{"text": "### A Pluto.jl notebook ###\n# v0.11.14\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 49e8e6f6-0483-11eb-0a74-d94aa536c9ab\nusing LinearAlgebra, Plots, Zygote, PlutoUI\n\n# ╔═╡ fccca5fc-0597-11eb-1033-a5cc3b71d854\nmd\"\"\"\n# Constrained convex optimization\n\n**Michiel Stock**\nSTMO\n\n## Equality constraints\n\nConsider the following optimization problem:\n\n$$\\min_{\\mathbf{x}} f(\\mathbf{x})$$\n$$\\text{subject to } g(\\mathbf{x})=0\\,.$$\n\nFor every point $\\mathbf{x}$ on the surface $g(\\mathbf{x})=0$, the gradient $\\nabla g(\\mathbf{x})$ is normal to this surface. This can be shown by considering a point $\\mathbf{x}+\\boldsymbol{\\epsilon}$, also on the surface. If we make a Taylor expansion around $\\mathbf{x}$, we have\n\n$$g(\\mathbf{x}+\\boldsymbol{\\epsilon})\\approx g(\\mathbf{x}) + \\boldsymbol{\\epsilon}^\\top\\nabla g(\\mathbf{x})\\,.$$\n\nGiven that both $\\mathbf{x}$ and $\\mathbf{x}+\\boldsymbol{\\epsilon}$ lie on the surface it follows that $g(\\mathbf{x}+\\boldsymbol{\\epsilon})= g(\\mathbf{x})$. In the limit that $||\\boldsymbol{\\epsilon}||\\rightarrow 0$ we have that $\\boldsymbol{\\epsilon}^\\top\\nabla g(\\mathbf{x})=0$. Because $\\boldsymbol{\\epsilon}$ is parallel to the surface $g(\\mathbf{x})$, it follows that $\\nabla g(\\mathbf{x})$ is normal to the surface.\n\nWe seek a point $\\mathbf{x}^\\star$ on the surface such that $f(\\mathbf{x})$ is minimized. For such a point, it should hold that the gradient w.r.t. $f$ should be parallel to $\\nabla g$. Otherwise, it would be possible to give a small 'nudge' to $\\mathbf{x}^\\star$ in the direction of $\\nabla f$ to decrease the function value, which would indicate that $\\mathbf{x}^\\star$ is not a minimizer. This figures below illustrate this point.\n\n$$\\nabla f(\\mathbf{x}^\\star) + \\nu \\nabla g (\\mathbf{x}^\\star)=0\\,,$$\nwith $\\nu\\neq 0$ called the *Lagrange multiplier*. The constrained minimization problem can also be represented by a *Lagrangian*:\n$$L(\\mathbf{x}, \\nu) \t\\equiv f(\\mathbf{x}) + \\nu g(\\mathbf{x})\\,.$$\nThe constrained stationary condition is obtained by setting $\\nabla_\\mathbf{x} L(\\mathbf{x}, \\nu) =0$, the condition $\\partial  L(\\mathbf{x}, \\nu)/\\partial \\nu=0$ leads to the constraint equation $g(\\mathbf{x})=0$.\n\n\n\"\"\"\n\n# ╔═╡ 5e4eabba-0483-11eb-09a4-31ae6c582d3e\nf((x1, x2)) = 2x1^2 +1.4x1*x2 + x2^2 - 0.3x1 + x1 \n\n# ╔═╡ 470048ec-0598-11eb-0d48-67357ed1f12c\nmd\"In addition to a $g(\\mathbf{x})$, we also implement a parametric version where $g(\\mathbf{x})=0$ for plotting purposes.\"\n\n# ╔═╡ 5503c842-0591-11eb-0104-359b9ebd5e98\nmd\"Show the countour of $f(\\mathbf{x})$:\"\n\n# ╔═╡ 47067fc8-058c-11eb-224c-6fe2e470107f\n@bind show_f_contour CheckBox()\n\n# ╔═╡ c369c65e-0598-11eb-0a90-dd4db070c99b\nshow_f_contour\n\n# ╔═╡ 60328136-0591-11eb-1929-b7515a8c03d9\nmd\"Show the countour of $g(\\mathbf{x})$:\"\n\n# ╔═╡ d10b14c2-058c-11eb-3a43-7bca5d042969\n@bind show_g_contour CheckBox()\n\n# ╔═╡ ba835a96-0598-11eb-1d54-9365e3ea337f\nshow_g_contour\n\n# ╔═╡ 681a031a-0591-11eb-2fec-8d94eca758f8\nmd\"Show the function $g(\\mathbf{x})=0$:\"\n\n# ╔═╡ 13467b42-058d-11eb-3023-b9d3f145335b\n@bind show_g0_constraint CheckBox()\n\n# ╔═╡ ca227ac2-0598-11eb-3a39-f1a90769ac52\nshow_g0_constraint\n\n# ╔═╡ d8276f26-0598-11eb-1626-95f87cf6de22\nmd\"Show the gradients:\"\n\n# ╔═╡ 60c41848-0592-11eb-39ef-7103ae834990\n@bind show_gradients CheckBox()\n\n# ╔═╡ d16723ca-0598-11eb-02f4-f1c5d45095a5\nshow_gradients\n\n# ╔═╡ 95dc760a-058e-11eb-2149-898b2776079f\n@bind t Slider(0:0.01:2π, default=4.3)\n\n# ╔═╡ 41d8c8d0-0591-11eb-2cd7-3b53f91ef589\nt\n\n# ╔═╡ aef30ee8-0597-11eb-2203-ed0f9b14f0e4\nt\n\n# ╔═╡ 00a009a2-0599-11eb-341f-3364198e1753\nmd\"We plot the objective value on the equality constraint.\"\n\n# ╔═╡ 13b4ad4a-0599-11eb-0043-6bfc0eb23389\nmd\"At the minimizer, the gradients are parallel.\"\n\n# ╔═╡ 7e77e628-0707-11eb-1b2f-27b5c5819260\n# compute angle between two vectors\nangle(u, v) = acos(dot(u, v) / (norm(u) * norm(v)))\n\n# ╔═╡ 358f21ca-0599-11eb-3bfb-0bb12a1465bb\nmd\"\"\"\n## Inequality constraints\n\nThe same argument can be made for inequality constraints, i.e. solving\n\n$$\\min_{\\mathbf{x}} f(\\mathbf{x})$$\n$$\\text{subject to } g(\\mathbf{x})\\leq0\\,.$$\n\nHere, two situations can arise:\n\n- **Inactive constraint**: the minimizer of $f$ lies in the region where $g(\\mathbf{x}) < 0$. This corresponds to a Lagrange multiplier $\\nu=0$. Note that the solution would be the same if the constraint was not present.\n- **Active constraint**: the minimizer of $f$ lies in the region where $g(\\mathbf{x}) > 0$. The solution of the constrained problem will lie on the bound where $g(\\mathbf{x})=0$, similar to the equality-constrained problem and corresponds to a Lagrange multiplier $\\nu>0$.\n\nFor both cases, the product $\\nu g(\\mathbf{x})=0$, the solution should thus satisfy the following conditions:\n$$g(\\mathbf{x}) \\leq 0$$\n$$\\nu \\geq 0$$\n$$\\nu g(\\mathbf{x})=0\\,.$$\nThese are called the *Karush-Kuhn-Tucker* conditions.\n\nIt is relatively straightforward to extend this framework towards multiple constraints (equality and inequality) by using several Lagrange multipliers.\n\"\"\"\n\n\n# ╔═╡ 2d7ae208-0599-11eb-1a91-277b764ad45e\nmd\"Change the location of the constraint\"\n\n# ╔═╡ c98b4f9a-0592-11eb-2034-5f05e792cbd2\n@bind R Slider(10:0.5:25, default=16)\n\n# ╔═╡ bd7b55ae-0599-11eb-1056-ed3682fe8160\ng((x1, x2)) = (x1-10)^2 + (x2-17)^2 - R^2\n\n# ╔═╡ c10838a2-0599-11eb-32e3-1579a926f9b7\ng0(t) = [R*cos(t) + 10, R*sin(t) + 17]\n\n# ╔═╡ d2c4ffe2-0485-11eb-0e20-dd52446fa3a6\nx = g0(t)\n\n# ╔═╡ 6e89822c-070b-11eb-06f3-8b8e20aaa57d\nf(x)\n\n# ╔═╡ e944567a-0596-11eb-2cf1-75f196bab4d1\nf'(x) / norm(f'(x))\n\n# ╔═╡ 02673cec-0597-11eb-2db4-e9f7d9047ac0\ng'(x) / norm(g'(x))\n\n# ╔═╡ c04a0ffe-0707-11eb-2a74-b3b258b4aec6\nangle(f'(x), g'(x))  # close to 0 or pi if stationary point\n\n# ╔═╡ f47ce686-0485-11eb-2a33-4bd0b150b18b\ng(x)\n\n# ╔═╡ b0cf9a40-058f-11eb-13dc-b7c35328ef2a\nbegin\n\tplot(t -> f(g0(t)), 0:0.01:2π, label=\"f(x) where g(x)=0\")\n\txlabel!(\"t\")\n\tylabel!(\"objective\")\n\tscatter!([t], [f(g0(t))], color=:purple, label=\"x\")\nend\n\n# ╔═╡ be35a06c-0596-11eb-2988-61a79c7e6a87\nR\n\n# ╔═╡ a08e7230-0591-11eb-3956-fb6c2d756494\nfconstr(x) = g(x) ≤ 0.0 ? f(x) : NaN\n\n# ╔═╡ 81629936-0593-11eb-3fca-afa68e2ace3d\n@bind t_approx Slider(0.1:0.05:10.0, default=1.0)\n\n# ╔═╡ a1402cbc-0593-11eb-33b4-09a0c654eefd\nt_approx\n\n# ╔═╡ cc4209ee-0593-11eb-3762-e76539e2a455\nÎ₋(u) = u < 0.0 ? -(1/t_approx)* log(-u) : Inf\n\n# ╔═╡ a398740e-0593-11eb-2f81-c92861e080b8\nbegin\n\tplot(-3:0.001:2, Î₋, label=\"logarithmic barier (t=$t_approx)\")\n\tplot!([-3, 0, 0], [0, 0, 5], ls=:dash, label=\"indicator function\")\n\tylims!(-2, 5)\n\txlabel!(\"u\")\nend\n\n# ╔═╡ dce25666-0594-11eb-24f9-85eba4949d1e\nfsoft(x) = g(x) ≤ 0.0 ? t_approx * f(x) + Î₋(g(x)) : NaN\n\n# ╔═╡ 701efa2a-0596-11eb-2592-39eced2fb875\n@bind show_soft_grads CheckBox()\n\n# ╔═╡ 7c5d381a-0596-11eb-1dfe-0b7074093cd6\nshow_soft_grads\n\n# ╔═╡ 7c934678-0599-11eb-1e6b-1f2c9003509a\nmd\"## Utilities\"\n\n# ╔═╡ 865bbb8e-0483-11eb-0622-b9a8a6ba5d4c\nx1min, x1max = -8.0, 15.0\n\n# ╔═╡ 9736f388-0483-11eb-069a-0d5ed87efb73\nx2min, x2max = -8.0, 12.0\n\n# ╔═╡ f39f0106-0483-11eb-3617-5fb04388489e\ngrads(f, x) = 0.1f'(x) |> df -> Tuple([e] for e in df)\n\n# ╔═╡ 828cbe72-0483-11eb-33b2-7f4f37db889f\nbegin\n\tplot(colorbar=false)\n\tshow_f_contour && contourf!(x1min:0.1:x1max, x2min:0.1:x2max, (x1, x2) -> f((x1, x2)), label=\"f(x)\", colorbar=true, color=:Blues, aspect=:equal)\n\tshow_g_contour && contour!(x1min:0.1:x1max, x2min:0.1:x2max, (x1, x2) -> g((x1, x2)), color=:Reds)\n\tshow_g0_constraint && plot!([g0(t)[1] for t in 0:0.01:2π], [g0(t)[2] for t in 0:0.01:2π], lw=2, color=:red, label=\"g(x)=0\")\n\tshow_g0_constraint && scatter!([x[1]], [x[2]], label=\"x\", color=:purple)\n\tscatter!([0], [0], label=\"x* (no constraint)\", color=:green)\n\tshow_gradients && quiver!([x[1]], [x[2]], quiver=grads(f, x), color=:blue)\n\tshow_gradients && quiver!([x[1]], [x[2]], quiver=grads(g, x), color=:orange)\n\txlims!(x1min, x1max)\n\tylims!(x2min, x2max)\n\txlabel!(\"x1\")\n\tylabel!(\"x2\")\nend\n\n# ╔═╡ c2640938-0591-11eb-058c-5949d1e316d3\nbegin\n\tcontourf(x1min:0.01:x1max, x2min:0.01:x2max, (x1, x2) -> fconstr((x1, x2)), \t\t\tcolor=:Blues)\n\tshow_g_contour && contour!(x1min:0.1:x1max, x2min:0.1:x2max, (x1, x2) -> g((x1, x2)), color=:Reds)\n\tcontour!(x1min:0.1:x1max, x2min:0.1:x2max, (x1, x2) -> f((x1, x2)), \t\t\tcolor=:Blues)\n\tscatter!([x[1]], [x[2]], label=\"x\", color=:purple)\n\tscatter!([0], [0], label=\"x* (no constraint)\", color=:green)\n\tshow_g0_constraint && plot!([g0(t)[1] for t in 0:0.01:2π], [g0(t)[2] for t in 0:0.01:2π], lw=2, color=:red, label=\"g(x)=0\")\n\tshow_gradients && quiver!([x[1]], [x[2]], quiver=grads(f, x), color=:blue)\n\tshow_gradients && quiver!([x[1]], [x[2]], quiver=grads(g, x), color=:orange)\n\txlims!(x1min, x1max)\n\tylims!(x2min, x2max)\nend\n\n# ╔═╡ 52bacf14-0595-11eb-33c9-dd5c40125360\n∇fsoft(x) = g(x) ≤ 0.0 ? fsoft'(x) : [0.0, 0.0]\n\n# ╔═╡ 0b93638a-0595-11eb-3096-af3cc7202aa5\nbegin\n\tcontourf(x1min:0.01:x1max, x2min:0.01:x2max, (x1, x2) -> fconstr((x1, x2)), \t\t\tcolor=:Blues)\n\t\n\tcontour!(x1min:0.1:x1max, x2min:0.1:x2max, (x1, x2) -> f((x1, x2)), \t\t\tcolor=:Blues)\n\tshow_g_contour && contour!(x1min:0.1:x1max, x2min:0.1:x2max, (x1, x2) -> fsoft((x1, x2)), color=:Reds)\n\tscatter!([x[1]], [x[2]], label=\"x\", color=:purple)\n\tscatter!([0], [0], label=\"x* (no constraint)\", color=:green)\n\tshow_g0_constraint && plot!([g0(t)[1] for t in 0:0.01:2π], [g0(t)[2] for t in 0:0.01:2π], lw=2, color=:red, label=\"g(x)=0\")\n\tshow_soft_grads && quiver!(x1min:2:x1max, (x2min:2:x2max)', quiver=(x1, x2)->-0.05.*∇fsoft((x1, x2)), color=:pink)\n\txlims!(x1min, x1max)\n\tylims!(x2min, x2max)\nend\n\n# ╔═╡ 0a5783e2-0596-11eb-1e38-a5da40325159\n\n\n# ╔═╡ Cell order:\n# ╠═49e8e6f6-0483-11eb-0a74-d94aa536c9ab\n# ╟─fccca5fc-0597-11eb-1033-a5cc3b71d854\n# ╠═5e4eabba-0483-11eb-09a4-31ae6c582d3e\n# ╠═bd7b55ae-0599-11eb-1056-ed3682fe8160\n# ╟─470048ec-0598-11eb-0d48-67357ed1f12c\n# ╠═c10838a2-0599-11eb-32e3-1579a926f9b7\n# ╠═41d8c8d0-0591-11eb-2cd7-3b53f91ef589\n# ╠═d2c4ffe2-0485-11eb-0e20-dd52446fa3a6\n# ╠═6e89822c-070b-11eb-06f3-8b8e20aaa57d\n# ╠═f47ce686-0485-11eb-2a33-4bd0b150b18b\n# ╟─5503c842-0591-11eb-0104-359b9ebd5e98\n# ╟─47067fc8-058c-11eb-224c-6fe2e470107f\n# ╟─c369c65e-0598-11eb-0a90-dd4db070c99b\n# ╟─60328136-0591-11eb-1929-b7515a8c03d9\n# ╟─d10b14c2-058c-11eb-3a43-7bca5d042969\n# ╟─ba835a96-0598-11eb-1d54-9365e3ea337f\n# ╟─681a031a-0591-11eb-2fec-8d94eca758f8\n# ╟─13467b42-058d-11eb-3023-b9d3f145335b\n# ╟─ca227ac2-0598-11eb-3a39-f1a90769ac52\n# ╟─d8276f26-0598-11eb-1626-95f87cf6de22\n# ╟─60c41848-0592-11eb-39ef-7103ae834990\n# ╟─d16723ca-0598-11eb-02f4-f1c5d45095a5\n# ╟─828cbe72-0483-11eb-33b2-7f4f37db889f\n# ╠═95dc760a-058e-11eb-2149-898b2776079f\n# ╠═aef30ee8-0597-11eb-2203-ed0f9b14f0e4\n# ╟─00a009a2-0599-11eb-341f-3364198e1753\n# ╟─b0cf9a40-058f-11eb-13dc-b7c35328ef2a\n# ╟─13b4ad4a-0599-11eb-0043-6bfc0eb23389\n# ╠═e944567a-0596-11eb-2cf1-75f196bab4d1\n# ╠═02673cec-0597-11eb-2db4-e9f7d9047ac0\n# ╠═7e77e628-0707-11eb-1b2f-27b5c5819260\n# ╠═c04a0ffe-0707-11eb-2a74-b3b258b4aec6\n# ╟─358f21ca-0599-11eb-3bfb-0bb12a1465bb\n# ╟─2d7ae208-0599-11eb-1a91-277b764ad45e\n# ╠═c98b4f9a-0592-11eb-2034-5f05e792cbd2\n# ╠═be35a06c-0596-11eb-2988-61a79c7e6a87\n# ╠═a08e7230-0591-11eb-3956-fb6c2d756494\n# ╟─c2640938-0591-11eb-058c-5949d1e316d3\n# ╟─81629936-0593-11eb-3fca-afa68e2ace3d\n# ╠═a1402cbc-0593-11eb-33b4-09a0c654eefd\n# ╠═cc4209ee-0593-11eb-3762-e76539e2a455\n# ╟─a398740e-0593-11eb-2f81-c92861e080b8\n# ╠═dce25666-0594-11eb-24f9-85eba4949d1e\n# ╟─701efa2a-0596-11eb-2592-39eced2fb875\n# ╠═7c5d381a-0596-11eb-1dfe-0b7074093cd6\n# ╟─0b93638a-0595-11eb-3096-af3cc7202aa5\n# ╟─7c934678-0599-11eb-1e6b-1f2c9003509a\n# ╠═865bbb8e-0483-11eb-0622-b9a8a6ba5d4c\n# ╠═9736f388-0483-11eb-069a-0d5ed87efb73\n# ╠═f39f0106-0483-11eb-3617-5fb04388489e\n# ╠═52bacf14-0595-11eb-33c9-dd5c40125360\n# ╠═0a5783e2-0596-11eb-1e38-a5da40325159\n", "meta": {"hexsha": "3aee010afc6ca7bd2329bdab3884cd40c078661c", "size": 11987, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapters/05.Constrained/lagrange.jl", "max_stars_repo_name": "f6v/STMO", "max_stars_repo_head_hexsha": "cbbb8083caeaef361fbcaa7e60c687ff6f0db17e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2020-01-28T15:43:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T07:35:52.000Z", "max_issues_repo_path": "chapters/05.Constrained/lagrange.jl", "max_issues_repo_name": "f6v/STMO", "max_issues_repo_head_hexsha": "cbbb8083caeaef361fbcaa7e60c687ff6f0db17e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-02-04T16:30:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-30T11:24:57.000Z", "max_forks_repo_path": "chapters/05.Constrained/lagrange.jl", "max_forks_repo_name": "f6v/STMO", "max_forks_repo_head_hexsha": "cbbb8083caeaef361fbcaa7e60c687ff6f0db17e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2020-02-09T15:13:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T18:32:40.000Z", "avg_line_length": 37.5768025078, "max_line_length": 433, "alphanum_fraction": 0.6939184116, "num_tokens": 5743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8856314738181875, "lm_q1q2_score": 0.7999857795745864}}
{"text": "using OrdinaryDiffEq, DifferentialEquations\n\ntspan = (0.0f0, 50.0f0)\n\n\"\"\"\nSimple SIR disease model from:\n    https://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology\n\nNote: this does not include birth and death rates\n\"\"\"\nfunction sir_system(du, u, p, t;\n                     U_func_time=U_func_time_trivial,\n                     U_func_space=U_func_space_trivial)\n    Ft = U_func_time(t)\n    Fs = U_func_space(u)\n    beta, gamma = p\n    S, I, R = u\n\n    N = sum([S,I,R])\n    tmp = beta*I*S/N\n    du[1] = -tmp\n    du[2] = tmp - gamma*I\n    du[3] = gamma*I\n\n    # This forcing function must keep the overall population constant\n    du[1] += -Ft[1]\n    du[3] += Ft[1]\n    # du .+= Ft .+ Fs\nend\n\n\n# Generate data, with a time component\np = [0.5, 0.2]\nu0 = [999.0, 1.0, 0.0]\nts = range(tspan[1], tspan[2], length=5001)\n\nfunction solve_sir_system(;U_func_time=U_func_time_trivial,\n                              U_func_space=U_func_space_trivial)\n    prob = ODEProblem((du, u, p, t)->sir_system(du, u, p, t,\n                                U_func_time=U_func_time,\n                                U_func_space=U_func_space),\n                    u0, tspan, p)\n    sol = solve(prob, Tsit5(), saveat=ts);#, adaptive=true,\n        #dt=1e-5);#, abstol=1e-12, reltol=1e-5);\n    # sol = solve(prob, AB4(), saveat=ts, dt=1e-5);\n    return sol\nend\n\n#####\n##### Turing function for Bayesian parameter estimation\n#####\n# Unforced version for use with Turing.jl\nfunction sir_system(u, p, t)\n    u = convert.(eltype(p),u)\n    beta, gamma = p\n    S, I, R = u\n\n    N = sum([S,I,R])\n    tmp = beta*I*S/N\n    du = [-tmp; tmp - gamma*I; gamma*I]\n    return du\nend\n\n#####\n##### True model in SINDy syntax\n#####\na, b = p\na = a / sum(u0)\n#      S  I  R  c SS SI SR II IR RR\n A = [[0  0  0  0  0 -a  0  0  0  0];\n      [0 -b  0  0  0  a  0  0  0  0];\n      [0  b  0  0  0  0  0  0  0  0]]\nn = size(A, 1)\nsindy_library = Dict(\n    \"cross_terms\"=>2,\n    \"constant\"=>nothing\n);\ncore_dyn_true = sindyModel(ts, A,\n                            convert_string2function(sindy_library),\n                            [\"S\", \"I\", \"R\"])\n\n# Actually export\nexport ts, solve_sir_system, sir_system, core_dyn_true\n    # ,lorenz_grad_residual\n", "meta": {"hexsha": "650267851dd4d3ed39f5983bca7dd9d5f02cc5ee", "size": 2205, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example_sir.jl", "max_stars_repo_name": "Charles-Fieseler/Learn_Control_Signals", "max_stars_repo_head_hexsha": "987a3775f4f75080c23d631832dd6963e7be078a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-02T15:05:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-02T15:05:34.000Z", "max_issues_repo_path": "examples/example_sir.jl", "max_issues_repo_name": "Charles-Fieseler/Learn_Control_Signals", "max_issues_repo_head_hexsha": "987a3775f4f75080c23d631832dd6963e7be078a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/example_sir.jl", "max_forks_repo_name": "Charles-Fieseler/Learn_Control_Signals", "max_forks_repo_head_hexsha": "987a3775f4f75080c23d631832dd6963e7be078a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9411764706, "max_line_length": 70, "alphanum_fraction": 0.556462585, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.8791467722591728, "lm_q1q2_score": 0.7999418095621859}}
{"text": "using Statistics\nusing StatsBase\n\n# Absolute energy of the time series, the sum over the squared values\nabs_energy(x::AbstractArray{T} where T<:Real) = mapreduce(x -> x * x, +, x) #using reduce(map()) is faster but with more mem allocation\n\n# Highest absolute value of the time series x\nabsolute_maximum(x::AbstractArray{T} where T<:Real) = maximum(abs, x)\n\n# Sum over the abs value of consecutive changes in the series x\nfunction absolute_sum_of_changes(x::AbstractArray{T} where T<:Real)\n    diff = Real[]\n\n    for i in 1:length(x)-1\n        push!(diff,x[i+1] - x[i])\n    end\n\n    return sum(map(abs,diff))\nend\n\n\"\"\"\nDescriptive statistics on the autocorrelation of the time series x.\nCalculates the value of an aggregation function fₐ over\n    the autocorrelation for different lags.\nInput:  x -> time series to calculate the feature of\n        param -> dictionaries {\"f_agg\":x, \"maxlag\":n},\n            with x, a string, the name of the aggregation funcion(e.g. mean, variance, ...),\n            and n, an integer, the maximal number of lags to consider\n\"\"\"\n#TODO functions that calls function must have parameter of type \"Function\" not \"String\"\nfunction agg_autocorrelation(x::AbstractArray{T} where T<:Real, f::Function, maxlag::Int)\n\n    R::AbstractArray = zeros(maxlag)\n    μ = mean(x)\n    σ²= var(x)\n\n    for i in 1:maxlag\n        aux = 0.\n\n        for t in 1:(length(x) - i)\n            aux += (x[t] - μ) * (x[t+i] - μ)\n        end\n\n        R[i] = ( 1 / ( (length(x) - i) * σ² ) ) * aux\n    end\n\n    return f(R)\n\nend\n\n\"\"\"\nImplements a vectorized approximate entropy algorithm.\nInput: x-> time series to calculate the feature of\n       m-> length of compared run of data (int)\n       r-> filtering level, must be positive (float)\n\"\"\"\n\n\"\"\"\nfunction approximate_entropy(x::AbstractArray{T} where T<:Real, m::Int, r::Real)\n    dist(x_i, x_j) =\n\n    n = length(x)\n\n    x_re = Array([[ x[j] for j in i:(i+m-1) ] for i in 1:(n-m+1)])\n\n    # GO AHEAD\nend\n\"\"\"\n\n# augmented_dickey_fuller TODO\n\n# Calculates the autocorrelation of the specified lag.\nfunction autocorrelation(x::AbstractArray{T} where T<:Real, lag::Int)\n    n = length(x)\n    μ = mean(x)\n    σ²= var(x)\n\n    sum = 0.\n    for t in 1:(n-lag)\n        sum += (x[t] - μ) * (x[t+lag] - μ)\n    end\n\n    return (1 / ((n-lag) * σ²)) * sum\nend\n\n\"\"\"\nReturns the correlation from first digit distribution when compared\n to the Newcomb-Benford's Law fistribution\n\"\"\"\nfunction benford_correlation(x::AbstractArray{T} where T<:Real)\n    # Take first digit from data\n    x = Array([last(digits(trunc(Int, abs(x[i])))) for i in 1:length(x)])\n\n    # Benford distribution\n    P = Array([log10(1 + 1/n) for n in 1:9])\n\n    # Data distribution\n    D = Array([count(i -> i==n, x)/length(x) for n in 1:9])\n\n    # Return the correlation between benford distribution and data distribution\n    return cor(P,D)\nend\n\n\"\"\"\nFirst bins the values of x into max_bins equidistant bins.\nThen calculates the value of binned entropy\n\"\"\"\nfunction binned_entropy(x::AbstractArray{T} where T<:Real, max_bins::Int)\n    # Create equidistant max_bins\n    edges = LinRange(minimum(x), maximum(x), max_bins)\n    # Fit function requires column vector\n    edges = collect(permutedims(edges))\n\n    # Create histogram with the calculated bins\n    h = fit(Histogram, vec(x), vec(edges))\n    hist = h.weights\n\n    # Vector pₖ with percentages of samples in bin k\n    p = hist / length(x)\n\n    # Where the percentage is 0, set to 1 to avoid Nan values?\n    p[p.==0] .= 1\n\n    # Return Entropy = - ∑ᵐᵢ₌₁ pᵢ * log(pᵢ)\n    return - reduce(+, map(x->x*log(x), p))\nend\n\n# Uses c3 statistics to measure non linearity in the time series\nfunction c3(x::AbstractArray{T} where T<:Real, lag::Int)\n    n = length(x)\n    if 2*lag ≥ n\n        return 0\n    end\n\n    sum=0.\n    for i in 1:(n - 2*lag)\n        sum += x[i + 2*lag] * x[i + lag] * x[i]\n    end\n\n    return (1 / (n - 2*lag)) * sum\nend\n\n\"\"\"\nFirst takes a corridor given by the quatiles ql and qh of\nthe distribution of x. Then calculates the average, absolute\nvalue of consecutive changes of the series x inside this corridor.\n\"\"\"\nfunction change_quantiles(x::AbstractArray{T} where T<:Real, ql::Float64, qh::Float64, f_agg::Function)\n        # Compute the quantiles\n        q = quantile(vec(x), [ql, qh], sorted=true)\n\n        # Corridor between the 2 quantiles\n        corr = Real[]\n        for i in 1:length(x)\n            if x[i] >= q[1] && x[i] <= q[2]\n                push!(corr, x[i])\n            end\n        end\n\n        # Return the aggregation function of corridor\n        return f_agg(corr)\nend\n\n#This function calculator is an estimate for a time series complexity\nfunction cid_ce(x::AbstractArray{T} where T<:Real, normalize::Bool)\n    n = length(x)\n\n    if normalize\n        s = std(x)\n        if s != 0\n            x = (x .- mean(x)) / s\n        else\n            return 0\n        end\n    end\n\n    sum = 0.\n    for i in 2:n\n        sum += (x[i] - x[i-1])^2\n    end\n\n    return sqrt(sum)\nend\n\n# Returns the percentage of values in x that are higher than t\ncount_above(x::AbstractArray{T} where T<:Real, t::Float64) = count(i -> i > t, x) / length(x)\n\n# Returns the number of values in x that are higher than the mean of x\ncount_above_mean(x::AbstractArray{T} where T<:Real) = count(i -> i > mean(x), x)\n\n# Returns the percentage of values in x that are lower than t\ncount_below(x::AbstractArray{T} where T<:Real, t::Float64) = count(i -> i < t, x) / length(x)\n\n# Returns the number of values in x that are lower than the mean of x\ncount_below_mean(x::AbstractArray{T} where T<:Real) = count(i -> i < mean(x), x)\n\n\"\"\"\nReturn the first location of the maximum value of x.\nThe position is calculated relatively to the length of x\n\"\"\"\nfirst_location_of_maximum(x::AbstractArray{T} where T<:Real) = findmax(x)[2] / length(x)\n\n\"\"\"\nReturn the first location of the minimum value of x.\nThe position is calculated relatively to the length of x\n\"\"\"\nfirst_location_of_minimum(x::AbstractArray{T} where T<:Real) = findmin(x)[2] / length(x)\n\n# Checks if any value in x occurs more than once\nhas_duplicate(x::AbstractArray{T} where T<:Real) = return length(x) != length(unique(x))\n\n# Checks if the maximum value of x is observed more than once\nhas_duplicate_max(x::AbstractArray{T} where T<:Real) = if count(i -> i == maximum(x), x) > 1 return true else return false end\n\n# Checks if the minimum value of x is observed more than once\nhas_duplicate_min(x::AbstractArray{T} where T<:Real) = if count(i -> i == minimum(x), x) > 1 return true else return false end\n\n\"\"\"\nDoes time series have large standard deviation?\nReturn boolean denoting if the standard deviation of x\nis higher than 'r' times the range.\n\"\"\"\nlarge_standard_deviation(x::AbstractArray{T} where T<:Real, r::Float64) = return std(x) > r * (maximum(x) - minimum(x))\n\n# Returns the relative last location of tha maximum value of x\nlast_location_of_maximum(x::AbstractArray{T} where T<:Real) = findmax(reverse(x))[2] / length(x)\n\n# Returns the relative last location of tha minimum value of x\nlast_location_of_minimum(x::AbstractArray{T} where T<:Real) = findmin(reverse(x))[2] / length(x)\n\n# Returns the length of the longest consecutive subsequence in x that is bigger than the mean of x\nfunction longest_strike_above_mean(x::AbstractArray{T} where T<:Real)\n    aux = x.>mean(x)\n    max_strike = 0\n    i=1\n\n    while i <= length(aux)\n        if aux[i] == 1\n            c = 1\n            i+=1\n            while i <= length(aux)\n                if aux[i] == 1\n                    c+=1\n                else\n                    break\n                end\n                i+=1\n            end\n            if c > max_strike\n                max_strike = c\n            end\n        else\n            i+=1\n        end\n    end\n\n    return max_strike\nend\n\n# Returns the length of the longest consecutive subsequence in x that is lower than the mean of x\nfunction longest_strike_below_mean(x::AbstractArray{T} where T<:Real)\n    aux = x.<mean(x)\n    max_strike = 0\n    i=1\n\n    while i <= length(aux)\n        if aux[i] == 1\n            c = 1\n            i+=1\n            while i <= length(aux)\n                if aux[i] == 1\n                    c+=1\n                else\n                    break\n                end\n                i+=1\n            end\n            if c > max_strike\n                max_strike = c\n            end\n        else\n            i+=1\n        end\n    end\n\n    return max_strike\nend\n\n# Average over first differences\nfunction mean_abs_change(x::AbstractArray{T} where T<:Real)\n    diff = Real[]\n\n    for i in 1:length(x)-1\n        push!(diff,x[i+1] - x[i])\n    end\n\n    return mean(map(abs, diff))\nend\n\n# Average over time sereis differences\nmean_change(x::AbstractArray{T} where T<:Real) = (x[end] - x[1]) / (length(x) - 1)\n\n# Calculates the arithmetic mean of the n absolute maximum values of the time series\nfunction mean_n_absolute_max(x::AbstractArray{T} where T<:Real, n::Int)\n    aux = sort(map(abs, x))\n    return mean(aux[length(aux) - (n - 1) : end])\nend\n\n# Returns the mean value of a central approximation of the secondo derivative\nmean_second_derivative_central(x::AbstractArray{T} where T<:Real) = (x[end] - x[end - 1] - x[2] - x[1]) / (2 * (length(x) - 2))\n\n# Calculates the number of crossing of x on m.\nfunction number_crossing_m(x::AbstractArray{T} where T<:Real, m::Float64)\n    positive = x .> m\n    diff = Int[]\n\n    for i in 1:length(x) - 1\n        push!(diff, positive[i+1] - positive[i])\n    end\n\n    return count(i -> i != 0, diff)\nend\n\n# TODO Gabriele\n# # Returns the percentage of non-unique data points.\n# function percentage_of_reoccurring_datapoints_to_all_datapoints(x::AbstractArray{T} where T<:Real)\n#     value_counts = countmap(x)\n#     reoccurring_values = 0\n#\n#     for item in value_counts\n#         if item[2] > 1\n#             reoccurring_values += 1\n#         end\n#     end\n#\n#     return reoccurring_values / length(x)\n# end\n\n# TODO Gabriele\n# # Returns the percentage of values that are present in the time series more than once\n# function percentage_of_reoccurring_values_to_all_values(x::AbstractArray{T} where T<:Real)\n#     value_counts = countmap(x)\n#     reoccurring_values = 0\n#     unique_values = 0\n#\n#     for item in value_counts\n#         if item[2] > 1\n#             reoccurring_values += 1\n#         else\n#             unique_values += 1\n#         end\n#     end\n#\n#     return reoccurring_values / unique_values\n# end\n\n# Count observed values within the interval [min, max)\nrange_count(x::AbstractArray{T} where T<:Real, min::Float64, max::Float64) = count(i -> i>=min && i<max, x)\n\n# Ratio of values that are mroe than r * std(x) away from the mean of x\nfunction ratio_beyond_r_sigma(x::AbstractArray{T} where T<:Real, r::Float64)\n    μ = mean(x)\n    r_sigma = r * std(x)\n\n    aux = map(abs, map(x -> x - μ, x))\n\n    aux = Array([aux[i] > r_sigma ? aux[i] : 0 for i in 1:length(aux)])\n\n    return sum(aux) / length(x)\nend\n\n# TODO Gabriele\n# \"\"\"\n# Returns a factow which is 1 if all values in the time series occur only once,\n# and below one if this is not the case\n# \"\"\"\n# function ratio_value_number_to_time_series_length(x::AbstractArray{T} where T<:Real)\n#     value_counts = countmap(x)\n#     unique = Real[]\n#\n#     for item in value_counts\n#         if item[2] == 1\n#             push!(unique, item[2])\n#         end\n#     end\n#\n#     return length(unique) / length(x)\n# end\n\n# Returns the root mean square of the time series\nroot_mean_square(x::AbstractArray{T} where T<:Real) = sqrt(mean(map(x -> x^2, x)))\n\n# Calculate and return sample entropy of x\nfunction sample_entropy(x::AbstractArray{T} where T<:Real)\n    m = 2\n    tolerance = 0.2 * std(x)\n\n    xmi = Array([x[i : i+m-1] for i in 1:length(x)-m])\n    xmj = Array([x[i : i+m-1] for i in 1:length(x)-m+1])\n\n    xmi = maximum(collect(hcat(xmi...)'), dims=2)\n    xmj = maximum(collect(hcat(xmj...)'), dims=2)\n\n    B = sum( Array([sum(x -> x <= tolerance, map(abs, xmi_i .- xmj)) - 1 for xmi_i in xmi]))\n\n    m += 1\n    xm = Array([x[i:i+m-1] for i in 1:length(x)-m+1])\n    xm = maximum(collect(hcat(xm...)'), dims=2)\n\n    A = sum( Array([sum(x -> x <= tolerance, map(abs, xm_i .- xm)) - 1 for xm_i in xm]))\n\n    return -log(A/B)\nend\n\n# # Returns the sum of all data points, that are present in the time series more than once\n# function sum_of_reoccurring_data_points(x::AbstractArray{T} where T<:Real)\n#     value_counts = countmap(x)\n#     reoc = Real[]\n#\n#     for item in value_counts\n#         if item[2] > 1\n#             for i in 1:item[2]\n#                 push!(reoc, item[1])\n#             end\n#         end\n#     end\n#\n#     return sum(reoc)\n# end\n\nfunction window_slice(x::AbstractArray{T} where T<:Real;\n        from::Union{Missing,Int}=missing,\n        to::Union{Missing,Int}=missing)\n        ismissing(from) && ismissing(to) && return x\n        ismissing(to) && return x[from:end]\n        ismissing(from) && return x[1:to]\n        return x[from:to]\nend\n\nfunction paa(x::AbstractArray{T} where T <: Real;\n        n_chunks::Union{Missing,Int}=missing,\n        f::Function=mean,\n        kwargs...)\n    if ismissing(n_chunks) return x\n    else\n        N = length(x)\n        @assert 0 ≤ n_chunks && n_chunks ≤ N \"The number of chunks must be in [0,$(N)]\"\n\n        y = Array{Float64}(undef, n_chunks) # TODO Float64?\n        for i in 1:n_chunks\n            l = Int(ceil((N*(i-1)/n_chunks) + 1))\n            h = Int(ceil(N*i/n_chunks))\n            y[i] = f(x[l:h]; kwargs...)\n        end\n        return y\n    end\nend\n", "meta": {"hexsha": "c3eb9e283ac23119a0611939ed81149e4f6c6808", "size": 13474, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "gspina140/SymbolicML.jl", "max_stars_repo_head_hexsha": "a89d19cbfeeb32ad6ead9944f7d87e86788c6a90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-30T08:44:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T06:23:08.000Z", "max_issues_repo_path": "src/functions.jl", "max_issues_repo_name": "gspina140/SymbolicML.jl", "max_issues_repo_head_hexsha": "a89d19cbfeeb32ad6ead9944f7d87e86788c6a90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-05-18T01:19:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-24T15:46:16.000Z", "max_forks_repo_path": "src/functions.jl", "max_forks_repo_name": "gspina140/SymbolicML.jl", "max_forks_repo_head_hexsha": "a89d19cbfeeb32ad6ead9944f7d87e86788c6a90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-26T14:17:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-26T14:17:39.000Z", "avg_line_length": 29.4192139738, "max_line_length": 135, "alphanum_fraction": 0.6180050468, "num_tokens": 3869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.8791467754256017, "lm_q1q2_score": 0.799941803852029}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.18\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\tL, K, n  = 500, [450, 400, 250, 100, 50], 30\n\thyperDists = [Hypergeometric(k,L-k,n) for k in K]\n\txGrid = 0:1:n\n\tpmfs = [ pdf.(dist, xGrid) for dist in hyperDists ]\n\tlabels = \"Successes = \" .* string.(K)\nend\n\n# ╔═╡ bfe8d6f0-2163-11eb-22e7-9b978bc1d407\nbegin\n\tbar( xGrid, pmfs, \n\t\talpha=0.8, c=[:orange :purple :green :red :blue ],\n\t\tlabel=hcat(labels...), ylims=(0,0.25),\n\t\txlabel=\"x\", ylabel=\"Probability\", legend=:top)\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.18\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═bfe8d6f0-2163-11eb-22e7-9b978bc1d407\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "8b5c3f632de6b78ee3f0b1fbf8bf287393a37a49", "size": 1199, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.18.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.18.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.18.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.5106382979, "max_line_length": 58, "alphanum_fraction": 0.7047539616, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8791467722591728, "lm_q1q2_score": 0.7999418031187013}}
{"text": "##\n##  p o l y n o m . j l  Polynomials\n##\n\n\nfunction pval(p::Vector, x::Number)\n    local n = length(p)\n    if n == 0\n        return NaN\n    elseif n == 1\n        return p[1]\n    else\n        y = p[1]\n        for i in 2:n\n            y = y * x + p[i]\n        end\n    end\n    return y\nend\n\n\nfunction horner(p::Vector, x::Number)\n    local n = length(p)\n    if n == 0\n        return NaN, NaN\n    elseif n == 1\n        return p[1], 0\n    else\n        y = p[1]; dy = 0\n        for i in 2:n\n            dy = dy * x + y\n            y  =  y * x + p[i]\n        end\n    end\n    return y, dy\nend\n\n\nfunction pzero{T<:Real}(p::Vector{T}, x0::T)\n    local x = x0, tol = 2*eps(x)\n    px, dpx = horner(p, x)\n    df = -px/dpx\n    niter = 1\n    while abs(df) >= tol && niter <= 100\n        x += df\n        px, dpx = horner(p, x)\n        df = -px/dpx\n        niter += 1\n    end\n    if niter > 100\n        warn(\"Number of iterations exceeded.\")\n        x = NaN\n    end\n    return x + df\nend\n\n\nfunction pfit()\n    error(\"Polynomial fit not yet implemented.\")\nend\n", "meta": {"hexsha": "ef247e4af931ef4e2b88015e46ef881d8f146bec", "size": 1044, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polynom.jl", "max_stars_repo_name": "hwborchers/NumericalMath.jl", "max_stars_repo_head_hexsha": "5afaa8d71e496dd71a2dbd642a688999b5f9963d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-03-11T19:26:16.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-12T21:39:58.000Z", "max_issues_repo_path": "src/polynom.jl", "max_issues_repo_name": "hwborchers/NumericalMath.jl", "max_issues_repo_head_hexsha": "5afaa8d71e496dd71a2dbd642a688999b5f9963d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-02-05T14:03:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-26T03:45:52.000Z", "max_forks_repo_path": "src/polynom.jl", "max_forks_repo_name": "hwborchers/NumericalMath.jl", "max_forks_repo_head_hexsha": "5afaa8d71e496dd71a2dbd642a688999b5f9963d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2015-01-25T21:38:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T04:30:29.000Z", "avg_line_length": 17.1147540984, "max_line_length": 48, "alphanum_fraction": 0.4578544061, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920262, "lm_q2_score": 0.8479677622198947, "lm_q1q2_score": 0.7999283319071624}}
{"text": "\"\"\"\n    log1mexp(x)\n\nCompute `log(1 - exp(x))` accurately. See\n\"**Accurately Computing log(1 - exp(.)) – Assessed by Rmpfr**\" by Martin Mächler\n(2012) for details:\nhttps://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf\n\"\"\"\nfunction log1mexp(x::Real)\n  if x > -log(2)\n    log(-expm1(x))\n  else\n    log1p(-exp(x))\n  end\nend\n\n\"\"\"\n    logexpm1(x)\n\nCompute `log(exp(x) - 1)` accurately. Thresholds were obtained similarly to\n\"**Accurately Computing log(1 - exp(.)) – Assessed by Rmpfr**\" by Martin Mächler\n(2012):\nhttps://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf\n\"\"\"\nfunction logexpm1(x::Real)\n  if x >= 37\n    x\n  elseif x >= 19\n    x - exp(-x)\n  else\n    log(expm1(x))\n  end\nend\n\n\"\"\"\n    log1pexp(x)\n\nCompute `log(1 + exp(x))` accurately. See\n\"**Accurately Computing log(1 - exp(.)) – Assessed by Rmpfr**\" by Martin Mächler\n(2012) for details:\nhttps://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf\n\"\"\"\nfunction log1pexp(x::Real)\n  if x <= -37\n    exp(x)\n  elseif x <= 18\n    log1p(exp(x))\n  elseif x <= 33.3\n    x + exp(-x)\n  else\n    x\n  end\nend\n", "meta": {"hexsha": "5899c63cc13db4d842f11249a92097a1adddd21c", "size": 1108, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/common/functions.jl", "max_stars_repo_name": "mauricelanghinrichs/SimpleBirthDeathProcess.jl", "max_stars_repo_head_hexsha": "7756b2489099a329466a81310eb8e173717e2c0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common/functions.jl", "max_issues_repo_name": "mauricelanghinrichs/SimpleBirthDeathProcess.jl", "max_issues_repo_head_hexsha": "7756b2489099a329466a81310eb8e173717e2c0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/functions.jl", "max_forks_repo_name": "mauricelanghinrichs/SimpleBirthDeathProcess.jl", "max_forks_repo_head_hexsha": "7756b2489099a329466a81310eb8e173717e2c0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-11T15:30:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T15:30:13.000Z", "avg_line_length": 20.5185185185, "max_line_length": 80, "alphanum_fraction": 0.6416967509, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211323, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.799928319256037}}
{"text": "using Random\n\n#Generate a matrix of given rank and ratio kappa between\n#largest and smallest nonzero singular values\nfunction generate_matrix(\n    m :: Int,       #Number of rows\n    n :: Int,       #Number of columns\n    r :: Int,       #Rank\n    κ :: Float64    #Condition number\n)\n    #Compute Rotations\n    u, _ = qr(randn(m, m))\n    vt, _ = qr(randn(n, n))\n\n    #Compute singular values\n    sig = sort(rand(r), rev=true) |> λ -> λ./maximum(λ)\n    a = (1 - 1/κ)/(1 - minimum(sig))\n    b = 1 - a\n    σ =  a.*sig .+ b\n    (min(m, n) > r) && append!(σ, zeros(min(m, n) - r))\n\n    #Return Matrix\n    return u*diagm(m, n, 0 => σ)*vt\nend\n\n# Generate a set of isotropic vector\nfunction isotropic_vector(n::Int)\n    return randn(n)\nend\n\nfunction isotropic_vector!(x::AbstractVector)\n    randn!(x)\n    return nothing\nend\n\nfunction randomized_trace(A::AbstractMatrix, nsamples::Int)\n    n = size(A, 1)\n    w = zeros(n)\n    x = zeros(n)\n    estimator = 0.0\n    # TODO: use compensated summation technique for large nsamples\n    factor = 1.0/nsamples\n\n    for i=1:nsamples\n        isotropic_vector!(w)\n        x .= A*w\n        estimator += factor*(w'*x)\n    end\n\n    return estimator\nend\n", "meta": {"hexsha": "83265e618746b153be29322a408bdd965348ca36", "size": 1180, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tools.jl", "max_stars_repo_name": "numlinalg/RLinearAlgebra.jl", "max_stars_repo_head_hexsha": "757cc7e581303c4fb6db228618f4be5caa02d3b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-05-28T17:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T05:23:14.000Z", "max_issues_repo_path": "src/tools.jl", "max_issues_repo_name": "numlinalg/RLinearAlgebra.jl", "max_issues_repo_head_hexsha": "757cc7e581303c4fb6db228618f4be5caa02d3b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-06-16T16:01:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-16T12:28:20.000Z", "max_forks_repo_path": "src/tools.jl", "max_forks_repo_name": "numlinalg/RLinearAlgebra.jl", "max_forks_repo_head_hexsha": "757cc7e581303c4fb6db228618f4be5caa02d3b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6923076923, "max_line_length": 66, "alphanum_fraction": 0.6008474576, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741281688026, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7999088597903219}}
{"text": "export CnoidalWaveSerreGreenNaghdi\nusing Elliptic\n\n\"\"\"\n    CnoidalWaveSerreGreenNaghdi(param; P)\n\nCompute the Serre-Green-Naghdi cnoidal wave with prescribed `h₀<h₁<h₂`.\n`h_1` is the minimum, `h_2` is the maximum of the wave.\nAs `h₀ -> h₁`, the cnoidal wave converges towards the solitary wave.\nSee for instance Gavrilyuk, Nkonga, Shyue and Truskinovsky, doi:10.1088/1361-6544/ab95ac\n\n# Arguments\n- `param :: NamedTuple`: parameters of the problem containing `h₀<h₁<h₂` and dimensionless parameters `ϵ` and `μ`, and number of collocation points `N`.\n- `P :: Int`: (keyword, optional, default = 2) the number of periods of the cnoidal wave in the constructed mesh.\n\n# Return values\n`(η,u,v,mesh,param)` with\n- `η :: Vector{Float64}`: surface deformation;\n- `u :: Vector{Float64}`: layer-averaged velocity;\n- `v :: Vector{Float64}`: tangential velocity;\n- `mesh :: Mesh`: mesh collocation points;\n- `param :: NamedTuple`: useful parameters\n\"\"\"\nfunction CnoidalWaveSerreGreenNaghdi(\n                param :: NamedTuple;\n                P = 2 :: Int)\n\n        ϵ = param.ϵ\n        μ = param.μ\n\n        h₀=param.h₀\n        h₁=param.h₁\n        h₂=param.h₂\n        c = sqrt(h₀*h₁*h₂)\n        @info string(\"The velocity is c=\",c)\n        m = sqrt((h₂-h₁)/(h₂-h₀))\n        κ = sqrt(3*(h₂-h₀))/(2*c)/sqrt(μ)\n        λ = Elliptic.K(m^2)/κ\n        @info string(\"The period is 2*λ=\",2*λ)\n        mesh = Mesh((L=P*λ,N=param.N))\n        formula = h₁ .-1 .+ (h₂-h₁)*(Jacobi.cn.(κ*mesh.x,m^2).^2)\n\n        a₀ = h₀\n        a₁ = h₂ - h₀\n        formula2 = a₀ .-1 .+ a₁*(Jacobi.dn.(κ*mesh.x,m^2).^2)\n        H₀= a₀+a₁*Elliptic.E(m^2)/Elliptic.K(m^2)\n        u2 = c*(1 ./ H₀ .- 1 ./(1 .+ formula2))\n        param = (h₀=h₀,h₁=h₁,h₂=h₂,a₀=a₀,a₁=a₁,H₀=H₀,c=c,λ=λ,m=m,κ=κ)\n\n\n        η = formula/ϵ\n        h = 1 .+ ϵ*η\n        u = c*η./h\n\tk = mesh.k\n        Dx=  1im * k\n\tF₀ = sqrt(μ)*Dx\n        DxF(v) = real.(ifft(F₀ .* fft(v)))\n\tv = u - 1/3 ./h .* (DxF(h.^3 .*DxF(u)))\n        #\n        # h2 = 1 .+ ϵ*formula2\n        # v2 = u2 - 1/3 ./h2 .* (DxF(h2.^3 .*DxF(u2)))\n\n        return (η,u,v,mesh,param)\n\nend\n", "meta": {"hexsha": "dde7be3d5a89811a8d8751b76df1963b96d00b3a", "size": 2081, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/initialdata/CnoidalWaveSerreGreenNaghdi.jl", "max_stars_repo_name": "WaterWavesModels/ShallowWaterModels.jl", "max_stars_repo_head_hexsha": "ab745353a2472a76646d976c6fe536f0be664488", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-21T17:07:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-25T20:31:31.000Z", "max_issues_repo_path": "src/initialdata/CnoidalWaveSerreGreenNaghdi.jl", "max_issues_repo_name": "WaterWavesModels/ShallowWaterModels.jl", "max_issues_repo_head_hexsha": "ab745353a2472a76646d976c6fe536f0be664488", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-07-17T17:38:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T07:36:48.000Z", "max_forks_repo_path": "src/initialdata/CnoidalWaveSerreGreenNaghdi.jl", "max_forks_repo_name": "WaterWavesModels/ShallowWaterModels.jl", "max_forks_repo_head_hexsha": "ab745353a2472a76646d976c6fe536f0be664488", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5303030303, "max_line_length": 152, "alphanum_fraction": 0.5670350793, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741295151718, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7999088513694025}}
{"text": "import QuadGK:quadgk\nimport Roots:find_zeros\n\n\n\" Compute M₀ by solving F(m) = 0 \"\nfunction mag(β, mass)\n    \n    F(m) = begin\n        g(x, n, m) = (1 / π) * (exp(β * m * cos(x)) * cos(n * x))\n        bessel0(x) = g(x, 0, m) \n        bessel1(x) = g(x, 1, m)\n        mass * quadgk(bessel1, 0, π)[1] / quadgk(bessel0, 0, π)[1] - m\n    end\n    \n    find_zero(F, (0, mass))\nend\n\n#-\n\nfunction Norm(f::Array{Float64,2}, delta1, delta2)\n   return delta1 * sum(delta2 * sum(real(f), dims=1))\nend\n\nstruct HMF\n\n    b    :: Float64\n    m    :: Float64\n    ϵ    :: Float64\n\n    function HMF( mass, T, ϵ )\n\n        b = 1 / T\n        m = mag(b, mass)\n        w = sqrt(m)\n        new( b, m, ϵ )\n    end\n\nend\n\nfunction distribution( mesh1 :: UniformMesh,\n                       mesh2 :: UniformMesh,\n\t\t       hmf   :: HMF)\n    b  = hmf.b\n    m  = hmf.m\n    delta1 = mesh1.step\n    delta2 = mesh2.step\n    x  = mesh1.points\n    v  = mesh2.points\n    \n    f  = transpose(exp.(-b * (v.^2 / 2))) .* exp.(b * m * cos.(x))\n    a  = mass / Norm(real(f), delta1, delta2)\n    @. a * transpose(exp(-b * (v^2) / 2)) * exp(b*m*cos(x)) * (1+ϵ*cos(x))\n    \nend \n", "meta": {"hexsha": "69161f8e14421f8beda90e14717ff0e911fa4446", "size": 1131, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/initializers/hmf.jl", "max_stars_repo_name": "pnavaro/Splittings.jl", "max_stars_repo_head_hexsha": "a2d98db435e9a2467b07ce0dacda2769fd94b752", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-25T05:52:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-25T05:52:11.000Z", "max_issues_repo_path": "src/initializers/hmf.jl", "max_issues_repo_name": "pnavaro/Splittings.jl", "max_issues_repo_head_hexsha": "a2d98db435e9a2467b07ce0dacda2769fd94b752", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/initializers/hmf.jl", "max_forks_repo_name": "pnavaro/Splittings.jl", "max_forks_repo_head_hexsha": "a2d98db435e9a2467b07ce0dacda2769fd94b752", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5636363636, "max_line_length": 74, "alphanum_fraction": 0.4854111406, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296943, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7999088506676386}}
{"text": "function lglnodes(N,a,b)\n\n# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n# %\n# % lglnodes.m\n# %\n# % Computes the Legendre-Gauss-Lobatto nodes, weights and the LGL Vandermonde \n# % matrix. The LGL nodes are the zeros of (1-x^2)*P'_N(x). Useful for numerical\n# % integration and spectral methods. \n# %\n# % Reference on LGL nodes and weights: \n# %   C. Canuto, M. Y. Hussaini, A. Quarteroni, T. A. Tang, \"Spectral Methods\n# %   in Fluid Dynamics,\" Section 2.3. Springer-Verlag 1987\n# %\n# % Written by Greg von Winckel - 04/17/2004\n# % Contact: gregvw@chtm.unm.edu\n# %\n# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n#\n# % Truncation + 1\n\tN1=N+1;\n\n\t#% Use the Chebyshev-Gauss-Lobatto nodes as the first guess\n\tx=cos.(pi*collect(0:N)/N);\n\n\t# The Legendre Vandermonde Matrix\n\tP=zeros(N1,N1);\n\n\t# \t% Compute P_(N) using the recursion relation\n\t# \t% Compute its first and second derivatives and \n\t# \t% update x using the Newton-Raphson method.\n\n\txold=2;\n\n\twhile maximum(abs.(x .- xold))>eps()\n\n\t    xold=x;\n        \n\t    P[:,1] .= 1;    P[:,2] = x;\n    \n\t    for k=2:N\n\t\tP[:,k+1]=( (2*k-1)*x.*P[:,k]-(k-1)*P[:,k-1] )/k;\n\t    end\n     \n\t    x=xold-( x.*P[:,N1]-P[:,N] )./( N1*P[:,N1] );\n             \n\tend\n\n\tw=2 ./ (N*N1*P[:,N1].^2)/2 .* (b-a);\n\tx = (x .+ 1)*(b-a)/2.0 .+ a \n\treturn x,w,P\nend", "meta": {"hexsha": "8fa016d27b3241b72efecb78ed3be3381913f3d4", "size": 1354, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lglnodes.jl", "max_stars_repo_name": "flavioluiz/phjulia", "max_stars_repo_head_hexsha": "aee3162f0bec3aed0bed0f6ae4138a7e6a5b5797", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-28T19:34:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-28T19:34:40.000Z", "max_issues_repo_path": "src/lglnodes.jl", "max_issues_repo_name": "flavioluiz/phjulia", "max_issues_repo_head_hexsha": "aee3162f0bec3aed0bed0f6ae4138a7e6a5b5797", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-10-31T14:12:22.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-31T14:12:22.000Z", "max_forks_repo_path": "src/lglnodes.jl", "max_forks_repo_name": "flavioluiz/phjulia", "max_forks_repo_head_hexsha": "aee3162f0bec3aed0bed0f6ae4138a7e6a5b5797", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-01T17:15:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:15:30.000Z", "avg_line_length": 26.0384615385, "max_line_length": 82, "alphanum_fraction": 0.5066469719, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.7998596473427734}}
{"text": "\"\"\"\n    to_matrix(points)\n\nConvert collection of d-dimensional points to d×n matrix\n\"\"\"\nfunction to_matrix(points)\n    dim = length(points[1])\n    T = eltype(points[1])\n    n = length(points)\n    result = zeros(T, (dim, n))\n\n    for (i, p) in enumerate(points)\n        length(p) == dim || throw(ArgumentError(\"points must have the same length\"))\n        result[:, i] .= p\n    end\n\n    return result\nend\n\n\"\"\"\n    distances(points, metric=Euclidean(1e-12))\n\nReturn distance matrix calculated from `points` with `metric`.\n\"\"\"\nfunction distances(points, metric=Euclidean(1e-12))\n    points_mat = to_matrix(points)\n    dists = pairwise(metric, points_mat; dims=2)\n    return dists\nend\n\n\"\"\"\n    radius(dists)\n    radius(points[, metric=Euclidean(1e-12)])\n\nCalculate the radius of the space. This is used for default `thresholds`.\n\"\"\"\nfunction radius(dists::AbstractMatrix)\n    return minimum(maximum(abs, dists[:, i]) for i in 1:size(dists, 1))\nend\nfunction radius(dists::SparseMatrixCSC)\n    return maximum(dists)\nend\nfunction radius(points, metric=Euclidean(1e-12))\n    radius = Inf\n    for p in points\n        p_max = 0.0\n        for q in points\n            p == q && continue\n            p_max = max(p_max, metric(SVector(p), SVector(q)))\n        end\n        radius = min(p_max, radius)\n    end\n    return radius\nend\n", "meta": {"hexsha": "015741d53c611cc974a4a4fac4980fd0b7d346d5", "size": 1315, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/filtrations/utils.jl", "max_stars_repo_name": "davidhien/Ripserer.jl", "max_stars_repo_head_hexsha": "95391396bea1b2b922967f7da21de05d6b3b67bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2020-06-03T11:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T21:37:46.000Z", "max_issues_repo_path": "src/filtrations/utils.jl", "max_issues_repo_name": "davidhien/Ripserer.jl", "max_issues_repo_head_hexsha": "95391396bea1b2b922967f7da21de05d6b3b67bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 149, "max_issues_repo_issues_event_min_datetime": "2020-04-09T07:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T10:20:46.000Z", "max_forks_repo_path": "src/filtrations/utils.jl", "max_forks_repo_name": "davidhien/Ripserer.jl", "max_forks_repo_head_hexsha": "95391396bea1b2b922967f7da21de05d6b3b67bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-08-06T22:56:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T14:55:51.000Z", "avg_line_length": 23.9090909091, "max_line_length": 84, "alphanum_fraction": 0.6448669202, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.7998596455799414}}
{"text": "using GaussQuadrature\nusing SpecialFunctions: gamma\nusing Printf\n\n#T = Float32\nT = Float64\n#T = BigFloat\n\nprintln(\"\\nFloating point data type is \", T)\nprintln(\"\\teps = \", eps(T))\n\nnpts = Dict( \n    Float32 => Dict(  \"Legendre\"  => 10, \n                      \"Chebyshev\" => 10,\n                      \"Jacobi\"    => 10,\n                      \"Laguerre\"  => 10,\n                      \"Hermite\"   => 10,\n                      \"Logweight\" => 10 ),\n    Float64 => Dict(  \"Legendre\"  => 20, \n                      \"Chebyshev\" => 12,\n                      \"Jacobi\"    => 12,\n                      \"Laguerre\"  => 20,\n                      \"Hermite\"   => 16,\n                      \"Logweight\" => 16 ),\n    BigFloat => Dict( \"Legendre\" => 100, \n                      \"Chebyshev\" => 60,\n                      \"Jacobi\"    => 60,\n                      \"Laguerre\"  => 600,\n                      \"Hermite\"   => 80,\n                      \"Logweight\" => 70 )\n)\n\nconst half = one(T) / 2\n\nfunction variant(endpt)\n    if endpt == neither\n        return \"Default    \"\n    elseif endpt == left\n        return \"Left Radau \"\n    elseif endpt == right\n        return \"Right Radau\"\n    elseif endpt == both\n        return \"Lobatto    \"\n    else\n        error(\"Unknown endpt\")\n    end\nend\n\nfunction table(f, rule, name, ans::T, n::Integer, endpts) where {T}\n    println(\"\\nTesting \", name, \" rule with \", n, \" points:\")\n    for endpt in endpts\n        x, w = rule(n, endpt)\n        integral = zero(typeof(x[1])) \n        for j = 1:n\n            integral += w[j] * f(x[j])\n        end\n        relerr = ( integral - ans ) / ans\n        @printf(\"\\t%s  %12.2e\\n\", variant(endpt), relerr)\n    end\nend\n\nBeta(x::T, y::T) where {T} = gamma(x) * gamma(y) / gamma(x+y)\n\nlegendrefunc(x::T)  where {T} = one(T) / ( one(T) + x^2 )\n\njacobifunc(x::T, c::T, alpha::T, beta::T) where {T} = (\n             (x+c)^convert(T,-alpha-beta-2) )\n\njacobiintegral(alpha::T, beta::T, c::T) where {T} = ( 2^(alpha+beta+1)\n      * Beta(1+alpha,1+beta) / ( (c-1)^(1+alpha) * (c+1)^(1+beta) ) )\n\nfunction laguerrefunc(x::T, alpha::T) where {T}\n    if x > eps(T)\n        r = -expm1(-x) / x\n    else\n        r = one(T)\n    end\n    return r^alpha\nend\n\nlaguerreintegral(alpha::T) where {T} = Beta(one(T), 1+alpha)\n\nhermiteintegral(a::T) where {T} = sqrt(convert(T, pi)) * exp(a^2)\n\nfunction logweightintegral(::Type{T}) where {T} \n    three = convert(T, 3)\n    return (π/three)^2 * 2sqrt(three)\nend\n\n\nendpts = [neither, left, right, both]\ntable(legendrefunc, (n, endpt) -> legendre(T, n, endpt), \n      \"Legendre\", convert(T, pi)/2, npts[T][\"Legendre\"], endpts)\n\nc = convert(T, 3.0)\ntable(x -> jacobifunc(x, c, -half, -half),\n      (n, endpt) -> chebyshev(T, n, 1, endpt), \"Chebyshev (kind=1)\",\n      jacobiintegral(-half, -half, c), npts[T][\"Chebyshev\"], endpts)\n\ntable(x -> jacobifunc(x, c, half, half),\n      (n, endpt) -> chebyshev(T, n, 2, endpt), \"Chebyshev (kind=2)\",\n      jacobiintegral(half, half, c), npts[T][\"Chebyshev\"], endpts)\n\nalpha = convert(T, 2)  / 5\nbeta  = convert(T, -1) / 5 \ntable(x -> jacobifunc(x, c, alpha, beta),\n      (n, endpt) -> jacobi(n, alpha, beta, endpt), \"Jacobi\", \n      jacobiintegral(alpha, beta, c), npts[T][\"Jacobi\"], endpts)\n\ntable(x -> laguerrefunc(x, alpha), \n      (n, endpt) -> laguerre(n, alpha, endpt), \"Laguerre\",\n      laguerreintegral(alpha), npts[T][\"Laguerre\"], [neither, left])\n\na = convert(T, 6) / 5\ntable(x -> exp(2*a*x), (n, endpt) -> hermite(T, n), \"Hermite\",\n      hermiteintegral(a), npts[T][\"Hermite\"], [neither])\n\nhalf = convert(T, 1//2)\ntable(x -> (1-x^2)/(1+x^3), (n, endpt) -> logweight(n, -half, endpt), \n      \"Logweight\", logweightintegral(T), npts[T][\"Logweight\"], endpts)\n", "meta": {"hexsha": "bc9e7d88e19979bd6f6d46fe80d3e9e97cab60c8", "size": 3678, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/examples.jl", "max_stars_repo_name": "simonbyrne/GaussQuadrature.jl", "max_stars_repo_head_hexsha": "3ab2952d35c8d7eab8796f72f430805540546d3e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2015-06-15T12:23:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T10:20:25.000Z", "max_issues_repo_path": "test/examples.jl", "max_issues_repo_name": "simonbyrne/GaussQuadrature.jl", "max_issues_repo_head_hexsha": "3ab2952d35c8d7eab8796f72f430805540546d3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2015-07-11T09:07:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-19T07:12:15.000Z", "max_forks_repo_path": "test/examples.jl", "max_forks_repo_name": "simonbyrne/GaussQuadrature.jl", "max_forks_repo_head_hexsha": "3ab2952d35c8d7eab8796f72f430805540546d3e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-06-15T12:23:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T18:10:50.000Z", "avg_line_length": 30.3966942149, "max_line_length": 70, "alphanum_fraction": 0.5149537792, "num_tokens": 1258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374443, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7998287144285257}}
{"text": "using JuMP\nusing Clp\n\n\nm = Model(Clp.Optimizer)\n\n@variable(m, x₁ ≥ 0)\n@variable(m, x₂ ≥ 0)\n\n@objective(m, Max, 3000x₁  + 5000x₂)\n@constraint(m, 3x₁ + 2x₂ ≤ 18)\n@constraint(m, x₁ ≤ 4)\n@constraint(m, x₂ ≤ 6)\n\nprint(m)\n\noptimize!(m)\n\nstatus = termination_status(m)\n\nprintln(\"Solution status: \", status)\n\nprintln(\"Objective value: \", objective_value(m))\nprintln(\"x₁ = \", value(x₁))\nprintln(\"x₂ = \", value(x₂))\n", "meta": {"hexsha": "8fa6bc1d90d5cc5166102a49c22537fa073c1e2b", "size": 406, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week2/from_tutorials/problem_1.jl", "max_stars_repo_name": "InzamamRahaman/COMP6925-2021", "max_stars_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-23T23:33:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T01:47:28.000Z", "max_issues_repo_path": "week2/from_tutorials/problem_1.jl", "max_issues_repo_name": "InzamamRahaman/COMP6925-2021", "max_issues_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week2/from_tutorials/problem_1.jl", "max_forks_repo_name": "InzamamRahaman/COMP6925-2021", "max_forks_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.6153846154, "max_line_length": 48, "alphanum_fraction": 0.657635468, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551576415562, "lm_q2_score": 0.8289388083214155, "lm_q1q2_score": 0.799805884578163}}
{"text": "\"\"\"\nArchimedes' Approximation of Pi\n\n## References\n\n- https://itech.fgcu.edu/faculty/clindsey/mhf4404/archimedes/archimedes.html\n- https://betterexplained.com/articles/prehistoric-calculus-discovering-pi/\n\"\"\"\nmodule ArchimedesPi\n\n#=\n\n\"If an angle of a triangle be bisected and the straight line cutting the angle cut the base also,\nthe segments of the base will have the same ratio as the remaining sides of the triangle.\"\n\n-- Euclid's Elements\n\nLet $r = 1$, $OSide_{n} = a$, $ISide_{n} = b$, $OSide_{2n} = x$, $ISide_{2n} = y$, we have\n\n$$\n(x / 2) / (a / 2 - x / 2) = 1 / (a / b)  =>\nx = a * b / (a + b)\n$$\n\nand\n\n$$\n(y / 2) / (x / 2) = (b / 2) / y  =>\n2 (y ^ 2) = x * b\n$$\n\nSo the perimeter of circumscribing polygon of 2n sides is (the harmonic mean)\n\n$$\nO_{2n} = 2n * OSide_{2n} = 2n / (1 / a + 1 / b) = \\frac{2}{1 / I_{n} + 1 / O_{n}}\n$$\n\nand the perimeter of inscribing polygon of 2n sides is (the geometric mean)\n\n$$\nI_{2n} = 2n * ISide_{2n}\n       = 2n * \\sqrt{x * b} / \\sqrt{2}\n       = n * \\sqrt{2} * \\sqrt{x * b}\n       = \\sqrt{2} * \\sqrt{(OSide_{2n} * n) * (ISide_{n} * n)}\n       = \\sqrt{2} * \\sqrt{(O_{2n} / 2) * I_{n}}\n       = \\sqrt{I_{n} * O_{2n}}\n$$\n=#\n\nfunction calculate_pi(n_digits::Int=100)::BigFloat\n    prec = Int(ceil(log2(10) * (n_digits + 1)))  # +1 because pi = 3.(...)\n    setprecision(prec * 2) do\n        # Starts from a hexagon\n        outer = big\"2.0\" * sqrt(big\"3.0\")\n        inner = big\"3.0\"\n        df = outer - inner\n\n        while true\n            outer = big\"2.0\" / (one(BigFloat) / inner + one(BigFloat) / outer)\n            inner = sqrt(inner * outer)\n\n            df = begin\n                new_df = outer - inner\n                if new_df >= df\n                    break\n                end\n                new_df\n            end\n        end\n\n        pi_archimedes = (outer + inner) / big\"2.0\"\n        # Still uses the default rounding, intentionally\n        setprecision(prec)\n        pi_archimedes + big(0)\n    end\nend\n\n#=\nVerifies the answer:\n\n    pi_archimedes = calculate_pi()\n    setprecision(precision(pi_archimedes))  # Warning: Set the global BigFloat precision!\n    println(pi_archimedes - big(pi))\n=#\n\nend # module\n", "meta": {"hexsha": "34dc94cd45feed64b55feae3029074e494b41417", "size": 2168, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ArchimedesPi/ArchimedesPi.jl", "max_stars_repo_name": "gyk/TrivialSolutions", "max_stars_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T05:51:37.000Z", "max_issues_repo_path": "ArchimedesPi/ArchimedesPi.jl", "max_issues_repo_name": "gyk/TrivialSolutions", "max_issues_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ArchimedesPi/ArchimedesPi.jl", "max_forks_repo_name": "gyk/TrivialSolutions", "max_forks_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9195402299, "max_line_length": 97, "alphanum_fraction": 0.5544280443, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551546097942, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.799805877987591}}
{"text": "#############################################################################\n# log_determinant.jl\n# given V = {1, 2, ..., n}, M ∈ ℜ^{n×n}, F(S) = logdet(M_S)\n#############################################################################\n\nimport Base.logdet\n\nexport logdet\nexport sign, monotonicity, modularity, evaluate\n\nmutable struct LogDeterminantAtom <: SubmodFunc\n  head::Symbol\n  id_hash::UInt64\n  children::Tuple{AbstractMatrix, CombiSet}\n  size::Tuple{Int, Int}\n  matrix::AbstractMatrix\n  setvariables::Array{CombiSet}\n\n  function LogDeterminantAtom(matrix::AbstractMatrix, S::CombiSet)\n    if size(matrix)[1] != S.cardinality\n      error(\"Cannot define a log determinant function when the number of volumns of the matrix is different from the size of the set variable.\")\n    else\n      children = (matrix, S)\n      setvariables = get_sv(S)\n      return new(:logdet, hash(children), children, (1, 1), matrix, setvariables)\n    end\n  end\nend\n\nlogdet(matrix::AbstractMatrix, S::CombiSet) = LogDeterminantAtom(matrix, S)\n\nfunction sign(F::LogDeterminantAtom)\n  return NoSign()\nend\n\nfunction monotonicity(F::LogDeterminantAtom)\n  return (NoMonotonicity(), )\nend\n\nfunction modularity(F::LogDeterminantAtom)\n  if isposdef(F.matrix)\n    return SubModularity()\n  elseif isposdef(-F.matrix)\n    return SuperModularity()\n  else\n    return NotDetermined()\n  end\nend\n\nfunction evaluate(F::LogDeterminantAtom)\n  set = get_elements(F.children[2])\n  if length(set) == 0\n    return 0\n  end\n  matrix = F.matrix[]\n  return logdet(F.matrix[set, set])\nend\n", "meta": {"hexsha": "32459009468e2e3d1cbd87053e1a82b1139bd9fe", "size": 1544, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/submodular_functions/log_determinant.jl", "max_stars_repo_name": "madeleineudell/CombiOpt.jl", "max_stars_repo_head_hexsha": "d3f1d0e06531597d3360f270adb5668545f49557", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-20T10:16:51.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-20T10:16:51.000Z", "max_issues_repo_path": "src/submodular_functions/log_determinant.jl", "max_issues_repo_name": "madeleineudell/CombiOpt.jl", "max_issues_repo_head_hexsha": "d3f1d0e06531597d3360f270adb5668545f49557", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/submodular_functions/log_determinant.jl", "max_forks_repo_name": "madeleineudell/CombiOpt.jl", "max_forks_repo_head_hexsha": "d3f1d0e06531597d3360f270adb5668545f49557", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6206896552, "max_line_length": 144, "alphanum_fraction": 0.6450777202, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778024535095, "lm_q2_score": 0.8354835371034369, "lm_q1q2_score": 0.7997898443844632}}
{"text": "\"\"\"\n**Adam Optimizer**\n```julia\n    Adam(;α=0.001, β₁=0.9, β₂=0.999, ϵ=10e-8)\n```\n\nAlgorithm:\n```math\n\\\\begin{align*}\n    m_t =& \\\\beta_1 m_{t-1} + (1-\\\\beta_1)g_t\\\\\\\\\n    v_t =& \\\\beta_2 v_{t-1} + (1-\\\\beta_2)g_t^2\\\\\\\\\n    \\\\hat{m}_t =& \\\\frac{m_t}{1-\\\\beta_1^t}\\\\\\\\\n    \\\\hat{v}_t =& \\\\frac{v_t}{1-\\\\beta_2^t}\\\\\\\\\n    \\\\Delta x_t =& \\\\frac{\\\\alpha}{\\\\sqrt{\\\\hat{v}_t}+\\\\epsilon}\\\\hat{m}_t\\\\\\\\\n\\\\end{align*}\n```\n[Algorithm Reference](https://arxiv.org/abs/1412.6980)\n\"\"\"\nmutable struct Adam <: Optimizer\n    opt_type::String\n    t::Int64\n    ϵ::Float64\n    α::Float64\n    β₁::Float64\n    β₂::Float64\n    m_t::AbstractArray\n    v_t::AbstractArray\nend\n\n\nfunction Adam(;α::Real=0.001, β₁::Real=0.9, β₂::Real=0.999, ϵ::Real=10e-8)\n    @assert α > 0.0 \"α must be greater than 0\"\n    @assert β₁ > 0.0 \"β₁ must be greater than 0\"\n    @assert β₂ > 0.0 \"β₂ must be greater than 0\"\n    @assert ϵ > 0.0 \"ϵ must be greater than 0\"\n\n    Adam(\"Adam\", 0, ϵ, α, β₁, β₂, [], [])\nend\n\nparams(opt::Adam) = \"ϵ=$(opt.ϵ), α=$(opt.α), β₁=$(opt.β₁), β₂=$(opt.β₂)\"\n\nfunction update(opt::Adam, g_t::AbstractArray{T}) where {T<:Real}\n    # resize biased moment estimates if first iteration\n    if opt.t == 0\n        opt.m_t = zero(g_t)\n        opt.v_t = zero(g_t)\n    end\n\n    # update timestep\n    opt.t += 1\n\n    # update biased first moment estimate\n    opt.m_t = opt.β₁ * opt.m_t + (one(T) - opt.β₁) * g_t\n\n    # update biased second raw moment estimate\n    opt.v_t = opt.β₂ * opt.v_t + (one(T) - opt.β₂) * ((g_t) .^2)\n\n    # compute bias corrected first moment estimate\n    m̂_t = opt.m_t / (one(T) - opt.β₁^opt.t)\n\n    # compute bias corrected second raw moment estimate\n    v̂_t = opt.v_t / (one(T) - opt.β₂^opt.t)\n\n    # apply update\n    ρ = opt.α * m̂_t ./ (sqrt.(v̂_t .+ opt.ϵ))\n\n    return ρ\nend\n", "meta": {"hexsha": "839d0de77e27aae3e0e11ee552ad22415e468093", "size": 1781, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/AdamOptimizer.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_stars_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2017-08-20T00:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T03:09:32.000Z", "max_issues_repo_path": "src/AdamOptimizer.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_issues_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-11-19T22:38:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-25T20:33:14.000Z", "max_forks_repo_path": "src/AdamOptimizer.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_forks_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-08-03T16:14:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:48:41.000Z", "avg_line_length": 25.8115942029, "max_line_length": 78, "alphanum_fraction": 0.569904548, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778036723354, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7997898434420982}}
{"text": "using LinearAlgebra\r\nusing Statistics\r\n\r\n\r\nfunction computegeometriccenter(points)\r\n    x = [points[i][1] for i in 1:length(points)]\r\n    y = [points[i][2] for i in 1:length(points)]\r\n    z = [points[i][3] for i in 1:length(points)]\r\n\r\n    return [mean(x), mean(y), mean(z)]\r\nend\r\n\r\nfunction computesurfacenormal(vectors)\r\n    v1 = vectors[2] - vectors[1]\r\n    v2 = vectors[3] - vectors[1]\r\n    return 0.5*cross(v1, v2)\r\nend\r\n\r\nfunction computemagnitude(vector)\r\n    return sqrt(dot(vector, vector))\r\nend\r\n", "meta": {"hexsha": "21c28f793aa0ee4a7c07fdf9b794e65eaeb32473", "size": 506, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Utils/MeshGeometryUtils.jl", "max_stars_repo_name": "andiraarif/FlicsFlow.jl", "max_stars_repo_head_hexsha": "50fa959666b9ed4fde158fc1be4d259f73675b06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/MeshGeometryUtils.jl", "max_issues_repo_name": "andiraarif/FlicsFlow.jl", "max_issues_repo_head_hexsha": "50fa959666b9ed4fde158fc1be4d259f73675b06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utils/MeshGeometryUtils.jl", "max_forks_repo_name": "andiraarif/FlicsFlow.jl", "max_forks_repo_head_hexsha": "50fa959666b9ed4fde158fc1be4d259f73675b06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0, "max_line_length": 49, "alphanum_fraction": 0.6442687747, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939516, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.7997628739072621}}
{"text": "\"\"\"\n softmax(X::AbstractMatrix{<:Real})\nReturn the softmax computed in a numerically stable way:\n``σ(x) = exp.(x) ./ sum(exp.(x))``\nImplementation taken from NNlib.jl.\n\"\"\"\nfunction softmax(X::AbstractMatrix{<:Real})\n    S = copyto!(similar(X, eltype(X)), X)\n    return softmax!(S)\nend\n\n\"\"\"\n softmax!(X::AbstractMatrix{<:Real})\nReturn the softmax computed in a numerically stable way:\n``σ(x) = exp.(x) ./ sum(exp.(x))`` and store the result in the\ninput matrix\nImplementation taken from NNlib.jl.\n\"\"\"\nfunction softmax!(X::AbstractMatrix{<:Real})\n    max_ = maximum(X, dims=2)\n    X .= exp.(X .- max_) \n    X ./= sum(X, dims=2)\n    return X \nend\n", "meta": {"hexsha": "2fbf07ef53c98a2ce47d28d796a346230be6bef4", "size": 644, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "HamletWantToCode/MLJMultivariateStatsInterface.jl", "max_stars_repo_head_hexsha": "21482fab3a6d7c5875dd215f1caa32025720fe42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "HamletWantToCode/MLJMultivariateStatsInterface.jl", "max_issues_repo_head_hexsha": "21482fab3a6d7c5875dd215f1caa32025720fe42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "HamletWantToCode/MLJMultivariateStatsInterface.jl", "max_forks_repo_head_hexsha": "21482fab3a6d7c5875dd215f1caa32025720fe42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.76, "max_line_length": 62, "alphanum_fraction": 0.650621118, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037363973294, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.7997628710367863}}
{"text": "using PyPlot\n\nL = 1.0\nγ0 = 0.5\nγL = -0.5\nx = range(0, stop=L, length=201)\nu(x, c) = ( ( L - x ) * γ0 + x * γL ) / L + (c/2) * x * ( L - x )\n\nfigure(1)\ncvals = collect(6:-3:-6)\nplot(x, u.(x,cvals'))\ngrid(true)\nxlabel(L\"x\")\nlegend([latexstring(\"c=$(cvals[k])\") for k = 1:length(cvals)])\nsavefig(\"bvp1d_const_rhs.pdf\")\n", "meta": {"hexsha": "271e8bfa0137b735d8a142c8a5a754e0dd4ea47e", "size": 316, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chap1/bvp1d_const_rhs.jl", "max_stars_repo_name": "billmclean/ComputationalMathsNotes", "max_stars_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T21:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:30:20.000Z", "max_issues_repo_path": "src/chap1/bvp1d_const_rhs.jl", "max_issues_repo_name": "billmclean/ComputationalMathsNotes", "max_issues_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chap1/bvp1d_const_rhs.jl", "max_forks_repo_name": "billmclean/ComputationalMathsNotes", "max_forks_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.75, "max_line_length": 65, "alphanum_fraction": 0.5506329114, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678381, "lm_q2_score": 0.8558511524823265, "lm_q1q2_score": 0.7997031782981271}}
{"text": "@doc raw\"\"\"\r\n```\r\nt = find_threshold(Balanced(), histogram, edges)\r\n```\r\nIn balanced histogram thresholding, one interprets a  bin as a  physical weight\r\nwith a mass equal to its occupancy count. The balanced histogram method involves\r\niterating the following three steps: (1) choose the midpoint bin index as a\r\n\"pivot\",  (2) compute the combined weight to the left and right of the pivot bin\r\nand (3) remove the leftmost bin if the left side is the heaviest, and the\r\nrightmost bin otherwise. The algorithm stops when only a single bin remains.\r\nThe last bin determines the sought-after threshold.\r\n\r\n# Output\r\n\r\nReturns a real number `t` in `edges`. The `edges` parameter represents an\r\n`AbstractRange` which specifies the intervals associated with the histogram bins.\r\n\r\n# Details\r\nLet ``f_n`` (``n = 1 \\ldots N``) denote the number of observations in the ``n``th\r\nbin of the histogram. The balanced histogram method constructs a sequence\r\nof nested intervals\r\n\r\n```math\r\n[1,N] \\cap \\mathbb{Z} \\supset I_2 \\supset I_3 \\supset \\ldots \\supset I_{N-1},\r\n```\r\nwhere for ``k = 2 \\ldots N-1``\r\n```math\r\nI_k = \\begin{cases}\r\n   I_{k-1} \\setminus \\{\\min \\left( I_{k-1} \\right) \\} &\\text{if } \\sum_{n = \\min \\left( I_{k-1} \\right)}^{I_m}f_n \\gt   \\sum_{n =  I_m + 1}^{ \\max \\left( I_{k-1} \\right)} f_n, \\\\\r\n   I_{k-1} \\setminus \\{\\max \\left( I_{k-1} \\right) \\} &\\text{otherwise},\r\n\\end{cases}\r\n```\r\nand ``I_m = \\lfloor \\frac{1}{2}\\left(  \\min \\left( I_{k-1} \\right) +  \\max \\left( I_{k-1} \\right) \\right) \\rfloor ``.\r\nThe final interval ``I_{N-1}`` consists of a single element which is the bin index\r\ncorresponding to the desired threshold.\r\n\r\nIf one interprets a bin as a physical weight with a mass equal to its occupancy\r\ncount, then each step of the algorithm can be conceptualised as removing the\r\nleftmost or rightmost bin to \"balance\" the resulting histogram on a pivot. The\r\npivot is defined to be the midpoint between the start and end points of the\r\ninterval under consideration.\r\n\r\nIf it turns out that the single element in ``I_{N-1}`` equals ``1`` or ``N`` then\r\nthe original histogram must have a single peak and the algorithm has failed to\r\nfind a suitable threshold. In this case the algorithm will fall back to using\r\nthe `UnimodalRosin` method to select the threshold.\r\n\r\n\r\n# Arguments\r\n\r\nThe function arguments are described in more detail below.\r\n\r\n##  `histogram`\r\n\r\nAn `AbstractArray` storing the frequency distribution.\r\n\r\n##  `edges`\r\n\r\nAn `AbstractRange` specifying how the intervals for the frequency distribution\r\nare divided.\r\n\r\n# Example\r\n\r\nCompute the threshold for the \"cameraman\" image in the `TestImages` package.\r\n\r\n```julia\r\n\r\nusing TestImages, ImageContrastAdjustment, HistogramThresholding\r\n\r\nimg = testimage(\"cameraman\")\r\nedges, counts = build_histogram(img, 256)\r\n#=\r\n  The `counts` array stores at index 0 the frequencies that were below the\r\n  first bin edge. Since we are seeking a threshold over the interval\r\n  partitioned by `edges` we need to discard the first bin in `counts`\r\n  so that the dimensions of `edges` and `counts` match.\r\n=#\r\nt = find_threshold(Balanced(), counts[1:end], edges)\r\n```\r\n\r\n# Reference\r\n\r\n1. “BI-LEVEL IMAGE THRESHOLDING - A Fast Method”, Proceedings of the First International Conference on Bio-inspired Systems and Signal Processing, 2008. Available: [10.5220/0001064300700076](https://doi.org/10.5220/0001064300700076)\r\n\"\"\"\r\nfunction find_threshold(algorithm::Balanced, histogram::AbstractArray, edges::AbstractRange)\r\n    # set initial start/middle/end points and weigths\r\n    Iₛ = 1\r\n    Iₑ = length(histogram)\r\n    Iₘ = round(Int, (Iₛ + Iₑ) / 2)\r\n    Wₗ = 0\r\n    Wᵣ = 0\r\n    for i = 1:Iₘ\r\n        Wₗ += histogram[i]\r\n    end\r\n    for i = Iₘ:Iₑ\r\n        Wᵣ += histogram[i]\r\n    end\r\n    while Iₛ < Iₑ\r\n        if Wₗ < Wᵣ\r\n            Wᵣ -= histogram[Iₑ]\r\n            Iₑ -= 1\r\n            if (Iₛ + Iₑ) / 2 < Iₘ\r\n                Wₗ -= histogram[Iₘ]\r\n                Wᵣ += histogram[Iₘ]\r\n                Iₘ -= 1\r\n            end\r\n        else\r\n            Wₗ -= histogram[Iₛ]\r\n            Iₛ += 1\r\n            if (Iₛ + Iₑ) / 2 > Iₘ\r\n                Wₗ += histogram[Iₘ + 1]\r\n                Wᵣ -= histogram[Iₘ + 1]\r\n                Iₘ += 1\r\n            end\r\n        end\r\n    end\r\n    if Iₘ == 1 || Iₘ == length(histogram)\r\n        @warn \"Failed to threshold. Falling back to `UnimodalRosin` method.\"\r\n        return find_threshold(UnimodalRosin(), histogram, edges)\r\n    else\r\n        return edges[Iₘ]\r\n    end\r\nend\r\n", "meta": {"hexsha": "7f684bbcb35c27bd429a8e187eef3e208a52725e", "size": 4486, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/balancedthreshold.jl", "max_stars_repo_name": "johnnychen94/HistogramThresholding.jl", "max_stars_repo_head_hexsha": "4dca5c8d80f73b83e80d31d44374aa6d70d36e04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-01-07T18:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-10T09:10:19.000Z", "max_issues_repo_path": "src/balancedthreshold.jl", "max_issues_repo_name": "johnnychen94/HistogramThresholding.jl", "max_issues_repo_head_hexsha": "4dca5c8d80f73b83e80d31d44374aa6d70d36e04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2019-01-07T05:43:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-24T04:03:55.000Z", "max_forks_repo_path": "src/balancedthreshold.jl", "max_forks_repo_name": "johnnychen94/HistogramThresholding.jl", "max_forks_repo_head_hexsha": "4dca5c8d80f73b83e80d31d44374aa6d70d36e04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-01-05T02:39:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T20:13:12.000Z", "avg_line_length": 36.1774193548, "max_line_length": 233, "alphanum_fraction": 0.651359786, "num_tokens": 1300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7997031764261866}}
{"text": "\"\"\" Julia program to find the Length of Longest Increasing Subsequence\n\nIn this problem, given an array we have to find the length of the longest increasing subsequence that array can make.\nThe problem can be solved using Dynamic Programming\n\"\"\"\n\nfunction length_longest_increasing_subsequence(arr, n)\n    max_len = 0\n    # Initialize the dp array with the 1 as value, as the maximum length\n    # at each point is atleast 1, by including that value in the sequence\n    dp = ones(Int, n)\n\n    \"\"\" Now Lets Fill the dp array in Bottom-Up manner\n    Compare Each i'th element to its previous elements from 0 to i-1, \n    If arr[i] > arr[j](where j = 0 to i-1), then it qualifies for increasing subsequence and\n    If dp[i] < dp[j] + 1, then that subsequence  qualifies for being the longest one\"\"\"\n    for i in 1:n\n        for j in 1:(i-1)\n            if(arr[i] > arr[j] && dp[i] < dp[j] + 1)\n                dp[i] = dp[j] + 1\n            end\n        end\n    end\n\n    # Now Find the largest element in the dp array \n    max_len = findmax(dp)[1]\n    return max_len\nend\n\n\nprint(\"What is the length of the array? \")\nn = readline()\nn = parse(Int, n)\nif (n <= 0)\n    println(\"No numbers present in the array!!!\")\n    exit()\nend\narr = Int[]\nprint(\"Enter the numbers: \")\narr = [parse(Int, num) for num in split(readline())]\nres = length_longest_increasing_subsequence(arr, n)\nprint(\"The length of the longest increasing subsequence of the given array is $res\")\n\n\n\"\"\"\nTime Complexity - O(n^2), where 'n' is the size of the array\nSpace Complexity - O(n)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE I\nWhat is the length of the array? 5 \nEnter the numbers: 5 4 3 2 1\nThe length of the longest increasing subsequence of the given array is 1\n\n\"\"\"\n", "meta": {"hexsha": "b04675a78daace8507345da847fec6d6ee27aba0", "size": 1720, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/dp/length_longest_increasing_subsequence.jl", "max_stars_repo_name": "TechSpiritSS/NeoAlgo", "max_stars_repo_head_hexsha": "08f559b56081a191db6c6b1339ef37311da9e986", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 897, "max_stars_repo_stars_event_min_datetime": "2020-06-25T00:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:49:31.000Z", "max_issues_repo_path": "Julia/dp/length_longest_increasing_subsequence.jl", "max_issues_repo_name": "AnshikaAgrawal5501/NeoAlgo", "max_issues_repo_head_hexsha": "d66d0915d8392c2573ba05d5528e00af52b0b996", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5707, "max_issues_repo_issues_event_min_datetime": "2020-06-24T17:53:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T05:03:15.000Z", "max_forks_repo_path": "Julia/dp/length_longest_increasing_subsequence.jl", "max_forks_repo_name": "AnshikaAgrawal5501/NeoAlgo", "max_forks_repo_head_hexsha": "d66d0915d8392c2573ba05d5528e00af52b0b996", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1817, "max_forks_repo_forks_event_min_datetime": "2020-06-25T03:51:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:14:07.000Z", "avg_line_length": 30.1754385965, "max_line_length": 117, "alphanum_fraction": 0.6715116279, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.8740772253241802, "lm_q1q2_score": 0.7996940902148498}}
{"text": "#############################################################################\n#############################################################################\n#\n# This file implements polynomial GCD \n#                                                                               \n#############################################################################\n#############################################################################\n\n\"\"\"\nThe extended euclid algorithm for polynomials modulo prime.\n\"\"\"\n\nfunction extended_euclid_alg(a::PolynomialModP, b::PolynomialModP)\n    prime = a.mod\n    old_r, r = a, b\n    old_s, s = one(PolynomialModP,prime), zero(PolynomialModP,prime)\n    old_t, t = zero(PolynomialModP,prime), one(PolynomialModP,prime)\n\n    while !iszero(r)\n\n        q = divide(old_r, r) |> first\n\n        old_r, r = r, old_r - q*r\n\n        old_s, s = s, old_s - q*s\n  \n        old_t, t = t, old_t - q*t\n     \n    end\n    g, s, t = old_r, old_s, old_t\n    @assert s*a + t*b - g == 0\n    return g, s, t  \nend\n\n\"\"\"\nThe GCD of two polynomials modulo prime.\n\"\"\"\n\ngcd(a::PolynomialModP, b::PolynomialModP) = extended_euclid_alg(a,b) |> first", "meta": {"hexsha": "4d24ffc81fdc9d8a3ad25ba4cbdead76b3620b97", "size": 1147, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basic_polynomial_operations/polynomial_gcd.jl", "max_stars_repo_name": "Talis0/2504_2021_project1", "max_stars_repo_head_hexsha": "c2c73a74e5b909b404ea8ed8ee42e1cddeacbb2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basic_polynomial_operations/polynomial_gcd.jl", "max_issues_repo_name": "Talis0/2504_2021_project1", "max_issues_repo_head_hexsha": "c2c73a74e5b909b404ea8ed8ee42e1cddeacbb2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basic_polynomial_operations/polynomial_gcd.jl", "max_forks_repo_name": "Talis0/2504_2021_project1", "max_forks_repo_head_hexsha": "c2c73a74e5b909b404ea8ed8ee42e1cddeacbb2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4102564103, "max_line_length": 80, "alphanum_fraction": 0.4071490846, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075744568838, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7996490278378126}}
{"text": "\r\n\r\n\r\n# function linsolve_tridiagonal(left_diag::Vector, main_diag::Vector, right_diag::Vector, rhs::Vector)\r\nfunction linsolve_tridiagonal(left_diag, main_diag, right_diag, rhs)\r\n    n_row = length(main_diag)\r\n    n = length(left_diag)\r\n    if n+1 != n_row\r\n        error(\"Invalid dimension for left diag\")\r\n    end\r\n    if length(right_diag) != n\r\n        error(\"Invalid dimension for right diag\")\r\n    end\r\n    \r\n    x = zeros(n_row)\r\n\r\n    a = copy(main_diag)\r\n    r = copy(rhs)\r\n\r\n    # fw elimination\r\n    @inbounds for ii = 2:n_row\r\n        a[ii] -= left_diag[ii-1] * right_diag[ii-1] / a[ii-1]\r\n        r[ii] -= left_diag[ii-1] * r[ii-1] / a[ii-1]\r\n    end\r\n\r\n    # bw elimination\r\n    x[n_row] = r[n_row] / a[n_row]\r\n    @inbounds for ii = (n_row-1):-1:1\r\n        x[ii] = (r[ii] - x[ii+1] * right_diag[ii]) / a[ii]\r\n    end\r\n\r\n    return x\r\nend", "meta": {"hexsha": "b8da70454265930fcdee3c5561ad85b1a655cc21", "size": 853, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/linalg/src/tridiagonal.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "__lib__/math/linalg/src/tridiagonal.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "__lib__/math/linalg/src/tridiagonal.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8484848485, "max_line_length": 103, "alphanum_fraction": 0.5744431419, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7996441745870866}}
{"text": "function sma{T,N}(ta::TimeArray{T,N}, n::Int)\n  tstamps = ta.timestamp[n:end]\n  vals    = zeros(length(ta) - (n-1))\n  cname   = [\"sma$n\"]\n  for i in 1:length(ta) - (n-1)\n    vals[i] =  mean(ta.values[i:i+(n-1)])\n  end\n  TimeArray(tstamps, vals, cname, ta.meta) \nend\n\nfunction ema{T,N}(ta::TimeArray{T,N}, n::Int; wilder=false)\n\n  if  wilder \n    k  = 1/n \n  else\n    k = 2/(n+1)\n  end\n\n  tstamps = ta.timestamp[n:end]\n  vals    = ones(length(ta))\n  vals[n] = sma(ta, n).values[1] # seed with first value an sma value\n  for i = n+1:length(ta)\n    vals[i] =  ta.values[i] * k + vals[i-1] * (1-k)\n  end\n  cname   = [\"ema$n\"]\n  TimeArray(tstamps, vals[n:length(ta)], cname, ta.meta)\nend\n\n# Array dispatch for use by ta algorithms\n\nfunction sma(a::Array{Float64,1}, n::Int)\n  vals    = zeros(length(a) - (n-1))\n  for i in 1:length(a) - (n-1)\n    vals[i] =  mean(a[i:i+(n-1)])\n  end\n  vals\nend\n\nfunction ema(a::Array{Float64,1}, n::Int; wilder=false)\n\n  if  wilder \n    k  = 1/n \n  else\n    k = 2/(n+1)\n  end\n\n  vals    = ones(length(a))\n  vals[n] = sma(a, n)[1] # seed with first value an sma value\n \n  for i = n+1:length(a)\n    vals[i] =  a[i] * k + vals[i-1] * (1-k)\n  end\n  vals[n:end]\nend\n", "meta": {"hexsha": "687a8d90021b029608340e9bd4ecf015dfd45a3e", "size": 1188, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/movingaverages.jl", "max_stars_repo_name": "JuliaPackageMirrors/MarketTechnicals.jl", "max_stars_repo_head_hexsha": "4c80ac26b9a24fb3c4992f6ff1795abdd689dad3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-07-25T07:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-25T08:34:12.000Z", "max_issues_repo_path": "src/movingaverages.jl", "max_issues_repo_name": "JuliaPackageMirrors/MarketTechnicals.jl", "max_issues_repo_head_hexsha": "4c80ac26b9a24fb3c4992f6ff1795abdd689dad3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/movingaverages.jl", "max_forks_repo_name": "JuliaPackageMirrors/MarketTechnicals.jl", "max_forks_repo_head_hexsha": "4c80ac26b9a24fb3c4992f6ff1795abdd689dad3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6, "max_line_length": 69, "alphanum_fraction": 0.5664983165, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474155747541, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7996317351647746}}
{"text": "using NLsolve\n\npoly(x, p) = sum(p[n] * x^(n-1) for n in 1:length(p))\n∂poly(x, p) = sum(n * p[n+1] * x^(n-1) for n in 1:length(p)-1)\n\n\"\"\"\n        fit_cubic(p1, p2, s1, s2)\n\nReturn the coeficients c such that f(x) = c₁ + c₂x + c₃x² + c₄x³ is a cubic polynomial that passes through the points p1 = (x1, y1) and p2 = (x2, y2) with slope s1 at p1 and slope s2 at p2.\n\"\"\"\nfunction fit_cubic(p1, p2, s1, s2)\n    x1, y1 = p1\n    x2, y2 = p2\n\n    function f!(F, c)\n        F[1] = poly(x1, c) - y1\n        F[2] = poly(x2, c) - y2\n        F[3] = ∂poly(x1, c) - s1\n        F[4] = ∂poly(x2, c) - s2\n    end\n\n    results = nlsolve(f!, zeros(4))\n    return results.zero\nend\n", "meta": {"hexsha": "a690e90bd02ecd28e92b20ee76dddfa8c320457f", "size": 659, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Utils/fit_cubic.jl", "max_stars_repo_name": "leea9524/LESbrary.jl", "max_stars_repo_head_hexsha": "1e65bf763ec52746aaaa8abe4c9207b0bb3a4687", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2020-09-22T21:09:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T22:06:32.000Z", "max_issues_repo_path": "src/Utils/fit_cubic.jl", "max_issues_repo_name": "leea9524/LESbrary.jl", "max_issues_repo_head_hexsha": "1e65bf763ec52746aaaa8abe4c9207b0bb3a4687", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69, "max_issues_repo_issues_event_min_datetime": "2020-10-16T18:26:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T21:54:18.000Z", "max_forks_repo_path": "src/Utils/fit_cubic.jl", "max_forks_repo_name": "leea9524/LESbrary.jl", "max_forks_repo_head_hexsha": "1e65bf763ec52746aaaa8abe4c9207b0bb3a4687", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-10-15T19:18:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T00:54:50.000Z", "avg_line_length": 26.36, "max_line_length": 189, "alphanum_fraction": 0.5402124431, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474155747541, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7996317274254552}}
{"text": "using JuMP\nusing Clp\nm = Model(Clp.Optimizer)\n@variable(m, x11 ≥ 0)\n@variable(m, x12 ≥ 0)\n@variable(m, x21  ≥ 0)\n@variable(m, x22 ≥ 0)\n@variable(m, x31 ≥ 0)\n@variable(m, x32 ≥ 0)\n@objective(m, Min, 80x11 + 100x21 + 102x31 + 251x12 + 108x22 + 68x32)\n@constraint(m, x11 + x12 ≤ 1000)\n@constraint(m, x21 + x22 ≤ 1500)\n@constraint(m, x31 + x32 ≤ 1200)\n@constraint(m, x11 + x21 + x31 == 2300)\n@constraint(m, x12 + x22 + x32 == 1400)\nprint(m)\noptimize!(m)\nstatus = termination_status(m)\nprintln(\"Solution status: \", status)\nprintln(\"Objective value: \", objective_value(m))\nprintln(\"x11: \", value(x11))\nprintln(\"x12: \", value(x12))\nprintln(\"x21 \", value(x21))\nprintln(\"x22 \", value(x22))\nprintln(\"x31\", value(x31))\nprintln(\"x32 \", value(x32))", "meta": {"hexsha": "4afe91626231bc2f77051e3cf23c7bd5dad3d1a8", "size": 735, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week3/example_1.jl", "max_stars_repo_name": "InzamamRahaman/COMP6925-2021", "max_stars_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-23T23:33:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T01:47:28.000Z", "max_issues_repo_path": "week3/example_1.jl", "max_issues_repo_name": "InzamamRahaman/COMP6925-2021", "max_issues_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week3/example_1.jl", "max_forks_repo_name": "InzamamRahaman/COMP6925-2021", "max_forks_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2692307692, "max_line_length": 69, "alphanum_fraction": 0.6571428571, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517488441415, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7996301505988788}}
{"text": "# Unit 01 - Linear Classifiers and Generalizations\n\nfunction perceptron(set, T=1000)\n    n = length(set); d = length(set[1][1])\n    θ = zeros(d); θ₀ = 0;\n    for t in 1:T\n        ϵ = 0\n        for i in 1:n\n            x = set[i][1]; y = set[i][2]\n            if (y*(θ' * x + θ₀) <= 0)\n                θ  = θ + y * x\n                θ₀ = θ₀ + y\n                ϵ += 1\n            end\n        end\n        if (ϵ == 0)\n            return (θ,θ₀,ϵ,t)\n        end\n    end\n    return (θ,θ₀,ϵ,T)\nend\n\nT = 5000\nset = [([7,8],-1),([4,2],-1),([2,7],1),([3,-2],1),([-3,-2],1)]\n(θ,θ₀,ϵ,t) = perceptron(set,T)\n\nusing Plots, LinearAlgebra\n\nθₙ = θ/norm(θ)\nθ₀ₙ = θ₀/norm(θ) *  θₙ\nx⁺ = vcat([([tuple[1][1] tuple[1][2]])  for tuple in set if tuple[2] == 1]...)\nx⁻ = vcat([([tuple[1][1] tuple[1][2]])  for tuple in set if tuple[2] == -1]...)\n\nscatter(x⁺[:,1],x⁺[:,2], label=\"+1\")\nscatter!(x⁻[:,1],x⁻[:,2], label=\"-1\")\n#plot!([0,θ[1]],[0,θ[2]])\nplot!([-θ₀ₙ[1],θₙ[1]-θ₀ₙ[1]],[-θ₀ₙ[2],θₙ[2]-θ₀ₙ[2]], arrow=1., label = \"theta\" )\n\n\nset = [([3,3],1),([4,2],1),([2,7],-1),([3,-2],-1)]\n\nfunction perceptronOrigin(set, T=30)\n    println(\"*** New Lookup ***\")\n    n  = length(set); d = length(set[1][1])\n    θ  = zeros(d)\n    ϵt = 0\n    for t in 1:T\n        ϵ = 0\n        for i in 1:n\n            x = set[i][1]; y = set[i][2]\n            error = false\n            θpre = θ\n            if (y*(θ' * x) <= 0)\n                θ  = θ + y * x\n                ϵ += 1; error = true; ϵt += 1\n            end\n            println(\"θpre: $θpre x: $x y: $y error: $error θpost=$θ\")\n        end\n        if (ϵ == 0)\n            return (θ,ϵ,t, ϵt)\n        end\n    end\n    return (θ,ϵ,T,ϵt)\nend\n\nset = [([-1,-1],1),([1,0],-1),([-1,1.5],1)]\nperceptronOrigin(set)\n\nset = [([1,0],-1),([-1,1.5],1),([-1,-1],1)]\nperceptronOrigin(set)\n\nset = [([-1,-1],1),([1,0],-1),([-1,10],1)]\nperceptronOrigin(set)\n\nset = [([1,0],-1),([-1,10],1),([-1,-1],1)]\nperceptronOrigin(set)\n\nfunction perceptronFull(set; T=30, θ = zeros(length(set[1])), θ₀ = 0)\n    println(\"*** New Classifier Lookup ***\")\n    println(\"Data: $set\")\n    println(\"Parameters: T = $T, θ=$θ, θ₀=$θ₀\")\n    n = length(set); d = length(set[1][1])\n    for t in 1:T\n        ϵ = 0\n        for i in 1:n\n            x = set[i][1]; y = set[i][2]\n            error = false\n            θpre = θ\n            θ₀pre = θ₀\n            if (y*(θ' * x + θ₀) <= 0)\n                θ  = θ + y * x\n                θ₀ = θ₀ + y\n                ϵ += 1\n                error = true\n            end\n            println(\"θpre: $θpre θ₀pre: $θ₀pre x: $x y: $y error: $error θpost=$θ θ₀post=$θ₀\")\n        end\n        if (ϵ == 0)\n            return (θ,θ₀,ϵ,T)\n        end\n    end\n    return (θ,θ₀,ϵ,T)\nend\n\nset = [([-4,2],1),([-2,1],1),([-1,-1],-1),([2,2],-1),([1,-2],-1)]\n(θ,θ₀,ϵ,T) = perceptronFull(set)\n\n## Homework 1\n\n### Tab 2\n\nscatter([-1,1],[1,-1],label=\"positive\")\nscatter!([1,2],[1,2],label=\"negative\")\n\n\n\n## Homework 2\n\n### Tab 1\n\nλ = 0.5\nx = [1,0]\ny = 1\n\nθ =\nloss(θ,y=1,x=[1,0],λ=0.5) = max(0,1-y*(θ' * x)) + λ/2 * norm(θ)^2\n\nloss([0,0])\nloss([1,0])\nloss([0.5,0])\nloss([-1,0])\nloss([1,-1])\n\nmax(0,1-1*([1,0]' * [1,0]))\nmax(0,1-1*([0.5,0]' * [1,0]))\n\nnorm()\n\n### Tab 3\n\ncos(0)\ncos(π)\ncos(2*π)\ncos(3*π)\ncos(4*π)\n\nfunction setFactory(d,labels=ones(d))\n    out = Tuple{Array{Int64,1},eltype(labels)}[] # or just out=[]\n    #out = []\n    for i in 1:d\n      x = zeros(d)\n      x[i] = cos(i*π)\n      push!(out,(x,labels[i]))\n    end\n    return out\nend\n\nset = setFactory(20)\nusing Random\nshuffle!(set)\n(θ,ϵ,t,ϵt) = perceptronOrigin(set,400)\n\nrandLabel = rand(20)\nset = setFactory(20,randLabel)\n(θ,ϵ,t,ϵt) = perceptronOrigin(set,400)\nshuffle!(set)\n(θ,ϵ,t,ϵt) = perceptronOrigin(set,400)\n\nrandLabel = rand(3)\nset = setFactory(3,randLabel)\n(θ,ϵ,t,ϵt) = perceptronOrigin(set,400)\n\nset = setFactory(3)\n(θ,ϵ,t,ϵt) = perceptronOrigin(set,400)\n\nset=setFactory(2)\n(θ,ϵ,t,ϵt) = perceptronOrigin(set,400)\n", "meta": {"hexsha": "ed7ad64314e636d0c476fa23f35f4da7f9fef00e", "size": 3868, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Unit 01 - Linear Classifiers and Generalizations/Unit 01 - Linear Classifiers and Generalizations.jl", "max_stars_repo_name": "fanyak/MITx_6.86x", "max_stars_repo_head_hexsha": "f6370c3c7f505644b242aa74531c645ece09d6ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-27T06:22:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T06:22:38.000Z", "max_issues_repo_path": "Unit 01 - Linear Classifiers and Generalizations/Unit 01 - Linear Classifiers and Generalizations.jl", "max_issues_repo_name": "fanyak/MITx_6.86x", "max_issues_repo_head_hexsha": "f6370c3c7f505644b242aa74531c645ece09d6ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Unit 01 - Linear Classifiers and Generalizations/Unit 01 - Linear Classifiers and Generalizations.jl", "max_forks_repo_name": "fanyak/MITx_6.86x", "max_forks_repo_head_hexsha": "f6370c3c7f505644b242aa74531c645ece09d6ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7303370787, "max_line_length": 94, "alphanum_fraction": 0.462254395, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8705972768020107, "lm_q1q2_score": 0.7996263992448559}}
{"text": "function _nancov(x::AbstractVector, y::AbstractVector, corrected::Bool, μᵪ::Number, μᵧ::Number)\n    # Calculate covariance\n    σᵪᵧ = ∅ = zero(promote_type(typeof(μᵪ), typeof(μᵧ), Int))\n    n = 0\n    @turbo for i ∈ indices((x,y))\n            δᵪ = x[i] - μᵪ\n            δᵧ = y[i] - μᵧ\n            δ² = δᵪ * δᵧ\n            notnan = δ²==δ²\n            n += notnan\n            σᵪᵧ += ifelse(notnan, δ², ∅)\n    end\n    σᵪᵧ = σᵪᵧ / (n-corrected)\n    return σᵪᵧ\nend\n\n\n\"\"\"\n```julia\nnancov(x::AbstractVector, y::AbstractVector; corrected::Bool=true)\n```\nCompute the covariance between the vectors `x` and `y`.\nAs `Statistics.cov`, but ignoring `NaN`s.\n\nIf `corrected` is `true` as is the default, _Bessel's correction_ will be applied,\nsuch that the sum is scaled by `n-1` rather than `n`, where `n = length(x)`.\n\"\"\"\nfunction nancov(x::AbstractVector, y::AbstractVector; corrected::Bool=true)\n    # Check lengths\n    nᵪ = length(x)\n    nᵧ = length(y)\n    @assert nᵪ == nᵧ\n\n    μᵪ = _nanmean(x,:)\n    μᵧ = _nanmean(y,:)\n    σᵪᵧ = _nancov(x, y, corrected, μᵪ, μᵧ)\n    return σᵪᵧ\nend\n\n\"\"\"\n```julia\nnancov(X::AbstractMatrix; dims::Int=1, corrected::Bool=true)\n```\nCompute the covariance matrix of the matrix `X`, along dimension `dims`.\nAs `Statistics.cov`, but ignoring `NaN`s.\n\nIf `corrected` is `true` as is the default, _Bessel's correction_ will be applied,\nsuch that the sum is scaled by `n-1` rather than `n`, where `n = length(x)`.\n\"\"\"\nfunction nancov(X::AbstractMatrix; dims::Int=1, corrected::Bool=true)\n    Tₒ = Base.promote_op(/, eltype(X), Int)\n    n = size(X, dims)\n    m = size(X, mod(dims,2)+1)\n    Σ = similar(X, Tₒ, (m, m))\n    # Only two dimensions are possible, so handle each manually\n    if dims == 1\n        # Precalculate means for each column\n        μ = ntuple(m) do d\n            nanmean(view(X,:,d))\n        end\n        # Fill covariance matrix symmetrically\n        @inbounds for i = 1:m\n            for j = 1:i\n                σᵢⱼ = _nancov(view(X,:,i), view(X,:,j), corrected, μ[i], μ[j])\n                Σ[i,j] = Σ[j,i] = σᵢⱼ\n            end\n        end\n    elseif dims == 2\n        # Precalculate means for each row\n        μ = ntuple(m) do d\n            nanmean(view(X,d,:))\n        end\n        # Fill covariance matrix symmetrically\n        @inbounds for i = 1:m\n            for j = 1:i\n                σᵢⱼ = _nancov(view(X,i,:), view(X,j,:), corrected, μ[i], μ[j])\n                Σ[i,j] = Σ[j,i] = σᵢⱼ\n            end\n        end\n    else\n        throw(\"Dimension not in range\")\n    end\n    return Σ\nend\nexport nancov\n\n\n\n\"\"\"\n```julia\nnancor(x::AbstractVector, y::AbstractVector)\n```\nCompute the (Pearson's product-moment) correlation between the vectors `x` and `y`.\nAs `Statistics.cor`, but ignoring `NaN`s.\n\nEquivalent to `nancov(x,y) / (nanstd(x) * nanstd(y))`.\n\"\"\"\nfunction nancor(x::AbstractVector, y::AbstractVector; corrected::Bool=true)\n    # Check lengths\n    nᵪ = length(x)\n    nᵧ = length(y)\n    @assert nᵪ == nᵧ\n\n    μᵪ = nanmean(x)\n    μᵧ = nanmean(y)\n    σᵪ = nanstd(x, mean=μᵪ, corrected=corrected)\n    σᵧ = nanstd(y, mean=μᵧ, corrected=corrected)\n    σᵪᵧ = _nancov(x, y, corrected, μᵪ, μᵧ)\n    ρᵪᵧ = σᵪᵧ / (σᵪ * σᵧ)\n\n    return ρᵪᵧ\nend\n\n\n\"\"\"\n```julia\nnancor(X::AbstractMatrix; dims::Int=1)\n```\nCompute the (Pearson's product-moment) correlation matrix of the matrix `X`,\nalong dimension `dims`. As `Statistics.cor`, but ignoring `NaN`s.\n\"\"\"\nfunction nancor(X::AbstractMatrix; dims::Int=1, corrected::Bool=true)\n    Tₒ = Base.promote_op(/, eltype(X), Int)\n    n = size(X, dims)\n    m = size(X, mod(dims,2)+1)\n    Ρ = similar(X, Tₒ, (m, m))\n    # Diagonal must be unity\n    @inbounds for i = 1:m\n        Ρ[i,i] = one(Tₒ)\n    end\n    # Only two dimensions are possible, so handle each manually\n    if dims == 1\n        # Precalculate means and standard deviations\n        μ = ntuple(m) do d\n            nanmean(view(X,:,d))\n        end\n        σ = ntuple(m) do d\n            nanstd(view(X,:,d), mean=μ[d], corrected=corrected)\n        end\n        # Fill off-diagonals symmetrically\n        @inbounds for i = 1:m\n            for j = 1:i\n                σᵢⱼ = _nancov(view(X,:,i), view(X,:,j), corrected, μ[i], μ[j])\n                Ρ[i,j] = Ρ[j,i] = σᵢⱼ / (σ[i] * σ[j])\n            end\n        end\n    elseif dims == 2\n        # Precalculate means and standard deviations\n        μ = ntuple(m) do d\n            nanmean(view(X,d,:))\n        end\n        σ = ntuple(m) do d\n            nanstd(view(X,d,:), mean=μ[d], corrected=corrected)\n        end\n        @inbounds for i = 1:m\n            for j = 1:i-1\n                σᵢⱼ = _nancov(view(X,i,:), view(X,j,:), corrected, μ[i], μ[j])\n                Ρ[i,j] = Ρ[j,i] = σᵢⱼ / (σ[i] * σ[j])\n            end\n        end\n    else\n        throw(\"Dimension not in range\")\n    end\n    return Ρ\nend\nexport nancor\n", "meta": {"hexsha": "2b76d4d35a136d8f6fe47380b0eb4157fa3631a1", "size": 4787, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ArrayStats/nancov.jl", "max_stars_repo_name": "brenhinkeller/NaNStatistics.jl", "max_stars_repo_head_hexsha": "941efe2be271ab086fcd63ec6ba9714e4ad7ddd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-05-15T03:30:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T09:44:56.000Z", "max_issues_repo_path": "src/ArrayStats/nancov.jl", "max_issues_repo_name": "brenhinkeller/NaNStatistics.jl", "max_issues_repo_head_hexsha": "941efe2be271ab086fcd63ec6ba9714e4ad7ddd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-05-16T05:48:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T21:16:34.000Z", "max_forks_repo_path": "src/ArrayStats/nancov.jl", "max_forks_repo_name": "brenhinkeller/NaNStatistics.jl", "max_forks_repo_head_hexsha": "941efe2be271ab086fcd63ec6ba9714e4ad7ddd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6646706587, "max_line_length": 95, "alphanum_fraction": 0.5588050971, "num_tokens": 1668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.870597270087091, "lm_q1q2_score": 0.7996263950200097}}
{"text": "using Optim\nusing GR\nusing Plots\n\ngr()\n\nf(x) =  (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2\n\nstart = [-5.0,4.0]\niter = 80\n\nGD_res = optimize(f, start, GradientDescent(),\n               Optim.Options(g_tol = 1e-40,\n                             iterations = iter,\n                             store_trace = true,\n                             extended_trace = true,\n                             show_trace = false))\n\nCGD_res = optimize(f, start, ConjugateGradient(),\n               Optim.Options(g_tol = 1e-40,\n                             iterations = iter,\n                             store_trace = true,\n                             extended_trace = true,\n                             show_trace = false))\n\nSA_res = optimize(f, start, SimulatedAnnealing(),\n               Optim.Options(g_tol = 1e-40,\n                             iterations = iter,\n                             store_trace = true,\n                             extended_trace = true,\n                             show_trace = false))\n\nl = iter + 1\n\nGD_trace = Array{Float64}(undef, l, 2)\nCGD_trace = Array{Float64}(undef, l, 2)\nSA_trace = Array{Float64}(undef, l, 2)\n\nfor i in 1:l\n    x1 = Optim.x_trace(GD_res)[i][1]\n    x2 = Optim.x_trace(GD_res)[i][2]\n    GD_trace[i,1] = x1\n    GD_trace[i,2] = x2\nend\n\nfor i in 1:l\n    x1 = Optim.x_trace(CGD_res)[i][1]\n    x2 = Optim.x_trace(CGD_res)[i][2]\n    CGD_trace[i,1] = x1\n    CGD_trace[i,2] = x2\nend\n\nfor i in 1:l\n    x1 = Optim.x_trace(SA_res)[i][1]\n    x2 = Optim.x_trace(SA_res)[i][2]\n    SA_trace[i,1] = x1\n    SA_trace[i,2] = x2\nend\n\ncontour(-5:0.005:5,-5:0.005:5,f)\n\nplot!([GD_trace[:,1]],\n    [GD_trace[:,2]],\n    lab = \"Gradient Descent\",\n    zcolor = reverse(GD_trace, dims = 1), m = (4, 0.9, :reds, Plots.stroke(0)), \n    cbar = false, \n    w = 1.5,\n    linecolor = :red)\n\nplot!([CGD_trace[:,1]],\n    [CGD_trace[:,2]],\n    lab = \"Conjugated GD\",\n    zcolor = reverse(CGD_trace, dims = 1), m = (4, 0.9, :greens, Plots.stroke(0)), \n    cbar = false, \n    w = 1.5,\n    linecolor = :green)\n\nplot!([SA_trace[:,1]],\n    [SA_trace[:,2]],\n    lab = \"Simulated Annealing\",\n    zcolor = reverse(SA_trace, dims = 1), m = (4, 0.9, :blues, Plots.stroke(0)), \n    cbar = false, \n    w = 1.5,\n    linecolor = :blue)\n", "meta": {"hexsha": "1ec5083e9a6bf767db24c7a9fa38e48ecf8c890b", "size": 2224, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Bivariate_Function.jl", "max_stars_repo_name": "lukaskln/Optim-Visualization", "max_stars_repo_head_hexsha": "e5a0c72767ab5232158e111701c1b3e35d9bae0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Bivariate_Function.jl", "max_issues_repo_name": "lukaskln/Optim-Visualization", "max_issues_repo_head_hexsha": "e5a0c72767ab5232158e111701c1b3e35d9bae0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Bivariate_Function.jl", "max_forks_repo_name": "lukaskln/Optim-Visualization", "max_forks_repo_head_hexsha": "e5a0c72767ab5232158e111701c1b3e35d9bae0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1647058824, "max_line_length": 83, "alphanum_fraction": 0.4986510791, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.8652240721511739, "lm_q1q2_score": 0.7995897541502339}}
{"text": "# indicator of nonnegative orthant\n\n\"\"\"\n  IndNonnegative()\n\nReturns the indicator function the nonnegative orthant, that is\n\n  `g(x) = 0 if x ⩾ 0, +∞ otherwise`\n\"\"\"\n\nimmutable IndNonnegative <: IndicatorConvexCone end\n\n\nfunction (f::IndNonnegative){R <: Real}(x::AbstractArray{R})\n  for k in eachindex(x)\n    if x[k] < 0\n      return +Inf\n    end\n  end\n  return 0.0\nend\n\nfunction prox!{R <: Real}(f::IndNonnegative, x::AbstractArray{R}, y::AbstractArray{R}, gamma::Real=1.0)\n  for k in eachindex(x)\n    if x[k] < 0\n      y[k] = zero(R)\n    else\n      y[k] = x[k]\n    end\n  end\n  return 0.0\nend\n\nfun_name(f::IndNonnegative) = \"indicator of the Nonnegative cone\"\nfun_dom(f::IndNonnegative) = \"AbstractArray{Real}\"\nfun_expr(f::IndNonnegative) = \"x ↦ 0 if all(0 ⩽ x), +∞ otherwise\"\nfun_params(f::IndNonnegative) = \"none\"\n\nfunction prox_naive{R <: Real}(f::IndNonnegative, x::AbstractArray{R}, gamma::Real=1.0)\n  y = max.(zero(R), x)\n  return y, 0.0\nend\n", "meta": {"hexsha": "06b157bf61aa884a3a6108aac1a1272d7ec45a81", "size": 949, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indNonnegative.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/indNonnegative.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/indNonnegative.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0697674419, "max_line_length": 103, "alphanum_fraction": 0.6543730242, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217417, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.799589749525678}}
{"text": "# Lotka-Volterra, np = 2\r\nid = :Sahlodin2011c\r\n\r\npL = [2.98; 0.98]\r\npU = [3.02; 1.02]\r\nSahlodin2011c_x0(p::Vector{T}) where T = T[1.2*one(T); 1.1*one(T)]\r\nfunction Sahlodin2011c_f!(du::Vector{T}, u::Vector{T}, p::Vector{T}, t) where T\r\n    du[1] = p[1]*u[1]*(1.0 - u[2])\r\n    du[2] = p[2]*u[2]*(u[1] - 1.0)\r\n    return\r\nend\r\ntspan = (0.0, 2.0)\r\n\r\nprob = ODERelaxProb(Sahlodin2011c_f!, tspan, Sahlodin2011c_x0, pL, pU)\r\nurl = \"https://www.sciencedirect.com/science/article/abs/pii/S0168927411000316\"\r\nsource = \"Sahlodin2011\"\r\ndesc = \"Lotka-Volterra, np = 2\"\r\n", "meta": {"hexsha": "d73135c88c93aff7bd894956f958c01842b21899", "size": 558, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/library/pODEs/Sahlodin2011c.jl", "max_stars_repo_name": "PSORLab/DynamicBounds.jl", "max_stars_repo_head_hexsha": "a7c258e3e4297442ad425c398705f3163e953331", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-15T17:57:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-15T17:57:30.000Z", "max_issues_repo_path": "src/library/pODEs/Sahlodin2011c.jl", "max_issues_repo_name": "PSORLab/DynamicBounds.jl", "max_issues_repo_head_hexsha": "a7c258e3e4297442ad425c398705f3163e953331", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-09-15T14:31:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T03:48:15.000Z", "max_forks_repo_path": "src/library/pODEs/Sahlodin2011c.jl", "max_forks_repo_name": "PSORLab/DynamicBounds.jl", "max_forks_repo_head_hexsha": "a7c258e3e4297442ad425c398705f3163e953331", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-15T17:57:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T17:57:36.000Z", "avg_line_length": 31.0, "max_line_length": 80, "alphanum_fraction": 0.6146953405, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.8774767906859264, "lm_q1q2_score": 0.7995390540285676}}
{"text": "\"\"\"\n    NeuralNetworkKernel()\n\nNeural network kernel function.\n\n```math\n    κ(x, y) =  asin(x' * y / sqrt[(1 + x' * x) * (1 + y' * y)])\n```\n# Significance\nNeal (1996) pursued the limits of large models, and showed that a Bayesian neural network\nbecomes a Gaussian process with a **neural network kernel** as the number of units\napproaches infinity. Here, we give the neural network kernel for single hidden layer\nBayesian neural network with erf (Error Function) as activation function.\n\n# References:\n- [GPML Pg 105](http://www.gaussianprocess.org/gpml/chapters/RW4.pdf)\n- [Neal(1996)](https://www.cs.toronto.edu/~radford/bnn.book.html)\n- [Andrew Gordon's Thesis Pg 45](http://www.cs.cmu.edu/~andrewgw/andrewgwthesis.pdf)\n\"\"\"\nstruct NeuralNetworkKernel <: BaseKernel end\n\nfunction (κ::NeuralNetworkKernel)(x, y)\n    return asin(dot(x, y) / sqrt((1 + sum(abs2, x)) * (1 + sum(abs2, y))))\nend\n\nBase.show(io::IO, κ::NeuralNetworkKernel) = print(io, \"Neural Network Kernel\")\n", "meta": {"hexsha": "b0e589e3b23ec6e0a0a026ad8703b0d8aa9511ac", "size": 972, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basekernels/nn.jl", "max_stars_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_stars_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basekernels/nn.jl", "max_issues_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_issues_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basekernels/nn.jl", "max_forks_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_forks_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0, "max_line_length": 89, "alphanum_fraction": 0.7057613169, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259038, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7995057118046911}}
{"text": "import Base: isequal, ==, show, *, length, >\nusing SymPy\n\n\"A plane geometric object.\"\nabstract type GeoObject end\nabstract type GeoShape <: GeoObject end\n\nshow(io::IO, objs::Vector{T}) where T <: GeoObject = print(io, \"[\", join(objs, \", \"), \"]\")\n\n\"\"\"\n    Point(x, y)\n    \nA point at coordinate `(x, y)`.\n\n# Examples\n```julia\nA = Point(0,0); B = Point(1, 3); C = Point(4,2)\n```\n\"\"\"\nstruct Point <: GeoObject\n    \"x cooridnate\"\n    x::Sym\n    \"y cooridnate\"\n    y::Sym\n\n    Point(x, y) = new(Sym(x), Sym(y))\nend\n\n\"\"\"\n# Function\n\n    Point()\n    \nA point at coordinate `(0, 0)`.\n\"\"\"\nPoint() = Point(0, 0)\n\n\"Check if two points are at the same coordinate.\"\n(==)(p1::Point, p2::Point) = p1.x==p2.x && p1.y==p2.y\n\nshow(io::IO, pt::Point) = print(io, \"Point($(pt.x), $(pt.y))\")\n\n\"\"\"\n    Triangle(A, B, C) \n\nA triangle with vertices `A, B, C`.\n\n# Examples\n```julia\nA = Point(0,0); B = Point(1, 3); C = Point(4,2)\ntri = Triangle(A, B, C)\n```\n\"\"\"\nstruct Triangle <: GeoShape\n    \"Vertex A\"\n    A::Point\n    \"Vertex B\"\n    B::Point\n    \"Vertex C\"\n    C::Point\nend\nshow(io::IO, tri::Triangle) = print(io, \"Triangle($(tri.A), $(tri.B), $(tri.C))\")\n\n\n\"\"\"\n# Function\n\n    Triangle()\n    \nA triangle with vertices `(0, 0), (0, 1), (1,1)`.\n\"\"\"\nTriangle() = Triangle(Point(0, 0), Point(0, 1), Point(1,1))\n\n\"\"\"\n    Triangle(ax, ay, bx, by, cx, cy)    \n\nA triangle with vertices `(ax, ay), (bx, by), (cx, cy)`.\n\n# Examples\n```julia\ntri = Triangle(0, 0, 1, 3, 4, 2)\n```\n\"\"\"\nTriangle(ax, ay, bx, by, cx, cy) = Triangle(Point(ax, ay), Point(bx, by), Point(cx, cy))\n\n\"Check if two triangles are the same.\"\n(==)(t1::Triangle, t2::Triangle) = vertices(t1) == vertices(t2)\n\n\"Get the list of vertices of the triangle `tri`.\"\nfunction vertices(tri::Triangle) \n    [tri.A, tri.B, tri.C]\nend\n\n\"\"\"\n    Edge(src, dst) \n\nAn edge from point `src` to point `dst`.\n\n# Examples\n```julia\ne = Edge(Point(0, 0), Point(1, 3))\n```\n\"\"\"\nstruct Edge <: GeoShape\n    \"Starting point of an edge.\"\n    src::Point\n    \"Ending point of an edge.\"\n    dst::Point\nend\n\n\"Check if two edges are at the same.\"\n(==)(e1::Edge, e2::Edge) = e1.src==e2.src && e1.dst==e2.dst\n\n\"Get the list of edges of the triangle `tri`.\"\nfunction edges(tri::Triangle)\n    elist = Edge[]\n    pts = vertices(tri)\n    for i in 1:length(pts)-1\n        push!(elist, Edge(pts[i], pts[i+1]))\n    end\n    push!(elist, Edge(pts[length(pts)], pts[1]))\n    elist\nend\n\n\"Mulitpliy the lengths of two edges.\"\n(*)(e1::Edge, e2::Edge) = length(e1) * length(e2)\n\n\"Mulitpliy a number and an edges length.\"\n(*)(s1::Sym, e2::Edge) = s1 * length(e2)\n\n\"Compare lengths of two edges.\"\n(>)(e1::Edge, e2::Edge) = length(e1) > length(e2)\n\n\"Find the length of an edge.\"\nlength(e::Edge) = distance(e.src, e.dst)\n\n\"\"\"\n    Circle(c, r) \n    \nA circle with center at `c` and radius `r`.\n\n# Examples\n```julia\ncircle = Circle(Point(0, 0), 1)\n```\n\"\"\"\nstruct Circle <: GeoShape\n    center::Point\n    radius::Number\nend\nshow(io::IO, c::Circle) = print(io, \"Circle($(c.center), $(c.radius))\")\n\n\"Check if two circles are the same.\"\n(==)(c1::Circle, c2::Circle) = c1.center == c2.center && c1.radius == c2.radius\n\n\"Get the center of a a circle.\"\ncenter(c::Circle) = c.center\n", "meta": {"hexsha": "be948a5e4b81f469fe0632cc6e8ae7698297b1a8", "size": 3159, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/elementary.jl", "max_stars_repo_name": "newptcai/PlaneGeometry.jl", "max_stars_repo_head_hexsha": "fe2644fdf824a364daa1ce362bf5557d40775226", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-05-12T04:22:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:20:31.000Z", "max_issues_repo_path": "src/elementary.jl", "max_issues_repo_name": "newptcai/PlaneGeometry.jl", "max_issues_repo_head_hexsha": "fe2644fdf824a364daa1ce362bf5557d40775226", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/elementary.jl", "max_forks_repo_name": "newptcai/PlaneGeometry.jl", "max_forks_repo_head_hexsha": "fe2644fdf824a364daa1ce362bf5557d40775226", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9936708861, "max_line_length": 90, "alphanum_fraction": 0.5862614752, "num_tokens": 1075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8539127585282745, "lm_q1q2_score": 0.7995057074725297}}
{"text": "# Functions related to sterographic projection to/from a three-dimensional\n# unit sphere centered at (0,0) = 0+0im\n\n# function stereo(z::Number)::Vector{Float64}\n#     if isinf(z)\n#         return [0, 0, 1]\n#     end\n\n#     X, Y = reim(z)\n\n#     x = 2X\n#     y = 2Y\n#     z = X^2 + Y^2 - 1\n\n#     d = 1 / (1 + X^2 + Y^2)\n\n#     return d * [x, y, z]\n# end\n\n\n\"\"\"\n    stereo \nStereographic projection between the complex plane and a three-dimensional unit sphere \ncentered at `[0,0,0]`. The north pole, `[0,0,1]`, corresponds to complex infinity and the \nsouth pole, `[0,0,-1]`, corresponds to `0+0im`.\n\nFor a complex number `z`, `stereo(z)` maps `z` to the sphere. This may also be invoked as \n`stereo(x,y)`.\n\nFor a (unit) three-dimensional vector `v`, `stereo(v)` returns the complex number by projecting \n`v` to the complex plane. This may also be invoked as `stereo(x,y,z)`.\n\"\"\"\nfunction stereo(X::Real, Y::Real)::Vector{Float64}\n    if isinf(X) || isinf(Y)\n        return [0, 0, 1]\n    end\n\n    x = 2X\n    y = 2Y\n    z = X^2 + Y^2 - 1\n\n    d = 1 / (1 + X^2 + Y^2)\n\n    return d * [x, y, z]\nend\n\n\nstereo(z::Number) = stereo(reim(z)...)\n\n\nfunction stereo(x::Real, y::Real, z::Real)::Complex\n    if z == 1\n        return Inf + im * Inf\n    end\n    X = x / (1 - z)\n    Y = y / (1 - z)\n    return X + im * Y\nend\n\n\nfunction stereo(v::Vector{T})::Complex where {T<:Real}\n    stereo(v...)\nend\n\n\n\"\"\"\n    LFTQ\nCreate a linear fractional transformation from a 3-by-3 unitary matrix. \n\nGiven a 3-by-3 real matrix `Q` with `Q*Q'` equal to the identity and `det(Q)` equal to `1`,\ncreate a `LFT` that maps a complex number `v` to\n`stereo(Q*stereo(v))`.\n\"\"\"\nfunction LFTQ(Q::AbstractMatrix)::LFT\n    Q = Matrix(Q)\n    zz = [0 + 0im, 1 + 0im, 0 + im]\n\n    uu = stereo.(zz)\n    uu = [Q * u for u in uu]\n\n    ww = [stereo(u) for u in uu]\n\n    LFT(zz[1], ww[1], zz[2], ww[2], zz[3], ww[3])\n\nend\n\nexport stereo, LFTQ\n", "meta": {"hexsha": "39e740da97874b50ad739712df40aa0588f350a0", "size": 1898, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/projection.jl", "max_stars_repo_name": "scheinerman/LinearFractionalTransformations.jl", "max_stars_repo_head_hexsha": "01181b1d0adaaf20fdd56865c04cc1eb29c63c0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/projection.jl", "max_issues_repo_name": "scheinerman/LinearFractionalTransformations.jl", "max_issues_repo_head_hexsha": "01181b1d0adaaf20fdd56865c04cc1eb29c63c0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/projection.jl", "max_forks_repo_name": "scheinerman/LinearFractionalTransformations.jl", "max_forks_repo_head_hexsha": "01181b1d0adaaf20fdd56865c04cc1eb29c63c0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5681818182, "max_line_length": 96, "alphanum_fraction": 0.5769230769, "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362849986365572, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7995057059543842}}
{"text": "# Simulate n random numbers generated as follows: half of the random\n# numbers are drawn from the standard univariate normal, and half of\n# the random numbers are drawn from a univariate normal with zero mean\n# and a standard deviation of 3. The return value is a vector of\n# floats of length n.\nfunction normdatasim(n::Int)\n\n  # Check input \"n\".\n  if n <= 0\n    throw(ArgumentError(\"Argument \\\"n\\\" should be positive\"))\n  end\n\n  # Generate the random numbers.\n  n1 = round(Int,0.5*n);\n  n2 = round(Int,0.2*n);\n  n3 = n - n1 - n2;\n  return vcat(randn(n1),4*randn(n2),6*randn(n3))\nend\n\n# Simulate n random numbers generated as follows: 50% of the random\n# numbers are drawn from the standard univariate normal; 20% are\n# drawn from a t distribution with 4 degrees of freedom; and the\n# remaining 30% are drawn from a t distribution with 6 degrees of\n# freedom. The return value is a vector of floats of length n.\nfunction normtmixdatasim(n::Int)\n  \n  # Check input \"n\".\n  if n <= 0\n    throw(ArgumentError(\"Argument \\\"n\\\" should be positive\"))\n  end\n\n  # Generate the random numbers.\n  n1 = round(Int,0.5*n);\n  n2 = round(Int,0.2*n);\n  n3 = n - n1 - n2;\n  return vcat(randn(n1),rand(TDist(4),n2),rand(TDist(6),n3))\nend\n", "meta": {"hexsha": "4841e9fb1a090caaae10af1fc87602628eeef83a", "size": 1218, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code/datasim.jl", "max_stars_repo_name": "stephenslab/mixsqp-paper", "max_stars_repo_head_hexsha": "577bb530064dda89e832c90cdf2546fd21bc9934", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-07-13T07:12:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-10T07:34:02.000Z", "max_issues_repo_path": "code/datasim.jl", "max_issues_repo_name": "stephenslab/mixsqp-paper", "max_issues_repo_head_hexsha": "577bb530064dda89e832c90cdf2546fd21bc9934", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-09T16:17:15.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-09T17:33:57.000Z", "max_forks_repo_path": "code/datasim.jl", "max_forks_repo_name": "stephenslab/mixsqp-paper", "max_forks_repo_head_hexsha": "577bb530064dda89e832c90cdf2546fd21bc9934", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-10T07:34:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-10T07:34:07.000Z", "avg_line_length": 32.0526315789, "max_line_length": 70, "alphanum_fraction": 0.697044335, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810421953309, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7994902199019286}}
{"text": "\nusing DifferentialEquations\nusing SimpleDiffEq\nusing DiffEqCallbacks\nusing Random\nusing Distributions\nusing Plots\n\n\nfunction sir_ode!(du,u,p,t)\n    (S,I,R,C) = u\n    (β,c,γ) = p\n    N = S+I+R\n    infection = β*c*I/N*S\n    recovery = γ*I\n    @inbounds begin\n        du[1] = -infection\n        du[2] = infection - recovery\n        du[3] = recovery\n        du[4] = infection\n    end\n    nothing\nend;\n\n\ntmax = 40.0\nδt = 1.0\ntspan = (0.0,tmax)\nobstimes = 1.0:δt:tmax;\nu0 = [990.0,10.0,0.0,0.0]; # S,I.R,C\np = [0.05,10.0,0.25]; # β,c,γ\n\n\nprob_ode = ODEProblem(sir_ode!,u0,tspan,p)\nsol_ode_cumulative = solve(prob_ode,Tsit5(),saveat=δt);\n\n\nout = Array(sol_ode_cumulative)\nC = out[4,:];\n\n\nX = C[2:end] .- C[1:(end-1)];\n\n\nRandom.seed!(1234);\n\n\nY = rand.(Poisson.(X));\n\n\nbar(obstimes,Y)\nplot!(obstimes,X)\n\n\nS = out[1,:]\nCpred = 990.0 .- S\nCdiff = Cpred .- C\nplot(obstimes,Cdiff[2:end])\n\n\naffect!(integrator) = integrator.u[4] = 0.0\ncb_zero = PresetTimeCallback(obstimes,affect!);\n\n\nsol_ode_cb = solve(prob_ode,Tsit5(),saveat=δt,callback=cb_zero);\n\n\nX_cb = sol_ode_cb(obstimes)[4,:];\n\n\nRandom.seed!(1234);\n\n\nY_cb = rand.(Poisson.(X_cb));\n\n\nX_diff_cb = X_cb .- X\nplot(obstimes,X_diff_cb)\n\n\nY_diff_cb = Y_cb .- Y\nplot(obstimes,Y_diff_cb)\n\n\nfunction sir_dde!(du,u,h,p,t)\n    (S,I,R,C) = u\n    (β,c,γ) = p\n    N = S+I+R\n    infection = β*c*I/N*S\n    recovery = γ*I\n    e = oneunit(t)\n    history = h(p, t-e)*inv(e)\n    @inbounds begin\n        du[1] = -infection\n        du[2] = infection - recovery\n        du[3] = recovery\n        du[4] = infection - history[4]\n    end\n    nothing\nend;\n\n\nfunction sir_history(p, t; idxs = 5)\n    zero(t)\nend;\n\n\nprob_dde = DDEProblem(DDEFunction(sir_dde!),\n        u0,\n        sir_history,\n        tspan,\n        p;\n        constant_lags = [1.0]);\n\n\nsol_dde = solve(prob_dde,MethodOfSteps(Tsit5()));\n\n\nX_dde = sol_dde(obstimes)[4,:];\n\n\nRandom.seed!(1234)\nY_dde = rand.(Poisson.(X_dde));\n\n\nX_diff_dde = X_dde .- X\nplot(X_diff_dde)\n\n\nY_diff_dde = Y_dde .- Y\nplot(obstimes, Y_diff_dde)\n\n", "meta": {"hexsha": "3f85941e6b21de716d63fb0aab2154df403594a1", "size": 2004, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_simdata/ode_simdata.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 126, "max_stars_repo_stars_event_min_datetime": "2020-04-29T08:41:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:42:53.000Z", "max_issues_repo_path": "script/ode_simdata/ode_simdata.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2020-04-29T11:44:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:45:15.000Z", "max_forks_repo_path": "script/ode_simdata/ode_simdata.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2020-04-29T08:01:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T16:55:08.000Z", "avg_line_length": 15.0676691729, "max_line_length": 64, "alphanum_fraction": 0.6037924152, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538936, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7994111317609237}}
{"text": "# bayesian inference for gauss-gamma distribution\n\nmodule GaussGamma\n  using DataFrames, CSV, Plots, FreqTables, NamedArrays, Distributions\n  using StatsBase, Statistics\n  pyplot()\n\n  function main(;test=false)\n    # step1: generate prior distribution\n    # initial parameters\n    mu_0 = 200\n    zeta_0 = 1\n    alpha_0 = 1\n    beta_0 = 2\n    # prior gamma distribution of lambda\n    lambda_dist = gen_lambda_dist(alpha_0, beta_0)\n    draw_dist_pdf(lambda_dist, 0, 5, 0.01,\n                  \"src/bayesian_inference/prior_lambda_dist.png\",\n                  test)\n    # prior normal distribution of mu\n    lambda = rand(lambda_dist)\n    mu_dist = gen_mu_dist(mu_0, zeta_0, lambda)\n    draw_dist_pdf(mu_dist, 180, 220, 0.1,\n                  \"src/bayesian_inference/prior_mu_dist.png\",\n                  test)\n    \n    # step2: calculate posterior distribution with not many observation\n    data_path = joinpath(split(@__FILE__, \"src\")[1], \"data/sensor_data_200.txt\")\n    df_200_mm = CSV.read(data_path, DataFrame, \n                         header=[\"date\", \"time\", \"ir\", \"lidar\"],\n                         delim=' ')\n    lidar = df_200_mm.lidar\n    samples = sample(lidar, 5)\n    println(\"Samples(N=5): $(samples)\")\n    println(\"Mean(N=5): $(sum(samples)/length(samples))\")\n    println(\"Std dev(N=5): $(Statistics.std(samples, corrected=false))\")\n    # calculate parameters\n    N = length(samples)\n    mu_N = 1.0/(N+beta_0)*sum(samples) + beta_0/(N+beta_0)*mu_0\n    zeta_N = N + zeta_0\n    alpha_N = N/2 + alpha_0\n    beta_N = 0.5*(sum([z^2 for z in samples]) + zeta_0*(mu_0^2) - zeta_N*(mu_N^2)) + beta_0\n    println(\"$(mu_N) $(zeta_N) $(alpha_N) $(beta_N)\")\n    # posterior gamma distribution of lambda\n    lambda_dist = gen_lambda_dist(alpha_N, beta_N)\n    draw_dist_pdf(lambda_dist, 0, 5, 0.01,\n                  \"src/bayesian_inference/posterior_lambda_dist_N5.png\",\n                  test)\n    draw_dist_pdf(lambda_dist, 0, 0.01, 0.00001,\n                  \"src/bayesian_inference/posterior_lambda_dist_N5_zoom.png\",\n                  test)\n    # posterior normal distribution of mu\n    lambda = rand(lambda_dist)\n    mu_dist = gen_mu_dist(mu_N, zeta_N, lambda)\n    draw_dist_pdf(mu_dist, 180, 220, 0.1,\n                  \"src/bayesian_inference/posterior_mu_dist_N5.png\",\n                  test)\n    println(\"Mean(N=5): $(mu_dist.μ)\")\n    println(\"Std dev(N=5): $(sqrt(1/lambda))\")\n\n    # step3: calculate posterior distribution with a lot of observation\n    samples = lidar # all data\n    println(\"Samples(all): $(samples)\")\n    println(\"Mean(all): $(sum(samples)/length(samples))\")\n    println(\"Std dev(all): $(Statistics.std(samples, corrected=false))\")\n    # calculate parameters\n    N = length(samples)\n    mu_N = 1.0/(N+beta_0)*sum(samples) + beta_0/(N+beta_0)*mu_0\n    zeta_N = N + zeta_0\n    alpha_N = N/2 + alpha_0\n    beta_N = 0.5*(sum([z^2 for z in samples]) + zeta_0*(mu_0^2) - zeta_N*(mu_N^2)) + beta_0\n    println(\"$(mu_N) $(zeta_N) $(alpha_N) $(beta_N)\")\n    # posterior gamma distribution of lambda\n    lambda_dist = gen_lambda_dist(alpha_N, beta_N)\n    draw_dist_pdf(lambda_dist, 0, 5, 0.01,\n                  \"src/bayesian_inference/posterior_lambda_dist_all.png\",\n                  test)\n    draw_dist_pdf(lambda_dist, 0.035, 0.05, 0.0001,\n                  \"src/bayesian_inference/posterior_lambda_dist_all_zoom.png\",\n                  test)\n    # posterior normal distribution of mu\n    lambda = rand(lambda_dist)\n    mu_dist = gen_mu_dist(mu_N, zeta_N, lambda)\n    draw_dist_pdf(mu_dist, 180, 220, 0.1,\n                  \"src/bayesian_inference/posterior_mu_dist_all.png\",\n                  test)\n    println(\"Mean(all): $(mu_dist.μ)\")\n    println(\"Std dev(all): $(sqrt(1/lambda))\")\n    # compare with histogram\n    # draw histogram\n    bin_min_max = maximum(df_200_mm.lidar) - minimum(df_200_mm.lidar)\n    histogram(df_200_mm.lidar, bins=bin_min_max, color=:orange, \n              label=\"histogram\")\n    if test == false\n      save_path = joinpath(split(@__FILE__, \"src\")[1], \"src/bayesian_inference/lidar_200mm_histogram.png\")\n      savefig(save_path)\n    end\n    # calculated distribution\n    z_dist = Normal(mu_dist.μ, sqrt(1/(lambda)))\n    xs = range(190, 230, length=Int64(floor(40/0.1)))\n    ys = [pdf(z_dist, x) for x in xs]\n    plot(xs, ys, label=\"PDF\", color=:blue)\n    if test == false\n      save_path = joinpath(split(@__FILE__, \"src\")[1], \"src/bayesian_inference/lidar_200mm_calc_dist.png\")\n      savefig(save_path)\n    end\n  end\n\n  function gen_lambda_dist(alpha, beta)\n    return Gamma(alpha, 1/beta)\n  end\n\n  function gen_mu_dist(mu_mean, zeta, lambda)\n    return Normal(mu_mean, sqrt(1/(zeta*lambda)))\n  end\n\n  function draw_dist_pdf(dist, range_min, range_max, step, save_name, test)\n    xs = range(range_min, range_max, length=Int64(floor((range_max-range_min)/step)))\n    ys = [pdf(dist, x) for x in xs]\n    plot(xs, ys, label=\"PDF\")\n\n    if test == false\n      save_path = joinpath(split(@__FILE__, \"src\")[1], save_name)\n      savefig(save_path)\n    end\n  end\nend", "meta": {"hexsha": "ce83879980eb29d6efc34615a527376019a6c0f8", "size": 5011, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bayesian_inference/gauss_gamma.jl", "max_stars_repo_name": "ShisatoYano/JuliaAutonomy", "max_stars_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2021-03-10T12:43:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T16:40:19.000Z", "max_issues_repo_path": "src/bayesian_inference/gauss_gamma.jl", "max_issues_repo_name": "ShisatoYano/JuliaAutonomy", "max_issues_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bayesian_inference/gauss_gamma.jl", "max_forks_repo_name": "ShisatoYano/JuliaAutonomy", "max_forks_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-14T02:46:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T09:19:40.000Z", "avg_line_length": 39.4566929134, "max_line_length": 106, "alphanum_fraction": 0.637397725, "num_tokens": 1468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7994111270437664}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ ffed97e2-dc07-48bb-870a-737a115e69dc\nbegin\n\tusing Pkg\n\tcd(joinpath(dirname(@__FILE__),\"..\"))\n    Pkg.activate(pwd())\n    using NativeSVG\n\tusing Plots\n\tusing LaTeXStrings\n\tusing GeneralQP\n\tusing NLopt\nend\n\n# ╔═╡ 9f5f8730-0188-11eb-209f-e771579d35ce\nmd\"# Sequential Quadratic Programming\"\n\n# ╔═╡ c30dbe90-0188-11eb-0c2b-ed5e93a86b0b\nmd\"\"\"## Quadratic Programming\n\nAn optimization problem with a quadratic objective function and linear\nconstraints is called a _quadratic program_. Problems of this\ntype are important in their own right, and they also arise a subproblems\nin methods for general constrained optimization such as sequential\nquadratic programming (this chapter) and interior-point methods (lecture 10).\n\nThe general quadratic program can be stated as\n\n```math\n\\begin{aligned}\n\\min_{\\vec{x}}\\, & f\\left(\\vec{x}\\right)\\overset{\\vartriangle}{=}\\frac{1}{2}\\vec{x}^\\mathsf{T}Q\\vec{x}-\\vec{c}^\\mathsf{T}\\vec{x}\\\\\n\\textrm{subject to}\\, & \\begin{cases}\nA_{\\textrm{eq}}\\vec{x}=\\vec{b}_{\\textrm{eq}}\\,,\\\\\nA_{\\textrm{in}}\\vec{x}\\leq\\vec{b}_{\\textrm{in}}\\,,\n\\end{cases}\n\\end{aligned}\n```\n\nwhere $Q$ is a symmetric $n\\times n$ matrix, $\\vec{c}\\in\\mathbb R^{n}$,\n$A_{\\textrm{eq}}$ is a $m\\times n$ matrix, $\\vec{b}_{\\textrm{eq}}\\in\\mathbb R^{m}$,\n$A_{\\textrm{in}}$ is a $p\\times n$ matrix and $\\vec{b}_{\\textrm{in}}\\in\\mathbb R^{p}$.\nIf the Hessian matrix $Q$ is positive semidefinite, we have a convex\nquadratic program. Non-convex quadratic programs, in which $Q$ is\nan indefinite matrix, can be more challenging because they have several\nstationary points and local minima.\"\"\"\n\n# ╔═╡ e0be4cbe-0188-11eb-1991-5b001cf2434a\nmd\"\"\"## Equality Constraints\n\nWe begin our discussion of algorithms for quadratic programming by considering\nthe case in which only equality constraints are present. We consider\nto following equality-constrained quadratic problem\n```math\n\\begin{aligned}\n\\min_{\\vec{x}}\\, & f\\left(\\vec{x}\\right)\\overset{\\vartriangle}{=}\\frac{1}{2} \\vec{x}^\\mathsf{T}Q\\vec{x}- \\vec{c}^\\mathsf{T}\\vec{x}\\\\\n\\textrm{subject to}\\, & A\\vec{x}=\\vec{b}\\,,\\nonumber \n\\end{aligned}\n```\nwhere $A$ is the $m\\times n$ Jacobian of constraints and $\\vec{b}\\in\\mathbb R^{m}$.\nWe assume that $A$ has rank $m$ so that the constraints are consistent.\n\nThe First Order Necessary Condition (FONC) uses the Langrangian function\n```math\n\\mathcal L\\left(\\vec x, \\vec \\lambda\\right)=\\vec{x}^\\mathsf{T}Q\\vec{x}- \\vec{c}^\\mathsf{T}\\vec{x} + \\vec\\lambda^\\mathsf{T} \\left(A\\vec{x}-\\vec{b}\\right)\n```\nand gives the following condition\n```math\n\\begin{aligned}\n\\nabla_{\\vec x}\\mathcal L\\left(\\vec x ^\\star, \\vec \\lambda ^\\star\\right)&=\\vec 0\\,,\\\\\n\\nabla_{\\vec \\lambda}\\mathcal L\\left(\\vec x ^\\star, \\vec \\lambda ^\\star\\right)&=\\vec 0\\,,\n\\end{aligned}\n```\nSo the FONC for $\\vec{x}^{\\star}$ to be a solution of the quadratic\nproblem yields a vector $\\vec{\\lambda}^{\\star}$ such\nthat the following system of equations is satisfied:\n```math\n\\begin{pmatrix}Q & A^\\mathsf{T}\\\\\nA & 0\n\\end{pmatrix}\\begin{pmatrix}\\vec{x}^{\\star}\\\\\n\\vec{\\lambda}^{\\star}\n\\end{pmatrix}=\\begin{pmatrix}\\vec{c}\\\\\n\\vec{b}\n\\end{pmatrix}\\,.\n```\nThis system can be solved directly by factorization. An alternative\nis to use an iterative method.\n\nConsider the quadratic programming problem\n```math\n\\begin{aligned}\n\\min_{\\vec{x}}\\, & \\frac{1}{2} \\vec{x}^\\mathsf{T}\\begin{pmatrix}6 & 2 & 1\\\\\n2 & 5 & 2\\\\\n1 & 2 & 4\n\\end{pmatrix}\\vec{x}- \\begin{pmatrix}8\\\\\n3\\\\\n3\n\\end{pmatrix}^\\mathsf{T}\\vec{x}\\\\\n\\textrm{subject to}\\, & \\begin{pmatrix}1 & 0 & 1\\\\\n0 & 1 & 1\n\\end{pmatrix}\\vec{x}=\\begin{pmatrix}3\\\\\n0\n\\end{pmatrix}\\,.\n\\end{aligned}\n```\"\"\"\n\n# ╔═╡ 56fd4bc0-0189-11eb-04c2-0d000ded6e97\nlet\n\tQ = [6 2 1\n     \t 2 5 2\n         1 2 4]\n\tc = [8, 3, 3]\n\tA = [1 0 1\n\t\t 0 1 1]\n\tb = [3, 0]\n\tsol = [Q transpose(A)\n\t\t   A zeros(2,2)] \\ [c; b]\nend\n\n# ╔═╡ 80edfd80-0189-11eb-1687-01a14b31ad39\nmd\"\"\"The solution $\\vec{x}^{\\star}$ and optimal Lagrange multiplier vector $\\vec \\lambda^\\star$ are given by\n```math\n\\begin{aligned}\n\\vec{x}^{\\star} & = \\begin{pmatrix}2 & -1 & 1\\end{pmatrix}^\\mathsf{T}\\,,\\\\\n\\vec{\\lambda}^{\\star} & = \\begin{pmatrix}-3 & 2\\end{pmatrix}^\\mathsf{T}\\,.\n\\end{aligned}\n```\"\"\"\n\n# ╔═╡ 8f340330-0189-11eb-27c8-7ba7c0954ac7\nmd\"\"\"## Active Set Method\n\nWe now describe active-set methods for solving quadratic programs\ncontaining both equality and inequality constraints. We consider only\nthe convex case, in which the matrix ``Q`` is positive semidefinite.\n\nIf the contents of the optimal active set ``J\\left(\\vec x^\\star\\right)`` were known in advance, we could find the solution ``\\vec{x}^{\\star}``\nby applying the technique for equality constrained quadratic programs\nto the problem\n```math\n\\begin{aligned}\n\\min_{\\vec{x}}\\, & f\\left(\\vec{x}\\right)\\overset{\\vartriangle}{=}\\frac{1}{2} \\vec{x}^\\mathsf{T}Q\\vec{x}- \\vec{c}^\\mathsf{T}\\vec{x}\\\\\n\\textrm{subject to}\\, & \\begin{cases}\nA_{\\textrm{eq}}\\vec{x}=\\vec{b}_{\\textrm{eq}}\\,,\\\\\n \\vec{a}_{\\textrm{in},j}^\\mathsf{T}\\vec{x}=b_{\\textrm{in},j}\\,, & \\forall j\\in J\\left(\\vec{x}^{\\star}\\right)\\,,\n\\end{cases}\n\\end{aligned}\n```\nwhere ``\\vec{a}_{\\textrm{in},j}`` is the ``j``th row in the matrix ``A_{\\textrm{in}}``\nand ``b_{\\textrm{in},j}`` is the ``j``th element of the vector ``\\vec{b}_{\\textrm{in}}``.\nOf course, we usually do not have prior knowledge of ``J\\left(\\vec{x}^{\\star}\\right)``\nand determination of this set is the main challenge facing algorithms\nfor inequality-constrained quadratic programs.\n\nActive-set methods find a step from one iterate to the next by solving\na quadratic subproblem in which some of the inequality constraints,\nand all the equality constraints are imposed as equalities. This subset\nis referred to as the _working set_ and is denoted at the ``k``th\niterate by ``W_{k}``. An important requirement we impose on ``W_{k}``\nis that the gradients ``\\vec{a}_{\\textrm{eq},i}``, ``i=1,\\dots,m`` and\n``\\vec{a}_{\\textrm{in},j}``, ``j\\in W_{k}`` are linearly independent,\neven when the full set of active constraints at that point has linearly\ndependent gradients.\n\nGiven an iterate ``\\vec{x}^{\\left(k\\right)}`` and the working set ``W_{k}``,\nwe first check whether ``\\vec{x}^{\\left(k\\right)}`` minimizes the quadratic\nfunction ``f`` in the subspace defined by the working set. If not,\nwe compute a step ``\\vec{d}^{\\left(k\\right)}`` by solving an equality-constrained\nquadratic subproblem in which the inequality constraints corresponding\nto the working set ``W_{k}`` are regarded as equalities and the other\ninequality constraints are temporarily disregarded. To express this\nsubproblem in terms of the step ``\\vec{d}^{\\left(k\\right)}``, we define\n```math\n\\vec{d}^{\\left(k\\right)}=\\vec{x}^{\\left(k+1\\right)}-\\vec{x}^{\\left(k\\right)}\\,,\\quad\\vec{g}_{k}=Q\\vec{x}^{\\left(k\\right)}-\\vec{c}\\,.\n```\nBy substituting for ``\\vec{x}^{\\left(k+1\\right)}`` into the objective\nfunction, we find that\n```math\nf\\left(\\vec{x}^{\\left(k+1\\right)}\\right)=f\\left(\\vec{x}^{\\left(k\\right)}+\\vec{d}^{\\left(k\\right)}\\right)=\\frac{1}{2}\\left(\\vec{d}^{\\left(k\\right)}\\right)^\\mathsf{T}Q\\vec{d}^{\\left(k\\right)}+\\vec{g}_{k}^\\mathsf{T}\\vec{d}^{\\left(k\\right)}+\\rho_{k}\\,,\n```\nwhere ``\\rho_{k}=\\frac{1}{2} \\left(\\vec{x}^{\\left(k\\right)}\\right)^\\mathsf{T}Q\\vec{x}^{\\left(k\\right)}- \\vec{c}^\\mathsf{T}\\vec{x}^{\\left(k\\right)}``\nis independent of ``\\vec{d}^{\\left(k\\right)}``. Since we can drop ``\\rho_{k}``\nfrom the objective function without changing the solution of the problem,\nwe can write the subproblem to be solved at the ``k``th iteration as\nfollows\n```math\n\\begin{aligned}\n\\min_{\\vec{d}^{\\left(k)\\right)}}\\, & \\frac{1}{2} \\left(\\vec{d}^{\\left(k\\right)}\\right)^\\mathsf{T}Q\\vec{d}^{\\left(k\\right)}+ \\vec{g}_{k}^\\mathsf{T}\\vec{d}^{\\left(k\\right)}\\label{eq:quadratic_subproblem}\\\\\n\\textrm{subject to}\\, & \\begin{cases}\nA_{\\textrm{eq}}\\vec{d}^{\\left(k\\right)}=\\vec{0}\\,,\\\\\n \\vec{a}_{\\textrm{in},j}^\\mathsf{T}\\vec{d}^{\\left(k\\right)}=0\\,, & \\forall j\\in W_{k}\\,.\n\\end{cases}\n\\end{aligned}\n```\nNote that for each ``j\\in W_{k}``, the value of `` \\vec{a}_{\\textrm{in},j}^\\mathsf{T}\\vec{x}^{\\left(k\\right)}``\ndoes not change as we move along ``\\vec{d}^{\\left(k\\right)}``, since\nwe have `` \\vec{a}_{\\textrm{in},j}^\\mathsf{T}\\left(\\vec{x}^{\\left(k\\right)}+\\alpha\\vec{d}^{\\left(k\\right)}\\right)= \\vec{a}_{\\textrm{in},j}^\\mathsf{T}\\vec{x}^{\\left(k\\right)}=b_{\\textrm{in},j}``\nfor all ``\\alpha``. Since the constraints in ``W_{k}`` were satisfied\nat ``\\vec{x}^{\\left(k\\right)}``, they are also satisfied at ``\\vec{x}^{\\left(k\\right)}+\\alpha\\vec{d}^{\\left(k\\right)}``,\nfor any value of ``\\alpha``.\n\nSupposing for the moment that the optimal ``\\vec{d}^{\\left(k\\right)}``\nis nonzero, we need to decide how far to move along this direction.\nIf ``\\vec{x}^{\\left(k\\right)}+\\vec{d}^{\\left(k\\right)}`` is feasible\nwith respect to all the constraints, we set ``\\vec{x}^{\\left(k+1\\right)}=\\vec{x}^{\\left(k\\right)}+\\vec{d}^{\\left(k\\right)}``.\nOtherwise, we set\n```math\n\\vec{x}^{\\left(k+1\\right)}=\\vec{x}^{\\left(k\\right)}+\\alpha_{k}\\vec{d}^{\\left(k\\right)}\\,,\n```\nwhere the step-length parameter ``\\alpha_{k}`` is chosen to be the\nlargest value in the range ``\\left[0,1\\right]`` for which all constraints\nare satisfied. We can derive an explicit definition of ``\\alpha_{k}``\nby considering what happens to the constraints ``j\\notin W_{k}``, since\nthe constraints ``j\\in W_{k}`` will certainly be satisfied regardless\nof the choice of ``\\alpha_{k}``. If `` \\vec{a}_{\\textrm{in},j}^\\mathsf{T}\\vec{d}^{\\left(k\\right)}\\leq0``\nfor some ``j\\notin W_{k}``, then for all ``\\alpha_{k}\\geq0``, we have\n`` \\vec{a}_{\\textrm{in},j}^\\mathsf{T}\\left(\\vec{x}^{\\left(k\\right)}+\\alpha_{k}\\vec{d}^{\\left(k\\right)}\\right)\\leq \\vec{a}_{\\textrm{in},j}^\\mathsf{T}\\vec{x}^{\\left(k\\right)}\\leq b_{\\textrm{in},j}``.\nHence, constraint ``j`` will be satisfied for all nonnegative choices\nof the step-length parameter. Whenever `` \\vec{a}_{\\textrm{in},j}^\\mathsf{T}\\vec{d}^{\\left(k\\right)}>0``\nfor some ``j\\notin W_{k}``, however, we have that `` \\vec{a}_{\\textrm{in},j}^\\mathsf{T}\\left(\\vec{x}^{\\left(k\\right)}+\\alpha_{k}\\vec{d}^{\\left(k\\right)}\\right)\\leq b_{\\textrm{in},j}``\nonly if\n```math\n\\alpha_{k}\\leq\\frac{b_{\\textrm{in},j}- \\vec{a}_{\\textrm{in},j}^\\mathsf{T}\\vec{x}^{\\left(k\\right)}}{ \\vec{a}_{\\textrm{in},j}^\\mathsf{T}\\vec{d}^{\\left(k\\right)}}\\,.\n```\nTo maximize the decrease in ``f``, we want ``\\alpha_{k}`` to be as large\nas possible in ``\\left[0,1\\right]`` subject to retaining feasibility,\nso we obtain the following definition\n```math\n\\alpha_{k}\\overset{\\textrm{def}}{=}\\min\\left\\{ 1,\\min_{j\\notin W_{k}, \\vec{a}_{\\textrm{in},j}^\\mathsf{T}\\vec{d}^{\\left(k\\right)}>0}\\frac{b_{\\textrm{in},j}- \\vec{a}_{\\textrm{in},j}^\\mathsf{T}\\vec{x}^{\\left(k\\right)}}{ \\vec{a}_{\\textrm{in},j}^\\mathsf{T}\\vec{d}^{\\left(k\\right)}}\\right\\} \\,.\n```\nWe call the constraints ``j`` for which this minimum is achieved the\n_blocking constraints_. Note that it is quite possible for ``\\alpha_{k}``\nto be zero, because we could have `` \\vec{a}_{\\textrm{in},j}^\\mathsf{T}\\vec{d}^{\\left(k\\right)}>0``\nfor some constraint ``j`` that is active at ``\\vec{x}^{\\left(k\\right)}``\nbut not a member of the current working set ``W_{k}``.\n\nIf ``\\alpha_{k}<1``, that is, the step along ``\\vec{d}_{k}`` was blocked\nby some constraint not in ``W_{k}``, a new working set ``W_{k+1}`` is\nconstructed by adding one of the blocking constraints to ``W_{k}``.\nWe continue to iterate in this manner, adding constraints to the working\nset until the subproblem has solution ``\\vec{d}^{\\circ}=\\vec{0}``.\nSince ``\\vec{d}^{\\circ}=\\vec{0}`` satisfy the optimality condition, we have that\n```math\n\\sum_{i=1}^{m}\\lambda_{i}^{\\circ}\\vec{a}_{\\textrm{eq},i}+\\sum_{j\\in W^{\\circ}}\\mu_{j}^{\\circ}\\vec{a}_{\\textrm{in},j}=-\\vec{g}^{\\circ}=-Q\\vec{x}^{\\circ}+\\vec{c}\\,,\n```\nfor some Lagrange multipliers ``\\lambda_{i}^{\\circ}``, ``i=1,\\dots,m``\nand ``\\mu_{j}^{\\circ}``, ``j\\in W^{\\circ}``. It follows that ``\\vec{x}^{\\circ}``,\n``\\vec{\\lambda}^{\\circ}`` and ``\\vec{\\mu}^{\\circ}`` satisfy the second\nKKT condition, if we define the multipliers corresponding to the inequality\nconstraints not in the working set to be zero. Because of the control\nimposed on the step length, ``\\vec{x}^{\\circ}`` is also feasible with\nrespect to all the constraints, so the third, fourth and fifth KKT\nconditions are satisfied at this point.\n\nWe now examine the signs of the KKT multipliers in the working set,\nthat is, the indices ``j\\in W^{\\circ}``. If these conditions are all\nnonnegative, the first KKT condition is also satisfied, so we conclude\nthat ``\\vec{x}^{\\circ}`` is a KKT point for the original problem. In\nfact, since ``Q`` is positive semidefinite, we have that ``\\vec{x}^{\\circ}``\nis a global minimum.\n\nIf, on the other hand, on or more of the multipliers ``\\mu_{j}^{\\circ}``,\n``j\\in W^{\\circ}``, are negative, the first KKT condition is not satisfied\nand the objective function ``f`` may be decreased by dropping one of\nthese constraints. Thus, we remove an index ``j`` corresponding to\none of the negative multipliers from the working set and solve a new\nsubproblem for the next step. While any index ``j`` for which ``\\mu_{j}^{\\circ}<0``\nusually will yield in a direction ``\\vec{d}`` along which the algorithm\ncan make progress, the most negative multiplier is often chosen in\npractice. This choice is motived by a sensitivity analysis, which\nshows that the rate of decrease in the objective function when one\nconstraint is removed, is proportional to the magnitude of the Lagrange\nmultiplier for that constraint.\"\"\"\n\n# ╔═╡ db088c90-0189-11eb-338d-81af9469d556\nmd\"\"\"## Example\n\nApply the active-set method to the following problem:\n```math\n\\begin{aligned}\n\\min_{\\vec{x}}\\, & f\\left(\\vec{x}\\right)=\\left(x_{1}-1\\right)^{2}+\\left(x_{2}-2.5\\right)^{2}\\\\\n\\textrm{subject to}\\, & \\begin{cases}\n-x_{1}+2x_{2}-2\\leq0\\,,\\\\\nx_{1}+2x_{2}-6\\leq0\\,.\\\\\nx_{1}-2x_{2}-2\\leq0\\,,\\\\\n-x_{1}\\leq0\\,,\\\\\n-x_{2}\\leq0\\,.\n\\end{cases}\n\\end{aligned}\n```\"\"\"\n\n# ╔═╡ 6bdfb630-018a-11eb-1010-b3c332121581\nbegin\n\tQ = Float64[2 0\n                0 2]\n\tc = Float64[2, 5]\n\tA = Float64[-1  2\n\t\t\t\t 1  2\n\t\t\t\t 1 -2\n\t\t\t\t-1  0\n\t\t\t\t 0 -1]\n\tb = Float64[2, 6, 2, 0, 0]\n\n\tx = -1:0.05:5\n\ty = -1:0.05:5\n\tz = Surface((x,y)->(0.5 .* [x y]*Q*[x;y] .- transpose(c)*[x;y] .+ 0.5 .* transpose(c)*Q*c)[1], x, y)\n\tcontour(x, y, z, levels=35)\n\tplot!(x, (2 .+ x) ./ 2, linestyle=:dash, label=L\"-x_1+2x_2-2\\le 0\")\n\tplot!(x, (6 .- x) ./ 2, linestyle=:dash, label=L\"x_1+2x_2-6\\le 0\")\n\tplot!(x, (2 .- x) ./ -2, linestyle=:dash, label=L\"x_1-2x_2-2\\le 0\")\n\tplot!([0,2,4,2,0,0],[0,0,1,2,1,0], linewidth=2, label=\"domain\")\nend\n\n# ╔═╡ 88c16630-018b-11eb-3ea1-a555d69b2e26\nmd\"\"\"We refer the constraints, in order, by indices $1$ through $5$.\nFor this problem it is easy to determine a feasible initial point;\nsay $\\vec{x}^{\\left(0\\right)}=\\begin{pmatrix}2 & 0\\end{pmatrix}\\mathsf{T}$.\nConstraints $3$ and $5$ are active at this point, and we set $W_{0}=\\left\\{ 3,5\\right\\} $.\nNote that we could just as validly have chosen $W_{0}=\\left\\{ 5\\right\\} $\nor $W_{0}=\\left\\{ 3\\right\\} $ or even $W_{0}=\\emptyset$; each choice\nwould lead the algorithm to perform somewhat differently.\"\"\"\n\n# ╔═╡ 4a460a20-018e-11eb-3da1-4d37893ead18\nx₀ = [2, 0]\n\n# ╔═╡ 8df4e190-018b-11eb-2eae-1d8f6c4e6248\nlet x = x₀\n\tg = Q*x - c\n\tain = [reshape(A[3,:], 1, 2); reshape(A[5,:], 1, 2)]\n\tsol = [Q transpose(ain)\n\t\t   ain zeros(2,2)] \\ [-g; 0; 0]\nend\n\n# ╔═╡ a8042d20-018b-11eb-0f74-3b70e587f20d\nmd\"\"\"Since $\\vec{x}^{\\left(0\\right)}$ lies on a vertex of the feasible\nregion, it is obviously a minimizer of the objective function $f$\nwith respect to the working set $W_{0}$; that is, the solution of\nthe subproblem with $k=0$ is $\\vec{d}^{\\left(0\\right)}=\\vec{0}$.\nWe can then find the multipliers $\\mu_{3}^{\\circ}$ and $\\mu_{5}^{\\circ}$\nassociated with the active constraints. Substitution of the data from\nour problem yields\n```math\n\\begin{pmatrix}-1\\\\\n2\n\\end{pmatrix}\\lambda_{3}^{\\circ}+\\begin{pmatrix}0\\\\\n1\n\\end{pmatrix}\\lambda_{5}^{\\circ}=\\begin{pmatrix}2\\\\\n-5\n\\end{pmatrix}\\,,\n```\nwhich has solution $\\lambda_{3}^{\\circ}=-2$ and $\\lambda_{5}^{\\circ}=-1$. \n\nWe now remove constraint $3$ from the working set, because it has\nthe most negative multiplier, and set $W_{1}=\\{5\\}$.\"\"\"\n\n# ╔═╡ b9b7e250-018b-11eb-1eca-51dc8250a3eb\nsol₁ = let x = x₀\n\tg = Q*x - c\n\tain = reshape(A[5,:], 1, 2)\n\tsol = [Q transpose(ain)\n\t\t   ain zeros(1,1)] \\ [-g; 0]\nend\n\n# ╔═╡ e14bb850-018b-11eb-0bb0-15ebdb2f7fcf\nmd\"\"\"We begin iteration $1$ by finding the solution of the subproblem for $k=1$, which is\n$\\vec{d}^{\\left(1\\right)}= \\begin{pmatrix}-1 & 0\\end{pmatrix}^\\mathsf{T}$.\"\"\"\n\n# ╔═╡ ea6595a0-018b-11eb-07dc-f394137f59f4\nα₁, d₁ = let x = x₀\n\td = sol₁[1:2]\n\tα = min(1.0, [(reshape(A[j,:], 1, 2) * d)[1,1] ≤ 0 ? 1.0 : ((b[j] .- reshape(A[j,:], 1, 2) * x) / (reshape(A[j,:], 1, 2) * d))[1,1] for j in (1,2,3,4)]...)\n\tα, d\nend\n\n# ╔═╡ 0d2eeb40-018c-11eb-0fdc-1b6668c5941f\nmd\"\"\"The step-length formula yields $\\alpha_{1}=1$, and the new iterate\nis $\\vec{x}^{\\left(2\\right)}=\\begin{pmatrix}1 & 0\\end{pmatrix}^\\mathsf{T}$. There are no blocking constraints, so that ``W_{2}=W_{1}=\\left\\{ 5\\right\\}``\"\"\"\n\n# ╔═╡ ee702bf0-018c-11eb-1ec9-6b481c119add\nx₁ = x₀ + α₁ .* d₁\n\n# ╔═╡ 2cb44400-018d-11eb-0138-c78f6a18b8f8\nsol₂ = let x = x₁\n\tg = Q*x - c\n\tain = reshape(A[5,:], 1, 2)\n\tsol = [Q transpose(ain)\n\t\t   ain zeros(1,1)] \\ [-g; 0]\nend\n\n# ╔═╡ 456d9c82-018d-11eb-0e81-bf7346539a32\nmd\"\"\"We find at the start of iteration $2$ that the solution of the\nsubproblem is $\\vec{d}^{\\left(2\\right)}=\\vec{0}$. We deduce that\nthe Lagrange multiplier for the lone working constraint is $\\lambda_{5}^{\\circ}=-5$,\nso we drop the working set to obtain $W_{3}=\\emptyset$.\"\"\"\n\n# ╔═╡ 84712210-018f-11eb-0bef-53cdfb93e0e2\nx₂ = x₁\n\n# ╔═╡ 96ecfeb2-018e-11eb-2dda-994575ee6011\nsol₃ = let x = x₂\n\tg = Q*x - c\n\tsol = Q \\ (-g)\nend\n\n# ╔═╡ 2ddf0860-018d-11eb-2884-7dacdda18597\nmd\"\"\"Iteration $3$ starts by solving the unconstrained problem, to obtain\nthe solution $\\vec{d}^{\\left(3\\right)}=\\begin{pmatrix}0 & 2.5\\end{pmatrix}^\\mathsf{T}$.\"\"\"\n\n# ╔═╡ c71e2f00-018e-11eb-1c30-a54d6d4d04ff\nα₃, d₃ = let x = x₂\n\td = sol₃[1:2]\n\tα = min(1.0, [(reshape(A[j,:], 1, 2) * d)[1,1] ≤ 0 ? 1.0 : ((b[j] .- reshape(A[j,:], 1, 2) * x) / (reshape(A[j,:], 1, 2) * d))[1,1] for j in (1,2,3,4,5)]...)\n\tα, d\nend\n\n# ╔═╡ e470e5c0-018e-11eb-229b-e521909f84e3\nmd\"\"\"The step-length formula yields a step length of $\\alpha_{3}=0.6$\nand a new iterate $\\vec{x}^{\\left(4\\right)}=\\begin{pmatrix}1 & 1.5\\end{pmatrix}^\\mathsf{T}$. There\nis a single blocking constraint (constraint $1$), so we obtain ``W_{4}=\\left\\{ 1\\right\\}``.\"\"\"\n\n# ╔═╡ 596ba4f0-018f-11eb-321e-03ec8a6d18db\nx₃ = x₂ + α₃ .* d₃\n\n# ╔═╡ 91ada700-018f-11eb-37d0-757a263bae99\nsol₄ = let x=x₃\n\tg = Q*x - c\n\tain = reshape(A[1,:], 1, 2)\n\tsol = [Q transpose(ain)\n\t\t   ain zeros(1,1)] \\ [-g; 0]\nend\n\n# ╔═╡ abfbf760-018f-11eb-18dc-bd573cc8be06\nmd\"\"\"The solution of the subproblem for $k=4$ is then $\\vec{d}^{\\left(4\\right)}=\\begin{pmatrix}0.4 & 0.2\\end{pmatrix}^\\mathsf{T}$.\"\"\"\n\n# ╔═╡ ba0f5450-018f-11eb-2188-4327aa9c02cc\nα₄, d₄ = let x = x₃\n\td = sol₄[1:2]\n\tα = min(1.0, [(reshape(A[j,:], 1, 2) * d)[1,1] ≤ 0 ? 1.0 : ((b[j] .- reshape(A[j,:], 1, 2) * x) / (reshape(A[j,:], 1, 2) * d))[1,1] for j in (2,3,4,5)]...)\n\tα, d\nend\n\n# ╔═╡ d8c62ef0-018f-11eb-21ce-ebe037f9d91d\nmd\"\"\"The new step-length is $1$. There are no blocking constraints\non this step, so the next working set in unchanged: $W_{5}=\\left\\{ 1\\right\\} $. The new iterate is $\\vec{x}^{\\left(5\\right)}=\\begin{pmatrix}1.4 & 1.7\\end{pmatrix}^\\mathsf{T}$.\"\"\"\n\n# ╔═╡ e59a7c30-018f-11eb-2b94-7b8dff2a6383\nx₄ = x₃ + α₄ .* d₄\n\n# ╔═╡ f5f705d0-018f-11eb-2462-e7e2265b700c\nsol₅ = let x = x₄\n\tg = Q*x - c\n\tain = reshape(A[1,:], 1, 2)\n\tsol = [Q transpose(ain)\n\t\t   ain zeros(1,1)] \\ [-g; 0]\nend\n\n# ╔═╡ 1254d540-0190-11eb-3066-b5a853eef0c0\nmd\"\"\"Finally, we solve the subproblem for $k=5$ to obtain a solution $\\vec{d}^{\\left(5\\right)}=\\vec{0}$.\nWe find a multiplier $\\mu_{1}^{\\circ}=0.8$, so we have found the\nsolution. Wet set $\\vec{x}^{\\star}=\\begin{pmatrix}1.4 & 1.7\\end{pmatrix}^\\mathsf{T}$\nand terminate.\"\"\"\n\n# ╔═╡ 02787820-0190-11eb-24ed-c5296c91df6b\nlet\n\tx = -1:0.05:5\n\ty = -1:0.05:5\n\tz = Surface((x,y)->(0.5 .* [x y]*Q*[x;y] .- transpose(c)*[x;y] .+ 0.5 .* transpose(c)*Q*c)[1], x, y)\n\tcontour(x, y, z, levels=35)\n\tplot!(x, (2 .+ x) ./ 2, linestyle=:dash, label=L\"-x_1+2x_2-2\\le 0\")\n\tplot!(x, (6 .- x) ./ 2, linestyle=:dash, label=L\"x_1+2x_2-6\\le 0\")\n\tplot!(x, (2 .- x) ./ -2, linestyle=:dash, label=L\"x_1-2x_2-2\\le 0\")\n\tplot!([0,2,4,2,0,0],[0,0,1,2,1,0], linewidth=2, label=\"domain\")\n\tplot!([2,2,1,1,1,1.4], [0,0,0,0,1.5,1.7], linewidth=2, label=\"iterates\", markershape=:circle)\nend\n\n# ╔═╡ aa606210-018a-11eb-29bd-5d4f9ae0966e\nmd\"\"\"## Julia\n\nThe package `GeneralQP` solves the quadratic programming problems using the function `solve(Q, -c, A, b, x₀)`.\"\"\"\n\n# ╔═╡ f3007460-018a-11eb-3fa2-8753aceaf89a\nsol = GeneralQP.solve(Q, -c, A, b, Float64[2,0])\n\n# ╔═╡ 24c67580-018b-11eb-3eb7-47a2e2ae5251\nmd\"\"\"## Sequential Quadratic Programming\n\nWe consider the general constrained problem\n```math\n\\begin{aligned}\n\\min\\, & f\\left(\\vec{x}\\right)\\\\\n\\textrm{subject to} & \\begin{cases}\n\\vec{h}\\left(\\vec{x}\\right)=\\vec{0}\\\\\n\\vec{g}\\left(\\vec{x}\\right)\\leq\\vec{0}\n\\end{cases}\n\\end{aligned}\n```\nwhere $f:\\mathbb{R}^{n}\\rightarrow\\mathbb{R}$, $\\vec{h}:\\mathbb{R}^{n}\\rightarrow\\mathbb{R}^{m}$,\n$m\\leq n$, and $\\vec{g}:\\mathbb{R}^{n}\\rightarrow\\mathbb{R}^{p}$. The idea\nbehind the _sequential quadratic programming_ (SQP) approach\nis to model the general problem at the current iterate $\\vec{x}^{\\left(k\\right)}$\nby a quadratic programming subproblem, then use the minimizer of this\nsubproblem to define a new iterate $\\vec{x}^{\\left(k+1\\right)}$.\nThe challenge is to design the quadratic subproblem so that it yields\na good step for the general optimization problem.\n\nWe know that the extended Lagrangian function for this problem is\n\n```math\n\\mathcal{L}\\left(\\vec{x},\\vec{\\lambda},\\vec{\\mu}\\right)=f\\left(\\vec{x}\\right)+\\vec{\\lambda}^\\mathsf{T}\\vec{h}\\left(\\vec{x}\\right)+\\vec{\\mu}^\\mathsf{T}\\vec g\\left(\\vec{x}\\right)\\,.\n```\n\nApplying Newton's method to the Lagrangian function and linearizing\nboth the equality and the inequality constraints yields the following\nsubproblem\n```math\n\\begin{aligned}\n\\min_{\\vec{d}^{\\left(k\\right)}}\\, & \\frac{1}{2}\\left(\\vec{d}^{\\left(k\\right)}\\right)^\\mathsf{T} \\mathsf{H} \\mathcal{L}\\left(\\vec{x}^{\\left(k\\right)},\\vec{\\lambda}^{\\left(k\\right)},\\vec{\\mu}^{\\left(k\\right)}\\right)\\vec{d}^{\\left(k\\right)}+ \\mathsf{D} \\mathcal{L}\\left(\\vec{x}^{\\left(k\\right)},\\vec{\\lambda}^{\\left(k\\right)},\\vec{\\mu}^{\\left(k\\right)}\\right)\\vec{d}^{\\left(k\\right)}\\\\\n\\textrm{subject to}\\, & \\begin{cases}\n \\mathsf{J}\\vec{h}\\left(\\vec{x}^{\\left(k\\right)}\\right)\\vec{d}^{\\left(k\\right)}=-\\vec{h}\\left(\\vec{x}^{\\left(k\\right)}\\right)\\\\\n \\mathsf{D} g_{j}\\left(\\vec{x}^{\\left(k\\right)}\\right)\\vec{d}^{\\left(k\\right)}=-g_{j}\\left(\\vec{x}^{\\left(k\\right)}\\right)\\,, & j\\in W_{k}\\,,\n\\end{cases}\n\\end{aligned}\n```\n\nwhere $\\mu_{j}^{\\left(k\\right)}=0$, for all\n$j\\notin W_{k}$. We can use the active-set method for quadratic programming\nto solve this subproblem. The new iterate is given by $\\vec{x}^{\\left(k+1\\right)}$,\n$\\vec{\\lambda}^{\\left(k+1\\right)}$, $\\vec{\\mu}^{\\left(k+1\\right)}$\nand $W_{k+1}$.\n\nIf the SQP method is able to identify the optimal active set then\nit will act like a Newton method for equality-constrained optimization\nand will converge rapidly.\n\nIt is also remarkable that, far from the solution, the SQP approach\nis usually able to improve the estimate of the active set and guide\nthe iterates towards a solution.\n\nNon-quadratic objective functions, however, can impede progress of\nthe SQP algorithm, a phenomenon known as the Maratos effect. Steps\nthat make good progress toward a solution are rejected and the algorithm\nfails to converge rapidly. These difficulties can be overcome by means\nof a _second-order correction_.\"\"\"\n\n# ╔═╡ a98c8890-0190-11eb-25a4-bfd18c42b749\nfunction myfunc(x::Vector, grad::Vector)\n    if length(grad) > 0\n        grad[1] = 0\n        grad[2] = 0.5/sqrt(x[2])\n    end\n    return sqrt(x[2])\nend\n\n# ╔═╡ acfea4e0-0190-11eb-07a9-a3f38d97ff80\nfunction myconstraint(x::Vector, grad::Vector, a, b)\n    if length(grad) > 0\n        grad[1] = 3a * (a*x[1] + b)^2\n        grad[2] = -1\n    end\n    (a*x[1] + b)^3 - x[2]\nend\n\n# ╔═╡ a4824010-0190-11eb-0d97-a55353709552\nlet\n\topt = Opt(:LD_SLSQP, 2)\n\topt.lower_bounds = [-Inf, 0.]\n\topt.xtol_rel = 1e-4\n\n\topt.min_objective = myfunc\n\tinequality_constraint!(opt, (x,g) -> myconstraint(x,g,2,0), 1e-8)\n\tinequality_constraint!(opt, (x,g) -> myconstraint(x,g,-1,1), 1e-8)\n\n\t(minf, minx, ret) = optimize(opt, [1.234, 5.678])\n\tnumevals = opt.numevals # the number of function evaluations\n\tminf, minx, numevals, ret\nend\n\n# ╔═╡ Cell order:\n# ╟─ffed97e2-dc07-48bb-870a-737a115e69dc\n# ╟─9f5f8730-0188-11eb-209f-e771579d35ce\n# ╟─c30dbe90-0188-11eb-0c2b-ed5e93a86b0b\n# ╟─e0be4cbe-0188-11eb-1991-5b001cf2434a\n# ╠═56fd4bc0-0189-11eb-04c2-0d000ded6e97\n# ╟─80edfd80-0189-11eb-1687-01a14b31ad39\n# ╟─8f340330-0189-11eb-27c8-7ba7c0954ac7\n# ╟─db088c90-0189-11eb-338d-81af9469d556\n# ╠═6bdfb630-018a-11eb-1010-b3c332121581\n# ╟─88c16630-018b-11eb-3ea1-a555d69b2e26\n# ╠═4a460a20-018e-11eb-3da1-4d37893ead18\n# ╠═8df4e190-018b-11eb-2eae-1d8f6c4e6248\n# ╟─a8042d20-018b-11eb-0f74-3b70e587f20d\n# ╠═b9b7e250-018b-11eb-1eca-51dc8250a3eb\n# ╟─e14bb850-018b-11eb-0bb0-15ebdb2f7fcf\n# ╠═ea6595a0-018b-11eb-07dc-f394137f59f4\n# ╟─0d2eeb40-018c-11eb-0fdc-1b6668c5941f\n# ╠═ee702bf0-018c-11eb-1ec9-6b481c119add\n# ╠═2cb44400-018d-11eb-0138-c78f6a18b8f8\n# ╟─456d9c82-018d-11eb-0e81-bf7346539a32\n# ╠═84712210-018f-11eb-0bef-53cdfb93e0e2\n# ╠═96ecfeb2-018e-11eb-2dda-994575ee6011\n# ╟─2ddf0860-018d-11eb-2884-7dacdda18597\n# ╠═c71e2f00-018e-11eb-1c30-a54d6d4d04ff\n# ╟─e470e5c0-018e-11eb-229b-e521909f84e3\n# ╠═596ba4f0-018f-11eb-321e-03ec8a6d18db\n# ╠═91ada700-018f-11eb-37d0-757a263bae99\n# ╟─abfbf760-018f-11eb-18dc-bd573cc8be06\n# ╠═ba0f5450-018f-11eb-2188-4327aa9c02cc\n# ╟─d8c62ef0-018f-11eb-21ce-ebe037f9d91d\n# ╠═e59a7c30-018f-11eb-2b94-7b8dff2a6383\n# ╠═f5f705d0-018f-11eb-2462-e7e2265b700c\n# ╟─1254d540-0190-11eb-3066-b5a853eef0c0\n# ╠═02787820-0190-11eb-24ed-c5296c91df6b\n# ╟─aa606210-018a-11eb-29bd-5d4f9ae0966e\n# ╠═f3007460-018a-11eb-3fa2-8753aceaf89a\n# ╟─24c67580-018b-11eb-3eb7-47a2e2ae5251\n# ╠═a98c8890-0190-11eb-25a4-bfd18c42b749\n# ╠═acfea4e0-0190-11eb-07a9-a3f38d97ff80\n# ╠═a4824010-0190-11eb-0d97-a55353709552\n", "meta": {"hexsha": "85d45b548378820933e80e5c3bf3292f473d2c4d", "size": 26321, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Lectures/Lecture09.jl", "max_stars_repo_name": "BenLauwens/ES313.jl", "max_stars_repo_head_hexsha": "5a7553e53c288834f768d26e0d5aa22f9062b6af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-12-17T16:00:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-18T04:09:25.000Z", "max_issues_repo_path": "Lectures/Lecture09.jl", "max_issues_repo_name": "BenLauwens/ES313", "max_issues_repo_head_hexsha": "5a7553e53c288834f768d26e0d5aa22f9062b6af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lectures/Lecture09.jl", "max_forks_repo_name": "BenLauwens/ES313", "max_forks_repo_head_hexsha": "5a7553e53c288834f768d26e0d5aa22f9062b6af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-08-27T13:41:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:00:53.000Z", "avg_line_length": 42.384863124, "max_line_length": 382, "alphanum_fraction": 0.6649823335, "num_tokens": 10736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100816, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7994111244228403}}
{"text": "module problem104\n\ndescription = \"\"\"\nPandigital Fibonacci ends\nProblem 104\n\nThe Fibonacci sequence is defined by the recurrence relation:\n\n    Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.\n\nIt turns out that F541, which contains 113 digits, is the first Fibonacci number for which the last nine digits are 1-9 pandigital (contain all the digits 1 to 9, but not necessarily in order). And F2749, which contains 575 digits, is the first Fibonacci number for which the first nine digits are 1-9 pandigital.\n\nGiven that Fk is the first Fibonacci number for which the first nine digits AND the last nine digits are 1-9 pandigital, find k.\n\"\"\"\n\n# test if the string representation of a number starts with digits 1-9\nis_start_pandigital(x :: String) = (length(x) >= 9) && all([in(c, x[1:9]) for c = '1':'9'])\n\n\n# test if an integer ends with digits 1-9\n# This has been optimized to avoid memory allocations as it is the inner loop\nfunction is_end_pandigital(x :: Int, digits=zeros(Bool, 10))\n  digits[:] = false\n  for i = 1:9\n    digits[x % 10  + 1] = true\n    x = div(x, 10)\n  end\n  for i = 2:10\n    if !digits[i]\n      return false\n    end\n  end\n  return true\nend \n\n\n# Find the first fibonacci that starts with and ends with digits 1-9\n# Calculate fibonacci sequence in BigInts, and in Int64s (modulo 10^10)\n# Test for end-pandigital on the native ints, and when found, test the BigInts for start-pandigital\nfunction find_start_end_pandigital()\n  a, b = 1, 1\n  A, B = BigInt(a), BigInt(b)\n  buf = zeros(Bool, 10)\n  for k = 3:1000000\n    a, b = b, (a+b) % 10000000000\n    A, B = B, (A+B)\n    if is_end_pandigital(b, buf)\n      if is_start_pandigital(string(B))\n        return k\n      end\n    end\n  end\nend \n\nusing Base.Test\n\n@test is_start_pandigital(\"3219485766456\")\n@test !is_start_pandigital(\"10201049586723\")\n@test is_end_pandigital(958928534791826)\n\nend", "meta": {"hexsha": "ab46377031f085529eee450ad92f10d5e25ba4de", "size": 1849, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem104.jl", "max_stars_repo_name": "mbuhot/mbuhot-euler-solutions", "max_stars_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-12-18T13:25:41.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-18T13:25:41.000Z", "max_issues_repo_path": "julia/problem104.jl", "max_issues_repo_name": "mbuhot/mbuhot-euler-solutions", "max_issues_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/problem104.jl", "max_forks_repo_name": "mbuhot/mbuhot-euler-solutions", "max_forks_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3114754098, "max_line_length": 313, "alphanum_fraction": 0.7025419145, "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741298, "lm_q2_score": 0.8670357546485408, "lm_q1q2_score": 0.799339186370551}}
{"text": "# # Optimal advertising\n\n# This example is taken from <https://web.stanford.edu/~boyd/papers/pdf/cvx_applications.pdf>.\n\n# Setup:\n#\n# * We have $m$ adverts and $n$ timeslots\n# * The total traffic in time slot $t$ is $T_t$\n# * The number of ad $i$ displayed in period $t$ is $D_{it} \\geq 0$\n# * We require $\\sum_{i=1}^m D_{it} \\leq T_t$ since we cannot show more than $T_t$ ads during time slot $t$.\n# * We require $\\sum_{t=1}^n D_{it} \\geq c_i$ to fulfill a contract to show advertisement $i$ at least $c_i$ times.\n#\n# Goal: Choose $D_{it}$.\n#\n# For some empirical $P_{it}$ with $0 \\leq P_{it} \\leq 1$, we obtain $C_{it} = P_{it}D_{it}$ clicks for ad $i$, which pays us some number $R_i > 0$ up to a budget $B_i$.\n# The ad revenue for ad $i$ is $S_i = \\min( R_i \\sum_t C_{it}, B_i )$ which is concave in $D$.\n# We aim to maximize $\\sum_i S_i$.\n\nusing Random\nusing Distributions: LogNormal\nRandom.seed!(1);\n\n\nm = 5; # number of adverts\nn = 24; # number of timeslots\nSCALE = 10000;\nB = rand(LogNormal(8), m) .+ 10000;\nB = round.(B, digits=3); # Budget\n\nP_ad = rand(m); \nP_time = rand(1,n); \nP = P_ad * P_time;\n\nT = sin.(range(-2*pi/2, stop=2*pi-2*pi/2, length=n)) * SCALE;\nT .+= -minimum(T) + SCALE; # traffic\nc = rand(m); # contractual minimum\nc *= 0.6*sum(T)/sum(c);\nc = round.(c, digits=3);\nR = [rand(LogNormal(minimum(c)/c[i]), 1) for i=1:m]; # revenue\n\n#-\n\n## Form and solve the optimal advertising problem.\nusing Convex, SCS;\nD = Variable(m, n);\nSi = [min(R[i]*dot(P[i,:], D[i,:]'), B[i]) for i=1:m];\nproblem = maximize(sum(Si),\n               [D >= 0, sum(D, dims=1)' <= T, sum(D, dims=2) >= c]);\nsolve!(problem, () -> SCS.Optimizer(verbose=0));\n\n#-\n\n# Plot traffic.\nusing Plots\nplot(1:length(T), T, xlabel=\"hour\", ylabel=\"Traffic\")\n\n#-\n\n# Plot P.\nheatmap(P)\n\n#-\n\n# Plot optimal D.\nheatmap(evaluate(D))\n", "meta": {"hexsha": "cddcc86774af72aeffb5da6fd8e6a1b8a9efcc49", "size": 1808, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/general_examples/optimal_advertising.jl", "max_stars_repo_name": "JinraeKim/Convex.jl", "max_stars_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 123, "max_stars_repo_stars_event_min_datetime": "2020-06-16T21:56:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:05:39.000Z", "max_issues_repo_path": "docs/examples_literate/general_examples/optimal_advertising.jl", "max_issues_repo_name": "JinraeKim/Convex.jl", "max_issues_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122, "max_issues_repo_issues_event_min_datetime": "2020-06-14T00:19:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T14:02:09.000Z", "max_forks_repo_path": "docs/examples_literate/general_examples/optimal_advertising.jl", "max_forks_repo_name": "JinraeKim/Convex.jl", "max_forks_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2020-08-21T07:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T13:40:50.000Z", "avg_line_length": 27.3939393939, "max_line_length": 169, "alphanum_fraction": 0.6200221239, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833653, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7993118858715371}}
{"text": "\n\"\"\"\n    logsumexp(x::Vector{Complex{T}})::Complex{T}\n\nLog-sum-exp with choosing the shift to be the maximum absolute value for\nthe real and imaginary parts of x's components.\n\n# Example:\n```\na = randn(3) + randn(3) .* im\nu = exp.(a)\nRHS = logsumexp(u)\nLHS = log(sum(exp.(u)))\nprintln(\"RHS = \", RHS)\nprintln(\"LHS = \", LHS)\n```\n\"\"\"\nfunction logsumexp(x::Vector{Complex{T}})::Complex{T} where T <: Real\n\n    # use the maximum magnitude for real and imaginary parts to get the shift, a.\n    val_unused, 𝑖_real = findmax( real.(x) )\n    val_unused, 𝑖_imag = findmax( imag.(x) )\n\n    a::Complex{T} = real(x[𝑖_real]) + im*imag(𝑖_imag)\n\n    # log-sum-exp.\n    running_sum::Complex{T} = zero(Complex{T})\n    for i = 1:length(x)\n        running_sum += exp( x[i] - a )\n    end\n\n    return a + log(running_sum)\nend\n", "meta": {"hexsha": "a6749f05c170a8ca8ec96d708b5a198fa63e3565", "size": 804, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/numerical.jl", "max_stars_repo_name": "RoyCCWang/RWJuliaUtilities", "max_stars_repo_head_hexsha": "3796a8dd251470a127d4fdb2f2ff19be4a5320aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/numerical.jl", "max_issues_repo_name": "RoyCCWang/RWJuliaUtilities", "max_issues_repo_head_hexsha": "3796a8dd251470a127d4fdb2f2ff19be4a5320aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/numerical.jl", "max_forks_repo_name": "RoyCCWang/RWJuliaUtilities", "max_forks_repo_head_hexsha": "3796a8dd251470a127d4fdb2f2ff19be4a5320aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6470588235, "max_line_length": 81, "alphanum_fraction": 0.6243781095, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632261523029, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.799311879760418}}
{"text": "\nfunction basis(elem::Quad, N, r, s)\n    Np = convert(Int, (N + 1) * (N + 1))\n    sk = 1\n    V, Vr, Vs = ntuple(x->zeros(length(r), Np), 3)\n    for j = 0:N\n        P_j = jacobiP(s, 0, 0, j)\n        for i = 0:N\n            P_i = jacobiP(r, 0, 0, i)\n            V[:, sk]  = P_i .* P_j\n            Vr[:, sk] = grad_jacobiP(r, 0, 0, i) .* P_j\n            Vs[:, sk] = P_i .* grad_jacobiP(s, 0, 0, j)\n            sk += 1\n        end\n    end\n    return V,Vr,Vs\nend\n\n\nfunction nodes(elem::Quad, N)\n    r1D, w1D = gauss_lobatto_quad(0, 0, N)\n    s, r = meshgrid(r1D)\n    return r[:], s[:]\nend\n\n\nfunction equi_nodes(elem::Quad, N)\n    r1D = LinRange(-1, 1, N + 1)\n    s, r = meshgrid(r1D)\n    return r[:], s[:]\nend\n\nfunction quad_nodes(elem::Quad,N)\n    r1D, w1D = gauss_quad(0, 0, N)\n    s, r = meshgrid(r1D)\n    ws, wr = meshgrid(w1D)\n    w = @. wr * ws\n    return r[:], s[:], w[:]\nend\n", "meta": {"hexsha": "d60738c355035ea6d9bd557da5aabd79fb626523", "size": 878, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/quad_element.jl", "max_stars_repo_name": "stevengj/NodesAndModes.jl", "max_stars_repo_head_hexsha": "2c13546a26b23e58164f72aab2e8555b002e79e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2020-08-28T06:59:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T16:38:39.000Z", "max_issues_repo_path": "src/quad_element.jl", "max_issues_repo_name": "stevengj/NodesAndModes.jl", "max_issues_repo_head_hexsha": "2c13546a26b23e58164f72aab2e8555b002e79e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-12-01T07:26:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T18:04:39.000Z", "max_forks_repo_path": "src/quad_element.jl", "max_forks_repo_name": "stevengj/NodesAndModes.jl", "max_forks_repo_head_hexsha": "2c13546a26b23e58164f72aab2e8555b002e79e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-23T16:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T16:50:40.000Z", "avg_line_length": 21.95, "max_line_length": 55, "alphanum_fraction": 0.4760820046, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900507, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7992868635717526}}
{"text": "# \"\"\"\n# Source Term Function\n# ```julia\n# source_term = SourceTerm(λ, μ)\n# source_term(x, p)\n# ```\n# where x is a discritzed price point, source_params is a vector of parameters for\n# the source term and p is the last \"observed\" mid price point\n#\n# The function returns a single scalar output\n#\n# \"\"\"\n\nmutable struct SourceTerm\n    λ::Float64\n    μ::Float64\nend\n\n\nfunction (st::SourceTerm)(x::Float64,p::Float64)\n    return st.λ*(p-x)*exp(-st.μ*(p-x)^2)\nend\n\n# function (st::SourceTerm)(x::Float64,p::Float64)\n#     return st.λ*tanh(st.μ*(p-x))\n# end\n", "meta": {"hexsha": "096ccde8c2da2e2e95348e478f6286f06d75bd25", "size": 551, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/source_function.jl", "max_stars_repo_name": "LOB-PJAGG/LatentOrderBookModel.jl", "max_stars_repo_head_hexsha": "e2702a5722f05298dee246cbba26dfe46d248cd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-09-20T15:19:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-26T23:44:07.000Z", "max_issues_repo_path": "src/source_function.jl", "max_issues_repo_name": "LOB-PJAGG/LatentOrderBookModel.jl", "max_issues_repo_head_hexsha": "e2702a5722f05298dee246cbba26dfe46d248cd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-07-20T13:27:13.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-28T21:09:25.000Z", "max_forks_repo_path": "src/source_function.jl", "max_forks_repo_name": "LOB-PJAGG/LatentOrderBookModel.jl", "max_forks_repo_head_hexsha": "e2702a5722f05298dee246cbba26dfe46d248cd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-06-19T07:41:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-05T12:27:52.000Z", "avg_line_length": 20.4074074074, "max_line_length": 82, "alphanum_fraction": 0.666061706, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154280587323, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7992868527122258}}
{"text": "# THIS FILE ADAPTED FROM GraphLayout.jl\n# see https://github.com/IainNZ/GraphLayout.jl\n\n\n\"\"\"\n    Use the spring/repulsion model of Fruchterman and Reingold (1991):\n        Attractive force:  f_a(d) =  d^2 / k\n        Repulsive force:  f_r(d) = -k^2 / d\n    where d is distance between two vertices and the optimal distance\n    between vertices k is defined as C * sqrt( area / num_vertices )\n    where C is a parameter we can adjust\n\n    Arguments:\n    adj_matrix Adjacency matrix of some type. Non-zero of the eltype\n               of the matrix is used to determine if a link exists,\n               but currently no sense of magnitude\n    C          Constant to fiddle with density of resulting layout\n    MAXITER    Number of iterations we apply the forces\n    INITTEMP   Initial \"temperature\", controls movement per iteration\n\"\"\"\nfunction layout_spring_adj(\n    adj_matrix::Array{T,2};\n    C = 2.0,\n    MAXITER = 100,\n    INITTEMP = 2.0,\n) where {T}\n\n    size(adj_matrix, 1) != size(adj_matrix, 2) && error(\"Adj. matrix must be square.\")\n    N = size(adj_matrix, 1)\n\n    # Initial layout is random on the square [-1,+1]^2\n    locs_x = 2 * rand(N) .- 1.0\n    locs_y = 2 * rand(N) .- 1.0\n\n    # The optimal distance bewteen vertices\n    K = C * sqrt(4.0 / N)\n\n    # Store forces and apply at end of iteration all at once\n    force_x = zeros(N)\n    force_y = zeros(N)\n\n    # Iterate MAXITER times\n    @inbounds for iter = 1:MAXITER\n        # Calculate forces\n        for i = 1:N\n            force_vec_x = 0.0\n            force_vec_y = 0.0\n            for j = 1:N\n                i == j && continue\n                d_x = locs_x[j] - locs_x[i]\n                d_y = locs_y[j] - locs_y[i]\n                d = sqrt(d_x^2 + d_y^2)\n                if adj_matrix[i, j] != zero(eltype(adj_matrix)) ||\n                   adj_matrix[j, i] != zero(eltype(adj_matrix))\n                    # F = d^2 / K - K^2 / d\n                    F_d = d / K - K^2 / d^2\n                else\n                    # Just repulsive\n                    # F = -K^2 / d^\n                    F_d = -K^2 / d^2\n                end\n                # d  /          sin θ = d_y/d = fy/F\n                # F /| dy fy    -> fy = F*d_y/d\n                #  / |          cos θ = d_x/d = fx/F\n                # /---          -> fx = F*d_x/d\n                # dx fx\n                force_vec_x += F_d * d_x\n                force_vec_y += F_d * d_y\n            end\n            force_x[i] = force_vec_x\n            force_y[i] = force_vec_y\n        end\n        # Cool down\n        TEMP = INITTEMP / iter\n        # Now apply them, but limit to temperature\n        for i = 1:N\n            force_mag = sqrt(force_x[i]^2 + force_y[i]^2)\n            scale = min(force_mag, TEMP) / force_mag\n            locs_x[i] += force_x[i] * scale\n            #locs_x[i]  = max(-1.0, min(locs_x[i], +1.0))\n            locs_y[i] += force_y[i] * scale\n            #locs_y[i]  = max(-1.0, min(locs_y[i], +1.0))\n        end\n    end\n\n    # Scale to unit square\n    min_x, max_x = minimum(locs_x), maximum(locs_x)\n    min_y, max_y = minimum(locs_y), maximum(locs_y)\n    function scaler(z, a, b)\n        2.0 * ((z - a) / (b - a)) - 1.0\n    end\n    locs_x = map(z -> scaler(z, min_x, max_x), locs_x)\n    locs_y = map(z -> scaler(z, min_y, max_y), locs_y)\n\n    return locs_x, locs_y\nend\n\n\n\n\n\nfunction _spring(G::SimpleGraph{T}, nits::Int = 1000) where {T}\n    n = NV(G)\n    A, vv = private_adj(G)\n\n    d = Dict{T,Vector{Float64}}()\n\n    if n == 0\n        return d\n    end\n\n    if n == 1\n        v = first(vv)\n        d[v] = [0.0, 0.0]\n        return d\n    end\n\n    x, y = layout_spring_adj(A, MAXITER = nits)\n\n    for i = 1:n\n        v = vv[i]\n        d[v] = [x[i], y[i]]\n    end\n    return d\nend\n", "meta": {"hexsha": "138f577165b983153d1adc771e81a34e8bf426b0", "size": 3724, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/embedding/my_spring.jl", "max_stars_repo_name": "willtebbutt/SimpleGraphs.jl", "max_stars_repo_head_hexsha": "c0aaf98c56ef64b75b24e7ff24347c348ce5246c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2015-03-08T00:51:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T18:54:27.000Z", "max_issues_repo_path": "src/embedding/my_spring.jl", "max_issues_repo_name": "willtebbutt/SimpleGraphs.jl", "max_issues_repo_head_hexsha": "c0aaf98c56ef64b75b24e7ff24347c348ce5246c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-08-15T11:25:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T22:46:00.000Z", "max_forks_repo_path": "src/embedding/my_spring.jl", "max_forks_repo_name": "willtebbutt/SimpleGraphs.jl", "max_forks_repo_head_hexsha": "c0aaf98c56ef64b75b24e7ff24347c348ce5246c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-07-04T01:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-11T09:09:06.000Z", "avg_line_length": 29.5555555556, "max_line_length": 86, "alphanum_fraction": 0.5059076262, "num_tokens": 1140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7992153198022389}}
{"text": "gyroid(v) = cos(v[1])*sin(v[2])+cos(v[2])*sin(v[3])+cos(v[3])*sin(v[1])\ngyroid_shell(v) = max(gyroid(v)-0.4,-gyroid(v)-0.4)\nxr,yr,zr = ntuple(_->LinRange(0,pi*4,50),3)\nA = [gyroid_shell((x,y,z)) for x in xr, y in yr, z in zr]\nA[1,:,:] .= 1e10\nA[:,1,:] .= 1e10\nA[:,:,1] .= 1e10\nA[end,:,:] .= 1e10\nA[:,end,:] .= 1e10\nA[:,:,end] .= 1e10\n\nvolume(A, algorithm=:iso, isovalue=0.5, isorange=0.05)\n\n\nusing FFTW\nusing LinearAlgebra\nusing Random\n# Fourier synthesis of an isosurface using 1/f^α noise\nfunction one_on_f_noise(T, α, f)\n    # 2α needed to convert powers to amplitudes here\n    ϵ = sqrt(eps(real(T)))\n    A = randn(T)\n    return convert(T, A / (ϵ + norm(f))^2α)\nend\n\nN = 200\nα = 1.2f0\nRandom.seed!(2)\n# symmetric frequency space\nfx = range(-1,1,length=N)\nfy = reshape(fx,1,:)\nfz = reshape(fx,1,1,:)\nspectrum = one_on_f_noise.(ComplexF32, α, Vec3f0.(fx, fy, fz))\niso = real.(fft(fftshift(spectrum)))\nmini, maxi = extrema(iso)\niso_norm = (iso .- mini) ./ (maxi - mini)\nvolume(iso_norm, algorithm=:iso, isovalue=0.5, isorange=0.05)\n", "meta": {"hexsha": "e7e3db3d537a603b22b188b5c71631173d92aa47", "size": 1032, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/volumes.jl", "max_stars_repo_name": "metanoid/MakieGallery.jl", "max_stars_repo_head_hexsha": "04c51ec1220fa2d6ced47b7f6f80400cb5c6e6ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-20T04:00:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T04:00:43.000Z", "max_issues_repo_path": "examples/volumes.jl", "max_issues_repo_name": "metanoid/MakieGallery.jl", "max_issues_repo_head_hexsha": "04c51ec1220fa2d6ced47b7f6f80400cb5c6e6ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/volumes.jl", "max_forks_repo_name": "metanoid/MakieGallery.jl", "max_forks_repo_head_hexsha": "04c51ec1220fa2d6ced47b7f6f80400cb5c6e6ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1578947368, "max_line_length": 71, "alphanum_fraction": 0.628875969, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7992153084516812}}
{"text": "using Econometrics\n\n# sample size\nn = 30\n\n# draw n values of x between 0 and 4\nx = 0:4/(n-1):4\n\n# true function (unknown to researcher)\nfunction f(x)\n    10 + 3*x - x^2\nend\n\n# derivative of the function\nfunction fprime(x)\n    3 - 2x\nend\n\n# elasticity of the function: marginal function divided by average function\nelasticity = x -> fprime(x)/(f(x)/x)\ne = elasticity.(x) # elasticities at the x values\n\n\n# noisy observation of true function\ny = f.(x) + randn(n) \n# researcher only observes y and x\n\n\n# linear fit and elasticity according to linear fit\nX = [ones(n) x]\nXprime = [zeros(n) ones(n)]\nb, fit, junk = lsfit(y,X)\nelinear = Xprime*b./(fit./x)\n\n# Fourier fit and elasticity\n#X = [ones(n) x cos.(x) sin.(x) cos.(2x) sin.(2x)]\n#Xprime = [zeros(n) ones(n) -sin.(x) cos.(x) -2sin.(2x) 2cos.(2x)]\nX = [ones(n) x cos.(x) sin.(x)]\nXprime = [zeros(n) ones(n) -sin.(x) cos.(x)]\nb, fourierfit, junk = lsfit(y,X)\nefourier = Xprime*b./(fourierfit./x)\n\n\n# plot function and fits\np1 = plot(x,[f.(x) fit fourierfit], title = \"Function and fits\", legend=:bottomleft, label=[\"true\" \"linear\" \"fourier\"])\n\n# plot true elasticities and fits\np2 = plot(x, [e elinear efourier], title = \"Elasticity and fitted elasticities\", legend=:bottomleft, label=[\"true\" \"linear\" \"fourier\"])\n\n\nplot(p1, p2)\n\n\n", "meta": {"hexsha": "29b6bd289ca7f53e9a27fede61cc901fbdd76503", "size": 1280, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/Nonparametric/Elasticity.jl", "max_stars_repo_name": "Hiroakiyusheng/Econometrics", "max_stars_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "Examples/Nonparametric/Elasticity.jl", "max_issues_repo_name": "Hiroakiyusheng/Econometrics", "max_issues_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "Examples/Nonparametric/Elasticity.jl", "max_forks_repo_name": "Hiroakiyusheng/Econometrics", "max_forks_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 23.7037037037, "max_line_length": 135, "alphanum_fraction": 0.66015625, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.8479677545357569, "lm_q1q2_score": 0.7992153080104956}}
{"text": "#=\n   Urn puzzle in Turing.jl\n    \n   From Berlin Bayesians\n   https://app.slack.com/client/TFPMSKW3F/CFQHMRD6K/thread/CFQHMRD6K-1623812230.000500\n   \"\"\"\n   Three urns, first blindly take one from the first and put in the second, \n   then blindly take one from the second and put in the third and then blindly pick \n   one from the third. How likely is it to pick a black one in the last step?\n\n   [\n     Urns\n\n     1: white black black\n     2: white white black\n     3: white black\n\n   ]\n   \"\"\"\n\n   Probability of drawing a black in the last step:\n   Distributions of variable (num:0)\n   0.00000 =>    5273  (0.527300)\n   1.00000 =>    4727  (0.472700)\n\n   (Cf the WebPPL model's exact solution: 0.47222222222222227)\n   \n   Cf ~/webppl/urn_puzzle\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n@model urn_puzzle() = begin\n    white = 1\n    black = 2\n\n    urn1 = [white,black,black]\n    urn2 = [white,white,black]\n    urn3 = [white,black]\n\n    # From urn 1 to urn 2\n    # Note: We have to do this in two steps, i.e.\n    # first pick some integer and then fetch that p1'th ball\n    # from the urn\n    p1 ~ DiscreteUniform(1,length(urn1))\n    urn2b = push!(urn2,urn1[p1])\n\n    # From urn 2 to urn 3\n    p2 ~ DiscreteUniform(1,length(urn2b))\n    urn3b = push!(urn3,urn2b[p2])\n\n    # Pick a ball from urn 3\n    p3 ~ DiscreteUniform(1,length(urn3b))\n    ball = urn3b[p3]\n\n    # Is it black?\n    pblack ~ Dirac(ball==black)\n\nend\n\nmodel = urn_puzzle()\n\nnum_chns = 4\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(15), 10_000)\n# chns = sample(model, SMC(1000), 10_000)\n# chns = sample(model, IS(), 10_000)\n#\n\ndisplay(chns)\n# display(plot(chns))\n\nshow_var_dist_pct(chns,:pblack)\nshow_var_dist_pct(chns,:ball)\n", "meta": {"hexsha": "e167e03e1aee9662451f22386ac8c6566464450d", "size": 1773, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/urn_puzzle.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/urn_puzzle.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/urn_puzzle.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 22.7307692308, "max_line_length": 86, "alphanum_fraction": 0.6520022561, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697694, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7992153034611033}}
{"text": "\"\"\"\nInformation Gain.\n\nThe uncertainty of the starting node, minus the weighted impurity of\ntwo child nodes.\n\"\"\"\nfunction info_gain(left, right, current_uncertainty::Float64)::Float64\n    p = Float64(length(left)) / (length(left) + length(right))\n    current_uncertainty - p * gini(left) - (1 - p) * gini(right)\nend\n", "meta": {"hexsha": "2e2a2dc351845d459b9186a6b73363152d18825d", "size": 316, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/info_gain.jl", "max_stars_repo_name": "bpr/CART.jl", "max_stars_repo_head_hexsha": "02b001d823cd7a47a215a7ee4f8214d3d395716c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/info_gain.jl", "max_issues_repo_name": "bpr/CART.jl", "max_issues_repo_head_hexsha": "02b001d823cd7a47a215a7ee4f8214d3d395716c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/info_gain.jl", "max_forks_repo_name": "bpr/CART.jl", "max_forks_repo_head_hexsha": "02b001d823cd7a47a215a7ee4f8214d3d395716c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7272727273, "max_line_length": 70, "alphanum_fraction": 0.7120253165, "num_tokens": 81, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9615338112885302, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7991721425331727}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.21\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 9947a66a-7fe5-11eb-0955-87881a67fbea\nbegin\n\tusing PlutoUI\n\tusing Plots\n\t\n\t# plotly()\nend\n\n# ╔═╡ 9872b1a8-7fe7-11eb-0b3b-cb6181515182\nusing SymPy\n\n# ╔═╡ 84fc02d6-7fef-11eb-2e21-cb577c3974f0\n# Pkg.add(\"ForwardDiff)\nusing ForwardDiff\n\n# ╔═╡ e529f550-7fe3-11eb-06f8-6beaa1506e66\nmd\"\"\"\n## AutoDiff - Exploration\n\nStatus:\n - ref. 2019-10-26 - ref. [Automatic Differentiation in 10 minutes with Julia](https://www.youtube.com/watch?v=vAp6nUMrKYg)\n - 2021-03-08 moved to `Pluto.jl`\n\n\"\"\"\n\n# ╔═╡ 28aa4e9c-7fe4-11eb-3d87-c5a10540c2c1\nmd\"\"\"\nLet's start with a simple example, the computation of $\\sqrt(x)$ where how autodiff works comes as both a mathematical surprise, and a computing wonder.  \nThe example is the Babylonian algorithm, known to mankind for millenia, to compute $\\sqrt(x)$:\n\n\nrepeat  \n\n   $~~~~t \\leftarrow \\frac{(t + \\frac{x}{t})}{2}$      \n\nuntil t converges to $\\sqrt(x)$   \n\n\nEach iteration has one add and two divides.  \nFor illustration purposes, 10 iterations suffice\n\"\"\"\n\n# ╔═╡ 1ecd40bc-7fe6-11eb-0a2f-cb9964fc5dbf\nmd\"\"\"\n### And now the derivative, almost by magic\n\nIn a few lines of code. No mention of $\\frac{1}{2}$ over  $\\sqrt(x)$. We will use the \"dual number\" denoted as $D$ in what follows, those where invented by the famous algebraist Clifford in 1873.\n\"\"\"\n\n# ╔═╡ 4ac7200c-7fe6-11eb-259a-8d881d2f7e3e\nstruct D <: Number # D is a <function, derivative> pair (a pair of floats)\n    f::Tuple{Float64, Float64}\nend\n\n# ╔═╡ 54f29be2-7fe6-11eb-38c5-d163b159730a\nmd\"\"\"\n- Sum Rule: $(x + y)' = x' + y'$\n- Quotient Rule: $(\\frac{x}{y})' = \\frac{yx' - xy'}{y^2}$\n\"\"\"\n\n# ╔═╡ 6e7efe02-7fe6-11eb-19a7-8b72c0836c8b\nbegin\n\timport Base: +, /, -, *, convert, promote_rule\n\n\t## overload: \n\t+(x::D, y::D) = D(x.f .+ y.f)\n\t/(x::D, y::D) = D((x.f[1] / y.f[1], \n\t\t\t(y.f[1] * x.f[2] - x.f[1] * y.f[2]) / y.f[1]^2))\n\t-(x::D, y::D) = D(x.f .- y.f)\n\t*(x::D, y::D) = D((x.f[1] * y.f[1], (y.f[1] * x.f[2] + x.f[1] * y.f[2])))\n\n\t## convert ordinary number to Dual number, intro. 0 for derivative\n\tconvert(::Type{D}, x::Real) = D((x, zero(x))) \n\t\n\t## then promote...\n\tpromote_rule(::Type{D}, ::Type{<:Number}) = D \nend\n\n# ╔═╡ 7a9389a2-7fe5-11eb-06b8-c52b073c876a\nfunction babylonian(x; n = 10)\n    t = (1. + x) / 2.\n    for i ∈ 2:n\n        t = (t + x/t) / 2.\n    end\n    t\nend\n\n# ╔═╡ 9091553e-7fe5-11eb-2131-9b1b1097c932\nbegin\n\tα = π\n\tbabylonian(α), √α\nend\n\n# ╔═╡ b9ccd308-7fe5-11eb-0b0c-efa652660cd5\nwith_terminal() do\n\tfor α ∈ 2:3\n   \t\tprintln(babylonian(α), \" \", √α)\n\tend\nend\n\n# ╔═╡ ff570916-7fe5-11eb-35ab-e915308e7bfc\n## WARN: first plots require to load package which takes time\n\nbegin\n\tix = 0:.01:49\n\n\tplot([x -> babylonian(x, n=i) for i ∈ 1:5], \n    \tix, \n    \tlabel=[\"Iteration $jx\" for _ ∈ 1:1, jx ∈ 1:5])\n\n\tplot!(sqrt, \n    \tix, \n    \tc=\"darkslateblue\", \n    \tlabel=\"sqrt\", \n    \ttitle = \"Those Babylonian really knew about √\")\nend\n\n# ╔═╡ 732679da-7ff0-11eb-1145-3750276a9601\nbegin\n\tusing LinearAlgebra\n\n\tn = 4\n\tStrang = SymTridiagonal(2 * ones(n), - ones(n-1))\nend\n\n# ╔═╡ 6e64c064-7fe6-11eb-1e6d-3dfeebace21b\nmd\"\"\"\nThe same algorithm with no rewrite at all computes properly the derivative as the check shows:\n\"\"\"\n\n# ╔═╡ 6e487e0e-7fe6-11eb-23a2-35a3a2ed7015\nx₁ = 49; babylonian(D((x₁, 1))), (√x₁, .5 / √x₁)\n\n# ╔═╡ a362fc86-7fe6-11eb-1b7a-03cd0549e790\nx₂ = π; babylonian(D((x₂, 1))), (√x₂, .5 / √x₂)\n\n# ╔═╡ a348cb0e-7fe6-11eb-1c9d-4b4278a367aa\nmd\"\"\"\n#### It just works!\n\nHow does this work?\nWe will explain in a moment. Right now marvel that it does. Note we did not import any autodiff package. Everything is just basic Julia.\n\n\n#### The assembler\n\nMost folks don't read assembler, but one can see that it is short (minus comments). The shortness is a clue that suggests speed!\n\n\"\"\"\n\n# ╔═╡ a32df540-7fe6-11eb-073f-1b34489aa4a0\nwith_terminal() do\n\t@show @inline function babylonian_(x; n = 10)\n    \t t = (1 + x) / 2.\n     \tfor i = 2:n; t = (t + x/t) / 2. end\n     \tt\n \tend\nend\n\n# ╔═╡ a312dfda-7fe6-11eb-0bae-37587f221888\nwith_terminal() do\n\t@code_native babylonian(D((2, 1)))\nend\n\n# ╔═╡ 37574936-7fe7-11eb-132a-2df44bf8d6bb\nmd\"\"\"\n### Symbolically\n\nWe haven't yet explained how it works, but it may be of some value to understand that the below is mathematically equivalent, though not what the computation is doing.\nNotice in the below that babylonian works on SymPy Symbols.\n\nNote: Python and Julia are very good friends.It's not a competition! Watch how nicely we can use the same code now in SymPy.\n\n\"\"\"\n\n# ╔═╡ 98544e52-7fe7-11eb-1094-9382f7126ce4\nwith_terminal()do\n\tx = symbols(\"x\")\n\t\n\tprintln(\"Iterations as a function of x\")\n\tfor k ∈ 1:5\n    \tprintln(simplify(babylonian(x, n=k)))\n\tend\nend\n\n# ╔═╡ 98399af8-7fe7-11eb-1276-13c05fa36ed9\nwith_terminal() do\n\tx = symbols(\"x\")\n\t\n\tprintln(\"Derivatives as a function of x\")\n\t\n\tfor k ∈ 1:5\n    \tprintln(simplify(diff(simplify(babylonian(x, n=k)), x)))\n\tend\nend\n\n# ╔═╡ 981ea264-7fe7-11eb-06ef-97ee66d5619b\nmd\"\"\"\nLet's by hand take the \"derivative\" of the babylonian iteration with respect to x.\n\nSpecifically $t' = \\frac{dt}{dx}$. This is the old fashioned way of a human writing code.  \n\"\"\"\n\n# ╔═╡ d05af69e-7feb-11eb-3874-d1b05fb6434a\nfunction dbabylonian(x; n = 10)\n    t = (1. + x) / 2.\n    dt = 1. / 2.\n    \n    for i ∈ 2:n \n        t = (t + x/t) / 2.\n        dt = (dt + (t - x * dt) / t^2) / 2.\n    end\n    dt\nend\n\n# ╔═╡ d0310bf4-7feb-11eb-2d05-c9531128eb4a\nmd\"\"\"\n\nNote: \n  -  $t = \\frac{1}{2} \\times (t + \\frac{x}{t})$  \n\n  - then $(\\frac{dt}{dx})' = \\frac{1}{2} \\times (t' + \\frac{x' \\times t - x \\times t'}{t^2})$, as $x' = 1$, we get:  \n\n$(\\frac{dt}{dx})' = \\frac{1}{2} \\times (\\frac{t' + (t - x \\times t')}{t^2})$\n\"\"\"\n\n# ╔═╡ d01a58be-7feb-11eb-1f29-6d23db7914da\nx= π; dbabylonian(x), .5 / √x\n\n# ╔═╡ cffee818-7feb-11eb-079b-a7dbfdd8cdd6\nmd\"\"\"\nWhat just happened?  \n\nAnswer: we created an iteration by hand for t' given our iteration for t, Then we ran the iteration alongside the iteration for t.\n\"\"\"\n\n# ╔═╡ d0ca45ac-7fec-11eb-202b-87ae22b66616\nbabylonian(D((x, 1)))\n\n# ╔═╡ d0addd04-7fec-11eb-0213-53ef5d729159\nmd\"\"\"\n\nHow did this work?\n\nIt created the same derivative iteration that we did by hand, using very general rules that are set once and need not be written by hand (and multiple dispatch).\n\nImportant: the derivative is substituted before the JIT compiler, and thus efficient compiled code is executed.\n\"\"\"\n\n# ╔═╡ d092a21e-7fec-11eb-0cc1-d1515675f521\nmd\"\"\"\n### Dual Number Notation\n\nInstead of $D(a, b)$ we can write: $a + b \\epsilon$ where $\\epsilon$ satisfies $\\epsilon^2 = 0$. Some people like to recall imaginary numbers where an $i$ is introduced with $i^2 = -1$. Others like to think of how engineers just fdrop the $O(\\epsilon^2)$ terms.  \n\nThe four rules are:  \n  - 1 & 2. $(a + b\\epsilon) \\pm (c + d\\epsilon) = (a + c) \\pm (b + d)\\epsilon$\n  - 3.$(a + b\\epsilon) \\times (c + d\\epsilon) = (ac) + (bc + ad)\\epsilon$\n  - 4.$\\frac{(a + b\\epsilon)}{(c + d\\epsilon)} = (\\frac{a}{c}) + \\frac{(bc - ad)}{d^2}\\epsilon$\n\n\"\"\"\n\n# ╔═╡ 1818fb9c-7fed-11eb-0bd3-21411f08fcdf\nBase.show(io::IO, x::D) = print(io, x.f[1], \" + \", x.f[2], \" ϵ\")\n\n# ╔═╡ 14125e9c-7fef-11eb-3dc4-a75f84383d5d\nD((1, 0))\n\n# ╔═╡ 13e452cc-7fef-11eb-2e1d-a5e3b9936a4c\nD((0, 2))^2 # should be zero!\n\n# ╔═╡ 13ab59ea-7fef-11eb-2078-6d8ee11d1c90\nD((2, 1))^2\n\n# ╔═╡ 2886e6c4-7fef-11eb-0fff-9b3033e4f943\nbegin\n\tϵ = D((0, 1))\n\twith_terminal() do\n\t\t@code_native(ϵ^2)\n\tend\nend\n\n# ╔═╡ 3f1f4bba-7fef-11eb-2f39-cf906aec10ae\nϵ * ϵ\n\n# ╔═╡ 3f037186-7fef-11eb-200f-3579d0ab8e1f\nϵ^2\n\n# ╔═╡ 3eea0d36-7fef-11eb-3ede-c7d54243194c\n(1 + ϵ)^5 # note it just works (we did not train powers)\n\n# ╔═╡ 3ece19f8-7fef-11eb-3b91-ff25fd3ca8f4\nmd\"\"\"\n### Generalization to arbitrary roots\n\"\"\"\n\n# ╔═╡ 3eb0843a-7fef-11eb-2c67-9ba2e4d1eefc\nfunction nth_root(x, n=2; t=1, p=10)\n    for i = 1:p\n        t += (x / t^(n-1) - t) / n\n    end\n    t\nend\n\n# ╔═╡ 5c9fbbc6-7fef-11eb-32ad-b986ca56aa9b\nnth_root(2, 3), ∛2  # copied from https://www.alt-codes.net/root-symbols\n\n# ╔═╡ 5c84a84c-7fef-11eb-3117-01f1842890f5\nnth_root(2 + ϵ, 3)\n\n# ╔═╡ 5c665cd4-7fef-11eb-2c89-e153a973b30e\nnth_root(7, 12), 7^(1/12)\n\n# ╔═╡ 5c4f64ac-7fef-11eb-1864-13f293e85fc4\nlet x = 2.0\n\tnth_root( x + ϵ), ∛x, 1/x*(2/3)/3\nend\n\n# ╔═╡ 5c33d6ce-7fef-11eb-12c1-29396395358d\nmd\"\"\"\n### Forward Diff\n\nNow that you understand it, you can use the official package.\n\"\"\"\n\n# ╔═╡ 84ddd280-7fef-11eb-29cb-3fc8c8547134\nForwardDiff.derivative(sqrt, 2)\n\n# ╔═╡ 916346b8-7fef-11eb-0d53-29bd11c34510\nForwardDiff.derivative(babylonian, 2)\n\n# ╔═╡ 99672fe6-7fef-11eb-305e-d98ce4bc8dc1\nwith_terminal() do\n\tprintln(@which ForwardDiff.derivative(√, 2))\nend\n\n# ╔═╡ be076e8a-7fef-11eb-0741-79beea838677\nmd\"\"\"\n### Close Look at Convergence with big floats\n\nthe $-log10$ gives the number of correct digits. Watch the quadratic convergence right before your eyes.\n\"\"\"\n\n# ╔═╡ d5b96cac-7fef-11eb-0772-551e4d96efb2\nwith_terminal() do\n\tsetprecision(3000)\n\n\t# round.(Float64.(log10.([babylonian(BigFloat(2), n=k) for k=1:10] - √BigFloat(2))), 3)\n\tprintln(round.(Float64.(log10.([babylonian(BigFloat(2), n=k) - √BigFloat(2.) for k=1:10])), sigdigits=6))\nend\n\n# ╔═╡ d59d0508-7fef-11eb-20a3-3f108b859670\nstruct D1{T} <: Number # D is a <function, derivative> pair\n    f::Tuple{T, T}\nend\n\n# ╔═╡ d57e75ac-7fef-11eb-1cc7-db506a7e4e2f\nbegin\n\tz = D((2., 1.))\n\tz₁ = D1((BigFloat(2.), BigFloat(1.)))\nend\n\n# ╔═╡ fbb04502-7fef-11eb-28fd-414c2f982855\n# begin\n# \t#import Base: +, /, convert, promote_rule\n\t\n# \t## overload: \n# \t+(x::D1, y::D1) = D1(x.f .+ y.f)\n# \t/(x::D1, y::D1) = D1((x.f[1] / y.f[1], (y.f[1] * x.f[2] - x.f[1] * y.f[2]) / y.f[1]^2))\n\n# \tconvert(::Type{D1{T}}, x::Real) where {T} = D1((convert(T, x), zero(T))) \n# \tpromote_rule(::Type{D1{T}}, ::Type{S}) where {T, S <: Number} = D1{promote_type(T, S)} \n# end\n\n# ╔═╡ 3e2da118-7ff0-11eb-36ca-e32af03b2a0c\nA = randn(3, 3)\n\n# ╔═╡ 3e0a484e-7ff0-11eb-17be-e9e7aa66fb2c\nx₃= randn(3)\n\n# ╔═╡ 3dd5c57e-7ff0-11eb-3330-cf7d02b5c632\nForwardDiff.gradient(x -> x'A*x, x₃)\n\n# ╔═╡ Cell order:\n# ╟─e529f550-7fe3-11eb-06f8-6beaa1506e66\n# ╠═9947a66a-7fe5-11eb-0955-87881a67fbea\n# ╟─28aa4e9c-7fe4-11eb-3d87-c5a10540c2c1\n# ╠═7a9389a2-7fe5-11eb-06b8-c52b073c876a\n# ╠═9091553e-7fe5-11eb-2131-9b1b1097c932\n# ╠═b9ccd308-7fe5-11eb-0b0c-efa652660cd5\n# ╠═ff570916-7fe5-11eb-35ab-e915308e7bfc\n# ╟─1ecd40bc-7fe6-11eb-0a2f-cb9964fc5dbf\n# ╠═4ac7200c-7fe6-11eb-259a-8d881d2f7e3e\n# ╟─54f29be2-7fe6-11eb-38c5-d163b159730a\n# ╠═6e7efe02-7fe6-11eb-19a7-8b72c0836c8b\n# ╟─6e64c064-7fe6-11eb-1e6d-3dfeebace21b\n# ╠═6e487e0e-7fe6-11eb-23a2-35a3a2ed7015\n# ╠═a362fc86-7fe6-11eb-1b7a-03cd0549e790\n# ╟─a348cb0e-7fe6-11eb-1c9d-4b4278a367aa\n# ╠═a32df540-7fe6-11eb-073f-1b34489aa4a0\n# ╠═a312dfda-7fe6-11eb-0bae-37587f221888\n# ╟─37574936-7fe7-11eb-132a-2df44bf8d6bb\n# ╠═9872b1a8-7fe7-11eb-0b3b-cb6181515182\n# ╠═98544e52-7fe7-11eb-1094-9382f7126ce4\n# ╠═98399af8-7fe7-11eb-1276-13c05fa36ed9\n# ╟─981ea264-7fe7-11eb-06ef-97ee66d5619b\n# ╠═d05af69e-7feb-11eb-3874-d1b05fb6434a\n# ╟─d0310bf4-7feb-11eb-2d05-c9531128eb4a\n# ╠═d01a58be-7feb-11eb-1f29-6d23db7914da\n# ╟─cffee818-7feb-11eb-079b-a7dbfdd8cdd6\n# ╠═d0ca45ac-7fec-11eb-202b-87ae22b66616\n# ╟─d0addd04-7fec-11eb-0213-53ef5d729159\n# ╟─d092a21e-7fec-11eb-0cc1-d1515675f521\n# ╠═1818fb9c-7fed-11eb-0bd3-21411f08fcdf\n# ╠═14125e9c-7fef-11eb-3dc4-a75f84383d5d\n# ╠═13e452cc-7fef-11eb-2e1d-a5e3b9936a4c\n# ╠═13ab59ea-7fef-11eb-2078-6d8ee11d1c90\n# ╠═2886e6c4-7fef-11eb-0fff-9b3033e4f943\n# ╠═3f1f4bba-7fef-11eb-2f39-cf906aec10ae\n# ╠═3f037186-7fef-11eb-200f-3579d0ab8e1f\n# ╠═3eea0d36-7fef-11eb-3ede-c7d54243194c\n# ╟─3ece19f8-7fef-11eb-3b91-ff25fd3ca8f4\n# ╠═3eb0843a-7fef-11eb-2c67-9ba2e4d1eefc\n# ╠═5c9fbbc6-7fef-11eb-32ad-b986ca56aa9b\n# ╠═5c84a84c-7fef-11eb-3117-01f1842890f5\n# ╠═5c665cd4-7fef-11eb-2c89-e153a973b30e\n# ╠═5c4f64ac-7fef-11eb-1864-13f293e85fc4\n# ╟─5c33d6ce-7fef-11eb-12c1-29396395358d\n# ╠═84fc02d6-7fef-11eb-2e21-cb577c3974f0\n# ╠═84ddd280-7fef-11eb-29cb-3fc8c8547134\n# ╠═916346b8-7fef-11eb-0d53-29bd11c34510\n# ╠═99672fe6-7fef-11eb-305e-d98ce4bc8dc1\n# ╟─be076e8a-7fef-11eb-0741-79beea838677\n# ╠═d5b96cac-7fef-11eb-0772-551e4d96efb2\n# ╠═d59d0508-7fef-11eb-20a3-3f108b859670\n# ╠═d57e75ac-7fef-11eb-1cc7-db506a7e4e2f\n# ╠═fbb04502-7fef-11eb-28fd-414c2f982855\n# ╠═3e2da118-7ff0-11eb-36ca-e32af03b2a0c\n# ╠═3e0a484e-7ff0-11eb-17be-e9e7aa66fb2c\n# ╠═3dd5c57e-7ff0-11eb-3330-cf7d02b5c632\n# ╠═732679da-7ff0-11eb-1145-3750276a9601\n", "meta": {"hexsha": "0dfa799da4fe4b773eede44fc0e65c4df3d16efb", "size": 12273, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "AutoDiff.jl", "max_stars_repo_name": "pascal-p/julia-notebooks", "max_stars_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-01T20:34:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-01T20:34:56.000Z", "max_issues_repo_path": "AutoDiff.jl", "max_issues_repo_name": "pascal-p/julia-notebooks", "max_issues_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AutoDiff.jl", "max_forks_repo_name": "pascal-p/julia-notebooks", "max_forks_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-10T09:03:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T09:03:18.000Z", "avg_line_length": 27.3950892857, "max_line_length": 263, "alphanum_fraction": 0.6696814145, "num_tokens": 5951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.9161096187428011, "lm_q1q2_score": 0.7991658269083421}}
{"text": "### A Pluto.jl notebook ###\n# v0.18.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 321b951c-9bea-11ec-0d10-31f76d44cc9e\nmd\"\"\"\n# HW 7\n\nEric Nguyen\n\"\"\"\n\n# ╔═╡ 710b2cc8-45e7-4eee-9066-3fd4080aebc9\nmd\"\"\"\n### Problem 1\n\nFirst we start with the Cartesian coordinates ``x``, ``y``, and ``z`` in terms of spherical coordinates,\n\n$\\begin{align*}\nx &= r \\sin{\\theta} \\cos{\\phi} \\\\\ny &= r \\sin{\\theta} \\sin{\\phi} \\\\\nz &= r \\cos{\\theta}\n\\end{align*}$\n\nImagine that we change the position ``\\vec{r}`` by a tiny ``d\\vec{r} = dx \\, \\hat{i} + dy \\, \\hat{j} + dz \\, \\hat{k}`` such that ``x``, ``y``, and ``z`` change by infinitesimal amounts,\n\n$\\begin{align*}\ndx &= \\sin{\\theta} \\cos{\\phi} \\,dr + r \\cos{\\theta} \\cos{\\phi} \\,d\\theta - r \\sin{\\theta} \\sin{\\phi} \\,d\\phi \\\\\ndy &= \\sin{\\theta} \\sin{\\phi} \\,dr + r \\cos{\\theta} \\sin{\\phi} \\,d\\theta + r \\sin{\\theta} \\cos{\\phi} \\,d\\phi \\\\\ndz &= \\cos{\\theta} \\,dr - r \\sin{\\theta} \\,d\\theta\n\\end{align*}$\n\nConsider the change ``d\\vec{r}`` in the ``r,\\theta,\\phi`` directions found by setting the infinitesimals equal to zero accordingly (e.g., for ``\\hat{r}`` set ``d\\theta = d\\phi = 0``, etc.),\n\n$\\begin{align*}\nd\\vec{r}_r &= \\hat{i} \\sin{\\theta} \\cos{\\phi} \\,dr + \\hat{j} \\sin{\\theta} \\sin{\\phi} \\,dr + \\hat{k} \\cos{\\theta} \\,dr \\\\\n&= (\\hat{i} \\sin{\\theta} \\cos{\\phi} + \\hat{j} \\sin{\\theta} \\sin{\\phi} + \\hat{k} \\cos{\\theta}) \\,dr \\\\\nd\\vec{r}_{\\theta} &= \\hat{i} r \\cos{\\theta} \\cos{\\phi} \\,d\\theta + \\hat{j} r \\cos{\\theta} \\sin{\\phi} \\,d\\theta - \\hat{k} r \\cos{\\theta} \\,d\\theta \\\\\n&= (\\hat{i} \\cos{\\theta} \\cos{\\phi} + \\hat{j} \\cos{\\theta} \\sin{\\phi} - \\hat{k} \\sin{\\theta}) r \\,d\\theta \\\\\nd\\vec{r}_{\\phi} &= \\hat{i} r \\sin{\\theta} \\sin{\\phi} \\,d\\phi + \\hat{j} r \\sin{\\theta} \\cos{\\phi} \\,d\\phi \\\\\n&= (\\hat{i} \\sin{\\phi} + \\hat{j} \\cos{\\phi}) r \\sin{\\theta} \\,d\\phi\n\\end{align*}$\n\nIt follows that the unit vectors in the spherical polar coordinates are\n\n$\\begin{align*}\n\\hat{r} &= \\hat{i} \\sin{\\theta} \\cos{\\phi} + \\hat{j} \\sin{\\theta} \\sin{\\phi} + \\hat{k} \\cos{\\theta} \\\\\n\\hat{\\theta} &= \\hat{i} \\cos{\\theta} \\cos{\\phi} + \\hat{j} \\cos{\\theta} \\sin{\\phi} - \\hat{k} \\sin{\\theta} \\\\\n\\hat{\\phi} &= \\hat{i} \\sin{\\phi} + \\hat{j} \\cos{\\phi}\n\\end{align*}$\n\"\"\"\n\n# ╔═╡ 370b6a47-79b6-41e3-ad41-01544affa97d\nmd\"\"\"\n### Problem 2\n\nUsing ``\\vec{v} = \\frac{d\\vec{r}}{dt}``, rewrite the expression for kinetic energy as\n\n$K = \\frac{1}{2} m \\left(\\vec{v} ⋅ \\vec{v}\\right) = \\frac{1}{2} m \\left(\\sqrt{{v_x}^2 + {v_y}^2 + {v_z}^2}\\right)^2 = \\frac{1}{2} m ({v_x}^2 + {v_y}^2 + {v_z}^2)$\n\nWe start with the transformation equations for the Cartesian coordinates,\n\n$\\begin{align*}\nx &= r \\sin{\\theta} \\cos{\\phi} \\\\\ny &= r \\sin{\\theta} \\sin{\\phi} \\\\\nz &= r \\cos{\\theta}\n\\end{align*}$\n\nTake the time derivative for each coordinate (i.e., find expressions for the components of ``\\vec{v}``):\n\n$\\begin{align*}\nv_x &= ẋ = \\sin{\\theta} \\cos{\\phi} \\, ṙ + r \\cos{\\theta} \\cos{\\phi} \\,\\dot{\\theta} - r \\sin{\\theta} \\sin{\\phi} \\,\\dot{\\phi} \\\\\nv_y &= ẏ = \\sin{\\theta} \\sin{\\phi} \\, ṙ + r \\cos{\\theta} \\sin{\\phi} \\,\\dot{\\theta} + r \\sin{\\theta} \\cos{\\phi} \\, \\dot{\\phi} \\\\\nv_z &= ż = \\cos{\\theta} \\,ṙ - r \\sin{\\theta} \\,\\dot{\\theta}\n\\end{align*}$\n\nGoing back to the expression for kinetic energy, we can write the velocity expression in terms of ``r``, ``\\theta``, and ``\\phi`` and simplify.\nFirst, we square each velocity component:\n\n$\\begin{align*}\n{v_x}^2 &= (\\sin{\\theta} \\cos{\\phi} \\, ṙ + r \\cos{\\theta} \\cos{\\phi} \\,\\dot{\\theta} - r \\sin{\\theta} \\sin{\\phi} \\,\\dot{\\phi})^2 \\\\\n&= \\sin{\\theta}^2 \\cos^2{\\phi} \\, ṙ^2 + r^2 \\cos^2{\\theta} \\cos^2{\\phi} \\,\\dot{\\theta}^2 + r^2 \\sin^2{\\theta} \\sin^2{\\phi} \\,\\dot{\\phi}^2 \\\\\n&\\quad + 2r \\sin{\\theta} \\cos{\\theta} \\cos^2{\\phi} \\,ṙ \\,\\dot{\\theta} - 2r \\sin^2{\\theta} \\sin{\\phi} \\cos{\\phi} \\,ṙ \\,\\dot{\\phi} \\\\\n&\\quad - 2r \\sin{\\theta} \\cos{\\theta} \\sin{\\phi} \\cos{\\phi} \\,\\dot{\\theta} \\,\\dot{\\phi} \\\\\n\\\\\n{v_y}^2 &= (\\sin{\\theta} \\sin{\\phi} \\, ṙ + r \\cos{\\theta} \\sin{\\phi} \\,\\dot{\\theta} + r \\sin{\\theta} \\cos{\\phi} \\, \\dot{\\phi})^2 \\\\\n&= \\sin^2{\\theta} \\sin^2{\\phi} \\,ṙ^2 + r^2 \\cos^2{\\theta} \\sin^2{\\phi} \\,\\dot{\\theta}^2 + r^2 \\sin^2{\\theta} \\cos^2{\\phi} \\,\\dot{\\phi}^2 \\\\\n&\\quad + 2r \\sin{\\theta} \\cos{\\theta} \\sin^2{\\phi} \\,ṙ \\,\\dot{\\theta} + 2r \\sin^2{\\theta} \\sin{\\phi} \\cos{\\phi} \\,ṙ \\,\\dot{\\phi} \\\\\n&\\quad + 2r \\sin{\\theta} \\cos{\\theta} \\sin{\\phi} \\cos{\\phi} \\,\\dot{\\theta} \\,\\dot{\\phi} \\\\\n\\\\\n{v_z}^2 &= (\\cos{\\theta} \\,ṙ - r \\sin{\\theta} \\,\\dot{\\theta})^2 \\\\\n&= \\cos^2{\\theta} \\,ṙ^2 + r^2 \\sin^2{\\theta} \\,\\dot{\\theta}^2 - 2r \\sin{\\theta} \\cos{\\theta} \\,ṙ \\,\\dot{\\theta}\n\\end{align*}$\n\nAdding the terms together, we get:\n\n$\\begin{align*}\n{v_x}^2 + {v_y}^2 + {v_z}^2 &= \\sin{\\theta}^2 \\cos^2{\\phi} \\, ṙ^2 + r^2 \\cos^2{\\theta} \\cos^2{\\phi} \\,\\dot{\\theta}^2 + r^2 \\sin^2{\\theta} \\sin^2{\\phi} \\,\\dot{\\phi}^2 \\\\\n&\\quad + 2r \\sin{\\theta} \\cos{\\theta} \\cos^2{\\phi} \\,ṙ \\,\\dot{\\theta} - 2r \\sin^2{\\theta} \\sin{\\phi} \\cos{\\phi} \\,ṙ \\,\\dot{\\phi} \\\\\n&\\quad - 2r \\sin{\\theta} \\cos{\\theta} \\sin{\\phi} \\cos{\\phi} \\,\\dot{\\theta} \\,\\dot{\\phi} \\\\\n&\\quad + \\sin^2{\\theta} \\sin^2{\\phi} \\,ṙ^2 + r^2 \\cos^2{\\theta} \\sin^2{\\phi} \\,\\dot{\\theta}^2 + r^2 \\sin^2{\\theta} \\cos^2{\\phi} \\,\\dot{\\phi}^2 \\\\\n&\\quad + 2r \\sin{\\theta} \\cos{\\theta} \\sin^2{\\phi} \\,ṙ \\,\\dot{\\theta} + 2r \\sin^2{\\theta} \\sin{\\phi} \\cos{\\phi} \\,ṙ \\,\\dot{\\phi} \\\\\n&\\quad + 2r \\sin{\\theta} \\cos{\\theta} \\sin{\\phi} \\cos{\\phi} \\,\\dot{\\theta} \\,\\dot{\\phi} \\\\\n&\\quad + \\cos^2{\\theta} \\,ṙ^2 + r^2 \\sin^2{\\theta} \\,\\dot{\\theta}^2 - 2r \\sin{\\theta} \\cos{\\theta} \\,ṙ \\,\\dot{\\theta} \\\\\n\n&= \\sin{\\theta}^2 \\cos^2{\\phi} \\, ṙ^2 + r^2 \\cos^2{\\theta} \\cos^2{\\phi} \\,\\dot{\\theta}^2 + r^2 \\sin^2{\\theta} \\sin^2{\\phi} \\,\\dot{\\phi}^2 \\\\\n&\\quad + \\sin^2{\\theta} \\sin^2{\\phi} \\,ṙ^2 + r^2 \\cos^2{\\theta} \\sin^2{\\phi} \\,\\dot{\\theta}^2 + r^2 \\sin^2{\\theta} \\cos^2{\\phi} \\,\\dot{\\phi}^2 \\\\\n&\\quad + \\cos^2{\\theta} \\,ṙ^2 + r^2 \\sin^2{\\theta} \\,\\dot{\\theta}^2 \\\\\n\n&= \\sin^2{\\theta} \\,ṙ^2 + r^2 \\cos^2{\\theta} \\,\\dot{\\theta}^2 + r^2 \\sin^2{\\theta} \\,\\dot{\\phi}^2 \\\\\n&\\quad + \\cos^2{\\theta} \\,ṙ^2 + r^2 \\sin^2{\\theta} \\,\\dot{\\theta}^2 \\\\\n\n&= ṙ^2 + r^2 \\, \\dot{\\theta}^2 + r^2 \\sin^2{\\theta} \\,\\dot{\\phi}^2\n\\end{align*}$\n\nSubstitute the result into the expression for kinetic energy:\n\n$K = \\frac{1}{2} m (ṙ^2 + r^2 \\, \\dot{\\theta}^2 + r^2 \\sin^2{\\theta} \\,\\dot{\\phi}^2)$\n\"\"\"\n\n# ╔═╡ a1799513-6a61-4443-8ec7-428c0696bc5f\nmd\"\"\"\n### Problem 3\n\n**(a).**\nThe square of the magnitude of the cross product ``|\\vec{A} × \\vec{B}|^2`` is\n\n$\\begin{align*}\n|\\vec{A} × \\vec{B}|^2 &= (A_y B_z - A_z B_y)^2 |\\hat{i}| + (A_z B_x - A_x B_z)^2 |\\hat{j}| + (A_x B_y - A_y B_x)^2 |\\hat{k}| \\\\\n&= {A_y}^2 {B_z}^2 + {A_z}^2 {B_y}^2 - 2 A_y A_z B_y B_z \\\\\n&\\quad + {A_z}^2 {B_x}^2 + {A_x}^2 {B_z}^2 - 2 A_x A_z B_x B_z \\\\\n&\\quad + {A_x}^2 {B_y}^2 + {A_y}^2 {B_x}^2 - 2 A_x A_y B_x B_y \\\\\n\\end{align*}$\n\nThe square of the magnitude of ``|\\vec{A}|^2`` and ``|\\vec{B}|^2`` are\n\n$\\begin{align*}\n|\\vec{A}|^2 &= {A_x}^2 + {A_y}^2 + {A_z}^2 \\\\\n|\\vec{B}|^2 &= {B_x}^2 + {B_y}^2 + {B_z}^2\n\\end{align*}$\n\nThe product ``|\\vec{A}|^2 |\\vec{B}|^2`` is then\n\n$\\begin{align*}\n|\\vec{A}|^2 |\\vec{B}|^2 &= ({A_x}^2 + {A_y}^2 + {A_z}^2)({B_x}^2 + {B_y}^2 + {B_z}^2) \\\\\n&= {A_x}^2 {B_x}^2 + {A_x}^2 {B_y}^2 + {A_x}^2 {B_z}^2 \\\\\n&\\quad + {A_y}^2 {B_x}^2 + {A_y}^2 {B_y}^2 + {A_y}^2 {B_z}^2 \\\\\n&\\quad + {A_z}^2 {B_x}^2 + {A_z}^2 {B_y}^2 + {A_z}^2 {B_z}^2 \\\\\n\\end{align*}$\n\nThe square of the magnitude of ``(\\vec{A} ⋅ \\vec{B})^2`` is\n\n$\\begin{align*}\n(\\vec{A} ⋅ \\vec{B})^2 &= (A_x B_x + A_y B_y + A_z B_z)^2 \\\\\n&= {A_x}^2 {B_x}^2 + {A_y}^2 {B_y}^2 + {A_z}^2 {B_z}^2 \\\\\n&\\quad + 2 A_x A_y B_x B_y + 2 A_x A_z B_x B_z + 2 A_y A_z B_y B_z\n\\end{align*}$\n\nNotice that\n\n$|\\vec{A}|^2 |\\vec{B}|^2 - (\\vec{A} ⋅ \\vec{B})^2 = |\\vec{A} × \\vec{B}|^2$\n\nThus,\n\n$|\\vec{A} × \\vec{B}|^2 = |\\vec{A}|^2 |\\vec{B}|^2 - (\\vec{A} ⋅ \\vec{B})^2$\n\"\"\"\n\n# ╔═╡ 08ef5ce6-9d82-4758-ade2-4ea62b514451\nmd\"\"\"\n**(b).**\nUsing components, summation ceonvention, and the relationship between the totally antisymmetric symbol and the Kronecker delta it's possible to arrive at the same expression.\n\n$\\begin{align*}\n|\\vec{A} × \\vec{B}|^2 &= (\\epsilon_{ijk} \\hat{e}_i A_j B_k) ⋅ (\\epsilon_{ℓmn} \\hat{e}_ℓ A_m B_n) \\\\\n&= A_j B_k A_m B_n \\epsilon_{ijk} \\epsilon_{ℓmn} \\delta_{iℓ} \\\\\n&= A_j B_k A_m B_n \\epsilon_{ijk} \\epsilon_{imn} \\\\\n&= A_j B_k A_m B_n (\\delta_{jm} \\delta_{kn} - \\delta_{jn} \\delta_{km}) \\\\\n&= \\sum_{jkmn} A_j B_k A_m B_n \\delta_{jm} \\delta_{kn} - \\sum_{jkmn} A_j B_k A_m B_n \\delta_{jn} \\delta_{km} \\\\\n&= \\sum_{jm} A_j A_m \\delta_{jm} \\sum_{kn} B_k B_n \\delta_{kn} - \\sum_{jn} A_j B_m \\delta_{jn} \\sum_{km} A_m B_k \\delta_{km} \\\\\n&= (\\vec{A} ⋅ \\vec{A}) (\\vec{B} ⋅ \\vec{B}) - (\\vec{A} ⋅ \\vec{B}) (\\vec{A} ⋅ \\vec{B}) \\\\\n&= |\\vec{A}|^2 |\\vec{B}|^2 - (\\vec{A} ⋅ \\vec{B})^2\n\\end{align*}$\n\"\"\"\n\n# ╔═╡ c0971a8a-7d86-4cb6-aae9-5423beeb1da4\nmd\"\"\"\n### Problem 4\n\nFrom Problem (1) I showed that\n\n$\\begin{align*}\nd\\vec{r}_{r} &= (\\hat{i} \\sin{\\theta} \\cos{\\phi} + \\hat{j} \\sin{\\theta} \\sin{\\phi} + \\hat{k} \\cos{\\theta}) \\,dr = \\,dr \\,\\hat{r} \\\\\nd\\vec{r}_{\\theta} &= (\\hat{i} \\cos{\\theta} \\cos{\\phi} + \\hat{j} \\cos{\\theta} \\sin{\\phi} - \\hat{k} \\sin{\\theta}) r \\,d\\theta = r \\,d\\theta \\,\\hat{\\theta}  \\\\\nd\\vec{r}_{\\phi} &= (\\hat{i} \\sin{\\phi} + \\hat{j} \\cos{\\phi}) r \\sin{\\theta} \\,d\\phi = r \\sin{\\theta} \\,d\\phi \\,\\hat{\\phi}\n\\end{align*}$\n\nThis shows that when moving in the ``r``-direction only, the derivative is ``\\frac{∂}{∂r}``, in the ``\\theta``-direction, the derivative is ``\\frac{1}{r} \\frac{∂}{∂\\theta}``, and in the ``\\phi``-direction, the derivative is ``\\frac{1}{r \\sin{\\theta}} \\frac{∂}{∂\\phi}``.\nThe gradient in spherical coordinates is then\n\n$\\vec{∇} = \\hat{r} \\frac{∂}{∂r} + \\hat{\\theta} \\frac{1}{r} \\frac{∂}{∂\\theta} + \\hat{\\phi} \\frac{1}{r \\sin{\\theta}} \\frac{∂}{∂\\phi}$\n\"\"\"\n\n# ╔═╡ 74bea6fd-90e1-4aad-bb58-50b141eb0255\nmd\"\"\"\n### Problem 5\n\nFrom the notes, it is given\n\n$\\begin{align*}\n\\hat{r} &= \\hat{i} \\cos{\\phi} + \\hat{j} \\sin{\\phi} \\\\\n\\hat{\\phi} &= -\\hat{i} \\sin{\\phi} + \\hat{j} \\cos{\\phi}\n\\end{align*}$\n\nThe partial derivatives of each unit vector with respect to ``\\phi`` are\n\n$\\begin{align*}\n\\frac{∂\\hat{r}}{∂\\phi} &= -\\hat{i} \\sin{\\phi} + \\hat{j} \\cos{\\phi} = \\hat{\\phi} \\\\\n\\frac{∂\\hat{\\phi}}{∂\\phi} &= -\\hat{i} \\cos{\\phi} - \\hat{j} \\sin{\\phi} = \\hat{r}\n\\end{align*}$\n\nProceeding with the derivation, the result is\n\n$\\begin{align*}\n\\vec{∇}^2 f(r,\\phi) &= \\vec{∇} ⋅ \\vec{∇} f(r,\\phi) \\\\\n&= \\left(\\hat{r} \\frac{∂}{∂r} + \\hat{\\phi} \\frac{1}{r} \\frac{∂}{∂\\phi}\\right) ⋅ \\left(\\hat{r} \\frac{∂f}{∂r} + \\hat{\\phi} \\frac{1}{r} \\frac{∂f}{∂\\phi}\\right) \\\\\n&= \\hat{r} \\frac{∂}{∂r} \\left(\\hat{r} \\frac{∂f}{∂r} + \\hat{\\phi} \\frac{1}{r} \\frac{∂f}{∂\\phi}\\right) + \\hat{\\phi} \\frac{1}{r} \\frac{∂}{∂\\phi} \\left(\\hat{r} \\frac{∂f}{∂r} + \\hat{\\phi} \\frac{1}{r} \\frac{∂f}{∂\\phi}\\right) \\\\\n&= \\hat{r} \\left(\\hat{r} \\frac{∂^2f}{∂r^2} - \\hat{\\phi} \\frac{1}{r^2} \\frac{∂f}{∂\\phi} + \\hat{\\phi} \\frac{1}{r} \\frac{∂f}{∂\\phi ∂r}\\right) \\\\\n&\\quad + \\hat{\\phi} \\frac{1}{r} \\left(\\hat{\\phi} \\frac{∂f}{∂r} + \\hat{r} \\frac{∂f}{∂r ∂\\phi} - \\hat{r} \\frac{1}{r} \\frac{∂f}{∂\\phi} + \\hat{\\phi} \\frac{1}{r} \\frac{∂^2 f}{∂\\phi^2}\\right) \\\\\n&= \\frac{∂^2f}{∂r^2} + \\frac{1}{r} \\frac{∂f}{∂r} + \\frac{1}{r^2} \\frac{∂^2 f}{∂\\phi^2} \\\\\n&= \\frac{1}{r} \\frac{∂}{∂r} \\left(r \\frac{∂f}{∂r}\\right) + \\frac{1}{r^2} \\frac{∂^2 f}{∂\\phi^2}\n\\end{align*}$\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\njulia_version = \"1.7.1\"\nmanifest_format = \"2.0\"\n\n[deps]\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─321b951c-9bea-11ec-0d10-31f76d44cc9e\n# ╟─710b2cc8-45e7-4eee-9066-3fd4080aebc9\n# ╟─370b6a47-79b6-41e3-ad41-01544affa97d\n# ╟─a1799513-6a61-4443-8ec7-428c0696bc5f\n# ╟─08ef5ce6-9d82-4758-ade2-4ea62b514451\n# ╟─c0971a8a-7d86-4cb6-aae9-5423beeb1da4\n# ╟─74bea6fd-90e1-4aad-bb58-50b141eb0255\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "372e26f3dfd12321a6841667202780aab64bd3f4", "size": 11927, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "homework-07.jl", "max_stars_repo_name": "airicbear/PHYS2502", "max_stars_repo_head_hexsha": "11d7b3de67e6152735abfeff8fa9295b932004ba", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework-07.jl", "max_issues_repo_name": "airicbear/PHYS2502", "max_issues_repo_head_hexsha": "11d7b3de67e6152735abfeff8fa9295b932004ba", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework-07.jl", "max_forks_repo_name": "airicbear/PHYS2502", "max_forks_repo_head_hexsha": "11d7b3de67e6152735abfeff8fa9295b932004ba", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.8730769231, "max_line_length": 269, "alphanum_fraction": 0.5505994802, "num_tokens": 5699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.8757869851639066, "lm_q1q2_score": 0.7990997203946365}}
{"text": "using SequenceTransformations, Polynomials # use my Polynomials fork Pkg.clone(\"https://github.com/MikaelSlevinsky/Polynomials.jl.git\")\n\nx = RatPoly(Poly([0;big(1)]),one(Poly{BigInt}))\n\n# In this example, we use nonlinear sequence transformations to obtain rational approximants to power series.\n# Consider the power series for the inverse tangent function.\n\na = Sequence(i->x*(-x^2)^(i-1)/(2i-1))\n\n# The ϵ-algorithm corresponds to creating a diagonal sequence in the Padé table.\n\nEpsilon = ϵ(cumsum(a))\n\nEpsilon(1:20)\n\n# Now we can see how the Padé aproximants compare to the function inverse tangent.\n\nmyatan(x,n) = convert(typeof(x),Epsilon(n)(x))\n\nmyatan(1.0,20)-atan(1.0) # Double precision. Summing 10 million terms can only deliver a little over 8 digits.\n\nmyatan(2.0,20)-atan(2.0) # Eight digits beyond region of convergence. Not bad!\n\n\n# More powerful sequence transformations create useful approximants to factorially divergent power series.\n# This series appears when computing the asymptotic expansion of the exponential integral.\n\na = Sequence(i->(-x)^(i)*factorial(big(i-1)))\n\nD,L,W = Drummond(cumsum(a)),Levin(cumsum(a)),Weniger(cumsum(a))\n\nW(1:20)\n\nmydivergentseries(x,n) = convert(typeof(x),W(n)(x))\n\nGompertz = -.596347362323194074341078499369279376074\n\nmydivergentseries(1.0,20)-Gompertz # It does quite well!\n\n\n# The ratio of these sequences is used in Stirling's asymptotic approximation to the Gamma function.\nA001163 = big([1,1,1,-139,-571,163879,5246819,-534703531,-4483131259,432261921612371,6232523202521089,-25834629665134204969,-1579029138854919086429,746590869962651602203151,1511513601028097903631961,-8849272268392873147705987190261,-142801712490607530608130701097701])\nA001164 = big([1,12,288,51840,2488320,209018880,75246796800,902961561600,86684309913600,514904800886784000,86504006548979712000,13494625021640835072000,9716130015581401251840000,116593560186976815022080000,2798245444487443560529920000,299692087104605205332754432000000,57540880724084199423888850944000000])\n\n# Here, we use the ϵ-algorithm to generate Padé approximants instead of a Poincaré-type asymptotic expansion.\n\nx = RatPoly(Poly([0;big(1)]),one(Poly{BigInt}))\n\na = Sequence(i->A001163[i]//A001164[i]*x^(i-1))\n\nϵ(cumsum(a))(1:2:17)\n\n# We can create the Levin d-transformations to the asymptotic expansion for different rational approximants.\n\nLevin(cumsum(a),:d)(1:10)\n", "meta": {"hexsha": "570c6a8f71e706ea85ec13ab47e00a5ea64bc30a", "size": 2376, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/rationalapproximants.jl", "max_stars_repo_name": "MikaelSlevinsky/SequenceTransformations", "max_stars_repo_head_hexsha": "9f5d743519bd9d523eccb8c4b715e1616466b3f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-05T15:53:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T19:28:58.000Z", "max_issues_repo_path": "examples/rationalapproximants.jl", "max_issues_repo_name": "MikaelSlevinsky/SequenceTransformations", "max_issues_repo_head_hexsha": "9f5d743519bd9d523eccb8c4b715e1616466b3f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/rationalapproximants.jl", "max_forks_repo_name": "MikaelSlevinsky/SequenceTransformations", "max_forks_repo_head_hexsha": "9f5d743519bd9d523eccb8c4b715e1616466b3f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4285714286, "max_line_length": 306, "alphanum_fraction": 0.7861952862, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660962919971, "lm_q2_score": 0.8376199694135333, "lm_q1q2_score": 0.7990610523976505}}
{"text": "\r\n##\r\nimport LinearAlgebra as linalg\r\nimport Plots as plt\r\n\r\ninclude(\"KalmanFilter.jl\")\r\nimport .KalmanFilter as kf\r\n\r\n##\r\nfunction get_data()\r\n    # Observations\r\n    x = [4000.0 4260.0 4550.0 4860.0 5110.0] # position [m]\r\n    v = [ 280.0  282.0  285.0  286.0  290.0] # velocity [m/s]\r\n    # x = [4000.0 4260.0 4550.0 4860.0 5110.0 5220.0 5115.0 4995.0 4871.0] # position [m]\r\n    # v = [ 280.0  282.0  285.0  286.0  290.0  295.0  292.0  287.0  284.0] # velocity [m/s]\r\n    X = [x; v]\r\n\r\n    # Initial values\r\n    a = 2.0 # acceleration\r\n    Δt = 1.0 # Time step\r\n    ΔP = [20.0; 5.0] # Process errors in process covariance matrix\r\n    Δ = [25.0; 6.0] # Observation errors\r\n    return X, a, Δ, ΔP, Δt\r\nend\r\n\r\n## Define the state space model\r\n\r\nfunction define_model(X, a, Δ, ΔP, Δt)\r\n    m, n = size(X)\r\n    Q = zeros(m, m) # Process noise covariance matrix\r\n    F = [1.0 Δt; 0.0 1.0] # Transition matrix\r\n    B = [Δt^2/2.0 Δt]' # Control-input matrix\r\n    u = 2.0 # # Control vector, acceleration\r\n    R = linalg.Diagonal([Δ[1]^2 0.0; 0.0 Δ[2]^2]) # Sensor noise covariance matrix\r\n    H = kf.eye(m) # Measurement matrix\r\n\r\n    # Initial predicted process covariance matrix\r\n    P = linalg.Diagonal([ΔP[1]^2 ΔP[1]*ΔP[2]; ΔP[2]*ΔP[1] ΔP[2]^2])\r\n    return P, Q, R, F, H, B, u, m, n\r\nend\r\n\r\n## Data input\r\nfunction data_input(X, n)\r\n    X = [ [X[1,i], X[2,i]] for i in 1:n ]\r\n    Xp = [ X[1] ] # Initialize predicted state\r\n    Xk = copy(Xp) # Initialized new state matrix\r\n    return Xp, Xk, X\r\nend\r\n\r\n## Smoothers\r\nfunction run_smoothers_bts(Xk, F, Σ)\r\n    k = length(Xk)\r\n    sm = Vector{kf.RTSSmoother}(undef, k)\r\n    sm[k] = kf.RTSSmoother(Xk[k], Σ[k])\r\n    ksmoother = kf.RauchTungStriebel()\r\n    while k > 1\r\n        s = kf.kalman_smooth(ksmoother, sm[k].xk, Xk[k-1], Xk[k], Σ[k-1], Σ[k], F)\r\n        k -= 1\r\n        sm[k] = s\r\n    end\r\n    return sm\r\nend\r\n\r\n## UKF\r\nfunction run_ukf(X, f, g, P, R, Q, α; filter=kf.CholeskySqrt())\r\n    m, n = size(X)\r\n    _, _, Xx = data_input(X, n)\r\n    k = 1\r\n    K = kf._kalman_gain(P, kf.eye(m), R)\r\n    sukf = [ kf.UnscentedKF(\r\n                Xx[k], Xx[k],\r\n                P, K,\r\n                zeros(2*m+1), zeros(2*m+1), zeros(m, 2*m+1),\r\n                zeros((2*m)*2+1), zeros((2*m)*2+1), zeros(m, (2*m)*2+1),\r\n                P, P,\r\n                filter,\r\n            )\r\n    ]\r\n    while k < n\r\n        s = kf.unscented_kalman(\r\n            Xx[k+1], sukf[k].xk, f, g, sukf[k].P, R, Q; sqrt_filter=filter, α=α,\r\n        )\r\n        push!(sukf, s)\r\n        k += 1\r\n    end\r\n    return sukf\r\nend\r\n\r\n## Plots\r\nfunction plot_kf(Xp, Xk, Xx, Δ)\r\n    # Xp, Xk, Xx = reduce(hcat, Xp), reduce(hcat, Xk), reduce(hcat, Xx)\r\n    p1 = plt.plot(Xp[1,:], m=:o, label=\"Predicted\", legend=:topleft, ylabel=\"Position [m]\", xlabel=\"Time [s]\")\r\n    plt.plot!(p1, Xx[1,:], m=:s, label=\"Measured\", ribbon=Δ[1])\r\n    plt.plot!(p1, Xk[1,:], m=:p, label=\"KF\")\r\n    p2 = plt.plot(Xp[2,:], m=:o, label=\"Predicted\", legend=:topleft, ylabel=\"Velocity [m/s]\", xlabel=\"Time [s]\")\r\n    plt.plot!(p2, Xx[2,:], m=:s, label=\"Measured\", ribbon=Δ[2])\r\n    plt.plot!(p2, Xk[2,:], m=:p, label=\"KF\")\r\n    p = plt.plot(p1, p2, size=(700,350))\r\n    return p\r\nend\r\n\r\nfunction plot_kf_smooth(Xp, Xk, Xx, Xks, Δ)\r\n    # Xp, Xk = reduce(hcat, Xp), reduce(hcat, Xk)\r\n    # Xx, Xks = reduce(hcat, Xx), reduce(hcat, Xks)\r\n    p1 = plt.plot(Xp[1,:], m=:o, label=\"Predicted\", legend=:topleft, ylabel=\"Position [m]\", xlabel=\"Time [s]\")\r\n    plt.plot!(p1, Xx[1,:], m=:s, label=\"Measured\", ribbon=Δ[1])\r\n    plt.plot!(p1, Xk[1,:], m=:p, label=\"KF\")\r\n    plt.plot!(p1, Xks[1,:], m=:h, label=\"Smooth\")\r\n    p2 = plt.plot(Xp[2,:], m=:o, label=\"Predicted\", legend=:topleft, ylabel=\"Velocity [m/s]\", xlabel=\"Time [s]\")\r\n    plt.plot!(p2, Xx[2,:], m=:s, label=\"Measured\", ribbon=Δ[2])\r\n    plt.plot!(p2, Xk[2,:], m=:p, label=\"KF\")\r\n    plt.plot!(p2, Xks[2,:], m=:h, label=\"Smooth\")\r\n    p = plt.plot(p1, p2, size=(700,350))\r\n    return p\r\nend\r\n\r\n## Run KFs\r\nX, a, Δ, ΔP, Δt = get_data()\r\nP, Q, R, F, H, B, u, m, n = define_model(X, a, Δ, ΔP, Δt)\r\n\r\n## Unscented Kalman Filter\r\nf(x) = F*x .+ B .* u\r\ng(x) = H*x\r\nskf = run_ukf(X, f, g, P, R, Q, 1e-3; filter=kf.SVDSqrt())\r\nXp, Xk = kf.unpack(skf, [:xp, :xk])\r\np1 = plot_kf(Xp, Xk, X, Δ)\r\n\r\n## Rauch Tung Striebel Smoother\r\nΣ, Xkm = kf.unpack_matrix(skf, [:P, :xk])\r\nskm = run_smoothers_bts(Xkm, F, Σ)\r\nXkm = kf.unpack(skf, :xk)\r\np1m = plot_kf_smooth(Xp, Xk, X, Xkm, Δ)\r\n", "meta": {"hexsha": "595835db8c81b149515d2d7ac698f3650a3604b4", "size": 4414, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test_package_UKF.jl", "max_stars_repo_name": "lnacquaroli/KalmanFilter.jl", "max_stars_repo_head_hexsha": "9746b6b1079c499323f777ecf7077a995ec49f78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test_package_UKF.jl", "max_issues_repo_name": "lnacquaroli/KalmanFilter.jl", "max_issues_repo_head_hexsha": "9746b6b1079c499323f777ecf7077a995ec49f78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_package_UKF.jl", "max_forks_repo_name": "lnacquaroli/KalmanFilter.jl", "max_forks_repo_head_hexsha": "9746b6b1079c499323f777ecf7077a995ec49f78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1879699248, "max_line_length": 113, "alphanum_fraction": 0.5364748527, "num_tokens": 1789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660989095221, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7990610487897948}}
{"text": "#=\n  Biased coin\n\n  From cplint: http://cplint.eu/example/inference/coin.pl\n  \"\"\"\n  Throwing a coin with uncertainty on its fairness, from\n  J. Vennekens, S. Verbaeten, and M. Bruynooghe. Logic programs with annotated\n  disjunctions. In International Conference on Logic Programming,\n  volume 3131 of LNCS, pages 195-209. Springer, 2004.\n  \"\"\"\n\n  Model 1: Probability of tossing a head (no observation)\n  Distributions of variable coinHead (num:0)\n  1.00000 =>    5049  (0.504900)\n  0.00000 =>    4951  (0.495100)\n\n  Model 2: Probability of tossing a head given that we know it's biased\n  Distributions of variable coinHead (num:0)\n  1.00000 =>    5712  (0.571200)\n  0.00000 =>    4288  (0.428800)\n\n  Cf ~/cplint/coin.pl\n     ~/blog/biased_coin.blog\n     ~/webppl/biased_coin.wppl\n\n=#\n\nusing Turing\ninclude(\"jl_utils.jl\")\n\n@model function biased_coin(experiment=\"observe biased\")\n    fair = 1\n    biased = 2\n\n    coinType ~ Categorical([0.9,0.1]) # fair,biased\n    head = 1\n    tail = 2\n    coinResult ~ coinType == fair ? Categorical([0.5,0.5]) :\n            Categorical([0.6,0.4])\n\n    if experiment == \"observe biased\"\n        true ~ Dirac(coinType == biased)\n    end\n\n    coinHead ~ Dirac(coinResult == head)\n    coinTail ~ Dirac(coinResult == tail)\n\nend\n\nprintln(\"Model 1: Probability of tossing a head (no observation)\")\nmodel = biased_coin(\"no observation\")\n\nnum_chns = 4\n# chs = sample(model, Prior(), 1000)\n# chs = sample(model, MH(), 10_000)\n# chs = sample(model, PG(15), 10_000)\n# chs = sample(model, IS(), 10_000)\nchs = sample(model, SMC(), 10_000)\n# chs = sample(model, SMC(), MCMCThreads(), 10_000, num_chs)\n\n# chs = sample(model, SGLD(), 10_000)\n# chs = sample(model,NUTS(), 10_000)\n# chs = sample(model,HMC(0.01,5), 10_000)\n\n# display(chs)\n# display(plot(chs))\n\nshow_var_dist_pct(chs,:coinHead)\n\n\nprintln(\"\\nModel 2: Probability of tossing a head given that we know it's biased\")\nmodel = biased_coin(\"observe biased\")\n\nnum_chns = 4\n# chs = sample(model, Prior(), 1000)\n# chs = sample(model, MH(), 10_000)\n# chs = sample(model, PG(15), 10_000)\n# chs = sample(model, IS(), 10_000)\nchs = sample(model, SMC(), 10_000)\n# chs = sample(model, SMC(), MCMCThreads(), 10_000, num_chs)\n\n# chs = sample(model, SGLD(), 10_000)\n# chs = sample(model,NUTS(), 10_000)\n# chs = sample(model,HMC(0.01,5), 10_000)\n\n# display(chs)\n# display(plot(chs))\n\nshow_var_dist_pct(chs,:coinHead)\n\n", "meta": {"hexsha": "75fa80503d56db83f03b5ebd76fd7056acd6c72f", "size": 2381, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/biased_coin.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/biased_coin.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/biased_coin.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 26.1648351648, "max_line_length": 82, "alphanum_fraction": 0.6669466611, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760996, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7990062234450483}}
{"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\n\n\"This routine solves the periodic advection-diffusion equation using Forward Euler\nin time and 2nd order finite differences in space.\"\n\nm = 100 # number of points\n\n# define spatial grid\nx = LinRange(-1,1,m+2) # x_0, x_1, ..., x_m, x_{m+1} = x_0\nxint = x[1:end-1]\nh = x[2]-x[1]\n\na = 1.0 # advection speed\nϵ = h/2 # diffusion coefficient\ndt = h # timestep\nT = 2.0 # final time\n\n# initial condition and forcing\nu0(x) = sin(pi*x)\nf(x,t) = 0.0\n\n# approximation of second derivative: largest eig = O(1/h^2)\nA = (1/h^2) * spdiagm(0=>2*ones(m+1),-1=>-ones(m),1=>-ones(m))\nA[1,end] = -1/h^2\nA[end,1] = -1/h^2\n\n# approximation of first derivative: largest eig = O(1/h)\nQ = (1/(2*h)) * spdiagm(1=>ones(m),-1=>-ones(m))\nQ[1,end] = -1/(2*h)\nQ[end,1] = 1/(2*h)\n\nu = u0.(xint)\nNsteps = ceil(Int,T/dt)\ndt = T / Nsteps\n\ninterval = 10\n@gif for k = 1:Nsteps\n    tk = k*dt\n    u .= u + dt * (f.(xint,tk) - (a*Q + ϵ*A)*u)\n    if k % interval==0\n        plot(xint,u,linewidth=2,label=\"Solution\",ylims=(-1.5,1.5))\n        println(\"on timestep $k out of $Nsteps.\")\n    end\nend every interval\n\nmaxλ = Float64[]\nϵvec = .0:.0001:.025\nfor ϵ = ϵvec\n    append!(maxλ,maximum(abs.(eigvals(Matrix(I - dt*(Q + ϵ*A))))))\nend\nscatter(ϵvec,maxλ,leg=false)\nplot!(title=\"Largest eigenvalue magnitude with ϵ\")\n", "meta": {"hexsha": "936b3bd60666d6cf3e66a1f6f05440a4d9005f1a", "size": 1323, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week4/fd_advec.jl", "max_stars_repo_name": "jlchan/caam452_s21", "max_stars_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:38:43.000Z", "max_issues_repo_path": "week4/fd_advec.jl", "max_issues_repo_name": "jlchan/caam452_s21", "max_issues_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week4/fd_advec.jl", "max_forks_repo_name": "jlchan/caam452_s21", "max_forks_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0545454545, "max_line_length": 82, "alphanum_fraction": 0.6250944822, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7989788311032563}}
{"text": "\n\"\"\"\n    Matern(lnℓ::AbstractFloat, ln𝓋::AbstractFloat) <: RadialKernel{SqEuclidean}\n\nThe matern kernel with parameters \n``\\\\exp(\\\\ln\\\\ell) = \\\\ell > 0`` and \n``\\\\exp(\\\\ln\\\\mathscr{v}) = \\\\mathscr{v} > 0``. \n\n\n\n```math\nk_{\\\\ell,\\\\mathscr{v}}(x, y) \n= k_{\\\\ell,\\\\mathscr{v}}(\\\\lVert x - y\\\\rVert_2) = \n\\\\frac{2^{1 - \\\\mathscr{v}}}{\\\\Gamma(\\\\mathscr{v})}\n\\\\bigg(\\\\sqrt{2\\\\mathscr{v}}\\\\frac{\\\\lVert x - y\\\\rVert_2}{\\\\ell}\n\\\\bigg)^\\\\mathscr{v}K_\\\\mathscr{v}\n\\\\bigg(\\\\sqrt{2\\\\mathscr{v}}\\\\frac{\\\\lVert x - y\\\\rVert_2}{\\\\ell}\\\\bigg)\n```\n\nExternal links\n* [Matérn covariance function on Wikipedia](https://en.wikipedia.org/wiki/Matérn_covariance_function)\n\n\"\"\"\nmutable struct Matern{\n    F<:AbstractFloat\n} <: RadialKernel{Euclidean}\n    dist::Euclidean\n    lnℓ::F\n    ln𝓋::F\n    \n    𝓋::F\n    c::F # 2^(1 - 𝓋) / Γ(𝓋)\n    sqrttwo𝓋_ℓ::F\n    \n    function Matern(\n        dist::Euclidean,\n        lnℓ::AbstractFloat,\n        ln𝓋::AbstractFloat\n    )\n        lnℓ, ln𝓋 = promote(lnℓ, ln𝓋)\n        𝓋 = exp(ln𝓋)\n        new{typeof(lnℓ)}(\n            dist,\n            lnℓ,\n            ln𝓋,\n            𝓋,\n            exp2(1 - 𝓋) / gamma(𝓋),\n            exp((float(logtwo) + ln𝓋) / 2),\n        )\n    end\nend\n\nMatern(lnℓ::AbstractFloat, ln𝓋::AbstractFloat) =\n    Matern(Euclidean(), lnℓ, ln𝓋)\n\n@inline function (k::Matern)(τ::AbstractFloat)\n    if τ == 0\n        return oneunit(promote(τ, k.𝓋)[1])\n    end\n    t = k.sqrttwo𝓋_ℓ * τ\n    return k.c * (t^k.𝓋) * besselk(k.𝓋, t)\nend\n\nnumparams(::Matern) = (1, 1)\nparamtypes(::Matern{F}) where F = (F, F)\nparams(k::Matern) = (lnℓ = k.lnℓ, ln𝓋 = k.ln𝓋)\nfunction setparams!(k::Matern{F}, lnℓ::F, ln𝓋::F) where F\n    𝓋 = exp(ln𝓋)\n    k.lnℓ = lnℓ\n    k.ln𝓋 = ln𝓋\n    k.𝓋 = 𝓋\n    k.c = exp2(1 - 𝓋) / gamma(𝓋)\n    k.sqrttwo𝓋_ℓ = exp((float(logtwo) + ln𝓋) / 2 - lnℓ)\nend\n", "meta": {"hexsha": "db0bcb52dd3014d550f3f66066daef4ded407959", "size": 1795, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/radial/Matern.jl", "max_stars_repo_name": "cameton/SKI.jl", "max_stars_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/radial/Matern.jl", "max_issues_repo_name": "cameton/SKI.jl", "max_issues_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/radial/Matern.jl", "max_forks_repo_name": "cameton/SKI.jl", "max_forks_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9333333333, "max_line_length": 103, "alphanum_fraction": 0.5465181058, "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363299661721, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7989589216279515}}
{"text": "using Printf, Combinatorics\n\nderangements(n::Int) = (perm for perm in permutations(1:n)\n                        if all(indx != p for (indx, p) in enumerate(perm)))\n\nfunction subfact(n::Integer)::Integer\n    if n in (0, 2)\n        return 1\n    elseif n == 1\n        return 0\n    elseif 1 ≤ n ≤ 18\n        return round(Int, factorial(n) / e)\n    elseif n > 0\n        return (n - 1) * ( subfact(n - 1) + subfact(n - 2) )\n    else\n        error()\n    end\nend\n\nprintln(\"Derangements of [1, 2, 3, 4]\")\nfor perm in derangements(4)\n    println(perm)\nend\n\n@printf(\"\\n%5s%13s%13s\\n\", \"n\", \"derangements\", \"!n\")\nfor n in 1:10\n    ders = derangements(n)\n    subf = subfact(n)\n    @printf(\"%5i%13i%13i\\n\", n, length(collect(ders)), subf)\nend\n\nprintln(\"\\n!20 = \", subfact(20))\n", "meta": {"hexsha": "d15b3ac2bc11b3ffe5792d089d5385147d4e18a3", "size": 763, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/permutations-derangements.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/permutations-derangements.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/permutations-derangements.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1212121212, "max_line_length": 75, "alphanum_fraction": 0.5648754915, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7989589150341709}}
{"text": "using LinearAlgebra\nusing Plots\n\n\nfunction flower(x, a=1, b=1, c=4)\n    return a * norm(x) + b * sin(c * atan(x[2], x[1]));\nend\n\n\ncontour(-3:0.1:3, -3:0.1:3, (x, y)->flower([x, y]))\n", "meta": {"hexsha": "6b69922a5c387701263b3e40d2b6dfebd4daea8a", "size": 182, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test_function/flower_function.jl", "max_stars_repo_name": "tor4z/convex_optimization", "max_stars_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test_function/flower_function.jl", "max_issues_repo_name": "tor4z/convex_optimization", "max_issues_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_function/flower_function.jl", "max_forks_repo_name": "tor4z/convex_optimization", "max_forks_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.5454545455, "max_line_length": 55, "alphanum_fraction": 0.5604395604, "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9637799451753696, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7989146033106334}}
{"text": "@inline function eig(t::SymTen{T}) where T<:AbstractFloat\n\n    e11 = t.xx\n    e12 = t.xy\n    e13 = t.xz\n    e22 = t.yy\n    e23 = t.yz\n    e33 = t.zz\n\n    p1 = muladd(e12, e12, muladd(e13, e13, e23*e23))\n    q = (e11 + e22 + e33)/3\n    p2 = (e11-q)^2 + (e22-q)^2 + (e33-q)^2 + 2*p1\n    p = @fastmath sqrt(p2/6)\n    r = ((e11-q)*(e22-q)*(e33-q) - (e11-q)*(e23^2) - (e12^2)*(e33-q) + 2*(e12*e13*e23) - (e13^2)*(e22-q))/(2*p*p*p)\n  \n    # In exact arithmetic for a symmetric matrix  -1 <= r <= 1\n    # but computation error can leave it slightly outside this range.\n\n    if r <= -1\n        ϕ =  T(π/3)\n    elseif r >= 1\n        ϕ = zero(T)\n    else\n        ϕ = acos(r)/3\n    end\n  \n    # the eigenvalues satisfy eig.z >= eig.y >= eig.x\n    eig3 = q + 2*p*cos(ϕ)\n    # cos(x+y) = cos(x)*cos(y) - sin(x)*sin(y)\n    eig1 = q + 2*p*cos(ϕ+(2*π/3))  # q - 2*p*(cos(ϕ)/2 + (√3/2)sin(ϕ))\n    eig2 = 3*q - eig1 - eig3     # since trace(E) = eig.x + eig.y + eig.z = 3q\n\n    return (eig1,eig2,eig3)\nend\n\n@inline function eig(t::SymTen)\n\n    e11 = t.xx\n    e12 = t.xy\n    e13 = t.xz\n    e22 = t.yy\n    e23 = t.yz\n    e33 = t.zz\n\n    p1 = muladd(e12, e12, muladd(e13, e13, e23*e23))\n    q = (e11 + e22 + e33)/3\n    p2 = (e11-q)^2 + (e22-q)^2 + (e33-q)^2 + 2*p1\n    p = sqrt(p2/6)\n    r = ((e11-q)*(e22-q)*(e33-q) - (e11-q)*(e23^2) - (e12^2)*(e33-q) + 2*(e12*e13*e23) - (e13^2)*(e22-q))/(2*p*p*p)\n  \n    ϕ = acos(r)/3\n  \n    # the eigenvalues satisfy eig.z >= eig.y >= eig.x\n    eig3 = q + 2*p*cos(ϕ)\n    eig1 = q + 2*p*cos(ϕ+(2*π/3))\n    eig2 = 3*q - eig1 - eig3     # since trace(E) = eig.x + eig.y + eig.z = 3q\n\n    return (eig1,eig2,eig3)\nend\n\nfunction eigvec(t::SymTen{T}) where {T<:AbstractFloat}\n    S11 = t.xx\n    S12 = t.xy\n    S13 = t.xz\n    S22 = t.yy\n    S23 = t.yz\n    S33 = t.zz\n\n    p1 = muladd(S12, S12, muladd(S13, S13, S23*S23))\n\n    if (p1 == 0) # diagonal tensor\n        v1 = Vec{T}(1,0,0)\n        v2 = Vec{T}(0,1,0)\n        v3 = Vec{T}(0,0,1)\n        if S11 < S22\n            if S22 < S33\n                return (S11, S22, S33), (v1, v2, v3)\n            elseif S33 < S11\n                return (S33, S11, S22), (v3, v1, v2)\n            else\n                return (S11, S33, S22), (v1, v3, v2)\n            end\n        else #S22 < S11\n            if S11 < S33\n                return (S22, S11, S33), (v2, v1, v3)\n            elseif S33 < S22\n                return (S33, S22, S11), (v3, v2, v1)\n            else\n                return (S22, S33, S11), (v2, v3, v1)\n            end\n        end\n    end\n\n    q = (S11 + S22 + S33)/3\n    p2 = (S11-q)^2 + (S22-q)^2 + (S33-q)^2 + 2*p1\n    p = @fastmath sqrt(p2/6)\n    r = ((S11-q)*(S22-q)*(S33-q) - (S11-q)*(S23^2) - (S12^2)*(S33-q) + 2*(S12*S13*S23) - (S13^2)*(S22-q))/(2*p*p*p)\n  \n    # In exact arithmetic for a symmetric matrix  -1 <= r <= 1\n    # but computation error can leave it slightly outside this range.\n\n    if r <= -1\n        ϕ =  T(π/3)\n    elseif r >= 1\n        ϕ = zero(T)\n    else\n        ϕ = acos(r)/3\n    end  \n\n    # the eigenvalues satisfy eig.z >= eig.y >= eig.x\n    λ3 = q + 2*p*cos(ϕ)\n    λ1 = q + 2*p*cos(ϕ+(2*π/3))\n    λ2 = 3*q - λ1 - λ3     # since trace(E) = eig.x + eig.y + eig.z = 3q\n\n\n    ######################### This part was copied from https://github.com/KristofferC/Tensors.jl/blob/master/src/eigen.jl #################################\n\n    if r > 0\n        (λ1, λ3) = (λ3, λ1)\n    end\n      # Calculate the first eigenvector\n        # This should be orthogonal to these three rows of A - λ1*I\n        # Use all combinations of cross products and choose the \"best\" one\n    r₁ = Vec(S11 - λ1, S12, S13)\n    r₂ = Vec(S12, S22 - λ1, S23)\n    r₃ = Vec(S13, S23, S33 - λ1)\n    n₁ = r₁ ⋅ r₁\n    n₂ = r₂ ⋅ r₂\n    n₃ = r₃ ⋅ r₃\n\n    r₁₂ = r₁ × r₂\n    r₂₃ = r₂ × r₃\n    r₃₁ = r₃ × r₁\n    n₁₂ = r₁₂ ⋅ r₁₂\n    n₂₃ = r₂₃ ⋅ r₂₃\n    n₃₁ = r₃₁ ⋅ r₃₁\n\n    # we want best angle so we put all norms on same footing\n    # (cheaper to multiply by third nᵢ rather than divide by the two involved)\n    if n₁₂ * n₃ > n₂₃ * n₁\n        if n₁₂ * n₃ > n₃₁ * n₂\n            @fastmath ϕ1 = r₁₂ / sqrt(n₁₂)\n        else\n            @fastmath ϕ1 = r₃₁ / sqrt(n₃₁)\n        end\n    else\n        if n₂₃ * n₁ > n₃₁ * n₂\n            @fastmath ϕ1 = r₂₃ / sqrt(n₂₃)\n        else\n            @fastmath ϕ1 = r₃₁ / sqrt(n₃₁)\n        end\n    end\n\n    # Calculate the second eigenvector\n    # This should be orthogonal to the previous eigenvector and the three\n    # rows of A - λ2*I. However, we need to \"solve\" the remaining 2x2 subspace\n    # problem in case the cross products are identically or nearly zero\n\n    # The remaing 2x2 subspace is:\n    if abs(ϕ1.x) < abs(ϕ1.y) # safe to set one component to zero, depending on this\n        @fastmath orthogonal1 = Vec(-ϕ1.z, zero(T), ϕ1.x) / sqrt(abs2(ϕ1.x) + abs2(ϕ1.z))\n    else\n        @fastmath orthogonal1 = Vec(zero(T), ϕ1.z, -ϕ1.y) / sqrt(abs2(ϕ1.y) + abs2(ϕ1.z))\n    end\n    orthogonal2 = ϕ1 × orthogonal1\n\n    # The projected 2x2 eigenvalue problem is C x = 0 where C is the projection\n    # of (A - λ2*I) onto the subspace {orthogonal1, orthogonal2}\n    a_orth1_1 = S11 * orthogonal1.x + S12 * orthogonal1.y + S13 * orthogonal1.z\n    a_orth1_2 = S12 * orthogonal1.x + S22 * orthogonal1.y + S23 * orthogonal1.z\n    a_orth1_3 = S13 * orthogonal1.x + S23 * orthogonal1.y + S33 * orthogonal1.z\n\n    a_orth2_1 = S11 * orthogonal2.x + S12 * orthogonal2.y + S13 * orthogonal2.z\n    a_orth2_2 = S12 * orthogonal2.x + S22 * orthogonal2.y + S23 * orthogonal2.z\n    a_orth2_3 = S13 * orthogonal2.x + S23 * orthogonal2.y + S33 * orthogonal2.z\n\n    c11 = orthogonal1.x*a_orth1_1 + orthogonal1.y*a_orth1_2 + orthogonal1.z*a_orth1_3 - λ2\n    c12 = orthogonal1.x*a_orth2_1 + orthogonal1.y*a_orth2_2 + orthogonal1.z*a_orth2_3\n    c22 = orthogonal2.x*a_orth2_1 + orthogonal2.y*a_orth2_2 + orthogonal2.z*a_orth2_3 - λ2\n\n    # Solve this robustly (some values might be small or zero)\n    c11² = abs2(c11)\n    c12² = abs2(c12)\n    c22² = abs2(c22)\n    if c11² >= c22²\n        if c11² > 0 || c12² > 0\n            if c11² >= c12²\n                tmp = c12 / c11\n                @fastmath p2 = inv(sqrt(1 + abs2(tmp)))\n                p1 = tmp * p2\n            else\n                tmp = c11 / c12 # TODO check for compex input\n                @fastmath p1 = inv(sqrt(1 + abs2(tmp)))\n                p2 = tmp * p1\n            end\n            ϕ2 = p1*orthogonal1 - p2*orthogonal2\n        else # c11 == 0 && c12 == 0 && c22 == 0 (smaller than c11)\n            ϕ2 = orthogonal1\n        end\n    else\n        if c22² >= c12²\n            tmp = c12 / c22\n            @fastmath p1 = inv(sqrt(1 + abs2(tmp)))\n            p2 = tmp * p1\n        else\n            tmp = c22 / c12\n            @fastmath p2 = inv(sqrt(1 + abs2(tmp)))\n            p1 = tmp * p2\n        end\n        ϕ2 = p1*orthogonal1 - p2*orthogonal2\n    end\n\n\n    # The third eigenvector is a simple cross product of the other two\n    ϕ3 = ϕ1 × ϕ2 # should be normalized already\n\n    ###############################################################################################################################333\n    if r > 0\n        (λ1, λ3) = (λ3, λ1)\n        (ϕ1, ϕ3) = (-ϕ3, ϕ1) # - sign so e3 = cross(e1,e2) is always true\n    end\n\n    return (λ1,λ2,λ3),(ϕ1,ϕ2,ϕ3)\nend\n\n@inline stress_state(a::Number,b::Number,c::Number) = begin \n    abc2 = muladd(a,a,muladd(b,b,c^2))\n    return (-3*sqrt(6)*a*b*c)/(abc2*@fastmath(sqrt(abc2)))\nend\n@inline stress_state(t::SymTen) = begin \n    abc2 = tr(square(t))\n    return (-3*sqrt(6)*det(t))/(abc2*@fastmath(sqrt(abc2)))\nend", "meta": {"hexsha": "8bd10554f762283a14a2bd89ed00c5a78508cd7f", "size": 7498, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/eigen.jl", "max_stars_repo_name": "favba/FluidTensors.jl", "max_stars_repo_head_hexsha": "2dc979ed2ac6b8bb7405b6a2279b2667d49ed8a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-05-25T06:00:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T04:24:43.000Z", "max_issues_repo_path": "src/eigen.jl", "max_issues_repo_name": "favba/FluidTensors.jl", "max_issues_repo_head_hexsha": "2dc979ed2ac6b8bb7405b6a2279b2667d49ed8a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eigen.jl", "max_forks_repo_name": "favba/FluidTensors.jl", "max_forks_repo_head_hexsha": "2dc979ed2ac6b8bb7405b6a2279b2667d49ed8a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1802575107, "max_line_length": 156, "alphanum_fraction": 0.5128034142, "num_tokens": 2910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799451753695, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.798914593128425}}
{"text": "\"\"\"\n    zs = smoothconv(z,nas)\n\nSmoothen field `z(ns,ns)` with a circular kernel of diameter `ns/nas` using convolution.\nTakes into account missing values.\n\"\"\"\n\tfunction smoothconv(zi,nas)\n\n        @compat iinan=findall(isnan.(zi))\n        @compat iinotnan=findall(.~isnan.(zi))\n        zi[iinan].=0.\n\n        nss=size(zi);\n        ns=nss[1];\n        sdim=div(ns,nas)/2; # the smoothing sigma is half large scale pixel wide \n\n        mask=zeros(ns,ns);\n        for i=1:ns\n           for j=1:ns\n               kx=i-1;\n               ky=j-1;\n               if(i>ns/2+1)\n                  kx=i-ns-1 ;\n               end\n               if(j>ns/2+1)\n                  ky=j-ns-1 ;\n               end\n               r2=kx*kx+ky*ky;\n               mask[i,j]=exp(-(r2/(sdim*sdim))/2);\n           end\n        end \n        fm=fft(mask)\n        zf=real(ifft(fm.*fft(zi)))/sum(mask)\n        if length(iinan)>0\n           zi1=deepcopy(zi)\n           zi1[iinotnan].=1.0\n           zf=zf./(real(ifft(fm.*fft(zi1)))/sum(mask))\n        end\n\tzf[iinan].=NaN\n        return zf\n   end\n", "meta": {"hexsha": "4fd069126ef93133d2dfecaf1c348a7d9a1014e4", "size": 1063, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rf/smoothconv.jl", "max_stars_repo_name": "UnofficialJuliaMirror/RainFARM.jl-e9a4e08f-a0a3-5224-a821-6d0231c12d6b", "max_stars_repo_head_hexsha": "740f4edff721692e13168b132503aa62d5fea574", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rf/smoothconv.jl", "max_issues_repo_name": "UnofficialJuliaMirror/RainFARM.jl-e9a4e08f-a0a3-5224-a821-6d0231c12d6b", "max_issues_repo_head_hexsha": "740f4edff721692e13168b132503aa62d5fea574", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rf/smoothconv.jl", "max_forks_repo_name": "UnofficialJuliaMirror/RainFARM.jl-e9a4e08f-a0a3-5224-a821-6d0231c12d6b", "max_forks_repo_head_hexsha": "740f4edff721692e13168b132503aa62d5fea574", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3095238095, "max_line_length": 88, "alphanum_fraction": 0.4647224835, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.798899250684972}}
{"text": "using Distributions\n\n#################################################\n# Functions to obtain particle radii from packing fraction and other simple geometric properties\n################################################\n\n\"Compute the radius from a given packing fraction 'ϕ', in arbitrary dimensions, 'd'.\"\nfunction radius_from_phi(d::Int64, ϕ::Real, N::Int64, L::Real=1.0)::Float64\n    #d: dimension; ϕ: packing fraction; N: number of particles; L: size of box\n    Vd = volume_d_ball(d)\n    return L*(ϕ/(N*Vd))^(1/d)\nend\nradius_from_phi(3, 0.64, 1000)\n\n\"Compute the radii of a *bi*disperse configuration of (N1, N2) particles with radii (R1, R2), from a given packing fraction 'ϕ', in arbitrary dimensions, 'd'. It is assumed that R2/R1=c.\"\nfunction radii_from_phi(d::Int64, ϕ::Real, N1::Int64, N2::Int64=N1, c::T=1.4, L::T=1.0) where T<:AbstractFloat\n    #d: dimension; ϕ: packing fraction; N: number of particles; L: size of box\n    Vd = volume_d_ball(d)\n    den = Vd*(N1 + N2*c^d)\n    R1 = L*(ϕ/den)^(1/d)\n    return R1, c*R1\nend\nradii_from_phi(2, 0.84, 1000)\n\n\n\n#################################################\n# Functions to generate a random configuration that is NOT jammed, but can be used as initial condition for CALiPPSO\n################################################\n\n\"Asses whether two particles of radius 'r' and centers 'X1' and 'X2' are overlapping. \"\nfunction are_overlapping(X1::SVector{d, PeriodicNumber{T}}, X2::SVector{d, PeriodicNumber{T}}, r::T)::Bool where {d, T<:AbstractFloat}\n    if norm(X1-X2)< 2*r\n        return true\n    else\n        return false\n    end\nend\nare_overlapping(PeriodicVector(rand(4)), PeriodicVector(rand(4)), 0.0)\n\n\"Asses whether two particles whose centers are 'X1' and 'X2', and with radii 'r1' and 'r2' are overlapping. \"\nfunction are_overlapping(X1::SVector{d, PeriodicNumber{T}}, X2::SVector{d, PeriodicNumber{T}}, r1::T, r2::T)::Bool where {d, T<:AbstractFloat}\n    if norm(X1-X2)< r1+r2\n        return true\n    else\n        return false\n    end\nend\nare_overlapping(PeriodicVector(rand(4)), PeriodicVector(rand(4)), 0.0, 0.0)\n\n\n\"\"\"\n    generate_random_configuration(d::Int64, N::Int64, ϕ::T, L::T=1.0; max_tries::Int64=5000 )\n\nGenerate 'N' random centers of monodisperse particles of radius 'r' and in 'd' dimensions, \nwithout any overlaps.\n\nThe output is the radius (that corresponds to the packing fraction 'ϕ' used as input), and \nthe vector containing the centers (each as a SVector{d, PeriodicNumber} type). \nEach center is placed at uniformly random in all space, and when an overlap is detected a \nnew random position is drawn. 'max_tries' (default 5000) attempts are tried for each particle \nand when this bound surpassed an error is thrown, with the index of the center that was not\ncreated.\n\"\"\"\nfunction generate_random_configuration(d::Int64, N::Int64, ϕ::T, L::T=1.0; max_tries::Int64=5000 ) where {T<:AbstractFloat}\n    r = radius_from_phi(d, ϕ, N, L)\n    Xs_distr = Uniform(0, L)\n    centers = Vector{SVector{d, PeriodicNumber{T}}}(undef, N)\n\n    centers[1] = PeriodicVector(rand(Xs_distr, d), L)\n\n    for i in 2:N\n        new_center = PeriodicVector(rand(Xs_distr, d), L)\n        overlaps = are_overlapping.(centers[1:i-1], [new_center], r)\n        c=0\n        \n        while any(overlaps)\n            new_center = PeriodicVector(rand(Xs_distr, d), L)\n            c+=1\n            overlaps = are_overlapping.(centers[1:i-1], [new_center], r)\n\n            (c>max_tries) && error(\"Could not assign a new center to particle \", i, \"    after \", max_tries, \" tries\")\n        end\n        centers[i] = new_center\n    end\n    return r, centers\nend\ngenerate_random_configuration(3, 10, 0.2)\n\n\nfunction generate_random_configuration(d::Int64, N1::Int64, R1::T, N2::Int64, R2::T, L::T=1.0; max_tries::Int64=5000, verbose::Bool=false ) where {T<:AbstractFloat}\n    N = N1+N2; Rs = [R1*ones(N1); R2*ones(N2)]\n\n    verbose && println(\"Trying to generate a d-\", d, \" dimensional configuration of N = \", N, \" spheres with packing fraction φ= \", packing_fraction(d, R1, N1, R2, N2, L))\n\n    Xs_distr = Uniform(0, L)\n    centers = Vector{SVector{d, PeriodicNumber{T}}}(undef, N)\n    # create array of radii\n    centers[1] = PeriodicVector(rand(Xs_distr, d), L)\n\n    for i in 2:N\n        new_center = PeriodicVector(rand(Xs_distr, d), L)\n        overlaps = [are_overlapping(centers[j], new_center, Rs[j], Rs[i]) for j in 1:i-1]\n        # overlaps = are_overlapping.(centers[1:i-1], [new_center], r)\n        c=0\n        \n        while any(overlaps)\n            new_center = PeriodicVector(rand(Xs_distr, d), L)\n            c+=1\n            # overlaps = are_overlapping.(centers[1:i-1], [new_center], r)\n            overlaps = [are_overlapping(centers[j], new_center, Rs[j], Rs[i]) for j in 1:i-1]\n\n            (c>max_tries) && error(\"Could not assign a new center to particle \", i, \"    after \", max_tries, \" tries\")\n        end\n        centers[i] = new_center\n    end\n    return Rs, centers\nend\ngenerate_random_configuration(3, 10, 0.02, 5, 0.01)\n\nfunction generate_random_configuration(d::Int64, N1::Int64, N2::Int64, ϕ::T, c::T=1.4, L::T=1.0; max_tries::Int64=5000, verbose::Bool=false ) where {T<:AbstractFloat}\n    R1, R2 = radii_from_phi(d, ϕ, N1, N2, c, L)\n    Rs, centers = generate_random_configuration(d, N1, R1, N2, R2, L; max_tries=max_tries, verbose=verbose)\n    return R1, R2, centers\nend\ngenerate_random_configuration(3, 50, 50, 0.2, 1.0)\n\n\nfunction generate_random_configuration(d::Int64, Rs::Vector{T}, L::T=1.0; max_tries::Int64=5000, verbose::Bool=false ) where {T<:AbstractFloat}\n    N = length(Rs)\n    φ = packing_fraction(d, Rs, L)\n    verbose && println(\"Trying to generate a d-\", d, \" dimensional configuration of N = \", N, \" spheres with packing fraction φ= \", φ)\n\n    Xs_distr = Uniform(0, L)\n    centers = Vector{SVector{d, PeriodicNumber{T}}}(undef, N)\n    # create array of radii\n    centers[1] = PeriodicVector(rand(Xs_distr, d), L)\n\n    for i in 2:N\n        new_center = PeriodicVector(rand(Xs_distr, d), L)\n        overlaps = [are_overlapping(centers[j], new_center, Rs[j], Rs[i]) for j in 1:i-1]\n        # overlaps = are_overlapping.(centers[1:i-1], [new_center], r)\n        c=0\n        \n        while any(overlaps)\n            new_center = PeriodicVector(rand(Xs_distr, d), L)\n            c+=1\n            # overlaps = are_overlapping.(centers[1:i-1], [new_center], r)\n            overlaps = [are_overlapping(centers[j], new_center, Rs[j], Rs[i]) for j in 1:i-1]\n\n            (c>max_tries) && error(\"Could not assign a new center to particle \", i, \"    after \", max_tries, \" tries\")\n        end\n        centers[i] = new_center\n    end\n    return φ, centers\nend\ngenerate_random_configuration(2, 0.02*rand(10))", "meta": {"hexsha": "7b57b149a12a808b6c650b4e01520b7b3965e390", "size": 6690, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/random_initial_conditions.jl", "max_stars_repo_name": "rdhr/CALiPPSO", "max_stars_repo_head_hexsha": "28dee11e0253549eeeb6cb701c763ea3d828fd18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-03-20T13:44:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:28:31.000Z", "max_issues_repo_path": "src/random_initial_conditions.jl", "max_issues_repo_name": "rdhr/CALiPPSO", "max_issues_repo_head_hexsha": "28dee11e0253549eeeb6cb701c763ea3d828fd18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/random_initial_conditions.jl", "max_forks_repo_name": "rdhr/CALiPPSO", "max_forks_repo_head_hexsha": "28dee11e0253549eeeb6cb701c763ea3d828fd18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6114649682, "max_line_length": 187, "alphanum_fraction": 0.6372197309, "num_tokens": 2064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7988992471039851}}
{"text": "\"\"\"\n    centroids_radii(points::Array{Float64, 2},\n                    indices_simplices::Array{Int, 1})\n\nCompute the centroids and radii of the simplices in the triangulation in any\ndimension.\n\n- `points::Array{Float64, 2}` Points furnishing the triangulation\n    (size = npoints x dim).\n- `indices_simplices::Array{Int, 1}` Indices of the vertices furnishing\n    simplices of the triangulation. Each row refers to one simplex.\n\"\"\"\nfunction centroids_radii2(points, indices_simplices)\n    dim = size(points, 2)\n    nsimplices = size(indices_simplices, 1)\n    centroids = zeros(nsimplices, dim)\n    radii = zeros(nsimplices)\n\n    for i = 1:nsimplices\n        simplex = points[indices_simplices[i, :], :] # (dim + 1) x dim)\n        centroid = sum(simplex, dims = 1) / (dim + 1)\n        centroid_matrix = repeat(centroid, dim + 1, 1)\n\n        # Subtract centroid from each simplex\n        subtracted = simplex - centroid_matrix\n        radius = sqrt(maximum(sum(subtracted.^2, dims = 2)))\n\n        centroids[i, :] = centroid\n        radii[i] = radius\n\n    end\n\n    return centroids, radii\nend\n\n\n\n\"\"\"\n    centroids_radii(points::Array{Float64, 2},\n                    indices_simplices::Array{Int, 1})\n\nCompute the volumes of a set of simplices.\n\n- `points::Array{Float64, 2}` Points furnishing the triangulation\n    (size = npoints x dim).\n- `indices_simplices::Array{Int, 1}` Indices of the vertices furnishing\n    simplices of the triangulation. Each row refers to one simplex.\n\"\"\"\nfunction simplex_volumes(points::AbstractArray{Float64, 2},\n                        indices_simplices::AbstractArray{Int, 2})\n    dim = size(points, 2)\n    nsimplices = size(indices_simplices, 1)\n\n    volumes = zeros(Float64, nsimplices)\n\n    for i = 1:nsimplices\n        simplex = transpose(points[indices_simplices[i, :], :])\n        volumes[i] = abs(det([ones(1, dim + 1); simplex]))\n    end\n\n    return volumes\nend\n\n\n\"\"\"\nCompute orientations of simplices given the `points` forming the vertices of\nthe simplices (a n_vertices x dim array) and `simplex_inds` (a n_simplices x\n(dim+1) array), telling how the simplices are formed from the vertices.\n\"\"\"\nfunction orientations(points::AbstractArray{Float64, 2},\n                    simplex_inds::AbstractArray{Int, 2})\n    n_simplices = size(simplex_inds, 1)\n    dim = size(simplex_inds, 2) - 1\n    orientations = Vector{Float64}(undef, n_simplices)\n\n    for i = 1:n_simplices\n        orientations[i] = det(hcat(view(points, view(simplex_inds, i, :), :),\n                                ones(dim + 1)))\n    end\n\n    return orientations\nend\n", "meta": {"hexsha": "28d401ad31f051c5a2169da641141e700f5a21d7", "size": 2572, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/x_partitioning/simplexoperations.jl", "max_stars_repo_name": "JuliaDynamics/StateSpaceReconstruction.jl", "max_stars_repo_head_hexsha": "d53dff4be52a319d435631768ac0560333629996", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-15T14:27:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T00:08:07.000Z", "max_issues_repo_path": "src/x_partitioning/simplexoperations.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StateSpaceReconstruction.jl-1441a9f6-6a74-5418-a591-cdf1d78a07f0", "max_issues_repo_head_hexsha": "acb3f9705c6786c8db08a9841cfbe9ec8be0aec9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2018-04-23T20:14:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-01T13:36:05.000Z", "max_forks_repo_path": "src/x_partitioning/simplexoperations.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StateSpaceReconstruction.jl-1441a9f6-6a74-5418-a591-cdf1d78a07f0", "max_forks_repo_head_hexsha": "acb3f9705c6786c8db08a9841cfbe9ec8be0aec9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:03:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:03:06.000Z", "avg_line_length": 30.9879518072, "max_line_length": 77, "alphanum_fraction": 0.6562986003, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8558511543206819, "lm_q1q2_score": 0.7988778370980865}}
{"text": "function isPrime(x)\r\n\ti = 2\r\n\tif x == 1\r\n\t\treturn false\r\n\tend\r\n\tif x == 2\r\n\t\treturn true\r\n\tend\r\n\tif x == 3\r\n\t\treturn true\r\n\tend\r\n\twhile i <= sqrt(x)\r\n\t\tif x % i == 0\r\n\t\treturn false\r\n\t\tend\r\n\t\ti =i+1\r\n\tend\r\n\treturn true\r\nend\r\n\r\nfunction nthPrime(n)\r\n\tprimeCount = 0\r\n\tif n == 0 \r\n\t\treturn \"there is no zeroth prime\"\r\n\tend\r\n\tif typeof(n)==String\r\n\t\tn = parse(Int64,n)\r\n\tend\r\n\tx=2\r\n\twhile primeCount <= n\r\n\t\tif isPrime(x)\r\n\t\t\tprimeCount += 1\r\n\t\tend\r\n\t\tif primeCount == n\r\n\t\t\treturn x\r\n\t\tend\r\n\t\tx+=1\r\n\tend\r\nend\t\r\n\r\nfunction main(input)\r\n\tnthPrime(input)\r\nend\r\n", "meta": {"hexsha": "9a47d36d900d57a3465e76460748de0c04300943", "size": 556, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/nth-prime/example.jl", "max_stars_repo_name": "KrymoreAkbota/julia", "max_stars_repo_head_hexsha": "3c90e23e22e77cb2fbb0eb5eca558969a4e04b86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercises/nth-prime/example.jl", "max_issues_repo_name": "KrymoreAkbota/julia", "max_issues_repo_head_hexsha": "3c90e23e22e77cb2fbb0eb5eca558969a4e04b86", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercises/nth-prime/example.jl", "max_forks_repo_name": "KrymoreAkbota/julia", "max_forks_repo_head_hexsha": "3c90e23e22e77cb2fbb0eb5eca558969a4e04b86", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.6363636364, "max_line_length": 36, "alphanum_fraction": 0.5683453237, "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331956, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7988778299720332}}
{"text": "# # Pandemic Control\n# A stochastic optimal control problem were we seek to control the spread of a \n# contagion with uncertain parameters.\n\n# ## Problem Statement and Model\n# We wish to determine optimal social distancing policy to control spread of a \n# contagion and minimize the economic impact of doing so. We'll model the spread \n# of the virus through a given population using the SEIR Model which considers 4 \n# population subsets that follow:\n# ```math \n# \\text{Susceptible} \\rightarrow \\text{Exposed} \\rightarrow \\text{Infectious} \\rightarrow \\text{Recovered}\n# ```\n# This model is formalized as:\n# ```math \n# \\begin{gathered}\n# \\frac{ds(t)}{dt} = (u(t) - 1)\\beta si(t) \\\\\n# \\frac{de(t)}{dt} = (1 - u(t))\\beta si(t) - \\xi e(t) \\\\\n# \\frac{di(t)}{dt} = \\xi e(t) - \\gamma i(t)\\\\\n# \\frac{dr(t)}{dt} = \\gamma i(t) \\\\\n# si(t) = s(t) i(t)\n# \\end{gathered}\n# ```\n# where ``s(t)`` is the susceptible population, ``e(t)`` is the exposed population, \n# ``i(t)`` is the infectious population, ``r(t)`` is the recovered population, \n# and ``u(t) \\in [0, 1]`` is the enforced population isolation (social distancing). \n# The other values denote model parameters that will be specific to the contagion \n# in question. \n\n# For our case study, we'll consider the incubation constant ``\\xi`` to be an \n# uncertain parameter ``\\xi \\sim \\mathcal{U}(\\underline{\\xi}, \\overline{\\xi})``. \n# This introduces to infinite dependencies into our model: time ``t`` and \n# uncertain incubation ``\\xi``. Moreover we'll seek to minimize the isolation \n# measures ``u(t)`` that are implemented while limiting the amount of infected \n# individuals ``i(t)`` to be below a threshold ``i_{max}``. Thus, the optimization \n# problem becomes:\n# ```math \n# \\begin{aligned}\n# &&\\min_{} &&& \\int_{t \\in \\mathcal{D}_{t}} u(t) dt \\\\\n# && \\text{s.t.} &&& \\frac{\\partial s(t, \\xi)}{\\partial t} = (u(t) - 1)\\beta si(t, \\xi), && \\forall t \\in \\mathcal{D}_{t}, \\xi \\in \\mathcal{D}_{\\xi} \\\\\n# &&&&& \\frac{\\partial e(t, \\xi)}{\\partial t} = (1 - u(t))\\beta si(t, \\xi) - \\xi e(t, \\xi), && \\forall t \\in \\mathcal{D}_{t}, \\xi \\in \\mathcal{D}_{\\xi} \\\\\n# &&&&& \\frac{\\partial i(t, \\xi)}{\\partial t} = \\xi e(t, \\xi) - \\gamma i(t, \\xi), && \\forall t \\in \\mathcal{D}_{t}, \\xi \\in \\mathcal{D}_{\\xi} \\\\\n# &&&&& \\frac{\\partial r(t, \\xi)}{\\partial t} = \\gamma i(t, \\xi), && \\forall t \\in \\mathcal{D}_{t}, \\xi \\in \\mathcal{D}_{\\xi} \\\\\n# &&&&& si(t, \\xi) = s(t, \\xi) i(t, \\xi), && \\forall \\forall t \\in \\mathcal{D}_{t}, \\xi \\in \\mathcal{D}_{\\xi} \\\\\n# &&&&& s(0, \\xi) = s_0, e(0, \\xi) = e_0, i(0, \\xi) = i_0, r(0, \\xi) = r_0, && \\forall \\xi \\in \\mathcal{D}_{\\xi} \\\\\n# &&&&& i(t, \\xi) \\leq i_{max}, && \\forall t \\in \\mathcal{D}_{t}, \\xi \\in \\mathcal{D}_{\\xi} \\\\\n# &&&&& u(t) \\in [0, 0.8] \\\\\n# &&&&& \\xi \\sim \\mathcal{U}(\\underline{\\xi}, \\overline{\\xi})\n# \\end{aligned}\n# ```\n# Notice that the SEIR model variables now all depend on both ``t`` and ``\\xi``, \n# except ``u(t)`` which means we need to decide our policy before knowing the \n# true value of ``\\xi``.\n\n# ## Modeling in InfiniteOpt\n# Traditional modeling frameworks like JuMP cannot be used to solve this model \n# directly because it is infinite, contains partial difference equations, and \n# contains a time expectation. We would first have to transform it into a \n# transcripted (discretized) variant by applying all the necessary techniques \n# (e.g., orthogonal collocation over finite elements, trapezoid rule, etc.) \n# which is very combersome and nontrivial in this case. \n\n# However, we can directly model the above form in InfiniteOpt and it will take \n# care of the rest! Let's get started by importing the needed packages and \n# specifying the model parameters that we'll need.\n\nusing InfiniteOpt, Ipopt, Distributions, Plots\n\n## Set the SEIR parameters\nγ = 0.303\nβ = 0.727\nN = 1e5\nξ_min = 0.1 \nξ_max = 0.6\n\n## Set the domain information\ni_max = 0.02\nϵ = 0.005\nt0 = 0\ntf = 200\nextra_ts = [0.001, 0.002, 0.004, 0.008, 0.02, 0.04, 0.08, 0.2, 0.4, 0.8]\nnum_samples = 5\n\n## Set the intial condition values\ne0 = 1 / N\ni0 = 0\nr0 = 0\ns0 = 1 - 1 / N;\n\n# ## Model Initialization\n# Now let's setup our infinite model and select Ipopt as our optimizer that will \n# be used to solve it. This is accomplished making an [`InfiniteModel`](@ref):\nmodel = InfiniteModel(Ipopt.Optimizer);\n\n# ## Infinite Parameter Definition\n# We now need to define the infinite parameters ``t \\in [t_0, t_f]`` and \n# ``\\xi \\sim \\mathcal{U}(\\underline{\\xi}, \\overline{\\xi})``. This is accomplished \n# with [`@infinite_parameter`](@ref). We'll also include the following \n# specifications:\n# - use 51 equidistant time points\n# - specify that orgothonal collocation using 2 nodes should be used for time derivatives\n# - specify that the number of random scenarios should equal `num_samples`\n# - add `extra_ts` as extra time points\n@infinite_parameter(model, t ∈ [t0, tf], num_supports = 51, \n                    derivative_method = OrthogonalCollocation(2))\n@infinite_parameter(model, ξ ~ Uniform(ξ_min, ξ_max), num_supports = num_samples)\nadd_supports(t, extra_ts)\n\n# ## Infinite Variable Definition\n# With our infinite parameters defined, we can now define our infinite variables:\n# - ``s(t, \\xi) \\geq 0``\n# - ``e(t, \\xi) \\geq 0``\n# - ``i(t, \\xi) \\geq 0``\n# - ``r(t, \\xi) \\geq 0``\n# - ``si(t, \\xi)``\n# - ``0 \\leq u(t) \\leq 0.8``\n@variable(model, s ≥ 0, Infinite(t, ξ))\n@variable(model, e ≥ 0, Infinite(t, ξ))\n@variable(model, i ≥ 0, Infinite(t, ξ))\n@variable(model, r ≥ 0, Infinite(t, ξ))\n@variable(model, si, Infinite(t, ξ))\n@variable(model, 0 ≤ u ≤ 0.8, Infinite(t), start = 0.2)\n\n# ## Objective Definition\n# Now its time to add the objective \n# ``\\min \\ \\int_{t \\in \\mathcal{D}_{t}} u(t) dt`` using `@objective`:\n@objective(model, Min, ∫(u, t))\n\n# ## Constraint Definition\n# The last step now to defining our model is to define the constraints using \n# `@constraint`. This will involve defining the initial conditions:\n# ```math \n# s(0, \\xi) = s_0, e(0, \\xi) = e_0, i(0, \\xi) = i_0, r(0, \\xi) = r_0, \\ \\forall \\xi \\in \\mathcal{D}_{\\xi}\n# ```\n# the model equations:\n# ```math \n# \\begin{aligned}\n# &&& \\frac{\\partial s(t, \\xi)}{\\partial t} = (u(t) - 1)\\beta si(t, \\xi), && \\forall t \\in \\mathcal{D}_{t}, \\xi \\in \\mathcal{D}_{\\xi} \\\\\n# &&& \\frac{\\partial e(t, \\xi)}{\\partial t} = (1 - u(t))\\beta si(t, \\xi) - \\xi e(t, \\xi), && \\forall t \\in \\mathcal{D}_{t}, \\xi \\in \\mathcal{D}_{\\xi} \\\\\n# &&& \\frac{\\partial i(t, \\xi)}{\\partial t} = \\xi e(t, \\xi) - \\gamma i(t, \\xi), && \\forall t \\in \\mathcal{D}_{t}, \\xi \\in \\mathcal{D}_{\\xi} \\\\\n# &&& \\frac{\\partial r(t, \\xi)}{\\partial t} = \\gamma i(t, \\xi), && \\forall t \\in \\mathcal{D}_{t}, \\xi \\in \\mathcal{D}_{\\xi} \\\\\n# &&& si(t, \\xi) = s(t, \\xi) i(t, \\xi), && \\forall \\forall t \\in \\mathcal{D}_{t}, \\xi \\in \\mathcal{D}_{\\xi}, \\\\\n# \\end{aligned}\n# ```\n# and the infection limit constraint:\n# ```math \n# i(t, \\xi) \\leq i_{max}, \\ \\forall t \\in \\mathcal{D}_t, \\xi \\in \\mathcal{D}_{\\xi}.\n# ```\n## Define the initial conditions\n@constraint(model, s == s0, DomainRestrictions(t => 0))\n@constraint(model, e == e0, DomainRestrictions(t => 0))\n@constraint(model, i == i0, DomainRestrictions(t => 0))\n@constraint(model, r == r0, DomainRestrictions(t => 0))\n\n## Define the SEIR equations\n@constraint(model, s_constr, ∂(s, t) == -(1 - u) * β * si)\n@constraint(model, e_constr, ∂(e, t) == (1 - u) * β * si - ξ * e)\n@constraint(model, i_constr, ∂(i, t) == ξ * e - γ * i)\n@constraint(model, r_constr, ∂(r, t) == γ * i)\n@constraint(model, si == s * i)\n\n## Define the infection rate limit\n@constraint(model, imax_constr, i ≤ i_max)\n\n# ## Display the Infinite Model\n# Let's display `model` now that it is fully defined:\nprint(model)\n\n# ## Optimize the Model\n# Let's solve our model and find the optimal policy. All we have to do is \n# invoke `optimize!` and the model will automatically be transformed solved behind \n# the scenes:\noptimize!(model)\n\n# ## Retrieve and Plot the Results\n# Now we can retrieve the optimal results and plot them to visualize the optimal \n# policy. Note that the values of infinite variables will be returned as arrays \n# corresponding to how the supports were used to discretize our model. We can \n# retrieve our values using `value`.\n\n# Get the results:\nr_opt = value(r, ndarray = true) * 100 # make the population fractions into percentages\ns_opt = value(s, ndarray = true) * 100\ni_opt = value(i, ndarray = true) * 100\ne_opt = value(e, ndarray = true) * 100\nu_opt = value(u)\nobj_opt = objective_value(model)\nts = value(t)\nξs = value(ξ);\n\n# Plot the values of ``r(t, \\xi)`` and ``s(t, \\xi)`` over time with \n# confidence bounds:\nr_mean = mean(r_opt, dims = 2)\nr_std = std(r_opt, dims = 2)\nplot(ts, r_mean, label = \"r(t, ξ)\", linecolor = :red, background_color = :transparent)\nplot!(ts, r_mean + r_std, linecolor = :red, linestyle = :dash, linealpha = 0.4, label = \"\")\nplot!(ts, r_mean - r_std, linecolor = :red, linestyle = :dash, linealpha = 0.4, label = \"\")\n\ns_mean = mean(s_opt, dims = 2)\ns_std = std(s_opt, dims = 2)\nplot!(ts, s_mean, label = \"s(t, ξ)\", linecolor = :blue)\nplot!(ts, s_mean + s_std, linecolor = :blue, linestyle = :dash, linealpha = 0.4, label = \"\")\nplot!(ts, s_mean - s_std, linecolor = :blue, linestyle = :dash, linealpha = 0.4, label = \"\")\nylabel!(\"Pop. (%)\")\nxlabel!(\"Time (Days)\")\n\n# Plot the values of ``i(t, \\xi)`` and ``e(t, \\xi)`` over time with \n# confidence bounds:\ni_mean = mean(i_opt, dims = 2)\ni_std = std(i_opt, dims = 2)\nplot(ts, i_mean, label = \"i(t, ξ)\", linecolor = :green, background_color = :transparent)\nplot!(ts, i_mean + i_std, linecolor = :green, linestyle = :dash, linealpha = 0.4, label = \"\")\nplot!(ts, i_mean - i_std, linecolor = :green, linestyle = :dash, linealpha = 0.4, label = \"\")\n\ne_mean = mean(e_opt, dims = 2)\ne_std = std(e_opt, dims = 2)\nplot!(ts, e_mean, label = \"e(t, ξ)\", linecolor = :purple)\nplot!(ts, e_mean + e_std, linecolor = :purple, linestyle = :dash, linealpha = 0.4, label = \"\")\nplot!(ts, e_mean - e_std, linecolor = :purple, linestyle = :dash, linealpha = 0.4, label = \"\")\nylabel!(\"Pop. (%)\")\nxlabel!(\"Time (Days)\")\n\n# Plot the values of ``u(t)`` over time:\nplot(ts, u_opt, linecolor = :orange, label = \"u(t)\", ylims = (-0.02, 1.02), \n     background_color = :transparent)\nxlabel!(\"Time (Days)\")\nylabel!(\"Distancing Ratio\")\n\n# ### Maintenance Tests\n# These are here to ensure this example stays up to date. \nusing Test\n@test termination_status(model) == MOI.LOCALLY_SOLVED\n@test has_values(model)\n@test u_opt isa Vector{<:Real}\n", "meta": {"hexsha": "af573964044dd36951b82b866cbe329fbd096360", "size": 10424, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/Optimal Control/pandemic_control.jl", "max_stars_repo_name": "azev77/InfiniteOpt.jl", "max_stars_repo_head_hexsha": "db734856e6d89fd105f7bdb4fb5b8e16a72bd7fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/src/examples/Optimal Control/pandemic_control.jl", "max_issues_repo_name": "azev77/InfiniteOpt.jl", "max_issues_repo_head_hexsha": "db734856e6d89fd105f7bdb4fb5b8e16a72bd7fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/src/examples/Optimal Control/pandemic_control.jl", "max_forks_repo_name": "azev77/InfiniteOpt.jl", "max_forks_repo_head_hexsha": "db734856e6d89fd105f7bdb4fb5b8e16a72bd7fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.547008547, "max_line_length": 154, "alphanum_fraction": 0.6413085188, "num_tokens": 3481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7988778266711486}}
{"text": "using LinearAlgebra: pinv\nusing DSP: conv\n\nexport savitzky_golay_filter\n\n\"\"\"\n\tsavitzky_golay_filter(y::AbstractVector, window_size::Integer, polynomial_order::Integer; deriv_order::Integer = 0, boundary_mode = :interpolation)\n\nApply Savitzky-Golay polynomial smoothing to input data `y` using a polynomial of order `polynomial_order` fit to a moving window `window_size` points wide. Optionally derivatives can be taken by specifying the `deriv_order` and the caller is responsible for the appropriate scaling by the point spacing. Handling of data within half the window size is specified by `boundary_mode`. When set to `:interpolation` the polynomial fit will be used; when set to `:nearest` the data will be padded using the edge values before convolution and the valid portion will then be returned.  \n\n# References\n1. Savitzky, A., & Golay, M. J. E. (1964). Smoothing and Differentiation of Data by Simplified Least Squares Procedures. Analytical Chemistry, 36(8), 1627–1639. https://doi.org/10.1021/ac60214a047\n2. Steinier, J., Termonia, Y., & Deltour, J. (1972). Comments on Smoothing and differentiation of data by simplified least square procedure. Analytical Chemistry, 44(11), 1906–1909. https://doi.org/10.1021/ac60319a045\n3. Press, W. H., & Teukolsky, S. A. (1990). Savitzky-Golay Smoothing Filters. Computers in Physics, 4(6), 669. https://doi.org/10.1063/1.4822961\n\"\"\"\nfunction savitzky_golay_filter(y::AbstractVector, window_size::Integer, polynomial_order::Integer; deriv_order::Integer = 0, boundary_mode = :interpolation)\n\n\t# input validity checks\n   \t@assert isodd(window_size) \"Window size must be an odd integer, i.e. fitting 2m + 1 points around the current value.\"\n\t@assert polynomial_order < window_size \"Polynomial order must be less than the window size.\"\n\t@assert boundary_mode in (:interpolation, :nearest) \"boundary_mode must be one of :interpolation, :nearest\"\n\n\t# window size is 2m + 1 points\n   \tm = (window_size - 1) ÷ 2\n\t\n\t# build the Vandermonde design matrix A. Each row corresponds to a point in the fitting window -m:m\n\t# and each columns correspond to powers in the range 0:polynomial_order\n   \tfitting_points = -m:m\n   \tA = Matrix{Float64}(undef, window_size, polynomial_order + 1)\n   \tfor i in 1:window_size, j in 1:polynomial_order + 1\n        A[i,j] = fitting_points[i]^(j - 1)\n    end\n\n\tif boundary_mode == :interpolation\n\t\t# for interpolation we'll want the full pseudo-inverse so we can calculate all the fit values at the edges\n\t\t# Ap = y\n\t\tC = pinv(A)\n\n\t\t# the filter coefficients are the rows of `C`\n\t\tfilter_coeffs = C[deriv_order + 1,:] * factorial(deriv_order)\n\n\t\t# convolve with the filter coefficients with a couple extra steps:\n\t\t# 1. because of convolution will reverse coefficients we flip before\n\t\t# 2. c = conv(a,b) will return a vector of length(c) = length(a) + length(b) - 1 so we chop off the first and last m points\n\t\tsmoothed = conv(reverse(filter_coeffs), y)[m+1:end-m]\n\n\t\t# for interpolation edge handling calculate the full fits\n\t\tif deriv_order == 0\n\t\t\t# if we are just smoothing then we can use the design and coefficient matrix as is\n\t\t\tAC = A*C\n\t\t\tsmoothed[1:m] = (AC*y[1:window_size])[1:m]\n\t\t\tsmoothed[end-m+1:end] = (AC*y[end-window_size+1:end])[end-m+1:end]\n\t\telse\n\t\t\t# otherwise we need to differentiate the polynomial coefficients\n\t\t\t# first m points\n\t\t\tp = C * y[1:window_size]\n\t\t\tfor _ in 1:deriv_order\n\t\t\t\tp = [(i-1)*p[i] for i in 2:length(p)]\n\t\t\tend\n\t\t\tsmoothed[1:m] = A[1:m, 1:size(A,2)-deriv_order]*p\n\t\t\t# last m points\n\t\t\tp = C * y[end-window_size+1:end]\n\t\t\tfor _ in 1:deriv_order\n\t\t\t\tp = [(i-1)*p[i] for i in 2:length(p)]\n\t\t\tend\n\t\t\tsmoothed[end-m+1:end] = A[m+2:end, 1:size(A,2)-deriv_order]*p\n\n\t\tend\n\n\t\treturn smoothed\n\n\telseif boundary_mode == :nearest\n\n\t\t# here we only need a single set of coefficients and so we can least-squares solve AᵀCᵀ = I for for a single row by picking a single column out of I\n\t\tIcol = zeros(Float64, polynomial_order+1, 1)\n\t\tIcol[deriv_order + 1] = 1.0\n\t\tfilter_coeffs = transpose(A) \\ Icol\n\n\t\t# pad the signal with the endpoints\n\t\tpadded_y = [y[1] * ones(m); vec(y); y[end] * ones(m)]\n\n\t\t# convolve with filter\n\t\tsmoothed = conv(filter_coeffs[end:-1:1], padded_y)\n\n\t\t# and return the valid midsection\n\t\treturn smoothed[window_size:end-2*m]\n\n\tend\n\nend\n", "meta": {"hexsha": "6289045ad176c1be44641deb03f7acef7818adda", "size": 4270, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SavitzkyGolay.jl", "max_stars_repo_name": "BBN-Q/Qlab.jl", "max_stars_repo_head_hexsha": "2f6330adff30723eea4d7db15ce90c1114cfdd90", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2016-05-10T15:05:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:16:59.000Z", "max_issues_repo_path": "src/SavitzkyGolay.jl", "max_issues_repo_name": "BBN-Q/Qlab.jl", "max_issues_repo_head_hexsha": "2f6330adff30723eea4d7db15ce90c1114cfdd90", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 38, "max_issues_repo_issues_event_min_datetime": "2016-08-02T13:08:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-30T06:23:46.000Z", "max_forks_repo_path": "src/SavitzkyGolay.jl", "max_forks_repo_name": "BBN-Q/Qlab.jl", "max_forks_repo_head_hexsha": "2f6330adff30723eea4d7db15ce90c1114cfdd90", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-10-28T12:11:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:53:31.000Z", "avg_line_length": 46.9230769231, "max_line_length": 579, "alphanum_fraction": 0.7224824356, "num_tokens": 1269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.8633916134888613, "lm_q1q2_score": 0.7988357801617375}}
{"text": "using KFEstimate\nusing LinearAlgebra, Plots, Zygote, Statistics, Revise\nusing Flux, Flux.Optimise\nusing ProgressBars\npathof(KFEstimate)\n\ndt = 0.001\nA = [1.0 dt 1/2*dt^2; 0.0 1.0 dt; 0.0 0.0 1.0]\nB = [0.0; 0.0; 1.0]\nB = reshape(B, length(B), 1)\nQ = 1*Matrix{Float64}(I, 3, 3)\n\n# observation model, assume we can noisily measure position\nH = randn(3, 3)\n# H = [1 0 0; 0 1 0; 0 0 1]\nR = 10.0*Matrix{Float64}(I, 3, 3)\n\nkf = KalmanFilter(A, B, Q, H, R)\n\n# run simulation\ntime_step = 0:1000\nx0 = [0.0; 0.0; 0.0]\naction_sequence = [[1] for t in time_step]\nsim_states, sim_measurements = run_simulation(kf, x0, action_sequence)\n# run kalman filter\nP0 = Matrix{Float64}(I, 3, 3)\ns0 = State(x0, P0) # initial state belief\nfiltered_states = run_filter(kf, s0, action_sequence, sim_measurements)\n\n# unpack sim and filtered states\nμ, Σ = unpack(filtered_states)\np = [x[1] for x in sim_states]\nv = [x[2] for x in sim_states]\na = [x[3] for x in sim_states]\nx = hcat(p, v, a)\n# plot\nplot(time_step, [x[2:end, 1] x[2:end, 2] x[2:end, 3]], label = [\"simulated p\" \"simulated v\" \"simulated a\"])\nplot!(time_step, [μ[2:end, 1] μ[2:end, 2] μ[2:end, 3]], label = [\"filtred p\" \"filtered v\" \"filtered a\"])\nxlabel!(\"time step (t)\")\n\n##\n\n# parametrized matrix estimates\nAhat(θ) = [θ[1] dt 1/2*dt^2; 0.0 θ[1] dt; 0.0 0.0 θ[1]]\nBhat(θ) = B\nQhat(θ) = Q\nHhat(θ) = H\nRhat(θ) = R\n# define a parametrized kalman filter\nparam_kf = ParamKalmanFilter(Ahat, Bhat, Qhat, Hhat, Rhat)\n\n\nθ0 = [1.1]\npkf = ParamKalmanFilter(Ahat, Bhat, Qhat, Hhat, Rhat)\n\nloss = []\nθ_range = 0.9:0.001:1.1\nfor i in θ_range\n    θ_i = [i]\n    states = run_param_kf(θ_i, pkf, s0, action_sequence, sim_measurements)\n    l = kf_likelihood(θ_i, param_kf, states, action_sequence, sim_measurements)\n    push!(loss, l)\nend\n\nplot(θ_range, loss)\n\n##\n\n# parametrized matrix estimates\nAhat(θ) = [θ[1] θ[2] θ[3]; 0 θ[1] θ[2]; 0 0 θ[1]]\n# Ahat(θ) = [θ[1, 1] θ[1, 2] θ[1, 3]; 0.0 θ[2, 2] θ[2, 3]; 0.0 0.0 θ[3, 3]]\nBhat(θ) = B\nQhat(θ) = Q\nHhat(θ) = H\nRhat(θ) = R\n# define a parametrized kalman filter\nparam_kf = ParamKalmanFilter(Ahat, Bhat, Qhat, Hhat, Rhat)\n\nθ0 = [1.0 dt 1/2*dt^2] + 0.1*randn(1, 3)\nopt = ADAM(0.01)\nepochs = 200\nnewθ, loss = run_kf_gradient(θ0, param_kf, s0, action_sequence, sim_measurements, opt, epochs)\n\ngrad_states = run_param_filter(newθ, param_kf, s0, action_sequence, sim_measurements)\nμgrad, Σgrad = unpack(grad_states)\n\nl = @layout [a{0.7h};grid(1, 3)]\np1 = plot(time_step, [x[2:end, 1] x[2:end, 2] x[2:end, 3]], label = [\"simulated p\" \"simulated v\" \"simulated a\"], xlabel=\"time step (t)\")\np1 = plot!(time_step, [μ[2:end, 1] μ[2:end, 2] μ[2:end, 3]], label = [\"filtered p\" \"filtered v\" \"filtered a\"], xlabel=\"time step (t)\")\np1 = plot!(time_step, [μgrad[2:end, 1] μgrad[2:end, 2] μgrad[2:end, 3]], label = [\"learned p\" \"learned v\" \"learned a\"],  xlabel=\"time step (t)\")\np2 = plot(1:epochs, loss, title=\"loss\", xlabel=\"number of epochs\")\np3 = plot(time_step, (x[2:end, :]-μ[2:end, :]).^2, title=\"KF vs. sim error\", xlabel=\"time step (t)\")\np4 = plot(time_step, (x[2:end, :]-μgrad[2:end, :]).^2, title=\"grad vs. sim error\", xlabel=\"time step (t)\")\nplot(p1, p2, p3, p4, layout=l, titlefont = font(12), size=(1000, 700))\n", "meta": {"hexsha": "15b630225c270230321e9d81c8ce849ed4d931f7", "size": 3169, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/linear.jl", "max_stars_repo_name": "jgbrasier/KFEstimate.jl", "max_stars_repo_head_hexsha": "5ed50b4b2a65d7ba6c782070bb8c145f83c0f3a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-20T15:16:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T12:48:24.000Z", "max_issues_repo_path": "examples/linear.jl", "max_issues_repo_name": "jgbrasier/KFEstimate.jl", "max_issues_repo_head_hexsha": "5ed50b4b2a65d7ba6c782070bb8c145f83c0f3a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/linear.jl", "max_forks_repo_name": "jgbrasier/KFEstimate.jl", "max_forks_repo_head_hexsha": "5ed50b4b2a65d7ba6c782070bb8c145f83c0f3a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-07T15:23:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T03:10:21.000Z", "avg_line_length": 33.3578947368, "max_line_length": 144, "alphanum_fraction": 0.64626065, "num_tokens": 1355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299529686199, "lm_q2_score": 0.863391602943619, "lm_q1q2_score": 0.798835772185026}}
{"text": "for f in [:chebyshev_basis, :sin_basis, :cos_basis, :fourier_basis, :polynomial_basis, :monomial_basis]\n    @eval $f(x, c) = $f(scalarize(x), c)\nend\nfunction _generateBasis!(eqs, f, x, coeffs)\n    n_x = size(x, 1)\n    @assert length(eqs) == size(x, 1)*length(coeffs)\n    @inbounds for (i, ti) in enumerate(coeffs)\n        eqs[(i-1)*n_x+1:i*n_x] .= f(x, ti)\n    end\n    return\nend\n\n\n\"\"\"\n$(SIGNATURES)\n\nConstructs an array containing a Chebyshev basis in the variables `x` with coefficients `c`.\nIf `c` is an `Int` returns all coefficients from 1 to `c`.\n\"\"\"\nfunction chebyshev_basis(x::Array, coefficients::AbstractVector)\n    eqs = Array{Num}(undef, size(x, 1)*length(coefficients))\n    f(x, t) = cos.(t .* acos.(x))\n    _generateBasis!(eqs, f, x, coefficients)\n    eqs\nend\n\nchebyshev_basis(x::Array, terms::Int) = chebyshev_basis(x, 1:terms)\n\n\n\"\"\"\n$(SIGNATURES)\n\nConstructs an array containing a Sine basis in the variables `x` with coefficients `c`.\nIf `c` is an `Int` returns all coefficients from 1 to `c`.\n\"\"\"\nfunction sin_basis(x::Array, coefficients::AbstractVector)\n    eqs = Array{Num}(undef, size(x, 1)*length(coefficients))\n    f(x, t) = sin.(t .* x)\n    _generateBasis!(eqs, f, x, coefficients)\n    eqs\nend\n\nsin_basis(x::Array, terms::Int) = sin_basis(x, 1:terms)\n\n\n\"\"\"\n$(SIGNATURES)\n\nConstructs an array containing a Cosine basis in the variables `x` with coefficients `c`.\nIf `c` is an `Int` returns all coefficients from 1 to `c`.\n\"\"\"\nfunction cos_basis(x::Array, coefficients::AbstractVector)\n    eqs = Array{Num}(undef, size(x, 1)*length(coefficients))\n    f(x, t) = cos.(t .* x)\n    _generateBasis!(eqs, f, x, coefficients)\n    eqs\nend\n\ncos_basis(x::Array, terms::Int) = cos_basis(x, 1:terms)\n\n\n\"\"\"\n$(SIGNATURES)\n\nConstructs an array containing a Fourier basis in the variables `x` with (integer) coefficients `c`.\nIf `c` is an `Int` returns all coefficients from 1 to `c`.\n\"\"\"\nfunction fourier_basis(x::Array, coefficients::AbstractVector{Int})\n    eqs = Array{Num}(undef, size(x, 1)*length(coefficients))\n    f(x, t) = iseven(t) ? cos.(t .* x ./ 2) : sin.(t .* x ./2)\n    _generateBasis!(eqs, f, x, coefficients)\n    eqs\nend\n\nfourier_basis(x::Array, terms::Int) = fourier_basis(x, 1:terms)\n\n\"\"\"\n$(SIGNATURES)\n\nConstructs an array containing a polynomial basis in the variables `x` up to degree `c` of the form\n`[x₁, x₂, x₃, ..., x₁^1 * x₂^(c-1)]`. Mixed terms are included.\n\"\"\"\nfunction polynomial_basis(x::Array, degree::Int = 1)\n    @assert degree > 0\n    n_x = length(x)\n    n_c = binomial(n_x+degree, degree)\n    eqs = Array{Num}(undef, n_c)\n    _check_degree(x) = sum(x)<=degree ? true : false\n    itr = Base.Iterators.product([0:degree for i in 1:n_x]...)\n    itr_ = Base.Iterators.Stateful(Base.Iterators.filter(_check_degree, itr))\n    filled = false\n    @inbounds for i in 1:n_c\n        eqs[i] = 1\n        filled = true\n        for (xi, ci) in zip(x, popfirst!(itr_))\n            if !iszero(ci)\n                filled ? eqs[i] = xi^ci : eqs[i] *= xi^ci\n                filled = false\n            end\n        end\n    end\n    eqs\nend\n\n\n\"\"\"\n$(SIGNATURES)\n\nConstructs an array containing monomial basis in the variables `x` up to degree `c` of the form\n`[x₁, x₁^2, ... , x₁^c, x₂, x₂^2, ...]`.\n\"\"\"\nfunction monomial_basis(x::AbstractArray, degree::Int = 1)\n    @assert degree > 0\n    n_x = length(x)\n    exponents = 1:degree\n    n_e = length(exponents)\n    n_c = n_x * n_e + 1\n    eqs = Array{Num}(undef, n_c)\n    eqs[1] = Num(1)\n    idx = 0\n    for i in 1:n_x, j in 1:n_e\n        idx = (i-1)*n_e+j+1\n        eqs[idx] = x[i]^exponents[j]\n    end\n    eqs\nend\n", "meta": {"hexsha": "f180f2cbf02c7e451d3bd7e5dd858c6f7da8f020", "size": 3583, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/basis_generators.jl", "max_stars_repo_name": "augustinas1/DataDrivenDiffEq.jl", "max_stars_repo_head_hexsha": "dda0763d7e9689c78cc2afc7179f9d574a1d4698", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 254, "max_stars_repo_stars_event_min_datetime": "2020-03-30T00:07:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T14:43:09.000Z", "max_issues_repo_path": "src/utils/basis_generators.jl", "max_issues_repo_name": "augustinas1/DataDrivenDiffEq.jl", "max_issues_repo_head_hexsha": "dda0763d7e9689c78cc2afc7179f9d574a1d4698", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 156, "max_issues_repo_issues_event_min_datetime": "2020-03-25T19:14:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:19:59.000Z", "max_forks_repo_path": "src/utils/basis_generators.jl", "max_forks_repo_name": "augustinas1/DataDrivenDiffEq.jl", "max_forks_repo_head_hexsha": "dda0763d7e9689c78cc2afc7179f9d574a1d4698", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2020-03-28T23:52:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T07:25:25.000Z", "avg_line_length": 28.2125984252, "max_line_length": 103, "alphanum_fraction": 0.6310354452, "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.8633915994285382, "lm_q1q2_score": 0.7988357653726428}}
{"text": "# export fourier_nodes, fourier_wavenumbers, cheb\nusing LinearAlgebra, FFTW\n\n\"\"\"\nfourier_nodes(n; a = 0, b = 2π)\n# Description\n- Create a uniform grid of points for periodic functions\n# Arguments\n- `N`: integer | number of evenly spaced points \n# Keyword Arguments\n- `a`: number | starting point of interval [a, b)\n- `b`: number | ending point of interval [a, b)\n# Return\n- `g`: array | an array of points of evenly spaced points from [a, b)\n\"\"\"\nfunction fourier_nodes(N; a = 0, b = 2π)\n    return (b - a) .* collect(0:(N - 1)) / N .+ a\nend\n\n\"\"\"\nfourier_wavenumbers(N; L = 2π)\n# Description\n- Create wavenumbers associated with the domain of length L\n# Arguments\n- `N`: integer | number of wavevectors\n# Keyword Arguments\n- `L`: number | length of interval [a, b), L = b-a\n# Return\n- `wavenumbers`: array | an array of wavevectors\n\"\"\"\nfunction fourier_wavenumbers(N; L = 2π)\n    up = collect(0:1:(N - 1))\n    down = collect((-N):1:-1)\n    indices = up\n    indices[(div(N, 2) + 1):end] = down[(div(N, 2) + 1):end]\n    wavenumbers = 2π / L .* indices\n    return wavenumbers\nend\n\n\"\"\"\n# Description\nSpectral differentiation matrix and nodes for periodic domains\n# Argument\n- 'N': number of gridpoints\n# Keyword Argument\na and b specify the interval [a, b)\ndefault assumes x ∈ [0, 2π)\n# Return\n- 'D': Fourier differentiation matrix\n- 'x': Fourier grid points\n\"\"\"\nfunction fourier(N; a = 0, b = 2π)\n    if N == 0\n        return [0], [0]\n    else\n        k = fourier_wavenumbers(N, L = b - a)\n        x = fourier_nodes(N, a = a, b = b)\n        ℱ = fft(I + zeros(N, N), 1)\n        ℱ⁻¹ = ifft(I + zeros(N, N), 1)\n        D = real.(ℱ⁻¹ * Diagonal(im .* k) * ℱ)\n        return D, x\n    end\nend\n\n\"\"\"\n# Description\nJulia version of Spectral Methods in Matlab\n# Argument\n- 'N': polynomial order\n# Keyword Argument\na and b specify the interval [a, b]\ndefault assumes x ∈ [-1, 1]\n# Return\n- 'D': Chebyshev differentiation matrix\n- 'x': Guass-Lobatto points\n\"\"\"\nfunction chebyshev(N; a = -1, b = 1)\n    if N == 0\n        return [0], [(a + b) / 2]\n    else\n        x = @. cos(pi * (0:N) / N)\n        c = [2; ones(N - 1); 2] .* (-1) .^ (0:N)\n        dX = x .- x'\n        D = (c ./ c') ./ (dX + I)                # off-diagonal entries\n        D = D - Diagonal(sum(D', dims = 1)[1:(N + 1)]) # diagonal entries\n        return 2 / (b - a) * D, (b - a) * (x .+ 1) / 2 .+ a\n    end\nend\n", "meta": {"hexsha": "7f1240bbf51d85e7397aa02d5be0816778aa14be", "size": 2362, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spectral.jl", "max_stars_repo_name": "sandreza/StatisticalNonlocality", "max_stars_repo_head_hexsha": "0e58dcd6a1a8a8c2594ffe428760520556211aa9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/spectral.jl", "max_issues_repo_name": "sandreza/StatisticalNonlocality", "max_issues_repo_head_hexsha": "0e58dcd6a1a8a8c2594ffe428760520556211aa9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-07T18:48:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-07T18:48:00.000Z", "max_forks_repo_path": "src/spectral.jl", "max_forks_repo_name": "sandreza/StatisticalNonlocality", "max_forks_repo_head_hexsha": "0e58dcd6a1a8a8c2594ffe428760520556211aa9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5393258427, "max_line_length": 73, "alphanum_fraction": 0.5859441152, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7988282997486649}}
{"text": "# This file includes the MonteCarlo simulation of FSK modulation scheme and compares \n# the numerical results with the theoretical results. \n\nusing DigitalCommunications \nusing Plots \n\n# Settings\npulse = RectangularPulse()          # Modulation pulse \nfs = 10                             # Samling frequency \nts = 1 / fs                         # Sampling period \ntb = pulse.duration                 # Pulse duration \nk = 3                               # Bits per symbol \nM = 2^k                             # Costellation size \nnsymbols = Int(1e6)                 # Number of symbols \nebno = collect(-2 : 8)              # Energy per bit to noise power spectral density ratio \nesno = ebno .+ 10 * log10(k)        # Energy per symbol to noise power spectral densit ratio.\n\n# Communcation system components  \ngen = SymbolGenerator(nsymbols, M) \nmodulator = Modulator(FSK(M), RectangularPulse(), ts)\nchannel = AWGNChannel(1., ts, tb)\ndetector = Detector(modulator(1:M))\n\n# Monte Carlo simulation \nmessage = gen.symbols  \nsymerr = zeros(length(esno))\nfor i in 1 : length(symerr)\n    channel.esno = esno[i]  # Update channel noise level \n    mbar = message |> modulator |> channel |> detector  # Run communication system \n    symerr[i] = sum(mbar .!= message) / length(message)  # Symbol error rate \nend\n\n# Plots\nplt = plot(title=\"$M-PSK\", xlabel=\"ebno [dB]\", ylabel=\"Pe\") \nplot!(ebno, berfsk.(esno, M), marker=:circle, yscale=:log10, label=\"theoretical\")\nplot!(ebno, symerr, marker=:circle, yscale=:log10, label=\"montecarlo\")\n", "meta": {"hexsha": "f2a6477a07f9b00971e52ba40c9a6eb1e6a82ebf", "size": 1524, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/waveform_simulations/montecarlofsk.jl", "max_stars_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_stars_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-03T20:02:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T06:43:38.000Z", "max_issues_repo_path": "example/waveform_simulations/montecarlofsk.jl", "max_issues_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_issues_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-11-26T21:56:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-03T19:54:59.000Z", "max_forks_repo_path": "example/waveform_simulations/montecarlofsk.jl", "max_forks_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_forks_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-20T12:53:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T12:53:43.000Z", "avg_line_length": 41.1891891892, "max_line_length": 93, "alphanum_fraction": 0.6332020997, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936262, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7988282965213757}}
{"text": "#===============================================================================\n\nThe most naive way of computing n15 requires fourteen multiplications:\n\nn × n × ... × n = n15\n\nBut using a \"binary\" method you can compute it in six multiplications:\n\nn × n = n^2\nn^2 × n^2 = n^4\nn^4 × n^4 = n^8\nn^8 × n^4 = n^12\nn^12 × n^2 = n^14\nn^14 × n = n^15\n\nHowever it is yet possible to compute it in only five multiplications:\n\nn × n = n^2\nn^2 × n = n^3\nn^3 × n^3 = n^6\nn^6 × n^6 = n^12\nn^12 × n^3 = n^15\n\nWe shall define m(k) to be the minimum number of multiplications to compute n^k;\nfor example m(15) = 5.\n\nFor 1 ≤ k ≤ 200, find ∑ m(k).\n\n--------------------------------------------------------------------------------\n\nTo start with, this problem can be reformulated by asking how many additions are\nnecessary to reach a number starting from 1 and using only additions.\n\nThe general approach is bottom up. At every iteration we build a new set of sets\nof numbers. An inner set contains all the numbers that can be together obtained\nby 'iter' calculations.\n\nAn inner set is generated from a previous inner set by taking a copy of the\nlater, then by selecting one of its elements, by adding it to the initial\nelements and adding the numbers so obtained to the new set. This must be done\nfor all elements of the initial set.\n\nAt the next iteration, it is only necessary to consider the new elements that\nhave been added when selecting the element to add to the other.\n\nBecause a same inner set can be obtained from different paths, each new inner\nset is associated with the numbers selected to produce it.\n\nEach time a new number is generated, the corresponding iteration is recorded\nwith it.\n\n===============================================================================#\n\nusing Base.Test\n\nfunction compute_nbr_steps(limit)\n    nbr_steps = Array{Int}(limit)\n    # nbr_steps[i] is the number of addition needed to compute i (i.e. it is\n    # m(i)).\n\n    fill!(nbr_steps, -1)\n    sets = Dict{Set{Int}, Set{Int}}()\n    # Key is all numbers in the set, Value is the set of the numbers added\n    # during the previous iteration.\n\n    const empty_value = Set{Int}()\n    # empty_value is used as an indicator\n\n    completion = 1\n    iter = 0\n    nbr_steps[1] = 0\n    sets[Set{Int}(1)] = Set{Int}(1)\n\n    while completion<limit\n        iter += 1\n        updated_sets = typeof(sets)()\n\n        for (set, added_numbers) in sets, l in set, m in added_numbers\n            n=l+m\n            if n ≤ limit && n ∉ set\n                updated_set = copy(set)\n                push!(updated_set, n)\n\n                nums = get(updated_sets, updated_set, empty_value)\n\n                if nums == empty_value\n                    nums = Set{Int}(n)\n                else\n                    push!(nums, n)\n                end\n\n                updated_sets[updated_set] = nums\n\n                if nbr_steps[n]<0\n                    nbr_steps[n] = iter\n                    completion += 1\n                    println(\"\\t completion = $(completion)\")\n                    if completion == limit\n                        return nbr_steps\n                    end\n                end\n            end\n        end\n        sets = updated_sets\n    end\nend\n\nresult = compute_nbr_steps(200)\n\n@test result[15] == 5\n@test length(result) == 200\n\nprint(\"Euler 122: $(sum(result))\")\n", "meta": {"hexsha": "7c46a9012e913afaf9b148ebb7d212e25dd1cad7", "size": 3335, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0122.jl", "max_stars_repo_name": "dpieroux/euler", "max_stars_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "0122.jl", "max_issues_repo_name": "dpieroux/euler", "max_issues_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0122.jl", "max_forks_repo_name": "dpieroux/euler", "max_forks_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2543859649, "max_line_length": 80, "alphanum_fraction": 0.5727136432, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936262, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7988282928049961}}
{"text": "\nusing LinearAlgebra\n\n\n@doc \"\"\"\nGaussian kernel function.\n\n# Examples\n```jldoctest\ny = k(x)\n```\nwhere the 'x' is Vector{Float64} sample and 'y' is density in point 'x'.\n\"\"\" ->\nk(x::Vector{Float64}) = √(2*π)*ℯ^(-(x'*x)/2)\n\n\n@doc \"\"\"\nFunction to return Parzen window estimation.\n\n# Examples\n```jldoctest\nfun = Σ(h, X, f, x)\n```\nwhere the 'fun' is parzen window estimation, 'h' is window size,\n'X' is set of train samples (size(dim, N) ~ (dimension of data, data count),\n'f' is kernel function and 'x' is given Vector{Float64} sample.\n\"\"\" ->\ncreate_parzen_window(h::Float64, X::Matrix{Float64}, \n                        f, x::Vector{Float64}) = (1/(h*size(X)[1]))*mapreduce(a->f((x-a)/h), +, eachcol(X))\n", "meta": {"hexsha": "94fb7f340c4aaaebab4d2295fc74882ef06b6e51", "size": 701, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/parzenwindow.jl", "max_stars_repo_name": "kozvojtex/AnomalyDetection", "max_stars_repo_head_hexsha": "a62f1c14a679aab147638af53ba26165760bca91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/parzenwindow.jl", "max_issues_repo_name": "kozvojtex/AnomalyDetection", "max_issues_repo_head_hexsha": "a62f1c14a679aab147638af53ba26165760bca91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/parzenwindow.jl", "max_forks_repo_name": "kozvojtex/AnomalyDetection", "max_forks_repo_head_hexsha": "a62f1c14a679aab147638af53ba26165760bca91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3666666667, "max_line_length": 107, "alphanum_fraction": 0.6205420827, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7988282923159054}}
{"text": "export choice_probabilities, choice_probabilities!\n\n\"\"\"\nCompute the choice probabilities using an overflow safe algorithm.\n\nThis is just a wrapper around [`choice_probabilities!`](@ref) which computes them in-place.\n\"\"\"\nfunction choice_probabilities(utilities::AbstractMatrix{<:AbstractFloat})\n    probabilities = similar(utilities)\n    choice_probabilities!(probabilities, utilities)\n    return probabilities\nend\n\n\"\"\"\nCompute the choice probabilities in-place using an overflow safe algorithm.\n\nBased on the SoftmaxThreePassReload function from\nDukhan and Ablavatski (2020), The Two-Pass Softmax Algorithm (https://arxiv.org/abs/2001.04438).\n\"\"\"\nfunction choice_probabilities!(output::AbstractMatrix{T}, utilities::AbstractMatrix{T}) where T<:AbstractFloat\n    @assert size(output) == size(utilities) \"Output matrix must have same size as utilities matrix.\"\n    J, I = size(utilities)\n\n    @inbounds for i = 1:I\n        max_u = T(0)\n        for j = 1:J\n            if utilities[j, i] > max_u\n                max_u = utilities[j, i]\n            end\n        end\n\n        sigma = @fastmath exp(-max_u)\n\n        @simd ivdep for j = 1:J\n            output[j, i] = @fastmath exp(utilities[j, i] - max_u)\n            # SIMD makes left-to-right summation both faster and more accurate\n            # https://discourse.julialang.org/t/when-shouldnt-we-use-simd/18276/14\n            sigma += output[j, i]\n        end\n    \n        sigma_inv = 1 / sigma\n        @simd ivdep for j = 1:J\n            output[j, i] *= sigma_inv\n        end\n    end\nend\n", "meta": {"hexsha": "73a9fe5f9e8ab146b96808fcb5c3f4169c13252c", "size": 1536, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/softmax.jl", "max_stars_repo_name": "james-atkins/blp.jl", "max_stars_repo_head_hexsha": "9f431554e3846547974791ffe5e9628a3bde2903", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/softmax.jl", "max_issues_repo_name": "james-atkins/blp.jl", "max_issues_repo_head_hexsha": "9f431554e3846547974791ffe5e9628a3bde2903", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/softmax.jl", "max_forks_repo_name": "james-atkins/blp.jl", "max_forks_repo_head_hexsha": "9f431554e3846547974791ffe5e9628a3bde2903", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6808510638, "max_line_length": 110, "alphanum_fraction": 0.6595052083, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.946596665680527, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7988282902622564}}
{"text": "\"\"\"\n    expected_shortfall(returns, confidence, method; multiplier=1.0)\n\nComputes the Expected Shortfall (ES), also known as Conditional Value-at-Risk (CVaR), Average Value-at-Risk (AVaR) or Expected Tail Loss (ETL). The ES is the expected return on the asset in the worst `α%` of cases, therefore quantifies the tail-risk of an asset. It is calculated by averaging all of the returns in the distribution that are worse than the VaR of the portfolio at a given significance level `α`. For instance, for a 5% significance level, the expected shortfall is calculated by taking the average of returns in the worst 5% of cases.\n\nExpected Shortfall puts emphasis on the tail of the loss distribution, whereas Value-at-risk neglects this aspect.\n\n\n# Arguments\n- `returns`:        Vector of asset returns.\n- `α`:              Significance level, e.g. use `0.05` for 95% confidence, or `0.01` for 99% confidence.\n- `method`:         Distribution estimation method: `:historical`, `:gaussian` or `:cornish_fisher`.\n- `multiplier`:     Optional scalar multiplier, i.e. use `12` to annualize monthly returns, and use `252` to annualize daily returns.\n\n# Methods\n- `:historical`:        Historical based on empirical distribution of returns.\n- `:gaussian`:          Gaussian distribution based on parametric fit (mean, variance).\n- `:cornish_fisher`:    Cornish-Fisher based on Gaussian parametric distribution fit adjusted for third and fourth moments (skewness, kurtosis). Cornish-Fisher expansion aims to approximate the quantile of a true distribution by using higher moments (skewness and kurtosis) of that distribution to adjust for its non-normality. See https://thema.u-cergy.fr/IMG/pdf/2017-21.pdf for details.\n\n# Sources\n- Amédée-Manesme, Charles-Olivier and Barthélémy, Fabrice and Maillard, Didier (2017). Computation of the Corrected Cornish–Fisher Expansion using the Response Surface Methodology: Application to VaR and CVaR. THEMA Working Paper n°2017-21, Université de Cergy-Pontoise, France.\n\"\"\"\nfunction expected_shortfall(returns, α, method::Symbol; multiplier=1.0)\n    if method == :historical\n        # average return below significance level (quantile)\n        sorted = sort(returns)\n        idx = floor(Int64, length(sorted) * α)\n        return mean(sorted[1:idx]) * sqrt(multiplier)\n    elseif method == :gaussian\n        # derivation: http://blog.smaga.ch/expected-shortfall-closed-form-for-normal-distribution/\n        q = quantile(Normal(), α)\n        μ = mean(returns)\n        σ = std(returns; corrected=false)\n        return (μ - σ*pdf(Normal(), q)/α) * sqrt(multiplier)\n    elseif method == :cornish_fisher\n        # third/fourth moment adjusted Gaussian distribution fit\n        # https://papers.ssrn.com/sol3/papers.cfm?abstract_id=1024151\n        q = quantile(Normal(), α)\n        S = skewness(returns)\n        K = kurtosis(returns; method=:excess)\n        g = q + 1/6*(q^2-1)S + 1/24*(q^3-3q)*K - 1/36*(2q^3-5q)*S^2\n        ϕ = pdf(Normal(), g)\n        EG2 = -1/α*ϕ * (1 + 1/6*(g^3)*S + 1/72*(g^6 - 9g^4 + 9g^2 + 3)*S^2 + 1/24*(g^4 - 2g^2 - 1)*K)\n        μ = mean(returns)\n        σ = std(returns; corrected=false)\n        return (μ + σ*EG2) * sqrt(multiplier)\n    end\n\n    throw(ArgumentError(\"Passed method parameter '$(method)' is invalid, must be one of :historical, :gaussian, :cornish_fisher.\"))\nend\n", "meta": {"hexsha": "2186af1cc14a347779febe79b63c2ec3f6fdc550", "size": 3329, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/expected_shortfall.jl", "max_stars_repo_name": "rbeeli/RiskPerf.jl", "max_stars_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-07T19:19:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T19:19:09.000Z", "max_issues_repo_path": "src/expected_shortfall.jl", "max_issues_repo_name": "rbeeli/RiskPerf.jl", "max_issues_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/expected_shortfall.jl", "max_forks_repo_name": "rbeeli/RiskPerf.jl", "max_forks_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.2745098039, "max_line_length": 550, "alphanum_fraction": 0.6933012917, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067252, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.798828289773166}}
{"text": "function project(vec1::Array{Float64}, vec2::Array{Float64})::Array{Float64}\n    return (dot(vec1,vec2)/dot(vec2,vec2)) * vec2\nend\n\nfunction unitvec(vec::Array{Float64})::Array{Float64}\n    return (1/norm(vec)) * vec\nend\n\nfunction gram_schmidt(vecs...)\n    u = [unitvec(vecs[1])]\n\n    for i in vecs[2:end]\n        new_u = i\n        for j in u\n            p = project(j, i)\n            new_u -= p\n        end\n        push!(u, unitvec(new_u))\n    end\n\n    return u\nend\n", "meta": {"hexsha": "70d180104c6747e6e99791097a940e3a1c6f650b", "size": 467, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "gram_schmidt.jl", "max_stars_repo_name": "emsal1863/linalg_functions", "max_stars_repo_head_hexsha": "876e3f174814466416c693a2082b03ae7792d0af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gram_schmidt.jl", "max_issues_repo_name": "emsal1863/linalg_functions", "max_issues_repo_head_hexsha": "876e3f174814466416c693a2082b03ae7792d0af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gram_schmidt.jl", "max_forks_repo_name": "emsal1863/linalg_functions", "max_forks_repo_head_hexsha": "876e3f174814466416c693a2082b03ae7792d0af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3043478261, "max_line_length": 76, "alphanum_fraction": 0.5760171306, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172688214137, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7988228996622094}}
{"text": "module DH32StatsHelpers\n\n# package code goes here\nexport cMDS,\nCohen_d,\nDataFrame_to_distmat,\nzscore_log10_cols\n\n#cMDS_of_DataFrame,\n#kmeans_of_cMDS,\n\nusing DataFrames\nusing Distances\nusing Distributions\nusing MultivariateStats\nusing Clustering\n\nusing Distributions\nusing DataFrames\n\n\"\"\"\nCompute effect size measure Cohen's d\n\nInput:\n  - float array x1\n  - float array x2\n  - confidence level (default 0.95)\n\nOutput:\n  - DataFrame with 1 row and 3 columns:\n  d, lower_ci, upper_ci\n\"\"\"\nfunction Cohen_d(x1::Array{Float64,1}, x2::Array{Float64,1}, conf_level::Float64=0.95)\n    \n    n1 = length(x1)\n    n2 = length(x2)\n    dof = n1 + n2 - 2.\n    d = (mean(x1) - mean(x2))/sqrt((((n1-1.)*var(x1)+(n2-1.)*var(x2))/(n1+n2-2.)))\n    S_d = sqrt(((n1 + n2)/(n1 * n2) + 0.5 * d^2/dof) * ((n1 + n2)/dof))\n    Z = -quantile(TDist(dof), (1.0-conf_level)/2.0)\n    lower_ci = d - Z * S_d\n    upper_ci = d + Z * S_d\n    \n    return DataFrame(d=d, lower_ci=lower_ci, upper_ci=upper_ci)\nend\n\n\n\"\"\"\nModify columns of a data frame of count data or other positive data by:\n\n- Replacing 0 by 1 (to avoid NA after log)\n- log10-transformation\n- z-scores of log10-transformed\n\nOutput: transformed data frame\n\"\"\"\nfunction zscore_log10_cols(df::DataFrame)\n\n    df_new = copy(df)\n\n    for i in 1:length(df)\n        \n        #replace all zeros by 1 to avoid log(0)\n        df_new[df_new[:,i] .== 0,i] = 1\n\n        #take the log10 of all columns\n        df_new[:,i] = map(log10,df[:,i])\n        \n        #take z-scores \n        df_new[:,i] = zscore(convert(Array{Float64},df_new[:,i]))\n    end\n    \n    return df_new\nend\n\n\n\"\"\"\nTranslates a data frame into a distance matrix.\n\nInput:\n\n   - data frame\n\n   - distance (from Distances.jl), e.g. HellingerDist()\n\n   - row_instances: true or false. Are rows of data frame the instances for which distances should be evaluated (true), or the columns (false)\n\nOutput: distance matrix (symmetric matrix with zero diagonal)\n       \n\"\"\"\nfunction DataFrame_to_distmat(df::DataFrame, dist::Any, row_instances::Bool=true)\n\n    x = convert(Array, df)\n\n    if (row_instances == true)\n        return pairwise(dist, x')\n    end\n\n    return pairwise(dist, x)\n    \nend\n\n\"\"\"\nCarry out a classical multi-dimensional scaling (cMDS).\n\nInput:\n\n    - distances (symmetric matrix)\n\n    - dimension of cMDS output (default: 2)\n\n    - should eigenvalues be computed? (true or false)\n\nOutput:\n\n    - cMDS array with instances as columns\n\n    - if eigenvalues == true: also 1-dim array of eigenvalues\n        \n\"\"\"\nfunction cMDS(d::Array{Float64,2}, dim::Int64=2, eigenvalues::Bool=true)\n\n    #do classical MDS:\n    cMDS = classical_mds(d, dim)\n\n    if eigenvalues == true\n        #compute eigenvalues\n        G = dmat2gram(d)\n        E = eigfact!(Symmetric(G))\n        #return cMDS array and eigenvalue vector descending from largest\n        return cMDS, sort(E.values[:,1],rev=true)\n    end\n    \n    return cMDS\n\nend\n\nend # module\n", "meta": {"hexsha": "192fa52bfc7d3f22d1d08245a4c7a0c9adf3fa77", "size": 2921, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DH32StatsHelpers.jl", "max_stars_repo_name": "DanielHoffmann32/DH32StatsHelpers.jl", "max_stars_repo_head_hexsha": "16117ad43ecda2b3dffbd4d9e9510001f99effe5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DH32StatsHelpers.jl", "max_issues_repo_name": "DanielHoffmann32/DH32StatsHelpers.jl", "max_issues_repo_head_hexsha": "16117ad43ecda2b3dffbd4d9e9510001f99effe5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DH32StatsHelpers.jl", "max_forks_repo_name": "DanielHoffmann32/DH32StatsHelpers.jl", "max_forks_repo_head_hexsha": "16117ad43ecda2b3dffbd4d9e9510001f99effe5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0143884892, "max_line_length": 142, "alphanum_fraction": 0.6511468675, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7988228867170852}}
{"text": "function wave_equation(m,M,y)\n\n# evaluates the discrete matrix equation for the waves\n#\n# a1 b'' + a2 b' + (a3 + a4 lambda + a5 I lambda^2)b = 0\n#\n# where a1-a2 are tridiagonal matrices resulting from derivatives\n# and a3-a5 are diagonal matrices. The eigenvalue is lambda = C\n# (see eq. 37) B&M 2019. We recover the value of frequency from\n# the definition of C\n#\n# input\n#  m -  angular order of wave\n#  C -  Coriolis parameter  (dimensionless)\n#  M -  magnetic parameter  (dimensionless)\n#  y -  meridional coordinate\n#\n# output\n# A0,A1,A2 - matrices used in nonlinear eigenvalue problem\n#\n# Form of eigenvalue problem\n# (A0 + A1 lambda + A2 lambda^2 ) b = 0\n#\n\n# size of matrix system\nn = length(y);\n\n# matrices defining first and second derivatives\nd1,d2 = derivatives(y);\n\n# assemble matrix a1 (second derivative)\ny2 = y.*y;\ny2c = -(y2.-1);\na1 = Diagonal(y2c) * d2;\n\n# assemble matrix a2   (first derivative)\na2 = -2*Diagonal(y) * d1;\n\n# assemble matrix a3   (constant term)\ny2c_inv = 1.0./y2c;\na3 = -m^2*Diagonal(y2c_inv);\n\n# now combine into A0, A1 and A2\nA0 = convert(Array{Complex{Float64},2},a1+a2+a3);\nA1 = convert(Array{Complex{Float64},2},m*Diagonal(ones(n))/M);\nA2 = convert(Array{Complex{Float64},2},Diagonal(y2)/M);\n\n\nreturn A0,A1,A2\n\nend\n", "meta": {"hexsha": "24a28db86274addd7299d4e44c7f0a7a2730d8bb", "size": 1256, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "wave_equation.jl", "max_stars_repo_name": "bbuffett/MagRossby", "max_stars_repo_head_hexsha": "3f18059656a425d2d951a096d97bc3e709b12043", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wave_equation.jl", "max_issues_repo_name": "bbuffett/MagRossby", "max_issues_repo_head_hexsha": "3f18059656a425d2d951a096d97bc3e709b12043", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wave_equation.jl", "max_forks_repo_name": "bbuffett/MagRossby", "max_forks_repo_head_hexsha": "3f18059656a425d2d951a096d97bc3e709b12043", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1538461538, "max_line_length": 65, "alphanum_fraction": 0.6886942675, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639694252315, "lm_q2_score": 0.8221891305219503, "lm_q1q2_score": 0.7988093352681858}}
{"text": "\"\"\"\n```jldoctest\njulia> floor(ArithematicAnalysis.bisection(x->x^4-4x^3+x+4,0,3);digits=2)\n1.23\n```\n\"\"\"\nfunction bisection(custom_func,starting::Real,ending::Real)\n    if custom_func(starting)==0\n        return starting\n    elseif custom_func(ending)==0\n        return ending\n    elseif  !_root_finder(starting,ending,custom_func)\n        print(\"Cannot find roots between a and b\")\n        return Nothing\n    else\n        mid_point = _get_mid_point(starting,ending)\n        while !_root_evaluate(mid_point,custom_func)\n            if _root_finder(starting,mid_point,custom_func)\n                ending = mid_point\n            elseif _root_finder(mid_point,ending,custom_func)\n                starting = mid_point\n            end\n            mid_point = _get_mid_point(starting,ending)\n        end\n        return mid_point\n    end\nend\n\nfunction _get_mid_point(x::Real, y::Real)\n    return x+(y-x)/2\nend\n\nfunction _root_evaluate(x::Real,func)\n    value = func(x)\n    abs_value = abs(value)\n    return abs_value<10^-7\nend\n\nfunction _root_finder(x::Real, y::Real,func)\n    x,y = func(x), func(y)\n    return x * y < 0\nend\n\n# Should be Monotonic Function\nfunction custom_func(x::Real)\n    return x^4-4x^3+x+4\nend\n", "meta": {"hexsha": "bca9c203697365f1b7fb4a2b1ab6f399b801be68", "size": 1207, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ArithematicAnalysis/Bisection.jl", "max_stars_repo_name": "Enforcer007/Algorithms-Julia", "max_stars_repo_head_hexsha": "19b3560f01f6376686c3066754e2b1ce4cf06cbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ArithematicAnalysis/Bisection.jl", "max_issues_repo_name": "Enforcer007/Algorithms-Julia", "max_issues_repo_head_hexsha": "19b3560f01f6376686c3066754e2b1ce4cf06cbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ArithematicAnalysis/Bisection.jl", "max_forks_repo_name": "Enforcer007/Algorithms-Julia", "max_forks_repo_head_hexsha": "19b3560f01f6376686c3066754e2b1ce4cf06cbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1458333333, "max_line_length": 73, "alphanum_fraction": 0.6512013256, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7987730597261496}}
{"text": "function prob(q)\n    p = zeros(Float64, 21, 50)\n\n    p[1, 50] = 50/q\n    p[2, 50] = 1 - 50/q\n\n    for k in 49:-1:1\n        for n in 0:min(51-k, 20)\n            if n == 0\n                p[n+1, k] = (k/q) * p[n+1, k+1]\n            elseif n + k == 51\n                p[n+1, k] = (1 - k/q) * p[n, k+1]\n            else\n                p[n+1, k] = (k/q) * p[n+1, k+1] + (1 - k/q) * p[n, k+1]\n            end\n        end\n    end\n    \n    return p[21, 1]\nend\n\nfunction main()\n    l = 50\n    h = 55\n    e = 10^-12\n\n    while h - l > e\n        p = prob((h + l)/2)\n        if p > 0.02\n            l = (h + l)/2\n        else\n            h = (h + l)/2\n        end\n    end\n\n    println(round((h + l)/2, digits=10))\nend\n\nmain()\n", "meta": {"hexsha": "e291013a05cc8da2aedce8d23f8e8665d68dae01", "size": 715, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/problem_286.jl", "max_stars_repo_name": "HarrisonGreen/Project-Euler-Solutions", "max_stars_repo_head_hexsha": "e2599e406c8a1c997bf620e1c35045303b12091e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Julia/problem_286.jl", "max_issues_repo_name": "HarrisonGreen/Project-Euler-Solutions", "max_issues_repo_head_hexsha": "e2599e406c8a1c997bf620e1c35045303b12091e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/problem_286.jl", "max_forks_repo_name": "HarrisonGreen/Project-Euler-Solutions", "max_forks_repo_head_hexsha": "e2599e406c8a1c997bf620e1c35045303b12091e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.875, "max_line_length": 71, "alphanum_fraction": 0.3398601399, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7987730577422713}}
{"text": "#----------------------------#\n# see page 57 in Sarkka book #\n#----------------------------#\n\nfunction simulatedata(N = 1_000; seed = 1)\n\n    rg = MersenneTwister(seed)\n\n    A, H = 0.5*randn(rg, 2, 2),   0.5*randn(rg, 2, 2)\n    Q, R = 0.005*Matrix(I, 2, 2), 0.05*Matrix(I, 2, 2)\n    m₀   = 0.5*randn(rg, 2)\n    P₀   = 0.05*Matrix(I, 2, 2)\n\n    yclean = Array{Vector{Float64}, 1}(undef, N)\n    y = Array{Vector{Float64}, 1}(undef, N)\n    x = Array{Vector{Float64}, 1}(undef, N)\n\n    x[1] = rand(rg, MvNormal(m₀, P₀))\n    yclean[1] = H*x[1]\n    y[1] = rand(rg, MvNormal(H * x[1], R))\n\n    for k in 2:N\n\n        # prediction step\n\n        x[k] = rand(rg, MvNormal(A * x[k-1], Q))\n\n        yclean[k] = H * x[k]\n\n        y[k] = rand(rg, MvNormal(H * x[k], R))\n\n    end\n\n    return yclean, y, x, A, H, Q, R, m₀, P₀\n\nend\n", "meta": {"hexsha": "4d601d13f0e7ae01dac5b06fe6f59b2dd35f42fb", "size": 814, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simulatedata.jl", "max_stars_repo_name": "ngiann/StateSpaceStudy.jl", "max_stars_repo_head_hexsha": "249206cca241b672dbe44d0b24fdafe7d6624001", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulatedata.jl", "max_issues_repo_name": "ngiann/StateSpaceStudy.jl", "max_issues_repo_head_hexsha": "249206cca241b672dbe44d0b24fdafe7d6624001", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulatedata.jl", "max_forks_repo_name": "ngiann/StateSpaceStudy.jl", "max_forks_repo_head_hexsha": "249206cca241b672dbe44d0b24fdafe7d6624001", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0, "max_line_length": 54, "alphanum_fraction": 0.4717444717, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768635777511, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.79871928089241}}
{"text": "#===============================================================================\n\nA bag contains one red disc and one blue disc. In a game of chance a player\ntakes a disc at random and its colour is noted. After each turn the disc is\nreturned to the bag, an extra red disc is added, and another disc is taken at\nrandom.\n\nThe player pays £1 to play and wins if they have taken more blue discs than red\ndiscs at the end of the game.\n\nIf the game is played for four turns, the probability of a player winning is\nexactly 11/120, and so the maximum prize fund the banker should allocate for\nwinning in this game would be £10 before they would expect to incur a loss. Note\nthat any payout will be a whole number of pounds and also includes the original\n£1 paid to play the game, so in the example given the player actually wins £9.\n\nFind the maximum prize fund that should be allocated to a single game in which\nfifteen turns are played.\n\n===============================================================================#\n\nusing Memoize\nusing Base.Test\n\n#=------------------------------------------------------------------------------\nLet p(b, n) the probability to take b blue disks in n attempts, and pb(n) the\nprobability to take a blue disk at the nth attempt.\n\nIt comes:\n    p(b, n) = | pb(n) p(b-1, n-1) + (1-pb(n)) p(b, n-1) if b≤n\n              | 0 if b>n\n\n    pb(n) = 1 / (1+n)\n\nIn addition p(1, 1) = pb(1) p(0,0) + (1-pb(1)) p(0, -1)\n                    = 1/2 p(0, 0)\n                    = 1/2\n            => p(0, 0) = 1\n------------------------------------------------------------------------------=#\n\n@memoize\nfunction p(b::Int, n::Int)::Rational{Int}\n    if     n<b  0\n    elseif b<0  0\n    elseif n==0 1  # In that case, b must also be equal to 0\n    else        p(b-1, n-1)//(1+n) + n*p(b, n-1)//(1+n)\n    end\nend\n\n\n#=------------------------------------------------------------------------------\nThe probability to win it then given by\n    p(n) = sum(p(b,n) for b ∈ [div(n,2)+1, n])\n------------------------------------------------------------------------------=#\n\np(n::Int)::Rational{Int} = sum([p(b,n) for b in div(n,2)+1:n])\n\n@test p(4) == 11//120\n\n#=------------------------------------------------------------------------------\nIf p(n) = N//D, then the maximal prize fund is div(D/N), i.e. floor(1//p(n))\n------------------------------------------------------------------------------=#\n\nmaxfund(n) = let p = p(n); div(p.den, p.num) end\n\n@test maxfund(4) == 10\n\n\n#=----------------------------------------------------------------------------=#\nprintln(\"Euler 121: $(maxfund(15))\")\n", "meta": {"hexsha": "b37fe0f177276d1567369ab285d4db293db299c4", "size": 2593, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0121.jl", "max_stars_repo_name": "dpieroux/euler", "max_stars_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "0121.jl", "max_issues_repo_name": "dpieroux/euler", "max_issues_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0121.jl", "max_forks_repo_name": "dpieroux/euler", "max_forks_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5211267606, "max_line_length": 80, "alphanum_fraction": 0.4558426533, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813513911654, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7987066828232329}}
{"text": "# Based on the introductory discussion on\n# https://www.maa.org/press/periodicals/loci/joma/the-sir-model-for-spread-of-disease-the-differential-equation-model\n\n## Uncomment the following lines if used as a standalone\n# using DifferentialEquations\n# using Plots\n\nfunction SIR(du, u, p, t)\n    s, i, r = u\n    b, k = p\n    du[1] = -b * s * i\n    du[2] = b * s * i - k * i\n    du[3] = k * i\nend\n\n# TODO: make the following a doctest example\n    # #initian conditions\n    # p = [0.5/7900000.0,0.33]\n    # u0 = [7900000.0,10.0,0.0]\n    # tspan = (0.0,140.0)\n\n    # #solve\n    # sir = ODEProblem(SIR,u0,tspan,p)\n    # sol = solve(sir)\n\n    # #plot\n    # plot(sol)\n", "meta": {"hexsha": "c0e4456926f871c70de5646bbcede54b5bb97632", "size": 659, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/sir_model.jl", "max_stars_repo_name": "ashwani-rathee/Julia", "max_stars_repo_head_hexsha": "f02c1b07bb491a27e02599888a545db86305a97a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-08-21T04:53:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T00:19:37.000Z", "max_issues_repo_path": "src/math/sir_model.jl", "max_issues_repo_name": "ashwani-rathee/Julia", "max_issues_repo_head_hexsha": "f02c1b07bb491a27e02599888a545db86305a97a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2021-08-09T22:40:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T16:56:36.000Z", "max_forks_repo_path": "src/math/sir_model.jl", "max_forks_repo_name": "ashwani-rathee/Julia", "max_forks_repo_head_hexsha": "f02c1b07bb491a27e02599888a545db86305a97a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-31T00:47:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T00:47:35.000Z", "avg_line_length": 23.5357142857, "max_line_length": 117, "alphanum_fraction": 0.6039453718, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813488829418, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7987066826856719}}
{"text": "function exponential_fg!(∇f, x)\n\n    if !(∇f==nothing)\n        ∇f[1] = -2.0 * (2.0 - x[1]) * exp((2.0 - x[1])^2)\n        ∇f[2] = -2.0 * (3.0 - x[2]) * exp((3.0 - x[2])^2)\n    end\n\n    fx = exp((2.0 - x[1])^2) + exp((3.0 - x[2])^2)\n\n    return fx\nend\n\n\nfunction exponential_hessian!(storage, x)\n    storage[1, 1] = 2.0 * exp((2.0 - x[1])^2) * (2.0 * x[1]^2 - 8.0 * x[1] + 9)\n    storage[1, 2] = 0.0\n    storage[2, 1] = 0.0\n    storage[2, 2] = 2.0 * exp((3.0 - x[2])^2) * (2.0 * x[2]^2 - 12.0 * x[2] + 19)\nend\n\ntp_fletch_powell_fg! = TestProblem(exponential_fg!, [0.0, 0.0], I, NearlyNewton.OptOptions())\ntp_fletch_powell_fg!_alt = TestProblem(exponential_fg!, [0.0, 0.0], I, NearlyNewton.OptOptions())\n", "meta": {"hexsha": "69e9fd13a22daf7686db311c3b462b36333f1768", "size": 701, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testproblems/exponential.jl", "max_stars_repo_name": "pkofod/NearlyNewton.jl", "max_stars_repo_head_hexsha": "f9f0f80f3b5e89dc3c56af838e338c9d77d8356a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/testproblems/exponential.jl", "max_issues_repo_name": "pkofod/NearlyNewton.jl", "max_issues_repo_head_hexsha": "f9f0f80f3b5e89dc3c56af838e338c9d77d8356a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/testproblems/exponential.jl", "max_forks_repo_name": "pkofod/NearlyNewton.jl", "max_forks_repo_head_hexsha": "f9f0f80f3b5e89dc3c56af838e338c9d77d8356a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4782608696, "max_line_length": 97, "alphanum_fraction": 0.5192582026, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813513911654, "lm_q2_score": 0.8354835371034369, "lm_q1q2_score": 0.7987066808652145}}
{"text": "\"\"\"\n    laplacian(n::Int, h::Real)\n    laplacian(x::AbstractRange{T}) where {T}\n\nReturns ``n \\\\times n`` differentiation matrix ``\\\\mathrm{D^{(2)}}`` using sinc interpolants. \nSee Weideman, J.A., and Reddy, S.C. (2000). A MATLAB differentiation matrix suite. \nACM Transactions on Mathematical Software (TOMS), 26(4), 465-519.\nEquation (20) on page 485.\n\nOn input: `n` - size of a uniform grid with step size `h`, or `x` - `AbstractRange` object.\n\n# Example\nSecond derivative of the gaussian function\n```math \n    \\\\partial^2 \\\\exp(-x^2)/\\\\partial x^2 = 2(2x^2 - 1)\\\\exp(-x^2)\n```\n```jldoctest\njulia> x = -6:0.01:6\n-6.0:0.01:6.0\n\njulia> d²f_exact = 2(2x.^2 .- 1).*exp.(-x.^2);\n\njulia> d²f_approx = laplacian(length(x), step(x)) * exp.(-x.^2);\n\njulia> isapprox(d²f_exact, d²f_approx, atol = 1e-10)\ntrue\n```\n\"\"\"\nfunction laplacian(n, h)\n  Δ = zeros(n, n)\n  Δ[diagind(Δ, 0)] .= -1/3*π^2 / h^2\n  for i=2:n\n    @inbounds Δ[diagind(Δ, i-1)] = \n      Δ[diagind(Δ, 1-i)] .= 2*(-1)^i / (i-1)^2 / h^2\n  end\n  return Δ\nend\nlaplacian(x::AbstractRange) = laplacian(length(x), step(x))\n\nfunction FGH(x::AbstractRange)\n  N, Δx = length(x), step(x)\n  iseven(N) && throw(DomainError(N, \"number of grid points must be odd\"))\n  K = zeros(N, N)\n  for d=0:N-1\n    # See Eq. 26 // C. Clay Marston et al. The Fourier grid Hamiltonian method \n    # for bound state eigenvalues and eigenfunctions. JCP 91, 3571 (1989)\n    # d ≝ i - j\n    K[diagind(K, d)] = K[diagind(K, -d)] .= \n    -2/N*(2π/N)^2 / Δx^2 * sum(l -> cos(2π*l*d/N)*l^2, 1:(N >> 1))\n  end\n  return K\nend\n\nfunction sincdiff(x::AbstractRange)\n  n, dx = length(x), step(x)\n  ∇ = zeros(n, n)\n  ∇[diagind(∇, 0)] .= 0\n  for i = 2:n\n      @inbounds ∇[diagind(∇, i - 1)] .= (-1)^i / (i - 1) / dx\n      @inbounds ∇[diagind(∇, 1 - i)] .= (-1)^(i - 1) / (i - 1) / dx\n  end\n  return ∇\nend\n\nfunction ∂r(f, x, r = exp.(x), D = sincdiff(x) - I, rₘᵢₙ = 5e-5)\n  df = D * (f .* r)\n  @. df /= r^2\n  extrapolate_left!(df, r, rₘᵢₙ)\n  return df\nend\n\n#=\n ρ = similar(r)\n∇ρ = similar(r)\n\n@. ρ = (2/27*r^2 - 2/3*r + 1)^2 * exp(-2/3*r) / 27π\n@. ∇ρ = -(8*r^4 - 192*r^3 + 1512*r^2 - 4536r + 4374)*exp(-2/3*r) / 59049π\n\nnorm(∂r(ρ, x) .- ∇ρ)\n=#\n", "meta": {"hexsha": "a3598f433797f5acacb9fb8fad1e841547b24f35", "size": 2152, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sincdif.jl", "max_stars_repo_name": "malykhin-sergei/AtomEnergyLevels.jl", "max_stars_repo_head_hexsha": "1476496969dee5fe38c32546b2aa35673bd8cc7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sincdif.jl", "max_issues_repo_name": "malykhin-sergei/AtomEnergyLevels.jl", "max_issues_repo_head_hexsha": "1476496969dee5fe38c32546b2aa35673bd8cc7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sincdif.jl", "max_forks_repo_name": "malykhin-sergei/AtomEnergyLevels.jl", "max_forks_repo_head_hexsha": "1476496969dee5fe38c32546b2aa35673bd8cc7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-26T17:45:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-26T17:45:38.000Z", "avg_line_length": 26.5679012346, "max_line_length": 94, "alphanum_fraction": 0.5683085502, "num_tokens": 941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627598, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7987064306337344}}
{"text": "using JuMP\nusing Clp\nusing LinearAlgebra\nusing Plots\n\nn = 100\ngrid = range(-1, 1, length=n)\nf = ℯ.^grid\ncoeff = zeros(n, 5)\nfor degree in 0:4\n    coeff[:, degree + 1] = grid .^ degree\nend\nerrors = zeros(5)\npolynomials = zeros(5, 5)\ntaylors = [1 0 0 0 0; 1 1 0 0 0; 1 1 1/2 0 0; 1 1 1/2 1/6 0; 1 1 1/2 1/6 1/24]\n\nfor d in 0:4\n\n    model = Model(Clp.Optimizer)\n\n    @variables(model, begin\n        m >= 0\n        a[1:5]\n    end\n    )\n\n    @objective(model, Min, m)\n\n    @constraints(model, begin\n        [i=d+2:5], a[i] == 0\n        m .>= f - coeff * a\n        m .>= coeff * a - f\n    end\n    )\n\n    optimize!(model)\n    errors[d + 1] = objective_value(model)\n    polynomials[d + 1, :] = value.(a)\nend\n\nplot(grid, f, label=\"e^x\")\nfor d in 0:4\n    plot!(grid, coeff * (polynomials[d + 1, :]), label=\"cheb $d\")\nend\nsavefig(\"polynomial.png\")\n\nplot(0:4, errors)\nsavefig(\"error.png\")\n\nfor d in 0:4\n    plot(grid, f, label=\"e^x\")\n    plot!(grid, coeff * polynomials[d + 1, :], label=\"cheb $d\")\n    plot!(grid, coeff * taylors[d + 1, :], label=\"tayl $d\")\n    savefig(\"compare-$d.png\")\nend\n", "meta": {"hexsha": "ca26a2435f2cabb7469ac26950aeb5d02d24b6fa", "size": 1080, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2/4.jl", "max_stars_repo_name": "tansongchen/learn-optimization", "max_stars_repo_head_hexsha": "b44e902c857287ff05da449b9a639dfe534af8ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2/4.jl", "max_issues_repo_name": "tansongchen/learn-optimization", "max_issues_repo_head_hexsha": "b44e902c857287ff05da449b9a639dfe534af8ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2/4.jl", "max_forks_repo_name": "tansongchen/learn-optimization", "max_forks_repo_head_hexsha": "b44e902c857287ff05da449b9a639dfe534af8ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2857142857, "max_line_length": 78, "alphanum_fraction": 0.5555555556, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422158380862, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7987064286337123}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction _lsf_rotate{T<:AbstractFloat}(Δ::T, vsini::T, ɛ::T)\n    n_2 = floor(ceil(2*vsini/Δ)/2)\n    vel = collect(-n_2:n_2)*Δ\n    e1 = 2*(1.0 - ɛ)\n    e2 = pi*ɛ/2.0\n    e3 = pi*(1.0 - ɛ/3.0)\n    x = vel/vsini\n    x1 = abs(1.0 - x.^2)\n    return vel, (e1*sqrt(x1) + e2*x1)/e3\nend\n\n\"\"\"\n    lsf_rotate(delta_v, v_sin_i[, epsilon = 0.3]) -> velocity_grid, lsf\n\n### Purpose ###\n\nCreate a 1-d convolution kernel to broaden a spectrum from a rotating star.\n\n### Explanation ###\n\nCan be used to derive the broadening effect (LSF, line spread function) due to\nrotation on a synthetic stellar spectrum.  Assumes constant limb darkening\nacross the disk.\n\n### Arguments ###\n\n* `delta_v`: numeric scalar giving the step increment (in km/s) in the output\n  rotation kernel\n* `v_sin_i`: the rotational velocity projected along the line of sight (km/s)\n* `epsilon` (optional numeric argument): numeric scalar giving the\n  limb-darkening coefficient, default = 0.6 which is typical for photospheric\n  lines.  The specific intensity \\$I\\$ at any angle \\$\\\\theta\\$ from the\n  specific intensity \\$I_{\\\\text{cen}}\\$ at the center of the disk is given by:\n\n\\$\\$ I = I_{\\\\text{cen}}\\\\cdot(1 - \\\\varepsilon\\\\cdot(1 - \\\\cos(\\\\theta))) \\$\\$\n\n### Output ###\n\nThe 2-tuple (`velocity_grid`, `lsf`):\n\n* `velocity_grid`: vector of velocity grid with the same number of elements as\n  `lsf` (see below)\n* `lsf`: the convolution kernel vector for the specified rotational velocity.\n  The number of points in `lsf` will be always be odd (the kernel is symmetric)\n  and equal to either `ceil(2*v_sin_i/delta_v)` or `ceil(2*v_sin_i/delta_v) + 1`,\n  whichever number is odd.  Elements of `lsf` will always be of type\n  `AbstractFloat`.  To actually compute the broadening, the spectrum should be\n  convolved with the rotational `lsf`\n\n### Example ###\n\nPlot the line spread function for a star rotating at 90 km/s in velocity space\nevery 3 km/s.  Use [PyPlot.jl](https://github.com/stevengj/PyPlot.jl) for\nplotting.\n\n``` julia\nusing PyPlot\nplot(lsf_rotate(3, 90)...)\n```\n\n### Notes ###\n\nCode of this function is based on IDL Astronomy User's Library.\n\"\"\"\nlsf_rotate(Δ::Real, v::Real, ɛ::Real=0.6) =\n    _lsf_rotate(promote(float(Δ), float(v), float(ɛ))...)\n", "meta": {"hexsha": "c2054a46df0ac5363ec3df2ce5515603ab522c4e", "size": 2318, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lsf_rotate.jl", "max_stars_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_stars_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lsf_rotate.jl", "max_issues_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_issues_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lsf_rotate.jl", "max_forks_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_forks_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1142857143, "max_line_length": 81, "alphanum_fraction": 0.6833477135, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7987064279818494}}
{"text": "\"\"\"\nImputes gradients based on a vector of x and y coordinates.\n### Takes\n * x - A Float64 vector of x coordinates\n * y - A Float64 vector of y coordinates\n\n### Returns\n * A Float64 vector of gradients for each input point\n\"\"\"\nfunction imputeGradients(x,y)\n     n = length(x)\n     # Judd (1998), page 233, second last equation\n     L = sqrt( (x[2:n]-x[1:(n-1)]).^2 + (y[2:n]-y[1:(n-1)]).^2)\n     # Judd (1998), page 233, last equation\n     d = (y[2:n]-y[1:(n-1)])./(x[2:n]-x[1:(n-1)])\n     # Judd (1998), page 234, Eqn 6.11.6\n     Conditionsi = d[1:(n-2)].*d[2:(n-1)] .> 0\n     MiddleSiwithoutApplyingCondition = (L[1:(n-2)].*d[1:(n-2)]+L[2:(n-1)].* d[2:(n-1)]) ./ (L[1:(n-2)]+L[2:(n-1)])\n     sb = Conditionsi .* MiddleSiwithoutApplyingCondition\n     # Judd (1998), page 234, Second Equation line plus 6.11.6 gives this array of slopes.\n     ff = [((-sb[1]+3*d[1])/2);  sb ;  ((3*d[n-1]-sb[n-2])/2)]\n     return ff\n end\n\n \"\"\"\n Creates a spline defined by interval starts IntStarts and quadratic coefficients SpCoefs which evaluates an input point.\n### Takes\n  * IntStarts - A Float64 vector that gives the starting points of intervals (in the x plane)\n  * SpCoefs - A 3 column matrix with the same number of rows as the length of the IntStarts vector. The first column is the coefficient of the quadratic term, the second column for the linear term. The third column is the constant.\n\n### Returns\n  * A spline function that takes a single Float64 input and returns the spline value at that point.\n \"\"\"\nfunction ppmak(IntStarts,SpCoefs)\n  function sp(PointToExamine)\n    IntervalNum = searchsortedlast(IntStarts, PointToExamine)\n    IntervalNum = max(IntervalNum, 1)\n    xmt = PointToExamine - IntStarts[IntervalNum]\n    Coefs = SpCoefs[ IntervalNum , :]\n    return reshape(Coefs' * [xmt^2 xmt 1]', 1)[1]\n  end\n  function Vsp(PointToExamine)\n    return map(x -> sp(x), PointToExamine)\n  end\n  return Vsp\nend\n\n\n \"\"\"\n Creates the derivative function of the spline defined by interval starts IntStarts and quadratic coefficients SpCoefs which evaluates an input point.\n### Takes\n  * IntStarts - A Float64 vector that gives the starting points of intervals (in the x plane)\n  * SpCoefs - A 3 column matrix with the same number of rows as the length of the IntStarts vector. The first column is the coefficient of the quadratic term, the second column for the linear term. The third column is the constant.\n\n### Returns\n * The derivative function that takes a single Float64 input and returns the derivative at that point.\n \"\"\"\nfunction ppmakDeriv(IntStarts,SpCoefs)\n  function sp(PointToExamine)\n    IntervalNum = searchsortedlast(IntStarts, PointToExamine)\n    IntervalNum = max(IntervalNum, 1)\n    xmt = PointToExamine - IntStarts[IntervalNum]\n    Coefs = SpCoefs[ IntervalNum , :]\n    return reshape(Coefs' * [2*xmt 1 0]', 1)[1]\n  end\n  function Vsp(PointToExamine)\n    return map(x -> sp(x), PointToExamine)\n  end\n  return Vsp\nend\n\n\"\"\"\nCreates the second derivative function of the spline defined by interval starts IntStarts and quadratic coefficients SpCoefs which evaluates an input point.\n### Takes\n * IntStarts - A Float64 vector that gives the starting points of intervals (in the x plane)\n * SpCoefs - A 3 column matrix with the same number of rows as the length of the IntStarts vector. The first column is the coefficient of the quadratic term, the second column for the linear term. The third column is the constant.\n\n### Returns\n * The second derivative function that takes a single Float64 input and returns the second derivative at that point.\n\"\"\"\nfunction ppmak2Deriv(IntStarts,SpCoefs)\n  function sp(PointToExamine)\n    IntervalNum = searchsortedlast(IntStarts, PointToExamine)\n    IntervalNum = max(IntervalNum, 1)\n    xmt = PointToExamine - IntStarts[IntervalNum]\n    Coefs = SpCoefs[ IntervalNum , :]\n    return reshape(Coefs' * [2 0 0]', 1)[1]\n  end\n  function Vsp(PointToExamine)\n    return map(x -> sp(x), PointToExamine)\n  end\n  return Vsp\nend\n\n\"\"\"\nSplits an interval into 2 subintervals and creates the quadratic coefficients\n### Takes\n * s - A 2 entry Float64 vector with gradients at either end of the interval\n * z - A 2 entry Float64 vector with y values at either end of the interval\n * Smallt - A 2 entry Float64 vector with x values at either end of the interval\n\n### Returns\n * A 2 x 5 matrix. The first column is the x values of start of the two subintervals. The second column is the ends. The last 3 columns are quadratic coefficients in two subintervals.\n\"\"\"\nfunction schumakerIndInterval(s,z,Smallt)\n   # The SchumakerIndInterval function takes in each interval individually\n   # and returns the location of the knot as well as the quadratic coefficients in each subinterval.\n\n   # Judd (1998), page 232, Lemma 6.11.1 provides this if condition:\n   if (sum(s)*(Smallt[2]-Smallt[1]) == 2*(z[2]-z[1]))\n     tsi = Smallt[2]\n   else\n     # Judd (1998), page 233, Algorithm 6.3 along with equations 6.11.4 and 6.11.5 provide this whole section\n     delta = (z[2] -z[1])/(Smallt[2]-Smallt[1])\n     Condition = ((s[1]-delta)*(s[2]-delta) >= 0)\n     Condition2 = abs(s[2]-delta) < abs(s[1]-delta)\n     if (Condition)\n       tsi = sum(Smallt)/2\n     elseif (Condition2)\n       tsi = (Smallt[1] + (Smallt[2]-Smallt[1])*(s[2]-delta)/(s[2]-s[1]))\n     else\n       tsi = (Smallt[2] + (Smallt[2]-Smallt[1])*(s[1]-delta)/(s[2]-s[1]))\n     end\n   end\n\n   # Judd (1998), page 232, 3rd last equation of page.\n   alpha = tsi-Smallt[1]\n   beta = Smallt[2]-tsi\n   # Judd (1998), page 232, 4th last equation of page.\n   sbar = (2*(z[2]-z[1])-(alpha*s[1]+beta*s[2]))/(Smallt[2]-Smallt[1])\n   # Judd (1998), page 232, 3rd equation of page. (C1, B1, A1)\n   Coeffs1 = [ (sbar-s[1])/(2*alpha)  s[1]  z[1] ]\n   if (beta == 0)\n     Coeffs2 = Coeffs1\n   else\n     # Judd (1998), page 232, 4th equation of page. (C2, B2, A2)\n     Coeffs2 = [ (s[2]-sbar)/(2*beta)  sbar  Coeffs1 * [alpha^2, alpha, 1] ]\n   end\n   Machine4Epsilon = 4*eps()\n     if (tsi  <  Smallt[1] + Machine4Epsilon )\n         return [Smallt[1] Smallt[2] Coeffs2]\n     elseif (tsi + Machine4Epsilon > Smallt[2] )\n         return [Smallt[1] Smallt[2] Coeffs1]\n     else\n         return [Smallt[1] tsi Coeffs1 ; tsi Smallt[2] Coeffs2]\n     end\n end\n\n \"\"\"\n Calls SchumakerIndInterval many times to get full set of spline intervals and coefficients. Then calls extrapolation for out of sample behaviour\n### Takes\n * gradients - A Float64 vector of gradients at each point\n * x - A Float64 vector of x coordinates\n * y - A Float64 vector of y coordinates\n * extrapolation - A string in (\"Curve\", \"Linear\", \"Constant\") that gives behaviour outside of interpolation range.\n\n### Returns\n * A vector of interval starts\n * A vector of interval ends\n * A matrix of all coefficients\n  \"\"\"\n function getCoefficientMatrix(gradients,y,x, extrapolation)\n   n = length(x)\n   fullMatrix = schumakerIndInterval([gradients[1] gradients[2]], [y[1] y[2]], [x[1] x[2]] )\n    for intrval = 2:(n-1)\n      Smallt = [ x[intrval] , x[intrval + 1] ]\n      s = [ y[intrval], y[intrval + 1] ]\n      z = [ gradients[intrval], gradients[intrval + 1] ]\n      intMatrix = schumakerIndInterval(z,s,Smallt)\n      fullMatrix = vcat(fullMatrix,intMatrix)\n    end\n    fullMatrix = extrapolate(fullMatrix, extrapolation, x, y)\n   return fullMatrix[:,1], fullMatrix[:,2], fullMatrix[:,3:5]\n end\n\n\"\"\"\n Adds a row on top and bottom of coefficient matrix to give out of sample prediction.\n### Takes\n * fullMatrix - output from GetCoefficientMatrix first few lines\n * extrapolation - A string in (\"Curve\", \"Linear\", \"Constant\") that gives behaviour outside of interpolation range.\n * x - A Float64 vector of x coordinates\n * y - A Float64 vector of y coordinates\n\n### Returns\n  * A new version of fullMatrix with out of sample prediction built into it.\n\"\"\"\nfunction extrapolate(fullMatrix, extrapolation, x, y)\n\n  if (extrapolation == \"Curve\")\n    return fullMatrix\n  end\n\n  dim = size(fullMatrix)[1]\n\n  Botx   = fullMatrix[1,1]\n  Boty   = y[1]\n\n  if (extrapolation == \"Linear\")\n    BotB = fullMatrix[1 , 4]\n    BotC   = Boty - BotB\n  else\n    BotB = 0.0\n    BotC = Boty\n  end\n\n  BotRow = [ Botx-1, Botx, 0.0, BotB, BotC]\n\n  Topx = fullMatrix[dim,2]\n  Topy = y[length(y)]\n\n  if (extrapolation == \"Linear\")\n    TopB = fullMatrix[dim ,4]\n    TopC = Topy\n  else\n    TopB = 0.0\n    TopC = Topy\n  end\n\n  TopRow = [ Topx, Topx + 1, 0.0 ,TopB ,TopC]\n\n  fullMatrix = vcat(BotRow' , fullMatrix,  TopRow')\n\n  return fullMatrix\nend\n\n\"\"\"\nCreates splines for a given set of x and y values (and optionally gradients) and the first and second derivatives of this spline.\n### Takes\n* x - A Float64 vector of x coordinates.\n* y - A Float64 vector of y coordinates.\n* gradients (optional)- A Float64 vector of gradients at each point. If not supplied these are imputed from x and y.\n* extrapolation (optional) - This should be a string in (\"Curve\", \"Linear\", \"Constant\") specifying how to interpolate outside of the sample domain. By default it is \"curve\" which extends out the first and last quadratic curves. The other options are \"Linear\" which extends the line (from first and last curve) out from the first and last point and \"Constant\" which extends out the y value at the first and last point.\n\n### Returns\n* A spline which takes and input value and returns the spline y value.\n* The derivative of this spline.\n* The second derivative of this spline.\n \"\"\"\nfunction schumaker(x,y,gradients = \"Not-Supplied\", extrapolation = (\"Curve\", \"Linear\", \"Constant\"))\n  # This is the main function of the package that creates and returns a schumaker spline.\n  # Inputs : An x array, the corresponding y array and optionally the gradients at each point.\n  #           If gradients are not input then they are estimated.\n  # Outputs: A schumaker spline function. Its derivative and its second derivative.\n\n  if (extrapolation == (\"Curve\", \"Linear\", \"Constant\"))\n    extrapolation = \"Curve\"\n  end\n\n  if (gradients == \"Not-Supplied\")\n     gradients = imputeGradients(x,y)\n  end\n\n  IntStarts, IntEnds, SpCoefs = getCoefficientMatrix(gradients,y,x, extrapolation)\n\n  Sp      = ppmak(IntStarts,SpCoefs)\n  SpDeriv = ppmakDeriv(IntStarts,SpCoefs)\n  SpDeriv2= ppmak2Deriv(IntStarts,SpCoefs)\n  return Sp, SpDeriv, SpDeriv2\nend\n", "meta": {"hexsha": "fecfa688f84b1a6f2674dea61ac750b9c1d22e95", "size": 10219, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SchumakerFunctions.jl", "max_stars_repo_name": "JuliaPackageMirrors/SchumakerSpline.jl", "max_stars_repo_head_hexsha": "ab288903e8f0993b0f90675dc06b85f411ed5be0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SchumakerFunctions.jl", "max_issues_repo_name": "JuliaPackageMirrors/SchumakerSpline.jl", "max_issues_repo_head_hexsha": "ab288903e8f0993b0f90675dc06b85f411ed5be0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SchumakerFunctions.jl", "max_forks_repo_name": "JuliaPackageMirrors/SchumakerSpline.jl", "max_forks_repo_head_hexsha": "ab288903e8f0993b0f90675dc06b85f411ed5be0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3038461538, "max_line_length": 417, "alphanum_fraction": 0.6874449555, "num_tokens": 3076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7987043177994355}}
{"text": "\"\"\"\n    Beta\n* Parametrization\n* Score\n* Fisher Information\n* `time_varying_params` map.\n* Default link\n\"\"\"\nBeta\n\nfunction score!(score_til::Matrix{T}, y::T, ::Type{Beta}, param::Matrix{T}, t::Int) where T\n    score_til[t, 1] = log(y) + digamma(param[t, 1] + param[t, 2]) - digamma(param[t, 1])\n    score_til[t, 2] = log(1 - y) + digamma(param[t, 1] + param[t, 2]) - digamma(param[t, 2])\n    return\nend\n\nfunction fisher_information!(aux::AuxiliaryLinAlg{T}, ::Type{Beta}, param::Matrix{T}, t::Int) where T\n    minus_trigamma_a_b = -trigamma(param[t, 1] + param[t, 2])\n    aux.fisher[1, 1] = trigamma(param[t, 1]) + minus_trigamma_a_b\n    aux.fisher[2, 2] = trigamma(param[t, 2]) + minus_trigamma_a_b\n    aux.fisher[2, 1] = minus_trigamma_a_b\n    aux.fisher[1, 2] = minus_trigamma_a_b\n    return\nend\n\nfunction log_likelihood(::Type{Beta}, y::Vector{T}, param::Matrix{T}, n::Int) where T\n    loglik = 0.0\n    for t in 1:n\n        loglik += (param[t, 1] - 1)*log(y[t]) + (param[t, 2] - 1)*log(1 - y[t]) - logbeta(param[t, 1], param[t, 2])\n    end\n    return -loglik\nend\n\n# Links\nfunction link!(param_tilde::Matrix{T}, ::Type{Beta}, param::Matrix{T}, t::Int) where T \n    param_tilde[t, 1] = link(LogLink, param[t, 1], zero(T))\n    param_tilde[t, 2] = link(LogLink, param[t, 2], zero(T))\n    return\nend\nfunction unlink!(param::Matrix{T}, ::Type{Beta}, param_tilde::Matrix{T}, t::Int) where T \n    param[t, 1] = unlink(LogLink, param_tilde[t, 1], zero(T))\n    param[t, 2] = unlink(LogLink, param_tilde[t, 2], zero(T))\n    return\nend\nfunction jacobian_link!(aux::AuxiliaryLinAlg{T}, ::Type{Beta}, param::Matrix{T}, t::Int) where T \n    aux.jac[1] = jacobian_link(LogLink, param[t, 1], zero(T))\n    aux.jac[2] = jacobian_link(LogLink, param[t, 2], zero(T))\n    return\nend\n\n# utils\nfunction update_dist(::Type{Beta}, param::Matrix{T}, t::Int) where T\n    small_threshold!(param, SMALL_NUM, t)\n    return Beta(param[t, 1], param[t, 2])\nend \n\nfunction params_sdm(d::Beta)\n    return Distributions.params(d)\nend\n\nfunction num_params(::Type{Beta})\n    return 2\nend", "meta": {"hexsha": "197ad05bbbb638ffca9f5d5bea40df4c7e7bc63a", "size": 2052, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distributions/beta.jl", "max_stars_repo_name": "marinadietze/ScoreDrivenModels.jl", "max_stars_repo_head_hexsha": "4ee85b8d606892535a7b0bf2aec1d976f44d796e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2020-02-05T04:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T18:46:03.000Z", "max_issues_repo_path": "src/distributions/beta.jl", "max_issues_repo_name": "marinadietze/ScoreDrivenModels.jl", "max_issues_repo_head_hexsha": "4ee85b8d606892535a7b0bf2aec1d976f44d796e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 109, "max_issues_repo_issues_event_min_datetime": "2019-11-26T12:34:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-27T20:16:55.000Z", "max_forks_repo_path": "src/distributions/beta.jl", "max_forks_repo_name": "LAMPSPUC/GAS.jl", "max_forks_repo_head_hexsha": "e169248c3f8908170868d898a4def97af15774cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:11:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-04T20:05:21.000Z", "avg_line_length": 32.5714285714, "max_line_length": 115, "alphanum_fraction": 0.6413255361, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7987043131825475}}
{"text": "using Calculus\n\n\n################################################################################\n# Function 1\n################################################################################\nf = function(x)\n    n = length(x)\n    total = 0\n    for i in 1:n-1\n        total += (x[i+1]-x[i])^2 + (exp(x[i]) - 1)^2\n    end\n    return(total + (exp(x[n]) - 1)^2)\nend\n\ngrad_f = function(x)\n    n = length(x)\n    J = zeros(n)\n    for i in 1:n\n        if i == 1\n            J[1] = -2 * (x[2]-x[1]) + 2*(exp(2*x[1]) - exp(x[1]))\n        elseif i == n\n            J[n] = 2 * (x[n]-x[n-1]) + 2*(exp(2*x[n]) - exp(x[n]))\n        else\n            J[i] = -2 * (x[i+1]-x[i]) + 2 * (x[i]-x[i-1]) + 2*(exp(2*x[i])-exp(x[i]))\n        end\n    end\n    return(J)\nend\n\nhess_f = function(x)\n    n = length(x)\n    H = zeros(n,n)\n    for i in 1:n\n        for j in 1:n\n            if i == j\n                H[i,j] = 2 + 4*exp(2*x[i]) - 2*exp(x[i])\n                if (i != n) && (i != 1)\n                    H[i,j] += 2\n                end\n\n            elseif abs(i-j) == 1\n                H[i,j] = -2\n            else\n                H[i,j] = 0\n            end\n        end\n    end\n    return(H)\nend\n\n# test that the numerical gradients equal the analytically computed gradients\n#x = [1.;2.;3.]\n#println(sum(grad_f(x)-Calculus.gradient(f,x)))\n#println(sum(hess_f(x)-Calculus.hessian(f,x)))\n\nf_g = Calculus.gradient(f)\nf_h = Calculus.hessian(f)\n\n################################################################################\n# Rosenbrock\n################################################################################\n\nfunction rosenbrock(x)\n    \"\"\"\n    Assumes x has an even number of elemnts.\n    \"\"\"\n    n = length(x)\n    @assert n%2 == 0\n    total = 0\n    for i in 1:Integer(n/2)\n        total += (1-x[2*i-1])^2 + 10*(x[2*i] - x[2*i-1]^2)^2\n    end\n    return total\nend\n\nrosenbrock_g = Calculus.gradient(rosenbrock)\nrosenbrock_h = Calculus.hessian(rosenbrock)\n\n\n################################################################################\n# Cute functions\n################################################################################\n\nfunction cute(x)\n    n = length(x)\n    total = 0\n    for i in 1:n-4\n        total += (-4x[i]+3)^2 + (x[i]^2 + 2*x[i+1]^2 + 3*x[i+2]^2 + 4*x[i+3]^2 + 5*x[n]^2)^2\n    end\n\treturn total\nend\n\ncute_g = Calculus.gradient(cute)\ncute_h = Calculus.hessian(cute)\n\nfunction cute2(x)\n    \"\"\"\n    the cute2 function\n    \"\"\"\n    n = length(x)\n    inds = 2:n-3\n    return sum((-4*x[inds]+3.0).^2) +\n        sum((x[inds].^2 + 2*x[inds+1].^2 +\n\t\t3*x[inds+2].^2 + 4*x[inds+3].^2 + 5*x[1].^2).^2)\nend\n\ncute2_g = Calculus.gradient(cute2)\ncute2_h = Calculus.hessian(cute2)\n\n################################################################################\n# Fenton\n################################################################################\n\nfunction fenton(x)\n    \"\"\"\n    Using Newton's method, the starting point [3;2] converges but [3;4] diverges\n    \"\"\"\n    x1 = x[1]; x2 = x[2];\n    return((12 + x1*x1 + (1+x2*x2)/(x1*x1) + (x1*x1*x2*x2+100)/((x1*x2)^4)) / 10)\nend\n\nfenton_g = Calculus.gradient(fenton)\nfenton_h = Calculus.hessian(fenton)\n", "meta": {"hexsha": "51ab9e8a3f0ef5affb5610e39e6a8e5de4a32b25", "size": 3149, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "utils/functions.jl", "max_stars_repo_name": "dicai/descent.jl", "max_stars_repo_head_hexsha": "f684b69f6c8dadc86402fc465455b51c0484cedf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-08-12T22:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-25T01:37:28.000Z", "max_issues_repo_path": "utils/functions.jl", "max_issues_repo_name": "dicai/descent.jl", "max_issues_repo_head_hexsha": "f684b69f6c8dadc86402fc465455b51c0484cedf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/functions.jl", "max_forks_repo_name": "dicai/descent.jl", "max_forks_repo_head_hexsha": "f684b69f6c8dadc86402fc465455b51c0484cedf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.192, "max_line_length": 92, "alphanum_fraction": 0.3953636075, "num_tokens": 968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370312, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7987043118432969}}
{"text": "function gausslobatto(n)\n    # Gauss-Legendre-Lobatto Quadrature Nodes and Weights\n    if n == 1\n        error(\"Lobatto undefined for n = 1.\")\n    elseif n == 2\n        [-1.0, 1.0], [1.0, 1.0]\n    elseif n == 3\n        [-1.0, 0.0, 1.0], [1.0 / 3, 4.0 / 3, 1.0 / 3]\n    else\n        # Compute via GaussJacobi:\n        x, w = gaussjacobi(n - 2, 1.0, 1.0)\n        @inbounds for i in 1:length(x)\n            w[i] = w[i] / (1 - x[i]^2)\n        end\n        pushfirst!(x, -1.0)\n        push!(x, 1.0)\n        pushfirst!(w, 2 / (n * (n - 1)))\n        push!(w, 2 / (n * (n - 1)))\n        x, w\n    end\nend\n", "meta": {"hexsha": "802c2664240c3574a5101dbd5a45f2ed7e5c3ae4", "size": 595, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gausslobatto.jl", "max_stars_repo_name": "GeoffChurch/FastGaussQuadrature.jl", "max_stars_repo_head_hexsha": "dadfdd5340f500bbc8a3ad54c04adeb6e5ea4eed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gausslobatto.jl", "max_issues_repo_name": "GeoffChurch/FastGaussQuadrature.jl", "max_issues_repo_head_hexsha": "dadfdd5340f500bbc8a3ad54c04adeb6e5ea4eed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gausslobatto.jl", "max_forks_repo_name": "GeoffChurch/FastGaussQuadrature.jl", "max_forks_repo_head_hexsha": "dadfdd5340f500bbc8a3ad54c04adeb6e5ea4eed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0454545455, "max_line_length": 57, "alphanum_fraction": 0.4403361345, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517095103498, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7986883367063548}}
{"text": "module LP\n\nusing JuMP\nusing Clp\n\nfunction example()\n    # inspired by Linear Algebra and its applications Ch. 9\n\n    m = Model(Clp.Optimizer)\n\n    # unknowns\n    @variable(m, 0 <= x1)\n    @variable(m, 0 <= x2)\n    @variable(m, 0 <= x3)\n\n    # dot(C, x)\n    @objective(m, Max, 2x1 + 3x2 + 4x3)\n\n    # A ∈ R(mxn), with m constraints and n unknowns\n    @constraint(m, x1 + x2 + x3 <= 50)\n    @constraint(m, x1 + 2x2 + 4x3 <= 80)\n\n    optimize!(m)\n\n    println(\"Optimal X: x1: $(value(x1)) x2: $(value(x2)) x3: $(value(x3))\")\n    println(\"Optimal Objective value: $(objective_value(m))\")\n\nend # example\n\nfunction practice_problem_one()\n    # inspired by Linear Algebra and its applications Ch. 9\n\n    m = Model(Clp.Optimizer)\n\n    # unknowns\n    @variable(m, 0 <= x1)\n    @variable(m, 0 <= x2)\n\n    # dot(C, x)\n    @objective(m, Max, 2x1 + x2)\n\n    @constraint(m, -x1 + x2 <= 8)\n    @constraint(m, 3x1 + 2x2  <= 24)\n\n    optimize!(m)\n\n    println(\"Optimal X: x1: $(value(x1)) x2: $(value(x2))\")\n    println(\"Optimal Objective value: $(objective_value(m))\")\n\nend # practice problem one\n\nfunction exercise_seven()\n    # inspired by Linear Algebra and its applications Ch. 9\n\n    m = Model(Clp.Optimizer)\n\n    # unknowns\n    @variable(m, 0 <= x1)\n    @variable(m, 0 <= x2)\n\n    # dot(C, x)\n    @objective(m, Max, 80x1 + 65x2)\n\n    @constraint(m, 2x1 + x2 <= 32)\n    @constraint(m, x1 + x2  <= 18)\n    @constraint(m, x1 + 3x2  <= 24)\n\n    optimize!(m)\n\n    println(\"Optimal X: x1: $(value(x1)) x2: $(value(x2))\")\n    println(\"Optimal Objective value: $(objective_value(m))\")\n\nend # exercise seven\n\nend # module\n", "meta": {"hexsha": "94a56aa981542d317eca696bb0936837b1824e03", "size": 1603, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lp/src/LP.jl", "max_stars_repo_name": "DonQueso89/LinearProgramming", "max_stars_repo_head_hexsha": "b38f65275f9efe851c50353ab82a98d99e6f33f1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lp/src/LP.jl", "max_issues_repo_name": "DonQueso89/LinearProgramming", "max_issues_repo_head_hexsha": "b38f65275f9efe851c50353ab82a98d99e6f33f1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lp/src/LP.jl", "max_forks_repo_name": "DonQueso89/LinearProgramming", "max_forks_repo_head_hexsha": "b38f65275f9efe851c50353ab82a98d99e6f33f1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0921052632, "max_line_length": 76, "alphanum_fraction": 0.5888958203, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517083920618, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7986883337672661}}
{"text": "module CubicHermiteSpline\n\nusing ArgCheck\n\nexport CubicHermiteSplineInterpolation\nexport interp, grad\n\nstruct CubicHermiteSplineInterpolation\n    x\n    y\n    gradient\nend\n\n\n\"\"\"\n    basis(t)\n\nCompute the basis functions of cubic Hermite spline interpolation. They are:\n    H_{00} = 2t^3 - 3t^2 + 1 = (1+2t)(t-1)^2\n    H_{10} = t^3 - 2t^2 + t = t(t-1)^2\n    H_{01} = -2t^3 + 3t^2 = t^2(3-2t)\n    H_{11} = t^3 - t^2 = t^2(t - 1)\n\"\"\"\nfunction basis(t)\n    t2 = t * t\n    it = t - 1\n    it2 = it * it\n    tt = 2 * t\n    h00 = (1 + tt) * it2\n    h10 = t * it2\n    h01 = t2 * (3 - tt)\n    h11 = t2 * it\n    return h00, h10, h01, h11\nend\n\n\"\"\"\n    basis_derivative(t)\n\nCompute the basis functions of cubic Hermite spline interpolation. They are:\n    H_{00} = 6t^2 - 6t = 6t(t-1)\n    H_{10} = 3t^2 - 4t + 1 = (3t-1)(t-1)\n    H_{01} = -6t^2 + 6t = -6t(t-1)\n    H_{11} = 3t^2 - 2t = t(3t - 2)\n\"\"\"\nfunction basis_derivative(t)\n    t2 = t * t\n    h00 = 6*t2 - 6*t\n    h10 = 3*t2 - 4*t + 1\n    h01 = -6*t2 + 6*t\n    h11 = 3*t2 - 2*t\n    return h00, h10, h01, h11\nend\n\nfunction findinterval(v, x)\n    for i in eachindex(x)\n        if x[i] == v\n            return i, x[i], nothing\n        elseif x[i] > v\n            return i-1, x[i-1], x[i]\n        end\n    end\nend\n\nfunction _interp(spl::CubicHermiteSplineInterpolation, v; grad=false)\n    x = spl.x\n    y = spl.y\n    gradient = spl.gradient\n    @argcheck v >= x[1]\n    @argcheck v <= x[end]\n\n    idx, x1, x2 = findinterval(v, x)\n    if x2 === nothing\n       return grad ? gradient[idx] : y[idx]\n    end\n\n    # mapping (x1, x2) to (0, 1), h is the scaling constant\n    t = (v - x1) / (x2 - x1)\n    h = x2 - x1\n    y1, y2 = y[idx], y[idx+1]\n    k1, k2 = gradient[idx], gradient[idx+1]\n\n    h00, h10, h01, h11 = grad ? basis_derivative(t) : basis(t)\n    r = y1*h00 + h*k1*h10 + y2*h01 + h*k2*h11\n\n    # Need to rescale the interpolated gradient before return\n    return grad ? (r/h) : r\nend\n\n(spl::CubicHermiteSplineInterpolation)(v::Real; grad=false) = _interp(spl, v; grad=grad)\n(spl::CubicHermiteSplineInterpolation)(x::AbstractVector; grad=false) = spl.(x; grad=grad)\n\n# handy methods\ninterp(spl::CubicHermiteSplineInterpolation, p) = spl(p)\ngrad(spl::CubicHermiteSplineInterpolation, p) = spl(p; grad=true)\n\nend # module", "meta": {"hexsha": "4a5dd0e11897c7effc11e3a06b27906382a2a544", "size": 2257, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CubicHermiteSpline.jl", "max_stars_repo_name": "liuyxpp/CubicHermiteSpline.jl", "max_stars_repo_head_hexsha": "545c1de78c5eee0036a9bcd485cf87d6accfe967", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-09-15T13:47:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T02:10:15.000Z", "max_issues_repo_path": "src/CubicHermiteSpline.jl", "max_issues_repo_name": "liuyxpp/CubicHermiteSpline.jl", "max_issues_repo_head_hexsha": "545c1de78c5eee0036a9bcd485cf87d6accfe967", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CubicHermiteSpline.jl", "max_forks_repo_name": "liuyxpp/CubicHermiteSpline.jl", "max_forks_repo_head_hexsha": "545c1de78c5eee0036a9bcd485cf87d6accfe967", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5104166667, "max_line_length": 90, "alphanum_fraction": 0.5768719539, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8740772351648677, "lm_q1q2_score": 0.7986238453113779}}
{"text": "# Locally Linear Embedding (LLE)\n# ------------------------\n# Nonlinear dimensionality reduction by locally linear embedding,\n# Roweis, S. & Saul, L., Science 290:2323 (2000)\n\nusing Logging\n\n#### LLE type\nstruct LLE{T <: Real} <: AbstractDimensionalityReduction\n    k::Int\n    λ::AbstractVector{T}\n    proj::Projection{T}\n\n    LLE{T}(k::Int, λ::AbstractVector{T}, proj::Projection{T})  where T = new(k, λ, proj)\nend\n\n## properties\noutdim(R::LLE) = size(R.proj, 1)\neigvals(R::LLE) = R.λ\nneighbors(R::LLE) = R.k\n\n## show\nsummary(io::IO, R::LLE) = print(io, \"LLE(outdim = $(outdim(R)), neighbors = $(neighbors(R)))\")\n\n## interface functions\nfunction fit(::Type{LLE}, X::AbstractMatrix{T};\n             maxoutdim::Int=2, k::Int=12, tol::Real=1e-5,\n             use_naive=false, use_eigen=false) where {T<:Real}\n    # Construct NN graph\n    D, E = find_nn(X, k)\n    _, C = largest_component(SimpleWeightedGraph(adjmat(D,E)))\n    X = X[:, C]\n    n = length(C)\n\n    # Correct indexes of neighbors if more then one connected component\n    Ec = E\n    if size(E,2) != n\n        R = Dict(zip(C, collect(1:n)))\n        Ec = zeros(Int,k,n)\n        for i in 1 : n\n            Ec[:,i] = map(j->get(R,j,C[i]), E[:,C[i]])\n        end\n    end\n\n    if k > maxoutdim\n        @warn(\"k > maxoutdim: regularization will be used\")\n    end\n\n    # Reconstruct weights and compute embedding:\n    # M = (I - w)'(I - w) = I - w'I - Iw + w'w\n    M = spdiagm(0 => fill(one(T), n))\n    Ones = fill(one(T), k, 1)\n    for i in 1 : n\n        J = Ec[:,i]\n        Z = view(X, :, J) .- view(X, :, i)\n        G = transpose(Z)*Z\n        G += I * tol # regularize\n        w = vec(G \\ Ones)\n        w ./= sum(w)\n        ww = w*transpose(w)\n        for (l, j) in enumerate(J)\n            M[i,j] -= w[l]\n            M[j,i] -= w[l]\n            for (m, jj) in enumerate(J)\n                M[j,jj] = ww[l,m]\n            end\n        end\n    end\n\n    if use_eigen\n        λ, V = decompose(M, maxoutdim)\n    else\n        λ, V = specDecompose(M, tol, maxoutdim, use_naive)\n    end\n    return LLE{T}(k, λ, rmul!(transpose(V), sqrt(n)))\nend\n\ntransform(R::LLE) = R.proj\n", "meta": {"hexsha": "70cca396a99abcc227b27c1f8de2a51899cd9d8d", "size": 2116, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lle.jl", "max_stars_repo_name": "VHarisop/ManifoldLearning.jl", "max_stars_repo_head_hexsha": "09b36fbce7f636ced8c1fe53af823d9d5153c046", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lle.jl", "max_issues_repo_name": "VHarisop/ManifoldLearning.jl", "max_issues_repo_head_hexsha": "09b36fbce7f636ced8c1fe53af823d9d5153c046", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lle.jl", "max_forks_repo_name": "VHarisop/ManifoldLearning.jl", "max_forks_repo_head_hexsha": "09b36fbce7f636ced8c1fe53af823d9d5153c046", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7848101266, "max_line_length": 94, "alphanum_fraction": 0.5297731569, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857204, "lm_q2_score": 0.8705972600147106, "lm_q1q2_score": 0.798601182039535}}
{"text": "\"\"\"\n Convert cartesian coordinates to spherical coordinates (θ,ϕ,r)\n θ, ϕ are in radians\n ϕ is the latitude, i.e., the angle from the equator.\n\"\"\"\nfunction xyz2θϕr(x)\n  r = sqrt(x[1]^2 + x[2]^2 + x[3]^2)\n  θ = atan(x[2], x[1])\n  ϕ = asin(x[3]/r)\n  VectorValue(θ,ϕ,r)\nend\n\n\"\"\"\n  Map point on the unit sphere on ambientspace to the parametric space of the unit sphere\n  (x,y,z) ↦ (θ,ϕ)\n\"\"\"\nfunction xyz2θϕ(x)\n  θ = atan(x[2], x[1])\n  ϕ = asin(x[3])\n  VectorValue(θ,ϕ)\nend\n\n\"\"\"\n  Map point on the parametric space of the unit sphere to the ambient space\n  (θ,ϕ) ↦ (x,y,z)\n\"\"\"\nfunction θϕ2xyz(θϕ)\n  θ,ϕ = θϕ\n  x = cos(θ)*cos(ϕ)\n  y = sin(θ)*cos(ϕ)\n  z = sin(ϕ)\n  VectorValue(x,y,z)\nend\n\n\n\"\"\"\nMatrix transformation from spherical vector field to Cartesian vector field.\n  θ∈(0,2π)\n  ϕ∈(-π/2,π/2)\n  r=constant for the sphere\n\"\"\"\nfunction spherical_to_cartesian_matrix(θϕr)\n  θ,ϕ,r = θϕr\n  TensorValue(-sin(θ)       , cos(θ)       ,      0,\n              -sin(ϕ)*cos(θ),-sin(ϕ)*sin(θ), cos(ϕ),\n               cos(ϕ)*cos(θ), cos(ϕ)*sin(θ), sin(ϕ))\nend\n\n\"\"\"\nMatrix transformation from cartesian vector field to spherical vector field\n\"\"\"\nfunction cartesian_to_spherical_matrix(xyz)\n  x,y,z = xyz\n  sr = sqrt(x^2+y^2+z^2)\n  cr = sqrt(x^2+y^2)\n  TensorValue(-y/cr, (x*z)/(sr*cr), x/sr,\n               x/cr, (y*z)/(sr*cr), y/sr,\n                  0,   -cr/(sr*cr), z/sr)\nend\n", "meta": {"hexsha": "e336d0ee2ce6811dac0b382e706e57eee39fb1bb", "size": 1363, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CoordinateTransformations.jl", "max_stars_repo_name": "santiagobadia/GridapGeosciences", "max_stars_repo_head_hexsha": "c9bfdd7bbd33a8464376d1d102a44d78ccd11069", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2020-04-20T07:04:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T17:40:12.000Z", "max_issues_repo_path": "src/CoordinateTransformations.jl", "max_issues_repo_name": "santiagobadia/GridapGeosciences", "max_issues_repo_head_hexsha": "c9bfdd7bbd33a8464376d1d102a44d78ccd11069", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-06-09T04:05:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T04:15:08.000Z", "max_forks_repo_path": "src/CoordinateTransformations.jl", "max_forks_repo_name": "santiagobadia/GridapGeosciences", "max_forks_repo_head_hexsha": "c9bfdd7bbd33a8464376d1d102a44d78ccd11069", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-03-10T06:11:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-05T02:32:21.000Z", "avg_line_length": 22.7166666667, "max_line_length": 89, "alphanum_fraction": 0.5898752751, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899575269305, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7985205707629887}}
{"text": "using Plots\n\nfunction bracket_minimum(f, x=0; s=1e-2, k=2.0)\n    a, ya = x, f(x)\n    b, yb = a + s, f(a + s)\n    if yb > ya\n        a, b = b, a\n        ya, yb = yb, ya\n        s = -s\n    end\n    while true\n        c, yc = b + s, f(b + s)\n        if yc > yb\n            return a < c ? (a,b, c) : (c, b, a)\n        end\n        a, ya, b, yb = b, yb, c, yc\n        s *= k\n    end\nend\n\n\nfunction quadratic_fit_search(f, a, b, c, n)\n    ya, yb, yc = f(a), f(b), f(c)\n    for i in 1:n-3\n        x = 0.5*(ya*(b^2-c^2)+yb*(c^2-a^2)+yc*(a^2-b^2)) /\n            (ya*(b-c) +yb*(c-a) +yc*(a-b))\n        yx = f(x)\n        if x > b\n            if yx > yb\n                c, yc = x, yx\n            else\n                a, ya, b, yb = b, yb, x, yx\n            end\n        elseif x < b\n            if yx > yb\n                a, ya = x, yx\n            else\n                c, yc, b, yb = b, yb, x, yx\n            end\n        end\n    end\n    return (a, b, c)\nend\n\n\nf = x->sin(10x)+cos(3x)\nx0 = 3.4\n#busca do intervalo\na,b,c = bracket_minimum(f,x0)\n\n#numero de iteracoes\nφ = MathConstants.φ\nn=(c-a)/(10^-3*log(φ))\n\nam,bm,cm = quadratic_fit_search(f,a,b,c,n)\n(am,f(am))\nam,bm,cm\n\n\nplot(f,0.,4.,lw=2,draw_arrow=\"true\")\nscatter!([a,b,c],[f(a),f(b),f(c)])\nscatter!([am,bm,cm],[f(am),f(bm),f(cm)])", "meta": {"hexsha": "7c069e89d0e588dd0efd0756bc726d136f5fa4d5", "size": 1271, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Quadratic_Fit_Search.jl", "max_stars_repo_name": "GilbertoLucas/Structural_Optimization", "max_stars_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Quadratic_Fit_Search.jl", "max_issues_repo_name": "GilbertoLucas/Structural_Optimization", "max_issues_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Quadratic_Fit_Search.jl", "max_forks_repo_name": "GilbertoLucas/Structural_Optimization", "max_forks_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5, "max_line_length": 58, "alphanum_fraction": 0.4114870181, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135442, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7984923675446653}}
{"text": "# This file investigates mean square error (MSE) with respect to free variables in hidden 1D interpolation \n\nusing FractalTools \nusing Makie \n\n# Construct interpolation data \n# f(x) = [FractalTools.sinusoid(x), FractalTools.sinusoid(x)]  # For regular data \nf(x) = [FractalTools.wen(x), FractalTools.weierstrass(x)]  # For irregular data \nline = [[0.], [1.]]\npts = getdata(f, line, 11)   \n\n# Construct test data \ntpts = getdata(line, 101)\nnpts = length(tpts) \n\n# Compute errors \nfvals = getindex.(map(pnt -> f(pnt[1]), tpts), 1)\nfreevars = 0.001 : 0.01 : 0.5\nmse = map(freevars) do freevar \n    interp = interpolate(pts, HInterp1D(fill(freevar, 2, 2)))\n    ivals = getindex.(map(pnt -> interp(pnt[1]), tpts), 1)\n    sum((fvals - ivals).^2) / npts \nend \n\n# Plot mse \nfig = Figure() \nax = fig[1, 1] = Axis(fig, xlabel=\"Free Variable\", ylabel=\"MSE\", title=\"1D Hidden Interpolation MSE\") \nstem!(ax, freevars, mse, color=:black)\nsave(joinpath(@__DIR__, \"hinterp1d_mse.png\"), fig)\ndisplay(fig)\n\n", "meta": {"hexsha": "2cc668b30c770ab542f0a51020fb3b3630978d06", "size": 989, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiment_2/interpolation_mse_vs_freevars/hinterp1d/hinterp1d.jl", "max_stars_repo_name": "zekeriyasari/FractalTools.jl", "max_stars_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-08T12:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T12:50:16.000Z", "max_issues_repo_path": "experiment_2/interpolation_mse_vs_freevars/hinterp1d/hinterp1d.jl", "max_issues_repo_name": "zekeriyasari/FractalTools.jl", "max_issues_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-09-05T18:22:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T10:09:46.000Z", "max_forks_repo_path": "experiment_2/interpolation_mse_vs_freevars/hinterp1d/hinterp1d.jl", "max_forks_repo_name": "zekeriyasari/FractalTools.jl", "max_forks_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.90625, "max_line_length": 107, "alphanum_fraction": 0.675429727, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7984923640537217}}
{"text": "export accuracy, bce, logistic, nll, zeroone\n\n\n\"\"\"\n    nll(scores, labels; dims=1, average=true)\n\nReturn the negative log likelihood for a single batch of data given an unnormalized `scores`\nmatrix and an `Integer` array of correct `labels`. The `scores` matrix should have size\n`(classes,instances)` if `dims=1` or `(instances,classes)` if `dims=2`. `labels[i]` should be\nin `1:classes` to indicate the correct class for instance i, or 0 to skip instance i.\n\nThe return value is `(total/count)` if `average=true` and `(total,count)` if `average=false`\nwhere `count` is the number of instances not skipped (i.e. `label != 0`) and `total` is their\ntotal negative log likelihood.\n\n## Example\n\nLet's assume that there are three classes (cat, dog, ostrich) and just 2 instances with\nthe unnormalized score `scores[:,1]` and `scores[:,2]` respectively. The first instance\nis actually a cat and the second instance a dog:\n\n    scores = [12.2    0.3;\n               2.0   21.5;\n               0.0  -21.0]\n    labels = [1, 2]\n    nll(scores,labels)\n    # returns 2.1657e-5\n\nThe probabilites are derived from the scores and the negative log-probabilities corresponding\nto the labels are averaged:\n\n    probabilites = exp.(scores) ./ sum(exp.(scores),dims=1)\n    -(log(probabilites[labels[1],1]) + log(probabilites[labels[2],2]))/2\n    # returns 2.1657e-5\n\n\"\"\"\nfunction nll(scores,labels::AbstractArray{<:Integer}; dims=1, average=true)\n    indices = findindices(scores,labels,dims=dims)\n    lp = logsoftmax(scores,dims=dims)[indices]\n    average ? (-sum(lp) / length(lp)) : (-sum(lp), length(lp))\nend\n\n\n\"\"\"\n    accuracy(scores, labels; dims=1, average=true)\n\nGiven an unnormalized `scores` matrix and an `Integer` array of correct `labels`, return the\nratio of instances where the correct label has the maximum score. `dims=1` means instances are\nin columns, `dims=2` means instances are in rows. Use `average=false` to return the pair\n(ncorrect,count) instead of the ratio (ncorrect/count). The valid labels should be integers in\nthe range `1:numclasses`, if `labels[i] == 0`, instance i is skipped.\n\n\"\"\"\nfunction accuracy(scores,labels::AbstractArray{<:Integer}; dims=1, average=true)\n    indices = findindices(scores,labels,dims=dims)\n    ycpu = convert(Array,value(scores))\n    (maxval,maxind) = findmax(ycpu,dims=dims)\n    maxind = LinearIndices(ycpu)[maxind]\n    maxind = vec(maxind)[vec(labels) .!= 0]\n    correct = (maxind .== indices)\n    average ? (sum(correct) / length(correct)) : (sum(correct), length(correct))\nend\n\n\n\"\"\"\n    logistic(scores, labels; average=true)\n\nComputes logistic loss given predicted unnormalized scores and answer labels for a binary\nprediction task.\n\n    log.(1 .+ exp.(-labels .* scores))\n\nLabel values should be {-1,1}. Scores are unrestricted.  The return value is `(total/count)`\nif `average=true` and `(total,count)` if `average=false` where `count` is the number of\ninstances and `total` is their total loss.\n\nSee also `bce` which computes the same loss with {0,1} labels.\n\nReference: https://towardsdatascience.com/nothing-but-numpy-understanding-creating-binary-classification-neural-networks-with-e746423c8d5c\n\"\"\"\nfunction logistic(scores, labels::AbstractVector{<:Integer}; average=true)\n    labels = ((labels .+ 1) .÷ 2) # (-1,1)->(0,1)\n    bce(scores,labels; average=average)\nend\n\n\n\"\"\"\n    bce(scores, labels; average=true)\n\nComputes binary cross entropy loss given predicted unnormalized scores and answer labels for a\nbinary prediction task. Label values should be in {0,1}. Scores are unrestricted and will be\nconverted to probabilities using\n\n    probs = 1 ./ (1 .+ exp.(-scores))\n\nThe loss calculated is\n\n    -(labels .* log.(probs) .+ (1 .- labels) .* log.(1 .- probs))\n\nThe return value is `(total/count)` if `average=true` and `(total,count)` if `average=false`\nwhere `count` is the number of instances and `total` is their total loss.\n\nSee also `logistic` which computes the same loss with {-1,1} labels.\n\nReference: https://towardsdatascience.com/nothing-but-numpy-understanding-creating-binary-classification-neural-networks-with-e746423c8d5c\n\"\"\"\nfunction bce(scores, labels::AbstractVector{<:Integer}; average=true) \n    labels = oftype(scores,labels)\n    l = max.(0, scores) .- labels .* scores .+ log.(1 .+ exp.(-abs.(scores)))\n    average ? (sum(l)/length(l)) : (sum(l),length(l))\nend\n\n\n# Indexing help for nll and accuracy\n\nfunction findindices(scores, labels::AbstractArray{<:Integer}; dims=1)\n    ninstances = length(labels)\n    nindices = 0\n    indices = Vector{Int}(undef,ninstances)\n    if dims == 1                   # instances in first dimension\n        y1 = size(scores,1)\n        y2 = div(length(scores),y1)\n        if ninstances != y2; throw(DimensionMismatch()); end\n        @inbounds for j=1:ninstances\n            if labels[j] == 0; continue; end\n            indices[nindices+=1] = (j-1)*y1 + labels[j]\n        end\n    elseif dims == 2               # instances in last dimension\n        y2 = size(scores,ndims(scores))\n        y1 = div(length(scores),y2)\n        if ninstances != y1; throw(DimensionMismatch()); end\n        @inbounds for j=1:ninstances\n            if labels[j] == 0; continue; end\n            indices[nindices+=1] = (labels[j]-1)*y1 + j\n        end\n    else\n        error(\"findindices only supports dims = 1 or 2\")\n    end\n    return (nindices == ninstances ? indices : view(indices,1:nindices))\nend\n\n\n\"\"\"\n    nll(model; data, dims=1, average=true, o...)\n\nCompute the negative log likelihood for a model over a dataset:\n\n    nll(model(inputs; kwargs...), labels; dims) for (inputs,labels) in data\n\nand return `(total/count)` if `average=true` or `(total,count)` if `average=false` where\n`count` is the number of instances not skipped (instances with `label==0` are skipped) and\n`total` is their total negative log likelihood.\n\nThe `model` should be a function returning scores given inputs, and data should be an iterable\nof `(inputs,labels)` pairs. The valid labels should be integers in the range `1:numclasses`,\nif `labels[i] == 0`, instance i is skipped.\n\n\"\"\"\nfunction nll(model; data, dims=1, average=true, o...)\n    sum = cnt = 0\n    for (x,y) in data\n        (z,n) = nll(model(x; o...), y; dims=dims, average=false) \n        sum += z; cnt += n\n    end\n    average ? sum / cnt : (sum, cnt)\nend\n\n\n\"\"\"\n    accuracy(model; data, dims=1, average=true, o...)\n\nCompute the number of correct predictions of a model over a dataset:\n\n    accuracy(model(inputs; kwargs...), labels; dims) for (inputs,labels) in data\n\nand return `(ncorrect/count)` if `average=true` or `(ncorrect,count)` if `average=false` where\n`count` is the number instances not skipped (instances with `label==0` are skipped) and\n`ncorrect` is the number of them correctly labeled by the model.\n\nThe `model` should be a function returning scores given inputs, and data should be an iterable\nof `(inputs,labels)` pairs. The valid labels should be integers in the range `1:numclasses`,\nif `labels[i] == 0`, instance i is skipped.\n\n\"\"\"\nfunction accuracy(model; data, dims=1, average=true, o...)\n    sum = cnt = 0\n    for (x,y) in data\n        (z,n) = accuracy(model(x; o...), y; dims=dims, average=false)\n        sum += z\n        cnt += n\n    end\n    average ? sum / cnt : (sum, cnt)\nend\n\n\n# DEPRECATE:\n\n# The two-arg model,data calls cause mix-ups with the scores,labels calls:\nfunction nll(model,data; o...)\n    @warn \"nll(model,data; o...) is deprecated, please use nll(model; data=data, o...)\" maxlog=1\n    nll(model; data=data, o...)\nend\n\nfunction accuracy(model,data; o...)\n    @warn \"accuracy(model,data; o...) is deprecated, please use accuracy(model; data=data, o...)\" maxlog=1\n    accuracy(model; data=data, o...)\nend\n\n# We need the (model,x,y) interface to implement regularization:\nfunction nll(f, x, y; dims=1, average=true, o...)\n    @warn \"nll(f,x,y; o...) is deprecated, please use nll(f(x),y; o...) instead.\" maxlog=1\n    nll(f(x; o...), y; dims=dims, average=average)\nend\n\nfunction accuracy(f, x, y; dims=1, average=true, o...)\n    @warn \"accuracy(f,x,y; o...) is deprecated, please use accuracy(f(x),y; o...) instead.\" maxlog=1\n    accuracy(f(x; o...), y; dims=dims, average=average)\nend\n\n# We need the (weights,data,predict) interface to support the old interface:\nfunction nll(w, data, f::Function; dims=1, average=true, o...)\n    @warn \"nll(weights,data,func; o...) is deprecated, please use nll(x->func(weights,x); data=data, o...) instead.\" maxlog=1\n    nll(x->f(w,x;o...), data; dims=dims, average=average)\nend\n\nfunction accuracy(w, data, f::Function; dims=1, average=true, o...)\n    @warn \"accuracy(weights,data,func; o...) is deprecated, please use accuracy(x->func(weights,x); data=data, o...) instead.\" maxlog=1\n    accuracy(x->f(w,x;o...), data; dims=dims, average=average)\nend\n\n\"zeroone loss is equal to 1 - accuracy\"\nfunction zeroone(x...; o...)\n    @warn \"zeroone() is deprecated, please use 1-accuracy()\" maxlog=1\n    1 - accuracy(x...; o...)\nend\n\n", "meta": {"hexsha": "7c82e4d943c8e307352956e0a5ba669f479434ab", "size": 8932, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ops20/loss.jl", "max_stars_repo_name": "AndrewSerra/Knet.jl", "max_stars_repo_head_hexsha": "cbbcb670667b1707ad1b1d7c637784e36a98b81e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1492, "max_stars_repo_stars_event_min_datetime": "2015-09-30T07:05:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T14:48:46.000Z", "max_issues_repo_path": "src/ops20/loss.jl", "max_issues_repo_name": "AndrewSerra/Knet.jl", "max_issues_repo_head_hexsha": "cbbcb670667b1707ad1b1d7c637784e36a98b81e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 604, "max_issues_repo_issues_event_min_datetime": "2016-02-05T06:32:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T20:09:19.000Z", "max_forks_repo_path": "src/ops20/loss.jl", "max_forks_repo_name": "AndrewSerra/Knet.jl", "max_forks_repo_head_hexsha": "cbbcb670667b1707ad1b1d7c637784e36a98b81e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 340, "max_forks_repo_forks_event_min_datetime": "2015-10-28T07:47:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:51:11.000Z", "avg_line_length": 37.6877637131, "max_line_length": 138, "alphanum_fraction": 0.6733094492, "num_tokens": 2461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541528387691, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7984923611498616}}
{"text": "using NumericalMethodsforEngineers, Plots\n\nold = pwd()\nProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n\n  f(x::Float64, y::Vector{Float64}) = (x + y[1])/x\n  steps = 3\n  h = 0.333\n\n  x = 2.0\n  y = [2.0]\n\n  # y(3.0) = 4.2165\n\n  r = Array{Float64,2}[]\n  push!(r, euler(f, x, y, steps, h))\n  push!(r, modified_euler(f, x, y, steps, h))\n  push!(r, mid_point_euler(f, x, y, steps, h))\n  push!(r, runga_kutta_4(f, x, y, steps, h))\n  println()\n  r |> display\n  println()\n\n  xs = x + Float64[(i-1)*h for i in 1:steps+1]\n  titles = [\"Euler\", \"Modified_Euler\", \"Mid_Point_Euler\", \"Runga_Kutta_4\"]\n\n\n  p1 = plot(xs, r[1][:, 2])\n  plot!(p1, xs, r[2][:, 2])\n  plot!(p1, xs, r[3][:, 2])\n  plot!(p1, xs, r[4][:, 2])\n  show(p1)\n  savefig(\"Ex7.2.png\")\n  gui()\n\nend\n", "meta": {"hexsha": "61610829cc2f80d3c6784a92a597fccab1289d4b", "size": 743, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch07/IVP/Ex7.1.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "examples/ch07/IVP/Ex7.1.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "examples/ch07/IVP/Ex7.1.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 19.5526315789, "max_line_length": 74, "alphanum_fraction": 0.5612382234, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7984923580794164}}
{"text": "using LinearAlgebra\n\nfunction swap_rows(i::T, nlinha::T) where {T<:Integer}\n    for n ∈ (i+1):nlinha        # iterate over lines above to check if could be swap\n        if A[n,i] ≠ 0.0         # condition to swap row\n            L = copy(A[i,:])    # copy line to swap\n            A[i,:] = A[n,:]     # swap occur\n            A[n,:] = L\n            break\n        end\n    end\nend\n\nfunction gauss_jordan(A::Matrix{T}) where {T<:Number}\n    \n    # convert to float to avoid InexactError: Int64()\n    (T <: Integer) && (A = convert.(Float64, A))\n\n    # check if matrix is singular\n    m, n = size(A)\n    if m == n\n        @assert det(A) ≠ 0.0 \"Must insert a non-singular matrix\"\n    else\n        @assert det(A[:,1:end-1]) ≠ 0.0 \"Must insert a non-singular matrix or a system matrix [A b]\"\n    end\n\n    for i ∈ axes(A, 1)\n        if A[i,i] == 0.0                            # check if need swap rows\n            swap_rows(i, m)\n        end\n\n        @. A[i,:] = A[i,:] / A[i,i]                 # divide pivot line by pivot element\n\n        for j ∈ axes(A, 1)                          # iterate each line for each pivot column, except pivot line\n            if j ≠ i                                # jump pivot line\n                @. A[j,:] = A[j,:] - A[i,:]*A[j,i]  # apply gauss jordan in each line\n            end\n        end\n    end\n\n    return A\nend\n\n## logic in the for loops \n# A[1,:] = A[1,:]./ A[1,1]\n# A[2,:] = A[2,:] - A[1,:]*A[2,1]\n# A[3,:] = A[3,:] - A[1,:]*A[3,1]\n\n# A[2,:] = A[2,:]./ A[2,2]\n# A[1,:] = A[1,:] - A[2,:].*A[1,2]\n# A[3,:] = A[3,:] - A[2,:].*A[3,2]\n\n# A[3,:] = A[3,:]./ A[3,3]\n# A[1,:] = A[1,:] - A[3,:].*A[1,3]\n# A[2,:] = A[2,:] - A[3,:].*A[2,3]", "meta": {"hexsha": "05c448dcbc04856ed98254911bc3d302e2cdeb1e", "size": 1667, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gauss_jordan_elim.jl", "max_stars_repo_name": "AugustoCL/gauss_jordan_elimination", "max_stars_repo_head_hexsha": "4f11a1fb0b1a42ca77905a0295eb7aedb8643734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gauss_jordan_elim.jl", "max_issues_repo_name": "AugustoCL/gauss_jordan_elimination", "max_issues_repo_head_hexsha": "4f11a1fb0b1a42ca77905a0295eb7aedb8643734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gauss_jordan_elim.jl", "max_forks_repo_name": "AugustoCL/gauss_jordan_elimination", "max_forks_repo_head_hexsha": "4f11a1fb0b1a42ca77905a0295eb7aedb8643734", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3090909091, "max_line_length": 112, "alphanum_fraction": 0.4433113377, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642557, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7984593660145266}}
{"text": "isharshad(x)   = x % sum(digits(x)) == 0\nnextharshad(x) = begin while !isharshad(x+1) x += 1 end; return x + 1 end\n\nfunction harshads(n::Integer)\n\th = Vector{typeof(n)}(n)\n\th[1] = 1\n\tfor j in 2:n\n\t\th[j] = nextharshad(h[j-1])\n\tend\n\treturn h\nend\n\nprintln(\"First 20 harshad numbers: \", join(harshads(20), \", \"))\nprintln(\"First harshad number after 1001: \", nextharshad(1000))\n", "meta": {"hexsha": "1f11c7b30f8ede3012de62f70fe5f82a8b28d031", "size": 373, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/harshad-or-niven-series.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/harshad-or-niven-series.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/harshad-or-niven-series.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8666666667, "max_line_length": 73, "alphanum_fraction": 0.6461126005, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657177, "lm_q2_score": 0.8774767954920547, "lm_q1q2_score": 0.798422275279043}}
{"text": "import Base.show\r\n\r\nusing Colors\r\nusing CSV\r\nusing LinearAlgebra\r\nusing Plots\r\n\r\n\"\"\"\r\n    getpoints(path::String, [usingnames::Bool])\r\n\r\nRead the x and y coordinates from a list in a CSV file at `path`.\r\n\r\nAlso read the names if `usingnames`.\r\n\r\n# Example\r\n```julia-repl\r\njulia> getpoints(\"points.txt\")\r\n```\r\n\"\"\"\r\nfunction getpoints(path::String, usingnames::Bool = false)\r\n    xs = Int64[]\r\n    ys = Int64[]\r\n    names = String[]\r\n    for row ∈ CSV.Rows(path)\r\n        push!(xs,parse(Int64,row.x))\r\n        push!(ys,parse(Int64,row.y))\r\n        if usingnames\r\n            push!(names,row.name)\r\n        end\r\n    end\r\n    return usingnames ? (names, xs, ys) : (xs, ys)\r\nend\r\n\r\n\"\"\"\r\n    bruteforcevoronoi(xs::Vector{Int64}, ys::Vector{Int64})\r\n\r\nDraw a Voronoi diagram from lists of coordinates `xs` and `ys` by individually colouring every square of a 1000x1000 grid.\r\n\r\n# Example\r\n```julia-repl\r\njulia> bruteforcevoronoi(rand(1:1000, 10), rand(1:1000, 10))\r\n```\r\n\"\"\"\r\nfunction bruteforcevoronoi(xs::Vector{Int64}, ys::Vector{Int64})\r\n    m = length(xs)\r\n    colours = distinguishable_colors(m, lchoices = 50:5:100)\r\n\r\n    pointcolours = fill(RGB(0,0,0), (1000,1000))\r\n    for y ∈ 1:1000\r\n        for x ∈ 1:1000\r\n            pointcolours[x,y] = colours[findmin(hypot.(xs .- x, ys .- y))[2]]\r\n        end\r\n    end\r\n\r\n    diagram = scatter(\r\n        [(x,y) for x ∈ 1:1000, y ∈ 1:1000][:];\r\n        c = pointcolours[:],\r\n        markersize = 1,\r\n        markerstrokewidth = 0,\r\n        legend = false,\r\n        showaxis = false,\r\n        ticks = false,\r\n        size = (1000, 1000)\r\n    )\r\n    return scatter!(\r\n        diagram,\r\n        xs,\r\n        ys;\r\n        c = :black,\r\n        markersize = 2,\r\n        markerstrokewidth = 0\r\n    )\r\nend\r\n\r\n\"\"\"\r\n    montecarlovoronoi(n::Int64, xs::Vector{Int64}, ys::Vector{Int64})\r\n\r\nSample `n` times from a 1000x1000 grid to approximate a Voronoi diagram from lists of coordinates `xs` and `ys`.\r\n\r\n# Example\r\n```julia-repl\r\njulia> montecarlovoronoi(100000, rand(1:1000, 10), rand(1:1000, 10))\r\n```\r\n\"\"\"\r\nfunction montecarlovoronoi(n::Int64, xs::Vector{Int64}, ys::Vector{Int64})\r\n    m = length(xs)\r\n    colours = distinguishable_colors(m, lchoices = 50:5:100)\r\n\r\n    randxs = Int64[]\r\n    randys = Int64[]\r\n    randcolours = RGB[]\r\n\r\n    for _ ∈ 1:n\r\n        x, y = rand(1:1000), rand(1:1000)\r\n        push!(randxs, x)\r\n        push!(randys, y)\r\n        push!(randcolours, colours[findmin(hypot.(xs .- x, ys .- y))[2]])\r\n    end\r\n\r\n    diagram = scatter(\r\n        randxs,\r\n        randys;\r\n        c = randcolours,\r\n        markersize = 1,\r\n        markerstrokewidth = 0,\r\n        legend = false,\r\n        showaxis = false,\r\n        ticks = false,\r\n        size = (1000, 1000)\r\n    )\r\n    return scatter!(\r\n        diagram,\r\n        xs,\r\n        ys;\r\n        c = :black,\r\n        markersize = 2,\r\n        markerstrokewidth = 0,\r\n    )\r\nend\r\n\r\n\"\"\"\r\n    VoronoiPoint(x::Real, y::Real, neighbours::Vector{VoronoiPoint})\r\n    VoronoiPoint(x::Real, y::Real)\r\n\r\nConstruct a `VoronoiPoint` at the coordinates `x`, `y`, representing a point in a Voronoi diagram.\r\n\r\nIf no neighbours are specified, default to an empty `Vector{VoronoiPoint}`.\r\n\r\n# Examples\r\n```julia-repl\r\njulia> p = VoronoiPoint(3,4)\r\n(3,4)\r\n\r\njulia> q = VoronoiPoint(4,5,[p])\r\n(4,5)\r\n\r\njulia> p.neighbours\r\nVoronoiPoint[]\r\n\r\njulia> q.neighbours\r\n1-element Vector{VoronoiPoint}:\r\n (3,4)\r\n```\r\n\"\"\"\r\nmutable struct VoronoiPoint\r\n    x::Real\r\n    y::Real\r\n    neighbours::Vector{VoronoiPoint}\r\nend\r\nVoronoiPoint(x::T, y::T) where T <: Real = VoronoiPoint(x, y, VoronoiPoint[])\r\n\r\nshow(io::IO, p::VoronoiPoint) = print(io, \"(\", p.x, \",\", p.y, \")\")\r\n\r\n\"\"\"\r\n    pos(p::VoronoiPoint)\r\n\r\nReturn the `x` and `y` coordinates of the `VoronoiPoint` `p` as a `Vector`.\r\n\r\n# Example\r\n```julia-repl\r\njulia> pos(VoronoiPoint(3,4))\r\n2-element Vector{Int64}:\r\n 3\r\n 4\r\n```\r\n\"\"\"\r\npos(p::VoronoiPoint) = [p.x, p.y]\r\n\r\n\"\"\"\r\n    perpbisector(p::VoronoiPoint, q::VoronoiPoint)\r\n\r\nReturn the midpoint of `VoronoiPoint`s `p` and `q`, and direction vector along the perpendicular bisector between of the same length as `p - q` and direction such that `p` is to the right and `q` is to the left.\r\n\r\n# Example\r\n```julia-repl\r\njulia> perpbisector(VoronoiPoint(0,1), VoronoiPoint(2,1))\r\n([1.0, 1.0], [0, -2])\r\n```\r\n\"\"\"\r\nfunction perpbisector(p::VoronoiPoint, q::VoronoiPoint)\r\n    return ( (pos(p) + pos(q))/2 , [[0,1] [-1,0]] * (pos(p) - pos(q)) )\r\nend\r\n\r\n\"\"\"\r\n    circumcentre(p::VoronoiPoint, q::VoronoiPoint, r::VoronoiPoint)\r\n\r\nReturn the circumcentre of the three `VoronoiPoint`s `p`, `q`, and `r`.\r\n\r\nIf they are collinear, return `[Inf, Inf]`.\r\n\r\n# Example\r\n```julia-repl\r\njulia> circumcentre(VoronoiPoint(0,0), VoronoiPoint(1,0), VoronoiPoint(0,1))\r\n2-element Vector{Float64}:\r\n 0.5\r\n 0.5\r\n```\r\n\"\"\"\r\nfunction circumcentre(p::VoronoiPoint, q::VoronoiPoint, r::VoronoiPoint)\r\n    (x₁, v₁) = perpbisector(p,q)\r\n    (x₂, v₂) = perpbisector(p,r)\r\n    det([v₁ v₂]) == 0 && return [Inf, Inf]\r\n    M = [v₁ v₂]^-1\r\n    t₁ = (M * (x₂ - x₁))[1]\r\n    return x₁ + t₁*v₁\r\nend\r\n\r\n\"\"\"\r\n    findnextpoint(p::VoronoiPoint, q::VoronoiPoint, z::Vector{T}, reversedirection::Bool) where T <: Real\r\n\r\nFind the `r` from `q.neighbours` where the circumcentre of `p`, `q`, and `r` is closest to `z` in the direction determined by `perpbisector`.\r\n\r\nIf `reversedirection == true`, find `r` based on the opposite direction.\r\n\r\n# Examples\r\n```julia-repl\r\njulia> p = VoronoiPoint(0,0)\r\n(0,0)\r\n\r\njulia> q = VoronoiPoint(0,1,[p, VoronoiPoint(3,4), VoronoiPoint(-3,4)])    \r\n(0,1)\r\n\r\njulia> findnextpoint(p, q, [0, 0.5], false)\r\n(3,4)\r\n\r\njulia> findnextpoint(p, q, [0, 0.5], true)\r\n(-3,4)\r\n```\r\n\"\"\"\r\nfunction findnextpoint(p::VoronoiPoint, q::VoronoiPoint, z::Vector{T}, reversedirection::Bool) where T <: Real\r\n    directionvector = perpbisector(p,q)[2] .* (-1)^reversedirection\r\n    \r\n    mindisplacement = Inf\r\n    nextpoint = VoronoiPoint(Inf,Inf)\r\n    for r ∈ q.neighbours\r\n        r ∈ [p,q] && continue\r\n        displacement = dot(directionvector, circumcentre(p,q,r) - z)\r\n        displacement > 0 && displacement < mindisplacement && (mindisplacement = displacement; nextpoint = r)\r\n    end\r\n    return nextpoint\r\nend\r\n\r\n\"\"\"\r\n    addpoint(x::Real, y::Real, allpoints::Vector{VoronoiPoint})\r\n\r\nAdd a new `VoronoiPoint` at coordinates `x` and `y`, including calculating all neighbours from `allpoints`.\r\n\r\nAlso, update neighbour lists of other points in `allpoints` to agree with the new addition.\r\n\r\n# Example\r\n```julia-repl\r\njulia> p = VoronoiPoint(1,1)\r\n(1,1)\r\n\r\njulia> q = VoronoiPoint(2,2)\r\n(2,2)\r\n\r\njulia> p.neighbours = [VoronoiPoint(Inf,Inf), q, VoronoiPoint(Inf,Inf)]\r\n3-element Vector{VoronoiPoint}:\r\n (Inf,Inf)\r\n (2,2)\r\n (Inf,Inf)\r\n\r\njulia> q.neighbours = [VoronoiPoint(Inf,Inf), p, VoronoiPoint(Inf,Inf)]\r\n3-element Vector{VoronoiPoint}:\r\n (Inf,Inf)\r\n (1,1)\r\n (Inf,Inf)\r\n\r\njulia> r = addpoint(1, 2, [p,q])\r\n(1,2)\r\n\r\njulia> p.neighbours\r\n4-element Vector{VoronoiPoint}:\r\n (Inf,Inf)\r\n (2,2)\r\n (1,2)\r\n (Inf,Inf)\r\n\r\njulia> q.neighbours\r\n4-element Vector{VoronoiPoint}:\r\n (Inf,Inf)\r\n (1,2)\r\n (1,1)\r\n (Inf,Inf)\r\n\r\njulia> r.neighbours\r\n4-element Vector{VoronoiPoint}:\r\n (Inf,Inf)\r\n (1,1)\r\n (2,2)\r\n (Inf,Inf)\r\n```\r\n\"\"\"\r\nfunction addpoint(x::Real, y::Real, allpoints::Vector{VoronoiPoint})\r\n    p = VoronoiPoint(x, y)\r\n    nearestpoint = allpoints[findmin([hypot(x-q.x, y-q.y) for q ∈ allpoints])[2]]\r\n    \r\n    z = perpbisector(p, nearestpoint)[1]\r\n    q = nearestpoint\r\n    reversedirection = false\r\n    while true\r\n        push!(p.neighbours, q)\r\n        r = findnextpoint(p, q, z, reversedirection)\r\n\r\n        # Edge goes to infinity\r\n        if pos(r) == [Inf,Inf]\r\n            push!(p.neighbours, r)\r\n            if reversedirection\r\n                break\r\n            else\r\n                reversedirection = true\r\n                q = nearestpoint\r\n                z = perpbisector(p, nearestpoint)[1]\r\n                pop!(reverse!(p.neighbours))\r\n                continue\r\n            end\r\n\r\n        # Back to start\r\n        elseif pos(r) == pos(nearestpoint)\r\n            reverse!(p.neighbours)\r\n            break\r\n\r\n        else\r\n            z = circumcentre(p,q,r) \r\n            q = r\r\n        end\r\n    end\r\n\r\n    n = length(p.neighbours)\r\n    for i ∈ 1:n\r\n        q = p.neighbours[i]\r\n        pos(q) == [Inf, Inf] && continue\r\n        j = findlast(r -> pos(r) == pos(p.neighbours[mod(i-1,1:n)]), q.neighbours)\r\n        k = findfirst(r -> pos(r) == pos(p.neighbours[mod(i+1,1:n)]), q.neighbours)\r\n        if j < k\r\n            q.neighbours = vcat(q.neighbours[j:k], p)\r\n        else\r\n            q.neighbours = vcat(q.neighbours[1:k], p, q.neighbours[j:end])\r\n        end\r\n    end\r\n\r\n    return p\r\nend\r\n\r\n\"\"\"\r\n    voronoipoints(xs::Vector{T}, ys::Vector{T}) where T <: Real\r\n\r\nCalculate the lists of neighbouring regions of a Voronoi diagram with points at coordinates given by `xs` and `ys`.\r\n\r\nReturn a list of `VoronoiPoint`s containing this information, with `Rational` parameters.\r\n\r\n# Example\r\n```julia-repl\r\nvoronoipoints([1,2,3],[2,1,3])\r\njulia> points = voronoipoints([1,2,3],[2,1,3])\r\n3-element Vector{VoronoiPoint}:\r\n (1//1,2//1)\r\n (2//1,1//1)\r\n (3//1,3//1)\r\n\r\njulia> points[1].neighbours\r\n4-element Vector{VoronoiPoint}:\r\n (Inf,Inf)\r\n (2//1,1//1)\r\n (3//1,3//1)\r\n (Inf,Inf)\r\n\r\njulia> points[2].neighbours\r\n4-element Vector{VoronoiPoint}:\r\n (Inf,Inf)\r\n (3//1,3//1)\r\n (1//1,2//1)\r\n (Inf,Inf)\r\n\r\njulia> points[3].neighbours\r\n4-element Vector{VoronoiPoint}:\r\n (Inf,Inf)\r\n (1//1,2//1)\r\n (2//1,1//1)\r\n (Inf,Inf)\r\n```\r\n\"\"\"\r\nfunction voronoipoints(xs::Vector{T}, ys::Vector{T}) where T <: Real\r\n    # Rational numbers!\r\n    xs, ys = Rational{BigInt}.(xs), Rational{BigInt}.(ys)\r\n    points = [VoronoiPoint(xs[1],ys[1],[VoronoiPoint(Inf,Inf)])]\r\n    for i ∈ 2:length(xs)\r\n        push!(points,addpoint(xs[i],ys[i],points))\r\n    end\r\n    return points\r\nend\r\n\r\n\"\"\"\r\n    voronoi(xs::Vector{T}, ys::Vector{T}; [names::Vector{String}]) where T <: Real\r\n\r\nDraw a Voronoi diagram from points at coordinates `xs` and `ys` in the region (x,y) ∈ [0,1000]².\r\n\r\nPoints given `names` in a legend if specified.\r\n\r\n# Example\r\n```julia-repl\r\njulia> voronoi(rand(1:1000, 10), rand(1:1000, 10))\r\n```\r\n\"\"\"\r\nfunction voronoi(xs::Vector{T}, ys::Vector{T}; names::Vector{String} = String[]) where T <: Real\r\n    points = voronoipoints(xs,ys)\r\n    m = length(xs)\r\n    colours = distinguishable_colors(m, lchoices = 50:5:100)\r\n    usingnames = !isempty(names)\r\n\r\n    polygons = Shape[]\r\n    for p ∈ points\r\n        n = length(p.neighbours)\r\n        vertices = Tuple{Rational{Int64}, Rational{Int64}}[]\r\n\r\n        if pos(p.neighbours[1]) == [Inf,Inf]\r\n            startindex, endindex = 2, n-2\r\n\r\n            x₁, v₁ = perpbisector(p.neighbours[n-1],p)\r\n            x₁, v₁ = Rational{Int64}.(x₁), Rational{Int64}.(v₁)\r\n            # Values of t₁ where the line x₁ + t₁v₁ intersects the borders\r\n            t₁vals = [-x₁[2]/v₁[2], (1000-x₁[1])/v₁[1], (1000-x₁[2])/v₁[2], -x₁[1]/v₁[1]]\r\n            t₁ = minimum(t₁vals[t₁vals .> 0])\r\n            push!(vertices,Tuple(x₁ + t₁*v₁))\r\n\r\n            x₂, v₂ = perpbisector(p,p.neighbours[2])\r\n            x₂, v₂ = Rational{Int64}.(x₂), Rational{Int64}.(v₂)\r\n            t₂vals = [-x₂[2]/v₂[2], (1000-x₂[1])/v₂[1], (1000-x₂[2])/v₂[2], -x₂[1]/v₂[1]]\r\n            t₂ = minimum(t₂vals[t₂vals .> 0])\r\n\r\n            t₁index = findfirst(==(t₁),t₁vals)\r\n            t₂index = findfirst(==(t₂),t₂vals)\r\n            indexdifference = mod(t₂index - t₁index,4)\r\n            corners = [(0,0), (1000,0), (1000,1000), (0,1000)]\r\n            for j ∈ 1:indexdifference\r\n                push!(vertices,corners[mod(t₁index+j, 1:4)])\r\n            end\r\n\r\n            push!(vertices,Tuple(x₂ + t₂*v₂))\r\n\r\n        else\r\n            startindex, endindex = 1, n\r\n        end\r\n\r\n        for j ∈ startindex:endindex\r\n            q,r = p.neighbours[j], p.neighbours[mod(j+1,1:n)]\r\n            push!(vertices,Tuple(circumcentre(p,q,r)))\r\n        end\r\n\r\n        push!(polygons, Shape(vertices))\r\n    end\r\n\r\n    diagram = plot(\r\n        polygons,\r\n        c = colours',\r\n        label = (usingnames ? hcat(names...) : false),\r\n        showaxis = false,\r\n        ticks = false,\r\n        size = (1000, 1000),\r\n        xlims = (0, 1000),\r\n        ylims = (0, 1000)\r\n    )\r\n    return scatter!(diagram, xs, ys, c = :black, markersize = 2, label = false)\r\nend\r\n\r\n\"\"\"\r\n    voronoidistribution(points::Vector{VoronoiPoint})\r\n\r\nCount the number of edges of each of the polygons from a Voronoi diagram, as represented by `points`.\r\n\r\n`points` should usually be the output of the function `voronoipoints`.\r\n\r\nDisplay the counts in a bar chart.\r\n\r\n# Example\r\n```julia-repl\r\nvoronoidistribution(voronoipoints(rand(1:1000, 10), rand(1:1000, 10)))\r\n```\r\n\"\"\"\r\nfunction voronoidistribution(points::Vector{VoronoiPoint})\r\n    neighbourcount = broadcast(p -> pos(p.neighbours[1]) == [Inf, Inf] ? 0 : length(p.neighbours), points)\r\n\r\n    m = maximum(neighbourcount)\r\n    total = count(!=(0), neighbourcount)\r\n    return bar(\r\n        1:m,\r\n        [count(==(i), neighbourcount)//total for i ∈ 1:m],\r\n        legend = false,\r\n        xticks = 1:m,\r\n        yticks = 0:0.1:1\r\n    )\r\nend\r\n\r\n\"\"\"\r\n    randomlattice(shape::Symbol, n::Int64, σ::Rational{Int64})\r\n\r\nCreate a lattice of `n^2` points, with each perturbed randomly both vertically and horizontally by a normal distribution of standard deviation `σ`.\r\n\r\nIf `shape == :square`, the lattice is a square lattice.\r\n\r\nIf `shape == :hexagonal`, the lattice is an approximately equilateral hexagonal lattice.\r\n\r\nReturn a bar chart of the distribution of edges of the polygons in the Voronoi diagram generated by these points.\r\n\r\n# Examples\r\n```julia-repl\r\njulia> randomlattice(:square, 10, 1)\r\n\r\njulia> randomlattice(:hexagonal, 20, 1//10)\r\n```\r\n\"\"\"\r\nfunction randomlattice(shape::Symbol, n::Int64, σ::Rational{Int64})\r\n\tif shape == :square\r\n\t\tcoords = [(x,y) for x ∈ 1:n, y ∈ 1:n]\r\n\telseif shape == :hexagonal\r\n\t\tcoords = hcat([(x,(6//7)*y) for x ∈ 1:n, y ∈ 1:2:n],\r\n\t\t\t[(x+1//2,(6//7)*y) for x ∈ 1:n, y ∈ 2:2:n])\r\n\telse\r\n\t\terror(\"Invalid shape\")\r\n\tend\r\n\t\r\n\txs,ys = [xy[1] for xy ∈ coords[:]], [xy[2] for xy ∈ coords[:]]\r\n\trandxs = xs .+ σ * round.(Int64, n * randn(n^2))//n\r\n\trandys = ys .+ σ * round.(Int64, n * randn(n^2))//n\r\n\treturn voronoidistribution(voronoipoints(randxs,randys))\r\nend", "meta": {"hexsha": "02826fea19ca8b2f747d0af68352a6b7a6b6727e", "size": 14278, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "casestudies/voronoi/voronoi.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "casestudies/voronoi/voronoi.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "casestudies/voronoi/voronoi.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 27.0929791271, "max_line_length": 212, "alphanum_fraction": 0.5843955736, "num_tokens": 4568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.8774767826757123, "lm_q1q2_score": 0.7984222700486081}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots, LaTeXStrings\n\tRandom.seed!(0)\nend;\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.03\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nfunction statPair(dist,n)\n    sample = rand(dist,n)\n    [mean(sample),var(sample)]\nend\n\n# ╔═╡ 1111d8c4-252c-11eb-3813-81de856f7fba\nbegin\n\tstdUni = Uniform(-sqrt(3),sqrt(3))\n\tn, N = 3, 10^4\n\n\tdataUni     = [statPair(stdUni,n) for _ in 1:N]\n\tdataUniInd  = [[mean(rand(stdUni,n)),var(rand(stdUni,n))] for _ in 1:N]\n\tdataNorm    = [statPair(Normal(),n) for _ in 1:N]\n\tdataNormInd = [[mean(rand(Normal(),n)),var(rand(Normal(),n))] for _ in 1:N]\nend;\n\n# ╔═╡ 11120d28-252c-11eb-1c1e-0dba64d8ae5c\nbegin\n\tp1 = scatter(first.(dataUni), last.(dataUni), \n\t\tc=:blue, ms=1, msw=0, label=\"Same group\")\n\tp1 = scatter!(first.(dataUniInd), last.(dataUniInd), \n\t\tc=:red, ms=0.8, msw=0, label=\"Separate group\", \n\t\txlabel=L\"\\overline{X}\", ylabel=L\"S^2\")\n\n\tp2 = scatter(first.(dataNorm), last.(dataNorm), \n\t\tc=:blue, ms=1, msw=0, label=\"Same group\")\n\tp2 = scatter!(first.(dataNormInd), last.(dataNormInd),\n\t\tc=:red, ms=0.8, msw=0, label=\"Separate group\", \n\t\txlabel=L\"\\overline{X}\", ylabel=L\"$S^2$\")\n\n\tplot(p1, p2, ylims=(0,5), size=(800, 400))\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.03\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═1111d8c4-252c-11eb-3813-81de856f7fba\n# ╠═11120d28-252c-11eb-1c1e-0dba64d8ae5c\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "9b83fee1c6acbff60764b61651a9b0646f0717ee", "size": 1825, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/listing5.03.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/05/listing5.03.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/05/listing5.03.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 28.0769230769, "max_line_length": 76, "alphanum_fraction": 0.6871232877, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.7982888454305272}}
{"text": "#=\n   Lotto Problem\n\n   From some unknown source (but I quoted it here: http://www.hakank.org/sims/simulering.html)\n   \"\"\"\n   One day I was asked \n\n   What is the probability that no two numbers are consecutive in\n   a lottery draw?\n\n   Information:\n\n   National Lottery in UK is to draw 6 different numbers from 1 to 49.\n   so, for example,\n\n    (a)   1  4  7   12  19  44    - no consecutive numbers\n    (b)   3  6  17  18  44  46    - 17 and 18 are consecutive \n    (c)   1  2  3   17  29  49    - 1, 2 and 3 are consecutive\n\n   We are asking the probability that class (a) occurs. Hope this is clear.\n\n   Observation shows that it is NOT a small number (actually near half-and-half).\n   ......\n\n   A Monte Carlo simulation experiment produced 50,558 sets of six numbers \n   between 1 and 49 with none consecutive out of 100,000 trials giving an \n   estimated probability of .50558.\n   \"\"\"\n\n   Summary Statistics\n   parameters      mean       std   naive_se      mcse          ess      rhat   ess_per_sec \n      Symbol   Float64   Float64    Float64   Float64      Float64   Float64       Float64 \n\n        prob    0.5054    0.5000     0.0025    0.0034   22057.4684    1.0000     1884.6094\n\n  \n\n=#\nusing Turing, StatsPlots, Distributions\ninclude(\"jl_utils.jl\")\n\n@model function lotto_not_two_consecutive_numbers(n=49,m=6)\n    \n    lotto ~ filldist(DiscreteUniform(1,n),m) \n    # Ensure unicity\n    true ~ Dirac(sum([lotto[i] == lotto[j] for i in 1:m for j in i+1:m]) == 0)\n    # Are there any consecutive numbers?\n    prob ~ Dirac(sum([ abs(lotto[i]-lotto[j]) == 1 for i in 1:m for j in i+1:m]) == 0)\nend\n\nn = 49\nm = 6\nmodel = lotto_not_two_consecutive_numbers(n,m)\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(5), 40_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 10_000)\n\ndisplay(chns[[:prob]])\n# display(plot(chns))\n", "meta": {"hexsha": "9925cb78e3173ecddbcc871c34c349fab5536edb", "size": 1904, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/lotto_not_two_consecutive_numbers.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/lotto_not_two_consecutive_numbers.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/lotto_not_two_consecutive_numbers.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 30.2222222222, "max_line_length": 94, "alphanum_fraction": 0.6397058824, "num_tokens": 615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.8824278571786139, "lm_q1q2_score": 0.7982888241107814}}
{"text": "\"\"\"\n    householderqr(R1, R2) computes the QR decompsition of\n    (m+l)-by-l block matrix [R1;R2]\n\n```math\n          l               l\n    m  (  R1  )  =  m  (  Q1  ) * R\n    l  (  R2  )     l  (  Q2  )\n```\n\n- Q1 is m-by-l orthogonal matrix,\n- Q2 is l-by-l orthogonal matrix,\n- R is l-by-l upper triangular matrix.\n\n# arguments:\nR1: m-by-l matrix,\nR2: m-by-l matrix.\n\n# returns:\nQ1: m-by-l matrix,\nQ2: l-by-l matrix,\nR: l-by-l matrix.\n\"\"\"\nfunction householderqr(R1, R2)\n    r, c = size(R1)\n    F = qr!([R1;R2])\n    Q = Matrix(F.Q)\n    Q1 = Q[1:r,:]\n    Q2 = Q[r+1:end,:]\n    return Q1, Q2, F.R\nend\n", "meta": {"hexsha": "a35b563a931c94016dd2f7400814da4e27f1cd8b", "size": 598, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/householderqr.jl", "max_stars_repo_name": "jiiwang/GeneralizedSVD.jl", "max_stars_repo_head_hexsha": "ce7d429271b51c505824b68edeae7565cf3537c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-02T23:15:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T23:15:06.000Z", "max_issues_repo_path": "src/householderqr.jl", "max_issues_repo_name": "jiiwang/GeneralizedSVD.jl", "max_issues_repo_head_hexsha": "ce7d429271b51c505824b68edeae7565cf3537c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-31T07:30:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-31T07:30:37.000Z", "max_forks_repo_path": "src/householderqr.jl", "max_forks_repo_name": "jiiwang/GeneralizedSVD.jl", "max_forks_repo_head_hexsha": "ce7d429271b51c505824b68edeae7565cf3537c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6875, "max_line_length": 57, "alphanum_fraction": 0.5200668896, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889437, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7982518654306598}}
{"text": "\"\"\"\nsigmoid activation function\n\"\"\"\nsigmoid(z::Number) = 1 / (1 + e^(-z))\nsigmoid{T<:Number}(arr::Array{T}) = map(sigmoid, arr)\n\npartial_sigmoid(z::Number) = z * (1 - z)\n\n\"\"\"\ntanh activation function\n\"\"\"\ntanh = Base.tanh\n\npartial_tanh(z::Number) = 2 / (e^z + e^-z)\n\n\"\"\"\nReLU activation function\n\"\"\"\nrelu(x::Real) = max(0, x)\nrelu{T<:Real}(arr::Array{T}) = map(relu, arr)\n\n\n", "meta": {"hexsha": "6ff6ecfd270e38e6d945a5e449f7e6a6e8e93025", "size": 373, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "neural_networks/activation.jl", "max_stars_repo_name": "zxteloiv/julia-ex", "max_stars_repo_head_hexsha": "f403ec99aff5a3cd0d0a0f38cc036b6da2d87648", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-04-12T09:06:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-07T10:13:19.000Z", "max_issues_repo_path": "neural_networks/activation.jl", "max_issues_repo_name": "zxteloiv/julia-ex", "max_issues_repo_head_hexsha": "f403ec99aff5a3cd0d0a0f38cc036b6da2d87648", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neural_networks/activation.jl", "max_forks_repo_name": "zxteloiv/julia-ex", "max_forks_repo_head_hexsha": "f403ec99aff5a3cd0d0a0f38cc036b6da2d87648", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.2173913043, "max_line_length": 53, "alphanum_fraction": 0.6058981233, "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813394, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7982518584417916}}
{"text": "using Distributions, Plots; pyplot()\n\nmu, sig = 2, 3\neta = sqrt(3)*sig/pi\nn, N = 15, 10^7\ndNormal   = Normal(mu, sig)\ndLogistic = Logistic(mu, eta)\nxGrid = -8:0.1:12\n\nsNormal   = [var(rand(dNormal,n)) for _ in 1:N]\nsLogistic = [var(rand(dLogistic,n)) for _ in 1:N]\n\np1 = plot(xGrid, pdf.(dNormal,xGrid), c=:blue, label=\"Normal\")\np1 = plot!(xGrid, pdf.(dLogistic,xGrid), c=:red, label=\"Logistic\", \n\txlabel=\"x\",ylabel=\"Density\", xlims= (-8,12), ylims=(0,0.16))\n\np2 = stephist(sNormal, bins=200, c=:blue, normed=true, label=\"Normal\")\np2 = stephist!(sLogistic, bins=200, c=:red, normed=true, label=\"Logistic\", \n\txlabel=\"Sample Variance\", ylabel=\"Density\", xlims=(0,30), ylims=(0,0.14))\n\nplot(p1, p2, size=(800, 400))", "meta": {"hexsha": "6fa93e12a237cbcbf8727339dce13025651c7f16", "size": 712, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "6_chapter/sampleVarDists.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "6_chapter/sampleVarDists.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "6_chapter/sampleVarDists.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 33.9047619048, "max_line_length": 75, "alphanum_fraction": 0.6530898876, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874228, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7982518545164836}}
{"text": "# method of moments estimators for a sample from Chi^2(theta)\n# increase n to observe consistency\n# note that the two estimators are different from one another\nusing Distributions\nn = 30\ntheta = 3\n\n# the distribution doesn't matter, what matters is\n# that the moments are correctly specified\n#y = rand(Chisq(theta), n)\ny = rand(Normal(theta, sqrt(2*theta)), n)\n\n# a MM estimator\nthetahat = mean(y)\nprintln(\"mm estimator based on mean: \", thetahat)\n\n# a second MM estimator\nthetahat = 0.5*var(y)\nprintln(\"mm estimator based on variance: \", thetahat)\n", "meta": {"hexsha": "f0a9732becb03ca196fadcd6703ad1e63ef117c6", "size": 549, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/GMM/chi2mm.jl", "max_stars_repo_name": "Hiroakiyusheng/Econometrics", "max_stars_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "Examples/GMM/chi2mm.jl", "max_issues_repo_name": "Hiroakiyusheng/Econometrics", "max_issues_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "Examples/GMM/chi2mm.jl", "max_forks_repo_name": "Hiroakiyusheng/Econometrics", "max_forks_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 27.45, "max_line_length": 61, "alphanum_fraction": 0.7413479053, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611643025387, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7981975111683628}}
{"text": "using MDP\n\n# This example describes a Markov decision process where\n#\n# S = {1, 2}\n# A = {1, 2}\n\n# r = S x A matrix\n\nr = [ 5  10\n     -1  -Inf ]\n\n\n# Transition matrix\n# P(1) = [0.5, 0.5; 0.0, 1.0]\n# P(2) = [0.0, 1.0; 0.5, 0.5]\nP = Matrix[ [ 0.5  0.5 \n              0.0  1.0 ],\n            [ 0.0  1.0\n              0.5  0.5 ] ]\n\n# Construct the MDP model\nmodel = ProbModel(r, P; objective=:Max)\n\n# Compute the optimal solution\n(v,g) = valueIteration(model; discount=0.95, tolerance=1e-4)\n\nprintln(g) # [1, 1]\nprintln(v) # [-8.571401228528563,-19.999971289954992]\n\n# For this model, the optimal solution is:\n\n# g = [1, 1]\n# w[1] = (5 - 5.5 β) / (1 -0.5 β)(1 - β)\n# w[2] = -1/(1-β)\n\n# which equals\n# \n# w = [ -8.57142857142855, -19.999999999999982]\n\n# As expected, v is within 1e-4 of w (in sup-norm). \n\n", "meta": {"hexsha": "9b827285d779579c5e2e9fc2e3b703d8eeaf6283", "size": 801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/puterman-3.1.jl", "max_stars_repo_name": "adityam/MDP.jl", "max_stars_repo_head_hexsha": "456e5d071a3c5e749620f477b158a3c957093536", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-07-19T01:39:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T01:45:55.000Z", "max_issues_repo_path": "examples/puterman-3.1.jl", "max_issues_repo_name": "adityam/MDP.jl", "max_issues_repo_head_hexsha": "456e5d071a3c5e749620f477b158a3c957093536", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/puterman-3.1.jl", "max_forks_repo_name": "adityam/MDP.jl", "max_forks_repo_head_hexsha": "456e5d071a3c5e749620f477b158a3c957093536", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-07-19T01:39:37.000Z", "max_forks_repo_forks_event_max_datetime": "2017-10-10T10:40:59.000Z", "avg_line_length": 18.6279069767, "max_line_length": 60, "alphanum_fraction": 0.5443196005, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611574955211, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7981974974771721}}
{"text": "function main()\n    A, B, C = parse.(Float64, split(readline()))\n    g(t; A=A, B=B, C=C) = A * t + B * sin(C * t * π) - 100\n    t̲, t̄ = 0, (B + 100) / A\n    ε = 1e-6\n\n    t = (t̄ + t̲) / 2\n    while abs(g(t)) > ε\n        if g(t) > 0\n            t̄ = t\n        else\n            t̲ = t\n        end\n        t = (t̄ + t̲) / 2\n    end\n\n    println(t)\n    println()\nend\n\nmain()", "meta": {"hexsha": "53dd3917919ea025af48c937377ddac8b31c937c", "size": 372, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/chapter06/nicetak/abc026_d.jl", "max_stars_repo_name": "tokuma09/algorithm_problems", "max_stars_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-07T15:46:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T15:46:58.000Z", "max_issues_repo_path": "problems/chapter06/nicetak/abc026_d.jl", "max_issues_repo_name": "tokuma09/algorithm_problems", "max_issues_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-06-05T14:16:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-10T07:08:28.000Z", "max_forks_repo_path": "problems/chapter06/nicetak/abc026_d.jl", "max_forks_repo_name": "tokuma09/algorithm_problems", "max_forks_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7142857143, "max_line_length": 58, "alphanum_fraction": 0.3548387097, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96036116089903, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7981974942807857}}
{"text": "# Computes the SVD of a 2-by-2 matrix M, returning U, S, and V such that A == U*S*V'.\n# Reference:\n# Blinn, J. (1996). Consider the lowly 2 x 2 matrix. IEEE Computer Graphics and Applications, 16(2), 82-88.\n# https://scicomp.stackexchange.com/questions/8899/robust-algorithm-for-2-times-2-svd\nfunction svd2x2(M::AbstractArray)\n    E = (M[1,1] + M[2,2]) / 2\n    F = (M[1,1] - M[2,2]) / 2\n    G = (M[2,1] + M[1,2]) / 2\n    H = (M[2,1] - M[1,2]) / 2\n    Q = sqrt(E^2 +H^2)\n    R = sqrt(F^2 + G^2)\n    sx = Q + R\n    sy = Q - R\n    a₁ = atan2(G,F)\n    a₂ = atan2(H,E)\n    θ = (a₂ - a₁) / 2\n    ϕ = (a₂ + a₁) / 2\n    s = sign(sy)\n    U = SMatrix{2,2,Float64}(cos(ϕ), sin(ϕ), -s*sin(ϕ), s*cos(ϕ))\n    S = SMatrix{2,2,Float64}(sx, 0.0, 0.0, abs(sy))\n    V = SMatrix{2,2,Float64}(cos(θ), -sin(θ), sin(θ), cos(θ))\n    U,S,V\nend\n\n#  Computes the Moore-Penrose pseudoinverse for a 2-by-2 matrix M by only inverting\n#  singular values above the threshold `tol = sqrt(eps(real(float(one(eltype(M))))))`\nfunction pinv2x2(M::AbstractArray)\n     tol = sqrt(eps(real(float(one(eltype(M))))))\n     U,S,V = svd2x2(M)\n     D = SMatrix{2,2,Float64}( S[1,1] > tol ?  1/S[1,1] : 0.0 , 0.0, 0.0, S[2,2] > tol ?  1/S[2,2] : 0.0 )\n     U*D*V'\nend\n", "meta": {"hexsha": "b3f47dc4649a26a5985eb0509a4bd7a8695bb341", "size": 1221, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/core.jl", "max_stars_repo_name": "zygmuntszpak/ImageTracking.jl", "max_stars_repo_head_hexsha": "caefd088b9b5b92739e1bcb9696904f0d2fd31c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core.jl", "max_issues_repo_name": "zygmuntszpak/ImageTracking.jl", "max_issues_repo_head_hexsha": "caefd088b9b5b92739e1bcb9696904f0d2fd31c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core.jl", "max_forks_repo_name": "zygmuntszpak/ImageTracking.jl", "max_forks_repo_head_hexsha": "caefd088b9b5b92739e1bcb9696904f0d2fd31c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0, "max_line_length": 107, "alphanum_fraction": 0.5569205569, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545377452442, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7981808036693069}}
{"text": "\"\"\"\nSolve system of linear equations: L*x = b, where L is Laplacian matrix\n\"\"\"\nfunction linsolve_cg_v2!( LF::LF3dGrid, x::Array{Float64,1}, b::Array{Float64,1};\n                          NiterMax=1000, verbose=false, TOL=5.e-10 )\n  #\n  Npoints = size(x)[1]\n  #\n  L_x = apply_Laplacian( LF, x )\n  #\n  r = b[:] - L_x[:]\n  z = r[:]\n  p = z[:]\n\n  r_old = r[:]\n  z_old = z[:]\n  p_old = p[:]\n  for iter = 1 : NiterMax\n    #\n    L_x = apply_Laplacian( LF, p )\n    #\n    α = dot( r, z ) / dot( p, L_x )\n    #\n    x[:] = x[:] + α * p[:]  # FIXME use x[:] to force x to be copied, not referenced\n    r[:] = r[:] - α * L_x[:]\n    #\n    norm_res = sqrt( dot( r, r ) )\n    if verbose\n      @printf(\"%8d %20.10f\\n\", iter, norm_res)\n    end\n    #\n    if norm_res < TOL\n      if verbose\n        @printf(\"#CONV in linsolve_cg_v2: iter, norm_res: %8d %10.5e\\n\", iter, norm_res)\n      end\n      break\n    end\n    #\n    z = r[:]  #XXX call appropriate preconditioner here\n    # Polak-Ribiere\n    β = dot( z, r - r_old ) / dot( z_old, r_old )\n    p = z[:] + β * p_old[:]\n    #\n    z_old = z[:]\n    r_old = r[:]\n    p_old = p[:]\n  end\n  #\n  return\n  #\nend # of function\n", "meta": {"hexsha": "e20c1dfbcf7817eabfb34b4b17a37ca625ececcc", "size": 1148, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LF/poisson_3d_p/linsolve_cg_v2.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "LF/poisson_3d_p/linsolve_cg_v2.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LF/poisson_3d_p/linsolve_cg_v2.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 22.0769230769, "max_line_length": 88, "alphanum_fraction": 0.4991289199, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191246389618, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7981533993592567}}
{"text": "\"\"\"\n    Ormsby(; <keyword arguments>)\n\nCreate a Ormsby wavelet sampled every dt seconds with corner frequencies\ndefined by the vector f = [f1, f2, f3, f4]. The final wavelet is multiplied by\na Hamming window.\n\n# Arguments\n- `dt::AbstractFloat=0.002`: sampling interval in secs.\n- `f::Vector{AbstractFloat}=[2.0, 10.0, 40.0, 60.0]`: corner frequencies in Hz.\n      ^\n    1 |     ***************\n      |    *               *\n      |   *                 *\n      |  *                   *\n      | *                     *\n      -----------------------------> f\n        f1  f2           f3  f4\n# Example\n```julia\njulia> w = Ormsby(); plot(w);\n```\n\"\"\"\nfunction Ormsby(; dt::Tf=0.002, f::Vector{Tf}=[2.0, 10.0, 40.0, 60.0]) where {Tf<:AbstractFloat}\n\n    f1,f2,f3,f4 = f\n\n    fc = (f2+f3)/2.0\n    nw = 2.2/(fc*dt)\n    nc = floor(Int, nw/2)\n    t = dt*collect(-nc:1:nc)\n    nw = 2*nc + 1\n    a4 = (pi*f4)^2/(pi*(f4-f3))\n    a3 = (pi*f3)^2/(pi*(f4-f3))\n    a2 = (pi*f2)^2/(pi*(f2-f1))\n    a1 = (pi*f1)^2/(pi*(f2-f1))\n\n    u = [ a4 * (sinc(f4 * t[i] ))^2 - a3 * (sinc(f3 * t[i] ))^2 for i in eachindex(t) ]\n    v = [ a2 * (sinc(f2 * t[i] ))^2 - a1 * (sinc(f1 * t[i] ))^2 for i in eachindex(t) ]\n\n    w  = u - v\n    Hm = Hamming(nw) \n    w  = [w[i] * Hm[i] for i in eachindex(w)]\n    w  = w/maximum(w)\n\nend\n", "meta": {"hexsha": "a2ae3c4af4cf11bd09d44bea3dfca08ca050ab97", "size": 1294, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Modelling/Wavelets/Ormsby.jl", "max_stars_repo_name": "fercarozzi/SeisProcessing.jl", "max_stars_repo_head_hexsha": "cf91516e0c45b4aba60bbb331eee1a0cb7acc896", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Modelling/Wavelets/Ormsby.jl", "max_issues_repo_name": "fercarozzi/SeisProcessing.jl", "max_issues_repo_head_hexsha": "cf91516e0c45b4aba60bbb331eee1a0cb7acc896", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-11-30T00:13:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T17:08:48.000Z", "max_forks_repo_path": "src/Modelling/Wavelets/Ormsby.jl", "max_forks_repo_name": "fercarozzi/SeisProcessing.jl", "max_forks_repo_head_hexsha": "cf91516e0c45b4aba60bbb331eee1a0cb7acc896", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5319148936, "max_line_length": 96, "alphanum_fraction": 0.4598145286, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478306, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7981440359612927}}
{"text": "using Plots\n\nfunction bracket_minimum(f, x=0; s=1e-2, k=2.0)\n    a, ya = x, f(x)\n    b, yb = a + s, f(a + s)\n    if yb > ya\n        a, b = b, a\n        ya, yb = yb, ya\n        s = -s\n    end\n    while true\n        c, yc = b + s, f(b + s)\n        if yc > yb\n            return a < c ? (a, c) : (c, a)\n        end\n        a, ya, b, yb = b, yb, c, yc\n        s *= k\n    end\nend\n\n\nφ = MathConstants.φ\nfunction golden_section_search(f, a, b, n)\n    ρ = φ-1\n    d = ρ * b + (1 - ρ)*a\n    yd = f(d)\n    for i = 1 : n-1\n        c = ρ*a + (1 - ρ)*b\n        yc = f(c)\n        if yc < yd\n            b, d, yd = d, c, yc\n        else\n            a, b = b, c\n        end\n    end\n    return a < b ? (a, b) : (b, a)\nend\n    \n#definicao da funcao\nf = x-> -(0.4/((x^2+1))^(1/2))+((x^2+1)^(1/2))*(1-0.4/(x^2+1))-x    #multiplicada por -1 para encontrar o minimo\ng = x-> -(-(0.4/((x^2+1))^(1/2))+((x^2+1)^(1/2))*(1-0.4/(x^2+1))-x) #funcao original\n\n#ponto inicial\ninitial_point = 0\n#busca do intervalo\na,c = bracket_minimum(f,initial_point)\n\n#numero de iteracoes\nn=(c-a)/(10^-3*log(φ))\n\nam,bm = golden_section_search(f,a,c,n)\n#(am,f(am))\n#am,bm\n\nprintln(\"x* = \", am)\n\nplot(g,a-1.,c+1.,lw=2,draw_arrow=\"true\",label=\"Function\")\nscatter!([a,c],[g(a),g(c)],label=\"interval\")\nscatter!([am,bm],[g(am),g(bm)],label=\"x*\")\n\n\n", "meta": {"hexsha": "3b429196f0d7a1afebea58b42244dedb6015938b", "size": 1297, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercicio01_golden_section.jl", "max_stars_repo_name": "GilbertoLucas/Structural_Optimization", "max_stars_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercicio01_golden_section.jl", "max_issues_repo_name": "GilbertoLucas/Structural_Optimization", "max_issues_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercicio01_golden_section.jl", "max_forks_repo_name": "GilbertoLucas/Structural_Optimization", "max_forks_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9193548387, "max_line_length": 112, "alphanum_fraction": 0.465690054, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939024825960626, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7981440335090692}}
{"text": "module DRAGO\n\nusing LinearAlgebra\nusing Plots\nusing Distributions\nusing BandedMatrices\n\ninclude(\"utility.jl\")\n\nexport drago, simulate_data, find_gaps, get_present \n\n\"\"\"\n    drago(y, λ1, λ2, S = I; ΔFmin = 0.01, maxiter = 10, verbose = false)\n\nNonlinear Smoothing of Data with Random Gaps and Outliers (DRAGO). A detailed description of the algorithm can be found in [1]\n\n[1] Parekh, A., et al. \"Nonlinear Smoothing of Core Body Temperature Data with Random Gaps and Outliers (DRAGO).\" Biomedical Signal Processing. Springer, Cham, 2021. 63-84.\n# Arguments\n\n* y:    Signal with gaps and outlier\n* λ1:   Influences the sparsity of the estimated outliers `x`. As a reasonable heuristic is λ1 = 3σ, where σ is the standard deviation of the noise. \n* λ2:   Influences the smoothness of the estimate `f`\n* S:    A matrix encoding gaps defaulting to `I` if none are present. Otherwise it can be created by starting with `I` and deleting all rows corresponding to a gap. \n\n# Keyword Arguments\n\n* ΔFmin:    The minimal change in the objective function F that defines convergence.\n* maxiter:  Maximum number of iterations\n* verbose:  Print some information\n\n# Returns\n\n* fRes:     The smoothed signal\n* xRes:     The estimated outliers\n* residual: The residual signal y - (f + x)     \n\"\"\"\nfunction drago(y, λ1, λ2, S = I(length(y)); ΔFmin = 0.01, maxiter = 10, verbose = false)\n    # Initialize\n    N = length(y)\n    xRes = S * y\n    present = [1:N;][diag(S' * S) .== 1]\n    Dn = Tridiagonal(ones(N-1), -2ones(N), ones(N-1))\n    Dn = Dn[2:end-1, 1:end] # make it N-2 x N\n    λ2DDn = λ2 .* Dn' * Dn\n    \n    # Objective function\n    F(f, x) = 0.5norm2(S * y .- S * f .- x)^2 + 0.5λ1 * norm1(x) + .5λ2 *  norm2(Dn * f)^2\n\n    # Iterate\n    iter = 1\n    fRes = similar(y)\n    Fold = ΔF = Inf\n    while ΔF > ΔFmin && iter <= maxiter\n        A = Diagonal(λ1 ./ (abs.(xRes) .+ λ1))\n        # B = Matrix(S' * A * S .+ λ2 .* Dn' * Dn) # faster for low N but more Memory gets allocated\n        B = BandedMatrix(S' * A * S .+ λ2DDn) # less Memory but apparently slower\n        fRes = inv(B) * S' * A * S * y\n        xRes = abs.(xRes) .* (S * (y .- fRes)) ./ (abs.(xRes) .+ λ1)\n        Fnow = F(fRes, xRes)\n        verbose && @info \"Iteration: $iter with F = $Fnow\"\n        ΔF = Fold .- Fnow\n        Fold = Fnow \n        iter += 1\n    end\n    residual = y .- (S' * xRes .+ fRes)\n\n    return fRes, xRes, residual    \nend\nend #module", "meta": {"hexsha": "3676308b5067778cd0b83adaf7b7d99fb860d0a0", "size": 2410, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DRAGO.jl", "max_stars_repo_name": "mapi1/DRAGO", "max_stars_repo_head_hexsha": "65a6545890432004dd425ea03878958fb7369ded", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DRAGO.jl", "max_issues_repo_name": "mapi1/DRAGO", "max_issues_repo_head_hexsha": "65a6545890432004dd425ea03878958fb7369ded", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DRAGO.jl", "max_forks_repo_name": "mapi1/DRAGO", "max_forks_repo_head_hexsha": "65a6545890432004dd425ea03878958fb7369ded", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9275362319, "max_line_length": 172, "alphanum_fraction": 0.6215767635, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248208414329, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7981440327265701}}
{"text": "module BigCombinatorics\n\nexport Fibonacci\nexport Factorial, DoubleFactorial, FallingFactorial, RisingFactorial, HyperFactorial\nexport Binomial, Catalan\nexport Derangements, MultiChoose, Multinomial\nexport Bell, Stirling1, Stirling2\nexport IntPartitions, IntPartitionsDistinct\nexport Euler, PowerSum, Menage\n\n\"\"\"\nThis is where we cache values already computed\n\"\"\"\n_master_table = Dict{Function,Dict}()\n\n\n\"\"\"\n    _save(f::Function, x, val::BigInt)\n\nSave the computed value of `f` with argument(s) `x` and value `val`.\n\"\"\"\nfunction _save(f::Function, x, val::BigInt)\n    d = _master_table[f]\n    d[x] = val\n    nothing\nend\n\n\n\"\"\"\n    _has(f::Function, x)\n\nCheck if argument `x` for function `f` is already in the `_master_table`.\n\"\"\"\nfunction _has(f::Function, x)::Bool\n    d = _master_table[f]\n    return haskey(d, x)\nend\n\n\"\"\"\n    _max_arg(f::Function)\n\nFind the largest argument known for `f`. Note that `f` must be a function\nof just a single value.\n\"\"\"\nfunction _max_arg(f::Function)\n    tab = _master_table[f]\n    return maximum(keys(tab))\nend\n\n\n\"\"\"\n    _get(f::Function, x)\n\nRetrieve the function value `f(x)` from the `_master_table`.\n\"\"\"\nfunction _get(f::Function, x)::BigInt\n    d = _master_table[f]\n    return d[x]\nend\n\n\n\"\"\"\n    _make(f::Function, T::Type)\n\nCreate an entry in the `_master_table` for the function `f`.\n\"\"\"\nfunction _make(f::Function, T::Type)\n    _master_table[f] = Dict{T,BigInt}()\n    nothing\nend\n\n\"\"\"\n`BigCombinatorics.cache_report()` reports how many\nentries are saved for each function in the `BigCombinatorics`\nmodule.\n\"\"\"\nfunction cache_report()\n    total = 0\n    for func in keys(_master_table)\n        parse_func = split(string(func), \".\")\n        func_name = last(parse_func)\n        sz = length(_master_table[func])\n        total += sz\n        println(\"$sz\\t$func_name\")\n    end\n    println()\n    println(\"$total\\tTotal entries\")\n    nothing\nend\n\n\n\n\n\"\"\"\n    BigCombinatorics.cache_clear()\n    \nClears all cached values.\n\"\"\"\nfunction cache_clear()\n    for f in keys(_master_table)\n        f()\n    end\n    nothing\nend\n\n\"\"\"\n`Fibonacci(n)` returns the `n`-th Fibonacci number.\nWe begin with `Fibonacci(0)==0` and `Fibonacci(1)==1`.\nSee https://oeis.org/A000045\n\"\"\"\nfunction Fibonacci(n::Integer)::BigInt\n    if n < 0\n        throw(DomainError(n, \"argument must be nonngative\"))\n    end\n\n    if _has(Fibonacci, n)\n        return _get(Fibonacci, n)\n    end\n\n    start = _max_arg(Fibonacci) + 1\n    for m = start:n\n        val = _get(Fibonacci, m - 1) + _get(Fibonacci, m - 2)\n        _save(Fibonacci, m, val)\n    end\n\n    return _get(Fibonacci, n)\nend\n\nfunction Fibonacci()\n    _make(Fibonacci, Integer)\n    _save(Fibonacci, 0, big(0))\n    _save(Fibonacci, 1, big(1))\nend\nFibonacci()\n\n\"\"\"\n`Factorial(n)` returns `n!` for nonnegative integers `n`.\nSee https://oeis.org/A000142 \n\n`Factorial(n,k)` returns `n!/k!` (to be consistent with Julia's\n`factorial`.) Requires `0 <= k <= n`.\n\nSee also `FallingFactorial` and `RisingFactorial`.\n\"\"\"\nfunction Factorial(n::Integer)::BigInt\n    if n < 0\n        throw(DomainError(n, \"argument must be nonngative\"))\n    end\n    return factorial(big(n))\nend\n\nfunction Factorial(n::Integer, k::Integer)::BigInt\n    if k > n\n        throw(DomainError((n, k), \"$k cannot exceed $n\"))\n    end\n    return div(Factorial(n), Factorial(k))\nend\n\n\"\"\"\n    FallingFactorial(n,k)\n\nreturns `n*(n-1)*(n-2)*...*(n-k+1)`\n(with a total of `k` factors). Requires `n,k >= 0`.\nIf `k>n` then `0` is returned.\n\"\"\"\nfunction FallingFactorial(n::Integer, k::Integer)::BigInt\n    if n < 0 || k < 0\n        throw(DomainError((n, k), \" arguments must be nonnegative\"))\n    end\n    if k > n\n        return big(0)\n    end\n    return Factorial(n, n - k)\nend\n\n\n\"\"\"\n    RisingFactorial(n,k)\n\nreturns `n*(n+1)*(n+2)*...*(n+k-1)`\n(with a total of `k` factors). Requires `n,k >= 0`.\n\"\"\"\nfunction RisingFactorial(n::Integer, k::Integer)::BigInt\n    if n < 0 || k < 0\n        throw(DomainError((n, k), \"arguments must be nonnegative\"))\n    end\n    if k == 0\n        return big(1)\n    end\n    if n == 0\n        return big(0)\n    end\n\n    return FallingFactorial(n + k - 1, k)\nend\n\n\n\"\"\"\n    DoubleFactorial(n)\n\nreturns `n!!`, i.e., `n*(n-2)*...` with `(-1)!! == 0!! == 1!! == 1`.\nSee https://oeis.org/A006882\n\"\"\"\nfunction DoubleFactorial(n::Integer)::BigInt\n    if n < -1\n        throw(DomainError(n, \"argument must be at least -1\"))\n    end\n    if _has(DoubleFactorial, n)\n        return _get(DoubleFactorial, n)\n    end\n\n    start = _max_arg(DoubleFactorial) + 1\n    for m = start:n\n        val = m * _get(DoubleFactorial, m - 2)\n        _save(DoubleFactorial, m, val)\n    end\n\n    return _get(DoubleFactorial, n)\nend\n\nfunction DoubleFactorial()\n    _make(DoubleFactorial, Integer)\n    _save(DoubleFactorial, -1, big(1))\n    _save(DoubleFactorial, 0, big(1))\n    _save(DoubleFactorial, 1, big(1))\nend\nDoubleFactorial()\n\n\n\"\"\"\n    HyperFactorial(n)\n\nreturns the hyperfactorial of `n`, that is \n`1^1 * 2^2 * 3^3 * ... * n^n`.\nSee https://oeis.org/A002109\n\"\"\"\nfunction HyperFactorial(n::Integer)::BigInt\n    if n < 0\n        throw(DomainError(n, \"arument must be nonnegative\"))\n    end\n\n    if _has(HyperFactorial, n)\n        return _get(HyperFactorial, n)\n    end\n    start = _max_arg(HyperFactorial) + 1\n    for m = start:n\n        val = (big(m))^m * _get(HyperFactorial, m - 1)\n        _save(HyperFactorial, m, val)\n    end\n    return _get(HyperFactorial, n)\nend\n\nfunction HyperFactorial()\n    _make(HyperFactorial, Integer)\n    _save(HyperFactorial, 0, big(1))\n    _save(HyperFactorial, 1, big(1))\nend\nHyperFactorial()\n\n\n\"\"\"\n    Binomial(n,k)\n\nreturns the binomial coefficient `n`-choose-`k`.\nThis is the number of `k`-element subsets of an `n`-element set.\nSee https://oeis.org/A007318\n\"\"\"\nBinomial(n::Integer, k::Integer) = binomial(big(n), big(k))::BigInt\n\n\n\"\"\"\n    Multinomial(vec)\n\nreturns the multinomial coefficient whose\ntop index is the sum of `vec` (an array of `Int`s) and whose\nbottom indices are given by `vec`.\n\nThis may also be called with a common-separated list of arguments,\nthat is, either of `Multinomial([1,2,3])` or `Multinomial(1,2,3)`.\nThe result is `60` in both cases as these equal `6!/(1! 2! 3!)`.\n\n**Warning**: This is not the same as `MultiChoose`.\n\"\"\"\nfunction Multinomial(v...)::BigInt\n    nv = length(v)\n    for i = 1:nv\n        typeof(v[i]) <: Integer || throw(DomainError(v, \"arguments must be integers\"))\n        v[i] >= 0 || throw(DomainError(v, \"arguments must be nonngative\"))\n    end\n    vals = [t for t in v]\n    return Multinomial(vals)\nend\n\nMultinomial() = big(1)::BigInt\n\nfunction Multinomial(vals::Vector{T})::BigInt where {T<:Integer}\n    if any([t < 0 for t in vals])\n        throw(DomainError(vals, \"arguments must be nonnegative\"))\n    end\n\n    nv = length(vals)\n    n = sum(vals)\n    # base cases\n    if nv <= 1 || n == 0\n        return big(1)\n    end\n    # reduce\n    return Binomial(n, vals[end]) * Multinomial(vals[1:nv-1])\nend\n\n\n\"\"\"\n    MultiChoose(n,k)\n\nreturns the number of `k`-element\n*multisets* that can be formed using the elements of an\n`n`-element set.\n\n**Warning**: This is not the same as `Multinomial`.\n\"\"\"\nfunction MultiChoose(n::Integer, k::Integer)::BigInt\n    return Binomial(n + k - 1, k)\nend\n\n\"\"\"\n    Catalan(n)\n\nreturns the `n`-th Catalan number. \nSee https://oeis.org/A000108\n\"\"\"\nfunction Catalan(n::Integer)::BigInt\n    n >= 0 || throw(DomainError(n, \"argument must be nonnegative\"))\n    return div(Binomial(2n, n), n + 1)\nend\n\n\n\"\"\"\n    Derangements(n)\n\nreturns the number of permutations of\nan `n`-set that have no fixed point.\nSee https://oeis.org/A000166\n\"\"\"\nfunction Derangements(n::Integer)::BigInt\n    if n < 0\n        throw(DomainError(n, \"argument must be nonnegative\"))\n    end\n    if _has(Derangements, n)\n        return _get(Derangements, n)\n    end\n\n    start = _max_arg(Derangements) + 1\n    for m = start:n\n        s = (m % 2 == 0) ? 1 : -1\n        val = m * _get(Derangements, m - 1) + s\n        _save(Derangements, m, val)\n    end\n    return _get(Derangements, n)\nend\n\n\nfunction Derangements()\n    _make(Derangements, Integer)\n    _save(Derangements, 0, big(1))\n    _save(Derangements, 1, big(0))\nend\nDerangements()\n\n\n\n\"\"\"\n    Bell(n)\n\ngives the `n`-th Bell number, that is,\nthe number of partitions of an `n`-element set.\nSee https://oeis.org/A000110\n\"\"\"\nfunction Bell(n::Integer)::BigInt\n    if n < 0\n        throw(DomainError(n, \"argument must be nonnegative\"))\n    end\n\n    if _has(Bell, n)\n        return _get(Bell, n)\n    end\n\n    start = _max_arg(Bell) + 1\n    for m = start:n\n        val = big(0)\n        for k = 0:m-1\n            val += Binomial(m - 1, k) * Bell(k)\n        end\n        _save(Bell, m, val)\n    end\n\n    return _get(Bell, n)\nend\n\nfunction Bell()\n    _make(Bell, Integer)\n    _save(Bell, 0, big(1))\n    _save(Bell, 1, big(1))\nend\nBell()\n\n\"\"\"\n    Stirling2(n,k)\n\ngives the Stirling number of the second kind,\nthat is, the number of paritions of an `n`-set into `k`-parts.\"\nSee https://oeis.org/A008277\n\"\"\"\nfunction Stirling2(n::Integer, k::Integer)::BigInt\n    # special cases\n    if k < 0 || n < 0\n        throw(DomainError((n, k), \"arguments must be nonnegative\"))\n    end\n\n    if k > n\n        return big(0)\n    end\n\n    if n == 0  # and by logic, k==0\n        return big(1)\n    end\n\n    if k == 0\n        return big(0)\n    end\n\n    if n == k\n        return big(1)\n    end\n    # END OF SPECIAL CASES, invoke recursion\n    if _has(Stirling2, (n, k))\n        return _get(Stirling2, (n, k))\n    end\n\n    val = Stirling2(n - 1, k - 1) + Stirling2(n - 1, k) * k\n    _save(Stirling2, (n, k), val)\n    return val\nend\nfunction Stirling2()\n    _make(Stirling2, Tuple{Integer,Integer})\nend\nStirling2()\n\n\n\"\"\"\n    Stirling1(n,k)\n\ngives the (signed) Stirling number\nof the first kind, that is, the coefficient of `x^k`\nin the poynomial `x(x-1)(x-2)...(x-n+1)`.\nSee https://oeis.org/A008275\n\"\"\"\nfunction Stirling1(n::Integer, k::Integer)::BigInt\n    # special cases\n    if k < 0 || n < 0\n        throw(DomainError((n, k), \"arguments must be nonnegative\"))\n    end\n\n    if k > n\n        return big(0)\n    end\n\n    if n == 0  # and, by logic, k==0\n        return big(1)\n    end\n\n    if k == 0  # and, by logic, n>0\n        return big(0)\n    end\n\n    if _has(Stirling1, (n, k))\n        return _get(Stirling1, (n, k))\n    end\n\n    # end of special cases, invoke recursion\n\n    val = Stirling1(n - 1, k - 1) - (n - 1) * Stirling1(n - 1, k)\n    _save(Stirling1, (n, k), val)\n    return val\nend\nfunction Stirling1()\n    _make(Stirling1, Tuple{Integer,Integer})\nend\nStirling1()\n\n\"\"\"\n`IntPartitions(n)` is the number of partitions of the integer `n`.\nSee https://oeis.org/A000041\n\n`IntPartitions(n,k)` is the number of partitions of the integer\n`n` with exactly `k` (nonzero) parts.\n\"\"\"\nfunction IntPartitions(n::Integer, k::Integer)::BigInt\n    if n < 0 || k < 0\n        throw(DomainError((n, k), \"arguments must be nonnegative\"))\n    end\n    # lots of special cases\n    if k > n\n        return big(0)\n    end\n    if n == 0\n        return big(1)\n    end\n    if k == 0\n        return big(0)\n    end\n    if k == n || k == 1\n        return big(1)\n    end\n    if _has(IntPartitions, (n, k))\n        return _get(IntPartitions, (n, k))\n    end\n\n    val = sum([IntPartitions(n - k, i) for i = 0:k])\n    _save(IntPartitions, (n, k), val)\n    return val\nend\n\nfunction IntPartitions(n::Integer)::BigInt\n    if n < 0\n        throw(DomainError(n, \"argument must be nonnegative\"))\n    end\n    if _has(IntPartitions, n)\n        return _get(IntPartitions, n)\n    end\n    val = sum([IntPartitions(n, k) for k = 0:n])\n    _save(IntPartitions, n, val)\n    return val\nend\nfunction IntPartitions()\n    _make(IntPartitions, Union{Tuple{Integer,Integer},Integer})\nend\nIntPartitions()\n\n\"\"\"\n`IntPartitionsDistinct(n,k)` is the number of partitions of\nthe integer `n` into exactly `k` *distinct* parts.\n\n`IntPartitionsDistinct(n)` is the number of partitions of `n`\ninto *distinct* parts.\n\"\"\"\nfunction IntPartitionsDistinct(n::Integer, k::Integer)::BigInt\n    if n < 0 || k < 0\n        throw(DomainError((n, k), \"arguments must be nonnegative\"))\n    end\n    Ck2 = div(k * (k - 1), 2)\n    if n < Ck2\n        return big(0)\n    end\n    return IntPartitions(n - Ck2, k)\nend\n\nfunction IntPartitionsDistinct(n::Integer)::BigInt\n    if n < 0\n        throw(DomainError(n, \"argument must be nonngative\"))\n    end\n    result = big(0)\n    for k = 1:n\n        s = IntPartitionsDistinct(n, k)\n        if s == 0\n            break\n        end\n        result += s\n    end\n    return result\nend\n\n\"\"\"\n    Euler(n)\n\nreturns the `n`-th Euler number. Starting with `n=0`\nthis is the sequence\n1, 0, -1, 0, 5, 0, -61, 0, 1385 and so on. \nSee https://oeis.org/A122045\n\nNot to be confused with `Eulerian`.\n\"\"\"\nfunction Euler(n::Integer)::BigInt\n    n >= 0 || throw(DomainError(n, \"argument must be nonngative\"))\n    if n % 2 == 1\n        return big(0)\n    end\n\n    if _has(Euler, n)\n        return _get(Euler, n)\n    end\n\n    start = _max_arg(Euler) + 2\n\n    for m = start:2:n\n        last = div(m, 2) - 1\n        val = -sum([Binomial(m, 2k) * Euler(2k) for k = 0:last])\n        _save(Euler, m, val)\n    end\n\n    return _get(Euler, n)\nend\n\nfunction Euler()\n    _make(Euler, Integer)\n    _save(Euler, 0, big(1))\nend\nEuler()\n\n\n\n\"\"\"\n    PowerSum(n,k)\n\nreturns the sum of the `k`-th powers of the\nintegers `1` through `n`, i.e.,\n`1^k + 2^k + 3^k + ... + n^k`.\n\"\"\"\nfunction PowerSum(n::Integer, k::Integer)::BigInt\n    (n >= 0 && k >= 0) || throw(DomainError((n, k), \"arguments must be nonngative\"))\n    # Base and special cases\n    if n == 0\n        return big(0)\n    end\n    if k == 0\n        return big(n)\n    end\n    if k == 1\n        return Binomial(n + 1, 2)\n    end\n    if _has(PowerSum, (n, k))\n        return _get(PowerSum, (n, k))\n    end\n\n    val = big(n)^k + PowerSum(n - 1, k)\n    _save(PowerSum, (n, k), val)\n    return val\nend\nfunction PowerSum()\n    _make(PowerSum, Tuple{Integer,Integer})\nend\nPowerSum()\n\nexport Eulerian\n\"\"\"\n    Eulerian(n,k)\n\nreturns the number of permutations of `{1,2,...,n}`\nwith `k` ascents. See https://oeis.org/A008292\n\nNot to be confused with `Euler`.\n\"\"\"\nfunction Eulerian(n::Integer, k::Integer)::BigInt\n    @assert (n >= 0 && k >= 0) \"$n,$k must both be nonnegative\"\n\n    if n == 0\n        return big(0)\n    end\n\n    if k > n || k == 0\n        return big(0)\n    end\n\n    if n < 2\n        return big(1)\n    end\n\n    if k == n      # includes the case n=k=0\n        return big(1)\n    end\n\n    if k == 1\n        return big(1)\n    end\n\n    if _has(Eulerian, (n, k))\n        return _get(Eulerian, (n, k))\n    end\n\n    val = (n - k + 1) * Eulerian(n - 1, k - 1) + k * Eulerian(n - 1, k)\n    _save(Eulerian, (n, k), val)\n    return val\nend\nfunction Eulerian()\n    _make(Eulerian, Tuple{Integer,Integer})\nend\nEulerian()\n\n\"\"\"\n    Menage(n)\n\nNumber of solutions to the Menage problem with `n` male/female couples. \nSee https://oeis.org/A059375 \n\"\"\"\nfunction Menage(n::Int)::BigInt\n    if n < 0\n        throw(DomainError(n, \"Argument must be nonnegative\"))\n    end\n    if _has(Menage, n)\n        return _get(Menage, n)\n    end\n    start = _max_arg(Menage) + 1\n    for m = start:n\n        s = (m % 2 == 0) ? -1 : 1\n        a1 = _get(Menage, m - 1) ÷ (2 * Factorial(m - 1))\n        a2 = _get(Menage, m - 2) ÷ (2 * Factorial(m - 2))\n\n        am = m * a1 + (m * a2 + 4s) ÷ (m - 2)\n        val = 2 * Factorial(m) * am\n\n        _save(Menage, m, val)\n    end\n    return _get(Menage, n)\nend\nfunction Menage()\n    _make(Menage, Int)\n    _save(Menage, 0, big(1))\n    _save(Menage, 1, big(0))\n    _save(Menage, 2, big(0))\n    _save(Menage, 3, big(12))\nend\nMenage()\n\nend  #end of module\n", "meta": {"hexsha": "f51ce0226aec5bbc81cdcd275c1b3896baaa2c23", "size": 15568, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BigCombinatorics.jl", "max_stars_repo_name": "scheinerman/BigCombinatorics.jl", "max_stars_repo_head_hexsha": "c8cea68e1e1ce2c6d78640340ac62411f49cae48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-13T02:37:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T02:37:20.000Z", "max_issues_repo_path": "src/BigCombinatorics.jl", "max_issues_repo_name": "scheinerman/BigCombinatorics.jl", "max_issues_repo_head_hexsha": "c8cea68e1e1ce2c6d78640340ac62411f49cae48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BigCombinatorics.jl", "max_forks_repo_name": "scheinerman/BigCombinatorics.jl", "max_forks_repo_head_hexsha": "c8cea68e1e1ce2c6d78640340ac62411f49cae48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-03T11:57:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T11:57:50.000Z", "avg_line_length": 21.5027624309, "max_line_length": 86, "alphanum_fraction": 0.6054085303, "num_tokens": 5030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7981193982017813}}
{"text": "using Plots, Printf, LinearAlgebra\n\n# enable plotting by default\nif !@isdefined do_visu; do_visu = true end\n\n@views function diffusion_1D(; do_visu=true)\n    # Physics\n    lx     = 10.0       # domain size\n    D      = 1.0        # diffusion coefficient\n    ttot   = 0.6        # total simulation time\n    dt     = 0.1        # physical time step\n    # Numerics\n    nx     = 256        # numerical grid resolution\n    tol    = 1e-6       # tolerance\n    itMax  = 1e5        # max number of iterations\n    damp   = 1-41/nx    # damping (this is a tuning parameter, dependent on e.g. grid resolution)\n    # Derived numerics\n    dx     = lx/nx      # grid size\n    dtau   = (1.0/(dx^2/D/2.1) + 1.0/dt)^-1 # iterative \"timestep\"\n    xc     = LinRange(dx/2, lx-dx/2, nx)\n    # Array allocation\n    qH     = zeros(nx-1)\n    dHdtau = zeros(nx-2)\n    ResH   = zeros(nx-2)\n    # Initial condition\n    H0     = exp.(-(xc.-lx/2).^2)\n    Hold   = copy(H0)\n    H      = copy(H0)\n    t = 0.0; it = 0; ittot = 0\n    # Physical time loop\n    while t<ttot\n        iter = 0; err = 2*tol\n        # Pseudo-transient iteration\n        while err>tol && iter<itMax\n            qH         .= -D*diff(H)/dx              # flux\n            ResH       .= -(H[2:end-1] - Hold[2:end-1])/dt - diff(qH)/dx # residual of the PDE\n            dHdtau     .= ResH + damp*dHdtau         # damped rate of change\n            H[2:end-1] .= H[2:end-1] + dtau*dHdtau   # update rule, sets the BC as H[1]=H[end]=0\n            iter += 1; err = norm(ResH)/length(ResH)\n        end\n        ittot += iter; it += 1; t += dt\n        Hold .= H\n    end\n    # Analytic solution\n    Hana = 1/sqrt(4*(ttot+1/4)) * exp.(-(xc.-lx/2).^2 /(4*(ttot+1/4)))\n    @printf(\"Total time = %1.2f, time steps = %d, iterations tot = %d, error vs analytic = %1.2e \\n\", round(ttot, sigdigits=2), it, ittot, norm(H-Hana))\n    # Visualize\n    if do_visu\n        plot(xc, H0, linewidth=3); display(plot!(xc, H, legend=false, framestyle=:box, linewidth=3, xlabel=\"lx\", ylabel=\"H\", title=\"damped diffusion (nt=$it, iters=$ittot)\"))\n    end\n    return xc, H0\nend\n\ndiffusion_1D(; do_visu=do_visu);\n", "meta": {"hexsha": "05a880907057127b972cc552b2c914c82f542f69", "size": 2120, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/diffusion_1D_damp.jl", "max_stars_repo_name": "luraess/julia-parallel-course-EGU21", "max_stars_repo_head_hexsha": "d7f0616e07f12deac45a635410d846e33eec0739", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2021-03-26T08:25:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T15:10:27.000Z", "max_issues_repo_path": "scripts/diffusion_1D_damp.jl", "max_issues_repo_name": "speedshi/julia-parallel-course-EGU21", "max_issues_repo_head_hexsha": "b700a9ad0d1d14f26e0590ce41a8e63380a1df15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-04-14T17:33:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T10:19:26.000Z", "max_forks_repo_path": "scripts/diffusion_1D_damp.jl", "max_forks_repo_name": "speedshi/julia-parallel-course-EGU21", "max_forks_repo_head_hexsha": "b700a9ad0d1d14f26e0590ce41a8e63380a1df15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-04-21T13:09:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-29T05:59:37.000Z", "avg_line_length": 38.5454545455, "max_line_length": 174, "alphanum_fraction": 0.5400943396, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7981174162417363}}
{"text": "using InfiniteOpt, Ipopt, Plots\nusing KNITRO\n\n# Parmeters\n# Time span\nt0 = 0\ntf = 1\n# Initial values\nx1 = 1\n\n\n# Model\nmodel = InfiniteModel(KNITRO.Optimizer)\n\n# infinite_parameter\n@infinite_parameter(model, t ∈ [t0, tf], num_supports = 101)\n\n# variable\n@variable(model, x ≥ 0, Infinite(t))\n\n@variable(model, u, Infinite(t), start = 0)\n\n# objective\n@objective(model, Min, x(1)^2 + ∫(u^2, t))\n\n# constraint\n@constraint(model, x(0) == x1)\n@constraint(model, x_constr, ∂(x, t) == x + u)\n\n\n# Optimization\n\nprint(model)\n\noptimize!(model)\n\n# Visulization\nts = value(t)\nu_value = value(u)\nx_value = value(x)\n\ndisplay(plot(ts, u_value))\ndisplay(plot(ts, x_value))\n\nusing DiffEqFlux, DifferentialEquations\nconst solveeq = DifferentialEquations.solve\n\ntspan = (t0, tf)\nann = FastChain(FastDense(1, 64, tanh), FastDense(64, 1))\nθ = initial_params(ann)\nfunction sir_nn(du, u, p, t)\n    du[1] = u[1] + ann([t], p)[1]\nend\nu0 = [x1]\nts = Float32.(collect(0.0:0.01:tspan[2]))\nprob = ODEProblem(sir_nn, u0, tspan, θ)\nsol_init = solveeq(prob, Vern9(), abstol = 1e-10, reltol = 1e-10)\nplot(sol_init)\nfunction predict_adjoint(θ)\n    Array(solveeq(prob, Vern9(), p = θ, saveat = ts, sensealg = InterpolatingAdjoint(autojacvec = ReverseDiffVJP(true))))\nend\nfunction loss_adjoint(θ)\n    x = predict_adjoint(θ)\n    x[1, end]^2 + 0.01 * sum(abs2, [first(ann([t], θ)) for t in ts])\nend\nl = loss_adjoint(θ)\n\nconst losses = []\ncallback(θ, l, pred) = begin\n    push!(losses, l)\n    if length(losses) % 50 == 0\n        println(losses[end])\n        p = plot(solveeq(remake(prob, p = θ), Tsit5(), saveat = ts), lw = 3)\n        #plot!(p, ts, [first(ann([t], θ)) for t in ts], label = \"u(t)\", lw = 3)\n        display(p)\n    end\n    false\nend\n# cb = function (θ, l)\n#     println(l)\n#     p = plot(solveeq(remake(prob, p = θ), Tsit5(), saveat = ts), lw = 3)\n#     #plot!(p, ts, [first(ann([t], θ)) for t in ts], label = \"u(t)\", lw = 3)\n#     display(p)\n#     return false\n# end\n# Display the ODE with the current parameter values.\ncb(θ, l)\nloss1 = loss_adjoint(θ)\nres1 = DiffEqFlux.sciml_train(loss_adjoint, θ, ADAM(0.05), cb = cb, maxiters = 100)\nres2 = DiffEqFlux.sciml_train(loss_adjoint, res1.u,\n    BFGS(initial_stepnorm = 0.01), cb = cb, maxiters = 100,\n    allow_f_increases = false)\n\n\nusing DataFrames\nusing CSV\np_value = res2.u\nresults_saving_opt = DataFrame()\nresults_saving_opt.t = ts\nresults_saving_opt.I = x_value\nresults_saving_opt.u = u_value\nresults_saving_opt.I_nn = Array(solveeq(remake(prob, p = p_value), Tsit5(), saveat = ts))[1, :]\nresults_saving_opt.u_nn = [first(ann([t], p_value)) for t in ts]\nCSV.write(\"results_saving_Example3_2.csv\", results_saving_opt)\n\nplot(results_saving_opt.t, results_saving_opt.I, lw = 2, label = \"I(t) by direct collection\")\nplot!(results_saving_opt.t, results_saving_opt.I_nn, lw = 2, label = \"I(t) by deep learning\")\nxlabel!(\"t(day)\")\nylabel!(\"I(t)\")\nsavefig(\"Example3_2_I.png\")\n\nplot(results_saving_opt.t[2:end-1], results_saving_opt.u[2:end-1], lw = 2, label = \"u(t) by direct collection\")\nplot!(results_saving_opt.t[2:end-1], results_saving_opt.u_nn[2:end-1], lw = 2, label = \"u(t) by deep learning\")\nxlabel!(\"t(day)\")\nylabel!(\"u(t)\")\nsavefig(\"Example3_2_control.png\")\n\n\n# \nopt_loss = objective_value(model)\n# opt_loss = 1.75\nopt_loss_nn = loss_adjoint(p_value)", "meta": {"hexsha": "22ef7b652adcec1c4e8e3ca11a1991aa286611c1", "size": 3282, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Example3.2.jl", "max_stars_repo_name": "Song921012/OptEpiDeepL", "max_stars_repo_head_hexsha": "25141f8716c743e80a5882f082f1459268e468a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Example3.2.jl", "max_issues_repo_name": "Song921012/OptEpiDeepL", "max_issues_repo_head_hexsha": "25141f8716c743e80a5882f082f1459268e468a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Example3.2.jl", "max_forks_repo_name": "Song921012/OptEpiDeepL", "max_forks_repo_head_hexsha": "25141f8716c743e80a5882f082f1459268e468a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9016393443, "max_line_length": 121, "alphanum_fraction": 0.6709323583, "num_tokens": 1145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090322, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7981174113168716}}
{"text": "#== # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n#\n# Description\n#\n#   Functions related to the associated Legendre functions.\n#\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n#\n# References\n#\n#   [1] Holmes, S. A. and W. E. Featherstone, 2002. A unified approach to the\n#       Clenshaw summation and the recursive computation of very high degree and\n#       order normalised associated Legendre functions. Journal of Geodesy,\n#       76(5), pp. 279-299.\n#\n#       For more info.: http://mitgcm.org/~mlosch/geoidcookbook/node11.html\n#\n#   [2] Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications.\n#       Microcosm Press, Hawthorn, CA, USA.\n#\n#   [3] Schmidt, A (1917). Erdmagnetismus, Enzykl. Math. Wiss., 6, pp. 265–396.\n#\n#   [4] Winch, D. E., Ivers, D. J., Turner, J. P. R., Stening R. J (2005).\n#       Geomagnetism and Schmidt quasi-normalization. Geophysical Journal\n#       International, 160(2), pp. 487-504.\n#\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ==#\n\nexport denormalize_legendre, legendre!, legendre\n\nexport legendre_fully_normalized!, legendre_fully_normalized\nexport legendre_schmidt_quasi_normalized!, legendre_schmidt_quasi_normalized\nexport legendre_conventional!, legendre_conventional\n\n\"\"\"\n    legendre!([N,] P::AbstractMatrix, ϕ::Number, ph_term::Bool = false, n_max::Integer = -1, m_max::Integer = -1)\n\nCompute the associated Legendre function `P_n,m[cos(ϕ)]`. The maximum degree and\norder that will be computed are given by the parameters `n_max` and `m_max`. If\nthey are negative, then the dimensions of matrix `P` will be used.\n\nThe result will be stored at matrix `P`.\n\nThe optional parameter `N` can be used to select the normalization. The\nfollowing values are valid:\n\n* `Val(:full)`: Compute the fully normalized associated Legendre function (see\n  `legendre_fully_normalized!`).\n* `Val(:schmidt)`: Compute the Schmidt quasi-normalized associated Legendre\n  function (see `legendre_schmidt_quasi_normalized!`).\n* `Val(:conv)`: Compute the conventional associated Legendre function (see\n  `legendre_conventional!`).\n\nIf `N` is omitted, then the full normalization will be used.\n\nIf `ph_term` is set to `true`, then the Condon-Shortley phase term `(-1)ᵐ` will\nbe included. If `ph_term` is not present, then it defaults to `false`.\n\n\"\"\"\nlegendre!(P::AbstractMatrix, ϕ::Number, ph_term::Bool = false,\n          n_max::Integer = -1, m_max::Integer = -1) =\n    legendre_fully_normalized!(P, float(ϕ), ph_term, n_max, m_max)\n\nlegendre!(::Val{:full}, P::AbstractMatrix, ϕ::Number, ph_term::Bool = false,\n          n_max::Integer = -1, m_max::Integer = -1) =\n    legendre_fully_normalized!(P, float(ϕ), ph_term, n_max, m_max)\n\nlegendre!(::Val{:schmidt}, P::AbstractMatrix, ϕ::Number, ph_term::Bool = false,\n          n_max::Integer = -1, m_max::Integer = -1) =\n    legendre_schmidt_quasi_normalized!(P, float(ϕ), ph_term, n_max, m_max)\n\nlegendre!(::Val{:conv}, P::AbstractMatrix, ϕ::Number, ph_term::Bool = false,\n          n_max::Integer = -1, m_max::Integer = -1) =\n    legendre_conventional!(P, float(ϕ), ph_term, n_max, m_max)\n\n\"\"\"\n    legendre([N,] ϕ::Number, n_max::Integer, m_max::Integer = -1, ph_term::Bool = false)\n\nCompute the associated Legendre function `P_n,m[cos(ϕ)]`. The maximum degree\nthat will be computed is `n_max` and the maximum order is `m_max`. Notice that\nif `m_max` is higher than `n_max` or negative, than it is set to `n_max`.\n\nThe optional parameter `N` can be used to select the normalization. The\nfollowing values are valid:\n\n* `Val(:full)`: Compute the fully normalized associated Legendre function (see\n  `legendre_fully_normalized`).\n* `Val(:schmidt)`: Compute the Schmidt quasi-normalized associated Legendre\n  function (see `legendre_schmidt_quasi_normalized`).\n* `Val(:conv)`: Compute the conventional associated Legendre function (see\n  `legendre_conventional`).\n\nIf `N` is omitted, then the full normalization will be used (`Val(:full)`).\n\nIf `ph_term` is set to `true`, then the Condon-Shortley phase term `(-1)ᵐ` will\nbe included. If `ph_term` is not present, then it defaults to `false`.\n\n# Returns\n\nA matrix with the Legendre associated functions `P_n,m[cos(ϕ)]`.\n\n\"\"\"\nlegendre(ϕ::Number, n_max::Integer, m_max::Integer = -1, ph_term::Bool = false) =\n    legendre_fully_normalized(float(ϕ), n_max, m_max, ph_term)\n\nlegendre(::Val{:full}, ϕ::Number, n_max::Integer, m_max::Integer = -1,\n         ph_term::Bool = false) =\n    legendre_fully_normalized(float(ϕ), n_max, m_max, ph_term)\n\nlegendre(::Val{:schmidt}, ϕ::Number, n_max::Integer, m_max::Integer = -1,\n         ph_term::Bool = false) =\n    legendre_schmidt_quasi_normalized(float(ϕ), n_max, m_max, ph_term)\n\nlegendre(::Val{:conv}, ϕ::Number, n_max::Integer, m_max::Integer = -1,\n         ph_term::Bool = false) =\n    legendre_conventional(float(ϕ), n_max, m_max, ph_term)\n\n################################################################################\n#                Fully Normalized Associated Legendre Functions\n################################################################################\n\n\"\"\"\n    legendre_fully_normalized!(P::AbstractMatrix, ϕ::Number, ph_term::Bool = false, n_max::Integer = -1, m_max::Integer = -1)\n\nCompute the fully normalized associated Legendre function `P_n,m[cos(ϕ)]`. The\nmaximum degree and order that will be computed are given by the parameters\n`n_max` and `m_max`. If they are negative, then the dimensions of matrix `P`\nwill be used:\n\n    maximum degree -> number of rows\n    maximum order  -> number of columns\n\nThe result will be stored at matrix `P`.\n\nIf `ph_term` is set to `true`, then the Condon-Shortley phase term `(-1)ᵐ` will\nbe included. If `ph_term` is not present, then it defaults to `false`.\n\n# Remarks\n\nThis algorithm was based on [1]. Our definition of fully normalized associated\nLegendre function can be seen in [2, p. 546]. The conversion is obtained by:\n\n                 _                     -\n                |  (n-m)! . k . (2n+1)  |      k = 1 if m  = 0\n    K_n,m = sqrt| --------------------- |,     k = 2 if m != 0\n                |         (n+m)!        |\n                 -                     -\n    _\n    P_n,m = P_n,m * K_n,m,\n\n          _\n    where P_n,m is the fully normalized Legendre associated function.\n\n\"\"\"\nfunction legendre_fully_normalized!(P::AbstractMatrix, ϕ::Number,\n                                    ph_term::Bool = false, n_max::Integer = -1,\n                                    m_max::Integer = -1)\n\n    # Obtain the maximum degree and order that must be computed.\n    n_max, m_max = _get_degree_and_order(P, n_max, m_max)\n\n    # Auxiliary variables to improve code performance.\n    c = cos(ϕ)\n    s = sqrt(1-c^2)\n\n    s_fact = !ph_term ? +s : -s\n\n    @inbounds for n = 0:n_max\n        # Starting values.\n        if n == 0\n            P[0+1,0+1] = 1\n            continue\n        elseif n == 1\n            P[1+1,0+1] = +sqrt(3)*c\n\n            if m_max > 0\n                P[1+1,1+1] = +sqrt(3)*s_fact\n            end\n\n            continue\n        end\n\n        aux_n = (2n-1)*(2n+1)\n\n        for m = 0:n\n\n            if n == m\n                P[n+1,n+1] = s_fact*sqrt( (2n+1)/(2n) )*P[n-1+1,n-1+1]\n            else\n                aux_nm = (n-m)*(n+m)\n                a_nm   = sqrt( aux_n / aux_nm )\n                b_nm   = sqrt( ( (2n+1)*(n+m-1)*(n-m-1) ) / ( aux_nm*(2n-3) ) )\n\n                # We assume that the matrix is not initialized. Hence, we must\n                # not access elements on the upper triangle.\n                if m != n-1\n                    P[n+1,m+1] = a_nm*c*P[n-1+1,m+1] - b_nm*P[n-2+1,m+1]\n                else\n                    P[n+1,m+1] = a_nm*c*P[n-1+1,m+1]\n                end\n            end\n\n            # Check if the maximum desired order has been reached.\n            m == m_max && break\n        end\n    end\n\n    nothing\nend\n\n\"\"\"\n    legendre_fully_normalized(ϕ::T, n_max::Integer, m_max::Integer = -1, ph_term::Bool = false) where T<:AbstractFloat\n\nCompute the fully normalized associated Legendre function `P_n,m[cos(ϕ)]`. The\nmaximum degree that will be computed is `n_max` and the maximum order is\n`m_max`. Notice that if `m_max` is higher than `n_max` or negative, than it is\nset to `n_max`.\n\nIf `ph_term` is set to `true`, then the Condon-Shortley phase term `(-1)ᵐ` will\nbe included. If `ph_term` is not present, then it defaults to `false`.\n\n# Returns\n\nA matrix with the Legendre associated functions `P_n,m[cos(ϕ)]`.\n\n# Remarks\n\nThis algorithm was based on [1]. Our definition of fully normalized associated\nLegendre function can be seen in [2, p. 546]. The conversion is obtained by:\n\n                 _                     -\n                |  (n-m)! . k . (2n+1)  |      k = 1 if m  = 0\n    K_n,m = sqrt| --------------------- |,     k = 2 if m != 0\n                |         (n+m)!        |\n                 -                     -\n    _\n    P_n,m = P_n,m * K_n,m,\n\n          _\n    where P_n,m is the fully normalized Legendre associated function.\n\n\"\"\"\nfunction legendre_fully_normalized(ϕ::T, n_max::Integer, m_max::Integer = -1,\n                                   ph_term::Bool = false) where T<:AbstractFloat\n\n    (n_max < 0) && throw(ArgumentError(\"n_max must be positive.\"))\n\n    ( (m_max < 0) || (m_max > n_max) ) && (m_max = n_max)\n\n    P = zeros(T, n_max+1, m_max+1)\n    legendre_fully_normalized!(P, ϕ, ph_term)\n    return P\nend\n\n################################################################################\n#            Schmidt Quasi-Normalized Associated Legendre Functions\n################################################################################\n\n\"\"\"\n    legendre_schmidt_quasi_normalized!(P::AbstractMatrix, ϕ::Number, ph_term::Bool = false, n_max::Integer = -1, m_max::Integer = -1)\n\nCompute the Schmidt quasi-normalized associated Legendre function\n`P_n,m[cos(ϕ)]` [3,4]. The maximum degree and order that will be computed are\ngiven by the parameters `n_max` and `m_max`. If they are negative, then the\ndimensions of matrix `P` will be used:\n\n    maximum degree -> number of rows\n    maximum order  -> number of columns\n\nThe result will be stored at matrix `P`.\n\nIf `ph_term` is set to `true`, then the Condon-Shortley phase term `(-1)ᵐ` will\nbe included. If `ph_term` is not present, then it defaults to `false`.\n\n# Remarks\n\nThis algorithm was based on [3,4]. The conversion is obtained by:\n\n                 _           -\n                |     (n-m)!  |    k = 1 if m  = 0\n    K_n,m = sqrt| k. -------- |,   k = 2 if m != 0\n                |     (n+m)!  |\n                 -           -\n\n    =\n    P_n,m = P_n,m * K_n,m,\n\n          =\n    where P_n,m is the quasi-normalized normalized Legendre associated function.\n\n\"\"\"\nfunction legendre_schmidt_quasi_normalized!(P::AbstractMatrix, ϕ::Number,\n                                            ph_term::Bool = false,\n                                            n_max::Integer = -1,\n                                            m_max::Integer = -1)\n\n    # Obtain the maximum degree and order that must be computed.\n    n_max, m_max = _get_degree_and_order(P, n_max, m_max)\n\n    # Auxiliary variables to improve code performance.\n    c = cos(ϕ)\n    s = sqrt(1-c^2)\n\n    s_fact = !ph_term ? +s : -s\n\n    @inbounds for n = 0:n_max\n        # Starting values.\n        if n == 0\n            P[0+1,0+1] = 1\n            continue\n\n        elseif n == 1\n            P[1+1,0+1] = +c\n\n            if m_max > 0\n                P[1+1,1+1] = +s_fact\n            end\n\n            continue\n        end\n\n        aux_n = 2n-1 # -> sqrt( (2n-1)*(2n-1) )\n\n        for m = 0:n\n\n            if m == n\n                P[n+1,n+1] = s_fact*sqrt( aux_n/(2n) )*P[n-1+1,n-1+1]\n            else\n                aux_nm = sqrt( (n-m)*(n+m) )\n                a_nm   = aux_n / aux_nm\n                b_nm   = sqrt( (n+m-1)*(n-m-1) ) / aux_nm\n\n                # We assume that the matrix is not initialized. Hence, we must not\n                # access elements on the upper triangle.\n                if m != n-1\n                    P[n+1,m+1] = a_nm*c*P[n-1+1,m+1] - b_nm*P[n-2+1,m+1]\n                else\n                    P[n+1,m+1] = a_nm*c*P[n-1+1,m+1]\n                end\n            end\n\n            # Check if the maximum desired order has been reached.\n            m == m_max && break\n        end\n    end\n\n    nothing\nend\n\n\"\"\"\n    legendre_schmidt_quasi_normalized(ϕ::T, n_max::Integer, m_max::Integer = -1, ph_term::Bool = false) where T<:AbstractFloat\n\nCompute the Schmidt quasi-normalized associated Legendre function\n`P_n,m[cos(ϕ)]`. The maximum degree that will be computed is `n_max` and the\nmaximum order is `m_max`. Notice that if `m_max` is higher than `n_max` or\nnegative, than it is set to `n_max`.\n\nIf `ph_term` is set to `true`, then the Condon-Shortley phase term `(-1)ᵐ` will\nbe included. If `ph_term` is not present, then it defaults to `false`.\n\n# Returns\n\nA matrix with the Legendre associated functions `P_n,m[cos(ϕ)]`.\n\n# Remarks\n\nThis algorithm was based on [3,4]. The conversion is obtained by:\n\n                 _           -\n                |     (n-m)!  |    k = 1 if m  = 0\n    K_n,m = sqrt| k. -------- |,   k = 2 if m != 0\n                |     (n+m)!  |\n                 -           -\n\n    =\n    P_n,m = P_n,m * K_n,m,\n\n          =\n    where P_n,m is the quasi-normalized normalized Legendre associated function.\n\n\"\"\"\nfunction legendre_schmidt_quasi_normalized(ϕ::T, n_max::Integer,\n                                           m_max::Integer = -1,\n                                           ph_term::Bool = false) where T<:AbstractFloat\n\n    (n_max < 0) && throw(ArgumentError(\"n_max must be positive.\"))\n\n    ( (m_max < 0) || (m_max > n_max) ) && (m_max = n_max)\n\n    P = zeros(T, n_max+1, m_max+1)\n    legendre_schmidt_quasi_normalized!(P, ϕ, ph_term)\n    return P\nend\n\n################################################################################\n#                  Conventional Associated Legendre Function\n################################################################################\n\n\"\"\"\n    legendre_conventional!(P::AbstractMatrix, ϕ::Number, ph_term::Bool = false, n_max::Integer = -1, m_max::Integer = -1)\n\nCompute the conventional associated Legendre function `P_n,m[cos(ϕ)]`. The\nmaximum degree and order that will be computed are given by the parameters\n`n_max` and `m_max`. If they are negative, then the dimensions of matrix `P`\nwill be used:\n\n    maximum degree -> number of rows\n    maximum order  -> number of columns\n\nThe result will be stored at matrix `P`.\n\nIf `ph_term` is set to `true`, then the Condon-Shortley phase term `(-1)ᵐ` will\nbe included. If `ph_term` is not present, then it defaults to `false`.\n\n\"\"\"\nfunction legendre_conventional!(P::AbstractMatrix, ϕ::Number,\n                                ph_term::Bool = false, n_max::Integer = -1,\n                                m_max::Integer = -1)\n\n    # Obtain the maximum degree and order that must be computed.\n    n_max, m_max = _get_degree_and_order(P, n_max, m_max)\n\n    # Auxiliary variables to improve code performance.\n    c = cos(ϕ)\n    s = sqrt(1-c^2)\n\n    s_fact = !ph_term ? +s : -s\n\n    @inbounds for n = 0:n_max\n        # Starting values.\n        if n == 0\n            P[0+1,0+1] = 1\n            continue\n        elseif n == 1\n            P[1+1,0+1] = +c\n\n            if m_max > 0\n                P[1+1,1+1] = +s_fact\n            end\n\n            continue\n        end\n\n        aux_n = 2n-1 # -> sqrt( (2n-1)*(2n-1) )\n\n        for m = 0:n\n\n            if n == m\n                P[n+1,n+1] = s_fact*aux_n*P[n-1+1,n-1+1]\n            else\n                aux_nm = n-m # -> sqrt( (n-m)*(n-m) )\n                a_nm   = aux_n / aux_nm\n                b_nm   = (n+m-1) / aux_nm # -> sqrt( (n+m-1)*(n+m-1) ) / aux_nm\n\n                # We assume that the matrix is not initialized. Hence, we must\n                # not access elements on the upper triangle.\n                if m != n-1\n                    P[n+1,m+1] = a_nm*c*P[n-1+1,m+1] - b_nm*P[n-2+1,m+1]\n                else\n                    P[n+1,m+1] = a_nm*c*P[n-1+1,m+1]\n                end\n            end\n\n            # Check if the maximum desired order has been reached.\n            m == m_max && break\n        end\n    end\n\n    nothing\nend\n\n\"\"\"\n    legendre_conventional(ϕ::T, n_max::Integer, m_max::Integer = -1, ph_term::Bool = false) where T<:AbstractFloat\n\nCompute the conventional associated Legendre function `P_n,m[cos(ϕ)]`. The\nmaximum degree that will be computed is `n_max` and the maximum order is\n`m_max`. Notice that if `m_max` is higher than `n_max` or negative, than it is\nset to `n_max`.\n\nIf `ph_term` is set to `true`, then the Condon-Shortley phase term `(-1)ᵐ` will\nbe included. If `ph_term` is not present, then it defaults to `false`.\n\n# Returns\n\nA matrix with the Legendre associated functions `P_n,m[cos(ϕ)]`.\n\n\"\"\"\nfunction legendre_conventional(ϕ::T, n_max::Integer, m_max::Integer = -1,\n                               ph_term::Bool = false) where T<:AbstractFloat\n\n    (n_max < 0) && throw(ArgumentError(\"n_max must be positive.\"))\n\n    ( (m_max < 0) || (m_max > n_max) ) && (m_max = n_max)\n\n    P = zeros(T, n_max+1, m_max+1)\n    legendre_conventional!(P, ϕ, ph_term)\n    return P\nend\n\n################################################################################\n#                                   Private\n################################################################################\n\n\"\"\"\n    _get_degree_and_order(P, n_max, m_max)\n\nReturn the maximum degree and order to compute the Legendre associated functions\ngiven the matrix `P` and the configuration values `n_max` and `m_max`.\n\n\"\"\"\n@inline function _get_degree_and_order(P, n_max, m_max)\n    # Get the size of the matrix.\n    (rows, cols) = size(P)\n\n    # If the order or degree is less than 0, then the user wants to use all the\n    # available memory.\n    n_max < 0 && (n_max = rows - 1)\n    m_max < 0 && (m_max = cols <= rows ? cols - 1 : n_max)\n\n    # Make sure that the degree and order fits the matrix.\n    n_max > rows - 1 && (n_max = rows - 1)\n    ( (m_max > cols - 1) || (m_max > n_max) ) && (m_max = min(cols-1, n_max))\n\n    return n_max, m_max\nend\n", "meta": {"hexsha": "54b6deccf3ccfa9f4b891043b1e0793bf9be4e0e", "size": 18166, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/misc/legendre.jl", "max_stars_repo_name": "disberd/SatelliteToolbox.jl", "max_stars_repo_head_hexsha": "441470938af978e9d5653a9c4b36ccc107023960", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/misc/legendre.jl", "max_issues_repo_name": "disberd/SatelliteToolbox.jl", "max_issues_repo_head_hexsha": "441470938af978e9d5653a9c4b36ccc107023960", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/misc/legendre.jl", "max_forks_repo_name": "disberd/SatelliteToolbox.jl", "max_forks_repo_head_hexsha": "441470938af978e9d5653a9c4b36ccc107023960", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.536121673, "max_line_length": 133, "alphanum_fraction": 0.5587361004, "num_tokens": 5195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7981174095129945}}
{"text": "\"\"\"\n    y = bquantize(x, nsd=3, abstol=eps, reltol=10*eps)\n\nBidirectionally quantize a n by 1 vector x to nsd signed digits, terminate early\nif the error is less than the specified tolerances.\n\n`y` is a 2-tuple of arrays with the following fields:\n- `y`[1][i] is the quantized value in floating-point form\n- `y`[2][i] is a 2-by-nsd (or less) matrix containing the powers of two\n    (first row) and their signs (second row).\n\nSee also bunquantize.\n\"\"\"\nfunction bquantize(x, nsd=3, abstol=eps(Float64), reltol=10*eps(Float64))\n    n = length(x)\n    offset = -log2(0.75)\n\n    y_val = zeros(n)\n    y_csd = Array{Matrix{Int}}(undef, n)\n\n    for i = 1:n\n        xp = x[i]\n        y_val[i] = 0.0\n        for j = 1:nsd\n            error = abs(y_val[i] - x[i])\n            if error <= abstol || error <= abs(x[i])*reltol\n                break\n            end\n            p = floor(Int, log2(abs(xp)) + offset)\n            p2 = 2.0 .^ p\n            sx = cmp(xp, 0)\n            xp = xp - sx*p2\n            y_val[i] = y_val[i] + sx*p2\n            if isassigned(y_csd, i)\n                y_csd[i] = hcat(y_csd[i], [p; sx])\n            else\n                y_csd[i] = reshape([p; sx], (2,1))\n            end\n        end\n    end\n\n    return y_val, y_csd\nend\n", "meta": {"hexsha": "a17989b78d134a78bd040fb565e315abfd61b70d", "size": 1243, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bquantize.jl", "max_stars_repo_name": "Mahmoud-Kharsa/DeltaSigma", "max_stars_repo_head_hexsha": "a351d03db5352a3a0c0e55e593b305255e743755", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bquantize.jl", "max_issues_repo_name": "Mahmoud-Kharsa/DeltaSigma", "max_issues_repo_head_hexsha": "a351d03db5352a3a0c0e55e593b305255e743755", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-02-12T04:56:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-03T09:08:22.000Z", "max_forks_repo_path": "src/bquantize.jl", "max_forks_repo_name": "Mahmoud-Kharsa/DeltaSigma", "max_forks_repo_head_hexsha": "a351d03db5352a3a0c0e55e593b305255e743755", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.25, "max_line_length": 80, "alphanum_fraction": 0.5309734513, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458251637412, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7981174062047889}}
{"text": "#### ODE Steppers for y'(t) = f(t, y(t)) #####\r\n\r\n##### Secondary Methods ######\r\n\r\nfunction Derivative(x, f, d=1, h=10.0^-8)\r\n    \"\"\"\r\n    Estimate the derivative of f at x using the center\r\n    finite difference technique with step size h.\r\n    \r\n    x and f can be vector valued, in which case\r\n    d must be provided. d should be a list of only\r\n    zeros and ones.\r\n    \r\n    For example, if x and f(x) are vectors of length four\r\n    and we want the derivative with respect to the second\r\n    component in x, then we call Derivative(x, f, [0, 1, 0, 0]).\r\n    \"\"\"\r\n    (f(x+h*d) - f(x-h*d)) / (2*h)\r\nend\r\n\r\nfunction NewtonsMethod(x, f, error_tol=10.0^-10)\r\n    \"\"\" \r\n    Estimate the root of f starting from x.\r\n    \r\n    x and f(x) are vector valued. Newton's method becomes\r\n    \r\n    \\vec{x}_{n+1} = \\vec{x}_{n} - inv(Jacobian) * \\vec{f(\\vec{x}_n)}\r\n    \r\n    I create the Jacobian by estimating the derivatives\r\n    using a center finite difference method.\r\n    \"\"\"\r\n    h, n = 10.0^-5, length(x)\r\n    J = zeros(n, n)\r\n    for j=1:n\r\n        d = zeros(n)\r\n        d[j] = 1\r\n        J[:, j] = Derivative(x, f, d)\r\n    end\r\n    count = 0\r\n    while norm(f(x)) > error_tol\r\n        count += 1\r\n        x -= inv(J) * f(x)\r\n        if count > 50\r\n            println(\"Newton's Method took unusually long so it was terminated prematurely.\")\r\n            return x\r\n        end\r\n    end\r\n    x\r\nend\r\n\r\n##### End Secondary Methods #####\r\n\r\n###### Single Steppers ######\r\n\r\n## Step functions that do not include an error estimate ##\r\n# Call these with Stepper(f, method, t0, y0, tf, h)\r\n\r\nfunction EulerStep(f, t, y, h)\r\n    h * f(t, y)\r\nend\r\n\r\nfunction ImprovedEulerStep(f, t, y, h)\r\n    f0 = f(t, y)\r\n    (h / 2.0) * (f0 + f(t + h, y + h * f0))\r\nend\r\n\r\nfunction BackwardEulerStep(f, t, y, h)\r\n    \"\"\" Implicit Backward Euler Step \"\"\"\r\n    #Use Euler step as starting point for NewtonsMethod.\r\n    NewtonsMethod(f(t, y), f1 -> h*f(t+h, y+f1) - f1)\r\nend\r\n\r\nfunction GL2Step(f, t, y, h)\r\n    \"\"\" Implicit Gauss-Legendre Order 2 Method \"\"\"\r\n    #Use Euler step as starting point for NewtonsMethod.\r\n    NewtonsMethod(f(t, y), f1 -> h*f(t+h/2.0, y+f1/2.0) - f1)\r\nend\r\n\r\nfunction MidpointStep(f, t, y, h)\r\n    h * f(t + h / 2, y + (h / 2) * f(t, y))\r\nend\r\n\r\nfunction CrankNicholsonStep(f, t, y, h)\r\n    \"\"\" Second order implicit \"\"\"\r\n    f1 = f(t, y)\r\n    NewtonsMethod(f1, f2 -> (h/2.0) * (f1 + f(t+h, y+f2)) - f2)\r\nend\r\n\r\nfunction RK4Step(f, t, y, h)\r\n    f1 = f(t, y)\r\n    f2 = f(t + h / 2, y + (h / 2) * f1)\r\n    f3 = f(t + h / 2, y + (h / 2) * f2)\r\n    f4 = f(t + h, y + h * f3)\r\n    (h / 6) * (f1 + f4 + 2 * (f2 + f3))\r\nend\r\n\r\nfunction Stepper(f, method, t0, y0, tf, h)\r\n    \"\"\"\r\n    The step function `method` returns just the step,\r\n    not an error estimate.\r\n    \"\"\"\r\n    ts, ys = Float64[], Vector{Float64}[]\r\n    while t0 <= tf\r\n        push!(ts, t0)\r\n        push!(ys, y0)\r\n        y0 += method(f, t0, y0, h)\r\n        t0 += h\r\n    end\r\n    ts, ys\r\nend\r\n\r\n## End step functions that do not include an error estimate ##\r\n\r\n## Step functions that include an error estimate ##\r\n# Call these with AdaptiveStepper(f, method, t0, y0, tf)\r\n\r\nfunction SimpleErrorStep(f, t, y, h)\r\n    \"\"\" Compare implicit Crank Nicholson to Midpoint to get error \"\"\"\r\n    step = CrankNicholsonStep(f, t, y, h)\r\n    step, norm(step - MidpointStep(f, t, y, h))\r\nend\r\n\r\nfunction RKTrapStep(f, t, y, h)\r\n    \"\"\" Implicit Runge-Kutta Trapazoidal Method \"\"\"\r\n    f1 = h * f(t, y)\r\n    f2 = NewtonsMethod(f1, f2 -> h*f(t+h, y+f1/2.0+f2/2.0) - f2)\r\n    \r\n    soln = f1/2.0 + f2/2.0\r\n    soln, norm(soln - f1)\r\nend\r\n\r\nfunction DopriStep(f, t, y, h)\r\n    \"\"\" Dormand-Prince Method \"\"\"\r\n    f1 = h * f(t, y)\r\n    f2 = h * f(t + h/5.0, y + f1/5.0)\r\n    f3 = h * f(t + 3*h/10.0, y + 3*f1/40.0 + 9*f2/40.0)\r\n    f4 = h * f(t + 4*h/5.0, y + 44*f1/45.0 - 56*f2/15.0 + 32*f3/9.0)\r\n    f5 = h * f(t + 8*h/9.0, y + 19372*f1/6561.0 - 25360*f2/2187.0 + 64448*f3/6561.0 - 212*f4/729.0)\r\n    f6 = h * f(t + h, y + 9017*f1/3168.0 - 355*f2/33.0 + 46732*f3/5247.0 + 49*f4/176.0 - 5103*f5/18656.0)\r\n    soln = 35*f1/384.0 + 500*f3/1113.0 + 125*f4/192.0 - 2187*f5/6784.0 + 11*f6/84.0\r\n    f7 = h * f(t + h, y + soln)\r\n    alt = 5179*f1/57600.0 + 7571*f3/16695.0 + 393*f4/640.0 - 92097*f5/339200.0 + 187*f6/2100.0 + f7/40.0\r\n\r\n    soln, norm(soln - alt)\r\nend\r\n\r\nfunction CarpStep(f, t, y, h)\r\n    \"\"\" Cash-Karp Method \"\"\"\r\n    f1 = h * f(t, y)\r\n    f2 = h * f(t + h/5.0, y + f1/5.0)\r\n    f3 = h * f(t + 3*h/10, y + 3*f1/40.0 + 9*f2/40.0)\r\n    f4 = h * f(t + 3*h/5.0, y + 3*f1/10.0 - 9*f2/10.0 + 6*f3/5.0)\r\n    f5 = h * f(t + h, y - 11*f1/54.0 + 5*f2/2.0 - 70*f3/27.0 + 35*f4/27.0)\r\n    f6 = h * f(t + 7*h/8.0, y + 1631*f1/55296 + 175*f2/512 + 575*f3/13824 + 44275*f4/110592.0 + 253*f5/4096.0)\r\n    soln = 37*f1/378.0 + 250*f3/621.0 + 125*f4/594.0 + 512*f6/1771.0\r\n    alt = 2825*f1/27648.0 + 18575*f3/48384.0 + 13525*f4/55296.0 + 277*f5/14336.0 + f6/4.0\r\n    \r\n    soln, norm(soln - alt)\r\nend\r\n\r\nfunction RKFStep(f, t, y, h)\r\n    \"\"\" Runge-Kutta-Fehlberg Method \"\"\"\r\n    f1 = h * f(t, y)\r\n    f2 = h * f(t + h/4.0, y + f1/4.0)\r\n    f3 = h * f(t + 3*h/8.0, y + 3*f1/32.0 + 9*f2/32.0)\r\n    f4 = h * f(t + 12*h/13.0, y + 1932*f1/2197.0 - 7200*f2/2197.0 + 7296*f3/2197.0)\r\n    f5 = h * f(t + h, y + 439*f1/216.0 - 8*f2 + 3680*f3/513.0 - 845*f4/4104.0)\r\n    f6 = h * f(t + h/2.0, y - 8*f1/27.0 + 2*f2 - 3544*f3/2565.0 + 1859*f4/4104.0 - 11*f5/40.0)\r\n    soln = 16*f1/135.0 + 6656*f3/12825.0 + 28561*f4/56430.0 - 9*f5/50.0 + 2*f6/55.0\r\n    alt = 25*f1/216.0 + 1408*f3/2565.0 + 2197*f4/4104.0 - f5/5.0\r\n    \r\n    soln, norm(soln - alt)\r\nend\r\n\r\nfunction AdaptiveStepper(f, method, t0, y0, tf, error_tol=10.0^-7)\r\n    \"\"\"\r\n    The step function `method` must return the tuple,\r\n    (step, error estimate).\r\n    \"\"\"\r\n    ts, ys = Float64[t0], Vector{Float64}[y0]\r\n    h, totalerror = 0.001, 0\r\n    while t0 < tf\r\n        if h < 10.0^-8 && h < tf - t0\r\n            println(\"Step size effectively zero at t = \", t0)\r\n            h = 0.001\r\n        else\r\n            if h > tf - t0\r\n                h = tf - t0\r\n            end\r\n            m, error_est = method(f, t0, y0, h)\r\n            if error_est > error_tol\r\n                h *= .75\r\n            else\r\n                t0 += h\r\n                y0 += m\r\n                push!(ts, t0)\r\n                push!(ys, y0) \r\n                if error_est < error_tol / 10.0\r\n                    h *= 1.2\r\n                end\r\n                totalerror += error_est\r\n            end\r\n        end\r\n    end\r\n    println(\"Estimated upper bound on total error of \", method, \": \", totalerror)\r\n    ts, ys\r\nend\r\n\r\n## End step functions that include an error estimate ##\r\n\r\n##### End Single Steppers #####\r\n\r\n##### Multi Steppers ######\r\n#Call these with MultiStepper(f, method, t0, y0, tf, h)\r\n\r\nfunction AdamsBash2(f, t, y, h)\r\n    \"\"\" Adams–Bashforth Order 2 explicit method \"\"\"\r\n    y0n = Array[y, y + RK4Step(f, t, y, h)]\r\n    function g(t, yn)\r\n        #yn = Array[y0, y1]\r\n        y0, y1 = yn\r\n        y2 = y1 + h * (1.5 * f(t + h, y1) - 0.5 * f(t, y0))\r\n        Array[y1, y2]\r\n    end\r\n    g, y0n\r\nend\r\n\r\nfunction AdamsBash3(f, t, y, h)\r\n    \"\"\" Adams–Bashforth Order 3 explicit method \"\"\"\r\n    y1 = y + RK4Step(f, t, y, h)\r\n    y2 = y1 + RK4Step(f, t+h, y1, h)\r\n    y0n = Array[y, y1, y2]\r\n    function g(t, yn)\r\n        #yn = Array[y0, y1, y2]\r\n        y0, y1, y2 = yn\r\n        y3 = y2 + h * (23.0 / 12.0 * f(t+2*h, y2) - 4.0 / 3.0 * f(t+h, y1) + 5.0 / 12.0 * f(t, y0))\r\n        Array[y1, y2, y3]\r\n    end\r\n    g, y0n\r\nend\r\n\r\nfunction AdamsBash4(f, t, y, h)\r\n    \"\"\" Adams–Bashforth Order 4 explicit method \"\"\"\r\n    y1 = y + RK4Step(f, t, y, h)\r\n    y2 = y1 + RK4Step(f, t+h, y1, h)\r\n    y3 = y2 + RK4Step(f, t+2*h, y2, h)\r\n    y0n = Array[y, y1, y2, y3]\r\n    function g(t, yn)\r\n        #yn = Array[y0, y1, y2, y3]\r\n        y0, y1, y2, y3 = yn\r\n        y4 = y3+h * (55.0 / 24.0 * f(t+3*h, y3) - 59.0 / 24.0 * f(t+2*h, y2) + 37.0 / 24.0 * f(t+h, y1) - 3.0 / 8.0 * f(t, y0))\r\n        Array[y1, y2, y3, y4]\r\n    end\r\n    g, y0n\r\nend\r\n\r\nfunction AdamsMoult2(f, t, y, h)\r\n    \"\"\" Adams-Moulton Order 2 implicit method \"\"\"\r\n    y1 = y + RK4Step(f, t, y, h)\r\n    y0n = Array[y, y1]\r\n    function g(t, yn)\r\n        y0, y1 = yn\r\n        f0, f1 = f(t, y0), f(t+h, y1)\r\n        y2 = NewtonsMethod(y1, y2 -> y1+h*(5*f(t+2*h, y2)/12.0 + 2*f1/3.0 - f0/12.0) - y2)\r\n        Array[y1, y2]\r\n    end\r\n    g, y0n\r\nend\r\n\r\nfunction AdamsMoult3(f, t, y, h)\r\n    \"\"\" Adams-Moulton Order 3 implicit method \"\"\"\r\n    y1 = y + RK4Step(f, t, y, h)\r\n    y2 = y1 + RK4Step(f, t+h, y1, h)\r\n    y0n = Array[y, y1, y2]\r\n    function g(t, yn)\r\n        y0, y1, y2 = yn\r\n        f0, f1, f2 = f(t, y0), f(t+h, y1), f(t+2*h, y2)\r\n        y3 = NewtonsMethod(y2, y3 -> y2+h*(3*f(t+3*h, y3)/8.0 + 19*f2/24.0 - 5*f1/24.0 + f0/24.0)-y3)\r\n        Array[y1, y2, y3]\r\n    end\r\n    g, y0n\r\nend\r\n\r\nfunction AdamsMoult4(f, t, y, h)\r\n    \"\"\" Adams-Moulton Order 4 implicit method \"\"\"\r\n    y1 = y + RK4Step(f, t, y, h)\r\n    y2 = y1 + RK4Step(f, t+h, y1, h)\r\n    y3 = y2 + RK4Step(f, t+2*h, y2, h)\r\n    y0n = Array[y, y1, y2, y3]\r\n    function g(t, yn)\r\n        y0, y1, y2, y3 = yn\r\n        f0, f1, f2, f3 = f(t, y0), f(t+h, y1), f(t+2*h, y2), f(t+3*h, y3)\r\n        y4 = NewtonsMethod(y3, y4 -> y3+h*(251*f(t+4*h, y4)/720.0+646*f3/720.0 - 264*f2/720.0 + 106*f1/720.0 - 19*f0/720.0)-y4)\r\n        Array[y1, y2, y3, y4]\r\n    end\r\n    g, y0n\r\nend\r\n\r\nfunction MultiStepper(f, method, t0, y0, tf, h)\r\n    \"\"\"\r\n    method returns g(t, yn), y0n with y0n is \r\n    an array  of previous values of y. \r\n    \"\"\"\r\n    g, y0n = method(f, t0, y0, h)\r\n    #y0n = Array[y0, y1, ..., yn]\r\n    ts, ys = Float64[], Vector{Float64}[]\r\n    while t0 <= tf + h\r\n        push!(ts, t0)\r\n        push!(ys, y0n[1])\r\n        y0n = g(t0, y0n)\r\n        t0 += h\r\n    end\r\n    ts, ys\r\nend\r\n\r\n##### End Multi Steppers #####\r\n\r\n\r\n#### Test ####\r\nfunction func(t, y)\r\n    y1, ydot = y\r\n    [ydot, -t*y1]\r\nend\r\n\r\nt, tmax, h = 0.0, 20, 0.01\r\ny0 = [-1.0, 0.0]\r\n\r\n#xs, ys = MultiStepper(func, AdamsMoult4, t, copy(y0), tmax, h)\r\nxs, ys = Stepper(func, GL2Step, t, copy(y0), tmax, h)\r\n#xs, ys = AdaptiveStepper(func, RKTrapStep, t, copy(y0), tmax, h)\r\nfigure(0)\r\nplot(xs, [ys[i][1] for i=1:length(ys)], \"o-\", label=\"Position\")\r\nplot(xs, [ys[i][2] for i=1:length(ys)], \"x--\", label=\"Velocity\")\r\nlegend()\r\n\r\n\r\nxs, ys = AdaptiveStepper(func, RKFStep, t, copy(y0), tmax)\r\nfigure(1)\r\nplot(xs, [ys[i][1] for i=1:length(ys)], \"o-\", label=\"Position\")\r\nplot(xs, [ys[i][2] for i=1:length(ys)], \"x--\", label=\"Velocity\")\r\nlegend()", "meta": {"hexsha": "8d67a1de7c18fd1c838d166c9401c49bc379c5d0", "size": 10516, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia_Code/Methods.jl", "max_stars_repo_name": "jiosue/QuadratureCandJulia", "max_stars_repo_head_hexsha": "198f7db626641ba551de0316c529c9b367068eb5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Julia_Code/Methods.jl", "max_issues_repo_name": "jiosue/QuadratureCandJulia", "max_issues_repo_head_hexsha": "198f7db626641ba551de0316c529c9b367068eb5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia_Code/Methods.jl", "max_forks_repo_name": "jiosue/QuadratureCandJulia", "max_forks_repo_head_hexsha": "198f7db626641ba551de0316c529c9b367068eb5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8387096774, "max_line_length": 128, "alphanum_fraction": 0.5030429821, "num_tokens": 4272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8723473730188542, "lm_q1q2_score": 0.7981114446605668}}
{"text": "using DataFrames, Plots\npyplot()\n\nProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n  \n  function euler_ex71(f::Function, y0::Float64, x::FloatRange{Float64})\n    y = Vector{Real}(length(x))\n    y[1] = y0\n    h = x.step/x.divisor\n    for i in 2:length(x)\n      k0 = h * f(x[i-1], y[i-1])\n      k1 = h * f(x[i-1] + h, y[i-1] + k0)\n      y[i] = y[i-1] + 1/2*(k0 + k1)\n    end\n    columns=[]\n    push!(columns, collect(x))\n    push!(columns, y)\n    df = DataFrame(columns, [:x, :y])\n  end\n\n  f(x,y) = (x+y)/x\n  fy(x) = x*(1+log(x/2))\n  \n  x1 = 2.0:0.25:2.5\n  x2 = 2.0:0.1:2.5\n  x3 = 1.8:0.1:2.6\n  df1 = euler_ex71(f, 2.0, x1)\n  df2 = euler_ex71(f, 2.0, x2)\n\n  df1 |> display\n  println()\n  df2 |> display\n  println()\n\n  global p2\n  \n  p1 = plot(x3, fy.(x3), ylims=(1.8, 3.5))\n  plot!(p1, df1[:x], df1[:y], line=(:dash, 1), marker=(:plus), color=:red)\n  plot!(p1, df2[:x], df2[:y], line=(:dash, 1), marker=(:circle), color=:red)\n  savefig(\"euler_ex7.2.png\")\n  plot(p1, layout=(1,1))\n  gui()\nend", "meta": {"hexsha": "69afeee9e70f61616338e2fcb1b3164037ab06d6", "size": 983, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch07/IVP/euler_ex7.2.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "examples/ch07/IVP/euler_ex7.2.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "examples/ch07/IVP/euler_ex7.2.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 22.3409090909, "max_line_length": 76, "alphanum_fraction": 0.5340793489, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8723473630627235, "lm_q1q2_score": 0.7981114436482116}}
{"text": "## PART 4\n\nprintln(\"\\nPart 4\");\n\nbvals = [b-3:b+3];\nprintln(\"\\n\\tEstimating σ for f1..f3 with bin around b=$b\");\n\nσf1jack = Float64[];\nσf2jack = Float64[];\nσf3jack = Float64[];\n\nfor bb in bvals\n    jestb = jacknife(v, N2, bb);\n    push!(σf1jack, jacknifeσ(f1, jestb));\n    push!(σf2jack, jacknifeσ(f2, jestb));\n    push!(σf3jack, jacknifeσ(f3, jestb));\nend\n\nσfjack = cat(2, σf1jack, σf2jack, σf3jack);\n\nprintln(\"\\n\\tGenerating plots in σfvsb to show σf dependence on b.\");\nusing Gadfly\nσfvsb = Plot[];\nfor i in [1:3]\n    push!(σfvsb, Gadfly.plot(\n        x = bvals,\n        y = σfjack[:,i],\n        Geom.line,\n        Geom.point,\n        Guide.xlabel(\"Bin size b\"),\n        Guide.ylabel(\"Estimated Variance\"),\n        Guide.title(\"Estimated Variance of function f$i vs. Bin Size\")\n    ));\nend\n\nprintln(\"\\n\\tCompare σfjack to naive σ̂ from part 1:\\n\")\nprintln(\"\\t\\tσ̂f1N2/σfjack[4,1] = $(σ̂f1N2/σfjack[4,1])\");\nprintln(\"\\t\\tσ̂f2N2/σfjack[4,2] = $(σ̂f2N2/σfjack[4,2])\");\nprintln(\"\\t\\tσ̂f3N2/σfjack[4,3] = $(σ̂f3N2/σfjack[4,3])\");\n", "meta": {"hexsha": "04faa6517ba6126823392d807117030d9da42a0a", "size": 1028, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "set03/q2/p4.jl", "max_stars_repo_name": "stefco/g6080", "max_stars_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "set03/q2/p4.jl", "max_issues_repo_name": "stefco/g6080", "max_issues_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "set03/q2/p4.jl", "max_forks_repo_name": "stefco/g6080", "max_forks_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7, "max_line_length": 70, "alphanum_fraction": 0.6118677043, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.872347369700144, "lm_q1q2_score": 0.7981114416242757}}
{"text": "# # [Open Circular Port Graph Examples](@id cpg_examples)\n#\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/examples/CPG_examples.ipynb)\n\nusing AlgebraicDynamics.DWDDynam\nusing AlgebraicDynamics.CPortGraphDynam\nusing AlgebraicDynamics.CPortGraphDynam: draw, barbell, gridpath, grid, meshpath\n\nusing Catlab\nusing Catlab.WiringDiagrams\nusing Catlab.WiringDiagrams.CPortGraphs\nusing Catlab.Theories\nusing Catlab.CategoricalAlgebra\n\nusing OrdinaryDiffEq\nusing DynamicalSystems\nusing Plots, Plots.PlotMeasures\n\nusing PrettyTables\n\n# ## SIR Epidemiology Model\n\n# An SIR epidemiology model has three types of people: susceptible, infected, and recovered. When a susceptible person interacts with infected person, the susceptible person also becomes infected. Over time infected people  recover. Transition rates determine the how frequently susceptible people come into contact with infected people and how fast infected people recover. The system evolves according to the law of mass action.\n\n# In a multi-city SIR model, each city has susceptible, infected, and recovered populations. To see the spread of the disease we will consider both susceptible and infected people moving between cities. To define a multi-city SIR model, we can compose multiple single-city SIR models using the composition syntax of open CPGs. The composition pattern will consist of three boxes each of which will be filled by a single-city SIR model. Ports expose the susceptible and infected populations of each city. One set of wires connect the susceptible and infected populations of cities 1 and 2. A second set of wires connect the susceptible and infected popuation of cities 2 and 3.\n\n\n## Define the composition pattern\nd₀ = OpenCPortGraph()\nadd_parts!(d₀, :Box, 1)\nd₁ = barbell(2)\nF = ACSetTransformation((Box=[2],), d₀, d₁)\nG = ACSetTransformation((Box=[1],), d₀, d₁)\nd₂ = apex(pushout(F,G))\n\n## Define the primitive systems\nβ, μ, α₁, α₂ = 0.4, 0.4, 0.01, 0.01\n\nsirfuncb = (u,x,p,t)->[-β*u[1]*u[2] - α₁*(u[1]-x[1]), # Ṡ\n                        β*u[1]*u[2] - μ*u[2] - α₂*(u[2]-x[2]), #İ\n                        μ*u[2] # Ṙ\n                        ]\nsirfuncm = (u,x,p,t)->[-β*u[1]*u[2] - α₁*(u[1]-(x[1]+x[3])/2),\n                        β*u[1]*u[2] - μ*u[2] - α₂*(u[2]-(x[2]+x[4])/2),\n                        μ*u[2]\n                       ]\n\nboundary  = ContinuousMachine{Float64}(2,3,sirfuncb, u->u[1:2])\nmiddle    = ContinuousMachine{Float64}(4,3, sirfuncm, u->u[[1,2,1,2]])\n\n## Compose\nthreecity = oapply(d₂, [boundary,middle,boundary])\n\n# First, we will approximate the solution to the three city SIR model using Euler's method. The initial condition has 100 susceptible people in each city a single infected person in the first city. We show the infected populations in each city over time.\n\nu0 = [100,1,0,100,0,0,100,0,0.0]\n\nh = 0.01\nnsteps = 100\n\nthreecity_approx = euler_approx(threecity, h)\ntraj = trajectory(threecity_approx, u0, [], nothing, nsteps)\n\nmap(traj) do u\n    return (i1=u[2], i2=u[5], i3=u[8])\nend |> pretty_table\n\n# Next, we will solve the continuous system and plot the results. Over time the infected populations increase and the susceptible populations decrease. The delays in the plots illustrate how the disease spreads from city 1 to city 2 and then from city 2 to city 3.\n\n## Solve and plot\ntspan = (0.0, 1.0)\n\nprob = ODEProblem(threecity, u0, tspan)\nsol = solve(prob, Tsit5(); dtmax = 0.01)\n\nplot(sol, lw=2, title = \"SIR Epidemiology Model\", bottom_margin=10mm, left_margin=10mm, \n    label=[\"S\" \"I\" \"R\"])\n\n\n# ## Cellular automata\n\n#  Circular port graphs are particularly useful for modeling systems where the composition pattern is given by a grid and where the dynamics are repetative. In the case of cellular automata the composition pattern is a row of $n$ cells each of which is connected to its two neighbors. The primitive systems are identical machines whose discrete dynamics are a specified rule. See [here](https://mathworld.wolfram.com/ElementaryCellularAutomaton.html) for a complete set of rules and the patterns they generate.\n\nfunction Rule(k::Int)\n    (left_neighbor, x, right_neighbor) -> \n    Bool(digits(k, base=2, pad=8)[1 + right_neighbor + 2*x + 4*left_neighbor])\nend\n\n## Define the composition pattern\nn = 100\nrow = apex(gridpath(n, 1))\n\n## Define the primitive system which will be repeated for each cell\nrule = DiscreteMachine{Bool}(2, 1, 2, (u, x, p, t)->Rule(p)(x[2], u[1], x[1]), \n            u->[u[1], u[1]])\n\n## Compose\nautomaton = oapply(row, rule)\n\n## Solve and plot\nu0 = zeros(Int, n); u0[Int(n/2)] = 1\n\nrule_number = 126\ntraj = trajectory(automaton, u0, [0,0], rule_number, 100)\nspy(Matrix(traj))\n\n\n", "meta": {"hexsha": "d4bbe911958ce505a1eb8067d3a455f461a019d0", "size": 4690, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/CPG_examples.jl", "max_stars_repo_name": "bakirtzisg/AlgebraicDynamics.jl", "max_stars_repo_head_hexsha": "0500f2d3bbdedb0b441575f6e9a3cdb9eec0a398", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/CPG_examples.jl", "max_issues_repo_name": "bakirtzisg/AlgebraicDynamics.jl", "max_issues_repo_head_hexsha": "0500f2d3bbdedb0b441575f6e9a3cdb9eec0a398", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/CPG_examples.jl", "max_forks_repo_name": "bakirtzisg/AlgebraicDynamics.jl", "max_forks_repo_head_hexsha": "0500f2d3bbdedb0b441575f6e9a3cdb9eec0a398", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-05T17:37:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-05T17:37:52.000Z", "avg_line_length": 43.4259259259, "max_line_length": 676, "alphanum_fraction": 0.7119402985, "num_tokens": 1355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.8723473614033683, "lm_q1q2_score": 0.7981114279611585}}
{"text": "using Statistics, Random, Distributions\n\n# returns the variable (or matrix), lagged p times,\n# with the first p rows filled with ones (to avoid divide errors)\n# remember to drop those rows before doing analysis\nfunction lag(x,p::Int64)\n\tn = size(x,1)\n\tlagged_x = zeros(eltype(x),n,p)\n\tlagged_x = [ones(p); x[1:n-p]]\nend\n\n# lags of a vector from 1 to p in a p column array\nfunction  lags(x,p)\n\tn = size(x,1)\n\tlagged_x = zeros(eltype(x),n,p)\n\tfor i = 1:p\n\t\tlagged_x[:,i] = lag(x,i)\n\tend\n    return lagged_x\nend\n\n# compute moving average using p most recent values, including current value\nfunction ma(x, p)\n    m = similar(x)\n    for i = p:size(x,1)\n        m[i] = mean(x[i-p+1:i])\n    end\n    return m\nend\n\n# auxiliary model: HAR-RV\n# Corsi, Fulvio. \"A simple approximate long-memory model\n# of realized volatility.\" Journal of Financial Econometrics 7,\n# no. 2 (2009): 174-196.\nfunction HAR(y)\n    ylags = lags(y,10)\n    X = [ones(size(y,1)) ylags[:,1]  mean(ylags[:,1:4],dims=2) mean(ylags[:,1:10],dims=2)]\n    # drop missings\n    y = y[11:end]\n    X = X[11:end,:]\n    βhat = X\\y\n    σhat = std(y-X*βhat)     \n    vcat(βhat,σhat)\nend\n\nfunction aux_stat(y)\n    y, m, s  = stnorm(abs.(y))\n    # look for evidence of volatility clusters\n    mm = ma(y,5)\n    mm = mm[5:end]\n    clusters = quantile(mm,0.75) -quantile(mm, 0.25)\n    ϕ = HAR(y)\n    vcat(m, s, clusters, ϕ)\nend\n\n# the dgp: simple discrete time stochastic volatility (SV) model\nfunction SVmodel(σe, ρ, σu, n, shocks_u, shocks_e)\n    burnin = size(shocks_u,1) - n\n    hlag = 0.0\n    h = ρ.*hlag .+ σu.*shocks_u[1] # figure out type\n    y = σe.*exp(h./2.0).*shocks_e[1]\n    ys = zeros(eltype(y),n)\n    for t = 1:burnin+n\n        h = ρ.*hlag .+ σu.*shocks_u[t]\n        y = σe.*exp(h./2.0).*shocks_e[t]\n        if t > burnin \n            ys[t-burnin] = y\n        end    \n        hlag = h\n    end\n    #plot(ys)\n    sqrt(n)*aux_stat(ys)\nend\n\n", "meta": {"hexsha": "3f923e760e28319f088ff58e09a8791068a03b7f", "size": 1895, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/SBEM/NUTS/SVlib.jl", "max_stars_repo_name": "nilshg/Econometrics", "max_stars_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "Examples/SBEM/NUTS/SVlib.jl", "max_issues_repo_name": "nilshg/Econometrics", "max_issues_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "Examples/SBEM/NUTS/SVlib.jl", "max_forks_repo_name": "nilshg/Econometrics", "max_forks_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 25.2666666667, "max_line_length": 90, "alphanum_fraction": 0.6036939314, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973294, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7980460624450333}}
{"text": "#=\n  From Joost-Pieter Katoen\n  \"Probabilistic Programming Quantitative Modeling for the Masses?\"\n  (MMB 2018 Conference, Erlangen)\n  \n  Slide 4:\n  \"\"\"\n  How likely does a student end up with a bad mood after getting\n  a bad grade for an easy exam, given that she is well prepared?\n  \"\"\"\n\nDistributions of variable difficulty\neasy       =>    6022  (0.602200)\nhard       =>    3978  (0.397800)\n\nDistributions of variable preparation\ngood       =>   10000  (1.000000)\n\nDistributions of variable grade\ngood       =>    6821  (0.682100)\nbad        =>    3179  (0.317900)\n\nDistributions of variable mood\nbad        =>    5004  (0.500400)\ngood       =>    4996  (0.499600)\n\n  Cf ~/webppl/student_mood_after_exam.wppl\n\n=#\nusing Turing, StatsPlots, Distributions\ninclude(\"jl_utils.jl\")\n\n@model function student_mood_after_exam()\n    bad = 1\n    good = 2\n    badGood = [bad,good]\n\n    easy = 1\n    hard = 2\n    \n    difficulty ~ Categorical([0.6,0.4]) # [easy,hard]\n    \n    preparation ~ Categorical([0.7,0.3]) # badGood\n    \n    grade ~\n        (difficulty==easy && preparation==bad)  ? Categorical([0.95,0.05]) : # badGood\n        (difficulty==easy && preparation==good) ? Categorical([0.5,0.5])   :\n        (difficulty==hard && preparation==bad)  ? Categorical([0.6,0.4])   :\n        (difficulty==hard && preparation==good) ? Categorical([0.05,0.95]) : Dirac(easy)\n    \n    mood ~ grade == bad ? # badGood\n        Categorical([0.9,0.1]) :\n        Categorical([0.3,0.7])\n    \n    \n    # true ~ Dirac(difficulty == easy)\n    true ~ Dirac(preparation == good)\n    # true ~ Dirac(grade == bad)\n    # true ~ Dirac(mood == bad)\n\nend\n\nmodel = student_mood_after_exam()\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(5), 10_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 10_000)\n\ndisplay(chns)\n# display(plot(chns))\n\nbad_good = [\"bad\",\"good\"]\nshow_var_dist_pct(chns, :difficulty, [\"easy\",\"hard\"])\n\nprintln()\nshow_var_dist_pct(chns, :preparation, bad_good)\n\nprintln()\nshow_var_dist_pct(chns, :grade, bad_good)\n\nprintln()\nshow_var_dist_pct(chns, :mood, bad_good)\n", "meta": {"hexsha": "221cf6967cad47856ac400a16c13d3bd8056bd63", "size": 2129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/student_mood_after_exam.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/student_mood_after_exam.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/student_mood_after_exam.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 25.0470588235, "max_line_length": 88, "alphanum_fraction": 0.6294034758, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303728259492, "lm_q2_score": 0.8615382165412808, "lm_q1q2_score": 0.798046062020222}}
{"text": "# indicator of the L2 norm ball with given radius\n\nexport IndBallL2\n\n\"\"\"\n**Indicator of a Euclidean ball**\n\n    IndBallL2(r=1.0)\n\nReturns the indicator function of the set\n```math\nS = \\\\{ x : \\\\|x\\\\| \\\\leq r \\\\},\n```\nwhere ``\\\\|\\\\cdot\\\\|`` is the ``L_2`` (Euclidean) norm. Parameter `r` must be positive.\n\"\"\"\nstruct IndBallL2{R <: Real} <: ProximableFunction\n    r::R\n    function IndBallL2{R}(r::R) where {R <: Real}\n        if r <= 0\n            error(\"parameter r must be positive\")\n        else\n            new(r)\n        end\n    end\nend\n\nis_convex(f::IndBallL2) = true\nis_set(f::IndBallL2) = true\n\nIndBallL2(r::R=1.0) where {R <: Real} = IndBallL2{R}(r)\n\nfunction (f::IndBallL2)(x::AbstractArray{T}) where {R <: Real, T <: RealOrComplex{R}}\n    if isapprox_le(norm(x), f.r, atol=eps(R), rtol=sqrt(eps(R)))\n        return R(0)\n    end\n    return R(Inf)\nend\n\nfunction prox!(y::AbstractArray{T}, f::IndBallL2, x::AbstractArray{T}, gamma::R=R(1)) where {R <: Real, T <: RealOrComplex{R}}\n    scal = f.r/norm(x)\n    if scal > 1\n        y .= x\n        return R(0)\n    end\n    for k in eachindex(x)\n        y[k] = scal*x[k]\n    end\n    return R(0)\nend\n\nfun_name(f::IndBallL2) = \"indicator of an L2 norm ball\"\nfun_dom(f::IndBallL2) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::IndBallL2) = \"x ↦ 0 if ||x|| ⩽ r, +∞ otherwise\"\nfun_params(f::IndBallL2) = \"r = $(f.r)\"\n\nfunction prox_naive(f::IndBallL2, x::AbstractArray{T}, gamma::R=R(1)) where {R <: Real, T <: RealOrComplex{R}}\n    normx = norm(x)\n    if normx > f.r\n        y = (f.r/normx)*x\n    else\n        y = x\n    end\n    return y, R(0)\nend\n", "meta": {"hexsha": "04b441798bd989c7a6380315fcc1a9a18fbc402d", "size": 1608, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indBallL2.jl", "max_stars_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_stars_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2016-10-29T12:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:11:52.000Z", "max_issues_repo_path": "src/functions/indBallL2.jl", "max_issues_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_issues_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2016-10-26T16:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T20:38:48.000Z", "max_forks_repo_path": "src/functions/indBallL2.jl", "max_forks_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_forks_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T10:40:24.000Z", "avg_line_length": 24.7384615385, "max_line_length": 126, "alphanum_fraction": 0.5845771144, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7980460538936165}}
{"text": "# indicator of the ball of matrices with (at most) a given rank\n\nusing LinearAlgebra\nusing TSVD\n\nexport IndBallRank\n\n\"\"\"\n**Indicator of rank ball**\n\n    IndBallRank(r=1)\n\nReturns the indicator function of the set of matrices of rank at most `r`:\n```math\nS = \\\\{ X : \\\\mathrm{rank}(X) \\\\leq r \\\\},\n```\nParameter `r` must be a positive integer.\n\"\"\"\nstruct IndBallRank{I <: Integer} <: ProximableFunction\n    r::I\n    function IndBallRank{I}(r::I) where {I <: Integer}\n        if r <= 0\n            error(\"parameter r must be a positive integer\")\n        else\n            new(r)\n        end\n    end\nend\n\nis_set(f::IndBallRank) = true\nis_prox_accurate(f::IndBallRank) = false\n\nIndBallRank(r::I=1) where {I <: Integer} = IndBallRank{I}(r)\n\nfunction (f::IndBallRank)(x::AbstractArray{T, 2}) where {R <: Real, T <: RealOrComplex{R}}\n    maxr = minimum(size(x))\n    if maxr <= f.r return R(0) end\n    U, S, V = tsvd(x, f.r+1)\n    # the tolerance in the following line should be customizable\n    if S[end]/S[1] <= 1e-7\n        return R(0)\n    end\n    return R(Inf)\nend\n\nfunction prox!(y::AbstractMatrix{T}, f::IndBallRank, x::AbstractMatrix{T}, gamma::R=R(1)) where {R <: Real, T <: RealOrComplex{R}}\n    maxr = minimum(size(x))\n    if maxr <= f.r\n        y .= x\n        return R(0)\n    end\n    U, S, V = tsvd(x, f.r)\n    # TODO: the order of the following matrix products should depend on the shape of x\n    M = S .* V'\n    mul!(y, U, M)\n    return R(0)\nend\n\nfun_name(f::IndBallRank) = \"indicator of the set of rank-r matrices\"\nfun_dom(f::IndBallRank) = \"AbstractArray{Real,2}, AbstractArray{Complex,2}\"\nfun_expr(f::IndBallRank) = \"x ↦ 0 if rank(x) ⩽ r, +∞ otherwise\"\nfun_params(f::IndBallRank) = \"r = $(f.r)\"\n\nfunction prox_naive(f::IndBallRank, x::AbstractMatrix{T}, gamma::R=R(1)) where {R <: Real, T <: RealOrComplex{R}}\n    maxr = minimum(size(x))\n    if maxr <= f.r\n        y = x\n        return y, R(0)\n    end\n    F = svd(x)\n    y = F.U[:,1:f.r]*(Diagonal(F.S[1:f.r])*F.V[:,1:f.r]')\n    return y, R(0)\nend\n", "meta": {"hexsha": "221f37200a49ba593357ec8671fcda3922d31ccf", "size": 2005, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indBallRank.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_stars_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2016-10-29T12:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:11:52.000Z", "max_issues_repo_path": "src/functions/indBallRank.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_issues_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2016-10-26T16:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T20:38:48.000Z", "max_forks_repo_path": "src/functions/indBallRank.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_forks_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T10:40:24.000Z", "avg_line_length": 27.0945945946, "max_line_length": 130, "alphanum_fraction": 0.6049875312, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915912, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.7980412421294126}}
{"text": "\"\"\"\n    Ridge(alpha = 0.1)\nRidge Regression. `alpha` is the value multiplied by regularization term.\n\n# Example\n```jldoctest regression\njulia> model = Ridge()\nRidge(Float64[], 0.1)\n\njulia> fit!(model, x, t)\n3-element Vector{Float64}:\n -0.5635468573581848\n  2.1185952951687614\n 40.334109796666425\n\njulia> model(x)\n20-element Vector{Float64}:\n 175.12510514593038\n 170.28763505842625\n 149.54478779081344\n 159.7466476176333\n 165.4525001910219\n 129.6935485937018\n 164.79709438985097\n 161.3621431448216\n 170.17418141858434\n 176.95192713546982\n 174.8078461898064\n 168.76930346791391\n 171.09202561187362\n 170.58861763111338\n 155.04089855305028\n 168.05151465675456\n 149.76311329450505\n 169.5183634524783\n 141.7695072903308\n 163.94744858842117\n```\n\"\"\"\nmutable struct Ridge\n    w::Array\n    α::Float64\n    Ridge(alpha = 0.1) = new(Array{Float64}(undef, 0), alpha)\nend\n\nfunction fit!(model::Ridge, x, t)\n    check_size(x, t)\n    x = expand(x)\n    n = size(x, 1)\n    _I = Matrix{Float64}(I, n, n)\n    model.w = inv(x * x' .+ model.α * _I) * x * t\nend\n\n(model::Ridge)(x) = expand(x)' * model.w", "meta": {"hexsha": "d2bca47bac7aee84060815abffd0a2e67f83f9fc", "size": 1079, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Regression/RR.jl", "max_stars_repo_name": "MommaWatasu/LearningHorse.jl", "max_stars_repo_head_hexsha": "f7cd74a3c2a1b09bd736844e30970b19cd3ae1d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-12-08T05:42:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T08:14:39.000Z", "max_issues_repo_path": "src/Regression/RR.jl", "max_issues_repo_name": "MommaWatasu/LearningHorse.jl", "max_issues_repo_head_hexsha": "f7cd74a3c2a1b09bd736844e30970b19cd3ae1d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-12T12:32:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-12T12:45:49.000Z", "max_forks_repo_path": "src/Regression/RR.jl", "max_forks_repo_name": "MommaWatasu/LearningHorse.jl", "max_forks_repo_head_hexsha": "f7cd74a3c2a1b09bd736844e30970b19cd3ae1d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-06T08:14:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T08:14:43.000Z", "avg_line_length": 19.9814814815, "max_line_length": 73, "alphanum_fraction": 0.7126969416, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7980412406306026}}
{"text": "#=\nThe number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.\n\nFind the sum of the only eleven primes that are both truncatable from left to right and right to left.\n\nNOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.\n=#\ninclude(\"projecteulerutils.jl\")\nusing Primes\n\nfunction istruncatableprime(a)\n  da = reverse(digits(a))\n  f1,f2 = copy(da), copy(da)\n  for i in 1:length(da)-1\n    deleteat!(f1,1)\n    pop!(f2)\n    if !isprime(nd(f1)) || !isprime(nd(f2))\n      return false\n    end\n  end\n  true\nend\n\nfunction calc()\n  i,count,total = 10,0,0\n  while count < 11\n    if isprime(i) && istruncatableprime(i)\n      count += 1\n      total += i\n    end\n    i += 1\n  end\n  total\nend\n@time println(calc())\n", "meta": {"hexsha": "f344dfa90c02d52ddbce4a4d82aba86d1fb26d6b", "size": 901, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p37.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p37.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p37.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 25.0277777778, "max_line_length": 247, "alphanum_fraction": 0.6736958935, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533069832974, "lm_q2_score": 0.855851154320682, "lm_q1q2_score": 0.7980412391317924}}
{"text": "module solver\n\nfunction euler(y0::AbstractArray{Float64}, f, a::Float64, b::Float64, h::Float64)::AbstractArray{Float64}\n    k = ceil(Integer, (b - a) / h)\n    t_range = range(a, stop=b, length=k)\n    y = y0\n    for t_n = t_range\n        if t_n == a\n            continue\n        end\n        y_n = y[:,end]\n        y_next = y_n + h * f(t_n, y_n)\n        y = [y y_next]\n    end\n    return y\nend\n\nfunction midpoint(y0::AbstractArray{Float64}, f, a::Float64, b::Float64, h::Float64)::AbstractArray{Float64}\n    k = ceil(Integer, (b - a) / h)\n    t_range = range(a, stop=b, length=k)\n    y = y0\n    for t_n = t_range\n        if t_n == a\n            continue\n        end\n        y_n = y[:,end]\n        y_next = y_n + h * f(t_n + h / 2.0, y_n + h / 2.0 * f(t_n, y_n))\n        y = [y y_next]\n    end\n    return y\nend\n\n\n\nend # module\n", "meta": {"hexsha": "c11d8368cc980b178a8022805ff469f8697aa987", "size": 825, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ode/solver/solver.jl", "max_stars_repo_name": "applied-math-coding/article-snippets", "max_stars_repo_head_hexsha": "3ac3dc58905a9f6c662e3922dafc9b230a9ffd6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ode/solver/solver.jl", "max_issues_repo_name": "applied-math-coding/article-snippets", "max_issues_repo_head_hexsha": "3ac3dc58905a9f6c662e3922dafc9b230a9ffd6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ode/solver/solver.jl", "max_forks_repo_name": "applied-math-coding/article-snippets", "max_forks_repo_head_hexsha": "3ac3dc58905a9f6c662e3922dafc9b230a9ffd6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9166666667, "max_line_length": 108, "alphanum_fraction": 0.5248484848, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915913, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7980412352726893}}
{"text": "module BasesAndSamples\n\nusing Combinatorics\n\nexport basis_monomial, basis_laguerre, basis_jacobi, basis_chebyshev, basis_gegenbauer\nexport sample_points_simplex, sample_points_padua, sample_points_rescaled_laguerre, sample_points_chebyshev, sample_points_chebyshev_mod\n\n\"\"\"\n    basis_monomial(d::Int, x...)\n\nGenerate the monomial basis in variables x... up to degree d (inclusive).\n\"\"\"\nfunction basis_monomial(d::Int, x...)\n    n = length(x)\n    if n > 1\n        q = Vector{typeof(prod(one.(x)))}(undef, binomial(n+d,d))\n    elseif n == 1\n        q = Vector{typeof(one(x...))}(undef, binomial(n+d,d))\n    end\n    idx = 1\n    for k=0:d\n        for exponent in multiexponents(n,k)\n            q[idx] = prod([x[i]^exponent[i] for i=1:length(exponent)])\n            idx+=1\n        end\n    end\n    return q\nend\n\n\"\"\"\n    basis_laguerre(d::Integer, alpha, x)\n\nGenerate the Laguerre polynomials with parameter alpha up to degree d (inclusive). (https://en.wikipedia.org/wiki/Laguerre_polynomials)\n\"\"\"\nfunction basis_laguerre(d::Integer, alpha, x)\n    v = Vector{typeof(one(alpha) * one(x))}(undef, 1 + d)\n    v[1] = one(x)\n    d == 0 && return v\n    v[2] = 1 + alpha - x\n    d == 1 && return v\n    for l = 2:d\n        v[l+1] = 1 // big(l) * ((2l - 1 + alpha - x) * v[l] - (l + alpha - 1) * v[l-1])\n    end\n    return v\nend\n\n\"\"\"\n    basis_jacobi(d::Integer, alpha, beta, x, normalized = true)\n\nGenerate the Jacobi polynomials with parameters alpha and beta up to degree d (inclusive). (https://en.wikipedia.org/wiki/Jacobi_polynomials)\n\"\"\"\nfunction basis_jacobi(d::Integer, alpha, beta, x, normalized = true)\n    q = Vector{typeof(one(alpha) * one(x))}(undef, d + 1)\n    q[1] = one(x)\n    d == 0 && return q\n    q[2] = x # normalized\n    if !normalized\n        q[2] *= (alpha + 1)\n    end\n    d == 1 && return q\n    for k = 2:d\n        # what if alpha+beta = -n for some integer 1 <= n < 2d ?\n        q[k+1] =\n            (2 * k + alpha + beta - 1) /\n            BigFloat(2k * (k + alpha + beta) * (2k + alpha + beta - 2)) *\n            ((2 * k + alpha + beta) * (2k + alpha + beta - 2) * x + beta^2 - alpha^2) *\n            q[k] + -2 * (k + alpha - 1) * (k + beta - 1) * (2 * k + alpha + beta) * q[k-1]\n    end\n    return q\nend\n\n\"\"\"\n    basis_chebyshev(d::Int,x)\n\nGenerate a basis of chebyshev polynomials up to degree d (inclusive). (https://en.wikipedia.org/wiki/Chebyshev_polynomials)\n\"\"\"\nfunction basis_chebyshev(d::Int,x)\n    v = Vector{typeof(one(x))}(undef, 1 + d)\n    v[1] = one(x)\n    d == 0 && return v\n    v[2] = x\n    d == 1 && return v\n    for l = 2:d\n        v[l+1] = 2x*v[l] - v[l-1]\n    end\n    return v\nend\n\n\n\"\"\"\n    basis_gegenbauer(d, n, x)\n\nBasis for the Gegenbauer polynomials in dimension n up to degree d.\n This is the Gegenbauer polynomial with parameter lambda = n/2-1,\n or the Jacobi polynomial with alpha = beta = (n-3)/2.\n Normalized to evaluate to 1 at 1.\n Taken from arxiv/2001.00256, ancillary files, SemidefiniteProgramming.jl.\n\"\"\"\nfunction basis_gegenbauer(d, n, x)\n    v = Vector{typeof(one(x))}(undef, 1 + d)\n    v[1] = one(x)\n    d == 0 && return v\n    v[2] = x\n    d == 1 && return v\n    for l = 2:d\n        v[l+1] = (2l + n - 4) // (l + n - 3) * x * v[l] - (l - 1) // (l + n - 3) * v[l-1]\n    end\n    return v\nend\n\n\"\"\"\n    sample_points_simplex(n, d)\n\nGenerate the rational sample points in the unit simplex with denominator d.\n\"\"\"\nfunction sample_points_simplex(n, d)\n    #rational points in the unit simplex with denominator d\n    #probably not very efficient, but I dont know how to do it better for general n.\n    x = [zeros(BigFloat, n) for i = 1:binomial(n + d, d)] #need n+d choose d points for a unisolvent set, if symmetry is not used.\n    idx = 1\n    for I in CartesianIndices(ntuple(k -> 0:d, n)) #all tuples with elements in 0:d of length n\n        if sum(Tuple(I)) <= d #in unit simplex\n            x[idx] = [i / BigFloat(d) for i in Tuple(I)]\n            idx += 1\n        end\n    end\n    return x\nend\n\n\"\"\"\n    sample_points_padua(d)\n\nGenerate the Padua points for degree d. (https://en.wikipedia.org/wiki/Padua_points)\n\"\"\"\nfunction sample_points_padua(d)\n    #padua points:\n    z = [Array{BigFloat}(undef, 2) for i = 1:binomial(2 + d, d)]\n    z_idx = 1\n    for j = 0:d\n        delta_j = j % 2 == d % 2 == 1 ? 1 : 0\n        mu_j = cospi(j / d)\n        for k = 1:(div(d, 2)+1+delta_j)\n            eta_k = j % 2 == 1 ? cospi((2 * k - 2) / (d + 1)) : cospi((2 * k - 1) / (d + 1))\n            z[z_idx] = [mu_j, eta_k]\n            z_idx += 1\n        end\n    end\n    return z\nend\n\n\"\"\"\n    sample_points_rescaled_laguerre(d)\n\nGenerate 'rescaled laguerre' points, as in SDPB.\n\"\"\"\nfunction sample_points_rescaled_laguerre(d)\n    #as done in sdpb: ('rescaled Laguerre')\n    # x[k] = sqrt(pi)/(64*(d+1)*log( 3- 2*sqrt(2))) * (-1+4*k)^2, with k=0:d\n    constant = -sqrt(BigFloat(pi)) / (64 * (d + 1) * log(3 - 2 * sqrt(BigFloat(2))))\n    x = zeros(BigFloat, d + 1)\n    for k = 0:d\n        x[k+1] = constant * (-1 + 4 * k)^2\n    end\n    return [[i] for i in x]\nend\n\n\"\"\"\n    sample_points_chebyshev(d, a = -1, b = 1)\n\nGenerate the d+1 chebyshev points in [a,b]. (https://en.wikipedia.org/wiki/Chebyshev_nodes)\n\"\"\"\nfunction sample_points_chebyshev(d, a = -1, b = 1)\n    #roots of chebyshev polynomials of the first kind, unisolvent for polynomials up to degree d\n    points = [\n        (a + b) / BigFloat(2) +\n        (b - a) / BigFloat(2) * cos((2k - 1) / BigFloat(2(d + 1)) * BigFloat(pi)) for\n        k = 1:d+1\n    ]\n    return [[i] for i in points]\nend\n\n\"\"\"\n    sample_points_chebyshev_mod(d, a = -1, b = 1)\n\nGenerate the d+1 modified chebyshev points in [a,b], the chebyshev points divided by cos(pi/(2(d+1))).\n\"\"\"\nfunction sample_points_chebyshev_mod(d, a = -1, b = 1)\n    #roots of chebyshev polynomials of the first kind, divided by cos(pi/2(d+1)) to get a lower lebesgue constant\n    points = [\n        (a + b) / BigFloat(2) +\n        (b - a) / BigFloat(2) * cos((2k - 1) / BigFloat(2(d + 1)) * BigFloat(pi)) /\n        cos(BigFloat(pi) / 2(d + 1)) for k = 1:d+1\n    ]\n    return [[i] for i in points]\nend\n\nend # end module\n", "meta": {"hexsha": "ea6e6573860cc404493b50e18f9e2444a54c9046", "size": 6060, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BasesAndSamples.jl", "max_stars_repo_name": "nanleij/BasesAndSamples.jl", "max_stars_repo_head_hexsha": "f8e5c426fe53b0c7420abd2bafdb8b936c6163e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BasesAndSamples.jl", "max_issues_repo_name": "nanleij/BasesAndSamples.jl", "max_issues_repo_head_hexsha": "f8e5c426fe53b0c7420abd2bafdb8b936c6163e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-06T16:30:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T16:30:41.000Z", "max_forks_repo_path": "src/BasesAndSamples.jl", "max_forks_repo_name": "nanleij/BasesAndSamples.jl", "max_forks_repo_head_hexsha": "f8e5c426fe53b0c7420abd2bafdb8b936c6163e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6060606061, "max_line_length": 141, "alphanum_fraction": 0.5826732673, "num_tokens": 2091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291502, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.798041229062078}}
{"text": "module Transformation\n\nexport Vec, Quat, Transf, dot, cross, magnitude, norm, ×, slerp, unit\n\n\"\"\"\n    Vec - three dimensional vector.\n\n# Examples\n```julia-repl\njulia> Vec(1, 2, 3)\nVec(1, 2, 3)\n```\n\"\"\"\nstruct Vec\n    x::Real\n    y::Real\n    z::Real\n    function Vec(x::Real=0, y::Real=0, z::Real=0)::Vec\n        new(x, y, z)\n    end\nend\n\nfunction Base.:+(a::Vec, b::Vec)::Vec\n    Vec(\n        a.x + b.x,\n        a.y + b.y,\n        a.z + b.z\n    )\nend\n\nfunction Base.:-(a::Vec, b::Vec)::Vec\n    Vec(\n        a.x - b.x,\n        a.y - b.y,\n        a.z - b.z\n    )\nend\n\nfunction Base.:-(a::Vec)::Vec\n    Vec(\n        -a.x,\n        -a.y,\n        -a.z\n    )\nend\n\n\"\"\"\n    dot(a::Vec, b::Vec)::Vec\n\nCompute the dot product of two vectors.\n\"\"\"\nfunction dot(a::Vec, b::Vec)\n    a.x * b.x + a.y * b.y + a.z * b.z\nend\n\n\"\"\"\n    cross(a::Vec, b::Vec)::Vec\n\nCompute the cross product of two vectors.\n\"\"\"\nfunction cross(a::Vec, b::Vec)::Vec\n    Vec(\n        a.y * b.z - a.z * b.y,\n        a.z * b.x - a.x * b.z,\n        a.x * b.y - a.y * b.x\n    )\nend\n\n\"\"\"\n    ×(a::Vec, b::Vec)::Vec\n\nCompute the cross product of two vectors.\n\"\"\"\nfunction ×(a::Vec, b::Vec)::Vec\n    cross(a, b)\nend\n\nfunction Base.:*(a::Real, b::Vec)::Vec\n    Vec(\n        a * b.x,\n        a * b.y,\n        a * b.z\n    )\nend\n\nfunction Base.:*(a::Vec, b::Real)::Vec\n    Vec(\n        a.x * b,\n        a.y * b,\n        a.z * b\n    )\nend\n\nfunction Base.:/(a::Vec, b::Real)::Vec\n    Vec(\n        a.x / b,\n        a.y / b,\n        a.z / b\n    )\nend\n\nfunction Base.isequal(a::Vec, b::Vec)::Bool\n    a.x == b.x && a.y == b.y && a.z == b.z\nend\n\n\"\"\"\n    norm(a::Vec)::Real\n\nCompute the Euclidean norm of the given vector.\n\"\"\"\nfunction norm(a::Vec)::Real\n    √(a.x^2 + a.y^2 + a.z^2)\nend\n\n\"\"\"\n    unit(a::Vec)::Vec\n\nCompute the unit vector colinear to the given one.\n\"\"\"\nfunction unit(a::Vec)::Vec\n    a / norm(a)\nend\n\n\"\"\"\n    round(a::Vec)::Vec\n\nCompute the vector with it's elements rounder to nearest value.\n\"\"\"\nfunction Base.round(a::Vec)::Vec\n    Vec(\n        round(a.x),\n        round(a.y),\n        round(a.z)\n    )\nend\n\n\"\"\"\n    Quat - hypercomplex number.\n\nUnit quaternions are used for rotation representation.\n\n# Examples\n```julia-repl\njulia> # 120° counterclockwise rotation around the (1, 1, 1) axis\njulia> Quat(2π/3, Vec(1, 1, 1))\nQuat(0.5, 0.5, 0.5, 0.5)\n\njulia> # 45° clockwise rotation around the (1, 0, 0) axis\njulia> Quat(-π/4, Vec(1, 0, 0))\nQuat(0.9238795325112867, -0.3826834323650898, -0.0, -0.0)\n```\n\"\"\"\nstruct Quat\n    w::Real\n    x::Real\n    y::Real\n    z::Real\n    function Quat(w::Real=1, x::Real=0, y::Real=0, z::Real=0)::Quat\n        new(w, x, y, z)\n    end\n    \n    function Quat(angle::Real, axis::Vec)::Quat\n        w = cos(angle / 2)\n        xyz = unit(axis) * sin(angle / 2)\n        Quat(w, xyz.x, xyz.y, xyz.z)\n    end\nend\n\nfunction Base.:+(a::Quat, b::Quat)::Quat\n    Quat(\n        a.w + b.w,\n        a.x + b.x,\n        a.y + b.y,\n        a.z + b.z\n    )\nend\n\nfunction Base.:-(a::Quat, b::Quat)::Quat\n    Quat(\n        a.w - b.w,\n        a.x - b.x,\n        a.y - b.y,\n        a.z - b.z\n    )\nend\n\nfunction Base.:*(a::Quat, b::Quat)::Quat\n    Quat(\n        a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,\n        a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,\n        a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,\n        a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w\n    )\nend\n\nfunction Base.:*(q::Quat, v::Vec)::Vec\n    r = q * Quat(0, v.x, v.y, v.z) * conj(q)\n    Vec(r.x, r.y, r.z)\nend\n\nfunction Base.:*(a::Quat, b::Real)::Quat\n    Quat(\n        a.w * b,\n        a.x * b,\n        a.y * b,\n        a.z * b\n    )\nend\n\nfunction Base.:*(a::Real, b::Quat)::Quat\n    Quat(\n        a * b.w,\n        a * b.x,\n        a * b.y,\n        a * b.z\n    )\nend\n\nfunction dot(a::Quat, b::Quat)::Real\n    a.w * b.w + a.x * b.x + a.y * b.y + a.z * b.z\nend\n\nfunction Base.:/(a::Quat, b::Real)::Quat\n    Quat(\n        a.w / b,\n        a.x / b,\n        a.y / b,\n        a.z / b\n    )\nend\n\n\"\"\"\n    conj(a::Quat)::Quat\n\nCompute the quaternion conjugate.\nIf the quaternion is unit, it's conjugate represents the reverse rotation.\n\n# Examples\n```julia-repl\njulia> q = Quat(π, Vec(1, 1, 1))\njulia> q * conj(q)\nQuat(1.0, 0.0, 0.0, 0.0)\n```\n\"\"\"\nfunction Base.conj(a::Quat)::Quat\n    Quat(\n        a.w,\n        -a.x,\n        -a.y,\n        -a.z\n    )\nend\n\n\"\"\"\n    norm(a::Quat)::Real\n\nCompute the quaternion norm.\n\"\"\"\nfunction norm(a::Quat)::Real\n    √(a.w^2 + a.x^2 + a.y^2 + a.z^2)\nend\n\n\"\"\"\n    unit(a::Quat)::Quat\n\nCompute the unit quaternion colinear to the given one.\n\"\"\"\nfunction unit(a::Quat)::Quat\n    a / norm(a)\nend\n\nfunction slerp(a::Quat, b::Quat, t)::Quat\n    d = dot(a, b)\n    if d < 0\n        b = -b\n        d = -d\n    end\n    if d > 0.9995\n        result = a + (a - b) * t\n        return norm(result)\n    end\n    theta0 = acos(d)\n    theta = theta0 * t\n    sinTheta = sin(theta)\n    sinTheta0 = sin(theta0)\n\n    s1 = sinTheta / sinTheta0\n    s0 = cos(theta) - d * s1\n    return a * s0 + b * s1\nend\n\n\"\"\"\n    Transf - spatial transformation representation.\n\nThe transformation consists of consecutive translation on vector `v` and rotation on `q` quaternion.\n\"\"\"\nstruct Transf\n    v::Vec\n    q::Quat\n    function Transf(v::Vec=Vec(), q::Quat=Quat())::Transf\n        new(v, q)\n    end\nend\n\nfunction Base.:+(a::Transf, b::Transf)::Transf\n    Transf(\n        a.v + a.q * b.v,\n        a.q * b.q\n    )\nend\n\nfunction Base.:+(a::Transf, b::Vec)::Vec\n    a.v + a.q * b\nend\n\n\"\"\"\n    conj(a::Transf)::Transf\n\nCompute such transformation, that `a + conj(a)` equals to zero transformation.\n\n# Examples\n```julia-repl\njulia> t = Transf(Vec(1, 2, 3), Quat(π/3, Vec(1, 1, 0)))\njulia> t + conj(t)\nTransf(Vec(0.0, 0.0, 0.0), Quat(1.0, 0.0, 0.0, 0.0))\n```\n\"\"\"\nfunction Base.conj(a::Transf)::Transf\n    q = conj(a.q)\n    Transf(\n        q * (-a.v),\n        q\n    )\nend\n\nend\n", "meta": {"hexsha": "9d4b65053b3f2690f0274a0dba09de66f9ac89ff", "size": 5812, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Transformation.jl", "max_stars_repo_name": "red-hara/Transformation", "max_stars_repo_head_hexsha": "a654ec3b0a0a5e476e25f220d6b5bf55535838dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Transformation.jl", "max_issues_repo_name": "red-hara/Transformation", "max_issues_repo_head_hexsha": "a654ec3b0a0a5e476e25f220d6b5bf55535838dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Transformation.jl", "max_forks_repo_name": "red-hara/Transformation", "max_forks_repo_head_hexsha": "a654ec3b0a0a5e476e25f220d6b5bf55535838dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.2462908012, "max_line_length": 100, "alphanum_fraction": 0.4993117688, "num_tokens": 2158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7980177497433596}}
{"text": "\"\"\"\n    poisson_eigenvalues(N, L, dim, ::Periodic)\n\nReturn the eigenvalues satisfying the discrete form of Poisson's equation\nwith periodic boundary conditions along the dimension `dim` with `N` grid\npoints and domain extent `L`.\n\"\"\"\nfunction poisson_eigenvalues(N, L, dim, ::Periodic)\n    inds = reshape(1:N, reshaped_size(N, dim)...)\n    return @. (2sin((inds - 1) * π / N) / (L / N))^2\nend\n\n\"\"\"\n    poisson_eigenvalues(N, L, dim, ::Bounded)\n\nReturn the eigenvalues satisfying the discrete form of Poisson's equation\nwith staggered Neumann boundary conditions along the dimension `dim` with\n`N` grid points and domain extent `L`.\n\"\"\"\nfunction poisson_eigenvalues(N, L, dim, ::Bounded)\n    inds = reshape(1:N, reshaped_size(N, dim)...)\n    return @. (2sin((inds - 1) * π / 2N) / (L / N))^2\nend\n\n\"\"\"\n    poisson_eigenvalues(N, L, dim, ::Flat)\n\nReturn N-element array of `0.0` reshaped to three-dimensions.\nThis is also the first `poisson_eigenvalue` for `Bounded` and `Periodic` directions.\n\"\"\"\npoisson_eigenvalues(N, L, dim, ::Flat) = reshape(zeros(N), reshaped_size(N, dim)...)\n\n", "meta": {"hexsha": "8a0dba0f87f36ed3fe9a84f6d06b0c3315d2732f", "size": 1081, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Solvers/poisson_eigenvalues.jl", "max_stars_repo_name": "leea9524/Oceananigans.jl", "max_stars_repo_head_hexsha": "5e1448d14660e110edd8b28094d486bfe97c905b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 239, "max_stars_repo_stars_event_min_datetime": "2019-03-05T03:46:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-04T21:53:14.000Z", "max_issues_repo_path": "src/Solvers/poisson_eigenvalues.jl", "max_issues_repo_name": "leea9524/Oceananigans.jl", "max_issues_repo_head_hexsha": "5e1448d14660e110edd8b28094d486bfe97c905b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 654, "max_issues_repo_issues_event_min_datetime": "2019-03-02T02:20:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-02T00:13:53.000Z", "max_forks_repo_path": "src/Solvers/poisson_eigenvalues.jl", "max_forks_repo_name": "ali-ramadhan/OceanDispatch.jl", "max_forks_repo_head_hexsha": "65b8851d37052e90ca4a3e0c4a1c20398b0ee09a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 45, "max_forks_repo_forks_event_min_datetime": "2019-03-05T18:25:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-04T08:04:25.000Z", "avg_line_length": 32.7575757576, "max_line_length": 84, "alphanum_fraction": 0.6901017576, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475794701961, "lm_q2_score": 0.8459424353665382, "lm_q1q2_score": 0.7980177487741467}}
{"text": "input = 347991\n\n# Part 1\nfunction side_length(number:: Int)\n  root = ceil(sqrt(number))\n  if root % 2 == 0\n    return root + 1\n  else\n    return root\n  end\nend\n\nfunction get_position(number:: Int)\n  slength = side_length(number)\n  x = floor(slength / 2)\n  \n  side_centers = slength^2 - ((slength - 1) * collect(1:4)) - floor(slength / 2)\n  y = minimum(abs.(side_centers - number))\n\n  return x, y\nend\n\n(x, y) = abs.(get_position(input))\nprintln(\"Part 1: $(x + y) steps from ($x, $y)\")\n\n# Part 2\nmutable struct NegativeIndexSquareArray\n  size::Int\n  content::Array{Int, 3}\n\n  NegativeIndexSquareArray(size) = new(size, zeros(size, size, 4))\nend\n\nfunction Base.getindex(array::NegativeIndexSquareArray, x, y)\n  sx = sign(x) == 0? 1 : sign(x)\n  sy = sign(y) == 0? 1 : sign(y)\n  (x, y) = abs.([x, y])\n\n  if sx == 1 && sy == 1\n    array.content[x + 1, y + 1, 1]\n  elseif sx == 1 && sy == -1\n    array.content[x + 1, y, 2]\n  elseif sx == -1 && sy == 1\n    array.content[x, y + 1, 3]\n  else # Both negative\n    array.content[x, y, 4]\n  end\nend\n\nfunction Base.setindex!(array::NegativeIndexSquareArray, value, x, y)\n  sx = sign(x) == 0? 1 : sign(x)\n  sy = sign(y) == 0? 1 : sign(y)\n  (x, y) = abs.([x, y])\n\n  if sx == 1 && sy == 1\n    array.content[x + 1, y + 1, 1] = value\n  elseif sx == 1 && sy == -1\n    array.content[x + 1, y, 2] = value\n  elseif sx == -1 && sy == 1\n    array.content[x, y + 1, 3] = value\n  else # Both negative\n    array.content[x, y, 4] = value\n  end\nend\n\nspiral = NegativeIndexSquareArray(10)\nspiral[0, 0] = 1\n(x, y) = [1, 0]\ndirection = im\n\nwhile true\n  spiral[x, y] = spiral[x - 1, y] + spiral[x - 1, y - 1] +\n    spiral[x, y - 1] + spiral[x + 1, y - 1] + spiral[x + 1, y] +\n    spiral[x + 1, y + 1] + spiral[x, y + 1] + spiral[x - 1, y + 1]\n\n  if spiral[x, y] > input\n    println(\"Part 2: $(spiral[x, y]) at ($x, $y)\")\n    break\n  end\n\n  left = direction * im\n  if spiral[x + real(left), y + imag(left)] == 0\n    direction = left\n  end\n  x += real(direction)\n  y += imag(direction)\nend", "meta": {"hexsha": "07923fcc4318aac3d11f88dba5c7ee6ec273b130", "size": 2003, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day-3/day-3.jl", "max_stars_repo_name": "sakisds/AoC-2017", "max_stars_repo_head_hexsha": "39a6c8dcf91cc493eafe112801ffc7c56dadebd2", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day-3/day-3.jl", "max_issues_repo_name": "sakisds/AoC-2017", "max_issues_repo_head_hexsha": "39a6c8dcf91cc493eafe112801ffc7c56dadebd2", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day-3/day-3.jl", "max_forks_repo_name": "sakisds/AoC-2017", "max_forks_repo_head_hexsha": "39a6c8dcf91cc493eafe112801ffc7c56dadebd2", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0229885057, "max_line_length": 80, "alphanum_fraction": 0.5691462806, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7980177383734677}}
{"text": "function bisect_left(A, p, r, v)\n\ti = p\n\tif p < r\n\t   q = floor(Int, (p + r) / 2)\n\t   if v <= A[q]\n\t\t   i = bisect_left(A, p, q, v)\n\t   else\n\t\t   i = bisect_left(A, q + 1, r, v)\n\t   end\n\tend\n\treturn i\nend\n\n\nfunction bisect_right(A, p, r, v)\n\ti = p\n\tif p < r\n\t   q = floor(Int, (p + r) / 2)\n\t   if v < A[q]\n\t\t   i = bisect_right(A, p, q, v)\n\t   else\n\t\t   i = bisect_right(A, q + 1, r, v)\n\t   end\n\tend\n\treturn i\nend\n\n\nfunction bisect_right(A, v)\n\treturn bisect_right(A, 1, length(A) + 1, v)\nend\n\n\nfunction bisect_left(A, v)\n\treturn bisect_left(A, 1, length(A) + 1, v)\nend\n", "meta": {"hexsha": "088028d2b23fb333c2ae1de3f3628a770ef4a990", "size": 570, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Sorting/src/bisect.jl", "max_stars_repo_name": "MarcusTL12/JuliaModules", "max_stars_repo_head_hexsha": "3ddb3f05548d25f74a6f9d7e3499be7f01510cd7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-22T10:43:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-22T10:43:27.000Z", "max_issues_repo_path": "Sorting/src/bisect.jl", "max_issues_repo_name": "MarcusTL12/JuliaModules", "max_issues_repo_head_hexsha": "3ddb3f05548d25f74a6f9d7e3499be7f01510cd7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sorting/src/bisect.jl", "max_forks_repo_name": "MarcusTL12/JuliaModules", "max_forks_repo_head_hexsha": "3ddb3f05548d25f74a6f9d7e3499be7f01510cd7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.4054054054, "max_line_length": 44, "alphanum_fraction": 0.5385964912, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.8688267830311354, "lm_q1q2_score": 0.7980002415103091}}
{"text": "export newtoncg\n\n\"\"\"\nnewtoncg(f,df,H,x)\n\nNewton-CG method for solving min_x f(x)\n\n\"\"\"\nfunction newtoncg(f::Function,df::Function,H::Function,x::Vector;maxIter=20,atol=1e-8,out::Int=0,storeInterm::Bool=false,\n\tlineSearch::Function=(f,df,fk,dfk,xk,pk)->armijo(f,fk,dfk,xk,pk,maxIter=20),tolCG=1e-2,maxIterCG=30,P=d2f->identity)\n\n    his = zeros(maxIter,6)\n    X = (storeInterm) ? zeros(length(x),maxIter) : []\n    i = 1; flag = -1; LL = []\n    while i<=maxIter\n        fk  = f(x)\n        dfk = df(x)\n        his[i,1:2] = [norm(fk) norm(dfk)]\n        if storeInterm; X[:,i] = x; end;\n\n        if(norm(dfk)<atol)\n            flag = 0\n            his = his[1:i,:]\n            break\n        end\n        \n        # get search direction\n        d2f = H(x)\n        PC  = P(d2f) # preconditioner\n        pk,his[i,6],his[i,5],his[i,4] = cg(d2f,-dfk,out=-1,tol=tolCG,maxIter=maxIterCG,M=PC)\n        if his[i,6]==-2 && norm(pk)==0\n            pk = -dfk\n        end\n      # line search\n        ak,his[i,3] = lineSearch(f,df,fk,dfk,x,pk) \n        if his[i,3]==-1\n            flag = -3\n            his  = his[1:i,:]\n            break\n        end\n      if out>0\n            @printf \"iter=%04d\\t|f|=%1.2e\\t|df|=%1.2e\\tcgIter=%d\\tLS=%1.4f\\n\" i his[i,1] his[i,2] his[i,4] ak\n        end\n        # update\n        x  += ak*pk\n        i+=1   \n    end\n    i = min(maxIter,i)\n\n    if out>=0\n        if flag==-1\n            println(@sprintf(\"newtoncg iterated maxIter (=%d) times but reached only atol of %1.2e instead of tol=%1.2e\",i,his[i,2],atol))\n        elseif flag==-3\n            println(@sprintf(\"newtoncg stopped at iteration %d due to a line search fail.\",i))\n        elseif out>1\n            println(@sprintf(\"newtoncg achieved desired atol of %1.2e at iteration %d.\",atol,i))\n        end\n    end\n    if storeInterm; X = X[:,1:i]; end\n    return x,flag,his,X\nend", "meta": {"hexsha": "60c563e3365126c518635f3f0e680408d574a821", "size": 1847, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/newtoncg.jl", "max_stars_repo_name": "lruthotto/OptimTools.jl", "max_stars_repo_head_hexsha": "977feb8f2fd5e04d3f3b2a700b8abc992740cedb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/newtoncg.jl", "max_issues_repo_name": "lruthotto/OptimTools.jl", "max_issues_repo_head_hexsha": "977feb8f2fd5e04d3f3b2a700b8abc992740cedb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/newtoncg.jl", "max_forks_repo_name": "lruthotto/OptimTools.jl", "max_forks_repo_head_hexsha": "977feb8f2fd5e04d3f3b2a700b8abc992740cedb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2786885246, "max_line_length": 138, "alphanum_fraction": 0.523010287, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252812, "lm_q2_score": 0.8688267762381844, "lm_q1q2_score": 0.798000229454946}}
{"text": "# # Padua transform\n# This demonstrates the Padua transform and inverse transform,\n# explaining precisely the normalization and points\n\nusing FastTransforms\n\n# We define the Padua points and extract Cartesian components:\nN = 15\npts = paduapoints(N)\nx = pts[:,1]\ny = pts[:,2];\n\n# We take the Padua transform of the function:\nf = (x,y) -> exp(x + cos(y))\nf̌ = paduatransform(f.(x , y));\n\n# and use the coefficients to create an approximation to the function $f$:\nf̃ = (x,y) -> begin\n    j = 1\n    ret = 0.0\n    for n in 0:N, k in 0:n\n        ret += f̌[j]*cos((n-k)*acos(x)) * cos(k*acos(y))\n        j += 1\n    end\n    ret\nend\n\n# At a particular point, is the function well-approximated?\nf̃(0.1,0.2) ≈ f(0.1,0.2)\n\n# Does the inverse transform bring us back to the grid?\nipaduatransform(f̌) ≈ f̃.(x,y)\n", "meta": {"hexsha": "91655ce442c098a7b8e2eebced22deb2b5dfb875", "size": 798, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/padua.jl", "max_stars_repo_name": "eschnett/FastTransforms.jl", "max_stars_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2019-04-13T05:52:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T10:03:15.000Z", "max_issues_repo_path": "examples/padua.jl", "max_issues_repo_name": "eschnett/FastTransforms.jl", "max_issues_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113, "max_issues_repo_issues_event_min_datetime": "2019-04-12T20:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:16:28.000Z", "max_forks_repo_path": "examples/padua.jl", "max_forks_repo_name": "eschnett/FastTransforms.jl", "max_forks_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2019-04-23T08:43:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T15:35:17.000Z", "avg_line_length": 24.1818181818, "max_line_length": 74, "alphanum_fraction": 0.6428571429, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992932829918, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7979961221406227}}
{"text": "using LinearAlgebra\nusing Zygote: @adjoint\n\n\"\"\" maximum eigenvalue of a symmetric square matrix \"\"\"\nfunction maxeig(symmat::Array{T,2})::T where {T}\n    eig = eigen(Symmetric(symmat))\n    max_idx = findmax(eig.values)[2]\n    eigmax = eig.values[max_idx]\n    return eigmax\nend\n\n@adjoint function maxeig(symmat::Array{T,2}) where {T}\n    eig = eigen(Symmetric(symmat))\n    max_idx = findmax(eig.values)[2]\n    eigmax = eig.values[max_idx]\n    vecmax = eig.vectors[:, max_idx]\n    jac_adj = vecmax * (vecmax')\n    return eigmax, c -> Tuple(jac_adj * c)\nend\n\n\"\"\" minimum eigenvalue of a symmetric square matrix \"\"\"\nfunction mineig(symmat::Array{T,2})::T where {T}\n    eig = eigen(Symmetric(symmat))\n    min_idx = findmin(eig.values)[2]\n    eigmin = eig.values[min_idx]\n    return eigmin\nend\n\n@adjoint function mineig(symmat::Array{T,2}) where {T}\n    eig = eigen(Symmetric(symmat))\n    min_idx = findmin(eig.values)[2]\n    eigmin = eig.values[min_idx]\n    vecmin = eig.vectors[:, min_idx]\n    jac_adj = vecmin * (vecmin')\n    return eigmax, c -> Tuple(jac_adj * c)\nend\n\n\"\"\" eigenvalue regularization \"\"\"\nfunction softplus_eigreg(symmat)\n    eig = eigen(Symmetric(symmat))\n    return mean(softplus.(eig.values))\nend\n\n@adjoint function softplus_eigreg(symmat)\n    eig = eigen(Symmetric(symmat))\n    return sum(softplus.(eig.values)),\n    c -> Tuple(\n        sum((\n            sigmoid(eig.values[i]) * eig.vectors[:, i] * (eig.vectors[:, i]') for\n            i = 1:size(symmat, 1)\n        )) * c,\n    )\nend\n\nfunction relu_eigreg(symmat)\n    eig = eigen(Symmetric(symmat))\n    return sum(relu.(eig.values))\nend\n\n@adjoint function relu_eigreg(symmat)\n    eig = eigen(Symmetric(symmat))\n    return sum(relu.(eig.values)),\n    c -> Tuple(\n        sum((\n            0.5 * (sign(eig.values[i]) + 1) * eig.vectors[:, i] * (eig.vectors[:, i]')\n            for i = 1:size(symmat, 1)\n        )) * c,\n    )\nend\n\n\"\"\" compute all eigenvalues \"\"\"\nfunction eigenvalues(symmat)\n    eig = eigen(Symmetric(symmat))\n    return eig.values\n    # return eigvals(Symmetric(symmat))\nend\n\n@adjoint function eigenvalues(symmat)\n    eig = eigen(Symmetric(symmat))\n    return eig.values,\n    c -> Tuple((eig.vectors[:, i] * (eig.vectors[:, i]')) * c for i = 1:size(symmat, 1))\n    # vals = eigvals(Symmetric(symmat))\n    # vecs = eigvecs(Symmetric(symmat))\n    # return vals, c -> Tuple((vecs[:,i]*(vecs[:,i]'))*c for i=1:size(symmat,1))\nend\n", "meta": {"hexsha": "25275eac6c26779d5f3613906bb2d960b9f94edb", "size": 2407, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/modifiers/eig.jl", "max_stars_repo_name": "syanga/ISSNeuralODE", "max_stars_repo_head_hexsha": "a7c70bd2ec374dfbbbf55b80ff1a551d5f8e9e2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/modifiers/eig.jl", "max_issues_repo_name": "syanga/ISSNeuralODE", "max_issues_repo_head_hexsha": "a7c70bd2ec374dfbbbf55b80ff1a551d5f8e9e2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/modifiers/eig.jl", "max_forks_repo_name": "syanga/ISSNeuralODE", "max_forks_repo_head_hexsha": "a7c70bd2ec374dfbbbf55b80ff1a551d5f8e9e2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.988372093, "max_line_length": 88, "alphanum_fraction": 0.6310760283, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992932829918, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7979961117039461}}
{"text": "include(\"prime.jl\")\r\nfunction  is_circular_prime(n::Int)\r\n\tif (!is_prime(n)) \r\n\t\treturn false\r\n\tend\r\n\ts=string(n)\r\n\tfor i=1:length(s)\r\n\t\tif (!is_prime( parse(Int,s[i:length(s)]*s[1:i-1])))\r\n\t\t\treturn false\r\n\t\tend\r\n\r\n\tend\r\n\r\n\treturn true\r\n\r\nend\r\n\r\nfunction  compute()\r\n\tconst N=1000000\r\n\tans =sum( 1 for i =1:N if is_circular_prime(i))\r\n\treturn ans\r\n\r\nend\r\n\r\nprintln(compute())\r\n\r\n", "meta": {"hexsha": "b246feba7a75656861dcdeed6a63f8f24addd61c", "size": 380, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/p035.jl", "max_stars_repo_name": "tlming16/Projec_Euler", "max_stars_repo_head_hexsha": "797824c5159fae67493de9eba24c22cc7512d95d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-11-14T12:03:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-03T14:33:28.000Z", "max_issues_repo_path": "julia/p035.jl", "max_issues_repo_name": "tlming16/Projec_Euler", "max_issues_repo_head_hexsha": "797824c5159fae67493de9eba24c22cc7512d95d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/p035.jl", "max_forks_repo_name": "tlming16/Projec_Euler", "max_forks_repo_head_hexsha": "797824c5159fae67493de9eba24c22cc7512d95d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-17T14:39:22.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-17T14:39:22.000Z", "avg_line_length": 14.0740740741, "max_line_length": 54, "alphanum_fraction": 0.6210526316, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9678992914310605, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7979961101770991}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.3\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 1c630e40-628c-11ec-1793-05688dabf6c9\nbegin\n\tusing Pkg; Pkg.activate(@__DIR__); Pkg.instantiate()\n\tPkg.precompile()\n\n\tusing PlutoUI\n\tusing Statistics\n\tusing StatsBase\n\tusing RDatasets\n\tusing Plots\n\tusing StatsPlots\n\tusing KernelDensity\n\tusing Distributions\n\tusing LinearAlgebra\n\tusing HypothesisTests\n\tusing PyCall\n\tusing MLBase\nend;\n\n# ╔═╡ 7242a33b-ec37-48d6-afca-8c8387a45a83\nPlutoUI.TableOfContents(aside=true, indent=true, depth=3)\n\n# ╔═╡ dd2aa8b3-9da3-418d-bf31-74574483360d\nhtml\"\"\"\n<p align=\"center\">\n\t<img src=\"https://github.com/JuliaAcademy/DataScience/blob/main/datascience.png?raw=true\" alt=\"Course-Logo\" width=\"450px\">\n</p>\n\"\"\"\n\n# ╔═╡ abc828f1-fd14-4329-8b47-f4135300f937\nmd\"\"\"\n# 📊 Statistics\n\nHaving a solid understanding of statistics in data science allows us to understand our data better, and allows us to create a quantifiable evaluation of any future conclusions.\n\n[YouTube Link](https://www.youtube.com/watch?v=AAGxWEJ_eWk)\n\"\"\"\n\n# ╔═╡ a8aae3d4-198c-482f-a972-05be31be39c1\nmd\"\"\"\n## Load dataset\n\nIn this notebook, we will use eruption data on the faithful geyser (Yellowstone, USA). The data will contain wait times between every consecutive times the geyser goes off (in minutes) and the length of the eruptions (also in minutes).\n\nLet's get the data first using the [RDatasets.jl](https://github.com/JuliaStats/RDatasets.jl) package...\n\n**Note:** the dataset will be loaded as a `DataFrame`.\n\"\"\"\n\n# ╔═╡ 63420679-9b77-4412-ba1c-fc471da6b1e9\ndata = dataset(\"datasets\", \"faithful\")\n\n# ╔═╡ 9d56b2cc-c4c6-4ce2-8d9c-33174fe5bc33\nmd\"\"\"\nWe can use the `describe` function to get some stats from our data...\n\"\"\"\n\n# ╔═╡ 67ac4a1d-eb15-473f-a548-07425fd627d8\ndescribe(data)\n\n# ╔═╡ 5ee886cc-2730-40cf-8497-507dcdc08c5f\nmd\"\"\"\nLet's call each column (feature) separately...\n\"\"\"\n\n# ╔═╡ 110fda28-1b77-44d6-8485-a4ec6e012011\nbegin\n\teruption = data[!, :Eruptions]\n\t# eruption = data.Eruptions\n\n\twaittime = data[!, :Waiting]\n\t# waittime = data.Waiting\nend;\n\n# ╔═╡ 6e093fbb-1e3a-4131-b3c2-b5891e734fa7\nmd\"\"\"\nNow, we can plot both variables in the same scatter plot...\n\"\"\"\n\n# ╔═╡ ed9da9c2-53e4-45d6-9ec1-02c8bf54c1a5\nbegin\n\tscatter(eruption, label=\"Eruptions\")\n\tscatter!(waittime, label=\"Wait Time\", xlabel=\"Index\", ylabel=\"Time (minutes)\")\nend\n\n# ╔═╡ 13137e30-cfde-459a-adb4-1ddc07e626e8\nmd\"\"\"\n## Statistics plots\n\nAs you can see, this doesn't tell us much about the data... Let's try some statistical plots.\n\"\"\"\n\n# ╔═╡ ff9d63e7-808a-4465-a68d-659a222afbae\nmd\"\"\"\n### Boxplot\n\"\"\"\n\n# ╔═╡ c3672771-248a-47f9-a019-2de03cdd79f4\nboxplot([\"Eruption Length\"], eruption, legend=false,\n\t\tsize=(200,400), whisker_width=1, ylabel=\"Time (minutes)\")\n\n# ╔═╡ 46b55947-428a-483f-a00f-a232e5329fbd\nmd\"\"\"\nStatistical plots such as a boxplot (and a violin plot), can provide a much better understanding of the data. Here, we immediately see that the median time of each eruption is about 4 minutes.\n\"\"\"\n\n# ╔═╡ e0933f5c-50b5-47cf-bae8-7a45a219fefb\nmd\"\"\"\n### Histogram\n\nThe next plot we will see is a histogram plot. Check its arguments below...\n\n- `x`: AbstractVector of values to be binned.\n- `bins`: Integer, NTuple{2,Integer}, AbstractVector or Symbol. Default is :auto (the Freedman-Diaconis rule). For histogram-types, defines the approximate number of bins to aim for, or the auto-binning algorithm to use (`:sturges`, `:sqrt`, `:rice`, `:scott` or `:fd`). For fine-grained control pass a Vector of break values, e.g. `range(minimum(x), stop = maximum(x), length = 25)`.\n- `weights`: Vector of weights for the values in x, for weighted bin counts.\n- `normalize`: Bool or Symbol. Histogram normalization mode. Possible values are: `false`/`:none` (no normalization, default), `true`/`:pdf` (normalize to a discrete Probability Density Function, where the total area of the bins is 1), `:probability` (bin heights sum to 1) and `:density` (the area of each bin, rather than the height, is equal to the counts - useful for uneven bin sizes).\n- `bar_position`: Symbol. Choose from `:overlay` (default), `:stack`. (warning: May not be implemented fully).\n- `bar_width`: nothing or Number. Width of bars in data coordinates. When nothing, chooses based on x (or y when orientation = `:h`).\n- `bar_edges`: Bool. Align bars to edges (true), or centers (the default).\n- `orientation`: Symbol. Horizontal or vertical orientation for bar types. Values `:h`, `:hor`, `:horizontal` correspond to horizontal (sideways, anchored to y-axis), and `:v`, `:vert`, and `:vertical` correspond to vertical (the default).\n\nLet's plot eruption length data...\n\"\"\"\n\n# ╔═╡ 943c8862-b909-4750-96da-7bda62c5fc8c\nhistogram(eruption, bins=:sqrt, label=\"Eruption\", color=:orange,\n\t\t  xlabel=\"Eruption Length (minutes)\", ylabel=\"Frequency\")\n\n# ╔═╡ ed480ae6-3302-4d0e-b83e-53a9c395d5ce\nmd\"\"\"\n### Kernel density estimates\n\nNext, we will see how we can fit a kernel density estimation function to our data. We will make use of the [KernelDensity.jl](https://github.com/JuliaStats/KernelDensity.jl) package.\n\nWith Kernel density estimates, we can see how things are changing...\n\"\"\"\n\n# ╔═╡ ed58e41f-3f73-40c1-92ec-5f2845c62b97\nρ = kde(eruption)\n\n# ╔═╡ 952506dc-6cd8-4ecd-ace8-b9d914560289\nmd\"\"\"\nIf we want the histogram and the kernel density graph to be aligned we need to remember that the \"density contribution\" of every point added to one of these histograms is `density * nb of elements * bin width`. We do this, since KDE are densities, while the y-axis is showing the frequency.\n\n**Note:** Read more about kernel density estimates [here](https://en.wikipedia.org/wiki/Kernel_density_estimation).\n\"\"\"\n\n# ╔═╡ 3ea44987-7ba7-4df6-a82a-c11a98ea784d\n# the range of density data (x-axis)\nρ.x\n\n# ╔═╡ 31274ae3-20da-4f52-9153-6f6b4d4472cb\n# density data (y-axis)\nρ.density\n\n# ╔═╡ 53f3e80a-2c88-405f-9131-21d07b132389\n# density * nb of elements * bin width\nscaled_density = ρ.density .* length(eruption) .* 0.2\n\n# ╔═╡ ccfe5310-cc85-457c-bfbc-9671062b9088\nbegin\n\thistogram(eruption, bins=:sqrt, label=\"Eruption\", color=:lightblue,\n\t\t  \t  xlabel=\"Eruption Length (minutes)\", ylabel=\"Frequency\")\n\n\tplot!(ρ.x, scaled_density, linewidth=1.5, color=:black, label=\"KDE fit\")\nend\n\n# ╔═╡ cbf471e5-523c-4550-835b-5c45b9648d8c\nmd\"\"\"\n## Probability distributions\n\nFirst, we will take a look at one probablity distribution, namely the Normal Distribution and verify that it generates a bell curve.\n\"\"\"\n\n# ╔═╡ 914412a4-69d4-4d9f-b575-03cfa03a7873\n# generating random normal data\nnormaldata = randn(100_000)\n\n# ╔═╡ 86c9cf10-2ade-45de-8649-a8dd5b2ae586\nbegin\n\t# generating the KDE\n\tρₙ = kde(normaldata)\n\n\t# scaling density estimates\n\tscaled_ρₙ = ρₙ.density .* length(normaldata) * 0.1\nend\n\n# ╔═╡ e137810d-9e3c-43c8-905c-4efc2213a130\nbegin\n\t# plotting histogram\n\thistogram(normaldata, color=:lightblue, label=\"Z ~ N(0,1)\",\n\t\t\t  xlabel=\"Z\", ylabel=\"Frequency\")\n\n\t# plotting KDE\n\tplot!(ρₙ.x, scaled_ρₙ, linewidth=3, color=:black, label=\"KDE fit\")\nend\n\n# ╔═╡ f6430d83-a92b-4c03-a07e-8a6146cc9e1c\nmd\"\"\"\nAnother way to generate the same plot is via using the [Distributions.jl](https://github.com/JuliaStats/Distributions.jl) package and choosing the probability distribution you want, and then drawing random numbers from it.\n\"\"\"\n\n# ╔═╡ 4ffd9a7a-c62c-40a4-8ec1-4e2351a2a66a\nmd\"\"\"\n### Normal distribution\n\nAs an example, we will use `N = Normal()` below to draw random numbers from a [Normal distribution](https://en.wikipedia.org/wiki/Normal_distribution). The default $\\mu$ and $\\sigma$ values are 0 and 1 (standard Normal distribution).\n\"\"\"\n\n# ╔═╡ 978e2f4c-b411-459c-8024-4f6205484f63\nbegin\n\t# drawing numbers ~N(0,1)\n\tN = Normal()\n\tgaussdata = rand(N, 100_000)\n\n\t# calculating KDE\n\trhoN = kde(gaussdata)\n\tscaled_rhoN = rhoN.density .* length(gaussdata) .* 0.1\nend\n\n# ╔═╡ d1483a5e-0b7e-4317-adb0-8f024fad21eb\nbegin\n\t# plotting histogram\n\thistogram(gaussdata, color=:lightblue, label=\"Z ~ N(0,1)\",\n\t\t\t  xlabel=\"Z\", ylabel=\"Frequency\")\n\n\t# plotting KDE\n\tplot!(rhoN.x, scaled_rhoN, linewidth=3, color=:black, label=\"KDE fit\")\nend\n\n# ╔═╡ 62470113-95dc-4b92-9e1d-3118efa0bd08\nmd\"\"\"\n### Binomial distribution\n\nNow, let's draw random numbers from a [Binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution).\n\"\"\"\n\n# ╔═╡ 7749b6b5-cf01-4812-b1ce-6fe3204b0bcf\nbegin\n\t# drawing numbers ~B with n=40 trials\n\tB = Binomial(40)\n\tbinomdata = rand(B, 100_000)\n\n\t# calculating KDE\n\trhoB = kde(binomdata)\n\tscaled_rhoB = rhoB.density .* length(binomdata) .* 0.5\nend\n\n# ╔═╡ ff68a550-9cc6-416e-96b8-07de164e5fc4\nbegin\n\t# plotting histogram\n\thistogram(binomdata, color=:lightblue, label=\"Z ~ B(40,0.5)\",\n\t\t\t  xlabel=\"Z\", ylabel=\"Frequency\")\n\n\t# plotting KDE\n\tplot!(rhoB.x, scaled_rhoB, linewidth=3, color=:black, label=\"KDE fit\")\nend\n\n# ╔═╡ 693de4f8-88b1-476f-9319-64edafb049af\nmd\"\"\"\n### Fit data to a distribution\n\nNext, we will try to fit a given set of numbers to a parametric distribution. Thus, we are going to use the StatsBase.jl `fit` function.\n\"\"\"\n\n# ╔═╡ 7f9949d9-22e2-4d4e-92ec-6e52e01d10aa\nbegin\n\t# creating 1000 random values\n\trandomdata = rand(1000)\n\t# fitting random values to a Standard Normal distribution\n\tfitted_distrib = fit(Normal, randomdata)\n\t# drawing 1000 values from the new fitted distribution\n\tnew_data = rand(fitted_distrib, 1000)\nend\n\n# ╔═╡ 98301aae-61ca-46ab-936a-fbb310854778\n# note that `fitted_distrib` is a `Distribution`\nfitted_distrib\n\n# ╔═╡ f270c785-3a7a-4e43-9f21-b9a6e199383b\nbegin\n\t# plotting new data (Normal distribution)\n\thistogram(new_data, nbins=20, fillalpha=0.3, label=\"Normal Data\")\n\n\t# plotting original data\n\thistogram!(randomdata, nbins=20, linecolor=:red, fillalpha=0.3,\n\t\t\t   label=\"Original Data\")\nend\n\n# ╔═╡ 2d5e5740-a3c6-4448-b79f-f231a0ac9d96\nmd\"\"\"\nWe can try to fit eruptions data to a Normal distribution, although eruptions distribution does not seem to be Normal.\n\"\"\"\n\n# ╔═╡ ef651442-e846-4a5e-9f3b-0da63afeca16\nbegin\n\terup_distrib = fit(Normal, eruption)\n\tnormal_erup = rand(erup_distrib, 1000)\nend\n\n# ╔═╡ a5a54536-4b60-4a9c-b423-2804cce37382\nerup_distrib\n\n# ╔═╡ 25b15bda-9bb4-4ed9-90e4-c1f937051314\nbegin\n\t# plotting fitted data (Normal distribution)\n\thistogram(normal_erup, nbins=20, fillalpha=0.3, label=\"Normal Data\")\n\n\t# plotting original data\n\thistogram!(eruption, nbins=20, linecolor=:red, fillalpha=0.3,\n\t\t\t   label=\"Original Data\")\nend\n\n# ╔═╡ b82db811-d97d-4efd-81bc-a48780b23dcb\nmd\"\"\"\n## Hypothesis testing\n\nNext, we will perform hypothesis testing using the [HypothesisTests.jl](https://github.com/JuliaStats/HypothesisTests.jl) package.\n\nLet's try to use the `OneSampleTTest` function to perform a one sample t-test of random sampled values.\n\nThe one-sample t-test is a statistical hypothesis test used to determine whether an unknown population mean is different from a specific value. In this case, the default value under $H_0$ is 0. \n\"\"\"\n\n# ╔═╡ af54608d-209f-4d16-9573-b4b8634d2acf\n# generating 1000 random normal values\nhypdata = randn(1000)\n\n# ╔═╡ 867dab59-1c8d-44d9-9add-9f3999f1b86c\n# performing one sample t-test\nOneSampleTTest(hypdata)\n\n# ╔═╡ 47c7f6df-0696-4b1e-b6c2-7eb8e782eb82\nmd\"\"\"\n**Note:** as we can see above, we cannot reject the null hypothesis $H_0$. This was expected, since we drew sample values from a Standard Normal distribution, with $\\mu=0$.\n\nNow we can perform a one sample t-test of eruption data. We will probably be able to reject $H_0$, since the eruption length mean is close to 3.5 minutes...\n\"\"\"\n\n# ╔═╡ 6555c2a2-227f-419b-9b8b-d563767f3ea5\nOneSampleTTest(eruption)\n\n# ╔═╡ 78585d9d-5696-41dd-80f0-abab1585b008\nmd\"\"\"\n## Correlation statistics\n\nFirst of all, let's see visually if there is a correlation between `eruption` and `waittime` variables using a scatter plot...\n\"\"\"\n\n# ╔═╡ 650a1af5-b413-4794-bf51-77fa34cfb820\nscatter(eruption, waittime, legend=false, color=:orange,\n\t\txlabel=\"Eruption Length (minutes)\", markersize=3,\n\t\tylabel = \"Time between Eruptions (minutes)\")\n\n# ╔═╡ 80db913d-faa8-43d5-9794-e17b02823cc5\nmd\"\"\"\nThese two variables may have a strong positive correlation. We can calculate both `Pearson` and `Spearman` correlation coefficients to check that.\n\"\"\"\n\n# ╔═╡ fcb84ac7-3bca-4284-8939-a55bd78a02fa\nbegin\n\tspearman_r = corspearman(eruption, waittime)\n\t\"r(Spearman) = $spearman_r\"\nend\n\n# ╔═╡ 960b8739-10d1-490d-ac49-e51527386161\nbegin\n\tpearson_r = cor(eruption, waittime)\n\t\"r(Pearson) = $pearson_r\"\nend\n\n# ╔═╡ 5bd50a69-4edb-435a-9263-e0b5d47851aa\nmd\"\"\"\nInteresting! This means that the next time you visit Yellowstone National part ot see the faithful geysser and you have to wait for too long for it to go off, you will likely get a longer eruption!\n\nCurrently we are using the p-value of Spearman and Pearson correlation coefficients from Python. But you can follow the formula [here](https://stackoverflow.com/questions/53345724/how-to-use-julia-to-compute-the-pearson-correlation-coefficient-with-p-value) to implement your own.\n\nLet's import the `scipy.stats` Python module.\n\n**Note:** sometimes there are some issues getting Python and Julia to communicate as desired. We can explicity add `scipy.stats` using the [Conda.jl](https://github.com/JuliaPy/Conda.jl) package:\n\n```julia\njulia> using Conda\njulia> Conda.add(\"scipy\")\n```\n\"\"\"\n\n# ╔═╡ d1ef6cd2-fda1-47f6-af12-8492ea70a539\nscipy_stats = pyimport(\"scipy.stats\");\n\n# ╔═╡ c5f77715-02cb-437a-a45f-3f3a4dfba67b\nbegin\n\trₛ, pvalueₛ = scipy_stats.spearmanr(eruption, waittime)\n\t\"r(Spearman) = $(rₛ) || p-value = $(pvalueₛ)\"\nend\n\n# ╔═╡ 615e7c40-bafe-475f-959d-29c5f5e845e9\nbegin\n\trₚ, pvalueₚ = scipy_stats.pearsonr(eruption, waittime)\n\t\"r(Pearson) = $(rₚ) || p-value = $(pvalueₚ)\"\nend\n\n# ╔═╡ 32bc5a24-638e-43bc-a5c1-bd0a85db7849\nmd\"\"\"\n## Confusion matrix & AUC\n\nFinally, we will cover basic tools you will need such as confusion matrix and AUC scores. We use the [MLBase.jl](https://github.com/JuliaStats/MLBase.jl) package for that.\n\nFirst, let's calculate a confusion matrix, given a target vector `y₁` and a prediction vector `ŷ₁`...\n\"\"\"\n\n# ╔═╡ 838a8a32-95f6-48c0-b87d-28a66ef431c5\nbegin\n\t# generating target and prediction vectors\n\ty₁ = [1, 1, 1, 1, 1, 1, 1, 2]\n\tyhat₁ = [1, 1, 2, 2, 1, 1, 1, 1]\nend;\n\n# ╔═╡ 68d7cd6c-bd76-406b-a3d7-4528ee9671fd\n# compute default confusion matrix\nC = confusmat(2, y₁, yhat₁)\n\n# ╔═╡ 2bcf8647-368d-4b74-8e1a-4a4b1a577fdc\nmd\"\"\"\nWe may normalize cell values per class...\n\"\"\"\n\n# ╔═╡ 86ad3850-f631-42b2-8d19-bf20cba89c6b\nC ./ sum(C, dims=2)\n\n# ╔═╡ 38a2bb94-1d8f-4e1a-a07f-3bc1332301fd\nmd\"\"\"\nAlso, we may compute the accuracy (correct rate) from confusion matrix...\n\n```math\naccuracy = \\frac{TP}{TP+TN+FP+FN}\n```\n\"\"\"\n\n# ╔═╡ ea2c50c6-9404-4ba4-8fe7-4d1e1b3246ff\nacc = sum(diag(C)) / length(y₁)\n\n# ╔═╡ 70cbc1f9-171e-4664-87d1-6e73f0bc841c\nmd\"\"\"\nInstead of calculating accuracy manually, we could use the `correctrate` function...\n\"\"\"\n\n# ╔═╡ 188c0219-8a54-4f28-95fd-9f2f525c12be\nacc == correctrate(y₁, yhat₁)\n\n# ╔═╡ 063d30ad-0ac4-4d50-b66b-9b06bf155fd8\nmd\"\"\"\nNow, we can use the `roc` function to calculate ROC scores...\n\"\"\"\n\n# ╔═╡ f3cca2ef-17ec-44e0-996d-8a0cb2f2fcb1\nbegin\n\t# generating target and prediction vectors\n\ty₂ = [1, 1, 1, 1, 1, 1, 1, 0]\n\tyhat₂ = [1, 1, 0, 0, 1, 1, 1, 1]\nend;\n\n# ╔═╡ 9af05d0f-5daf-48f4-9949-79db70ae4bbc\nROC = MLBase.roc(y₂, yhat₂)\n\n# ╔═╡ 92f98fe2-9154-4029-8282-45dee3f11d31\nmd\"\"\"\nWe may also use both `recall` and `precision` functions to compute these metrics...\n\"\"\"\n\n# ╔═╡ 0cfa5643-b65b-4374-a227-8f036ce32bbf\nbegin\n\trec = recall(ROC)\n\t\"Recall = $rec\"\nend\n\n# ╔═╡ 93ea2a29-bac3-4629-bac5-5d03e8e45d80\nbegin\n\tprec = precision(ROC)\n\t\"Precision = $prec\"\nend\n\n# ╔═╡ Cell order:\n# ╟─1c630e40-628c-11ec-1793-05688dabf6c9\n# ╟─7242a33b-ec37-48d6-afca-8c8387a45a83\n# ╟─dd2aa8b3-9da3-418d-bf31-74574483360d\n# ╟─abc828f1-fd14-4329-8b47-f4135300f937\n# ╟─a8aae3d4-198c-482f-a972-05be31be39c1\n# ╠═63420679-9b77-4412-ba1c-fc471da6b1e9\n# ╟─9d56b2cc-c4c6-4ce2-8d9c-33174fe5bc33\n# ╠═67ac4a1d-eb15-473f-a548-07425fd627d8\n# ╟─5ee886cc-2730-40cf-8497-507dcdc08c5f\n# ╠═110fda28-1b77-44d6-8485-a4ec6e012011\n# ╟─6e093fbb-1e3a-4131-b3c2-b5891e734fa7\n# ╠═ed9da9c2-53e4-45d6-9ec1-02c8bf54c1a5\n# ╟─13137e30-cfde-459a-adb4-1ddc07e626e8\n# ╟─ff9d63e7-808a-4465-a68d-659a222afbae\n# ╠═c3672771-248a-47f9-a019-2de03cdd79f4\n# ╟─46b55947-428a-483f-a00f-a232e5329fbd\n# ╟─e0933f5c-50b5-47cf-bae8-7a45a219fefb\n# ╠═943c8862-b909-4750-96da-7bda62c5fc8c\n# ╟─ed480ae6-3302-4d0e-b83e-53a9c395d5ce\n# ╠═ed58e41f-3f73-40c1-92ec-5f2845c62b97\n# ╟─952506dc-6cd8-4ecd-ace8-b9d914560289\n# ╠═3ea44987-7ba7-4df6-a82a-c11a98ea784d\n# ╠═31274ae3-20da-4f52-9153-6f6b4d4472cb\n# ╠═53f3e80a-2c88-405f-9131-21d07b132389\n# ╠═ccfe5310-cc85-457c-bfbc-9671062b9088\n# ╟─cbf471e5-523c-4550-835b-5c45b9648d8c\n# ╠═914412a4-69d4-4d9f-b575-03cfa03a7873\n# ╠═86c9cf10-2ade-45de-8649-a8dd5b2ae586\n# ╠═e137810d-9e3c-43c8-905c-4efc2213a130\n# ╟─f6430d83-a92b-4c03-a07e-8a6146cc9e1c\n# ╟─4ffd9a7a-c62c-40a4-8ec1-4e2351a2a66a\n# ╠═978e2f4c-b411-459c-8024-4f6205484f63\n# ╠═d1483a5e-0b7e-4317-adb0-8f024fad21eb\n# ╟─62470113-95dc-4b92-9e1d-3118efa0bd08\n# ╠═7749b6b5-cf01-4812-b1ce-6fe3204b0bcf\n# ╠═ff68a550-9cc6-416e-96b8-07de164e5fc4\n# ╟─693de4f8-88b1-476f-9319-64edafb049af\n# ╠═7f9949d9-22e2-4d4e-92ec-6e52e01d10aa\n# ╠═98301aae-61ca-46ab-936a-fbb310854778\n# ╠═f270c785-3a7a-4e43-9f21-b9a6e199383b\n# ╟─2d5e5740-a3c6-4448-b79f-f231a0ac9d96\n# ╠═ef651442-e846-4a5e-9f3b-0da63afeca16\n# ╠═a5a54536-4b60-4a9c-b423-2804cce37382\n# ╠═25b15bda-9bb4-4ed9-90e4-c1f937051314\n# ╟─b82db811-d97d-4efd-81bc-a48780b23dcb\n# ╠═af54608d-209f-4d16-9573-b4b8634d2acf\n# ╠═867dab59-1c8d-44d9-9add-9f3999f1b86c\n# ╟─47c7f6df-0696-4b1e-b6c2-7eb8e782eb82\n# ╠═6555c2a2-227f-419b-9b8b-d563767f3ea5\n# ╟─78585d9d-5696-41dd-80f0-abab1585b008\n# ╠═650a1af5-b413-4794-bf51-77fa34cfb820\n# ╟─80db913d-faa8-43d5-9794-e17b02823cc5\n# ╠═fcb84ac7-3bca-4284-8939-a55bd78a02fa\n# ╠═960b8739-10d1-490d-ac49-e51527386161\n# ╟─5bd50a69-4edb-435a-9263-e0b5d47851aa\n# ╠═d1ef6cd2-fda1-47f6-af12-8492ea70a539\n# ╠═c5f77715-02cb-437a-a45f-3f3a4dfba67b\n# ╠═615e7c40-bafe-475f-959d-29c5f5e845e9\n# ╟─32bc5a24-638e-43bc-a5c1-bd0a85db7849\n# ╠═838a8a32-95f6-48c0-b87d-28a66ef431c5\n# ╠═68d7cd6c-bd76-406b-a3d7-4528ee9671fd\n# ╟─2bcf8647-368d-4b74-8e1a-4a4b1a577fdc\n# ╠═86ad3850-f631-42b2-8d19-bf20cba89c6b\n# ╟─38a2bb94-1d8f-4e1a-a07f-3bc1332301fd\n# ╠═ea2c50c6-9404-4ba4-8fe7-4d1e1b3246ff\n# ╟─70cbc1f9-171e-4664-87d1-6e73f0bc841c\n# ╠═188c0219-8a54-4f28-95fd-9f2f525c12be\n# ╟─063d30ad-0ac4-4d50-b66b-9b06bf155fd8\n# ╠═f3cca2ef-17ec-44e0-996d-8a0cb2f2fcb1\n# ╠═9af05d0f-5daf-48f4-9949-79db70ae4bbc\n# ╟─92f98fe2-9154-4029-8282-45dee3f11d31\n# ╠═0cfa5643-b65b-4374-a227-8f036ce32bbf\n# ╠═93ea2a29-bac3-4629-bac5-5d03e8e45d80\n", "meta": {"hexsha": "6f1131fcadb8a29e2bd7d77de1f6baaeb9803b8f", "size": 18508, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "03_Statistics.jl", "max_stars_repo_name": "fnaghetini/DataScience", "max_stars_repo_head_hexsha": "5cd1c2a9c72aacc8a67800c74e394fb0e2045f2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "03_Statistics.jl", "max_issues_repo_name": "fnaghetini/DataScience", "max_issues_repo_head_hexsha": "5cd1c2a9c72aacc8a67800c74e394fb0e2045f2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "03_Statistics.jl", "max_forks_repo_name": "fnaghetini/DataScience", "max_forks_repo_head_hexsha": "5cd1c2a9c72aacc8a67800c74e394fb0e2045f2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8738898757, "max_line_length": 390, "alphanum_fraction": 0.7382753404, "num_tokens": 7658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.894789454880027, "lm_q1q2_score": 0.7979831243492373}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.2\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 17ada06e-a49a-11eb-29f8-35891d4afe6c\nbegin\n\tusing Random\n\tusing Plots\n\tusing Base.Threads\n\tusing Distributions\n\tusing DataFrames\nend\n\n# ╔═╡ d79fcb85-28ca-4e32-bc4d-8c442b771cd6\nmd\"\"\"\n# Random Election Upsets Riddler\n\nThis notebook solves the [Riddler Classic problem from April 23rd 2021](https://fivethirtyeight.com/features/can-you-cut-the-perfect-pancake/), which asks us to consider a large nation of voters who independently submit their vote between two candidates (A and B) by flipping identical fair coins. We're asked: if 80% of votes are tallied on election day (regular votes), while the remaining 20% (early votes) are tallied later, what is the probability of an upset -- i.e. what is the probability that the election day outcome doesn't match the final outcome?\n\nAs usual, I'll solve this problem in two ways. First I'll compute the result using some gratuitous math, and then I'll run a simulation of the random process to cross-check my analytical results. Since this problem isn't substantially harder if we assume that 20% of votes are submitted early, or that an arbitrary fraction of votes are submitted early, I'll solve the prompt in general and then report the solution for the prompt as a special case.\n\"\"\"\n\n# ╔═╡ 7c4713bb-7e75-4c0b-815c-e817b71e2f8b\nmd\"\"\"\n## Analytical Solution\n\n### Notation\nFirst let's introduce a bit of notation. Throughout, we will use the subscripts $E$ and $R$ to indicate quantities computed respectively for the early voter and regular voter subpopulations. Similarly, we will use a subscript $T$ to refer to the total population. We will use $v$ to denote the number of votes in favor of candidate A in a population and $n$ will denote the number of voters in a population. E.g. $v_E$ is the number of voters who voted for candidate A in the early voter subpopulation, and $n_E$ is the number of voters. Finally, we will use $f$ to denote the fracction of voters who belong to a subpopulation, e.g. $f_E = n_E / n_T$.\n\n\n### General Solution\nSince each voter places their vote by independently flipping a fair coin, the total number of votes for candidate A is distributed as $v_\\text{T} \\sim \\text{Binomial}(n_T,~0.5)$, and this remains true when we sub-divide into regular and early voter sub-populations. That is,\n\n$$\\begin{array}{ccl}\nv_R &\\sim& \\text{Binomial}(n_R,~0.5). \\\\\nv_E &\\sim& \\text{Binomial}(n_E,~0.5), \\\\\n\\end{array}$$\n\nThe prompt tells us that the population is \"large,\" which is a hint that we should  think about using the Normal approximation to the Binomial. To that end, we recall that if $m \\sim \\text{Binomial}(n, p)$, then $m$ is approximately $\\text{Normal}(\\mu_m,\\sigma_m)$, where $\\mu_m = E[m] = pn$, and $\\sigma_m = \\sqrt{np(1-p)}$. Hence,\n\n$$\\begin{array}{ccl}\nv_R &\\approx& \\text{Normal}(\\mu_R,\\sigma_R). \\\\\nv_E &\\approx& \\text{Normal}(\\mu_E,\\sigma_E), \\\\\n\\end{array}$$\n\nwhere $\\mu_R = 0.5n_R$, $\\sigma_R = 0.5 \\sqrt{n_R}$ and an analogous expressions hold for $\\mu_E$ and $\\sigma_E$. \n\nAn election upset will occur if candidate A wins the regular vote but loses the total vote, or if candidate A loses the regular vote and wins the total vote. Since both events occur with equal probability (since candidate A and B are interchangeable), it follows that\n\n$$P(\\text{upset}) = 2 \\cdot P(\\text{A loses the total vote} \\cap \\text{A wins the regular vote}).$$\n\nWe can then re-write this as,\n\n$$\\begin{eqnarray}\nP(\\text{upset}) &=& 2 \\cdot P(\\text{A wins the regular vote} \\cap \\text{A loses the total vote}) \\\\\n&=& 2 \\cdot P(v_R > 0.5 \\cdot n_R \\text{ and }  v_T < 0.5 \\cdot n_T)\\\\\n&=& 2 \\cdot P(v_R > 0.5 \\cdot n_R \\text{ and } v_E + v_R < 0.5 \\cdot (n_E + n_R)) \\\\\n&=& 2 \\cdot P(v_R > \\mu_R \\text{ and } v_E + v_R < \\mu_E+\\mu_R) \\\\\n&=& 2 \\cdot P(v_R > \\mu_R \\text{ and } v_E < \\mu_E + \\mu_R - v_R). \\\\\n\\end{eqnarray}$$\n\nHere we have used the fact that candidate A wins a round of votes if $v > 0.5\\cdot n$, and used the expressions for $\\mu_R, \\mu_E$ from above. \n\nNext, we note that $v_E$ and $v_R$ are independent so their joint density is just the product of their respective densities. Using this obsevation and the fact that both variables are normally distributed we obtain:\n\n$$P(\\text{upset}) = 2 \\cdot \\int_{\\mu_R}^\\infty \\,dv_R \\int_{-\\infty}^{\\mu_R + \\mu_E - v_R}\\,dv_E \n\\frac{e^{-\\frac{1}{2}(\\frac{v_R-\\mu_R}{\\sigma_R})^2}}{\\sigma_R\\sqrt{2\\pi}}\n\\frac{e^{-\\frac{1}{2}(\\frac{v_E-\\mu_E}{\\sigma_E})^2}}{\\sigma_E\\sqrt{2\\pi}}.$$\n\nWe will now manipulate this expression so that it matches an expression that I managed to find in a table of integrals 🙂. To that end, we make the substitution $w_R = \\frac{v_R-\\mu_R}{\\sigma_R\\sqrt{2}}$, $w_E = \\frac{v_E -\\mu_E}{\\sigma_E\\sqrt{2}}$, which (after some book-keeping) yields:\n\n$$P(\\text{upset}) = 2 \\cdot \\int_{0}^\\infty \\,dw_R \\frac{e^{-w_R^2}}{\\sqrt{\\pi}} \\int_{-\\infty}^{-\\frac{\\sigma_R}{\\sigma_E}w_R}\\,dw_E \\frac{e^{-w_E^2}}{\\sqrt{\\pi}}$$\n\nNext, we recall that $$\\text{erfc}(x) = \\frac{2}{\\sqrt{\\pi}} \\int_x^\\infty e^{-t^2}\\,dt$$, and that $$\\text{erf}(x) = 1 - \\text{erfc}(x)$$ so the above can be written:\n\n$$\\begin{eqnarray}\nP(\\text{upset}) &=&\\int_{0}^\\infty \\,dw_R \\frac{e^{-w_R^2}}{\\sqrt{\\pi}} \\left(1 - \\text{erf}(\\frac{\\sigma_R}{\\sigma_E}w_R)\\right)\\\\\n&=&\\int_{0}^\\infty \\,dw_R \\frac{e^{-w_R^2}}{\\sqrt{\\pi}} - \\frac{1}{\\sqrt{\\pi}} \\cdot \\int_{0}^\\infty\\,dw_R~e^{-w_R^2} \\cdot \\text{erf}(\\frac{\\sigma_R}{\\sigma_E}w_R)\n\\end{eqnarray}$$\n\nThe first integral is equal to $\\frac{1}{2}\\text{erfc}(0) = \\frac{1}{2}$. For the second integral, we apply formula 2 from section 4.3 of [this table of integrals involving error functions](https://nvlpubs.nist.gov/nistpubs/jres/73b/jresv73bn1p1_a1b.pdf) with $a = \\sigma_R/\\sigma_E$ and $b = 1$, to obtain:\n\n$$\\begin{eqnarray}\nP(\\text{upset})&=&\\frac{1}{2} - \\frac{1}{\\sqrt{\\pi}} \\left[\\frac{\\sqrt{\\pi}}{2} - \\frac{1}{\\sqrt{\\pi}}\\tan^{-1}\\left(\\frac{\\sigma_E}{\\sigma_R}\\right)\\right]\\\\\n&=&\\frac{1}{\\pi}\\tan^{-1}\\left(\\frac{\\sigma_E}{\\sigma_R}\\right)\n\\end{eqnarray}$$\n\nFinally, since $\\sigma_E = \\sqrt{\\frac{1}{2}f_E\\cdot n_\\text{total}}$, $\\sigma_R = \\sqrt{\\frac{1}{2}f_R\\cdot n_\\text{total}}$, and $f_E + f_R = 1$, we conclude that:\n\n$$\\boxed{P(\\text{upset})=\\frac{1}{\\pi}\\tan^{-1}\\left(\\sqrt{\\frac{f_E}{1-f_E}}\\right)}$$\n\n### Solution for the Prompt\nIn particular, for the case outlined in prompt with $f_E = 0.2$, we find:\n\n$$\\boxed{P\\left(\\text{upset}_\\text{prompt}\\right) = \\frac{1}{\\pi} \\tan^{-1}\\left(\\frac{1}{2}\\right) \\approx 0.14758}$$\n\n\"\"\"\n\n# ╔═╡ 70ef11be-81b9-4e4d-b83a-f7a225a9001b\nfunction exact_prob_upset(frac_early)\n\treturn (1/π) * atan(sqrt(frac_early / (1 - frac_early)))\nend\n\n# ╔═╡ 24e2efe2-f6f2-4648-8c28-bffedf98095b\nexact_prob_upset(0.2)\n\n# ╔═╡ 2383b70b-0693-4adf-99d4-9bcedec5d6cb\nmd\"\"\"\n## Simulation Solution\n\nAs discussed above, the number of votes for candidate A in the early and regular vote subpopulations are both Binomial random variables. So, we  simulate the election tally by simulating appropriate Binomial random variables. From the simulated results, we next determine if A wins on election night (i.e. if more than 50% of the regular vote is for A) and determine the overall winner (i.e. if more than 50% of the total vote is for A). An election upset results if A wins in either the regular or total tally, but loses in the other tally. We simulate this process 100K times and tally up the fraction of times that an election upset occurred.\n\nThis process is repeated for 1001 evenly spaced early voter share fractions in [0,1], and the result is then compared (graphically) against the analytical solution.\n\"\"\"\n\n# ╔═╡ 562b2637-ec4f-4be2-a525-09e83c6458fa\n\"\"\"\n    simulate_election(frac_early, n_simulations, [n_country, p_A])\n\n\tInputs:\n\tfrac_early - percentage of early voters, 20% in the problem prompt\n\tn_simulations - number of simulations to run\n\n\tOptional:\n\tn_country - Has to be big-enough™. defaults to 100_001 votes \n\tp_A - probability that a voter selects candidate A. defaults to 0.5\n\n\tOutput:\n\testimated probability of an upset to the election night results\n\"\"\"\nfunction simulate_election(frac_early, n_simulations, n_country = 100_001, p_A=0.5)\n\t\n\t# number of early and regular voters\n\tn_early = floor(Int, frac_early * n_country)\n\tn_regular = n_country - n_early\n\t\n\t# distributions of votes for A for early and regular voters\n\td_early = Binomial(n_early, p_A)\n\td_regular = Binomial(n_regular, p_A)\n\t\n\t# simulate votes for A for early, regular, and total\n\tn_votes_A_early = rand(d_early, n_simulations)\n\tn_votes_A_regular = rand(d_regular, n_simulations)\n\tn_votes_A = n_votes_A_early + n_votes_A_regular\n\t\n\t# fraction of vote for A between regular and all votes\n\tfrac_votes_A_regular = n_votes_A_regular / n_regular\n\tfrac_votes_A = n_votes_A / n_country\n\t\n\t# determine if A wins on election night and if A wins overall\n\ta_wins_regular = frac_votes_A_regular .> 0.5\n\ta_wins = frac_votes_A .> 0.5\n\t\n\t# an upset occurs if\n\t#  1. A wins  regular, but loses overall (i.e. True, False)\n\t#  2. A loses regular, but wins overall (i.e. False, True)\n\tupset = a_wins_regular .!= a_wins\n\tprob_upset = sum(upset) / n_simulations\n\n\treturn prob_upset\nend\n\n# ╔═╡ 5f82ec16-38a7-4c44-aa5a-f76d18d521dd\nbegin\n\tn_sim = 100_000\n\tn_pop = 10_00_001\n\tfrac_earlys = LinRange(0, 1, 1_001)\n\t\n\tprob_upset_sim = map(fe->simulate_election(fe, n_sim, n_pop), frac_earlys)\n\tprob_upset_exact = map(exact_prob_upset, frac_earlys)\nend\n\n# ╔═╡ b2346518-43b5-4c4d-9536-244514a4d5a3\nplot(\n\tfrac_earlys, \n\thcat(prob_upset_exact, prob_upset_sim), \n\tlabel=[\"Exact\" \"Simulated\"], \n\tlegend=:bottomright,\n\tlinewidth=[5 2],\n\txlabel=\"Fraction of Early Voters\",\n\tylabel=\"Probability of Election Upset\",\n\ttitle=\"Probability of Election Upset \\nvs Fraction of Early Voters\",\n\tsize=(800,500)\n)\n\n\n# ╔═╡ 06cdba4f-426d-47e5-a4c0-c35f9a41d547\nmd\"\"\"\nThe above figure shows great agreement between the exact solution discussed above and the simulation results -- so I'd wager that my exact solution is probably correct! 🙂\n\"\"\"\n\n# ╔═╡ 4a8020c4-b9f4-4c22-8919-eb0f135b1725\nsavefig(\"election_upset_probability.png\")\n\n# ╔═╡ e1bfd335-b818-4931-8e71-03b46c90c9ec\nmd\"\"\"\n### Simulating the Prompt Solution\nFinally, we'll simulate the prompt problem 10 million times to get a bit more accuracy in our simulation.\n\"\"\"\n\n# ╔═╡ e55c8934-7268-4c5f-af6c-2098a48cc094\nbegin\n\tRandom.seed!(2021)\n\tsimulate_election(0.2, 100_000_000, n_pop)\nend\n\n# ╔═╡ 537e2e5d-378b-4676-8ba4-3a50f54eb84c\nmd\"\"\"\nSetting the seed for reproducibility (but not selecting it to cherry-pick!), the simulation result agrees with the theoretical result to around four decimal places, which is pretty good!\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─d79fcb85-28ca-4e32-bc4d-8c442b771cd6\n# ╟─7c4713bb-7e75-4c0b-815c-e817b71e2f8b\n# ╠═70ef11be-81b9-4e4d-b83a-f7a225a9001b\n# ╠═24e2efe2-f6f2-4648-8c28-bffedf98095b\n# ╟─2383b70b-0693-4adf-99d4-9bcedec5d6cb\n# ╠═562b2637-ec4f-4be2-a525-09e83c6458fa\n# ╠═5f82ec16-38a7-4c44-aa5a-f76d18d521dd\n# ╠═b2346518-43b5-4c4d-9536-244514a4d5a3\n# ╟─06cdba4f-426d-47e5-a4c0-c35f9a41d547\n# ╟─4a8020c4-b9f4-4c22-8919-eb0f135b1725\n# ╟─e1bfd335-b818-4931-8e71-03b46c90c9ec\n# ╠═e55c8934-7268-4c5f-af6c-2098a48cc094\n# ╟─537e2e5d-378b-4676-8ba4-3a50f54eb84c\n# ╠═17ada06e-a49a-11eb-29f8-35891d4afe6c\n", "meta": {"hexsha": "3b2c20d2df4a059cd32e9c3fbccf414ce2a00bea", "size": 11215, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "assets/posts/20210426_RiddlerRandomElectionUpsets/random_elections.jl", "max_stars_repo_name": "pkepley/pkepley.github.io", "max_stars_repo_head_hexsha": "e507941ebff889f8c5c6b5e3a5b294a0886cf86f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assets/posts/20210426_RiddlerRandomElectionUpsets/random_elections.jl", "max_issues_repo_name": "pkepley/pkepley.github.io", "max_issues_repo_head_hexsha": "e507941ebff889f8c5c6b5e3a5b294a0886cf86f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assets/posts/20210426_RiddlerRandomElectionUpsets/random_elections.jl", "max_forks_repo_name": "pkepley/pkepley.github.io", "max_forks_repo_head_hexsha": "e507941ebff889f8c5c6b5e3a5b294a0886cf86f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.9737991266, "max_line_length": 651, "alphanum_fraction": 0.7209094962, "num_tokens": 3932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.924141826246517, "lm_q2_score": 0.863391624034103, "lm_q1q2_score": 0.7978963122008221}}
{"text": "export project_l1_Duchi!\nfunction project_l1_Duchi!(v::Union{Vector{TF},Vector{Complex{TF}}}, b::TF) where {TF<:Real}\n# % PROJECTONTOL1BALL Projects point onto L1 ball of specified radius.\n# %\n# % w = ProjectOntoL1Ball(v, b) returns the vector w which is the solution\n# %   to the following constrained minimization problem:\n# %\n# %    min   ||w - v||_2\n# %    s.t.  ||w||_1 <= b.\n# %\n# %   That is, performs Euclidean projection of v to the 1-norm ball of radius\n# %   b.\n# %\n# % Author: John Duchi (jduchi@cs.berkeley.edu)\n# Translated (with some modification) to Julia 1.1 by Bas Peters\nif (b <= TF(0))\n  error(\"Radius of L1 ball is negative\");\nend\nif norm(v, 1) <= b\n  return v\nend\nlv=length(v)\nu = Vector{TF}(undef,lv)\nsv= Vector{TF}(undef,lv)\n\n#u = sort(abs(v),'descend');\n#u = sort(abs.(v), rev=true) #faster than the line below\n#u = sort(v, by=abs , rev=true)\n\n#use RadixSort for Float32 (short keywords)\nu=copy(v)\nif TF==Float32\n u = sort!(abs.(u), rev=true,alg=RadixSort)\nelse\n u = sort!(abs.(u), rev=true,alg=QuickSort)\nend\n\n#sv = cumsum(u);\nsv = cumsum(u)\n\n#rho = find(u > (sv - b) ./ (1:length(u))', 1, 'last');\n#tmp = (u .> ((sv.-b)./ LinSpace(1,lv,lv)))#::BitVector\n\nrho = max(1,min(lv,findlast(u .> ((sv.-b)./ (1.0:1.0:lv)))))\n#convert(TF,rho) why was this here...\n#rho = findlast(tmp)::Int64\n\n#theta = max(0, (sv(rho) - b) / rho);\ntheta = max.(TF(0) , (sv[rho] .- b) ./ rho)::TF\n\n#w = sign(v) .* max(abs(v) - theta, 0);\nv .= sign.(v) .* max.(abs.(v) .- theta, TF(0))\n\nreturn v\nend #end project_l1_Duchi\n#\n# function project_l1_Duchi!{TF<:Real}(v::Union{Array{TF,3},Array{Complex{TF},3}}, b::TF,mode::String)\n#\n# if (b < TF(0))\n#   error(\"Radius of L1 ball is negative\");\n# end\n# (n1,n2,n3)=size(v)\n#\n# ##Slice based projection\n# if mode == \"x_slice\"\n#   u = Vector{TF}(n2*n3)\n#   sv= Vector{TF}(n2*n3)\n#   v = reshape(v,n1,n2*n3)\n#   Threads.@threads for i=1:n1\n#     u = sort(abs.(v[i,:]), rev=true)\n#     sv = cumsum(u)\n#     rho = findlast(u .> ((sv.-b)./ (1.0:1.0:(n2*n3))))\n#     theta = max.(TF(0) , (sv[rho] .- b) ./ rho)::TF\n#     @inbounds v[i,:] .= sign.(v[i,:]) .* max.(abs.(v[:,i]).-theta, TF(0))\n#   end\n#   v = reshape(v,n1,n2,n3)\n# elseif mode == \"z_slice\"\n#   u = Vector{TF}(n1*n2)\n#   sv= Vector{TF}(n1*n2)\n#   v = reshape(v,n1*n2,n3)\n#   Threads.@threads for i=1:n3\n#     u = sort(abs.(v[:,i]), rev=true)\n#     sv = cumsum(u)\n#     rho = findlast(u .> ((sv.-b)./ (1.0:1.0:(n1*n2))))\n#     theta = max.(TF(0) , (sv[rho] .- b) ./ rho)::TF\n#     @inbounds v[:,i] .= sign.(v[:,i]) .* max.(abs.(v[:,i]).-theta, TF(0))\n#   end\n#   v = reshape(v,n1,n2,n3)\n# elseif mode == \"y_slice\"\n#   permutedims(v,[2;1;3]);\n#   v = reshape(v,n2,n1*n3)\n#   u = Vector{TF}(n1*n3)\n#   sv= Vector{TF}(n1*n3)\n#   Threads.@threads for i=1:size(v,1)\n#     u = sort(abs.(v[i,:]), rev=true)\n#     sv = cumsum(u)\n#     rho = findlast(u .> ((sv.-b)./ (1.0:1.0:(n1*n3))))\n#     theta = max.(TF(0) , (sv[rho] .- b) ./ rho)::TF\n#     @inbounds v[i,:] .= sign.(v[i,:]) .* max.(abs.(v[:,i]).-theta, TF(0))\n#   end\n#   v = reshape(v,n2,n1,n3);\n#   permutedims(v,[2;1;3]);\n# else\n#   error(\"provided incorred mode for l1_projection\")\n# end #end if\n# v=vec(v)\n#\n# return v\n# end #end project_l1_Duchi\n", "meta": {"hexsha": "9ba677c39fd789904f319d214c40efa7e81aa62f", "size": 3197, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/projectors/project_l1_Duchi!.jl", "max_stars_repo_name": "slimgroup/SetIntersectionProjection.jl", "max_stars_repo_head_hexsha": "ffbc7cbca7342dcb0c9d28263295a1b1fd8833aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-04-22T18:13:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T18:57:30.000Z", "max_issues_repo_path": "src/projectors/project_l1_Duchi!.jl", "max_issues_repo_name": "slimgroup/SetIntersectionProjection.jl", "max_issues_repo_head_hexsha": "ffbc7cbca7342dcb0c9d28263295a1b1fd8833aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-08T18:09:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:47:15.000Z", "max_forks_repo_path": "src/projectors/project_l1_Duchi!.jl", "max_forks_repo_name": "slimgroup/SetIntersectionProjection.jl", "max_forks_repo_head_hexsha": "ffbc7cbca7342dcb0c9d28263295a1b1fd8833aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-10-30T22:32:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T14:07:13.000Z", "avg_line_length": 29.0636363636, "max_line_length": 102, "alphanum_fraction": 0.5639662183, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.863391602943619, "lm_q1q2_score": 0.7978962909063799}}
{"text": "\r\n\r\ninclude(\"../../common/numder/src/numder_module.jl\")\r\n# include(\"testfunctions.jl\")\r\n\r\nmodule opti\r\nusing ..numder\r\nusing LinearAlgebra\r\n\r\ninclude(\"opti_1d.jl\")\r\ninclude(\"line_search.jl\")\r\ninclude(\"gradient_descent.jl\")\r\n\r\n\r\nmutable struct BFGS <: DescentMethod\r\n    B\r\nend\r\nfunction BFGS(x::Vector{T}) where {T}\r\n    BFGS( Matrix(one(T)*I, length(x), length(x)) )\r\nend\r\n\r\nfunction init!(m::BFGS, x)\r\n    m.B = Matrix(one(eltype(x))*I, length(x), length(x))\r\nend\r\n\r\nfunction bfgs_matrix_update(B, g, g_prev, x, x_prev)\r\n    dg = g - g_prev\r\n    dx = x - x_prev\r\n\r\n    dxdg = dot(dx, dg)\r\n    \r\n    if dxdg < 0\r\n        println(\"No update happens, some accuracy errors\")\r\n        println(\" dxdg = $(dxdg) \")\r\n        return B\r\n    end\r\n\r\n    t1 = (dx ./ dxdg) * (dg' * B)\r\n    t1 = t1 + t1'\r\n\r\n    t2f = 1 + (dg' * (B * dg)) / dxdg\r\n    t2 = (dx .* (t2f / dxdg)) * dx'\r\n\r\n    # B = B - t1 + t2\r\n    B += (t2 - t1)\r\n    return B\r\nend\r\n\r\nfunction quasi_newton(\r\n    fcn,\r\n    x0;\r\n    tol_options::ToleranceOptions       = ToleranceOptions(),\r\n    search_options::LineSearchOptions   = LineSearchOptions(),\r\n    gradient_fcn                        = numder.gradient_fw,\r\n    line_search_fcn                     = line_search,\r\n    log_path                            = false)\r\n\r\n    m = BFGS(x0)\r\n\r\n    x = x0\r\n    f = fcn(x)\r\n    g = gradient_fcn(fcn, x)\r\n\r\n    step_direction  = -m.B * g\r\n    step_size       = line_search_fcn(fcn, x, step_direction, f, search_options)\r\n    dx              = step_size * step_direction\r\n    g_new           = gradient_fcn(fcn, x + dx)\r\n    dg              = g_new - g\r\n    m.B             = m.B * dot(dg, dx) / dot(dg, dg)\r\n\r\n    x_prev  = x\r\n    x       = x_prev + dx\r\n    f_prev  = f\r\n    f       = fcn(x)\r\n    g_prev  = g\r\n    g       = g_new\r\n\r\n\r\n\r\n    # out parameters\r\n    x_sol = x\r\n    y_sol = f\r\n    stopping_crit = unknown::GradientDescentStoppingCrit\r\n\r\n\r\n\r\n    iter = 0\r\n    for outer iter = 1:tol_options.max_iter\r\n\r\n        # update B\r\n        # dg = g - g_prev\r\n        # dx = x - x_prev\r\n\r\n        # dxdg = dot(dx, dg)\r\n\r\n        # t1 = (dx ./ dxdg) * (dg' * m.B)\r\n        # t1 = t1 + t1'\r\n\r\n        # t2f = 1 + (dg' * (m.B * dg)) / dxdg\r\n        # t2 = (dx .* (t2f / dxdg)) * dx'\r\n\r\n        # m.B = m.B - t1 + t2\r\n\r\n        m.B = bfgs_matrix_update(m.B, g, g_prev, x, x_prev)\r\n\r\n        # step dir\r\n        step_direction = - m.B * g\r\n        step_size      = line_search_fcn(fcn, x, step_direction, f, search_options)\r\n\r\n        dx = step_direction * step_size\r\n\r\n\r\n        # stopping criterion based on the step size\r\n        abs_step_size = norm( dx )\r\n        if abs_step_size <= tol_options.step_size_tol\r\n            x_sol = x\r\n            y_sol = f\r\n            stopping_crit = small_step_size::GradientDescentStoppingCrit\r\n            break\r\n        end\r\n\r\n\r\n        x_prev = x\r\n        x      = x_prev + dx\r\n        f_prev = f\r\n        f      = fcn(x)\r\n        g_prev = g\r\n\r\n\r\n        # stopping criteria for function value\r\n        if abs(f - f_prev) <= tol_options.f_abs_tol || abs(f - f_prev) / ( abs(f_prev) == 0 ? mach_eps : abs(f_prev)) < tol_options.f_rel_tol\r\n            x_sol = x\r\n            y_sol = f\r\n            stopping_crit = small_function_value_delta::GradientDescentStoppingCrit\r\n            break\r\n        end\r\n\r\n\r\n        # calculate the gradient at the new point\r\n        g = gradient_fcn(fcn, x)\r\n\r\n\r\n        # stopping criterion based on the gradient norm\r\n        norm_g = norm(g)\r\n        if norm_g <= tol_options.g_abs_tol\r\n            x_sol = m.x\r\n            y_sol = m.f\r\n            stopping_crit = small_gradient::GradientDescentStoppingCrit\r\n            break\r\n        end\r\n\r\n    end\r\n\r\n    return (x_sol, y_sol, iter, stopping_crit)\r\n\r\nend\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nfunction bfgs(\r\n\tfcn,\r\n\tx0;\r\n\tgrad_fcn = numder.gradient_fw,\r\n\toptions = ToleranceOptions() )\r\n\r\n    n_dim = length(x0)\r\n    H     = Matrix{Float64}(I, n_dim, n_dim)\r\n    eye   = Matrix{Float64}(I, n_dim, n_dim)\r\n\r\n    # first step is the steepest gradient descent\r\n    g0        = grad_fcn(fcn, x0)\r\n    step_size = line_search(fcn, x0, -g0)\r\n    x1        = x0 - step_size * g0\r\n    g1        = grad_fcn(fcn, x1)\r\n\r\n    y            = g1 - g0\r\n    s            = -step_size * g0\r\n    scale_factor = dot(y, s) / dot(y, y)\r\n    for ii = 1:n_dim\r\n        H[ii, ii] *= scale_factor\r\n    end\r\n\r\n    # main loop\r\n    iter = 0\r\n    for outer iter = 1:options.max_iter\r\n\r\n        # update of the matrix\r\n        s       = x1 - x0\r\n        y       = g1 - g0\r\n        \r\n\t\tsdy     = dot(s, y)\r\n\t\tHs \t\t= H * s\r\n\t\tsHs     = dot(s, Hs)\r\n\t\ttheta   = 1.0\r\n\t\tif sdy < 0.2 * sHs\r\n\t\t\ttheta = 0.8 * sHs / (sHs - sdy)\r\n\t\tend\r\n\r\n\t\tr = theta * y + (1 - theta) * Hs\r\n\r\n        Hy      = H * y\r\n\t\trho     = 1 / sdy\r\n        rhos    = rho * s\r\n        Hyst    = Hy * rhos'\r\n        sytHyst = rhos * (y' * Hyst)\r\n        # sst     = rhos * s'\r\n        sst \t= r * r' / dot(s, r)\r\n\r\n\t\tHnew    = H - (Hyst + Hyst') + sytHyst + sst\r\n        # Hnew   = (eye - rho * s * y') * H * (eye - rho * y * s') + rho * s * s'\r\n\r\n        # dH = norm(Htest - Hnew)\r\n        # println(dH)\r\n\r\n        x0        = x1\r\n        p         = -(Hnew * g1)\r\n        step_size = line_search(fcn, x0, p)\r\n        dx        = p * step_size\r\n        x1        = x0 + dx\r\n\r\n        if norm(dx) <= options.step_size_tol\r\n            break\r\n        end\r\n        \r\n        # options.f_abs_tol\r\n        # options.f_rel_tol\r\n        \r\n        g0        = g1\r\n        g1        = grad_fcn(fcn, x1)\r\n\r\n        if norm(g1) <= options.g_abs_tol\r\n            break\r\n        end\r\n\r\n\r\n        H = Hnew\r\n    end\r\n\r\n    return (x1, iter)\r\nend\r\n\r\n\r\nend # opti\r\n\r\n\r\n#=\r\n\r\nfunction nonlinear_conjugate_gradient_descent_template(beta_method, fcn, x0, options, wolfe_condition_options)\r\n\tx_act = x0\r\n\ty_act = fcn(x_act)\r\n\tx_next = x_act\r\n\tx_sol = x_act\r\n\r\n\t# first step is a gradient descent step\r\n\tg_act = NumDiff.gradient_fw(fcn, x_act)\r\n\tdirection_act = -g_act\r\n\talpha = strong_wolfe_line_search(fcn, x_act, direction_act,\r\n\t \t\t\t\t\t\t\t\twolfe_condition_options.alpha_0,\r\n\t\t\t\t\t\t\t\t\twolfe_condition_options.beta,\r\n\t\t\t\t\t\t\t\t\twolfe_condition_options.sigma)\r\n\tstep = alpha * direction_act\r\n\tx_act = x_act + step\r\n\ty_act = fcn(x_act)\r\n\tg_prev = g_act\r\n\tdirection_prev = direction_act\r\n\r\n\t# main loop\r\n\tprintln(\"x: $x_act\")\r\n\titer = 1\r\n\tfor outer iter = 1:options.max_iter\r\n\r\n\t\tg_act = NumDiff.gradient_fw(fcn, x_act)\r\n\r\n\t\t## specific method is applied\r\n\t\tbeta = beta_method(g_act, g_prev, direction_prev)\r\n\r\n\r\n\t\tdirection_act = -g_act + beta .* direction_prev\r\n\r\n\t\talpha = strong_wolfe_line_search(fcn, x_act, direction_act)\r\n\t\tstep = alpha * direction_act\r\n\t\tx_next = x_act + step\r\n\t\ty_next = fcn(x_next)\r\n\r\n\t\t# convergence checks\r\n\t\tif norm(g_act) <= options.gradient_tolerance\r\n\t\t\tx_sol = x_next\r\n\t\t\tbreak\r\n\t\tend\r\n\t\tif norm(step) <= options.step_tolerance\r\n\t\t\tx_sol = x_next\r\n\t\t\tbreak\r\n\t\tend\r\n\t\tif abs(y_next - y_act) <= options.function_value_change_tolerance\r\n\t\t\tx_sol = x_next\r\n\t\t\tbreak\r\n\t\tend\r\n\r\n\t\t# updates\r\n\t\ty_act = y_next\r\n\t\tx_act = x_next\r\n\t\tdirection_prev = direction_act\r\n\t\tprintln(\"x: $x_act\")\r\n\tend\r\n\r\n\tif iter == options.max_iter\r\n\t\tx_sol = x_next\r\n\tend\r\n\treturn x_sol\r\nend\r\n\r\nfunction beta_polak_ribiere(g_act, g_prev, direction_prev)\r\n\ty_hat = g_act - g_prev\r\n\tbeta = dot(g_act, y_hat) / dot( g_prev, g_prev )\r\n\tbeta = max(beta, 0)\r\n\treturn beta\r\nend\r\n\r\n\r\nfunction beta_dai_yuan(g_act, g_prev, direction_prev)\r\n\ty_hat = g_act - g_prev\r\n\tbeta = dot(g_act, g_act) / dot(y_hat, direction_prev)\r\n\tbeta = max(beta, 0)\r\n\treturn beta\r\nend\r\n\r\nfunction beta_hestenes_stiefel(g_act, g_prev, direction_prev)\r\n\ty_hat = g_act - g_prev\r\n\tbeta = dot(y_hat, g_act) / dot(y_hat, direction_prev)\r\n\tbeta = max(beta, 0)\r\n\treturn beta\r\nend\r\n\r\nfunction beta_hager_zhang(g_act, g_prev, direction_prev)\r\n\t# probably implementation error\r\n\ty_hat = g_act - g_prev\r\n\tnumer = dot(y_hat, direction_prev)\r\n\tt1 = y_hat - 2 .* direction_prev .* dot(y_hat, y_hat) ./ numer\r\n\tt2 = g_act ./ numer\r\n\tbeta = dot(t1, t2)\r\n\t# beta = max(beta, 0)\r\n\treturn beta\r\nend\r\n\r\n\r\nfunction nonlinear_conjugate_gradient_descent_polak_ribiere(\r\n\tfcn,\r\n\tx0,\r\n\toptions::GradientDescentOptions = default_options(GradientDescentOptions),\r\n\twolfe_condition_options = default_strong_wolfe_conditions_options()\r\n\t)\r\n\tx_sol = nonlinear_conjugate_gradient_descent_template(beta_polak_ribiere, fcn, x0, options, wolfe_condition_options)\r\nend\r\n\r\nfunction nonlinear_conjugate_gradient_descent_dai_yuan(\r\n\tfcn,\r\n\tx0,\r\n\toptions::GradientDescentOptions = default_options(GradientDescentOptions),\r\n\twolfe_condition_options = default_strong_wolfe_conditions_options()\r\n\t)\r\n\tx_sol = nonlinear_conjugate_gradient_descent_template(beta_dai_yuan, fcn, x0, options, wolfe_condition_options)\r\nend\r\n\r\nfunction nonlinear_conjugate_gradient_descent_hestenes_stiefel(\r\n\tfcn,\r\n\tx0,\r\n\toptions::GradientDescentOptions = default_options(GradientDescentOptions),\r\n\twolfe_condition_options = default_strong_wolfe_conditions_options()\r\n\t)\r\n\tx_sol = nonlinear_conjugate_gradient_descent_template(beta_hestenes_stiefel, fcn, x0, options, wolfe_condition_options)\r\nend\r\n\r\nfunction nonlinear_conjugate_gradient_descent_hager_zhang(\r\n\tfcn,\r\n\tx0,\r\n\toptions::GradientDescentOptions = default_options(GradientDescentOptions),\r\n\twolfe_condition_options = default_strong_wolfe_conditions_options()\r\n\t)\r\n\tx_sol = nonlinear_conjugate_gradient_descent_template(beta_hager_zhang, fcn, x0, options, wolfe_condition_options)\r\nend\r\n\r\n=#", "meta": {"hexsha": "a2da9832e8950e212481d854a6fdb4b65e4766bb", "size": 9425, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/opti/src/opti_module.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "__lib__/math/opti/src/opti_module.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "__lib__/math/opti/src/opti_module.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2287917738, "max_line_length": 142, "alphanum_fraction": 0.584933687, "num_tokens": 2762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760638, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7978951059841283}}
{"text": "using AdFem\nusing PyPlot\nusing SparseArrays\n\n\n\nfunction f1func(x,y)\n    18.8495559215388*pi^2*sin(pi*x)^2*sin(pi*y)*cos(pi*y) - 6.28318530717959*pi^2*sin(pi*y)*cos(pi*x)^2*cos(pi*y) + pi*sin(pi*y)*cos(pi*x)\nend\nfunction f2func(x,y)\n    -18.8495559215388*pi^2*sin(pi*x)*sin(pi*y)^2*cos(pi*x) + 6.28318530717959*pi^2*sin(pi*x)*cos(pi*x)*cos(pi*y)^2 + pi*sin(pi*x)*cos(pi*y)\nend\n\nm = 50\nn = 50\nh = 1/n\nν = 0.5\nK = ν*constant(compute_fem_laplace_matrix(m, n, h))\nB = constant(compute_interaction_matrix(m, n, h))\nZ = [K -B'\n-B spzero(size(B,1))]\n\nbd = bcnode(\"all\", m, n, h)\n# Due to the rank insufficiency of bilinear quadrilateral element, \n# we add more pressure constraints \nbd = [bd; bd .+ (m+1)*(n+1); ((1:m) .+ 2(m+1)*(n+1))] \n\nF1 = eval_f_on_gauss_pts(f1func, m, n, h)\nF2 = eval_f_on_gauss_pts(f2func, m, n, h)\nF = compute_fem_source_term(F1, F2, m, n, h)\nrhs = [F;zeros(m*n)]\nZ, rhs = impose_Dirichlet_boundary_conditions(Z, rhs, bd, zeros(length(bd)))\nsol = Z\\rhs \n\nsess = Session(); init(sess)\nS = run(sess, sol)\n\nxy = fem_nodes(m, n, h)\nx, y = xy[:,1], xy[:,2]\nU = @. 2*pi*sin(pi*x)*sin(pi*x)*cos(pi*y)*sin(pi*y)\nfigure(figsize=(12,5))\nsubplot(121)\nvisualize_scalar_on_fem_points(U, m, n, h)\ntitle(\"Reference\")\nsubplot(122)\nvisualize_scalar_on_fem_points(S[1:(m+1)*(n+1)], m, n, h)\ntitle(\"Computed\")\nsavefig(\"stokes1.png\")\n\nU = @. -2*pi*sin(pi*x)*sin(pi*y)*cos(pi*x)*sin(pi*y)\nfigure(figsize=(12,5))\nsubplot(121)\nvisualize_scalar_on_fem_points(U, m, n, h)\ntitle(\"Reference\")\nsubplot(122)\nvisualize_scalar_on_fem_points(S[(m+1)*(n+1)+1:2(m+1)*(n+1)], m, n, h)\ntitle(\"Computed\")\nsavefig(\"stokes2.png\")\n\n\nxy = fvm_nodes(m, n, h)\nx, y = xy[:,1], xy[:,2]\np = @. sin(pi*x)*sin(pi*y)\nfigure(figsize=(12,5))\nsubplot(121)\nvisualize_scalar_on_fvm_points(p, m, n, h)\ntitle(\"Reference\")\nsubplot(122)\nvisualize_scalar_on_fvm_points(S[2(m+1)*(n+1)+1:end], m, n, h)\ntitle(\"Computed\")\nsavefig(\"stokes3.png\")", "meta": {"hexsha": "025ba4397a987f5618e8553270656cdd3e38d075", "size": 1899, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/codes/Stokes/structured_forward.jl", "max_stars_repo_name": "kailaix/AdFem.jl", "max_stars_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2020-10-18T01:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:13:24.000Z", "max_issues_repo_path": "docs/src/codes/Stokes/structured_forward.jl", "max_issues_repo_name": "kailaix/AdFem.jl", "max_issues_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-10-19T03:51:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:38:46.000Z", "max_forks_repo_path": "docs/src/codes/Stokes/structured_forward.jl", "max_forks_repo_name": "kailaix/AdFem.jl", "max_forks_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-11-05T11:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T19:30:09.000Z", "avg_line_length": 26.7464788732, "max_line_length": 139, "alphanum_fraction": 0.6582411796, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741214369554, "lm_q2_score": 0.8376199633332893, "lm_q1q2_score": 0.7978951006702628}}
{"text": "module problem122\n\ndescription = \"\"\"\nEfficient exponentiation\n\nThe most naive way of computing n15 requires fourteen multiplications:\nn × n × ... × n = n15\n\nBut using a \"binary\" method you can compute it in six multiplications:\n\nn × n = n^2\nn^2 × n^2 = n^4\nn^4 × n^4 = n^8\nn^8 × n^4 = n^12\nn^12 × n^2 = n^14\nn^14 × n = n^15\n\nHowever it is yet possible to compute it in only five multiplications:\n\nn × n = n^2\nn^2 × n = n^3\nn^3 × n^3 = n^6\nn^6 × n^6 = n^12\nn^12 × n^3 = n^15\n\nWe shall define m(k) to be the minimum number of multiplications to compute nk; for example m(15) = 5.\nFor 1 ≤ k ≤ 200, find ∑ m(k).\n\"\"\"\n\n# Calculates the minimum number of multiplications to compute n^k\n# given the known powers, and a maximum cutoff\nfunction muls(k :: Int, known = [1], maxp = k-1)\n  if (k % 2) == 0\n    return muls(div(k,2)) + 1 # for even powers, solution is always to square the half power\n  \n  elseif known[end] == k \n    return length(known)-1  # solution found\n  \n  elseif length(known) >= maxp # no solution for given known path\n    return -1\n  \n  elseif (maxp - length(known)) < floor(log2(k / known[end])) # no possible solution for given knowns\n    return -1\n  end\n\n  # search for solutions by summing items in the knowns path\n  for i = length(known):-1:1\n    for j = i:-1:1\n      n = known[i] + known[j]\n      if n <= k && n > known[end]\n        push!(known, n)\n        result = muls(k, known, maxp)\n        pop!(known)\n        if result == -1\n          break \n        elseif result == length(known)\n          return result\n        elseif result < maxp\n          maxp = result\n        end\n      end\n    end\n  end\n\n  return maxp\nend\n\nfunction solve(maxk = 200)\n  total = 0\n  for i = 1:maxk\n    total += muls(i)\n  end\n  return total\nend\n\nend", "meta": {"hexsha": "6e8dd0798aaad625de03bd9910f311206376cd3d", "size": 1743, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem122.jl", "max_stars_repo_name": "mbuhot/mbuhot-euler-solutions", "max_stars_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-12-18T13:25:41.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-18T13:25:41.000Z", "max_issues_repo_path": "julia/problem122.jl", "max_issues_repo_name": "mbuhot/mbuhot-euler-solutions", "max_issues_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/problem122.jl", "max_forks_repo_name": "mbuhot/mbuhot-euler-solutions", "max_forks_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9342105263, "max_line_length": 102, "alphanum_fraction": 0.6075731497, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224331, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.797895099389363}}
{"text": "function ABCDQR_kfilter(y,u,A,B,C,D,Q,R,x10,P10)\r\n\t# \r\n\t# Kalman filter for model\r\n\t# \r\n\t# x_{t+1} = A*x_{t} + B*u_{t} + w_{t}\r\n\t# y_{t}   = C*x_{t} + D*u_{t} + v_{t}\r\n\t# \r\n\t# cov(w_{t},v_{t}) = [Q 0;0 R]\r\n\t#\r\n\t# javier.cara@upm.es, 2015-10 \r\n\t# \r\n\r\n\t(ny,nt) = size(y)\r\n\tnx = size(A,1)\t\r\n\r\n\t# allocation\r\n\txtt = zeros(nx,nt)\r\n\tPtt = zeros(nx,nx,nt)\r\n\txtt1 = zeros(nx,nt+1)\r\n\tPtt1 = zeros(nx,nx,nt+1)\r\n\tet = zeros(ny,nt)\r\n\tSt = zeros(ny,ny,nt)\r\n\tKt = zeros(nx,ny,nt)\r\n\tloglik = 0.0\r\n\r\n\t# Filter \r\n\txtt1[:,1] = x10\r\n\tPtt1[:,:,1] = P10\r\n\tfor t in 1:nt\t\t\r\n\t\t#  innovations\r\n\t\tet[:,t] = y[:,t] - C*xtt1[:,t] - D*u[:,t]\r\n\t\tSt[:,:,t] = C*Ptt1[:,:,t]*C' + R # et variance\r\n\t\t\r\n\t\t# Kalman gain\r\n\t\tStinv = eye(ny,ny)/St[:,:,t] # numerically preferible to Stinv=inv(St)\r\n\t\tKt[:,:,t] = Ptt1[:,:,t]*C'*Stinv # kalman gain\t\t\r\n\t\t\t\r\n\t\t# filtered values\r\n\t\txtt[:,t] = xtt1[:,t] + Kt[:,:,t]*et[:,t]\r\n\t\tPtt[:,:,t] = (eye(nx) - Kt[:,:,t]*C)*Ptt1[:,:,t]\r\n\t\t\r\n\t\t# one-step ahead prediction\r\n\t\txtt1[:,t+1] = A*xtt[:,t] + B*u[:,t]\r\n\t\tPtt1[:,:,t+1] = A*Ptt[:,:,t]*A' + Q\r\n\t\t\r\n\t\t# likelihood\r\n\t\tl0 = et[:,t]'*Stinv*et[:,t] # typeof(l0) = Array{Float64,1}\r\n\t\tloglik = loglik + log(det(St[:,:,t])) + l0[1]\t\r\n\tend\r\n\t\r\n\tloglik =  - ny*nt/2*log(2*pi) - 0.5*loglik\r\n\r\n\treturn xtt,Ptt,xtt1,Ptt1,et,St,Kt,loglik\r\n\r\nend\r\n\r\n", "meta": {"hexsha": "01e7e5546637fbd53eed21c293ea9009a3d4793f", "size": 1288, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ABCDQR_kfilter.jl", "max_stars_repo_name": "javiercara/emABCDQR.jl", "max_stars_repo_head_hexsha": "21e2994d69956a7dbaba3391ad2a293a7d0ec53a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ABCDQR_kfilter.jl", "max_issues_repo_name": "javiercara/emABCDQR.jl", "max_issues_repo_head_hexsha": "21e2994d69956a7dbaba3391ad2a293a7d0ec53a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ABCDQR_kfilter.jl", "max_forks_repo_name": "javiercara/emABCDQR.jl", "max_forks_repo_head_hexsha": "21e2994d69956a7dbaba3391ad2a293a7d0ec53a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5964912281, "max_line_length": 73, "alphanum_fraction": 0.4914596273, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7978919341392825}}
{"text": "@doc raw\"\"\"\n    PeriodicKernel([α=1 [,p=π]])\n\nThe periodic kernel is given by:\n\n```math\n\\kappa(\\mathbf{x},\\mathbf{y}) =\n\\exp\\left(-\\alpha \\sum_{i=1}^n \\sin(p(x_i - y_i))^2\\right)\n\\qquad p >0, \\; \\alpha > 0\n```\n\nwhere ``\\mathbf{x}`` and ``\\mathbf{y}`` are ``n`` dimensional vectors. The parameters ``p`` \nand ``\\alpha`` are scaling parameters for the periodicity and the magnitude, respectively. \nThis kernel is useful when data has periodicity to it.\n\"\"\"\nstruct PeriodicKernel{T<:AbstractFloat} <: MercerKernel{T}\n    alpha::HyperParameter{T}\n    PeriodicKernel{T}(α::Real) where {T<:AbstractFloat} = new{T}(\n        HyperParameter(convert(T,α), interval(OpenBound(zero(T)), nothing))\n    )\nend\nPeriodicKernel(α::T1 = 1.0) where {T1<:Real} = PeriodicKernel{floattype(T1)}(α)\n\n@inline basefunction(::PeriodicKernel) = SineSquared()\n@inline kappa(κ::PeriodicKernel{T}, z::T) where {T} = squaredexponentialkernel(z, getvalue(κ.alpha))", "meta": {"hexsha": "6aabb1b07cf30aaae669d6d5dd076208fe8ec04b", "size": 931, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernelfunctions/mercer/periodic.jl", "max_stars_repo_name": "holtri/MLKernels.jl", "max_stars_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernelfunctions/mercer/periodic.jl", "max_issues_repo_name": "holtri/MLKernels.jl", "max_issues_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernelfunctions/mercer/periodic.jl", "max_forks_repo_name": "holtri/MLKernels.jl", "max_forks_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.24, "max_line_length": 100, "alphanum_fraction": 0.6799140709, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7977593808142236}}
{"text": "\"\"\"\nExample modelling a linear beam element\n\nFormulation:\n\nK=-E*A*[dw_i!dx*du_j!dx]\n\"\"\"\n\n# local coordinates:\nlocal_interp=InterpolationFunction(\n    :(a0+a1*xi), # interpolation function expression\n    [:xi], # local coordinate system degrees of freedom\n    [:a0, :a1], # linear coefficients for regression\n    [\n        [0] # conditions to impose with regression: absolute value (order 0 derivative in the first axis)\n    ];\n    maximum_derivative=1\n)\n\n# absolute coordinates\nabs_interp=InterpolationFunction(\n    :(a0+a1*x), # interpolation function expression\n    [:x], # absolute coordinate system degrees of freedom\n    [:a0, :a1], # linear coefficients for regression\n    [\n        [0] # conditions to impose with regression: absolute value (order 0 derivative)\n    ];\n    maximum_derivative=1\n)\n\n# defining an integration domain:\ndmn=Domain(\n    local_interp, # local coordinate system\n    [\n        [0.0, 1.0] # boundaries for local coordinates: xi between 0 and 1\n    ],\n    [\n        [0.0], # positions at which to impose values for interpolation:\n        [1.0] # xi=0, xi=1\n    ]\n)\n\n# defining a residual for within the beam:\ndomain_resd=Residual(\n    [\n        ( # variable w (weight), interpolated by InterpolationFunction abs_interp,\n            :w, abs_interp, [\n                (:dw!dx, [1]) # accompanied by its first order derivative\n            ]\n        )\n        ( # variable u (displacement), interpolated by InterpolationFunction abs_interp,\n            :u, abs_interp, [\n                (:du!dx, [1]) # accompanied by its first order derivative\n            ]\n        )\n    ],\n    :(-E*(dw!dx*du!dx)),\n    3; # Gauss-Legendre quadrature order\n    extra_args=[:E, :A] # additional argument: elasticity\n)\n\ndmn_resd_func=get_volume_residual_function(domain_resd)\n\n# defining a specific finite element:\nfin=Finel(\n    [\n        [0.0],\n        [1.0] # defined by corner points at x=0 and x=1 (corresponding to xi=0 and xi=1 in local coordinates: see Domain)\n    ],\n    dmn\n)\n\n# obtaining elasticity matrix:\nK=zeros(Float64, 2, 2)\n\nws=zeros(Float64, 2)\nus=zeros(Float64, 2)\n\nE=1.0\nA=1.0\n\nfor i=1:2\n    ws[i]=1.0\n\n    for j=1:2\n        us[j]=1.0\n\n        variable_vals=[ws, us]\n        K[i, j]=dmn_resd_func(variable_vals, fin, E, A)\n\n        us[j]=0.0\n    end\n\n    ws[i]=0.0\nend\n\n@assert isapprox(\n    K,\n    [\n        -1.0 1.0;\n        1.0 -1.0\n    ]\n)\n", "meta": {"hexsha": "57a84423b1b2653d8beae736a45f10d5b687bde0", "size": 2372, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/AxialBeamElement.jl", "max_stars_repo_name": "pedrosecchi67/SymFinel.jl", "max_stars_repo_head_hexsha": "24cc4110f48af1d33e1ba1837a6436e4d6506c95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-01-11T03:50:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T15:56:29.000Z", "max_issues_repo_path": "examples/AxialBeamElement.jl", "max_issues_repo_name": "pedrosecchi67/SymFinel.jl", "max_issues_repo_head_hexsha": "24cc4110f48af1d33e1ba1837a6436e4d6506c95", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/AxialBeamElement.jl", "max_forks_repo_name": "pedrosecchi67/SymFinel.jl", "max_forks_repo_head_hexsha": "24cc4110f48af1d33e1ba1837a6436e4d6506c95", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-02T15:56:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-02T15:56:40.000Z", "avg_line_length": 22.8076923077, "max_line_length": 121, "alphanum_fraction": 0.6138279933, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7977593790069342}}
{"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\n\n\"This code solves Laplace's equation with Dirichlet boundary conditions using a\nfinite difference method.\"\n\nm = 100 # number of points\nx = LinRange(-1,1,m+2)\nxint = x[2:end-1]\n\nf(x) = 5*(Float64((x > -.5) && (x <= 0.0)) - Float64((x < .5) && (x >= 0.0)))\nα,β = 1.0,pi\n\nh = x[2]-x[1]\nA = (1/h^2) * spdiagm(0=>2*ones(m),-1=>-ones(m-1),1=>-ones(m-1))\nb = f.(xint)\nb[1] += α/h^2\nb[m] += β/h^2\n\n# solve Au = F\nuu = A\\b\nplot(xint,uu,linewidth=2,label=\"Solution\")\nplot!(x,uexact.(x),linestyle=:dash)\n# plot!(x,.1*f.(x),linecolor=:red,ls=:dash,label=\"f(x)\")\n# plot!(leg=:topleft)\n\n# uu - uexact.(xint)\n", "meta": {"hexsha": "f62d90c3a125bdbeb447a79d1859650d8e731a5b", "size": 646, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week1/fd_laplace.jl", "max_stars_repo_name": "jlchan/caam452_s21", "max_stars_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:38:43.000Z", "max_issues_repo_path": "week1/fd_laplace.jl", "max_issues_repo_name": "jlchan/caam452_s21", "max_issues_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week1/fd_laplace.jl", "max_forks_repo_name": "jlchan/caam452_s21", "max_forks_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.275862069, "max_line_length": 79, "alphanum_fraction": 0.6037151703, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957277806109987, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7977231443403279}}
{"text": "# Headcount.jl\n\n###### headcount #####\n\"\"\"\n    headcount(v, z)\n\nCompute the Headcount Ratio of a vector `v` at a specified poverty threshold `z`.\n\n# Examples\n```julia\njulia> using Inequality\njulia> headcount([8, 5, 1, 3, 5, 6, 7, 6, 3], 4)\n0.3333333333333333\n```\n\"\"\"\nheadcount(v::AbstractVector{<:Real}, z::Real)::Float64 = length(v[v .< z]) / length(v)\n\n\n###### weighted headcount #####\n\"\"\"\n    headcount(v, w, z)\n\nCompute the Headcount Ratio of a vector `v` at a specified poverty threshold `z`, \nusing weights given by a weight vector `w`.\n\nWeights must not be negative, missing or NaN. The weights and data vectors must have the same length.\n\n# Examples\n```julia\njulia> using Inequality\njulia> headcount([8, 5, 1, 3, 5, 6, 7, 6, 3], [0.1,0.5,0.3,0.8,0.1,0.5,0.3,0.8,0.2], 4)\n0.36111111111111116\n```\n\"\"\"\nfunction headcount(v::AbstractVector{<:Real}, w::AbstractVector{<:Real}, z::Real)::Float64\n    \n    checks_weights(v, w)\n\n    return sum(w[v .< z]) / sum(w)\nend\n\n\nfunction headcount(v::AbstractVector{<:Real}, w::AbstractWeights, z::Real)::Float64\n    \n    checks_weights(v, w)\n\n    return sum(w[v .< z]) / w.sum\n\nend\n\n\nwheadcount(v::AbstractVector{<:Real}, w::AbstractVector{<:Real}, z::Real)::Float64 = headcount(v, w, z)\n\nwheadcount(v::AbstractVector{<:Real}, w::AbstractWeights, z::Real)::Float64 = headcount(v, w, z)", "meta": {"hexsha": "6d218c84319c71d1c2cb8000eca14ca488a7ef94", "size": 1327, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Headcount.jl", "max_stars_repo_name": "JosepER/Inequality.jl", "max_stars_repo_head_hexsha": "fd1bb964856dc37eb2648f3825123de9d8181578", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-03-12T13:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T18:45:45.000Z", "max_issues_repo_path": "src/Headcount.jl", "max_issues_repo_name": "JosepER/Inequality.jl", "max_issues_repo_head_hexsha": "fd1bb964856dc37eb2648f3825123de9d8181578", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Headcount.jl", "max_forks_repo_name": "JosepER/Inequality.jl", "max_forks_repo_head_hexsha": "fd1bb964856dc37eb2648f3825123de9d8181578", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5740740741, "max_line_length": 103, "alphanum_fraction": 0.6518462698, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730775, "lm_q2_score": 0.8872045892435128, "lm_q1q2_score": 0.7977046145990746}}
{"text": "function vandermonde_1d(N, r)\n    V = zeros(length(r), N+1)\n    for j in 1:N+1\n        @. V[:, j] = jacobi(r, 0, 0, j-1)\n    end\n    return V\nend\n\n\" Initialize the gradient of the modal basis (i) at (r) at order N. \"\nfunction ∂vandermonde_1d(N, r)\n    DVr = zeros(length(r), N+1)\n    for i in 0:N\n        @. DVr[:, i+1] = ∂jacobi(r, 0, 0, i)\n    end\n    return DVr\nend\n\n\" Initialize the (r) differentiation matrices on the interval, evaluated at (r) at order N. \"\nfunction Dmatrix1D(N, r, V)\n    Vr = ∂vandermonde_1d(N, r)\n    Dr = Vr / V\n    return Dr\nend\n", "meta": {"hexsha": "fccfce043ca67a022a0d19ac5550f5fa02bb10a2", "size": 557, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vandermonde.jl", "max_stars_repo_name": "ali-ramadhan/DiscontinuousGherkins.jl", "max_stars_repo_head_hexsha": "8cef921b3b6491d41134f3b8eb6b1568f408a25b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-29T22:59:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-29T22:59:28.000Z", "max_issues_repo_path": "src/vandermonde.jl", "max_issues_repo_name": "ali-ramadhan/nodal-discontinuous-galerkin-julia", "max_issues_repo_head_hexsha": "8cef921b3b6491d41134f3b8eb6b1568f408a25b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-02-13T14:39:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-20T13:14:13.000Z", "max_forks_repo_path": "src/vandermonde.jl", "max_forks_repo_name": "ali-ramadhan/nodal-discontinuous-galerkin-julia", "max_forks_repo_head_hexsha": "8cef921b3b6491d41134f3b8eb6b1568f408a25b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2083333333, "max_line_length": 93, "alphanum_fraction": 0.5834829443, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620619801095, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7976995593915005}}
{"text": "\"\"\"\n    TF(r, Z)\n\nApproximate solution of the [Thomas-Fermi equation](https://en.wikipedia.org/wiki/Thomas-Fermi_model) \nfor neutral atom with nuclear charge `Z`. Returns density at the distance `r`.\n\nSee Moliere, G. (1947). Theorie der streuung schneller geladener teilchen i. einzelstreuung am abgeschirmten coulomb-feld.\nZeitschrift für Naturforschung A, 2(3), 133-145.\n\n## Example\nFor a density function ``\\\\rho(r)`` of ``N`` particles the following equation holds.\n```math\nN = 4\\\\pi\\\\int dr \\\\rho(r)r^2\n``` \nOn the grid ``r_i = \\\\exp(x_i)`` it is\n```math \nN = 4\\\\pi\\\\int dx \\\\rho(r(x))r^3\n```\n```jldoctest\njulia> x = -30:0.1:20\n-30.0:0.1:20.0\n\njulia> r, n, dx = exp.(x), length(x), step(x);\n\njulia> isapprox(4π * dx * sum(TF.(r, 18) .* r .^3), 18, atol=1e-10)\ntrue\n```\n\"\"\"\nfunction TF(r, Z)\n  b = 1/2*(3π/4)^(2/3)*Z^(-1/3)\n  x = r/b\n\n  B₁, B₂, B₃ = 0.1, 0.55, 0.35\n  β₁, β₂, β₃ = 6.0, 1.20, 0.30\n\n  Z/(4π*b^3*x)*(B₁*β₁^2*exp(-β₁*x) + B₂*β₂^2*exp(-β₂*x) + B₃*β₃^2*exp(-β₃*x))\nend\n", "meta": {"hexsha": "b96f0dd93830eb3928f0b15713d2a715294e4d6e", "size": 984, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TF.jl", "max_stars_repo_name": "malykhin-sergei/AtomEnergyLevels.jl", "max_stars_repo_head_hexsha": "1476496969dee5fe38c32546b2aa35673bd8cc7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TF.jl", "max_issues_repo_name": "malykhin-sergei/AtomEnergyLevels.jl", "max_issues_repo_head_hexsha": "1476496969dee5fe38c32546b2aa35673bd8cc7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TF.jl", "max_forks_repo_name": "malykhin-sergei/AtomEnergyLevels.jl", "max_forks_repo_head_hexsha": "1476496969dee5fe38c32546b2aa35673bd8cc7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-26T17:45:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-26T17:45:38.000Z", "avg_line_length": 25.8947368421, "max_line_length": 122, "alphanum_fraction": 0.612804878, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620573763839, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7976995535580025}}
{"text": "\"\"\"\n    combinationrank(xs...)\n\nReturns the index of the combination `xs` in the combinatorial number system. The elements\nof `xs` all have to be unique, greater than zero and sorted in ascending order.\n\"\"\"\nfunction combinationrank(xs...)\n    @assert length(unique(xs)) == length(xs)\n    @assert sort([xs...]) == [xs...]\n    @assert all(xs .> 0)\n    k = length(xs)\n    1 + sum(binomial.(xs .- 1, 1:k))\nend\n\n\"\"\"\n    combinationunrank(k, i)\n\nReturns the `i`-th `k`-element combination in the combinatorial number system.\n\"\"\"\nfunction combinationunrank(k, idx)\n    @assert k > 0\n    @assert idx > 0\n    v = zeros(Int, k)\n    for i = k:-1:1\n        ck = _max_ck(i, idx - 1)\n        v[i] = ck + 1\n        idx -= binomial(ck, i)\n    end\n    tuple(v...)\nend\n\nfunction _max_ck(k, idx)\n    ck = 0\n    while true\n        binomial(ck + 1, k) > idx && return ck\n        ck += 1\n    end\n    error(\"Unreachable reached.\")\nend\n\n\"\"\"\n    findcombinationdiff(c1::NTuple{N,Int}, c2::NTuple{N,Int}) -> (idx1, idx2) or nothing\n\nIf the two ordered combinations of the same length have all elements except one in common,\nreturn a pair of indices of those elements. Otherwise, return `nothing`.\n\"\"\"\nfunction findcombinationdiff(c1::NTuple{N,Int}, c2::NTuple{N,Int}) where N\n    idx1::Union{Nothing,Int}, idx2::Union{Nothing,Int} = nothing, nothing\n    i = 1\n    while i < N\n        i1 = isnothing(idx1) ? i : i + 1\n        i2 = isnothing(idx2) ? i : i + 1\n        if c1[i1] == c2[i2]\n            i += 1\n        elseif (c1[i1] < c2[i2]) && isnothing(idx1)\n            idx1 = i1\n        elseif (c1[i1] > c2[i2]) && isnothing(idx2)\n            idx2 = i2\n        else\n            return nothing\n        end\n    end\n    isnothing(idx1) && (idx1 = N)\n    isnothing(idx2) && (idx2 = N)\n    c1[idx1] == c2[idx2] ? nothing : (idx1, idx2)\nend\n", "meta": {"hexsha": "651acb55ddbf26dbefb922670c4815b53ff6161a", "size": 1809, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/combinatorics.jl", "max_stars_repo_name": "mortenpi/Angular.jl", "max_stars_repo_head_hexsha": "5ea9efb019c53eaed4c6486f5a36d8c17b298609", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/combinatorics.jl", "max_issues_repo_name": "mortenpi/Angular.jl", "max_issues_repo_head_hexsha": "5ea9efb019c53eaed4c6486f5a36d8c17b298609", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/combinatorics.jl", "max_forks_repo_name": "mortenpi/Angular.jl", "max_forks_repo_head_hexsha": "5ea9efb019c53eaed4c6486f5a36d8c17b298609", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 90, "alphanum_fraction": 0.5793255943, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.7976689790843856}}
{"text": "export cycle_detection_floyd, cycle_detection_brent\n\n# https://en.wikipedia.org/wiki/Cycle_detection#Algorithms\n\ncycle_detection_floyd(f, x0) = begin\n    # Main phase of algorithm: finding a repetition x_i = x_2i.\n    # The hare moves twice as quickly as the tortoise and\n    # the distance between them increases by 1 at each step.\n    # Eventually they will both be inside the cycle and then,\n    # at some point, the distance between them will be\n    # divisible by the period λ.\n    tortoise = f(x0) # f(x0) is the element/node next to x0.\n    hare = (f ∘ f)(x0)\n    while tortoise ≠ hare\n        tortoise = f(tortoise)\n        hare = (f ∘ f)(hare)\n    end\n\n    # At this point the tortoise position, ν, which is also equal\n    # to the distance between hare and tortoise, is divisible by\n    # the period λ. So hare moving in circle one step at a time, \n    # and tortoise (reset to x0) moving towards the circle, will \n    # intersect at the beginning of the circle. Because the \n    # distance between them is constant at 2ν, a multiple of λ,\n    # they will agree as soon as the tortoise reaches index μ.\n\n    # Find the position μ of first repetition.    \n    μ = 0\n    tortoise = x0\n    while tortoise ≠ hare\n        tortoise = f(tortoise)\n        hare = f(hare)   # Hare and tortoise move at same speed\n        μ += 1\n    end\n\n    # Find the length of the shortest cycle starting from x_μ\n    # The hare moves one step at a time while tortoise is still.\n    # λ is incremented until λ is found.\n    λ = 1\n    hare = f(tortoise)\n    while tortoise ≠ hare\n        hare = f(hare)\n        λ += 1\n    end\n\n    λ, μ\nend\n\ncycle_detection_brent(f, x0) = begin\n    # main phase: search successive powers of two\n    power = λ = 1\n    tortoise = x0\n    hare = f(x0)  # f(x0) is the element/node next to x0.\n    while tortoise ≠ hare\n        if power == λ  # time to start a new power of two?\n            tortoise = hare\n            power *= 2\n            λ = 0\n        end\n        hare = f(hare)\n        λ += 1\n    end\n\n    # Find the position of the first repetition of length λ\n    μ = 0\n    tortoise = hare = x0\n    for i in 0:λ-1\n        hare = f(hare)\n    end\n    # The distance between the hare and tortoise is now λ.\n\n    # Next, the hare and tortoise move at same speed until they agree\n    while tortoise ≠ hare\n        tortoise = f(tortoise)\n        hare = f(hare)\n        μ += 1\n    end\n\n    λ, μ\nend\n", "meta": {"hexsha": "e1f78cc8eb25a469328fc4832b7756e65925b97b", "size": 2412, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Algorithm/cycledetection.jl", "max_stars_repo_name": "Samayel/Brainstorm.jl", "max_stars_repo_head_hexsha": "9d83bb0a104973e498ba4ca84b0a27ede6c053ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-12-22T17:56:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T21:13:36.000Z", "max_issues_repo_path": "src/Algorithm/cycledetection.jl", "max_issues_repo_name": "Samayel/Brainstorm.jl", "max_issues_repo_head_hexsha": "9d83bb0a104973e498ba4ca84b0a27ede6c053ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Algorithm/cycledetection.jl", "max_forks_repo_name": "Samayel/Brainstorm.jl", "max_forks_repo_head_hexsha": "9d83bb0a104973e498ba4ca84b0a27ede6c053ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7777777778, "max_line_length": 69, "alphanum_fraction": 0.6202321725, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.7976689772282812}}
{"text": "# ---\n# title: 70. Climbing Stairs\n# id: problem70\n# author: zhwang\n# date: 2022-01-16\n# difficulty: Easy\n# categories: Dynamic Programming\n# link: <https://leetcode.com/problems/climbing-stairs/description/>\n# hidden: true\n# ---\n# \n# You are climbing a staircase. It takes `n` steps to reach the top.\n# \n# Each time you can either climb `1` or `2` steps. In how many distinct ways can\n# you climb to the top?\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: n = 2\n#     Output: 2\n#     Explanation: There are two ways to climb to the top.\n#     1. 1 step + 1 step\n#     2. 2 steps\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: n = 3\n#     Output: 3\n#     Explanation: There are three ways to climb to the top.\n#     1. 1 step + 1 step + 1 step\n#     2. 1 step + 2 steps\n#     3. 2 steps + 1 step\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= n <= 45`\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction climbing_stairs(n::Int)::Int\n    n == 1 && return 1\n    a, b = 1, 2\n    for _ in 3:n\n        a, b = b, a + b\n    end\n    return b\nend\n\n## @lc code=end\n", "meta": {"hexsha": "51f6265cb75499a8714c800b631500cdfe306a4d", "size": 1074, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/70.climbing-stairs.jl", "max_stars_repo_name": "RexWzh/LeetCode.jl", "max_stars_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/70.climbing-stairs.jl", "max_issues_repo_name": "RexWzh/LeetCode.jl", "max_issues_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/70.climbing-stairs.jl", "max_forks_repo_name": "RexWzh/LeetCode.jl", "max_forks_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3225806452, "max_line_length": 80, "alphanum_fraction": 0.5474860335, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.7976689735160724}}
{"text": "# Simulate a Poisson point process on a disk\n# Author: H. Paul Keeler, 2019.\n# Website: hpaulkeeler.com\n# Repository: github.com/hpaulkeeler/posts\n# For more details, see the post:\n# hpaulkeeler.com/testing-the-julia-language-with-point-process-simulations/\n\n#Note: Need the .+ for adding a scalar to an array\n#Also need . for sqrt, exp, cos, sin etc and assinging scalars to arrays\n#Best to use vectors instead of 1-D matrices eg x=rand(n),  NOT x=rand(n,1).\n\nusing Distributions #for random simulations\nusing Plots #for plotting\n\n#Simulation window parameters\nr=1; #radius of disk\nxx0=0; yy0=0; #centre of disk\nareaTotal=pi*r^2; #area of disk\n\n#Point process parameters\nlambda=100; #intensity (ie mean density) of the Poisson process\n\n#Simulate Poisson point process\nnumbPoints=rand(Poisson(areaTotal*lambda)); #Poisson number of points\ntheta=2*pi*(rand(numbPoints));#angular coordinates  of Poisson points\nrho=r*sqrt.(rand(numbPoints));#radial coordinates of Poisson points\n\n#Convert polar to Cartesian coordinates\nxx=rho.*cos.(theta);\nyy=rho.*sin.(theta);\n\n#Shift centre of disk to (xx0,yy0)\nxx=xx.+xx0;\nyy=yy.+yy0;\n\nplot1=scatter(xx,yy,xlabel =\"x\",ylabel =\"y\", leg=false);\ndisplay(plot1);\n", "meta": {"hexsha": "0765d028bc3faa287b621baf25a4c448fb09b7a2", "size": 1194, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "TestingJulia/PoissonDisk.jl", "max_stars_repo_name": "hpkeeler/posts", "max_stars_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2020-05-14T12:14:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:22:09.000Z", "max_issues_repo_path": "TestingJulia/PoissonDisk.jl", "max_issues_repo_name": "hpkeeler/posts", "max_issues_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TestingJulia/PoissonDisk.jl", "max_forks_repo_name": "hpkeeler/posts", "max_forks_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-10-26T01:22:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T17:33:40.000Z", "avg_line_length": 31.4210526316, "max_line_length": 76, "alphanum_fraction": 0.7529313233, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551556203815, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7976571429003843}}
{"text": "## Maximum entropy degree distribution of a network with S species and L links\n\nfunction p_k(k::Int64, S::Int64, L::Int64)\n    # k: degree of a species\n    # S: number of species in the food web\n    # L: number of links in the food web\n\n    # return probability of degree k from MaxEnt distribution\n    # p_k = c * r^k\n\n    # constraint of mean\n    mean_degree = (2 * L) / S\n\n    # maximum entropy distribution\n    c = 1 / (mean_degree - 1)\n    r = (mean_degree - 1) / mean_degree\n\n    return c * r ^ k\nend\n\n\n\nfunction maxent_dd(S::Int64, L::Int64)\n    # S: number of species\n    # L: number of links\n\n    # return degree distribution with maximum entropy\n    # i.e. probability for each k between 1 and S\n    degree_dist = zeros(S)\n    for k in 1:S\n        degree_dist[k] = p_k(k, S, L)\n    end\n\n    return degree_dist\nend\n", "meta": {"hexsha": "433120f8fd255171cee78187f97a2d5a7aa4c812", "size": 824, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/maxent_dd.jl", "max_stars_repo_name": "FrancisBanville/Trophic-METE", "max_stars_repo_head_hexsha": "3d517beb42946789c350fa8cf3e579637cb0a792", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/maxent_dd.jl", "max_issues_repo_name": "FrancisBanville/Trophic-METE", "max_issues_repo_head_hexsha": "3d517beb42946789c350fa8cf3e579637cb0a792", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/maxent_dd.jl", "max_forks_repo_name": "FrancisBanville/Trophic-METE", "max_forks_repo_head_hexsha": "3d517beb42946789c350fa8cf3e579637cb0a792", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8888888889, "max_line_length": 78, "alphanum_fraction": 0.6347087379, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.972830769252026, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.797617468962664}}
{"text": "function naiveDFT(hk::Array{T}) where T\n    N = length(hk);\n    Wnk = Array{Complex{T}}(undef, N, N)\n\n    prefactor = -2 * π * im / N\n\n    for n = 0:(N - 1), k = 0:(N - 1)\n        Wnk[k + 1, n + 1] = exp(prefactor * n * k)\n    end\n\n    return Wnk * hk\nend\n\nfunction naiveDFTIterative(hk::Array{T}) where T\n    N = length(hk);\n    Hk = zeros(Complex{T}, N)\n\n    prefactor = -2 * π * im / N\n\n    @inbounds @simd for k = 1:N\n        s = zero(Complex{T})\n        km1 = k - 1\n        for j = 1:N\n            s += exp(prefactor * (j - 1) * km1) * hk[j]\n        end\n        Hk[k] = s\n    end\n\n    return Hk\nend\n", "meta": {"hexsha": "f9cb47ea792941b2bb58cdacca326d217e0e69d5", "size": 604, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Excercise_01/A2/naiveDFT.jl", "max_stars_repo_name": "JulienKluge/ComputationalPhotonics", "max_stars_repo_head_hexsha": "78bfdccc49dca5b19e524814c0ca3fcff7be6765", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Excercise_01/A2/naiveDFT.jl", "max_issues_repo_name": "JulienKluge/ComputationalPhotonics", "max_issues_repo_head_hexsha": "78bfdccc49dca5b19e524814c0ca3fcff7be6765", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Excercise_01/A2/naiveDFT.jl", "max_forks_repo_name": "JulienKluge/ComputationalPhotonics", "max_forks_repo_head_hexsha": "78bfdccc49dca5b19e524814c0ca3fcff7be6765", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4838709677, "max_line_length": 55, "alphanum_fraction": 0.4751655629, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474233166328, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.797592209829835}}
{"text": "function log_oneplusexp(E::Float64)\n    return (E < 50) ? log(1+exp(E)) : E\nend\n\nfunction xlogy(x::Float64, y::Float64)\n    if x == 0.0\n        return 0.0\n    else\n        return x*log(y)\n    end\nend\n\n\nfunction log_binom(n::Float64, k::Float64)\n    @assert n >= k\n    if (n == 0) || (k == 0)\n       return 0\n    end\n    return n*log(n)-k*log(k)-(n-k)*log(n-k)\nend\n", "meta": {"hexsha": "2d275476935844c22960859cbe82e149d6c9992b", "size": 364, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/log_approx.jl", "max_stars_repo_name": "matteodeleonardis/UAF2.jl", "max_stars_repo_head_hexsha": "83af0afd03a6e9bacdc809c7fcbcdd2760bbb98d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/log_approx.jl", "max_issues_repo_name": "matteodeleonardis/UAF2.jl", "max_issues_repo_head_hexsha": "83af0afd03a6e9bacdc809c7fcbcdd2760bbb98d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/log_approx.jl", "max_forks_repo_name": "matteodeleonardis/UAF2.jl", "max_forks_repo_head_hexsha": "83af0afd03a6e9bacdc809c7fcbcdd2760bbb98d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3333333333, "max_line_length": 43, "alphanum_fraction": 0.5412087912, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474233166329, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7975922059192624}}
{"text": "# fibonacci seq - LaTeX\n#JL Plots\n\n\nPkg.add(\"LaTeXStrings\")\nPkg.add(\"Measures\")\nusing LaTeXStrings, Measures\ngr(bg = :white)\n\nfib = zeros(12);\nfor i = 1:12\n    fib[i] = (((1+sqrt(5))/2)^i - ((1-sqrt(5))/2)^i)/sqrt(5);\nend\n\nPlots.plot(fib,\n    marker=:circle,\n    linewidth= 2,\n    xlabel=L\"n\",\n    ylabel=L\"F_n\",\n    annotation=(5, 100, L\"F_n = \\frac{1}{\\sqrt{5}} \\left[\\left( \\frac{1+\\sqrt{5}}{2} \\right)^n - \\left( \\frac{1-\\sqrt{5}}{2} \\right)^n \\right]\"))\n", "meta": {"hexsha": "96eda6e5f40eb773241cbab374a0683e19464a26", "size": 459, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lines/fibonacci.jl", "max_stars_repo_name": "Ellon-M/visualizations", "max_stars_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lines/fibonacci.jl", "max_issues_repo_name": "Ellon-M/visualizations", "max_issues_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lines/fibonacci.jl", "max_forks_repo_name": "Ellon-M/visualizations", "max_forks_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8571428571, "max_line_length": 145, "alphanum_fraction": 0.5795206972, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9546474155747541, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7975922033616228}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots, Measures\nend;\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.09\"\n\n# ╔═╡ 1aa41898-3afa-11eb-2f49-570853ce6435\nbegin\n\tN = 5*10^3\n\talpha = 0.05\n\tconfLevel = 1 - alpha\n\tz = quantile(Normal(),1-alpha/2) \nend;\n\n# ╔═╡ 7e997ce4-3b27-11eb-167a-f74a6dff6b1c\nfunction randCI(n,p)\n    sample = rand(n) .< p\n    pHat = sum(sample)/n \n    serr = sqrt(pHat*(1-pHat)/n)\n    (pHat - z*serr, pHat + z*serr) \nend\n\n# ╔═╡ 7e99af3e-3b27-11eb-2b94-051fc56f27cf\ncover(p,ci) = ci[1] <= p && p <= ci[2]\n\n# ╔═╡ 7e9a284c-3b27-11eb-37b2-6fcc5cbb3adb\nbegin\n\tpGrid = 0.1:0.01:0.9\n\tnGrid = 5:1:50\n\terrs = zeros(length(nGrid),length(pGrid))\n\n\tfor i in 1:length(nGrid)\n\t\tfor j in 1:length(pGrid)\n\t\t\tRandom.seed!(0)\n\t\t\tn, p = nGrid[i], pGrid[j]\n\t\t\tcoverageRatio = sum([cover(p,randCI(n,p)) for _ in 1:N])/N\n\t\t\terrs[i,j] = confLevel - coverageRatio\n\t\tend\n\tend\nend;\n\n# ╔═╡ 7ea98df0-3b27-11eb-292f-4d1335c99239\nbegin\n\tdefault(xlabel = \"p\", ylabel = \"n\", \n\t\txticks =([1:5:length(pGrid);], minimum(pGrid):0.05:maximum(pGrid)),\n\t\tyticks =([1:5:length(nGrid);], minimum(nGrid):5:maximum(nGrid)))\n\n\tp1 = heatmap(errs, c=cgrad([:white, :black]))\n\tp2 = heatmap(abs.(errs) .<= 0.04, legend = false, c=cgrad([:black, :white]))\n\tplot(p1,p2, size = (1000,400), margin = 5mm)\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.09\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═1aa41898-3afa-11eb-2f49-570853ce6435\n# ╠═7e997ce4-3b27-11eb-167a-f74a6dff6b1c\n# ╠═7e99af3e-3b27-11eb-2b94-051fc56f27cf\n# ╠═7e9a284c-3b27-11eb-37b2-6fcc5cbb3adb\n# ╠═7ea98df0-3b27-11eb-292f-4d1335c99239\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "5c72b3ba5981d0a417e922e92a6bcbd2771f5cc3", "size": 1981, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/06/listing6.09.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/06/listing6.09.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/06/listing6.09.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.3974358974, "max_line_length": 77, "alphanum_fraction": 0.6804644119, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8740772450055544, "lm_q1q2_score": 0.7975396812306024}}
{"text": "## spherical.jl : implementation of spherical covariance function\n\n## Spherical ##\nstruct Spherical{T} <: IsotropicCovarianceStructure{T}\n    λ::T\n    σ::T\n    p::T\n\n    function Spherical{T}(λ::T, σ::T, p::T) where T\n        λ > 0 || throw(DomainError(λ, \"correlation length λ of spherical covariance cannot be negative or zero\"))\n        σ > 0 || throw(DomainError(σ, \"marginal standard deviation σ of spherical covariance cannot be negative or zero\"))\n        p >= 1 || throw(DomainError(p, \"in p-norm, p must be greater than or equal to 1\"))\n        isinf(p) && throw(DomainError(p, \"in p-norm, p cannot be infinity\"))\n\n        new{T}(λ, σ, p)\n    end\nend\n\n\"\"\"\n    Spherical(λ, [σ = 1], [p = 2])\n\nSpherical covariance structure with correlation length `λ`, (optional) marginal standard deviation `σ` and (optional) `p`-norm, defined as\n\n``C(x, y) = \\\\begin{cases} σ \\\\left(1 - \\\\displaystyle\\\\frac{3}{2}\\\\frac{ρ}{λ} + \\\\frac{1}{2}\\\\left(\\\\frac{ρ}{λ}\\\\right)^3\\\\right) & \\\\text{for }ρ≤λ\\\\\\\\0 & \\\\text{for }ρ>λ\\\\end{cases}``\n\nwith ``ρ = ||x - y||_p``.\n\n# Examples\n```jldoctest\njulia> Spherical(0.1)\nspherical (λ=0.1, σ=1.0, p=2.0)\n\njulia> Spherical(1.0, σ=2)\nspherical (λ=1.0, σ=2.0, p=2.0)\n\n```\nSee also: [`Exponential`](@ref), [`Linear`](@ref), [`Whittle`](@ref), [`Gaussian`](@ref), [`SquaredExponential`](@ref), [`Matern`](@ref)\n\"\"\"\nSpherical(λ::Real; σ::Real=1.0, p::Real=2) = Spherical{promote_type(typeof(λ),typeof(σ),typeof(p))}(promote(λ, σ, p)...)\n\n# evaluate spherical covariance\napply(s::Spherical, x::Real) = max(zero(x), 1 - 3/2 * x/s.λ + 1/2 * (x/s.λ)^3)\n\n# short name\nshortname(::Spherical) = \"spherical\"\n", "meta": {"hexsha": "49b16b22d4bbb6db6369ae908d7748d096e90b30", "size": 1623, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/covariance_functions/spherical.jl", "max_stars_repo_name": "Philippe1123/GaussianRandomFields.jl", "max_stars_repo_head_hexsha": "86ae443ae46d27a45d4afcdceb453c48cbfd9807", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2018-02-01T10:43:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:29:00.000Z", "max_issues_repo_path": "src/covariance_functions/spherical.jl", "max_issues_repo_name": "Philippe1123/GaussianRandomFields.jl", "max_issues_repo_head_hexsha": "86ae443ae46d27a45d4afcdceb453c48cbfd9807", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2018-01-17T18:32:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T07:14:13.000Z", "max_forks_repo_path": "src/covariance_functions/spherical.jl", "max_forks_repo_name": "Philippe1123/GaussianRandomFields.jl", "max_forks_repo_head_hexsha": "86ae443ae46d27a45d4afcdceb453c48cbfd9807", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-08-01T17:13:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T11:19:26.000Z", "avg_line_length": 35.2826086957, "max_line_length": 185, "alphanum_fraction": 0.6192236599, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8740772335247531, "lm_q1q2_score": 0.7975396749176326}}
{"text": "\n\n\"\"\" \n    VaR(states,prob,alpha::Float32)\n\nimplements the Value-at-Risk at level ``\\\\alpha`` defined by\n```math\nVaR_\\\\alpha (Y) = \\\\arg \\\\min_x \\\\left( x\\\\in \\\\mathbb{R} : F_Y(x) \\\\geq \\\\alpha \\\\right),\n```\nfor the random variable ``Y`` defined by `states` and `prob`.\n\"\"\"\nfunction VaR(x::Vector{Float64}, f::Vector{Float64}, α::Float32)\n    ind = sortperm(x[1:length(x)])\n    x = x[ind]; f = f[ind];\n    i = findfirst(p -> p≥α, cumsum(f))\n    if i === nothing\n        return x[end]\n    else\n        return x[i]\n    end\nend\n\n\n\"\"\" \n    CTE(states,prob,alpha::Float32)\n\nimplements the Conditional Value-at-Risk at level ``\\\\alpha`` defined by\n```math\nCTE_\\\\alpha (Y) = VaR_\\\\alpha(Y) + \\\\frac{1}{1-\\\\alpha} \\\\mathbb{E} \\\\left( Y- VaR_\\\\alpha (Y) \\\\right)_+ ,\n```\nfor the random variable ``Y`` defined by `states` and `prob`.\n\"\"\"\nfunction CTE(x::Vector{Float64}, f::Vector{Float64}, α::Float32)\n    x = -x; α = 1-α;\n    x_α = VaR(x, f, α)\n    if iszero(α)\n        return -x_α\n    else\n        tail = x .≤ x_α\n        result = (sum(x[tail] .* f[tail]) - (sum(f[tail]) - α) * x_α) / α\n        return -result\n    end\nend\n\n\n\n\n\"\"\"\n    EVaR2(states,prob,beta)\n\nSolves the optimization problem associated with the primal formulation of the Entropic Value-at-Risk:\n\n```math\nEVaR_\\\\alpha(Y) = \\\\min_{x >0} \\\\frac{1}{x} \\\\left( \\\\beta +  \\\\log\\\\mathbb{E} e^{xY} \\\\right),\n```\nwhere ``Y`` is the discrete random variable defined by `states` and `prob`.\nHere the optimization is done via the goldenSearch optimization routine implemented as part of this package. \n\"\"\"\nfunction EVaR2(states::Vector{Float64}, prob::Vector{Float64},beta::Float32)\n\tif sum(prob) == 0\n\t\tprob = ones(length(states))./ length(states)\n\tend\n\tdualZ = zeros(length(states))\n\tesssup = maximum(states[vec(prob.>0.0)]) \n\tvarm = dot(prob, (states .- dot(prob,states)).^2)\n\tif beta == 0.0\n\t\tFvalue = dot(prob, states)\n\t\ttOpt = 0.0\n\t\tdualZ = exp.(tOpt .*states)\n\telse\n\t\tif varm >0.0\n\t\t\ttOpt = sqrt.(2 *beta/varm)\n\t\t\tfunction objective1(t)\n\t\t\t\tt=max(t,0.0)\n\t\t\t\tw = states./t\n\t\t\t\toffset = maximum(w)\n    \t\t\twe = exp.(w .- offset)\n    \t\t\ts = dot(prob, we)\n    \t\t\tw = log(s) + offset\n\t\t\t\ttmp = t*beta + t*w\n\t\t\t\t#tmp = t*beta + t*log(dot(prob,exp.(states./t)))\n\t\t\t\treturn(tmp)\n\t\t\tend\n\t\t\tout = goldenSearch(objective1,tOpt)\n\t\t\ttOpt = out[1]\n\t\t\tFvalue = out[2]\n\t\telse\n\t\t\ttOpt = 0.0\n\t\t\tFvalue = 0.0\n\t\t\tdualZ = esssup\n\t\tend\n\t\t#if Fvalue < esssup\n\t\t\tdualZ = exp.(tOpt .*states)\n\t\t#else\n\t\t#\tFvalue = esssup\n\t\t#\tdualZ[states .>= esssup] .= 1\n\t\t#end\n\t\tdualZ = dualZ / dot(prob,dualZ)\n\tend\n\treturn(Fvalue,tOpt,dualZ) # for numerical stability\nend\n\n\n\"\"\"\n    EVaR(states,prob,beta::Float32)\n\nSolves the optimization problem associated with the primal formulation of the Entropic Value-at-Risk:\n\n```math\nEVaR_\\\\alpha(Y) = \\\\min_{x >0} \\\\frac{1}{x} \\\\left( \\\\beta +  \\\\log\\\\mathbb{E} e^{xY} \\\\right),\n```\nwhere ``Y`` is the discrete random variable defined by `states` and `prob`. Here, the optimization is done using JuMP and Ipopt.  \n\"\"\"\nfunction EVaR(states::Vector{Float64}, prob::Vector{Float64},beta::Float32)\n\tif sum(prob) == 0\n\t\tprob = ones(length(states))./ length(states)\n\tend\n\tdualZ = zeros(length(states))\n\tesssup = maximum(states[prob.>0.0]) #error\n\tvar = dot(prob, (states .- dot(prob,states)).^2 )\n\tif beta == 0.0\n\t\tEVaR = dot(prob, states)\n\t\ttOpt = 0\n\t\tdualZ = exp.(tOpt .*states)\n\telse\n\t\tif var >0\n\t\t\ttOpt = sqrt.(2 *beta/var)\n\t\t\tEV = Model(optimizer_with_attributes(Ipopt.Optimizer, \"print_level\" =>0))\n\t\t\tfunction objective1(t)\n\t\t\t\treturn( (beta.+ log(dot(prob,exp.(t.*states))))/t)\n\t\t\tend\n\t\t\tregister(EV, :objective1, 1, objective1, autodiff=true)\n\n\t    \t@variable(EV,t,start = tOpt)\n\t\t\t@constraint(EV, t .>=0)\n\t    \t@NLobjective(EV, Min, objective1(t) )\n\n\t\t\tJuMP.optimize!(EV)\n\t\t\tEVaR = JuMP.objective_value(EV)\n\t    \ttOpt = JuMP.value(t)\n\t\telse\n\t\t\ttOpt = 0\n\t\t\tEVaR = 0\n\t\t\tdualZ = esssup\n\t\tend\n\t\tif EVaR < esssup\n\t\t\tdualZ = exp.(tOpt .*states)\n\t\telse\n\t\t\tEVaR = esssup\n\t\t\t#dualZ[states==esssup] .= 1\n\t\tend\n\t\t#dualZ = dualZ / dot(prob,dualZ)\n\tend\n\treturn(EVaR,tOpt,dualZ)\nend\n\n\n\n\"\"\"\n    AVaR(states,prob,alpha::Float32)\n\nSolves the optimization problem associated with the primal formulation of the Average Value-at-Risk:\n\n```math\nAVaR_\\\\alpha(Y) = \\\\min_{x\\\\in \\\\mathbb{R}} x + \\\\frac{1}{1-\\\\alpha} \\\\mathbb{E} \\\\left( Y - x \\\\right)_+,\n```\nwhere ``Y`` is the discrete random variable defined by `states` and `prob`.\n\"\"\"\nfunction AVaR(states::Vector{Float64},prob::Vector{Float64}, alpha::Float32)\n    var2 = dot(prob, (states .- dot(prob,states)).^2);\n     #First trivial case\n    if alpha == 0.0\n        return(dot(prob, states))\n  #Now set up optimization problem using goldenSearch\n    else\n       tOpt = sqrt.(2 *alpha/var2)\n       EV = Model(optimizer_with_attributes(Ipopt.Optimizer, \"print_level\" =>0))\n\t\tfunction objective1(t)\n\t\t\treturn( t + 1/(1-alpha) * dot(prob, max.(states .- t,0)) )\n\t\tend\n\t\tregister(EV, :objective1, 1, objective1, autodiff=true)\n\t    @variable(EV,t,start = tOpt)\n\t\t@NLobjective(EV, Min, objective1(t) )\n\n\t\tJuMP.optimize!(EV)\n\t\tAVaR = JuMP.objective_value(EV)\n\t    tOpt = JuMP.value(t)\n    end\n    return(AVaR, tOpt)\nend\n", "meta": {"hexsha": "9bff51e664e2568d9791baeaeb4e34541724d591", "size": 5108, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/valueRisk.jl", "max_stars_repo_name": "rubsc/RiskMeasures.jl", "max_stars_repo_head_hexsha": "6b0dd90bdb8428edc901dea7ac2e347746e8ce47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-18T18:47:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T18:47:59.000Z", "max_issues_repo_path": "src/valueRisk.jl", "max_issues_repo_name": "rubsc/RiskMeasures.jl", "max_issues_repo_head_hexsha": "6b0dd90bdb8428edc901dea7ac2e347746e8ce47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/valueRisk.jl", "max_forks_repo_name": "rubsc/RiskMeasures.jl", "max_forks_repo_head_hexsha": "6b0dd90bdb8428edc901dea7ac2e347746e8ce47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7434554974, "max_line_length": 130, "alphanum_fraction": 0.6227486296, "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092412, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7975296684236708}}
{"text": "# The following reproduces the example introduced in Section 3.2.3 of Lütkepohl (2006)\n\nusing VectorAutoregressions\nusing CSV, DataFrames\nusing Dates\n\nexdir = pkgdir(VectorAutoregressions) * \"/examples\";\ndatadf = DataFrame(CSV.File(exdir * \"/lutkepohl_data.csv\"));\nfirst(datadf, 6)\n\n# Take the subset from 1960q1 to 1978q4, and use log-difference for each series\ndatadf = datadf[datadf.date.<Date(1979, 3, 1), :];\nY = DataFrame(\n    investment = diff(log.(datadf.invest)),\n    income = diff(log.(datadf.income)),\n    consumption = diff(log.(datadf.cons)),\n);\nfirst(Y, 6)\n\n# ## Calculate lag selection criteria\nls = LagSelection(Y, 8)\n# ## Estimate the VAR\nv = VAR(Y, ls.selection[\"AIC\"])\n# ## Check stability of the VAR\nsc = StabilityCheck(v)\n# ## Check for autocorrelation in the residuals\npt = PortmanteauTest(v, 12)\nbg1 = LMCorrTest(v, 4)\nbg2 = LMCorrTest(v, 4, smallsample = true)\n", "meta": {"hexsha": "d94e17077e4b26e7d9d49e9ec1d21be8ace7ab1e", "size": 885, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/lutkepohl_example.jl", "max_stars_repo_name": "stephenbnicar/VectorAutoregressions.jl", "max_stars_repo_head_hexsha": "f5575b39b589745ca9d1ac1dda0e8f7707349188", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-05-16T16:36:33.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-19T06:17:16.000Z", "max_issues_repo_path": "examples/lutkepohl_example.jl", "max_issues_repo_name": "stephenbnicar/VectorAutoregressions.jl", "max_issues_repo_head_hexsha": "f5575b39b589745ca9d1ac1dda0e8f7707349188", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-05-14T15:09:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-03T13:58:55.000Z", "max_forks_repo_path": "examples/lutkepohl_example.jl", "max_forks_repo_name": "stephenbnicar/VectorAutoregressions.jl", "max_forks_repo_head_hexsha": "f5575b39b589745ca9d1ac1dda0e8f7707349188", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-05-16T16:36:34.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-16T16:36:34.000Z", "avg_line_length": 29.5, "max_line_length": 86, "alphanum_fraction": 0.7141242938, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810481379379, "lm_q2_score": 0.8418256472515684, "lm_q1q2_score": 0.7975296640425888}}
{"text": "export ExtensionalSet, IntensionalSet, settuple, orderedpair, cardinality\n\n\nabstract type MathematicalSet <: AbstractExpression end\nistree(s::MathematicalSet) = false # TODO: refactor structure conditionals to make more sense\n\n\nstruct ExtensionalSet{T} <: MathematicalSet\n    elements::Set{T}\nend\nExtensionalSet(elements::Vector{T}) where {T} = ExtensionalSet(Set{T}(elements))\nExtensionalSet(elements::Tuple{Vararg{T}}) where {T} = ExtensionalSet(Set{T}([elements...]))\nelements(es::ExtensionalSet) = es.elements\nBase.length(es::ExtensionalSet) = length(elements(es))\nBase.isempty(es::ExtensionalSet) = Base.isempty(elements(es))\nBase.hash(es::ExtensionalSet, h::UInt) = hash(elements(es), h)\nBase.:(==)(es1::ExtensionalSet, es2::ExtensionalSet) = elements(es1) == elements(es2)\ncardinality(es::ExtensionalSet) = length(es)\n\n# expression methods\nvariables(es::ExtensionalSet) = length(es) > 0 ? reduce(∪, variables.(elements(es))) : Set{LogicalSymbol}()\noperations(es::ExtensionalSet) = length(es) > 0 ? reduce(∪, operations.(elements(es))) : Set{LogicalOperation}()\n\nfunction Base.show(io::IO, es::ExtensionalSet)\n    if isempty(es)\n        print(io, \"∅\")\n        return\n    end\n\n    print(io, \"{\")\n    i = 1\n    truncated_elements = truncate([elements(es)...], 5)\n    for el ∈ truncated_elements\n        print(io, el)\n        if i < cardinality(es)\n            print(io, \", \")\n        end\n        i += 1\n    end\n    if length(truncated_elements) < cardinality(es)\n        missed_elements = cardinality(es) - length(truncated_elements)\n        print(io, \"...$(missed_elements) more\")\n    end\n    print(io, \"}\")\nend\n\norderedpair(a, b) = ExtensionalSet([ExtensionalSet([a]), ExtensionalSet([a, b])])\nfunction settuple(a...)\n    a = [a...]\n    if length(a) == 0\n        return ∅\n    end\n    x = settuple(a[1:end-1]...)\n    ExtensionalSet([ExtensionalSet([x]), ExtensionalSet([x, a[end]])])\nend\n\n\nstruct IntensionalSet <: MathematicalSet\n    transform::AbstractExpression\n    rule::AbstractExpression\nend\nIntensionalSet(transform::AbstractExpression, rules::Vector{LogicalExpression}) = IntensionalSet(transform, reduce(∧, rules))\nIntensionalSet(transform::AbstractExpression, rules::Set{LogicalExpression}) = IntensionalSet(transform, [rules...])\nIntensionalSet(transform::AbstractExpression, rules::Tuple{Vararg{LogicalExpression}}) = IntensionalSet(transform, [rules...])\ntransform(is::IntensionalSet) = is.transform\nrule(is::IntensionalSet) = is.rule\n\n# expression methods\nvariables(is::IntensionalSet) = variables(rule(is))\noperations(is::IntensionalSet) = operations(rule(is))\n\nfunction Base.show(io::IO, is::IntensionalSet)\n    print(io, \"{\")\n    print(io, transform(is))\n    print(io, \" | \")\n    print(io, rule(is))\n    print(io, \"}\")\nend\n", "meta": {"hexsha": "ca7b7e099bcf0b5167c0bb4c25264b11bcd7ef5e", "size": 2745, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/set/set.jl", "max_stars_repo_name": "ctrekker/PropositionalLogic.jl", "max_stars_repo_head_hexsha": "bfa9c9865abdaebab3f18d3c70c44d945d8a732b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-12-14T18:44:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T06:51:57.000Z", "max_issues_repo_path": "src/set/set.jl", "max_issues_repo_name": "ctrekker/PropositionalLogic.jl", "max_issues_repo_head_hexsha": "bfa9c9865abdaebab3f18d3c70c44d945d8a732b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2021-12-14T07:19:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T21:28:04.000Z", "max_forks_repo_path": "src/set/set.jl", "max_forks_repo_name": "ctrekker/Deductive.jl", "max_forks_repo_head_hexsha": "bfa9c9865abdaebab3f18d3c70c44d945d8a732b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.746835443, "max_line_length": 126, "alphanum_fraction": 0.6928961749, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7974764104563873}}
{"text": "# This file includes investigates the 2D interpolation mean square error(MSE) with respect to inteprolation point number.\n\nusing FractalTools \nusing Makie \n\n# Construct interpolation data \nf(x, y) = x^2 + y^2 + 1\nvtx = [\n    BigFloat.([0.0, 0.0]), \n    BigFloat.([1.0, 0.0]), \n    BigFloat.([0.5, 1.0])\n    ]\nfreevar = 0.001\nnpts    = 50 : 5 : 150\nntpts   = 2 * npts[end]\n\n# Construct test data \ntpts = getdata(vtx, ntpts)\n\n# Compute errors \nmse = map(npts) do npt\n    @info npt \n    # Construct interpolation data \n    pts = getdata(f, vtx, npt)\n\n    # Construct interpolant \n    interp = interpolate(pts, Interp2D(freevar))\n\n    # Compute error \n    fvals = map(pnt -> f(pnt...), tpts)\n    ivals = map(pnt -> interp(pnt...), tpts)\n    sum((fvals - ivals).^2) / length(tpts)\nend \n\n# Plot mse \nfig = Figure() \nax = fig[1, 1] = Axis(fig, xlabel=\"Number of Points\", ylabel=\"MSE\", title=\"2D Interpolation MSE\") \nstem!(ax, npts, mse, color=:black)\nsave(joinpath(@__DIR__, \"interp2d_mse.png\"), fig)\ndisplay(fig)\n", "meta": {"hexsha": "f1ed79c36e8e3738188419af4a931052df91c5e8", "size": 1007, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiment_1/interpolation_mse_vs_numpoints/interp2d/interp2d.jl", "max_stars_repo_name": "zekeriyasari/FractalTools.jl", "max_stars_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-08T12:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T12:50:16.000Z", "max_issues_repo_path": "experiment_2/interpolation_mse_vs_numpoints/interp2d/interp2d.jl", "max_issues_repo_name": "zekeriyasari/FractalTools.jl", "max_issues_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-09-05T18:22:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T10:09:46.000Z", "max_forks_repo_path": "experiment_2/interpolation_mse_vs_numpoints/interp2d/interp2d.jl", "max_forks_repo_name": "zekeriyasari/FractalTools.jl", "max_forks_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5609756098, "max_line_length": 121, "alphanum_fraction": 0.6335650447, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7974764080535882}}
{"text": "\nusing JuMP, GLPK, LinearAlgebra, DataFrames\n\n\n# Define some input data about the test system\n# Maximum power output of generators\ng_max = [1000, 1000];\n# Minimum power output of generators\ng_min = [0, 300];\n# Incremental cost of generators \nc_g = [50, 100];\n# Fixed cost of generators\nc_g0 = [1000, 0]\n# Incremental cost of wind generators\nc_w = 50;\n# Total demand\nd = 1500;\n# Wind forecast\nw_f = 200;\n\n\n# In this cell we create function solve_ed, which solves the economic dispatch problem for a given set of input parameters.\nfunction solve_ed(g_max, g_min, c_g, c_w, d, w_f)\n    #Define the economic dispatch (ED) model\n    ed = Model(GLPK.Optimizer)\n    \n    # Define decision variables    \n    @variable(ed, 0 <= g[i = 1:2] <= g_max[i]) # power output of generators\n    @variable(ed, 0 <= w <= w_f) # wind power injection\n\n    # Define the objective function\n    @objective(ed, Min, dot(c_g, g) + c_w * w)\n\n    # Define the constraint on the maximum and minimum power output of each generator\n    @constraint(ed, [i = 1:2], g[i] <= g_max[i]) #maximum\n    @constraint(ed, [i = 1:2], g[i] >= g_min[i]) #minimum\n\n    # Define the constraint on the wind power injection\n    @constraint(ed, w <= w_f)\n\n    # Define the power balance constraint\n    @constraint(ed, sum(g) + w == d)\n\n    # Solve statement\n    optimize!(ed)\n    \n    # return the optimal value of the objective function and its minimizers\n    return value.(g), value(w), w_f - value(w), objective_value(ed)\nend\n\n# Solve the economic dispatch problem\n(g_opt, w_opt, ws_opt, obj) = solve_ed(g_max, g_min, c_g, c_w, d, w_f);\n\nprintln(\"\\n\")\nprintln(\"Dispatch of Generators: \", g_opt, \" MW\")\nprintln(\"Dispatch of Wind: \", w_opt, \" MW\")\nprintln(\"Wind spillage: \", w_f - w_opt, \" MW\") \nprintln(\"\\n\")\nprintln(\"Total cost: \", obj, \"\\$\")\n\n\nc_g_scale_df = DataFrame(Symbol(\"Dispatch of Generator 1(MW)\") => Float64[],\n               Symbol(\"Dispatch of Generator 2(MW)\") => Float64[],\n               Symbol(\"Dispatch of Wind(MW)\") => Float64[],\n               Symbol(\"Spillage of Wind(MW)\") => Float64[],\n               Symbol(\"Total cost(\\$)\") => Float64[])\nfor c_g1_scale = 0.5:0.1:3.0\n    c_g_scale = [c_g[1] * c_g1_scale, c_g[2]] # update the incremental cost of the first generator at every iteration\n    g_opt, w_opt, ws_opt, obj = solve_ed(g_max, g_min, c_g_scale, c_w, d, w_f) # solve the ed problem with the updated incremental cost\n    push!(c_g_scale_df, (g_opt[1], g_opt[2], w_opt, ws_opt, obj))\nend\n\n\nENV[\"COLUMNS\"]=250 # Helps us display the complete table\nc_g_scale_df\n\n\nfunction solve_ed_inplace(c_w_scale)\n    start = time()\n    obj_out = Float64[]\n    w_out = Float64[]\n    g1_out = Float64[]\n    g2_out = Float64[]\n    \n    ed = Model(GLPK.Optimizer)\n    \n    # Define decision variables    \n    @variable(ed, 0 <= g[i = 1:2] <= g_max[i]) # power output of generators\n    @variable(ed, 0 <= w <= w_f ) # wind power injection\n\n    # Define the objective function\n    @objective(ed, Min, dot(c_g, g) + c_w * w)\n\n    # Define the constraint on the maximum and minimum power output of each generator\n    @constraint(ed, [i = 1:2], g[i] <= g_max[i]) #maximum\n    @constraint(ed, [i = 1:2], g[i] >= g_min[i]) #minimum\n\n    # Define the constraint on the wind power injection\n    @constraint(ed, w <= w_f)\n\n    # Define the power balance constraint\n    @constraint(ed, sum(g) + w == d)\n    \n    optimize!(ed)\n    \n    for c_g1_scale = 0.5:0.01:3.0\n        @objective(ed, Min, c_g1_scale*c_g[1]*g[1] + c_g[2]*g[2] + c_w_scale*c_w*w)\n        optimize!(ed)\n        push!(obj_out, objective_value(ed))\n        push!(w_out, value(w))\n        push!(g1_out, value(g[1]))\n        push!(g2_out, value(g[2]))\n    end\n    elapsed = time() - start\n    print(string(\"elapsed time: \", elapsed, \" seconds\"))\n    return obj_out, w_out, g1_out, g2_out\nend\n\nsolve_ed_inplace(2.0);\n\n\ndemandscale_df = DataFrame(Symbol(\"Dispatch of Generators(MW)\") => Float64[],\n               Symbol(\"Dispatch of Generator 2(MW)\") => Float64[],\n               Symbol(\"Dispatch of Wind(MW)\") => Float64[],\n               Symbol(\"Spillage of Wind(MW)\") => Float64[],\n               Symbol(\"Total cost(\\$)\") => Float64[])\n\nfor demandscale = 0.2:0.1:1.5\n    g_opt,w_opt,ws_opt,obj = solve_ed(g_max, g_min, c_g, c_w, demandscale*d, w_f)\n\n    push!(demandscale_df, (g_opt[1], g_opt[2], w_opt, ws_opt, obj))\nend\n\n\ndemandscale_df\n\n\n# In this cell we introduce binary decision u to the economic dispatch problem (function solve_ed)\nfunction solve_uc(g_max, g_min, c_g, c_w, d, w_f)\n    #Define the unit commitment (UC) model\n    uc = Model(GLPK.Optimizer)\n    \n    # Define decision variables    \n    @variable(uc, 0 <= g[i=1:2] <= g_max[i]) # power output of generators\n    @variable(uc, u[i = 1:2], Bin) # Binary status of generators\n    @variable(uc, 0 <= w <= w_f ) # wind power injection\n\n    # Define the objective function\n    @objective(uc, Min, dot(c_g, g) + c_w * w)\n\n    # Define the constraint on the maximum and minimum power output of each generator\n    @constraint(uc, [i = 1:2], g[i] <= g_max[i]) #maximum\n    @constraint(uc, [i = 1:2], g[i] >= g_min[i]) #minimum\n\n    # Define the constraint on the wind power injection\n    @constraint(uc, w <= w_f)\n\n    # Define the power balance constraint\n        @constraint(uc, sum(g) + w == d)\n\n    # Solve statement\n    optimize!(uc)\n    \n    status = termination_status(uc)\n    if status != MOI.OPTIMAL\n        return status, zeros(length(g)), 0.0, 0.0, zeros(length(u)), Inf\n    end\n    return status, value.(g), value(w), w_f - value(w), value.(u), objective_value(uc)\nend\n\n# Solve the economic dispatch problem\nstatus, g_opt, w_opt, ws_opt, u_opt, obj = solve_uc(g_max, g_min, c_g, c_w, d, w_f);\n\nprintln(\"\\n\")\nprintln(\"Dispatch of Generators: \", g_opt[:], \" MW\")\nprintln(\"Commitments of Generators: \", u_opt[:])\nprintln(\"Dispatch of Wind: \", w_opt, \" MW\")\nprintln(\"Wind spillage: \", w_f - w_opt, \" MW\") \nprintln(\"\\n\")\nprintln(\"Total cost: \", obj, \"\\$\")\n\n\nuc_df = DataFrame(Symbol(\"Commitment of Generator 1(MW)\") => Float64[],\n               Symbol(\"Commitment of Generator 2(MW)\") => Float64[],\n               Symbol(\"Dispatch of Generator 1(MW)\") => Float64[],\n               Symbol(\"Dispatch of Generator 2(MW)\") => Float64[],\n               Symbol(\"Dispatch of Wind(MW)\") => Float64[],\n               Symbol(\"Spillage of Wind(MW)\") => Float64[],\n               Symbol(\"Total cost(\\$)\") => Float64[])\n\nfor demandscale = 0.2:0.1:1.5\n    status, g_opt, w_opt, ws_opt, u_opt, obj = solve_uc(g_max, g_min, c_g, c_w, demandscale*d, w_f)\n \n    if status == MOI.OPTIMAL\n    push!(uc_df, (u_opt[1], u_opt[2], g_opt[1], g_opt[2], w_opt, ws_opt, obj))\n    else\n        println(\"Status: $status for demandscale = $demandscale \\n\")\n    end\nend\n\n\nuc_df\n\n", "meta": {"hexsha": "5e3d33bf15b0058fa2552532ea157de109d2dc13", "size": 6729, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/modelling/power_systems.jl", "max_stars_repo_name": "mtanneau/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-07T20:43:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-06T17:51:12.000Z", "max_issues_repo_path": "test/modelling/power_systems.jl", "max_issues_repo_name": "mtanneau/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-05T21:03:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-05T21:03:40.000Z", "max_forks_repo_path": "test/modelling/power_systems.jl", "max_forks_repo_name": "mtanneau/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-18T01:29:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-18T01:29:51.000Z", "avg_line_length": 32.9852941176, "max_line_length": 135, "alphanum_fraction": 0.6274334968, "num_tokens": 2008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7974764061985431}}
{"text": "using DifferentialEquations\nusing Plots\nplotlyjs()\n\n#constants\nl = 1.0                             # length [m]\nm = 1.0                             # mass[Kg]\ng = 9.81                            # gravitational acceleration [m/s²]\n\n#function to compute ODE\nfunction pendulum!(du,u,p,t)\n    du[1] = u[2]                    # θ'(t) = ω(t)\n    du[2] = -(g\\l)*sin(u[1])  # ω'(t) = -(g/l) sin θ(t)\nend\n\n#initial conditions\nθ₀ = π/6                         # initial angular deflection [rad]\nω₀ = 0.0                            # initial angular velocity [rad/s]\nu₀ = [θ₀, ω₀]                       # initial state vector\ntspan = (0.0,100.0)                  # time interval\n\n#defining the problem and solving\nprob = ODEProblem(pendulum!,u₀,tspan)\nsol = solve(prob,saveat=0.1)\n\n#plotting the solution\ndisplay(plot(sol,linewidth=2,xaxis=\"t (s)\",\n    color=[\"green\" \"blue\"],label=[\"θ [rad]\" \"ω [rad/s]\"],layout=(2,1)))\nsavefig(\"./plots/simple pendulum-plot.png\")\n\n# trajectory\nt=sol.t\nU=sol[1:end,:]\n(θ,ω)=[U[x,:] for x in 1:size(U,1)]\nx=l.*sin.(π.-θ)\ny=zeros(size(t))\nz=l.*cos.(π.-θ)\ndisplay(plot(x,y,z,linewidth=2,label=\"trajectory\",\n    xaxis=\"x (m)\",yaxis=\"y (m)\",zaxis=\"z (m)\",grid=(:on,:black)))\nsavefig(\"./plots/simple pendulum-trajectory.png\")\n\n\n", "meta": {"hexsha": "31183eb5aeb852b3e3d998203824b7a4d9f9df62", "size": 1246, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Modeling the Dragon Module as a Pendulum/Scripts/pendulum.jl", "max_stars_repo_name": "Ramana-bharathi/modelling-recovery-module", "max_stars_repo_head_hexsha": "7d522aef4ae184f7ca9991056de7327e2a782eef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Modeling the Dragon Module as a Pendulum/Scripts/pendulum.jl", "max_issues_repo_name": "Ramana-bharathi/modelling-recovery-module", "max_issues_repo_head_hexsha": "7d522aef4ae184f7ca9991056de7327e2a782eef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modeling the Dragon Module as a Pendulum/Scripts/pendulum.jl", "max_forks_repo_name": "Ramana-bharathi/modelling-recovery-module", "max_forks_repo_head_hexsha": "7d522aef4ae184f7ca9991056de7327e2a782eef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.976744186, "max_line_length": 71, "alphanum_fraction": 0.5393258427, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693688269984, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7974696289663635}}
{"text": "using Printf\n\nagm1step(x, y) = (x + y) / 2, sqrt(x * y)\n\nfunction approxπstep(x, y, z, n::Integer)\n    a, g = agm1step(x, y)\n    k = n + 1\n    s = z + 2 ^ (k + 1) * (a ^ 2 - g ^ 2)\n    return a, g, s, k\nend\n\napproxπ(a, g, s) = 4a ^ 2 / (1 - s)\n\nfunction testmakepi()\n\tsetprecision(512)\n\ta, g, s, k = BigFloat(1.0), 1 / √BigFloat(2.0), BigFloat(0.0), 0\n\toldπ = BigFloat(0.0)\n\tprintln(\"Approximating π using \", precision(BigFloat), \"-bit floats.\")\n\tprintln(\"   k     Error  Result\")\n\tfor i in 1:100\n\t\ta, g, s, k = approxπstep(a, g, s, k)\n\t\testπ = approxπ(a, g, s)\n\t\tif abs(estπ - oldπ) < 2eps(estπ) break end\n\t\toldπ = estπ\n\t\terr = abs(π - estπ)\n\t\t@printf(\"%4d%10.1e%68.60e\\n\", i, err, estπ)\n\tend\nend\n\ntestmakepi()\n", "meta": {"hexsha": "9a242c100b8eb257d062a7560414a7d136a66f37", "size": 712, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/arithmetic-geometric-mean-calculate-pi.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/arithmetic-geometric-mean-calculate-pi.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/arithmetic-geometric-mean-calculate-pi.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9677419355, "max_line_length": 71, "alphanum_fraction": 0.5603932584, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7974696258657064}}
{"text": "module MyCalculus\n\nexport EulerMethod\n\n\n\"\"\"\n    EulerMethod(f, x₀, y₀, step= 0.5, n=100.0)\n\nFunction to approximate solution to an ordinary differential equation using the Euler's Method.\ndy/dx = f(x, y) where y(x₀) = y₀ and x₀ = x₀.\n\n# Arguments\n    f: function to approximate solution to, of the form f(x, y). \n        This is the right hand side of the differential equation.\n    x₀: initial x value condition\n    y₀: initial y value condition\n    step: step size for the Euler's Method\n    n: number of steps to take\n\n# Returns\n    x: array of x values\n    y: array of y values\n\n\"\"\"\nfunction EulerMethod(f::Function, x₀::Real, y₀::Real, step::Real, n::Real=100.0)\n\n    y =[y₀] #initialize y array with intiial condition\n    x = [x for x in range(x₀, step=step, length=n)] # array of x values starting with initial condition\n    m = [] # this array will hold slope (right hand side of differential equation)\n    \n    push!(m, f(x[1], y[1])) # push initial slope onto array\n\n    for k in 2:length(x) # iterate through x values starting at 2nd element\n\n        push!(y, y[k-1] + m[k-1]*step) # push new y value to array using Euler's Method\n        push!(m, f(x[k], y[k])) # push slope to array\n    end\n    \n    return x, y\n\nend\n\n\n\n\n\n\nend\n", "meta": {"hexsha": "44b995c0c239424d46b73fb804886ce9fd5519cd", "size": 1240, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MyCalculus.jl", "max_stars_repo_name": "gjunqueira-sys/MyCalculus.jl", "max_stars_repo_head_hexsha": "9a1dee9be36b805e9523ca6d047d827f58c29a62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MyCalculus.jl", "max_issues_repo_name": "gjunqueira-sys/MyCalculus.jl", "max_issues_repo_head_hexsha": "9a1dee9be36b805e9523ca6d047d827f58c29a62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MyCalculus.jl", "max_forks_repo_name": "gjunqueira-sys/MyCalculus.jl", "max_forks_repo_head_hexsha": "9a1dee9be36b805e9523ca6d047d827f58c29a62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.306122449, "max_line_length": 103, "alphanum_fraction": 0.6540322581, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693631290971, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7974696222771653}}
{"text": "using DelimitedFiles\nusing LinearAlgebra\n\nfunction convolve_linear(signal::Array{T, 2}, filter::Array{T, 2},\n                         output_size) where {T <: Number}\n\n    # convolutional output\n    out = Array{Float64,2}(undef, output_size)\n    sum = 0\n\n    for i = 1:output_size[1]\n        for j = 1:output_size[2]\n            for k = max(1, i-size(filter)[1]):i\n                for l = max(1, j-size(filter)[2]):j\n                    if k <= size(signal)[1] && i-k+1 <= size(filter)[1] &&\n                       l <= size(signal)[2] && j-l+1 <= size(filter)[2]\n                        sum += signal[k,l] * filter[i-k+1, j-l+1]\n                    end\n                end\n            end\n\n            out[i,j] = sum\n            sum = 0\n        end\n    end\n\n    return out\nend\n\nfunction create_gaussian_kernel(kernel_size)\n\n    kernel = zeros(kernel_size, kernel_size)\n\n    # The center must be offset by 0.5 to find the correct index\n    center = kernel_size * 0.5 + 0.5\n\n    sigma = sqrt(0.1*kernel_size)\n\n    for i = 1:kernel_size\n        for j = 1:kernel_size\n            kernel[i,j] = exp(-((i-center)^2 + (j-center)^2) / (2*sigma^2))\n        end\n    end\n\n    return normalize(kernel)\n    \nend\n\nfunction create_sobel_operators()\n    Sx = [1.0, 2.0, 1.0]*[-1.0 0.0 1.0] / 9\n    Sy = [-1.0, 0.0, 1.0]*[1.0 2.0 1.0] / 9\n\n    return Sx, Sy\nend\n\nfunction compute_sobel(signal)\n    Sx, Sy = create_sobel_operators()\n\n    Gx = convolve_linear(signal, Sx, size(signal) .+ size(Sx))\n    Gy = convolve_linear(signal, Sy, size(signal) .+ size(Sy))\n\n    return sqrt.(Gx.^2 .+ Gy.^2)\nend\n\n# Simple function to create a square grid with a circle embedded inside of it\nfunction create_circle(image_resolution, grid_extents, radius)\n    out = zeros(image_resolution, image_resolution)\n\n    for i = 1:image_resolution\n        x_position = ((i-1)*grid_extents/image_resolution)-0.5*grid_extents\n        for j = 1:image_resolution\n            y_position = ((j-1)*grid_extents/image_resolution)-0.5*grid_extents\n            if x_position^2 + y_position^2 <= radius^2\n                out[i,j] = 1.0\n            end\n        end\n    end \n\n    return out\nend\n\nfunction main()\n\n    # Random distribution in x\n    x = rand(100, 100)\n\n    # Gaussian signals\n    y = [exp(-(((i-50)/100)^2 + ((j-50)/100)^2)/.01) for i = 1:100, j=1:100]\n\n    # Normalization is not strictly necessary, but good practice\n    normalize!(x)\n    normalize!(y)\n\n    # full convolution, output will be the size of x + y\n    full_linear_output = convolve_linear(x, y, size(x) .+ size(y))\n\n    # simple boundaries\n    simple_linear_output = convolve_linear(x, y, size(x))\n\n    # outputting convolutions to different files for plotting in external code\n    writedlm(\"full_linear.dat\", full_linear_output)\n    writedlm(\"simple_linear.dat\", simple_linear_output)\n\n    # creating simple circle and 2 different Gaussian kernels\n    circle = create_circle(50,2,0.5)\n\n    normalize!(circle)\n\n    small_kernel = create_gaussian_kernel(3)\n    large_kernel = create_gaussian_kernel(25)\n\n    small_kernel_output = convolve_linear(circle, small_kernel,\n                                          size(circle).+size(small_kernel))\n    large_kernel_output = convolve_linear(circle, large_kernel,\n                                          size(circle).+size(large_kernel))\n\n    writedlm(\"small_kernel.dat\", small_kernel_output)\n    writedlm(\"large_kernel.dat\", large_kernel_output)\n\n    # Using the circle for Sobel operations as well\n    sobel_output = compute_sobel(circle)\n\n    writedlm(\"sobel_output.dat\", sobel_output)\n\nend\n", "meta": {"hexsha": "6d38e504886b0e953be647a806e5da16e7b046d4", "size": 3565, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "contents/convolutions/2d/code/julia/2d_convolution.jl", "max_stars_repo_name": "alzawad26/algorithm-archive", "max_stars_repo_head_hexsha": "98ca4ab8115dd9013e6a5267cb757d61f0350ad7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1975, "max_stars_repo_stars_event_min_datetime": "2018-04-28T13:46:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:14:47.000Z", "max_issues_repo_path": "contents/convolutions/2d/code/julia/2d_convolution.jl", "max_issues_repo_name": "alzawad26/algorithm-archive", "max_issues_repo_head_hexsha": "98ca4ab8115dd9013e6a5267cb757d61f0350ad7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 632, "max_issues_repo_issues_event_min_datetime": "2018-04-28T10:27:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T20:38:53.000Z", "max_forks_repo_path": "contents/convolutions/2d/code/julia/2d_convolution.jl", "max_forks_repo_name": "alzawad26/algorithm-archive", "max_forks_repo_head_hexsha": "98ca4ab8115dd9013e6a5267cb757d61f0350ad7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 433, "max_forks_repo_forks_event_min_datetime": "2018-04-27T22:50:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T06:16:03.000Z", "avg_line_length": 28.2936507937, "max_line_length": 79, "alphanum_fraction": 0.6067321178, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.797378374267887}}
{"text": "\n# N is the number of dimensions of the prediction\nabstract Loss{N}\ntypealias UnivariateLoss Loss{0}\ntypealias MultivariateLoss Loss{1}\n\n## Abs loss (for regression)\n#\n#   loss(p, y) = |p - y|\n#\nimmutable AbsLoss <: UnivariateLoss\nend\n\nvalue{T<:BlasReal}(::AbsLoss, p::T, y::T) = abs(p - y)\nderiv{T<:BlasReal}(::AbsLoss, p::T, y::T) = sign(p - y)\nvalue_and_deriv{T<:BlasReal}(::AbsLoss, p::T, y::T) = (r = p - y; (abs(r), sign(r)))\n\n\n## Squared loss (for regression)\n#\n#   loss(p, y) := (1/2) * (p - y)^2\n#\nimmutable SqrLoss <: UnivariateLoss\nend\n\nvalue{T<:BlasReal}(::SqrLoss, p::T, y::T) = half(abs2(p - y))\nderiv{T<:BlasReal}(::SqrLoss, p::T, y::T) = p - y\nvalue_and_deriv{T<:BlasReal}(::SqrLoss, p::T, y::T) = (r = p - y; v = half(abs2(r)); (v, r))\n\n\n## Quantile loss (for quantile regression, asymmetric version of Abs loss)\n#\n#   loss(p, y) := t * (p - y)         ... (p >= y)\n#               = (1 - t) * (y - p)   ... (p < y)\n#\nimmutable QuantileLoss <: UnivariateLoss\n    t::Float64\n\n    function QuantileLoss(t::Real)\n        zero(t) < t < one(t) || error(\"t must be a real value in (0, 1).\")\n        new(convert(Float64, t))\n    end\nend\n\nfunction value{T<:BlasReal}(loss::QuantileLoss, p::T, y::T)\n    t = convert(T, loss.t)\n    p >= y ? t * (p - y) : (one(T) - t) * (y - p)\nend\n\nfunction deriv{T<:BlasReal}(loss::QuantileLoss, p::T, y::T)\n    t = convert(T, loss.t)\n    p > y ? t :\n    p < y ? t - one(T) : zero(T)\nend\n\nfunction value_and_deriv{T<:BlasReal}(loss::QuantileLoss, p::T, y::T)\n    t = convert(T, loss.t)\n    if p > y\n        (t * (p - y), t)\n    elseif p < y\n        c = t - one(T)\n        (c * (p - y), c)\n    else\n        (zero(T), zero(T))\n    end\nend\n\n\n## Epsilon Insensitive loss (for support vector regression)\n#\n#   loss(p, y) := 0                   ... abs(y - p) <= eps\n#               = abs(y - p) - eps    ... otherwise\n#\nimmutable EpsilonInsLoss <: UnivariateLoss\n    epsilon::Float64\n\n    function EpsilonInsLoss(epsilon::Real)\n        new(convert(Float64, epsilon))\n    end\nend\n\nfunction value{T<:BlasReal}(loss::EpsilonInsLoss, p::T, y::T)\n    eps = convert(T, loss.epsilon)\n    a = abs(p - y)\n    a > eps ? a - eps : zero(T)\nend\n\nfunction deriv{T<:BlasReal}(loss::EpsilonInsLoss, p::T, y::T)\n    eps = convert(T, loss.epsilon)\n    r = p - y\n    abs(r) > eps ? sign(r) : zero(T)\nend\n\nfunction value_and_deriv{T<:BlasReal}(loss::EpsilonInsLoss, p::T, y::T)\n    eps = convert(T, loss.epsilon)\n    r = p - y\n    a = abs(r)\n    a > eps ? (a - eps, sign(r)) : (zero(T), zero(T))\nend\n\n\n## Huber loss (for regression, smoothed version of Abs loss)\n#\n#   loss(p, y) := (1/2) * (p - y)^2      ... (|p - y| <= h)\n#                 h * |p - y| - h^2/2    ... otherwise\n#\nimmutable HuberLoss <: UnivariateLoss\n    h::Float64\n\n    function HuberLoss(h::Real)\n        h > zero(h) || error(\"h must be a positive value.\")\n        new(convert(Float64, h))\n    end\nend\n\nfunction value{T<:BlasReal}(loss::HuberLoss, p::T, y::T)\n    h = convert(T, loss.h)\n    a = abs(p - y)\n    a <= h ? half(a * a) : h * a - half(h * h)\nend\n\nfunction deriv{T<:BlasReal}(loss::HuberLoss, p::T, y::T)\n    h = convert(T, loss.h)\n    r = p - y\n    r > h ? h : r < -h ? -h : r\nend\n\nfunction value_and_deriv{T<:BlasReal}(loss::HuberLoss, p::T, y::T)\n    h = convert(T, loss.h)\n    r = p - y\n    r > h ? (h * r - half(h * h), h) :\n    r < -h ? (-h * r - half(h * h), -h) :\n    (half(r * r), r)\nend\n\n\n## Hinge loss (for L1-SVM)\n#\n#   loss(p, y) := max(1 - y * p, 0)\n#\nimmutable HingeLoss <: UnivariateLoss\nend\n\nvalue{T<:BlasReal}(::HingeLoss, p::T, y::T) = nonneg(one(T) - y * p)\nderiv{T<:BlasReal}(::HingeLoss, p::T, y::T) = y * p < one(T) ? -y : zero(T)\n\nfunction value_and_deriv{T<:BlasReal}(::HingeLoss, p::T, y::T)\n    yp = y * p\n    yp >= one(T) ? (zero(T), zero(T)) : (one(T) - yp, -y)\nend\n\n\n## Squared Hinge loss (for L2-SVM)\n#\n#   loss(p, y) := max(1 - y * p, 0)^2\n#\nimmutable SqrHingeLoss <: UnivariateLoss\nend\n\nfunction value{T<:BlasReal}(::SqrHingeLoss, p::T, y::T)\n    yp = y * p\n    yp >= one(T) ? zero(T) : abs2(nonneg(one(T) - yp))\nend\n\nderiv{T<:BlasReal}(::SqrHingeLoss, p::T, y::T) = y * p < one(T) ? 2(p - y) : zero(T)\n\nfunction value_and_deriv{T<:BlasReal}(::SqrHingeLoss, p::T, y::T)\n    yp = y * p\n    yp >= one(T) ? (zero(T), zero(T)) : (abs2(one(T) - yp), 2(p - y))\nend\n\n\n## Smoothed HingeLoss\n#\n#   loss(p, y) := 0              ... y * p > 1 + h\n#                 1 - y * p      ... y * p < 1 - h\n#                 (1 + h - y * p)^2 / 4h   ... otherwise\n#\n#  Reference\n#\n#   O. Chapelle, \"Training a Support Vector Machine in the Primal\", Neural Computation.\n#\nimmutable SmoothedHingeLoss <: UnivariateLoss\n    h::Float64\n\n    function SmoothedHingeLoss(h::Real)\n        h > zero(h) || error(\"h must be a positive value.\")\n        new(convert(Float64, h))\n    end\nend\n\nfunction value{T<:BlasReal}(loss::SmoothedHingeLoss, p::T, y::T)\n    h = convert(T, loss.h)\n    yp = y * p\n    yp >= one(T) + h ? zero(T) :\n    yp <= one(T) - h ? one(T) - yp :\n    abs2(one(T) + h - yp) / 4h\nend\n\nfunction deriv{T<:BlasReal}(loss::SmoothedHingeLoss, p::T, y::T)\n    h = convert(T, loss.h)\n    yp = y * p\n    yp >= one(T) + h ? zero(T) :\n    yp <= one(T) - h ? -y :\n    y * (yp - one(T) - h) / 2h\nend\n\nfunction value_and_deriv{T<:BlasReal}(loss::SmoothedHingeLoss, p::T, y::T)\n    h = convert(T, loss.h)\n    yp = y * p\n    if yp >= one(T) + h\n        (zero(T), zero(T))\n    elseif yp <= one(T) - h\n        (one(T) - yp, -y)\n    else\n        z = yp - one(T) - h\n        (abs2(z) / 4h, y * z / 2h)\n    end\nend\n\n\n## Logistic loss (for logistic regression)\n#\n#   loss(p, y) := log(1 + exp(-y * p))\n#\nimmutable LogisticLoss <: UnivariateLoss\nend\n\nvalue{T<:BlasReal}(::LogisticLoss, p::T, y::T) =\n    (yp = y * p; yp >= zero(T) ? log1p(exp(-yp)) : log1p(exp(yp)) - yp)\n\nfunction deriv{T<:BlasReal}(::LogisticLoss, p::T, y::T)\n    yp = y * p\n    if yp >= zero(T)\n        e = exp(-yp)\n        -y * e / (one(T) + e)\n    else\n        -y / (one(T) + exp(yp))\n    end\nend\n\nfunction value_and_deriv{T<:BlasReal}(::LogisticLoss, p::T, y::T)\n    yp = y * p\n    if yp >= zero(T)\n        e = exp(-yp)\n        (log1p(e), -y * e / (one(T) + e))\n    else\n        e = exp(yp)\n        (log1p(e) - yp, -y / (one(T) + e))\n    end\nend\n\n\n## general functions for multivariate loss\n\ngrad{T<:BlasReal}(loss::MultivariateLoss, p::StridedVector{T}, y) =\n    grad!(loss, zeros(T, length(p)), p, y)\n\nvalue_and_grad{T<:BlasReal}(loss::MultivariateLoss, p::StridedVector{T}, y) =\n    value_and_grad!(loss, zeros(T, length(p)), p, y)\n\n\n## SumLoss\n#\n#   loss(p, y) := sum_k loss.intern(p[k], y[k])\n#\nimmutable SumLoss{L<:UnivariateLoss} <: MultivariateLoss\n    intern::L\nend\n\nSumLoss{L<:UnivariateLoss}(loss::L) = SumLoss{L}(loss)\n\ntypealias SumSqrLoss SumLoss{SqrLoss}\nSumSqrLoss() = SumLoss{SqrLoss}(SqrLoss())\n\nfunction value{T<:BlasReal}(s::SumLoss, p::StridedVector{T}, y::StridedVector{T})\n    loss = s.intern\n    k = length(p)\n    @_checkdims k == length(y)\n    s = value(loss, p[1], y[1])\n    @inbounds for i = 2:k\n        s += value(loss, p[i], y[i])\n    end\n    s\nend\n\nfunction grad!{T<:BlasReal}(s::SumLoss, g::StridedVector{T}, p::StridedVector{T}, y::StridedVector{T})\n    loss = s.intern\n    k = length(p)\n    @_checkdims k == length(g) == length(y)\n    @inbounds for i = 1:k\n        g[i] = deriv(loss, p[i], y[i])\n    end\n    g\nend\n\nfunction value_and_grad!{T<:BlasReal}(s::SumLoss, g::StridedVector{T}, p::StridedVector{T}, y::StridedVector{T})\n    loss = s.intern\n    k = length(p)\n    @_checkdims k == length(g) == length(y)\n    s, dv = value_and_deriv(loss, p[1], y[1])\n    g[1] = dv\n    @inbounds for i = 2:k\n        v, dv = value_and_deriv(loss, p[i], y[i])\n        s += v\n        g[i] = dv\n    end\n    (s, g)\nend\n\n\n## Multinomial logistic loss (for Multinomial logistic regression)\n#\n#   loss(p, y) := log(sum_k exp(p[k])) - p[y]\n#\nimmutable MultiLogisticLoss <: MultivariateLoss\nend\n\nfunction value{T<:BlasReal}(::MultiLogisticLoss, p::StridedVector{T}, y::Integer)\n    k = length(p)\n    pmax = maximum(p)\n    s = zero(T)\n    @inbounds for i = 1:k\n        s += exp(p[i] - pmax)\n    end\n    pmax + log(s) - p[y]\nend\n\nfunction grad!{T<:BlasReal}(::MultiLogisticLoss, g::StridedVector{T}, p::StridedVector{T}, y::Integer)\n    k = length(p)\n    @_checkdims length(g) == k\n    pmax = maximum(p)\n    s = zero(T)\n    @inbounds for i = 1:k\n        pi = exp(p[i] - pmax)\n        g[i] = pi\n        s += pi\n    end\n    @inbounds for i = 1:k\n        g[i] /= s\n    end\n    g[y] -= one(T)\n    g\nend\n\nfunction value_and_grad!{T<:BlasReal}(::MultiLogisticLoss, g::StridedVector{T}, p::StridedVector{T}, y::Integer)\n    k = length(p)\n    @_checkdims length(g) == k\n\n    pmax = maximum(p)\n    p_y = p[y]  # g and p can be the same array, so have to cache p[y] before p is overwritten\n\n    s = zero(T)\n    @inbounds for i = 1:k\n        pi = exp(p[i] - pmax)\n        g[i] = pi\n        s += pi\n    end\n\n    @inbounds for i = 1:k\n        g[i] /= s\n    end\n    g[y] -= one(T)\n    return (pmax - p_y + log(s), g)\nend\n", "meta": {"hexsha": "f667ed41961479fad646e1e99dc3f1962e6e312a", "size": 8985, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/loss.jl", "max_stars_repo_name": "JuliaPackageMirrors/EmpiricalRisks.jl", "max_stars_repo_head_hexsha": "28361a117a4c97a89991a7d99968ba2c7850df03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2015-04-20T12:42:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-25T23:02:37.000Z", "max_issues_repo_path": "src/loss.jl", "max_issues_repo_name": "JuliaPackageMirrors/EmpiricalRisks.jl", "max_issues_repo_head_hexsha": "28361a117a4c97a89991a7d99968ba2c7850df03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2015-05-15T16:00:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:31:43.000Z", "max_forks_repo_path": "src/loss.jl", "max_forks_repo_name": "JuliaPackageMirrors/EmpiricalRisks.jl", "max_forks_repo_head_hexsha": "28361a117a4c97a89991a7d99968ba2c7850df03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-05-15T15:18:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:11:30.000Z", "avg_line_length": 24.5491803279, "max_line_length": 112, "alphanum_fraction": 0.5443516973, "num_tokens": 3286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7973783662914308}}
{"text": "\n\nfunction RouwenNormalize!(A)\n    A[2:end-1, :] ./= 2\n    nothing\nend\n\nfunction rouwenupdate!(Πold, Πnew, p, q)\n    Nold = size(Πold, 1)\n    Πnew[1:Nold, 1:Nold] = p*Πold\n    Πnew[1:Nold, 2:(Nold+1)] .+= (1-p)*Πold\n    Πnew[2:(Nold+1), 1:Nold] .+= (1-q)*Πold\n    Πnew[2:(Nold+1), 2:(Nold+1)] .+= q*Πold\n    nothing\nend\n\nfunction rouwenmat(N, ρ, p, q)\n    initmat = [p 1-p;1-q q]\n    if N==2\n        ret = initmat\n    else\n        currmat = initmat\n        for n = 3:N\n            nextmat = fill(zero(ρ), (n, n))\n            rouwenupdate!(currmat, nextmat, p, q)\n            currmat = nextmat\n            RouwenNormalize!(currmat)\n        end\n        ret = currmat\n    end\n    return(ret)\nend\n\n\"\"\"\n    rouwenhorst(npts, ρ, σ)\n\nDiscretizes AR(1) process `y′ = ρ y +  σ ϵ`.\n\n\n# Example\n\nnpts = 10\nrho = 0.9\nsig = 0.01\npoints, Π = rouwenhorst(npts, rho, sig)\n\n\"\"\"\nfunction rouwenhorst(npts, ρ, σ)\n    ω = σ/sqrt(1-ρ^2) # long run std dev\n    # println(\"long run variance: $ω\")\n    q = (1+ρ)/2\n\n    points = range(-ω*sqrt(npts - 1),\n                   ω*sqrt(npts-1),\n                   length=npts)\n\n    # points = GenGrid(uniform(npts, bds))\n    Π = (npts > 1) ? rouwenmat(npts, ρ, q, q) : fill(one(ρ), (1,1))\n\n    return points, Π\nend\n\n\n\"Returns a MarkovChain with discretized AR(1) from applying `rouwenhorst`\"\nrouwenhorst_mc(npts, ρ, σ)=MarkovChain(rouwenhorst(npts, ρ, σ)...)\n", "meta": {"hexsha": "09cd36c3328008de8b4384a3b317dbaedb19975f", "size": 1378, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rouwenhorst.jl", "max_stars_repo_name": "pereiragc/Econlite.jl", "max_stars_repo_head_hexsha": "4ee2664231bac4ba62b38bb85abcd7129da6bf09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rouwenhorst.jl", "max_issues_repo_name": "pereiragc/Econlite.jl", "max_issues_repo_head_hexsha": "4ee2664231bac4ba62b38bb85abcd7129da6bf09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rouwenhorst.jl", "max_forks_repo_name": "pereiragc/Econlite.jl", "max_forks_repo_head_hexsha": "4ee2664231bac4ba62b38bb85abcd7129da6bf09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8787878788, "max_line_length": 74, "alphanum_fraction": 0.5449927431, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.8670357615200475, "lm_q1q2_score": 0.7973629642555177}}
{"text": "\nfunction check_symplecticity(tab::Tableau{T}; atol=16eps(T), rtol=16eps(T)) where {T}\n    a, b = tab.a, tab.b\n    [isapprox(b[i] * a[i,j] + b[j] * a[j,i], b[i] * b[j]; atol=atol, rtol=rtol) for i in axes(a,1), j in axes(a,2)]\nend\n\nfunction issymplectic(tab::Tableau; kwargs...)\n    all(check_symplecticity(tab; kwargs...))\nend\n\n\nfunction check_symplecticity(tab::PartitionedTableau{T}; atol=16eps(T), rtol=16eps(T)) where {T}\n    a, b = tab.q.a, tab.q.b\n    ā, b̄ = tab.p.a, tab.p.b\n    ([isapprox(b[i] * ā[i,j] + b̄[j] * a[j,i], b[i] * b̄[j]; atol=atol, rtol=rtol) for i in axes(a,1), j in axes(a,2)],\n     [isapprox(b[i], b̄[i]; atol=atol, rtol=rtol) for i in eachindex(b,b̄)])\nend\n\nfunction issymplectic(tab::PartitionedTableau; kwargs...)\n    all(all.(check_symplecticity(tab; kwargs...)))\nend\n\n\nfunction compute_symplecticity_error(tab::Tableau)\n    a, b = tab.a, tab.b\n    [b[i] * a[i,j] + b[j] * a[j,i] - b[i] * b[j] for i in axes(a,1), j in axes(a,2)]\nend\n\n\nfunction get_symplectic_conjugate_coefficients!(a̅::AbstractMatrix{T}, a::AbstractMatrix{T}, b::AbstractVector{T}) where {T}\n    @assert size(a) == size(a̅)\n    @assert length(b) == size(a,1) == size(a,2)\n\n    for i in axes(a̅, 1)\n        for j in axes(a̅, 2)\n            a̅[i,j] = b[j] / b[i] * ( b[i] - a[j,i] )\n        end\n    end\n\n    return a̅\nend\n\nget_symplectic_conjugate_coefficients(a, b) = get_symplectic_conjugate_coefficients!(zero(a), a, b)\nget_symplectic_conjugate_coefficients(tab::Tableau) = Tableau(tab.name, tab.s, get_symplectic_conjugate_coefficients(tab.a, tab.b), tab.b, tab.c)\n\n\nfunction symplecticize(tab::Tableau; name=nothing, T=Float64)\n    a̅ = get_symplectic_conjugate_coefficients(tab.a, tab.b)\n    Tableau{T}(name === nothing ? Symbol(tab.name, \"S\") : name, tab.o, (tab.a .+ a̅) ./ 2, tab.b, tab.c)\nend\n\n", "meta": {"hexsha": "769c26ad274dcace958c08ec8d77089e9fd01788", "size": 1804, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/symplecticity.jl", "max_stars_repo_name": "JuliaGNI/RungeKutta.jl", "max_stars_repo_head_hexsha": "b6933446c0f76525a2e36f4d94bf7ff9694c7f5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-13T13:08:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-02T11:55:34.000Z", "max_issues_repo_path": "src/symplecticity.jl", "max_issues_repo_name": "JuliaGNI/RungeKutta.jl", "max_issues_repo_head_hexsha": "b6933446c0f76525a2e36f4d94bf7ff9694c7f5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-11-28T20:00:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T17:28:29.000Z", "max_forks_repo_path": "src/symplecticity.jl", "max_forks_repo_name": "JuliaGNI/RungeKutta.jl", "max_forks_repo_head_hexsha": "b6933446c0f76525a2e36f4d94bf7ff9694c7f5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6923076923, "max_line_length": 145, "alphanum_fraction": 0.6297117517, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.8670357563664174, "lm_q1q2_score": 0.7973629556969082}}
{"text": "export gauss_quad_linear,gauss_points\nfunction gauss_quad_linear(N,a,b)\n    N=N-1;\n    N1=N+1;\n    N2=N+2;\n    xu=linspace(-1,1,N1)';\n    # Initial guess\n    y=cos.((2*(0:N)'+1)*pi/(2*N+2))+(0.27/N1)*sin.(pi*xu*N/N2);\n    # Legendre-Gauss Vandermonde Matrix\n    L=zeros(N1,N2);\n    # Derivative of LGVM\n    Lp=zeros(N1,N2);\n    # Compute the zeros of the N+1 Legendre Polynomial\n    # using the recursion relation and the Newton-Raphson method\n    y0=2;\n    # Iterate until new points are uniformly within epsilon of old points\n    while (maximum(abs.(y-y0))>eps(1.0))\n        L[:,1]=1;\n        Lp[:,1]=0;\n        L[:,2]=y;\n        #Lp[:,2]=1;\n        for k=2:N1\n            L[:,k+1]=( (2*k-1)*y'.*L[:,k]-(k-1)*L[:,k-1] )/k;\n        end\n        Lp=(N2)*( L[:,N1]-y'.*L[:,N2] )./(1-y.^2)';\n        y0=y;\n        y=y0'-L[:,N2]./Lp;\n        y=y'\n    end\n    y=y'\n    # Linear map from[-1,1] to [a,b]\n    x=(a*(1-y)+b*(1+y))/2;\n    # Compute the weights\n    w=(b-a)./((1-y.^2).*Lp.^2)*(N2/N1)^2;\n    return x, w\nend\n\nfunction gauss_points(N)\n    x,w = gauss_quad_linear(N,-1,1)\n    gpt = zeros(N*N,2)\n    gpw = zeros(N*N,1)\n    for i = 1:N\n        u = x[i]\n        wu = w[i]\n        for j = 1:N\n            v = x[j]\n            wv = w[j]\n            gpt[(i-1)*N + j,1] = u\n            gpt[(i-1)*N + j,2] = v\n            gpw[(i-1)*N + j] = wu * wv\n        end\n    end\n    return gpt,gpw\nend\n", "meta": {"hexsha": "51dee41694ddffa2833df6dbee0537c26159aaee", "size": 1386, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gaussquarature.jl", "max_stars_repo_name": "sbadrian/CompScienceMeshes.jl", "max_stars_repo_head_hexsha": "27c6737d2a39bca7e97aa204f4595ef007defe9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2018-05-30T20:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:10:58.000Z", "max_issues_repo_path": "src/gaussquarature.jl", "max_issues_repo_name": "sbadrian/CompScienceMeshes.jl", "max_issues_repo_head_hexsha": "27c6737d2a39bca7e97aa204f4595ef007defe9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2017-04-11T14:45:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T14:06:03.000Z", "max_forks_repo_path": "src/gaussquarature.jl", "max_forks_repo_name": "sbadrian/CompScienceMeshes.jl", "max_forks_repo_head_hexsha": "27c6737d2a39bca7e97aa204f4595ef007defe9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2017-03-29T17:00:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T11:45:35.000Z", "avg_line_length": 25.2, "max_line_length": 73, "alphanum_fraction": 0.4682539683, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7973064288128641}}
{"text": "##\n##  d e r i v a t i v e . j l  Numerical Derivatives\n##\n\n\n#-- Numerical gradient of multivariate function ------------------------------\n#\nfunction fd_gradient{T<:Real}(f::Function, x0::Array{T,1}; h::Real = 0.0)\n    local heps::Real = h\n    if heps == 0.0; heps = eps()^(1.0/3.0); end\n    local n::Int = length(x0)\n    if length(f(x0)) > 1\n        error(\"Function 'f' must be a scalar function.\")\n    end\n\n    local hh = zeros(n), gr = zeros(n)\n    for i = 1:n\n        hh[i] = heps\n        gr[i] = ((f(x0 + hh) - f(x0 - hh)) / (2.0*heps))\n        hh[i] = 0.0\n    end\n    return gr\nend\n\n\nfunction fd_gradient(f::Function, x0::Real; h::Real = 0.0)\n    local heps::Real = h\n    if heps == 0.0; heps = eps()^(1.0/3.0); end\n    if length(f(x0)) > 1\n        error(\"Function 'f' must be a scalar function.\")\n    end\n    return (f(x0 + heps) - f(x0 - heps)) / (2.0*heps)\nend\n\n\nfunction fd_jacobian{T<:Real}(f::Function, x0::Array{T,1}; h::Real = 0.0)\n    local heps::Real = h\n    if heps == 0.0; heps = eps()^(1.0/3.0); end\n\tlocal n = length(x0), m = length(f(x0))\n\tlocal hh = zeros(n)\n\tjacob = zeros(m, n)\n\tfor i = 1:n\n\t\thh[i] = heps\n\t\tjacob[:, i] = (f(x0 + hh) - f(x0 - hh)) / (2.0*heps)\n\t\thh[i] = 0.0\n\tend\n\treturn jacob\nend\n\n\nfunction fd_hessian{T<:Real}(f::Function, x0::Array{T,1}; h::Real = 0.0)\n    local heps::Real = h\n    if heps == 0.0; heps = eps()^(1.0/4.0); end\n    local n::Int = length(x0)\n    if length(f(x0)) != 1\n        error(\"Function 'f' must a scalar function of n variables.\")\n    end\n\n    if n == 1\n        H = (f(x0.-heps) - 2.0*f(x0) + f(x0.+heps)) / heps^2\n\n    else\n        H = zeros(n, n)\n        hh = diagm(heps*ones(n))\n        for i = 1:(n-1)\n            hi = hh[:, i]\n            H[i, i] = (f(x0-hi) - 2.0*f(x0) + f(x0+hi)) / heps^2\n            for j = (i+1):n\n                hj = hh[:, j]\n                H[i, j] = (f(x0+hi+hj) - f(x0+hi-hj) - f(x0-hi+hj) + f(x0-hi-hj)) / (4.0*heps^2)\n                H[j, i] = H[i, j]\n            end\n        end\n        hi = hh[:, n]\n        H[n, n] = (f(x0-hi) - 2.0*f(x0) + f(x0+hi)) / heps^2\n    end\n\n    return H\nend\n\n\nfunction fd_laplacian{T<:Real}(f::Function, x0::Array{T,1}; h::Real = 0.0)\n    local heps::Real = h\n    if heps == 0.0; heps = eps()^(1.0/4.0); end\n    local n::Int = length(x0)\n    local hh::Real = zeros(n)\n\n    L = 0.0\n    for i = 1:n\n        hh[i] = heps\n        L += (f(x0+hh) + f(x0-hh) - 2.0*f(x0)) / heps^2\n        hh[i] = 0.0\n    end\n\n    return L\nend\n\n\n#-- Central difference combined with Richardson approximation ----------------\n#\nfunction numderiv(f::Function, x0::Real; n::Int = 16, h::Real = 0.1)\n\n    local epsilon = eps(), err = Inf\n    local hstep::Real = h\n\n    j::Int = 1\n    D = zeros(n, n)\n    D[1, 1] = (f(x0+hstep) - f(x0-hstep))/(2*hstep)\n\n    while j < n\n        hstep = hstep / 2.0\n        D[j+1, 1] = (f(x0+hstep) - f(x0-hstep)) / (2*hstep)\n        for k = 1:j\n            D[j+1,k+1] = D[j+1,k] + (D[j+1,k] - D[j,k]) / (4^k - 1)\n        end\n\n        err_new = 2 * abs(D[j+1,j+1] - D[j,j]) /\n                  (abs(D[j+1,j+1]) + abs(D[j,j]) + epsilon)\n\n        if err_new >= err; break; end\n        err = err_new\n        j += 1\n    end\n\n    return D[j,j]\nend\n\n\n#-- Complex-step derivative approach -----------------------------------------\n#\nfunction complex_step(f::Function, x0::Real; h::Real = 1e-20)\n    # Check whether function accepts and returns complex values\n    if !isa(f(x0), Real)\n        error(\"Function 'f' must take on a real(!) value at 'x0'.\")\n    end\n\n    fx0hi = try\n        f(x0 + h*1im)\n    catch err\n        error(\"Function 'f' does not appear to accept complex arguments.\")\n    end\n\n    # f(x0) must be real, fx0hi complex\n    if !isa(fx0hi, Complex)\n        error(\"'f(x0 + h*1im)' must be complex for 'complex-step' to work.\")\n    end\n\n    return imag(fx0hi) / h\nend\n", "meta": {"hexsha": "504120a3365a3f962d75509e5885ee384e6b0361", "size": 3808, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/derivative.jl", "max_stars_repo_name": "hwborchers/NumericalMath.jl", "max_stars_repo_head_hexsha": "5afaa8d71e496dd71a2dbd642a688999b5f9963d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-03-11T19:26:16.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-12T21:39:58.000Z", "max_issues_repo_path": "src/derivative.jl", "max_issues_repo_name": "hwborchers/NumericalMath.jl", "max_issues_repo_head_hexsha": "5afaa8d71e496dd71a2dbd642a688999b5f9963d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-02-05T14:03:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-26T03:45:52.000Z", "max_forks_repo_path": "src/derivative.jl", "max_forks_repo_name": "hwborchers/NumericalMath.jl", "max_forks_repo_head_hexsha": "5afaa8d71e496dd71a2dbd642a688999b5f9963d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2015-01-25T21:38:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T04:30:29.000Z", "avg_line_length": 25.3866666667, "max_line_length": 96, "alphanum_fraction": 0.4897584034, "num_tokens": 1462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7972996390172166}}
{"text": "# # Implementations and proof of concept\n#\n# In this examples I want to show some of the implementations and how they are used\n# as a proof of concept. This means that we will use the \"low-level API\", i.e. calling\n# the methods directly instead of the `optimize` interface.\n#\n# Further, we wish to show that the implementations can at least solve some of the\n# most common benchmark optimization problems.\n#\n# Before we start, I will define a seed and an RNG to enable reproducibility of the\n# results presented here.\n\nusing Random\n\nRANDOM_SEED = 458012;\nrng = MersenneTwister(RANDOM_SEED);\n\n#\n# ## Nonlinear ``d``-dimensional global optimization problem\n#\n# Using `BioMetaheuristics.jl` is fairly straightforward, we will start by defining\n# an d-dimensional nonlinear function to minimize,\n# in this case we will use a popular function, the\n# [Griewank function](http://mathworld.wolfram.com/GriewankFunction.html)\n# defined as\n#\n# ```math\n# f(\\mathbf{x}) = \\sum_{i=1}^d \\frac{x_i^2}{4000} - \\prod_{i=1}^d \\cos{\\left(\n# \\frac{x_i}{\\sqrt{i}}\\right)} + 1\n# ```\n#\n# where ``d`` is the dimension of the problem. It's mostly evaluated within the\n# boundaries ``-100 \\leq x_i \\leq 100``, and it has a **minimum** at ``\\mathbf\n# {x^*} = (0, \\cdots, 0)``, and it evaluates to ``f(\\mathbf{x^*}) = 0``.\n#\n# We define the function in `Julia` like this\n\nfunction griewank(x)\n    first_term = sum(x.^2) / 4000\n    ## This variable will hold the result of the product,\n    ## the second term in the function definition from above\n    second_term = 1.0\n    for (idx, val) in enumerate(x)\n        second_term *= cos(val / sqrt(idx))\n    end\n\n    return first_term - second_term + 1.0\nend\n\n# Now, we wish to find the minimum of this function, and fortunately we know the\n# true value so we can compare it later, we can use some of the implementations\n# from `BioMetaheuristics.jl`, for example, [`PSO`](@ref).\n# In this script we have chosen 30 particles within the population, `d` is equal\n# to 20, next we define the boundaries and finally we declare that the algorithm\n# will run for 20000 maximum iterations until it stops, having _converged_.\n\nusing BioMetaheuristics\n\nval = PSO(\n    griewank,\n    Population(35, 10, -600.0, 600.0, rng),\n    20_000,\n    rng\n)\nprintln(val)\n\n# Within a certain tolerance of about ``\\epsilon = 1 \\times 10^{-6}`` we have found\n# the _global_ minimum of the function. We can actually check the value with the\n# evaluation, notice that it actually returns `0`, as expected.\n\ngriewank(val.x)\n\n# ## Nonlinear 2-dimensional global optimization problem\n#\n# Let us now tackle one of the most common optimization problems, which is\n# finding the minimum of the [Rosenbrock function](https://en.wikipedia.org/wiki/Rosenbrock_function)\n# which is a non-convex function, meaning that is does not have just one minimum\n# or stationary point, it has several, so it is a difficult problem for classical\n# optimization algorithms. In this example we will try to solve it using the\n# [`SimulatedAnnealing`](@ref) implementation from `BioMetaheuristics.jl`.\n#\n# First, we define the Rosenbrock function in `Julia`\n\nrosenbrock2d(x) =  (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2;\n\n# We will apply the _Simulated Annealing_ algorithm to find the global optimum\nval = SimulatedAnnealing(\n    rosenbrock2d, -5.0, 5.0, 2, rng; low_temp=10_000\n)\nprintln(val)\n\n# Again, within a certain tolerance we find the expected result which is\n#\n# ```math\n# \\mathbf{x}^{*} = (1, 1)\n# ```\n#\n# and if we account for rounding errors and floating-point arithmetic, we\n# can safely take this result as the best.\n", "meta": {"hexsha": "9527095bd294cff6e25bb3bb52fe127740c93f1a", "size": 3593, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/examples.jl", "max_stars_repo_name": "edwinb-ai/BioMetaheuristics.jl", "max_stars_repo_head_hexsha": "4b3570d446d2c9effef74dfee874aec807f66ac6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-02T02:13:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:54:23.000Z", "max_issues_repo_path": "docs/src/examples/examples.jl", "max_issues_repo_name": "edwinb-ai/BioMetaheuristics.jl", "max_issues_repo_head_hexsha": "4b3570d446d2c9effef74dfee874aec807f66ac6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/src/examples/examples.jl", "max_forks_repo_name": "edwinb-ai/BioMetaheuristics.jl", "max_forks_repo_head_hexsha": "4b3570d446d2c9effef74dfee874aec807f66ac6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.93, "max_line_length": 101, "alphanum_fraction": 0.7161146674, "num_tokens": 1022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.8774767890838837, "lm_q1q2_score": 0.7972911168761114}}
{"text": "using Random: AbstractRNG\nusing Bijectors\nimport Bijectors: logabsdetjac, bijector\nusing Distributions: MultivariateDistribution, Continuous\nimport Distributions: _rand!, _logpdf\nusing StatsFuns\n\n\"\"\"\n    Kipping13()\n\nA non-informative prior for two-parameter limb-darkening coefficients using *triangular sampling* ([Kipping 2013](https://ui.adsabs.harvard.edu/abs/2013MNRAS.435.2152K/)).\n\n# Examples\n\n```jldoctest\njulia> using Random; rng = Random.seed!(10);\n\njulia> rand(rng, Kipping13())\n2-element Vector{Float64}:\n 0.24716310305467298\n 0.08836997249298882\n\njulia> rand(rng, Kipping13(), 5)\n2×5 Matrix{Float64}:\n 0.0664907  0.124817   1.00732    0.806902  0.74165\n 0.520411   0.222718  -0.389412  -0.314755  0.0768429\n```\n\n# References\n\n> [Kipping (2013)](https://ui.adsabs.harvard.edu/abs/2013MNRAS.435.2152K/)\n>\n>   \"Efficient, uninformative sampling of limb darkening coefficients for two-parameter laws\"\n\"\"\"\nstruct Kipping13 <: MultivariateDistribution{Continuous} end\n\nBase.length(::Kipping13) = 2\n\nfunction _rand!(rng::AbstractRNG, ::Kipping13, x::AbstractVector{T}) where T\n    q1, q2 = rand(rng, T, 2)\n    sqrtq1 = sqrt(q1)\n    twoq2 = 2 * q2\n    x[begin] = sqrtq1 * twoq2\n    x[end] = sqrtq1 * (1 - twoq2)\n    return x\nend\n\n_logpdf(::Kipping13, x::AbstractArray{T}) where {T} = zero(T)\n\nstruct Kipping13Transform <: Bijector{1} end\n\nfunction (::Kipping13Transform)(x::AbstractVector)\n    usum = sum(x)\n    q = [usum^2, 0.5 * first(x) / usum]\n    return @. log(q) - log(1 - q)\nend\n\nfunction (::Inverse{<:Kipping13Transform})(y::AbstractVector)\n    tmp = map(logistic, y)\n    sqrtq1 = sqrt(first(tmp))\n    twoq2 = 2 * last(tmp)\n    tmp[begin] = sqrtq1 * twoq2\n    tmp[end] = sqrtq1 * (1 - twoq2)\n    return tmp\nend\n\nlogabsdetjac(::Kipping13Transform, y::Number) = -2 * softplus(-y) - y\nlogabsdetjac(k::Kipping13Transform, y) = sum((yi) -> logabsdetjac(k, yi), y)\nbijector(::Kipping13) = Kipping13Transform()\n", "meta": {"hexsha": "ed644235759237dbf36595f37512bc13300ff541", "size": 1918, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distributions.jl", "max_stars_repo_name": "icweaver/Transits.jl", "max_stars_repo_head_hexsha": "a9b3d871b83cb31f0fa3b927e84611f9400b6ab9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-02-04T19:29:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T10:09:01.000Z", "max_issues_repo_path": "src/distributions.jl", "max_issues_repo_name": "icweaver/Transits.jl", "max_issues_repo_head_hexsha": "a9b3d871b83cb31f0fa3b927e84611f9400b6ab9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2021-02-10T00:25:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T18:12:28.000Z", "max_forks_repo_path": "src/distributions.jl", "max_forks_repo_name": "icweaver/Transits.jl", "max_forks_repo_head_hexsha": "a9b3d871b83cb31f0fa3b927e84611f9400b6ab9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-02-06T23:03:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-16T22:13:59.000Z", "avg_line_length": 27.4, "max_line_length": 171, "alphanum_fraction": 0.6960375391, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.797244337272273}}
{"text": "# From algorithm 3.1\n\nfunction bracket_minimum(f, x=0, s=1e-2, k=2.0)\n\n    a, ya = x, f(x)\n    b, yb = a + s, f(a + s)\n    if yb > ya\n        a, b = b, a\n        ya, yb = yb, ya\n        s = -s\n    end\n    while true\n        c, yc = b + s, f(b + s)\n        if yc > yb\n            return (min(a,c), max(a,c))\n        end\n        a, ya, b, yb = b, yb, c, yc\n        s *= k\n    end\nend\n\n\nfunction test_f(x)\n     return x^3 + 2 * x^2 + x + 3\nend\n\n@time a, b = bracket_minimum(test_f)\n", "meta": {"hexsha": "37fb3b4b921be79462eac224309b15458f2deb60", "size": 479, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "python/optalg/ch3/bracket_minimum.jl", "max_stars_repo_name": "gerritjvv/optimization_algorithms", "max_stars_repo_head_hexsha": "eab2e8fff39eeab8d9be45af3dae3be1a62be3ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/optalg/ch3/bracket_minimum.jl", "max_issues_repo_name": "gerritjvv/optimization_algorithms", "max_issues_repo_head_hexsha": "eab2e8fff39eeab8d9be45af3dae3be1a62be3ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/optalg/ch3/bracket_minimum.jl", "max_forks_repo_name": "gerritjvv/optimization_algorithms", "max_forks_repo_head_hexsha": "eab2e8fff39eeab8d9be45af3dae3be1a62be3ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1071428571, "max_line_length": 47, "alphanum_fraction": 0.4279749478, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.7972443355297018}}
{"text": "# # Munk Gyre analytical solution equations\n# things between #### blocks are the code for checking exact solution in DGmodel test\n\nusing Pkg\nPkg.add(\"Latexify\")\nusing Latexify\nPkg.add(\"Plots\")\nusing Plots\nPkg.add(\"PyPlot\")\npyplot()\n\n# Problem parameters\n# These will come from DG model/problem settings\n###\nτ₀=0.1      # Stress\nρ=1000      # density\nf=1.e-4     # Coriolis\nβ=1.e-11    # Rate of change of Coriolis\nH=1000      # Depth \nL_x=1000.e3 # Zonal extent\nL_y=1000.e3 # Meridional extent\nAh=1000.    # Viscosity\ng=10.       # Gravity\n\nδ_m=(Ah/β)^(1/3) \n####\n\n# Set up Munk formula per https://mitgcm.readthedocs.io/en/latest/examples/examples.html#model-solution\n# Build up using expressions to catch typos\nt1=:( cos((3^0.5*x)/(2*δ_m))+(1)/(3^0.5)*sin((3^0.5*x)/(2*δ_m)) )\ndisplay(latexify(t1))\nt2=:( 1-exp((-x)/(2*δ_m) ) * $t1 )\ndisplay(latexify(t2))\nt3=:( π*sin(π*y/L_y) )\ndisplay(latexify(t3))\nt4=:( τ₀/(ρ*g*H)*(f/β)*(1-x/L_x) )\ndisplay(latexify(t4))\ntfull=:( ($t4) * ($t3) * ($t2) )\ndisplay(latexify(tfull))\ndisplay(tfull)\n\n# Actual function (a copy paste from display(tfull) line)\n#### This is formula needed for checking numerical against exact\nηfun(x,y)=(((τ₀ / (ρ * g * H)) * (f / β) * (1 - x / L_x)) * (π * sin((π * y) / L_y)) * (1 - exp(-x / (2δ_m)) * (cos((3 ^ 0.5 * x) / (2δ_m)) + (1 / 3 ^ 0.5) * sin((3 ^ 0.5 * x) / (2δ_m)))))\n####\n\n# Now make a plot to check\nxvals=collect(0:L_x/100:L_x)\nyvals=collect(0:L_y/100:L_y)\nnx=length(xvals)\nny=length(yvals)\nη=zeros(nx,ny)\nfor j=1:ny\n for i=1:nx\n  η[i,j]=ηfun(xvals[i],yvals[j])\n end\nend\n\n\np2 = contour(xvals, yvals, η')\nplot(p2)\n", "meta": {"hexsha": "33d673ab08eccfdb6a1b140f36c8c6aeeabff670", "size": 1593, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "gyre-exact-solutions/munk-exact.jl", "max_stars_repo_name": "christophernhill/climahacks", "max_stars_repo_head_hexsha": "c5db08e8dcc76204ee21dfed5457599bec31d7f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gyre-exact-solutions/munk-exact.jl", "max_issues_repo_name": "christophernhill/climahacks", "max_issues_repo_head_hexsha": "c5db08e8dcc76204ee21dfed5457599bec31d7f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gyre-exact-solutions/munk-exact.jl", "max_forks_repo_name": "christophernhill/climahacks", "max_forks_repo_head_hexsha": "c5db08e8dcc76204ee21dfed5457599bec31d7f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6935483871, "max_line_length": 188, "alphanum_fraction": 0.6258631513, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582426, "lm_q2_score": 0.8577681068080748, "lm_q1q2_score": 0.7972443338928811}}
{"text": "\nfunction swiss_roll(n, σ = 0.1)\n    # x = rand(n) .* (3.0 * π) .+ (1.5 * π)\n    # y = rand(n) .* (30.0 * π)\n\n    ### 1\n    # f = permutedims([(x, y) -> x .* cos.(x),\n    #                  (x, y) -> y,\n    #                  (x, y) -> x .* sin.(x) ])\n    # broadcast((f, x, y) -> f(x, y), f, x, y)\n\n    ### 2\n    # f = ((x, y) -> x .* cos.(x),\n    #      (x, y) -> y,\n    #      (x, y) -> x .* sin.(x) )\n    # for i in axis(res, 1), j in axis(res, 2)\n    #     res[i, j] = ff[j](x[i], y[i])\n    # end\n    # return res\n\n    ### 3\n    # res = Array{Float64, 2}(undef, n, 3)\n    # f1(x, y) = x .* cos.(x)\n    # f2(x, y) = y\n    # f3(x, y) = x .* sin.(x)\n    # res[:, 1] .= f1.(x, y) .+ randn(n) .* σ\n    # res[:, 2] .= f2.(x, y) .+ randn(n) .* σ\n    # res[:, 3] .= f3.(x, y) .+ randn(n) .* σ\n    # return res\n\n    ### 4\n    # hcat(x .* cos.(x), y, x .* sin.(x));\n\n    ### 5\n    # f(x, y) = (x * cos(x), y, x * sin(x))\n    # permutedims(reshape(reinterpret(Float64, f.(x, y)), (3, n)))\n\n    xx() = rand() .* (3.0 * π) .+ (1.5 * π)\n    yy() = rand() .* (30.0 * π)\n\n    permutedims(reshape(reinterpret(Float64, [\n        begin\n            x = xx()\n            y = yy()\n            (x * cos(x), y, x * sin(x))\n        end for i in 1:n\n    ]), (3, n)))\nend\n\nfunction circles(n, σ = 0.1, factor = 0.8)\n    res = Array{Float64, 2}(undef, n, 2)\n\n    classes = rand(Bool, n)\n    ff = classes .* factor\n    res[:, 1] .= cos.(range(0, stop = 2 * π, length = n)) .* ff\n    res[:, 2] .= sin.(range(0, stop = 2 * π, length = n)) .* ff\n\n    res .+= randn(size(res)...) .* σ\n    res, classes\nend\n", "meta": {"hexsha": "41d5fa543f8c2185a9a451cf4813b25cace1990e", "size": 1578, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/datasets.jl", "max_stars_repo_name": "gdkrmr/MLKernelsMissing.jl", "max_stars_repo_head_hexsha": "fe6b98d48be7be86d2f7f000cfa8407d37f43199", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/datasets.jl", "max_issues_repo_name": "gdkrmr/MLKernelsMissing.jl", "max_issues_repo_head_hexsha": "fe6b98d48be7be86d2f7f000cfa8407d37f43199", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/datasets.jl", "max_forks_repo_name": "gdkrmr/MLKernelsMissing.jl", "max_forks_repo_head_hexsha": "fe6b98d48be7be86d2f7f000cfa8407d37f43199", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.868852459, "max_line_length": 66, "alphanum_fraction": 0.3770595691, "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7972443305267081}}
{"text": "function luhntest(x::Integer)\n    d = reverse(digits(x))\n    s = sum(d[1:2:end])\n    s += sum(sum.(digits.(2d[2:2:end])))\n    return s % 10 == 0\nend\n\nfor card in [49927398716, 49927398717, 1234567812345678, 1234567812345670]\n    println(luhntest(card) ? \"PASS \" : \"FAIL \", card)\nend\n", "meta": {"hexsha": "2f59f715de6c6f35971af8b02c7043dded6672be", "size": 283, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/luhn-test-of-credit-card-numbers-2.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/luhn-test-of-credit-card-numbers-2.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/luhn-test-of-credit-card-numbers-2.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7272727273, "max_line_length": 74, "alphanum_fraction": 0.6325088339, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.7972443271473163}}
{"text": "import Pkg; Pkg.add(Pkg.PackageSpec(url=\"https://github.com/JuliaComputing/JuliaAcademyData.jl\"))\nusing JuliaAcademyData; activate(\"Foundations of machine learning\")\n\n# ## What is learning?\n#\n# Computers read data, as we saw in notebooks 1 and 2. We can then build functions that model that data to make decisions, as we saw in notebooks 3 and 5.\n#\n# But how do you make sure that the model actually fits the data well? In the last notebook, we saw that we can fiddle with the parameters of our function defining the model to reduce the loss function. However, we don't want to have to pick the model parameters ourselves. Choosing parameters ourselves works *well enough* when we have a simple model and only a few data points, but can quickly become extremely complex for more detailed models and larger data sets.\n#\n# Instead, we want our machine to *learn* the parameters that fit the model to our data, without needing us to fiddle with the parameters ourselves. In this notebook, we'll talk about the \"learning\" in machine learning.\n\n#-\n\n# ### Motivation: Fitting parameters by hand\n#\n# Let's go back to our example of fitting parameters from notebook 3. Recall that we looked at whether the amount of green in the pictures could distinguish between an apple and a banana, and used a sigmoid function to model our choice of \"apple or banana\" using the amount of green in an image.\n\nusing Plots; gr()\nusing Images, Statistics\n\nσ(x,w,b) = 1 / (1 + exp(-w*x+b))\n\napple =  load(datapath(\"data/10_100.jpg\"))\nbanana = load(datapath(\"data/104_100.jpg\"))\napple_green_amount =  mean(Float64.(green.(apple)))\nbanana_green_amount = mean(Float64.(green.(banana)));\n\nw = 10.0 # Try manipulating w between 0 and 30 to see how the plot changes\nb = 15.0 # Try manipulating b bewteen 0 and 30\n\nplot(x->σ(x,w,b), 0, 1, label=\"Model\", legend = :topleft, lw=3)\nscatter!([apple_green_amount],  [0.0], label=\"Apple\")\nscatter!([banana_green_amount], [1.0], label=\"Banana\")\n\n# Intuitively, how did you tweak the sliders so that way the model sends apples to 0 and bananas to 1? Most likely, you did the following:\n#\n# #### Move the sliders a bit, see whether the curve moves in the right direction, and if it did, keep doing it.\n#\n# For a machine, \"learning\" is that same process, translated into math!\n\n#-\n\n# ## \"Learning by nudging\": The process of descent\n#\n# Let's start to formalize this idea. In order to push the curve in the \"right direction\", we need some measurement of \"how right\" and \"how wrong\" the model is. When we translate the idea of a \"right direction\" into math, we end up with a **loss function**, `L(w, b)`, as we saw in notebook 5. We say that the loss function is lowest when the model `σ(x, w, b)` performs the best.\n#\n# Now we want to create a loss function that is the lowest when the apple is at `0` and the banana is at `1`. If the data (the amount of green) for our apple is $x_1$, then our model will output $σ(x_1,w, b)$ for our apple. So, we want the difference $0 - σ(x_1, w, b)$ to be small. Similarly, if our data for our banana (the banana's amount of green) is $x_2$, we want the difference $1 - σ(x_2, w, b)$ to be small.\n#\n# To create our loss function, let's add together the squares of the difference of the model's output from the desired output for the apple and the banana. We get\n#\n# $$ L(w,b) = (0 - σ(x_1, w, b))^2 + (1 - σ(x_2, w, b))^2. $$\n#\n# $L(w, b)$ is lowest when it outputs `0` for the apple and `1` for the banana, and thus the cost is lowest when the model \"is correct\".\n#\n# We can visualize this function by plotting it in 3D with the `surface` function or in 2D with contour lines\n\n## plotly() # The plotly backend is nice for 3d surface plots\ngr() # The GR backend is good for faster interactive plots\n\n#-\n\nL(w, b) = (0 - σ(apple_green_amount,w,b))^2 + (1 - σ(banana_green_amount,w,b))^2\n\nw_range = 10:0.1:13\nb_range = 0:1:20\n\nL_values = [L(w,b) for b in b_range, w in w_range]\n\n\nw = 11.5 # Try manipulating w with values from w_range (between 10 and 13)\nb = 10 # Try manipulating b with values from b_range (between 0 and 20)\n##     p1 = surface(w_range, b_range, L_values, xlabel=\"w\", ylabel=\"b\", cam=(70,40), cbar=false, leg=false)\n##     scatter!(p1, [w], [b], [L(w,b)+1e-2], markersize=5, color = :blue)\np1 = contour(w_range, b_range, L_values, levels=0.05:0.1:1, xlabel=\"w\", ylabel=\"b\", cam=(70,40), cbar=false, leg=false)\nscatter!(p1, [w], [b], markersize=5, color = :blue)\n\np2 = plot(x->σ(x,w,b), 0, 1, label=\"Model\", legend = :topleft, lw=3)\nscatter!(p2, [apple_green_amount],  [0.0], label=\"Apple\", markersize=10)\nscatter!(p2, [banana_green_amount], [1.0], label=\"Banana\", markersize=10, xlim=(0,1), ylim=(0,1))\nplot(p1, p2, layout=(2,1))\n\n# The blue ball on the 3D plot shows the current parameter choices, plotted as `(w,b)`. Shown below the 3D plot is a 2D plot of the corresponding model with those parameters. Notice that as the blue ball rolls down the hill, the model becomes a better fit. Our loss function gives us a mathematical notion of a \"hill\", and the process of \"learning by nudging\" is simply rolling the ball down that hill.\n\n#-\n\n# To do this mathematically, we need to know which direction is \"downhill\". Recall from calculus that the derivative of `L` with respect to `b` tells you how `L` changes when `b` changes. Thus to roll downhill, we should go in the direction where the derivative is negative (the function goes down) for each parameter. This direction is the negative of what's called the **gradient**, $\\nabla L$. This means that the \"learn by nudging method\" can be rephrased in mathematical terms as:\n#\n# 1. Calculate the gradient\n# 2. Move a little bit in the direction of the negative gradient\n# 3. Repeat\n#\n# This process of rolling the ball in the direction of the negative gradient is called **gradient descent**; written mathematically, it is\n#\n# $$p_{n+1} = p_n - \\eta \\nabla L(p_n).$$\n#\n# Here, $p_n$ represents the vector of current parameters $(w, b)$; $\\nabla L(p_n)$ is the gradient of the loss function, given those parameters. We start from $p_n$ and change it by $\\eta \\nabla L(p_n)$, where $\\eta$ is a small step size that determines how far we move the parameters in the direction of the negative gradient; notice that if you step too far, you'll overshoot the minimum!. The result is $p_{n+1}$, the new vector of parameters.\n#\n# [Picture of Gradient Descent Vectors]\n#\n# If we repeat this process, then we will end up at parameters where the model correctly labels apples as `0` and bananas as `1`. When this happens, the model has learned from the data and can then read pictures and tell you whether they are apples or bananas!\n\n#-\n\n# #### Exercise 1\n#\n# Use the following terms to fill in the sentences below. Terms may be used more than once or not at all:\n# > gradient, loss function, derivative, gradient descent, learning.\n#\n# * We can think of a _(A)_ as a 1D version of a _(B)_.\n# * We can visualize a _(C)_ as a hill.\n# * In the explanation above, rolling downhill is called _(D)_ and means traveling along the _(E)_.\n# * To quantify the correctness of a model we use a _(F)_.\n# * When our program can minimize a _(G)_ on its own, we say it is _(H)_.\n#\n# <br><br>\n#\n# A)<br>\n# B)<br>\n# C)<br>\n# D)<br>\n# E)<br>\n# F)<br>\n# G)<br>\n# H)<br>\n\n#-\n\n# #### Solution\n#\n# A) derivative <br>\n# B) gradient <br>\n# C) loss function <br>\n# D) gradient descent <br>\n# E) gradient <br>\n# F) loss function <br>\n# G) loss function<br>\n# H) learning<br>\n\n", "meta": {"hexsha": "0c2a61ad40be20aa3686814859e922ab77010c97", "size": 7451, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Foundations of machine learning/0900.What-is-learning.jl", "max_stars_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_stars_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2020-02-13T00:50:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T07:57:22.000Z", "max_issues_repo_path": "Courses/Foundations of machine learning/0900.What-is-learning.jl", "max_issues_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_issues_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2019-10-30T16:22:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-26T20:02:43.000Z", "max_forks_repo_path": "Courses/Foundations of machine learning/0900.What-is-learning.jl", "max_forks_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_forks_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2020-02-26T11:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T22:34:53.000Z", "avg_line_length": 53.6043165468, "max_line_length": 485, "alphanum_fraction": 0.7115823379, "num_tokens": 2107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467158, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7972206038195137}}
{"text": "function pagerank(\n    g::AbstractGraph{U}, \n    α=0.85, \n    n=100::Integer, \n    ϵ=1.0e-6\n    ) where U <: Integer\n    \n    # indegree(g, v) is estimated run-time to iterate over inneighbors(g, v)\n    partitions = LightGraphs.optimal_contiguous_partition(indegree(g), nthreads(), nv(g))\n\n    α_div_outdegree = Vector{Float64}(undef,nv(g))\n    dangling_nodes = Vector{U}()\n    @inbounds for v in vertices(g)\n        if outdegree(g, v) == 0\n            push!(dangling_nodes, v)\n        end\n        α_div_outdegree[v] = (α/outdegree(g, v))\n    end\n\n    nvg = Int(nv(g))\n    # solution vector and temporary vector\n    x = fill(1.0 / nvg, nvg)\n    xlast = copy(x)\n    @inbounds for _ in 1:n\n        dangling_sum = 0.0\n        for v in dangling_nodes\n            dangling_sum += x[v]\n        end\n        # flow from teleprotation\n        y = (1 - α + α * dangling_sum) * (1.0 / nvg)\n        xlast .= y\n        # flow from edges\n        let x = x\n            @threads for v_set in partitions\n                for v in v_set\n                    for u in inneighbors(g, v)\n                        xlast[v] += (x[u] * α_div_outdegree[u])\n                    end\n                end\n            end\n        end\n\n        # l1 change in solution convergence criterion\n        err = 0.0\n        for v in vertices(g)\n            err += abs(xlast[v] - x[v])\n            x[v] = xlast[v]\n        end\n        if (err < nvg * ϵ)\n            return x\n        end\n    end\n    error(\"Pagerank did not converge after $n iterations.\") # TODO 0.7: change to InexactError with appropriate msg.\nend\n", "meta": {"hexsha": "7090f74ef6da29c5aafa9059afda8548be83d8be", "size": 1572, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Parallel/centrality/pagerank.jl", "max_stars_repo_name": "blepabyte/LightGraphs.jl", "max_stars_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 745, "max_stars_repo_stars_event_min_datetime": "2015-03-19T03:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-07T00:59:06.000Z", "max_issues_repo_path": "src/Parallel/centrality/pagerank.jl", "max_issues_repo_name": "blepabyte/LightGraphs.jl", "max_issues_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1491, "max_issues_repo_issues_event_min_datetime": "2015-03-19T17:04:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T14:47:57.000Z", "max_forks_repo_path": "src/Parallel/centrality/pagerank.jl", "max_forks_repo_name": "blepabyte/LightGraphs.jl", "max_forks_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 288, "max_forks_repo_forks_event_min_datetime": "2015-04-04T14:31:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T10:37:21.000Z", "avg_line_length": 28.5818181818, "max_line_length": 116, "alphanum_fraction": 0.5209923664, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9591542829224748, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7971944120686716}}
{"text": "# Exploration of Boos Stanski Chapter 1 - consulting example\n\n# You are trying to model maximum flooding level Q\n# while A is floodplane\n# and k and η are parameters to be estimated\n\n# literature suggests over 100 years the maximum level is:\nQ(k, A, η) = k * A^(η - 1)\n\n# Take the log to linearlize\nlogQ(k, A, η) = log(k) + (η - 1)*log(A)\n\n# Verify\nround(logQ(5, 100, .5), digits=5) == round(log(Q(5, 100, .5)), digits=5)\n\n# The problem is that we don't actually see any observation which spans 100 years\n\n# Example is of 140 gauging stations - 140 areas\n# Stations have between 6 and 83 years of observations.\n\n# The expected value E for subset of observations X₁ which is smaller than subset\n# X₂ which is smaller than the full set X₁₀₀ is going to have the following property:\n# E(max(X₁)) < E(max(X₂)) < E(max(X₁₀₀))\n\n# What we would like to know is max(X₁₀₀)\n\n# But the maximum of any of our observed values will be biased downwards since we\n# never observe 100 years.\n\n# Authors suggest using an estimate of the the joint likelihood that any observation\n# will be below the median using the following identity allowing unobserved and observed\n# X_i through X_100 to be ordered\n# P(X_100 ≤ t) = P(X_1 ≤, ... X_100 ≤ t) = Π P(X_i < t) = [F(t)]^100\n# by iid P(X_100 ≤ t) => [F(t)]^100\n\n# P(X_100 ≤ t) = [F(t)]^100 = 1/2\n# → P(X_100 ≤ t) = F(t₀) = (1/2)^.01 → t₀ = .993\n\n\n# Using Extreme value function\n# P(X_i <= t) = exp(-exp(-(t-μ)/σ))\n\nQ993(μ, σ) = σ*(-log(-log(.993))) + μ\n\n# The Authors suggest that we can estimate μ and σ then plug them into the function\n# to get the solution.\n\n# lets try it\n\nusing Random, Distributions\n\nwaterlevel = rand(Poisson(50), 100)\nobserve = rand(Binomial(1, .25), 100)\n\nμhat = mean(waterlevel[observe .== 1])\nσhat = var(waterlevel[observe .== 1])^.5\n\nQ993(μhat, σhat)\nmaximum(waterlevel)\n", "meta": {"hexsha": "b11d407f0ef5038002de40bd33a30f717342b83a", "size": 1826, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "simulations/extremevalue.jl/BoosStefanski2016.jl", "max_stars_repo_name": "EconometricsBySimulation/StatisticalSimulations.jl", "max_stars_repo_head_hexsha": "dcc98e75d26a3e653efb81e6d1f6d4592fd5d600", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulations/extremevalue.jl/BoosStefanski2016.jl", "max_issues_repo_name": "EconometricsBySimulation/StatisticalSimulations.jl", "max_issues_repo_head_hexsha": "dcc98e75d26a3e653efb81e6d1f6d4592fd5d600", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulations/extremevalue.jl/BoosStefanski2016.jl", "max_forks_repo_name": "EconometricsBySimulation/StatisticalSimulations.jl", "max_forks_repo_head_hexsha": "dcc98e75d26a3e653efb81e6d1f6d4592fd5d600", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4333333333, "max_line_length": 88, "alphanum_fraction": 0.6834611172, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542794197472, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7971944071515316}}
{"text": "# D(u)_function.jl\n\n\"\"\"\nImplementation of FHIP's susceptibility formula D(u) for the Optical Absorption of Polarons.\n\nSee FHIP 1962, equation (35c):\nhttps://link.aps.org/doi/10.1103/PhysRev.127.1004.\n\"\"\"\n\n\"\"\"\nℜD(x::Float64, y::Float64, v::Float64, w::Float64, β::Float64)\n\n    Calculate the real part of D(u) (equation (35c) in FHIP) for a complex argument u = x + iy. v and w are the variational Polaron parameters that minimise the free energy, for the supplied α Frohlich coupling. β is the reduced thermodynamical beta = ħω/kT with k being Boltzman's constant.\n\"\"\"\nfunction ℜD(x, y, v, w, β)\n    x = BigFloat(x)\n    y = BigFloat(y)\n    β = BigFloat(β)\n    v = BigFloat(v)\n    w = BigFloat(w)\n\n    R = (v^2 - w^2) / (w^2 * v)\n    a_squared = β^2 / 4 + R * β * coth(β * v / 2)\n    b = R * β / sinh(β * v / 2)\n\n    w^2 * (a_squared - β^2 / 4 - b * cos(v * x) * cosh(v * (y - β / 2)) + x^2 + y * (β - y)) / (β * v^2)\nend\n\n\"\"\"\nℑD(x::Float64, y::Float64, v::Float64, w::Float64, β::Float64)\n\n    Calculate the imaginary part of D(u) (equation (35c) in FHIP) for a complex argument u = x + iy. v and w are the variational Polaron parameters that minimise the free energy, for the supplied α Frohlich coupling. β is the reduced thermodynamical beta = ħω/kT with k being Boltzman's constant.\n\"\"\"\nfunction ℑD(x, y, v, w, β)\n    x = BigFloat(x)\n    y = BigFloat(y)\n    β = BigFloat(β)\n    v = BigFloat(v)\n    w = BigFloat(w)\n\n    R = (v^2 - w^2) / (w^2 * v)\n    a_squared = β^2 / 4 + R * β * coth(β * v / 2)\n    b = R * β / sinh(β * v / 2)\n\n    w^2 * (b * sin(v * x) * sinh(v * (y - β / 2)) + 2 * x * (y - β / 2)) / (β * v^2)\nend\n\n# Create a complex number from the real and imaginary parts of D(u).\n\nD(x, y, v, w, β) = ℜD(x, y, v, w, β) + 1im * ℑD(x, y, v, w, β)\n", "meta": {"hexsha": "00680f1453d602e5100d49aabd0a54f4bb027f3f", "size": 1757, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polaronmakie/D(u)_function.jl", "max_stars_repo_name": "Neutrino155/PolaronPathIntegrals.jl", "max_stars_repo_head_hexsha": "ed17579530069fb1f8f064a151b933267be8f973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-30T22:38:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T11:00:29.000Z", "max_issues_repo_path": "src/polaronmakie/D(u)_function.jl", "max_issues_repo_name": "Neutrino155/PolaronPathIntegrals.jl", "max_issues_repo_head_hexsha": "ed17579530069fb1f8f064a151b933267be8f973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polaronmakie/D(u)_function.jl", "max_forks_repo_name": "Neutrino155/PolaronPathIntegrals.jl", "max_forks_repo_head_hexsha": "ed17579530069fb1f8f064a151b933267be8f973", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4509803922, "max_line_length": 296, "alphanum_fraction": 0.5873648264, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654263, "lm_q2_score": 0.8558511543206819, "lm_q1q2_score": 0.7971932601666791}}
{"text": "\nabstract type actFun end\n\nexport actFun\n\n\n\nexport probToValue\n\n\n### sigmoid\n\nabstract type σ <: actFun end\n\n\"\"\"\n    return the Sigmoid output\n    inputs must be matices\n\"\"\"\nσ(X, W, B) = 1 ./ (1 .+ exp.(.-(W * X .+ B)))\nσ(Z) = 1 ./ (1 .+ exp.(.-Z))\n\nexport σ\n\n\"\"\"\n    return the derivative of Sigmoid function\n\"\"\"\ndσ(Z) = σ(Z) .* (1 .- σ(Z))\n\nexport dσ\n\n@doc raw\"\"\"\n    function probToValue(\n        actFun::Type{σ},\n        probs::AbstractArray{T,N},\n        labels::Aa = nothing;\n        evalConst = 0.5,\n    ) where {Aa<:Union{<:AbstractArray,Nothing},T,N}\n\nConvert the probabilities return out of sigmoid function to Bool value (i.e. 0,1) values based on comparing on a threshold value `evalConst`\n\n# Return\n\n- `Ŷ_bool` := Boolean valuse of the probabilites\n\n- `acc` := Accuracy when `labels` provided\n\"\"\"\nfunction probToValue(\n    actFun::Type{σ},\n    probs::AbstractArray{T,N},\n    labels::Aa = nothing;\n    evalConst = 0.5,\n) where {Aa<:Union{<:AbstractArray,Nothing},T,N}\n\n    s = size{probs}\n    Ŷ_bool = probs .> T(evalConst)\n    acc = nothing\n    if labels isa AbstractArray\n        acc = sum(Ŷ_bool .== labels) / (s[end-1] * s[end])\n        # println(\"Accuracy = $acc\")\n    end\n    return Ŷ_bool, acc\nend #predictpredict(probs::AbstractArray{T, 2},\n\n\n### relu\n\nabstract type relu <: actFun end\n\n\n\"\"\"\n    return the ReLU output\n\"\"\"\nfunction relu(Z::AbstractArray{T,N}) where {T,N}\n    max.(zero(T), Z)\nend #function relu(Z::AbstractArray{T,N}) where {T,N}\n\nexport relu\n\n\"\"\"\n    return the derivative of ReLU function\n\"\"\"\nfunction drelu(Z::AbstractArray{T,N}) where {T,N}\n    return T.(Z .> zero(T))\nend #function drelu(z::AbstractArray{T,N}) where {T,N}\n\nexport drelu\n\n\n\n### softmax\n\n\nabstract type softmaxFamily <: actFun end\n\nabstract type softmax <: softmaxFamily end\n\n\"\"\"\n    compute the softmax function\n\n\"\"\"\nfunction softmax(Ŷ::AbstractArray{T,N}) where {T,N}\n    Ŷ_exp = exp.(Ŷ)\n    sumofexp = sum(Ŷ_exp, dims = N - 1)\n    return Ŷ_exp ./ sumofexp\nend #softmax\n\nfunction dsoftmax(Ŷ, dim = 1)\n    sŶ = softmax(Ŷ)\n    T = eltype(Ŷ)\n    softMat = AbstractArray{T,3}(undef, 0, 0, 0)\n    sSize = size(Ŷ)[dim]\n    for c in eachcol(sŶ)\n        tmpMat = zeros(T, sSize, sSize)\n        for i = 1:length(c)\n            for j = 1:length(c)\n                if i == j\n                    tmpMat[i, j] = c[i] * (1 - c[j])\n                else\n                    tmpMat[i, j] = -c[i] * c[j]\n                end\n            end\n        end\n        softMat = cat(softMat, tmpMat, dims = 3)\n    end\n\n    return softMat\nend #dsoftmax\n\nexport softmax, dsoftmax\n\n@doc raw\"\"\"\n    function probToValue(\n        actFun::Type{S},\n        probs::AbstractArray{T,N};\n        labels = nothing,\n    ) where {T,N,S<:softmaxFamily}\n\nconvert the probabilites out of `softmax` or softmax-like functions into `Bool` values, where the max value gets 1 and the other get zeros\n\n# Return\n\n- `Ŷ_bool` := Boolean valuse of the probabilites\n\n- `acc` := Accuracy when `labels` provided\n\"\"\"\nfunction probToValue(\n    actFun::Type{S},\n    probs::AbstractArray{T,N};\n    labels = nothing,\n) where {T,N,S<:softmaxFamily}\n\n    maximums = maximum(probs, dims = N - 1)\n    Ŷ_bool = probs .== maximums\n    acc = nothing\n    if labels isa AbstractArray\n        acc = 0\n        bool_labels = Bool.(labels)\n        ax = axes(bool_labels)[1:end-1]\n        endax = axes(bool_labels)[end]\n        trueFalse = Array{Bool,1}(undef, length(endax))\n        @simd for i in endax\n            lab = view(bool_labels, ax..., i)\n            pred = view(Ŷ_bool, ax..., i)\n            trueFalse[i] = (lab == pred)\n        end\n        acc = mean(trueFalse)\n        # println(\"Accuracy = $acc\")\n    end\n\n\n    return Ŷ_bool, acc\nend #predictpredict(probs::AbstractArray{T, 2}, :softmax)\n\n\n### tanh\n\nabstract type tanh <: actFun end\n\n\nBase.tanh(Z::AbstractArray{T,N}) where {T,N} = Base.tanh.(Z)\n\ntanh(Z::AbstractArray{T,N}) where {T,N} = Base.tanh.(Z)\n\ndtanh(Z::AbstractArray{T,N}) where {T,N} = 1 .- (Base.tanh.(Z)) .^ 2\n\nexport dtanh, tanh\n\n\n### noAct\n\n\nabstract type noAct <: actFun end\n\nfunction noAct(Z)\n    return Z\nend\n\nfunction dnoAct(Z)\n    return ones(eltype(Z), size(Z)...)\nend\n\nexport noAct, dnoAct\n", "meta": {"hexsha": "ea0c309c41f05dc80dae13d55b3a975ce74eb87a", "size": 4180, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/actFuns.jl", "max_stars_repo_name": "MohHizzani/NumNN.jl", "max_stars_repo_head_hexsha": "1a753a20cc2bcd8bde789aa12d7fbb1b31506512", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-04-15T13:45:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T11:43:26.000Z", "max_issues_repo_path": "src/actFuns.jl", "max_issues_repo_name": "MohHizzani/NumNN.jl", "max_issues_repo_head_hexsha": "1a753a20cc2bcd8bde789aa12d7fbb1b31506512", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/actFuns.jl", "max_forks_repo_name": "MohHizzani/NumNN.jl", "max_forks_repo_head_hexsha": "1a753a20cc2bcd8bde789aa12d7fbb1b31506512", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5911330049, "max_line_length": 140, "alphanum_fraction": 0.5942583732, "num_tokens": 1284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7971932599145857}}
{"text": "\"\"\"\n    horner(coefficients, x)\n\nEvaluate the given polynomial at position x using the Horner scheme.\n\n```math\np(x) = \\\\sum_{n=0}^N c_n x^n\n```\n\"\"\"\nfunction horner(coefficients::Vector{T}, x::Number) where T<:Number\n    bn = coefficients[end]\n    for n=length(coefficients)-1:-1:1\n        bn = coefficients[n] + bn*x\n    end\n    bn\nend\n\n\nmodule hermite\n\n\"\"\"\n    a_nk(N)\n\nCalculate the all coefficients for all Hermite polynomials up to order N.\n\n```math\nH_n(x) = \\\\sum_{k=0}^n a_{n,k} x^k\n```\n\nReturns a vector of length N+1 where the n-th entry contains all coefficients\nfor the n-th Hermite polynomial.\n\"\"\"\nfunction a(N::Int)\n    a = Vector{Vector{Int}}(undef, N+1)\n    a[1] = [1]\n    a[2] = [0,2]\n    am = a[2]\n    for n=2:N\n        an = zeros(Int, n+1)\n        a[n+1] = an\n        if iseven(n)\n            an[1] = -am[2]\n        end\n        an[n+1] = 2*am[n]\n        if iseven(n)\n            for k=3:2:n-1\n                an[k] = 2*am[k-1] - am[k+1]*k\n            end\n        else\n            for k=2:2:n-1\n                an[k] = 2*am[k-1] - am[k+1]*k\n            end\n        end\n        am = an\n    end\n    a\nend\n\n\"\"\"\n    A_nk(N)\n\nCalculate the all scaled coefficients for all Hermite polynomials up to order N.\n\nThe scaled coefficients `A` are connected to the unscaled coefficients `a` by\nthe relation ``A_{n,k} = \\\\frac{a_{n,k}}{\\\\sqrt{2^n n!}}``\n\nReturns a vector of length N+1 where the n-th entry contains all scaled\ncoefficients for the n-th Hermite polynomial.\n\"\"\"\nfunction A(N)\n    A = Vector{Vector{Float64}}(undef, N+1)\n    A[1] = [1.]\n    A[2] = [0., sqrt(2)]\n    Am = A[2]\n    for n=2:N\n        An = zeros(Float64, n+1)\n        A[n+1] = An\n        if iseven(n)\n            An[1] = -Am[2]/sqrt(2*n)\n        end\n        An[n+1] = Am[n]*sqrt(2/n)\n        if iseven(n)\n            for k=3:2:n-1\n                An[k] = Am[k-1]*sqrt(2/n) - Am[k+1]*k/sqrt(2*n)\n            end\n        else\n            for k=2:2:n-1\n                An[k] = Am[k-1]*sqrt(2/n) - Am[k+1]*k/sqrt(2*n)\n            end\n        end\n        Am = An\n    end\n    A\nend\n\nend # module hermite\n", "meta": {"hexsha": "35b9356a3bdafd932f3142483d98cbf512bf522a", "size": 2077, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polynomials.jl", "max_stars_repo_name": "PhilipVinc/QuantumOpticsBase.jl", "max_stars_repo_head_hexsha": "122ce91cadedfa8bd47528517c845cd715c60271", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polynomials.jl", "max_issues_repo_name": "PhilipVinc/QuantumOpticsBase.jl", "max_issues_repo_head_hexsha": "122ce91cadedfa8bd47528517c845cd715c60271", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polynomials.jl", "max_forks_repo_name": "PhilipVinc/QuantumOpticsBase.jl", "max_forks_repo_head_hexsha": "122ce91cadedfa8bd47528517c845cd715c60271", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.412371134, "max_line_length": 80, "alphanum_fraction": 0.5113143958, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7971932568259916}}
{"text": "\"\"\"\r\n    metnum.jl\r\n\r\nModul ini berisi metode untuk menyelesaikan\r\n\r\n1. Akar pertaksamaan tak-linear: `bisection`, `regulaFalsi`, `fixpoint`, `newtonRaphson`, `secant`\r\n2. SPL langsung: `backsub`, `elimGaussNonPivoting`, `elimGaussWithPivoting`, `LUtanpaP`, `LUdenganP`\r\n3. SPL iteratif: `jacobi`, `gaussSeidel`, `rekons` ,`conGrad`\r\n4. Interpolas: `lagrange`, `newton`\r\n5. Regresi: `reglin`, `regpower`, `regpoly`\r\n6. Turunan: `bedaPusat`, `richardson`\r\n7. Integral: `komptrap`, `kompsimp`, `rekursif`, `romberg`, `adaptif`\r\n8. PDB dengan MNA: `euler`, `heun`, `taylor`, `rungekutta`, `rungekuttasistem`, `rkf45`\r\n9. PDB dengan MNB: `linearshooting`, `findiff`\r\n10. PDP: `gelombang`, `panas`, `dirichlet`\r\n\"\"\"\r\nmodule metnum\r\n\r\nusing LinearAlgebra\r\nusing Statistics\r\nusing Dates\r\nusing IJulia\r\n\r\nexport regpoly, regpower, regulaFalsi, rekons, rekursif, richardson, rkf45\r\nexport romberg, rungekutta, rungekuttasistem, secant\r\nexport taylor, adaptif, backsub, bedaPusat, bisection\r\nexport conGrad, dirichlet, elimGaussNonPivoting, elimGaussWithPivoting\r\nexport euler, findiff, fixpoint, gaussSeidel, gelombang, heun, jacobi\r\nexport kompsimp, komptrap, lagrange, linearshooting, LUdenganP, LUtanpaP\r\nexport newton, newtonRaphson, panas, reglin, mulaipraktikum\r\n\r\ninclude(\"regpoly.jl\")\r\ninclude(\"regpower.jl\")\r\ninclude(\"regulaFalsi.jl\")\r\ninclude(\"rekons.jl\")\r\ninclude(\"rekursif.jl\")\r\ninclude(\"richardson.jl\")\r\ninclude(\"rkf45.jl\")\r\ninclude(\"romberg.jl\")\r\ninclude(\"rungekutta.jl\")\r\ninclude(\"rungekuttasistem.jl\")\r\ninclude(\"secant.jl\")\r\ninclude(\"taylor.jl\")\r\ninclude(\"adaptif.jl\")\r\ninclude(\"backsub.jl\")\r\ninclude(\"bedaPusat.jl\")\r\ninclude(\"bisection.jl\")\r\ninclude(\"conGrad.jl\")\r\ninclude(\"dirichlet.jl\")\r\ninclude(\"elimGaussNonPivoting.jl\")\r\ninclude(\"elimGaussWithPivoting.jl\")\r\ninclude(\"euler.jl\")\r\ninclude(\"findiff.jl\")\r\ninclude(\"fixpoint.jl\")\r\ninclude(\"gaussSeidel.jl\")\r\ninclude(\"gelombang.jl\")\r\ninclude(\"heun.jl\")\r\ninclude(\"jacobi.jl\")\r\ninclude(\"kompsimp.jl\")\r\ninclude(\"komptrap.jl\")\r\ninclude(\"lagrange.jl\")\r\ninclude(\"linearshooting.jl\")\r\ninclude(\"LUdenganP.jl\")\r\ninclude(\"LUtanpaP.jl\")\r\ninclude(\"newton.jl\")\r\ninclude(\"newtonRaphson.jl\")\r\ninclude(\"panas.jl\")\r\ninclude(\"reglin.jl\")\r\ninclude(\"mulaipraktikum.jl\")\r\n\r\nend\r\n", "meta": {"hexsha": "799ba49efee91347fdb012510bbcbea44d960ea0", "size": 2215, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/metnum.jl", "max_stars_repo_name": "mkhoirun-najiboi/metnum.jl", "max_stars_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/metnum.jl", "max_issues_repo_name": "mkhoirun-najiboi/metnum.jl", "max_issues_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/metnum.jl", "max_forks_repo_name": "mkhoirun-najiboi/metnum.jl", "max_forks_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7638888889, "max_line_length": 101, "alphanum_fraction": 0.7295711061, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7971932564898668}}
{"text": "#   Unit \"tools\" of the FourierAnalysis Package for julia language\n#\n#   MIT License\n#   Copyright (c) 2019, Marco Congedo, CNRS, Grenobe, France:\n#   https://sites.google.com/site/marcocongedo/home\n\n# ? CONTENTS :\n#   This unit implements useful functions for Fourier analysis.\n\n#   ~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~  #\n#                                                                             #\n#   ~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~  #\n\n\"\"\"\n```\nfunction sinusoidal(a :: IntOrReal,\n                    f :: IntOrReal,\n                   sr :: Int,\n                    t :: Int,\n                    θ :: IntOrReal = 0.;\n                DClevel = 0.)\n```\n\nGenerate a sinusoidal wave with peak amplitude `a`, frequency `f`,\nsampling rate `sr`, duration (in samples) `t`, angle `θ`\n(θ=0 makes a sine, θ=π/2 makes a cosine)\nand optional keyword argument `DC` (float), the DC level defaulting to zero.\nIt is adopted the convention that a sine wave starts at zero.\n\n**See**: [IntOrReal](@ref)\n\n**Examples**:\n```\nusing FourierAnalysis, Plots\n\n# create and plot a sinusoidal wave of 128 samples with\n# peak amplitude 1, frequency 12Hz, sr=64, phase=π/2\nv=sinusoidal(1., 12, 64, 128, π/2)\nplot(v)\n\n# estimate amplitude of a sinusoidal wave using Goertzel algorithm\nf, sr, t = 32, 128, 128\nv=sinusoidal(3., f, sr, t, 0)\nc=goertzel(v, f, sr, t) # c should be equal to 0+3.0im\n```\n\"\"\"\nfunction sinusoidal(a  :: IntOrReal,\n                    f  :: IntOrReal,\n                    sr :: Int,\n                    t  :: Int,\n                    θ  :: IntOrReal =0.;\n                DC = 0.)\n    Δi = inv(sr)\n    f2π = f * 2π\n    ν=Vector([DC+(a*sin(f2π * i * Δi + θ)) for i=0:t-1])\nend\n\n\n\"\"\"\n```\nfunction fres(sr :: Int,\n              wl :: Int)\n```\n\nFFT **f**requency **res**olution given sampling rate `sr` and window length `wl`.\n\n**See also**: [`f2b`](@ref), [`b2f`](@ref), [`fdf`](@ref), [`brange`](@ref).\n\n**Examples**:\n```\nusing FourierAnalysis\nfres(1024, 2048) # return 0.5\n```\n\"\"\"\nfres(sr :: Int,\n     wl :: Int) = sr/wl\n\n\n\"\"\"\n```\nfunction f2b(f :: IntOrReal,\n            sr :: Int,\n            wl :: Int;\n        DC :: Bool = false)\n```\n\n**f**requency **to b**in. Return the bin (position) in a real-FFT vector best matching\na frequency `f` (in Hz), given sampling rate `sr` and window length `wl`.\nThe frequency can be given either as an integer or as a real number.\n\nIf the requested `f` is exactly in between two Fourier discrete frequencies,\nthen the smallest of the two equidistant frequencies is returned.\n\nThe FFT vector is assumed to be 1-based (as always in Julia).\nIf `DC` is false, the first discrete frequency is assumed to be at bin 1,\notherwise the DC is assumed to be at bin 1 and the first discrete frequency\nat bin 2.\n\nIf `DC` is false return 0 for frequencies inferior to half the frequency\nresolution.\n\n**See**: [IntOrReal](@ref).\n\n**See also**: [`fres`](@ref), [`b2f`](@ref), [`fdf`](@ref), [`brange`](@ref).\n\n**Examples**:\n```\nusing FourierAnalysis\nf2b(10, 512, 1024) # return 20\n```\n\"\"\"\nf2b(f  :: IntOrReal,\n    sr :: Int,\n    wl :: Int;\n  DC :: Bool = false) =\n    !DC*fres(sr, wl)<=f<=sr/2 ? (return round(Int, (f*(wl/sr))-eps()) + DC) :\n    @error 📌*\", call to f2b function; invalid frequency argument. The frequency must be comprised between $(!DC*fres(sr, wl)) and $(sr/2) (half the sampling rate)\" f\n#¤ if DC is true the first frequency is the DC level, hence !DC*fres(sr, wl)\n#¤ is equal to zero since !DC=0, otherwise the first frequency is fres(sr, wl)\n\n\n\"\"\"\n```\nfunction b2f(bin :: Int,\n              sr :: Int,\n              wl :: Int;\n        DC :: Bool = false)\n```\n\n**b**in **to f**requency. Return the closest discrete Fourier frequency (in Hz)\nthat corresponds to a bin (position) in a real-FFT vector,\ngiven sampling rate `sr` and window length `wl`.\nThe FFT vector is assumed to be 1-based, as always in Julia.\n\nIf `DC` is false, the first discrete frequency is assumed to be at bin 1,\notherwise the DC level is assumed to be at bin 1 and the first discrete\nfrequency at bin 2.\n\n**See also**: [`f2b`](@ref), [`fres`](@ref), [`fdf`](@ref), [`brange`](@ref).\n\n**Examples**:\n```\nusing FourierAnalysis\nf2b(20, 512, 1024) # return 40\nf2b(10, 128, 128) # return 10\n```\n\"\"\"\nb2f(bin :: Int,\n    sr  :: Int,\n    wl  :: Int;\n  DC :: Bool = false) =\n    0<bin<=wl÷2+DC ? (return (bin-DC)*(sr/wl) ) :\n    @error 📌*\", call to b2f function; invalid bin argument. The bin must be comprised between 1 and half the window length (+ 1 if DC=true)\" bin\n#¤ if DC is true there are wl÷2+1 bins, otherwise there are wl÷2 bins\n\n\n\"\"\"\n```\nfunction fdf(sr :: Int,\n             wl :: Int;\n          DC :: Bool = false)\n```\nReturn a vector with all **F**ourier **d**iscrete **f**requencies for a real-FFT,\ngiven sampling rate `sr` and window length `wl`.\nIf `DC` is false, the first discrete frequency starts at bin (position) 1 and\nthe length of the vector is ``wl÷2`` (integer division), otherwise the DC level is at position 1.\nand the length of the vector is ``(wl÷2)+1``.\n\n**See also**: [`f2b`](@ref), [`fres`](@ref), [`b2f`](@ref), [`brange`](@ref).\n\n**Examples**:\n```\nusing FourierAnalysis\nfdf(8, 16)\n# return the 8-element Array{Float64,1}:\n# [0.5, 1.0, 1.5, 2.0, 2.5, 3, 3.5, 4.0]\n```\n\"\"\"\nfdf(sr :: Int,\n    wl :: Int;\n  DC :: Bool = false) = [i*(sr/wl) for i=!DC:wl÷2]\n#¤ if DC is true !DC=0, hence !DC:wl÷2 starts at zero\n\n\n\"\"\"\n```\nfunction brange(wl :: Int;\n             DC :: Bool = false)\n```\nReturn a range of bins for a real-FFT vector covering all Fourier discrete\nfrequencies given window length `wl`.\n\nIf `DC` is false, the range is ``1:(wl÷2)`` (integer division),\notherwise it is ``1:(wl÷2)+1``.\n\n**See also**: [`f2b`](@ref), [`fres`](@ref), [`b2f`](@ref), [`fdf`](@ref).\n\n**Examples**:\n```\nusing FourierAnalysis\nbrange(0.5, 8) # return 1:4\n```\n\"\"\"\nbrange(wl::Int;\n    DC::Bool=false) = (1:wl÷2+DC)\n\n\n\"\"\"\n```\nfunction bbands(sr :: Int,\n                wl :: Int,\n         bandwidth :: IntOrReal;\n    DC :: Bool = false)\n```\n\nReturn a vector of integers holding the limits of all `bandwidth`-spaced\nband-pass regions of a real-FFT, in bins of discrete Fourier frequencies,\nfrom one to ``wl÷2`` (integer division).\n\nThis is used by function [`bands`](@ref).\n\nTo know the frequencies in Hz to which these bins correspond, call\n[`fbands`](@ref).\n\n**See**: [`bands`](@ref).\n\n**See also**: [`fbands`](@ref).\n\n**Examples**:\n```\nusing FourierAnalysis\nbbands(128, 256, 16) # return [1, 32, 64, 96, 128]\nfbands(128, 256, 16) # return [0.5, 16.0, 32.0, 48.0, 64.0]\n\nbbands(128, 256, 16; DC=true) # return [2, 33, 65, 97, 129]\nfbands(128, 256, 16; DC=true) # return [0.5, 16.0, 32.0, 48.0, 64.0]\n\nbbands(128, 128, 16) # return [1, 16, 32, 48, 64]\nfbands(128, 128, 16) # return [1.0, 16.0, 32.0, 48.0, 64.0]\n```\n\"\"\"\nfunction bbands(sr        :: Int,\n                wl        :: Int,\n                bandwidth :: IntOrReal;\n            DC        :: Bool=false)\n    fr=fres(sr, wl)\n    if bandwidth<fr\n        @error 📌*\", call to function `bbands` or `bandsaverage`: bandwidth cannot be smaller than the FFT frequency resolution\" bandwidth fr\n        return\n    end\n    b=collect(StepRange(0, f2b(bandwidth, sr, wl; DC=DC), wl÷2))\n    b[1]=1\n    if b[2]==1 popfirst!(b) end\n    return DC ? b.+=1 : b\nend\n\n\"\"\"\n```\nfunction fbands(sr :: Int,\n                wl :: Int,\n         bandwidth :: IntOrReal;\n      DC :: Bool = false)\n```\nReturn a vector of Frequencies (in Hz) to which the bins created by a call\nto function [`bbands`](@ref) with the same arguments correspond.\n\n**See**: [`bbands`](@ref).\n\n**See also**: [`bands`](@ref).\n\"\"\"\nfbands(sr        :: Int,\n       wl        :: Int,\n       bandwidth :: IntOrReal;\n    DC :: Bool = false) = b2f.(bbands(sr, wl, bandwidth; DC=DC), sr, wl; DC=DC)\n\n\n\"\"\"\n```\n(1)\nfunction decibel(S :: Union{Real, AbstractArray{T}}) where T<:Real\n\n(2)\nfunction decibel(S1 :: Union{Real, AbstractArray{T}},\n            S2 :: Union{Real, AbstractArray{T}}) where T<:Real\n```\n\nConvert (1) a measure `S`, or (2) a ratio between two measures `S1`./`S2`\ninto deciBels.\n\nInput measures can be real numbers or real arrays of any dimensions.\n\nFor array input, the ratio and the conversion is computed element-wise.\n\n**Examples**:\n```\nusing FourierAnalysis\nv=sinusoidal(3., 1, 128, 256, 0)\ns=spectra(v, 128, 256; func=decibel) # compute the spectra in dB\ns.y # show the spectra\n\ndecibel(s.y)\n\ndecibel(10.0)\n\nN=abs.(randn(3, 3))\ndecibel(N)\n```\n\"\"\"\ndecibel(S::Union{Real, AbstractArray{T}}) where T<:Real = 10*log10.(S)\ndecibel(S1::Union{Real, AbstractArray{T}},\n   S2::Union{Real, AbstractArray{T}}) where T<:Real = 10*log10.(S1./S2)\n\n\n\"\"\"\n```\n(1)\nfunction amplitude(c::Complex;\n                        func::Function=identity) = func(abs(c))\n\n(2)\nfunction amplitude(A::AbstractArray{T};\n                        func::Function=identity) where T<:Complex\n\n(3)\nfunction amplitude(A::TFAnalyticSignal;\n                        func::Function=identity)\n\n(4)\nfunction amplitude(𝐀::TFAnalyticSignalVector;\n                        func::Function=identity)\n```\n(1)\n\nReturn the amplitude (modulus) of a complex number.\nThis corresponds to Julia's\n[abs](https://docs.julialang.org/en/v1/base/math/#Base.abs) function.\nIt is here provided for syntactic consistency with the following methods.\n\n(2)\n\nReturn the amplitude of a complex array `Z`.\nTypically, `Z` holds analytic signal, in which case the output is\nthe analytic (instantaneous) amplitude (also known as envelope).\nThe output is a real array of the same size as `Z`.\n\n(3)\n\nReturn a real matrix with the analytic (instantaneous) amplitude of the\n[TFAnalyticSignal](@ref) object `Z`. The output is of the same\nsize as the data field `Z.y`.\n\n(4)\n\nAs (3), but return a vector of amplitude matrices for all\n[TFAnalyticSignal](@ref) objects in 𝐀\n\n~\n\nIn all methods if a function is provided by the optional keyword\nargument `func`, it is applied element-wise to the output. For example,\n- passing `func=x->x^2` will return the power,\n- passing `func=x->log(x^2)` will return the log-power,\n- passing `func=x->decibel(x^2)` will return the power in deciBels.\n\n**See**: [TFAnalyticSignal](@ref).\n\n**Examples**:\n```\nusing FourierAnalysis, Plots\nx=sinusoidal(10, 2, 128, t*4, 0).*sinusoidal(10, 1, 128, t*4, 0)\n\n# amplitude and phase of a vector using analytic signal standard method\ny=analyticsignal(x)\na=amplitude(y)\nϕ=phase(y, func=x->(x+π)/2π*50)\nplot([x, a, ϕ]; labels=[\"signal\", \"amplitude\", \"phase\"])\n\n# see what happen if `x` contains energy in frequencies below sr/wl Hz\n# (see documentation of `analyticSignal` function)\ny=analyticsignal(x, 64)\na=amplitude(y)\nϕ=phase(y, func=x->(x+π)/2π*50)\nplot([x, a, ϕ]; labels=[\"signal\", \"amplitude\", \"phase\"])\n\n# unwrapped phase\n# the line below will do nothing as argument `unwrapdims` is 0 by default\nϕ2=unwrapPhase(phase(y))\n# this will do the job\nϕ2=unwrapPhase(phase(y); unwrapdims=1)\nplot([x, a, ϕ2./25]; labels=[\"signal\", \"amplitude\", \"unwr. phase\"])\n\n# amplitude from analytic signal of a data matrix holding multiple series\nX=randn(t, 4)\nY=analyticsignal(X)\nA=amplitude(Y)\nplot(A[:, 1:2])\n\n# phase\n𝛷=phase(Y)\nplot(𝛷[:, 1:1])\n\n# unwrapped phase\n𝛷2=unwrapPhase(𝛷; unwrapdims=1)\nplot(𝛷2)\n\n# phase represented in [-1, 1]\n𝛷=phase(Y, func=x->(x+π)/2π)\nplot(𝛷[:, 1:1])\n\n# sine of the phase\n𝛷=phase(Y, func=sin)\nplot(𝛷[:, 1:1])\n\n# get Amplitude and phase from analytic Signal\nA, 𝛷=polar(Y)\nA\n𝛷\n```\n\"\"\"\namplitude(c::Complex;\n                func::Function=identity) = func(abs(c))\n\namplitude(A::AbstractArray{T};\n                    func::Function=identity) where T<:Complex = @.func(abs(A))\n\namplitude(A::TFAnalyticSignal;\n                    func::Function=identity) = amplitude(A.y, func)\n\namplitude(𝐀::TFAnalyticSignalVector;\n                    func::Function=identity) = [amplitude(A.y, func) for A ∈ 𝐀]\n\n# Standard atan function in other languages\natan2(z::Complex) = atan(imag(z), real(z))\n\n\"\"\"\n```\n(1)\nfunction phase(z::Complex; func::Function=identity)\n\n(2)\nfunction phase(Z::AbstractArray{T};\n                        unwrapdims::Int=0,\n                        func::Function=identity) where T<:Complex\n\n(3)\nfunction phase(Z::TFAnalyticSignal;\n                        unwrapped::Bool=false,\n                        func::Function=identity)\n\n(4)\nfunction phase(𝐙::TFAnalyticSignalVector;\n                        unwrapped::Bool=false,\n                        func::Function=identity)\n\n```\n(1)\n\nReturn the phase (argument) of a complex number.\nThis corresponds to a standard\n[atan2](https://en.wikipedia.org/wiki/Atan2) function.\nIt is here provided for syntactic consistency with the following methods.\n\n(2)\n\nReturn the phase of a complex array `Z`.\nTypically, `Z` holds analytic signal, in which case the output is\nthe analytic (instantaneous) phase.\nThe output is a real array of the same size as `Z`.\n\nIf optional keyword argument `unwrapdims` is > 0, return the unwrapped phase\nalong the `unwrapdims` dimension of the array. For example, if `Z` is a matrix,\npassing `unwrapdims=1` unwrap the phase indipendently along its columns.\n\n(3)\n\nReturn a real matrix with the analytic (instantaneous) phase of the\n[TFAnalyticSignal](@ref) object `Z`. The output is of the same\nsize as the data field `Z.y`.\n\nIf optional keyword argument `unwrapped` is true, return the unwrapped phase\nalong the time dimension of the analytic signal (dims=2).\n\n(4)\n\nAs (3), but return a vector of phase matrices for all\n[TFAnalyticSignal](@ref) objects in 𝚯.\n\n~\n\nIn all methods by default the phase is returned in [−π, π].\nIf a function is provided by the optional keyword argument `func`,\nit is applied to the phase. For example\n- passing `func=x->x+π` will return the phase in [0, 2π],\n- passing `func=x->x/π` will return the phase in [-1, 1],\n- passing `func=sin` will return the sine of the phase.\n\n!!! note \"Nota Bene\"\n    If in method (2) `unwrapdims` is >0 or in method (3) and (4)\n    `unwrapped` is true, the function `func` is applied to the unwrapped phase.\n\n**See**: [`unwrapPhase`](@ref), [TFAnalyticSignal](@ref).\n\n**Examples**: see examples of [`amplitude`](@ref).\n\"\"\"\nphase(z::Complex; func::Function=identity) = func(atan2(z))\n\nphase(Z::AbstractArray{T};\n                unwrapdims::Int=0,\n                func::Function=identity) where T<:Complex =\n    unwrapdims>0 ? func.(unwrapPhase(Z, unwrapdims=unwrapdims)) : @.func(atan2(Z))  # see Base.Broadcast.@__dot__\n\nphase(Z::TFAnalyticSignal; unwrapped::Bool=false, func::Function=identity) =\n    phase(Z.y; unwrapdims=2*unwrapped, func=func) # unwrap==true -> unwrapdims=2, else unwrapdims=0\n\nphase(𝐙::TFAnalyticSignalVector; unwrapped::Bool=false, func::Function=identity) =\n    [phase(Z; unwrapped=unwrapped, func=func) for Z ∈ 𝐙]\n\n\"\"\"\n```\n(1)\nfunction polar(c::Complex)\n\n(2)\nfunction polar(Z::AbstractArray{T}) where T<:Complex\n\n(3)\nfunction polar(Z::TFAnalyticSignal)\n\n```\n\n(1)\n\nReturn the amplitude (modulus) and phase (argument)\nof a complex number as a 2-tuple.\n\n(2)\n\nReturn the amplitude and phase of a complex array `Z`.\nTypically, `Z` holds analytic signal, in which case return\nthe analytic (instantaneous) amplitude and phase.\nThe output is a tuple of two real arrays of the same size as data field `Z.y`.\n\n(3)\n\nReturn the analytic (instantaneous) amplitude\nand phase of the [TFAnalyticSignal](@ref) object `Z`.\nThe output is a tuple of two real arrays of the same size as data field `Z.y`.\n\n~\n\nIn all methods the phase is returned in [−π, π].\n\n**See**: [`amplitude`](@ref), [`phase`](@ref), [TFAnalyticSignal](@ref).\n\n**Examples**: see examples of [`amplitude`](@ref).\n\"\"\"\npolar(c::Complex) = amp(c), atan2(c)\n\npolar(Z::AbstractArray{T}) where T<:Complex = amplitude(Z), phase(Z)\n\npolar(Z::TFAnalyticSignal) = polar(Z.y)\n\n\n# instantaneous frequency from wikipedia\n  #function frequency(Y::TimeFrequency)\n    #  W=zeros(real(eltype(Y.Z)), size(Y.Z))\n    #  @inbounds for j=2:size(Y.Z, 2), i=1:size(Y.Z, 1)\n    #                W[i, j]=atan2(Y.Z[i, j]*conj(Y.Z[i, j-1]))/2π end\n    #  return\n # end\n\n\n\n\"\"\"\n```\n(1)\nfunction unwrapPhase(Z::AbstractArray{T};\n                                unwrapdims::Int=0) where T<:Complex\n\n(2)\nfunction unwrapPhase(ϴ::AbstractArray{T};\n                                unwrapdims::Int=0) where T<:Real\n\n(3)\nunwrapPhase(ϴ::TFPhase) [constructor of a TFPhase object]\n\n(4)\nunwrapPhase(𝚯::TFPhaseVector) [constructor of a TFPhaseVector object]\n```\n(1)\n\nIf optional keyword argument `unwrapdims` is > 0, compute the phase\n(argument) from a *complex* array and unwrap it along the `unwrapdims`\ndimension, otherwise (default) return `Z`.\nTypically, `Z` holds analytic signal.\n\n(2)\n\nIf optional keyword argument `unwrapdims` is > 0, unwrap along the\n`unwrapdims` dimension a *real* array holding phase data in [−π, π],\notherwise return `ϴ`.\n\n(3)\n\nConstruct a [TFPhase](@ref) object by unwrapping its phase along the time\ndimension and copying all other fields from the `ϴ` object. If `ϴ.func`\nis different from the `identity` (do nothing) function,\nreturn instead an error message.\n\n(4)\n\nAs (3), but conctruct a [TFPhaseVector](@ref) holding\n[TFPhase](@ref) objects in 𝚯 with the phase unwrapped.\n`ϴ.func` must be the identity function for all ϴ ∈ 𝚯.\n\nThe unwrapped phase is defined as the cumulative sum\nof the phase (along the relevant dimension)\nonce this is represented in [0, 2π].\n\n**Examples**: see examples of [`amplitude`](@ref).\n\"\"\"\nunwrapPhase(Z::AbstractArray{T}; unwrapdims::Int=0) where T<:Complex =\n    unwrapdims>0 ? accumulate(+, (atan2.(Z)).+π; dims=unwrapdims) : Z\n\nunwrapPhase(ϴ::AbstractArray{T}; unwrapdims::Int=0) where T<:Real =\n    unwrapdims>0 ? accumulate(+, ϴ.+π; dims=unwrapdims) : ϴ\n\nunwrapPhase(ϴ::TFPhase) =\n    ϴ.func==identity ? TFPhase(unwrapPhase(ϴ.y; unwrapdims=2), ϴ.bandwidth,\n                               ϴ.flabels, ϴ.nonlinear,\n                               ϴ.fsmoothing, ϴ.tsmoothing, true, ϴ.func) :\n   @error 📌*\", call to unwrapPhase constructor; I shall not unwrap a phase on which a function has been applied. The unwrapped phase object has not been created.)\" ϴ.func\n\n\nunwrapPhase(𝚯::TFPhaseVector) =\n   sum(ϴ.func==identity for ϴ ∈ 𝚯)==length(𝚯) ? TFPhaseVector([\n                    TFPhase(unwrapPhase(ϴ.y; unwrapdims=2), ϴ.bandwidth,\n                    ϴ.flabels, ϴ.nonlinear, ϴ.fsmoothing, ϴ.tsmoothing,\n                    true, ϴ.func) for ϴ ∈ 𝚯]) :\n  @error 📌*\", call to unwrapPhase constructor; I shall not unwrap a phase on which a function has been applied. The unwrapped phase object has not been created.)\" ϴ.func\n\n\n\n\"\"\"\n```\nfunction sameParams(𝐒        :: FDobjectsVector,\n                    funcname :: String)\n```\n\n\nReturn true if all objects in 𝐒 have the same `sr`, `wl`, `DC`, `taper`,\n`func`(only for [SpectraVector](@ref) objects), `nonlinear` (only for\n[CrossSpectraVector](@ref) and [CoherenceVector](@ref)) and `smoothing` fields,\notherwise print an error message pointing to the first field that is not\nidentical in all objects and return `Nothing`. This method applies to\nall [FDobjectsVector](@ref) types, that is,\nto [SpectraVector](@ref), [CrossSpectraVector](@ref) and\n[CoherenceVector](@ref).\n\n`funcname` is an optional string that the user can\nprovide. It is inserted into the error message to locate the part\nof the code that generated the error. By defalut, \"unknown\" is used.\n\"\"\"\nsameParams(𝐒        :: FDobjectsVector,\n           funcname :: String = \"unknown\") =\n   if      !_allsame([S.sr for S ∈ 𝐒])\n               @error 📌*\", \"*funcname*\" function. All objects in argument of type $typeof(𝐒) must have the same sampling rate (.sr field)\"\n   elseif  !_allsame([S.wl for S ∈ 𝐒])\n               @error 📌*\", \"*funcname*\" function. All objects in argument of type $typeof(𝐒) must have the same window length (.wl field)\"\n   elseif  !_allsame([S.DC for S ∈ 𝐒])\n               @error 📌*\", \"*funcname*\" function. All objects in argument of type $typeof(𝐒) must all hold or not hold DC level (.DC field)\"\n   elseif  !_allsame([S.taper for S ∈ 𝐒])\n               @error 📌*\", \"*funcname*\". All objects in argument of type $typeof(𝐒) must have the same taper (.taper field)\"\n   elseif  𝐒 isa SpectraVector && !_allsame([S.func for S ∈ 𝐒])\n               @error 📌*\", \"*funcname*\". All objects in argument of type $typeof(𝐒) must have been subjected to the same function (.func field)\"\n   elseif  (𝐒 isa CrossSpectraVector || 𝐒 isa CoherenceVector) && !_allsame([S.nonlinear for S ∈ 𝐒])\n               @error 📌*\", \"*funcname*\". The objects in argument of type $typeof(𝐒) must be either all linear or all non-linear (.nonlinear field)\"\n   elseif  !_allsame([S.smoothing for S ∈ 𝐒])\n               @error 📌*\", \"*funcname*\". All the objects in argument of type $typeof(𝐒) must have been subjected to the same smoother (.smoothing field)\"\n   elseif      return true\n   end\n\n\n\"\"\"\n```\nfunction sameParams(𝒀        :: TFobjectsVector,\n                    funcname :: String) =\n```\nReturn true if all objects in 𝒀 have the same `bandwidth`, `nonlinear`,\n`fsmoothing` and `tsmoothing` field, otherwise print an error message\npointing to the first field that is not identical in all objects and\nreturn `Nothing`. This method applies to all [TFobjectsVector](@ref) types,\nthat is, [TFAnalyticSignalVector](@ref), [TFAmplitudeVector](@ref) and\n[TFPhaseVector](@ref).\n\n`funcname` has the same meaning as in the previous method.\n\"\"\"\nsameParams(𝒀        :: TFobjectsVector,\n           funcname :: String = \"unknown\") =\n   if      !_allsame([Y.bandwidth for Y ∈ 𝒀])\n               @error 📌*\", \"*funcname*\" function. All the objects in argument of type $typeof(𝒀) must all be definied with the same bandwidth\"\n   elseif  !isa(𝒀, TFAmplitudeVector) && !_allsame([Y.nonlinear for Y ∈ 𝒀])\n               @error 📌*\", \"*funcname*\" function. All the objects in argument of type $typeof(𝒀) must be definied as either all nonlinear or all linear\"\n   elseif  !_allsame([Y.fsmoothing for Y ∈ 𝒀])\n               @error 📌*\", \"*funcname*\" function. All the objects in argument of type $typeof(𝒀) must be definied with the same frequency smoother\"\n   elseif  !_allsame([Y.tsmoothing for Y ∈ 𝒀])\n               @error 📌*\", \"*funcname*\" function. All the objects in argument of type $typeof(𝒀) must be definied with the same time smoother\"\n   elseif      return true\n   end\n\n\n\"\"\"\n```\nfunction isLinear(𝒀::Union{FDobjectsVector, TFobjectsVector})\n```\nReturn true if all objects in `𝒀` are linear.\nBy definition, [Spectra](@ref) and [TFAmplitude](@ref) objects are linear.\n[CrossSpectra](@ref), [Coherence](@ref), [TFAnalyticSignal](@ref)\nand [TFPhase](@ref) objects may be linear or non-linear.\n\n**See**:[FDobjectsVector](@ref), [TFobjectsVector](@ref).\n\"\"\"\nisLinear(𝒀::FDobjectsVector) =\n   𝒀 isa SpectraVector ? true : sum(Y.nonlinear for Y ∈ 𝒀)==0\n\nisLinear(𝒀::TFobjectsVector) =\n   𝒀 isa TFAmplitudeVector ? true : sum(Y.nonlinear for Y ∈ 𝒀)==0\n\n\"\"\"\n```\nfunction isNonLinear(𝒀::Union{FDobjectsVector, TFobjectsVector})\n```\nReturn true if all objects in `𝒀` are non-linear.\nBy definition, [Spectra](@ref) and [TFAmplitude](@ref) objects are linear.\n[CrossSpectra](@ref), [Coherence](@ref), [TFAnalyticSignal](@ref)\nand [TFPhase](@ref) objects may be linear or non-linear.\n\n**See**:[FDobjectsVector](@ref), [TFobjectsVector](@ref).\n\n\"\"\"\nisNonLinear(𝒀::FDobjectsVector) =\n   𝒀 isa SpectraVector ? false : sum(Y.nonlinear for Y ∈ 𝒀)==length(𝒀)\n\nisNonLinear(𝒀::TFobjectsVector) =\n   𝒀 isa TFAmplitudeVector ? false : sum(Y.nonlinear for Y ∈ 𝒀)==length(𝒀)\n\n\"\"\"\n```\n(1)\nfunction isUnwrapped(ϴ::TFPhase)\n\n(2)\nfunction isUnwrapped(𝚯::TFPhaseVector)\n```\n(1)\nReturn true if the TFPhase objects ϴ have the phase unwrapped.\n\n(2)\nReturn true if all TFPhase objects in 𝚯 have the phase unwrapped.\n\n**See**: [`unwrapPhase`](@ref), [TFPhase](@ref), [TFPhaseVector](@ref).\n\"\"\"\nisUnwrapped(ϴ::TFPhase) =  ϴ.unwrapped\n\nisUnwrapped(𝚯::TFPhaseVector) =  sum(ϴ.unwrapped for ϴ ∈ 𝚯)==0\n\n\n### Frequency-domain smoothing ###\n###############################################################################\n\n# Internal function: computes coefficients for smoothing\nfunction _getSmoothCoeff(smoother::Smoother)\n    if      smoother == hannSmoother\n            return [0.25, 0.5, 0.25], 0.75, 0. # 0.75=c1+c2\n    elseif  smoother == hammingSmoother\n            return [0.23, 0.54, 0.23], 0.77, 0. # 0.77=c1+c2\n    elseif  smoother == blackmanSmoother\n            return [0.04, 0.25, 0.42, 0.25, 0.04], 0.71, 0.96 # 0.71=c1+c2+c3, 0.96=c1+c2+c3+c4\n    end\nend\n\n\n# Internal function: apply frequency-domain smoothing to the `X` vector\n# of real or complex numbers or real or complex lower-triangular matrices\nfunction __smooth(X, c, s, t)\n    Y=similar(X)\n    k=length(X)\n    type=typeof(X)\n\n    if      type isa Vector{LowerTriangular} # || type===Array{LowerTriangular{Complex{Float64},S} where S<:AbstractArray{Complex{Float64},2},1}\n            T=LowerTriangular\n    elseif  type isa Array{Hermitian} # || Array{Hermitian{Complex{Float64},S} where S<:AbstractArray{Complex{Float64},2},1}\n            T=Hermitian\n    else    T=eltype(X)\n    end\n\n    if length(c) == 3 # `smoother` = `hannSmoother` or `hammingSmoother`\n        Y[1] = T(X[1]*(c[2]/s) + X[2]*(c[3]/s))\n        @inbounds for i=2:k-1 Y[i] = T(X[i-1]*c[1] + X[i]*c[2] + X[i+1]*c[3]) end\n        Y[k] = T(X[k-1]*(c[1]/s) + X[k]*(c[2]/s))\n    else # `smoother` = `blackmanSmoother`, for which length(c) == 5\n        Y[1] = T(X[1]*(c[3]/s) + X[2]*(c[4]/s) + X[3]*(c[5]/s))\n        Y[2] = T(X[1]*(c[2]/t) + X[2]*(c[3]/t) + X[3]*(c[4]/t) + X[4]*(c[5]/t))\n        @inbounds for i=3:k-2 Y[i] = T(X[i-2]*c[1] + X[i-1]*c[2] + X[i]*c[3] + X[i+1]*c[4] + X[i+2]*c[5]) end\n        Y[k-1] = T(X[k-3]*(c[1]/t) + X[k-2]*(c[2]/t) + X[k-1]*(c[3]/t) + X[k]*(c[4]/t))\n        Y[k] = T(X[k-2]*(c[1]/s) + X[k-1]*(c[2]/s) + X[k]*(c[3]/s))\n    end\n    return type(Y)\nend\n\nsmooth(smoothing::Smoother, S::Union{Vector{<:Real}, Vector{<:Complex}}) =\n    return smoothing == noSmoother ? S : __smooth(S, _getSmoothCoeff(smoothing)...)\n\n\n# Internal function: smooth the output of `spectra` function; spectra of a Matrix (columns)\nfunction _smooth(smoother::Smoother, S::Spectra, γ, c1, c2)\n    Y=similar(S.y)\n    @inbounds for i=1:size(S.y, 2) Y[:, i]=__smooth(S.y[:, i], γ, c1, c2) end\n    return Spectra(Y, S.sr, S.wl, S.DC, S.taper, S.flabels, S.func, smoother)\nend\n\n# Internal function: smooth the output of `spectra` function; k-spectra of a Matrix Vector\n_smooth(smoother::Smoother, 𝐒::SpectraVector, γ, c1, c2) =\n    SpectraVector([_smooth(smoother, S, γ, c1, c2) for S ∈ 𝐒])\n\n# Internal function: smooth the output of `cross-spectra` or `coherence` function\n_smooth(smoother::Smoother, 𝙎::Union{CrossSpectra, Coherence}, γ, c1, c2) =\n    typeof(𝙎)(__smooth(𝙎.y, γ, c1, c2), 𝙎.sr, 𝙎.wl, 𝙎.DC, 𝙎.taper, 𝙎.flabels, 𝙎.nonlinear, smoother, 𝙎.tril)\n\n# Internal function: smooth the output of `cross-spectra` or `coherence` function; k-cross-spectra of a Matrix Vector\n_smooth(smoother::Smoother, 𝓢::Union{CrossSpectraVector, CoherenceVector}, γ, c1, c2) =\n    typeof(𝓢)([_smooth(smoother, 𝐒, γ, c1, c2) for 𝐒 ∈ 𝓢])\n\n\n\"\"\"\n```\n(1)\nfunction smooth(smoother :: Smoother,\n                       S :: Union{Vector{<:Real}, Vector{<:Complex}})\n\n(2)\nfunction smooth(smoother :: Smoother,\n                       S :: Union{FDobjects, FDobjectsVector})\n\n(3)\nfunction smooth(fsmoothing :: Smoother,\n                tsmoothing :: Smoother,\n                         Y :: Union{TFobjects, TFobjectsVector})\n```\n\nApply a smoothing function of type [Smoother](@ref) to\n- (1) a vector of real or complex numbers,\n- (2) a [FDobjects](@ref) or all objects in a [FDobjectsVector](@ref),\n- (3) a [TFobjects](@ref) or all objects in a [TFobjectsVector](@ref).\n\nThis function is a constructor; for all methods the output is always of\nthe same type as the input.\n\nMethod (1) is provided for low-level computations,\nbut typically it is not needed.\n\nMethod (2) smooths across the frequency dimension:\n- for [Spectra](@ref) objects this amounts to smoothing the column vectors in their `.y` field,\n- for [CrossSpectra](@ref) and [Coherence](@ref) objects this amounts to smoothing adjacent matrices in their .y field.\n\nMethod (3) smooths across the frequency dimension, time dimension or both.\nThis amount to smooth across the column vectors (frequency) and/or row vectors\n(time) in the `.y` field of the object.\nA smoother must be specified for the frequency dimension\n(`fsmoothing`) and for the time dimension (`tsmoothing`).\nEither one may be `noSmoother`, but if the two are different from `noSmoother`,\nthen they must be the same. If smoothing is requested in both the frequency and\ntime dimension, then the data is smoothed indipendently in those dimensions\nand the result of the two smoothings is averaged.\nFor [TFPhase](@ref) objects, smoothing is allowed only if the phase is unwrapped.\n\nThis function allow smoothing frequency domain and time-frequency domain objects\nafter they have been created, however, smoothing can also be requested upon\ncreation. For example, see the documentation of [Spectra](@ref).\n\n!!! note \"Nota Bene\"\n    For methods (1) and (2), if `Smoother` is `noSmoother`, then the input\n    is returned unchanged. For method (3) this is the case if both `fsmoother`\n    and `tsmoother` are `noSmoother`.\n\n    The data input must hold in the concerned dimension at least three elements\n    for applying an Hann or Hamming smoother and at least five elements for\n    applying the Blackman smoother.\n\n## Maths\n\nSmoothing of a series ``x`` composed of ``k`` elements is carried out at element\n``i`` such as\n\n``x_{i}=ax_{i-2}+bx_i{-1}+cx_{i}+bx_{i+1}+ax_{i+2}``.\n\nThe coefficients are\n\n| smoothing window  |  a   |  b   |  c   |\n|:-----------------:|:----:|:----:|:----:|\n| Hann              | 0    | 0.25 | 0.50 |\n| Hamming           | 0    | 0.23 | 0.54 |\n| Blackman          | 0.04 | 0.25 | 0.42 |\n\nFor 3-point smoothers, the first point is smoothed as\n\n``x_{1}=\\\\frac{c}{b+c}x_{1} + \\\\frac{b}{b+c}x_{2}``\n\nand the last (the ``k^{th}``) as\n\n``x_{k}=\\\\frac{c}{b+c}x_{k} + \\\\frac{b}{b+c}x_{k-1}``.\n\nFor 5-point smoothers, the first point is smoothed as\n\n``x_{1}=\\\\frac{c}{a+b+c}x_{1} + \\\\frac{b}{a+b+c}x_{2} + \\\\frac{a}{a+b+c}x_{3}``,\n\nthe second as\n\n``x_{2}=\\\\frac{b}{a+2b+c}x_{1} + \\\\frac{c}{a+2b+c}x_{2} + \\\\frac{b}{a+2b+c}x_{3} + \\\\frac{a}{a+2b+c}x_{4}``,\n\nthe second to last as\n\n``x_{k-1}=\\\\frac{a}{a+2b+c}x_{k-3} + \\\\frac{b}{a+2b+c}x_{k-2} + \\\\frac{c}{a+2b+c}x_{k-1} + \\\\frac{b}{a+2b+c}x_{k}``\n\nand the last as\n\n``x_{k}=\\\\frac{a}{a+b+c}x_{k-2} + \\\\frac{b}{a+b+c}x_{k-1} + \\\\frac{c}{a+b+c}x_{k}``.\n\n**See**: [Smoother](@ref)\n\n**Examples**:\n```\nusing FourierAnalysis, Plots\nsr, t, f, a = 128, 128, 10, 0.5\n# create a sinusoidal superimposed to white noise\nv=sinusoidal(a, f, sr, t*16, 0) + randn(t*16)\n# compute Amplitude Spectra\nΣ=spectra(v, sr, t; func=√)\nbar(Σ.y, labels=\"raw amplitude spectra\")\n\n#smooth spectra\nΣ2=smooth(blackmanSmoother, Σ)\nbar!(Σ2.y, labels=\"smoothed amplitude spectra\")\n\n# smooth cross-spectra (or coherence) matrices\nX=broadcast(+, v, randn(t*16, 3))*randn(3, 3)\nS=crossSpectra(X, sr, t) # or coherence (X, sr, t)\n# smooth the cross-spectra # or coherence\nS2=smooth(blackmanSmoother, S)\n\n# smooth time-frequency object\nY = TFanalyticsignal(v, sr, sr*4)\n# smooth frequency\nZ=smooth(blackmanSmoother, noSmoother, Y)\n# plot amplitude of smoothed analytic signal\nheatmap(Z, amplitude)\n\n# smooth AS: smooth both frequency and time\nE=smooth(blackmanSmoother, blackmanSmoother, Y)\n# plot real part of smoothed analytic signal\nheatmap(Z, real)\n```\n\"\"\"\nsmooth(smoothing::Smoother, S::Union{FDobjects, FDobjectsVector}) =\n    return smoothing == noSmoother ? S : _smooth(smoothing, S, _getSmoothCoeff(smoothing)...)\n\n# internal function: Smooth the TimeFrequency types; dim1 = time, dim2=frequency\nfunction _smooth(smoother  :: Smoother,\n                 Z         :: TFobjects,\n                 frequency :: Bool,\n                 time      :: Bool,\n                 γ, c1, c2)\n\n    cT=eltype(Z.y)\n    if     !frequency & !time\n        Z_=Z.y\n    elseif !frequency & time\n        Z_=Matrix{cT}(undef, size(Z.y))\n        @inbounds for i=1:size(Z_, 1) Z_[i, :]=__smooth(Z.y[i, :], γ, c1, c2) end\n    elseif frequency & !time\n        Z_=Matrix{cT}(undef, size(Z.y))\n        @inbounds for i=1:size(Z_, 2) Z_[:, i]=__smooth(Z.y[:, i], γ, c1, c2) end\n    elseif frequency & time\n        Zf=Matrix{cT}(undef, size(Z.y))\n        @inbounds for i=1:size(Zf, 2) Zf[:, i]=__smooth(Z.y[:, i], γ, c1, c2) end\n        Zt=Matrix{cT}(undef, size(Z.y))\n        @inbounds for i=1:size(Zt, 1) Zt[i, :]=__smooth(Z.y[i, :], γ, c1, c2) end\n        Z_=(Zf+Zt)/2\n    end\n\n    type=typeof(Z)\n    if     type===TFAnalyticSignal\n        return type(Z_, Z.bandwidth, Z.flabels, Z.nonlinear, frequency ? smoother : noSmoother, time ? smoother : noSmoother)\n    elseif type===TFAmplitude\n        return type(Z_, Z.bandwidth, Z.flabels, frequency ? smoother : noSmoother, time ? smoother : noSmoother, Z.func)\n    elseif type===TFPhase\n        return type(Z_, Z.bandwidth, Z.flabels, Z.nonlinear, frequency ? smoother : noSmoother, time ? smoother : noSmoother, Z.unwrapped, Z.func)\n    end\nend\n\n# Smooth the TFobjects types; dim1 = time, dim2=frequency\nsmooth(fsmoothing :: Smoother,\n       tsmoothing :: Smoother,\n       Z          :: TFobjects,\n       funcname   :: String=\"\") =\n    if Z isa TFPhase && !Z.unwrapped\n        @error 📌*\", function \"*funcname*\": smoothing of TFPhase objects can be applied only if the phase is unwrapped\"\n        return\n    elseif fsmoothing == tsmoothing == noSmoother\n        return Z\n    elseif fsmoothing==tsmoothing || (fsmoothing==noSmoother || tsmoothing==noSmoother)\n        smoother=max(fsmoothing, tsmoothing) # return the smoother if they are equal or one of them is noSmoother\n        return _smooth(smoother, Z, fsmoothing≠noSmoother, tsmoothing≠noSmoother, _getSmoothCoeff(smoother)...)\n    else\n        @error 📌*\", function \"*funcname*\": if smoothing is requested, then the `Smoother` for frequency and time must be of the same kind\"\n    end\n\n# Smooth the TFobjectsVector types; dim1 = time, dim2=frequency\nsmooth(fsmoothing :: Smoother,\n       tsmoothing :: Smoother,\n       𝐙          :: TFobjectsVector,\n       funcname   :: String=\"\") =\n   if 𝐙 isa TFPhaseVector && isUnwrapped(𝐙)\n       @error 📌*\", function \"*funcname*\": smoothing of TFPhaseVector objects can be applied only if the phase is unwrapped for all TFPhase objects it holds\"\n       return\n   elseif fsmoothing == tsmoothing == noSmoother\n       return 𝐙\n   elseif fsmoothing==tsmoothing || (fsmoothing==noSmoother || tsmoothing==noSmoother)\n       smoother=max(fsmoothing, tsmoothing) # return the smoother if they are equal or one of them is noSmoother\n       return typeof(𝐙)([_smooth(smoother, Z, fsmoothing≠noSmoother, tsmoothing≠noSmoother, _getSmoothCoeff(smoother)...) for Z ∈ 𝐙])\n   else\n       @error 📌*\", function \"*funcname*\": if smoothing is requested, then the `Smoother` for frequency and time must be of the same kind\"\n   end\n#    return smoother == noSmoother ? 𝐙 :\n#           typeof(𝐙)([_smooth(smoother, Z, frequency, time, _getSmoothCoeff(smoother)...) for Z ∈ 𝐙])\n\n\n### Frequency-domain data extraction and averaging ###\n###############################################################################\n\n# get an fInterval type and output a UnitRange whose start and stop are the\n# corresonding Fourier discrete frequency bins\nfunction _getfrange(S::FDobjects, frange::fInterval, funcname::String)\n    if      isa(frange, IntOrReal)\n            !S.DC*fres(S.sr, S.wl)<=frange<=S.sr/2 ? (return f2b(frange, S.sr, S.wl; DC=S.DC):f2b(frange, S.sr, S.wl; DC=S.DC)) :\n            @error 📌*\", \"*funcname*\" function passed invalid frange Int or Real argument. The frequency must be comprised between $(!S.DC*fres(S.sr, S.wl)) and $(S.sr/2) (half the sampling rate)\" frange\n            return 0\n    elseif  isa(frange, Colon)\n            return 1:size(S.y, 1)\n    elseif  isa(frange, Tuple{IntOrReal, IntOrReal})\n            # println(frange[1], \", \", frange[2])\n            if      frange[1]>frange[2]\n                        @error 📌*\", \"*funcname*\" function passed invalid frange 2-tuple argument. The second element cannot be inferior to the first\" frange[1] frange[2]\n                        return 0\n            elseif  frange[1]<!S.DC*fres(S.sr, S.wl) || frange[2]>S.sr/2\n                        @error 📌*\", \"*funcname*\" function passed invalid frange 2-tuple argument. The two frequencies must be comprised between $(!S.DC*fres(S.sr, S.wl)) and $(S.sr/2) (half the sampling rate)\" frange[1] frange[2]\n                        return 0\n            else        return f2b(frange[1], S.sr, S.wl; DC=S.DC): f2b(frange[2], S.sr, S.wl; DC=S.DC)\n            end\n    end\nend\n\n# as _getfrange above, but for a FDobjectsVector object.\n# By default, it is checked that the elements of the vector are homogeneous.\n# If so return the UnitRange obtained on the first FDobject in the vector,\n# otherwise return 0.\n# if `check` is false, the check is skypped.\n_getfrange(𝐒::FDobjectsVector, frange::fInterval, funcname::String; check::Bool=true) =\n    check ? (sameParams(𝐒, funcname) ? _getfrange(𝐒[1], frange, funcname) : 0) :\n    _getfrange(𝐒[1], frange, funcname)\n\n_extract(S::Spectra, frange::UnitRange{Int64}) =\n    _isnull(frange) && size(S.y, 2)==1 ? S.y[first(frange), 1] :\n                                         copy(S.y[frange, :])\n\n_extract(𝐒::SpectraVector, frange::UnitRange{Int64}) =\n    _isnull(frange) && size(𝐒[1].y, 2)==1 ? [S[first(frange), 1] for S ∈ 𝐒] :\n                                            [S[frange, :] for S ∈ 𝐒]\n\nfunction _extract(S::Union{CrossSpectra, Coherence}, frange::UnitRange{Int64})\n    mattype = S.tril ? LowerTriangular : Hermitian\n    _isnull(frange) ? mattype(copy(S.y[first(frange)])) :\n                      typeof(S.y)([mattype(S.y[i]) for i∈frange])\nend\n\nfunction _extract(𝐒::Union{CrossSpectraVector, CoherenceVector}, frange::UnitRange{Int64})\n    mattype = 𝐒[1].tril ? LowerTriangular : Hermitian\n    _isnull(frange) ? typeof(𝐒[1].y)([mattype(S.y[first(frange)]) for S ∈ 𝐒]) :\n                      [typeof(𝐒[1].y)([mattype(S.y[i]) for i∈frange]) for S ∈ 𝐒]\nend\n\n_mean(S::Spectra, frange::UnitRange{Int64}) =\n    size(S.y, 2)==1 ? mean(view(S.y, frange, 1)) :\n                     [mean(view(S.y, frange, k)) for k=1:size(S.y, 2)]\n\n_mean(S::Union{CrossSpectra, Coherence}, frange::UnitRange{Int64}) =\n    eltype(S.y)(mean(view(S.y[i], :, :) for i∈frange))\n\n_mean(𝐒::SpectraVector, frange::UnitRange{Int64}) =\n    size(𝐒[1].y, 2)==1 ? [mean(view(S.y, frange, 1)) for S ∈ 𝐒] :\n                         [[mean(view(S.y, frange, k)) for k=1:size(S.y, 2)] for S ∈ 𝐒]\n\n_mean(𝐒::Union{CrossSpectraVector, CoherenceVector}, frange::UnitRange{Int64}) =\n    typeof(𝐒[1].y)([_mean(S, frange) for S ∈ 𝐒])\n\n\"\"\"\n```\n(1)\nfunction extract(S :: FDobjects,\n            frange :: fInterval)\n\n(2)\nfunction extract(𝐒 :: FDobjectsVector,\n            frange :: fInterval;\n        w :: Vector = [],\n    check :: Bool   = true)\n\n(3)\nfunction extract(Y :: TFobjects,\n            frange :: fInterval,\n            trange :: tInterval)\n\n(4)\nfunction extract(𝒀 :: TFobjectsVector,\n            frange :: fInterval,\n            trange :: tInterval;\n        w :: Vector = [],\n    check :: Bool   = true)\n```\n\n**alias**: `extr`\n\nExtract data in a frequency region from [FDobjects](@ref) and data in a\ntime-frequency region from [TFobjects](@ref). The frequency and time region\nare indicated by `frange` and `trange`, which are of type [fInterval](@ref)\nand [tInterval](@ref), respectively.\n\nThe input/output types of this function for a region with more then one\nfrequency and more than one sample is reported in the following table:\n\n|method|        input object          |                   output                |\n|:---:|:------------------------------|:---------------------------------------------|\n|(1.1)| [Spectra](@ref)               | a real matrix with spectra in `frange` arranged in columns¹|\n|(1.2)| [CrossSpectra](@ref)          | a vector of complex matrices holding the cross-spectra in `frange`²|\n|(1.3)| [Coherence](@ref)             | a vector of real matrices holding the coherence in `frange`²|\n|(2.1)| [SpectraVector](@ref)         | a vector of matrices of type (1.1)|\n|(2.2)| [CrossSpectraVector](@ref)    | a vector of vectors of type (1.2)|\n|(2.3)| [CoherenceVector](@ref)       | a vector of vectors of type (1.3)|\n|(3.1)| [TFAnalyticSignal](@ref)      | a complex matrix holding the analytic signal in [`frange`, `trange`]|\n|(3.2)| [TFAmplitude](@ref)           | a real matrix holding the amplitude in [`frange`, `trange`]|\n|(3.3)| [TFPhase](@ref)               | a real matrices holding the phase in [`frange`, `trange`]|\n|(4.1)| [TFAnalyticSignalVector](@ref)| a vector of matrices of type (3.1)|\n|(4.2)| [TFAmplitudeVector](@ref)     | a vector of matrices of type (3.2)|\n|(4.3)| [TFPhaseVector](@ref)         | a vector of matrices of type (3.3)|\nLegend: ¹ *each column refers to a time-series on which the spectra have been computed.*\n² *depending on how the objects has been created, the matrices may be either\nHermitian or LowerTriangular. See the documentation of [CrossSpectra](@ref) and [Coherence](@ref).\n\nNote that depending on the arguments the type of the output may loose one or two dimensions.\nFor instance,\n- if the [Spectra](@ref) object holds only one spectrum, (1.1) will output a column vector and (2.1) a vector of column vectors.\n- if `frange` points to a single frequency, (1.1) will output a row vector and (2.1) a vector of row vectors.\n- if both the above two conditions hold, (1.1) will output a real number and (2.1) a vector.\n- if `frange` points to a single frequency, (1.2), (1.3) will output a matrix and (2.2), (2.3) a vector of matrices.\n- If `frange` points to a single frequency band, (3.1), (3.2), (3.3) will output a row vector and (4.1), (4.2), (4.3) a vector of row vectors.\n- If `trange` points to a single time sample, (3.1), (3.2), (3.3) will output a column vector and (4.1), (4.2), (4.3) a vector of column vectors.\n- if both the above two conditions hold, (3.1), (3.2), (3.3) will output a number and (4.1), (4.2), (4.3) a vector.\n\nMethod (2) and (4) allows the following *optional keyword arguments*:\n\n`w`, a ``k``-vector of non-negative integers or real numbers, where ``k`` is the\nnumbers of objects hold in the input [FDobjectsVector](@ref) or\n[TFobjectsVector](@ref). `w` is a vector of weights for the regions extracted from\nthe input objects. By default, no weights are assigned.\n\n`check`, a boolean. If it is true (default), it is checked that the non-data fields\nof the input objects are all the same (for example, sampling rate, bandwidth, etc.).\nSet it to false to improve speed.\n\n**See also**: [`mean`](@ref).\n\n**Examples**:\n```\nusing FourierAnalysis\n\n# example with univariate Spectra objects (one series -> one spectrum)\nsr, t, f, a = 128, 256, 10, 1\n# create a sinusoidal superimposed to white noise\nv=sinusoidal(a, f, sr, t*16, 0) + randn(t*16)\n# compute univariate spectra\nΣ=spectra(v, sr, t)\n# spectra in between 8Hz and 12Hz\ns=extract(Σ, (8, 12))\n# spectra in between 8Hz and 12.5Hz\ns=extract(Σ, (8, 12.5))\n# spectra at 10Hz\ns=extract(Σ, 10) # or s=extract(S, (10, 10))\n# these two expressions are equivalent: s=extract(Σ, :), s=Σ.y\n\n# example with multivariate spectra (several series -> several spectra)\nΣ=spectra(hcat(v, v+randn(t*16)), sr, t)\n# spectra in between 8Hz and 12Hz\nS=extract(Σ, (8, 12))\n# spectra at 10Hz\nS=extract(Σ, 10)\n\n# example with CrossSpectra objects (the same goes for Coherence objects)\nX=broadcast(+, v, randn(t*16, 3))*randn(3, 3)\nΣ=crossSpectra(X, sr, t)\n# cross-spectra in between 8Hz and 12Hz (Hermitian matrices)\nS=extract(Σ, (8, 12))\nΣ=crossSpectra(X, sr, t; tril=true)\n# cross-spectra in between 8Hz and 12Hz (LowerTriangular matrices)\nS=extract(Σ, (8, 12))\n\n# example with multiple cross-spectra\nX2=broadcast(+, v, randn(t*16, 3))*randn(3, 3)\nΣ=crossSpectra([X, X2], sr, t) # this is a CrossSpectraVector\nS=extract(Σ, (8, 12); w=[0.4, 0.6])\n# now S[1] holds the cross-spectra in range 8-12Hz for X\n# and S[2] holds the cross-spectra in range 8-12Hz for X2\n\n# example with time-frequency objects\n# (work in the same way for TFAnalyticSignal, TFAmplitude and TFPhase)\nY = TFanalyticsignal(v, sr, t)\n# analytic signal within frequencies 8Hz and 12Hz and time samples 1 to 64.\nAS=extract(Y, (8, 12), (1, 64))\n\n# all analytic signal within frequencies 8Hz and 12Hz.\nAS=extract(Y, (8.0, 12), :) # accept integers and reals for frequencies\n\n# all analytic signal within time samples 1 to 64.\nAS=extract(Y, :, (1, 64))\n\n# example with multiple time-frequency objects\n# (notice how the type of the output changes)\nY = TFanalyticsignal([v, v+randn(t*16)], sr, t)\nAS=extract(Y, (8, 12), (1, 64))\nAS=extract(Y, (8), :)\nAS=extract(Y, 8, 2)\n```\n\"\"\"\nextract(S::FDobjects, frange::fInterval) =\n    if (_frange=_getfrange(S, frange, \"extract\")) ≠ 0\n        return _extract(S, _frange)\n    end\n\nextract(𝐒::FDobjectsVector, frange::fInterval;\n        w::Vector=[], check::Bool=true) =\n    if (_frange=_getfrange(𝐒, frange, \"extract\"; check=check)) ≠ 0\n        return isempty(w) ? [_extract(S, _frange) for S ∈ 𝐒] :\n                            [ω*_extract(S, _frange) for (ω, S) ∈ zip(w, 𝐒)]\n    end\n\n\n\"\"\"\n```\n(1)\nfunction mean(S :: FDobjects,\n         frange :: fInterval)\n\n(2)\nfunction mean(𝐒 :: FDobjectsVector,\n         frange :: fInterval;\n        w :: Vector = [],\n    check :: Bool   = true)\n\n(3)\nfunction mean(Y :: TFobjects,\n         frange :: fInterval,\n         trange :: tInterval)\n\n(4)\nfunction mean(𝒀 :: TFobjectsVector,\n         frange :: fInterval,\n         trange :: tInterval;\n          w :: Vector = [],\n      check :: Bool   = true)\n```\n\nReturn the mean of data in a frequency region from [FDobjects](@ref) and data in a\ntime-frequency region from [TFobjects](@ref). The frequency and time region\nare indicated by `frange` and `trange`, which are of type [fInterval](@ref)\nand [fInterval](@ref), respectively.\n\nThe complete input/output types for this function is reported in the following table:\n\n|method|        input object           |                   output                |\n|:----:|:------------------------------|:---------------------------------------------|\n|(1.1)| [Spectra](@ref)                | a vector holding the mean spectra in `frange`¹|\n|(1.2)| [CrossSpectra](@ref)           | a complex matrix holding the mean cross-spectra in `frange`²|\n|(1.3)| [Coherence](@ref)              | a real matrix holding the mean coherence in `frange`²|\n|(2.1)| [SpectraVector](@ref)          | a vector of vectors of type (1.1)|\n|(2.2)| [CrossSpectraVector](@ref)     | a vector of matrices of type (1.2)|\n|(2.3)| [CoherenceVector](@ref)        | a vector of matrices of type (1.3)|\n|(3.1)| [TFAnalyticSignal](@ref)       | a complex number holding the mean analytic signal in [`frange`, `trange`]|\n|(3.2)| [TFAmplitude](@ref)            | a real number holding the mean amplitude in [`frange`, `trange`]|\n|(3.3)| [TFPhase](@ref)                | a real number holding the mean phase in [`frange`, `trange`]|\n|(4.1)| [TFAnalyticSignalVector](@ref) | a vector of numbers of type (3.1)|\n|(4.2)| [TFAmplitudeVector](@ref)      | a vector of numbers of type (3.2)|\n|(4.3)| [TFPhaseVector](@ref)          | a vector of numbers of type (3.3)|\nlegend: ¹*each element of the vector refers to a time-series on which the spectra have been computed.*\n² *depending on how the objects has been created, the matrices may be either\nHermitian or LowerTriangular.*\n\nMethod (2) and (4) allows the following *optional keyword arguments*:\n\n`w`, a ``k``-vector of non-negative integers or real numbers, where ``k`` is the\nnumbers of objects hold in the input [FDobjectsVector](@ref) or\n[TFobjectsVector](@ref). `w` is a vector of weights for the means extracted from\nthe input objects. By default, no weights are assigned.\n\n`check`, a boolean. If it is true (default), it is checked that the non-data fields\nof the input objects are all the same (for example, sampling rate, bandwidth, etc.).\n\n**See also**: [`extract`](@ref).\n\n**Examples**:\n```\nusing FourierAnalysis, Plots\n\n# example with univariate Spectra objects (one series -> one spectrum)\nsr, t, f, a = 128, 256, 10, 1\n# create a sinusoidal superimposed to white noise\nv=sinusoidal(a, f, sr, t*16, 0) + randn(t*16)\n# compute the spectrum\nΣ=spectra(v, sr, t)\n# mean spectrum in between 8Hz and 12Hz\ns=mean(Σ, (8, 12))\n# mean spectrum in between 8Hz and 12.5Hz\ns=mean(Σ, (8, 12.5))\n\n# example with multivariate spectra (several series -> several spectra)\nΣ=spectra(hcat(v, v+randn(t*16)), sr, t)\n# mean spectra in between 8Hz and 12Hz\nS=mean(Σ, (8, 12))\n# mean spectra at 10Hz, i.e., the spectra at 10Hz\nS=mean(Σ, 10)\n\n# example with CrossSpectra objects (the same goes for Coherence objects)\nX=broadcast(+, v, randn(t*16, 3))*randn(3, 3)\nΣ=crossSpectra(X, sr, t)\n# mean cross-spectra in between 8Hz and 12Hz (an Hermitian matrix)\nS=mean(Σ, (8, 12))\nΣ=crossSpectra(X, sr, t; tril=true)\n# mean cross-spectra in between 8Hz and 12Hz (a LowerTriangular matrix)\nS=mean(Σ, (8.0, 12.0)) # accept integers and reals for frequencies\n\n# example with multiple CrossSpectra objects\nX2=broadcast(+, v, randn(t*16, 3))*randn(3, 3)\nΣ=crossSpectra([X, X2], sr, t) # this is a CrossSpectraVector\nS=mean(Σ, (8, 12); w=[0.4, 0.6])\n# now S[1] will hold the mean cross-spectrum in range 8-12Hz for X\n# and S[2] will hold the mean cross-spectrum in range 8-12Hz for X2\n\n# example with time-frequency objects\n# (work in the same way for TFAnalyticSignal, TFAmplitude and TFPhase)\nY = TFanalyticsignal(v, sr, t)\n# mean analytic signal within frequencies 8Hz and 12Hz and time samples 1 to 64.\nas=mean(Σ, (8, 12), (1, 64))\n# mean analytic signal within frequencies 8Hz and 12Hz.\nas=mean(Σ, (8, 12), :)\n# mean analytic signal within time samples 1 to 64.\nas=mean(Σ, :, (1, 64))\n\n# example with multiple time-frequency objects\nY = TFanalyticsignal([v, v+randn(t*16)], sr, t)\nAS=mean(Y, (8, 12), (1, 64))\n# get the mean across TFobjects of those means\nm=mean(mean(Y, (8, 12), (1, 64)))\nAS=mean(Y, (8), :)\nAS=mean(Y, 8, 2)\n```\n\"\"\"\nmean(S::FDobjects, frange::fInterval) =\n    if (_frange=_getfrange(S, frange, \"mean\")) ≠ 0\n        return _mean(S, _frange)\n    end\n\nmean(𝐒::FDobjectsVector, frange::fInterval;\n     w::Vector=[], check::Bool=true) =\n    if (_frange=_getfrange(𝐒, frange, \"mean\"; check=check)) ≠ 0\n        return isempty(w) ? [_mean(S, _frange) for S ∈ 𝐒] :\n                            [ω*_mean(S, _frange) for (ω, S) ∈ zip(w, 𝐒)]\n    end\n\n### Time-Frequency-domain data extraction and averaging ###\n###############################################################################\n\nfunction _getfrange(Y::TFobjects, frange::fInterval, funcname::String)\n    # find frequencies in filterbanks\n    hb=Y.bandwidth/2\n    if      isa(frange, IntOrReal)\n            (Y.flabels[1]-hb)<=frange<=(Y.flabels[end]+hb) ? (return max(1, (findmin([abs(f-frange) for f∈Y.flabels])[2])):min(length(Y.flabels), (findmin([abs(f-frange)  for f∈Y.flabels])[2]))) :\n            @error 📌*\", \"*funcname*\" function passed invalid frange Int or Real argument. The frequency must be comprised between $((Y.flabels[1]-hb)) and $((Y.flabels[end]+hb))\" frange\n            return 0\n    elseif  isa(frange, Colon)\n            return 1:size(Y.y, 1)\n    elseif  isa(frange, Tuple{IntOrReal, IntOrReal})\n        if      frange[1]>frange[2]\n                    @error 📌*\", \"*funcname*\" function passed invalid frange 2-tuple argument. The second element cannot be inferior to the first\" frange[1] frange[2]\n                    return 0\n        elseif  frange[1]<(Y.flabels[1]-hb) || frange[2]>(Y.flabels[end]+hb)\n                    @error 📌*\", \"*funcname*\" function passed invalid frange 2-tuple argument. The two frequencies must be comprised between $(Y.flabels[1]-hb) and $(Y.flabels[end]+hb)\" frange[1] frange[2]\n                    return 0\n        else        return max(1, (findmin([abs(f-frange[1]) for f∈Y.flabels])[2])):min(length(Y.flabels), (findmin([abs(f-frange[2])  for f∈Y.flabels])[2]))\n        end\n    end\nend\n\n\nfunction _gettrange(Y::TFobjects, trange::tInterval, funcname::String)\n    if      isa(trange, Int)\n            1<=trange<=size(Y.y, 2) ? (return trange:trange) :\n            @error 📌*\", \"*funcname*\" function passed invalid trange Int argument. The time sample must be comprised between 1 and $(size(Y.y, 2))\" trange\n            return 0\n    elseif  isa(trange, Colon)\n            return 1:size(Y.y, 2)\n    elseif  isa(trange, Tuple{Int, Int})\n        if      trange[1]>trange[2]\n                    @error 📌*\", \"*funcname*\" function passed invalid trange 2-tuple argument. The second element cannot be inferior to the first\" trange[1] trange[2]\n                    return 0\n        elseif  trange[1]<1 || trange[2]>size(Y.y, 2)\n                    @error 📌*\", \"*funcname*\" function passed invalid trange 2-tuple argument. The time limits in samples must be comprised between 1 and $(size(Y.y, 2))\" trange[1] trange[2]\n                    return 0\n        else        return trange[1]:trange[2]\n        end\n    end\nend\n\n_getftrange(Y::TFobjects, frange::fInterval, trange::tInterval, funcname::String) =\n    _getfrange(Y, frange, funcname), _gettrange(Y, trange, funcname)\n\n\nfunction extract(Y::TFobjects, frange::fInterval, trange::tInterval)\n    _frange, _trange = _getftrange(Y, frange, trange, \"extract\")\n    if _frange ≠ 0 && _trange ≠ 0\n        _isnull(_frange, _trange) ? Y.y[first(_frange), first(_trange)] :\n                                    copy(Y.y[_frange, _trange])\n    end\nend\n\nfunction mean(Y::TFobjects, frange::fInterval, trange::tInterval)\n    _frange, _trange = _getftrange(Y, frange, trange, \"mean\")\n    if _frange ≠ 0 && _trange ≠ 0\n        return mean(view(Y.y, _frange, _trange))\n    end\nend\n\n_getftrange(𝒀::TFobjectsVector, frange::fInterval, trange::tInterval, funcname::String;\n            check::Bool=true) =\n    check ? (sameParams(𝒀, funcname) ? _getftrange(𝒀[1], frange, trange, funcname) : 0) :\n    _getftrange(𝒀[1], frange, trange, funcname)\n\nextract(𝒀::TFobjectsVector, frange::fInterval, trange::tInterval;\n        w::Vector=[], check::Bool=true) =\n    if      check && frange isa Colon && !_allsame([size(Y.y, 1) for Y ∈ 𝒀])\n            @error 📌*\", extract function. In order of using a column (:) as `frange` argument, the number of rows (frequencies) must be identical in all time-frequency objects\"\n    elseif  check && trange isa Colon && !_allsame([size(Y.y, 2) for Y ∈ 𝒀])\n            @error 📌*\", extract function. In order of using a column (:) as `trange` argument, the number of columns (time samples) must be identical in all time-frequency objects\"\n    elseif  ((_frange, _trange)=_getftrange(𝒀, frange, trange, \"extract\"; check=check)) ≠ (0, 0)\n            if _isnull(_frange, _trange)\n                isempty(w) ? [Y.y[first(_frange), first(_trange)] for Y ∈ 𝒀] :\n                             [ω*Y.y[first(_frange), first(_trange)] for (ω, Y) ∈ zip(w, 𝒀)]\n            else\n                isempty(w) ? [Y.y[_frange, _trange] for Y ∈ 𝒀] :\n                             [ω*Y.y[_frange, _trange] for (ω, Y) ∈ zip(w, 𝒀)]\n            end\n    end\n\n\nmean(𝒀::TFobjectsVector, frange::fInterval, trange::tInterval;\n     w::Vector=[], check::Bool=true) =\n    if      check && frange isa Colon && !_allsame([size(Y.y, 1) for Y ∈ 𝒀])\n            @error 📌*\", extract function. In order of using a column (:) as `frange` argument, the number of rows (frequencies) must be identical in all time-frequency objects\"\n    elseif  check && trange isa Colon && !_allsame([size(Y.y, 2) for Y ∈ 𝒀])\n            @error 📌*\", extract function. In order of using a column (:) as `trange` argument, the number of columns (time samples) must be identical in all time-frequency objects\"\n    elseif  ((_frange, _trange)=_getftrange(𝒀, frange, trange, \"mean\"; check=check)) ≠ (0, 0)\n            return isempty(w) ? [mean(view(Y.y, _frange, _trange)) for Y ∈ 𝒀] :\n                                [ω*mean(view(Y.y, _frange, _trange)) for (ω, Y) ∈ zip(w, 𝒀)]\n    end\n\nextr=extract\n\n### Band-pass Averages ###\n\n\"\"\"\n```\nfunction bands(S :: Union{FDobjects, FDobjectsVector}\n       bandwidth :: IntOrReal)\n```\n\nReturn band-pass average of spectral, cross-spectral or coherence estimates\nin equally spaced band-pass regions with the given `bandwidth`.\n`bandwidth` can be given as an integer or as a real number. See [`bbands`](@ref)\nfor details on the definition of band-pass regions.\n\nBand-pass average is not supported for time-frequency objects as for those\nobjects a similar averaging is natively avaiable using argument `bandwidth`\nin their constructors.\n\nThe output of this function is as it follows:\n- for univariate [Spectra](@ref) objects (i.e., those hodling one spectrum only), a real column vector,\n- for multivariate [Spectra](@ref) objects, a real matrix,\n- for [SpectraVector](@ref) objects, a vector of the above,\n- for [CrossSpectra](@ref) and [Coherence](@ref) objects, a vector of Hermitian or LowerTriangular matrices, depending on how the object has been cosntructed,\n- for [CrossSpectraVector](@ref) and [CoherenceVector](@ref) objects, a vector  of the above.\n\n**See**: [`bbands`](@ref).\n\n**Examples**:\n```\nusing FourierAnalysis, Plots\n\n# example with univariate Spectra objects (one series -> one spectrum)\nsr, t, f, a = 128, 256, 10, 1\n# create a sinusoidal superimposed to white noise\nv=sinusoidal(a, f, sr, t*16, 0) + randn(t*16)\n# compute the spectrum\nΣ=spectra(v, sr, t)\n# mean spectra in 2Hz-band-pass regions\nb=bands(Σ, 2)\nplot(b)\n\n# example with multivariate spectra (several series -> several spectra)\nΣ=spectra(hcat(v, v+randn(t*16), v+randn(t*16) ), sr, t)\n# mean spectra in 2Hz-band-pass regions for all time-series\nb=bands(Σ, 2)\nplot(b)\n# plot mean spectra in 2Hz-band-pass regions for time-series 2 and 3 only\nplot(bands(Σ, 2)[:, 2:3])\n\n# example with CrossSpectra objects (the same goes for Coherence objects)\nX=broadcast(+, v, randn(t*16, 3))*randn(3, 3)\nΣ=crossSpectra(X, sr, t)\n# mean cross-spectra in 4Hz-band-pass regions\nB=bands(Σ, 4)\n\n# example with multiple CrossSpectra objects\nX2=broadcast(+, v, randn(t*16, 3))*randn(3, 3)\nΣ=crossSpectra([X, X2], sr, t) # this is a CrossSpectraVector\n# mean cross-spectra in 4Hz-band-pass regions for all cross-spectra objects\nB=bands(Σ, 4)\n```\n\"\"\"\nfunction bands(S::Spectra, bandwidth::IntOrReal)\n    if (bands=bbands(S.sr, S.wl, bandwidth; DC=S.DC)) isa Nothing return S end\n    r, n=length(bands)-1, size(S.y, 2)\n    if n==1 return [mean(S.y[bands[b]:bands[b+1]]) for b=1:r]\n    else\n        Y=Matrix{eltype(S.y)}(undef, r, n)\n        @inbounds for i=1:n Y[:, i]=[mean(S.y[bands[b]:bands[b+1], i]) for b=1:r] end\n        return Y\n    end\nend # input Spectra, Output a vector or a Matrix\n\n\nbands(𝐒::SpectraVector, bandwidth::IntOrReal) =\n    [bands(S, bandwidth) for S ∈ 𝐒] # output a vector of vectors or matrices\n\nfunction bands(S::Union{CrossSpectra, Coherence}, bandwidth::IntOrReal)\n    if (bands=bbands(S.sr, S.wl, bandwidth; DC=S.DC)) isa Nothing return S end\n    r=length(bands)-1\n    mattype = S.tril ? LowerTriangular : Hermitian\n    return typeof(S.y)([mattype(mean(S.y[i] for i=bands[b]:bands[b+1])) for b=1:r])\nend # output: a vector of LowerTriangular (if tril=true) or Hermitian (if tril=false) matrices\n\n\nbands(𝐒::Union{CrossSpectraVector, CoherenceVector}, bandwidth::IntOrReal) =\n    [bands(S, bandwidth) for S ∈ 𝐒] # output: a vector of vectors of LowerTriangular (if tril=true) or Hermitian (if tril=false) matrices\n\n\n# internal function: used by functions that may execute in multi-threading\n# to decide to so so or not.\n# The multi-threading is to be done for a for looping over `n` elements.\n# Return true if `n` is large enough to justify multi-threading (n>thr, where\n# `thr` is the number of threads Julia is instructed to use) and thr>1,\n# otherwise return false.\nfunction _thread(⏩, n)\n    thr = nthreads() # of threads Julia is instructed to use\n    ⏩ && n>=thr*2 && thr > 1 ? (return true) : (return false)\nend\n\n# check that all elements of a vector are equal. General function\n# taken from https://stackoverflow.com/questions/47564825/check-if-all-the-elements-of-a-julia-array-are-equal\n_allsame(x) = all(y -> y == (first(x)), x)\n\n_isnull(frange::UnitRange{Int64}) = first(frange)==last(frange)\n_isnull(frange::UnitRange{Int64}, trange::UnitRange{Int64}) =\n    (first(frange)==last(frange)) & (first(trange)==last(trange))\n", "meta": {"hexsha": "1986a0507ef7c84a50690f8ef70ff09cc58c5425", "size": 60369, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tools.jl", "max_stars_repo_name": "PallHaraldsson/FourierAnalysis.jl", "max_stars_repo_head_hexsha": "5a0c73816b8e1c7a531dfabdb56ae1d0971bb8d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tools.jl", "max_issues_repo_name": "PallHaraldsson/FourierAnalysis.jl", "max_issues_repo_head_hexsha": "5a0c73816b8e1c7a531dfabdb56ae1d0971bb8d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools.jl", "max_forks_repo_name": "PallHaraldsson/FourierAnalysis.jl", "max_forks_repo_head_hexsha": "5a0c73816b8e1c7a531dfabdb56ae1d0971bb8d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9440603394, "max_line_length": 229, "alphanum_fraction": 0.639566665, "num_tokens": 19050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7971209691630586}}
{"text": "export CubicSplineInterpolator, BicubicSplineInterpolator\n\n#-------------------------------------------------------------------------------\n# piecewise cubics with continuous derivatives (splines!)\n\nstruct CubicSplineInterpolator{T,B} <: OneDimensionalInterpolator\n    r::InterpolatorRange{T}\n    coef::Vector{NTuple{4,T}}\n    boundaries::B\n    i::RefValue{Int64} #previous cell index\nend\n\n#-------------------------------------------------------------------------------\n# constructors\n\n\"\"\"\n    CubicSplineInterpolator(x, y, boundaries=StrictBoundaries())\n\nConstruct a `CubicSplineInterpolator` for the points defined by coordinates `x` and values `y`. This constructor creates a natural spline, where the second derivative is set to zero at the boundaries.\n\"\"\"\nfunction CubicSplineInterpolator(x, y, boundaries::AbstractBoundaries=StrictBoundaries())\n    #construct the underlying range, triggering some checks\n    T = promote_type(eltype(x), eltype(y))\n    r = InterpolatorRange(x, y)\n    n = r.n\n    #compute coefficients\n    #Burden, Richard L., and J. Douglas Faires. Numerical Analysis. 2011.\n    a = collect(T, r.y)\n    b = zeros(T, n - 1)\n    d = zeros(T, n - 1)\n    h = diff(r.x)\n    α = zeros(T, n-1)\n    for i = 2:n-1\n        α[i] = 3*(a[i+1] - a[i])/h[i] - 3*(a[i] - a[i-1])/h[i-1]\n    end\n    c = zeros(T, n)\n    l = ones(T, n)\n    μ = zeros(T, n)\n    z = zeros(T, n)\n    l[1] = 1\n    for i = 2:n-1\n        l[i] = 2*(x[i+1] - x[i-1]) - h[i-1]*μ[i-1]\n        μ[i] = h[i]/l[i]\n        z[i] = (α[i] - h[i-1]*z[i-1])/l[i]\n    end\n    for j = n-1:-1:1\n        c[j] = z[j] - μ[j]*c[j+1]\n        b[j] = (a[j+1] - a[j])/h[j] - h[j]*(c[j+1] + 2*c[j])/3\n        d[j] = (c[j+1] - c[j])/(3*h[j])\n    end\n    a = a[1:end-1]\n    c = c[1:end-1]\n    #static arrays\n    coef = Vector{NTuple{4,T}}(undef,n-1)\n    for i = 1:n-1\n        coef[i] = (a[i], b[i], c[i], d[i])\n    end\n    #construct the object\n    CubicSplineInterpolator(r, coef, boundaries, Ref(1))\nend\n\n\"\"\"\n    CubicSplineInterpolator(x, y, dy₁, dyₙ, boundaries=StrictBoundaries())\n\nConstruct a `CubicSplineInterpolator` for the points defined by coordinates `x` and values `y`. This constructor creates a clamped spline, where the first derivatives at the boundaries are set by `dy₁` and `dyₙ`.\n\"\"\"\nfunction CubicSplineInterpolator(x,\n                                 y,\n                                 dy₁::Real,\n                                 dyₙ::Real,\n                                 boundaries::AbstractBoundaries=StrictBoundaries())\n    #construct the underlying range, triggering some checks\n    T = promote_type(eltype(x), eltype(y))\n    r = InterpolatorRange(x, y)\n    n = r.n\n    #compute coefficients\n    #Burden, Richard L., and J. Douglas Faires. Numerical Analysis. 2011.\n    a = collect(T, r.y)\n    b = zeros(T, n - 1)\n    d = zeros(T, n - 1)\n    h = diff(r.x)\n    α = zeros(T, n)\n    α[1] = 3*(a[2] - a[1])/h[1] - 3*dy₁\n    for i = 2:n-1\n        α[i] = 3*(a[i+1] - a[i])/h[i] - 3*(a[i] - a[i-1])/h[i-1]\n    end\n    α[n] = 3*dyₙ - 3*(a[n] - a[n - 1])/h[n-1]\n    c = zeros(T, n)\n    l = zeros(T, n)\n    μ = zeros(T, n)\n    z = zeros(T, n)\n    l[1] = 2*h[1]\n    μ[1] = 0.5\n    z[1] = α[1]/l[1]\n    for i = 2:n-1\n        l[i] = 2*(x[i+1] - x[i-1]) - h[i-1]*μ[i-1]\n        μ[i] = h[i]/l[i]\n        z[i] = (α[i] - h[i-1]*z[i-1])/l[i]\n    end\n    l[n] = h[n-1]*(2 - μ[n-1])\n    z[n] = (α[n] - h[n-1]*z[n-1])/l[n]\n    c[n] = z[n]\n    for j = n-1:-1:1\n        c[j] = z[j] - μ[j]*c[j+1]\n        b[j] = (a[j+1] - a[j])/h[j] - h[j]*(c[j+1] + 2*c[j])/3\n        d[j] = (c[j+1] - c[j])/(3*h[j])\n    end\n    a = a[1:end-1]\n    c = c[1:end-1]\n    #static arrays\n    coef = Vector{NTuple{4,T}}(undef,n-1)\n    for i = 1:n-1\n        coef[i] = (a[i], b[i], c[i], d[i])\n    end\n    #construct the object\n    CubicSplineInterpolator(r, coef, boundaries, Ref(1))\nend\n\n\"\"\"\n    CubicSplineInterpolator(f, xa, xb, n, boundaries=StrictBoundaries())\n\nConstruct a `CubicSplineInterpolator` for the function `f` using `n` evenly spaced function evaluations in the range [`xa`,`xb`]. A natural spline is created.\n\"\"\"\nfunction CubicSplineInterpolator(f,\n                                 xa::Real,\n                                 xb::Real,\n                                 n::Int,\n                                 boundaries::AbstractBoundaries=StrictBoundaries())\n    linstruct(CubicSplineInterpolator, f, xa, xb, n, boundaries)\nend\n\nfunction (ϕ::CubicSplineInterpolator)(x)\n    #enforce boundaries if desired\n    ϕ.boundaries(x, ϕ.r.xa, ϕ.r.xb)\n    #find the interpolation point\n    i = findcell(x, ϕ)\n    #offset from the nearest lower point\n    @inbounds ξ = x - ϕ.r.x[i]\n    #evaluate polynomial\n    @inbounds ϕ.coef[i][1] + ϕ.coef[i][2]*ξ + ϕ.coef[i][3]*ξ^2 + ϕ.coef[i][4]*ξ^3\nend\n\nBase.getindex(ϕ::CubicSplineInterpolator, i) = ϕ.r.y[i]\nfunction Base.copy(ϕ::CubicSplineInterpolator)\n    CubicSplineInterpolator(ϕ.r, ϕ.coef, ϕ.boundaries, Ref(1))\nend\n", "meta": {"hexsha": "ffc32d9425a74150aec0b7ddff63fced79236f9e", "size": 4904, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spline.jl", "max_stars_repo_name": "wordsworthgroup/BasicInterpolators.jl", "max_stars_repo_head_hexsha": "1a43e6e657377ee9de53c721cf58141363036e78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-03T14:12:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-05T02:27:30.000Z", "max_issues_repo_path": "src/spline.jl", "max_issues_repo_name": "markmbaum/BasicInterpolators.jl", "max_issues_repo_head_hexsha": "6986d0418913b39207ccc7825a7f00822e434ef4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-16T15:16:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T15:05:48.000Z", "max_forks_repo_path": "src/spline.jl", "max_forks_repo_name": "wordsworthgroup/BasicInterpolators.jl", "max_forks_repo_head_hexsha": "1a43e6e657377ee9de53c721cf58141363036e78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3605442177, "max_line_length": 212, "alphanum_fraction": 0.5303833605, "num_tokens": 1666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388754, "lm_q2_score": 0.8615382094310355, "lm_q1q2_score": 0.7971209676499937}}
{"text": "using JuMP, LinearAlgebra, SparseArrays\nusing SCS\nusing MosekTools\nconst MOI = JuMP.MathOptInterface\n\n# formulating LMI constraint with sparse matrices\n#   https://github.com/JuliaOpt/JuMP.jl/issues/1950\n# We are trying to solve:\n# min c' x\n# s.t.  A0 + A1 * x[1] + A2 * x[2] ⪰ 0\n\nm = 2\nA0 = sparse([1. 0; 0 3])\nA1 = sparse([0. 1; 1 -2])\nA2 = sparse([5. -1; -1 0])\nB = [A1, A2]\nc = [1.; 1]\n\n# A0 = [1. 0; 0 3]\n# A1 = [0. 1; 1 -2]\n# A2 = [5. -1; -1 0]\n# B = [A1, A2]\n# c = [1.; 1]\n\n# model = JuMP.Model(with_optimizer(SCS.Optimizer, verbose = 0));\nmodel = JuMP.Model(with_optimizer(Mosek.Optimizer, QUIET=false))\n\n@variable(model, x[1:m]);\n@objective(model, Min, c' * x);\n\n# formulate LMI constraint A0 + A1 x[1] + A2 x[2] in PSDCone\n# works\nK = A0 + sum(B[k] .* x[k] for k in 1:m)\n@SDconstraint(model, con1,  Symmetric(K) >= 0);\n# @constraint(model, con1,  Symmetric(K) in JuMP.PSDCone());\n\n# throws error\n# @constraint(model, con2,  A0 + sum(B[k] .* x[k] for k in 1:m) in JuMP.PSDCone());\n# @SDconstraint(model, con1,  K >= 0);\n\nJuMP.optimize!(model)\n@show JuMP.objective_value(model)\n\n@show JuMP.termination_status(model) == MOI.OPTIMAL\n@show JuMP.primal_status(model) == MOI.FEASIBLE_POINT\n\nL = JuMP.value.(K)\n# L = A0 + sum(B[k] .* obj_x[k] for k in 1:m)\n@show isposdef(L)\n", "meta": {"hexsha": "272755a5d3e77542501eb0555b4750d61cdd5271", "size": 1277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_LMI_sparse.jl", "max_stars_repo_name": "yijiangh/StabTrussTopOpt.jl", "max_stars_repo_head_hexsha": "466bc9e716f6ce79ea95134fb2d63d4446bf74e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-24T22:52:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-06T02:50:15.000Z", "max_issues_repo_path": "test/test_LMI_sparse.jl", "max_issues_repo_name": "yijiangh/StabTrussTopOpt.jl", "max_issues_repo_head_hexsha": "466bc9e716f6ce79ea95134fb2d63d4446bf74e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_LMI_sparse.jl", "max_forks_repo_name": "yijiangh/StabTrussTopOpt.jl", "max_forks_repo_head_hexsha": "466bc9e716f6ce79ea95134fb2d63d4446bf74e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.54, "max_line_length": 83, "alphanum_fraction": 0.6296006265, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7971209553478931}}
{"text": "struct Connection \n    from\n    to\n    dist\nend\n\nfunction euclidean(v, u)\n    v .- u .|> (x -> x * x) |> sum |> sqrt\nend\n\nfunction getnearest(datapoints, linked, unlinked)\n    mindist = Inf \n    from = nothing \n    to = nothing \n    for i in linked\n        for j in unlinked\n            dist = euclidean(datapoints[i,:], datapoints[j,:])\n            if dist < mindist \n                mindist = dist \n                from = i\n                to = j\n            end\n        end\n    end \n    return Connection(from, to, mindist)\nend\n\nfunction mst(datapoints)\n    result = []\n    n, p = size(datapoints)\n    allindices = collect(1:n)\n    linkedset = [1]\n\n    while true\n        unlinkedset = setdiff(allindices, linkedset)\n        if length(unlinkedset) == 0\n            break\n        end\n        conn = getnearest(datapoints, linkedset, unlinkedset)\n        push!(result, conn)\n        push!(linkedset, conn.to) \n    end \n    return result\nend\n\nfunction cutree(tree)\n    n = length(tree)\n    maxdist = maximum(x -> x.dist, tree)\n    part1 = []\n    part2 = []\n    i = 1\n    while i < n\n        if tree[i].dist < maxdist\n            push!(part1, tree[i])\n        else \n            break\n        end\n        i += 1\n    end \n    \n    for j = (i+1):n\n        push!(part2, tree[j])\n    end\n    return (part1, part2)\nend", "meta": {"hexsha": "f6062d4a8c307602a4f3194b9b547b8dbfe33dd2", "size": 1311, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mst.jl", "max_stars_repo_name": "jbytecode/divpopga", "max_stars_repo_head_hexsha": "dcd31725deafc3c473f12082ca3b381f9ce29ed4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mst.jl", "max_issues_repo_name": "jbytecode/divpopga", "max_issues_repo_head_hexsha": "dcd31725deafc3c473f12082ca3b381f9ce29ed4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-01-04T10:48:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-04T16:56:30.000Z", "max_forks_repo_path": "src/mst.jl", "max_forks_repo_name": "jbytecode/divpopga", "max_forks_repo_head_hexsha": "dcd31725deafc3c473f12082ca3b381f9ce29ed4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-04T08:01:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T11:19:22.000Z", "avg_line_length": 20.1692307692, "max_line_length": 62, "alphanum_fraction": 0.5141113654, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294984, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7970684665956844}}
{"text": "T = 250\nΣ = [0.2 0.0; 0.0 0.8]\nt = range(0, 20, length = T)\ns = sin.(t)\ny = s * [1 1] + randn(T, 2) * cholesky(Σ).L\n\nH = Matrix(1.0I, 2, 2)\nA = Matrix(1.0I, 2, 2)\nQ = Matrix(0.01*I, 2, 2)\nx = [0.0, 0.0]\nP = Matrix(1000.0I, 2, 2)\n\nm = Model(y, H, A, Q, Σ, x, P)\nkf = kalmanfilter(m)\nks = kalmansmoother(m, kf.priors, kf.posteriors)\n\nusing Plots\nl = @layout [a b]\np1 = scatter(t, y[:, 1], label = \"Measurement\", legend = :bottom, ylim = [-5, 4],\n        title = \"Variable 1\", markerstrokewidth = 0, markercolor = \"black\", foreground_color_legend = nothing)\np1 = plot!(t, s, label = \"Noiseless signal\", linewidth = 3, color = \"grey\")\np1 = plot!(t, ks.μ[:, 1], label = \"Smoother\", linewidth = 2, color = :red)\n\np2 = scatter(t, y[:, 2], ylim = [-5, 4], legend = false, title = \"Variable 2\", markerstrokewidth = 0, markercolor = \"black\", foreground_color_legend = nothing)\np2 = plot!(t, s, linewidth = 3, color = \"grey\")\np2 = plot!(t, ks.μ[:, 2], linewidth = 2, color = :red)\n\nplot(p1, p2, layout = l)", "meta": {"hexsha": "eaf9b6c7b81414a4f1b8d6222349e91fa9974f44", "size": 995, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/multivariate_local_level.jl", "max_stars_repo_name": "madskoefoed/KalmanFilter.jl", "max_stars_repo_head_hexsha": "057347af3ddc2cceb3791e9474b3b2d6bc6a61c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/multivariate_local_level.jl", "max_issues_repo_name": "madskoefoed/KalmanFilter.jl", "max_issues_repo_head_hexsha": "057347af3ddc2cceb3791e9474b3b2d6bc6a61c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/multivariate_local_level.jl", "max_forks_repo_name": "madskoefoed/KalmanFilter.jl", "max_forks_repo_head_hexsha": "057347af3ddc2cceb3791e9474b3b2d6bc6a61c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5357142857, "max_line_length": 159, "alphanum_fraction": 0.5899497487, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338068793908, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7970526900670519}}
{"text": "#=\r\n\r\nAuthor: Shunsuke Hori\r\n\r\n=#\r\n\r\nusing QuantEcon\r\n\r\n\"\"\"\r\ng: input policy function\r\ngrid: grid points\r\nβ: discount factor\r\nu_prime: derivative of utility function\r\nf: production function\r\nf_prime: derivative of production function\r\nshocks::shock draws, used for Monte Carlo integration to compute expectation\r\nKg: output value is stored\r\n\"\"\"\r\nfunction coleman_operator!(g::AbstractVector,\r\n                           grid::AbstractVector,\r\n                           β::AbstractFloat,\r\n                           u_prime::Function,\r\n                           f::Function,\r\n                           f_prime::Function,\r\n                           shocks::AbstractVector,\r\n                           Kg::AbstractVector=similar(g))\r\n\r\n    # This function requires the container of the output value as argument Kg\r\n\r\n    # Construct linear interpolation object #\r\n    g_func=LinInterp(grid, g)\r\n\r\n    # solve for updated consumption value #\r\n    for (i,y) in enumerate(grid)\r\n        function h(c)\r\n            vals = u_prime.(g_func.(f(y - c)*shocks)).*f_prime(y - c).*shocks\r\n            return u_prime(c) - β * mean(vals)\r\n        end\r\n        Kg[i] = brent(h, 1e-10, y-1e-10)\r\n    end\r\n    return Kg\r\nend\r\n\r\n# The following function does NOT require the container of the output value as argument\r\nfunction coleman_operator(g::AbstractVector,\r\n                          grid::AbstractVector,\r\n                          β::AbstractFloat,\r\n                          u_prime::Function,\r\n                          f::Function,\r\n                          f_prime::Function,\r\n                          shocks::AbstractVector)\r\n\r\n    return coleman_operator!(g, grid, β, u_prime,\r\n                             f, f_prime, shocks, similar(g))\r\nend\r\n", "meta": {"hexsha": "082e8e34c37da9fd5a3b76f043a933c89601208a", "size": 1745, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "coleman_policy_iter/coleman.jl", "max_stars_repo_name": "chenwang/QuantEcon.lectures.code", "max_stars_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "coleman_policy_iter/coleman.jl", "max_issues_repo_name": "chenwang/QuantEcon.lectures.code", "max_issues_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coleman_policy_iter/coleman.jl", "max_forks_repo_name": "chenwang/QuantEcon.lectures.code", "max_forks_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-30T13:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-30T13:08:09.000Z", "avg_line_length": 31.1607142857, "max_line_length": 88, "alphanum_fraction": 0.5421203438, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.8723473813156294, "lm_q1q2_score": 0.7970433307715574}}
{"text": "using TuringModels\n\nTuring.setadbackend(:reverse_diff)\n#nbTuring.turnprogress(false);\n\nd = CSV.read(joinpath(@__DIR__, \"..\", \"..\", \"data\", \"Kline.csv\"), delim=';');\nsize(d) # Should be 10x5\n\n# New col log_pop, set log() for population data\nd[!, :log_pop] = map((x) -> log(x), d[:, :population]);\nd[!, :society] = 1:10;\n\n# Turing model\n\n@model m12_6(total_tools, log_pop, society) = begin\n\n    # Total num of y\n    N = length(total_tools)\n\n    # priors\n    α ~ Normal(0, 10)\n    βp ~ Normal(0, 1)\n\n    # Separate σ priors for each society\n    σ_society ~ Truncated(Cauchy(0, 1), 0, Inf)\n\n    # Number of unique societies in the data set\n    N_society = length(unique(society)) #10\n\n    # Vector of societies (1,..,10) which we'll set priors on\n    α_society = Vector{Real}(undef, N_society)\n\n    # For each society [1,..,10] set a prior N(0, σ_society)\n    α_society ~ [Normal(0, σ_society)]\n\n    for i ∈ 1:N\n        λ = exp(α + α_society[society[i]] + βp*log_pop[i])\n        total_tools[i] ~ Poisson(λ)\n    end\nend\n\n# Sample\n\nchns = sample(m12_6(d[:, :total_tools], d[:, :log_pop],\n    d[:, :society]), NUTS(0.95), 1000);\n\n# Results rethinking\nm12_6rethinking = \"\n              Mean StdDev lower 0.89 upper 0.89 n_eff Rhat\na              1.11   0.75      -0.05       2.24  1256    1\nbp             0.26   0.08       0.13       0.38  1276    1\na_society[1]  -0.20   0.24      -0.57       0.16  2389    1\na_society[2]   0.04   0.21      -0.29       0.38  2220    1\na_society[3]  -0.05   0.19      -0.36       0.25  3018    1\na_society[4]   0.32   0.18       0.01       0.60  2153    1\na_society[5]   0.04   0.18      -0.22       0.33  3196    1\na_society[6]  -0.32   0.21      -0.62       0.02  2574    1\na_society[7]   0.14   0.17      -0.13       0.40  2751    1\na_society[8]  -0.18   0.19      -0.46       0.12  2952    1\na_society[9]   0.27   0.17      -0.02       0.52  2540    1\na_society[10] -0.10   0.30      -0.52       0.37  1433    1\nsigma_society  0.31   0.13       0.11       0.47  1345    1\n\";\n\n# Describe the posterior samples\n\ndescribe(chns)\n\n# End of `12/m12.6t.jl`\n", "meta": {"hexsha": "80995ac0ddac5033b675d8cb6ad1a9b0f37b6195", "size": 2081, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/12/m12.6t.jl", "max_stars_repo_name": "UnofficialJuliaMirror/TuringModels.jl-ead7e11d-4ba5-55c3-9d74-177ea73ef1fd", "max_stars_repo_head_hexsha": "f5c955d6b0f6b5ba6d79e0d29475eb4cf73e84aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/12/m12.6t.jl", "max_issues_repo_name": "UnofficialJuliaMirror/TuringModels.jl-ead7e11d-4ba5-55c3-9d74-177ea73ef1fd", "max_issues_repo_head_hexsha": "f5c955d6b0f6b5ba6d79e0d29475eb4cf73e84aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/12/m12.6t.jl", "max_forks_repo_name": "UnofficialJuliaMirror/TuringModels.jl-ead7e11d-4ba5-55c3-9d74-177ea73ef1fd", "max_forks_repo_head_hexsha": "f5c955d6b0f6b5ba6d79e0d29475eb4cf73e84aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7285714286, "max_line_length": 77, "alphanum_fraction": 0.5526189332, "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8723473663814338, "lm_q1q2_score": 0.7970433027729947}}
{"text": "# A Julia implementation of the Affine ciphertext\n\n# Determines if 2 values are coprime\nfunction coprime(x, y)\n    xlist = []\n    ylist = []\n    for i in 2 : x\n        if x % i == 0\n            push!(xlist, i)\n        end\n    end\n    for j in 2 : y\n        if y % j == 0\n            push!(ylist, j)\n        end\n    end\n    for a in xlist\n        for b in ylist\n            if a == b\n                return false\n            end\n        end\n    end\n    return true\nend\n\n# Changes a char to an int value\nfunction charToVal(c)\n    alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    val = findfirst(isequal(c), alphabet)\n    return val\nend\n\n# Changes a value to a char1\nfunction valToChar(i)\n    alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    char = alphabet[i]\n    return char\nend\n\n# Main function\nfunction affine()\n\n    m = 26 # The number of letters in the alphabet used\n    println(\"Please input the plaintext\")\n    plaintext = readline()\n    plaintext = uppercase(plaintext)\n    plaintext = replace(plaintext, \" \" => \"\")\n\n    # Take keys and ensure they're valid\n    println(\"Please enter the a value\")\n    a = parse(Int, readline())\n    while !coprime(a, m)\n        println(\"a value invalid, must be coprime with m value \" * string(m))\n        a = parse(Int, readline())\n    end\n    println(\"Please enter the b value\")\n    b = parse(Int, readline())\n\n    # Produce the ciphertext\n    ciphertext = \"\"\n    for c in plaintext\n        val = charToVal(c) - 1 # Must account for Julia being 1-indexed\n        newVal = mod(((a * val) + b), m)\n        newchar = valToChar(newVal + 1)\n        ciphertext *= newchar\n    end\n    println(ciphertext)\nend\n\naffine()\n", "meta": {"hexsha": "80be90dc00a1a49f27f53c8cc717fd3037b0a799", "size": 1644, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/affine.jl", "max_stars_repo_name": "PaulB99/Julia-Ciphers", "max_stars_repo_head_hexsha": "22e6f6f972e5a208886665d928a17c92be792459", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/affine.jl", "max_issues_repo_name": "PaulB99/Julia-Ciphers", "max_issues_repo_head_hexsha": "22e6f6f972e5a208886665d928a17c92be792459", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/affine.jl", "max_forks_repo_name": "PaulB99/Julia-Ciphers", "max_forks_repo_head_hexsha": "22e6f6f972e5a208886665d928a17c92be792459", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8333333333, "max_line_length": 77, "alphanum_fraction": 0.5881995134, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661015270469, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7970229688728115}}
{"text": "\nfunction make_vandermonte_real(c::Vector{T}) where {T}\n    n = length(c)\n    V = zeros(T, n, n)\n    for k = 1:n\n        for kk = 1:n\n            V[k, kk] = c[kk] ^ (k-1)\n        end\n    end\n    return V\nend\n\nfunction find_real_eigenvalue(A::Matrix{BigFloat})\n    n, _ = size(A)\n    isodd(n) || error(\"A needs to be odd sized\")\n    ev = eigvals(A)\n    min_val, min_ind = findmin(abs.(imag.(ev)))\n    (min_val != 0.0) && error(\"something is wrong\")\n    return real.(ev[min_ind])\nend\n\nfunction calc_b_hat(A, c)\n    gamma_0 = find_real_eigenvalue(A)\n    n, _ = size(A)\n    rhs = BigFloat.(collect(1 .// (1:n)))\n    rhs[1] = 1 - gamma_0\n    V = make_vandermonte_real(c)\n    return vcat([gamma_0], V \\ rhs)\nend\n\nfunction radau_butcher_table_plus(s::Int64)\n    # ABC returns coefficients for S-stage Gauss-Legendre methods. (From RKGL, DiffMan package v.2 by K. Engo, A. Marthinsen & H. Munthe-Kaas.)\n    P_Radau = output_p_Radau(s)\n    c = roots(BigFloat.(coeffs(P_Radau)))\n    c = sort(real.(c))\n    V = make_vandermonte_real(c)'\n    J = diagm(0 => 1 .// (1:s) )\n    A = diagm(0 => c) * V * J / V\n    b = (ones(BigFloat, 1, s) * J / V)[:]\n    bi = get_dense_radau(J, V, c)\n    if isodd(s)\n        b̂ = calc_b_hat(A, c)\n    else\n        b̂ = zeros(BigFloat, s + 1) .+ NaN\n    end\n    return A, b, c, bi, b̂\nend\n\nfunction make_legendre_poly_by_order(n::Int64)\n    P_x2_minus_1 = Poly([-1, 0, 1])\n    return (1 // (2^n * factorial(n))) * polyder(P_x2_minus_1^n, n)\nend\n\nfunction output_p_Radau(n::Int64)\n    Pn = make_legendre_poly_by_order(n)\n    Pn_m = make_legendre_poly_by_order(n-1)\n    P_2x_minus_1 = Poly([-1, 2])\n    P_Radau = polyval(Pn, P_2x_minus_1) - polyval(Pn_m, P_2x_minus_1)\n    return P_Radau\nend\n\nfunction get_dense_radau(J, V, c)\n    s = length(c)\n    interp_poly = (J / V)' .* ((1 ./ c) * collect(1:s)')\n    return interp_poly\nend\n", "meta": {"hexsha": "0274e940ad9a619394869dc0a3e1bc36eee62070", "size": 1844, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/generate_butcher_table.jl", "max_stars_repo_name": "ryanelandt/RadauBig.jl", "max_stars_repo_head_hexsha": "33f41404c77524476d9008a8636d5ca6a44604f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/generate_butcher_table.jl", "max_issues_repo_name": "ryanelandt/RadauBig.jl", "max_issues_repo_head_hexsha": "33f41404c77524476d9008a8636d5ca6a44604f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/generate_butcher_table.jl", "max_forks_repo_name": "ryanelandt/RadauBig.jl", "max_forks_repo_head_hexsha": "33f41404c77524476d9008a8636d5ca6a44604f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5223880597, "max_line_length": 143, "alphanum_fraction": 0.5992407809, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660936744719, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7970229681737873}}
{"text": "\"\"\"\n    MahalanobisKernel(P::AbstractMatrix)\n\nMahalanobis distance-based kernel given by\n```math\n    κ(x,y) =  exp(-r^2), r^2 = maha(x,P,y) = (x-y)'*inv(P)*(x-y)\n```\nwhere the matrix P is the metric.\n\n\"\"\"\nstruct MahalanobisKernel{T<:Real, A<:AbstractMatrix{T}} <: SimpleKernel\n    P::A\n    function MahalanobisKernel(P::AbstractMatrix{T}) where {T<:Real}\n        LinearAlgebra.checksquare(P)\n        new{T,typeof(P)}(P)\n    end\nend\n\nkappa(κ::MahalanobisKernel, d::T) where {T<:Real} = exp(-d)\n\nmetric(κ::MahalanobisKernel) = SqMahalanobis(κ.P)\n\nBase.show(io::IO, κ::MahalanobisKernel) = print(io, \"Mahalanobis Kernel (size(P) = \", size(κ.P), \")\")\n", "meta": {"hexsha": "5c06b511774ff0eeca3c52e94bfb4837491c1f3e", "size": 647, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basekernels/maha.jl", "max_stars_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_stars_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basekernels/maha.jl", "max_issues_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_issues_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basekernels/maha.jl", "max_forks_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_forks_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9583333333, "max_line_length": 101, "alphanum_fraction": 0.6476043277, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660962919971, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7970229625451228}}
{"text": "using DifferentialEquations\nusing LinearAlgebra\nusing Plots\nusing ForwardDiff\nusing ProgressMeter\n\n# 2D Ball Example\nfunction physics(u, p, t)\n    # x, dx = u[1, 3]\n    # y, dy = u[2, 4]\n\n    # g = gravity, b = drag\n    g, b = p[1], p[2]\n\n    dx = u[2]\n    ddx = b * u[1]^2 \n    dy = u[4]\n    ddy = -g - b * u[3]^2\n\n    [dx, ddx, dy, ddy]\nend\n\n# Callback\ncondition_cont(u,t,integrator) = u[3]\n# condition(u,t,integrator) = u[3]<=0\naffect!(integrator) = terminate!(integrator)\n# cb = DiscreteCallback(condition,affect!)\ncb = ContinuousCallback(condition_cont,nothing,affect!)\n\n\n#Lets wrap this into a \"predict\" method\nfunction predict(vel)\n    # Simply roll this forward in time and we get our solution\n    tspan = (0.0, 10.0)\n    tspan_dual = convert.(eltype(vel),tspan)\n    p = [9.8, 0.0]\n\n    start_state = [0.0, vel[1], 10.0, vel[2]]\n    prob = ODEProblem(physics, start_state, tspan_dual, p)\n    sol = solve(prob, callback=cb)\n\n    sol\nend\n\n## Now let's try to optimize the system to hit a particular point\n# want point (1.0, 0)\nfunction loss(vel)\n    simulation = predict(vel)\n    final_pos = simulation[[1, 3], end]\n    l = (final_pos[1] - 1.0)^2 + final_pos[2]^2 # x -> 1.0, y -> 0\n    return l\nend\n\n# Plots loss surface over velocities in x and y\nfunction plot_loss_surf()\n    v_x = 0.0:0.01:3 \n    v_y = 0.0:0.01:2\n\n    loss_mat = zeros(length(v_x), length(v_y))\n    for x in 1:length(v_x)\n        for y in 1:length(v_y)\n            loss_mat[x, y] = loss([v_x[x], v_y[y]])\n        end\n    end\n\n    # sol_f(x, y) = loss_mat[x, y]\n    # plot(1:length(v_x), 1:length(v_y), sol_f, st=:surf, color=:viridis)\n    plot(loss_mat, st=:heatmap, color=:viridis)\n\nend\n\n# Plots loss over just x velocities\nfunction plot_loss_x()\n\n    v_x = 0.05:0.01:3 \n\n    loss_mat = zeros(length(v_x))\n    for x in 1:length(v_x)\n        loss_mat[x] = loss([v_x[x], 0.0])\n    end\n\n    plot(v_x, loss_mat)\n\nend\n\n\n# Optimize the xy velocities needed\nfunction optimize(vel_opt, η)\n    @showprogress for idx in 1:1000\n        grads = ForwardDiff.gradient(s -> loss(s), vel_opt) # Magic\n        vel_opt .-= η*grads\n\n        if loss(vel_opt) < 0.00001\n            break\n        end\n    end\n\n    vel_opt\nend\n\nfunction optimize_and_save(vel_opt, η)\n    solns = []\n    for idx in 1:1000\n        if idx % 10 == 1\n            append!(solns, [deepcopy(vel_opt)])    \n            # @show idx\n            # @show vel_opt\n            # @show solns\n        end\n\n        grads = ForwardDiff.gradient(s -> loss(s), vel_opt) # Magic\n        vel_opt .-= η*grads\n\n        if loss(vel_opt) < 0.00001\n            break\n        end\n\n    end\n    display(solns)\n    solns\nend\n\n# Example run of optimize\nfunction run_test()\n    p = [1.0, 0.2]\n    init_sol = predict(p); \n    v = optimize(p, 0.2); \n    final_sol = predict(v);\n\n    display(plot(init_sol, vars=(1, 3), label=\"Initial\")); display(plot!(final_sol, vars=(1,3), label=\"Optimized to land at x=1.0, y=0.0\"))\nend\n\nfunction run_and_save()\n    p = [2.0, 0.4]\n    vs = optimize_and_save(p, 0.03); \n    display(plot(title=\"Ballistic Optimizer: Goal final position (1.0, 0.0)\",\n                 xlabel=\"x distance [m]\",\n                 ylabel=\"y distance [m]\"))\n    i = 0\n    for v in vs \n        display(\n            plot!(predict(v), \n                vars=(1,3), \n                label=\"Iteration \" * string(i),\n                color=:Blues,\n                colorbar=:none,\n                legend=:bottomleft,\n                line_z=i+1)\n            )\n        i += 10\n    end\n\n    savefig(\"plots/ballistic_example.png\")\nend\n", "meta": {"hexsha": "61660f3b296b4ed1ca53da1508b443c123aba76f", "size": 3534, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ballistic_optimizer.jl", "max_stars_repo_name": "zzumbo/6.338-final-project", "max_stars_repo_head_hexsha": "696fdc095dc831abbe2c47b5a0186d95a9949e15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/ballistic_optimizer.jl", "max_issues_repo_name": "zzumbo/6.338-final-project", "max_issues_repo_head_hexsha": "696fdc095dc831abbe2c47b5a0186d95a9949e15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ballistic_optimizer.jl", "max_forks_repo_name": "zzumbo/6.338-final-project", "max_forks_repo_head_hexsha": "696fdc095dc831abbe2c47b5a0186d95a9949e15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8, "max_line_length": 139, "alphanum_fraction": 0.5690435767, "num_tokens": 1146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7970162170780831}}
{"text": "\n#\n# Evaluates definite integral\n# ∫ erf(b-y)/(sqrt(2)*ℓ), y∈[c,d]\n#\n# Wolfram code: Integrate[erf(b-y)/(sqrt(2)*ℓ), {y, c, d}]\n#\n\nfunction sub_1(; b = b, c = c, d = d, ℓ = ℓ)\n\n    @assert(c < d)\n\n    sqrt(2/π) * ℓ * ( exp(-(b - c)^2/(2 * ℓ^2)) - exp(-(b - d)^2/(2 * ℓ^2))) +\n        (b - c) * erf((b - c)/(sqrt(2) * ℓ)) +\n        (d - b) * erf((b - d)/(sqrt(2) * ℓ))\n\n\nend\n\n\nfunction verify_sub_1(; b = b, c = c, d = d, ℓ = ℓ)\n\n    # integrand\n    f(y) = erf((b-y)/(sqrt(2)*ℓ))\n\n\n    # own numerical verification on 1d regular grid\n    dx = 1e-6\n    X  = c:dx:d\n    num = 0.0\n    for x in X\n        num += f(x)*dx\n    end\n\n\n    # numerical verification via Cuba.jl library\n    h = Cuba.vegas((x, out) -> out[1] = (d-c) * f(c + (d-c)*x[1]), 1, 1, maxevals=1_000_000)\n\n    display(h)\n\n    # numerical verification via HCubature.jl library\n    hc = hquadrature(f, c, d)\n\n\n    # return exact and numerical results\n    sub_1(; b = b, c = c, d = d, ℓ = ℓ),\n    h.integral[1],\n    hc[1],\n    num\n\nend\n\n\n\n\n#\n# Evaluates definite integral\n# ∫∫ exp(- (x-y)² / (2ℓ²) ) dx dy, x∈[a,b], y∈[c,d]\n#\n# Wolfram code: Integrate[E^(-(x - y)^2/(2 (ℓ^2))), {x, a, b}]\n#\n\nfunction integralfunction_1(; lowerx = lowerx, upperx = upperx, lowery = lowery, uppery = uppery, ℓ = ℓ)\n\n    @assert(lowerx < upperx)\n    @assert(lowery < uppery)\n\n    # easier names\n    a = lowerx\n    b = upperx\n    c = lowery\n    d = uppery\n\n    # Result of ∫ exp(- (x-y)² / (2ℓ²) ) dx  x∈[a,b] is:\n    # sqrt(π/2) r (erf((b - y)/(sqrt(2) ℓ)) - erf((a - y)/(sqrt(2) ℓ)))\n    # We need to carry out the second integral over y.\n    # The result of this second integral over y is:\n\n    sqrt(π/2) * ℓ * (sub_1(b=b, c=c, d=d, ℓ=ℓ) - sub_1(b=a, c=c, d=d, ℓ=ℓ))\n\nend\n\n\n#\n# Verification: numerical evaluation for definite integral\n# ∫∫ exp(- (x-y)² / (2ℓ²) ) dx dy, x∈[a, b], y∈[c, d]\n#\n\nfunction verify_1(; lowerx = lowerx, upperx = upperx, lowery = lowery, uppery = uppery, ℓ = ℓ)\n\n    @assert(lowerx < upperx)\n    @assert(lowery < uppery)\n\n    # intergrand\n    f(x,y) =  exp(-(x-y)^2 / (2*(ℓ^2)))\n\n\n    # numerical verification on regular grid\n    Δx = 1e-3\n    X  = lowerx:Δx:upperx\n    Y  = lowery:Δx:uppery\n\n    num = 0.0\n    for i in 1:length(X)\n        for j in 1:length(Y)\n            @inbounds num += f(X[i], Y[j])\n        end\n    end\n    num *= Δx^2\n\n\n    # numerical verification via Cuba.jl libary\n    h = divonne((x, out) -> out[1] = (uppery-lowery)*(upperx-lowerx) * f(lowerx + (upperx-lowerx)*x[1], lowery + (uppery-lowery)*x[2]), 2, 1)\n\n    display(h)\n\n\n    # return exact and numerical results to verify\n    integralfunction_1(lowerx = lowerx, upperx = upperx, lowery = lowery, uppery = uppery, ℓ = ℓ), num, h.integral[1]\n\nend\n\n\n\n################################################################################\n################################################################################\n################################################################################\n\n\n\n#\n# Evaluates definite integral\n# ∫ exp(- (a-y)² / (2ℓ²) ) dy,  y ∈ [c, d]\n#\nfunction sub_2a(; a = a, c = c, d = d, ℓ = ℓ)\n\n    # Wolfram code: Integrate[E^(-(a - y)^2/(2 ℓ^2)), {y, c, d}]\n    # Solution returned in plain text:\n    # integral_c^d e^(-(a - y)^2/(2 ℓ^2)) dy = sqrt(π/2) r (erf((a - c)/(sqrt(2) ℓ)) - erf((a - d)/(sqrt(2) ℓ)))\n\n    sqrt(π/2) * ℓ * (erf((a - c)/(sqrt(2) * ℓ)) - erf((a - d)/(sqrt(2) * ℓ)))\n\nend\n\n\n#\n# Verifies definite integral\n# ∫ exp(- (a-y)² / (2ℓ²) ) dy,  y ∈ [c, d]\n#\nfunction verify_sub_2a(; a = a, c = c, d = d, ℓ = ℓ)\n\n    f(y) = exp(-(a-y)^2/(2*ℓ^2))\n\n    # own numerical verification on 1d regular grid\n    dx = 1e-6\n    X  = c:dx:d\n    num = 0.0\n    for x in X\n        num += f(x)*dx\n    end\n\n\n    # numerical verification via Cuba.jl libary\n    h = Cuba.vegas((x, out) -> out[1] = (d-c) * f(c + (d-c)*x[1]), 1, 1, maxevals=3_000_000)\n\n    display(h)\n\n\n    # return exact and numerical results\n    sub_2a(; a = a, c = c, d = d, ℓ = ℓ),\n    h.integral[1],\n    num\n\nend\n\n\n#\n# Evaluates definite integral\n# ∫ y erf((a-y)/(sqrt(2)ℓ) dy,  y ∈ [c, d]\n#\nfunction sub_2b(; a = a, c = c, d = d, ℓ = ℓ)\n\n    # Wolfram code: Integrate[y Erf[(a - y)/(Sqrt[2] ℓ)], {y, c, d}]\n    # Solution returned in plain text:\n    # integral_c^d y erf((a - y)/(sqrt(2) ℓ)) dy = 1/2 (a^2 - c^2 + ℓ^2) erf((a - c)/(sqrt(2) ℓ)) - 1/2 (a^2 - d^2 + ℓ^2) erf((a - d)/(sqrt(2) ℓ)) + (ℓ (a + c) e^(-(a - c)^2/(2 ℓ^2)))/sqrt(2 π) - (ℓ (a + d) e^(-(a - d)^2/(2 ℓ^2)))/sqrt(2 π)\n\n    1/2 * (a^2 - c^2 + ℓ^2) * erf((a - c)/(sqrt(2) * ℓ)) -\n    1/2 * (a^2 - d^2 + ℓ^2) * erf((a - d)/(sqrt(2) * ℓ)) +\n    (ℓ * (a + c) * exp(-(a - c)^2/(2 * ℓ^2)))/sqrt(2*π) - (ℓ*(a + d) * exp(-(a - d)^2/(2*ℓ^2)))/sqrt(2π)\n\n\nend\n\n\n#\n# Verifies definite integral\n# ∫ y erf((a-y)/(sqrt(2)ℓ) dy,  y ∈ [c, d]\n#\nfunction verify_sub_2b(; a = a, c = c, d = d, ℓ = ℓ)\n\n    f(y) = y * erf((a-y)/(sqrt(2)*ℓ))\n\n    # own numerical verification on 1d regular grid\n    dx = 1e-6\n    X  = c:dx:d\n    num = 0.0\n    for x in X\n        num += f(x)*dx\n    end\n\n\n    # numerical verification via Cuba.jl libary\n    h = Cuba.vegas((x, out) -> out[1] = (d-c) * f(c + (d-c)*x[1]), 1, 1, maxevals=1_000_000)\n\n    display(h)\n\n\n    # return exact and numerical results\n    sub_2b(; a = a, c = c, d = d, ℓ = ℓ),\n    h.integral[1],\n    num\n\n\nend\n\n\n\n#\n# Evaluates definite integral\n# ∫∫ x exp(- (x-y)² / (2ℓ²) ) dx dy, x∈[a, b], y∈[c, d]\n#\nfunction integralfunction_2(; lowerx = lowerx, upperx = upperx, lowery = lowery, uppery = uppery, ℓ = ℓ)\n\n    @assert(lowerx < upperx)\n    @assert(lowery < uppery)\n\n    # easier names\n    a = lowerx\n    b = upperx\n    c = lowery\n    d = uppery\n\n\n\n\n    # Intermediate step:\n    # Solution of integral ∫ᵇₐ x exp(-(x-y)^2 / (2ℓ²)) dx is\n    # integral_a^b x e^(-(x - y)^2/(2 ℓ^2)) dx = 1/2 ℓ (2 ℓ (e^(-(a - y)^2/(2 ℓ^2)) - e^(-(b - y)^2/(2 ℓ^2))) - sqrt(2 π) y erf((a - y)/(sqrt(2) ℓ)) + sqrt(2 π) y erf((b - y)/(sqrt(2) ℓ)))\n    # (Wolfram code: Integrate[x * E^(-((x - y)^2)/(2*ℓ^2)), {x, a, b}]\n    #\n\n    #1/2 * ℓ *(2*ℓ * (exp(-(a - y)^2/(2*ℓ^2)) - exp(-(b - y)^2/(2*ℓ^2))) -\n    #          sqrt(2π) * y * erf((a - y)/(sqrt(2)*ℓ)) + sqrt(2π) * y * erf((b - y) /(sqrt(2)*ℓ)))\n\n    1/2 * ℓ *(2*ℓ * (sub_2a(a=a, c=c, d=d, ℓ=ℓ) - sub_2a(a=b, c=c, d=d, ℓ=ℓ)) -\n              sqrt(2π) * (sub_2b(a = a, c = c, d = d, ℓ = ℓ) -  sub_2b(a = b, c = c, d = d, ℓ = ℓ)))\n\n\nend\n\n\n\nfunction verify_2(; lowerx = lowerx, upperx = upperx, lowery = lowery, uppery = uppery, ℓ = ℓ)\n\n    f(x,y) =  x * exp(- (x-y)^2 / (2*ℓ^2) )\n\n    # numerical verification on regular grid\n    Δx = 1e-3\n    X  = lowerx:Δx:upperx\n    Y  = lowery:Δx:uppery\n\n    num = 0.0\n    for i in 1:length(X)\n        for j in 1:length(Y)\n            @inbounds num += f(X[i], Y[j])\n        end\n    end\n    num *= Δx^2\n\n\n    # numerical verification via Cuba.jl libary\n    h = divonne((x, out) -> out[1] = (uppery-lowery)*(upperx-lowerx) * f(lowerx + (upperx-lowerx)*x[1], lowery + (uppery-lowery)*x[2]), 2, 1)\n\n    display(h)\n\n\n    # return exact and numerical results to verify\n    integralfunction_2(lowerx = lowerx, upperx = upperx, lowery = lowery, uppery = uppery, ℓ = ℓ), num, h.integral[1]\n\nend\n\n\n\n################################################################################\n################################################################################\n################################################################################\n\n#\n# Evaluate integral:\n# ∫ y² erf( (a-y) / (sqrt(2) ℓ) ) dy\n#\n\nfunction sub_3a(; a = a, c = c, d = d, ℓ = ℓ)\n\n    # Wolram code: Integrate[y^2 Erf[(a - y)/(Sqrt[2] ℓ)], {y, c, d}]\n    #\n    # solution:\n    # integral_c^d y y erf((a - y)/(sqrt(2) ℓ)) dy = 1/3 (-(a^3 + 3 a ℓ^2) erf((c - a)/(sqrt(2) ℓ)) + (a^3 + 3 a ℓ^2) erf((d - a)/(sqrt(2) ℓ)) + sqrt(2/π) ℓ e^(-(a - c)^2/(2 ℓ^2)) (a^2 + a c + c^2 + 2 ℓ^2) - sqrt(2/π) ℓ e^(-(a - d)^2/(2 ℓ^2)) (a^2 + a d + d^2 + 2 ℓ^2) + c^3 (-erf((a - c)/(sqrt(2) ℓ))) + d^3 erf((a - d)/(sqrt(2) ℓ)))\n\n    1/3 * (-(a^3 + 3*a*ℓ^2) * (erf((c - a)/(sqrt(2)*ℓ)) - erf((d - a)/(sqrt(2)*ℓ))) +\n              sqrt(2/π) * ℓ * (exp(-(a - c)^2/(2 * ℓ^2)) * (a^2 + a * c + c^2 + 2 * ℓ^2) -\n                               exp(-(a - d)^2/(2 * ℓ^2)) * (a^2 + a * d + d^2 + 2 * ℓ^2)) +\n          c^3 * (-erf((a - c)/(sqrt(2) * ℓ))) + d^3 * erf((a - d)/(sqrt(2) * ℓ)))\n\nend\n\n#\n# Verify integral:\n# ∫ y² erf( (a-y) / (sqrt(2) ℓ) ) dy\n#\n\nfunction verify_sub_3a(; a = a, c = c, d = d, ℓ = ℓ)\n\n    f(y) = y^2 * erf( (a-y) / (sqrt(2) * ℓ) )\n\n    # own numerical verification on 1d regular grid\n    dx = 1e-6\n    X  = c:dx:d\n    num = 0.0\n    for x in X\n        num += f(x)*dx\n    end\n\n\n    # numerical verification via Cuba.jl libary\n    h = Cuba.vegas((x, out) -> out[1] = (d-c) * f(c + (d-c)*x[1]), 1, 1, maxevals=10_000_000)\n\n    display(h)\n\n\n    # return exact and numerical results\n    sub_3a(; a = a, c = c, d = d, ℓ = ℓ),\n    h.integral[1],\n    num\n\nend\n\n\n\n\n#\n# Evaluate integral:\n# ∫ y exp( -(a-y)² / (2 ℓ²) ) dy\n#\n\nfunction sub_3b(; a = a, c = c, d = d, ℓ = ℓ)\n\n    # Wolram code: Integrate[y/E^((a - y)^2/(2 ℓ^2)), {y, c, d}]\n    #\n    # solution:\n    # integral_c^d y e^(-(a - y)^2/(2 ℓ^2)) dy = 1/2 ℓ (2 ℓ (e^(-(a - c)^2/(2 ℓ^2)) - e^(-(a - d)^2/(2 ℓ^2))) + sqrt(2 π) a erf((a - c)/(sqrt(2) ℓ)) - sqrt(2 π) a erf((a - d)/(sqrt(2) ℓ)))\n\n    1/2 * ℓ * (2 * ℓ * (exp(-(a - c)^2/(2*ℓ^2)) - exp(-(a - d)^2/(2*ℓ^2))) +\n            sqrt(2*π) * a * erf((a - c)/(sqrt(2)*ℓ)) - sqrt(2*π) * a * erf((a - d)/(sqrt(2)*ℓ)))\n\n\nend\n\n#\n# Verify integral:\n# ∫ y exp( -(a-y)² / (2 ℓ²) ) dy\n#\n\nfunction verify_sub_3b(; a = a, c = c, d = d, ℓ = ℓ)\n\n    f(y) = y * exp( -(a-y)^2 / (2 * ℓ^2) )\n\n    # own numerical verification on 1d regular grid\n    dx = 1e-6\n    X  = c:dx:d\n    num = 0.0\n    for x in X\n        num += f(x)*dx\n    end\n\n\n    # numerical verification via Cuba.jl libary\n    h = Cuba.vegas((x, out) -> out[1] = (d-c) * f(c + (d-c)*x[1]), 1, 1, maxevals=10_000_000)\n\n    display(h)\n\n\n    # return exact and numerical results\n    sub_3b(; a = a, c = c, d = d, ℓ = ℓ),\n    h.integral[1],\n    num\n\nend\n\n\n\n\n#\n# Evaluate integral:\n# ∫∫ y x exp(- (x-y)² / (2ℓ²) ) dx dy, x∈[a, b], y∈[c, d]\n#\nfunction integralfunction_3(; lowerx = lowerx, upperx = upperx, lowery = lowery, uppery = uppery, ℓ = ℓ)\n\n    @assert(lowerx < upperx)\n    @assert(lowery < uppery)\n\n    # easier names\n    a = lowerx\n    b = upperx\n    c = lowery\n    d = uppery\n\n\n    # Intermediate step: ∫ y x exp(- (x-y)² / (2ℓ²) ) dx dy, x∈[a, b]\n    # Wolfram code: Integrate[(x y)/E^((x - y)^2/(2 ℓ^2)), {x, a, b}]\n    # solution:\n    # integral_a^b y x e^(-(x - y)^2/(2 ℓ^2)) dx = 1/2 ℓ y (2 ℓ (e^(-(a - y)^2/(2 ℓ^2)) - e^(-(b - y)^2/(2 ℓ^2))) - sqrt(2 π) y erf((a - y)/(sqrt(2) ℓ)) + sqrt(2 π) y erf((b - y)/(sqrt(2) ℓ)))\n    #\n    # We need to integrate the above solution over y y∈[c, d]\n\n    1/2 * ℓ * (2 * ℓ * (sub_3b(; a = a, c = c, d = d, ℓ = ℓ) - sub_3b(; a = b, c = c, d = d, ℓ = ℓ)) -\n                    sqrt(2*π) * sub_3a(; a = a, c = c, d = d, ℓ = ℓ) +\n                    sqrt(2*π) * sub_3a(; a = b, c = c, d = d, ℓ = ℓ))\n\nend\n\n\nfunction verify_3(; lowerx = lowerx, upperx = upperx, lowery = lowery, uppery = uppery, ℓ = ℓ)\n\n    # integrand\n    f(x,y) =  y * x * exp(- (x-y)^2 / (2ℓ^2) )\n\n    # numerical verification on regular grid\n    Δx = 1e-3\n    X  = lowerx:Δx:upperx\n    Y  = lowery:Δx:uppery\n\n    num = 0.0\n    for i in 1:length(X)\n        for j in 1:length(Y)\n            @inbounds num += f(X[i], Y[j])\n        end\n    end\n    num *= Δx^2\n\n\n    # numerical verification via Cuba.jl libary\n    h = divonne((x, out) -> out[1] = (uppery-lowery)*(upperx-lowerx) * f(lowerx + (upperx-lowerx)*x[1], lowery + (uppery-lowery)*x[2]), 2, 1)\n\n    display(h)\n\n\n    # return exact and numerical results to verify\n    integralfunction_3(lowerx = lowerx, upperx = upperx, lowery = lowery, uppery = uppery, ℓ = ℓ), num, h.integral[1]\n\nend\n", "meta": {"hexsha": "c82ab4f6ce65e63ecbfc57951306c45f7d925c7e", "size": 11758, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/integrals.jl", "max_stars_repo_name": "ngiann/TransferFunctionGPKernel.jl", "max_stars_repo_head_hexsha": "79401407a235bd75ad3122731fa0e707652261cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/integrals.jl", "max_issues_repo_name": "ngiann/TransferFunctionGPKernel.jl", "max_issues_repo_head_hexsha": "79401407a235bd75ad3122731fa0e707652261cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/integrals.jl", "max_forks_repo_name": "ngiann/TransferFunctionGPKernel.jl", "max_forks_repo_head_hexsha": "79401407a235bd75ad3122731fa0e707652261cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4502164502, "max_line_length": 334, "alphanum_fraction": 0.4721040993, "num_tokens": 4974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913354875362, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7970162169918306}}
{"text": "using LinearAlgebra: norm, ⋅, ×\nusing StaticArrays: SVector\n\nexport\n    sec2rad, rad2sec, normalize_angle, angle,\n    dms2rad, rad2dms, sec2deg, deg2sec\n\n\"\"\"\n    sec2rad(sec)\n\nConvert an angle in arcseconds to radians.\n\n# Example\n\n```jldoctest\njulia> sec2rad(3600 * 30)\n0.5235987755982988\n```\n\"\"\"\nsec2rad(sec) = deg2rad(sec / 3600)\n\n\"\"\"\n    rad2sec(rad)\nConvert an angle in radians to arcseconds.\n\n# Example\n\n```jldoctest\njulia> rad2sec(0.5235987755982988)\n107999.99999999999\n```\n\"\"\"\nrad2sec(rad) = rad2deg(rad) * 3600\n\nsec2deg(sec) = sec / 3600\ndeg2sec(deg) = deg * 3600\n\nfunction normalize_angle(angle, center)\n    angle - 2π * floor((angle + π - center) / 2π)\nend\n\nfunction dms2rad(deg, arcmin, arcsec)\n    deg2rad(deg + arcmin/60 + arcsec/3600)\nend\n\nfunction rad2dms(rad)\n    d = rad2deg(rad)\n    deg = trunc(d)\n    arcmin = trunc((d-deg)*60)\n    arcsec = (d-deg-arcmin/60)*3600\n    return deg, arcmin, arcsec\nend\n\nfunction angle(v1, v2)\n    normprod = norm(v1) * norm(v2)\n    if normprod == 0.0\n        throw(DomainError())\n    else\n        v1v2 = v1 ⋅ v2\n        threshold = normprod * 0.9999\n        if v1v2 >= -threshold && v1v2 <= threshold\n            return acos(v1v2 / normprod)\n        else\n            v3n = norm(v1 × v2)\n            return v1v2 >= 0.0 ? (v3n / normprod) : π - asin(v3n / normprod)\n        end\n    end\nend\n\nfunction azimuth(v)\n    atan(v[2], v[1])\nend\n\nfunction elevation(v)\n    asin(v[3] / norm(v))\nend\n\nfunction vector_azel(az, el)\n    saz, caz = sincos(az)\n    sel, cel = sincos(el)\n    SVector(caz * cel, saz * cel, sel)\nend\n\nfunction angular_velocity(ψ, δψ, θ, δθ, ϕ, δϕ)\n    Ω₁ = δψ * sin(θ) * sin(ϕ) - δθ * cos(ϕ)\n    Ω₂ = δψ * sin(θ) * cos(ϕ) + δθ * sin(ϕ)\n    Ω₃ = δψ * cos(θ) + δϕ\n    [Ω₁, Ω₂, Ω₃]\nend\n\n", "meta": {"hexsha": "b37aa53f87cc1c3beb5e276d897c7b85679e8914", "size": 1744, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/util.jl", "max_stars_repo_name": "ravising-h/AstroBase.jl", "max_stars_repo_head_hexsha": "f67976b0635741aa3965ebf325fd372636bec92f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-26T19:15:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-26T19:15:00.000Z", "max_issues_repo_path": "src/util.jl", "max_issues_repo_name": "ravising-h/AstroBase.jl", "max_issues_repo_head_hexsha": "f67976b0635741aa3965ebf325fd372636bec92f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util.jl", "max_forks_repo_name": "ravising-h/AstroBase.jl", "max_forks_repo_head_hexsha": "f67976b0635741aa3965ebf325fd372636bec92f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1648351648, "max_line_length": 76, "alphanum_fraction": 0.6072247706, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7970162119533845}}
{"text": "# This file is a part of SimilaritySearch.jl\n\nexport JaccardDistance, DiceDistance, IntersectionDissimilarity, CosineDistanceSet\nimport Distances: evaluate\nusing Base.Order\n\n\"\"\"\n    JaccardDistance()\n\nThe Jaccard distance is defined as\n\n```math\nJ(u, v) = \\\\frac{|u \\\\cap v|}{|u \\\\cup v|}\n```\n\"\"\"\nstruct JaccardDistance <: SemiMetric end\n\n\"\"\"\n    DiceDistance()\n\nThe Dice distance is defined as\n\n```math\nD(u, v) = \\\\frac{2 |u \\\\cap v|}{|u| + |v|}\n```\n\"\"\"\nstruct DiceDistance <: SemiMetric end\n\n\"\"\"\n    IntersectionDissimilarity()\n\nThe intersection dissimilarity uses the size of the intersection as a mesuare of similarity as follows:\n\n```math\nI(u, v) = 1 - \\\\frac{|u \\\\cap v|}{\\\\max \\\\{|u|, |v|\\\\}}\n```\n\"\"\"\nstruct IntersectionDissimilarity <: SemiMetric end\n\n\"\"\"\n    CosineDistanceSet()\n\nThe cosine distance for very sparse binary vectors represented as\nsorted lists of positive integers where ones occur.\n\"\"\"\nstruct CosineDistanceSet <: SemiMetric end\n\n\"\"\"\n    intersectionsize(a, b, o=Forward)\n\nComputes the size the intersections of `a` and `b`, specified as ordered sequences.\n\"\"\"\nfunction intersectionsize(a, b, o=Forward)\n    len_a::Int = length(a)\n    len_b::Int = length(b)\n    ia::Int = ib::Int = 1\n    intersection_size::Int = 0\n    @inbounds while ia <= len_a && ib <= len_b\n        if lt(o, a[ia], b[ib])\n            ia += 1\n        elseif lt(o, b[ib], a[ia])\n            ib += 1\n        else\n            ia += 1\n            ib += 1\n            intersection_size += 1\n        end\n    end\n\n    intersection_size\nend\n\n\"\"\"\n    unionsize(a, b, isize)\n\nComputes the size of the union of `a` and `b` that have an intersection size `isize`\n\"\"\"\nfunction unionsize(a, b, isize)\n    length(a) + length(b) - isize\nend\n\n\"\"\"\n    evaluate(::JaccardDistance, a, b)\n\nComputes the Jaccard's distance of `a` and `b` both sets specified as\nsorted vectors.\n\"\"\"\nfunction evaluate(::JaccardDistance, a, b)\n    isize = intersectionsize(a, b)\n    1.0 - isize / unionsize(a, b, isize)\nend\n\n\"\"\"\n    evaluate(::DiceDistance, a, b)\n\nComputes the Dice's distance of `a` and `b` both sets specified as\nsorted vectors.\n\"\"\"\nfunction evaluate(::DiceDistance, a, b)\n    i = intersectionsize(a, b)\n    1.0 - 2 * i / (length(a) + length(b))\nend\n\n\n\"\"\"\n    evaluate(::IntersectionDissimilarity, a, b)\n\nUses the intersection as a distance function (non-metric)\n\"\"\"\nfunction evaluate(::IntersectionDissimilarity, a, b)\n    i = intersectionsize(a, b)\n    return 1.0 - i / max(length(a), length(b))\nend\n\n\"\"\"\n    evaluate(::CosineDistanceSet, a, b)\n\nComputes the cosine distance where `a` and `b` are sorted lists of integers (emulating binary sparse vectores)\n\"\"\"\nfunction evaluate(::CosineDistanceSet, U, V)\n    1 - intersectionsize(U, V) / (sqrt(length(U)) * sqrt(length(V)))\nend", "meta": {"hexsha": "8925f8de07384962b8e3635e322c4ee4f6e5639d", "size": 2751, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances/sets.jl", "max_stars_repo_name": "sadit/SimilaritySearch", "max_stars_repo_head_hexsha": "3d3ed4cbca4858f9df4929318993b030387e1da7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-05-23T21:10:24.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-23T21:10:24.000Z", "max_issues_repo_path": "src/distances/sets.jl", "max_issues_repo_name": "sadit/NNS", "max_issues_repo_head_hexsha": "f149e488906c0b6334b64f3a3bd071d870b98a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-05-23T22:44:14.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-23T22:44:14.000Z", "max_forks_repo_path": "src/distances/sets.jl", "max_forks_repo_name": "sadit/SimilaritySearch", "max_forks_repo_head_hexsha": "3d3ed4cbca4858f9df4929318993b030387e1da7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5491803279, "max_line_length": 110, "alphanum_fraction": 0.6484914577, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7970162094772878}}
{"text": "#### Cauchy matrix\n\nexport Cauchy\n\nstruct Cauchy{T} <: AbstractMatrix{T}\n    x::Vector{T} #\n    y::Vector{T} #\nend # immutable\n\nfunction Cauchy(k::Number)\n         Cauchy(collect(1:k),collect(1:k))\nend\n\nfunction Cauchy(x::Vector)\n         Cauchy(x,x)\nend\n\n# Define its size\n\nsize(A::Cauchy, dim::Integer) = length(A.x)\nsize(A::Cauchy)= size(A,1), size(A,1)\n\n# Index into a Cauchy\nfunction getindex(A::Cauchy,i::Integer,j::Integer)\n    return 1.0/(A.x[i]+A.y[j])\nend # getindex\n\n# Dense version of Cauchy\nMatrix(A::Cauchy) = [A[i,j] for i=1:size(A,1), j=1:size(A,2)]\n", "meta": {"hexsha": "0e4528fb9f52a73d83dbee59e8318cd347d3785c", "size": 566, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cauchy.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SpecialMatrices.jl-928aab9d-ef52-54ac-8ca1-acd7ca42c160", "max_stars_repo_head_hexsha": "196405f3a93e21760860b31566887ed562fb780b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cauchy.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SpecialMatrices.jl-928aab9d-ef52-54ac-8ca1-acd7ca42c160", "max_issues_repo_head_hexsha": "196405f3a93e21760860b31566887ed562fb780b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cauchy.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SpecialMatrices.jl-928aab9d-ef52-54ac-8ca1-acd7ca42c160", "max_forks_repo_head_hexsha": "196405f3a93e21760860b31566887ed562fb780b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8666666667, "max_line_length": 61, "alphanum_fraction": 0.6360424028, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8633916134888613, "lm_q1q2_score": 0.7969442770375793}}
{"text": "using Distributions\r\n\r\nfunction betarnd(a,b,n,m)\r\n\td = Beta(a,b)\r\n\tr = rand(d,int(n*m))\r\n\treshape(r, n,m)\r\nend\r\n\r\nfunction randVonMisesFisher(m, n, kappa, mu = None)\r\n\t#% randVonMISESFISHERM Random number generation from von Mises Fisher\r\n\t#% distribution.\r\n\t#% X = randVonMisesFisherm(m, n, kappa) returns n samples of random unit \r\n\t#% directions in m dimensional space, with concentration parameter kappa,\r\n\t#% and the direction parameter mu = e_m\r\n\t#% X = randVonMisesFisherm(m, n, kappa, mu) with direction parameter mu\r\n\t#% (m-dimensional column unit vector)\r\n\t#%\r\n\t#% Sungkyu Jung, Feb 3, 2010.\r\n\t#\r\n\t# converted into Julia, Daniel Perry, April 2015, \r\n\t#\r\n\t# see http://www.stat.pitt.edu/sungkyu/MiscPage.html\r\n\t#     http://www.stat.pitt.edu/sungkyu/software/randVonMisesFisherm.zip\r\n\t#     http://www.stat.pitt.edu/sungkyu/software/randVonMisesFisher3.pdf\r\n\r\n\r\n\tif mu == None\r\n\t\tmuflag = false;\r\n\telse \r\n\t\tmuflag = true;\r\n\tend\r\n\r\n\tif m < 2; \r\n\t\t\tprintln(\"Message from randVonMisesFisherm.m: dimension m must be > 2\")\r\n\t\t\tprintln(\"Message from randVonMisesFisherm.m: Set m to be 2\")\r\n\t\t\tm = 2;\r\n\tend\r\n\r\n\tif kappa < 0; \r\n\t\t\tprintln(\"Message from randVonMisesFisherm.m: kappa must be >= 0\"); \r\n\t\t\tprintln(\"Message from randVonMisesFisherm.m: Set kappa to be 0\"); \r\n\t\t\tkappa = 0;\r\n\tend\r\n\r\n\t#%\r\n\t#% the following algorithm is following the modified Ulrich's algorithm \r\n\t#% discussed by Andrew T.A. Wood in \"SIMULATION OF THE VON MISES FISHER \r\n\t#% DISTRIBUTION\", COMMUN. STATIST 23(1), 1994.\r\n\r\n\t#% step 0 : initialize\r\n\tb = (-2*kappa + sqrt(4*kappa^2 + (m-1)^2))/(m-1);\r\n\tx0 = (1-b)/(1+b);\r\n\tc = kappa*x0 + (m-1)*log(1-x0^2);\r\n\r\n\t#% step 1 & step 2\r\n\tnnow = n; \r\n\tw = [];\r\n\t#%cnt = 0;\r\n\twhile true\r\n\t\t\tntrial = int(max(round(nnow*1.2),nnow+10))\r\n\t\t\tZ = betarnd((m-1)/2,(m-1)/2,ntrial,1);\r\n\t\t\tU = rand(ntrial,1);\r\n\t\t\tW = (1-(1+b)*Z)./(1-(1-b)*Z);\r\n\t\t\t\r\n\t\t\tindicator = (kappa*W + (m-1)*log(1-x0*W) - c) .>= log(U)\r\n\t\t\tif sum(indicator) >= nnow\r\n\t\t\t\t\tw1 = W[find(indicator)]\r\n\t\t\t\t\tw = [w ;w1[1:nnow]];\r\n\t\t\t\t\tbreak;\r\n\t\t\telse\r\n\t\t\t\t\tw = [w ; W[find(indicator)]];\r\n\t\t\t\t\tnnow = nnow-sum(indicator);\r\n\t\t\t\t\t#%cnt = cnt+1;disp(['retrial' num2str(cnt) '.' num2str(sum(indicator))]);\r\n\t\t\tend\r\n\tend\r\n\r\n\t#% step 3\r\n\tV = UNIFORMdirections(m-1,n);\r\n\tX = [repmat(sqrt(1-w'.^2),m-1,1).*V ;w'];\r\n\r\n\tif muflag\r\n\t\t\tmu = mu / norm(mu);\r\n\t\t\tX = rotMat(mu)'*X;\r\n\tend\r\n\treturn X\r\nend\r\n\r\n\r\nfunction UNIFORMdirections(m,n)\r\n\t#% generate n uniformly distributed m dim'l random directions\r\n\t#% Using the logic: \"directions of Normal distribution are uniform on sphere\"\r\n\r\n\tV = zeros(m,n);\r\n\tnr = randn(m,n); #%Normal random \r\n\tfor i=1:n\r\n\t\t\twhile true\r\n\t\t\t\t\tni=(nr[:,i]'*nr[:,i])[1]; #% length of ith vector\r\n\t\t\t\t\t#% exclude too small values to avoid numerical discretization\r\n\t\t\t\t\tif ni < 1e-10 \r\n\t\t\t\t\t\t\t#% so repeat random generation\r\n\t\t\t\t\t\t\tnr[:,i]=randn(m,1);\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\t\t V[:,i]=nr[:,i]/sqrt(ni);\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tend\r\n\t\t\tend\r\n\tend\r\n\r\n\treturn V\r\nend\r\n\r\nfunction rotMat(b, a = None, alpha = None)\r\n\t#% ROTMAT returns a rotation matrix that rotates unit vector b to a\r\n\t#%\r\n\t#%   rot = rotMat(b) returns a d x d rotation matrix that rotate\r\n\t#%   unit vector b to the north pole (0,0,...,0,1)\r\n\t#%\r\n\t#%   rot = rotMat(b,a ) returns a d x d rotation matrix that rotate\r\n\t#%   unit vector b to a\r\n\t#%\r\n\t#%   rot = rotMat(b,a,alpha) returns a d x d rotation matrix that rotate\r\n\t#%   unit vector b towards a by alpha (in radian)\r\n\t#%\r\n\t#%    See also .\r\n\t#\r\n\t#% Last updated Nov 7, 2009\r\n\t#% Sungkyu Jung\r\n\r\n\r\n\ts1 = size(b,1)\r\n\ts2 = size(b,2)\r\n\td = max(s1,s2);\r\n\tb= b/norm(b);\r\n\r\n\tif s1<=s2\r\n\t\tb = b'\r\n\tend\r\n\r\n\tif a == None \r\n\t\t\ta = [zeros(d-1,1); 1];\r\n\tend\r\n\tif alpha == None\r\n\t\t\talpha = acos((a'*b)[1]);\r\n\tend\r\n\r\n\tif abs((a'*b)[1] - 1) < 1e-15\r\n\t\trot = eye(d)\r\n\t\treturn rot\r\n\tend\r\n\tif abs((a'*b)[1] + 1) < 1e-15\r\n\t\trot = -eye(d)\r\n\t\treturn rot\r\n\tend\r\n\r\n\tc = b - a * (a'*b); c = c / norm(c);\r\n\tA = a*c' - c*a' ;\r\n\r\n\trot = eye(d) + sin(alpha)*A + (cos(alpha) - 1)*(a*a' +c*c');\r\nend\r\n\r\n", "meta": {"hexsha": "dfa4a693a1508a3e850860356ddb84e37102942d", "size": 3973, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/randVonMisesFisher.jl", "max_stars_repo_name": "daniel-perry/Kernel.jl", "max_stars_repo_head_hexsha": "da7255ffe7b9e1341d4f2decc82128451dc3d383", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/randVonMisesFisher.jl", "max_issues_repo_name": "daniel-perry/Kernel.jl", "max_issues_repo_head_hexsha": "da7255ffe7b9e1341d4f2decc82128451dc3d383", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-07-12T17:40:45.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-12T17:40:45.000Z", "max_forks_repo_path": "src/randVonMisesFisher.jl", "max_forks_repo_name": "daniel-perry/Kernel.jl", "max_forks_repo_head_hexsha": "da7255ffe7b9e1341d4f2decc82128451dc3d383", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6770186335, "max_line_length": 79, "alphanum_fraction": 0.582683111, "num_tokens": 1397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391600697869, "lm_q2_score": 0.863391602943619, "lm_q1q2_score": 0.796944259992385}}
{"text": "# ---\n# title: 382. Linked List Random Node\n# id: problem382\n# author: zhwang\n# date: 2022-02-15\n# difficulty: Medium\n# categories: Reservoir Sampling\n# link: <https://leetcode.com/problems/linked-list-random-node/description/>\n# hidden: true\n# ---\n# \n# Given a singly linked list, return a random node's value from the linked list.\n# Each node must have the **same probability** of being chosen.\n# \n# **Follow up:**  \n# What if the linked list is extremely large and its length is unknown to you?\n# Could you solve this efficiently without using extra space?\n# \n# **Example:**\n# \n#     \n#     \n#     // Init a singly linked list [1,2,3].\n#     ListNode head = new ListNode(1);\n#     head.next = new ListNode(2);\n#     head.next.next = new ListNode(3);\n#     Solution solution = new Solution(head);\n#     \n#     // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.\n#     solution.getRandom();\n#     \n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction get_random(head::ListNode)::Int\n    node, i, res = head, 1, 0\n    while !isnothing(node)\n        if rand(1:i) == 1  ## 1/i prob for value change\n            res = node.val\n        end\n        node = node.next\n        i += 1\n    end\n    return res\nend\n## @lc code=end\n", "meta": {"hexsha": "4e3a3fd0ba9a2855108c8baf78ba326858352fe7", "size": 1277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/382.linked-list-random-node.jl", "max_stars_repo_name": "RexWzh/LeetCode.jl", "max_stars_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/382.linked-list-random-node.jl", "max_issues_repo_name": "RexWzh/LeetCode.jl", "max_issues_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/382.linked-list-random-node.jl", "max_forks_repo_name": "RexWzh/LeetCode.jl", "max_forks_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0612244898, "max_line_length": 119, "alphanum_fraction": 0.6327329679, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8757869981319863, "lm_q1q2_score": 0.7968847168388453}}
{"text": "#!/usr/bin/julia\n\nfunction base10ToAny(in_dig,base)\n    if base >= 21\n        println(\"Warning: There're not special characters for digits in base 21 or more\")\n    end\n    digits_b10=[]\n    q=in_dig\n    while true\n        if q % base <= 9\n            push!(digits_b10,q % base)\n        elseif q % base == 10\n            push!(digits_b10,'A')\n        elseif q % base == 11\n            push!(digits_b10,'B')\n        elseif q % base == 12\n            push!(digits_b10,'C')\n        elseif q % base == 13\n            push!(digits_b10,'D')\n        elseif q % base == 14\n            push!(digits_b10,'E')\n        elseif q % base == 15\n            push!(digits_b10,'F')\n        elseif q % base == 16\n            push!(digits_b10,'G')\n        elseif q % base == 17\n            push!(digits_b10,'H')\n        elseif q % base == 18\n            push!(digits_b10,'I')\n        elseif q % base == 19\n            push!(digits_b10,'J')\n        else\n            r=(q % base)\n            push!(digits_b10,\"($r)\")\n        end\n        q=div(q,base)\n        if q == 0\n            break\n        end\n    end\n    l=length(digits_b10)\n    to_ret=[]\n    for idx in 1:l\n        push!(to_ret,pop!(digits_b10))\n    end\n    if base <= 10\n        return parse(Int,join(to_ret))\n    else\n        return join(to_ret)\n    end\nend\n\nfunction anyBaseTo10(iterDig,base)\n    if base >= 21\n        println(\"Error: Only works for a base 20 or less\")\n        return\n    end\n    if !isa(iterDig,AbstractString)\n        println(\"Error: Input n should be a string\")\n        return\n    end\n    summation=0\n    l=sizeof(iterDig)\n    for idx in 1:l\n        digit = iterDig[ l - (idx-1)]\n        if digit == 'A'\n            digit = 10\n        elseif digit == 'B'\n            digit = 11\n        elseif digit == 'C'\n            digit = 12\n        elseif digit == 'D'\n            digit = 13\n        elseif digit == 'E'\n            digit = 14\n        elseif digit == 'F'\n            digit = 15\n        elseif digit == 'G'\n            digit = 16\n        elseif digit == 'H'\n            digit = 17\n        elseif digit == 'I'\n            digit = 18\n        elseif digit == 'J'\n            digit = 19\n        else\n            digit = parse(Int64, digit)\n        end\n        summation = digit*(base^(idx-1)) + summation\n    end\n    return summation\nend\n\nfunction binAddition(in_bin_1,in_bin_2)\n    in_bin_1=base10ToAny(in_bin_1,2)\n    in_bin_2=base10ToAny(in_bin_2,2)\n    ib1=string(in_bin_1)\n    ib2=string(in_bin_2)\n    l1=sizeof(ib1)\n    l2=sizeof(ib2)\n    if l1 > l2\n        AddZeros = l1 - l2\n        ib2=(\"0\" ^ AddZeros) * ib2\n        larger=l1\n    elseif l2 > l1\n        AddZeros = l2 - l1\n        ib1=(\"0\" ^ AddZeros) * ib1\n        larger=l2\n    else\n        larger=l1\n    end\n    c=0\n    all_s=[]\n    for idx in 1:larger\n        dig1= parse(Int64, ib1[ larger - (idx-1) ])\n        dig2= parse(Int64, ib2[ larger - (idx-1) ])\n        d=div( dig1 + dig2 + c, 2)\n        s=dig1 + dig2 + c - 2d\n        c=d\n        push!(all_s,s)\n    end\n    push!(all_s,c)\n    justZero = true\n    catResult=[]\n    for idx in 1:length(all_s)\n        if length(all_s) == 2 && join(all_s) == \"00\"\n            return 0\n        end\n        if justZero && all_s[ length(all_s) - (idx -1 ) ] == 0\n            continue\n        end\n        if all_s[ length(all_s) - (idx -1 ) ]  == 1\n            justZero = false\n        end\n        push!(catResult,all_s[ length(all_s) - (idx -1 ) ])\n    end\n    return anyBaseTo10(join(catResult),2)\nend\n\nfunction binMultiplication(a,b)\n    a=base10ToAny(a,2)\n    b=base10ToAny(b,2)\n    a=string(a)\n    b=string(b)\n    la=sizeof(a)\n    lb=sizeof(b)\n    if la > lb\n        AddZeros = la - lb\n        b=(\"0\" ^ AddZeros) * b\n        larger=la\n    elseif lb > la\n        AddZeros = lb - la\n        a=(\"0\" ^ AddZeros) * a\n        larger=lb\n    else\n        larger=la\n    end\n    c_partials=[]\n    for idx in 1:larger\n        if b[larger - (idx -1)] == '1'\n            c = a * (\"0\" ^ (idx - 1))\n            push!(c_partials,c)\n        else\n            c = \"0\"\n            push!(c_partials,c)\n        end\n    end\n    p = 0\n    for partial in c_partials\n        partial = parse(Int64, partial)\n        p = binAddition(p,anyBaseTo10(string(partial),2))\n    end\n    return p\nend\n\n\n\n\n# Division Algorithm\n# a = d(q) + r\nfunction intDivision(a::Int,d::Int)\n    q = 0\n    r = abs(a)\n    while r >= d\n        r = r - d\n        q = q + 1\n    end\n    if a < 0 && r > 0\n        r = d - r\n        q = -(q + 1)\n    end\n    return [q,r]\nend\n\n# Modular Exponentiation\n# x = b ^ n mod m\nfunction modExp(b::Int, n::Int, m::Int)\n    n=base10ToAny(n,2) #convert to binary\n    x=1\n    power=mod(b,m)\n    ns=string(n)\n    for idx in 1:sizeof(ns)\n        if ns[sizeof(ns) - (idx-1)] == '1'\n            x = mod(x * power,m)\n        end\n        power = mod((power * power),m)\n    end\n    return x\nend\n\ninstall.packages(\"plotly\")\n# The Euclidean Algorithm\nfunction gcd(a::Int,b::Int)\n    x=a\n    y=b\n    while y != 0\n        r = mod(x,y)\n        x = y\n        y = r\n    end\n    return x\nend\n\nfunction sieveEratosthenes(n::Int) # accepts one integer argument\n    isprime = ones(Bool, n) # n-element vector of true-s\n    isprime[1] = false\n    # 1 is not a prime\n    for i in 2:round(Int, sqrt(n)) # loop integers from 2 to sqrt(n)\n        if isprime[i]\n            # conditional evaluation\n            for j in (i*i):i:n # sequence with step i\n            isprime[j] = false\n            end\n        end\n    end\n    return filter(x -> isprime[x], 1:n) # filter using anonymous function\nend\n", "meta": {"hexsha": "cd910351658795d2876b49222d3964fd5717020b", "size": 5513, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "maths/operations_bases/BasicOperations.jl", "max_stars_repo_name": "elbecerrasoto/tutti-frutti", "max_stars_repo_head_hexsha": "edb33d78f490e4a2a084af005b7679e296368e18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-03T02:21:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T02:21:22.000Z", "max_issues_repo_path": "maths/operations_bases/BasicOperations.jl", "max_issues_repo_name": "elbecerrasoto/tutti-frutti", "max_issues_repo_head_hexsha": "edb33d78f490e4a2a084af005b7679e296368e18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maths/operations_bases/BasicOperations.jl", "max_forks_repo_name": "elbecerrasoto/tutti-frutti", "max_forks_repo_head_hexsha": "edb33d78f490e4a2a084af005b7679e296368e18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1638655462, "max_line_length": 89, "alphanum_fraction": 0.494467622, "num_tokens": 1745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505204, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7968710842545336}}
{"text": "# # Implementation of the real cubic root finding method described in:\n# # 92.34 The cubic equation – a new look at the irreducible case\n# # Author(s): I. J. ZUCKER\n# # Source: The Mathematical Gazette , July 2008, Vol. 92, No. 524 (July 2008), pp. 264-268\n# # Published by: The Mathematical Association of America\n# # Stable URL: https://www.jstor.org/stable/27821778\n\n\n\"\"\"\nReturn all the real roots of a cubic equation represented as a\nvector of real coefficients for terms of increasing degree.\nNote that any higher order coefficients (degree >= 4) are ignored.\n\nImplementation of the real cubic root finding method of Zucker (2008).\n\"\"\"\nfunction solve_real_cubic_roots(polycoeff::Vector{T}; \n    warn_scaling::Bool=true,\n    leading_tol::Float64=CUBIC_ATOL,\n    coeff_tol::Float64=1.0/CUBIC_ATOL) where {T<:Real}\n\n    Rts = Vector{Float64}() # object to return with real roots inside.\n\n    if length(polycoeff) < 4\n        @error \"There are too few coefficients given.\"\n        return Rts\n    end\n\n    if warn_scaling && isapprox(polycoeff[4], zero(T), atol=leading_tol)\n        @warn \"The leading cubic coefficient is approximately zero. Returning empty array.\"\n        ## TODO?: fall back to solving a quadratic instead\n        return Rts\n    end\n\n    (e, d, c) = polycoeff[1:3]./polycoeff[4]\n    \n    if warn_scaling && poor_conditioning((e,d,c), coeff_tol)\n        @warn \"Large coefficients in scaled polynomial. Poor conditioning may occur.\"\n    end\n   \n    # We reduce f(x) = e + d*x + c*x^2 + x^3 via x == t - c/3 to\n    # the standard transformed form f'(t) = 2q + 3p*t + t^3 :\n    p = d/3 - c^2/9\n    q = (c^3/27) - (c*d/6) + e/2\n    Disc = q^2 + p^3  # cubic discriminant\n\n    if Disc >= 0  # one real root: encompasses the case where p >= 0.\n        u = cbrt(-q + sqrt(Disc))\n        v = cbrt(-q - sqrt(Disc))\n\n        r1 = u + v            # transformed real cubic root\n        push!(Rts, r1 - c/3)  # original cubic root\n    elseif Disc < 0  # three real roots : we necessarily have p < 0, hence 0 < s < 1\n        h = q/p\n        s = Disc/p^3\n        w = sqrt(s)\n\n        r_hyp = [\n                   2*h*HgF(1//3, 2//3, 1//2, s),\n             (-2//3)*h*HgF(2//3, 4//3, 3//2, 1//2*(1 + w)),\n             (-2//3)*h*HgF(2//3, 4//3, 3//2, 1//2*(1 - w)),\n        ]\n\n        append!(Rts, r_hyp .- c/3)\n    else\n        error(\"\"\"\n        The computed discriminant is not comparable to 0;\n        it may have a value of NaN or Inf due to numerical overflow.\n        \"\"\")\n    end\n\n    return Rts\nend\n\nfunction solve_all_cubic_roots(polycoeff::Vector{T}; \n    warn_scaling::Bool=true,\n    leading_tol::Float64=CUBIC_ATOL,\n    coeff_tol::Float64=1.0/CUBIC_ATOL) where {T<:Real}\n\n    Rts = Vector{Complex{Float64}}()\n\n    real_roots = solve_real_cubic_roots(polycoeff; warn_scaling, leading_tol, coeff_tol)\n    append!(Rts, real_roots)\n\n    if length(real_roots) == 3\n        return Rts\n    elseif length(real_roots) == 1\n        r = real_roots[1]\n        c0, c1, c2 = polycoeff[1:3]./polycoeff[4]\n        # If we know the one real root r of c0 + c1*z + c2*z^2 + z^3 = 0,\n        # then we can solve a quadratic -c0/r + (c2 + r)*x + x^2 = 0 (or multiply through by r)\n        # to obtain s1 and s2, the complex conjugate roots, since\n        # c0 = -r*s1*s2 and c2 = -(r + s1 + s2), \n        # and we obtain the sum and product of s1 and s2:\n        complex_roots = solve_quadratic_roots([-c0, r*(r + c2), r]) # return type Vector{Complex{Float64}}\n        Rts = append!(Rts, complex_roots)\n        return Rts\n    else\n        error(\"Incorrect number of cubic roots returned: $(Rts).\")\n        return Rts\n    end\n    \n        \nend", "meta": {"hexsha": "d67bfe81d24ab400f497d67f50d6b397bd3d148a", "size": 3636, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cubic.jl", "max_stars_repo_name": "jd-foster/HyperCubicRoots", "max_stars_repo_head_hexsha": "2094f30676e9b76a0cc621666868a546084cf17e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cubic.jl", "max_issues_repo_name": "jd-foster/HyperCubicRoots", "max_issues_repo_head_hexsha": "2094f30676e9b76a0cc621666868a546084cf17e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cubic.jl", "max_forks_repo_name": "jd-foster/HyperCubicRoots", "max_forks_repo_head_hexsha": "2094f30676e9b76a0cc621666868a546084cf17e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3009708738, "max_line_length": 106, "alphanum_fraction": 0.6025852585, "num_tokens": 1142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.7968710838317384}}
{"text": "# # Nonnegative over a variety\n\n#md # [![](https://mybinder.org/badge_logo.svg)](@__BINDER_ROOT_URL__/generated/Getting started/circle.ipynb)\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/generated/Getting started/circle.ipynb)\n\n# The polynomial ``1 - y^2`` is nonnegative for all ``y`` in the unit circle.\n# This can be verified using Sum-of-Squares.\n\nusing Test #src\nusing DynamicPolynomials\nusing SumOfSquares\n@polyvar x y\nS = @set x^2 + y^2 == 1\n\n# We need to pick an SDP solver, see [here](https://jump.dev/JuMP.jl/v0.23.0/installation/#Supported-solvers) for a list of the available choices.\n# The domain over which the nonnegativity of ``1 - y^2`` should be certified\n# is specified through the `domain` keyword argument.\n\nimport CSDP\nmodel = SOSModel(CSDP.Optimizer)\nset_silent(model)\ncon_ref = @constraint(model, 1 - y^2 >= 0, domain = S)\noptimize!(model)\n\n# We can see that the model was feasible:\n\n@test JuMP.termination_status(model) == MOI.OPTIMAL #src\n@test JuMP.primal_status(model) == MOI.FEASIBLE_POINT #src\nsolution_summary(model)\n\n# The certificate can be obtained as follows:\n\ndec = sos_decomposition(con_ref, 1e-6) #src\n@test length(dec) == 1 #src\n@test first(dec) ≈ x rtol = 1e-6 #src\nsos_decomposition(con_ref, 1e-6)\n\n# It returns ``x^2`` which is a valid certificate as:\n# $$ 1 - y^2 \\equiv x^2 \\pmod{x^2 + y^2 - 1} $$\n", "meta": {"hexsha": "baa4c394dac8022a6b908553814941effbfbed8b", "size": 1387, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/tutorials/Getting started/circle.jl", "max_stars_repo_name": "blegat/SumOfSquares", "max_stars_repo_head_hexsha": "a4e1a6ac8853bb3df3e46e33e6cce658c1c6df12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2016-11-10T11:05:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-10T09:08:47.000Z", "max_issues_repo_path": "docs/src/tutorials/Getting started/circle.jl", "max_issues_repo_name": "blegat/SumOfSquares", "max_issues_repo_head_hexsha": "a4e1a6ac8853bb3df3e46e33e6cce658c1c6df12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 138, "max_issues_repo_issues_event_min_datetime": "2016-11-23T01:37:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-08T18:13:22.000Z", "max_forks_repo_path": "docs/src/tutorials/Getting started/circle.jl", "max_forks_repo_name": "blegat/SumOfSquares", "max_forks_repo_head_hexsha": "a4e1a6ac8853bb3df3e46e33e6cce658c1c6df12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2017-03-16T20:55:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T19:05:37.000Z", "avg_line_length": 34.675, "max_line_length": 146, "alphanum_fraction": 0.7217015141, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.796871077890285}}
{"text": "using GaussQuadrature\nusing PyPlot\n\nx = collect(linspace(0, 1, 201))\nconst n = 5\n\na, b = shifted_legendre_coefs(Float64, n)\np = orthonormal_poly(x, a, b)\ngrid(true)\n\nfigure(1)\nplot(x, p)\nconst r = 0\nα, β = logweight_coefs(Float64, n+1, r)\nq = orthonormal_poly(x, α[1:n], β)\ntitle(\"Orthonormal shifted Legendre polynomials\")\n\nfigure(2)\nplot(x, q)\ngrid(true)\ns = \"Orthonormal polymials with weight \\$\\\\log x^{-1}\\$\"\ntitle(latexstring(s))\n", "meta": {"hexsha": "6997e4bd9593d20be77c735ed344a84aa1c0a794", "size": 436, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/show_orthog.jl", "max_stars_repo_name": "lcw/GaussQuadrature.jl", "max_stars_repo_head_hexsha": "b886776942e489f74a97176db8dca82e15f03f8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/show_orthog.jl", "max_issues_repo_name": "lcw/GaussQuadrature.jl", "max_issues_repo_head_hexsha": "b886776942e489f74a97176db8dca82e15f03f8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/show_orthog.jl", "max_forks_repo_name": "lcw/GaussQuadrature.jl", "max_forks_repo_head_hexsha": "b886776942e489f74a97176db8dca82e15f03f8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9565217391, "max_line_length": 56, "alphanum_fraction": 0.6972477064, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.7968693640168172}}
{"text": "#= Install the primes package: (if unavailable)\nimport Pkg; Pkg.add(\"Primes\") =#\nusing Primes\n\n# Public key: (e,n)\nstruct PublicKey\n    n::Integer\n    e::Integer\nend\n\n# Private key: (d,n)\nstruct PrivateKey\n    n::Integer\n    d::Integer    \nend\n\nfunction keyGenerator(p::Integer, q::Integer, e::Integer)\n    # Basic corner cases:    \n    isprime(p) || error(\"p must be a prime number\")\n    isprime(q) || error(\"q must be a prime number\")\n    e > 0 || error(\"e must be positive\")\n    # Computing Euler's totient:\n    phi = (p - 1) * (q - 1)\n    # Computing greatest common divisor and Bézout coefficients (i.e. u and v, such that u*e + u*phi = gcd(e,phi)):\n    (g, u, v) = gcdx(e,phi)\n    # If gcd(e,phi)!=1, they aren't coprime: \n    g == 1 || error(\"phi(n) and e must be coprime\")\n    # Computing private exponent d based on (+ve)/(-ve) value of u through a ternary operator:\n    u < 0 ? d = (u % phi) + phi : d = u % phi\n    # Computing n as the product of the two entered primes and returning the computed public and private key components: \n    n = p * q\n    return PublicKey(n, e), PrivateKey(n, d)\nend\n\n# Encryption function:\nfunction encrypt(m::Integer, k::PublicKey)\n    0 <= m || error(\"m must be non-negative\")\n    m < k.n || error(\"m is too large\")\n    return powermod(m, k.e, k.n)\nend\n\n# Decryption function:\nfunction decrypt(c::Integer, k::PrivateKey)\n    0 <= c || error(\"c must be non-negative\")\n    c < k.n || error(\"c is too large\")\n    return powermod(c, k.d, k.n)\nend\n\nprint(\"Enter a prime number: \")\np = parse(Int, readline())\nprint(\"Enter another prime number: \")\nq = parse(Int, readline())\nprint(\"Enter public key exponent: \")\ne = parse(Int, readline())\n(publicKey, privateKey) = keyGenerator(p, q, e)\nprintln(\"Public key (n,e) = ($(publicKey.n),$(publicKey.e)); (to be shared)\")\nprintln(\"Private key (n,d) = ($(privateKey.n),$(privateKey.d)); (to be kept with oneself)\")\nprintln(\"Enter an integer to encrypt:\")\nm = parse(Int, readline())\nprintln(\"Original integer: $m\")\nc = encrypt(m, publicKey)\nprintln(\"Encrypted integer: $c\")\nprintln(\"Decrypted integer: $(decrypt(c,privateKey))\")", "meta": {"hexsha": "f6cf36bd1c24335980cacb9428383900eeb37139", "size": 2105, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Implementations/RSA.jl", "max_stars_repo_name": "Anirban166/RSA-Cryptosystem", "max_stars_repo_head_hexsha": "2283bbeab811fb4cacf86b55c9f6e7247610bf74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 65, "max_stars_repo_stars_event_min_datetime": "2019-05-22T16:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-06T09:37:53.000Z", "max_issues_repo_path": "Implementations/RSA.jl", "max_issues_repo_name": "Anirban166/RSA-Cryptosystem", "max_issues_repo_head_hexsha": "2283bbeab811fb4cacf86b55c9f6e7247610bf74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-03T05:13:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-03T05:14:03.000Z", "max_forks_repo_path": "Implementations/RSA.jl", "max_forks_repo_name": "Anirban166/RSA-Cryptosystem", "max_forks_repo_head_hexsha": "2283bbeab811fb4cacf86b55c9f6e7247610bf74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-05-22T16:34:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-28T14:26:47.000Z", "avg_line_length": 33.4126984127, "max_line_length": 121, "alphanum_fraction": 0.6408551069, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.796869360870359}}
{"text": "\n\nfunction lagrange_interpolant(R, xs, i)\n    n = length(xs)\n    x = AbstractAlgebra.gen(R)\n\n    f = R(prod(\n        j == i ? 1 : (x - xs[j])\n        for j in 1:n\n    ))\n    \n    c = prod(\n        j == i ? 1 : (xs[i] - xs[j])\n        for j in 1:n\n    )\n\n    AbstractAlgebra.map_coefficients(t -> t // c, f)\nend\n\n# univariate\n# returns :: AbstractAlgebra.Generic.Poly\nfunction interpolate_polynomial(R, xs, ys)\n    f = sum(\n        ys[i] * lagrange_interpolant(R, xs, i)\n        for i in 1:length(xs)\n    )\nend\n\n\n\"\"\"\n    For given polynomial g and m computes the rational fraction r//t,\n    s.t. r//t approximates g modulo m \n    \n        r == t*g (mod m)\n    \n    and\n        deg(r) + deg(t) <= deg(m)\n\n    Throws if ??? TODO\n\"\"\"\nfunction polynomial_reconstruction(g, m)\n    # The function implements Algorithm 12.9 from\n    #   \"Modern Computer Algebra\", second edition,\n    #   Joachim von zur Gathen, Jürgen Gerhard\n\n    n = AbstractAlgebra.degree(m)\n    k = div(n, 2)\n    FF = AbstractAlgebra.parent(g)\n\n    U = (FF(1), FF(0), m)\n    V = (FF(0), FF(1), g)\n    while AbstractAlgebra.degree(V[3]) >= k\n        q = div(U[3], V[3])\n        T = U .- q .* V\n        U = V\n        V = T\n    end\n\n    r, t = V[3], V[2]\n\n    if gcd(r, t) == FF(1) && AbstractAlgebra.degree(t) <= n - k\n        return r // t\n    end\n\n    throw(DomainError(\n        g, \"reconstruction of $g (mod $m) does not exist\"\n    ))\nend\n\n\n\"\"\"\n    Interpolates rational function in the given ring R with\n    the given interpolation points xs and ys by\n    interpolating as a polynomial first\n    and reconstructing into a polynomial fraction after\n\"\"\"\nfunction interpolate_rational_function(R, xs, ys)\n    # The function implements algorithm derived from Corollary 5.20 of\n    #   \"Modern Computer Algebra\", second edition,\n    #   Joachim von zur Gathen, Jürgen Gerhard\n\n    x = AbstractAlgebra.gen(R)\n    g = Nemo.interpolate(R, xs, ys)\n\n    # TODO: this computation can be done faster\n    m = prod(x - xs[i] for i in 1:length(xs))\n    \n    polynomial_reconstruction(g, m)\nend\n\n\n# TODO: why is it still here?\nfunction interpolate_multivariate_rational_function(MR, R, xs, ys)\n   \n    f = interpolate_rational_function(R, xs, ys)\n    \n    f   \nend\n\n\"\"\"\n    Returns reversed vector of base-adic representation of n\n\"\"\"\nfunction decompose_by_degrees(n, base, len)\n    powers = [base^(i-1) for i in 1:len]\n    exps = zeros(Int, len)\n    for i in 1:len\n        exps[len - i + 1] = div(n, powers[len - i + 1])\n        n = n - exps[len - i + 1] * powers[len - i + 1]\n    end\n    exps\nend\n\n\n# TODO : not used\nfunction random_linear_shift(ground_ring, n)\n    functors = []\n    inverses = []\n    \n    for i in 1:n\n        a, b = ground_ring(rand(1:10000)), ground_ring(rand(1:10000))\n        f  = ( x -> x + b ) \n        fi = ( x -> x - b )\n        \n        push!(functors, f)\n        push!(inverses, fi)\n    end\n    \n    return functors, inverses\nend\n\n\n\"\"\"\n    Given a callable functor f tries to find degrees of univariate polynomials\n    A, B approximating f as a rational function f = A // B\n\"\"\"\n# TODO: not used\nfunction predict_degrees(f)\n    # staring from small amount of points..\n    n = 8\n\n    # = deg(A), deg(B) initially\n    predicted_degrees = (n, n)\n\n    polyring, = AbstractAlgebra.PolynomialRing(ground, \"u\")    \n    \n    # \"safety condition\" to assume f is interpolated correctly indeed\n    # failes on first iteration\n    while 4*(sum(predicted_degrees) + 2) > n  \n        xs = [ rand(f) for _ in 1:n  ]\n        ys = f.(xs)\n            \n        interpolated = interpolate_rational_function(polyring, xs, ys)    \n        \n        predicted_degrees = map(degree, (numerator(interpolated), denominator(interpolated)))   \n        \n        @debug \"for $n points degrees are \" predicted_degrees\n\n        n = n * 2\n    end\n    \n    predicted_degrees\nend\n\n\n\n\"\"\"\n    Same as the function above, key difference is that here\n    f returns an array of results on each evaluation\n\"\"\"\n# TODO: not used\nfunction simultaneous_predict_degrees(f)\n    # staring from small amount of points..\n    n = 8\n    \n    polyring = base_ring(f)\n    nfrom, nto = arity(f)\n\n    predicted_degrees = [ (n, n) for _ in 1:nto ]\n    already_interpolated = 0    \n\n    while already_interpolated < nto \n        \n        4*(sum(values(predicted_degrees)) + 2) > n\n        xs = [ rand(f) for _ in 1:n  ]\n        ys = f.(xs)\n\n        for (j, deg) in enumerate(predicted_degrees)\n            if 4*(sum(deg) + 2) < n\n                continue\n            end\n            yparticular = [y[j] for y in ys]\n            interpolated = interpolate_rational_function(polyring, xs, yparticular)\n            \n            predicted_degrees[j] = map(degree, (numerator(interpolated), denominator(interpolated)))\n\n        end\n\n        @debug \"for $n points degrees are \" predicted_degrees\n\n        n = n * 2\n    end\n\n    predicted_degrees\nend\n\n\n\"\"\"\n    \n\"\"\"\n# TODO: not used\nfunction backward_kronecker(\n                     f,\n                     target_ring,\n                     maxexp) where {T}\n\n    polybuilder = MPolyBuildCtx(target_ring)\n    nvariables = length(gens(target_ring)) \n    \n\n    # TODO: fix 0:degree(f)\n    for (e, c) in zip(0:degree(f), coefficients(f))\n        if iszero(c)\n            continue\n        end\n        push_term!(\n            polybuilder,\n            c,\n            decompose_by_degrees(e, maxexp, nvariables)\n        )\n    end\n\n    finish(polybuilder)\nend\n\n\nfunction decompose_by_good_degrees(e, prods, n)\n    ans = zeros(Int, n)\n\n    for i in 1:n\n        ans[n - i + 1] = div(e, prods[n - i + 1])\n        e = mod(e, prods[n - i + 1])\n    end\n    \n    ans\nend\n\nfunction backward_good_kronecker(\n                     f,\n                     target_ring,\n                     exps) where {T}\n    \n    prods = deepcopy(exps)\n    prods[1] = 1\n    for i in 2:length(prods)\n        prods[i] = prods[i - 1] * (exps[i - 1] + 1)\n    end\n\n    polybuilder = MPolyBuildCtx(target_ring)\n    nvariables = length(gens(target_ring))\n\n    for (e, c) in zip(0:degree(f), coefficients(f))\n        if iszero(c)\n            continue\n        end\n        push_term!(\n            polybuilder,\n            c,\n            decompose_by_good_degrees(e, prods, nvariables)\n        )\n    end\n\n    ans = finish(polybuilder)\n    ans\nend\n\n\nfunction backward_kronecker(\n                  f::AbstractAlgebra.Generic.Frac{T},\n                  target_ring,\n                  maxexp) where {T}\n\n    backward_kronecker(numerator(f), target_ring, maxexp) //\n        backward_kronecker(denominator(f), target_ring, maxexp)\nend\n\nfunction backward_good_kronecker(\n                  f::AbstractAlgebra.Generic.Frac{T},\n                  target_ring,\n                  maxexp) where {T}\n\n    backward_good_kronecker(numerator(f), target_ring, maxexp) //\n        backward_good_kronecker(denominator(f), target_ring, maxexp)\nend\n\nfunction generate_kronecker_points(ground, maxexp, nvariables)\n    npoints = (maxexp^nvariables + 2) * 2\n    xs = [rand(ground) for _ in 1:npoints]\n    points = [\n        [ ground(j)^i for i in [ (maxexp)^k for k in 0:(nvariables - 1) ] ]\n          for j in xs\n    ]\n    xs, points\nend\n\nfunction generate_good_kronecker_points(ground, exps, nvariables)\n    npoints = prod( map(x -> x + 1, exps) ) * 2\n   \n    prods = deepcopy(exps)\n    # univariate case? =(\n    prods[1] = 1\n    for i in 2:length(prods)\n        prods[i] = prods[i - 1] * (exps[i - 1] + 1)\n    end\n    \n    xs = Set([rand(ground) for _ in 1:npoints])\n    while length(xs) < npoints\n        xs = union!(xs, Set([rand(ground) for _ in 1:(npoints-length(xs))]))\n    end\n    xs = collect(xs)\n\n    points = [\n        [ p^prods[k] for k in 1:nvariables ]\n        for p in xs\n    ]\n    \n    xs, points\nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "9f6c046668cfde55e17b8aecc92eb7ac34d0dd0f", "size": 7726, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/interpolation.jl", "max_stars_repo_name": "sumiya11/RationalFunctionFields", "max_stars_repo_head_hexsha": "648db6a3ca01fd087b9eeba4e72930f73210e765", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-23T23:19:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T03:25:12.000Z", "max_issues_repo_path": "src/interpolation.jl", "max_issues_repo_name": "sumiya11/RationalFunctionFields", "max_issues_repo_head_hexsha": "648db6a3ca01fd087b9eeba4e72930f73210e765", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-09-03T19:40:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-16T14:18:26.000Z", "max_forks_repo_path": "src/interpolation.jl", "max_forks_repo_name": "sumiya11/RationalFunctionFields", "max_forks_repo_head_hexsha": "648db6a3ca01fd087b9eeba4e72930f73210e765", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.265129683, "max_line_length": 100, "alphanum_fraction": 0.5676935025, "num_tokens": 2200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7968693565039919}}
{"text": "function colNullities(P::AbstractArray, tol=0)\n    A, B = toPencil(P)\n    return colNullities(A, B, tol)\nend\n\n\"\"\"\n    e, d, Ar, Br = colNullities(A, B, tol=0)\ncomputes the column nullities of the pencil Bx-A.\ne = column nullities\nd =  nullities of infinite eigenvalue\nx*Br - Ar = reduced pencil containing only finite eigenvalues and row indices\n\"\"\"\nfunction colNullities(A::AbstractArray{T, N}, B::AbstractArray{T, N}, tol=0) where {T<:Number, N}\n\n    r = rank(B, atol=tol)\n    s = size(B, 2) - r\n    blocks  = [s]\n    ranks = Int[]\n\n    while s != 0\n        F = svd(B, full=true);\n        B = B*F.V\n        A = A*F.V\n\n        F = svd(A[:, r+1:end], full=true)\n        Ua = F.U\n        ra = rank(A[:, r+1:end], atol=tol)\n        push!(ranks, ra)\n        P = Matrix(I, size(Ua))\n        P = P[[ra+1:end; 1:ra], :]\n        A = P*Ua'*A\n        B = P*Ua'*B\n\n        A = A[1:end-ra, 1:r]\n        B = B[1:end-ra, 1:r]\n        r = rank(B, atol=tol)\n        s = size(B, 2) - r\n        push!(blocks, s)\n    end\n    e = blocks[1:end-1] - ranks\n    d = ranks - blocks[2:end]\n\n    removeTailZeroes!(e)\n    removeTailZeroes!(d)\n    iszero(d) && (d = Int[])\n    iszero(e) && (e = Int[])\n    return e, d, A, B\nend\n\nfunction rowNullities(P::AbstractArray, tol=0)\n    A, B = toPencil(P)\n    return rowNullities(A, B, tol)\nend\n\n\"\"\"\n    e, d, Ar, Br = colNullities(A, B, tol=0)\ncomputes the row nullities of the pencil Bx-A.\ne = row nullities\nd =  nullities of infinite eigenvalue\nx*Br - Ar = reduced pencil containing only finite eigenvalues and column indices\n\"\"\"\nfunction rowNullities(A::AbstractArray{T, N}, B::AbstractArray{T, N}, tol=0) where {T<:Number, N}\n\n    r = rank(B, atol=tol)\n    s = size(B, 1) - r\n    blocks = [s]\n    ranks = Int[]\n    while s != 0\n        F = svd(B, full=true)\n        Ub = F.U\n        P = Matrix(I, size(Ub))\n        P = P[[r+1:end; 1:r], :]\n        B = P*Ub'*B\n        A = P*Ub'*A\n        F = svd(A[1:s, :], full=true)\n        ra = rank(A[1:s, :], atol=tol)\n        push!(ranks, ra)\n        A = A*F.V\n        B = B*F.V\n        A = A[s+1:end, ra+1:end]\n        B = B[s+1:end, ra+1:end]\n        r = rank(B, atol=tol)\n        s = size(B, 1) - r\n        push!(blocks, s)\n    end\n\n    e = blocks[1:end-1] - ranks\n    d = ranks - blocks[2:end]\n\n    removeTailZeroes!(e)\n    removeTailZeroes!(d)\n    iszero(d) && (d = Int[])\n    iszero(e) && (e = Int[])\n    return e, d, A, B\nend\n\nfunction eigNullities(λ::Number, A::AbstractArray{T, N}, B::AbstractArray{T, N}, tol=0) where {T<:Number, N}\n    A = A - λ*B\n    r = rank(A, atol=tol)\n    s = size(A, 2) - r\n\n    blocks  = [s]\n\n    while s != 0\n        F = svd(A, full=true);\n        B = B*F.V\n        A = A*F.V\n\n        F = svd(B[:, r+1:end], full=true)\n        Ua = F.U\n\n        P = Matrix(I, size(Ua))\n        P = P[[s+1:end; 1:s], :]\n        A = P*Ua'*A\n        B = P*Ua'*B\n\n        A = A[1:r, 1:r]\n        B = B[1:r, 1:r]\n        r = rank(A, atol=tol)\n        s = size(A, 2) - r\n        push!(blocks, s)\n    end\n    e = blocks[1:end-1] - blocks[2:end]\n\n    return e\nend\n\nfunction eigNullities(λ::Number, P::AbstractArray, tol=0)\n    _, _, Ar, Br = colNullities(P, tol)\n    _, _, Ar, Br = rowNullities(Ar, Br, tol)\n    return eigNullities(λ, Ar, Br, tol)\nend\n", "meta": {"hexsha": "093fde785fa5ac18f73a57a6d4ebde3451730a17", "size": 3222, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/eigenvalues/nullities.jl", "max_stars_repo_name": "lucaferranti/MatrixPolynomials.jl", "max_stars_repo_head_hexsha": "909ce44f5dc339157ac563769f7ebf089084646f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/eigenvalues/nullities.jl", "max_issues_repo_name": "lucaferranti/MatrixPolynomials.jl", "max_issues_repo_head_hexsha": "909ce44f5dc339157ac563769f7ebf089084646f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eigenvalues/nullities.jl", "max_forks_repo_name": "lucaferranti/MatrixPolynomials.jl", "max_forks_repo_head_hexsha": "909ce44f5dc339157ac563769f7ebf089084646f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-31T23:31:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T23:31:12.000Z", "avg_line_length": 24.2255639098, "max_line_length": 108, "alphanum_fraction": 0.5071384233, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.8418256492357359, "lm_q1q2_score": 0.7968693539191446}}
{"text": "## B-splines, recursive definition\nB0(u::Vector{Float64}, i::Integer) = x::Real -> (u[i] <= x < u[i+1]) ? float(1) : float(0) ## non-continuous\nB(p::Integer,u::Vector{Float64},i::Integer) = (p==0) ? B0(u,i) : x -> float(((x-u[i])/(u[i+p]-u[i]))*B(p-1,u,i)(x) + ((u[i+p+1]-x)/(u[i+p+1]-u[i+1]))*B(p-1,u,i+1)(x))\n\ntotalNumNodes(numNodes::Integer, p::Integer) = numNodes + 2p ## adding p nodes on each side\nnumOfBasisElements(numNodes::Integer,p::Integer) = numNodes + p - 1 ## number of non-zero spline functions\n\n## returns an index-function of basis-functions, which takes as input i in 1:k\n## creates evenly-spaced nodes\nfunction splineBasisFuns(p::Integer, range::(Real,Real), numNodes::Integer)\n    intervalLen = (range[2]-range[1])/(numNodes-1)\n    u = linspace(range[1] - p*intervalLen, range[2]+ p*intervalLen, totalNumNodes(numNodes,p))\n    i -> B(p,u,i)\nend\n\n## B-splines with pre-specific nodes\n## WARNING: all functions in this basis will be 0 at the leftmost and rightmost nodes, and the same is true of their first p-1 derivatives.\nfunction splineBasisFuns(p::Integer, nodes::Vector{Float64})\n    i::Integer -> B(p,nodes,i)\nend\n\n\ncubicSplineBasisFuns(range::(Real,Real), numNodes::Integer) = splineBasisFuns(3, range, numNodes)\nquadraticSplineBasisFuns(range::(Real,Real), numNodes::Integer) = splineBasisFuns(2, range, numNodes)\nlinearSplineBasisFuns(range::(Real,Real), numNodes::Integer) = splineBasisFuns(1, range, numNodes)\n\n\n## BFE \"Basis Function Expansion\"\n\n## evenly-spaced nodes\nfunction splineBFE(p::Integer, x::Vector{Float64}, range::(Real,Real), numNodes::Integer)\n    funs = splineBasisFuns(p, range, numNodes)\n    num = numOfBasisElements(numNodes,p)\n    Float64[funs(i)(xj) for xj in x, i in 1:num]\nend\n\n## pre-specified nodes\nfunction splineBFE(p::Integer, x::Vector{Float64}, nodes::Vector{Float64})\n    funs = splineBasisFuns(p, nodes)\n    n = length(nodes) - p - 1\n    Float64[funs(i)(xj) for xj in x, i in 1:n]\nend\n\n\ncubicSplineBFE(x::Vector{Float64}, range::(Real,Real), numNodes::Integer) =\n    splineBFE(3, x, range, numNodes)\nquadraticSplineBFE(x::Vector{Float64}, range::(Real,Real), numNodes::Integer) =\n    splineBFE(2, x, range, numNodes)\nlinearSplineBFE(x::Vector{Float64}, range::(Real,Real), numNodes::Integer) =\n    splineBFE(1, x, range, numNodes)\n\ncubicSplineBFE(x::Vector{Float64}, nodes::Vector{Float64}) = splineBFE(3, x, nodes)\nquadraticSplineBFE(x::Vector{Float64}, nodes::Vector{Float64}) = splineBFE(2, x, nodes)\nlinearSplineBFE(x::Vector{Float64}, nodes::Vector{Float64}) = splineBFE(1, x, nodes)\n", "meta": {"hexsha": "1479a88b2e1b0716b83e0eef1583d707bd7ecc98", "size": 2553, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/code.jl", "max_stars_repo_name": "JuliaPackageMirrors/BSplines.jl", "max_stars_repo_head_hexsha": "4fdaec1667c0b5ac05ee251519f6887a117168f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/code.jl", "max_issues_repo_name": "JuliaPackageMirrors/BSplines.jl", "max_issues_repo_head_hexsha": "4fdaec1667c0b5ac05ee251519f6887a117168f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/code.jl", "max_forks_repo_name": "JuliaPackageMirrors/BSplines.jl", "max_forks_repo_head_hexsha": "4fdaec1667c0b5ac05ee251519f6887a117168f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.4181818182, "max_line_length": 166, "alphanum_fraction": 0.6991774383, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.946596665680527, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.796869345138067}}
{"text": "using TensorToolbox\nusing LinearAlgebra\nusing Arpack\n#using TensorDecompositions\n\n\"\"\"\nhyper parameters max_iter and tol are decieded by sklearn\n\"\"\"\nfunction lranmf_mu(X, r ; max_iter=200, tol = 1.0E-3, verbose = false)\n    # lranmf_mu is effective when r << min(n,m)\n    # input is a onnegative matrix\n    # proposed by Guoxu Zhou in 2012\n    # https://ieeexplore.ieee.org/document/6166354\n\n    n, m = size(X)\n    epsilon = 0.000001\n\n    # See step1 in section II-B in the paper\n    if r == min(n, m)\n        svd_X = svd(X)\n    else\n        svd_X = svds(X; nsv=r, ritzvec=true)[1]\n    end\n    Achil = svd_X.U * diagm(svd_X.S)\n    Bchil = svd_X.V\n\n    # See step2 in section II-B in the paper\n    A = rand(n, r)\n    B = rand(m, r)\n    cost_at_init = norm(X - A*B')\n    previous_cost = cost_at_init\n    for iter = 1:max_iter\n        B .= B .* ( max.( Bchil*(Achil' * A), epsilon ) ) ./ ( B*(A'*A) )\n        A .= A .* ( max.( Achil*(Bchil' * B), epsilon ) ) ./ ( A*(B'*B) )\n\n        if tol > 0 && iter % 10 == 0\n            cost = norm(X - A*B')\n            if verbose\n                println(\"iter: $iter cost: $cost\")\n            end\n            if (previous_cost - cost) / cost_at_init < tol\n                break\n            end\n            previous_cost = cost\n        end\n    end\n\n    # A * B' is rank-r matrix\n    return A, B'\nend\n\nfunction lraSNTD(Y, reqrank)\n    # Sequential nonnegative Tucker based on lraNMF\n    # input is a nonnegative tensor\n    # proposed by Guoxu Zhou in 2012\n    # https://ieeexplore.ieee.org/document/6166354\n\n    N = ndims(Y)\n    input_tensor_shape = size(Y)\n\n    # See section IV-2) in the paper\n    # get non-negative factors\n    A = []\n    for n=1:N\n        # Yn is Matricization of tensor Y by mode n\n        Yn = tenmat(Y, n)\n        An, _ = lranmf_mu(Yn, reqrank[n])\n        push!(A, An)\n        # ttm(Y,An,n) is mode-n product of tensor X and matrix An\n        Y = ttm(Y, pinv(An), n)\n    end\n\n    # reproduce\n    Y = ttm(Y, A[1], 1)\n    for n=2:N\n        Y = ttm(Y, A[n], n)\n    end\n\n    return Y\nend\n", "meta": {"hexsha": "117dd9e1514d28c3b24e27f8dab60b3733405352", "size": 2042, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/methods/lraSNTD.jl", "max_stars_repo_name": "gkazunii/Legendre-tucker-rank-reduction", "max_stars_repo_head_hexsha": "303d5b3cb5e559841ad0df20adb40966e18b1248", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-09-30T06:58:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T16:08:44.000Z", "max_issues_repo_path": "src/methods/lraSNTD.jl", "max_issues_repo_name": "gkazunii/Legendre-tucker-rank-reduction", "max_issues_repo_head_hexsha": "303d5b3cb5e559841ad0df20adb40966e18b1248", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/methods/lraSNTD.jl", "max_forks_repo_name": "gkazunii/Legendre-tucker-rank-reduction", "max_forks_repo_head_hexsha": "303d5b3cb5e559841ad0df20adb40966e18b1248", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2098765432, "max_line_length": 73, "alphanum_fraction": 0.5528893242, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172688214137, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7968380650430795}}
{"text": "struct PolyharmonicSpline\n    dim::Int64\n    order::Int64\n    coeff::Vector{Float64}\n    centers::Array{Float64,2}\n    error::Float64\nend\n\nfunction polyharmonicK(r,K)\n    if iseven(K)\n        iszero(r) && return zero(r)\n        if r >= 1.0\n            return (r^K)*log(r)\n        elseif 0.0 < r < 1.0\n            return (r.^(K-1))*log(r.^r)\n        elseif iszero(r) # Needed for autodiff to work at zero\n            return zero(r)\n        end\n    else\n        return r^K\n    end\nend\n\nfunction PolyharmonicSpline(K::Int64, centers::Array{Float64,2}, values::Array{Float64}; s = 0.0)\n    m,n = size(centers)\n    m != length(values) && throw(DimensionMismatch())\n\n    M = zeros(m,m)\n    N = zeros(m,n+1)\n\n    for i=1:m\n        N[i,1] = 1\n        N[i,2:end] = centers[i,:]\n        for j=1:m\n            M[i,j] = polyharmonicK(norm(centers[i,:] .- centers[j,:]),K)\n        end\n    end\n    M = M + s*I\n    L = vcat(hcat(M,N),hcat(N', zeros(n+1,n+1)))\n\n    w = pinv(L)*vcat(values,zeros(n+1))\n\n    ivalues = zeros(m)\n    for i=1:m\n        tmp = 0.0\n        for j=1:m\n            tmp = tmp + w[j]*polyharmonicK(norm(centers[i,:] .- centers[j,:]),K)\n        end\n        tmp = tmp + w[m+1]\n        for j=2:n+1\n            tmp = tmp + w[m+j]*centers[i,j-1]\n        end\n        ivalues[i] = tmp\n    end\n    error = norm(values .- ivalues)\n\n    return PolyharmonicSpline(n,K,w,centers,error)\nend\n\nfunction PolyharmonicSpline(K::Int64, centers::Vector{Float64},values::Vector{Float64};s = 0.0)\n    PolyharmonicSpline(K,reshape(centers,length(centers),1),values,s=s)\nend\n\nfunction (S::PolyharmonicSpline)(x::T...) where T <: Real\n    n = length(x)\n    n != S.dim && throw(DimensionMismatch(\"$n != $(S.dim)\"))\n\n    v = 0.0\n    l = length(S.coeff)-(n+1)\n    for j=1:l\n        v = v + S.coeff[j]*polyharmonicK(norm(x .- S.centers[j,:]), S.order)\n    end\n\n    v = v + S.coeff[l+1]\n    for j=2:n+1\n        v = v + S.coeff[l+j]*x[j-1]\n    end\n\n    return v\nend\n", "meta": {"hexsha": "1fc27e0860ad1b29f48c54cac4f90574b3e916b6", "size": 1940, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polyharmonic.jl", "max_stars_repo_name": "JuliaTagBot/OrbitTomography.jl", "max_stars_repo_head_hexsha": "c198ad0ca1ecd9816a41b9fbe20c74af6816bda8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-18T22:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T22:38:56.000Z", "max_issues_repo_path": "src/polyharmonic.jl", "max_issues_repo_name": "JuliaTagBot/OrbitTomography.jl", "max_issues_repo_head_hexsha": "c198ad0ca1ecd9816a41b9fbe20c74af6816bda8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-07-06T15:24:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:35:45.000Z", "max_forks_repo_path": "src/polyharmonic.jl", "max_forks_repo_name": "JuliaTagBot/OrbitTomography.jl", "max_forks_repo_head_hexsha": "c198ad0ca1ecd9816a41b9fbe20c74af6816bda8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:54:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T19:04:35.000Z", "avg_line_length": 23.950617284, "max_line_length": 97, "alphanum_fraction": 0.5350515464, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7967862260861125}}
{"text": "# [Martinsson & Tropp, Algorithm 7]\nfunction rangefinder(A::AbstractMatrix{T}, r::Int; q::Int=0) where {T <: Number}\n    m, n = size(A)\n    if q == 0\n        Ω = 1/sqrt(n) * randn(n, r)\n        Y = A * Ω\n    else\n        Y = 1/sqrt(m) * randn(m, r)\n        for i in 1:q\n            Y = Array(qr(Y).Q)\n            Y = A*A'*Y\n        end\n    end\n\n    return Array(qr(Y).Q)\nend\n", "meta": {"hexsha": "fa6b5ab6748e4604b8decb5b8c6ff149149b7315", "size": 375, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rangefinder.jl", "max_stars_repo_name": "tjdiamandis/RandomizedPreconditioners.jl", "max_stars_repo_head_hexsha": "06de6c9797aab550e9b6dfd73e7bb80ca698f7c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2021-12-18T02:07:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T02:16:55.000Z", "max_issues_repo_path": "src/rangefinder.jl", "max_issues_repo_name": "tjdiamandis/RandomizedPreconditioners.jl", "max_issues_repo_head_hexsha": "06de6c9797aab550e9b6dfd73e7bb80ca698f7c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-03-23T03:07:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T18:24:11.000Z", "max_forks_repo_path": "src/rangefinder.jl", "max_forks_repo_name": "tjdiamandis/RandomizedPreconditioners.jl", "max_forks_repo_head_hexsha": "06de6c9797aab550e9b6dfd73e7bb80ca698f7c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0588235294, "max_line_length": 80, "alphanum_fraction": 0.4613333333, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7967862250185276}}
{"text": "# sin (θ) cos (θ)\n\n\n#Makie\nusing CairoMakie\nlet\n    x = -2π:0.1:2π\n    fig = Figure(resolution = (600, 400), backgroundcolor = :honeydew,\n          font = \"CMU Serif\")\n    ax = Axis(fig[1, 1], xlabel = L\"f(x)\", ylabel = L\"x\",\n            xlabelsize = 22, ylabelsize = 22)\n    lines!(x, cos.(x); linewidth = 3, linestyle = \".-\", label = L\"cos θ\",\n      color = :paleturquoise4)\n    lines!(x, sin.(x); linewidth = 3, linestyle = :dot, label = L\"sin θ\",\n      color = :springgreen)\n    axislegend(; merge = true, framecolor = :mediumpurple, position = :lt)\n    display(fig)\nend;\n\n\n#Jl Plots\np = Plots.plot([sin], zeros(0), xlims = (0, 2π), ylims = (-1, 1), c=[:black, :magenta], marker=:circle, linewidth= 2, label = \"sin θ\")\np = Plots.plot!([cos], zeros(0), xlims = (0, 2π), ylims = (-1, 1), c=[:cyan, :black], marker=:hexagon, linewidth= 2,  label = \"cos θ\")\nfor x = range(0, stop = 2π, length = 20)\n    push!(p, x, Float64[sin(x), cos(x)])\nend\n\n", "meta": {"hexsha": "289c4b54a755a62c9dfc55770737ab1e5b62b72d", "size": 945, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lines/cos_sin_curves.jl", "max_stars_repo_name": "Ellon-M/visualizations", "max_stars_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lines/cos_sin_curves.jl", "max_issues_repo_name": "Ellon-M/visualizations", "max_issues_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lines/cos_sin_curves.jl", "max_forks_repo_name": "Ellon-M/visualizations", "max_forks_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.75, "max_line_length": 134, "alphanum_fraction": 0.5703703704, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7967862170769099}}
{"text": "####\n# Some Closed-Form Formulae and Helpers\n####\n#returns max coeff_dev for dist S, M\ncomp_Sc(S, M) = (S + M - 1)/M\nmax_dev(S, M) = M * (S - 1) / (S + M - 1)\nfunction max_cv(S, M)\n\tSc = comp_Sc(S, M)\n\tM * sqrt((Sc - 1))\nend\n\n#Returns the minimum B\nfunction min_gm(S, M, mu) \n\tSc = comp_Sc(S, M)\n\tout = (Sc - 1)/Sc * log(1 - M) + 1/Sc * log(M * (S - 1) + 1)\n\tmu * exp(out)\nend\n\n#helper function for a robust (indefinite) quadratic  \n#ax^2 + bx +c >= 0 for all x in [l, u]\n#adds everything to model m\nfunction _addRQ!(m, a, b, c, l, u)\n    y1 = @variable(m)  #theta\n    @constraint(m, y1 >= 0)\n    y = @variable(m)    #t\n    @constraint(m, y >= 0)\n    t2 = @variable(m)\n    @constraint(m, 4 * y1 * y >= t2^2)\n    @constraint(m, t2 == b - (l + u) * (y1 - a))\n    @constraint(m, y1 - a >= 0)\n    @constraint(m, c + l * u * (y1 - a) - y >= 0)\nend\n\n#conjecture that maximal CV occurs for uniform distribution among unimodals\n#Not formally proven\nfunction max_std_cv_unimodal_guess(mu, S, M, isSym)\n    #convert to standardized distribution\n    c = mu * (1 - M)\n    Sc = vopp.comp_Sc(S, M)\n\n    #adjust for symmetry if needed\n    if isSym \n        if Sc > 2 \n            Sc = 2\n        end\n        if Sc < 2 \n            lb = 2 - Sc\n        else\n            lb = 0\n        end\n    end\n\n    return 2 / sqrt(12) * (Sc - lb) / (Sc + lb)\nend\n\n\n#for the standardized distribution\n#document indexes 0 to N\nfunction geom_price_ladder(S, delta)\n    N = ceil(Int, 1 + log(S/delta) / log(1 + delta))\n    ps = zeros(N + 1)\n    ps[0 + 1] = 0.\n    ps[1 + 1] = delta\n    ps[N + 1] = S\n    for i = 2:N-1\n        ps[i + 1] = ps[i - 1 + 1] * (1 + delta)\n    end\n    ps\nend\n\n\nvopp_ub_scale(S, M) = -lambertw(-M / exp(1) / (S + M - 1))\n\n#assumes standardized\nfunction tight_dist_ub_scale(x, S)\n    alpha = 1/vopp_ub_scale(S, 1)\n    if 0 <= x <= alpha\n        return 1.\n    elseif x <= S\n        return alpha / x\n    else\n        return 0.\n    end\n    return -1.\nend\n\n\n\n#Approximately computes the minimum and maximal valid q for distn\n#assumes it is standardized\nfunction min_max_q_IC_uni(S, mode, v0, supp_size=100)\n    \n    function G(p, m, t)\n        if p > max(m, t)\n            return 0.\n        elseif p < min(m, t)\n            return 1.\n        elseif m == t\n            return m >= p ? 1. : 0.\n        end\n        return (max(m, t) - p) / abs(m-t)       \n    end\n   \n    m = Model(solver=GurobiSolver(OutputFlag=false))\n    \n    t_grid = range(0, stop=S, length=supp_size)\n    \n    @variable(m, ws[1:supp_size] >= 0)\n    @constraint(m, sum(ws) == 1)\n    @constraint(m, sum(ws[i] * (mode + t_grid[i])/2 for i = 1:supp_size) == 1)\n    @objective(m, Min, sum(ws[i] * G(v0, mode, t_grid[i]) for i = 1:supp_size))\n\n    status = solve(m) \n    @assert status == :Optimal\n    minq = getobjectivevalue(m)\n\n    @objective(m, Max, sum(ws[i] * G(v0, mode, t_grid[i]) for i = 1:supp_size))\n\n    status = solve(m) \n    @assert status == :Optimal\n    maxq = getobjectivevalue(m)\n    return minq, maxq        \nend\n\n\nfunction min_max_q_IC_uni(S, M, mu, mode, phat, supp_size=100)\n    c = mu * (1 - M)\n    Sc = vopp.comp_Sc(S, M)\n    mode_c = (mode - c) / (mu - c)\n    v0 = (phat - 1)/ M + 1\n    return min_max_q_IC_uni(Sc, mode_c, v0, supp_size)\n\nend        \n", "meta": {"hexsha": "7e295accce454572c126fab56f3a9b688ef62673", "size": 3225, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Helpers.jl", "max_stars_repo_name": "vgupta1/VoPP_OptProblems", "max_stars_repo_head_hexsha": "ca49ad08674ea08f9aa914b72d2e29bd4084b470", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-24T15:15:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T12:37:17.000Z", "max_issues_repo_path": "Helpers.jl", "max_issues_repo_name": "stormrage7/VoPP_OptProblems", "max_issues_repo_head_hexsha": "ca49ad08674ea08f9aa914b72d2e29bd4084b470", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Helpers.jl", "max_forks_repo_name": "stormrage7/VoPP_OptProblems", "max_forks_repo_head_hexsha": "ca49ad08674ea08f9aa914b72d2e29bd4084b470", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-24T15:04:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T07:11:32.000Z", "avg_line_length": 24.0671641791, "max_line_length": 79, "alphanum_fraction": 0.5441860465, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142225532629, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7966957237862862}}
{"text": "\"Log PDF of Generalized student-t Distribution.\"\nfunction tlogpdf(x, df, mean, sigma)\n\n   function tdist_consts(df, sigma)\n       hdf = 0.5 * df\n       shdfhdim = hdf + 0.5\n       v = lgamma(hdf + 1/2) - lgamma(hdf) - 0.5*log(df) - 0.5*log(pi) - log(sigma)\n       return (shdfhdim, v)\n   end\n\n    shdfhdim, v = tdist_consts(df, sigma)\n\n    xx = x .- mean\n    xx = (xx ./ sqrt(sigma)).^2\n\n    p = 1/df * xx\n\n    return v - log((1 + p).^((df+1) / 2))\nend\n", "meta": {"hexsha": "3ed8a14873ee0503652dd41a37658260c76a0949", "size": 453, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math.jl", "max_stars_repo_name": "UnofficialJuliaMirror/BayesianNonparametrics.jl-7e49bc5d-d907-5fdd-93a4-11f1b4f8bb51", "max_stars_repo_head_hexsha": "12d790361ffefeeadc97810e1ebb06f6a237fde1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2016-12-10T01:58:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T04:10:57.000Z", "max_issues_repo_path": "src/math.jl", "max_issues_repo_name": "UnofficialJuliaMirror/BayesianNonparametrics.jl-7e49bc5d-d907-5fdd-93a4-11f1b4f8bb51", "max_issues_repo_head_hexsha": "12d790361ffefeeadc97810e1ebb06f6a237fde1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-01-05T23:29:50.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-13T10:36:48.000Z", "max_forks_repo_path": "src/math.jl", "max_forks_repo_name": "UnofficialJuliaMirror/BayesianNonparametrics.jl-7e49bc5d-d907-5fdd-93a4-11f1b4f8bb51", "max_forks_repo_head_hexsha": "12d790361ffefeeadc97810e1ebb06f6a237fde1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2017-04-05T13:29:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T01:06:47.000Z", "avg_line_length": 22.65, "max_line_length": 83, "alphanum_fraction": 0.5474613687, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7966957083474134}}
{"text": "#--------------------------------------------------------------------\n# Spacetime Discretization methods in Julia\n# Soham 05-2019\n# Chebyshev Polynomials: Gauss Lobatto grid \n# See Boyd F.8\n#--------------------------------------------------------------------\n\nexport collocation, derivative, integral \n\nfunction naturalcollocation(S::ChebyshevGL{Tag, N, T}, i::Int)::T where {Tag, N, T}\n    @assert i <= N\n    return  cospi(T(i-1)/T(N-1))\nend\n\n\nfunction naturalderivative(S::ChebyshevGL{Tag, N, T}, i::Int, j::Int)::T where {Tag, N, T}\n    @assert i <= N && j <= N\n\tif i==j==1\n        return  (2T(N-1)^2 + 1)/T(6)\n\telseif i==j==N\n        return -(2T(N-1)^2 + 1)/T(6)\n\telseif i==j\n        return - naturalcollocation(S,j)/(2(1-naturalcollocation(S,j)^2))\n\telse\n\t\tci = (i == 1 || i == N) ?  2 : 1\n\t\tcj = (j == 1 || j == N) ?  2 : 1\n\t\ts  = (i + j) % 2 != 0   ? -1 : 1\n        return (T(ci)/T(cj))*(T(s)/(naturalcollocation(S, i) - naturalcollocation(S,j)))\n\tend\nend\n\nfunction naturalintegral(S::ChebyshevGL{Tag, N, T}, i::Int)::T where {Tag, N, T}\n    @assert i <= N\n    W = T(0)\n\tfor j in 1:N\n        w = (j == 1 ? 1 : (j-1)%2 == 0 ? T(2)/T((1-(j-1)^2)) : 0)\n        l = (i == 1 || i == N ? (T(1)/T(N-1))*cospi(T(i-1)*T(j-1)/T(N-1)) : (T(2)/T(N-1))*cospi(T(i-1)*T(j-1)/T(N-1)))\n        W = W + w*l\n\tend\n\treturn W\nend\n\nfunction collocation(space::S, i::Int)::T where {S <: Cardinal{Tag, N, T}} where {Tag, N, T}\n    return naturalcollocation(space,i)*T(space.max - space.min)/2 + T(space.max + space.min)/2 \nend\n\nfunction derivative(space::S, i::Int, j::Int)::T where {S <: Cardinal{Tag, N, T}} where {Tag, N, T}\n    return naturalderivative(space,i,j)*(2/T(space.max - space.min))\nend\n\nfunction integral(space::S, i::Int)::T where {S <: Cardinal{Tag, N, T}} where {Tag, N, T}\n    return naturalintegral(space,i)*T(space.max - space.min)/T(2)\nend\n", "meta": {"hexsha": "5393b2782d02a5214c66a9cbcbef8dbc049b642a", "size": 1845, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Spectral/ChebyshevGL.jl", "max_stars_repo_name": "mukherjeesoham/DNSS.jl", "max_stars_repo_head_hexsha": "22859ab776c3880738b757ccf43d827da2d999c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Spectral/ChebyshevGL.jl", "max_issues_repo_name": "mukherjeesoham/DNSS.jl", "max_issues_repo_head_hexsha": "22859ab776c3880738b757ccf43d827da2d999c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Spectral/ChebyshevGL.jl", "max_forks_repo_name": "mukherjeesoham/DNSS.jl", "max_forks_repo_head_hexsha": "22859ab776c3880738b757ccf43d827da2d999c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1666666667, "max_line_length": 118, "alphanum_fraction": 0.5241192412, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422158380861, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7966957079550411}}
{"text": "\"\"\"\n    regression(data::Dataset, labels::Labels; kwargs...)\n\nperform learning of logistic regression classifier on given `data` and correct `labels`\n\noutputs vector `w` which detrmines a hyperplane optimally separating the data samples\n\n- `kwargs` can contain `epsilon` to specify accuracy of optimization method and initial `step` size\n\"\"\"\nfunction regression(data::Dataset, labels::Labels; kwargs...)\n    trainX = data()\n    trainy = labels()\n\n    w = gd(trainX, trainy; kwargs...)\n\n    return w\nend\n\n\"\"\"\n    classify(data::Dataset, w::Vector{<:Real})\n\nclassify the `data` using separating hyperplane determined by `w`\n\"\"\"\nfunction classify(data::Dataset, w::Vector{<:Real})\n    X = data()\n    _, n = size(X)\n    return Labels(data, [dot(X[:, i], w) >= 0 ? 1 : -1 for i in 1:n])\nend\n\n\"\"\"\n    computeE(X::Matrix{<:Real}, k::Vector{<:Integer}, w::Vector{<:Real})\n\nreturns energy of hyperplane `w` with respect to data `X` and labels `k`; this objective is to be minimized\n\"\"\"\nfunction computeE(X::Matrix{<:Real}, k::Vector{<:Integer}, w::Vector{<:Real})\n    N = length(k)\n    return sum([log(1 + exp(-k[i] * dot(X[:, i], w))) for i in 1:N]) ./ N\nend\n\n\"\"\"\n    gradE(X::Matrix{<:Real}, k::Vector{<:Integer}, w::Vector{<:Real})\n\nreturns gradient of energy with respect to vector w\n\"\"\"\nfunction gradE(X::Matrix{<:Real}, k::Vector{<:Integer}, w::Vector{<:Real})\n    N = length(k)\n    return - sum([(k[i] * X[:, i]) / (1 + exp(k[i] * dot(X[:, i], w))) for i in 1:N]; dims=1)[1] ./ N\nend\n\n\"\"\"\n    l2norm(x)\n\ncomputes l2-norm of given vector `x`\n\"\"\"\nfunction l2norm(x)\n    return sqrt.(dot(x, x))\nend\n\n\"\"\"\n    gd(X::Matrix{<:Real}, k::Vector{<:Integer}; epsilon=1e-4, step=1.0)\n\nperforms gradient descent method to find optimal separating hyperplane `w` on data `X` and labels `k`\n\nkeyword arguments can be used to alter the optimization:\n- `epsilon` to specify accuracy/terminal condition\n- `step` to adjust initial step size\n\"\"\"\nfunction gd(X::Matrix{<:Real}, k::Vector{<:Integer}; epsilon=1e-4, step=1.0)\n    dim, _ = size(X)\n\n    w = zeros(Float64, dim)\n    lastw = fill(Inf64, dim)\n    E = Inf64\n\n    while l2norm(w - lastw) > epsilon\n        grad = gradE(X, k, w)\n        neww = w - step * grad\n        newE = computeE(X, k, neww)\n\n        if newE < E\n            step *= 2\n            E = newE\n            lastw = w\n            w = neww\n        else\n            step /= 2\n        end\n\n    end\n\n    return w\nend\n", "meta": {"hexsha": "a3d677d53b9164803ef7598d469b718567e9abf2", "size": 2411, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/logistic.jl", "max_stars_repo_name": "JakubRada/jul_titanic", "max_stars_repo_head_hexsha": "37628b53086eeda53a4c12254cc1db1e37fec3bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/logistic.jl", "max_issues_repo_name": "JakubRada/jul_titanic", "max_issues_repo_head_hexsha": "37628b53086eeda53a4c12254cc1db1e37fec3bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/logistic.jl", "max_forks_repo_name": "JakubRada/jul_titanic", "max_forks_repo_head_hexsha": "37628b53086eeda53a4c12254cc1db1e37fec3bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9247311828, "max_line_length": 107, "alphanum_fraction": 0.6059726255, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928904, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7966957037242853}}
{"text": "\n\"\"\"\n    GammaExponential(lnℓ::AbstractFloat, lnγ::AbstractFloat) \n    <: RadialKernel{Euclidean}\n\nThe gamma exponential kernel with length scale \n``\\\\exp(\\\\gamma\\\\ln\\\\ell) = \\\\ell^\\\\gamma > 0``.\n\n```math\nk_{\\\\gamma,\\\\ell}(x, y) = \nk_{\\\\gamma,\\\\ell}(\\\\lVert x - y\\\\rVert_2) = \n\\\\exp\\\\bigg\\\\lbrace -\n\\\\frac{\\\\lVert x - y\\\\rVert_2^\\\\gamma}{\\\\ell^\\\\gamma}\\\\bigg\\\\rbrace\n```\n\"\"\"\nmutable struct GammaExponential{F<:AbstractFloat} <: RadialKernel{Euclidean}\n    dist::Euclidean\n    lnℓ::F\n    lnγ::F\n    \n    ℓᵞ::F\n    γ::F\n    function GammaExponential(\n        dist::Euclidean,\n        lnℓ::AbstractFloat,\n        lnγ::AbstractFloat\n    )\n        lnℓ, lnγ = promote(lnℓ, lnγ)\n        γ = exp(lnγ)\n        new{typeof(lnℓ)}(dist, lnℓ, lnγ, exp(γ * lnℓ), γ)\n    end\nend\n\nGammaExponential(lnℓ::AbstractFloat, lnγ::AbstractFloat) =\n    GammaExponential(Euclidean(), lnℓ, lnγ)\n\n@inline (k::GammaExponential)(τ::AbstractFloat) = exp(-τ^k.γ / k.ℓᵞ)\n\nnumparams(::GammaExponential) = (1, 1)\nparamtypes(::GammaExponential{F}) where F = (F, F)\nparams(k::GammaExponential) = (lnℓ = k.lnℓ, lnγ = k.lnγ)\nfunction setparams!(k::GammaExponential{F}, lnℓ::F, lnγ::F) where F\n    lnℓ, lnγ = promote(lnℓ, lnγ)\n    γ = exp(lnγ)\n    k.lnℓ = lnℓ\n    k.lnγ = lnγ\n    k.ℓᵞ = exp(γ * lnℓ)\n    k.γ = γ\nend\n", "meta": {"hexsha": "7c50b40f7c2bd8f07e488e9bcbc885328b240c2f", "size": 1275, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/radial/GammaExponential.jl", "max_stars_repo_name": "cameton/SKI.jl", "max_stars_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/radial/GammaExponential.jl", "max_issues_repo_name": "cameton/SKI.jl", "max_issues_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/radial/GammaExponential.jl", "max_forks_repo_name": "cameton/SKI.jl", "max_forks_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5, "max_line_length": 76, "alphanum_fraction": 0.6078431373, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.7966894175306319}}
{"text": "\"\"\"\n        greedy_star2_coloring\n\nFind a coloring of a given input graph such that\nno two vertices connected by an edge have the same\ncolor using greedy approach. The number of colors\nused may be equal or greater than the chromatic\nnumber `χ(G)` of the graph.\n\nA star coloring is a special type of distance - 1  coloring,\nFor a coloring to be called a star coloring, it must satisfy\ntwo conditions:\n\n1. every pair of adjacent vertices receives distinct  colors\n(a distance-1 coloring)\n\n2. For any vertex v, any color that leads to a two-colored path\ninvolving v and three other vertices  is  impermissible  for  v.\nIn other words, every path on four vertices uses at least three\ncolors.\n\nReference: Gebremedhin AH, Manne F, Pothen A. **What color is your Jacobian? Graph coloring for computing derivatives.** SIAM review. 2005;47(4):629-705.\n\nTODO: add text explaining the difference between star1 and star2\n\"\"\"\nfunction color_graph(g::Graphs.AbstractGraph, ::GreedyStar2Color)\n    v = nv(g)\n    colorvec = zeros(Int, v)\n\n    forbidden_colors = zeros(Int, v+1)\n\n    for vertex_i = vertices(g)\n        for w in inneighbors(g, vertex_i)\n            if colorvec[w] != 0\n                forbidden_colors[colorvec[w]] = vertex_i\n            end\n\n            for x in inneighbors(g, w)\n                if colorvec[x] != 0\n                    if colorvec[w] == 0\n                        forbidden_colors[colorvec[x]] = vertex_i\n                    else\n                        if colorvec[x] < colorvec[w]\n                            forbidden_colors[colorvec[x]] = vertex_i\n                        end\n                    end\n                end\n            end\n        end\n        colorvec[vertex_i] = find_min_color(forbidden_colors, vertex_i)\n    end\n    return colorvec\nend\n", "meta": {"hexsha": "cf1f24f80f80e2d4f37e24b791fd9047c8c6d889", "size": 1773, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/coloring/greedy_star2_coloring.jl", "max_stars_repo_name": "avik-pal/SparseDiffTools.jl", "max_stars_repo_head_hexsha": "1829086b7563cf1484043717c87ed3fd5458eda1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 42, "max_stars_repo_stars_event_min_datetime": "2019-05-28T20:03:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-23T20:37:02.000Z", "max_issues_repo_path": "src/coloring/greedy_star2_coloring.jl", "max_issues_repo_name": "avik-pal/SparseDiffTools.jl", "max_issues_repo_head_hexsha": "1829086b7563cf1484043717c87ed3fd5458eda1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2019-05-30T18:40:30.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-28T18:32:25.000Z", "max_forks_repo_path": "src/coloring/greedy_star2_coloring.jl", "max_forks_repo_name": "avik-pal/SparseDiffTools.jl", "max_forks_repo_head_hexsha": "1829086b7563cf1484043717c87ed3fd5458eda1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2019-06-01T14:38:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-26T15:41:49.000Z", "avg_line_length": 32.8333333333, "max_line_length": 153, "alphanum_fraction": 0.630569656, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8652240756264638, "lm_q1q2_score": 0.7966893961691606}}
{"text": "using DataStructures\n\n\"\"\"\n    stack_to_rational(st::Stack)\n\nTake a stack consisting of the convergents of the continued\nfraction expansion of a number and return the rational approximation.\n\nNote: This function makes a deep copy of the given stack.\n\nEx.\n    [3, 7, 15] ---> 333/106\n\njulia> st = Stack(Int)\nDataStructures.Stack{Int64}(Deque [Int64[]])\n\njulia> push!(st, 3)\nDataStructures.Stack{Int64}(Deque [[3]])\n\njulia> push!(st, 7)\nDataStructures.Stack{Int64}(Deque [[3,7]])\n\njulia> push!(st, 15)\nDataStructures.Stack{Int64}(Deque [[3,7,15]])\n\njulia> stack_to_rational(st)\n333//106\n\"\"\"\nfunction stack_to_rational(st)\n    tmp = deepcopy(st)\n    x = pop!(tmp)\n\n    while (length(tmp) > 0)\n        x = pop!(tmp) + 1 // x\n    end\n\n    return x\nend\n\n\n\"\"\"\n    diophantine(x [, ε = 10.0-5])\n\nReturn a rational approximation of x with an error tolerance of ε (default value of 10^-5).\n\nUsing notation from Bremner (pg 146).\n\njulia> diophantine(float(π))\n355//113\n\"\"\"\nfunction diophantine(x, ε = 10.0^-5)\n    st = Stack(Int)\n\n    # step i=2\n    γ = x\n    qi = floor(Int, γ)\n    push!(st, qi)\n\n    # step i=3,4,...\n    while (abs(stack_to_rational(st) - x) > ε)\n        γ = 1 / (γ - qi)\n        qi = floor(Int, γ)\n        push!(st, qi)\n    end\n\n    return stack_to_rational(st)\nend\n", "meta": {"hexsha": "e8888983afc21f96b907526d0b057ca59c32d40d", "size": 1274, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/diophantine.jl", "max_stars_repo_name": "pikachau/LatticeBasisReduction.jl", "max_stars_repo_head_hexsha": "a9eb13052d70f0826e116ac4e5e8c993e16ef575", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-22T23:53:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-22T23:53:41.000Z", "max_issues_repo_path": "src/diophantine.jl", "max_issues_repo_name": "pikachau/LatticeBasisReduction.jl", "max_issues_repo_head_hexsha": "a9eb13052d70f0826e116ac4e5e8c993e16ef575", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/diophantine.jl", "max_forks_repo_name": "pikachau/LatticeBasisReduction.jl", "max_forks_repo_head_hexsha": "a9eb13052d70f0826e116ac4e5e8c993e16ef575", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-26T15:32:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T15:32:58.000Z", "avg_line_length": 18.7352941176, "max_line_length": 91, "alphanum_fraction": 0.6287284144, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.865224072151174, "lm_q1q2_score": 0.7966893873270312}}
{"text": "\ninclude(\"randExp.jl\")\n\n# we write an improoved function that uses Monte Carlo with exponential importance sampling\n# to estimate the volume of the unit hypersphere in d dimensions.\n# We choose our points x with independent Cartesian components and prob density exp(-lam.xi) / [ lam*((1-exp(-lam)) ].\n# We achieve this by taking xi = (1/lam) log (1/y) where y is chosen uniformly in (exp(-lam),1)\nfunction sphereVolMCImpExp(d, n, lam)\n\tcount = 0.0\n\tfor i = 1:n\n\n\t\t# we generate x according to our distribution\n\t\tx = randExp(d, lam)\n\n\t\t# we calculate the squared norm of x and check if x is inside the hypersphere\n\t\tnorm2 = x' * x\n\t\tif norm2 < 1\n\n\t\t\t# we compute the density at x\n\t\t\trho = 1\n\t\t\tfor i = 1:d\n\n\t\t\t\t# note that y(i) = exp(-lam * x(i))\n\t\t\t\trho *= exp(-lam*x[i]) * lam / (1-exp(-lam))\n\t\t\tend\n\t\t\tcount += 1/rho\n\t\tend\n\tend\n\tvol =  2^d * count / n\n\treturn vol\nend", "meta": {"hexsha": "64e3597165d14be96d06e43f70d2f2aa4e071823", "size": 869, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1a/Monte Carlo integration/sphereVolMCImpExp.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "1a/Monte Carlo integration/sphereVolMCImpExp.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "1a/Monte Carlo integration/sphereVolMCImpExp.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 28.0322580645, "max_line_length": 118, "alphanum_fraction": 0.6593785961, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452772, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7966427718403788}}
{"text": "\"\"\"\n\tstationarydist(m::MarkovProcess)\n\nPhân phối dừng của quá trình Markov\n\"\"\"\nfunction stationarydist(m::MarkovProcess)\n\tG = m.G\n\tA = vcat(transpose(G)[1:end-1, :], ones(1, size(G, 1)))\n\tB = vcat(zeros(size(G, 1) - 1), 1)\n\tinv(A) * B\nend\n\n\"\"\"\n\timbeddedchain(m::MarkovProcess)\n\nXích Markov nhúng của một quá trình Markov\n\"\"\"\nfunction imbeddedchain(m::MarkovProcess)\n\tλ = -diag(m.G)\n\tp = m.G ./ λ - I\n\tp[diagind(p)] .= 0\n\tp[diagind(p)] = 1 .- sum(p; dims=2)\n\tMarkovChain(p) \nend\n\n\"\"\"\n\ttransition_matrix(m::MarkovProcess, t)\n\nTạo ma trận chuyển tại thời điểm t\n\"\"\"\nfunction transition_matrix(m::MarkovProcess, t)\n\tD, Q = eigen(m.G)\n\tQ * diagm(exp.(D * t)) * inv(Q)\nend\n\nfunction Base.show(io::IO, m::MarkovProcess)\n\tdisplay(\"Quá trình Markov với ma trận sinh\")\n\tdisplay(m.G)\nend\n", "meta": {"hexsha": "f8f15e093c6016fa30d5a0ca8e82ba269a6e1813", "size": 777, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/markovprocess.jl", "max_stars_repo_name": "ndgnuh/MarkovAndQueueModels.jl", "max_stars_repo_head_hexsha": "30d0c3ecb9da61a466b95b791e8dbefc854ed38f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/markovprocess.jl", "max_issues_repo_name": "ndgnuh/MarkovAndQueueModels.jl", "max_issues_repo_head_hexsha": "30d0c3ecb9da61a466b95b791e8dbefc854ed38f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/markovprocess.jl", "max_forks_repo_name": "ndgnuh/MarkovAndQueueModels.jl", "max_forks_repo_head_hexsha": "30d0c3ecb9da61a466b95b791e8dbefc854ed38f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.425, "max_line_length": 56, "alphanum_fraction": 0.6589446589, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.8499711775577735, "lm_q1q2_score": 0.7966021659512293}}
{"text": "module Mel\n\n\n\"\"\"\n    mel(frequency::Number)\n\nTransform the input to mel scale\n\"\"\"\nmel(frequency::Number)::Number = 1127*log(1 + frequency/700)\n\n\n\"\"\"\n    imel(mel::Number)\n\nTransform the input back from mel scale\n\"\"\"\nimel(mel::Number)::Number = 700*(exp(mel/1127) - 1)\n\n\n\"\"\"\n    melspace(start::Number, length::Int, stop::Number)::Array\n\nReturn an array of mel spaced points\n\"\"\"\nmelspace(start::Number, length::Int, stop::Number)::Array =\n\timel.(range(mel(start), length=length, mel(stop)))\n\n\n\"\"\"\n    mffilters(noffilters::Int, filterlength::Int, sr::Real) -> (windows, starts)\n\nProject a filterbank composed by triangular and even-spaced filters in the mel\nscale.\n\n\nThe first element of the tuple is an array containing arrays, each one filled\nwith the non-zero part of a filter from a filterbank. The second element is an\narray containing the start of the non-zero part of each filter. The return can\nbe used to create a [`Filterbank`](@ref) defined in the Filterbank module.\n\n\n**Parameters:**\n\n`noffilters`: The number of filters in the filterbank.\n\n`filterlenght`: The length of the filters, should match the lenght of the lenght\nof the signal to which the filterbank will be applied.\n\n`sr`: The sampling rate to be used, should match the original sampling rate of\nthe sequence.\n\n\nSee also: [`Filterbank`](@ref)\n\"\"\"\nfunction mffilters(noffilters::Int, filterlength::Int, sr::Real)\n\n\tmelpoints = ceil.(Int, melspace(1, noffilters + 2, sr)*filterlength/sr)\n\n\treturn (map(m->\tbegin\n\n\t\tstart, apex, stop = melpoints[m:m + 2]\n\t\tw = zeros(stop - start)\n\n\t\tfor k in 1:(apex - start)\n\t\t\tw[k] = k/(apex - start)\n\t\tend\n\n\t\tfor k in apex:(stop - 1)\n\t\t\tw[k - start + 1] = (stop - k)/(stop - apex)\n\t\tend\n\n\t\treturn 2w/(stop - start)\t#Normalized so that the triangle has area 1\n\n\tend, 1:noffilters),\n\tmelpoints[1:end - 2])\n\nend\n\nexport mel, imel, melspace, mffilters\nend  # module Mel\n", "meta": {"hexsha": "c35d802f81e16b3d5b03bc916de56ed3234bb683", "size": 1872, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Mel.jl", "max_stars_repo_name": "gabriel-ss/MFCC.jl", "max_stars_repo_head_hexsha": "a84f9b67dd7182cb8550c360f473732c1edb1140", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Mel.jl", "max_issues_repo_name": "gabriel-ss/MFCC.jl", "max_issues_repo_head_hexsha": "a84f9b67dd7182cb8550c360f473732c1edb1140", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Mel.jl", "max_forks_repo_name": "gabriel-ss/MFCC.jl", "max_forks_repo_head_hexsha": "a84f9b67dd7182cb8550c360f473732c1edb1140", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1111111111, "max_line_length": 80, "alphanum_fraction": 0.6976495726, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642554, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7966021644605763}}
{"text": "using Interpolations\nusing QuadGK\nusing Jacobi\nusing Plots\n\nfunction polynomial_decomposition(f, xs, ops; w=one, rtol=1e-8)\n    x1, x2 = minimum(xs), maximum(xs)\n    ys = f.(xs)\n    ℑf = interpolate((xs,), ys, Gridded(Linear()))\n\n    numerators = [quadgk(x -> ℑf(x) * op(x) * w(x), x1, x2, rtol=rtol)[1] for op in ops]\n    denominators = [quadgk(x -> op(x)^2 * w(x), x1, x2, rtol=rtol)[1] for op in ops]\n    cs = numerators ./ denominators\n\n    N = length(ops)\n    f′(x) = sum(cs[n] * ops[n](x) for n in 1:N)\n\n    return cs, f′\nend\n\n@info \"Decomposing into Fourier series...\"\n\nxs = range(-π, π, length=101)\nf(x) = x/π + 2exp(-3(x+2)^2) -  3exp(-6(x-1)^2)\n\ncs_even, ℑf_even = Dict(), Dict()\ncs_odd,  ℑf_odd  = Dict(), Dict()\nanim = @animate for N in 1:16\n    ops_cos = [x -> cos(n*x) for n in 0:N]\n    ops_sin = [x -> sin(n*x) for n in 1:N]\n    cs_even[N], ℑf_even[N] = polynomial_decomposition(f, xs, ops_cos)\n    cs_odd[N],  ℑf_odd[N]  = polynomial_decomposition(f, xs, ops_sin)\n    plot(xs, f.(xs), label=\"\", linewidth=2, xlim=(-π, π), title=\"Fourier series decomposition (N=$N)\")\n    plot!(xs, ℑf_even[N].(xs) .+ ℑf_odd[N].(xs), label=\"\", linewidth=2)\nend\nmp4(anim, \"fourier_decomposition.mp4\", fps=5)\ngif(anim, \"fourier_decomposition.gif\", fps=5)\n\n@info \"Decomposing into Legendre series...\"\n\nxs = range(-1, 1, length=101)\nf(x) = x + 2exp(-2π*(x+2/π)^2) -  3exp(-6π*(x-1/π)^2)\n\ncs, ℑf = Dict(), Dict()\nanim = @animate for N in 0:32\n    ops = [x -> legendre(x, n) for n in 0:N]\n    cs[N], ℑf[N] = polynomial_decomposition(f, xs, ops)\n    plot(xs, f.(xs), label=\"\", linewidth=2, xlim=(-1, 1), title=\"Legendre series decomposition (N=$N)\")\n    plot!(xs, ℑf[N].(xs), label=\"\", linewidth=2)\nend\nmp4(anim, \"legendre_decomposition.mp4\", fps=5)\nmp4(anim, \"legendre_decomposition.gif\", fps=5)\n\n@info \"Decomposing into Chebyshev series...\"\n\ncs, ℑf = Dict(), Dict()\nanim = @animate for N in 0:16\n    w(x) = 1 / √(1 - x^2)\n    ops = [x -> chebyshev(x, n) for n in 0:N]\n    cs[N], ℑf[N] = polynomial_decomposition(f, xs, ops, w=w, rtol=1e-5)\n    plot(xs, f.(xs), label=\"\", linewidth=2, xlim=(-1, 1), title=\"Chebyshev series decomposition (N=$N)\")\n    plot!(xs, ℑf[N].(xs), label=\"\", linewidth=2)\nend\nmp4(anim, \"chebyshev_decomposition.mp4\", fps=5)\nmp4(anim, \"chebyshev_decomposition.gif\", fps=5)\n", "meta": {"hexsha": "f43b7869c7c19cef5546896b226cab58af3e35b9", "size": 2287, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polynomial_decomposition.jl", "max_stars_repo_name": "CliMA/ClimateParameterizations.jl", "max_stars_repo_head_hexsha": "1263e2edefced4e03e925d6bfa60ba1f1940e8c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2020-12-23T06:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:05:51.000Z", "max_issues_repo_path": "src/polynomial_decomposition.jl", "max_issues_repo_name": "CliMA/OceanParameterizations.jl", "max_issues_repo_head_hexsha": "5942c66ba8724b9661db170acb239ca3a2abd5c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-12-05T02:43:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T14:27:03.000Z", "max_forks_repo_path": "src/polynomial_decomposition.jl", "max_forks_repo_name": "ali-ramadhan/ClimateParameterizations.jl", "max_forks_repo_head_hexsha": "1263e2edefced4e03e925d6bfa60ba1f1940e8c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-17T18:06:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T18:06:40.000Z", "avg_line_length": 34.6515151515, "max_line_length": 104, "alphanum_fraction": 0.6143419327, "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7966021537357709}}
{"text": "\n# Get the mean approximation error in random interior points.\nfunction abserror(f::Function, F::Expansion; vals = 200)\n    rgrid = randomgrid(support(F),vals)\n    @debug \"Random evaluation in abserror\"\n    Fval = F(rgrid)\n    fval = sample(rgrid,f,codomaintype(F))\n    sum(abs.(Fval-fval))/vals\nend\n\n# Get the max approximation error in random interior points\nfunction maxerror(f::Function, F::Expansion; vals = 200, options...)\n    rgrid = randomgrid(support(F),vals)\n    @debug \"Random evaluation in maxerror\"\n    Fval = F(rgrid; options...)\n    fval = sample(rgrid,f,codomaintype(F))\n    maximum(abs.(Fval-fval))\nend\n\nusing QuadGK\n\nfunction L2error(f::Function, F::Expansion{S,T}; rtol = eps(real(T)), atol = eps(real(T)), options...) where {S,T}\n    I = QuadGK.quadgk(x->abs(F(x)-f(x))^2, infimum(support(dictionary(F))), supremum(support(dictionary(F))), rtol=rtol, atol=atol)\n    @assert I[2] < 100max(rtol*I[1],atol)\n    sqrt(I[1])\nend\n\nfunction residual(f::Function, F::Expansion; residualtype = :l2, options...)\n    A, B = discretization(f, dictionary(F); options...)\n    R = A*coefficients(F)-B\n    if residualtype == :l2\n        norm(R)\n    elseif residualtype == :relativel2\n        norm(R)/norm(B)\n    elseif residualtype == :maxnorm\n        maximum(abs.(R))\n    else\n        error(\"Unknown residualtype: $residualtype\")\n    end\nend\n", "meta": {"hexsha": "0debfb95962ea7ed9d220b0f3473f77c4b3f387a", "size": 1347, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fun/error.jl", "max_stars_repo_name": "GeorgAUT/FrameFun.jl", "max_stars_repo_head_hexsha": "769c342ae76de06fa986662862ab448e48c1849c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fun/error.jl", "max_issues_repo_name": "GeorgAUT/FrameFun.jl", "max_issues_repo_head_hexsha": "769c342ae76de06fa986662862ab448e48c1849c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fun/error.jl", "max_forks_repo_name": "GeorgAUT/FrameFun.jl", "max_forks_repo_head_hexsha": "769c342ae76de06fa986662862ab448e48c1849c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8536585366, "max_line_length": 131, "alphanum_fraction": 0.6592427617, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654164300481, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.796585215192721}}
{"text": "# Solve Poisson's equation -(uxx + uyy) = f, bnd cnds u(x,y) = g(x,y)\n# on a square grid using the finite difference method.\n#\n# UC Berkeley Math 228B, Per-Olof Persson <persson@berkeley.edu>\n\nusing Pkg\nPkg.add(\"Laplacians\")\nusing SparseArrays, PyPlot, Laplacians\n\n\"\"\"\n    A, b, x, y = assemblePoisson(n, f, g)\n\nAssemble linear system Au = b for Poisson's equation using finite differences.\nGrid size (n+1) x (n+1), right hand side function f(x,y), Dirichlet boundary\nconditions g(x,y).\n\"\"\"\n\nfunction D2x(f,x,y,h) \n  return (f(x-h,y)-2*f(x,y)+f(x+h,y))/h^2\nend\nfunction D2y(f,x,y,h) \n  return (f(x,y-h)-2*f(x,y)+f(x,y+h))/h^2\nend\n\nfunction z(f,x,y,h)\n  return f(x,y) + h^2*(D2x(f,x,y,h)+D2y(f,x,y,h))/12\nend\n\nfunction assemblePoisson(n, f, g)\n    h = 1.0 / n #on a grid of 1x1, figure out index spacing\n    N = (n+1)^2 #size of all elements, including boundary conditions\n    x = h * (0:n) #x coords of the index points\n    y = x #equate 2 axis\n\n    umap = reshape(1:N, n+1, n+1)     # Index mapping from 2D grid to vector\n    A = Tuple{Int64,Int64,Float64}[]  # Array of matrix elements (row,col,value)\n    b = zeros(N)\n    \n\n    # Main loop, insert stencil in matrix for each node point\n    for j = 1:n+1\n        for i = 1:n+1\n            row = umap[i,j]\n            if i == 1 || i == n+1 || j == 1 || j == n+1\n                # Dirichlet boundary condition, u = g\n                push!(A, (row, row, 1.0))\n                b[row] = g(x[i],y[j])\n            else\n                # Interior nodes, 5-point stencil\n                push!(A, (row, row, 20.0))\n                push!(A, (row, umap[i+1,j], -4.0))\n                push!(A, (row, umap[i-1,j], -4.0))\n                push!(A, (row, umap[i,j+1], -4.0))\n                push!(A, (row, umap[i,j-1], -4.0))\n                \n                push!(A, (row, umap[i+1,j+1], -1.0))\n                push!(A, (row, umap[i-1,j+1], -1.0))\n                push!(A, (row, umap[i+1,j-1], -1.0))\n                push!(A, (row, umap[i-1,j-1], -1.0))\n                b[row] = z(f, x[i], y[j], h) * 6*h^2\n            end\n        end\n    end\n\n    # Create CSC sparse matrix from matrix elements\n    A = sparse((x->x[1]).(A), (x->x[2]).(A), (x->x[3]).(A), N, N)\n\n    return A, b, x, y\nend\n\nfunction testPoisson(n=40)\n    uexact(x,y) = exp(-(4(x - 0.3)^2 + 9(y - 0.6)^2)) #truesoln\n    f(x,y) = uexact(x,y) * (26 - (18y - 10.8)^2 - (8x - 2.4)^2) #f_ij\n    \n    A, b, x, y = assemblePoisson(n, f, uexact)\n\n    # Solve + reshape for plotting\n    u = reshape(A \\ b, n+1, n+1)\n\n    # Plotting\n    clf()\n    contour(x, y, u, 10, colors=\"k\")\n    contourf(x, y, u, 10)\n    axis(\"equal\")\n    colorbar()\n    \n    # Compute error in max-norm\n    u0 = uexact.(x, y') #solving for lte\n    error = maximum(abs.(u - u0))\nend\n", "meta": {"hexsha": "06e5984025e475cfb1016ca307f3c6968d9d43bc", "size": 2746, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "fdpoisson9.jl", "max_stars_repo_name": "edhschen/228bCode", "max_stars_repo_head_hexsha": "70cfb5547a6ec93244c7d2a303ab272b0a44a016", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fdpoisson9.jl", "max_issues_repo_name": "edhschen/228bCode", "max_issues_repo_head_hexsha": "70cfb5547a6ec93244c7d2a303ab272b0a44a016", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fdpoisson9.jl", "max_forks_repo_name": "edhschen/228bCode", "max_forks_repo_head_hexsha": "70cfb5547a6ec93244c7d2a303ab272b0a44a016", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1758241758, "max_line_length": 80, "alphanum_fraction": 0.5105608157, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7965852110373147}}
{"text": "using FastGaussQuadrature\nimport GSL\n\n\"\"\"\n    U = upsampling_matrix(n, m)\n\num = U*un upsamples a function u(x) from n to m GL nodes on [-1,1] \\\\\nCan be used to create a downsampling matrix as well\n\"\"\"\nfunction upsampling_matrix(n, m)\n    L = legendre_matrix(n)\n    B = Array{Float64}(m, n)\n    glpoints, glweights = gausslegendre(m)        \n    for i=1:m\n        P = GSL.sf_legendre_Pl_array(n-1, glpoints[i])\n        for j=1:n\n            B[i,j] = P[j]\n        end\n    end\n    return B*L\nend\n\n\"\"\"\n    L = legendre_matrix(order)\n\nL computes Legendre expansion coefficients for a function\ndefined at the Gauss-Legendre quadrature nodes on [-1, 1] \\\\\n``c = L*f  ->  c_l = (2l+1)/2 \\\\sum_n P_l(x_n) f_n w_n``\n\"\"\"\nfunction legendre_matrix(n)\n    glpoints, glweights = gausslegendre(n)    \n    L = Array{Float64}(n, n)\n    for i=1:n\n        P = GSL.sf_legendre_Pl_array(n-1, glpoints[i])\n        for j=1:n\n            l = j-1\n            L[j, i] = P[j]*glweights[i]*(2*l+1)/2\n        end\n    end\n    return L\nend\n\n\"\"\" \n    D = legendre_diff_matrix(order)\n\nD approximates the derivative of a function defined at \nthe Gauss-Legendre quadrature nodes on [-1, 1] \\\\\n``D*f =~ f'``\n\"\"\"\nfunction legendre_diff_matrix(n)\n    glpoints, glweights = gausslegendre(n)    \n    dPt = Array{Float64}(n, n)\n    for i=1:n\n        _, dP = legendre_Pl_deriv_array(n-1, glpoints[i])\n        for j=1:n\n            dPt[i, j] = dP[j]\n        end\n    end\n    L = legendre_matrix(n)\n    return dPt*L\nend\n\n\n\"\"\"\nP, D = legendre_Pl_deriv_array(n, x) \\\\\nRecurrence relation used: [http://dlmf.nist.gov/18.9]\n\nAs fast as the GSL implementation, but also takes x outside [-1, 1].\n    \"\"\"\nfunction legendre_Pl_deriv_array(n, x)\n    P = Array{Complex{Float64}}(n+1)\n    D = Array{Complex{Float64}}(n+1)\n    P[1] = 1.0 # l=0\n    D[1] = 0.0\n    P[2] = x # l=1\n    D[2] = 1.0\n    for l=1:n-1\n        # Compute l+1\n        P[l+1+1] = ( (2*l+1)*x * P[l+1] - l*P[l-1+1] ) / (l+1)\n        D[l+1+1] = ( (2*l+1)*(P[l+1] + x * D[l+1]) - l*D[l-1+1] ) / (l+1)\n    end\n    P, D\nend\n\n\"\"\"\n    t, relres, iter = newton_legendre(c, zr, t0, maxiter, tol)\n\nFind root t of Legendre expansion c such that\n``\\\\sum_n c_n*P_n(t) = zr``\n\"\"\"\nfunction newton_legendre(c, zr, t0, maxiter, tol)\n    t = t0\n    iter = 0\n    dt = Inf\n    lmax = length(c)-1\n    relres = tol\n    for iter=1:maxiter\n        P, D = legendre_Pl_deriv_array(lmax, t)\n        f = sum(P.*c) - zr\n        fp = sum(D.*c)\n        dt = -f / fp\n        t = t + dt\n        relres = abs(dt/t)\n        if relres < tol\n            break\n        end\n    end\n    return t, relres, iter\nend\n", "meta": {"hexsha": "c7449d1417c3dbd1f260cfdeab94508ff17cbc6d", "size": 2586, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/src/legendre.jl", "max_stars_repo_name": "askhamwhat/inse-fiem-2d", "max_stars_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-08-20T12:53:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:15:10.000Z", "max_issues_repo_path": "julia/src/legendre.jl", "max_issues_repo_name": "askhamwhat/inse-fiem-2d", "max_issues_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/src/legendre.jl", "max_forks_repo_name": "askhamwhat/inse-fiem-2d", "max_forks_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-28T18:44:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T04:17:59.000Z", "avg_line_length": 23.5090909091, "max_line_length": 73, "alphanum_fraction": 0.5560711524, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509316, "lm_q2_score": 0.8459424314825852, "lm_q1q2_score": 0.796585207823509}}
{"text": "module Newton\n\n# Write your package code here.\nusing Statistics, LinearAlgebra, ForwardDiff\n\nfunction newtonroot(f,f′;x₀,tol=1E-7,maxiter=1000)\n    println(\"the first dispach\")\n    x=zeros(maxiter+1)\n    x_old=x₀\n    i=1\n    norm_dif=Inf\n    while i <= maxiter &&  norm_dif>=tol \n        x_new=x_old - f(x_old)/f′(x_old)\n        i+=1\n        norm_dif=norm(x_new-x_old)\n        x_old=x_new\n    end\n    if i == maxiter+1\n        return nothing\n    else \n        return (iteration=i, norm_dif=norm_dif, x=x_old)\n    end\nend\n\n\nfunction newtonroot(f;x₀,tol = 1E-7,maxiter = 1000)\n    println(\"the second dispach\")\n    x=zeros(maxiter+1)\n    x_old=x₀\n    i=1\n    norm_dif=Inf\n    f_prime(x)=ForwardDiff.derivative(f,x)\n    while i <= maxiter &&  norm_dif>=tol \n        x_new=x_old - f(x_old)/f_prime(x_old)\n        i+=1\n        norm_dif=norm(x_new-x_old)\n        x_old=x_new\n    end\n    if i == maxiter+1\n        return nothing\n    else \n        return (iteration=i, norm_dif=norm_dif, x=x_old)\n    end\nend\n\nexport newtonroot\nend\n", "meta": {"hexsha": "5e748e61a0482c1b6778f2e4d1ed88d9092b2041", "size": 1024, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Newton.jl", "max_stars_repo_name": "khosseini1130/Newton.jl", "max_stars_repo_head_hexsha": "53560477b961beef6fe2ac862b05b5385b777c2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Newton.jl", "max_issues_repo_name": "khosseini1130/Newton.jl", "max_issues_repo_head_hexsha": "53560477b961beef6fe2ac862b05b5385b777c2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Newton.jl", "max_forks_repo_name": "khosseini1130/Newton.jl", "max_forks_repo_head_hexsha": "53560477b961beef6fe2ac862b05b5385b777c2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3333333333, "max_line_length": 56, "alphanum_fraction": 0.6162109375, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.796585207823509}}
{"text": "function euclidean_distance(set1::Array, set2::Array)\n\n    @assert length(set1) == length(set2) \"Sets don't have the same length\"\n\n    sum = zero(eltype(set1))\n\n    for i in 1:length(set1)\n            sum += (set2[i] - set1[i])^2\n    end\n\n    return sqrt(sum)\n\nend\n", "meta": {"hexsha": "634106eadec3a2fdde7bd9bf4955f43af09ac3ea", "size": 265, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/EuclideanDistance.jl", "max_stars_repo_name": "eRRe-i/MyDistanceSimilarityPKG.jl", "max_stars_repo_head_hexsha": "9c45e2da36eedcd2f230e5a2bdd4262ca18ed5f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/EuclideanDistance.jl", "max_issues_repo_name": "eRRe-i/MyDistanceSimilarityPKG.jl", "max_issues_repo_head_hexsha": "9c45e2da36eedcd2f230e5a2bdd4262ca18ed5f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/EuclideanDistance.jl", "max_forks_repo_name": "eRRe-i/MyDistanceSimilarityPKG.jl", "max_forks_repo_head_hexsha": "9c45e2da36eedcd2f230e5a2bdd4262ca18ed5f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9285714286, "max_line_length": 74, "alphanum_fraction": 0.6113207547, "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9688561685659695, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7965830045022312}}
{"text": "using LinearAlgebra\r\n\r\n# k_local(Elastic Modulus,thickness,height,length,number of nodes,row/column one,row/column two, ==1 adjusts for fixed node)\r\n\r\n#creates local stiffness matrix and maps to global\r\nfunction k_local(E,t,h,l,i,n1,n2,fixed=0)\r\n    k_global = zeros(i,i)\r\n    A = t*h\r\n    k = ((E*A)/l)\r\n    k_global[n1,n1] = k\r\n    k_global[n1,n2] = -k\r\n    k_global[n2,n1] = -k\r\n    k_global[n2,n2] = k\r\n    if fixed == 1\r\n      adj = zeros(1,i)\r\n      adj[n1] = 1\r\n      k_global[n1,:] = adj \r\n      k_global[:,n1] = adj \r\n    end\r\n    return k_global\r\nend\r\n\r\n# constants from problem statement\r\nE = 28*10^3\r\nt = 1/8\r\nh16 = 4\r\nh2345 = 2.5/4\r\nl = 2\r\nl2345 = 8\r\n\r\n# combining all globally mapped matrices\r\nkG = k_local(E,t,h16,l,4,1,2,1)+\r\n     k_local(E,t,h2345,l2345,4,2,3)+\r\n     k_local(E,t,h2345,l2345,4,2,3)+\r\n     k_local(E,t,h2345,l2345,4,2,3)+\r\n     k_local(E,t,h2345,l2345,4,2,3)+\r\n     k_local(E,t,h16,l,4,3,4)\r\n\r\n# Force Vector\r\nf = Float64[0 0 0 500]\r\nF = transpose(f)\r\n\r\n# Displacement vector\r\nu = kG\\F\r\nprintln(\"Nodal Displacement Vector (inches)\")\r\ndisplay(u)\r\n\r\n# Strain Function\r\nϵ(x2,x1,l) = (x2 - x1)/l\r\n\r\n#Strain Vector\r\nϵM = [ϵ(u[2],u[1],l)\r\n      ϵ(u[3],u[2],l2345) \r\n      ϵ(u[3],u[2],l2345) \r\n      ϵ(u[3],u[2],l2345) \r\n      ϵ(u[3],u[2],l2345)\r\n      ϵ(u[4],u[3],l)]\r\n\r\n# Stress Function\r\nσ(E,ϵ) = E*ϵ\r\n\r\n# Stress Vector\r\nσM = [σ(E,ϵM[1])\r\n      σ(E,ϵM[2])\r\n      σ(E,ϵM[3])\r\n      σ(E,ϵM[4])\r\n      σ(E,ϵM[5])\r\n      σ(E,ϵM[6])]\r\nprintln(\"Element Stress Vector (psi)\")\r\ndisplay(σM)\r\n\r\n", "meta": {"hexsha": "dff569f6d1992873cdaf86165fc0ca91350377d6", "size": 1514, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "trejo_nicholas_HW3_p2.jl", "max_stars_repo_name": "UltraHeckerNick/MechanicalPrograms_small", "max_stars_repo_head_hexsha": "1059fb6c0d391be5ef75c4ba165e4f48819bfb2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trejo_nicholas_HW3_p2.jl", "max_issues_repo_name": "UltraHeckerNick/MechanicalPrograms_small", "max_issues_repo_head_hexsha": "1059fb6c0d391be5ef75c4ba165e4f48819bfb2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trejo_nicholas_HW3_p2.jl", "max_forks_repo_name": "UltraHeckerNick/MechanicalPrograms_small", "max_forks_repo_head_hexsha": "1059fb6c0d391be5ef75c4ba165e4f48819bfb2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0277777778, "max_line_length": 125, "alphanum_fraction": 0.5561426684, "num_tokens": 619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517095103499, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7965701710273333}}
{"text": "# calculate probability by pdf\n# sensor_data_200.txt\n# plot as 2d-contour\n\nmodule ContourPdf200\n    using DataFrames, CSV, Statistics, LinearAlgebra\n    using Base.Iterators, Plots\n    pyplot()\n\n    function pdf(x, mu, cov_mat)\n        # determinant\n        det_mat = det(cov_mat)\n\n        diff_x = x - mu\n        return exp(-((diff_x'/cov_mat)*diff_x)/2)/(2*pi*sqrt(det_mat))\n    end\n\n    function main(is_test=false)\n        # input\n        data_path = joinpath(split(@__FILE__, \"src\")[1], \"data/sensor_data_200.txt\")\n        df = CSV.read(data_path, DataFrame, \n                      header=[\"date\", \"time\", \"ir\", \"lidar\"],\n                      delim=' ')\n\n        # variance\n        var_ir = var(df.ir)\n        var_lidar = var(df.lidar)\n\n        #covariance\n        diff_ir = df.ir .- mean(df.ir)\n        diff_lidar = df.lidar .- mean(df.lidar)\n        a = diff_ir .* diff_lidar\n        covar = cov(df.ir, df.lidar, corrected=false)\n        \n        # covariance matrix\n        cov_mat = [var_ir covar; covar var_lidar]\n\n        # mean(mu)\n        mu = [mean(df.ir); mean(df.lidar)]\n\n        # plot contour\n        vx = 280:340\n        vy = 190:230\n        z = [pdf([x; y], mu, cov_mat) for x in vx, y in vy]\n        contour(vx, vy, z', label=\"contour\", c=:haline, aspect_ratio=:equal)\n        \n        if is_test == false\n            save_path = joinpath(split(@__FILE__, \"src\")[1], \"src/prob_stats/multi_dim_gauss_dist/contour_pdf/contour_pdf_200.png\")\n            savefig(save_path)\n        end\n    end\nend", "meta": {"hexsha": "9afa0929394a66190ded29837a356c406c846328", "size": 1514, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/prob_stats/multi_dim_gauss_dist/contour_pdf/contour_pdf_200.jl", "max_stars_repo_name": "ShisatoYano/JuliaAutonomy", "max_stars_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2021-03-10T12:43:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T16:40:19.000Z", "max_issues_repo_path": "src/prob_stats/multi_dim_gauss_dist/contour_pdf/contour_pdf_200.jl", "max_issues_repo_name": "ShisatoYano/JuliaAutonomy", "max_issues_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/prob_stats/multi_dim_gauss_dist/contour_pdf/contour_pdf_200.jl", "max_forks_repo_name": "ShisatoYano/JuliaAutonomy", "max_forks_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-14T02:46:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T09:19:40.000Z", "avg_line_length": 29.1153846154, "max_line_length": 131, "alphanum_fraction": 0.5614266843, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517117469261, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7965701606985244}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.6\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, StatsBase, DataFrames\n\tRandom.seed!(1)\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 2.2\"\n\n# ╔═╡ 6ffea8a0-1ea1-11eb-1991-61c054bcac44\nbegin\n\tA = Set(['a','e','i','o','u'])\n\tB = Set(['x','y','z'])\n\tomega = 'a':'z'\n\n\tN = 10^6\nend;\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\tdf = DataFrame()\n\tlocal mcEst1, mcEst2\n\tfor _ in 1:5\n    \tmcEst1 = sum([in(sample(omega),A) || in(sample(omega),B) for _ in 1:N])/N\n    \tmcEst2 = sum([in(sample(omega),union(A,B)) for _ in 1:N])/N\n\t\tappend!(df, DataFrame(:mcEst1 => mcEst1, :mcEst2 => mcEst2))\n\tend\n\tdf\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 2.2\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═6ffea8a0-1ea1-11eb-1991-61c054bcac44\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "de423a332b6e62521b9e784e6a804fc89d3a6193", "size": 1163, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/02/listing2.02.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/02/listing2.02.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/02/listing2.02.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 22.8039215686, "max_line_length": 78, "alphanum_fraction": 0.6835769561, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.8962513842182777, "lm_q1q2_score": 0.7965512962630171}}
{"text": "# # Ordinary random walk\n\n# Here is the prototypical application. We repeatedly perform an ordinary random walk with a fixed\n# number of steps on $\\mathbb{Z}$, collecting statistics on the final position.\n# We call each walk, or trajectory, a *sample*. An ensemble of samples is a *trial*.\n\n# We begin by loading packages that we will use.\n\nusing RandomWalks\nusing EmpiricalCDFs: EmpiricalCDF, get_data\nusing Statistics\n\n# First, we show an uncommented version of the code that specifies and runs the experiment.\n# Note that it is very compact!\n\ntrial_loop = SampleLoopActor(10^6, ECDFActor(get_x, EmpiricalCDF()));\ntrial!(WalkPlan(WalkF(), StepLimitActor(10^3)), trial_loop);\n\n# In the following we go through the same code step-by-step.\n\n# ### Generating the samples and the trial\n\n# A sample is a single trajectory, or walk. We will take `nsamples` samples.\nnsamples = 10^6;\n\n# Choose the number of steps per walk.\nnsteps = 10^3;\n\n# Create an emtpy empirical cumulative distribution function for floating point data.\necdf = EmpiricalCDF()\n\n# A trial is a collection of samples (walks) from which we collect statistics.\n# The following instance of a `SampleLoopActor` specifies that we collect `nsamples` samples and that we\n# build an empirical CDF of the final position (on the x-axis) of the walker after each walk. Below, we will\n# use a one-dimensional walk, so `get_x` returns the position.\ntrial_loop = SampleLoopActor(nsamples, ECDFActor(get_x, ecdf));\n\n# We used two `AbstractActors` above. `Actors` are treated (for the most part)\n# in a uniform way within a sample, and in (a different)\n# uniform way within a trial. This gives flexibility in designing experiments.\n\n# We create a `WalkPlan` and run a trial of `nsamples` samples.\n# The `WalkPlan` consists of  two parts;\n# The first, a walk specification `WalkF()`, which is the default one-dimension walk on the integers.\n# The second an action `StepLimitActor(nsteps)` to take after each step.\n# `StepLimitActor(nsteps)` stops the walk if the number of steps exceeds `nsteps`.\n# The `WalkPlan` specifies the sample and how it is collected.\n\n# The `Actor` `trial_loop` was described above. It describes how to take several samples and actions to take\n# afer each sample.\n# In this case, which statistics to collect.\n# So, the following line builds an ECDF of the final position of a one-dimensional walk after `nsteps` steps.\n@time trial!(WalkPlan(WalkF(), StepLimitActor(nsteps)), trial_loop);\n\n# We rescale the data so that the expected standard deviation is equal to `1`.\nx = get_data(ecdf);\nx ./= sqrt(nsteps);\n\n# Test that the standard deviation and mean are as expected\n\n## The mean should be near 0 and the standard deviation near 1\n@show mean(ecdf), std(ecdf);\n\n# We test the above results with a generous tolerance.\ntolerance = 1e-3;\n\nisapprox(std(ecdf), 1; atol = tolerance)\n#-\nisapprox(mean(ecdf), 0; atol = tolerance)\n\n# We approximate the probability density function with a normalized `Histogram`\n# and see that it looks reasonable.\nusing StatsBase: Histogram, fit, normalize\nh = normalize(fit(Histogram, get_data(ecdf), -5.5:1.0:5.5));\n\nprintln(h.weights);\n\n\n", "meta": {"hexsha": "482cd88237901a05f3ddf301a7cf927ca6a3e91c", "size": 3139, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/orw1.jl", "max_stars_repo_name": "JuliaTagBot/RandomWalks.jl", "max_stars_repo_head_hexsha": "6292bc29d610d3fdd8bd57b1c49901167c97fb00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/orw1.jl", "max_issues_repo_name": "JuliaTagBot/RandomWalks.jl", "max_issues_repo_head_hexsha": "6292bc29d610d3fdd8bd57b1c49901167c97fb00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-01-10T06:43:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-14T12:00:55.000Z", "max_forks_repo_path": "examples/orw1.jl", "max_forks_repo_name": "JuliaTagBot/RandomWalks.jl", "max_forks_repo_head_hexsha": "6292bc29d610d3fdd8bd57b1c49901167c97fb00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:41:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:41:48.000Z", "avg_line_length": 39.7341772152, "max_line_length": 109, "alphanum_fraction": 0.7531060847, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8705972801594707, "lm_q1q2_score": 0.7965102749519145}}
{"text": "\nusing DifferentialEquations\nusing SimpleDiffEq\nusing DiffEqSensitivity\nusing Random\nusing Distributions\nusing DiffEqParamEstim\nusing Plots\n\n\nfunction sir_ode!(du,u,p,t)\n    (S,I,R,C) = u\n    (β,c,γ) = p\n    N = S+I+R\n    infection = β*c*I/N*S\n    recovery = γ*I\n    @inbounds begin\n        du[1] = -infection\n        du[2] = infection - recovery\n        du[3] = recovery\n        du[4] = infection\n    end\n    nothing\nend;\n\n\nδt = 1.0\ntmax = 40.0\ntspan = (0.0,tmax)\nobstimes = 1.0:1.0:tmax;\n\n\nu0 = [990.0,10.0,0.0,0.0]; # S,I.R,Y\n\n\np = [0.05,10.0,0.25]; # β,c,γ\n\n\nprob_ode = ODEProblem(sir_ode!,u0,tspan,p)\nsol_ode = solve(prob_ode,Tsit5(),saveat=δt);\n\n\nout = Array(sol_ode)\nC = out[4,:];\n\n\nX = C[2:end] .- C[1:(end-1)];\n\n\nRandom.seed!(1234);\n\n\nY = rand.(Poisson.(X));\n\n\nusing Optim\n\n\nfunction ss1(β)\n    prob = remake(prob_ode,u0=[990.0,10.0,0.0,0.0],p=[β,10.0,0.25])\n    sol = solve(prob,Tsit5(),saveat=δt)\n    out = Array(sol)\n    C = out[4,:]\n    X = C[2:end] .- C[1:(end-1)]\n    nonpos = sum(X .<= 0)\n    if nonpos > 0\n        return Inf\n    end\n    return(sum((X .- Y) .^2))\nend;\n\n\nfunction nll1(β)\n    prob = remake(prob_ode,u0=[990.0,10.0,0.0,0.0],p=[β,10.0,0.25])\n    sol = solve(prob,Tsit5(),saveat=δt)\n    out = Array(sol)\n    C = out[4,:]\n    X = C[2:end] .- C[1:(end-1)]\n    nonpos = sum(X .<= 0)\n    if nonpos > 0\n        return Inf\n    end\n    -sum(logpdf.(Poisson.(X),Y))\nend;\n\n\nlower1 = 0.0\nupper1 = 1.0\ninitial_x1 = 0.1;\n\n\nopt1_ss = Optim.optimize(ss1,lower1,upper1)\n\n\nopt1_nll = Optim.optimize(nll1,lower1,upper1)\n\n\nfunction ss2(x)\n    (i0,β) = x\n    I = i0*1000.0\n    prob = remake(prob_ode,u0=[1000.0-I,I,0.0,0.0],p=[β,10.0,0.25])\n    sol = solve(prob,Tsit5(),saveat=δt)\n    out = Array(sol)\n    C = out[4,:]\n    X = C[2:end] .- C[1:(end-1)]\n    nonpos = sum(X .<= 0)\n    if nonpos > 0\n        return Inf\n    end\n    return(sum((X .- Y) .^2))\nend;\n\n\nfunction nll2(x)\n    (i0,β) = x\n    I = i0*1000.0\n    prob = remake(prob_ode,u0=[1000.0-I,I,0.0,0.0],p=[β,10.0,0.25])\n    sol = solve(prob,Tsit5(),saveat=δt)\n    out = Array(sol)\n    C = out[4,:]\n    X = C[2:end] .- C[1:(end-1)]\n    nonpos = sum(X .<= 0)\n    if nonpos > 0\n        return Inf\n    end\n    -sum(logpdf.(Poisson.(X),Y))\nend;\n\n\nlower2 = [0.0,0.0]\nupper2 = [1.0,1.0]\ninitial_x2 = [0.01,0.1];\n\n\nopt2_ss = Optim.optimize(ss2,lower2,upper2,initial_x2)\n\n\nopt2_nll = Optim.optimize(nll2,lower2,upper2,initial_x2)\n\n\nfunction loss_function(sol)\n    out = Array(sol)\n    C = out[4,:]\n    X = C[2:end] .- C[1:(end-1)]\n    nonpos = sum(X .<= 0)\n    if nonpos > 0\n        return Inf\n    end\n    -sum(logpdf.(Poisson.(X),Y))\nend;\n\n\nprob_generator = (prob,q) -> remake(prob,\n    u0=[1000.0-(q[1]*1000),q[1]*1000,0.0,0.0],\n    p=[q[2],10.0,0.25]);\n\n\ncost_function = build_loss_objective(prob_ode,\n    Tsit5(),\n    loss_function,\n    saveat=δt,\n    prob_generator = prob_generator,\n    maxiters=100,\n    verbose=false);\n\n\nopt_pe1 = Optim.optimize(cost_function,lower2,upper2,initial_x2)\n\n\nusing NLopt\nopt = Opt(:LD_MMA, 2)\nopt.lower_bounds = lower2\nopt.upper_bounds = upper2\nopt.min_objective = cost_function\nopt.maxeval = 10000\n(minf,minx,ret) = NLopt.optimize(opt,initial_x2)\n\n\nusing BlackBoxOptim\nbound1 = Tuple{Float64, Float64}[(0.0,1.0),(0.0, 1.0)]\nresult = bboptimize(cost_function;SearchRange = bound1, MaxSteps = 1e4)\n\n", "meta": {"hexsha": "305c7c1d606e6bf81034d4b8b8f5d1a3ce0c12e0", "size": 3294, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_optim/ode_optim.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 126, "max_stars_repo_stars_event_min_datetime": "2020-04-29T08:41:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:42:53.000Z", "max_issues_repo_path": "script/ode_optim/ode_optim.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2020-04-29T11:44:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:45:15.000Z", "max_forks_repo_path": "script/ode_optim/ode_optim.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2020-04-29T08:01:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T16:55:08.000Z", "avg_line_length": 18.0, "max_line_length": 71, "alphanum_fraction": 0.5853066181, "num_tokens": 1339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.8705972616934406, "lm_q1q2_score": 0.7965102721978083}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.3\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local iv = try Base.loaded_modules[Base.PkgId(Base.UUID(\"6e696c72-6542-2067-7265-42206c756150\"), \"AbstractPlutoDingetjes\")].Bonds.initial_value catch; b -> missing; end\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)\n        el\n    end\nend\n\n# ╔═╡ 6c3082f0-6196-11ec-1d58-03f55d178603\nbegin\n\tusing Pkg; Pkg.activate(@__DIR__); Pkg.instantiate()\n\tPkg.precompile()\n\n\tusing PlutoUI\n\tusing LinearAlgebra\n\tusing SparseArrays\n\tusing Images\n\tusing MAT\nend;\n\n# ╔═╡ 6ff4cfec-ba3e-4937-bc3a-bf2d22f1a8f6\nPlutoUI.TableOfContents(aside=true, indent=true, depth=3)\n\n# ╔═╡ 63f2a85b-a426-4c37-a1a0-049d00cfed23\nhtml\"\"\"\n<p align=\"center\">\n\t<img src=\"https://github.com/JuliaAcademy/DataScience/blob/main/datascience.png?raw=true\" alt=\"Course-Logo\" width=\"450px\">\n</p>\n\"\"\"\n\n# ╔═╡ a3ead5b3-0251-4054-b6f7-63bf51b5ff71\nmd\"\"\"\n# 📐 Linear Algebra\n\nA lot of the Data Science methods we will see in this tutorial require some understanding of Linear Algebra, and, in this notebook, we will focus on how Julia handles matrices, the types that exist, and how to call basic Linear Algebra tasks.\n\n[YouTube link](https://www.youtube.com/watch?v=bndXPsRHPg0)\n\n**Note:** matrices in Julia are stored column-wise. It's not actually a matrix (2D structure). In fact, it's an 1D structure.\n\n```math\n\\begin{bmatrix}\n\t1   & 2   & 3   \\\\\n\t11  & 12  & 13  \\\\\n\t110 & 120 & 130 \\\\\n\\end{bmatrix}\n```\n\nis stored in memory as:\n\n```math\n\\begin{bmatrix}\n\t1   \\\\\n\t11  \\\\\n    110 \\\\\n    2   \\\\\n\t12  \\\\\n    120 \\\\\n    3   \\\\\n\t13  \\\\\n    130 \\\\\n\\end{bmatrix}\n```\n\n\"\"\"\n\n# ╔═╡ 1fe44825-0933-4fb8-9b36-511f0e7ffeea\nmd\"\"\"\n## Getting started\n\nWe will get started with creating a random (2D) matrix...\n\"\"\"\n\n# ╔═╡ cd961076-6baf-4626-9089-d33b9dbc94ce\nA = rand(10, 10)\n\n# ╔═╡ eaaffef2-903c-49cf-80b4-bb5adf7d8e92\nmd\"\"\"\nWe can transpose the matrix with the `'` operator...\n\"\"\"\n\n# ╔═╡ 92c1a395-bd96-477a-95dc-294a2ac99784\nAᵗ = A'\n\n# ╔═╡ 5c852935-3055-4178-8ac3-3a6f1d6e8de9\nmd\"\"\"\nThe `transpose` function creates a matrix of type `Adjoint`. In Julia, it is a lazy adjoint. Often, we can easily perform Linear Algebra operations such as `A * A'` without actually transposing the matrix. This type is intended for Linear Algebra usage.\n\"\"\"\n\n# ╔═╡ de94c2dc-b4b0-42a2-aff0-e54543df82e1\ntypeof(Aᵗ)\n\n# ╔═╡ 4770ca47-71ea-4fe1-a5ad-52c4e31f3bdd\n\"Adjoint = $(sizeof(Aᵗ)) bytes\"\n\n# ╔═╡ eccced3e-5898-4d93-8950-58aa77fc4c0b\n\"Matrix = $(sizeof(copy(Aᵗ))) bytes\"\n\n# ╔═╡ 02cbd31b-bd62-48f4-be5e-242279e215d9\nmd\"\"\"\n**Note:** we can convert an `Adjoint` object into a `Matrix` by copying it with the `copy` function.\n\nWe can check if $A$ is positive definite with the `isposdef` function.\n\"\"\"\n\n# ╔═╡ 89fb6b4c-911b-4a39-bdef-b70dbe17f14f\nisposdef(A)\n\n# ╔═╡ 2082cb17-c373-459d-abc1-abe41cfa023a\nmd\"\"\"\nWe can do matrix multiplication with the `*` operator.\n\"\"\"\n\n# ╔═╡ efc88903-189b-48f4-8cde-17bb2c407010\nA * Aᵗ\n\n# ╔═╡ e6c8e66b-f9a3-4b93-b5a4-97c030d381d4\nmd\"\"\"\nWe basically can access matrix elements in two different ways. We can think about a matrix as an 1D column-wise structure and use just one index...\n\"\"\"\n\n# ╔═╡ bb678a13-b45d-410b-b8d5-6346eb839c56\nA[11]\n\n# ╔═╡ 41e22cf0-2448-4643-89ea-7315fb8b0b32\nmd\"\"\"\nOr we can intuitively access matrix elements with a 2D indexing syntax...\n\"\"\"\n\n# ╔═╡ e759d9a1-29cb-4e15-b629-a913ce721b6f\nA[1,2]\n\n# ╔═╡ f662e8dd-d998-4e8c-8924-aee9fe633129\nmd\"\"\"\nBoth methods are equivalent, but the first one is faster...\n\"\"\"\n\n# ╔═╡ 39797209-2206-495f-b517-2ed219ff47ca\nA[13] == A[3,2]\n\n# ╔═╡ f9e97b10-4908-4811-a255-c76c0eaed01c\nmd\"\"\"\nWe can use the sliders below to access matrix `A` elements using the 2nd method...\n\nRow $i$ $(@bind i Slider(1:10, show_value=true))\n\nColumn $j$ $(@bind j Slider(1:10, show_value=true))\n\"\"\"\n\n# ╔═╡ 157971c4-04d9-41de-b378-4a9e998725e9\nA[i,j]\n\n# ╔═╡ d82db838-5ba6-456d-bdeb-cb75a20e081c\nmd\"\"\"\nNow, we can create a (1D) vector of random values...\n\"\"\"\n\n# ╔═╡ 5dc61a15-48e9-46a2-b893-9fb97ecc8b55\nb = rand(10)\n\n# ╔═╡ 0ec44c81-40d5-4b3f-bdec-d3e0cab7de74\nmd\"\"\"\nSuppose that we have a linear system $Ax = b$ and we want the solution $x$. We can easily solve this system, using the `\\` operator.\n\nThe `\\` operator gives the multiplication of `b` by the inverse of `A` on the left. It gives floating-point results for integer arguments. It allows you to solve a system of linear equations, and often uses a suitable matrix factorization to solve the problem. We will cover factorizations next.\n\n**Note:** `\\` is always the recommended way to solve a linear system. You almost never want to call the `inv` function.\n\"\"\"\n\n# ╔═╡ 10474148-5a43-4cc1-8e9f-de57bd3019bc\nx = A \\ b\n\n# ╔═╡ 859cb7ee-d9d8-4bd7-b7c9-5777867297b7\nmd\"\"\"\nwhere `x` is the solution vector.\n\nWhen there isn't any solution `x` for the system $Ax = b$, the `\\` operator will return a vector whose the norm of $Ax-b$ is the minimum least square solution.\n\n**Note:** `A` is a `Matrix` type, and `b` is a `Vector` type. A `Matrix` is a 2D `Array`, and a `Vector` is an 1D `Array`.\n\"\"\"\n\n# ╔═╡ 9f56f781-5abe-407c-b449-0d917dfa2767\nMatrix{Float64} == Array{Float64, 2}\n\n# ╔═╡ 32b59524-9b72-40a2-828f-96f20b0dd924\nVector{Float64} == Array{Float64, 1}\n\n# ╔═╡ 4732c64c-c957-4bdb-9332-7ccb8f40f655\nmd\"\"\"\nWe can also calculate the norm of a structure with the `norm` function. Let's calculate the norm of $Ax-b$, which should be a number close to zero, since $Ax=b$...\n\"\"\"\n\n# ╔═╡ b4b29ad0-8573-40ea-a2d8-c25183825149\nnorm(A*x - b)\n\n# ╔═╡ 8c19fd6c-2f71-480d-8fd0-2241b6f3debe\nmd\"\"\"\n## Factorization\n\nA common tool used in Linear Algebra is matrix factorizations. These factorizations are often used to solve linear systems like $Ax=b$, and as we will see later in this tutorial... $Ax=b$ comes up in a lot of Data Science problems.\n\"\"\"\n\n# ╔═╡ 11bc3a82-19d2-453f-b40b-1eb488ebb323\nmd\"\"\"\n### LU factorization\n\nThe **Lower–Upper (LU) factorization** (decomposition) factors a matrix as the product of a _lower triangular matrix_ $L$ and an _upper triangular matrix_ $U$. The product sometimes includes a _permutation matrix_ $P$ as well.\n\nIn LU factorization (with partial pivoting), we know that $LU=PA$, where $L$ and $U$ are lower and upper matrices and $P$ and $A$ are permutation and original matrices.\n\nIn Julia, we can use the `lu` function to perform LU decomposition.\n\"\"\"\n\n# ╔═╡ 983aeaea-a556-49ba-aedf-898c1b71407d\n# LU factorization\nLUₐ = lu(A)\n\n# ╔═╡ c8d51d21-ec99-4451-a87e-b51d8f118e24\nmd\"\"\"\nWe can access lower, upper and permutation matrices...\n\"\"\"\n\n# ╔═╡ b2b6c7d0-8abb-415e-b668-1fe089b42b04\n# lower triangular matrix\nLₐ = LUₐ.L\n\n# ╔═╡ 790d0305-216f-4335-ab37-acff2de0f18f\n# upper triangular matrix\nUₐ = LUₐ.U\n\n# ╔═╡ 8bb9722c-9cb6-4316-831b-26cb64f93619\n# permutation matrix\nPₐ = LUₐ.P\n\n# ╔═╡ e3571e13-1fa6-44d6-8a31-f810c11cd1f4\n# check if LU = PA\nLₐ*Uₐ ≈ Pₐ*A\n\n# ╔═╡ 311b85d4-6509-4945-a451-41020cac465e\n# norm should be near zero\nnorm(Lₐ*Uₐ - Pₐ*A)\n\n# ╔═╡ ea01ba90-0b30-4998-b1a5-e7fa17e53679\nmd\"\"\"\n### QR factorization\n\nThe **QR factorization**, also known as a QR factorization or QU factorization, is a decomposition of a matrix $A$ into a product $A = QR$ of an _orthogonal matrix_ $Q$ and an _upper triangular matrix_ $R$.\n\nQR decomposition is often used to solve the linear least squares problem and is the basis for a particular eigenvalue algorithm, the QR algorithm.\n\nIn Julia, we can use the `qr` function to perform QR decomposition.\n\"\"\"\n\n# ╔═╡ ada5e3a2-b801-4d2b-8ed8-0b9d8e0cf132\n# QR factorization\nQRₐ = qr(A)\n\n# ╔═╡ 930c8f5d-a05b-4623-84c3-9b58fe59a721\nmd\"\"\"\nWe can access both orthogonal and upper triangular matrices...\n\"\"\"\n\n# ╔═╡ c03c19b1-ec14-4215-9b54-f6cc6b5a2e5c\n# orthogonal matrix\nQₐ = QRₐ.Q\n\n# ╔═╡ 7371a76e-ae89-4138-a614-fa41bfb2dfb0\n# upper triangular matrix\nRₐ = QRₐ.R\n\n# ╔═╡ da750f88-e883-4bec-8e2e-79a91da23f9b\n# check if A = QR\nA ≈ Qₐ*Rₐ\n\n# ╔═╡ 2669897d-cd5a-45c6-afe0-7a91153e3686\n# norm should be near zero\nnorm(A - Qₐ*Rₐ)\n\n# ╔═╡ 737762ba-b142-4fd9-9862-af69f7415030\nmd\"\"\"\n### Cholesky factorization\n\nThe **Cholesky factorization**,  or Cholesky decomposition, is a decomposition of a Hermitian, positive-definite matrix into the product of a _lower triangular matrix_ $L$ and its _conjugate transpose_ $L^t$. In other words, $A = LL^t$ which is useful for efficient numerical solutions.\n\nCholesky factorization is a type of LU factorization, where $L$ and $U$ matrices are the transposed matrices of each other. That's why we call them $L$ and $L^t$.\n\n**Note:** The input matrix needs to be _symmetric positive definite_.\n\"\"\"\n\n# ╔═╡ b1ebbd9d-01d5-4eed-85c3-732491322582\n# make a positive definite matrix\nAᵖ = A * Aᵗ\n\n# ╔═╡ 6cea7788-57a1-426b-8ede-0a424970e2e3\n# check if Aˢ is positive definite\nisposdef(Aᵖ)\n\n# ╔═╡ f7a4fffa-a633-45c9-98a5-b25a047a8a3f\n# Cholesky factorization\nchoₐ = cholesky(Aᵖ)\n\n# ╔═╡ c64cf987-9329-4139-b7e3-0fc21e6f0d92\nmd\"\"\"\nWe can access both lower triangular matrix and its conjugate transpose... \n\"\"\"\n\n# ╔═╡ aa195042-2f7e-4881-9d01-834085dccc11\n# lower triangular matrix\nL = choₐ.L\n\n# ╔═╡ 503192fc-8384-4116-b389-38f04015953c\n# lower triangular conjugate transpose\nLᵗ = choₐ.U\n\n# ╔═╡ 61ea5d3c-63aa-480d-8252-0762f586232f\n# check A = LLᵗ\nAᵖ ≈ L*Lᵗ\n\n# ╔═╡ 49803952-b650-4e5b-9b65-a0d84b21134b\n# norm should be near zero\nnorm(Aᵖ - L*Lᵗ)\n\n# ╔═╡ 3f0a1c9f-8b8a-4886-97bd-3810dfa0263b\nmd\"\"\"\n### The `factorize` function\n\nThe `factorize` function compute a _convenient factorization of_ $A$, based upon the type of the input matrix. factorize checks $A$ to see if it is symmetric/triangular/etc. If $A$ is passed as a generic matrix, `factorize` checks every element of $A$ to verify/rule out each property.\n\n|     Properties of `A`    |\t    Type of factorization       |\n|:------------------------:|:----------------------------------:|\nPositive-definite          | Cholesky (see `cholesky`)          |\nDense Symmetric/Hermitian  | Bunch-Kaufman (see `bunchkaufman`) |\nSparse Symmetric/Hermitian | LDLt (see `ldlt`)                  |\nTriangular                 | Triangular                         |\nDiagonal                   | Diagonal                           |\nBidiagonal                 | Bidiagonal                         |\nTridiagonal\t               | LU (see `lu`)                      |\nSymmetric real tridiagonal | LDLt (see `ldlt`)                  |\nGeneral square\t           | LU (see `lu`)                      |\nGeneral non-square         | QR (see `qr`)                      |\n\n**Example:** if `factorize` is called on a Hermitian positive-definite matrix, for instance, then `factorize` will return a Cholesky factorization.\n\"\"\"\n\n# ╔═╡ 433c016e-334a-43fa-b315-608b4bbdef51\nfactorize(A)\n\n# ╔═╡ 1d9e27be-c21b-4b45-be25-dd1f5b954cb2\nmd\"\"\"\nIn this case, `factorize` performs the LU factorization, since `A` is a square matrix (no need to perform QR factorization), although it is not a positive definite matrix (cannot perform Cholesky factorization).\n\"\"\"\n\n# ╔═╡ d806f387-587a-438c-bb22-f6f14b4d4509\nmd\"\"\"\n## Some LinearAlgebra.jl functions\n\nWith `LinearAlgebra.jl`, we can specify what kind of matrix we want to build. For example, we can use the `diagm` function to create a diagonal matrix whose main diagonal is a vector...\n\"\"\"\n\n# ╔═╡ 1755c27b-b170-4b5f-acf9-87e722fd6fad\nD = diagm([1,2,3,4,5])\n\n# ╔═╡ 10f4304f-06da-4f0a-bfa9-a148169b531f\ntypeof(D)\n\n# ╔═╡ 926cb115-c47f-44e3-bb40-53533d0a1354\nmd\"\"\"\nAlthough it is a diagonal matrix, it's a `Matrix`. To convert it into a `Diagonal`, we can do...\n\"\"\"\n\n# ╔═╡ d86cf3cc-0490-4144-b732-41e40f380813\nDiagonal(D)\n\n# ╔═╡ 7a7002b3-2523-4b33-8dde-511728dfaf0e\nmd\"\"\"\nWe can also build a identity matrix with the `I` function by just passing the number of elements...\n\n**Note:** the matrix below is `Diagonal` type.\n\"\"\"\n\n# ╔═╡ 9980569d-ca11-432e-afb5-33001dea3746\nI(3)\n\n# ╔═╡ a31e0b0d-159f-43f3-aed8-a3b7a33bb73b\ntypeof(I(3))\n\n# ╔═╡ 05bd36f7-b0db-4a58-a591-4cde55139ade\nmd\"\"\"\nWe can perform $A + I$ and Julia will figure it out the convenient size of $I$.\n\"\"\"\n\n# ╔═╡ fee37f40-b39d-4cfa-8f25-882a723d5874\nA + I\n\n# ╔═╡ 83ba1696-9345-49d8-993a-78517d4ffecb\nA + 2I\n\n# ╔═╡ 1d8970d9-7fae-4fef-b4e0-a92aa3e911a7\nmd\"\"\"\n## Sparse Linear Algebra\n\nSparse matrices are stored in Compressed Sparse Column (CSC) form. This form is useful when we are dealing with matrices in which there are very few non-zero elements.\n\nHere, we will use the `SparseArrays.jl` package.\n\nWe can create a sparse random matrix with the `sprand` function. The arguments are: number os rows, number of columns and the probability of non-zero values.\n\"\"\"\n\n# ╔═╡ 512da58a-f8d5-4e0c-8c12-de12cc2a4ba5\nS = sprand(5, 8, 0.2)\n\n# ╔═╡ 0293d061-05bc-484f-abcb-76dd4b54fd30\nmd\"\"\"\nWe can convert it into a regular `Matrix`...\n\"\"\"\n\n# ╔═╡ f051a1cc-cd3d-465d-9ec0-cb711ad691d7\nM = Matrix(S)\n\n# ╔═╡ ab47cafa-3d00-4e7a-8af9-103241fc68c1\nmd\"\"\"\nLet's compare the memory allocation of both `SparseMatrixCSC` and `Matrix` types...\n\"\"\"\n\n# ╔═╡ 8ebe9e1d-981b-4f96-9598-91c8893b8818\n\"Regular matrix = $(sizeof(M)) bytes.\"\n\n# ╔═╡ 223cca30-9c72-4ae3-aa51-85c54a362cf4\n\"Sparse matrix = $(sizeof(S)) bytes.\"\n\n# ╔═╡ 640da366-e78b-4a62-aedc-2668ae69ae95\nmd\"\"\"\nWe can access the non-zero elements of the matrix, using the `nzval` attribute. This attribute returns a `Vector` with all non-zero elements.\n\"\"\"\n\n# ╔═╡ 3a5c505a-0620-4cf4-a546-0a01c191b512\nS.nzval\n\n# ╔═╡ 6b140d76-a5c3-4b86-9cbd-116a724851af\nmd\"\"\"\nWe can access the number of rows with the `m` attribute...\n\"\"\"\n\n# ╔═╡ 12bdbf11-c352-4243-b080-b28c34527e3b\n\"There are $(S.m) rows in the matrix.\"\n\n# ╔═╡ 6d53f3e5-66d1-433f-ad4e-0800b0ecb70f\nmd\"\"\"\nAnd we can also access the number of columns with the `n` attribute...\n\"\"\"\n\n# ╔═╡ 17764c04-a202-4563-98a4-eddb9f432e6d\n\"There are $(S.n) columns in the matrix.\"\n\n# ╔═╡ a441d0b6-9a18-46e4-899d-f3ea2642c7b7\nmd\"\"\"\n## Images as matrices\n\nLet's get to the more _\"data science-y\"_ side. We will do so by working with images (which can be viewed as matrices), and we will use the `SVD` decomposition.\n\nFirst let's load an image. I chose this image as it has a lot of details.\n\"\"\"\n\n# ╔═╡ 0f82de90-1a24-49a6-9673-3abf01283817\nX₁ = load(\"data/khiam-small.jpg\")\n\n# ╔═╡ 4eb22f0f-b287-4be2-b013-824371a44c26\nmd\"\"\"\nAn image may be treated as a `Matrix` of `RGB` pixels as we can see below...\n\"\"\"\n\n# ╔═╡ 3dc31e0a-194c-4ed2-ae6f-c258170aba1a\ntypeof(X₁)\n\n# ╔═╡ 83c6b744-750c-4c74-8b79-a3d78e5b2c12\nmd\"\"\"\nThus, we can access pixels by slicing an image...\n\"\"\"\n\n# ╔═╡ b61a2c57-6443-4e8a-b48a-28e2ad1fca4f\n# the first pixel\nX₁[1,1]\n\n# ╔═╡ 7f003ee7-6958-48e1-a3d8-11876cfa1dbd\n# a random chosen pixel\nX₁[100,20]\n\n# ╔═╡ c2d97352-fb67-4d66-a999-a8362e41ee84\n# first row of pixels\nX₁[1,:]\n\n# ╔═╡ 45f5c9ac-d450-49d6-af9d-28704161f360\n# first column of pixels\nX₁[:,1]\n\n# ╔═╡ 946bf2e5-51e4-4b8b-a316-27e29f15c2e3\nmd\"\"\"\nWe can easily convert the image to gray scale. This is useful when working with images, since we can deal with a single value instead of a RGB tuple.\n\"\"\"\n\n# ╔═╡ 69c75582-f4a1-443e-bda2-385681712821\nXgray = Gray.(X₁)\n\n# ╔═╡ 42a1ee17-86ab-41d8-8b89-5064700e2e64\nmd\"\"\"\nWe can easily extract the RGB layers from the image. We will make use of the `reshape` function below to reshape a vector to a matrix...\n\"\"\"\n\n# ╔═╡ ff77b413-a905-44d6-973d-f7d1193dbb25\nbegin\n\t# red layer\n\tr_arr = map(i -> X₁[i].r, 1:length(X₁))\n\tr_mtx = Float64.(reshape(r_arr, size(X₁)))\n\n\t# red.(X₁)\nend\n\n# ╔═╡ f98fdf05-e6e8-4d0e-b6a6-d3398c2d1ab5\nbegin\n\t# green layer\n\tg_arr = map(i -> X₁[i].g, 1:length(X₁))\n\tg_mtx = Float64.(reshape(g_arr, size(X₁)))\n\n\t# green.(X₁)\nend\n\n# ╔═╡ 34b5d940-7d9a-40fb-a38f-16b267130026\nbegin\n\tb_arr = map(i -> X₁[i].b, 1:length(X₁))\n\tb_mtx = Float64.(reshape(b_arr, size(X₁)))\n\n\t# blue.(X₁)\nend\n\n# ╔═╡ 3b2724d7-f429-447d-948c-e11a8fc20572\nmd\"\"\"\nWe can now create a matrix of all zeros of equal size as the image and then plot each layer separately...\n\"\"\"\n\n# ╔═╡ c071dc2a-e53e-402b-b800-6601025b62c7\nZ_mtx = zeros(size(r_mtx)...)\n\n# ╔═╡ 5e54ac09-2276-4760-adc9-a05082a5c17f\n# red layer\nRGB.(r_mtx, Z_mtx, Z_mtx)\n\n# ╔═╡ 33b3de91-010a-4bd2-863d-199bfbfb8ed8\n# green layer\nRGB.(Z_mtx, g_mtx, Z_mtx)\n\n# ╔═╡ ac394a4c-f983-487c-9d90-1cada3b9e398\n# blue layer\nRGB.(Z_mtx, Z_mtx, b_mtx)\n\n# ╔═╡ 59daefac-6e47-4ecc-9f4a-033faa55fc59\nmd\"\"\"\nWe can easily obtain the `Float64` values of the grayscale image.\n\"\"\"\n\n# ╔═╡ 9d1fa923-e20a-44cc-b0b6-0656f85178fc\nXgrayvalues = Float64.(Xgray)\n\n# ╔═╡ a551a1cb-0d7d-4c82-8f7b-9d92274516f3\nmd\"\"\"\n### SVD factorization\n\nThe **Singular Value Decomposition (SVD)** is a factorization of a real or complex matrix. It generalizes the eigendecomposition of a square normal matrix with an orthonormal eigenbasis to any $n \\times m$ matrix.\n\nThe SVD of an $n \\times m$ complex matrix $A$ is a factorization of the form $A = U \\Sigma V^t$, where $U$ is an $n \\times m$ _complex unitary matrix_, $\\Sigma$ is an $n \\times m$ _rectangular diagonal matrix with singular values_ (non-negative real numbers), and $V$ is an $n \\times n$ _complex unitary matrix_.\n\nThe SVD is an indicator of how much redundant information you have within your data. For example, if we have just a few non-zero values (i.e. low rank matrix), we may assume that we could store this data in much less memory.\n\n**Note:** _low rank_ means that the matrix has very few linearly independent rows or columns.\n\nWe will downsample the grayscale values using the SVD. First, let's obtain the factorization using the function `svd`.\n\"\"\"\n\n# ╔═╡ d66ae839-2d03-40f6-a82e-1e8a063e27f0\nSVD = svd(Xgrayvalues)\n\n# ╔═╡ 54caef76-2f0d-4e9f-a3a1-725ab3d64648\nmd\"\"\"\nWe may access $U$, $\\Sigma$ and $V$...\n\"\"\"\n\n# ╔═╡ a28364a5-5c03-4b42-b354-2cdb1880ca1d\n# rectangular unitary matrix\nU = SVD.U\n\n# ╔═╡ 0a30e77d-8770-4b75-9c7d-e45f6d301022\n# diagonal matrix with singular values\nΣ = diagm(SVD.S)\n\n# ╔═╡ ac8e9a63-708c-408f-bc91-a57356dae648\n# transposed square unitary matrix\nVᵗ = SVD.V'\n\n# ╔═╡ 96766fac-6950-4554-b89a-32143f120f04\n# check if A = UΣVᵗ\nXgrayvalues ≈ U*Σ*Vᵗ\n\n# ╔═╡ 1de26f9d-89eb-4397-adba-ed566cd054d6\n# norm should be near zero\nnorm(Xgrayvalues - U*Σ*Vᵗ)\n\n# ╔═╡ 90922832-4ed1-4fa6-bb61-1242c17e1cd8\nmd\"\"\"\nAccording to the Eckart–Young theorem, we can get the closest rank estimation to the matrix $A$ by extracting the top $k$ singular values.\n\nLet's try to extract the top 4 singular vectors/values to form a new matrix/image.\n\"\"\"\n\n# ╔═╡ 8fc6ee4b-5abc-45e5-a642-6570af32a492\nbegin\n\t# range of singular values\n\tr₄ = 1:4\n\t# first 4 columns of U \n\tu₄ = U[:,r₄]\n\t# first 4 columns of V\n\tv₄ = SVD.V[:,r₄]\n\t# Σ with the top 4 singular values\n\tσ₄ = spdiagm(Σ[r₄])\n\n\t# downsampled image\n\timg₄ = u₄*σ₄*v₄'\n\n\t# grayscale final image\n\tGray.(img₄)\nend\n\n# ╔═╡ ddf9e602-ae0a-43c3-a4b9-c052c513ffc5\nmd\"\"\"\nAs you can see, it's still far away from the original image. Let's try using 50 singular vectors/values.\n\"\"\"\n\n# ╔═╡ 91575c63-16b5-4b30-8f50-392c058218c9\nbegin\n\t# range of singular values\n\tr = 1:50\n\t# first 50 columns of U \n\tu = U[:,r]\n\t# first 50 columns of V\n\tv = SVD.V[:,r]\n\t# Σ with the top 50 singular values\n\tσ = spdiagm(0 => SVD.S[r])\n\n\t# downsampled image\n\timg = u*σ*v'\n\n\t# grayscale final image\n\tGray.(img)\nend\n\n# ╔═╡ 4113a8aa-af35-40fa-836a-f9e347431b5b\nmd\"\"\"\nThis looks better, even though it's not identical to the original image. We can see this from the norm difference below.\n\"\"\"\n\n# ╔═╡ eb0f7a49-c6b9-4b94-9fb1-f9cdcf6c8ee6\nnorm(Xgrayvalues - img)\n\n# ╔═╡ bb25ecf5-b4ed-42a7-8ccd-b67d6d8b8bf0\nmd\"\"\"\n### Face recognition\n\nOur next problem will still be related to images, but this time we will solve a simple form of the face recognition problem. Let's get the data first.\n\n**Note:** we can access the data (`Matrix` type) using the notation `data[\"V2\"]`.\n\"\"\"\n\n# ╔═╡ 716fec98-ef10-465a-a216-beceb4057a91\ndata = matread(\"data/face_recog_qr.mat\")\n\n# ╔═╡ a9dd7d9e-c91e-4a35-ba77-b765161b58b5\nmd\"\"\"\nEach one of the 490 vectors in `data[\"V2\"]` is a fase image. Let's reshape the first one and take a look...\n\"\"\"\n\n# ╔═╡ 194a229c-0a2f-46a4-bdbe-678df9dae106\nbegin\n\tfig₁ = reshape(data[\"V2\"][:,1], 192, 168)\n\tGray.(fig₁)\nend\n\n# ╔═╡ 049cf246-8dbf-4af8-a60d-01e162097272\nmd\"\"\"\nNow we will go back to the vectorized version of this image, and try to select the images that are most similar to it from the \"dictionary\" matrix.\n\nLet's use `b = q[:]` to be the query image.\n\n**Note:** the notation `[:]` vectorizes a matrix column wise.\n\"\"\"\n\n# ╔═╡ 70338fd5-570d-4c71-becd-b30a768554cc\nb¹ = fig₁[:]\n\n# ╔═╡ f1704b39-f48d-49ce-9ec2-77b1fa2af0f8\nmd\"\"\"\nWe will now remove the first image from the dictionary. The goal is to find the solution of the linear system $Ax=b$ where $A$ is the dictionary of all images.\n\nIn face recognition problem, we really want to minimize the norm differece $norm(Ax-b)$ but the `\\` operator actually solves a least squares problem even when the matrix at hand is not invertible.\n\"\"\"\n\n# ╔═╡ dfbaf736-ccb1-4e7c-a2eb-b432e1498008\nbegin\n\tA¹ = data[\"V2\"][:,2:end]\n\tx¹ = A¹\\b¹\n\n\t# display image\n\tGray.(reshape(A¹*x¹, 192, 168))\nend\n\n# ╔═╡ 383a0be3-ce45-43e6-9fe9-d925a40ad9f5\nmd\"\"\"\nNow, let's check the norm difference...\n\"\"\"\n\n# ╔═╡ dd60c14e-d157-48a7-955f-845656636beb\nnorm(A¹*x¹-b¹)\n\n# ╔═╡ 3f20fcb5-6e94-48e0-b2c3-9ff828269e23\nmd\"\"\"\nThis was an easy problem. Let's try to make the picture harder to recover. We will add some random error...\n\"\"\"\n\n# ╔═╡ 50c8a7f4-b620-441f-b941-ece127899ce0\nbegin\n\tfig_temp = fig₁ + rand(size(fig₁,1), size(fig₁,2)) * 0.5\n\tfig₂ = fig_temp ./ maximum(fig_temp)\n\n\t# display noisy image\n\tGray.(fig₂)\nend\n\n# ╔═╡ 6aee282e-e19d-4e8f-bc45-bf20474d41b9\nmd\"\"\"\nLet's define $b$ by vectorizing the matrix `fig₂` and then get $A$...\n\"\"\"\n\n# ╔═╡ 29e803bd-402e-484e-acb7-9053fc8f6a70\nb² = fig₂[:]\n\n# ╔═╡ 5511fbe1-901b-4c0f-b354-21795f3316dc\nA² = A¹\n\n# ╔═╡ bec4214d-6cbe-43d1-a02a-82d4245bdd27\nmd\"\"\"\nNow, let's find the solution $x$ and check the norm difference...\n\"\"\"\n\n# ╔═╡ 798f5b17-48b4-4349-b850-e3e2e62418de\nbegin\n\tx² = A²\\b²\n\tnorm(A²*x² - b²)\nend\n\n# ╔═╡ ea16d6a3-34ac-4c36-b916-47439fbcd0fa\nmd\"\"\"\nThe error is so much bigger this time. Finally, let's check the resulting image...\n\"\"\"\n\n# ╔═╡ 64f6dd6a-0cbf-4f05-b780-c4b2c74ce839\nGray.(reshape(A²*x², 192, 168))\n\n# ╔═╡ Cell order:\n# ╟─6c3082f0-6196-11ec-1d58-03f55d178603\n# ╟─6ff4cfec-ba3e-4937-bc3a-bf2d22f1a8f6\n# ╟─63f2a85b-a426-4c37-a1a0-049d00cfed23\n# ╟─a3ead5b3-0251-4054-b6f7-63bf51b5ff71\n# ╟─1fe44825-0933-4fb8-9b36-511f0e7ffeea\n# ╠═cd961076-6baf-4626-9089-d33b9dbc94ce\n# ╟─eaaffef2-903c-49cf-80b4-bb5adf7d8e92\n# ╠═92c1a395-bd96-477a-95dc-294a2ac99784\n# ╟─5c852935-3055-4178-8ac3-3a6f1d6e8de9\n# ╠═de94c2dc-b4b0-42a2-aff0-e54543df82e1\n# ╠═4770ca47-71ea-4fe1-a5ad-52c4e31f3bdd\n# ╠═eccced3e-5898-4d93-8950-58aa77fc4c0b\n# ╟─02cbd31b-bd62-48f4-be5e-242279e215d9\n# ╠═89fb6b4c-911b-4a39-bdef-b70dbe17f14f\n# ╟─2082cb17-c373-459d-abc1-abe41cfa023a\n# ╠═efc88903-189b-48f4-8cde-17bb2c407010\n# ╟─e6c8e66b-f9a3-4b93-b5a4-97c030d381d4\n# ╠═bb678a13-b45d-410b-b8d5-6346eb839c56\n# ╟─41e22cf0-2448-4643-89ea-7315fb8b0b32\n# ╠═e759d9a1-29cb-4e15-b629-a913ce721b6f\n# ╟─f662e8dd-d998-4e8c-8924-aee9fe633129\n# ╠═39797209-2206-495f-b517-2ed219ff47ca\n# ╟─f9e97b10-4908-4811-a255-c76c0eaed01c\n# ╠═157971c4-04d9-41de-b378-4a9e998725e9\n# ╟─d82db838-5ba6-456d-bdeb-cb75a20e081c\n# ╠═5dc61a15-48e9-46a2-b893-9fb97ecc8b55\n# ╟─0ec44c81-40d5-4b3f-bdec-d3e0cab7de74\n# ╠═10474148-5a43-4cc1-8e9f-de57bd3019bc\n# ╟─859cb7ee-d9d8-4bd7-b7c9-5777867297b7\n# ╠═9f56f781-5abe-407c-b449-0d917dfa2767\n# ╠═32b59524-9b72-40a2-828f-96f20b0dd924\n# ╟─4732c64c-c957-4bdb-9332-7ccb8f40f655\n# ╠═b4b29ad0-8573-40ea-a2d8-c25183825149\n# ╟─8c19fd6c-2f71-480d-8fd0-2241b6f3debe\n# ╟─11bc3a82-19d2-453f-b40b-1eb488ebb323\n# ╠═983aeaea-a556-49ba-aedf-898c1b71407d\n# ╟─c8d51d21-ec99-4451-a87e-b51d8f118e24\n# ╠═b2b6c7d0-8abb-415e-b668-1fe089b42b04\n# ╠═790d0305-216f-4335-ab37-acff2de0f18f\n# ╠═8bb9722c-9cb6-4316-831b-26cb64f93619\n# ╠═e3571e13-1fa6-44d6-8a31-f810c11cd1f4\n# ╠═311b85d4-6509-4945-a451-41020cac465e\n# ╟─ea01ba90-0b30-4998-b1a5-e7fa17e53679\n# ╠═ada5e3a2-b801-4d2b-8ed8-0b9d8e0cf132\n# ╟─930c8f5d-a05b-4623-84c3-9b58fe59a721\n# ╠═c03c19b1-ec14-4215-9b54-f6cc6b5a2e5c\n# ╠═7371a76e-ae89-4138-a614-fa41bfb2dfb0\n# ╠═da750f88-e883-4bec-8e2e-79a91da23f9b\n# ╠═2669897d-cd5a-45c6-afe0-7a91153e3686\n# ╟─737762ba-b142-4fd9-9862-af69f7415030\n# ╠═b1ebbd9d-01d5-4eed-85c3-732491322582\n# ╠═6cea7788-57a1-426b-8ede-0a424970e2e3\n# ╠═f7a4fffa-a633-45c9-98a5-b25a047a8a3f\n# ╟─c64cf987-9329-4139-b7e3-0fc21e6f0d92\n# ╠═aa195042-2f7e-4881-9d01-834085dccc11\n# ╠═503192fc-8384-4116-b389-38f04015953c\n# ╠═61ea5d3c-63aa-480d-8252-0762f586232f\n# ╠═49803952-b650-4e5b-9b65-a0d84b21134b\n# ╟─3f0a1c9f-8b8a-4886-97bd-3810dfa0263b\n# ╠═433c016e-334a-43fa-b315-608b4bbdef51\n# ╟─1d9e27be-c21b-4b45-be25-dd1f5b954cb2\n# ╟─d806f387-587a-438c-bb22-f6f14b4d4509\n# ╠═1755c27b-b170-4b5f-acf9-87e722fd6fad\n# ╠═10f4304f-06da-4f0a-bfa9-a148169b531f\n# ╟─926cb115-c47f-44e3-bb40-53533d0a1354\n# ╠═d86cf3cc-0490-4144-b732-41e40f380813\n# ╟─7a7002b3-2523-4b33-8dde-511728dfaf0e\n# ╠═9980569d-ca11-432e-afb5-33001dea3746\n# ╠═a31e0b0d-159f-43f3-aed8-a3b7a33bb73b\n# ╟─05bd36f7-b0db-4a58-a591-4cde55139ade\n# ╠═fee37f40-b39d-4cfa-8f25-882a723d5874\n# ╠═83ba1696-9345-49d8-993a-78517d4ffecb\n# ╟─1d8970d9-7fae-4fef-b4e0-a92aa3e911a7\n# ╠═512da58a-f8d5-4e0c-8c12-de12cc2a4ba5\n# ╟─0293d061-05bc-484f-abcb-76dd4b54fd30\n# ╠═f051a1cc-cd3d-465d-9ec0-cb711ad691d7\n# ╟─ab47cafa-3d00-4e7a-8af9-103241fc68c1\n# ╠═8ebe9e1d-981b-4f96-9598-91c8893b8818\n# ╠═223cca30-9c72-4ae3-aa51-85c54a362cf4\n# ╟─640da366-e78b-4a62-aedc-2668ae69ae95\n# ╠═3a5c505a-0620-4cf4-a546-0a01c191b512\n# ╟─6b140d76-a5c3-4b86-9cbd-116a724851af\n# ╠═12bdbf11-c352-4243-b080-b28c34527e3b\n# ╟─6d53f3e5-66d1-433f-ad4e-0800b0ecb70f\n# ╠═17764c04-a202-4563-98a4-eddb9f432e6d\n# ╟─a441d0b6-9a18-46e4-899d-f3ea2642c7b7\n# ╠═0f82de90-1a24-49a6-9673-3abf01283817\n# ╟─4eb22f0f-b287-4be2-b013-824371a44c26\n# ╠═3dc31e0a-194c-4ed2-ae6f-c258170aba1a\n# ╟─83c6b744-750c-4c74-8b79-a3d78e5b2c12\n# ╠═b61a2c57-6443-4e8a-b48a-28e2ad1fca4f\n# ╠═7f003ee7-6958-48e1-a3d8-11876cfa1dbd\n# ╠═c2d97352-fb67-4d66-a999-a8362e41ee84\n# ╠═45f5c9ac-d450-49d6-af9d-28704161f360\n# ╟─946bf2e5-51e4-4b8b-a316-27e29f15c2e3\n# ╠═69c75582-f4a1-443e-bda2-385681712821\n# ╟─42a1ee17-86ab-41d8-8b89-5064700e2e64\n# ╠═ff77b413-a905-44d6-973d-f7d1193dbb25\n# ╠═f98fdf05-e6e8-4d0e-b6a6-d3398c2d1ab5\n# ╠═34b5d940-7d9a-40fb-a38f-16b267130026\n# ╟─3b2724d7-f429-447d-948c-e11a8fc20572\n# ╠═c071dc2a-e53e-402b-b800-6601025b62c7\n# ╠═5e54ac09-2276-4760-adc9-a05082a5c17f\n# ╠═33b3de91-010a-4bd2-863d-199bfbfb8ed8\n# ╠═ac394a4c-f983-487c-9d90-1cada3b9e398\n# ╟─59daefac-6e47-4ecc-9f4a-033faa55fc59\n# ╠═9d1fa923-e20a-44cc-b0b6-0656f85178fc\n# ╟─a551a1cb-0d7d-4c82-8f7b-9d92274516f3\n# ╠═d66ae839-2d03-40f6-a82e-1e8a063e27f0\n# ╟─54caef76-2f0d-4e9f-a3a1-725ab3d64648\n# ╠═a28364a5-5c03-4b42-b354-2cdb1880ca1d\n# ╠═0a30e77d-8770-4b75-9c7d-e45f6d301022\n# ╠═ac8e9a63-708c-408f-bc91-a57356dae648\n# ╠═96766fac-6950-4554-b89a-32143f120f04\n# ╠═1de26f9d-89eb-4397-adba-ed566cd054d6\n# ╟─90922832-4ed1-4fa6-bb61-1242c17e1cd8\n# ╠═8fc6ee4b-5abc-45e5-a642-6570af32a492\n# ╟─ddf9e602-ae0a-43c3-a4b9-c052c513ffc5\n# ╠═91575c63-16b5-4b30-8f50-392c058218c9\n# ╟─4113a8aa-af35-40fa-836a-f9e347431b5b\n# ╠═eb0f7a49-c6b9-4b94-9fb1-f9cdcf6c8ee6\n# ╟─bb25ecf5-b4ed-42a7-8ccd-b67d6d8b8bf0\n# ╠═716fec98-ef10-465a-a216-beceb4057a91\n# ╟─a9dd7d9e-c91e-4a35-ba77-b765161b58b5\n# ╠═194a229c-0a2f-46a4-bdbe-678df9dae106\n# ╟─049cf246-8dbf-4af8-a60d-01e162097272\n# ╠═70338fd5-570d-4c71-becd-b30a768554cc\n# ╟─f1704b39-f48d-49ce-9ec2-77b1fa2af0f8\n# ╠═dfbaf736-ccb1-4e7c-a2eb-b432e1498008\n# ╟─383a0be3-ce45-43e6-9fe9-d925a40ad9f5\n# ╠═dd60c14e-d157-48a7-955f-845656636beb\n# ╟─3f20fcb5-6e94-48e0-b2c3-9ff828269e23\n# ╠═50c8a7f4-b620-441f-b941-ece127899ce0\n# ╟─6aee282e-e19d-4e8f-bc45-bf20474d41b9\n# ╠═29e803bd-402e-484e-acb7-9053fc8f6a70\n# ╠═5511fbe1-901b-4c0f-b354-21795f3316dc\n# ╟─bec4214d-6cbe-43d1-a02a-82d4245bdd27\n# ╠═798f5b17-48b4-4349-b850-e3e2e62418de\n# ╟─ea16d6a3-34ac-4c36-b916-47439fbcd0fa\n# ╠═64f6dd6a-0cbf-4f05-b780-c4b2c74ce839\n", "meta": {"hexsha": "424d5f0cb34c0ea73191fe6543a1b5c3ee78897a", "size": 28007, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "02_Linear_Algebra.jl", "max_stars_repo_name": "fnaghetini/DataScience", "max_stars_repo_head_hexsha": "5cd1c2a9c72aacc8a67800c74e394fb0e2045f2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "02_Linear_Algebra.jl", "max_issues_repo_name": "fnaghetini/DataScience", "max_issues_repo_head_hexsha": "5cd1c2a9c72aacc8a67800c74e394fb0e2045f2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02_Linear_Algebra.jl", "max_forks_repo_name": "fnaghetini/DataScience", "max_forks_repo_head_hexsha": "5cd1c2a9c72aacc8a67800c74e394fb0e2045f2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6422319475, "max_line_length": 312, "alphanum_fraction": 0.7163923305, "num_tokens": 12615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.9059898108646849, "lm_q1q2_score": 0.7964980250932668}}
{"text": "# helpful bits for working with n \\geq 2\n\n\"\"\"\n   uvec(x)\n\nHelper to find a unit vector.\n\"\"\"\nfunction uvec(x)\n    nm = norm(x)\n    nm == 0 && return x\n    return x/nm\nend\n\n\"\"\"\n    `unzip(vs)`\n    `unzip(v1, v2, ...)`\n    `unzip(r::Function, a, b)`\n\nTake a vector of points described by vectors (as returned by, say\n`r(t)=[sin(t),cos(t)], r.([1,2,3])`, and return a tuple of collected x\nvalues, y values, and optionally z values.\n\nIf the argument is specified as a comma separated collection of vectors, then these are combined and passed along.\n\nIf the argument is a function and two end point, then the function is\nevaluated at 100 points between `a` and `b`.\n\nThis is useful for plotting when the data is more conveniently\nrepresented in terms of vectors, but the plotting interface requires the x and y values collected.\n\nExamples:\n```\nusing Plots\nr(t) = [sin(t), cos(t)]\nrp(t) = [cos(t), -sin(t)]\nplot(unzip(r, 0, 2pi)...)  # calls plot(xs, ys)\n\nt0, t1 = pi/6, pi/4\n\np, v = r(t0), rp(t0)\nplot!(unzip(p, p+v)...)  # connect p to p+v with line\n\np, v = r(t1), rp(t1)\nquiver!(unzip([p])..., quiver=unzip([v]))\n```\n\nBased on `unzip` from the `Plots` package.\n\"\"\"\nunzip(vs::Vector) = Tuple([[vs[i][j] for i in eachindex(vs)] for j in eachindex(vs[1])])\nfunction unzip(ws::Array; recursive=false)\n    if recursive\n        unzip([unzip(ws[:,j]) for j in 1:size(ws)[end]])\n    else\n        Tuple(eltype(first(ws))[xyz[j] for xyz in ws] for j in eachindex(first(ws)))\n    end\nend\n#unzip(vs) = (A=hcat(vs...); Tuple([A[i,:] for i in eachindex(vs[1])]))\nunzip(v,vs...) = unzip([v, vs...])\nunzip(r::Function, a, b, n=100) = unzip(r.(range(a, stop=b, length=n)))\n\n\n## -----------------------------------\n\n\n## The gradient in SymPy.\n## We avoid name collision with  ForwardDiff.gradient we use `grad`\nimport ForwardDiff: gradient\ngradient(ex::SymPy.Sym, vars::AbstractArray=free_symbols(ex)) = diff.(ex, [vars...])\ngradient(f::Function) = (x, xs...) -> ForwardDiff.gradient(f, vcat(x, xs...))\n\n\n\"\"\"\n    curl(F)\n\nFind curl of a 2 or 3-D vector field.\n\"\"\"\nfunction curl(J::Matrix)\n    if size(J) == (2,2)\n        Mx, Nx, My, Ny = J\n        return Nx - My # a scalar\n    elseif size(J) == (3,3)\n        Mx, Nx, Px, My, Ny, Py, Mz, Nz, Pz = J\n        return [Py-Nz, Mz-Px, Nx-My] # ∇×VF\n    else\n        throw(ArgumentError(\"Wrong size jacobian matrix for a curl\"))\n    end\nend\ncurl(F::Vector{Sym}, vars=free_symbols(F)) = curl(F.jacobian(vars))\ncurl(F::Tuple) = curl(F[1], F[2])\ncurl(F::Function, pt) = curl(ForwardDiff.jacobian(F, float.(pt)))\ncurl(F::Function) = (pt, pts...) -> curl(F, vcat(pt, pts...))\n\n\"\"\"\n    divergence(F)\n\nFind divergence of a 3-D vector vield.\n\"\"\"\ndivergence(F::Vector{Sym}, vars=free_symbols(F)) = sum(diff.(F, vars))\ndivergence(F::Tuple) = divergence(F[1], F[2])\ndivergence(F::Function, pt) = sum(diag(ForwardDiff.jacobian(F, float.(pt))))\ndivergence(F::Function) = (pt, pts...) -> divergence(F, vcat(pt, pts...))\n\n## Is this a bad idea?\n## syntax is a bit heavy with parentheses\n\nstruct DelOperator end\nconst ∇ = DelOperator()\n\n## For symbolic objects, these use `free_symbols(ex)` to find variables\n## this *may* not be right if sorting isn't as desired, or variables don't\n## appear in the formula\n(::DelOperator)(f) = return gradient(f)\n(::DelOperator)(f::Tuple) = gradient(f[1],f[2])\nLinearAlgebra.dot(::DelOperator, F) = divergence(F)\nLinearAlgebra.dot(::DelOperator, F, vars) = divergence(F, vars)\n\nLinearAlgebra.cross(::DelOperator, F) = curl(F)\nLinearAlgebra.cross(::DelOperator, F, vars) = curl(F, vars)\n\n\n##\n", "meta": {"hexsha": "c1fa6528f79d3add70748318c26ed37a76a93263", "size": 3532, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/multidimensional.jl", "max_stars_repo_name": "UnofficialJuliaMirror/CalculusWithJulia.jl-a2e0e22d-7d4c-5312-9169-8b992201a882", "max_stars_repo_head_hexsha": "143c1386e139c395d0971a40395aae16a1da9a9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-25T00:45:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T00:45:02.000Z", "max_issues_repo_path": "src/multidimensional.jl", "max_issues_repo_name": "UnofficialJuliaMirror/CalculusWithJulia.jl-a2e0e22d-7d4c-5312-9169-8b992201a882", "max_issues_repo_head_hexsha": "143c1386e139c395d0971a40395aae16a1da9a9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multidimensional.jl", "max_forks_repo_name": "UnofficialJuliaMirror/CalculusWithJulia.jl-a2e0e22d-7d4c-5312-9169-8b992201a882", "max_forks_repo_head_hexsha": "143c1386e139c395d0971a40395aae16a1da9a9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-25T00:45:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T00:45:44.000Z", "avg_line_length": 28.9508196721, "max_line_length": 114, "alphanum_fraction": 0.6333522084, "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8791467754256017, "lm_q1q2_score": 0.7964980246953788}}
{"text": "# Canonical Correlation Analysis\n\n#### CCA Type\n\"\"\"\nCanonical Correlation Analysis Model\n\"\"\"\nstruct CCA{T<:Real} <: RegressionModel\n    xmean::Vector{T}  # sample mean of X: of length dx (can be empty)\n    ymean::Vector{T}  # sample mean of Y: of length dy (can be empty)\n    xproj::Matrix{T}  # projection matrix for X, of size (dx, p)\n    yproj::Matrix{T}  # projection matrix for Y, of size (dy, p)\n    corrs::Vector{T}  # correlations, of length p\n\n    function CCA(xm::Vector{T},\n                 ym::Vector{T},\n                 xp::Matrix{T},\n                 yp::Matrix{T},\n                 crs::Vector{T}) where T<:Real\n\n        dx, px = size(xp)\n        dy, py = size(yp)\n\n        isempty(xm) || length(xm) == dx ||\n            throw(DimensionMismatch(\"Incorrect length of xmean.\"))\n\n        isempty(ym) || length(ym) == dy ||\n            throw(DimensionMismatch(\"Incorrect length of ymean.\"))\n\n        px == py ||\n            throw(DimensionMismatch(\"xproj and yproj should have the same number of columns.\"))\n\n        length(crs) == px ||\n            throw(DimensionMismatch(\"Incorrect length of corrs.\"))\n\n        new{T}(xm, ym, xp, yp, crs)\n    end\nend\n\n## properties\n\n\"\"\"\n    size(M:CCA)\n\nReturn a tuple with the dimension of `X`, `Y`, and the output dimension.\n\"\"\"\nsize(M::CCA) = (size(M.xproj, 1), size(M.yproj, 1), size(M.xproj, 2))\n\n\"\"\"\n    mean(M::CCA, c::Symbol)\n\nGet the mean vector for the component `c` of the model `M`.\nThe component parameter can be `:x` or `:y`.\n\"\"\"\nfunction mean(M::CCA, c::Symbol)\n    xi, yi, o = size(M)\n    if c == :x\n        fullmean(xi, M.xmean)\n    elseif c == :y\n        fullmean(yi, M.ymean)\n    else\n        throw(ArgumentError(\"Unknown component $c\"))\n    end\nend\n\n\"\"\"\n    projection(M::CCA, c::Symbol)\n\nGet the projection matrix for the component `c` of the model `M`.\nThe component parameter can be `:x` or `:y`.\n\"\"\"\nfunction projection(M::CCA, c::Symbol)\n    if c == :x\n        M.xproj\n    elseif c == :y\n        M.yproj\n    else\n        throw(ArgumentError(\"Unknown component $c\"))\n    end\nend\n\n\"\"\"\n    cor(M::CCA)\n\nThe correlations of the projected componnents (a vector of length `p`).\n\"\"\"\ncor(M::CCA) = M.corrs\n\n## use\n\"\"\"\n    predict(M::CCA, Z::AbstractVecOrMat{<:Real}, c::Symbol)\n\nGiven a [`CCA`](@ref) model, one can transform observations into both spaces into a common space, as\n\n```math\n\\\\mathbf{z}_x = \\\\mathbf{P}_x^T (\\\\mathbf{x} - \\\\boldsymbol{\\\\mu}_x) \\\\\\\\\n\\\\mathbf{z}_y = \\\\mathbf{P}_y^T (\\\\mathbf{y} - \\\\boldsymbol{\\\\mu}_y)\n```\n\nHere, ``\\\\mathbf{P}_x`` and ``\\\\mathbf{P}_y`` are projection matrices for ``X`` and ``Y``;\n``\\\\boldsymbol{\\\\mu}_x`` and ``\\\\boldsymbol{\\\\mu}_y`` are mean vectors.\n\nParameter `Z` can be either a vector of length `dx`, `dy`, or a matrix where each column is an observation. The component parameter `c` can be `:x` or `:y`.\n\"\"\"\nfunction predict(M::CCA, Z::AbstractVecOrMat{<:Real}, c::Symbol)\n    if c == :x\n        transpose(M.xproj) * centralize(Z, M.xmean)\n    elseif c == :y\n        transpose(M.yproj) * centralize(Z, M.ymean)\n    else\n        throw(ArgumentError(\"Unknown component $c\"))\n    end\nend\n\n## show\n\nfunction show(io::IO, M::CCA)\n    xi, yi, o = size(M)\n    print(io, \"CCA (xindim = $xi, yindim = $yi, outdim = $o)\")\nend\n\n\n#### Perform CCA on data\n\n\"\"\"\n    ccacov(Cxx, Cyy, Cxy, xmean, ymean, p)\n\nCompute CCA based on analysis of the given covariance matrices, using generalized\neigenvalue decomposition, and return [`CCA`](@ref) model.\n\nParameters:\n- `Cxx`: The covariance matrix of `X`.\n- `Cyy`: The covariance matrix of `Y`.\n- `Cxy`: The covariance matrix between `X` and `Y`.\n- `xmean`: The mean vector of the **original** samples of `X`, which can be\na vector of length `dx`, or an empty vector indicating a zero mean.\n- `ymean`: The mean vector of the **original** samples of `Y`, which can be\na vector of length `dy`, or an empty vector indicating a zero mean.\n- `p`: The output dimension, *i.e* the dimension of the common space.\n\"\"\"\nfunction ccacov(Cxx::DenseMatrix{T},\n                Cyy::DenseMatrix{T},\n                Cxy::DenseMatrix{T},\n                xmean::Vector{T},\n                ymean::Vector{T},\n                p::Int) where T<:Real\n\n    # argument checking\n    dx, dx2 = size(Cxx)\n    dy, dy2 = size(Cyy)\n    dx == dx2 || error(\"Cxx must be a square matrix.\")\n    dy == dy2 || error(\"Cyy must be a square matrix.\")\n    size(Cxy) == (dx, dy) ||\n        throw(DimensionMismatch(\"size(Cxy) should be equal to (dx, dy)\"))\n\n    isempty(xmean) || length(xmean) == dx ||\n        throw(DimensionMismatch(\"Incorrect length of xmean.\"))\n\n    isempty(ymean) || length(ymean) == dy ||\n        throw(DimensionMismatch(\"Incorrect length of ymean.\"))\n\n    1 <= p <= min(dx, dy) ||\n        throw(DimensionMismatch(\"\"))\n\n    _ccacov(Cxx, Cyy, Cxy, xmean, ymean, p)\nend\n\nfunction _ccacov(Cxx, Cyy, Cxy, xmean, ymean, p::Int)\n    dx = size(Cxx, 1)\n    dy = size(Cyy, 1)\n\n    # solve Px and Py\n\n    if dx <= dy\n        # solve Px: (Cxy * inv(Cyy) * Cyx) Px = λ Cxx * Px\n        # compute Py: inv(Cyy) * Cyx * Px\n\n        G = cholesky(Cyy) \\ Cxy'\n        Ex = eigen(Symmetric(Cxy * G), Symmetric(Cxx))\n        ord = sortperm(Ex.values; rev=true)\n        vx, Px = extract_kv(Ex, ord, p)\n        Py = qnormalize!(G * Px, Cyy)\n    else\n        # solve Py: (Cyx * inv(Cxx) * Cxy) Py = λ Cyy Py\n        # compute Px: inv(Cx) * Cxy * Py\n\n        H = cholesky(Cxx) \\ Cxy\n        Ey = eigen(Symmetric(Cxy'H), Symmetric(Cyy))\n        ord = sortperm(Ey.values; rev=true)\n        vy, Py = extract_kv(Ey, ord, p)\n        Px = qnormalize!(H * Py, Cxx)\n    end\n\n    # compute correlations\n    # Note: Px' * Cxx * Px == I\n    #       Py' * Cyy * Py == I\n    crs = coldot(Px, Cxy * Py)\n\n    # construct CCA model\n    CCA(xmean, ymean, Px, Py, crs)\nend\n\n\"\"\"\n    ccasvd(Zx, Zy, xmean, ymean, p)\n\nCompute CCA based on singular value decomposition of centralized sample matrices `Zx` and `Zy`, and return [`CCA`](@ref) model[^1].\n\nParameters:\n- `Zx`: The centralized sample matrix for `X`.\n- `Zy`: The centralized sample matrix for `Y`.\n- `xmean`: The mean vector of the **original** samples of `X`, which can be\na vector of length `dx`, or an empty vector indicating a zero mean.\n- `ymean`: The mean vector of the **original** samples of `Y`, which can be\na vector of length `dy`, or an empty vector indicating a zero mean.\n- `p`: The output dimension, *i.e* the dimension of the common space.\n\"\"\"\nfunction ccasvd(Zx::DenseMatrix{T},\n                Zy::DenseMatrix{T},\n                xmean::Vector{T},\n                ymean::Vector{T},\n                p::Int) where T<:Real\n\n    dx, n = size(Zx)\n    dy, n2 = size(Zy)\n    n == n2 ||\n        throw(DimensionMismatch(\"Zx and Zy must have the same number of columns.\"))\n\n    isempty(xmean) || length(xmean) == dx ||\n        throw(DimensionMismatch(\"Incorrect length of xmean.\"))\n\n    isempty(ymean) || length(ymean) == dy ||\n        throw(DimensionMismatch(\"Incorrect length of ymean.\"))\n\n    1 <= p <= min(dx, dy) ||\n        throw(DimensionMismatch(\"\"))\n\n    _ccasvd(Zx, Zy, xmean, ymean, p)\nend\n\n# The implementation is partly based on:\n#\n#   David Weenink.\n#   Canonical Correlation Analysis.\n#   Institute of Phonetic Sciences, Univ. of Amsterdam,\n#   Proceedings 25 (2003), 81-99.\n#\n#   Note: in this paper, each row is considered as an observation.\n#   The algorithm is adpated to the column-major format here.\n#\nfunction _ccasvd(Zx::DenseMatrix{T}, Zy::DenseMatrix{T}, xmean::Vector{T}, ymean::Vector{T}, p::Int) where T<:Real\n    # svd factorization of Z\n\n    n = size(Zx, 2)\n\n    # svd decomposition\n    Sx = svd(Zx)\n    Sy = svd(Zy)\n    S = svd!(Sx.Vt * transpose(Sy.Vt)) # svd of Vx * Vy'\n\n    # compute Px and Py\n    ord = sortperm(S.S; rev=true)\n    si = ord[1:p]\n    Px = rmul!(Sx.U, Diagonal(1.0 ./ Sx.S)) * S.U[:, si]\n    Py = rmul!(Sy.U, Diagonal(1.0 ./ Sy.S)) * S.V[:, si]\n\n    # scale so that Px' * Cxx * Py == I\n    #           and Py' * Cyy * Py == I,\n    #\n    # with Cxx = Zx * Zx' / (n - 1)\n    #      Cyy = Zy * Zy' / (n - 1)\n    #\n    rmul!(Px, sqrt(n-1))\n    rmul!(Py, sqrt(n-1))\n\n    # compute correlations\n    crs = rmul!(coldot(Zx'Px, Zy'Py), one(T)/(n-1))\n\n    # construct CCA model\n    CCA(xmean, ymean, Px, Py, crs)\nend\n\n## interface functions\n\n\"\"\"\n    fit(CCA, X, Y; ...)\n\nPerform CCA over the data given in matrices `X` and `Y`.\nEach column of `X` and `Y` is an observation.\n\n`X` and `Y` should have the same number of columns (denoted by `n` below).\n\nThis method returns an instance of [`CCA`](@ref).\n\n**Keyword arguments:**\n- `method`: The choice of methods:\n    - `:cov`: based on covariance matrices\n    - `:svd`: based on SVD of the input data (*default*)\n- `outdim`: The output dimension, *i.e* dimension of the common space (*default*: `min(dx, dy, n)`)\n- `mean`: The mean vector, which can be either of:\n    - `0`: the input data has already been centralized\n    - `nothing`: this function will compute the mean (*default*)\n    - a pre-computed mean vector\n\n**Notes:** This function calls [`ccacov`](@ref) or [`ccasvd`](@ref) internally, depending on the choice of method.\n\"\"\"\nfunction fit(::Type{CCA}, X::AbstractMatrix{T}, Y::AbstractMatrix{T};\n             outdim::Int=min(min(size(X)...), min(size(Y)...)),\n             method::Symbol=:svd,\n             xmean=nothing,\n             ymean=nothing) where T<:Real\n\n    dx, n = size(X)\n    dy, n2 = size(Y)\n\n    n2 == n ||\n        throw(DimensionMismatch(\"X and Y should have the same number of columns.\"))\n\n    (n >= dx && n >= dy) ||\n        @warn(\"CCA would be numerically instable when n < dx or n < dy.\")\n\n    xmv = preprocess_mean(X, xmean)\n    ymv = preprocess_mean(Y, ymean)\n\n    Zx = centralize(X, xmv)\n    Zy = centralize(Y, ymv)\n\n    if method == :cov\n        Cxx = rmul!(Zx*transpose(Zx), inv(n - 1))\n        Cyy = rmul!(Zy*transpose(Zy), inv(n - 1))\n        Cxy = rmul!(Zx*transpose(Zy), inv(n - 1))\n        M = ccacov(Cxx, Cyy, Cxy, xmv, ymv, outdim)\n    elseif method == :svd\n        M = ccasvd(Zx, Zy, xmv, ymv, outdim)\n    else\n        error(\"Invalid method name $(method)\")\n    end\n\n    return M::CCA\nend\n", "meta": {"hexsha": "71a4a7b6c1991945efde98a960f61877058acd20", "size": 10067, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cca.jl", "max_stars_repo_name": "KronosTheLate/MultivariateStats.jl", "max_stars_repo_head_hexsha": "99ee965df3a8e136ff2d0fcb10456b434e1f9001", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cca.jl", "max_issues_repo_name": "KronosTheLate/MultivariateStats.jl", "max_issues_repo_head_hexsha": "99ee965df3a8e136ff2d0fcb10456b434e1f9001", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cca.jl", "max_forks_repo_name": "KronosTheLate/MultivariateStats.jl", "max_forks_repo_head_hexsha": "99ee965df3a8e136ff2d0fcb10456b434e1f9001", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6961651917, "max_line_length": 156, "alphanum_fraction": 0.5885566703, "num_tokens": 3095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750466836961, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7964456058832629}}
{"text": "using Distributions, NLsolve, Statistics\n\nfunction effectsize(xs::AbstractVector, ys::AbstractVector)\n    if length(xs) != length(ys)\n        throw(ArgumentError(\"samples must have the same number of observations\"))\n    end\n    n, m = length(xs), length(ys)\n    x̄, ȳ = mean(xs), mean(ys)\n    σx², σy² = var(xs), var(ys)\n    σ = sqrt(0.5*(σx² + σy²))\n    abs(x̄ - ȳ)/σ\nend\n\nfunction power(xs::AbstractVector, ys::AbstractVector, n::Int=length(xs), p::Float64=0.05; unequalvar=true)\n    dof = if unequalvar\n        varx, vary = var(xs), var(ys)\n        nx, ny = length(xs), length(ys)\n        (varx / nx + vary / ny)^2 / ((varx / nx)^2 / (nx - 1) + (vary / ny)^2 / (ny - 1))\n    else\n        length(xs) + length(ys) - 2\n    end\n    power(effectsize(xs, ys), n, dof, p)\nend\n \nfunction power(d::Float64, n::Int=length(xs), dof=2n-2, α::Float64=0.05)\n    δ = d*sqrt(n/2)\n    tc = quantile(TDist(dof), 1 - α/2)\n    ccdf(NoncentralT(dof, δ), tc) + cdf(NoncentralT(dof, δ), -tc)\nend\n\nfunction power(d::Float64, n::Float64=length(xs), dof=2n-2, α::Float64=0.05)\n    δ = d*sqrt(n/2)\n    tc = quantile(TDist(dof), 1 - α/2)\n    ccdf(NoncentralT(dof, δ), tc) + cdf(NoncentralT(dof, δ), -tc)\nend\n\nfunction solvepower(d::Float64, dof::Float64, β::Float64=0.8, α::Float64=0.05)\n    first(nlsolve((F,x) -> F[1] = power(d, x[1], dof, α) - β, [2.0]).zero)\nend\n\nfunction solvepower(xs::AbstractVector, ys::AbstractVector, β::Float64=0.8, α::Float64=0.05; unequalvar=true)\n    dof = if unequalvar\n        varx, vary = var(xs), var(ys)\n        nx, ny = length(xs), length(ys)\n        (varx / nx + vary / ny)^2 / ((varx / nx)^2 / (nx - 1) + (vary / ny)^2 / (ny - 1))\n    else\n        length(xs) + length(ys) - 2\n    end\n    solvepower(effectsize(xs, ys), dof, β, α)\nend", "meta": {"hexsha": "6a3e132e4ed13ca4e410b982ec924c38cc8c6f51", "size": 1749, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "yuji/src/power.jl", "max_stars_repo_name": "ELIFE-ASU/dglmoore", "max_stars_repo_head_hexsha": "c62d4f0813385095bf9c5cc6b0c4b581b805ebdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "yuji/src/power.jl", "max_issues_repo_name": "ELIFE-ASU/dglmoore", "max_issues_repo_head_hexsha": "c62d4f0813385095bf9c5cc6b0c4b581b805ebdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "yuji/src/power.jl", "max_forks_repo_name": "ELIFE-ASU/dglmoore", "max_forks_repo_head_hexsha": "c62d4f0813385095bf9c5cc6b0c4b581b805ebdb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-03T20:29:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-03T20:29:25.000Z", "avg_line_length": 34.98, "max_line_length": 109, "alphanum_fraction": 0.5871926815, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013548, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7964455986511311}}
{"text": "\n#=\n\nLog linear optimal growth model, with log utility, CD production and\nmultiplicative lognormal shock, so that\n\n    y = f(k, z) = z k^alpha\n\nwith z ~ LN(mu, s).\n\n=#\n\nalpha = 0.4\nbeta = 0.96\nmu = 0\ns = 0.1\n\nab = alpha * beta\nc1 = log(1 - ab) / (1 - beta)\nc2 = (mu + alpha * log(ab)) / (1 - alpha)\nc3 = 1 / (1 - beta)\nc4 = 1 / (1 - ab)\n\n# Utility \nu(c) = log(c)\n\nu_prime(c) = 1 / c\n\n# Deterministic part of production function\nf(k) = k^alpha\n\nf_prime(k) = alpha * k^(alpha - 1)\n\n# True optimal policy\nc_star(y) = (1 - alpha * beta) * y\n\n# True value function\nv_star(y) = c1 + c2 * (c3 - c4) + c4 * log(y)\n    \n\n\n", "meta": {"hexsha": "df900e91cef9b793de8aed2cce67742584ab5b17", "size": 613, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "optgrowth/loglinear_og.jl", "max_stars_repo_name": "parkjt0506/QuantEconPractice", "max_stars_repo_head_hexsha": "2d83848dab7ed8d40efc9bbcf1e73aed7e5e532f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-06T04:09:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-06T04:09:21.000Z", "max_issues_repo_path": "optgrowth/loglinear_og.jl", "max_issues_repo_name": "zhouweimin-econ/QuantEcon.lectures.code", "max_issues_repo_head_hexsha": "a8a17e753857e0157f18337264114ce7cb23e841", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optgrowth/loglinear_og.jl", "max_forks_repo_name": "zhouweimin-econ/QuantEcon.lectures.code", "max_forks_repo_head_hexsha": "a8a17e753857e0157f18337264114ce7cb23e841", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-04-21T21:41:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T22:09:19.000Z", "avg_line_length": 14.5952380952, "max_line_length": 68, "alphanum_fraction": 0.5709624796, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305328688783, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7963140419316811}}
{"text": "module CentroidLinearClassifierImpl\n\nexport train_model\n\nusing LinearAlgebra\nusing ..Clusters, ..LinearClassifiers\n\n\"\"\"\n    train_model(positive_data, negative_data)\n\nTrains a binary classification model.\n\nThe returned model has a field `classify`, a function that classifies a point\nand returns a scalar value, where positive and negative results indicate that\nthe point is positively or negatively classified, respectively.\n\"\"\"\nfunction train_model(positive_data::AbstractMatrix{<:Number},\n                     negative_data::AbstractMatrix{<:Number})::CentroidLinearClassifier\n    @assert size(positive_data, 2) == size(negative_data, 2)\n\n    positive_data_centroid = compute_centroid(positive_data)\n    negative_data_centroid = compute_centroid(negative_data)\n\n    normal_vector = positive_data_centroid .- negative_data_centroid\n    midpoint = (positive_data_centroid .+ negative_data_centroid) ./ 2\n\n    offset = -1 * dot(normal_vector, midpoint)\n\n    decision_function =\n        function (x)\n            return dot(normal_vector, x) + offset\n        end\n\n    return CentroidLinearClassifier(decision_function, normal_vector, offset)\nend\n\nend # module\n", "meta": {"hexsha": "eb694671aa47265ad496cb25e493842d914a5084", "size": 1158, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear_classifiers/centroid_linear_classifier_impl.jl", "max_stars_repo_name": "brianxie/automaton-edification", "max_stars_repo_head_hexsha": "d432604a9eb1ac01b9f99567ece0f00f4145a4f1", "max_stars_repo_licenses": ["BSD-2-Clause-Patent"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/linear_classifiers/centroid_linear_classifier_impl.jl", "max_issues_repo_name": "brianxie/automaton-edification", "max_issues_repo_head_hexsha": "d432604a9eb1ac01b9f99567ece0f00f4145a4f1", "max_issues_repo_licenses": ["BSD-2-Clause-Patent"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/linear_classifiers/centroid_linear_classifier_impl.jl", "max_forks_repo_name": "brianxie/automaton-edification", "max_forks_repo_head_hexsha": "d432604a9eb1ac01b9f99567ece0f00f4145a4f1", "max_forks_repo_licenses": ["BSD-2-Clause-Patent"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4736842105, "max_line_length": 87, "alphanum_fraction": 0.7590673575, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305328688784, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7963140398754427}}
{"text": "#=\n\nPlots reservation wage against the discount factor\n\n=#\n\nusing Plots, LaTeXStrings\npyplot()\n\ninclude(\"mccall_bellman_iteration.jl\") \ninclude(\"compute_reservation_wage.jl\")\n\n\ngrid_size = 25  \nbeta_vals = linspace(0.8, 0.99, grid_size)  \nw_bar_vals = similar(beta_vals)\n\nmcm = McCallModel()\n\nfor (i, beta) in enumerate(beta_vals)\n    mcm.beta = beta\n    w_bar = compute_reservation_wage(mcm)\n    w_bar_vals[i] = w_bar\nend\n\nplot(beta_vals, \n    w_bar_vals, \n    lw=2, \n    alpha=0.7, \n    xlabel=\"discount rate\",\n    ylabel=\"reservation wage\",\n    label=L\"$\\bar w$ as a function of $\\beta$\")\n\n", "meta": {"hexsha": "99d53c548d384d04e0e2df507bfd214c41b75280", "size": 593, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "mccall/mccall_resw_beta.jl", "max_stars_repo_name": "mwhchen/quantecon", "max_stars_repo_head_hexsha": "1a401e3453cbccbcf609945fced1b478b945446e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-05-02T22:12:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T01:07:33.000Z", "max_issues_repo_path": "mccall/mccall_resw_beta.jl", "max_issues_repo_name": "mwhchen/quantecon", "max_issues_repo_head_hexsha": "1a401e3453cbccbcf609945fced1b478b945446e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mccall/mccall_resw_beta.jl", "max_forks_repo_name": "mwhchen/quantecon", "max_forks_repo_head_hexsha": "1a401e3453cbccbcf609945fced1b478b945446e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-11-11T22:38:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T20:33:03.000Z", "avg_line_length": 17.4411764706, "max_line_length": 50, "alphanum_fraction": 0.6897133221, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7963097387283656}}
{"text": "# # SVM with L^1 regularization\n## Generate data for SVM classifier with L1 regularization.\nusing Random\nRandom.seed!(3);\nn = 20;\nm = 1000;\nTEST = m;\nDENSITY = 0.2;\nbeta_true = randn(n, 1);\nidxs = randperm(n)[1:round(Int, (1 - DENSITY) * n)];\nbeta_true[idxs] .= 0\noffset = 0;\nsigma = 45;\nX = 5 * randn(m, n);\nY = sign.(X * beta_true .+ offset .+ sigma * randn(m, 1));\nX_test = 5 * randn(TEST, n);\n\n#-\n\n## Form SVM with L1 regularization problem.\nusing Convex, SCS, ECOS\n\nbeta = Variable(n);\nv = Variable();\nloss = sum(pos(1 - Y .* (X * beta - v)));\nreg = norm(beta, 1);\n\n## Compute a trade-off curve and record train and test error.\nTRIALS = 100\ntrain_error = zeros(TRIALS);\ntest_error = zeros(TRIALS);\nlambda_vals = exp10.(range(-2, stop = 0, length = TRIALS);)\nbeta_vals = zeros(length(beta), TRIALS);\nfor i in 1:TRIALS\n    lambda = lambda_vals[i]\n    problem = minimize(loss / m + lambda * reg)\n    solve!(problem, SCS.Optimizer; silent_solver = true)\n    train_error[i] =\n        sum(\n            float(\n                sign.(X * beta_true .+ offset) .!=\n                sign.(evaluate(X * beta - v)),\n            ),\n        ) / m\n    test_error[i] =\n        sum(\n            float(\n                sign.(X_test * beta_true .+ offset) .!=\n                sign.(evaluate(X_test * beta - v)),\n            ),\n        ) / TEST\n    beta_vals[:, i] = evaluate(beta)\nend\n\n#-\n\n# Plot the train and test error over the trade-off curve.\nusing Plots\nplot(lambda_vals, train_error, label = \"Train error\");\nplot!(lambda_vals, test_error, label = \"Test error\");\nplot!(xscale = :log, yscale = :log, ylabel = \"errors\", xlabel = \"lambda\")\n\n#-\n\n# Plot the regularization path for beta.\n\nplot()\nfor i in 1:n\n    plot!(lambda_vals, vec(beta_vals[i, :]), label = \"beta$i\")\nend\nplot!(xscale = :log, ylabel = \"betas\", xlabel = \"lambda\")\n", "meta": {"hexsha": "9b34749ebc221c510dee0dbe3871b3febb17ed40", "size": 1818, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/general_examples/svm_l1regularization.jl", "max_stars_repo_name": "baggepinnen/Convex.jl", "max_stars_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 327, "max_stars_repo_stars_event_min_datetime": "2015-01-22T01:00:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T16:42:11.000Z", "max_issues_repo_path": "docs/examples_literate/general_examples/svm_l1regularization.jl", "max_issues_repo_name": "baggepinnen/Convex.jl", "max_issues_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 275, "max_issues_repo_issues_event_min_datetime": "2015-01-12T19:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-05T19:05:45.000Z", "max_forks_repo_path": "docs/examples_literate/general_examples/svm_l1regularization.jl", "max_forks_repo_name": "baggepinnen/Convex.jl", "max_forks_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 121, "max_forks_repo_forks_event_min_datetime": "2015-01-23T21:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T13:58:39.000Z", "avg_line_length": 25.25, "max_line_length": 73, "alphanum_fraction": 0.5929592959, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.8596637487122112, "lm_q1q2_score": 0.7963097319837502}}
{"text": "using LinearAlgebraicRepresentation\nLar = LinearAlgebraicRepresentation\nusing ViewerGL\nGL = ViewerGL\n\nV,(VV,EV,FV) = Lar.simplex(2, true)\ntriangle = (V,EV,FV)\nmodel = Lar.Struct([ triangle, Lar.t(.15,.15), Lar.s(.5,.5), triangle ])\nV,EV,FV = Lar.struct2lar(model)\nVV = [[k] for k=1:size(V,2)]\nGL.VIEW(GL.numbering(.4)((V,[VV, EV, FV]),GL.COLORS[1],0.2));\n\ntriangles = Lar.triangulate2d(V, EV)\nGL.VIEW([ GL.GLGrid(V,triangles) ])\n\n# generate edges\nev = map(sort,cat([[[u,v], [v,w], [w,u]] for (u,v,w) in triangles]))\n# remove duplicated edges from triangulation\nnodupev = collect(Set(ev))\nGL.VIEW(GL.numbering(.4)((V,[VV, nodupev])));\n", "meta": {"hexsha": "1b78e039ffb8198aa206e62e49c4aedcb0e6eb4c", "size": 634, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/2d/triangle.jl", "max_stars_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_stars_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-25T16:45:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-25T16:45:01.000Z", "max_issues_repo_path": "examples/2d/triangle.jl", "max_issues_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_issues_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/2d/triangle.jl", "max_forks_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_forks_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1904761905, "max_line_length": 72, "alphanum_fraction": 0.6719242902, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542283, "lm_q2_score": 0.8479677622198947, "lm_q1q2_score": 0.7962627788917879}}
{"text": "\n\"\"\"\n    random_unit_vector(N)\n\nGenerates N random unit vectors, i.e. random points on a unit sphere.\n\"\"\"\nfunction random_unit_vector(N::Int64)\n    phis = 2 * pi * rand(Float64, N)\n    cts = 2 * rand(Float64, N) .- 1\n    sts = sqrt.(1. .- cts .* cts) # sin(acos(cts)) # max(0., )\n\n    [SVector{3, Float64}(\n        sts[i] .* cos.(phis[i]),\n        sts[i] .* sin.(phis[i]),\n        cts[i]\n    ) for i in 1:N]\nend\n", "meta": {"hexsha": "045ec2cb6ad818b7111a6286f802407aeaeb7378", "size": 412, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/extras/point_generator.jl", "max_stars_repo_name": "ffreyer/SphereSurfaceHistogram.jl", "max_stars_repo_head_hexsha": "58b9aaee993bf12fde3e044c2568bda9d79e726b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-09T08:18:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T00:54:26.000Z", "max_issues_repo_path": "src/extras/point_generator.jl", "max_issues_repo_name": "ffreyer/SphereSurfaceHistogram.jl", "max_issues_repo_head_hexsha": "58b9aaee993bf12fde3e044c2568bda9d79e726b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-08-20T22:04:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T14:18:09.000Z", "max_forks_repo_path": "src/extras/point_generator.jl", "max_forks_repo_name": "ffreyer/SphereSurfaceHistogram.jl", "max_forks_repo_head_hexsha": "58b9aaee993bf12fde3e044c2568bda9d79e726b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8888888889, "max_line_length": 69, "alphanum_fraction": 0.5412621359, "num_tokens": 143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9390248225478306, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7962627738370196}}
{"text": "# # Worst case risk analysis\n# Generate data for worst-case risk analysis.\nusing Random\n\nRandom.seed!(2);\nn = 5;\nr = abs.(randn(n, 1)) / 15;\nSigma = 0.9 * rand(n, n) .- 0.15;\nSigma_nom = Sigma' * Sigma;\nSigma_nom .-= (maximum(Sigma_nom) - 0.9)\n\n#-\n\n# Form and solve portfolio optimization problem.\n# Here we minimize risk while requiring a 0.1 return.\nusing Convex, SCS\nw = Variable(n);\nret = dot(r, w);\nrisk = sum(quadform(w, Sigma_nom));\nproblem = minimize(risk, [sum(w) == 1, ret >= 0.1, norm(w, 1) <= 2])\nsolve!(problem, SCS.Optimizer; silent_solver = true)\nwval = vec(evaluate(w))\n\n#-\n\n# Form and solve worst-case risk analysis problem.\nSigma = Semidefinite(n);\nDelta = Variable(n, n);\nrisk = sum(quadform(wval, Sigma));\nproblem = maximize(\n    risk,\n    [\n        Sigma == Sigma_nom + Delta,\n        diag(Delta) == 0,\n        abs(Delta) <= 0.2,\n        Delta == Delta',\n    ],\n);\nsolve!(problem, SCS.Optimizer; silent_solver = true)\nprintln(\n    \"standard deviation = \",\n    round(sqrt(wval' * Sigma_nom * wval), sigdigits = 2),\n);\nprintln(\n    \"worst-case standard deviation = \",\n    round(sqrt(evaluate(risk)), sigdigits = 2),\n);\nprintln(\"worst-case Delta = \");\nprintln(round.(evaluate(Delta), sigdigits = 2));\n", "meta": {"hexsha": "80dd8a94532a03cb125d32ae6a82c03c0b6db0cb", "size": 1219, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/general_examples/worst_case_analysis.jl", "max_stars_repo_name": "baggepinnen/Convex.jl", "max_stars_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 327, "max_stars_repo_stars_event_min_datetime": "2015-01-22T01:00:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T16:42:11.000Z", "max_issues_repo_path": "docs/examples_literate/general_examples/worst_case_analysis.jl", "max_issues_repo_name": "baggepinnen/Convex.jl", "max_issues_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 275, "max_issues_repo_issues_event_min_datetime": "2015-01-12T19:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-05T19:05:45.000Z", "max_forks_repo_path": "docs/examples_literate/general_examples/worst_case_analysis.jl", "max_forks_repo_name": "baggepinnen/Convex.jl", "max_forks_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 121, "max_forks_repo_forks_event_min_datetime": "2015-01-23T21:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T13:58:39.000Z", "avg_line_length": 24.38, "max_line_length": 68, "alphanum_fraction": 0.6341263331, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.796233768892611}}
{"text": "# TSP & Simulated Annealing\n\n# Import Packages and Files\n\nusing Plots\nusing Distances\n\ninclude(\"sumLen.jl\")\ninclude(\"plotPath.jl\")\n\n# Constants\n\nn = 20                              # Number of Cities\ntemperature = Float64(100 * n)      # Starting Temperature\niter = 100                          # Iteration Times\n\n# Randomizing Coordinates\n\ncity = rand(n, 2) * 100 .+ 1\n\n# Interation Notes\n\nl = 1                               # Interation Times\nlen = []                            # Sum of Distance\n\nplot()\nplotPath(city)                      # Plot the Path\n\n# Iteration\n\nwhile true\n\n    global n, temperature, iter, city, cityNew, l, len\n\n    for ii = 1: iter\n\n        len1 = sumLen(city)         # Sum of Distance before Exchange\n\n        cityNew = copy(city)        # Exchange Coordinates\n\n        while true\n\n            p =  Int64.(floor.(n * rand(2, 1) .+ 1))\n\n            if p[1] != p[2]\n\n                cityNew[p[1], :] = city[p[2], :]\n                cityNew[p[2], :] = city[p[1], :]\n\n                break\n\n            end\n\n        end\n\n        len2 = sumLen(cityNew)      # Sum of Distance after Exchange\n\n        deltaE = len2 - len1        # Energy difference\n\n        if (deltaE < 0) || (exp(- deltaE / temperature) > rand())\n\n            city = cityNew          # Accept\n\n        end\n\n    end\n\n    len = [len; sumLen(city)]       # New Length\n    l += 1\n    temperature *= 0.99             # Lower Temperature\n\n    if temperature < 0.001\n\n        break                       # Stop\n\n    end\n\nend\n\n# Output\n\nplotPath(city)                      # Plot Result\nprintln(\"min = $(len[end])\")\n", "meta": {"hexsha": "11c6e669da73e3eaaebba4a8cc8ad1d1926d684f", "size": 1604, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SA/sa.jl", "max_stars_repo_name": "mizu-bai/Try-Julia", "max_stars_repo_head_hexsha": "c8fd95a3e261418654dc1fd13b18dd83cf94cf28", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-08-16T02:30:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-27T12:02:16.000Z", "max_issues_repo_path": "SA/sa.jl", "max_issues_repo_name": "mizu-bai/Data-Science-Demos", "max_issues_repo_head_hexsha": "be9dd44c7a2d3433faa049e1217969d08dbac432", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SA/sa.jl", "max_forks_repo_name": "mizu-bai/Data-Science-Demos", "max_forks_repo_head_hexsha": "be9dd44c7a2d3433faa049e1217969d08dbac432", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0952380952, "max_line_length": 69, "alphanum_fraction": 0.4831670823, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.796233768892611}}
{"text": "## Configuration\nn = 5\nadj = Float64[0 0 1 1 0;\n              0 0 1 0 0;\n              0 1 0 0 0;\n              1 0 1 0 1;\n              0 1 1 0 0]\nadj ./= sum(adj,2)\n\n## Graph algorithm\npageRank = ones(Float64,n)\nN = 30\nfor t = 1:N\n  temp = zeros(pageRank)\n  for j = 1:n\n    temp[j] = 0.15 + 0.85 * vecdot(pageRank,adj[:,j])\n  end\n  pageRank = temp\nend\npageRank\n\n## Markov Chain algorithm\ncomAdj = [0.85*adj 0.15*ones(n); ones(n)'/n 0.0]\ncomPageRank = eigvecs(comAdj')[:,1]\ncomPageRank = comPageRank / sum(comPageRank) * 1.15n\n\n", "meta": {"hexsha": "c4c61ad980faf0cc573e89fb199cb59bdfebc9e9", "size": 529, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PageRank.jl", "max_stars_repo_name": "WenjieZ/PageRank", "max_stars_repo_head_hexsha": "6366acc9ea0f4b02c46209bb4ca24d88b4374f8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PageRank.jl", "max_issues_repo_name": "WenjieZ/PageRank", "max_issues_repo_head_hexsha": "6366acc9ea0f4b02c46209bb4ca24d88b4374f8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PageRank.jl", "max_forks_repo_name": "WenjieZ/PageRank", "max_forks_repo_head_hexsha": "6366acc9ea0f4b02c46209bb4ca24d88b4374f8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5925925926, "max_line_length": 53, "alphanum_fraction": 0.5557655955, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9711290897113961, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7962222668292521}}
{"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENCE in the project root.\n# ------------------------------------------------------------------\n\n# -------------\n# COMPOSITIONS\n# -------------\n\n\"\"\"\n    alr(c)\n\nAdditive log-ratio transformation of composition `c`.\n\"\"\"\nfunction alr(c::Composition{D}) where {D}\n  w = components(c) .+ eps()\n  SVector(ntuple(i -> log(w[i] / w[D]), D-1))\nend\n\n\"\"\"\n    alrinv(x)\n\nInverse alr transformation of coordinates `x`.\n\"\"\"\nalrinv(x::SVector{D,T}) where {D,T<:Real} =\n  Composition(𝒞([exp.(x); SVector(one(T))]))\n\nalrinv(x::AbstractVector) = alrinv(SVector{length(x)}(x))\n\n# -------\n# TABLES\n# -------\n\n\"\"\"\n    ALR([refvar])\n\nAdditive log-ratio transform following the\n[TableTransforms.jl](https://github.com/JuliaML/TableTransforms.jl)\ninterface.\n\nOptionally, specify the reference variable `refvar` for the ratios.\nDefault to the last column of the input table.\n\"\"\"\nstruct ALR <: LogRatio\n  refvar::Union{Symbol,Nothing}\nend\n\nALR() = ALR(nothing)\n\nrefvar(transform::ALR, vars) =\n  isnothing(transform.refvar) ? last(vars) : transform.refvar\n\nnewvars(::ALR, n) = collect(n)[begin:end-1]\n\noldvars(::ALR, vars, rvar) = [collect(vars); rvar]\n\nfunction applymatrix(::ALR, X)\n  L = log.(X .+ eps())\n  L[:,begin:end-1] .- L[:,end]\nend\n\nfunction revertmatrix(::ALR, Y)\n  E = [exp.(Y) ones(size(Y,1))]\n  mapslices(𝒞, E, dims=2)\nend", "meta": {"hexsha": "ac03294006d1bf05a2e5b97b962b1789f9ebabaf", "size": 1420, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transforms/alr.jl", "max_stars_repo_name": "OkonSamuel/CoDa.jl", "max_stars_repo_head_hexsha": "cae693f6662085280c09a2b4b9a05e7093851e8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-12-21T01:16:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-08T13:42:09.000Z", "max_issues_repo_path": "src/transforms/alr.jl", "max_issues_repo_name": "OkonSamuel/CoDa.jl", "max_issues_repo_head_hexsha": "cae693f6662085280c09a2b4b9a05e7093851e8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/transforms/alr.jl", "max_forks_repo_name": "OkonSamuel/CoDa.jl", "max_forks_repo_head_hexsha": "cae693f6662085280c09a2b4b9a05e7093851e8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:31:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-08T21:48:36.000Z", "avg_line_length": 22.1875, "max_line_length": 68, "alphanum_fraction": 0.5809859155, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7961997633801878}}
{"text": "#=\nHackerRank - Binomial distribution\nhttps://www.hackerrank.com/challenges/s10-binomial-distribution-1/problem\nhttps://www.hackerrank.com/challenges/s10-binomial-distribution-2/problem\n=#\nusing Printf\n\nfunction comb(n::Int, r::Int)\n    r == 0 ? 1.0 : reduce(*, n-r+1:n, init=1) / reduce(*, 1:r, init=1)\nend\n\nfunction binomial(p::Float64, n::Int64, r::Int64)\n    comb(n, r) * p ^ r * (1 - p) ^ (n - r)\nend\n\n# Binomial Problem 1\n# What is the probability of having at least three boys out of six kids.\nlet ratio = 1.09    # Ratio of a boy or an event\n    local p = ratio / (1.0 + ratio)\n    # at least 3 out of 6\n    local n = 6\n    local c = 3\n    local result = mapreduce(c -> binomial(p, n, c), +, c:n)\n    @printf(\"%.3f\", result)\nend\n\n## Binomial Problem 2\n## What are the probabilities of:\n##  No more than two rejected, and\n##  At least two rejected.\nlet defect_ratio = 0.12, n = 10\n    # No more than two rejected\n    local result1 = mapreduce(x -> binomial(defect_ratio, n, x), +, 0:2)\n    @printf(\"%.3f\\n\", result1)\n    local result2 = 1.0 - mapreduce(x -> binomial(defect_ratio, n, x), +, 0:1)\n    @printf(\"%.3f\\n\", result2)\nend\n", "meta": {"hexsha": "ba51a72f28690d94c51a797cfb936a0f30de8446", "size": 1138, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "hackerrank_binomial.jl", "max_stars_repo_name": "eric-nam/julia_practices", "max_stars_repo_head_hexsha": "8baaff9533fd229dfd1ee298065c89d408e8c2b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hackerrank_binomial.jl", "max_issues_repo_name": "eric-nam/julia_practices", "max_issues_repo_head_hexsha": "8baaff9533fd229dfd1ee298065c89d408e8c2b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hackerrank_binomial.jl", "max_forks_repo_name": "eric-nam/julia_practices", "max_forks_repo_head_hexsha": "8baaff9533fd229dfd1ee298065c89d408e8c2b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9473684211, "max_line_length": 78, "alphanum_fraction": 0.6370826011, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551957, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.796197570270267}}
{"text": "import FractionalDiffEq.solve, FractionalDiffEq.FractionalDiffEqAlgorithm\n\nusing LinearAlgebra, InvertedIndices\n\n\"\"\"\nUsing [triangular strip matrices](https://en.wikipedia.org/wiki/Triangular_matrix) to discrete fractional differential equations to simple algebra system and solve the system.\n\n```tex\n@inproceedings{Podlubny2000MATRIXAT,\n  title={MATRIX APPROACH TO DISCRETE FRACTIONAL CALCULUS},\n  author={Igor Podlubny},\n  year={2000}\n}\n```\n\"\"\"\nstruct MatrixDiscrete <: FractionalDiffEqAlgorithm end\n\n\n\"\"\"\n@inproceedings{Podlubny1998FractionalDE,\n  title={Fractional differential equations},\n  author={Igor Podlubny},\n  year={1998}\n}\n\"\"\"\n\n\"\"\"\n@inproceedings{Podlubny2000MATRIXAT,\n  title={MATRIX APPROACH TO DISCRETE FRACTIONAL CALCULUS},\n  author={Igor Podlubny},\n  year={2000}\n}\n\"\"\"\n\n\"\"\"\n    solve(p1, α, p2, c, h, T, MatrixDiscrete())\n\nUsing the **Matrix Discretization algorithm** proposed by [Prof Igor Podlubny](http://people.tuke.sk/igor.podlubny/index.html) to approximate the numerical solution.\n\"\"\"\nfunction solve(p1, α, p2, c, h, T, ::MatrixDiscrete)\n    n=Int64(floor(α))\n    rows=collect(1:n)\n    N=Int64(T/h+1)\n    equation = p1*B(N, α, h)+p2*(zeros(N, N)+I)\n    equation = eliminator(N, rows)*equation*eliminator(N, rows)'\n    righthand = c*eliminator(N, rows)*ones(N)\n    result = equation\\righthand\n    return vcat(zeros(n), result)\nend\n\n\nfunction solve(equation, right, h, T)\n    N=Int64(T/h+1)\n    equation = eliminator(N, rows)*equation*eliminator(N, rows)'\n    right = right*eliminator(N, rows)*ones(N)\n    result = equation\\right\n    return vcat(zeros(n), result)\nend\n\n\"\"\"\n    eliminator(n, row)\n\nCompute the eliminator matrix Sₖ by omiting n-th row\n\"\"\"\nfunction eliminator(n, row)\n    temp = zeros(n, n)+I\n    return temp[Not(row), :]\nend\n\n\"\"\"\nGenerating elements in Matrix.\n\"\"\"\nfunction omega(n, p)\n    omega = zeros(n+1)\n\n    omega[1]=1\n    for i in range(1, n, step=1)\n        omega[i+1]=(1-(p+1)/i)*omega[i]\n    end\n    \n    return omega\n\nend\n\nfunction B(N, p, h)\n    result=zeros(N, N)\n    temp=omega(N, p)\n\n    for i in range(1, N, step=1)\n        result[i, 1:i]=reverse(temp[1:i])\n    end\n\n    return h^(-p)*result\nend\n\nfunction F(N, p, h)\n    result=zeros(N, N)\n    temp = omega(N, p)\n\n    for i in range(1, N, step=1)\n        result[i, 1:i]=reverse(temp[1:i])\n    end\n\n    result=reverse(reverse(result, dims=1), dims=2)\n\n    return (-1)^(ceil(p))*h^(-p)*result\nend\n\n\"\"\"\n    bagleytorvik(p1, p2, p3, T, h)\n\nBy specifying the parameters of Bagley Torvik Equation, we can use **bagleytorvik** to directly obtain the numerical approximation.\n\n!!! info p2 ≠ 0\n    Please note that the parameter of fractional derivative item must not be 0\n\"\"\"\nfunction bagleytorvik(p1, p2, p3, T, h)\n    N=Int64(T/h+1)\n    equation = p1*B(N, 2, h)+p2*B(N, 1.5, h)+p3*(zeros(N, N)+I)\n    equation = eliminator(N, [1,2])*equation*eliminator(N, [1,2])'\n    right = eliminator(N, [1,2])*ones(N)\n    result = equation\\right\n\n    return vcat(zeros(2), result)\nend", "meta": {"hexsha": "44a64fd9ab9992383a851a64b9236a2de95c8d05", "size": 2970, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix.jl", "max_stars_repo_name": "ERIKQQY6/FractionalDiffEq.jl", "max_stars_repo_head_hexsha": "7638f3b9d31e8e1aaaca0b4328b70e4d45b169c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matrix.jl", "max_issues_repo_name": "ERIKQQY6/FractionalDiffEq.jl", "max_issues_repo_head_hexsha": "7638f3b9d31e8e1aaaca0b4328b70e4d45b169c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix.jl", "max_forks_repo_name": "ERIKQQY6/FractionalDiffEq.jl", "max_forks_repo_head_hexsha": "7638f3b9d31e8e1aaaca0b4328b70e4d45b169c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.76, "max_line_length": 175, "alphanum_fraction": 0.6646464646, "num_tokens": 947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.796197560091849}}
{"text": "module MadelungConstant\n\nimport Plots\n\n\nfunction Madelung(m)\n\tmadelung = 0\n\tfor i = -m:m\n\t\tfor j = -m:m\n\t\t\tfor k = -m:m\n\t\t\t\tif i == 0 && j == 0 && k == 0\n\t\t\t\t\tcontinue\n\t\t\t\tend\n\t\t\t\tmadelung += ( (i + j + k) % 2 == 0 ? -1 : 1) / √(i^2 + j^2 + k^2)\n\t\t\tend\n\t\tend\n\tend\n\tmadelung\nend\n\nfunction Madelung2(m)\n\tmadelung = 0\n\tfor i = -m:m\n\t\tfor j = -m:m\n\t\t\tfor k = -m:m\n\t\t\t\tif i == 0 && j == 0 && k == 0\n\t\t\t\t\tcontinue\n\t\t\t\tend\n\t\t\t\tr = √(i^2 + j^2 + k^2)\n\t\t\t\tif r > m\n\t\t\t\t\tcontinue\n\t\t\t\tend\n\t\t\t\tmadelung += ((i + j + k) % 2 == 0 ? -1 : 1) / r\n\t\t\tend\n\t\tend\n\tend\n\tmadelung\nend\n\nfunction plot(range=1:50)\n    Plots.plot([Madelung, Madelung2], range, show=true)\nend\n\nend # module\n", "meta": {"hexsha": "1e8153eba6876d1038e69b85db0b70f328cfb706", "size": 663, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MadelungConstant.jl", "max_stars_repo_name": "YIsoda/MadelungConstant", "max_stars_repo_head_hexsha": "912d1ede4bfcd7b16e6a19119f089d82aac73f89", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MadelungConstant.jl", "max_issues_repo_name": "YIsoda/MadelungConstant", "max_issues_repo_head_hexsha": "912d1ede4bfcd7b16e6a19119f089d82aac73f89", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MadelungConstant.jl", "max_forks_repo_name": "YIsoda/MadelungConstant", "max_forks_repo_head_hexsha": "912d1ede4bfcd7b16e6a19119f089d82aac73f89", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.7333333333, "max_line_length": 69, "alphanum_fraction": 0.4977375566, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7961834975301889}}
{"text": "\"\"\"\n    Hermite( nodes::NodesType, epsilon:Real, gamma:Real )\n\nHermite interpolation\n\n\"\"\"\nmutable struct Hermite <: InterpolationType\n\n    nnodes     :: Int64\n    epsilon    :: Float64\n    gamma      :: Float64\n    nodes      :: Array{Float64,1}\n    colloc_mat :: Array{Float64,2}\n    \n    function Hermite( nodes_t::NodesType, epsilon::Float64, gamma::Float64 )\n\n        nodes  = nodes_t.xk\n        nnodes = nodes_t.nx\n        colloc_mat = evaluate_hermite(nodes, nnodes, epsilon, gamma)\n        new( nnodes, epsilon, gamma, nodes, colloc_mat )\n\n    end\n\nend\n\n\"\"\"\n    Hermite( xe )\n\nThis function returns the matrix He of the values of the HermiteGF basis\nfunctions. The computation is done via three term recurrence for Hermite\nfunctions with an argument gamma*x and then appropriate exponential scaling.\n\nMore details can be found in Section 5.1 of the paper\n\n*STABLE EVALUATION OF GAUSSIAN RADIAL BASIS\n FUNCTIONS USING HERMITE POLYNOMIALS*\n by Anna Yurova and Katharina Kormann.\n\n\n\"\"\"\nfunction (interp::Hermite)( x::Array{Float64,1} )\n\n   nx      = interp.nnodes\n   epsilon = interp.epsilon\n   gamma   = interp.gamma\n\n   evaluate_hermite(x, nx, epsilon, gamma) / interp.colloc_mat\n\nend\n\n\n\"\"\"\n\n    evaluate_hermite(xk, n, epsilon, gamma)\n\nThis function returns the matrix He of the values of the HermiteGF basis\nfunctions. The computation is done via three term recurrence for Hermite\nfunctions with an argument gamma*x and then appropriate exponential scaling.\n\nMore details can be found in Section 5.1 of the paper\n\n*STABLE EVALUATION OF GAUSSIAN RADIAL BASIS\n FUNCTIONS USING HERMITE POLYNOMIALS*\n by Anna Yurova and Katharina Kormann.\n\nThis function should be used both for computation of the\ncollocation and evaluation matrices.\n\n\"\"\"\nfunction evaluate_hermite(xk, n, epsilon, gamma)\n\n  # Initialize the result matrix\n  result = zeros(Int(length(xk)), n)\n\n  # Write the values of the first two Hermite functions to initialize the\n  # three-term recurrence\n  result[:,1] = exp.(-0.5.*((gamma*xk).^2))\n  result[:,2] = gamma*xk.*sqrt(2).*exp.(-0.5.*((gamma*xk).^2))\n\n  # Three term recurrence for the Hermite functions with argument gamma*x\n  for i = 3:n\n    result[:,i] = sqrt(2.0/(i-1)) .* (gamma*xk) .* result[:,i-1] - sqrt((i-2)/(i-1)) .* result[:,i-2]\n  end\n\n  # Scaling the Hermite functions with the exponential factor\n  # exp(-epsilon^2 x^2 + (gamma x)^2/2)\n  \n  for i=1:n\n      result[:,i] = (pi^(1/4)) * result[:,i] .* exp.((xk.^2) .* (gamma*gamma*0.5 - epsilon^2))\n  end\n\n  result\n\nend\n", "meta": {"hexsha": "069c443cf4b36f8cc106bcf418f40e147e1c204c", "size": 2502, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hermite.jl", "max_stars_repo_name": "JuliaVlasov/HermiteGF.jl", "max_stars_repo_head_hexsha": "e2591e78b08c1982e4d14101cba25c3e5de7f223", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-10-26T19:46:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T06:20:24.000Z", "max_issues_repo_path": "src/hermite.jl", "max_issues_repo_name": "JuliaVlasov/HermiteGF.jl", "max_issues_repo_head_hexsha": "e2591e78b08c1982e4d14101cba25c3e5de7f223", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hermite.jl", "max_forks_repo_name": "JuliaVlasov/HermiteGF.jl", "max_forks_repo_head_hexsha": "e2591e78b08c1982e4d14101cba25c3e5de7f223", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3368421053, "max_line_length": 101, "alphanum_fraction": 0.6898481215, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874229, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7961621314049192}}
{"text": "\n\"\"\"\n    PODsvd(X)\n\nUses the SVD based decomposition technique to calculate the POD basis of X. \n\"\"\"\nfunction PODsvd(X; subtractmean::Bool = false)\n\n    Xcop = deepcopy(X)\n    PODsvd!(Xcop, subtractmean = subtractmean)\n\nend\n\n\"\"\"\n    PODsvd(X,W)\n\nSame as `PODsvd(X)` but uses weights for each data point. The weights are equal to the\ncell volume for a volume mesh.\n\"\"\"\nfunction PODsvd(X,W::AbstractVector; subtractmean::Bool = false)\n\n    Xcop = deepcopy(X)\n    PODsvd!(Xcop, W, subtractmean = subtractmean)\n\nend\n\n\"\"\"\n    PODsvd!(X)\n\nSame as `PODsvd(X)` but overwrites memory.\n\"\"\"\nfunction PODsvd!(X; subtractmean::Bool = false)\n\n    if subtractmean\n        X .-= mean(X,dims=2)\n    end\n\n    # Economy sized SVD\n    F = svd!(X)\n\n    # Mode coefficients\n    a = Diagonal(F.S)*F.Vt\n\n    POD = PODBasis(a, F.U)\n\n    return POD, F.S\n\nend\n\n\"\"\"\n    PODsvd!(X,W)\n\nSame as `PODsvd!(X)` but uses weights for each data point. The weights are equal to the\ncell volume for a volume mesh.\n\"\"\"\nfunction PODsvd!(X,W::AbstractVector; subtractmean::Bool = false)\n\n    if subtractmean\n        X .-= mean(X,dims=2)\n    end\n\n    # Take into account the weights\n    X = sqrt.(W).*X\n\n    # Economy sized SVD\n    F = svd!(X)\n\n    # Mode coefficients\n    a = Diagonal(F.S)*F.Vt\n    Φ = 1 ./sqrt.(W).*F.U\n    \n    POD = PODBasis(a, Φ)\n\n    return POD, F.S\n\nend\n", "meta": {"hexsha": "5ccf31ae43f3ef609cea91317ab2a53270075ad7", "size": 1335, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PODsvd.jl", "max_stars_repo_name": "JuliaDocsForks/ProperOrthogonalDecomposition.jl", "max_stars_repo_head_hexsha": "6b889e1310ca904f43c9940e409d70a266cdd1ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-19T09:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-08T12:23:43.000Z", "max_issues_repo_path": "src/PODsvd.jl", "max_issues_repo_name": "JuliaDocsForks/ProperOrthogonalDecomposition.jl", "max_issues_repo_head_hexsha": "6b889e1310ca904f43c9940e409d70a266cdd1ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-10-17T07:09:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-05T11:00:50.000Z", "max_forks_repo_path": "src/PODsvd.jl", "max_forks_repo_name": "JuliaDocsForks/ProperOrthogonalDecomposition.jl", "max_forks_repo_head_hexsha": "6b889e1310ca904f43c9940e409d70a266cdd1ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-10-17T02:57:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-18T21:53:00.000Z", "avg_line_length": 17.3376623377, "max_line_length": 87, "alphanum_fraction": 0.6224719101, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.7961454103731701}}
{"text": "using LabelledArrays\n\nexport ar1_bidir\n\n\"\"\"\n    eom_ar1_bidir(x, p, n) → SVector{2}\n\nEquations of motion for a system consisting of two mutually \ncoupled first order autoregressive processes. \n\n## Equations of motion \n\n```math\n\\\\begin{aligned}\nx(t+1) &= a_{1}x + c_{yx}y + \\\\epsilon_{x} \\\\\\\\\ny(t+1) &= b_{1}y + c_{xy}x + \\\\epsilon_{y}\n\\\\end{aligned}\n```\n    \nwhere ``\\\\epsilon_{x}`` and ``\\\\epsilon_{y}`` are drawn independently \nat each time step from normal distributions with zero mean and standard \ndeviations `σx` and `σy`.\n\"\"\"\nfunction eom_ar1_bidir(x, p, n)\n    a₁, b₁, c_xy, c_yx, σx, σy = (p...,)\n    x, y = (x...,)\n\n    ϵx = rand(Normal(0, σx))\n    ϵy = rand(Normal(0, σy))\n\n    dx = a₁*x + c_yx*y + ϵx\n    dy = b₁*y + c_xy*x + ϵy\n    return SVector{2}(dx, dy)\nend\n\nfunction ar1_bidir(u₀,a₁, b₁, c_xy, c_yx, σx, σy)\n    p = @LArray [a₁, b₁, c_xy, c_yx, σx, σy] (:a₁, :b₁, :c_xy, :c_yx, :σx, :σy)\n    logistic_system = DiscreteDynamicalSystem(eom_ar1_bidir, u₀, p)\n\n    return logistic_system\nend\n\n\"\"\"\n    ar1_bidir(;u₀ = rand(2), a₁ = 0.5, b₁ = 0.7, c_xy = 0, c_yx = 0.2, \n        σx = 0.3, σy = 0.3) → DiscreteDynamicalSystem\n\nA system consisting of two mutually coupled first order autoregressive processes. \n\n## Equations of motion \n\n```math\n\\\\begin{aligned}\nx(t+1) &= a_{1}x + c_{yx}y + \\\\epsilon_{x} \\\\\\\\\ny(t+1) &= b_{1}y + c_{xy}x + \\\\epsilon_{y}\n\\\\end{aligned}\n```\n\nwhere ``\\\\epsilon_{x}`` and ``\\\\epsilon_{y}`` are drawn independently \nat each time step from normal distributions with zero mean and standard \ndeviations `σx` and `σy`.\n\"\"\"\nar1_bidir(;a₁ = 0.5, b₁ = 0.7, u₀ = rand(2), c_xy = 0, c_yx = 0.2, σx = 0.3, σy = 0.3) =\n    ar1_bidir(u₀, a₁, b₁, c_xy, c_yx, σx, σy)\n", "meta": {"hexsha": "c6833a8cb0b5c4c0a68bb6f88322d1ea82a7547c", "size": 1692, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/example_systems/discretemaps/ar1_bidir.jl", "max_stars_repo_name": "kahaaga/CausalityTools.jl", "max_stars_repo_head_hexsha": "e1de3943a2ccb3c9997ca38e7a4fac025f1f8475", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2018-11-07T11:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-05T06:26:37.000Z", "max_issues_repo_path": "src/example_systems/discretemaps/ar1_bidir.jl", "max_issues_repo_name": "kahaaga/CausalityTools.jl", "max_issues_repo_head_hexsha": "e1de3943a2ccb3c9997ca38e7a4fac025f1f8475", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2018-09-04T08:02:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-04T11:59:38.000Z", "max_forks_repo_path": "src/example_systems/discretemaps/ar1_bidir.jl", "max_forks_repo_name": "kahaaga/CausalityTools.jl", "max_forks_repo_head_hexsha": "e1de3943a2ccb3c9997ca38e7a4fac025f1f8475", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-12-03T10:59:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:02:55.000Z", "avg_line_length": 26.4375, "max_line_length": 88, "alphanum_fraction": 0.61643026, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8840392741081575, "lm_q1q2_score": 0.7961036937124276}}
{"text": "# Unit 02 - Nonlinear Classification, Linear regression, Collaborative Filtering\n\n# Lecture 5\n\n# Hinge loss computation\n\nx = [1 0 1; 1 1 1; 1 1 -1; -1 1 1]\ny = [2,2.7,-0.7, 2]\nθ = [0,1,2]\nz = y - (θ' * x')'\n\nhinge(z) = (z >= (1 - eps()) ) ? 0 : (1 - z)\nl = mean(map(z -> hinge(z), z))\n\nsquared_error(z) = z^2 / 2\nl = mean(map(z -> squared_error(z), z))\n\n# Lecture 6\n\n# radial basis kernel\nusing LinearAlgebra\nradial_kernel(x,xᵖ) = exp(-1/2 * norm(x-xᵖ)^2)\n\nx = [1,0,0]\n\nxᵖ = [0,1,0]\n\nk = radial_kernel(x,xᵖ)\n", "meta": {"hexsha": "ec133dbb4ff795e5df3bbfd7cfe03a207435ac27", "size": 508, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Unit 02 - Nonlinear Classification, Linear regression, Collaborative Filtering/Unit 02 - Nonlinear Classification, Linear regression, Collaborative Filtering.jl", "max_stars_repo_name": "fanyak/MITx_6.86x", "max_stars_repo_head_hexsha": "f6370c3c7f505644b242aa74531c645ece09d6ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-27T06:22:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T06:22:38.000Z", "max_issues_repo_path": "Unit 02 - Nonlinear Classification, Linear regression, Collaborative Filtering/Unit 02 - Nonlinear Classification, Linear regression, Collaborative Filtering.jl", "max_issues_repo_name": "fanyak/MITx_6.86x", "max_issues_repo_head_hexsha": "f6370c3c7f505644b242aa74531c645ece09d6ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Unit 02 - Nonlinear Classification, Linear regression, Collaborative Filtering/Unit 02 - Nonlinear Classification, Linear regression, Collaborative Filtering.jl", "max_forks_repo_name": "fanyak/MITx_6.86x", "max_forks_repo_head_hexsha": "f6370c3c7f505644b242aa74531c645ece09d6ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5172413793, "max_line_length": 80, "alphanum_fraction": 0.5748031496, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191309994468, "lm_q2_score": 0.8333246035907932, "lm_q1q2_score": 0.796090936142815}}
{"text": "module LossFunctions\n\nexport mse, cross_entropy\n\nusing Statistics\n\n\"\"\"\n    mse(x, y)\n\nComputes the mean-squared error between `x` and `y`, returning a scalar.\n\nFor the multi-sample case, takes the error along columns (dimensions), and\naverages along rows (count).\n\n- `x`: Either (1) a vector containing a single prediction, or (2) a matrix where\n  rows index predictions in a batch and columns indicate dimensions of the\n  prediction.\n- `y`: Either (1) a vector containing a single label, or (2) a matrix where rows\n  index labels in a batch and columns indicate dimensions of the label.\n\n`x` and `y` should have the same dimensionality.\n\"\"\"\nmse(x, y) = mean(sum((x .- y) .^2, dims=2), dims=1)[1]\n\n\n\"\"\"\n    cross_entropy(x, y)\n\nComputes the cross-entropy error between `x` and `y`, returning a scalar.\n\nFor the multi-sample case, takes the error along columns (dimensions), and\naverages along rows (count).\n\n- `x`: Either (1) a vector containing a single prediction, or (2) a matrix where\n  rows index predictions in a batch and columns indicate dimensions of the\n  prediction.\n- `y`: Either (1) a vector containing a single label, or (2) a matrix where rows\n  index labels in a batch and columns indicate dimensions of the label.\n\n`x` and `y` should have the same dimensionality.\n\"\"\"\ncross_entropy(x, y) = mean((-1) * sum(y .* log.(x), dims=2), dims=1)[1]\n\nend # module\n", "meta": {"hexsha": "f5b94c2825c9659a7967fa18a6db12e48f3355dd", "size": 1371, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/optimization/loss_functions.jl", "max_stars_repo_name": "brianxie/automaton-edification", "max_stars_repo_head_hexsha": "d432604a9eb1ac01b9f99567ece0f00f4145a4f1", "max_stars_repo_licenses": ["BSD-2-Clause-Patent"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/optimization/loss_functions.jl", "max_issues_repo_name": "brianxie/automaton-edification", "max_issues_repo_head_hexsha": "d432604a9eb1ac01b9f99567ece0f00f4145a4f1", "max_issues_repo_licenses": ["BSD-2-Clause-Patent"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimization/loss_functions.jl", "max_forks_repo_name": "brianxie/automaton-edification", "max_forks_repo_head_hexsha": "d432604a9eb1ac01b9f99567ece0f00f4145a4f1", "max_forks_repo_licenses": ["BSD-2-Clause-Patent"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4666666667, "max_line_length": 80, "alphanum_fraction": 0.7126185266, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7960909311283118}}
{"text": "# NEED:\n# A Julia JIT Compiler\n# USAGE:\n# type \"python pi.py [iterations]\" into terminal/prompt\n\n\n# needed variables to approximate pi\niterations = 10000\ntotal = 0.0\nin_circle = 0.0\nradius = 1.0\n\n# get user input, otherwise use default value\nif length(ARGS) > 0\n    iterations = parse(ARGS[1])\nelse\n    println(\"No iteration limit specified --> used default: \", iterations)\nend\n\n\n# initialize random 2 dimensional array and square each value for later calculation quadratic\npoints = (rand!(zeros(iterations,2)) .* radius) .^ 2\n\n# is point in circle/ out of circle\nfor i = 1:iterations\n    total += 1\n    distance = sqrt(points[i,1] + points[i,2])\n    if distance < radius\n        in_circle += 1\n    end\nend\n\n# pi approximation\npi = 4 * (in_circle / total)\n\n# user output\nprintln(\"Iterations: \", iterations)\nprintln(\"PI-Approximation: \", pi)\n", "meta": {"hexsha": "fa193788dca73d11a662b6bcc8e8fae32454b0b0", "size": 841, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/pi.jl", "max_stars_repo_name": "CitrusPunk/approximatePi", "max_stars_repo_head_hexsha": "cd16c2771bfdc87fd26fdc7068ee86077b5f77c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-03-18T09:12:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-18T09:12:04.000Z", "max_issues_repo_path": "Julia/pi.jl", "max_issues_repo_name": "CitrusPunk/approximatePi", "max_issues_repo_head_hexsha": "cd16c2771bfdc87fd26fdc7068ee86077b5f77c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/pi.jl", "max_forks_repo_name": "CitrusPunk/approximatePi", "max_forks_repo_head_hexsha": "cd16c2771bfdc87fd26fdc7068ee86077b5f77c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5641025641, "max_line_length": 93, "alphanum_fraction": 0.6896551724, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7960832119989263}}
{"text": "@doc raw\"\"\"\n```\nDiscreteShape(iterations::Int = 2000, smoothness::Int = 1000, albedo::Real = Inf, illumination_direction::Vector{T} where T <: Real = [Inf, Inf, Inf])\n```\nContins `DiscreteShape` algorithm which ttempts to produce a heightmap from a\ngrayscale image by minimization of a set of Euler-Lagrange equations. This is done\ndiscretely at each point in the image utilizing the second derivates of the\nsurface normals and their Fourier Transforms.\n# Output\nReturns a `DiscreteShape` functor which can be run on an image to attempt reconstruction\nof the surface contianed in the image.\n# Details\nThe algorithm attempts to minimise the brightness deviation ``ϵ`` through the\nbrightness constraint ``\\epsilon_1`` and smoothness constraint ``\\epsilon_2``\nas defined bellow:\n```math\n\\epsilon=\\iint((\\epsilon_1+\\lambda\\epsilon_2))dxdy=\\iint((E(x,y)-R(p,q))^2+\n\\lambda(p_x^2+q_x^2+p_y^2+q_y^2))\n```\nThis is minimised using the Euler-Lagrange equations defined as;\n```math\n\\dfrac{\\delta\\epsilon}{\\delta p}-\\dfrac{\\delta}{\\delta x}\\dfrac{\\delta\\epsilon}{\n\\delta p_x}-\\dfrac{\\delta}{\\delta y}\\dfrac{\\delta\\epsilon}{\\delta p_y}=0\n```\nand\n```math\n\\dfrac{\\delta\n\\epsilon}{\\delta q}-\\dfrac{\\delta}{\\delta x}\\dfrac{\\delta\\epsilon}{\\delta q_x}-\n\\dfrac{\\delta}{\\delta y}\\dfrac{\\delta\\epsilon}{\\delta q_y}=0\n```\nwhich become:\n```math\n\\begin{gathered}\n-2(E-R)\\dfrac{\\delta R}{\\delta p}-2\\lambda p_{xx}-2\\lambda p_{yy}=0\\\\\n-2(E-R)\\dfrac{\\delta R}{\\delta p}-2\\lambda q_{xx}-2\\lambda q_{yy}=0\n\\end{gathered}\n```\nwhich can be further simplified to give:\n```math\n\\begin{gathered}\n\\nabla^2p=\\dfrac{1}{\\lambda}(R-E)\\dfrac{\\delta R}{\\delta p}\\\\\n\\nabla^2q=\\dfrac{1}{\\lambda}(R-E)\\dfrac{\\delta R}{\\delta q}\n\\end{gathered}\n```\nwhere ``\\nabla^2p=p_{xx}+p_{yy}`` and ``\\nabla^2q=q_{xx}+q_{yy}`` are Laplacians\nof p and q.\n\nHowever, for computation we are dealing with a discreate case of these equations\nwhich can be defined as below:\n```math\n\\begin{gathered}\np_{i,j}=\\bar{p}_{i,j}+\\dfrac{1}{4\\lambda}(E-R)\\dfrac{\\delta R}{\\delta p}\\\\q_{i,j}=\n\\bar{q}_{i,j}+\\dfrac{1}{4\\lambda}(E-R)\\dfrac{\\delta R}{\\delta q}\\\\\n\\end{gathered}\n```\nwhere\n```math\n\\bar{p}_{i,j}=\\dfrac{p_{i+1,j}+p_{i-1,j}+p_{i,j+1}+p_{i,j-1}}{4}\n```\nand\n```math\n\\bar{q}_{i,j}=\\dfrac{q_{i+1,j}+q_{i-1,j}+q_{i,j+1}+q_{i,j-1}}{4}\n```\nFinally, the algorithm needs to enforce integrability on p and q and retrieve\nthe surface Z. This can be done by taking the Fast Fourier Transform of p and q\n()``c_p(\\omega_x,\\omega_y)`` and ``c_q(\\omega_x,\\omega_y)``) and then using the\nInverse Fast Fourier Transform to recover Z and update p and q as per bellow:\n```math\n\\begin{gathered}\np=\\sum c_p(\\omega_x,\\omega_y)e^{j(\\omega_xx+\\omega_yy)}\\\\\nq=\\sum c_q(\\omega_x,\\omega_y)e^{j(\\omega_xx+\\omega_yy)}\\\\Z=\\sum c(\\omega_x,\\omega_y)\ne^{j(\\omega_xx+\\omega_yy)}\\\\\n\\end{gathered}\n```\nwhere\n```math\nc(\\omega_x,\\omega_y)=\\dfrac{-j(\\omega_xc_p(\\omega_x,\\omega_y)+\\omega_yc_q(\\omega_x\n,\\omega_y))}{\\omega_x^2+\\omega_y^2}\n```\n# Arguments\nThe arguments are described in more detail below.\n## `albedo`\nA `Real` that specifies the albedo (amount of light reflected) of the image. If\n`albedo` is specified to must the `illumination_direction`. Defults to `Inf` which\nwill trigger the algorithm to run `estimate_img_properties`.\n## `illumination_direction`\nA `Vector{T} where T <: Real` that specifies the tilt value to be used by the\nalgorithm. The `illumination_direction` should be a vector of the form [x,y,z]\nwhere x,y,z are int he range [0,1]. If `illumination_direction` is specified\nto must the `albedo`. Defults to `[Inf, Inf, Inf]` which\nwill trigger the algorithm to run `estimate_img_properties`.\n## `iterations`\nAn `Int` that specifies the number of iterations the algorithm is to perform. If\nleft unspecified a default value of 2000 is used.\n## `smoothness`\nAn `Int` that specifies the strength of the smoothness constraint in the minimised\nfunction. Defults to `1000`.\n!!! note\n    If `albedo` and `illumination_direction` are not defined (i.e. have defulted\n    to `Inf`) they will be calculated at runtime using `estimate_img_properties`.\n# Example\nCompute the heightmap for a synthetic image generated by `generate_surface`.\n```julia\nusing Images, Makie, ShapeFromShading\n\n#generate synthetic image\nimg = generate_surface(SynthSphere(50), 1.0, [0.2,0,0.9])\n\n#calculate the heightmap (using 500 iterations)\ndiscreteShape = DiscreteShape(iterations = 500, albedo = 1.0, illumination_direction = [0.2,0,0.9])\nZ,p,q = discreteShape(img)\n\n#normalize to maximum of 1 (not necessary but makes displaying easier)\nZ = Z./maximum(Z)\n\n#display using Makie (Note: Makie can often take several minutes first time)\nr = 0.0:0.1:2\nsurface(r, r, Z)\n```\n# Reference\n1. S. Elhabian, \"Hands on Shape from Shading\", Computer Vision and Image Processing, 2008.\n\"\"\"\nfunction (algorithm::DiscreteShape)(img::AbstractArray)\n    ρ = algorithm.albedo\n    I = algorithm.illumination_direction\n    smoothness = algorithm.smoothness\n    iterations = algorithm.iterations\n\n    if ρ == Inf || I == [Inf, Inf, Inf]\n        ρ,I,σ,τ = estimate_img_properties(img)\n    end\n\n    E = Array{Float64}(img)\n\n    #initialize variables\n    p = zeros(Complex{Float64},axes(E))\n    q = zeros(Complex{Float64},axes(E))\n    R = zeros(Complex{Float64},axes(E))\n    Z = zeros(axes(E))\n    return solve_EulerLagrange(ρ, I, iterations, p, q, R, smoothness, E, Z)\nend\n", "meta": {"hexsha": "5d666b8a7c0dc518db6c16e33e67552680ad5c92", "size": 5339, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/discreteshape.jl", "max_stars_repo_name": "betttris13/ShapeFromShading.jl", "max_stars_repo_head_hexsha": "c486ad60d1675a65aacfe61dc1ef4d308bd534e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/discreteshape.jl", "max_issues_repo_name": "betttris13/ShapeFromShading.jl", "max_issues_repo_head_hexsha": "c486ad60d1675a65aacfe61dc1ef4d308bd534e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/discreteshape.jl", "max_forks_repo_name": "betttris13/ShapeFromShading.jl", "max_forks_repo_head_hexsha": "c486ad60d1675a65aacfe61dc1ef4d308bd534e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5985915493, "max_line_length": 150, "alphanum_fraction": 0.7117437722, "num_tokens": 1716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611563610179, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7960806284536432}}
{"text": "function lglnodes(N,a,b)\n\n# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n# %\n# % lglnodes.m\n# %\n# % Computes the Legendre-Gauss-Lobatto nodes, weights and the LGL Vandermonde \n# % matrix. The LGL nodes are the zeros of (1-x^2)*P'_N(x). Useful for numerical\n# % integration and spectral methods. \n# %\n# % Reference on LGL nodes and weights: \n# %   C. Canuto, M. Y. Hussaini, A. Quarteroni, T. A. Tang, \"Spectral Methods\n# %   in Fluid Dynamics,\" Section 2.3. Springer-Verlag 1987\n# %\n# % Written by Greg von Winckel - 04/17/2004\n# % Contact: gregvw@chtm.unm.edu\n# %\n# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n#\n# % Truncation + 1\n\tN1=N+1;\n\n\t#% Use the Chebyshev-Gauss-Lobatto nodes as the first guess\n\tx=cos(pi*[0:N]/N);\n\n\t# The Legendre Vandermonde Matrix\n\tP=zeros(N1,N1);\n\n\t# \t% Compute P_(N) using the recursion relation\n\t# \t% Compute its first and second derivatives and \n\t# \t% update x using the Newton-Raphson method.\n\n\txold=2;\n\n\twhile maximum(abs(x-xold))>eps()\n\n\t    xold=x;\n        \n\t    P[:,1]=1;    P[:,2]=x;\n    \n\t    for k=2:N\n\t\tP[:,k+1]=( (2*k-1)*x.*P[:,k]-(k-1)*P[:,k-1] )/k;\n\t    end\n     \n\t    x=xold-( x.*P[:,N1]-P[:,N] )./( N1*P[:,N1] );\n             \n\tend\n\n\tw=2./(N*N1*P[:,N1].^2)/2.*(b-a);\n\tx = (x+1)*(b-a)/2.+a \n\treturn x,w,P\nend", "meta": {"hexsha": "90c2d98946ba79648af36cc2d2b9a6234d9a2bae", "size": 1326, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lglnodes.jl", "max_stars_repo_name": "flavioluiz/PortHamiltonian", "max_stars_repo_head_hexsha": "8dc9e517292a95b4ae04ab15e8fbde30f0349caf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-08T05:39:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-08T05:39:52.000Z", "max_issues_repo_path": "src/lglnodes.jl", "max_issues_repo_name": "flavioluiz/PortHamiltonian", "max_issues_repo_head_hexsha": "8dc9e517292a95b4ae04ab15e8fbde30f0349caf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lglnodes.jl", "max_forks_repo_name": "flavioluiz/PortHamiltonian", "max_forks_repo_head_hexsha": "8dc9e517292a95b4ae04ab15e8fbde30f0349caf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5, "max_line_length": 82, "alphanum_fraction": 0.5113122172, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.7960605747167502}}
{"text": "\"\"\"\n        critic(decisionMat, fns)\n\nApply CRITIC (Combined Compromise Solution) method for a given matrix and criteria types.\n\n# Arguments:\n - `decisionMat::DataFrame`: n × m matrix of objective values for n alternatives and m criteria \n - `fns::Array{Function, 1}`: m-vector of functions to be applied on the columns.\n\n# Description \ncritic() applies the CRITIC method to rank n alterntives subject to m criteria which are supposed to be \neither maximized or minimized.\n\n# Output \n- `::CRITICResult`: CRITICResult object that holds multiple outputs including weighting and best index.\n\n# Examples\n```julia-repl\n\njulia> decmat\n3×4 Array{Float64,2}:\n 12.9918  0.7264  -1.1009  1.59814\n  4.1201  5.8824   3.4483  1.02156\n  4.1039  0.0     -0.5076  0.984469\n\njulia> df = makeDecisionMatrix(decmat)\n\n3×4 DataFrame\n Row │ Crt1     Crt2     Crt3     Crt4     \n     │ Float64  Float64  Float64  Float64  \n─────┼─────────────────────────────────────\n   1 │ 12.9918   0.7264  -1.1009  1.59814\n   2 │  4.1201   5.8824   3.4483  1.02156\n   3 │  4.1039   0.0     -0.5076  0.984469\n\njulia> fns = [maximum, maximum, minimum, maximum];\n\njulia> result = critic(df, fns);\n\njulia> result.w\n4-element Array{Float64,1}:\n 0.16883905506169491\n 0.41844653698732126\n 0.24912338769165807\n 0.16359102025932576\n\njulia> result.bestIndex\n2\n```\n# References\n\nDiakoulaki, D., Mavrotas, G., & Papayannakis, L. (1995). Determining objective weights in multiple criteria problems: The critic method. Computers & Operations Research, 22(7), 763–770. doi:10.1016/0305-0548(94)00059-h \nAkçakanat, Ö., Aksoy, E., Teker, T. (2018). CRITIC ve MDL Temelli EDAS Yöntemi ile TR-61 Bölgesi Bankalarının Performans Değerlendirmesi. Süleyman Demirel Üniversitesi Sosyal Bilimler Enstitüsü Dergisi, 1 (32), 1-24.\n\n\"\"\"\nfunction critic(decisionMat::DataFrame, fns::Array{Function,1})::CRITICResult\n    \n    row, col = size(decisionMat)\n    colMax = colmaxs(decisionMat)\n    colMin = colmins(decisionMat)\n\n    A = similar(decisionMat)\n\n    for i in 1:row\n        for j in 1:col\n            if fns[j] == maximum\n                @inbounds A[i, j] = (decisionMat[i, j] - colMin[j]) / (colMax[j] - colMin[j])\n            elseif fns[j] == minimum\n                @inbounds A[i, j] = (colMax[j] - decisionMat[i, j]) / (colMax[j] - colMin[j])\n            end                    \n        end\n    end\n\n    # normalizedMat = convert(Matrix, A)\n    normalizedMat = Matrix(A)\n    \n    corMat = 1 .- cor(normalizedMat)\n\n    scores = zeros(Float64, col)\n    for i in 1:col\n        scores[i] = sum(corMat[:, i]) .* std(normalizedMat[:, i])\n    end\n\n    w = zeros(Float64, col)\n    \n    for i in 1:col\n        w[i] = scores[i] ./ sum(scores)\n    end\n    \n    rankings = sortperm(w)\n    \n    bestIndex = rankings |> last\n    \n    result = CRITICResult(\n        decisionMat,\n        w,\n        rankings,\n        bestIndex\n    )\n\n    return result\nend\n\n\n\"\"\"\n        critic(setting)\n\nApply CRITIC (Combined Compromise Solution) method for a given matrix and criteria types.\n\n# Arguments:\n - `setting::MCDMSetting`: MCDMSetting object. \n \n# Description \ncritic() applies the CRITIC method to rank n alterntives subject to m criteria which are supposed to be \neither maximized or minimized.\n\n# Output \n- `::CRITICResult`: CRITICResult object that holds multiple outputs including weighting and best index.\n\"\"\"\nfunction critic(setting::MCDMSetting)::CRITICResult\n    critic(\n        setting.df, \n        setting.fns\n    )\nend ", "meta": {"hexsha": "e32996ce07b018cd5b8312eba90373c02b73b2e1", "size": 3455, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/critic.jl", "max_stars_repo_name": "drvinceknight/JMcDM", "max_stars_repo_head_hexsha": "89bec7ead2a7553f9e58fc75f37b5b89a30582fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2021-02-09T17:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T22:21:26.000Z", "max_issues_repo_path": "src/critic.jl", "max_issues_repo_name": "drvinceknight/JMcDM", "max_issues_repo_head_hexsha": "89bec7ead2a7553f9e58fc75f37b5b89a30582fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-02-09T16:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T18:11:34.000Z", "max_forks_repo_path": "src/critic.jl", "max_forks_repo_name": "drvinceknight/JMcDM", "max_forks_repo_head_hexsha": "89bec7ead2a7553f9e58fc75f37b5b89a30582fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2021-02-12T16:01:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:02:44.000Z", "avg_line_length": 27.64, "max_line_length": 219, "alphanum_fraction": 0.6460202605, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.7960605684909944}}
{"text": "\"\"\"\n    smoothstep(x, x_step, dx, a=zero(x), b=one(x))\n\nsmooth step function: \n- = a for x <= x_step - dx\n- = b for x >= x_step + dx\n- = (a-b)/2 for x == x_step\nand smooth in between.\n\"\"\"\nfunction smoothstep(x, x_step, dx, a=zero(x), b=one(x))\n    @assert dx > 0\n    edge0 = x_step - dx\n    x <= edge0 && return(a)\n    edge1 = x_step + dx\n    x >= edge1 && return(b)\n    y0 = _smoothstep(x,edge0,edge1)\n    y0 * (b-a) + a\nend\n\nfunction _smoothstep(x, edge0, edge1) \n    #https://en.wikipedia.org/wiki/Smoothstep\n    # Scale, bias and saturate x to 0..1 range\n    # assume that \n    @assert edge0 < x < edge1\n    #x = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0); \n    xs = (x - edge0) / (edge1 - edge0)\n    # Evaluate polynomial\n    xs * xs * (3 - 2 * xs)\n  end\n  \n\n  \n\n\n  ", "meta": {"hexsha": "a76204d738390a00e44b8317e4a725bd7af652a5", "size": 775, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/smoothstep.jl", "max_stars_repo_name": "bgctw/MTKHelpers", "max_stars_repo_head_hexsha": "5de2f0449c8d9c003d067fa10f8187232a731376", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/smoothstep.jl", "max_issues_repo_name": "bgctw/MTKHelpers", "max_issues_repo_head_hexsha": "5de2f0449c8d9c003d067fa10f8187232a731376", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-02-11T06:02:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T11:26:50.000Z", "max_forks_repo_path": "src/smoothstep.jl", "max_forks_repo_name": "bgctw/MTKHelpers", "max_forks_repo_head_hexsha": "5de2f0449c8d9c003d067fa10f8187232a731376", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1428571429, "max_line_length": 57, "alphanum_fraction": 0.5535483871, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.7960605684909944}}
{"text": "function volume(ϵ::Ellipsoid)\n    n = size(ϵ.H, 1)\n    return (n^(n / 2) * _unit_ball_volume(n)) / sqrt(det(ϵ.H))\nend\n\nfunction _unit_ball_volume(n::Integer)\n    return π^(n / 2) / gamma(n / 2 + 1)\nend\n", "meta": {"hexsha": "d2ad3838b599b8b0e94c1995fd90addc53898f0c", "size": 202, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/volume.jl", "max_stars_repo_name": "FriesischScott/MinimumVolumeEllipsoids.jl", "max_stars_repo_head_hexsha": "64303b99e68d70c44168536b39fd0a660e6a8ad8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-11-04T10:03:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T09:28:23.000Z", "max_issues_repo_path": "src/volume.jl", "max_issues_repo_name": "FriesischScott/MinimumVolumeEllipsoids.jl", "max_issues_repo_head_hexsha": "64303b99e68d70c44168536b39fd0a660e6a8ad8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-11-06T22:47:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T15:37:12.000Z", "max_forks_repo_path": "src/volume.jl", "max_forks_repo_name": "FriesischScott/MinimumVolumeEllipsoids.jl", "max_forks_repo_head_hexsha": "64303b99e68d70c44168536b39fd0a660e6a8ad8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-02T09:28:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T09:28:51.000Z", "avg_line_length": 22.4444444444, "max_line_length": 62, "alphanum_fraction": 0.6138613861, "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9736446456243805, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7960270046534534}}
{"text": "using ForwardDiff, BenchmarkTools, StaticArrays\n\n# Using StaticArrays #\n#--------------------#\n\n@inline eom(u) = @SVector [10.0(u[2]-u[1]), u[1]*(28.0-u[3]) - u[2], u[1]*u[2] - (8/3)*u[3]]\n\n@inline function manual_jacobian(u)\n    i = one(eltype(u))\n    return @SMatrix [       -10i    10i     0i;\n                     (28i - u[3])    -i  -u[1];\n                             u[2]  u[1]  -8i/3]\nend\n\n@inline forward_jacobian(u) = ForwardDiff.jacobian(eom, u)\n\nu = SVector{3}(rand(3))\n\n# sanity check\n@assert manual_jacobian(u) == forward_jacobian(u)\n\nprintln(\"---- eom(::SVector) benchmark results ----\")\ndisplay(@benchmark eom($u))\n\nprintln(\"---- manual_jacobian(::SVector) benchmark results ----\")\ndisplay(@benchmark manual_jacobian($u))\n\nprintln(\"---- forward_jacobian(::SVector) benchmark results ----\")\ndisplay(@benchmark forward_jacobian($u))\n\n# Using Base Arrays #\n#-------------------#\n\n@inline function eom!(du, u)\n    du[1] = 10.0(u[2]-u[1])\n    du[2] = u[1]*(28.0-u[3]) - u[2]\n    du[3] = u[1]*u[2] - (8/3)*u[3]\nend\n\n@inline function manual_jacobian!(J, u)\n    i = one(eltype(J))\n    J[1,1] = -10i\n    J[1,2] = 10i\n    J[1,3] = 0i\n    J[2,1] = 28i - u[3]\n    J[2,2] = -i\n    J[2,3] = -u[1]\n    J[3,1] = u[2]\n    J[3,2] = u[1]\n    J[3,3] = -8i/3\n    return J\nend\n\n@inline forward_jacobian!(J, du, u, cfg) = ForwardDiff.jacobian!(J, eom!, du, u, cfg)\n\nu = rand(3)\ndu = zeros(3)\nJ = zeros(3, 3)\ncfg = ForwardDiff.JacobianConfig(eom!, du, u)\n\n# sanity check\n@assert manual_jacobian!(J, u) == forward_jacobian!(J, du, u, cfg)\n\nprintln(\"---- eom!(::Vector, ::Vector) benchmark results ----\")\ndisplay(@benchmark eom!($du, $u))\n\nprintln(\"---- manual_jacobian!(::Matrix, ::Vector) benchmark results ----\")\ndisplay(@benchmark manual_jacobian!($J, $u))\n\nprintln(\"---- forward_jacobian!(::Matrix, ::Vector, ::Vector, ::JacobianConfig) benchmark results ----\")\ndisplay(@benchmark forward_jacobian!($J, $du, $u, $cfg))\n", "meta": {"hexsha": "1a41e0cb52db8ec717248444daaf7939b38cabaf", "size": 1914, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/benchmarks/older/jdrevels_original.jl", "max_stars_repo_name": "KalelR/DynamicalSystems.jl", "max_stars_repo_head_hexsha": "ac80eca0d8a11b8f2a98764b63bfcb624a4db248", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 585, "max_stars_repo_stars_event_min_datetime": "2017-09-14T10:59:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:41:49.000Z", "max_issues_repo_path": "test/benchmarks/older/jdrevels_original.jl", "max_issues_repo_name": "KalelR/DynamicalSystems.jl", "max_issues_repo_head_hexsha": "ac80eca0d8a11b8f2a98764b63bfcb624a4db248", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 101, "max_issues_repo_issues_event_min_datetime": "2017-09-08T17:07:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T15:41:36.000Z", "max_forks_repo_path": "test/benchmarks/older/jdrevels_original.jl", "max_forks_repo_name": "KalelR/DynamicalSystems.jl", "max_forks_repo_head_hexsha": "ac80eca0d8a11b8f2a98764b63bfcb624a4db248", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 75, "max_forks_repo_forks_event_min_datetime": "2017-09-24T14:32:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T09:19:44.000Z", "avg_line_length": 26.5833333333, "max_line_length": 104, "alphanum_fraction": 0.5726227795, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.863391617003942, "lm_q1q2_score": 0.7959795855989152}}
{"text": "\"\"\"\n    struct CartesianSpace <: EuclideanSpace{ℝ}\n\nA real euclidean space `ℝ^d`, which is therefore self-dual. `CartesianSpace` has no\nadditonal structure and is completely characterised by its dimension `d`. This is the\nvector space that is implicitly assumed in most of matrix algebra.\n\"\"\"\nstruct CartesianSpace <: EuclideanSpace{ℝ}\n    d::Int\nend\nCartesianSpace(V::CartesianSpace) = V\n\nBase.getindex(::RealNumbers) = CartesianSpace\nBase.getindex(::RealNumbers, d::Int) = CartesianSpace(d)\nBase.:^(::RealNumbers, d::Int) = CartesianSpace(d)\n\n# Corresponding methods:\n#------------------------\ndim(V::CartesianSpace) = V.d\nBase.axes(V::CartesianSpace) = Base.OneTo(dim(V))\n\nBase.oneunit(::Type{CartesianSpace}) = CartesianSpace(1)\n⊕(V1::CartesianSpace, V2::CartesianSpace) = CartesianSpace(V1.d+V2.d)\nfuse(V1::CartesianSpace, V2::CartesianSpace) = CartesianSpace(V1.d*V2.d)\nflip(V::CartesianSpace) = V\n\nBase.min(V1::CartesianSpace, V2::CartesianSpace) = CartesianSpace(min(V1.d, V2.d))\nBase.max(V1::CartesianSpace, V2::CartesianSpace) = CartesianSpace(max(V1.d, V2.d))\n\nBase.show(io::IO, V::CartesianSpace) = print(io, \"ℝ^$(V.d)\")\nBase.show(io::IO, ::Type{CartesianSpace}) = print(io, \"CartesianSpace\")\n", "meta": {"hexsha": "b143a9791358db17d7e738da8c0ecebe9c55566c", "size": 1205, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spaces/cartesianspace.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/TensorKit.jl-07d1fe3e-3e46-537d-9eac-e9e13d0d4cec", "max_stars_repo_head_hexsha": "6af4dd58a9ba0e354ffca5596760f16bfbe66715", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/spaces/cartesianspace.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/TensorKit.jl-07d1fe3e-3e46-537d-9eac-e9e13d0d4cec", "max_issues_repo_head_hexsha": "6af4dd58a9ba0e354ffca5596760f16bfbe66715", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spaces/cartesianspace.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/TensorKit.jl-07d1fe3e-3e46-537d-9eac-e9e13d0d4cec", "max_forks_repo_head_hexsha": "6af4dd58a9ba0e354ffca5596760f16bfbe66715", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.65625, "max_line_length": 85, "alphanum_fraction": 0.7211618257, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.8633916047011595, "lm_q1q2_score": 0.7959795668480178}}
{"text": "\n\"\"\"\n    barycentric_weights{T<:Real}(x::AbstractVector{T})\n\nCompute the barycentric weights corresponding to the nodes `x`.\n[Kopriva, Implementing Spectral Methods for PDEs, Algorithm 30].\n\"\"\"\nfunction barycentric_weights(x::AbstractVector)\n    w = fill!(similar(x), one(eltype(x)))\n    @inbounds barycentric_weights!(w, x)\n    w\nend\n\nfunction barycentric_weights!(w, x)\n    @boundscheck begin\n        length(w) == length(x)\n    end\n    fill!(w, 1)\n    @inbounds for j in 2:length(w), k in 1:j-1\n        diff = x[k] - x[j]\n        w[k] *= diff\n        w[j] *= -diff\n    end\n    @inbounds for j in 1:length(w)\n        w[j] = 1 / w[j]\n    end\n    nothing\nend\n\n\n\"\"\"\n    interpolate(x::Real, nodes, values, baryweights)\n\nInterpolate the function represented by `values` on the `nodes` using the\ncorresponding barycentric weights `baryweights`.\n[Kopriva, Implementing Spectral Methods for PDEs, Algorithm 31].\n\"\"\"\nfunction interpolate(x::Real, values, nodes, baryweights)\n    @boundscheck begin\n        @assert size(values) == size(nodes) == size(baryweights)\n    end\n    num = zero(first(baryweights)*first(values)/first(nodes)*one(x))\n    den = zero(first(baryweights)/first(nodes)*one(x))\n    @inbounds for idx in eachindex(nodes)\n        xval = nodes[idx]\n        if xval ≈ x\n            return values[idx]\n        end\n        t = baryweights[idx] / (x - xval)\n        num += t*values[idx]\n        den += t\n    end\n    num / den\nend\n\nfunction interpolate(x::AbstractVector, values, nodes, baryweights)\n    ret = similar(x)\n    interpolate!(ret, x, values, nodes, baryweights)\n    ret\nend\n\nfunction interpolate!(ret::AbstractVector, x::AbstractVector, values, nodes, baryweights)\n    @boundscheck begin\n        @assert size(ret) == size(x)\n        @assert size(values) == size(nodes) == size(baryweights)\n    end\n    @inbounds for idx in eachindex(ret)\n        ret[idx] = interpolate(x[idx], values, nodes, baryweights)\n    end\n    nothing\nend\n\nfunction interpolate(x, values, basis::NodalBasis)\n    @unpack nodes, baryweights = basis\n    interpolate(x, values, nodes, baryweights)\nend\n\nfunction interpolate!(ret, x, values, basis::NodalBasis)\n    @unpack nodes, baryweights = basis\n    interpolate!(ret, x, values, nodes, baryweights)\nend\n\n\n\"\"\"\n    interpolation_matrix(destination, source, baryweights)\n\nCompute the matrix performing interpolation from `src` to `dest`, where\n`baryweights` are the barycentric weights corresponding to `src`.\n[Kopriva, Implementing Spectral Methods for PDEs, Algorithm 32].\n\"\"\"\nfunction interpolation_matrix(dest, src, baryweights)\n    @boundscheck begin\n        @assert length(src) == length(baryweights)\n    end\n    T = promote_type(eltype(dest), eltype(src), eltype(baryweights))\n    mat = Array{T}(undef, length(dest), length(src))\n    @inbounds interpolation_matrix!(mat, dest, src, baryweights)\n    mat\nend\n\nfunction interpolation_matrix!(mat, dest, src, baryweights)\n    @boundscheck begin\n        @assert length(src) == length(baryweights)\n        @assert size(mat,1) == length(dest)\n        @assert size(mat,2) == length(src)\n    end\n    fill!(mat, zero(eltype(mat)))\n    @inbounds for k in 1:size(mat,1)\n        row_has_match = false\n        for j in 1:size(mat,2)\n            if dest[k] ≈ src[j]\n                row_has_match = true\n                mat[k,j] = 1\n            end\n        end\n        if row_has_match == false\n            s = zero(eltype(mat))\n            for j in 1:size(mat,2)\n                t = baryweights[j] / (dest[k] - src[j])\n                mat[k,j] = t\n                s = s + t\n            end\n            for j in 1:size(mat,2)\n                mat[k,j] /= s\n            end\n        end\n    end\n    nothing\nend\n\n# special methods of interpolation_matrix for SymPy and SymEngine are in __init__\n\nfunction interpolation_matrix(dest, basis::NodalBasis)\n    @unpack nodes, baryweights = basis\n    interpolation_matrix(dest, nodes, baryweights)\nend\n\nfunction interpolation_matrix!(mat, dest, basis::NodalBasis)\n    @unpack nodes, baryweights = basis\n    interpolation_matrix!(mat, dest, nodes, baryweights)\nend\n", "meta": {"hexsha": "233365441a2fcb5ff9a7fe647df67629e5910fba", "size": 4077, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/interpolation.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_stars_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-09-11T18:12:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T21:08:56.000Z", "max_issues_repo_path": "src/interpolation.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_issues_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2018-02-15T06:32:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T15:59:07.000Z", "max_forks_repo_path": "src/interpolation.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_forks_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:34:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:01:42.000Z", "avg_line_length": 28.7112676056, "max_line_length": 89, "alphanum_fraction": 0.6369879814, "num_tokens": 1106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361533336451, "lm_q2_score": 0.8723473813156295, "lm_q1q2_score": 0.7959612889783115}}
{"text": "# # Heat equation\n#\n# In this example, we numerically solve the 1D [heat\n# equation](https://en.wikipedia.org/wiki/Heat_equation)\n#\n# ```math\n# \\frac{∂θ}{∂t} = ν \\frac{∂^2 θ}{∂x^2},\n# ```\n#\n# in a bounded domain ``x ∈ [-1, 1]`` with homogeneous Neumann boundary\n# conditions, ``∂_x θ(±1, t) = 0``.\n\n# ## Defining a B-spline basis\n\n# The general idea is to approximate the unknown solution by a spline of order\n# ``k``.\n# For this, we first define a B-spline basis ``\\{ b_i(x), \\, i = 1, …, N \\}``, such\n# that the solution at a given time $t$ is approximated by\n#\n# ```math\n# θ(x, t) = ∑_{i = 1}^N v_i(t) b_i(x),\n# ```\n#\n# where the $v_i$ are the B-spline coefficients.\n#\n# A B-spline basis is uniquely defined by its order ``k`` and by a choice of\n# *knot* locations within the spatial domain, which form the spatial grid.\n\n# For this example, we take a uniform repartition of knots in ``[-1, 1]``.\nknots_in = range(-1, 1; length = 11)\n\n# We then create a B-spline basis of order ``k = 4`` using these knots.\nusing BSplineKit\nB = BSplineBasis(BSplineOrder(4), knots_in)\n\n# Note that the generated basis includes an *augmented* set of knots, in which\n# each boundary is repeated ``k`` times:\n\nknots(B)\n\n# In other words, the boundary knots have multiplicity ``k``, while interior\n# knots have multiplicity 1.\n# This is common practice in bounded domains, and translates the fact that the\n# solution does not need to be continuous at the boundaries.\n# This provides additional degrees of freedom notably for the boundary\n# conditions.\n# This behaviour can be disabled via the `augment` argument of\n# [`BSplineBasis`](@ref).\n\n# We can now plot the knot locations (crosses) and the generated B-spline basis:\n\nusing CairoMakie\nusing LaTeXStrings\nCairoMakie.activate!(type = \"svg\")\n\nfunction plot_knots!(ax, ts; knot_offset = 0.03, kws...)\n    ys = zero(ts)\n    ## Add offset to distinguish knots with multiplicity > 1\n    for i in eachindex(ts)[(begin + 1):end]\n        if ts[i] == ts[i - 1]\n            ys[i] = ys[i - 1] + knot_offset\n        end\n    end\n    scatter!(ax, ts, ys; marker = :x, markersize = 20, color = :gray, kws...)\n    ax\nend\n\nfunction plot_basis!(ax, B; eval_args = (), kws...)\n    cmap = cgrad(:tab20)\n    N = length(B)\n    ts = knots(B)\n    hlines!(ax, 0; color = :gray)\n    for (n, bi) in enumerate(B)\n        color = cmap[(n - 1) / (N - 1)]\n        i, j = extrema(support(bi))\n        lines!(ax, ts[i]..ts[j], x -> bi(x, eval_args...); color, linewidth = 2.5)\n    end\n    plot_knots!(ax, ts; kws...)\n    ax\nend\n\nfig = Figure()\nax = Axis(fig[1, 1]; xlabel = L\"x\", ylabel = L\"b_i(x)\")\nplot_basis!(ax, B)\nfig\n\n# ## Imposing boundary conditions\n\n# In BSplineKit, the recommended approach for solving boundary value problems is\n# to use the **basis recombination** method.\n# That is, to expand the solution onto a new basis consisting on linear\n# combinations of B-splines ``b_i(x)``, such that each recombined basis function\n# ``ϕ_j(x)`` individually satisfies the required homogeneous boundary conditions\n# (BCs).\n# Thanks to the local support of B-splines, basis recombination only involves a\n# small number of B-splines near the boundaries.\n#\n# Using the [`RecombinedBSplineBasis`](@ref) type, we can easily define such\n# recombined bases for many different BCs.\n# In this example we generate a basis satisfying homogeneous Neumann BCs:\n\nR = RecombinedBSplineBasis(Derivative(1), B)\n\nfig = Figure()\nax = Axis(fig[1, 1]; xlabel = L\"x\", ylabel = L\"ϕ_i(x)\")\nplot_basis!(ax, R)\nfig\n\n# We notice that, on each of the two boundaries, the two initial (or final)\n# B-splines of the original basis have been combined to produce a single basis\n# function that has zero derivative at each respective boundary.\n# To verify this, we can plot the basis function derivatives:\n\nfig = Figure()\nax = Axis(fig[1, 1]; xlabel = L\"x\", ylabel = L\"ϕ_i^′(x)\")\nplot_basis!(ax, R; eval_args = (Derivative(1), ), knot_offset = 0.4)\nfig\n\n# Note that the new basis has two less functions than the original one,\n# reflecting a loss of two degrees of freedom corresponding to the new\n# constraints on each boundary:\n\nlength(B), length(R)\n\n# ### Recombination matrix\n\n# As stated above, the basis recombination approach consists in performing\n# linear combinations of B-splines ``b_i`` to obtain a derived basis of\n# functions ``ϕ_j`` satisfying certain boundary conditions.\n# This can be conveniently expressed using a transformation matrix\n# ``\\mathbf{T}`` relating the two bases:\n#\n# ```math\n# ϕ_j(x) = ∑_{i = 1}^N T_{ij} b_i(x)\n# \\quad \\text{for } j = 1, 2, …, M,\n# ```\n#\n# where ``N`` is the number of B-splines ``b_i``, and ``M < N`` is the number of\n# ``ϕ_j`` functions (in this example, ``M = N - 2``).\n#\n# The recombination matrix associated to the generated basis can be obtained\n# using [`recombination_matrix`](@ref):\n\nT = recombination_matrix(R)\n\n# Note that the matrix is almost an identity matrix, since most B-splines are\n# kept intact in the new basis.\n# This simple structure allows for very efficient computations using this\n# matrix.\n# The first and last columns indicate that Neumann BCs are imposed by adding the\n# two first (and two last) B-splines, i.e.\n#\n# ```math\n# ϕ_1(x) = b_1(x) + b_2(x),\n# \\qquad\n# ϕ_M(x) = b_{N - 1}(x) + b_N(x).\n# ```\n\n# ### Representation of the solution\n#\n# Note that the solution ``θ(x, t)`` can be represented in the original and in\n# the recombined B-spline bases as\n#\n# ```math\n# θ(x, t) = ∑_{i = 1}^N v_i(t) b_i(x) = ∑_{j = 1}^M u_j(t) ϕ_j(x),\n# ```\n#\n# where the ``u_j`` are the coefficients in the recombined basis.\n#\n# The recombination matrix introduced above can be used to transform between the\n# coefficients ``u_j`` and ``v_i`` in both bases, via the linear relation\n# ``\\bm{v} = \\mathbf{T} \\bm{u}``.\n\n# ## Initial condition\n\n# We come back now to our problem.\n# We want to impose the following initial condition:\n#\n# ```math\n# θ(x, 0) = θ_0(x) = 1 + \\cos(π x).\n# ```\n\n# First, we approximate this initial condition in the recombined\n# B-spline basis that we have just constructed.\n# This may be easily done using [`approximate`](@ref):\n\nθ₀(x) = 1 + cos(π * x)\nθ₀_spline = approximate(θ₀, R, MinimiseL2Error())\n\n# To see that everything went well, we can plot the exact initial condition and\n# its spline approximation, which show no important differences.\n\nfig = Figure(resolution = (800, 400))\nlet ax = Axis(fig[1, 1]; xlabel = L\"x\", ylabel = L\"\\theta\")\n    lines!(ax, -1..1, θ₀; label = L\"θ_0(x)\", color = :blue)\n    lines!(ax, -1..1, x -> θ₀_spline(x); label = \"Approximation\", color = :orange, linestyle = :dash)\n    axislegend(ax; position = :cb)\nend\nlet ax = Axis(fig[1, 2]; xlabel = L\"x\", ylabel = \"Difference\")\n    lines!(ax, -1..1, x -> θ₀(x) - θ₀_spline(x))\n    plot_knots!(ax, knots(R); knot_offset = 0)\nend\nfig\n\n# Note that we have access to the recombined B-spline coefficients ``u_j``\n# associated to the initial condition, which we will use further below:\n\nu_init = coefficients(θ₀_spline)\n\n# ## Solving the heat equation\n#\n# To solve the governing equation, the strategy is to project the unknown\n# solution onto the chosen recombined basis.\n# That is, we approximate the solution as\n#\n# ```math\n# θ(x, t) = \\sum_{j = 1}^M u_j(t) \\, ϕ_j(x).\n# ```\n#\n# Plugging this representation into the heat equation, we find\n#\n# ```math\n# \\newcommand{\\dd}{\\mathrm{d}}\n# ∑_j \\frac{\\dd u_j}{\\dd t} \\, ϕ_j(x) = ν ∑_j u_j \\, ϕ_j''(x),\n# ```\n#\n# where primes denote spatial derivatives.\n#\n# We can now use the [method of mean weighted\n# residuals](https://en.wikipedia.org/wiki/Method_of_mean_weighted_residuals) to\n# find the coefficients ``u_j``, by projecting the above equation onto a chosen\n# set of *test* functions ``φ_i``:\n#\n# ```math\n# ∑_j \\frac{\\mathrm{d} u_j}{\\mathrm{d} t} \\, ⟨φ_i, ϕ_j⟩ = ν ∑_j u_j \\, ⟨φ_i, ϕ_j''⟩,\n# ```\n#\n# where ``⟨ f, g ⟩ = ∫_{-1}^1 f(x) \\, g(x) \\, \\mathrm{d} x`` is the inner product\n# between functions.\n#\n# By choosing ``M`` different test functions ``φ_i``, the above problem can be\n# written as the linear system\n#\n# ```math\n# \\mathbf{A} \\frac{\\mathrm{d} \\bm{u}(t)}{\\mathrm{d} t} =\n# ν \\mathbf{L} \\bm{u}(t),\n# ```\n#\n# where the matrices are defined by ``A_{ij} = ⟨ φ_i, ϕ_j ⟩`` and\n# ``L_{ij} = ⟨ φ_i, ϕ_j'' ⟩``.\n#\n# Two of the most common choices of test functions ``φ_i`` are:\n#\n# - ``φ_i(x) = δ(x - x_i)``, where ``δ`` is Dirac's delta, and ``x_i`` are a set of\n#   *collocation* points where the equation will be satisfied.\n#   This approach is known as the **collocation** method.\n#\n# - ``φ_i(x) = ϕ_i(x)``, in which case this is the **Galerkin** method.\n#\n# We describe the solution using both methods in the following.\n\n# ## Collocation method\n\n# For the collocation method, we need to choose a set of ``M`` grid points\n# ``x_j``.\n# Since the basis functions implicitly satisfy the boundary conditions, these\n# points must be chosen *inside* of the domain.\n#\n# The collocation points may be automatically generated by calling\n# [`collocation_points`](@ref).\n# Note that, since we pass the recombined basis `R`, the boundaries are not\n# included in the chosen points:\n\nxcol = collocation_points(R)\n\n# We can now construct the matrices ``\\mathbf{A}`` and ``\\mathbf{L}`` associated\n# to the collocation method.\n# By definition, these matrices simply contain the evaluations of all basis\n# functions ``ϕ_j`` and their derivatives at the collocation points:\n# ``A_{ij} = ϕ_j(x_i)`` and ``L_{ij} = ϕ_j''(x_i)``.\n# Both these matrices can be constructed in BSplineKit using\n# [`collocation_matrix`](@ref).\n# Note that both matrices are of type [`CollocationMatrix`](@ref), which wrap\n# matrices defined in\n# [BandedMatrices.jl](https://github.com/JuliaMatrices/BandedMatrices.jl).\n\nAcol = collocation_matrix(R, xcol)\nLcol = collocation_matrix(R, xcol, Derivative(2))\n\n# For convenience and performance, we can incorporate the heat diffusivity ``ν``\n# in the ``\\mathbf{L}`` matrix:\n\nν = 0.01\nLcol *= ν\n\n# Finally, for the time integration, we use OrdinaryDiffEq.jl from the\n# [DifferentialEquations.jl suite](https://diffeq.sciml.ai/stable/).\n\nusing LinearAlgebra\nusing OrdinaryDiffEq\n\nfunction heat_rhs!(du, u, params, t)\n    mul!(du, params.L, u)    # du = ν * L * u\n    ldiv!(du, params.A, du)  # du = A \\ (ν * L * u)\n    du\nend\n\n## Solver parameters\nparams_col = (\n    A = lu(Acol),  # we pass the factorised matrix A for performance\n    L = Lcol,\n)\n\ntspan = (0.0, 10.0)\nprob = ODEProblem(heat_rhs!, u_init, tspan, params_col)\nsol_collocation = solve(prob, Tsit5(); saveat = 0.5)\n\nfunction plot_heat_solution(sol, R)\n    fig = Figure()\n    ax = Axis(fig[1, 1]; xlabel = L\"x\", ylabel = L\"θ(x, t)\")\n    colormap = cgrad(:viridis)\n    tspan = sol.prob.tspan\n    Δt = tspan[2] - tspan[1]\n    for (u, t) in tuples(sol)\n        S = Spline(R, u)\n        color = colormap[(t - tspan[1]) / Δt]\n        lines!(ax, -1..1, x -> S(x); label = string(t), color, linewidth = 2)\n    end\n    Colorbar(fig[1, 2]; colormap, limits = tspan, label = \"Time\")\n    fig\nend\n\nplot_heat_solution(sol_collocation, R)\n\n# ## Galerkin method\n\n# We start by constructing the Galerkin matrices ``\\mathbf{A}`` and\n# ``\\mathbf{L}``.\n# The first of these matrices, ``A_{ij} = ⟨ ϕ_i, ϕ_j ⟩``, is usually\n# known as the *mass matrix* of the system.\n# It is a positive definite symmetric matrix, which enables the use of Cholesky\n# factorisation to solve the resulting linear system.\n# Moreover, here it is banded thanks to the local support of the B-splines.\n# The mass matrix can be constructed by calling [`galerkin_matrix`](@ref):\n\nAgal = galerkin_matrix(R)\n\n# Note that, unlike the collocation method, in the Galerkin method we don't need\n# to specify a set of grid points, as functions are not evaluated at collocation\n# points (they are instead integrated over the whole domain).\n# The integration is performed using Gauss--Legendre quadrature, which can be\n# made exact up to numerical precision, taking advantage of the fact that the\n# product of two B-splines is a piecewise polynomial.\n\n# As for the matrix ``\\mathbf{L}`` representing the second derivative operator,\n# we can write it using integration by parts as\n#\n# ```math\n# L_{ij} = ⟨ ϕ_i, ϕ_j'' ⟩\n# = -⟨ ϕ_i', ϕ_j' ⟩ + \\left[ ϕ_i ϕ_j' \\right]_{-1}^1  = -R_{ij},\n# ```\n#\n# where ``R_{ij} = ⟨ ϕ_i', ϕ_j' ⟩`` is a positive definite symmetric matrix.\n# Note that the boundary terms all vanish since all basis functions individually\n# satisfy homogeneous Neumann boundary conditions, ``ϕ_i'(±1) = 0``.\n# (The same result would be obtained with homogeneous Dirichlet boundary\n# conditions.)\n#\n# As can be seen above, one well-known advantage of the Galerkin method is that\n# the basis functions can satisfy weaker continuity conditions than in the\n# collocation method, as high-order derivatives can be reduced using integration\n# by parts.\n#\n# The matrix ``\\mathbf{R}`` can be constructed using [`galerkin_matrix`](@ref):\n\nRgal = galerkin_matrix(R, (Derivative(1), Derivative(1)))\n\n# Note that, instead, we could have constructed the original matrix\n# ``\\mathbf{L}``, which, as expected, is equal to ``\\mathbf{R}`` up to a sign:\n\nLgal = galerkin_matrix(R, (Derivative(0), Derivative(2)))\n\n# As in the collocation example, we include the heat diffusivity ``ν`` in the\n# ``\\mathbf{R}`` matrix:\n\nparent(Rgal) .*= -ν  # we can't directly multiply Rgal, as it's a Hermitian wrapper\n\n# We finally solve using DifferentialEquations.jl.\n# Note that not much is changed compared to the collocation example.\n# The only difference is that we use a Cholesky factorisation for the mass\n# matrix ``\\mathbf{A}``.\n\nparams_gal = (\n    A = cholesky(Agal),\n    L = Rgal,\n)\n\nprob = ODEProblem(heat_rhs!, u_init, tspan, params_gal)\nsol_galerkin = solve(prob, Tsit5(); saveat = 0.5)\n\nplot_heat_solution(sol_galerkin, R)\n\n# ## Result comparison\n\n# The solution of the Galerkin method looks very similar to the one obtained\n# with the collocation method.\n# However, as seen below, there are non-negligible differences between the two.\n\nfig = Figure(resolution = (800, 400))\nlet ax = Axis(fig[1, 1]; xlabel = L\"x\", ylabel = latexstring(\"θ(x, t = $(tspan[end]))\"))\n    for pair in (\n            \"Collocation\" => sol_collocation,\n            \"Galerkin\" => sol_galerkin,\n        )\n        label, sol = pair\n        u = last(sol.u)\n        S = Spline(R, u)\n        lines!(ax, -1..1, x -> S(x); label, linewidth = 2)\n    end\n    axislegend(ax; position = :cb)\nend\nlet ax = Axis(fig[1, 2]; xlabel = L\"x\", ylabel = \"Difference\")\n    Sc = Spline(R, last(sol_collocation.u))\n    Sg = Spline(R, last(sol_galerkin.u))\n    lines!(ax, -1..1, x -> Sc(x) - Sg(x); linewidth = 2)\nend\nfig\n\n# Compared to the Galerkin method, there seems to be some additional dissipation\n# in the domain interior when using the collocation method.\n# This hints at the presence of numerical dissipation introduced by this method.\n\n# To finish, we compare the two solutions to a solution at a higher resolution, using\n# a higher number of B-spline knots and a higher B-spline order.\n# This last solution is obtained using the collocation method to allow for\n# better comparisons between both methods.\n\nhi_res = let\n    knots_in = range(-1, 1; length = 101)\n    B = BSplineBasis(BSplineOrder(6), knots_in)\n    R = RecombinedBSplineBasis(Derivative(1), B)\n    θ₀_spline = approximate(θ₀, R)\n    u_init = coefficients(θ₀_spline)\n    xcol = collocation_points(R)\n    Acol = collocation_matrix(R, xcol)\n    Lcol = ν .* collocation_matrix(R, xcol, Derivative(2))\n    params_col = (A = lu(Acol), L = Lcol)\n    prob = ODEProblem(heat_rhs!, u_init, tspan, params_col)\n    sol = solve(prob, Tsit5(); saveat = 0.5)\n    (; R, sol)\nend\n\nfig = Figure(resolution = (800, 400))\nlet ax = Axis(fig[1, 1]; xlabel = L\"x\", ylabel = latexstring(\"θ(x, t = $(tspan[end]))\"))\n    for pair in (\n            \"Collocation\" => sol_collocation,\n            \"Galerkin\" => sol_galerkin,\n        )\n        label, sol = pair\n        u = last(sol.u)\n        S = Spline(R, u)\n        lines!(ax, -1..1, x -> S(x); label, linewidth = 2)\n    end\n    let u = last(hi_res.sol.u)\n        S = Spline(hi_res.R, u)\n        lines!(ax, -1..1, x -> S(x); label = \"Hi-res\", linewidth = 2, linestyle = :dash, color = :gray)\n    end\n    axislegend(ax; position = :cb)\nend\nlet ax = Axis(fig[1, 2]; xlabel = L\"x\", ylabel = \"Difference with hi-res solution\")\n    Sc = Spline(R, last(sol_collocation.u))\n    Sg = Spline(R, last(sol_galerkin.u))\n    S_hi = Spline(hi_res.R, last(hi_res.sol.u))\n    lines!(ax, -1..1, x -> Sc(x) - S_hi(x); label = \"Colloc.\", linewidth = 2)\n    lines!(ax, -1..1, x -> Sg(x) - S_hi(x); label = \"Galerkin\", linewidth = 2)\n    axislegend(ax; position = :rb)\nend\nfig\n\n# We see that the low-resolution solution with the Galerkin method matches the\n# high-resolution solution.\n# This confirms that the Galerkin method provides higher accuracy than the\n# collocation method when both are used at the same resolution.\n", "meta": {"hexsha": "1e5039ab9879eaf7d3f1ce9e6c7d7c2d152c1a5a", "size": 16837, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/heat.jl", "max_stars_repo_name": "jipolanco/BasisSplines", "max_stars_repo_head_hexsha": "16c689d6464adc9f467b451fe17df3221df67c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-11-03T21:11:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T19:09:34.000Z", "max_issues_repo_path": "examples/heat.jl", "max_issues_repo_name": "jipolanco/BasisSplines", "max_issues_repo_head_hexsha": "16c689d6464adc9f467b451fe17df3221df67c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2020-06-29T07:46:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T16:25:06.000Z", "max_forks_repo_path": "examples/heat.jl", "max_forks_repo_name": "jipolanco/BasisSplines", "max_forks_repo_head_hexsha": "16c689d6464adc9f467b451fe17df3221df67c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7871900826, "max_line_length": 103, "alphanum_fraction": 0.6709033676, "num_tokens": 5091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8688267830311354, "lm_q1q2_score": 0.7959405744486528}}
{"text": "#\n#\n#In the 20×20 grid below, four numbers along a diagonal line have been marked in red.\n\nA = [\n08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08\n49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00\n81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65\n52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91\n22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80\n24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50\n32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70\n67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21\n24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72\n21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95\n78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92\n16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57\n86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58\n19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40\n04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66\n88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69\n04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36\n20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16\n20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54\n01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48\n]\n\n#The product of these numbers is 26 × 63 × 78 × 14 = 1788696.\n#\n#What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?\n\nprintln(size(A))\n\nmaxval = typemin(Int64)\nxi, xj, di = 0, 0, '.'\n# horizontal\nfor i in 1:20\n\tfor j in 1:20\n\t\t# horizontal\n\t\tif j <= 17\n\t\t\tx = prod(A[i, j:j+3])\n\t\t\tif x > maxval\n\t\t\t\tprintln(A[i, j:j+3])\n\t\t\t\tmaxval, xi, xj, di = x, i, j, '>'\n\t\t\tend\n\t\tend\n\t\t# vertical\n\t\tif i <= 17\n\t\t\tx = prod(A[i:i+3, j])\n\t\t\tif x > maxval\n\t\t\t\tprintln(A[i:i+3, j])\n\t\t\t\tmaxval, xi, xj, di = x, i, j, 'v'\n\t\t\tend\n\t\tend\n\t\t# top left -> bottom right\n\t\tif i <= 17 && j <= 17\n\t\t\tx = prod(diag(A[i:i+3, j:j+3]))\n\t\t\tif x > maxval\n\t\t\t\tprintln(diag(A[i:i+3, j:j+3]))\n\t\t\t\tmaxval, xi, xj, di = x, i, j, '\\\\'\n\t\t\tend\n\t\tend\n\t\t# top right -> bottom left\n\t\tif i <= 17 && j <= 17\n\t\t\tx = prod(diag(rotr90(A[i:i+3, j:j+3])))\n\t\t\tif x > maxval\n\t\t\t\tprintln(diag(rotr90(A[i:i+3, j:j+3])))\n\t\t\t\tmaxval, xi, xj, di = x, i, j, '/'\n\t\t\tend\n\t\tend\n\tend\nend\nprint(maxval, ' ', xi, ' ', xj, ' ', di)\nprint(A[xi:xi+3, xj:xj+3])\n\n# 89*94*97*87\n# 70600674\n\n", "meta": {"hexsha": "18b676f0c14a8b07e4b0b42b2945b966ff35f7fe", "size": 2400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "algo/su.11.jl", "max_stars_repo_name": "cdluminate/MyNotes", "max_stars_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algo/su.11.jl", "max_issues_repo_name": "cdluminate/MyNotes", "max_issues_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algo/su.11.jl", "max_forks_repo_name": "cdluminate/MyNotes", "max_forks_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3797468354, "max_line_length": 134, "alphanum_fraction": 0.6070833333, "num_tokens": 1295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8688267779364222, "lm_q1q2_score": 0.795940569781337}}
{"text": "\"\"\"\n    polyinterp(t,y)\n\nConstruct a callable polynomial interpolant through the points in\nvectors `t`,`y` using the barycentric interpolation formula.\n\"\"\"\nfunction polyinterp(t,y)\n    n = length(t)-1\n    C = (t[n+1]-t[1]) / 4           # scaling factor to ensure stability\n    tc = t/C\n\n    # Adding one node at a time, compute inverses of the weights.\n    ω = ones(n+1)\n    for m in 0:n-1\n        d = tc[1:m+1] .- tc[m+2]    # vector of node differences\n        @. ω[1:m+1] *= d            # update previous\n        ω[m+2] = prod( -d )         # compute the new one\n    end\n    w = 1 ./ ω                      # go from inverses to weights\n\n    # This function evaluates the interpolant at given x.\n    p = function (x)\n        terms = @. w / (x - t)\n        if any(isinf.(terms))     # there was division by zero\n            # return the node's data value\n            idx = findfirst(x.==t)\n            f = y[idx]\n        else\n            f = sum(y.*terms) / sum(terms)\n        end\n    end\n    return p\nend\n\n\"\"\"\n    triginterp(t,y)\n\nConstruct the trigonometric interpolant for the points defined by \nvectors `t` and `y`.\n\"\"\"\nfunction triginterp(t,y)\n    N = length(t)\n\n    function τ(x)\n        if x==0\n            return 1.0\n        else\n            denom = isodd(N) ? N*sin(π*x/2) : N*tan(π*x/2)\n            return sin(N*π*x/2)/denom\n        end\n    end\n\n    return function (x)\n        sum( y[k]*τ(x-t[k]) for k in eachindex(y) )\n    end\nend\n\n\"\"\"\n    ccint(f,n)\n\nPerform Clenshaw-Curtis integration for the function `f` on `n`+1\nnodes in [-1,1]. Returns the integral estimate and a vector of the \nnodes used. Note: `n` must be even.\n\"\"\"\nfunction ccint(f,n)\n    @assert iseven(n) \"Value of `n` must be an even integer.\"\n    # Find Chebyshev extreme nodes.\n    θ = [ i*π/n for i in 0:n ]\n    x = -cos.(θ)\n\n    # Compute the C-C weights.\n    c = similar(θ)\n    c[[1,n+1]] .= 1/(n^2-1)\n    s = sum( cos.(2k*θ[2:n])/(4k^2-1) for k in 1:n/2-1 )\n    v = @. 1 - 2s - cos(n*θ[2:n])/(n^2-1)\n    c[2:n] = 2v/n\n\n    # Evaluate integrand and integral.\n    I = dot(c,f.(x))   # vector inner product\n    return I,x\nend\n\n\"\"\"\n    glint(f,n)\n\nPerform Gauss-Legendre integration for the function `f` on `n` nodes\nin (-1,1). Returns the integral estimate and a vector of the nodes used.\n\"\"\"\nfunction glint(f,n)\n    # Nodes and weights are found via a tridiagonal eigenvalue problem.\n    β = @. 0.5/sqrt(1-(2*(1:n-1))^(-2))\n    T = diagm(-1=>β,1=>β)\n    λ,V = eigen(T)\n    p = sortperm(λ)\n    x = λ[p]               # nodes\n    c = @. 2V[1,p]^2       # weights\n\n    # Evaluate the integrand and compute the integral.\n    I = dot(c,f.(x))      # vector inner product\n    return I,x\nend\n\n\"\"\"\n    intinf(f,tol)\n\nPerform adaptive doubly-exponential integration of function `f` \nover (-Inf,Inf), with error tolerance `tol`. Returns the integral \nestimate and a vector of the nodes used.\n\"\"\"\nfunction intinf(f,tol)   \n    x = t -> sinh(sinh(t))\n    dx_dt = t -> cosh(t)*cosh(sinh(t))\n    g = t -> f(x(t))*dx_dt(t)\n\n    # Find where to truncate the integration interval.\n    M = 3\n    while (abs(g(-M)) > tol/100) || (abs(g(M)) > tol/100)\n        M += 0.5\n        if isinf(x(M)) \n            @warn \"Function may not decay fast enough.\"\n            M -= 0.5\n            break\n        end\n    end\n\n    I,t = intadapt(g,-M,M,tol)\n\treturn I,x.(t)\nend\n\n\"\"\"\n    intsing(f,tol)\n\nAdaptively integrate function `f` over (0,1), where `f` may be \nsingular at zero, with error tolerance `tol`. Returns the\nintegral estimate and a vector of the nodes used.\n\"\"\"\nfunction intsing(f,tol)\n    x = t -> 2/(1+exp(2sinh(t)))\n\tdx_dt = t -> cosh(t)/cosh(sinh(t))^2\n\tg = t -> f(x(t))*dx_dt(t)\n\n    # Find where to truncate the integration interval.\n    M = 3\n    while abs(g(M)) > tol/100\n        M += 0.5\n        if iszero(x(M)) \n            @warn \"Function may grow too rapidly.\"\n            M -= 0.5\n            break\n        end\n    end\n\n    I,t = intadapt(g,0,M,tol)\n\treturn I,x.(t)\nend\n", "meta": {"hexsha": "a84103527153a439d209c30f85015261973b4f69", "size": 3947, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter09.jl", "max_stars_repo_name": "fncbook/FundamentalsNumericalComputation.jl", "max_stars_repo_head_hexsha": "39096a535832f04c8d3d8433b0edc29fc4350e14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-07-29T23:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T23:05:57.000Z", "max_issues_repo_path": "src/chapter09.jl", "max_issues_repo_name": "fncbook/FundamentalsNumericalComputation.jl", "max_issues_repo_head_hexsha": "39096a535832f04c8d3d8433b0edc29fc4350e14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chapter09.jl", "max_forks_repo_name": "fncbook/FundamentalsNumericalComputation.jl", "max_forks_repo_head_hexsha": "39096a535832f04c8d3d8433b0edc29fc4350e14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-22T18:40:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T18:40:18.000Z", "avg_line_length": 25.3012820513, "max_line_length": 72, "alphanum_fraction": 0.5502913605, "num_tokens": 1262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8688267762381843, "lm_q1q2_score": 0.795940560265751}}
{"text": "# # Multiple dispatch\n\n#-\n\n# **Multiple dispatch** is a key feature of Julia, that we will explore in this notebook.\n#\n# It helps make software fast. It also makes software extensible, programmable, and downright fun to play with.\n#\n# It may just herald a breakthrough for parallel computation.\n\n#-\n\n# 1. Roman numerals\n# 2. Functions\n# 3. Parallel computing\n\n#-\n\n# ## 1. Roman numerals (for fun)\n\n#-\n\n# Let's define a **new struct** that represents a Roman numeral. For coding simplicity, we'll just deal with numbers between 0 and 9.\n#\n# **Exercise**: Extend this to larger numbers. (Recall that Roman numbers are a base-10 system!)\n\nstruct Roman\n    n::Int\nend\n\nBase.show(io::IO, r::Roman) = print(io, 'ⅰ' + (r.n - 1) % 10 )  # nice display; 'ⅰ' is a Unicode Roman numeral\n\n# We can create an object of this type as follows:\n\nRoman(4)\n\n#-\n\ntypeof.([5 5.0 Roman(5) \"Five\" '5'  5//1])\n\n# We would like to display it nicely, in Roman numerals:\n\nx = [7 1 2 5 8 9]\nRoman.(x)   # equivalent to map(Roman, x)  or  [Roman(w) for w in x]\n\n# It'd be nice to be able to add Roman numerals together like normal numbers:\n\nRoman(4) + Roman(5)\n\n# But Julia doesn't know how to do that. Let's teach it by `import`ing the `+` function, which then allows us to _extend_ its definition:\n\nimport Base: +, *\n\n+(a::Roman, b::Roman) = Roman(a.n + b.n)\n\n#-\n\nRoman(4) + Roman(5)\n\n# This **adds a new method** to the function `+`:\n\nmethods(+)\n\n#-\n\nimport Base.*\n*(i::Roman, j::Roman) = Roman(i.n * j.n)                     # Multiply like a Roman\n\n#-\n\nRoman(3) * Roman(2)\n\n#-\n\nRoman.(1:3) .* [Roman(1) Roman(2) Roman(3)]\n\n# But\n\nRoman(3) * 2\n\n#-\n\n## Complicated mytimes to decide what to do based on type\n## not suggested, better way coming soon\nfunction mytimes(i,j)\n  if isa(i,Roman) & isa(j,Number)\n        return  fill(1, i.n, j)   # i by j matrix with ones\n    elseif    isa(i,Number) & isa(j,Roman)\n        return \"😄\"^ (i*j.n)   #  i * j happy faces\n    else\n        return(\"I Don't know\")\n    end\nend\n\n#-\n\nmytimes(4,Roman(3)) # Twelve happys\n\n#-\n\nmytimes(Roman(4),3) # 4x3 matrix with ones\n\n# The simplest thing to do is to explicitly define multiplication of a `Roman` by a number. We can do it as we see fit:\n\n*(i::Number, j::Roman) = \"😄\"^ (i*j.n)        #  i * j happy faces\n\n*(i::Roman, j::Number) =   fill(1, i.n, j)       # i by j matrix\n\n#-\n\n3 * Roman(3) # Nine happys\n\n#-\n\nRoman(3) * 5  # Three by Five matrix of ones\n\n#-\n\nt(x::Roman,y::Roman) = x.n * y.n\n\n#-\n\nt(Roman(5),Roman(4))\n\n#-\n\n##  Notice how tight the assembler is!\n@code_native t(Roman(2),Roman(4))\n\n# ## Functions\n\nimport Base: *, +, ^\n\n#-\n\n*(α::Number,   g::Function) = x -> α * g(x)   # Scalar times function\n\n*(f::Function, λ::Number)   = x -> f(λ * x)   # Scale the argument\n\n*(f::Function, g::Function) = x -> f(g(x))    # Function composition  -- abuse of notation!  use \\circ in Julia 0.6\n\n^(f::Function, n::Integer) = n == 1 ? f : f*f^(n-1) # A naive exponentiation algorithm by recursive multiplication\n\n#-\n\n+(f::Function, g::Function) = x -> f(x) + g(x)\n\n# For example, the exponential function is defined as\n#\n# $$\\exp(x) = \\sum_{n=0}^\\infty \\frac{1}{n!} x^n.$$\n#\n# We can think of this just in terms of functions:\n#\n# $$\\exp = \\sum_{n=0}^\\infty \\frac{1}{n!} \\mathrm{pow}_n,$$\n#\n# where $\\mathrm{pow}_n(x) = x^n$.\n#\n# (starts to blur the symbolic with the numerical!)\n\npow(n) = x -> x^n\n\nmyexp = sum(1/factorial(big(n)) * pow(n) for n in 0:100)   # taylor series not efficient!\n\n#-\n\n[myexp(1); exp(1); exp(big(1))]\n\n#-\n\nf = x -> x^2\nf(10)\n\n#-\n\ng = 3f\ng(10)\n\n#-\n\n(f^2)(10)  # since we defined multiplication of functions as composition\n\n#-\n\nusing Plots;\ngr()\n\n#-\n\nx = pi*(0:0.001:4)\n\nplot(x, sin.(x),    c=\"black\", label=\"Fun\")\nplot!(x, (12*sin).(x),    c=\"green\", label=\"Num * Fun\")\nplot!(x, (sin*12).(x),    c=\"red\", alpha=0.9, label=\"Fun * Num\")\nplot!(x, (5*sin*exp).(x), c=\"blue\", alpha=0.2, label=\"Num * Fun * Fun\")\n\n#-\n\nplot([12*sin, sin*12, 5*sin*exp], 0:.01:4π, α=[1 .9 .2], c=[:green :red :blue])\n\n# <img src=\"https://lh4.googleusercontent.com/--z5eKJbB7sg/UffjL1iAd4I/AAAAAAAABOc/S_wDVyDOBfQ/gauss.jpg\">\n\n#-\n\n# ###  \"Sin^2 phi is odious to me, even though Laplace made use of it; should  it be feared that sin^2 phi might become ambiguous, which would perhaps  never occur, or at most very rarely when speaking of sin(phi^2), well  then, let us write (sin phi)^2, but not sin^2 phi, which by analogy  should signify sin(sin phi).\" -- Gauss\n\nx=(0:.01:2) * pi;\n\nplot(x, (sin^2).(x), c=\"blue\")     # Squaring just works, y=sin(sin(x)), Gauss would be pleased!\nplot!(x, sin.(x).^2,  c=\"red\")\n\n# # Exercise\n\nh(a, b::Any) = \"fallback\"\nh(a::Number, b::Number) = \"a and b are both numbers\"\nh(a::Number, b) = \"a is a number\"\nh(a, b::Number) = \"b is a number\"\nh(a::Integer, b::Integer) = \"a and b are both integers\"\n\n#-\n\n## Try playing with h\n\n", "meta": {"hexsha": "5d03f28dc4877abdb14cd0b438f97bfdbc6c0512", "size": 4808, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Introduction to Julia/10.1.Multiple-dispatch.jl", "max_stars_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_stars_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2020-02-13T00:50:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T07:57:22.000Z", "max_issues_repo_path": "Courses/Introduction to Julia/10.1.Multiple-dispatch.jl", "max_issues_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_issues_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2019-10-30T16:22:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-26T20:02:43.000Z", "max_forks_repo_path": "Courses/Introduction to Julia/10.1.Multiple-dispatch.jl", "max_forks_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_forks_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2020-02-26T11:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T22:34:53.000Z", "avg_line_length": 21.5605381166, "max_line_length": 330, "alphanum_fraction": 0.6135607321, "num_tokens": 1636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.9019206699387733, "lm_q1q2_score": 0.7958799436400833}}
{"text": "using TriangleMesh\nusing Plots\nusing Triplot\nusing LinearAlgebra\nusing SparseArrays\nusing ForwardDiff\nusing UnPack  # for convenience @unpack macro\ninclude(\"./TriFEMUtils.jl\") # plotting and misc routines\n\npoly = polygon_unitSquare()\n# poly = polygon_regular(5)\npoly = polygon_Lshape()\nnum_refinements = 3\nmax_triangle_area = .05/(4^num_refinements)\nmesh = create_mesh(poly, quality_meshing=true,\n                   add_switches=\"penva\"*string(max_triangle_area)*\"q\") # switches\n\n# new problem\nf(x,y) = exp(sin(1+pi*x)*sin(pi*y))\non_Neumann(x,y)   = x ≈ 1 && y > 0 && y < .5 # right face x = 1 (excluding corners)\non_Dirichlet(x,y) = !on_Neumann(x,y) # Dirichlet boundary = everywhere else\nu_Dirichlet(x,y)  = 0.0\n∇u_dot_n(x,y)     = 0.0 # note that n = [1,0] on the Neumann face\nu0(x,y) = sin(pi*x)*sin(pi*y)\n\n# ordering of reference element vertices\n# 3\n# |`.\n# 1--2\nreference_vertices = [[-1,1,-1],[-1,-1,1]] # stored as [r,s]\nreference_face_indices = [[1,2],[2,3],[1,3]] # ordering of faces for the reference element\nref_elem_info = (;reference_face_indices,reference_vertices)\n\n# define reference basis functions\nλ1(r,s) = -(r+s)/2\nλ2(r,s) = (1+r)/2\nλ3(r,s) = (1+s)/2\nλ(r,s) = [λ1.(r,s) λ2.(r,s) λ3.(r,s)]\ndλr() = [-.5 .5 0.0]\ndλs() = [-.5 0.0 .5]\n\n# x,y = lists of vertices\nfunction compute_geometric_terms(x,y)\n    # dx(r,s)/dr = dλ1/dr*x1 + dλ2/dr*x2 + dλ3/dr*x3 = [dλ1/dr dλ2/dr dλ3/dr] * [x1; x2; x3]\n    dxdr,dydr = dλr()*x, dλr()*y\n    dxds,dyds = dλs()*x, dλs()*y\n    G = [dxdr dxds; dydr dyds] # G*r = x, r = inv(G)*x\n    J = det(G) # change of variables det(Jacobian) for integration\n    drdx, dsdx, drdy, dsdy = inv(G)\n    return J, drdx, dsdx, drdy, dsdy\nend\n\n# assemble stiffness matrix and RHS vector\nfunction assemble_FE_matrix(mesh)\n    VX,VY,EToV = unpack_mesh_info(mesh)\n    num_vertices = length(VX)\n    num_elements = size(EToV,2) # number of elements = of columns\n\n    # rq,sq,wq = 1/3,1/3,2.0\n    rq,sq,wq = [-2/3; 1/3; -2/3], [-2/3; -2/3; 1/3], 2/3 * ones(3) # 3 point rule - Gockenbach\n\n    A = spzeros(num_vertices, num_vertices)\n    M = spzeros(num_vertices, num_vertices)\n    b = zeros(num_vertices)\n    for e = 1:num_elements # loop through all elements\n        ids = EToV[:,e] # vertex ids = local to global index maps\n        xv,yv = VX[ids],VY[ids]\n\n        # compute geometric mappings\n        J,drdx,dsdx,drdy,dsdy = compute_geometric_terms(xv,yv)\n        dλdx = drdx*dλr() + dsdx*dλs() # dλr() = [dλ1/dr dλ2/dr dλ3/dr]\n        dλdy = drdy*dλr() + dsdy*dλs() # dλs() = [dλ1/ds dλ2/ds dλ3/ds]\n        reference_elem_area = 2.0\n        @. A[ids,ids] += J*reference_elem_area*(dλdx'*dλdx + dλdy'*dλdy) # (dλdx'*dλdx)_ij = dλj/dx * dλi/dx\n\n        # assemble mass matrix using quadrature: ∫ϕ_j * ϕ_i = integrals of quadratic\n        M[ids,ids] .+= J*reference_elem_area*(λ(rq,sq)'*Diagonal(wq)*λ(rq,sq)) # M = V^T * diag(weights) * V\n\n        # quadrature rule\n        xq,yq = map_triangle_pts(rq,sq,xv,yv)\n        b[ids] .+= J*λ(rq,sq)'*(wq.*f.(xq,yq))\n    end\n    return M,A,b\nend\n\nfunction compute_Neumann_BCs(mesh,ref_elem_info,on_Neumann_boundary,∇u_dot_n)\n\n    @unpack reference_face_indices, reference_vertices = ref_elem_info\n    VX,VY,EToV = unpack_mesh_info(mesh)\n    boundary_indices, boundary_faces = get_boundary_info(reference_face_indices, mesh)\n    # contributions from Neumann BCs\n\n    num_vertices = length(VX)\n    b = zeros(num_vertices)\n    for (f,e) in boundary_faces\n        ref_fids = reference_face_indices[f]\n        fids = EToV[ref_fids,e]\n        xf,yf = VX[fids],VY[fids]\n        x_mid,y_mid = sum(xf)/2,sum(yf)/2\n\n        if on_Neumann_boundary(x_mid,y_mid)\n            r,s = reference_vertices\n            r_mid, s_mid = sum(r[ref_fids])/2, sum(s[ref_fids])/2\n            w_mid = 2.0\n\n            ids = EToV[:,e]\n            face_length = sqrt((xf[1]-xf[2])^2 + (yf[1]-yf[2])^2)\n            b[ids] .+= face_length/2 * vec(λ(r_mid,s_mid)) * w_mid * ∇u_dot_n(x_mid,y_mid) # ∫ ∇u⋅n ϕ_i on each Neumann face\n        end\n    end\n    return b\nend\nfunction modify_matrix_Dirichlet_BCs!(A,mesh,ref_elem_info,on_Dirichlet_boundary)\n    @unpack reference_face_indices, reference_vertices = ref_elem_info\n    VX,VY,EToV = unpack_mesh_info(mesh)\n    boundary_indices, boundary_faces = get_boundary_info(reference_face_indices, mesh)\n\n    # impose Dirichlet BCs\n    for i in boundary_indices\n        xi,yi = VX[i],VY[i]\n        if on_Dirichlet_boundary(xi,yi)\n            A[:,i] .= 0\n            A[i,:] .= 0\n            A[i,i] = 1.0\n        end\n    end\nend\nfunction compute_Dirichlet_BCs(A,mesh,ref_elem_info,on_Dirichlet_boundary,u_Dirichlet)\n    @unpack reference_face_indices, reference_vertices = ref_elem_info\n    VX,VY,EToV = unpack_mesh_info(mesh)\n    boundary_indices, boundary_faces = get_boundary_info(reference_face_indices, mesh)\n\n    num_vertices = length(VX)\n    b = zeros(num_vertices)\n    # impose Dirichlet BCs\n    for i in boundary_indices\n        xi,yi = VX[i],VY[i]\n        if on_Dirichlet_boundary(xi,yi)\n            b -= Vector(A[:,i]*u_Dirichlet(xi,yi))\n        end\n    end\n    return b\nend\n# modifies the arguments\nfunction constrain_Dirichlet_nodes!(b,mesh,ref_elem_info,on_Dirichlet_boundary,u_Dirichlet)\n    @unpack reference_face_indices, reference_vertices = ref_elem_info\n    VX,VY,EToV = unpack_mesh_info(mesh)\n    boundary_indices, boundary_faces = get_boundary_info(reference_face_indices, mesh)\n\n    for i in boundary_indices\n        xi,yi = VX[i],VY[i]\n        if on_Dirichlet_boundary(xi,yi)\n            b[i] = u_Dirichlet(xi,yi)\n        end\n    end\nend\n\nM,A,b = assemble_FE_matrix(mesh)\n\n# set up timestepping parameters\nΔt = .001\nT = .5\n\n# create/prefactor Crank-Nicolson matrix\nC = (M + .5*Δt*A)\nmodify_matrix_Dirichlet_BCs!(C,mesh,ref_elem_info,on_Dirichlet)\nC = cholesky(Symmetric(C)) # speed up solution of C\\b\n\n# precompute BC contributions\nb_Neumann = compute_Neumann_BCs(mesh,ref_elem_info,on_Neumann,∇u_dot_n)\nb_Dirichlet = compute_Dirichlet_BCs(M+.5*Δt*A,mesh,ref_elem_info,on_Dirichlet,u_Dirichlet)\n\nNsteps = ceil(T/Δt)\nΔt = T/Nsteps\nVX,VY,EToV = unpack_mesh_info(mesh)\nu = u0.(VX,VY)\nplot()\nVX,VY,EToV = unpack_mesh_info(mesh) # for plotting\n@gif for i = 1:Nsteps\n    global u\n\n    # compute RHS\n    b = M*u - .5*Δt*A*u\n\n    # compute BC contributions\n    @. b += b_Neumann + b_Dirichlet # add BC contributions\n\n    # modify b_i = u[i]\n    constrain_Dirichlet_nodes!(b,mesh,ref_elem_info,on_Dirichlet,u_Dirichlet)\n\n    u = C \\ b\n\n    if i%5==0\n        println(\"on iter $i out of $Nsteps\")\n        triplot(VX,VY,u,EToV)\n    end\nend every 5\n\n# triplot(VX,VY,uexact.(VX,VY),EToV)\n", "meta": {"hexsha": "eefad56d4cfbde1ccaf191e568d3cdfff7307ade", "size": 6577, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "weeks11_to_12/fem_heat_2D.jl", "max_stars_repo_name": "jlchan/caam452_s21", "max_stars_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:38:43.000Z", "max_issues_repo_path": "weeks11_to_12/fem_heat_2D.jl", "max_issues_repo_name": "jlchan/caam452_s21", "max_issues_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "weeks11_to_12/fem_heat_2D.jl", "max_forks_repo_name": "jlchan/caam452_s21", "max_forks_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.885, "max_line_length": 124, "alphanum_fraction": 0.6554660179, "num_tokens": 2267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741322079104, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7958600072813419}}
{"text": "\"Test the null of normality using the Jarque-Bera test statistic.\"\nfunction jbtest(x::Vector)\n  n = length(x)\n  m1 = sum(x)/n\n  m2 = sum((x .- m1).^2)/n\n  m3 = sum((x .- m1).^3)/n\n  m4 = sum((x .- m1).^4)/n\n  b1 = (m3/m2^(3/2))^2\n  b2 = (m4/m2^2)\n  statistic = n * b1/6 + n*(b2 - 3)^2/24\n  d = Chisq(2.)\n  pvalue = 1. - cdf(d, statistic)\n  statistic, pvalue\nend\n", "meta": {"hexsha": "161deba686f2eade11ff806ee1be1667414ff4e6", "size": 362, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stattests.jl", "max_stars_repo_name": "UnofficialJuliaMirror/GARCH.jl-4d2f22df-77d7-5622-8d7f-1db4ec2bcc3a", "max_stars_repo_head_hexsha": "b2a9861b890e307ba125b9397db4f32c3ed68562", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-03-05T08:23:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T11:20:17.000Z", "max_issues_repo_path": "src/stattests.jl", "max_issues_repo_name": "UnofficialJuliaMirror/GARCH.jl-4d2f22df-77d7-5622-8d7f-1db4ec2bcc3a", "max_issues_repo_head_hexsha": "b2a9861b890e307ba125b9397db4f32c3ed68562", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-10-14T08:55:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-18T09:29:22.000Z", "max_forks_repo_path": "src/stattests.jl", "max_forks_repo_name": "AndreyKolev/GARCH.jl", "max_forks_repo_head_hexsha": "b2a9861b890e307ba125b9397db4f32c3ed68562", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2015-02-23T08:46:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:49:40.000Z", "avg_line_length": 24.1333333333, "max_line_length": 66, "alphanum_fraction": 0.5524861878, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741227833249, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7958600033093354}}
{"text": "using LinearAlgebra\r\n\r\n# k_local(Elastic Modulus,thickness,height,length,number of nodes,row one, row two, column one, column two)\r\n\r\n#creates local stiffness matrix and maps to global\r\nfunction k_local(k,l,n,r_1,r_2,c_1,c_2)\r\n    k_global = zeros(n,n)\r\n    k_global[r_1,c_1] = k\r\n    k_global[r_1,c_2] = -k\r\n    k_global[r_2,c_1] = -k\r\n    k_global[r_2,c_2] = k\r\n    return k_global\r\nend\r\n\r\n# constants from problem statement\r\nE = 29*10^6\r\nl = 2\r\nk1 = 50\r\nk2 = 60\r\nk3 = 55\r\n# combining all globally mapped matrices\r\nkG = k_local(k1,l,4,1,2,1,2)+\r\n     k_local(k2,l,4,2,3,2,3)+\r\n     k_local(k3,l,4,3,4,3,4)\r\nkG[4,:] = [0 0 0 1] #adjustment for Reaction from fixed end\r\n\r\n# Force Vector\r\nf = Float64[60 0 0 0]\r\nF = transpose(f)\r\n\r\n# Displacement vector\r\nu = kG\\F\r\nprintln(\"Nodal displacement vector (inches):\")\r\ndisplay(u)\r\n\r\n# Strain Function\r\nϵ(x2,x1,l) = (x2 - x1)/l\r\n\r\n#Strain Vector\r\nϵM = [ϵ(u[2],u[1],l)\r\n      ϵ(u[3],u[2],l) \r\n      ϵ(u[4],u[3],l) ]\r\nprintln(\"Element strain vector (inch/inch):\")\r\ndisplay(ϵM)\r\n\r\n# Stress Function\r\nσ(E,ϵ) = E*ϵ\r\n\r\n# Stress Vector\r\nσM = [σ(E,ϵM[1])\r\n      σ(E,ϵM[2])\r\n      σ(E,ϵM[3])]\r\nprintln(\"Element Stress vector (psi):\")\r\ndisplay(σM)\r\n\r\n", "meta": {"hexsha": "e2442d58ba7e3eba33b96774ac265b774fc4cff2", "size": 1183, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "trejo_nicholas_HW2.jl", "max_stars_repo_name": "UltraHeckerNick/MechanicalPrograms_small", "max_stars_repo_head_hexsha": "1059fb6c0d391be5ef75c4ba165e4f48819bfb2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trejo_nicholas_HW2.jl", "max_issues_repo_name": "UltraHeckerNick/MechanicalPrograms_small", "max_issues_repo_head_hexsha": "1059fb6c0d391be5ef75c4ba165e4f48819bfb2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trejo_nicholas_HW2.jl", "max_forks_repo_name": "UltraHeckerNick/MechanicalPrograms_small", "max_forks_repo_head_hexsha": "1059fb6c0d391be5ef75c4ba165e4f48819bfb2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.125, "max_line_length": 108, "alphanum_fraction": 0.6120033812, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574129515172, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7958600011295234}}
{"text": "import Distributions\nusing Plots\nusing Statistics\nusing Turing\nusing StatsPlots\n\nfunction invlogit(x)\n\treturn exp(x)/(1+exp(x))\nend\n\ndose = [-0.86,-0.3,-0.05,0.73]\nn = ones(4)*5\nnd = [0,1,3,5]\n\n@model function ld50_fit(dose,deaths,n)\n    α ~ Uniform(-4.0,6.0)\n    β ~ Uniform(-5.0,50)\n\tfor i in 1:length(dose)\n\t\tΘ = invlogit(α+β*dose[i])\n\t\tdeaths[i] ~ Binomial(n[i],Θ)\n\tend\nend\n    \nmodel1 = ld50_fit(dose,nd,n)\nchain = Turing.sample(model1,NUTS(0.65),1000)\n\nalpha = vec(chain[:α])\nbeta = vec(chain[:β])\n\nhistogram(alpha)\nhistogram(beta)\n\nld50 = -alpha ./ beta\n\nhistogram(ld50)\n\nmean(ld50)\nstd(ld50)\n", "meta": {"hexsha": "6f453c4c5915b3026f1e5e45b04d1720ee4cdfa7", "size": 600, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LD50_prob.jl", "max_stars_repo_name": "hstrey/BME-502-2022", "max_stars_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LD50_prob.jl", "max_issues_repo_name": "hstrey/BME-502-2022", "max_issues_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LD50_prob.jl", "max_forks_repo_name": "hstrey/BME-502-2022", "max_forks_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-15T18:19:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T18:26:08.000Z", "avg_line_length": 15.3846153846, "max_line_length": 45, "alphanum_fraction": 0.66, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731094431571, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7958532134113462}}
{"text": "#in this file, op_a and op_b are a,b operators in Barry's original paper.\n#H,V means horizontal and vertical\n#p means '(prime) for output modes\n\nusing SymPy\nusing Printf\nusing PyCall\nstruct QRelaySym{T<:Tuple}\n    aH::T\n    bH::T\n    aV::T\n    bV::T\n    apH::T\n    bpH::T\n    apV::T\n    bpV::T\nend\n\n\nfunction trans(op, a, b, ap, bp, B)\n    p = B * [ap; bp]\n    op = subs(op, a, p[1])\n    op = subs(op, b, p[2])\n    return op\nend\n\n#2D rotation matrix\nfunction rotmat(theta)\n    c = cos(theta)\n    s = sin(theta)\n    return [c s; -s c]\nend\n\n\nfunction qrelay_op(n, phi, alpha, delta)\n    #operators before BS\n    aH = symbols(@sprintf(\"a_H1:%d\", n+1))\n    bH = symbols(@sprintf(\"b_H1:%d\", n+1))\n    aV = symbols(@sprintf(\"a_V1:%d\", n+1))\n    bV = symbols(@sprintf(\"b_V1:%d\", n+1))\n    \n    op = 0\n    for i=1:n\n        op += phi[i] * (aH[i]*bH[i] + aV[i]*bV[i])\n    end\n\n    #beam splitter transformation\n    B = 1/sqrt(2)*[1 1;-1 1]\n    \n    #operators after beam splitter\n    apH = symbols(@sprintf(\"a'_H1:%d\", n+1))\n    bpH = symbols(@sprintf(\"b'_H1:%d\", n+1))\n    apV = symbols(@sprintf(\"a'_V1:%d\", n+1))\n    bpV = symbols(@sprintf(\"b'_V1:%d\", n+1))\n\n    for i=1:n-1\n        op = trans(op, bH[i], aH[i+1], bpH[i], apH[i+1], B)\n        op = trans(op, bV[i], aV[i+1], bpV[i], apV[i+1], B)\n    end\n\n    op = trans(op, aH[1], aV[1], apH[1], apV[1], rotmat(alpha))\n    op = trans(op, bH[n], bV[n], bpH[n], bpV[n], rotmat(delta))\n    \n    syms = QRelaySym(aH, bH, aV, bV, apH, bpH, apV, bpV)\n    \n    return syms, op\nend\n\nfunction op_mat(op)\n    op = op[:as_poly](domain=\"C\")\n    op_a = op.x[:gens]\n    nab = op[:length]()\n    op_ab = ones(SymPy.Sym, nab)\n    coef = zeros(Complex, nab)\n    mat = zeros(Int64, length(op_a), nab)\n    for (i, (ps, c)) in enumerate(op[:as_dict]())\n        for (j, p) in enumerate(ps)\n            mat[j, i] = p\n            op_ab[i] = op_a[j]^p * op_ab[i]\n        end\n        coef[i] = c\n    end\n   \n    return op_a, op_ab, mat, coef\nend", "meta": {"hexsha": "8864f8ff7a166baf2f9c7fa8205360325ed8f6f3", "size": 1961, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operateurs.jl", "max_stars_repo_name": "KristofferC/Quantum_Relay", "max_stars_repo_head_hexsha": "1a9f88d38a13ab901d99da7941a05b55e059dab0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/operateurs.jl", "max_issues_repo_name": "KristofferC/Quantum_Relay", "max_issues_repo_head_hexsha": "1a9f88d38a13ab901d99da7941a05b55e059dab0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/operateurs.jl", "max_forks_repo_name": "KristofferC/Quantum_Relay", "max_forks_repo_head_hexsha": "1a9f88d38a13ab901d99da7941a05b55e059dab0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0705882353, "max_line_length": 73, "alphanum_fraction": 0.5374808771, "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7958152701084915}}
{"text": "doc\"\"\"\n    Cauchy(μ, σ)\n\nThe *Cauchy distribution* with location `μ` and scale `σ` has probability density function\n\n$f(x; \\mu, \\sigma) = \\frac{1}{\\pi \\sigma \\left(1 + \\left(\\frac{x - \\mu}{\\sigma} \\right)^2 \\right)}$\n\n```julia\nCauchy()         # Standard Cauchy distribution, i.e. Cauchy(0.0, 1.0)\nCauchy(u)        # Cauchy distribution with location u and unit scale, i.e. Cauchy(u, 1.0)\nCauchy(u, b)     # Cauchy distribution with location u and scale b\n\nparams(d)        # Get the parameters, i.e. (u, b)\nlocation(d)      # Get the location parameter, i.e. u\nscale(d)         # Get the scale parameter, i.e. b\n```\n\nExternal links\n\n* [Cauchy distribution on Wikipedia](http://en.wikipedia.org/wiki/Cauchy_distribution)\n\n\"\"\"\nimmutable Cauchy <: ContinuousUnivariateDistribution\n    μ::Float64\n    σ::Float64\n\n    Cauchy(μ::Real, σ::Real) = (@check_args(Cauchy, σ > zero(σ)); new(μ, σ))\n    Cauchy(μ::Real) = new(μ, 1.0)\n    Cauchy() = new(0.0, 1.0)\nend\n\n@distr_support Cauchy -Inf Inf\n\n#### Parameters\n\nlocation(d::Cauchy) = d.μ\nscale(d::Cauchy) = d.σ\n\nparams(d::Cauchy) = (d.μ, d.σ)\n\n\n#### Statistics\n\nmean(d::Cauchy) = NaN\nmedian(d::Cauchy) = d.μ\nmode(d::Cauchy) = d.μ\n\nvar(d::Cauchy) = NaN\nskewness(d::Cauchy) = NaN\nkurtosis(d::Cauchy) = NaN\n\nentropy(d::Cauchy) = log4π + log(d.σ)\n\n\n#### Functions\n\nzval(d::Cauchy, x::Float64) = (x - d.μ) / d.σ\nxval(d::Cauchy, z::Float64) = d.μ + z * d.σ\n\npdf(d::Cauchy, x::Float64) = 1.0 / (π * scale(d) * (1.0 + zval(d, x)^2))\nlogpdf(d::Cauchy, x::Float64) = - (log1psq(zval(d, x)) + logπ + log(d.σ))\n\nfunction cdf(d::Cauchy, x::Float64)\n    μ, σ = params(d)\n    invπ * atan2(x - μ, σ) + 0.5\nend\n\nfunction ccdf(d::Cauchy, x::Float64)\n    μ, σ = params(d)\n    invπ * atan2(μ - x, σ) + 0.5\nend\n\nfunction quantile(d::Cauchy, p::Float64)\n    μ, σ = params(d)\n    μ + σ * tan(π * (p - 0.5))\nend\n\nfunction cquantile(d::Cauchy, p::Float64)\n    μ, σ = params(d)\n    μ + σ * tan(π * (0.5 - p))\nend\n\nmgf(d::Cauchy, t::Real) = t == zero(t) ? 1.0 : NaN\ncf(d::Cauchy, t::Real) = exp(im * (t * d.μ) - d.σ * abs(t))\n\n\n#### Fitting\n\n# Note: this is not a Maximum Likelihood estimator\nfunction fit{T<:Real}(::Type{Cauchy}, x::AbstractArray{T})\n    l, m, u = quantile(x, [0.25, 0.5, 0.75])\n    Cauchy(m, (u - l) / 2.0)\nend\n", "meta": {"hexsha": "155845380ca9faf5d466992e3b756b640701bce0", "size": 2245, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/cauchy.jl", "max_stars_repo_name": "ericproffitt/Distributions.jl", "max_stars_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/cauchy.jl", "max_issues_repo_name": "ericproffitt/Distributions.jl", "max_issues_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/cauchy.jl", "max_forks_repo_name": "ericproffitt/Distributions.jl", "max_forks_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8829787234, "max_line_length": 99, "alphanum_fraction": 0.595545657, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8499711699569786, "lm_q1q2_score": 0.7958152632599711}}
{"text": "using StatsBase: sample\nusing UnicodePlots: spy\nusing Printf\n\nabstract type SEM end\n\nstruct GaussianSEM <: SEM\n    p       ::Int64\n    B       ::Matrix{Float64}\n    err_var ::Vector{Float64}\n    function GaussianSEM(B, err_var)\n        @assert size(B, 1) == size(B, 2) == length(err_var)\n        @assert all(err_var .> 0)\n        p = length(err_var)\n        new(p, B, err_var)\n    end\nend\n\nfunction Base.show(io::IO, sem::GaussianSEM)\n    print(io, \"Gaussian SEM with $(sem.p) variables:\\n\")\n    print(io, \"B = \\n\")\n    print(io, spy(sem.B))\n    print(io, \"σ² = $(sem.err_var)\")\nend\n\n\"\"\"\n    simulate(sem, [n])\n    simulate(sem, [do_variables, do_values], [n])\n\nSimulate from a Gaussian SEM `sem`. `n` is the sample size.\ndo-interventions can be performed by specifying vectors of `do_variables` and `do_values`.\n\"\"\"\nfunction simulate(sem::GaussianSEM)\n    p = sem.p\n    ϵ = randn(p) .* sqrt.(sem.err_var)\n    return (I - sem.B) \\ ϵ\nend\n\nfunction simulate(sem::GaussianSEM, do_variables::Vector{Int64}, do_values::Vector{Float64})\n    @assert length(do_variables) == length(do_values)\n    p = sem.p\n    ϵ = randn(p) .* sqrt.(sem.err_var)\n    ϵ[do_variables] .= do_values\n    B = copy(sem.B)\n    B[do_variables, :] .= 0\n    return (I - B) \\ ϵ\nend\n\nfunction simulate(sem::GaussianSEM, n::Int64)\n    return vcat(map(i -> simulate(sem), 1:n)'...)\nend\n\nfunction simulate(sem::GaussianSEM, do_variables::Vector{Int64}, do_values::Vector{Float64}, n::Int64)\n    return vcat(map(i -> simulate(sem, do_variables, do_values), 1:n)'...)\nend\n\nfunction causes(sem::SEM, i::Int64)\n    @assert 1 <= i <= sem.p\n    return (1:sem.p)[sem.B[i, :].!=0]\nend\n\nfunction cov(sem::GaussianSEM)\n    S = inv(I - sem.B)\n    return S * diagm(sem.err_var) * S'\nend\n\n\"\"\"\n    random_gaussian_SEM(p, k; [lb=-2, ub=2, var_min=0.5, var_max=2])\n\nGenerate a random-graph acyclic SEM with `p` variables and `k` average degree, and random coefficients.\n* `lb`, `ub`: coeff  ~ unif[`lb`, `ub`] with random sign\n* `var_min`, `var_max`: var of error ~ unif[`var.min`, `var.max`]\n\"\"\"\nfunction random_gaussian_SEM(p::Int64, k::Int64; lb=-2, ub=2, var_min=0.5, var_max=2)\n    B = zeros(p, p)\n    B[rand(p, p) .< 2k / (p-1)] .= 1\n    B[UpperTriangular(B).!=0] .= 0\n    m = sum(B.==1)\n    B[B.==1] .= (rand(m) * (ub - lb) .+ lb) .* sign.(randn(m))\n    err_var = rand(p) * (var_max - var_min) .+ var_min\n    _order = sample(1:p, p, replace=false)\n    B = B[_order, _order]\n    return GaussianSEM(B, err_var)\nend\n\n\"\"\"\n    random_noise_intervened_SEM(sem::GaussianSEM, [p_intervened=2, noise_multiplier_min=0.5, noise_multiplier_max=2., avoid=[],\n                                                   prob_coeff_unchanged=2/3, lb=-2, ub=2])\n\nProduce a new SEM based on original SEM by changing coefficients and noise variances.\n* `p_intervened`: randomly choose `p_intervened` variables to intervene; will avoid those specified in `avoid`\n* [`noise_multiplier_min`, `noise_multiplier_max`]: interval that noise multiplier is uniformly sampled from\n* `prob.coeff.unchanged`: probability that coefficient is not changed\n* `[lb, ub]`: if to change, coefficient is drawn uniformly from this interval with random sign\n\nReturn: `sem_new`, `intervened_variables`\n\"\"\"\nfunction random_noise_intervened_SEM(sem::GaussianSEM;\n                                     p_intervened=2, noise_multiplier_min=0.5, noise_multiplier_max=2., avoid=[],\n                                     prob_coeff_unchanged=2/3, lb=-2, ub=2)\n    B = copy(sem.B)\n    p = sem.p\n    err_var = copy(sem.err_var)\n    vars = sample(setdiff(collect(1:p), avoid), p_intervened, replace=false)\n    for i in vars\n        noise_multiplier = rand() * (noise_multiplier_max - noise_multiplier_min) + noise_multiplier_min\n        err_var[i] = err_var[i] * noise_multiplier\n        if rand() > prob_coeff_unchanged\n            _J = (1:p)[B[i, :].!=0]\n            B[i, _J] .= rand(length(_J)) * (ub - lb) .+ lb\n        end\n    end\n    return GaussianSEM(B, err_var), vars\nend\n", "meta": {"hexsha": "6a9a473242a6cdb6ac03a1390fcd7ccbe29c554f", "size": 3970, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SEM.jl", "max_stars_repo_name": "richardkwo/InvariantCausal.jl", "max_stars_repo_head_hexsha": "5eedfa7749973fb33885f5a0c8a36565ede28c97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-06-18T09:12:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-25T18:23:52.000Z", "max_issues_repo_path": "src/SEM.jl", "max_issues_repo_name": "richardkwo/InvariantCausal", "max_issues_repo_head_hexsha": "5eedfa7749973fb33885f5a0c8a36565ede28c97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-09-04T16:44:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-06T12:32:58.000Z", "max_forks_repo_path": "src/SEM.jl", "max_forks_repo_name": "richardkwo/InvariantCausal", "max_forks_repo_head_hexsha": "5eedfa7749973fb33885f5a0c8a36565ede28c97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-01-09T21:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-25T18:23:54.000Z", "avg_line_length": 34.5217391304, "max_line_length": 127, "alphanum_fraction": 0.6317380353, "num_tokens": 1196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144265, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.795815258994548}}
{"text": "\"\"\"\n    crosscorrelate(series, template, [element_type=Float64], normalize_template=true)\n\nReturn the normalized cross-correlation between `series` and `template`. \n\nIf `series` is a vector of ``n`` elements and template a vector of ``N`` elements, \ncross-correlation will be a vector of ``n - N + 1`` elements of type `element_type`. \nThe element of cross-correlation ``χ_k`` is Pearson correlation coefficient between \n``x^{(k)}_i`` denoting the elements of `series` ``x_{i + k}`` and \nthe elements of `template` ``y_i``, with ``i = 1, 2, \\\\dots, N``\n\n``\nχ_k = \\\\frac{\\\\sum{\\\\left(x^{(k)}_i - μ_{x^{(k)}}\\\\right) \n\\\\left(y_i - μ_y\\\\right)}}{N σ_{x^{(k)}} σ_y} \\\\, ,\n``\n\nwhere ``μ`` and ``σ`` denotes the mean and variance respectively. \n\nIf `normalize_template` is set to false then `template` is assumed to have mean and std\nrespectively equal to 0.0 and 1.0.\n\nSee the [Wikipedia page](https://en.wikipedia.org/wiki/Cross-correlation#Normalization) \non cross-correlation for more details.\n\n# Examples\n\n```jldoctest\njulia> crosscorrelate(sin.(0:0.25pi:2pi), [1, 1+√2, 1])\n7-element Vector{Float64}:\n  0.23258781949447394\n  1.000000000000001\n  0.23258781949447402\n  7.401486830834377e-17\n -0.23258781949447394\n -1.0000000000000007\n -0.23258781949447394\n```\n\"\"\"\nfunction crosscorrelate(series::AbstractVector{T1}, template::AbstractVector{T2}, element_type::Type{T3}=Float64; \n    normalize_template=true) where {T1 <: Number, T2 <: Number, T3 <: AbstractFloat}\n    \n    if isempty(series)\n        throw(ArgumentError(\"Series must be a non-empty vector.\"))\n    elseif isempty(template)\n        throw(ArgumentError(\"Template must be a non-empty vector.\"))\n    elseif size(series) < size(template)\n        throw(DimensionMismatch(\"Template is longer than series.\"))\n    end\n\n    if normalize_template\n        template_mean, template_std = mean_and_std(template, corrected=false)\n        y = @. (template - template_mean) / template_std\n    else\n        y = template\n    end\n\n    N = length(template)\n    cc = Vector{element_type}(undef, length(series) - N + 1)\n    x = similar(y) \n    for n in eachindex(cc)\n        series_view = view(series, n:n + N - 1)\n        series_view_std = std(series_view, corrected=false)\n        @. x = series_view / series_view_std\n        cc[n] = dot(x, y) / N\n    end\n    cc\nend\n\n\"\"\"\n    maxfilter(x, tolerance)\n\nReturn a vector of the same size of `x` whose element at index `n` is the maximum \nof the elements of `x` which are at most `tolerance` apart from `x[n]` \n(i.e. in a window of at most `2 * tolerance + 1` elements).\n\n# Examples\n\n```jldoctest\njulia> maxfilter(sin.(0:0.25pi:2pi), 1)\n9-element Vector{Float64}:\n  0.7071067811865475\n  1.0\n  1.0\n  1.0\n  0.7071067811865476\n  1.2246467991473532e-16\n -0.7071067811865475\n -2.4492935982947064e-16\n -2.4492935982947064e-16\n```\n\"\"\"\nfunction maxfilter(x::AbstractVector, l)\n    y = similar(x)\n    for n in eachindex(x)\n        lower = max(n - l, firstindex(x))\n        upper = min(n + l, lastindex(x))\n        y[n] = maximum(view(x, lower:upper))\n    end\n    y\nend\n\n\"\"\"\n    stack(correlations, offsets)\n\nReturn the average cross-correlation after aligning `correlations`. \nEach cross-correlation `correlations[n]` is shifted to the right by `offsets[n]`.\n\n# Examples\n\n```jldoctest\njulia> stack([[0, 1.0, 0, 0], [0, 0, 1.0, 0]], [1, 2])\n3-element OffsetArray(::Vector{Float64}, 0:2) with eltype Float64 with indices 0:2:\n 0.0\n 1.0\n 0.0\n```\n\"\"\"\nfunction stack(correlations::AbstractVector{T1}, offsets::AbstractVector{T2}) where {T1 <: AbstractVector, T2 <: Integer}\n    if isempty(correlations)\n        throw(ArgumentError(\"Cross-correlations vector must be non-empty.\"))\n    elseif length(correlations) != length(offsets)\n        throw(DimensionMismatch(\"Cross-correlations and offsets vectors must have the same length.\"))\n    end\n    stackedcorrelations = OffsetVector.(correlations, -offsets)\n    start = maximum(series -> firstindex(series), stackedcorrelations)\n    stop = minimum(series -> lastindex(series), stackedcorrelations)\n    OffsetVector(mean(series -> view(series, start:stop), stackedcorrelations), start:stop)\nend\n\n\"\"\"\n    correlatetemplate(data, template, offsets, tolerance, [element_type=Float64])\n\nReturn the cross-correlation between `data` and `template`. The cross-correlations for each series \nare aligned using `offsets` and averaged. If `tolerance`` is not zero, then the average accounts for possible\nmisplacement of each series by `tolerance` sample, and return the average of the maximum cross-correlation \ncompatible with that misplacement.\n\"\"\"\nfunction correlatetemplate(data, template, offsets, tolerance, element_type=Float64)\n    if isempty(data)\n        throw(ArgumentError(\"Data must be non-empty.\"))\n    elseif !(length(data) == length(template) == length(offsets))\n        throw(DimensionMismatch(\"Data, template and shifts must have the same length.\"))\n    end\n    correlations = similar(data, Vector{element_type})\n    Threads.@threads for n = eachindex(data)\n        correlations[n] = maxfilter(crosscorrelate(data[n], template[n], element_type), tolerance)\n    end\n    stack(correlations, offsets)\nend", "meta": {"hexsha": "27c22d0c823839d98413d61a5cebbf4b8a6d305c", "size": 5126, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/crosscorrelation.jl", "max_stars_repo_name": "stefanocampanella/TemplateMatching.jl", "max_stars_repo_head_hexsha": "6a016534630a257f97012d8f73586b11d15747ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/crosscorrelation.jl", "max_issues_repo_name": "stefanocampanella/TemplateMatching.jl", "max_issues_repo_head_hexsha": "6a016534630a257f97012d8f73586b11d15747ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-08T09:45:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T09:45:59.000Z", "max_forks_repo_path": "src/crosscorrelation.jl", "max_forks_repo_name": "stefanocampanella/TemplateMatching.jl", "max_forks_repo_head_hexsha": "6a016534630a257f97012d8f73586b11d15747ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4026845638, "max_line_length": 121, "alphanum_fraction": 0.6937182989, "num_tokens": 1470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8652240930029117, "lm_q1q2_score": 0.7956968711140756}}
{"text": "using Statistics\nfunction demere(num::Int)\n    numrolls = 4\n    numsixes = 0\n    for run in 1:num\n        roll = rand(1:6, numrolls, 1)\n        if any( roll .== 6)\n            numsixes += 1\n        end\n    end\n    probsix = numsixes/num\n    return probsix\nend\n\nfunction roulette(k, t, num::Int)\n    p = 18/37\n    numruin = 0\n    numbet = 0\n    for run in 1:num\n        money = k\n        while money > 0 && money < t\n            if rand(1)[1] < p\n                money += 1\n            else\n                money -= 1\n            end\n            numbet += 1\n        end\n        if money == 0 \n            numruin += 1\n        end\n    end\n    probruin = numruin / num\n    averagebet = numbet / num\n    return probruin, averagebet\nend\n\nfunction hitmiss(f::Function, box = [0; 1], num=10000; fmin=0, fmax=1) \n   x = (box[2]-box[1]).*rand(num,1) .+ box[1]\n   y = (fmax-fmin).*rand(num,1) .+ fmin\n   rectarea = (fmax-fmin)*(box[2]-box[1])\n   prop = sum(y.<f.(x))/num\n   return prop*rectarea\nend\n\nfunction crudemc(f::Function, box = [0;1], num=10000)\n   x = (box[2]-box[1]).*rand(num,1) .+ box[1]\n   fmean = mean(f.(x))\n   return (box[2]-box[1])*fmean\nend", "meta": {"hexsha": "322342b8dce2e3e10b562af28f9448e2ef1be30b", "size": 1148, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stochasticsimulation.jl", "max_stars_repo_name": "hessianguo/NumericalMethod.jl", "max_stars_repo_head_hexsha": "bd6c00a88c8168e39b2ba1894466a6b6f6e24984", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stochasticsimulation.jl", "max_issues_repo_name": "hessianguo/NumericalMethod.jl", "max_issues_repo_head_hexsha": "bd6c00a88c8168e39b2ba1894466a6b6f6e24984", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stochasticsimulation.jl", "max_forks_repo_name": "hessianguo/NumericalMethod.jl", "max_forks_repo_head_hexsha": "bd6c00a88c8168e39b2ba1894466a6b6f6e24984", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.96, "max_line_length": 71, "alphanum_fraction": 0.5087108014, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849805, "lm_q2_score": 0.8652240704135291, "lm_q1q2_score": 0.7956968598677486}}
{"text": "#===============================================================================\n\nUsing a combination of black square tiles and oblong tiles chosen from: red\ntiles measuring two units, green tiles measuring three units, and blue tiles\nmeasuring four units, it is possible to tile a row measuring five units in\nlength in exactly fifteen different ways.\n\nHow many ways can a row measuring fifty units in length be tiled?\n\n===============================================================================#\n\nusing Memoize\nusing Base.Test\n\n@memoize function ncases_swb(rowlen)\n    # Return the number of cases starting with a block\n\n    ncases_swglb(2, rowlen) + ncases_swglb(3, rowlen) + ncases_swglb(4, rowlen)\nend\n\n@memoize function ncases_swglb(blocklen, rowlen)\n    # Return the number of cases starting with a block of a given length\n    if rowlen < blocklen\n        return 0\n    end\n\n    result = 1\n    # case for which there is only the starting block\n\n    rowlen -= blocklen\n    # account for the head block\n\n    for nspace = 0:rowlen-2\n        # nbr spaces allowed between first block and second one\n        result += ncases_swb(rowlen-nspace)\n    end\n\n    result\nend\n\nfunction ncases(rowlen)\n    result = 1\n    # No block at all\n\n    for nspace = 0:rowlen-2\n        # nbr spaces before first block\n        result += ncases_swb(rowlen-nspace)\n    end\n\n    result\nend\n\n@test ncases(5) == 15\n\n@printf(\"Euler 0117: %d\", ncases(50))\n", "meta": {"hexsha": "0c6b7a15b931ca91b807bacb0f08b69360e08d77", "size": 1432, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0117.jl", "max_stars_repo_name": "dpieroux/euler", "max_stars_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "0117.jl", "max_issues_repo_name": "dpieroux/euler", "max_issues_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0117.jl", "max_forks_repo_name": "dpieroux/euler", "max_forks_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5714285714, "max_line_length": 80, "alphanum_fraction": 0.6222067039, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.8807970826714614, "lm_q1q2_score": 0.7956189089378656}}
{"text": "### Load in with\n### include(download(\"https://raw.githubusercontent.com/mth229/MTH229.jl/master/src/229.jl\"))\n\nusing Pkg\npkg\"add SymPy SpecialFunctions Roots ForwardDiff Plots QuadGK\"\n\nusing Plots\nusing SpecialFunctions\n\nimport ForwardDiff\nimport QuadGK: quadgk\n\n\" f'(x) will find the derivative of `f` using Automatic Differentation from the `ForwardDiff` package \"\nBase.adjoint(f::Function) = x -> ForwardDiff.derivative(f, float(x))\nD(f, n=1) = n > 1 ? D(D(f), n-1) : x -> ForwardDiff.derivative(f, float(x))\n\n\"\"\"\nReturns a function describing the tangent line to the graph of f at x=c.\n\nExample. Where does the tangent line intersect the y axis?\n```\nf(x) = sin(x)\ntl(x) = tangent(f, pi/4)(x)  # or tl = tangent(f, pi/3) to use a non-generic function\ntl(0)\n```\n\nUses the automatic derivative of `f` to find the slope of the tangent line at `x=c`.\n\n\"\"\"\ntangent(f,c) = x -> f(c) + f'(c) * (x-c)\n\n\"\"\"\nReturns a function describing the secant line to the graph of f at x=a and x=b.\n\nExample. Where does the secant line intersect the y axis?\n```\nf(x) = sin(x)\na, b = pi/4, pi/3\nsl(x) = secant(f, a, b)(x)  # or sl = sl(f, a, b) to use a non-generic function\nsl(0)\n```\n\n\n\"\"\"\nsecant(f, a, b) = x -> f(a) + (f(b) - f(a)) / (b-a) * (x - a)\n\n\n\"\"\"\n\n`lim(f, c, n, dir=\"+\")`: means to generate numeric table of values of `f` as `h` gets close to `c`.\n\nExample:\n```\nf(x) = sin(x) / x\nlim(f, 0)\n```\n\"\"\"\nfunction lim(f::Function, c::Real; n::Int=6, dir=\"+\")\n\t hs = [(1/10)^i for i in 1:n] # close to 0\n\t if dir == \"+\"\n\t   xs = c .+ hs\n\t else\n\t   xs = c .- hs\n\t end\n\t ys = map(f, xs)\n\t [xs ys]\nend\n\n\n\"\"\"\n\nSimple implementation of the bisection method.\n\nExample:\n\n```julia\nbisection(sin, 3, 4)\nf(x) = x^5 - x^4 - x^3 - x^2 - x - 1\na = bisection(f, 1, 2)\nf(a)\n```\n\nThe display shows a simple graphic illustrating the method's division for the first few steps.\n\nAn easier-to-understand alternative to `Roots.find_zero(f, (a,b), Bisection())`.\n\n\n\"\"\"\nfunction bisection(f::Function, a, b)\n    a,b = sort([a,b])\n\n    if f(a) * f(b) > 0\n        error(\"[a,b] is not a bracket. A bracket means f(a) and f(b) have different signs!\")\n    end\n\n    M = a + (b-a) / 2\n\n\n    i, j = 0, 64\n    ss = fill(\"#\", 65)\n    ss[i+1]=\"a\"; ss[j+1]=\"b\"\n    println(\"\")\n    println(join(ss))\n    flag = true\n\n    while a < M < b\n        if flag && j-i == 1\n            ss = fill(\" \", 65)\n            ss[j:(j+1)] = \"⋮\"\n            println(join(ss))\n            println(\"\")\n            flag = false\n        end\n\n\n        if f(M) == 0.0\n            println(\"... exact answer found ...\")\n\t    break\n        end\n        ## update step\n\tif f(a) * f(M) < 0\n\t    a, b = a, M\n\n            if flag\n                j = div(i + j, 2)\n            end\n\n\n\telse\n\t    a, b = M, b\n\n            if flag\n                i = div(i + j, 2)\n            end\n\n\tend\n\n        if flag\n            ss = fill(\".\", 65)\n            ss[i+1]=\"a\"; ss[j+1]=\"b\"; ss[(i+2):j]=\"#\"\n            println(join(ss))\n        end\n\n        M = a + (b-a) / 2\n    end\n    M\nend\n\nimport Roots\nimport Roots: newton, find_zero, find_zeros\nnewton(f, fp, x0; kwargs...) = Roots.find_zero((f,fp), x0, Roots.Newton(); kwargs...)\nnewton(f, x0; kwargs...) = newton(f, D(f), x0; kwargs...)\nfzero(f, x0; kwargs...) = Roots.find_zero(f, x0; kwargs...)\nfzero(f, a, b; kwargs...) = Roots.find_zero(f, (a, b); kwargs...)\nfzeros(f, a, b; kwargs...) = Roots.find_zeros(f, a, b; kwargs...)\n\n\n# some plotting utilities\n\n\"\"\"\n   trimplot(f, a, b, c=20; kwargs...)\n\nPlot f over [a,b] but break graph if it exceeds c in absolute value.\n\"\"\"\nfunction trimplot(f, a, b, c=20; kwargs...)\n  xs = linspace(a, b, 251) #range(a, stop=b, length=251)\n  ys = f.(xs)\n\n  us, vs = Real[], Real[]\n  p = plot(us, vs, xlim=(a, b), legend=false, kwargs...)\n  for (x,y) in zip(xs, ys)\n    if abs(y) <= c\n       push!(us, x); push!(vs, y)\n    else\n      length(us) > 0 && plot!(p, us, vs, color=:blue)\n      empty!(us); empty!(vs)\n    end\n end\n length(us) > 0 && plot!(p, us, vs, color=:blue)\n p\nend\n\n\n\"\"\"\n    plotif(f, g, a, b)\n\nPlot f colored depending on g < 0 or not.\n\"\"\"\nfunction plotif(f, g, a, b)\n  plot([f, x -> g(x) > 0.0 ? f(x) : NaN], a, b, linewidth=5)\nend\n\n\"\"\"\n   signchart(f, a, b)\n\nPlot f over a,b with different color when negative.\n\"\"\"\nfunction signchart(f, a, b)\n    p = plotif(f, f, a, b)\n    plot!(p, zero)\n    p\nend\n\n\n# visualize newtons method\nfunction newton_vis(f, x0, a=Inf,b=-Inf; steps=5, kwargs...)\n    xs = Float64[x0]\n    for i in 1:steps\n        push!(xs, xs[end] - f(xs[end]) / f'(xs[end]))\n    end\n\n    m,M = extrema(xs)\n    m = min(m, a)\n    M = max(M, b)\n\n    p = plot(f, m, M; linewidth=3, legend=false, kwargs...)\n    plot!(p, zero, m, M)\n    for i in 1:steps\n        plot!(p, [xs[i],xs[i],xs[i+1]], [0,f(xs[i]), 0])\n        scatter!(p, xs[i:i],[0])\n    end\n    scatter!(p, [xs[steps+1]], [0])\n    p\nend\n\n\n\"\"\"\nriemann: compute Riemann sum approximations to a definite integral. As well, implement trapezoid and Simpson's rule.\n\nExample:\n```\nf(x) = exp(x^2)\nriemann(f, 0, 1, 1000)   # default right-Riemann sums\nriemann(f, 0, 1, 1000, method=\"left\")       # left sums\nriemann(f, 0, 1, x1000, method=\"trapezoid\")  # use trapezoid rule\nriemann(f, 0, 1, 1000, method=\"simpsons\")   # use Simpson's rule\n```\n\n\"\"\"\nfunction riemann(f::Function, a::Real, b::Real, n::Int; method=\"right\")\n  if method == \"right\"\n     meth = (f,l,r) -> f(r) * (r-l)\n  elseif method == \"left\"\n     meth= (f,l,r) -> f(l) * (r-l)\n  elseif method == \"trapezoid\"\n     meth = (f,l,r) -> (1/2) * (f(l) + f(r)) * (r-l)\n  elseif method == \"simpsons\"\n     meth = (f,l,r) -> (1/6) * (f(l) + 4*(f((l+r)/2)) + f(r)) * (r-l)\n  end\n\n  xs = a + (0:n) * (b-a)/n\n  as = [meth(f, l, r) for (l,r) in zip(xs[1:end-1], xs[2:end])]\n  sum(as)\nend\n", "meta": {"hexsha": "c3c90155b55b3956ce6111d5835de76a5c660574", "size": 5698, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/229.jl", "max_stars_repo_name": "josephmaher/mth229-jm", "max_stars_repo_head_hexsha": "a0c998a001c6e0163fcb19b76af88a96cd813ce6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/229.jl", "max_issues_repo_name": "josephmaher/mth229-jm", "max_issues_repo_head_hexsha": "a0c998a001c6e0163fcb19b76af88a96cd813ce6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/229.jl", "max_forks_repo_name": "josephmaher/mth229-jm", "max_forks_repo_head_hexsha": "a0c998a001c6e0163fcb19b76af88a96cd813ce6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3450980392, "max_line_length": 116, "alphanum_fraction": 0.5428220428, "num_tokens": 2004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488299, "lm_q2_score": 0.9032942151647513, "lm_q1q2_score": 0.7956189024449825}}
{"text": "\"\"\"\n    BoolDistribution(p_true)\n\nCreate a distribution over Boolean values (`true` or `false`).\n\n`p_true` is the probability of the `true` outcome; the probability of `false` is 1-`p_true`.\n\"\"\"\nstruct BoolDistribution\n    p::Float64 # probability of true\nend\n\npdf(d::BoolDistribution, s::Bool) = s ? d.p : 1.0-d.p\n\nrand(rng::AbstractRNG, d::BoolDistribution) = rand(rng) <= d.p\n\nBase.iterate(d::BoolDistribution) = ((d.p, true), true)\nfunction Base.iterate(d::BoolDistribution, state::Bool)\n    if state\n        return  ((1.0 - d.p, false), false)\n    else\n        return nothing\n    end\nend    \n\nsupport(d::BoolDistribution) = [true, false]\n\n==(d1::BoolDistribution, d2::BoolDistribution) = d1.p == d2.p\n\nBase.hash(d::BoolDistribution) = hash(d.p)\n\nBase.length(d::BoolDistribution) = 2\n", "meta": {"hexsha": "4b0b26d4e8fc878ea9ec92c36522c03a1fbb1a32", "size": 788, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distributions/bool.jl", "max_stars_repo_name": "JuliaDocsForks/POMDPModelTools.jl", "max_stars_repo_head_hexsha": "c4b9e3150d8634d041f8ba25c0ab5fc290040fc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distributions/bool.jl", "max_issues_repo_name": "JuliaDocsForks/POMDPModelTools.jl", "max_issues_repo_head_hexsha": "c4b9e3150d8634d041f8ba25c0ab5fc290040fc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distributions/bool.jl", "max_forks_repo_name": "JuliaDocsForks/POMDPModelTools.jl", "max_forks_repo_head_hexsha": "c4b9e3150d8634d041f8ba25c0ab5fc290040fc7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.625, "max_line_length": 92, "alphanum_fraction": 0.6725888325, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810525948927, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7955480463932355}}
{"text": "# Julia translation of http://nbviewer.jupyter.org/github/barbagroup/AeroPython/blob/master/lessons/01_Lesson01_sourceSink.ipynb\n# Lession 1 Source and sink\n\nusing PyPlot\nusing Distributions\n\nclose(\"all\")\nmeshgrid(x,y) = (repmat(x',length(y),1),repmat(y,1,length(x)))\n\nN = 40                                # number of points in each direction\nx_start, x_end = -2.0, 2.0            # boundaries in the x-direction\ny_start, y_end = -1.0, 1.0            # boundaries in the y-direction\nx = linspace(x_start, x_end, N)    # creates a 1D-array with the x-coordinates\ny = linspace(y_start, y_end, N)    # creates a 1D-array with the y-coordinates\n\n# print(\"x = \", x)\n# print(\"y = \", y)\n\n\n\nX,Y=meshgrid(x,y)\n# X = repmat(x',N,1)\n# Y= repmat(y,1,N)\n\n# plots the grid of points\nsize = 10\nPyPlot.figure(figsize=(size, (y_end-y_start)/(x_end-x_start)*size))\nPyPlot.xlabel('x', fontsize=16)\nPyPlot.ylabel('y', fontsize=16)\nPyPlot.xlim(x_start, x_end)\nPyPlot.ylim(y_start, y_end)\nPyPlot.scatter(X, Y)\n\nstrength_source = 5.0                      # source strength\nx_source, y_source = -1.0, 0.0             # location of the source\n\n# computes the velocity field on the mesh grid\n\nu_source = strength_source/(2*pi) .* (X-x_source)./((X-x_source).^2 + (Y-y_source).^2)\nv_source = strength_source/(2*pi) .* (Y-y_source)./((X-x_source).^2 + (Y-y_source).^2)\n\n# plotting the streamlines\nsize = 10\nPyPlot.figure(figsize=(size, (y_end-y_start)/(x_end-x_start)*size))\nPyPlot.xlabel('x', fontsize=16)\nPyPlot.ylabel('y', fontsize=16)\nPyPlot.xlim(x_start, x_end)\nPyPlot.ylim(y_start, y_end)\nPyPlot.streamplot(X, Y, u_source, v_source, density=2, linewidth=1, arrowsize=2, arrowstyle=\"->\")\nPyPlot.scatter(x_source, y_source, color=\"#CD2305\", s=80, marker=\"o\", linewidth=0);\n\nstrength_sink = -5.0                     # strength of the sink\nx_sink, y_sink = 1.0, 0.0                # location of the sink\n\n# computes the velocity on the mesh grid\nu_sink = strength_sink/(2*pi) .* (X-x_sink)./((X-x_sink).^2 + (Y-y_sink).^2)\nv_sink = strength_sink/(2*pi) .* (Y-y_sink)./((X-x_sink).^2 + (Y-y_sink).^2)\n\n# plots the streamlines\nsize = 10\nPyPlot.figure(figsize=(size, (y_end-y_start)/(x_end-x_start)*size))\nPyPlot.xlabel('x', fontsize=16)\nPyPlot.ylabel('y', fontsize=16)\nPyPlot.xlim(x_start, x_end)\nPyPlot.ylim(y_start, y_end)\nPyPlot.streamplot(X, Y, u_sink, v_sink, density=2, linewidth=1, arrowsize=2, arrowstyle=\"->\")\nPyPlot.scatter(x_sink, y_sink, color=\"#CD2305\", s=80, marker=\"o\", linewidth=0);\n\n# computes the velocity of the pair source/sink by superposition\nu_pair = u_source + u_sink\nv_pair = v_source + v_sink\n\n# plots the streamlines of the pair source/sink\nsize = 10\nPyPlot.figure(figsize=(size, (y_end-y_start)/(x_end-x_start)*size))\nPyPlot.xlabel('x', fontsize=16)\nPyPlot.ylabel('y', fontsize=16)\nPyPlot.xlim(x_start, x_end)\nPyPlot.ylim(y_start, y_end)\nPyPlot.streamplot(X, Y, u_pair, v_pair, density=2.0, linewidth=1, arrowsize=2, arrowstyle=\"->\")\nPyPlot.scatter([x_source, x_sink], [y_source, y_sink],\n             color=\"#CD2305\", s=80, marker=\"o\", linewidth=0);\n", "meta": {"hexsha": "4b453ea13d2d7ef16cfa21ee0326eb5ae35e076a", "size": 3052, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Lesson1_SourceSink.jl", "max_stars_repo_name": "moore54/JuliaPotentialFlowTranslations", "max_stars_repo_head_hexsha": "2aad7750c23057518ca988ba4a02a4c99f4fde5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lesson1_SourceSink.jl", "max_issues_repo_name": "moore54/JuliaPotentialFlowTranslations", "max_issues_repo_head_hexsha": "2aad7750c23057518ca988ba4a02a4c99f4fde5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lesson1_SourceSink.jl", "max_forks_repo_name": "moore54/JuliaPotentialFlowTranslations", "max_forks_repo_head_hexsha": "2aad7750c23057518ca988ba4a02a4c99f4fde5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7710843373, "max_line_length": 128, "alphanum_fraction": 0.6802096986, "num_tokens": 945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810451666346, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.795548045855139}}
{"text": "include(\"orthopoly_evaluate.jl\")\nfunction compute_hermite(n, x, all=true);\n    # Evaluate Orthonormalized Hermite polynomials at x\n    # Physicists Hermite:\n    #       w(x)=exp(-x^2) with integral sqrt(pi)\n    #       Equivalent Mathematica: HermiteH[n,x]/Sqrt[Sqrt[Pi]*n!*2^n] \n    # Probabilists Hermite:\n    #       w(x)=exp(-x^2/2) with integral sqrt(2*pi)\n    #       Equivalent Mathematica: HermiteH[n,x/Sqrt[2]]/Sqrt[Sqrt[Pi]*n!*2^(1/2+n)]\n    \n    ## Physicists Hermite Tridiagonal matrix (w=exp(-x^2))\n    T = diagm(sqrt((1:n)/2),1) # n+1 by n+1 matrix \n    T = T+T'\n    c = sqrt(pi) #Integral of weight function\n    ## Probabilists Hermite Tridiagonal matrix (w=exp(-x^2/2))\n    # T = diagm(sqrt((1:n)),1) # n+1 by n+1 matrix\n    # T = T+T'\n    # c = sqrt(2*pi)\n    ## Default to 0 through n computation\n    if all\n        phi = orthopoly_evaluate_all(T, x)\n    else\n        phi = orthopoly_evaluate_n(T, x)\n    end\n    phi/sqrt(c)\nend\n", "meta": {"hexsha": "0a012d23094c1337793b52bee855c804f2ee956c", "size": 947, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demos/book/5/compute_hermite.jl", "max_stars_repo_name": "shashi/RandomMatrices.jl", "max_stars_repo_head_hexsha": "603b9e9acd95133839e804d6ef068cdfee4cbbfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2017-09-29T08:46:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T10:05:30.000Z", "max_issues_repo_path": "demos/book/5/compute_hermite.jl", "max_issues_repo_name": "shashi/RandomMatrices.jl", "max_issues_repo_head_hexsha": "603b9e9acd95133839e804d6ef068cdfee4cbbfb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2017-08-18T19:50:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-15T08:08:44.000Z", "max_forks_repo_path": "demos/book/5/compute_hermite.jl", "max_forks_repo_name": "shashi/RandomMatrices.jl", "max_forks_repo_head_hexsha": "603b9e9acd95133839e804d6ef068cdfee4cbbfb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2018-01-05T22:05:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T20:25:41.000Z", "avg_line_length": 35.0740740741, "max_line_length": 85, "alphanum_fraction": 0.600844773, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474207360066, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.795531173574673}}
{"text": "#Special named numbers and symbols\n\nexport bellnum,\n    catalannum,\n    lobbnum,\n    narayana,\n    fibonaccinum,\n    jacobisymbol,\n    lassallenum,\n    legendresymbol,\n    lucasnum,\n    stirlings1,\n    stirlings2,\n    dealnnoy\n\n\"\"\"\n    bellnum(n)\n\nCompute the ``n``th Bell number.\n\"\"\"\nfunction bellnum(n::Integer)\n    if n < 0\n        throw(DomainError(n))\n    elseif n < 2\n        return 1\n    end\n    list = Vector{BigInt}(undef, n)\n    list[1] = 1\n    for i = 2:n\n        for j = 1:i - 2\n            list[i - j - 1] += list[i - j]\n        end\n        list[i] = list[1] + list[i - 1]\n    end\n    return list[n]\nend\n\n\n\"\"\"\n    catalannum(n)\n\nCompute the ``n``th Catalan number.\n\"\"\"\nfunction catalannum(bn::Integer)\n    if bn < 0\n        throw(DomainError(bn, \"n must be nonnegative\"))\n    else\n        n = BigInt(bn)\n    end\n    div(binomial(2*n, n), (n + 1))\nend\n\n\"\"\"\n    lobbnum(m,n)\n\nCompute the Lobb number `L(m,n)`, or the generalised Catalan number given by ``\\\\frac{2m+1}{m+n+1} \\\\binom{2n}{m+n}``.\nWikipedia : https://en.wikipedia.org/wiki/Lobb_number\n\"\"\"\nfunction lobbnum(bm::Integer,bn::Integer)\n    if !(0 <= bm <= bn)\n        throw(DomainError(\"m and n must be non-negative\"))\n    else\n        m = BigInt(bm)\n        n = BigInt(bn)\n    end\n    div(binomial(2*n, m + n)*(2*m + 1), (m + n + 1))\nend\n\n\"\"\"\n    narayana(n,k)\n\nCompute the Narayana number `N(n,k)`` given by ``\\\\frac{1}{n}\\\\binom{n}{k}\\\\binom{n}{k-1}``\nWikipedia : https://en.wikipedia.org/wiki/Narayana_number\n\"\"\"\nfunction narayana(bn::Integer,bk::Integer)\n    if !(1 <= bk <= bn)\n        throw(DomainError(\"Domain is 1 <= k <= n\"))\n    else\n        n = BigInt(bn)\n        k = BigInt(bk)\n    end\n    div(binomial(n, k)*binomial(n, k - 1) , n)\nend\n\nfunction fibonaccinum(n::Integer)\n    if n < 0\n        throw(DomainError(n, \"n must be nonnegative\"))\n    end\n    z = Ref{BigInt}(0)\n    ccall((:__gmpz_fib_ui, :libgmp), Cvoid, (Ref{BigInt}, UInt), z, UInt(n))\n    return z[]\nend\n\n\nfunction jacobisymbol(a::Integer, b::Integer)\n    ba = Ref{BigInt}(a)\n    bb = Ref{BigInt}(b)\n    return ccall((:__gmpz_jacobi, :libgmp), Cint, (Ref{BigInt}, Ref{BigInt}), ba, bb)\nend\n\n\"\"\"\n    lassallenum(n)\n\nCompute the ``n``th entry in Lassalle's sequence, OEIS entry A180874.\n\"\"\"\nfunction lassallenum(m::Integer)\n    A = ones(BigInt, m)\n    for n = 2:m\n        A[n] = (-1)^(n-1) * (catalannum(n) + sum(j->(-1)^j*binomial(2n-1, 2j-1)*A[j]*catalannum(n-j), 1:n-1))\n    end\n    A[m]\nend\n\nfunction legendresymbol(a::Integer, b::Integer)\n    ba = Ref{BigInt}(a)\n    bb = Ref{BigInt}(b)\n    return ccall((:__gmpz_legendre, :libgmp), Cint, (Ref{BigInt}, Ref{BigInt}), ba, bb)\nend\n\nfunction lucasnum(n::Integer)\n    if n < 0\n        throw(DomainError(n, \"n must be nonnegative\"))\n    end\n    z = Ref{BigInt}(0)\n    ccall((:__gmpz_lucnum_ui, :libgmp), Cvoid, (Ref{BigInt}, UInt), z, UInt(n))\n    return z[]\nend\n\nfunction stirlings1(n::Int, k::Int, signed::Bool=false)\n    if signed == true\n        return (-1)^(n - k) * stirlings1(n, k)\n    end\n\n    if n < 0\n        throw(DomainError(n, \"n must be nonnegative\"))\n    elseif n == k == 0\n        return 1\n    elseif n == 0 || k == 0\n        return 0\n    elseif n == k\n        return 1\n    elseif k == 1\n        return factorial(n-1)\n    elseif k == n - 1\n        return binomial(n, 2)\n    elseif k == n - 2\n        return div((3 * n - 1) * binomial(n, 3), 4)\n    elseif k == n - 3\n        return binomial(n, 2) * binomial(n, 4)\n    end\n\n    return (n - 1) * stirlings1(n - 1, k) + stirlings1(n - 1, k - 1)\nend\n\nfunction stirlings2(n::Int, k::Int)\n    if n < 0\n        throw(DomainError(n, \"n must be nonnegative\"))\n    elseif n == k == 0\n        return 1\n    elseif n == 0 || k == 0\n        return 0\n    elseif k == n - 1\n        return binomial(n, 2)\n    elseif k == 2\n        return 2^(n-1) - 1\n    end\n\n    return k * stirlings2(n - 1, k) + stirlings2(n - 1, k - 1)\nend\n\n\"\"\"\nDelannoy number  describes the number of paths from the southwest corner (0, 0) of a rectangular grid\nto the northeast corner (m, n), using only single steps north, northeast, or east\n\"\"\"\nfunction dealnnoy(m::Integer,n::Integer)\n    if m<0\n        throw(DomainError(m, \"m must be nonnegative\"))\n    end\n    if n<0\n        throw(DomainError(n, \"n must be nonnegative\"))\n    end\n    A = ones(BigInt, m+1, n+1)\n    for i = 1:m+1\n        A[i,1] = 1\n    end\n    for i = 1:n+1\n        A[1,i] = 1\n    end\n    for i = 2:m+1\n        for j = 2:n+1\n            A[i,j] = A[i-1,j] + A[i-1,j-1] + A[i,j-1]\n        end\n    end\n    return(A[m+1,n+1])\nend\n", "meta": {"hexsha": "d38417fbbf747ede30e012f01d7552ab10eb44c9", "size": 4512, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/numbers.jl", "max_stars_repo_name": "krish8484/Combinatorics.jl", "max_stars_repo_head_hexsha": "b5ab4d0c586edf13c5db010171c6347455a10231", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/numbers.jl", "max_issues_repo_name": "krish8484/Combinatorics.jl", "max_issues_repo_head_hexsha": "b5ab4d0c586edf13c5db010171c6347455a10231", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/numbers.jl", "max_forks_repo_name": "krish8484/Combinatorics.jl", "max_forks_repo_head_hexsha": "b5ab4d0c586edf13c5db010171c6347455a10231", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0204081633, "max_line_length": 118, "alphanum_fraction": 0.5562943262, "num_tokens": 1605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7955207874398431}}
{"text": "using Distributed\nusing Distributions\n\nnb_draws = 100000\n\nfunction inside_circle(x::Float64, y::Float64)\n    output = 0\n    if x^2 + y^2 <= 1\n\toutput = 1\n    end\n    return output\nend\n\nfunction pi_serial(nbPoints::Int64 = 128 * 1000; d=Uniform(-1.0,1.0))\n\n   #draw NbPoints from within the square centered in 0\n   #with side length equal to 2\n   xDraws = rand(d, nbPoints)\n   yDraws = rand(d, nbPoints)\n   sumInCircle = 0\n\n   for (xValue, yValue) in zip(xDraws, yDraws)\n\tsumInCircle+=inside_circle(xValue, yValue)\n   end\n\n   return 4*sumInCircle/nbPoints\n\nend\n\npi_approx = pi_serial(nb_draws);\n\n\nprintln(\"Approximation for Pi $(pi_approx) with $(nb_draws) random draws\")\nprintln(\"True value is $(pi)\")\n\n\n", "meta": {"hexsha": "3a0bea24c21e9db1632355445f24abd979e98241", "size": 704, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia-app/app.jl", "max_stars_repo_name": "JulienPascal/MyFirstDockerApp", "max_stars_repo_head_hexsha": "2b44c68460aedc960ac8a7e47287784d534c08b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia-app/app.jl", "max_issues_repo_name": "JulienPascal/MyFirstDockerApp", "max_issues_repo_head_hexsha": "2b44c68460aedc960ac8a7e47287784d534c08b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia-app/app.jl", "max_forks_repo_name": "JulienPascal/MyFirstDockerApp", "max_forks_repo_head_hexsha": "2b44c68460aedc960ac8a7e47287784d534c08b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.027027027, "max_line_length": 74, "alphanum_fraction": 0.6960227273, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7955207859735565}}
{"text": "\"\"\"\n    simplex_projection_and_support(z)\n\nCompute the Euclidean projection onto the probability simplex and the set of indices where it is nonzero.\n\nSee <https://arxiv.org/abs/1602.02068> for details.\n\"\"\"\nfunction simplex_projection_and_support(z::AbstractVector{R}) where {R<:Real}\n    d = length(z)\n    z_sorted = sort(z; rev=true)\n    z_sorted_cumsum = cumsum(z_sorted)\n    k = maximum(j for j in 1:d if (1 + j * z_sorted[j]) > z_sorted_cumsum[j])\n    τ = (z_sorted_cumsum[k] - 1) / k\n    p = Vector{R}(undef, d)\n    s = Vector{Int}(undef, d)\n    for i in 1:d\n        p[i] = max(z[i] - τ, zero(R))\n        s[i] = Int(!iszero(p[i]))\n    end\n    return p, s\nend;\n\n\"\"\"\n    simplex_projection(z)\n\nCompute the Euclidean projection onto the probability simplex.\n\"\"\"\nfunction simplex_projection(z::AbstractVector{<:Real})\n    p, _ = simplex_projection_and_support(z)\n    return p\nend;\n\n\"\"\"\n    rrule(::typeof(simplex_projection), z)\n\nCustom reverse rule for [`simplex_projection`](@ref) which bypasses the sorting step.\n\nSee <https://arxiv.org/abs/1602.02068> for details.\n\"\"\"\nfunction ChainRulesCore.rrule(::typeof(simplex_projection), z::AbstractVector{<:Real})\n    p, s = simplex_projection_and_support(z)\n    S = sum(s)\n    function simplex_projection_pullback(dp)\n        vjp = s .* (dp .- (dp's) / S)\n        return (NoTangent(), vjp)\n    end\n    return p, simplex_projection_pullback\nend;\n", "meta": {"hexsha": "d099eca75540f4ca3df51339782ad8ebf183889c", "size": 1393, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simplex.jl", "max_stars_repo_name": "gdalle/ImplicitDifferentiation.jl", "max_stars_repo_head_hexsha": "19f68d94c754e2bb2ef370e31b0b6aa2ac1a00f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2022-03-29T14:06:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:10:49.000Z", "max_issues_repo_path": "src/simplex.jl", "max_issues_repo_name": "gdalle/ImplicitDifferentiation.jl", "max_issues_repo_head_hexsha": "19f68d94c754e2bb2ef370e31b0b6aa2ac1a00f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2022-03-30T10:29:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T07:23:57.000Z", "max_forks_repo_path": "src/simplex.jl", "max_forks_repo_name": "gdalle/ImplicitDifferentiation.jl", "max_forks_repo_head_hexsha": "19f68d94c754e2bb2ef370e31b0b6aa2ac1a00f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4285714286, "max_line_length": 105, "alphanum_fraction": 0.6683417085, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7955207790443876}}
{"text": "function nmex(a::Matrix{Float64}, x::Vector{Float64};\n    tol::Float64=1.0e-10, limit::Int64=1000, show=0)\n    \n  iters = 0\n  n = size(a, 1)\n  converged = false\n  local big\n  while true\n    iters += 1\n    x1 = a * x\n    big = 0.0\n    for i in 1:n\n      abs(x1[i]) > abs(big) && (big = x1[i])\n    end\n    x1 = x1 / big\n    (checkit(x1, x, tol) || (iters == limit)) && break\n    x = x1\n    iters <= show && println(\"$iters $big $x\")\n  end\n  l2 = norm(x1)\n  x1 = x1 / l2\n  (iters, big, x1)\nend\n", "meta": {"hexsha": "baeb630a9ed4100c4623f470e6727fea8db18e25", "size": 491, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nmlib/nmex.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "src/nmlib/nmex.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "src/nmlib/nmex.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 20.4583333333, "max_line_length": 54, "alphanum_fraction": 0.5193482688, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7954989178015602}}
{"text": "M, ΔM = 0.0266, 0.0001\nL, ΔL = 0.380, 0.001\nL1,ΔL1= 0.025, 0.001\nL2,ΔL2= 0.190, 0.001\nd,Δd= 0.008,0.001\n\nm,Δm = 0.0753, 0.0001\nh,Δh = 0.02, 0.001\nde,Δde = 0.025, 0.001\ndi,Δdi = 0.008, 0.001\n\n# Barra\n\nIh = (1/12)*M*L^2 + (1/16)*M*de^2\nΔIh = (1/12)*(ΔM*L^2 + 2*M*L*ΔL) + (1/16)*(ΔM*d + 2*M*d*Δd)\n\nIh_eixo = Ih + M*(L2 - L1)^2\nΔIh_eixo = ΔIh + ΔM*(L2-L1)^2 + 2*M*(L2-L1)*(ΔL2+ΔL1)\n\n\n\n# Cilindro\n\nIcl = (1/16)*m*(de^2 + di^2) +  (1/12)*m*h^2\nΔIcl = (1/16)*(Δm*(de^2+di^2) + 2*m*(de*Δde+di*Δdi)) + (1/12)*(Δm*h^2 + 2*m*h*Δh)\n\nIcl_cm = Icl + m*(L2 - h/2)^2\nΔIcl_cm = ΔIcl + Δm*(L2- h/2)^2 + 2*m*(L2-h/2)*(ΔL2+ Δh/2)\n\nIcl_eixo = Icl + m*(L - L1 - h/2)^2\nΔIcl_eixo = ΔIcl + Δm*(L - L1 - h/2)^2 + 2*m*(L-L1-h/2)*(ΔL +ΔL1 + Δh/2)\n\nprintln(\"\\n Sistema no centro de massa\\n\")\nprintln(\"======================\")\nprintln(\"Ih ± ΔIh =\" , round(Ih,digits=8), \" ± \", round(ΔIh,digits=8))\nprintln(\"Icl_cm ± ΔIcl_cm =\" , round(Icl_cm,digits=8), \" ± \", round(ΔIcl_cm,digits=8))\n\nprintln(\"\\n Sistema no eixo \\n \")\nprintln(\"======================\")\nprintln(\"Ih_eixo ± ΔIh_eixo =\" , round(Ih_eixo,digits=8), \" ± \", round(ΔIh_eixo,digits=8))\nprintln(\"Icl_eixo ± ΔIh_eixo =\" , round(Icl_eixo,digits=8), \" ± \",round(ΔIcl_eixo,digits=8))\n", "meta": {"hexsha": "c4f2b8cf38660c39890a93e13ea609a1754789ee", "size": 1209, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Fisica experimental/02/03/src/momento-inercia.jl", "max_stars_repo_name": "jefter66/notes", "max_stars_repo_head_hexsha": "adf8753b166162dcb898470932db2235c5d5966b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Fisica experimental/02/03/src/momento-inercia.jl", "max_issues_repo_name": "jefter66/notes", "max_issues_repo_head_hexsha": "adf8753b166162dcb898470932db2235c5d5966b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Fisica experimental/02/03/src/momento-inercia.jl", "max_forks_repo_name": "jefter66/notes", "max_forks_repo_head_hexsha": "adf8753b166162dcb898470932db2235c5d5966b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7857142857, "max_line_length": 92, "alphanum_fraction": 0.5425971878, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399077750858, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7954932324872132}}
{"text": "# Compute C = A * B, using naive matrix-multiplication algorithm,\n# with a pre-allocated output array C.  (\"!\" is a Julia convention\n# for functions that modify their arguments.)\n\nfunction matmul!(C, A, B)\n    m,n = size(A)\n    n,p = size(B)\n    size(C) == (m,p) || error(\"incorrect dimensions \", size(C), \" ≠ $m × $p\")\n    for i = 1:m\n        for k = 1:p\n            c = zero(eltype(C))\n            for j = 1:n\n                @inbounds c += A[i,j] * B[j,k]\n            end\n            @inbounds C[i,k] = c\n        end\n    end\n    return C\nend\n\n# a wrapper that allocates C of an appropriate type\nmatmul(A, B) = matmul!(Array{promote_type(eltype(A), eltype(B))}(undef,size(A,1), size(B,2)),A, B)\n\n# Example:\n# A = rand(5,6)\n# B = rand(6,7)\n# matmul(A,B)", "meta": {"hexsha": "7dcd74318449dda091039d97c641a351fd3ace2e", "size": 754, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Code/Numerical Analysis & Machine Learning/Matrix Multiplication/NaiveMatrixMultiplication.jl", "max_stars_repo_name": "BambooFlower/Math-Scripts", "max_stars_repo_head_hexsha": "ee89c4f8a1fe80f355e2daa0baa4f94374ee3ab5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-03-10T13:21:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-20T19:52:53.000Z", "max_issues_repo_path": "Code/Numerical Analysis & Machine Learning/Matrix Multiplication/NaiveMatrixMultiplication.jl", "max_issues_repo_name": "BambooFlower/Math-Scripts", "max_issues_repo_head_hexsha": "ee89c4f8a1fe80f355e2daa0baa4f94374ee3ab5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-25T14:25:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-25T14:28:07.000Z", "max_forks_repo_path": "Code/Numerical Analysis & Machine Learning/Matrix Multiplication/NaiveMatrixMultiplication.jl", "max_forks_repo_name": "BambooFlower/Math-Scripts", "max_forks_repo_head_hexsha": "ee89c4f8a1fe80f355e2daa0baa4f94374ee3ab5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-25T13:17:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T15:11:25.000Z", "avg_line_length": 27.9259259259, "max_line_length": 98, "alphanum_fraction": 0.5450928382, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7954626584662325}}
{"text": "\"\"\"Sieve of Eratosthenes function docstring\"\"\"\nfunction es(n::Int) # one integer argument\n    isprime = trues(n) # n-elt vector of true\n    isprime[1] = false # since 1 is not prime\n    for i in 2:isqrt(n) # loop odd ints less or equal to sqrt(n)\n        if isprime[i] # conditonal evaluation\n            for j in i^2:i:n # sequence with step i\n                isprime[j] = false\n            end\n        end\n    end\n    return filter(x -> isprime[x], 1:n) # filter using anonymous fn\nend\n\nprintln(es(100)) # print all primes less or equal to 100\n@time length(es(10^6)) # check fn execution time and memory usage\n", "meta": {"hexsha": "e4bb1a176f5e87183976dfede68dc470cd72ea45", "size": 612, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "sieve/prime_sieve.jl", "max_stars_repo_name": "mxxo/numerics", "max_stars_repo_head_hexsha": "1ebc8aee369fdc0938bfdf4567afd4fb79011191", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sieve/prime_sieve.jl", "max_issues_repo_name": "mxxo/numerics", "max_issues_repo_head_hexsha": "1ebc8aee369fdc0938bfdf4567afd4fb79011191", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sieve/prime_sieve.jl", "max_forks_repo_name": "mxxo/numerics", "max_forks_repo_head_hexsha": "1ebc8aee369fdc0938bfdf4567afd4fb79011191", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0, "max_line_length": 67, "alphanum_fraction": 0.6307189542, "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632916317103, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.795462653300317}}
{"text": "function isPrime(n::Int)\n\tfor i in 2:ceil(sqrt(n))\n\t\tif n%i==0 && n!=i return false end\n\tend\n\treturn true\nend\nprimes = [1,2,3]\n\nubound = 2000000\nfor i in 5:2:ubound\n\tif isPrime(i)\n\t\tpush!(primes, i)\n\tend\nend\n\nprintln(sum(primes))\n", "meta": {"hexsha": "1af3f8648a99aebaf2f0177fffe923acf8561b3e", "size": 230, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "algo/su.0.jl", "max_stars_repo_name": "cdluminate/MyNotes", "max_stars_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algo/su.0.jl", "max_issues_repo_name": "cdluminate/MyNotes", "max_issues_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algo/su.0.jl", "max_forks_repo_name": "cdluminate/MyNotes", "max_forks_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.5294117647, "max_line_length": 36, "alphanum_fraction": 0.6565217391, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632856092016, "lm_q2_score": 0.85776809953619, "lm_q1q2_score": 0.7954626430766418}}
{"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e6bbe0a2-3f9c-431a-894d-32279bef9e73\nbegin\n\tusing PlutoUI\n\tPlutoUI.TableOfContents(title = \"Contents\")\nend\n\n# ╔═╡ 73a77da6-7ec7-4460-9542-bb994676a375\nusing Plots\n\n# ╔═╡ 25afb2d2-f437-11eb-327c-496dc439ccfa\nmd\"\"\"\n# Primes and Matters of Efficiency\n\"\"\"\n\n# ╔═╡ b735e72f-1498-4bf7-9f30-93a46aa46392\nmd\"\"\"\n## Objectives\n- Introduce **asymptotic runtime analysis** with \"big O\" notation \n- Compare different approaches for **finding prime numbers** in regard to their efficiency\n- Measure runtimes experimentally with the **runtime tools** built into Julia\n- Statistically varify certain theorems about the **distribution of primes**\n\"\"\"\n\n# ╔═╡ 480b1c62-9a1d-4504-8872-c388403bec0b\nmd\"\"\"\n## Why care about Primes?\nThere is no doubt that prime numbers play an important role in modern day mathematics. They appear in almost all areas of study and are still not understood as well as their simple definition would suggest. But why should one care about computing primes on a computer?\n\n### Statistical Data inspires Research\nAlmost all conjectures about the distributions of primes throughout history have been motivated through data. Likewise, new conjectures about the primes inspired by theoretical observations can be checked against a list of small primes, either showing a concrete contradiction or boosting the mathematician's confidence in their conjecture.\n\n### Computational Proofs\nOften, proofs about prime numbers are reduced to a finite case check of small primes which then can be checked by a computer.\n\n### Cryptography\nMany traditional encryption algorithm make use of the fact that there is no algorithm (yet) for decomposing a number into prime factors quickly. Therefore, there is a big need in cryptography for novel large prime numbers.\n\"\"\"\n\n# ╔═╡ 6164b325-44b8-478e-a122-a871c44d7ab1\nmd\"\"\"\n## Asymptotic Runtime Analysis\nWhen analysing an algorithm theoretically, we are interested in counting the number of \"elementary operations\" as a function of the input size. An elementary operation, also sometimes called a zero operation, is any algorithmic step that can be performed by the computer in constant time. Elementary operations include addition, multiplication, division, modulus calculations, conditional checks, etc\nWhile the time to perform some of these operations, for example multiplication, does depend on the size of the numbers involved, modern computers have specific processor instructions to run such operations directly on the hardware in negligible time.\n\n### The \"Big O\" Notation\nWhen counting elementary operations, we are usually only interested in its growth rate with respect to the input size. To express this we make use of the following:\n\n_**Definition:**_ For functions $f,g:\\mathbb{R}\\to\\mathbb{R}$ we say that $f$ is $O(g)$ if there exist constants $M$ and $x_0$ such that $|f(x)| \\leq Mg(x)$ for all $x \\geq x_0$.\n\nFor example, we have:\n- The function $x\\to 3x^2+100x-3$ is $O(x^2)$\n- The function $x\\to \\log(x!)$ is $O(x\\log x)$\n- The function $x\\to \\binom{x}{k}$ is $O(x^k)$ for any fixed $k$\n- The function $x\\to \\sqrt{x} + (\\log x)^k$ is $O(\\sqrt{x})$ for any fixed $k$\n\nNote that this is just an upper bound on the asymptotic behaviour. A function that is $O(x^2)$ for example could also be $O(x)$ or even smaller. Finding the best upper bound however can generally speaking be very hard.\n\"\"\"\n\n# ╔═╡ 24f264de-60d8-463b-8907-0a43f8297e52\nmd\"\"\"\n## Finding Primes\n\nIn this section we will discuss increasingly efficient methods for finding all the prime numbers up to some integer $N$. We are particularly interested in analyzing the runtime of our algorithms as $N$ grows very large.\n\n### A Naïve Approach\nIn order to check if a given integer $n$ is prime, the most canonical algorithm just counts the number of divisors of $n$ by running though all the integers less than or equal to $n$. If the number of divisors is exactly 2, we have found ourselves a prime.\n\"\"\"\n\n# ╔═╡ 53cd01c6-0090-47a0-ad59-63950fe471c1\nfunction isPrime(n)\n\tcount = 0\n\tfor k in 1:n\n\t\tif n % k == 0\n\t\t\tcount += 1\n\t\tend\n\tend\n\treturn count == 2\nend\n\n# ╔═╡ e3525717-d598-4730-9ee0-b65ea09f7ce0\nmd\"\"\"\nNow to find all the primes up to $N$, we can just run through all the positive integers less than or equal to $N$, add each integer to our list if it passes our primality test.\n\"\"\"\n\n# ╔═╡ 9f7705cb-775b-4e86-bc70-70b2e852fbc2\nfunction findPrimes(N)\n\tprimes = []\n\tfor n in 1:N\n\t\tif isPrime(n)\n\t\t\tappend!(primes, n)\n\t\tend\n\tend\n\treturn primes\nend\n\n# ╔═╡ 48e8d826-a81c-42fa-910b-abd3d80a230d\nmd\"\"\"\nWe can check that our code works by making it find all the 25 primes less than one hundred:\n\"\"\"\n\n# ╔═╡ a3d579fc-b5d9-4662-9823-b171e4a29fab\nfindPrimes(100)\n\n# ╔═╡ dc109446-aa32-4fb7-8f74-edc0c6f98c6a\nmd\"\"\"\nFor most applications and in order to have some meaningful statistics, we need many more primes. Let's say we therefore want to use our algorithm to find all primes up to 100,000.\n\"\"\"\n\n# ╔═╡ a346aa06-7db4-4d7a-aad8-bf005c294c67\n@time findPrimes(100000)\n\n# ╔═╡ ba0eae87-4eec-4387-a210-64e0f2126f87\nmd\"\"\"\nOur algorithm already took considerably longer! If we want to go higher, our aim must be to get this time down dramatically. Running the algorithm for one million, we already have no chance of getting a result anytime soon...\n\"\"\"\n\n# ╔═╡ e5293427-7721-4a89-ab7b-0c8fb4a618cf\nmd\"\"\"\nLet's analyze what we have so far. The benefit of an algorithm as simple as the one we wrote, is that it is easy to analyse: Our algorithm calls the function `isPrime` once for every integer $n$ in the range $1$ to $N$. Since the procedure `isPrime(n)`\n itself runs through all positive integers up to $n$, the code inside the inner most loop therefore runs approximately $1+2+3+\\cdots+N = N(N+1)/2$ times in total. All the operations like checking divisibility or appending to a vector can be taken as elementary and we conclude that our algorithm has time complexity $O(N^2)$.\n\"\"\"\n\n# ╔═╡ af8fa992-1bc8-4896-8f6c-8edf3f19c475\nmd\"\"\"\nWe can also analyse our algorithm experimentally. In order to do so, we write a little function that runs any algorithm we give it at equally spaced input values and plots the runtime against input size. Note that in Julia we can use the `@elapsed` macro to get the runtime of any function in seconds, and we need to import the package `Plots` to use its plotting functionality:\n\"\"\"\n\n# ╔═╡ aa777745-618a-4681-b73a-1a1ca978d165\nfunction plotTime(f, step, num)\n\tinputs = []\n\ttimes = []\n\tfor i in 1:num\n\t\tappend!(inputs, i * step)\n\t\tappend!(times, @elapsed f(i * step))\n\tend\n\tplot(inputs, times, xlabel = \"N\", ylabel = \"time (seconds)\", legend = false)\nend\n\n# ╔═╡ 656b291e-f430-4e32-a3c9-87553cf2b1a5\nplotTime(findPrimes, 5000, 20)\n\n# ╔═╡ 7c8670bf-85f6-438c-b9d7-a9b1ca4a6c01\nmd\"\"\"\nThe resulting plot clearly demonstrates the quadratic growth we predicted theoretically. It is always useful to also analyse runtime with experimentation, since efficiency is also heavily influenced by things like cache locality, the branch predictor, multithreading features, etc.\n\nA very useful tool for more in depth runtime measurments is the 'BenchmarkTools' julia package.\n\"\"\"\n\n# ╔═╡ a4232c06-eb44-4f7c-a8eb-09aa524cc1a7\nmd\"\"\"\n### Using all Available Information\nOne observation that allows us to improve the efficiency of our algorithm is that when checking for the existence of divisors, we only have to check for prime divisors! Since we are finding all the prime numbers in order, whenever we are checking if $n$ is prime, we already have a list of all primes less than $n$ at hand. Let's see how we would write an improved version of the function `isPrime`, which now not only takes a positive integer $n$ as input, but also the list of all primes less than $n$:\n\"\"\"\n\n# ╔═╡ f4b38f40-6c51-430a-a7fd-5029e3b6ab0f\nfunction isPrimeV2(primes, n)\n\tif n < 2 return false end\n\tanswer = true\n    for p in primes\n        if n % p == 0\n\t\t\tanswer = false\n\t\tend\n    end\n    return answer\nend\n\n# ╔═╡ 17fa50b7-afee-42f9-b622-d18ef1060720\nmd\"\"\"\nNote that now we have to exclude the cases $n < 2$ explicitly, as for these inputs the list of smaller primes would be empty. Let's now use this new, improved version of `isPrime` to write an improved `findPrimes` function.\n\"\"\"\n\n# ╔═╡ 519ce97d-fde8-49c7-8b92-56185bd02333\nfunction findPrimesV2(N)\n\tprimes = []\n\tfor n in 1:N\n\t\tif isPrimeV2(primes, n)\n\t\t\tappend!(primes, n)\n\t\tend\n\tend\n\treturn primes\nend\n\n# ╔═╡ 9e76abdc-ddf9-4edd-a40d-059706f556d0\n@time findPrimesV2(100_000)\n\n# ╔═╡ ae3c3fa7-0581-46e1-a3f3-abe49173ed1c\nmd\"\"\"\nSurprisingly we find that with this new version of our algorithm, finding all the primes up to 100 000 takes about twice as long! But given that we clearly perform fewer iterations of our loop, how could that possibly be?\n\"\"\"\n\n# ╔═╡ 2b4873be-3cb7-4c2a-b8a0-451baddf428f\nmd\"\"\"\nLet's investigate how the runtime complexity of our algorithms has changed. To do so, we will make use of a very famous result about prime numbers. Note that throughout this case study $\\log$ will denote the natural logarithm.\n\n_**Prime Number Theorem:**_ The number of primes up to $N$ is asymptotically $N/\\log N$.\n\"\"\"\n\n\n# ╔═╡ c28f9636-7d0c-4bd2-9c4d-bfc127ea06bc\nmd\"\"\"\nInstead of $1+2+3+\\cdots + N = N(N+1)/2$ iterations of the inner loop we therefore have approximately $2/\\log(2) + 3/\\log(3) + \\cdots + N/\\log(N)\\leq \\frac{N(N+1)/2}{\\log((N+1)/2)}$, using concavity of the function $x/\\log(x)$ for $x > e^2$. Note that since we only care about the asymptotic behaviour of the expression, there is no problem with dropping the first term of the series to avoid the pole of $x/\\log(x)$ at $1$. The runtime complexity is therefore at most $O(N^2/\\log(N))$ and as $N$ grows large we have succesfully shaved of a factor of $\\log(N)$.\n\nHowever, $\\log N$ is very small for small values of $N$. In the case above with $N=100000$ we merely have $\\log(N) \\approx 11.5$. As it so happens, julia is heavily optimized for iterators of the form $1:N$, while of looping over a custom array of the same size can take much longer. The efficiency gain from this optimization outweighs the factor of $\\log N$ for small values of $N$.\n\"\"\"\n\n# ╔═╡ ce2733ab-10a6-4e87-aae4-ed30fa346823\nmd\"\"\"\n### Using Some Mathematical Insight\nOur algorithms can be made much more efficient when considering the following property of a positive integer:\n\n\n_**Lemma:**_ If an integer $n\\geq 2$ has no prime divisor $p \\leq \\sqrt n$, then it is prime.\n\n\nIt is easy to see why this is the case, since if $n$ were to be composite, it would need to have at least one divisor $d > \\sqrt n$, but then the number $n/d$ is also a divisor of $n$ and less than $\\sqrt n$. The smallest prime divisor of $n$ is therefore also less than $\\sqrt n$, a contradiction.\n\"\"\"\n\n# ╔═╡ aa396120-1a8d-4d13-9558-1faad05f76c7\nmd\"\"\"\nIn general, removing unnecessary work is a very effective way of making algorithms more efficient. Especially when it is possible to break out of nested loops early, we can often gain order of magnitudes in performance. Let's see how this translates into our code. Instead of the procedure `isPrime(n)` running through all positive integers up to $n$, we can break out of the loop as soon as we pass $\\sqrt n$. Note that we have to be slightly careful, as in the case where $n$ is the square of a prime, it is essential that we still check $\\sqrt n$ itself as a divisor.\n\"\"\"\n\n# ╔═╡ 5f99ba92-7c35-4e6b-a3fc-f42178c43cad\nfunction isPrimeV3(primes, n)\n\tif n < 2 return false end\n\tanswer = true\n    for p in primes\n\t\tif p > sqrt(n) break end\n        if n % p == 0 answer = false end\n    end\n    return answer\nend\n\n# ╔═╡ 3b53142b-d6bd-49e3-91b5-689cdb1cac01\nfunction findPrimesV3(N)\n\tprimes = []\n\tfor n in 1:N\n\t\tif isPrimeV3(primes, n)\n\t\t\tappend!(primes, n)\n\t\tend\n\tend\n\treturn primes\nend\n\n# ╔═╡ bc2831a1-f808-4bc7-afaf-994abefb5286\n@time findPrimesV3(100000)\n\n# ╔═╡ 157a17af-eb12-4d6d-be12-37a1b609005d\nmd\"\"\"\nWe have reduced the runtime for `findPrimes(100000)` from about half a minute down to about 1 second! And all of that not by using some advanced mathematics, but just removing unnecessary work. Lets see how far we can push our algorithm now:\n\"\"\"\n\n# ╔═╡ 54c591db-16c9-4c9e-9d01-444558af9c6e\nfindPrimesV3(1_000_000)\n\n\n# ╔═╡ 6e319277-a897-49aa-9e78-7a905a11dc89\nmd\"\"\"\nFinding all primes up to one million in around 15 seconds, that's pretty fast now. Let us also analyse the runtime of our improved version theoretically: instead of the approximate $2/\\log(2) + 3/\\log(3) + \\cdots + N/\\log(N)$ iterations, we now have approximately $\\sqrt 2/\\log(\\sqrt 2) + \\sqrt 3/\\log(\\sqrt 3) + \\cdots + \\sqrt N/\\log(\\sqrt N)\\leq \\frac{N\\sqrt{(N+1)/2})}{\\log(\\sqrt{(N+1)/2})}$, again using concavity, this time of the function $\\sqrt x/\\log(\\sqrt x)$ for $x > e^{2\\sqrt 2}$. We get a runtime complexity of $O(N^{3/2}/\\log(N))$, a factor $\\sqrt N$ better than before. This efficiency gain is much greater than the previous ones, as $\\sqrt N$ grows much faster than $\\log(N)$ for large $N$.\n\"\"\"\n\n# ╔═╡ 3ed289cd-6ace-442f-a9b4-7fe109af5e49\nmd\"\"\"\n### Don't do any Unnecessary Work\nPushing the idea of removing unnecessary work further, we realise that there is another place where we can break out of the loop early: when we find a prime divisor of $n$, there is no need to continue looking. Instead, as soon as we find a prime that divides $n$ we should immediately break out of the loop.\n\"\"\"\n\n# ╔═╡ acda705d-1e1a-4b5f-ba15-0c7d3bdbd5d4\nfunction isPrimeV4(primes, n)\n    for p in primes\n\t\tif p > sqrt(n) return true end\n\t\tif n % p == 0 return false end\n    end\n    return true\nend\n\n# ╔═╡ 7ccb1dea-7a69-47f4-964b-fc7799c58b8a\nmd\"\"\"\nSimilarly, we don't have to check for the case $n < 2$ every time we run `isPrime`. Instead we can just start looking for primes starting at 2, assuming that all values passed to `isPrime` satisfy $n > 2$ already. In fact, since we know that 2 is the only even prime, let's just add to our initial list of primes and only consider odd $n$ going forth. We just need to add a small check to handle the cases $N < 2$ but that is no problem, since this line is only executed once.\n\"\"\"\n\n# ╔═╡ 8f73a313-e31d-4087-beb9-1f5c43f44ea1\nfunction findPrimesV4(N)\n\tif N < 2 return [] end\n\tprimes = [2]\n\tfor n in 3:2:N\n\t\tif isPrimeV4(primes, n)\n\t\t\tappend!(primes, n)\n\t\tend\n\tend\n\treturn primes\nend\n\n# ╔═╡ e9cdb8d0-3daa-4ada-9344-45099f184a64\nfindPrimesV4(100000);\n\n# ╔═╡ 86076221-f0eb-4434-b15e-abcc7fc54384\nfindPrimesV4(1000000);\n\n# ╔═╡ 998e600b-6933-48a9-bcf4-f7c1f981411e\nfindPrimesV4(10000000);\n\n# ╔═╡ bf89a580-d02c-4c14-af67-f249071b4d5e\nfindPrimesV4(100000000);\n\n# ╔═╡ d1edf66f-856b-463a-af27-775507ee70f2\nmd\"\"\"\nFinding all primes up to one million now only takes a fraction of a second and just about a 20 second wait gives us all primes up to one hundred million!\n\"\"\"\n\n# ╔═╡ d22ec8ae-e5de-4b8d-85ac-17c7844f667b\nmd\"\"\"\nHow about the runtime complexity of this evidently much faster algorithm? Well, things get a bit more tricky to analyse here, as the asymptotic runtime now depends on how often and how early we can break out of the loop, which in turn depends on the distribution of primes in a more complicated way than before. If we count the number of iterations of the inner most loop for odd $N$, we get an estimate of\n$h(3)/\\log(h(3)) + h(5)/\\log(h(5)) + \\cdots + h(N)/\\log(h(N))$,\nwhere $h(n)$ is the smallest prime divisor of $n$ if $n$ is composite, and $\\sqrt n$ if $n$ is prime. \n\"\"\"\n\n# ╔═╡ 8eae3bb0-4fa5-4e0f-8336-d28b199ef229\nmd\"\"\"\nThe last changes we made does not affect the runtime complexity itself, as it only shaves of a constant time factor. Nevertheless, as seen before, optimizations like this one are not to be underestimated. For small values of $N$, say $N < 10^9$ for example, a factor of $20$ is often worth more than a factor of $\\log(N)$ for instance.\n\"\"\"\n\n# ╔═╡ ae8373e9-347d-4d2c-b988-6170ec2040a2\nmd\"\"\"\n## Applications\nNow that we have a way of finding the first 10 million primes in almost the blink of an eye, lets make use of them to verify some well-known but hard to prove result about their distribution.\n\"\"\"\n\n# ╔═╡ cdefc0aa-aefa-4c62-b8a9-692331c9bf50\nprimes = findPrimesV4(10_000_000);\n\n# ╔═╡ ba871ee3-125d-402c-aef0-fe7046bf2bde\nmd\"\"\"\n### The Prime Number Theorem\nAs already mentioned in a previous section, the Prime Number Theorem states that the number of primes up to $N$ is asymptotically given by $N/\\log N$. A better estimate with the same asymptotic is the function $N/(\\log N-1)$. To see this result visually, let us plot $i(\\log p_i-1)/p_i$ against $i$:\n\"\"\"\n\n# ╔═╡ ed0a598c-84a5-4062-bb7a-1d00added226\nfunction plotPNT(primes)\n\tdata = []\n\tfor (i, p) in enumerate(primes)\n\t\tappend!(data, i*(log(p)-1)/p)\n\tend\n\t\n\tplot(data, ylims = (0.995,1.015), legend = false)\nend\n\n# ╔═╡ 1455bae3-7b50-4f0f-b521-b5aa5b9ba926\nplotPNT(primes)\n\n# ╔═╡ 54f33702-08e9-439f-9d28-c783d7c27547\nmd\"\"\"\nAs predicted, the ratio does seem to tend towards $1$, be that very slowly.\n\"\"\"\n\n# ╔═╡ 03116ef9-39b9-459e-95cc-c367dedd7896\nmd\"\"\"\n### First and Last Digits of Primes in Base 10\nDespite their unique properties, prime numbers behave in many ways just like a random subset of the integers with a distribution given by the prime number theorem. For example, looking at the last digits of our primes, we expect all possible digits (the odd digits except five) to approximately appear equally often:\n\"\"\"\n\n# ╔═╡ 6e66626d-7660-45d6-88c5-497ffce7c81e\nhistogram(broadcast(x -> x % 10, primes), bins = -0.5:1:9.5, xticks = -1:9, legend = false, norm = :pdf, ylims = (.249,.251), xlabel = \"Last Digit\", ylabel = \"Frequency\")\n\n# ╔═╡ 166c0bb7-e75b-4e32-b3f3-0568e9e3d2b3\nmd\"\"\"\nThe first digits of primes on the other hand we expect to follow a distribution approximately resembling the so-called Benford's Law, since the distribution of the primes gets progressively sparser and therefore lower leading digits are more likely:\n\"\"\"\n\n# ╔═╡ e5bc63bc-751e-4faa-81ce-db37343baf19\nhistogram(broadcast(x -> floor(x/10^floor(log10(x))), primes), bins = 0.5:1:9.5, xticks = -1:9, normalize = :pdf, ylims = (.105,.12), legend = false, xlabel = \"First Digit\", ylabel = \"Frequency\")\n\n# ╔═╡ 9d56672c-f3a0-4705-8e04-6bd2776d46b5\nmd\"\"\"\n### The Goldbach Conjecture\nThe Goldbach Conjecture is one of the most famous open problems about prime numbers. Proposed in 1742 by Christian Goldbach in correspondence with Leonhard Euler, it states that every even integer greater than 2 can be written as the sum of two prime numbers. While the problem remains open to this day, the conjecture is strongly believed to be true, not least because no counter example has been found so far. Let us verify this for the first few even integers:\n\"\"\"\n\n# ╔═╡ b0ba2f26-291f-4204-942f-2b87cd5ba8a8\nfunction verifyGoldbach(n, primes)\n\tsums = Set()\n\tfor p in primes\n\t\tfor q in primes\n\t\t\tif p+q > n break end\n\t\t\tpush!(sums, p+q)\n\t\tend\n\tend\n\tfor k = 4:2:n\n\t\tif !in(k, sums) return false end\n\tend\n\treturn true\nend\t\t\n\n# ╔═╡ 5c1b3bac-98d2-4d5b-b8ef-85ca8e2a4f80\nmd\"\"\"\nSince this algorithm runs in $O(n^2)$ time, we will only be able to check up to about 100000. Using the \"Fast Fourier Transform\" the time complexity could be brought down to $O(n\\log n)$ but would go beyond the scope of this case study.\n\"\"\"\n\n# ╔═╡ 6d322108-fa1b-41ad-81d6-5f36b6ef2fb1\nverifyGoldbach(100000, primes)\n\n# ╔═╡ 6ee5e9b2-2d38-4a92-9e71-660f06bbc7a5\nmd\"\"\"\n### Reciprocal Sum of Primes\nIt is well known that the sum of reciprocals of primes diverges. Moreover, the growth rate of the partial sums is also known. In particular, the quantity\n\n$P(n) = \\sum_{p \\leq n} \\frac{1}{p} - \\log\\log n$\n\nis decreasing and tends to a constant $M \\approx 0.2614972$, called the Meissel–Mertens constant, as $n$ tends to infinity. Let us verify that this result is consistent with our data:\n\"\"\"\n\n# ╔═╡ 39b108b3-b41e-44c4-9565-d199c5831746\nfunction plotReciprocal(primes)\n\tpartialSum = 0.0\n    data = []\n\tfor (i, p) in enumerate(primes)\n\t\tpartialSum += 1/p\n\t\tappend!(data, partialSum - log(log(p)))\n\tend\n\t\n\tplot(xlabel=\"i-th prime q_i\", ylabel=\"P(q_i)\", legend = false)\n\tplot!(data, ylims = (0.261, 0.263))\n\thline!([0.2615])\nend\n\n\n# ╔═╡ 00484f64-99c0-43b0-97aa-2c2d3ed98318\nplotReciprocal(primes)\n\n# ╔═╡ 2eff73ca-34ba-4a86-bc98-8543003fa46f\nmd\"\"\"\nThe expression does indeed seem to be decreasing and slowly tending towards some positive constant, just as desired.\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\n\n[compat]\nPlots = \"~1.20.0\"\nPlutoUI = \"~0.7.9\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c3598e525718abcc440f69cc6d5f60dda0a1b61e\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.6+5\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"e2f47f6d8337369411569fd45ae5753ca10394c6\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.0+6\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\", \"StaticArrays\"]\ngit-tree-sha1 = \"ed268efe58512df8c7e224d2e170afd76dd6a417\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.13.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"344f143fa0ec67e47917848795ab19c6a455f32c\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.32.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"ee400abb2298bd13bfc3df1c412ed228061a2385\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.7.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"4437b64df1e0adccc3e5d1adbc3ac741095e4677\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.9\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"92d8f9f208637e8d2d28c664051a00569c01493d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.1.5+1\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"LibVPX_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"3cc57ad0a213808473eafef4845a74766242e05f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.3.1+4\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"35895cf184ceaab11fd778b4590144034a167a2f\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.1+14\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"cbd58c9deb1d304f5a245a0b7eb841a2560cfec6\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.1+5\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"dba1e8614e98949abfa60480b13653813d8f0157\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+0\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"182da592436e287758ded5be6e32c406de3a2e47\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.58.1\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"eaf96e05a880f3db5ded5a5a8a7817ecba3c7392\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.58.0+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"7bf67e9a481712b3dbe9cb3dac852dc4b1162e02\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"44e3b40da000eab4ccb1aecdc4801c040026aeb5\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.13\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"81690084b6198a2e1da36fcfda16eeca9f9f24e4\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.1\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a4b12a1bd2ebade87891ab7e36fdbce582301a92\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.6\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[LibVPX_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"12ee7e23fa4d18361e7c2cde8f8337d4c3101bc7\"\nuuid = \"dd192d2f-8180-539f-9fb4-cc70b1dcf69a\"\nversion = \"1.10.0+0\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"761a393aeccd6aa92ec3515e428c26bf99575b3b\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+0\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"0fb723cd8c45858c22169b2e42269e53271a6df7\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.7\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"4ea90bd5d3985ae1f9a908bd4500ae88921c5ce7\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.0\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+0\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"bfd7d8c7fd87f04543810d9cbd3995972236ba1b\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"1.1.2\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"501c20a63a34ac1d015d5304da0e645f42d91c9f\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.0.11\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\"]\ngit-tree-sha1 = \"e39bea10478c6aff5495ab522517fae5134b40e3\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.20.0\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"Suppressor\"]\ngit-tree-sha1 = \"44e225d5837e2a2345e69a1d1e01ac2443ff9fcb\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.9\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"b3fb709f3c97bfc6e948be68beeecb55a0b340ae\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.1\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"2a7a2469ed5d94a98dea0e85c46fa653d76be0cd\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.3.4\"\n\n[[Reexport]]\ngit-tree-sha1 = \"5f6c21241f0f655da3952fd60aa18477cf96c220\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.1.0\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"885838778bb6f0136f8317757d7803e0d81201e4\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.9\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"1958272568dc176a1d881acb797beb909c785510\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.0.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"fed1ec1e65749c4d96fc20dd13bea72b55457e62\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.9\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"000e168f5cc9aded17b6999a560b7c11dda69095\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.0\"\n\n[[Suppressor]]\ngit-tree-sha1 = \"a819d77f31f83e5792a76081eee1ea6342ab8787\"\nuuid = \"fd094767-a336-5f1f-9728-57cf17d0bbfb\"\nversion = \"0.2.0\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"d0c690d37c73aeb5ca063056283fde5585a41710\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.5.0\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\"]\ngit-tree-sha1 = \"2839f1c1296940218e35df0bbb220f2a79686670\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.18.0+4\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"acc685bcf777b2202a904cdcb49ad34c2fa1880c\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.14.0+4\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7a5780a0d9c6864184b3a2eeeb833a0c871f00ab\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"0.1.6+4\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d713c1ce4deac133e3334ee12f4adff07f81778f\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2020.7.14+2\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"487da2f8f2f0c8ee0e83f39d13037d6bbf0a45ab\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.0.0+3\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─25afb2d2-f437-11eb-327c-496dc439ccfa\n# ╟─b735e72f-1498-4bf7-9f30-93a46aa46392\n# ╟─480b1c62-9a1d-4504-8872-c388403bec0b\n# ╟─6164b325-44b8-478e-a122-a871c44d7ab1\n# ╟─24f264de-60d8-463b-8907-0a43f8297e52\n# ╠═53cd01c6-0090-47a0-ad59-63950fe471c1\n# ╠═e3525717-d598-4730-9ee0-b65ea09f7ce0\n# ╠═9f7705cb-775b-4e86-bc70-70b2e852fbc2\n# ╟─48e8d826-a81c-42fa-910b-abd3d80a230d\n# ╠═a3d579fc-b5d9-4662-9823-b171e4a29fab\n# ╟─dc109446-aa32-4fb7-8f74-edc0c6f98c6a\n# ╠═a346aa06-7db4-4d7a-aad8-bf005c294c67\n# ╟─ba0eae87-4eec-4387-a210-64e0f2126f87\n# ╟─e5293427-7721-4a89-ab7b-0c8fb4a618cf\n# ╟─af8fa992-1bc8-4896-8f6c-8edf3f19c475\n# ╠═aa777745-618a-4681-b73a-1a1ca978d165\n# ╠═656b291e-f430-4e32-a3c9-87553cf2b1a5\n# ╟─7c8670bf-85f6-438c-b9d7-a9b1ca4a6c01\n# ╟─a4232c06-eb44-4f7c-a8eb-09aa524cc1a7\n# ╠═f4b38f40-6c51-430a-a7fd-5029e3b6ab0f\n# ╟─17fa50b7-afee-42f9-b622-d18ef1060720\n# ╠═519ce97d-fde8-49c7-8b92-56185bd02333\n# ╠═9e76abdc-ddf9-4edd-a40d-059706f556d0\n# ╟─ae3c3fa7-0581-46e1-a3f3-abe49173ed1c\n# ╟─2b4873be-3cb7-4c2a-b8a0-451baddf428f\n# ╟─c28f9636-7d0c-4bd2-9c4d-bfc127ea06bc\n# ╟─ce2733ab-10a6-4e87-aae4-ed30fa346823\n# ╟─aa396120-1a8d-4d13-9558-1faad05f76c7\n# ╠═5f99ba92-7c35-4e6b-a3fc-f42178c43cad\n# ╠═3b53142b-d6bd-49e3-91b5-689cdb1cac01\n# ╠═bc2831a1-f808-4bc7-afaf-994abefb5286\n# ╟─157a17af-eb12-4d6d-be12-37a1b609005d\n# ╠═54c591db-16c9-4c9e-9d01-444558af9c6e\n# ╟─6e319277-a897-49aa-9e78-7a905a11dc89\n# ╟─3ed289cd-6ace-442f-a9b4-7fe109af5e49\n# ╠═acda705d-1e1a-4b5f-ba15-0c7d3bdbd5d4\n# ╟─7ccb1dea-7a69-47f4-964b-fc7799c58b8a\n# ╠═8f73a313-e31d-4087-beb9-1f5c43f44ea1\n# ╠═e9cdb8d0-3daa-4ada-9344-45099f184a64\n# ╠═86076221-f0eb-4434-b15e-abcc7fc54384\n# ╠═998e600b-6933-48a9-bcf4-f7c1f981411e\n# ╠═bf89a580-d02c-4c14-af67-f249071b4d5e\n# ╟─d1edf66f-856b-463a-af27-775507ee70f2\n# ╟─d22ec8ae-e5de-4b8d-85ac-17c7844f667b\n# ╟─8eae3bb0-4fa5-4e0f-8336-d28b199ef229\n# ╟─ae8373e9-347d-4d2c-b988-6170ec2040a2\n# ╠═cdefc0aa-aefa-4c62-b8a9-692331c9bf50\n# ╟─ba871ee3-125d-402c-aef0-fe7046bf2bde\n# ╠═ed0a598c-84a5-4062-bb7a-1d00added226\n# ╠═1455bae3-7b50-4f0f-b521-b5aa5b9ba926\n# ╟─54f33702-08e9-439f-9d28-c783d7c27547\n# ╟─03116ef9-39b9-459e-95cc-c367dedd7896\n# ╟─6e66626d-7660-45d6-88c5-497ffce7c81e\n# ╟─166c0bb7-e75b-4e32-b3f3-0568e9e3d2b3\n# ╟─e5bc63bc-751e-4faa-81ce-db37343baf19\n# ╟─9d56672c-f3a0-4705-8e04-6bd2776d46b5\n# ╠═b0ba2f26-291f-4204-942f-2b87cd5ba8a8\n# ╟─5c1b3bac-98d2-4d5b-b8ef-85ca8e2a4f80\n# ╠═6d322108-fa1b-41ad-81d6-5f36b6ef2fb1\n# ╟─6ee5e9b2-2d38-4a92-9e71-660f06bbc7a5\n# ╠═39b108b3-b41e-44c4-9565-d199c5831746\n# ╠═00484f64-99c0-43b0-97aa-2c2d3ed98318\n# ╟─2eff73ca-34ba-4a86-bc98-8543003fa46f\n# ╟─e6bbe0a2-3f9c-431a-894d-32279bef9e73\n# ╟─73a77da6-7ec7-4460-9542-bb994676a375\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "344dda87dafeb2f95a2de769f72ee8dd6dc2f340", "size": 50760, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "casestudies/Primes and Efficiency/primes.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "casestudies/Primes and Efficiency/primes.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "casestudies/Primes and Efficiency/primes.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 38.07951988, "max_line_length": 706, "alphanum_fraction": 0.7365445232, "num_tokens": 21336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948495, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.7954626323671798}}
{"text": "\n\npeaks(x::AbstractArray,y::AbstractArray) = 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) - 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) - 1/3*exp(-(x+1).^2 - y.^2) \npeaks(x::Number,y::Number) = 3*(1-x)^2*exp(-(x^2) - (y+1)^2) - 10*(x/5 - x^3 - y^5)*exp(-x^2-y^2) - 1/3*exp(-(x+1)^2 - y^2) \npeaks(v::AbstractVector) = peaks(v[1],v[2])\n\nPower(a,b) = a^b\nE = e\ngrad_peaks(x::Number, y::Number) = SVector((-2*Power(E,-2*x - Power(x,2) - Power(1 + y,2))* (-(Power(E,2*y)*(1 + x)) + 9*Power(E,2*x)*(1 - 2*Power(x,2) + Power(x,3)) + Power(E,1 + 2*x + 2*y)*(3 - 51*Power(x,2) + 30*Power(x,4) + 30*x*Power(y,5))))/3., (-2*Power(E,-2*x - Power(x,2) - Power(1 + y,2))* (-(Power(E,2*y)*y) + 9*Power(E,2*x)*Power(-1 + x,2)*(1 + y) + 3*Power(E,1 + 2*x + 2*y)*y*(-2*x + 10*Power(x,3) + 5*Power(y,3)*(-5 + 2*Power(y,2)))))/3.)\ngrad_peaks(v::AbstractVector) = grad_peaks(v[1], v[2])\n\ngrad_scaled_peaks(x, y) = 0.1*grad_peaks(x/1000, y/1000)\ngrad_scaled_peaks(v::AbstractVector) = 0.1*grad_peaks(v/1000)\nscaled_peaks(x,y) = 100*peaks(x/1000, y/1000)\nscaled_peaks(v::AbstractVector) = 100*peaks(v/1000)\n\nfunction plot_peaks(n=100)\n    x = linspace(-4, 4, n)\n    y = linspace(-4, 4, n)\n    surface(x,y,peaks)\nend\n\nfunction plot_scaled_peaks(n=100)\n    x = linspace(-4000, 4000, n)\n    y = linspace(-4000, 4000, n)\n    surface(x,y,scaled_peaks, ratio=:equal)\nend\n\n\npeaks2(x,y) = 3*(1-x)^2*exp(-(x^2) - (y+1)^2) - 7*(x/5 - x^2 - y^4)*exp(-x^2/2-(y)^2) - 1/3*exp(-(x+1)^2 - y^2) \npeaks2(v) = peaks2(v[1], v[2])\nscaled_peaks2(x,y) = 70*peaks2(x/1000, y/1000)\nscaled_peaks2(v) = scaled_peaks2(v[1], v[2])\n\ngrad_peaks2(x,y) = SVector((exp(-2*x - Power(x,2) - Power(1 + y,2))*\n      (10*exp(2*y)*(1 + x) - 90*exp(2*x)*(1 - 2*Power(x,2) + Power(x,3)) - \n        21*exp(1 + 2*x + Power(x,2)/2. + 2*y)*\n         (1 - Power(x,2) + 5*Power(x,3) + 5*x*(-2 + Power(y,4)))))/15.,\n   (2*exp(-Power(1 + x,2) - Power(y,2))*y)/3. + \n    28*exp(-Power(x,2)/2. - Power(y,2))*Power(y,3) - \n    6*exp(-Power(x,2) - Power(1 + y,2))*Power(-1 + x,2)*(1 + y) - \n    (14*exp(-Power(x,2)/2. - Power(y,2))*y*(-x + 5*Power(x,2) + 5*Power(y,4)))/5.)\ngrad_peaks2(v) = grad_peaks2(v[1], v[2])\n\ngrad_scaled_peaks2(v) = 0.07*grad_peaks2(v[1]/1000, v[2]/1000)\n\n#=\ngrad_peaks2(x,y) = SVector((Power(E,-2*x - Power(x,2) - Power(1 + y,2))*\n      (10*Power(E,2*y)*(1 + x) - 90*Power(E,2*x)*(1 - 2*Power(x,2) + Power(x,3)) - \n        21*Power(E,1 + 2*x + Power(x,2)/2. + 2*y)*\n         (1 - Power(x,2) + 5*Power(x,3) + 5*x*(-2 + Power(y,4)))))/15.,\n   (2*Power(E,-Power(1 + x,2) - Power(y,2))*y)/3. + \n    28*Power(E,-Power(x,2)/2. - Power(y,2))*Power(y,3) - \n    6*Power(E,-Power(x,2) - Power(1 + y,2))*Power(-1 + x,2)*(1 + y) - \n    (14*Power(E,-Power(x,2)/2. - Power(y,2))*y*(-x + 5*Power(x,2) + 5*Power(y,4)))/5.)\n=#\n", "meta": {"hexsha": "94f7278470a55afea1ef78df897c58f52345f04f", "size": 2746, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/peaks.jl", "max_stars_repo_name": "zsunberg/Powseeker.jl", "max_stars_repo_head_hexsha": "2c62dd2ce4bcda20eb67e73262f3264509950683", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/peaks.jl", "max_issues_repo_name": "zsunberg/Powseeker.jl", "max_issues_repo_head_hexsha": "2c62dd2ce4bcda20eb67e73262f3264509950683", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/peaks.jl", "max_forks_repo_name": "zsunberg/Powseeker.jl", "max_forks_repo_head_hexsha": "2c62dd2ce4bcda20eb67e73262f3264509950683", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.1754385965, "max_line_length": 452, "alphanum_fraction": 0.5258557902, "num_tokens": 1332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7954620288630088}}
{"text": "using Plots\n\ncList = [complex(-0.4,-0.6), complex(0,-1),\n            complex(-0.12,-0.75), complex(-0.6,0),\n                complex(-0.8,0.16), complex(-0.4,0.6)]\n\nfunction JuliaSet(c, opnum)\n    abst = zeros((601,601))\n    k = (1 + sqrt(1 + (4 * abs(c)))) / 2\n    inum = 0\n    for i in -1.5:0.005:1.5\n        inum += 1\n        jnum = 0\n        for j in -1.5:0.005:1.5\n            jnum += 1\n            z = complex(i,j)\n            for n in 1:opnum\n                z = (z^2) + c\n                if abs(z) > k\n                    abst[inum,jnum] = abs(z)\n                    break\n                # else\n                #     abst[inum,jnum] = k\n                end\n            end\n        end\n    end\n    return abst\nend\n\n# theme(:dark)\n\nfor C in 1:length(cList)\n    data = JuliaSet(cList[C], 100)\n    heatmap(data, c = cgrad(:solar, rev = false), legend = false, border=:none, title = \"C = $(cList[C])\")\n    savefig(\"C:\\\\Users\\\\Yaghoub\\\\Documents\\\\GitHub\\\\ComputationalPhysics-Fall2021\\\\ProblemSet2\\\\Figs\\\\Q1\\\\JuliaSet$C.png\")\nend\n", "meta": {"hexsha": "2ec1ef2af91c703b865a691e83f49058a2d35abf", "size": 1032, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSet2/Codes/Q1/Q1.jl", "max_stars_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_stars_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSet2/Codes/Q1/Q1.jl", "max_issues_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_issues_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSet2/Codes/Q1/Q1.jl", "max_forks_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_forks_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-21T11:07:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-21T11:07:08.000Z", "avg_line_length": 27.1578947368, "max_line_length": 122, "alphanum_fraction": 0.4660852713, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514736, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7954620230887871}}
{"text": "using Statistics,QuadGK\r\n\r\nusing Optim,Roots\r\n\r\n\r\nmutable struct  EuropeanOption\r\n    St::Float64 #current assset price 当期价格\r\n    K::Float64 #strike price 行权价\r\n    T::Float64 #maturity time 到期时间\r\n    t::Float64 #valuation date 有效日期\r\n    r::Float64 #risk_less rate 无风险收益率\r\n    σ::Float64 #volatility 波动率\r\n    type::String #option type(call,put) 看涨、看跌\r\n    # EuropeanOtion(St,K,T,t,r,σ,type)=new(St,K,T,t,r,σ,type)\r\nend\r\n\r\n\r\n#正态分布，数值累计积分算法\r\nfunction CDF_dn1(x)\r\n    a1 = 0.31938153\r\n    a2 = -0.356563782\r\n    a3 = 1.781477937\r\n    a4 = -1.821255978\r\n    a5 = 1.330274429\r\n    l = abs(x)\r\n    k = 1 / (1 + 0.2316419 * l)\r\n\r\n    CND = 1 - 1 / sqrt(2 * π) * exp(-l^2 / 2) * (a1 * k + a2 * k^2 + a3 * k^3 + a4 * k^4 + a5 * k^5)\r\n\r\n    if x < 0\r\n        return 1 - CND\r\n    end\r\n\r\n    return CND\r\nend\r\n\r\n\r\n#BSM公式定价\r\n#dN(x)标准正太函数显示表达（即高斯函数）\r\n#CDF_dn(x)高斯函数积分\r\nfunction BSM_value(o::EuropeanOption,greeks::Bool)\r\n    dN(x)=exp(-0.5*x^2)/sqrt(2*pi)\r\n    CDF_dn(x)=quadgk((x)->dN(x),-20,x)[1]\r\n\r\n    d1=(log(o.St/o.K)+(o.r+o.σ^2/2)*o.T)/(o.σ*√o.T)\r\n    d2=d1-o.σ*√o.T\r\n\r\n    option_value=0.0\r\n\r\n    if o.type==\"put\"\r\n        option_value=CDF_dn(-d2)*o.K*exp(-o.r*o.T)-CDF_dn(-d1)*o.St\r\n    else\r\n        option_value=o.St*CDF_dn(d1)-exp(-o.r*o.T)*o.K*CDF_dn(d2)\r\n    end\r\n\r\n    if greeks\r\n        vega=o.St*dN(d1)*√o.T\r\n        δ=CDF_dn(d1)\r\n        γ=dN(d1)/(o.St*o.σ*√o.T)\r\n        ρ=o.K*o.T*exp(-o.r*o.T)*CDF_dn(d2)\r\n        θ=-(o.St*dN(d1)*o.σ/(2*√o.T)+o.r*o.K*exp(-o.r*o.T)*CDF_dn(d2))\r\n        return [option_value,vega,δ,γ,ρ,θ]\r\n    else\r\n        return [option_value]\r\n    end\r\n\r\nend\r\n#\r\n#\r\n\r\n\r\n#格式化函数为，find_zero提供标准输入\r\nfunction formatfun(o::EuropeanOption,x)\r\n    o.σ=x\r\n    z=BSM_value(option)[1]\r\nend\r\n\r\n\r\n#隐含波动率计算\r\nfunction imp_vol(o::EuropeanOption,x,c0)\r\n    fi(x)=formatfun(o,x)-c0\r\n    z=find_zero(fi,(0,1),Bisection())\r\n    return z\r\nend\r\n\r\n\r\n\r\n# option=EuropeanOption(100.0,100.0,1,0,0.05,0.2,\"call\")\r\n# option_values=BSM_value(option,false)\r\n#\r\n# vega=option_values[2]\r\n", "meta": {"hexsha": "e70ce3b2cb52a9ce0b0058e54d6f5345e204ded1", "size": 1979, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "BSM_OPTION.jl", "max_stars_repo_name": "Alchemist-yao/Julia4Derivatives", "max_stars_repo_head_hexsha": "c42a46583a354f326a4f1527fc1c05606170ea4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-09T02:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T02:51:59.000Z", "max_issues_repo_path": "BSM_OPTION.jl", "max_issues_repo_name": "Alchemist-yao/Julia4Derivatives", "max_issues_repo_head_hexsha": "c42a46583a354f326a4f1527fc1c05606170ea4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BSM_OPTION.jl", "max_forks_repo_name": "Alchemist-yao/Julia4Derivatives", "max_forks_repo_head_hexsha": "c42a46583a354f326a4f1527fc1c05606170ea4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5108695652, "max_line_length": 101, "alphanum_fraction": 0.564426478, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102571131692, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.795394206583762}}
{"text": "# Algorithm 2.1\n# Bisection algorithm for finding the solutions to f(x) = 0\n\nfunction bisect_approx(f, a, b, tolerance, maxIter)\n\tfa = f(a)\n\tfor i ∈ 1:maxIter\n\t\tp = a + (b - a)/2\n\t\tfp = f(p)\n\t\tif fp == 0 || (b - a)/2 < tolerance\n\t\t\treturn p\n\t\tend\n\t\tif sign(fa) == sign(fp)\n\t\t\ta = p\n\t\telse\n\t\t\tb = p\n\t\tend\n\tend\n\tthrow(ArgumentError(\"Method failed\"))\nend\n\nprintln(bisect_approx(sin, 1, 2π, 0.01, 100))\n", "meta": {"hexsha": "2b28796f5d7d8ae68be43afac275410c9fea1c81", "size": 399, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter2/bisection.jl", "max_stars_repo_name": "Matt8898/julia-numerical", "max_stars_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-05T01:36:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-26T04:07:41.000Z", "max_issues_repo_path": "chapter2/bisection.jl", "max_issues_repo_name": "Matt8898/julia-numerical", "max_issues_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter2/bisection.jl", "max_forks_repo_name": "Matt8898/julia-numerical", "max_forks_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.1363636364, "max_line_length": 59, "alphanum_fraction": 0.6040100251, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7953877187907152}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.21\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 59afc220-9195-11eb-2384-29ae6f4aa263\nmd\"\"\"\n### REPL 101\n\n- `]` enters the package manager\n- `;` enters the terminal\n- `?` gives you the documentation of a function\n\"\"\"\n\n# ╔═╡ e5c840d8-8978-11eb-37fa-77fb05a3d821\nmd\"\"\"\n# Multi-dimensional `Array`s\n_continuation_ ([read more](https://docs.julialang.org/en/v1/manual/arrays/))\n\nThere are a bunch of basic functions one has to know to effectively work with arrays.\n\n##### Constructing arrays\n\n```julia\nA = zeros(T, sizes...)\nB = ones(T, sizes...)\nC = rand(T, sizes...)\nD = copy(A)\nE = reshape(A, new_sizes...)\n```\n\n##### Working with arrays\n```julia\neltype(A)\nlength(A)\nsize(A)\neachindex(A) # iterator for visiting each position in A\n```\n\n##### Concatenating arrays\nArrays can be concatenated with the `;` syntax\n```julia\nA = rand(3)\nB = zeros(3)\nC = [A; B]\n```\n\nor with the `cat` functions\n```julia\nC = cat(A,B,dims=1) # What would happens if `dims=2`\n```\n\n### Linear indexing\nWhen exactly one index `i` is provided, that index no longer represents a location in a particular dimension of the array but the `i`th element using the **column-major order**\n```julia\nA = [2 6; 4 7; 3 1]\n\nA[5] == vec(A)[5] == 7\n```\n\n- Question: How to understand the matrix-creation notation (for example with `A`) from the concatenation operator `;`?\n\n### Array `@views`\n\n**Slicing operations like x[1:2] create a copy by default in Julia**\n\nA “view” is a data structure that acts like an array, but the underlying data is actually part of another array (reference!).\n\n```julia\nA = [1 2; 3 4]\n\nb = view(A, :, 1)\nb = @views A[:,1]\n\nb[2] = 99\nA\n```\n\nNote: Sometimes it's not faster to use `view`s!\n\"\"\"\n\n# ╔═╡ 8636e926-8b38-11eb-3f98-f58135f3d02e\nmd\"\"\"\n### Broadcasting and loop fusions\nIt is common to have \"vectorized\" versions of functions, which simply `map` a function `f(x)` to each element of an array `a`. Unlike some languages, in `Julia` this is **not required** for performance: it's just a convenient for-loop.\n\nThis is achieved through the `dot` syntax\n```julia\na = [0 π/2; -π/2 π/6]\nsin.(a)\n```\n\nDue to historical (and parsing) reasons, the `dot` syntax for infix operators in on the left\n```julia\na = [1.0, 2.0, 3.0]\na .^ 3 # NOT the power of a vector\n```\n\nOn complicated expression with several `dot` calls, the operation is fused together (there will be a single loop)\n```julia\nb = 2 .* a.^2 .+ sin.(a)\n```\n\nThe `@.` macro can be used to convert all function / operator calls in an expression to a `dot`-call\n```julia\nb = @. 2 * a^2 + sin(a)\n```\n\nand a `$` inserted to bypass the dot\n```julia\n@. sqrt(abs($sort(x))) # equivalent to sqrt.(abs.(sort(x)))\n```\n\nNaturally calls like\n```julia\nsin.(sort(cos.(X)))\n```\ncan't be completely fused together.\n\n**Singleton (size=1) and missing dimensions are expanded to match the extents of the other arguments by virtually repeating the value.**\n```julia\na = rand(2,2)\nb = zeros(2,2,3)\na .+ b\n```\n\nDot calls are just syntatic sugar for `broadcast(f, As...)` so you can extend _broadcasting_ for custom types.\n\"\"\"\n\n# ╔═╡ 540516aa-8b38-11eb-26f8-d31b72022689\nmd\"\"\"\n#### Exercise: \n  - Convince yourself that the loop is indeed fused by `@time`ing a complex `dot`ed expression vs the expression terms seperately computed. Run the code once beforehand to avoid timing the compilation time!\n\"\"\"\n\n# ╔═╡ 53f03512-8b38-11eb-031b-55d81ef5aeac\nmd\"\"\"\n##### Solution:\n\n```julia\na = rand(100_000)\n\nf(a) = @. a ^ 2 + sin(2a) / (a ^ 3)\n\nfunction g(a)\n\tb = a .^ 2\n\tc = sin.(2a)\n\td = a .^ 3\n\te = c ./ d\n\tf = b + e\n\treturn f\nend\n\n# Make sure they are doing the same thing\n@assert f(a) == g(a)\n\n@time f(a);\n@time g(a);\n```\n\"\"\"\n\n# ╔═╡ 533f5a58-8b38-11eb-1c75-61000cf8394f\nmd\"\"\"\n\n# `using LinearAlgebra`\n\n\"High-level\" mathematical functions to operate on (multi-)dimensional `Array`s.\n\nAssume that when you call methods from [`LinearAlgebra`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/) that libraries like OpenBLAS (default) will be called for standard types such as `Float64`.\n\nIf your life depends on OpenBLAS-like operations its worth to check other implementations such as Intel's MKL or even pure Julia's like `Octavian.jl` (especially if your matrices are more interesting than dense ones).\n\n### `LinearAlgebra` vs `GenericLinearAlgebra`\n\nGeneric programming allied with multiple dispatch allows one to share types with generic algorithms. An example of this is `GenericLinearAlgebra`, which implements some of `LinearAlgebra` functions in pure Julia.\n\"\"\"\n\n# ╔═╡ e6cc166a-8ed2-11eb-23be-2d657eb00795\nmd\"\"\"\n#### Exercise: Quantum Ising\n\n- Consider a finite ``1``D spin-chain Hamiltonian with ``N`` sites coupled to a magnetic field `` H_N = -\\sum^N_i \\sigma^z_i \\otimes \\sigma^z_{i+1} - h \\sum^N_i \\sigma^x_i`` with ``\\sigma^z_i \\otimes \\sigma^z_{i+1} := ... \\otimes \\mathbb{1}_{i-1} \\otimes \\sigma^z_i \\otimes \\sigma^z_{i+1} \\otimes \\mathbb{1}_{i+1}  \\otimes ...``\n\n  - Define the identity ``\\mathbb{1}_2`` and Pauli matrices.\n  - Take the Kronecker products using the function `kron` at all sites `i` and sum them.\n  - Diagonalise the Hamiltonian `using LinearAlgebra`'s `eigen` function\n    - Which states (columns of the eigenvectors matrix) have the lowest energy for ``h=0`` and ``h \\gg 1``?\n\"\"\"\n\n# ╔═╡ 247b2cf8-8ed3-11eb-19ee-fd0f17cec519\n#= md\"\"\"\n##### Solution:\n\n```julia\nfunction H(;N,h)\n\tid = [1 0; 0 1]\n\tσˣ = [0 1; 1 0]\n    σᶻ = [1 0; 0 -1]\n\t\n\t# final Hamiltonian\n\thamiltonian = zeros(Float64, 2^N, 2^N)\n\t\n\t# kinetic term: sum only until (N-1) because there's no site to the right of N\n\tfor i in 1:(N-1)\n\t\t\n\t\t# For each site contribution, σᶻ will be at position k and k+1\n\t\tmat(k) = k == i || k == (i + 1) ? σᶻ : id\n\t\t\n\t\t# kronecker products\n\t\tout = mat(1)\n\t\tfor j in 2:N\n\t\t\tout = kron(out, mat(j))\n\t\tend\n\n\t\t# Add contribution to the Hamiltonian\n\t\thamiltonian -= out\n\tend\n\t\n\t# magnetic term: can take sum everywhere\n\tfor i in 1:N\n\t\n\t\t# For each site contribution, σᶜ will be at position k\n\t\tmat(k) = k == i ? σˣ : id\n\t\t\n\t\t# kronecker products\n\t\tout = mat(1)\n\t\tfor j in 2:N\n\t\t\tout = kron(out, mat(j))\n\t\tend\n\t\t\n\t\t# Add contribution to the Hamiltonian\n\t\thamiltonian -= h .* out\n\tend\n\treturn hamiltonian\nend\n```\n\nWith a function that can generate the Hamiltonian generally, it's easy to check for the eigenstates.\n\nSince the eigenvalues are sorted by ascending value, we just need to look at the first terms\n\n```julia\nusing LinearAlgebra\n\nh1 = H(N=8, h=0.0);\nh2 = H(N=8, h=100);\n\nvals1, vecs1 = eigen(h1);\nvals2, vecs2 = eigen(h2);\n\n@show vecs1[:,1]; # Vectors all pointing in the same direction\n@show vecs2[:,1]; # Vectors aligned with σˣ (equal super-position of eigenstates)\n```\n\"\"\" =#\n\n# ╔═╡ 9ba8170a-7b50-11eb-0aac-adc493e1f386\nmd\"\"\"\n# A first taste of functional programming\n\n**Functional programming** a programming paradigm where programs are constructed by applying and composing functions.\n\nFunction definitions are trees of expressions that map values to other values.\nUnlike imperative programming, in which a sequence of imperative statements which updates the running state of the program.\n\nThere are 2 main conceptes from FP which have clear benefits for scientific code\n- Higher-order functions\n- Pure functions\n\n## Higher order functions\n\nIn Julia the functions are already first-class citizens (can pass them as arguments, return them and assign them to variable names).\n\nA higher-order function is a function that\n- takes other functions as arguments\nand/or\n- returns a function as result\n\n\n### Function composition and piping\nMany times in scientific code it's required that functions are chained together.\n\nThis can be quite of eye sore\n```julia\nsqrt(abs(sum([1,2,3])))\n```\n\nFunction composition `\\circ`\n```julia\n(sqrt ∘ abs ∘ sum)([1,2,3])\n```\n\nand piping\n```julia\nsum([1,2,3]) |> abs |> sqrt\n```\nalleviate this problem for _unary_ (single-argument) functions.\n\"\"\"\n\n# ╔═╡ c9862c2a-897e-11eb-3592-ada39cc0637b\nmd\"\"\"\n#### Exercise: Becoming a pastry chef\n(Re)create some syntatic sugar such as\n- a function composition operator `∘` for _unary_ functions\n- a reverse pipe `<|`\n\nNote: infix operators such as `∘` need to be wrapped around `()` in method definitions for parsing reasons.\n\"\"\"\n\n# ╔═╡ 44b9eb9c-8980-11eb-17b8-1937532d3a28\nmd\"\"\"\n##### Solution:\n```julia\n(∘)(f::Function, g::Function) = (x...) -> f(g(x...))\n\n(<|)(f::Function, args...) = f(args...)\n```\n\"\"\"\n\n# ╔═╡ af38a46c-8981-11eb-26de-35f9e487423c\nmd\"\"\"\nOne of the most glaring differences between functional and imperative programming is that functional avoids _side effects_, which are needed in imperative style to control the state of the program.\n\nHere are examples of higher-order functions that take us closer to the functional heaven.\n\n### map\n\n`map(f, [a1,a2,...]) = [f(a1), f(a2), ...]`\n\n`map(g, [a1,a2,...], [b1,b2,...]) = [g(a1,b1), g(a2,b2), ...]`\n\nMaps a function over the elements of a container and collect the results\n\n```julia\n# data\nv1 = [1, 2, 3]\nv2 = [10, 20, 30]\n\n# imperative\nout = zero(v1)\nfor i in eachindex(v1) # equivalent to 1:length(v1)\n\tout[i] = v1[i] + v2[i]\nend\n\n# functional\nout = map(+, v1, v2)\n```\n\n##### `map` vs `broadcast`\n  - Broadcast only handles containers with th \"shapes\" `M×N×...` (i.e., a size and dimensionality) while map is more general (unknown length iterator)\n  - Map requires all arguments to have the same length (and hence cannot combine arrays and scalars)\n\n### foreach\n`foreach(f, [a1,a2,...]) = f(a1); f(a2); ...; nothing` \n\nMap a function over the elements of a container but without collecting the results\n\n```julia\n# data\nv = [1, 2, 3]\n\n# imperative\nfor i in eachindex(v)\n\tprintln(v[i])\nend\n\n# functional\nforeach(println, v)\n```\n\n### foldl and foldr\n`foldl(op, [a1, a2, a3, ...]) = op(op(op(a1, a2), a3), ...)`\n\n`foldr(op, [a1, a2, a3, ...]) = op(a1, op(a2, op(a3, op(...))))`\n\nFolds are ubiquitous in functional and scientific programming. They are a class of functions that process some data structure and return a value. Basically a left- and right- associative reduce.\n\n```julia\n# data\nv = [1, 2, 3, 4]\n\n# binary function\nop = *\n\n# imperative\nout = v[1]\nfor i in 2:length(v)\n\tout = op(out, v[i])\nend\n\n# functional\nout = foldl(op, v)\n```\n\nQuestion: why is there a distinction between left and right folds?\n\nFor most cases these binary functions are not associative!\n\nWe implicitely have left- and right- associativeness hard coded in our brain. What's `0 - 1 - 2 - 3 - 4` ?\n- left-associative `((((0 - 1) - 2) - 3) - 4) == -10`\n- right-associative `(0 - (1 - (2 - (3 - 4)))) == 2`\n\nAn initial value cal also be passed as a _keyword_\n```julia\nfoldl(=>, 1:4) == ((1 => 2) => 3) => 4\nfoldl(=>, 1:4; init=0) == (((0 => 1) => 2) => 3) => 4\n```\n\"\"\"\n\n# ╔═╡ afc5f13c-8ee2-11eb-2dfe-0dcbc74c120e\nmd\"\"\"\n#### Exercise: folding left and right\n- Use a folding operator to find the `min`imum element in a container\n  - Define your own `min(a,b)` function or use Julia's\n\"\"\"\n\n# ╔═╡ bded83c2-8ee2-11eb-3b00-a7681ba476dc\nmd\"\"\"\n##### Solution:\n\n```julia\nmy_min(x,y) = x < y ? x : y\nmin_fold(c) = foldl(my_min, c)\n```\n\"\"\"\n\n# ╔═╡ 0d6a34a4-8ee3-11eb-08ae-2763ca230fd5\nmd\"\"\"\n### mapreduce\n`mapreduce(f, op, [a1, a2, a3, ...]) = op(op(op(f(a1), f(a2)), f(a3)), ...)`\n\nApplies a function `f` to each element of the container and `reduces` the result using a binary function `op`.\n\n```julia\n# data\nv = [1, 2, 3, 4]\n\n# operations\nf = sin\nop = *\n\n# imperative\nout = 1.0\nfor i in eachindex(v)\n\tout = op(out, f(v[i]))\nend\n\n# functional\nout = mapreduce(f, op, v; init=1.0)\n```\n\nUnlike a `fold`, a `reduce` operation **assumes associativity** with the binary operations. If this cannot be guaranteed, a `mapfoldl` or `mapfoldr` can be used instead.\n\nQuestion: Where could a `reduce` operation be preferred (computationally!) over a fold?\n\n\nIt doesn't end here: check also `filter`, `reduce` and possible multiple chains with `Transducers.jl`.\n\"\"\"\n\n# ╔═╡ 59e7aaf0-8cac-11eb-0ea8-3fb87d36ad90\nmd\"\"\"\n#### Exercise: Wilson chains \n- Consider a finite ``1``D Wilson chain with ``N`` sites `` H_N = -\\sum^N_i \\alpha^{-i} \\sigma^z_i \\otimes \\sigma^z_{i+1}`` for ``\\alpha \\ge 1``\n  - Build the Hamiltonian in a functional way. Suggestion:\n    - Use `mapfold` or `fold` to take the Kronecker products\n\n- Numerically renormalize the problem by iterating\n  - Diagonalise ``H_N =: U_N D_N U^\\dagger_N`` `using LinearAlgebra`'s `eigen` function\n  - Truncate ``H_N \\rightarrow \\tilde{H}_N`` by taking only the half lowest eigenvalues\n  - Coupling ``\\tilde{H}_N`` to a next site in the chain ``H_{N+1} = \\tilde{D}_N \\otimes \\mathbb{1}_2 - \\alpha^{-(N+1)} \\tilde{\\sigma}^z_N \\otimes \\sigma^z_{N+1}`` where ``\\tilde{\\sigma}^z_N = \\tilde{U}_N \\sigma^z_N \\tilde{U}_N^†``\n\nTip: A diagonal matrix can be created out of the vector of eigenvalues with the `diagm` function and the adjoint of a matrix is achieved with the `adjoint` function or `'` operator after the matrix.\n\"\"\"\n\n# ╔═╡ 45c45594-8ca4-11eb-1db9-6187459bf306\n#= md\"\"\"\n##### Solution:\n\n```julia\nusing LinearAlgebra\n\nconst id = [1 0; 0 1]\nconst σᶻ = [1 0; 0 -1]\n\n# Wilson chain Hamiltonian\nfunction H(N, α)\n\tT(i) = -α^(-i) * mapreduce(j -> j == i || j == i + 1 ? σᶻ : id, kron, 1:N)\n\treturn mapreduce(T, +, 1:(N-1))\nend\n\n# Couple H to the chain site `n`\nfunction add_chain(H, n, α)\n\t# truncates half of the highest eigenvalues\n\tλ̃, Ũ = let\n\t\tλ, U = eigen(H)\n\t\tN₂ = length(λ) ÷ 2\n\t\tλ[1:N₂], U[1:N₂, 1:N₂]\n\tend\n\n\tσᶻₙ = let\n\t\tn = ceil(Int, log2(length(λ̃))) # number of sites in H̃\n\t\tmapreduce(i -> i == n ? σᶻ : id, kron, 1:n)\n\tend\n\t\n\t# Rotate σᶻ → σ̃ᶻₙ and add chain\n\treturn kron(diagm(λ̃), id) - α^(-(n+1)) * kron(Ũ * σᶻₙ * Ũ', σᶻ)\nend\n\n# Numerical renormalization group\nrg(;N,α,steps=0) = foldl((h, i) -> add_chain(h, N+i, α), 1:steps; init=H(N, α))\n```\n\"\"\" =#\n\n# ╔═╡ 4bee5324-8eeb-11eb-326b-efba53215f34\nmd\"\"\"\n### Pure functions\n_Pure thoughts_\n\nAnother great tool of functional programming we should steal for scientifc programming is the concept of pure functions. These functions are very close to mathematical functions.\n\n- The function return values are identical for identical arguments\n- The application of the function has no side effects\n  - No mutation of non-local variables or mutable reference arguments\n\nExamples of _indecent thoughts_:\n\nMutation of non local variables ⚰️⚰️⚰️\n```julia\nf() = x[1] += 1\n\nx = [1]\n@show x\n\nf()\n@show x\n```\n\nDifferent return values with identical arguments 🪦🪦🪦\n```julia\nf() = x\n\nx = 1\n@show f()\n\nx = 2\n@show f()\n```\n\n##### Why do I care?\n- Becase you're not a sociopath\n- If the result of a pure expression is not used, it can be removed without affecting other expressions.\n- Pure functions have no side-effects and you can intelectually refeer to them as being _referentially transparent_, just like mathematical functions\n- Since they only depend on their arguments, different function calls can't interfer with each other (great for parallel programming!)\n- No side effects means your compiler can, theoretically, safely apply \n- Unit tests are valid and can be injected anywhere\n\"\"\"\n\n# ╔═╡ 28f63950-8eef-11eb-0481-55fad44619d5\nmd\"\"\"\n### Meta-discussion: mutable vs immutable/pure algorithms\n\nImmutability doesn't really exist: immutability implies time-independence... and there's nothing really stopping time (at least until the heat-death of the universe).\n\nThe very process of storing information (that is ordering bits) requires mutation.\nBut we can achieve immutability at least syntatically.\n\n\n##### Tips to scientific code right, denying mutation and and promoting good hygiene\n\n- Use `let` blocks to reduce global scope pollution\n    - Global variables are **very** prone to be mutated since they don't have to be passed as an argument explicitely\n\n\n- Pure thoughts: decompose programs into (pure) functions:\n    - Break software into chunks to fit into the most limited memory: human memory.\n\n\n- Give functions and variables meaningful names\n    - Use `Pluto` notebooks to prototype\n\n\n- Use tuples / structs to avoid repetition\n    - `a1 = 1, a2 = 2` becomes `as = (1, 2)`\n\n\n- Be defensive\n    - Add `@assert`s to ensure validity of your inputs / results\n    - Generate unit tests for your functions: these are as important as the problem you are ultimately solving\n\n\n- Be smart by not oversmarting yourself:\n    - avoid _premature optimisation_: write clear and concise code and only think about optimisations after unit testing\n    - avoid _premature pessimisation_: take a chill pill and sketch on paper the data structures / algorithm design before writing any code\n    - require of your code the same standards you require others' calculations / experiments / general care in life\n\n\nRead more on good Scientific Practises\n- [1](https://swcarpentry.github.io/good-enough-practices-in-scientific-computing/)\n- [2](https://arxiv.org/pdf/1210.0530v3.pdf)\n- [3](https://blog.higher-order.com/blog/2009/04/27/a-critique-of-impure-reason/)\n\"\"\"\n\n# ╔═╡ 8ac22e72-8978-11eb-1674-e1b95403e215\nmd\"\"\"\n# Performance\nWe will step out of the beautiful pure world of functional programming and dive deep into the messy world of algorithm optimisation.\n\nWhile some topics will be related to avoiding common pitfalls when writing in Julia, other universal topics on algorithm optimisation will also be covered.\n\n## Profiling\nIn order to know where and what to optimise we need tools to diagnose time spent, memory allocations and possibly how machine code is being generated.\n\n- For quick-and-dirty diagnostics (time and memory tracking) we can use the `@time` macro behind function calls\n- For an accurate measure of the latter preferer `using BenchmarkTools` and the `@btime` macro (this will give you the lower bound of `@benchmark`, which is what you want to measure!)\n- For more serious profiling tools, consider reading the [manual section](https://docs.julialang.org/en/v1/manual/profile/)\n\n\nThe code can be inspected at several stages with the macros\n- The AST after parsing: `@macroexpand`\n- The AST after type inference and some optimizations: `@code_typed` (prefer `@code_warntype`)\n- The LLVM and assembly: `@code_llvm`, `@code_native`\n\nRead more on [introspection](https://docs.julialang.org/en/v1/devdocs/reflection/)\n\"\"\"\n\n# ╔═╡ 8d9f2162-8f07-11eb-1c1d-b994b88811e1\nmd\"\"\"\n#### Exercise: Not all \"created\" equal\nBenchmark the different ways of mapping a function to a container and realise that computationally not all operations are equivalent\n- `map`\n- `broadcast`\n- list comprehension\n- explicit `for`-loop\n\"\"\"\n\n# ╔═╡ bff46124-8f08-11eb-1140-d78145e2fe05\n#= md\"\"\"\n\n```julia\nusing BenchmarkTools\n\nfmap(x) = map(x -> 2x, x)\n\nfdot(x) = 2 .* x\n\nfcomprehension(x) = [2x for x in x]\n\nfunction floop(x)\n    y = similar(x) # prefer similar to zero as it only has to allocate (and not zero)\n    for i in eachindex(x)\n        y[i] = 2*x[i]\n    end\n    return y\nend\n\nx = rand(10_000)\n\n# The $ interpolates values into the expression avoiding the global-variable problem\n\n@btime fmap($x);\n# > 7.977 μs (2 allocations: 78.20 KiB)\n@btime fcomprehension($x);\n# > 7.890 μs (2 allocations: 78.20 KiB)\n@btime fdot($x);\n# > 8.238 μs (2 allocations: 78.20 KiB)\n@btime floop($x);\n# > 9.495 μs (2 allocations: 78.20 KiB)\n```\n\"\"\" =#\n\n# ╔═╡ fdfddce2-919d-11eb-1b48-5d31c8d4b250\nmd\"\"\"\n### Global (`isa Any`) variables: Electric Boogaloo\n_It's not over yet_\n\n[1st performance tip](https://docs.julialang.org/en/v1/manual/performance-tips/#Avoid-global-variables) on the Julia's official documentation: **Avoid global variables**\n\nA global variable might have its value, and therefore its type, change at any point. This makes it difficult for the compiler to optimize code using global variables.\n- Variables should be local\n- Or passed as arguments to functions (this way the code will be specialized for the input types)\n\n```julia\nx = rand(100_000);\n\nfunction sum_global()\n\ts = 0.0\n\tfor i in x\n\t   s += i\n\tend\n\treturn s\nend\n\nfunction sum_arg(x)\n\ts = 0.0\n\tfor i in x\n\t   s += i\n\tend\n\treturn s\nend\n\n@time sum_global()\n# 0.016230 seconds (399.49 k allocations: 7.622 MiB)\n\n@time sum_arg(x)\n# 0.000123 seconds (1 allocation: 16 bytes)\n```\n\nThis unfortunate dichotomy between the functions is due to one thing: Julia can't **specialize** the function `sum_global` since it cannot guarantee the type of `x`.\nWhile for `sum_arg`, it will specialize it for the type of `x` that is encountered (a complex `x` would trigger compilation).\n\n**Type inference did not require the type to be annotated!**\n\n`@code_warntype` can detect these `isa Any` variables or the also related type instabilities!\n\"\"\"\n\n# ╔═╡ 8a97bcb8-91a3-11eb-37b4-4f9004e01e0b\nmd\"\"\"\n#### Exercise: Purging type instabilities / \"untyped\" containers\n- Remember that an array with abstract type (e.g. `Any` or `Real`) will end up being an array of pointers and can't be operated on efficiently. `abstract` types can also prevent Julia from triggering the appropriate function specialization. Compare the `@code_native` outputs from a simple function operating on the fields of\n```julia\nmutable struct MyAmbiguousType\n   a::AbstractFloat # less ambiguous than `Any` but still ambiguous\nend\n\nmutable struct MyType{T<:AbstractFloat}\n   a::T\nend\n```\n\n- Can you spot the type instability? Fix it and consequently `@btime` and `@code_native` the new function vs the old one.\n```julia\nfunction f()\n\tx = 1\n\tfor i = 1:10\n\t\tx = x/2\n\tend\n\treturn x\nend\n```\n\"\"\"\n\n# ╔═╡ 0ae35bf0-91a6-11eb-1a75-235aaf78d346\n#= md\"\"\"\n##### Solution:\n\n```julia\nadd1(m::MyType) = m.a + 1\n\n@code_native add1(MyType{Float64}(0.3))\n@code_native add1(MyType{AbstractFloat}(0.3))\n```\n\"\"\" =#\n\n# ╔═╡ 700b1240-9197-11eb-0cfd-1bb3d7393084\nmd\"\"\"\n## Understanding timecales\nThere's a rather famous table comparing computer with human timecales\n\n| Action (3GHz) | Average latency | Human time |\n|:---------- | ---------- |:------------:|\n| 1 clock-cyle   | 0.3 ns | 1 s |\n| L1 cache    | 0.9 ns  | 3 s |\n| L2 cache    | 2.8 ns  | 9 s |\n| L3 cache    | 12.9 ns  | 43 s |\n| RAM    | 70-100 ns  | 3.5 to 5.5 min |\n| SSD/IO | 7-150 μs | 2h to 2 days |\n| Reboot | 30-60s | 1000-2000 years |\n\nIn a single cycle a photon can only travel <10 cms to the RAM better not be too far away (imagine an electron).\n\nThe slowness of RAM can be mitigated by transfering data into the caches. **BUT** when the CPU requests data from the RAM, it is checked if it's in the cache. If not, there will be a _cache miss_ and the program will stall until the data is fetched from the RAM.\n\nNaturally, to reduce these cache misses, consider\n- _Temporal locality_: If you need to access a piece of memory multiple times, do it close in time\n- _Spatial locality_: Access memory which is close to each other (since the CPU fetches chunks of data at a time)\n\nAs a corollary\n- Use little memory\n- Access data sequentially (since the CPU can prefetch data that you may need)\n\nIt doesn't end here: read more on [alignment issues](https://biojulia.net/post/hardware/#alignment) [(show-in-class)](https://juliasimd.github.io/LoopVectorization.jl/stable/examples/matrix_multiplication/)\n\n### Allocations\nMemory allocation can be a significant bottleneck in critical operations.\nDynamic languages such as Julia usually employ a _garbage collector_ to allocate and deallocate objects in the RAM for us\n```julia\na = [1,2,3] # allocation\na = nothing # the previous value of `a` is now garbage (since in this case no other variables are pointing at it) and shall be collected automatically\n```\n- Allocation and deallocation create _overhead_ which can be very costly\n- More allocations results in more memory usage which results in more cache misses\n\nThe 3 most encountered problems where this can be fixed are\n\n- When updating some value _inplace_\n```julia\nN = 1000\na = rand(10,10);\n\nfunction f1(a, N)\n\tx = zero(a)\n\tfor i in 1:N\n\t\tx += i * a # remember that updating operators such as `+=` reassign `x`\n\tend\n\tx\nend\n\n@btime f1($a, $N)\n# 436.185 μs (2001 allocations: 1.71 MiB)\n```\n\nIn this case use the **inplace (broadcasted) assignment**\n```julia\nfunction f2(a, N)\n\tx = zero(a)\n\tfor i in 1:N\n\t\tx .+= i * a # \"add element-wise to `x`\n\tend\n\tx\nend\n\n@btime f2($a, $N)\n# 354.372 μs (1001 allocations: 875.88 KiB)\n```\n\n- When running a compution whose output memory can be recycled (see the exercise!)\n\n- When taking slices (see the exercise!)\n\n\n#### Single instruction, multiple data: `@simd`\nCPUs operate on data present in registers inside the CPU, which are meant to hold small fixed size slots, like floats (see the `r`s in `@code_native`).\nSince this is a major bottleneck, modern CPUs have bigger registries (instead of 64-bit, 256+), which allow a **S**ingle **I**nstruction operate on **M**ultiple **D**ata.\n\nShow the difference of\n```julia\nusing StaticArrays\na = @SVector Int32[1,2,3,4,5,6,7,8]\ncode_native(+, (typeof(a), typeof(a)), debuginfo=:none)\n\na = @SVector Int64[1,2,3,4,5,6,7,8]\ncode_native(+, (typeof(a), typeof(a)), debuginfo=:none)\n\na = @SVector Int64[1,2,3,4]\ncode_native(+, (typeof(a), typeof(a)), debuginfo=:none)\n```\n\n- SIMD needs uninterrupted iteration of fixed length\n- Bound-checking causes branching so deactivate it with `@inbounds for i in ...` (This is also may be desirable for critical non-`@simd` loops)\n  - Avoid branching at all costs. Even with _branch prediction_, a misprediction (common for random braches) will cost several CPU cycles.\n- SIMD needs associative operations (since the loop will be reordered)\nSince float addition is **not** associative, automatic `@simd` is not \"automatically\" on for, e.g., float addition\n```julia\n@show 0.1 + (0.2 + 0.3)\n@show (0.1 + 0.2) + 0.3\n```\n\nActually, IEEE 754 float arithmetic is tricky! Consider a number that is undefined or unrepresentable, a `NaN`\n```julia\n@show NaN == NaN # not even reflexive!\n```\n\n[Reference](https://biojulia.net/post/hardware/#simd)\n\"\"\"\n\n# ╔═╡ a3346d6a-919a-11eb-13e9-59293be49654\nmd\"\"\"\n#### Exercise: The 3 ecology Rs: RECYCLE, REUSE and REDUCE\n\n- Avoid extra allocations by _recycling_\n  - Rewrite `loopinc` using an in-place version of `xinc` –> `xinc!`\n  - Compare the performance of the new `loop` function\n  - Note: The point is not to optimise away the `ret[2]` part so keep it!\n```julia\nxinc(x) = [x, x+1, x+2]\nfunction loop()\n\ty = 0\n\tfor i = 1:10^7\n\t\tret = xinc(i)\n\t\ty += ret[2]\n\tend\n\treturn y\nend\n```\n\n\n- Avoid extra allocations by _reusing_\n  - Create a `(50, 100_000)` `rand`om matrix `A` and a vector `x` with size `(100_000,)`\n  - Compare the performance of ``\\sum_i \\sum^{80000}_{j=1}A_{ij}x_j`` using `slice`s and `@view`s\n  - Note that performance from `@view` is just a [rule of thumb](https://docs.julialang.org/en/v1/manual/performance-tips/#Copying-data-is-not-always-bad).\n\n\n- Optimise away by _reducing_ (and everything else)\n```julia\nfunction work()\n\tA = zeros(N,N)\n\tfor i in 1:N\n        for j in 1:N\n            val = mod(v[i],256);\n            A[i,j] = B[i,j]*(sin(val)*sin(val)-cos(val)*cos(val))\n        end\n\tend\n\treturn A\nend\n```\n\ngiven the parameters\n```julia\nN = 4_000\nB = [float(i-j) for i in 1:N, j in 1:N]\nv = [i for i in 1:N]\n```\n\nPro-tip: Compare different implementations of `work!` using the `≈` (`\\approx`) operator, since the `==` may be too strict given the shenanigans we encountered with float arithmetics.\n\"\"\"\n\n# ╔═╡ fd81c0c0-91fd-11eb-1ddb-1546f52626af\n#= md\"\"\"\n##### Solution\nThis excellent exercise was adapted from [here](https://github.com/crstnbr/JuliaCologne21/blob/master/Day2/exercise_solutions/solution_optimization2.ipynb)\n\n```julia\nusing Test\nusing BenchmarkTools\n\n# Parameters\nN = 1_000\nB = [float(i-j) for i in 1:N, j in 1:N]\nv = [i for i in 1:N]\n\n# Base\nfunction work()\n\tA = zeros(N,N)\n\tfor i in 1:N\n        for j in 1:N\n            val = mod(v[i],256);\n            A[i,j] = B[i,j]*(sin(val)*sin(val)-cos(val)*cos(val))\n        end\n\tend\n\treturn A\nend\n\n@btime work()\n# 670.186 ms (11469981 allocations: 197.94 MiB)\n```\n\n- Purge globals!\n```julia\n@code_warntype work()\n\nfunction work1(B, v, N)\n\tA = zeros(N,N)\n\tfor i in 1:N\n        for j in 1:N\n            val = mod(v[i],256);\n            A[i,j] = B[i,j]*(sin(val)*sin(val)-cos(val)*cos(val))\n        end\n\tend\n\treturn A\nend\n\n@code_warntype work(B, v, N)\n\n@test work() ≈ work1(B, v, N)\n@btime work1($B, $v, $N)\n# 88.320 ms (2 allocations: 7.63 MiB)\n```\n\n- Analytic optimisations (these are the best)\n```julia\n@testset \"My trig identities\" begin\n\tx = rand()\n\t@test 1-2*cos(x)*cos(x) ≈ sin(x)*sin(x)-cos(x)*cos(x)\n\t@test -cos(2*x) ≈ sin(x)*sin(x)-cos(x)*cos(x)\nend\n\nfunction work2(B, v, N)\n    A = zeros(N,N)\n    for i in 1:N\n        for j in 1:N\n            val = mod(v[i],256);\n            A[i,j] = B[i,j]*(-cos(2*val));\n        end\n    end\n\treturn A\nend\n\n@test work() ≈ work2(B, v, N)\n@btime work2($B, $v, $N)\n# 37.520 ms (2 allocations: 7.63 MiB)\n```\n\n- Pull-out `val` computation\n```julia\nfunction work3(B, v, N)\n    A = zeros(N,N)\n    for i in 1:N\n\t\tval = -cos(2*mod(v[i],256))\n        for j in 1:N\n            A[i,j] = B[i,j]*val;\n        end\n    end\n\treturn A\nend\n\nfunction work4(B, v, N)\n\tval = [-cos(2*mod(x,256)) for x in v]\n\n    A = zeros(N,N)\n    for i in 1:N\n        for j in 1:N\n            A[i,j] = B[i,j]*val[i];\n        end\n    end\n\treturn A\nend\n\n@test work() ≈ work3(B, v, N)\n@test work() ≈ work4(B, v, N)\n\n@btime work3($B, $v, $N)\n# 20.755 ms (2 allocations: 7.63 MiB)\n\n@btime work4($B, $v, $N)\n# 20.262 ms (3 allocations: 7.64 MiB)\n```\n\n- Switch order of the loops: favour data locality!\n```julia\nfunction work5(B, v, N)\n\tval = [-cos(2*mod(x,256)) for x in v]\n\n    A = zeros(N,N)\n    for j in 1:N\n        for i in 1:N\n            A[i,j] = B[i,j]*val[i];\n        end\n    end\n\treturn A\nend\n\n@test work() ≈ work5(B, v, N)\n\n@btime work5($B, $v, $N)\n# 4.947 ms (3 allocations: 7.64 MiB)\n```\n\n- `@inbounds` and `@simd`\n```julia\nfunction work6(B, v, N)\n\tval = [-cos(2*mod(x,256)) for x in v]\n\n    A = zeros(N,N)\n    for j in 1:N\n        for i in 1:N\n            @inbounds A[i,j] = B[i,j] * val[i];\n        end\n    end\n\treturn A\nend\n\n@test work() ≈ work6(B, v, N)\n\n@btime work6($B, $v, $N)\n# 3.298 ms (3 allocations: 7.64 MiB)\n```\n\n- Broadcast it for beauty points\n```julia\nwork7(B, v) = return B .* [-cos(2*mod(x,256)) for x in v]\n\n@test work() ≈ work7(B, v)\n\n@btime work7($B, $v, $N)\n# 2.019 ms (3 allocations: 7.64 MiB)\n```\n\"\"\" =#\n\n# ╔═╡ 4eb2573e-8998-11eb-2274-379a03bed49c\nmd\"\"\"\n# Iteration Utilities\nFor more examples see [here](https://docs.julialang.org/en/v1/base/iterators/)\n\n### zip\nRun multiple iterators at the same time, until any of them is exhausted\n```julia\na = [1,2,3]\nb = (10,20,30)\n\nfor z in zip(a,b)\n\tprintln(z) # (1,10) ... (2, 20) ... (3, 30)\nend\n```\n\nQuestion: What is the mathematical operation equivalent of zipping?\n\n### enumerate\nAn iterator that yields `(i, x)` where `i` is a counter starting at `1`, and `x` is the `i`-th value from the given iterator\n```julia\na = [10, 20, 30]\n\nfor (i, aᵢ) in enumerate(a)\n\tprintln(\"The $i-th entry of a is $aᵢ)\nend\n```\n\"\"\"\n\n# ╔═╡ b58a861c-7b50-11eb-286d-c5a5dd03429f\n#= md\"\"\"\n# Fixed points\n\nA fixed point of a function is an element of the function's domain that is mapped to itself by the function.\n\n$ x,\\;f(x),\\;f \\circ f(x),\\;f \\circ f \\circ f(x),\\;... \\rightarrow x^*$\n\nLet's write a `Julia` function that finds the fixed point of some function `f`\n\n```julia\n\n# Identity operator\nconst id = x -> x\n\n# Ideally... Why will it fail?\nfunction ideal_fixed_point(f::Function)\n    fix(x) = f ∘ fix(x)\n    return fix\nend\n\nbad_g = fixed_point(id)\n# @show bad_g(3) why will it fail??\n```\n\n```julia\n# Need a stopping criterion\nfunction fixed_point(f::Function)\n\tfunction fix(xᵢ)\n\t\txᵢ₊₁ = f(xᵢ)\n\t\tif xᵢ₊₁ == xᵢ\n\t\t\treturn xᵢ\n\t\telse\n\t\t\treturn fix(xᵢ₊₁)\n\t\tend\n\tend\n\treturn fix\nend\n\ngood_g = fixed_point(id)\n@show good_g(3);\n\n# TODO: Write this function as a 1-liner!\nfixed_point(f::Function) = nothing\n```\n\n```julia\n# The equality condition is too strict for computations! Change it for an approximation (\\approx)\napprox_fixed_point(f::Function) = fix(xᵢ) = (xᵢ₊₁ = f(xᵢ)) ≈ xᵢ ? xᵢ : fix(xᵢ₊₁)\n\ng = approx_fixed_point(id)\n@show g(3);\n```\n\n```julia\n# Add another stopping criteria to avoid getting stuck\napprox_stop_fixed_point(f::Function; maxᵢ=10^4) = fix(xᵢ, i=1) = (xᵢ₊₁ = f(xᵢ)) ≈ xᵢ || i == maxᵢ ? xᵢ : fix(xᵢ₊₁, i+1)\n\n# Kondo poor-man's scaling equations\nkondo_rg_eqs(x; dk=-10^-3) = x .+ dk * [-2 * x[2]^2, -2 * x[1] * x[2]]\nkondo_rg = approx_stop_fixed_point(kondo_rg_eqs)\n```\n\n```julia\nusing Plots\n\ndj = 0.06\n\n# ps = hcat([[[jz, j₊] ; kondo_rg([jz, j₊])] for j₊ in 0.0:dj:1.0 for jz in -dj-j₊:-dj:-1.0]...)\n\nplot(ps[[1,3],:], ps[[2,4],:];\n\txlims = (-1,dj),\n\tylims=(-dj,1),\n\tframestyle = :origin,\n\tlegend=false)\n```\n\n```julia\n# Another example\nlogistic_map(r) = approx_stop_fixed_point(x -> r * x * (1-x))\n```\n\"\"\" =#\n\n# ╔═╡ Cell order:\n# ╟─59afc220-9195-11eb-2384-29ae6f4aa263\n# ╟─e5c840d8-8978-11eb-37fa-77fb05a3d821\n# ╟─8636e926-8b38-11eb-3f98-f58135f3d02e\n# ╟─540516aa-8b38-11eb-26f8-d31b72022689\n# ╟─53f03512-8b38-11eb-031b-55d81ef5aeac\n# ╟─533f5a58-8b38-11eb-1c75-61000cf8394f\n# ╟─e6cc166a-8ed2-11eb-23be-2d657eb00795\n# ╟─247b2cf8-8ed3-11eb-19ee-fd0f17cec519\n# ╟─9ba8170a-7b50-11eb-0aac-adc493e1f386\n# ╟─c9862c2a-897e-11eb-3592-ada39cc0637b\n# ╟─44b9eb9c-8980-11eb-17b8-1937532d3a28\n# ╟─af38a46c-8981-11eb-26de-35f9e487423c\n# ╟─afc5f13c-8ee2-11eb-2dfe-0dcbc74c120e\n# ╟─bded83c2-8ee2-11eb-3b00-a7681ba476dc\n# ╟─0d6a34a4-8ee3-11eb-08ae-2763ca230fd5\n# ╟─59e7aaf0-8cac-11eb-0ea8-3fb87d36ad90\n# ╟─45c45594-8ca4-11eb-1db9-6187459bf306\n# ╟─4bee5324-8eeb-11eb-326b-efba53215f34\n# ╟─28f63950-8eef-11eb-0481-55fad44619d5\n# ╟─8ac22e72-8978-11eb-1674-e1b95403e215\n# ╟─8d9f2162-8f07-11eb-1c1d-b994b88811e1\n# ╟─bff46124-8f08-11eb-1140-d78145e2fe05\n# ╟─fdfddce2-919d-11eb-1b48-5d31c8d4b250\n# ╟─8a97bcb8-91a3-11eb-37b4-4f9004e01e0b\n# ╟─0ae35bf0-91a6-11eb-1a75-235aaf78d346\n# ╟─700b1240-9197-11eb-0cfd-1bb3d7393084\n# ╟─a3346d6a-919a-11eb-13e9-59293be49654\n# ╟─fd81c0c0-91fd-11eb-1ddb-1546f52626af\n# ╟─4eb2573e-8998-11eb-2274-379a03bed49c\n# ╟─b58a861c-7b50-11eb-286d-c5a5dd03429f\n", "meta": {"hexsha": "a906361faecc33b80395bf0c7307e70c72532a14", "size": 33786, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "presentations/intermediate.jl", "max_stars_repo_name": "Fromeworld/JuliaSeminar", "max_stars_repo_head_hexsha": "6cdff99ae476661bf4242dd5da9ffc86383502dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-05T12:34:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T12:34:58.000Z", "max_issues_repo_path": "presentations/intermediate.jl", "max_issues_repo_name": "Fromeworld/JuliaSeminar", "max_issues_repo_head_hexsha": "6cdff99ae476661bf4242dd5da9ffc86383502dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "presentations/intermediate.jl", "max_forks_repo_name": "Fromeworld/JuliaSeminar", "max_forks_repo_head_hexsha": "6cdff99ae476661bf4242dd5da9ffc86383502dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6481178396, "max_line_length": 328, "alphanum_fraction": 0.6799857929, "num_tokens": 11355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.9314625017359053, "lm_q1q2_score": 0.7953877160544098}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.18\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 8595f030-5e9b-11eb-3bd7-ef8250cd1fab\nbegin\n\t# import the entire package\n\tusing Optim\n\tusing Distributions\n\tusing DataFrames\n\n\t# import just a few functions\n\tusing Random: seed!\n\tusing StatsFuns: logsumexp, softmax\n\tusing LinearAlgebra: diag\n\tusing StatsBase: countmap\n\t\n\t# autodiff instead of finite diff?\n\tusing FiniteDiff: finite_difference_gradient\nend\n\n# ╔═╡ 0ece0030-5e9d-11eb-0092-254fc6e72e83\nmd\"\n# Logit\n\nSuppose that agents can choose an action $y \\in \\{0,1\\}$. The payoffs to each are\n\n```math\n\\begin{align*}\nu_0(X,\\epsilon) &= \\epsilon_{i0} \\\\\nu_1(X,\\epsilon) &= x_i^\\top \\beta + \\epsilon_{i1}\n\\end{align*}\n```\n\nThe shocks $\\epsilon_{i0},\\epsilon_{i1}$ are distributed as iid Type-I extreme value with mean 0 and scale parameter 1. Agents choose $y_i=1$ if $u_1 \\geq u_0$ and $y_0$ if $u_1 < u_0$\n\"\n\n# ╔═╡ b7910ac0-5ffe-11eb-3925-13fbd88d3f67\nmd\" \nDenote $cdf(z) = F(z)$. Let choice $y_i \\in \\{0,1\\}$. For a symmetric distribution and a binary discrete choice model, we can use this shortcut (trick is in Greene's Econometrics tome, Greene 6th ed p. 779):\n```math\n\\log L(y|X) = \\sum_i \\log F\\left( 2(y_i-1) x_i^\\top \\beta \\right)\n```\nScore is a vector\n```math\n\\nabla_\\beta \\log L(y_i|x_i) = \\left[y_i - F\\left(x_i^\\top\\beta\\right)\\right]x_i\n```\nInformation matrix is\n```math\n\\left[\\sum_i \\nabla \\log L_i \\nabla \\log L_i^\\top\\right] \\to Var(\\beta)\n```\n\"\n\n# ╔═╡ e2248c2e-5ffe-11eb-189c-85dbf7703168\nmd\"\nWe can vectorize stuff to make it simpler. The $.$ means element-by-element operations a la MATLAB/Julia. Define\n```math\n\\boldsymbol q \\equiv 2.\\boldsymbol y .- 1\n```\nThen \n```math\n\\log L(y|X) = \\sum_i \\log. F.\\left(\\boldsymbol q .* X\\beta \\right)\n```\nMatrix of scores\n```math\n\\frac{\\partial \\log L_i}{\\partial \\beta} = \\left(y .- F.(X\\beta)\\right) .* X\n```\nInformation matrix\n```math\n\\left(\\frac{\\partial \\log L_i}{\\partial \\beta}\\right)^\\top \\frac{\\partial \\log L_i}{\\partial \\beta} \\to Var(\\beta)\n```\n\n\"\n\n# ╔═╡ 1508d920-6000-11eb-34bf-81e7d3ceb9bc\nmd\"\nIn the version below, we use the `Distributions.jl` package, which means we could actually change to a binary probit just by swapping out the distribution from `Logistic` to `Normal`.\n\nAlternatively, for lower-level control, we can use the following functions from [`StatsFuns.jl`](https://github.com/JuliaStats/StatsFuns.jl). This is useful for more computationally intensive work with multinomial discrete choice.\n\n```julia\nlogsumexp      # log(exp(x) + exp(y)) or log(sum(exp(x)))\nsoftmax        # exp(x_i) / sum(exp(x)), for i\n```\n\"\n\n# ╔═╡ b9c02010-5e9b-11eb-1e5d-9358c778cbba\n# set seed for random # generator\nseed!(1234)\n\n# ╔═╡ b9a85250-5e9b-11eb-1787-6b671b235984\nbegin\n\tnobs = 1_000\n\tβ = [1.0, -2.0, 1.0, 0.5]\n\tk = length(β)\n\tX = randn(nobs, k);\n\n\t# choice utilities\n\tu0 = zeros(nobs)\n\tu1 = X*β\n\tu = hcat(u0, u1)\nend\n\n# ╔═╡ b976e210-5e9b-11eb-0b18-e95537e1d64f\n# multinomial logit probabilities\nprob_actions = mapslices(softmax, u; dims=2)\n\n# ╔═╡ dc8270d0-5e9b-11eb-02cb-1faa58ce2656\ncum_prob = cumsum(prob_actions; dims=2)\n\n# ╔═╡ dc82bef0-5e9b-11eb-20f5-0d1ed55e9bb5\n# will throw an error if we goof\n@assert all(cum_prob[:,2] .≈ 1)\n\n# ╔═╡ dc87c800-5e9b-11eb-194c-4f7f0e83a5c5\n# instead of simulating random type-1 extreme values, we just\n# use a uniform variable and the CDF\ny = [searchsortedfirst(row, rand()) for row in eachrow(cum_prob) ] .-1 \n\n# ╔═╡ 694cc4c0-5e9c-11eb-3d00-458ca8c8fa28\ncountmap(y)\n\n# ╔═╡ 90b963b0-5e9c-11eb-3e39-bdf160b8655e\nfunction loglik(y, X, theta)\n    n,k = size(X)\n    ff(z) = logcdf(Logistic(), z)\n\n    # see footnote 6 on p. 778 in Greene 6th ed for this shortcut\n    q = 2 .* y .- 1\n    u1 = X*theta\n    LL = sum(ff.(q.*u1))    \n\n    return -LL  # I *think* you'll need to flip sign to maximize\nend\n\n# ╔═╡ 90b963b0-5e9c-11eb-1d75-25729dfb57ee\n# note that the `!` means we're updating the first argument(s)\nfunction dloglik!(grad, y, X, theta)\n    \n\tn,k = size(X)    \n    u1 = X*theta\n\t\n\t# create function\n\tff(z) = cdf(Logistic(), z)    \n\n\t# all the broadcasting fuses operations into a single\n\t# loop instead of allocating temp vectors\n\t# this can help w/ speed + memory\n    grad .= -vec(sum( (y .- ff.(u1)) .* X; dims=1))\n    return grad\nend\n\n# ╔═╡ 90b963b0-5e9c-11eb-0dea-81d683f42601\n# wrapper to allocate gradient vector\ndloglik(y, X, theta) = dloglik!(similar(theta), y, X, theta)\n\n# ╔═╡ 90c65c02-5e9c-11eb-032a-7d600b60b9c4\nfunction informationmatrix(y, X, theta)\n\n\tn,k = size(X)\n    infomatrix = zeros(k,k)\n\n    u1 = X*theta\n    ff(z) = cdf(Logistic(), z)    \n    g = y .- ff.(u1)   # as per Greene 6th ed p. 779\n    \n    infomatrix = (g .* X)' * (g .* X)\n    \n    return infomatrix # maybe flip signs?\nend\n\n# ╔═╡ 640b3fa2-5e9c-11eb-19d3-97ebb410851a\n# closures wrap likelihood & gradient\nbegin\n\tf(thet) = loglik(y,X,thet)\n\tg!(grad,thet) = dloglik!(grad,y,X,thet)\nend\n\n# ╔═╡ ba5f02b0-5e9c-11eb-30cc-fbb3e2d4b6e2\n# initial guess\ntheta0 = zeros(k)\n\n# ╔═╡ ba5f02b0-5e9c-11eb-2221-4b0d5e525673\n# Check gradient against finite difference\nbegin\n\tfdgrad = finite_difference_gradient(f, theta0, Val{:central})\n\t@assert  fdgrad ≈ dloglik(y,X,theta0)\n\tfdgrad .- dloglik(y,X,theta0)\nend\n\n# ╔═╡ ba614ca0-5e9c-11eb-3619-0507168a18d6\nres = optimize(f, g!, theta0, BFGS(), Optim.Options(;show_trace=true))\n\n# ╔═╡ 61327d20-5e9c-11eb-3704-bf5055d67bb0\nbegin\n\ttheta1 = res.minimizer  # should be about β\n\tvcov = informationmatrix(y, X, theta1)\n\tvcovinv = inv(vcov)\n\tstderr = sqrt.(diag(vcovinv))\n\ttstats = theta1 ./ stderr\n\tpvals = map(z -> 2 .* cdf(Normal(), -abs(z)), tstats)\n\t\n\tDataFrame(beta = β, betahat = theta1, tstat=tstats, se = stderr, pval=pvals)\nend\n\n# ╔═╡ Cell order:\n# ╠═0ece0030-5e9d-11eb-0092-254fc6e72e83\n# ╠═b7910ac0-5ffe-11eb-3925-13fbd88d3f67\n# ╠═e2248c2e-5ffe-11eb-189c-85dbf7703168\n# ╠═1508d920-6000-11eb-34bf-81e7d3ceb9bc\n# ╠═8595f030-5e9b-11eb-3bd7-ef8250cd1fab\n# ╠═b9c02010-5e9b-11eb-1e5d-9358c778cbba\n# ╠═b9a85250-5e9b-11eb-1787-6b671b235984\n# ╠═b976e210-5e9b-11eb-0b18-e95537e1d64f\n# ╠═dc8270d0-5e9b-11eb-02cb-1faa58ce2656\n# ╠═dc82bef0-5e9b-11eb-20f5-0d1ed55e9bb5\n# ╠═dc87c800-5e9b-11eb-194c-4f7f0e83a5c5\n# ╠═694cc4c0-5e9c-11eb-3d00-458ca8c8fa28\n# ╠═90b963b0-5e9c-11eb-3e39-bdf160b8655e\n# ╠═90b963b0-5e9c-11eb-1d75-25729dfb57ee\n# ╠═90b963b0-5e9c-11eb-0dea-81d683f42601\n# ╠═90c65c02-5e9c-11eb-032a-7d600b60b9c4\n# ╠═640b3fa2-5e9c-11eb-19d3-97ebb410851a\n# ╠═ba5f02b0-5e9c-11eb-30cc-fbb3e2d4b6e2\n# ╠═ba5f02b0-5e9c-11eb-2221-4b0d5e525673\n# ╠═ba614ca0-5e9c-11eb-3619-0507168a18d6\n# ╠═61327d20-5e9c-11eb-3704-bf5055d67bb0\n", "meta": {"hexsha": "338430cef7967636adb46406532d86b73391179e", "size": 6524, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "logit-example.jl", "max_stars_repo_name": "magerton/rcmnl.jl", "max_stars_repo_head_hexsha": "e9d20ade27f3e8c71331cfdba62a048f991ba2b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "logit-example.jl", "max_issues_repo_name": "magerton/rcmnl.jl", "max_issues_repo_head_hexsha": "e9d20ade27f3e8c71331cfdba62a048f991ba2b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logit-example.jl", "max_forks_repo_name": "magerton/rcmnl.jl", "max_forks_repo_head_hexsha": "e9d20ade27f3e8c71331cfdba62a048f991ba2b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3652173913, "max_line_length": 230, "alphanum_fraction": 0.6932863274, "num_tokens": 2834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7953877137031644}}
{"text": "function mh_results{T<:Integer}(ncur::T, ncar::T,\n                                nruns::T, play_mh::Function)\n    stickwins = 0\n    switchwins = 0\n    for i in 1:nruns\n        (isstickwin, isswitchwin) = play_mh(ncur, ncar)\n        if isstickwin\n            stickwins += 1\n        end\n        if isswitchwin\n            switchwins += 1\n        end\n    end\n    return (stickwins/nruns, switchwins/nruns)\nend\n\nfunction mh_analytic{T<:Integer}(ncur::T, ncar::T)\n    stickodds = ncar/ncur\n    switchodds = (ncar - stickodds)/(ncur-2)\n    return (stickodds, switchodds)\nend\n\nfunction show_odds{T<:Real}(a::T, b::T)\n    @sprintf \"   %.1f   %.1f     %.2f\" 100.0*a 100*b 1.0*b/a\nend\n\nfunction show_simulation{T<:Integer}(ncur::T, ncar::T, nruns::T)\n    println()\n    print(\"Simulating a \", ncur, \" door, \", ncar, \" car \")\n    println(\"Monty Hall problem with \", nruns, \" runs.\\n\")\n\n    println(\"   Solution   Stick  Switch  Improvement\")\n\n    (a, b) = mh_results(ncur, ncar, nruns, play_mh_literal)\n    println(@sprintf(\"%10s: \", \"Literal\"), show_odds(a, b))\n\n    (a, b) = mh_results(ncur, ncar, nruns, play_mh_clean)\n    println(@sprintf(\"%10s: \", \"Clean\"), show_odds(a, b))\n\n    (a, b) = mh_analytic(ncur, ncar)\n    println(@sprintf(\"%10s: \", \"Analytic\"), show_odds(a, b))\n    println()\n    return nothing\nend\n", "meta": {"hexsha": "2f4c46b411c605c26714ca28a268338353f9e173", "size": 1305, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/monty-hall-problem-3.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/monty-hall-problem-3.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/monty-hall-problem-3.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0, "max_line_length": 64, "alphanum_fraction": 0.5892720307, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7953877085087984}}
{"text": "\"\"\"\nHelper function for quadratic_interval that computes roots of a\nreal quadratic using interval arithmetic to bound rounding errors.\n\"\"\"\nfunction quadratic_helper!(a::Interval{T}, b::Interval{T}, c::Interval{T}, L::Array{Interval{T}}) where {T}\n\n    Δ = b^2 - 4*a*c\n\n    Δ.hi < 0 && return\n\n    Δ = sqrt(Δ)\n\n    if (b.lo >= 0)\n        x0 = -0.5 * (b + Δ)\n\n    else\n        x0 = -0.5 * (b - Δ)\n    end\n\n    if (0 ∈ x0)\n        push!(L, x0)\n\n    else\n        x1 = c / x0\n        x0 = x0 / a\n        push!(L, x0, x1)\n    end\n\nend\n\n\n\"\"\"\nFunction to solve a quadratic equation where the coefficients are intervals.\nReturns an array of intervals of the roots.\nArguments `a`, `b` and `c` are interval coefficients of `x²`, `x` and `1` respectively.\nThe interval case differs from the non-interval case in that\nthere might be three disjoint interval roots. In the third\ncase, one interval root extends to −∞ and another extends to +∞.\nThis algorithm finds the set of points where `F.lo(x) ≥ 0` and the set\nof points where `F.hi(x) ≤ 0` and takes the intersection of these two sets.\nEldon Hansen and G. William Walster : Global Optimization Using Interval Analysis - Chapter 8\n\"\"\"\nfunction quadratic_roots(a::Interval{T}, b::Interval{T}, c::Interval{T}) where {T}\n\n    L = Interval{T}[]\n    R = Interval{T}[]\n\n    quadratic_helper!(Interval(a.lo), Interval(b.lo), Interval(c.lo), L)\n    quadratic_helper!(Interval(a.hi), Interval(b.hi), Interval(c.hi), L)\n    quadratic_helper!(Interval(a.lo), Interval(b.hi), Interval(c.lo), L)\n    quadratic_helper!(Interval(a.hi), Interval(b.lo), Interval(c.hi), L)\n\n    if (length(L) == 8)\n        resize!(L, 4)\n    end\n\n    if (a.lo < 0 || (a.lo == 0 && b.hi == 0) || (a.lo == 0 && b.hi == 0 && c.lo ≤ 0))\n        push!(L, Interval(-∞))\n    end\n\n    if (a.lo < 0 || (a.lo == 0 && b.lo == 0) || (a.lo == 0 && b.lo == 0 && c.lo ≤ 0))\n        push!(L, Interval(∞))\n    end\n\n    sort!(L, by = x -> x.lo)\n\n    for i in 1:2:length(L)\n        push!(R, Interval(L[i].lo, L[i+1].hi))\n    end\n\n    R\nend\n", "meta": {"hexsha": "c7fe6f6fabb3de4f6959d2c45537054609742dff", "size": 2025, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/quadratic.jl", "max_stars_repo_name": "ericphanson/IntervalRootFinding.jl", "max_stars_repo_head_hexsha": "21be6924ec971ccc0c61a5f1e171f3b8f35c42c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 109, "max_stars_repo_stars_event_min_datetime": "2017-04-18T21:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T18:49:59.000Z", "max_issues_repo_path": "src/quadratic.jl", "max_issues_repo_name": "ericphanson/IntervalRootFinding.jl", "max_issues_repo_head_hexsha": "21be6924ec971ccc0c61a5f1e171f3b8f35c42c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 166, "max_issues_repo_issues_event_min_datetime": "2017-04-16T05:11:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-30T23:06:12.000Z", "max_forks_repo_path": "src/quadratic.jl", "max_forks_repo_name": "ericphanson/IntervalRootFinding.jl", "max_forks_repo_head_hexsha": "21be6924ec971ccc0c61a5f1e171f3b8f35c42c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2017-04-18T13:43:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T17:52:34.000Z", "avg_line_length": 27.7397260274, "max_line_length": 107, "alphanum_fraction": 0.5925925926, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.7953866603150013}}
{"text": "#=\n   Locomotive problem.\n\n   From Think Bayes, page 22ff\n   \"\"\"\n   I found the locomotive problem in Frederick Mosteller's \"Fifty Challenging\n   Problems in Probability with Solutions\" (Dover, 1987):\n      'A railroad numbers its locomotives in order 1..N. One day you\n       see a locomotive with the number 60. Estimate how many loco-\n       motives the railroad has.'\n\n   ...\n\n   The mean of the posterior is 333, so that might be a good guess if you wanted to\n   minimize error.\n   \"\"\"\n\n   As the book (Think Bayes) mentions, the model is very sensitive to \n   the value of maxInt. Here are some results for different maxInt:\n   \n\n   Here are the values from this model for different values of maxInt \n   (using MH())\n     maxInt:100  mean(n): 78.23232\n     maxInt:200  mean(n): 115.87732\n     maxInt:500  mean(n): 206.42599\n     maxInt:1000  mean(n): 335.66271\n     maxInt:2000  mean(n): 552.68673\n\n   These are the exact values from WebPPL model using the enumerate sampler.\n   maxInt  n\n   -------------------------\n    100    77.8166306057923\n    200   115.84577808279282\n    500   207.2393675826458\n   1000   334.04414386751915 \n   2000   553.5237331955558\n\n   Mosteller's solution: 2*(60-1)+1: 119.\n\n  cf german_tank.jl\n     german_tank_int.jl\n     ~/blog/locomotive_problem.blog\n     ~/webppl/locomotive_problem.wppl\n=#\n\nusing Turing\ninclude(\"jl_utils.jl\")\n\n@model function locomotive_problem(ys,maxInt=1000)\n    len = length(ys)\n    n ~ DiscreteUniform(1,maxInt)\n    ys ~ filldist(DiscreteUniform(1,n),len)\nend\n\n# Run the model with different values of maxInt\nfunction run_locomotive_problem(ys,maxInt)\n   model = locomotive_problem(ys,maxInt)\n\n    # chns = sample(model, Prior(), 100_000)\n    chns = sample(model, MH(), 100_000)\n    # chns = sample(model, PG(15), 10_000)\n    # chns = sample(model, SMC(), 10_000)\n    # chns = sample(model, IS(), 100_000)\n    # display(chns)\n\n    println(\"maxInt:$maxInt  mean(n): \", mean_val(chns,:n))\nend\n\nys = [60]\nfor maxInt in [100,200,500,1000,2000]\n    run_locomotive_problem(ys,maxInt)\nend\n", "meta": {"hexsha": "779bd8826408362d0acde8580ee19be99cc68e71", "size": 2046, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/locomotive_problem.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/locomotive_problem.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/locomotive_problem.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 27.6486486486, "max_line_length": 83, "alphanum_fraction": 0.6730205279, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7953866531164089}}
{"text": "export det\nexport minor\nexport cofactor\n\n\nsub(M::Array{Float64}, i, j) = M[1:end .!= i, 1:end .!= j]\ndet(a::Array{Float64}) = begin\n    if size(a) == (2, 2)\n        a[1, 1] * a[2, 2] - a[1, 2] * a[2, 1]\n    else\n        sum([(-1)^(i+1) * a[i, 1] * det(sub(a, i, 1)) for i in 1:size(a, 1)])\n        # performance tip, look for the best row/column choice for expansion.\n    end\nend\nminor(M::Array{Float64}, i, j) = det(sub(M, i, j))\ncofactor(M::Array{Float64}, i, j) = minor(M, i, j) * (-1)^(i+j)\n", "meta": {"hexsha": "836fb53a758eaf2e9373c777f73a1ca541590dac", "size": 495, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linearalgebra/determinant.jl", "max_stars_repo_name": "SimonDanisch/Porta.jl", "max_stars_repo_head_hexsha": "70a5b6586b74f5d76d3add8c9f305071dea13b6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2020-03-28T05:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T22:16:31.000Z", "max_issues_repo_path": "src/linearalgebra/determinant.jl", "max_issues_repo_name": "iamazadi/Porta", "max_issues_repo_head_hexsha": "73a97d879d06a1466ff3b966b2ea8e8a846d4c78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-15T12:36:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-15T12:36:59.000Z", "max_forks_repo_path": "src/linearalgebra/determinant.jl", "max_forks_repo_name": "iamazadi/Porta", "max_forks_repo_head_hexsha": "73a97d879d06a1466ff3b966b2ea8e8a846d4c78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-09-13T20:28:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T03:31:59.000Z", "avg_line_length": 29.1176470588, "max_line_length": 77, "alphanum_fraction": 0.5333333333, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075733703925, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7953856862853843}}
{"text": "@doc raw\"\"\"\n# Lotka-Volterra model in 2D with symmetric Lagrangian\n\n```math\n\\begin{aligned}\nL (q, \\dot{q}) &= \\frac{1}{2} \\frac{\\log q_2}{q_1} \\, \\dot{q_1} - \\frac{1}{2} \\frac{\\log q_1}{q_2} \\, \\dot{q_2} - H(q) , \\\\\nH(q) &= a_1 \\, q_1 + a_2 \\, q_2 + b_1 \\, \\log q_1 + b_2 \\, \\log q_2\n\\end{aligned}\n```\n\nThis Lagrangian is a slight generalization of Equation (5) in José Fernández-Núñez,\nLagrangian Structure of the Two-Dimensional Lotka-Volterra System, International\nJournal of Theoretical Physics, Vol. 37, No. 9, pp. 2457-2462, 1998.\n\n\"\"\"\nmodule LotkaVolterra2dSymmetric\n\n    ϑ₁(t, q) = + log(q[2]) / q[1] / 2\n    ϑ₂(t, q) = - log(q[1]) / q[2] / 2\n\n    dϑ₁dx₁(t, q) = - log(q[2]) / q[1]^2 / 2\n    dϑ₁dx₂(t, q) = + 1 / (q[1] * q[2]) / 2\n\n    dϑ₂dx₁(t, q) = - 1 / (q[2] * q[1]) / 2\n    dϑ₂dx₂(t, q) = + log(q[1]) / q[2]^2 / 2\n\n\n    include(\"lotka_volterra_2d_common.jl\")\n    include(\"lotka_volterra_2d_equations.jl\")\n\nend\n", "meta": {"hexsha": "5ecdd16ff9aa2901ddef55141135e55921ad0845", "size": 924, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lotka_volterra_2d_symmetric.jl", "max_stars_repo_name": "DDMGNI/GeometricProblems.jl", "max_stars_repo_head_hexsha": "367f4cf63ff614c3051c7760b835889fdb7a040f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lotka_volterra_2d_symmetric.jl", "max_issues_repo_name": "DDMGNI/GeometricProblems.jl", "max_issues_repo_head_hexsha": "367f4cf63ff614c3051c7760b835889fdb7a040f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-02-11T01:23:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-24T11:06:23.000Z", "max_forks_repo_path": "src/lotka_volterra_2d_symmetric.jl", "max_forks_repo_name": "DDMGNI/GeometricProblems.jl", "max_forks_repo_head_hexsha": "367f4cf63ff614c3051c7760b835889fdb7a040f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.875, "max_line_length": 123, "alphanum_fraction": 0.5865800866, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075733703925, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7953856780700193}}
{"text": "using Plots\n\nfunction vfsolvebasic(vnew, kgrid, tolerance, imax)\n    α = 0.3\n    δ = 0.1\n    β = 0.9\n\n    n = length(kgrid)\n    v = vnew .+ 2*tolerance\n    cartesianindex = Array{CartesianIndex{2}, n}\n    i = 1\n    while maximum(abs.(v - vnew)) > tolerance && i<=imax\n        v = vnew;\n        c = zeros(n, n);\n        for i in 1:n\n            for j in 1:n\n                c[i,j] = kgrid[i]^α + (1-δ)*kgrid[i] - kgrid[j];\n                if c[i,j] < 0\n                    c[i,j] = 0\n                end\n            end\n            (vnew, cartesianindex) = findmax(log.(c) .+ β*v', dims = 2);\n        end\n        i += 1\n    end\n    kprimeindex = getindex.(cartesianindex, 2)\n    return (v = vnew, kprime = kgrid[kprimeindex], kprimindex = kprimeindex)\nend\n\n\nkupper = 2\nklower = 0.001\nn = 10\ntolerance = 0.001\nimax = 1000\nkgrid = collect(range(klower, stop = kupper, length = n))\n(vbasic, kprimebasic, kprimeindex) = vfsolvebasic(zeros(n), kgrid, tolerance, imax)\n\n# Check it agrees with previous version\nscatter(kgrid, vbasic, label = \"v\")\nscatter!(kgrid, vnew, label = \"v\")\n\nscatter(kgrid, kprime, label = \"k'\")\nscatter!(kgrid, kprimebasic, label = \"k'\")\n\nvbasic == vnew\nkprimebasic == kprime", "meta": {"hexsha": "669cb5c45b8d74c8cd06d6d28dcd8e383c22b615", "size": 1192, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vf_iteration_intuitive.jl", "max_stars_repo_name": "PhilipCaoChicago/ECON602_2021", "max_stars_repo_head_hexsha": "ef62b3763663c076ab5ea40009a57232ba338885", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-17T23:05:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T04:17:50.000Z", "max_issues_repo_path": "src/vf_iteration_intuitive.jl", "max_issues_repo_name": "PhilipCaoChicago/ECON602_2021", "max_issues_repo_head_hexsha": "ef62b3763663c076ab5ea40009a57232ba338885", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vf_iteration_intuitive.jl", "max_forks_repo_name": "PhilipCaoChicago/ECON602_2021", "max_forks_repo_head_hexsha": "ef62b3763663c076ab5ea40009a57232ba338885", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-09-21T19:07:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T22:37:40.000Z", "avg_line_length": 25.3617021277, "max_line_length": 83, "alphanum_fraction": 0.5587248322, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7953768033202605}}
{"text": "using DifferentialEquations\r\nusing NLsolve\r\nusing Plots\r\n\r\n# The range of values α = M₂/(M₁+M₂) where the Lagrange points will be found\r\nαvals = 0.001:0.001:0.5\r\n# The number of values of α\r\nnαvals = length(αvals)\r\n# Will store the positions of the Lagrange points\r\nlagrangepoints = zeros(Float64, nαvals, 10);\r\n\r\nfor i ∈ 1:nαvals\r\n    # Set the value of α = M₂/(M₁+M₂)\r\n\tα = αvals[i]\r\n\t\r\n    # Set up the function for NLsolve to use\r\n\tfunction evalF!(F, X)\r\n\t\tx, y = X\r\n\t\tF[1] = x -\r\n\t\t\t(1 - α)*(x + α)/√((x + α)^2 + y^2)^3 -\r\n\t\t\tα*(x + α - 1)/√((x + α - 1)^2 + y^2)^3\r\n\t\tF[2] = y -\r\n\t\t\t(1 - α)*y/√((x + α)^2 + y^2)^3 -\r\n\t\t\tα*y/√((x + α - 1)^2 + y^2)^3\r\n\tend\r\n\t\r\n    # Run nlsolve at each of the five predetermined starting positions to find the five Lagrange points\r\n\tlagrangepoints[i,1:2 ] = nlsolve(evalF!, [ 0.0, 0.0], autodiff=:forward).zero\r\n\tlagrangepoints[i,3:4 ] = nlsolve(evalF!, [ 1.0, 0.0], autodiff=:forward).zero\r\n\tlagrangepoints[i,5:6 ] = nlsolve(evalF!, [-1.0, 0.0], autodiff=:forward).zero\r\n\tlagrangepoints[i,7:8 ] = nlsolve(evalF!, [ 0.0, 1.0], autodiff=:forward).zero\r\n\tlagrangepoints[i,9:10] = nlsolve(evalF!, [ 0.0,-1.0], autodiff=:forward).zero\r\n\t\r\nend\r\n\r\n# Plot the values of α against the coordinates of the Lagrange points,\r\n#  both as found numerically, and as approximated theoretically\r\nfunction locationplots()\r\n    return plot(\r\n        plot(αvals, [lagrangepoints[:,1 ], α -> 1 - ∛(α/3)]),\r\n        plot(αvals, [lagrangepoints[:,2 ], α -> 0]),\r\n        plot(αvals, [lagrangepoints[:,3 ], α -> 1 + ∛(α/3)]),\r\n        plot(αvals, [lagrangepoints[:,4 ], α -> 0]),\r\n        plot(αvals, [lagrangepoints[:,5 ], α -> - 1 - 5α/12]),\r\n        plot(αvals, [lagrangepoints[:,6 ], α -> 0]),\r\n        plot(αvals, [lagrangepoints[:,7 ], α -> 1/2 - α]),\r\n        plot(αvals, [lagrangepoints[:,8 ], α -> (√3)/2]),\r\n        plot(αvals, [lagrangepoints[:,9 ], α -> 1/2 - α]),\r\n        plot(αvals, [lagrangepoints[:,10], α -> -(√3)/2]),\r\n        linestyle = [:solid :dash],\r\n        layout = (5,2),\r\n        size = (600, 1000),\r\n        label = [\"numerical\" \"theoretical\"],\r\n        yticks = false,\r\n        title = [\"L₁ x\" \"L₁ y\" \"L₂ x\" \"L₂ y\" \"L₃ x\" \"L₃ y\" \"L₄ x\" \"L₄ y\" \"L₅ x\" \"L₅ y\"]\r\n    )\r\nend\r\n\r\n# Calculates the acceleration of m, given position r and velocity v, with p a vector of parameters\r\nfunction acceleration(r, v, p)\r\n    # Parameters for the system\r\n    G, M₁, M₂, r₁, r₂, Ω = p\r\n\r\n    # The four forces (including fictitious) acting on m\r\n    gravitational₁ = - ( G * M₁ / hypot((r - r₁)...)^3 ) .* (r - r₁)\r\n    gravitational₂ = - ( G * M₂ / hypot((r - r₂)...)^3 ) .* (r - r₂)\r\n    coriolis = - 2Ω .* [[0, -1] [1, 0]] * v\r\n    centrifugal = (Ω^2) .* r\r\n    return gravitational₁ + gravitational₂ + coriolis + centrifugal\r\nend\r\n\r\n# Sets up the derivative function for DifferentialEquations to use\r\nfunction derivative!(du, u, p, t)\r\n    du[1] = u[3]\r\n    du[2] = u[4]\r\n    du[3], du[4] = acceleration(u[1:2], u[3:4], p)\r\nend\r\n\r\n# Uses DifferentialEquations to simulate the trajectory of m for time T with initial conditions\r\n#  r₀ and v₀, and parameters α and M₁\r\nfunction simulate(α, G, r₀, v₀, T)\r\n    # M₂ is the mass of the other large stationary body\r\n    M₂ = M₁ * α/(1-α)\r\n\r\n    # r₁ and r₂ are the positions of M₁ and M₂\r\n    r₁ = [-α, 0]\r\n    r₂ = [1-α, 0]\r\n\r\n\t# G is the gravitational constant, which is 1 for an appropriate system of units\r\n\tG = 1\r\n    # Ω is the magnitude of the angular velocity of the rotating frame of reference\r\n    Ω = √(G * (M₁ + M₂))\r\n\r\n    # DifferentialEquations simulates the mass for time T\r\n    return solve(ODEProblem(derivative!, vcat(r₀, v₀), (0.0, float(T)), [G, M₁, M₂, r₁, r₂, Ω]))\r\nend\r\n\r\n# Creates a diagram of the Sun/Earth/Moon system to test the simulation\r\nfunction moondiagram()\r\n    diagram = plot(\r\n\t\tsimulate(3e-6, 39, [1.003, 0.0], [0.0, 0.215], 1/12),\r\n\t\tvars = (1,2),\r\n\t\tlinecolor = :white,\r\n\t\tlinewidth = 1,\r\n\t\tarrow = true,\r\n\t\tbg = :black,\r\n\t\tticks = false,\r\n\t\tshowaxis = false,\r\n\t\tlegend = false,\r\n\t\txlims = [0.995, 1.005],\r\n\t\tylims = [-0.005, 0.005]\r\n\t)\r\n\t\r\n\tscatter!(\r\n\t\tdiagram,\r\n\t\t[(1-(3e-6),0)],\r\n\t\tmarkercolor = :aqua,\r\n\t\tmarkersize = 4\r\n\t)\r\n\r\n    return diagram\r\nend\r\n\r\n# Plots the trajectory of m starting near Lₙ up to time T, with parameters α and M₁\r\nfunction trajectory(α, M₁, n, T, lims = [2,1])\r\n\ti = findfirst(≥(α), αvals)\r\n    simulatedtrajectory = simulate(αvals[i], M₁, lagrangepoints[i, (2n-1):2n], [0.0, 0.0], T)\r\n\t\r\n\tdiagram = plot(\r\n\t\tsimulatedtrajectory,\r\n\t\tvars = (1,2),\r\n\t\tlinecolor = :white,\r\n\t\tlinewidth = 1,\r\n\t\tbg = :black,\r\n\t\tticks = false,\r\n\t\tshowaxis = false,\r\n\t\tlegend = false,\r\n        xlims = [-lims[1],lims[1]],\r\n        ylims = [-lims[2],lims[2]],\r\n        size = Tuple(lims) .* round(Int64, 1200/sum(lims))\r\n\t)\r\n\t\r\n\tscatter!(\r\n\t\tdiagram,\r\n\t\t[Tuple(simulatedtrajectory.u[1][1:2]), (-α,0), (1-α, 0)],\r\n\t\tmarkercolor = [:white, :yellow, :aqua],\r\n\t\tmarkersize = [3, 10, 4]\r\n\t)\r\n\t\r\n\treturn diagram\r\nend", "meta": {"hexsha": "2f0e0e7c274fe63b215340e4fca49e80678acb4c", "size": 4929, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "casestudies/lagrangepoints/lagrangepoints.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "casestudies/lagrangepoints/lagrangepoints.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "casestudies/lagrangepoints/lagrangepoints.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 32.642384106, "max_line_length": 104, "alphanum_fraction": 0.5776019477, "num_tokens": 1837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7953768010819466}}
{"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    spheredir(θ, φ)\n\nReturn the 3D direction given polar angle `θ` and\nazimuthal angle `φ` in degrees according to the ISO\nconvention.\n\"\"\"\nfunction spheredir(theta, phi)\n  θ, φ = deg2rad(theta), deg2rad(phi)\n  Vec(sin(θ)*cos(φ), sin(θ)*sin(φ), cos(θ))\nend\n\n\"\"\"\n    planebasis(normal)\n\nReturn 2D basis vectors in the plane with given 3D `normal`.\n\"\"\"\nfunction planebasis(normal::Vec{3,T}) where {T}\n  # normalize input\n  n = normal ./ sqrt(sum(normal[i]^2 for i in 1:3))\n\n  # find last non-zero component\n  idx = -1\n  for (i, c) in enumerate(reverse(n))\n    if c != 0\n      idx = length(n) - i + 1\n      break\n    end\n  end\n\n  @assert idx > 0 \"invalid normal vector\"\n\n  # first basis vector (perturb and subtract projection)\n  u = ntuple(i -> i == idx%3 + 1 ? n[i] + one(T) : n[i], 3)\n  l = sum(u[i]*n[i] for i in 1:3)\n  u = ntuple(i -> u[i] - l*n[i], 3)\n\n  # second basis vector (cross product)\n  nx, ny, nz = n\n  ux, uy, uz = u\n  v = (ny*uz - nz*uz, nz*ux - nx*uz, nx*uy - ny*ux)\n\n  # normalize output\n  u = u ./ sqrt(sum(u[i]^2 for i in 1:3))\n  v = v ./ sqrt(sum(v[i]^2 for i in 1:3))\n\n  Vec(u), Vec(v)\nend\n\nplanebasis(normal::NTuple{3,T}) where {T} = planebasis(Vec(normal))\n", "meta": {"hexsha": "1aa49d41ce2da4595e868a801462f87f1377118f", "size": 1388, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "stevengj/Variography.jl", "max_stars_repo_head_hexsha": "8b3b6cc68d94da33983125457d8386f9689d63cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-18T10:01:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-18T10:01:09.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "stevengj/Variography.jl", "max_issues_repo_head_hexsha": "8b3b6cc68d94da33983125457d8386f9689d63cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-06-14T08:34:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-01T23:03:38.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "stevengj/Variography.jl", "max_forks_repo_head_hexsha": "8b3b6cc68d94da33983125457d8386f9689d63cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-06-14T08:17:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-17T18:20:15.000Z", "avg_line_length": 25.2363636364, "max_line_length": 68, "alphanum_fraction": 0.5461095101, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.8670357735451835, "lm_q1q2_score": 0.7953342210289591}}
{"text": "doc\"\"\"\n    Chisq(ν)\n\nThe *Chi squared distribution* (typically written χ²) with `ν` degrees of freedom has the\nprobability density function\n\n$f(x; k) = \\frac{x^{k/2 - 1} e^{-x/2}}{2^{k/2} \\Gamma(k/2)}, \\quad x > 0.$\n\nIf `ν` is an integer, then it is the distribution of the sum of squares of `ν` independent standard [`Normal`](:func:`Normal`) variates.\n\n```julia\nChisq(k)     # Chi-squared distribution with k degrees of freedom\n\nparams(d)    # Get the parameters, i.e. (k,)\ndof(d)       # Get the degrees of freedom, i.e. k\n```\n\nExternal links\n\n* [Chi-squared distribution on Wikipedia](http://en.wikipedia.org/wiki/Chi-squared_distribution)\n\n\"\"\"\nimmutable Chisq <: ContinuousUnivariateDistribution\n    ν::Float64\n\n    Chisq(ν::Real) = (@check_args(Chisq, ν > zero(ν)); new(ν))\nend\n\n@distr_support Chisq 0.0 Inf\n\n#### Parameters\n\ndof(d::Chisq) = d.ν\nparams(d::Chisq) = (d.ν,)\n\n\n#### Statistics\n\nmean(d::Chisq) = d.ν\n\nvar(d::Chisq) = 2.0 * d.ν\n\nskewness(d::Chisq) = sqrt(8.0 / d.ν)\n\nkurtosis(d::Chisq) = 12.0 / d.ν\n\nmode(d::Chisq) = d.ν > 2.0 ? d.ν - 2.0 : 0.0\n\nfunction median(d::Chisq; approx::Bool=false)\n    if approx\n        return d.ν * (1.0 - 2.0 / (9.0 * d.ν))^3\n    else\n        return quantile(d, 0.5)\n    end\nend\n\nfunction entropy(d::Chisq)\n    hν = 0.5 * d.ν\n    hν + logtwo + lgamma(hν) + (1.0 - hν) * digamma(hν)\nend\n\n\n#### Evaluation\n\n@_delegate_statsfuns Chisq chisq ν\n\nmgf(d::Chisq, t::Real) = (1.0 - 2.0 * t)^(-d.ν * 0.5)\n\ncf(d::Chisq, t::Real) = (1.0 - 2.0 * im * t)^(-d.ν * 0.5)\n\ngradlogpdf(d::Chisq, x::Float64) =  x > 0.0 ? (d.ν * 0.5 - 1) / x - 0.5 : 0.0\n\n\n#### Sampling\n\n_chisq_rand(ν::Float64) = StatsFuns.Rmath.chisqrand(ν)\nrand(d::Chisq) = _chisq_rand(d.ν)\n", "meta": {"hexsha": "a9af7ec27eef1cf2b39bdb7239724c5715f4ff74", "size": 1685, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/chisq.jl", "max_stars_repo_name": "ericproffitt/Distributions.jl", "max_stars_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/chisq.jl", "max_issues_repo_name": "ericproffitt/Distributions.jl", "max_issues_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/chisq.jl", "max_forks_repo_name": "ericproffitt/Distributions.jl", "max_forks_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6025641026, "max_line_length": 136, "alphanum_fraction": 0.6083086053, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.8670357632379241, "lm_q1q2_score": 0.7953342076537645}}
{"text": "\"\"\"\r\n    fixpoint(g,p0)\r\n\r\nadalah fungsi untuk mencari solusi dari `x=g(x)` dengan nilai tebakan awal `p0`\r\n\r\n# Examples\r\n```jl\r\njulia> g(x) = exp(-x);\r\n\r\njulia> pn, flag, M = fixpoint(g,0.5);\r\n\r\njulia> pn\r\n0.5671432633594872\r\n\r\njulia> flag\r\n0\r\n\r\njulia> M\r\n27×3 Array{Float64,2}:\r\n  0.0  0.5       NaN\r\n  1.0  0.606531    0.106531\r\n  2.0  0.545239    0.0612914\r\n  3.0  0.579703    0.0344639\r\n  ⋮\r\n 23.0  0.567143    4.09741e-7\r\n 24.0  0.567143    2.32382e-7\r\n 25.0  0.567143    1.31794e-7\r\n 26.0  0.567143    7.4746e-8\r\n```\r\nreturn solusi `pn` dengan `flag` bernilai 0 jika metode bisection berhasil menemukan\r\nsolusi dan gagal jika tidak 0. Serta, matriks `M` yang berisi catatan proses tiap\r\niterasi `[k, pk, f(pk)]`\r\n\r\n\"\"\"\r\nfunction fixpoint(g,p0)\r\n    # Definisikan nilai toleransi, maksimum iterasi dan tebakan awal\r\n    delta = 10^-7;\r\n    maxi = 100;\r\n    flag = 1;\r\n    pn = p0\r\n    M = [0 pn NaN];\r\n    for n = 2:maxi\r\n        pn1 = pn;\r\n        pn = g(pn1);\r\n        err = abs(pn-pn1);\r\n        relerr = err/(abs(pn)+eps());\r\n        M = [M; [n-1 pn err]]\r\n        if (err<delta) || (relerr<delta)\r\n            flag = 0; break\r\n        end\r\n    end\r\n    return pn, flag, M\r\nend\r\n", "meta": {"hexsha": "3134bdc173c5e18bee64771e2dd333382c86f216", "size": 1189, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fixpoint.jl", "max_stars_repo_name": "mkhoirun-najiboi/metnum.jl", "max_stars_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fixpoint.jl", "max_issues_repo_name": "mkhoirun-najiboi/metnum.jl", "max_issues_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fixpoint.jl", "max_forks_repo_name": "mkhoirun-najiboi/metnum.jl", "max_forks_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0185185185, "max_line_length": 85, "alphanum_fraction": 0.5550883095, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.8791467754256018, "lm_q1q2_score": 0.7953205985609819}}
{"text": "\"\"\"Julia program to implement Ternary Search algorithm.\nTernary Search is a Divide and Conquer strategy based algorithm similar to binary search.\nHere we divide the entire array into three parts and recursively search for the required element\n\"\"\"\n\nfunction ternary_search_recursive(arr, low, high, ele)\n    while (high >= low)\n        # FInd the two required midpoints to divide the array into three.\n        midA = low + (high - low) ÷ 3\n        midB = high - (high - low) ÷ 3\n        # Search, if the element is present in the midpoint indices\n        if (arr[midA] == ele)\n            return true\n        elseif (arr[midB] == ele)\n            return true\n        end\n    \n        # Identify the part in which the required element belongs to and recursively call the function with limited length\n        if (ele < arr[midA])\n            return ternary_search_recursive(arr, low, midA - 1, ele)\n        elseif (ele > arr[midB])\n            return ternary_search_recursive(arr, midB + 1, high, ele)\n        else\n            return ternary_search_recursive(arr, midA + 1, midB - 1, ele)\n        end\n    end\n    return false\nend\n\n\nprint(\"How many numbers are present in the array? \")\nn = readline()\nn = parse(Int, n)\nif (n <= 0)\n    println(\"Array is Empty!!!\")\n    exit()\nend\narr = Int[]\nprint(\"Enter the numbers: \")\narr = [parse(Int, num) for num in split(readline())] \nprint(\"Which number do you want to search in the array? \")\nele = readline()\nele = parse(Int, ele)\n# Sort the array in ascending order\narr = sort(arr)\nres = ternary_search_recursive(arr, 1, n, ele)\nif (res == 0)\n    print(\"The number $ele is not present in the array\")\nelse\n    print(\"The number $ele is present in the array.\")\nend\n\n\n\"\"\"\nTime Complexity - O(log(n)), where 'n' is the size of the array\nSpace Complexity - O(n)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE I\n\nHow many numbers are present in the array? 5 \nEnter the numbers: 1 2 3 4 5\nWhich number do you want to search in the array? 6\nThe number 6 is not present in the array\n\nSAMPLE II\n\nHow many numbers are present in the array? 3\nEnter the numbers: 3 1 2\nWhich number do you want to search in the array? 2\nThe number 2 is present in the array.\n \n\"\"\"\n", "meta": {"hexsha": "7f60f03b22f5f0ce1a92e60932cb6549b9499861", "size": 2175, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/search/ternary_search_recursive.jl", "max_stars_repo_name": "TechSpiritSS/NeoAlgo", "max_stars_repo_head_hexsha": "08f559b56081a191db6c6b1339ef37311da9e986", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 897, "max_stars_repo_stars_event_min_datetime": "2020-06-25T00:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:49:31.000Z", "max_issues_repo_path": "Julia/search/ternary_search_recursive.jl", "max_issues_repo_name": "AnshikaAgrawal5501/NeoAlgo", "max_issues_repo_head_hexsha": "d66d0915d8392c2573ba05d5528e00af52b0b996", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5707, "max_issues_repo_issues_event_min_datetime": "2020-06-24T17:53:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T05:03:15.000Z", "max_forks_repo_path": "Julia/search/ternary_search_recursive.jl", "max_forks_repo_name": "AnshikaAgrawal5501/NeoAlgo", "max_forks_repo_head_hexsha": "d66d0915d8392c2573ba05d5528e00af52b0b996", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1817, "max_forks_repo_forks_event_min_datetime": "2020-06-25T03:51:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:14:07.000Z", "avg_line_length": 29.0, "max_line_length": 122, "alphanum_fraction": 0.6629885057, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.8902942333990422, "lm_q1q2_score": 0.795308215380094}}
{"text": "# linreg.jl\n#\n# File with methods related to linear regression.\n#\n# Author: John Duchi (jduchi@stanford.edu)\n\n# (A, b, x) = GenerateLinearRegressionData(m, n; condition_number, noise)\n#\n# Generates data for a linear regression problem\nfunction GenerateLinearRegressionData(mm::Int64, nn::Int64;\n                                      condition_number::Float64 = 1.0,\n                                      noise::Float64 = 0.0)\n  A = randn(mm, nn);\n  x = randn(nn);\n  if (condition_number > 1)\n    D = LinRange(1, condition_number, nn);\n    A = A * Diagonal(D);\n  end\n  b = A * x + noise * randn(mm);\n  return (A, b, x);\nend\n\n# o = LinearRegressionObj(A::Matrix{Float64}, b::Vector{Float64},\n#                         x::Vector{Float64})\n#\n# Computes and returns linear regression objective (mean squared error).\nfunction LinearRegressionObj(A::Matrix{Float64}, b::Vector{Float64},\n                             x::Vector{Float64})\n  margins = A * x - b;\n  return mean(margins.^2) / 2;\nend\n\n# x = ProximalUpdateLinreg(a::Vector{Float64}, b::Float64,\n#                              x_init::Vector, stepsize::Float64)\n#\n# Sets x to minimize\n#\n#  .5 * (a' * x - b)^2 + norm(x - x_init)^2 / (2 * stepsize)\n#\n# Returns the minimizing x.\nfunction ProximalUpdateLinreg(a::Vector{Float64}, b::Float64,\n                              x_init::Vector, stepsize::Float64)\n  # Replace this code to return the correct update.\n  return x_init;\nend\n\n# x = SGUpdateLinreg(a::Vector{Float64}, b::Float64,\n#                    x_init::Vector, stepsize::Float64)\n#\n# Sets x to minimize the linear approximation to the standard squared\n# loss for linear regression, or, if g is the gradient of the loss\n#\n#   F(x; (a, b)) = .5 * (a' * x - b)^2\n#\n# at the point x_init, updates\n#\n#   x = x_init - stepsize * g;\nfunction SGUpdateLinreg(a::Vector{Float64}, b::Float64,\n                        x_init::Vector, stepsize::Float64)\n  # Replace this code to return the correct update.\n  return x_init;\nend\n\n# x = TruncatedUpdateLinreg(a::Vector{Float64}, b::Float64,\n#                              x_init::Vector, stepsize::Float64)\n#\n# Let F(x; (a, b)) = .5 * (a' * x - b)^2. Sets x to minimize the\n# positive approximation to F at x_init, that is, for\n#\n#  F_lin(x) = (F(x_init) + F'(x_init) * (x - x_init))_+\n#\n# sets x to minimize\n#\n#  F_lin + norm(x - x_init)^2 / (2 * stepsize).\n#\n# Returns the minimizing x.\nfunction TruncatedUpdateLinreg(a::Vector{Float64}, b::Float64,\n                               x_init::Vector, stepsize::Float64)\n  # Replace this code to return the correct update.\n  return x_init;\nend\n", "meta": {"hexsha": "16f4e70112747cf950c7688887a14e9d58c69f30", "size": 2584, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Machine Learning Summer School 2019 (London, UK)/tutorials/optimization/linreg.jl", "max_stars_repo_name": "xuedong/rlss2019", "max_stars_repo_head_hexsha": "d7468c2fcf269d8afd6fb0f44993aa9797867944", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Machine Learning Summer School 2019 (London, UK)/tutorials/optimization/linreg.jl", "max_issues_repo_name": "xuedong/rlss2019", "max_issues_repo_head_hexsha": "d7468c2fcf269d8afd6fb0f44993aa9797867944", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Machine Learning Summer School 2019 (London, UK)/tutorials/optimization/linreg.jl", "max_forks_repo_name": "xuedong/rlss2019", "max_forks_repo_head_hexsha": "d7468c2fcf269d8afd6fb0f44993aa9797867944", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.512195122, "max_line_length": 73, "alphanum_fraction": 0.6044891641, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735663, "lm_q2_score": 0.8902942261220292, "lm_q1q2_score": 0.7953082012931182}}
{"text": "#=\n## Control System: Spaceship\nAs an example we want to build an IOSystem controlling the altitude of a spacecraft.\nThe spacecraft has mass ``m`` and can be controlled with thrusters which apply the force ``F(t)`` to the spacecraft. The altitude ``x(t)``\n```math\n\\dot v(t) = \\frac{ F(t) }{m}\\\\\n\\dot x(t) =  v(t)\n```\nin our model this system has the input ``F(t)``, the internal state ``v(t)`` (vertical velocity) and the output ``x(t)``.\n\n```\n       +------------+\nF(t) --| spacecraft |-- x(t)\n       | m, v(t)    |\n       +------------+\n\n```\n=#\n\nusing BlockSystems\nusing ModelingToolkit\n@parameters t M F(t)\n@variables x(t) v(t)\nD = Differential(t)\n\nspacecraft = IOBlock([D(v) ~ F/M, D(x) ~ v], # define the equation\n                     [F], # inputs of the system\n                     [x], # outputs of the system\n                     name = :spacecraft)\n\n#=\nWe want to model a controller which takes a desired altitude as an input parameter and outputs the force for thrusters.\n\n## Simple proportional controller\nA proportional controller takes an input `i` and calculates the output proportional to the input.\n```math\n o(t) = K\\cdot i(t)\n```\n```\n       +--------+\ni(t) --| prop K |-- o(t)\n       +--------+\n```\n=#\n@parameters K i(t)\n@variables o(t)\n\nprop = IOBlock([o ~ K*i], [i], [o], name = :prop)\nnothing # hide\n#=\nIn order to make this useful as an controller, the input has to be the difference\nbetween the reference and the system variable (negative feedback). We can model this\nas an IOSystem where\n```math\nΔ = p - m\\,.\n```\n```\n       +--------+\np(t) --|  diff  |-- Δ(t)\nm(t) --|        |\n       +--------+\n```\n=#\n@parameters p(t) m(t)\n@variables Δ(t)\ndiff = IOBlock([Δ ~ p - m], [p, m], [Δ], name=:diff)\nnothing # hide\n#=\nNow we can connect both of the defined models to create an proportional controller\n\n```\n             +----------------------------------------+\n             | propc                                  |\n             |         +--------+   +--------+        |\n  target(t)--|--p(t) --|  diff  |---| prop K |--o(t)--|--o(t)\nfeedback(t)--|--m(t) --|        |   +--------+        |\n             |         +--------+                     |\n             +----------------------------------------+\n```\n\nIf we don't provide additional information the system will try to promote all of the enclosed\nvariables to the new systemwide namespace.\n=#\nprop_c = IOSystem([diff.Δ => prop.i], # connect output of diff to input of prop\n                  [diff, prop], # subsystems\n                  name=:propc)\n\n#=\nFor finer control, it is often preferred to give new names manually, this is\ndone with the `namespace_map` argument. Per default, all of the outputs of the\nsubsystems will become outputs of the connected system (in this case also the\noutput `diff.Δ`). We can prevent this by supplying the `outputs` argument\nmanually. Sub outputs which are not referenced here will become internal states\nof the connected system.\n\nThe rhs of the namespace map can be given as a Variable/Parameter type from MTK.\nFor simple renaming one can also give the rhs as a `Symbol` type.\n=#\nprop_c = IOSystem([diff.Δ => prop.i], [diff, prop],\n                  namespace_map = [prop.o => o,\n                                   diff.p => :target,\n                                   diff.m => :feedback],\n                  outputs = [o],\n                  name=:propc)\n\n#=\nRight now, the created object is a container for the two included systems. However,\nit is possible to transform the object into a new `IOBlock` by calling the `connect_system`\nfunction. The resulting is equivalent to\n```\n             +----------------------------------+\n  target(t)--| prop_c_block                     |--o(t)\nfeedback(t)--| o(t)=K*(target(t) - feedback(t)) |\n             +----------------------------------+\n```\n=#\nprop_c_block = connect_system(prop_c)\nnothing #hide\n\n#=\nNow we can hook our spaceship to this controller. It does not matter whether we use the\nconnected `IOBlock` version `prop_c` or the `IOSystem` version `prop_c_block`. We want to build\nthe connected system\n\n```\n           +--------------------------------------------+\n           |  control system                            |\n           |       +--------+   +------------+          |\ntarget(t)--|-------| prop_c |---| spacecraft |-x(t)--+--|--altitude(t)\n           |  +-fb-|        |   | m, v(t)    |       |  |\n           |  |    +--------+   +------------+       |  |\n           |  +--------------------------------------+  |\n           +--------------------------------------------+\n```\n=#\n@variables altitude(t)\nspace_controller = IOSystem([prop_c.o => spacecraft.F, spacecraft.x => prop_c.feedback],\n                            [prop_c, spacecraft],\n                            namespace_map = [spacecraft.x => altitude],\n                            outputs = [altitude])\n## we want to reduce the space_controller to a block\nspace_controller = connect_system(space_controller)\n@info \"Variables of space_controller\" space_controller equations(space_controller.system)\n\n#=\n## Simulate System\nIn order to simulate the system we can have to build the Julia functions.\n=#\ngen = generate_io_function(space_controller)\nnothing # hide\n#=\nBy doing so we get access to a named tuple with the fileds\n- `gen.f_ip` in-place function\n- `gen.f_oop` out-of-place function\n- `gen.massm` mass matrix of the system\n- `gen.states` symbols of states (in order)\n- `gen.inputs` symbols of inputs (in order)\n- `gen.params` symbols of parameters (in order)\n- (see docstring for full list)\n\nThe functions have the form\n`f_ip(du, u, inputs, params, t)`\nwhere `u` are all the states (outputs stacked on top of internal states) and `t` is the independent variable of the system.\nThe order of the inputs and states can be controlled.\n=#\ngen = generate_io_function(space_controller, f_states=[altitude, v], f_params=[K, M])\n@info \"Generated function\" gen.massm gen.states gen.inputs gen.params\nnothing # hide\n\n#=\nWell, let's see how our model is doing.\n=#\nusing Plots\nusing OrdinaryDiffEq\ntargetfun(t) = t>1.0 ? 1.0 : 0\nodefun(du, u, p, t) = gen.f_ip(du, u, [targetfun(t)], p, t)\np = [0.5, 1.0] # K, m\nu0 = [0.0, 0.0] # altitude, v\ntspan = (0.0, 30.0)\nprob = ODEProblem(odefun, u0, tspan, p)\nsol = solve(prob, Tsit5())\nplot(t->sol(t)[1],tspan..., label=\"altitude\", title=\"proportional control\")\nplot!(t->targetfun(t),tspan..., label=\"target\")\n\n#=\nWell who could have thought, proportional control looks like an harmonic oscillator 🤷‍♂️\n\n## Defining a better controller\nWe might just add a damping term (a force proportional to the velocity of the spaceship).\nIf it works for a harmonic oscillator, it should work for our spaceship.\n```\n           +--------------------------------------------------------+\n           |  control system                                        |\n           |  +--------------------------------------------------+  |\n           |  |    +--------+     +---+                          |  |\n           |  +-v--| prop_v |-(-)-| d |     +------------+       |  |\n           |       +--------+     | i |--F--| spacecraft |-v(t)--+  |\n           |       +--------+     | f |     | m          |-x(t)--+--|--altitude(t)\ntarget(t)--|-------| prop_c |-(+)-| f |     +------------+       |  |\n           |  +-fb-|        |     +---+                          |  |\n           |  |    +--------+                                    |  |\n           |  +--------------------------------------------------+  |\n           +--------------------------------------------------------+\n```\nIn order to do so we have to slightly redefine the spaceship system: now the velocity `v(t)` is also an output and not and internal state.\n=#\n\nspacecraft = IOBlock([D(v) ~ F/M, D(x) ~ v],\n                     [F],\n                     [x,v],\n                     name = :spacecraft)\n\n# One can define new blocks based on previously defined blocks.\nprop_v = IOBlock(prop, name=:prop_v)\nfdiff = IOBlock(diff, name=:fdiff)\n\nspace_controller = IOSystem([spacecraft.v => prop_v.i,\n                             spacecraft.x => prop_c.feedback,\n                             prop_c.o => fdiff.p,\n                             prop_v.o => fdiff.m,\n                             fdiff.Δ => spacecraft.F],\n                            [prop_v, prop_c, fdiff, spacecraft],\n                            namespace_map = [spacecraft.x => altitude],\n                            outputs = [altitude])\n\nspace_controller = connect_system(space_controller)\ngen = generate_io_function(space_controller, f_states=[altitude, v], f_params=[prop_c.K, M, prop_v.K])\n\nodefun(du, u, p, t) = gen.f_ip(du, u, [targetfun(t)], p, t)\np = [1.0, 1.0, 0.5] # propc, M, propv\nu0 = [0.0, 0.0] # altitude, v\ntspan = (0.0, 30.0)\nprob = ODEProblem(odefun, u0, tspan, p)\nsol = solve(prob, Tsit5())\nplot(sol, vars=(0,1), label=\"altitude\", title=\"better control\")\nplot!(t->targetfun(t),tspan..., label=\"target\")\n\n#=\n## Defining an PT1 controller\n```\n             +-----------------------------------------------+\n             | pi_c                                   +---+  |\n             |                           +------------|   |  |\n             |        +----+  +--------+ | +-------+  |sum|--|--o(t)\n  target(t)--|--p(t)--|diff|--| prop K |-+-| int T |--|   |  |\nfeedback(t)--|--m(t)--|    |  +--------+   +-------+  +---+  |\n             |        +----+                                 |\n             +-----------------------------------------------+\n```\n=#\n\n@parameters T a1(t) a2(t)\n@variables Σ(t) altitude(t)\nint = IOBlock([D(o) ~ 1/T * i - o], [i], [o], name=:int)\nadder = IOBlock([Σ ~ a1 + a2], [a1, a2], [Σ], name=:add)\n\npi_c = IOSystem([diff.Δ => prop.i,\n                 prop.o => int.i,\n                 prop.o => adder.a1,\n                 int.o => adder.a2],\n                [diff, prop, int, adder],\n                namespace_map = [diff.p => :target,\n                                 diff.m => :feedback,\n                                 adder.Σ => o],\n                outputs = [o],\n                name=:pi_c)\nnothing # hide\n\n# as before we can close the loop and build the control circuit\n\nspace_controller = IOSystem([pi_c.o => spacecraft.F , spacecraft.x => pi_c.feedback],\n                            [pi_c, spacecraft],\n                            namespace_map = [spacecraft.x => altitude],\n                            outputs = [altitude])\nspace_controller = connect_system(space_controller, verbose=false)\n@info \"Variables of space_controller\" space_controller equations(space_controller.system)\n\n# and we can simulate and plot the system\ngen = generate_io_function(space_controller, f_states=[altitude], f_params=[K, T, M])\n\nodefun(du, u, p, t) = gen.f_ip(du, u, [targetfun(t)], p, t)\np = [0.5, -1.5, 1.0] # K, T, m\nu0 = [0.0, 0.0, 0.0] # altitude, int.o, v\ntspan = (0.0, 50.0)\nprob = ODEProblem(odefun, u0, tspan, p)\nsol = solve(prob, Tsit5())\nplot(sol, vars=(0,[ 1,2 ]), label=[\"altitude\" \"integrator\"], title=\"PT1 controller\")\nplot!(t->targetfun(t),tspan..., label=\"target\")\n\n# thank you for flying with us :)\n", "meta": {"hexsha": "73fe6a476345c4efc06743475c5843ad84569b94", "size": 11027, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/spacecraft.jl", "max_stars_repo_name": "hexaeder/BlockSystems.jl", "max_stars_repo_head_hexsha": "2dabd797f51067b19882976705bf49614f09ef33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2021-04-12T14:36:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T07:10:17.000Z", "max_issues_repo_path": "examples/spacecraft.jl", "max_issues_repo_name": "hexaeder/IOSystems_prototype", "max_issues_repo_head_hexsha": "93ae0593bd6430a2d686a22f21f3c17688234124", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-02-05T18:50:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:15:27.000Z", "max_forks_repo_path": "examples/spacecraft.jl", "max_forks_repo_name": "hexaeder/BlockSystems.jl", "max_forks_repo_head_hexsha": "2dabd797f51067b19882976705bf49614f09ef33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-04-14T13:47:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T14:19:40.000Z", "avg_line_length": 37.8934707904, "max_line_length": 138, "alphanum_fraction": 0.5037634896, "num_tokens": 2791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896132, "lm_q2_score": 0.8933093954028816, "lm_q1q2_score": 0.795308189066997}}
{"text": "# # Linear regression\n\nimport MaximumLikelihoodProblems\n\nimport Distributions\nimport ForwardDiff\nimport LogDensityProblems\nimport TransformVariables\n\nstruct LinearRegression{Ty, TX}\n    y::Ty\n    X::TX\nend\n\nfunction (problem::LinearRegression)(θ)\n    y = problem.y\n    X = problem.X\n\n    β = θ.β\n    σ = θ.σ\n\n    η = X * β\n    μ = η\n    ε = y - μ\n\n    ## these two lines are equivalent:\n    ## log_likelihood = Distributions.loglikelihood(Distributions.Normal(0, σ), ε)\n    ## log_likelihood = sum(Distributions.logpdf.(Distributions.Normal(0, σ), ε))\n\n    log_likelihood = sum(Distributions.logpdf.(Distributions.Normal(0, σ), ε))\n    return log_likelihood\nend\n\nN = 10_000\n\n## the first column (the column of all ones) is the intercept\nX = hcat(ones(N), randn(N), randn(N))\n\nsize_β = (3,)\nβ_true = [1.0, 2.0, -1.0]\nσ_true = 0.5\nη_true = X * β_true\nμ_true = η_true\nε_true = randn(N) .* σ_true\ny = μ_true + ε_true\n\nfunction generate_problem_transformation(p::LinearRegression)\n    return TransformVariables.as((β = TransformVariables.as(Array, size(p.X, 2)),\n                                  σ = TransformVariables.asℝ₊))\nend\n\nproblem = LinearRegression(y, X)\ntransformation = generate_problem_transformation(problem)\ntransformed_problem = LogDensityProblems.TransformedLogDensity(transformation,\n                                                               problem)\ntransformed_gradient_problem = LogDensityProblems.ADgradient(:ForwardDiff,\n                                                             transformed_problem)\n\nβ_hat_initial_guess = zeros(size_β)\nσ_hat_initial_guess = 1.0\n\nθ_hat_initial = (; β = β_hat_initial_guess,\n                   σ = σ_hat_initial_guess)\n\n# θ_hat:\n\nθ_hat = MaximumLikelihoodProblems.fit(transformed_gradient_problem,\n                                      θ_hat_initial;\n                                      learning_rate = 1e-6)\n\n# β_hat:\n\nβ_hat = θ_hat[:β]\n\n# σ_hat:\n\nσ_hat = θ_hat[:σ]\n\n# Value of the log likelihood function evaluated at θ_hat:\n\nMaximumLikelihoodProblems.loglikelihood(transformed_gradient_problem, θ_hat)\n", "meta": {"hexsha": "136b35a8a6a596c8342b614adb0d438bec6a08a1", "size": 2066, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/linear_regression.jl", "max_stars_repo_name": "bcbi/MaximumLikelihoodProblems.jl", "max_stars_repo_head_hexsha": "628bdb40c60c1376484937a49e85d2aef5b41f3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-02T12:14:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-02T12:14:38.000Z", "max_issues_repo_path": "examples/linear_regression.jl", "max_issues_repo_name": "bcbi/MaximumLikelihoodProblems.jl", "max_issues_repo_head_hexsha": "628bdb40c60c1376484937a49e85d2aef5b41f3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38, "max_issues_repo_issues_event_min_datetime": "2020-04-02T10:43:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T00:26:37.000Z", "max_forks_repo_path": "examples/linear_regression.jl", "max_forks_repo_name": "bcbi/MaximumLikelihoodProblems.jl", "max_forks_repo_head_hexsha": "628bdb40c60c1376484937a49e85d2aef5b41f3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1951219512, "max_line_length": 82, "alphanum_fraction": 0.651500484, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.7952390050729369}}
{"text": "\"\"\"\n    update(x, measurement, H)\n\nUPDATE step in Kalman filtering for linear dynamics models:\n```math\nK = P_{n+1}^P * H^T * S^{-1}\nm_{n+1} = m_{n+1}^P + K * (0 - z)\nP_{n+1} = P_{n+1}^P - K*S*K^T\n```\n\nThis function provides a very simple UPDATE implementation.\nIn the solvers, we recommend to use the non-allocating [`update!`](@ref).\n\"\"\"\nfunction update(x::Gaussian, measurement::Gaussian, H::AbstractMatrix)\n    m, C = x\n    z, S = measurement\n\n    K = C * H' * inv(S)\n    m_new = m - K * z\n    C_new = C - K * S * K'\n\n    return Gaussian(m_new, C_new)\nend\n\"\"\"UPDATE step in Joseph-form, with square-root matrix inputs\"\"\"\nfunction update(x::SRGaussian, measurement::SRGaussian, H::AbstractMatrix)\n    m, C = x\n    z, S = measurement\n\n    K = C * H' * inv(S)\n    m_new = m - K * z\n    C_new = X_A_Xt(C, (I - K * H))\n\n    return Gaussian(m_new, C_new)\nend\n\n\"\"\"\n    update!(x_out, x_pred, measurement, H, R=0)\n\nUPDATE step in Kalman filtering for linear dynamics models, given a measurement `Z=N(z, S)`.\nIn-place implementation of [`update`](@ref), saving the result in `x_out`.\n\n```math\nK = P_{n+1}^P * H^T * S^{-1}\nm_{n+1} = m_{n+1}^P + K * (0 - z)\nP_{n+1} = P_{n+1}^P - K*S*K^T\n```\n\nImplemented in Joseph Form.\n\nSee also: [`predict`](@ref)\n\"\"\"\nfunction update!(\n    x_out::Gaussian,\n    x_pred::Gaussian,\n    measurement::Gaussian,\n    H::AbstractMatrix,\n    K_cache::AbstractMatrix,\n    M_cache::AbstractMatrix,\n    m_tmp,\n)\n    z, S = measurement.μ, copy!(m_tmp.Σ, measurement.Σ)\n    m_p, P_p = x_pred.μ, x_pred.Σ\n    D = length(m_p)\n\n    # K = P_p * H' / S\n    S_chol = cholesky!(S)\n    K = _matmul!(K_cache, Matrix(P_p), H')\n    rdiv!(K, S_chol)\n\n    # x_out.μ .= m_p .+ K * (0 .- z)\n    x_out.μ .= m_p .- _matmul!(x_out.μ, K, z)\n\n    # M_cache .= I(D) .- mul!(M_cache, K, H)\n    _matmul!(M_cache, K, H, -1.0, 0.0)\n    @inbounds @simd ivdep for i in 1:D\n        M_cache[i, i] += 1\n    end\n\n    X_A_Xt!(x_out.Σ, P_p, M_cache)\n\n    return x_out\nend\n", "meta": {"hexsha": "5141063331da474eb87f1df41b79b0b9d572c501", "size": 1953, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/filtering/update.jl", "max_stars_repo_name": "nathanaelbosch/ODEFilters.jl", "max_stars_repo_head_hexsha": "c24deb0b28d419ade8d6a5e60b325cd8f1a88d00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-10-28T20:38:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T21:38:53.000Z", "max_issues_repo_path": "src/filtering/update.jl", "max_issues_repo_name": "nathanaelbosch/ODEFilters.jl", "max_issues_repo_head_hexsha": "c24deb0b28d419ade8d6a5e60b325cd8f1a88d00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-11-03T22:22:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-10T00:56:24.000Z", "max_forks_repo_path": "src/filtering/update.jl", "max_forks_repo_name": "nathanaelbosch/ODEFilters.jl", "max_forks_repo_head_hexsha": "c24deb0b28d419ade8d6a5e60b325cd8f1a88d00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-05T07:07:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-05T07:07:38.000Z", "avg_line_length": 23.5301204819, "max_line_length": 92, "alphanum_fraction": 0.5883256528, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7951125922373641}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.4\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 10b19f7a-1f8b-11eb-128e-11743ce72ef5\nusing PlutoUI, Plots\n\n# ╔═╡ e5a688ac-1f91-11eb-104a-2753c9263f14\nmd\"\"\"\n # Floating Point Arithmetic\n\"\"\"\n\n# ╔═╡ 2df31082-1f8b-11eb-145a-93fa6e01e345\n@bind f Slider(1:100)\n\n# ╔═╡ 37c0afe8-1f8b-11eb-1154-31f5954ca4ff\nf\n\n# ╔═╡ 8d2203e8-1f8a-11eb-0332-7d512d831ec1\nbitstring(f)\n\n# ╔═╡ 4aa7bc3c-1f8b-11eb-30dd-89d64f42fc27\nlength(bitstring(f))\n\n# ╔═╡ c90f7b06-1f8a-11eb-17d7-35a09af858f1\nfloat(f)\n\n# ╔═╡ d4cd33f2-1f8a-11eb-1af7-bdbc1fb236da\nbitstring(float(f))\n\n# ╔═╡ 4f354440-1f8b-11eb-225a-f55552bc9e29\nlength(bitstring(float(f)))\n\n# ╔═╡ b7eb6210-1f9e-11eb-2a57-95b4fab4187f\nmd\"\"\"\nIEEE 64 bit representation (double precision) (64 bits0\n\"\"\"\n\n# ╔═╡ 2ee2a8ec-1f8e-11eb-23e6-9d5e2bb00d1e\nieee0(x::Float64) = [bitstring(x)[1:1], bitstring(x)[2:12], bitstring(x)[13:64]] \n\n# ╔═╡ d6b5d1f6-1f9e-11eb-0c32-9b9cb51352a0\nmd\"\"\"\n## Let me work with numbers from 1 to 2\n\"\"\"\n\n# ╔═╡ e0cd119a-1f9e-11eb-1181-3d3fa6e0653f\n nextfloat(1.0)-1.0\n\n# ╔═╡ f3357c5a-1f9e-11eb-270d-d3b5fd6bd542\n2.0 ^(-52)\n\n# ╔═╡ fbe68df8-1f9e-11eb-1278-a102df99c88c\n\n\n# ╔═╡ 0bf5f86a-1f8f-11eb-17fd-75f4b45f16d5\n@bind j Slider(1: 2^(52), show_value = true)\n\n# ╔═╡ 2ff48c68-1f8f-11eb-0bd0-cde93f2cc18b\ng = 1 + j/2^52\n\n# ╔═╡ 316b7dd0-1f8e-11eb-0da9-9fc5b63a4e80\nieee0(g)\n\n\n# ╔═╡ 56e8258a-1f8f-11eb-3249-6592feed84b3\nieee0(1.0)\n\n# ╔═╡ 5d7dcbe0-1f8f-11eb-05e9-1b2ae35cf681\nieee0(-1.0)\n\n# ╔═╡ bf3bd13c-1f95-11eb-3187-a7311125be18\nnextfloat(1.0)-1\n\n# ╔═╡ d3a6bbaa-1f95-11eb-27de-e99b0e230d21\neps(1.0)\n\n# ╔═╡ c6d813ba-1f95-11eb-1be6-55cb3ffeb358\nnextfloat(1.0f0)-1\n\n# ╔═╡ d66f2a16-1f95-11eb-3edc-4182c1a4b8ad\neps(1.0f0)\n\n# ╔═╡ d31baed4-1f95-11eb-19df-15ff5c378487\neps(1.0f0) * 2^23\n\n# ╔═╡ 81a7921c-1f8f-11eb-33c6-397d38b57a75\nieee(x) = [ parse.(Int,ieee0(x),base=2)      ieee0(x)]\n\n# ╔═╡ 85c8f822-1f8f-11eb-15a1-7956d269779a\nieee(g)\n\n# ╔═╡ dd3031d8-1f9f-11eb-39b2-cb7ac57c6bdf\nieee(1.0)\n\n# ╔═╡ e4b2733a-1f9f-11eb-30ac-0dc5305b8938\nieee(-1.0)\n\n# ╔═╡ ff15233a-1f9f-11eb-0012-f198e05abaf9\nmd\"\"\"\n# s, e, m  (sign, exponent, mantissa)  =  (-1)^s  * 2^(e-1023) * (1 + m/2^52)\n\"\"\"\n\n# ╔═╡ 3f36e4a8-1fa0-11eb-1c46-97ff95905b41\nieee(prevfloat(1.0))\n\n# ╔═╡ f8612fa6-1f91-11eb-36d6-cbd0f9b5b0ea\nfloat2ieee(x::Float64) =  parse.(Int,ieee0(x),base=2)\n\n# ╔═╡ 66f85a94-1fa0-11eb-32bd-178184d8aef9\n2^52-1\n\n# ╔═╡ 0a44c782-1f92-11eb-1b67-eb93f1dfe1ff\nfloat2ieee(1.0)\n\n# ╔═╡ 37039e06-1f92-11eb-192e-e59ffb46a368\nbegin\n\ti =-2:2\n\tx =  2.0 .^i\n\tplot(yticks=[],xticks=round.(x,digits=2),size=(500,100))\n\tfor xx∈x\n\t   \n\t\n\t\t\n\t\tz = (1+1/16):(1/16):(2-1/16)\n\t\tfor zz∈ xx.*z\n\t\t\t\n\t\t\t   \n\t  plot!( [zz, zz], [-.1, 0.0], color=:red, ratio=10, legend=false, ylims=(-.1,.1),tickfontsize=1)\n\t\t\t\n\t\tend\n\t\t  plot!( [xx, xx], [-.1, .1], color=:blue, ratio=5, legend=false, ylims=(-.1,.1),tickfontsize=4)\n\tend\n\t\n\tplot!()\nend\n\n# ╔═╡ c51ad4de-1fa1-11eb-3e01-fb46ed72f493\n(1 + 1.000001*eps(1.0)/2)-1\n\n# ╔═╡ 79e5e5ca-1fa0-11eb-087f-9fad526c1b0e\nieee(0.0) ## does not follow the same rule\n\n# ╔═╡ 8fd89a82-1fa0-11eb-2921-0d3c31c93cbc\nieee(-0.0) ## is this the same as 0.0?\n\n# ╔═╡ a207d416-1fa0-11eb-3bf0-bdc40925736e\n1.0 / 0.0\n\n# ╔═╡ c7473096-1fa0-11eb-39fd-31c4c4b1eb04\nieee(Inf)\n\n# ╔═╡ d08a02dc-1fa0-11eb-3369-a7c84dad581a\nieee(1.0/-0.0)\n\n# ╔═╡ f072cf66-1fa0-11eb-0789-733f904d41d0\n0.0 / 0.0\n\n# ╔═╡ ff8975cc-1fa0-11eb-1fa6-514db7898e52\nmd\"\"\"\n# Not a Number\n\"\"\"\n\n# ╔═╡ 0b340f86-1fa1-11eb-37bd-839bd7525dc9\nNaN == NaN\n\n# ╔═╡ 0d1c1902-1f96-11eb-0734-1bb3dda2aa7d\nmd\"\"\"\nWhy do we need this floating point representation?\n\"\"\"\n\n# ╔═╡ a40c4352-1f94-11eb-263e-632828cb6079\nfloat2ieee(0.0)\n\n# ╔═╡ b7b6a198-1f94-11eb-0093-8f3ab007d770\nfloat2ieee(-0.0)\n\n# ╔═╡ bb04eb2c-1f94-11eb-0a4a-3d2765531e94\nfloat2ieee(Inf)\n\n# ╔═╡ c0e4f8f2-1f94-11eb-1305-d9028395ab2f\nfloat2ieee(-Inf)\n\n# ╔═╡ c500ec66-1f94-11eb-079a-1b5b4befade2\n1/-0.0\n\n# ╔═╡ 1e37c20a-1f95-11eb-37f9-11c5a6041e1b\nInf - Inf\n\n# ╔═╡ 25be9fbc-1f95-11eb-294a-1dd62a135bfa\n0.0/0.0\n\n# ╔═╡ 7345c08e-1f96-11eb-0bf1-c50d0108facd\nmd\"\"\"\n$$\\begin{matrix}   \\text{exponent\\\\mantissa} & 0 & ≠0  \\\\ \\hline 0 & ±0  &  \\text{denormal} \\\\ \n\\text{regular} &  2^k & \\text{general} \\\\ \\text{max} &  \\pm\\infty &  \\text{NaN} \\end{matrix}$$\n\"\"\"\n\n# ╔═╡ b22dc266-1f9a-11eb-199b-170ef50b702c\nmd\"\"\"\nRules of IEEE arithmetic\n\"\"\"\n\n# ╔═╡ 3f2943c6-1f95-11eb-0342-6569169f32ca\nFloat32(1.0)\n\n# ╔═╡ 47153ebe-1f95-11eb-2224-716d2e152db0\nbitstring(Float32(1.0))\n\n# ╔═╡ 60135b2e-1f95-11eb-293d-4f8a96a677b2\nfloat32ieee0(x::Float32) = [bitstring(x)[1:1], bitstring(x)[2:9], bitstring(x)[10:32]]\n\n# ╔═╡ 77de76f8-1f95-11eb-00bc-915dd7977c75\nfloat32ieee0(1.0f0)\n\n# ╔═╡ 65ef756c-1f96-11eb-2546-35b37cb7f54c\n## The rules of +, -, / , * and √\n\n# ╔═╡ f707de2e-1fa1-11eb-0147-3fca8c03ab5f\n\n\n# ╔═╡ 2b0265d4-1f96-11eb-1553-ef2ecb7d451b\nmd\"\"\"\nWhat precision do you need? \n - Small absolute precision?\n - Small relative precision?\n - Neither?\n\"\"\"\n\n# ╔═╡ c5f5c97c-1f97-11eb-3683-55c16be8274e\nmd\"\"\"\nWhat is displayed? What can you represent?\n\"\"\"\n\n# ╔═╡ b86c366c-1f95-11eb-0a18-a52cdf00da4c\n1/5\n\n# ╔═╡ d400e394-1f97-11eb-0f74-476c32bdd9d0\nbitstring(1/5)\n\n# ╔═╡ f5e3b162-1f97-11eb-2879-f7c7954143a0\nbig(1/5)\n\n# ╔═╡ 000c656c-1f98-11eb-0f0e-657b9651f0bd\nbig(1)/5\n\n# ╔═╡ 149b4c9e-1f98-11eb-19b7-eb9988c9333a\nBigFloat(1//5,precision=1000)\n\n# ╔═╡ 3aae6bac-1f98-11eb-22a5-bdc5e5de3f4c\nBigFloat(π,precision=1000)\n\n# ╔═╡ 43bed31c-1f98-11eb-1131-f5dd8dd27086\nBigFloat(float(pi),precision=1000)\n\n# ╔═╡ 56fb9c94-1f98-11eb-216e-f9e6e04d6f45\nmd\"\"\"\nNote that every IEEE number terminates (is not a repeating expansion)\n\"\"\"\n\n# ╔═╡ 32cf8afa-1f99-11eb-0193-e969cca12f86\nmd\"\"\"\nFind the first floating point number bigger than 1 such that x * (1/x) ≠ 1\n\"\"\"\n\n# ╔═╡ 51baa858-1f99-11eb-3329-4d9bf850b1c0\nbegin\n\tt = 1+rand()\n\tt,ieee(t*1/t)\nend\n\n# ╔═╡ 64c9235e-1f99-11eb-24f3-d940be06c7c8\nlet\n\t α = 1.0\n     while( α * (1/α) == 1.0)\n\t\tα = nextfloat(α)\n\t end\n\t Int((α-1)/eps(1.0))\nend\n\n# ╔═╡ ecc5c55a-1f99-11eb-3f44-4161850426cc\nα= 1 + 257736490*eps()\n\n# ╔═╡ 40575ec2-1f9a-11eb-2d29-5b517d1f3b18\nα*(1/α)\n\n# ╔═╡ 0b0719c2-1f9c-11eb-3ed6-6927c927145d\n\n\n# ╔═╡ 11ebb920-1f9c-11eb-061a-8df3899e8945\n\n\n# ╔═╡ Cell order:\n# ╟─e5a688ac-1f91-11eb-104a-2753c9263f14\n# ╠═2df31082-1f8b-11eb-145a-93fa6e01e345\n# ╠═37c0afe8-1f8b-11eb-1154-31f5954ca4ff\n# ╠═8d2203e8-1f8a-11eb-0332-7d512d831ec1\n# ╠═4aa7bc3c-1f8b-11eb-30dd-89d64f42fc27\n# ╠═c90f7b06-1f8a-11eb-17d7-35a09af858f1\n# ╠═d4cd33f2-1f8a-11eb-1af7-bdbc1fb236da\n# ╠═4f354440-1f8b-11eb-225a-f55552bc9e29\n# ╟─b7eb6210-1f9e-11eb-2a57-95b4fab4187f\n# ╠═2ee2a8ec-1f8e-11eb-23e6-9d5e2bb00d1e\n# ╟─d6b5d1f6-1f9e-11eb-0c32-9b9cb51352a0\n# ╠═e0cd119a-1f9e-11eb-1181-3d3fa6e0653f\n# ╠═f3357c5a-1f9e-11eb-270d-d3b5fd6bd542\n# ╠═fbe68df8-1f9e-11eb-1278-a102df99c88c\n# ╠═0bf5f86a-1f8f-11eb-17fd-75f4b45f16d5\n# ╠═2ff48c68-1f8f-11eb-0bd0-cde93f2cc18b\n# ╠═316b7dd0-1f8e-11eb-0da9-9fc5b63a4e80\n# ╠═56e8258a-1f8f-11eb-3249-6592feed84b3\n# ╠═5d7dcbe0-1f8f-11eb-05e9-1b2ae35cf681\n# ╠═bf3bd13c-1f95-11eb-3187-a7311125be18\n# ╠═d3a6bbaa-1f95-11eb-27de-e99b0e230d21\n# ╠═c6d813ba-1f95-11eb-1be6-55cb3ffeb358\n# ╠═d66f2a16-1f95-11eb-3edc-4182c1a4b8ad\n# ╠═d31baed4-1f95-11eb-19df-15ff5c378487\n# ╠═81a7921c-1f8f-11eb-33c6-397d38b57a75\n# ╠═85c8f822-1f8f-11eb-15a1-7956d269779a\n# ╠═dd3031d8-1f9f-11eb-39b2-cb7ac57c6bdf\n# ╠═e4b2733a-1f9f-11eb-30ac-0dc5305b8938\n# ╠═ff15233a-1f9f-11eb-0012-f198e05abaf9\n# ╠═3f36e4a8-1fa0-11eb-1c46-97ff95905b41\n# ╠═f8612fa6-1f91-11eb-36d6-cbd0f9b5b0ea\n# ╠═66f85a94-1fa0-11eb-32bd-178184d8aef9\n# ╠═0a44c782-1f92-11eb-1b67-eb93f1dfe1ff\n# ╠═37039e06-1f92-11eb-192e-e59ffb46a368\n# ╠═c51ad4de-1fa1-11eb-3e01-fb46ed72f493\n# ╠═79e5e5ca-1fa0-11eb-087f-9fad526c1b0e\n# ╠═8fd89a82-1fa0-11eb-2921-0d3c31c93cbc\n# ╠═a207d416-1fa0-11eb-3bf0-bdc40925736e\n# ╠═c7473096-1fa0-11eb-39fd-31c4c4b1eb04\n# ╠═d08a02dc-1fa0-11eb-3369-a7c84dad581a\n# ╠═f072cf66-1fa0-11eb-0789-733f904d41d0\n# ╟─ff8975cc-1fa0-11eb-1fa6-514db7898e52\n# ╠═0b340f86-1fa1-11eb-37bd-839bd7525dc9\n# ╟─0d1c1902-1f96-11eb-0734-1bb3dda2aa7d\n# ╠═a40c4352-1f94-11eb-263e-632828cb6079\n# ╠═b7b6a198-1f94-11eb-0093-8f3ab007d770\n# ╠═bb04eb2c-1f94-11eb-0a4a-3d2765531e94\n# ╠═c0e4f8f2-1f94-11eb-1305-d9028395ab2f\n# ╠═c500ec66-1f94-11eb-079a-1b5b4befade2\n# ╠═1e37c20a-1f95-11eb-37f9-11c5a6041e1b\n# ╠═25be9fbc-1f95-11eb-294a-1dd62a135bfa\n# ╠═7345c08e-1f96-11eb-0bf1-c50d0108facd\n# ╟─b22dc266-1f9a-11eb-199b-170ef50b702c\n# ╠═3f2943c6-1f95-11eb-0342-6569169f32ca\n# ╠═47153ebe-1f95-11eb-2224-716d2e152db0\n# ╠═60135b2e-1f95-11eb-293d-4f8a96a677b2\n# ╠═77de76f8-1f95-11eb-00bc-915dd7977c75\n# ╠═65ef756c-1f96-11eb-2546-35b37cb7f54c\n# ╠═f707de2e-1fa1-11eb-0147-3fca8c03ab5f\n# ╠═2b0265d4-1f96-11eb-1553-ef2ecb7d451b\n# ╟─c5f5c97c-1f97-11eb-3683-55c16be8274e\n# ╠═b86c366c-1f95-11eb-0a18-a52cdf00da4c\n# ╠═d400e394-1f97-11eb-0f74-476c32bdd9d0\n# ╠═f5e3b162-1f97-11eb-2879-f7c7954143a0\n# ╠═000c656c-1f98-11eb-0f0e-657b9651f0bd\n# ╠═149b4c9e-1f98-11eb-19b7-eb9988c9333a\n# ╠═3aae6bac-1f98-11eb-22a5-bdc5e5de3f4c\n# ╠═43bed31c-1f98-11eb-1131-f5dd8dd27086\n# ╟─56fb9c94-1f98-11eb-216e-f9e6e04d6f45\n# ╟─32cf8afa-1f99-11eb-0193-e969cca12f86\n# ╠═51baa858-1f99-11eb-3329-4d9bf850b1c0\n# ╠═64c9235e-1f99-11eb-24f3-d940be06c7c8\n# ╠═ecc5c55a-1f99-11eb-3f44-4161850426cc\n# ╠═40575ec2-1f9a-11eb-2d29-5b517d1f3b18\n# ╠═0b0719c2-1f9c-11eb-3ed6-6927c927145d\n# ╠═11ebb920-1f9c-11eb-061a-8df3899e8945\n# ╠═10b19f7a-1f8b-11eb-128e-11743ce72ef5\n", "meta": {"hexsha": "ff5bb70b7fe07e2996b60d1272ae145656fdee30", "size": 9631, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_notebooks/week10/FloatingPoint.jl", "max_stars_repo_name": "mathijsvdv/ComputationalThinking", "max_stars_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lecture_notebooks/week10/FloatingPoint.jl", "max_issues_repo_name": "mathijsvdv/ComputationalThinking", "max_issues_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecture_notebooks/week10/FloatingPoint.jl", "max_forks_repo_name": "mathijsvdv/ComputationalThinking", "max_forks_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2120418848, "max_line_length": 195, "alphanum_fraction": 0.7105181186, "num_tokens": 5853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7951125908135387}}
{"text": "#############\n# This demonstrates the Padua transform and inverse transform,\n# explaining precisely the normalization and points\n#############\n\nusing FastTransforms\n\nN = 15\npts = paduapoints(N)\nx = pts[:,1]; y = pts[:,2]\n\nf = (x,y) -> exp(x + cos(y))\nf̌ = paduatransform(f.(x , y))\nf̃ = (x,y) -> begin\n    j = 1\n    ret = 0.0\n    for n in 0:N, k in 0:n\n        ret += f̌[j]*cos((n-k)*acos(x)) * cos(k*acos(y))\n        j += 1\n    end\n    ret\nend\n\nf̃(0.1,0.2) ≈ f(0.1,0.2)\n\nipaduatransform(f̌) ≈ f̃.(x,y)\n", "meta": {"hexsha": "bdb9fdab9aaacce845f6901b1ad34d6d9b21298a", "size": 503, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/padua.jl", "max_stars_repo_name": "putianyi889/FastTransforms.jl", "max_stars_repo_head_hexsha": "491716260d0b8de4aa3b9bab15c98a8f8ce59970", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-15T03:23:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T03:23:28.000Z", "max_issues_repo_path": "examples/padua.jl", "max_issues_repo_name": "putianyi889/FastTransforms.jl", "max_issues_repo_head_hexsha": "491716260d0b8de4aa3b9bab15c98a8f8ce59970", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/padua.jl", "max_forks_repo_name": "putianyi889/FastTransforms.jl", "max_forks_repo_head_hexsha": "491716260d0b8de4aa3b9bab15c98a8f8ce59970", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6296296296, "max_line_length": 62, "alphanum_fraction": 0.5248508946, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342024724487, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7950998667284611}}
{"text": "function fractran(n::Integer, ratios::Vector{<:Rational}, steplim::Integer)\n    rst = zeros(BigInt, steplim)\n    for i in 1:steplim\n        rst[i] = n\n        if (pos = findfirst(x -> isinteger(n * x), ratios)) > 0\n            n *= ratios[pos]\n        else\n            break\n        end\n    end\n    return rst\nend\n\nusing IterTools\nmacro ratio_str(s)\n    a = split(s, r\"[\\s,/]+\")\n    return collect(parse(BigInt, n) // parse(BigInt, d) for (n, d) in partition(a, 2))\nend\n\nfracs = ratio\"\"\"17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33, 77 / 29, 95 / 23,\n                77 / 19, 1 / 17, 11 / 13, 13 / 11, 15 / 14, 15 / 2, 55 / 1\"\"\"\nprintln(\"The first 20 in the series are \", fractran(2, fracs, 20))\n\nprmfound = 0\nn = big(2)\nwhile prmfound < 20\n    if isinteger(log2(n))\n        prmfound += 1\n        println(\"Prime $prmfound found: $n is 2 ^ $(Int(log2(n)))\")\n    end\n    n = fractran(n, fracs, 2)[2]\nend\n", "meta": {"hexsha": "d3e38efc381d1a5c6d0b136cfd3cbf48c60bcf5f", "size": 901, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/fractran.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/fractran.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/fractran.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.303030303, "max_line_length": 86, "alphanum_fraction": 0.5416204218, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542805873231, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7950802063464404}}
{"text": "using Statistics;\nusing Random;\n\nfunction distance(from::Vector{T}, to::Vector{V}) where {T,V}\n    sum((from .- to) .^2) |> sqrt\nend\n\nfunction KMEANS(\n    matrix::Vector{Vector{T}},\n    k::Int;\n    max::Int,\n)::Vector{Vector{Vector{T}}} where {T}\n    len = matrix |> length\n    μ = shuffle(MersenneTwister(888888), 1:len)[1:k] .|> x -> matrix[x]\n    C::Vector{Vector{Vector{T}}} = 1:k .|> _ -> []\n    for _ ∈ 1:max\n        for x ∈ matrix\n            distances = μ .|> ϵ -> distance(x, ϵ)\n            min = argmin(distances)\n            C[min] = C[min] ∪ [x]\n        end\n        δ = C .|> x -> mean(x)\n        μ == δ && break\n        μ = δ\n    end\n    C\nend\n\nKMEANS(\n    [\n        [0, 2],\n        [0, 0],\n        [1.5, 0],\n        [5, 0],\n        [5, 2]\n    ],\n    2,\n    max = 20,\n) .|> println\n", "meta": {"hexsha": "b45e6a1cac783fe2a24362678e047dceb89fb070", "size": 795, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "DataMining/k-means/src/main.jl", "max_stars_repo_name": "lovebaihezi/lab", "max_stars_repo_head_hexsha": "9f28b8b038bfdb0297d8a34520a3df69d683f42d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DataMining/k-means/src/main.jl", "max_issues_repo_name": "lovebaihezi/lab", "max_issues_repo_head_hexsha": "9f28b8b038bfdb0297d8a34520a3df69d683f42d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DataMining/k-means/src/main.jl", "max_forks_repo_name": "lovebaihezi/lab", "max_forks_repo_head_hexsha": "9f28b8b038bfdb0297d8a34520a3df69d683f42d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.875, "max_line_length": 71, "alphanum_fraction": 0.4503144654, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542864252023, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.7950802051056818}}
{"text": "@doc raw\"\"\"\n    gausschebyshev(n::Integer) -> Tuple{Vector{Float64},Vector{Float64}}\n    gausschebyshev(n::Integer, 1) -> Tuple{Vector{Float64},Vector{Float64}}\n\nReturn nodes and weights of [Gauss-Chebyshev quadrature](https://en.wikipedia.org/wiki/Chebyshev%E2%80%93Gauss_quadrature) of the 1st kind.\n\n```math\n\\int_{-1}^{1} \\frac{f(x)}{\\sqrt{1-x^2}} dx \\approx \\sum_{i=1}^{n} w_i f(x_i)\n```\n\n# Examples\n```jldoctest\njulia> x, w = gausschebyshev(3);\n\njulia> f(x) = x^4;\n\njulia> I = dot(w, f.(x));\n\njulia> I ≈ 3π/8\ntrue\n```\n\n---\n\n    gausschebyshev(n::Integer, 2) -> Tuple{Vector{Float64},Vector{Float64}}\n\nReturn nodes and weights of [Gauss-Chebyshev quadrature](https://en.wikipedia.org/wiki/Chebyshev%E2%80%93Gauss_quadrature) of the 2nd kind.\n\n```math\n\\int_{-1}^{1} f(x)\\sqrt{1-x^2} dx \\approx \\sum_{i=1}^{n} w_i f(x_i)\n```\n\n# Examples\n```jldoctest\njulia> x, w = gausschebyshev(3, 2);\n\njulia> f(x) = x^4;\n\njulia> I = dot(w, f.(x));\n\njulia> I ≈ π/16\ntrue\n```\n\n---\n\n    gausschebyshev(n::Integer, 3) -> Tuple{Vector{Float64},Vector{Float64}}\n\nReturn nodes and weights of [Gauss-Chebyshev quadrature](https://en.wikipedia.org/wiki/Chebyshev%E2%80%93Gauss_quadrature) of the 3rd kind.\n\n```math\n\\int_{-1}^{1} f(x)\\sqrt{1-x^2} dx \\approx \\sum_{i=1}^{n} w_i f(x_i)\n```\n\n# Examples\n```jldoctest\njulia> x, w = gausschebyshev(3, 3);\n\njulia> f(x) = x^4;\n\njulia> I = dot(w, f.(x));\n\njulia> I ≈ 3π/8\ntrue\n```\n\n---\n\n    gausschebyshev(n::Integer, 4) -> Tuple{Vector{Float64},Vector{Float64}}\n\nReturn nodes and weights of [Gauss-Chebyshev quadrature](https://en.wikipedia.org/wiki/Chebyshev%E2%80%93Gauss_quadrature) of the 4th kind.\n\n```math\n\\int_{-1}^{1} f(x)\\sqrt{1-x^2} dx \\approx \\sum_{i=1}^{n} w_i f(x_i)\n```\n\n# Examples\n```jldoctest\njulia> x, w = gausschebyshev(3, 4);\n\njulia> f(x) = x^4;\n\njulia> I = dot(w, f.(x));\n\njulia> I ≈ 3π/8\ntrue\n```\n\"\"\"\nfunction gausschebyshev(n::Integer, kind::Integer=1)\n    # GAUSS-CHEBYSHEV NODES AND WEIGHTS.\n\n    if n < 0\n        throw(DomainError(n, \"Input n must be a non-negative integer\"))\n    end\n\n    # Use known explicit formulas. Complexity O(n).\n    if kind == 1\n        # Gauss-ChebyshevT quadrature, i.e., w(x) = 1/sqrt(1-x^2)\n        return ([cos((2 * k - 1) * π / (2 * n)) for k = n:-1:1], fill(π / n, n))\n    elseif kind == 2\n        # Gauss-ChebyshevU quadrature, i.e., w(x) = sqrt(1-x^2)\n        return ([cos(k * π / (n + 1)) for k = n:-1:1],\n                [π/(n + 1) * sin(k / (n + 1) * π)^2 for k = n:-1:1])\n    elseif kind == 3\n        # Gauss-ChebyshevV quadrature, i.e., w(x) = sqrt((1+x)/(1-x))\n        return ([cos((k - .5) * π / (n + .5)) for k = n:-1:1],\n                [2π / (n + .5) * cos((k - .5) * π / (2 * (n + .5)))^2 for k = n:-1:1])\n    elseif kind == 4\n        # Gauss-ChebyshevW quadrature, i.e., w(x) = sqrt((1-x)/(1+x))\n        return ([cos(k * π / (n + .5)) for k = n:-1:1],\n                [2π / (n + .5) * sin(k * π / (2 * (n + .5)))^2 for k = n:-1:1])\n    else\n        throw(ArgumentError(\"Chebyshev kind should be 1, 2, 3, or 4\"))\n    end\nend\n", "meta": {"hexsha": "f860e3a9c238ad59d568faad6dffd3b234ac95dd", "size": 3015, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gausschebyshev.jl", "max_stars_repo_name": "Datseris/FastGaussQuadrature.jl", "max_stars_repo_head_hexsha": "dd1f2fed53c4024bb6bde9f8d5a237ac47985b51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 145, "max_stars_repo_stars_event_min_datetime": "2019-04-12T02:58:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:02:17.000Z", "max_issues_repo_path": "src/gausschebyshev.jl", "max_issues_repo_name": "Datseris/FastGaussQuadrature.jl", "max_issues_repo_head_hexsha": "dd1f2fed53c4024bb6bde9f8d5a237ac47985b51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2019-04-08T23:32:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T21:02:07.000Z", "max_forks_repo_path": "src/gausschebyshev.jl", "max_forks_repo_name": "Datseris/FastGaussQuadrature.jl", "max_forks_repo_head_hexsha": "dd1f2fed53c4024bb6bde9f8d5a237ac47985b51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-04-11T03:26:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T10:24:13.000Z", "avg_line_length": 25.9913793103, "max_line_length": 139, "alphanum_fraction": 0.5781094527, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542794197472, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7950801992985881}}
{"text": "# # [Stochastic Gradient Descent](@id SGDTutorial)\n#\n# This tutorial illustrates how to use the [`stochastic_gradient_descent`](@ref)\n# solver and different [`DirectionUpdateRule`](@ref)s in order to introduce\n# the average or momentum variant, see [Stochastic Gradient Descent](https://en.wikipedia.org/wiki/Stochastic_gradient_descent).\n#\n# Computationally we look at a very simple but large scale problem,\n# the Riemannian Center of Mass or [Fréchet mean](https://en.wikipedia.org/wiki/Fréchet_mean):\n# For given points ``p_i ∈\\mathcal M``, ``i=1,…,N`` this optimization problem reads\n#\n# ```math\n# \\operatorname*{arg\\,min}_{x∈\\mathcal M} \\frac{1}{2}\\sum_{i=1}^{N}\n#   \\operatorname{d}^2_{\\mathcal M}(x,p_i),\n# ```\n# which of course can be (and is) solved by a gradient descent, see the [introductionary tutorial](@ref Optimize).\n# If ``N`` is very large it might be quite expensive to evaluate the complete gradient.\n# A remedy is, to evaluate only one of the terms at a time and choose a random order for these.\n#\n# We first initialize the manifold (see [])\nexport_folder = joinpath( #src\n    @__DIR__, #src\n    \"..\", #src\n    \"..\", #src\n    \"docs\", #src\n    \"src\", #src\n    \"assets\", #src\n    \"images\", #src\n    \"tutorials\", #src\n) #src\nusing Manopt, Manifolds, Random, Colors\n# and we define some colors from [Paul Tol](https://personal.sron.nl/~pault/)\nblack = RGBA{Float64}(colorant\"#000000\")\nTolVibrantOrange = RGBA{Float64}(colorant\"#EE7733\") # Start\nTolVibrantBlue = RGBA{Float64}(colorant\"#0077BB\") # a path\nTolVibrantTeal = RGBA{Float64}(colorant\"#009988\") # points\nnothing #hide\n#\n# And optain a large data set\nn = 5000\nσ = π / 12\nM = Sphere(2)\nx = 1 / sqrt(2) * [1.0, 0.0, 1.0]\nRandom.seed!(42)\ndata = [exp(M, x, random_tangent(M, x, Val(:Gaussian), σ)) for i in 1:n]\nnothing #hide\n# which looks like\n#\nasymptote_export_S2_signals( #src\n    export_folder * \"/centerAndLargeData.asy\"; #src\n    points=[[x], data], #src\n    colors=Dict(:points => [TolVibrantOrange, TolVibrantTeal]), #src\n    dot_sizes=[2.5, 1.25], #src\n    camera_position=(1.0, 0.5, 0.5), #src\n) #src\nrender_asymptote(export_folder * \"/centerAndLargeData.asy\"; render=2) #src\n#md # ```julia\n#md # asymptote_export_S2_signals(\"centerAndLargeData.asy\";\n#md #     points = [ [x], data],\n#md #     colors=Dict(:points => [TolVibrantBlue, TolVibrantTeal]),\n#md #     dot_sizes = [2.5, 1.0], camera_position = (1.,.5,.5)\n#md # )\n#md # render_asymptote(\"centerAndLargeData.asy\"; render = 2)\n#md # ```\n#md #\n#md # ![The data of noisy versions of $x$](../assets/images/tutorials/centerAndLargeData.png)\n#\n# Note that due to the construction of the points as zero mean tangent vectors, the mean should\n# be very close to our initial point `x`.\n#\n# In order to use the stochastic gradient, we now need a function that returns the vector of gradients.\n# There are two ways to define it in `Manopt.jl`: as one function, that returns a vector or a vector of funtions.\n#\n# The first variant is of course easier to define, but the second is more efficient when only evaluating one of the gradients.\n# For the mean we have as a gradient\n#\n# ```math\n#  gradF(x) = \\sum_{i=1}^N \\operatorname{grad}f_i(x) \\quad \\text{where} \\operatorname{grad}f_i(x) = -\\log_x p_i\n# ```\n#\n# Which we define as\nF(M, x) = 1 / (2 * n) * sum(map(p -> distance(M, x, p)^2, data))\ngradF(M, x) = [grad_distance(M, p, x) for p in data]\ngradf = [(M, x) -> grad_distance(M, p, x) for p in data];\n# The calls are only slightly different, but notice that accessing the 2nd gradient element\n# requires evaluating all logs in the first function.\n# So while you can use both `gradF` and `gradf` in the following call, the second one is faster:\n@time x_opt1 = stochastic_gradient_descent(M, gradF, x);\n# versus\n@time x_opt2 = stochastic_gradient_descent(M, gradf, x);\n# This result is reasonably close. But we can improve it by using a [`DirectionUpdateRule`](@ref),\n# namely:\n# On the one hand [`MomentumGradient`](@ref), which requires both the manifold and the initial value,\n#    in order to keep track of the iterate and parallel transport the last direction to the current iterate.\n#    you can also set a `vector_transport_method`, if `ParallelTransport()` is not\n#    available on your manifold. Here we simply do\n@time x_opt3 = stochastic_gradient_descent(\n    M, gradf, x; direction=MomentumGradient(M, x, StochasticGradient(zero_vector(M, x)))\n);\n# And on the other hand the [`AverageGradient`](@ref) computes an average of the last `n` gradients, i.e.\n@time x_opt4 = stochastic_gradient_descent(\n    M, gradf, x; direction=AverageGradient(M, x, 10, StochasticGradient(zero_vector(M, x)))\n);\n# note that the default [`StoppingCriterion`](@ref) is a fixed number of iterations.\n#\n# Note that since you can apply both also in case of [`gradient_descent`](@ref),\n# i.e. to use [`IdentityUpdateRule`](@ref) and evaluate the classical gradient,\n# both constructors have to know that internally the default evaluation of the Stochastic gradient\n# (choosing one gradient $\\operatorname{grad}f_k$ at random) has to be specified.\n#\n# For this small example you can of course also use a gradient descent with [`ArmijoLinesearch`](@ref),\n# but it will be a little slower usually\n@time x_opt5 = gradient_descent(\n    M, F, (M, x) -> sum(gradF(M, x)), x; stepsize=ArmijoLinesearch()\n);\n# but it is for sure faster than the variant above that evaluates the full gradient on every iteration,\n# since stochastic gradient descent takes more iterations.\n#\n# Note that all 5 of couse yield the same result\n[distance(M, x, y) for y in [x_opt1, x_opt2, x_opt3, x_opt4, x_opt5]]\n", "meta": {"hexsha": "e7bc279a40685a25dc4eab1b89dd60e7fcb7f34b", "size": 5598, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tutorials/StochasticGradientDescent.jl", "max_stars_repo_name": "const-ae/Manopt.jl", "max_stars_repo_head_hexsha": "cdaeee451d53d4813d37cf859f2ca6adcad82635", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 141, "max_stars_repo_stars_event_min_datetime": "2020-03-30T08:00:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T09:37:54.000Z", "max_issues_repo_path": "src/tutorials/StochasticGradientDescent.jl", "max_issues_repo_name": "const-ae/Manopt.jl", "max_issues_repo_head_hexsha": "cdaeee451d53d4813d37cf859f2ca6adcad82635", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 90, "max_issues_repo_issues_event_min_datetime": "2020-03-30T08:00:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T08:55:37.000Z", "max_forks_repo_path": "src/tutorials/StochasticGradientDescent.jl", "max_forks_repo_name": "const-ae/Manopt.jl", "max_forks_repo_head_hexsha": "cdaeee451d53d4813d37cf859f2ca6adcad82635", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2020-04-14T11:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T21:36:59.000Z", "avg_line_length": 46.65, "max_line_length": 128, "alphanum_fraction": 0.7100750268, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.8856314723088733, "lm_q1q2_score": 0.7950271935378826}}
{"text": "# ---\n# title: 396. Rotate Function\n# id: problem396\n# author: Tian Jun\n# date: 2020-11-14\n# difficulty: Medium\n# categories: Math\n# link: <https://leetcode.com/problems/rotate-function/description/>\n# hidden: true\n# ---\n# \n# Given an array of integers `A` and let _n_ to be its length.\n# \n# Assume `Bk` to be an array obtained by rotating the array `A` _k_ positions\n# clock-wise, we define a \"rotation function\" `F` on `A` as follow:\n# \n# `F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]`.\n# \n# Calculate the maximum value of `F(0), F(1), ..., F(n-1)`.\n# \n# **Note:**  \n# _n_ is guaranteed to be less than 105.\n# \n# **Example:**\n# \n#     \n#     \n#     A = [4, 3, 2, 6]\n#     \n#     F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25\n#     F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16\n#     F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23\n#     F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26\n#     \n#     So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.\n#     \n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction max_rotate_function(A::Vector{Int})::Int\n    ## f(i+1) = f(i) + ∑(A) - A[end] * length(A)\n    s = sum(A)\n    n = length(A)\n    cur = sum(k -> (k - 1) * A[k], 1:n)\n    res = cur\n    for i in n:-1:2\n        cur += s - n * A[i]\n        res = max(res, cur)\n    end\n    return res\nend\n## @lc code=end\n", "meta": {"hexsha": "dc74e1bbca2f91e7815acb2b59b3b33194392f7d", "size": 1400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/396.rotate-function.jl", "max_stars_repo_name": "noob-data-analaysis/LeetCode.jl", "max_stars_repo_head_hexsha": "94d91b295e988948e77e737c10d2f0e3ecb7c2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/396.rotate-function.jl", "max_issues_repo_name": "noob-data-analaysis/LeetCode.jl", "max_issues_repo_head_hexsha": "94d91b295e988948e77e737c10d2f0e3ecb7c2b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-10T02:19:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T05:00:12.000Z", "max_forks_repo_path": "src/problems/396.rotate-function.jl", "max_forks_repo_name": "noob-data-analaysis/LeetCode.jl", "max_forks_repo_head_hexsha": "94d91b295e988948e77e737c10d2f0e3ecb7c2b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4545454545, "max_line_length": 77, "alphanum_fraction": 0.4721428571, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505204, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7950175787446487}}
{"text": "export ode45, rk4, αscheme, αscheme_time, \n    αscheme_atime, TR_BDF2, ExplicitNewmark, Newmark\n\nfunction runge_kutta_one_step(f::Function, t::PyObject, y::PyObject, Δt::PyObject, θ::Union{PyObject, Missing})\n    k1 = Δt*f(t, y, θ)\n    k2 = Δt*f(t+Δt/2, y+k1/2, θ)\n    k3 = Δt*f(t+Δt/2, y+k2/2, θ)\n    k4 = Δt*f(t+Δt, y+k3, θ)\n    y = y + k1/6 + k2/3 + k3/3 + k4/6\nend\n\nfunction ode45_one_step(f::Function, t::PyObject, y::PyObject, h::PyObject, θ::Union{PyObject, Missing})\n    k1 = h * f(t, y, θ);\n    k2 = h * f(t + (1/5)*h, y + (1/5)*k1, θ);\n    k3 = h * f(t + (3/10)*h, y + (3/40)*k1 + (9/40)*k2, θ);\n    k4 = h * f(t + (4/5)*h, y + (44/45)*k1 + (-56/15)*k2 + (32/9)*k3, θ);\n    k5 = h * f(t + (8/9)*h, y + (19372/6561)*k1 + (-25360/2187)*k2 + (64448/6561)*k3 + (-212/729)*k4, θ);\n    k6 = h * f(t + h, y + (9017/3168)*k1 + (-355/33)*k2 + (46732/5247 )*k3 + (49/176)*k4 + (-5103/18656)*k5, θ);\n    k7 = h * f(t + h, y + (35/384)*k1 + (500/1113)*k3 + (125/192)*k4 + (-2187/6784)*k5 + (11/84)*k6, θ);\n    \n    y_new = y + (35/384)*k1 + (500/1113)*k3 + (125/192)*k4 + (-2187/6784)*k5 + (11/84)*k6;\nend\n\n@doc raw\"\"\"\n    runge_kutta(f::Function, T::Union{PyObject, Float64}, \n                NT::Union{PyObject,Int64}, y::Union{PyObject, Float64, Array{Float64}}, θ::Union{PyObject, Missing}=missing; method::String=\"rk4\")\n\nSolves \n```math\n\\frac{dy}{dt} = f(y, t, \\theta)\n```\nwith Runge-Kutta method. \n\nFor example, the default solver, `RK4`, has the following numerical scheme per time step \n```math\n\\begin{aligned}\nk_1 &= \\Delta t f(t_n, y_n, \\theta)\\\\\nk_2 &= \\Delta t f(t_n+\\Delta t/2, y_n + k_1/2, \\theta)\\\\\nk_3 &= \\Delta t f(t_n+\\Delta t/2, y_n + k_2/2, \\theta)\\\\\nk_4 &= \\Delta t f(t_n+\\Delta t, y_n + k_3, \\theta)\\\\\ny_{n+1} &= y_n + \\frac{k_1}{6} +\\frac{k_2}{3} +\\frac{k_3}{3} +\\frac{k_4}{6}\n\\end{aligned}\n```\n\"\"\"\nfunction runge_kutta(f::Function, T::Union{PyObject, Float64}, \n                NT::Union{PyObject,Int64}, y::Union{PyObject, Float64, Array{Float64}}, θ::Union{PyObject, Missing}=missing; method::String=\"rk4\")\n\n    local one_step\n    if lowercase(method)==\"rk4\"\n        one_step = runge_kutta_one_step\n    elseif lowercase(method)==\"rk45\"\n        one_step = ode45_one_step\n    else\n        error(\"Method $method not implemented yet\")\n    end\n    y = convert_to_tensor(y)\n    Δt = convert_to_tensor(T/NT)\n\n    ta = TensorArray(NT+1) # storing y\n    function condition(i, ta)\n        i <= NT+1\n    end\n    function body(i, ta)\n        y = read(ta, i-1)\n        y_ = one_step(f, (cast(eltype(Δt), i)-1)*Δt, y, Δt, θ)\n        ta = write(ta, i, y_)\n        i+1, ta \n    end\n    ta = write(ta, 1, y)\n    i = constant(2, dtype=Int32)\n    _, out = while_loop(condition, body, [i, ta])\n    res = stack(out)\nend\n\n@doc raw\"\"\"\n    rk4(y::Union{PyObject, Float64, Array{Float64}}, T::Union{PyObject, Float64}, \n                NT::Union{PyObject,Int64}, f::Function, θ::Union{PyObject, Missing}=missing)\n\nSolves \n```math\n\\frac{dy}{dt} = f(y, t, \\theta)\n```\nwith Runge-Kutta (order 4) method. \n\"\"\"\nrk4(args...;kwargs...) = runge_kutta(args...;method=\"rk4\", kwargs...)\n\n@doc raw\"\"\"\n    ode45(y::Union{PyObject, Float64, Array{Float64}}, T::Union{PyObject, Float64}, \n                NT::Union{PyObject,Int64}, f::Function, θ::Union{PyObject, Missing}=missing)\n\nSolves \n```math\n\\frac{dy}{dt} = f(y, t, \\theta)\n```\nwith six-stage, fifth-order, Runge-Kutta method.\n\"\"\"\node45(args...;kwargs...) = runge_kutta(args...;method=\"rk45\", kwargs...)\n\n\n@doc raw\"\"\"\n    αscheme(M::Union{SparseTensor, SparseMatrixCSC}, \n        C::Union{SparseTensor, SparseMatrixCSC}, \n        K::Union{SparseTensor, SparseMatrixCSC}, \n        Force::Union{Array{Float64}, PyObject}, \n        d0::Union{Array{Float64, 1}, PyObject}, \n        v0::Union{Array{Float64, 1}, PyObject}, \n        a0::Union{Array{Float64, 1}, PyObject}, \n        Δt::Array{Float64}; \n        solve::Union{Missing, Function} = missing,\n        extsolve::Union{Missing, Function} = missing, \n        ρ::Float64 = 1.0)\n\nGeneralized α-scheme. \n$$M u_{tt} + C u_{t} + K u = F$$\n\n`Force` must be an array of size `n`×`p`, where `d0`, `v0`, and `a0` have a size `p`\n`Δt` is an array (variable time step). \n\nThe generalized α scheme solves the equation by the time stepping\n```math\n\\begin{aligned}\n\\bf d_{n+1} &= \\bf d_n + h\\bf v_n + h^2 \\left(\\left(\\frac{1}{2}-\\beta_2 \\right)\\bf a_n + \\beta_2 \\bf a_{n+1}  \\right)\\\\\n\\bf v_{n+1} &= \\bf v_n + h((1-\\gamma_2)\\bf a_n + \\gamma_2 \\bf a_{n+1})\\\\\n\\bf F(t_{n+1-\\alpha_{f_2}}) &= M \\bf a _{n+1-\\alpha_{m_2}} + C \\bf v_{n+1-\\alpha_{f_2}} + K \\bf{d}_{n+1-\\alpha_{f_2}}\n\\end{aligned}\n```\nwhere \n```math\n\\begin{aligned}\n\\bf d_{n+1-\\alpha_{f_2}} &= (1-\\alpha_{f_2})\\bf d_{n+1} + \\alpha_{f_2} \\bf d_n\\\\\n\\bf v_{n+1-\\alpha_{f_2}} &= (1-\\alpha_{f_2}) \\bf v_{n+1} + \\alpha_{f_2} \\bf v_n \\\\\n\\bf a_{n+1-\\alpha_{m_2} } &= (1-\\alpha_{m_2}) \\bf a_{n+1} + \\alpha_{m_2} \\bf a_n\\\\\nt_{n+1-\\alpha_{f_2}} & = (1-\\alpha_{f_2}) t_{n+1 + \\alpha_{f_2}} + \\alpha_{f_2}t_n\n\\end{aligned}\n```\n\nHere the parameters are computed using \n```math \n\\begin{aligned}\n\\gamma_2 &= \\frac{1}{2} - \\alpha_{m_2} + \\alpha_{f_2}\\\\\n\\beta_2 &= \\frac{1}{4} (1-\\alpha_{m_2}+\\alpha_{f_2})^2 \\\\\n\\alpha_{m_2} &= \\frac{2\\rho_\\infty-1}{\\rho_\\infty+1}\\\\\n\\alpha_{f_2} &= \\frac{\\rho_\\infty}{\\rho_\\infty+1}\n\\end{aligned}\n```\n\n∘ `solve`: users can provide a solver function, `solve(A, rhs)` for solving `Ax = rhs`\n∘ `extsolve`: similar to `solve`, but the signature has the form \n```julia\nextsolve(A, rhs, i)\n```\nThis provides the users with more control, e.g., (time-dependent) Dirichlet boundary conditions. \nSee [Generalized α Scheme](https://kailaix.github.io/ADCME.jl/dev/alphascheme/) for details.\n\n!!! note \n    In the case $u$ has a nonzero essential boundary condition $u_b$, we let $\\tilde u=u-u_b$, then \n    $$M \\tilde u_{tt} + C \\tilde u_t + K u = F - K u_b - C \\dot u_b$$\n\"\"\"\nfunction αscheme(M::Union{SparseTensor, SparseMatrixCSC}, \n                      C::Union{SparseTensor, SparseMatrixCSC}, \n                      K::Union{SparseTensor, SparseMatrixCSC}, \n                      Force::Union{Array{Float64, 2}, PyObject}, \n                      d0::Union{Array{Float64, 1}, PyObject}, \n                      v0::Union{Array{Float64, 1}, PyObject}, \n                      a0::Union{Array{Float64, 1}, PyObject}, \n                      Δt::Array{Float64, 1}; \n                      solve::Union{Missing, Function} = missing,\n                      extsolve::Union{Missing, Function} = missing, \n                      ρ::Float64 = 1.0)\n    if !ismissing(solve) && !ismissing(extsolve)\n        error(\"You cannot provide `solve` and `extsolve` at the same time.\")\n    end\n    nt = length(Δt)\n    αm = (2ρ-1)/(ρ+1)\n    αf = ρ/(1+ρ)\n    γ = 1/2-αm+αf \n    β = 0.25*(1-αm+αf)^2\n    d = length(d0)\n\n    M = isa(M, SparseMatrixCSC) ? constant(M) : M\n    C = isa(C, SparseMatrixCSC) ? constant(C) : C\n    K = isa(K, SparseMatrixCSC) ? constant(K) : K\n    Force, d0, v0, a0, Δt = convert_to_tensor([Force, d0, v0, a0, Δt], [Float64, Float64, Float64, Float64, Float64])\n\n    function equ(dc, vc, ac, dt, Force, i)\n        dn = dc + dt*vc + dt^2/2*(1-2β)*ac \n        vn = vc + dt*((1-γ)*ac)\n\n        df = (1-αf)*dn + αf*dc\n        vf = (1-αf)*vn + αf*vc \n        am = αm*ac \n\n        rhs = Force - (M*am + C*vf + K*df)\n        A = (1-αm)*M + (1-αf)*C*dt*γ + (1-αf)*K*β*dt^2\n\n        if !ismissing(solve)\n            return solve(A, rhs)\n        elseif !ismissing(extsolve)\n            return extsolve(A, rhs, i)\n        else \n            return A\\rhs\n        end\n    end\n\n    function condition(i, tas...)\n        return i<=nt\n    end\n    function body(i, tas...)\n        dc_arr, vc_arr, ac_arr = tas\n        dc = read(dc_arr, i)\n        vc = read(vc_arr, i)\n        ac = read(ac_arr, i)\n        y = equ(dc, vc, ac, Δt[i], Force[i], i)\n        dn = dc + Δt[i]*vc + Δt[i]^2/2*((1-2β)*ac+2β*y)\n        vn = vc + Δt[i]*((1-γ)*ac+γ*y)\n        i+1, write(dc_arr, i+1, dn), write(vc_arr, i+1, vn), write(ac_arr, i+1, y)\n    end\n\n    dM = TensorArray(nt+1); vM = TensorArray(nt+1); aM = TensorArray(nt+1)\n    dM = write(dM, 1, d0)\n    vM = write(vM, 1, v0)\n    aM = write(aM, 1, a0)\n    i = constant(1, dtype=Int32)\n    _, d, v, a = while_loop(condition, body, [i,dM, vM, aM])\n    set_shape(stack(d), (nt+1, length(d0))), set_shape(stack(v), (nt+1, length(v0))), set_shape(stack(a), (nt+1, length(a0)))\nend\n\n\n@doc raw\"\"\"\n    αscheme_time(Δt::Array{Float64}; ρ::Float64 = 1.0)\n\nReturns the integration time $t_{i+1-\\alpha_{f_2}}$ between $[t_i, t_{i+1}]$ using the alpha scheme. \nIf $\\Delta t$ has length $n$, the output will also have length $n$. \n\"\"\"\nfunction αscheme_time(Δt::Array{Float64}; ρ::Float64 = 1.0)\n    n = length(Δt)\n    αm = (2ρ-1)/(ρ+1)\n    αf = ρ/(1+ρ)\n    γ = 1/2-αm+αf \n    β = 0.25*(1-αm+αf)^2\n    function equ(tc, dt)\n        tf1 = (1-αf)*(tc+dt) + αf*tc\n        return tf1\n    end\n\n    tcf = Float64[]\n    tc = 0.0\n    for i = 1:n\n        t1 = equ(tc, Δt[i])\n        push!(tcf, t1)\n        tc += Δt[i]\n    end\n    return tcf\nend\n\n@doc raw\"\"\"\n    TR_BDF2(D0::Union{SparseTensor, SparseMatrixCSC}, \n        D1::Union{SparseTensor, SparseMatrixCSC}, \n        Δt::Float64)\n\nConstructs a TR-BDF2 (the Trapezoidal Rule with Second Order Backward Difference Formula) handler for \nthe DAE \n\n$$D_1 \\dot y + D_0 y = f$$\n\nThe struct is a functor, which performs one step simulation \n\n```\n(tr::TR_BDF2)(y::Union{PyObject, Array{Float64, 1}}, \n    f1::Union{PyObject, Array{Float64, 1}}, \n    f2::Union{PyObject, Array{Float64, 1}}, \n    f3::Union{PyObject, Array{Float64, 1}})\n```\nHere `f1`, `f2`, and `f3` correspond to the right hand side at time step $n$, $n+\\frac12$, and $n+1$.\n\nOr we can pass a batched `F` defined as a `(2NT+1) × DOF` array\n\n```\n(tr::TR_BDF2)(y0::Union{PyObject, Array{Float64, 1}}, \n    F::Union{PyObject, Array{Float64, 2}})\n```\n\nThe output will be the entire solution of size `(NT+1) × DOF`.\n\n\n!!! info \n    The scheme takes the following form for n = 0, 1, ...\n    $$\\begin{aligned} D_1(y^{n+\\frac12}-y^n) = \\frac12\\frac{\\Delta t}{2}\\left(f^{n+\\frac12} + f^n - D_0 \\left(y^{n+\\frac12} + y^n\\right)\\right)\\\\ \\left(\\frac{\\Delta t}{2}\\right)^{-1} D_1 \\left(\\frac32y^{n+1} - 2y^{n+\\frac12} + \\frac12 y^n\\right) + D_0 y^{n+1} = f^{n+1}\\end{aligned}$$\n\"\"\"\nmutable struct TR_BDF2 \n    D0::Union{SparseTensor, SparseMatrixCSC} \n    D1::Union{SparseTensor, SparseMatrixCSC}  \n    Δt::Float64\n    _D0::Union{SparseTensor, SparseMatrixCSC} \n    _D1::Union{SparseTensor, SparseMatrixCSC}\n    symbolic::Bool \n    function TR_BDF2(D0::Union{SparseTensor, SparseMatrixCSC}, \n            D1::Union{SparseTensor, SparseMatrixCSC}, \n            Δt::Float64)\n        if isa(D0, SparseTensor) || isa(D1, SparseTensor)\n            symbolic = true \n            D0 = constant(D0)\n            D1 = constant(D1)\n        else \n            symbolic = false \n        end\n        @assert size(D0, 1)==size(D0,2)==size(D1,1)==size(D1,2)\n        _D0 = D1 + Δt/4 * D0 \n        _D1 = 1/(Δt/2) * 3/2 * D1  + D0 \n        new(D0, D1, Δt, _D0, _D1, symbolic)\n    end\nend\n\n\"\"\"\n    constant(tr::TR_BDF2)\n\nConverts `tr` to a symbolic solver. \n\"\"\"\nfunction constant(tr::TR_BDF2)\n    TR_BDF2(constant(tr.D0), constant(tr.D1), tr.Δt)\nend\n\nfunction Base.:show(io::IO, tr::TR_BDF2)\n    print(\"\"\"TR_BDF2 (DOF = $(size(tr.D0, 1)), Δt = $(tr.Δt)$(tr.symbolic ? \", symbolic\" : \"\"))\"\"\")\nend\n\nfunction (tr::TR_BDF2)(y::Union{PyObject, Array{Float64, 1}}, \n    f1::Union{PyObject, Array{Float64, 1}}, \n    f2::Union{PyObject, Array{Float64, 1}}, \n    f3::Union{PyObject, Array{Float64, 1}})\n    y, f1, f2, f3 = convert_to_tensor([y, f1, f2, f3], [Float64, Float64, Float64, Float64])\n    r1 = tr.Δt/4 * (f2 + f1) - tr.Δt/4 * (tr.D0 * y) + tr.D1 * y\n    yn = tr._D0\\r1\n    r2 = f3 + 1/(tr.Δt/2)*(tr.D1* (2*yn - 0.5*y))\n    tr._D1\\r2\nend\n\nfunction (tr::TR_BDF2)(y0::Union{PyObject, Array{Float64, 1}}, \n    F::Union{PyObject, Array{Float64, 2}})\n    @assert size(F, 2)==size(tr.D0, 1) && mod(size(F, 1), 2)==1\n    y0, F = convert_to_tensor([y0, F], [Float64, Float64])\n    NT = size(F, 1)÷2\n    y_arr = TensorArray(NT+1)\n    y_arr = write(y_arr, 1, y0)\n    function condition(i, y_arr)\n        i<=NT\n    end\n    function body(i, y_arr)\n        y = read(y_arr, i)\n        f1, f2, f3 = F[2*i-1], F[2*i], F[2*i+1]\n        yn = tr(y, f1, f2, f3)\n        i+1, write(y_arr, i+1, yn)\n    end\n    i = constant(1, dtype = Int32)\n    _, ya = while_loop(condition, body, [i, y_arr])\n    set_shape(stack(ya), (NT+1, length(y0)))\nend\n\nfunction (tr::TR_BDF2)(y::Array{Float64, 1}, \n    f1::Array{Float64, 1}, \n    f2::Array{Float64, 1}, \n    f3::Array{Float64, 1})\n    if tr.symbolic\n        return tr(constant(y), f1, f2, f3)\n    end\n    r1 = tr.Δt/4 * (f2 + f1) - tr.Δt/4 * (tr.D0 * y) + tr.D1 * y\n    yn = tr._D0\\r1\n    r2 = f3 + 1/(tr.Δt/2)*(tr.D1* (2*yn - 0.5*y))\n    tr._D1\\r2\nend\n\nfunction (tr::TR_BDF2)(y0::Array{Float64,1}, F::Array{Float64, 2})\n    if tr.symbolic\n        return tr(constant(y0), F)\n    end\n    @assert size(F, 2)==size(tr.D0, 1) && mod(size(F, 1), 2)==1\n    y = zeros(size(F, 1)÷2+1, 2)\n    y[1,:] = y0\n    for i = 1:size(F, 1)÷2\n        y[i+1,:] = tr(y[i,:], F[2*i-1,:], F[2*i,:], F[2*i+1,:])\n    end\n    y\nend\n\n\n# design principle: proceed one step \n# (states) u0, u1, ..., (coefficients) M0, M1, ..., (step size) Δt\n\n@doc raw\"\"\"\n    ExplicitNewmark(M::Union{SparseTensor, SparseMatrixCSC}, Z1::Union{Missing, SparseTensor, SparseMatrixCSC}, Z2::Union{Missing, SparseTensor, SparseMatrixCSC}, Δt::Float64)\n\nAn explicit Newmark integrator for \n\n$$M \\ddot{\\mathbf{d}} + Z_1 \\dot{\\mathbf{d}} + Z_2 \\mathbf{d} + f = 0$$\n\nThe numerical scheme is \n\n$$\\left(\\frac{1}{\\Delta t^2} M + \\frac{1}{2\\Delta t}Z_1\\right)d^{n+1} = \\left(\\frac{2}{\\Delta t^2} M - Z_2\\right)d^n - \\left(\\frac{1}{\\Delta t^2} M - \\frac{1}{2\\Delta t}Z_1\\right) d^{n-1} - f$$\n\nTo use this integrator, \n\n```julia \nen = ExplicitNewmark(M, Z1, Z2, Δt)\nd2 = step(en, d0, d1, f)\n```\n\"\"\"\nmutable struct ExplicitNewmark \n    A::Union{PyObject, Tuple{SparseTensor, PyObject}, SparseTensor}\n    B::Union{PyObject, SparseTensor} \n    C::Union{PyObject, SparseTensor} \n    function ExplicitNewmark(M::Union{SparseTensor, PyObject, Array{Float64, 2}, SparseMatrixCSC}, \n            Z1::Union{Missing, PyObject, Array{Float64, 2}, SparseTensor, SparseMatrixCSC}, \n            Z2::Union{Missing, PyObject, Array{Float64, 2}, SparseTensor, SparseMatrixCSC}, Δt::Float64;\n            factorize_A::Bool = true)\n        M = constant(M)\n        if ismissing(Z1)\n            A = 1/Δt^2 * M\n            C = -1/Δt^2 * M \n        else\n            Z1 = constant(Z1)\n            A = (1/Δt^2 * M + 1/(2Δt) * Z1)\n            C = -(1/Δt^2 * M - 1/(2Δt) * Z1)\n        end\n        if isa(A, SparseTensor) && factorize_A\n            A = factorize(A)\n        end\n        if ismissing(Z2)\n            B = 2/Δt^2 * M\n        else\n            Z2 = constant(Z2)\n            B = (2/Δt^2 * M - Z2)\n        end\n        new(A, B, C)\n    end\nend \n\nfunction Base.:show(io::IO, en::ExplicitNewmark)\n    print(\"ExplicitNewmark(DOF=$(size(en.B, 1)))\")\nend\n\nfunction Base.:step(en::ExplicitNewmark, \n    d0::Union{Array{Float64, 1}, PyObject}, \n    d1::Union{Array{Float64, 1}, PyObject}, \n    f::Union{Array{Float64, 1}, PyObject})\n    d0, d1, f = convert_to_tensor([d0, d1, f], [Float64, Float64, Float64])\n    en.A \\ (en.B * d1 + en.C * d0 - f)\nend\n\n@doc raw\"\"\"\n    Newmark(M::Union{SparseTensor, PyObject, Array{Float64, 2}, SparseMatrixCSC}, \n                        C::Union{SparseTensor, PyObject, Array{Float64, 2}, SparseMatrixCSC}, \n                        K::Union{SparseTensor, PyObject, Array{Float64, 2}, SparseMatrixCSC}, \n                        Δt::Float64; β::Float64 = 1/4, γ::Float64 = 1/2, factorize_S::Bool = true)\n\nCreates a Newmark algorithm object. This function uses \"a-form\" implementation for \n\n$$M\\ddot \\mathbf{d} + C \\dot\\mathbf{d} + K \\mathbf{d} + f = 0$$\n\nThe numerical scheme is \n\n$$\\begin{aligned}\n\\tilde d_{n+1} &= d_n + \\Delta t v_n + \\Delta^2/2(1-2\\beta)a_n \\\\ \n\\tilde v_{n+1} &= v_n + (1-\\gamma)\\Delta a_n \\\\ \n(M+\\gamma\\Delta C+\\beta \\Delta^2 K)a_{n+1} &= F_{n+1} - C\\tilde v_{n+1} - K\\tilde d_{n+1}\\\\ \nd_{n+1} &= \\tilde d_{n+1} + \\beta \\Delta^2 a_{n+1}\\\\ \nv_{n+1} &= \\tilde v_{n+1} + \\gamma \\Delta ta_n\n\\end{aligned}$$\n\nFor unconditional stability\n$$2\\beta \\geq \\gamma \\geq \\frac12$$\n\nFor an explicit form, see [`ExplicitNewmark`](@ref), which corresponds to $\\beta = 0, \\gamma = \\frac12$. \n\nA common choice for Newmark algorithm is $\\beta = \\frac14, \\gamma = \\frac12$ (a.k.a., average acceleration, or \nTrapezoidal rule), which is unconditionally stable, \nhas second order of accuracy. \n\n!!! info \n    Internally, $M+\\gamma\\Delta C+\\beta \\Delta^2 K$ is represented by `S`. Users can elect to factorize $S$ (default $=$ true). \n\nTo perform time marching, use \n```\nstep(nm::Newmark, d::PyObject, v::PyObject, a::PyObject, \n        F::Union{Array{Float64, 1}, PyObject})\n```\n\"\"\"\nmutable struct Newmark\n    M::SparseTensor\n    C::SparseTensor\n    K::SparseTensor\n    S::Union{Tuple{SparseTensor, PyCall.PyObject}, SparseTensor}\n    β::Float64\n    γ::Float64\n    Δt::Float64\n    function Newmark(M::Union{SparseTensor, PyObject, Array{Float64, 2}, SparseMatrixCSC}, \n            C::Union{SparseTensor, PyObject, Array{Float64, 2}, SparseMatrixCSC}, \n            K::Union{SparseTensor, PyObject, Array{Float64, 2}, SparseMatrixCSC}, \n            Δt::Float64; β::Float64 = 1/4, γ::Float64 = 1/2, factorize_S::Bool = true)\n        M = SparseTensor(M)\n        C = SparseTensor(C)\n        K = SparseTensor(K)\n        S = M + γ*Δt*C + β*Δt^2*K\n        if factorize_S\n            S = factorize(S)\n        end\n        new(M, C, K, S, β, γ, Δt)\n    end\nend\n\nfunction Base.:show(io::IO, en::Newmark)\n    print(\"Newmark(DOF=$(size(en.S, 1)), γ=$(en.γ), β=$(en.β))\")\nend\n\n\nfunction Base.:step(nm::Newmark, d::PyObject, v::PyObject, a::PyObject, \n        F::Union{Array{Float64, 1}, PyObject})\n    β, γ, Δt = nm.β, nm.γ, nm.Δt\n    td = d + Δt * v + Δt^2/2*(1-2β)*a \n    tv = v + (1-γ)*Δt*a     \n    a_ = nm.S\\(-F - nm.C*tv - nm.K*td)\n    d_ = td + β*Δt^2*a_\n    v_ = tv + γ*Δt*a_\n    d_, v_, a_\nend", "meta": {"hexsha": "71fb5712ac57dcb29ec4e9107a857896e075ecb8", "size": 18062, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ode.jl", "max_stars_repo_name": "kailaix/ADCME.jl", "max_stars_repo_head_hexsha": "074c84443cfe89b66a1b8900a83d60f81d4fbc03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 202, "max_stars_repo_stars_event_min_datetime": "2019-06-12T18:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T16:56:46.000Z", "max_issues_repo_path": "src/ode.jl", "max_issues_repo_name": "kailaix/ADCME.jl", "max_issues_repo_head_hexsha": "074c84443cfe89b66a1b8900a83d60f81d4fbc03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2019-08-19T19:37:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T11:17:50.000Z", "max_forks_repo_path": "src/ode.jl", "max_forks_repo_name": "kailaix/ADCME.jl", "max_forks_repo_head_hexsha": "074c84443cfe89b66a1b8900a83d60f81d4fbc03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 56, "max_forks_repo_forks_event_min_datetime": "2019-07-30T05:50:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:41:07.000Z", "avg_line_length": 34.4694656489, "max_line_length": 284, "alphanum_fraction": 0.5733584321, "num_tokens": 6895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7950175741490718}}
{"text": "export combinations,\n       CoolLexCombinations,\n       multiset_combinations,\n       with_replacement_combinations,\n       powerset\n\n#The Combinations iterator\n\nstruct Combinations{T}\n    a::T\n    t::Int\nend\n\nfunction Base.iterate(c::Combinations, s = collect(1:c.t))\n    (!isempty(s) && s[1] > length(c.a) - c.t + 1) && return\n\n    comb = [c.a[si] for si in s]\n    if c.t == 0\n        # special case to generate 1 result for t==0\n        return (comb, [length(c.a)+2])\n    end\n    s = copy(s)\n    for i = length(s):-1:1\n        s[i] += 1\n        if s[i] > (length(c.a) - (length(s) - i))\n            continue\n        end\n        for j = i+1:lastindex(s)\n            s[j] = s[j-1]+1\n        end\n        break\n    end\n    (comb, s)\nend\n\nBase.length(c::Combinations) = binomial(length(c.a), c.t)\n\nBase.eltype(::Type{Combinations{T}}) where {T} = Vector{eltype(T)}\n\n\"\"\"\n    combinations(a, n)\n\nGenerate all combinations of `n` elements from an indexable object `a`. Because the number\nof combinations can be very large, this function returns an iterator object.\nUse `collect(combinations(a, n))` to get an array of all combinations.\n\"\"\"\nfunction combinations(a, t::Integer)\n    if t < 0\n        # generate 0 combinations for negative argument\n        t = length(a) + 1\n    end\n    Combinations(a, t)\nend\n\n\n\"\"\"\n    combinations(a)\n\nGenerate combinations of the elements of `a` of all orders. Chaining of order iterators\nis eager, but the sequence at each order is lazy.\n\"\"\"\ncombinations(a) = Iterators.flatten([combinations(a, k) for k = 1:length(a)])\n\n\n\n# cool-lex combinations iterator\n\n\"\"\"\n    CoolLexCombinations\n\nProduce ``(n,k)``-combinations in cool-lex order.\n\n# Reference\n\nRuskey, F., & Williams, A. (2009). The coolest way to generate combinations.\n*Discrete Mathematics*, 309(17), 5305-5320.\n\"\"\"\nstruct CoolLexCombinations\n    n::Int\n    t::Int\nend\n\nstruct CoolLexIterState{T<:Integer}\n    R0::T\n    R1::T\n    R2::T\n    R3::T\nend\n\nfunction Base.iterate(C::CoolLexCombinations)\n    if C.n < 0\n        throw(DomainError(C.n))\n    end\n    if C.t ≤ 0\n        throw(DomainError(C.t))\n    end\n\n    #What integer size should I use?\n    if C.n < 8sizeof(Int)\n        T = Int\n    else\n        T = BigInt\n    end\n\n    state = CoolLexIterState{T}(0, 0, T(1) << C.n, (T(1) << C.t) - 1)\n    iterate(C, state)\nend\n\nfunction Base.iterate(C::CoolLexCombinations, S::CoolLexIterState)\n    (S.R3 & S.R2 != 0) && return\n\n    R0 = S.R0\n    R1 = S.R1\n    R2 = S.R2\n    R3 = S.R3\n\n    R0 = R3 & (R3 + 1)\n    R1 = xor(R0, R0 - 1)\n    R0 = R1 + 1\n    R1 &= R3\n    R0 = max((R0 & R3) - 1, 0)\n    R3 += R1 - R0\n\n    _cool_lex_visit(S.R3), CoolLexIterState(R0, R1, R2, R3)\nend\n\n#Converts an integer bit pattern X into a subset\n#If X & 2^k == 1, then k is in the subset\nfunction _cool_lex_visit(X::Integer)\n    subset = Int[]\n    n = 1\n    while X != 0\n        X & 1 == 1 && push!(subset, n)\n        X >>= 1\n        n += 1\n    end\n    subset\nend\n\nBase.length(C::CoolLexCombinations) = max(0, binomial(C.n, C.t))\n\n\nstruct MultiSetCombinations{T}\n    m::T\n    f::Vector{Int}\n    t::Int\n    ref::Vector{Int}\nend\n\nBase.eltype(::Type{MultiSetCombinations{T}}) where {T} = Vector{eltype(T)}\n\nfunction Base.length(c::MultiSetCombinations)\n    t = c.t\n    if t > length(c.ref)\n        return 0\n    end\n    p = [1; zeros(Int, t)]\n    for i in 1:length(c.f)\n        f = c.f[i]\n        if i == 1\n            for j in 1:min(f, t)\n                p[j+1] = 1\n            end\n        else\n            for j in t:-1:1\n                p[j+1] = sum(p[max(1,j+1-f):(j+1)])\n            end\n        end\n    end\n    return p[t+1]\nend\n\nfunction multiset_combinations(m, f::Vector{<:Integer}, t::Integer)\n    length(m) == length(f) || error(\"Lengths of m and f are not the same.\")\n    ref = length(f) > 0 ? vcat([[i for j in 1:f[i] ] for i in 1:length(f)]...) : Int[]\n    if t < 0\n        t = length(ref) + 1\n    end\n    MultiSetCombinations(m, f, t, ref)\nend\n\n\"\"\"\n    multiset_combinations(a, t)\n\nGenerate all combinations of size `t` from an array `a` with possibly duplicated elements.\n\"\"\"\nfunction multiset_combinations(a, t::Integer)\n    m = unique(collect(a))\n    f = Int[sum([c == x for c in a]) for x in m]\n    multiset_combinations(m, f, t)\nend\n\nfunction Base.iterate(c::MultiSetCombinations, s = c.ref)\n    ((!isempty(s) && max(s[1], c.t) > length(c.ref)) || (isempty(s) && c.t > 0)) && return\n\n    ref = c.ref\n    n = length(ref)\n    t = c.t\n    changed = false\n    comb = [c.m[s[i]] for i in 1:t]\n    if t > 0\n        s = copy(s)\n        for i in t:-1:1\n            if s[i] < ref[i + (n - t)]\n                j = 1\n                while ref[j] <= s[i]\n                    j += 1\n                end\n                s[i] = ref[j]\n                for l in (i+1):t\n                    s[l] = ref[j+=1]\n                end\n                changed = true\n                break\n            end\n        end\n        !changed && (s[1] = n+1)\n    else\n        s = [n+1]\n    end\n    (comb, s)\nend\n\nstruct WithReplacementCombinations{T}\n    a::T\n    t::Int\nend\n\nBase.eltype(::Type{WithReplacementCombinations{T}}) where {T} = Vector{eltype(T)}\n\nBase.length(c::WithReplacementCombinations) = binomial(length(c.a) + c.t - 1, c.t)\n\n\"\"\"\n    with_replacement_combinations(a, t)\n\nGenerate all combinations with replacement of size `t` from an array `a`.\n\"\"\"\nwith_replacement_combinations(a, t::Integer) = WithReplacementCombinations(a, t)\n\nfunction Base.iterate(c::WithReplacementCombinations, s = [1 for i in 1:c.t])\n    (!isempty(s) && s[1] > length(c.a) || c.t < 0) && return\n\n    n = length(c.a)\n    t = c.t\n    comb = [c.a[si] for si in s]\n    if t > 0\n        s = copy(s)\n        changed = false\n        for i in t:-1:1\n            if s[i] < n\n                s[i] += 1\n                for j in (i+1):t\n                    s[j] = s[i]\n                end\n                changed = true\n                break\n            end\n        end\n        !changed && (s[1] = n+1)\n    else\n        s = [n+1]\n    end\n    (comb, s)\nend\n\n## Power set\n\n\"\"\"\n    powerset(a, min=0, max=length(a))\n\nGenerate all subsets of an indexable object `a` including the empty set, with cardinality\nbounded by `min` and `max`. Because the number of subsets can be very large, this function\nreturns an iterator object. Use `collect(powerset(a, min, max))` to get an array of all\nsubsets.\n\"\"\"\nfunction powerset(a, min::Integer=0, max::Integer=length(a))\n    itrs = [combinations(a, k) for k = min:max]\n    min < 1 && append!(itrs, eltype(a)[])\n    Iterators.flatten(itrs)\nend\n", "meta": {"hexsha": "bc8898df9bca0b396045f75b3292c896aa39f827", "size": 6501, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/combinations.jl", "max_stars_repo_name": "mschauer/Combinatorics.jl", "max_stars_repo_head_hexsha": "0e0edc6b204f3cbd726074a9d3f8d4288b3ab16b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/combinations.jl", "max_issues_repo_name": "mschauer/Combinatorics.jl", "max_issues_repo_head_hexsha": "0e0edc6b204f3cbd726074a9d3f8d4288b3ab16b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/combinations.jl", "max_forks_repo_name": "mschauer/Combinatorics.jl", "max_forks_repo_head_hexsha": "0e0edc6b204f3cbd726074a9d3f8d4288b3ab16b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1352313167, "max_line_length": 90, "alphanum_fraction": 0.5531456699, "num_tokens": 2056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346504434783, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7950175680216355}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.18\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ ceff6126-51fc-11eb-3cf5-dd30d637e267\nbegin\n\tusing Dates \n\tusing MortalityTables \n\tusing DifferentialEquations \n\tusing Plots \n\tusing ActuaryUtilities\nend\n\n# ╔═╡ cd5e7080-5348-11eb-2c22-455a3556cab0\nmd\"\n# Universal Life Policy Account Mechanics as a Differential Equation\n\"\n\n# ╔═╡ de0ace1a-5348-11eb-35c9-5f0ff4009d97\nmd\"\"\"\n## Introduction\n\nThis demonstrates an example of defining an universal life policy value roll like a discrete differential equation. \n\nIt then uses the [SciML DifferentialEquations](https://sciml.ai/) package to \"solve\" the policy projection given a single point, but also to see how the policy projection behaves under different premium and interest rate conditions./\n\"\"\"\n\n# ╔═╡ ef26ffb6-5348-11eb-04a8-c5cbfdcab72a\nmd\"\"\"\nLet's use the 2001 CSO table as the basis for cost of insurance charges:\n\"\"\"\n\n# ╔═╡ 45dab59c-528d-11eb-357d-af3664466910\nbegin\n\ttables = MortalityTables.tables()\n\tcso = tables[\"2001 CSO Super Preferred Select and Ultimate - Male Nonsmoker, ANB\"]\nend\n\n# ╔═╡ ffe9b6e0-5348-11eb-2d38-a5613eb24383\nmd\"\"\"\nNext, policy mechanics are coded. It's essentially a discrete differential equation, so it leverages [`DifferentialEquations.jl`](https://diffeq.sciml.ai/dev/)\n\nThe projection is coded in the [Discrete DifferentialEquation format](https://diffeq.sciml.ai/dev/types/discrete_types/):\n\n``u_{n+1} = f(u,p,t_{n+1})``\n\nIn the code below, this translates to:\n\n- `u` is the *state* of the system. We  will track three variables to represent the `state`:\n   - `state[1]` is the account value\n   - `state[2]` is the premium paid\n   - `state[3]` is the policy duration\n- `p` are the parameters of the system.\n- `t` is the time, which will represent days since policy issuance\n\"\"\"\n\n# ╔═╡ da199644-51fc-11eb-0aab-dd68b1fcddc6\nfunction policy_projection(state,p,t)\n    # grab the state from the inputs\n    av = state[1] \n    \n    # calculated variables\n    cur_date = p.issue_date + Day(t)\n    dur = duration(p.issue_date,cur_date)\n    att_age = p.issue_age + dur - 1\n\t\n\t# lapse if AV <= 0 \n    lapsed = (av <= 0.0 ) & (t > 1) \n    \n    if !lapsed \n\n        monthly_coi_rate = (1 - (1-p.mort_assump[att_age]) ^ (1/12))\n\n\t\t## Periodic Policy elements\n\t\t\n        # annual events\n        if Dates.monthday(cur_date) == Dates.monthday(p.issue_date) || \n\t\t\tcur_date ==p.issue_date + Day(1) # OR first issue date\n\t\t\t\n            premium = p.annual_prem\n        else\n            premium = 0.0\n        end\n\n        # monthly_events\n        if Dates.day(cur_date) == Dates.day(p.issue_date)\n            coi = max((p.face - av) * monthly_coi_rate,0.0)\n        else\n            coi = 0.0\n        end\n\n        # daily events\n        int(av) = av * ((1 + p.int_rate) ^ (1 / 360) - 1.0)\n\n\n        \n        # av\n        new_av = max(0.0,av - coi + premium + int(av-coi)) \n\t\n\t\t\t\t# new state\n\t\treturn [new_av, premium, dur] # AV, Prem, Dur\n        \n    else\n\t\t# new state\n\t\treturn [0.0, 0.0, dur] # AV, Prem, Dur\n        \n    end\n\t\n    \nend\n\n# ╔═╡ 8a227236-5349-11eb-353d-1d3f94a968d0\nmd\"The following function will create a named tuple of parameters given a varying `prem` (premium) and `int` (credit rate).\"\n\n# ╔═╡ 956811e4-5349-11eb-2b34-b5441def32a1\nparams(prem,int) = (\n    int_rate = int,\n    issue_date = Date(2010,1,1),\n    face = 1e6,\n    issue_age = 25,\n    mort_assump = tables[\"2001 CSO Super Preferred Select and Ultimate - Male Nonsmoker, ANB\"].ultimate,\n    projection_years = 75,\n    annual_prem = prem,\n)\n\n# ╔═╡ 9ee35710-5349-11eb-0d45-23bc292d8a3d\nmd\"\"\"\n## Runing the system\n\nThis results in the following plot. The tracked output variables u1 and u2 represent the two vars that we tracked above: account value and cumulative premium.\n\"\"\"\n\n# ╔═╡ b65ef28c-5349-11eb-1baa-6575ad7fb946\nbegin\n\tp = params(\n\t        8000.0, # 8,000 annual premium\n\t        0.08    # 8% interest\n\t        ) \n\t\n\t# calculate the number of days to project\n\tprojection_end_date = p.issue_date + Year(p.projection_years) \n\tdays_to_project = Dates.value(projection_end_date - p.issue_date)\n\t        \n\t# the [0.0,..] are the initial conditions for the tracked variables\n\t prob = DiscreteProblem(policy_projection,[0.0,0.0,0],(0,days_to_project),p)\n\t proj = solve(prob,FunctionMap())\n\t\n\t plot(proj)\nend\n\n# ╔═╡ c4637664-5349-11eb-0e81-59e39974f02e\nmd\"\"\"\n## Moving up the ladder of abstraction\n\nAn excellent way to understand the behavior of a model is to [move up the ladder of abstraction](http://worrydream.com/LadderOfAbstraction/). Below, we will see what happens to the projection at varying levels of credit rates and annual premiums.\n\"\"\"\n\n# ╔═╡ 02cc352a-5409-11eb-0fda-336d5fa42fa9\nbegin\n\tprem_range = 1000.0:100.0:9000.0\n\tint_range = 0.02:0.0025:0.08\n\t\n\tfunction ending_av(ann_prem,int,days_to_project)\n\t    p = params(ann_prem,int)\n\t    prob = DiscreteProblem(policy_projection,[0.0,0.0,0],(0,days_to_project),p)\n\t    proj = solve(prob,FunctionMap())\n\t    end_av = proj[end][1] \n\t    if end_av == 0.0\n\t        lapse_time = findfirst(isequal(0.0),proj[1,2:end])\n\t    else\n\t        lapse_time = length(proj)\n\t    end\n\t    duration = proj[3,lapse_time]\n\t    end_age = p.issue_age + duration - 1.0\n\t    \n\t    return end_av,end_age\n\t    \n\tend\n\t\n\tend_age = zeros(length(prem_range),length(int_range))\n\tend_av = zeros(length(prem_range),length(int_range))\n\t\n\t# loop through each projection we did and fill our ranges with the ending AV and ending age\n\tfor (i,vp) in enumerate(prem_range)\n\t    for (j,vi) in enumerate(int_range)\n\t        (end_av[i,j],end_age[i,j]) = ending_av(vp,vi,days_to_project)\n\t    end\n\tend\nend\n\n# ╔═╡ 280d25a6-5409-11eb-17d9-674f218f4351\nbegin\n\tusing ColorSchemes # for Turbo colors, which emphasize readability\n\t\n\tviz = plot(layout=2) # side by side plot\n\t\n\t# \n\tcontour!(viz[1],int_range,\n\t    prem_range,\n\t    end_av ./ 1e6, # scale to millions for readability\n\t\n\t    contour_labels=true,\n\t    c=cgrad(ColorSchemes.turbo.colors),\n\t    fill=true,\n\t    title=\"AV at age 100 (\\$M)\",\n\t    ylabel=\"Annual Premium (\\$)\",\n\t    \n\t\n\t)\n\t\n\tcontour!(viz[2],int_range,\n\t    prem_range,\n\t    end_age, \n\t\n\t    contour_labels=true,\n\t    c=cgrad(ColorSchemes.turbo.colors),\n\t    fill=true,\n\t    yaxis=false,\n\t    title=\"Age at Lapse\",\n\t)\n\t\n\tannotate!(viz[2],0.055,7000,Plots.text(\"Doesn't lapse \\nbefore age 100\", 8, :white, :center))\n\t\nend\n\n# ╔═╡ 21e53f60-5409-11eb-291d-d903da8e16b4\nmd\"\nNow let's plot the result. Not surprising, interest has a huge effect on the policy projection. Premium is also a major influence.\n\nOne thing that's remarkable is how going from 2000 premium to just ~2200 of premium results in about a $5m difference at 8% interest. The power of compound interest!\n\"\n\n# ╔═╡ 684f7efc-5409-11eb-0757-19b40c5d418e\nmd\"\n## Conclusion\n\nThis shows how universal life mechanics are a dynamic system. the growth/decay is governed by two competing feedback loops:\n\n- Growth: the force of interest lets the balance grow exponentially over long periods of time\n\n- Decay: low balances increase the net amount at risk and the resulting COI charges.\n\n\"\n\n# ╔═╡ 7e80faf0-5409-11eb-33f6-4f6be6fea835\nmd\" \n## Endnotes\n\nThis is not meant to represent any particular insurance product, nor fully replicate typical account mechanics.\n\"\n\n# ╔═╡ Cell order:\n# ╟─cd5e7080-5348-11eb-2c22-455a3556cab0\n# ╟─de0ace1a-5348-11eb-35c9-5f0ff4009d97\n# ╠═ceff6126-51fc-11eb-3cf5-dd30d637e267\n# ╟─ef26ffb6-5348-11eb-04a8-c5cbfdcab72a\n# ╠═45dab59c-528d-11eb-357d-af3664466910\n# ╟─ffe9b6e0-5348-11eb-2d38-a5613eb24383\n# ╠═da199644-51fc-11eb-0aab-dd68b1fcddc6\n# ╟─8a227236-5349-11eb-353d-1d3f94a968d0\n# ╠═956811e4-5349-11eb-2b34-b5441def32a1\n# ╟─9ee35710-5349-11eb-0d45-23bc292d8a3d\n# ╠═b65ef28c-5349-11eb-1baa-6575ad7fb946\n# ╟─c4637664-5349-11eb-0e81-59e39974f02e\n# ╠═02cc352a-5409-11eb-0fda-336d5fa42fa9\n# ╟─21e53f60-5409-11eb-291d-d903da8e16b4\n# ╠═280d25a6-5409-11eb-17d9-674f218f4351\n# ╟─684f7efc-5409-11eb-0757-19b40c5d418e\n# ╟─7e80faf0-5409-11eb-33f6-4f6be6fea835\n", "meta": {"hexsha": "a86b44bb7c79c55bc0c288bf679e0294bcbee96b", "size": 7948, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "DiffEq.jl", "max_stars_repo_name": "EarthGoddessDude/Learn", "max_stars_repo_head_hexsha": "cb504f6a0a9654365caa09a38d7d8e6ab6decc47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DiffEq.jl", "max_issues_repo_name": "EarthGoddessDude/Learn", "max_issues_repo_head_hexsha": "cb504f6a0a9654365caa09a38d7d8e6ab6decc47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DiffEq.jl", "max_forks_repo_name": "EarthGoddessDude/Learn", "max_forks_repo_head_hexsha": "cb504f6a0a9654365caa09a38d7d8e6ab6decc47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2205882353, "max_line_length": 246, "alphanum_fraction": 0.6911172622, "num_tokens": 2739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7950175624441177}}
{"text": "using Cubature\nusing Distributions\n\n\"\"\"\nDemo of robust Bayesian analysis, from Berger 1984\n\"\"\"\nfunction robustPriorDemo()\n    x = 5\n    obsVar = 1\n    \n    # First let us verify that the Gaussian prior indeed satisfies the prior quartiles\n    priorMu = 0\n    priorVar = 2.19\n    \n    nprior = Normal(priorMu, sqrt(priorVar))\n    @assert isapprox(cdf(nprior, -1), .25; atol=.001)\n    @assert isapprox(cdf(nprior, 0) - cdf(nprior, -1), .25; atol=.001)\n    @assert isapprox(cdf(nprior, 1) - cdf(nprior, 0), .25; atol=.001)\n    @assert isapprox(1-cdf(nprior, 1), .25; atol=.001)\n    @assert isapprox(median(nprior), 0; atol=.001)\n    \n    # Now compute posterior mean using Gaussian prior\n    postVar = 1/(1/obsVar + 1/priorVar)\n    postMeanNormal = postVar*(priorMu/priorVar + x/obsVar)\n    @assert isapprox(postMeanNormal, 3.43; atol=.01)\n    \n    # Now let us do the same thing for the Cauchy\n    cprior = Cauchy(0, 1)\n    @assert isapprox(cdf(cprior, -1), .25; atol=.001)\n    @assert isapprox(cdf(cprior, 0) - cdf(cprior, -1), .25; atol=.001)\n    @assert isapprox(cdf(cprior, 1) - cdf(cprior, 0), .25; atol=.001)\n    @assert isapprox(1-cdf(cprior, 1), .25; atol=.001)\n    @assert isapprox(median(cprior), 0; atol=.001)\n    \n    # Now let us compute posterior mean using Cauchy\n    \n    lik(θ) = pdf(Normal(θ, sqrt(obsVar)), x)\n    prior(θ) = pdf(cprior, θ)\n    post(θ) = lik(θ).*prior(θ)\n    \n    ∞=10\n    \n    Z, err = hquadrature(post, -∞, ∞; reltol=1e-4)\n    \n    f(θ) = θ.*post(θ)/Z\n    \n    postMeanCauchy, err = hquadrature(f, -∞, ∞; reltol=1e-4)\n    @assert isapprox(postMeanCauchy, 4.56; atol=.01)\n    \n    (postMeanNormal, postMeanCauchy)\nend\n\n", "meta": {"hexsha": "3220fef7a1422b0f821cf77005079ad19c805b79", "size": 1653, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BayesianStatistics/robustPriorDemo.jl", "max_stars_repo_name": "aoboturov/PMTK4BookDemos.jl", "max_stars_repo_head_hexsha": "f44853081139b358e0e9a2bb36a3d35ac35dcb39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-25T15:50:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-25T15:50:42.000Z", "max_issues_repo_path": "src/BayesianStatistics/robustPriorDemo.jl", "max_issues_repo_name": "aoboturov/PMTK4BookDemos.jl", "max_issues_repo_head_hexsha": "f44853081139b358e0e9a2bb36a3d35ac35dcb39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BayesianStatistics/robustPriorDemo.jl", "max_forks_repo_name": "aoboturov/PMTK4BookDemos.jl", "max_forks_repo_head_hexsha": "f44853081139b358e0e9a2bb36a3d35ac35dcb39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1886792453, "max_line_length": 86, "alphanum_fraction": 0.6231094979, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182847, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.7949634203290407}}
{"text": "function solve_poisson_pcg( Lmat::SparseMatrixCSC{Float64,Int64},\n                            prec::SparseMatrixCSC{Float64,Int64},\n                            rho::Array{Float64,1}, NiterMax::Int64;\n                            verbose=false, TOL=5.e-10 )\n  #\n  Npoints = size(rho)[1]\n  phi = zeros( Float64, Npoints ) # XXX or use some starting guess\n  #\n  r = zeros( Float64, Npoints )\n  p = zeros( Float64, Npoints )\n  z = zeros( Float64, Npoints )\n  #\n  nabla2_phi = Lmat*phi\n  r = rho - nabla2_phi\n  z = apply_prec_ilu0( prec, r)\n  p = copy(z)\n\n  rsold = dot( r, z )\n\n  for iter = 1 : NiterMax\n    #\n    nabla2_phi = Lmat*p\n    #\n    alpha = rsold/dot( p, nabla2_phi )\n    #\n    phi = phi + alpha * p\n    r = r - alpha * nabla2_phi\n    z = apply_prec_ilu0( prec, r)\n    #\n    rsnew = dot( z, r )\n    deltars = rsold - rsnew\n    #println(typeof(rsnew))\n    #println(rsnew)\n    if verbose\n      @printf(\"%8d %18.10e\\n\", iter, sqrt(abs(rsnew)))\n    end\n    #\n    if sqrt(abs(rsnew)) < TOL\n      if verbose\n        @printf(\"Convergence achieved in solve_poison_pcg: N, iter: %d %d\\n\", Npoints, iter)\n      end\n      break\n    end\n    #\n    p = z + (rsnew/rsold) * p\n    #\n    rsold = rsnew\n  end\n  #\n  return phi\n  #\nend # of function\n", "meta": {"hexsha": "ab9957bee36aa9612b58d9b40a2cd790f0182450", "size": 1236, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LF/poisson_3d_p/solve_poisson_pcg.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "LF/poisson_3d_p/solve_poisson_pcg.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LF/poisson_3d_p/solve_poisson_pcg.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 23.320754717, "max_line_length": 92, "alphanum_fraction": 0.5469255663, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182844, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.794963410456958}}
{"text": "function besselj(m, x)\n    sn = 0\n    an = 1/factorial(m)\n    k = 0\n    \n    while abs(an) > eps()\n        sn += an\n        an = -an * x * x/4/(k+1)/(k+m+1)\n        k += 1\n    end\n\n    sn *= (x/2)^m\n    return sn\nend\n\nfunction besselj_plots()\n    x = 0:0.02:20\n    y1, y2, y3, y4, y5, y6 =[], [], [], [], [], []\n    \n    for i in x\n        push!(y1, besselj(0, i))\n        push!(y2, besselj(1, i))\n        push!(y3, besselj(2, i))\n        push!(y4, besselj(3, i))\n        push!(y5, besselj(4, i))\n        push!(y6, besselj(5, i))\n    end\n\n    p = plot(x, y1)\n    plot!(p, x, y2)\n    plot!(p, x, y3)\n    plot!(p, x, y4)\n    plot!(p, x, y5)\n    plot!(p, x, y6)\n    display(p)\nend", "meta": {"hexsha": "ee494362a57f3493b9c49f1024e6e8dcb8b62c19", "size": 677, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "task_9_5.jl", "max_stars_repo_name": "Litger45/julia-algorithms-2", "max_stars_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "task_9_5.jl", "max_issues_repo_name": "Litger45/julia-algorithms-2", "max_issues_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "task_9_5.jl", "max_forks_repo_name": "Litger45/julia-algorithms-2", "max_forks_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8055555556, "max_line_length": 50, "alphanum_fraction": 0.4194977843, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338090839606, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7949113403674094}}
{"text": "\"\"\"\n    dct2!(a, fft_type::FFTType=Radix2Type())\n\nDiscrete cosine transform of type II\n\nY = DCT2(X) returns the discrete cosine transform of X,\nbased on the staggered-grid definition\n           N\n   Y(k) =  ∑  X(j) cos (π*(k-1)*(j-1/2)/N)\n          j=1\nThe vector Y is the same size as X and contains the\ndiscrete cosine transform coefficients.\n\nY = DCT2(X,N) pads or truncates the vector X to length N\nbefore transforming.\n\nIf X is a matrix, the DCT2 operation is applied to each\ncolumn. This transform can be inverted using IDCT2.\n\nVerified correct within machine precision for 2D array input 2/28/2021\n\nTraditional dct2:\n          N-1\n   Y(k) =  ∑  X(j) cos (π*(j+1/2)*k/N)\n          j=0\n\n\"\"\"\nfunction dct2!(x, fft_type=Radix2Type())\n    x .= dct2(x, fft_type)\nend\nfunction dct2(a, fft_type::FFTType=Radix2Type())\n    FT = eltype(a)\n    if min(size(a)...)==1\n        if size(a,2)>1\n            do_trans = true;\n        else\n            do_trans = false;\n        end\n        a = a[:];\n    else\n        do_trans = false;\n    end\n    n = size(a,1);\n    m = size(a,2);\n    # Pad or truncate a if necessary\n    if size(a,1)<n\n      aa = zeros(n,m);\n      aa[1:size(a,1),:] = a;\n    else\n      aa = a[1:n,:];\n    end\n    y = zeros(2*n, m);\n    y[1:n,:] .= aa;\n    i = Complex(0,1);\n    e = 0.5 * exp.(-i*FT(0.5) * π * (0:n-1) ./ n);\n    y[n+1:2*n,:] .= reverse(aa[1:n,:]; dims=1);\n    yy = fft(y, 1);\n    b = zeros(n,m);\n    for l = 1:m\n        b[1:n,l] .= real.(yy[1:n,l] .* e);\n    end\n    if isreal(a)\n        b = real.(b);\n    end\n    if do_trans\n        b = b'\n    end\n    return b\nend\n", "meta": {"hexsha": "92bddaf69c515d87be16d8101d8e6f319daf51a3", "size": 1588, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FFTs/dct.jl", "max_stars_repo_name": "charleskawczynski/MOONS.jl", "max_stars_repo_head_hexsha": "a88311ce88b665289e9780a65dceef76529f2d94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-26T22:31:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T22:31:50.000Z", "max_issues_repo_path": "src/FFTs/dct.jl", "max_issues_repo_name": "charleskawczynski/MOONS.jl", "max_issues_repo_head_hexsha": "a88311ce88b665289e9780a65dceef76529f2d94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2020-12-30T19:19:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-28T15:26:15.000Z", "max_forks_repo_path": "src/FFTs/dct.jl", "max_forks_repo_name": "charleskawczynski/MOONS.jl", "max_forks_repo_head_hexsha": "a88311ce88b665289e9780a65dceef76529f2d94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6857142857, "max_line_length": 70, "alphanum_fraction": 0.5371536524, "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8723473663814338, "lm_q1q2_score": 0.7948652224330597}}
{"text": "\"\"\"\n# Divide-and-conquer algorithms\n\n- Multiplication\n- Recurrence relations\n    - Master theorem\n    - Binary search\n- Mergesort\n    - An n log n lower bound for sorting\n- Medians\n    - A randomized divide-and-conquer algorithm for selection\n    - Efficiency analysis\n    - The Unix sort command\n- Matrix multiplication\n- The fast Fourier transform\n    - Why multiply polynomials?\n    - An alternative representation of polynomials\n    - Evaluation by divide-and-conquer\n    - Interpolation\n    - A matrix reformulation\n    - Interpolation resolved\n    - Inversion formula\n    - A closer look at the fast Fourier transform\n    - The definitive FFT algorithm\n    - The fast Fourier transform unraveled\n    - The slow spread of a fast algorithm\n\"\"\"\nmodule Chapter2\n\nexport\n    karatsuba,\n    karatsuba2,\n    mergesort,\n    iterativemergesort,\n    polynomialmultiplication\n\n\"\"\"\n    karatsuba(x, y)\n\nUsing the Karatsuba algorithm, compute the product of two integers `x` and `y`.\n\n# Examples\n\n```jldoctest\njulia> karatsuba(2412, 3231)\n7793172\n```\n\"\"\"\nfunction karatsuba(x::Int, y::Int)\n    if ndigits(x) == 1 || ndigits(x) == 1\n        return x * y\n    end\n\n    n = max(ndigits(x), ndigits(y))\n    m = n ÷ 2\n\n    xL, xR = x ÷ 10^m, x % 10^m\n    yL, yR = y ÷ 10^m, y % 10^m\n\n    P1 = karatsuba(xL, yL)\n    P2 = karatsuba(xR, yR)\n    P3 = karatsuba((xL + xR), (yL + yR))\n\n    return (P1 * 10^(2m)) + ((P3 - P1 - P2) * 10^m) + P2\nend\n\n\"\"\"\n    karatsuba2(x, y)\n\nUsing the Karatsuba algorithm, compute the product of two integers `x` and `y`.\n\n# Examples\n\n```jldoctest\njulia> karatsuba(2412, 3231)\n7793172\n```\n\"\"\"\nfunction karatsuba2(x::Int, y::Int)\n    if ndigits(x, base=2) == 1 || ndigits(y, base=2) == 1\n        return x * y\n    end\n\n    n = max(ndigits(x, base=2), ndigits(y, base=2))\n    m = n ÷ 2\n\n    xL, xR = x ÷ 2^m, x % 2^m\n    yL, yR = y ÷ 2^m, y % 2^m\n\n    P1 = karatsuba(xL, yL)\n    P2 = karatsuba(xR, yR)\n    P3 = karatsuba((xL + xR), (yL + yR))\n\n    return (P1 * 2^n) + ((P3 - P1 - P2) * 2^m) + P2\nend\n\n\"\"\"\n    mergesort(a)\n\nSort an array of numbers `a` using the merge sort algorithm.\n\n# Examples\n\n```jldoctest\njulia> mergesort([10, 2, 5, 3, 7, 13, 1, 6])\n8-element Vector{Int64}:\n  1\n  2\n  3\n  5\n  6\n  7\n 10\n 13\n\njulia> mergesort([1, 4.54312, 3.4321, π])\n4-element Vector{Float64}:\n 1.0\n 3.141592653589793\n 3.4321\n 4.54312\n```\n\"\"\"\nfunction mergesort(a::AbstractVector)\n    if length(a) > 1\n        m = length(a) ÷ 2\n        return merge(mergesort(a[1:m]), mergesort(a[(m + 1):end]))\n    else\n        return a\n    end\nend\n\nfunction merge(x::AbstractVector, y::AbstractVector)\n    if length(x) == 0\n        return y\n    end\n    if length(y) == 0\n        return x\n    end\n    if x[1] <= y[1]\n        return pushfirst!(merge(x[2:end], y), x[1])\n    else\n        return pushfirst!(merge(x, y[2:end]), y[1])\n    end\nend\n\nfunction iterativemergesort(a::AbstractVector)\n    Q = []\n    for i ∈ 1:length(a)\n        push!(Q, [a[i]])\n    end\n    while length(Q) > 1\n        push!(Q, merge(eject(Q), eject(Q)))\n    end\n    return eject(Q)\nend\n\nfunction polynomialmultiplication(A::AbstractVector{T}, B::AbstractVector{T}) where {T <: Real}\n    product = zeros(length(A) + length(B))\n\n    for i ∈ 1:length(A)\n        for j ∈ 1:length(B)\n            product[i + j] += A[i] * B[j]\n        end\n    end\n\n    return product\nend\n\n# TODO: FFT\n# function FFT(A, ω)\n#\n# end\n\nend # module\n", "meta": {"hexsha": "bdad8794d0ff6a9eae5b8d249f7d030ce31173ec", "size": 3375, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter2.jl", "max_stars_repo_name": "airicbear/CIS3223", "max_stars_repo_head_hexsha": "8769e6b74021e1285114753b49bd6e8e6b822dd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/chapter2.jl", "max_issues_repo_name": "airicbear/CIS3223", "max_issues_repo_head_hexsha": "8769e6b74021e1285114753b49bd6e8e6b822dd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chapter2.jl", "max_forks_repo_name": "airicbear/CIS3223", "max_forks_repo_head_hexsha": "8769e6b74021e1285114753b49bd6e8e6b822dd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1761363636, "max_line_length": 95, "alphanum_fraction": 0.5943703704, "num_tokens": 1191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121366457407, "lm_q2_score": 0.8840392878563335, "lm_q1q2_score": 0.7948586124994196}}
{"text": "\"\"\"\n    maxwell_boltzmann(f)\n\nMaxwell Boltzmann entropy\n\"\"\"\nmaxwell_boltzmann(f) = f * log(f) - f\n\n\n\"\"\"\n    maxwell_boltzmann_prime(x)\n\nPrim of Maxwell Boltzmann entropy\n\"\"\"\nmaxwell_boltzmann_prime(x) = log(x)\n\n\n\"\"\"\n    maxwell_boltzmann_dual(f)\n\nDual of Maxwell Boltzmann entropy\n\"\"\"\nmaxwell_boltzmann_dual(f) = exp(f)\n\n\n\"\"\"\n    maxwell_boltzmann_dual_prime(f)\n\nDual prim of Maxwell Boltzmann entropy\n\"\"\"\nmaxwell_boltzmann_dual_prime(f) = exp(f)\n\n\n\"\"\"\n    kinetic_entropy(α, m, weights)\n\nReconstruct mathematical entropy from Legendre dual\n\"\"\"\nfunction kinetic_entropy(α::AbstractArray, m::AbstractArray, weights::AbstractVector)\n    B = KitBase.maxwell_boltzmann_dual_prime.(α' * m)[:]\n    return sum(maxwell_boltzmann.(B) .* weights)\nend\n", "meta": {"hexsha": "8d12aa2f83690c0a489f1dfd2508b4aa12ed2727", "size": 741, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Math/math_entropy.jl", "max_stars_repo_name": "vavrines/KitBase.jl", "max_stars_repo_head_hexsha": "c7b835e8151828c4065691c9882e42335a237ec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-12-02T13:59:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T00:49:20.000Z", "max_issues_repo_path": "src/Math/math_entropy.jl", "max_issues_repo_name": "vavrines/KitBase.jl", "max_issues_repo_head_hexsha": "c7b835e8151828c4065691c9882e42335a237ec1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2020-12-02T21:20:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T00:35:04.000Z", "max_forks_repo_path": "src/Math/math_entropy.jl", "max_forks_repo_name": "vavrines/KitBase.jl", "max_forks_repo_head_hexsha": "c7b835e8151828c4065691c9882e42335a237ec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-07T17:11:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T21:13:25.000Z", "avg_line_length": 17.6428571429, "max_line_length": 85, "alphanum_fraction": 0.7246963563, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.8418256452674009, "lm_q1q2_score": 0.7948322921385708}}
{"text": "# Example 0: Solve 1D Burgers Equation\n# u(x,t)_t+(0.5*u²(x,t))_{x}=0\n# u(0,x) = f0(x)\n\nusing ConservationLawsDiffEq\nusing OrdinaryDiffEq\nusing LinearAlgebra\n\nconst CFL = 0.5\n# First define the problem data (Jacobian is optional but useful)\nJf(u) = u           #Jacobian\nf(u) = u^2/2        #Flux function\nf0(x) = sin(2*π*x)  #Initial data distribution\n\n# Now discretizate the domain\nmesh = Uniform1DFVMesh(10, [0.0, 1.0])\n\n# Now get a explicit semidiscretization (discrete in space) du_h(t)/dt = f_h(u_h(t))\nf_h = getSemiDiscretization(f,LaxFriedrichsScheme(),mesh,[Periodic()]; Df = Jf, use_threads = false,numvars = 1)\n\n#Compute discrete initial data\nu0 = getInitialState(mesh,f0,use_threads = true)\n\n#Setup ODE problem for a time interval = [0.0,1.0]\node_prob = ODEProblem(f_h,u0,(0.0,1.0))\n\n#Setup callback in order to fix CFL constant value\ncb = getCFLCallback(f_h, CFL)\n\n#Estimate an initial dt\ndt = update_dt!(u0, f_h, CFL)\n\n#Solve problem using OrdinaryDiffEq\nsol = solve(ode_prob,SSPRK22(); dt = dt, callback = cb)\n\n#Plot solution\n#Wrap solution so we can plot using dispatch\nu_h = fv_solution(sol, mesh)\n\nusing Plots\nplot(u_h,tidx = 1,lab=\"uo\",line=(:dot,2)) #Plot inital data\nplot!(u_h,lab=\"LF\")                       #Plot LaxFriedrichsScheme solution\n", "meta": {"hexsha": "c74b565398199b2ba8adb88fc905d199af9757af", "size": 1265, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/0_Burgers1D.jl", "max_stars_repo_name": "Paulms/ConservationLawsDiffEq.jl", "max_stars_repo_head_hexsha": "9b7e5f13865a65a0d77614eae508044d0528c9a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-07-10T00:00:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T15:45:29.000Z", "max_issues_repo_path": "examples/0_Burgers1D.jl", "max_issues_repo_name": "jamesamiller/ConservationLawsDiffEq.jl", "max_issues_repo_head_hexsha": "9b7e5f13865a65a0d77614eae508044d0528c9a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2018-06-01T15:01:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T08:08:21.000Z", "max_forks_repo_path": "examples/0_Burgers1D.jl", "max_forks_repo_name": "jamesamiller/ConservationLawsDiffEq.jl", "max_forks_repo_head_hexsha": "9b7e5f13865a65a0d77614eae508044d0528c9a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-08-02T13:11:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T22:21:30.000Z", "avg_line_length": 29.4186046512, "max_line_length": 112, "alphanum_fraction": 0.7019762846, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7948320467064779}}
{"text": "function hilb(n::Int)\n# Function generates the Hilbert matrix  A of size n,\n#  A (i, j) = 1 / (i + j - 1)\n# Inputs:\n#\tn: size of matrix A, n>=1\n#\n#\n# Usage: hilb(10)\n#\n# Pawel Zielinski\n        if n < 1\n         error(\"size n should be >= 1\")\n        end\n        return [1 / (i + j - 1) for i in 1:n, j in 1:n]\nend\n", "meta": {"hexsha": "9ee304458731245a0914ab7b1e2c9593fb7bb118", "size": 315, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5th-semester/on/lab/lista-2/hilb.jl", "max_stars_repo_name": "jerry-sky/academic-notebook", "max_stars_repo_head_hexsha": "be2d350289441b99168ea40412891bc65b9cb431", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-28T21:53:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T19:24:47.000Z", "max_issues_repo_path": "5th-semester/on/lab/lista-2/hilb.jl", "max_issues_repo_name": "jerry-sky/academic-notebook", "max_issues_repo_head_hexsha": "be2d350289441b99168ea40412891bc65b9cb431", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-02-13T18:07:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T18:16:07.000Z", "max_forks_repo_path": "5th-semester/on/lab/lista-2/hilb.jl", "max_forks_repo_name": "jerry-sky/academic-notebook", "max_forks_repo_head_hexsha": "be2d350289441b99168ea40412891bc65b9cb431", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-28T16:05:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T16:20:00.000Z", "avg_line_length": 19.6875, "max_line_length": 55, "alphanum_fraction": 0.5174603175, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172644875642, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7948320442863985}}
{"text": "\nfunction bracket_minimum(f, x=0; s=1e-2, k=2.0)\n    a, ya = x, f(x)\n    b, yb = a + s, f(a + s)\n    if yb > ya\n        a, b = b, a\n        ya, yb = yb, ya\n        s = -s\n    end\n    while true\n        c, yc = b + s, f(b + s)\n        if yc > yb\n            return a < c ? (a,b, c) : (c,b, a)\n        end\n        a, ya, b, yb = b, yb, c, yc\n        s *= k\n    end\nend\n\nfunction quadratic_fit_search(f, a, b, c, n)\n    ya, yb, yc = f(a), f(b), f(c)\n    for i in 1:n-3\n        x = 0.5*(ya*(b^2-c^2)+yb*(c^2-a^2)+yc*(a^2-b^2)) /\n            (ya*(b-c) +yb*(c-a) +yc*(a-b))\n        yx = f(x)\n        if x > b\n            if yx > yb\n                c, yc = x, yx\n            else\n                a, ya, b, yb = b, yb, x, yx\n            end\n        elseif x < b\n            if yx > yb\n                a, ya = x, yx\n            else\n                c, yc, b, yb = b, yb, x, yx\n            end\n        end\n    end\n    return (a, b, c)\nend\n\nφ = MathConstants.φ\nfunction golden_section_search(f, a, b, n)\n    ρ = φ-1\n    d = ρ * b + (1 - ρ)*a\n    yd = f(d)\n    for i = 1 : n-1\n        c = ρ*a + (1 - ρ)*b\n        yc = f(c)\n        if yc < yd\n            b, d, yd = d, c, yc\n        else\n            a, b = b, c\n        end\n    end\n    return a < b ? (a, b) : (b, a)\nend\n    \nfunction line_search(f, x, d)\n    objective = α -> f(x + α*d)\n    a, b,c = bracket_minimum(objective)\n    \n    #numero de iteracoes\n    n=(c-a)/(10^-3*log(φ))\n    \n    #pelo metodo golden section search\n    α,beta = golden_section_search(objective, a, c,n)\n\n    #pelo metodo quadratic fit search\n    #α,beta,gamma = quadratic_fit_search(objective, a, b, c,n)\n    return (x + α*d,α)\nend\n\n#funcao multivariavel\nf(x) = sin(x[1]*x[2])+exp(x[2]+x[3])-x[3]\n\n#ponto inicial\nx0 = [1,2,3]\n\n#direcao de busca\nd = [0,-1,-1]\n\n(x,α) = line_search(f, x0, d)\nprintln(\"x* = \", x)", "meta": {"hexsha": "f0b9e2ee3beadbc603da800293bcea62faa21d52", "size": 1826, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "line_search.jl", "max_stars_repo_name": "GilbertoLucas/Structural_Optimization", "max_stars_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "line_search.jl", "max_issues_repo_name": "GilbertoLucas/Structural_Optimization", "max_issues_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "line_search.jl", "max_forks_repo_name": "GilbertoLucas/Structural_Optimization", "max_forks_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4823529412, "max_line_length": 62, "alphanum_fraction": 0.4233296824, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7948320348866305}}
{"text": "\"\"\"Squared deviations from the array mean.\"\"\"\nfunction SqDeviation(X::Array{T,1}) where {T<:AbstractFloat}\n\n    s = zero(T)\n    μ = mean(X)\n\n    @simd for xi in X\n        s += (xi - μ)^2\n    end\n\n    return s\nend\n\n\"\"\"Linear deviations from the array mean - i.e. L1-Norm.\"\"\"\nfunction LinDeviation(X::Array{T,1}) where {T<:AbstractFloat}\n\n    s = zero(T)\n    μ = mean(X)\n\n    @simd for xi in X\n        s += abs(xi - μ)\n    end\n\n    return s\nend\n\n\"\"\"Squared deviations from the class means.\"\"\"\nfunction SDCM(X::Array{T,1},breaks::Array{Int,1}) where {T<:AbstractFloat}\n\n    n = length(breaks)-1  # number of classes (aka intervals)\n\n    @boundscheck breaks[end] == length(X)+1 || throw(BoundsError())\n    @boundscheck breaks[1] == 1 || throw(BoundsError())\n\n    s = zero(T)\n\n    for iclass in 1:n\n        s += SqDeviation(ClassValues(X,breaks,iclass))\n    end\n\n    return s\nend\n\n\"\"\"Goodness of variance fit for data array X (assumed to be sorted) and classes determined by break indices.\"\"\"\nfunction GVF(X::Array{T,1},breaks::Array{Int,1}) where {T<:AbstractFloat}\n    sdam = SqDeviation(X)       # squared deviation from array mean\n    sdcm = SDCM(X,breaks)       # sum  of squared deviations from class mean for each class\n    return 1 - sdcm/sdam\nend\n\n\"\"\"Average rounding error for data array X (assumed to be sorted) and classes determind by break indices.\"\"\"\nfunction ARE(X::Array{T,1},breaks::Array{Int,1}) where {T<:AbstractFloat}\n    s = zero(T)\n    ndata = length(X)\n    for iclass in 1:(length(breaks)-1)\n        s += LinDeviation(ClassValues(X,breaks,iclass))\n    end\n    return s/ndata\nend\n", "meta": {"hexsha": "3fd675b4ba1f76295f17c5646c345cc24537ed1c", "size": 1599, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/metrics.jl", "max_stars_repo_name": "milankl/Jenks.jl", "max_stars_repo_head_hexsha": "b218030240f2ab52320d9218e2d1c3708682f708", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-10T17:31:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-11T12:31:07.000Z", "max_issues_repo_path": "src/metrics.jl", "max_issues_repo_name": "milankl/Jenks.jl", "max_issues_repo_head_hexsha": "b218030240f2ab52320d9218e2d1c3708682f708", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-10T17:42:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-10T18:40:50.000Z", "max_forks_repo_path": "src/metrics.jl", "max_forks_repo_name": "milankl/Jenks.jl", "max_forks_repo_head_hexsha": "b218030240f2ab52320d9218e2d1c3708682f708", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-30T07:22:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-30T07:22:25.000Z", "avg_line_length": 26.65, "max_line_length": 111, "alphanum_fraction": 0.641025641, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7947245372010202}}
{"text": "module ForwardAutodiff\n\nimport Base: exp, sin, cos, tan, +, -, *, /, sqrt, convert, promote_rule, zero\n\nexport D\n\nstruct Infinitesimal{T <: Number} <: Number\n    x::T\n    dx::T\nend\n\nfunction convert(::Type{Infinitesimal{T}}, x::T) where {T}\n   Infinitesimal(x, zero(x))\nend\nfunction convert(::Type{Infinitesimal{T}}, x::Infinitesimal{S}) where {S, T}\n   Infinitesimal(T(x.x), T(x.dx))\nend\n# This is needed according to an error before\nfunction convert(::Type{Infinitesimal{T}}, x::T) where {T <: Number}\n    Infinitesimal(x, zero(x))\nend\nfunction convert(::Type{Infinitesimal{T}}, x::S) where {T, S <: Number}\n    x_as_T = convert(T, x)\n    Infinitesimal(x_as_T, zero(x_as_T))\nend\n\nfunction zero(x::Infinitesimal{T}) where T\n    Infinitesimal(zero(x.x), zero(x.dx))\nend\n\nfunction promote_rule(::Type{Infinitesimal{T}}, ::Type{Infinitesimal{S}}) where {T,S}\n    Infinitesimal{promote_type(T,S)}\nend\nfunction promote_rule(::Type{Infinitesimal{T}}, ::Type{S}) where {T, S <: Number}\n    Infinitesimal{promote_type(T,S)}\nend\nfunction promote_rule(::Type{T}, ::Type{Infinitesimal{S}}) where {T <: Number, S}\n    Infinitesimal{promote_type(T,S)}\nend\nfunction promote_rule(::Type{S}, ::Type{Infinitesimal{T}}) where {S <: AbstractIrrational, T}\n    Infinitesimal{promote_type(S,T)}\nend\n\nfunction extract_derivative(xdx::Infinitesimal)\n    return xdx.dx\nend\nfunction extract_derivative(xs::Array)\n    [extract_derivative(x) for x in xs]\nend\nfunction extract_derivative(xs::Tuple)\n    convert(Tuple, [extract_derivative(x) for x in xs])\nend\n\n\"\"\"    D([i], f)\n\nDifferential operator; with an optional integer, specifies a partial derivative\nwith respect to argment `i` (from 1).\n\nReturns a function that computes the derivative of `f`.  NOTE: at the moment,\nnested derivatives won't work: `D(D(f))` will not compute a second derivative.\n\"\"\"\nfunction D(f)\n    function df(x)\n        xdx = Infinitesimal(x, one(x))\n        result = f(xdx)\n        return extract_derivative(result)\n    end\n    df\nend\nfunction D(i::Integer, f)\n    function df(xs...)\n        xarr = [(j != i ? x : Infinitesimal(x, one(x))) for (j,x) in enumerate(xs)]\n        result = f(xarr...)\n        return extract_derivative(result)\n    end\n    df\nend\n\nfunction +(x::Infinitesimal, y::Infinitesimal)\n    Infinitesimal(x.x+y.x, x.dx+y.dx)\nend\nfunction -(x::Infinitesimal, y::Infinitesimal)\n    Infinitesimal(x.x-y.x, x.dx-y.dx)\nend\nfunction -(x::Infinitesimal)\n    Infinitesimal(-x.x, -x.dx)\nend\nfunction *(x::Infinitesimal, y::Infinitesimal)\n    Infinitesimal(x.x*y.x, x.x*y.dx + x.dx*y.x)\nend\nfunction /(x::Infinitesimal, y::Infinitesimal)\n    Infinitesimal(x.x/y.x, x.dx/y.x - x.x*y.dx/(y.x*y.x))\nend\n\nfunction sqrt(x::Infinitesimal)\n    Infinitesimal(sqrt(x.x), x.dx/(2*sqrt(x.x)))\nend\n\nfunction exp(x::Infinitesimal)\n    return Infinitesimal(exp(x.x), exp(x.x)*x.dx)\nend\nfunction sin(x::Infinitesimal)\n    return Infinitesimal(sin(x.x), cos(x.x)*x.dx)\nend\nfunction cos(x::Infinitesimal)\n    return Infinitesimal(cos(x.x), -sin(x.x)*x.dx)\nend\nfunction tan(x::Infinitesimal)\n    c = cos(x.x)\n    return Infinitesimal(tan(x.x), x.dx/(c*c))\nend\n\nend # module\n", "meta": {"hexsha": "6f799a7098a754bd113cd705c806fd867d006939", "size": 3117, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ForwardAutodiff.jl", "max_stars_repo_name": "Farr-PHY-604/ForwardAutodiff.jl", "max_stars_repo_head_hexsha": "7f49ad4f7a5f885c81874d92964d4ce82f64156a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-27T00:38:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T00:38:34.000Z", "max_issues_repo_path": "src/ForwardAutodiff.jl", "max_issues_repo_name": "Farr-PHY-604/ForwardAutodiff.jl", "max_issues_repo_head_hexsha": "7f49ad4f7a5f885c81874d92964d4ce82f64156a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-13T13:22:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-13T14:32:49.000Z", "max_forks_repo_path": "src/ForwardAutodiff.jl", "max_forks_repo_name": "Farr-PHY-604/ForwardAutodiff.jl", "max_forks_repo_head_hexsha": "7f49ad4f7a5f885c81874d92964d4ce82f64156a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3421052632, "max_line_length": 93, "alphanum_fraction": 0.6791786975, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.7946912326286594}}
{"text": "\"\"\"\n    estimateKernelSize{T <: Real}(X::Array{T, 2}; sampleSize = 100)\n\n    Estimate kernel size by taking median distance between points.\n\"\"\"\nfunction estimateKernelSize(X::Array{T, 2}; sampleSize = 100) where T <: Real\n\n\tM = size(X)[1]\n\n\t# set kernel size to median distance between points\n\tif M > sampleSize\n\t\tXmed = X[shuffle(collect(1:M))[1:sampleSize],:]\n\t\tS = sampleSize\n\telse\n\t\tXmed = X\n\t\tS = M\n\tend\n\n\tdists = pairwise(SqEuclidean(), Xmed, Xmed, dims=1)\n    sig = sqrt(0.5 * median(dists))\n\n    return sig\nend\n\n\"\"\"\n    rbfDotProduct(X::Array{T, 2}, X::Array{T, 2}, kernelSize::Float64)\n\n\"\"\"\nfunction rbfDotProduct(X::Array{T, 2}, Y::Array{T, 2}, kernelSize) where T <: Real\n\n    H = zeros(size(X,1), size(Y,1))\n    @assert size(X,2) == size(Y,2)\n\n    for i in 1:size(X,1)\n        for j in 1:size(Y,1)\n            @inbounds begin\n                H[i,j] = first( (X[i,:].-Y[j,:]) * (X[i,:].-Y[j,:])' )\n            end\n        end\n    end\n\n    return exp.(-H/2/kernelSize^2)\nend\n\neye(n) = Matrix(I, n, n)\n", "meta": {"hexsha": "c4c2982e24a6e22cfc84cd372c56e06d9f6c1419", "size": 1011, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/common.jl", "max_stars_repo_name": "UnofficialJuliaMirror/HilbertSchmidtIndependenceCriterion.jl-08eae483-2844-53a4-a2b9-23549d80f877", "max_stars_repo_head_hexsha": "2420e331fbd05fa6a4dee8623d646d82bedcf942", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-01-13T08:15:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-19T10:24:01.000Z", "max_issues_repo_path": "src/common.jl", "max_issues_repo_name": "UnofficialJuliaMirror/HilbertSchmidtIndependenceCriterion.jl-08eae483-2844-53a4-a2b9-23549d80f877", "max_issues_repo_head_hexsha": "2420e331fbd05fa6a4dee8623d646d82bedcf942", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-04-26T16:16:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-04T07:26:43.000Z", "max_forks_repo_path": "src/common.jl", "max_forks_repo_name": "UnofficialJuliaMirror/HilbertSchmidtIndependenceCriterion.jl-08eae483-2844-53a4-a2b9-23549d80f877", "max_forks_repo_head_hexsha": "2420e331fbd05fa6a4dee8623d646d82bedcf942", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-07-14T08:04:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-03T03:00:46.000Z", "avg_line_length": 21.9782608696, "max_line_length": 82, "alphanum_fraction": 0.5766567755, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8652240773641087, "lm_q1q2_score": 0.7946912236446201}}
{"text": "using MonteCarloX\nusing Random\nusing Plots\n\n\n\"\"\" Self-exciting process. Rate jumps up by x_increase on event and subsequently\ndecays to the baserate with timeconstant tau.\"\"\"\nfunction hawkes_process(tau::Float64 = 1.0, baserate::Float64 = 0.2, x_increase::Float64 = 0.001;\n    plotflag::Bool = false, nSamples::Int = 30, rng::AbstractRNG = MersenneTwister(1000))\n    \n    alg = InhomogeneousPoissonPiecewiseDecreasing()\n\n    decay(t, t0, x0) = x0 * exp(-(t - t0) / tau)\n    Lambda(t, t0, x0) = baserate + decay(t, t0, x0)\n\n    samples = zeros(nSamples)\n\n    t0 = 0.0\n    x0 = 0.0\n    for i in 1:nSamples\n        t_previous = t0\n        t0 += next_time(alg, rng, dt->Lambda(dt, 0.0, x0))\n        # The current exponential decays starting value x0 is \n        # the decay up to now (t0) plus the increase \n        x0 = decay(t0, t_previous, x0) + x_increase\n        samples[i] = t0\n    end\n\n    if plotflag\n        # For plotting we are inefficient; (t > t0) means only causal influence\n        ratefun(t) = sum([(t > t0) * decay(t, t0, x_increase) for t0 in samples])\n        maxT = samples[end] + 4 * tau\n        plotrange = range(0.0, stop = maxT, length = 2000)\n        plot(plotrange, map(ratefun, plotrange), grid = false)\n        display(vline!(samples)) # plot lines when events happen\n    end\n\n    return samples\nend\n\n\n", "meta": {"hexsha": "e77c3de92cf63cca1ab797d86c74fa183a176ffb", "size": 1326, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/hawkes_process.jl", "max_stars_repo_name": "zierenberg/MonteCarloX.jl", "max_stars_repo_head_hexsha": "698ed26dabea8bbdf39299facdf8daf70a4a679e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-03-07T19:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-19T18:24:25.000Z", "max_issues_repo_path": "examples/hawkes_process.jl", "max_issues_repo_name": "zierenberg/MonteCarloX.jl", "max_issues_repo_head_hexsha": "698ed26dabea8bbdf39299facdf8daf70a4a679e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2019-10-15T09:48:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-02T18:51:06.000Z", "max_forks_repo_path": "examples/hawkes_process.jl", "max_forks_repo_name": "zierenberg/MonteCarloX.jl", "max_forks_repo_head_hexsha": "698ed26dabea8bbdf39299facdf8daf70a4a679e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-10-15T12:16:12.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-07T14:34:28.000Z", "avg_line_length": 31.5714285714, "max_line_length": 97, "alphanum_fraction": 0.6319758673, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8652240756264639, "lm_q1q2_score": 0.7946912220486276}}
{"text": "T = 250\nσ = 0.2\nt = range(0, 20, length = T)\ns = sin.(t)\ny = s + randn(T) * σ\n\nh = (t[end] - t[1])/T\nH = [1.0, 0.0, 0.0]\nA = [1.0 h   0.5*h^2;\n     0.0 1.0 h;\n     0.0 0.0 1.0]\n\nm = Model(y, H, A, Matrix(0.01*I, 3, 3), σ^2, [0.0, 0.0, 0.0], Matrix(1000.0I, 3, 3))\nkf = kalmanfilter(m)\nks = kalmansmoother(m, kf.priors, kf.posteriors)\n\nusing Plots\n\nscatter(y, label = \"Measurements\", legend = :bottom, ylim = [-3, 2],\n        markerstrokewidth = 0, markercolor = \"black\", foreground_color_legend = nothing)\nplot!(s, label = \"Noiseless signal\", linewidth = 3, color = \"grey\")\nplot!(kf.priors.μ, label = \"Prediction\", linewidth = 2, color = \"blue\")\nplot!(kf.posteriors.μ, label = \"Filter\", linewidth = 2, color = \"red\")\nplot!(ks.μ, label = \"Smoother\", linewidth = 2, color = \"green\")\n\nscatter(y, label = \"Measurements\", legend = :bottom, ylim = [-3, 2],\n        markerstrokewidth = 0, markercolor = \"black\", foreground_color_legend = nothing)\nplot!(s, label = \"Noiseless signal\", linewidth = 3, color = \"grey\")\nplot!(ks.x, label = [\"Position\" \"Velocity\" \"Acceleration\"], linewidth = 2, color = [\"blue\" \"red\" \"green\"])", "meta": {"hexsha": "d9ecaa43aa232eff7d9c442ea263f1a72b4c5d80", "size": 1114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/kca.jl", "max_stars_repo_name": "madskoefoed/KalmanFilter.jl", "max_stars_repo_head_hexsha": "057347af3ddc2cceb3791e9474b3b2d6bc6a61c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/kca.jl", "max_issues_repo_name": "madskoefoed/KalmanFilter.jl", "max_issues_repo_head_hexsha": "057347af3ddc2cceb3791e9474b3b2d6bc6a61c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/kca.jl", "max_forks_repo_name": "madskoefoed/KalmanFilter.jl", "max_forks_repo_head_hexsha": "057347af3ddc2cceb3791e9474b3b2d6bc6a61c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4137931034, "max_line_length": 106, "alphanum_fraction": 0.6086175943, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7946636713013797}}
{"text": "using DelimitedFiles\nusing FFTW\n\nfunction create_sine_wave(freq, res, filename)\n    a = [sin(freq*2*pi*i/res) for i = 1:res]\n    writedlm(filename, a)\nend\n\nfunction create_sine_fft(freq, res, filename)\n    a = [sin(freq*2*pi*i/res) for i = 1:res]\n    writedlm(filename, abs.(fft(a)))\nend\n\nfunction create_3_sine_waves(freq1, freq2, freq3, res, filename)\n    a = [sin(freq1*2*pi*i/res) for i = 1:res]\n    a += [sin(freq2*2*pi*i/res) for i = 1:res]\n    a += [sin(freq3*2*pi*i/res) for i = 1:res]\n    writedlm(filename, a)\nend\n\nfunction create_3_sine_fft(freq1, freq2, freq3, res, filename)\n    a = [sin(freq1*2*pi*i/res) for i = 1:res]\n    a += [sin(freq2*2*pi*i/res) for i = 1:res]\n    a += [sin(freq3*2*pi*i/res) for i = 1:res]\n    writedlm(filename, abs.(fft(a)))\nend\n", "meta": {"hexsha": "281017eec91cd01093269863cffbeecb9fe498b3", "size": 769, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "data/splitop/fourier/fourier_figure.jl", "max_stars_repo_name": "leios/thesis", "max_stars_repo_head_hexsha": "0fdbfdc9b42a967a9b3492be4ab788bdf76d4ce5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-02-12T02:41:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T09:46:28.000Z", "max_issues_repo_path": "data/splitop/fourier/fourier_figure.jl", "max_issues_repo_name": "leios/thesis", "max_issues_repo_head_hexsha": "0fdbfdc9b42a967a9b3492be4ab788bdf76d4ce5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-02-07T08:22:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-07T08:22:21.000Z", "max_forks_repo_path": "data/splitop/fourier/fourier_figure.jl", "max_forks_repo_name": "leios/thesis", "max_forks_repo_head_hexsha": "0fdbfdc9b42a967a9b3492be4ab788bdf76d4ce5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-07T08:07:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-07T08:07:50.000Z", "avg_line_length": 28.4814814815, "max_line_length": 64, "alphanum_fraction": 0.6384915475, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079558, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.794663661194771}}
{"text": "using LsqFit\nusing Statistics\nusing StatsBase\n\n\"\"\"\nfit_straight_line(tdata::Vector{Float64}, vdata::Vector{Float64}; pa0=[0.0, 0.5], i0=1)\n\n# Fields \n\n`tdata`: time-like (x) data\n`vdata`` : voltage-like (y) data \n`pa0`: initial values of parameters \n`i0` : index of first point in array to be used in the fit \n\n# Returns \n- coefficient of the field (a vector)\n- standard errors of coefficients (a vector)\n- yfit = fit(tdata), that is the prediction of the values corresponding to each tdata\n  for the fit parameters \n\n\"\"\"\nfunction fit_straight_line(tdata::Vector{Float64}, vdata::Vector{Float64}; pa0=[0.0, 0.5], i0=1)\n\ttfun(t, a, b) = a + b * t\n\tpfun(t, p) = p[1] .+ p[2] .* t\n\til = length(tdata)\n\tfit = curve_fit(pfun, tdata[i0:il], vdata[i0:il], pa0)\n\tcoef(fit), stderror(fit), tfun.(tdata, coef(fit)...)\nend\n\n\n\"\"\"\nfit_expo(tdata::Vector{Float64}, vdata::Vector{Float64}; pa0=[0.0, 0.5], i0=1)\n\n# Fields \n\n`tdata`: time-like (x) data\n`vdata`` : voltage-like (y) data \n`pa0`: initial values of parameters \n`i0` : index of first point in array to be used in the fit \n\n# Returns \n- coefficient of the field (a vector)\n- standard errors of coefficients (a vector)\n- yfit = fit(tdata), that is the prediction of the values corresponding to each tdata\n  for the fit parameters \n\n\"\"\"\nfunction fit_expo(tdata::Vector{Float64}, vdata::Vector{Float64}; pa0=[0.0, 0.5], i0=1)\n\ttfun(t, N, λ) = N*exp(-t/λ)\n\tpfun(t, p) = p[1] * exp.(-t/p[2])\n\til = length(tdata)\n\tfit = curve_fit(pfun, tdata[i0:il], vdata[i0:il], pa0)\n\tcoef(fit), stderror(fit), tfun.(tdata, coef(fit)...)\nend\n\n\n\"\"\"\n    fit_time_histo(htime::Histogram; pa0=[100.0, 0.5], i0=1)\n    \n# Fields\n\n\t`htime` : An histogram of times \n\t`pa0`   : initial value of fit parameters \n\t`i0`    : first bin to fit  \n\n# Returns\n\n# Returns \n- coefficient of the field (a vector)\n- standard errors of coefficients (a vector)\n- yfit = fit(tdata), that is the prediction of the values corresponding to each tdata\n  for the fit parameters \n\n\"\"\"\nfunction fit_time_histo(htime::Histogram; pa0=[100.0, 0.5], i0=1)\n\ttdata = centers(htime)\n\tvdata = htime.weights\n    fit_expo(tdata, vdata; pa0=pa0, i0=i0)\nend", "meta": {"hexsha": "7178bdb29dca03f5a1dba6a9edbd76480760d81f", "size": 2138, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fits.jl", "max_stars_repo_name": "jjgomezcadenas/laserlab", "max_stars_repo_head_hexsha": "76014d9368c482dd9deec0e4948070370ad7da88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fits.jl", "max_issues_repo_name": "jjgomezcadenas/laserlab", "max_issues_repo_head_hexsha": "76014d9368c482dd9deec0e4948070370ad7da88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fits.jl", "max_forks_repo_name": "jjgomezcadenas/laserlab", "max_forks_repo_head_hexsha": "76014d9368c482dd9deec0e4948070370ad7da88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-14T16:53:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T16:53:50.000Z", "avg_line_length": 27.0632911392, "max_line_length": 96, "alphanum_fraction": 0.6739943873, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.7946636596127368}}
{"text": "@doc raw\"\"\"\n    LogKernel([α [,γ]])\n\nThe Log Kernel is a negative definite kernel given by:\n\n```math\n\\kappa(\\mathbf{x},\\mathbf{y}) = \n\\log \\left(1 + \\alpha\\|\\mathbf{x} - \\mathbf{y} \\|^{2\\gamma}\\right)\n\\qquad \\alpha > 0, \\; \\gamma \\in (0,1]\n```\n\"\"\"\nstruct LogKernel{T<:AbstractFloat} <: NegativeDefiniteKernel{T}\n    alpha::HyperParameter{T}\n    gamma::HyperParameter{T}\n    LogKernel{T}(α::Real, γ::Real) where {T<:AbstractFloat} = new{T}(\n        HyperParameter(convert(T,α), interval(OpenBound(zero(T)), nothing)),\n        HyperParameter(convert(T,γ), interval(OpenBound(zero(T)), ClosedBound(one(T))))\n    )\nend\nfunction LogKernel(α::T1 = 1.0, γ::T2 = one(T1)) where {T1<:Real,T2<:Real}\n    LogKernel{floattype(T1,T2)}(α, γ)\nend\n\n@inline logkernel(z::T, α::T, γ::T) where {T<:AbstractFloat} = log(α*z^γ+1)\n\n@inline basefunction(::LogKernel) = SquaredEuclidean()\n@inline function kappa(κ::LogKernel{T}, z::T) where {T}\n    logkernel(z, getvalue(κ.alpha), getvalue(κ.gamma))\nend", "meta": {"hexsha": "699c896d8c29337158c60b593fb5259d6299c850", "size": 979, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernelfunctions/negativedefinite/log.jl", "max_stars_repo_name": "holtri/MLKernels.jl", "max_stars_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernelfunctions/negativedefinite/log.jl", "max_issues_repo_name": "holtri/MLKernels.jl", "max_issues_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernelfunctions/negativedefinite/log.jl", "max_forks_repo_name": "holtri/MLKernels.jl", "max_forks_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7586206897, "max_line_length": 87, "alphanum_fraction": 0.6486210419, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350253, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.79459987350157}}
{"text": "defaulttol(a) = eps(real(float(one(eltype(a)))))^(1/2)\n\n\"\"\"\n Take the L2 Tikhonov regularised inverse of a matrix `m`.\n\n The regularisation parameter is the larger of `delta` (the optional argument that defaults\n to zero) and square root of machine epsilon. The inverse is done using an SVD.\n \"\"\"\n function reginv(a::AbstractMatrix, δ = defaulttol(a))\n     U, S, V = svd(a)\n     Sinv = inv.(hypot.(S, δ))\n     return  V * Diagonal(Sinv) * U'\n end\n\n function posreginv(a::AbstractMatrix, δ = defaulttol(a))\n     # assumes a is positive definite (or close to)\n     D, V = eigen(Hermitian(a))\n     Dinv = inv.(hypot.(D, δ))\n     return  V * Diagonal(Dinv) * V'\n end\n\n # computes solution C of A * C + C * A = B for A hermitian\n  function symm_sylvester_reg(A::AbstractMatrix, B::AbstractMatrix, δ = zero(eltype(A)))\n      n = LinearAlgebra.checksquare(A)\n      Λ, U = eigen(Hermitian(A))\n      UdCU = U' * B * U\n      for j = 1:n\n          for i = 1:n\n              UdCU[i,j] /= sqrt((Λ[i] + Λ[j])^2 + δ^2)\n          end\n      end\n      C = U*UdCU*U'\n      return C\n  end\n", "meta": {"hexsha": "4ecefc05d549b2cadb8be1402e8c1f162ad9a229", "size": 1069, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/common/regularisedinverse.jl", "max_stars_repo_name": "BenoitTuybens/CMPSKit.jl", "max_stars_repo_head_hexsha": "e113add1365d4c67ae16561ab98a522dfb6f6dcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common/regularisedinverse.jl", "max_issues_repo_name": "BenoitTuybens/CMPSKit.jl", "max_issues_repo_head_hexsha": "e113add1365d4c67ae16561ab98a522dfb6f6dcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/regularisedinverse.jl", "max_forks_repo_name": "BenoitTuybens/CMPSKit.jl", "max_forks_repo_head_hexsha": "e113add1365d4c67ae16561ab98a522dfb6f6dcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5428571429, "max_line_length": 91, "alphanum_fraction": 0.5996258185, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799420543365, "lm_q2_score": 0.8244619263765706, "lm_q1q2_score": 0.7945998676292179}}
{"text": "doc\"\"\"\n    Pareto(α,θ)\n\nThe *Pareto distribution* with shape `α` and scale `θ` has probability density function\n\n$f(x; \\alpha, \\theta) = \\frac{\\alpha \\theta^\\alpha}{x^{\\alpha + 1}}, \\quad x \\ge \\theta$\n\n```julia\nPareto()            # Pareto distribution with unit shape and unit scale, i.e. Pareto(1.0, 1.0)\nPareto(a)           # Pareto distribution with shape a and unit scale, i.e. Pareto(a, 1.0)\nPareto(a, b)        # Pareto distribution with shape a and scale b\n\nparams(d)        # Get the parameters, i.e. (a, b)\nshape(d)         # Get the shape parameter, i.e. a\nscale(d)         # Get the scale parameter, i.e. b\n```\n\nExternal links\n * [Pareto distribution on Wikipedia](http://en.wikipedia.org/wiki/Pareto_distribution)\n\n\"\"\"\nimmutable Pareto <: ContinuousUnivariateDistribution\n    α::Float64\n    θ::Float64\n\n    function Pareto(α::Real, θ::Real)\n        @check_args(Pareto, α > zero(α) && θ > zero(θ))\n        new(α, θ)\n    end\n    Pareto(α::Real) = Pareto(α, 1.0)\n    Pareto() = new(1.0, 1.0)\nend\n\n@distr_support Pareto d.θ Inf\n\n\n#### Parameters\n\nshape(d::Pareto) = d.α\nscale(d::Pareto) = d.θ\n\nparams(d::Pareto) = (d.α, d.θ)\n\n\n#### Statistics\n\nmean(d::Pareto) = ((α, θ) = params(d); α > 1.0 ? α * θ / (α - 1.0) : Inf)\nmedian(d::Pareto) = ((α, θ) = params(d); θ * 2.0 ^ (1.0 / α))\nmode(d::Pareto) = d.θ\n\nfunction var(d::Pareto)\n    (α, θ) = params(d)\n    α > 2.0 ? (θ^2 * α) / ((α - 1.0)^2 * (α - 2.0)) : Inf\nend\n\nfunction skewness(d::Pareto)\n    α = shape(d)\n    α > 3.0 ? ((2.0 * (1.0 + α)) / (α - 3.0)) * sqrt((α - 2.0) / α) : NaN\nend\n\nfunction kurtosis(d::Pareto)\n    α = shape(d)\n    α > 4.0 ? (6.0 * (α^3 + α^2 - 6.0 * α - 2.0)) / (α * (α - 3.0) * (α - 4.0)) : NaN\nend\n\nentropy(d::Pareto) = ((α, θ) = params(d); log(θ / α) + 1.0 / α + 1.0)\n\n\n#### Evaluation\n\nfunction pdf(d::Pareto, x::Float64)\n    (α, θ) = params(d)\n    x >= θ ? α * (θ / x)^α * (1.0 / x) : 0.0\nend\n\nfunction logpdf(d::Pareto, x::Float64)\n    (α, θ) = params(d)\n    x >= θ ? log(α) + α * log(θ) - (α + 1.0) * log(x) : -Inf\nend\n\nfunction ccdf(d::Pareto, x::Float64)\n    (α, θ) = params(d)\n    x >= θ ? (θ / x)^α : 1.0\nend\n\ncdf(d::Pareto, x::Float64) = 1.0 - ccdf(d, x)\n\nfunction logccdf(d::Pareto, x::Float64)\n    (α, θ) = params(d)\n    x >= θ ? α * log(θ / x) : 0.0\nend\n\nlogcdf(d::Pareto, x::Float64) = log1p(-ccdf(d, x))\n\ncquantile(d::Pareto, p::Float64) = d.θ / p^(1.0 / d.α)\nquantile(d::Pareto, p::Float64) = cquantile(d, 1.0 - p)\n\n\n#### Sampling\n\nrand(d::Pareto) = d.θ * exp(randexp() / d.α)\n\n\n## Fitting\n\nfunction fit_mle{T <: Real}(::Type{Pareto}, x::AbstractArray{T})\n    # Based on\n    # https://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation\n\n    θ = minimum(x)\n\n    n = length(x)\n    lθ = log(θ)\n    temp1 = zero(T)\n    for i=1:n\n        temp1 += log(x[i]) - lθ\n    end\n    α = n/temp1\n\n    return Pareto(α, θ)\nend\n", "meta": {"hexsha": "eb0822b72d1001a333c1e0d00cc76c9ec9fc0beb", "size": 2824, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/pareto.jl", "max_stars_repo_name": "ericproffitt/Distributions.jl", "max_stars_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/pareto.jl", "max_issues_repo_name": "ericproffitt/Distributions.jl", "max_issues_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/pareto.jl", "max_forks_repo_name": "ericproffitt/Distributions.jl", "max_forks_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1475409836, "max_line_length": 95, "alphanum_fraction": 0.5502832861, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7945797350802456}}
{"text": "# p39.m - eigenmodes of biharmonic on a square with clamped BCs\n#         (compare p38.m)\n\n# Construct spectral approximation to biharmonic operator:\nN = 17; (D,x) = cheb(N); D2 = D^2; D2 = D2[2:N,2:N];\nS = diagm([0; 1 ./(1-x[2:N].^2); 0]);\nD4 = (diagm(1-x.^2)*D^4 - 8*diagm(x)*D^3 - 12*D^2)*S;\nD4 = D4[2:N,2:N]; I = eye(N-1);\nL = kron(I,D4) + kron(D4,I) + 2*kron(D2,I)*kron(I,D2);\n\n# Find and plot 25 eigenmodes:\n(Lam,V) = eig(-L); Lam = -real(Lam);\nii = sortperm(Lam)[1:25]; Lam = Lam[ii]; V = real(V[:,ii]);\nLam = sqrt.(Lam/Lam[1]);\ny = x; xxx = yyy = -1:.01:1;\nsq = [1+1im,-1+1im,-1-1im,1-1im,1+1im]; clf();\nfor i = 1:25\n    uu = zeros(N+1,N+1); uu[2:N,2:N] = reshape(V[:,i],N-1,N-1);\n    subplot(5,5,i); plot(real(sq),imag(sq));\n    s = interpolate((x[end:-1:1],y[end:-1:1]),reduce(flipdim,uu,1:2),Gridded(Linear()));\n    contour(xxx,yyy,s[xxx,yyy],levels=[0],color=\"k\"); axis(\"square\");\n    axis(1.25*[-1,1,-1,1]); axis(\"off\");\n    text(-.3,1.15,\"$(signif(Lam[i],5))\",fontsize=7);\nend\n", "meta": {"hexsha": "73b253f6afc034006ff83f3c970daa5347d14bbb", "size": 991, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p39.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p39.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p39.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.64, "max_line_length": 88, "alphanum_fraction": 0.5539858729, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813513911654, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7945572580894394}}
{"text": "\"\"\"\n    euclsq(X, Y)\nSquared Euclidean distances \nbetween the rows of `X` and `Y`.\n* `X` : Data.\n* `Y` : Data.\n\nWhen `X` (n, p) and `Y` (m, p), it returns an object (n, m) with:\n* i, j = distance between row i of `X` and row j of `Y`.\n\"\"\"\nfunction euclsq(X, Y)\n    X = ensure_mat(X)\n    Y = ensure_mat(Y)\n    Distances.pairwise(SqEuclidean(), X', Y', dims = 2)\nend\n\n\"\"\"\n    mahsq(X, Y)\n    mahsq(X, Y, Sinv)\nSquared Mahalanobis distances \nbetween the rows of `X` and `Y`.\n* `X` : Data.\n* `Y` : Data.\n* `Sinv` : Inverse of a covariance matrix S.\n    If not given, this is the uncorrected covariance matrix of `X`.\n\nFor `X` (n, p) and `Y` (m, p), it returns an object (n, m) with:\n* i, j = distance between row i of `X` and row j of `Y`.\n\"\"\"\nfunction mahsq(X, Y)\n    X = ensure_mat(X)\n    Y = ensure_mat(Y)\n    S = Statistics.cov(X, corrected = false)\n    LinearAlgebra.inv!(cholesky!(Hermitian(S)))\n    Distances.pairwise(SqMahalanobis(S), X', Y', dims = 2)\nend\n\nfunction mahsq(X, Y, Sinv)\n    X = ensure_mat(X)\n    Y = ensure_mat(Y)\n    Sinv = ensure_mat(Sinv)\n    Distances.pairwise(SqMahalanobis(Sinv), X', Y', dims = 2)\nend\n\n\"\"\"\n    mahsqchol(X, Y)\n    mahsqchol(X, Y, Uinv)\nCompute the squared Mahalanobis distances (with a Cholesky factorization)\nbetween the observations (rows) of `X` and `Y`.\n* `X` : Data.\n* `Y` : Data.\n* `Uinv` : Inverse of the upper matrix of a Cholesky factorization \n    of a covariance matrix S.\n    If not given, the factorization is done on S, the uncorrected covariance matrix of `X`.\n\nWhen `X` (n, p) and `Y` (m, p), it returns an object (n, m) with:\n* i, j = distance between row i of `X` and row j of `Y`.\n\"\"\"\nfunction mahsqchol(X, Y)\n    X = ensure_mat(X)\n    Y = ensure_mat(Y)    \n    p = size(X, 2)\n    S = Statistics.cov(X, corrected = false)\n    if p == 1\n        Uinv = inv(sqrt(S)) \n    else\n        Uinv = LinearAlgebra.inv!(cholesky!(Hermitian(S)).U)\n    end\n    zX = X * Uinv\n    zY = Y * Uinv\n    euclsq(zX, zY)\nend\n\nfunction mahsqchol(X, Y, Uinv)\n    X = ensure_mat(X)\n    Y = ensure_mat(Y)\n    Uinv = ensure_mat(Uinv)\n    zX = X * Uinv\n    zY = Y * Uinv\n    euclsq(zX, zY)\nend\n\n\n\n\n\n", "meta": {"hexsha": "65cef84e613ff47b5035b2a8a87210f96055e4e8", "size": 2131, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances.jl", "max_stars_repo_name": "mlesnoff/Jchemo.jl", "max_stars_repo_head_hexsha": "fea8da15c0458c0e68921cda55a5bf448170eb53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distances.jl", "max_issues_repo_name": "mlesnoff/Jchemo.jl", "max_issues_repo_head_hexsha": "fea8da15c0458c0e68921cda55a5bf448170eb53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distances.jl", "max_forks_repo_name": "mlesnoff/Jchemo.jl", "max_forks_repo_head_hexsha": "fea8da15c0458c0e68921cda55a5bf448170eb53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4942528736, "max_line_length": 91, "alphanum_fraction": 0.6034725481, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813451206062, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7945572528777078}}
{"text": "\nusing Jecco\nusing LinearAlgebra\nusing SparseArrays\nusing Plots\n\n# returns A_ij = x_i A_ij (no sum in i). note that A itself is also changed.\n# this is equivalent to the operation A = x .* A, but it's much more efficient\nfunction mul_col!(x::Vector, A::SparseMatrixCSC)\n    @assert size(x)[1] == size(A)[1]\n\n    rows = rowvals(A)\n    vals = nonzeros(A)\n    @inbounds for idx in eachindex(vals)\n        row = rows[idx]\n        vals[idx] *= x[row]\n    end\n    A\nend\n\n#=\nbuild operator\n\n   aa Dxx + bb Dx + cc\n\nby overwriting Dxx with the returned value. the construction here is more\nefficient than directly summing the sparse arrays. note that this construction\nonly works because we know that the returned array has the *same* sparsity\npattern as Dxx! we couldn't, for instance, mutate Dx instead since the Dx array\nhas zeros along the diagonal (which would be skipped in the construction below).\n=#\nfunction build_operator!(Dxx::SparseMatrixCSC, Dx::SparseMatrixCSC,\n                         aa::Vector, bb::Vector, cc::Vector)\n    mul_col!(aa, Dxx)\n    mul_col!(bb, Dx)\n    ccId = Diagonal(cc)\n\n    rows = rowvals(Dxx)\n    vals = nonzeros(Dxx)\n    m, n = size(Dxx)\n\n    # cf. https://docs.julialang.org/en/v1/stdlib/SparseArrays/#SparseArrays.nzrange\n    @inbounds for j = 1:n\n        @inbounds for i in nzrange(Dxx, j)\n            row = rows[i]\n            vals[i] += Dx[row,j] + ccId[row,j]\n        end\n    end\n    Dxx\nend\n\nsource(x) = exp(-x^2) * (-2 + 3*x^2)\n\n\nx_min   = -5.0\nx_max   = 5.0\nx_nodes = 256\n\nxcoord  = Cartesian{1}(\"x\", x_min, x_max, x_nodes, endpoint=false)\n\nhx = Jecco.delta(xcoord)\nNx = xcoord.nodes\nx  = xcoord[:]\n\nf_exact = exp.(-x.^2)\n\nord = 4\n\nDx_op  = CenteredDiff{1}(1, ord, hx, Nx)\nDxx_op = CenteredDiff{1}(2, ord, hx, Nx)\nDx     = SparseMatrixCSC(Dx_op)\nDxx    = SparseMatrixCSC(Dxx_op)\n\naa = ones(Nx)\nbb = copy(x)\ncc = x.^2\n\nA_mat  = copy(Dxx)\nDx_tmp = copy(Dx)\n\n# build operator A = Dxx + x Dx + x^2\nbuild_operator!(A_mat, Dx_tmp, aa, bb, cc)\n\nb_vec = source.(x)\n\nA_fact = factorize(A_mat)\nsol    = A_fact \\ b_vec\n\nplot(x, f_exact)\nscatter!(x, sol)\n", "meta": {"hexsha": "830bf0fe7d2435475363ed1bf4cbefd3bb030496", "size": 2081, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example_1D_PDE.jl", "max_stars_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_stars_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-09-08T23:37:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:19:01.000Z", "max_issues_repo_path": "examples/example_1D_PDE.jl", "max_issues_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_issues_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-02T17:57:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-02T17:57:23.000Z", "max_forks_repo_path": "examples/example_1D_PDE.jl", "max_forks_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_forks_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-02-26T15:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T08:46:55.000Z", "avg_line_length": 22.8681318681, "max_line_length": 84, "alphanum_fraction": 0.6463238827, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7945538006147899}}
{"text": "\"\"\"\n    LeviCivita(T::Type{<:Number} = Sym)\n\nBuilds an Array{T,3} of Levi-Civita Symbol `ϵᵢⱼₖ = (i-j) (j-k) (k-i) / 2`\n\n# Examples\n```julia\njulia> ε = LeviCivita(Sym)\n3×3×3 Array{Sym, 3}:\n[:, :, 1] =\n 0   0  0\n 0   0  1\n 0  -1  0\n\n[:, :, 2] =\n 0  0  -1\n 0  0   0\n 1  0   0\n\n[:, :, 3] =\n  0  1  0\n -1  0  0\n  0  0  0\n``` \n\"\"\"\nLeviCivita(T::Type{<:Number} = Sym) = [T(T((i - j) * (j - k) * (k - i)) / T(2)) for i = 1:3, j = 1:3, k = 1:3]\n\n\"\"\"\n    𝐞(i::Integer, dim::Int = 3, T::Type{<:Number} = Sym)\n\nVector of the canonical basis\n\n# Examples\n```julia\njulia> 𝐞(1)\nTens{1, 3, Sym, Sym, Vec{3, Sym}, CanonicalBasis{3, Sym}}\n# data: 3-element Vec{3, Sym}:\n 1\n 0\n 0\n# var: (:cont,)\n# basis: 3×3 Tensor{2, 3, Sym, 9}:\n 1  0  0\n 0  1  0\n 0  0  1\n``` \n\"\"\"\n𝐞(::Val{i}, ::Val{dim} = Val(3), ::Val{T} = Val(Sym)) where {i, dim, T<:Number} =\n    Tens(Vec{dim}(j -> j == i ? one(T) : zero(T)))\n\n\"\"\"\n    init_cartesian(coords = symbols(\"x y z\", real = true))\n\nReturns the coordinates, unit vectors and basis of the cartesian basis\n\n# Examples\n```julia\njulia> coords, vectors, ℬ = init_cartesian() ; x, y, z = coords ; 𝐞₁, 𝐞₂, 𝐞₃ = vectors ;\n``` \n\"\"\"\ninit_cartesian(coords = symbols(\"x y z\", real = true)) = Tuple(coords),\nntuple(i -> 𝐞(Val(i), Val(length(coords)), Val(eltype(coords))), length(coords)),\nCanonicalBasis{length(coords),eltype(coords)}()\n\ninit_cartesian(::Val{3}) = init_cartesian(symbols(\"x y z\", real = true))\ninit_cartesian(::Val{2}) = init_cartesian(symbols(\"x y\", real = true))\ninit_cartesian(dim::Integer) = init_cartesian(Val(dim))\n\n\n\"\"\"\n    𝐞ᵖ(i::Integer, θ::T = zero(Sym); canonical = false)\n\nVector of the polar basis\n\n# Examples\n```julia\njulia> θ = symbols(\"θ\", real = true) ;\n\njulia> 𝐞ᵖ(1, θ)\nTens{1, 2, Sym, Sym, Vec{2, Sym}, RotatedBasis{2, Sym}}\n# data: 2-element Vec{2, Sym}:\n 1\n 0\n# var: (:cont,)\n# basis: 2×2 Tensor{2, 2, Sym, 4}:\n cos(θ)  -sin(θ)\n sin(θ)   cos(θ)\n``` \n\"\"\"\n𝐞ᵖ(::Val{1}, θ::T = zero(Sym); canonical = false) where {T<:Number} =\n    canonical ? Tens(Vec{2}([cos(θ), sin(θ)])) :\n    Tens(Vec{2}([one(T), zero(T)]), Basis(θ))\n𝐞ᵖ(::Val{2}, θ::T = zero(Sym); canonical = false) where {T<:Number} =\n    canonical ? Tens(Vec{2}([-sin(θ), cos(θ)])) :\n    Tens(Vec{2}([zero(T), one(T)]), Basis(θ))\n\n\"\"\"\n    init_polar(coords = (symbols(\"r\", positive = true), symbols(\"θ\", real = true)); canonical = false)\n\nReturns the coordinates, base vectors and basis of the polar basis\n\n# Examples\n```julia\njulia> coords, vectors, ℬᵖ = init_polar() ; r, θ = coords ; 𝐞ʳ, 𝐞ᶿ = vectors ;\n``` \n\"\"\"\ninit_polar(\n    coords = (symbols(\"r\", positive = true), symbols(\"θ\", real = true));\n    canonical = false,\n) = Tuple(coords),\nntuple(i -> 𝐞ᵖ(Val(i), coords[2]; canonical = canonical), 2),\nBasis(coords[2])\n\n\"\"\"\n    𝐞ᶜ(i::Integer, θ::T = zero(Sym); canonical = false)\n\nVector of the cylindrical basis\n\n# Examples\n```julia\njulia> θ = symbols(\"θ\", real = true) ;\n\njulia> 𝐞ᶜ(1, θ)\nTens{1, 3, Sym, Sym, Vec{3, Sym}, RotatedBasis{3, Sym}}\n# data: 3-element Vec{3, Sym}:\n 1\n 0\n 0\n# var: (:cont,)\n# basis: 3×3 Tensor{2, 3, Sym, 9}:\n cos(θ)  -sin(θ)  0\n sin(θ)   cos(θ)  0\n      0        0  1\n``` \n\"\"\"\n𝐞ᶜ(::Val{1}, θ::T = zero(Sym); canonical = false) where {T<:Number} =\n    canonical ? Tens(Vec{3}([cos(θ), sin(θ), zero(T)])) :\n    Tens(Vec{3}([one(T), zero(T), zero(T)]), CylindricalBasis(θ))\n𝐞ᶜ(::Val{2}, θ::T = zero(Sym); canonical = false) where {T<:Number} =\n    canonical ? Tens(Vec{3}([-sin(θ), cos(θ), zero(T)])) :\n    Tens(Vec{3}([zero(T), one(T), zero(T)]), CylindricalBasis(θ))\n𝐞ᶜ(::Val{3}, θ::T = zero(Sym); canonical = false) where {T<:Number} =\n    canonical ? Tens(Vec{3}([zero(T), zero(T), one(T)])) :\n    Tens(Vec{3}([zero(T), zero(T), one(T)]), CylindricalBasis(θ))\n\n\"\"\"\n    init_cylindrical(coords = (symbols(\"r\", positive = true), symbols(\"θ\", real = true), symbols(\"z\", real = true)); canonical = false)\n\nReturns the coordinates, base vectors and basis of the cylindrical basis\n\n# Examples\n```julia\njulia> coords, vectors, ℬᶜ = init_cylindrical() ; r, θ, z = coords ; 𝐞ʳ, 𝐞ᶿ, 𝐞ᶻ = vectors ;\n``` \n\"\"\"\ninit_cylindrical(\n    coords = (\n        symbols(\"r\", positive = true),\n        symbols(\"θ\", real = true),\n        symbols(\"z\", real = true),\n    );\n    canonical = false,\n) = Tuple(coords),\nntuple(i -> 𝐞ᶜ(Val(i), coords[2]; canonical = canonical), 3),\nCylindricalBasis(coords[2])\n\n\"\"\"\n    𝐞ˢ(i::Integer, θ::T = zero(Sym), ϕ::T = zero(Sym), ψ::T = zero(Sym); canonical = false)\n\nVector of the basis rotated with the 3 Euler angles `θ, ϕ, ψ` (spherical if `ψ=0`)\n\n# Examples\n```julia\njulia> θ, ϕ, ψ = symbols(\"θ, ϕ, ψ\", real = true) ;\n\nTens{1, 3, Sym, Sym, Vec{3, Sym}, RotatedBasis{3, Sym}}\n# data: 3-element Vec{3, Sym}:\n 1\n 0\n 0\n# var: (:cont,)\n# basis: 3×3 Tensor{2, 3, Sym, 9}:\n -sin(ψ)⋅sin(ϕ) + cos(θ)⋅cos(ψ)⋅cos(ϕ)  -sin(ψ)⋅cos(θ)⋅cos(ϕ) - sin(ϕ)⋅cos(ψ)  sin(θ)⋅cos(ϕ)\n  sin(ψ)⋅cos(ϕ) + sin(ϕ)⋅cos(θ)⋅cos(ψ)  -sin(ψ)⋅sin(ϕ)⋅cos(θ) + cos(ψ)⋅cos(ϕ)  sin(θ)⋅sin(ϕ)\n                        -sin(θ)⋅cos(ψ)                          sin(θ)⋅sin(ψ)         cos(θ)\n``` \n\"\"\"\nfunction 𝐞ˢ(\n    ::Val{1},\n    θ::T1 = 0,\n    ϕ::T2 = 0,\n    ψ::T3 = 0;\n    canonical = false,\n) where {T1<:Number,T2<:Number,T3<:Number}\n    if canonical\n        return Tens(\n            Vec{3}([\n                -sin(ψ) * sin(ϕ) + cos(θ) * cos(ψ) * cos(ϕ),\n                sin(ψ) * cos(ϕ) + sin(ϕ) * cos(θ) * cos(ψ),\n                -sin(θ) * cos(ψ),\n            ]),\n        )\n    else\n        T = promote_type(T1, T2, T3)\n        return Tens(Vec{3}([one(T), zero(T), zero(T)]), Basis(θ, ϕ, ψ))\n    end\nend\nfunction 𝐞ˢ(\n    ::Val{2},\n    θ::T1 = 0,\n    ϕ::T2 = 0,\n    ψ::T3 = 0;\n    canonical = false,\n) where {T1<:Number,T2<:Number,T3<:Number}\n    if canonical\n        return Tens(\n            Vec{3}([\n                -sin(ψ) * cos(θ) * cos(ϕ) - sin(ϕ) * cos(ψ),\n                -sin(ψ) * sin(ϕ) * cos(θ) + cos(ψ) * cos(ϕ),\n                sin(θ) * sin(ψ),\n            ]),\n        )\n    else\n        T = promote_type(T1, T2, T3)\n        return Tens(Vec{3}([zero(T), one(T), zero(T)]), Basis(θ, ϕ, ψ))\n    end\nend\nfunction 𝐞ˢ(\n    ::Val{3},\n    θ::T1 = 0,\n    ϕ::T2 = 0,\n    ψ::T3 = 0;\n    canonical = false,\n) where {T1<:Number,T2<:Number,T3<:Number}\n    if canonical\n        return Tens(Vec{3}([sin(θ) * cos(ϕ), sin(θ) * sin(ϕ), cos(θ)]))\n    else\n        T = promote_type(T1, T2, T3)\n        return Tens(Vec{3}([zero(T), zero(T), one(T)]), Basis(θ, ϕ, ψ))\n    end\nend\n\nfor eb in (:𝐞, :𝐞ᵖ, :𝐞ᶜ, :𝐞ˢ)\n    @eval $eb(i::Integer, args...; kwargs...) = $eb(Val(i), args...; kwargs...)\nend\n\n\"\"\"\n    init_spherical(coords = (symbols(\"θ\", real = true), symbols(\"ϕ\", real = true), symbols(\"r\", positive = true)); canonical = false)\n\nReturns the coordinates, base vectors and basis of the spherical basis.\nTake care that the order of the 3 vectors is `𝐞ᶿ, 𝐞ᵠ, 𝐞ʳ` so that\nthe basis coincides with the canonical one when the angles are null and in consistency\nthe coordinates are ordered as `θ, ϕ, r`.\n\n# Examples\n```julia\njulia> coords, vectors, ℬˢ = init_spherical() ; θ, ϕ, r = coords ; 𝐞ᶿ, 𝐞ᵠ, 𝐞ʳ  = vectors ;\n``` \n\"\"\"\ninit_spherical(\n    coords = (\n        symbols(\"θ\", real = true),\n        symbols(\"ϕ\", real = true),\n        symbols(\"r\", positive = true),\n    );\n    canonical = false,\n) = Tuple(coords),\nntuple(i -> 𝐞ˢ(Val(i), coords[1:2]...; canonical = canonical), 3),\nSphericalBasis(coords[1:2]...)\n\n\"\"\"\n    init_rotated(coords = symbols(\"θ ϕ ψ\", real = true); canonical = false)\n\nReturns the angles, base vectors and basis of the rotated basis.\nNote that here the coordinates are angles and do not represent a valid parametrization of `ℝ³`\n\n# Examples\n```julia\njulia> angles, vectors, ℬʳ = init_rotated() ; θ, ϕ, ψ = angles ; 𝐞ᶿ, 𝐞ᵠ, 𝐞ʳ = vectors ;\n```\n\"\"\"\ninit_rotated(angles = symbols(\"θ ϕ ψ\", real = true); canonical = false) = Tuple(angles),\nntuple(i -> 𝐞ˢ(Val(i), angles...; canonical = canonical), 3),\nBasis(angles...)\n\n\"\"\"\n    rot3(θ, ϕ = 0, ψ = 0)\n\nReturns a rotation matrix with respect to the 3 Euler angles `θ, ϕ, ψ`\n\n# Examples\n```julia\njulia> cθ, cϕ, cψ, sθ, sϕ, sψ = symbols(\"cθ cϕ cψ sθ sϕ sψ\", real = true) ;\n\njulia> d = Dict(cos(θ) => cθ, cos(ϕ) => cϕ, cos(ψ) => cψ, sin(θ) => sθ, sin(ϕ) => sϕ, sin(ψ) => sψ) ;\n\njulia> subs.(rot3(θ, ϕ, ψ),d...)\n3×3 StaticArrays.SMatrix{3, 3, Sym, 9} with indices SOneTo(3)×SOneTo(3):\n cθ⋅cψ⋅cϕ - sψ⋅sϕ  -cθ⋅cϕ⋅sψ - cψ⋅sϕ  cϕ⋅sθ\n cθ⋅cψ⋅sϕ + cϕ⋅sψ  -cθ⋅sψ⋅sϕ + cψ⋅cϕ  sθ⋅sϕ\n           -cψ⋅sθ              sθ⋅sψ     cθ\n```\n\"\"\"\nrot3(θ, ϕ = 0, ψ = 0) = RotZYZ(ϕ, θ, ψ)\n\n\"\"\"\n    rot2(θ)\n\nReturns a 2D rotation matrix with respect to the angle `θ`\n\n# Examples\n```julia\njulia> rot2(θ)\n2×2 Tensor{2, 2, Sym, 4}:\n cos(θ)  -sin(θ)\n sin(θ)   cos(θ)\n```\n\"\"\"\nrot2(θ) = Tensor{2,2}((cos(θ), sin(θ), -sin(θ), cos(θ)))\n\n\n\"\"\"\n    rot6(θ, ϕ = 0, ψ = 0)\n\nReturns a rotation matrix with respect to the 3 Euler angles `θ, ϕ, ψ`\n\n# Examples\n```julia\njulia> cθ, cϕ, cψ, sθ, sϕ, sψ = symbols(\"cθ cϕ cψ sθ sϕ sψ\", real = true) ;\n\njulia> d = Dict(cos(θ) => cθ, cos(ϕ) => cϕ, cos(ψ) => cψ, sin(θ) => sθ, sin(ϕ) => sϕ, sin(ψ) => sψ) ;\n\njulia> R = Tens(subs.(rot3(θ, ϕ, ψ),d...))\nTens.TensCanonical{2, 3, Sym, Tensor{2, 3, Sym, 9}}\n# data: 3×3 Tensor{2, 3, Sym, 9}:\n cθ⋅cψ⋅cϕ - sψ⋅sϕ  -cθ⋅cϕ⋅sψ - cψ⋅sϕ  cϕ⋅sθ\n cθ⋅cψ⋅sϕ + cϕ⋅sψ  -cθ⋅sψ⋅sϕ + cψ⋅cϕ  sθ⋅sϕ\n           -cψ⋅sθ              sθ⋅sψ     cθ\n# var: (:cont, :cont)\n# basis: 3×3 Tens.LazyIdentity{3, Sym}:\n 1  0  0\n 0  1  0\n 0  0  1\n\njulia> RR = R ⊠ˢ R\nTens.TensCanonical{4, 3, Sym, SymmetricTensor{4, 3, Sym, 36}}\n# data: 6×6 Matrix{Sym}:\n                          (cθ*cψ*cϕ - sψ*sϕ)^2                            (-cθ*cϕ*sψ - cψ*sϕ)^2           cϕ^2*sθ^2                      √2⋅cϕ⋅sθ⋅(-cθ⋅cϕ⋅sψ - cψ⋅sϕ)                     √2⋅cϕ⋅sθ⋅(cθ⋅cψ⋅cϕ - sψ⋅sϕ)                                   √2⋅(cθ⋅cψ⋅cϕ - sψ⋅sϕ)⋅(-cθ⋅cϕ⋅sψ - cψ⋅sϕ)\n                          (cθ*cψ*sϕ + cϕ*sψ)^2                            (-cθ*sψ*sϕ + cψ*cϕ)^2           sθ^2*sϕ^2                      √2⋅sθ⋅sϕ⋅(-cθ⋅sψ⋅sϕ + cψ⋅cϕ)                     √2⋅sθ⋅sϕ⋅(cθ⋅cψ⋅sϕ + cϕ⋅sψ)                                   √2⋅(cθ⋅cψ⋅sϕ + cϕ⋅sψ)⋅(-cθ⋅sψ⋅sϕ + cψ⋅cϕ)\n                                     cψ^2*sθ^2                                        sθ^2*sψ^2                cθ^2                                       √2⋅cθ⋅sθ⋅sψ                                    -√2⋅cθ⋅cψ⋅sθ                                                              -sqrt(2)*cψ*sθ^2*sψ\n             -√2⋅cψ⋅sθ⋅(cθ⋅cψ⋅sϕ + cϕ⋅sψ)                √2⋅sθ⋅sψ⋅(-cθ⋅sψ⋅sϕ + cψ⋅cϕ)    √2⋅cθ⋅sθ⋅sϕ                    cθ*(-cθ*sψ*sϕ + cψ*cϕ) + sθ^2*sψ*sϕ                   cθ*(cθ*cψ*sϕ + cϕ*sψ) - cψ*sθ^2*sϕ                            -cψ⋅sθ⋅(-cθ⋅sψ⋅sϕ + cψ⋅cϕ) + sθ⋅sψ⋅(cθ⋅cψ⋅sϕ + cϕ⋅sψ)\n             -√2⋅cψ⋅sθ⋅(cθ⋅cψ⋅cϕ - sψ⋅sϕ)                √2⋅sθ⋅sψ⋅(-cθ⋅cϕ⋅sψ - cψ⋅sϕ)    √2⋅cθ⋅cϕ⋅sθ                    cθ*(-cθ*cϕ*sψ - cψ*sϕ) + cϕ*sθ^2*sψ                   cθ*(cθ*cψ*cϕ - sψ*sϕ) - cψ*cϕ*sθ^2                            -cψ⋅sθ⋅(-cθ⋅cϕ⋅sψ - cψ⋅sϕ) + sθ⋅sψ⋅(cθ⋅cψ⋅cϕ - sψ⋅sϕ)\n √2⋅(cθ⋅cψ⋅cϕ - sψ⋅sϕ)⋅(cθ⋅cψ⋅sϕ + cϕ⋅sψ)  √2⋅(-cθ⋅cϕ⋅sψ - cψ⋅sϕ)⋅(-cθ⋅sψ⋅sϕ + cψ⋅cϕ)  sqrt(2)*cϕ*sθ^2*sϕ  cϕ⋅sθ⋅(-cθ⋅sψ⋅sϕ + cψ⋅cϕ) + sθ⋅sϕ⋅(-cθ⋅cϕ⋅sψ - cψ⋅sϕ)  cϕ⋅sθ⋅(cθ⋅cψ⋅sϕ + cϕ⋅sψ) + sθ⋅sϕ⋅(cθ⋅cψ⋅cϕ - sψ⋅sϕ)  (cθ*cψ*cϕ - sψ*sϕ)*(-cθ*sψ*sϕ + cψ*cϕ) + (cθ*cψ*sϕ + cϕ*sψ)*(-cθ*cϕ*sψ - cψ*sϕ)\n# var: (:cont, :cont, :cont, :cont)\n# basis: 3×3 Tens.LazyIdentity{3, Sym}:\n 1  0  0\n 0  1  0\n 0  0  1\n\njulia> R6 = invKM(subs.(KM(rot6(θ, ϕ, ψ)),d...))\nTens.TensCanonical{4, 3, Sym, SymmetricTensor{4, 3, Sym, 36}}\n# data: 6×6 Matrix{Sym}:\n                          (cθ*cψ*cϕ - sψ*sϕ)^2                            (-cθ*cϕ*sψ - cψ*sϕ)^2           cϕ^2*sθ^2                      √2⋅cϕ⋅sθ⋅(-cθ⋅cϕ⋅sψ - cψ⋅sϕ)                     √2⋅cϕ⋅sθ⋅(cθ⋅cψ⋅cϕ - sψ⋅sϕ)                                   √2⋅(cθ⋅cψ⋅cϕ - sψ⋅sϕ)⋅(-cθ⋅cϕ⋅sψ - cψ⋅sϕ)\n                          (cθ*cψ*sϕ + cϕ*sψ)^2                            (-cθ*sψ*sϕ + cψ*cϕ)^2           sθ^2*sϕ^2                      √2⋅sθ⋅sϕ⋅(-cθ⋅sψ⋅sϕ + cψ⋅cϕ)                     √2⋅sθ⋅sϕ⋅(cθ⋅cψ⋅sϕ + cϕ⋅sψ)                                   √2⋅(cθ⋅cψ⋅sϕ + cϕ⋅sψ)⋅(-cθ⋅sψ⋅sϕ + cψ⋅cϕ)\n                                     cψ^2*sθ^2                                        sθ^2*sψ^2                cθ^2                                       √2⋅cθ⋅sθ⋅sψ                                    -√2⋅cθ⋅cψ⋅sθ                                                              -sqrt(2)*cψ*sθ^2*sψ\n             -√2⋅cψ⋅sθ⋅(cθ⋅cψ⋅sϕ + cϕ⋅sψ)                √2⋅sθ⋅sψ⋅(-cθ⋅sψ⋅sϕ + cψ⋅cϕ)    √2⋅cθ⋅sθ⋅sϕ                    cθ*(-cθ*sψ*sϕ + cψ*cϕ) + sθ^2*sψ*sϕ                   cθ*(cθ*cψ*sϕ + cϕ*sψ) - cψ*sθ^2*sϕ                            -cψ⋅sθ⋅(-cθ⋅sψ⋅sϕ + cψ⋅cϕ) + sθ⋅sψ⋅(cθ⋅cψ⋅sϕ + cϕ⋅sψ)\n             -√2⋅cψ⋅sθ⋅(cθ⋅cψ⋅cϕ - sψ⋅sϕ)                √2⋅sθ⋅sψ⋅(-cθ⋅cϕ⋅sψ - cψ⋅sϕ)    √2⋅cθ⋅cϕ⋅sθ                    cθ*(-cθ*cϕ*sψ - cψ*sϕ) + cϕ*sθ^2*sψ                   cθ*(cθ*cψ*cϕ - sψ*sϕ) - cψ*cϕ*sθ^2                            -cψ⋅sθ⋅(-cθ⋅cϕ⋅sψ - cψ⋅sϕ) + sθ⋅sψ⋅(cθ⋅cψ⋅cϕ - sψ⋅sϕ)\n √2⋅(cθ⋅cψ⋅cϕ - sψ⋅sϕ)⋅(cθ⋅cψ⋅sϕ + cϕ⋅sψ)  √2⋅(-cθ⋅cϕ⋅sψ - cψ⋅sϕ)⋅(-cθ⋅sψ⋅sϕ + cψ⋅cϕ)  sqrt(2)*cde Liv Lehn ϕ*sθ^2*sϕ  cϕ⋅sθ⋅(-cθ⋅sψ⋅sϕ + cψ⋅cϕ) + sθ⋅sϕ⋅(-cθ⋅cϕ⋅sψ - cψ⋅sϕ)  cϕ⋅sθ⋅(cθ⋅cψ⋅sϕ + cϕ⋅sψ) + sθ⋅sϕ⋅(cθ⋅cψ⋅cϕ - sψ⋅sϕ)  (cθ*cψ*cϕ - sψ*sϕ)*(-cθ*sψ*sϕ + cψ*cϕ) + (cθ*cψ*sϕ + cϕ*sψ)*(-cθ*cϕ*sψ - cψ*sϕ)\n# var: (:cont, :cont, :cont, :cont)\n# basis: 3×3 Tens.LazyIdentity{3, Sym}:\n 1  0  0\n 0  1  0\n 0  0  1\n\njulia> R6 == RR\ntrue\n```\n\"\"\"\nfunction rot6(θ, ϕ = 0, ψ = 0)\n    R = TensCanonical(rot3(θ, ϕ, ψ))\n    return sboxtimes(R, R)\nend\n\nexport LeviCivita\nexport 𝐞, 𝐞ᵖ, 𝐞ᶜ, 𝐞ˢ\nexport init_cartesian, init_polar, init_cylindrical, init_spherical, init_rotated\nexport rot2, rot3, rot6\n", "meta": {"hexsha": "56ed696e75f525c26bf8046cc1eec620a99a98de", "size": 13541, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/special_tens.jl", "max_stars_repo_name": "jfbarthelemy/TensND.jl", "max_stars_repo_head_hexsha": "668c22129e9b074ab67ca8752f518976266ef0c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-08-19T19:59:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T23:16:22.000Z", "max_issues_repo_path": "src/special_tens.jl", "max_issues_repo_name": "jfbarthelemy/TensND.jl", "max_issues_repo_head_hexsha": "668c22129e9b074ab67ca8752f518976266ef0c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/special_tens.jl", "max_forks_repo_name": "jfbarthelemy/TensND.jl", "max_forks_repo_head_hexsha": "668c22129e9b074ab67ca8752f518976266ef0c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8994845361, "max_line_length": 306, "alphanum_fraction": 0.4953843882, "num_tokens": 7141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.7945538003703864}}
{"text": "module EqualizerFilters\n\nimport DSP.Biquad\nimport DSP.SecondOrderSections\nusing DSP\n\ninclude(\"equalizerAPOstrings.jl\")\ninclude(\"DSPjlBiquads.jl\")\n\nexport LP, HP, BP, NO, AP, PK, LS, HS, Biquad, eqAPOstring, SecondOrderSections\n\n#default sampling rate\nfs = 48e3\n\n\"\"\"\n    EqualizerFilters.sampling_rate(custom_sampling_rate)\n\nSet the sampling rate for calculation of the biquads in Hz.\n\nDefaults to 48 kHz.\n\"\"\"\nfunction sampling_rate(custom_sampling_rate)\n    global fs = custom_sampling_rate\nend\n\n\"\"\"\n    EqualizerFilters.sampling_rate()\n\nReturn the current sampling rate for biquad calculation in Hz.\n\nDefaults to 48 kHz.\n\"\"\"\nfunction sampling_rate()\n    fs\nend\n\n\"\"\"\n    biquadPrecalculations(dbGain, freq, srate, Q)\n\nReturns `(A, sn, cs, alpha, beta)` that have to be calculated for all\nfilter types.\n\nThe parameter A is not needed for gain-less filters.\nThe calling functions simply pass 0 dB Gain and do not use the returned parameter\n`A`.\n\"\"\"\nfunction biquadPrecalculations(dbGain, freq, srate, Q)\n    A = 10^(dbGain/40)\n    omega = 2pi * freq / srate\n    sn = sin(omega)\n    cs = cos(omega)\n    alpha = sn / (2 * Q)\n    beta = 2 * sqrt(A) * alpha\n    return A, sn, cs, alpha, beta\nend\n\n\"\"\"\n    LP(f, Q, fs=sampling_rate)\n\nReturn lowpass biquad at frequency `f` in Hz with quality factor `Q`.\n\nThis second order lowpass falls of with 12 dB/oct.\n\nIf not given in the arguments, the sampling rate defaults to 48 kHz or can be\nset with [`EqualizerFilters.sampling_rate`](@ref).\n\"\"\"\nfunction LP(f, Q, fs=fs)\n    A, sn, cs, alpha, beta = biquadPrecalculations(0, f, fs, Q)\n    b0 = (1 - cs) / 2\n    b1 = 1 - cs\n    b2 = (1 - cs) / 2\n    a0 = 1 + alpha\n    a1 = -2 * cs\n    a2 = 1 - alpha\n    biquadCoefs = [b0, b1, b2, a1, a2]./a0\n    return Biquad(biquadCoefs...)\nend\n\n\"\"\"\n    HP(f, Q, fs=sampling_rate)\n\nReturn highpass biquad at frequency `f` in Hz with quality factor `Q`.\n\nThis second order highpass falls of with 12 dB/oct.\n\nIf not given in the arguments, the sampling rate defaults to 48 kHz or can be\nset with [`EqualizerFilters.sampling_rate`](@ref).\n\"\"\"\nfunction HP(f, Q, fs=fs)\n    A, sn, cs, alpha, beta = biquadPrecalculations(0, f, fs, Q)\n    b0 = (1 + cs) / 2;\n    b1 = -(1 + cs);\n    b2 = (1 + cs) / 2;\n    a0 = 1 + alpha;\n    a1 = -2 * cs;\n    a2 = 1 - alpha;\n    biquadCoefs = [b0, b1, b2, a1, a2]./a0\n    return Biquad(biquadCoefs...)\nend\n\n\"\"\"\n    BP(f, Q, fs=sampling_rate)\n\nReturn bandpass biquad at frequency `f` in Hz with quality factor `Q`.\n\nIf not given in the arguments, the sampling rate defaults to 48 kHz or can be\nset with [`EqualizerFilters.sampling_rate`](@ref).\n\"\"\"\nfunction BP(f, Q, fs=fs)\n    A, sn, cs, alpha, beta = biquadPrecalculations(0, f, fs, Q)\n    b0 = alpha;\n    b1 = 0;\n    b2 = -alpha;\n    a0 = 1 + alpha;\n    a1 = -2 * cs;\n    a2 = 1 - alpha;\n    biquadCoefs = [b0, b1, b2, a1, a2]./a0\n    return Biquad(biquadCoefs...)\nend\n\n\"\"\"\n    NO(f, Q, fs=sampling_rate)\n\nReturn notch biquad at frequency `f` in Hz with quality factor `Q`.\n\nIf not given in the arguments, the sampling rate defaults to 48 kHz or can be\nset with [`EqualizerFilters.sampling_rate`](@ref).\n\"\"\"\nfunction NO(f, Q, fs=fs)\n    A, sn, cs, alpha, beta = biquadPrecalculations(0, f, fs, Q)\n    b0 = 1;\n    b1 = -2 * cs;\n    b2 = 1;\n    a0 = 1 + alpha;\n    a1 = -2 * cs;\n    a2 = 1 - alpha;\n    biquadCoefs = [b0, b1, b2, a1, a2]./a0\n    return Biquad(biquadCoefs...)\nend\n\n\"\"\"\n    AP(f, Q, fs=sampling_rate)\n\nReturn allpass biquad at frequency `f` in Hz with quality factor `Q`.\n\nThis second order allpass rotates the phase by a total of ``2π``.\n\nIf not given in the arguments, the sampling rate defaults to 48 kHz or can be\nset with [`EqualizerFilters.sampling_rate`](@ref).\n\"\"\"\nfunction AP(f, Q, fs=fs)\n    A, sn, cs, alpha, beta = biquadPrecalculations(0, f, fs, Q)\n    b0 = 1 - alpha;\n    b1 = -2 * cs;\n    b2 = 1 + alpha;\n    a0 = 1 + alpha;\n    a1 = -2 * cs;\n    a2 = 1 - alpha;\n    biquadCoefs = [b0, b1, b2, a1, a2]./a0\n    return Biquad(biquadCoefs...)\nend\n\n\"\"\"\n    PK(f, dbGain, Q, fs=sampling_rate)\n\nReturn peaking biquad with Gain `dbGain` in dB at frequency `f` in Hz\nwith quality factor `Q`.\n\nIn this implementation the Gain at 0 Hz and at the Nyquist frequency will\nalways be 0 dB. For an Orfanidis-like peak EQ with analog-inspired\nNyquist-gain see the package LakeBiquads.jl.\n\nIf not given in the arguments, the sampling rate defaults to 48 kHz or can be\nset with [`EqualizerFilters.sampling_rate`](@ref).\n\"\"\"\nfunction PK(f, dbGain, Q, fs=fs)\n    A, sn, cs, alpha, beta = biquadPrecalculations(dbGain, f, fs, Q)\n    b0 = 1 + (alpha * A);\n    b1 = -2 * cs;\n    b2 = 1 - (alpha * A);\n    a0 = 1 + (alpha / A);\n    a1 = -2 * cs;\n    a2 = 1 - (alpha / A);\n    biquadCoefs = [b0, b1, b2, a1, a2]./a0\n    return Biquad(biquadCoefs...)\nend\n\n\"\"\"\n    LS(f, dbGain, Q, fs=sampling_rate)\n\nReturn low shelf biquad with Gain `dbGain` in dB, center frequency `f` in Hz and\nquality factor `Q`.\n\nIf not given in the arguments, the sampling rate defaults to 48 kHz or can be\nset with [`EqualizerFilters.sampling_rate`](@ref).\n\"\"\"\nfunction LS(f, dbGain, Q, fs=fs)\n    A, sn, cs, alpha, beta = biquadPrecalculations(dbGain, f, fs, Q)\n    b0 = A * ((A + 1) - (A - 1) * cs + beta);\n    b1 = 2 * A * ((A - 1) - (A + 1) * cs);\n    b2 = A * ((A + 1) - (A - 1) * cs - beta);\n    a0 = (A + 1) + (A - 1) * cs + beta;\n    a1 = -2 * ((A - 1) + (A + 1) * cs);\n    a2 = (A + 1) + (A - 1) * cs - beta;\n    biquadCoefs = [b0, b1, b2, a1, a2]./a0\n    return Biquad(biquadCoefs...)\nend\n\n\"\"\"\n    HS(f, dbGain, Q, fs=sampling_rate)\n\nReturn high shelf biquad with Gain `dbGain` in dB, center frequency `f` in Hz and\nquality factor `Q`.\n\nIf not given in the arguments, the sampling rate defaults to 48 kHz or can be\nset with [`EqualizerFilters.sampling_rate`](@ref).\n\"\"\"\nfunction HS(f, dbGain, Q, fs=fs)\n    A, sn, cs, alpha, beta = biquadPrecalculations(dbGain, f, fs, Q)\n    b0 = A * ((A + 1) + (A - 1) * cs + beta);\n    b1 = -2 * A * ((A - 1) + (A + 1) * cs);\n    b2 = A * ((A + 1) + (A - 1) * cs - beta);\n    a0 = (A + 1) - (A - 1) * cs + beta;\n    a1 = 2 * ((A - 1) - (A + 1) * cs);\n    a2 = (A + 1) - (A - 1) * cs - beta;\n    biquadCoefs = [b0, b1, b2, a1, a2]./a0\n    return Biquad(biquadCoefs...)\nend\n\nend # module\n", "meta": {"hexsha": "61c8f30849c5e40f5825643abb8d264da33088b0", "size": 6210, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/EqualizerFilters.jl", "max_stars_repo_name": "Firionus/EqualizerFilters.jl", "max_stars_repo_head_hexsha": "aa2415bc5981b67bcddcbfac77c46c1249e69a24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-05T21:51:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-05T21:51:30.000Z", "max_issues_repo_path": "src/EqualizerFilters.jl", "max_issues_repo_name": "Firionus/EqualizerFilters.jl", "max_issues_repo_head_hexsha": "aa2415bc5981b67bcddcbfac77c46c1249e69a24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-12-11T21:31:34.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-11T21:39:03.000Z", "max_forks_repo_path": "src/EqualizerFilters.jl", "max_forks_repo_name": "Firionus/EqualizerFilters.jl", "max_forks_repo_head_hexsha": "aa2415bc5981b67bcddcbfac77c46c1249e69a24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8831168831, "max_line_length": 81, "alphanum_fraction": 0.6198067633, "num_tokens": 2224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7945301805844385}}
{"text": "# Atkinson.jl\n\n\n###### atkinson #####\n\"\"\"\n    atkinson(v, ϵ)\n\nCompute the Atkinson Index of a vector `v` at a specified inequality \naversion parameter `ϵ`.\n\n# Examples\n```julia\njulia> using Inequality\njulia> atkinson([8, 5, 1, 3, 5, 6, 7, 6, 3], 1.2)\n0.1631765870035865\n```\n\"\"\"\nfunction atkinson(v::AbstractVector{<:Real}, ϵ::Real)::Float64\n\n    ϵ >= 0 ? nothing : throw(ArgumentError(\"`ϵ` must be larger or equal than 0\"))\n\n    if ϵ == 1\n        v = v[v .!= 0]\n        return 1 - (exp.(mean(log.(v)))/mean(v))\n    elseif ϵ < 1\n        return 1 - mean( (v./mean(v)).^(1-ϵ) ).^(1/(1-ϵ))\n    else\n        v = v[v .!= 0]\n        return 1 - mean( (v./mean(v)).^(1-ϵ) ).^(1/(1-ϵ))\n    end \nend\n\n\n###### weighted atkinson #####\n\"\"\"\n    atkinson(v, w, ϵ)\n\nCompute the weighted Atkinson Index of a vector `v` at a specified inequality \naversion parameter `ϵ`, using weights given by a weight vector `w`.\n\nWeights must not be negative, missing or NaN. The weights and data vectors must have the same length.\n\n# Examples\n```julia\njulia> using Inequality\njulia> atkinson([8, 5, 1, 3], [0.1,0.5,0.3,0.8], 1.2)\n0.1681319821792493\n```\n\"\"\"\nfunction atkinson(v::AbstractVector{<:Real}, w::AbstractVector{<:Real}, ϵ::Real)::Float64\n\n    ϵ >= 0 ? nothing : throw(ArgumentError(\"`ϵ` must be larger or equal than 0\"))\n    checks_weights(v, w)\n   \n    v = v/Statistics.mean(v)\n    w = w/sum(w)\n \n    if ϵ == 1\n        w = w[v .!= 0]\n        v = v[v .!= 0]\n\n        return 1 - (prod(exp.(w .* log.(v)))/sum(v .* w) )\n    elseif ϵ < 1\n        return 1-(sum(((v/sum(v.* w)).^(1-ϵ)).*w)).^(1/(1-ϵ))\n    else \n        w = w[v .!= 0]\n        v = v[v .!= 0]\n        \n        return 1-(sum(((v/sum(v.* w)).^(1-ϵ)).*w)).^(1/(1-ϵ))\n    end\nend\n\n\n\n\nfunction atkinson(v::AbstractVector{<:Real}, w::AbstractWeights, ϵ::Real)::Float64\n\n    ϵ >= 0 ? nothing : throw(ArgumentError(\"`ϵ` must be larger or equal than 0\"))\n    checks_weights(v, w)\n   \n    v = v/Statistics.mean(v)\n    w = w/w.sum\n \n    if ϵ == 1\n        w = w[v .!= 0]\n        v = v[v .!= 0]\n\n        return 1 - (prod(exp.(w .* log.(v)))/sum(v .* w) )\n    elseif ϵ < 1\n        return 1-(sum(((v/sum(v.* w)).^(1-ϵ)).*w)).^(1/(1-ϵ))\n    else \n        w = w[v .!= 0]\n        v = v[v .!= 0]\n        \n        return 1-(sum(((v/sum(v.* w)).^(1-ϵ)).*w)).^(1/(1-ϵ))\n    end\nend\n\n\n\"\"\"\n    watkinson(v, w, p)\n\nCompute the atkinson index of `v` with weights `w` and inequality aversion parameter 'ϵ'. See also [`atkinson`](@atkinson)\n\"\"\"\nwatkinson(v::AbstractVector{<:Real}, w::AbstractVector{<:Real}, ϵ::Real) = atkinson(v, w, ϵ)\n\nwatkinson(v::AbstractVector{<:Real}, w::AbstractWeights, ϵ::Real) = atkinson(v, w, ϵ)", "meta": {"hexsha": "2f04f052a0de8b6e151887a4c5c4aebe5125e078", "size": 2633, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Atkinson.jl", "max_stars_repo_name": "JosepER/Inequality.jl", "max_stars_repo_head_hexsha": "fd1bb964856dc37eb2648f3825123de9d8181578", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-03-12T13:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T18:45:45.000Z", "max_issues_repo_path": "src/Atkinson.jl", "max_issues_repo_name": "JosepER/Inequality.jl", "max_issues_repo_head_hexsha": "fd1bb964856dc37eb2648f3825123de9d8181578", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Atkinson.jl", "max_forks_repo_name": "JosepER/Inequality.jl", "max_forks_repo_head_hexsha": "fd1bb964856dc37eb2648f3825123de9d8181578", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6074766355, "max_line_length": 122, "alphanum_fraction": 0.5393087733, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7945301721852572}}
{"text": "###\n#   Set operations\n###\n\n# Envolpe/hull. Keeps it as a IntervalUnion\nenv(x :: IntervalU) = IntervalU([hull(x.v)])\nhull(x :: IntervalU) = IntervalU([hull(x.v)])\n\n\n# Computes the complement of a IntervalUnion\nfunction complement(x :: IntervalU)\n\n    v = sort(x.v)\n    vLo = left.(v)\n    vHi = right.(v)\n\n    vLo[1] == -∞ ? popfirst!(vLo) : pushfirst!(vHi, -∞)\n    vHi[end] == ∞ ? pop!(vHi) : push!(vLo, ∞)\n\n\n    complements = interval.(vHi,vLo)\n\n    return intervalU(complements)\nend\n\ncomplement(x :: Interval) = complement(intervalU(x))\n\n\n# bisect x at α\nfunction bisect( x :: IntervalU, α = 0)\n\n    v = deepcopy(x.v)\n\n    αIn = α .∈ v\n    these = findall(αIn .== 1)\n\n    if isempty(these); return x ; end\n\n    this = popat!(v, these[1])\n\n    β = (α - this.lo) /(this.hi - this.lo)\n\n    bs = bisect(this, β)\n\n    new = IntervalU(v ∪ bs[1] ∪ bs[2])\n    new = remove_empties(new)\n    sort!(new.v)\n    return new\n\nend\n\n\nfunction intersect(x :: IntervalU, y :: IntervalU)\n    intersects = [intersect(xv, yv) for xv in x.v, yv in y.v]\n    return intervalU(intersects[:])\nend\n\nfunction intersect(x :: IntervalU, y :: Interval)\n    intersects = [intersect(xv, y) for xv in x.v]\n    return intervalU(intersects[:])\nend\n\nfunction intersect(x :: Interval, y :: IntervalU)\n    intersects = [intersect(x, yv) for yv in y.v]\n    return intervalU(intersects[:])\nend\n\n\nfunction setdiff(x :: IntervalU, y :: IntervalU)\n    yc = complement(y)\n    return intersect(x, yc)\nend\n\n\\(x :: IntervalU, y :: IntervalU) = setdiff(x, y)\n\\(x :: Interval, y :: IntervalU) = setdiff(intervalU(x), y)\n\\(x :: IntervalU, y :: Interval) = setdiff(x, intervalU(y))\n\nfunction ⊂(x :: IntervalU, y :: IntervalU)\n    issubs = [xv .⊂ y.v for xv in x.v]\n    return all(any.(issubs))\nend\n\nfunction ⊂(x :: Interval, y :: IntervalU)\n    if length(y.v) == 1; return x ⊂ y; end\n    issubs = x .⊆ y.v\n    return any(issubs)\nend\n\nfunction ⊂( x::IntervalU, y :: Interval)\n    issubs = x.v .⊂ y\n    return all(issubs)\nend\n\nfunction ⊆(x :: IntervalU, y :: IntervalU)\n    issubs = [xv .⊆ y.v for xv in x.v]\n    return all(any.(issubs))\nend\n\nfunction ⊆(x :: Interval, y :: IntervalU)\n    issubs = x .⊆ y.v\n    return any(issubs)\nend\n\nfunction ⊆( x::IntervalU, y :: Interval)\n    issubs = x.v .⊆ y\n    return all(issubs)\nend\n", "meta": {"hexsha": "7ecaa52dab2168440b30d76a9cc3d27e703700a0", "size": 2272, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/set_operations.jl", "max_stars_repo_name": "dpsanders/IntervalUnionArithmetic.jl", "max_stars_repo_head_hexsha": "e6561b4fbaf9428488a73bf7eb734c413fdd9fbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/set_operations.jl", "max_issues_repo_name": "dpsanders/IntervalUnionArithmetic.jl", "max_issues_repo_head_hexsha": "e6561b4fbaf9428488a73bf7eb734c413fdd9fbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/set_operations.jl", "max_forks_repo_name": "dpsanders/IntervalUnionArithmetic.jl", "max_forks_repo_head_hexsha": "e6561b4fbaf9428488a73bf7eb734c413fdd9fbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.037037037, "max_line_length": 61, "alphanum_fraction": 0.6034330986, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.7945301706215093}}
{"text": "## PART 1\n\nprintln(\"Part 1\");\n\n# Define functions for this part\nfunction f1(v̄)\n    return v̄[:,1] ./ v̄[:,2];\nend\n\nfunction f2(v̄)\n    return exp( v̄[:,3] - v̄[:,4] );\nend\n\nfunction f3(v̄)\n    logs = Float64[];\n    for vv in v̄[:,5]\n        push!(logs,log(vv));\n    end\n    return ( v̄[:,1]./v̄[:,2] + v̄[:,3]./v̄[:,4] ) .* logs;\nend\n\n# Calculate f1, f2, and f3 for these means\nprintln(\"RESUMING QUESTION 2\");\nprintln(\"\\n\\tCalculating functions of means f1v1, f2v1, ...\");\nf1N1 = f1(v̄1);\nf2N1 = f2(v̄1);\nf3N1 = f3(v̄1);\n\nf1N2 = f1(v̄2);\nf2N2 = f2(v̄2);\nf3N2 = f3(v̄2);\n\n# Find standard deviations\nprintln(\"\\n\\tCalculating standard deviations of the functions\");\nσ̂truef1N1 = std(f1N1);\nσ̂truef2N1 = std(f2N1);\nσ̂truef3N1 = std(f3N1);\n\nσ̂truef1N2 = std(f1N2);\nσ̂truef2N2 = std(f2N2);\nσ̂truef3N2 = std(f3N2);\n\n", "meta": {"hexsha": "cf6161a8dac43c479f3708a0c871618fbcdd2fbe", "size": 810, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "set03/q2/p1.jl", "max_stars_repo_name": "stefco/g6080", "max_stars_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "set03/q2/p1.jl", "max_issues_repo_name": "stefco/g6080", "max_issues_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "set03/q2/p1.jl", "max_forks_repo_name": "stefco/g6080", "max_forks_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8372093023, "max_line_length": 64, "alphanum_fraction": 0.5913580247, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806522, "lm_q2_score": 0.8539127510928477, "lm_q1q2_score": 0.7945301621394073}}
{"text": "function chebyshev_polynomial_derivative(order::S,x::T) where {T<:AbstractFloat,S<:Integer}\n\n  polynomial    = Array{T}(undef,1,order+1)\n  poly_deriv    = Array{T}(undef,1,order+1)\n  polynomial[1] = one(T)\n  poly_deriv[1] = zero(T)\n\n  for i = 2:order+1\n    if i == 2\n      polynomial[i] = x\n      poly_deriv[i] = one(T)\n    else\n      polynomial[i] = 2*x*polynomial[i-1]-polynomial[i-2]\n      poly_deriv[i] = 2*polynomial[i-1]+2*x*poly_deriv[i-1]-poly_deriv[i-2] \n    end\n  end\n\n  return poly_deriv\n\nend\n\nfunction chebyshev_polynomial_derivative(order::S,x::Array{T,1}) where {T<:AbstractFloat,S<:Integer}\n\n  poly_deriv = Array{T,2}(undef,length(x),order+1)\n\n  for i = 1:length(x)\n    poly_deriv[i,:] = chebyshev_polynomial_derivative(order,x[i])\n  end\n\n  return poly_deriv\n\nend\n", "meta": {"hexsha": "e25d52bfd6e981a8bb86a7873d15f97a7416f47e", "size": 779, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chebyshev_polynomial_derivative.jl", "max_stars_repo_name": "RJDennis/SmolyakApprox.jl", "max_stars_repo_head_hexsha": "42a669e34fb2417341b24936c1b72873c3c25857", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2018-04-23T15:47:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T10:38:53.000Z", "max_issues_repo_path": "src/chebyshev_polynomial_derivative.jl", "max_issues_repo_name": "RJDennis/SmolyakApprox.jl", "max_issues_repo_head_hexsha": "42a669e34fb2417341b24936c1b72873c3c25857", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2017-08-08T00:07:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T11:53:45.000Z", "max_forks_repo_path": "src/chebyshev_polynomial_derivative.jl", "max_forks_repo_name": "RJDennis/SmolyakApprox.jl", "max_forks_repo_head_hexsha": "42a669e34fb2417341b24936c1b72873c3c25857", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-12-22T21:24:48.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-07T21:47:10.000Z", "avg_line_length": 23.6060606061, "max_line_length": 100, "alphanum_fraction": 0.6636713736, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.79445123015022}}
{"text": "import RationalApproximations: aaa_v1, aaa_v2, locate_extrema_idx\nimport RationalApproximations: RationalFunc, equioscillation!, minimax\nusing PyPlot\n\nf = exp\nS = range(-1, 1, length=201)\nF = f.(S)\ntol = 1e-6\nmax_m = 5\nr, err = aaa_v1(F, S, max_m, tol)\nm = length(r)\n\nfigure(1)\nsupp_pt = r[m].supp_pt\nresid = F - r[m].(S)\nplot(S, resid, supp_pt, f.(supp_pt)-r[m].(supp_pt), \"o\")\nlegend((L\"$f-r$\", \"support points\"))\ntitle(\"Result using aaa_v1 (m = $m)\")\ngrid(true)\nxylims = axis()\n\nfigure(2)\nr, err = aaa_v2(F, S, max_m, tol)\nm = length(r)\nsupp_pt = r[m].supp_pt\nresid = F - r[m].(S)\nplot(S, resid, supp_pt, f.(supp_pt)-r[m].(supp_pt), \"o\")\nlegend((L\"$f-r$\", \"support points\"))\ntitle(\"Result using aaa_v2 (m = $m)\")\ngrid(true)\naxis(xylims)\n\nidx = locate_extrema_idx(resid, m)\nx = S[idx]\nfigure(3)\nplot(S, resid, x, f.(x)-r[m].(x), \"o\")\nlegend((L\"$f-r$\", \"extrema\"))\ntitle(\"Locate extrema\")\ngrid(true)\naxis(xylims)\n\nclamp = :no\nα, β, λ = equioscillation!(f, x, supp_pt, clamp)\nnew_r = RationalFunc(α, β, supp_pt)\nfigure(4)\nplot(S, f.(S) - new_r.(S),\n     [-1.0, 1.0, NaN, -1.0, 1.0], [λ, λ, NaN, -λ, -λ], \":k\",\n     x, f.(x)-new_r.(x), \"o\")\ngrid(true)\ntitle(\"Equioscillation procedure\")\naxis(xylims)\n\nmax_iterations = 4\nx = S[idx]\nr, zmin, zmax = minimax(f, x, supp_pt, (-1.0,1.0), max_iterations, clamp)\nm = length(r)\nfigure(5)\nplot(S, f.(S) - r[m].(S), x, f.(x) - r[m].(x), \"o\")\ngrid(true)\ntitle(\"Result after $m Remez iterations\")\naxis(xylims)\n\n", "meta": {"hexsha": "16b222b07b2d77f44366c79b6653ec089d350749", "size": 1447, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/exp_minimax.jl", "max_stars_repo_name": "billmclean/RationalApproximations", "max_stars_repo_head_hexsha": "daf519b2ee3b3d4eeafb0a0c29f78d494030b48c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/exp_minimax.jl", "max_issues_repo_name": "billmclean/RationalApproximations", "max_issues_repo_head_hexsha": "daf519b2ee3b3d4eeafb0a0c29f78d494030b48c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/exp_minimax.jl", "max_forks_repo_name": "billmclean/RationalApproximations", "max_forks_repo_head_hexsha": "daf519b2ee3b3d4eeafb0a0c29f78d494030b48c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9682539683, "max_line_length": 73, "alphanum_fraction": 0.6247408431, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.924141826246517, "lm_q2_score": 0.8596637433190939, "lm_q1q2_score": 0.7944512217088244}}
{"text": "module BigCombinatorics\n\nusing Combinatorics\n\nexport Fibonacci\nexport Factorial, DoubleFactorial, FallingFactorial, RisingFactorial\nexport Binomial, Catalan\nexport Derangements, MultiChoose, Multinomial\nexport Bell, Stirling1, Stirling2\nexport IntPartitions, IntPartitionsDistinct\nexport Euler, PowerSum\n\n_master_table = Dict{Function,Dict}()\n\nfunction _save(f::Function, x, val::BigInt)\n    d = _master_table[f]\n    d[x] = val\n    nothing\nend\n\nfunction _has(f::Function, x)::Bool\n    d = _master_table[f]\n    return haskey(d,x)\nend\n\nfunction _get(f::Function, x)::BigInt\n    d = _master_table[f]\n    return d[x]\nend\n\nfunction _make(f::Function, T::Type)\n    _master_table[f] = Dict{T,BigInt}()\n    nothing\nend\n\n\"\"\"\n`BigCombinatorics.cache_report()` reports how many\nentries are saved for each function in the `BigCombinatorics`\nmodule.\n\"\"\"\nfunction cache_report()\n    total = 0\n    for func in keys(_master_table)\n        parse_func = split(string(func),\".\")\n        func_name = last(parse_func)  \n        sz = length(_master_table[func])\n        total += sz\n        println(\"$sz\\t$func_name\")\n    end\n    println()\n    println(\"$total\\tTotal entries\")\n    nothing\nend\n\n\n\"\"\"\n`BigCombinatorics.cache_clear(f)` clears the cached values for\nthe function `f`. Returns `false` if `f` values are not cached.\n\n`BigCombinatorics.cache_clear()` clears all cached values.\n\"\"\"\nfunction cache_clear(f::Function)::Bool\n    if !haskey(_master_table,f)\n        return false\n    end\n    tab = _master_table[f]\n    for k in keys(tab)\n        delete!(tab,k)\n    end\n    return true\nend\n\nfunction cache_clear()\n    for f in keys(_master_table)\n        cache_clear(f)\n    end\n    true\nend\n\n\"\"\"\n`Fibonacci(n)` returns the `n`-th Fibonacci number.\nWe begin with `Fibonacci(0)==0` and `Fibonacci(1)==1`.\n\"\"\"\nfunction Fibonacci(n::Integer)::BigInt\n  if n<0\n    throw(DomainError(n,\"argument must be nonngative\"))\n  end\n  if n==0\n    return big(0)\n  end\n  if n==1\n    return big(1)\n  end\n  if _has(Fibonacci,n)\n      return _get(Fibonacci,n)\n  end\n  val = Fibonacci(n-1)+Fibonacci(n-2)\n  _save(Fibonacci,n,val)\n  return val\nend\n\n\n_make(Fibonacci,Integer)\n\n\"\"\"\n`Factorial(n)` returns `n!` for nonnegative integers `n`.\n`Factorial(n,k)` returns `n!/k!` (to be consistent with Julia's\n`factorial`.) Requires `0 <= k <= n`.\n\nSee also `FallingFactorial` and `RisingFactorial`.\n\"\"\"\nfunction Factorial(n::Integer)::BigInt\n    if n < 0\n        throw(DomainError(n,\"argument must be nonngative\"))\n    end\n    if n <= 1\n        return big(1)\n    end\n    if _has(Factorial,n)\n        return _get(Factorial,n)\n    end\n    val = big(n) * Factorial(n-1)\n    _save(Factorial,n,val)\n    return val\nend\n\nfunction Factorial(n::Integer,k::Integer)::BigInt\n    if k>n\n        throw(DomainError((n,k),\"$k cannot exceed $n\"))\n    end\n    return div(Factorial(n),Factorial(k))\nend\n_make(Factorial,Integer)\n\n\"\"\"\n`FallingFactorial(n,k)` returns `n*(n-1)*(n-2)*...*(n-k+1)`\n(with a total of `k` factors). Requires `n,k >= 0`.\nIf `k>n` then `0` is returned.\n\"\"\"\nfunction FallingFactorial(n::Integer, k::Integer)::BigInt\n  if n<0 || k<0\n    throw(DomainError((n,k),\" arguments must be nonnegative\"))\n  end\n  if k>n\n    return big(0)\n  end\n  return Factorial(n,n-k)\nend\n\n\n\"\"\"\n`RisingFactorial(n,k)` returns `n*(n+1)*(n+2)*...*(n+k-1)`\n(with a total of `k` factors). Requires `n,k >= 0`.\n\"\"\"\nfunction RisingFactorial(n::Integer,k::Integer)::BigInt\n  if n<0 || k<0\n    throw(DomainError((n,k),\"arguments must be nonnegative\"))\n  end\n  if k==0\n    return big(1)\n  end\n  if n==0\n    return big(0)\n  end\n\n  return FallingFactorial(n+k-1,k)\nend\n\n\n\"\"\"\n`DoubleFactorial(n)` returns `n!!`, i.e.,\n`n*(n-2)*...` with `(-1)!! == 0!! == 1!! == 1`.\n\"\"\"\nfunction DoubleFactorial(n::Integer)::BigInt\n  if n<-1\n    throw(DomainError(n,\"argument must be at least -1\"))\n  end\n  if n<2\n    return big(1)\n  end\n  if _has(DoubleFactorial,n)\n      return _get(DoubleFactorial,n)\n  end\n  val = n * DoubleFactorial(n-2)\n  _save(DoubleFactorial,n,val)\n  return val\nend\n_make(DoubleFactorial,Integer)\n\n\n\"\"\"\n`Binomial(n,k)` returns the binomial coefficient `n`-choose-`k`.\nThis is the number of `k`-element subsets of an `n`-element set.\n\"\"\"\nBinomial(n::Integer, k::Integer) = binomial(big(n),big(k))::BigInt\n\n\n\"\"\"\n`Multinomial(vec)` returns the multinomial coefficient whose\ntop index is the sum of `vec` (an array of `Int`s) and whose\nbottom indices are given by `vec`.\n\nThis may also be called with a common-separated list of arguments,\nthat is, either of `Multinomial([1,2,3])` or `Multinomial(1,2,3)`.\nThe result is `60` in both cases as these equal `6!/(1! 2! 3!)`.\n\n**Warning**: This is not the same as `MultiChoose`.\n\"\"\"\nfunction Multinomial(v...)::BigInt\n  nv = length(v)\n  for i=1:nv\n    typeof(v[i])<:Integer || throw(DomainError(v,\"arguments must be integers\"))\n    v[i]>=0 || throw(DomainError(v,\"arguments must be nonngative\"))\n  end\n  vals = [t for t in v]\n  return Multinomial(vals)\nend\n\nMultinomial() = big(1)::BigInt\n\nfunction Multinomial(vals::Vector{T})::BigInt where T<:Integer\n  if any([t<0 for t in vals])\n    throw(DomainError(vals,\"arguments must be nonnegative\"))\n  end\n\n  nv = length(vals)\n  n  = sum(vals)\n  # base cases\n  if nv<=1 || n==0\n    return big(1)\n  end\n  # reduce\n  return Binomial(n,vals[end]) * Multinomial(vals[1:nv-1])\nend\n\n\n\"\"\"\n`MultiChoose(n,k)` returns the number of `k`-element\n*multisets* that can be formed using the elements of an\n`n`-element set.\n\n**Warning**: This is not the same as `Multinomial`.\n\"\"\"\nfunction MultiChoose(n::Integer,k::Integer)::BigInt\n  return Binomial(n+k-1,k)\nend\n\n\"\"\"\n`Catalan(n)` returns the `n`-th Catalan number.\n\"\"\"\nfunction Catalan(n::Integer)::BigInt\n  n >= 0 || throw(DomainError(n,\"argument must be nonnegative\"))\n  return div(Binomial(2n,n),n+1)\nend\n\n\n\"\"\"\n`Derangements(n)` returns the number of permutations of\nan `n`-set that have no fixed point.\n\"\"\"\nfunction Derangements(n::Integer)::BigInt\n  if n<0\n    throw(DomainError(n,\"argument must be nonnegative\"))\n  end\n  if n==0\n    return big(1)\n  end\n  if n==1\n    return big(0)\n  end\n  if _has(Derangements,n)\n      return _get(Derangements,n)\n  end\n\n  val = (n-1)*(Derangements(n-1)+Derangements(n-2))\n  _save(Derangements,n,val)\n  return val\nend\n\n_make(Derangements,Integer)\n\n\"\"\"\n`Bell(n)` gives the `n`-th Bell number, that is,\nthe number of partitions of an `n`-element set.\n\"\"\"\nfunction Bell(n::Integer)::BigInt\n  if n<0\n    throw(DomainError(n,\"argument must be nonnegative\"))\n  end\n  if n==1 || n==0\n    return big(1)\n  end\n  if _has(Bell,n)\n      return _get(Bell,n)\n  end\n  N1 = n-1\n  result = big(0)\n  for k=0:n-1\n    result += Binomial(n-1,k) * Bell(k)\n  end\n  _save(Bell,n,result)\n  return result\nend\n_make(Bell,Integer)\n\n\n\"\"\"\n`Stirling2(n,k)` gives the Stirling number of the second kind,\nthat is, the number of paritions of an `n`-set into `k`-parts.\"\n\"\"\"\nfunction Stirling2(n::Integer,k::Integer)::BigInt\n  # special cases\n  if k<0 || n<0\n    throw(DomainError((n,k),\"arguments must be nonnegative\"))\n  end\n\n  if k>n\n    return big(0)\n  end\n\n  if n==0  # and by logic, k==0\n    return big(1)\n  end\n\n  if k==0\n    return big(0)\n  end\n\n  if n==k\n    return big(1)\n  end\n  # END OF SPECIAL CASES, invoke recursion\n  if _has(Stirling2,(n,k))\n      return _get(Stirling2,(n,k))\n  end\n\n  val = Stirling2(n-1,k-1) + Stirling2(n-1,k)*k\n  _save(Stirling2,(n,k),val)\n  return val\nend\n_make(Stirling2,Tuple{Integer,Integer})\n\n\n\"\"\"\n`Stirling1(n,k)` gives the (signed) Stirling number\nof the first kind, that is, the coefficient of `x^k`\nin the poynomial `x(x-1)(x-2)...(x-n+1)`.\n\"\"\"\nfunction Stirling1(n::Integer,k::Integer)::BigInt\n  # special cases\n  if k<0 || n<0\n    throw(DomainError((n,k),\"arguments must be nonnegative\"))\n  end\n\n  if k>n\n    return big(0)\n  end\n\n  if n==0  # and, by logic, k==0\n    return big(1)\n  end\n\n  if k==0  # and, by logic, n>0\n    return big(0)\n  end\n\n  if _has(Stirling1,(n,k))\n      return _get(Stirling1,(n,k))\n  end\n\n  # end of special cases, invoke recursion\n\n  val = Stirling1(n-1,k-1) - (n-1)*Stirling1(n-1,k)\n  _save(Stirling1,(n,k),val)\n  return val\nend\n\n_make(Stirling1,Tuple{Integer,Integer})\n\n\n\n\"\"\"\n`IntPartitions(n)` is the number of partitions of the integer `n`.\n\n`IntPartitions(n,k)` is the number of partitions of the integer\n`n` with exactly `k` (nonzero) parts.\n\"\"\"\nfunction IntPartitions(n::Integer,k::Integer)::BigInt\n  if n<0 || k<0\n    throw(DomainError((n,k),\"arguments must be nonnegative\"))\n  end\n  # lots of special cases\n  if k>n\n    return big(0)\n  end\n  if n==0\n    return big(1)\n  end\n  if k==0\n    return big(0)\n  end\n  if k==n || k==1\n    return big(1)\n  end\n  if _has(IntPartitions,(n,k))\n      return _get(IntPartitions,(n,k))\n  end\n\n  val =  sum([IntPartitions(n-k,i) for i=0:k])\n  _save(IntPartitions,(n,k),val)\n  return val\nend\n\nfunction IntPartitions(n::Integer)::BigInt\n    if n<0\n        throw(DomainError(n,\"argument must be nonnegative\"))\n    end\n    if _has(IntPartitions,n)\n        return _get(IntPartitions,n)\n    end\n    val = sum([IntPartitions(n,k) for k=0:n])\n    _save(IntPartitions,n,val)\n    return val\nend\n\n_make(IntPartitions,Union{Tuple{Integer,Integer},Integer})\n\n\"\"\"\n`IntPartitionsDistinct(n,k)` is the number of partitions of\nthe integer `n` into exactly `k` *distinct* parts.\n\n`IntPartitionsDistinct(n)` is the number of partitions of `n`\ninto *distinct* parts.\n\"\"\"\nfunction IntPartitionsDistinct(n::Integer,k::Integer)::BigInt\n  if n<0 || k<0\n    throw(DomainError((n,k),\"arguments must be nonnegative\"))\n  end\n  Ck2 = div(k*(k-1),2)\n  if n < Ck2\n    return big(0)\n  end\n  return IntPartitions(n-Ck2,k)\nend\n\nfunction IntPartitionsDistinct(n::Integer)::BigInt\n  if n<0\n    throw(DomainError(n,\"argument must be nonngative\"))\n  end\n  result = big(0)\n  for k=1:n\n    s = IntPartitionsDistinct(n,k)\n    if s==0\n      break\n    end\n    result += s\n  end\n  return result\nend\n\n\"\"\"\n`Euler(n)` returns the `n`-th Euler number. Starting with `n=0`\nthis is the sequence\n1, 0, -1, 0, 5, 0, -61, 0, 1385 and so on.\n\"\"\"\nfunction Euler(n::Integer)::BigInt\n  n>=0 || throw(DomainError(n,\"argument must be nonngative\"))\n  if n%2 == 1\n    return big(0)\n  end\n  if n==0\n    return big(1)\n  end\n  if _has(Euler,n)\n      return _get(Euler,n)\n  end\n\n\n  last = div(n,2)-1\n  val =  -sum([ Binomial(n,2k)*Euler(2k) for k=0:last])\n  _save(Euler,n,val)\n  return val\nend\n_make(Euler,Integer)\n\n\n\"\"\"\n`PowerSum(n,k)` returns the sum of the `k`-th powers of the\nintegers `1` through `n`, i.e.,\n`1^k + 2^k + 3^k + ... + n^k`.\n\"\"\"\nfunction PowerSum(n::Integer, k::Integer)::BigInt\n  (n>=0 && k>=0) || throw(DomainError((n,k),\"arguments must be nonngative\"))\n  # Base and special cases\n  if n==0\n    return big(0)\n  end\n  if k==0\n    return big(n)\n  end\n  if k==1\n    return Binomial(n,2)\n  end\n  if _has(PowerSum,(n,k))\n      return _get(PowerSum,(n,k))\n  end\n\n  val =  big(n)^k + PowerSum(n-1,k)\n  _save(PowerSum,(n,k),val)\n  return val\nend\n_make(PowerSum,Tuple{Integer,Integer})\n\n\ninclude(\"eulerian.jl\")\n\nend  #end of module\n", "meta": {"hexsha": "226841438b60fe14829034f8e5a90c5e55410322", "size": 10944, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BigCombinatorics.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/BigCombinatorics.jl-7b33fef7-ef1d-5d54-bb67-cf96d4c8a166", "max_stars_repo_head_hexsha": "ff20dad53db78a62c1e0f9e0c1fa0530bc854d65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BigCombinatorics.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/BigCombinatorics.jl-7b33fef7-ef1d-5d54-bb67-cf96d4c8a166", "max_issues_repo_head_hexsha": "ff20dad53db78a62c1e0f9e0c1fa0530bc854d65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BigCombinatorics.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/BigCombinatorics.jl-7b33fef7-ef1d-5d54-bb67-cf96d4c8a166", "max_forks_repo_head_hexsha": "ff20dad53db78a62c1e0f9e0c1fa0530bc854d65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1274131274, "max_line_length": 79, "alphanum_fraction": 0.6510416667, "num_tokens": 3550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7944512197780486}}
{"text": "# Undergraduate Student: Arturo Burgos\n# Professor: João Rodrigo Andrade\n# Federal University of Uberlândia - UFU, Fluid Mechanics Laboratory - MFLab, Block 5P, Uberlândia, MG, Brazil\n\n\n# Fourth exercise: Solving a Linear System --> ax = b\n\n\n\nusing Printf # Just the same as import a module\nusing Statistics\nusing LinearAlgebra # Import this module to use the norm function\nusing CPUTime\n\nn = 324\nk = Int32(sqrt(324)) \n\n\n# Here I set the A matrix\n\n\n\na = rand([0,0],(n,n))\n\nfor i = 1:n\n  for j = 1:n\n    if i==j\n\n      a[i,j] = -4\n    \n      elseif i == (j-3) || i == (j+3)\n\n        a[i,j] = 1\n\n      elseif (mod(i,3) != 0 && j == (i+1)) \n\n        a[i,j] = 1\n\n      elseif (mod(i,3) != 1 && j == (i-1))\n\n        a[i,j] = 1\n    \n      end\n  end\nend\n\n\n\n# Here I set the b matrix   \n\nb = ones(n)\n\n\nfor i = 1:k\n  if  i < k\n\n    b[i] = -50\n\n  else\n\n    b[i] = -150\n  \n  end\nend\n\n\nfor i = k+1:n-k\n  if i%k != 0\n    \n    b[i] = 0\n  \n  else\n    \n    b[i] = -100\n  \n  end\nend\n\nfor i = n-k+1:n\n  if  i < n\n\n    b[i] = -50\n  \n  else\n  \n    b[i] = -150\n  \n  end\nend \n\nprintln(\"\\n\")\n\nprintln(\"The B matrix is: \")\nprintln(b)\n\nR = zeros(n)\n\nfunction  linearsystem(a,b,x_k1)\n  # Initial x_k and x_k1 value\n  x_k = zeros(n)\n\n  x_k1 = ones(n)\n\n  # Here I set the tolerance\n\n  e = 1e-9\n\n\n\n  # Here I set the iterations \n  ite = 0\n\n\n  # Here I set the error based in the Infinite norm\n  #erro = (x_k1 - x_k)/x_k1; # ---> Why the relative error has the same result? \n  global erro = norm((x_k1 - x_k),Inf)\n\n\n\n  while erro>e\n    for i = 1:n\n    \n      global x_k1[i] = b[i]\n    \n      for j = 1:n\n        if j != i\n\n          global x_k1[i] =  x_k1[i] - a[i,j]*x_k[j]\n    \n        end\n      end\n    \n    \n  \n      global x_k1[i] = x_k1[i]/a[i,i]\n  \n    end\n \n    global erro = norm((x_k1 - x_k),Inf)\n    global x_k[:] = x_k1[:]\n\n    ite = ite + 1\n\n  end\n\n  return x_k1\n\nend\n\nR = linearsystem(a,b,R);\nprintln(\"\\n\\nThe R Matrix is: \\n\\n\",R)\nprintln(\"\\n\\n\")\n\n@time @CPUtime linearsystem(a,b,R)\n   \n", "meta": {"hexsha": "61b72a4ec25339ab86bc3b443dba31d786a66ec0", "size": 1972, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Linear System/Julia/linear_system.jl", "max_stars_repo_name": "arturofburgos/Comparing-Languages", "max_stars_repo_head_hexsha": "a20dc24699c762252c94c26e32c7053c04793d9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-03-17T18:40:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-21T11:51:12.000Z", "max_issues_repo_path": "Linear System/Julia/linear_system.jl", "max_issues_repo_name": "arturofburgos/Assessment-of-Programming-Languages-for-Computational-Numerical-Dynamics", "max_issues_repo_head_hexsha": "eefdc8800b424bbfb34286f4f507297300122a4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear System/Julia/linear_system.jl", "max_forks_repo_name": "arturofburgos/Assessment-of-Programming-Languages-for-Computational-Numerical-Dynamics", "max_forks_repo_head_hexsha": "eefdc8800b424bbfb34286f4f507297300122a4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-11T01:20:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-11T01:20:01.000Z", "avg_line_length": 12.641025641, "max_line_length": 110, "alphanum_fraction": 0.5253549696, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7944512174431105}}
{"text": "function variable_degrees{T<:Real}(num_variables::Integer, poly_degrees::AbstractVector{T})\n    max_poly_degree = maximum(poly_degrees)\n    poly_degrees = Set(poly_degrees)\n    all_variable_degrees = Vector{Int}[]\n    var_degrees = zeros(Int, num_variables)\n    total = 0\n    while var_degrees[1] <= max_poly_degree\n        if in(total, poly_degrees)\n            push!(all_variable_degrees, copy(var_degrees))\n        end\n        var_degrees[end] += 1\n        total += 1\n        for j = length(var_degrees):-1:2\n            if var_degrees[j] > max_poly_degree || total > max_poly_degree\n                total -= var_degrees[j] - 1\n                var_degrees[j] = 0\n                var_degrees[j-1] += 1\n            else\n                break\n            end\n        end\n    end\n    return all_variable_degrees\nend\n\nfunction monomial(variable::Symbol, degree::Integer)\n    MPoly{Float64}(OrderedDict([degree]=>1.0), [variable])\nend\n\nfunction chebyshev_polynomial_first_kind(variable::Symbol, degree::Integer)\n    x = generator(variable)\n    @assert degree >= 0\n    if degree == 0\n        return 1 + 0 * x\n    elseif degree == 1\n        return x\n    else\n        return (2x * chebyshev_polynomial_first_kind(variable, degree - 1)\n                - chebyshev_polynomial_first_kind(variable, degree - 2))\n    end\nend\n\nfunction polynomial_basis(variables, degrees=0:2, generator::Function=monomial)\n    map(d -> prod(map(i -> generator(variables[i], d[i]), \n                  1:length(variables))), \n        variable_degrees(length(variables), degrees))\nend\n\nmonomials(variables, degrees=0:2) = polynomial_basis(variables, degrees, monomial)\nchebyshev_basis_first_kind(variables, degrees=0:2) = polynomial_basis(variables, degrees, chebyshev_polynomial_first_kind)\n", "meta": {"hexsha": "7890d2b5f1c872703bdcc8236e56d02ccd790bf1", "size": 1761, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basis.jl", "max_stars_repo_name": "JuliaPackageMirrors/Mayday.jl", "max_stars_repo_head_hexsha": "329d9e85c71046655c4a63dd614711142af71fbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2016-02-24T21:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-31T20:52:07.000Z", "max_issues_repo_path": "src/basis.jl", "max_issues_repo_name": "JuliaPackageMirrors/Mayday.jl", "max_issues_repo_head_hexsha": "329d9e85c71046655c4a63dd614711142af71fbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2016-02-08T20:53:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:28:47.000Z", "max_forks_repo_path": "src/basis.jl", "max_forks_repo_name": "JuliaPackageMirrors/Mayday.jl", "max_forks_repo_head_hexsha": "329d9e85c71046655c4a63dd614711142af71fbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-02-26T22:14:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:11:42.000Z", "avg_line_length": 34.5294117647, "max_line_length": 122, "alphanum_fraction": 0.6501987507, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895028, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7944512161859374}}
{"text": "# -*- coding: utf-8 -*-\n# $$\n# \\frac{d f}{dt} +  (v \\frac{d f}{dx} - x \\frac{d f}{dv}) = 0\n# $$\n\n# $$ \n# x \\in [-\\pi, \\pi],\\qquad y \\in [-\\pi, \\pi] \\qquad \\mbox{ and } \\qquad t \\in [0, 200\\pi] \n# $$\n\nusing  FFTW\nusing  LinearAlgebra\nusing  Plots, ProgressMeter\nusing  BenchmarkTools\n\n# ## Mesh parameters (matlab code)\n#\n# ```m\n# Nx=128;Ny=256;\n# xmin=-pi; xmax=pi; \n#\n# dx=(xmax-xmin)/Nx; \n# x=xmin:dx:xmax-dx;\n#\n# ymin=-pi; ymax=pi; \n# dy=(ymax-ymin)/Ny; \n# y=ymin:dy:ymax-dy;\n# ```\n\n# ## Julia type for mesh information\n#\n# ```jl\n# struct Mesh\n#     nx   :: Int\n#     ny   :: Int\n#     xmin :: Float64\n#     xmax :: Float64\n#     ymin :: Float64\n#     ymax :: Float64\n#     dx   :: Float64\n#     dy   :: Float64\n#     x    :: Vector{Float64}\n#     y    :: Vector{Float64}\n# end\n#\n# mesh = Mesh( 128, 256, -π, π, -π, π, 2π/128, 2π/256, ...)\n#\n# ```\n#\n\nstruct Mesh\n    \n    nx   :: Int\n    ny   :: Int\n    xmin :: Float64\n    xmax :: Float64\n    ymin :: Float64\n    ymax :: Float64\n    dx   :: Float64\n    dy   :: Float64\n    x    :: Vector{Float64}\n    y    :: Vector{Float64}\n    \n    function Mesh( xmin, xmax, nx, ymin, ymax, ny)\n        dx, dy = (xmax-xmin)/nx, (ymax-ymin)/ny\n        x = range(xmin, stop=xmax, length=nx+1)[1:end-1]  ## we remove the end point\n        y = range(ymin, stop=ymax, length=ny+1)[1:end-1]  ## periodic boundary condition\n        new( nx, ny, xmin, xmax, ymin, ymax, dx, dy, x, y)\n    end\nend\n\nmesh = Mesh(-π, π, 128, -π, π, 256)\n\n@show mesh.xmin, mesh.xmax, mesh.nx, mesh.dx\n\n# # Initialization of f : 2d array of double float\n#\n# ```m\n# f=zeros(Nx,Ny);\n# for i=1:Nx\n#     xx=xmin+(i-1)*dx;\n#     for j=1:Ny\n#         yy=ymin+(j-1)*dy;\n#         f(i,j)=exp(-(xx-1)*(xx-1)/0.1)*exp(-(yy-1)*(yy-1)/0.1);\n#     end\n# end\n# ```\n\n# ```jl\n# f = zeros(Float64,(mesh.nx,mesh.ny))\n#\n# for (i, x) in enumerate(mesh.x), (j, y) in enumerate(mesh.y)\n#\n#     f[i,j] = exp(-(x-1)*(x-1)/0.1)*exp(-(y-1)*(y-1)/0.1)\n#         \n# end\n# ```\n\n# ### Julia function to compute exact solution\n\nfunction exact(tf, mesh)\n   \n    f = zeros(Float64,(mesh.nx, mesh.ny))\n    for (i, x) in enumerate(mesh.x), (j, y) in enumerate(mesh.y)\n        xn = cos(tf)*x - sin(tf)*y\n        yn = sin(tf)*x + cos(tf)*y\n        f[i,j] = exp(-(xn-1)*(xn-1)/0.1)*exp(-(yn-1)*(yn-1)/0.1)\n    end\n\n    f\nend\n\nf = exact(0.0, mesh)\nsurface(f)\n\n# ## Create the gif to show what we are computing\n\nfunction create_gif()\n    x = y = range(-π, stop=π, length=40)\n    n = 100\n    \n    prog = Progress(n,1) ## progress bar\n    \n    @gif for t in range(0, stop=2π, length=n)\n        f(x,y) = exp(-((cos(t)*x-sin(t)*y)-1)^2/0.2)*exp(-((sin(t)*x+cos(t)*y)-1)^2/0.2)\n        \n        p = plot(x, y, f, st = [:surface])\n    \n        plot!(p[1])\n        plot!(zlims=(-0.01,1.01))\n    \n        next!(prog) ## increment the progress bar\n    end\nend\n\ncreate_gif();\n\n# ![](tmp.gif)\n\n# ## Advection and loop over time\n# ```m\n# tf=200*pi;Nt=1000;dt=tf/Nt;\n# kx=2*pi/(xmax-xmin)*[0:Nx/2-1,Nx/2-Nx:Nx-1-Nx];\n# ky=2*pi/(ymax-ymin)*[0:Ny/2-1,Ny/2-Ny:Ny-1-Ny];\n#\n# fnx=zeros(1,Nx);ffx=zeros(1,Nx);fny=zeros(1,Ny);ffy=zeros(1,Ny);\n#\n# for n=1:Nt     \n#     for i=1:Nx\n#         xx=xmin+(i-1)*dx;\n#         ffy=fft(f(i,:));\n#         fny=real(ifft(exp(sqrt(-1)*xx*ky*tan(dt/2)).*ffy));\n#         f(i,:)=fny;\n#     end\n#     \n#     for j=1:Ny\n#         yy=ymin+(j-1)*dy;\n#         ffx=fft(f(:,j));\n#         fnx=real(ifft(exp(-sqrt(-1)*yy*kx*sin(dt)).*transpose(ffx)));\n#         f(:,j)=fnx;\n#     end\n#\n#     for i=1:Nx\n#         xx=xmin+(i-1)*dx;\n#         ffy=fft(f(i,:));\n#         fny=real(ifft(exp(sqrt(-1)*xx*ky*tan(dt/2)).*ffy));\n#         f(i,:)=fny;\n#     end        \n# end\n# ```\n\n# ## Function to compute error\n#\n# ```m\n#\n# % compute errors in Linfty norm\n# error1=max(max(f-f_exact))\n#\n# ```\n#\n# - In julia the max value of an array is `maximum`.\n\nfunction error1(f, f_exact)\n    maximum(abs.(f .- f_exact))\nend\n#----------------------------------------------------------------------------\n\n# ## Naive translation of the matlab code\n\nfunction naive_from_matlab(tf, nt, mesh::Mesh)\n\n    dt = tf/nt\n\n    kx = 2π/(mesh.xmax-mesh.xmin)*[0:mesh.nx÷2-1;mesh.nx÷2-mesh.nx:-1]\n    ky = 2π/(mesh.ymax-mesh.ymin)*[0:mesh.ny÷2-1;mesh.ny÷2-mesh.ny:-1]\n\n    f = exact(0.0, mesh)\n\n    for n=1:nt\n       \n       for (i, x) in enumerate(mesh.x)\n           f[i,:]=real(ifft(exp.(1im*x*ky*tan(dt/2)).*fft(f[i,:])))\n       end\n       \n       for (j, y) in enumerate(mesh.y)\n           f[:,j]=real(ifft(exp.(-1im*y*kx*sin(dt)).*fft(f[:,j])))\n       end\n       \n       for (i, x) in enumerate(mesh.x)\n           f[i,:]=real(ifft(exp.(1im*x*ky*tan(dt/2)).*fft(f[i,:])))\n       end\n   end\n\n    f\nend\n#----------------------------------------------------------------------------\n\nnt, tf = 1000, 200\nprintln( \" error = \", error1(naive_from_matlab(tf, nt, mesh), exact(tf, mesh)))\n@btime naive_from_matlab(tf, nt, mesh);\n#----------------------------------------------------------------------------\n\n# ###  Vectorized version\n#\n# - We remove the for loops over direction x and y by creating the 2d arrays `exky` and `ekxy`.\n# - We save cpu time by computing them before the loop over time\n\nfunction vectorized(tf, nt, mesh::Mesh)\n\n    dt = tf/nt\n\n    kx = 2π/(mesh.xmax-mesh.xmin)*[0:mesh.nx÷2-1;mesh.nx÷2-mesh.nx:-1]\n    ky = 2π/(mesh.ymax-mesh.ymin)*[0:mesh.ny÷2-1;mesh.ny÷2-mesh.ny:-1]\n\n    f = exact(0.0, mesh)\n\n    exky = exp.( 1im*tan(dt/2) .* mesh.x  .* ky')\n    ekxy = exp.(-1im*sin(dt)   .* mesh.y' .* kx )\n    \n    for n = 1:nt\n        f = real(ifft(exky .* fft(f, 2), 2))\n        f = real(ifft(ekxy .* fft(f, 1), 1))\n        f = real(ifft(exky .* fft(f, 2), 2))\n    end\n\n    f\nend\n#----------------------------------------------------------------------------\n\nnt, tf = 1000, 200\nprintln( \" error = \", error1(vectorized(tf, nt, mesh), exact(tf, mesh)))\n@btime vectorized(tf, nt, mesh);\n#----------------------------------------------------------------------------\n\n# ## Inplace computation \n# - We remove the Float64-Complex128 conversion by allocating the distribution function `f` as a Complex array\n# - Note that we need to use the inplace assignement operator \".=\"  to initialize the `f` array.\n# - We use inplace computation for fft with the \"bang\" operator `!`\n\nfunction inplace(tf, nt, mesh::Mesh)\n\n    dt = tf/nt\n\n    kx = 2π/(mesh.xmax-mesh.xmin)*[0:mesh.nx÷2-1;mesh.nx÷2-mesh.nx:-1]\n    ky = 2π/(mesh.ymax-mesh.ymin)*[0:mesh.ny÷2-1;mesh.ny÷2-mesh.ny:-1]\n    \n    f  = zeros(Complex{Float64},(mesh.nx,mesh.ny))\n    f .= exact(0.0, mesh)\n\n    exky = exp.( 1im*tan(dt/2) .* mesh.x  .* ky')\n    ekxy = exp.(-1im*sin(dt)   .* mesh.y' .* kx )\n    \n    for n = 1:nt\n        fft!(f, 2)\n        f .= exky .* f\n        ifft!(f,2)\n        fft!(f, 1)\n        f .= ekxy .* f\n        ifft!(f, 1)\n        fft!(f, 2)\n        f .= exky .* f\n        ifft!(f,2)        \n    end\n\n    real(f)\nend\n#----------------------------------------------------------------------------\n\nnt, tf = 1000, 200\nprintln( \" error = \", error1(inplace(tf, nt, mesh), exact(tf, mesh)))\n@btime inplace(tf, nt, mesh);\n#----------------------------------------------------------------------------\n\n# ### Use plans for fft\n\n# - When you apply multiple fft on array with same shape and size, it is recommended to use fftw plan to improve computations.\n# - Let's try to initialize our two fft along x and y with plans.\n\nfunction with_fft_plans(tf, nt, mesh::Mesh)\n\n    dt = tf/nt\n\n    kx = 2π/(mesh.xmax-mesh.xmin)*[0:mesh.nx÷2-1;mesh.nx÷2-mesh.nx:-1]\n    ky = 2π/(mesh.ymax-mesh.ymin)*[0:mesh.ny÷2-1;mesh.ny÷2-mesh.ny:-1]\n    \n    f  = zeros(Complex{Float64},(mesh.nx,mesh.ny))\n    f .= exact(0.0, mesh)\n    f̂  = similar(f)\n\n    exky = exp.( 1im*tan(dt/2) .* mesh.x  .* ky')\n    ekxy = exp.(-1im*sin(dt)   .* mesh.y' .* kx )\n        \n    Px = plan_fft(f, 1)\n    Py = plan_fft(f, 2)\n        \n    for n = 1:nt\n        \n        f̂ .= Py * f\n        f̂ .= f̂  .* exky\n        f .= Py \\ f̂\n        \n        f̂ .= Px * f\n        f̂ .= f̂  .* ekxy \n        f .= Px \\ f̂\n        \n        f̂ .= Py * f\n        f̂ .= f̂  .* exky\n        f .= Py \\ f̂\n        \n    end\n\n    real(f)\nend\n#----------------------------------------------------------------------------\n\nnt, tf = 1000, 200\nprintln( \" error = \", error1(with_fft_plans(tf, nt, mesh), exact(tf, mesh)))\n@btime with_fft_plans(tf, nt, mesh);\n#----------------------------------------------------------------------------\n\n# ## Inplace computation and fft plans\n#\n# To apply fft plan to an array A, we use a preallocated output array Â by calling `mul!(Â, plan, A)`. \n# The input array A must be a complex floating-point array like the output Â.\n# The inverse-transform is computed inplace by applying `inv(P)` with `ldiv!(A, P, Â)`.\n\nfunction with_fft_plans_inplace(tf, nt, mesh::Mesh)\n\n    dt = tf/nt\n\n    kx = 2π/(mesh.xmax-mesh.xmin)*[0:mesh.nx÷2-1;mesh.nx÷2-mesh.nx:-1]\n    ky = 2π/(mesh.ymax-mesh.ymin)*[0:mesh.ny÷2-1;mesh.ny÷2-mesh.ny:-1]\n    \n    f  = zeros(Complex{Float64},(mesh.nx,mesh.ny))\n    f .= exact(0.0, mesh)\n    f̂  = similar(f)\n\n    exky = exp.( 1im*tan(dt/2) .* mesh.x  .* ky')\n    ekxy = exp.(-1im*sin(dt)   .* mesh.y' .* kx )\n\n    Px = plan_fft(f, 1)    \n    Py = plan_fft(f, 2)\n        \n    for n = 1:nt\n        \n        mul!(f̂, Py, f)\n        f̂ .= f̂ .* exky\n        ldiv!(f, Py, f̂)\n        \n        mul!(f̂, Px, f)\n        f̂ .= f̂ .* ekxy \n        ldiv!(f, Px, f̂)\n        \n        mul!(f̂, Py, f)\n        f̂ .= f̂ .* exky\n        ldiv!(f, Py, f̂)\n        \n    end\n\n    real(f)\nend\n#----------------------------------------------------------------------------\n\nnt, tf = 1000, 200\nprintln( \" error = \", error1(with_fft_plans_inplace(tf, nt, mesh), exact(tf, mesh)))\n@btime with_fft_plans_inplace(tf, nt, mesh);\n#----------------------------------------------------------------------------\n\n# ## Explicit transpose of `f`\n#\n# - Multidimensional arrays in Julia are stored in column-major order.\n# - FFTs along y are slower than FFTs along x\n# - We can speed-up the computation by allocating the transposed `f` \n# and transpose f for each advection along y.\n\nfunction with_fft_transposed(tf, nt, mesh::Mesh)\n\n    dt = tf/nt\n\n    kx = 2π/(mesh.xmax-mesh.xmin)*[0:mesh.nx÷2-1;mesh.nx÷2-mesh.nx:-1]\n    ky = 2π/(mesh.ymax-mesh.ymin)*[0:mesh.ny÷2-1;mesh.ny÷2-mesh.ny:-1]\n    \n    f  = zeros(Complex{Float64},(mesh.nx,mesh.ny))\n    f̂  = similar(f)\n    fᵗ = zeros(Complex{Float64},(mesh.ny,mesh.nx))\n    f̂ᵗ = similar(fᵗ)\n\n    exky = exp.( 1im*tan(dt/2) .* mesh.x' .* ky )\n    ekxy = exp.(-1im*sin(dt)   .* mesh.y' .* kx )\n    \n    FFTW.set_num_threads(4)\n    Px = plan_fft(f,  1, flags=FFTW.PATIENT)    \n    Py = plan_fft(fᵗ, 1, flags=FFTW.PATIENT)\n    \n    f .= exact(0.0, mesh)\n    \n    for n = 1:nt\n        transpose!(fᵗ,f)\n        mul!(f̂ᵗ, Py, fᵗ)\n        f̂ᵗ .= f̂ᵗ .* exky\n        ldiv!(fᵗ, Py, f̂ᵗ)\n        transpose!(f,fᵗ)\n        \n        mul!(f̂, Px, f)\n        f̂ .= f̂ .* ekxy \n        ldiv!(f, Px, f̂)\n        \n        transpose!(fᵗ,f)\n        mul!(f̂ᵗ, Py, fᵗ)\n        f̂ᵗ .= f̂ᵗ .* exky\n        ldiv!(fᵗ, Py, f̂ᵗ)\n        transpose!(f,fᵗ)\n    end\n    real(f)\nend\n#----------------------------------------------------------------------------\n\nnt, tf = 1000, 200\nprintln( \" error = \", error1(with_fft_transposed(tf, nt, mesh), exact(tf, mesh)))\n@btime with_fft_transposed(tf, nt, mesh);\n#----------------------------------------------------------------------------\n\ntf, nt = 400π, 1000\nmesh = Mesh(-π, π, 512, -π, π, 256)\n\ninplace_bench = @benchmark inplace(tf, nt, mesh)\nvectorized_bench = @benchmark vectorized(tf, nt, mesh)\nwith_fft_plans_bench = @benchmark with_fft_plans(tf, nt, mesh)\nwith_fft_plans_inplace_bench = @benchmark with_fft_plans_inplace(tf, nt, mesh)\nwith_fft_transposed_bench = @benchmark with_fft_transposed(tf, nt, mesh)\n#----------------------------------------------------------------------------\n\nd = Dict() \nd[\"vectorized\"] = minimum(vectorized_bench.times) / 1e6\nd[\"inplace\"] = minimum(inplace_bench.times) / 1e6\nd[\"with_fft_plans\"] = minimum(with_fft_plans_bench.times) / 1e6\nd[\"with_fft_plans_inplace\"] = minimum(with_fft_plans_inplace_bench.times) / 1e6\nd[\"with_fft_transposed\"] = minimum(with_fft_transposed_bench.times) / 1e6;\n#----------------------------------------------------------------------------\n\nfor (key, value) in sort(collect(d), by=last)\n    println(rpad(key, 25, \".\"), lpad(round(value, digits=1), 6, \".\"))\nend\n#----------------------------------------------------------------------------\n\n# ## Conclusion\n# - Use pre-allocations of memory and inplace computation are very important\n# - Try to always do computation on data contiguous in memory\n# - In this notebook, use btime to not taking account of time consumed in \n# compilation.\n", "meta": {"hexsha": "d6b4361ab8aaaff6dbafd96d8191074721c34a6c", "size": 12680, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "02.RotationFFT.jl", "max_stars_repo_name": "pnavaro/math-julia", "max_stars_repo_head_hexsha": "900db803b2ddd9e44eb2d4fabb481768a14953c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-01-14T13:32:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T04:22:17.000Z", "max_issues_repo_path": "02.RotationFFT.jl", "max_issues_repo_name": "pnavaro/math-julia", "max_issues_repo_head_hexsha": "900db803b2ddd9e44eb2d4fabb481768a14953c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02.RotationFFT.jl", "max_forks_repo_name": "pnavaro/math-julia", "max_forks_repo_head_hexsha": "900db803b2ddd9e44eb2d4fabb481768a14953c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-10-15T07:58:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-11T01:52:10.000Z", "avg_line_length": 26.9787234043, "max_line_length": 126, "alphanum_fraction": 0.4930599369, "num_tokens": 4346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002491, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7944512160512168}}
{"text": "\"\"\"\ncelsius_to_fahrenheit(celsius, ndigits::Int = 2)\n\nConverts celsius to fahrenheit and round to 2 decimal places\n\n# Example\n\n```julia\ncelsius_to_fahrenheit(273.354, 3) == 524.037  # returns true\ncelsius_to_fahrenheit(273.354, 0) == 524.0    # returns true\ncelsius_to_fahrenheit(-40.0) == -40.0         # returns true\ncelsius_to_fahrenheit(-20.0) == -4.0          # returns true\ncelsius_to_fahrenheit(0) == 32.0              # returns true\ncelsius_to_fahrenheit(20) == 68.0             # returns true\n```\n\"\"\"\nfunction celsius_to_fahrenheit(celsius, ndigits::Int = 2)\n    return round((float(celsius) * 1.8) + 32.0; digits = ndigits)\nend\n\n\"\"\"\nfunction celsius_to_kelvin(celsius, ndigits::Int = 2)\n\nConverts celsius to kelvin and round to 2 decimal places\n\n# Example\n\n```julia\ncelsius_to_kelvin(273.354, 3) == 546.504    # returns true\ncelsius_to_kelvin(273.354, 0) == 547.0      # returns true\ncelsius_to_kelvin(0.0) == 273.15            # returns true\ncelsius_to_kelvin(20.0) == 293.15           # returns true\n```\n\n\"\"\"\nfunction celsius_to_kelvin(celsius, ndigits::Int = 2)\n    return round(float(celsius) + 273.15; digits = ndigits)\nend\n\n\"\"\"\nfahrenheit_to_celsius(fahrenheit, ndigits::Int = 2)\n\nConverts fahrenheit to celsius and round to 2 decimal places\n\n# Example\n\n```julia\nfahrenheit_to_celsius(273.354, 3) == 134.086 # returns true\nfahrenheit_to_celsius(273.354, 0) == 134.0   # returns true\nfahrenheit_to_celsius(0.0) == -17.78         # returns true\nfahrenheit_to_celsius(20.0) == -6.67         # returns true\nfahrenheit_to_celsius(40.0) == 4.44          # returns true\nfahrenheit_to_celsius(60.0) == 15.56         # returns true\nfahrenheit_to_celsius(80.0) == 26.67         # returns true\n```\n\"\"\"\nfunction fahrenheit_to_celsius(fahrenheit, ndigits::Int = 2)\n    return round((float(fahrenheit) - 32.0) * 5 / 9; digits = ndigits)\nend\n\n\"\"\"\nfahrenheit_to_kelvin(fahrenheit, ndigits::Int = 2)\n\nConverts fahrenheit to kelvin and round to 2 decimal places\n\n# Example\n\n```julia\nfahrenheit_to_kelvin(273.354, 3) == 407.236 # returns true\nfahrenheit_to_kelvin(273.354, 0) == 407.0   # returns true\nfahrenheit_to_kelvin(0) == 255.37           # returns true\nfahrenheit_to_kelvin(20.0) == 266.48        # returns true\nfahrenheit_to_kelvin(40.0) == 277.59        # returns true\nfahrenheit_to_kelvin(60.0) == 288.71        # returns true\nfahrenheit_to_kelvin(80.0) == 299.82        # returns true\n```\n\"\"\"\nfunction fahrenheit_to_kelvin(fahrenheit, ndigits::Int = 2)\n    return round(\n        ((float(fahrenheit) - 32.0) * 5 / 9) + 273.15;\n        digits = ndigits,\n    )\nend\n\n\"\"\"\nfunction kelvin_to_celsius(kelvin, ndigits::Int = 2)\n\nConverts kelvin to celsius and round to 2 decimal places\n\n# Example\n\n```julia\nkelvin_to_celsius(273.354, 3) == 0.204   # returns true\nkelvin_to_celsius(273.354, 0) == 0.0     # returns true\nkelvin_to_celsius(273.15) == 0.0         # returns true\nkelvin_to_celsius(300) == 26.85          # returns true\n```\n\"\"\"\nfunction kelvin_to_celsius(kelvin, ndigits::Int = 2)\n    return round(float(kelvin) - 273.15; digits = ndigits)\nend\n\n\"\"\"\nfunction kelvin_to_fahrenheit(kelvin, ndigits::Int = 2)\n\nConverts kelvin to fahrenheit and round to 2 decimal places\n\n# Example\n\n```julia\nkelvin_to_fahrenheit(273.354, 3) == 32.367  # returns true\nkelvin_to_fahrenheit(273.354, 0) == 32.0    # returns true\nkelvin_to_fahrenheit(273.15) == 32.0        # returns true\nkelvin_to_fahrenheit(300) == 80.33          # returns true\n```\n\"\"\"\nfunction kelvin_to_fahrenheit(kelvin, ndigits::Int = 2)\n    return round(((float(kelvin) - 273.15) * 1.8) + 32.0; digits = ndigits)\nend\n", "meta": {"hexsha": "750d8e6a5860f994e8ef098a7e394d4a29feb973", "size": 3579, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/conversions/temparature_conversion.jl", "max_stars_repo_name": "Whiteshark-314/Julia", "max_stars_repo_head_hexsha": "3285d8d6b7585cc1075831c2c210b891151da0c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-14T21:48:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-14T21:48:50.000Z", "max_issues_repo_path": "src/conversions/temparature_conversion.jl", "max_issues_repo_name": "AugustoCL/Julia", "max_issues_repo_head_hexsha": "1bf4e4a7829fafc64290d903bcbfdd48eab839e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/conversions/temparature_conversion.jl", "max_forks_repo_name": "AugustoCL/Julia", "max_forks_repo_head_hexsha": "1bf4e4a7829fafc64290d903bcbfdd48eab839e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.825, "max_line_length": 75, "alphanum_fraction": 0.6781223806, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.8807970779778824, "lm_q1q2_score": 0.7944090871668487}}
{"text": "mutable struct GaussianFeature\n    _means::AbstractArray{Float64,1} # the list of means\n    _var::Float64 # the variance of gaussian\n    _n_kernels::Int64 # cache the number of kernels\n    function GaussianFeature(means::AbstractArray{Float64,1}, var::Float64)\n        new(means, var, size(means)[1])\n    end\nend\n\nfunction _gauss(mean::Float64, var::Float64, x::AbstractArray{Float64,1})\n    return exp.(-(0.5 / var) .* (x .- mean) .^ 2)\nend\n\nfunction transform(feature::GaussianFeature, x::AbstractArray{Float64,1})\n    # this feature transforms R^1 to R^1\n    # x is an array of size n_samples\n    # returns Phi = [phi_1(x),,,, phi_N(x)] where phi_i(x) is a gaussian centered around means[i]\n    n_samples = size(x)[1]\n    n_kernels = feature._n_kernels\n    Phi = zeros(n_samples, n_kernels)\n    for i = 1:n_kernels\n        mean = feature._means[i]\n        var = feature._var\n        Phi[:, i] = _gauss(mean, var, x)\n    end\n\n    return Phi\nend\n", "meta": {"hexsha": "c4280a9b171814207d3f0d36dcfc861a957e3721", "size": 947, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/feature/gaussian_feature.jl", "max_stars_repo_name": "soblin/prml-julia", "max_stars_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-10T21:46:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:40:22.000Z", "max_issues_repo_path": "src/feature/gaussian_feature.jl", "max_issues_repo_name": "soblin/prml-julia", "max_issues_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/feature/gaussian_feature.jl", "max_forks_repo_name": "soblin/prml-julia", "max_forks_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6551724138, "max_line_length": 97, "alphanum_fraction": 0.6631467793, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374443, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7944062160449528}}
{"text": "\nusing JuMP, GLPK\n\n\n# wrap all of our code inside a function (for better performance)\nfunction example_basic()\n    \n    # define model and optimizer\n    model = Model(GLPK.Optimizer)\n    \n    # define variables\n    @variable(model, 0 <= x <= 2)\n    @variable(model, 0 <= y <= 30)\n\n    # define objective function\n    @objective(model, Max, 5x + 3y)\n    \n    # add additional constraints\n    @constraint(model, 1x + 5y <= 3.0)\n\n    # display the model\n    print(model)\n    \n    # optimize the model\n    JuMP.optimize!(model)\n\n    # return and print objective function and optimal values of variables\n    obj_value = JuMP.objective_value(model)\n    x_value = JuMP.value(x)\n    y_value = JuMP.value(y)\n    println(\"Objective value: \", obj_value)\n    println(\"x = \", x_value)\n    println(\"y = \", y_value)\nend\n\n\n# call the function defined above\nexample_basic()\n\nusing JuMP, GLPK\nfunction example_sudoku()\n    \n    # input the initial puzzle board (0s mean blanks)\n    initial_grid = [\n                    3 1 0 0 5 8 0 0 4;\n                    0 0 9 3 2 0 0 0 0;\n                    0 2 5 1 0 4 0 9 0;\n                    0 0 0 0 0 0 3 8 9;\n                    0 0 8 0 0 0 5 0 0;\n                    5 4 6 0 0 0 0 0 0;\n                    0 8 0 2 0 3 6 5 0;\n                    0 0 0 0 7 1 4 0 0;\n                    7 0 0 4 8 0 0 2 1\n                    ]\n\n    # use GLPK Optimizer\n    model = Model(GLPK.Optimizer)\n    \n    # Set up the variables: each one can only take on binary values, so we add \"Bin\" to the end as a constraint\n    @variable(model, x[1:9, 1:9, 1:9], Bin)\n\n    # Add the constraints\n    @constraints(model, begin\n                     # Constraint 1 - Only one value appears in each cell\n                     cell[i in 1:9, j in 1:9], sum(x[i, j, :]) == 1\n                     # Constraint 2 - Each value appears in each row once only\n                     row[i in 1:9, k in 1:9], sum(x[i, :, k]) == 1\n                     # Constraint 3 - Each value appears in each column once only\n                     col[j in 1:9, k in 1:9], sum(x[:, j, k]) == 1\n                     # Constraint 4 - Each value appears in each 3x3 subgrid once only\n                     subgrid[i=1:3:7, j=1:3:7, val=1:9], sum(x[i:i + 2, j:j + 2, val]) == 1\n                 end)\n\n    # Add additional constraints that reflect the starting point of the puzzle board\n    # (i.e. don't attempt to update the numbers that were given as part of the puzzle)\n    for row in 1:9, col in 1:9\n        if initial_grid[row, col] != 0\n            @constraint(model, x[row, col, initial_grid[row, col]] == 1)\n        end\n    end\n\n    # Solve it\n    JuMP.optimize!(model)\n\n    term_status = JuMP.termination_status(model)\n    primal_status = JuMP.primal_status(model)\n    is_optimal = term_status == MOI.OPTIMAL\n\n    # Check solution\n    if is_optimal\n        mip_solution = JuMP.value.(x)\n        sol = zeros(Int, 9, 9)\n        for row in 1:9, col in 1:9, val in 1:9\n            if mip_solution[row, col, val] >= 0.9\n                sol[row, col] = val\n            end\n        end\n        return sol\n    else\n        error(\"The solver did not find an optimal solution.\")\n    end\nend\n\nfunction print_sudoku_solution(solution)\n    println(\"Solution:\")\n    println(\"[-----------------------]\")\n    for row in 1:9\n        print(\"[ \")\n        for col in 1:9\n            print(solution[row, col], \" \")\n            if col % 3 == 0 && col < 9\n                print(\"| \")\n            end\n        end\n        println(\"]\")\n        if row % 3 == 0\n            println(\"[-----------------------]\")\n        end\n    end\nend\n\nsol = example_sudoku()\nprint_sudoku_solution(sol)\n\nusing HTTP, JuliaDB, JuMP, GLPK\n\n# first function: read in the player data from the class GitHub repository\nfunction read_in_data(url)\n    newtable  = csvread(IOBuffer(HTTP.get(url).body), skiplines_begin=0, header_exists=true)\n    players   = newtable[1][2]\n    salaries  = newtable[1][4]./1000000\n    ppg       = newtable[1][11]\n    return players,salaries,ppg\nend\n\nfunction SolveModel(players,salary,points)\n    N = length(salary) \n    \n    m = Model(GLPK.Optimizer)\n\n    # define the variables: they are 0 if the player did not make the team, 1 if the player did make the team\n    @variable(m, picked[1:N], Bin)\n\n    # categories: \n    @objective(m, Max, sum( points[i] * picked[i] for i in 1:N)) \n\n    @constraints m begin\n        # Constraint 1 - payroll <= 132.6m\n        sum(salary[i] * picked[i] for i in 1:N) <= 132.6\n        # Constraint 2 - must have exactly 15 players on roster\n        sum(picked[i] for i in 1:N) == 15\n    end\n\n    # Solve it\n    JuMP.optimize!(m);\n    pck     = convert(BitArray,JuMP.value.(picked))\n    lineup  = players[pck]\n    points  = JuMP.objective_value(m)\n    payroll = sum(salary[pck])\n    return lineup,points,payroll\nend\n\n# call first function (to import data)\nplayers,salaries,pts = read_in_data(\"https://raw.githubusercontent.com/tyleransom/DScourseS20/master/WebData/playerSalaryStats.csv\")\n\n# pass data into second function to get optimal lineup\nlineup,total_points,payroll = SolveModel(players,salaries,pts)\nprintln(\"team: \",lineup)\nprintln(\"total points scored per game: \",total_points)\nprintln(\"payroll: \",payroll)\n\n# first function: read in the player data from the class GitHub repository\nfunction read_in_data(url)\n    newtable = csvread(IOBuffer(HTTP.get(url).body), skiplines_begin=0, header_exists=true)\n    players  = newtable[1][2]\n    salaries = newtable[1][4]./1000000\n    mpg      = newtable[1][5]\n    fgaG5    = 1.0.*((newtable[1][9]).>5)\n    fga      = newtable[1][9]\n    ppg      = newtable[1][11]\n    return players,salaries,mpg,fgaG5,fga,ppg\nend\n\nfunction SolveModel(players,salary,minutes,field_goals_over5,field_goals,points)\n    N = length(salary) \n    \n    m = Model(GLPK.Optimizer)\n\n    # define the variables: they are 0 if the player did not make the team, 1 if the player did make the team\n    @variable(m, picked[1:N], Bin)\n\n    # categories: \n    @objective(m, Max, sum( points[i] * picked[i] for i in 1:N)) \n\n    @constraints m begin\n        # Constraint 1 - payroll <= 132.6m\n        sum(salary[i] * picked[i] for i in 1:N) <= 132.6\n        # Constraint 2 - must have exactly 15 players on roster\n        sum(picked[i] for i in 1:N) == 15\n        # Constraint 3 - total minutes must not exceed 240\n        sum(minutes[i] * picked[i] for i in 1:N) <= 240\n        # Constraint 4 - total shot attempts must be lower than 80\n        sum(field_goals[i] * picked[i] for i in 1:N) <= 80\n    end\n\n    # Solve it\n    JuMP.optimize!(m);\n    pck      = convert(BitArray,JuMP.value.(picked))\n    lineup   = players[pck]\n    totmin   = sum(minutes[pck])\n    payroll  = sum(salary[pck])\n    totshots = sum(field_goals[pck])\n    points   = JuMP.objective_value(m)\n    return lineup,points,totmin,payroll,totshots\nend\n\n# call first function (to import data)\nplayers,salaries,minutes,over5fg,fga,pts = read_in_data(\"https://raw.githubusercontent.com/tyleransom/DScourseS20/master/WebData/playerSalaryStats.csv\")\n\n# pass data into second function to get optimal lineup\nlineup,total_points,total_minutes,payroll,totshots = SolveModel(players,salaries,minutes,over5fg,fga,pts)\nprintln(\"team: \",lineup)\nprintln(\"total points scored per game: \",total_points)\nprintln(\"payroll: \",payroll)\nprintln(\"total shots per game: \",totshots)\nprintln(\"total minutes per game: \",total_minutes)\n\nusing HTTP, JuliaDB, JuMP, Ipopt\nfunction import_auto(url)\n    newtable  = csvread(IOBuffer(HTTP.get(url).body), skiplines_begin=0, header_exists=true)\n    depvar    = log.(newtable[1][2]) # log price\n    indepvars = cat(ones(size(depvar)),newtable[1][3],newtable[1][5],newtable[1][6]; dims=2) # constant, mpg, headroom, trunk\n    return depvar,indepvars\nend\n\nY,X = import_auto(\"https://tyleransom.github.io/teaching/MetricsLabs/auto.csv\")\n\n\nfunction jumpOLS(Y,X,startval=zeros(size(X,2),1))\n    OLS = Model(Ipopt.Optimizer)\n    \n    # Declare the variables you are optimizing over\n    @variable(OLS, b[i=1:size(X,2)], start = startval[i])\n    \n    # Write your objective function\n    @NLobjective(OLS, Min, sum( (Y[i]-sum( X[i,k]*b[k] for k in 1:size(X,2) ))^2 for i in 1:size(X,1) ) )\n    \n    # Solve the objective function\n    JuMP.optimize!(OLS)\n    \n    SSR = JuMP.objective_value(OLS)\n    b_value = JuMP.value.(b)\n    println(\"Objective value: \", SSR)\n    println(\"beta hat = \", b_value)\n    println(\"RMSE = \", sqrt(SSR/(size(X,1)-size(X,2))))\nend\n\njumpOLS(Y,X)\n\n", "meta": {"hexsha": "3ccb9a059d5683c45412596b0dd15f9cdf046ac5", "size": 8447, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LectureNotes/14-JuMP/JuMPintro.jl", "max_stars_repo_name": "brandyherrera/DScourseS21", "max_stars_repo_head_hexsha": "05f627c2413a61457b97951915368e26549e398a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 52, "max_stars_repo_stars_event_min_datetime": "2020-01-09T04:00:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T12:22:41.000Z", "max_issues_repo_path": "LectureNotes/14-JuMP/JuMPintro.jl", "max_issues_repo_name": "brandyherrera/DScourseS21", "max_issues_repo_head_hexsha": "05f627c2413a61457b97951915368e26549e398a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2020-01-08T22:46:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-28T20:39:17.000Z", "max_forks_repo_path": "LectureNotes/14-JuMP/JuMPintro.jl", "max_forks_repo_name": "brandyherrera/DScourseS21", "max_forks_repo_head_hexsha": "05f627c2413a61457b97951915368e26549e398a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2020-01-09T04:00:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T12:30:14.000Z", "avg_line_length": 32.4884615385, "max_line_length": 152, "alphanum_fraction": 0.6089736001, "num_tokens": 2520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915913, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7944062104807098}}
{"text": "using AlgebraicPetri\nusing OrdinaryDiffEq\nusing Plots\nusing Catlab.Meta\nusing JSON\n\nimport OrdinaryDiffEq: ODEProblem\nODEProblem(p::LabelledReactionNet, t) = ODEProblem(vectorfield(p), concentrations(p), t, rates(p))\n\n# help capture JSON of defined functions\nmacro capture(funcname, exname, ex)\n    quote\n        $(esc(exname)) = $(repr(strip_lines(ex, recurse=true)))\n        $(esc(funcname)) = $ex\n    end\nend\n\n@capture γ γ_text 1/14\n@capture β β_text t->begin\n    policy_days = [20,60,120] .+ 17\n    contact_rate = 0.05\n    pol = findfirst(x->t<=x, policy_days) # array of days when policy changes\n    growth_rate = pol == 1 ? 0.0 : (2^(1/((pol-1)*5)) - 1) # growth rate depending on policy\n    return (growth_rate + γ) / 990 * (1-contact_rate) # calculate rate of infection\nend\n\nsir_cset= LabelledReactionNet{Function, Float64}((:S=>990, :I=>10, :R=>0), (:inf, β)=>((:S, :I)=>(:I,:I)), (:rec, t->γ)=>(:I=>:R))\n\nGraph(sir_cset)\n\nprob = ODEProblem(sir_cset, (17.0, 120.0))\nsol = OrdinaryDiffEq.solve(prob,Tsit5())\nplot(sol)\n\n## Getting Sharable JSON\nsir_cset_string = LabelledReactionNet{String, Int}((:S=>990, :I=>10, :R=>0), (:inf, β_text)=>((:S, :I)=>(:I,:I)), (:rec, γ_text)=>(:I=>:R))\nJSON.print(sir_cset_string.tables, 2)\n", "meta": {"hexsha": "85ef862982f099863a667b559722c53b0448e111", "size": 1230, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/covid/chime/chime-cset.jl", "max_stars_repo_name": "tylerhanks/AlgebraicPetri.jl", "max_stars_repo_head_hexsha": "91535bd5aea8b8bbc3de25d1c7b55071017c1801", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/covid/chime/chime-cset.jl", "max_issues_repo_name": "tylerhanks/AlgebraicPetri.jl", "max_issues_repo_head_hexsha": "91535bd5aea8b8bbc3de25d1c7b55071017c1801", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/covid/chime/chime-cset.jl", "max_forks_repo_name": "tylerhanks/AlgebraicPetri.jl", "max_forks_repo_head_hexsha": "91535bd5aea8b8bbc3de25d1c7b55071017c1801", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3684210526, "max_line_length": 139, "alphanum_fraction": 0.6585365854, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953275045356249, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7943875394195605}}
{"text": "# Minimum variance analysis\n\nexport mva\n\n\"\"\"\n    mva(Bx, By, Bz; verbose=false)\n\nPerform minimum variance analysis to vector components defined in orthogonal\ncoordinates `Bx`, `By` and `Bz`.\nIf λ₁ ≥ λ₂ ≥ λ₃ are 3 eigenvalues of the constructed matrix M, then a good\nindicator of nice fitting LMN coordinate system should have λ₂/λ₃ > 5. Set \n`verbose=true` to turn on the check.\n\"\"\"\nfunction mva(Bx, By, Bz; verbose=false)\n\n   B̄1 = mean(Bx)\n   B̄2 = mean(By)\n   B̄3 = mean(Bz)\n   B̄11= mean(Bx.*Bx) - B̄1*B̄1\n   B̄22= mean(By.*By) - B̄2*B̄2\n   B̄33= mean(Bz.*Bz) - B̄3*B̄3\n   B̄12= mean(Bx.*By) - B̄1*B̄2\n   B̄23= mean(By.*Bz) - B̄2*B̄3\n   B̄31= mean(Bz.*Bx) - B̄3*B̄1\n   # Construct the matrix\n   M = [B̄11 B̄12 B̄31; B̄12 B̄22 B̄23; B̄31 B̄23 B̄33]\n\n   # Compute the eigen values and ratios (descending order)\n   F = eigen(M, sortby = x -> -abs(x))\n\n   if verbose\n      println(\"Eigenvalues:\", F.values)\n      println(\"Eigenvectors:\")\n      println(F.vectors[:,1])\n      println(F.vectors[:,2])\n      println(F.vectors[:,3])\n      r = F.values[2] / F.values[3]\n      println(\"Ratio of intermediate variance to minimum variance = \",\n         round(r, digits=3))\n      if r ≥ 5\n         println(\"Seems to be a proper MVA attempt!\")\n      else\n         @warn \"Take the MVA result with a grain of salt!\"\n      end\n   end\n   F\nend", "meta": {"hexsha": "4b9238cf422fed62f6b99f6e4407d852ec6aafcc", "size": 1328, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MVA.jl", "max_stars_repo_name": "henry2004y/VisAnaJulia", "max_stars_repo_head_hexsha": "cbf608847f66321f3fa8665f12a8850f7bd01408", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-07-29T18:10:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T07:29:39.000Z", "max_issues_repo_path": "src/MVA.jl", "max_issues_repo_name": "henry2004y/VisAnaJulia", "max_issues_repo_head_hexsha": "cbf608847f66321f3fa8665f12a8850f7bd01408", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-10-07T16:08:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-08T20:18:32.000Z", "max_forks_repo_path": "src/MVA.jl", "max_forks_repo_name": "henry2004y/VisAnaJulia", "max_forks_repo_head_hexsha": "cbf608847f66321f3fa8665f12a8850f7bd01408", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-04T10:31:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T10:31:52.000Z", "avg_line_length": 28.2553191489, "max_line_length": 76, "alphanum_fraction": 0.6039156627, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248208414329, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.794360949282921}}
{"text": "# V-measure of contingency table\nfunction _vmeasure(A::AbstractMatrix{<:Integer}; β::Real)\n    (β >= 0) || throw(ArgumentError(\"β should be nonnegative\"))\n\n    N = sum(A)\n    (N == 0.0) && return 0.0\n\n    entA = entropy(A)\n    entArows = entropy(sum(A, dims=2))\n    entAcols = entropy(sum(A, dims=1))\n\n    hck = (entA - entAcols)/N\n    hkc = (entA - entArows)/N\n    hc = entArows/N + log(N)\n    hk = entAcols/N + log(N)\n\n    # Homogeneity\n    h = hc == 0.0 ? 1.0 : 1.0 - hck/hc\n    # Completeness\n    c = hk == 0.0 ? 1.0 : 1.0 - hkc/hk\n\n    # V-measure\n    V_β = (1 + β)*h*c/(β*h + c)\n    return V_β\nend\n\n\"\"\"\n    vmeasure(assign1, assign2; β = 1.0)\n\nV-measure between two clustering assignments.\n\n`assign1` and `assign2` can be either `ClusteringResult` objects or\nassignments vectors (`AbstractVector{<:Integer}`).\n\nThe `β` parameter defines trade-off between _homogeneity_ and _completeness_:\n * if `β` is greater than 1, _completeness_ is weighted more strongly,\n * if `β` is less than 1, _homogeneity_ is weighted more strongly.\n\n*Ref:* Andrew Rosenberg and Julia Hirschberg, 2007. \"V-Measure: A conditional entropy-based external cluster evaluation measure\"\n\"\"\"\nfunction vmeasure(assign1::Union{AbstractVector{<:Integer}, ClusteringResult},\n                  assign2::Union{AbstractVector{<:Integer}, ClusteringResult};\n                  β::Real = 1.0)\n    _assign1 = isa(assign1, AbstractVector) ? assign1 : assignments(assign1)\n    _assign2 = isa(assign2, AbstractVector) ? assign2 : assignments(assign2)\n    return _vmeasure(counts(_assign1, _assign2,\n                            (1:maximum(_assign1), 1:maximum(_assign2))), β=β)\nend\n", "meta": {"hexsha": "8163dd7789d86fa164aac7a8e5498204500b50aa", "size": 1642, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vmeasure.jl", "max_stars_repo_name": "leonardopetrini/Clustering.jl", "max_stars_repo_head_hexsha": "c16a31f0410cdf0fec29bc2c65383683348a6f7e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/vmeasure.jl", "max_issues_repo_name": "leonardopetrini/Clustering.jl", "max_issues_repo_head_hexsha": "c16a31f0410cdf0fec29bc2c65383683348a6f7e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vmeasure.jl", "max_forks_repo_name": "leonardopetrini/Clustering.jl", "max_forks_repo_head_hexsha": "c16a31f0410cdf0fec29bc2c65383683348a6f7e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5102040816, "max_line_length": 128, "alphanum_fraction": 0.6485992692, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7943609482194565}}
{"text": "#=\nGiven an array of numbers, find the maximum sum of any contiguous subarray of the array.\n\nFor example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, since we would take elements 42, 14, -5, and 86.\n\nGiven the array [-5, -1, -8, -9], the maximum sum would be 0, since we would not take any elements.\n\nDo this in O(N) time.\n=#\n\nfunction maximum_contiguous_sum(X::Array{Int,1})\n    max_sum = 0\n    current_subarray = []\n    current_sum = 0\n    for index in eachindex(X)\n        if current_sum + X[index] > 0\n            push!(current_subarray, X[index])\n            current_sum = current_sum + X[index]\n            if current_sum > max_sum\n                max_sum = current_sum\n            end\n        else\n            current_sum = 0\n            current_subarray = []\n        end\n    end\n    return max_sum\nend\n", "meta": {"hexsha": "93ea731efb6863fdd386cbd777d0028d83360fcd", "size": 839, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/problem49_maximum_sum_contiguous_subarray.jl", "max_stars_repo_name": "DominiqueCaron/daily-coding-problem", "max_stars_repo_head_hexsha": "41234497aa3a2c21c5dff43d86e9153d9582cced", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Solutions/problem49_maximum_sum_contiguous_subarray.jl", "max_issues_repo_name": "DominiqueCaron/daily-coding-problem", "max_issues_repo_head_hexsha": "41234497aa3a2c21c5dff43d86e9153d9582cced", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2019-06-17T14:04:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-12T20:01:45.000Z", "max_forks_repo_path": "Solutions/problem49_maximum_sum_contiguous_subarray.jl", "max_forks_repo_name": "DominiqueCaron/daily-coding-problem", "max_forks_repo_head_hexsha": "41234497aa3a2c21c5dff43d86e9153d9582cced", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9310344828, "max_line_length": 134, "alphanum_fraction": 0.6066746126, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8670357649558006, "lm_q1q2_score": 0.7942997976160143}}
{"text": "# Implement code blocks 3.11 through 3.19 in Statistical Rethinking, 2nd edition.\n\nusing Distributions\nusing Statistics\nusing StatsBase\nusing LinearAlgebra\n\ngrid_size = 1000\nnum_observations = 3\nnum_samples = 1000\n\n\n# Code block 3.11\nparam_grid = range(0, 1, length=grid_size)\nprior = ones((grid_size))\nlikelihood = [pdf(Binomial(3, p), num_observations) for p in param_grid]\nposterior = likelihood .* prior\nposterior = posterior / sum(posterior)\n\n@assert abs(sum(posterior) - 1) < 1e-4 \"Posterior does not sum to 1.\"\n@assert minimum(posterior) >= 0\n@assert maximum(posterior) <= 1\n\nsamples = sample(param_grid, Weights(posterior), num_samples; replace=true, ordered=false)\n\n\n# Code block 3.12\nfunction central_interval(samples, proba::AbstractFloat)\n    @assert proba > 0\n    @assert proba < 1\n    quantile(samples, [0.5 - proba / 2, 0.5 + proba / 2])\nend\n\ncentral_interval(samples, 0.5)\n\n\n# Code block 3.13\n\n# UPDATE: all the prob. prog. packages have it right. Because they *sort* the samples\n# first, they're really working with the ECDF. Subtracting in the domain of the ECDF\n# such that the range always has at least `proba` mass.\n\n# - I'm 85% sure the StatisticalRethinking.jl package has this wrong, it assumes\n#   some mass on both sides of the tail, which is not correct.\n\nfunction high_density_interval(samples, proba::AbstractFloat)\n    @assert proba >= 0\n    @assert proba <= 1\n\n    count_threshold = proba * length(samples)\n    hist = fit(Histogram, samples; closed=:right, nbins=100)\n\n    interval_mass = 0\n    start_index = 1\n    min_interval_length = Inf\n    candidate = (NaN, NaN)\n    candidate_mass = 0\n\n    for (i, w) in enumerate(hist.weights)\n        interval_mass += w\n\n        while interval_mass >= count_threshold\n            interval_length = i - start_index\n        \n            if (interval_length < min_interval_length) || \n                    ((interval_length == min_interval_length) &&\n                     interval_mass > candidate_mass)\n\n                candidate = (start_index, i)\n                candidate_mass = interval_mass\n                min_interval_length = interval_length\n            end\n\n            interval_mass = interval_mass - hist.weights[start_index]\n            start_index += 1\n        end\n    end\n\n    interval = [hist.edges[1][candidate[1]], hist.edges[1][candidate[2]]]\nend\n\nhigh_density_interval(samples, 0.5)\n\n\n# Code block 3.14 - MAP of the explicit posterior\n_, i = findmax(posterior)\nposterior_mode = param_grid[i]\n\n\n# Code block 3.15 - MAP based on posterior samples\n# - Based on a density estimate again\n\n\n# Code block 3.16\nmean(samples)\nmedian(samples)\n\n\n# Code block 3.17 - mean absolute error loss for a point estimate\nfunction mae_loss(point_estimate, param_grid, posterior)\n    sum(posterior .* abs.(point_estimate .- param_grid))\nend\n\nloss = mae_loss(0.5, param_grid, posterior)\n\n\n# Code blocks 3.18 and 3.19 - mean absolute error for all param values\n# - The book uses `sapply` in R. I don't know how to vectorize like that yet in Julia,\n#   so let's just loop.\nlosses = [mae_loss(p, param_grid, posterior) for p in param_grid]\n\n_, i = findmin(losses)\n\nbest_point_estimate = param_grid[i]\n", "meta": {"hexsha": "bcf02c9bca61d0b1cb39ef0092136fdb9d406790", "size": 3163, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3-11_sampling_stats.jl", "max_stars_repo_name": "CrosstabKite/stat_rethinking_julia", "max_stars_repo_head_hexsha": "5dd23fc7d2a438db59e4b45ae08d93503c1a4ef3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3-11_sampling_stats.jl", "max_issues_repo_name": "CrosstabKite/stat_rethinking_julia", "max_issues_repo_head_hexsha": "5dd23fc7d2a438db59e4b45ae08d93503c1a4ef3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3-11_sampling_stats.jl", "max_forks_repo_name": "CrosstabKite/stat_rethinking_julia", "max_forks_repo_head_hexsha": "5dd23fc7d2a438db59e4b45ae08d93503c1a4ef3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5043478261, "max_line_length": 90, "alphanum_fraction": 0.6911160291, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.8615382165412809, "lm_q1q2_score": 0.7942708989360763}}
{"text": "\"\"\"\n    kruskal_mst(g, distmx=weights(g); minimize=true)\n\nReturn a vector of edges representing the minimum (by default) spanning tree of a connected, \nundirected graph `g` with optional distance matrix `distmx` using [Kruskal's algorithm](https://en.wikipedia.org/wiki/Kruskal%27s_algorithm).\n\n### Optional Arguments\n- `minimize=true`: if set to `false`, calculate the maximum spanning tree.\n\"\"\"\nfunction kruskal_mst end\n# see https://github.com/mauro3/SimpleTraits.jl/issues/47#issuecomment-327880153 for syntax\n@traitfn function kruskal_mst(g::AG::(!IsDirected),\n    distmx::AbstractMatrix{T}=weights(g); minimize=true) where {T <: Real, U, AG <: AbstractGraph{U}}\n\n    connected_vs = IntDisjointSets(nv(g))\n\n    mst = Vector{edgetype(g)}()\n    sizehint!(mst, nv(g) - 1)\n\n    weights = Vector{T}()\n    sizehint!(weights, ne(g))\n    edge_list = collect(edges(g))\n    for e in edge_list\n        push!(weights, distmx[src(e), dst(e)])\n    end\n\n    weight = 0\n    for e in edge_list[sortperm(weights; rev=!minimize)]\n        if !in_same_set(connected_vs, src(e), dst(e))\n            union!(connected_vs, src(e), dst(e))\n            weight += distmx[src(e), dst(e)]\n            push!(mst, e)\n            (length(mst) >= nv(g) - 1) && break\n        end\n    end\n\n    return (mst=mst, weight=weight)\nend\n", "meta": {"hexsha": "946935c9361b7e2790a2755eff7baeb3c0d2aef0", "size": 1299, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spanningtrees/kruskal.jl", "max_stars_repo_name": "idan-weizman/LightGraphs.jl", "max_stars_repo_head_hexsha": "b2fc913ef5572abcdec6db9b0287e17d2ef9a8b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/spanningtrees/kruskal.jl", "max_issues_repo_name": "idan-weizman/LightGraphs.jl", "max_issues_repo_head_hexsha": "b2fc913ef5572abcdec6db9b0287e17d2ef9a8b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spanningtrees/kruskal.jl", "max_forks_repo_name": "idan-weizman/LightGraphs.jl", "max_forks_repo_head_hexsha": "b2fc913ef5572abcdec6db9b0287e17d2ef9a8b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3076923077, "max_line_length": 141, "alphanum_fraction": 0.6520400308, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.7942708851976213}}
{"text": "# back-substitution jl\r\n\r\n\"\"\"\r\nPerforms Rx = b by back_substitution\r\n\r\n# Arguments\r\n- `R::Array{Float64,2}`: diagonal matrix of size m x m\r\n- `x::Array{Float64,1}`: vector of size m. The result is stored in x.\r\n- `b::Array{Float64,1}`: vector of size m.\r\n\r\n# Complexity\r\n\r\nO(m^2)\r\n\r\n\"\"\"\r\nfunction back_substitution_v!(R, x, b)\r\n    (_, m) = size(R)\r\n\r\n    x .= 0\r\n\r\n    # O(m^2)\r\n    @inbounds for i = m:-1:1 \r\n        b_i = b[i]\r\n        for k = i + 1:m\r\n            b_i = b_i - R[i,k] * x[k]\r\n        end\r\n        x[i] = b_i / R[i,i]\r\n    end    \r\n    \r\nend\r\n\r\n\"\"\"\r\nPerforms RW = V by back_substitution\r\n\r\n# Arguments\r\n- `R::Array{Float64,2}`: diagonal matrix of size m x m\r\n- `V::Array{Float64,2}`: matrix of size m x k\r\n- `W::Array{Float64,2}`: matrix of size m x k. The result is stored in W.\r\n\r\n# Complexity\r\n\r\nO(km^2)\r\n\r\n\"\"\"\r\nfunction back_substitution!(R,V,W)\r\n\r\n    (_,k) = size(V)\r\n    (m,_) = size(R)\r\n\r\n    #Complexity: O(km^2)\r\n    @views @inbounds for i = 1 : k\r\n        V[:,i] .= 0\r\n        for j = m:-1:1 \r\n            V[j,i] = W[j,i]/R[j,j];\r\n            @. W[1:j-1,i] = W[1:j-1,i] - R[1:j-1,j]*V[j,i];\r\n        end    \r\n    end\r\n\r\nend", "meta": {"hexsha": "89ece496906c0168f8c1e1dfc59ba11b14763d53", "size": 1152, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "back_substitution.jl", "max_stars_repo_name": "MazzeiM/Alternating-Least-Square-With-QR", "max_stars_repo_head_hexsha": "8d3494c78d36496a435b259d6affcfefe2247d9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "back_substitution.jl", "max_issues_repo_name": "MazzeiM/Alternating-Least-Square-With-QR", "max_issues_repo_head_hexsha": "8d3494c78d36496a435b259d6affcfefe2247d9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "back_substitution.jl", "max_forks_repo_name": "MazzeiM/Alternating-Least-Square-With-QR", "max_forks_repo_head_hexsha": "8d3494c78d36496a435b259d6affcfefe2247d9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5254237288, "max_line_length": 74, "alphanum_fraction": 0.4921875, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741298, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7942708827211492}}
{"text": "function gen_β(β, η, D, R)\n    α = 2.0 .- β .^ (-  η - 1.0 )\n    mask = R .<= 1.0 ./ α\n    s = 1.0 / (η + 1.0)\n    βq = [ mask[i] ?  (R[i] * α[i])^s : (1.0 / (2.0 - R[i]*α[i]))^s for i in 1:D]\n    βq\nend\n\n\"\"\"\n    SBX_crossover(vector1, vector2, bounds, η=15, p_variable = 0.9)\n\nSimulated binomial crossover for given two `Vectors{Real}`.\n\"\"\"\nfunction SBX_crossover(vector1, vector2, bounds, η=15, p_variable = 0.9)\n    xu = view(bounds, 2,:)\n    xl = view(bounds, 1,:)\n    D = length(vector1)\n\n    do_crossover = ones(Bool, D)\n    do_crossover[rand(D) .> p_variable] .= false\n    do_crossover[ abs.( vector2 - vector1 ) .<= eps() ] .= false\n\n    y1 = min.( vector1, vector2 )\n    y2 = max.( vector1, vector2 )\n    Δ = max.(eps(), y2 - y1)\n\n\n    R = rand(D)\n\n    β = @. 1.0 + (2.0 * (y1 - xl) / Δ)\n    βq = gen_β(β, η, D, R) \n    c1 = @. 0.5*(y1 + y2 -  βq*Δ)\n\n    β = @. 1.0 + (2.0 * (y1 - xl) / Δ)\n    βq = gen_β(β, η, D, R) \n    c2 = @. 0.5*(y1 + y2 +  βq*Δ)\n\n    # swap\n    mask = rand(Bool, D)\n    cc = copy(c1)\n    c1[mask] = c2[mask]\n    c2[mask] = cc[mask]\n\n    cc1 = copy(vector1)\n    cc1[do_crossover] = c1[do_crossover]\n    cc2 = copy(vector2)\n    cc2[do_crossover] = c2[do_crossover]\n\n\n    reset_to_violated_bounds!(cc1, bounds)\n    reset_to_violated_bounds!(cc2, bounds)\n\n    return cc1, cc2\nend\n\n\"\"\"\n    DE_crossover(x, u, CR)\n\nBinomial crossover between x and u for Differential Evolution with probability CR, i.e.,\n`v[j] = u[j]` if `rand() < CR`, otherwise `v[j] = x[j]`. Return `v`.\n\"\"\"\nfunction DE_crossover(x, u, CR)\n    D = length(x)\n    # binomial crossover\n    v = zeros(D)\n    j_rand = rand(1:D)\n\n    # binomial crossover\n    for j = 1:D\n        if rand() < CR || j == j_rand\n            v[j] = u[j]\n        else\n            v[j] = x[j]\n        end\n    end\n\n    return v\nend\n\n", "meta": {"hexsha": "40c4467b2f3bae40fb804ca1677f88fd8dc0a21a", "size": 1798, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/common/crossover.jl", "max_stars_repo_name": "jbytecode/Metaheuristics.jl", "max_stars_repo_head_hexsha": "939c0cd9d92ef06c320480725c809e89e1dc9e14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 89, "max_stars_repo_stars_event_min_datetime": "2018-03-07T07:11:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:57:16.000Z", "max_issues_repo_path": "src/common/crossover.jl", "max_issues_repo_name": "jbytecode/Metaheuristics.jl", "max_issues_repo_head_hexsha": "939c0cd9d92ef06c320480725c809e89e1dc9e14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-01-30T23:03:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T15:45:15.000Z", "max_forks_repo_path": "src/common/crossover.jl", "max_forks_repo_name": "jbytecode/Metaheuristics.jl", "max_forks_repo_head_hexsha": "939c0cd9d92ef06c320480725c809e89e1dc9e14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-06-08T10:06:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:15:35.000Z", "avg_line_length": 22.475, "max_line_length": 88, "alphanum_fraction": 0.5244716352, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937033, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7942214550765855}}
{"text": "# Ranking based Metrics for Recommender Systems\n\n\"\"\"\n    ranking_stats_k(y_rec, y_rel, k = 10)\n\nEvaluates the relevancy of top k recommendations using `precison@k`, `recall@k` and `f1_score@k`. Returns result as a `Dict`.\n\nHere, `y_rec` are predicted probabilities for recommendation and `y_rel` defines as `1` if particular result is relevant, else `0`.\nThe shape of `y_rec` and `y_rel` are expected to be (1, N_elements).<br>\n\n* `precison_k` is evaluated as `Recommended_items_that_are_relevant / Total_Recommended_items`.\n* `recall_l` is evaluated as `Recommended_items_that_are_relevant / Total_Relevant_items`.\n* `f1_k` is evaluated as `2 * Recommended_items_that_are_relevant / (Total_Recommended_items + Total_Relevant_items)`.\n\"\"\"\nfunction ranking_stats_k(y_rec, y_rel; k = 10)\n    @assert size(y_rec) == size(y_rel)\n    if size(y_rec,1) !=1\n       y_rec = reshape(y_rec, 1, :)\n       y_rel = reshape(y_rel, 1, :)\n    end\n    top_k = partialsortperm(y_rec[1,:], 1:k, lt= >)\n    y_rec_k, y_rel_k = y_rec[:, top_k], y_rel[:, top_k]\n    tp = sum(y_rel_k .== 1)\n    total_positive = sum(y_rel.==1)\n    precision_k = k!=0 ? tp / k : 1\n    recall_k = total_positive!=0 ? tp / total_positive : 1\n    f1_k = (total_positive + k!=0) ? (2 * tp / (total_positive + k)) : 1 \n    return Dict(\"precision_k\" => precision_k,\n                \"recall_k\" => recall_k,\n                \"f1_k\" => f1_k)\nend\n\n\"\"\"\n    avg_precision(y_rec, y_rel, k = 10)\n\nEvaluates how much of the relevant documents are concentrated in the highest ranked predictions. \n\nCalculated as\n    `∑(Recall@i - Recall@i-1)* Precision@i for i = (1, 2, 3....k)`\n\nHere, `y_rec` are predicted probabilities for recommendation and `y_rel` defines as `1` if particular result is relevant, else `0`.\nThe shape of `y_rec` and `y_rel` are expected to be (1, N_elements)\n\"\"\"\nfunction avg_precision(y_rec, y_rel; k = 10)\n    @assert size(y_rec) == size(y_rel)\n    if size(y_rec,1) !=1\n       y_rec = reshape(y_rec, 1, :)\n       y_rel = reshape(y_rel, 1, :)\n    end\n    top_k = partialsortperm(y_rec[1,:], 1:k, lt= >)\n    y_rec_k, y_rel_k = y_rec[:, top_k], y_rel[:, top_k]\n    correct_prediction = 0\n    running_sum = 0\n    for i in 1:k\n        if y_rel_k[i] == 1\n            correct_prediction +=1\n            running_sum += correct_prediction / i\n        end\n    end\n    return running_sum / sum(y_rel .== 1)\nend\n\n# TODO\n\n# DCG\n# NDCG\n\n\n", "meta": {"hexsha": "099d05139519e584bcb18dd14e1b4581585e8b5f", "size": 2387, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Ranking_n_Statistical.jl", "max_stars_repo_name": "yuehhua/Metrics.jl", "max_stars_repo_head_hexsha": "6dc6fd6155afe551dd6424debdf7f034e68acb29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-06-02T14:09:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T00:08:26.000Z", "max_issues_repo_path": "src/Ranking_n_Statistical.jl", "max_issues_repo_name": "yuehhua/Metrics.jl", "max_issues_repo_head_hexsha": "6dc6fd6155afe551dd6424debdf7f034e68acb29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-12-22T06:28:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T02:47:49.000Z", "max_forks_repo_path": "src/Ranking_n_Statistical.jl", "max_forks_repo_name": "yuehhua/Metrics.jl", "max_forks_repo_head_hexsha": "6dc6fd6155afe551dd6424debdf7f034e68acb29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-13T11:32:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T06:04:19.000Z", "avg_line_length": 34.5942028986, "max_line_length": 131, "alphanum_fraction": 0.6531210725, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7942214545178845}}
{"text": "import Distributions: cdf, Normal\n\nN(x) = cdf(Normal(), x)\n\nfunction d1(S, K, τ, r, σ, q)\n    return (log(S / K) + (r - q + σ^2 / 2) * τ) / (σ * √(τ))\nend\n\nfunction d2(S, K, τ, r, σ, q)\n    return d1(S, K, τ, r, σ, q) - σ * √(τ)\nend\n\n\"\"\"\n    eurocall(;S=1.,K=1.,τ=1,r,σ,q=0.)\n\nCalculate the Black-Scholes implied option price for a european call, where:\n\n- `S` is the current asset price\n- `K` is the strike or exercise price\n- `τ` is the time remaining to maturity (can be typed with \\\\tau[tab])\n- `r` is the continuously compounded risk free rate\n- `σ` is the (implied) volatility (can be typed with \\\\sigma[tab])\n- `q` is the continuously paid dividend rate\n\nRates should be input as rates (not percentages), e.g.: `0.05` instead of `5` for a rate of five percent.\n\n!!! Experimental: this function is well-tested, but the derivatives functionality (API) may change in a future version of ActuaryUtilities.\n\n# Extended Help\n\nThis is the same as the formulation presented in the [dividend extension of the BS model in Wikipedia](https://en.wikipedia.org/wiki/Black%E2%80%93Scholes_model#Black%E2%80%93Scholes_equation).\n\n## Other general comments:\n\n- Swap/OIS curves are generally better sources for `r` than government debt (e.g. US Treasury) due to the collateralized nature of swap instruments.\n- (Implied) volatility is characterized by a curve that is a function of the strike price (among other things), so take care when using \n- Yields.jl can assist with converting rates to continuously compounded if you need to perform conversions.\n\n\"\"\"\nfunction eurocall(; S = 1.0, K = 1.0, τ = 1, r, σ, q = 0.0)\n    d₁ = d1(S, K, τ, r, σ, q)\n    d₂ = d2(S, K, τ, r, σ, q)\n    return (N(d₁) * S * exp(τ * (r - q)) - N(d₂) * K) * exp(-r * τ)\nend\n\n\"\"\"\n    europut(;S=1.,K=1.,τ=1,r,σ,q=0.)\n\nCalculate the Black-Scholes implied option price for a european call, where:\n\n- `S` is the current asset price\n- `K` is the strike or exercise price\n- `τ` is the time remaining to maturity (can be typed with \\\\tau[tab])\n- `r` is the continuously compounded risk free rate\n- `σ` is the (implied) volatility (can be typed with \\\\sigma[tab])\n- `q` is the continuously paid dividend rate\n\nRates should be input as rates (not percentages), e.g.: `0.05` instead of `5` for a rate of five percent.\n\n\n!!! Experimental: this function is well-tested, but the derivatives functionality (API) may change in a future version of ActuaryUtilities.\n\n# Extended Help\n\nThis is the same as the formulation presented in the [dividend extension of the BS model in Wikipedia](https://en.wikipedia.org/wiki/Black%E2%80%93Scholes_model#Black%E2%80%93Scholes_equation).\n\n## Other general comments:\n\n- Swap/OIS curves are generally better sources for `r` than government debt (e.g. US Treasury) due to the collateralized nature of swap instruments.\n- (Implied) volatility is characterized by a curve that is a function of the strike price (among other things), so take care when using \n- Yields.jl can assist with converting rates to continuously compounded if you need to perform conversions.\n\n\"\"\"\nfunction europut(; S = 1.0, K = 1.0, τ = 1, r, σ, q = 0.0)\n    d₁ = d1(S, K, τ, r, σ, q)\n    d₂ = d2(S, K, τ, r, σ, q)\n    return (N(-d₂) * K - N(-d₁) * S * exp(τ * (r - q))) * exp(-r * τ)\nend", "meta": {"hexsha": "8088716246bf1ba609f538e97c3a8177dc5a9c64", "size": 3249, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/derivatives.jl", "max_stars_repo_name": "alecloudenback/ActuaryUtilities", "max_stars_repo_head_hexsha": "fe323b90e571e51b72ecd62417828b90d411627a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/derivatives.jl", "max_issues_repo_name": "alecloudenback/ActuaryUtilities", "max_issues_repo_head_hexsha": "fe323b90e571e51b72ecd62417828b90d411627a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/derivatives.jl", "max_forks_repo_name": "alecloudenback/ActuaryUtilities", "max_forks_repo_head_hexsha": "fe323b90e571e51b72ecd62417828b90d411627a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6538461538, "max_line_length": 193, "alphanum_fraction": 0.6891351185, "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7942214544627304}}
{"text": "function KalmanFilter(T::Matrix, Z::Matrix, Q::Matrix, H::Matrix, n::Integer, α0, y)\n    \n    # Initialize state variables\n    αhat = repeat([zeros(size(α0))], n);\n    αhat[1] = T*α0;\n\n    println(\"I'm here 1\")\n\n    yhat = repeat([zeros(size(y[1]))], n);\n    v = copy(yhat);\n\n    P0 = [2.0]; # Initial guess given in the problem\n    \n    P = repeat([zeros(size(Q))], n);\n    P[1] = T * P0 * T' + Q;\n\n    println(\"I'm here 2, P[1] = $(P[1])\")\n\n    F = repeat([zeros(size(H))], n)\n    G = repeat([zeros(size(Z * Q))], n)\n    K = repeat([zeros(size(T * G[1]' * ones(size(H))))], n)\n\n    for i in 1:n-1\n        yhat[i] = Z * αhat[i];\n        v[i] = y[i] - yhat[i];\n\n        F[i] = Z * P[i] * Z' + H;\n        G[i] = Z * P[i];\n        K[i] = T * G[i]' * inv(F[i]);\n\n        αhat[i + 1] = T * αhat[i] + K[i] * v[i];\n        P[i + 1] = T * (P[i] - G[i]' * inv(F[i]) * G[i]) * T' + Q;\n    end\n\n    yhat[n] = Z * αhat[n];\n    v[n] = y[n] - yhat[n];\n    \n    F[n] = Z * P[n] * Z' + H;\n    G[n] = Z * P[n];\n    K[n] = T * G[n]' * inv(F[n]);\n\n    return αhat, v, yhat, P, F, G, K\nend", "meta": {"hexsha": "0ea4be5c66428c8be3ca47dbb7acbddb1ccec1f3", "size": 1070, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Anmol/PS1/KalmanFilter.jl", "max_stars_repo_name": "wongr003/ECON8185", "max_stars_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Anmol/PS1/KalmanFilter.jl", "max_issues_repo_name": "wongr003/ECON8185", "max_issues_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Anmol/PS1/KalmanFilter.jl", "max_forks_repo_name": "wongr003/ECON8185", "max_forks_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8837209302, "max_line_length": 84, "alphanum_fraction": 0.4214953271, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7942214532901738}}
{"text": "###########################################\n# Unconstrained optimization\n###########################################\n\nf(x) = sin(x[1] + x[2]) + cos(x[1])^2\ng(x) = [cos(x[1] + x[2]) - 2*cos(x[1])*sin(x[1]); cos(x[1] + x[2])]\n\nf(x1,x2) = f([x1;x2])\n\nf([0; 0])\nf(0, 0)\n\n#### Exercise\n\nusing Plots\n\nxs = range(-3, 1, length = 40)\nys = range(-2, 1, length = 40)\n\ncontourf(xs, ys, f, color = :jet)\n\n#### Exercise\n\nfinite_difference(f, x::Real; h=1e-8) = (f(x+h) - f(x)) / h\n\n#### Exercise\n\nx = [-2; -1]\nfin_diff(h) = finite_difference(y -> f(x[1], y), x[2]; h=h)\n\ntrue_grad = g(x)[2]\n\nhs = 10. .^ (-15:0.01:-1)\n\nplot(hs, fin_diff,\n    xlabel = \"h\",\n    ylabel = \"Partial gradient wrt y\",\n    label = [\"Approximation\" \"True gradient\"],\n    xscale = :log10,\n)\n\nhline!([true_grad]; label =  \"True gradient\")\n\n#### Numerical errors\n\nx = 1\nh = 1e-13\n\n(x+h)^2 - x^2\n2*x*h + h^2\n\n#### Exercise\n\nx = [-2; -1]\nα = 0.25\nx_grad = [x x.+α.*g(x)]\n\ncontourf(xs, ys, f; color = :jet)\nplot!(x_grad[1, :], x_grad[2, :];\n    line = (:arrow, 4, :black),\n    label = \"\",\n)\n\n#### Exercise\n\nfunction optim(f, g, x, α; max_iter=100)\n    xs = zeros(length(x), max_iter+1)\n    xs[:,1] = x\n    for i in 1:max_iter\n        x -= α*g(x)\n        xs[:,i+1] = x\n    end\n    return xs\nend\n\n#### Animation\n\nusing Random\n\nfunction create_anim(\n    f,\n    path,\n    xlims,\n    ylims,\n    file_name = joinpath(pwd(), randstring(12) * \".gif\");\n    xbounds = xlims,\n    ybounds = ylims,\n    fps = 15,\n)\n    xs = range(xlims...; length = 100)\n    ys = range(ylims...; length = 100)\n    plt = contourf(xs, ys, f; color = :jet)\n\n    # add constraints if provided\n    if !(xbounds == xlims && ybounds == ylims)\n        x_rect = [xbounds[1]; xbounds[2]; xbounds[2]; xbounds[1]; xbounds[1]]\n        y_rect = [ybounds[1]; ybounds[1]; ybounds[2]; ybounds[2]; ybounds[1]]\n        \n        plot!(x_rect, y_rect; line = (2, :dash, :red), label=\"\")\n    end\n\n    # add an empty plot\n    plot!(Float64[], Float64[]; line = (4, :arrow, :black), label = \"\")\n\n    # extract the last plot series\n    plt_path = plt.series_list[end]\n\n    # create the animation and save it\n    anim = Animation()\n    for x in eachcol(path)\n        push!(plt_path, x[1], x[2]) # add a new point\n        frame(anim)\n    end\n    gif(anim, file_name; fps = fps, show_msg = false)\n    return nothing\nend\n\n#### Exercise\n\nx_gd = optim([], g, [0; -1], 0.1)\n\nxlims = (-3, 1)\nylims = (-2, 1)\ncreate_anim(f, x_gd, xlims, ylims, \"anim1.gif\")\n\nf_gd = [f(x) for x in eachcol(x_gd)]\n\nplot(f_gd, label=\"\", xlabel=\"Iteration\", ylabel=\"Function value\")\n\n#### Different stepsizes\n\nx_gd = optim([], g, [0; -1], 0.01)\n\ncreate_anim(f, x_gd, xlims, ylims, \"anim2.gif\")\n\nx_gd = optim([], g, [0; -1], 1)\n\ncreate_anim(f, x_gd, xlims, ylims, \"anim3.gif\")\n\n#### Stepsize selection\n\nabstract type Step end\n\nstruct GD <: Step\n    α::Float64\nend\n\n#### Gradient descent\n\noptim_step(s::GD, f, g, x) = -s.α*g(x)\n\nfunction optim(f, g, x, s::Step; max_iter=100)\n    xs = zeros(length(x), max_iter+1)\n    xs[:,1] = x\n    for i in 1:max_iter\n        x += optim_step(s, f, g, x)\n        xs[:,i+1] = x\n    end\n    return xs\nend\n\ngd = GD(0.1)\nx_opt = optim(f, g, [0;-1], gd)\n\ncreate_anim(f, x_opt, xlims, ylims, \"anim4.gif\")\n\n#### Exercise\n\nstruct Armijo <: Step\n    c::Float64\n    α_max::Float64\nend\n\nfunction optim_step(s::Armijo, f, g, x)\n    fun = f(x)\n    grad = g(x)\n    α = s.α_max\n    while f(x .- α*grad) > fun - s.c*α*(grad'*grad)\n        α /= 2\n        if α <= 1e-6\n            warning(\"Armijo line search failed.\")\n            break\n        end\n    end\n    return -α*grad\nend\n\ngd = Armijo(1e-4, 1)\nx_opt = optim(f, g, [0;-1], gd)\n\ncreate_anim(f, x_opt, xlims, ylims, \"anim5.gif\")\n\n###########################################\n# Constrained optimization\n###########################################\n\nf(x) = sin(x[1] + x[2]) + cos(x[1])^2\ng(x) = [cos(x[1] + x[2]) - 2*cos(x[1])*sin(x[1]); cos(x[1] + x[2])]\n\nf(x1,x2) = f([x1;x2])\n\n#### Projected gradients\n\nfunction optim(f, g, P, x, α; max_iter=100)\n    xs = zeros(length(x), max_iter+1)\n    ys = zeros(length(x), max_iter)\n    xs[:,1] = x\n    for i in 1:max_iter\n        ys[:,i] = xs[:,i] - α*g(xs[:,i])\n        xs[:,i+1] = P(ys[:,i])\n    end\n    return xs, ys\nend\n\nP(x, x_min, x_max) = min.(max.(x, x_min), x_max)\n\nx_min = [-1; -1]\nx_max = [0; 0]\n\nxs, ys = optim(f, g, x -> P(x,x_min,x_max), [0;-1], 0.1)\n\n#### Plot 1\n\nxlims = (-3, 1)\nylims = (-2, 1)\n\ncreate_anim(f, xs, xlims, ylims, \"anim6.gif\";\n    xbounds=(x_min[1], x_max[1]),\n    ybounds=(x_min[2], x_max[2]),\n)\n\n#### Plot 2\n\nxys = hcat(reshape([xs[:,1:end-1]; ys][:], 2, :), xs[:,end])\n\ncreate_anim(f, xys, xlims, ylims, \"anim7.gif\";\n    xbounds=(x_min[1], x_max[1]),\n    ybounds=(x_min[2], x_max[2]),\n)\n\n\n", "meta": {"hexsha": "b4048fe9a4434ec0f54dc6ab848bd7722432a859", "size": 4702, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/lecture_07/script.jl", "max_stars_repo_name": "rzehumat/JuliaCourse", "max_stars_repo_head_hexsha": "ee26c21e90ab5d3d67ad979910d750683304e83c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-06-04T12:03:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T21:43:02.000Z", "max_issues_repo_path": "docs/src/lecture_07/script.jl", "max_issues_repo_name": "rzehumat/JuliaCourse", "max_issues_repo_head_hexsha": "ee26c21e90ab5d3d67ad979910d750683304e83c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/src/lecture_07/script.jl", "max_forks_repo_name": "rzehumat/JuliaCourse", "max_forks_repo_head_hexsha": "ee26c21e90ab5d3d67ad979910d750683304e83c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-20T19:57:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T03:27:21.000Z", "avg_line_length": 19.4297520661, "max_line_length": 77, "alphanum_fraction": 0.5221182476, "num_tokens": 1724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7942214449791307}}
{"text": "@doc raw\"\"\"\n    gauss_quadrature(q)\n\nReturn the Gauss-Legendre quadrature rule with `q` points (integrates polynomials of degree\n$2q-1$ exactly).\n\nA tuple `(x,w)` is returned.\n\"\"\"\nfunction gauss_quadrature(q)\n    x = zeros(CeedScalar, q)\n    w = zeros(CeedScalar, q)\n    C.CeedGaussQuadrature(q, x, w)\n    x, w\nend\n\nstruct QuadratureMode{T} end\nconst Abscissa = QuadratureMode{:Abscissa}()\nconst AbscissaAndWeights = QuadratureMode{:AbscissaAndWeights}()\n\n@doc raw\"\"\"\n    lobatto_quadrature(q, mode::Mode=Abscissa)\n\nReturn the Gauss-Lobatto quadrature rule with `q` points (integrates polynomials of degree\n$2q-3$ exactly).\n\nIf `mode` is `AbscissaAndWeights`, then both the weights and abscissa are returned as a\ntuple `(x,w)`.\n\nOtherwise, (if `mode` is `Abscissa`), then only the abscissa `x` are returned.\n\"\"\"\nfunction lobatto_quadrature(q, mode::Mode=Abscissa) where {Mode}\n    return_weights = (mode == AbscissaAndWeights)\n    x = zeros(CeedScalar, q)\n    w = (return_weights) ? zeros(CeedScalar, q) : C_NULL\n    C.CeedLobattoQuadrature(q, x, w)\n    return_weights ? (x, w) : x\nend\n", "meta": {"hexsha": "610fcbbe641943000b2fef6a8cee2716ff449e02", "size": 1086, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/LibCEED.jl/src/Quadrature.jl", "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 123, "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_issues_repo_path": "julia/LibCEED.jl/src/Quadrature.jl", "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 781, "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_forks_repo_path": "julia/LibCEED.jl/src/Quadrature.jl", "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "avg_line_length": 28.5789473684, "max_line_length": 91, "alphanum_fraction": 0.711786372, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7942089430730634}}
{"text": "# ---\n# title: 50. Pow(x, n)\n# id: problem50\n# author: zhwang\n# date: 2022-03-02\n# difficulty: Medium\n# categories: Math, Binary Search\n# link: <https://leetcode.com/problems/powx-n/description/>\n# hidden: true\n# ---\n# \n# Implement [pow( _x_ , _n_\n# )](http://www.cplusplus.com/reference/valarray/pow/), which calculates  _x_\n# raised to the power _n_ (i.e. xn).\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: x = 2.00000, n = 10\n#     Output: 1024.00000\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: x = 2.10000, n = 3\n#     Output: 9.26100\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: x = 2.00000, n = -2\n#     Output: 0.25000\n#     Explanation: 2-2 = 1/22 = 1/4 = 0.25\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `-100.0 < x < 100.0`\n#   * `-231 <= n <= 231-1`\n#   * `-104 <= xn <= 104`\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction my_pow(x::Float64, n::Int)::Float64\n    n == 0 && return 1\n    if n < 0\n        x, n = 1 / x, -n\n    end\n    res, extra = x, 1\n    while n > 1\n        n & 1 == 1 && (extra *= res)\n        res *= res\n        n >>= 1\n    end\n    return res * extra\nend\n## @lc code=end\n", "meta": {"hexsha": "d659aa027308e825e6a135666046a765f4808708", "size": 1137, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/50.powx-n.jl", "max_stars_repo_name": "RexWzh/LeetCode.jl", "max_stars_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/50.powx-n.jl", "max_issues_repo_name": "RexWzh/LeetCode.jl", "max_issues_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/50.powx-n.jl", "max_forks_repo_name": "RexWzh/LeetCode.jl", "max_forks_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.4782608696, "max_line_length": 77, "alphanum_fraction": 0.4810905893, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.794193171756684}}
{"text": "function EuropeanDownAndOutCallMC(K, T, S, sig, r, div, H, N, M)\n\n\ndt = T/N\nnudt = (r - div - 0.5 * sig^2) * dt\nsigsdt = sig * sqrt(dt)\n\n\n## variables to store the sums of the option values\n\nsum_CT = 0\nsum_CT2 = 0\n\n## outer loop is the number of simulations bigger is better\n\nfor j = 1:M\n\n        St = S\n        BARRIERCROSSED = false\n    ## inner loop is simulating each price path of length N\n        for i = 1:N\n\n        St = St * exp( nudt + sigsdt * randn()) ## note, it only add the changes, does not store the path\n\n        if St <= H\n\n                BARRIERCROSSED = true\n                break\n        end\n\n        end\n\n    ## wraps up and stores all the values of each path\n\nif BARRIERCROSSED == true\n            CT = 0\n\n        else\n\n            CT = max(0, St - K)\n        end\n\nsum_CT = sum_CT + CT\nsum_CT2 = sum_CT2 + CT^2\n\n    end\n\n  ## discounting the average call value\ncall_value = sum_CT / M * exp(-r*T)\n\n\nSD = (sqrt(sum_CT2 - 1/M * (sum_CT^2)) * exp(-2*r*T)) / (M-1)\nSE = SD / sqrt(M)\n\nprintln(\"The Call Value is $call_value\")\nprintln(\"The SD is $SD\")\nprintln(\"The SE is $SE\")\n\nMC = [call_value, SD, SE]\n\nend\n\n\n\n", "meta": {"hexsha": "b1855b04784fe5555d14001c660447c061949b99", "size": 1131, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/IB/PricingEngines/EuropeanDownAndOutCallMC.jl", "max_stars_repo_name": "SvenDuve/JuliaAOT.jl", "max_stars_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/IB/PricingEngines/EuropeanDownAndOutCallMC.jl", "max_issues_repo_name": "SvenDuve/JuliaAOT.jl", "max_issues_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IB/PricingEngines/EuropeanDownAndOutCallMC.jl", "max_forks_repo_name": "SvenDuve/JuliaAOT.jl", "max_forks_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-27T15:45:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-27T15:45:30.000Z", "avg_line_length": 17.4, "max_line_length": 105, "alphanum_fraction": 0.566755084, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545377452443, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7941931710621336}}
{"text": "function MultBinTreeAMPut(K, T, S, r, N, u, d)\n        dt = T/N ## Time to Maturity/ Number of Steps\n        p = (exp(r * dt) - d) / (u - d)\n        disc = exp(-r * dt)\n\n        #St = linspace(1,N+1,N+1)\n\n        St = Array(Float64, (N+1, N+1))\n\n        # Initialising asset prices at maturity\n\n        St[1 , N+1] = S * u^N\n        for j in 2:(N+1)\n                St[j, N+1] = St[j-1, N+1] * d/u\n        end\n\n        #St = flipdim(St, 1)\n\n        # create Array for options value tree\n\n        P = Array(Float64, (N+1, N+1))#linspace(1, N+1, N+1)\n\n        # Initialise Option Values at maturity\n\n        for j in 1:(N+1)\n                P[j, N+1] = max(0.0, K - St[j, N+1])\n        end\n\n        # Stepping back through the tree\n\n        for i = linrange(N, 1, N)\n                for j in 1:i\n                      P[j, i] = disc * (p * P[j, i+1] + (1-p) * P[j+1, i+1])\n                      St[j,i] = St[j,i+1] * d\n                      P[j, i] = max(P[j, i], K - St[j,i])\n                end\n        end\n\nP\n\nend\n\nMultBinTreeAMPut(100,1,100,0.06,3,1.1,0.9091)\n\n", "meta": {"hexsha": "ba4d0d92b0c918ebf54c235c127d7f879dd6870c", "size": 1063, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/IB/PricingEngines/MultBinTreeAMPut.jl", "max_stars_repo_name": "SvenDuve/JuliaAOT.jl", "max_stars_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/IB/PricingEngines/MultBinTreeAMPut.jl", "max_issues_repo_name": "SvenDuve/JuliaAOT.jl", "max_issues_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IB/PricingEngines/MultBinTreeAMPut.jl", "max_forks_repo_name": "SvenDuve/JuliaAOT.jl", "max_forks_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-27T15:45:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-27T15:45:30.000Z", "avg_line_length": 23.6222222222, "max_line_length": 76, "alphanum_fraction": 0.42144873, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995752693051, "lm_q2_score": 0.8221891218080991, "lm_q1q2_score": 0.7941521235454859}}
{"text": "export factors\nexport primefactors\nexport totient\n\n\"\"\"\nReturn sorted list of unique factors for a number n.\n\"\"\"\nfunction factors(n::Integer)::Array{Integer}\n    factors = Set{Integer}(1)\n    for i in 2:Integer(floor(sqrt(n)))\n        if n % i == 0\n            push!(factors, i)\n            push!(factors, div(n, i))\n        end\n    end\n    return sort(collect(factors))\nend\n\n\"\"\"\nReturn sorted list of prime factors for number n.\n\"\"\"\nfunction primefactors(n::Integer)::Array{Integer}\n    factors = ones(Integer, 0)\n\n    # Store all of the factors of 2.\n    while n % 2 == 0\n        push!(factors, 2)\n        n = fld(n, 2)\n    end\n\n    # Store all other prime factors, increasing to sqrt(n).\n    for i in 3:2:Integer(floor(sqrt(n)))\n        while n % i == 0\n            push!(factors, i)\n            n = fld(n, i)\n        end\n    end\n\n    # Store last prime factor.\n    if n > 1\n        push!(factors, n)\n    end\n\n    return sort(factors)\nend\n\n\"\"\"\nEuler's totient function returns the number of positive integers up to n that\nare releatively prime to n.  Pull out the prime factors f and take a produce of\nn and all (1 - 1/f).\n\"\"\"\nfunction totient(n::Integer)::Integer\n    factors = primefactors(n)\n    last_prime = 0\n    result = Float64(n)\n    for f in factors \n        if f == last_prime\n            continue\n        else\n            result *= (1 - 1 / f)\n            last_prime = f \n        end\n    end\n    return Integer(round(result))\nend\n", "meta": {"hexsha": "fa63bd1be9ef5fc8b1e1ca3c3ff1d6b2454377fa", "size": 1443, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/factorization.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/factorization.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/factorization.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8636363636, "max_line_length": 79, "alphanum_fraction": 0.5821205821, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305307578324, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7941468947787953}}
{"text": "half(L) = div(L - 1, 2)\n\nlogZ(M::Matrix) = logdet(I + M)\nZ(M::Matrix) = det(I + M)\n\nfunction pairing(L, h)\n    E(k) = sqrt(1 + h^2 + 2h * cospi((2k + 1) / L))\n    ζ(k) = - (h + cospi((2k + 1) / L))\n    u(k) = sqrt((1 + ζ(k) / E(k)) / 2)\n    v(k) = sqrt((1 - ζ(k) / E(k)) / 2)\n    g(r) = 2 / L * sum(sinpi((2k + 1) / L * r) * v(k) / u(k) for k in 0:div(L - 1, 2))\n\n    M = zeros(L, L)\n    for i in 1:L, j in 1:L\n        M[i,j] = g(i -  j) \n    end\n    return M\nend\n\nfunction get_prob(x::BitVector, M::Matrix)\n    amp = log(abs.(det(M[x .> 0, x .> 0])))\n    return amp\nend\n\nfunction get_all_probs(M::Matrix)\n    L = size(M, 1)\n    logZ = log(abs(det(M)))\n    x = i->bitarray(i, L)\n    amps = [get_prob(x(i), M) for i in 0:2^L - 1]\n    amps = exp.(amps)\n    amps2 = normalize(amps, 1)\n    return round.(amps, digits = 7), round.(amps2, digits = 7)\nend\n\n# for L in [2, 4,8,16,20, 32]\n#     P = pairing(L, 1.0)\n#     Z1 = logdet(I + P)\n#     Z2 = log(sum(get_all_probs(P)[1]))                                                   \n#     println(\"L is $L Z is $Z1 and $Z2\")\n# end\n", "meta": {"hexsha": "d5a91d6e9e04400500b6821b5945f3aa282bd60f", "size": 1071, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/new.jl", "max_stars_repo_name": "mbeach42/TFIMSampler", "max_stars_repo_head_hexsha": "2960be388174e612227177de0c0efe469cc485dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/new.jl", "max_issues_repo_name": "mbeach42/TFIMSampler", "max_issues_repo_head_hexsha": "2960be388174e612227177de0c0efe469cc485dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/new.jl", "max_forks_repo_name": "mbeach42/TFIMSampler", "max_forks_repo_head_hexsha": "2960be388174e612227177de0c0efe469cc485dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1219512195, "max_line_length": 91, "alphanum_fraction": 0.4603174603, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305339244013, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.794146893234977}}
{"text": "#=\nProject:      MIRTdev\nFile:         mri_geom_compress.jl\nDescription:  MRI Coil Compression\nAuthor:       Rajas Gupta\nDate Created: October 8th 2019\nDate Update:  October 8th 2019\n=#\n\nexport ir_mri_coil_compress\n\nusing LinearAlgebra: svd, norm\n\n\n\"\"\"\n    (odata, σ, Vr) = ir_mri_coil_compress(idata ; ncoil)\n\nMRI coil compression via PCA.\nGiven multiple MRI surface coil images (idata), use SVD/PCA\nto find a smaller number of virtual coil images (odata).\n\nIn:\n* `idata` `[(N) n_in]`: noisy complex images (2D or 3D) for each coil\n\nOption:\n* `ncoil` Desired # of virtual coils (default: 1)\n\nOut:\n* `odata` `[(N) ncoil]`: virtual coil images\n* `σ`     `[n_in]`: singular values.\n* `Vr`    `[n_in, ncoil]`: compression matrix for reducing other data.\n\ntodo: currently ignores noise correlations\n\n\"\"\"\nfunction ir_mri_coil_compress(idata::AbstractArray{<:Number} ; ncoil::Int = 1)\n\n    idim = size(idata)\n    n_in = idim[end]\n    idata = reshape(idata, :, n_in)\n\n    (_, σ, V) = svd(idata)\n\n    Vr = V[:, 1:ncoil]\n    odata = idata * Vr\n    odata = reshape(odata, idim[1:end-1]..., ncoil)\n    return (odata, σ, Vr)\nend\n\n\n\"\"\"\n    snr2sigma(db, yb)\nconvert SNR in dB to noise σ for complex gaussian noise\n\"\"\"\nfunction snr2sigma(db, yb::AbstractArray{<:Complex})\n    10^(-db/20) * norm(yb) / sqrt(length(yb)) / sqrt(2)\nend\n", "meta": {"hexsha": "9204df9a16eaec6078fe15c6e9de460c9a679093", "size": 1318, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mri/coil_compress.jl", "max_stars_repo_name": "jamesthesnake/MIRT.jl", "max_stars_repo_head_hexsha": "3a4b1e33a35e2ab062f532a22866bfb11f6e5cd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mri/coil_compress.jl", "max_issues_repo_name": "jamesthesnake/MIRT.jl", "max_issues_repo_head_hexsha": "3a4b1e33a35e2ab062f532a22866bfb11f6e5cd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mri/coil_compress.jl", "max_forks_repo_name": "jamesthesnake/MIRT.jl", "max_forks_repo_head_hexsha": "3a4b1e33a35e2ab062f532a22866bfb11f6e5cd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.724137931, "max_line_length": 78, "alphanum_fraction": 0.6631259484, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993028, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7941341813075168}}
{"text": "const ykow = [1.957e-1, 1.947e-1, 1.735e-1, 1.600e-1, 8.44e-2, 6.27e-2,\n              4.56e-2,  3.42e-2, 3.23e-2, 2.35e-2, 2.46e-2]\n\nconst ukow = [4.0e0, 2.0e0, 1.0e0, 5.0e-1, 2.5e-1, 1.67e-1,\n              1.25e-1, 1.0e-1, 8.33e-2, 7.14e-2, 6.25e-2]\n\nconst kowalik_osborne = let res_init=zeros(11), jac_init=zeros(11,4), x_init=[.25, .39, .415, .39]\n\n    function res(x, r)\n        for i = 1:11\n            r[i] = ykow[i] - x[1]*(ukow[i] ^ 2 + x[2] * ukow[i]) / (ukow[i] ^ 2 + x[3]*ukow[i] + x[4])\n        end\n        return r\n    end\n\n    function jac(x, j)\n        for i = 1:11\n            t = -1.e0 / (ukow[i]^2 + x[3] * ukow[i] + x[4])\n            j[i, 1] = t * (ukow[i]^2 + x[2] * ukow[i])\n            j[i, 2] = x[1] * ukow[i]*t\n            t = t * j[i, 1] * x[1]\n            j[i, 3] = ukow[i] * t\n            j[i, 4] = t\n        end\n        return j\n    end\n\n    f(;scale=1, verbose=false, print_steps=false) = testone(\"kowalik_osborne\", res, jac,\n                                                            res_init, jac_init, x_init;\n                                                            scale=scale, verbose=verbose,\n                                                            print_steps=print_steps)\nend\n", "meta": {"hexsha": "8a0fa6ad717a8c15c20dd03cc01e5c4fe1977969", "size": 1222, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/optests/kowalik_osborne.jl", "max_stars_repo_name": "macd/NL2sol.jl", "max_stars_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-01-19T21:59:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T00:42:56.000Z", "max_issues_repo_path": "test/optests/kowalik_osborne.jl", "max_issues_repo_name": "macd/NL2sol.jl", "max_issues_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/optests/kowalik_osborne.jl", "max_forks_repo_name": "macd/NL2sol.jl", "max_forks_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0303030303, "max_line_length": 102, "alphanum_fraction": 0.4083469722, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993028, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7941341756922379}}
{"text": "using Statistics\n\nexport testchaos01\n\n\"\"\"\n    testchaos01(φ::Vector [, cs, N0]) -> chaotic?\nPerform the so called \"0-1\" test for chaos introduced by Gottwald and\nMelbourne [1] on the timeseries `φ`.\nReturn `true` if `φ` is chaotic, `false` otherwise.\n\n## Description\nThis method tests if the given timeseries is chaotic or not by transforming\nit into a two-dimensional diffusive process. If the timeseries is chaotic,\nthe mean square displacement of the process grows as `sqrt(length(φ))`,\nwhile it stays constant if the timeseries is regular.\nThe implementation here computes `K`, the correlation coefficient (median\nof `Kc for c ∈ cs`), and simply checks if `K > 0.5`.\n\nIf you want to access the various `Kc` you should call the method\n`testchaos01(φ, c::Real, N0)` which returns `Kc`.\n\n`cs` defaults to `3π/5*rand(10) + π/4` and `N0`, the length\nof the two-dimensional process, is `N0 = length(φ)/10`.\n\nNotice that for data sampled from continous dynamical systems, some\ncare must be taken regarding the values of `cs`, see [1].\n\n## References\n\n[1] : Gottwald & Melbourne, “The 0-1 test for chaos: A review”\n[Lect. Notes Phys., vol. 915, pp. 221–247, 2016.](www.doi.org/10.1007/978-3-662-48410-4_7)\n\"\"\"\nfunction testchaos01(φ::Vector, cs = 3π/5*rand(10) .+ π/4, N0 = Int(length(φ)÷10))\n    K = median(testchaos01(φ, c, N0) for c in cs)\n    return K > 0.5\nend\n\nfunction testchaos01(φ::Vector, c::Real, N0 = Int(length(φ)÷10))\n    N, E = length(φ), mean(φ)\n    @assert N0 ≤ N/10\n    pc, qc = trigonometric_decomposition(φ, c)\n    Dc = mmsd(E, pc, qc, N0, c)\n    Kc = cor(Dc, 1:N0)\n    return Kc\nend\n\nfunction trigonometric_decomposition(φ, c)\n    X = promote_type(eltype(φ), typeof(c))\n    N = length(φ)\n    pc, qc = zeros(X, N), zeros(X, N)\n    @inbounds for n in 1:N-1\n        si, co = sincos(c*n)\n        pc[n+1] = pc[n] + φ[n]*co\n        qc[n+1] = qc[n] + φ[n]*si\n    end\n    return pc, qc\nend\n\n\"modified mean square displacement\"\nfunction mmsd(mf, pc::Vector{T}, qc, N0, c) where T\n    N, Dc = length(pc), zeros(T, N0)\n    f = mf^2/(1-cos(c)) # constant factor for Dc\n    for n in 1:N0\n        Mc = sum((pc[n+j] - pc[j])^2 + (qc[n+j] - qc[j])^2 for j in 1:N-n)/(N-n)\n        Dc[n] = Mc - f*(1 - cos(n*c))\n    end\n    return Dc\nend\n", "meta": {"hexsha": "64572066dde6d7af1aa556ecdbb8615d739f6482", "size": 2237, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chaosdetection/testchaos01.jl", "max_stars_repo_name": "yuxiliu1995/ChaosTools.jl", "max_stars_repo_head_hexsha": "219d5d19b2aba54348cfdd8133108ad3be7dde3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-06T13:06:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-06T13:06:05.000Z", "max_issues_repo_path": "src/chaosdetection/testchaos01.jl", "max_issues_repo_name": "yuxiliu1995/ChaosTools.jl", "max_issues_repo_head_hexsha": "219d5d19b2aba54348cfdd8133108ad3be7dde3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chaosdetection/testchaos01.jl", "max_forks_repo_name": "yuxiliu1995/ChaosTools.jl", "max_forks_repo_head_hexsha": "219d5d19b2aba54348cfdd8133108ad3be7dde3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4202898551, "max_line_length": 90, "alphanum_fraction": 0.6446133214, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7941341751612736}}
{"text": "# Implement code blocks 3.2 - 3.10 in McElreath's Statistical Rethinking, 2nd edition.\n\nusing Distributions\nusing Plots\nusing Statistics\nusing StatsBase\n\n\ngrid_size = 1000\nnum_samples = 1000\n\n\n## Code block 3.2\nparam_grid = range(0, 1, length=grid_size)  \nprior = ones((grid_size))\nlikelihood = [pdf(Binomial(9, p), 6) for p in param_grid]\nposterior = likelihood .* prior\nposterior = posterior / sum(posterior)\n\n@assert abs(sum(posterior) - 1) < 1e-4 \"Posterior does not sum to 1.\"\n@assert minimum(posterior) >= 0\n@assert maximum(posterior) <= 1\n\n\n## Code block 3.3\nsamples = sample(param_grid, Weights(posterior), num_samples; replace=true, ordered=false)\n\n\n## Code block 3.4\ndisplay(scatter(samples, xlabel=\"Sample number\", ylabel=\"Proportion water (p)\"))\n\n\n## Code block 3.5\n# use a histogram, because I don't yet know a comparable tool for density estimation in\n# Julia.\ndisplay(histogram(samples, bins=:40))\n\n\n## Code block 3.6\nsum(posterior[param_grid .< 0.5])\n\n\n## Code block 3.7\nsum(samples .< 0.5) / num_samples\n\n\n## Code block 3.8\nsum(0.5 .< samples .< 0.75) / num_samples\n\n\n## Code block 3.9\nquantile(samples, 0.8)\n\n\n## Code block 3.10\nquantile(samples, [0.1, 0.9])\n", "meta": {"hexsha": "898f2ff0164660bafdb3e5b0ca17b03ef9c5760c", "size": 1177, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3-2_grid_sampling.jl", "max_stars_repo_name": "CrosstabKite/stat_rethinking_julia", "max_stars_repo_head_hexsha": "5dd23fc7d2a438db59e4b45ae08d93503c1a4ef3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3-2_grid_sampling.jl", "max_issues_repo_name": "CrosstabKite/stat_rethinking_julia", "max_issues_repo_head_hexsha": "5dd23fc7d2a438db59e4b45ae08d93503c1a4ef3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3-2_grid_sampling.jl", "max_forks_repo_name": "CrosstabKite/stat_rethinking_julia", "max_forks_repo_head_hexsha": "5dd23fc7d2a438db59e4b45ae08d93503c1a4ef3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.649122807, "max_line_length": 90, "alphanum_fraction": 0.7094307562, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109784205502, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7940527317925676}}
{"text": "\"\"\"\n    fresnels(x)\n\nCompute the Fresnel S integral of type 0 (integral of `sin(πt²/2)`).\n\"\"\"\nfresnels(x) = (1 + im) / 4 * (erf((1 + im)√π / 2 * x) - im * erf((1 - im)√π / 2 * x))\n\n\"\"\"\n    fresnelc(x)\n\nCompute the Fresnel C integral of type 0 (integral of `cos(πt²/2)`).\n\"\"\"\nfresnelc(x) = (1 - im) / 4 * (erf((1 + im)√π / 2 * x) + im * erf((1 - im)√π / 2 * x))\n", "meta": {"hexsha": "166d1229fb0365085633a76bdad5888fb3c68976", "size": 361, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/fresnel.jl", "max_stars_repo_name": "fachra/SpinDoctor.jl", "max_stars_repo_head_hexsha": "25c633fb8020843728c1004c492a7c33b2fe2e4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2022-03-19T12:53:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:39:38.000Z", "max_issues_repo_path": "src/utils/fresnel.jl", "max_issues_repo_name": "fachra/SpinDoctor.jl", "max_issues_repo_head_hexsha": "25c633fb8020843728c1004c492a7c33b2fe2e4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2022-03-13T19:49:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T14:58:15.000Z", "max_forks_repo_path": "src/utils/fresnel.jl", "max_forks_repo_name": "fachra/SpinDoctor.jl", "max_forks_repo_head_hexsha": "25c633fb8020843728c1004c492a7c33b2fe2e4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-11T09:54:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T11:10:57.000Z", "avg_line_length": 25.7857142857, "max_line_length": 85, "alphanum_fraction": 0.5096952909, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159683, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7940527247792344}}
{"text": "using JuMP\nusing Cbc\n# cria o modelo para a otimização linear, utiliza o cbc como solver\nm = Model(with_optimizer(Cbc.Optimizer))\n\nset_time_limit_sec(m , 1)\n\nn = 6\n\n# define as variaveis binárias xij e o u como inteiro\n@variable(m , x[1:n , 1:n] , Bin)\n@variable(m , u[1:n] , integer=true)\n\nfix(u[1] , 0)\n\n# cria o grafo de pesos para fazer conexão\ny = zeros(Int64 , n , n)\n\n# dados do exemplo do slide da prof(trabalho -  material auxiliar)\n# é o exemplo das cidades que está logo depois do MTZ\ny = [ 0  186 105 208 177 94 ;\n     187 0 89.8 223 255 254 ;\n     99.9 89 0  203 204 172 ;\n     206 220 203 0 377 295 ; \n     168 251 201 376 0 156 ;\n     86.8 255 173  293 159  0]\n\n#for i in 1:5\n#    for j in 1:5\n#        y[i,j] = i+j\n#    end\n#end\n\n# função objetiva\n@objective(m , Min , sum(x.*y))\n\n\n# constraint de que a soma de uma linha vai ser 1\n@constraint(m , [i= 1:n] , sum(x[i,1:end .!=i]) == 1)\n# constraint de que a soma de uma coluna vai ser 1\n@constraint(m , [i= 1:n] , sum(x[1:end.!=i,i]) == 1)\n\n# constraint do u\n@constraint(m , [i = 1:n , j =2:n , i != j] , u[j] >= u[i] + x[i,j] - n *(1-x[i,j]))\n\n#printa os dados do modelo\nprintln(m)\n\n# resolve e printa os resultados\noptimize!(m)\n\nuAux = value.(u)\nxAux = value.(x)\n\nfor i in 1:n\n    println(\"u$(i) $(uAux[i])\")\nend\n\nprint(\"\\n\\n Xij:\\n\")\n\nfor i in 1:n\n    for j in 1:n\n        print(\"$(xAux[i,j]) \")\n    end\n    println()\nend\n\n", "meta": {"hexsha": "ca4f3f136dfb27880acb27ed44eac8a6c4c0a04c", "size": 1392, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "toybox/teste.jl", "max_stars_repo_name": "jvlsg/julia-tsp", "max_stars_repo_head_hexsha": "23062c381439bd6ccf12255d8f5827e32c46016d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "toybox/teste.jl", "max_issues_repo_name": "jvlsg/julia-tsp", "max_issues_repo_head_hexsha": "23062c381439bd6ccf12255d8f5827e32c46016d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toybox/teste.jl", "max_forks_repo_name": "jvlsg/julia-tsp", "max_forks_repo_head_hexsha": "23062c381439bd6ccf12255d8f5827e32c46016d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-28T10:45:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-28T10:45:05.000Z", "avg_line_length": 20.4705882353, "max_line_length": 84, "alphanum_fraction": 0.5984195402, "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813394, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7940506492339817}}
{"text": "### A Pluto.jl notebook ###\n# v0.9.11\n\nusing Markdown\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.peek, el) ? Base.peek(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 77489ff6-bd82-11ea-2d09-8737634cc579\nusing Random\n\n# ╔═╡ e9b93d52-bd82-11ea-15c9-699eeebaa243\nusing Plots\n\n# ╔═╡ 7eab739e-bdba-11ea-3ff3-fd88b08946d3\nusing LaTeXStrings\n\n# ╔═╡ 508fed7e-bdbe-11ea-1d75-8935a47d06d8\nusing Statistics\n\n# ╔═╡ fc08751c-bd79-11ea-072b-33a239fa0605\nmd\"# Stochastic Thinking\"\n\n# ╔═╡ f895f5da-bd7c-11ea-2250-efdcd9d49a38\nmd\"## Modelling the recovery process using probability\nRecall code: $I_{n+1} = (1 + c) I_n = \\lambda * I_n$\"\n\n# ╔═╡ 65f53264-bd7d-11ea-03cc-9513654c222c\nfunction run_infection(I₀, λ, T=20)\n\tI = zeros(T)\n\tI[1] = I₀\n\t\n\tfor n ∈ 1:T-1\n\t\tI[n+1] = λ * I[n]\n\tend\n\t\n\treturn I\nend\n\n# ╔═╡ 2dce78b0-bd7e-11ea-0381-d16883397ebd\nrun_infection(1.0, 0.1)\n\n# ╔═╡ 38ad903e-bd7e-11ea-08b6-f9a9a086260f\nmd\"## Adding new data to extend a vector\"\n\n# ╔═╡ c7c0a170-bd7f-11ea-3b68-a9ae0c8ccfde\nv = [1.0]\n\n# ╔═╡ e40b10e0-bd7f-11ea-2883-bf485b88d6ad\npush!(v, 7.0) # ! means the function modifies its first argument\n\n# ╔═╡ b9db886e-bd80-11ea-1347-5d5415a22dd5\nv\n\n# ╔═╡ c427a4fc-bd80-11ea-365a-59fd43802b47\n[v; 10]\n\n# ╔═╡ 92666d14-bd81-11ea-2ba7-e181ffa9f476\npushfirst!(v, 8) # deque - double endedn queue\n\n# ╔═╡ 0f3c4b1c-bd80-11ea-0fd0-df1c82c3ed1c\nfunction run_infection_vectorized(I₀, λ, T=20)\n\tIs = [I₀]\n\tI = I₀\n\t\n\tfor n ∈ 1:T-1\n\t\tI_next = λ * I\n\t\t\n\t\tpush!(Is, I_next)\n\t\t\n\t\tI = I_next\n\tend\n\t\n\treturn Is\nend\n\n# ╔═╡ 71759792-bd81-11ea-1cbe-35ca8456b6a1\nrun_infection_vectorized(1.0, 1.1)\n\n# ╔═╡ 7a610d46-bd81-11ea-0ff9-5b97563bce1e\nmd\"## Randomness\"\n\n# ╔═╡ 29e900e6-bd82-11ea-0344-2b2276b99422\nrand()\n\n# ╔═╡ 8cec500a-bd82-11ea-2fbb-03dec9457d7e\nRandom.seed!(3);\n\n# ╔═╡ a1c76a96-bd82-11ea-22a0-d9110840ecf3\nrand()\n\n# ╔═╡ d39e0c64-bd82-11ea-188d-6f762d4dd688\nrand(10)\n\n# ╔═╡ ed82a2b8-bd82-11ea-1d5c-8759b29ce1cc\nscatter(rand(50))\n\n# ╔═╡ 0682ca0c-bd83-11ea-0afa-8794eb7bd9b8\nbegin\n\tlocal r = rand(50)\n\t\n\tscatter(r, 0.5 * one.(r), ylim=(0, 1))\nend\n\n# ╔═╡ be2d6b30-bd83-11ea-2683-49e64cbccb3c\n@bind num_points html\"<input type='range' min=1 max=100>\"\n\n# ╔═╡ 811488a0-bdab-11ea-0f9d-b1bc9f854e07\n#TODO coloring exercise\nbegin\n\tlocal r = rand(num_points)\n\t\n\tscatter(r[1:num_points],0.5 .* one.(r[1:num_points]),ylim=(0, 1),xlim=(0, 1))\nend\n\n# ╔═╡ 89984d06-bdab-11ea-3ff4-55786243da18\nmd\"## Event with probability $p$\"\n\n# ╔═╡ a8196c14-bdac-11ea-3b3d-f744310c289d\nbegin\n\tlocal p = 0.25\n\tlocal r = rand()\n\t\n\tif r < p\n\t\ttrue\n\telse\n\t\tfalse\n\tend\nend\n\n# ╔═╡ cfac1f86-bdac-11ea-316c-a9abea7ed509\nmd\"Bernoulli Trial\"\n\n# ╔═╡ 46de61a4-bdad-11ea-3aaf-a5f9b96e533f\nfunction bernoulli(p)\n\tr = rand()\n\t\n\treturn r < p\nend\n\n# ╔═╡ 8a20f6b6-bdad-11ea-0ef5-af788315bd82\n2 < 3 ? true : false # ternary operator\n\n# ╔═╡ bc82b248-bdad-11ea-3ad5-019463cf2ef1\n2 < 3\n\n# ╔═╡ c7552f0e-bdad-11ea-3fe8-fd3cf143ff30\nbegin\n\tlocal p = 0.25\n\t\n\ttrials = [bernoulli(p) for i ∈ 1:100]\nend\n\n# ╔═╡ fe9569d2-bdad-11ea-0f72-09084f78f692\nscatter(trials)\n\n# ╔═╡ 38c6f580-bdae-11ea-2cbe-935e598ee04c\ntrials\n\n# ╔═╡ 3a406aea-bdae-11ea-0c69-b13a4340a01a\ncount(trials)\n\n# ╔═╡ 1b778d18-bdaf-11ea-3ee4-0f3a16536b9f\nfunction bernoulli_experiment(p, N=100)\n\ttrials = [bernoulli(p) for i ∈ 1:N]\n\treturn count(trials)\nend\n\n# ╔═╡ 45a5c6a4-bdaf-11ea-1812-359502135397\ncount(trials .== false) + count(trials)\n\n# ╔═╡ 65bf3b8a-bdaf-11ea-1878-bb69724e1a7b\ncount(.!(trials)) # ! is \"not\" in Julia\n\n# ╔═╡ 84062240-bdaf-11ea-3494-8d49391f642a\nbernoulli_experiment(0.25)\n\n# ╔═╡ a9b7c836-bdaf-11ea-1691-9d38af43f16a\nbernoulli_experiment(0.25)\n\n# ╔═╡ be407118-bdaf-11ea-2973-853fc1a266e1\nmd\"A quantity that has different **outcomes** in different runs is called a **random variable**\"\n\n# ╔═╡ de5398ea-bdaf-11ea-1d81-5df4eb22e68b\nmd\"## Monte Carlo simulation\"\n\n# ╔═╡ 73e79708-bdb0-11ea-123f-9fbb2c18dc12\nmd\"Run the same random process a lot of times and look at the results\"\n\n# ╔═╡ 85f366ac-bdb0-11ea-16b7-2bec6b2f5356\nbegin\n\tlocal p = 0.25\n\tlocal N = 20 # number of trials\n\tlocal num_expts = 1000\n\t\n\tresults = [bernoulli_experiment(p, N) for i in 1:num_expts]\nend\n\n# ╔═╡ af9e25e6-bdb0-11ea-23aa-7db6e35a4447\nscatter(results, zcolor=results)\n\n# ╔═╡ 87eaac94-bdb1-11ea-117a-ffa693e0b098\nmd\" $X$ = number of heads\n\n**Probability distribution** of a random variable $X$\n\n$\\text{Prob}(X = x)$\n\"\n\n# ╔═╡ 976c1838-bdb1-11ea-30b1-f5c5eb8e2360\nmd\"Probability that $X = x$ = proportion of time that the result was $x$\"\n\n# ╔═╡ f411c49a-bdb2-11ea-00b9-dfcc68181d37\nmd\"## Counting\"\n\n# ╔═╡ 0922211a-bdb3-11ea-1e49-3518de406ace\nmd\"Need to count how many of the trials come out as 5\"\n\n# ╔═╡ 286acb30-bdb3-11ea-1be2-c51955c53ab8\nmd\"Need data structure where we store the counts:\n\n- `Dict` (dictionary)\n- `Vector`\"\n\n# ╔═╡ 50d0c656-bdb3-11ea-0a32-f7d63d08f64a\nresults\n\n# ╔═╡ 99aab29c-bdb3-11ea-3dd0-57d1e619f762\nmaximum(results) #not 'max': max(1, 2, 3)\n\n# ╔═╡ 2beb3cb0-bdb6-11ea-1451-05c1e3087165\nminimum(results)\n\n# ╔═╡ 6e8a4d8a-bdb7-11ea-0fd5-6d942ceb5283\nl = maximum(results) + 1\n\n# ╔═╡ 8e80e7fc-bdb7-11ea-1967-bbff2030d913\ncounts = zeros(Int, l)\n\n# ╔═╡ 9b648744-bdb7-11ea-3e0e-7307a4084f9a\nfor score ∈ results\n\tcounts[score + 1] += 1\nend\n\n# ╔═╡ e2635850-bdb7-11ea-21bc-5beadadfa675\ncounts\n\n# ╔═╡ 7aecb5b0-bdba-11ea-026f-09ebc21a36a6\nimport Pkg; Pkg.add(\"LaTeXStrings\")\n\n# ╔═╡ 96b1bbb2-bdb8-11ea-3e81-1bca33878a99\nbegin\n\tplot(0:maximum(results), counts, m=:o)\n\tylabel!(\"frequency of having n heads\")\n\txlabel!(\"n\")\n\t#xlabel!(\"n\")\nend\n\n# ╔═╡ 7090316e-bdba-11ea-27a6-dbc5ec194d02\nfunction count_them(results)\n\tcounts = zeros(Int, maximum(results) + 1)\n\t\n\tfor score ∈ results\n\t\tcounts[score + 1] += 1\n\tend\n\t\n\treturn counts\nend\n\n# ╔═╡ c56f3320-bdbb-11ea-2904-6197a97efbbf\nfunction run_experiments(p, N, num_expts=1000)\n\tresults = [bernoulli_experiment(p, N) for i ∈ 1:num_expts]\n\t\n\treturn results\nend\n\n# ╔═╡ 4c85f43c-bdbc-11ea-1ba1-810cadb75f6e\nbegin\n\tlocal data = count_them(run_experiments(0.25, 20, 10000))\n\tplot(0:length(data)-1, data, m=:o)\nend\n\n# ╔═╡ 8c2374a2-bdbc-11ea-12a9-eda80a7e4e21\nmd\"## Probability distribution\"\n\n# ╔═╡ a00fa58a-bdbc-11ea-14a2-fd43cfedf7bb\nmd\"Probability = relative frequency\n\nDivide by the number of experiments\"\n\n# ╔═╡ bc8cf4ec-bdbc-11ea-33f3-d9aa8f26cd60\nbegin\n\tlocal data = run_experiments(0.25, 20, 10^5) |> count_them\n\tplot(0:length(data)-1, data ./ sum(data), m=:o)\nend\n\n# ╔═╡ 0839ca58-bdbd-11ea-2a3e-c99ad45c7121\nbegin\n\tnum_expts = 10^5\n\tdata = run_experiments(0.25, 20, num_expts) |> count_them\n\tprobs = data .// num_expts\nend\n\n# ╔═╡ cb4d967a-bdbd-11ea-35c8-ad831d395195\nsum(probs)\n\n# ╔═╡ cf802b2c-bdbd-11ea-0d10-390f5ea9fe19\nx = 3 // 4\n\n# ╔═╡ fb862028-bdbd-11ea-3c26-e5e8ebd9630d\ntypeof(x)\n\n# ╔═╡ 04180cb0-bdbe-11ea-2a64-a33a4f778d68\nx + x\n\n# ╔═╡ 08a5bf84-bdbe-11ea-18d4-dd7255a35b56\ndata\n\n# ╔═╡ 741484a8-bdbe-11ea-3fd8-e55fe46723f8\nbegin\n\tlocal results = run_experiments(0.25, 20, 10^5)\n\tmean(results)\nend\n\n# ╔═╡ 5d7c00b8-bdbe-11ea-2b46-6d1117a42368\nmd\"Expected mean value = N * p\"\n\n# ╔═╡ Cell order:\n# ╟─fc08751c-bd79-11ea-072b-33a239fa0605\n# ╟─f895f5da-bd7c-11ea-2250-efdcd9d49a38\n# ╠═65f53264-bd7d-11ea-03cc-9513654c222c\n# ╠═2dce78b0-bd7e-11ea-0381-d16883397ebd\n# ╟─38ad903e-bd7e-11ea-08b6-f9a9a086260f\n# ╠═c7c0a170-bd7f-11ea-3b68-a9ae0c8ccfde\n# ╠═e40b10e0-bd7f-11ea-2883-bf485b88d6ad\n# ╠═b9db886e-bd80-11ea-1347-5d5415a22dd5\n# ╠═c427a4fc-bd80-11ea-365a-59fd43802b47\n# ╠═92666d14-bd81-11ea-2ba7-e181ffa9f476\n# ╠═0f3c4b1c-bd80-11ea-0fd0-df1c82c3ed1c\n# ╠═71759792-bd81-11ea-1cbe-35ca8456b6a1\n# ╟─7a610d46-bd81-11ea-0ff9-5b97563bce1e\n# ╠═29e900e6-bd82-11ea-0344-2b2276b99422\n# ╠═77489ff6-bd82-11ea-2d09-8737634cc579\n# ╠═8cec500a-bd82-11ea-2fbb-03dec9457d7e\n# ╠═a1c76a96-bd82-11ea-22a0-d9110840ecf3\n# ╠═d39e0c64-bd82-11ea-188d-6f762d4dd688\n# ╠═e9b93d52-bd82-11ea-15c9-699eeebaa243\n# ╠═ed82a2b8-bd82-11ea-1d5c-8759b29ce1cc\n# ╠═0682ca0c-bd83-11ea-0afa-8794eb7bd9b8\n# ╟─be2d6b30-bd83-11ea-2683-49e64cbccb3c\n# ╠═811488a0-bdab-11ea-0f9d-b1bc9f854e07\n# ╟─89984d06-bdab-11ea-3ff4-55786243da18\n# ╠═a8196c14-bdac-11ea-3b3d-f744310c289d\n# ╟─cfac1f86-bdac-11ea-316c-a9abea7ed509\n# ╠═46de61a4-bdad-11ea-3aaf-a5f9b96e533f\n# ╠═8a20f6b6-bdad-11ea-0ef5-af788315bd82\n# ╠═bc82b248-bdad-11ea-3ad5-019463cf2ef1\n# ╠═c7552f0e-bdad-11ea-3fe8-fd3cf143ff30\n# ╠═fe9569d2-bdad-11ea-0f72-09084f78f692\n# ╠═38c6f580-bdae-11ea-2cbe-935e598ee04c\n# ╠═3a406aea-bdae-11ea-0c69-b13a4340a01a\n# ╠═1b778d18-bdaf-11ea-3ee4-0f3a16536b9f\n# ╠═45a5c6a4-bdaf-11ea-1812-359502135397\n# ╠═65bf3b8a-bdaf-11ea-1878-bb69724e1a7b\n# ╠═84062240-bdaf-11ea-3494-8d49391f642a\n# ╠═a9b7c836-bdaf-11ea-1691-9d38af43f16a\n# ╟─be407118-bdaf-11ea-2973-853fc1a266e1\n# ╟─de5398ea-bdaf-11ea-1d81-5df4eb22e68b\n# ╟─73e79708-bdb0-11ea-123f-9fbb2c18dc12\n# ╠═85f366ac-bdb0-11ea-16b7-2bec6b2f5356\n# ╠═af9e25e6-bdb0-11ea-23aa-7db6e35a4447\n# ╟─87eaac94-bdb1-11ea-117a-ffa693e0b098\n# ╟─976c1838-bdb1-11ea-30b1-f5c5eb8e2360\n# ╟─f411c49a-bdb2-11ea-00b9-dfcc68181d37\n# ╟─0922211a-bdb3-11ea-1e49-3518de406ace\n# ╟─286acb30-bdb3-11ea-1be2-c51955c53ab8\n# ╠═50d0c656-bdb3-11ea-0a32-f7d63d08f64a\n# ╠═99aab29c-bdb3-11ea-3dd0-57d1e619f762\n# ╠═2beb3cb0-bdb6-11ea-1451-05c1e3087165\n# ╠═6e8a4d8a-bdb7-11ea-0fd5-6d942ceb5283\n# ╠═8e80e7fc-bdb7-11ea-1967-bbff2030d913\n# ╠═9b648744-bdb7-11ea-3e0e-7307a4084f9a\n# ╠═e2635850-bdb7-11ea-21bc-5beadadfa675\n# ╠═7aecb5b0-bdba-11ea-026f-09ebc21a36a6\n# ╠═7eab739e-bdba-11ea-3ff3-fd88b08946d3\n# ╠═96b1bbb2-bdb8-11ea-3e81-1bca33878a99\n# ╠═7090316e-bdba-11ea-27a6-dbc5ec194d02\n# ╠═c56f3320-bdbb-11ea-2904-6197a97efbbf\n# ╠═4c85f43c-bdbc-11ea-1ba1-810cadb75f6e\n# ╟─8c2374a2-bdbc-11ea-12a9-eda80a7e4e21\n# ╟─a00fa58a-bdbc-11ea-14a2-fd43cfedf7bb\n# ╠═bc8cf4ec-bdbc-11ea-33f3-d9aa8f26cd60\n# ╠═0839ca58-bdbd-11ea-2a3e-c99ad45c7121\n# ╠═cb4d967a-bdbd-11ea-35c8-ad831d395195\n# ╠═cf802b2c-bdbd-11ea-0d10-390f5ea9fe19\n# ╠═fb862028-bdbd-11ea-3c26-e5e8ebd9630d\n# ╠═04180cb0-bdbe-11ea-2a64-a33a4f778d68\n# ╠═08a5bf84-bdbe-11ea-18d4-dd7255a35b56\n# ╠═508fed7e-bdbe-11ea-1d75-8935a47d06d8\n# ╠═741484a8-bdbe-11ea-3fd8-e55fe46723f8\n# ╟─5d7c00b8-bdbe-11ea-2b46-6d1117a42368\n", "meta": {"hexsha": "d4b65b9655b79ddabf32b86f3108bd81de019a82", "size": 9998, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Stochastic_Thinking.jl", "max_stars_repo_name": "elihugarret/my-notebooks", "max_stars_repo_head_hexsha": "b90b275fbc2a7b406daccd954b78f71d64e65f9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-10T19:16:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T20:34:25.000Z", "max_issues_repo_path": "Stochastic_Thinking.jl", "max_issues_repo_name": "elihugarret/Computational-Modeling-in-Julia-with-Applications-to-the-COVID-19-Pandemic", "max_issues_repo_head_hexsha": "b90b275fbc2a7b406daccd954b78f71d64e65f9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Stochastic_Thinking.jl", "max_forks_repo_name": "elihugarret/Computational-Modeling-in-Julia-with-Applications-to-the-COVID-19-Pandemic", "max_forks_repo_head_hexsha": "b90b275fbc2a7b406daccd954b78f71d64e65f9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6256157635, "max_line_length": 96, "alphanum_fraction": 0.724544909, "num_tokens": 5424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.7940116466398234}}
{"text": "import StatsBase: sample\n\n# Model selection\n\n# Taken from https://royalsocietypublishing.org/doi/pdf/10.1098/rspa.2017.0009\nfunction AIC(k::Int64, X::AbstractArray, Y::AbstractArray; likelyhood = (X,Y) -> sum(abs2, X-Y))\n    @assert size(X) == size(Y) \"Dimensions of trajectories should be equal !\"\n    return 2*k - 2*log(likelyhood(X, Y))\nend\n# Taken from https://royalsocietypublishing.org/doi/pdf/10.1098/rspa.2017.0009\nfunction AICC(k::Int64, X::AbstractArray, Y::AbstractArray; likelyhood = (X,Y) -> sum(abs2, X-Y))\n    @assert size(X) == size(Y) \"Dimensions of trajectories should be equal !\"\n    return AIC(k, X, Y, likelyhood = likelyhood)+ 2*(k+1)*(k+2)/(size(X)[2]-k-2)\nend\n\n# Double check on that\n# Taken from https://www.immagic.com/eLibrary/ARCHIVES/GENERAL/WIKIPEDI/W120607B.pdf\nfunction BIC(k::Int64, X::AbstractArray, Y::AbstractArray; likelyhood = (X,Y) -> sum(abs2, X-Y))\n    @assert size(X) == size(Y) \"Dimensions of trajectories should be equal !\"\n    return - 2*log(likelyhood(X, Y)) + k*log(size(X)[2])\nend\n\n\n# Optimal Shrinkage for data in presence of white noise\n# See D. L. Donoho and M. Gavish, \"The Optimal Hard Threshold for Singular\n# Values is 4/sqrt(3)\", http://arxiv.org/abs/1305.5870\n# Code taken from https://github.com/erichson/optht\n\nfunction optimal_svht(m::Int64, n::Int64; known_noise::Bool = false)\n    @assert m/n > 0\n    @assert m/n <= 1\n\n    β = m/n\n    ω = (8*β) / (β+1+sqrt(β^2+14β+1))\n    c = sqrt(2*(β+1)+ω)\n\n    if known_noise\n        return c\n    else\n        median = median_marcenko_pastur(β)\n        return c / sqrt(median)\n    end\nend\n\nfunction marcenko_pastur_density(t, lower, upper, beta)\n    sqrt((upper-t).*(t-lower))./(2π*beta*t)\nend\n\nfunction incremental_marcenko_pastur(x, beta, gamma)\n    @assert beta <= 1\n    upper = (1+sqrt(beta))^2\n    lower = (1-sqrt(beta))^2\n\n    @inline marcenko_pastur(x) = begin\n        if (upper-x)*(x-lower) > 0\n            return marcenko_pastur_density(x, lower, upper, beta)\n        else\n            return zero(eltype(x))\n        end\n    end\n\n    if gamma ≈ zero(eltype(gamma))\n        i, ϵ = quadgk(x->(x^gamma)*marcenko_pastur(x), x, upper)\n        return i\n    else\n        i, ϵ = quadgk(x->marcenko_pastur(x), x, upper)\n        return i\n    end\nend\n\nfunction median_marcenko_pastur(beta)\n    @assert 0 < beta <= 1\n    upper = (1+sqrt(beta))^2\n    lower = (1-sqrt(beta))^2\n    change = true\n    x = ones(eltype(upper), 5)\n    y = similar(x)\n    while change && (upper - lower > 1e-5)\n        x = range(lower, upper, length = 5)\n        for (i,xi) in enumerate(x)\n            y[i] = one(eltype(x)) - incremental_marcenko_pastur(xi, beta, 0)\n        end\n        any(y .< 0.5) ? lower = maximum(x[y .< 0.5]) : change = false\n        any(y .> 0.5) ? upper = minimum(x[y .> 0.5]) : change = false\n    end\n    return (lower+upper)/2\nend\n\nfunction optimal_shrinkage(X::AbstractArray{T, 2}) where T <: Number\n    m,n = minimum(size(X)), maximum(size(X))\n    U, S, V = svd(X)\n    τ = optimal_svht(m,n)\n    inds = S .>= τ*median(S)\n    return U[:, inds]*Diagonal(S[inds])*V[:, inds]'\nend\n\nfunction optimal_shrinkage!(X::AbstractArray{T, 2}) where T <: Number\n    m,n = minimum(size(X)), maximum(size(X))\n    U, S, V = svd(X)\n    τ = optimal_svht(m,n)\n    inds = S .>= τ*median(S)\n    X .= U[:, inds]*Diagonal(S[inds])*V[:, inds]'\n    return\nend\n\nfunction savitzky_golay(x::AbstractVector{T}, windowSize::Integer, polyOrder::Integer; deriv::Integer=0, dt::Real=1.0, crop::Bool = true) where T <: Number\n\t# Polynomial smoothing with the Savitzky Golay filters\n\t# Adapted from: https://github.com/BBN-Q/Qlab.jl/blob/master/src/SavitskyGolay.jl\n\t# More information: https://pdfs.semanticscholar.org/066b/7534921b308925f6616480b4d2d2557943d1.pdf\n\t# Requires LinearAlgebra and DSP modules loaded.\n\n\t# Some error checking\n\t@assert isodd(windowSize) \"Window size must be an odd integer.\"\n\t@assert polyOrder < windowSize \"Polynomial order must be less than window size.\"\n\n\t# Calculate filter coefficients\n\tfilterCoeffs = calculate_filterCoeffs(windowSize, polyOrder, deriv, dt)\n\n\t# Pad the signal with the endpoints and convolve with filter\n\thalfWindow = Int(ceil((windowSize - 1)/2))\n\tpaddedX = [x[1]*ones(halfWindow); x; x[end]*ones(halfWindow)]\n\ty = conv(filterCoeffs[end:-1:1], paddedX)\n\n\tif !crop\n\t\t# Return the valid midsection\n\t\treturn y[2*halfWindow+1:end-2*halfWindow]\n\telse\n\t\t# Return cropped data. Excluding borders, where the estimation is less accurate\n\t\treturn x[halfWindow+2:end-halfWindow-1], y[3*halfWindow+2:end-3*halfWindow-1]\n\tend\nend\n\nfunction savitzky_golay(x::AbstractMatrix{T}, windowSize::Integer, polyOrder::Integer; deriv::Integer=0, dt::Real=1.0, crop::Bool = true) where T <: Number\n\t# Polynomial smoothing with the Savitzky Golay filters\n\t# Adapted from: https://github.com/BBN-Q/Qlab.jl/blob/master/src/SavitskyGolay.jl\n\t# More information: https://pdfs.semanticscholar.org/066b/7534921b308925f6616480b4d2d2557943d1.pdf\n\t# Requires LinearAlgebra and DSP modules loaded.\n\n\t# Some error checking\n\t@assert isodd(windowSize) \"Window size must be an odd integer.\"\n\t@assert polyOrder < windowSize \"Polynomial order must be less than window size.\"\n\n\t# Calculate filter coefficients\n\tfilterCoeffs = calculate_filterCoeffs(windowSize, polyOrder, deriv, dt)\n\n\t# Apply filter to each component\n\thalfWindow = Int(ceil((windowSize - 1)/2))\n\n\tif !crop\n\t\ty = similar(x)\n\t\tfor (i, xi) in enumerate(eachrow(x))\n\t\t\tpaddedX = [xi[1]*ones(halfWindow); xi; xi[end]*ones(halfWindow)]\n\t\t\ty₀ = conv(filterCoeffs[end:-1:1], paddedX)\n\t\t\ty[i,:] = y₀[2*halfWindow+1:end-2*halfWindow]\n\t\tend\n\t\treturn y\n\telse\n\t\tcropped_x = x[:,halfWindow+2:end-halfWindow-1]\n\t\ty = similar(cropped_x)\n\t\tfor (i, xi) in enumerate(eachrow(x))\n\t\t\tpaddedX = [xi[1]*ones(halfWindow); xi; xi[end]*ones(halfWindow)]\n\t\t\ty₀ = conv(filterCoeffs[end:-1:1], paddedX)\n\t\t\ty[i,:] = y₀[3*halfWindow+2:end-3*halfWindow-1]\n\t\tend\n\t\treturn cropped_x, y\n\tend\nend\n\nfunction calculate_filterCoeffs(windowSize::Integer, polyOrder::Integer, deriv::Integer, dt::Real)\n\t# Some error checking\n\t@assert isodd(windowSize) \"Window size must be an odd integer.\"\n\t@assert polyOrder < windowSize \"Polynomial order must be less than window size.\"\n\n\t# Form the design matrix A\n\thalfWindow = Int(ceil((windowSize - 1)/2))\n\tA = zeros(windowSize, polyOrder+1)\n\tfor order = 0:polyOrder\n\t\tA[:, order+1] = (-halfWindow:halfWindow).^(order)\n\tend\n\n\t# Compute the required column of the inverse of A'*A\n\t# and calculate filter coefficients\n\tei = zeros(polyOrder+1)\n\tei[deriv+1] = 1.0\n\tinv_col = (A'*A) \\ ei\n\treturn A*inv_col * factorial(deriv) ./(dt^deriv)\nend\n\n@inline function burst_sampling(x::AbstractArray, samplesize::Int64, bursts::Int64)\n    @assert size(x)[end] >= samplesize*bursts \"Length of data array too small for subsampling of size $size!\"\n    inds = sample(1:size(x)[end]-samplesize, bursts, replace = false)\n    inds = sort(unique(vcat([collect(i:i+samplesize) for i in inds]...)))\n    return resample(x, inds)\nend\n\n\n@inline function burst_sampling(x::AbstractArray, y::AbstractArray, samplesize::Int64, bursts::Int64)\n    @assert size(x)[end] >= samplesize*bursts \"Length of data array too small for subsampling of size $size!\"\n    @assert size(x)[end] == size(y)[end]\n    inds = sample(1:size(x)[end]-samplesize, bursts, replace = false)\n    inds = sort(unique(vcat([collect(i:i+samplesize) for i in inds]...)))\n    return resample(x, inds), resample(y, inds)\nend\n\n\n@inline function burst_sampling(x::AbstractArray, t::AbstractVector, period::T, bursts::Int64) where T <: AbstractFloat\n    @assert period > zero(typeof(period)) \"Sampling period has to be positive.\"\n    @assert size(x)[end] == size(t)[end] \"Provide consistent data.\"\n    @assert bursts >= 1 \"Number of bursts has to be positive.\"\n    @assert t[end]-t[1]>= period*bursts \"Bursting impossible. Please provide more data or reduce bursts.\"\n    t_ids = zero(eltype(t)) .<= t .- period  .<= t[end] .- 2*period\n    samplesize = Int64(floor(period/(t[end]-t[1])*length(t)))\n    inds = sample(collect(1:length(t))[t_ids], bursts, replace = false)\n    inds = sort(unique(vcat([collect(i:i+samplesize) for i in inds]...)))\n    return resample(x, inds), resample(t, inds)\nend\n\n\n@inline function subsample(x::AbstractVector, frequency::Int64)\n    @assert frequency > 1\n    return x[1:frequency:end]\nend\n\n\n@inline function subsample(x::AbstractArray, frequency::Int64)\n    @assert frequency > 1\n    return x[:, 1:frequency:end]\nend\n\n@inline function subsample(x::AbstractArray, t::AbstractVector, period::T) where T <: AbstractFloat\n    @assert period > zero(typeof(period)) \"Sampling period has to be positive.\"\n    @assert size(x)[end] == size(t)[end] \"Provide consistent data.\"\n    @assert t[end]-t[1]>= period \"Subsampling impossible. Sampling period exceeds time window.\"\n    idx = Int64[1]\n    t_now = t[1]\n    @inbounds for (i, t_current) in enumerate(t)\n        if t_current - t_now >= period\n            push!(idx, i)\n            t_now = t_current\n        end\n    end\n    return resample(x, idx), resample(t, idx)\nend\n\n@inline function resample(x::AbstractArray{T,1}, indx::AbstractArray{Int64}) where T <: Number\n    @assert maximum(indx) <= length(x)\n    @assert minimum(indx) >= 1\n    return x[indx]\nend\n\n@inline function resample(x::AbstractArray{T,2}, indx::AbstractArray{Int64}) where T <: Number\n    @assert maximum(indx) <= size(x, 2)\n    @assert minimum(indx) >= 1\n    return x[:, indx]\nend\n", "meta": {"hexsha": "18db3ccad69c0f2fcf3f12a59445b4c3dd7d0a54", "size": 9397, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "DanielParraUnam/DataDrivenDiffEq.jl", "max_stars_repo_head_hexsha": "8e81616be8463983fb0be9cf14f273b49c2a81ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "DanielParraUnam/DataDrivenDiffEq.jl", "max_issues_repo_head_hexsha": "8e81616be8463983fb0be9cf14f273b49c2a81ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "DanielParraUnam/DataDrivenDiffEq.jl", "max_forks_repo_head_hexsha": "8e81616be8463983fb0be9cf14f273b49c2a81ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.70703125, "max_line_length": 155, "alphanum_fraction": 0.6760668298, "num_tokens": 2913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.863391599428538, "lm_q1q2_score": 0.794011637797634}}
{"text": "\nusing DifferentialEquations\nusing SimpleDiffEq\nusing DataFrames\nusing StatsPlots\nusing BenchmarkTools\n\n\n@inline function rate_to_proportion(r::Float64,t::Float64)\n    1-exp(-r*t)\nend;\n\n\nfunction sir_map!(du,u,p,t)\n    (S,I,R) = u\n    (β,c,γ,δt) = p\n    N = S+I+R\n    infection = rate_to_proportion(β*c*I/N,δt)*S\n    recovery = rate_to_proportion(γ,δt)*I\n    @inbounds begin\n        du[1] = S-infection\n        du[2] = I+infection-recovery\n        du[3] = R+recovery\n    end\n    nothing\nend;\n\n\nδt = 0.1\nnsteps = 400\ntmax = nsteps*δt\ntspan = (0.0,nsteps)\nt = 0.0:δt:tmax;\n\n\nu0 = [990.0,10.0,0.0];\n\n\np = [0.05,10.0,0.25,δt]; # β,c,γ,δt\n\n\nprob_map = DiscreteProblem(sir_map!,u0,tspan,p);\n\n\nsol_map = solve(prob_map,solver=FunctionMap);\n\n\ndf_map = DataFrame(sol_map')\ndf_map[!,:t] = t;\n\n\n@df df_map plot(:t,\n    [:x1 :x2 :x3],\n    label=[\"S\" \"I\" \"R\"],\n    xlabel=\"Time\",\n    ylabel=\"Number\")\n\n\n@benchmark solve(prob_map,solver=FunctionMap)\n\n", "meta": {"hexsha": "b2db508d0bc97fc8b88589326b9d107746bf25c4", "size": 937, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/function_map/function_map.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 126, "max_stars_repo_stars_event_min_datetime": "2020-04-29T08:41:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:42:53.000Z", "max_issues_repo_path": "script/function_map/function_map.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2020-04-29T11:44:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:45:15.000Z", "max_forks_repo_path": "script/function_map/function_map.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2020-04-29T08:01:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T16:55:08.000Z", "avg_line_length": 15.3606557377, "max_line_length": 58, "alphanum_fraction": 0.6264674493, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715435, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7940068612670891}}
{"text": "struct GeneralizedPoisson <: Distributions.DiscreteUnivariateDistribution\n    θ::Float64\n    λ::Float64\nend\n\nfunction Distributions.pdf(G::GeneralizedPoisson, x::Int64)\n    G.θ*(G.θ+G.λ*x)^(x-1)*exp(-G.θ - G.λ*x)/factorial(x)\nend\n\nfunction Distributions.logpdf(G::GeneralizedPoisson, x::Int64)\n    a = log(G.θ)\n    a += (x-1)*log(G.θ+G.λ*x)\n    a -= G.θ\n    a -= G.λ*x\n    a -= lgamma(x+1)\n    a\nend\n\nDistributions.mean(G::GeneralizedPoisson) = G.θ/(1-G.λ)\nDistributions.var(G::GeneralizedPoisson) = G.θ/(1-G.λ)^3\n", "meta": {"hexsha": "7037fc260e275056a5f0c2aaca320f1e8a0675ea", "size": 514, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/generalized_poisson.jl", "max_stars_repo_name": "grero/StatUtils.jl", "max_stars_repo_head_hexsha": "200994b3143b692499f11028ea4e5c4c749463b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-13T21:25:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-13T21:25:00.000Z", "max_issues_repo_path": "src/generalized_poisson.jl", "max_issues_repo_name": "grero/StatUtils.jl", "max_issues_repo_head_hexsha": "200994b3143b692499f11028ea4e5c4c749463b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/generalized_poisson.jl", "max_forks_repo_name": "grero/StatUtils.jl", "max_forks_repo_head_hexsha": "200994b3143b692499f11028ea4e5c4c749463b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4761904762, "max_line_length": 73, "alphanum_fraction": 0.6536964981, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191259110588, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7940068459913566}}
{"text": "using Pkg\nPkg.activate(pwd())\n\n# # Arrays\n# ## Vectors\n\nv = [1, 2, 3, 4, 5, 6, 7, 8] # or equivalently v = [1; 2; 3; 4; ...]\n\n#+\n\ntypeof(v)\nndims(v)\neltype(v)\nsize(v)\nlength(v)\n\n#+\n\nv[3]\nv[begin] # the first element\nv[end] # the last element\nv[[2, 3]]\n\n#+\n\nrange(1; stop = 10, step = 2) # or equivalently range(1, 10; step = 2)\n1:2:10\n\n#+\n\nv[1:3] # the first three elements\nv[1:2:end] # select all elements with odd index\nv[:] # all elements\n\n#+\n\nv = [1,2,3]\n\nappend!(v, 4)\nappend!(v, [5,6])\nappend!(v, 7:8)\nappend!(v, 3.0)\nappend!(v, 3.1415)\n\n#+\n\nisinteger(3.0)\n\n#+\n\nv = Float64[1, 2, 3]\nappend!(v, 3.1415)\n\n#+\n\nv = [1, 2, 3, 4]\nv[2] = 4\nv\n\n#+\n\nv[3:4] .= 11\nv\n\n# ### Exercise:\n# Create a vector of positive integers that contains all odd numbers smaller than `10`.\n# Then change the first element to `4` and the last two elements to `1`.\n# \n# ---\n# ### Solution:\n\nv = [1,3,5,7,9]\n\ncollect(1:2:9)\nVector(1:2:9)\n\nv[1] = 4\nv[end-1:end] .= 1\nv\n\n# ---\n# \n# ## Matrices\n\nm = [1  2  3  4; 5  6  7  8]\n\ntypeof(m)\neltype(m)\nndims(m)\nsize(m)\nlength(m)\n\n#+\n\nm[1] # the first element, equivalent to m[begin]\nm[2] # the second element\nm[end-1] # the last element\nm[1, 2]\nm[1, [2, 3]] # the second and third element in the first row\nm[1:3] # the first three elements according to linear indexing\nm[:, 1:3] # the first three columns\nm[1, :] # the first row\nm[:] # all elements\n\n#+\n\nhcat(m, m)\nvcat(m, m)\n\n#+\n\ncat(m, m; dims = 2) # equivalent to hcat(m, m)\ncat(m, m; dims = 1) # equivalent to vcat(m, m)\n\n#+\n\nv = [11, 12]\nvcat(m, v)\n\n# ### Exercise:\n# Create two vectors: vector of all odd positive integers smaller than `10` and vector of\n# all even positive integers smaller than `10`. Then concatenate these two vectors\n# horizontally and fill the third row with `4`.\n# \n# ---\n# ### Solution:\n\nv1 = collect(1:2:9)\nv2 = collect(2:2:10)\n\nM = hcat(v1, v2)\nM[3,:] .= 4\nM\n\n# ---\n# \n# ## `N`-dimensional arrays\n\n\nA = zeros(3, 5, 2) # equivalent to A = zeros((3, 5, 2))\nB = zeros(Int64, 3, 5, 2)  # equivalent to B = zeros(Int64, (3, 5, 2))\n\ntypeof(A)\neltype(A)\nndims(A)\nsize(A)\nlength(A)\n\n#+\n\nB[1] = 1 # assign 1 to the first element\nB[1, 2, 2] = 2 # assign 2 to the element at position (1,2,2)\nB[2,:,1] .= 4\n\nB\n\n#+\n\nones(Float32, 2, 3, 1)\nfill(1.234, 2, 2)\n\n# ### Exercise:\n# Create three matrices with the following properties:\n# - Matrix `A` is of size `2x3`, and all its elements equal 0.\n# - Matrix `B` is of size `2x3x1`, and all its elements equal 1.\n# - Matrix `C` is of size `2x3`, and all its elements equal 2.\n# Concatenate these three matrices along the third dimension.\n#\n# **Hint:** use the `cat` function and the keyword `dims`.\n# \n# ---\n# ### Solution:\n\nA = zeros(2, 3)\nB = ones(2, 3, 1)\nC = fill(2, 2, 3)\n\ncat(A, B, C; dims = 3)\n\n# ---\n# \n# ## Broadcasting\n\na = [1,2,3] # column vector\n\na .-= 4 # from each element of vector subtracts 4\na -= 1\n\n#+\n\nabs.(a)\nsum(exp.(sqrt.(abs.(a .- 1)))./2)\n\n#+\n\na = [1,2,3] # column vector\nb = [4,5,6] # column vector\n\na * b\na' * b\na * b'\na .* b\n\n\n# ### Exercise:\n# Construct a matrix whose elements are given by the following formula\n# $$\n# A_{i, j} = \\frac{1}{2}\\exp\\{(B_{i, j} + 1)^2\\}, \\quad i \\in \\{1, 2\\}, \\; j \\in\n# \\{1, 2, 3\\}\n# $$\n# where the matrix $B$ is defined by\n\nB = [\n    -1  0  2;\n    2  -3  1;\n]\n\n# \n# ---\n# ### Solution:\n\nA = exp.((B .+ 1) .^ 2) ./ 2\n\nA = @. exp((B + 1) ^ 2) / 2\n\nA = zeros(2, 3);\nfor i in 1:length(A)\n    A[i] = exp((B[i] + 1)^2)/2\nend\nA\n\n# ---\n# \n# ## Views\n\nA = [1 2 3; 4 5 6]\nB = A\n\nB[2] = 42\n\nA == B\n\n#+\n\nC = copy(A)\nC[4] = 10\n\nA == C\n\n#+\n\nD = A[1:2, 1:2]\nD[1] = 15\n\nD == A[1:2, 1:2]\n\n#+\n\nE = view(A, 1:2, 1:2)\nE = @view A[1:2, 1:2]\n\nE[4] = 78\n\nE == A[1:2, 1:2]\n\n#+\n\ntypeof(E)\n\n#+\n\nA = [1 2 3; 4 5 6]\nA_view = @view A[:, :]\n\nsum(A)\nsum(A_view)\nminimum(A; dims = 1)\nminimum(A_view; dims = 1)\n\n#+\n\nA = [1 2 3; 4 5 6];\n\nsum(exp.(sqrt.(abs.(@view(A[1, :]) .- @view(A[2, :]))))./2)\n@views sum(exp.(sqrt.(abs.(A[1, :] .- A[2, :])))./2)\n", "meta": {"hexsha": "1e754b7ba943fff25ad3e9ec20014bfa8d5dd25d", "size": 3904, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_02/01-arrays-solved.jl", "max_stars_repo_name": "JuliaTeachingCTU/Julia-for-Optimization-and-Learning-Scripts", "max_stars_repo_head_hexsha": "8e00299449736e4ccf47c247aa9d80f99a7e5b92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lecture_02/01-arrays-solved.jl", "max_issues_repo_name": "JuliaTeachingCTU/Julia-for-Optimization-and-Learning-Scripts", "max_issues_repo_head_hexsha": "8e00299449736e4ccf47c247aa9d80f99a7e5b92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecture_02/01-arrays-solved.jl", "max_forks_repo_name": "JuliaTeachingCTU/Julia-for-Optimization-and-Learning-Scripts", "max_forks_repo_head_hexsha": "8e00299449736e4ccf47c247aa9d80f99a7e5b92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.6503496503, "max_line_length": 89, "alphanum_fraction": 0.5489241803, "num_tokens": 1675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8902942333990422, "lm_q1q2_score": 0.7939742335949569}}
{"text": "# # Binary (or 0-1) knapsack problem\n# Given a knapsack of some capacity $C$ and $n$ objects with object $i$ having weight $w_i$ and profit $p_i$, the goal is to choose some subset of the objects that can fit in the knapsack (i.e. the sum of their weights is no more than $C$) while maximizing profit.\n#\n# This can be formulated as a mixed-integer program as:\n#\n# $$\n# \\begin{array}{ll}\n#   \\text{maximize} & x' p \\\\\n#     \\text{subject to} & x \\in \\{0, 1\\} \\\\\n#   & w' x \\leq C \\\\\n# \\end{array}\n# $$\n#\n# where $x$ is a vector is size $n$ where $x_i$ is one if we chose to keep the object in the knapsack, 0 otherwise.\n\n## Data taken from http://people.sc.fsu.edu/~jburkardt/datasets/knapsack_01/knapsack_01.html\nw = [23; 31; 29; 44; 53; 38; 63; 85; 89; 82]\nC = 165 \np =  [92; 57; 49; 68; 60; 43; 67; 84; 87; 72];\nn = length(w)\n\n#-\n\nusing Convex, GLPK\nx = Variable(n, :Bin)\nproblem = maximize(dot(p, x), dot(w, x) <= C)\nsolve!(problem, GLPK.Optimizer)\nevaluate(x)\n", "meta": {"hexsha": "8e640843621c3dd8686df063d2d0c16a5ba93dc5", "size": 964, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/mixed_integer/binary_knapsack.jl", "max_stars_repo_name": "JinraeKim/Convex.jl", "max_stars_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 123, "max_stars_repo_stars_event_min_datetime": "2020-06-16T21:56:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:05:39.000Z", "max_issues_repo_path": "docs/examples_literate/mixed_integer/binary_knapsack.jl", "max_issues_repo_name": "JinraeKim/Convex.jl", "max_issues_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122, "max_issues_repo_issues_event_min_datetime": "2020-06-14T00:19:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T14:02:09.000Z", "max_forks_repo_path": "docs/examples_literate/mixed_integer/binary_knapsack.jl", "max_forks_repo_name": "JinraeKim/Convex.jl", "max_forks_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2020-08-21T07:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T13:40:50.000Z", "avg_line_length": 33.2413793103, "max_line_length": 264, "alphanum_fraction": 0.643153527, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812309063186, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7939693135821305}}
{"text": "function hessian{T<:AbstractFloat}(f::Function,x::Array{T,1})\n\n  m = length(x)\n\n\te = eps(T)^(1/4)*maxabs([x;one(T)])\n\tdh = eye(m)*e\n  hess = Array(T,m,m)\n\n  for i = 1:m\n\t\thess[i,i] = (-f(x+2*dh[:,i])+16*f(x+dh[:,i])-30*f(x)+16*f(x-dh[:,i])-f(x-2*dh[:,i]))/(12*e^2)\n  end\n\n    for i = 1:m-1\n      for j = i+1:m\n\t\t\t  hess[i,j] = (f(x+dh[:,i]+dh[:,j])+f(x-dh[:,i]-dh[:,j])-f(x-dh[:,i]+dh[:,j])-f(x+dh[:,i]-dh[:,j]))/(4*e^2)\n        hess[j,i] = hess[i,j]\n      end\n    end\n\n    return hess\n\nend\n", "meta": {"hexsha": "703dc7a4fa693aadc9619584c38e21608f242cd6", "size": 491, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hessian.jl", "max_stars_repo_name": "JuliaPackageMirrors/SolveDSGE.jl", "max_stars_repo_head_hexsha": "1f416fa81fe7a77279bff1d81474b85e652fb58a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-07T23:17:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-07T23:17:35.000Z", "max_issues_repo_path": "src/hessian.jl", "max_issues_repo_name": "JuliaPackageMirrors/SolveDSGE.jl", "max_issues_repo_head_hexsha": "1f416fa81fe7a77279bff1d81474b85e652fb58a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hessian.jl", "max_forks_repo_name": "JuliaPackageMirrors/SolveDSGE.jl", "max_forks_repo_head_hexsha": "1f416fa81fe7a77279bff1d81474b85e652fb58a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.347826087, "max_line_length": 110, "alphanum_fraction": 0.4602851324, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9683812318188366, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7939693100685906}}
{"text": "\"\"\"\n    MaternKernel(; ν = 1.0)\n\nThe matern kernel is a Mercer kernel given by the formula:\n```\n    κ(x,y) = 2^{1-ν}/Γ(ν)*(√(2ν)‖x-y‖)^ν K_ν(√(2ν)‖x-y‖)\n```\nFor `ν=n+1/2, n=0,1,2,...` it can be simplified and you should instead use \n[`ExponentialKernel`](@ref) for `n=0`, [`Matern32Kernel`](@ref), for `n=1`, \n[`Matern52Kernel`](@ref) for `n=2` and [`SqExponentialKernel`](@ref) for `n=∞`.\n\"\"\"\nstruct MaternKernel{Tν<:Real} <: SimpleKernel\n    ν::Vector{Tν}\n    function MaternKernel(;nu::T=1.5, ν::T=nu) where {T<:Real}\n        @check_args(MaternKernel, ν, ν > zero(T), \"ν > 0\")\n        return new{T}([ν])\n    end\nend\n\n@functor MaternKernel\n\n@inline function kappa(κ::MaternKernel, d::Real)\n    result = _matern(first(κ.ν), d)\n    return ifelse(iszero(d), one(result), result)\nend\n\nfunction _matern(ν::Real, d::Real)\n    y = sqrt(2ν) * d\n    return exp((one(d) - ν) * logtwo - loggamma(ν) + ν * log(y) + log(besselk(ν, y)))\nend\n\nmetric(::MaternKernel) = Euclidean()\n\nBase.show(io::IO, κ::MaternKernel) = print(io, \"Matern Kernel (ν = \", first(κ.ν), \")\")\n\n\"\"\"\n    Matern32Kernel()\n\nThe matern 3/2 kernel is a Mercer kernel given by the formula:\n```\n    κ(x,y) = (1+√(3)‖x-y‖)exp(-√(3)‖x-y‖)\n```\n\"\"\"\nstruct Matern32Kernel <: SimpleKernel end\n\nkappa(κ::Matern32Kernel, d::Real) = (1 + sqrt(3) * d) * exp(-sqrt(3) * d)\n\nmetric(::Matern32Kernel) = Euclidean()\n\nBase.show(io::IO, ::Matern32Kernel) = print(io, \"Matern 3/2 Kernel\")\n\n\"\"\"\n    Matern52Kernel()\n\nThe matern 5/2 kernel is a Mercer kernel given by the formula:\n```\n    κ(x,y) = (1+√(5)‖x-y‖ + 5/3‖x-y‖^2)exp(-√(5)‖x-y‖)\n```\n\"\"\"\nstruct Matern52Kernel <: SimpleKernel end\n\nkappa(κ::Matern52Kernel, d::Real) = (1 + sqrt(5) * d + 5 * d^2 / 3) * exp(-sqrt(5) * d)\n\nmetric(::Matern52Kernel) = Euclidean()\n\nBase.show(io::IO, ::Matern52Kernel) = print(io, \"Matern 5/2 Kernel\")\n", "meta": {"hexsha": "e6b8ee8eaaab3736d9ff3267aae18a0f33eaf280", "size": 1824, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basekernels/matern.jl", "max_stars_repo_name": "gkazunii/KernelFunctions.jl", "max_stars_repo_head_hexsha": "1e5751ec632477373203886920b1fe0f29966b48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-22T12:11:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-22T12:11:38.000Z", "max_issues_repo_path": "src/basekernels/matern.jl", "max_issues_repo_name": "st--/KernelFunctions.jl", "max_issues_repo_head_hexsha": "d6eab2bfbf5c772bd293752665ea42dd087866b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basekernels/matern.jl", "max_forks_repo_name": "st--/KernelFunctions.jl", "max_forks_repo_head_hexsha": "d6eab2bfbf5c772bd293752665ea42dd087866b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.223880597, "max_line_length": 87, "alphanum_fraction": 0.6041666667, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361162033533, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7939418971704255}}
{"text": "#=\nGenerate Symbolic Jacobian with ModelingToolkit. The testing equations are from Matlab tutorial: \n- Jacobian and gradient: https://www.mathworks.com/help/symbolic/jacobian.html\n- Hessian: https://www.mathworks.com/help/symbolic/hessian.html\n=#\n\nusing ModelingToolkit\n\n@variables x, y, z\n\n\n# Jacobian: Vector{1, N} → Matrix{N,M} where M is Number of variables\njac = ModelingToolkit.jacobian([x*y*z, y^2, x + z], [x, y, z])\n\n# Gradient: Equation → Vector\ngrad = ModelingToolkit.gradient(2*x + 3*y + 4*z, [x, y, z])\n\n# Hessian\nhess = ModelingToolkit.hessian(x*y+2*z*x, [x,y,z])\n\n# Hessian: Jacobian of Gradient \nhess_ = ModelingToolkit.jacobian(ModelingToolkit.gradient(x*y+2*z*x, [x,y,z]), [x,y,z])", "meta": {"hexsha": "37ba6256e26a6781bc21fb1c0e236661d222a563", "size": 699, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".stack/cal_jac.jl", "max_stars_repo_name": "stevengogogo/PotentialMap.jl", "max_stars_repo_head_hexsha": "bb8fe3df8bf20c9ee30e17dd61640a3546befd83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-20T06:05:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-20T06:05:07.000Z", "max_issues_repo_path": ".stack/cal_jac.jl", "max_issues_repo_name": "stevengogogo/PotentialMap.jl", "max_issues_repo_head_hexsha": "bb8fe3df8bf20c9ee30e17dd61640a3546befd83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-01-04T00:26:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T06:41:56.000Z", "max_forks_repo_path": ".stack/cal_jac.jl", "max_forks_repo_name": "stevengogogo/PotentialMap.jl", "max_forks_repo_head_hexsha": "bb8fe3df8bf20c9ee30e17dd61640a3546befd83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-02T03:43:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-02T03:43:40.000Z", "avg_line_length": 31.7727272727, "max_line_length": 97, "alphanum_fraction": 0.7138769671, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7939418902564781}}
{"text": "# logarithmic barrier function\n\nimmutable LogBarrier{T <: Real} <: ProximableFunction\n  a::T\n  b::T\n  mu::T\n  function LogBarrier(a::T, b::T, mu::T)\n    if mu <= 0\n      error(\"parameter mu must be positive\")\n    else\n      new(a, b, mu)\n    end\n  end\nend\n\n\"\"\"\n  LogBarrier(a::Real=1.0, b::Real=0.0, mu::Real=1.0)\n\nReturns the function `g(x) = -mu*sum(log(a*x_i+b), i=1,...,n)`.\n\"\"\"\n\nLogBarrier{T <: Real}(a::T=1.0, b::T=0.0, mu::T=1.0) = LogBarrier{T}(a, b, mu)\n\nfunction (f::LogBarrier){T <: Real}(x::AbstractArray{T,1})\n  sumf = 0.0\n  v = 0.0\n  for i in eachindex(x)\n    v = f.a*x[i]+f.b\n    if v <= 0.0\n      return +Inf\n    end\n    sumf += log(v)\n  end\n  return -f.mu*sumf\nend\n\nfunction prox!{T <: Real}(f::LogBarrier, x::AbstractArray{T,1}, y::AbstractArray{T}, gamma::Real=1.0)\n  par = 4*gamma*f.mu*f.a*f.a\n  sumf = 0.0\n  z = 0.0\n  v = 0.0\n  for i in eachindex(x)\n    z = f.a*x[i] + f.b\n    v = (z + sqrt(z*z + par))/2\n    y[i] = (v - f.b)/f.a\n    sumf += log(v)\n  end\n  return -f.mu*sumf\nend\n\nfun_name(f::LogBarrier) = \"logarithmic barrier\"\nfun_dom(f::LogBarrier) = \"AbstractArray{Real}\"\nfun_expr(f::LogBarrier) = \"x ↦ -μ * sum( log(a*x_i+b), i=1,...,n )\"\nfun_params(f::LogBarrier) = \"a = $(f.a), b = $(f.b), μ = $(f.mu)\"\n\nfunction prox_naive{T <: Real}(f::LogBarrier, x::AbstractArray{T,1}, gamma::Real=1.0)\n  asqr = f.a*f.a\n  z = f.a*x + f.b\n  y = ((z + sqrt.(z.*z + 4*gamma*f.mu*asqr))/2 - f.b)/f.a\n  fy = -f.mu * sum(log.(f.a*y+f.b))\n  return y, fy\nend\n", "meta": {"hexsha": "bcc445532375a46ffdd9f0a5b020a47666093234", "size": 1465, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/logBarrier.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/logBarrier.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/logBarrier.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.253968254, "max_line_length": 101, "alphanum_fraction": 0.556996587, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850021922959, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.7939395017063217}}
{"text": "using Random\nRandom.seed!(1)\n\nnumbers = 10:25\nN = 10^7\n\nfirstDigit(x) = Int(floor(x/10))\nsecondDigit(x) = x%10\n\nnumThirteen, numFirstIsOne, numSecondIsThree = 0, 0, 0\n\nfor _ in 1:N\n    X = rand(numbers)\n    global numThirteen += X == 13 \n    global numFirstIsOne += firstDigit(X) == 1 \n    global numSecondIsThree += secondDigit(X) == 3\nend\n\nprobThirteen, probFirstIsOne, probSecondIsThree =\n    (numThirteen,numFirstIsOne,numSecondIsThree)./N\n\nprintln(\"P(13) = \", round(probThirteen, digits=4),\n        \"\\nP(1_) = \",round(probFirstIsOne, digits=4),\n        \"\\nP(_3) = \", round(probSecondIsThree, digits=4),\n        \"\\nP(1_)*P(_3) = \",round(probFirstIsOne*probSecondIsThree, digits=4))\n", "meta": {"hexsha": "b488e36537ac8504d05e12ad4178f70bdcc5bcec", "size": 686, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2_chapter/independence.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "2_chapter/independence.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "2_chapter/independence.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 26.3846153846, "max_line_length": 77, "alphanum_fraction": 0.666180758, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7939394984001101}}
{"text": "\nm = model(data...) # instantiate model on the data\nq = vi(m, vi_alg)  # perform VI on `m` using the VI method `vi_alg`, which returns a `VariationalPosterior`\n\n\nusing Random\nusing Turing\nusing Turing: Variational\n\nRandom.seed!(42);\n\n\n# generate data\nx = randn(2000);\n\n\n@model model(x) = begin\n    s ~ InverseGamma(2, 3)\n    m ~ Normal(0.0, sqrt(s))\n    for i = 1:length(x)\n        x[i] ~ Normal(m, sqrt(s))\n    end\nend;\n\n\n# Instantiate model\nm = model(x);\n\n\nsamples_nuts = sample(m, NUTS(200, 0.65), 10000);\n\n\n@doc(Variational.vi)\n\n\n@doc(Variational.meanfield)\n\n\n@doc(Variational.ADVI)\n\n\n# ADVI\nadvi = ADVI(10, 1000)\nq = vi(m, advi);\n\n\nq isa MultivariateDistribution\n\n\nrand(q)\n\n\nlogpdf(q, rand(q))\n\n\nvar(x), mean(x)\n\n\n(mean(rand(q, 1000); dims = 2)..., )\n\n\nsamples = rand(q, 10000);\n\n\n# setup for plotting\nusing Plots, LaTeXStrings, StatsPlots\n\n\np1 = histogram(samples[1, :], bins=100, normed=true, alpha=0.2, color = :blue, label = \"\")\ndensity!(samples[1, :], label = \"s (ADVI)\", color = :blue, linewidth = 2)\ndensity!(samples_nuts, :s; label = \"s (NUTS)\", color = :green, linewidth = 2)\nvline!([var(x)], label = \"s (data)\", color = :black)\nvline!([mean(samples[1, :])], color = :blue, label =\"\")\n\np2 = histogram(samples[2, :], bins=100, normed=true, alpha=0.2, color = :blue, label = \"\")\ndensity!(samples[2, :], label = \"m (ADVI)\", color = :blue, linewidth = 2)\ndensity!(samples_nuts, :m; label = \"m (NUTS)\", color = :green, linewidth = 2)\nvline!([mean(x)], color = :black, label = \"m (data)\")\nvline!([mean(samples[2, :])], color = :blue, label=\"\")\n\nplot(p1, p2, layout=(2, 1), size=(900, 500))\n\n\n# used to compute closed form expression of posterior\nusing ConjugatePriors\n\n# closed form computation\n# notation mapping has been verified by explicitly computing expressions\n# in \"Conjugate Bayesian analysis of the Gaussian distribution\" by Murphy\nμ₀ = 0.0 # => μ\nκ₀ = 1.0 # => ν, which scales the precision of the Normal\nα₀ = 2.0 # => \"shape\"\nβ₀ = 3.0 # => \"rate\", which is 1 / θ, where θ is \"scale\"\n\n# prior\npri = NormalGamma(μ₀, κ₀, α₀, β₀)\n\n# posterior\npost = posterior(pri, Normal, x)\n\n# marginal distribution of τ = 1 / σ²\n# Eq. (90) in \"Conjugate Bayesian analysis of the Gaussian distribution\" by Murphy\n# `scale(post)` = θ\np_τ = Gamma(post.shape, scale(post))\np_σ²_pdf = z -> pdf(p_τ, 1 / z) # τ => 1 / σ² \n\n# marginal of μ\n# Eq. (91) in \"Conjugate Bayesian analysis of the Gaussian distribution\" by Murphy\np_μ = TDist(2 * post.shape)\n\nμₙ = post.mu    # μ → μ\nκₙ = post.nu    # κ → ν\nαₙ = post.shape # α → shape\nβₙ = post.rate  # β → rate\n\n# numerically more stable but doesn't seem to have effect; issue is probably internal to\n# `pdf` which needs to compute ≈ Γ(1000) \np_μ_pdf = z -> exp(logpdf(p_μ, (z - μₙ) * exp(- 0.5 * log(βₙ) + 0.5 * log(αₙ) + 0.5 * log(κₙ))))\n\n# posterior plots\np1 = plot();\nhistogram!(samples[1, :], bins=100, normed=true, alpha=0.2, color = :blue, label = \"\")\ndensity!(samples[1, :], label = \"s (ADVI)\", color = :blue)\ndensity!(samples_nuts, :s; label = \"s (NUTS)\", color = :green)\nvline!([mean(samples[1, :])], linewidth = 1.5, color = :blue, label =\"\")\n\n# normalize using Riemann approx. because of (almost certainly) numerical issues\nΔ = 0.001\nr = 0.75:0.001:1.50\nnorm_const = sum(p_σ²_pdf.(r) .* Δ)\nplot!(r, p_σ²_pdf, label = \"s (posterior)\", color = :red);\nvline!([var(x)], label = \"s (data)\", linewidth = 1.5, color = :black, alpha = 0.7);\nxlims!(0.75, 1.35);\n\np2 = plot();\nhistogram!(samples[2, :], bins=100, normed=true, alpha=0.2, color = :blue, label = \"\")\ndensity!(samples[2, :], label = \"m (ADVI)\", color = :blue)\ndensity!(samples_nuts, :m; label = \"m (NUTS)\", color = :green)\nvline!([mean(samples[2, :])], linewidth = 1.5, color = :blue, label=\"\")\n\n\n# normalize using Riemann approx. because of (almost certainly) numerical issues\nΔ = 0.0001\nr = -0.1 + mean(x):Δ:0.1 + mean(x)\nnorm_const = sum(p_μ_pdf.(r) .* Δ)\nplot!(r, z -> p_μ_pdf(z) / norm_const, label = \"m (posterior)\", color = :red);\nvline!([mean(x)], label = \"m (data)\", linewidth = 1.5, color = :black, alpha = 0.7);\n\nxlims!(-0.25, 0.25);\n\np = plot(p1, p2; layout=(2, 1), size=(900, 500))\n\n\nRandom.seed!(1);\n\n\n# Import RDatasets.\nusing RDatasets\n\n# Hide the progress prompt while sampling.\nTuring.setprogress!(false);\n\n\n# Import the \"Default\" dataset.\ndata = RDatasets.dataset(\"datasets\", \"mtcars\");\n\n# Show the first six rows of the dataset.\nfirst(data, 6)\n\n\n# Function to split samples.\nfunction split_data(df, at = 0.70)\n    r = size(df,1)\n    index = Int(round(r * at))\n    train = df[1:index, :]\n    test  = df[(index+1):end, :]\n    return train, test\nend\n\n# A handy helper function to rescale our dataset.\nfunction standardize(x)\n    return (x .- mean(x, dims=1)) ./ std(x, dims=1), x\nend\n\n# Another helper function to unstandardize our datasets.\nfunction unstandardize(x, orig)\n    return (x .+ mean(orig, dims=1)) .* std(orig, dims=1)\nend\n\n\n# Remove the model column.\nselect!(data, Not(:Model))\n\n# Standardize our dataset.\n(std_data, data_arr) = standardize(Matrix(data))\n\n# Split our dataset 70%/30% into training/test sets.\ntrain, test = split_data(std_data, 0.7)\n\n# Save dataframe versions of our dataset.\ntrain_cut = DataFrame(train, names(data))\ntest_cut = DataFrame(test, names(data))\n\n# Create our labels. These are the values we are trying to predict.\ntrain_label = train_cut[:, :MPG]\ntest_label = test_cut[:, :MPG]\n\n# Get the list of columns to keep.\nremove_names = filter(x->!in(x, [:MPG, :Model]), names(data))\n\n# Filter the test and train sets.\ntrain = Matrix(train_cut[:,remove_names]);\ntest = Matrix(test_cut[:,remove_names]);\n\n\n# Bayesian linear regression.\n@model linear_regression(x, y, n_obs, n_vars, ::Type{T}=Vector{Float64}) where {T} = begin\n    # Set variance prior.\n    σ₂ ~ truncated(Normal(0,100), 0, Inf)\n    \n    # Set intercept prior.\n    intercept ~ Normal(0, 3)\n    \n    # Set the priors on our coefficients.\n    coefficients ~ MvNormal(zeros(n_vars), 10 * ones(n_vars))\n    \n    # Calculate all the mu terms.\n    mu = intercept .+ x * coefficients\n    y ~ MvNormal(mu, σ₂)\nend;\n\n\nn_obs, n_vars = size(train)\nm = linear_regression(train, train_label, n_obs, n_vars);\n\n\nq0 = Variational.meanfield(m)\ntypeof(q0)\n\n\nadvi = ADVI(10, 10_000)\n\n\nusing Flux, Turing\nusing Turing.Variational\n\nvi(m, advi; optimizer = Flux.ADAM())\n\n\nopt = Variational.DecayedADAGrad(1e-2, 1.1, 0.9)\n\n\nq = vi(m, advi, q0; optimizer = opt)\ntypeof(q)\n\n\nz = rand(q, 10_000);\n\n\navg = vec(mean(z; dims = 2))\n\n\n_, sym2range = bijector(m, Val(true));\nsym2range\n\n\navg[union(sym2range[:σ₂]...)]\n\n\navg[union(sym2range[:intercept]...)]\n\n\navg[union(sym2range[:coefficients]...)]\n\n\nfunction plot_variational_marginals(z, sym2range)\n    ps = []\n\n    for (i, sym) in enumerate(keys(sym2range))\n        indices = union(sym2range[sym]...)  # <= array of ranges\n        if sum(length.(indices)) > 1\n            offset = 1\n            for r in indices\n                for j in r\n                    p = density(z[j, :], title = \"$(sym)[$offset]\", titlefontsize = 10, label = \"\")\n                    push!(ps, p)\n\n                    offset += 1\n                end\n            end\n        else\n            p = density(z[first(indices), :], title = \"$(sym)\", titlefontsize = 10, label = \"\")\n            push!(ps, p)\n        end\n    end\n    \n    return plot(ps..., layout = (length(ps), 1), size = (500, 1500))\nend\n\n\nplot_variational_marginals(z, sym2range)\n\n\nchain = sample(m, NUTS(0.65), 10_000);\n\n\nplot(chain)\n\n\nvi_mean = vec(mean(z; dims = 2))[[union(sym2range[:coefficients]...)..., union(sym2range[:intercept]...)..., union(sym2range[:σ₂]...)...]]\n\n\nmean(chain).nt.mean\n\n\nsum(abs2, mean(chain).nt.mean .- vi_mean)\n\n\n# Import the GLM package.\nusing GLM\n\n# Perform multivariate OLS.\nols = lm(@formula(MPG ~ Cyl + Disp + HP + DRat + WT + QSec + VS + AM + Gear + Carb), train_cut)\n\n# Store our predictions in the original dataframe.\ntrain_cut.OLSPrediction = unstandardize(GLM.predict(ols), data.MPG);\ntest_cut.OLSPrediction = unstandardize(GLM.predict(ols, test_cut), data.MPG);\n\n\n# Make a prediction given an input vector.\nfunction prediction_chain(chain, x)\n    p = get_params(chain)\n    α = mean(p.intercept)\n    β = collect(mean.(p.coefficients))\n    return  α .+ x * β\nend\n\n\n# Make a prediction using samples from the variational posterior given an input vector.\nfunction prediction(samples::AbstractVector, sym2ranges, x)\n    α = mean(samples[union(sym2ranges[:intercept]...)])\n    β = vec(mean(samples[union(sym2ranges[:coefficients]...)]; dims = 2))\n    return  α .+ x * β\nend\n\nfunction prediction(samples::AbstractMatrix, sym2ranges, x)\n    α = mean(samples[union(sym2ranges[:intercept]...), :])\n    β = vec(mean(samples[union(sym2ranges[:coefficients]...), :]; dims = 2))\n    return  α .+ x * β\nend\n\n\n# Unstandardize the dependent variable.\ntrain_cut.MPG = unstandardize(train_cut.MPG, data.MPG);\ntest_cut.MPG = unstandardize(test_cut.MPG, data.MPG);\n\n\n# Show the first side rows of the modified dataframe.\nfirst(test_cut, 6)\n\n\nz = rand(q, 10_000);\n\n\n# Calculate the predictions for the training and testing sets using the samples `z` from variational posterior\ntrain_cut.VIPredictions = unstandardize(prediction(z, sym2range, train), data.MPG);\ntest_cut.VIPredictions = unstandardize(prediction(z, sym2range, test), data.MPG);\n\ntrain_cut.BayesPredictions = unstandardize(prediction_chain(chain, train), data.MPG);\ntest_cut.BayesPredictions = unstandardize(prediction_chain(chain, test), data.MPG);\n\n\nvi_loss1 = mean((train_cut.VIPredictions - train_cut.MPG).^2)\nbayes_loss1 = mean((train_cut.BayesPredictions - train_cut.MPG).^2)\nols_loss1 = mean((train_cut.OLSPrediction - train_cut.MPG).^2)\n\nvi_loss2 = mean((test_cut.VIPredictions - test_cut.MPG).^2)\nbayes_loss2 = mean((test_cut.BayesPredictions - test_cut.MPG).^2)\nols_loss2 = mean((test_cut.OLSPrediction - test_cut.MPG).^2)\n\nprintln(\"Training set:\n    VI loss: $vi_loss1\n    Bayes loss: $bayes_loss1\n    OLS loss: $ols_loss1\nTest set: \n    VI loss: $vi_loss2\n    Bayes loss: $bayes_loss2\n    OLS loss: $ols_loss2\")\n\n\nz = rand(q, 1000);\npreds = hcat([unstandardize(prediction(z[:, i], sym2range, test), data.MPG) for i = 1:size(z, 2)]...);\n\nscatter(1:size(test, 1), mean(preds; dims = 2), yerr=std(preds; dims = 2), label=\"prediction (mean ± std)\", size = (900, 500), markersize = 8)\nscatter!(1:size(test, 1), unstandardize(test_label, data.MPG), label=\"true\")\nxaxis!(1:size(test, 1))\nylims!(95, 140)\ntitle!(\"Mean-field ADVI (Normal)\")\n\n\npreds = hcat([unstandardize(prediction_chain(chain[i], test), data.MPG) for i = 1:5:size(chain, 1)]...);\n\nscatter(1:size(test, 1), mean(preds; dims = 2), yerr=std(preds; dims = 2), label=\"prediction (mean ± std)\", size = (900, 500), markersize = 8)\nscatter!(1:size(test, 1), unstandardize(test_label, data.MPG), label=\"true\")\nxaxis!(1:size(test, 1))\nylims!(95, 140)\ntitle!(\"MCMC (NUTS)\")\n\n\nusing Bijectors\n\n\nusing Bijectors: Scale, Shift\n\n\nd = length(q)\nbase_dist = Turing.DistributionsAD.TuringDiagMvNormal(zeros(d), ones(d))\n\n\nto_constrained = inv(bijector(m));\n\n\nfunction getq(θ)\n    d = length(θ) ÷ 2\n    A = @inbounds θ[1:d]\n    b = @inbounds θ[d + 1: 2 * d]\n    \n    b = to_constrained ∘ Shift(b; dim = Val(1)) ∘ Scale(exp.(A); dim = Val(1))\n    \n    return transformed(base_dist, b)\nend\n\n\nq_mf_normal = vi(m, advi, getq, randn(2 * d));\n\n\np1 = plot_variational_marginals(rand(q_mf_normal, 10_000), sym2range) # MvDiagNormal + Affine transformation + to_constrained\np2 = plot_variational_marginals(rand(q, 10_000), sym2range)  # Turing.meanfield(m)\n\nplot(p1, p2, layout = (1, 2), size = (800, 2000))\n\n\nusing LinearAlgebra\n\n\n# Using `ComponentArrays.jl` together with `UnPack.jl` makes our lives much easier.\nusing ComponentArrays, UnPack\n\n\nproto_arr = ComponentArray(\n    L = zeros(d, d),\n    b = zeros(d)\n)\nproto_axes = proto_arr |> getaxes\nnum_params = length(proto_arr)\n\nfunction getq(θ)\n    L, b = begin\n        @unpack L, b = ComponentArray(θ, proto_axes)\n        LowerTriangular(L), b\n    end\n    # For this to represent a covariance matrix we need to ensure that the diagonal is positive.\n    # We can enforce this by zeroing out the diagonal and then adding back the diagonal exponentiated.\n    D = Diagonal(diag(L))\n    A = L - D + exp(D) # exp for Diagonal is the same as exponentiating only the diagonal entries\n    \n    b = to_constrained ∘ Shift(b; dim = Val(1)) ∘ Scale(A; dim = Val(1))\n    \n    return transformed(base_dist, b)\nend\n\n\nadvi = ADVI(10, 20_000)\n\n\nq_full_normal = vi(m, advi, getq, randn(num_params); optimizer = Variational.DecayedADAGrad(1e-2));\n\n\nA = q_full_normal.transform.ts[1].a\n\n\nheatmap(cov(A * A'))\n\n\nzs = rand(q_full_normal, 10_000);\n\n\np1 = plot_variational_marginals(rand(q_mf_normal, 10_000), sym2range)\np2 = plot_variational_marginals(rand(q_full_normal, 10_000), sym2range)\n\nplot(p1, p2, layout = (1, 2), size = (800, 2000))\n\n\n# Unfortunately, it seems like this has quite a high variance which is likely to be due to numerical instability, \n# so we consider a larger number of samples. If we get a couple of outliers due to numerical issues, \n# these kind affect the mean prediction greatly.\nz = rand(q_full_normal, 10_000);\n\n\ntrain_cut.VIFullPredictions = unstandardize(prediction(z, sym2range, train), data.MPG);\ntest_cut.VIFullPredictions = unstandardize(prediction(z, sym2range, test), data.MPG);\n\n\nvi_loss1 = mean((train_cut.VIPredictions - train_cut.MPG).^2)\nvifull_loss1 = mean((train_cut.VIFullPredictions - train_cut.MPG).^2)\nbayes_loss1 = mean((train_cut.BayesPredictions - train_cut.MPG).^2)\nols_loss1 = mean((train_cut.OLSPrediction - train_cut.MPG).^2)\n\nvi_loss2 = mean((test_cut.VIPredictions - test_cut.MPG).^2)\nvifull_loss2 = mean((test_cut.VIFullPredictions - test_cut.MPG).^2)\nbayes_loss2 = mean((test_cut.BayesPredictions - test_cut.MPG).^2)\nols_loss2 = mean((test_cut.OLSPrediction - test_cut.MPG).^2)\n\nprintln(\"Training set:\n    VI loss: $vi_loss1\n    Bayes loss: $bayes_loss1\n    OLS loss: $ols_loss1\nTest set: \n    VI loss: $vi_loss2\n    Bayes loss: $bayes_loss2\n    OLS loss: $ols_loss2\")\n\n\nz = rand(q_mf_normal, 1000);\npreds = hcat([unstandardize(prediction(z[:, i], sym2range, test), data.MPG) for i = 1:size(z, 2)]...);\n\np1 = scatter(1:size(test, 1), mean(preds; dims = 2), yerr=std(preds; dims = 2), label=\"prediction (mean ± std)\", size = (900, 500), markersize = 8)\nscatter!(1:size(test, 1), unstandardize(test_label, data.MPG), label=\"true\")\nxaxis!(1:size(test, 1))\nylims!(95, 140)\ntitle!(\"Mean-field ADVI (Normal)\")\n\n\nz = rand(q_full_normal, 1000);\npreds = hcat([unstandardize(prediction(z[:, i], sym2range, test), data.MPG) for i = 1:size(z, 2)]...);\n\np2 = scatter(1:size(test, 1), mean(preds; dims = 2), yerr=std(preds; dims = 2), label=\"prediction (mean ± std)\", size = (900, 500), markersize = 8)\nscatter!(1:size(test, 1), unstandardize(test_label, data.MPG), label=\"true\")\nxaxis!(1:size(test, 1))\nylims!(95, 140)\ntitle!(\"Full ADVI (Normal)\")\n\n\npreds = hcat([unstandardize(prediction_chain(chain[i], test), data.MPG) for i = 1:5:size(chain, 1)]...);\n\np3 = scatter(1:size(test, 1), mean(preds; dims = 2), yerr=std(preds; dims = 2), label=\"prediction (mean ± std)\", size = (900, 500), markersize = 8)\nscatter!(1:size(test, 1), unstandardize(test_label, data.MPG), label=\"true\")\nxaxis!(1:size(test, 1))\nylims!(95, 140)\ntitle!(\"MCMC (NUTS)\")\n\n\nplot(p1, p2, p3, layout = (1, 3), size = (900, 250), label=\"\")\n\n\nif isdefined(Main, :TuringTutorials)\n    Main.TuringTutorials.tutorial_footer(WEAVE_ARGS[:folder], WEAVE_ARGS[:file])\nend\n\n", "meta": {"hexsha": "469ededa8d362079bf4672bb9c55ddf0771c2af6", "size": 15419, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/09-variational-inference/09_variational-inference.jl", "max_stars_repo_name": "leachim/TuringTutorials", "max_stars_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 154, "max_stars_repo_stars_event_min_datetime": "2018-08-13T17:04:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T06:28:19.000Z", "max_issues_repo_path": "script/09-variational-inference/09_variational-inference.jl", "max_issues_repo_name": "leachim/TuringTutorials", "max_issues_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 137, "max_issues_repo_issues_event_min_datetime": "2018-09-06T21:56:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T07:36:07.000Z", "max_forks_repo_path": "script/09-variational-inference/09_variational-inference.jl", "max_forks_repo_name": "leachim/TuringTutorials", "max_forks_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 82, "max_forks_repo_forks_event_min_datetime": "2018-09-17T15:57:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T04:54:57.000Z", "avg_line_length": 27.5339285714, "max_line_length": 147, "alphanum_fraction": 0.664958817, "num_tokens": 4920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7939394954372349}}
{"text": "## Preloads\nmodule DHC_Utils\n\n    using Statistics\n    using FFTW\n    using Plots\n    using LinearAlgebra\n    using StaticArrays\n    using HybridArrays\n\n    export finklet\n    export fink_filter_bank_slow\n    export fink_filter_bank\n    export fink_filter_list\n    export speedy_DHC\n\n\n    ## Define wavelet in Fourier space\n    function finklet(j, l)\n        # -------- set filters\n        jrad = 7-j\n        dθ = π/8        # 8 angular bins hardwired\n        θ_l = dθ*l\n        # -------- define coordinates\n        nx = 256\n        xbox = LinRange(-nx/2, nx/2-1 , nx)\n        # make a 256x256 grid of X\n        sx = xbox' .* ones(nx)\n        sy = ones(nx)' .* xbox\n        r  = sqrt.((sx).^2 + (sy).^2)\n        θ  = mod.(atan.(sy, sx).+π .-θ_l,2*π)\n        nozeros = r .> 0\n        logr = log2.(r[nozeros])\n        r[nozeros] = logr\n        # -------- in Fourier plane, envelope of psi_j,l\n        mask = (abs.(θ.-π).<= dθ) .& (abs.(r.-jrad) .<= 1)\n        # -------- angular part\n        ang = cos.((θ.-π).*4)\n        # -------- radial part\n        rad = cos.((r.-jrad).*π./2)\n        psi = mask.*ang.*rad             #mask times angular part times radial part\n        return psi\n    end\n\n\n    ## Compute the whole filter bank.  Legacy code for comparison\n    function fink_filter_bank_slow(J,L)\n        fink_filter = Array{Float64, 4}(undef, 256, 256, J, L)\n        for l = 1:L\n            for j = 1:J\n                @inbounds fink_filter[:,:,j,l]=fftshift(finklet(j-1,l-1))\n            end\n        end\n        return fink_filter\n    end\n\n\n    ## Faster filter bank generation.  Only square filters allowed.\n    function fink_filter_bank(J::Integer, L::Integer; nx::Integer=256, wid::Integer=1)\n\n        # -------- set parameters\n        dθ   = π/8        # 8 angular bins hardwired\n        dx   = nx÷2-1\n\n        # -------- allocate output array of zeros\n        filt = zeros(Float64, nx, nx, J, L)\n\n        # -------- allocate theta and logr arrays\n        logr = zeros(Float64, nx, nx)\n        θ    = zeros(Float64, nx, nx)\n\n        for l = 0:L-1\n            θ_l = dθ*l\n\n        # -------- allocate anggood BitArray\n            anggood = falses(nx, nx)\n\n        # -------- loop over pixels\n            for x = 1:nx\n                sx = mod(x+dx, nx)-dx -1    # define sx,sy so that no fftshift() needed\n                for y = 1:nx\n                    sy = mod(y+dx, nx)-dx -1\n                    θ_pix  = mod(atan(sy, sx)+π -θ_l, 2*π)\n                    θ_good = abs(θ_pix-π) <= (dθ*wid)\n\n                    # If this is a pixel we might use, calculate log2(r)\n                    if θ_good\n                        anggood[y, x] = θ_good\n                        θ[y, x]       = θ_pix\n                        r = sqrt(sx^2 + sy^2)\n                        logr[y, x] = log2(max(1,r))\n                    end\n                end\n            end\n            angmask = findall(anggood)\n        # -------- compute the wavelet in the Fourier domain\n        #          the angular factor is the same for all j\n            F_angular = cos.((θ[angmask].-π).*(4/wid))\n\n        # -------- loop over j for the radial part\n            for j = 0:J-1\n                jrad  = 7-j\n                Δj    = abs.(logr[angmask].-jrad)\n                rmask = (Δj .<= 1)\n\n        # -------- radial part\n                F_radial = cos.(Δj[rmask] .* (π/2))\n                ind      = angmask[rmask]\n                filt[ind,j+1,l+1] = F_radial .* F_angular[rmask]\n            end\n        end\n        return filt\n    end\n\n\n    ## Make a list of non-zero pixels for the (Fourier plane) filters\n    function fink_filter_list(filt)\n        (ny,nx,J,L) = size(filt)\n\n        # Allocate output arrays\n        filtind = fill(CartesianIndex{2}[], J, L)\n        filtval = fill(Float64[], J, L)\n\n        # Loop over J,L and record non-zero values\n        for l=1:L\n            for j=1:J\n                f = @view filt[:,:,j,l]\n                ind = findall(f .> 1E-13)\n                val = f[ind]\n                filtind[j,l] = ind\n                filtval[j,l] = val\n            end\n        end\n        return [filtind, filtval]\n    end\n\n\n    ## Todo list\n    # Check if 2 threads really help FFT when computer is busy\n    function speedy_DHC(image::Array{Float64,2}, filter_list)\n        # Use 2 threads for FFT\n        FFTW.set_num_threads(2)\n\n        # array sizes\n        (Nx, Ny)  = size(image)\n        (J,L)     = size(filter_list[1])\n\n        # allocate coeff arrays\n        out_coeff = []\n        S0  = zeros(Float64, 2)\n        S1  = zeros(Float64, J, L)\n        S20 = zeros(Float64, J, L, J, L)\n        S12 = zeros(Float64, J, L, J, L)\n\n        # allocate image arrays for internal use\n        im_fdf_0_1 = zeros(Float64,           Nx, Ny, J, L)   # this must be zeroed!\n        im_rd_0_1  = Array{Float64, 4}(undef, Nx, Ny, J, L)\n\n        ## 0th Order\n        S0[1]   = mean(image)\n        norm_im = image.-S0[1]\n        S0[2]   = sum(norm_im .* norm_im)/(Nx*Ny)\n        norm_im ./= sqrt(Nx*Ny*S0[2])\n\n        append!(out_coeff,S0[:])\n\n        ## 1st Order\n        im_fd_0 = fft(norm_im)\n\n        # unpack filter_list\n        f_ind   = filter_list[1]  # (J, L) array of filters represented as index value pairs\n        f_val   = filter_list[2]\n\n        zarr = zeros(ComplexF64, Nx, Ny)  # temporary array to fill with zvals\n\n        # make a FFTW \"plan\" for an array of the given size and type\n        P   = plan_ifft(im_fd_0)   # P is an operator, P*im is ifft(im)\n\n        ## Main 1st Order and Precompute 2nd Order\n        for l = 1:L\n            for j = 1:J\n                S1tot = 0.0\n                f_i = f_ind[j,l]  # CartesianIndex list for filter\n                f_v = f_val[j,l]  # Values for f_i\n                # for (ind, val) in zip(f_i, f_v)   # this is slower!\n                if length(f_i) > 0\n                    for i = 1:length(f_i)\n                        ind       = f_i[i]\n                        zval      = f_v[i] * im_fd_0[ind]\n                        S1tot    += abs2(zval)\n                        zarr[ind] = zval\n                        im_fdf_0_1[ind,j,l] = abs(zval)\n                    end\n                    S1[j,l] = S1tot\n                    im_rd_0_1[:,:,j,l] .= abs2.(P*zarr)\n                    zarr[f_i] .= 0\n                end\n            end\n        end\n        append!(out_coeff, S1[:])\n\n        # we stored the abs()^2, so take sqrt (this is faster to do all at once)\n        im_rd_0_1 .= sqrt.(im_rd_0_1)\n\n        ## 2nd Order\n        Amat = reshape(im_fdf_0_1, Nx*Ny, J*L)\n        S12  = reshape(Amat' * Amat, J, L, J, L)\n        Amat = reshape(im_rd_0_1, Nx*Ny, J*L)\n        S20  = reshape(Amat' * Amat, J, L, J, L)\n\n        append!(out_coeff, S20)\n        append!(out_coeff, S12)\n\n        return out_coeff\n    end\n\nend # of module\n", "meta": {"hexsha": "ef982ca49a6a9f984a6141b6f2b23cb4bd6efc38", "size": 6770, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scratch_AKS/DHC_Utils.jl", "max_stars_repo_name": "andrew-saydjari/DHC", "max_stars_repo_head_hexsha": "4c544fd2f381f43ee02c6465a563d288b9e5a2a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-02-23T04:59:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T16:52:05.000Z", "max_issues_repo_path": "scratch_AKS/DHC_Utils.jl", "max_issues_repo_name": "andrew-saydjari/DHC", "max_issues_repo_head_hexsha": "4c544fd2f381f43ee02c6465a563d288b9e5a2a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-02-28T14:00:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-08T15:15:45.000Z", "max_forks_repo_path": "scratch_AKS/DHC_Utils.jl", "max_forks_repo_name": "andrew-saydjari/DHC", "max_forks_repo_head_hexsha": "4c544fd2f381f43ee02c6465a563d288b9e5a2a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0550458716, "max_line_length": 92, "alphanum_fraction": 0.4729689808, "num_tokens": 2010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701655, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7939394942207192}}
{"text": "# The cube, 41063625 (345^3), can be permuted to produce two other cubes:\n# 56623104 (384^33) and 66430125 (405^33). In fact, 41063625 is the smallest\n# cube which has exactly three permutations of its digits which are also cube.\n#\n# Find the smallest cube for which exactly five permutations of its digits are\n# cube.\n\nusing ProjectEulerSolutions\n\n# For each fixed number of digits, search through the right ranges of numbers\n# to build up sets of cubes.  Store them as sorted tuples, counting the number\n# that match to the same key.  When we hit 5, return the smallest.\nfunction p062solution(n::Integer=5)::Integer\n\n    ndig_max = ndigits(2^63-1) - 1  # Bigger than 18 and we will need to use BigInts\n    for ndig in 9:ndig_max\n\n        dict = Dict{Tuple, Array{Integer,1}}()\n    \n        num_low = Integer(ceil(10^((ndig-1)/3)))\n        num_high = Integer(floor(10^(ndig/3)))\n        max_count = 1\n        max_key = 1\n\n        for i in num_low:num_high\n            num = i^3\n            key = Tuple(sort(digits(num)))\n            if haskey(dict, key)\n                append!(dict[key], num)\n            else\n                dict[key] = [num]\n            end\n            c = length(dict[key])\n            if max_count < c\n               max_count = c\n               if max_count == n\n                   return minimum(dict[key])\n               end\n            end\n        end\n    end\n    return -1\nend\n\np062 = Problems.Problem(p062solution)\n\nProblems.benchmark(p062, 5)\n", "meta": {"hexsha": "59e10ed021433c53cac24fbb1af31712aa07fa7c", "size": 1473, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/062.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/062.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/062.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6875, "max_line_length": 84, "alphanum_fraction": 0.5994568907, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850021922959, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7939394927131431}}
{"text": "#\n# Implements example 4.2 in Sarkka book, but due to technical reasons with\n# regard to handling univariate and multivariate gaussians consistently,\n# we simulate two random walks by making A, H, Q, R matrices as opposed to\n# scalars specified in book.\n#\n\nfunction Example_4_2(; T = 400, seed = 1)\n\n    # Set random number generator\n\n    rg = MersenneTwister(seed)\n\n\n    # Matrices in the dynamic model are:\n\n    A = H = diagm(ones(2))\n    Q = R = diagm(ones(2))\n\n    # initialise\n\n    m₀, P₀ = zeros(2), diagm(ones(2))\n\n    x₀ = rand(rg, MvNormal(m₀, P₀))\n\n\n    # store measurements and states\n\n    yclean = Array{Vector{Float64},1}(undef, T)\n\n    y = Array{Vector{Float64},1}(undef, T)\n\n    x = Array{Vector{Float64},1}(undef, T)\n\n    # first state\n\n    x[1]      = A * x₀\n\n    y[1]      = rand(rg, MvNormal(H * x[1], R))\n\n    yclean[1] = H * x₀\n\n\n    for k in 2:T\n\n        x[k] = rand(rg, MvNormal(A * x[k-1], Q)) # (4.32)\n\n        yclean[k] = H * x[k]\n\n        y[k] = rand(rg, MvNormal(H * (x[k]), R)) # (4.33)\n\n    end\n\n    return yclean, y, x, A, H, Q, R, m₀, P₀\n\nend\n\n\nfunction runExample_4_2(seed = 1)\n\n    # Simulate data\n\n    yclean, y, x, A, H, Q, R, m₀, P₀ = Example_4_2(seed=seed)\n\n\n    # Inference\n\n    μfilter, Σfilter = filteringrecursion(y; A = A, H = H, Q = Q, R = R, m₀ = m₀, P₀ = P₀)\n\n    μsmooth, Σsmooth = smoothingrecursion(y; A = A, H = H, Q = Q, R = R, m = μfilter, P = Σfilter)\n\n\n    # collect positions\n\n    truepositions = reduce(hcat, [xₖ[1:2] for xₖ in x])\n\n    filtpositions = reduce(hcat, [xₖ[1:2] for xₖ in μfilter])\n\n    smoopositions = reduce(hcat, [xₖ[1:2] for xₖ in μsmooth])\n\n\n    # plot positions\n\n    figure(1); cla()\n\n    plot(truepositions[1,:], \"-\", label = \"true\")\n\n    plot(filtpositions[1,:], \"-\", label = \"filter\")\n\n    plot(smoopositions[1,:], \"-\", label = \"smoother\")\n\n    legend()\n\n    nothing\n\nend\n", "meta": {"hexsha": "54c384cd167198e068cb72cf189cebacf5b9015f", "size": 1850, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Example_4_2.jl", "max_stars_repo_name": "ngiann/StateSpaceStudy.jl", "max_stars_repo_head_hexsha": "249206cca241b672dbe44d0b24fdafe7d6624001", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Example_4_2.jl", "max_issues_repo_name": "ngiann/StateSpaceStudy.jl", "max_issues_repo_head_hexsha": "249206cca241b672dbe44d0b24fdafe7d6624001", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Example_4_2.jl", "max_forks_repo_name": "ngiann/StateSpaceStudy.jl", "max_forks_repo_head_hexsha": "249206cca241b672dbe44d0b24fdafe7d6624001", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0721649485, "max_line_length": 98, "alphanum_fraction": 0.5772972973, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8774767746654976, "lm_q1q2_score": 0.7938098382511822}}
{"text": "# 'cstrt_tamvakis_ngon' provides the vertices coordinates (a,b) of the\r\n# Tamvakis n-gon\r\n# Please, cite...\r\n#   N. K. Tamvakis. On the perimeter and the area of the convex polygon of\r\n#   a given diameter. Bull. Greek Math. Soc, 28: 115-132, 1987.\r\nfunction cstrt_tamvakis_ngon(n)\r\nif n>=3\r\n    a = zeros(n-1); b = zeros(n-1);\r\n    if mod(n,3) == 0\r\n        a[Int(n/3)] = 1/2; a[Int(2*n/3)] = -a[Int(n/3)];\r\n        b[Int(n/3)] = sqrt(3)/2; b[Int(2*n/3)] = b[Int(n/3)];\r\n        if n>3\r\n            for j = 1:Int((n-3)/3)\r\n                a[Int(n/3+j)] = cos(pi/3+j*pi/n);\r\n                b[Int(n/3+j)] = sin(pi/3+j*pi/n);\r\n                a[Int(2*n/3+j)] = a[Int(n/3)] + cos(pi+j*pi/n);\r\n                b[Int(2*n/3+j)] = b[Int(n/3)] + sin(pi+j*pi/n);\r\n                a[Int(n/3-j)] = -a[Int(2*n/3+j)];\r\n                b[Int(n/3-j)] = b[Int(2*n/3+j)];\r\n            end\r\n        end\r\n    elseif mod(n,3) == 1\r\n        a[Int((n-1)/3)] = 1/2; a[Int((2*n+1)/3)] = -a[Int((n-1)/3)];\r\n        b[Int((n-1)/3)] = sqrt(3)/2; b[Int((2*n+1)/3)] = b[Int((n-1)/3)];\r\n        for j = 1:Int((n-1)/3)\r\n            a[Int((n-1)/3+j)] = cos(pi/3+j*pi/(n+2));\r\n            b[Int((n-1)/3+j)] = sin(pi/3+j*pi/(n+2));\r\n        end\r\n        if n>4\r\n            for j = 1:Int((n-4)/3)\r\n                a[Int((2*n+1)/3+j)] = a[Int((n-1)/3)] + cos(pi+j*pi/(n-1));\r\n                b[Int((2*n+1)/3+j)] = b[Int((n-1)/3)] + sin(pi+j*pi/(n-1));\r\n                a[Int((n-1)/3-j)] = -a[Int((2*n+1)/3+j)];\r\n                b[Int((n-1)/3-j)] = b[Int((2*n+1)/3+j)];\r\n            end\r\n        end\r\n    else\r\n        a[Int((n+1)/3)] = 1/2; a[Int((2*n-1)/3)] = -a[Int((n+1)/3)];\r\n        b[Int((n+1)/3)] = sqrt(3)/2; b[Int((2*n-1)/3)] = b[Int((n+1)/3)];\r\n        for j = 1:Int((n-2)/3)\r\n            a[Int((2*n-1)/3+j)] = a[Int((n+1)/3)] + cos(pi+j*pi/(n+1));\r\n            b[Int((2*n-1)/3+j)] = b[Int((n+1)/3)] + sin(pi+j*pi/(n+1));\r\n            a[Int((n+1)/3-j)] = -a[Int((2*n-1)/3+j)];\r\n            b[Int((n+1)/3-j)] = b[Int((2*n-1)/3+j)];\r\n        end\r\n        if n>5\r\n            for j = 1:Int((n-5)/3)\r\n                a[Int((n+1)/3+j)] = cos(pi/3+j*pi/(n-2));\r\n                b[Int((n+1)/3+j)] = sin(pi/3+j*pi/(n-2));\r\n            end\r\n        end\r\n    end\r\n    return(a,b)\r\nend\r\nend", "meta": {"hexsha": "ed8dd60a20a8e0148af46ba0d85f6c150f9a72f0", "size": 2255, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "cstrt_ngon/cstrt_tamvakis_ngon.jl", "max_stars_repo_name": "cbingane/optigon", "max_stars_repo_head_hexsha": "f585de7a2b01ff1e7a15c566596a7ba8f77f782a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cstrt_ngon/cstrt_tamvakis_ngon.jl", "max_issues_repo_name": "cbingane/optigon", "max_issues_repo_head_hexsha": "f585de7a2b01ff1e7a15c566596a7ba8f77f782a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cstrt_ngon/cstrt_tamvakis_ngon.jl", "max_forks_repo_name": "cbingane/optigon", "max_forks_repo_head_hexsha": "f585de7a2b01ff1e7a15c566596a7ba8f77f782a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0, "max_line_length": 76, "alphanum_fraction": 0.3822616408, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741322079105, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7938034551983943}}
{"text": "using DataDrivenDiffEq\nusing ModelingToolkit\nusing OrdinaryDiffEq\nusing LinearAlgebra\nusing Plots\ngr()\n\n# Create a test problem\nfunction pendulum(u, p, t)\n    x = u[2]\n    y = -9.81sin(u[1]) - 0.1u[2]\n    return [x;y]\nend\n\nu0 = [0.2π; -1.0]\ntspan = (0.0, 40.0)\nprob = ODEProblem(pendulum, u0, tspan)\nsol = solve(prob)\n\nplot(sol)\n\n# Create the differential data\nDX = similar(sol[:,:])\nfor (i, xi) in enumerate(eachcol(sol[:,:]))\n    DX[:,i] = pendulum(xi, [], 0.0)\nend\n\n# Create a basis\n@variables u[1:2]\n\n# Lots of polynomials\npolys = [u[1]^0]\nfor i ∈ 1:3\n    for j ∈ 1:3\n        push!(polys, u[1]^i*u[2]^j)\n    end\nend\n\n# And some other stuff\nh = [1u[1];1u[2]; cos(u[1]); sin(u[1]); u[1]*u[2]; u[1]*sin(u[2]); u[2]*cos(u[2]); polys...]\n\nbasis = Basis(h, u)\n\n# Get the reduced basis via the sparse regression\nΨ = SInDy(sol[:,:], DX, basis, ϵ = 1e-10)\n\n# Transform into ODE System\nsys = ODESystem(Ψ)\n\n# Simulate\nestimator = ODEProblem(dynamics(Ψ), u0, tspan)\nsol_ = solve(estimator, saveat = sol.t)\n\n# Yeah! We got it right\nplot(sol, vars = (1,2))\nplot!(sol, vars = (1,2))\n\nnorm(sol-sol_) # ≈ 1.89e-13\n", "meta": {"hexsha": "be95e89933c317c73b02d5deb92816e3036284bc", "size": 1101, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/SInDy_Examples.jl", "max_stars_repo_name": "gabrevaya/DataDrivenDiffEq.jl", "max_stars_repo_head_hexsha": "f6fb2e062c6ca98908b44514b5fdf8af00f5a125", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/SInDy_Examples.jl", "max_issues_repo_name": "gabrevaya/DataDrivenDiffEq.jl", "max_issues_repo_head_hexsha": "f6fb2e062c6ca98908b44514b5fdf8af00f5a125", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/SInDy_Examples.jl", "max_forks_repo_name": "gabrevaya/DataDrivenDiffEq.jl", "max_forks_repo_head_hexsha": "f6fb2e062c6ca98908b44514b5fdf8af00f5a125", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6610169492, "max_line_length": 92, "alphanum_fraction": 0.6158038147, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224333, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7938034507105437}}
{"text": "#=\n\t\t\t\t\t\t\tMultiples of 3 and 5\n\n\tIf we list all the natural numbers below 10 that are multiples of 3 or 5, we\n\tget 3, 5, 6 and 9. The sum of these multiples is 23.\n\n\tFind the sum of all the multiples of 3 or 5 below 1000.\n\n\t\t\t\t\t\t\tAnswer: 233168\n=#\n\nfunction multiples(a::Int, b::Int, limit::Int)\n    array = []\n\n    for i in 2:limit-1\n        if 0 == i%a || 0 == i%b\n            push!(array, i)\n        end\n    end\n\n    return array\nend\n\nprintln(sum(multiples(3, 5, 1000)))\n", "meta": {"hexsha": "f3ad462d45e378276a161c4b38598d2127a11813", "size": 474, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/julia/1-25/problem_1.jl", "max_stars_repo_name": "Fazendaaa/project-euler", "max_stars_repo_head_hexsha": "80286ffe2db566872953d3021c3d6006f686c2cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-09-16T11:45:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-20T23:21:29.000Z", "max_issues_repo_path": "src/julia/1-25/problem_1.jl", "max_issues_repo_name": "Fazendaaa/project-euler", "max_issues_repo_head_hexsha": "80286ffe2db566872953d3021c3d6006f686c2cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/julia/1-25/problem_1.jl", "max_forks_repo_name": "Fazendaaa/project-euler", "max_forks_repo_head_hexsha": "80286ffe2db566872953d3021c3d6006f686c2cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.96, "max_line_length": 77, "alphanum_fraction": 0.5886075949, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907010924213, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7937549952007515}}
{"text": "export cg\n\nfunction cg(A::Union(AbstractMatrix, Function),b::Vector; \n\ttol::Real=1e-6,maxIter::Int64=1000,\n\tM::Union(AbstractMatrix, Function)=x->x ,x0::Vector=[],out::Int64=0)\n\n\n\tn = length(b)\n\tnb = norm(b)\n\t\n\t# allocate memory once\n\tAp = zeros(eltype(b),n) \n\n\tAf =  isa(A,Function) ? A : x->A_mul_B!(Ap, A, x) \n\tMf =  isa(M,Function) ? M : x->M\\x\n\t\n\tif isempty(x0)\n\t\tx0 = zeros(eltype(b),n)\n\t\tr = copy(b)\n\telse\n\t\tr = b - Af(x0)\n\tend\t\n\n\tz = Mf(r)\n\tp = copy(z)\t\n\t\t\t\n\tresvec = zeros(maxIter)\n\n\titer   = 1 \n\tflag   = 1\n\t\n\t@inbounds for iter=1:maxIter\n\t\tAp = Af(p)\n\t\tgamma = dot(r,z)\n\t\talpha = gamma/dot(p,Ap)\n\t\t\n\t\t# if A is ill-conditioned\n\t\tif alpha==Inf || alpha<0\n\t\t\tflag = 2; break\n\t\tend\n\t\t\n\t\tBLAS.axpy!(n,alpha,p,1,x0,1) # x = alpha*p+x\t\n\t\tBLAS.axpy!(n,-alpha,Ap,1,r,1) # r -= alpha*Ap \n\n\t\tresvec[iter] = norm(r)/nb\n\t\t# converge\n\t\tif  resvec[iter] <= tol\n\t\t\tflag = 0; break\n\t\tend\n\t\t\n\t\tz    = Mf(r)\n\t\tbeta = dot(z,r)/gamma\n\n\t\t# p = z + beta*p\n\t\tp = BLAS.scal!(n,beta,p,1)\n\t\tp = BLAS.axpy!(n,1.0,z,1,p,1)\n\tend\n\t# control output\n\tif out>=0\n\t\tif flag == 1\n\t\t\tprintln(\"Does not converge within maximum iterations.\")\n\t\telseif flag == 2\n\t\t\tprintln(\"Matrix A in cg has to be positive definite.\")\n\t\tend\n\tend\n\treturn x0,flag, resvec[iter],  resvec, iter\nend", "meta": {"hexsha": "a721352d879df1b3afd6606970e05b3c3eec4496", "size": 1250, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linalg/iterative/cg.jl", "max_stars_repo_name": "GaZ3ll3/Step_In_Julia", "max_stars_repo_head_hexsha": "66d3be0223f020e156c9c1c89c2ae98d473d525f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-03-12T18:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2016-04-21T13:41:19.000Z", "max_issues_repo_path": "src/linalg/iterative/cg.jl", "max_issues_repo_name": "GaZ3ll3/Step_In_Julia", "max_issues_repo_head_hexsha": "66d3be0223f020e156c9c1c89c2ae98d473d525f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/linalg/iterative/cg.jl", "max_forks_repo_name": "GaZ3ll3/Step_In_Julia", "max_forks_repo_head_hexsha": "66d3be0223f020e156c9c1c89c2ae98d473d525f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6567164179, "max_line_length": 69, "alphanum_fraction": 0.588, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.8723473697001441, "lm_q1q2_score": 0.7937549897826741}}
{"text": "\n\n\"\"\"\n    cubed_sphere_warp(::EquiangularSphereWarp, a, b, c)\n\nGiven points `(a, b, c)` on the surface of a cube, warp the points out to a\nspherical shell of radius `R` based on the equiangular gnomonic grid proposed by\n[Ronchi1996]\n\nReturns a tuple of (x1, x2, x3), where x1, x2, x3 are the corresponding coordinates on a sphere\nof radius R.\n\nThe \"Cubed Sphere\": A New Method for the Solution of Partial Differential Equations in Spherical Geometry\nC. RONCHI,*,1 R. IACONO,* AND P. S. PAOLUCCI†\nJOURNAL OF COMPUTATIONAL PHYSICS 124, 93–114 (1996)\n\nhttps://github.com/CliMA/ClimateMachine.jl/blob/master/src/Numerics/Mesh/Topologies.jl\n\"\"\"\nfunction cubed_sphere_warp(\n    ::EquiangularSphereWarp,\n    a::FT,\n    b::FT,\n    c::FT,\n) where {FT <: AbstractFloat}\n\n    R = max(abs(a), abs(b), abs(c))\n    function f(sR, ξ, η)\n        X, Y = tan(π * ξ / 4), tan(π * η / 4)\n        ζ1 = sR / sqrt(X^2 + Y^2 + 1)\n        ζ2, ζ3 = X * ζ1, Y * ζ1\n        ζ1, ζ2, ζ3\n    end\n\n    fdim = argmax(abs.((a, b, c)))\n    if fdim == 1 && a < 0\n        # (-R, *, *) : formulas for Face I from Ronchi, Iacono, Paolucci (1996)\n        #              but for us face IV of the developed net of the cube\n        x1, x2, x3 = f(-R, b / a, c / a)\n    elseif fdim == 2 && b < 0\n        # ( *,-R, *) : formulas for Face II from Ronchi, Iacono, Paolucci (1996)\n        #              but for us face V of the developed net of the cube\n        x2, x1, x3 = f(-R, a / b, c / b)\n    elseif fdim == 1 && a > 0\n        # ( R, *, *) : formulas for Face III from Ronchi, Iacono, Paolucci (1996)\n        #              but for us face II of the developed net of the cube\n        x1, x2, x3 = f(R, b / a, c / a)\n    elseif fdim == 2 && b > 0\n        # ( *, R, *) : formulas for Face IV from Ronchi, Iacono, Paolucci (1996)\n        #              but for us face III of the developed net of the cube\n        x2, x1, x3 = f(R, a / b, c / b)\n    elseif fdim == 3 && c > 0\n        # ( *, *, R) : formulas for Face V from Ronchi, Iacono, Paolucci (1996)\n        #              but for us face VI of the developed net of the cube\n        x3, x2, x1 = f(R, b / c, a / c)\n    elseif fdim == 3 && c < 0\n        # ( *, *,-R) : formulas for Face VI from Ronchi, Iacono, Paolucci (1996)\n        #              but for us face I of the developed net of the cube\n        x3, x2, x1 = f(-R, b / c, a / c)\n    else\n        error(\n            \"invalid case for cubed_sphere_warp(::EquiangularCubedSphere): $a, $b, $c\",\n        )\n    end\n    return x1, x2, x3\nend\n\n\"\"\"\n    cubed_sphere_warp(::EquidistantSphereWarp, a, b, c)\n\nGiven points `(a, b, c)` on the surface of a cube, warp the points out to a\nspherical shell of radius `R` based on the equidistant gnomonic grid outlined in\n[Rancic1996] and [Nair2005]\n\nReturns a tuple of (x1, x2, x3), where x1, x2, x3 are the corresponding coordinates on a sphere\nof radius R.\n\nThe \"Cubed Sphere\": A New Method for the Solution of Partial Differential Equations in Spherical Geometry\nC. RONCHI,*,1 R. IACONO,* AND P. S. PAOLUCCI†\nJOURNAL OF COMPUTATIONAL PHYSICS 124, 93–114 (1996)\n\nA Discontinuous Galerkin Transport Scheme on the Cubed Sphere\nRamachandran D. Nair1, Stephen J. Thomas1, and Richard D. Loft1\nhttps://doi.org/10.1175/MWR2890.1\n\nhttps://github.com/CliMA/ClimateMachine.jl/blob/master/src/Numerics/Mesh/Topologies.jl\n\"\"\"\nfunction cubed_sphere_warp(\n    ::EquidistantSphereWarp,\n    a::FT,\n    b::FT,\n    c::FT,\n) where {FT <: AbstractFloat}\n    R = max(abs(a), abs(b), abs(c))\n    r = hypot(a, b, c)\n    return R * a / r, R * b / r, R * c / r\nend\n", "meta": {"hexsha": "ffa4ff89266151ffda6d318add744bdb65797eb5", "size": 3551, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Meshes/warp_cube_to_sphere.jl", "max_stars_repo_name": "aviatesk/ClimaCore.jl", "max_stars_repo_head_hexsha": "44c9cf6b9d6dccaba648f8084fb2185a2c1fa3ce", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Meshes/warp_cube_to_sphere.jl", "max_issues_repo_name": "aviatesk/ClimaCore.jl", "max_issues_repo_head_hexsha": "44c9cf6b9d6dccaba648f8084fb2185a2c1fa3ce", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Meshes/warp_cube_to_sphere.jl", "max_forks_repo_name": "aviatesk/ClimaCore.jl", "max_forks_repo_head_hexsha": "44c9cf6b9d6dccaba648f8084fb2185a2c1fa3ce", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6082474227, "max_line_length": 105, "alphanum_fraction": 0.5967333146, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976794, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7936873348491577}}
{"text": "\n## Implement the Newton's method update to estimate sqrt(x)\n\"\"\" the function we are using here is y^2 - x, for which\nthe Newton update step is y - (y^2 - x)/(2y) \"\"\"\nfunction mysqrt(x; err = max(1.0,x)*eps(typeof(x/x)), maxiter=100)\n  y = one(typeof(x/x))\n  iter = 0\n  while abs(y^2 - x) >= err && iter <= maxiter\n    y = y - (y^2 - x)/(2*y)\n    iter += 1\n  end\n  return y\nend\n@show mysqrt(500)\n##\n@show mysqrt(0.25)\n", "meta": {"hexsha": "f738fad9d6099d755b3c45429200937686a58323", "size": 418, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3-unit-2-demos/sqrt-demo.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "3-unit-2-demos/sqrt-demo.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3-unit-2-demos/sqrt-demo.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 24.5882352941, "max_line_length": 66, "alphanum_fraction": 0.5956937799, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731169394881, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7936873345389328}}
{"text": "#= udemy.com code challenge\nfrom Prof. Mike X Cohen's course in Linear Algebra\nhttps://www.udemy.com/course/linear-algebra-theory-and-implementation\n\nObjective:\ncreate 2 4x6 matrices with random numbers\ncalculate dot products with corresponding columns\n=#\n\nusing LinearAlgebra\n\n# define 4x6 matrices - numbers range from -10 to 10\na = rand(-10:10, 4,6)\nb = rand(-10:10, 4,6)\n\n# display matrices\nprintln(\"Matrix A:\")\ndisplay(a)\nprintln(\"\\n\") # 2 newlines\nprintln(\"Matrix B:\")\ndisplay(b)\nprintln(\"\\n\")\n\n# size function generates a tuple of dimensions\n# in this case (4,6)\n# thus rows = 1st element of tuple (4)\n# cols = 2nd element of tuple (6)\nrows = size(a)[1] # unused in this example\n\ncols = size(a)[2]\n\n# Main for loop\nfor i in 1:cols\n  dp = dot(a[:, i], b[:, i])\n  println(\"Dot product of matrix column $i is $(dp)\")\nend\n", "meta": {"hexsha": "672cd0ee1ebbff249a19f3c532135d77b69dc49e", "size": 825, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear-algebra-code-challenges/01DotProductColumns.jl", "max_stars_repo_name": "jawuku/julia", "max_stars_repo_head_hexsha": "11ec183e6573d202590ffdb08c756b1ebcd38be8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-16T19:29:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T19:29:57.000Z", "max_issues_repo_path": "linear-algebra-code-challenges/01DotProductColumns.jl", "max_issues_repo_name": "jawuku/julia", "max_issues_repo_head_hexsha": "11ec183e6573d202590ffdb08c756b1ebcd38be8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear-algebra-code-challenges/01DotProductColumns.jl", "max_forks_repo_name": "jawuku/julia", "max_forks_repo_head_hexsha": "11ec183e6573d202590ffdb08c756b1ebcd38be8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2972972973, "max_line_length": 69, "alphanum_fraction": 0.7006060606, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7936849419527029}}
{"text": "#    Problem : \n#    *********\t \n#   The generalized Rosenbrock function.\n#\n#   Source: problem 5 in\n#   S. Nash,\n#   \"Newton-type minimization via the Lanczos process\",\n#\n#   SIF input: Nick Gould, Oct 1992.\n#              minor correction by Ph. Shott, Jan 1995.\n#\n#   classification SUR2-AN-V-0\n#\n#   Number of variables\n#\n#\n# Daniel Henderson, 08/2021   \n\n\n\nf = x -> begin\n\tN = lastindex(x)\n    return 1.0 + 100sum((x[i] - x[i-1]^2)^2 for i = 2:N) + sum((x[i] - 1.0)^2 for i = 2:N)\nend\n\ng! = (g, x) -> begin\n\tN = lastindex(x)\n\tg[1] = -400 * x[1] * (x[2] - x[1]^2)\n\tα    =  200 * (x[2] - x[1]^2)\n\tfor i in 2:N-1\n\t\tg[i] =  -400 * x[i] * (x[i+1] - x[i]^2) + 2 * (x[i] - 1.0) + α\n\t\tα    =   200 * (x[i+1] - x[i]^2)\n\tend\n\tg[N] = 200 * (x[N] - x[N-1]^2) + 2*(x[N] - 1.0)\n\treturn g\nend\n\nfg! = (g, x) -> begin\n\t@warn \"GENROSE fg! not implmented\"\n\t# N = lastindex(x)\n\t# fx = 0.0\n\t# g[1] = -400 * x[1] * (x[2] - x[1]^2)\n\t# α    =  200 * (x[2] - x[1]^2)\n\t# for i in 2:N-1\n\t# \tg[i] =  -400 * x[i] * (x[i+1] - x[i]^2) + 2 * (x[i] - 1.0) + α\n\t# \tα    =   200 * (x[i+1] - x[i]^2)\n\t# \tfx  += (x[i] - x[i-1]^2)^2 + (x[i] - 1.0)^2\n\t# end\n\t# fx  += (x[N] - x[N-1]^2)^2 + (x[N] - 1.0)^2\n\t# g[N] = 200 * (x[N] - x[N-1]^2) + 2*(x[N] - 1.0)\n\t# return fx,  g\t\nend\n\ninit = (n::Int=500) -> begin\n\tx0 = [j/(n+1) for j in 1:n]\n\treturn n, x0\nend\n\nTestSet[\"GENROSE\"] = UncProgram(\"GENROSE\",  f, g!, fg!, init)", "meta": {"hexsha": "1ac6d691f1ef65a38598476ebe9b0c7f69513c85", "size": 1383, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/programs/GENROSE.jl", "max_stars_repo_name": "danphenderson/UncNLPrograms.jl", "max_stars_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/programs/GENROSE.jl", "max_issues_repo_name": "danphenderson/UncNLPrograms.jl", "max_issues_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/programs/GENROSE.jl", "max_forks_repo_name": "danphenderson/UncNLPrograms.jl", "max_forks_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4406779661, "max_line_length": 90, "alphanum_fraction": 0.4584237166, "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632856092016, "lm_q2_score": 0.8558511543206819, "lm_q1q2_score": 0.7936849384632554}}
{"text": "# Continuation of ex 7.13, Least Squares WRM\n\nusing NumericalMethodsforEngineers\nusing Test\n\n@sym begin\n  LagrangePolynomial(xi_, yi_) := Module([N, sum, num, den],\n    begin\n      N = Length(xi)\n      sum = 0\n      For( i=1, i <= N, Increment(i),\n        begin\n          num = 1\n          den = 1\n          For( j=1, j <= N, Increment(j),\n            begin\n              If(j != i, num *= (x-xi[j]))\n              If(j != i, den *= (xi[i]-xi[j]))\n            end\n          )\n          sum += yi[i] * num/den\n        end\n      ),\n      Return(Simplify(sum))\n    end\n  )\nend\n\n@sym begin\n  ClearAll(xi, yi, N1, Y, Ydotdot, C11, ytilde1, ytilde2)\n  xi = [0, 1//2, 1]\n  yi = [0, a, 1]\n  Y(x_) := LagrangePolynomial(xi, yi)\n  Ydotdot(x_) = D(Y(x), x, 2)\n  R(x_) := Simplify(Expand(Ydotdot(x) - 3*x - 4*Y(x)))\n  R(x_) = Simplify(Expand(R(x) ./ (a => -C1/4)))\n  Rdot(x_) = D(R(x), C1)\n  C11 = Solve(Integrate(R(x)*Rdot(x), [x, 0, 1]), C1)[1]\n  SetJ(r, ToString(Simplify(R(x))))\n  SetJ(C1, ToString(C11[1][2]))\n  ytilde1 = Simplify(Y(x) ./ (a => -C1/4))\n  ytilde2 = Simplify(ytilde1 ./ C11)\n  SetJ(y, ToString(Simplify(Expand(ytilde2))));\nend\n\nprintln(\"\\n\\nExample 7.17: y'' = 3x + 4y, y(0)=0, y(1)=1\")\nprintln(\"by 1-point least squares Weighted Residual Method\")\n@sym Print(\"\\nY(x) = $(Y(x))\\n\")\n@sym Print(\"Y(x) = $(Simplify(Expand(Y(x) ./ (a => -C1/4))))\\n\")\n@sym Println(\"R(x) = $(R(x))\\n\")\n@sym Print(\"C1 = $(Solve(Integrate(R(x)*Rdot(x), [x, 0, 1]), C1)[1][1][2])\\n\")\n@eval ytilde_1pt_leastsquares(x) = $(Meta.parse(y))\n@eval rf_1pt_leastsquares(x, C1) = $(Meta.parse(r))\nprintln()\n\nrf_1pt_leastsquares_1(x) = rf_1pt_leastsquares(x, Meta.parse(C1))\nprintln()\n\n@test r == \"4 + 2C1 + x + 4C1*x - 8x^2 - 4C1*x^2\"\n@test y == \"(1/27)*x*(-8 + 35x)\"\n#@test (quadgk(rf_1pt_leastsquares_1, 0, 1))[1] < 5*eps()\n\n", "meta": {"hexsha": "b063f343a1859f6f33f19b8095c72c001d366513", "size": 1800, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch07/WRM/Ex.7.17.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "examples/ch07/WRM/Ex.7.17.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "examples/ch07/WRM/Ex.7.17.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 28.5714285714, "max_line_length": 78, "alphanum_fraction": 0.5377777778, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7936849316705614}}
{"text": "function sma(ta::TimeArray, n::Int)\n    tstamps = ta.timestamp[n:end]\n\n    vals = zeros(size(ta.values,1) - (n-1), size(ta.values,2))\n    for i in 1:size(ta.values,1) - (n-1)\n        for j in 1:size(ta.values,2)\n            vals[i,j] = mean(ta.values[i:i+(n-1),j])\n        end\n    end\n\n    cname = String[]\n    cols  = colnames(ta)\n    for c in 1:length(cols)\n        push!(cname, string(cols[c], \"_sma_\", n))\n    end\n\n    TimeArray(tstamps, vals, cname, ta.meta)\nend\n\nfunction ema(ta::TimeArray, n::Int; wilder=false)\n    k = if wilder\n        1 / n\n    else\n        2 / (n + 1)\n    end\n\n    tstamps = ta.timestamp[n:end]\n\n    vals    =  zeros(size(ta.values,1), size(ta.values,2))\n    # seed with first value with an sma value\n    vals[n,:] = sma(ta, n).values[1,:]\n\n    for i in n+1:size(ta.values,1)\n        for j in 1:size(ta.values,2)\n            vals[i,j] = ta.values[i,j] * k + vals[i-1, j] * (1-k)\n        end\n    end\n\n    cname   = String[]\n    cols    = colnames(ta)\n    for c in 1:length(cols)\n        push!(cname, string(cols[c], \"_ema_\", n))\n    end\n\n    TimeArray(tstamps, vals[n:length(ta),:], cname, ta.meta)\nend\n\nfunction kama(ta::TimeArray, n::Int=10, fn::Int=2, sn::Int=30)\n    vola = moving(sum, abs.(ta .- lag(ta)), n)\n    change = abs.(ta .- lag(ta, n))\n    er = safediv.(change, vola)  # Efficiency Ratio\n\n    # Smooth Constant\n    sc = (er .* (2 / (fn + 1) - 2 / (sn + 1)) .+ 2 / (sn + 1)).^2\n\n    cl = ta[n+1:end]\n    vals = similar(Array{Float64}, indices(cl.values))\n    # using simple moving average as initial kama\n    pri_kama = mean(ta[1:n].values, 1)\n\n    @assert length(cl) == length(sc)\n\n    for idx ∈ 1:length(cl)\n        vals[idx, :] =\n            pri_kama =\n            pri_kama .+ sc[idx].values .* (cl[idx].values .- pri_kama)\n    end\n\n    cols =\n    if length(ta.colnames) == 1\n        [\"kama\"]\n    else\n        [\"$c\\_kama\" for c in ta.colnames]\n    end\n\n    TimeArray(cl.timestamp, vals, cols)\nend\n\nfunction env(ta::TimeArray, n::Int; e::Float64 = 0.1)\n    tstamps = ta.timestamp[n:end]\n\n    s = sma(ta, n)\n\n    upper = s.values .* (1 + e)\n    lower = s.values .* (1 - e)\n\n    up_cname = string.(colnames(ta), \"_env_$n\", \"_up\")\n    lw_cname = string.(colnames(ta), \"_env_$n\", \"_low\")\n\n    u = TimeArray(tstamps, upper, up_cname, ta.meta)\n    l = TimeArray(tstamps, lower, lw_cname, ta.meta)\n\n    merge(l, u, :inner)\nend\n\n# Array dispatch for use by other algorithms\n\nfunction sma(a::Array, n::Int)\n    vals = zeros(size(a,1) - (n-1), size(a,2))\n\n    for i in 1:size(a,1) - (n-1)\n        for j in 1:size(a,2)\n            vals[i,j] = mean(a[i:i+(n-1),j])\n        end\n    end\n\n    vals\nend\n\nfunction ema(a::Array, n::Int; wilder=false)\n    k = if wilder\n        1 / n\n    else\n        2 / (n + 1)\n    end\n\n    vals = zeros(size(a,1), size(a,2))\n    # seed with first value with an sma value\n    vals[n,:] = sma(a, n)[1,:]\n\n    for i in n+1:size(a,1)\n        for j in 1:size(a,2)\n            vals[i,j] = a[i,j] * k + vals[i-1, j] * (1-k)\n        end\n    end\n\n    vals[n:end, :]\nend\n\nfunction env(a::AbstractArray, n::Int; e::Float64 = 0.1)\n    s = sma(a, n)\n\n    upper = @. s * (1 + e)\n    lower = @. s * (1 - e)\n\n    [lower upper]\nend\n\ndoc\"\"\"\n    sma(arr, n)\n\nSimple Moving Average\n\n```math\nSMA = \\frac{\\sum_i^n{P_i}}{n}\n```\n\"\"\"\nsma\n\ndoc\"\"\"\n    ema(arr, n, wilder=false)\n\nExponemtial Moving Average\n\nA.k.a. exponentially weighted moving average (EWMA)\n\n```math\n    \\text{Let } k \\text{denote the degree of weighting decrease}\n```\n\nIf parameter `wilder` is `true`, ``k = \\frac{1}{n}``,\nelse ``k = \\frac{2}{n + 1}``.\n\n```math\n    EMA_t = k \\times P_t + (1 - k) \\times EMA_{t - 1}\n```\n\"\"\"\nema\n\ndoc\"\"\"\n\nKaufman's Adaptive Moving Average\n\n**Arguments**:\n\n- `n`: period\n\n- `fn`: the fastest EMA constant\n\n- `sn`: the slowest EMA constant\n\n**Formula**:\n\n```math\n    \\begin{align*}\n        KAMA_t & = KAMA_{t-1} + SC \\times (Price - KAMA_{t-1}) \\\\\n        SC     & =\n            (ER \\times (\\frac{2}{fn + 1} - \\frac{2}{sn + 1}) + \\frac{2}{sn + 1})^2 \\\\\n        ER     & = \\frac{Change}{Volatility} \\\\\n        Change & = | Price - Price_{t-n} | \\\\\n        Volatility & = \\sum_{i}^{n} | Price_i - Price_{i-1} |\n    \\end{align*}\n```\n\"\"\"\nkama\n\ndoc\"\"\"\n\n    env(arr, n; e = 0.1)\n\nMoving Average Envelope\n\n```math\n  \\begin{align*}\n    \\text{Upper Envelope} & = \\text{n period SMA } \\times (1 + e) \\\\\n    \\text{Lower Envelope} & = \\text{n period SMA } \\times (1 - e)\n  \\end{align*}\n```\n\n**Arguments**\n\n- `e`: the envelope, `0.1` implies the `10%` envelope.\n\n**Reference**\n\n- [TradingView](https://www.tradingview.com/wiki/Envelope_(ENV))\n\"\"\"\nenv\n", "meta": {"hexsha": "cbcb522e399936fd30c607f3b892a3ba6f0b1182", "size": 4569, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/movingaverages.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/MarketTechnicals.jl-4f8c86c6-9e40-5506-9807-98571cb48bc8", "max_stars_repo_head_hexsha": "168ab386e9e368e13a908642dedb4c51c82a642b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/movingaverages.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/MarketTechnicals.jl-4f8c86c6-9e40-5506-9807-98571cb48bc8", "max_issues_repo_head_hexsha": "168ab386e9e368e13a908642dedb4c51c82a642b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/movingaverages.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/MarketTechnicals.jl-4f8c86c6-9e40-5506-9807-98571cb48bc8", "max_forks_repo_head_hexsha": "168ab386e9e368e13a908642dedb4c51c82a642b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8630136986, "max_line_length": 85, "alphanum_fraction": 0.5366601007, "num_tokens": 1606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.865224073888819, "lm_q1q2_score": 0.7936723382476154}}
{"text": "##### Weighted var & std\n\n## var\n\"\"\"\n    varm(x::AbstractArray, w::AbstractWeights, m, [dim]; corrected=false)\n\nCompute the variance of a real-valued array `x` with a known mean `m`, optionally\nover a dimension `dim`. Observations in `x` are weighted using weight vector `w`.\nThe uncorrected (when `corrected=false`) sample variance is defined as:\n```math\n\\\\frac{1}{\\\\sum{w}} \\\\sum_{i=1}^n {w_i\\\\left({x_i - m}\\\\right)^2 }\n```\nwhere ``n`` is the length of the input. The unbiased estimate (when `corrected=true`) of\nthe population variance is computed by replacing\n``\\\\frac{1}{\\\\sum{w}}`` with a factor dependent on the type of weights used:\n* `AnalyticWeights`: ``\\\\frac{1}{\\\\sum w - \\\\sum {w^2} / \\\\sum w}``\n* `FrequencyWeights`: ``\\\\frac{1}{\\\\sum{w} - 1}``\n* `ProbabilityWeights`: ``\\\\frac{n}{(n - 1) \\\\sum w}`` where ``n`` equals `count(!iszero, w)`\n* `Weights`: `ArgumentError` (bias correction not supported)\n\"\"\"\nvarm(v::RealArray, w::AbstractWeights, m::Real; corrected::DepBool=nothing) =\n    _moment2(v, w, m; corrected=depcheck(:varm, corrected))\n\n\"\"\"\n    var(x::AbstractArray, w::AbstractWeights, [dim]; mean=nothing, corrected=false)\n\nCompute the variance of a real-valued array `x`, optionally over a dimension `dim`.\nObservations in `x` are weighted using weight vector `w`.\nThe uncorrected (when `corrected=false`) sample variance is defined as:\n```math\n\\\\frac{1}{\\\\sum{w}} \\\\sum_{i=1}^n {w_i\\\\left({x_i - μ}\\\\right)^2 }\n```\nwhere ``n`` is the length of the input and ``μ`` is the mean.\nThe unbiased estimate (when `corrected=true`) of the population variance is computed by\nreplacing ``\\\\frac{1}{\\\\sum{w}}`` with a factor dependent on the type of weights used:\n* `AnalyticWeights`: ``\\\\frac{1}{\\\\sum w - \\\\sum {w^2} / \\\\sum w}``\n* `FrequencyWeights`: ``\\\\frac{1}{\\\\sum{w} - 1}``\n* `ProbabilityWeights`: ``\\\\frac{n}{(n - 1) \\\\sum w}`` where ``n`` equals `count(!iszero, w)`\n* `Weights`: `ArgumentError` (bias correction not supported)\n\"\"\"\nfunction var(v::RealArray, w::AbstractWeights; mean=nothing,\n                  corrected::DepBool=nothing)\n    corrected = depcheck(:var, corrected)\n\n    if mean == nothing\n        varm(v, w, Statistics.mean(v, w); corrected=corrected)\n    else\n        varm(v, w, mean; corrected=corrected)\n    end\nend\n\n## var along dim\n\nfunction varm!(R::AbstractArray, A::RealArray, w::AbstractWeights, M::RealArray,\n                    dim::Int; corrected::DepBool=nothing)\n    corrected = depcheck(:varm!, corrected)\n    rmul!(_wsum_centralize!(R, abs2, A, convert(Vector, w), M, dim, true),\n          varcorrection(w, corrected))\nend\n\nfunction var!(R::AbstractArray, A::RealArray, w::AbstractWeights, dims::Int;\n              mean=nothing, corrected::DepBool=nothing)\n    corrected = depcheck(:var!, corrected)\n\n    if mean == 0\n        varm!(R, A, w, Base.reducedim_initarray(A, dims, 0, eltype(R)), dims;\n                   corrected=corrected)\n    elseif mean == nothing\n        varm!(R, A, w, Statistics.mean(A, w, dims=dims), dims; corrected=corrected)\n    else\n        # check size of mean\n        for i = 1:ndims(A)\n            dA = size(A,i)\n            dM = size(mean,i)\n            if i == dims\n                dM == 1 || throw(DimensionMismatch(\"Incorrect size of mean.\"))\n            else\n                dM == dA || throw(DimensionMismatch(\"Incorrect size of mean.\"))\n            end\n        end\n        varm!(R, A, w, mean, dims; corrected=corrected)\n    end\nend\n\nfunction varm(A::RealArray, w::AbstractWeights, M::RealArray, dim::Int;\n                   corrected::DepBool=nothing)\n    corrected = depcheck(:varm, corrected)\n    varm!(similar(A, Float64, Base.reduced_indices(axes(A), dim)), A, w, M,\n               dim; corrected=corrected)\nend\n\nfunction var(A::RealArray, w::AbstractWeights, dim::Int; mean=nothing,\n                  corrected::DepBool=nothing)\n    corrected = depcheck(:var, corrected)\n    var!(similar(A, Float64, Base.reduced_indices(axes(A), dim)), A, w, dim;\n         mean=mean, corrected=corrected)\nend\n\n## std\n\"\"\"\n    stdm(x::AbstractArray, w::AbstractWeights, m, [dim]; corrected=false)\n\nCompute the standard deviation of a real-valued array `x` with a known mean `m`,\noptionally over a dimension `dim`. Observations in `x` are weighted using weight vector `w`.\nThe uncorrected (when `corrected=false`) sample standard deviation is defined as:\n```math\n\\\\sqrt{\\\\frac{1}{\\\\sum{w}} \\\\sum_{i=1}^n {w_i\\\\left({x_i - m}\\\\right)^2 }}\n```\nwhere ``n`` is the length of the input. The unbiased estimate (when `corrected=true`) of the\npopulation standard deviation is computed by replacing ``\\\\frac{1}{\\\\sum{w}}`` with a factor\ndependent on the type of weights used:\n* `AnalyticWeights`: ``\\\\frac{1}{\\\\sum w - \\\\sum {w^2} / \\\\sum w}``\n* `FrequencyWeights`: ``\\\\frac{1}{\\\\sum{w} - 1}``\n* `ProbabilityWeights`: ``\\\\frac{n}{(n - 1) \\\\sum w}`` where ``n`` equals `count(!iszero, w)`\n* `Weights`: `ArgumentError` (bias correction not supported)\n\"\"\"\nstdm(v::RealArray, w::AbstractWeights, m::Real; corrected::DepBool=nothing) =\n    sqrt(varm(v, w, m, corrected=depcheck(:stdm, corrected)))\n\n\"\"\"\n    std(x::AbstractArray, w::AbstractWeights, [dim]; mean=nothing, corrected=false)\n\nCompute the standard deviation of a real-valued array `x`,\noptionally over a dimension `dim`. Observations in `x` are weighted using weight vector `w`.\nThe uncorrected (when `corrected=false`) sample standard deviation is defined as:\n```math\n\\\\sqrt{\\\\frac{1}{\\\\sum{w}} \\\\sum_{i=1}^n {w_i\\\\left({x_i - μ}\\\\right)^2 }}\n```\nwhere ``n`` is the length of the input and ``μ`` is the mean.\nThe unbiased estimate (when `corrected=true`) of the population standard deviation is\ncomputed by replacing ``\\\\frac{1}{\\\\sum{w}}`` with a factor dependent on the type of\nweights used:\n* `AnalyticWeights`: ``\\\\frac{1}{\\\\sum w - \\\\sum {w^2} / \\\\sum w}``\n* `FrequencyWeights`: ``\\\\frac{1}{\\\\sum{w} - 1}``\n* `ProbabilityWeights`: ``\\\\frac{n}{(n - 1) \\\\sum w}`` where ``n`` equals `count(!iszero, w)`\n* `Weights`: `ArgumentError` (bias correction not supported)\n\"\"\"\nstd(v::RealArray, w::AbstractWeights; mean=nothing, corrected::DepBool=nothing) =\n    sqrt.(var(v, w; mean=mean, corrected=depcheck(:std, corrected)))\n\nstdm(v::RealArray, m::RealArray, dim::Int; corrected::DepBool=nothing) =\n    sqrt!(varm(v, m, dims=dim, corrected=depcheck(:stdm, corrected)))\n\nstdm(v::RealArray, w::AbstractWeights, m::RealArray, dim::Int;\n          corrected::DepBool=nothing) =\n    sqrt.(varm(v, w, m, dim; corrected=depcheck(:stdm, corrected)))\n\nstd(v::RealArray, w::AbstractWeights, dim::Int; mean=nothing,\n         corrected::DepBool=nothing) =\n    sqrt.(var(v, w, dim; mean=mean, corrected=depcheck(:std, corrected)))\n\n##### Fused statistics\n\"\"\"\n    mean_and_var(x, [w::AbstractWeights], [dim]; corrected=false) -> (mean, var)\n\nReturn the mean and standard deviation of collection `x`. If `x` is an `AbstractArray`,\n`dim` can be specified as a tuple to compute statistics over these dimensions.\nA weighting vector `w` can be specified to weight the estimates.\nFinally, bias correction is be applied to the variance calculation if `corrected=true`.\nSee [`var`](@ref) documentation for more details.\n\"\"\"\nfunction mean_and_var(x; corrected::Bool=true)\n    m = mean(x)\n    v = varm(x, m; corrected=corrected)\n    m, v\nend\n\n\"\"\"\n    mean_and_std(x, [w::AbstractWeights], [dim]; corrected=false) -> (mean, std)\n\nReturn the mean and standard deviation of collection `x`. If `x` is an `AbstractArray`,\n`dim` can be specified as a tuple to compute statistics over these dimensions.\nA weighting vector `w` can be specified to weight the estimates.\nFinally, bias correction is applied to the\nstandard deviation calculation if `corrected=true`.\nSee [`std`](@ref) documentation for more details.\n\"\"\"\nfunction mean_and_std(x; corrected::Bool=true)\n    m = mean(x)\n    s = stdm(x, m; corrected=corrected)\n    m, s\nend\n\nfunction mean_and_var(x::RealArray, w::AbstractWeights; corrected::DepBool=nothing)\n    m = mean(x, w)\n    v = varm(x, w, m; corrected=depcheck(:mean_and_var, corrected))\n    m, v\nend\nfunction mean_and_std(x::RealArray, w::AbstractWeights; corrected::DepBool=nothing)\n    m = mean(x, w)\n    s = stdm(x, w, m; corrected=depcheck(:mean_and_std, corrected))\n    m, s\nend\n\n\nfunction mean_and_var(x::RealArray, dim::Int; corrected::Bool=true)\n    m = mean(x, dims = dim)\n    v = varm(x, m, dims = dim, corrected=corrected)\n    m, v\nend\nfunction mean_and_std(x::RealArray, dim::Int; corrected::Bool=true)\n    m = mean(x, dims = dim)\n    s = stdm(x, m, dim; corrected=corrected)\n    m, s\nend\n\n\nfunction mean_and_var(x::RealArray, w::AbstractWeights, dims::Int;\n                      corrected::DepBool=nothing)\n    m = mean(x, w, dims=dims)\n    v = varm(x, w, m, dims; corrected=depcheck(:mean_and_var, corrected))\n    m, v\nend\nfunction mean_and_std(x::RealArray, w::AbstractWeights, dims::Int;\n                      corrected::DepBool=nothing)\n    m = mean(x, w, dims=dims)\n    s = stdm(x, w, m, dims; corrected=depcheck(:mean_and_std, corrected))\n    m, s\nend\n\n\n\n##### General central moment\nfunction _moment2(v::RealArray, m::Real; corrected=false)\n    n = length(v)\n    s = 0.0\n    for i = 1:n\n        @inbounds z = v[i] - m\n        s += z * z\n    end\n    varcorrection(n, corrected) * s\nend\n\nfunction _moment2(v::RealArray, wv::AbstractWeights, m::Real; corrected=false)\n    n = length(v)\n    s = 0.0\n    for i = 1:n\n        @inbounds z = v[i] - m\n        @inbounds s += (z * z) * wv[i]\n    end\n\n    varcorrection(wv, corrected) * s\nend\n\nfunction _moment3(v::RealArray, m::Real)\n    n = length(v)\n    s = 0.0\n    for i = 1:n\n        @inbounds z = v[i] - m\n        s += z * z * z\n    end\n    s / n\nend\n\nfunction _moment3(v::RealArray, wv::AbstractWeights, m::Real)\n    n = length(v)\n    s = 0.0\n    for i = 1:n\n        @inbounds z = v[i] - m\n        @inbounds s += (z * z * z) * wv[i]\n    end\n    s / sum(wv)\nend\n\nfunction _moment4(v::RealArray, m::Real)\n    n = length(v)\n    s = 0.0\n    for i = 1:n\n        @inbounds z = v[i] - m\n        s += abs2(z * z)\n    end\n    s / n\nend\n\nfunction _moment4(v::RealArray, wv::AbstractWeights, m::Real)\n    n = length(v)\n    s = 0.0\n    for i = 1:n\n        @inbounds z = v[i] - m\n        @inbounds s += abs2(z * z) * wv[i]\n    end\n    s / sum(wv)\nend\n\nfunction _momentk(v::RealArray, k::Int, m::Real)\n    n = length(v)\n    s = 0.0\n    for i = 1:n\n        @inbounds z = v[i] - m\n        s += (z ^ k)\n    end\n    s / n\nend\n\nfunction _momentk(v::RealArray, k::Int, wv::AbstractWeights, m::Real)\n    n = length(v)\n    s = 0.0\n    for i = 1:n\n        @inbounds z = v[i] - m\n        @inbounds s += (z ^ k) * wv[i]\n    end\n    s / sum(wv)\nend\n\n\n\"\"\"\n    moment(v, k, [wv::AbstractWeights], m=mean(v))\n\nReturn the `k`th order central moment of a real-valued array `v`, optionally\nspecifying a weighting vector `wv` and a center `m`.\n\"\"\"\nfunction moment(v::RealArray, k::Int, m::Real)\n    k == 2 ? _moment2(v, m) :\n    k == 3 ? _moment3(v, m) :\n    k == 4 ? _moment4(v, m) :\n    _momentk(v, k, m)\nend\n\nfunction moment(v::RealArray, k::Int, wv::AbstractWeights, m::Real)\n    k == 2 ? _moment2(v, wv, m) :\n    k == 3 ? _moment3(v, wv, m) :\n    k == 4 ? _moment4(v, wv, m) :\n    _momentk(v, k, wv, m)\nend\n\nmoment(v::RealArray, k::Int) = moment(v, k, mean(v))\nfunction moment(v::RealArray, k::Int, wv::AbstractWeights)\n    moment(v, k, wv, mean(v, wv))\nend\n\n\n##### Skewness and Kurtosis\n\n# Skewness\n# This is Type 1 definition according to Joanes and Gill (1998)\n\"\"\"\n    skewness(v, [wv::AbstractWeights], m=mean(v))\n\nCompute the standardized skewness of a real-valued array `v`, optionally\nspecifying a weighting vector `wv` and a center `m`.\n\"\"\"\nfunction skewness(v::RealArray, m::Real)\n    n = length(v)\n    cm2 = 0.0   # empirical 2nd centered moment (variance)\n    cm3 = 0.0   # empirical 3rd centered moment\n    for i = 1:n\n        @inbounds z = v[i] - m\n        z2 = z * z\n\n        cm2 += z2\n        cm3 += z2 * z\n    end\n    cm3 /= n\n    cm2 /= n\n    return cm3 / sqrt(cm2 * cm2 * cm2)  # this is much faster than cm2^1.5\nend\n\nfunction skewness(v::RealArray, wv::AbstractWeights, m::Real)\n    n = length(v)\n    length(wv) == n || throw(DimensionMismatch(\"Inconsistent array lengths.\"))\n    cm2 = 0.0   # empirical 2nd centered moment (variance)\n    cm3 = 0.0   # empirical 3rd centered moment\n\n    @inbounds for i = 1:n\n        x_i = v[i]\n        w_i = wv[i]\n        z = x_i - m\n        z2w = z * z * w_i\n        cm2 += z2w\n        cm3 += z2w * z\n    end\n    sw = sum(wv)\n    cm3 /= sw\n    cm2 /= sw\n    return cm3 / sqrt(cm2 * cm2 * cm2)  # this is much faster than cm2^1.5\nend\n\nskewness(v::RealArray) = skewness(v, mean(v))\nskewness(v::RealArray, wv::AbstractWeights) = skewness(v, wv, mean(v, wv))\n\n# (excessive) Kurtosis\n# This is Type 1 definition according to Joanes and Gill (1998)\n\"\"\"\n    kurtosis(v, [wv::AbstractWeights], m=mean(v))\n\nCompute the excess kurtosis of a real-valued array `v`, optionally\nspecifying a weighting vector `wv` and a center `m`.\n\"\"\"\nfunction kurtosis(v::RealArray, m::Real)\n    n = length(v)\n    cm2 = 0.0  # empirical 2nd centered moment (variance)\n    cm4 = 0.0  # empirical 4th centered moment\n    for i = 1:n\n        @inbounds z = v[i] - m\n        z2 = z * z\n        cm2 += z2\n        cm4 += z2 * z2\n    end\n    cm4 /= n\n    cm2 /= n\n    return (cm4 / (cm2 * cm2)) - 3.0\nend\n\nfunction kurtosis(v::RealArray, wv::AbstractWeights, m::Real)\n    n = length(v)\n    length(wv) == n || throw(DimensionMismatch(\"Inconsistent array lengths.\"))\n    cm2 = 0.0  # empirical 2nd centered moment (variance)\n    cm4 = 0.0  # empirical 4th centered moment\n\n    @inbounds for i = 1 : n\n        x_i = v[i]\n        w_i = wv[i]\n        z = x_i - m\n        z2 = z * z\n        z2w = z2 * w_i\n        cm2 += z2w\n        cm4 += z2w * z2\n    end\n    sw = sum(wv)\n    cm4 /= sw\n    cm2 /= sw\n    return (cm4 / (cm2 * cm2)) - 3.0\nend\n\nkurtosis(v::RealArray) = kurtosis(v, mean(v))\nkurtosis(v::RealArray, wv::AbstractWeights) = kurtosis(v, wv, mean(v, wv))\n", "meta": {"hexsha": "c5d0ae5c075078a7970f4b84bdfd3655677214ff", "size": 13919, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/moments.jl", "max_stars_repo_name": "logankilpatrick/StatsBase.jl", "max_stars_repo_head_hexsha": "c5328b186f721f9e320928356fb69cf579035240", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/moments.jl", "max_issues_repo_name": "logankilpatrick/StatsBase.jl", "max_issues_repo_head_hexsha": "c5328b186f721f9e320928356fb69cf579035240", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/moments.jl", "max_forks_repo_name": "logankilpatrick/StatsBase.jl", "max_forks_repo_head_hexsha": "c5328b186f721f9e320928356fb69cf579035240", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5971896956, "max_line_length": 93, "alphanum_fraction": 0.6203031827, "num_tokens": 4408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7936610139242524}}
{"text": "\r\nmutable struct MoschopoulosParameters{T}\r\n        θ₁::T\r\n        C::T\r\n        to_power::AbstractVector{T}\r\n        γ::AbstractVector{T}\r\n        ρ::T\r\n        δ::AbstractVector{T}\r\nend\r\nfunction MoschopoulosParameters(α,θ)\r\n    T = Base.promote_eltype(α,θ,[1.0])\r\n    α = T.(α)\r\n    θ = T.(θ)\r\n    δ = T.([1])\r\n    θ₁ = Base.minimum(θ)\r\n    C = exp(sum(α .* log.(θ₁ ./ θ)))\r\n    ρ = sum(α)\r\n    to_power = (-θ₁ ./ θ) .+1\r\n    γ = [sum(α .* to_power)] # gamma1\r\n    return MoschopoulosParameters(θ₁,C,to_power,γ,ρ,δ)\r\nend\r\nBase.eltype(::MoschopoulosParameters{T}) where T = T\r\n\r\n\r\n\r\n\"\"\"\r\n    UnivariateGammaConvolution(α,θ)\r\n\r\nConstructs a distribution that corresponds to the convolutions of Gamma(α[i],θ[i]) distributions.\r\nThe distribution can then be used through several methods,\r\nfollowing the Distributions.jl standard, to obtain pdf, cdf, random samples...\r\n\r\nThe pdf and cdf are handled by the Moshopoulos algorithm, and random samples by simply adding random gammas.\r\nThe code is type stable and handles any <:Real types, given by the parameters.\r\n\r\nTo fit the distribution, a loglikelyhood approach could be used. A more involved approach from Furman might be coded sometimes (but requires tanh-sinh integration and bigfloats...)\r\n\r\n\r\n# Examples\r\n```julia-repl\r\njulia> dist = UnivariateGammaConvolution([1,0.5, 3.7],[4,2, 10]);\r\njulia> sample = zeros(Float64,10);\r\njulia> Random.rand!(dist,sample);\r\njulia> pdf.((dist,),sample);\r\n```\r\n\"\"\"\r\nstruct UnivariateGammaConvolution{T<:Real} <: Distributions.ContinuousUnivariateDistribution where T\r\n    α::AbstractVector{T}\r\n    θ::AbstractVector{T}\r\n    P::MoschopoulosParameters{T}\r\nend\r\n\r\nn(x::UnivariateGammaConvolution) = length(x.α)\r\n\r\nfunction Base.show(io::IO, m::UnivariateGammaConvolution) \r\n    println(\"Univariate Gamma Convolutions with parametrisation:\")\r\n    display([Text.([\"α\" \"θ\"]); [m.α m.θ]])\r\nend\r\n\r\n# Constructors :\r\nUnivariateGammaConvolution(α::Real,θ::Real) = Distributions.Gamma(α,θ)\r\nfunction UnivariateGammaConvolution(α::AbstractVector{T1},θ::AbstractVector{T2}) where {T1 <: Real, T2 <: Real}\r\n\r\n    # Start by promoving alpha and theta to the same type :\r\n    T = Base.promote_eltype(α,θ,[1.0]) # At least float.\r\n    α = T.(α)\r\n    θ = T.(θ)\r\n    tol = eps(T) # Arbitrary fixed tolerence ! \r\n    \r\n    order = sortperm(θ)\r\n    n = length(θ)\r\n    θ = θ[order]\r\n    α = α[order]\r\n    for i in 1:n\r\n        if i < length(θ)\r\n            for j in (i+1):n\r\n                if j <= length(θ)\r\n                    if abs(θ[i] - θ[j]) <= tol\r\n                        new_α = α[i]+α[j]\r\n                        new_θ = (α[i]*θ[i]+α[j]*θ[j])/(new_α)\r\n                        α[i] = new_α\r\n                        θ[i] = new_θ\r\n                        deleteat!(α,j)\r\n                        deleteat!(θ,j)\r\n                        j = j-1\r\n                    end\r\n                end\r\n            end\r\n        end\r\n    end\r\n    to_be_kept = (α .> tol) .& (θ .> tol) .* (α.*θ .> tol)\r\n    α = α[to_be_kept]\r\n    θ = θ[to_be_kept]\r\n\r\n    if length(α) == 1\r\n        return Distributions.Gamma(α[1],θ[1])\r\n    end\r\n    return UnivariateGammaConvolution(α,θ,MoschopoulosParameters(α,θ))\r\nend\r\n\r\n#### Support\r\nDistributions.@distr_support UnivariateGammaConvolution 0.0 Inf\r\n\r\n#### Conversions\r\nBase.eltype(d::UnivariateGammaConvolution) = typeof(d.α[1])\r\nBase.convert(::Type{UnivariateGammaConvolution{T}}, d::UnivariateGammaConvolution{S}) where {T <: Real, S <: Real} = UnivariateGammaConvolution(T.(d.α), T.(d.θ))\r\n\r\n#### parameters\r\nshapes(d::UnivariateGammaConvolution) = d.α\r\nscales(d::UnivariateGammaConvolution) = d.θ\r\nrates(d::UnivariateGammaConvolution) = 1 / d.θ\r\n\r\n\r\n#### Statistics\r\nmean(d::UnivariateGammaConvolution) = sum(d.α .* d.θ)\r\nvar(d::UnivariateGammaConvolution) = sum(d.α .* d.θ .^ 2)\r\n\r\n\r\n#### Sampling\r\nfunction Base.rand(rng::Distributions.AbstractRNG,d::UnivariateGammaConvolution)\r\n    sum(rand.(rng,Distributions.Gamma.(d.α,d.θ)))\r\nend\r\n\r\n#### Characteristic functions: pdf, cdf, mgf, cf\r\n\r\n# Moshopoulos algorithm for pdf and cdf.\r\nfunction MoschopoulosAlgo!(d::UnivariateGammaConvolution,x::Real, which)\r\n\r\n    @assert(which in [\"pdf\",\"cdf\"], \"which should be etiher pdf or cdf\")\r\n    T = Base.eltype(d)\r\n    atol = eps(T)\r\n    rtol = T(0)\r\n    entry_type = typeof(x)\r\n    x = T(x)\r\n    if x < T(0)\r\n        return T(0)\r\n    end\r\n    k = 0\r\n    out = T(0)\r\n    while true\r\n        if length(d.P.δ) < k+1\r\n            # then compute the new deltas:\r\n            n = length(d.P.δ)\r\n            for k in n:(k+1)\r\n                pushfirst!(d.P.γ, sum(d.α .* d.P.to_power .^ (k+1)))\r\n                push!(d.P.δ,sum(d.P.γ[2:end] .* d.P.δ)/(k))\r\n            end\r\n        end\r\n        dist = Distributions.Gamma(T(d.P.ρ + k),T(d.P.θ₁))\r\n        if which == \"pdf\"\r\n            step = d.P.δ[k+1] * Distributions.pdf(dist,x)\r\n        elseif which == \"cdf\"\r\n            step = d.P.δ[k+1] * Distributions.cdf(dist,x)\r\n        end\r\n        # if ((!isfinite(step)) & (x > T(0)))\r\n        #     print(\"x = \", x)\r\n        #     print(d)\r\n        #     error(\"mince\")\r\n        # end\r\n        @assert(!((!isfinite(step)) & (x > T(0))),\"inf or nan append, the algorithm did not converge for x = $x\")\r\n        out += step\r\n        if isapprox(step,T(0),atol=atol,rtol=rtol)\r\n            break\r\n        end\r\n        k = k+1\r\n    end\r\n    out *= d.P.C\r\n    return entry_type(out)\r\nend\r\n\r\nDistributions.pdf(d::UnivariateGammaConvolution,x::Real) = MoschopoulosAlgo!(d,x,\"pdf\")\r\nDistributions.cdf(d::UnivariateGammaConvolution, x::Real) = MoschopoulosAlgo!(d,x,\"cdf\")\r\nDistributions.logpdf(d::UnivariateGammaConvolution, x::Real) = log(pdf(d,x))\r\nDistributions.mgf(d::UnivariateGammaConvolution, t::Real) = prod((1 - t .* d.θ) .^ (-d.α))\r\nDistributions.cf(d::UnivariateGammaConvolution, t::Real) = prod((1 - (im * t) .* d.θ) .^ (-d.α))\r\n", "meta": {"hexsha": "976397b9c7d3282c7820eb32e14ad1e7f4bd3a1b", "size": 5820, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/UnivariateGammaConvolution.jl", "max_stars_repo_name": "lrnv/ThorinDistributions.jl", "max_stars_repo_head_hexsha": "2d0a6c358878e38705e18b99ec5fa68552c9a2ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-02-23T15:28:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T17:58:25.000Z", "max_issues_repo_path": "src/UnivariateGammaConvolution.jl", "max_issues_repo_name": "lrnv/ThorinDistributions.jl", "max_issues_repo_head_hexsha": "2d0a6c358878e38705e18b99ec5fa68552c9a2ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2020-11-24T00:06:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T00:32:14.000Z", "max_forks_repo_path": "src/UnivariateGammaConvolution.jl", "max_forks_repo_name": "lrnv/ThorinDistributions.jl", "max_forks_repo_head_hexsha": "2d0a6c358878e38705e18b99ec5fa68552c9a2ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0681818182, "max_line_length": 181, "alphanum_fraction": 0.5802405498, "num_tokens": 1746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.7936327489162351}}
{"text": "using Distributions, LinearAlgebra, ForwardDiff, Seaborn, Pandas\n\n# Evaluates target distribution π(q)\nfunction π_q(q)\n    q₁ = q[1]\n    q₂ = q[2]\n    in_bound = (-π/2 < q₁ < π/2) & (-π/2 < q₂ < π/2)\n    return in_bound*(2/π * exp(-2*(q₁^2 + q₂^2)) + (sin(q₁*q₂)*sin(q₁)*cos(q₂))^2)\nend\n\n# Evaluates conditional probability π(p|q)\nfunction π_pq(p,q)\n    return pdf(MvNormal([0,0], 1.0*Matrix(I, 2, 2)), p)\nend\n\n# Evaluates Kinetic enery K(p,q)\nfunction K(p,q)\n    return -log(π_pq(p,q))\nend\n\n# Evaluates Potential energy V(q)\nfunction V(q)\n    return -log(π_q(q))\nend\n\n# Compute Hamiltonian at q,p\nfunction H(p,q)\n    return K(p,q) + V(q)\nend\n\n\n# Gets a trajectory of length L with n steps\nfunction get_trajectory(q,p,L,n,dV_dq)\n\n    # Step size\n    ϵ = L/n\n\n    q_trajectory = zeros(n,2)\n    p_trajectory = zeros(n,2)\n\n    q_trajectory[1,:] = q\n    p_trajectory[1,:] = p\n\n    for j=2:n\n        ψ = p_trajectory[j-1,:] - ϵ/2 * dV_dq(q_trajectory[j-1,:])\n        q_trajectory[j,:] = q_trajectory[j-1,:] + ϵ*ψ\n        p_trajectory[j,:] = ψ - ϵ/2*dV_dq(q_trajectory[j,:])\n    end\n\n    return q_trajectory, p_trajectory\nend\n\nfunction hmc_alg(q₀, p₀)\n    # Number of samples to return\n    n = 25000\n\n    q_samples = zeros(n,2)\n    p_samples = zeros(n,2)\n    q_samples[1,:] = q₀\n    p_samples[1,:] = p₀\n\n    trajectory_length = 1\n    trajectory_partitions = 5\n\n    # Gradient of V\n    dV_dq(x) = ForwardDiff.gradient(V, x)\n\n    for j=2:n\n\n        q = q_samples[j-1,:]\n        p = rand(MvNormal([0,0],1.0*Matrix(I, 2, 2)))\n        q_proposal_trajectory, p_proposal_trajectory =\n        get_trajectory(q, p, trajectory_length, trajectory_partitions, dV_dq)\n\n        # Proposal\n        q_L = q_proposal_trajectory[lastindex(q_proposal_trajectory)÷2,:]\n        p_L = p_proposal_trajectory[lastindex(p_proposal_trajectory)÷2,:]\n\n        # Compute acceptance probabilty\n        α = min(1, exp(H(p,q) - H(-p_L,q_L)))\n\n        if rand() < α\n            q_samples[j,:] = q_L\n            p_samples[j,:] = -p_L\n        else\n            q_samples[j,:] = q\n            p_samples[j,:] = p\n        end\n\n    end\n\n    return q_samples\nend\n\nsamples = hmc_alg([0,0],[1,1])\n\nusing PyCall\nusing Plots\n@pyimport seaborn as sns\npygui(true)\ndata = Pandas.DataFrame(Dict(:q₁=>samples[:,1], :q₂=>samples[:,2]))\nrc(\"axes\",facecolor = \"#f7ece2\")\nrc(\"figure\",facecolor = \"#f7ece2\")\nrc(\"savefig\",facecolor = \"#f7ece2\")\nsns.jointplot(x = \"q₁\", y = \"q₂\", data = data, s = 1, alpha = 0.18)\n\nusing SpecialFunctions\nq_values = -π/2:0.01:π/2\n\n# Plot of q₁ marginal\nfunction q₁_marginal(q)\n    return √(2/π)*erf(π/√2)*exp(-2q^2) +\n    sin(q)^2*(-π*q+π*q^3+sin(π*q))/(4*q^3-4*q)\nend\n\nq₁_values = [q₁_marginal(q) for q in q_values]\n\nPlots.plot(q_values, q₁_values, legend = false, grid = false, xlabel = L\"q_1\", ylabel = L\"\\pi_{q_1}(q_1)\", bg = RGB(247/255, 236/255, 226/255))\n\nPlots.savefig(\"hmc_ex_2_marginal_1_plot.svg\")\n\n# Plot of q₂ marginal\nfunction q₂_marginal(q)\n    return √(2/π)*erf(π/√2)*exp(-2q^2) +\n    1/4*cos(q)^2*(π + (1-2*q^2)*sin(π*q)/(q^3-q))\nend\n\nq₂_values = [q₂_marginal(q) for q in q_values]\n\nPlots.plot(q_values, q₂_values, legend = false, grid = false, xlabel = L\"q_2\", ylabel = L\"\\pi_{q_2}(q_2)\", bg = RGB(247/255, 236/255, 226/255))\nPlots.savefig(\"hmc_ex_2_marginal_2_plot.svg\")\n", "meta": {"hexsha": "136da85282de6384d12125b65eb55975701c51e5", "size": 3260, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/stochastic-approximations/code/hmc_ex_2.jl", "max_stars_repo_name": "seanrattana/courses", "max_stars_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-08-21T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T15:46:58.000Z", "max_issues_repo_path": "content/stochastic-approximations/code/hmc_ex_2.jl", "max_issues_repo_name": "seanrattana/courses", "max_issues_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-08-23T06:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-26T12:47:12.000Z", "max_forks_repo_path": "content/stochastic-approximations/code/hmc_ex_2.jl", "max_forks_repo_name": "seanrattana/courses", "max_forks_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-08-18T21:23:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T19:14:33.000Z", "avg_line_length": 24.696969697, "max_line_length": 143, "alphanum_fraction": 0.6153374233, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7936327383918516}}
{"text": "# Lets use black-box optimization to do regression!\n#\n# To run this, just do:\n#   julia regression_via_optimization.jl\n# from a command line after having installed BlackBoxOptim.\n#\n# The basic idea is that a regression problem is a problem of deciding\n# which set of coefficients (betas) minimize an objective function\n# that compares the dependent variable y to a model based on the betas and the\n# independent variables x.\n#\n# When implementing this, x will be a matrix d*n of floats where d is the dimension\n# of the problem and n is the number of examples/cases. Thus y is an array/vector\n# 1*n of floats and the coefficients is an array/vector (d+1)*1 of coefficients\n# where the first is the intercept (beta0) while the rest are the coefficients.\n#\n# We get different types of regression depending on which objective function\n# we select. Common to many of them is that they first calculate the deviances\n# between the model and the actual values the model should predict:\nfunction discrepancies(betas, x, y)\n  y' .- ( betas[1] + sum(broadcast(*, betas[2:end], x), 1) )\nend\n\n# Given this setup we can now create an objective function for\n# Ordinare Least Squares (OLS) regression. This is actually just the L2 norm:\nfunction ols_regression_objective(beta, x, y)\n  norm(discrepancies(beta, x, y), 2)\nend\n\n# And the L1 norm gives Least Absolute Deviations (LAD) (aka Robust regression) regression:\nfunction lad_regression_objective(beta, x, y)\n  norm(discrepancies(beta, x, y), 1)\nend\n\n# And we can do LASSO and Ridge regression by adding a penalty on large coefficients, but\n# note that these also take a lambda constant:\nfunction regularized_regression_objective(lambda, beta, x, y, p = 2, q = 1)\n  norm(discrepancies(beta, x, y), p) + lambda * norm(beta[2:end], q)\nend\n\n# By selecting p = 2 and q = 1 we get LASSO regression:\nfunction lasso_regression_objective(lambda, beta, x, y)\n  regularized_regression_objective(lambda, beta, x, y, 2, 1)\nend\n\n# and by selecting p = 2 and q = 2 we get Ridge regression:\nfunction ridge_regression_objective(lambda, beta, x, y)\n  regularized_regression_objective(lambda, beta, x, y, 2, 2)\nend\n\n# Ok, we're ready to do some regression. We need some data, lets start with\n# a way to generate data from models specified as julia functions. Lets start\n# with a simple model of 3 vars: X1 + 2*X2 - X3\nfunction m1(x)\n  x[1,:] + 2*x[2,:] - x[3,:]\nend\n\n# and we generate random input for it:\nx1 = rand(3, 100)\n# and calc the outputs:\ny1 = m1(x1)\n\n# We can now search for the coefficients that minimize the OLS objective\n# with a black-box optimization search like so (we allow coefficients to have\n# a min value of -5.0 and a max value of 5.0, and the search is for 4\n# coefficients, one intercept and three for each of the values of x):\nusing BlackBoxOptim\nolsresult = bboptimize(b -> ols_regression_objective(b, x1, y1); \n  SearchRange = (-10.0, 10.0), NumDimensions = 4, MaxSteps = 2e4)\n@show (best_fitness(olsresult), best_candidate(olsresult))\n\n# But the really nice thing is that we can easily consider other objectives such as the LAD:\nladresult = bboptimize(b -> lad_regression_objective(b, x1, y1); \n  SearchRange = (-10.0, 10.0), NumDimensions = 4, MaxSteps = 2e4)\n@show (best_fitness(ladresult), best_candidate(ladresult))\n\n# For regularized regression we can optimize for different values of lambda so\n# create a wrapper function that handles this:\nfunction regularized_opt(lambda, func, x, y, dims, its = 2e4)\n  bboptimize((b) -> func(lambda, b, x, y);\n    SearchRange = (-10.0, 10.0), NumDimensions = dims, MaxSteps = its)\nend\n\nlassores1 = regularized_opt(1, lasso_regression_objective, x1, y1, 4)\nlassores2 = regularized_opt(2, lasso_regression_objective, x1, y1, 4)\nlassores3 = regularized_opt(3, lasso_regression_objective, x1, y1, 4)\n\nridgeres1 = regularized_opt(1, ridge_regression_objective, x1, y1, 4)\nridgeres2 = regularized_opt(2, ridge_regression_objective, x1, y1, 4)\nridgeres3 = regularized_opt(3, ridge_regression_objective, x1, y1, 4)\n\n# Now lets create some support functions for printing models nicely.\nlinear_terms(num) = [@sprintf(\" * X%d\", i) for i in 1:num]\nsquared_terms(num) = [@sprintf(\" * X%d^2\", i) for i in 1:num]\nlinsq_terms(num) = vcat(linear_terms(num), squared_terms(num))\n\nfunction sprint_predicted_model(fitresult, terms = nothing, skipIfLower = 1e-5)\n  bestfit = best_candidate(fitresult)\n  if terms == nothing\n    terms = linear_terms(length(bestfit)-1)\n  end\n  if length(terms) < length(bestfit)\n    terms = vcat([\"\"], terms) # Put an empty term first which corresponds to intercept\n  end\n\n  signstr(value) = (value < 0.0) ? (@sprintf(\" - %.3f\", abs(value))) : (@sprintf(\" + %.3f\", value))\n\n  elems = Any[]\n  first_push = true\n  for i in 1:length(bestfit)\n    if abs(bestfit[i]) > skipIfLower\n      str = join([signstr(bestfit[i]), terms[i]])\n      if first_push\n        # Strip away leading sign since this it the first push\n        push!(elems, str[3:end])\n        first_push = false\n      else\n        push!(elems, str)\n      end\n    end\n  end\n\n  join(elems)\nend\n\n# Let's try a model which involves a squared terms:\n#   X1 + 4.13*X2*X2 - 3.14*X3\nfunction m2(x)\n  x[1,:] + (4.13 * x[2,:].^2) - (3.14 * x[3,:])\nend\n\n# and we generate random input for it:\nx2 = rand(3, 100)\n# and calc the outputs:\ny2 = m2(x2)\n\n# Before we regress we need to encode our beliefs about the general\n# structure of the model. Let's say we believe there are squared terms but we\n# do not know which ones. So we add one squared term per independent variable:\nx2m = zeros(3+3, 100)\nx2m[1:3,:] = x2\nx2m[4,:] = x2[1,:].^2\nx2m[5,:] = x2[2,:].^2\nx2m[6,:] = x2[3,:].^2\n\n# With this we can fit models:\nm2_olsres = bboptimize((b) -> ols_regression_objective(b, x2m, y2); \n  SearchRange = (-10.0, 10.0), NumDimensions = 7, MaxSteps = 5e4)\nm2_ladres = bboptimize((b) -> lad_regression_objective(b, x2m, y2); \n  SearchRange = (-10.0, 10.0), NumDimensions = 7, MaxSteps = 5e4)\nm2_lassores1 = regularized_opt(1, lasso_regression_objective, x2m, y2, 7, 5e4)\nm2_lassores2 = regularized_opt(2, lasso_regression_objective, x2m, y2, 7, 5e4)\nm2_lassores3 = regularized_opt(3, lasso_regression_objective, x2m, y2, 7, 5e4)\nm2_ridgeres1 = regularized_opt(1, ridge_regression_objective, x2m, y2, 7, 5e4)\nm2_ridgeres2 = regularized_opt(2, ridge_regression_objective, x2m, y2, 7, 5e4)\nm2_ridgeres3 = regularized_opt(3, ridge_regression_objective, x2m, y2, 7, 5e4)\n\n# And now lets print our models nicely so user can see the results...\n\nprintln(\"Model1 = 1.000 * X1 + 2.000 * X2 - 1.000 * X3\")\nprintln(\"OLS best fit: \", sprint_predicted_model(olsresult))\nprintln(\"LAD best fit: \", sprint_predicted_model(ladresult))\nprintln(\"LASSO best fit, lambda = 1: \", sprint_predicted_model(lassores1))\nprintln(\"LASSO best fit, lambda = 2: \", sprint_predicted_model(lassores2))\nprintln(\"LASSO best fit, lambda = 3: \", sprint_predicted_model(lassores3))\nprintln(\"Ridge best fit, lambda = 1: \", sprint_predicted_model(ridgeres1))\nprintln(\"Ridge best fit, lambda = 2: \", sprint_predicted_model(ridgeres2))\nprintln(\"Ridge best fit, lambda = 3: \", sprint_predicted_model(ridgeres3))\n\nterms = linsq_terms(3)\nprintln(\"\")\nprintln(\"Model2 = 1.000 * X1 - 3.140 * X3 + 4.130 * X2^2 \")\nprintln(\"OLS best fit: \", sprint_predicted_model(m2_olsres, terms))\nprintln(\"LAD best fit: \", sprint_predicted_model(m2_ladres, terms))\nprintln(\"LASSO best fit, lambda = 1: \", sprint_predicted_model(m2_lassores1, terms))\nprintln(\"LASSO best fit, lambda = 2: \", sprint_predicted_model(m2_lassores2, terms))\nprintln(\"LASSO best fit, lambda = 3: \", sprint_predicted_model(m2_lassores3, terms))\nprintln(\"Ridge best fit, lambda = 1: \", sprint_predicted_model(m2_ridgeres1, terms))\nprintln(\"Ridge best fit, lambda = 2: \", sprint_predicted_model(m2_ridgeres2, terms))\nprintln(\"Ridge best fit, lambda = 3: \", sprint_predicted_model(m2_ridgeres3, terms))\n\n# Conclusion: With black-box optimization you can easily fit regression models\n# from very different paradigms without having to implement very much code.\n", "meta": {"hexsha": "c98f99bf8b158b792038ce18b34c3d1f0c2b884e", "size": 7999, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/regression_via_optimization.jl", "max_stars_repo_name": "baggepinnen/BlackBoxOptim.jl", "max_stars_repo_head_hexsha": "ab909f3b47f11e05d3537adabbd543b34efd17e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-14T01:35:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-14T01:35:51.000Z", "max_issues_repo_path": "examples/regression_via_optimization.jl", "max_issues_repo_name": "tpapp/BlackBoxOptim.jl", "max_issues_repo_head_hexsha": "b36833ef59966c16ed026dc9bc2e3c165c79c909", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/regression_via_optimization.jl", "max_forks_repo_name": "tpapp/BlackBoxOptim.jl", "max_forks_repo_head_hexsha": "b36833ef59966c16ed026dc9bc2e3c165c79c909", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.472826087, "max_line_length": 99, "alphanum_fraction": 0.7260907613, "num_tokens": 2474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.85776809953619, "lm_q1q2_score": 0.7936327366233832}}
{"text": "\"\"\"\nCORDIC (COordinate Rotation DIgital Computer), a.k.a. Volder's algorithm, for computing `sin` and\n`cos` functions efficiently.\n\"\"\"\nmodule CORDIC\n\nexport cordic\n\n# Plagiarizing @njuffa's answer from https://stackoverflow.com/a/23097989/.\n#\n# These coefficients are obtained by Remez algorithm rather than from Taylor series.\nfunction arctan(x::Float64)::Float64\n    # argument reduction:\n    #\n    # arctan (-x) = -arctan(x)\n    # arctan (1/x) = 1/2 * pi - arctan (x), when x > 0\n    z = abs(x)\n    a = (z > 1.0) ? 1.0 / z : z\n\n    # evaluate minimax polynomial approximation\n    s = a * a  # a ^ 2\n    q = s * s  # a ^ 4\n    o = q * q  # a ^ 8\n\n    # use Estrin's scheme for low-order terms\n    p = fma(fma(fma(-0x1.53e1d2a25ff34p-16, s, 0x1.d3b63dbb65af4p-13),\n                q,\n                fma(-0x1.312788dde0801p-10, s, 0x1.f9690c82492dbp-9)),\n            o,\n            fma(fma(-0x1.2cf5aabc7cef3p-7, s, 0x1.162b0b2a3bfcep-6),\n                q,\n                fma(-0x1.a7256feb6fc5cp-6, s, 0x1.171560ce4a483p-5)))\n\n    # use Horner's scheme for high-order terms\n    p = fma(fma(fma(fma(fma(fma(fma(fma(fma(fma(fma(fma(p, s,\n            -0x1.4f44d841450e1p-5), s,\n            +0x1.7ee3d3f36bb94p-5), s,\n            -0x1.ad32ae04a9fd1p-5), s,\n            +0x1.e17813d66954fp-5), s,\n            -0x1.11089ca9a5bcdp-4), s,\n            +0x1.3b12b2db51738p-4), s,\n            -0x1.745d022f8dc5cp-4), s,\n            +0x1.c71c709dfe927p-4), s,\n            -0x1.2492491fa1744p-3), s,\n            +0x1.99999999840d2p-3), s,\n            -0x1.555555555544cp-2) * s, a, a)\n    # back substitution based on argument reduction\n    r = (z > 1.0) ? (0x1.921fb54442d18p+0 - p) : p\n    copysign(r, x)\nend\n\nANGLES = @. arctan(exp2(-(0:27)))\nK_VALUES = cumprod(@. 1.0 / sqrt(1.0 + exp2(-(0:2:50))))\n\n\"Returns a pair of `(sin(beta), cos(beta))` using CORDIC.\"\nfunction cordic(beta::Float64, n_iterations::Integer=25)::Tuple{Float64, Float64}\n    if beta < -pi / 2.0\n        return .-cordic(beta + pi, n_iterations)\n    elseif beta > pi / 2.0\n        return .-cordic(beta - pi, n_iterations)\n    end\n\n    v = [1.0, 0.0]\n    angle = ANGLES[1]\n\n    i = 0\n    while i < n_iterations\n        σ = sign(beta)\n        if σ == 0.0\n            break\n        end\n\n        x = v[1] - σ * ldexp(v[2], -i)\n        y = σ * ldexp(v[1], -i) + v[2]\n        v = [x, y]\n        beta -= σ * angle\n        i += 1\n\n        # +1 because the iterating variable starts from 0 (2 ^ 0, 2 ^ (-1), ...).\n        if i + 1 > length(ANGLES)\n            angle /= 2.0\n        else\n            angle = ANGLES[i + 1]\n        end\n    end\n\n    if i > 0\n        v *= K_VALUES[min(i, length(K_VALUES))]\n    end\n    (v[2], v[1])\nend\n\nconst flatten = Iterators.flatten\nfunction smoke()\n    X = range(-pi*4, stop=pi*4, length=800)\n    println(\"arctan error: \", max(@. abs(arctan(X) - atan(X))...))\n    println(\"cordic error: \", max(abs.(flatten(cordic.(X)) .- flatten(sincos.(X)))...))\nend\n\nend  # module\n", "meta": {"hexsha": "b3ee1bfb867d5904c787e237b5bee453450c78ee", "size": 2954, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CORDIC/cordic.jl", "max_stars_repo_name": "gyk/TrivialSolutions", "max_stars_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T05:51:37.000Z", "max_issues_repo_path": "CORDIC/cordic.jl", "max_issues_repo_name": "gyk/TrivialSolutions", "max_issues_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CORDIC/cordic.jl", "max_forks_repo_name": "gyk/TrivialSolutions", "max_forks_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2475247525, "max_line_length": 97, "alphanum_fraction": 0.5436696005, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7935620944904805}}
{"text": "###########\n# This gives an example of Gauss–Seidel\n#\n# It is _much_ more efficient to use BlockBandedMatrices.jl\n###########\n\n\nusing BandedMatrices, LazyArrays, LinearAlgebra\n\nfunction finitedifference_2d(n)\n    h = 1/n\n    D² = BandedMatrix(0 => Fill(-2,n), 1 => Fill(1,n-1), -1 => Fill(1,n-1))/h^2\n    D_xx = kron(D², Eye(n))\n    D_yy = kron(Eye(n), D²)\n    D_xx + D_yy\nend\n\nfunction gaussseidel(L, U, b, x=copy(b), M=5)\n    for _=1:M\n        @view(x[1:end-1]) .= Mul(U , @view(x[2:end]))\n        x[end] = 0\n        x .= b .- x\n        x .= Ldiv(L, x)\n    end\n    x\nend\n\nn = 400\nΔt = (1/n^2)/4; Δ = finitedifference_2d(n); A = I - Δt*Δ  # 160k x 160k discretization\n\nL = LowerTriangular(A)\nU = UpperTriangular(@view A[1:end-1,2:end])\n\nb = randn(size(A,1));\n@time u = A\\b; # 6s\nx = copy(b)\n@time gaussseidel(L,U, b, x, 20) # 1.6s\nnorm(x - u) # 6*10^(-10)\n", "meta": {"hexsha": "342ed74107614488998459f5fec0fabc153ab707", "size": 857, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/finitedifference_2d.jl", "max_stars_repo_name": "JuliaDocsForks/BandedMatrices.jl", "max_stars_repo_head_hexsha": "f7c40a47e23d3054e6bb18a30dc8c6e9b51a9583", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/finitedifference_2d.jl", "max_issues_repo_name": "JuliaDocsForks/BandedMatrices.jl", "max_issues_repo_head_hexsha": "f7c40a47e23d3054e6bb18a30dc8c6e9b51a9583", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/finitedifference_2d.jl", "max_forks_repo_name": "JuliaDocsForks/BandedMatrices.jl", "max_forks_repo_head_hexsha": "f7c40a47e23d3054e6bb18a30dc8c6e9b51a9583", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9743589744, "max_line_length": 86, "alphanum_fraction": 0.5600933489, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092412, "lm_q2_score": 0.8376199714402813, "lm_q1q2_score": 0.7935452889731863}}
{"text": "\nfunction _lobatto_legendre_fast(s, T)\n    c, b = FastGaussQuadrature.gausslobatto(s)\n    shift!(b,c)\n    QuadratureRule(2s-2, c, b, T)\nend\n\n\n\"\"\"\nLobatto-Legendre quadrature.\n\"\"\"\nfunction LobattoLegendreQuadrature(::Type{T}, s::Integer; IT=BigFloat, fast=false) where {T}\n    if s == 1\n        throw(ErrorException(\"Lobatto quadrature is not defined for one stage.\"))\n    end\n\n    if fast\n        return _lobatto_legendre_fast(s, T)\n    end\n\n    D(k) = Polynomials.derivative(Polynomial(IT[0, 1, -1])^(k-1), k-2)\n    P(k,x) = Polynomials.derivative(Polynomial(IT[-1, 0, 1])^k, k)(x) / factorial(k) / 2^k\n    c = sort(IT.(Polynomials.roots(D(s)))); c[begin] = 0; c[end] = 1;\n    b = [ 1 / ( s*(s-1) * P(s-1, 2c[i] - 1)^2 ) for i in 1:s ]\n    return QuadratureRule(2s-2, c, b, T)\nend\n\nLobattoLegendreQuadrature(s; kwargs...) = LobattoLegendreQuadrature(Float64, s; kwargs...)\n", "meta": {"hexsha": "85744af0f4871622f522689447c26baf902d7bc7", "size": 874, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lobatto_legendre.jl", "max_stars_repo_name": "JuliaGNI/QuadratureRules.jl", "max_stars_repo_head_hexsha": "188e1a1e85970803ae4456b5158a771a7aeeafd4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lobatto_legendre.jl", "max_issues_repo_name": "JuliaGNI/QuadratureRules.jl", "max_issues_repo_head_hexsha": "188e1a1e85970803ae4456b5158a771a7aeeafd4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-08T00:01:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T16:34:33.000Z", "max_forks_repo_path": "src/lobatto_legendre.jl", "max_forks_repo_name": "JuliaGNI/QuadratureRules.jl", "max_forks_repo_head_hexsha": "188e1a1e85970803ae4456b5158a771a7aeeafd4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1379310345, "max_line_length": 92, "alphanum_fraction": 0.6304347826, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092411, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7935452870530835}}
{"text": "\"\"\"\n    f₁(r, θ, ϕ, ψ)\n\nDefine a coordinate chart from 3-hyperspherical coordinates into Cartesian coordinates in ℝ⁴\nwith the given radius `r`, and angles: `θ`, `ϕ` and `ψ`. f₁: S³ ⟼ ℝ⁴.\n\"\"\"\nfunction f₁(r::Real, θ::Real, ϕ::Real, ψ::Real)\n    x₁ = r * cos(θ)\n    x₂ = r * sin(θ) * cos(ϕ)\n    x₃ = r * sin(θ) * sin(ϕ) * cos(ψ)\n    x₄ = r * sin(θ) * sin(ϕ) * sin(ψ)\n    ℝ⁴(x₁, x₂, x₃, x₄)\nend\n\n\n\"\"\"\n    f₂(α, ϕ₁, ϕ₂)\n\nDefine a coordinate chart from Hopf coordinates on 3-sphere into Cartesian coordinates in ℝ⁴\nwith the given angles `α`, `ϕ₁` and `ϕ₂`. f₂: S³ ⟼ ℝ⁴.\n\"\"\"\nfunction f₂(α::Real, ϕ₁::Real, ϕ₂::Real)\n    @assert(0 < α < π / 2, \"α ∈ (0, π/2)\")\n    @assert(0 ≤ ϕ₁ ≤ 2π, \"ϕ₁ ∈ [0, 2π]\")\n    @assert(0 ≤ ϕ₂ ≤ 2π, \"ϕ₂ ∈ [0, 2π]\")\n    x₁ = cos(ϕ₁) * sin(α)\n    x₂ = sin(ϕ₁) * sin(α)\n    x₃ = cos(ϕ₂) * cos(α)\n    x₄ = sin(ϕ₂) * cos(α)\n    ℝ⁴(x₁, x₂, x₃, x₄)\nend\n\n\n\"\"\"\n    f₃(α, ϕ₁, ϕ₂)\n\nDefine a coordinate chart from Hopf coordinates on 3-sphere into Cartesian coordinates in ℝ⁴\nwith the given angles `α`, `ϕ₁` and `ϕ₂`. f₃: S³ ⟼ ℝ⁴.\n\"\"\"\nfunction f₃(α::Real, ϕ₁::Real, ϕ₂::Real)\n    @assert(0 < α < π / 2, \"α ∈ (0, π/2)\")\n    @assert(0 ≤ ϕ₁ ≤ 2π, \"ϕ₁ ∈ [0, 2π]\")\n    @assert(0 ≤ ϕ₂ ≤ 4π, \"ϕ₂ ∈ [0, 4π]\")\n    x₁ = cos((ϕ₁ + ϕ₂) / 2) * sin(α)\n    x₂ = sin((ϕ₁ + ϕ₂) / 2) * sin(α)\n    x₃ = cos((ϕ₂ - ϕ₁) / 2) * cos(α)\n    x₄ = sin((ϕ₂ - ϕ₁) / 2) * cos(α)\n    ℝ⁴(x₁, x₂, x₃, x₄)\nend\n", "meta": {"hexsha": "b615b2b1c8d276e9499165d27b6e60620c2f82a8", "size": 1383, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geometry/metrics.jl", "max_stars_repo_name": "iamazadi/geometrizer", "max_stars_repo_head_hexsha": "73a97d879d06a1466ff3b966b2ea8e8a846d4c78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2020-03-28T05:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T22:16:31.000Z", "max_issues_repo_path": "src/geometry/metrics.jl", "max_issues_repo_name": "iamazadi/Porta", "max_issues_repo_head_hexsha": "73a97d879d06a1466ff3b966b2ea8e8a846d4c78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-15T12:36:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-15T12:36:59.000Z", "max_forks_repo_path": "src/geometry/metrics.jl", "max_forks_repo_name": "iamazadi/Porta", "max_forks_repo_head_hexsha": "73a97d879d06a1466ff3b966b2ea8e8a846d4c78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-09-13T20:28:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T03:31:59.000Z", "avg_line_length": 27.66, "max_line_length": 92, "alphanum_fraction": 0.5227765727, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522863, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7935452775595411}}
{"text": "clenshawcurtis_plan(μ) = length(μ) > 1 ? FFTW.plan_r2r!(μ, FFTW.REDFT00) : ones(μ)'\n\n\"\"\"\nCompute nodes and weights of the Clenshaw—Curtis quadrature rule with a Jacobi weight.\n\"\"\"\nclenshawcurtis{T<:AbstractFloat}(N::Int,α::T,β::T) = clenshawcurtis(N,α,β,clenshawcurtis_plan(zeros(T,N)))\nclenshawcurtis{T<:AbstractFloat}(N::Int,α::T,β::T,plan) = T[cospi(k/(N-one(T))) for k=0:N-1],clenshawcurtisweights(N,α,β,plan)\n\n\"\"\"\nCompute weights of the Clenshaw—Curtis quadrature rule with a Jacobi weight.\n\"\"\"\nclenshawcurtisweights{T<:AbstractFloat}(N::Int,α::T,β::T) = clenshawcurtisweights(N,α,β,clenshawcurtis_plan(zeros(T,N)))\nfunction clenshawcurtisweights{T<:AbstractFloat}(N::Int,α::T,β::T,plan)\n    μ = chebyshevjacobimoments1(N,α,β)\n    scale!(μ,inv(N-one(T)))\n    plan*μ\n    μ[1]/=2;μ[N]/=2\n    return μ\nend\n\n# Chebyshev-T coefficients to values at Clenshaw-Curtis nodes\n\napplyTN_plan(x) = length(x) > 1 ? FFTW.plan_r2r!(x, FFTW.REDFT00) : ones(x)'\n\napplyTN!{T<:AbstractFloat}(x::Vector{T}) = applyTN!(x,applyTN_plan(x))\nfunction applyTN!{T<:AbstractFloat}(x::Vector{T},plan)\n    x[1] *= 2; x[end] *=2\n    plan*x\n    scale!(x,half(T))\nend\napplyTN{T<:AbstractFloat}(x::Vector{T},plan) = applyTN!(copy(x),plan)\napplyTN{T<:AbstractFloat}(x::Vector{T}) = applyTN!(copy(x))\n\n# Values at Clenshaw-Curtis nodes to Chebyshev-T coefficients\n\napplyTNinv_plan(x) = length(x) > 1 ? FFTW.plan_r2r!(x, FFTW.REDFT00) : ones(x)'\n\napplyTNinv!{T<:AbstractFloat}(x::Vector{T}) = applyTNinv!(x,applyTNinv_plan(x))\nfunction applyTNinv!{T<:AbstractFloat}(x::Vector{T},plan)\n    plan*x\n    x[1] /= 2;x[end] /= 2\n    scale!(x,inv(length(x)-one(T)))\nend\napplyTNinv{T<:AbstractFloat}(x::Vector{T},plan) = applyTNinv!(copy(x),plan)\napplyTNinv{T<:AbstractFloat}(x::Vector{T}) = applyTNinv!(copy(x))\n\n# sin(nθ) coefficients to values at Clenshaw-Curtis nodes except ±1\n\napplyUN_plan(x) = length(x) > 0 ? FFTW.plan_r2r!(x, FFTW.RODFT00) : ones(x)'\n\napplyUN!{T<:AbstractFloat}(x::AbstractVector{T}) = applyUN!(x,applyUN_plan(x))\nfunction applyUN!{T<:AbstractFloat}(x::AbstractVector{T},plan)\n    plan*x\n    scale!(x,half(T))\nend\napplyUN{T<:AbstractFloat}(x::AbstractVector{T},plan) = applyUN!(copy(x),plan)\napplyUN{T<:AbstractFloat}(x::AbstractVector{T}) = applyUN!(copy(x))\n", "meta": {"hexsha": "efeaaac2bc9fbbfcb6a21c15378719f052fd77d1", "size": 2244, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/clenshawcurtis.jl", "max_stars_repo_name": "JuliaPackageMirrors/FastTransforms.jl", "max_stars_repo_head_hexsha": "eb9f1612f174cc1f7c3bc349deee94aedde77825", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/clenshawcurtis.jl", "max_issues_repo_name": "JuliaPackageMirrors/FastTransforms.jl", "max_issues_repo_head_hexsha": "eb9f1612f174cc1f7c3bc349deee94aedde77825", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/clenshawcurtis.jl", "max_forks_repo_name": "JuliaPackageMirrors/FastTransforms.jl", "max_forks_repo_head_hexsha": "eb9f1612f174cc1f7c3bc349deee94aedde77825", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6896551724, "max_line_length": 126, "alphanum_fraction": 0.6942959002, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556619, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7935441656767743}}
{"text": "\"\"\"\n**Inversedecay constructor**\n```julia\n    Inversedecay(; t0::Real=1, κ::Real=0.51)\n```\n\nAlgorithm:\n```math\n\\\\Delta x_t = (t+t_0)^{-\\\\kappa}g_t\n```\n\nSimple learning rate respecting the [Robbins-Monro conditions](https://en.wikipedia.org/wiki/Stochastic_approximation#Robbins%E2%80%93Monro_algorithm) for κ ∈ (0.5,1]\n\"\"\"\nmutable struct Inversedecay <: Optimizer\n    opt_type::String\n    t::Int64\n    t₀::Float64\n    κ::Float64\nend\n\nfunction Inversedecay(; t0::Real=1, κ::Real=0.51)\n    @assert t0 > 0.0 \"t0 must be greater than 0\"\n    @assert (κ > 0.5 || κ <= 1.0) \"κ argument is in (0.5,1]\"\n\n    Inversedecay(\"Inversedecay\", 0, t0, κ)\nend\n\nparams(opt::Inversedecay) = \"t₀=$(opt.t₀), κ=$(opt.κ)\"\n\nfunction update(opt::Inversedecay, g_t::AbstractArray{T}) where {T<:Real}\n    # update timestep\n    opt.t += 1\n    return (opt.t₀+opt.t)^(-opt.κ) * g_t\nend\n", "meta": {"hexsha": "a93f6ac7dbc792bd1dc865c61a564dffc6bb4507", "size": 855, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/InverseDecayOptimizer.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_stars_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2017-08-20T00:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T03:09:32.000Z", "max_issues_repo_path": "src/InverseDecayOptimizer.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_issues_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-11-19T22:38:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-25T20:33:14.000Z", "max_forks_repo_path": "src/InverseDecayOptimizer.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_forks_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-08-03T16:14:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:48:41.000Z", "avg_line_length": 24.4285714286, "max_line_length": 166, "alphanum_fraction": 0.6479532164, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947179030094, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7935441619989001}}
{"text": "export randomInv, RandomVectorSketch\n\n\"\"\"\nSolve TAx=Tb with T a random projector\n\"\"\"\nfunction randomInv(\n  stp::AbstractStopping;\n  is_zero_start::Bool = false,\n  k = 50,\n  random_func = random_matrix_1,\n  kwargs...,\n)\n  A, b = get_matrix(stp.pb), get_vector(stp.pb)\n  m = size(A, 1)\n\n  start!(stp)\n  k = Int(floor(m / 8))\n  T = random_func(k, m)\n  xk = T * A \\ T * b\n\n  return update_and_stop!(stp, x = xk)\nend\n\n\"\"\"\nRandom vector sketch\n\nSection 3.2 in Gower, R. M., & Richtárik, P. (2015).\nRandomized iterative methods for linear systems.\nSIAM Journal on Matrix Analysis and Applications, 36(4), 1660-1690.\n\"\"\"\nfunction RandomVectorSketch(\n  stp::AbstractStopping;\n  is_zero_start::Bool = false,\n  random_func = random_matrix_1,\n  kwargs...,\n)\n  A, b = get_matrix(stp.pb), get_vector(stp.pb)\n  m, n = size(A)\n  x0 = stp.current_state.x\n  xk = x0\n  stp.current_state.res = A * xk - b\n  OK = start!(stp)\n\n  while !OK\n    s = vec(random_func(1, m)')\n    As = A' * s\n    xk = As == 0 ? x0 : x0 - dot(s, stp.current_state.res) / dot(As, As) * As\n\n    update!(stp.current_state, x = xk)\n    stp.current_state.res = A * xk - b\n    OK = stop!(stp)\n    x0 = xk\n  end\n\n  return stp\nend\n", "meta": {"hexsha": "b0c99cadce2c04bbde96da27e745ee874b6b32d0", "size": 1178, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/random_methods.jl", "max_stars_repo_name": "tmigot/RandomLinearAlgebraSolvers.jl", "max_stars_repo_head_hexsha": "e4f53b533f8f4bed61d5dc40ce75ff74d95e0d28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-23T19:07:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T19:08:09.000Z", "max_issues_repo_path": "src/random_methods.jl", "max_issues_repo_name": "tmigot/RandomLinearAlgebraSolvers.jl", "max_issues_repo_head_hexsha": "e4f53b533f8f4bed61d5dc40ce75ff74d95e0d28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-11-26T17:38:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T01:21:44.000Z", "max_forks_repo_path": "src/random_methods.jl", "max_forks_repo_name": "tmigot/RandomLinearAlgebraSolvers.jl", "max_forks_repo_head_hexsha": "e4f53b533f8f4bed61d5dc40ce75ff74d95e0d28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6666666667, "max_line_length": 77, "alphanum_fraction": 0.6358234295, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7935441517044689}}
{"text": "\nfunction stencil1d(m::Int)\n\n    ic = Int(ceil(m/2.0))\n    M = zeros((m, m))\n    for i=1:m\n        for j=1:m\n            M[i, j] = (i - ic)^(j-1) / factorial(j-1)\n        end\n    end\n    return inv(M)\nend\n\n\nfunction periodic_projection(N, m)\n\n    js = [N-m+1:N...]\n    append!(js, [1:N...], [1:m...])\n\n    P = sparse([1:N...], [m+1:m+N...], ones(N), N, N+2*m)\n    PT = sparse([1:N+2*m...], js, ones(N+2*m), N+2*m, N)\n\n    return P, PT\nend\n\n\nfunction periodic_derivative_1d(n, m, N)\n\n    Nb = N + 2*m\n    D = sparse(zeros(Float64, (Nb, Nb)))\n    stencil = stencil1d(m)[n+1,:]\n    ic = Int(ceil(m/2.0))\n\n    for i=1:m\n        k = i - ic\n        vec = stencil[i] * ones(Nb - abs(k))\n        D += spdiagm(k => vec)\n    end\n\n    P, PT = periodic_projection(N, m)\n    return P * D * PT\nend\n\n\nfunction periodic_derivative(nx, ny, mx, my, Nx, Ny, dx, dy)\n\n    Dx = periodic_derivative_1d(nx, mx, Nx) / dx^nx\n    Dy = periodic_derivative_1d(ny, my, Ny) / dy^ny\n    return kron(Dy, Dx)\nend\n", "meta": {"hexsha": "184a07cfe3c3fdcd2620d802a5bce52e4e404b00", "size": 980, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experimental/periodic_derivatives.jl", "max_stars_repo_name": "JakeWillard/GDB.jl", "max_stars_repo_head_hexsha": "9d025feeb47995ac4a880919d801fd2256b826d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-07T19:52:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T19:52:36.000Z", "max_issues_repo_path": "experimental/periodic_derivatives.jl", "max_issues_repo_name": "JakeWillard/GDB.jl", "max_issues_repo_head_hexsha": "9d025feeb47995ac4a880919d801fd2256b826d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-21T00:18:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-21T00:18:46.000Z", "max_forks_repo_path": "experimental/periodic_derivatives.jl", "max_forks_repo_name": "JakeWillard/GDB.jl", "max_forks_repo_head_hexsha": "9d025feeb47995ac4a880919d801fd2256b826d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2156862745, "max_line_length": 60, "alphanum_fraction": 0.5102040816, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778012346834, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7935247218107262}}
{"text": "module firstTask\n\n# Global variable\ngoldenRatio = (1 + sqrt(5)) / 2\n\n\"\"\"\nFunction optimizes single variable function using golden section method (to find local minimum value in provided range)\n\"\"\"\nfunction goldenSection(f, a, b, tol = 1e-8)\n  # Make sure that entered range is correct\n  a = min(a, b)\n  b = max(a, b)\n\n  while abs(a - b) >= tol\n    # Calculate next 2 points\n    x1 = b - (b - a) / goldenRatio\n    x2 = a + (b - a) / goldenRatio\n    # Compare function values from calculated points and determine where minimum is located\n    if f(x1) < f(x2)\n      b = x2\n    else\n      a = x1\n    end\n  end\n  # Get the approximate value and return it\n  result = (a + b) / 2\n  resultY = f(result)\n  return (result, resultY)\nend\n\nexport goldenSection\n\nend # module\n", "meta": {"hexsha": "48bc5c5442c76106ea6827ec8cc8ae6b554d4ecb", "size": 762, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/firstTask.jl", "max_stars_repo_name": "KK-studia/firstTask", "max_stars_repo_head_hexsha": "0dfaa975168ab2788dd624a194d6ed1c24e08ea0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/firstTask.jl", "max_issues_repo_name": "KK-studia/firstTask", "max_issues_repo_head_hexsha": "0dfaa975168ab2788dd624a194d6ed1c24e08ea0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/firstTask.jl", "max_forks_repo_name": "KK-studia/firstTask", "max_forks_repo_head_hexsha": "0dfaa975168ab2788dd624a194d6ed1c24e08ea0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4117647059, "max_line_length": 119, "alphanum_fraction": 0.6456692913, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777987970316, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7935247157446564}}
{"text": "###############################################################################\n## Logistic Problem\n#    min_x  1/m * ∑_{i=1}^m log(1 + exp(-y_i dot(A_i, x))) + g(reg, x)\n#\n#    x : R^n\n#    y : R^m observations, *values -1 and 1*\n#    A : mxn matrix of samples\n\nmutable struct LogisticPb{Tr, Tm, Txman} <: CompositeProblem\n    A::Matrix{Float64}\n    y::Vector{Float64}\n    regularizer::Tr\n    n::Int64\n    x0::Txman\n    M_x0::Tm\n    λ₂::Float64\n    function LogisticPb(\n            A::Matrix{Float64},\n            y::Vector{Float64},\n            regularizer::Tr,\n            n::Int64,\n            x0::Txman,\n            M_x0::Tm,\n            λ₂::Float64\n        ) where {Tr, Tm, Txman}\n        @assert Set(y) ⊆ Set([-1.0, 1.0]) \"Logistic rhs vector shoudl take values -1.0, 1.0, here: $(Set(y)).\"\n        return new{Tr, Tm, Txman}(A, y, regularizer, n, x0, M_x0, λ₂)\n    end\nend\n\nproblem_dimension(pb::LogisticPb) = pb.n\n\n\n\"\"\"\n    logsig(t)\n\nCompute the logarithm of sigmoid `-log(1+exp(-t))` with higher precision than plain\nimplementation.\n\nReference:\n- F. Pedragosa's blog post http://fa.bianp.net/blog/2019/evaluate_logistic/\n\"\"\"\n@inline function logsig(t)\n    if t < -33.3\n        return t\n    elseif t <= -18\n        return t - exp(t)\n    elseif t <= 37\n        return -log1p(exp(-t))\n    else\n        return -exp(-t)\n    end\nend\n\n## f\n# 0th order\nfunction f(pb::LogisticPb, x)\n    m = size(pb.A, 1)\n\n    Ax = pb.A * x\n    fval = 0.0\n    @inbounds @simd for i in 1:m\n        fval -= logsig(pb.y[i] * Ax[i])\n    end\n\n    return fval / m + 0.5 * pb.λ₂ * norm(x, 2)^2\nend\n\n# 1st order\nσ(x) = 1/(1+exp(-x))\nfunction ∇f!(pb::LogisticPb, res, x)\n    m = size(pb.A, 1)\n\n    σyAx = pb.A * x\n    σyAx .*= -pb.y\n    σyAx .= σ.(σyAx)\n    res .= transpose(pb.A) * (σyAx .* pb.y)\n    res ./= -m\n    res .+= pb.λ₂ .* x\n\n    return res\nend\n\n# 2nd order\n∇σ(x) = σ(x) * σ(-x)\nfunction ∇²f_h!(pb::LogisticPb, res, x, h)\n    m = size(pb.A, 1)\n\n    yAx = -pb.y .* (pb.A * x)\n    Ah = pb.A * h\n\n    res .= transpose(pb.A) * (Ah .* ∇σ.(yAx))\n    res ./= m\n    res .+= pb.λ₂ .* h\n\n    return res\nend\n\n# conditioning\nfunction get_gradlips(pb::LogisticPb)\n    m = size(pb.A, 1)\n    return opnorm(pb.A)^2 / m + pb.λ₂\nend\n# get_μ_cvx(pb::LogisticPb) = (svdvals(pb.A)[end])^2\n", "meta": {"hexsha": "d8e957659b533a9b5ecf09d5949591c34864d099", "size": 2255, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/Logistic.jl", "max_stars_repo_name": "GillesBareilles/CompositeProblems.jl", "max_stars_repo_head_hexsha": "d5cc1b99a00bf61614af9a750fc93bf718d3151b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/Logistic.jl", "max_issues_repo_name": "GillesBareilles/CompositeProblems.jl", "max_issues_repo_head_hexsha": "d5cc1b99a00bf61614af9a750fc93bf718d3151b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/Logistic.jl", "max_forks_repo_name": "GillesBareilles/CompositeProblems.jl", "max_forks_repo_head_hexsha": "d5cc1b99a00bf61614af9a750fc93bf718d3151b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4761904762, "max_line_length": 110, "alphanum_fraction": 0.5179600887, "num_tokens": 835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620608291781, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7934466151890567}}
{"text": "# General vector utilities that may have application outside of MkCell.\n\n\n\"Calculate angle between two vectors (in radians)\"\nang(x,y) = acos(dot(x,y)/(norm(x)*norm(y)))\n\n\n\"\"\"Get lattice a, b, c from cell\"\"\"\ncell_abc(cell) = norm(cell[1,:]), norm(cell[2,:]), norm(cell[3,:])\n\n\"\"\"Get cell angles α, β, γ (in degrees) from a cell.\"\"\"\ncell_angles(cell) = tuple((ang(cell[p[1],:], cell[p[2],:])*180.0/π for p in [(2,3), (1,3), (1,2)])...)\n", "meta": {"hexsha": "1d487661935aca6f14745b2b66a889e6ac4a4320", "size": 434, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vecutils.jl", "max_stars_repo_name": "bocklund/MkCell.jl", "max_stars_repo_head_hexsha": "e6e51999f9051c9b58ac8ead3b1345a7f4e9d745", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/vecutils.jl", "max_issues_repo_name": "bocklund/MkCell.jl", "max_issues_repo_head_hexsha": "e6e51999f9051c9b58ac8ead3b1345a7f4e9d745", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vecutils.jl", "max_forks_repo_name": "bocklund/MkCell.jl", "max_forks_repo_head_hexsha": "e6e51999f9051c9b58ac8ead3b1345a7f4e9d745", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3846153846, "max_line_length": 102, "alphanum_fraction": 0.6198156682, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9597620573763839, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7934466082369224}}
{"text": "\"\"\"\n`LinearKernel([ρ=1.0,[c=0.0]])`\nThe linear kernel is a Mercer kernel given by\n```\n    κ(x,y) = ρ²xᵀy + c\n```\nWhere `c` is a real number\n\"\"\"\nstruct LinearKernel{Tr, Tc<:Real} <: Kernel{Tr}\n    transform::Tr\n    c::Tc\nend\n\nfunction LinearKernel(ρ::T=1.0, c::Real=zero(T)) where {T<:Real}\n    LinearKernel(ScaleTransform(ρ), c)\nend\n\nfunction LinearKernel(ρ::AbstractVector{T}, c::Real=zero(T)) where {T<:Real}\n    LinearKernel(ARDTransform(ρ), c)\nend\n\nLinearKernel(t::Transform) = LinearKernel(t, 0.0)\n\nparams(k::LinearKernel) = (params(transform(k)),k.c)\nopt_params(k::LinearKernel) = (opt_params(transform(k)),k.c)\n\n@inline kappa(κ::LinearKernel, xᵀy::T) where {T<:Real} = xᵀy + κ.c\n\nmetric(::LinearKernel) = DotProduct()\n\n\"\"\"\n`PolynomialKernel([ρ=1.0[,d=2.0[,c=0.0]]])`\nThe polynomial kernel is a Mercer kernel given by\n```\n    κ(x,y) = (ρ²xᵀy + c)^d\n```\nWhere `c` is a real number, and `d` is a shape parameter bigger than 1\n\"\"\"\nstruct PolynomialKernel{Tr,Tc<:Real,Td<:Real} <: Kernel{Tr}\n    transform::Tr\n    d::Td\n    c::Tc\n    function PolynomialKernel{Tr, Tc, Td}(transform::Tr, d::Td, c::Tc) where {Tr<:Transform, Td<:Real, Tc<:Real}\n        @check_args(PolynomialKernel, d, d >= one(Td), \"d >= 1\")\n        return new{Tr, Td, Tc}(transform,d, c)\n    end\nend\n\nfunction PolynomialKernel(ρ::Real=1.0, d::Td=2.0, c::Real=zero(Td)) where {Td<:Real}\n    PolynomialKernel(ScaleTransform(ρ), d, c)\nend\n\nfunction PolynomialKernel(ρ::AbstractVector{T}, d::Real=2.0, c::Real=zero(T₁)) where {T<:Real}\n    PolynomialKernel(ARDTransform(ρ), d, c)\nend\n\nfunction PolynomialKernel(t::Tr, d::Td=2.0, c::Tc=zero(eltype(Td))) where {Tr<:Transform, Td<:Real, Tc<:Real}\n    PolynomialKernel{Tr, Tc, Td}(t, d, c)\nend\n\nparams(k::PolynomialKernel) = (params(transform(k)),k.d,k.c)\nopt_params(k::PolynomialKernel) = (opt_params(transform(k)),k.d,k.c)\n\n@inline kappa(κ::PolynomialKernel, xᵀy::T) where {T<:Real} = (xᵀy + κ.c)^(κ.d)\n\nmetric(::PolynomialKernel) = DotProduct()\n", "meta": {"hexsha": "4c5c78febd38caa88a6da2f5c47f3e5d1b42992f", "size": 1960, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/polynomial.jl", "max_stars_repo_name": "IsakFalk/KernelFunctions.jl", "max_stars_repo_head_hexsha": "d629d2f8d26e31fa4a07d417d115416292aa7c62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/polynomial.jl", "max_issues_repo_name": "IsakFalk/KernelFunctions.jl", "max_issues_repo_head_hexsha": "d629d2f8d26e31fa4a07d417d115416292aa7c62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/polynomial.jl", "max_forks_repo_name": "IsakFalk/KernelFunctions.jl", "max_forks_repo_head_hexsha": "d629d2f8d26e31fa4a07d417d115416292aa7c62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2537313433, "max_line_length": 112, "alphanum_fraction": 0.6571428571, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7934263295916022}}
{"text": "\"\"\"\nModule: SymbolicDiff (Symbolic Operation for Arithmetic)\n\"\"\"\n\n\"\"\"\nseval(f, dvar, env, cache)\nReturn the first derivative of expr f with respect to dvar\n\"\"\"\n\nfunction seval(f, dvar::Symbol)\n    seval(f, dvar, globalenv, SymbolicCache())\nend\n\nfunction seval(f, dvar::Symbol, env::SymbolicEnv)\n    seval(f, dvar, env, SymbolicCache())\nend\n\nfunction seval(f, dvar::Symbol, cache::SymbolicCache)\n    seval(f, dvar, globalenv, cache)\nend\n\n###\n\nfunction seval(f, dvar::SymbolicVariable{Tv}) where Tv\n    seval(f, dvar.var)\nend\n\nfunction seval(f, dvar::SymbolicVariable{Tv}, env::SymbolicEnv) where Tv\n    seval(f, dvar.var, env)\nend\n\nfunction seval(f, dvar::SymbolicVariable{Tv}, cache::SymbolicCache) where Tv\n    seval(f, dvar.var, cache)\nend\n\nfunction seval(f, dvar::SymbolicVariable{Tv}, env::SymbolicEnv, cache::SymbolicCache) where Tv\n    seval(f, dvar.var, env, cache)\nend\n\n###\n\nfunction seval(f::SymbolicValue{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv\n    Tv(0)\nend\n\nfunction seval(f::SymbolicVariable{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv\n    f.var == dvar ? 1 : 0\nend\n\nfunction seval(f::AbstractNumberSymbolic{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv\n    (dvar in f.params) || return 0\n    get(cache, (f,dvar)) do\n        retval = _eval(Val(f.op), f, dvar, env, cache)\n        cache[(f,dvar)] = retval\n    end\nend\n\n\"\"\"\n_eval(::Val{xx}, dvar, f, env, cache)\n\nDispached function to evaluate the first derivative of f\n\"\"\"\n\nfunction _eval(::Val{:+}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv\n    args = [seval(x, dvar, env, cache) for x = f.args]\n    +(args...)\nend\n\nfunction _eval(::Val{:-}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv\n    args = [seval(x, dvar, env, cache) for x = f.args]\n    -(args...)\nend\n\nfunction _eval(::Val{:*}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv\n    args = [seval(x, env, cache) for x = f.args]\n    dargs = [seval(x, dvar, env, cache) for x = f.args]\n    ret = dargs[1]\n    s = args[1]\n    for i = 2:length(args)\n        ret *= args[i]\n        ret += s * dargs[i]\n        (i == length(args)) && break\n        s *= args[i]\n    end\n    ret\nend\n\nfunction _eval(::Val{:/}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv\n    x,y = [seval(x, env, cache) for x = f.args]\n    dx,dy = [seval(x, dvar, env, cache) for x = f.args]\n    (dx * y - x * dy) / y^2\nend\n\nfunction _eval(::Val{:^}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv\n    x,y = [seval(x, env, cache) for x = f.args]\n    dx,dy = [seval(x, dvar, env, cache) for x = f.args]\n    x^(y-1) * (x * log(x) * dy + y * dx)\nend\n\nfunction _eval(::Val{:exp}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv\n    x, = [seval(x, env, cache) for x = f.args]\n    dx, = [seval(x, dvar, env, cache) for x = f.args]\n    exp(x) * dx\nend\n\nfunction _eval(::Val{:log}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv\n    x, = [seval(x, env, cache) for x = f.args]\n    dx, = [seval(x, dvar, env, cache) for x = f.args]\n    dx / x\nend\n\nfunction _eval(::Val{:sqrt}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv\n    x, = [seval(x, env, cache) for x = f.args]\n    dx, = [seval(x, dvar, env, cache) for x = f.args]\n    dx /(2 * sqrt(x))\nend\n\nfunction _eval(::Val{:sum}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv\n    dx, = [seval(x, dvar, env, cache) for x = f.args]\n    sum(dx)\nend\n\nfunction _eval(::Val{:dot}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv\n    x,y = [seval(x, env, cache) for x = f.args]\n    dx,dy = [seval(x, dvar, env, cache) for x = f.args]\n    dot(x,dy) + dot(dx,y)\nend\n", "meta": {"hexsha": "0a03619069535572f53aaf4f7f90e1acf14f97ec", "size": 4039, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/_deriv.jl", "max_stars_repo_name": "JuliaReliab/SymbolicDiff.jl", "max_stars_repo_head_hexsha": "6b0e99c51c0e83eb751ace9bb40b87180bd4b2cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/_deriv.jl", "max_issues_repo_name": "JuliaReliab/SymbolicDiff.jl", "max_issues_repo_head_hexsha": "6b0e99c51c0e83eb751ace9bb40b87180bd4b2cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-07T06:07:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-26T18:45:18.000Z", "max_forks_repo_path": "src/_deriv.jl", "max_forks_repo_name": "JuliaReliab/SymbolicDiff.jl", "max_forks_repo_head_hexsha": "6b0e99c51c0e83eb751ace9bb40b87180bd4b2cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5546875, "max_line_length": 122, "alphanum_fraction": 0.6427333498, "num_tokens": 1364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145364, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7934263263620278}}
{"text": "# DBSCAN Clustering\r\n#\r\n#   References:\r\n#\r\n#       Martin Ester, Hans-peter Kriegel, Jörg S, and Xiaowei Xu\r\n#       A density-based algorithm for discovering clusters\r\n#       in large spatial databases with noise. 1996.\r\n#\r\n\r\n\r\ntype DbscanResult <: ClusteringResult\r\n    seeds::Vector{Int}          # starting points of clusters, size (k,)\r\n    assignments::Vector{Int}    # assignments, size (n,)\r\n    counts::Vector{Int}         # number of points in each cluster, size (k,)\r\nend\r\n\r\n\r\n## main algorithm\r\n\r\nfunction dbscan{T<:Real}(D::DenseMatrix{T}, eps::Real, minpts::Int)\r\n    # check arguments\r\n    n = size(D, 1)\r\n    size(D, 2) == n || error(\"D must be a square matrix.\")\r\n    n >= 2 || error(\"There must be at least two points.\")\r\n    eps > 0 || error(\"eps must be a positive real value.\")\r\n    minpts >= 1 || error(\"minpts must be a positive integer.\")\r\n\r\n    # invoke core algorithm\r\n    _dbscan(D, convert(T, eps), minpts, 1:n)\r\nend\r\n\r\nfunction _dbscan{T<:Real}(D::DenseMatrix{T}, eps::T, minpts::Int, visitseq::AbstractVector{Int})\r\n    n = size(D, 1)\r\n\r\n    # prepare\r\n    seeds = Int[]\r\n    counts = Int[]\r\n    assignments = zeros(Int, n)\r\n    visited = zeros(Bool, n)\r\n    k = 0\r\n\r\n    # main loop\r\n    for p in visitseq\r\n        if assignments[p] == 0 && !visited[p]\r\n            visited[p] = true\r\n            nbs = _dbs_region_query(D, p, eps)\r\n            if length(nbs) >= minpts\r\n                k += 1\r\n                cnt = _dbs_expand_cluster!(D, k, p, nbs, eps, minpts, assignments, visited)\r\n                push!(seeds, p)\r\n                push!(counts, cnt)\r\n            end\r\n        end\r\n    end\r\n\r\n    # make output\r\n    return DbscanResult(seeds, assignments, counts)\r\nend\r\n\r\n## key steps\r\n\r\nfunction _dbs_region_query{T<:Real}(D::DenseMatrix{T}, p::Int, eps::T)\r\n    n = size(D,1)\r\n    nbs = Int[]\r\n    dists = view(D,:,p)\r\n    for i = 1:n\r\n        @inbounds if dists[i] < eps\r\n            push!(nbs, i)\r\n        end\r\n    end\r\n    return nbs::Vector{Int}\r\nend\r\n\r\nfunction _dbs_expand_cluster!{T<:Real}(D::DenseMatrix{T},           # distance matrix\r\n                                       k::Int,                      # the index of current cluster\r\n                                       p::Int,                      # the index of seeding point\r\n                                       nbs::Vector{Int},            # eps-neighborhood of p\r\n                                       eps::T,                      # radius of neighborhood\r\n                                       minpts::Int,                 # minimum number of neighbors of a density point\r\n                                       assignments::Vector{Int},    # assignment vector\r\n                                       visited::Vector{Bool})       # visited indicators\r\n    assignments[p] = k\r\n    cnt = 1\r\n    while !isempty(nbs)\r\n        q = shift!(nbs)\r\n        if !visited[q]\r\n            visited[q] = true\r\n            qnbs = _dbs_region_query(D, q, eps)\r\n            if length(qnbs) > minpts\r\n                for x in qnbs\r\n                    if assignments[x] == 0\r\n                        push!(nbs, x)\r\n                    end\r\n                end\r\n            end\r\n        end\r\n        if assignments[q] == 0\r\n            assignments[q] = k\r\n            cnt += 1\r\n        end\r\n    end\r\n    return cnt\r\nend\r\n\r\n\r\n", "meta": {"hexsha": "c4c0950b66902eb91a185c436b0f792a018a8e17", "size": 3319, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dbscan.jl", "max_stars_repo_name": "axsk/Clustering.jl", "max_stars_repo_head_hexsha": "b8e0991dee0ce70f428d1c225faaf382c0fa5447", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dbscan.jl", "max_issues_repo_name": "axsk/Clustering.jl", "max_issues_repo_head_hexsha": "b8e0991dee0ce70f428d1c225faaf382c0fa5447", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dbscan.jl", "max_forks_repo_name": "axsk/Clustering.jl", "max_forks_repo_head_hexsha": "b8e0991dee0ce70f428d1c225faaf382c0fa5447", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3113207547, "max_line_length": 117, "alphanum_fraction": 0.4808677312, "num_tokens": 838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7933892905411903}}
{"text": "# ---\n# title: 458. Poor Pigs\n# id: problem458\n# author: Indigo\n# date: 2021-02-02\n# difficulty: Hard\n# categories: Math\n# link: <https://leetcode.com/problems/poor-pigs/description/>\n# hidden: true\n# ---\n# \n# There are `buckets` buckets of liquid, where **exactly one** of the buckets is\n# poisonous. To figure out which one is poisonous, you feed some number of\n# (poor) pigs the liquid to see whether they will die or not. Unfortunately, you\n# only have `minutesToTest` minutes to determine which bucket is poisonous.\n# \n# You can feed the pigs according to these steps:\n# \n#   1. Choose some live pigs to feed.\n#   2. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time.\n#   3. Wait for `minutesToDie` minutes. You may **not** feed any other pigs during this time.\n#   4. After `minutesToDie` minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.\n#   5. Repeat this process until you run out of time.\n# \n# Given `buckets`, `minutesToDie`, and `minutesToTest`, return _the **minimum**\n# number of pigs needed to figure out which bucket is poisonous within the\n# allotted time_.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: buckets = 1000, minutesToDie = 15, minutesToTest = 60\n#     Output: 5\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: buckets = 4, minutesToDie = 15, minutesToTest = 15\n#     Output: 2\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: buckets = 4, minutesToDie = 15, minutesToTest = 30\n#     Output: 2\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= buckets <= 1000`\n#   * `1 <= minutesToDie <= minutesToTest <= 100`\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction poor_pigs(buckets::Int, minutesToDie::Int, minutesToTest::Int)\n    state = minutesToTest ÷ minutesToDie + 1\n    return ceil(Int, log(buckets) / log(state))\nend\n## @lc code=end\n", "meta": {"hexsha": "f855ea7b7a0f2e253d70e3e109b0d184e2af6750", "size": 1928, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/458.poor-pigs.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/458.poor-pigs.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/458.poor-pigs.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 27.1549295775, "max_line_length": 136, "alphanum_fraction": 0.6556016598, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7933892860188221}}
{"text": "__precompile__()\n\nmodule SparseRelaxation\n\nexport gauss_seidel, gauss_seidel!, weighted_jacobi!, weighted_jacobi\n\n# TODO: how to improve locality\n# order is different than it should be?\n\"\"\"\n    gauss_seidel(A::SparseMatrixCSC, x::Vector, b::Vector; backwards::Bool = false, iterations = 1)\n\nReturn a vector that is the result of applying one iteration of Gauss Seidel to\n`Ax=b`. This iteration is equivalent to `L(b - Ux)` where `L` is the lower\ntriangular part of `A` and `U` is the strictly upper triangular part of `A`. If\n`backwards` is true, then a backwards sweep is performed. `A` is assumed to be symmetric. If not, then `gauss_seidel(A)` is really Gauss-Seidel applied to `A^T`.\n\"\"\"\nfunction gauss_seidel{T}( A :: SparseMatrixCSC{T}\n                        , x :: Vector{T}\n                        , b :: Vector{T}\n                        ; backwards :: Bool = false\n                        , iterations :: Int = 1\n                        ) :: Vector{T}\n    x_new = copy(x)\n    gauss_seidel!(A, x_new, b, backwards=backwards, iterations=iterations)\n    x_new\nend\n\n\"\"\"\n    gauss_seidel!(A::SparseMatrixCSC, x::Vector, b::Vector, backwards::Bool = false)\n\nIn place, more efficient version of `gauss_seidel(A, x, b)`.\n\"\"\"\nfunction gauss_seidel!{T}( A :: SparseMatrixCSC{T}\n                         , x :: Vector{T}\n                         , b :: Vector{T}\n                         ; backwards :: Bool = false\n                         , iterations :: Int = 1\n                         ) :: Vector{T}\n    rows = rowvals(A)\n    vals = nonzeros(A)\n    m, n = size(A)\n    for col in 1:n\n        colsum :: T = 0\n        diag :: T = 0\n\n        js = nzrange(A, col)\n        # hack to avoid allocating\n        start = backwards ? js.stop : js.start\n        stop = backwards ? js.start : js.stop\n        step = backwards ? -1 : 1\n        @inbounds for j in start:step:stop\n            row = rows[j]\n            val = vals[j]\n            if row != col\n                colsum += val * x[row]\n            else\n                diag = val\n            end\n        end\n\n        @inbounds x[col] = (b[col] - colsum) / diag\n    end\n\n    x\nend\n\n\"\"\"\nIn place version of `weighted_jacobi`.\n\"\"\"\nfunction weighted_jacobi!{T}( A :: SparseMatrixCSC{T}\n                            , x :: Vector{T}\n                            , b :: Vector{T}\n                            ; weight :: T = 2/3\n                            , iterations :: Int = 1\n                            ) :: Vector{T}\n    Di = spdiagm(map(x -> 1/x, diag(A)))\n    R = A - spdiagm(diag(A))\n    for i in 1:iterations\n        x[:] = weight * Di * (b - R*x) + (1 - weight) * x\n    end\n\n    x\nend\n\n\"\"\"\n    weighted_jacobi(A::SparseMatrixCSC, x::Vector, b::Vector; weight = 2/3, iterations = 1)\n\nReturn a vector that is the result of applying one iteration of Jacobi smoothing to\n`Ax=b`. This iteration is equivalent to `wD(b - R*x) + (1-w)x` where `D` is the inverse diagonal and `R` is `A` without its diagonal.\n\"\"\"\nfunction weighted_jacobi{T}( A :: SparseMatrixCSC{T}\n                           , x :: Vector{T}\n                           , b :: Vector{T}\n                           ; weight :: T = 2/3\n                           , iterations :: Int = 1\n                           ) :: Vector{T}\n    x_new = copy(x)\n    weighted_jacobi!(A, x_new, b, weight=weight, iterations=iterations)\n    x_new\nend\n\nend\n", "meta": {"hexsha": "a798e0019aa4836bb0e72326d7a23ba1a40f3124", "size": 3350, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SparseRelaxation.jl", "max_stars_repo_name": "tkonolige/SparseRelaxation.jl", "max_stars_repo_head_hexsha": "18caf343467cd566e471c80f52f8b0b51d8e541b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-19T13:13:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-19T13:13:00.000Z", "max_issues_repo_path": "src/SparseRelaxation.jl", "max_issues_repo_name": "tkonolige/SparseRelaxation.jl", "max_issues_repo_head_hexsha": "18caf343467cd566e471c80f52f8b0b51d8e541b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SparseRelaxation.jl", "max_forks_repo_name": "tkonolige/SparseRelaxation.jl", "max_forks_repo_head_hexsha": "18caf343467cd566e471c80f52f8b0b51d8e541b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5242718447, "max_line_length": 161, "alphanum_fraction": 0.5167164179, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7933892838457464}}
{"text": "module FreudenthalTriangulation\n\nusing LinearAlgebra\nusing SparseArrays\n\nexport freudenthal_vertices, freudenthal_simplex, barycentric_coordinates, freudenthal_simplex_and_coords,\n        freudenthal_simplex_and_coords!\n\n\n# Construct the Freudenthal triangulation of the belief simplex\n\n\"\"\"\n    freudenthal_vertices(n::Int64, m::Int64)\nConstruct the list of Freudenthal vertices in an `n` dimensional space with grid resolution `m`.\nThe vertices are represented by a list of `n` dimensional vectors.\n\"\"\"\nfunction freudenthal_vertices(n::Int64, m::Int64)\n    V = Vector{Int}[]\n    v = Vector{Int}(undef, n)\n    v[1] = m\n    freudenthal_vertices!(V, v, 2)\n    return V\nend\n\nfunction freudenthal_vertices!(V::Vector{Vector{Int64}}, v::Vector{Int64}, i::Int64)\n    n = length(v)\n    if i > n\n        push!(V, copy(v))\n        return\n    end\n    for k in 0 : v[i-1]\n        v[i] = k\n        freudenthal_vertices!(V, v, i+1)\n    end\nend\n\n\"\"\"\n    freudenthal_simplex(x::Vector{Float64})\nReturns the list of vertices of the simplex of point `x` in the Freudenthal grid.\n\"\"\"\nfunction freudenthal_simplex(x::Vector{Float64})\n    n = length(x)\n    V = Vector{Vector{Int}}(undef, n+1)\n    V[1] = floor.(Int, x)\n    d = x - V[1]\n    p = sortperm(d, rev=true)\n    for i in 2 : n+1\n        V[i] = copy(V[i-1])\n        V[i][p[i-1]] += 1\n    end\n    return V\nend\n\n\"\"\"\n    barycentric_coordinates(x::Vector{Int64}, V::Vector{Vector{Int64}})\nGiven a point `x` and its simplex `V` in the Freudenthal grid, returns the barycentric coordinates\nof `x` in the grid. `V` must be in the same order as provided by the output of `freudenthal_simplex`\n\"\"\"\nfunction barycentric_coordinates(x, V)\n    d = x - V[1]\n    p = sortperm(d, rev=true)\n    n = length(x)\n    λ = Vector{Float64}(undef, n+1)\n    λ[n+1] = d[p[n]]\n    for i in n:-1:2\n        λ[i] = d[p[i-1]] - d[p[i]]\n    end\n    λ[1] = 1.0 - sum(λ[2:end])\n    return λ\nend\n\n\"\"\"\n    freudenthal_coords(x::AbstractArray{Float64})\nGiven a point `x`, returns the simplex of the point `x` and the barycentric coordinates of `x` in the grid.\n\"\"\"\nfunction freudenthal_simplex_and_coords(x::Vector{Float64})\n    V = freudenthal_simplex(x)\n    return V, barycentric_coordinates(x, V)\nend\n\n\"\"\"\n    freudenthal_simplex_and_coords!(x::AbstractArray{Float64}, V::Vector{Vector{Int64}}, λ::Vector{Float64})\nFills `V` and `λ` with the simplex points in the Freudenthal space and associated coordinates respectively.\n\"\"\"\nfunction freudenthal_simplex_and_coords!(x::AbstractArray{Float64}, V::Vector{Vector{Int64}}, λ::Vector{Float64})\n    n = length(x)\n    V[1] = floor.(Int, x)\n    d = x - V[1]\n    p = sortperm(d, rev=true)\n    for i in 2 : n+1\n        copyto!(V[i], V[i-1])\n        V[i][p[i-1]] += 1\n    end\n    λ[n+1] = d[p[n]]\n    for i in n:-1:2\n        λ[i] = d[p[i-1]] - d[p[i]]\n    end\n    λ[1] = 1.0 - sum(λ[2:end])\n    return V, λ\nend\n\nend # module\n", "meta": {"hexsha": "0fb6aef3ba70453fbc23c333aaccbc1f18ee852e", "size": 2870, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FreudenthalTriangulation.jl", "max_stars_repo_name": "SidhartK/TestRepo2.jl", "max_stars_repo_head_hexsha": "0a6f1e0930b88b9fd98c29fc071f7e9723d9027d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FreudenthalTriangulation.jl", "max_issues_repo_name": "SidhartK/TestRepo2.jl", "max_issues_repo_head_hexsha": "0a6f1e0930b88b9fd98c29fc071f7e9723d9027d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FreudenthalTriangulation.jl", "max_forks_repo_name": "SidhartK/TestRepo2.jl", "max_forks_repo_head_hexsha": "0a6f1e0930b88b9fd98c29fc071f7e9723d9027d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8640776699, "max_line_length": 113, "alphanum_fraction": 0.6414634146, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7933892798989661}}
{"text": "module ShearFunctions\n\nusing StaticArrays\nusing ..PhysicalVectors\n\nexport b1g_shear, b2g_shear, bxg_shears!\n\n\"\"\"\n    b1g_shear( eval_r::Vector2D, bob::Vector2D )\n\nCalculate the ``B_{1g}`` from an edge dislocation for a given Burgers vector `bob` at site `eval_r`. \n\n# Additional Information\n* The edge dislocation is aligned along the ``z`` axis at the origin.\n* This is in units of ``1/(1-σ)`` for a Poisson ratio ``σ``.\n\n# Examples\n```jldocstest\njulia> b1g_shear( Vector2D(1.,1.), Vector2D(1.,0.) )\n-0.07957747154594767\n```\n\"\"\"\nfunction b1g_shear( eval_r::Vector2D, bob::Vector2D )\n    return -1/π * ( eval_r.vec[1] * eval_r.vec[2] / magnitude2(eval_r) ) * (bob ⋅ eval_r) / magnitude2(eval_r)\nend\n\n\"\"\"\n    b2g_shear( eval_r::Vector2D, bob::Vector2D )\n\nCalculate the ``B_{2g}`` from an edge dislocation for a given Burgers vector `bob` at site `eval_r`. \n\n# Additional Information\n* The edge dislocation is aligned along the ``z`` axis at the origin.\n* This is in units of ``1/(1-σ)`` for a Poisson ratio ``σ``.\n\n# Examples\n```jldocstest\njulia> b2g_shear( Vector2D(1.,1.), Vector2D(1.,0.) )\n0.15915494309189535\n```\n\"\"\"\nfunction b2g_shear( bob::Vector2D, eval_r::Vector2D )\n    return 1/(2*π) * ( ( eval_r.vec[1]^2 - eval_r.vec[2]^2 ) / magnitude2(eval_r) ) * (bob ⋅ eval_r) / magnitude2(eval_r)\nend\n\n\"\"\"\n    bxg_shears!(eval_r::Vector2D, bob::Vector2D; diff::Function, source_r::Vector2D = Vector2D(0.,0.)) -> Tuple{T, T} where {T <: Real}\n\nCalculate the two shears `(b1g, b2g)` from the ``B_{1g}`` and ``B_{2g}`` channels from and edge dislocation situated at the `source_r`\nlocation and aligned along the ``z`` axis with a Burger's vector `bob`. \n\n# Additional Information\n* This function mutates both and `eval_r`. It should be used in cases where `eval_r` is a temporary vector.\n* The keyword argument `diff <: Function` should be used in cases where `Vector2D` subtraction has a different definition than the normal one expected, for example with periodic boundary conditions.\n\n# Examples\n```jldocstest\njulia> using StaticArrays\n\njulia> A = MVector{2}(0., 0.)\n2-element MVector{2, Float64} with indices SOneTo(2):\n 0.0\n 0.0\n\njulia> bxg_shears!( A, Vector2D(1.,1.), Vector2D(1.,0.) )\n\njulia> A\n2-element MVector{2, Float64} with indices SOneTo(2):\n -0.07957747154594767\n  0.15915494309189535\n```\n\"\"\"\nfunction bxg_shears!( eval_r::Vector2D, bob::Vector2D; diff::Function = subtract!, source_r::Vector2D = Vector2D(0.,0.) )\n    diff(eval_r, source_r)\n    b1g = b1g_shear(eval_r, bob)\n    b2g = b2g_shear(eval_r, bob)\n    return (b1g, b2g)\nend\n    \nend # module ShearFunctions", "meta": {"hexsha": "77ef67498f55a5529c5b86a4f3bf8365ac31d304", "size": 2578, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ShearFunctions.jl", "max_stars_repo_name": "meese-wj/RandomStrainDistributions.jl", "max_stars_repo_head_hexsha": "870f3f28f7a529484768a652511c843dbcae9d2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ShearFunctions.jl", "max_issues_repo_name": "meese-wj/RandomStrainDistributions.jl", "max_issues_repo_head_hexsha": "870f3f28f7a529484768a652511c843dbcae9d2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ShearFunctions.jl", "max_forks_repo_name": "meese-wj/RandomStrainDistributions.jl", "max_forks_repo_head_hexsha": "870f3f28f7a529484768a652511c843dbcae9d2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.225, "max_line_length": 198, "alphanum_fraction": 0.6982156711, "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7933892771503022}}
{"text": "#\n# 2D Position operators\n#\n\nfunction x_coord_matrix(p::Param)\n\n    #Variables\n    xmin        = p.xmin\n    xmax        = p.xmax\n    Nx          = p.xnodes\n\n    ymin        = p.ymin\n    ymax        = p.ymax\n    Ny          = p.ynodes\n\n     #Discretize space\n     dx      = (xmax - xmin)/(Nx-1)\n     x       = [xmin + (i-1)*dx for i in 1:Nx]\n     \n     dy      = (ymax - ymin)/(Ny-1)\n     y       = [ymin + (i-1)*dy for i in 1:Ny]\n     \n     if(p.Boundaries == :periodic )\n         dx      = (xmax - xmin)/(Nx)\n         x       = [xmin + (i-1)*dx for i in 1:Nx]   \n         \n         dy      = (ymax - ymin)/(Ny)\n         y       = [ymin + (i-1)*dy for i in 1:Ny] \n     end\n\n    A = spzeros(Nx*Ny , Nx*Ny)\n    \n    index = 0\n\n    for (ix , posx) in enumerate(x) , (iy , posy) in enumerate(y)\n\n        index = (iy-1)*Nx+ix\n        A[index , index] = posx\n             \n    end\n\n    return A\nend\n\nfunction y_coord_matrix(p::Param)\n\n    #Variables\n    xmin        = p.xmin\n    xmax        = p.xmax\n    Nx          = p.xnodes\n\n    ymin        = p.ymin\n    ymax        = p.ymax\n    Ny          = p.ynodes\n\n    #Discretize space\n    dx      = (xmax - xmin)/(Nx-1)\n    x       = [xmin + (i-1)*dx for i in 1:Nx]\n    \n    dy      = (ymax - ymin)/(Ny-1)\n    y       = [ymin + (i-1)*dy for i in 1:Ny]\n    \n    if(p.Boundaries == :periodic )\n        dx      = (xmax - xmin)/(Nx)\n        x       = [xmin + (i-1)*dx for i in 1:Nx]   \n        \n        dy      = (ymax - ymin)/(Ny)\n        y       = [ymin + (i-1)*dy for i in 1:Ny] \n    end\n\n    A = spzeros(Nx*Ny , Nx*Ny)\n    \n    index = 0\n\n    for (ix , posx) in enumerate(x) , (iy , posy) in enumerate(y)\n  \n        index = (iy-1)*Nx+ix\n        A[index , index] = posy\n             \n    end\n\n    return A\nend\n\n\n", "meta": {"hexsha": "209962b772e5182c1c1754c2ab240a8c14014488", "size": 1748, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operators/position_operator.jl", "max_stars_repo_name": "diogoribeiro98/BhAbs_Solver", "max_stars_repo_head_hexsha": "7c0f47256d0ab75978532bc770d1e40c307ecb8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/operators/position_operator.jl", "max_issues_repo_name": "diogoribeiro98/BhAbs_Solver", "max_issues_repo_head_hexsha": "7c0f47256d0ab75978532bc770d1e40c307ecb8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/operators/position_operator.jl", "max_forks_repo_name": "diogoribeiro98/BhAbs_Solver", "max_forks_repo_head_hexsha": "7c0f47256d0ab75978532bc770d1e40c307ecb8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3255813953, "max_line_length": 65, "alphanum_fraction": 0.4147597254, "num_tokens": 604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7932954972853636}}
{"text": "\n# # Support Vector Machine\n# We are showing how to solve a support vector machine problem with COSMO (and JuMP).\n#\n# ## Generating the Dataset\n# We want to classify the points in this example dataset with $m = 100$ samples and $n = 2$ features:\n\nusing Distributions: MvNormal\nusing Plots, LinearAlgebra, SparseArrays, Random, Test\n\n#-\n\n## Generate dataset\nrng = Random.MersenneTwister(123);\nnum_samples = 100;\nXpos = rand(rng, MvNormal([1.5, 1.5], 1.25), div(num_samples, 2))';\nXneg = rand(rng, MvNormal([-1.5, -1.5], 1.25), div(num_samples, 2))';\nypos = ones(div(num_samples, 2));\nyneg = -ones(div(num_samples, 2));\n\n#-\n## Plot dataset\nplot(Xpos[:, 1], Xpos[:, 2], color = :red, st=:scatter, markershape = :rect, label = \"positive\", xlabel = \"x1\", ylabel = \"x2\")\nplot!(Xneg[:, 1], Xneg[:, 2], color = :blue, st=:scatter, markershape = :circle, label = \"negative\")\n\n# with samples $(x_1, x_2, \\ldots, x_m) \\in \\mathbb{R}^2$ and labels $y_i \\in \\{-1,1\\}$.\n#\n# ## Solving SVM as a QP\n# We want to compute the weights $w$ and bias term $b$ of the (soft-margin) SVM classifier:\n#\n# $$\n# \\begin{array}{ll}\n#     \\text{minimize}   & \\|w\\|^2 + \\lambda \\sum_{i=1}^m \\text{max}(0, 1 - y_i(w^\\top x_i  - b)),\n# \\end{array}\n# $$\n# where $\\lambda$ is a hyperparameter. This problem can be solved as a quadratic program.\n# We can rewrite above problem into an optimisation problem in primal form by introducing the auxiliary slack variables $t_i$:\n#\n# $$\n# t_i = \\text{max}(0, 1 - y_i(w^T x_i  - b)), \\quad t_i \\geq 0.\n# $$\n\n# This allows us to write the problems in standard QP format:\n# $$\n# \\begin{array}{ll}\n#     \\text{minimize}   & \\|w\\|^2 + \\lambda \\sum_{i=1}^m t_i\\\\\n#     \\text{subject to} & y_i (w^\\top x_i - b) \\geq 1 - t_i, \\quad \\text{for } i = 1,\\ldots, m\\\\\n#                       & t_i \\geq 0, \\quad \\text{for } i = 1,\\ldots, m.\n# \\end{array}\n# $$\n# Next, we will remove the bias term $b$ by adding an initial feature $x_0 = -1$ to each sample (now: $n = 3$):\n\nX = [-ones(num_samples) [Xpos; Xneg]];\ny = [ypos; yneg];\nm, n = size(X)\n\n# ## Modelling in JuMP\n# We can model this problem using `JuMP` and then hand it to `COSMO`:\nusing JuMP, COSMO\n#-\nλ = 1.0; # hyperparameter\nmodel = JuMP.Model(optimizer_with_attributes(COSMO.Optimizer, \"verbose\" => true));\n\n\n@variable(model, w[1:n]);\n@variable(model, t[1:m] >= 0.);\n@objective(model, Min, w' * w  + λ * ones(m)' * t);\n@constraint(model, diagm(0 => y) * X * w .+ t .- 1 .>= 0);\nstatus = JuMP.optimize!(model)\n# The optimal weights $w = [w_0, w_1, w_2]^\\top$ (where $w_0 = b$) are:\nw_opt = JuMP.value.(w)\n\n\n# ## Plotting the hyperplane\n# The separating hyperplane is defined by $w^\\top x - b = 0$. To plot the hyperplane, we calculate $x_2$ over a range of $x_1$ values:\n# $$\n# x_2 = (-w_1 x_1 - w_0) / w_2, \\text{ where } w_0 = b.\n# $$\nx1 = -4:0.1:4;\nx2 = (-w_opt[2] * x1  .- w_opt[1]) / w_opt[3]\nplot!(x1, x2, label = \"SVM separator\", legend = :topleft)\n\n# ## Modelling with COSMO\n# The problem can also be solved by transforming it directly into `COSMO`'s problem format.\n# Define `COSMO``s $x$-variable to be $x=[w, t]^\\top$ and choose $P$, $q$, accordingly:\nP = blockdiag(spdiagm(0 => ones(n)), spzeros(m, m));\nq = [zeros(n); 0.5 * λ * ones(m)];\n\n# Next we transform the first constraint $y_i (w^\\top x_i - b) \\geq 1 - t_i, \\quad \\text{for } i = 1,\\ldots, m$ into\n# `COSMO`'s constraint format: $Ax + b \\in \\mathcal{K}$.\nA1 = [(spdiagm(0 => y) * X) spdiagm(0 => ones(m))];\nb1 = -ones(m);\ncs1 = COSMO.Constraint(A1, b1, COSMO.Nonnegatives);\n\n# It remains to specify the constraint $t_i \\geq 0, \\quad \\text{for } i = 1,\\ldots, m$:\nA2 = spdiagm(0 => ones(m));\nb2 = zeros(m);\ncs2 = COSMO.Constraint(A2, b2, COSMO.Nonnegatives, m+n, n+1:m+n);\n\n# Create, assemble and solve the `COSMO.Model`:\nmodel2 = COSMO.Model();\nassemble!(model2, P, q, [cs1; cs2]);\nresult2 = COSMO.optimize!(model2);\nw_opt2 = result2.x[1:3];\n@test norm(w_opt2 - w_opt, Inf) < 1e-3\n", "meta": {"hexsha": "8ad1d2fa7ab43485171c42cbb54253d6e4b0f95c", "size": 3905, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/svm_primal.jl", "max_stars_repo_name": "blegat/COSMO.jl", "max_stars_repo_head_hexsha": "88d03d4c676051f5aaa1c7aac0b17fe2026b9797", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 210, "max_stars_repo_stars_event_min_datetime": "2018-12-11T23:45:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T23:11:26.000Z", "max_issues_repo_path": "examples/svm_primal.jl", "max_issues_repo_name": "blegat/COSMO.jl", "max_issues_repo_head_hexsha": "88d03d4c676051f5aaa1c7aac0b17fe2026b9797", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 110, "max_issues_repo_issues_event_min_datetime": "2018-12-12T15:52:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T00:44:39.000Z", "max_forks_repo_path": "examples/svm_primal.jl", "max_forks_repo_name": "blegat/COSMO.jl", "max_forks_repo_head_hexsha": "88d03d4c676051f5aaa1c7aac0b17fe2026b9797", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2019-03-10T06:40:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T08:53:29.000Z", "avg_line_length": 36.8396226415, "max_line_length": 134, "alphanum_fraction": 0.6256081946, "num_tokens": 1444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7932954923750832}}
{"text": "#\n# Denoise an SPD Example with Cyclic Proximal Point applied to the\n#\n# L2-TV functional with anisotropic TV\n#\n# where the example is the same data as for the corresponding CP algorithm\n#\nusing Manopt, Manifolds\nusing Images, CSV, DataFrames, LinearAlgebra, JLD2\n#\n# Settings\nExportResult = true\nExportOrig = true\nExportTable = true\nasy_render_detail = 2\n#\n# Manifold and Data\nf = artificial_SPD_image2(32)\npixelM = SymmetricPositiveDefinite(3)\nresultsFolder = \"examples/Total_Variation/SPD_TV/\"\nexperimentName = \"ImageCPPA\"\nif !isdir(resultsFolder)\n    mkdir(resultsFolder)\nend\nif ExportOrig\n    asymptote_export_SPD(\n        resultsFolder * experimentName * \"-orig.asy\";\n        data = f,\n        scaleAxes = (7.5, 7.5, 7.5),\n    )\n    render_asymptote(resultsFolder * experimentName * \"-orig.asy\", render=asy_render_detail)\nend\n#\n# Parameters\nα = 6.0\nmaxIterations = 4000\n#\n# Build Problem for L2-TV\nM = PowerManifold(pixelM, NestedPowerRepresentation(), size(f)...)\nd = length(size(f))\nrep(d) = (d > 1) ? [ones(Int, d)..., d] : d\nfidelity(x) = 1 / 2 * distance(M, x, f)^2\nΛ(x) = forward_logs(M, x) # on T_xN\nprior(x) = norm(norm.(Ref(pixelM), repeat(x, rep(d)...), Λ(x)), 1)\n#\n# Setup and Optimize\ncost(x) = fidelity(x) + α * prior(x)\nproxes = [(λ, x) -> prox_distance(M, λ, f, x, 2), (λ, x) -> prox_TV(M, α * λ, x, 1)]\nx0 = f\n@time o = cyclic_proximal_point(\n    M,\n    cost,\n    proxes,\n    x0;\n    debug = [\n        :Iteration,\n        \" | \",\n        DebugProximalParameter(),\n        \" | \",\n        :Change,\n        \" | \",\n        :Cost,\n        \"\\n\",\n        100,\n        :Stop,\n    ],\n    record = [:Iteration, :Iterate, :Cost],\n    stopping_criterion = StopAfterIteration(maxIterations),\n    return_options = true,\n)\ny = get_solver_result(o)\nyRec = get_record(o)\n#\n# Results\nif ExportResult\n    asymptote_export_SPD(\n        resultsFolder *\n        experimentName *\n        \"-result-$(maxIterations)-α$(replace(string(α), \".\" => \"-\")).asy\";\n        data = y,\n        scaleAxes = (7.5, 7.5, 7.5),\n    )\n    render_asymptote(\n        resultsFolder *\n        experimentName *\n        \"-result-$(maxIterations)-α$(replace(string(α), \".\" => \"-\")).asy\";\n        render=asy_render_detail,\n    )\nend\nif ExportTable\n    A = cat([y[1] for y in yRec], [y[3] for y in yRec]; dims = 2)\n    CSV.write(\n        string(resultsFolder * experimentName * \"ResultCost.csv\"),\n        DataFrame(A),\n        writeheader = false,\n    )\n    save(\n        resultsFolder * experimentName * \"-CostValue.jld2\",\n        Dict(\"compareCostFunctionValue\" => last(yRec)[3]),\n    )\nend\n", "meta": {"hexsha": "7bcdf509870b79e0b2220393d2f41f703e39ceae", "size": 2563, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Total_Variation/SPDImage_CPPA.jl", "max_stars_repo_name": "matbesancon/Manopt.jl", "max_stars_repo_head_hexsha": "25671e4c56728b7ab3ce82321d063308095750da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Total_Variation/SPDImage_CPPA.jl", "max_issues_repo_name": "matbesancon/Manopt.jl", "max_issues_repo_head_hexsha": "25671e4c56728b7ab3ce82321d063308095750da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Total_Variation/SPDImage_CPPA.jl", "max_forks_repo_name": "matbesancon/Manopt.jl", "max_forks_repo_head_hexsha": "25671e4c56728b7ab3ce82321d063308095750da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1274509804, "max_line_length": 92, "alphanum_fraction": 0.6110027312, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.8615382040983516, "lm_q1q2_score": 0.7932954874648028}}
{"text": "## Exercise 5-3\n## Fermat’s Last Theorem says that there are no positive integers a, b, and c such that\n\n## a^n+b^n=c^n\n## for any value of n greater than 2.\n\n## Write a function named checkfermat that takes four parameters—a, b, c and n—and checks to see if Fermat’s theorem holds. If n is greater than 2 and a^n + b^n == c^n the program should print, “Holy smokes, Fermat was wrong!” Otherwise the program should print, “No, that doesn’t work.”\nprintln(\"Ans 1: \")\n\nfunction check_fermats_theorem(a::Int, b::Int, c::Int, n::Int)\n    if a^n + b^n == c^n && n > 2\n        println(\"Holy smokes, Fermat was wrong!\")\n    else\n        println(\"No, that doesn’t work.\")\n    end \nend\n\ncheck_fermats_theorem(3, 5, 3, 3)\n\n## 2. Write a function that prompts the user to input values for a, b, c and n, converts them to integers, and uses checkfermat to check whether they violate Fermat’s theorem.\nprintln(\"Ans 2: \")\n\nfunction check_fermats_theorem2()\n    print(\"Enter value for a: \")\n    a = parse(Int64, readline())\n    print(\"Enter value for b: \")\n    b = parse(Int64, readline())\n    print(\"Enter value for c: \")\n    c = parse(Int64, readline())\n    print(\"Enter value for n: \")\n    n = parse(Int64, readline())\n\n    check_fermats_theorem(a, b, c, n)\nend\n\ncheck_fermats_theorem2()\n\nprintln(\"End.\")\n", "meta": {"hexsha": "aa330f2c2ccf4eeb5fc00c088ba2e06fb71cc882", "size": 1293, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter5/ex3.jl", "max_stars_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_stars_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-13T14:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T14:11:30.000Z", "max_issues_repo_path": "Chapter5/ex3.jl", "max_issues_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_issues_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter5/ex3.jl", "max_forks_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_forks_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1538461538, "max_line_length": 287, "alphanum_fraction": 0.6674400619, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7932954853561744}}
{"text": "\n\n\"\"\"\nGraph Laplacian of the line graph. With keyword `boundary = false`,\na graph Laplacian of the circle.\n\"\"\"\nlinelaplacian(n; kwargs...) = linelaplacian(Float64,n; kwargs...)\nfunction linelaplacian(T,n; boundary=true)\n    A = SymTridiagonal(2ones(T,n), -ones(T,n-1))\n    if boundary\n        A[1,1] = A[end,end] = true\n    end\n    A\nend\n\n\"\"\"\nGraph Laplacian of a `m×n` lattice.\n\"\"\"\nfunction gridlaplacian(T, m, n)\n    S = sparse(T(0.0)I, n*m, n*m)\n    linear = LinearIndices((1:m, 1:n))\n    for i in 1:m\n        for j in 1:n\n            for (i2, j2) in ((i + 1, j), (i, j + 1))\n                if i2 <= m && j2 <= n\n                    S[linear[i, j], linear[i2, j2]] -= 1\n                    S[linear[i2, j2], linear[i, j]] -= 1\n\n                    S[linear[i, j], linear[i, j]] += 1\n                    S[linear[i2, j2], linear[i2, j2]] += 1\n                end\n            end\n        end\n    end\n    S\nend\n\nfunction gridderiv(T, m, n)\n    S1 = sparse(T(0.0)*I, n*m, n*m)\n    S2 = sparse(T(0.0)*I, n*m, n*m)\n    S3 = sparse(T(0.0)*I, n*m, n*m)\n    S4 = sparse(T(0.0)*I, n*m, n*m)\n\n    linear = LinearIndices((1:m, 1:n))\n    for i in 1:m\n        for j in 1:n\n            if i > 1\n                S1[linear[i, j], linear[i, j]] -= 1\n                S1[linear[i, j], linear[i - 1, j]] += 1\n            end\n            if j > 1\n                S2[linear[i, j], linear[i, j]] -= 1\n                S2[linear[i, j], linear[i, j - 1]] += +1\n            end\n            if i < m\n                S3[linear[i, j], linear[i, j]] -= 1\n                S3[linear[i, j], linear[i + 1, j]] += 1\n            end\n            if j < n\n                S4[linear[i, j], linear[i, j]] -= 1\n                S4[linear[i, j], linear[i, j + 1]] += +1\n            end\n        end\n    end\n    S1, S2, S3, S4\nend\n\nfunction boundary(A)\n    m, n = size(A)\n    B = zero(A)\n    for i in 1:m\n        for j in 1:n\n            v = A[i,j]\n            for (i2, j2) in ((i + 1, j), (i + 1, j +1 ), (i, j + 1))\n                if 1 <= i2 <= m && 1<= j2 <= n\n                    if v != A[i2, j2]\n                        B[i,j] = 1.0\n                        break\n                    end\n                end\n            end\n        end\n    end\n    B\nend\n\n\nfunction downop(T, m, n)\n    S = sparse(T(0.0)I, (n÷2)*(m÷2), n*m)\n    linearj = LinearIndices((1:m, 1:n))\n    lineari = LinearIndices((1:m÷2, 1:n÷2))\n\n    for i in 2:2:m\n        for j in 2:2:n\n            S[lineari[i÷2,j÷2], linearj[i, j]] = 1/4\n            S[lineari[i÷2,j÷2], linearj[i-1, j]] = 1/4\n            S[lineari[i÷2,j÷2], linearj[i, j-1]] = 1/4\n            S[lineari[i÷2,j÷2], linearj[i-1, j-1]] = 1/4\n        end\n    end\n    S\nend\n#=\nm = n = 8\nL = downop(F0, m, n); Λ = gridlaplacian(F0, m, n); Λ2 = gridlaplacian(F0, m÷2, n÷2)\nheatmap([Matrix(8L*Λ*L') Matrix(Λ2) Matrix(8L*Λ*L' - Λ2)])\nL = downop(F0, m, n); Λ = gridlaplacian(F0, m, n) + I/2; Λ2 = gridlaplacian(F0, m÷2, n÷2) + I\ninvm(x) = inv(Matrix(x))\nF = Float64\nL = downop(F, m, n); Λ = gridlaplacian(F, m, n)/2 + I/4; Λ2 = gridlaplacian(F, m÷2, n÷2) + I\nheatmap([Matrix(L*invm(Λ)*L') Matrix(invm(Λ2)) Matrix(L*invm(Λ)*L' - invm(Λ2))])\nmean(diag(L*invm(Λ)*L') - diag(invm(Λ2)))\n.32007- .32008\n=#\n", "meta": {"hexsha": "b4c73f563073546aa09d9c7c1817817cd9f13c71", "size": 3184, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/laplace.jl", "max_stars_repo_name": "mschauer/BridgeSPDE.jl", "max_stars_repo_head_hexsha": "f3634274ceb74526f58a930eae212bb4736d2780", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-02-13T10:16:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T22:35:43.000Z", "max_issues_repo_path": "src/laplace.jl", "max_issues_repo_name": "mschauer/BridgeSPDE.jl", "max_issues_repo_head_hexsha": "f3634274ceb74526f58a930eae212bb4736d2780", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/laplace.jl", "max_forks_repo_name": "mschauer/BridgeSPDE.jl", "max_forks_repo_head_hexsha": "f3634274ceb74526f58a930eae212bb4736d2780", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:18:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-05T22:35:49.000Z", "avg_line_length": 27.6869565217, "max_line_length": 93, "alphanum_fraction": 0.4378140704, "num_tokens": 1268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8615381952105442, "lm_q1q2_score": 0.7932954755356131}}
{"text": "function minkowski_distance(set1::Array, set2::Array, p::Int64)\n\n    @assert length(set1) == length(set2) \"Sets don't have the same length.\"\n\n    sum = zero(eltype(set1))\n\n    for i in 1:length(set1)\n        sum += abs(set2[i] - set1[i])^p\n    end\n\n    return sum^(1/p)\nend\n", "meta": {"hexsha": "c68c0a1faa1cfd13e8095a53215a900f5e458999", "size": 274, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MinkowskiDistance.jl", "max_stars_repo_name": "eRRe-i/MyDistanceSimilarityPKG.jl", "max_stars_repo_head_hexsha": "9c45e2da36eedcd2f230e5a2bdd4262ca18ed5f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MinkowskiDistance.jl", "max_issues_repo_name": "eRRe-i/MyDistanceSimilarityPKG.jl", "max_issues_repo_head_hexsha": "9c45e2da36eedcd2f230e5a2bdd4262ca18ed5f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MinkowskiDistance.jl", "max_forks_repo_name": "eRRe-i/MyDistanceSimilarityPKG.jl", "max_forks_repo_head_hexsha": "9c45e2da36eedcd2f230e5a2bdd4262ca18ed5f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0769230769, "max_line_length": 75, "alphanum_fraction": 0.6167883212, "num_tokens": 88, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9648551535992067, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7932934156135525}}
{"text": "# N = 10 # 2520\nN = 20 # 232792560\nfunction isPrime(n::Int)\n\tfor i in 2:ceil(sqrt(n))\n\t\tif n%i==0 && i!=n return false end\n\tend\n\treturn true\nend\nprimes = [x for x in 1:N if isPrime(x)]\nprint(primes)\n\nfunction factorize(n::Int)\n\tf = Int[]\n\twhile n > 1\n\t\tfor i in 2:n\n\t\t\tif n%i==0\n\t\t\t\tn /= i\n\t\t\t\tpush!(f, i)\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\tend\n\tf\nend\n#println(factorize(2520))\n\np = Dict((i, 0) for i in primes)\nfor i in 1:N\n\ts = factorize(i)\n\tc = Dict((i,0) for i in primes)\n\tfor j in s\n\t\tc[j] += 1\n\tend\n\tfor (k,v) in c\n\t\tp[k] = max(p[k], v)\n\tend\nend\nprintln(p)\nprod_p = 1\nfor (k, v) in p\n\tprod_p *= k^v\nend\nprintln(N, '\\t', prod_p)\n", "meta": {"hexsha": "14b8b20f2833da11b6e8fa6baf6d909cf1a02e54", "size": 623, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "algo/su.5.jl", "max_stars_repo_name": "cdluminate/MyNotes", "max_stars_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algo/su.5.jl", "max_issues_repo_name": "cdluminate/MyNotes", "max_issues_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algo/su.5.jl", "max_forks_repo_name": "cdluminate/MyNotes", "max_forks_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.1590909091, "max_line_length": 39, "alphanum_fraction": 0.5762439807, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.870597270087091, "lm_q1q2_score": 0.7932705617955559}}
{"text": "julia> sum([1,2,3,4,5].^2)\n55\n\njulia> sum([x^2 for x in [1,2,3,4,5]])\n55\n\njulia> mapreduce(x->x^2,+,[1:5])\n55\n\njulia> sum([x^2 for x in []])\n0\n", "meta": {"hexsha": "f4fb40571ea2799d16ec8545f86c1a9d1562dc60", "size": 143, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/sum-of-squares.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/sum-of-squares.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/sum-of-squares.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.9166666667, "max_line_length": 38, "alphanum_fraction": 0.5384615385, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8670357701094303, "lm_q1q2_score": 0.7932518540861915}}
{"text": "using DifferentialEquations\nusing Plots\nusing Markdown\n\ndescription = md\"\"\"\n\nSolve the Lorenz System:\n``dx/dt = σ(y-x),\n  dy/dt = x(ρ-z) -y,\n  dz/dt = xy - βz\n``\nwhere t∈[0,100] and u₀= [1.0, 0.0, 0.0]\n\n\"\"\"\ndisplay(description)\n\n\n# use in-place version (w/ ! symbol) so that\n# the number of array allocations is minimal\nfunction lorenz!(du, u, p, t)\n    x,y,z = u\n    σ, ρ, β = p\n    du[1] = σ*(y-x)\n    du[2] = x*(ρ-z) - y\n    du[3] = x*y - β*z\nend\n\n\n# define IC's, parameters, and time span\nu0 = [1.0; 0.0; 0.0]\np = [10.0; 28.0; 8/3]\ntspan = (0.0, 100.0)\n\n# solve the problem\nprob = ODEProblem(lorenz!, u0, tspan, p)\nsol = solve(prob)\n\n\n# visualize the result\np1 = plot(sol, vars=(1, 2, 3)) # i.e. plot x,y,z\np2 = plot(sol, vars=(0,2))\nplot(p1, p2)\n", "meta": {"hexsha": "0525aee6f9d1e0b6bf556dd58ba0a82a9b98bee8", "size": 751, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "DiffEqs/ODEs/SystemsOfEquations.jl", "max_stars_repo_name": "john-waczak/SciML-examples", "max_stars_repo_head_hexsha": "bed1fc7c7038f7676662540d5939465584978a85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DiffEqs/ODEs/SystemsOfEquations.jl", "max_issues_repo_name": "john-waczak/SciML-examples", "max_issues_repo_head_hexsha": "bed1fc7c7038f7676662540d5939465584978a85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DiffEqs/ODEs/SystemsOfEquations.jl", "max_forks_repo_name": "john-waczak/SciML-examples", "max_forks_repo_head_hexsha": "bed1fc7c7038f7676662540d5939465584978a85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4651162791, "max_line_length": 48, "alphanum_fraction": 0.5845539281, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298656, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7932210743091332}}
{"text": "function get_christoffel(x::TensorHead,TIT::TensorIndexType,metric::T ) where {T <: Tensor}\n    \"\"\"\n    returns christoffel symbols as ``Γ_{ijk}``\n    \"\"\"\n    @indices TIT i j k l\n    g = metric\n\n    simp(x) = contract_metric(x,TIT.metric)\n    gg = diff(g(-i,-j),x(k))\n    gg = simp(gg)\n\n    h = (gg(-i,-j,-k) - gg(-j,-k,-i) + gg(-k,-i,-j))/2\n    h = simp(h)\n\n    return h(-i,-j,-k)\nend\n\n\nfunction get_riemann(x::TensorHead,h::S,TIT::TensorIndexType,metric::T) where {S <: Tensor, T <: Tensor}\n    \"\"\"\n    compute Riemann curvature tensor as ``R_{ijkl}``\n    \"\"\"\n    @indices TIT i j k l m n\n    g = metric\n    simp(x) = contract_metric(x,TIT.metric)\n    dh = diff(h(-i,-j,-k),x(l))\n    dh = simp(dh)\n\n    hh = (TIT.metric(m,n)*h(-m,-i,-j))*h(-n,-k,-l)\n    hh = simp(hh)\n\n    Riemann = dh(-l,-i,-k,-j) - dh(-l,-j,-k,-i) + hh(-j,-k,-i,-l) - hh(-i,-k,-j,-l)\n    return Riemann\nend\n\n\"\"\"\n    Compute the Ricci tensor as ``R_{αβ}``\n\"\"\"\nfunction get_ricci(x::TensorHead, h::S, TIT::TensorIndexType, metric::T) where {S<:Tensor, T<:Tensor}\n    @indices TIT i j k l\n    g = metric\n    Riemann = get_riemann(x, h, TIT, metric)\n    Ricci = Riemann(-i, -j, -k, -l) * TIT.metric(i,k)\n    return Ricci\nend\n\n\"\"\"\nCompute the Ricci Scalar as ``R ≡ g^{μν}R_{μν}``\n\"\"\"\nfunction get_ricci_scalar(x::TensorHead, h::S, TIT::TensorIndexType, metric::T) where {S<:Tensor, T<:Tensor}\n    @indices TIT i j\n    g = metric\n    Ricci = get_ricci(x, h, TIT, metric)\n    R = Ricci(-i,-j)*TIT.metric(j,i)\n    return R\nend\n\n\"\"\"\nCompute the Einstein tensor as ``G^{μν} ≡ R^{μν} - \\frac{1}{2}⋅ g^{μν}R\n\"\"\"\nfunction get_einstein(x::TensorHead, h::S, TIT::TensorIndexType, metric::T) where {S<:Tensor, T<:Tensor}\n    @indices TIT i j\n    g = metric\n    R = get_ricci_scalar(x, h, TIT, metric)\n    Ricci = get_ricci(x, h, TIT, metric)\n    return Ricci(-i,-j) - 1/2*g(-i,-j)*R\nend\n\n\n", "meta": {"hexsha": "2c0fec103640225496de1647cf815c4ae8f4b8a8", "size": 1845, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gr.jl", "max_stars_repo_name": "LBJ-Wade/SymbolicTensors.jl", "max_stars_repo_head_hexsha": "e51922a784da96fe8cb9c5178a82fa3fec2db32a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2020-07-27T14:25:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T20:29:33.000Z", "max_issues_repo_path": "src/gr.jl", "max_issues_repo_name": "LBJ-Wade/SymbolicTensors.jl", "max_issues_repo_head_hexsha": "e51922a784da96fe8cb9c5178a82fa3fec2db32a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-07-15T03:29:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T22:29:00.000Z", "max_forks_repo_path": "src/gr.jl", "max_forks_repo_name": "LBJ-Wade/SymbolicTensors.jl", "max_forks_repo_head_hexsha": "e51922a784da96fe8cb9c5178a82fa3fec2db32a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-09-21T01:17:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T01:14:35.000Z", "avg_line_length": 26.3571428571, "max_line_length": 108, "alphanum_fraction": 0.5750677507, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075711974104, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7932210615309007}}
{"text": "function log(a::Real, x::Real, ε::Real)\n    z = x\n    t = 1\n    y = 0\n    while z > a || z < 1/a || t > ε   \n        if z > a\n            z /= a\n            y += t \n        elseif z < 1/a\n            z *= a\n            y -= t \n        else\n            t /= 2\n            z *= z \n        end\n    end\n    return y\nend", "meta": {"hexsha": "29256e806824efab2f5353e9ccf0bf500e9845c6", "size": 315, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "task_7_3.jl", "max_stars_repo_name": "Litger45/julia-algorithms-2", "max_stars_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "task_7_3.jl", "max_issues_repo_name": "Litger45/julia-algorithms-2", "max_issues_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "task_7_3.jl", "max_forks_repo_name": "Litger45/julia-algorithms-2", "max_forks_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5, "max_line_length": 39, "alphanum_fraction": 0.2825396825, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488963, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7932110411395568}}
{"text": "#softmax function: f(x)=exp(x)/sum(exp(x))\n\nFsoftmax(x::Array{Float64,2})=(exp(x)./sum(exp(x),1),[]) # TODO: better to subtract the max of x to make it numerically more stable\n\nfunction Fsoftmax_inplace(value,auxvalue,x::Array{Float64,2})\n    copy!(value,exp(x)./sum(exp(x),1)) # TODO: better to subtract the max of x to make it numerically more stable\nend\n          \nfunction Dsoftmax(derivativeIDX,f_c,faux_c,grad_c,grad_n,x::Array{Float64,2})\n    axpy!(1.0,f_c.*(grad_c-repmat(sum(f_c.*grad_c,1),size(f_c,1),1)),grad_n)\nend\n\n\n\nif PROC==\"GPU\"\n    \n    function Fsoftmax(X::CudaArray)\n        expX=CudaArray(Float64,size(X))\n        exp!(X,expX) \n        onr=CudaArray(Float64,(1,size(X,1))); fill!(onr,1.0);\n        colsum=onr*expX\n        onc=CudaArray(Float64,(size(X,1),1)); fill!(onc,1.0);\n        out=CudaArray(Float64,size(X))\n        vdiv!(1.0,expX,onc*colsum,out)\n        free(expX); free(onr); free(colsum); free(onc)\n        return (out,[]) # memory leak -- how to free out\n    end\n\n    function softmax!(X::CudaArray,out::CudaArray)\n        expX=CudaArray(Float64,size(X))\n        exp!(X,expX) \n        onr=CudaArray(Float64,(1,size(X,1))); fill!(onr,1.0);\n        colsum=onr*expX\n        onc=CudaArray(Float64,(size(X,1),1)); fill!(onc,1.0);\n        vdiv!(1.0,expX,onc*colsum,out)\n        free(expX); free(onr); free(colsum); free(onc)\n    end\n    export softmax!\n\n\n    function Fsoftmax_inplace(value,auxvalue,X::CudaArray)\n        expX=CudaArray(Float64,size(X))\n        exp!(X,expX) \n        onr=CudaArray(Float64,(1,size(X,1))); fill!(onr,1.0);\n        colsum=onr*expX\n        onc=CudaArray(Float64,(size(X,1),1)); fill!(onc,1.0);\n        vdiv!(1.0,expX,onc*colsum,value)\n        free(expX); free(onr); free(colsum); free(onc)\n    end\n\n\n    function Dsoftmax(derivativeIDX,f_c,faux_c,grad_c,grad_n,x::CudaArray)\n        tmp=CudaArray(Float64,size(f_c))\n        vmult!(1.0,f_c,grad_c,tmp)\n        onr=CudaArray(Float64,(1,size(tmp,1))); fill!(onr,1.0);\n        colsum=onr*tmp\n        onc=CudaArray(Float64,(size(tmp,1),1)); fill!(onc,1.0);\n        copy!(tmp,grad_c)\n        axpy!(-1.0,onc*colsum,tmp)\n        vmult!(1.0,f_c,tmp,tmp)\n        axpy!(1.0,tmp,grad_n)\n        free(tmp); free(onr); free(onc);\n    end\n    \nend\n\n\n\n\nDerivative[Fsoftmax]=Dsoftmax\nInplace[Fsoftmax]=Fsoftmax_inplace\n\nADsoftmax(n)=ADnode(Fsoftmax,n)\n\nsoftmax(n::ADnode)=ADnode(Fsoftmax,n)\nsoftmax(x::Array)=exp(x)./sum(exp(x),1) # TODO: better to subtract the max of x to make it numerically more stableFsoftmax(x)\n\nexport softmax\n", "meta": {"hexsha": "4599eca344acdd7405002de3e38595693599be72", "size": 2521, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/Fsoftmax.jl", "max_stars_repo_name": "davidbarber/AutoDiff", "max_stars_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2016-03-20T20:52:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T07:31:59.000Z", "max_issues_repo_path": "src/functions/Fsoftmax.jl", "max_issues_repo_name": "davidbarber/AutoDiff", "max_issues_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-06-17T20:12:48.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-17T20:12:48.000Z", "max_forks_repo_path": "src/functions/Fsoftmax.jl", "max_forks_repo_name": "davidbarber/AutoDiff", "max_forks_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-01-11T21:36:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-06T21:04:40.000Z", "avg_line_length": 31.9113924051, "max_line_length": 131, "alphanum_fraction": 0.6239587465, "num_tokens": 842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.793211034923567}}
{"text": "module Utility\n\nusing LinearAlgebra\nusing Statistics, StatsBase\n\nexport sinkhorn\n\n\"\"\"\n    sinkhorn(A; r=[], c=[], maxit=1000, δ=1e-6, verbose=false)\n\nCompute the row and column multiplicative factors that constrain marginals of `A` to unity.\nReturns a boolean flag if algorithm converges within tolerance `δ` within `maxit` iterations.\nIf `r` is given and non-empty, row marginals will be constrained to user-supplied inputs.\nIf `c` is given and non-empty, column marginals will be constrained to user-supplied inputs.\n\"\"\"\nfunction sinkhorn(A; r=[], c=[], maxit=1000, δ=1e-6, verbose=false)\n    if length(r) == 0\n        r = size(A,2)\n    end\n\n    if length(c) == 0\n        c = size(A,1)\n    end\n\n    x = ones(size(A,1))\n    y = ones(size(A,2))\n    for i ∈ 1:maxit\n        δr = maximum(abs.(x.*(A*y)  .- r))\n        δc = maximum(abs.(y.*(A'*x) .- c))\n\n        if verbose\n            @show minimum(A'*x), minimum(A*y)\n            @show r, c\n            @show i, δr, δc\n        end\n\n        (isnan(δr) || isnan(δc)) && return x, y, false\n        (δr < δ && δc < δ) \t\t && return x, y, true\n\n        y = c ./ (A'*x)\n        x = r ./ (A*y)\n        if verbose\n            @show mean(x), mean(y)\n        end\n    end\n\n    return x, y, false\nend\n\nfunction sinkhorn(N, ϕ; maxit=1000, δ=1e-6, verbose=false)\n    nrow = size(N,1)\n    ncol = size(N,2)\n\n    N² = N.^2\n    u, v = ones(size(N,1)), ones(size(N,2))\n    for i ∈ 1:maxit\n        σ² = ((Diagonal(u.^2 ./ (1 .+ ϕ))*N²*Diagonal(v.^2)) .+ (Diagonal(u.*ϕ ./ (1 .+ ϕ))*N*Diagonal(v)))\n        δr = maximum(abs.(sum(σ², dims=1) .- nrow))\n        δc = maximum(abs.(sum(σ², dims=2) .- ncol))\n\n        if verbose\n            @show i, δr, δc\n        end\n\n        (isnan(δr) || isnan(δc)) && return u, v, false\n        (δr < δ && δc < δ) \t\t && return u, v, true\n\n        A = vec(sum(Diagonal(u.^2 ./ (1 .+ ϕ)) * N², dims=1))\n        B = vec(sum(Diagonal(u.*ϕ ./ (1 .+ ϕ)) * N , dims=1))\n\n        v = @. (sqrt(B^2 + 4*A*nrow) - B) / (2*A)\n\n        A = vec(sum(N² * Diagonal(v.^2),           dims=2))\n        B = vec(sum(Diagonal(ϕ) * N * Diagonal(v), dims=2))\n\n        u = @. (sqrt(B^2 + 4*A*ncol*(1+ϕ)) - B) / (2*A)\n    end\n\n    return u, v, false\nend\n\nend\n", "meta": {"hexsha": "779b7a80e9a54649e779607e885ea671ba568869", "size": 2192, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/util.jl", "max_stars_repo_name": "nnoll/seqspace", "max_stars_repo_head_hexsha": "ec2165fbe80af1280ef7c69071f472d13977d5d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/util.jl", "max_issues_repo_name": "nnoll/seqspace", "max_issues_repo_head_hexsha": "ec2165fbe80af1280ef7c69071f472d13977d5d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util.jl", "max_forks_repo_name": "nnoll/seqspace", "max_forks_repo_head_hexsha": "ec2165fbe80af1280ef7c69071f472d13977d5d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4096385542, "max_line_length": 107, "alphanum_fraction": 0.5114051095, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.793188279274689}}
{"text": "# Logistic Regression Module with CUDA support\n# Logistic Regression Module\nmodule LogRegGPU\nexport train, predict, predict_proba, scale, cost, accuracy\n\nusing CUDA\nimport Random\nimport Statistics\n\nCUDA.allowscalar(false)\n\n\"\"\"\nHelper function to scale input `X` to unit variance\\\\\n`X` is required to have dimension 2\n\"\"\"\nfunction scale(X::Array)::Array\n    @assert ndims(X) == 2\n    u = Statistics.mean(X, dims=1)\n    s = Statistics.std(X, dims=1)\n    res = (X .- u) ./ s\n    return res\nend\n\n\"\"\"\nSigmoid function on array `Z`\n\"\"\"\nfunction sigmoid(Z::CuArray)::CuArray\n    denom = 1 .+ (Float32(MathConstants.e) .^ (-Z))\n    return 1 ./ denom\nend\n\n\"\"\"\nCost function for logistic Regression\\\\\nIf `X` is shape (M, N)\\\\\n`y` should be (M,)\\\\\n`beta` can be (N,) or (N+1,)\n------\nMay not be used\n\"\"\"\nfunction cost(X::CuArray, y::CuArray, beta::CuArray)::AbstractFloat\n    @assert ndims(X) == 2\n    @assert ndims(y) == 1\n    @assert ndims(beta) == 1\n    @assert size(X)[1] == size(y)[1]\n    @assert size(X)[2] == size(beta)[1] || size(X)[2] == size(beta)[1] - 1\n    if size(X)[2] < size(beta)[1]\n        X = hcat(X, ones(size(X)[1]))\n    end\n    m = size(X)[1]\n    X_combined = X * beta\n    prob = sigmoid(X_combined)\n    vec = y .* (log.(prob)) .+ (1 .- y) .* (log.(1 .- prob))\n    cost = -1 / Float32(m) * sum(vec)\n    return cost\nend\n\nfunction cost(X::Array, y::Array, beta::Array)::AbstractFloat\n    @assert ndims(X) == 2\n    @assert ndims(y) == 1\n    @assert ndims(beta) == 1\n    @assert size(X)[1] == size(y)[1]\n    @assert size(X)[2] == size(beta)[1] || size(X)[2] == size(beta)[1] - 1\n    if size(X)[2] < size(beta)[1]\n        X = hcat(X, ones(size(X)[1]))\n    end\n    X = CUDA.CuArray(Float32.(X))\n    y = CUDA.CuArray(Float32.(y))\n    beta = CUDA.CuArray(Float32.(beta))\n    m = size(X)[1]\n    X_combined = X * beta\n    prob = sigmoid(X_combined)\n    vec = y .* (log.(prob)) .+ (1 .- y) .* (log.(1 .- prob))\n    cost = -1 / float(m) * sum(vec)\n    CUDA.reclaim()\n    return cost\nend\n\n\"\"\"\nPredict function for Logistic Regression\\\\\nIf `X` is shape (M, N)\\\\\n`beta` can be (N,) or (N+1,)\\\\\nReturns 1d array of real probabilities\n\"\"\"\nfunction predict_proba(X::CuArray, beta::CuArray)::CuArray\n    @assert ndims(X) == 2\n    @assert ndims(beta) == 1\n    @assert size(X)[2] == size(beta)[1] || size(X)[2] == size(beta)[1] - 1\n    if size(X)[2] < size(beta)[1]\n        X = hcat(X, ones(size(X)[1]))\n    end\n    X_combined = X * beta\n    prob = sigmoid(X_combined)\n    return prob\nend\n\nfunction predict_proba(X::Array, beta::Array)::Array\n    @assert ndims(X) == 2\n    @assert ndims(beta) == 1\n    @assert size(X)[2] == size(beta)[1] || size(X)[2] == size(beta)[1] - 1\n    if size(X)[2] < size(beta)[1]\n        X = hcat(X, ones(size(X)[1]))\n    end\n    X = CUDA.CuArray(Float32.(X))\n    beta = CUDA.CuArray(Float32.(beta))\n    X_combined = X * beta\n    prob = sigmoid(X_combined)\n    prob_cpu = Array(prob)\n    CUDA.reclaim()\n    return prob_cpu\nend\n\n\"\"\"\nPredict function for Logistic Regression\\\\\nIf `X` is shape (M, N)\\\\\n`beta` can be (N,) or (N+1,)\\\\\nReturns 1d array of 0,1\n\"\"\"\nfunction predict(X::CuArray, beta::CuArray)::CuArray\n    @assert ndims(X) == 2\n    @assert ndims(beta) == 1\n    @assert size(X)[2] == size(beta)[1] || size(X)[2] == size(beta)[1] - 1\n    if size(X)[2] < size(beta)[1]\n        X = hcat(X, ones(size(X)[1]))\n    end\n    X_combined = X * beta\n    prob = sigmoid(X_combined)\n    real_prob::CuArray = map(m -> m >= 0.5 ? 1.0 : 0.0, prob)\n    return real_prob\nend\n\nfunction predict(X::Array, beta::Array)::Array\n    @assert ndims(X) == 2\n    @assert ndims(beta) == 1\n    @assert size(X)[2] == size(beta)[1] || size(X)[2] == size(beta)[1] - 1\n    if size(X)[2] < size(beta)[1]\n        X = hcat(X, ones(size(X)[1]))\n    end\n    X = CUDA.CuArray(Float32.(X))\n    beta = CUDA.CuArray(Float32.(beta))\n    X_combined = X * beta\n    prob = sigmoid(X_combined)\n    prob_cpu = Array(prob)\n    real_prob::Array = map(m -> m >= 0.5 ? 1.0 : 0.0, prob_cpu)\n    CUDA.reclaim()\n    return real_prob\nend\n\n\"\"\"\nLearning function for Gradient Descent\\\\\nIf `X` is shape (M, N)\\\\\n`y` should be (M,)\\\\\n`beta` should be (N,)\n------\nReturns `nothing`\n------\nNote: `beta` will be updated inplace\n\"\"\"\nfunction learn!(X::CuArray, y::CuArray, beta::CuArray, momentum::CuArray, alpha::AbstractFloat)\n    @assert ndims(X) == 2\n    @assert ndims(y) == 1\n    @assert ndims(beta) == 1\n    @assert size(X) == (size(y)[1], size(beta)[1])\n    predictions = predict_proba(X, beta)\n    offset = predictions .- y\n    gradients = X' * offset\n    gradients .= gradients ./ size(X)[1]\n    gradients .= gradients .* alpha\n    momentum .= gradients .+ (0.9 .* momentum)\n    beta .= beta .- momentum\n    return nothing\nend\n\n\"\"\"\nTraining function for Logisitic Regression\\\\\nImplemented using Gradient Descent\\\\\nIf `X` is shape (M, N)\\\\\n`y` should be (M,)\\\\\n`max_iter` should be >= 0\n------\nReturns `beta` in shape (N+1,)\n\n------\nSet `early_stop` to `false`, to force run maximum iteractions\\\\\nSet `random_weights` to `false` to initialize weights of 0.0\n\"\"\"\nfunction train(X::Array, y::Array; learning_rate::AbstractFloat=0.1, max_iter::Integer=1000,\n        n_iter_no_change::Integer=5, tol::AbstractFloat=0.001, verbose::Bool=false,\n        shuffle::Bool=true, early_stop::Bool=true, random_weights::Bool=true)::Array\n    @assert ndims(X) == 2\n    @assert ndims(y) == 1\n    @assert size(X)[1] == size(y)[1]\n    @assert max_iter >= 0\n    @assert n_iter_no_change >= 0\n    @assert tol >= 0.0\n    tol = Float32(tol)\n    X = hcat(X, ones(size(X)[1])) # for constant multiplication\n    X .= Float32.(X)\n    y = Float32.(y)\n    if shuffle\n        JuTools.shuffle_data!(X, y)\n    end\n    X = CUDA.CuArray(X)\n    y = CUDA.CuArray(y)\n    beta = nothing\n    if random_weights\n        beta = CuArray(Random.randn(size(X)[2]))\n    else\n        beta = CuArray(zeros(size(X)[2]))\n    end\n    momentum = CuArray(zeros(size(X)[2]))\n    best_cost = nothing\n    n_cost_no_change = n_iter_no_change\n    for i = 1:max_iter\n        if n_cost_no_change <= 0 && early_stop\n            break\n        end\n        learn!(X, y, beta, momentum, learning_rate)\n        new_cost = cost(X, y, beta)\n        if verbose\n            acc = accuracy(predict(X, beta), y)\n            println(\"Iter: \", i)\n            println(\"Cost = \", new_cost)\n            println(\"Accuracy = \", acc)\n            println()\n        end\n        if early_stop\n            if best_cost === nothing || isnan(best_cost)\n                best_cost = new_cost\n            else\n                if new_cost > best_cost - tol\n                    n_cost_no_change -= 1\n                else\n                    best_cost = min(new_cost, best_cost)\n                    n_cost_no_change = n_iter_no_change\n                end\n            end\n        end\n    end\n    beta_cpu = Array(beta)\n    CUDA.reclaim()\n    return beta_cpu\nend\n\n\"\"\"\nAccuracy function for Logisitic Regression\\\\\n`y_pred` and `y_real` should have same shape, 1d array\n------\nReturns accuracy as float\n\"\"\"\nfunction accuracy(y_pred::Array, y_real::Array)::AbstractFloat\n    @assert ndims(y_pred) == ndims(y_real) == 1\n    @assert size(y_pred) == size(y_real)\n    acc = Statistics.mean(float.(y_pred) .== float.(y_real))\n    return acc\nend\n\nfunction accuracy(y_pred::CuArray, y_real::CuArray)::AbstractFloat\n    @assert ndims(y_pred) == ndims(y_real) == 1\n    @assert size(y_pred) == size(y_real)\n    acc = Statistics.mean(y_pred .== y_real)\n    return acc\nend\n\nend", "meta": {"hexsha": "09eee55b5eabb64d6c131199b98123bec9735953", "size": 7437, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Logistic_Regression/script_gpu.jl", "max_stars_repo_name": "teamclouday/JuliaLearn", "max_stars_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Logistic_Regression/script_gpu.jl", "max_issues_repo_name": "teamclouday/JuliaLearn", "max_issues_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Logistic_Regression/script_gpu.jl", "max_forks_repo_name": "teamclouday/JuliaLearn", "max_forks_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1704545455, "max_line_length": 95, "alphanum_fraction": 0.5878714535, "num_tokens": 2312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7931882760092392}}
{"text": "function randOrth(d)\n    q = Matrix(qr(randn(d,d)).Q)\n    q = q * Diagonal(rand([1;-1],d))\n    return q\nend\n\n\"\"\"\n    Q = randOrth(d, pert)\n\nProduces a random orthogonal matrix close to I.\nThe smaller pert is, the closer to I.\nThe diagonals are always positive.\n\"\"\"\nfunction randOrth(d, pert)\n    q = Matrix(qr(eye(d)+pert*randn(d,d)).Q)\n    q = q * Diagonal(sign.(diag(q)))\n    return q\nend\n\nfunction randFullBDD(n,d)\n    A = triu([randOrth(d) for i in 1:n, j in 1:n],1)\n    for i in 1:n\n        A[i,i] = eye(d)*(0.001 + (n-1)/2)\n    end\n    B = BlockCSC(A)\n    B = B + transpose(B)\nend\n\nfunction randOrthWt(a,d)\n    #deg = sum(a,dims=1)\n    n = size(a,1)\n    ai,aj,av = findnz(triu(a))\n    vq = [randOrth(d)*av[i] for i in 1:length(av)]\n\n    ai = vcat(ai,[n])\n    aj = vcat(aj,[n])\n    vq = vcat(vq,[zeros(d,d)])\n\n    B = BlockCSC(sparse([ai;aj],[aj;ai],[vq;collect.(transpose.(vq))],n,n))\n    #B = B + transpose(B)\n\n    E = one(typeof(B[1,1]))\n\n    sp = BlockCSC(sparse(1:n,1:n,[E*sum(opnorm.(a[:,i])) for i in 1:n]))\n\n    return B + sp\nend\n\n\"\"\"\n    B = randOrthWtPotential(a,d, pert)\n\nProduces a bdd matrix with orthogonal matrices, slightly perturbed from a potential.\nIf the potential is zero, then the resulting matrix is singular.\nNote that if there are very few edges, then the matrix can be singular anyway.\nThis motivates randBDDWtPotential, which is never singular.\n\"\"\"\nfunction randOrthWtPotential(a,d, pert)\n    #deg = sum(a,dims=1)\n    n = size(a,1)\n    ai,aj,av = findnz(triu(a))\n\n    vr = [randOrth(d) for i in 1:n]\n\n    vq = [-vr[ai[i]]*vr[aj[i]]'*randOrth(d,pert)*av[i] for i in 1:length(av)]\n\n    ai = vcat(ai,[n])\n    aj = vcat(aj,[n])\n    vq = vcat(vq,[zeros(d,d)])\n\n    B = BlockCSC(sparse(ai,aj,vq,n,n))\n    B = B + transpose(B)\n\n    dg = [eye(d)*sum(opnorm.(B[:,i])) for i in 1:n]\n    B = B + BlockCSC(sparse(Diagonal(dg)))\nend\n\nfunction randBDDWtPotential(a,d, pert)\n    #deg = sum(a,dims=1)\n    n = size(a,1)\n    ai,aj,av = findnz(triu(a))\n\n    vr = [randOrth(d) for i in 1:n]\n\n    vq = [(-vr[ai[i]]*vr[aj[i]]' + randn(d,d)*pert)*av[i] for i in 1:length(av)]\n\n    ai = vcat(ai,[n])\n    aj = vcat(aj,[n])\n    vq = vcat(vq,[zeros(d,d)])\n\n    B = BlockCSC(sparse(ai,aj,vq,n,n))\n    B = B + transpose(B)\n\n    dg = [eye(d)*sum(opnorm.(B[:,i])) for i in 1:n]\n    B = B + BlockCSC(sparse(Diagonal(dg)))\nend\n\nfunction randBDDWt(a,d)\n    n = size(a,1)\n    ai,aj,av = findnz(triu(a))\n    vq = [randn(d,d) for i in 1:length(av)]\n    ai = vcat(ai,[n])\n    aj = vcat(aj,[n])\n    vq = vcat(vq,[zeros(d,d)])\n    B = BlockCSC(sparse(ai,aj,vq,n,n))\n    B = B + transpose(B)\n\n    dg = [eye(d)*sum(opnorm.(B[:,i])) for i in 1:n]\n    B = B + BlockCSC(sparse(Diagonal(dg)))\nend\n", "meta": {"hexsha": "0d5a77f3f5ffb202729f4484dafab01a0e7d275f", "size": 2683, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/generators.jl", "max_stars_repo_name": "danspielman/BDDSolver.jl", "max_stars_repo_head_hexsha": "3fff5d6bf378da67ff3d018ae8743e06caab8bf3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/generators.jl", "max_issues_repo_name": "danspielman/BDDSolver.jl", "max_issues_repo_head_hexsha": "3fff5d6bf378da67ff3d018ae8743e06caab8bf3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-07-29T13:34:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-29T13:34:00.000Z", "max_forks_repo_path": "src/generators.jl", "max_forks_repo_name": "danspielman/BDDSolver.jl", "max_forks_repo_head_hexsha": "3fff5d6bf378da67ff3d018ae8743e06caab8bf3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3909090909, "max_line_length": 84, "alphanum_fraction": 0.5736116288, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7931882731684803}}
{"text": "## Show the effect of seeded PageRank on MNIST\n\n## Load the MNIST Graph and draw it\n##\nusing DelimitedFiles\nusing SparseArrays\nusing LinearAlgebra\nei,ej = copy.(eachcol(Int.(readdlm(\"mnist-train-4.edges\"))))\nxy = readdlm(\"mnist-train-4.xy\")\nn = maximum(ei)\nA = sparse(ei,ej,1,n,n)\n@assert issymmetric(A)\n\n##\n## Simple PageRank\nfunction simplepagerank(A,α,v)\n  @assert(0 ≤ α < 1, \"needs probably α\")\n  @assert(all(vi -> vi ≥ 0, v), \"needs non-negative v\")\n  v = v ./ sum(v) # we can normalize for them.\n  d = vec(sum(A,dims=2)) # compute the degrees\n  x = copy(v) # start of with v\n  nsteps = 2*ceil(Int,log(eps(1.0))/log(α)) # upper bound on steps\n  for i=1:nsteps\n    x = α*(A'*(x./d)) .+ (1-α).*v\n  end\n  return x/sum(x) # renormalize to probability\nend\n\n## Let's show global pagerank first\npr = simplepagerank(A,0.85,ones(n)./n)\n## Now show the entire graph\nusing GraphRecipes\nusing LinearAlgebra\nusing Plots\n\nei, ej = findnz(A)\ngraphplot(ei, ej, x =xy[:,1], y=xy[:,2],\n  markercolor=:black, markerstrokecolor=:white,\n  size=(1200,1200),dpi=300,\n  markersize=0, linecolor=1, linealpha=0.2, linewidth=0.5,\n  markeralpha=0.2,colorbar=false,\n  axis_buffer=0.02, background=nothing)\np=sortperm(pr)\nscatter!(xy[p,1],xy[p,2],marker_z=-abs.(log10.(pr[p])).^0.5,markerstrokewidth=0,alpha=0.5)\nsavefig(\"pagerank-mnist.png\")\n## now show Seeded PageRank\nv = zeros(n)\nv[1] = 1\npr = simplepagerank(A,0.85,v)\n\nusing GraphRecipes\nusing LinearAlgebra\nusing Plots\n\nei, ej = findnz(A)\ngraphplot(ei, ej, x =xy[:,1], y=xy[:,2],\n  markercolor=:black, markerstrokecolor=:white,\n  size=(1200,1200),dpi=300,\n  markersize=0, linecolor=1, linealpha=0.2, linewidth=0.5,\n  markeralpha=0.2,colorbar=false,\n  axis_buffer=0.02, background=nothing)\np=sortperm(pr)\nscatter!(xy[p,1],xy[p,2],marker_z=-abs.(log10.(pr[p])).^0.5,markerstrokewidth=0,alpha=0.5)\nsavefig(\"seeded-pagerank-mnist.png\")\n\n##\n## Try the same set of nodes labeled 1 as we used for the least squares exampmle.\nusing MLDatasets\ntrain_x, train_y = MNIST.traindata()\nnlabels = 10\nS = findall(train_y .== 1)[1:nlabels]\n##\nv = zeros(n)\nv[S] .= 1/length(S)\npr = simplepagerank(A,0.85,v)\nei, ej = findnz(A)\ngraphplot(ei, ej, x =xy[:,1], y=xy[:,2],\n  markercolor=:black, markerstrokecolor=:white,\n  size=(1200,1200),dpi=300,\n  markersize=0, linecolor=1, linealpha=0.2, linewidth=0.5,\n  markeralpha=0.2,colorbar=false,\n  axis_buffer=0.02, background=nothing)\np=sortperm(pr)\nscatter!(xy[p,1],xy[p,2],marker_z=-abs.(log10.(pr[p])).^0.5,markerstrokewidth=0,alpha=0.5)\nsavefig(\"seeded-pagerank-mnist-set-1.png\")\n\n##\nv = zeros(n)\nv[S] .= 1/length(S)\npr = simplepagerank(A,0.5,v)\nei, ej = findnz(A)\ngraphplot(ei, ej, x =xy[:,1], y=xy[:,2],\n  markercolor=:black, markerstrokecolor=:white,\n  size=(1200,1200),dpi=300,\n  markersize=0, linecolor=1, linealpha=0.2, linewidth=0.5,\n  markeralpha=0.2,colorbar=false,\n  axis_buffer=0.02, background=nothing)\np=sortperm(pr)\nscatter!(xy[p,1],xy[p,2],marker_z=-abs.(log10.(pr[p])).^0.5,markerstrokewidth=0,alpha=0.5)\nsavefig(\"seeded-pagerank-mnist-set-1-alpha-half.png\")\n\n##\nv = zeros(n)\nv[S] .= 1/length(S)\npr = simplepagerank(A,0.99,v)\nei, ej = findnz(A)\ngraphplot(ei, ej, x =xy[:,1], y=xy[:,2],\n  markercolor=:black, markerstrokecolor=:white,\n  size=(1200,1200),dpi=300,\n  markersize=0, linecolor=1, linealpha=0.2, linewidth=0.5,\n  markeralpha=0.2,colorbar=false,\n  axis_buffer=0.02, background=nothing)\np=sortperm(pr)\nscatter!(xy[p,1],xy[p,2],marker_z=-abs.(log10.(pr[p])).^0.5,markerstrokewidth=0,alpha=0.5)\nsavefig(\"seeded-pagerank-mnist-set-1-alpha-99.png\")\n", "meta": {"hexsha": "474096a782d077683380462a984b16490531c050", "size": 3527, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5-unit-4-demos/seeded-pagerank-mnist.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "5-unit-4-demos/seeded-pagerank-mnist.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5-unit-4-demos/seeded-pagerank-mnist.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 30.4051724138, "max_line_length": 90, "alphanum_fraction": 0.6881202155, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.7931436950289197}}
{"text": "\"\"\"\nHigh-order singular value decomposition (HO-SVD).\n\"\"\"\nfunction hosvd(tensor::AbstractArray{T,N}, core_dims::NTuple{N, Int};\n               pad_zeros::Bool=false, compute_error::Bool=false) where {T,N}\n    pad_zeros || _check_tensor(tensor, core_dims)\n\n    factors = map(1:N) do i\n        X = _col_unfold(tensor, i)\n        f = eigen(Symmetric(X'X), max(1, size(X,2)-core_dims[i]+1):size(X,2)).vectors\n        if pad_zeros && size(f, 2) < core_dims[i] # fill missing factors with zeros\n            f = hcat(f, zeros(T, size(tensor, i), core_dims[i]-size(f, 2)))\n        end\n        mapslices(_check_sign, f, dims=1)\n    end\n\n    res = Tucker(factors, tensorcontractmatrices(tensor, factors))\n    compute_error && _set_rel_residue(res, tensor)\n    return res\nend\n\nhosvd(tensor::AbstractArray, r::Int;\n      pad_zeros::Bool=false, compute_error::Bool=false) =\n    hosvd(tensor, ntuple(_ -> r, ndims(tensor)),\n          pad_zeros=pad_zeros, compute_error=compute_error)\n", "meta": {"hexsha": "7cc26c2c12e6c2c348c4e38eee4fbce630650a4e", "size": 970, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hosvd.jl", "max_stars_repo_name": "UnofficialJuliaMirror/TensorDecompositions.jl-04ed911b-6d5f-4088-a74e-60d2d5028204", "max_stars_repo_head_hexsha": "f80f007e3a90164d9b1dbb3abbb710403d843269", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hosvd.jl", "max_issues_repo_name": "UnofficialJuliaMirror/TensorDecompositions.jl-04ed911b-6d5f-4088-a74e-60d2d5028204", "max_issues_repo_head_hexsha": "f80f007e3a90164d9b1dbb3abbb710403d843269", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hosvd.jl", "max_forks_repo_name": "UnofficialJuliaMirror/TensorDecompositions.jl-04ed911b-6d5f-4088-a74e-60d2d5028204", "max_forks_repo_head_hexsha": "f80f007e3a90164d9b1dbb3abbb710403d843269", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3076923077, "max_line_length": 85, "alphanum_fraction": 0.6494845361, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.793143681191426}}
{"text": "using QuantEcon\r\n\r\n\"\"\"\r\nThe data for a consumption problem, including some default values.\r\n\"\"\"\r\nstruct ConsumptionProblem{TF<:AbstractFloat}\r\n    beta::TF\r\n    y::Vector{TF}\r\n    b0::TF\r\n    P::Matrix{TF}\r\nend\r\n\r\n\"\"\"\r\nParameters\r\n----------\r\n\r\nbeta : discount factor\r\nP    : 2x2 transition matrix\r\ny    : Array containing the two income levels\r\nb0   : debt in period 0 (= state_1 debt level)\r\n\"\"\"\r\nfunction ConsumptionProblem(;\r\n                 beta = 0.96,\r\n                 y = [2.0, 1.5],\r\n                 b0 = 3.0,\r\n                 P = [0.8 0.2;\r\n                      0.4 0.6])\r\n\r\n    ConsumptionProblem(beta, y, b0, P)\r\nend\r\n\r\n\"\"\"\r\nComputes endogenous values for the complete market case.\r\n\r\nParameters\r\n----------\r\n\r\ncp : instance of ConsumptionProblem\r\n\r\nReturns\r\n-------\r\n\r\n    c_bar : constant consumption\r\n    b1    : rolled over b0\r\n    b2    : debt in state_2\r\n\r\nassociated with the price system\r\n\r\n    Q = beta * P\r\n\r\n\"\"\"\r\n\r\nfunction consumption_complete(cp::ConsumptionProblem)\r\n\r\n    beta, P, y, b0 = cp.beta, cp.P, cp.y, cp.b0  # Unpack\r\n\r\n    y1, y2 = y          # extract income levels\r\n    b1 = b0             # b1 is known to be equal to b0\r\n    Q = beta * P        # assumed price system\r\n\r\n    # Using equation (7) calculate b2\r\n    b2 = (y2 - y1 - (Q[1, 1] - Q[2, 1] - 1) * b1)/(Q[1, 2] + 1 - Q[2, 2])\r\n\r\n    # Using equation (5) calculae c_bar\r\n    c_bar = y1 - b0 + ([b1 b2] * Q[1, :] )[1]\r\n\r\n    return c_bar, b1, b2\r\nend\r\n\r\n\"\"\"\r\nComputes endogenous values for the incomplete market case.\r\n\r\nParameters\r\n----------\r\n\r\ncp : instance of ConsumptionProblem\r\nN_simul : Integer\r\n\r\n\"\"\"\r\nfunction consumption_incomplete(cp::ConsumptionProblem;\r\n                                N_simul::Integer=150)\r\n\r\n    beta, P, y, b0 = cp.beta, cp.P, cp.y, cp.b0  # Unpack\r\n    # For the simulation define a quantecon MC class\r\n    mc = MarkovChain(P)\r\n\r\n    # Useful variables\r\n    y = y''\r\n    v = inv(eye(2) - beta * P) * y\r\n\r\n    # Simulat state path\r\n    s_path = simulate(mc, N_simul, init = 1)\r\n\r\n    # Store consumption and debt path\r\n    b_path, c_path = ones(N_simul + 1), ones(N_simul)\r\n    b_path[1] = b0\r\n\r\n    # Optimal decisions from (12) and (13)\r\n    db = ((1 - beta) * v - y) / beta\r\n\r\n    for (i, s) in enumerate(s_path)\r\n        c_path[i] = (1 - beta) * (v - b_path[i] * ones(2, 1))[s, 1]\r\n        b_path[i + 1] = b_path[i] + db[s, 1]\r\n    end\r\n\r\n    return c_path, b_path[1:end-1], y[s_path], s_path\r\nend\r\n", "meta": {"hexsha": "8b276ad507cccda00ba873fd6d084d776df4aa53", "size": 2438, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "smoothing/smoothing_actions.jl", "max_stars_repo_name": "parkjt0506/QuantEconPractice", "max_stars_repo_head_hexsha": "2d83848dab7ed8d40efc9bbcf1e73aed7e5e532f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "smoothing/smoothing_actions.jl", "max_issues_repo_name": "parkjt0506/QuantEconPractice", "max_issues_repo_head_hexsha": "2d83848dab7ed8d40efc9bbcf1e73aed7e5e532f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "smoothing/smoothing_actions.jl", "max_forks_repo_name": "parkjt0506/QuantEconPractice", "max_forks_repo_head_hexsha": "2d83848dab7ed8d40efc9bbcf1e73aed7e5e532f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5740740741, "max_line_length": 74, "alphanum_fraction": 0.5434782609, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8740772351648677, "lm_q1q2_score": 0.7930609534968264}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.5\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6e58a278-ede3-440f-b5ad-c23d03833918\nusing LinearAlgebra\n\n# ╔═╡ 81465bdf-4eb3-4dc5-8f60-2ccdca956e73\nmd\"#### Sigmoid\"\n\n# ╔═╡ 78b943f0-ae7b-11eb-3de1-d5cfb31433c6\nfunction σ(x)\n\tt = exp(-abs(x))\n\treturn ifelse(x ≥ 0, inv(1 + t), t / (1 + t))\nend\n\n# ╔═╡ 6fe8d0a2-fd10-4097-95c8-fea57d2a32e8\nconst sigmoid = σ\n\n# ╔═╡ 112f4771-632e-4c35-81bd-ec7f09b40dc0\nmd\"#### ReLU\"\n\n# ╔═╡ 257e3608-759e-49b2-aa9f-88211bba198b\nrelu(x) = max(zero(x), x)\n\n# ╔═╡ 5b4291e3-1f67-46ac-89f5-d00aaefdac8a\nsigmoid(4) == σ(4)\n\n# ╔═╡ 45ba9913-5316-457e-9f97-2622661397e1\nbegin\n\tinputs = [1, 2, 3, 2.5]\n\tweights = [0.2, 0.8, -0.5, 1.0]\n\tbias = 2.0\n\t\n\t(\n\t\tσ(weights ⋅ inputs + bias),\n\t\trelu(weights ⋅ inputs + bias)\n\t)\nend\n\n# ╔═╡ e2f8442b-5ccd-431a-8881-3e746b0eb047\nbegin\n\t#inputs = [1, 2, 3, 2.5]\n\tweights_matrix = [\n\t\t 0.2   0.8  -0.5   1.0\n\t\t 0.5  -0.91  0.26 -0.5\n\t\t-0.26 -0.27  0.17  0.87\n\t]\t\t\n\t\n\tbias_vec = [2.0, 3.0, 0.5]\n\t\n\t( \n\t\tσ.(weights_matrix * inputs + bias_vec), \n\t\trelu.(weights_matrix * inputs + bias_vec)\n\t)\nend\n\n# ╔═╡ 0e4a6376-d3fa-47fc-b140-ddb65ee0c592\nmd\"#### Softmax\"\n\n# ╔═╡ afbe3c9c-6db4-415c-921d-cdc4033e9b06\nfunction softmax(x::Vector{T}) where {T<:Real}\n\tm = maximum(x)\n\texp_val = exp.(x .- m)\n\ts = sum(exp_val)\n\texp_val ./ s\nend\n\n# ╔═╡ 662251f6-03ae-4ea6-8bd1-e90ec8a10805\nfunction softmax(x::Matrix{T}) where {T<:Real}\n\tm = maximum.(eachcol(x))\n\texp_val = exp.(x .- m')\t\n\ts = sum(eachrow(exp_val))\n\treturn exp_val ./ s' \nend\n\n# ╔═╡ 383304f8-eb30-45be-99c4-542132ecc78a\nbegin\n\t#inputs_batch = [\n\t#\t[1, 2, 3, 2.5] [2, 5, -1, 2] [-1.5, 2.7, 3.3, -0.8]\n\t#]\n\tinputs_batch = [\n\t\t1 2 3 2.5\n\t\t2 5 -1 2\n\t\t-1.5 2.7 3.3 -0.8\n\t]\n\t\n\t(\n\t\tsoftmax(weights_matrix * inputs + bias_vec), \n\t\tsoftmax(weights_matrix * inputs_batch' .+ bias_vec) # orientacao coluna\n\t)\t\nend\n\n# ╔═╡ Cell order:\n# ╠═6e58a278-ede3-440f-b5ad-c23d03833918\n# ╟─81465bdf-4eb3-4dc5-8f60-2ccdca956e73\n# ╠═78b943f0-ae7b-11eb-3de1-d5cfb31433c6\n# ╠═6fe8d0a2-fd10-4097-95c8-fea57d2a32e8\n# ╟─112f4771-632e-4c35-81bd-ec7f09b40dc0\n# ╠═257e3608-759e-49b2-aa9f-88211bba198b\n# ╠═5b4291e3-1f67-46ac-89f5-d00aaefdac8a\n# ╠═45ba9913-5316-457e-9f97-2622661397e1\n# ╠═e2f8442b-5ccd-431a-8881-3e746b0eb047\n# ╟─0e4a6376-d3fa-47fc-b140-ddb65ee0c592\n# ╠═afbe3c9c-6db4-415c-921d-cdc4033e9b06\n# ╠═662251f6-03ae-4ea6-8bd1-e90ec8a10805\n# ╠═383304f8-eb30-45be-99c4-542132ecc78a\n", "meta": {"hexsha": "462d9d6139b3a510d9fb2819524818676ac955ae", "size": 2387, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapters/Chapter04.jl", "max_stars_repo_name": "AugustoCL/Neural_Network_From_Scratch_in_Julia", "max_stars_repo_head_hexsha": "33f0f479c2e935b179306418e860dfa4e7cec07b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-20T16:40:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T16:40:27.000Z", "max_issues_repo_path": "Chapters/Chapter04.jl", "max_issues_repo_name": "AugustoCL/Neural_Network_From_Scratch_in_Julia", "max_issues_repo_head_hexsha": "33f0f479c2e935b179306418e860dfa4e7cec07b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapters/Chapter04.jl", "max_forks_repo_name": "AugustoCL/Neural_Network_From_Scratch_in_Julia", "max_forks_repo_head_hexsha": "33f0f479c2e935b179306418e860dfa4e7cec07b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7, "max_line_length": 73, "alphanum_fraction": 0.6556346879, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.7930081276097782}}
{"text": "using LinearAlgebra\n\n# Linear Combination\na=[1,2]; b=[3,4]; \nalpha = -0.5; beta = 1.5; \nc = alpha*a + beta*b\n\n# Define function\nfunction lincomb(coeff, vectors)\n    n = length(vectors[1])  \n    a = zeros(n);\n    for i = 1:length(vectors)\n        a = a + coeff[i] * vectors[i];\n    end\nreturn a\nend\n\n#Alternate definition\nfunction lincomb(coeff, vectors)\n    return sum( coeff[i] * vectors[i] \n        for i = 1:length(vectors) )\n    end\n\n# Use funtion\nlincomb( ( -0.5, 1.5), ( [1, 2], [ 3, 4]) )", "meta": {"hexsha": "c0c55b4b19f9a3ae14190fef65a21a874874310e", "size": 495, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1_Vectors/3b_Ops.jl", "max_stars_repo_name": "lynnlangit/julia-linear-algebra", "max_stars_repo_head_hexsha": "41df121aaed38e0fbb1c6b4d24f9ec2774ed2522", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-04-20T17:27:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T08:28:31.000Z", "max_issues_repo_path": "1_Vectors/3b_Ops.jl", "max_issues_repo_name": "lynnlangit/julia-linear-algebra", "max_issues_repo_head_hexsha": "41df121aaed38e0fbb1c6b4d24f9ec2774ed2522", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1_Vectors/3b_Ops.jl", "max_forks_repo_name": "lynnlangit/julia-linear-algebra", "max_forks_repo_head_hexsha": "41df121aaed38e0fbb1c6b4d24f9ec2774ed2522", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-14T19:07:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T19:07:03.000Z", "avg_line_length": 19.8, "max_line_length": 43, "alphanum_fraction": 0.5878787879, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900508, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7929441610381951}}
{"text": "using LazIO\r\nusing LasIO\r\nusing FileIO\r\nusing StaticArrays\r\nusing LinearAlgebra\r\nusing BenchmarkTools\r\nusing DataFrames\r\nusing PointCloudRasterizers\r\n\r\n\r\n\"Store coordinates\"\r\nfunction coordinates(points,h)\r\n    coords = SArray{Tuple{9},Float64,1,9}[]\r\n    for (ind,p) in enumerate(points)\r\n        x = xcoord(p,h)\r\n        y = ycoord(p,h)\r\n        z = zcoord(p,h)\r\n        inten = intensity(p)\r\n        ret = return_number(p)\r\n        nret = number_of_returns(p)\r\n        classificc = classification(p)\r\n        gps = gps_time(p)\r\n        push!(coords,(ind, x, y, z, inten, ret, nret, classificc, gps))\r\n    end\r\n    return coords\r\nend\r\n\r\n\"Convert Cartesian to Spherical coordinates\"\r\nfunction cart2pol(x::Float64, y::Float64, z::Float64)\r\n    cart = Tuple{Float64,Float64,Float64}\r\n    ρ = sqrt(x^2 + y^2 + z^2) #distance\r\n    θ = atand(y,x) #horizontal angle\r\n    ϕ = acosd(z/ρ) #incidence angle\r\n    cart = (ρ,θ,ϕ)\r\n    return cart\r\nend\r\n\r\n\"Convert Spherical to Cartesian coordinates\"\r\nfunction pol2cart(ρ::Float64, θ::Float64, ϕ::Float64)\r\n    pol = Tuple{Float64,Float64,Float64}\r\n    x = (ρ * sind(ϕ) * cosd(θ))\r\n    y = (ρ * sind(ϕ) * sind(θ))\r\n    z = (ρ * cosd(ϕ))\r\n    return pol = (x,y,z)\r\nend\r\n\r\nconst c_air, c_water = 2.99*10^8, 2.25*10^8\r\nconst n_air_water = c_water/c_air\r\n\r\n\"Correct an underwater point according to a watersurface point from the refraction factor by using Snell's Law.\"\r\nfunction refraction_correction(watersurface::SArray{Tuple{4},Float64,1,4},underwater::SArray{Tuple{4},Float64,1,4})\r\n    x0, y0, z0 = watersurface[2:4]\r\n    x1, y1, z1 = underwater[2:4]\r\n    Δx, Δy, Δz = (x1-x0), (y1-y0), (z1-z0)\r\n    ind = underwater[1]\r\n    #Calculate the distance of the two points (ρ), the vertical-incidence angle (ϕ) and horizontal angle (θ) between the two points\r\n    ρ,θ,ϕ = cart2pol(Δx, Δy, Δz)\r\n\r\n    #Calculate the underwater angle due to the refraction effect.\r\n    #Using Snell's Law: n(air)*sin(ϕ_air) = n(water)*sin(ϕ_water),\r\n    #where ϕ_air: the angle of incidence (I know that the angle of the scan is 20)\r\n    #      ϕ_water: the angle of refraction\r\n    #      n(air): the refraction idex of medium containing the incident ray, value=1.000293\r\n    #      n(water): the refraction idex of medium containing the transmitted ray, value=1.333\r\n\r\n    #check the height values of the water-surface and underwater point\r\n    if z0 == z1\r\n        error(\"the water-surface and underwater point are at the same height level\")\r\n    elseif z0 > z1\r\n        ϕ_water = asind(n_air_water*sind(ϕ)) #ϕ_new is the new vertical\r\n    else\r\n        error(\"the underwater point can not be higher than the watersurface point\")\r\n    end\r\n\r\n    #Distance under the water has been influenced by the different speed of light in the water.\r\n    #In a specific moment, ρ = c_air * t and ρ_water = c_water * t.\r\n    #So, by diving these two equations, the ratio (ρ1/ρ2) = n_air_water\r\n    ρ_water = (ρ*n_air_water)\r\n\r\n    #Calculate the correction in the 3d space using the pol2cart function\r\n    xcor, ycor, zcor = pol2cart(ρ_water, θ, ϕ_water)\r\n\r\n    #Define the new corrected coordinates of the points\r\n    xnew = x0 + xcor\r\n    ynew = y0 + ycor\r\n    znew = z0 - zcor\r\n\r\n    #Return the new corrected point\r\n    corrections = @SVector[xcor, ycor, zcor]\r\n    correct_point = @SVector[ind, xnew, ynew ,znew]\r\n\r\n    return corrections, correct_point\r\nend\r\n\r\n\"Group the laser pulses based on their GPS time\"\r\nfunction laserpulses(points)\r\n    println(\"Execution Time of laser pulses \" * string(length(points)) * \" points\")\r\n    @time begin\r\n        laser_pulses = SArray{Tuple{}}[] #specify the type of array\r\n        sorted_gps = sort!(points, by = x -> x[9], rev = false)\r\n        pp = [tuple(p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8],p[9]) for p in sorted_gps]\r\n        df = DataFrame(pp[:]) #create a dataframe\r\n        groups = groupby(df,:9) #group by gps time\r\n        for gr in groups\r\n            if size(gr,1) > 1\r\n                push!(laser_pulses,[gr])\r\n            end\r\n        end\r\n    end\r\n    return laser_pulses\r\nend\r\n\r\n\"Calculate the corrected/refracted points for every pulse\"\r\nfunction corrected_points(laser_pulses,coords)\r\n    corrected_laser_pulses = [] #specify the type of array\r\n\r\n    INDEXES_corr = [] #indexes of corrected_points\r\n    INDEXES_un_corr = [] #indexes of non-corrected points\r\n\r\n    for every_pulse in laser_pulses\r\n        indexes = getindex(every_pulse)[1]\r\n        ind_surf = Int64(indexes[1]) #water surface index\r\n        p_surf = coords[ind_surf] #water surface point\r\n        p_surf = @SVector[ind_surf,p_surf[2],p_surf[3],p_surf[4]] #create Arrays\r\n        corrected_points = SArray{Tuple{4},Float64,1,4}[] #store the corrected points for each pulse!\r\n        not_corrected = SArray{Tuple{4},Float64,1,4}[] #store the un-corrected points due to the Exception ERRORsfor each pulse!\r\n\r\n        push!(corrected_points,(p_surf)) # add the water surface point\r\n        push!(not_corrected,(p_surf)) # add the water surface point\r\n\r\n        for ind_under = 2:length(indexes) #iterate throught the inder water points\r\n            n = Int64(indexes[ind_under])\r\n            p_under = coords[n]\r\n            p_under = @SVector[n,p_under[2],p_under[3],p_under[4]]\r\n            try\r\n                correction, corre_pt = refraction_correction(p_surf,p_under)\r\n                push!(INDEXES_corr,p_under[1])\r\n                push!(corrected_points,(corre_pt)) # I will classify as un-refracted with classif.code = 19\r\n            catch\r\n                push!(INDEXES_un_corr,p_under[1])\r\n                push!(not_corrected,(p_under)) # I will classify as un-refracted with classif.code = 20\r\n            end\r\n        end\r\n\r\n        if length(corrected_points) > 1 #check if there is NOT only water surface point\r\n            push!(corrected_laser_pulses,[corrected_points])\r\n        end\r\n    end\r\n    return corrected_laser_pulses, INDEXES_corr, INDEXES_un_corr\r\nend\r\n\r\n\r\n#Write a new classified Pointcloud\r\nfunction write_pointcloud(ds,header,pp,indexes_corr,index_un_corr)\r\n    n = length(indexes_corr) + length(index_un_corr)\r\n    println(\"Execution Time of writing points \" * string(n) * \" points\")\r\n    @time  begin\r\n        laz_out = joinpath(path, \"myoutput_\" * string(length(pp)) * \"_points.laz\")\r\n        LazIO.write(laz_out, ds.header) do io\r\n            for (ind,p) in enumerate(ds)\r\n                if ind in indexes_corr\r\n                    p.classification = UInt8(19)\r\n                elseif ind in indexes_un_corr #this elseif doesn't work!!why???\r\n                    p.classification = UInt8(20)\r\n                else\r\n                    p.classification = UInt8(9)\r\n                end\r\n                LazIO.writepoint(io, p)\r\n            end\r\n        end\r\n    end\r\nend\r\n\r\n\r\n#MAIN#\r\nconst path = \"C:/Users/alexandr/OneDrive - Stichting Deltares/Desktop/NL3_subset/\"\r\nconst filename = \"NL3_clipped_water_cropheight_pointformat3_classification.laz\" #classification = 9 (water)\r\nconst lazinput = path * filename\r\n\r\n#Open LAZ pointcloud\r\nopen_file = File{format\"LAZ_\"}(lazinput)\r\nh, points = load(open_file)\r\nn = length(points)\r\n\r\n#dataset\r\nds = LazIO.open(lazinput)\r\n\r\n#subset\r\npp = points[1500000:1520000]\r\n#Array with coordinates\r\ncoords = coordinates(pp,h)\r\n#Separate laser pulses\r\nlaser_pulses = laserpulses(coords)\r\n#Return corrected points\r\ncorrected_laser_pulses, indexes_corr, indexes_un_corr  = corrected_points(laser_pulses,coords)\r\n#write pointcloud\r\nwrite_pointcloud(ds,h,pp,indexes_corr,indexes_un_corr)\r\n", "meta": {"hexsha": "a6cb212785a0794101aa7e7dff95d6b9a416bff4", "size": 7487, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "RefractionCorrection_revised.jl", "max_stars_repo_name": "VasilisAle/Refraction.jl", "max_stars_repo_head_hexsha": "7309f5eb6091377dbaada374599142a52159c940", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RefractionCorrection_revised.jl", "max_issues_repo_name": "VasilisAle/Refraction.jl", "max_issues_repo_head_hexsha": "7309f5eb6091377dbaada374599142a52159c940", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RefractionCorrection_revised.jl", "max_forks_repo_name": "VasilisAle/Refraction.jl", "max_forks_repo_head_hexsha": "7309f5eb6091377dbaada374599142a52159c940", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8131313131, "max_line_length": 132, "alphanum_fraction": 0.6448510752, "num_tokens": 2089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900507, "lm_q2_score": 0.8267117940706735, "lm_q1q2_score": 0.7929441589906583}}
{"text": "using Pkg\nPkg.activate(@__DIR__)\nPkg.instantiate()\n\nusing LinearAlgebra, Symbolics, DifferentialEquations, JLD2\n\nstruct DoublePendulum{T}\n\tm1::T\n\tm2::T\n\tl1::T\n\tl2::T\nend\n\nn = 2 # number of states\nmodel = DoublePendulum(1.0, 1.0, 1.0, 1.0) # model\n\n# kinematics\nfunction kinematics_1(model::DoublePendulum, q)\n\tθ1, θ2 = q\n\n\t[0.5 * model.l1 * sin(θ1);\n\t -0.5 * model.l1 * cos(θ1)]\nend\n\nfunction kinematics_2(model::DoublePendulum, q)\n\tθ1, θ2 = q\n\n\t[model.l1 * sin(θ1) + 0.5 * model.l2 * sin(θ1 + θ2);\n\t -model.l1 * cos(θ1) - 0.5 * model.l2 * cos(θ1 + θ2)]\nend\n\n# fast kinematics functions\n@variables q[1:n]\n@variables q̇[1:n]\n\nk1 = kinematics_1(model, q)\nk2 = kinematics_2(model, q)\n\nk1_exp = Symbolics.build_function(k1, q)\nk2_exp = Symbolics.build_function(k2, q)\n\nk1_func = eval(k1_exp[1])\nk2_func = eval(k2_exp[1])\n\n# kinematics Jacobians\nj1 = Symbolics.jacobian(k1, q, simplify = true)\nj2 = Symbolics.jacobian(k2, q, simplify = true)\n\nj1_exp = Symbolics.build_function(j1, q)\nj2_exp = Symbolics.build_function(j2, q)\n\nj1_func = eval(j1_exp[1])\nj2_func = eval(j2_exp[1])\n\n# Lagrangian\nfunction lagrangian(model, q, q̇)\n\tL = 0.0\n\n\t# mass 1\n\tv1 = j1_func(q) * q̇\n\tL += 0.5 * model.m1 * transpose(v1) * v1 \t\t# kinetic energy\n\tL -= model.m1 * 9.81 * k1_func(q)[2]            # potential energy\n\n\t# mass 2\n\tv2 = j2_func(q) * q̇\n\tL += 0.5 * model.m2 * transpose(v2) * v2\n\tL -= model.m2 * 9.81 * k2_func(q)[2]\n\n\treturn L\nend\n\n# fast Lagrangian\nL = lagrangian(model, q, q̇)\n\ndLq = Symbolics.gradient(L, q, simplify = true)\ndLq̇ = Symbolics.gradient(L, q̇, simplify = true)\nddL = Symbolics.hessian(L, [q; q̇], simplify = true)\n\n# mass matrix\nM = ddL[n .+ (1:n), n .+ (1:n)]\nM = simplify.(M)\n\n# dynamics bias\nC = ddL[n .+ (1:n), 1:n] * q̇ - dLq\nC = simplify.(C)\n\n# dynamics\n# ẋ = [q̇; M \\ (-1.0 * C)]\nẋ = [q̇; M \\ (-0.5 * q̇ -1.0 * C)]\nẋ = simplify.(ẋ)\n\nẋ_exp = Symbolics.build_function(ẋ, q, q̇)\ndynamics = eval(ẋ_exp[1])\n\n# save dynamics function\npath = joinpath(pwd(), \"dynamics.jld2\")\n# @save path ẋ_exp\n# @load path ẋ_exp\n\n# DifferentialEquations.jl\nfunction dynamics!(ẋ, x, p, t)\n\tẋ .= dynamics(view(x, 1:n), view(x, n .+ (1:n)))\nend\n\n# simulate\nx0 = [0.5 * π; 0.0; 0.0; 0.0]\ntspan = (0.0, 10.0)\ndt = 0.01\nprob = ODEProblem(dynamics!, x0, tspan)\nsol = solve(prob, Tsit5(), adaptive = false, dt = dt)\n\n# MeshCat.jl\ninclude(joinpath(pwd(), \"visuals.jl\"))\nvis = Visualizer()\nrender(vis)\nvisualize_double_pendulum!(vis, model, sol.u, Δt = dt)\n", "meta": {"hexsha": "65241a98db5b28829fd7311ca16e17637cf8fd69", "size": 2448, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "double_pendulum.jl", "max_stars_repo_name": "thowell/symbolics_double_pendulum", "max_stars_repo_head_hexsha": "1d8541f491fd61f7862ff2885d1f2c7cf30a4544", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-04-21T20:56:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-22T14:19:25.000Z", "max_issues_repo_path": "double_pendulum.jl", "max_issues_repo_name": "thowell/symbolics_double_pendulum", "max_issues_repo_head_hexsha": "1d8541f491fd61f7862ff2885d1f2c7cf30a4544", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "double_pendulum.jl", "max_forks_repo_name": "thowell/symbolics_double_pendulum", "max_forks_repo_head_hexsha": "1d8541f491fd61f7862ff2885d1f2c7cf30a4544", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9230769231, "max_line_length": 67, "alphanum_fraction": 0.6348039216, "num_tokens": 1003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067253, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7928882694464008}}
{"text": "mutable struct UncertaintyTrapEcon{TF<:AbstractFloat, TI<:Integer}\n    a::TF          # Risk aversion\n    γ_x::TF        # Production shock precision\n    ρ::TF          # Correlation coefficient for θ\n    σ_θ::TF        # Standard dev of θ shock\n    num_firms::TI  # Number of firms\n    σ_F::TF        # Std dev of fixed costs\n    c::TF          # External opportunity cost\n    μ::TF          # Initial value for μ\n    γ::TF          # Initial value for γ\n    θ::TF          # Initial value for θ\n    σ_x::TF        # Standard deviation of shock\nend\n\nfunction UncertaintyTrapEcon(;a::AbstractFloat=1.5, γ_x::AbstractFloat=0.5,\n                             ρ::AbstractFloat=0.99, σ_θ::AbstractFloat=0.5,\n                             num_firms::Integer=100, σ_F::AbstractFloat=1.5,\n                             c::AbstractFloat=-420.0, μ_init::AbstractFloat=0.0,\n                             γ_init::AbstractFloat=4.0,\n                             θ_init::AbstractFloat=0.0)\n    σ_x = sqrt(a / γ_x)\n    UncertaintyTrapEcon(a, γ_x, ρ, σ_θ, num_firms, σ_F, c, μ_init,\n                        γ_init, θ_init, σ_x)\n\nend\n\nfunction ψ(uc::UncertaintyTrapEcon, F::Real)\n    temp1 = -uc.a * (uc.μ - F)\n    temp2 = 0.5 * uc.a^2 * (1 / uc.γ + 1 / uc.γ_x)\n    return (1 / uc.a) * (1 - exp(temp1 + temp2)) - uc.c\nend\n\n\"\"\"\nUpdate beliefs (μ, γ) based on aggregates X and M.\n\"\"\"\nfunction update_beliefs!(uc::UncertaintyTrapEcon, X::Real, M::Real)\n    # Simplify names\n    γ_x, ρ, σ_θ = uc.γ_x, uc.ρ, uc.σ_θ\n\n    # Update μ\n    temp1 = ρ * (uc.γ * uc.μ + M * γ_x * X)\n    temp2 = uc.γ + M * γ_x\n    uc.μ =  temp1 / temp2\n\n    # Update γ\n    uc.γ = 1 / (ρ^2 / (uc.γ + M * γ_x) + σ_θ^2)\nend\n\nupdate_θ!(uc::UncertaintyTrapEcon, w::Real) =\n    (uc.θ = uc.ρ * uc.θ + uc.σ_θ * w)\n\n\"\"\"\nGenerate aggregates based on current beliefs (μ, γ).  This\nis a simulation step that depends on the draws for F.\n\"\"\"\nfunction gen_aggregates(uc::UncertaintyTrapEcon)\n    F_vals = uc.σ_F * randn(uc.num_firms)\n\n    M = sum(ψ.(uc, F_vals) .> 0)  # Counts number of active firms\n    if M > 0\n        x_vals = uc.θ + uc.σ_x * randn(M)\n        X = mean(x_vals)\n    else\n        X = 0.0\n    end\n    return X, M\nend\n", "meta": {"hexsha": "d15211716291fb2d84a15482260b30c77f944be2", "size": 2169, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "uncertainty_traps/uncertainty_traps.jl", "max_stars_repo_name": "chenwang/QuantEcon.lectures.code", "max_stars_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2017-05-09T10:45:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:33:27.000Z", "max_issues_repo_path": "uncertainty_traps/uncertainty_traps.jl", "max_issues_repo_name": "chenwang/QuantEcon.lectures.code", "max_issues_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2017-06-30T01:52:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-01T20:09:47.000Z", "max_forks_repo_path": "uncertainty_traps/uncertainty_traps.jl", "max_forks_repo_name": "QuantEcon/QuantEcon.lectures.code", "max_forks_repo_head_hexsha": "d61ac7bc54529dd5c77470c17539eb2418b047c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 117, "max_forks_repo_forks_event_min_datetime": "2017-04-25T16:09:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T02:30:29.000Z", "avg_line_length": 31.8970588235, "max_line_length": 80, "alphanum_fraction": 0.5541724297, "num_tokens": 737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966656805269, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7928882586431977}}
{"text": "using LinearAlgebra\ninclude(\"gates.jl\")\n\n# common states\nket_0 = Complex[1; 0]\nket_1 = Complex[0; 1]\nket_plus = Complex[1; 1] ./ sqrt(2)\nket_minus = Complex[1; -1] ./ sqrt(2)\n\n# TODO\n# struct Op\n#     U::Matrix{Complex}\n#     isUnitary::Bool\n# end\n\n\n\"\"\"\n    conj_transpose(s)\n\nconj_transpose is a clearer name for adjoint for students.\nit is identical to `s'`\n\"\"\"\nfunction conj_transpose(s::Union{AbstractVecOrMat})\n    conj.(transpose(s))\nend\n\n\"\"\"\n    commutator(A, B)\n\ncommutator(A, B) := A * B - B * A\nTakes in two operators, if the result is zero, the operators commute.\n\"\"\"\nfunction commutator(A, B)\n    A * B - B * A\nend\n\n\"\"\"\n    ops_commute(A, B)\n\nops_commute(A, B) := commutator(A,B) ≈ fill(0., (dim, dim)) \nfor ops to commute they must be square and equal dim, so dim\n    is arbitrarily size(A, 1)\n\"\"\"\nfunction ops_commute(A, B)\n    if size(A) != size(B)\n        return false\n    end\n    dim = size(A, 1)\n    commutator(A,B) ≈ fill(0., (dim, dim)) \nend\n    \n    \"\"\"\n    is_unitary(s)\n\nA unitary matrix U is defined by U†U = UU† = I.\nreturns true if `s` is unitary.\nNote `s` must be square.\n\"\"\"\n# TODO: fix 1/sqrt(2) and normalization \nfunction is_unitary(s)\n    LinearAlgebra.checksquare(s)\n    s * conj_transpose(s) ≈ Id\nend \n\n\"\"\"\n    is_hermitian(s)\n\nA hermitian matrix U is defined by U = †U.\nreturns true if s is hermitian.\n\"\"\"\n# throws error if not hermitian\nfunction is_hermitian(s)\n    LinearAlgebra.checksquare(s);\n    s ≈ conj_transpose(s)\nend\n\n\"\"\"\n    is_normed(s)\n\nif sum(s .^ 2)) ≈ 1., returns true\n\"\"\"\n# throws error if s is not normalized\nfunction is_normed(s)\n    mag = convert.(Float64, sum(s .^ 2))\n    @assert mag ≈ 1.\nend\n\n\"\"\"\n    is_linear(s)\n\n\n\"\"\"\nfunction is_linear()\n    \nend\n\n\n\"\"\"\n    inner(a, b)\n\ngiven two equal dimension column vectors, a and b,\nreturns the inner product <a|b> where <a| == conj_transpose(a)\nthis is a duplicate function of dot(a, b) or (a ⋅ b).\n\"\"\"\n# use ⋅ ?\nfunction inner(a, b)\n    conj_transpose(a) * b\nend\n\n\"\"\"\n    outer(a, b)\n\ngiven two equal dimension column vectors, |a> and |b>,\nreturns the inner product |a><b| where <b| == conj_transpose(b)\nnote, this function does NOT return the same as kron(a, b).\nouter returns a matrix, whereas kron returns a vector\n\"\"\"\n# todo splat n ops\n# add assert equal dims\nfunction outer(a, b)\n    a * conj_transpose(b)\nend\n\n\"\"\"\n    Cgate(U)\n\nCgate(U) creates a controlled U gate, given a unitary U.\n\"\"\"\nCgate(U) = kron(outer(ket_0, ket_0), Id) + kron(outer(ket_1, ket_1), U)\n\n\"\"\"\n    bell_states()\n\nreturns the four bell states as vectors in order of binary increasing\nqubit input states (00, 01, 10, 11)\n\"\"\"\nfunction bell_states()\n    # # bell states\n    # 00: 00 + 11\n    # 10: 00 - 11\n    # 01: 01 + 10\n    # 11: 01 - 10\n    β_00 = Cgate(X) * kron(H * ket_0, ket_0)\n    β_01 = Cgate(X) * kron(H * ket_0, ket_1)\n    β_10 = Cgate(X) * kron(H * ket_1, ket_0)\n    β_11 = Cgate(X) * kron(H * ket_1, ket_1)\n    β_00, β_01, β_10, β_11\nend\n\n\n\"\"\"\n    cauchy_schwarz(u, v)\n\ngiven arbitrary column vectors `|u⟩, |v⟩`, we want to show that,\n\n⟨u|u⟩⟨v|v⟩ ≥ |⟨u|v⟩|²\n\"\"\"\n\nfunction cauchy_schwarz(u, v)\n\nend\n# function eulerform(U)\n    # thm \n    # U single qubit unitary ⟹ ∃ α, β, γ, δ ∈ ℝ, st \n    # U = exp(iα) * [exp(-i\\)]\n    \n# end", "meta": {"hexsha": "d1623f118bdd38549254004471c0c4bc7c9e6b92", "size": 3218, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/base.jl", "max_stars_repo_name": "anandijain/MyQuantum", "max_stars_repo_head_hexsha": "4550de7140f38c55fd76e4ae754bebd9dd9c7caf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/base.jl", "max_issues_repo_name": "anandijain/MyQuantum", "max_issues_repo_head_hexsha": "4550de7140f38c55fd76e4ae754bebd9dd9c7caf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/base.jl", "max_forks_repo_name": "anandijain/MyQuantum", "max_forks_repo_head_hexsha": "4550de7140f38c55fd76e4ae754bebd9dd9c7caf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2694610778, "max_line_length": 71, "alphanum_fraction": 0.6236793039, "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768604361742, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.792857383091849}}
{"text": "module Math3D\n\nusing LinearAlgebra\n\nexport orthogonalize, orthogonalize!\nexport rotx, roty, rotz, rotxyz, rot, axisangle, trans, perspective, ortho\n\nfunction orthogonalize(v::Vector, n::Vector)\n\tnUnit = normalize(n)\n\tv - nUnit * dot(v, nUnit)\nend\n\nfunction orthogonalize!(v::Vector, n::Vector)\n\tnUnit = normalize(n)\n\tv -= nUnit * dot(v, nUnit)\nend\n\nfunction rotx(m::Matrix, angle::Real)\n\ts = sin(angle)\n\tc = cos(angle)\n\tm[1,1] = 1\n\tm[2,1] = m[3,1] = m[1,2] = m[1,3] = 0\n\tm[2,2] = m[3,3] = c\n\tm[3,2] = s\n\tm[2,3] = -s\n\treturn m\nend\n\nfunction roty(m::Matrix, angle::Real)\n\ts = sin(angle)\n\tc = cos(angle)\n\tm[1,1] = m[3,3] = c\n\tm[2,1] = m[1,2] = m[3,2] = m[2,3] = 0\n\tm[2,2] = 1\n\tm[3,1] = -s\n\tm[1,3] = s\n\treturn m\nend\n\nfunction rotz(m::Matrix, angle::Real)\n\ts = sin(angle)\n\tc = cos(angle)\n\tm[1,1] = m[2,2] = c\n\tm[2,1] = s\n\tm[1,2] = -s\n\tm[3,1] = m[3,2] = m[1,3] = m[2,3] = 0\n\tm[3,3] = 1\n\treturn m\nend\n\n# rotation with angles around each of the axes\nfunction rotxyz(m::Matrix, xAngle::Real, yAngle::Real, zAngle::Real)\n\t# Tait-Bryan angles transform in the order X1Y2Z3\n\tsx = sin(xAngle)\n\tcx = cos(xAngle)\n\tsy = sin(yAngle)\n\tcy = cos(yAngle)\n\tsz = sin(zAngle)\n\tcz = cos(zAngle)\n\n\tm[1,1] = cy*cz\n\tm[2,1] = cx*sz+cz*sx*sy\n\tm[3,1] = sx*sz-cx*cz*sy\n\n\tm[1,2] = -cy*sz\n\tm[2,2] = cx*cz-sx*sy*sz\n\tm[3,2] = cz*sx+cx*sy*sz\n\n\tm[1,3] = sy\n\tm[2,3] = -cy*sx\n\tm[3,3] = cx*cy\n\n\treturn m\nend\n\nrotx(angle::Real) = rotx(Array{typeof(angle)}(undef, 3, 3), angle)\nroty(angle::Real) = roty(Array{typeof(angle)}(undef, 3, 3), angle)\nrotz(angle::Real) = rotz(Array{typeof(angle)}(undef, 3, 3), angle)\nrotxyz(xAngle::Real, yAngle::Real, zAngle::Real) = rotxyz(Array{typeof(xAngle)}(undef, 3, 3), xAngle, yAngle, zAngle)\n\nfunction rot(m::Matrix, axis::Vector, angle::Real)\n\tu = normalize(axis[1:3])\n\tux = u[1]\n\tuy = u[2]\n\tuz = u[3]\n\ts = sin(angle)\n\tc = cos(angle)\n\n\tm[1,1] = c+ux*ux*(1-c)\n\tm[2,1] = uy*ux*(1-c)+uz*s\n\tm[3,1] = uz*ux*(1-c)-uy*s\n\n\tm[1,2] = ux*uy*(1-c)-uz*s\n\tm[2,2] = c+uy*uy*(1-c)\n\tm[3,2] = uz*uy*(1-c)+ux*s\n\n\tm[1,3] = ux*uz*(1-c)+uy*s\n\tm[2,3] = uy*uz*(1-c)-ux*s\n\tm[3,3] = c+uz*uz*(1-c)\n\n\treturn m\nend\n\nrot(axis::Vector, angle::Real) = rot(Array{typeof(angle)}(undef, 3, 3), axis, angle)\n\nfunction axisangle(m::Matrix{T}) where T\n\tt = m[1,1] + m[2,2] + m[3,3]\n\tanglecos = (t-1)/2\n\tanglecos >= 1 - eps(T) && return T[0,0,1], zero(T)\n\taxis = [m[3,2] - m[2,3], m[1,3] - m[3,1], m[2,1] - m[1,2]]\n\tif anglecos <= -1 + eps(T)\n\t\tsquares = T[(m[1,1]+1)/2, (m[2,2]+1)/2, (m[3,3]+1)/2]\n\t\taxis /= 4\n\t\ti = indmax(squares)\n\t\taxis[i] = squares[i]\n\t\tmaxel = sqrt(squares[i])\n\t\taxis /= maxel\n\t\treturn axis,T(pi)\n\tend\n\taxislen = norm(axis)\n\tanglesin = axislen/2\n\tangle = atan2(anglesin, anglecos)\n\taxis /= axislen\n\taxis, angle\nend\n\nfunction trans(m::Matrix, t::Vector)\n\tm[1,4] = t[1]\n\tm[2,4] = t[2]\n\tm[3,4] = t[3]\n\treturn m\nend\n\ntrans(t::Vector) = trans(Matrix{eltype(t)}(I, 4, 4), t)\n\nfunction scale(m::Matrix, s::Vector)\n  m[1,1] = s[1]\n  m[2,2] = s[2]\n  m[3,3] = s[3]\n  m[1,2] = m[1,3] = m[2,1] = m[2,3] = m[3,1] = m[3,2] = 0\nend\n\nscale(s::Vector) = diagm(0 => vcat(s, 1))\n\nfunction perspective(m::Matrix, left::Real, right::Real, top::Real, bottom::Real, near::Real, far::Real; leftHanded = false)\n\tzsign = leftHanded ? -1 : 1\n\tm[1:4, 1:4] = [ 2near/(right-left)\t\t\t\t   0  (right+left)/(right-left)*zsign\t\t\t\t\t  0 ;\n\t\t\t\t\t\t\t\t\t 0  2near/(top-bottom)  (top+bottom)/(top-bottom)*zsign\t\t\t\t\t  0 ;\n\t\t\t\t\t\t\t\t\t 0\t\t\t\t   0\t (-far-near)/(far-near)*zsign  -2far*near/(far-near) ;\n\t\t\t\t\t\t\t\t\t 0\t\t\t\t   0\t\t\t\t\t\t -1*zsign\t\t\t\t\t  0 ]\n\treturn m\nend\n\nperspective(left::Real, right::Real, top::Real, near::Real, far::Real; leftHanded = false) = perspective(Array{typeof(near)}(undef, 4, 4), left, right, top, bottom, near, far, leftHanded = leftHanded)\nperspective(m::Matrix, width::Real, height::Real, near::Real, far::Real; leftHanded = false) = perspective(m, -0.5width, 0.5width, -0.5height, 0.5height, near, far, leftHanded = leftHanded)\nperspective(width::Real, height::Real, near::Real, far::Real; leftHanded = false) = perspective(Array{typeof(near)}(undef, 4, 4), width, height, near, far, leftHanded = leftHanded)\nfunction persp_horizontal_fov(m::Matrix, hfov::Real, w_h_ratio::Real, near::Real, far::Real; leftHanded = false)\n\twidth = 2near*tan(hfov/2)\n\tperspective(m, width, width / w_h_ratio, near, far, leftHanded = leftHanded)\nend\npersp_horizontal_fov(hfov::Real, w_h_ratio::Real, near::Real, far::Real; leftHanded = false) = persp_horizontal_fov(Array{typeof(near)}(undef, 4, 4), hfov, w_h_ratio, near, far, leftHanded = leftHanded)\nfunction persp_vertical_fov(m::Matrix, vfov::Real, w_h_ratio::Real, near::Real, far::Real; leftHanded = false)\n\theight = 2near*tan(vfov/2)\n\tperspective(m, w_h_ratio * height, height, near, far, leftHanded = leftHanded)\nend\npersp_vertical_fov(vfov::Real, w_h_ratio::Real, near::Real, far::Real; leftHanded = false) = persp_vertical_fov(Array{typeof(near)}(undef, 4, 4), vfov, w_h_ratio, near, far, leftHanded = leftHanded)\n\nfunction ortho(m::Matrix, left::Real, right::Real, top::Real, bottom::Real, near::Real, far::Real; leftHanded = false)\n\tzsign = leftHanded ? -1 : 1\n\tm[1:4, 1:4] = [ 2/(right-left)\t\t\t   0\t\t\t\t   0 (-right-left)/(right-left) ;\n\t\t\t\t\t\t\t\t 0  2/(top-bottom)\t\t\t\t   0 (-top-bottom)/(top-bottom) ;\n\t\t\t\t\t\t\t\t 0\t\t\t   0 -2/(far-near)*zsign\t (-far-near)/(far-near) ;\n\t\t\t\t\t\t\t\t 0\t\t\t   0\t\t\t\t   0\t\t\t\t\t\t  1 ]\n\treturn m\nend\n\northo(left::Real, right::Real, top::Real, bottom::Real, near::Real, far::Real; leftHanded = false) = ortho(Array{typeof(near)}(undef, 4, 4), left, right, top, bottom, near, far, leftHanded = leftHanded)\northo(m::Matrix, width::Real, height::Real, near::Real, far::Real; leftHanded = false) = ortho(m, -0.5width, 0.5width, -0.5height, 0.5height, near, far, leftHanded = leftHanded)\northo(width::Real, height::Real, near::Real, far::Real; leftHanded = false) = ortho(Array{typeof(near)}(undef, 4, 4), width, height, near, far, leftHanded = leftHanded)\n\nend\n", "meta": {"hexsha": "d7b9e5f7bedb667bd0c333d53937d44002abb80f", "size": 5870, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Math3D.jl", "max_stars_repo_name": "aaalexandrov/GR.jl", "max_stars_repo_head_hexsha": "8d6f7cef5319f933688b003cb35afa5f53936194", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-30T02:59:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T02:59:15.000Z", "max_issues_repo_path": "src/Math3D.jl", "max_issues_repo_name": "aaalexandrov/GR.jl", "max_issues_repo_head_hexsha": "8d6f7cef5319f933688b003cb35afa5f53936194", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math3D.jl", "max_forks_repo_name": "aaalexandrov/GR.jl", "max_forks_repo_head_hexsha": "8d6f7cef5319f933688b003cb35afa5f53936194", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2527472527, "max_line_length": 202, "alphanum_fraction": 0.6185689949, "num_tokens": 2401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7928573778156708}}
{"text": "\"\"\"\n    magic_number(n::Int64))\n\nA magic number has to build as the power of 5 or the sum of unique powers of 5. First few\nmagic numbers are:\n    1. 5\n    2. 5^2 = 25\n    3. 5 + 25 = 30\n    4. 5^3 = 125\n    5. 125 + 5 = 130\n\n\n# Arguments\n- `n::Int64`: Integer value of the number, which has to become a magic number\n\n\n# Examples\n```julia-repl\njulia> import ClassicAlgorithmsCollections\njulia> ClassicAlgorithmsCollections.magic_number(5)\n130\n```\n\"\"\"\nfunction magic_number(n::Int64)\n\n    pow = 1\n    result = 0\n\n    while n != 0\n        pow *= 5\n        if n & 1 % Bool\n            result += pow\n        end\n        n >>= 1\n    end\n    return result\nend\n", "meta": {"hexsha": "5d43a24392b588ad20b41120a94575f4c0f8c0d3", "size": 653, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BitManipulation/MagicNumber.jl", "max_stars_repo_name": "Anselmoo/ClassicAlgorithmsCollections", "max_stars_repo_head_hexsha": "9f802c4f317492e19b0b8bb6d9020d8450e00772", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BitManipulation/MagicNumber.jl", "max_issues_repo_name": "Anselmoo/ClassicAlgorithmsCollections", "max_issues_repo_head_hexsha": "9f802c4f317492e19b0b8bb6d9020d8450e00772", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2020-09-03T06:47:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-20T06:58:58.000Z", "max_forks_repo_path": "src/BitManipulation/MagicNumber.jl", "max_forks_repo_name": "Anselmoo/ClassicAlgorithmsCollections", "max_forks_repo_head_hexsha": "9f802c4f317492e19b0b8bb6d9020d8450e00772", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1842105263, "max_line_length": 89, "alphanum_fraction": 0.5926493109, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.944176852582231, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7928573764966261}}
{"text": "function compute_log_joint(observations, partition, tau0, tau1, sigma, theta)\n  n = length(observations)\n  k = length(partition)\n  prob = k*log(sigma) + lgamma(theta) + lgamma(theta/sigma + k) - lgamma(theta/sigma) - lgamma(theta + n)\n  for cluster in partition\n    prob += lgamma(length(cluster) - sigma) - lgamma(1 - sigma)\n    prob += compute_log_conditonal_observations(observations, cluster, tau0, tau1)\n  end\n  prob\nend\n\nfunction compute_log_conditonal_observations(observations, cluster, tau0, tau1)\n  nl = length(cluster)\n  prob = (nl/2)*log(tau1) - (nl/2)*log(2*pi) + 0.5*log(tau0) + 0.5*log(tau0+nl)\n  prob += -tau1/2*(sum(observations)) + 0.5*(tau0*mu_0+tau1*sum(observations[cluster]))^2/(tau0+nl*tau1)\n  prob\nend\n\n# Test of similarity between distributions\nfunction correct_posterior(empirical_probs, data, partitions, τ0, τ1, σ, θ)\n    true_log_probs = map(p -> compute_log_joint(data, p, τ0, τ1, σ, θ), partitions)\n    true_probs = exp.(true_log_probs)\n    true_probs /= sum(true_probs)\n\n    empirical_probs /= sum(empirical_probs)\n\n    # compare distribitions\n    # L2\n    L2 = sum((empirical_probs - true_probs).^2)\n\n    # Discrepancy\n    discr = maximum(abs.(empirical_probs - true_probs))\n    return L2, discr\nend\n", "meta": {"hexsha": "947fcd60edca8887420a89dff40471909100643b", "size": 1233, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_utils/random_measure_utils.jl", "max_stars_repo_name": "tdiethe/Turing.jl", "max_stars_repo_head_hexsha": "b5042d69a0ec42b38b91ac84c8a5319fa1109062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1446, "max_stars_repo_stars_event_min_datetime": "2018-05-26T02:15:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:23:19.000Z", "max_issues_repo_path": "test/test_utils/random_measure_utils.jl", "max_issues_repo_name": "tdiethe/Turing.jl", "max_issues_repo_head_hexsha": "b5042d69a0ec42b38b91ac84c8a5319fa1109062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1218, "max_issues_repo_issues_event_min_datetime": "2018-05-23T15:30:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:25:51.000Z", "max_forks_repo_path": "test/test_utils/random_measure_utils.jl", "max_forks_repo_name": "tdiethe/Turing.jl", "max_forks_repo_head_hexsha": "b5042d69a0ec42b38b91ac84c8a5319fa1109062", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 222, "max_forks_repo_forks_event_min_datetime": "2018-05-23T15:33:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:51:57.000Z", "avg_line_length": 35.2285714286, "max_line_length": 105, "alphanum_fraction": 0.702351987, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176852582231, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7928573689227768}}
{"text": "\"\"\"\n    NeuralNetworkKernel()\n\nKernel of a Gaussian process obtained as the limit of a Bayesian neural network with a\nsingle hidden layer as the number of units goes to infinity.\n\n# Definition\n\nConsider the single-layer Bayesian neural network\n``f \\\\colon \\\\mathbb{R}^d \\\\to \\\\mathbb{R}`` with ``h`` hidden units defined by\n```math\nf(x; b, v, u) = b + \\\\sqrt{\\\\frac{\\\\pi}{2}} \\\\sum_{i=1}^{h} v_i \\\\mathrm{erf}\\\\big(u_i^\\\\top x\\\\big),\n```\nwhere ``\\\\mathrm{erf}`` is the error function, and with prior distributions\n```math\n\\\\begin{aligned}\nb &\\\\sim \\\\mathcal{N}(0, \\\\sigma_b^2),\\\\\\\\\nv &\\\\sim \\\\mathcal{N}(0, \\\\sigma_v^2 \\\\mathrm{I}_{h}/h),\\\\\\\\\nu_i &\\\\sim \\\\mathcal{N}(0, \\\\mathrm{I}_{d}/2) \\\\qquad (i = 1,\\\\ldots,h).\n\\\\end{aligned}\n```\nAs ``h \\\\to \\\\infty``, the neural network converges to the Gaussian process\n```math\ng(\\\\cdot) \\\\sim \\\\mathcal{GP}\\\\big(0, \\\\sigma_b^2 + \\\\sigma_v^2 k(\\\\cdot, \\\\cdot)\\\\big),\n```\nwhere the neural network kernel ``k`` is given by\n```math\nk(x, x') = \\\\arcsin\\\\left(\\\\frac{x^\\\\top x'}{\\\\sqrt{\\\\big(1 + \\\\|x\\\\|^2_2\\\\big) \\\\big(1 + \\\\|x'\\\\|_2^2\\\\big)}}\\\\right)\n```\nfor inputs ``x, x' \\\\in \\\\mathbb{R}^d``.[^CW]\n\n[^CW]: C. K. I. Williams (1998). Computation with infinite neural networks.\n\"\"\"\nstruct NeuralNetworkKernel <: Kernel end\n\nfunction (κ::NeuralNetworkKernel)(x, y)\n    return asin(dot(x, y) / sqrt((1 + sum(abs2, x)) * (1 + sum(abs2, y))))\nend\n\nfunction kernelmatrix(::NeuralNetworkKernel, x::ColVecs, y::ColVecs)\n    validate_inputs(x, y)\n    X_2 = sum(x.X .* x.X; dims=1)\n    Y_2 = sum(y.X .* y.X; dims=1)\n    XY = x.X' * y.X\n    return asin.(XY ./ sqrt.((X_2 .+ 1)' * (Y_2 .+ 1)))\nend\n\nfunction kernelmatrix(::NeuralNetworkKernel, x::ColVecs)\n    X_2_1 = sum(x.X .* x.X; dims=1) .+ 1\n    XX = x.X' * x.X\n    return asin.(XX ./ sqrt.(X_2_1' * X_2_1))\nend\n\nfunction kernelmatrix_diag(::NeuralNetworkKernel, x::ColVecs)\n    x_2 = vec(sum(x.X .* x.X; dims=1))\n    return asin.(x_2 ./ (x_2 .+ 1))\nend\n\nfunction kernelmatrix_diag(::NeuralNetworkKernel, x::ColVecs, y::ColVecs)\n    validate_inputs(x, y)\n    x_2 = vec(sum(x.X .* x.X; dims=1) .+ 1)\n    y_2 = vec(sum(y.X .* y.X; dims=1) .+ 1)\n    xy = vec(sum(x.X' .* y.X'; dims=2))\n    return asin.(xy ./ sqrt.(x_2 .* y_2))\nend\n\nfunction kernelmatrix(::NeuralNetworkKernel, x::RowVecs, y::RowVecs)\n    validate_inputs(x, y)\n    X_2 = sum(x.X .* x.X; dims=2)\n    Y_2 = sum(y.X .* y.X; dims=2)\n    XY = x.X * y.X'\n    return asin.(XY ./ sqrt.((X_2 .+ 1) * (Y_2 .+ 1)'))\nend\n\nfunction kernelmatrix(::NeuralNetworkKernel, x::RowVecs)\n    X_2_1 = sum(x.X .* x.X; dims=2) .+ 1\n    XX = x.X * x.X'\n    return asin.(XX ./ sqrt.(X_2_1 * X_2_1'))\nend\n\nfunction kernelmatrix_diag(::NeuralNetworkKernel, x::RowVecs)\n    x_2 = vec(sum(x.X .* x.X; dims=2))\n    return asin.(x_2 ./ (x_2 .+ 1))\nend\n\nfunction kernelmatrix_diag(::NeuralNetworkKernel, x::RowVecs, y::RowVecs)\n    validate_inputs(x, y)\n    x_2 = vec(sum(x.X .* x.X; dims=2) .+ 1)\n    y_2 = vec(sum(y.X .* y.X; dims=2) .+ 1)\n    xy = vec(sum(x.X .* y.X; dims=2))\n    return asin.(xy ./ sqrt.(x_2 .* y_2))\nend\n\nBase.show(io::IO, ::NeuralNetworkKernel) = print(io, \"Neural Network Kernel\")\n", "meta": {"hexsha": "40070075d079cbcdab4753b9f958dec098926eb8", "size": 3118, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basekernels/nn.jl", "max_stars_repo_name": "bmharsha/KernelFunctions.jl", "max_stars_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 200, "max_stars_repo_stars_event_min_datetime": "2020-04-07T11:28:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:14:13.000Z", "max_issues_repo_path": "src/basekernels/nn.jl", "max_issues_repo_name": "bmharsha/KernelFunctions.jl", "max_issues_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 324, "max_issues_repo_issues_event_min_datetime": "2020-03-24T16:26:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T07:34:54.000Z", "max_forks_repo_path": "src/basekernels/nn.jl", "max_forks_repo_name": "bmharsha/KernelFunctions.jl", "max_forks_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2020-03-25T10:25:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T21:19:06.000Z", "avg_line_length": 32.8210526316, "max_line_length": 118, "alphanum_fraction": 0.5997434253, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7928047552327342}}
{"text": "\r\n\r\nfunction ldl_decomp(A)\r\n    # assumption: the matrix A is positive definite (Hermitian)\r\n    # not explicitly checked but assumed: n_row == n_col\r\n    # only the lower left part is used from A\r\n\r\n    (n_row, n_col) = size(A)\r\n    L = UnitLowerTriangular( zeros(n_row, n_col) )\r\n    d = zeros(n_col)\r\n\r\n    # initial d element\r\n    @inbounds d[1] = A[1,1]\r\n    @inbounds for jj = 1:(n_col-1)\r\n\r\n        # determine the next column of L\r\n        @inbounds for ii = (jj+1):n_row\r\n            internal_sum = zero(eltype(A))\r\n            @inbounds @simd for kk = 1:(jj-1)\r\n                @fastmath internal_sum += d[kk] * L[jj,kk] * L[ii,kk]\r\n            end\r\n            @fastmath L[ii, jj] = (A[ii, jj] - internal_sum)/ d[jj]\r\n        end\r\n        \r\n\r\n        # determine the next d element\r\n        diag_sum = zero(eltype(A))\r\n        @inbounds @simd for kk = 1:jj\r\n            @fastmath diag_sum += d[kk] * L[jj+1, kk]^2\r\n        end\r\n        @fastmath d[jj+1] = A[jj+1, jj+1] - diag_sum\r\n    end\r\n\r\n    return (L, d)\r\nend\r\n\r\n\r\n\r\nfunction linsolve_ldl(A, b)\r\n\r\n    (L, d) = ldl_decomp(A)\r\n    y = triangular_solve_lower_colwise(L, b)\r\n    @fastmath y ./= d\r\n    x = triangular_solve_upper_colwise_transposed(L, y)\r\n\r\n    return x\r\nend\r\n", "meta": {"hexsha": "66d0902f01fbb8137c7e51b800cdc431250ae25a", "size": 1240, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/linalg/src/ldl.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "__lib__/math/linalg/src/ldl.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "__lib__/math/linalg/src/ldl.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8333333333, "max_line_length": 70, "alphanum_fraction": 0.5427419355, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429474, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.792804745514984}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.8\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 86a927d5-0b05-4a7a-83c4-0f98fb15509e\nbegin\n\tusing PlutoUI\n\tusing Plots\nend\n\n# ╔═╡ 5d15bae3-d408-4f74-98a3-8b5e53562770\nmd\"\"\"\n# Chapter 4\n#### Nicetak\n $(import Dates; Dates.format(Dates.today(), Dates.DateFormat(\"U d, Y\")))\n\"\"\"\n\n# ╔═╡ 435ece74-d26a-11eb-1bd1-5b65d058f3a1\nmd\"\"\"\n## 4.1\nトリボナッチ数列の第$N$項の値を求める再起関数を設計してください.\n\"\"\"\n\n# ╔═╡ 4a01190f-1e0e-4371-9847-e66eeab849b9\nfunction f₁(n)\n\tif n == 0\n\t\treturn 0\n\telseif n == 1\n\t\treturn 0\n\telseif n == 2\n\t\treturn 1\n\tend\n\t\n\treturn f₁(n - 1) + f₁(n - 2) + f₁(n - 3)\nend\n\n# ╔═╡ 0224c51b-3028-45f0-bf6c-7423aac643a6\nwith_terminal() do\n\tfor n ∈ 0:9\n\t\tprintln(\"n = $n: $(f₁(n))\")\n\tend\nend\n\n# ╔═╡ aa51aa81-b8be-4e65-b259-e816655d01c9\nplot(n -> (@timed f₁(n)).time, 1:33,\n\ttitle = \"Computational Time of Naive Tribonacci\",\n\txlabel = \"n\",\n\tylabel = \"Seconds\",\n\tlegend = false\n)\n\n# ╔═╡ 5d8bedcf-6f20-4be3-961b-3b81ef486209\nmd\"\"\"\n## 4.2\n問題4.1で設計した再帰関数をメモ化によって効率化してください.\nまた, メモ化を実施後の計算量を評価してください.\n\"\"\"\n\n# ╔═╡ 1f806382-2995-4da2-b33d-c0403c530163\nfunction f₂(n, memo = -ones(Int, n))\n\tif n == 0\n\t\treturn 0\n\telseif n == 1\n\t\treturn 0\n\telseif n == 2\n\t\treturn 1\n\tend\n\t\n\tif memo[n] != -1\n\t\treturn memo[n]\n\tend\n\t\n\tres = f₂(n - 1, memo) + f₂(n - 2, memo) + f₂(n - 3, memo)\n\tmemo[n] = res\n\treturn res\nend\n\n# ╔═╡ 645cdd0a-97c5-4a90-a70e-09a3571142db\nwith_terminal() do\n\tfor n ∈ 0:9\n\t\tprintln(\"n = $n: $(f₂(n))\")\n\tend\nend\n\n# ╔═╡ d65730a4-ec5f-436f-876b-fc98eb203107\nmd\"\"\"\n計算量は$T_0, \\dots, T_{N-1}$までメモ化されている時, $T_N$の計算量が$O(1)$であることから, $O(N)$.\n\"\"\"\n\n# ╔═╡ 3ac6e8f6-a3e9-4d81-a271-5457b20477bc\nplot(n -> median((@timed f₂(n)).time for _ in 1:100), 1:3000,\n\ttitle = \"Computational Time of Memorized Tribonacci\",\n\txlabel = \"n\",\n\tylabel = \"Seconds\",\n\tlegend = false\n)\n\n# ╔═╡ f6e73830-ad09-4718-868d-26f6a2c11b16\nmd\"\"\"\n## 4.3\nフィボナッチ数列の一般項が\n$F_N = \\frac{1}{\\sqrt{5}}\\left[\\left(\\frac{1 + \\sqrt{5}}{2}\\right)^N -\n\\left(\\frac{1 - \\sqrt{5}}{2}\\right)^N \\right]$\nで表されることを示してください.\n\"\"\"\n\n# ╔═╡ 65503b27-14d4-42c8-abec-70060988d465\nmd\"\"\"\n**答**\n$F_0 = 1, F_1 = 1$は自明. 一般項を$F_{N-1}$まで仮定して,\n\n$\\begin{aligned}\n\\sqrt{5}(F_{N-1} + F_{N-2}) &= \\left(1 + \\frac{2}{1 + \\sqrt{5}}\\right)\n\\left(\\frac{1 + \\sqrt{5}}{2}\\right)^{N-1} -\n\\left(1 + \\frac{2}{1 - \\sqrt{5}}\\right)\n\\left(\\frac{1 - \\sqrt{5}}{2}\\right)^{N-1} \\\\\n&= \\left(\\frac{1 + \\sqrt{5}}{2}\\right)^N -\n\\left(\\frac{1 - \\sqrt{5}}{2}\\right)^N.\n\\end{aligned}$\nよって,\n$F_N = F_{N - 1} + F_{N - 2}$.\n帰納法から, 命題は示された.\n\"\"\"\n\n# ╔═╡ ae54b3e7-e04c-457f-839d-8aeecb6eba0d\nmd\"\"\"\n## 4.4\nコード 4.5で示したアルゴリズムの計算量が $O\\left(\\left(\\frac{1 + \\sqrt{5}}{2}\\right)^N\\right)$ で与えられることを示してください.\n\"\"\"\n\n# ╔═╡ e0cd89ce-9a49-4d51-9c36-1b467b3e4add\nmd\"\"\"\n**答** コード4.5のアルゴリズムの計算量が$O(f(N))$であると仮定する.\n定義から, $f(0) = f(1) = 1$は自明. また, Big Oの計算規則とコードの定義から,\n\n$f(N) = f(N - 1) + f(N - 2).$\n\nこれはフィボナッチ数列と一致し, 一般項は問4.3で示された通りである.\n支配項は$\\left(\\frac{1 + \\sqrt{5}}{2}\\right)^N$であるから, 命題は示された.\n\"\"\"\n\n# ╔═╡ 0303b656-d949-4365-b884-bf7bbc026a6d\nmd\"\"\"\n## 4.6\n部分和問題に対する再帰関数を用いる計算量$O(2^N)$のコード4.9に対してメモ化して, $O(NW)$ の計算量で動作するようにしてください.\n\"\"\"\n\n# ╔═╡ 14bcda24-9431-468a-ac5b-4bf6feb1e8e8\nfunction f₆(as, w, i = length(as), memo = -ones(Int, length(as), w))\n\tif w < 0\n\t\treturn false\n\telseif w == 0\n\t\treturn true\n\telseif i == 0\n\t\treturn false\n\tend\n\t\n\tif memo[i, w] == 1\n\t\treturn true\n\telseif memo[i, w] == 0\n\t\treturn false\n\tend\n\t\t\n\tif f₆(as, w, i - 1, memo)\n\t\tmemo[i, w] = 1\n\t\treturn true\n\telseif f₆(as, w - as[i], i - 1, memo)\n\t\tmemo[i, w] = 1\n\t\treturn true\n\telse\n\t\tmemo[i, w] = 0\n\t\treturn false\n\tend\n\t\t\nend\n\n# ╔═╡ 501824d0-017f-4d05-a477-cd7f4cef1df8\nwith_terminal() do\n\tprintln(\"Given a = [2, 4, 8]\")\n\tfor w ∈ 1:16\n\t\tprintln(\"w = $w: $(f₆([2, 4, 8], w))\")\n\tend\nend\n\n# ╔═╡ Cell order:\n# ╟─5d15bae3-d408-4f74-98a3-8b5e53562770\n# ╠═86a927d5-0b05-4a7a-83c4-0f98fb15509e\n# ╟─435ece74-d26a-11eb-1bd1-5b65d058f3a1\n# ╠═4a01190f-1e0e-4371-9847-e66eeab849b9\n# ╟─0224c51b-3028-45f0-bf6c-7423aac643a6\n# ╟─aa51aa81-b8be-4e65-b259-e816655d01c9\n# ╟─5d8bedcf-6f20-4be3-961b-3b81ef486209\n# ╠═1f806382-2995-4da2-b33d-c0403c530163\n# ╟─645cdd0a-97c5-4a90-a70e-09a3571142db\n# ╟─d65730a4-ec5f-436f-876b-fc98eb203107\n# ╟─3ac6e8f6-a3e9-4d81-a271-5457b20477bc\n# ╟─f6e73830-ad09-4718-868d-26f6a2c11b16\n# ╟─65503b27-14d4-42c8-abec-70060988d465\n# ╟─ae54b3e7-e04c-457f-839d-8aeecb6eba0d\n# ╟─e0cd89ce-9a49-4d51-9c36-1b467b3e4add\n# ╟─0303b656-d949-4365-b884-bf7bbc026a6d\n# ╠═14bcda24-9431-468a-ac5b-4bf6feb1e8e8\n# ╟─501824d0-017f-4d05-a477-cd7f4cef1df8\n", "meta": {"hexsha": "f87393e5d40077d1c076be2226240032aac28122", "size": 4393, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/chapter04/nicetak/chap4.jl", "max_stars_repo_name": "tokuma09/algorithm_problems", "max_stars_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-07T15:46:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T15:46:58.000Z", "max_issues_repo_path": "problems/chapter04/nicetak/chap4.jl", "max_issues_repo_name": "tokuma09/algorithm_problems", "max_issues_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-06-05T14:16:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-10T07:08:28.000Z", "max_forks_repo_path": "problems/chapter04/nicetak/chap4.jl", "max_forks_repo_name": "tokuma09/algorithm_problems", "max_forks_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3252427184, "max_line_length": 94, "alphanum_fraction": 0.6435237878, "num_tokens": 2503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087926320944, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7927801131583765}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.17\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nfunction rouletteSpins(r,p)\n    x = 0\n    wins = 0\n    while true\n        x += 1\n        if rand() < p\n            wins += 1\n            if wins == r\n                return x\n            end\n        end\n    end\nend\n\n# ╔═╡ 6b47d86c-2163-11eb-157b-136057260d22\nbegin\n\tr, p, N = 5, 18/37,10^6\n\txGrid = r:r+15\n\n\tmcEstimate = counts([rouletteSpins(r,p) for _ in 1:N],xGrid)/N\n\n\tnbDist = NegativeBinomial(r,p)\n\tnbPmf = [pdf(nbDist,x-r) for x in xGrid]\nend;\n\n# ╔═╡ 6b480968-2163-11eb-0f1c-d18166a51f5e\nbegin\n\tplot( xGrid, mcEstimate, \n\t\tline=:stem, marker=:circle, c=:blue, \n\t\tms=10, msw=0, lw=4, label=\"MC estimate\")\n\tplot!( xGrid, nbPmf, line=:stem, \n\t\t marker=:xcross, c=:red, ms=6, msw=0, lw=2, label=\"PMF\", \n\t\t xlims=(0,maximum(xGrid)), ylims=(0,0.2), \n\t\t xlabel=\"x\", ylabel=\"Probability\")\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.17\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═6b47d86c-2163-11eb-157b-136057260d22\n# ╠═6b480968-2163-11eb-0f1c-d18166a51f5e\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "3b611206182f777f4208b68cf7ab42cfa03b9560", "size": 1601, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.17.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.17.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.17.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 23.5441176471, "max_line_length": 63, "alphanum_fraction": 0.6602123673, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7927801130554291}}
{"text": "using LinearAlgebra\nusing StatsBase\n\n\n\"\"\"\n    shift_to_non_negative(matrix::Array)\n\nReturns a matrix in which values are non-negative. This is done by finding the\nminimal value in the input matrix and adding its absolute value to the matrix\nelements.\n\"\"\"\nfunction shift_to_non_negative(matrix::Array)\n\n    min_val = findmin(matrix)[1]\n    if min_val < 0\n        return matrix .-= min_val\n    else\n        return matrix\n    end\nend\n\n\n\n\"\"\"\n    normalize_to_01(matrix::Array; use_factor=false, norm_factor=256)\n\nReturns a matrix which values are in range [0, 1]. If 'use_factor' is set to\n'true' then values are normalized to 'norm_factor' (by default set to 256).\n\nIf the values in the input matrix are below 0, then they are shifted so that only positive numbers are in\nthe matrix (the values are normalized to new maximal value or norm_factor).\n\"\"\"\nfunction normalize_to_01(matrix::Array; use_factor = false, norm_factor = 256)\n    normalized_matrix = copy(matrix)\n\n    min_val = findmin(normalized_matrix)[1]\n    if min_val < 0\n        normalized_matrix .+= abs(min_val)\n    else\n        normalized_matrix .-= abs(min_val)\n    end\n\n    max_val = findmax(normalized_matrix)[1]\n\n    if use_factor\n        if max_val > norm_factor\n            @warn \"Maximal values exceed \\'norm_factor\\'.\"\n        end\n        normalized_matrix = normalized_matrix ./ norm_factor\n    else\n        normalized_matrix = normalized_matrix ./ max_val\n    end\n\n    return normalized_matrix\nend\n\n\n# function symmetrize_image(image)\n\"\"\"\n    function diagonal_symmetrize(image::Matrix; below_over_upper::Bool=false)\n\nTakes an 'image' in the form of a matrix and return a copy which is symmetric\nwith respect to diagonal- values above diagonal are copied over values below the\ndiagonal. This can be inverted by setting 'below_over_upper=true'.\n\nIf the input matrix is not square, then square matrix is created by taking\nmatrix of k times 'k' elements, 'k=min(r,c)' where 'r' is number of rows and 'c'\nis number of columns.\n\"\"\"\nfunction diagonal_symmetrize(image::Matrix; below_over_upper::Bool = false)\n    w, h = size(image)\n    mat_size = findmin([w, h])[1]\n\n    img = copy(image[1:mat_size, 1:mat_size])\n\n    # Get all cartesian indices from input matrix\n    matrix_indices = CartesianIndices((1:mat_size, 1:mat_size))\n    # Filter out indices below diagonal\n    if below_over_upper\n        matrix_indices = findall(x -> x[1] > x[2], matrix_indices)\n    else\n        matrix_indices = findall(x -> x[2] > x[1], matrix_indices)\n    end\n\n\n    # how many elements are above diagonal\n    repetition_number = Int(ceil((mat_size * (mat_size - 1)) / 2))\n\n    # Substitute elements\n    for k = 1:repetition_number\n        # n_pos = matrix_indices[k]\n        mat_ind = matrix_indices[k]\n        # ordered_matrix[mat_ind] = k\n        img[mat_ind[2], mat_ind[1]] = img[mat_ind]\n    end\n\n    try\n        checksquare(img)\n    catch err\n        if isa(err, DimensionMismatch)\n            @error \"Resulting matrix is not a square matrix\"\n            throw(err)\n        end\n    end\n    # issymmetric(Float64.(img))\n    return img\nend\n\n\n# =====\n# matrix ordering\n\n\n\"\"\"\n    function get_ordered_matrix(in_matrix::Matrix;\n                                assign_same_values::Bool = false,\n                                force_symmetry::Bool = false,\n                                small_dist_grouping::Bool = false,\n                                min_dist::Number = 1e-16,\n                                total_dist_groups::Int = 0,\n                                ordering_start::Int=1)\n\nTakes a @input_matrix and returns ordered form of this matrix.\nThe ordered form is a matrix which elements represent ordering from smallest to\nhighest values in @input_matrix.\n\nIf @input_matrix is symmetric, then ordering happens only with upper diagonal.\nLower diagonal is symetrically copied from values above diagonal.\n\nBy default, if there is a geoup of entriess with the same value, they all are\nassigned with the same ordering number. This can be changed with\n@assign_same_values parameter.\n\nSymetry ordering can be froced with @force_symmetry parameter.\n\nBy setting 'small_dist_grouping' to true, all the values that difference is\nlower than 'min_dist', will be assigned with the same order number.\n\n# Examples\n```julia-repl\njulia> a = [0 11 12;\n            11 0 13;\n            12 13 0];\njulia> get_ordered_matrix(a)\n3×3 Array{Int64,2}:\n 0  1  2\n 1  0  3\n 2  3  0\n```\n\n```julia-repl\njulia> b = [38 37 36 30;\n            37 34 30 32;\n            36 30 31 30;\n            30 32 30 29]\njulia> get_ordered_matrix(b; assign_same_values=false)\n4×4 Array{Int64,2}:\n0  6  5  2\n6  0  1  4\n5  1  0  3\n2  4  3  0\n\njulia> get_ordered_matrix(b; assign_same_values=true)\n4×4 Array{Int64,2}:\n0  4  3  1\n4  0  1  2\n3  1  0  1\n1  2  1  0\n```\n\"\"\"\nfunction get_ordered_matrix(in_matrix::Matrix;\n                            assign_same_values::Bool = false,\n                            force_symmetry::Bool = false,\n                            small_dist_grouping::Bool = false,\n                            min_dist::Number = 1e-16,\n                            total_dist_groups::Int = 0,\n                            ordering_start::Int=1)\n\n    # TODO Symmetry must be forced for matrix in which there are NaN elements- needs\n    #   to be further investigated\n    # TODO not working for negative only values\n    # TODO check for square matrix\n\n    # ==\n    mat_size = size(in_matrix)\n    ord_mat = zeros(Int, mat_size)\n\n    # how many elements are above diagonal\n    if issymmetric(in_matrix) || force_symmetry\n        matrix_indices =\n            generate_indices(mat_size, symmetry_order = true, include_diagonal = false)\n        do_symmetry = true\n    else\n        matrix_indices = generate_indices(mat_size, symmetry_order = false)\n        do_symmetry = false\n    end\n    total_elements = length(matrix_indices)\n\n    # Collect vector of indices\n    all_ind_collected = arr_to_vec(matrix_indices)\n\n    # Sort indices vector according to inpu array\n    # TODO Cant this be done with sortperm? in_matrix > UpperTriangular |> sortperm\n    index_sorting = sort_indices_by_values(in_matrix, all_ind_collected)\n\n    ordering_number = ordering_start\n    for k = 1:total_elements\n        # global ordering_number\n        next_sorted_pos = index_sorting[k]\n        mat_ind = matrix_indices[next_sorted_pos]\n\n        if assign_same_values && k != 1\n            prev_sorted_pos = index_sorting[k-1]\n            prev_mat_ind = matrix_indices[prev_sorted_pos]\n\n            cond1 = in_matrix[prev_mat_ind] == in_matrix[mat_ind]\n            cond2 = small_dist_grouping\n            cond3 = abs(in_matrix[prev_mat_ind] - in_matrix[mat_ind]) < min_dist\n\n            if cond1 || (cond2 && cond3)\n                ordering_number -= 1\n            end\n        end\n        set_values!(ord_mat, mat_ind, ordering_number; do_symmetry = do_symmetry)\n        ordering_number += 1\n        # else\n        #     set_values!(ord_mat, mat_ind, ordering_number; do_symmetry=do_symmetry)\n        #     ordering_number+=1\n        # end\n    end\n\n    return ord_mat\nend\n\n\n# TODO this one has to be specified for 3 dim matrix\nfunction get_ordered_matrix(input_array::Array{Any,3}; do_slices = true, dims = 0)\n    arr_size = size(input_array)\n    out_arr = zeros(Int, arr_size)\n\n    if do_slices\n        # param check\n        if dims > length(arr_size)\n            throw(DomainError(\"Given dimension is greater than total size of array.\"))\n        elseif dims > 0\n            throw(DomainError(\"Given dimension must be positive value.\"))\n        elseif dims <= 3\n            throw(DomainError(\"Given dimension must be lower than 3.\"))\n        end\n\n        for dim = 1:arr_size[dims]\n            if dims == 1\n                out_arr[dim, :, :] = get_ordered_matrix(input_array[dim, :, :])\n            elseif dims == 2\n                out_arr[:, dim, :] = get_ordered_matrix(input_array[:, dim, :])\n            elseif dims == 3\n                out_arr[:, :, dim] = get_ordered_matrix(input_array[:, :, dim])\n            end\n        end\n    else\n        out_arr = get_ordered_matrix(input_array)\n    end\nend\n\nfunction get_ordered_matrix(input_array::Array)\n    out_array = copy(input_array)\n    arr_size = size(input_array)\n    total_elements = length(input_array)\n\n    # Collect vector of indices\n    all_ind_collected = collect(reshape(generate_indices(arr_size), (length(input_array))))\n\n    # Sort indices vector according to inpu array\n    index_sorting = sort!(\n        [1:total_elements;],\n        by = i -> (input_array[all_ind_collected][i], all_ind_collected[i]),\n    )\n\n    for k = 1:total_elements\n        target = index_sorting[k]\n        out_array[target] = k\n    end\n\n    return out_array\nend\n\n\n\n\n# Care must be taken so that values from 'input_matrix' are within distance\n# groups, otherwise error is thrown.\n\"\"\"\n    function group_distances(input_matrix::Array, total_dist_groups::Int)\n\nTakes a matrix and rearranges values into 'total_dist_groups' number of groups.\nEvery group is assigned with number value from range '<0,1>'.\n\"\"\"\nfunction group_distances(input_matrix::Array, total_dist_groups::Int)\n\n    normed_matrix = normalize_to_01(input_matrix)\n    target_matrix = copy(normed_matrix)\n\n    h, w = size(input_matrix)\n\n    if h * w < total_dist_groups\n        throw(DomainError(\"Total number of groups exceed total number of entries in input matrix\"))\n    end\n\n    total_borders = total_dist_groups + 1\n\n    range_val = collect(range(0, 1, length = total_borders))\n\n    for k = 2:total_borders\n        indices = findall(x -> x >= range_val[k-1] && x <= range_val[k], normed_matrix)\n        target_matrix[indices] .= range_val[k]\n    end\n    unique(target_matrix)\n\n    # Sets last range to values smaller than unity, just in case this might cause trobules\n    # normed_matrix[normed_matrix .> range_val[end-1]] .= 0.99\n    return target_matrix\nend\n\n\n\n\"\"\"\n    generate_indices(matrix_size::Tuple; symmetry_order::Bool=false, include_diagonal::Bool=true)\n\nReturn all the possible indices of the matrix of size 'matrix_size'.\n'matrix_size' may be a tuple or a series of integer arguments corresponding to\nthe lengths in each dimension.\n\nIf 'symetry_order' is set to'true', then only indices of values below diagonal\nare returned.\n\"\"\"\nfunction generate_indices(matrix_size::Tuple;\n                            symmetry_order::Bool = false,\n                            include_diagonal::Bool = true)\n\n    # Get all cartesian indices from input matrix\n    matrix_indices = CartesianIndices(matrix_size)\n    # Filter out indices below diagonal\n    if symmetry_order\n        matrix_indices = findall(x -> x[1] <= x[2], matrix_indices)\n    else\n        matrix_indices = findall(x -> true, matrix_indices)\n    end\n\n    if !include_diagonal\n        filter!(x -> x[1] != x[2], matrix_indices)\n    end\n\n    return matrix_indices\nend\n\n\n\"\"\"\n    generate_indices(matrix_size::Int; symmetry_order::Bool=false, include_diagonal::Bool=true)\n\nGenerate indices for a matrix of given dimensions. 'generate_indices' is a\nseries of integer arguments corresponding to the lengths in each dimension.\n\"\"\"\nfunction generate_indices(matrix_size::Int;\n                            symmetry_order::Bool = false,\n                            include_diagonal::Bool = true)\n    return generate_indices(\n        (matrix_size, matrix_size);\n        symmetry_order = symmetry_order,\n        include_diagonal = include_diagonal,\n    )\nend\n\n\n\n\"\"\"\n    arr_to_vec(some_array::Array)\n\nTakes an array and reshapes it into a vector.\n\"\"\"\nfunction arr_to_vec(some_array::Array)\n    return collect(reshape(some_array, length(some_array)))\nend\n\nfunction cartesianInd_to_vec(some_array::CartesianIndices)\n    return collect(reshape(some_array, length(some_array)))\nend\n\n\n\"\"\"\n    sort_indices_by_values(values_matrix::T, index_vector) where {T<:VecOrMat}\n\nSorts the 'index_vector' according to corresponding values in the 'values_matrix'\nand returns a Vector of intigers which is an list of ordering of\n'sorted index_vector'.\n\"\"\"\nfunction sort_indices_by_values(values_matrix::T, index_vector) where {T<:VecOrMat}\n    if !isa(index_vector, Vector)\n        throw(TypeError(\n            :sort_indices_by_values,\n            \"\\'index_vector\\' must be a vector, otherwise an ordering list can no be created!\",\n            Vector,\n            typeof(index_vector),\n        ))\n    end\n    total_elements = length(index_vector)\n    return sort!(\n        [1:total_elements;],\n        by = i -> (values_matrix[index_vector][i], index_vector[i]),\n    )\nend\n\n\n\"\"\"\n    set_values!(input_matrix::Matrix, position::CartesianIndex, target_value::Number; do_symmetry=false)\n\nAssigns 'target_value' to indices at 'input_matrix[position[1], position[2]]'.\nIf 'do_symmetry' is set to 'true', then the 'target_value' is also assigned at\nposition 'input_matrix[position[2], position[1]]'.\n\"\"\"\nfunction set_values!(input_matrix::Matrix,\n                        position::CartesianIndex,\n                        target_value::Number;\n                        do_symmetry::Bool = false)\n    input_matrix[position[1], position[2]] = target_value\n    if do_symmetry\n        input_matrix[position[2], position[1]] = target_value\n    end\n    return input_matrix\nend\n\n# matrix ordering\n# =====\n\nfunction get_high_dim_ordered_matrix(input_matrix)\n    matrix_size = size(input_matrix)\n    ordered_matrix_3D = zeros(Int, matrix_size)\n\n    for slice = 1:matrix_size[1]\n        ordered_matrix_3D[slice, :, :] = get_ordered_matrix(input_matrix[slice, :, :])\n    end\n    return ordered_matrix_3D\nend\n\n\n\"\"\"\n    reduce_arrs_to_min_len(arrs)\n\nTakes vector of vectors of different length and returns array of arrays which\nare of the same length. Length in the output is the shortest vector length from\nthe input- values above this size are discarded.\n\"\"\"\nfunction reduce_arrs_to_min_len(arrs::Array)\n    @debug \"Argument specific\"\n    new_arr = copy(arrs)\n\n    simulation = size(new_arr, 1)\n    min_size = Inf\n    for m = 1:simulation\n        @debug \"Simulation number\" m\n        current_size = size(new_arr[m], 1)\n        @debug \"Current size: \" current_size\n        if convert(Float64, current_size) < min_size\n            min_size = current_size\n            @debug \"min size changed to: \" min_size\n        end\n    end\n    # min_size = Int.(min_size)\n    @debug \"Concatenating\"\n    for m = 1:simulation\n        new_arr[m] = new_arr[m][1:min_size, :]\n    end\n    min_size = Inf\n    return new_arr\nend\n\n\n\"\"\"\n    increase_arrs_to_max_len(arrs)\n\nTakes vector of vectors of different length and returns array of arrays which\nare of the same length. Length in the output is the longest vector length from\nthe input- values above this size are discarded.\n\"\"\"\nfunction increase_arrs_to_max_len(arrs)\n    new_arr = copy(arrs)\n\n    simulation = size(new_arr, 1)\n    max_size = 0\n    for m = 1:simulation\n        @debug \"Simulation number\" m\n        current_size = size(new_arr[m], 1)\n        @debug \"Current size: \" current_size\n        if convert(Float64, current_size) > max_size\n            max_size = current_size\n            @debug \"min size changed to: \" max_size\n        end\n    end\n    # max_size = Int.(max_size)\n    @debug \"Concatenating\"\n    for m = 1:simulation\n        correct_len_arr = zeros(Int, max_size, 3)\n        correct_len_arr[1:size(arrs[m], 1), :] = new_arr[m][:, :]\n        new_arr[m] = correct_len_arr\n    end\n    # min_size = Inf\n    return new_arr\nend\n", "meta": {"hexsha": "1f9d7e62cc211ce7ea1a88f005882b487c8a99e6", "size": 15396, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MatrixProcessing.jl", "max_stars_repo_name": "edd26/TopologyPreprocessing.jl", "max_stars_repo_head_hexsha": "273497114e8adf84244d3b24b0155b3ae813b84d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-08T02:01:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-08T02:01:57.000Z", "max_issues_repo_path": "src/MatrixProcessing.jl", "max_issues_repo_name": "edd26/TopologyPreprocessing", "max_issues_repo_head_hexsha": "12948c0ff3885f8fc2fa6b98d46b8d1c599715fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-11-30T16:38:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T15:10:02.000Z", "max_forks_repo_path": "src/MatrixProcessing.jl", "max_forks_repo_name": "edd26/TopologyPreprocessing", "max_forks_repo_head_hexsha": "12948c0ff3885f8fc2fa6b98d46b8d1c599715fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3070866142, "max_line_length": 105, "alphanum_fraction": 0.660236425, "num_tokens": 3790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7927781134945181}}
{"text": "export GammaShapeRate\n\nimport Distributions: Gamma, shape, rate\nimport SpecialFunctions: loggamma, digamma, gamma\nimport StatsFuns: log2π\n\nstruct GammaShapeRate{T <: Real} <: ContinuousUnivariateDistribution\n    a :: T\n    b :: T\nend\n\nGammaShapeRate(a::Real, b::Real)       = GammaShapeRate(promote(a, b)...)\nGammaShapeRate(a::Integer, b::Integer) = GammaShapeRate(float(a), float(b))\nGammaShapeRate(a::Real)                = GammaShapeRate(a, one(a))\nGammaShapeRate()                       = GammaShapeRate(1.0, 1.0)\n\nDistributions.@distr_support GammaShapeRate 0 Inf\n\nDistributions.support(dist::GammaShapeRate) = Distributions.RealInterval(minimum(dist), maximum(dist))\n\nDistributions.shape(dist::GammaShapeRate)  = dist.a\nDistributions.rate(dist::GammaShapeRate)   = dist.b\nDistributions.scale(dist::GammaShapeRate)  = inv(dist.b)\nDistributions.mean(dist::GammaShapeRate)   = shape(dist) / rate(dist)\nDistributions.var(dist::GammaShapeRate)    = shape(dist) / abs2(rate(dist))\nDistributions.params(dist::GammaShapeRate) = (shape(dist), rate(dist))\n\nfunction Distributions.entropy(dist::GammaShapeRate)\n    a, b = params(dist)\n    return a - log(b) + loggamma(a) + (1-a)*digamma(a)\nend\n\nfunction logmean(dist::GammaShapeRate)\n    a, b = params(dist)\n    return digamma(a) - log(b)\nend\n\nfunction loggammamean(dist::GammaShapeRate)\n    a, b = params(dist)\n    return 0.5 * (log2π - (digamma(a) - log(b))) + mean(dist) * (-1 + digamma(a + 1) - log(b))\nend\n\nfunction meanlogmean(dist::GammaShapeRate)\n    a, b = params(dist)\n    return mean(dist) * (digamma(a + 1) - log(b))\nend\n\nBase.eltype(::GammaShapeRate{T}) where T = T\n\nBase.convert(::Type{ GammaShapeRate{T} }, a::Real, b::Real) where { T <: Real } = GammaShapeRate(convert(T, a), convert(T, b))\n\nvague(::Type{ <: GammaShapeRate }) = GammaShapeRate(1.0, tiny)\n\nprod_analytical_rule(::Type{ <: GammaShapeRate }, ::Type{ <: GammaShapeRate }) = ProdAnalyticalRuleAvailable()\n\nfunction prod(::ProdAnalytical, left::GammaShapeRate, right::GammaShapeRate)\n    T = promote_type(eltype(left), eltype(right))\n    return GammaShapeRate(shape(left) + shape(right) - one(T), rate(left) + rate(right))\nend\n\nDistributions.pdf(dist::GammaShapeRate, x::Real)    = (rate(dist)^shape(dist)) / gamma(shape(dist)) * x^(shape(dist)-1)*exp(-rate(dist) * x)\nDistributions.logpdf(dist::GammaShapeRate, x::Real) = shape(dist) * log(rate(dist)) - loggamma(shape(dist)) + (shape(dist)-1)*log(x) - rate(dist)*x\n", "meta": {"hexsha": "e1d1a48e05162c709ede6b62f7142414a6f6bb45", "size": 2439, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distributions/gamma_shape_rate.jl", "max_stars_repo_name": "albertpod/ReactiveMP.jl", "max_stars_repo_head_hexsha": "71c390e6b41e6890ba808640d0bf3ef2f66efc71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2021-03-28T13:18:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:52:52.000Z", "max_issues_repo_path": "src/distributions/gamma_shape_rate.jl", "max_issues_repo_name": "albertpod/ReactiveMP.jl", "max_issues_repo_head_hexsha": "71c390e6b41e6890ba808640d0bf3ef2f66efc71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 58, "max_issues_repo_issues_event_min_datetime": "2021-03-17T16:07:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T08:50:44.000Z", "max_forks_repo_path": "src/distributions/gamma_shape_rate.jl", "max_forks_repo_name": "albertpod/ReactiveMP.jl", "max_forks_repo_head_hexsha": "71c390e6b41e6890ba808640d0bf3ef2f66efc71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-07-12T18:48:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T17:19:20.000Z", "avg_line_length": 38.7142857143, "max_line_length": 147, "alphanum_fraction": 0.6961869619, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.8558511543206819, "lm_q1q2_score": 0.7927781116000486}}
{"text": "using LabelledArrays\n\nexport rossler_lorenz\n\n@inline @inbounds function eom_rossler_lorenz(u, p, t)\n    c_xy, a₁, a₂, a₃, b₁, b₂, b₃ = (p...,)\n    x1, x2, x3, y1, y2, y3 = u[1], u[2], u[3], u[4], u[5], u[6] \n    \n    dx1 = -a₁*(x2 + x3)\n    dx2 = a₁*(x1 + a₂*x2)\n    dx3 = a₁*(a₂ + x3*(x1 - a₃))\n    dy1 = b₁*(-y1 + y2)\n    dy2 = b₂*y1 - y2 - y1*y3 + c_xy*(x2^2)\n    dy3 = y1*y2 - b₃*y3\n    \n    return SVector{6}(dx1, dx2, dx3, dy1, dy2, dy3)\nend\n\n\"\"\"\n    rossler_lorenz(;u₀ = rand(6), a₁ = -6, a₂ = 6, a₃ = 2.0, \n        b₁ = 10, b₂ = 28, b₃ = 8/3, c_xy = 1) → ContinuousDynamicalSystem\n\nInitialise a Rössler-Lorenz system consisting of two independent 3D subsystems:\none Rössler system and one Lorenz system. They are coupled such that the\nsecond component (`x₂`) of the Rössler system unidirectionally forces the\nsecond component (`y₂`) of the Lorenz system. \n\nThe parameter `c_xy` controls the coupling strength. The implementation here also \nallows for tuning the parameters of each subsystem by introducing the constants \n`a₁`, `a₂`, `a₃`, `b₁`, `b₂`, `b₃`. Default values for these parameters are \nas in [1].\n\n## Equations of motion \n\nThe dynamics is generated by the following vector field\n\n```math\n\\\\begin{aligned}\n\\\\dot x_1 &= a_1(x_2 + x_3) \\\\\\\\\n\\\\dot x_2 &= a_2(x_1 + 0.2x_2) \\\\\\\\\n\\\\dot x_3 &= a_2(0.2 + x_3(x_1 - a_3)) \\\\\\\\\n\\\\dot y_1 &= b_1(y_2 - y_1) \\\\\\\\\n\\\\dot y_2 &= y_1(b_2 - y_3) - y_2 +c_{xy}(x_2)^2 \\\\\\\\\n\\\\dot y_3 &= y_1 y_2 - b_3y_3\n\\\\end{aligned}\n```\n\nwith the coupling constant ``c_{xy} \\\\geq 0``.\n\n## References\n\n1. Krakovská, Anna, et al. \"Comparison of six methods for the detection of causality in a \n    bivariate time series.\" Physical Review E 97.4 (2018):042207. \n    [https://journals.aps.org/pre/abstract/10.1103/PhysRevE.97.042207](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.97.042207)\n\"\"\"\nfunction rossler_lorenz(;u₀ = rand(6), a₁ = -6, a₂ = 6, a₃ = 2.0, \n    b₁ = 10, b₂ = 28, b₃ = 8/3, c_xy = 1)\n\n    p = @LArray [c_xy, a₁, a₂, a₃, b₁, b₂, b₃] (:c_xy, :a₁, :a₂, :a₃, :b₁, :b₂, :b₃)\n    ContinuousDynamicalSystem(eom_rossler_lorenz, u₀, p)\nend\n", "meta": {"hexsha": "8417abd1102ec98829ca1917d5b43eb74a4d9996", "size": 2093, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/example_systems/continuous_systems/rossler_lorenz.jl", "max_stars_repo_name": "kahaaga/CausalityTools.jl", "max_stars_repo_head_hexsha": "e1de3943a2ccb3c9997ca38e7a4fac025f1f8475", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2018-11-07T11:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-05T06:26:37.000Z", "max_issues_repo_path": "src/example_systems/continuous_systems/rossler_lorenz.jl", "max_issues_repo_name": "kahaaga/CausalityTools.jl", "max_issues_repo_head_hexsha": "e1de3943a2ccb3c9997ca38e7a4fac025f1f8475", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2018-09-04T08:02:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-04T11:59:38.000Z", "max_forks_repo_path": "src/example_systems/continuous_systems/rossler_lorenz.jl", "max_forks_repo_name": "kahaaga/CausalityTools.jl", "max_forks_repo_head_hexsha": "e1de3943a2ccb3c9997ca38e7a4fac025f1f8475", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-12-03T10:59:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:02:55.000Z", "avg_line_length": 33.7580645161, "max_line_length": 136, "alphanum_fraction": 0.629718108, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7927781100121293}}
{"text": "\"\"\"\n- second-order (so)\n    ||z1|| <= z2\n\nA Semismooth Newton Method for Fast, Generic Convex Programming\n    https://arxiv.org/abs/1705.00772\n\n# todo: try backtracking linesearch for cone\n    https://digital.lib.washington.edu/researchworks/bitstream/handle/1773/43279/Dueri_washington_0250E_19426.pdf?isAllowed=y&sequence=1\n\"\"\"\n\n# second-order cone\nfunction κ_so(z)\n    z1 = z[1:end-1]\n    z2 = z[end]\n\n    z_proj = zero(z)\n\n    if norm(z1) <= z2\n        z_proj = copy(z)\n    elseif norm(z1) <= -z2\n        z_proj = zero(z)\n    else\n        a = 0.5 * (1.0 + z2 / norm(z1))\n        z_proj[1:end-1] = a * z1\n        z_proj[end] = a * norm(z1)\n    end\n\n    return z_proj\nend\n\n# second-order cone Jacobian\nfunction Jκ_so(z)\n    z1 = z[1:end-1]\n    z2 = z[end]\n    m = length(z)\n\n    if norm(z1) <= z2\n        return Diagonal(ones(m))\n    elseif norm(z1) <= -z2\n        return Diagonal(zeros(m))\n    else\n        D = zeros(m, m)\n        for i = 1:m\n            if i < m\n                D[i, i] = 0.5 + 0.5 * z2 / norm(z1) - 0.5 * z2 * ((z1[i])^2.0) / norm(z1)^3.0\n            else\n                D[i, i] = 0.5\n            end\n            for j = 1:m\n                if j > i\n                    if j < m\n                        D[i, j] = -0.5 * z2 * z1[i] * z1[j] / norm(z1)^3.0\n                        D[j, i] = -0.5 * z2 * z1[i] * z1[j] / norm(z1)^3.0\n                    elseif j == m\n                        D[i, j] = 0.5 * z1[i] / norm(z1)\n                        D[j, i] = 0.5 * z1[i] / norm(z1)\n                    end\n                end\n            end\n        end\n        return D\n    end\nend\n\nfunction cone_product(z, s)\n    if length(z) > 1\n        z0 = z[1]\n        z1 = z[2:end]\n\n        s0 = s[1]\n        s1 = s[2:end]\n        return [z' * s; z0 * s1 + s0 * z1]\n    else\n        return [z' * s]\n    end\nend\n\nfunction e_soc(n)\n    e = zeros(n)\n    e[1] = 1.0\n    return e\nend\n", "meta": {"hexsha": "9239290f6bfdec2a8a31da76920cf32f9025250c", "size": 1888, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cones/second_order.jl", "max_stars_repo_name": "jmichaux/motion_planning", "max_stars_repo_head_hexsha": "9a36f394261ff11ca8325d8a5e9d8a79f18b2744", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2021-02-07T10:46:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:30:20.000Z", "max_issues_repo_path": "src/cones/second_order.jl", "max_issues_repo_name": "jmichaux/motion_planning", "max_issues_repo_head_hexsha": "9a36f394261ff11ca8325d8a5e9d8a79f18b2744", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-10-07T05:36:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-11T17:16:28.000Z", "max_forks_repo_path": "src/cones/second_order.jl", "max_forks_repo_name": "thowell/motion_planning", "max_forks_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-01-25T19:23:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T06:43:01.000Z", "avg_line_length": 22.4761904762, "max_line_length": 136, "alphanum_fraction": 0.4443855932, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7927781083858908}}
{"text": "#\n\nusing Gadfly, Colors\nusing Distributions\nusing FFTW\nusing DSP\n\n\n\np1 = Normal(-pi/2, 0.5)\np2 = Normal(pi/2, 0.5)\np12_t = Normal(0.0, 1.0/sqrt(8.0))\n\n\nx = range(-pi, stop=pi, length=1024)\n\ng1 = (x)->pdf(p1,x)\ng2 = (x)->pdf(p2,x)\ng12_t = (x)->pdf(p12_t,x)\n\n\ny1 = g1.(x)\ny2 = g2.(x)\ny12_t = g12_t.(x)\n\ny12_t .*= 0.5\ntemp = fftshift(y12_t)\ny12_t .+= temp\n\n\nplot(y=y12_t, Geom.line)\n\n\nY12_t = fftshift(fft(y12_t))\n\n\n\npl = Gadfly.plot(\nlayer(y=abs.(Y1), Geom.line, Theme(default_color=colorant\"red\")),\nlayer(y=abs.(Y2), Geom.line, Theme(default_color=colorant\"blue\")),\nlayer(y=abs.(Y12_t), Geom.line, Theme(default_color=colorant\"magenta\"))\n)\n\npl |> SVG(\"/tmp/test.svg\",100cm,100cm)\n\n\ny12_tr = ifft(ifftshift(Y12_t))\n\nplot(y=abs.(y12_tr), Geom.line)\n\n\n\nplot(\nlayer(x=x, y=y1, Geom.line, Theme(default_color=colorant\"red\")),\nlayer(x=x, y=y2, Geom.line, Theme(default_color=colorant\"blue\"))\n)\n\n\nusing Makie\n\n\nscene = lines(x, abs.(y12_tr), color = :blue)\n# scatter!(scene, x, y1, color = :red, markersize = 0.1)\n\n\n\n\n\nY1 = fftshift(fft(y1))\nY2 = fftshift(fft(y2))\nY12_t = fft(y12_t)\n\n\nplot(y=abs.(Y1), Geom.line)\nplot(y=abs.(Y2), Geom.line)\n\n\n\nY12 = conv((Y1), (Y2))\n\nst = 1\noff = 2046\ny12 = ifft(ifftshift(Y12[st:(st+off)]))\n\n\nplot(y=abs.(y12), Geom.line)\n\n\n\n# plot(x=real.(Y1), y=imag.(Y1), Geom.point)\n# plot(x=real.(Y2), y=imag.(Y2), Geom.point)\n\nplot(y=abs.(Y12), Geom.line)\n\n\n\n\n##\n\n#YY1 = [Y1; Y1; Y1]\nYY2 = [ifftshift(Y2); ifftshift(Y2); ifftshift(Y2)]\n\nplot(y=abs.(YY1), Geom.line)\n\n\nYY12 = conv(ifftshift(Y1), (YY2))\n\n\nplot(y=abs.(YY12), Geom.line)\n\n\n\n\nst = 1024\noff = 2047\nyy12 = ifft(ifftshift(YY12[st:(st+off)]))\n\n\npl = plot(y=abs.(yy12), Geom.line)\n\n\n##\n\nusing Cairo, Fontconfig\nusing Gadfly\n\npl |> PDF(\"/tmp/test.pdf\", 30cm, 20cm)\n\nrun(`evince /tmp/test.pdf`)\n\n\n##\n\n\n\nplot(x=real.(Y12_t), y=imag.(Y12_t), Geom.point)\n\n# brute force product\ny12_d = y1 .* y2\ny12_d ./= sum(y12_d)*(x[2]-x[1])\n\n\n\nplot(\nlayer(x=x, y=y1, Geom.line, Theme(default_color=colorant\"red\")),\nlayer(x=x, y=y2, Geom.line, Theme(default_color=colorant\"blue\")),\nlayer(x=x, y=y12_d, Geom.line, Theme(default_color=colorant\"magenta\"))\n)\n\n\n\n\n# calculating the square using convolution\n\ny1sqrt = sqrt.(y1)\n\nY1sqrt = fft(y1sqrt)\n\nY11 = conv(Y1sqrt, conj(Y1sqrt))\n\n##\n\nst = 1\noff = 512\ny11 = ifft(Y11[st:(st+off)])\n\n\n\nplot(\nlayer(y=y1, Geom.line, Theme(default_color=colorant\"red\")),\nlayer(y=abs.(y11)./(sum(abs.(y11))*(x[2]-x[1])), Geom.line, Theme(default_color=colorant\"blue\"))\n# layer(x=x, y=y12_d, Geom.line, Theme(default_color=colorant\"magenta\"))\n)\n\n\n\n\n\n\n\n\n\n\n\n## Linear convolution in Euclid space\n\nxx = 0:127;\n\nY = (x::Real; mu::Real=0.0) -> pdf(Normal(mu, 1.0), x)\n\ny1 = Y.(xx, mu=10)\ny2 = Y.(xx, mu=20)\n\nfY1 = fft(y1)\nfY2 = fft(y2)\n\nfYY = fY1.*fY2\nyy = abs.(ifft(fYY))\n\nplot(\n  layer(\n    x=xx,\n    y=y1,\n    Geom.line\n  ),\n  layer(\n    x=xx,\n    y=y2,\n    Geom.line,\n    Theme(default_color=colorant\"deepskyblue\")\n  ),\n  layer(\n    x=xx,\n    y=yy,\n    Geom.line,\n    Theme(default_color=colorant\"magenta\")\n  )\n)\n\n\n\n## Test with Sine function\n\nx = range(-7.5, stop=7.5, length=2048)\ny = sin.(10.0*x) + sin.(100.0*x)\n\nY = fft(y)\n\nYs = fftshift(Y)\n\nplot(y=abs.(Ys), Geom.line)\n\n\n\n#\n", "meta": {"hexsha": "e1903896108055a21ad96baad665cd789c9bcd21", "size": 3159, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/FourierProducts.jl", "max_stars_repo_name": "akhand1111/ApproxManifoldProducts.jl", "max_stars_repo_head_hexsha": "f7c37c963d3c8d9504502935456fc79197e7abef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-10-01T22:36:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T07:10:29.000Z", "max_issues_repo_path": "examples/FourierProducts.jl", "max_issues_repo_name": "akhand1111/ApproxManifoldProducts.jl", "max_issues_repo_head_hexsha": "f7c37c963d3c8d9504502935456fc79197e7abef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 163, "max_issues_repo_issues_event_min_datetime": "2018-10-01T22:39:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T01:47:57.000Z", "max_forks_repo_path": "examples/FourierProducts.jl", "max_forks_repo_name": "akhand1111/ApproxManifoldProducts.jl", "max_forks_repo_head_hexsha": "f7c37c963d3c8d9504502935456fc79197e7abef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-01-10T13:59:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T11:48:20.000Z", "avg_line_length": 13.3855932203, "max_line_length": 96, "alphanum_fraction": 0.6229819563, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8688267813328977, "lm_q1q2_score": 0.7927489766164528}}
{"text": "# N = 13195 # 29\n N = 600851475143 # 6857\nubound = Int(ceil(sqrt(N)))\nif ubound%2 == 0\n\tubound -= 1\nend\nlpf = 1\n\nfunction isPrime(n::Int)\n\tfor i in 2:ceil(sqrt(n))\n\t\tif n%i==0\n\t\t\treturn false\n\t\tend\n\tend\n\treturn true\nend\n\nwhile ubound > 1\n\tif N%ubound==0 && isPrime(ubound)\n\t\tlpf = ubound\n\t\tbreak\n\tend\n\tubound -= 2\nend\nprintln(N, '\\t', lpf)\n", "meta": {"hexsha": "ad07e4bc2ec7f1ff241e824364d9162b870b41de", "size": 340, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "algo/su.3.jl", "max_stars_repo_name": "cdluminate/MyNotes", "max_stars_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algo/su.3.jl", "max_issues_repo_name": "cdluminate/MyNotes", "max_issues_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algo/su.3.jl", "max_forks_repo_name": "cdluminate/MyNotes", "max_forks_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.0769230769, "max_line_length": 34, "alphanum_fraction": 0.6205882353, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.8688267779364222, "lm_q1q2_score": 0.7927489693798613}}
{"text": "\"\"\"\ndiffper(n,xspan)\n\nConstruct 2nd-order differentiation matrices for functions with\nperiodic end conditions, using `n` unique nodes in the interval\n`xspan`. Return a vector of nodes and the  matrices for the first\nand second derivatives.\n\"\"\"\nfunction diffper(n,xspan)\n    a,b = xspan\n    h = (b-a)/n\n    x = @. a + h*(0:n-1)   # nodes, omitting the repeated data\n\n    # Construct Dx by diagonals, then correct the corners.\n    dp = fill(0.5/h,n-1)        # superdiagonal\n    dm = fill(-0.5/h,n-1)       # subdiagonal\n    Dx = diagm(-1=>dm,1=>dp)\n    Dx[1,n] = -1/(2*h)\n    Dx[n,1] = 1/(2*h)\n\n    # Construct Dxx by diagonals, then correct the corners.\n    d0 =  fill(-2/h^2,n)        # main diagonal\n    dp =  ones(n-1)/h^2         # superdiagonal and subdiagonal\n    Dxx = diagm(-1=>dp,0=>d0,1=>dp)\n    Dxx[1,n] = 1/(h^2)\n    Dxx[n,1] = 1/(h^2)\n\n    return x,Dx,Dxx\nend\n", "meta": {"hexsha": "34ac1dd73a53fd2fb3a66f6270be13d965a52e22", "size": 873, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter11.jl", "max_stars_repo_name": "tobydriscoll/fnc", "max_stars_repo_head_hexsha": "dde6097e6a9efff3c8cd7748c96214b4fcec2dc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2020-07-15T15:31:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T14:48:49.000Z", "max_issues_repo_path": "src/chapter11.jl", "max_issues_repo_name": "tobydriscoll/fnc", "max_issues_repo_head_hexsha": "dde6097e6a9efff3c8cd7748c96214b4fcec2dc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-07-20T15:42:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T19:08:43.000Z", "max_forks_repo_path": "src/chapter11.jl", "max_forks_repo_name": "tobydriscoll/fnc", "max_forks_repo_head_hexsha": "dde6097e6a9efff3c8cd7748c96214b4fcec2dc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-07-26T17:42:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T06:10:19.000Z", "avg_line_length": 29.1, "max_line_length": 65, "alphanum_fraction": 0.5990836197, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7927086217241981}}
{"text": "function get_energy( p::Param, every::Int , tlimit::Float64)\n\n    #Get variables\n    xmin        = p.xmin\n    xmax        = p.xmax\n    Nx          = p.xnodes\n\n    ymin        = p.ymin\n    ymax        = p.ymax\n    Ny          = p.ynodes\n\n    #Discretize space\n    dx      = (xmax - xmin)/(Nx-1)\n    x       = [xmin + (i-1)*dx for i in 1:Nx]\n\n    dy      = (ymax - ymin)/(Ny-1)\n    y       = [ymin + (i-1)*dy for i in 1:Ny]\n\n    if(p.Boundaries == :periodic )\n        dx      = (xmax - xmin)/(Nx)\n        x       = [xmin + (i-1)*dx for i in 1:Nx]   \n        \n        dy      = (ymax - ymin)/(Ny)\n        y       = [ymin + (i-1)*dy for i in 1:Ny] \n    end\n\n    #Create Differential Operators \n    Dx  =   Diff_Operator_2D(1 ,1, [dx,dy] , [Nx,Ny]) \n    Dxx =   Diff_Operator_2D(2 ,1, [dx,dy] , [Nx,Ny])\n    \n    Dy  =   Diff_Operator_2D(1 ,2, [dx,dy] , [Nx,Ny]) \n    Dyy =   Diff_Operator_2D(2 ,2, [dx,dy] , [Nx,Ny]) \n    \n    if(p.Boundaries == :periodic )\n        Dx  =   Diff_Operator_2D_Periodic(1 ,1, [dx,dy] , [Nx,Ny])\n        Dxx =   Diff_Operator_2D_Periodic(2 ,1, [dx,dy] , [Nx,Ny])\n \n        Dy  =  Diff_Operator_2D_Periodic(1 ,2, [dx,dy] , [Nx,Ny]) \n        Dyy =  Diff_Operator_2D_Periodic(2 ,2, [dx,dy] , [Nx,Ny])\n    end\n   \n\n    #Get max time iteration \n    max_sim_iter , tmax = get_t_max(p)    \n    max_plot_iter = max_sim_iter\n\n    if(tlimit <=  tmax)\n        max_plot_iter = floor(Int , max_sim_iter * tlimit/tmax )\n    else\n        println(\"ATTENTION: max time input is larger than simulation time, using tmax\")\n    end\n    #Mas user iteration\n    \n    #Potential Matrix\n    Vpot = potential_matrix(p)\n\n    # Total volume of space\n    Volume = ((ymax-ymin)*(xmax-xmin))\n\n    #Storage vectors\n    E_vector = Float64[]\n    t_vector = Float64[]\n\n    t = 0\n    E = 0\n\n    #Loop to get energy\n    for i in 1:every:max_plot_iter\n        \n        #Time and fields\n        t, _ , _ , ψ , dψ = get_fields(p,i)\n\n        #Volume element\n        dV = dx*dy\n        E = 0\n        \n        #Gradient term (possibly wrong)\n         vx = Dx * reshape(ψ, Nx*Ny)\n         vy = Dy * reshape(ψ, Nx*Ny)\n\n        #Potential term\n        v2 = Vpot * reshape(ψ, Nx*Ny)\n     \n        #Add all terms\n        for i in 1:(Nx*Ny) #length(ψ)\n            E+= vx[i]^2 + vy[i]^2 + dψ[i]^2 + (p.μ)^2*ψ[i]^2 + v2[i]^2\n        end\n     \n        #Add to storage vectors  and normalize\n        push!(t_vector, t)\n        push!(E_vector, dV * E / Volume )\n    end\n\n    return t_vector , E_vector\n\nend\n\n\nfunction get_energy( fname::String, every::Int , tlimit::Float64)\n\n    #Get Variables  \n    fid         = h5open( fname , \"r\")\n\n    xmin = read_attribute(fid, \"xmin\")\n    xmax = read_attribute(fid, \"xmax\")\n    Nx   = read_attribute(fid, \"xnodes\")\n\n    ymin = read_attribute(fid, \"ymin\")\n    ymax = read_attribute(fid, \"ymax\")\n    Ny   = read_attribute(fid, \"ynodes\")\n\n    #Discretize space\n    dx      = (xmax - xmin)/(Nx-1)\n    x       = [xmin + (i-1)*dx for i in 1:Nx]\n\n    dy      = (ymax - ymin)/(Ny-1)\n    y       = [ymin + (i-1)*dy for i in 1:Ny]\n\n    #Create Differential Operators \n    Dx  =   Diff_Operator_2D(1 ,1, [dx,dy] , [Nx,Ny]) \n    Dxx =   Diff_Operator_2D(2 ,1, [dx,dy] , [Nx,Ny])\n    \n    Dy  =   Diff_Operator_2D(1 ,2, [dx,dy] , [Nx,Ny]) \n    Dyy =   Diff_Operator_2D(2 ,2, [dx,dy] , [Nx,Ny]) \n    \n\n    #Get max time iteration \n    max_sim_iter , tmax = get_t_max(fname)    \n    max_plot_iter = max_sim_iter\n\n    if(tlimit <=  tmax)\n        max_plot_iter = floor(Int , max_sim_iter * tlimit/tmax )\n    else\n        println(\"ATTENTION: max time input is larger than simulation time, using tmax\")\n    end\n    #Mas user iteration\n    \n    #Potential Matrix\n   # Vpot = potential_matrix(p)\n\n    # Total volume of space\n    Volume = ((ymax-ymin)*(xmax-xmin))\n\n    #Storage vectors\n    E_vector = Float64[]\n    t_vector = Float64[]\n\n    t = 0\n    E = 0\n\n    #Loop to get energy\n    for i in 1:every:max_plot_iter\n        \n        #Time and fields\n        t, _ , _ , ψ , dψ = get_fields(fname,i)\n\n        #Volume element\n        dV = dx*dy\n        E = 0\n        \n        #Gradient term (possibly wrong)\n         vx = Dx * reshape(ψ, Nx*Ny)\n         vy = Dy * reshape(ψ, Nx*Ny)\n\n        #Potential term\n       # v2 = Vpot * reshape(ψ, Nx*Ny)\n     \n        #Add all terms\n        for i in 1:(Nx*Ny) #length(ψ)\n            E+= vx[i]^2 + vy[i]^2 + dψ[i]^2 # + (p.μ)^2*ψ[i]^2  # + v2[i]^2\n        end\n     \n        #Add to storage vectors  and normalize\n        push!(t_vector, t)\n        push!(E_vector, dV * E / Volume )\n    end\n\n    return t_vector , E_vector\n\nend", "meta": {"hexsha": "d18e68a433b5bbacb5b4b7b01c26b02d2da2d540", "size": 4556, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/get_energy.jl", "max_stars_repo_name": "diogoribeiro98/BhAbs-Solver", "max_stars_repo_head_hexsha": "c014326aef6cf25f0a2fb61125cc84cd3955a16e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/get_energy.jl", "max_issues_repo_name": "diogoribeiro98/BhAbs-Solver", "max_issues_repo_head_hexsha": "c014326aef6cf25f0a2fb61125cc84cd3955a16e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/get_energy.jl", "max_forks_repo_name": "diogoribeiro98/BhAbs-Solver", "max_forks_repo_head_hexsha": "c014326aef6cf25f0a2fb61125cc84cd3955a16e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3111111111, "max_line_length": 87, "alphanum_fraction": 0.5193151888, "num_tokens": 1547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.8418256432832332, "lm_q1q2_score": 0.7927086198557984}}
{"text": "# Simple example of an inhomogeneous heat equation:\n#\n#           y\n#             |\n#             |     u_y = 0\n#          Ly ----------------------------------\n#             |                                |\n#             |                                |\n#             |                                |\n#     u_x = 0 |    u_t - a(u_xx + u_yy) = f    | u_x = 0\n#             |                                |\n#             |                                |\n#             |                                |\n#           -----------------------------------|-----  x\n#                         u_y = 0              Lx\n#\n# Here, a>0, the initial data is u0 = 0 and the source term is\n#\n#      f(x, y, t) = t cos(pi x / Lx) cos(pi y / Ly)\n#\n# The exact solution is\n#\n#                    lambda t - 1 - exp(-lambda t) \n#      u(x, y, t) =  ----------------------------- phi(x,y)\n#                          lambda^2\n#\n# where\n#\n#      phi(x,y) = cos(pi x / Lx ) cos(pi y / Ly)\n#      lambda = a pi^2 ( 1 / Lx^2 + 1 / Ly^2 )\n#\nusing FinElt\nusing FinElt.PlanarPoisson\ninclude(\"ode23s.jl\")\n\nconst a = 0.1\nconst Lx = 1.0\nconst Ly = 1.0\nconst lambda = a * pi^2 * ( 1/Lx^2 + 1/Ly^2 )\nconst T = 2.0\n\nfunction phi(x)\n    return cos(pi*x[1]/Lx)* cos(pi*x[2]/Ly)\nend\n\nfunction exact_u(x, t)\n    v = ( lambda*t - 1 + exp(-lambda*t) ) / lambda^2\n    return v * phi(x)\nend\n\nfunction f(x, t)\n    return t * phi(x)\nend\n\nfunction RHS(t, u, S, mesh, dof)\n    F = assembled_vector(\"Omega\", source_times_func!, \n                         x -> f(x,t), mesh, dof)\n    return F - S * u\nend\n\nmaxnorm(x) = norm(x, Inf)\n\nstart = time()\nmesh = read_msh_file(\"../rectangle/rect2.msh\")    \ndof = degrees_of_freedom(mesh, String[])\nM = assembled_matrix(\"Omega\", func_times_func!, 1.0, mesh, dof)\nS = assembled_matrix(\"Omega\", grad_dot_grad!, a, mesh, dof)\nu0 = zeros(length(dof.freenode))\nt, u = ode23s((t,u) -> RHS(t, u, S, mesh, dof), u0, [0,T]; \n             reltol=1.0e-4, abstol=1.0e-4, mass=M, norm=maxnorm)\n\nN = length(t)\nerr = zeros(N)\nfor n = 1:N\n    un = get_nodal_vals(x->exact_u(x,t[n]), mesh)\n    err[n] = maxnorm(un-u[n])\nend\n\nfinish = time()\nelapsed = finish - start\n\nfigure(1)\nplot(t, err)\nxlabel(L\"$t$\")\ntitle(\"Error solving the inhomogeneous heat equation\")\ngrid(true)\n", "meta": {"hexsha": "869cbbb49ca048f168508b0b662f8feed5735a17", "size": 2255, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/heat/inhomog.jl", "max_stars_repo_name": "billmclean/FinElt.jl", "max_stars_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-07-18T20:04:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:29:09.000Z", "max_issues_repo_path": "examples/heat/inhomog.jl", "max_issues_repo_name": "billmclean/FinElt.jl", "max_issues_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/heat/inhomog.jl", "max_forks_repo_name": "billmclean/FinElt.jl", "max_forks_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-06-29T15:15:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T18:01:08.000Z", "avg_line_length": 25.9195402299, "max_line_length": 64, "alphanum_fraction": 0.4390243902, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090322, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.79270651295414}}
{"text": "#=\nThis first example comes almost straight from the documentation for DiffEqFlux\n\nhttps://github.com/SciML/DiffEqFlux.jl#optimizing-parameters-of-an-ode-for-an-optimal-control-problem\nhttps://julialang.org/blog/2019/01/fluxdiffeq/\n\n=#\n\n\n\nmodule lotka_volterra\n\n\nusing DifferentialEquations, Flux, Optim, DiffEqFlux, Plots\n\nu0 = [1.0,1.0]\ntstart=0.0\ntend=10.0\nsampling=0.1\n\nmodel_params= [1.5,1.0,3.0,1.0]\n\nfunction model(du,u,p,t)\n  x, y = u\n  α, β, δ, γ = p\n  du[1] = dx = α*x - β*x*y\n  du[2] = dy = -δ*y + γ*x*y\nend\n\nfunction InitPlot(;vars=(0,1))\n    #Simple function to plot the dynamics\n    tspan=(tstart,tend)\n    prob = ODEProblem(model,u0,tspan,model_params)\n    sol = solve(prob,Tsit5())\n    plot(sol, lw=2, legend=false, vars=(0,1))\nend\n\nfunction predict_adjoint(param) # Our 1-layer neural network\n    prob=ODEProblem(model,[1.0,0.0],(tstart,tend), model_params)\n    Array(concrete_solve(prob,Tsit5(),param[1:2],param[3:end],saveat=tstart:sampling:tend, abstol=1e-8,reltol=1e-6))\nend\n\n# Generate some data to fit, and add some noise to it\ndata=predict_adjoint([1.0,1.0,1.5,1.0,3.0,1.0])\nσN=0.1\ndata+=σN*randn(size(data))\ndata=abs.(data) #Keep measurements positive\n\n\n# Returning more than just the loss function breaks the Flux optim\nfunction loss_adjoint(param)\n  prediction = predict_adjoint(param)\n  loss = sum(abs2,prediction - data)\n  loss\nend;\n\n#Test\n\nfunction train_model(;pguess=[0.8,1.2,1.2,1.0,2.9,1.1])\n    println(\"The initial loss function is $(loss_adjoint(pguess)[1])\")\n    #Train the ODE\n    resinit=DiffEqFlux.sciml_train(loss_adjoint,pguess,ADAM(), maxiters=3000)\n    res = DiffEqFlux.sciml_train(loss_adjoint,resinit.minimizer,BFGS(initial_stepnorm = 1e-5))\n    println(\"The parameters are $(res.minimizer) with final loss value $(res.minimum)\")\n    return(res)\nend\n\n\nfunction plotFit(param)\n\n    tspan=(tstart,tend)\n    sol_fit=solve(ODEProblem(model,param[1:2],tspan,param[3:end]), Tsit5())\n\n    tgrid=tstart:sampling:tend\n    pl=plot(sol_fit, lw=2, legend=false)\n    scatter!(pl,tgrid, data[1,:], color=:blue)\n    scatter!(pl,tgrid, data[2,:], color=:red)\n    xlabel!(pl,\"Time\")\n    ylabel!(pl,\"Population\")\n    title!(pl,\"Model Parameter Fits\")\n    savefig(\"Lotka_Volterra_ParamFit.png\")\n    display(pl)\nend\n\nfunction validationPlot(param, ic)\n    tspan=(tstart,tend)\n    sol_fit=solve(ODEProblem(model,ic,tspan,param[3:end]), Tsit5())\n    sol_actual=solve(ODEProblem(model,ic,tspan,model_params), Tsit5(), saveat=0.0:0.1:10.0)\n\n\n    pl=scatter(sol_actual, lw=2.0, color=:blue, vars=(0,1))\n    scatter!(sol_actual, color=:red, vars=(0,2))\n    plot!(pl, sol_fit, lw=2, legend=false, color=:blue, vars=(0,1))\n    plot!(pl, sol_fit, lw=2, color=:red, vars=(0,2))\n    xlabel!(pl,\"Rabbits\")\n    ylabel!(pl,\"Lynx\")\n    title!(pl,\"Validation Plot\")\n    savefig(\"Lotka_Volterra_Validation_Plot.png\")\n    display(pl)\nend\n\nend #module\n\nlotka_volterra.InitPlot()\n\nresL=lotka_volterra.train_model()\n\nlotka_volterra.plotFit(resL.minimizer)\n\nlotka_volterra.validationPlot(resL.minimizer, [6.,6.])\n", "meta": {"hexsha": "f74c506f69d8dc259a79b19e15224fd80f9ad4e3", "size": 3018, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/lotka_volterra_param_fit.jl", "max_stars_repo_name": "khannay/FittingParamsDiffEqFlux", "max_stars_repo_head_hexsha": "19cf5691b5a81d8bdea945c266515dff70fb06ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-04-24T10:23:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T14:25:55.000Z", "max_issues_repo_path": "julia/lotka_volterra_param_fit.jl", "max_issues_repo_name": "khannay/FittingParamsDiffEqFlux", "max_issues_repo_head_hexsha": "19cf5691b5a81d8bdea945c266515dff70fb06ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-16T12:49:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-16T12:49:02.000Z", "max_forks_repo_path": "julia/lotka_volterra_param_fit.jl", "max_forks_repo_name": "khannay/FittingParamsDiffEqFlux", "max_forks_repo_head_hexsha": "19cf5691b5a81d8bdea945c266515dff70fb06ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-04T00:28:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T00:28:43.000Z", "avg_line_length": 27.1891891892, "max_line_length": 116, "alphanum_fraction": 0.6991385023, "num_tokens": 1012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7926993813615052}}
{"text": "#=\nAlgorithm RSVD.\ngiven a matrix A \\in \\reals^{m \\times n}, a target rank k and an oversampling\n      parameter p (e.g., p = 10 is a good choice).\nstage A. Find an approximate range.\n    1. form an n \\times (k+p) Gaussian random matrix G.\n    2. form the sample matrix Y = AG.\n    3. orthonormalize the columns of Y via a QR factorization.\nstage B. Form a specific factorization.\n    4. form the (k+p) \\times n matrix B = Q'A.\n    5. form the SVD of the (small) matrix B as B = \\hat{U} D V'.\n    6. form U = Q \\hat{U}.\nreturn matrices U, D, and V as an approximate rank (k+p) SVD of A.\n=#\nusing Random, LinearAlgebra, Plots, Statistics\n# ---------------------------------------------------------------------------- #\nfunction vignette_rsvd()\nrng = Random.seed!(2);              # set seed for reproducibility\nn_sims = 10;                        # number of simulations\nn_subs = 25;                        # number of subsamples\nm = 2000;                           # rows of matrix\nn = 20*ceil(log(m));                # columns of matrix\n# n_sims = 50; n_subs = 25; m = 1000; n = 15*ceil(log(m)); # alt. run parameters\n# n_sims = 1;  n_subs = 25; m = 5000; n = 15*ceil(log(m)); # alt. run parameters\nk = ceil(log(m));                   # target rank\np = max(ceil(log(m)), 10);          # oversampling parameter\nn = Int16(n); k = Int16(k); p = Int16(p);   # convert floats to integers\n# ---------------------------------------------------------------------------- #\ntimes = zeros(n_sims, 2);           # bookkeeping for run times\nfro_mean = zeros(n_sims, n_subs);   # bookkeeping for mean Frobenius norm\nop_mean = zeros(n_sims, n_subs);    # bookkeeping for mean operator norm\nnorm_bound = zeros(n_sims, 2);      # bookkeeping for theoretrical norm\nfro_lo = zeros(n_sims, 1);          # bookkeeping for Frobenius norm bound\nop_lo = zeros(n_sims, 1);           # bookkeeping for operator norm bound\n# ---------------------------------------------------------------------------- #\nfor j in 1:n_sims\n    # \"data\" matrix\n    A = [2*ones(m,2)+rand(m,2) randn(m, k-2) 0.01*randn(m, n-k)]/sqrt(m);\n    # NOTE: the matrix A has k columns that lead to \"important\" singular values.\n    # The remaing n-k columns correspond to fast-decaying singular values.\n    for i in 1:n_subs\n        # stage A of randomized SVD\n        G = randn(n, k+p);                              # Gaussian random matrix\n        Y = A*G;                                        # sample matrix\n        F = qr(Y); Q = Matrix(F.Q);                     # orthonormalize Y\n        # stage B of randomized SVD\n        B = Q'*A;                                       # form small matrix\n        U_B, D_B, V_B = svd(B);                         # SVD of B\n        U = Q*U_B;                                      # rank k matrix\n        # bookkeeping and comparisons\n        U_A, D_A, V_A = svd(A);                         # SVD of A\n        fro_mean[j,i] = norm(A - Q*Q'*A, 2);\n        op_mean[j,i] = opnorm(A - Q*Q'*A);\n    end # end of inner simulation loop (i.e., simulation for a fixed matrix A)\n    fro_lo[j,1] = sum( D_A[k+1:min(m,n)].^2 )^0.5;\n    op_lo[j,1] =  D_A[k+1];\n    norm_bound[j, 1] = (1 + k / (p-1))^(0.5) * fro_lo[j,1];     # Frobenius\n    norm_bound[j, 2] = (1 + sqrt(k / (p-1))) * op_lo[j,1] +     # operator\n                            exp(1) * (sqrt(k+p) / p) * fro_lo[j,1];\nend # end of outer simulation loop\n# ---------------------------------------------------------------------------- #\n# plot showing singular value decay\np3 = plot(D_A, yscale = :log10, linecolor = :blue,\n            marker = :circle, markercolor = :blue, label = \"full\",\n            title = \"sing. value decay (final sim.)\");\np4 = plot(D_A[1:k+p], yscale = :log10, linecolor = :blue,\n            marker = :circle, markercolor = :blue, label = \"full\",\n            title = \"sing. value comparison (final sim.)\")\nplot!(D_B, yscale = :log10, linecolor = :red, linestyle = :dash,\n            marker = :x, markerstrokecolor = :red, label = \"randomized\");\n\n# ---------------------------------------------------------------------------- #\n# plots of average Frobenius and operator norms vs. theoretical bounds\np1 = plot(norm_bound[:,1],linecolor = :blue, marker = :circle,\n            markercolor = :blue, label = \"upper\",\n            title = \"E-Y bounds: Frobenius\");\nplot!(mean(fro_mean, dims = 2),linecolor = :red, linestyle = :dash,\n     marker = :x, markerstrokecolor = :red, label = \"mean\");\n     plot!(fro_lo, linecolor = :blue, linestyle = :dot,\n           marker = :star8, markercolor = :blue, label = \"lower\",\n           legend = :bottomright);\np2 = plot(norm_bound[:,2],linecolor = :blue, marker = :circle,\n            markercolor = :blue, label = \"upper\",\n            title = \"E-Y bounds: operator\");\nplot!(mean(op_mean, dims = 2),linecolor = :red, linestyle = :dash,\n     marker = :x, markerstrokecolor = :red, label = \"mean\");\nplot!(op_lo,linecolor = :blue, linestyle = :dot,\n      marker = :star8, markercolor = :blue, label = \"lower\",\n      legend = :bottomright);\n# return summary plot as \"output\" of the function\nplot(p3, p4, p1, p2, layout=(2,2))\nend # end of function\n# ---------------------------------------------------------------------------- #\nvignette_rsvd()\n", "meta": {"hexsha": "c82e9c6fc3a9876b0204958b8430670b1862c29d", "size": 5229, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Demos/vignette-rsvd.jl", "max_stars_repo_name": "jakeknigge/randomized-algorithm-class", "max_stars_repo_head_hexsha": "5d1318ed06e59e518f815013c12d3e0935032cd4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-01-13T15:42:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T19:41:14.000Z", "max_issues_repo_path": "Demos/vignette-rsvd.jl", "max_issues_repo_name": "jakeknigge/randomized-algorithm-class", "max_issues_repo_head_hexsha": "5d1318ed06e59e518f815013c12d3e0935032cd4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-01-21T16:01:04.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-17T12:48:32.000Z", "max_forks_repo_path": "Demos/vignette-rsvd.jl", "max_forks_repo_name": "jakeknigge/randomized-algorithm-class", "max_forks_repo_head_hexsha": "5d1318ed06e59e518f815013c12d3e0935032cd4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-01-21T00:01:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T03:46:45.000Z", "avg_line_length": 55.0421052632, "max_line_length": 80, "alphanum_fraction": 0.5142474661, "num_tokens": 1455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.7926993707209667}}
{"text": "# Some misc functions related to quadratic optimization problems\n#\nimport LinearAlgebra: Symmetric, UniformScaling\n\n@doc raw\"\"\"\n```julia\ncheck_first_order(∇f::AbstractVector{<:Real},\n                  xstar::AbstractVector{<:Real},\n                  bc::BoundConstraints{<:Real,1})\n\ncheck_first_order(Q::Symmetric{<:Real},\n                  q::AbstractVector{<:Real},\n                  xstar::AbstractVector{<:Real},\n                  bc::BoundConstraints{<:Real,1})\n```\n\nCheck First-Order Conditions \n(see [Bound Constrained Optimization slides](https://wiki.mcs.anl.gov/leyffer/images/0/01/07-bndCons.pdf))\n\nIf ``x^\\star=\\arg\\min f(x), x\\in[l,u]`` then:\n\n```math\n\\partial_i f(x^\\star) = \\left\\{\\begin{array}{ll}\n\\ge 0, & \\text{if } x^\\star[i] = l[i] \\\\\n= 0, & \\text{if } l[i] \\le x^\\star[i] \\le u[i] \\\\\n\\le 0, & \\text{if } x^\\star[i] = u[i] \\\\\n\\end{array}\n\\right.\n```\n\nThis is equivalent to:\n```math\nx^\\star = P_{[l,u]}(x^\\star-\\nabla f(x^\\star))\n```\n\nAccording to the previous result, this function returns:\n```math\n\\max \\mid x^\\star - P_{[l,u]}(x^\\star-(Q.x^\\star+q)) \\mid\n```\n\nFor a local stationary point this quantity must be null \n\nThe second function is a wrapper that computes ``∇f=Q.x^\\star+q``\n\"\"\"\nfunction check_first_order(∇f::AbstractVector{<:Real},\n                           xstar::AbstractVector{<:Real},\n                           bc::BoundConstraints{<:Real,1})\n\n    # the condition assumes feasible constraints\n    @assert xstar ∈ bc\n\n    @assert size(∇f)==size(xstar)\n\n    # TODO: refactoring to avoid mem alloc\n    # (-> inline computation of max(...sequence...)\n    v = xstar-∇f\n    v = project!(v,bc)\n\n    maximum(abs.(xstar .- v))\nend\n\nfunction check_first_order(Q::Symmetric{<:Real},\n                           q::AbstractVector{<:Real},\n                           xstar::AbstractVector{<:Real},\n                           bc::BoundConstraints{<:Real,1})\n    # TODO: for BlasFloat use BLAS... to avoid unnecessary memory\n    # allocs...\n    ∇f=Q*xstar+q\n    check_first_order(∇f,xstar,bc)\nend\n", "meta": {"hexsha": "bfce7f14fc7e2720302869209b53196494b92435", "size": 2020, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/QuadSolvers/misc.jl", "max_stars_repo_name": "vincent-picaud/NLS_Solver.jl", "max_stars_repo_head_hexsha": "55d1a21e2128427ce168579ee67bde6f3499870b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-02T14:49:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T19:49:40.000Z", "max_issues_repo_path": "src/QuadSolvers/misc.jl", "max_issues_repo_name": "vincent-picaud/NLS_Solver.jl", "max_issues_repo_head_hexsha": "55d1a21e2128427ce168579ee67bde6f3499870b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-12-25T23:06:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-30T21:04:01.000Z", "max_forks_repo_path": "src/QuadSolvers/misc.jl", "max_forks_repo_name": "vincent-picaud/NLS_Solver.jl", "max_forks_repo_head_hexsha": "55d1a21e2128427ce168579ee67bde6f3499870b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4507042254, "max_line_length": 106, "alphanum_fraction": 0.5905940594, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.7926401071050655}}
{"text": "module TheAlgorithms\n\n# Usings/Imports (keep sorted)\nusing DataFrames\nusing DifferentialEquations\nusing GLM\nusing LinearAlgebra\nusing Plots\nusing Random\n\n\n## Exports\n# Please keep the folders/functions sorted\n\n# Exports: knapsack\nexport ZeroOnePack!\nexport CompletePack!\n\n# Exports: math\nexport abs_max\nexport abs_min\nexport abs_val\nexport area_circle\nexport area_ellipse\nexport area_heron_triangle\nexport area_parallelogram\nexport area_rectangle\nexport area_rhombus\nexport area_square\nexport area_trapezium\nexport area_triangle\nexport ceil_val, floor_val\nexport collatz_sequence\nexport euler_method\nexport is_armstrong\nexport line_length\nexport mean\nexport median\nexport mode\nexport SIR # TODO: make the name lowercase if possible\nexport surfarea_cube\nexport surfarea_sphere\nexport trapazoidal_area\n\n# Exports: matrix\nexport determinant\nexport lu_decompose\n\n# Exports: project-rosalind\nexport count_nucleotides\nexport dna2rna\nexport reverse_complement\n\n# Exports: searches\nexport binarysearch\nexport search\n\n# Exports: statistics\nexport OLSbeta\nexport PearsonCorrelation\n# Exports: strings\nexport is_palindrome\n\n# Exports: scheduling\nexport fcfs\n\n## Includes\n# Please keep the folders/files sorted (by dependencies then alphabetical order)\n\n# Includes: knapsack\ninclude(\"knapsack/knapsack.jl\")\n\n# Includes: math\ninclude(\"math/abs.jl\")\ninclude(\"math/area_under_curve.jl\")\ninclude(\"math/armstrong_number.jl\")\ninclude(\"math/area.jl\")\ninclude(\"math/average_mean.jl\")\ninclude(\"math/average_median.jl\")\ninclude(\"math/average_mode.jl\")\ninclude(\"math/ceil_floor.jl\")\ninclude(\"math/collatz_sequence.jl\")\ninclude(\"math/euler_method.jl\")\ninclude(\"math/line_length.jl\")\ninclude(\"math/sir_model.jl\")\n\n\n\n\n# Includes: matrix\ninclude(\"matrix/lu_decompose.jl\") # used by determinant.jl\ninclude(\"matrix/determinant.jl\")\n\n# Includes: project-rosalind\ninclude(\"project-rosalind/count_nucleotide.jl\")\ninclude(\"project-rosalind/dna2rna.jl\")\ninclude(\"project-rosalind/reverse_complement.jl\")\n\n# Includes: search\ninclude(\"searches/binary_search.jl\")\ninclude(\"searches/linear_search.jl\")\n\n# Includes: statistics\ninclude(\"statistics/ordinary_least_squares.jl\")\n\n# Includes: strings\ninclude(\"strings/is_palindrome.jl\")\n\n# Includes: scheduling\ninclude(\"scheduling/fcfs.jl\")\n\nend\n", "meta": {"hexsha": "1e0c7d59ca246694e6922aed832b6a3176d97f89", "size": 2252, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TheAlgorithms.jl", "max_stars_repo_name": "arubhardwaj/Julia", "max_stars_repo_head_hexsha": "cc8e8e942072f7bfb5479b25482133fd2c7141a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TheAlgorithms.jl", "max_issues_repo_name": "arubhardwaj/Julia", "max_issues_repo_head_hexsha": "cc8e8e942072f7bfb5479b25482133fd2c7141a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TheAlgorithms.jl", "max_forks_repo_name": "arubhardwaj/Julia", "max_forks_repo_head_hexsha": "cc8e8e942072f7bfb5479b25482133fd2c7141a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9292035398, "max_line_length": 80, "alphanum_fraction": 0.8148312611, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.7926400975863845}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ f252364e-f2e3-11ea-09b5-ff1a685abd56\nusing Pkg, DrWatson\n\n# ╔═╡ c126b36a-f2e3-11ea-1b0f-a7d38ecffcd8\nmd\"## Clip-03-01t.jl\"\n\n# ╔═╡ f2526f60-f2e3-11ea-2d32-276d0b91d917\n@quickactivate \"StatisticalRethinkingTuring\"\n\n# ╔═╡ f252ea76-f2e3-11ea-093a-01c585ee2ea1\nmd\"### snippet 3.1\"\n\n# ╔═╡ f25a9eec-f2e3-11ea-1611-9129817fe7a6\nbegin\n\tPr_Positive_Vampire = 0.95\n\tPr_Positive_Mortal = 0.01\n\tPr_Vampire = 0.001\n\tPr_Positive = Pr_Positive_Vampire * Pr_Vampire + Pr_Positive_Mortal * (1 - Pr_Vampire)\n\tPr_Vampire_Positive = Pr_Positive_Vampire * Pr_Vampire / Pr_Positive\n\tPr_Vampire_Positive\nend\n\n# ╔═╡ f25b24a2-f2e3-11ea-302d-f3e7f49f645b\nmd\"## End of clip-03-01t.jl\"\n\n# ╔═╡ Cell order:\n# ╟─c126b36a-f2e3-11ea-1b0f-a7d38ecffcd8\n# ╠═f252364e-f2e3-11ea-09b5-ff1a685abd56\n# ╠═f2526f60-f2e3-11ea-2d32-276d0b91d917\n# ╟─f252ea76-f2e3-11ea-093a-01c585ee2ea1\n# ╠═f25a9eec-f2e3-11ea-1611-9129817fe7a6\n# ╟─f25b24a2-f2e3-11ea-302d-f3e7f49f645b\n", "meta": {"hexsha": "2dd76dcc348dd842b6b190c6f816c43f4561c554", "size": 1006, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/clip-03-01t.jl", "max_stars_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_stars_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2020-10-01T23:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T11:48:45.000Z", "max_issues_repo_path": "notebooks/03/clip-03-01t.jl", "max_issues_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_issues_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-11-24T21:59:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T12:34:49.000Z", "max_forks_repo_path": "notebooks/03/clip-03-01t.jl", "max_forks_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_forks_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-11-30T18:25:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T06:59:27.000Z", "avg_line_length": 25.7948717949, "max_line_length": 87, "alphanum_fraction": 0.7534791252, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.8652240791017536, "lm_q1q2_score": 0.7926400928107653}}
{"text": "module GrahamScan\n\nexport FindConvexHull, EdgePoint, SortAngle\n\nusing LinearAlgebra\n\nfunction EdgePoint(A)\n    # find lexicographic minimum row of A with the second column having\n    # preceeding importance over the first one.\n    min_y = minimum(A[:,2]);\n    candidates = A[:,2] .== min_y;\n    min_x = minimum(A[candidates, 1]);\n    [min_x min_y]\nend\n\nfunction SortAngle(points)\n    function Cos(x,y)\n        c = acos(x/sqrt(x^2 + y^2));\n        if x > 0 && y > 0\n            c\n        elseif x < 0 && y > 0\n            c + π/2\n        elseif x > 0 && y < 0\n            -c\n        elseif x < 0 && y < 0\n            -c - π/2\n        else\n            c\n        end\n    end\n    f(p1,p2) = Cos(p1...) < Cos(p2...);\n    sortslices(points; dims=1, lt=f)\nend\n\nfunction ToDirection(p1, p2, p3)\n    T = [1 p1;\n         1 p2;\n         1 p3];\n    d = det(T);\n    if d < 0\n        :right\n    elseif d == 0\n        :inline\n    else\n        :left\n    end\nend\n\nfunction Scan(p1, ps)\n    (number_of_points, _) = size(ps);\n    if number_of_points < 2\n        [p1; ps]\n    else\n        p2 = ps[1,:]';\n        p3 = ps[2,:]';\n        ps = ps[3:end,:];\n        direction = ToDirection(p1, p2, p3);\n        if direction == :right\n            Scan(p1, [p3; ps]) # reject move, again with same tail and next head\n        elseif direction == :left\n            [p1; Scan(p2, [p3; ps])] # Save point, onward with next point\n        elseif direction == :inline\n            Scan(p1, [p3; ps]) # Discard mid point, onward with next point\n        end\n    end\nend\n\nfunction FindConvexHull(P)\n    # P is a (number of points) x (2) matrix\n    (number_of_points, _) = size(P);\n    if number_of_points == 0\n        return []\n    else\n        start = EdgePoint(P);\n        start_idx = (P[:, 1] .== start[1]) .& (P[:, 2] .== start[2]);\n        without_start = reshape(P[.~[start_idx start_idx]], :, 2);\n        # transform p into a coordinate system where o is\n        # the origin (relative to the previous system)\n        TranslateTo(o, p) = p - o;\n        TranslateCloud(o, cloud) = hcat(map(p -> TranslateTo(o, p), eachrow(cloud))...)';\n        sorted_points = TranslateCloud(start', without_start) |>\n            SortAngle |>\n            c -> TranslateCloud(-start', c)\n        if number_of_points <= 3\n            return [start; sorted_points]\n        else\n            return Scan(start, sorted_points)\n        end\n    end\nend\n\n#=\nTest 1\nA = [1 -1; 3 4; -1 2; -1 -1]\n\nGrahamScan(A) # should be A\n\nTest 2\nB = [2.3486669219560348 2.7215254125789414;\n    2.4139648037583257  -4.681676398649306;\n    -0.6260514711523584 6.850334341587001;\n    -7.64216704719866   -2.7605815091225576;\n    -5.026012253905725  1.5777744917255312;\n    -6.4853594504513445 5.318092139833023;\n    5.082500986696756   -1.896255262210346;\n    -6.497957092016469  -6.549163826826357;\n    7.051754797682392   -5.031079040862534;\n    3.283138295813238   -8.076020743414723;\n    7.805413024480348   9.26931407569144;\n    7.910312138709568   5.417744228015254;\n    2.4605192481055127  -1.4160149654176593;\n    -2.877588474503572  -3.4053645090358486;\n    0.5611514305387537  -9.743920605133937;\n    8.555954343029967   -4.394948528913232;\n    1.550287503925139   9.078244403761712;\n    -3.271086970349943  1.934092461779306;\n    -2.2965794125239603 1.2422580281368312;\n    3.182950465475866   7.148107783065644]\n\nC = [[0.5611514305387537,-9.743920605133937],[3.283138295813238,-8.076020743414723],[8.555954343029967,-4.394948528913232],[7.805413024480348,9.26931407569144],[3.182950465475866,7.148107783065644],[1.550287503925139,9.078244403761712],[-0.6260514711523584,6.850334341587001],[-6.4853594504513445,5.318092139833023],[-5.026012253905725,1.5777744917255312],[-7.64216704719866,-2.7605815091225576],[-6.497957092016469,-6.549163826826357]]\nc = GrahamScan(B)\nhcat(C...)' - c # should be 0\n=#\n    \nend", "meta": {"hexsha": "9aa8de0b6a09b033b04bf41b805742adf367a47f", "size": 3845, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "arej/GrahamScan.jl", "max_stars_repo_name": "SV-97/ares", "max_stars_repo_head_hexsha": "f702e109e357d86773c44923acc8d8d10cc55356", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "arej/GrahamScan.jl", "max_issues_repo_name": "SV-97/ares", "max_issues_repo_head_hexsha": "f702e109e357d86773c44923acc8d8d10cc55356", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arej/GrahamScan.jl", "max_forks_repo_name": "SV-97/ares", "max_forks_repo_head_hexsha": "f702e109e357d86773c44923acc8d8d10cc55356", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.76, "max_line_length": 436, "alphanum_fraction": 0.6080624187, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.8723473879530491, "lm_q1q2_score": 0.7926304533540435}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.6\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 10c7a648-1488-11eb-0f9c-c3bfe711a449\nmd\" ### Nomenclatura\"\n\n# ╔═╡ 10170496-1488-11eb-0882-df72e258d63c\nmd\"Seja $X$ uma matriz com dimensões $n x m$ com $n$ linhas e $m$ colunas que contém nossos exemplos. $X_i^{(j)}$ corresponde ao elemento de $X$ em que $i$ é uma linha da matriz (exemplo) e $j$ uma coluna da matriz (atributo), cujo acesso na linguagem representamos por x[i,j]. Para pegarmos um vetor linha desta matriz (exemplo) representamos formalmente por $X_i$ e na linguagem por x[i,:].\"\n\n# ╔═╡ 3996c40e-1489-11eb-266a-95abbb9cd199\nmd\"Seja $\\theta$ um vetor linha com $m$ elementos tal que $m$ corresponde ao número de atributos mais um. $\\theta = [\\theta^{(0)},\\theta^{(1)}, ...,\\theta^{(m)}]$ em que cada elemento corresponde ao j-ésimo parâmetro associado ao j-ésimo atributo. Na nossa lingugaem acessamos um elemento por $\\theta[i]$ e o vetor por $\\theta$\"\n\n# ╔═╡ 391d5e2a-1489-11eb-15d4-77bf4828cfcd\nmd\"Seja $y$ nosso vetor alvo em que representamos o i-ésimo elemento por $y_i$. Na nossa linguagem representamos por $y[i]$.\"\n\n# ╔═╡ 794e1306-1487-11eb-203c-37766708b1a2\nmd\" ### Hipótese e modelo linear\"\n\n# ╔═╡ 7882a5fe-1487-11eb-3f45-fd54863cdfbd\nmd\"$H_{\\theta}(X_i) = \\sum_{j}^{m}{x_{i}^{(j)} \\theta^{(j)}} = X_i\\theta^{T}$\"\n\n# ╔═╡ 272f710e-1f99-11eb-21f0-d98d7f2445c8\nmd\"Exemplificando o produto de vetores, nossa hipótese faria o seguinte cálculo para um exemplo $X_i = \\begin{bmatrix} 1 & 500 \\end{bmatrix}$ e um vetor de parâmetros $\\theta = \\begin{bmatrix}\n    0.5 \\\\\n    1.0\n\\end{bmatrix}$:\"\n\n# ╔═╡ 2821e75e-1f99-11eb-2f10-831050151433\nmd\"e.g. $H_{\\theta}(X_i) = \\begin{bmatrix}\n    1 & 500 \n  \\end{bmatrix}\\begin{bmatrix}\n    0.5 \\\\\n    1.0\n\\end{bmatrix} = 500.5$\"\n\n# ╔═╡ 295c3c20-1f99-11eb-20df-1b793c23e91f\nmd\"Note que o resultado é um escalar, pois estamos estimando um valor contínuo (problema de regressão).\"\n\n# ╔═╡ f6213c24-1486-11eb-0981-ad6addc2a8ef\nmd\" ### Função de custo\"\n\n# ╔═╡ d8c3e0d8-1485-11eb-3eab-a11e3d31269f\n\nmd\"$J(\\theta)= \\frac{1}{2n}\\sum_{i=1}^{n}{(H_{\\theta}(X_i) - y_i)²} = \\frac{1}{2n}\\sum_{i=1}^{n}{(X_i\\theta^T - y_i)²} = J_2$\"\n\n\n# ╔═╡ be81b7b2-148b-11eb-222c-135499b083cf\nmd\"que pode ser expandido ainda mais na forma: \"\n\n# ╔═╡ d16ba126-148b-11eb-388b-ed88f5dc2099\nmd\"$= \\frac{1}{2n}\\sum_{i=1}^{n}{(\\sum_{j=1}^{m}X_{i}^{(j)}\\theta_{j} - y_i)²} = J_1$\"\n\n# ╔═╡ 1980e48e-148d-11eb-282a-155aa6620659\nmd\"Podemos ainda calcular toda a função de custo apenas por operações de matrizes e vetores sem um laço de repetição explícito da seguinte forma:\"\n\n# ╔═╡ b3ed93fc-1406-11eb-34d4-31acb0c7d641\nbegin \n   import Statistics: mean\n   import BenchmarkTools: @benchmark, @btime\n   import StaticArrays: @SMatrix\t\n   μ = mean\t\nend\n\n# ╔═╡ 35a275a0-1402-11eb-3ce4-fba2f21b24d6\nfunction J₁(Θ,χ,γ)\n     n,m = size(χ)\n\t ∑ = 0.0\n\t for i=1:n\n\t\th = 0.0\n\t\tfor j=1:m \n\t\t   h += Θ[j] * χ[i,j]\n\t\tend\n\t\t∑ += (h - γ[i])^2\n\t end\n\t .5∑/n\nend \n\n# ╔═╡ 1c4d435e-140d-11eb-1585-476688f1ec0c\nfunction J₂(Θ,χ,γ)\n     n,m = size(χ)\n\t ∑ = 0.0\n\t for (x,y) in zip(eachrow(χ),γ)\n\t\t∑ += (Θ*x .- y).^2 ...\n\t end\n\t .5∑/n\nend \n\n# ╔═╡ 329221e4-1498-11eb-0569-d9bde9e62e1a\nmd\" É possível ainda vetorizar todo o cálculo sem precisar fazer um loop explícito. Desta maneira, geramos em uma multiplicação de matrizes, um vetor de predições com a mesma dimensão da saída. Após isto, subtraímos elemento a elemento. Após isto, elevamos cada elemento ao quadrado e depois tiramos uma média.\"\n\n# ╔═╡ 19392bd6-1405-11eb-3022-bbaecf23c544\nJ₃(Θ,χ,γ) = .5μ((χ*Θ' .- γ).^2) \n\n# ╔═╡ 7b5e9f88-1498-11eb-2acf-a139d4c8e8fb\nmd\" Abaixo temos um exemplo de teste da função de custo.\"\n\n# ╔═╡ 48f06c34-1405-11eb-067e-cbe31a8e3cf3\nbegin\n\tΘ =  @SMatrix [0. 4.] \n\tχ =  @SMatrix [1 50.;1 60.;1 100.; 1 200.]\n\tγ =  @SMatrix [200  ;   240  ;   400; 800]\n\tJ₁(Θ,χ,γ),J₂(Θ,χ,γ),J₃(Θ,χ,γ)\nend\t\n\n# ╔═╡ 1c69de24-1499-11eb-1151-bbc0bf07a89c\nmd\"### Medindo o tempo computacional\"\n\n# ╔═╡ 93db1528-1498-11eb-035d-efef99b051ed\nmd\"Podemos medir o tempo de cada função a partir de um benchmark. É importante ressaltar que diversas otimizações podem ser testadas para melhorar o tempo. Uma forma seria trabalhar com a matriz $X$ transposta e $\\theta$ como vetor coluna. Isto porque Julia representa uma matriz em ordem de coluna (como Matlab, R, Fortran, ...) devido à compatibilidade com libs de fortran dierentemente de outras linguagens como C, C++, ... Há ainda otimizações com vetores estáticos, macros como @inbounds, ... tudo isto pode acelerar ainda mais seu código.\"\n\n# ╔═╡ cdfe994c-1415-11eb-01c0-13fd220aaa92\n@benchmark J₁(Θ,χ,γ) seconds=1 gctrial=true\n#@benchmark J₂(Θ,χ,γ) seconds=1 gctrial=true\n#@benchmark J₃(Θ,χ,γ) seconds=1 gctrial=true\n\n# ╔═╡ 7ee07dd4-149d-11eb-1f6d-2d565ee61a12\nmd\" ### E se fosse você escolhesse os valores de $\\theta$ ?\"\n\n# ╔═╡ 7fff1162-149d-11eb-2ec6-c3ad197a6d4c\n\n\n# ╔═╡ 6aa7e186-14a2-11eb-287d-35f60c88cc0b\n@bind θ₀ html\"<input type='range' step='0.1' min='-10' max='10'>\"\n\n# ╔═╡ d357e744-14a2-11eb-2652-c35400acb3cf\n@bind θ₁ html\"<input type='range' step='0.1' min='-10' max='10'>\"\n\n# ╔═╡ 150cec5a-14aa-11eb-2be7-390b12287032\nbegin\n\tusing Plots; \n\tx = range(1,stop=300,length=300)\n\tn = length(x)\n\ty = zeros(n)\n\tfor i=1:n \n\t\ty[i] = θ₀ + θ₁*x[i]\n\t\t#y[i] = θ₀ + θ₁^2*x[i]\n\t\t#y[i] = θ₀ + θ₁*x[i]^2\n\t\t\n\tend\n\tplot(x,y,xlims = (0,300),ylims = (100,900),xlabel=\"Metros\",ylabel=\"Preço\",label=\"estimado\");\n\tscatter!(χ[:,2],γ[:],xlims = (0,300),ylims = (100,900),label=\"exemplo\");\nend\n\n# ╔═╡ 8ef513d8-14a2-11eb-3f6e-5b2f0a09363e\nθ = [θ₀ θ₁]\n\n# ╔═╡ 7c888c54-14a5-11eb-315f-3d32578eaf32\nmd\"##### Erro : $(J₁([θ₀ θ₁],χ,γ))\"\n\n# ╔═╡ bfd7693a-14a5-11eb-3479-057e03ef43f4\nmd\" ### Gráfico do modelo linear\"\n\n# ╔═╡ f17bfc22-14b3-11eb-319a-47522cda243c\nmd\"### Curva de erro\"\n\n# ╔═╡ 3ac52d04-14b4-11eb-17cf-1b2f8531335d\nbegin\n\te = []\n\tfor i=-1:1:10\n\t    for j=1:1:10\n\t\t    append!(e,J₁([i j],χ,γ))\n\t\tend\n\tend\n\tprintln(\"e = \",e)\n\tscatter(1:1:10,e,xlabel=\"θ₁\",ylabel=\"J\",label=\"erro\") # apenas com relação à θ₁. para fazer com θ₀ teríamos outro eixo e teríamos uma superfície. \n\nend\n\n# ╔═╡ Cell order:\n# ╠═10c7a648-1488-11eb-0f9c-c3bfe711a449\n# ╠═10170496-1488-11eb-0882-df72e258d63c\n# ╠═3996c40e-1489-11eb-266a-95abbb9cd199\n# ╠═391d5e2a-1489-11eb-15d4-77bf4828cfcd\n# ╟─794e1306-1487-11eb-203c-37766708b1a2\n# ╠═7882a5fe-1487-11eb-3f45-fd54863cdfbd\n# ╟─272f710e-1f99-11eb-21f0-d98d7f2445c8\n# ╟─2821e75e-1f99-11eb-2f10-831050151433\n# ╟─295c3c20-1f99-11eb-20df-1b793c23e91f\n# ╟─f6213c24-1486-11eb-0981-ad6addc2a8ef\n# ╟─d8c3e0d8-1485-11eb-3eab-a11e3d31269f\n# ╟─be81b7b2-148b-11eb-222c-135499b083cf\n# ╟─d16ba126-148b-11eb-388b-ed88f5dc2099\n# ╟─1980e48e-148d-11eb-282a-155aa6620659\n# ╠═b3ed93fc-1406-11eb-34d4-31acb0c7d641\n# ╠═35a275a0-1402-11eb-3ce4-fba2f21b24d6\n# ╠═1c4d435e-140d-11eb-1585-476688f1ec0c\n# ╠═329221e4-1498-11eb-0569-d9bde9e62e1a\n# ╠═19392bd6-1405-11eb-3022-bbaecf23c544\n# ╟─7b5e9f88-1498-11eb-2acf-a139d4c8e8fb\n# ╠═48f06c34-1405-11eb-067e-cbe31a8e3cf3\n# ╟─1c69de24-1499-11eb-1151-bbc0bf07a89c\n# ╟─93db1528-1498-11eb-035d-efef99b051ed\n# ╠═cdfe994c-1415-11eb-01c0-13fd220aaa92\n# ╠═7ee07dd4-149d-11eb-1f6d-2d565ee61a12\n# ╟─7fff1162-149d-11eb-2ec6-c3ad197a6d4c\n# ╠═6aa7e186-14a2-11eb-287d-35f60c88cc0b\n# ╟─d357e744-14a2-11eb-2652-c35400acb3cf\n# ╠═8ef513d8-14a2-11eb-3f6e-5b2f0a09363e\n# ╠═7c888c54-14a5-11eb-315f-3d32578eaf32\n# ╠═bfd7693a-14a5-11eb-3479-057e03ef43f4\n# ╠═150cec5a-14aa-11eb-2be7-390b12287032\n# ╠═f17bfc22-14b3-11eb-319a-47522cda243c\n# ╠═3ac52d04-14b4-11eb-17cf-1b2f8531335d\n", "meta": {"hexsha": "190e700335eec376e01823c7b38261efc2e4cc41", "size": 7834, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "cost_function.jl", "max_stars_repo_name": "lalvim/machinelearning", "max_stars_repo_head_hexsha": "495afd09a639baca85763ceb82c39595733b86c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cost_function.jl", "max_issues_repo_name": "lalvim/machinelearning", "max_issues_repo_head_hexsha": "495afd09a639baca85763ceb82c39595733b86c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cost_function.jl", "max_forks_repo_name": "lalvim/machinelearning", "max_forks_repo_head_hexsha": "495afd09a639baca85763ceb82c39595733b86c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2685185185, "max_line_length": 545, "alphanum_fraction": 0.6947919326, "num_tokens": 3794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.903294216466424, "lm_q1q2_score": 0.7926197158985802}}
{"text": "\"\"\"\n```\n    sample_points_on_ellipse(A::Real, B::Real, H::Real, K::Real, τ::Real, N::Integer, α₁::Real, α₂::Real)\n```\n    Samples N data points in the angle range [α₁, α₂] for an ellipse specified by  semi-major (A) semi-minor (B) axes,\n    centroid (H,K) and orientation (τ). All angles are assumed to be specified in radians. The results are returned\n    as `[Observations](@ref)`. \n\"\"\"\nfunction sample_points_on_ellipse(A::Real, B::Real, H::Real, K::Real, τ::Real, N::Integer, α₁::Real, α₂::Real)\n    ℳ = [SVector(0.0,0.0) for n = 1:N]\n    for (n,α) in enumerate(range(α₁, stop = α₂, length = N))\n        x = H + A*cos(α)*cos(τ) - B*sin(α)*sin(τ)\n        y = K + A*cos(α)*sin(τ) + B*sin(α)*cos(τ)\n        𝐦 = SVector(x,y)\n        ℳ[n] = 𝐦\n    end\n    data = tuple(ℳ)\n    return Observations(data)\nend", "meta": {"hexsha": "0a29cd7e45475ce52e5d5fdf2c6f9b6bd894b364", "size": 803, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sampling.jl", "max_stars_repo_name": "mkretlow/GuaranteedEllipseFitting.jl", "max_stars_repo_head_hexsha": "4533c291d1cb49c9e7d7054f3ec6e67d23436e57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sampling.jl", "max_issues_repo_name": "mkretlow/GuaranteedEllipseFitting.jl", "max_issues_repo_head_hexsha": "4533c291d1cb49c9e7d7054f3ec6e67d23436e57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-27T05:59:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-27T05:59:59.000Z", "max_forks_repo_path": "src/sampling.jl", "max_forks_repo_name": "mkretlow/GuaranteedEllipseFitting.jl", "max_forks_repo_head_hexsha": "4533c291d1cb49c9e7d7054f3ec6e67d23436e57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-27T20:13:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T23:55:25.000Z", "avg_line_length": 42.2631578947, "max_line_length": 118, "alphanum_fraction": 0.596513076, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928905, "lm_q2_score": 0.8333245953120234, "lm_q1q2_score": 0.792610205559755}}
{"text": "# taken from: http://www.sunshine2k.de/coding/java/TriangleRasterization/TriangleRasterization.html#algo2\n\nfunction _draw_hline!(img, xi::Int64, xf::Int64, y::Int64, color)\n    y < 1 && return\n    y > size(img)[1] && return\n    if xi>xf\n        xi,xf = xf,xi\n    end\n    for x in max(xi,1):min(size(img)[2],xf)\n        img[y,x,:] .= color\n    end\nend\n\nfunction _fill_bottom_flat_triangle!(img, v1x::Int64,v1y::Int64, v2x::Int64,v2y::Int64, v3x::Int64,v3y::Int64, color)\n    invslope1::Float64 = (v2x - v1x) / (v2y - v1y);    \n    invslope2::Float64 = (v3x - v1x) / (v3y - v1y);\n    curx1::Float64 = v1x;\n    curx2::Float64 = v1x;\n    scanlineY::Int64 = v1y;\n    while scanlineY <= v2y\n        _draw_hline!(img, floor(Int64, curx1), floor(Int64, curx2), scanlineY, color);\n        curx1 += invslope1;\n        curx2 += invslope2;\n        scanlineY += 1\n    end\nend\n\nfunction _fill_top_flat_triangle!(img, v1x::Int64,v1y::Int64, v2x::Int64,v2y::Int64, v3x::Int64,v3y::Int64, color)\n    invslope1::Float64 = (v3x - v1x) / (v3y - v1y);\n    invslope2::Float64 = (v3x - v2x) / (v3y - v2y);\n    curx1::Float64 = v3x;\n    curx2::Float64 = v3x;\n    scanlineY::Int64 = v3y;\n    while scanlineY > v1y\n        _draw_hline!(img, floor(Int64, curx1), floor(Int64, curx2), scanlineY, color);\n        curx1 -= invslope1;\n        curx2 -= invslope2;\n        scanlineY -= 1\n    end\nend\n\nfunction draw_triangle!(img, v1x::Int64,v1y::Int64, v2x::Int64,v2y::Int64, v3x::Int64,v3y::Int64, color)\n    # at first sort the three vertices by y-coordinate ascending so v1 is the topmost vertice\n    if v1y > v2y\n        v1x,v2x = v2x,v1x\n        v1y,v2y = v2y,v1y\n    end\n    if v2y > v3y\n        v2x,v3x = v3x,v2x\n        v2y,v3y = v3y,v2y\n    end\n    if v1y > v2y\n        v1x,v2x = v2x,v1x\n        v1y,v2y = v2y,v1y\n    end\n    v1y > size(img)[1] && return\n    v3y < 1 && return\n    max(v1x,v2x,v3x) < 1 && return\n    min(v1x,v2x,v3x) > size(img)[2] && return\n\n    # here we know that v1.y <= v2.y <= v3.y\n    # check for trivial case of bottom-flat triangle\n    if v2y == v3y\n        _fill_bottom_flat_triangle!(img, v1x,v1y, v2x,v2y, v3x,v3y, color);\n    elseif v1y == v2y\n        # check for trivial case of top-flat triangle\n        _fill_top_flat_triangle!(img, v1x,v1y, v2x,v2y, v3x,v3y, color);\n    else\n        # general case - split the triangle in a topflat and bottom-flat one\n        v4x::Int64 = floor(Int64, (v1x + ((v2y - v1y) / (v3y - v1y)) * (v3x - v1x)))\n        v4y::Int64 = v2y\n        _fill_bottom_flat_triangle!(img, v1x,v1y, v2x,v2y, v4x,v4y, color);\n        _fill_top_flat_triangle!(img, v2x,v2y, v4x,v4y, v3x,v3y, color);\n    end\nend\n\n# line from: https://github.com/JuliaImages/ImageDraw.jl/blob/master/src/line2d.jl\nfunction line!(img, x0::Int, y0::Int, x1::Int, y1::Int, color)\n    dx = abs(x1 - x0)\n    dy = abs(y1 - y0)\n\n    sx = x0 < x1 ? 1 : -1\n    sy = y0 < y1 ? 1 : -1;\n\n    err = (dx > dy ? dx : -dy) / 2\n\n    while true\n        if y0 >= 1 && y0 <= size(img)[1] && x0 >= 1 && x0 <= size(img)[2]\n            img[y0, x0] = color\n        end\n        (x0 != x1 || y0 != y1) || break\n        e2 = err\n        if e2 > -dx\n            err -= dy\n            x0 += sx\n        end\n        if e2 < dy\n            err += dx\n            y0 += sy\n        end\n    end\n\n    img\nend\n", "meta": {"hexsha": "d774b4b015976707f6311d044135f7fb2d8433a5", "size": 3275, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "env/draw.jl", "max_stars_repo_name": "digital-idiot/aleph_star", "max_stars_repo_head_hexsha": "bce55397fed5ca691bf27c1278660bbb0152148a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 245, "max_stars_repo_stars_event_min_datetime": "2018-10-07T17:38:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:33:15.000Z", "max_issues_repo_path": "env/draw.jl", "max_issues_repo_name": "digital-idiot/aleph_star", "max_issues_repo_head_hexsha": "bce55397fed5ca691bf27c1278660bbb0152148a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-11-04T22:54:37.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-27T15:05:41.000Z", "max_forks_repo_path": "env/draw.jl", "max_forks_repo_name": "digital-idiot/aleph_star", "max_forks_repo_head_hexsha": "bce55397fed5ca691bf27c1278660bbb0152148a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 32, "max_forks_repo_forks_event_min_datetime": "2018-10-22T10:16:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:32:17.000Z", "avg_line_length": 31.1904761905, "max_line_length": 117, "alphanum_fraction": 0.5688549618, "num_tokens": 1317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928905, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.792610203591183}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Statistics, DataFrames, CSV\n\tusing Random, Distributions, Plots\n\tusing HypothesisTests\n\tRandom.seed!(0)\nend;\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.03\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tdata = CSV.read(datadir(\"machine1.csv\"), DataFrame; delim=\",\")[:, 1]\nend;\n\n# ╔═╡ 1aa41898-3afa-11eb-2f49-570853ce6435\nbegin\n\txBar, n = mean(data), length(data)\n\tsig = 1.2\n\talpha = 0.1\n\tz = quantile(Normal(),1-alpha/2)\n\n\tText(\"Calculating formula: $((xBar - z*sig/sqrt(n), xBar + z*sig/sqrt(n)))\")\nend\n\n# ╔═╡ c69d5eae-3b0c-11eb-38aa-b578cce81150\nText(\"Using confint() function: $(confint(OneSampleZTest(xBar,sig,n),alpha))\")\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.03\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═1aa41898-3afa-11eb-2f49-570853ce6435\n# ╠═c69d5eae-3b0c-11eb-38aa-b578cce81150\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "a81553c1417e075b23a5893a8bd484110b9b1ecf", "size": 1274, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/06/listing6.03.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/06/listing6.03.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/06/listing6.03.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 24.9803921569, "max_line_length": 78, "alphanum_fraction": 0.7244897959, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.8918110468756548, "lm_q1q2_score": 0.7926049100444519}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.2\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local iv = try Base.loaded_modules[Base.PkgId(Base.UUID(\"6e696c72-6542-2067-7265-42206c756150\"), \"AbstractPlutoDingetjes\")].Bonds.initial_value catch; b -> missing; end\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)\n        el\n    end\nend\n\n# ╔═╡ 73555af0-8353-11eb-215d-d3578a6f1e2e\nbegin\n\t#try\n\t\tusing PlutoUI\n\t\tusing Plots, Plots.PlotMeasures\n\t\t#using LinearAlgebra\n\t\t#using SparseArrays\n\t\tusing SpecialFunctions\n\t\t#using StatsBase\n\t\t#using Random\n\t\tusing Distributions\n\t\tusing LaTeXStrings\t\n\t\tusing Markdown\n\t\t\n\t\tmd\"\"\" \n\t\t# Packages\n\t\t\n\t\tAll needed Packages available :) \"\"\"\n\t#=catch\n\t\timport Pkg\n\t\tPkg.activate(mktempdir())\n\t\tPkg.add(\"PlutoUI\")\n\t\tPkg.add(\"Plots\")\n\t\t#Pkg.add(\"LinearAlgebra\")\n\t\t#Pkg.add(\"SparseArrays\")\n\t\tPkg.add(\"SpecialFunctions\")\n\t\t#Pkg.add(\"StatsBase\")\n\t\tPkg.add([\"Distributions\", \"LaTeXStrings\", \"Markdown\"])\n\t\t\n\t\tusing PlutoUI\n\t\tusing Plots, Plots.PlotMeasures\n\t\t#using LinearAlgebra\n\t\t#using SparseArrays\n\t\tusing SpecialFunctions\n\t\t#using StatsBase\n\t\t#using Random\n\t\tusing Distributions\n\t\tusing LaTeXStrings\n\t\tmd\"\"\" \n\t\t# Packages\n\t\t\n\t\tSome Package sources not added, this will take approx. 3 minutes\"\"\"\n\tend\n\t=#\nend\n\n# ╔═╡ d141cf00-8352-11eb-2e51-f115e26e1570\nbegin\n\tmd\"\"\"\n# Popular discrete probability distributions 🥳\nHere you can explore some of the most famous discrete probability distributions\n\"\"\"\nend\n\n# ╔═╡ e6d68ef0-8352-11eb-1999-0384c7ff8526\nmd\"\"\"\n## Poisson distribution\n\nThe Poisson distribution is given by\n> $P_{\\cal P}(K|\\lambda) =\\textrm{e}^{-\\lambda} \\frac{\\lambda^K}{K!}$\n\nwith $K$ the number of observed counts per interval given that $\\lambda$ discribes the fixed average of counts per interval.\n\"\"\"\n\n\n# ╔═╡ 6196a940-8353-11eb-1a09-29cb2338d697\nmd\"\"\"\nVary the parameter of 👉 $\\lambda$: $(@bind lambda Slider(0:1:18, default=1, show_value = true))\n\"\"\"\n\n# ╔═╡ a88ae050-8353-11eb-3eee-b7ee9b717fdb\nbegin\t\n\t\n\tk =0:1:17\n\tpoisson = lambda.^k./gamma.(k.+1).*exp(-lambda)\n\tcol_pal = palette(:default) # color palette\n\t\n\tplot(\n    k, poisson,\n    line = (0.0 , 2.0 , :bar),\n    normalize = false,\n\tbar_width = 0.2,\n    marker = (6, 0.5, :none),\n    markerstrokewidth = 5.,\n    color = col_pal[1],\n    fill = 0.9,\n    orientation = :v,\n    title = \"The Poisson distribution with lambda: \"*string(lambda),\n\tylabel = \"probability mass function\",\n\txlabel = \"Points\",\n\tlabel = :none,\n\tylim =[0,1],)\n\t\n\tplot!(\n    k, poisson,\n    line = ( 1, 0., :path),\n    normalize = false,\n    marker = (5, 1., :o),\n    markerstrokewidth = 1.,\n    color = col_pal[1],\n    fill = 0.,\n    orientation = :v,\n    title = \"The Poisson distribution with lambda: \"*string(lambda),\n\tylabel = latexstring(\"P_{\\\\mathcal{P}}(K\\\\,|\\\\, \\\\lambda)\"),\n\txlabel = \"K - number of counting events\",\n\tlabel = :none,\n\tylim =[0,1],\t\n\t#xtick = [0,10],\n\t#ytick = [0,1/10],\n\t#xticklabel = latexstring(\"x_{\\\\textrm{max}}\"),\n\t#ylim = [0,50],\n\tlegend= :right,\n\t#xlim = [0,60],\n\t# series properties\n\t# size of image, margins, font size, ...\n\tsize = (600,400),  \n\tlabelfontsize = 20,\n\tlegendfontsize = 15,\n\ttickfontsize = 15,\n\tbottom_margin =25mm,\n\tleft_margin = 5mm,\n\tright_margin = 10mm,\n\ttitlefontsize = 15,\t\n\tbackground_color = :transparent,  \n\t# this is really cool, transparent background :)\n\tforeground_color = :black,\n\t# makes it look like LaTeX\n\tfontfamily=\"Computer Modern\"\n)\nend\n\n# ╔═╡ 47882682-844f-11eb-335e-afc41d5498e1\nmd\"\"\"\n_What could be the reason for the **strange behavior** for $\\lambda \\geq 14$ for large values of K?_ \n\n👉 The function becomes discontinuous for values larger 14  $(@bind is_discontinuous CheckBox())\n\n👉 There is no problem, the function should look like that  $(@bind is_no_problem CheckBox())\n\n👉 There are numerical issues  $(@bind is_num CheckBox())\n\n\"\"\"\n\n# ╔═╡ 7799e4c0-844b-11eb-2484-051807211341\nmd\"\"\"\n## Binomial distribution  \n\n> $P_{\\cal B}(K|N,Q)  = {N\\choose K}  Q^K (1-Q)^{N-K}$\n\n_When can a Binomial be approximated by a Gaussian or a Poissonian?_  🤔\n\n\n\"\"\"\n\n# ╔═╡ 9acafce0-844b-11eb-331c-0186de214a59\nmd\"\"\"\nVary the parameters of the **the total number of experiments** 👉 N: $(@bind N_binom Scrubbable(0:1:20)) and of the **success probability** 👉 Q: $(@bind Q_binom Scrubbable(0:0.05:1)) \n\nCompare with **Gauss distribution** 👉 $(@bind check_gauss CheckBox())\nand with **Poisson distribution** 👉 $(@bind check_poisson CheckBox())\n\n_For which parameters do they match?_ 🤔\n\"\"\"\n\n# ╔═╡ 3a1c82a0-844c-11eb-05a6-75924317db64\nbegin\n\tL_m = [0:1:N_binom;]\n\tP_m = pdf.(Binomial(N_binom,Q_binom),L_m)\n\n\tplot(L_m,P_m,\n\tline = (.0 , 3.0 , :bar),\n\tylim = (0,1),\n\tlabel = :none,\n    normalize = false,\n\tbar_width = 0.2*N_binom/18,\n    marker = (8, 1.5, :none),\n    markerstrokewidth = 1,\n    #color = [:steelblue],\n    fill = 0.9,\n\t)\n\t\n\t\n\t\n\tif check_gauss\n\t\tavg = N_binom*Q_binom\n\tvar = N_binom*Q_binom*(1-Q_binom)\n\n\tP_g2 = [exp(-(m - avg)^2 /(2*var)) for m in L_m]\n\n\tP_g2 = P_g2 / sum(P_g2)\n\tplot!(L_m,P_g2,\n\t\tline = (1.,0.,:path),\n\t\tmarker = (6, :square),\n\t\topacity = 0.4,\n\t\tcolor = :red,\n\t\tlabel = \"Gauss with same mean and variance\"\n\t)\n\tend\n\t\n\n\t\n\tif check_poisson\n\t\tavg = N_binom*Q_binom\n\t\tPoisson_m = pdf.(Poisson(avg),L_m)\n\t\tplot!(L_m,Poisson_m,\n\t\tline = (1.,0.,:path),\n\t\t\n\t\tmarker = (10., :s,:blue),\n\t\topacity = 0.4,\n\t\tcolor = :red,\n\t\tlabel = \"Poisson with same mean\"\n\t)\n\tend\n\tplot!(\n    L_m,P_m,\n    line = ( 1., 0., :path),\n    normalize = false,\n    marker = (5, 1., :o),\n    markerstrokewidth = 1.,\n\tlabel = \"Binomial\",\n\tcolor = col_pal[1],\n\txlabel = latexstring(\"K\"), \n\tylabel = latexstring(\"P_{\\\\mathcal{B}}(K\\\\,|\\\\, N,Q)\"),\n\t#xtick = [0,10],\n\t#ytick = [0,1/10],\n\t#xticklabel = latexstring(\"x_{\\\\textrm{max}}\"),\n\t#ylim = [0,50],\n\tlegend= :right,\n\ttitle = \"Binomial distribution\",\n\t#xlim = [0,60],\n\t# series properties\n\t# size of image, margins, font size, ...\n\tsize = (600,400),  \n\tlabelfontsize = 20,\n\tlegendfontsize = 15,\n\ttickfontsize = 15,\n\tbottom_margin =25mm,\n\tleft_margin = 5mm,\n\tright_margin = 10mm,\n\ttitlefontsize = 20,\t\n\tbackground_color = :transparent,  \n\t# this is really cool, transparent background :)\n\tforeground_color = :black,\n\t# makes it look like LaTeX\n\tfontfamily=\"Computer Modern\"\n)\n\nend\n\n# ╔═╡ 73b7eb70-8452-11eb-0f2e-df6b5cd0da4a\nmd\"\"\"\n## Geometric distribution  \n\n> $P_{\\cal G}(K|Q_a)  = Q_a (1-Q_a)^{K-1}$\n\n_What's the connection to the Binomial distribution?_  🤔\n\n\n\"\"\"\n\n# ╔═╡ 08562f30-8453-11eb-36bd-7b55fcd4b82e\nbegin \nmd\"\"\"\nVary the **success probability** 👉 $Q_a$:  $(@bind q_a_aux Scrubbable(0.3:0.05:0.99,default = sqrt(1/6))) \n\"\"\"\nend\n\n# ╔═╡ b10c08c0-8453-11eb-1614-ef634e6929e5\nbegin\n\tQ_a = q_a_aux^2\n\tavg_k = 1/Q_a\n\tmd\"\"\"\n\tFor $Q_a$ = $(round(Q_a,digits=3)) the mean waiting time is $(round(avg_k,digits=3))\n\t\"\"\"\nend\n\n# ╔═╡ 65567910-8453-11eb-1de3-d38bd5010350\nbegin\n    k_max = ceil(10/Q_a)\n\tL_k = [0:1:k_max;]\n\tP_k = Q_a.*(1-Q_a).^L_k\n\t\n\tplot(L_k,P_k,\n\tline = (0.0 , 2.0 , :bar),\n    normalize = false,\n\tbar_width = 0.3,\n    marker = (6, 0.5, :none),\n    markerstrokewidth = 5.,\n    color = col_pal[1],\n\txlim = (0,40),\n\tylim = (0,.3),\n\tlabel = :none)\n\t\n\tplot!(L_k,P_k,\n\t\tline = ( 1, 0., :path),\n    normalize = false,\n    marker = (5, 1., :o),\n    markerstrokewidth = 1.,\n    color = col_pal[1],\n\tlabel = \"Geometric\",\n\txlabel = latexstring(\"K\"), \n\tylabel = latexstring(\"P_{\\\\mathcal{G}}(K\\\\,|\\\\, Q_a)\"),\n\t\ttitle = \"Geometric distribution\",\n\t#xtick = [0,10],\n\t#ytick = [0,1/10],\n\t#xticklabel = latexstring(\"x_{\\\\textrm{max}}\"),\n\t#ylim = [0,50],\n\tlegend= :right,\n\t#xlim = [0,60],\n\t# series properties\n\t# size of image, margins, font size, ...\n\tsize = (600,400),  \n\tlabelfontsize = 20,\n\tlegendfontsize = 15,\n\ttickfontsize = 15,\n\tbottom_margin =25mm,\n\tleft_margin = 5mm,\n\tright_margin = 10mm,\n\ttitlefontsize = 20,\t\n\tbackground_color = :transparent,  \n\t# this is really cool, transparent background :)\n\tforeground_color = :black,\n\t# makes it look like LaTeX\n\tfontfamily=\"Computer Modern\"\n)\n\t\t\n#=\t\n\tavg = N*q\n\tvar = N*q*(1-q)\n\n\tP_g2 = [exp(-(m - avg)^2 /(2*var)) for m in L_m]\n\n\tP_g2 = P_g2 / sum(P_g2)\n\n\tplot!(L_m,P_g2,\n\t\tline = false,\n\t\tmarker = :dot,\n\t\tcolor = :red,\n\t\tlabel = \"Gauss with same mean and variance\"\n\t)\n=#\nend\n\n# ╔═╡ 1cc62475-2dd3-488b-9647-9d5b2986d791\nmd\"\"\"\n# Popular continuous probability distributions 🐱‍👤\n\"\"\"\n\n# ╔═╡ 48811336-16f6-496f-848d-54fd834bb0da\nmd\"\"\"\n## Gamma distribution\n\n> $p_{\\Gamma}(x\\,|\\,\\alpha, \\beta)  = \\frac{\\beta^\\alpha}{\\Gamma(\\alpha)} x^{\\alpha-1} e^{-\\beta x}, \\quad x \\in [0,\\infty)$\n> $\\Gamma(\\alpha):= \\int_0^\\infty t^{\\alpha-1} e^{-t} dt$\n\n\n_What's the connection to the Poisson distribution?_  🤔\n\n\"\"\"\n\n# ╔═╡ fb470501-cea4-4ac9-a652-d9874dbd7bdc\nmd\"\"\"\nChoose **parameters** $\\alpha$ 👉 $(@bind α Scrubbable(0:0.1:5, default = 2)) and \n\n $\\beta$ 👉 $(@bind β Scrubbable(0:0.1:5, default = 2))\n\"\"\"\n\n# ╔═╡ 3d85408a-b356-4107-b604-b39fb5a6982e\nmd\"\"\"\n## Beta distribution\n\n> $p_{\\beta}(x\\,|\\,\\alpha, \\rho)  = \\frac{1}{B(\\alpha,\\rho)} x^{\\alpha-1} (1-x)^{\\rho-1}, \\quad x \\in [0,1]$\n> $B(\\alpha, \\rho):= \\int_0^1 p^{\\alpha-1} (1-p)^{\\rho-1}dp$\n\n\n_What's the conjugated Likelihood?_  🤔\n\n\"\"\"\n\n# ╔═╡ 8ced1f19-501a-47ff-8b0a-eee49816bd4a\nmd\"\"\"\nChoose **parameters** $\\alpha$ 👉 $(@bind α_b Scrubbable(0:0.1:5, default = 2)) and \n\n $\\rho$ 👉 $(@bind ρ Scrubbable(0:0.1:5, default = 2))\n\n\n\"\"\"\n\n# ╔═╡ 8efc6cb4-23f3-4ff3-84ee-2cd7891dd1a8\nmd\"\"\"\n## Gaussian distribution\n\n> $p_{\\mathcal{N}}(x\\,|\\,x_0, \\sigma)  = \\frac{1}{\\sqrt{2\\pi\\sigma^2}} \\exp\\left( -\\frac{(x-x_0)^2}{2\\sigma^2}\\right), \\quad x \\in (-\\infty,\\infty)$\n\n\n_What's the definition in more dimensions?_  🤔\n\n\"\"\"\n\n# ╔═╡ ed6970b0-8f76-4490-aef6-7bdfba026c27\nmd\"\"\"\nChoose **parameters** $x_0$ 👉 $(@bind x_0 Scrubbable(-10:0.1:10, default = 0)) and \n\n $\\sigma$ 👉 $(@bind σ Scrubbable(0.1:0.1:5, default = 2))\n\n\n\"\"\"\n\n# ╔═╡ 44d4d19e-b0d2-4768-bc6b-eb63affc3898\nmd\"\"\"\n# About the creators\n\nThis notebook was created by **Prof. Wolfgang von der Linden** and **Gerhard Dorn** in the context of the course **Bayesian probability theory**.\n\nThe course is a free massive open online course (MOOC) available on the platform [`IMOOX`](https://imoox.at/mooc/local/landingpage/course.php?shortname=bayes&lang=en)\n\n$(Resource(\"https://raw.githubusercontent.com/Captain-Bayes/images/main/adventure_map.gif\"))\n\"\"\"\n\n# ╔═╡ 02f9fccb-594a-4594-b3f1-900f0847e01e\nfunction sr(variable, dig = 2; add_sign = false)\n\t# string and round - converts a variable into a string with the predifined precission - to be extended to scientific and other formats\n\tif dig == 0\n\t\tst = string(round(Int, variable))\n\telse\n\t\tst =  string(round(variable, digits = dig))\n\tend\n\t\n\tif add_sign\n\t\tst = (variable < 0 ? \"\" : \"+\") * st\n\tend\n\t\n\treturn st\n\t\n\t\nend\n\n\n# ╔═╡ c3fad29d-ffa2-4bab-a164-6b53573b6050\nbegin\n\t\n\tmd\"\"\"asdf $asdf$ $(α)  as\"\"\"\n\tgamma_x = 0:0.1:10\n\t\n\t\n\tgamma_pdf = β^α / gamma(α) .* gamma_x.^(α-1) .* exp.(-β .* gamma_x)\n\t\n\tplot(gamma_x, gamma_pdf,\n\tlines = :path,\n\ttitle = \"Gamma distribution\" ,\n\t#yscale = :log10,\n\t# labels\n\txlabel = latexstring(\"x\"), \n\tylabel = latexstring(\"p_\\\\Gamma(x\\\\,|\\\\, \\\\alpha, \\\\beta)\"),\n\tlabel = latexstring(\" \\\\alpha = \" * sr(α,2) * \", \\\\beta = \" * sr(β,2)),\n\t#xtick = [0,10],\n\t#ytick = [0,1/10],\n\t#xticklabel = latexstring(\"x_{\\\\textrm{max}}\"),\n\t#ylim = [0,50],\n\tlegend= :right,\n\t#xlim = [0,60],\n\t# series properties\n\tlinewidth = 4,\n\t# size of image, margins, font size, ...\n\tsize = (600,400),  \n\tlabelfontsize = 20,\n\tlegendfontsize = 15,\n\ttickfontsize = 15,\n\tbottom_margin =25mm,\n\tleft_margin = 5mm,\n\tright_margin = 10mm,\n\ttitlefontsize = 20,\t\n\tbackground_color = :transparent,  \n\t# this is really cool, transparent background :)\n\tforeground_color = :black,\n\t# makes it look like LaTeX\n\tfontfamily=\"Computer Modern\"\n)\n\t\n\t\nend\n\n# ╔═╡ 2ba5aa6f-cdb8-4a82-85c2-66820ceefd4b\nbegin\n\tbeta_x = 0:0.01:1\n\t\n\t\n\tbeta_pdf = 1 ./beta(α_b, ρ) .* beta_x.^(α_b-1) .* (1 .- beta_x).^(ρ-1)\n\t\n\tplot(beta_x, beta_pdf,\n\tlines = :path,\n\ttitle = \"Beta distribution\",\n\t#yscale = :log10,\n\t# labels\n\txlabel = latexstring(\"x\"), \n\tylabel = latexstring(\"p_\\\\beta(x\\\\,|\\\\, \\\\alpha, \\\\rho)\"),\n\tlabel = latexstring(\" \\\\alpha = \" * sr(α_b,2) * \", \\\\rho = \" * sr(ρ,2)),\n\t#xtick = [0,10],\n\t#ytick = [0,1/10],\n\t#xticklabel = latexstring(\"x_{\\\\textrm{max}}\"),\n\tylim = [0,4],\n\tlegend= :top,\n\t#xlim = [0,60],\n\t# series properties\n\tlinewidth = 4,\n\t# size of image, margins, font size, ...\n\tsize = (600,400),  \n\tlabelfontsize = 20,\n\tlegendfontsize = 15,\n\ttickfontsize = 15,\n\tbottom_margin =25mm,\n\tleft_margin = 5mm,\n\tright_margin = 10mm,\n\ttitlefontsize = 20,\t\n\tbackground_color = :transparent,  \n\t# this is really cool, transparent background :)\n\tforeground_color = :black,\n\t# makes it look like LaTeX\n\tfontfamily=\"Computer Modern\"\n)\n\t\n\t\n\t#savefig(\"C://beta_alpha_01_rho_01\")\n\t\nend\n\n# ╔═╡ 49cbd69b-e140-422c-9c1e-e9dd2a0545d8\nbegin\n\td = -10:0.01:10\n\t\n\td1_pdf = 1 ./sqrt(2*pi*σ^2) .* exp.(- (d .-x_0).^2 ./(2*σ^2))\n\tplot(d, d1_pdf,\n\tlines = :path,\n\ttitle = \"Gaussian distribution\",\n\t#yscale = :log10,\n\t# labels\n\txlabel = latexstring(\"x\"), \n\tylabel = latexstring(\"p\\\\,(x\\\\,|\\\\, \\\\vec a)\"),\n\tlabel = latexstring(\" x_0 = \" * sr(x_0,2) * \", \\\\sigma = \" * sr(σ,2)),\n\t#xtick = [0,10],\n\t#ytick = [0,1/10],\n\t#xticklabel = latexstring(\"x_{\\\\textrm{max}}\"),\n\tylim = [0,1],\n\tlegend= :topright,\n\t#xlim = [0,60],\n\t# series properties\n\tlinewidth = 4,\n\t# size of image, margins, font size, ...\n\tsize = (600,400),  \n\tlabelfontsize = 20,\n\tlegendfontsize = 15,\n\ttickfontsize = 15,\n\tbottom_margin =25mm,\n\tleft_margin = 5mm,\n\tright_margin = 10mm,\n\ttitlefontsize = 20,\t\t\n\tbackground_color = :transparent,  \n\t# this is really cool, transparent background :)\n\tforeground_color = :black,\n\t# makes it look like LaTeX\n\tfontfamily=\"Computer Modern\"\n)\nend\n\n# ╔═╡ 3554f46b-3a86-4e97-8c02-4911f8f0776a\n\tTableOfContents()\n\n\n# ╔═╡ 1bf9a33d-da46-4dec-8c17-75243c3b84a9\nbegin\nkeep_working(text=md\"The answer is not quite right.\", title=\"Keep working on it!\") = Markdown.MD(Markdown.Admonition(\"danger\", title, [text]));\n\nalmost(text, title=\"Almost there!\") = Markdown.MD(Markdown.Admonition(\"warning\", title, [text]));\n\nhint(text, title =\"Hint\") = Markdown.MD(Markdown.Admonition(\"hint\", title, [text]));\n\t\ncorrect(text=md\"Great! You got the right answer! Let's move on to the next section.\", title=\"Got it!\") = Markdown.MD(Markdown.Admonition(\"correct\", title, [text]));\nmd\" Definition of Boxes\"\nend\n\n# ╔═╡ 92552af0-844f-11eb-23fa-5711044ae250\nif !(is_num & !is_discontinuous & !is_no_problem)\n\thint(md\"The depicted values are wrong, guess what the reason in our implementation could be.\")\nelse\n\tcorrect(md\"**Great!** ✨ You got the right answer! 🎈\n\t\t\nWe are dividing two very large numbers - think and post in the forum of how this could be solved!\")\nend\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nDistributions = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nLaTeXStrings = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nMarkdown = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nSpecialFunctions = \"276daf66-3868-5448-9aa4-cd146d93841b\"\n\n[compat]\nDistributions = \"~0.25.32\"\nLaTeXStrings = \"~1.3.0\"\nPlots = \"~1.24.0\"\nPlutoUI = \"~0.7.20\"\nSpecialFunctions = \"~1.8.1\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[AbstractPlutoDingetjes]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"0bc60e3006ad95b4bb7497698dd7c6d649b9bc06\"\nuuid = \"6e696c72-6542-2067-7265-42206c756150\"\nversion = \"1.1.1\"\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"f2202b55d816427cd385a9a4f3ffb226bee80f99\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+0\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"f885e7e7c124f8c92650d61b9477b9ac2ee607dd\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.11.1\"\n\n[[ChangesOfVariables]]\ndeps = [\"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"9a1d594397670492219635b35a3d830b04730d62\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.1\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"a851fec56cb73cfdf43762999ec72eff5b86882a\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.15.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"dce3e3fea680869eaa0b774b2e8343e9ff442313\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.40.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[DensityInterface]]\ndeps = [\"InverseFunctions\", \"Test\"]\ngit-tree-sha1 = \"80c3e8639e3353e5d2912fb3a1916b8455e2494b\"\nuuid = \"b429d917-457f-4dbc-8f4c-0cc954292b1d\"\nversion = \"0.4.0\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Distributions]]\ndeps = [\"ChainRulesCore\", \"DensityInterface\", \"FillArrays\", \"LinearAlgebra\", \"PDMats\", \"Printf\", \"QuadGK\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"Test\"]\ngit-tree-sha1 = \"380dab663ca4234c4ec91340c3211c5e73374612\"\nuuid = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nversion = \"0.25.32\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"8756f9935b7ccc9064c6eef0bff0ad643df733a3\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.12.7\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"0c603255764a1fa0b61752d2bec14cfbd18f7fe8\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+1\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"30f2b340c2fff8410d89bfcdc9c0a6dd661ac5f7\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.62.1\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"fd75fa3a2080109a2c0ec9864a6e14c60cca3866\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.62.0+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"7bf67e9a481712b3dbe9cb3dac852dc4b1162e02\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+0\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"0fa77022fe4b511826b39c894c90daf5fce3334a\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.17\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"8a954fed8ac097d5be04921d595f741115c1b2ad\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+0\"\n\n[[Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[HypertextLiteral]]\ngit-tree-sha1 = \"2b078b5a615c6c0396c77810d92ee8c6f470d238\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.3\"\n\n[[IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.2\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"f2355693d6778a178ade15952b7ac47a4ff97996\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.3.0\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a8f4f279b6fa3c3c4f1adadd78a621b13a506bce\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.9\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"0b4a5d71f3e5200a7dff793393e09dfc2d874290\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+1\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"be9eef9f9d78cecb6f262f3c10da151a6c5ab827\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.5\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+0\"\n\n[[OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[PDMats]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"SuiteSparse\"]\ngit-tree-sha1 = \"ee26b350276c51697c9c2d88a072b339f9f03d73\"\nuuid = \"90014a1f-27ba-587c-ab20-58faa44d9150\"\nversion = \"0.11.5\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"ae4bbcadb2906ccc085cf52ac286dc1377dceccc\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.1.2\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"b084324b4af5a438cd63619fd006614b3b20b87b\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.0.15\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\", \"UnicodeFun\"]\ngit-tree-sha1 = \"02a083caba3f73e42decb810b2e0740783022978\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.24.0\"\n\n[[PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"1e0cb51e0ccef0afc01aab41dc51a3e7f781e8cb\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.20\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[QuadGK]]\ndeps = [\"DataStructures\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"78aadffb3efd2155af139781b8a8df1ef279ea39\"\nuuid = \"1fd47b50-473d-5c70-9696-f719f8f3bcdc\"\nversion = \"2.4.2\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.2.1\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"7ad0dfa8d03b7bcf8c597f59f5292801730c55b8\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.4.1\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[Rmath]]\ndeps = [\"Random\", \"Rmath_jll\"]\ngit-tree-sha1 = \"bf3188feca147ce108c76ad82c2792c57abe7b1f\"\nuuid = \"79098fc4-a85e-5d69-aa6a-4863f24498fa\"\nversion = \"0.7.0\"\n\n[[Rmath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"68db32dff12bb6127bac73c209881191bf0efbb7\"\nuuid = \"f50d1b31-88e8-58de-be2c-1cc44531875f\"\nversion = \"0.3.0+0\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"f0bccf98e16759818ffc5d97ac3ebf87eb950150\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.8.1\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3c76dde64d03699e074ac02eb2e8ba8254d428da\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.13\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"0f2aa8e32d511f758a2ce49208181f7733a0936a\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.1.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"2bb0cb32026a66037360606510fca5984ccc6b75\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.13\"\n\n[[StatsFuns]]\ndeps = [\"ChainRulesCore\", \"InverseFunctions\", \"IrrationalConstants\", \"LogExpFunctions\", \"Reexport\", \"Rmath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"bedb3e17cc1d94ce0e6e66d3afa47157978ba404\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.14\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.3\"\n\n[[SuiteSparse]]\ndeps = [\"Libdl\", \"LinearAlgebra\", \"Serialization\", \"SparseArrays\"]\nuuid = \"4607b0f0-06f3-5cda-b6b1-a6196a1729e9\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"fed34d0e71b91734bf0a7e10eb1bb05296ddbcd0\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.6.0\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[UnicodeFun]]\ndeps = [\"REPL\"]\ngit-tree-sha1 = \"53915e50200959667e78a92a418594b428dffddf\"\nuuid = \"1cfade01-22cf-5700-b092-accc4b62d6e1\"\nversion = \"0.4.1\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"66d72dc6fcc86352f01676e8f0f698562e60510f\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.23.0+0\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─d141cf00-8352-11eb-2e51-f115e26e1570\n# ╟─e6d68ef0-8352-11eb-1999-0384c7ff8526\n# ╟─6196a940-8353-11eb-1a09-29cb2338d697\n# ╟─a88ae050-8353-11eb-3eee-b7ee9b717fdb\n# ╟─47882682-844f-11eb-335e-afc41d5498e1\n# ╟─92552af0-844f-11eb-23fa-5711044ae250\n# ╟─7799e4c0-844b-11eb-2484-051807211341\n# ╟─9acafce0-844b-11eb-331c-0186de214a59\n# ╟─3a1c82a0-844c-11eb-05a6-75924317db64\n# ╟─73b7eb70-8452-11eb-0f2e-df6b5cd0da4a\n# ╟─08562f30-8453-11eb-36bd-7b55fcd4b82e\n# ╟─b10c08c0-8453-11eb-1614-ef634e6929e5\n# ╟─65567910-8453-11eb-1de3-d38bd5010350\n# ╟─1cc62475-2dd3-488b-9647-9d5b2986d791\n# ╟─48811336-16f6-496f-848d-54fd834bb0da\n# ╟─fb470501-cea4-4ac9-a652-d9874dbd7bdc\n# ╟─c3fad29d-ffa2-4bab-a164-6b53573b6050\n# ╟─3d85408a-b356-4107-b604-b39fb5a6982e\n# ╟─8ced1f19-501a-47ff-8b0a-eee49816bd4a\n# ╟─2ba5aa6f-cdb8-4a82-85c2-66820ceefd4b\n# ╟─8efc6cb4-23f3-4ff3-84ee-2cd7891dd1a8\n# ╟─ed6970b0-8f76-4490-aef6-7bdfba026c27\n# ╟─49cbd69b-e140-422c-9c1e-e9dd2a0545d8\n# ╟─44d4d19e-b0d2-4768-bc6b-eb63affc3898\n# ╟─73555af0-8353-11eb-215d-d3578a6f1e2e\n# ╟─02f9fccb-594a-4594-b3f1-900f0847e01e\n# ╟─3554f46b-3a86-4e97-8c02-4911f8f0776a\n# ╟─1bf9a33d-da46-4dec-8c17-75243c3b84a9\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "0354df889f7998bc9341044d7b3165c1e155586a", "size": 48632, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/distributions.jl", "max_stars_repo_name": "moserjo/bayes-imoox", "max_stars_repo_head_hexsha": "144bde64410b7e740efa28c82b5e7dfe66885141", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-03-19T04:40:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T14:12:16.000Z", "max_issues_repo_path": "notebooks/distributions.jl", "max_issues_repo_name": "moserjo/bayes-imoox", "max_issues_repo_head_hexsha": "144bde64410b7e740efa28c82b5e7dfe66885141", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-02-20T10:51:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-26T13:57:05.000Z", "max_forks_repo_path": "notebooks/distributions.jl", "max_forks_repo_name": "moserjo/bayes-imoox", "max_forks_repo_head_hexsha": "144bde64410b7e740efa28c82b5e7dfe66885141", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-19T18:14:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T07:07:35.000Z", "avg_line_length": 30.3760149906, "max_line_length": 366, "alphanum_fraction": 0.7096561935, "num_tokens": 21413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.8887587934924569, "lm_q1q2_score": 0.7926049087666609}}
{"text": "using LinearAlgebra\nusing StatsBase\n\n\nfunction best_approx(A, k)\n    U, _, _ = svd(A);\n    return U[:, 1:k]\nend\n\n\nfunction ell(A, i; λ=0)\n    ai = A[:, i]\n    return ai' * pinv(A * A' + λ^2 * I) * ai\nend\n\n\nfunction ridge_weights(A, λ)\n    _, n = size(A)\n    weights = zeros(n)\n    for i = 1:n\n        weights[i] = ell(A, i, λ=λ)\n    end\n    return weights\nend\n\n\nfunction uniform_weights(A)\n    _, n = size(A)\n    return ones(n) / n\nend\n\n\nfunction squared_norms_weights(A)\n    _, n = size(A)\n    return dropdims(sum(A .* A, dims=1), dims=1)\nend\n\n\nfunction samplemat(A, weights, k)\n    columns = sample(1:n, Weights(weights), k)\n    return A[:, columns]\nend\n\n\nfunction ridge_sampling(A, k, λ)\n    return samplemat(A, ridge_weights(A, λ), k)\nend\n\n\nfunction uniform_sampling(A, k)\n    return samplemat(A, uniform_weights(A), k)\nend\n\n\nfunction squared_norms_sampling(A, k)\n    return samplemat(A, squared_norms_weights(A), k)\nend\n\n\nfunction hilbert(n)\n    H = zeros(n, n)\n    for i = 1:n\n        for j = 1:n\n            H[i, j] = 1 / (i + j - 1)\n        end\n    end\n    return H\nend\n\n\nfunction robustproj(A, tol=1e-12)\n    U, s, _ = svd(A)\n    k = sum(s .> tol)\n    return U[:, 1:k] * U[:, 1:k]'\nend\n\n\nfunction approxerror(A, C)\n    return norm(A - robustproj(C) * A)\nend\n", "meta": {"hexsha": "77c6b56452ce88949429e122a3bb980569e67b17", "size": 1267, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code/utils.jl", "max_stars_repo_name": "qrebjock/low-rank-approximation-techniques", "max_stars_repo_head_hexsha": "c39c1774a7a4503047025bc93ac6481f9b464cab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/utils.jl", "max_issues_repo_name": "qrebjock/low-rank-approximation-techniques", "max_issues_repo_head_hexsha": "c39c1774a7a4503047025bc93ac6481f9b464cab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/utils.jl", "max_forks_repo_name": "qrebjock/low-rank-approximation-techniques", "max_forks_repo_head_hexsha": "c39c1774a7a4503047025bc93ac6481f9b464cab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.6419753086, "max_line_length": 52, "alphanum_fraction": 0.5856353591, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7925584355306216}}
{"text": "# Sum of the positive components\n\nexport SumPositive\n\n\"\"\"\n**Sum of the positive coefficients**\n\n    SumPositive()\n\nReturns the function\n```math\nf(x) = ∑_i \\\\max\\\\{0, x_i\\\\}.\n```\n\"\"\"\nstruct SumPositive <: ProximableFunction end\n\nis_separable(f::SumPositive) = true\nis_convex(f::SumPositive) = true\n\nfunction (f::SumPositive)(x::AbstractArray{T}) where T <: Real\n    return sum(xi -> max(xi, 0), x)\nend\n\nfunction prox!(y::AbstractArray{R}, f::SumPositive, x::AbstractArray{R}, gamma::R=R(1)) where R <: Real\n    fsum = R(0)\n    for i in eachindex(x)\n        y[i] = x[i] < gamma ? (x[i] > 0 ? R(0) : x[i]) : x[i]-gamma\n        fsum += y[i] > 0 ? y[i] : R(0)\n    end\n    return fsum\nend\n\nfunction gradient!(y::AbstractArray{R}, f::SumPositive, x::AbstractArray{R}) where R <: Real\n    y .= max.(0, sign.(x))\n    return sum(xi -> max(xi, 0), x)\nend\n\nfun_name(f::SumPositive) = \"Sum of the positive coefficients\"\nfun_dom(f::SumPositive) = \"AbstractArray{Real}\"\nfun_expr(f::SumPositive) = \"x ↦ sum(max(0, x))\"\n\nfunction prox_naive(f::SumPositive, x::AbstractArray{R}, gamma::R=R(1)) where R <: Real\n    y = copy(x)\n    indpos = x .> 0\n    y[indpos] = max.(R(0), x[indpos] .- gamma)\n    return y, sum(max.(R(0), y))\nend\n\n# ######################### #\n# Prox with multiple gammas #\n# ######################### #\n\nfunction prox!(y::AbstractArray{R}, f::SumPositive, x::AbstractArray{R}, gamma::AbstractArray{R}) where R <: Real\n    fsum = R(0)\n    for i in eachindex(x)\n        y[i] = x[i] < gamma[i] ? (x[i] > 0 ? R(0) : x[i]) : x[i]-gamma[i]\n        fsum += y[i] > 0 ? y[i] : R(0)\n    end\n    return fsum\nend\n\nfunction prox_naive(f::SumPositive, x::AbstractArray{R}, gamma::AbstractArray{R}) where R <: Real\n    y = copy(x)\n    indpos = x .> 0\n    y[indpos] = max.(R(0), x[indpos] .- gamma[indpos])\n    return y, sum(max.(R(0), y))\nend\n", "meta": {"hexsha": "430fa55c04f24a9686de511bb2bda2d294a5bd50", "size": 1828, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/sumPositive.jl", "max_stars_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_stars_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2016-10-29T12:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:11:52.000Z", "max_issues_repo_path": "src/functions/sumPositive.jl", "max_issues_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_issues_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2016-10-26T16:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T20:38:48.000Z", "max_forks_repo_path": "src/functions/sumPositive.jl", "max_forks_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_forks_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T10:40:24.000Z", "avg_line_length": 26.8823529412, "max_line_length": 113, "alphanum_fraction": 0.5820568928, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520764, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7925584270241648}}
{"text": "# signal_haar.jl\n##########################\nfs=Int(1000);\nTs=1/fs;\nN=Int(12000);\nT=N/fs;\n#t=(0:Int(N-1))*Ts;\n\nx=zeros(Float64, N)\nfor m=1:N\n    x[m]=sin(2*Ts*(m-1)*(Ts*(m-1)-3)*(Ts*(m-1)-6)*(Ts*(m-1)-9)*(Ts*(m-1)-12))\nend\n\nusing DSP, Wavelets\n\ny1=dwt(x, wavelet(WT.haar), 1);\ny2=dwt(x, wavelet(WT.haar), 2);\ny3=dwt(x, wavelet(WT.haar), 3);\ny4=dwt(x, wavelet(WT.haar), 4);\ny5=dwt(x, wavelet(WT.haar), 5);\n\ny1a=zeros(N);\ny2a=zeros(N);\ny3a=zeros(N);\ny4a=zeros(N);\ny5a=zeros(N);\ny1a[1:Int(N/2)]=y1[1:Int(N/2)];\ny2a[1:Int(N/4)]=y2[1:Int(N/4)];\ny3a[1:Int(N/8)]=y3[1:Int(N/8)];\ny4a[1:Int(N/16)]=y4[1:Int(N/16)];\ny5a[1:Int(N/32)]=y5[1:Int(N/32)];\ny1d=y1-y1a;\ny2d=y2-y2a;\ny3d=y3-y3a;\ny4d=y4-y4a;\ny5d=y5-y5a;\n\nx1a=idwt(y1a, wavelet(WT.haar), 1);\nx1d=idwt(y1d, wavelet(WT.haar), 1);\nx2a=idwt(y2a, wavelet(WT.haar), 2);\nx2d=idwt(y2d, wavelet(WT.haar), 2);\nx3a=idwt(y3a, wavelet(WT.haar), 3);\nx3d=idwt(y3d, wavelet(WT.haar), 3);\nx4a=idwt(y4a, wavelet(WT.haar), 4);\nx4d=idwt(y4d, wavelet(WT.haar), 4);\nx5a=idwt(y5a, wavelet(WT.haar), 5);\nx5d=idwt(y5d, wavelet(WT.haar), 5);\n\nusing Plots\n\n# x1a\np1a=plot(x1a, \n    xaxis=\"n = 0, 1, 2, ..., N-1\", \n    yaxis=\"amplitude\", \n    title=\"Level 1 Approximation\", \n    grid=false, \n    legend=false)\nplot!(xticks = ([0 6000 12000;], [0 6000 12000]))\nplot!(yticks = ([-1 0 1;], [-1 0 1]))\n# x1d\np1d=plot(x1d, \n    xaxis=\"n = 0, 1, 2, ..., N-1\", \n    yaxis=\"amplitude\", \n    title=\"Level 1 Detail\", \n    grid=false, \n    legend=false)\nplot!(xticks = ([0 6000 12000;], [0 6000 12000]))\nplot!(yticks = ([-1 0 1;], [-1 0 1]))\n# x1\nplot(p1a, p1d, layout = (1,2))\nsavefig(\"signal_haar_level_1.png\") \n\n# x2a\np2a=plot(x2a, \n    xaxis=\"n = 0, 1, 2, ..., N-1\", \n    yaxis=\"amplitude\", \n    title=\"Level 2 Approximation\", \n    grid=false, \n    legend=false)\nplot!(xticks = ([0 6000 12000;], [0 6000 12000]))\nplot!(yticks = ([-1 0 1;], [-1 0 1]))\n# x2d\np2d=plot(x2d, \n    xaxis=\"n = 0, 1, 2, ..., N-1\", \n    yaxis=\"amplitude\", \n    title=\"Level 2 Detail\", \n    grid=false, \n    legend=false)\nplot!(xticks = ([0 6000 12000;], [0 6000 12000]))\nplot!(yticks = ([-1 0 1;], [-1 0 1]))\n# x1\nplot(p2a, p2d, layout = (1,2))\nsavefig(\"signal_haar_level_2.png\") \n\n# x3a\np3a=plot(x3a, \n    xaxis=\"n = 0, 1, 2, ..., N-1\", \n    yaxis=\"amplitude\", \n    title=\"Level 3 Approximation\", \n    grid=false, \n    legend=false)\nplot!(xticks = ([0 6000 12000;], [0 6000 12000]))\nplot!(yticks = ([-1 0 1;], [-1 0 1]))\n# x3d\np3d=plot(x3d, \n    xaxis=\"n = 0, 1, 2, ..., N-1\", \n    yaxis=\"amplitude\", \n    title=\"Level 3 Detail\", \n    grid=false, \n    legend=false)\nplot!(xticks = ([0 6000 12000;], [0 6000 12000]))\nplot!(yticks = ([-1 0 1;], [-1 0 1]))\n# x1\nplot(p3a, p3d, layout = (1,2))\nsavefig(\"signal_haar_level_3.png\") \n\n# x4a\np4a=plot(x4a, \n    xaxis=\"n = 0, 1, 2, ..., N-1\", \n    yaxis=\"amplitude\", \n    title=\"Level 4 Approximation\", \n    grid=false, \n    legend=false)\nplot!(xticks = ([0 6000 12000;], [0 6000 12000]))\nplot!(yticks = ([-1 0 1;], [-1 0 1]))\n# x4d\np4d=plot(x4d, \n    xaxis=\"n = 0, 1, 2, ..., N-1\", \n    yaxis=\"amplitude\", \n    title=\"Level 4 Detail\", \n    grid=false, \n    legend=false)\nplot!(xticks = ([0 6000 12000;], [0 6000 12000]))\nplot!(yticks = ([-1 0 1;], [-1 0 1]))\n# x1\nplot(p4a, p4d, layout = (1,2))\nsavefig(\"signal_haar_level_4.png\") \n\n# x5a\np5a=plot(x5a, \n    xaxis=\"n = 0, 1, 2, ..., N-1\", \n    yaxis=\"amplitude\", \n    title=\"Level 5 Approximation\", \n    grid=false, \n    legend=false)\nplot!(xticks = ([0 6000 12000;], [0 6000 12000]))\nplot!(yticks = ([-1 0 1;], [-1 0 1]))\n# x5d\np5d=plot(x5d, \n    xaxis=\"n = 0, 1, 2, ..., N-1\", \n    yaxis=\"amplitude\", \n    title=\"Level 5 Detail\", \n    grid=false, \n    legend=false)\nplot!(xticks = ([0 6000 12000;], [0 6000 12000]))\nplot!(yticks = ([-1 0 1;], [-1 0 1]))\n# x1\nplot(p5a, p5d, layout = (1,2))\nsavefig(\"signal_haar_level_5.png\") \n\n\n", "meta": {"hexsha": "4f4ac2c426cae080619d8f2cf3583047d89d2cf9", "size": 3805, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "signal_haar.jl", "max_stars_repo_name": "hiroyuki-chihara/Julia.signal_processing", "max_stars_repo_head_hexsha": "feea74154abb039d221dc42178f3fd2fb26bde0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-06T11:54:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T11:54:07.000Z", "max_issues_repo_path": "signal_haar.jl", "max_issues_repo_name": "hiroyuki-chihara/Julia.signal_processing", "max_issues_repo_head_hexsha": "feea74154abb039d221dc42178f3fd2fb26bde0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "signal_haar.jl", "max_forks_repo_name": "hiroyuki-chihara/Julia.signal_processing", "max_forks_repo_head_hexsha": "feea74154abb039d221dc42178f3fd2fb26bde0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.487654321, "max_line_length": 77, "alphanum_fraction": 0.5605781866, "num_tokens": 1794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7925427781664585}}
{"text": "\"\"\"\n# Cooley–Tukey FFT algorithm\n\n## References\n\n- [clrs]: Cormen, Thomas H., Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein.\n  Introduction to algorithms. MIT press, 2009.\n- [manber]: Manber, Udi. Introduction to algorithms: a creative approach. Addison-Wesley Longman\n  Publishing Co., Inc., 1989.\n- [wiki]: https://en.wikipedia.org/wiki/Cooley–Tukey_FFT_algorithm\n\"\"\"\nmodule FastFourierTransform\n\nusing OffsetArrays\n\nexport\n    Direction, Forward, Backward,\n    dft, idft,\n    fft_recursive_naive, ifft_recursive_naive,\n    fft_recursive, ifft_recursive,\n    fft_iterative, ifft_iterative,\n    eval_poly, poly_mul\n\n#=\n\nPrimitive nth root of unity (can be either clockwise or counterclockwise):\n\n    w_n = exp(-im * 2π / n)\n\nCancellation lemma ([clrs] Lemma 30.3):\n\n    w_{n d}^{d k} = exp(-im * 2π * (k d)/(n d)) = w_n^k\n\nHalving lemma ([clrs] Lemma 30.5) (by Cancellation lemma we have $(w_n^k)^2 = w_{n/2}^k$):\n\n      { (w_n^k)^2 for k in 0..(n - 1) }\n    = { w_{n/2}^k for k in 0..(n/2 - 1) } ∪ { w_{n/2}^k for k in (n/2)..(n - 1) }\n    = { w_{n/2}^k for k in 0..(n/2 - 1) }\n\nSummation lemma ([clrs] Lemma 30.6):\n\n      \\sum_{j = 0}^{n - 1} w_n^{j k}\n    = ((w_n^k)^n - 1) / (w_n^k - 1)\n    = (1^k - 1) / (w_n^k - 1)\n    = 0\n\nDanielson–Lanczos(?) lemma ([manber] Eq. 9.8):\n\n    P(x) = P_e(x^2) + x * P_o(x^2)\n\nSo the problem of computing (note it's a list instead of a set)\n\n    [ P(w_n^i) for i in 0..(n - 1) ]\n\nreduces to\n\n    [ P_e((w_n^i)^2) + w_n^i * P_o((w_n^i)^2) for i in 0..(n - 1) ]\n\nwhich by Halving lemma further reduces to (also uses [clrs] Corollary 30.4)\n\n      [ P_e(w_{n/2}^i) + w_n^i * P_o(w_{n/2}^i) for i in 0..(n - 1) ]\n    = [ P_e(w_{n/2}^i) + w_n^i * P_o(w_{n/2}^i) for i in 0..(n/2 - 1) ] ++\n      [ P_e(w_{n/2}^i) - w_n^i * P_o(w_{n/2}^i) for i in 0..(n/2 - 1) ]\n\nThe inverse of DFT matrix `V^(-1)`:\n\n    V_ij(w) = w^{i j}\n    V^{-1}_ij(w) = 1/n V_ij(1/w) = 1/n w^{-i j}\n    (V V^{-1})_ij(w) = 1/n w_{i k} w^{-k j}  ...(*)\n\n    (*) = 1/n n = 1,  if i = j\n    (*) = 1/n n = 1/n \\sum_{k = 0}^{n - 1} (k d) = 0,  if i - j = d ≠ 0  (by Summation lemma)\n\n=#\n\n# All `OffsetArray`s are 0-based.\n\n@inline function zero_based(A::AbstractArray)::OffsetArray\n    (r, c) = size(A) .- 1\n    OffsetArray(A, 0:r, 0:c)\nend\n\n@inline function zero_based(v::AbstractVector)::OffsetVector\n    OffsetVector(v, 0:(length(v) - 1))\nend\n\nfunction divide(W::OffsetArray{T})::Tuple{OffsetArray{T}, OffsetArray{T}} where T\n    (n, nn) = size(W)\n    @assert n == nn && n > 1 && iseven(n) \"Invalid input\"\n\n    W_e = @view parent(W)[1:(n ÷ 2), 1:2:end]\n    W_o = @view parent(W)[1:(n ÷ 2), 2:2:end]\n    (W_e, W_o) .|> zero_based\nend\n\nfunction divide_vec(\n    x::OffsetVector{T}\n)::Tuple{OffsetVector{T}, OffsetVector{T}} where T\n    n = length(x)\n    # `n` can be 1 -- an edge case\n    @assert (n == 1) || (n > 1 && iseven(n)) \"Invalid input\"\n\n    x_e = @view parent(x)[1:2:end]\n    x_o = @view parent(x)[2:2:end]\n    (x_e, x_o) .|> zero_based\nend\n\nfunction bit_reverse(x::Int, bit_len::Int)::Int\n    y = 0\n    for i in 1:bit_len\n        y <<= 1\n        y |= x & 1\n        x >>= 1\n    end\n    y\nend\n\nfunction bit_reverse_copy(a::OffsetVector{T})::OffsetVector{T} where T\n    n = length_checked(a)\n    bit_len = trailing_zeros(n)\n    b = zero(a)\n    for i in 0:(n - 1)\n        b[bit_reverse(i, bit_len)] = a[i]\n    end\n    b\nend\n\n@enum Direction Forward Backward\n\nfunction dft_matrix(T::Type, n::Int, dir::Direction)::OffsetArray{Complex{T}}\n    W = OffsetArray(Array{Complex{T}, 2}(undef, n, n), 0:(n - 1), 0:(n - 1))\n\n    # Sets `W_ij = exp(-im * 2π * i*j/n)` (forward). It is already O(n^2).\n    for i in 0:(n - 1)\n        for j in i:(n - 1)\n            W[i, j] = W[j, i] =\n                if dir == Forward\n                    exp((-2π)im * (i * j / n))\n                else\n                    # (!) Do not put `/ n` here.\n                    exp((2π)im * (i * j / n))\n                end\n        end\n    end\n\n    W\nend\n\nfunction dft_vector(T::Type, n::Int, dir::Direction)::OffsetVector{Complex{T}}\n    # Sets `w_i = exp(-im * 2π * i/n)` (forward).\n    #\n    # Type annotation is required for `n == 1`.\n    w::Vector{Complex{T}} =\n        if dir == Forward\n            [exp((-2 * T(π))im * i / n) for i in 0:(n ÷ 2 - 1)]\n        else\n            # (!) Do not put `/ n` here as unlike `W`, `V[:, 0]` is not 0\n            [exp((2 * T(π))im * i / n) for i in 0:(n ÷ 2 - 1)]\n        end\n    OffsetVector(w, 0:(n ÷ 2 - 1))\nend\n\nfunction length_checked(a::AbstractVector)::Int\n    n = length(a)\n    @assert ispow2(n) \"Coefficient length is not a power of 2\"\n    n\nend\n\n#===== DFT (by direct matrix-vector multiplication) =====#\n\n# Reference implementation, for verification.\nfunction dft(a::Vector{Complex{T}})::Vector{Complex{T}} where T<:AbstractFloat\n    n = length_checked(a)\n    W = dft_matrix(T, n, Forward)\n    parent(W) * a\nend\n\nfunction idft(a::Vector{Complex{T}})::Vector{Complex{T}} where T<:AbstractFloat\n    n = length_checked(a)\n    W = dft_matrix(T, n, Backward)\n    parent(W) * a / n\nend\n\n#===== FFT (by recursing on DFT matrix) =====#\n#\n# This section follows the explanation in [manber] 9.6.\n\nfunction fft_recursive_naive(a::Vector{Complex{T}})::Vector{Complex{T}} where T<:AbstractFloat\n    length_checked(a)\n    fft_recursive_naive_impl(a, Forward)\nend\n\nfunction ifft_recursive_naive(a::Vector{Complex{T}})::Vector{Complex{T}} where T<:AbstractFloat\n    n = length_checked(a)\n    fft_recursive_naive_impl(a, Backward) / n\nend\n\nfunction fft_recursive_naive_impl(\n    a::Vector{Complex{T}},\n    dir::Direction,\n)::Vector{Complex{T}} where T<:AbstractFloat\n    n = length_checked(a)\n    a = zero_based(a)\n\n    W = dft_matrix(T, n, dir)\n\n    function fft_recursive_naive_r!(\n        W::OffsetArray{Complex{T}},\n        a::OffsetVector{Complex{T}},\n    )::Vector{Complex{T}} where T<:AbstractFloat\n        local n = length(a)\n        if n == 1\n            return [W[0, 0] * a[0]]\n        end\n\n        (W_e, W_o) = divide(W)\n        (a_e, a_o) = divide_vec(a)\n\n        # Warning: Tricky code. Should also use `W_e` to compute `p_o`, and scales the result with\n        # `w`. This is due to the odd sub matrix (`W_o`) no longer holds the recursing property.\n        w = parent(W)[1:(n ÷ 2), 2]\n        p_e = fft_recursive_naive_r!(W_e, a_e)\n        p_o = fft_recursive_naive_r!(W_e, a_o) .* w\n\n        [\n            p_e + p_o\n            p_e - p_o\n        ]\n    end\n\n    fft_recursive_naive_r!(W, a)\nend\n\n#===== FFT (the \"standard\" recursive version) =====#\n\nfunction fft_recursive(a::Vector{Complex{T}})::Vector{Complex{T}} where T<:AbstractFloat\n    n = length_checked(a)\n    w = dft_vector(T, n, Forward)\n    fft_recursive_r(zero_based(a), w)\nend\n\nfunction ifft_recursive(a::Vector{Complex{T}})::Vector{Complex{T}} where T<:AbstractFloat\n    n = length_checked(a)\n    w = dft_vector(T, n, Backward)\n    fft_recursive_r(zero_based(a), w) / n\nend\n\nfunction fft_recursive_r(\n    a::OffsetVector{Complex{T}},\n    w::OffsetVector{Complex{T}},\n)::Vector{Complex{T}} where T<:AbstractFloat\n    n = length(a)\n    if n == 1\n        return [a[0]]\n    end\n\n    (a_e, a_o) = divide_vec(a)\n    (w_e, _) = divide_vec(w)  # relies on DFT matrix's special structure\n    p_e = fft_recursive_r(a_e, w_e)\n    p_o = fft_recursive_r(a_o, w_e)\n\n    [\n        p_e .+ parent(w) .* p_o\n        p_e .- parent(w) .* p_o\n    ]\nend\n\n#===== FFT (the iterative version) =====#\n\nfunction fft_iterative(a::Vector{Complex{T}})::Vector{Complex{T}} where T<:AbstractFloat\n    fft_iterative_impl(a, Forward)\nend\n\nfunction ifft_iterative(a::Vector{Complex{T}})::Vector{Complex{T}} where T<:AbstractFloat\n    n = length_checked(a)\n    fft_iterative_impl(a, Backward) / n\nend\n\nfunction fft_iterative_impl(\n    a::Vector{Complex{T}},\n    dir::Direction,\n)::Vector{Complex{T}} where T<:AbstractFloat\n    n = length_checked(a)\n    log2n = trailing_zeros(n)\n\n    a = zero_based(a)\n    a = bit_reverse_copy(a)\n    w = dft_vector(T, n, dir)\n\n    # The `m` here is actually `1/2 m` in [clrs].\n    for s in 1:log2n\n        m = 2 ^ (s - 1)\n        k = 0\n        while k < n\n            # butterfly operation\n            for i = 0:(m - 1)\n                # Indexes `w_{2 ^ s}^i` into vector `w_n`, so its step is `2 ^ (log2n - s)`.\n                t = w[(2 ^ (log2n - s)) * i] * a[k + i + m]\n                u = a[k + i]\n                a[k + i] = u + t\n                a[k + i + m] = u - t\n            end\n\n            k += m * 2\n        end\n    end\n    parent(a)\nend\n\n#===== Polynomial multiplication =====#\n\n\"\"\"\nEvaluates polynomial `p(x)` using Horner's rule, where `p` is the coefficient list for `x` from\n`x^0` to `x^{n - 1}`.\n\"\"\"\nfunction eval_poly(p::Vector{T}, x::T)::T where T<:Real\n    foldr((a::T, s::T) -> s * x + a, p)\nend\n\nfunction poly_mul(\n    a::Vector{T}, b::Vector{T},\n    fft_f::Function=fft_iterative, ifft_f::Function=ifft_iterative,\n)::Vector{T} where T<:Real\n    # zero-padding\n    na = length(a)\n    nb = length(b)\n    # da = na - 1, db = nb - 1; d = da + db = na + nb - 2, n = d + 1 = na + nb - 1\n    n = na + nb - 1\n    np = nextpow(2, n)\n    a = vcat(complex(a), zeros(Complex{T}, np - na))\n    b = vcat(complex(b), zeros(Complex{T}, np - nb))\n\n    # By Convolution theorem ([clrs] Theorem 30.8)\n    fa = fft_f(a)\n    fb = fft_f(b)\n    fp = fa .* fb\n    real(ifft_f(fp)[1:n])\nend\n\nend # module\n", "meta": {"hexsha": "400d44bd882f69380b255903261c5866333e922a", "size": 9300, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "FastFourierTransform/src/FastFourierTransform.jl", "max_stars_repo_name": "gyk/TrivialSolutions", "max_stars_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T05:51:37.000Z", "max_issues_repo_path": "FastFourierTransform/src/FastFourierTransform.jl", "max_issues_repo_name": "gyk/TrivialSolutions", "max_issues_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FastFourierTransform/src/FastFourierTransform.jl", "max_forks_repo_name": "gyk/TrivialSolutions", "max_forks_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2727272727, "max_line_length": 98, "alphanum_fraction": 0.564516129, "num_tokens": 3250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7925427770696111}}
{"text": "# Uses the Newton method to find the analytic center of a polytope.\n\nfunction polytope_analcenter(A::AbstractMatrix,\n                             b::AbstractVector,\n                             x0::AbstractVector,\n                             ϵ::Real;\n                             α::Real=0.01, β::Real=0.05)\n  all(A*x0.<b) || throw(\n    DomainError(\"x0 must lie strictly inside the polytope\"))\n  x = copy(x0)\n  H = zeros(size(x0, 1), size(x0, 1))\n  polytope_log(x) = -sum(log.(b-A*x))\n  while true\n    d = 1./(b-A*x)\n    ∇ = A'*d\n    H = A'*Diagonal(d)^2*A\n    Δxnt = -H\\∇\n    λ² = -∇⋅Δxnt\n    λ²/2 < ϵ && break\n    t = 1\n    xtest = x + t*Δxnt\n    while(any(A*xtest .≥ b)\n          || polytope_log(xtest) > polytope_log(x)-t*α*λ²)\n      t *= β\n      xtest = x + t*Δxnt\n    end\n    # numeric limit\n    polytope_log(xtest) == polytope_log(x) && break\n    x = xtest\n  end\n  x, H\nend\n", "meta": {"hexsha": "58bcc1b19911f46ca3f9dd946b9768900a2d6b33", "size": 882, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SVM/analyticcenter.jl", "max_stars_repo_name": "cyber-meow/Optimization_algos", "max_stars_repo_head_hexsha": "ae38b156fbd6ca71bf200fb8d2af7a5d5f817b68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SVM/analyticcenter.jl", "max_issues_repo_name": "cyber-meow/Optimization_algos", "max_issues_repo_head_hexsha": "ae38b156fbd6ca71bf200fb8d2af7a5d5f817b68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SVM/analyticcenter.jl", "max_forks_repo_name": "cyber-meow/Optimization_algos", "max_forks_repo_head_hexsha": "ae38b156fbd6ca71bf200fb8d2af7a5d5f817b68", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7272727273, "max_line_length": 67, "alphanum_fraction": 0.5, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241956308277, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7924947258132584}}
{"text": "using IntervalLinearAlgebra, LazySets, Plots\n\nA = [2..4 -1..1;-1..1 2..4]\nb = [-2..2, -1..1]\n\nXenclose = solve(A, b)\npolytopes = solve(A, b, LinearOettliPrager())\n\nplot(UnionSetArray(polytopes), ratio=1, label=\"solution set\", legend=:top)\nplot!(IntervalBox(Xenclose), label=\"enclosure\")\n", "meta": {"hexsha": "0b2c0b52b7f40c9d884e9701f1de8ae7421357f0", "size": 287, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/quickstart.jl", "max_stars_repo_name": "jorgepz/IntervalLinearAlgebra.jl", "max_stars_repo_head_hexsha": "ec65e2c5ddefc73a3ff8b94fb172d9178014a89b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2021-08-13T07:22:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T03:06:32.000Z", "max_issues_repo_path": "examples/quickstart.jl", "max_issues_repo_name": "jorgepz/IntervalLinearAlgebra.jl", "max_issues_repo_head_hexsha": "ec65e2c5ddefc73a3ff8b94fb172d9178014a89b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2021-08-10T07:44:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:45:10.000Z", "max_forks_repo_path": "examples/quickstart.jl", "max_forks_repo_name": "jorgepz/IntervalLinearAlgebra.jl", "max_forks_repo_head_hexsha": "ec65e2c5ddefc73a3ff8b94fb172d9178014a89b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-08-24T10:12:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T20:14:44.000Z", "avg_line_length": 26.0909090909, "max_line_length": 74, "alphanum_fraction": 0.6829268293, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9693242000616578, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.792494720818673}}
{"text": "mutable struct DirichletDist\n    #=\n    Dirichlet Distribution\n    p(mu | alpha)\n    = gamma(sum(alpha))\n    * Prod_k[ mu_k^(alpha_k-1)]\n    / gamma(alpha_1) / ... / gamma(alpha_k)\n    =#\n    _alpha::AbstractArray{Float64,1}\nend\n\nfunction pdf(dirichlet::DirichletDist, mu::AbstractArray{Float64,1})\n    N = size(mu)[1]\n    @assert N == size(dirichlet._alpha)[1]\n\n    sum_alpha = sum(dirichlet._alpha)\n    prod_k = 1.0\n    gamma_k = 1.0\n    for k = 1:N\n        alpha_k = dirichlet._alpha[k]\n        prod_k *= (mu[k]^(alpha_k - 1.0))\n        gamma_k *= gamma(alpha_k)\n    end\n    return gamma(sum_alpha) * prod_k / gamma_k\nend\n\nfunction pdf(dirichlet::DirichletDist, mu::AbstractArray{Float64,2})\n    N = size(mu)[1]\n    n_samples = size(mu)[2]\n    @assert N == size(dirichlet._alpha)[1]\n\n    return [pdf(dirichlet, mu[:, i]) for i = 1:n_samples]\nend\n", "meta": {"hexsha": "3b77680fd225c79d17ae4607663cf8fd3874ec62", "size": 849, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distribution/dirichlet.jl", "max_stars_repo_name": "soblin/prml-julia", "max_stars_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-10T21:46:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:40:22.000Z", "max_issues_repo_path": "src/distribution/dirichlet.jl", "max_issues_repo_name": "soblin/prml-julia", "max_issues_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distribution/dirichlet.jl", "max_forks_repo_name": "soblin/prml-julia", "max_forks_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9705882353, "max_line_length": 68, "alphanum_fraction": 0.6183745583, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7924500330210531}}
{"text": "function planeFit(X)\n    n = size(X)[1]\n    X′ = zeros(n, 3)\n    Xmean = mean(X, 1)\n    for i in 1:n\n        X′[i, :] = X[i, :] - Xmean\n    end\n    A = zeros(3, 3)\n    B = zeros(3)\n    for i in 1:n\n        A[1, 1] += X′[i, 1] ^ 2\n        A[1, 2] += X′[i, 1] * X′[i, 2]\n        A[1, 3] += X′[i, 1]\n        A[2, 2] += X′[i, 2] ^ 2\n        A[2, 3] += X′[i, 2]\n        A[3, 3] += 1.0\n        B[1] += X′[i, 1] * X′[i, 3]\n        B[2] += X′[i, 2] * X′[i, 3]\n        B[3] += X′[i, 3]\n    end\n    A[2, 1] = A[1, 2]\n    A[3, 1] = A[1, 3]\n    A[3, 2] = A[2, 3]\n    \n    Y = \\(A, B)\n    Y[3] = Y[3] - Y[1] * Xmean[1] - Y[2] * Xmean[2] + Xmean[3]\n    return Y, Xmean\nend\n\n\nfunction sphereFit(X, iternum)\n    n = size(X)[1]\n    Xmean = mean(X, 1)\n\n    function update(a, b, c, Xmean)\n        L̄ = 0.0\n        L̄a = 0.0\n        L̄b = 0.0\n        L̄c = 0.0\n        function L(x, y, z, a, b, c)\n            return sqrt((x - a)^2 + (y - b)^2 + (z - c)^2)\n        end\n        for i in 1:n\n            L̄ += L(X[i, 1], X[i, 2], X[i, 3], a, b, c)\n            L̄a += (a - X[i, 1]) / L(X[i, 1], X[i, 2], X[i, 3], a, b, c)\n            L̄b += (b - X[i, 2]) / L(X[i, 1], X[i, 2], X[i, 3], a, b, c)\n            L̄c += (c - X[i, 3]) / L(X[i, 1], X[i, 2], X[i, 3], a, b, c)\n        end\n        L̄ /= n\n        L̄a /= n\n        L̄b /= n\n        L̄c /= n\n\n        return Xmean[1] + L̄ * L̄a, Xmean[2] + L̄ * L̄b, Xmean[3] + L̄ * L̄c, L̄\n    end\n\n    a = Xmean[1]\n    b = Xmean[2]\n    c = Xmean[3]\n    r = 0.0\n    for i in 1:iternum\n        a, b, c, r = update(a, b, c, Xmean)\n    end\n    return a, b, c, r\nend\n\n\ntype param\n    θ₀::Float64\n    θ₁::Float64\n    C::Vector{Float64}\n    sampleSize::Int64\nend\n\n\nfunction cylinderFit(X)\n\n    function G(X, W, rSqr, params)\n        S = zeros(3, 3)\n        P = eye(3, 3)\n        sinθ₀ = sin(params.θ₀)\n        cosθ₀ = cos(params.θ₀)\n        sinθ₁ = sin(params.θ₁)\n        cosθ₁ = cos(params.θ₁)\n        W[1] = cosθ₀ * sinθ₁\n        W[2] = sinθ₀ * sinθ₁\n        W[3] = cosθ₁\n        S[1, 1] = 0.0\n        S[1, 2] = -W[3]\n        S[1, 3] = W[2]\n        S[2, 1] = W[3]\n        S[2, 2] = 0.0\n        S[2, 3] = W[1]\n        S[3, 1] = -W[2]\n        S[3, 2] = W[1]\n        S[3, 3] = 0.0\n        P -= W * W'\n        A = zeros(3, 3)\n        B = zeros(3)\n        Y = zeros(params.sampleSize, 3)\n        averageSqrLength = 0.0\n        sqrLength = zeros(params.sampleSize)\n        for i in 1:params.sampleSize\n            Y[i, :] = P * vec(X[i, :])\n            sqrLength[i] = dot(vec(Y[i, :]), vec(Y[i, :]))\n            A += vec(Y[i, :]) * vec(Y[i, :])'\n            B += sqrLength[i] * vec(Y[i, :])\n            averageSqrLength += sqrLength[i]\n        end\n        A /= params.sampleSize\n        B /= params.sampleSize\n        averageSqrLength /= params.sampleSize\n        Ahat = - S * A * S\n        params.C = (Ahat * B) / trace(Ahat * A)\n        error = 0.0\n        rSqr = 0.0\n        for i in 1:params.sampleSize\n            term = sqrLength[i] - averageSqrLength - 2 * dot(vec(Y[i, :]), params.C)\n            error += term * term\n            diff = params.C - vec(Y[i, :])\n            rSqr += dot(diff, diff)\n        end\n        error /= params.sampleSize\n        rSqr /= params.sampleSize\n        return  error, W, rSqr, params\n    end\n\n    params = param(0, 0, zeros(3), size(X)[1])\n    average = mean(X, 1)\n    for i in 1:params.sampleSize\n        X[i, :] -= average\n    end\n    jMax = 30 \n    iMax = 120\n    W = zeros(3)\n    C = zeros(3)\n    θ₀ = 0.0\n    θ₁ = 0.0\n    rSqr = 0.0\n    minError = Inf\n    for i in 1:iMax\n        params.θ₀ = 2 * pi * (i / iMax)\n        for j in 1:jMax\n            params.θ₁ = pi / 2.0 * (j / jMax)\n            currentW = zeros(3)\n            currentRSqr = 0.0\n            error, currentW, currentRSqr, params = G(X, currentW, currentRSqr, params)\n            if error < minError\n                minError = error\n                W =  currentW\n                C = params.C\n                θ₀ = params.θ₀\n                θ₁ = params.θ₁\n                rSqr = currentRSqr\n            end\n        end\n    end\n    return  W, C + vec(average), sqrt(rSqr), θ₀, θ₁\nend\n", "meta": {"hexsha": "d1949508836b4acd578b4e888b38f899988e2628", "size": 4096, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JuliaDe3DFitting.jl", "max_stars_repo_name": "clclcocoro/JuliaDe3DFitting", "max_stars_repo_head_hexsha": "cd82d056cb4669baf43169a510d5b2fb2d13c9c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-07-11T09:37:10.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-20T03:10:58.000Z", "max_issues_repo_path": "JuliaDe3DFitting.jl", "max_issues_repo_name": "clclcocoro/JuliaDe3DFitting", "max_issues_repo_head_hexsha": "cd82d056cb4669baf43169a510d5b2fb2d13c9c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-08-19T18:02:53.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-27T14:47:20.000Z", "max_forks_repo_path": "JuliaDe3DFitting.jl", "max_forks_repo_name": "clclcocoro/JuliaDe3DFitting", "max_forks_repo_head_hexsha": "cd82d056cb4669baf43169a510d5b2fb2d13c9c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6, "max_line_length": 86, "alphanum_fraction": 0.4052734375, "num_tokens": 1707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248259606259, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7924384518053039}}
{"text": "#=\n    Goal:\n        For the given Hilbert matrix H, and a collection of\n        100 random vectors bᵢ,\n        compute H⁻¹ bᵢ using\n        a) the LU factorization\n        b) the automatic factorization\n        c) use a SVD factorization\n\n    Hint:\n=#\n\nusing LinearAlgebra\n\n# construction of a Hilbert matrix\nN = 25\nH = Float64[1/(i+j-1) for i in 1:N, j in 1:N]\n\nM = 1000\nxs = [rand(N) for _ in 1:M]\n\nH_lu = lu(H)\nH_fact = factorize(H)\n\nbs = [H*x for x in xs]\n\nratios = zeros(M)\nfor i in 1:M\n    res_lu   = norm(xs[i] - H_lu\\bs[i])\n    res_fact = norm(xs[i] - H_fact\\bs[i])\n    ratios[i] = res_lu/res_fact\nend\n\n\n# optional: visuation of the results\nusing CairoMakie\nbegin\n    p = hist(ratios, bins=100, axis = (title = \"Ratio\",))\n    vlines!(p.axis, [1.0], color = :red)\n    current_figure()\nend\n\n\nnorm(xs[1] - lu(H) \\ bs[1])\nnorm(xs[1] - svd(H) \\ bs[1])\n", "meta": {"hexsha": "98e2c97f49c843281ab41f558aab6e8d7c114efa", "size": 856, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/atom/linearalgebra/factorize.jl", "max_stars_repo_name": "SteffenPL/Julia-for-mathematicians", "max_stars_repo_head_hexsha": "accd6bc8f4e064a1d55ae5f903607778ca84a79a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercises/atom/linearalgebra/factorize.jl", "max_issues_repo_name": "SteffenPL/Julia-for-mathematicians", "max_issues_repo_head_hexsha": "accd6bc8f4e064a1d55ae5f903607778ca84a79a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercises/atom/linearalgebra/factorize.jl", "max_forks_repo_name": "SteffenPL/Julia-for-mathematicians", "max_forks_repo_head_hexsha": "accd6bc8f4e064a1d55ae5f903607778ca84a79a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6086956522, "max_line_length": 59, "alphanum_fraction": 0.5981308411, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158416, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7924384398818328}}
{"text": "#Thin QR implementation\r\n\r\nusing LinearAlgebra\r\n\r\n\r\n\"\"\"\r\nAllocate matrices and vectors for the QR factorization of A\r\n\r\n# Arguments\r\n- `A::Array{Float64,2}`: matrix of size m x n such that m < n\r\n\r\n# Return\r\n\r\n- `QR::Array{Float64,2}`: matrix of size m+1 x n\r\n- `v::Array{Float64,1}`: vector of size m\r\n- `u::Array{Float64,1}`: vector of size m\r\n\r\n\"\"\"\r\nfunction allocate_matrices(A)\r\n    (m,n) = size(A)\r\n\r\n    if m < n \r\n        error(\"m must be greater or equal than n\")\r\n    end\r\n    \r\n    QR = zeros(m+1,n)\r\n    v = zeros(m)\r\n    u = zeros(m)\r\n    return QR,v,u\r\nend\r\n\r\n\r\n\"\"\"\r\nPerforms QR factorization of A\r\n\r\n# Arguments\r\n- `A::Array{Float64,2}`: matrix of size m x n such that m < n.\r\n- `QR::Array{Float64,2}`: matrix of size m+1 x n. The result of the factorization is stored in QR such that:\r\n    - the upper triangular part contains R. Therefore, R = triu(QR)[1:n,:]\r\n    - the sub-diagonal part contains the reflectors v. Hence, V = tril(QR,-1)[2:n+1,:]\r\n- `v::Array{Float64,1}`: vector of size m\r\n- `u::Array{Float64,1}`: vector of size m\r\n\"\"\"\r\nfunction qr_factorization!(A, QR::Array{Float64,2}, v::Array{Float64,1}, u::Array{Float64,1} )\r\n    (m,n) = size(A)\r\n\r\n    #copying elements of A in R\r\n    for j = 1 : n\r\n        for i = 1 : m\r\n            QR[i,j] = A[i,j]\r\n        end\r\n    end\r\n\r\n    #Total Complexity: O(n(3m + 2mn)) = O(3nm + 2mn^2) = O(2n^2m) + O(nm)\r\n    @inbounds @views for j = 1 : min(m-1,n)\r\n\r\n        #copying j-th column of R into v\r\n        #Complexity: O(m)\r\n        for i = 1 : m\r\n            v[i] = i < j ? 0 : QR[i,j]\r\n        end\r\n\r\n        #calculating householders\r\n        s = norm(v)\r\n            \r\n        if v[j] >= 0\r\n            s = -s\r\n        end\r\n        \r\n        v[j] = v[j] - s\r\n\r\n        norm_v = norm(v)\r\n\r\n        #Complexity: O(m)\r\n        @. v = v/norm_v\r\n\r\n        #calculating R\r\n        # R = R - 2v*(v'*R)\r\n\r\n        t = j+1\r\n            \r\n        QR[j,j] = s\r\n        @. QR[t:m, j] = 0\r\n\r\n        #Complexity: O(mn)\r\n        u[t:n]' .= v[j:m]' * QR[j:m, t:n]\r\n        \r\n        #Complexity: O(mn)\r\n        @. QR[j:m, t:n] = QR[j:m, t:n] - (2*v[j:m])*u[t:n]'\r\n\r\n        #copying householder reflector into QR matrix\r\n        @. QR[j+1:m+1, j] = v[j : m]\r\n    end\r\n\r\n    #if m== n then QR[m+1,n]=0\r\n    if m == n\r\n        QR[m+1,n] = 0.0\r\n    end\r\n\r\nend\r\n\r\n\"\"\"\r\nPerforms Q^t * A and stores the result in W (Q^t is Q transposed)\r\n\r\n# Arguments\r\n- `QR::Array{Float64,2}`: matrix of size m+1 x n. The result of the factorization is stored in QR such that:\r\n    - the upper triangular part contains R. Therefore, R = triu(QR)[1:n,:]\r\n    - the sub-diagonal part contains the reflectors v. Hence, V = tril(QR,-1)[2:n+1,:]\r\n- `A::Array{Float64,2}`: matrix of size m x n.\r\n- `W::Array{Float64,2}`:matrix of size m x n in which the result is stored.\r\n\"\"\"\r\nfunction Q_t_times_A!(QR,A,W)\r\n    #Taking householder vectors\r\n    @views V = tril(QR, -1)[2:end,:]\r\n    (m,n) = size(V)\r\n\r\n    W .= 0\r\n    W .= A .- 2 .* V[:,1] .* (V[:,1]'*A)\r\n\r\n    #Complexity: O(mn^2)\r\n    num_iteration = n\r\n    if V[m,n] == 0.0\r\n        num_iteration -= 1\r\n    end\r\n\r\n    for j = 2:num_iteration\r\n        W .= W .- 2 .* V[:,j] .* (V[:,j]'*W)\r\n    end\r\nend\r\n\r\n\"\"\"\r\nGiven the QR factorization returns the Q factor\r\n\r\n# Arguments\r\n- `QR::Array{Float64,2}`: matrix of size m+1 x n. The result of the factorization is stored in QR such that:\r\n    - the upper triangular part contains R. Therefore, R = triu(QR)[1:n,:]\r\n    - the sub-diagonal part contains the reflectors v. Hence, V = tril(QR,-1)[2:n+1,:]\r\n- `Q::Array{Float64,2}`:matrix of size m x n in which the result is stored.\r\n\"\"\"\r\nfunction get_Q!(QR, Q)\r\n    @views V = tril(QR, -1)[2:end,:]\r\n    (m,n) = size(V)\r\n\r\n    #initialize Q\r\n    @views @inbounds Q .= (I - 2 .* V[:,n] .* V[:,n]')[:,1:n]\r\n    \r\n    @views @inbounds for j in n-1:-1:1\r\n        Q[j:end,j:end] .= (I - 2 .* V[:,j] .* V[:,j]')[j:end,j:end] * Q[j:end,j:end] \r\n    end\r\nend", "meta": {"hexsha": "7588c54eeafad05f12c51903d00896750a5aa523", "size": 3930, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "qr_factorization.jl", "max_stars_repo_name": "MazzeiM/Alternating-Least-Square-With-QR", "max_stars_repo_head_hexsha": "8d3494c78d36496a435b259d6affcfefe2247d9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qr_factorization.jl", "max_issues_repo_name": "MazzeiM/Alternating-Least-Square-With-QR", "max_issues_repo_head_hexsha": "8d3494c78d36496a435b259d6affcfefe2247d9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qr_factorization.jl", "max_forks_repo_name": "MazzeiM/Alternating-Least-Square-With-QR", "max_forks_repo_head_hexsha": "8d3494c78d36496a435b259d6affcfefe2247d9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2, "max_line_length": 109, "alphanum_fraction": 0.5178117048, "num_tokens": 1336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7924384386719167}}
{"text": "export distance\n\n\"\"\"\n    distance(H1::AbstractHyperrectangle{N}, H2::AbstractHyperrectangle{N};\n             p::Real=2) where {N<:Real}\n\nCompute the standard distance between two hyperrectangular sets, defined as\n\n```math\n    \\\\inf_{x \\\\in H_1, y \\\\in H_2} \\\\{ d(x, y) \\\\}.\n```\n\n### Input\n\n- `H1` -- hyperrectangular set\n- `H2` -- hyperrectangular set\n- `p`  -- (optional; default: `2`) value of the ``p``-norm\n\n### Output\n\nThe distance, which is zero if the sets intersect and otherwise the ``p``-norm\nof the shortest line segment between any pair of points.\n\n### Notes\n\nSee also [`hausdorff_distance`](@ref) for an alternative distance notion.\n\"\"\"\nfunction distance(H1::AbstractHyperrectangle{N},\n                  H2::AbstractHyperrectangle{N};\n                  p::Real=2) where {N<:Real}\n    n = dim(H1)\n    @assert n == dim(H2) \"incompatible set dimensions $n and $(dim(H2))\"\n\n    d = Vector{N}(undef, n)\n    @inbounds for i in 1:n\n        # find relative position in dimension i\n        # (if c1 == c2, the results are equivalent independent of the branch)\n        if center(H1, i) >= center(H2, i)\n            lhs = low(H1, i)\n            rhs = high(H2, i)\n        else\n            lhs = low(H2, i)\n            rhs = high(H1, i)\n        end\n        if _leq(lhs, rhs)\n            d[i] = zero(N)\n        else\n            d[i] = rhs - lhs\n        end\n    end\n    return norm(d, p)\nend\n", "meta": {"hexsha": "33d9a36cbe052b0c960e721df354b40ba95a9682", "size": 1390, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Approximations/distance.jl", "max_stars_repo_name": "yupbank/LazySets.jl", "max_stars_repo_head_hexsha": "55528b6458f84bb7fe19b6e868e5e11cc008e684", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-15T03:15:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-15T03:18:05.000Z", "max_issues_repo_path": "src/Approximations/distance.jl", "max_issues_repo_name": "KennyKangMPC/LazySets.jl", "max_issues_repo_head_hexsha": "29aeb96d9b417cb3157f2b2aa3f46c79a8f96c18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Approximations/distance.jl", "max_forks_repo_name": "KennyKangMPC/LazySets.jl", "max_forks_repo_head_hexsha": "29aeb96d9b417cb3157f2b2aa3f46c79a8f96c18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2264150943, "max_line_length": 78, "alphanum_fraction": 0.5712230216, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222396, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7924384376352015}}
{"text": "\"\"\"\n    ilc_weights(cij)\n\nThis function returns weights (a vector of the number of frequency channels) of the ILC method.\n\n*Reference*: Equation (12) of Tegmark et al., Phys. Rev. D, 68, 123523 (2003)\n\n# Arguments\n- `cij::Array{<:AbstractFloat,2}`: symmetric covariance matrix with the dimention of `(nν, nν)` where `nν` is the number of frequency bands.\n\"\"\"\nfunction ilc_weights(cij::Array{<:AbstractFloat,2})\n    if size(cij)[1] ≠ size(cij)[2]\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    else\n        M = Symmetric(cij)\n    end\n    nν = size(cij)[1]\n    e = ones(nν) # e = [1,...,1]\n    x = M \\ e\n    w = x / e'x  # ILC weights\nend\n\n\"\"\"\n    ilc_weights(cij, e)\n\nThis function returns weights (a vector of the number of frequency channels) of the ILC method.\n\n*Reference*: Equation (12) of Tegmark et al., Phys. Rev. D, 68, 123523 (2003)\n\n# Arguments\n- `cij::Array{<:AbstractFloat,2}`: symmetric covariance matrix with the dimention of `(nν, nν)` where `nν` is the number of frequency bands.\n- `e::Array{<:AbstractFloat,1}`: vector of the frequency response. E.g., `e = [1,...,1]` for CMB.\n\"\"\"\nfunction ilc_weights(cij::Array{T,2}, e::Array{T,1}) where {T<:AbstractFloat}\n    if size(cij)[1] ≠ size(cij)[2]\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    elseif size(cij)[1] ≠ length(e)\n        throw(DimensionMismatch(\"dimensions of the covariance matrix and the frequency response vector do not match\"))\n    else\n        M = Symmetric(cij)\n    end\n    x = M \\ e\n    w = x / e'x  # ILC weights\nend\n\n\"\"\"\n    ilc_weights(cijℓ[, ℓid=3])\n\nThis function returns weights (a `nν`-by-`nℓ` matrix) of the ILC method.\n\nHere, `nν` is the number of frequency channels and `nℓ` is the number of elements in the relevant domain, e.g., multipoles, band-power bins, pixels, etc.\n\n*Reference*: Equation (12) of Tegmark et al., Phys. Rev. D, 68, 123523 (2003)\n\n# Arguments\n- `cijℓ::Array{<:AbstractFloat,3}`: symmetric covariance matrix with the dimention of `(nℓ, nν, nν)`, `(nν, nℓ, nν)` or `(nν, nν, nℓ)` (default).\n\n# Optional Arguments\n- `ℓid::Integer=3`: location of the index for the `nℓ` domain. `ℓid=1` if `cijℓ[nℓ,nν,nν]`, `ℓid=2` if `cijℓ[nν,nℓ,nν]`, and `ℓid=3` (the default value) if `cijℓ[nν,nν,nℓ]`.\n\"\"\"\nfunction ilc_weights(\n    cijℓ::Array{<:AbstractFloat,3},\n    ℓid::Integer = 3,\n)\n    if ℓid > 3 || ℓid < 1\n        throw(DomainError(ℓid, \"ℓid must be 1, 2, or 3\"))\n    end\n    if (ℓid == 3 && size(cijℓ)[1] ≠ size(cijℓ)[2]) ||\n       (ℓid == 2 && size(cijℓ)[1] ≠ size(cijℓ)[3]) ||\n       (ℓid == 1 && size(cijℓ)[2] ≠ size(cijℓ)[3])\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    end\n    nℓ = size(cijℓ)[ℓid]\n    nν = ifelse(ℓid == 3, size(cijℓ)[1], size(cijℓ)[3])\n    e = ones(nν)      # e = [1,...,1]\n    wℓ = zeros(nν, nℓ) # ILC weights\n    for iℓ = 1:nℓ\n        if ℓid == 3\n            M = Symmetric(cijℓ[:, :, iℓ])\n        elseif ℓid == 2\n            M = Symmetric(cijℓ[:, iℓ, :])\n        else\n            M = Symmetric(cijℓ[iℓ, :, :])\n        end\n        x = M \\ e\n        wℓ[:, iℓ] = x / e'x\n    end\n    return wℓ\nend\n\n\"\"\"\n    ilc_weights(cijℓ, e[, ℓid=3])\n\nThis function returns weights (a `nν`-by-`nℓ` matrix) of the ILC method.\n\nHere, `nν` is the number of frequency channels and `nℓ` is the number of elements in the relevant domain, e.g., multipoles, band-power bins, pixels, etc.\n\n*Reference*: Equation (12) of Tegmark et al., Phys. Rev. D, 68, 123523 (2003)\n\n# Arguments\n- `cijℓ::Array{<:AbstractFloat,3}`: symmetric covariance matrix with the dimention of `(nℓ, nν, nν)`, `(nν, nℓ, nν)` or `(nν, nν, nℓ)` (default).\n- `e::Array{<:AbstractFloat,1}`: vector of the frequency response. E.g., `e = [1,...,1]` for CMB.\n\n# Optional Arguments\n- `ℓid::Integer=3`: location of the index for the `nℓ` domain. `ℓid=1` if `cijℓ[nℓ,nν,nν]`, `ℓid=2` if `cijℓ[nν,nℓ,nν]`, and `ℓid=3` (the default value) if `cijℓ[nν,nν,nℓ]`.\n\"\"\"\nfunction ilc_weights(\n    cijℓ::Array{T,3},\n    e::Array{T,1},\n    ℓid::Integer = 3,\n) where {T<:AbstractFloat}\n    if ℓid > 3 || ℓid < 1\n        throw(DomainError(ℓid, \"ℓid must be 1, 2, or 3\"))\n    end\n    if (ℓid == 3 && size(cijℓ)[1] ≠ size(cijℓ)[2]) ||\n       (ℓid == 2 && size(cijℓ)[1] ≠ size(cijℓ)[3]) ||\n       (ℓid == 1 && size(cijℓ)[2] ≠ size(cijℓ)[3])\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    end\n    nℓ = size(cijℓ)[ℓid]\n    nν = ifelse(ℓid == 3, size(cijℓ)[1], size(cijℓ)[3])\n    if length(e) ≠ nν\n        throw(DimensionMismatch(\"dimensions of the covariance matrix and the frequency response vector do not match\"))\n    end\n    wℓ = zeros(nν, nℓ) # ILC weights\n    for iℓ = 1:nℓ\n        if ℓid == 3\n            M = Symmetric(cijℓ[:, :, iℓ])\n        elseif ℓid == 2\n            M = Symmetric(cijℓ[:, iℓ, :])\n        else\n            M = Symmetric(cijℓ[iℓ, :, :])\n        end\n        x = M \\ e\n        wℓ[:, iℓ] = x / e'x\n    end\n    return wℓ\nend\n\n\"\"\"\n    ilc_clean_cij(cij, w)\n\nThis function returns power of the extracted component for a given element of the relevant domain, e.g., multipole, band-power bin, pixel, etc.\n\n*Reference*: Tegmark et al., Phys. Rev. D, 68, 123523 (2003)\n\n# Arguments\n- `cij::Array{<:AbstractFloat,2}`: symmetric covariance matrix with the dimention of `(nν, nν)` where `nν` is the number of frequency bands.\n- `w::Array{<:AbstractFloat,1}`: ILC weights.\n\"\"\"\nfunction ilc_clean_cij(cij::Array{T,2}, w::Array{T,1}) where {T<:AbstractFloat}\n    if size(cij)[1] ≠ size(cij)[2]\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    elseif size(cij)[1] ≠ length(w)\n        throw(DimensionMismatch(\"dimensions of the covariance matrix and the ILC weight do not match\"))\n    else\n        M = Symmetric(cij)\n    end\n    cl = w' * M * w\nend\n\n\"\"\"\n    ilc_clean_cij(cijℓ, wℓ[, ℓid::Integer=3])\n\n\nThis function returns a vector of the power of the extracted component, with elements in the relevant domain, e.g., multipole, band-power bin, pixel, etc.\n\n*Reference*: Tegmark et al., Phys. Rev. D, 68, 123523 (2003)\n\n# Arguments\n- `cijℓ::Array{<:AbstractFloat,3}`: symmetric covariance matrix with the dimention of `(nℓ, nν, nν)`, `(nν, nℓ, nν)` or `(nν, nν, nℓ)` (default).\n- `wℓ::Array{<:AbstractFloat,2}`: ILC weights (a `nν`-by-`nℓ` matrix).\n    - Here, `nν` is the number of frequency bands and `nℓ` is the number of elements in the relevant domain.\n\n# Optional Arguments\n- `ℓid::Integer=3`: location of the index for the `nℓ` domain. `ℓid=1` if `cijℓ[nℓ,nν,nν]`, `ℓid=2` if `cijℓ[nν,nℓ,nν]`, and `ℓid=3` (the default value) if `cijℓ[nν,nν,nℓ]`.\n\"\"\"\nfunction ilc_clean_cij(\n    cijℓ::Array{T,3},\n    wℓ::Array{T,2},\n    ℓid::Integer = 3,\n) where {T<:AbstractFloat}\n    if ℓid > 3 || ℓid < 1\n        throw(DomainError(ℓid, \"ℓid must be 1, 2, or 3\"))\n    end\n    if (ℓid == 3 && size(cijℓ)[1] ≠ size(cijℓ)[2]) ||\n       (ℓid == 2 && size(cijℓ)[1] ≠ size(cijℓ)[3]) ||\n       (ℓid == 1 && size(cijℓ)[2] ≠ size(cijℓ)[3])\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    end\n    nℓ = size(cijℓ)[ℓid]\n    nν = ifelse(ℓid == 3, size(cijℓ)[1], size(cijℓ)[3])\n    if nℓ ≠ size(wℓ)[2] || nν ≠ size(wℓ)[1]\n        throw(DimensionMismatch(\"dimensions of the covariance matrix and the ILC weight do not match\"))\n    end\n    cl = zeros(nℓ)\n    for iℓ = 1:nℓ\n        if ℓid == 3\n            M = Symmetric(cijℓ[:, :, iℓ])\n        elseif ℓid == 2\n            M = Symmetric(cijℓ[:, iℓ, :])\n        else\n            M = Symmetric(cijℓ[iℓ, :, :])\n        end\n        cl[iℓ] = wℓ[:, iℓ]' * M * wℓ[:, iℓ]\n    end\n    return cl\nend\n", "meta": {"hexsha": "659a6d83fc8dc4492915ed5a802575ab0390304e", "size": 7583, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ilc.jl", "max_stars_repo_name": "komatsu5147/CleanCMB.jl", "max_stars_repo_head_hexsha": "d44d5731f01047b6d02293cfb1b96d97b9c3e003", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-06-22T14:41:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-23T20:05:14.000Z", "max_issues_repo_path": "src/ilc.jl", "max_issues_repo_name": "komatsu5147/CleanCMB.jl", "max_issues_repo_head_hexsha": "d44d5731f01047b6d02293cfb1b96d97b9c3e003", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ilc.jl", "max_forks_repo_name": "komatsu5147/CleanCMB.jl", "max_forks_repo_head_hexsha": "d44d5731f01047b6d02293cfb1b96d97b9c3e003", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-03T15:17:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T15:17:51.000Z", "avg_line_length": 36.2822966507, "max_line_length": 173, "alphanum_fraction": 0.6013451141, "num_tokens": 2826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574668, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7924344543544369}}
{"text": "\"\"\"\r\n    reglin(X,Y)\r\n\r\nadalah fungsi untuk mencari garis linear dari variabel dependen `Y` dan\r\nindependen `X` dengan persamaan `y=Ax+B`.\r\n\r\n# Example\r\n```jldoctest\r\njulia> x = [-1, 0, 1, 2, 3, 4, 5, 6];\r\n\r\njulia> y = [10, 9, 7, 5, 4, 3, 0, -1];\r\n\r\njulia> A,B = reglin(x,y)\r\n(-1.6071428571428572, 8.642857142857142)\r\n```\r\nreturn nilai koefisien `A` dan `B`.\r\n\"\"\"\r\nfunction reglin(X,Y)\r\n    xmean = mean(X);\r\n    ymean = mean(Y);\r\n    # Hitung nilai jumlah dari xy dan x^2\r\n    sumxy = (X.-xmean)'*(Y.-ymean)\r\n    sumx2 = (X.-xmean)'*(X.-xmean)\r\n    # Hitung nilau koefisien garis regresi linear Y=Ax+B\r\n    A = sumxy/sumx2;\r\n    B = ymean .- A*xmean;\r\n    return A,B\r\nend\r\n", "meta": {"hexsha": "1ca0356cacf59f067b180df445d98a0a14a07fea", "size": 674, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/reglin.jl", "max_stars_repo_name": "mkhoirun-najiboi/metnum.jl", "max_stars_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/reglin.jl", "max_issues_repo_name": "mkhoirun-najiboi/metnum.jl", "max_issues_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/reglin.jl", "max_forks_repo_name": "mkhoirun-najiboi/metnum.jl", "max_forks_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2413793103, "max_line_length": 72, "alphanum_fraction": 0.5771513353, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.8267118026095992, "lm_q1q2_score": 0.7924344504376807}}
{"text": "\"\"\"\n    evalbezier(control, t)\n\nEvaluate a Bezier curve using Horner's method.\n\"\"\"\nfunction evalbezier(control::AbstractArray{T,2}, t::T) where {T<:AbstractFloat}\n    # Horner's method\n    tᶜ = 1.0 - t\n    tᵢ = 1.0\n    cᵢ = 1.0\n    bᵢ = control[:, 1]*tᶜ\n    n = size(control, 2) - 1\n    for i in 1:n-1\n        tᵢ = tᵢ*t\n        cᵢ = (n-i+1)*cᵢ/i\n        bᵢ = (bᵢ+ cᵢ*control[:, i+1]*tᵢ)*tᶜ\n    end\n    bᵢ + control[:, n+1]*tᵢ*t\nend\n\n\"\"\"\n    evalbezier(control, tvec)\n\nEvaluate along at array of time instants.\n\"\"\"\nfunction evalbezier(control::AbstractArray{T,2}, tvec::AbstractArray{T, 1}) where {T<:AbstractFloat}\n    # TODO Just a hack (only really meant for viz)\n    p = zeros(size(control, 1), size(tvec, 1))\n    for (i,t) in enumerate(tvec)\n        p[:,i] = evalbezier(control, t)\n    end\n    p\nend\n", "meta": {"hexsha": "9b5b20e031fcc8fa50917fe38d7a947177f2eb14", "size": 804, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/evalbezier.jl", "max_stars_repo_name": "arlk/Bezier.jl", "max_stars_repo_head_hexsha": "308e376c83bd419870083df4b1891e994c712dc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-07T00:00:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-07T00:00:42.000Z", "max_issues_repo_path": "src/evalbezier.jl", "max_issues_repo_name": "arlk/Bezier.jl", "max_issues_repo_head_hexsha": "308e376c83bd419870083df4b1891e994c712dc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/evalbezier.jl", "max_forks_repo_name": "arlk/Bezier.jl", "max_forks_repo_head_hexsha": "308e376c83bd419870083df4b1891e994c712dc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6470588235, "max_line_length": 100, "alphanum_fraction": 0.5858208955, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7923369732139224}}
{"text": "# ==============================================================================\n# Five-dimensional system\n#\n# Example from Althoff's thesis, Section 3.2.3\n#\n#\n# system type: continuous LTI system\n# state dimension: 5\n# input dimension: 1\n#\n# This five-dimensional system is taken from Example 4.1 in [1].\n#\n# [1] Colas Le Guernic: Reachability analysis of hybrid systems with linear\n#     continuous dynamics. PhD thesis, 2009.\n# ==============================================================================\n\nfunction linear5D_homog()\n    A = Float64[-1 -4   0   0   0;\n                 4 -1   0   0   0;\n                 0  0  -3   1   0;\n                 0  0  -1  -3   0;\n                 0  0   0   0  -2]\n    X0 = Hyperrectangle(low=fill(0.9, 5), high=fill(1.1, 5))\n    prob = @ivp(x' = Ax, x(0) ∈ X0)\n    tspan = (0.0, 5.0)\n    return prob, tspan\nend\n\nfunction linear5D()\n    # system matrix\n    D = [-1.0 -4.0  0.0  0.0  0.0;\n          4.0 -1.0  0.0  0.0  0.0;\n          0.0  0.0 -3.0  1.0  0.0;\n          0.0  0.0 -1.0 -3.0  0.0;\n          0.0  0.0  0.0  0.0 -2.0]\n    P = [ 0.6 -0.1  0.1  0.7 -0.2;\n         -0.5  0.7 -0.1 -0.8  0.0;\n          0.9 -0.5  0.3 -0.6  0.1;\n          0.5 -0.7  0.5  0.6  0.3;\n          0.8  0.7  0.6 -0.3  0.2]\n    A = P * D * inv(P)\n    X = Universe(5) # state domain\n    U = Ball2(zeros(5), 0.01) # input domain\n\n    X0 = BallInf([1.0, 0.0, 0.0, 0.0, 0.0], 0.1)\n    prob = @ivp(x' = Ax + u, x ∈ X, u ∈ U, x(0) ∈ X0) # continuous LTI system\n    tspan = (0.0, 5.0)\n    return prob, tspan\nend\n", "meta": {"hexsha": "fe3cee832967c0bdb281f2c10c1d2cf79c1bb946", "size": 1531, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/models/linear5D.jl", "max_stars_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_stars_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2020-03-30T16:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:26:48.000Z", "max_issues_repo_path": "test/models/linear5D.jl", "max_issues_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_issues_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 258, "max_issues_repo_issues_event_min_datetime": "2020-03-30T14:13:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T17:07:04.000Z", "max_forks_repo_path": "test/models/linear5D.jl", "max_forks_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_forks_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-04-23T03:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T23:11:32.000Z", "avg_line_length": 30.62, "max_line_length": 80, "alphanum_fraction": 0.4291312867, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.8479677545357569, "lm_q1q2_score": 0.7923369631814305}}
{"text": "#some random matrices for testing\nmodule Randm\nexport randsym, randposdef, randstable, randnormal, randorth, randunitary\n\n#%  .. currentmodule:: Randm\n#%    \n\n#%  Module Randm\n#%  ------------\n#%  \n#%\n#%  Introduction\n#%  ~~~~~~~~~~~~\n#%\n\n#%  Random matrices for testing purposes. I did not figure out the actual distributions\n#%  the matrices are drawn from.\n#%  \n\n\n#%  Reference \n#%  ~~~~~~~~~\n#%  \n\n##%  .. function:: randsym(d)\n##%               \n##%  \tRandom symmetric matrix. Note: randsym\n##%  \t\n\n#function randsym(d)\n#\tx = 0.5*randn(d, d)\n#\tx' + x\n#end\n\n#%  .. function:: randposdef(d)\n#%               \n#%  \tRandom positive definite matrix of dimension ``d``.\n#%  \t\n\nfunction randposdef(d)\n\tx = randn(d, d) \n\tx'* x\nend\n\n#%  .. function:: randstable(d)\n#%               \n#%  \tRandom stable matrix (matrix with eigenvalues with negative real part) with\n#%  \tdimension ``d``.\n\n\nfunction randstable(d)\n\t# positive definite matrix\n\tx = randn(d, d) \n\ta = x'*x \n\t\n\t# anti symmetric matrix\n\tabove_diag =\t[ i<j ? 1 : 0 for i in 1:d, j in 1:d] # nonzero pattern for above diagonal\n\ty = randn(d, d) \n\tb = above_diag.*y - above_diag'.*y' \n\t\n\t# return stable matrix\n\tb - a\nend\n\n#%  .. function:: randunitary(d)\n#%               \n#%  \tRandom unitary matrix of dimension ``d``.\n#%  \t\n\nrandunitary(d) = expm(im* randposdef(d))\n\n#%  .. function:: randorth(d)\n#%               \n#%  \tOrthogonal matrix drawn according to the Haar measure on the group of orthogonal matrices.\n#%  \t\n\nrandorth(d) = qr(randn(d,d))[1]\n\n#%  .. function:: randnormal(d) \n#%               \n#%  \tRandom normal matrix.\n#%  \t\n\n\nfunction tridiag(di, u, l)\n\tassert(length(di) -1 == length(u) == length(l))\n\tM = diagm(di)\n\tfor i in 1:length(u)\n\t  M[i,i+1] = l[i]\n  \t  M[i+1,i] = u[i]\n\tend\n\tM\n\t\nend\ntridiag(alpha, beta) = tridiag(alpha, beta, -beta)\n\n\nfunction randnormal(d) \n\tQ = randorth(d)\n\tB = schur(randn(d,d))[1] #same eigenvalues as a randn(d,d)\n\tm = d\n\talpha = zeros(d)\n\tbeta = zeros(d-1)\n\twhile m > 1\n\t   s = abs(B[m-1,m-1]) + abs(B[m,m])\n\t   if s + abs(B[m,m-1]) > s # if significant offdiagonal value: evaluate submatrix m-1:m;\n\t\tspur = B[m,m] + B[m-1,m-1]\n\t\tdis2 = abs2(B[m,m]- B[m-1,m-1]) + 4.0*B[m,m-1]*B[m-1,m] # = spur^2 - 4det\n\t\talpha[m] = alpha[m-1] = 0.5*spur\n\t\t\n\t\tbeta[m-1] = 0.5*sqrt(-dis2)\n\t\tm -= 2       \n\t   else\n\t        alpha[m] = B[m,m]\n\t        beta[m-1] = 0\n\t        m -= 1        \n\t   end\n\t   \n\tend\n\tif (m == 1) \n\t\talpha[1] = B[1,1]\n\tend\n\t\n\tQ' * tridiag(alpha, beta) * Q\n\t#tridiag(alpha, beta)\n\t\nend\n\nend #module\n", "meta": {"hexsha": "eaa7636172252ad66892dcba26263794fab17e34", "size": 2502, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Randm.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SDE.jl-0d6d677f-8475-5ebf-bbf8-769304748c2b", "max_stars_repo_head_hexsha": "b08ea02c5de06fb7a41aee29f5d41b921878e2d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-04-09T16:37:49.000Z", "max_stars_repo_stars_event_max_datetime": "2015-04-09T16:37:49.000Z", "max_issues_repo_path": "src/Randm.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SDE.jl-0d6d677f-8475-5ebf-bbf8-769304748c2b", "max_issues_repo_head_hexsha": "b08ea02c5de06fb7a41aee29f5d41b921878e2d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-07-21T14:56:10.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:32:41.000Z", "max_forks_repo_path": "src/Randm.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SDE.jl-0d6d677f-8475-5ebf-bbf8-769304748c2b", "max_forks_repo_head_hexsha": "b08ea02c5de06fb7a41aee29f5d41b921878e2d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:16:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:48:05.000Z", "avg_line_length": 19.2461538462, "max_line_length": 95, "alphanum_fraction": 0.5555555556, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7923369616322716}}
{"text": "module Functions \n\n#=\ntwo-variable function\nx = 5.90133\ny = 0.5\nfmin = -43.3159 \n-30 <= x, y <= 30\n=#\nfunction chichinadze(pars)\n    @assert(length(pars) == 2)\n    x = pars[1]\n    y = pars[2]\n    return x^2 - 12.0x + 11.0 + 10.0 * cos(pi * x / 2.0) + 8.0 * sin(5 * pi * x) -\n           (1 / sqrt(5)) * exp(-0.5 * (y - 0.5)^2)\nend\n\n\n#=\nn-variable function\nx = [1, 1, ..., 1]\nfmin = 0\n-10 <= x_i <= 10\n=#\nfunction levy(pars)\n    d = length(pars)\n\n    w = zeros(Float64, d)\n\n    for ii = 1:d\n        w[ii] = 1 + (pars[ii] - 1.0) / 4.0\n    end\n\n    term1 = (sin(pi * w[1]))^2\n    term3 = (w[d] - 1)^2.0 * (1 + (sin(2.0 * pi * w[d]))^2.0)\n\n    sum = 0\n    for ii = 1:(d-1)\n        wi = w[ii]\n        new = (wi - 1)^2 * (1 + 10 * (sin(pi * wi + 1))^2)\n        sum = sum + new\n    end\n\n    return term1 + sum + term3\nend\n\n\n#=\nn-variable function\nx = [0, 0, ..., 0]\nfmin = 0\n-32.768 <= x_i <= 32.768\n=#\nfunction ackley(xx)\n    d = length(xx)\n    a = 20\n    b = 0.2\n    c = 2 * pi\n  \n    sum1 = 0\n    for i in 1:d\n        sum1 = sum1 + xx[i]^2\n    end\n\n    sum2 = 0\n    for i in 1:d\n        sum2 = sum2 + cos(c * xx[i])\n    end\n  \n    term1 = -a * exp(-b*sqrt(sum1/d))\n    term2 = -exp(sum2/d)\n  \n    y = term1 + term2 + a + exp(1)\n\n    return(y)\nend\n\n\nend \n\n", "meta": {"hexsha": "3c4620eac87ef45fd610e3b7b330a0d4d307a42e", "size": 1250, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/funcset.jl", "max_stars_repo_name": "jbytecode/MCCGA", "max_stars_repo_head_hexsha": "313a54c9427ca08757b5d4f651027b46f7cb4843", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/funcset.jl", "max_issues_repo_name": "jbytecode/MCCGA", "max_issues_repo_head_hexsha": "313a54c9427ca08757b5d4f651027b46f7cb4843", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/funcset.jl", "max_forks_repo_name": "jbytecode/MCCGA", "max_forks_repo_head_hexsha": "313a54c9427ca08757b5d4f651027b46f7cb4843", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.4320987654, "max_line_length": 82, "alphanum_fraction": 0.4496, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464604, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.7923079302057827}}
{"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    ∠(A, B, C)\n\nAngle ∠ABC between rays BA and BC.\nSee https://en.wikipedia.org/wiki/Angle.\n\nUses the two-argument form of `atan` returning value in range [-π, π].\nSee https://en.wikipedia.org/wiki/Atan2.\n\n## Examples\n\n```julia\n∠(Point(1,0), Point(0,0), Point(0,1)) == π/2\n```\n\"\"\"\n∠(A::P, B::P, C::P) where {P<:Point{2}} = ∠(A-B, C-B)\n∠(A::P, B::P, C::P) where {P<:Point{3}} = ∠(A-B, C-B)\n\n\"\"\"\n    ∠(u, v)\n\nAngle between vectors u and v.\nSee https://en.wikipedia.org/wiki/Angle.\n\nUses the two-argument form of `atan` returning value in range [-π, π].\nSee https://en.wikipedia.org/wiki/Atan2.\n\n## Examples\n\n```julia\n∠(Vec(1,0), Vec(0,1)) == π/2\n```\n\"\"\"\n∠(u::V, v::V) where {V<:Vec{2}} = atan(u × v, u ⋅ v)  # preserve sign\n∠(u::V, v::V) where {V<:Vec{3}} = atan(norm(u × v), u ⋅ v)  # discard sign\n", "meta": {"hexsha": "e8ffdb4e1124556deb833f226dbfa4dbc4073333", "size": 1007, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/angles.jl", "max_stars_repo_name": "deltaeecs/Meshes.jl", "max_stars_repo_head_hexsha": "f2041f726c07c489583976944558498082a048cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/angles.jl", "max_issues_repo_name": "deltaeecs/Meshes.jl", "max_issues_repo_head_hexsha": "f2041f726c07c489583976944558498082a048cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/angles.jl", "max_forks_repo_name": "deltaeecs/Meshes.jl", "max_forks_repo_head_hexsha": "f2041f726c07c489583976944558498082a048cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.175, "max_line_length": 74, "alphanum_fraction": 0.5054617676, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013549, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7923079204509168}}
{"text": "# Uncomment below if the package is not already installed\n#using Pkg; Pkg.add(\"NBInclude\") \n\n# Import code from previous section\nusing NBInclude\n@nbinclude(\"Graph_Code.ipynb\");\n\nfunction dfs(g::Graph, start)\n    visited = falses(length(g.vertices))\n    function visit(ivertex)\n        visited[ivertex] = true\n        println(\"Visiting vertex #$ivertex\")\n        for nb in g.vertices[ivertex].neighbors\n            if !visited[nb]\n                visit(nb)\n            end\n        end\n    end\n    visit(start)\n    return nothing\nend\n\nplot_graph(g)\n\ndfs(g,1) \n\nfunction find_path_dfs(g::Graph, start, finish)\n    visited = falses(length(g.vertices))\n    path = Int64[]\n    function visit(ivertex)\n        visited[ivertex] = true\n        if ivertex == finish\n            pushfirst!(path, ivertex)\n            return true\n        end\n        for nb in g.vertices[ivertex].neighbors\n            if !visited[nb]\n                if visit(nb)\n                    pushfirst!(path, ivertex)\n                    return true\n                end\n            end\n        end\n        return false\n    end\n    visit(start)\n    return path\nend\n\nfunction plot_path(g, path)\n    xypath = [v.coordinates for v in g.vertices][path]\n    plot(first.(xypath), last.(xypath), color=\"red\", linewidth=2)\nend\n\nplot_graph(g)\npath = find_path_dfs(g, 10, 5)\nplot_path(g, path)\nprintln(\"Path from 10 to 5: $path\")\n\nfunction bfs(g::Graph, start)\n    visited = falses(length(g.vertices))\n    S = [start]\n    visited[start] = true\n    while !isempty(S)\n        ivertex = popfirst!(S)\n        println(\"Visiting vertex #$ivertex\")\n        for nb in g.vertices[ivertex].neighbors\n            if !visited[nb]\n                visited[nb] = true\n                push!(S, nb)\n            end\n        end\n    end\nend\n\nbfs(g,1)\n\nfunction shortest_path_bfs(g::Graph, start, finish)\n    parent = zeros(Int64, length(g.vertices))\n    S = [start]\n    parent[start] = start\n    while !isempty(S)\n        ivertex = popfirst!(S)\n        if ivertex == finish\n            break\n        end\n        for nb in g.vertices[ivertex].neighbors\n            if parent[nb] == 0 # Not visited yet\n                parent[nb] = ivertex\n                push!(S, nb)\n            end\n        end\n    end\n    # Build path\n    path = Int64[]\n    iv = finish\n    while true\n        pushfirst!(path, iv)\n        if iv == start\n            break\n        end\n        iv = parent[iv]\n    end\n    return path\nend\n\n\npath = shortest_path_bfs(g, 10, 5)\nplot_graph(g)\nplot_path(g, path)\nprintln(\"Shortest path from 10 to 5: $path\")\n\nfield = \"\"\"\n....O....\nO.O.O.O..\n..O...O.O\n.OOOOOO.O\n....OO..O\n.O...OOOO\n.O.......\n.OOOOOO..\n......O..\n......O..\n\"\"\"\nn = 10\n\nF = Int.(reverse(reshape(collect(field), n, n) .== 'O', dims=2))\n\ng1 = Graph([])\nnbr = 0\nfor j = 1:n\n    for i = 1:n\n        nbr += 1\n        nb = Int64[]\n        for dj = -1:1\n            for di = -1:1\n                if 1 ≤ i+di ≤ n && 1 ≤ j+dj ≤ n\n                    if F[i,j] == 0 && F[i+di,j+dj] == 0\n                        push!(nb, nbr + di + n*dj)\n                    end\n                end\n            end\n        end\n        v = Vertex(nb, coordinates=[i,j])\n        push!(g1.vertices, v)\n    end\nend\n\npath = shortest_path_bfs(g1, 6, 57)\nxypath = [v.coordinates for v in g1.vertices][path]\nplot_graph(g1, scale=0.5)\nplot(first.(xypath), last.(xypath), color=\"red\", linewidth=2)\n", "meta": {"hexsha": "afef90a8fd12227e2f72b48e0dd25129d5b3dd1f", "size": 3368, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Graphs/Graph_Algorithms.jl", "max_stars_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_stars_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "textbook/_build/jupyter_execute/content/Graphs/Graph_Algorithms.jl", "max_issues_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_issues_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "textbook/_build/jupyter_execute/content/Graphs/Graph_Algorithms.jl", "max_forks_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_forks_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0130718954, "max_line_length": 65, "alphanum_fraction": 0.5293942993, "num_tokens": 973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7923071836851646}}
{"text": "### A Pluto.jl notebook ###\n# v0.11.14\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 57f367d6-025a-11eb-182a-773094da4307\nusing Yao, YaoPlots #calling the Yao and YaoPlots package\n\n# ╔═╡ 3c9cf124-0257-11eb-16ce-0d857dce310f\nmd\"# Using Yao - The basics of quantum computing in Julia using Yao.jl\"\n\n# ╔═╡ 5d5644b2-0257-11eb-36e9-7f4803cb3558\nmd\"At the current moment, we don't have have quantum computers. How do we make quantum circuits then? Well, two things we can do right now are, simulate a few qubits or use the qubits created by corporates like IBM and D'Wave. Using Yao, we can simulate the qubits, without having a quantum computer\\(based on the known mathematical and physics rules\\), although the support to run your circuits on Yao using real qubits is coming to Yao soon.\"\n\n# ╔═╡ 0f7d5bdc-0258-11eb-05bb-074d1b38c551\nmd\"We can make a cicuit in Yao using *chain* function. For parameters we define the number of qubits and the operations we've to perform on them. Lets say we want to pass two qubits through two X gates. We do this by chain(number of qubits, operations). To use the X gate, we use the put() parameter. Run the cell below to see what happens.\"\n\n# ╔═╡ ee15c64e-025a-11eb-2158-bd9cbea5f262\nmd\" **\\#\\#** or single **#** sign mean comments in julia. It means that anything written after # or ## won't be read as a part of the program, in the line you used them.\"\n\n# ╔═╡ dcf63604-0258-11eb-1466-fb21170c2e1a\nlet\n\tcircuit = chain(2, put(1=>X), put(2=>X)); #define a variable \"circuit\" and \"put\" an X gate on the first qubit, and then put an X gate on the second qubit\n\tplot(circuit) #plot function, which takes a circuit for a parameter and prints the circuit diagram.\nend\n\n# ╔═╡ 841aa488-0259-11eb-351a-c1f1770b3a51\nmd\"Assume we have 5 qubits and we have to pass each through an X gate. We can use the *repeat\\(\\)* parameter to pass the given number of qubits through the same gate.\"\n\n# ╔═╡ af1aa2b4-0259-11eb-29fe-19ba9462deb9\nplot(chain(5, repeat(X,1:5))) #plot function takes a circuit, which repeats the X gate on the qubits 1:5 or from 1st qubit to 5th qubit\n\n# ╔═╡ 1efc3566-025a-11eb-2aae-fd953f22edfb\nmd\"What about the Y, Z and H gate? Figure that out yourself. The next cell is left for you to play around.\"\n\n# ╔═╡ 443afbfa-025a-11eb-03c6-e74bb5344e36\nlet\n\t##circuit = \n\t##plot(circuit)\nend\n\n# ╔═╡ 686ec0a0-025b-11eb-339e-1158d9b25529\nmd\"What about multiqubit gates? We can use the control gate in Yao using the control\\( \\) parameter.\" \n\n# ╔═╡ 22f24af0-025c-11eb-23d3-b9945bc05a36\nplot(chain(2, control(1, 2=>X))) #Which translates to if the state of the 1st qubit is |1>, perform X gate to the 2nd qubit or \"put\" the 2nd qubit through the X gate.\n\n# ╔═╡ Cell order:\n# ╟─3c9cf124-0257-11eb-16ce-0d857dce310f\n# ╟─5d5644b2-0257-11eb-36e9-7f4803cb3558\n# ╟─0f7d5bdc-0258-11eb-05bb-074d1b38c551\n# ╟─ee15c64e-025a-11eb-2158-bd9cbea5f262\n# ╠═57f367d6-025a-11eb-182a-773094da4307\n# ╠═dcf63604-0258-11eb-1466-fb21170c2e1a\n# ╟─841aa488-0259-11eb-351a-c1f1770b3a51\n# ╠═af1aa2b4-0259-11eb-29fe-19ba9462deb9\n# ╟─1efc3566-025a-11eb-2aae-fd953f22edfb\n# ╠═443afbfa-025a-11eb-03c6-e74bb5344e36\n# ╟─686ec0a0-025b-11eb-339e-1158d9b25529\n# ╠═22f24af0-025c-11eb-23d3-b9945bc05a36\n", "meta": {"hexsha": "9330d49743ef426f5c1f0f3ef3586b0959e6d43c", "size": 3190, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Notebooks/p3.jl", "max_stars_repo_name": "logankilpatrick/tutorials", "max_stars_repo_head_hexsha": "d1f97b7e81ded47d541833f008b9fcb8872d310e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Notebooks/p3.jl", "max_issues_repo_name": "logankilpatrick/tutorials", "max_issues_repo_head_hexsha": "d1f97b7e81ded47d541833f008b9fcb8872d310e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notebooks/p3.jl", "max_forks_repo_name": "logankilpatrick/tutorials", "max_forks_repo_head_hexsha": "d1f97b7e81ded47d541833f008b9fcb8872d310e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-21T09:32:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-21T09:32:49.000Z", "avg_line_length": 51.4516129032, "max_line_length": 444, "alphanum_fraction": 0.7457680251, "num_tokens": 1265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7923071801529955}}
{"text": "immutable Uniform <: ContinuousUnivariateDistribution\n    a::Float64\n    b::Float64\n    function Uniform(a::Real, b::Real)\n\ta < b || error(\"a < b required for range [a, b]\")\n\tnew(float64(a), float64(b))\n    end\n    Uniform() = new(0.0, 1.0)\nend\n\n## Support\n@distr_support Uniform d.a d.b\n\n## Properties\nmean(d::Uniform) = (d.a + d.b) / 2.0\n\nmedian(d::Uniform) = (d.a + d.b) / 2.0\n\nmode(d::Uniform) = mean(d)\nmodes(d::Uniform) = Float64[]\n\nfunction var(d::Uniform)\n    w = d.b - d.a\n    w * w / 12.0\nend\n\nskewness(d::Uniform) = 0.0\nkurtosis(d::Uniform) = -1.2\n\nentropy(d::Uniform) = log(d.b - d.a)\n\n## Functions\npdf(d::Uniform, x::Float64) = insupport(d,x) ? 1/(d.b-d.a) : 0.0\nlogpdf(d::Uniform, x::Float64) = insupport(d,x) ? -log(d.b-d.a) : -Inf \n\nfunction cdf(d::Uniform, q::Float64) \n    if isnan(q)\n        return NaN\n    elseif q <= d.a\n        return 0.0\n    elseif q >= d.b\n        return 1.0\n    end\n    (q-d.a)/(d.b-d.a)\nend\nfunction ccdf(d::Uniform, q::Float64) \n    if isnan(q)\n        return NaN\n    elseif q <= d.a\n        return 1.0\n    elseif q >= d.b\n        return 0.0\n    end\n    (d.b-q)/(d.b-d.a)\nend\n\nquantile(d::Uniform, p::Float64) = @checkquantile p d.a+p*(d.b-d.a)\ncquantile(d::Uniform, p::Float64) = @checkquantile p d.b+p*(d.a-d.b)\n\n\nfunction mgf(d::Uniform, t::Real)\n    u = 0.5*(d.b-d.a)*t\n    u == zero(u) && return one(u)\n    v = 0.5*(d.a+d.b)*t\n    exp(v)*(sinh(u)/u)\nend\nfunction cf(d::Uniform, t::Real)\n    u = 0.5*(d.b-d.a)*t\n    u == zero(u) && return complex(one(u))\n    v = 0.5*(d.a+d.b)*t\n    exp(im*v)*(sin(u)/u)\nend\n\n## Sampling\nrand(d::Uniform) = d.a + (d.b - d.a) * rand()\n\n## Fitting\nfunction fit_mle{T <: Real}(::Type{Uniform}, x::Vector{T})\n    if isempty(x)\n        throw(ArgumentError(\"x cannot be empty.\"))\n    end\n\n    xmin = xmax = x[1]\n    for i = 2:length(x)\n        xi = x[i]\n        if xi < xmin\n            xmin = xi\n        elseif xi > xmax\n            xmax = xi\n        end\n    end\n\n    Uniform(xmin, xmax)\nend\n", "meta": {"hexsha": "d3dcb28424cf926a75d3b64518d068f44b6cab7a", "size": 1968, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/uniform.jl", "max_stars_repo_name": "davidanthoff/Distributions.jl", "max_stars_repo_head_hexsha": "75a04ebc12f3643392d33240a4029d458f86e7f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-11T18:43:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T18:43:39.000Z", "max_issues_repo_path": "src/univariate/continuous/uniform.jl", "max_issues_repo_name": "davidanthoff/Distributions.jl", "max_issues_repo_head_hexsha": "75a04ebc12f3643392d33240a4029d458f86e7f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/uniform.jl", "max_forks_repo_name": "davidanthoff/Distributions.jl", "max_forks_repo_head_hexsha": "75a04ebc12f3643392d33240a4029d458f86e7f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7157894737, "max_line_length": 71, "alphanum_fraction": 0.5447154472, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.8757869997529962, "lm_q1q2_score": 0.7922811869664483}}
{"text": "using Distributions, StatsBase, Plots, LaTeXStrings; pyplot()\n\nmu0, mu1, sd, tau  = 15, 18, 2, 17.5\ndist0, dist1 = Normal(mu0,sd), Normal(mu1,sd)\ngrid = 5:0.1:25\nh0grid, h1grid = tau:0.1:25, 5:0.1:tau\n\nprintln(\"Probability of Type I error: \", ccdf(dist0,tau))\nprintln(\"Probability of Type II error: \", cdf(dist1,tau))\n\nplot(grid, pdf.(dist0,grid),\n\tc=:blue, label=\"Bolt type 15g\")\nplot!(h0grid, pdf.(dist0, h0grid), \n\tc=:blue, fa=0.2, fillrange=[0 1], label=\"\")\nplot!(grid, pdf.(dist1,grid), \n\tc=:green, label=\"Bolt type 18g\")\nplot!(h1grid, pdf.(dist1, h1grid), \n\tc=:green, fa=0.2, fillrange=[0 1], label=\"\")\nplot!([tau, 25],[0,0],\n\tc=:red, lw=3, label=\"Rejection region\", \n\txlims=(5, 25), ylims=(0,0.25) , legend=:topleft,\n    xlabel=\"x\", ylabel=\"Density\")\nannotate!([(16, 0.02, text(L\"\\beta\")),(18.5, 0.02, text(L\"\\alpha\")),\n            (15, 0.21, text(L\"H_0\")),(18, 0.21, text(L\"H_1\"))])", "meta": {"hexsha": "500a008164f0efdb02de77807115368e6bf71480", "size": 890, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5_chapter/simpleHypothesisTest.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "5_chapter/simpleHypothesisTest.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "5_chapter/simpleHypothesisTest.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 37.0833333333, "max_line_length": 68, "alphanum_fraction": 0.6213483146, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517061554855, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7922681031012133}}
{"text": "include(\"TypeDefine.jl\")\n\n#see (4.46) from Toro\nfunction p_guess(left::HydroStatus, right::HydroStatus, ::TwoRarefaction)\n\t\t@assert left.gamma == right.gamma\n\t\tgamma = left.gamma\n\t\tgamma_power = (gamma-1) / 2. / gamma\n\t\tdelta_u = right.u - left.u\n\t\treturn ( (left.c + right.c - 0.5 * (gamma - 1) * delta_u) /\n\t\t\t   (left.c/left.p^gamma_power + right.c/right.p^gamma_power) ) ^\n\t\t       (1. / gamma_power)\nend\n\n#see (4.47) from Toro\nfunction p_guess(left::HydroStatus, right::HydroStatus, ::PrimitiveValue)\n\tdelta_u = right.u - left.u\n\tmean_pressure = 0.5 * (left.p + right.p)\n\tmean_density = 0.5 * (left.rho + right.rho)\n\tmean_speed_of_sound = 0.5 * (left.c + right.c)\n\treturn mean_pressure - delta_u * mean_density * mean_speed_of_sound\nend\n\n#see (4.48) from Toro\ng(p, status::HydroStatus) = sqrt(status.A / (p + status.B))\t\nfunction p_guess(left::HydroStatus, right::HydroStatus, ::TwoShock)\n\tp_hat = p_guess(left, right, PrimitiveValue)\n\tg_left = g(p_hat, left)\n\tg_right = g(p_hat, right)\n\tdelta_u = right.u - left.u\n\treturn (g_right * left.p + g_left * right.p - delta_u)/(g_right + g_left)\nend\t\t\t\t  \n\n#see (4.49) from Toro\np_guess(left::HydroStatus, right::HydroStatus, ::MeanPressure) = 0.5*(left.p + right.p)", "meta": {"hexsha": "d86157405284a0f22348e399e29735b8a17fc0ca", "size": 1215, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PressureGuess.jl", "max_stars_repo_name": "ryarazi/ExactRiemannProblemSolver", "max_stars_repo_head_hexsha": "207f917efb6a3ee2cf6da4e494e08e1b8bbb49bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2018-12-12T18:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T21:21:32.000Z", "max_issues_repo_path": "PressureGuess.jl", "max_issues_repo_name": "ryarazi/ExactRiemannProblemSolver", "max_issues_repo_head_hexsha": "207f917efb6a3ee2cf6da4e494e08e1b8bbb49bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PressureGuess.jl", "max_forks_repo_name": "ryarazi/ExactRiemannProblemSolver", "max_forks_repo_head_hexsha": "207f917efb6a3ee2cf6da4e494e08e1b8bbb49bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-12-05T13:15:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T13:28:33.000Z", "avg_line_length": 35.7352941176, "max_line_length": 87, "alphanum_fraction": 0.6798353909, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876287, "lm_q2_score": 0.8376199613065411, "lm_q1q2_score": 0.7922220284477207}}
{"text": "\"\"\"\n    node_clustering(s,v)\n\nReturn the clustering coefficient of the given node v in stream s:\n```math\ncc \\\\left(v \\\\right) = \\\\frac{ \\\\sum_{uw \\\\in V \\\\otimes V} \\\\left| T_{vu} \\\\cap T_{vw} \\\\cap T_{uw} \\\\right| }{\\\\sum_{uw \\\\in V \\\\otimes V} \\\\left| T_{vu} \\\\cap T_{vw} \\\\right|}\n```\nNote: If node v never has two neighbors present at the same\ntime in the stream, this function returns 0.\n\n### Reference\n- Matthieu Latapy, Tiphaine Viard and Clémence Magnien Social \n  Networks Analysis and Mining, 8: 61, 2018. \"Stream Graphs and \n  Link Streams for the Modeling of Interactions over Time\".\n  [(arXiv)](https://arxiv.org/pdf/1710.04073.pdf)\n\"\"\"\nfunction node_clustering(s::AbstractUndirectedStream, v::AbstractString)\n    nomin=0\n    denom=0\n    N=Set(AbstractString[])\n    for n in keys(neighborhood(s,v))\n        push!(N,n)\n    end\n    for (u,w) in N ⊗ N\n        nomin+=length((times(s,v,u) ∩ times(s,v,w)) ∩ times(s,u,w))\n        denom+=length(times(s,v,u) ∩ times(s,v,w))\n    end\n    denom != 0 ? nomin/denom : 0.0\nend\n\n\"\"\"\n    node_clustering(s,v,t)\n\nReturn the instantaneous clustering coefficient of the given node v\nat the given time t in the given stream:\n```math\ncc_t \\\\left(v \\\\right)= \\\\frac{\\\\sum_{uw} vu_t vw_t uw_t}{\\\\sum_{uw} vu_t vw_t}\n```\nNote: If node v does not have two neighbors at the given\ntime t, this function returns 0.\n\n### Reference\n- Matthieu Latapy, Tiphaine Viard and Clémence Magnien Social \n  Networks Analysis and Mining, 8: 61, 2018. \"Stream Graphs and \n  Link Streams for the Modeling of Interactions over Time\".\n  [(arXiv)](https://arxiv.org/pdf/1710.04073.pdf)\n\"\"\"\nfunction node_clustering(s::AbstractUndirectedStream,v::AbstractString,t::Float64)\n    Nt=Set(AbstractString[])\n    for n in neighborhood(s,v,t)\n        push!(Nt,n)\n    end\n    nom=sum([1.0 for (u,w) in Nt ⊗ Nt if ((t ∈ times(s,v,u)) & (t ∈ times(s,v,w)) & (t ∈ times(s,u,w)))])\n    denom=sum([1.0 for (u,w) in Nt ⊗ Nt if ((t ∈ times(s,v,u)) & (t ∈ times(s,v,w)))])\n    denom != 0 ? nom/denom : 0.0\nend\n\n\"\"\"\n    node_clustering(s)\n\nReturn the node clustering coefficient of the given stream:\n```math\ncc \\\\left( V \\\\right)= \\\\frac{1}{n} \\\\sum_{v \\\\in V} n_v cc \\\\left( v \\\\right) = \\\\sum_{v \\\\in V} \\\\frac{\\\\left| T_v \\\\right|}{\\\\left|W \\\\right|} cc \\\\left(v \\\\right)\n```\nWhere n is the number of nodes in the stream.\nNote: If there is no node in the stream, this function returns 0.\n\n### Reference\n- Matthieu Latapy, Tiphaine Viard and Clémence Magnien Social \n  Networks Analysis and Mining, 8: 61, 2018. \"Stream Graphs and \n  Link Streams for the Modeling of Interactions over Time\".\n  [(arXiv)](https://arxiv.org/pdf/1710.04073.pdf)\n\"\"\"\nfunction node_clustering(s::AbstractUndirectedStream)\n    if length(s.V)>0\n        1.0/length(s.V)*sum([contribution(s,v)*node_clustering(s,v) for v in s.V])\n    else\n        0.0\n    end\nend\n\n\"\"\"\n    time_clustering(s,t)\n\nReturn time clustering coefficient of a given time instant in the stream:\n```math\ncc \\\\left( t \\\\right)= \\\\frac{\\\\sum_{v}cc_t\\\\left(v \\\\right) \\\\sum_{uw} vu_t vw_t}{\\\\sum_{v} \\\\sum_{uw} vu_t vw_t}\n```\n\n### Reference\n- Matthieu Latapy, Tiphaine Viard and Clémence Magnien Social \n  Networks Analysis and Mining, 8: 61, 2018. \"Stream Graphs and \n  Link Streams for the Modeling of Interactions over Time\".\n  [(arXiv)](https://arxiv.org/pdf/1710.04073.pdf)\n\"\"\"\nfunction time_clustering(s::AbstractUndirectedStream,t::Float64)\n    nom::Float64=0.0\n    denom::Float64=0.0\n    for v in s.V\n        acc::Float64=0.0\n        for (u,w) in s.V ⊗ s.V\n            if ((t ∈ times(s,v,u)) & (t ∈ times(s,v,w)))\n                acc+=1.0\n            end\n        end\n        nom+=node_clustering(s,v,t) * acc\n        denom+=acc\n    end\n    denom != 0 ? nom/denom : 0.0\nend\n\n\"\"\"\n    time_clustering(s)\n\nReturn the time clustering coefficient of the given stream:\n```math\ncc \\\\left( T \\\\right) = \\\\int_{t} \\\\frac{\\\\left| V_t \\\\right|}{\\\\left| W \\\\right|} cc \\\\left( t \\\\right) dt\n```\nNote: If nodes are never present in the stream, this function returns 0.\n\n### Reference\n- Matthieu Latapy, Tiphaine Viard and Clémence Magnien Social \n  Networks Analysis and Mining, 8: 61, 2018. \"Stream Graphs and \n  Link Streams for the Modeling of Interactions over Time\".\n  [(arXiv)](https://arxiv.org/pdf/1710.04073.pdf)\n\"\"\"\nfunction time_clustering(s::AbstractUndirectedStream)\n    τ = times(s)\n    dW = duration(s.W)\n    dW != 0 ? 1.0/dW*sum([time_clustering(s,0.5*(t[2]+t[1])) * length(nodes(s,0.5*(t[2]+t[1]))) for t in zip(τ[1:end-1],τ[2:end])]) : 0.0\nend\n\n\"\"\"\n    time_clustering(s)\n\nReturn the time clustering coefficient of the given stream using a TimeCursor.\n\"\"\"\nfunction time_clustering(s::AbstractUndirectedStream,tc::TimeCursor)\n    throw(\"Not Implemented\")\nend\n\n\"\"\"\n    clustering(s)\n\nReturn the clustering coefficient of the given stream:\n```math\ncc \\\\left( S \\\\right) = \\\\int_t \\\\frac{1}{\\\\left|T \\\\right|} \\\\sum_{v} \\\\frac{cc_t\\\\left(v \\\\right)}{\\\\left|V \\\\right|} dt\n```\n\n### Reference\n- Matthieu Latapy, Tiphaine Viard and Clémence Magnien Social \n  Networks Analysis and Mining, 8: 61, 2018. \"Stream Graphs and \n  Link Streams for the Modeling of Interactions over Time\".\n  [(arXiv)](https://arxiv.org/pdf/1710.04073.pdf)\n\"\"\"\nfunction clustering(s::AbstractUndirectedStream)\n    card_TV = duration(s)*length(s.V)\n    if card_TV==0\n        return 0.0\n    end\n    τ = times(s)\n    acc::Float64 = 0.0\n    for v in s.V\n        for t in zip(τ[1:end-1],τ[2:end])\n            acc+=node_clustering(s,v,0.5*(t[1]+t[2]))*(t[2]-t[1])\n        end\n    end\n    1.0/card_TV*acc\nend\n\n", "meta": {"hexsha": "78ac6f94dff59a58d48c51d22b8e5b86851bd361", "size": 5529, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/clustering.jl", "max_stars_repo_name": "NicolasGensollen/StreamGraphs.jl", "max_stars_repo_head_hexsha": "ab49d23f2078f2ac3321e83c292196cf14559a7a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-08T12:45:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-08T12:45:16.000Z", "max_issues_repo_path": "src/clustering.jl", "max_issues_repo_name": "NicolasGensollen/StreamGraphs.jl", "max_issues_repo_head_hexsha": "ab49d23f2078f2ac3321e83c292196cf14559a7a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/clustering.jl", "max_forks_repo_name": "NicolasGensollen/StreamGraphs.jl", "max_forks_repo_head_hexsha": "ab49d23f2078f2ac3321e83c292196cf14559a7a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3333333333, "max_line_length": 178, "alphanum_fraction": 0.6458672454, "num_tokens": 1781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7922220156564735}}
{"text": "## fit logistic regression\n\nusing DataFrames, GLM, Plots\ntemp = [53, 57, 58, 63, 66, 67, 67, 67, 68, 69, 70, 70, 70, 70, 72, 73, 75, 75, 76, 76, 78, 79, 81]\nfailure = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0]\n\ndata = DataFrame(temp = temp, failure = failure)\n\nlogit_fit = glm(@formula(failure ~ temp), data, Binomial(), LogitLink())\n#plot(temp, predict(logit_fit), legend = false, xlabel = \"Temperature\", ylab = \"Probability\")\n#scatter!(temp, predict(logit_fit))\n\n## metropolis-hastings\nusing Distributions\nγ = 0.57721\nfunction ll(α::Float64, β::Float64)\n    a = exp.(α .+ β*temp)\n    return prod( (a ./ (1 .+ a) ).^failure .* (1 ./ (1 .+ a)).^(1 .- failure) )\nend\nfunction mh_logit(T::Int, α_hat::Float64, β_hat::Float64, σ_hat::Float64)\n    φ = Normal(β_hat, σ_hat)\n    π = Exponential(exp(α_hat+γ))\n    Α = ones(T)\n    Β = ones(T)\n    for t = 1:T-1\n        α = log(rand(π))\n        β = rand(φ)\n        r = ( ll(α, β) / ll(Α[t], Β[t]) ) * ( pdf(φ, Β[t]) / pdf(φ, β) )\n        if rand() < r\n            Α[t+1] = α\n            Β[t+1] = β\n        else\n            Α[t+1] = Α[t]\n            Β[t+1] = Β[t]\n        end\n    end\n    return Α, Β\nend\n\n# trace plot\n\nΑ, Β = mh_logit(10000, 15.04, -0.233, 0.108)\n\np1 = plot(Α, legend = false, xlab = \"Intercept\")\nhline!([15.04])\n\np2 = plot(Β, legend = false, xlab = \"Slope\")\nhline!([-0.233])\n\nplot(p1, p2, layout = (1,2))\n\n# mean trace plot\n\nΑmean = cumsum(Α) ./ collect(1:length(Α))\nΒmean = cumsum(Β) ./ collect(1:length(Β))\n\np1 = plot(Αmean, legend = false, xlab = \"Intercept\")\nhline!([15.04])\n\np2 = plot(Βmean, legend = false, xlab = \"Slope\")\nhline!([-0.233])\n\nplot(p1, p2, layout = (1,2))\n", "meta": {"hexsha": "a61f1eb9f3b80c1c12b2baf0ea655b45a14a2f45", "size": 1661, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "MH/IMH/logit_imh.jl", "max_stars_repo_name": "szcf-weiya/MCMC", "max_stars_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-07-19T12:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T08:06:50.000Z", "max_issues_repo_path": "MH/IMH/logit_imh.jl", "max_issues_repo_name": "szcf-weiya/MCMC", "max_issues_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-02-03T15:08:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-05T15:41:39.000Z", "max_forks_repo_path": "MH/IMH/logit_imh.jl", "max_forks_repo_name": "szcf-weiya/MCMC", "max_forks_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-07-19T12:50:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T08:06:52.000Z", "avg_line_length": 25.953125, "max_line_length": 99, "alphanum_fraction": 0.5466586394, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545377452443, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7921675146840219}}
{"text": "# Function for FAVAR by Bernanke et al. (2015)\r\nimport Pkg;\r\nusing LinearAlgebra, Distributions, Statistics, MultivariateStats;\r\nusing ProgressMeter;\r\nusing Gadfly, Colors;\r\n\r\nfunction func_std(mat)\r\n    # Function to standardize data\r\n    T, k = size(mat);\r\n    μ = mean(mat; dims = 1);\r\n    σ = std(mat; dims = 1);\r\n    return (mat .- μ) ./ σ;\r\nend\r\n\r\nfunction func_favar(yₘ, yₚ, p, ζ)\r\n    # yₘ: data - main block\r\n    # yₚ: data - factor block - to be\r\n    # p: lag term for VAR\r\n    # ζ: Number of factors to be extracted\r\n\r\n    T, kₘ = size(yₘ);\r\n\r\n    # For principal component analysis (PCA), always use standardized data.\r\n    res_pca = fit(PCA, func_std(yₚ); maxoutdim = ζ);\r\n    𝔽ₒ = projection(res_pca);\r\n\r\n    Q = yₚ';\r\n    Z = [yₘ 𝔽ₒ]';\r\n    ℾₒ = (Q * Z')/(Z * Z');\r\n    ℾₒ𝑦 = ℾₒ[:, (1:kₘ)];\r\n    x̃ = yₚ - (ℾₒ𝑦 * yₘ')';\r\n\r\n    ssrₒ = sum((Q - ℾₒ * Z).^2, dims = 2)\r\n\r\n    # Start the iteraction process\r\n    𝔽₁ = 𝔽ₒ;\r\n    ℾ₁ = ℾₒ; ℾ₁𝑦 = ℾₒ𝑦;\r\n    ssr₁ = ssrₒ\r\n\r\n    n_ϝ = 0; # Count iterations;\r\n    while sum(abs(ssr₁ .- ssrₒ) > 10^(-6))\r\n        # If no convergence, repeat the process\r\n        # Update the criteria\r\n        𝔽ₒ = 𝔽₁;\r\n        ssrₒ = ssr₁;\r\n\r\n        # Redraw component\r\n        res_pca = fit(PCA, func_std(x̃); maxoutdim = ζ);\r\n        𝔽₁ = projection(res_pca);\r\n\r\n        Q = yₚ';\r\n        Z = [yₘ 𝔽₁]';\r\n        ℾ₁ = (Q * Z')/(Z * Z');\r\n        ℾ₁𝑦 = ℾ₁[:, (1:kₘ)];\r\n        x̃ = yₚ - (ℾ₁𝑦 * yₘ')';\r\n\r\n        ssr₁ = sum((Q - ℾ₁ * Z).^2, dims = 2);\r\n\r\n        n_ϝ = n_ϝ + 1;\r\n    end\r\n\r\n    # conditional check for factor loading (optional)\r\n    #=\r\n    #Check on elements of factor loading that belongs to first series in the\r\n    # information set matrix - yₚ\r\n    # If an element is negative, multiply whole factor loading with -1 and\r\n    # then respective factor\r\n\r\n    for iₚ = (kₘ + 1):size(Gamma_final, 2)\r\n        if ℾ₁[1, iₚ] < 0\r\n            ℾ₁[:, iₚ] = -1 .* ℾ₁[:, iₚ];\r\n            𝔽₁[:, (iₚ - kₘ)] = -1 .* 𝔽₁[:, (iₚ - kₘ)];\r\n        end\r\n    end\r\n    =#\r\n\r\n    Q = yₚ';\r\n    Z = [yₘ 𝔽₁]';\r\n    ℾ₁ = (Q * Z')/(Z * Z');\r\n    ℾ₁𝑦 = ℾ₁[:, (1:kₘ)];\r\n    x̃ = yₚ - (ℾ₁𝑦 * yₘ')';\r\n\r\n    # compute VAR(p)\r\n    𝔇 = [yₘ 𝔽₁];\r\n\r\n    𝚩, 𝞄, 𝝨 = func_VAR(𝔇, p);\r\n\r\n    return 𝚩, 𝞄, 𝝨, 𝔽₁, ℾ₁;\r\nend\r\n", "meta": {"hexsha": "a06b52f8bf51ba6e6d2b60feac8e2f33a192f698", "size": 2236, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/func_FAVAR.jl", "max_stars_repo_name": "jjl3411/julia-FactorAugmentedVectorAR.jl", "max_stars_repo_head_hexsha": "1718641d3db9a4f40c0db385836973eb9ca27e4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/func_FAVAR.jl", "max_issues_repo_name": "jjl3411/julia-FactorAugmentedVectorAR.jl", "max_issues_repo_head_hexsha": "1718641d3db9a4f40c0db385836973eb9ca27e4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-19T04:42:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-15T20:14:22.000Z", "max_forks_repo_path": "src/func_FAVAR.jl", "max_forks_repo_name": "justinjoliver/julia-FactorAugmentedVectorAR.jl", "max_forks_repo_head_hexsha": "1718641d3db9a4f40c0db385836973eb9ca27e4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8444444444, "max_line_length": 77, "alphanum_fraction": 0.4910554562, "num_tokens": 914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7921675076340684}}
{"text": "using ChooseOptimizer, JuMP, Multisets\n\n\"\"\"\n`matrix_match(A,B)` returns permutation matrices `P` and `Q` \nso that `P*A==B*Q` or throws an error if not possible. \n\"\"\"\nfunction matrix_match(A::AbstractMatrix, B::AbstractMatrix)\n    err_msg = \"Matrices do not match\"\n\n    # Check that A and B have same dimensions and same elements\n    r, c = size(A)\n    if (r, c) != size(B) || Multiset(collect(A)) != Multiset(collect(B))\n        error(err_msg)\n    end\n\n    m = Model(get_solver())\n\n    # Set up P and Q are permutation matrices\n\n    @variable(m, P[1:r, 1:r], Bin)\n    @variable(m, Q[1:c, 1:c], Bin)\n\n    for i = 1:r\n        @constraint(m, sum(P[i, j] for j = 1:r) == 1)\n        @constraint(m, sum(P[j, i] for j = 1:r) == 1)\n    end\n\n    for i = 1:c\n        @constraint(m, sum(Q[i, j] for j = 1:c) == 1)\n        @constraint(m, sum(Q[j, i] for j = 1:c) == 1)\n    end\n\n    # require P*A == B*Q\n\n    for i = 1:r\n        for j = 1:c\n            @constraint(\n                m,\n                sum(P[i, k] * A[k, j] for k = 1:r) == sum(B[i, k] * Q[k, j] for k = 1:c)\n            )\n        end\n    end\n\n    optimize!(m)\n    status = Int(termination_status(m))\n    if status != 1\n        error(err_msg)\n    end\n\n    PP = Int.(value.(P))\n    QQ = Int.(value.(Q))\n    return PP, QQ\nend\n", "meta": {"hexsha": "6acaff5aab9827fe600ae422bc7ca78b814893c4", "size": 1276, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix_match.jl", "max_stars_repo_name": "scheinerman/Misc.jl", "max_stars_repo_head_hexsha": "2cccc9bf616188c2b1258bdae71123a0d1b37418", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-12T17:02:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T12:31:19.000Z", "max_issues_repo_path": "src/matrix_match.jl", "max_issues_repo_name": "scheinerman/Misc.jl", "max_issues_repo_head_hexsha": "2cccc9bf616188c2b1258bdae71123a0d1b37418", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix_match.jl", "max_forks_repo_name": "scheinerman/Misc.jl", "max_forks_repo_head_hexsha": "2cccc9bf616188c2b1258bdae71123a0d1b37418", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6296296296, "max_line_length": 88, "alphanum_fraction": 0.5195924765, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545377452442, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.792167503032095}}
{"text": "#Prezentacja wyników do sprawozdania: Zadanie P1.2\n#Kacper Kulczak 279079\n\n\n#Pomocnicza funkcja pomgająca. Potegowanie\nfunction pow(n,w)\n    result = one(n)\n    for i = one(w):w\n        result *= n\n    end\n    return result\nend\n\n# Funkcja obliczajaca stala e za pomoca przyblizenia granicy (1+1/n)^n\nfunction definition_e(n)\n    result = (one(n) + one(n) / n)\n    for i = one(n):log2(n)\n        result *= result\n    end\n    return result\nend\n# Funkcja obliczajaca stala e za pomoca szeregu taylora sum(1/ n!)\nfunction taylor_series(n)\n    result = zero(n)\n    for i = zero(n):n\n        result += one(n) / factorial(n-i)\n    end\n    return result\nend\n# Funkcja obliczajaca stala e za pomoca ulamka lancuchowego\nfunction continued_fraction(n)\n    i = n + n\n    result = i\n    result = one(n) + one(n) / result\n    result = one(n) + one(n) / result\n    i -= one(n) + one(n)\n    while i > one(n) + one(n)\n        result = i + one(n) / result\n        result = one(n) + one(n) / result\n        result = one(n) + one(n) / result\n        i -= one(n) + one(n)\n    end\n    result = one(n) + one(n) + one(n) / result\n    result = one(n) + one(n) / result\n    result = one(n) + one(n) + one(n) / result\n    return result\n    \nend\n#Drugi szereg SUM (3k+1)/(3k)!\nfunction second_series(n)\n    result = zero(n)\n    for i = zero(n):n\n        result += (one(n) + (convert(typeof(n),3) * (n-i) ) * ( convert(typeof(n),3) * (n-i) ) )/ factorial(convert(typeof(n),3) *(n-i))\n    end\n    return result\nend\n\n       \n# Trzeci szreg SUM (4k + 3) / 2^(2k+1) * (2k+1)!\nfunction third_series(n)\n    result = zero(n)\n    for i = zero(n):n\n        temp = convert(typeof(n),4) * (n-i) + one(n) + one(n) + one(n)\n        temp /= factorial(convert(typeof(n),2) *(n-i) + one(n)) * pow( convert(typeof(n),2), convert(typeof(n),2)*(n-i) + one(n)) \n        result += temp\n    end\n    return result * result\nend\n#Test zapisujace wyniki na zadanym zasiegu 1->range\nfunction test(fun,range)\n    container= [[],[],[],[]]\n    for i = one(range) : range\n        temp = fun(i)\n        err = convert(typeof(range),eu)-temp\n        push!(container[1], i)\n        push!(container[2], temp)\n        push!(container[3],err)\n        push!(container[4], -log10(abs( err )) )\n    end\n    return container\nend\n\n#Test dla definicji, przedstawiajacy tylko niektore iteracje\nfunction test_def(fun,range)\n    container= [[],[],[],[]]\n    x = one(range)\n    for i = one(range) : range\n        x *= convert(typeof(range),8.)\n        temp = fun(x)\n        err = convert(typeof(range),eu)-temp\n        push!(container[1], x)\n        push!(container[2], temp)\n        push!(container[3],err)\n        push!(container[4], -log10(abs( err )) )\n    end\n    return container\nend\n\n#Funkcja formatujaca wyjscie\nfunction myshow(list)\n    for i = 1:length(list[1])\n        @printf \"n=%d val=%.f error=%.4e #cyfr=%.0f\\n\" list[1][i] list[2][i] list[3][i] list[4][i]\n    end\nend\n\nsetprecision(256)\n@show precision(BigFloat)\nrange = BigFloat(60.)\ndata1 = test_def(definition_e, BigFloat(30.) )\ndata2 = test(taylor_series, range)\ndata3 = test(continued_fraction, range )\ndata4 = test(second_series, range)\ndata5 = test(third_series, range)\n@printf \"\\n\\n\\n\"\nprintln(\"Definition of e\")\nmyshow(data1)\n@printf \"\\n\\n\\n\"\nprintln(\"Taylor series\")\nmyshow(data2)\n@printf \"\\n\\n\\n\"\nprintln(\"Contiuned fraction\")\nmyshow(data3)\n@printf \"\\n\\n\\n\"\nprintln(\"Second Series\")\nmyshow(data4)\n@printf \"\\n\\n\\n\"\nprintln(\"Third Series\")\nmyshow(data5)\n\n#Funckje do obliczenia ilości mnożeń i dzieleń w zależnosci od iteracji w wykorzytanych\n# przeze mnie metodach\nfunction Tdef(n)\n    return one(n)+ one(n)+log2(n)\nend\nfunction TCF(n)\n    return n * convert(typeof(n),3)\nend\nfunction Tser1(n)\n    return n * convert(typeof(n),2)\nend\nfunction Tser2(n)\n    return n * convert(typeof(n),4)\nend\nfunction Tser3(n)\n    return n * convert(typeof(n),5) + one(n)\nend", "meta": {"hexsha": "a88c851f1ced150b52602288de1d349a08c98637", "size": 3856, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Sprawozdania_doswadczenia_Numeryczne/Przyblizanie_stalej_e/prog/program.jl", "max_stars_repo_name": "Magikis/University_Projects", "max_stars_repo_head_hexsha": "bcaf8bd5695cd3809dfd53a922936a64daf51fec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sprawozdania_doswadczenia_Numeryczne/Przyblizanie_stalej_e/prog/program.jl", "max_issues_repo_name": "Magikis/University_Projects", "max_issues_repo_head_hexsha": "bcaf8bd5695cd3809dfd53a922936a64daf51fec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sprawozdania_doswadczenia_Numeryczne/Przyblizanie_stalej_e/prog/program.jl", "max_forks_repo_name": "Magikis/University_Projects", "max_forks_repo_head_hexsha": "bcaf8bd5695cd3809dfd53a922936a64daf51fec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4109589041, "max_line_length": 136, "alphanum_fraction": 0.6117738589, "num_tokens": 1255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.870597270087091, "lm_q1q2_score": 0.7921625533629019}}
{"text": "function bisection(f::Function, a, b; atol = 0.001, rtol = 0.001)\n    x = (a+b) / 2\n    while (b-a) > atol || (b - a)/x > rtol\n        if f(a)*f(x) < 0\n            b = x\n            x = (a+b)/2\n        elseif f(x)*f(b) < 0\n            a = x\n            x = (a+b)/2\n        elseif f(x) == 0\n            return x\n        end\n    end\n    return x\nend", "meta": {"hexsha": "4022b88170e46556740ca4617b6ac8e3700d1e8a", "size": 347, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "task_7_13.jl", "max_stars_repo_name": "Litger45/julia-algorithms-2", "max_stars_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "task_7_13.jl", "max_issues_repo_name": "Litger45/julia-algorithms-2", "max_issues_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "task_7_13.jl", "max_forks_repo_name": "Litger45/julia-algorithms-2", "max_forks_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1333333333, "max_line_length": 65, "alphanum_fraction": 0.3688760807, "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211323, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7921610040074601}}
{"text": "import PyPlot\nconst plt = PyPlot\n\nfunction M(p::Int64,u)\n    if p == 2\n        if u >= 0 && u <= 2\n            return 1 - abs(u-1)\n        else\n            return 0.0\n        end\n    else\n        return M(p-1,u)*u/(p-1) + (p-u)/(p-1)*M(p-1,u-1)\n    end\nend\n\n\nfunction main()\n    @time println( M(2,1.1) )\n    @time println( M(3,1.1) )\n    @time println( M(4,1.1) )\n\n    NptsPlot = 100\n    x = Array{Float64}( linspace(0.0,5.0,NptsPlot) )\n    y2 = Array{Float64}(NptsPlot)\n    y3 = Array{Float64}(NptsPlot)\n    y4 = Array{Float64}(NptsPlot)\n    y5 = Array{Float64}(NptsPlot)\n    for i = 1:NptsPlot\n        y2[i] = M(2,x[i])\n        y3[i] = M(3,x[i])\n        y4[i] = M(4,x[i])\n        y5[i] = M(5,x[i])\n    end\n    plt.clf()\n    plt.plot( x, y2, linewidth=2.0, label=\"M2.png\" )\n    plt.plot( x, y3, linewidth=2.0, label=\"M3.png\" )\n    plt.plot( x, y4, linewidth=2.0, label=\"M4.png\" )\n    plt.plot( x, y5, linewidth=2.0, label=\"M5.png\" )\n    plt.grid(true)\n    plt.legend()\n    plt.savefig(\"M2.png\", dpi=300)\nend\n\nmain()\n", "meta": {"hexsha": "a9704ee8c888e733eb620fa203e79b802708a557", "size": 1018, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LF/test_NLESS/main_NLESS.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "LF/test_NLESS/main_NLESS.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LF/test_NLESS/main_NLESS.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 22.6222222222, "max_line_length": 56, "alphanum_fraction": 0.5127701375, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7921610012357839}}
{"text": "# [1] M. R. Teague, “Image analysis via the general theory of moments*,” Journal of the Optical Society of America, vol. 70, no. 8, p. 920, Aug. 1980.\n# https://doi.org/10.1364/josa.70.000920\nfunction measure_feature(property::RegionEllipse, t::IndexedTable, labels::AbstractArray, N::Int = 0)\n    init = StepRange(typemax(Int), -1, -typemax(Int))\n    ℳ₀₀ = zeros(N)\n    ℳ₁₀ = zeros(N)\n    ℳ₀₁ = zeros(N)\n    ℳ₁₁ = zeros(N)\n    ℳ₂₀ = zeros(N)\n    ℳ₀₂ = zeros(N)\n    # TODO Document discretization model that underpins these moment computations.\n    for i in CartesianIndices(labels)\n        l = labels[i]\n        if  l != 0\n            y, x = i.I\n            ℳ₀₀[l] += 1\n            ℳ₁₀[l] += x\n            ℳ₀₁[l] += y\n            ℳ₁₁[l] += x*y\n            ℳ₂₀[l] += x^2 + 1/12\n            ℳ₀₂[l] += y^2 + 1/12\n        end\n    end\n    t = pushcol(t, :M₀₀ => ℳ₀₀, :M₁₀ => ℳ₁₀, :M₀₁ => ℳ₀₁, :M₁₁ => ℳ₁₁, :M₂₀ => ℳ₂₀, :M₀₂ => ℳ₀₂)\n    fill_properties(property, t)\nend\n\nfunction fill_properties(property::RegionEllipse, t::IndexedTable)\n    t = property.centroid ? compute_centroid(t) : t\n    t = property.semi_axes ? compute_semi_axes(t) : t\n    t = property.orientation ? compute_orientation(t) : t\n    t = property.eccentricity ? compute_eccentricity(t) : t\nend\n\nfunction compute_centroid(t::IndexedTable)\n    @transform t {centroid = (:M₀₁ / :M₀₀, :M₁₀ / :M₀₀)}\nend\n\nfunction compute_semi_axes(t::IndexedTable)\n    semi_axes = select(t, (:M₀₀,  :M₁₀, :M₀₁, :M₁₁, :M₂₀, :M₀₂) => row -> compute_semi_axes(row...))\n    t = pushcol(t, :semi_axes => semi_axes)\nend\n\n\nfunction compute_semi_axes(M₀₀::Real, M₁₀::Real, M₀₁::Real, M₁₁::Real, M₂₀::Real, M₀₂::Real)\n    μ′₂₀ = (M₂₀ / M₀₀) - (M₁₀ / M₀₀)^2\n    μ′₀₂ = (M₀₂ / M₀₀) - (M₀₁ / M₀₀)^2\n    μ′₁₁ = (M₁₁ / M₀₀) - ((M₁₀ / M₀₀) * (M₀₁ / M₀₀))\n\n    # See Equations (7) and (8) in [1].\n    l₁ = sqrt((μ′₂₀ + μ′₀₂ + sqrt(4 * μ′₁₁^2 +  (μ′₂₀ - μ′₀₂)^2)) / (1 / 2))\n    l₂ = sqrt((μ′₂₀ + μ′₀₂ - sqrt(4 * μ′₁₁^2 +  (μ′₂₀ - μ′₀₂)^2)) / (1 / 2))\n    min(l₁, l₂), max(l₁, l₂)\nend\n\nfunction compute_orientation(t::IndexedTable)\n    orientation = select(t, (:M₀₀,  :M₁₀, :M₀₁, :M₁₁, :M₂₀, :M₀₂) => row -> compute_orientation(row...))\n    t = pushcol(t, :orientation => orientation)\nend\n\nfunction compute_eccentricity(t::IndexedTable)\n    eccentricity = select(t, (:M₀₀,  :M₁₀, :M₀₁, :M₁₁, :M₂₀, :M₀₂) => row -> compute_eccentricity(row...))\n    t = pushcol(t, :eccentricity => eccentricity)\nend\n\nfunction compute_eccentricity(M₀₀::Real, M₁₀::Real, M₀₁::Real, M₁₁::Real, M₂₀::Real, M₀₂::Real)\n    b, a = compute_semi_axes(M₀₀, M₁₀, M₀₁, M₁₁, M₂₀, M₀₂)\n    e = sqrt(1 - (b/a)^2)\nend\n\n# [1] M. R. Teague, “Image analysis via the general theory of moments*,” Journal of the Optical Society of America, vol. 70, no. 8, p. 920, Aug. 1980.\n# https://doi.org/10.1364/josa.70.000920\nfunction compute_orientation(M₀₀::Real, M₁₀::Real, M₀₁::Real, M₁₁::Real, M₂₀::Real, M₀₂::Real)\n    μ′₂₀ = M₂₀ / M₀₀ - (M₁₀ / M₀₀)^2\n    μ′₀₂ = M₀₂ / M₀₀ - (M₀₁ / M₀₀)^2\n    μ′₁₁ = M₁₁ / M₀₀ - (M₁₀ / M₀₀) * (M₀₁ / M₀₀)\n\n    # Ellipse tilt angle for various cases of signs of the second moments [1].\n    θ = 0.0\n    if μ′₂₀ - μ′₀₂ == 0 && μ′₁₁  == 0\n        θ = 0.0\n    elseif μ′₂₀ - μ′₀₂ == 0 && μ′₁₁  > 0\n        θ = 45.0\n    elseif μ′₂₀ - μ′₀₂ == 0 && μ′₁₁  < 0\n        θ = -45.0\n    elseif μ′₂₀ - μ′₀₂ > 0 && μ′₁₁ == 0\n        θ = 0.0\n    elseif μ′₂₀ - μ′₀₂ < 0 && μ′₁₁ == 0\n        θ = -90.0\n    elseif μ′₂₀ - μ′₀₂ > 0 && μ′₁₁ > 0\n        # 0 < θ < 45\n        ξ = 2*μ′₁₁ / (μ′₂₀ - μ′₀₂)\n        θ = (1/2) * atand(ξ)\n    elseif μ′₂₀ - μ′₀₂ > 0 && μ′₁₁ < 0\n        # -45 < θ < 0\n        ξ = 2*μ′₁₁ / (μ′₂₀ - μ′₀₂)\n        θ = (1/2) * atand(ξ)\n    elseif μ′₂₀ - μ′₀₂ < 0 && μ′₁₁ > 0\n        # 45 < θ < 90\n        ξ = 2*μ′₁₁ / (μ′₂₀ - μ′₀₂)\n        θ = (1/2) * atand(ξ) + 90.0\n    elseif μ′₂₀ - μ′₀₂ < 0 && μ′₁₁ < 0\n        # -90 < θ < -45\n        ξ = 2*μ′₁₁ / (μ′₂₀ - μ′₀₂)\n        θ = (1/2) * atand(ξ) - 90.0\n    end\n    θ\nend\n", "meta": {"hexsha": "7c609b2418a0658808764366dad362607329c7ac", "size": 3934, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/region_ellipse.jl", "max_stars_repo_name": "wesleytanws/ImageComponentAnalysis.jl", "max_stars_repo_head_hexsha": "c9bf018c4ab59e2bc57d406100201fb8d838b184", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-02T22:00:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-02T22:00:19.000Z", "max_issues_repo_path": "src/region_ellipse.jl", "max_issues_repo_name": "wesleytanws/ImageComponentAnalysis.jl", "max_issues_repo_head_hexsha": "c9bf018c4ab59e2bc57d406100201fb8d838b184", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/region_ellipse.jl", "max_forks_repo_name": "wesleytanws/ImageComponentAnalysis.jl", "max_forks_repo_head_hexsha": "c9bf018c4ab59e2bc57d406100201fb8d838b184", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0917431193, "max_line_length": 150, "alphanum_fraction": 0.5452465684, "num_tokens": 1745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211323, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7921609983320624}}
{"text": "#HW2 Problem 3\n#Minhao Yan my497, Wentong Chen wc422\n\n#Firm's Profit Function\nfunction profit(η,c1,c2,q)\n    profit1=sum(q)^(-1/η)*q[1]-c1*q[1] # Firm 1's profit\n    profit2=sum(q)^(-1/η)*q[2]-c2*q[2] # Firm 2's profit\n    profit=[profit1; profit2]\n    return profit\nend\n\n#Function that solves q_prime\nfunction q_prime(η,c1,c2,q)\n    q_prime11=(-1/η)*sum(q)^(-1/η-1)-(1/η)*sum(q)^(-1/η-1)+(1/η^2+1/η)*q[1]*sum(q)^(-1/η-2)-c1\n    q_prime12=(-1/η)*sum(q)^(-1/η-1)+(1/η^2+1/η)*sum(q)^(-1/η-2)*q[1]\n    q_prime21=(-1/η)*sum(q)^(-1/η-1)+(1/η^2+1/η)*sum(q)^(-1/η-2)*q[2]\n    q_prime22=(-1/η)*sum(q)^(-1/η-1)-(1/η)*sum(q)^(-1/η-1)+(1/η^2+1/η)*q[2]*sum(q)^(-1/η-2)-c2\n    q_prime_m=[q_prime11 q_prime12; q_prime21 q_prime22]\n    return q_prime_m\nend\n\n#Newton's method\nfunction cournot_newton(η,c1,c2,initial_guess,tolerance)\n    diff=[Inf; Inf]\n    q_old=initial_guess\n    q=[1e10;1e10]\n\n    while abs.(diff)>tolerance\n        q = q_old - transpose(transpose(profit(η,c1,c2,q_old))*inv(q_prime(η,c1,c2,q_old)))\n        diff= q- q_old\n        q_old= q\n    end\n #  Print out final output\n println(\"The solution is $q.\")\nend\n\n#   Parameters and Inputs\nη=1.6\nc1=0.15\nc2=0.2\ninitial_guess=[20;20]\ntolerance=[1e-5;1e-5]\n\n#   Optimization\nq_opt=cournot_newton(η,c1,c2,initial_guess,tolerance)\n", "meta": {"hexsha": "9dcc6ba35de11bf7f320f9be39ddecd8c4c85614", "size": 1278, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Problem3.jl", "max_stars_repo_name": "wentong-chen/problem-set-1-q-3", "max_stars_repo_head_hexsha": "fd47dc79c0ca19d820faa47bcfe0edc67a42b40a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Problem3.jl", "max_issues_repo_name": "wentong-chen/problem-set-1-q-3", "max_issues_repo_head_hexsha": "fd47dc79c0ca19d820faa47bcfe0edc67a42b40a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Problem3.jl", "max_forks_repo_name": "wentong-chen/problem-set-1-q-3", "max_forks_repo_head_hexsha": "fd47dc79c0ca19d820faa47bcfe0edc67a42b40a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7826086957, "max_line_length": 94, "alphanum_fraction": 0.6251956182, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138559, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7921609902105301}}
{"text": "# Create an image\nx = LinRange(-3, 3, 150)\ny = LinRange(-2, 2, 100)\n# RGB values\nr = (1 .+ cos.(atan.(y, x')))/2\ng = (1 .+ sin.(atan.(y, x')))/2\nb = exp.(-(x'.^2 .+ y.^2)/4)\ndata = cat(r, g, b, dims=3)\n# Draw the image\nimshow(data)\n", "meta": {"hexsha": "b500c2ea98a7d2fe21e632d88f3ce76c44e05aa5", "size": 232, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/docstrings/imshow.jl", "max_stars_repo_name": "Abhisheknishant/GRUtils.jl", "max_stars_repo_head_hexsha": "9908f4ebe678a189f2394f15e5bf8b233233be52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-09-23T12:54:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T12:23:42.000Z", "max_issues_repo_path": "examples/docstrings/imshow.jl", "max_issues_repo_name": "steven-varga/GRUtils.jl", "max_issues_repo_head_hexsha": "f86dfc795eab4af029291b53ab83d02a1305e748", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 56, "max_issues_repo_issues_event_min_datetime": "2019-09-20T09:21:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T11:04:27.000Z", "max_forks_repo_path": "examples/docstrings/imshow.jl", "max_forks_repo_name": "steven-varga/GRUtils.jl", "max_forks_repo_head_hexsha": "f86dfc795eab4af029291b53ab83d02a1305e748", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-02-07T07:03:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-03T01:41:53.000Z", "avg_line_length": 21.0909090909, "max_line_length": 31, "alphanum_fraction": 0.5172413793, "num_tokens": 107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9504109756113862, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7920008435985222}}
{"text": "# This file calculates scattering from the Helmholtz equation via the adaptive spectral method.\n# Δu + k^2u = 0,\n# ∂u∂n|Γ = 0,\n# ∂u^i/∂n = -im k d[2] e^{im k x⋅d},\n# u = u^i + u^s.\n# The normal derivative ∂u/∂n of the entire wave is calculated on the sound-hard boundaries.\n# The scattered wave is calculated by convolving [u] with the fundamental solution.\n# Then, the total wave is obtained by summing the incident and the scattered waves.\n\nusing ApproxFun, SingularIntegralEquations\ninclude(\"Scatteraux.jl\")\n\nk = 50.\nω = 2π\nd = (1,-1)\nd = d[1]/hypot(d[1],d[2]),d[2]/hypot(d[1],d[2])\nui(x,y) = exp(im*k*(d⋅(x,y)))\n\n# The Helmholtz Green's function, split into singular and nonsingular pieces.\ng1(x,y) = besselj0(k*abs(y-x))/2\ng2(x,y) = x == y ? -k^2/4 : -k*besselj1(k*abs(y-x))./abs(y-x)/2\ng3(x,y) = g3neumann(x,y) # In /Scatteraux.jl\ng4old(x,y) = im*k/4*hankelh1(1,k*abs(y-x))./abs(y-x).*imag(y-x)\ng4(x,y) = im*k/4*besselj1(k*abs(y-x))./abs(y-x).*imag(y-x)  # For linesum\ng5(x,y) = -k/2*besselj1(k*abs(y-x))./abs(y-x).*imag(y-x)  # For logkernel\ng6(x,y) = k/2*abs(y-x).*(bessely1(k*abs(y-x)) - 2besselj1(k*abs(y-x)).*logabs(y-x)/π) # For Re{Cauchy}\n\n\ndom = ∪(Interval,[-2.,1.],[-1.,2.])\nsp = Space(dom)\ncwsp,cwsp2 = CauchyWeight(sp⊗sp,0),CauchyWeight(sp⊗sp,2)\n∂ui∂nΓ,⨍ = Fun(t->-im*k*d[2]*ui(real(t),imag(t)),sp),\n                DefiniteLineIntegral(PiecewiseSpace(map(d->JacobiWeight(.5,.5,Ultraspherical(1,d)),dom.domains)))#DefiniteLineIntegral(dom)\n\n@time G = GreensFun(g1,cwsp2;method=:Cholesky) + GreensFun(g2,cwsp;method=:Cholesky) + GreensFun(g3,sp⊗sp;method=:Cholesky)\n\n@time u = ⨍[G]\\-∂ui∂nΓ\nprintln(\"The length of u is: \",length(u))\nus(x,y) = linesum(g4,u,complex(x,y))+logkernel(g5,u,complex(x,y))+π*real(cauchy(g6,real(u),complex(x,y)))+π*im*real(cauchy(g6,imag(u),complex(x,y)))\n#dom += 0im\n", "meta": {"hexsha": "b44f18e0b00b602b3a9de7ce3b48bf0f014be367", "size": 1809, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/HelmholtzNeumann.jl", "max_stars_repo_name": "JuliaPackageMirrors/SingularIntegralEquations.jl", "max_stars_repo_head_hexsha": "eb9e03d887d4450211f73df3569d27d3fa2e8942", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/HelmholtzNeumann.jl", "max_issues_repo_name": "JuliaPackageMirrors/SingularIntegralEquations.jl", "max_issues_repo_head_hexsha": "eb9e03d887d4450211f73df3569d27d3fa2e8942", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/HelmholtzNeumann.jl", "max_forks_repo_name": "JuliaPackageMirrors/SingularIntegralEquations.jl", "max_forks_repo_head_hexsha": "eb9e03d887d4450211f73df3569d27d3fa2e8942", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.1219512195, "max_line_length": 148, "alphanum_fraction": 0.6489773355, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109728022221, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7920008412575766}}
{"text": "# ----------\r\n# Geometry Module, providing Geometry convertion function\r\n# ----------\r\n\r\n\r\n# xyz Coordinetes -> rθz Coordinates\r\nfunction xy_to_polar(ux,uy;Lx=2π,Ly=Lx,T=Float32)   \r\n  nx,ny,nz = size(ux);  \r\n  dev = CPU();\r\n  grid = TwoDGrid(dev, nx, Lx, ny, Ly; T=T)\r\n  Ur,Uθ = xy_to_polar(ux,uy,grid;Lx=2π,Ly=Lx,T=Float32);\r\n  return Ur,Uθ;\r\nend\r\n\r\nfunction xy_to_polar(ux::Array,uy::Array,grid;Lx=2π,Ly=Lx,T=Float32)\r\n#=\r\n  Function for converting x-y vector to r-θ vector, using linear transform\r\n    [x']  =  [cos(θ) -rsin(θ)][r']\r\n    [y']     [sin(θ)  rcos(θ)][θ']\r\n    So e_r =  cosθ ̂i + sinθ ̂j\r\n       e_θ = -sinθ ̂j + cosθ ̂j\r\n=#    \r\n  nx,ny,nz = size(ux);  \r\n  Ur = zeros(T,nx,ny,nz);\r\n  Uθ = zeros(T,nx,ny,nz);\r\n  for j ∈ 1:ny, i ∈ 1:nx\r\n    r = sqrt(grid.x[i]^2+grid.y[j]^2);\r\n    θ = atan(grid.y[j],grid.x[i]) ;\r\n    θ = isnan(θ) ? π/2 : θ;\r\n    sinθ = sin(θ);\r\n    cosθ = cos(θ);    \r\n    Uθ[i,j,:] .= @. -sinθ*ux[i,j,:] + cosθ*uy[i,j,:];    \r\n    Ur[i,j,:] .= @.  cosθ*ux[i,j,:] + sinθ*uy[i,j,:];    \r\n  end\r\n  return Ur,Uθ;\r\nend\r\n", "meta": {"hexsha": "e1905b23ea1f11bf6edad726d935cdc20d638881", "size": 1051, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/GeometryFunction.jl", "max_stars_repo_name": "MHDFlows/MHDFlows", "max_stars_repo_head_hexsha": "0861ca1aae752b5b3f6478ce71d0cb3ad106632e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-28T05:55:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T03:48:38.000Z", "max_issues_repo_path": "src/utils/GeometryFunction.jl", "max_issues_repo_name": "MHDFlows/MHDFlows", "max_issues_repo_head_hexsha": "0861ca1aae752b5b3f6478ce71d0cb3ad106632e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/GeometryFunction.jl", "max_forks_repo_name": "MHDFlows/MHDFlows", "max_forks_repo_head_hexsha": "0861ca1aae752b5b3f6478ce71d0cb3ad106632e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4054054054, "max_line_length": 75, "alphanum_fraction": 0.515699334, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7919809498591591}}
{"text": "# Pawel Zielinski\nmodule matrixgen\n\nusing LinearAlgebra\n\nexport  blockmat\n\n\n\tfunction matcond(n::Int, c::Float64)\n\t\t# Function generates a random square matrix A of size n with\n\t\t# a given condition number c.\n\t\t# Inputs:\n\t\t#\tn: size of matrix A, n>1\n\t\t#\tc: condition of matrix A, c>= 1.0\n\t\t#\n\t\t# Usage: matcond(10, 100.0)\n\t\t#\n\t\t# Pawel Zielinski\n        if n < 2\n         error(\"size n should be > 1\")\n        end\n        if c< 1.0\n         error(\"condition number  c of a matrix  should be >= 1.0\")\n        end\n        (U,S,V)=svd(rand(n,n))\n        return U*diagm(0 =>[LinRange(1.0,c,n);])*V'\n\tend\n\n\n  function blockmat(n::Int, l::Int, ck::Float64, outputfile::String)\n\t\t# Function generates a random block sparse matrix A of size n with\n\t\t# a given condition number ck of inner block Ak and it stores the output\n\t\t# matrix in a text file.\n\t\t# Inputs:\n\t\t#\tn: size of block matrix A, n>3\n\t\t#   l: size of inner matrices Ak, n mod l =0 (n is  divisible by l), l>1\n\t\t#\tck: condition of inner matrix Ak, ck>= 1.0\t\n\t\t# outputfile: name of the output text file\n\t\t#\n\t\t# Usage: blockmat(100, 4 ,10.0, \"A.txt\")\n\t\t#\t\t\n\t\t#\n\t\t#  the output file format\n\t  #  n  l              <--- the size of block matrix A, the size of inner matrices Ak\n\t\t#  i1  j1   A[i1,j1] <--- a non-zero element of block matrix A \n\t\t#  i2  j2   A[i2,j2] <--- a non-zero element of block matrix A \n\t\t#  i3  j3   A[i3,j3] <--- a non-zero element of block matrix A \n\t\t#  ...\n\t\t#  ...\n\t\t#  EOF\n\t\t#\n\t\t\t\t\t\t\t\t\n    if n < 4\n     error(\"size n should be > 3\")\n    end\n    if l < 2\n     error(\"size l should be > 1\")\n    end\n\t\tif n%l!=0 \n\t\t\terror(\"n is not divisible by l\")\n\t\tend\n\t\t\t\t\t\n\t\tnb=div(n,l)\n\t\tAk=Matrix{Float64}(undef, l, l)\t\t\n\t\topen(outputfile, \"w\") do f\n\t\t\tprintln(f, n,\" \",l)\n\t\t\tfor k in 1:nb\n\t\t\t\tAk=matcond(l, ck)\n\t\t\t\tfor i in 1:l, j in 1:l\n\t\t\t\t\tprintln(f,(k-1)*l+i,\" \",(k-1)*l+j,\" \", Ak[i,j])\n\t\t\t\tend\n\t\t\t\tif k<nb\n\t\t\t  \t for i in 1:l\n\t\t\t\t\t\tprintln(f,(k-1)*l+i,\" \",k*l+i,\" \",0.3*rand())\n\t\t\t\t \t end\n\t\t\t\tend\n\t\t\t\tif k>1\n\t\t\t   for i in 1:l\n\t\t\t\t\t println(f,(k-1)*l+i,\" \",(k-1)*l-1,\" \",0.3*rand())\n\t\t\t\t\t println(f,(k-1)*l+i,\" \",(k-1)*l,\" \",0.3*rand())\n\t\t\t\t end\n\t\t\t\tend \n\t\t\tend\n\t\tend\t # do\n\tend # blockmat\n\t\t\n\n \n\nend # matrixgen\n", "meta": {"hexsha": "49398ffe29e049f0ee3d2f820700ef97f57a5053", "size": 2188, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "list5/matrixgen.jl", "max_stars_repo_name": "luk9400/on", "max_stars_repo_head_hexsha": "0f35fb60d020c065c96c54893161a3c41ab77acb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "list5/matrixgen.jl", "max_issues_repo_name": "luk9400/on", "max_issues_repo_head_hexsha": "0f35fb60d020c065c96c54893161a3c41ab77acb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "list5/matrixgen.jl", "max_forks_repo_name": "luk9400/on", "max_forks_repo_head_hexsha": "0f35fb60d020c065c96c54893161a3c41ab77acb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.043956044, "max_line_length": 86, "alphanum_fraction": 0.5466179159, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828604, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7919173761136533}}
{"text": "### A Pluto.jl notebook ###\n# v0.18.0\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local iv = try Base.loaded_modules[Base.PkgId(Base.UUID(\"6e696c72-6542-2067-7265-42206c756150\"), \"AbstractPlutoDingetjes\")].Bonds.initial_value catch; b -> missing; end\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)\n        el\n    end\nend\n\n# ╔═╡ 150d58e7-0e73-4b36-836c-d81eef531a9c\nbegin\n    using Pkg\n\tPkg.activate(joinpath(Pkg.devdir(), \"MLCourse\"))\n    using MLJ, MLJLinearModels, Plots, LinearAlgebra, Random, DataFrames, CSV, MLCourse\n    import MLCourse: Polynomial\nend\n\n\n# ╔═╡ 2e9ce2a9-217e-4910-b6ce-d174f2f2668e\nusing PlutoUI; PlutoUI.TableOfContents()\n\n# ╔═╡ 78bdd11d-b6f9-4ba6-8b2e-6189c4005bf1\nmd\"# Ridge Regression (L2 Regularization)\n\"\n\n# ╔═╡ 64b9cfa0-99f7-439b-b70e-f9266754ff74\nmd\"In the following cell there is some custom code to run ridge regression and the lasso for the simple example of 1-dimensional input. In this example we penalize also the intercept β₀. For ridge regression the solution is\n```math\n\\begin{eqnarray*}\n\\beta_1 &= \\frac{\\langle x y \\rangle - \\frac{\\langle x\\rangle \\langle y\\rangle}{1 + \\lambda}}{\\langle x^2\\rangle - \\frac{\\langle x\\rangle^2}{1 + \\lambda} + \\lambda}\\\\\n\\beta_0 &= \\frac{\\langle y \\rangle - \\beta_1 \\langle x \\rangle}{1 + \\lambda}\n\\end{eqnarray*}\n```\nwhere ``\\langle . \\rangle`` denotes the average.\n\nFor the lasso, there we run a fixed point iteration that starts at the unregularized solution of linear regression and shrinks β₁ and β₀ towards zero until there is not change anymore.\n\"\n\n# ╔═╡ 8bd483cc-f490-11eb-38a1-b342dd2551fd\nbegin\n    function ridge_regression(x, y, λ)\n       β₁ = (mean(x .* y) - mean(x) * mean(y)/(1 + λ))/\n\t\t    (mean(x.^2) - mean(x)^2/(1 + λ) + λ)\n       β₀ = (mean(y) - β₁ * mean(x))/(1 + λ)\n       (β₀ = β₀, β₁ = β₁)\n    end\n    function updateβ₀(x̄, ȳ, β₁, l)\n        tmp = ȳ - β₁ * x̄\n        abs(tmp) > l ? tmp - sign(tmp) * l : 0.\n    end\n    function updateβ₁(x̄, ȳ, x2, xy, β₀, l)\n        tmp = (x̄ * ȳ - xy - x̄ * sign(β₀) * l)\n        abs(tmp) > l ? (tmp - sign(tmp) * l)/(x̄^2 - x2) : 0\n    end\n    function lasso(x, y, λ)\n        x̄ = mean(x)\n        ȳ = mean(y)\n        x2 = mean(x.^2)\n        xy = mean(x .* y)\n        β₁ = (x̄ * ȳ - xy)/(x̄^2 - x2)\n        β₀ = ȳ - β₁ * x̄\n        β₀old, β₁old = zero(β₀), zero(β₁)\n        while β₀old != β₀ || β₁old != β₁\n            β₀old, β₁old = β₀, β₁\n            β₁ = updateβ₁(x̄, ȳ, x2, xy, β₀, λ)\n            β₀ = updateβ₀(x̄, ȳ, β₁, λ)\n        end\n       (β₀ = β₀, β₁ = β₁)\n    end\nend;\n\n# ╔═╡ 3a71618b-0d74-4480-b87b-c6ba87363b5d\nmd\"We generate now some data to observe the effect of regularization when fitting this data.\"\n\n# ╔═╡ 9e1e8284-a8c1-47a9-83d0-2d8fbd8ce005\nn = 30; x = rand(n); y = 2.2x .+ .3 .+ .2randn(n);\n\n# ╔═╡ 1009e251-59af-4f1a-9d0a-e96f4b696cad\nmd\"λ₂ = $(@bind λ₂ Slider(0:.01:5, show_value = true))\"\n\n# ╔═╡ 50ac0b07-ffee-40c3-843e-984b3c628282\nl2coefs = ridge_regression(x, y, λ₂)\n\n# ╔═╡ 58746554-ca5a-4e8e-97e5-587a9c2aa44c\nlet r = λ₂ == 0 ? 6 : norm([l2coefs...]),\n    ccol = plot_color(:blue, .3),\n    path = hcat([[ridge_regression(x, y, l)...] for l in 0:.01:5]...)\n    p1 = scatter(x, y, label = \"data\", xlabel = \"x\", ylabel = \"y\",\n\t             legend = :topleft)\n    plot!(x -> l2coefs.β₀ + x * l2coefs.β₁, w = 3, label = \"ridge regression\")\n    p2 = contour(-1:.1:3, -1:.1:3, (β₀, β₁) -> mean((β₀ .+ β₁*x .- y).^2),\n                 label = \"loss\", title = \"loss with constraints\",\n\t\t         legend = :bottomright,\n                 levels = 100, aspect_ratio = 1, ylims = (-1, 3), xlims = (-1, 3))\n    plot!(t -> r * sin(t), t -> r * cos(t), 0:.001:2π,\n          fill = (0, ccol), label = \"constraint\", color = ccol)\n    plot!(path[1, :], path[2, :], label = \"path\", color = :blue, w = 3)\n    scatter!([l2coefs.β₀], [l2coefs.β₁], label = \"current fit\", markersize = 6, color = :red)\n    p3 = plot(0:.01:5, path[1, :], label = \"β₀\", xlabel = \"λ₂\", ylabel = \"\")\n    plot!(0:.01:5, path[2, :], label = \"β₁\", ylims = (0, 2.4))\n    scatter!([λ₂], [l2coefs.β₀], label = nothing, markersize = 6, color = :red)\n    scatter!([λ₂], [l2coefs.β₁], label = nothing, markersize = 6, color = :red)\n    p4 = contour(-1:.1:3, -1:.1:3, (β₀, β₁) -> mean((β₀ .+ β₁*x .- y).^2) + λ₂ * (β₀^2 + β₁^2),\n                 label = \"loss\", title = \"regularized loss\",\n                 levels = 100, aspect_ratio = 1, ylims = (-1, 3), xlims = (-1, 3))\n    scatter!([l2coefs.β₀], [l2coefs.β₁], markersize = 6, label = nothing, color = :red)\n    plot(p1, p4, p3, p2,\n         layout = (2, 2), size = (700, 600), cbar = false)\nend\n\n# ╔═╡ f43a82e2-1145-426d-8e0e-5363d1c38ccf\nmd\"# Lasso (L1 Regression)\"\n\n# ╔═╡ ff7cc2bf-2a38-46d2-8d11-529159b08c82\nmd\"λ₁ = $(@bind λ₁ Slider(0:.01:1, show_value = true))\"\n\n# ╔═╡ 4841f9ba-f3d2-4c65-9225-bc8d0c0a9478\nl1coefs = lasso(x, y, λ₁)\n\n# ╔═╡ ed2b7969-79cd-43c8-bcdb-34dab89c2cb0\nlet r = λ₁ == 0 ? 10 : norm([l1coefs...], 1),\n    ccol = plot_color(:blue, .3),\n    path = hcat([[lasso(x, y, l)...] for l in 0:.01:1]...)\n    p1 = scatter(x, y, label = \"data\", xlabel = \"x\", ylabel = \"y\", legend = :topleft)\n    plot!(x -> l1coefs.β₀ + x * l1coefs.β₁, w = 3, label = \"lasso\")\n    p2 = contour(-1:.1:3, -1:.1:3, (β₀, β₁) -> mean((β₀ .+ β₁*x .- y).^2),\n                 label = \"loss\", title = \"loss with constraints\",\n\t\t         legend = :topright,\n                 levels = 100, aspect_ratio = 1, ylims = (-1, 3), xlims = (-1, 3))\n    plot!([0, r, 0, -r, 0], [r, 0, -r, 0, r],\n          fill = (0, ccol), label = \"constraint\", color = ccol)\n    plot!(path[1, :], path[2, :], label = \"path\", color = :blue, w = 3)\n    scatter!([l1coefs.β₀], [l1coefs.β₁], label = \"current fit\", markersize = 6,\n\t\t     color = :red)\n    p3 = plot(0:.01:1, path[1, :], label = \"β₀\", xlabel = \"λ₁\", ylabel = \"\")\n    plot!(0:.01:1, path[2, :], label = \"β₁\", ylims = (0, 2.4))\n    scatter!([λ₁], [l1coefs.β₀], label = nothing, markersize = 6, color = :red)\n    scatter!([λ₁], [l1coefs.β₁], label = nothing, markersize = 6, color = :red)\n    p4 = contour(-1:.1:3, -1:.1:3, (β₀, β₁) -> mean((β₀ .+ β₁*x .- y).^2)/2 + λ₁ * (abs(β₀) + abs(β₁)),\n                 label = \"loss\", title = \"regularized loss\",\n                 levels = 100, aspect_ratio = 1, ylims = (-1, 3), xlims = (-1, 3))\n    scatter!([l1coefs.β₀], [l1coefs.β₁], markersize = 6, label = nothing, color = :red)\n    plot(p1, p4, p3, p2,\n         layout = (2, 2), size = (700, 600), cbar = false)\nend\n\n\n# ╔═╡ 4c3c816c-e901-4931-a27c-632b60291ad7\nmd\"Instead of using the custom code to compute the ridge regression and the lasso we could have used some MLJ functions.\"\n\n# ╔═╡ c1033416-334e-4b0e-b81e-6f9137402730\nlet mach = machine(RidgeRegressor(lambda = 3.82, penalize_intercept = true),\n\t               DataFrame(x = x), y)\n\tfit!(mach, verbosity = 0)\n\tfitted_params(mach)\nend\n\n# ╔═╡ 1dae5378-f3eb-4598-a060-445bfd8afe5e\nmd\"Let us check that we get indeed the same result with our custom method.\"\n\n# ╔═╡ 15a85810-ccbd-4aa3-98a5-fdcf68c97adb\nridge_regression(x, y, 3.82)\n\n# ╔═╡ 0429acfe-d31e-427a-96d9-deddfa2c30f8\nlet mach = machine(LassoRegressor(lambda = .1,\n\t                              # usually the intercept is not penalized,\n\t                              # but here we do penalize it.\n\t                              penalize_intercept = true,\n\t                              # usually the default optimizer is quite good,\n\t                              # but here we decrease the tolerance to get \n\t                              # higher precision.\n                                  solver = ISTA(tol = 1e-8)),\n\t            DataFrame(x = x), y)\n\tfit!(mach, verbosity = 0)\n\tfitted_params(mach)\nend\n\n# ╔═╡ 2ba5b965-1dce-4773-b6eb-fd838876674d\nlasso(x, y, .1)\n\n# ╔═╡ 6c87eb35-ddb3-44a3-b4ae-77a371e28960\nmd\"There is also the `ElasticNetRegressor` that allows to fit with L1 and L2 penalties of different strengths. Look up the documentation to learn more about it.\"\n\n# ╔═╡ ca394b88-06dc-4188-884a-50d7c180aa33\nmd\"# Regularization Examples\n\n## Polynomial Ridge Regression\n\nIn `MLJ` can apply ridge regression or the lasso to polynomial regression simply by replacing in the pipeline the `LinearRegressor` with a `RidgeRegressor` or a `LassoRegressor`, for example `mach = Polynomial(degree = 3) |> RidgeRegressor(lambda = 1e-3)`.\"\n\n# ╔═╡ b45a9739-0f81-4c0c-a93b-434a5af91490\nbegin\n    f(x) = .3 * sin(10x) + .7x\n    function regression_data_generator(; n, seed = 3, rng = MersenneTwister(seed))\n        x = rand(rng, n)\n        DataFrame(x = x, y = f.(x) .+ .1*randn(rng, n))\n    end\n    regression_data = regression_data_generator(n = 50)\nend;\n\n# ╔═╡ 3d50111b-3a08-4a41-96ce-d77a8e37275d\nmd\"degree = $(@bind degree Slider(0:20, show_value = true, default = 20))\n\n$(@bind lambda Slider(-14:.1:.5, default = -4))\n\"\n\n# ╔═╡ a54e3439-69b8-41c8-bfe0-4575795fb9b8\nmd\"λ = $(lambda == -14 ? 0 : 10.0^lambda)\"\n\n# ╔═╡ bdbf0dfd-8da5-4e54-89c4-ef4d6b3796ce\nlet X = select(regression_data, Not(:y)), y = regression_data.y\n    mach = fit!(machine(Polynomial(; degree) |> RidgeRegressor(lambda = lambda == -14 ? 0 : 10.0^lambda),\n                        X, y), verbosity = 0)\n    p1 = scatter(regression_data.x, y, label = \"training data\", ylims = (-.1, 1.1))\n    plot!(f, label = \"generator\", c = :green, w = 2)\n    grid = 0:.01:1\n    pred = predict(mach, (x = grid,))\n    plot!(grid, pred,\n          label = \"fit\", w = 3, c = :red, legend = :topleft)\n    annotate!([(.28, .6, \"reducible error ≈ $(round(mean((pred .- f.(grid)).^2), sigdigits = 3))\")])\nend\n\n# ╔═╡ fe2fe54f-0163-4f5d-9fd1-3d1aa3580875\nbegin\n    model = Polynomial() |> RidgeRegressor()\n    self_tuning_model = TunedModel(model = model,\n                                   tuning =  Grid(goal = 500),\n                                   resampling = CV(nfolds = 5),\n                                   range = [range(model, :(polynomial.degree),\n                                                  lower = 1, upper = 20),\n                                            range(model, :(ridge_regressor.lambda),\n                                                  lower = 1e-12, upper = 1e-3,\n                                                  scale = :log)],\n                                   measure = rmse)\n    self_tuning_mach = machine(self_tuning_model,\n                               select(regression_data, :x),\n                               regression_data.y) |> fit!\nend;\n\n# ╔═╡ f5057d4a-1103-4728-becc-287d93d682ba\nplot(self_tuning_mach)\n\n# ╔═╡ bd54bfcd-f682-4b74-8a44-35463d421491\nreport(self_tuning_mach)\n\n# ╔═╡ 596fd0f2-eee0-46ca-a203-e7cbac6f9788\nlet\n    p1 = scatter(regression_data.x, regression_data.y,\n                 label = \"training data\", ylims = (-.1, 1.1))\n    plot!(f, label = \"generator\", c = :green, w = 2)\n    grid = 0:.01:1\n    pred = predict(self_tuning_mach, (x = grid,))\n    plot!(grid, pred,\n          label = \"fit\", w = 3, c = :red, legend = :topleft)\n    annotate!([(.28, .6, \"reducible error ≈ $(round(mean((pred .- f.(grid)).^2), sigdigits = 3))\")])\nend\n\n\n# ╔═╡ 8e170a5a-9c46-413e-895d-796e178b69df\nmd\"## Multiple Logistic Ridge Regression on the Spam Data\n\nWe load here the preprocessed spam data.\n\"\n\n# ╔═╡ 8e542a48-ed28-4297-b2e8-d6a755a5fdf9\nbegin\n    spam_train = CSV.read(joinpath(dirname(pathof(MLCourse)), \"..\", \"data\",\n                                   \"spam_preprocessed.csv\"), DataFrame)\n\tspam_train.spam_or_ham = String.(spam_train.spam_or_ham)\n    coerce!(spam_train, :spam_or_ham => OrderedFactor)\n    spam_test = CSV.read(joinpath(dirname(pathof(MLCourse)), \"..\", \"data\",\n                                  \"spam_preprocessed_test.csv\"), DataFrame)\n\tspam_test.spam_or_ham = String.(spam_test.spam_or_ham)\n    coerce!(spam_test, :spam_or_ham => OrderedFactor)\nend;\n\n# ╔═╡ c5ef5d4e-200d-46d9-86fa-50af1896a6c3\nmd\"The `LogisticClassifier` and the `MultinomialClassifier` have a `penalty` argument that can be used to enforce an L1 or L2 penalty. Look up the documentation to learn more about it.\"\n\n# ╔═╡ d956613e-db32-488c-8ebb-fd61dfa31e59\nspam_fit = fit!(machine(LogisticClassifier(penalty = :l2, lambda = 1e-5),\n                        select(spam_train, Not(:spam_or_ham)),\n                        spam_train.spam_or_ham));\n\n# ╔═╡ 552f14fc-06c7-4c2a-9515-e64f28828b70\nconfusion_matrix(predict_mode(spam_fit, select(spam_train, Not(:spam_or_ham))),\n                 spam_train.spam_or_ham)\n\n# ╔═╡ ef701511-db7e-4dc0-8d31-ea14471943ab\nconfusion_matrix(predict_mode(spam_fit, select(spam_test, Not(:spam_or_ham))),\n                 spam_test.spam_or_ham)\n\n# ╔═╡ 19bdd76c-4131-422d-983e-1b29cd9edd30\nmd\"We see that the test misclassification rate with regularization\nis lower than in our original fit without regularization\n(notebook \\\"Generalized Linear Regression\\\"; 48 false negatives and 48 false\npositives). The misclassification rate on the training set is higher. This\nindicates that unregularized logistic regression is too flexible for our spam\ndata set.\n\"\n\n# ╔═╡ 13655a50-fbbb-46c7-bdf7-ed5644646966\nmd\"## The Lasso Path for the Weather Data\n\nFor the Lasso it is often interesting to see the fitted parameter values for different regularization values (the Lasso path). In the following we use the package `GLMNet` to do so.\"\n\n# ╔═╡ 1fa932c1-ce29-40ca-a8dc-e636aa2ecf66\nweather = CSV.read(joinpath(@__DIR__, \"..\", \"data\", \"weather2015-2018.csv\"), DataFrame);\n\n# ╔═╡ 470dc7f4-04a9-4253-8125-9112778021eb\nimport GLMNet: glmnet\n\n# ╔═╡ ecf80b6a-1946-46fd-b1b4-bcbe91848e3c\nbegin\n    weather_input = select(weather, Not(:LUZ_wind_peak))[1:end-5, :]\n    weather_output = weather.LUZ_wind_peak[6:end]\n    weather_fits = glmnet(Array(weather_input), weather_output)\nend\n\n# ╔═╡ 4652a904-5edb-463c-a046-5c5d378f7cca\nlet lambda = log.(weather_fits.lambda),\n    col_names = names(weather_input)\n    plotly()\n    p = plot()\n    for i in 1:size(weather_fits.betas, 1)\n        plot!(lambda, weather_fits.betas[i, :], label = col_names[i])\n    end\n    plot!(legend = :outertopright, xlabel = \"log(λ)\", size = (700, 400))\n    gr()\n    p\nend\n\n# ╔═╡ 40bb385f-1cbd-4555-a8ab-544a67f33595\nlet lambda = log.(weather_fits.lambda)\n    p1 = plot(lambda, 100 * weather_fits.dev_ratio, ylabel = \"% variance explained\")\n    p2 = plot(lambda, reshape(sum(weather_fits.betas .!= 0, dims = 1), :),\n              ylabel = \"non-zero parameters\",\n              xlabel = \"log(λ)\")\n    plot(p1, p2, layout = (2, 1), legend = false)\nend\n\n# ╔═╡ c9ed011c-8d36-4926-9ec4-84be3b4878d7\nscatter(weather_input.BER_wind_peak, weather_output)\n\n# ╔═╡ 8262b948-6d54-4348-87d1-4c762c74db30\nmd\"# Exercises\n\n## Conceptual\n\n#### Exercise 1.\nWe review here the two formulations of regularization.\nA standard approach to solve constraint optimization\nproblems makes use of Karush-Kuhn-Tucker (KKT) multipliers. For example, to find\nthe minimum of function ``f(x)`` under the constraint ``g(x) \\leq s`` one can define\nthe loss function ``L(x, \\lambda) = f(x) + \\lambda(g(x) - s)`` where\n``\\lambda\\geq0`` is a KKT multiplier.  Minimizing the loss both in ``x`` and\n``\\lambda`` amounts to solving the equations ``\\frac{\\partial L}{\\partial x} = f'(x) + \\lambda g'(x) = 0`` and ``\\frac{\\partial L}{\\partial \\lambda} = g(x) - s = 0``,\nif the solution is on the boundary of the area defined by the inequality\nconstraint; otherwise one can find the solution by simply solving the\nunconstrained problem, i.e. with ``\\lambda = 0``. In this formulation one choses\nthe size ``s`` of the allowed area and finds ``\\lambda`` by solving the equations.\n\nInterestingly, the loss function ``L(x) = f(x) + \\lambda\ng(x)`` has exactly the same partial derivative in ``x`` as ``L(x, \\lambda)`` and\ntherefore all critical points of ``L(x)`` have corresponding critical\npoints of ``L(x,\\lambda)``. Because of this, regularization is often formulated\nas \\\"adding a regularization term to the cost function\\\". For example, given the loss\n    function of linear regression ``L(\\beta) = \\frac1n\\sum_{i=1}^n(y_i - \\beta_0 + \\beta_1x_{i1} + \\cdots + \\beta_p x_{ip})^2`` one can define the\n        L1-regularized loss function ``L_\\mathrm{L1}(\\beta) = L(\\beta) + \\lambda\n\\|\\beta\\|_1`` and choose a value for ``\\lambda`` instead of the size ``s`` of the\nallowed area.\n\n1. Derive how ``\\lambda`` in the second formulation depends on ``s`` in the first formulation for ridge regression with standardized one-dimensional input. *Hint:* use the analytical solution at the top of this notebook, the fact that ``\\langle x \\rangle = 0`` and ``\\langle x^2\\rangle = 0`` and note that ``\\beta_0^2 + \\beta_1^2 = s``, if the solution lies on the boundary.\n1. Argue, why choosing ``\\lambda = 0`` in the second formulation is equivalent to choosing a sufficiently large ``s`` in the first formulation.\n2. Argue, why choosing ``\\lambda = \\infty`` in the second formulation is equivalent to choosing ``s = 0`` in the first formulation.\n\n#### Exercise 2.\nConsider a data set with as many data points as predictors ``n = p``.\nAssume ``x_{ii} = 1`` and ``x_{ij} = 0`` for all ``i\\neq j`` and arbitrary values\n``y_i``. To simplify the problem further we perform regression without an\nintercept. We would like to study L1- and L2-regularized multiple linear regression.\n\n1. Write the mean squared error loss once with L1 regularization and once with L2 regularization for this setting and the fomulation of regularization with regularization constant ``\\lambda``.\n2. Show that in the case of L2 regularization the estimated coefficients take the form ``\\hat \\beta_j = y_j/(1 + \\lambda)``.\n3. Show that in the case of L1 regularization the estimated coefficients take the form ``\\hat \\beta_j = y_j - \\lambda/2``, if ``y_j > \\lambda/2``, ``\\hat \\beta_j = y_j + \\lambda/2``, if ``y_j < -\\lambda/2`` and ``\\hat \\beta_j = 0`` otherwise.\n4. Write a brief summary on how the estimated coefficients ``\\hat \\beta_j`` are changed relative to the unregularized solution for both kinds of regularization.\n\n## Applied\n\n#### Exercise 1.\nCreate an artificial dataset with 20 points, 4 predictors ``X_1, X_2, X_3, X_4``\nand ``Y = X_1 + \\epsilon`` with ``\\mathrm{Var}(\\epsilon) = 0.1^2``.\n\n1. Find with cross-validation and the lasso the best model.\n2. Find with cross-validation and the ridge regression the best model.\n3. Which of the two best models has the lowest reducible error?\n4. Repeat the above 3 steps on an artificial data set with 20 points and 4 predictors with ``Y = 10X_1 + X_2 + .1 * X_3 + .01 * X_4 + \\epsilon``.\n\"\n\n# ╔═╡ e04c5e8a-15f8-44a8-845d-60acaf795813\nMLCourse.list_notebooks(@__FILE__)\n\n# ╔═╡ c48dff95-8028-4e97-8ec6-705ea2b9c72e\nMLCourse.footer()\n\n# ╔═╡ Cell order:\n# ╟─2e9ce2a9-217e-4910-b6ce-d174f2f2668e\n# ╠═150d58e7-0e73-4b36-836c-d81eef531a9c\n# ╟─78bdd11d-b6f9-4ba6-8b2e-6189c4005bf1\n# ╟─64b9cfa0-99f7-439b-b70e-f9266754ff74\n# ╠═8bd483cc-f490-11eb-38a1-b342dd2551fd\n# ╟─3a71618b-0d74-4480-b87b-c6ba87363b5d\n# ╠═9e1e8284-a8c1-47a9-83d0-2d8fbd8ce005\n# ╟─1009e251-59af-4f1a-9d0a-e96f4b696cad\n# ╠═50ac0b07-ffee-40c3-843e-984b3c628282\n# ╟─58746554-ca5a-4e8e-97e5-587a9c2aa44c\n# ╟─f43a82e2-1145-426d-8e0e-5363d1c38ccf\n# ╟─ff7cc2bf-2a38-46d2-8d11-529159b08c82\n# ╠═4841f9ba-f3d2-4c65-9225-bc8d0c0a9478\n# ╟─ed2b7969-79cd-43c8-bcdb-34dab89c2cb0\n# ╟─4c3c816c-e901-4931-a27c-632b60291ad7\n# ╠═c1033416-334e-4b0e-b81e-6f9137402730\n# ╟─1dae5378-f3eb-4598-a060-445bfd8afe5e\n# ╠═15a85810-ccbd-4aa3-98a5-fdcf68c97adb\n# ╠═0429acfe-d31e-427a-96d9-deddfa2c30f8\n# ╠═2ba5b965-1dce-4773-b6eb-fd838876674d\n# ╟─6c87eb35-ddb3-44a3-b4ae-77a371e28960\n# ╟─ca394b88-06dc-4188-884a-50d7c180aa33\n# ╠═b45a9739-0f81-4c0c-a93b-434a5af91490\n# ╟─3d50111b-3a08-4a41-96ce-d77a8e37275d\n# ╟─a54e3439-69b8-41c8-bfe0-4575795fb9b8\n# ╟─bdbf0dfd-8da5-4e54-89c4-ef4d6b3796ce\n# ╠═fe2fe54f-0163-4f5d-9fd1-3d1aa3580875\n# ╠═f5057d4a-1103-4728-becc-287d93d682ba\n# ╠═bd54bfcd-f682-4b74-8a44-35463d421491\n# ╟─596fd0f2-eee0-46ca-a203-e7cbac6f9788\n# ╟─8e170a5a-9c46-413e-895d-796e178b69df\n# ╠═8e542a48-ed28-4297-b2e8-d6a755a5fdf9\n# ╟─c5ef5d4e-200d-46d9-86fa-50af1896a6c3\n# ╠═d956613e-db32-488c-8ebb-fd61dfa31e59\n# ╠═552f14fc-06c7-4c2a-9515-e64f28828b70\n# ╠═ef701511-db7e-4dc0-8d31-ea14471943ab\n# ╟─19bdd76c-4131-422d-983e-1b29cd9edd30\n# ╟─13655a50-fbbb-46c7-bdf7-ed5644646966\n# ╠═1fa932c1-ce29-40ca-a8dc-e636aa2ecf66\n# ╠═470dc7f4-04a9-4253-8125-9112778021eb\n# ╠═ecf80b6a-1946-46fd-b1b4-bcbe91848e3c\n# ╟─4652a904-5edb-463c-a046-5c5d378f7cca\n# ╟─40bb385f-1cbd-4555-a8ab-544a67f33595\n# ╠═c9ed011c-8d36-4926-9ec4-84be3b4878d7\n# ╟─8262b948-6d54-4348-87d1-4c762c74db30\n# ╟─e04c5e8a-15f8-44a8-845d-60acaf795813\n# ╟─c48dff95-8028-4e97-8ec6-705ea2b9c72e\n", "meta": {"hexsha": "aa86b4cede504d9608668d1bb0727f7eb4fc37e7", "size": 20711, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/regularization.jl", "max_stars_repo_name": "baltisberger/MLCourse", "max_stars_repo_head_hexsha": "9a2efad0f3d241503ad2fbce4f2d875d4332045b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/regularization.jl", "max_issues_repo_name": "baltisberger/MLCourse", "max_issues_repo_head_hexsha": "9a2efad0f3d241503ad2fbce4f2d875d4332045b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/regularization.jl", "max_forks_repo_name": "baltisberger/MLCourse", "max_forks_repo_head_hexsha": "9a2efad0f3d241503ad2fbce4f2d875d4332045b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9262472885, "max_line_length": 374, "alphanum_fraction": 0.6399980687, "num_tokens": 7807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984213, "lm_q2_score": 0.874077230244524, "lm_q1q2_score": 0.7919050794865728}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 0d696b90-14b9-11eb-19c6-7110e9eded9e\nusing PotentialFlow\n\n# ╔═╡ 40e53300-14b9-11eb-28ca-c39ecf8c05ef\nusing Plots\n\n# ╔═╡ 59e4bc40-14b9-11eb-3670-cdc8fa8f0ded\nbegin\n\tX = range(-1, 1, length=101)\n\tY = range(-1, 1, length=101)\n\tZ = [x + im*y for y in Y, x in X]\nend\n\n# ╔═╡ 27ebaaf0-14be-11eb-3b42-d3c031377d61\nbegin\n\t\n\tv2 = Vortex.Point(0.0, 2)\n    \n\tψ = streamfunction(Z,v2)\n\t\n\tcontour(X, Y, ψ,\n\t\tcolor = cgrad([:red, :blue]), \n\t\tgrid = false, \n\t\tlegend = false, \n\t\tratio = 1,\n\t\txlim = (-1, 1),\n\t\tylim = (-1, 1),)\n\n\nend\n\n# ╔═╡ 2e843420-1538-11eb-14b2-d9ab38fa091b\nbegin\n\t\n\tvs = Vortex.Point.(rand(ComplexF64, 10), π*rand(10))\n    fs = Freestreams.Freestream(rand(ComplexF64))\n\t\n\tψs = streamfunction(Z,(vs,fs))\n\t\n\tcontour(X, Y, ψs,\n\t\tcolor = cgrad([:red, :blue]), \n\t\tgrid = false, \n\t\tlegend = false, \n\t\tratio = 1,\n\t\txlim = (0, 1),\n\t\tylim = (0, 1),)\n\n\nend\n\n# ╔═╡ e0cf3580-1538-11eb-1ba8-1baff87ba9e1\nmd\"\"\" \n### Flow over a cylinder \n\"\"\"\n\n# ╔═╡ Cell order:\n# ╠═0d696b90-14b9-11eb-19c6-7110e9eded9e\n# ╠═40e53300-14b9-11eb-28ca-c39ecf8c05ef\n# ╠═59e4bc40-14b9-11eb-3670-cdc8fa8f0ded\n# ╠═27ebaaf0-14be-11eb-3b42-d3c031377d61\n# ╠═2e843420-1538-11eb-14b2-d9ab38fa091b\n# ╟─e0cf3580-1538-11eb-1ba8-1baff87ba9e1\n", "meta": {"hexsha": "8076ef3d2604d557e1f472040f9861dbcea2f37e", "size": 1281, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Elementary_Potential_Flows_Streamlines.jl", "max_stars_repo_name": "kursatkara/MAE-5943-Unsteady-Aerodynamics", "max_stars_repo_head_hexsha": "539bd5bb7498312a99f2b91b2271046d01575e0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-10-08T14:41:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-11T19:27:14.000Z", "max_issues_repo_path": "Elementary_Potential_Flows_Streamlines.jl", "max_issues_repo_name": "kursatkara/MAE-5943-Unsteady-Aerodynamics", "max_issues_repo_head_hexsha": "539bd5bb7498312a99f2b91b2271046d01575e0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Elementary_Potential_Flows_Streamlines.jl", "max_forks_repo_name": "kursatkara/MAE-5943-Unsteady-Aerodynamics", "max_forks_repo_head_hexsha": "539bd5bb7498312a99f2b91b2271046d01575e0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-24T00:29:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-16T04:05:26.000Z", "avg_line_length": 18.5652173913, "max_line_length": 53, "alphanum_fraction": 0.6463700234, "num_tokens": 657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7918873482101201}}
{"text": "\n\"\"\"\nProblema de asignación. (Vanderbei LP, pg. 227). Dado un conjunto S de m personas, un conjunto D de m tareas, y para cada iS,jD un costo cij de asignar la tarea j a la persona i, el problema de asignación consiste en asignar a cada persona una y solo una tarea, de manera tal que se minimize el costo total. Formule este problema como un problema de programación lineal con enteros. Escriba una función para resolverlo, que tome como entrada una matriz de costos cij arbitraria.\n\n\"\"\"\n\nexport solve_with_lineal_programming;\nfunction solve_with_lineal_programming(m::Matrix{T}) where {T<:Number}\n\n\t#Checking matrix\n\tcheckmatrix(m);\n\tml = size(m,1);\n\t\n\t#Create model\n\tlocal model = Model(with_optimizer(GLPK.Optimizer));\n\n\t#Variables\n\t@variable(model, x[1:ml,1:ml], Bin);\n\n\t#Objective\n\t@objective(model, Min, sum(m[i,j] * x[i,j] for i in 1:ml, j in 1:ml));\n\n\t#Constrains\n\t@constraint(model, [i=1:ml], sum(x[i,j] for j in 1:ml) <= 1);\n\t@constraint(model, [j=1:ml], sum(x[i,j] for i in 1:ml) >= 1);\n\n\t#Optimize\n\toptimize!(model);\n\n\treturn pick_results(value.(x),m);\nend\n\nfunction pick_results(bm,m)\n\tr = Vector{eltype(m)}();\n\tzer0 = zero(eltype(m));\n\tfor i in 1:length(bm)\n\t\tbm[i] != zer0 && push!(r,m[i]);\n\tend\n\treturn push!(Vector{typeof(r)}(),r);\nend", "meta": {"hexsha": "74a0b40c86a70d319748c37a528e9cd02118b8f1", "size": 1253, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LinearProgramming.jl", "max_stars_repo_name": "josePereiro/AssigmentProblem.jl", "max_stars_repo_head_hexsha": "1ce6f1e671798ceb943c5d5b712e43b5b21be8c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LinearProgramming.jl", "max_issues_repo_name": "josePereiro/AssigmentProblem.jl", "max_issues_repo_head_hexsha": "1ce6f1e671798ceb943c5d5b712e43b5b21be8c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LinearProgramming.jl", "max_forks_repo_name": "josePereiro/AssigmentProblem.jl", "max_forks_repo_head_hexsha": "1ce6f1e671798ceb943c5d5b712e43b5b21be8c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.325, "max_line_length": 478, "alphanum_fraction": 0.7015163607, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167044, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7918873413627942}}
{"text": "###############################################################################\n#\n# The primary module for computing the Riemann theta function.\n#\n# .. math::\n#\n#   Θ(z, ω) = Σ\n    # \\theta(z, \\Omega) = \\sum_{n \\in \\mathbb{Z}^g}\n                        # e^{2 \\pi i \\left( \\tfrac{1}{2} n \\cdot \\Omega n\n                           # + n \\cdot z \\right)}\n#\n#\n#  Original Authors\n#  -------\n#  * Chris Swierczewski (@cswiercz) - September 2012, July 2016\n#  * Grady Williams (@gradyrw) - October 2012\n#  * Jeremy Upsal (@jupsal) - July 2016\n#\n# References\n# ----------\n#\n# .. [CRTF] B. Deconinck, M.  Heil, A. Bobenko, M. van Hoeij and M. Schmies,\n#    Computing Riemann Theta Functions, Mathematics of Computation, 73, (2004),\n#    1417-1442.\n#\n# .. [DLMF] B. Deconinck, Digital Library of Mathematics Functions - Riemann\n#    Theta Functions, http://dlmf.nist.gov/21\n#\n# .. [SAGE] Computing Riemann theta functions in Sage with applications.\n#    C. Swierczewski and B. Deconinck.Submitted for publication.  Available\n#    online at\n#    http://depts.washington.edu/bdecon/papers/pdfs/Swierczewski_Deconinck1.pdf\n#\n###############################################################################\n\n\"\"\"\n         oscillatory_part(zs::Vector{Vector{ComplexF64}},\n                          Ω::Matrix{ComplexF64};\n                          eps::Float64=1e-8,\n                          derivs::Vector{Vector{ComplexF64}}=Vector{ComplexF64}[],\n                          accuracy_radius::Float64=5.)::Vector{ComplexF64}\n\nReturn the value of the oscillatory part of the Riemann theta function for Ω and\nall z in `zs` if `derivs` is empty, or the derivatives at all z in `zs` for the\ngiven directional derivatives in `derivs`.\n\nParameters\n----------\n- `zs` : A vector of complex vectors at which to evaluate the Riemann theta function.\n- `Omega` : A Riemann matrix.\n- `eps` : (Default: 1e-8) The desired numerical accuracy.\n- `derivs` : A vector of complex vectors giving a directional derivative.\n- `accuracy_radius` : (Default: 5.) The radius from the g-dimensional origin\nwhere the requested accuracy of the Riemann theta is guaranteed when computing\nderivatives. Not used if no derivatives of theta are requested.\n\nReturns\n-------\n- The value of the oscillatory part of the Riemann theta function at each point appearing in `z`.\n\"\"\"\nfunction oscillatory_part(zs::Vector{Vector{ComplexF64}},\n                          Ω::Matrix{ComplexF64};\n                          eps::Float64=1e-8,\n                          derivs::Vector{Vector{ComplexF64}}=Vector{ComplexF64}[],\n                          accuracy_radius::Float64=5.)\n    # extract the requested information: the real part, inverse of the\n    # imaginary part, and the cholesky decomposition of the imaginary part\n    X = real.(Ω)\n    Y = imag.(Ω)\n\n    # In python version numpy.linalg.cholesky returns the lower triangular\n    #  matrix, which is then transposed. Julia's cholesky returns the upper\n    #  triangular matrix, hence no need to transpose.\n    T = Matrix(cholesky(Y).U)\n\n    Yinv = inv(Y)\n\n    # compute the integer points over which we approximate the infinite sum to\n    # the requested accuracy\n    R = radius(eps, T, derivs, accuracy_radius)\n    S = innerpoints(T, R)\n\n    finite_sum(X, Yinv, T, zs, S, derivs)\nend\n\n\n\"\"\"\n         exponential_part(zs::Vector{Vector{ComplexF64}},\n                          Ω::Matrix{ComplexF64})::Vector{Float64}\n\nReturn the value of the exponential part of the Riemann theta function for Ω and\nall z in `zs`.\n\nParameters\n----------\n- `zs` : A vector of complex vectors at which to evaluate the Riemann theta function.\n- `Omega` : A Riemann matrix.\n\nReturns\n-------\nThe value of the exponential part of the Riemann theta function at\neach point appearing in `zs`.\n\n\"\"\"\nfunction exponential_part(zs::Vector{Vector{ComplexF64}},\n                          Ω::Matrix{ComplexF64})::Vector{Float64}\n    # extract the imaginary parts of z and the inverse of the imaginary part\n    # of Omega\n    y = [ imag.(z) for z in zs ]\n    Yinv = inv(imag.(Ω))\n\n    # apply the quadratic form to each vector in z\n    map(y -> π * dot(y, Yinv * y), y)\nend\n\n\n\"\"\"\n     riemanntheta(zs::Vector{Vector{ComplexF64}},\n                  Ω::Matrix{ComplexF64};\n                  eps::Float64=1e-8,\n                  derivs::Vector{Vector{ComplexF64}}=Vector{ComplexF64}[],\n                  accuracy_radius::Float64=5.)::Vector{ComplexF64}\n\nReturn the value of the Riemann theta function for Ω and all z in `zs` if\n`derivs` is empty, or the derivatives at all z in `zs` for the given directional\nderivatives in `derivs`.\n\nParameters\n----------\n- `zs` : A vector of complex vectors at which to evaluate the Riemann theta function.\n- `Omega` : A Riemann matrix.\n- `eps` : (Default: 1e-8) The desired numerical accuracy.\n- `derivs` : A vector of complex vectors giving a directional derivative.\n- `accuracy_radius` : (Default: 5.) The radius from the g-dimensional origin\nwhere the requested accuracy of the Riemann theta is guaranteed when computing\nderivatives. Not used if no derivatives of theta are requested.\n\nReturns\n-------\nThe value (or derivative) of the Riemann theta function at each point in `zs`.\n\"\"\"\nfunction riemanntheta(zs::Vector{Vector{ComplexF64}},\n                      Ω::Matrix{ComplexF64};\n                      eps::Float64=1e-8,\n                      derivs::Vector{Vector{ComplexF64}}=Vector{ComplexF64}[],\n                      accuracy_radius::Float64=5.)::Vector{ComplexF64}\n\n    u = exponential_part(zs, Ω)\n    v = oscillatory_part(zs, Ω, eps=eps, derivs=derivs,\n                         accuracy_radius=accuracy_radius)\n\n    exp.(u) .* v\nend\n", "meta": {"hexsha": "a0b8ac105383ead69fbfc39b8fb45bffa99ebe4f", "size": 5639, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/main.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/RiemannTheta.jl-803aa692-84f0-5eed-9cc1-fbb46710dded", "max_stars_repo_head_hexsha": "af371a543767493c495f535ada2ce896a27644e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/RiemannTheta.jl-803aa692-84f0-5eed-9cc1-fbb46710dded", "max_issues_repo_head_hexsha": "af371a543767493c495f535ada2ce896a27644e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/RiemannTheta.jl-803aa692-84f0-5eed-9cc1-fbb46710dded", "max_forks_repo_head_hexsha": "af371a543767493c495f535ada2ce896a27644e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6168831169, "max_line_length": 97, "alphanum_fraction": 0.6235148076, "num_tokens": 1515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.855851148805615, "lm_q1q2_score": 0.7918591163930422}}
{"text": "# \n# Linear fit\n#\n\nstruct Linear\n  a :: Float64\n  b :: Float64\n  R :: Float64\n  x :: Vector{Float64}\n  y :: Vector{Float64}\n  ypred :: Vector{Float64}\n  residues :: Vector{Float64}\nend\n\n\"\"\"\n`fitlinear(x,y)`\n\nObtains the linear fit: ``y = a*x + b``\n\nOptional lower and upper bounds for a, and constant b can be provided using, for example:\n\n```\nfitlinear(x,y, l=lower(a=0.), b=3)\n```\n\n# Examples\n```jldoctest\njulia> x = sort(rand(10)) ; y = sort(rand(10));\n\njulia> fit = fitlinear(x,y)\n\n------------------- Linear Fit ------------- \n\nEquation: y = ax + b \n\nWith: a = 1.0448783208110997\n      b = 0.18817627115683894\n\nPearson correlation coefficient, R = 0.8818586822210751\nAverage absolute residue = 0.14274752107157443\n\nPredicted Y: ypred = [0.1987357699444139, 0.32264343301109627...\nresidues = [0.1613987313816987, 0.22309410865095275...\n\n-------------------------------------------- \n\n```\n\"\"\"\nfunction fitlinear(X :: AbstractArray{<:Real}, Y :: AbstractArray{<:Real}; \n                   l :: lower = lower(), u :: upper = upper(), b = nothing,\n                   options :: Options = Options() )\n  # Check data\n  X, Y = checkdata(X,Y,options)\n  # Set bounds\n  vars = [ VarType(:a,Number,1), \n           VarType(:b,Nothing,1) ]\n  lower, upper = setbounds(vars,l,u)\n  if b == nothing\n    # Set model\n    @. model(x,p) = p[1]*x + p[2]\n    # Initial point\n    p0 = Vector{Float64}(undef,2)\n    initP!(p0,options,lower,upper)\n    # Fit\n    fit = curve_fit(model, X, Y, p0, lower=lower, upper=upper)\n    # Analyze results and return\n    R = pearson(X,Y,model,fit)\n    x, y, ypred = finexy(X,length(X),model,fit)\n    return Linear(fit.param...,R,x,y,ypred,fit.resid)\n  else\n    lower = [lower[1]]; upper = [upper[1]];\n    # Set model\n    @. model_const(x,p) = p[1]*x + b \n    # Initial point\n    p0 = Vector{Float64}(undef,1)\n    initP!(p0,options,lower,upper)\n    # Fit\n    fit = curve_fit(model_const, X, Y, p0, lower=lower, upper=upper)\n    # Analyze results and return\n    R = pearson(X,Y,model_const,fit)\n    x, y, ypred = finexy(X,length(X),model_const,fit)\n    return Linear(fit.param...,b,R,x,y,ypred,fit.resid)\n  end\nend\n\nfunction Base.show( io :: IO, fit :: Linear )\n  println(\"\")\n  println(\" ------------------- Linear Fit ------------- \")\n  println(\"\")\n  println(\" Equation: y = ax + b \")\n  println(\"\")\n  println(\" With: a = \", fit.a)\n  println(\"       b = \", fit.b)\n  println(\"\")\n  println(\" Pearson correlation coefficient, R = \", fit.R)\n  println(\" Average square residue = \", mean(fit.residues.^2))\n  println(\"\")\n  println(\" Predicted Y: ypred = [\",fit.ypred[1],\", \",fit.ypred[2],\"...\")\n  println(\" residues = [\", fit.residues[1],\", \",fit.residues[2],\"...\")\n  println(\"\")\n  println(\" -------------------------------------------- \")\nend\n\nexport fitlinear\n", "meta": {"hexsha": "772ed26bcd4653ddbba5f26d8b71b2cba5d42283", "size": 2767, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fitlinear.jl", "max_stars_repo_name": "m3g/EasyF", "max_stars_repo_head_hexsha": "601df86cb3927a195d91558a4027bb5e949771c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-04-07T12:58:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T13:42:50.000Z", "max_issues_repo_path": "src/fitlinear.jl", "max_issues_repo_name": "m3g/EasyF", "max_issues_repo_head_hexsha": "601df86cb3927a195d91558a4027bb5e949771c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-17T14:34:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-24T14:19:10.000Z", "max_forks_repo_path": "src/fitlinear.jl", "max_forks_repo_name": "m3g/EasyFit.jl", "max_forks_repo_head_hexsha": "601df86cb3927a195d91558a4027bb5e949771c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-08-19T20:58:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-17T18:43:12.000Z", "avg_line_length": 26.3523809524, "max_line_length": 89, "alphanum_fraction": 0.5746295627, "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7918591112267224}}
{"text": "### ADAPTIVE GAUSS-LOBATTO FROM GANDER AND GAUTSCHI (2000)\n\n### constants from section 4 of the paper\nconst α = sqrt(2/3)\nconst β = 1/sqrt(5)\n\nconst X1 = 0.94288241569547971905635175843185720232\nconst X2 = 0.64185334234578130578123554132903188354\nconst X3 = 0.23638319966214988028222377349205292599\n\nconst A = 0.015827191973480183087169986733305510591\nconst B = 0.094273840218850045531282505077108171960\nconst C = 0.155071987336585396253963597980210298680\nconst D = 0.18882157396018245442000533937297167125\nconst E = 0.199773405226858526792068022066048840246\nconst F = 0.22492646533333952701601768799639508076\nconst G = 0.24261107190140773379964095790325635233\n\n\n\n\n\"\"\"\n    adaptlob(f,a,b; tol::Real=1e-10, trace::Bool=false)\n\nNumerically integrate `f` over the closed real interval `[a,b]` to within tolerance `tol` using the adaptive Gauss-Lobatto method from Gander and Gautschi (2000).\n\nPassing `trace=true` prints out information about where the function is being sampled.\n\n`f` must be defined at `a` and `b`.\n\n```\nusing QuadGG\nadaptlob(sqrt,0,1)\n```\n\"\"\"\nfunction adaptlob(f,a,b; tol::Real=1e-10, trace::Bool=false)\n    m = (a+b)/2\n    h = (b-a)/2\n\n    x = (a,m-X1*h,m-α*h,m-X2*h,m-β*h,m-X3*h,m,m+X3*h,m+β*h,m+X2*h,m+α*h,m+X1*h,b)\n    y = f.(x)\n\n    \n    fa,fb = y[1],y[end]\n\n    _i2 = (h/6) * (y[1] + y[13] + 5*(y[5]+y[9]))\n    _i1 = (h/1470) * (77*(y[1]+y[13]) + 432*(y[3]+y[11]) + 625 * (y[2]+y[12]) + 672*y[7])\n\n    _is = h * (A*(y[1]+y[13]) + B*(y[2]+y[12]) + C*(y[3]+y[11]) + D*(y[4]+y[10]) + E*(y[5]+y[9]) + F*(y[6]+y[8]) + G*y[7])\n\n    sgn = sign(_is)\n    sgn = ifelse(iszero(sgn),1,sgn)\n    erri1 = abs(_i1 - _is)\n    erri2 = abs(_i2 - _is)\n    \n    R = ifelse(!iszero(erri2), erri1/erri2, 1)\n\n    if 0 < R < 1\n        tol = tol/R\n    end\n\n    _is_new = sgn * abs(_is) * tol / eps()\n\n    if iszero(_is_new)\n        _is_new = b-a\n    end\n\n    flag = WarnFlag(false)\n    Q = adaptlobstp(f,a,b,fa,fb,_is_new,trace,flag)\n    return Q\nend\n\n\nfunction adaptlobstp(f,a,b,fa,fb,_is,trace,flag)\n    m = (a+b)/2\n    h = (b-a)/2\n\n    mll = m-α*h\n    ml = m-β*h\n    mr = m+β*h\n    mrr = m+α*h\n\n    fmll = f(mll)\n    fml = f(ml)\n    fm = f(m)\n    fmr = f(mr)\n    fmrr = f(mrr)\n\n    i2=(h/6)*(fa+fb+5*(fml+fmr))\n    i1=(h/1470)*(77*(fa+fb)+432*(fmll+fmrr)+625*(fml+fmr)+672*fm)\n\n    if ≈(_is+i1-i2, _is, atol=1e-16) || mll <= a || b <= mrr || !isfinite(_is)\n        if (m <= a || b <= m) && !flag.nowarn\n            @warn \"Interval contains no more machine numbers. Required tolerance may not be met.\"\n            flag.nowarn = true\n        end\n        Q = i1\n        trace && @printf \"%20.15f    %20.15f    %20.15f\\n\" a b-a Q\n    else\n        Q = adaptlobstp(f,a,mll,fa,fmll,_is,trace,flag) +\n            adaptlobstp(f,mll,ml,fmll,fml,_is,trace,flag) +\n            adaptlobstp(f,ml,m,fml,fm,_is,trace,flag) +\n            adaptlobstp(f,m,mr,fm,fmr,_is,trace,flag) +\n            adaptlobstp(f,mr,mrr,fmr,fmrr,_is,trace,flag) +\n            adaptlobstp(f,mrr,b,fmrr,fb,_is,trace,flag)\n    end\n    return Q\nend", "meta": {"hexsha": "ac73eb5fae9f0e07baaa1080fdade04126914720", "size": 3004, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/adaptlob.jl", "max_stars_repo_name": "tbeason/QuadGG.jl", "max_stars_repo_head_hexsha": "3452e4f3ef568b0a8f068ba9705148456350796b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/adaptlob.jl", "max_issues_repo_name": "tbeason/QuadGG.jl", "max_issues_repo_head_hexsha": "3452e4f3ef568b0a8f068ba9705148456350796b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/adaptlob.jl", "max_forks_repo_name": "tbeason/QuadGG.jl", "max_forks_repo_head_hexsha": "3452e4f3ef568b0a8f068ba9705148456350796b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8148148148, "max_line_length": 162, "alphanum_fraction": 0.5985352863, "num_tokens": 1223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.8558511414521922, "lm_q1q2_score": 0.7918591095894352}}
{"text": "##############################################################################\n#\n# REFERENCES: Forbes et al. \"Statistical Distributions\"\n#\n##############################################################################\n\nimmutable BetaPrime <: ContinuousUnivariateDistribution\n    alpha::Float64\n    beta::Float64\n    function BetaPrime(a::Float64, b::Float64)\n        (a > zero(a) && b > zero(b)) || error(\"Alpha and beta must be positive\")\n        new(float64(a), float64(b))\n    end\nend\n\nBetaPrime() = BetaPrime(1.0, 1.0)\n\n@distr_support BetaPrime 0.0 Inf\n\nfunction mean(d::BetaPrime)\n    d.beta > 1.0 ? d.alpha / (d.beta - 1.0) : NaN\nend\n\nmode(d::BetaPrime) = d.alpha > 1.0 ? (d.alpha - 1.0) / (d.beta + 1.0) : 0.0\n\nfunction pdf(d::BetaPrime, x::Float64)\n    α, β = d.alpha, d.beta\n    (x^(α - 1.0) * (1.0 + x)^(-(α + β))) / beta(α, β)\nend\n\ncdf(d::BetaPrime, x::Float64) = cdf(Beta(d.alpha, d.beta), x / (one(x) + x))\nccdf(d::BetaPrime, x::Float64) = ccdf(Beta(d.alpha, d.beta), x / (one(x) + x))\nlogcdf(d::BetaPrime, x::Float64) = logcdf(Beta(d.alpha, d.beta), x / (one(x) + x))\nlogccdf(d::BetaPrime, x::Float64) = logccdf(Beta(d.alpha, d.beta), x / (one(x) + x))\n\nquantile(d::BetaPrime, p::Float64) = (x = quantile(Beta(d.alpha,d.beta),p); x / (1.0-x))\ncquantile(d::BetaPrime, p::Float64) = (x = cquantile(Beta(d.alpha,d.beta),p); x / (1.0-x))\ninvlogcdf(d::BetaPrime, p::Float64) = (x = invlogcdf(Beta(d.alpha,d.beta),p); x / (1.0-x))\ninvlogccdf(d::BetaPrime, p::Float64) = (x = invlogccdf(Beta(d.alpha,d.beta),p); x / (1.0-x))\n    \n\nfunction rand(d::BetaPrime)\n    x = rand(Gamma(d.alpha, 1))\n    y = rand(Gamma(d.beta, 1))\n    x/y\nend\n\nfunction skewness(d::BetaPrime)\n    α, β = d.alpha, d.beta\n    β > 3.0 ? (2.0 * (2.0 * α + β - 1))/(β - 3.0) * sqrt((β - 2.0)/(α * (α + β - 1.0))) : NaN\nend\n\nfunction var(d::BetaPrime)\n    α, β = d.alpha, d.beta\n    β > 2.0 ? (α * (α + β - 1.0)) / ((β - 2.0) * (β - 1.0)^2) : NaN\nend\n", "meta": {"hexsha": "441425962c59b24a482a01b9b4751d243ecc4ac2", "size": 1926, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/betaprime.jl", "max_stars_repo_name": "davidanthoff/Distributions.jl", "max_stars_repo_head_hexsha": "75a04ebc12f3643392d33240a4029d458f86e7f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/betaprime.jl", "max_issues_repo_name": "davidanthoff/Distributions.jl", "max_issues_repo_head_hexsha": "75a04ebc12f3643392d33240a4029d458f86e7f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/betaprime.jl", "max_forks_repo_name": "davidanthoff/Distributions.jl", "max_forks_repo_head_hexsha": "75a04ebc12f3643392d33240a4029d458f86e7f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7894736842, "max_line_length": 93, "alphanum_fraction": 0.531152648, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7918393562907938}}
{"text": "module Mathes \n\nimport Statistics: mean \nimport LinearAlgebra: svd, diagm, diag\n\n\"\"\"\n    pca(data)\nperform PCA using SVD\ninputs:\n    - data: M x N matrix of input data. (M dimensions, N trials)\noutputs:\n    - PC: each column is a principle component\n    - V: M x 1 matrix of variances\n\"\"\"\nfunction pca(data::Array{T,2}) where T\n    X = data .- mean(data, dims=2)\n    Y = X' ./ sqrt(T(size(X,2)-1))\n    U,S,PC = svd(Y)\n    S = diagm(0=>S)\n    V = S .* S\n    \n    # find the least variance vector\n    indexList = sortperm(diag(V); rev=true)\n\n    PCs = map(x->PC[:,x], indexList)\n    return PCs, diag(V)[indexList]\nend \n\nend # end of module\n", "meta": {"hexsha": "fbac59296c130339b236d380e9452d5ec2eecae3", "size": 638, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Utils/Mathes.jl", "max_stars_repo_name": "UnofficialJuliaMirror/RealNeuralNetworks.jl-4491297b-8966-5840-8cb9-b189d60f3398", "max_stars_repo_head_hexsha": "e6f19dd0515e2105de0ff7c26997d7de64fb3153", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2018-11-20T01:09:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T08:15:56.000Z", "max_issues_repo_path": "src/Utils/Mathes.jl", "max_issues_repo_name": "UnofficialJuliaMirror/RealNeuralNetworks.jl-4491297b-8966-5840-8cb9-b189d60f3398", "max_issues_repo_head_hexsha": "e6f19dd0515e2105de0ff7c26997d7de64fb3153", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2018-08-20T21:24:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T18:59:00.000Z", "max_forks_repo_path": "src/Utils/Mathes.jl", "max_forks_repo_name": "UnofficialJuliaMirror/RealNeuralNetworks.jl-4491297b-8966-5840-8cb9-b189d60f3398", "max_forks_repo_head_hexsha": "e6f19dd0515e2105de0ff7c26997d7de64fb3153", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:01:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:01:26.000Z", "avg_line_length": 21.2666666667, "max_line_length": 64, "alphanum_fraction": 0.6112852665, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96036116089903, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7917812148031329}}
{"text": "#=\nThe first two consecutive numbers to have two distinct prime factors are:\n\n14 = 2 × 7\n15 = 3 × 5\n\nThe first three consecutive numbers to have three distinct prime factors are:\n\n644 = 2² × 7 × 23\n645 = 3 × 5 × 43\n646 = 2 × 17 × 19.\n\nFind the first four consecutive integers to have four distinct prime factors. What is the first of these numbers?\n=#\n\nusing Primes\n\nfunction calc()\n  num = 4\n  arr = Int64[]\n  i = 7\n  while length(arr) < num\n    if (length(keys(factor(i))) == num) && (length(arr) == 0 || last(arr) == i-1)\n      push!(arr, i)\n    else\n      arr = Int64[]\n    end\n    i += 1\n  end\n  arr[1]\nend\n@time println(calc())\n", "meta": {"hexsha": "42b7aa9fe26b7cd6b047d9c2712de8b1b3e795a7", "size": 634, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p47.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p47.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p47.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 19.2121212121, "max_line_length": 113, "alphanum_fraction": 0.6230283912, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611631680358, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.7917812104606051}}
{"text": "#=\n\n@authors : Spencer Lyon, John Stachurski\n\n=#\n\nusing Optim\n\n\n\"\"\"\nThe approximate Bellman operator, which computes and returns the\nupdated value function Tw on the grid points.  An array to store\nthe new set of values Tw is optionally supplied (to avoid having to\nallocate new arrays at each iteration).  If supplied, any existing data in \nTw will be overwritten.\n\n#### Arguments\n\n`w` : Vector\n      The value of the input function on different grid points\n`grid` : Vector\n         The set of grid points\n`β` : AbstractFloat\n         The discount factor\n`u` : Function\n      The utility function\n`f` : Function\n      The production function\n`shocks` : Vector\n           An array of draws from the shock, for Monte Carlo integration (to\n           compute expectations).\n`Tw` : Vector, optional (default=similar(w))\n       Array to write output values to\n`compute_policy` : Bool, optional (default=false)\n                   Whether or not to compute policy function\n\n\"\"\"\nfunction bellman_operator(w::Vector, \n                          grid::Vector,\n                          β::AbstractFloat, \n                          u::Function, \n                          f::Function, \n                          shocks::Vector, \n                          Tw::Vector = similar(w);\n                          compute_policy::Bool = false)\n\n    # === Apply linear interpolation to w === #\n    w_func = LinInterp(grid, w)\n\n    if compute_policy\n        σ = similar(w)\n    end\n\n    # == set Tw[i] = max_c { u(c) + β E w(f(y  - c) z)} == #\n    for (i, y) in enumerate(grid)\n        objective(c) = - u(c) - β * mean(w_func.(f(y - c) .* shocks))\n        res = optimize(objective, 1e-10, y)\n\n        if compute_policy\n            σ[i] = res.minimizer\n        end\n        Tw[i] = - res.minimum\n    end\n\n    if compute_policy\n        return Tw, σ\n    else\n        return Tw\n    end\nend\n    \n\n\n", "meta": {"hexsha": "544314a950bb02480ed3849808e23c7cac5fb98d", "size": 1870, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "optgrowth/optgrowth.jl", "max_stars_repo_name": "QuantEcon/QuantEcon.lectures.code", "max_stars_repo_head_hexsha": "d61ac7bc54529dd5c77470c17539eb2418b047c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2017-05-09T10:45:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:33:27.000Z", "max_issues_repo_path": "optgrowth/optgrowth.jl", "max_issues_repo_name": "QuantEcon/QuantEcon.lectures.code", "max_issues_repo_head_hexsha": "d61ac7bc54529dd5c77470c17539eb2418b047c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2017-06-30T01:52:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-01T20:09:47.000Z", "max_forks_repo_path": "optgrowth/optgrowth.jl", "max_forks_repo_name": "QuantEcon/QuantEcon.lectures.code", "max_forks_repo_head_hexsha": "d61ac7bc54529dd5c77470c17539eb2418b047c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 117, "max_forks_repo_forks_event_min_datetime": "2017-04-25T16:09:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T02:30:29.000Z", "avg_line_length": 25.2702702703, "max_line_length": 76, "alphanum_fraction": 0.5668449198, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391600697869, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7917535561988939}}
{"text": "export softmax, softmax!, ∇softmax, ∇softmax!,\n       logsoftmax, logsoftmax!, ∇logsoftmax, ∇logsoftmax!\n\n\"\"\"\n    softmax(x; dims=1)\n    \n[Softmax](https://en.wikipedia.org/wiki/Softmax_function) turns input array `x` \ninto probability distributions that sum to 1 along the dimensions specified by `dims`.\nIt is semantically equivalent to the following:\n\n    softmax(x; dims=1) = exp.(x) ./ sum(exp.(x), dims=dims)\n\nwith additional manipulations enhancing numerical stability.\n\nFor a matrix input `x` it will by default (`dims=1`) treat it as a batch of vectors,\nwith each column independent. Keyword `dims=2` will instead treat rows independently, \netc...\n```julia-repl\njulia> softmax([1, 2, 3])\n3-element Array{Float64,1}:\n  0.0900306\n  0.244728\n  0.665241\n```\n\nSee also [`logsoftmax`](@ref).\n\"\"\"\nfunction softmax(xs::AbstractArray; dims=1)\n    max_ = maximum(xs, dims=dims)\n    exp_ = exp.(xs .- max_)\n    exp_ ./ sum(exp_, dims=dims)\nend\n\nfunction softmax!(out::AbstractVecOrMat{T}, xs::AbstractVecOrMat{T}) where {T}\n    @inbounds for j = 1:size(xs, 2)\n        # First, store column-wise maximum in the last element of `out`\n        out[end, j] = xs[end, j]\n        @inbounds for i = 1:(size(xs, 1) - 1)\n            out[end, j] = max(out[end, j], xs[i, j])\n        end\n\n        # Subtract the column-wise maximums to normalize, take exp()\n        # out .= exp(xs .- out[end, :])\n        @inbounds for i = 1:size(out, 1)\n            out[i, j] = exp(xs[i, j] - out[end, j])\n        end\n\n        # Normalize by sum of the entire thing\n        # out ./= sum(out, 1)\n        s = T(0)\n        @inbounds for i = 1:size(out, 1)\n            s += out[i, j]\n        end\n        @inbounds for i = 1:size(out, 1)\n            out[i, j] /= s\n        end\n    end\n    return out\nend\n\nfunction ∇softmax!(out::AbstractVecOrMat, Δ::AbstractVecOrMat, xs::AbstractVecOrMat)\n    sf = softmax(xs)\n    out .= sf .* (Δ .- sum(Δ .* sf, dims = 1))\nend\nfunction ∇softmax(Δ, xs; dims=1)\n    sf = softmax(xs, dims=dims)\n    sf .* (Δ .- sum(Δ .* sf, dims=dims))\nend\n∇softmax!(Δ, xs) = ∇softmax!(Δ, Δ, xs)\n\n\n\"\"\"\n    logsoftmax(x; dims=1)\n\nComputes the log of softmax in a more numerically stable\nway than directly taking `log.(softmax(xs))`. Commonly used in\ncomputing cross entropy loss.\n\nIt is semantically equivalent to the following:\n\n    logsoftmax(x; dims=1) = x .- log.(sum(exp.(x), dims=dims))\n\nSee also [`softmax`](@ref).\n\"\"\"\nfunction logsoftmax(xs::AbstractArray; dims=1)\n    max_ = maximum(xs, dims=dims)\n    exp_ = exp.(xs .- max_)\n    log_ = log.(sum(exp_, dims=dims))\n    (xs .- max_) .- log_\nend\n\nfunction logsoftmax!(out::AbstractVecOrMat, xs::AbstractVecOrMat)\n    for j = 1:size(xs, 2)\n        @inbounds begin\n            xi_max = xs[1, j]\n            for i = 1:size(out, 1)\n                xi_max = max(xi_max, xs[i, j])\n            end\n            s = zero(eltype(out))\n            for i = 1:size(out, 1)\n                s += exp(xs[i, j] - xi_max)\n            end\n            for i = 1:size(out, 1)\n                out[i, j] = xs[i, j] - log(s) - xi_max\n            end\n        end\n    end\n    return out\nend\n\n∇logsoftmax(Δ, xs; dims=1) = Δ .- sum(Δ, dims=dims) .* softmax(xs, dims=dims)\n∇logsoftmax!(Δ, xs) = ∇softmax!(Δ, Δ, xs)\n", "meta": {"hexsha": "9aa12d63edb9bbe941e3e4d601da5d1a559cc286", "size": 3223, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/softmax.jl", "max_stars_repo_name": "nirmal-suthar/NNlib.jl", "max_stars_repo_head_hexsha": "bf027df6b5e33b05a464ec51f78aca0836d0c489", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/softmax.jl", "max_issues_repo_name": "nirmal-suthar/NNlib.jl", "max_issues_repo_head_hexsha": "bf027df6b5e33b05a464ec51f78aca0836d0c489", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/softmax.jl", "max_forks_repo_name": "nirmal-suthar/NNlib.jl", "max_forks_repo_head_hexsha": "bf027df6b5e33b05a464ec51f78aca0836d0c489", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5221238938, "max_line_length": 86, "alphanum_fraction": 0.5820663978, "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8577680977182186, "lm_q1q2_score": 0.7917535553483341}}
{"text": "\"\"\"\n    assortativity(g)\n\nReturn the [assortativity coefficient](https://en.wikipedia.org/wiki/Assortativity)\nof graph `g`, defined as the Pearson correlation of excess degree between\nthe end vertices of all the edges of the graph.\n\nThe excess degree is equal to the degree of linked vertices minus one,\ni.e. discounting the edge that links the pair.\nIn directed graphs, the paired values are the out-degree of source vertices\nand the in-degree of destination vertices.\n\n# Examples\n```jldoctest\njulia> using LightGraphs\n\njulia> assortativity(star_graph(4))\n-1.0\n```\n\"\"\"\nfunction assortativity(g::AbstractGraph{T}) where T\n    P = promote_type(Int64, T) # at least Int64 to reduce risk of overflow\n    nue  = ne(g)\n    sjk = sj = sk = sjs = sks = zero(P)\n    for d in edges(g)\n        j = P(outdegree(g, src(d)) - 1)\n        k = P(indegree(g, dst(d)) - 1)\n        sjk += j*k\n        sj  += j\n        sk  += k\n        sjs += j^2\n        sks += k^2\n    end\n    return assortativity_coefficient(g, sjk, sj, sk, sjs, sks, nue)\nend\n\n#=\nassortativity coefficient for directed graphs: \nsee equation (21) in M. E. J. Newman: Mixing patterns in networks, Phys. Rev. E 67, 026126 (2003), \nhttp://arxiv.org/abs/cond-mat/0209450\n=#\n@traitfn function assortativity_coefficient(g::::IsDirected, sjk, sj, sk, sjs, sks, nue)\n    return (sjk - sj*sk/nue) / sqrt((sjs - sj^2/nue)*(sks - sk^2/nue))\nend\n\n#=\nassortativity coefficient for undirected graphs: \nsee equation (4) in M. E. J. Newman: Assortative mixing in networks, Phys. Rev. Lett. 89, 208701 (2002), \nhttp://arxiv.org/abs/cond-mat/0205405/\n=#\n@traitfn function assortativity_coefficient(g::::(!IsDirected), sjk, sj, sk, sjs, sks, nue)\n    return (sjk/nue - ((sj + sk)/(2*nue))^2) / ((sjs + sks)/(2*nue) - ((sj + sk)/(2*nue))^2)\nend\n", "meta": {"hexsha": "0d17ae5f4b196511721ebd792497c43b0197cc90", "size": 1774, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/community/assortativity.jl", "max_stars_repo_name": "blepabyte/LightGraphs.jl", "max_stars_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 745, "max_stars_repo_stars_event_min_datetime": "2015-03-19T03:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-07T00:59:06.000Z", "max_issues_repo_path": "src/community/assortativity.jl", "max_issues_repo_name": "blepabyte/LightGraphs.jl", "max_issues_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1491, "max_issues_repo_issues_event_min_datetime": "2015-03-19T17:04:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T14:47:57.000Z", "max_forks_repo_path": "src/community/assortativity.jl", "max_forks_repo_name": "blepabyte/LightGraphs.jl", "max_forks_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 288, "max_forks_repo_forks_event_min_datetime": "2015-04-04T14:31:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T10:37:21.000Z", "avg_line_length": 32.8518518519, "max_line_length": 105, "alphanum_fraction": 0.6640360767, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552536, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7917535552104178}}
{"text": "using Revise\n\ninclude(\"Interface.jl\")\n\nmodule Attractors\n\nusing ..Interface: @ODE\n\nexport lorenz, TSUCS1, TSUCS2, yuwang, aizawa, \n       rucklidge, genesio_tesi, finance, shimizu_morioka, \n       noose_hoover, liu_chen, arneodo, bouali,\n       burke_shaw, chen_celikovsky, chen_lee, dequan_li,\n       hadley, halvorsen, newton_leipnik\n\nlorenz = @ODE quote\n    dx = σ * (y - x)\n    dy = x * (ρ - z) - y\n    dz = x * y - β * z\n\n    σ = 10\n    ρ = 28\n    β = 8/3\nend\n\nTSUCS1 = @ODE quote\n    dx = α * (y - x) + δ * x * z\n    dy = ζ * y - x * z\n    dz = β * z + x * y - ϵ * x * x\n\n    α = 40\n    β = 0.833\n    δ = 0.5\n    ϵ = 0.65\n    ζ = 20\nend\n\nTSUCS2 = @ODE quote\n    dx = α * (y - x) + δ * x * z\n    dy = (ς * x) - (x * z) + ζ * y\n    dz = (β * z) + (x * y) - (ϵ * x * x)\n\n    α = 40\n    δ = 0.16\n    ς = 55\n    ζ = 20\n    β = 1.833\n    ϵ = 0.65\nend\n\nyuwang = @ODE quote\n    dx = α * (y - x)\n    dy = β * x - σ * x * z\n    dz = exp(x * y) - δ * z\n\n    α = 10\n    β = 40\n    σ = 2\n    δ = 2.5\nend\n\naizawa = @ODE quote\n    dx = (z - β) * x - δ * y\n    dy = δ * x + (z - β) * y\n    dz = σ + α * z - (z^3)/3 - (x^2 + y^2)*(1 + ϵ * z) + ζ * z * x^3\n\n    α = 0.95\n    β = 0.7\n    σ = 0.6\n    δ = 3.5\n    ϵ = 0.25\n    ζ = 0.1\nend\n\nlorenz_mod_2 = @ODE quote\n    dx = -α*x + y^2 - z^2 + α*σ\n    dy = x*(y-β*z) + δ\n    dz = -z + x*(β * y + z)\n\n    α = 0.9\n    β = 5\n    σ = 9.9\n    δ = 1\nend\n\nthomas = @ODE quote\n    dx = -β * x + sin(y)\n    dy = -β * y + sin(z)\n    dz = -β * z + sin(x)\n\n    β = 0.19\nend\n\nrucklidge = @ODE quote\n    dx = -κ*x + α*y - y* z\n    dy = x\n    dz = -z + y^2\n\n    κ = 2\n    α = 6.7\nend\n\ngenesio_tesi = @ODE quote\n    dx = y\n    dy = z\n    dz = -σ * x - β * y - α * z + x^2\n\n    α = 0.44\n    β = 1.1\n    σ = 1.0\nend\n\nfinance = @ODE quote\n    dx = ((1/β) - α)*x + z + x*y\n    dy = -β*y - x^2\n    dz = -x - σ*z\n\n    α = 0.001\n    β = 0.2\n    σ = 1.1\nend\n\nshimizu_morioka = @ODE quote\n    dx = y\n    dy = (1-z)*x - α*y\n    dz = x^2 - β*z\n\n    α = 0.75\n    β = 0.45\nend\n\nnoose_hoover = @ODE quote\n    dx = y\n    dy = -x + y*z\n    dz = α - y^2\n\n    α = 1.5\nend\n\nliu_chen = @ODE quote\n    dx = α*y + β*x + σ*y*z\n    dy = δ*y - z + ϵ*x*z\n    dz = ζ*z + η*x*y\n\n    α = 2.4\n    β = -3.78\n    σ = 14\n    δ = -11\n    ϵ = 4\n    ζ = 5.58\n    η = 1\nend\n\narneodo = @ODE quote\n    dx = y\n    dy = z\n    dz = -α*x - β*y - z + σ*x^3\n\n    α = -5.5\n    β = 3.5\n    σ = -1.0\nend\n\nbouali = @ODE quote\n    dx = x*(4-y) + α*z\n    dy = -y*(1-x^2)\n    dz = -x*(1.5 - σ*z) - 0.05*z\n\n    α = 0.3\n    σ = 1.0\nend\n\nburke_shaw = @ODE quote\n    dx = -σ*(x+y)\n    dy = -y -σ*x*z\n    dz = σ*x*y + ν\n\n    σ = 10\n    ν = 4.272\nend\n\nchen_celikovsky = @ODE quote\n    dx = α*(y-x)\n    dy = -x*z + σ*y\n    dz = x*y - β*z\n\n    α = 36\n    β = 3\n    σ = 20\nend\n\nchen_lee = @ODE quote\n    dx = α*x - y*z\n    dy = β*y + x*z\n    dz = σ*z + x*(y/3)\n\n    α = 5\n    β = -10\n    σ = -0.38\nend\n\ndequan_li = TSUCS2\n\nhadley = @ODE quote\n    dx = -y^2 -z^2 -α*x + α*ζ\n    dy = x*y - β*x*z - y + η\n    dz = β*x*y + x*z - z\n\n    α = 0.2\n    β = 4\n    ζ = 8\n    η = 1\nend\n\nhalvorsen = @ODE quote\n    dx = -α*x -4*y -4*z - y^2\n    dy = -α*y - 4*z - 4*x - z^2\n    dz = -α*z - 4*x - 4*y - x^2\n\n    α = 1.4\nend\n\nnewton_leipnik = @ODE quote\n    dx = -α*x + y + 10*y*z\n    dy = -x - 0.4*y + 5*x*z\n    dz = β*z -5*x*y\n\n    α = 0.4\n    β = 0.175\nend\n\nend", "meta": {"hexsha": "91d12ecf76c994aa35743ceaab093eaa0b4d7a16", "size": 3306, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ExampleFunctions.jl", "max_stars_repo_name": "Sharn-konet/Flo.jl", "max_stars_repo_head_hexsha": "45cce4b24e92f8a0771b470ab73fcae5e41dcf1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ExampleFunctions.jl", "max_issues_repo_name": "Sharn-konet/Flo.jl", "max_issues_repo_head_hexsha": "45cce4b24e92f8a0771b470ab73fcae5e41dcf1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ExampleFunctions.jl", "max_forks_repo_name": "Sharn-konet/Flo.jl", "max_forks_repo_head_hexsha": "45cce4b24e92f8a0771b470ab73fcae5e41dcf1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.3116883117, "max_line_length": 68, "alphanum_fraction": 0.4050211736, "num_tokens": 1664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7917535461305423}}
{"text": "# double factorial\nfactorial2(n) = prod(n:-2:1)\n\ndist2(dx,dy,dz) = dx*dx + dy*dy + dz*dz\n\ntriangle(i::Int64) = div(i*(i+1),2)\ntriangle(i::Int64,j::Int64) = i < j ? triangle(j-1)+i : triangle(i-1)+j\n\niindex(i::Int64,j::Int64,k::Int64,l::Int64) = triangle(triangle(i,j),triangle(k,l))\n\ntrace2(A,B) = sum(A.*B)\n", "meta": {"hexsha": "c8166b552e1e7afaa8144497a26800c432d76a2b", "size": 308, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LO_Gaussian/utils.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "LO_Gaussian/utils.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LO_Gaussian/utils.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 25.6666666667, "max_line_length": 83, "alphanum_fraction": 0.6233766234, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462514578343, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7917162921370429}}
{"text": "# Matern 3/2 isotropic covariance function\n\n@doc \"\"\"\n# Description\nConstructor for the isotropic Matern 3/2 kernel (covariance)\n\nk(x,x') = σ²(1+√3*d/ℓ)exp(-√3*d/ℓ), where d = |x-x'|\n# Arguments:\n* `ll::Float64`: Log of the length scale ℓ\n* `lσ::Float64`: Log of the signal standard deviation σ\n\"\"\" ->\ntype Mat32Iso <: Isotropic\n    ℓ::Float64       # Length scale \n    σ2::Float64      # Signal std\n    Mat32Iso(ll::Float64, lσ::Float64) = new(exp(ll),exp(2*lσ))\nend\n\nfunction set_params!(mat::Mat32Iso, hyp::Vector{Float64})\n    length(hyp) == 2 || throw(ArgumentError(\"Matern 3/2 only has two parameters\"))\n    mat.ℓ, mat.σ2 = exp(hyp[1]), exp(2.0*hyp[2])\nend\n\nget_params(mat::Mat32Iso) = Float64[log(mat.ℓ), log(mat.σ2)/2.0]\nget_param_names(mat::Mat32Iso) = [:ll, :lσ]\nnum_params(mat::Mat32Iso) = 2\n\nmetric(mat::Mat32Iso) = Euclidean()\ncov(mat::Mat32Iso, r::Float64) = mat.σ2*(1+sqrt(3)*r/mat.ℓ)*exp(-sqrt(3)*r/mat.ℓ)\n\nfunction grad_kern(mat::Mat32Iso, x::Vector{Float64}, y::Vector{Float64})\n    r = distance(mat,x,y)\n    exp_r = exp(-sqrt(3)*r/mat.ℓ)\n\n    g1= mat.σ2*(sqrt(3)*r/mat.ℓ)^2*exp_r       #dK_d(log ℓ)\n    g2 = 2.0*mat.σ2*(1+sqrt(3)*r/mat.ℓ)*exp_r  #dK_d(log σ)\n    return [g1,g2]\nend    \n\n\nfunction grad_stack!(stack::AbstractArray, mat::Mat32Iso, X::Matrix{Float64}, data::IsotropicData)\n    nobsv = size(X,2)\n    R = distance(mat, X, data)\n    exp_R = exp(-sqrt(3)*R/mat.ℓ)\n\n    for i in 1:nobsv, j in 1:i\n        @inbounds stack[i,j,1] = mat.σ2*(sqrt(3)*R[i,j]/mat.ℓ)^2*exp_R[i,j]       # dK_dℓ\n        @inbounds stack[j,i,1] = stack[i,j,1] \n        @inbounds stack[i,j,2] = 2.0 *mat.σ2*(1+sqrt(3)*R[i,j]/mat.ℓ)*exp_R[i,j]  # dK_dσ\n        @inbounds stack[j,i,2] = stack[i,j,2] \n    end\n    \n    return stack\nend\n", "meta": {"hexsha": "fc7e39333dcc4dd1990fc8be859e804f6e74f977", "size": 1732, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/mat32_iso.jl", "max_stars_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/mat32_iso.jl", "max_issues_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/mat32_iso.jl", "max_forks_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0740740741, "max_line_length": 98, "alphanum_fraction": 0.6177829099, "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7917162874384428}}
{"text": "export Companion\n\nstruct Companion{T} <: AbstractArray{T, 2}\n    c :: Vector{T}\nend\n#From polynomial\n\nusing Polynomials\n#Generate companion matrix from a polynomial\n\nfunction Companion(P::Poly{T}) where T\n   n = length(P)\n   c = Array{T}(undef, n-1)\n   d=P.a[n]\n   for i=1:n-1\n       c[i]=P.a[i]/d\n   end\n   Companion(c)   \nend\n\n#Basic property computations\nsize(C::Companion, r::Int) = (r==1 || r==2) ? length(C.c) : \n    throw(ArgumentError(\"Companion is of rank 2\"))\n\nfunction size(C::Companion)\n    n = length(C.c)\n    n, n\nend\n\n#XXX Inefficient but works\n# getindex(C::Companion, i, j) = getindex(Matrix(C), i, j)\n# isassigned(C::Companion, i, j) = isassigned(Matrix(C), i, j)\ngetindex(C::Companion{T}, i::Int, j::Int) where T = (j==length(C.c)) ? -C.c[i] : (i==j+1 ? one(T) : zero(T) )\nisassigned(C::Companion, i::Int, j::Int) = (j==length(C.c)) ? isassigned(C.c,i) : true\n\n\nfunction Matrix(C::Companion{T}) where T\n    M = zeros(T, size(C)...)\n    M[:,end]=-C.c\n    for i=1:size(C,1)-1\n    \tM[i+1, i] = one(T)\n\tend\n    M\nend\n\n#Linear algebra stuff\nfunction mul!(C::Companion{T}, b::Vector{T}) where T\n\tx = b[end]\n\ty = -C.c[1]*x\n\tb[2:end] = b[1:end-1]-C.c[2:end]*x\n\tb[1] = y\n    b\nend\n*(C::Companion{T}, b::Vector{T}) where T = mul!(C, copy(b))\n\nfunction mul!(A::Matrix{T}, C::Companion{T}) where T\n\tv = Array{T}(undef, size(A,1))\n\tfor i=1:size(A,1)\n\t\tv[i] =dot(vec(A[i,:]),-C.c)\n\tend\n\tfor i=1:size(A,1), j=1:size(A,2)-1\n\t\tA[i,j] = A[i,j+1]\n\tend\n\tA[:,end] = v\n\tA\nend\n*(A::Matrix{T}, C::Companion{T}) where T = mul!(copy(A), C)\n\nfunction inv(C::Companion{T}) where T\n\tM = zeros(T, size(C)...)\n    for i=1:size(C,1)-1\n    \tM[i, i+1] = one(T)\n\tend\n\td = M[end, 1] = -one(T)/C.c[1]\n\tM[1:end-1, 1] = d*C.c[2:end]\n    M\nend\n", "meta": {"hexsha": "77e3f6894047bb552995500ec2eafdef65ab14a9", "size": 1723, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/companion.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SpecialMatrices.jl-928aab9d-ef52-54ac-8ca1-acd7ca42c160", "max_stars_repo_head_hexsha": "196405f3a93e21760860b31566887ed562fb780b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/companion.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SpecialMatrices.jl-928aab9d-ef52-54ac-8ca1-acd7ca42c160", "max_issues_repo_head_hexsha": "196405f3a93e21760860b31566887ed562fb780b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/companion.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SpecialMatrices.jl-928aab9d-ef52-54ac-8ca1-acd7ca42c160", "max_forks_repo_head_hexsha": "196405f3a93e21760860b31566887ed562fb780b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0897435897, "max_line_length": 109, "alphanum_fraction": 0.5763203714, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7917162835928694}}
{"text": "using StanModels, Distributions\n\n# Define the Stan language model\n\nm8_5s = \"\ndata{\n  int N;\n  vector[N] y;\n}\nparameters{\n  real sigma;\n  real a1;\n  real a2;\n}\nmodel{\n  real mu;\n  a1 ~ normal(0, 10);\n  a2 ~ normal(0, 10);\n  mu = a1 + a2;\n  y ~ normal( mu , sigma );\n}\n\";\n\n# Define the Stanmodel and set the output format to :mcmcchains.\n\nsm = SampleModel(\"m8.5s\", m8_5s);\n\n# Input data for cmdstan\n\nm8_5_data = Dict(\"N\" => 100, \"y\" => rand(Normal(0, 1), 100));\n\n# Sample using cmdstan\n\n(sample_file, log_file) = stan_sample(sm, data=m8_5_data);\n  \nrethinking = \"\n       mean   sd   5.5% 94.5% n_eff Rhat\na1    -0.08 7.15 -11.34 11.25  1680    1\na2    -0.05 7.15 -11.37 11.19  1682    1\nsigma  0.90 0.07   0.81  1.02  2186    1\n\";\n\n# Describe the draws\nif !(sample_file == nothing)\n  chn = read_samples(sm)\n  describe(chn)\nend\n", "meta": {"hexsha": "d41f8e53962b7126f085f1b1884d711f5ed089d4", "size": 825, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/08/m8.5s.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StanModels.jl-fb740163-aa3c-59c1-9c12-c3f890714cde", "max_stars_repo_head_hexsha": "16dd5f82cc418e8444ef6ac8490b4bbda3783283", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/08/m8.5s.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StanModels.jl-fb740163-aa3c-59c1-9c12-c3f890714cde", "max_issues_repo_head_hexsha": "16dd5f82cc418e8444ef6ac8490b4bbda3783283", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/08/m8.5s.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StanModels.jl-fb740163-aa3c-59c1-9c12-c3f890714cde", "max_forks_repo_head_hexsha": "16dd5f82cc418e8444ef6ac8490b4bbda3783283", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1875, "max_line_length": 64, "alphanum_fraction": 0.6157575758, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7917162805114103}}
{"text": "# Machinery for complex plane mappings\n\n\"zr = rotate_and_scale(za, zb, z)\"\nfunction rotate_and_scale(za, zb, z)\n    # computes\n    # zr = M(z)\n    # where\n    # M(za) = -1\n    # M(zb) = 1\n    c_map = ((za+zb)/(za-zb), 2/(zb-za))\n    zr = c_map[1] + z*c_map[2]\n    return zr\nend\n\nfunction z_edges(grid, i)\n    za = grid.edges[1,i] + 1im*grid.edges[2,i]\n    zb = grid.edges[3,i] + 1im*grid.edges[4,i]\n    return za, zb\nend\n\nfunction map_panels(grid::DiscreteCurve)\n    L = legendre_matrix(grid.panelorder)\n    ffit(z) = L*z\n    coeffs = Array{Complex{Float64}}(grid.panelorder, grid.numpanels)\n    for i=1:grid.numpanels\n        za, zb = z_edges(grid, i)\n        idx = (1:grid.panelorder) + grid.panelorder*(i-1)\n        zpanel = grid.points[1,idx] + 1im*grid.points[2,idx]\n        # First rescale [za,zb] to [-1,1], which helps Newton search later on\n        zscaled = rotate_and_scale(za, zb, zpanel)\n        c = ffit(zscaled)\n        coeffs[:,i] = c\n    end\n    return coeffs\nend\n\nfunction invert_map(grid, coeffs, panel_idx, z; fall_back_to_initial::Bool=true)\n    # Step 1: Rotate and scale\n    za, zb = z_edges(grid, panel_idx)\n    zr = rotate_and_scale(za, zb, z)\n    # Step 2: Get the right expansion and solve with Newton\n    c = coeffs[:, panel_idx]\n    c = c[1 : min(length(c), 16)]     # Limit to 16 modes\n    t0 = zr\n    maxiter = 30\n    converged = true\n    t, relres, iter = newton_legendre(c, zr, t0, maxiter, 1e-13) # Try to hit 1e-13\n    if iter == maxiter && relres > 1e-10 # ...but consider things converged if only 1e-10\n        info(\"Newton did not converge, relres=\", @sprintf(\"%.2e\", relres), \". t=$t, t0=$t0\")\n        converged = false\n        if fall_back_to_initial\n            t = t0 # Fall back to initial guess\n        end\n    end                    \n    tlocal = t\n    # Step 3: Rescale t back to global parametrization\n    ta = grid.t_edges[1, panel_idx]\n    tb = grid.t_edges[2, panel_idx]\n    tglobal = ta + (t+1)/2*(tb-ta)\n    return tlocal, tglobal, converged\nend\n", "meta": {"hexsha": "975ff5c4313922d5d60657ba0b0c4d92d3d62103", "size": 1998, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/src/mappings.jl", "max_stars_repo_name": "askhamwhat/inse-fiem-2d", "max_stars_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-08-20T12:53:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:15:10.000Z", "max_issues_repo_path": "julia/src/mappings.jl", "max_issues_repo_name": "askhamwhat/inse-fiem-2d", "max_issues_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/src/mappings.jl", "max_forks_repo_name": "askhamwhat/inse-fiem-2d", "max_forks_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-28T18:44:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T04:17:59.000Z", "avg_line_length": 32.2258064516, "max_line_length": 92, "alphanum_fraction": 0.6036036036, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7916782649197414}}
{"text": "# A palindromic number reads the same both ways. The largest palindrome made\n# from the product of two 2-digit numbers is 9009 = 91 * 99.\n\n# Find the largest palindrome made from the product of two 3-digit numbers.\n\n\nfunction largest_palindrome(digits)\n    limit = 10^digits-1\n    largest = 0\n    for i in limit:-1:1\n        for j in i:-1:1\n            num = i*j\n            str = string(num, pad=digits*2)\n            if (num > 10^(digits*2-1)) & (num > largest) & (reverse(str[1:digits]) == str[digits+1:end])\n                largest = num\n            end\n        end\n    end\n    #return sort(list)[end]\n    return largest\nend\n\nlargest_palindrome(2)\n\nlargest_palindrome(3)\n", "meta": {"hexsha": "6454cc03074b9c8a06322c2aa64701b07c39df5b", "size": 675, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "euler_4.jl", "max_stars_repo_name": "pedvide/project-euler", "max_stars_repo_head_hexsha": "8e8e1e57b2c4d7e70a7127483539dca060c50a38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "euler_4.jl", "max_issues_repo_name": "pedvide/project-euler", "max_issues_repo_head_hexsha": "8e8e1e57b2c4d7e70a7127483539dca060c50a38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "euler_4.jl", "max_forks_repo_name": "pedvide/project-euler", "max_forks_repo_head_hexsha": "8e8e1e57b2c4d7e70a7127483539dca060c50a38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9615384615, "max_line_length": 104, "alphanum_fraction": 0.6103703704, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7916782605400627}}
{"text": "export\n    laguerre_horner,\n    laguerre\n\nfunction laguerre_horner(n::Integer, α::Integer, x::Real)\n    # by Horner's method\n    laguerre_l = 1\n    bin = 1\n    for i in n:-1:1\n        bin *= (α + i) / (n + 1 - i)\n        laguerre_l = bin - x * laguerre_l / i\n    end\n\n    return laguerre_l\nend\n\nlaguerre_horner(n::Integer, α::Integer) = x->laguerre_horner(n, α, x)\n\nfunction laguerre(n::Integer, α::Integer, x::T) where {T<:Real}\n    if n == 0\n        return one(T)\n    elseif n == 1\n        return one(T) + α - x\n    else\n        L_prev = one(T)\n        L_k = one(T) + α - x\n        for k = 1:(n-1)\n            L_next = ((2k + one(T) + α - x) * L_k - (k+α) * L_prev) / (k+one(T))\n            L_prev, L_k = L_k, L_next\n        end\n        return L_k\n    end\nend\n\nlaguerre(n::Integer, α::Integer) = x->laguerre(n, α, x)\n\nfunction laguerre(m::Integer, n::Integer, x::Real, p::Real)\n    if n ≥ m\n        return laguerre(m, n - m, abs2(z(x, p)))\n    else\n        return laguerre(n, m - n, abs2(z(x, p)))\n    end\nend\n\nfunction laguerre(m::Vector{<:Integer}, n::Vector{<:Integer}, x::Vector{<:Real}, p::Vector{<:Real})\n    x = reshape(x, 1, 1, length(x))\n    p = reshape(p, 1, 1, 1, length(p))\n    if n ≥ m\n        return laguerre.(m, n' .- m, x, p)\n    else\n        return laguerre.(n', m .- n', x, p)\n    end\nend\n\nfunction laguerre(m::Vector{<:Integer}, n::Vector{<:Integer})\n    laguerre_xp(x::Vector{<:Real}, p::Vector{<:Real}) = laguerre(m, n, x, p)\n    return laguerre_xp\nend\n\nfunction laguerre(x::Vector{<:Real}, p::Vector{<:Real})\n    x = reshape(x, 1, 1, length(x))\n    p = reshape(p, 1, 1, 1, length(p))\n    function laguerre_mn(m::Vector{<:Integer}, n::Vector{<:Integer})\n        if n ≥ m\n            return laguerre.(m, n' .- m, x, p)\n        else\n            return laguerre.(n', m .- n', x, p)\n        end\n    end\n    return laguerre_mn\nend\n", "meta": {"hexsha": "11d182028401bb993d6b4e9b26c28c3a76119806", "size": 1849, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polynomial.jl", "max_stars_repo_name": "yuehhua/SqState.jl", "max_stars_repo_head_hexsha": "95d06c0478663570181647d1f7cd80ecdd3b69b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polynomial.jl", "max_issues_repo_name": "yuehhua/SqState.jl", "max_issues_repo_head_hexsha": "95d06c0478663570181647d1f7cd80ecdd3b69b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polynomial.jl", "max_forks_repo_name": "yuehhua/SqState.jl", "max_forks_repo_head_hexsha": "95d06c0478663570181647d1f7cd80ecdd3b69b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6805555556, "max_line_length": 99, "alphanum_fraction": 0.5348837209, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.938124016006303, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7916782571718449}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 7022d960-2901-11eb-2528-87791813b415\nusing OffsetArrays\n\n# ╔═╡ afa4a77e-28fc-11eb-1ab0-bbba1b653e46\ndata = reshape(rand(1:9,36),6,6)\n\n# ╔═╡ 0019e726-28fd-11eb-0e86-31ec28b3c1a9\nI = CartesianIndices(data)\n\n# ╔═╡ 15548ecc-28fd-11eb-1206-476c5f44efdf\n[ data[i] for i∈I]\n\n# ╔═╡ 5fb6e7b6-2901-11eb-0e94-aba290fd0bae\nA = OffsetArray(zeros(Int,8,8), 0:7 ,0:7)\n\n# ╔═╡ 87c260a2-2901-11eb-1060-b1e4b6b5b02b\nfor i ∈ I\n\tA[i] = data[i]  # copy data\nend\n\n# ╔═╡ a5c7693a-2901-11eb-1083-0da8138a73c2\nA\n\n# ╔═╡ b6fde83c-2901-11eb-0e3b-4b3766579cc8\nneighborhood = CartesianIndices((-1:1, -1:1))\n\n# ╔═╡ babe3c24-2901-11eb-2d30-51256eb97e11\n[ A[i.+neighborhood] for i ∈ I]\n\n# ╔═╡ e6bd9dea-2901-11eb-1100-ad10705f41cc\nstencil =  [ 0  -1   0\n            -1   4  -1\n            0  -1   0]\n\n# ╔═╡ fe4f6df0-2901-11eb-1945-27e3f041ed1f\n[  sum(A[i.+neighborhood].*stencil) for i ∈ I]\n\n# ╔═╡ 77c06ce6-2902-11eb-30a7-51f210dbd723\nbegin\n B = copy(A)\n\t\n B[0,:] = B[6,:]  ## periodic\n B[7,:] = B[1,:]\n B[:,0] = B[:,6]\n B[:,7] = B[:,1]\n\t\n\t\n #B[0,:] = B[1,:]  ## zero derivative\n #B[7,:] = B[6,:]\n #B[:,0] = B[:,1]\n #B[:,7] = B[:,6]\n\t\t\n B\nend\n\n# ╔═╡ 4f342744-2902-11eb-1401-55e770d9d751\n\nfor i∈I\n\tB[i] = sum(A[i.+neighborhood].*stencil)\nend\n\n\n# ╔═╡ 6223e374-2902-11eb-3bb2-4d2d0d352801\nB\n\n# ╔═╡ Cell order:\n# ╠═afa4a77e-28fc-11eb-1ab0-bbba1b653e46\n# ╠═0019e726-28fd-11eb-0e86-31ec28b3c1a9\n# ╠═15548ecc-28fd-11eb-1206-476c5f44efdf\n# ╠═7022d960-2901-11eb-2528-87791813b415\n# ╠═5fb6e7b6-2901-11eb-0e94-aba290fd0bae\n# ╠═87c260a2-2901-11eb-1060-b1e4b6b5b02b\n# ╠═a5c7693a-2901-11eb-1083-0da8138a73c2\n# ╠═b6fde83c-2901-11eb-0e3b-4b3766579cc8\n# ╠═babe3c24-2901-11eb-2d30-51256eb97e11\n# ╠═e6bd9dea-2901-11eb-1100-ad10705f41cc\n# ╠═fe4f6df0-2901-11eb-1945-27e3f041ed1f\n# ╠═77c06ce6-2902-11eb-30a7-51f210dbd723\n# ╠═4f342744-2902-11eb-1401-55e770d9d751\n# ╠═6223e374-2902-11eb-3bb2-4d2d0d352801\n", "meta": {"hexsha": "615d6e9844694a77013726840d5ad2b6ed90d105", "size": 1930, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_notebooks/week12/stencils_and_BC.jl", "max_stars_repo_name": "mathijsvdv/ComputationalThinking", "max_stars_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lecture_notebooks/week12/stencils_and_BC.jl", "max_issues_repo_name": "mathijsvdv/ComputationalThinking", "max_issues_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecture_notebooks/week12/stencils_and_BC.jl", "max_forks_repo_name": "mathijsvdv/ComputationalThinking", "max_forks_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.183908046, "max_line_length": 46, "alphanum_fraction": 0.6626943005, "num_tokens": 1121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.8688267626522814, "lm_q1q2_score": 0.7916573218351297}}
{"text": "\"\"\"\r\n    heun(f,a,b,y0,M)\r\n\r\nberisi program untuk mencari solusi persamaan differensial `y'=f(t,y)`\r\ndengan masalah nilai awal `y(a) = y0` pada interval `[a, b]`. Program ini secara default\r\nberisi 5 masukan, yaitu fungsi `f(t,y)`, titik ujung interval penyelesaian `[a,b]`, nilai awal\r\n`y0`, dan jumlah sub-interval `M`.\r\n\r\n# Examples\r\n```jldoctest\r\njulia> heun((t,y)->(t-y)/2,0,3,1,6)\r\n7×2 Array{Float64,2}:\r\n 0.0  1.0\r\n 0.5  0.84375\r\n 1.0  0.831055\r\n 1.5  0.930511\r\n 2.0  1.11759\r\n 2.5  1.37311\r\n 3.0  1.68212\r\n```\r\nreturn solusi masalah nilai awal `sol`.\r\n\"\"\"\r\nfunction heun(f,a,b,y0,M)\r\n    M = Int(M)\r\n    h = (b-a)/M;\r\n    T = a:h:b;\r\n    Y = Array{Float64}(undef,length(T),1)\r\n    P = Array{Float64}(undef,length(T),1)\r\n    Y[1] = y0;\r\n    # Mulai langkah iterasi Heun\r\n    for k = 1:M\r\n        #% Rumus iterasi Heun\r\n        P[k+1]=Y[k]+h*f(T[k],Y[k]);\r\n        Y[k+1]=Y[k]+h/2*(f(T[k],Y[k])+f(T[k+1],P[k+1]));\r\n    end\r\n    sol = [T Y];\r\nend\r\n", "meta": {"hexsha": "e25e81cae52388eb5e47064a19ae47d4afa33b05", "size": 953, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/heun.jl", "max_stars_repo_name": "mkhoirun-najiboi/metnum.jl", "max_stars_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/heun.jl", "max_issues_repo_name": "mkhoirun-najiboi/metnum.jl", "max_issues_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/heun.jl", "max_forks_repo_name": "mkhoirun-najiboi/metnum.jl", "max_forks_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0789473684, "max_line_length": 95, "alphanum_fraction": 0.555089192, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.8688267728417087, "lm_q1q2_score": 0.7916573164506279}}
{"text": "# Source: Lanshammar, H. (1982).\n# On precision limits for derivatives numerically calculated from noisy data\n# Journal of Biomechanics 15(6), 459-470\n\n\"\"\"Define parameters for Lanshammar's polynomial filter\"\"\"\nfunction lpparams(n, p; window=epanwin, dt::Real=1.)\n    U = zeros(2n+1,p+1)\n    for k=0:p\n      U[:,k+1] = (-n:n).^k\n    end\n    w = window(2*n+1)\n    W = diagm(w./maximum(w))\n    V = U'*W*U\n    f = map(factorial, 0:p) ./ (-dt).^(0:p)\n    Dict(:h => diagm(f)*(V\\eye(p+1))*U'*W, :p=>p)\nend\n\n\"\"\"Apply Lanshammar polynomial filter\"\"\"\nfunction lpfit(x::Matrix; h::VecOrMat=[1], p::Integer=0);\ny = zeros(size(x)..., p+1)\nfor k=1:p+1\n  y[:,:,k] = filt(collect(h[k,:]),1,x)\nend\ny\nend\n\nfunction lpfit(x::Vector; h::VecOrMat=[1], p::Integer=0);\ny = zeros(length(x), p+1)\nfor k=1:p+1\n  y[:,k] = filt(collect(h[k,:]),1,x)\nend\ny\nend\n\n\"\"\"Table of optimal bandwidths\"\"\"\noptband =\n    [NaN  .275  NaN; # p=1\n     .53  .275  .33; # p=2\n     .53  .600  .33; # p=3\n     .82  .600  .70; # p=4\n     .82  .920  .70; # p=5\n    1.15  .920 1.02; # p=6\n    1.15 1.250 1.02; # p=7\n    1.48 1.250 1.35; # p=8\n    1.48   NaN 1.35] # p=9\n    \nnmin = \n    [0 1 0; # p=1\n     1 1 1; # p=2\n     1 2 1; # p=3\n     2 2 2; # p=4\n     2 3 2; # p=5\n     3 3 3; # p=6\n     3 4 3; # p=7\n     4 4 4; # p=8\n     4 0 4] # p=9\n\nfunction optbandn(p,k,w)\n    !(1 <= p <= size(optband)[1]) &&\n        error(\"polynomial order must be between 1 and $(size(optband)[1])\")\n    !(0 <= k <= size(optband)[2]) &&\n        error(\"the target order of the derivative must be between 0 and $(size(optband)[2])\")\n    isnan(optband[p,k+1]) && error(\"value undefined for p==$p, k==$k\")\n    max(ceil(Integer, optband[p,k+1]/w), nmin[p,k+1])\nend\n", "meta": {"hexsha": "010dbe019ec1a5efa5f3439120653d5e329a72de", "size": 1695, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lanshammar.jl", "max_stars_repo_name": "heliosdrm/LocalPolynomialFitting.jl", "max_stars_repo_head_hexsha": "7d213d4cbf0157af35806c47069e7a9183129900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lanshammar.jl", "max_issues_repo_name": "heliosdrm/LocalPolynomialFitting.jl", "max_issues_repo_head_hexsha": "7d213d4cbf0157af35806c47069e7a9183129900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lanshammar.jl", "max_forks_repo_name": "heliosdrm/LocalPolynomialFitting.jl", "max_forks_repo_head_hexsha": "7d213d4cbf0157af35806c47069e7a9183129900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6818181818, "max_line_length": 93, "alphanum_fraction": 0.5339233038, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009573133051, "lm_q2_score": 0.8652240964782011, "lm_q1q2_score": 0.7915943541584456}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction _eqpole(l::T, b::T, southpole::Bool) where {T<:AbstractFloat}\n    sgn = southpole ? -1 : 1\n    l = deg2rad(sgn*l)\n    b = deg2rad(sgn*b)\n    r = 18 * sqrt(2 * (1 - sin(b))) * 3.53553391\n    return r .* sincos(l)\nend\n\n\"\"\"\n    eqpole(l, b[; southpole = false]) -> x, y\n\n### Purpose ###\n\nConvert right ascension \\$l\\$ and declination \\$b\\$ to coordinate \\$(x, y)\\$\nusing an equal-area polar projection.\n\n### Explanation ###\n\nThe output \\$x\\$ and \\$y\\$ coordinates are scaled to be in the range \\$[-90, 90]\\$\nand to go from equator to pole to equator.  Output map points can be\ncentered on the north pole or south pole.\n\n### Arguments ###\n\n* `l`: longitude, scalar or vector, in degrees\n* `b`: latitude, same number of elements as right ascension, in degrees\n* `southpole` (optional boolean keyword): keyword to indicate that the plot is\n  to be centered on the south pole instead of the north pole.  Default is\n  `false`.\n\n### Output ###\n\nThe 2-tuple \\$(x, y)\\$:\n\n* ``x`` coordinate, same number of elements as right ascension, normalized to be\n  in the range ``[-90, 90]``.\n* ``y`` coordinate, same number of elements as declination, normalized to be\n  in the range ``[-90, 90]``.\n\n### Example ###\n\n```jldoctest\njulia> using AstroLib\n\njulia> eqpole(100, 35, southpole=true)\n(-111.18287262822456, -19.604540237028665)\n\njulia> eqpole(80, 19)\n(72.78853915267848, 12.83458333897169)\n```\n\n### Notes ###\n\nCode of this function is based on IDL Astronomy User's Library.\n\"\"\"\neqpole(l::Real, b::Real; southpole::Bool=false) =\n    _eqpole(promote(float(l), float(b))..., southpole)\n\nfunction eqpole(l::AbstractArray{L}, b::AbstractArray{<:Real};\n                southpole::Bool=false) where {L<:Real}\n    @assert length(l) == length(b)\n    typel = float(L)\n    x = similar(l, typel)\n    y = similar(l, typel)\n    for i in eachindex(l)\n        x[i], y[i] = eqpole(l[i], b[i], southpole=southpole)\n    end\n    return x, y\nend\n", "meta": {"hexsha": "e171b3f947e791ddfc5eda84e8e3e560ac21e940", "size": 2020, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/eqpole.jl", "max_stars_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_stars_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2016-09-11T14:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T20:45:36.000Z", "max_issues_repo_path": "src/eqpole.jl", "max_issues_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_issues_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 64, "max_issues_repo_issues_event_min_datetime": "2017-01-19T21:03:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:27:46.000Z", "max_forks_repo_path": "src/eqpole.jl", "max_forks_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_forks_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:11:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:55:21.000Z", "avg_line_length": 27.6712328767, "max_line_length": 82, "alphanum_fraction": 0.647029703, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.7915943445382672}}
{"text": "\nusing Unitful\nt = 1.0u\"s\"\n\n\nt2 = 1.02u\"s\"\nt+t2\n\n\nt*t2\n\n\nsqrt(t)\n\n\nt + sqrt(t)\n\n\nusing DifferentialEquations\nf = (y,p,t) -> 0.5*y\nu0 = 1.5u\"N\"\nprob = ODEProblem(f,u0,(0.0u\"s\",1.0u\"s\"))\nsol = solve(prob,Tsit5())\n\n\nf = (y,p,t) -> 0.5*y/3.0u\"s\"\nprob = ODEProblem(f,u0,(0.0u\"s\",1.0u\"s\"))\nsol = solve(prob,Tsit5())\n\n\nprint(sol[:])\n\n\nusing Plots\ngr()\nplot(ustrip(sol.t),ustrip(sol[:]),lw=3)\n\n\nusing SciMLTutorials\nSciMLTutorials.tutorial_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])\n\n", "meta": {"hexsha": "fa5b37cb0430e66b87305ca0fadaad44bfe675c2", "size": 479, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/type_handling/03-unitful.jl", "max_stars_repo_name": "siravan/SciMLTutorials.jl", "max_stars_repo_head_hexsha": "34f4044f96facf351eb32c991b73325a32d17a94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-05-24T10:30:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T12:13:03.000Z", "max_issues_repo_path": "script/type_handling/03-unitful.jl", "max_issues_repo_name": "LoopGlitch26/SciMLTutorials.jl", "max_issues_repo_head_hexsha": "837d71ad59de12af2fa48babb9e5cd2e280dc71a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-07T21:39:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T03:48:31.000Z", "max_forks_repo_path": "script/type_handling/03-unitful.jl", "max_forks_repo_name": "LoopGlitch26/SciMLTutorials.jl", "max_forks_repo_head_hexsha": "837d71ad59de12af2fa48babb9e5cd2e280dc71a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-24T14:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T14:30:36.000Z", "avg_line_length": 11.4047619048, "max_line_length": 69, "alphanum_fraction": 0.624217119, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.865224073888819, "lm_q1q2_score": 0.7915943354989995}}
{"text": "# Robertson chemical reaction:\n#\n# Adapted from\n# http://www.unige.ch/~hairer/testset/testset.html\n# reference solution from\n# http://www.dm.uniba.it/~testset/problems/rober.php\n#\n# See also:\n# http://octave.sourceforge.net/odepkg/function/odepkg_testsuite_robertson.html\n#\n# Note that this runs over large tspan = [0,1e11] with the first step being < 1!\n\nexport rober\n\nrober = let\n    tcname = :rober\n    T = Float64 # the datatype used\n    Tarr = Matrix\n    dof = 3 # degrees of freedom\n    dae=0\n    # stiffness of system, one of the three constants\n    stiffness = [nonstiff, mildlystiff, stiff][3] \n    function fn!(t,y,dydt)\n        # the ode function\n        dydt[1] = -0.04*y[1] + 1.0e4*y[2]*y[3]\n        dydt[3] = 3.0e7 *y[2]*y[2]\n        dydt[2] = -dydt[1]-dydt[3]\n        nothing\n    end\n    # initializes storage for y:\n    fn!( ; T_::Type=T, dof_=dof) = zeros(T_,dof_)\n    \n    function jac!(t,y,dfdy)\n        # the Jacobian of f\n        prod1 = 1.0e4*y[2]\n        prod2 = 1.0e4*y[3]\n        prod3 = 6.0e7*y[2]\n        dfdy[1,1] = -0.04\n        dfdy[1,2] = prod2\n        dfdy[1,3] = prod1\n        dfdy[2,1] = 0.04\n        dfdy[2,2] = -prod2-prod3\n        dfdy[2,3] = -prod1\n        dfdy[3,1] = 0.0\n        dfdy[3,2] = prod3\n        dfdy[3,3] = 0.0\n        return nothing\n    end\n    jac!( ; T_::Type=T, dof_=dof) = zeros(T_,dof_,dof_)  # if the problem is large better return an appropriate sparse matrix\n\n    # mass matrix M(t,y) dydt = f(t,y)\n    mass! = nothing\n    \n    ic = T[1,0,0] # vector of initial conditions\n    tspan = T[0, 1e11] # integration interval\n    refsol = T[0.2083340149701255e-07,\n               0.8333360770334713e-13,\n               0.9999999791665050] # reference solution at tspan[2]\n    refsolinds = trues(dof)\n    scd_absinds = falses(dof)\n    \n    tc = TestCaseExplicit{tcname, T, Tarr}(\n                             stiffness,\n                             dae,\n                             dof,\n                             fn!,\n                             jac!,\n                             mass!,\n                             ic,\n                             tspan,\n                             refsol,\n                             refsolinds,\n                             scd_absinds)\n\n    tc_all[tcname] = tc\n    tc_stiff[tcname] = tc\nend\n    \n", "meta": {"hexsha": "03ff8d4a1a1816aabc5f01e3e7cb6ebc1c5e0eee", "size": 2293, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/testcases/rober.jl", "max_stars_repo_name": "pwl/IVPTestSuite.jl", "max_stars_repo_head_hexsha": "15d92b5b943c35493ce29e8aa8def14619d96760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/testcases/rober.jl", "max_issues_repo_name": "pwl/IVPTestSuite.jl", "max_issues_repo_head_hexsha": "15d92b5b943c35493ce29e8aa8def14619d96760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/testcases/rober.jl", "max_forks_repo_name": "pwl/IVPTestSuite.jl", "max_forks_repo_head_hexsha": "15d92b5b943c35493ce29e8aa8def14619d96760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0253164557, "max_line_length": 125, "alphanum_fraction": 0.5067597034, "num_tokens": 737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7915695082891775}}
{"text": "\"\"\"\n    GeneralizedGaussian( μ, α, β )\n\nThe \"Generalized Normal\" or \"Generalized Gaussian\" with shape parameter 'β',\nscale 'α', and location 'μ' has probability density function\n\n```math\nf(x; \\\\mu \\\\alpha \\\\beta ) = \\\\frac{\\\\beta}{2\\\\alpha\\\\Gamma(1/\\\\beta)}\n\\\\text{exp}\\\\left( -|x - \\\\mu|/\\\\alpha \\\\right),\n\n\\\\alpha = \\\\sigma \\\\sqrt{ \\\\frac{\\\\Gamma(1/\\\\beta)}{\\\\Gamma(3/\\\\beta)} }\n\n```\nwhere `β = 1` incorporates the Laplacian distribution, `β = 2` is the Normal distribution,\nand as `β → ∞`, the distribution approaches Uniform on `[μ-α, μ+α]`.\n\n```julia\nGeneralizedGaussian(m, a, b)    # Generalized Gaussian with mu, alpha, and beta.\nparams(d)                       # Get the parameters (m,a,b)\nshape(d)                        # returns β shape\nscale(d)                        # returns the scale parameter, α\n```\n\nExternal Links\n* [Generalized Normal Distribution on Wikipedia](https://en.wikipedia.org/wiki/Generalized_normal_distribution)\n* [Reference implementation paper](https://www.researchgate.net/publication/254282790_Simulation_of_the_p-generalized_Gaussian_distribution)\n\nReferences\n[1] Nadarajah, Saralees (September 2005). \"A generalized normal distribution\".\n    Journal of Applied Statistics. 32 (7): 685&ndash, 694.\n[2]  Gonzalez-Farias, G., Molina, J. A. D., & Rodríguez-Dagnino, R. M. (2009).\n    Efficiency of the approximated shape parameter estimator in the generalized\n    Gaussian distribution. IEEE Transactions on Vehicular Technology, 58(8),\n    4214-4223.\n\"\"\"\nstruct GeneralizedGaussian{T<:Real}\n    μ::T\n    α::T\n    β::T\n    function GeneralizedGaussian{T}(μ::T, α::T, β::T) where T\n        α > zero(α) || error(\"standard deviation must be positive.\")\n        β > zero(β) || error(\"β must be greater than zero.\")\n        new{T}(μ, α, β)\n    end\nend\n\nGeneralizedGaussian(μ::T, α::T, β::T) where {T<:Real} = GeneralizedGaussian{T}(μ, α, β)\nGeneralizedGaussian(μ::Real, α::Real, β::Real) = GeneralizedGaussian(promote(μ, α, β)...)\nGeneralizedGaussian(μ::Integer, σ::Integer, β::Integer) = GeneralizedGaussian(Float64(μ), Float64(σ), Float64(β))\n\n\"\"\"\n    GeneralizedGaussian(β)\n\nBuilds a default distribution with shape `β` and `μ=0, α=1`.\n\"\"\"\nGeneralizedGaussian(β::Real) = GeneralizedGaussian(zero(β), one(β), β)\n\n\"\"\"\n    GeneralizedGaussian()\n\nBuilds the Normal distribution case, where `μ=0, α=√2, β=2`, or N(0, 1).\n\"\"\"\nGeneralizedGaussian() = GeneralizedGaussian(0.0, √2, 2)\n\n### Conversion\nfunction convert(::Type{GeneralizedGaussian{T}}, μ::Real, σ::Real, β::Real) where T <: Real\n    GeneralizedGaussian(T(μ), T(α), T(β))\nend\nfunction convert(::Type{GeneralizedGaussian{T}}, d::GeneralizedGaussian{S}) where {T <: Real, S <: Real}\n    GeneralizedGaussian(T(d.μ), T(d.α), T(d.β))\nend\n\n### Parameters\nparams(d::GeneralizedGaussian) = (d.μ, d.α, d.β)\nlocation(d::GeneralizedGaussian) = d.μ\nscale(d::GeneralizedGaussian) = d.α\nshape(d::GeneralizedGaussian) = d.β\n\nvar(d::GeneralizedGaussian) = (d.α^2) * (gamma(3.0 * inv(d.β)) / gamma(inv(d.β)))\nstd(d::GeneralizedGaussian) = (d.α) * sqrt(gamma(3.0 * inv(d.β)) / gamma(inv(d.β)))\n\nmean(d::GeneralizedGaussian) = d.μ\nmedian(d::GeneralizedGaussian) = d.μ\nmode(d::GeneralizedGaussian) = d.μ\n\n### Statistics\nskewness(d::GeneralizedGaussian{T}) where T = zero(T)\nkurtosis(d::GeneralizedGaussian) = gamma(5.0 * inv(d.β)) * gamma(inv(d.β)) / (gamma(3.0 * inv(d.β))^2) - 3.0\nentropy(d::GeneralizedGaussian) = inv(d.β) - log( d.β / (2.0 * d.α * gamma(inv(d.β))))\n\n### Evaluation\nfunction pdf(d::GeneralizedGaussian{T}, x::Real) where T<:Real\n    if x == -Inf || x == Inf\n        return zero(T)\n    else\n        A = d.β / (2.0 * d.α * gamma(1. / d.β) )\n        return A * exp( -(abs(x - d.μ) / d.α)^d.β )\n    end\nend\nlogpdf(d::GeneralizedGaussian, x::Real) = log(pdf(d, x))\n\n\n\"\"\"\n    cdf(d, x)\nCalculates the CDF of the distribution. To determine the CDF, the incomplete\ngamma function is required. The CDF  of the Gamma distribution provides this,\nwith the necessary 1/Γ(a) normalization.\n\"\"\"\nfunction cdf(d::GeneralizedGaussian{T}, x::Real) where T<:Real\n    if x == -Inf || x == Inf\n        return zero(T)\n    else\n        v = cdf(Gamma(inv(d.β), 1), (abs(x - μ) / d.α)^d.β) * inv(2)\n        return typeof(v)(1/2) + sign(x - μ) * v\n    end\nend\n\n\n\"\"\"\n    rand(rng, d)\nExtract a sample from the Generalized Gaussian distribution `d`. The sampling\nprocedure is implemented from from [2].\n\"\"\"\nfunction rand(rng::AbstractRNG, d::GeneralizedGaussian)\n    # utilizing the sampler from the Gamma distribution.\n    g = Gamma(inv(d.β), 1)\n    # random variable with value -1 or 1 with probability (1/2).\n    b = 2.0 * rand(Bernoulli()) - 1\n    return d.μ + inv(sqrt(d.α)) * rand(rng, g)^inv(d.β) * b\nend\n\n# multi-sample case\nfunction rand(rng::AbstractRNG, d::GeneralizedGaussian, dims::Dims)\n    out = Array{eltype(params(d))}(undef, dims)\n    @inbounds for i in eachindex(out)\n        out[i] = rand(rng, d)\n    end\n    out\nend\n\n# various function signatures for sampling the distribution.\nrand(d::GeneralizedGaussian) = rand(GLOBAL_RNG, d)\nrand(d::GeneralizedGaussian, dims::Dims) = rand(GLOBAL_RNG, d, dims)\nrand(d::GeneralizedGaussian, dims::Int) = rand(GLOBAL_RNG, d, (dims))\nrand(rng::AbstractRNG, d::GeneralizedGaussian, dim::Int, dims::Int...) = rand(rng, d, (dim, dims...))\nrand(d::GeneralizedGaussian, dims::Int...) = rand(GLOBAL_RNG, d, dims...)\n\n\nfunction Zn(X::AbstractArray, β::Real)\n    n = size(X,1)\n    S1 = 1/n * sum(abs.(X).^(2β))\n    S2 = 1/n * sum(abs.(X).^β)\n    return (S1/(S2^2)) - (β + 1)\nend\n\nfunction Zn′(X::AbstractArray, β::Real)\n    n = size(X,1)\n    S1 = sum(abs.(X).^β) # sum\n    S2 = sum(abs.(X).^(2β))\n    L1 = sum(abs.(X).^β .* log.(abs.(X)))    # log\n    L2 = sum(abs.(X).^(2β) .* log.(abs.(X)))\n    num1 = (2/n * L2) * (1/n * S1)^2\n    denom = (1/n * S1)^4\n    num2 = (1/n * L1) * (1/n * S2) * (2/n * S1)\n    return (num1/denom) - (num2/denom) - 1\nend\n\n\"\"\"\n    β = gcmsearch(X::AbstractArray, βi::Real)\n\nGlobally convergent method for β-parameter estimation using Newton-Raphson\niterative search from [1].\n\n[1] Song, Kai-Sheng. \"A globally convergent and consistent method \n    for estimating the shape parameter of a generalized Gaussian distribution.\" \n    IEEE Transactions on Information Theory 52.2 (2006): 510-527.\n\"\"\"\nfunction gcmsearch(X::AbstractArray{T}, βi::Real) where T<:AbstractFloat\n    ϵ = √eps(T)\n    N_MAX = 1_000\n    βp = copy(βi)\n    num, denom = Zn(X, βp), Zn′(X, βp)\n    βn = βp - (num/denom)\n    βp = copy(βn)\n    for _ = 2:N_MAX\n        num, denom = Zn(X, βp), Zn′(X, βp)\n        βn = βp - (num/denom)\n        if (abs(βn - βp) < ϵ) # check if converged?\n            break\n        else\n            βp = copy(βn) # prep for next iteration.\n        end\n    end\n    βn\nend\n    \n", "meta": {"hexsha": "0a51bb2842dd4465a66235da5dddb57c312cb2b3", "size": 6701, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/generalizedgaussian.jl", "max_stars_repo_name": "jsmithnh09/GGD.jl", "max_stars_repo_head_hexsha": "405d2dc01035a921f88288f9267aeacc5e771bd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/generalizedgaussian.jl", "max_issues_repo_name": "jsmithnh09/GGD.jl", "max_issues_repo_head_hexsha": "405d2dc01035a921f88288f9267aeacc5e771bd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/generalizedgaussian.jl", "max_forks_repo_name": "jsmithnh09/GGD.jl", "max_forks_repo_head_hexsha": "405d2dc01035a921f88288f9267aeacc5e771bd7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0152284264, "max_line_length": 140, "alphanum_fraction": 0.632442919, "num_tokens": 2235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7915695047652488}}
{"text": "## Julia program for Calculation of Gamma function\r\n## author: weiya <szcfweiya@gmail.com>\r\n## date: 2018-08-21\r\n##\r\n## refer to \"Coefficients for the Lanczos Approximation to the Gamma Function\"\r\n##   https://mrob.com/pub/ries/lanczos-gamma.html\r\n\r\nconst LG_g = 5.0;\r\nconst LG_N = 6;\r\nconst lct = [\r\n    1.000000000190015,\r\n    76.18009172947146,\r\n    -86.50532032941677,\r\n    24.01409824083091,\r\n    -1.231739572450155,\r\n    0.1208650973866179e-2,\r\n    -0.5395239384953e-5];\r\nconst ln_sqrt_2_pi = 0.91893853320467274178;\r\nconst g_pi = 3.14159265358979323846;\r\n\r\nfunction lanczos_ln_gamma(z)\r\n    if z < 0.5\r\n        #Use Euler's reflection formula:\r\n        #Gamma(z) = Pi / [Sin[Pi*z] * Gamma[1-z]];\r\n        return log(g_pi / sin(g_pi * z)) - lanczos_ln_gamma(1.0 - z);\r\n    end\r\n    z = z - 1.0;\r\n    base = z + LG_g + 0.5;  # Base of the Lanczos exponential\r\n    sum = 0;\r\n    ## We start with the terms that have the smallest coefficients and largest denominator.\r\n    for i = 2:LG_N+1\r\n      sum += lct[i] / (z + i - 1);\r\n    end\r\n    sum += lct[1];\r\n    ## This printf is just for debugging\r\n#    @printf(\"ls2p %7g  l(b^e) %7g   -b %7g  l(s) %7g\\n\", ln_sqrt_2_pi,\r\n#              log(base)*(z+0.5), -base, log(sum));\r\n    ## Gamma[z] = Sqrt(2*Pi) * sum * base^[z + 0.5] / E^base\r\n    return ((ln_sqrt_2_pi + log(sum)) - base) + log(base)*(z+0.5);\r\nend\r\n\r\nfunction lanczos_gamma(z)\r\n    return(exp(lanczos_ln_gamma(z)));\r\nend\r\n\r\n## example\r\nlanczos_gamma(1)", "meta": {"hexsha": "004a0b6ce23c3545f020f0c713710461b22deb8d", "size": 1465, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "GenRV/func_gamma.jl", "max_stars_repo_name": "szcf-weiya/MCMC", "max_stars_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-07-19T12:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T08:06:50.000Z", "max_issues_repo_path": "GenRV/func_gamma.jl", "max_issues_repo_name": "szcf-weiya/MCMC", "max_issues_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-02-03T15:08:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-05T15:41:39.000Z", "max_forks_repo_path": "GenRV/func_gamma.jl", "max_forks_repo_name": "szcf-weiya/MCMC", "max_forks_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-07-19T12:50:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T08:06:52.000Z", "avg_line_length": 31.170212766, "max_line_length": 92, "alphanum_fraction": 0.6034129693, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7915695028966291}}
{"text": "_rescale(x, m, M) = (x .- minimum(x))./(maximum(x)-minimum(x)).*(M-m).+m\n\n\"\"\"\n    rescale!(layer::TI, template::TJ) where {TI <: SimpleSDMLayer, TJ <: SimpleSDMLayer}\n\nChanges the values of the layer given as its first argument, so that it has the\nsame *range* as the values of the layer given as its second argument.\nModification is done in-place.\n\"\"\"\nfunction rescale!(layer::TI, template::TJ) where {TI <: SimpleSDMLayer, TJ <: SimpleSDMLayer}\n    return rescale!(layer, extrema(template))\nend\n\n\"\"\"\n    rescale!(layer::TI, t::Tuple{T,T}) where {TI <: SimpleSDMLayer, T <: Number}\n\nChanges the values of the layer given as its first argument, so that it has the\nsame *range* as the values given as a tuple of values. Modification is done\nin-place.\n\"\"\"\nfunction rescale!(layer::TI, t::Tuple{T,T}) where {TI <: SimpleSDMLayer, T <: Number}\n    occ = findall(!isnothing, layer.grid)\n    layer.grid[occ] .= _rescale(layer.grid[occ], t...)\nend\n\n\"\"\"\n    rescale(layer::TI, template::TJ) where {TI <: SimpleSDMLayer, TJ <: SimpleSDMLayer}\n\nCopying version of `rescale!`.\n\"\"\"\nfunction rescale(layer::TI, template::TJ) where {TI <: SimpleSDMLayer, TJ <: SimpleSDMLayer}\n    l = copy(layer)\n    return rescale!(l, extrema(template))\nend\n\n\"\"\"\n    rescale(layer::TI, t::Tuple{T,T}) where {TI <: SimpleSDMLayer, T <: Number}\n\nCopying version of `rescale!`.\n\"\"\"\nfunction rescale(layer::TI, t::Tuple{T,T}) where {TI <: SimpleSDMLayer, T <: Number}\n    l = copy(layer)\n    return rescale!(l, t)\nend\n\n\n\"\"\"\n    rescale!(layer::T, p::Vector{Real}) where {T <: SimpleSDMLayer}\n\nRescale the values of a `layer` so that they match with the quantiles given in\n`p`. Internally, this uses the `Statistics.quantile` function.\n\"\"\"\nfunction rescale!(layer::T, p::Vector{TI}) where {T <: SimpleSDMLayer, TI <: AbstractFloat}\n    q = reverse!(quantile(layer, p))\n    occupied = findall(!isnothing, layer.grid)\n    v = collect(layer)\n    for i in 1:length(q)\n        layer.grid[occupied[findall(x -> x <= q[i], v)]] .= reverse(p)[i]\n    end\n    return layer\nend \n\n\"\"\"\n    rescale(layer::T, p::Vector{Real}) where {T <: SimpleSDMLayer}\n\nCopying version of `rescale!`.\n\"\"\"\nfunction rescale(layer::T, p::Vector{TI}) where {T <: SimpleSDMLayer, TI <: AbstractFloat}\n    l = copy(layer)\n    return rescale!(l, p)\nend", "meta": {"hexsha": "4d8da913428802b00f01e9f89d224243f2a03f6e", "size": 2282, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operations/rescale.jl", "max_stars_repo_name": "gottacatchenall/SimpleSDMLayers.jl", "max_stars_repo_head_hexsha": "7c3316ca92e543104fadb3228873f74cd2c77121", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/operations/rescale.jl", "max_issues_repo_name": "gottacatchenall/SimpleSDMLayers.jl", "max_issues_repo_head_hexsha": "7c3316ca92e543104fadb3228873f74cd2c77121", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/operations/rescale.jl", "max_forks_repo_name": "gottacatchenall/SimpleSDMLayers.jl", "max_forks_repo_head_hexsha": "7c3316ca92e543104fadb3228873f74cd2c77121", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1408450704, "max_line_length": 93, "alphanum_fraction": 0.6652059597, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.791569502256696}}
{"text": "using NiLang, NiLang.AD\nusing LinearAlgebra\n\nfunction _iqr(A)\n    @assert size(A, 1) == size(A, 2)\n    N = size(A, 1)\n    Q = zero(A)\n    R = zero(A)\n    for col = 1:N\n        ri = A[:,col]\n        for precol = 1:col-1\n            ni = Q[:,precol]'*ri\n            R[precol,col] = ni\n            ri = ri - ni*Q[:,precol]\n        end\n        R[col, col] = norm(ri)\n        Q[:,col] = ri/R[col,col]\n    end\n    return Q, R\nend\n\n@i function iqr(Q, R, A::AbstractMatrix{T}) where T\n    @anc anc_norm = zero(T)\n    @anc anc_dot = zeros(T, size(A,2))\n    @anc ri = zeros(T, size(A,1))\n    for col = 1:size(A, 1)\n        ri .+= identity.(A[:,col])\n        for precol = 1:col-1\n            idot(anc_dot[precol], Q[:,precol], ri)\n            R[precol,col] += identity(anc_dot[precol])\n            for row = 1:size(Q,1)\n                ri[row] -= anc_dot[precol] * Q[row, precol]\n            end\n        end\n        inorm2(anc_norm, ri)\n\n        R[col, col] += anc_norm^0.5\n        for row = 1:size(Q,1)\n            Q[row,col] += ri[row] / R[col, col]\n        end\n\n        ~begin\n            ri .+= identity.(A[:,col])\n            for precol = 1:col-1\n                idot(anc_dot[precol], Q[:,precol], ri)\n                for row = 1:size(Q,1)\n                    ri[row] -= anc_dot[precol] * Q[row, precol]\n                end\n            end\n            inorm2(anc_norm, ri)\n        end\n    end\nend\n\nusing Test, Random\n@testset \"test qr\" begin\n    Random.seed!(2)\n    A = randn(4,4)\n    Q, R = _iqr(A)\n    @test Q * R ≈ A\n    @test Q'*Q ≈ I\n    R[abs.(R).<1e-10] .= 0.0\n    @test istriu(R)\n\n    q = zero(A)\n    r = zero(A)\n    @instr iqr(q, r, A)\n    @test q ≈ Q\n    @test r ≈ R\n    @test check_inv(iqr, (q, r, A))\n\n    @i function test1(out, q, r, A)\n        iqr(q, r, A)\n        out += identity(q[1,2])\n    end\n    @i function test2(out, q, r, A)\n        iqr(q, r, A)\n        out += identity(r[1,2])\n    end\n    @test check_grad(test1, (Loss(0.0), q, r, A); atol=0.05, verbose=true)\n    @test check_grad(test2, (Loss(0.0), q, r, A); atol=0.05, verbose=true)\nend\n", "meta": {"hexsha": "d0ca006cef3966e88d6cb6dad976fc8df9fd0db9", "size": 2056, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "project/qr.jl", "max_stars_repo_name": "PallHaraldsson/NiLang.jl", "max_stars_repo_head_hexsha": "09e4c5f044ca8b02b78a4c3cb7f307a5ce35b981", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project/qr.jl", "max_issues_repo_name": "PallHaraldsson/NiLang.jl", "max_issues_repo_head_hexsha": "09e4c5f044ca8b02b78a4c3cb7f307a5ce35b981", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project/qr.jl", "max_forks_repo_name": "PallHaraldsson/NiLang.jl", "max_forks_repo_head_hexsha": "09e4c5f044ca8b02b78a4c3cb7f307a5ce35b981", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7710843373, "max_line_length": 74, "alphanum_fraction": 0.4664396887, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7915464370673595}}
{"text": "function z2gk(A::Float64, B::Float64, g::Float64, k::Float64, z::Float64, c=0.8)\n    temp = exp(-g*z)\n    A + B*(1.0+c*(1.0-temp)/(1.0+temp))*(1.0+z^2)^k*z    \nend\n\nfunction rgk(pars)\n    (A,B,g,k) = pars\n    z = randn()\n    z2gk(A, B, g, k, z)\nend\n\n##Simulates U(0,1) order statistics specified in \"orderstats\" from n total sims\n##orderstats should be in ascending order\n##See Ripley \"Stochastic Simulation\" pg 98\nfunction unif_os(orderstats::Array{Int,1}, n::Int)\n    p = size(orderstats)[1]\n    w = Array{Float64}(p+1)\n    w[1] = rand(Gamma(orderstats[1]))\n    for i in 2:p\n        w[i] = rand(Gamma(orderstats[i] - orderstats[i-1]))\n    end\n    w[p+1] = rand(Gamma(n + 1 - orderstats[p]))\n    wsums = cumsum(w)\n    wsums[1:p] / wsums[p+1]\nend\n\n##Efficiently simulates g&k order statistics specified in \"orderstats\" from n total sims\n##orderstats should be in ascending order\nfunction rgk_os(pars::Array{Float64,1}, orderstats::Array{Int,1}, n::Int)\n    (A,B,g,k) = pars\n    u = unif_os(orderstats, n)\n    z = quantile.(Normal(), u)\n    map((x)->z2gk(A,B,g,k,x), z)\nend\n", "meta": {"hexsha": "17023460a839ef5aadd70d1510796bfcb2d76e7b", "size": 1073, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gk.jl", "max_stars_repo_name": "dennisprangle/ABCDistances.jl", "max_stars_repo_head_hexsha": "beb5a511685f2290266732cbc2ee352d00835112", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-06-11T15:41:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-20T12:01:06.000Z", "max_issues_repo_path": "src/gk.jl", "max_issues_repo_name": "dennisprangle/ABCDistances.jl", "max_issues_repo_head_hexsha": "beb5a511685f2290266732cbc2ee352d00835112", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-09-21T17:01:30.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-20T06:53:50.000Z", "max_forks_repo_path": "src/gk.jl", "max_forks_repo_name": "dennisprangle/ABCDistances.jl", "max_forks_repo_head_hexsha": "beb5a511685f2290266732cbc2ee352d00835112", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-06-11T15:41:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T12:57:13.000Z", "avg_line_length": 30.6571428571, "max_line_length": 88, "alphanum_fraction": 0.624417521, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7915464242160126}}
{"text": "# Algorithm 5.1\n# Euler's method\n\nfunction euler(f, a, b, N, α)\n\tresult = Tuple{Float64, Float64}[]\n\th = (b - a)/N\n\tt = α\n\tω = α\n\tpush!(result, (t, ω))\n\tfor i ∈ 1:N\n\t\tω = ω + h*f(t, ω)\n\t\tt = a + i*h\n\t\tpush!(result, (t, ω))\n\tend\n\treturn result\nend\n\nf(t, y) = y -t^2 + 1\nprintln(euler(f, 0, 2, 10, 0.5))\n", "meta": {"hexsha": "3e6bf8bd8789719b0306a0a145af4c496d0f29b5", "size": 302, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter5/euler.jl", "max_stars_repo_name": "Matt8898/julia-numerical", "max_stars_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-05T01:36:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-26T04:07:41.000Z", "max_issues_repo_path": "chapter5/euler.jl", "max_issues_repo_name": "Matt8898/julia-numerical", "max_issues_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter5/euler.jl", "max_forks_repo_name": "Matt8898/julia-numerical", "max_forks_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.1, "max_line_length": 35, "alphanum_fraction": 0.5231788079, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810511092412, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7915212754463278}}
{"text": "\n\"\"\"\n    cheb(xmin, xmax, N)\n\nReturn a Chebyshev-Lobatto grid, together with its first and second\ndifferentiation matrices.\n\n# Arguments\n* `xmin::Real`: rightmost grid point\n* `xmax::Real`: leftmost grid point\n* `N::Integer`: total number of grid points\n\"\"\"\nfunction cheb(xmin::T, xmax::T, N::Integer) where {T<:Real}\n    x, D, D2 = cheb(N)\n    x = 0.5 * (xmax + xmin .+ (xmax - xmin) * x)\n    D  ./= 0.5 * (xmax - xmin)\n    D2 ./= 0.25 * (xmax - xmin)^2\n    x, D, D2\nend\n\n\n# taken from Trefethen (2000), \"Spectral Methods in MatLab\"\n\n\"When omitting grid limits, default to [-1,1] interval\"\nfunction cheb(N::Integer)\n    @assert(N > 1, \"number of points should be greater than 1...\")\n    M = N - 1\n    x = -cos.(pi*(0:M)/M)\n\n    c  = [2; ones(M-1, 1); 2] .* (-1).^(0:M)\n    X  = repeat(x, 1, N)\n    dX = X - X'\n\n    D = (c * (1 ./ c)') ./ (dX + Matrix(I, N, N))  # off-diagonal entries\n    D = D - diagm(0 => sum(D', dims=1)[:])         # diagonal entries\n\n    x, D, D*D\nend\n\n\n\"\"\"\n    fourier(xsize, N)\n\nReturn the first and second derivative matrices on a Fourier grid\n\n# Arguments\n* `xsize::Real`: size of (periodic) domain\n* `N::Integer`: total number of grid points\n\"\"\"\nfunction fourier(xsize::T, N::Integer) where {T<:Real}\n    D, D2 = fourier(N)\n    pi_ = T(pi)\n    D  ./= xsize / (2*pi_)\n    D2 ./= xsize^2 / (4*pi_^2)\n    D, D2\nend\n\n# taken from Trefethen (2000), \"Spectral Methods in MatLab\"\n\n\"When omitting `xsize`, default to 2π\"\nfunction fourier(N::Integer)\n    @assert(mod(N,2)==0, \"number of points needs to be even\")\n    h = 2*pi/N\n\n    column = [0; 0.5*(-1).^(1:N-1) .* cot.((1:N-1)*h/2)]\n    tmp = [circshift(column, i) for i in 0:N-1]\n    D   = hcat(tmp...)\n\n    column2 = [-pi^2/(3*h^2) - 1/6; -0.5*(-1).^(1:N-1) ./ sin.((1:N-1)*h/2).^2]\n    tmp = [circshift(column2, i) for i in 0:N-1]\n    D2  = hcat(tmp...)\n\n    D, D2\nend\n\n\nstruct ChebInterpolator{T,A,FT<:FFTW.r2rFFTWPlan}\n    xmin     :: T\n    xmax     :: T\n    c        :: A\n    fft_plan :: FT\nend\n\"\"\"\n    ChebInterpolator(xmin, xmax, N)\n\nBuild an interpolator to act on functions defined on a Chebyshev-Lobatto grid.\nUses `FFTW`.\n\n# Arguments\n* `xmin::Real`: rightmost grid point\n* `xmax::Real`: leftmost grid point\n* `N::Integer`: total number of grid points\n\"\"\"\nfunction ChebInterpolator(xmin::T, xmax::T, N::Int) where {T<:Real}\n    M  = N - 1\n    x  = Vector{T}(undef, N)\n\n    # use only one thread for the FFTW! by default it allocates a bunch of them,\n    # and it hurts performance (by a huge amount!) when using this inside loops.\n    # it's much better to thread the loops themselves, which is what we do.\n    FFTW.set_num_threads(1)\n\n    # Create the FFT plan for the DCT-I\n    fft_plan = FFTW.plan_r2r(x, FFTW.REDFT00)\n\n    c  = M * [2; ones(Int,M-1); 2] .* (-1).^(0:M)\n\n    ChebInterpolator{T,typeof(c),typeof(fft_plan)}(xmin, xmax, c, fft_plan)\nend\n\"\"\"\n    ChebInterpolator(xp::Vector)\n\nBuild it directly from a `Vector` with the grid points\n\"\"\"\nChebInterpolator(xp::Vector) = ChebInterpolator(xp[1], xp[end], length(xp))\n\n\"\"\"\n# Examples\n\n```\njulia> xx, = Jecco.cheb(0.0, 2.0, 16);\n\njulia> f = xx.^2;\n\njulia> interp = Jecco.ChebInterpolator(xx);\n\njulia> f_interp = interp(f);\n\njulia> f_interp(0.2)\n0.03999999999999987\n```\n\"\"\"\nfunction (interp::ChebInterpolator)(fp)\n    # compute the DCT-I of the coefficients\n    fft_fp = interp.fft_plan * fp\n\n    # compute the spectral coefficients\n    spec_coeff = fft_fp ./ interp.c\n\n    function (x0::T) where {T<:Real}\n        @assert interp.xmin <= x0 <= interp.xmax\n        X = (2 * x0 - (interp.xmin + interp.xmax)) / (interp.xmax - interp.xmin)\n        sum_l = zero(T)\n        @fastmath @inbounds for i in LinearIndices(spec_coeff)\n            sum_l += spec_coeff[i] * cos( (i-1)*acos(X) )\n        end\n        sum_l\n    end\nend\n", "meta": {"hexsha": "907addef17eb56ab1a741e76bea3fefe56741690", "size": 3761, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spectral.jl", "max_stars_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_stars_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-09-08T23:37:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:19:01.000Z", "max_issues_repo_path": "src/spectral.jl", "max_issues_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_issues_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-02T17:57:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-02T17:57:23.000Z", "max_forks_repo_path": "src/spectral.jl", "max_forks_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_forks_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-02-26T15:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T08:46:55.000Z", "avg_line_length": 25.0733333333, "max_line_length": 80, "alphanum_fraction": 0.5990428078, "num_tokens": 1298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666346, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7915212685409743}}
{"text": "\"\"\"\n    ExponentiatedKernel()\n\nThe exponentiated kernel is a Mercer kernel given by:\n```\n    κ(x,y) = exp(xᵀy)\n```\n\"\"\"\nstruct ExponentiatedKernel <: SimpleKernel end\n\nkappa(κ::ExponentiatedKernel, xᵀy::Real) = exp(xᵀy)\n\nmetric(::ExponentiatedKernel) = DotProduct()\n\niskroncompatible(::ExponentiatedKernel) = true\n\nBase.show(io::IO, ::ExponentiatedKernel) = print(io, \"Exponentiated Kernel\")\n", "meta": {"hexsha": "73eba7d060914b8761d3242aa9bfe190c0422178", "size": 391, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basekernels/exponentiated.jl", "max_stars_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_stars_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-22T12:11:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-22T12:11:38.000Z", "max_issues_repo_path": "src/basekernels/exponentiated.jl", "max_issues_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_issues_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basekernels/exponentiated.jl", "max_forks_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_forks_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7222222222, "max_line_length": 76, "alphanum_fraction": 0.7186700767, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.8479677545357569, "lm_q1q2_score": 0.7915192335540979}}
{"text": "# Logistic loss function\n\nexport LogisticLoss\n\n\"\"\"\n**Logistic loss**\n\n    LogisticLoss(y, μ=1)\n\nReturns the function\n```math\nf(x) = μ⋅∑_i log(1+exp(-y_i⋅x_i))\n```\nwhere `y` is an array and `μ` is a positive parameter.\n\"\"\"\nstruct LogisticLoss{T <: AbstractArray, R <: Real} <: ProximableFunction\n    y::T\n    mu::R\n    function LogisticLoss{T, R}(y::T, mu::R) where {T, R}\n        if mu <= R(0)\n            error(\"parameter mu must be positive\")\n        end\n        new(y, mu)\n    end\nend\n\nLogisticLoss(y::T, mu::R=1) where {R, T <: AbstractArray} = LogisticLoss{T, R}(y, mu)\n\nis_separable(f::LogisticLoss) = true\nis_convex(f::LogisticLoss) = true\nis_smooth(f::LogisticLoss) = true\nis_prox_accurate(f::LogisticLoss) = false\n\n# f(x)  =  mu log(1 + exp(-y x))\n\nfunction (f::LogisticLoss)(x::AbstractArray{R}) where R\n    val = R(0)\n    for k in eachindex(x)\n        expyx = exp(f.y[k] * x[k])\n        val += log(R(1) + R(1) / expyx)\n    end\n    return f.mu * val\nend\n\n# f'(x) = -mu y exp(-y x) / (1 + exp(-y x))\n#       = -mu y / (1 + exp(y x))\n#\n# Lipschitz constant of gradient: (mu y)\n\nfunction gradient!(g::AbstractArray{R}, f::LogisticLoss, x::AbstractArray{R}) where R\n    val = R(0)\n    for k in eachindex(x)\n        expyx = exp(f.y[k] * x[k])\n        g[k] = -f.mu * f.y[k] / (R(1) + expyx)\n        val += log(R(1) + R(1) / expyx)\n    end\n    return f.mu * val\nend\n\n# Computing proximal operator:\n# z = prox(f, x, gamma)\n# <==> f'(z) + (z - x)/gamma = 0\n# <==> (z - x)/gamma - mu y / (1 + exp(y z)) = 0\n# <==> z - x - mu gamma y / (1 + exp(y z)) = 0\n#\n# Indicating the above condition as F(z) = 0, then\n# ==> F'(z) = 1 - (mu gamma y^2 exp(y z))/(1+exp(y z))^2\n#\n# Newton's method (no damping) to compute z reads:\n# z_{k+1} = z_k - F(z_k)/F'(z_k)\n#\n# To ensure convergence of Newton's method a damping is required.\n# The damping coefficient could be computed by backtracking.\n#\n# Alternatively we can use gradient methods with constant step size.\n\nfunction prox!(z::AbstractArray{R}, f::LogisticLoss, x::AbstractArray{R}, gamma::R=R(1)) where R\n    c = R(1) / gamma # convexity modulus\n    L = maximum(abs, f.mu .* f.y) + c # Lipschitz constants\n    z .= x\n    expyz = similar(z)\n    Fz = similar(z)\n    F1z = similar(z)\n    for k = 1:20\n        expyz .= exp.(f.y .* z)\n        Fz .= z .- x .- f.mu * gamma * (f.y ./ (1 .+ expyz))\n        z .-= Fz ./ L\n    end\n    expyz .= exp.(f.y .* z)\n    val = R(0)\n    for k in eachindex(expyz)\n        val += log(R(1) + R(1)/expyz[k])\n    end\n    return f.mu * val\nend\n", "meta": {"hexsha": "85695649062bb93f3f6fc471f93428e5d6888cf6", "size": 2512, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/logisticLoss.jl", "max_stars_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_stars_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2016-10-29T12:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:11:52.000Z", "max_issues_repo_path": "src/functions/logisticLoss.jl", "max_issues_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_issues_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2016-10-26T16:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T20:38:48.000Z", "max_forks_repo_path": "src/functions/logisticLoss.jl", "max_forks_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_forks_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T10:40:24.000Z", "avg_line_length": 26.1666666667, "max_line_length": 96, "alphanum_fraction": 0.5625, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7915192313048608}}
{"text": "mutable struct AffineMean{T<:Real,V<:AbstractVector{<:Real}} <: PriorMean{T}\n    w::V\n    b::T\n    nDim::Int\n    opt::Optimizer\nend\n\n\"\"\"\n**AffineMean**\n```julia\n    AffineMean(A::V,b::V;opt::Optimizer=Adam(α=0.01))\n    AffineMean(dims::Int,features::Int;opt::Optimizer=Adam(α=0.01))\n```\nConstruct an affine operation on `X` : `μ₀(X) = X*w + b` where `w` is a vector and `b` a scalar\nOptionally give an optimizer `opt` (`Adam(α=0.01)` by default)\n\"\"\"\nfunction AffineMean(w::V,b::T,;opt::Optimizer=Adam(α=0.01)) where {V<:AbstractVector{<:Real},T<:Real}\n    AffineMean{eltype(w),V}(w,b,length(w),opt)\nend\n\nfunction AffineMean(dims::Int;opt::Optimizer=Adam(α=0.01))\n    AffineMean{Float64,Vector{Float64}}(randn(dims),0.0,dims,opt)\nend\n\nfunction update!(μ::AffineMean{T},grad::AbstractVector{T},X::AbstractMatrix) where {T<:Real}\n    Δ = vcat(X'*grad,sum(grad))\n    Δ = update(μ.opt,Δ)\n    μ.w .+= Δ[1:μ.nDim]\n    μ.b += Δ[end]\nend\n\nfunction (μ::AffineMean{T})(x::AbstractMatrix) where {T<:Real}\n    @assert μ.nDim == size(x,2) \"Number of dimensions do not match\"\n    return x*μ.w .+ μ.b\nend\n", "meta": {"hexsha": "aafc191f889124407cd6a1af21e36af327d4b2ba", "size": 1089, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/prior/affinemean.jl", "max_stars_repo_name": "UnofficialJuliaMirror/AugmentedGaussianProcesses.jl-38eea1fd-7d7d-5162-9d08-f89d0f2e271e", "max_stars_repo_head_hexsha": "ad94aa679c3b70f675c91982cdd057eb846c3992", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/prior/affinemean.jl", "max_issues_repo_name": "UnofficialJuliaMirror/AugmentedGaussianProcesses.jl-38eea1fd-7d7d-5162-9d08-f89d0f2e271e", "max_issues_repo_head_hexsha": "ad94aa679c3b70f675c91982cdd057eb846c3992", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/prior/affinemean.jl", "max_forks_repo_name": "UnofficialJuliaMirror/AugmentedGaussianProcesses.jl-38eea1fd-7d7d-5162-9d08-f89d0f2e271e", "max_forks_repo_head_hexsha": "ad94aa679c3b70f675c91982cdd057eb846c3992", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.25, "max_line_length": 101, "alphanum_fraction": 0.6492194674, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7915192223390971}}
{"text": "using AdFem\nusing PyPlot\n\nfunction g_func(x, y)\n    -2*x*(1-x) - 2*y*(1-y) + 2*(1-2x)*y*(1-y) + 3*(1-2y)*x*(1-x)\nend\n\nm = 30\nn = 30\nh = 1/n\n\nxy = fem_nodes(m, n, h)\nx, y = xy[:,1], xy[:,2]\nu = @. (x*(1-x)*y*(1-y))\n\nA = constant(compute_fem_laplace_matrix1(m, n, h))\nu0 = 2ones(2(m+1)*(n+1))\nv0 = 3ones(2(m+1)*(n+1))\nu0 = fem_to_gauss_points(u0, m, n, h)\nv0 = fem_to_gauss_points(v0, m, n, h)\nB = compute_fem_advection_matrix1(constant(u0), constant(v0), m, n, h)\nL = -A+B\ng = eval_f_on_gauss_pts(g_func, m, n, h)\nrhs = compute_fem_source_term1(g, m, n, h)\nbd = bcnode(\"all\", m, n, h)\nL, _ = fem_impose_Dirichlet_boundary_condition1(L, bd, m, n, h)\nrhs[bd] .= 0.0\nsol = L\\rhs\n\nsess = Session(); init(sess)\nS = run(sess, sol)\nfigure(figsize=(10,4))\nsubplot(121)\nvisualize_scalar_on_fem_points(S, m, n, h)\ntitle(\"computed solution\")\nsubplot(122)\nvisualize_scalar_on_fem_points(u, m, n, h)\ntitle(\"exact solution\")\n\n# subplot(133)\n# visualize_scalar_on_fem_points(S-u, m, n, h)\n# title(\"difference between computed and exact\")\n", "meta": {"hexsha": "a4df8d04af75805cd162a1cc691de1067b652fe7", "size": 1022, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/codes/SteadyNavierStokes/steady_state_advection_diffusion_equation.jl", "max_stars_repo_name": "kailaix/AdFem.jl", "max_stars_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2020-10-18T01:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:13:24.000Z", "max_issues_repo_path": "docs/src/codes/SteadyNavierStokes/steady_state_advection_diffusion_equation.jl", "max_issues_repo_name": "kailaix/AdFem.jl", "max_issues_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-10-19T03:51:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:38:46.000Z", "max_forks_repo_path": "docs/src/codes/SteadyNavierStokes/steady_state_advection_diffusion_equation.jl", "max_forks_repo_name": "kailaix/AdFem.jl", "max_forks_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-11-05T11:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T19:30:09.000Z", "avg_line_length": 23.7674418605, "max_line_length": 70, "alphanum_fraction": 0.6487279843, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976794, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7914993691352141}}
{"text": "# X.F. Yang's Double Cosine kernel (2013)\nfunction doublecosine(r, h)\n    # Kernel constant\n    k = 2\n    if abs(r) < 2h\n        # Normalizing factor\n        σ = 1/(6k * h)\n\n        # Checking sign\n        sign = r == 0 ? 1 : r/abs(r)\n\n        # Kernel computation\n        W = (4cos(π/(2h) * r) + cos(π/h * r) + 3) * σ\n\n        # Derivatives computation\n        ∂x_W = (4π/(2h) * sin(π/(2h) * r) + π/h * sin(π/h * r)) * -sign * σ\n\n        return (W,∂x_W)\n    else\n        return (0,0)\n    end\n    res\nend\n\n# J.J. Monaghan's Cubic Spline kernel (1992)\nfunction cubicspline(r, h)\n    if abs(r) < 2h\n        # Reduced radius\n        q = r/h\n\n        # Normalizing factor\n        σ = 2/(3h)\n\n        # Checking sign\n        sign = r == 0 ? 1 : r/abs(r)\n\n        if abs(r) < h\n            # Kernel computation\n            W = (1 - 1.5q^2 + 0.75q^3) * σ\n\n            # Derivatives computation\n            ∂x_W = (2q - 1.5q^2) * sign/h^2\n\n        else #if h <abs(r) < 2h\n            # Kernel computation\n            W = (2-q)^3/4 * σ\n\n            # Derivatives computation\n            ∂x_W = (q-2)^2/2 * sign/h^2\n        end\n        return (W,∂x_W)\n    else\n        return (0,0)\n    end\n    res\nend\n", "meta": {"hexsha": "d277f3f674c41bf1470b251390119a25c3319692", "size": 1192, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels.jl", "max_stars_repo_name": "pierremtb/SPHShockTube1D.jl", "max_stars_repo_head_hexsha": "4528603b419fe4d91a643080f65958a254c007ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-10T22:26:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T22:26:17.000Z", "max_issues_repo_path": "src/kernels.jl", "max_issues_repo_name": "pierremtb/SPHShockTube1D.jl", "max_issues_repo_head_hexsha": "4528603b419fe4d91a643080f65958a254c007ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels.jl", "max_forks_repo_name": "pierremtb/SPHShockTube1D.jl", "max_forks_repo_head_hexsha": "4528603b419fe4d91a643080f65958a254c007ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-10T22:26:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T22:26:11.000Z", "avg_line_length": 20.9122807018, "max_line_length": 75, "alphanum_fraction": 0.4488255034, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7914993673742423}}
{"text": "using LinearAlgebra\n\n\"\"\"\n    normal_hessenberg_matrix(Float64, vals::AbstractVector)\n\nGenerate a normal hessenberg matrix with eigenvalues `vals`\n\"\"\"\nfunction normal_hessenberg_matrix(T::Type{<:Number}, vals::AbstractVector)\n    n = length(vals)\n    Q, R = qr(randn(T, n, n))\n    A = Q * Diagonal(vals) * Q'\n    return triu(hessenberg!(A).factors, -1)\nend\n\nfunction normal_hessenberg_matrix(T::Type{<:Real}, vals::AbstractVector{<:Complex})\n    n = length(vals)\n    Q, R = qr(randn(T, n, n))\n    D = zeros(T, n, n)\n    i = 1\n    while i ≤ n\n        if imag(vals[i]) != 0\n            D[i+0,i+0] = real(vals[i])\n            D[i+1,i+0] = imag(vals[i])\n            D[i+0,i+1] = -imag(vals[i])\n            D[i+1,i+1] = real(vals[i])\n            i += 2\n        else\n            D[i] = real(vals[i])\n            i += 1\n        end\n    end\n    return triu(hessenberg!(Q * D * Q').factors, -1)\nend\n\n\"\"\"\n    realimag(1 + 3im) → (1, 3)\n\nSplit imaginary number into a tuple of real and imaginary part\n\"\"\"\nrealimag(x) = (real(x), imag(x))\n\n\"\"\"\n    is_hessenberg(H) → bool\n\nTest whether the sub-subdiagonals of H are zero.\n\"\"\"\nis_hessenberg(H) = norm(tril(H, -2)) == 0", "meta": {"hexsha": "a9a24a394b587b0fb0f076b6bdce1c37910e5cac", "size": 1154, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/utils.jl", "max_stars_repo_name": "andreasnoack/ArnoldiMethod.jl", "max_stars_repo_head_hexsha": "d44bac4022e5e39f9fa80f6398091c41180ec5a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2018-08-28T14:04:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T02:18:47.000Z", "max_issues_repo_path": "test/utils.jl", "max_issues_repo_name": "andreasnoack/ArnoldiMethod.jl", "max_issues_repo_head_hexsha": "d44bac4022e5e39f9fa80f6398091c41180ec5a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2018-05-21T12:53:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-27T08:58:38.000Z", "max_forks_repo_path": "test/utils.jl", "max_forks_repo_name": "andreasnoack/ArnoldiMethod.jl", "max_forks_repo_head_hexsha": "d44bac4022e5e39f9fa80f6398091c41180ec5a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2018-09-10T19:35:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T11:48:46.000Z", "avg_line_length": 24.5531914894, "max_line_length": 83, "alphanum_fraction": 0.5623916811, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7914549053044868}}
{"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\n\n\"This routine solves the heat equation using Forward Euler in time and finite differences\nin space. Note that this is unstable unless dt ~ O(h^2).\"\n\nm = 100 # number of points\nT = .01\ndt = .0005\n\nu0(x) = 0.0 # initial condition\nf(x) = 5*(Float64((x > -.5) && (x <= 0.0)) - Float64((x < .5) && (x >= 0.0)))\nf(x,t) = f(x)*exp(-t)\nα(t) = 1.0\nβ(t) = pi\n\n# define spatial grid\nx = LinRange(-1,1,m+2)\nxint = x[2:end-1]\nh = x[2]-x[1]\nA = (1/h^2) * spdiagm(0=>2*ones(m),-1=>-ones(m-1),1=>-ones(m-1))\n\nfunction F(t)\n    b = f.(xint,t) # look for f(x,t)\n    b[1] += α(t)/h^2\n    b[end] += β(t)/h^2\n    return b\nend\n\nu = u0.(xint)\nNsteps = ceil(Int,T/dt)\ndt = T / Nsteps\n\ninterval = 1\n@gif for k = 1:Nsteps\n    tk = k*dt\n    u .= u + dt * (F(tk) - A*u)\n    if k % interval==0\n        plot(xint,u,linewidth=2,label=\"Solution\",ylims=(-1.0,3.0))\n        println(\"on timestep $k out of $Nsteps.\")\n    end\nend every interval\n", "meta": {"hexsha": "e7acb7ed73882f41aa82e78fa1162dd241f0ecbb", "size": 961, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week3/fd_heat_forward_euler.jl", "max_stars_repo_name": "jlchan/caam452_s21", "max_stars_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:38:43.000Z", "max_issues_repo_path": "week3/fd_heat_forward_euler.jl", "max_issues_repo_name": "jlchan/caam452_s21", "max_issues_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week3/fd_heat_forward_euler.jl", "max_forks_repo_name": "jlchan/caam452_s21", "max_forks_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8409090909, "max_line_length": 89, "alphanum_fraction": 0.5723204995, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067147399244, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7914548993460581}}
{"text": "@doc raw\"\"\"\n    GammaRationalKernel([α [,β [,γ]]])\n  \nThe gamma-rational kernel is a generalization of the rational-quadratic kernel with an \nadditional shape parameter:\n\n```math\n\\kappa(\\mathbf{x},\\mathbf{y})\n= \\left(1 +\\alpha ||\\mathbf{x},\\mathbf{y}||^{\\gamma}\\right)^{-\\beta} \n\\qquad \\alpha > 0, \\; \\beta > 0, \\; 0 < \\gamma \\leq 1\n```\n\nwhere ``\\alpha`` is a scaling parameter and ``\\beta`` and ``\\gamma`` are shape parameters.\n\"\"\"\nstruct GammaRationalKernel{T<:AbstractFloat} <: MercerKernel{T}\n    alpha::HyperParameter{T}\n    beta::HyperParameter{T}\n    gamma::HyperParameter{T}\n    GammaRationalKernel{T}(α::Real, β::Real, γ::Real) where {T<:AbstractFloat} = new{T}(\n        HyperParameter(convert(T,α), interval(OpenBound(zero(T)), nothing)),\n        HyperParameter(convert(T,β), interval(OpenBound(zero(T)), nothing)),\n        HyperParameter(convert(T,γ), interval(OpenBound(zero(T)), ClosedBound(one(T))))\n    )\nend\nfunction GammaRationalKernel(\n        α::T1 = 1.0,\n        β::T2 = one(T1),\n        γ::T3 = one(floattype(T1,T2))\n    ) where {T1<:Real,T2<:Real,T3<:Real}\n    GammaRationalKernel{floattype(T1,T2,T3)}(α,β,γ)\nend\n\n@inline gammarationalkernel(z::T, α::T, β::T, γ::T) where {T<:AbstractFloat} = (1 + α*(z^γ))^(-β)\n\n@inline basefunction(::GammaRationalKernel) = SquaredEuclidean()\n@inline function kappa(κ::GammaRationalKernel{T}, z::T) where {T}\n    gammarationalkernel(z, getvalue(κ.alpha), getvalue(κ.beta), getvalue(κ.gamma))\nend", "meta": {"hexsha": "1615076394e5ec54a1a89c54fdc8740519be784a", "size": 1452, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernelfunctions/mercer/gammarational.jl", "max_stars_repo_name": "holtri/MLKernels.jl", "max_stars_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernelfunctions/mercer/gammarational.jl", "max_issues_repo_name": "holtri/MLKernels.jl", "max_issues_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernelfunctions/mercer/gammarational.jl", "max_forks_repo_name": "holtri/MLKernels.jl", "max_forks_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2105263158, "max_line_length": 97, "alphanum_fraction": 0.6570247934, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7914548988120503}}
{"text": "#' ---\n#' title: Experiment Design\n#' ---\n\n#' **Originally Contributed by**: Arpit Bhatia, Chris Coey \n\n#' This tutorial covers experiment design examples (D-optimal, A-optimal, and E-optimal) \n#' from section 7.5 of the book Convex Optimization by Boyd and Vandenberghe[[1]](#c1)\n\n#' ## Relaxed Experiment Design Problem\n\n#' The basic experiment design problem is as follows. \n#' Given the menu of possible choices for experiments, $v_{1}, \\ldots, v_{p}$, \n#' and the total number $m$ of experiments to be carried out, choose the numbers of each type of experiment, \n#' $i . e ., m_{1}, \\ldots, m_{p}$ to make the error covariance $E$ small (in some sense). \n#' The variables $m_{1}, \\ldots, m_{p}$ must, of course, be integers and sum to $m,$ the given total number of experiments. \n#' This leads to the optimization problem\n\n#' $$\n#' \\begin{array}{cl}{\\operatorname{minimize}\\left(\\mathrm{w.r.t.} \\mathbf{S}_{+}^{n}\\right)} & {E=\\left(\\sum_{j=1}^{p} m_{j} v_{j} v_{j}^{T}\\right)^{-1}} \\\\ {\\text { subject to }} & {m_{i} \\geq 0, \\quad m_{1}+\\cdots+m_{p}=m} \\\\ {} & {m_{i} \\in \\mathbf{Z}}\\end{array}\n#' $$\n\n#' The basic experiment design problem can be a hard combinatorial problem when $m,$ the total number of experiments, \n#' is comparable to $n$ , since in this case the $m_{i}$ are all small integers. \n#' In the case when $m$ is large compared to $n$ , however, a good approximate solution can be found by ignoring, \n#' or relaxing, the constraint that the $m_{i}$ are integers. \n#' Let $\\lambda_{i}=m_{i} / m,$ which is the fraction of the total number of experiments for which \n#' $a_{j}=v_{i},$ or the relative frequency of experiment $i$. \n#' We can express the error covariance in terms of $\\lambda_{i}$ as\n\n#' $$\n#' E=\\frac{1}{m}\\left(\\sum_{i=1}^{p} \\lambda_{i} v_{i} v_{i}^{T}\\right)^{-1}\n#' $$\n\n#' The vector $\\lambda \\in \\mathbf{R}^{p}$ satisfies $\\lambda \\succeq 0, \n#' \\mathbf{1}^{T} \\lambda=1,$ and also, each $\\lambda_{i}$ is an integer multiple of $1 / m$. \n#' By ignoring this last constraint, we arrive at the problem\n\n#' $$\n#' \\begin{array}{ll}{\\operatorname{minimize}\\left(\\mathrm{w.r.t.} \\mathbf{S}_{+}^{n}\\right)} & {E=(1 / m)\\left(\\sum_{i=1}^{p} \\lambda_{i} v_{i} v_{i}^{T}\\right)^{-1}} \\\\ {\\text { subject to }} & {\\lambda \\succeq 0, \\quad \\mathbf{1}^{T} \\lambda=1}\\end{array}\n#' $$\n\n#' ## Types of Experiment Design Problems\n\n#' Several scalarizations have been proposed for the experiment design problem, \n#' which is a vector optimization problem over the positive semidefinite cone.\n\nusing JuMP\nusing SCS\nusing LinearAlgebra\n\nq = 4 # dimension of estimate space\np = 8 # number of experimental vectors\nnmax = 3 # upper bound on lambda\nn = 12 \n\nV = randn(q, p)\n\neye = Matrix{Float64}(I, q, q);\n\n#' ### A-optimal design\n\n#' In A-optimal experiment design, we minimize tr $E$, the trace of the covariance matrix. \n#' This objective is simply the mean of the norm of the error squared:\n\n#' $$\n#' \\mathbf{E}\\|e\\|_{2}^{2}=\\mathbf{E} \\operatorname{tr}\\left(e e^{T}\\right)=\\operatorname{tr} E\n#' $$\n\n#' The A-optimal experiment design problem in SDP form is\n\n#' $$\n#' \\begin{array}{ll}{\\operatorname{minimize}} & {\\mathbf{1}^{T} u} \\\\ {\\text { subject to }} & {\\left[\\begin{array}{cc}{\\sum_{i=1}^{p} \\lambda_{i} v_{i} v_{i}^{T}} & {e_{k}} \\\\ {e_{k}^{T}} & {u_{k}}\\end{array}\\right] \\succeq 0, \\quad k=1, \\ldots, n} \\\\ {} & {\\lambda \\succeq 0, \\quad \\mathbf{1}^{T} \\lambda=1}\\end{array}\n#' $$\n\naOpt = Model(with_optimizer(SCS.Optimizer, verbose = 0))\n@variable(aOpt, np[1:p], lower_bound = 0, upper_bound = nmax)\n@variable(aOpt, u[1:q], lower_bound = 0)\n\n@constraint(aOpt, sum(np) <= n)\nfor i = 1:q\n    @SDconstraint(aOpt, [V * diagm(0 => np ./ n) * V' eye[:, i]; eye[i, :]' u[i]] >= 0)\nend\n\n@objective(aOpt, Min, sum(u))\n\noptimize!(aOpt)\n\n@show objective_value(aOpt);\n@show value.(np);\n\n#' ### E-optimal design\n\n#' In $E$ -optimal design, we minimize the norm of the error covariance matrix, i.e. the maximum eigenvalue of $E$. \n#' Since the diameter (twice the longest semi-axis) of the confidence ellipsoid $\\mathcal{E}$ \n#' is proportional to $\\|E\\|_{2}^{1 / 2}$, \n#' minimizing $\\|E\\|_{2}$ can be interpreted geometrically as minimizing the diameter of the confidence ellipsoid. \n#' E-optimal design can also be interpreted as minimizing the maximum variance of $q^{T} e$,\n#' over all $q$ with $\\|q\\|_{2}=1$. \n#' The E-optimal experiment design problem in SDP form is\n\n#' $$\n#' \\begin{array}{cl}{\\operatorname{maximize}} & {t} \\\\ {\\text { subject to }} & {\\sum_{i=1}^{p} \\lambda_{i} v_{i} v_{i}^{T} \\succeq t I} \\\\ {} & {\\lambda \\succeq 0, \\quad \\mathbf{1}^{T} \\lambda=1}\\end{array}\n#' $$\n\neOpt = Model(with_optimizer(SCS.Optimizer, verbose = 0))\n@variable(eOpt, np[1:p], lower_bound = 0, upper_bound = nmax)\n@variable(eOpt, t)\n\n@SDconstraint(eOpt, V * diagm(0 => np ./ n) * V' - (t .* eye) >= 0)\n@constraint(eOpt, sum(np) <= n)\n\n@objective(eOpt, Max, t)\n\noptimize!(eOpt)\n\n@show objective_value(eOpt);\n@show value.(np);\n\n#' ### D-optimal design\n#' The most widely used scalarization is called $D$ -optimal design, \n#' in which we minimize the determinant of the error covariance matrix $E$. \n#' This corresponds to designing the experiment to minimize the volume of the resulting confidence ellipsoid \n#' (for a fixed confidence level). \n#' Ignoring the constant factor 1$/ m$ in $E$, and taking the logarithm of the objective, \n#' we can pose this problem as convex optimization problem\n\n#' $$\n#' \\begin{array}{ll}{\\operatorname{minimize}} & {\\log \\operatorname{det}\\left(\\sum_{i=1}^{p} \\lambda_{i} v_{i} v_{i}^{T}\\right)^{-1}} \\\\ {\\text { subject to }} & {\\lambda \\succeq 0, \\quad \\mathbf{1}^{T} \\lambda=1}\\end{array}\n#' $$\n\ndOpt = Model(with_optimizer(SCS.Optimizer, verbose = 0))\n@variable(dOpt, np[1:p], lower_bound = 0, upper_bound = nmax)\n@variable(dOpt, t)\n@objective(dOpt, Max, t)\n@constraint(dOpt, sum(np) <= n)\nE = V * diagm(0 => np ./ n) * V'\n@constraint(dOpt, [t, 1, (E[i, j] for i in 1:q for j in 1:i)...] in MOI.LogDetConeTriangle(q))\n\noptimize!(dOpt)\n\n@show objective_value(dOpt);\n@show value.(np);\n\n#' ### References\n#' <a id='c1'></a>\n#' 1. Boyd, S., & Vandenberghe, L. (2004). Convex Optimization. Cambridge: Cambridge University Press. doi:10.1017/CBO9780511804441", "meta": {"hexsha": "bd2b23b7b189cc7dab4ed6960292501a51c87d7a", "size": 6212, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/modelling/experiment_design.jl", "max_stars_repo_name": "carlosal1015/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/modelling/experiment_design.jl", "max_issues_repo_name": "carlosal1015/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/modelling/experiment_design.jl", "max_forks_repo_name": "carlosal1015/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2585034014, "max_line_length": 320, "alphanum_fraction": 0.6522858983, "num_tokens": 2051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.8774767762675405, "lm_q1q2_score": 0.7914144384369883}}
{"text": "# Helper function for lesson 8 lecture notes.\nusing Distributions\n\nfunction genDataset(N::Int64)\n    # Generate dataset {(x1,y1),...,(xN,yN)}\n    # x is a 2d feature vector [x1;x2]\n    # y ∈ {false,true} is a binary class label\n    # p(x|y) is multi-modal (mixture of uniform and Gaussian distributions)\n#     srand(123)\n    X = Matrix{Float64}(undef,2,N); y = Vector{Bool}(undef,N)\n    for n=1:N\n        if (y[n]=(rand()>0.6)) # p(y=true) = 0.6\n            # Sample class 1 conditional distribution\n            if rand()<0.5\n                X[:,n] = [6.0; 0.5] .* rand(2) .+ [3.0; 6.0]\n            else\n                X[:,n] = sqrt(0.5) * randn(2) .+ [5.5, 0.0]\n            end\n        else\n            # Sample class 2 conditional distribution\n            X[:,n] = randn(2) .+ [1., 4.]\n        end\n    end\n\n    return (X, y)\nend\n\nfunction buildGenerativeDiscriminationBoundary(X::Matrix, y::Vector{Bool})\n    # Generate discrimination boundary function x[2] = boundary(x[1]) for a Gaussian generative model:\n    # X = [x_1,...,x_N]\n    # y = [y_1;...;y_N]\n    # x is a 2-d real (feature) vector\n    # y ∈ {false,true}\n    # x|y ~ 𝓝(x|μ_y, Σ_y)\n    # We find the class-conditional Gaussian distributions by MLE\n    # See lesson 7 (generative classification) for more details\n    (size(X,1)==2) || error(\"The columns of X should have length 2\")\n\n    # MLE of p(y)\n    p_1_est = sum(y.==true) / length(y)\n    π_hat = [p_1_est; 1 .- p_1_est]\n\n    # MLE of class-conditional multivariate Gaussian densities\n    X_cls1 = X[:,y.==true]\n    X_cls2 = X[:,y.==false]\n    d1 = fit_mle(FullNormal, X_cls1)  # MLE density estimation d1 = N(μ₁, Σ₁)\n    d2 = fit_mle(FullNormal, X_cls2)  # MLE density estimation d2 = N(μ₂, Σ₂)\n    Σ = π_hat[1] * cov(d1) + π_hat[2] * cov(d2) # Combine Σ₁ and Σ₂ into Σ\n\n    conditionals = [MvNormal(mean(d1), Σ); MvNormal(mean(d2), Σ)] # p(x|C)\n\n    # Discrimination boundary of the posterior (p(apple|x;D) = p(peach|x;D) = 0.5)\n    β(k) = inv(Σ)* mean(conditionals[k])\n    γ(k) = -0.5 * mean(conditionals[k])' * inv(Σ) * mean(conditionals[k]) + log(π_hat[k])\n    function discriminant_x2(x1)\n        # Solve discriminant equation for x2\n        \n        β12 = β(1) .- β(2)\n        γ12 = (γ(1) .- γ(2))[1,1]\n        return -1 ./ β12[2]*(β12[1]*x1 .+ γ12) \n    end\n\n    return discriminant_x2\nend", "meta": {"hexsha": "473e058fb2abbf3121d7729103a30f64485fc9cf", "size": 2317, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lessons/notebooks/scripts/lesson8_helpers.jl", "max_stars_repo_name": "Yikeru/BMLIP", "max_stars_repo_head_hexsha": "296f5330210d387809b2c3ce7a6847f2bd69b24c", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-09-14T17:34:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T18:29:11.000Z", "max_issues_repo_path": "lessons/notebooks/scripts/lesson8_helpers.jl", "max_issues_repo_name": "Yikeru/BMLIP", "max_issues_repo_head_hexsha": "296f5330210d387809b2c3ce7a6847f2bd69b24c", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2015-08-18T11:30:12.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-03T15:17:33.000Z", "max_forks_repo_path": "lessons/notebooks/scripts/lesson8_helpers.jl", "max_forks_repo_name": "Yikeru/BMLIP", "max_forks_repo_head_hexsha": "296f5330210d387809b2c3ce7a6847f2bd69b24c", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-03-18T14:05:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T14:35:32.000Z", "avg_line_length": 36.203125, "max_line_length": 102, "alphanum_fraction": 0.5722917566, "num_tokens": 819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025231, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7913828452019799}}
{"text": "using OrdinaryDiffEq, ParameterizedFunctions, DiffEqBase, RecursiveArrayTools\n\n# Here are the problems to solve\n\nf1 = @ode_def LotkaVolterraTest begin\n  dx = a*x - x*y\n  dy = -3y + x*y\nend a\nu0 = [1.0;1.0]\ntspan = (0.0,10.0)\np = [1.5]\nprob1 = ODEProblem(f1,u0,tspan,[1.5])\n\nf2 = @ode_def LotkaVolterraMulti begin\n  dx = a*x - x*y\n  dy = -c*y + x*y\nend a c\np = [1.5,3.0]\nprob2 = ODEProblem(f2,u0,tspan,p)\n\nf3 = @ode_def LotkaVolterraAll begin\n  dx = a*x - b*x*y\n  dy = -c*y + d*x*y\nend a b c d\np = [1.5,1.0,3.0,1.0]\nprob3 = ODEProblem(f3,u0,tspan,p)\n\n# Generate random data based off of the known solution\nsol = solve(prob1,Tsit5())\nt = collect(range(0, stop=10, length=200))\nrandomized = VectorOfArray([(sol(t[i]) + .01randn(2)) for i in 1:length(t)])\ndata = convert(Array,randomized)\n", "meta": {"hexsha": "28b6f9b894d8ecfca354112b25bff6e686ff0783", "size": 785, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tests_on_odes/test_problems.jl", "max_stars_repo_name": "Vaibhavdixit02/DiffEqParamEstim.jl", "max_stars_repo_head_hexsha": "d68ac5e139eb1005064d1b5f404870c008889d03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/tests_on_odes/test_problems.jl", "max_issues_repo_name": "Vaibhavdixit02/DiffEqParamEstim.jl", "max_issues_repo_head_hexsha": "d68ac5e139eb1005064d1b5f404870c008889d03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-28T23:47:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-28T23:47:15.000Z", "max_forks_repo_path": "test/tests_on_odes/test_problems.jl", "max_forks_repo_name": "Vaibhavdixit02/DiffEqParamEstim.jl", "max_forks_repo_head_hexsha": "d68ac5e139eb1005064d1b5f404870c008889d03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7878787879, "max_line_length": 77, "alphanum_fraction": 0.6598726115, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693617046216, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7913828424193019}}
{"text": "# exercise estimating a linear model by iterative minimization,\n# and verifying that OLS gives same results.\n# If the data is missing, run BasicDataAnalysis.jl\n# in the Examples/Julia directory\n\nusing CSV, DataFrames, StatsModels, Econometrics\n# prepare the data\ncard = CSV.read(\"../Julia/cooked.csv\", DataFrame)\ndisplay(card)\n\ny = card[:,1]\nx = Matrix{Float64}([ones(size(card,1)) card[:,2:7]])\n\n# define the objective function and start value\nobj = theta -> (y-x*theta)'*(y-x*theta)\nstartval = zeros(size(x,2))\n# do the minimization\nthetahat, objvalue = fminunc(obj, startval) \nprintln(\"the OLS estimates by numeric min: obj. value: \", round(objvalue,digits=5))\nprettyprint(thetahat)\n\n# verify by using OLS, which uses the analytic solution\nprintln(\"verifying by OLS:\")\nols( @formula(lnwage ~ 1 + educ + exper + expsq + black + south + smsa), card)\nnothing\n", "meta": {"hexsha": "c51eba78edbc99c7f18d8132004ed8c0d2b54d46", "size": 859, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/NonlinearOptimization/EstimateCard.jl", "max_stars_repo_name": "Hiroakiyusheng/Econometrics", "max_stars_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "Examples/NonlinearOptimization/EstimateCard.jl", "max_issues_repo_name": "Hiroakiyusheng/Econometrics", "max_issues_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "Examples/NonlinearOptimization/EstimateCard.jl", "max_forks_repo_name": "Hiroakiyusheng/Econometrics", "max_forks_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 33.0384615385, "max_line_length": 83, "alphanum_fraction": 0.7299185099, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474246069457, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7913442944865005}}
{"text": "function parametrized_strogatz(du,u,p,t)\n    #NumberOfOscillators,CouplingConstant, and NaturalFreqs\n    N,K,w = p\n    ##Centroid\n    du[1] = 0\n    for i in 1:N\n        du[1] += du[i+1]\n    end\n    du[1] = du[1]/N\n    #Oscillators\n    for i in 1:N\n        du[i+1] = (1.0-abs2(u[i+1])+w[i]*im)*u[i+1] + K*(u[1]-u[i+1])\n    end\nend\n\nfunction getparameters_strogatz(N,K,γ,distribution)\n    distribution == \"Uniform\" ? nothing : error(\"$(distribution) is not yet supported\")\n    j = collect(1:N)\n    w = broadcast(j->((2j-N-1)/(N-1))*((pi*γ)/2),j)\n    p = (N=N, K=K, w=w)\n    return p\nend\n\nfunction getstartpoints_strogatz(N)\n    u0 = ComplexF64[]\n    d = Uniform(-1,1)\n    for i in 1:N\n        push!(u0,rand(d)+rand(d)im)\n    end\n    pushfirst!(u0,mean(u0))\n    return u0\nend\n\nfunction strogatz(N,K,T,fs,γ,distribution)\n    tspan = (0.0,T)\n    u0 = getstartpoints_strogatz(N)\n    p = getparameters_strogatz(N,K,γ,distribution)\n    prob = ODEProblem(parametrized_strogatz,u0,tspan,p)\n    sol = solve(prob,RK4(),saveat=collect(0:1/fs:T),progress=true)\nend\n\n", "meta": {"hexsha": "30e164222743d71b0ee49276a16fe53c5cc3ead6", "size": 1052, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/strogatz.jl", "max_stars_repo_name": "VMHidalgo/CoupledOscillators.jl", "max_stars_repo_head_hexsha": "267a51f4880c3bdf09f370b1716b78a94cca361d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/strogatz.jl", "max_issues_repo_name": "VMHidalgo/CoupledOscillators.jl", "max_issues_repo_head_hexsha": "267a51f4880c3bdf09f370b1716b78a94cca361d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/strogatz.jl", "max_forks_repo_name": "VMHidalgo/CoupledOscillators.jl", "max_forks_repo_head_hexsha": "267a51f4880c3bdf09f370b1716b78a94cca361d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0476190476, "max_line_length": 87, "alphanum_fraction": 0.6064638783, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992969868542, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7913297585911103}}
{"text": "# It is possible to show that the square root of two can be expressed as an\n# infinite continued fraction.\n#\n# √2=1+1/(2+1/(2+1/(2+...)))\n#\n# By expanding this for the first four iterations, we get:\n# \n# 1+1/2 = 3/2 = 1.5\n# 1+1/(2+1/2) = 7/5 = 1.4\n# 1+1/(2+1/(2+1/2)) = 17/12 =1.41666...\n# 1+1/(2+1/(2+1/(2+1/2))) = 41/29 = 1.41379...\n# \n# The next three expansions are 99/70, 239/169, and 577/408, but the eighth\n# expansion, 1393/985, is the first example where the number of digits in the\n# numerator exceeds the number of digits in the denominator.\n#\n# In the first one-thousand expansions, how many fractions contain a numerator\n# with more digits than the denominator?\n\nusing ProjectEulerSolutions\n\n# Using Julia's built-in rational numbers only works up to n=47 or so, when we\n# begin to run into over-runs.  Really this is a pattern matching game.  The \n# numerator for iteration i (n_i) and the denominator for iteration i (d_i)\n# follow a pattern: d_i = n_{i-1} + d_{i-1}, n_i = d_i + d_{i-1}\nfunction p057solution(n_max::Integer=100)::Integer\n    \n    num = BigInt(3)\n    denom = BigInt(2)\n    count = 0\n    for n in 2:n_max\n        denom, num = num + denom, num + 2*denom\n        if ndigits(num) > ndigits(denom)\n            count += 1\n        end\n    end\n    return count\nend\n\n\np057 = Problems.Problem(p057solution)\n\nProblems.benchmark(p057, 1_000)\n", "meta": {"hexsha": "4ccf36ddd7b5ea1916ff026a00cd85c782183817", "size": 1362, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/057.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/057.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/057.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9545454545, "max_line_length": 78, "alphanum_fraction": 0.6593245228, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7913058338680115}}
{"text": "\nusing JuMP, Ipopt\n\n# Create JuMP model, using Ipopt as the solver\nrocket = Model(optimizer_with_attributes(Ipopt.Optimizer, \"print_level\" => 0))\n\n# Constants\n# Note that all parameters in the model have been normalized\n# to be dimensionless. See the COPS3 paper for more info.\nh_0 = 1    # Initial height\nv_0 = 0    # Initial velocity\nm_0 = 1    # Initial mass\ng_0 = 1    # Gravity at the surface\n\nT_c = 3.5  # Used for thrust\nh_c = 500  # Used for drag\nv_c = 620  # Used for drag\nm_c = 0.6  # Fraction of initial mass left at end\n\nc     = 0.5 * sqrt(g_0 * h_0)  # Thrust-to-fuel mass\nm_f   = m_c * m_0            # Final mass\nD_c   = 0.5 * v_c * m_0 / g_0    # Drag scaling\nT_max = T_c * g_0 * m_0        # Maximum thrust\n\nn = 800   # Time steps\n\n@variables(rocket, begin\n    Δt ≥ 0, (start = 1/n) # Time step\n    # State variables\n    v[1:n] ≥ 0            # Velocity\n    h[1:n] ≥ h_0          # Height\n    m_f ≤ m[1:n] ≤ m_0    # Mass\n    # Control\n    0 ≤ T[1:n] ≤ T_max    # Thrust\nend)\n\n# Objective: maximize altitude at end of time of flight\n@objective(rocket, Max, h[n])\n\n# Initial conditions\n@constraints(rocket, begin\n    v[1] == v_0\n    h[1] == h_0\n    m[1] == m_0\n    m[n] == m_f\nend)\n\n# Forces\n# Drag(h,v) = Dc v^2 exp( -hc * (h - h0) / h0 )\n@NLexpression(rocket, drag[j = 1:n], D_c * (v[j]^2) * exp(-h_c * (h[j] - h_0) / h_0))\n# Grav(h)   = go * (h0 / h)^2\n@NLexpression(rocket, grav[j = 1:n], g_0 * (h_0 / h[j])^2)\n# Time of flight\n@NLexpression(rocket, t_f, Δt * n)\n\n# Dynamics\nfor j in 2:n\n    # h' = v\n    \n    # Rectangular integration\n    # @NLconstraint(rocket, h[j] == h[j - 1] + Δt * v[j - 1])\n    \n    # Trapezoidal integration\n    @NLconstraint(rocket,\n        h[j] == h[j - 1] + 0.5 * Δt * (v[j] + v[j - 1]))\n\n    # v' = (T-D(h,v))/m - g(h)\n    \n    # Rectangular integration\n    # @NLconstraint(rocket, v[j] == v[j - 1] + Δt *(\n    #                 (T[j - 1] - drag[j - 1]) / m[j - 1] - grav[j - 1]))\n    \n    # Trapezoidal integration\n    @NLconstraint(rocket,\n        v[j] == v[j-1] + 0.5 * Δt * (\n            (T[j] - drag[j] - m[j] * grav[j]) / m[j] +\n            (T[j - 1] - drag[j - 1] - m[j - 1] * grav[j - 1]) / m[j - 1]))\n\n    # m' = -T/c\n\n    # Rectangular integration\n    # @NLconstraint(rocket, m[j] == m[j - 1] - Δt * T[j - 1] / c)\n    \n    # Trapezoidal integration\n    @NLconstraint(rocket,\n        m[j] == m[j - 1] - 0.5 * Δt * (T[j] + T[j-1]) / c)\nend\n\n# Solve for the control and state\nprintln(\"Solving...\")\nstatus = optimize!(rocket)\n\n# Display results\n# println(\"Solver status: \", status)\nprintln(\"Max height: \", objective_value(rocket))\n\n\n# Can visualize the state and control variables\nusing Gadfly\n\n\nh_plot = plot(x = (1:n) * value.(Δt), y = value.(h)[:], Geom.line,\n                Guide.xlabel(\"Time (s)\"), Guide.ylabel(\"Altitude\"))\nm_plot = plot(x = (1:n) * value.(Δt), y = value.(m)[:], Geom.line,\n                Guide.xlabel(\"Time (s)\"), Guide.ylabel(\"Mass\"))\nv_plot = plot(x = (1:n) * value.(Δt), y = value.(v)[:], Geom.line,\n                Guide.xlabel(\"Time (s)\"), Guide.ylabel(\"Velocity\"))\nT_plot = plot(x = (1:n) * value.(Δt), y = value.(T)[:], Geom.line,\n                Guide.xlabel(\"Time (s)\"), Guide.ylabel(\"Thrust\"))\ndraw(SVG(6inch, 6inch), vstack(hstack(h_plot, m_plot), hstack(v_plot, T_plot)))\n\n", "meta": {"hexsha": "18daa67dd3adecf0089c8d4ae4b0061c8c027cf3", "size": 3266, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/modelling/rocket_control.jl", "max_stars_repo_name": "mtanneau/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 75, "max_stars_repo_stars_event_min_datetime": "2020-06-15T13:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T12:58:48.000Z", "max_issues_repo_path": "test/modelling/rocket_control.jl", "max_issues_repo_name": "mtanneau/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-05-27T05:36:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T09:52:29.000Z", "max_forks_repo_path": "test/modelling/rocket_control.jl", "max_forks_repo_name": "mtanneau/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-10-09T09:32:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T17:41:21.000Z", "avg_line_length": 29.1607142857, "max_line_length": 85, "alphanum_fraction": 0.5483772198, "num_tokens": 1186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620608291783, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7912872816739454}}
{"text": "\"\"\"\n    CosineKernel(; metric=Euclidean())\n\nCosine kernel with respect to the `metric`.\n\n# Definition\n\nFor inputs ``x, x'`` and metric ``d(\\\\cdot, \\\\cdot)``, the cosine kernel is defined as\n```math\nk(x, x') = \\\\cos(\\\\pi d(x, x')).\n```\nBy default, ``d`` is the Euclidean metric ``d(x, x') = \\\\|x - x'\\\\|_2``.\n\"\"\"\nstruct CosineKernel{M} <: SimpleKernel\n    metric::M\nend\n\nCosineKernel(; metric=Euclidean()) = CosineKernel(metric)\n\nkappa(::CosineKernel, d::Real) = cospi(d)\n\nmetric(k::CosineKernel) = k.metric\n\nBase.show(io::IO, k::CosineKernel) = print(io, \"Cosine Kernel (metric = \", k.metric, \")\")\n", "meta": {"hexsha": "50cc6fdf362719cb5ef5150678c6368abdffe271", "size": 598, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basekernels/cosine.jl", "max_stars_repo_name": "bmharsha/KernelFunctions.jl", "max_stars_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 200, "max_stars_repo_stars_event_min_datetime": "2020-04-07T11:28:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:14:13.000Z", "max_issues_repo_path": "src/basekernels/cosine.jl", "max_issues_repo_name": "bmharsha/KernelFunctions.jl", "max_issues_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 324, "max_issues_repo_issues_event_min_datetime": "2020-03-24T16:26:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T07:34:54.000Z", "max_forks_repo_path": "src/basekernels/cosine.jl", "max_forks_repo_name": "bmharsha/KernelFunctions.jl", "max_forks_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2020-03-25T10:25:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T21:19:06.000Z", "avg_line_length": 23.92, "max_line_length": 89, "alphanum_fraction": 0.627090301, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7912493129453927}}
{"text": "\"\"\"\nspitchfork(u,lambda)\n\nThe nonlinearity f(u) = u^3 - lamba u. The dynamics for du/du = -f(u)\nhave a pitchfork bifurcation at lambda=0. The steady-state solution \nu=0 is unique for lambda < 0 and there are three steady-state solutions\nif lambda > 0. This is a simple-minded version of the buckling beam problem.\n\nThe function sptest(u) = spitchfork(u,.5) is the one I call in the testing.\n\n\"\"\"\nfunction spitchfork(u, lambda)\n    fu = u^3 - lambda * u\n    return fu\nend\n\nfunction sptest(u)\n    lambda = 0.5\n    spt = spitchfork(u, lambda)\n    return spt\nend\n\nfunction spitchp(u, lambda)\n    fp = 3 * u^2 - lambda\n    return fp\nend\n\nfunction sptestp(u)\n    lambda = 0.5\n    sptp = spitchp(u, lambda)\n    return sptp\nend\n", "meta": {"hexsha": "1b7a64e2dc0413ec362b25068dc33849638dab50", "size": 720, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TestProblems/Scalars/spitchfork.jl", "max_stars_repo_name": "aliddell/SIAMFANLEquations.jl", "max_stars_repo_head_hexsha": "4a9bad23d726993764c5790d56b9d68cb27dffe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2020-04-16T19:59:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T12:18:53.000Z", "max_issues_repo_path": "src/TestProblems/Scalars/spitchfork.jl", "max_issues_repo_name": "aliddell/SIAMFANLEquations.jl", "max_issues_repo_head_hexsha": "4a9bad23d726993764c5790d56b9d68cb27dffe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-07-22T20:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T01:14:10.000Z", "max_forks_repo_path": "src/TestProblems/Scalars/spitchfork.jl", "max_forks_repo_name": "aliddell/SIAMFANLEquations.jl", "max_forks_repo_head_hexsha": "4a9bad23d726993764c5790d56b9d68cb27dffe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-03T10:47:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-03T10:47:05.000Z", "avg_line_length": 21.8181818182, "max_line_length": 76, "alphanum_fraction": 0.6791666667, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133565584851, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7912431678802953}}
{"text": "# This file investigates 2D hiddden interpolation mean square error(MSE) with respect to inteprolation point number.\n\nusing FractalTools \nusing Makie \n\n# Construct interpolation data \nf(x, y) = [\n    x^2 + y^2 + 1,\n    x^2 - y^2,\n]\nvtx = [\n    BigFloat.([0.0, 0.0]), \n    BigFloat.([1.0, 0.0]), \n    BigFloat.([0.5, 1.0])\n    ]\nfreevar = 0.001\nnpts    = 50 : 5 : 150\nntpts   = 2 * npts[end]\n\n# Construct test data \ntpts = getdata(vtx, ntpts)\n\n# Compute errors \nmse = map(npts) do npt\n    @info npt \n    # Construct interpolation data \n    pts = getdata(f, vtx, npt)\n\n    # Construct interpolant \n    interp = interpolate(pts, HInterp2D(fill(freevar, 2, 2)))\n\n    # Compute error \n    fvals = getindex.(map(pnt -> f(pnt...), tpts), 1)\n    ivals = getindex.(map(pnt -> interp(pnt...), tpts), 1)\n    sum((fvals - ivals).^2) / length(tpts)\nend \n\n# Plot mse \nfig = Figure() \nax = fig[1, 1] = Axis(fig, xlabel=\"Number of Points\", ylabel=\"MSE\", title=\"2D Hidden Interpolation MSE\") \nstem!(ax, npts, mse, color=:black)\nsave(joinpath(@__DIR__, \"hinterp2d_mse.png\"), fig)\ndisplay(fig)\n", "meta": {"hexsha": "c2444dffd1da3313a0aa132987f3ac521044bce2", "size": 1075, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiment_1/interpolation_mse_vs_numpoints/hinterp2d/hinterp2d.jl", "max_stars_repo_name": "zekeriyasari/FractalTools.jl", "max_stars_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-08T12:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T12:50:16.000Z", "max_issues_repo_path": "experiment_2/interpolation_mse_vs_numpoints/hinterp2d/hinterp2d.jl", "max_issues_repo_name": "zekeriyasari/FractalTools.jl", "max_issues_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-09-05T18:22:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T10:09:46.000Z", "max_forks_repo_path": "experiment_2/interpolation_mse_vs_numpoints/hinterp2d/hinterp2d.jl", "max_forks_repo_name": "zekeriyasari/FractalTools.jl", "max_forks_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4318181818, "max_line_length": 116, "alphanum_fraction": 0.623255814, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.7912431668386994}}
{"text": "function score(x, y)\n    r = sqrt(x^2 + y^2)\n    if r <= 1\n        return 10\n    elseif r <= 5\n        return 5\n    elseif r <= 10\n        return 1\n    else\n        return 0\n    end\nend\n", "meta": {"hexsha": "21cec9e0fae339dc4e8b24f291e958d5a0702ee7", "size": 186, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/darts/darts.jl", "max_stars_repo_name": "aadimator/exercism", "max_stars_repo_head_hexsha": "191d979166258e508230d3b652eeb581ff1077e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/darts/darts.jl", "max_issues_repo_name": "aadimator/exercism", "max_issues_repo_head_hexsha": "191d979166258e508230d3b652eeb581ff1077e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/darts/darts.jl", "max_forks_repo_name": "aadimator/exercism", "max_forks_repo_head_hexsha": "191d979166258e508230d3b652eeb581ff1077e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.3076923077, "max_line_length": 23, "alphanum_fraction": 0.4516129032, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.939913356558485, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7912431622854584}}
{"text": "export fourier_diff\n\n\"\"\"\n    fourier_diff([T=Float64,] N; order=1)\n\nCreate a Fourier differentiation matrix with numerical type T on the domain\n`x = range(0, 2π, length=N+1)[1:end-1]`.\n\"\"\"\nfunction fourier_diff(T::Type{<:Number}, N::Integer; order=1)\n    D = zeros(T, N, N)\n    n1 = (N - 1) ÷ 2\n    n2 = N ÷ 2\n    x = LinRange{T}(0, π, N+1)\n    if order == 1\n        for i in 2:N\n            sgn = (one(T)/2 - iseven(i))\n            D[i, 1] = iseven(N) ? sgn*cot(x[i]) : sgn*csc(x[i])\n        end\n    elseif order == 2\n        D[1, 1] = iseven(N) ? -N^2*one(T)/12 - one(T)/6 : -N^2*one(T)/12 + one(T)/12\n        for i in 2:N\n            sgn = -(one(T)/2 - iseven(i))\n            D[i, 1] = iseven(N) ? sgn*csc(x[i]).^2 : sgn*cot(x[i])*csc(x[i])\n        end\n    else\n        error(\"Not implemented\")\n    end\n    for j in 2:N\n        D[1, j] = D[N, j-1]\n        D[2:N, j] .= D[1:N-1, j-1]\n    end\n    return D\nend\nfourier_diff(N::Integer; kwargs...) = fourier_diff(Float64, N; kwargs...)\n", "meta": {"hexsha": "1270529b52a52648ab093f7943a1765daba8c320", "size": 985, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fourier_diff.jl", "max_stars_repo_name": "dawbarton/RandomUseful.jl", "max_stars_repo_head_hexsha": "4411a4c7a8927f0be13811e6c97427733447f2ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fourier_diff.jl", "max_issues_repo_name": "dawbarton/RandomUseful.jl", "max_issues_repo_head_hexsha": "4411a4c7a8927f0be13811e6c97427733447f2ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fourier_diff.jl", "max_forks_repo_name": "dawbarton/RandomUseful.jl", "max_forks_repo_head_hexsha": "4411a4c7a8927f0be13811e6c97427733447f2ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1428571429, "max_line_length": 84, "alphanum_fraction": 0.4984771574, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766225, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7912431560970756}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.18\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ dcfde69e-20c7-11eb-0108-dbd2f5cb0098\nbegin\n\tusing Pkg\n    Pkg.activate(pwd())\n\tPkg.instantiate()\nend\n\n# ╔═╡ 864115a0-20d4-11eb-16ff-71d198f9342e\nbegin\n\tusing CSV\n\tusing DataFrames\n\tusing RDatasets\n\tusing StatsBase\n\tusing Plots\n\tusing LinearAlgebra\n\timport Statistics: covm\nend\n\n# ╔═╡ a33c14a0-20c2-11eb-0bf8-837173d9d91c\nmd\"\"\"\n# Assignment 1: Implement PCA\n### Aadam (CS1945)\n### CSE 662 - Deep Learning by Dr. Masroor Hussain\n\n---\n\n## Assignment Statement:\nWrite the code in C, Python or Matlab for $l=1$ PCA as discussed in class of Chapter no. 2. Five bonus points for $1 =< l < n$\n\n---\n\"\"\"\n\n# ╔═╡ cf5c9eb0-20c2-11eb-05ba-2f5dd23fdaf4\nmd\"\"\"\n# Principal Component Analysis (PCA)\nPCA is a technique that is used to derive an orthogonal projection to convert a given set of observations to linearly uncorrelated variables, called **principal components**.\n\nOne of the most widely used application of PCA is **dimensionality reduction**, which helps us out, when training our models on large datasets, by minimizing noise and redundancy in the dataset. Basic idea of the dimensionality reduction is to represent an $M$-dimensional data into an $N$-dimensional subspace, where $N < M$. This would result in data loss, but our aim is to minimize it as much as possible. For that purposes, we try to find some **principal components** in the data that can represent the features as a linear combination, without loosing much information.\n\nPCA uses **covariance matrix** to analyze:\n- variance of each feature, showing if a feature is relevant or pure noise.\n- linear relationship strength between pairs of features, spotting redundant features.\n\nThere are two main approaches to identify principal components:\n1. Calculate the **eigenvectors** of the covariance matrix.\n2. Calculate the **single value decomposition** of the covariance matrix.\n\nAlthough **SVD** has higher numerical accuracy, it has lower running time, as compared to the **eigenvector decomposition** method.\n\nFor this assignment, we'll use **Eigendecomposition** method to find principal components. \n\"\"\"\n\n# ╔═╡ b6ed7820-20ce-11eb-0584-9130387e39ef\nmd\"\"\"\n# Solution:\nFirst, let's create a dummy dataset.\n\"\"\"\n\n# ╔═╡ 85bf8990-20d4-11eb-1a7b-e35d9e62f35a\ngr();\n\n# ╔═╡ f5d95832-20ea-11eb-2828-39ebb61c877f\nmd\"\"\"\n### Utility functions\n\"\"\"\n\n# ╔═╡ 0024d7b0-20eb-11eb-2959-af3584eb7750\nbegin\n\tcentralize(x::AbstractVector, m::AbstractVector) = (isempty(m) ? x : x - m)\n\tcentralize(x::AbstractMatrix, m::AbstractVector) = (isempty(m) ? x : x .- m)\n\n\tdecentralize(x::AbstractVector, m::AbstractVector) = (isempty(m) ? x : x + m)\n\tdecentralize(x::AbstractMatrix, m::AbstractVector) = (isempty(m) ? x : x .+ m)\n\t\n\ttransform(P, x, mv) = transpose(P) * centralize(x, mv)\n\treconstruct(P, y, mv) = decentralize(P * y, mv)\n\t\n\t# extract k values/vectors\n\tfunction extract_kv(fac, ord, k)\n\t\tsi = ord[1:k]\n\t\tvals = fac.values[si]\n\t\tvecs = fac.vectors[:, si]\n\t\treturn (vals, vecs)\n\tend\nend\n\n# ╔═╡ 85976820-20d4-11eb-2afa-47a833fdccc4\nmd\"\"\"\n## Input Data\nFor this example, we'll use **iris** dataset.\n\"\"\"\n\n# ╔═╡ dcce4b20-20c7-11eb-3cb1-852a46b75c31\niris = dataset(\"datasets\", \"iris\") # DataFrame(rand(100, 10))\n\n# ╔═╡ dcb4a8a2-20c7-11eb-3a1a-9fb620e84e57\nsize(iris)\n\n# ╔═╡ dc975ca0-20c7-11eb-0a2b-b9e470c6e311\ndescribe(iris)\n\n# ╔═╡ 9241d120-20d2-11eb-0b30-25249995c00c\nmd\"\"\"\n#### Let's create separate train and test datasets.\n\"\"\"\n\n# ╔═╡ b2a8ccc0-20d2-11eb-28eb-87dc018ae352\nXtrain = Array(iris[1:2:end,1:4])';\n\n# ╔═╡ afb22c8e-20d3-11eb-339a-09f39705a02f\nYtrain = Array(iris[1:2:end,5]);\n\n# ╔═╡ afe6aa10-20d3-11eb-03a4-89a46ade9feb\nXtest = Array(iris[2:2:end,1:4])';\n\n# ╔═╡ b0004c90-20d3-11eb-2b38-452b177600d8\nYtest = Array(iris[2:2:end,5]);\n\n# ╔═╡ b02fe810-20d3-11eb-21f4-f9939c117c12\nmd\"\"\"\nSuppose `Xtrain` and `Xtest` are training and testing data matrix, with each observation in a column.\n\n## Data Normalization\nNow, we need to normalize the data.\n\n\"\"\"\n\n# ╔═╡ 399f2a20-20d4-11eb-1c3a-e76ac9707e29\nmean_iris = vec(mean(Xtrain, dims=2))\n\n# ╔═╡ c58d8a10-20e1-11eb-301a-eb715e5926d8\nmd\"\"\"\n## Covariance Matrix Computation\nCovariance matrix is an $N \\times N$ symmetric matrix, where $N$ is the number of dimensions. This tells us about the relation between any two features, and the variation of data from the mean.\n\"\"\"\n\n# ╔═╡ 39b65ba2-20d4-11eb-11bd-7daa396810ac\nC_iris = covm(Xtrain, mean_iris, 2);\n\n# ╔═╡ 6493e090-20e3-11eb-0dec-0bdef8eb1c6a\nDataFrame(C_iris)\n\n# ╔═╡ c308e590-20e2-11eb-0ddb-055f8bdedb85\nmd\"\"\"\n## Eigendecomposition of Covariance Matrix\nWe need to find the eigenvalues and eigenvectors of the covariance matrix in order to find the principal components of the data. These components are created in such a way that they are uncorrelated, and the first component contains the maximum amount of information possible, and the second contains the maximum remaining, and so on.\n\"\"\"\n\n# ╔═╡ 39e24da0-20d4-11eb-10e5-8320e876fb74\neg = eigen(Symmetric(C_iris));\n\n# ╔═╡ b04fa510-20d3-11eb-0d40-21f2bf50e115\neg_values = eg.values\n\n# ╔═╡ f010e210-20e5-11eb-1952-37e6ed84ea22\neg_vectors = eg.vectors\n\n# ╔═╡ 35710110-20e5-11eb-0ad2-ef911c8d78bc\nmd\"\"\"\nLet's sort the eigenvalues in reverse order, so the component which contains the most information is at the front.\n\"\"\"\n\n# ╔═╡ b1d8dc20-20de-11eb-1364-59fc5f488736\nord = sortperm(eg_values; rev=true)\n\n# ╔═╡ 6f9d6dfe-20e5-11eb-2745-e95f930eaf88\nmd\"\"\"\nLet's see how much information each component contains. For that, we need to find the total variance of the input, and then divide the principal component's variance with it. We'll plot the values for better visualization.\n\"\"\"\n\n# ╔═╡ b211ed80-20de-11eb-3abc-7f0b887915a5\ntvar = sum(eg_values)\n\n# ╔═╡ 9fefec80-20e6-11eb-3e16-e5f17e1d9560\neg_values[ord] ./ tvar * 100\n\n# ╔═╡ b25a1a10-20de-11eb-3bcb-fbe70a5b974d\nbar(eg_values[ord] ./ tvar * 100, title=\"Scree Plot\")\n\n# ╔═╡ b26da210-20de-11eb-026b-8fc4efce305c\nmd\"\"\"\nBy looking at the above graph, we can see that the first component, $PC 1$, contains more than $90 \\%$ of the information, while $PC 2$ contains less than $5 \\%$.\n\nEven though many believe $PCA$ to be a dimensionality reduction algorithm, primarily it's a data transformation algorithm. It just makes our data amenable to data reduction, as shown above. Here, as most of the information is contained in the first couple of principal components, we can decide to keep only those componenets and discard the rest, resulting in a reduction in the dimensionality of the dataset.\n\n### $l = 1$:\nThis means that we only take the first PC and discard the rest.\n\"\"\"\n\n# ╔═╡ d6429920-20cf-11eb-0bf1-8f74c17dc643\nv, P = extract_kv(eg, ord, 1)\n\n# ╔═╡ 72f60020-20eb-11eb-049a-d14c26e12ddb\nmd\"\"\"\nThis returns the eigen values, as well as the project matrix $P$. We can use $P$ to transform dataset. Transforming the `Xtest` using $P$ would result in:\n\"\"\"\n\n# ╔═╡ d628f6a0-20cf-11eb-11cc-01f1ca2b6f13\ntr_data = transform(P, Xtest, mean_iris)\n\n# ╔═╡ 6ae889c0-20eb-11eb-3ecb-4f13647511c3\nmd\"\"\"\nwhich is a $1 \\times 75$ array, instead of the original $4 \\times 75$.  \n\nLet's try to reconstruct the original data from the transformed data using $P$.\n\"\"\"\n\n# ╔═╡ 1081c390-20f8-11eb-3e81-133df7444871\nrecon_data = reconstruct(P, tr_data, mean_iris);\n\n# ╔═╡ 3313dc90-20f8-11eb-27eb-e9ea7e6a3805\nmd\"\"\"\nPrinting the first 5 observations from both the reconstructed data as well as the original data.\n\"\"\"\n\n# ╔═╡ d5e95590-20cf-11eb-0d5f-e3e5f2be14c0\nDataFrame(recon_data)\n\n# ╔═╡ d5b26710-20cf-11eb-0f4c-7f81055af3e3\nDataFrame(Xtest[:, 1:5])\n\n# ╔═╡ 4cd4fb30-20c3-11eb-0631-a9c8840a4cf9\nmd\"\"\"\nAs can be seen, the reconstructed data is fairly close to the original data, although not exactly the same because this is a lossy method. Even though we retained around $92\\%$ information, we still lost some information by reducing the dimensions.\n\nWe can retain more information by increasing $l$, i.e. increasing the number of output dimensions.\n\n## $1 <= l < n$\nInstead of taking only $PC 1$, we will take the first three PCs.\n\"\"\"\n\n# ╔═╡ 740d6e20-20ec-11eb-1b12-1d614d3efb08\nv3, P3 = extract_kv(eg, ord, 3)\n\n# ╔═╡ 7466b1b2-20ec-11eb-1a71-e7061e6a7ad6\nmd\"\"\"\nAgain, let's first transform and reconstruct the data using `P3`.\n\"\"\"\n\n# ╔═╡ 747f1bb0-20ec-11eb-3cbf-a3a8d7a64563\ntr3_data = transform(P3, Xtest, mean_iris);\n\n# ╔═╡ 65ce7a10-20fc-11eb-1d02-f57de17db24e\nsize(tr3_data)\n\n# ╔═╡ 7493b520-20ec-11eb-0e19-57cbd43d09af\nrecon3_data = reconstruct(P3, tr3_data, mean_iris);\n\n# ╔═╡ 74a9ae20-20ec-11eb-1e5d-7984c0a399f3\nDataFrame(recon3_data)\n\n# ╔═╡ ff1b4e90-20f8-11eb-3924-2fa0c61677fd\nDataFrame(Xtest[:, 1:5])\n\n# ╔═╡ 053f9290-20f9-11eb-1cb6-6f5c7b26e279\nmd\"\"\"\nWe can see that using $l = 3$ gives a better approximation of the original data as compared to $l = 1$.\n\n## Visualization\nLet's visualize the first 3 principal components in a 3D plot.\n\"\"\"\n\n# ╔═╡ 9599eb10-20f9-11eb-044b-cd71da0c30a3\nbegin\n\t# group by labels, for color coding\n\tsetosa = tr3_data[:,Ytest.==\"setosa\"];\n\tversicolor = tr3_data[:,Ytest.==\"versicolor\"];\n\tvirginica = tr3_data[:,Ytest.==\"virginica\"];\n\t\n\tp = scatter(setosa[1,:],setosa[2,:],setosa[3,:],marker=:circle,linewidth=0)\n\tscatter!(versicolor[1,:],versicolor[2,:],versicolor[3,:],marker=:circle,linewidth=0)\n\tscatter!(virginica[1,:],virginica[2,:],virginica[3,:],marker=:circle,linewidth=0)\n\tplot!(p,xlabel=\"PC1\",ylabel=\"PC2\",zlabel=\"PC3\")\nend\n\n# ╔═╡ 645934a0-20fb-11eb-1750-cf7ca28ab9e6\nmd\"\"\"\n## Conclusion\nIn this notebook, we showed how we can use `PCA` to find principal components of some data, and then use those for dimensionality reduction without severly affecting and losing the information.\n\"\"\"\n\n# ╔═╡ 4d526890-20c3-11eb-082b-e912d7c9b3e2\nmd\"\"\"\n# Resources\n\n- [StatQuest: Principal Component Analysis (PCA), Step-by-Step](https://www.youtube.com/watch?v=FgakZw6K1QQ&t=458s&ab_channel=StatQuestwithJoshStarmer)\n- [Data Analysis 6: Principal Component Analysis (PCA) - Computerphile](https://www.youtube.com/watch?v=TJdH6rPA-TI&ab_channel=Computerphile)\n- [Making sense of principal component analysis, eigenvectors & eigenvalues](https://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues/140579)\n- [A STEP BY STEP EXPLANATION OF PRINCIPAL COMPONENT ANALYSIS](https://builtin.com/data-science/step-step-explanation-principal-component-analysis)\n- [Machine Learning — Singular Value Decomposition (SVD) & Principal Component Analysis (PCA)](https://jonathan-hui.medium.com/machine-learning-singular-value-decomposition-svd-principal-component-analysis-pca-1d45e885e491)\n- [Relationship between SVD and PCA. How to use SVD to perform PCA?](https://stats.stackexchange.com/questions/134282/relationship-between-svd-and-pca-how-to-use-svd-to-perform-pca)\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─a33c14a0-20c2-11eb-0bf8-837173d9d91c\n# ╟─cf5c9eb0-20c2-11eb-05ba-2f5dd23fdaf4\n# ╟─dcfde69e-20c7-11eb-0108-dbd2f5cb0098\n# ╟─b6ed7820-20ce-11eb-0584-9130387e39ef\n# ╠═864115a0-20d4-11eb-16ff-71d198f9342e\n# ╟─85bf8990-20d4-11eb-1a7b-e35d9e62f35a\n# ╟─f5d95832-20ea-11eb-2828-39ebb61c877f\n# ╠═0024d7b0-20eb-11eb-2959-af3584eb7750\n# ╟─85976820-20d4-11eb-2afa-47a833fdccc4\n# ╠═dcce4b20-20c7-11eb-3cb1-852a46b75c31\n# ╠═dcb4a8a2-20c7-11eb-3a1a-9fb620e84e57\n# ╠═dc975ca0-20c7-11eb-0a2b-b9e470c6e311\n# ╟─9241d120-20d2-11eb-0b30-25249995c00c\n# ╠═b2a8ccc0-20d2-11eb-28eb-87dc018ae352\n# ╠═afb22c8e-20d3-11eb-339a-09f39705a02f\n# ╠═afe6aa10-20d3-11eb-03a4-89a46ade9feb\n# ╠═b0004c90-20d3-11eb-2b38-452b177600d8\n# ╟─b02fe810-20d3-11eb-21f4-f9939c117c12\n# ╠═399f2a20-20d4-11eb-1c3a-e76ac9707e29\n# ╟─c58d8a10-20e1-11eb-301a-eb715e5926d8\n# ╠═39b65ba2-20d4-11eb-11bd-7daa396810ac\n# ╟─6493e090-20e3-11eb-0dec-0bdef8eb1c6a\n# ╟─c308e590-20e2-11eb-0ddb-055f8bdedb85\n# ╠═39e24da0-20d4-11eb-10e5-8320e876fb74\n# ╠═b04fa510-20d3-11eb-0d40-21f2bf50e115\n# ╠═f010e210-20e5-11eb-1952-37e6ed84ea22\n# ╟─35710110-20e5-11eb-0ad2-ef911c8d78bc\n# ╠═b1d8dc20-20de-11eb-1364-59fc5f488736\n# ╟─6f9d6dfe-20e5-11eb-2745-e95f930eaf88\n# ╠═b211ed80-20de-11eb-3abc-7f0b887915a5\n# ╟─9fefec80-20e6-11eb-3e16-e5f17e1d9560\n# ╠═b25a1a10-20de-11eb-3bcb-fbe70a5b974d\n# ╟─b26da210-20de-11eb-026b-8fc4efce305c\n# ╠═d6429920-20cf-11eb-0bf1-8f74c17dc643\n# ╟─72f60020-20eb-11eb-049a-d14c26e12ddb\n# ╠═d628f6a0-20cf-11eb-11cc-01f1ca2b6f13\n# ╟─6ae889c0-20eb-11eb-3ecb-4f13647511c3\n# ╠═1081c390-20f8-11eb-3e81-133df7444871\n# ╟─3313dc90-20f8-11eb-27eb-e9ea7e6a3805\n# ╠═d5e95590-20cf-11eb-0d5f-e3e5f2be14c0\n# ╠═d5b26710-20cf-11eb-0f4c-7f81055af3e3\n# ╟─4cd4fb30-20c3-11eb-0631-a9c8840a4cf9\n# ╠═740d6e20-20ec-11eb-1b12-1d614d3efb08\n# ╟─7466b1b2-20ec-11eb-1a71-e7061e6a7ad6\n# ╠═747f1bb0-20ec-11eb-3cbf-a3a8d7a64563\n# ╠═65ce7a10-20fc-11eb-1d02-f57de17db24e\n# ╠═7493b520-20ec-11eb-0e19-57cbd43d09af\n# ╠═74a9ae20-20ec-11eb-1e5d-7984c0a399f3\n# ╠═ff1b4e90-20f8-11eb-3924-2fa0c61677fd\n# ╟─053f9290-20f9-11eb-1cb6-6f5c7b26e279\n# ╟─9599eb10-20f9-11eb-044b-cd71da0c30a3\n# ╟─645934a0-20fb-11eb-1750-cf7ca28ab9e6\n# ╟─4d526890-20c3-11eb-082b-e912d7c9b3e2\n", "meta": {"hexsha": "c99232438c49524d63c7bb83484208a85f283384", "size": 12951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1.pca/notebook.jl", "max_stars_repo_name": "aadimator/CSE-622-Deep-Learning", "max_stars_repo_head_hexsha": "1920533f227cbafdd95c4ae3035f6994f17dc7a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1.pca/notebook.jl", "max_issues_repo_name": "aadimator/CSE-622-Deep-Learning", "max_issues_repo_head_hexsha": "1920533f227cbafdd95c4ae3035f6994f17dc7a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1.pca/notebook.jl", "max_forks_repo_name": "aadimator/CSE-622-Deep-Learning", "max_forks_repo_head_hexsha": "1920533f227cbafdd95c4ae3035f6994f17dc7a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5847457627, "max_line_length": 576, "alphanum_fraction": 0.7463516331, "num_tokens": 5314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8872046026642944, "lm_q1q2_score": 0.7912188693216129}}
{"text": "function axis_angle_to_quaternion(x)\n    @assert length(x) == 3\n    θ = norm(x)\n    if θ > 0.0\n        r = x ./ θ\n        q = Quaternion(cos(0.5 * θ), sin(0.5 * θ) * r)\n    else\n        q = Quaternion(1.0, 0.0, 0.0, 0.0)\n    end\n    return q\nend\n\nfunction daxis_angle_to_quaterniondx(x)\n    θ = norm(x)\n    if θ > 0.0\n        r = x ./ θ\n\n        ∂qw∂x = -0.5 * sin(0.5 * θ) * transpose(x) ./ θ\n        ∂qx∂x = 0.5 * cos(0.5 * θ) * transpose(x) ./ θ * r[1] + [sin(0.5 * θ) / θ 0.0 0.0] - sin(0.5 * θ) * x[1] / θ^2 * transpose(x) ./ θ\n        ∂qy∂x = 0.5 * cos(0.5 * θ) * transpose(x) ./ θ * r[2] + [0.0 sin(0.5 * θ) / θ 0.0] - sin(0.5 * θ) * x[2] / θ^2 * transpose(x) ./ θ\n        ∂qz∂x = 0.5 * cos(0.5 * θ) * transpose(x) ./ θ * r[3] + [0.0 0.0 sin(0.5 * θ) / θ] - sin(0.5 * θ) * x[3] / θ^2 * transpose(x) ./ θ\n\n        return [\n                ∂qw∂x;\n                ∂qx∂x;\n                ∂qy∂x;\n                ∂qz∂x;\n               ]\n    else\n        return [\n                    0.0  0.0  0.0;\n                    0.5  0.0  0.0;\n                    0.0  0.5  0.0;\n                    0.0  0.0  0.5;\n                ]\n    end\nend\n\nfunction axes_pair_to_quaternion(n1, n2)\n\tif norm(n1 + n2, Inf) < 1e-5\n\t\tn2 = n2 + 1e-5ones(3)\n\tend\n\n\treg(x) = 1e-20 * (x == 0) + x\n\t# provides the quaternion that rotates n1 into n2, assuming n1 and n2 are normalized\n\tn1 ./= reg(norm(n1))\n\tn2 ./= reg(norm(n2))\n\tn3 = skew(n1)*n2\n\tcθ = n1' * n2 # cosine\n\tsθ = norm(n3) # sine\n\taxis = n3 ./ reg(sθ)\n\ttanθhalf = sθ / reg(1 + cθ)\n\tq = [1; tanθhalf * axis]\n\tq /= norm(q)\n\treturn Quaternion(q...)\nend\n", "meta": {"hexsha": "e2c0455293f2f58db62cf07baf9de1097840e809", "size": 1581, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/orientation/axis_angle.jl", "max_stars_repo_name": "rejuvyesh/Dojo.jl", "max_stars_repo_head_hexsha": "6c9f8bdb31de3e2068ea1a51afe317ada3922379", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70, "max_stars_repo_stars_event_min_datetime": "2022-03-02T01:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:14:51.000Z", "max_issues_repo_path": "src/orientation/axis_angle.jl", "max_issues_repo_name": "dojo-sim/Dojo.jl", "max_issues_repo_head_hexsha": "33ccdde8d7f74c4ea3c3bffdebcc6ed65959a5be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2022-03-02T06:58:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T17:17:26.000Z", "max_forks_repo_path": "src/orientation/axis_angle.jl", "max_forks_repo_name": "rejuvyesh/Dojo.jl", "max_forks_repo_head_hexsha": "6c9f8bdb31de3e2068ea1a51afe317ada3922379", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2022-03-07T01:47:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T19:13:07.000Z", "avg_line_length": 27.7368421053, "max_line_length": 138, "alphanum_fraction": 0.4345351044, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488964, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7911345123052046}}
{"text": "# p30.jl - spectral integration, ODE style (compare p12.jl)\n\n# Computation: various values of N, four functions:\nNmax = 50; E = zeros(4,Nmax); clf();\nfor N = 1:Nmax\n    i = 1:N; (D,x) = cheb(N);\n    x = x[i]; Di = inv(D[i,i]); w = Di[1,:];\n    f = @. abs(x)^3;     E[1,N] = abs(dot(w,f) - .5);\n    f = @. exp(-x^(-2)); E[2,N] = abs(dot(w,f) - 2*(exp(-1)+sqrt(pi)*(erf(1)-1)));\n    f = @. 1/(1+x^2);    E[3,N] = abs(dot(w,f) - pi/2);\n    f = x.^10;           E[4,N] = abs(dot(w,f) - 2/11);\nend\n\n# Plot results:\nlabels = [L\"|x|^3\",L\"\\exp(-x^2)\",L\"1/(1+x^2)\",L\"x^{10}\"];\nfor iplot = 1:4\n    subplot(2,2,iplot)\n    semilogy(E[iplot,:]+1e-100,\".-\",markersize=10);\n    axis([0,Nmax,1e-18,1e3]); grid(true);\n    xticks(0:10:Nmax); yticks((10.0).^(-15:5:0));\n    ylabel(\"error\"); text(32,.004,labels[iplot]);\nend\n", "meta": {"hexsha": "59063fd6edac196388dae58209d038718a205d32", "size": 805, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p30.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p30.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p30.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0, "max_line_length": 82, "alphanum_fraction": 0.500621118, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.791134509458907}}
{"text": "# Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/\n#  Niccolò Antonello <nantonel@idiap.ch>\n\nexport BoolWeight\n\n\"\"\"\n`BoolWeight(x::Bool)`\n\n| Set           |     ``\\\\oplus``      |  ``\\\\otimes``  | ``\\\\bar{0}`` | ``\\\\bar{1}`` |\n|:-------------:|:--------------------:|:--------------:|:------------:|:------------:|\n| ``\\\\{0,1\\\\}`` |       ``\\\\lor``      |  ``\\\\land``    |   ``0``      |    ``1``     | \n\"\"\"\nstruct BoolWeight <: Semiring\n  x::Bool\nend\n\nzero(::Type{BoolWeight}) = BoolWeight(false)\none(::Type{BoolWeight}) = BoolWeight(true)\n\n*(a::BoolWeight, b::BoolWeight) = BoolWeight(a.x && b.x)\n+(a::BoolWeight, b::BoolWeight) = BoolWeight(a.x || b.x)\n\n#properties\nisidempotent(::Type{W}) where {W <: BoolWeight} = true\niscommulative(::Type{W}) where {W <: BoolWeight} = true\nisleft(::Type{W}) where {W <: BoolWeight}= true\nisright(::Type{W}) where {W <: BoolWeight}= true\nispath(::Type{W}) where {W <: BoolWeight}= true\niscomplete(::Type{W}) where {W <: BoolWeight}= true\n", "meta": {"hexsha": "b421cfec3ce24d7b30f43c3fae7c7bc341fd4df2", "size": 994, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/semirings/boolean.jl", "max_stars_repo_name": "idiap/FiniteStateTransducers.jl", "max_stars_repo_head_hexsha": "430bf273960bd3f43f4042ee85a7c9f3d846d37f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-20T10:41:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-20T10:41:21.000Z", "max_issues_repo_path": "src/semirings/boolean.jl", "max_issues_repo_name": "idiap/FiniteStateTransducers.jl", "max_issues_repo_head_hexsha": "430bf273960bd3f43f4042ee85a7c9f3d846d37f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-02-09T16:54:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-14T00:10:46.000Z", "max_forks_repo_path": "src/semirings/boolean.jl", "max_forks_repo_name": "idiap/FiniteStateTransducers.jl", "max_forks_repo_head_hexsha": "430bf273960bd3f43f4042ee85a7c9f3d846d37f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1333333333, "max_line_length": 88, "alphanum_fraction": 0.5301810865, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7911344980915529}}
{"text": "using Distributions\nusing DataStructures\n\nf(x) = x^2 - 5 * x + 6\n\nfunction filter_best_solutions(solutions; pa=0.25)\n    new_best_solutions=SortedDict(Dict{Float64, Float64}())\n    println(\"***FILTER RCVD : \", length(solutions))\n    println(\"Filterting : \", floor((length(solutions) - length(solutions)*pa)))\n    let\n        i = 1\n        for (key, value) in solutions\n            new_best_solutions[key] = value\n            i = i + 1\n            if i >= (length(solutions) - length(solutions)*pa)\n                return merge(new_best_solutions, initialize_population(floor((length(solutions) - length(solutions)*pa))))\n            end\n        end\n    end\nend\n\n\nfunction get_best_solution(soln)\n    best = soln[1]\n    for s in soln\n        if f(s) < f(best)\n            best = s\n        end\n    end\n    return best\nend\n\nheaviside(x::AbstractFloat) = ifelse(x < 0, zero(x), ifelse(x > 0, one(x), oftype(x,0.5)))\n\nfunction generate_new_population(population; pa=0.25)\n    new_population=SortedDict(Dict{Float64, Float64}())\n    for (key, value) in population\n        new_value = value + heaviside(pa - rand()) * (rand(population)[2] - rand(population)[2])\n        new_population[f(new_value)] = new_value\n    end\n    return new_population\nend\n\n\n\nfunction initialize_population(total)\n    population = SortedDict(Dict{Float64,Float64}())\n    for i=1:total\n        soln = rand(Float64)\n        population[f(soln)] = soln\n    end\n    return population\nend\n\n\nfunction cuckoo_search(f;total_cuckoos=25,pa = 0.25,α=0.01, λ=0.5, MaxGenerations = 15)\n    cuckoos = initialize_population(total_cuckoos)\n    println(\"Initial population of Cuckoos: \", length(cuckoos))\n    L = Levy(λ)\n    best = nothing\n    t=1\n    while t < MaxGenerations\n        r_cuckoo = rand(cuckoos)\n        new_best = r_cuckoo[2] + α * rand(L)\n        if (f(new_best) < r_cuckoo[2])\n            best = new_best\n        end\n        #\n        cuckoos = filter_best_solutions(cuckoos, pa=pa)\n        println(\"After FILTER Total Cuckoos: \", length(cuckoos))\n        cuckoos = generate_new_population(cuckoos, pa=pa)\n        best = first(cuckoos)[2]\n        println(\"Current Best: \", best)\n        println(\"Total Cuckoos: \", length(cuckoos))\n        t = t +1\n    end\n    return best\nend\n\n\nglobal_minimum=cuckoo_search(f)\n\nprintln(\"Final Global Minimum: \", global_minimum)\n", "meta": {"hexsha": "b27e3ee548ed9d6d20b8cad522be617b08417ab2", "size": 2330, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CuckooSearch.jl", "max_stars_repo_name": "amir1m/bio-inspired", "max_stars_repo_head_hexsha": "ca965bf83bcc5a1935d80bcc7cb9b68a85ab115b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CuckooSearch.jl", "max_issues_repo_name": "amir1m/bio-inspired", "max_issues_repo_head_hexsha": "ca965bf83bcc5a1935d80bcc7cb9b68a85ab115b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CuckooSearch.jl", "max_forks_repo_name": "amir1m/bio-inspired", "max_forks_repo_head_hexsha": "ca965bf83bcc5a1935d80bcc7cb9b68a85ab115b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7380952381, "max_line_length": 122, "alphanum_fraction": 0.6274678112, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.7911147702653832}}
{"text": "using Symata\nusing Test\n\n@sym begin\n  LagrangePolynomial(xi_, yi_) := Module([N, sum, num, den],\n    begin\n      N = Length(xi)\n      sum = 0\n      For( i=1, i <= N, Increment(i),\n        begin\n          num = 1.0\n          den = 1.0\n          For( j=1, j <= N, Increment(j),\n            begin\n              num = If(j != i, num = num * (x-xi[j]), num)\n              den = If(j != i, den = den * (xi[i]-xi[j]), den)\n            end\n          )\n          sum = sum + yi[i] * num/den\n        end\n      ),\n      Return(Simplify(sum))\n    end\n  )\nend\n\n@sym begin\n  CollocationWeightedResidualMethod(xi_, yi_, doprint_) := Module([Y, R],\n    begin\n      Y(x_) := LagrangePolynomial(xi, yi)\n      If(doprint, Println(\"\\nY(x) = \", Y(x), \"\\n\"))\n      #\n      # Can be formulated as ytile(x) = F(x) + C1(a) * Ψ(x)\n      #\n      # F(x_) := 2*x^2 - x\n      # C(a_) := -4a\n      # Ψ(x_) := x^2 - x\n      #\n      #Y(x_) := F(x) + C(a)*Ψ(x)\n      #\n      R(x_) = Simplify(D(Y(x), x, 2) - 3*x - 4*Y(x))\n      R(x_) = Simplify(R(x) ./ (a => -C1/4))\n      If(doprint, Println(\"R(x) = \", R(x), \"\\n\"))\n      Return(R(x))\n    end\n  )\nend\n\nfunction wrm(x1,y1, doprint=true)\n    setsymata(:xin, List(x1...))\n    setsymata(:yin, List(y1...))\n    setsymata(:doprint, doprint ? true : false)\n    #symtranseval(Meta.parse(\"Compile(Evaluate(CollocationWeightedResidualMethod(xin,yin,doprint)))\"))\n    symparseeval(\"Compile(Evaluate(CollocationWeightedResidualMethod(xin,yin,doprint)))\")\nend\n\nprintln(\"\\nExample 7.13: y'' = 3x + 4y, y(0)=0, y(1)=1\")\nprintln(\"Residual for Weighted Residual Method using 1 point Lagragian Polynomial\\n\")\n\n#\n# A consequence of the Julia function based approach is that Y(x) and R(x) are local\n# to the Symata function and are not available for examination, e.g. @sym R(x)\n#\n\nlp_eq = @sym ToString(LagrangePolynomial([0.0,0.5,1.0], [0.0,a,1.0]))\nprintln(lp_eq)\n@test lp_eq == \"x*(-1.0 + 2.0*x + (-4.0)*a*(-1.0 + x))\"\nwrm_eq = @sym ToString(CollocationWeightedResidualMethod([0.0,0.5,1.0], [0.0,a,1.0], false))\nprintln(wrm_eq)\n@test wrm_eq == \"4.0 + 2.0*C1 - 3x - 4x*(-1.0 + 2.0*x + C1*(-1.0 + x))\"\n\n#\n# Another consideration is that below yt is yt(C1::Any, x::Any)\n#\n\nyt = wrm([0.0,0.5,1.0], [0.0,:a,1.0], true)\n\nprintln(\"( Example 7.13 gives: R = -4x^2*(2 + C1) + x*(1 + 4C1) + 2*(2 + C1) )\", \"\\n\")\n\n\"\n```\nThe function ytilde(x, C1) contains the 1-point Weighted Residual Method\npolynomial with parameter C1.\n```\nArguments to ytilde(x, C1):\n\nx::Float64          : x value\\n\nC1::Float64         : Weighted Residual Method constant.\n\nC1 can be estimated by e.g. collocation, subdomain, least squares or Galerkin.\nSee examples 7.15 through 7.18 and Fig.7.14.jl\n\"\nytilde(x, C1) = yt(C1, x)\nprintln(\"ytilde(1.0, 0.0) = $(ytilde(1.0, 0.0))\")\n@test ytilde(1.0, 0.0) == -3.0\n\nprintln(\"ytilde(0.0, 1.0) = $(ytilde(0.0, 1.0))\")\n@test ytilde(0.0, 1.0) == 6.0\n\n#\n# Tests with @symExpr\n#\n\nsetsymata(:x1, [0.0,0.5,1.0])\nwrm_1pt_col(x, C1) = @symExpr CollocationWeightedResidualMethod(x1, [0.0,a,1.0], false)\n\n#\n# The order of the arguments can be chosen. This is nice.\n#\n\nprintln(\"wrm_1pt_col(1.0, 0.0) = $(wrm_1pt_col(1.0, 0.0))\")\n@test wrm_1pt_col(1.0, 0.0) == ytilde(1.0, 0.0)\n\n#\n# Like @sym, I think @symExpr is not intended to return an expression from a Julia function.\n#\n\nfunction wrm_1(xin, xinval, C1inval)\n  setsymata(:x1, xin)\n  f(x, C1) = @symExpr CollocationWeightedResidualMethod(x1, [0.0,a,1.0], false)\n  f(xinval, C1inval)\nend\n\n@test wrm_1([0.0,0.5,1.0], 1.0, 0.0) == ytilde(1.0, 0.0)\n\n", "meta": {"hexsha": "adb48ceee7e4d1fd81a678ac6ce46e275488cae7", "size": 3491, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ch07_jl_sym_fnc_ex.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "test/ch07_jl_sym_fnc_ex.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "test/ch07_jl_sym_fnc_ex.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 27.7063492063, "max_line_length": 102, "alphanum_fraction": 0.5774849613, "num_tokens": 1378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.8757869900269366, "lm_q1q2_score": 0.7910933212378877}}
{"text": "# ---\n# title: 62. Unique Paths\n# id: problem62\n# author: AquaIndigo\n# date: 2020-12-09\n# difficulty: Medium\n# categories: Array, Dynamic Programming\n# link: <https://leetcode.com/problems/unique-paths/description/>\n# hidden: true\n# ---\n# \n# A robot is located at the top-left corner of a `m x n` grid (marked 'Start' in\n# the diagram below).\n# \n# The robot can only move either down or right at any point in time. The robot\n# is trying to reach the bottom-right corner of the grid (marked 'Finish' in the\n# diagram below).\n# \n# How many possible unique paths are there?\n# \n# \n# \n# **Example 1:**\n# \n# ![](https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png)\n# \n#     \n#     \n#     Input: m = 3, n = 7\n#     Output: 28\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: m = 3, n = 2\n#     Output: 3\n#     Explanation:\n#     From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:\n#     1. Right -> Down -> Down\n#     2. Down -> Down -> Right\n#     3. Down -> Right -> Down\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: m = 7, n = 3\n#     Output: 28\n#     \n# \n# **Example 4:**\n# \n#     \n#     \n#     Input: m = 3, n = 3\n#     Output: 6\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= m, n <= 100`\n#   * It's guaranteed that the answer will be less than or equal to `2 * 109`.\n# \n# \n## @lc code=start\nusing LeetCode\n\nunique_paths(m::Int, n::Int) = binomial(m + n - 2, n - 1)\n## @lc code=end\n", "meta": {"hexsha": "55fa34f39e43c652140211981e3de7e5ce5dae87", "size": 1450, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/62.unique-paths.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/62.unique-paths.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/62.unique-paths.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 19.3333333333, "max_line_length": 93, "alphanum_fraction": 0.5579310345, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8705972566572504, "lm_q1q2_score": 0.7910402527280371}}
{"text": "\"\"\"\n    create_upper_tri(vec,V)\n\nCreate an upper triangluar matrix from a vector of the form [12, ... 1V,23,...(V-1)V]\nto the form [0 12 13  ... 1V]\n            [0 0  23  ... 2V]\n            [...............]\n            [0 0  0...(V-1)V]\n# Arguments\n- `vec`: vector containing values to put into the upper triangluar matrix\n- `V`  : dimension of output matrix\n\n# Returns\nUpper triangluar matrix containing values of `vec`\n\"\"\"\nfunction create_upper_tri(vec::Array{T,1},V::Int64) where T <: Union{Int64,Float64}\n    mat = zeros(T,V,V)\n    vec2 = deepcopy(vec)\n    for k = 1:V\n        for l = k+1:V\n            mat[k,l] = popfirst!(vec2)\n        end\n    end\n    return mat\nend\n\n\"\"\"\n    upper_triangle(matrix)\n\nReturn the upper triangle (without the diagonal) of the matrix as a vector\n\n# Arguments\n- `matrix`: matrix of which to capture the upper triangle\n\n# Returns\nVector of upper triangluar section of `matrix`\n\"\"\"\nfunction upper_triangle(matrix::Array{T,2}) where T <: Union{Int64,Float64}\n    k = 1\n    ret = zeros(T,convert(Int64, round(size(matrix,1)*(size(matrix,2) - 1)/2)))\n    for i in 1:size(matrix,1)\n        for j in (i+1):size(matrix,2)\n            ret[k] = matrix[i,j]\n            k = k + 1\n        end\n    end\n    return ret\nend\n", "meta": {"hexsha": "aaed584071dc8ad6777d1a80d1e372e4b25f494e", "size": 1244, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "dmbates/BayesianNetworkRegression.jl", "max_stars_repo_head_hexsha": "9410541f95a2451cd49f9ffa37c7bf5e8209908f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "dmbates/BayesianNetworkRegression.jl", "max_issues_repo_head_hexsha": "9410541f95a2451cd49f9ffa37c7bf5e8209908f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "dmbates/BayesianNetworkRegression.jl", "max_forks_repo_head_hexsha": "9410541f95a2451cd49f9ffa37c7bf5e8209908f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.387755102, "max_line_length": 85, "alphanum_fraction": 0.595659164, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.8840392939666336, "lm_q1q2_score": 0.7910290528226445}}
{"text": "using RadauBVP, Plots\npyplot()\n\nProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n\n  if !isdefined(Main, :bc!)\n    function bc!(y0, yn, r)\n      r[1] = y0[1] - 0.0\n      r[2] = yn[2] - (-1.0)\n    end\n\n    function dbc!(y0, yn, jac)\n      jac[:,:] = 0.0\n      jac[1,1] = 1.0\n      jac[2,4] = 1.0\n    end\n\n    function odeeq!(t, y, dydt)\n      dydt[1] = y[2]\n      dydt[2] = -y[1]\n    end\n\n    function dodeeq!(t, y, jac)\n      jac[1,1] = 0.0\n      jac[1,2] = 1.0\n      jac[2,1] = -1.0\n      jac[2,2] = 0.0\n    end\n  end\n\n  nt = 5\n  const y0 = zeros(Float64, (2, 3*(nt-1)+1))\n\n  for n=1:3*(nt-1)+1\n    y0[:, n] = [0.0, 1.0]\n  end\n\n  @time (conv, ttot, ytot, result) = \n    RadauBVP.radau3(bc!, odeeq!, dbc!, dodeeq!, y0, 0.0, convert(Float64, π))\n\n  result |> display\n  \n  yres = ytot[1,:]\n  vres = ytot[2,:]\n\n  let t = linspace(0.0, π, 100)\n    \n    global possol = sin.(t)\n    global vsol = cos.(t)\n    global ysol = Array(Float64, 2*100)\n    \n    ysol[1:2:end-1] = possol\n    ysol[2:2:end] = vsol\n  end\n\n  p1 = plot(\n  linspace(0.0, π, 100),\n  possol,\n  title = \"Coordinate (n = $nt)\",\n  label = \"Exact\")\n  plot!(ttot, yres, label = \"Numerical\", linetype = :scatter)\n\n\n  p2 = plot(\n  linspace(0.0, π, 100),\n  vsol,\n  title = \"Velocity (n = $nt)\",\n  label = \"Exact\")\n  plot!(ttot, vres, label = \"Numerical\", linetype = :scatter)\n\n  plot(p1,p2)\n  savefig(\"radau.png\")\n  plot(p1,p2)\n\nend", "meta": {"hexsha": "470e3d3024a8f5d7f90be86efd9d6ca1cd30e5d1", "size": 1379, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/radauIIA.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "test/radauIIA.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "test/radauIIA.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 18.1447368421, "max_line_length": 77, "alphanum_fraction": 0.515591008, "num_tokens": 604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7909825770448405}}
{"text": "\"LU Decomposition\"\nmodule LUDecomposition\n\nusing LinearAlgebra: dot\n\nfunction get_n(A::Matrix)::Int\n    (n_r, n_c) = size(A)\n    @assert n_r == n_c \"Input matrix is not square\"\n    n_r\nend\n\n\"Row permutation\"\nstruct Permutation\n    indices::Vector{Int}\n    n_pivots::Int\nend\n\nraw\"\"\"\nLU factorization with partial pivoting.\n\n`A` is changed to $(L - E) + U$ s.t. $P A = L U$.\n\"\"\"\nfunction lu_decompose!(A::Matrix{<:AbstractFloat})::Union{Permutation, Nothing}\n    n = get_n(A)\n    p = collect(1:n)\n    n_pivots = n  # for computing the determinant\n\n    @inbounds for c in 1:n\n        # Using ArrayView here doesn't help.\n        # See https://github.com/JuliaLang/julia/issues/19198#issuecomment-257986870.\n        (max_value, c_max) = findmax(abs.(A[c:n, c]))\n        if max_value < eps()\n            return nothing\n        end\n        c_max += c - 1\n\n        if c_max != c\n            @views A[[c, c_max], :] .= A[[c_max, c], :]\n            p[c], p[c_max] = p[c_max], p[c]\n            n_pivots += 1\n        end\n\n        # `A[r, c]` is assigned to 0 by `A[r, c] -= A[c, c] * (A[r, c] / A[c, c])`, so the element\n        # in `L` is `(A[r, c] / A[c, c])`.\n        rg = (c + 1):n;\n        @views A[rg, c] /= A[c, c]\n        @. @views A[rg, rg] -= A[rg, c] * A[c, rg]'\n    end\n\n    Permutation(p, n_pivots)\nend\n\nraw\"\"\"\nSolves $A x = b$.\n\n**Precondition**: `LU` is obtained by appling `lu_decompose!` on `A`.\n\"\"\"\nfunction lu_solve(LU::Matrix{T}, perm::Permutation, b::Vector{T})::Vector{T} where T<:AbstractFloat\n    n = get_n(LU)\n\n    # transforms `b`, stored in `x`\n    x = b[perm.indices]\n    for r in 1:n\n        @views x[r] -= dot(LU[r, 1:(r - 1)], x[1:(r - 1)])\n    end\n\n    # computes `x`\n    for r in n:-1:1\n        p = @views dot(LU[r, (r + 1):n], x[(r + 1):n])\n        x[r] = (x[r] - p) / LU[r, r]\n    end\n\n    x\nend\n\nfunction lu_det(LU::Matrix{T}, n_pivots::Int)::T where T<:AbstractFloat\n    n = get_n(LU)\n    det = foldl(*, LU[i, i] for i in 1:n)\n    if iseven(n - n_pivots)\n        det\n    else\n        -det\n    end\nend\n\n#===== Unit Tests =====#\nusing Test\n\nusing LinearAlgebra: Diagonal, I, LowerTriangular, UpperTriangular\nusing LinearAlgebra: det  # for reference implementation\nusing Random: seed!\n\n@testset \"LU decomposition\" begin\n    n = 32\n    seed!()\n    A = rand(n, n)\n    b = rand(n)\n\n    LU = copy(A)\n    perm = lu_decompose!(LU)\n    if perm != nothing\n        L = LowerTriangular(LU) - Diagonal(LU) + I\n        U = UpperTriangular(LU)\n        @test L * U ≈ A[perm.indices[:], :]\n\n        @test lu_det(LU, perm.n_pivots) ≈ det(A)\n\n        x = lu_solve(LU, perm, b)\n        @test A * x ≈ b\n    end\nend\n\nend # module\n", "meta": {"hexsha": "d5b9ed845e21e0fff4109bd3002b566207c20d1c", "size": 2635, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LUDecomposition/src/LUDecomposition.jl", "max_stars_repo_name": "gyk/TrivialSolutions", "max_stars_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T05:51:37.000Z", "max_issues_repo_path": "LUDecomposition/src/LUDecomposition.jl", "max_issues_repo_name": "gyk/TrivialSolutions", "max_issues_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LUDecomposition/src/LUDecomposition.jl", "max_forks_repo_name": "gyk/TrivialSolutions", "max_forks_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1140350877, "max_line_length": 99, "alphanum_fraction": 0.5438330171, "num_tokens": 912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317888, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7909825736318783}}
{"text": "# Laplacian Eigenmaps\n# -------------------\n# Laplacian Eigenmaps for Dimensionality Reduction and Data Representation,\n# M. Belkin, P. Niyogi, Neural Computation, June 2003; 15 (6):1373-1396\n\n\"\"\"\n    LEM{NN <: AbstractNearestNeighbors, T <: Real} <: AbstractDimensionalityReduction\n\nThe `LEM` type represents a Laplacian eigenmaps model constructed for `T` type data with a help of the `NN` nearest neighbor algorithm.\n\"\"\"\nstruct LEM{NN <: AbstractNearestNeighbors, T <: Real} <: AbstractDimensionalityReduction\n    λ::AbstractVector{T}\n    ɛ::T\n    proj::Projection{T}\n    nearestneighbors::NN\n    component::AbstractVector{Int}\nend\n\n## properties\noutdim(R::LEM) = size(R.proj, 1)\neigvals(R::LEM) = R.λ\nneighbors(R::LEM) = R.nearestneighbors.k\nvertices(R::LEM) = R.component\n\n## show\nsummary(io::IO, R::LEM) = print(io, \"Laplacian Eigenmaps(outdim = $(outdim(R)), neighbors = $(neighbors(R)), ɛ = $(R.ɛ))\")\n\n## interface functions\n\"\"\"\n    fit(LEM, data; k=12, maxoutdim=2, ɛ=1.0, nntype=BruteForce)\n\nFit a Laplacian eigenmaps model to `data`.\n\n# Arguments\n* `data`: a matrix of observations. Each column of `data` is an observation.\n\n# Keyword arguments\n* `k`: a number of nearest neighbors for construction of local subspace representation\n* `maxoutdim`: a dimension of the reduced space.\n* `nntype`: a nearest neighbor construction class (derived from `AbstractNearestNeighbors`)\n* `ɛ`: a Gaussian kernel variance (the scale parameter)\n\n# Examples\n```julia\nM = fit(LEM, rand(3,100)) # construct Laplacian eigenmaps model\nR = transform(M)          # perform dimensionality reduction\n```\n\"\"\"\nfunction fit(::Type{LEM}, X::AbstractMatrix{T};\n        k::Int=12, maxoutdim::Int=2, ɛ::Real=1.0, nntype=BruteForce) where {T<:Real}\n    # Construct NN graph\n    NN = fit(nntype, X, k)\n    D, E = knn(NN, X)\n    G, C = largest_component(SimpleWeightedGraph(adjmat(D,E)))\n\n    # Compute weights\n    W = weights(G)\n    W .^= 2\n    W ./= maximum(W)\n\n    W[W .> eps(T)] = exp.(-W[W .> eps(T)] ./ convert(T,ɛ))\n    D = spdiagm(0=>vec(sum(W, dims=2)))\n    L = D - W\n\n    λ, V = decompose(L, D, maxoutdim)\n    return LEM{nntype, T}(λ, ɛ, transpose(V), NN, C)\nend\n\n\"\"\"\n    transform(R::LEM)\n\nTransforms the data fitted to the Laplacian eigenmaps model `R` into a reduced space representation.\n\"\"\"\ntransform(R::LEM) = R.proj\n", "meta": {"hexsha": "0978db80901bda4e86d66c8c40fbd0ddcc35edf6", "size": 2309, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lem.jl", "max_stars_repo_name": "yha/ManifoldLearning.jl", "max_stars_repo_head_hexsha": "29a97cce829f0ab8fb172ac27ddfcfff446596a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71, "max_stars_repo_stars_event_min_datetime": "2015-03-15T17:34:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T19:17:06.000Z", "max_issues_repo_path": "src/lem.jl", "max_issues_repo_name": "yha/ManifoldLearning.jl", "max_issues_repo_head_hexsha": "29a97cce829f0ab8fb172ac27ddfcfff446596a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2015-02-13T17:18:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T21:36:26.000Z", "max_forks_repo_path": "src/lem.jl", "max_forks_repo_name": "yha/ManifoldLearning.jl", "max_forks_repo_head_hexsha": "29a97cce829f0ab8fb172ac27ddfcfff446596a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2015-06-17T17:56:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T21:45:13.000Z", "avg_line_length": 30.7866666667, "max_line_length": 135, "alphanum_fraction": 0.6704200953, "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7909825701573767}}
{"text": "using Makie \nusing GeometryBasics\n\nouttrig = Triangle(\n    Point(0., 0.), \n    Point(1., 0.),\n    Point(0.5, 1.)\n)\n\nintrig = Triangle(\n    Point(rand(2)...), \n    Point(rand(2)...), \n    Point(rand(2)...)\n)\n\nfig = Figure() \nax1 = Axis(fig[1, 1])\nax2 = Axis(fig[1, 2])\nmesh!(ax1, outtrig.points)\nmesh!(ax2, intrig.points)\nusing GeometryBasics \nusing Makie \nusing FractalTools \n\nusing Random \nRandom.seed!(0)\n\n\n# Define the triangle \ntrig = Triangle(\n    Point(-1., -1.), \n    Point(1., -1.), \n    Point(0., 2)\n)\n\n# Get valid points in the domain \npnts2d = disperse(trig, 10)\n\n# Define function \nf(x, y) = x^2 + y^2 \n\n# Evaluate function \npnts3d = [Point(pnt[1], pnt[2], f(pnt[1], pnt[2])) for pnt in pnts2d]  # Interpolation data \n\n# Check transformations \n_, msh3 = triangulate(pnts3d)\nouttrig = findouttriangle(pnts3d)\nouttrigpnts2d = project(outtrig.points)\n\ni = Node(39) \nttrig = @lift(msh3[$i])\n\nttrigpnts2d = lift(ttrig) do ttrig \n    project(ttrig.points)\nend \n\nmtrig = lift(ttrig) do ttrig \n    tfm = gettransform(outtrig, ttrig, 0.01)\n    L(x) = tfm.A[1:2, 1:2] * x + tfm.b[1:2]\n    Triangle(map(pnt -> Point(L(pnt)...), outtrigpnts2d)...)\nend \n\nfig = Figure() \nls = LScene(fig[1, 1])\nbuttongrid = fig[1, 2] =  GridLayout(tellheight=false)\nbutton1 = buttongrid[1, 1] = Button(fig, label = \"Inc\")\nbutton2 = buttongrid[2, 1] = Button(fig, label = \"Dec\")\nlabel = buttongrid[3, 1] = Label(fig, \"Tri idx:$(string(i[]))\")\nmesh!(ls, outtrig)\nwireframe!(outtrigpnts2d, color=:black, linewidth=3)\nmesh!(ttrig, color=:blue)\nwireframe!(ttrigpnts2d, color=:blue, linewidth=3)\nmesh!(mtrig, color=:green)\n\non(button1.clicks) do n \n    i[] += 1\n    label.text[] = \"Tri idx: \" * string(i[])\nend \n\non(button2.clicks) do n \n    i[] -= 1\n    label.text[] = \"Tri idx: \" * string(i[])\nend \n\ndisplay(fig) \n\n# # Interpolate the data\n# itp = interpolate(pnts3d, maxiters=4)\n\n# # Evaluat the itp \n# tpnt = pnts2d\n# # tpnt = [getpoint(trig) for i in 1 : 500]\n# val = map(pnt -> itp(pnt...), tpnt) \n# rval =  map(pnt -> f(pnt...), tpnt) \n# relerr = abs.(val - rval) ./ abs.(rval) * 100\n\n# @show findall(isnan, val) \n# @show sum(relerr .≥ 1)\n\n\n# # Plots \n# tess, mesh3 = triangulate(pnts3d)\n# mesh2 = GeometryBasics.Mesh(project(coordinates(mesh3)), faces(mesh3))\n# fig, ax, plt = scatter(pnts3d, color=:red, markersize=20)\n# wireframe!(trig.points, linewidth=3)\n# wireframe!(mesh2) \n# scatter!(pnts2d, markersize=8, color=:black)\n# scatter!(tpnt, markersize=8, color=:green)\n# # mesh!(mesh3, color=first.(mesh3.position))\n# wireframe!(mesh3, color=:black)\n\n# # Test point \n# tpnt = getpoint(trig)      \n# idx = tess.find_simplex(tpnt)[1] + 1  \n# scatter!(tpnt, markersize=30, color=:orange)\n# mesh!(mesh2[idx])\n\n# tpnt2 = (trig.points[1] + trig.points[2]) / 2 \n# idx = tess.find_simplex(tpnt2)[1] + 1  \n# scatter!(tpnt2, markersize=30, color=:blue)\n# mesh!(mesh2[idx], color=:green)\n\n# tpnt3 = pnts2d[40]\n# idx = tess.find_simplex(tpnt3)[1] + 1  \n# scatter!(tpnt3, markersize=30, color=:green)\n# mesh!(mesh2[idx], color=:black)\n\n# tpnt4 = pnts2d[39]\n# scatter!(tpnt4, markersize=30, color=:blue)\n\n# tpnt5 = (pnts2d[40] + pnts2d[39]) / 2 \n# scatter!(tpnt5, markersize=30, color=:blue)\n# idx = tess.find_simplex(tpnt5)[1] + 1  \n# mesh!(mesh2[idx])\n\n# display(fig) ", "meta": {"hexsha": "9e334a95149fc4afb57a57f53a7a2acb6781ca9c", "size": 3243, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/stash/mesh/stash/test.jl", "max_stars_repo_name": "zekeriyasari/FractalTools.jl", "max_stars_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-08T12:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T12:50:16.000Z", "max_issues_repo_path": "example/stash/mesh/stash/test.jl", "max_issues_repo_name": "zekeriyasari/FractalTools.jl", "max_issues_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-09-05T18:22:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T10:09:46.000Z", "max_forks_repo_path": "example/stash/mesh/stash/test.jl", "max_forks_repo_name": "zekeriyasari/FractalTools.jl", "max_forks_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8455882353, "max_line_length": 92, "alphanum_fraction": 0.6342892384, "num_tokens": 1217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7909825684355108}}
{"text": "# #######################################\n# Example 9.8 and 10.24 Grouped Multinomial Data of\n# Robert, C. P., & Casella, G. (2010). Monte Carlo statistical methods (2. ed., softcover reprint of the hardcover 2. ed. 2004). New York, NY: Springer.\n# #######################################\n\nusing Distributions\nusing Plots\nusing LaTeXStrings\n\n# configure\na = [0.06, 0.14, 0.11, 0.09]\nb = [0.17, 0.24, 0.19, 0.20]\nx = [9, 15, 12, 7, 8]\n\n# normal gibbs\nfunction gibbs(M = 1000)\n    Z = ones(M, 4)\n    Params = ones(M, 2)\n    Eparams = ones(M, 2)\n    # prior\n    alpha = [1/2, 1/2, 1/2]\n    # initial \n    mu = 0.1\n    eta = 0.1\n    for m in 1:M\n        # sample zi\n        zi = ones(4)\n        for i = 1:2\n            aimu = a[i] * mu\n            zi[i] = rand(Binomial(x[i], aimu / (aimu + b[i])))\n        end\n        for i = 3:4\n            aieta = a[i] * eta\n            zi[i] = rand(Binomial(x[i], aieta / (aieta + b[i])))\n        end\n        # sample mu eta \n        mu, eta, = rand(Dirichlet([ zi[1] + zi[2] + alpha[1], zi[3] + zi[4] + alpha[2], x[5] + alpha[3] ]))\n        # store\n        Z[m, :] = zi\n        Params[m, :] = [mu, eta]\n        #Eparams[m, :] = mean(Params[1:m, :], dims = 1)\n    end\n    Eparams[:, 1] = cumsum(Params[:, 1]) ./ Array(1:M)\n    Eparams[:, 2] = cumsum(Params[:, 2]) ./ Array(1:M)\n    return Z, Params, Eparams\nend\nZ, Params, Eparams = gibbs(10000)\n\nplot(Eparams[:,1], label = L\"\\mu\")\nplot!(Eparams[:,2], label = L\"\\eta\")\nsavefig(\"gibbs.png\")\n\n# Metropolization\nfunction Metrogibbs(M = 1000)\n    Z = ones(Int, M, 4)\n    Params = ones(M, 2)\n    Eparams = ones(M, 2)\n    # prior\n    alpha = [1/2, 1/2, 1/2]\n    # initial \n    mu = 0.1\n    eta = 0.1\n    for m in 1:M\n        # sample zi\n        zi = ones(Int, 4)\n        for i = 1:4\n            if i == 1 || i == 2\n                aimu = a[i] * mu\n            else\n                aimu = a[i] * eta\n            end\n            p1 = aimu / (aimu + b[i])\n            p2 = 1 - p1 \n            while true\n                zi[i] = rand(Binomial(x[i], p1))\n                if m == 1 || zi[i] != Z[m-1, i] # short-circuiting boolean \n                    break\n                end\n            end\n            # accept or not \n            if m == 1\n                rho = 1.1\n            else\n                num1 = 1 - binomial(Z[m-1, i], x[i]) * p1^Z[m-1,i] * p2^(x[i] - Z[m-1, i])\n                num2 = 1 - binomial(zi[i], x[i]) * p1^zi[i] * p2^(x[i] - zi[i])\n                rho = num1 / num2\n            end\n            if rand() > rho\n                zi[i] = Z[m-1, i]\n            end\n            \n        end\n        # sample mu eta \n        mu, eta, = rand(Dirichlet([ zi[1] + zi[2] + alpha[1], zi[3] + zi[4] + alpha[2], x[5] + alpha[3] ]))\n        # store\n        Z[m, :] = zi\n        Params[m, :] = [mu, eta]\n        #Eparams[m, :] = mean(Params[1:m, :], dims = 1)\n    end\n    Eparams[:, 1] = cumsum(Params[:, 1]) ./ Array(1:M)\n    Eparams[:, 2] = cumsum(Params[:, 2]) ./ Array(1:M)\n    return Z, Params, Eparams\nend\n\nZ, Params, Eparams = Metrogibbs(10000)\nplot(Eparams[:,1], label = L\"\\mu\")\nplot!(Eparams[:,2], label = L\"\\eta\")\nsavefig(\"metrogibbs.png\")", "meta": {"hexsha": "8d6794a578777419f06d7cceb75a284dd1016bab", "size": 3132, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Gibbs/GMdata/grouped-multinomial.jl", "max_stars_repo_name": "szcf-weiya/MCMC", "max_stars_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-07-19T12:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T08:06:50.000Z", "max_issues_repo_path": "Gibbs/GMdata/grouped-multinomial.jl", "max_issues_repo_name": "szcf-weiya/MCMC", "max_issues_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-02-03T15:08:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-05T15:41:39.000Z", "max_forks_repo_path": "Gibbs/GMdata/grouped-multinomial.jl", "max_forks_repo_name": "szcf-weiya/MCMC", "max_forks_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-07-19T12:50:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T08:06:52.000Z", "avg_line_length": 29.0, "max_line_length": 152, "alphanum_fraction": 0.4367816092, "num_tokens": 1129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7909825615172774}}
{"text": "\"\"\"\n`sort_by_size(list)` returns a sorted copy of `list`\nin which the elements are sorted by the `length` function\n(from smallest to largest).\n\"\"\"\nfunction sort_by_size(list::Array)\n    sort(list,lt=((x,y) -> length(x) < length(y)))\nend\n\nimport Base.sqrt\n\nfunction weave(c::Array{Int,1})::Array{Int,1}\n    nc = length(c)\n    if nc%2 == 0\n        error(\"Attempting to weave $c, an even-length cycle, with itself\")\n    end\n    half = Int((nc+1)/2)\n    result = zeros(Int,nc)\n    j = 1  # index into c\n    jj = 1  # index into result\n    while j <= nc\n        result[j] = c[jj]\n        j += 1\n        jj = (jj+half) % nc\n        if jj == 0\n            jj = nc\n        end\n    end\n    return result\nend\n\nfunction weave(c1::Array{Int,1}, c2::Array{Int,1})::Array{Int,1}\n    n1 = length(c1)\n    n2 = length(c2)\n    @assert n1==n2 \"Cycles $c1 and $c2 have different lengths\"\n    @assert n1%2==0 \"Cycles must have even length to be weaved together\"\n\n    result = zeros(Int,2n1)\n    for j=1:n1\n        result[2j-1]=c1[j]\n        result[2j]=c2[j]\n    end\n    return result\nend\n\"\"\"\n`sqrt(p::Permutation)` returns a `Permutation` `q` such that\n`q*q==p`. Note: There may be other square roots besides the one\nreturned. If `p` does not have a square root, an error is thrown.\n\"\"\"\nfunction sqrt(p::Permutation)::Permutation\n    err_msg = \"This permutation does not have a square root\"\n    n = length(p)\n    clist = sort_by_size(cycles(p))\n    nc = length(clist)\n    result = zeros(Int,n)\n\n    idx = 1\n    while idx <= nc\n        cyc = clist[idx]  # next cycle to process\n        m = length(cyc)\n        if m%2 == 1   # an odd cycle\n            tmp = weave(cyc)\n            for j=1:m-1\n                result[tmp[j]] = tmp[j+1]\n            end\n            result[tmp[m]] = tmp[1]\n            idx += 1\n        else\n            if idx == nc\n                error(err_msg)\n            end\n            cyc2 = clist[idx+1]\n            if length(cyc2) != length(cyc)\n                error(err_msg)\n            end\n            tmp = weave(cyc,cyc2)\n            for j=1:2m-1\n                result[tmp[j]] = tmp[j+1]\n            end\n            result[tmp[2m]] = tmp[1]\n            idx += 2\n        end\n    end\n    return Permutation(result)\nend\n\n√(p::Permutation) = sqrt(p)\n", "meta": {"hexsha": "94bf92cb8a5864fa642fbfecb7c202362a1fe2c5", "size": 2251, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sqrt.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Permutations.jl-2ae35dd2-176d-5d53-8349-f30d82d94d4f", "max_stars_repo_head_hexsha": "f21831634d7da115132d054efa63a0b01af953c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-13T00:01:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-13T00:01:05.000Z", "max_issues_repo_path": "src/sqrt.jl", "max_issues_repo_name": "cscherrer/Permutations.jl", "max_issues_repo_head_hexsha": "89487f498c6de89a6e694cdab8d83a6f2d06dd8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sqrt.jl", "max_forks_repo_name": "cscherrer/Permutations.jl", "max_forks_repo_head_hexsha": "89487f498c6de89a6e694cdab8d83a6f2d06dd8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5795454545, "max_line_length": 74, "alphanum_fraction": 0.5344291426, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.8633916222765627, "lm_q1q2_score": 0.7909613733701437}}
{"text": "# ------------------------------------------------------------------------------------------\n# # Creating a dynamical system\n#\n# Topics:\n# * What *is* a dynamical system in the context of **DynamicalSystems.jl**?\n# * How can we define a discrete or continuous system?\n# * What are the differences in handling large and small systems?\n#     * Handy Dandy definition table!\n# * Comment on DifferentialEquations.jl\n# * Docstrings\n#\n# ---\n#\n# # Dynamical System\n#\n# A \"dynamical system\" is a law that describes how some variables should evolve in time.\n# This law is described by the \"equations of motion\" function $\\vec{f}$.\n#\n# There are two types of dynamical systems (in our case):\n#\n# 1. One is called a map, where time is a discrete quantity (like \"steps\" or \"generations\").\n# The equations of motion then look something like $\\vec{u}_{n+1} = \\vec{f}(\\vec{u}_n, p,\n# n)$ where $n$ is an integer and $p$ are the parameters of the system.\n#\n# 2. The other type is called an Ordinary Differential Equation (ODE), where time is a\n# continuous quantity. Then, the equations of motion give the time derivatives of the\n# variables: $\\frac{d\\vec{u}}{dt} = \\vec{f}(\\vec{u}, p, t)$.\n#\n# In both cases $\\vec{u}$ is the state of the system, a vector of the variables that define\n# the system. For example, $\\vec{u}$ may be defined as $(x, y, z)$, or as $(\\theta, I)$, or\n# as $(V, I, R, C_1, C_2)$, etc.\n#\n# ---\n# \n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# # Creating a simple discrete system\n#\n#\n# For all intents and purposes, a `DynamicalSystem` is a Julia `struct` that contains all\n# the information of a dynamical system:\n# 1. Equations of motion function $\\vec{f}$\n# 3. Initial state.\n# 4. Parameter container (if the equations of motion are parameterized).\n# 2. *Optional* : Jacobian of the equations of motion.\n#\n#\n# For simplicity let's focus on creating a simple discrete chaotic system, the [Hénon\n# map](https://en.wikipedia.org/wiki/H%C3%A9non_map).\n#\n# The constructor we need is:\n#\n# ```julia\n# DiscreteDynamicalSystem(eom, state, p)\n# ```\n#\n# In order to construct a Hénon map, let's discuss the input arguments we need to pass to\n# this constructor!\n#\n# #### 1. Equations of motion\n# The first argument of the above constructor --`eom` -- is a **function** representing the\n# equations of motion.\n#\n# Therefore, the first step in creating a `DynamicalSystem` is to define the equations of\n# motion. For the Hénon map they have the form:\n#\n# $$\n# \\begin{aligned}\n# x_{n+1} &= 1 - ax^2_n+y_n \\\\\n# y_{n+1} & = bx_n\n# \\end{aligned}\n# $$\n#\n# Now we must make a function out of them. There is some strictness when writing this\n# function in Julia. Specifically, it can only be one of two forms: out-of-place (oop) or\n# in-place (iip). Here is how to define it:\n#\n# * **oop** : The `eom` function **must** be in the form `eom(x, p, t) -> SVector`\n#   which means that given a state `x::SVector` and some parameter container\n#   `p` it returns a\n# [`SVector`](http://juliaarrays.github.io/StaticArrays.jl/stable/pages/api.html#SVector-1)\n#   (from the [StaticArrays](https://github.com/JuliaArrays/StaticArrays.jl) module)\n#   containing the next state.\n# * **iip** : The `eom` function **must** be in the form `eom!(xnew, x, p, t)`\n#   which means that given a state `x::Vector` and some parameter container `p`,\n#   it writes in-place the new state in `xnew`.\n#\n# We advise to use **oop** for systems with dimension < 11, and use **iip** otherwise.\n#\n# *If you are familiar with [DifferentialEquations.jl](http://docs.juliadiffeq.org/latest/),\n# then notice that the equations of motion are defined in an identical manner*\n#\n# Because the Hénon map is only 2-dimensional, we follow the advice of the documentation and\n# take advantage of the [`StaticArrays`](https://github.com/JuliaArrays/StaticArrays.jl)\n# module.\n# ------------------------------------------------------------------------------------------\n\nusing DynamicalSystems\nh_eom(x, p, t) = SVector{2}(1.0 - p[1]*x[1]^2 + x[2], p[2]*x[1])\n\n# ------------------------------------------------------------------------------------------\n# * Remember: *both* `p` (for parameters) and `t` (for time) must be included in the\n# equations of motion function, irrespective of whether they are used or not!\n#\n# #### 2. State\n#\n# The second argument for the `DiscreteDynamicalSystem` constructor is a `state`, which\n# represents the initial condition for the system:\n# ------------------------------------------------------------------------------------------\n\nstate = zeros(2) # doesn't matter if we use Vector of SVector for the `state`\n\n# ------------------------------------------------------------------------------------------\n# #### 3. Parameters for our EOM\n#\n# Then, the last argument, `p`, is simply a parameter container.\n# ------------------------------------------------------------------------------------------\n\np = [1.4, 0.3] # p = [a, b] from the equations of motion\n\n# ------------------------------------------------------------------------------------------\n# These 3 things are enough to make a `DynamicalSystem`:\n# ------------------------------------------------------------------------------------------\n\nhenon = DiscreteDynamicalSystem(h_eom, state, p)\n\n# ------------------------------------------------------------------------------------------\n# ## Getting a trajectory\n#\n# Now that we have created the system, the first (and most basic) thing to do is to simply\n# plot its time evolution and see what it looks like.\n#\n# The `trajectory` function is a convenient tool that evolves the system and returns the\n# output at equally spaced time intervals. The call signature is simply:\n#\n# ```julia\n# trajectory(ds::DynamicalSystem, T [, u]; kwargs...)\n# ```\n# which evolves a system for total time `T`, optionally starting from a different state `u`.\n# ------------------------------------------------------------------------------------------\n\n# trajectory from initial condition\ntr = trajectory(henon, 100000)\n\n# trajectory from a different starting point\ntr2 = trajectory(henon, 100000, 0.01rand(2))\n\nusing PyPlot\nfigure(figsize=(6,4))\nplot(tr[:, 1], tr[:, 2], lw = 0.0, marker = \"o\", ms = 0.1, alpha = 0.5);\nplot(tr2[:, 1], tr2[:, 2], lw = 0.0, marker = \"o\", ms = 0.1, alpha = 0.5);\nxlabel(\"x\"); ylabel(\"y\");\n\n# ------------------------------------------------------------------------------------------\n# ## Crash-course on `Dataset`\n#\n# `trajectory` returns an object that is a `Dataset`:\n# ------------------------------------------------------------------------------------------\n\ntr = trajectory(henon, 100000)\nprintln(typeof(tr))\nprintln(summary(tr))\n\n# ------------------------------------------------------------------------------------------\n# `Dataset` instances handle most data in **DynamicalSystems.jl**. `Dataset` is a wrapper of\n# a `Vector` of `SVector`s (statically sized vectors).\n# ------------------------------------------------------------------------------------------\n\ntypeof(tr.data) # this is where the `Dataset` has the data\n\n# ------------------------------------------------------------------------------------------\n# When accessed with one index, a `Dataset` behaves as a vector of vectors\n# ------------------------------------------------------------------------------------------\n\ntr[1] # variables at first time point\n\ntr[1:5]\n\n# ------------------------------------------------------------------------------------------\n# When accessed with two indices, a `Dataset` behaves like a matrix with each column being\n# the timeseries of each dynamic variable\n# ------------------------------------------------------------------------------------------\n\ntr[:, 1] # timeseries of first variable\n\ntr[1:56, 2] # time points 1:56 of second variable\n\ntr[12, 1] # value of first variable at 12th timepoint\n\ntr[1:10, 1:2] # using two ranges returns a `Dataset`\n\n# ------------------------------------------------------------------------------------------\n# # Adding a Jacobian\n#\n# Let's see `henon` again:\n# ------------------------------------------------------------------------------------------\n\nhenon\n\n# ------------------------------------------------------------------------------------------\n# * The last line, \"`jacobian:  ForwardDiff`\"\n# says that the Jacobian function of the equations of motion was computed automatically\n# using the module\n# [`ForwardDiff`](http://www.juliadiff.org/ForwardDiff.jl/stable/user/api.html).\n# * The Jacobian function is a crucial component of a dynamical system, and that is why if\n# it is not given, it is computed automatically.\n#\n#\n#\n# Even though the automatic computation is very efficient, the best possible performance\n# will come if you pass a \"hard-coded\" jacobian:\n# ------------------------------------------------------------------------------------------\n\nh_jacobian(x, p, t) = @SMatrix [-2*p[1]*x[1] 1.0; p[2] 0.0]\n\n# ------------------------------------------------------------------------------------------\n# * Notice that for **out-of-place** systems, the Jacobian must also have the same form as\n# the equations of motion, namely to return an `SMatrix`.\n#\n# Now, we can pass this Jacobian function to the `DiscreteDynamicalSystem` constructor as a\n# 4th argument:\n# ------------------------------------------------------------------------------------------\n\nhenon_with_jac = DiscreteDynamicalSystem(h_eom, state, p, h_jacobian)\n\n# ------------------------------------------------------------------------------------------\n# To see the difference in performance, let's call this Jacobian function\n# ------------------------------------------------------------------------------------------\n\nusing BenchmarkTools\na = rand(SVector{2})\n@btime $(henon_with_jac.jacobian)($a, $henon.prob.p, 0);\n@btime $(henon.jacobian)($a, $henon.prob.p, 0);\n\n# ------------------------------------------------------------------------------------------\n# You can see that even though `ForwardDiff` is truly performant, the hard-coded version is\n# much faster.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# # Continuous System\n# * The process of creating a continuous system is identical to that of a discrete system,\n# except that the constructor `ContinuousDynamicalSystem` is used instead.\n# * In this case the function `eom` returns the time derivatives and not a \"next state\".\n#\n#\n# ---\n#\n#\n#\n# * We will take the opportunity to show the process of using in-place equations of motion\n# for a continuous system, which is aimed to be used for large systems (dimensionality $\\ge$\n# 10).\n#\n# * In addition, the system we will use (Henon-Heiles) does not have any parameters.\n# $$\n# \\begin{aligned}\n# \\dot{x} &= p_x \\\\\n# \\dot{y} &= p_y \\\\\n# \\dot{p}_x &= -x -2 xy \\\\\n# \\dot{p}_y &= -y - (x^2 - y^2)\n# \\end{aligned}\n# $$\n# ------------------------------------------------------------------------------------------\n\n# Henon-heiles famous system\n# in-place form of equations of motion\n# du is the derivatives vector, u is the state vector\nfunction hheom!(du, u, p, t)\n    du[1] = u[3]\n    du[2] = u[4]\n    du[3] = -u[1] - 2u[1]*u[2]\n    du[4] = -u[2] - (u[1]^2 - u[2]^2)\n    return nothing\nend\n\n# pass `nothing` as the parameters, because the system doesn't have any\nhh = ContinuousDynamicalSystem(hheom!, [0, -0.25, 0.42081, 0], nothing)\n\n# ------------------------------------------------------------------------------------------\n# Great, now we can get a trajectory of this system, by solving using\n# DifferentialEquations.jl\n# ------------------------------------------------------------------------------------------\n\ntr = trajectory(hh, 100.0, dt = 0.05)\n\nfigure(figsize = (6,4))\nplot(tr[:, 1], tr[:, 2]);\nxlabel(\"\\$q_1\\$\"); ylabel(\"\\$q_2\\$\");\n\n# ------------------------------------------------------------------------------------------\n# # Handy Dandy definition table\n#\n# Depending on whether your system is small or large, you want to use out-of-place or in-\n# place equations of motion. The Jacobian function (if you wish to provide it) must also be\n# of the same form.\n#\n# Here is a handy table that summarizes what the definitions should look like:\n#\n# |          System Type         |    equations of motion    |            Jacobian\n# |\n# |:----------------------------:|:-------------------------:|:-----------------------------\n# -:|\n# | in-place (big systems)       | `eom!(du, u, p, t)`       | `jacobian!(J, u, p, t)`\n# |\n# | out-of-place (small systems) | `eom(u, p, t) -> SVector` | `jacobian(u, p, t) ->\n# SMatrix` |\n# \n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# # Time-evolution of systems & DifferentialEquations.jl\n# Discrete systems are evolved using internal algorithms. However, all time evolution of\n# continuous systems is done through the\n# [DifferentialEquations.jl](http://docs.juliadiffeq.org/latest/) library. In fact,\n# `trajectory` for continuous systems simply wraps `solve` with some extra arguments.\n#\n# Keep in mind that by default all continuous systems are evolved using the solver `Vern9()`\n# (9th order Verner solver) with tolerances `abstol = reltol = 1e-9`. This is especially\n# important when one wants to compare benchmarks with different packages.\n#\n# It is almost certain that if you use **DynamicalSystems.jl** you want to use also\n# DifferentialEquations.jl, due to the huge list of available features.\n#\n#\n# ## When to use **DynamicalSystems.jl**?\n# At this point in the tutorial you might be thinking:\n# > How is DynamicalSystems.jl different from DifferentialEquations.jl? Seems the same to me\n# so far...\n#\n# That's because we haven't seen any special features of **DynamicalSystems.jl** yet!\n# `trajectory` is nothing more than a \"convenient shortcut\".\n#\n# The [contents page](https://juliadynamics.github.io/DynamicalSystems.jl/latest/#contents)\n# of the documentation does a good job describing what is possible through\n# **DynamicalSystems.jl**.\n#\n# In addition, for usage with DifferentialEquations.jl, we can create specialized\n# integrators that evolve the system and the tangent space, or many states of the system in\n# parallel (at *exactly* same times):\n# * `tangent_integrator`\n# * `parallel_integrator`\n#\n# These functions work for both continuous and discrete systems and also work regardless of\n# whether the system is in-place (large), out-of-place (small) or auto-differentiated.\n# Special attention has also been given to the performance of the integrators.\n#\n# Also, keep in mind that regardless of whether you use a `DynamicalSystem` to produce a\n# timeseries or not, more than half of the **DynamicalSystems.jl** library is using\n# numerical data as an input. Most of the time this numerical data is expected in the form\n# of an `AbstractDataset` instance, which is what `trajectory` returns.\n#\n# ## Using DifferentialEquations.jl from a `DynamicalSystem`\n#\n# It is *very* likely that other features of DifferentialEquations.jl will be useful to\n# someone using **DynamicalSystems.jl**. However, you can still use DifferentialEquations.jl\n# *after* you have defined a continuous dynamical system, because the field `prob` gives an\n# `ODEProblem`:\n# ------------------------------------------------------------------------------------------\n\nhh.prob\n\n# ------------------------------------------------------------------------------------------\n# * **please be careful when using this problem directly, because as you can see the\n# `tspan[end]` field is `Inf`!!!**\n#\n#\n# * One final comment: using Callbacks is *not* possible with **DynamicalSystems.jl**,\n# because the the equations of motion function has to be assumed differentiable\n# \"everywhere\".\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# # Docstrings\n# ------------------------------------------------------------------------------------------\n\n?DynamicalSystem\n\n?trajectory\n\n?Dataset\n", "meta": {"hexsha": "8f262e746fe4045eed78b26c196f4b77747c2a19", "size": 16333, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/introduction-to-dynamicalsystems.jl/1. Creating a dynamical system.jl", "max_stars_repo_name": "grenkoca/JuliaTutorials", "max_stars_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 535, "max_stars_repo_stars_event_min_datetime": "2020-07-15T14:56:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T12:50:32.000Z", "max_issues_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/introduction-to-dynamicalsystems.jl/1. Creating a dynamical system.jl", "max_issues_repo_name": "grenkoca/JuliaTutorials", "max_issues_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2018-02-25T22:53:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-14T02:15:50.000Z", "max_forks_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/introduction-to-dynamicalsystems.jl/1. Creating a dynamical system.jl", "max_forks_repo_name": "grenkoca/JuliaTutorials", "max_forks_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 394, "max_forks_repo_forks_event_min_datetime": "2020-07-14T23:22:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:12:57.000Z", "avg_line_length": 42.6449086162, "max_line_length": 92, "alphanum_fraction": 0.5332149636, "num_tokens": 3657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8633916029436189, "lm_q1q2_score": 0.7909613517040385}}
{"text": "\"\"\"\n    bernoulli(n, x)\n\n Calculates Bernoulli polynomials ``B_n(x)``\n e.g., see\n \n + [https://en.wikipedia.org/wiki/Bernoulli_polynomials](https://en.wikipedia.org/wiki/Bernoulli_polynomials)\n + [http://dlmf.nist.gov/24](http://dlmf.nist.gov/24)\n\n## Arguments\n* ``n`` `::Integer`: the index into the series, ``n=0,1,2,3,...``\n* ``x`` `::Real`: the point at which to calculate the polynomial\n\n## Examples\n```jldoctest; setup = :(using Polylogarithms)\njulia> bernoulli(6, 1.2)\n0.008833523809524735\n```\n\"\"\"\nfunction bernoulli(n::Integer, x::Real)\n    if n<0\n        throw(DomainError(n))\n    end\n    if n == 0\n        return 1 # zeta formula doesn't hold for n=0, so return explicit value\n    elseif n == 1 # get some easy cases out of the way quickly\n        return x-0.5 \n    elseif n == 2\n        return x^2 - x + 1.0/6.0\n    elseif n == 3\n        return x^3 - 1.5*x^2 + 0.5*x\n    elseif n == 4\n        return x^4 - 2.0*x^3 +     x^2 - 1/30.0\n    elseif n == 5\n         return x^5 - 2.5*x^4 +(5.0/3.0)*x^3 - x/6.0\n    end\n\n # from the Hurwitz-zeta function using\n\n # ``ζ(-n,x) = -B_{n+1}(x)/(n+1), for Re(x)>0,``\n\n # which is faster than direct calculation of the polynomial except for n<=4, but for \n # small n (n<=5) we use the exact polynomials. For negative x, we use the recursive\n # formula to push it into a postive range. \n     # return -n*SpecialFunctions.zeta(1-n, x)\n    # see https://carma.newcastle.edu.au/resources/jon/Preprints/Papers/Published-InPress/Oscillatory%20(Tapas%20II)/Papers/coffey-zeta.pdf, p.341\n    # however, I am not really happy with the results I am getting out of this\n    # so exploit symmetries in B_n(x) to compute recursively for x<=0\n    # if x >= 0\n    #      return -n*SpecialFunctions.zeta(1-n, x)\n    # else\n    #     return bernoulli(n, x+1) - n*x^(n-1)\n    # end\n\n    # total = 0.0\n    # for k = 0:n-1\n    #     total -= binomial(n+1, k) *  bernoulli(k,x)\n    # end\n    # total = total / (n+1)\n    # total += x^n\n    # return total\n\n    # alternative, a little better, but relies on bernoulli numbers, which I only have to 35\n    # and still has some non-negligable errors, so I still would like a better piece in here\n    n = Int64(n) \n    if n <= 35\n        total = 0.0\n        for k = 0:n\n            k = Int64(k)\n            total += binomial(n, k) *  bernoulli(n-k) * x^k\n            # this will overflow for large n and k, but that migth be avoidable if we were more clever?\n        end\n        return total\n    else\n        # this is faster but less accurate, and runs into some weird problems, e.g.,\n        # SpecialFunctions.zeta(-6, -1.0) = NaN (probably should be 2)\n        return -n*SpecialFunctions.zeta(1-n, x)\n    end\nend\n", "meta": {"hexsha": "b1e3341ee89762e9765432313dfc50a414789b43", "size": 2686, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bernoulli_poly.jl", "max_stars_repo_name": "AshtonSBradley/Polylogarithms.jl", "max_stars_repo_head_hexsha": "f52e3075cd1d87b0d67d26c72cd1a79a365eddcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-08-24T09:17:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T10:54:45.000Z", "max_issues_repo_path": "src/bernoulli_poly.jl", "max_issues_repo_name": "AshtonSBradley/Polylogarithms.jl", "max_issues_repo_head_hexsha": "f52e3075cd1d87b0d67d26c72cd1a79a365eddcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-11-18T00:06:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-18T10:35:43.000Z", "max_forks_repo_path": "src/bernoulli_poly.jl", "max_forks_repo_name": "AshtonSBradley/Polylogarithms.jl", "max_forks_repo_head_hexsha": "f52e3075cd1d87b0d67d26c72cd1a79a365eddcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-17T16:20:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T09:32:06.000Z", "avg_line_length": 33.575, "max_line_length": 146, "alphanum_fraction": 0.6027550261, "num_tokens": 898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979619, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.790960485812912}}
{"text": "module paqueteFourier\n\nimport Base: +, -, *, /\n\nimport Gadfly\n\n# Notar que los métodos de +, -, *, / y diff se exportan solos\nexport trigPoly, innerProduct, nodes, vals, tpfplot\n\n# El objeto básico de este paquete es un trigPoly, cuyo campo coefs contiene\n# los coeficientes de la representación de un polinomio trigonométrico como\n# combinación lineal de 1, exp(-im θ), exp(im θ), exp(-2im θ), exp(2im θ), …,\n# en ese orden.\n# Junto a la definición de este 'type' Julia automáticamente deja disponible un\n# constructor, que es una función que recibe un vector de números complejos y\n# devuelve un trigPoly con ese vector en el campo coefs.\n# A continuación justificaré mi elección de ordenamiento para los coeficientes\n# con la ayuda de una tabla.  Denoto al orden elegido (0, -1, 1, -2, 2, …) por\n# A, al orden visto en clase (-N/2, -N/2+1, …, -1, 0, 1, …, N/2-2, N/2) por B y\n# al orden por defecto de la FFT (0, 1, …, N/2-1, -N/2, -N/2+1, …, -1) por C (B\n# y C son ligeramente distintos si N es impar, pero la tabla sigue valiendo).\n#                                 ┌───┬───┬───┐\n#                                 │ A │ B │ C │\n# ┌───────────────────────────────┼───┼───┼───┤\n# │                          Suma │ ✓ │ ✗ │ ✗ │\n# │Interpretación de coeficientes │ ✓ │ ✗ │ ~ │\n# │     Vector de números de onda │ ~ │ ✓ │ ✗ │\n# │           Interpolación (FFT) │ ✗ │ ~ │ ✓ │\n# ├───────────────────────────────┴───┴───┴───┤\n# │   ✓ = Fácil, ~ = Moderado, ✗ = Difícil    │\n# └───────────────────────────────────────────┘\n\"\"\"\n    trigPoly(x)\n\nPolinomio trigonométrico que es combinación lineal de 1, exp(-im θ), exp(im θ), exp(-2im θ), … con los coeficientes indicados en `x`.\n\"\"\"\ntype trigPoly\n\tcoefs::Vector{Complex128}\nend\n\n\"\"\"\n    innerProduct(f,g)\n\nProducto interior L² entre los trigPoly `f` y `g`.\n\"\"\"\nfunction innerProduct(f::trigPoly, g::trigPoly)\n\tac = 0.0 + 0.0im\n\tfor k = 1:min(length(f.coefs),length(g.coefs))\n\t\tac += f.coefs[k] * conj(g.coefs[k])\n\tend\n\t2π*ac\nend\n\n# Sin cargar ningún paquete Julia ya tiene una función llamada norm; la nuestra\n# será un método más\n\"\"\"\n    norm(f::trigPoly)\n\nNorma L² de `f`.\n\"\"\"\nBase.norm(f::trigPoly) = sqrt(real(innerProduct(f,f)))\n\n\"\"\"\n    nodes(n)\n\nArreglo de `n` nodos de Fourier.\n\"\"\"\nfunction nodes(n::Integer)\n\t2π*(0:n-1)/n\nend\n\n# Función que transforma un vector del orden C al orden A; Julia reemplazará T\n# con el tipo de número que contenga el vector con el cual se alimente a esta\n# función\nfunction reordering{T}(v::Vector{T})\n\tn = length(v)\n\tout = Vector{T}(n) # Reserva de memoria\n\tfloorhalfn = n÷2\n\tfor k = 1:floorhalfn\n\t\tout[2*k] = v[n+1-k]\n\tend\n\tfor k = 1:n-floorhalfn\n\t\tout[2*k-1] = v[k]\n\tend\n\tout\nend\n\n# Función que transforma un vector del orden A al orden C\nfunction reverse_reordering{T}(v::Vector{T})\n\tn = length(v)\n\tfloorhalfn = n÷2\n\tout = Vector{T}(n)\n\tfor k = 1:floorhalfn\n\t\tout[n+1-k] = v[2*k]\n\tend\n\tfor k = 1:n-floorhalfn\n\t\tout[k] = v[2*k-1]\n\tend\n\tout\nend\n\n# Interpolador que asume que los valores recibidos corresponden a la evaluación\n# de una función en los nodos de Fourier\nfunction interp{T}(v::Vector{T})\n\tmodes = fft(v)/length(v)\n\ttrigPoly(reordering(modes))\nend\n\n\"\"\"\n    trigPoly(f, n)\n\nPolinomio trigonométrico que interpola a la función `f` en `n` nodos de Fourier.\n\"\"\"\nfunction trigPoly(f::Function, n::Integer)\n\tvals = map(f, nodes(n)) # Vector con evaluaciones de f\n\tinterp(vals)\nend\n\n\"\"\"\n    vals(f)\n\nEvaluación del polinomio trigonométrico `f` en tantos nodos de Fourier como coeficientes almacena `f`.\n\"\"\"\nfunction vals(f::trigPoly)\n\tifft(reverse_reordering(f.coefs*length(f.coefs)))\nend\n\n\"\"\"\n    vals(f, x)\n\nEvaluación del polinomio trigonométrico `f` en el arreglo o escalar real `x`.\n\"\"\"\nfunction vals(f::trigPoly, x)\n\tcoefsplus = f.coefs[3:2:end]\n\tcoefsminus = f.coefs[2:2:end]\n\t# Podría escribir exp(im*x), pero si x es escalar Julia emite una\n\t# advertencia (no un error) que invita a usar la versión vectorizada de\n\t# exp; usando map x puede ser escalar o vectorial indistintamente\n\texpplusix = map(exp, im*x)\n\texpminusix = conj(expplusix)\n\t# Arreglo con ceros o escalar cero según lo que sea x\n\toutplus = zero(expplusix)\n\toutminus = zero(expplusix)\n\tfor val in reverse(coefsplus)\n\t\toutplus = expplusix.*(outplus + val)\n\tend\n\tfor val in reverse(coefsminus)\n\t\toutminus = expminusix.*(outminus + val)\n\tend\n\toutplus + outminus + f.coefs[1]\nend\n\n# Evaluador por defecto de un trigPoly; permite evaluar un trigPoly f en x con\n# la sintaxis clásica f(x)\n(f::trigPoly)(x) = vals(f, x)\n\n# Suma\nfunction +(f::trigPoly, g::trigPoly)\n\tfl = length(f.coefs)\n\tgl = length(g.coefs)\n\tretl = max(fl, gl)\n\tretcoefs = zeros(Complex128, retl)\n\tretcoefs[1:fl] = f.coefs\n\tretcoefs[1:gl] += g.coefs\n\ttrigPoly(retcoefs)\nend\n\n# Cambio de signo\n-(f::trigPoly) = trigPoly(-f.coefs)\n\n# Resta\n-(f::trigPoly, g::trigPoly) = f + (-g)\n\n# Suma, resta, multiplicación y división por escalar\nfunction +(f::trigPoly, a::Number)\n\tretcoefs = f.coefs\n\tretcoefs[1] += a\n\ttrigPoly(retcoefs)\nend\n-(f::trigPoly, a::Number) = f + (-a)\n*(f::trigPoly, a::Number) = trigPoly(f.coefs*a)\n/(f::trigPoly, a::Number) = trigPoly(f.coefs/a)\n*(a::Number, f::trigPoly) = f*a\n+(a::Number, f::trigPoly) = f+a\n-(a::Number, f::trigPoly) = (-f) + a\n\n# Multiplicación\nfunction *(f::trigPoly, g::trigPoly)\n\tndof = length(f.coefs) + length(g.coefs)\n\tpaddedf = trigPoly([f.coefs; zeros(Complex128,ndof-length(f.coefs))])\n\tpaddedg = trigPoly([g.coefs; zeros(Complex128,ndof-length(g.coefs))])\n\tproductvals = vals(paddedf) .* vals(paddedg)\n\tinterp(productvals)\nend\n\n\"\"\"\n    diff(f::trigPoly)\n\nDerivada de `f`.\n\"\"\"\nfunction Base.diff(f::trigPoly)\n\tretcoefs = Vector{Complex128}(length(f.coefs))\n\tfor k = 1:length(f.coefs)\n\t\t#             ↓     modo     ↓\n\t\tretcoefs[k] = (-1)^(k+1)*(k÷2) * im * f.coefs[k]\n\tend\n\ttrigPoly(retcoefs)\nend\n\n\"\"\"\n    diff(f::trigPoly, k::Int64)\n\n`k`-ésima derivada de `f`.\n\"\"\"\nfunction Base.diff(f::trigPoly, k::Int64)\n\t@assert k>=0\n\tif k == 0\n\t\treturn f\n\telseif k == 1\n\t\treturn diff(f)\n\telse\n\t\treturn diff(f, k-1)\n\tend\nend\n\n\"\"\"\n    tpfplot(f)\n    tpfplot(f1, f2, ...)\n    tpfplot(f1, f2, ..., labels=[label1, label2, ...])\n\nGrafica a un polinomio trigonométrico (trigPoly) o función (Function) `f` o a la colección de polinomios trigonométricos o funciones `f1`, `f2`, ...; el argumento opcional `labels`, de aparecer, debe especificar nombres para las curvas ingresadas como un arreglo de cadenas de tipo `String`.\n\nLa figura obtenida se puede guardar mediante la sintaxis\n\n    fh = tpfplot(...)\n    Gadfly.draw(Gadfly.SVG(\"myplot.svg\", 15Gadfly.cm, 9Gadfly.cm), fh)\n\"\"\"\nfunction tpfplot(vf::Vararg{Union{Function,trigPoly}}; labels=[])\n\tdefaultNamesFlag = isempty(labels)\n\tlayersReal = []\n\tlayersImag = []\n\tlayerLabels = []\n\tlayerColors = []\n\tfor i = 1:length(vf)\n\t\tc = [\"blue\" \"green\" \"red\" \"deepskyblue\" \"magenta\" \"gold\" \"lightcoral\" \"black\"][(i-1)%8+1]\n\t\tif defaultNamesFlag\n\t\t\tpush!(labels, \"Curve $(i)\")\n\t\tend\n\t\tif typeof(vf[i]) <: trigPoly\n\t\t\tnsamples = max(150, 6*length(vf[i].coefs))\n\t\t\tx = nodes(nsamples)\n\t\t\tvfix = vals(trigPoly([vf[i].coefs;zeros(Complex128,nsamples-length(vf[i].coefs))]))\n\t\t\t# Agrego el punto de abscisa 2π\n\t\t\tx = [x;2π]\n\t\t\tvfix = [vfix;vfix[1]]\n\t\t\t# Ahora los puntos con abscisas en la colección de\n\t\t\t# nodos de Fourier que corresponde a vf[i]\n\t\t\txn = nodes(length(vf[i].coefs))\n\t\t\tvfin = vals(vf[i])\n\t\t\tpush!(layersReal, Gadfly.layer(x=x, y=real(vfix), Gadfly.Geom.line, Gadfly.Theme(default_color=c)))\n\t\t\tpush!(layersReal, Gadfly.layer(x=xn, y=real(vfin), Gadfly.Geom.point, Gadfly.Theme(default_color=c)))\n\t\t\tpush!(layersImag, Gadfly.layer(x=x, y=imag(vfix), Gadfly.Geom.line, Gadfly.Theme(default_color=c)))\n\t\t\tpush!(layersImag, Gadfly.layer(x=xn, y=imag(vfin), Gadfly.Geom.point, Gadfly.Theme(default_color=c)))\n\t\t\tpush!(layerColors, c); push!(layerLabels, labels[i])\n\t\telse\n\t\t\tx = linspace(0,2π,2000)\n\t\t\tvfix = map(vf[i], x)\n\t\t\tpush!(layersReal, Gadfly.layer(x=x, y=real(vfix), Gadfly.Geom.line, Gadfly.Theme(default_color=c)))\n\t\t\tpush!(layersImag, Gadfly.layer(x=x, y=imag(vfix), Gadfly.Geom.line, Gadfly.Theme(default_color=c)))\n\t\t\tpush!(layerColors, c); push!(layerLabels, labels[i])\n\t\tend\n\tend\n\tlabelSpecification = Gadfly.Guide.manual_color_key(\"\", layerLabels, layerColors)\n\tGadfly.hstack(\n\t       Gadfly.plot(layersReal..., Gadfly.Guide.XLabel(\"θ\"), Gadfly.Guide.YLabel(\"\"), Gadfly.Guide.Title(\"Real part\"), Gadfly.Coord.cartesian(xmin=0, xmax=2π), Gadfly.Theme(key_position=:bottom), labelSpecification),\n\t       Gadfly.plot(layersImag..., Gadfly.Guide.XLabel(\"θ\"), Gadfly.Guide.YLabel(\"\"), Gadfly.Guide.Title(\"Imaginary part\"), Gadfly.Coord.cartesian(xmin=0, xmax=2π), Gadfly.Theme(key_position=:bottom), labelSpecification)\n\t       )\nend\n\nend # module\n", "meta": {"hexsha": "bdc5be26b7d93aa88db8ab798ca67d2ee0e59d1e", "size": 8657, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/paqueteFourier.jl", "max_stars_repo_name": "lfiguero/paqueteFourier", "max_stars_repo_head_hexsha": "443da6a741f6f3716cee1543e6c173a39f40b65e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-14T15:47:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-14T15:47:41.000Z", "max_issues_repo_path": "src/paqueteFourier.jl", "max_issues_repo_name": "lfiguero/paqueteFourier", "max_issues_repo_head_hexsha": "443da6a741f6f3716cee1543e6c173a39f40b65e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/paqueteFourier.jl", "max_forks_repo_name": "lfiguero/paqueteFourier", "max_forks_repo_head_hexsha": "443da6a741f6f3716cee1543e6c173a39f40b65e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8078291815, "max_line_length": 291, "alphanum_fraction": 0.6558854107, "num_tokens": 2943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.7909604737131593}}
{"text": "using Roots\n\nf(x) = x^3 - x - 1\n@show fzeros(f)\nprintln()\n\n@show fzero(f, [-2,2])\nprintln()\n\n@show fzero(f, 1.0)\nprintln()\n\nf(x) = exp(x) - x^4\nfp(x) = exp(x) - 4x^3\nfpp(x) = exp(x) - 12x^2\nnewton(f, fp, 8)        # 8.613169456441398\nnewton(f, 8)    \nhalley(f, fp, fpp, 8)\nhalley(f, 8)\nsecant_method(f, 8, 8.5)", "meta": {"hexsha": "ab75080af169e9e41bf440ff3ddb4fe2775f07c0", "size": 310, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch03/p_03_01.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-02T01:16:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-02T01:16:31.000Z", "max_issues_repo_path": "examples/ch03/p_03_01.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ch03/p_03_01.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.5, "max_line_length": 43, "alphanum_fraction": 0.5612903226, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102514755852, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7909299210144083}}
{"text": "module TestFunctions\n\n\"\"\"\nOne dimensional Runge function defined over \\$[-1, 1]\\$\n (Taken from chapter 13 of \"Approximation Theory and Approximation\n Practice\" by Prof. Trefethen)\n\"\"\"\n1d_runge(x) = 1./(1 + 25x.*x)\n\n\"\"\"\nOne dimensional Keane test function\n    (Taken from \"Engineering Design with Surrogate Modelling\" by Prof. Keane\n    et al.)\n\"\"\"\n1d_keane(x) = (6x - 2).^2.*sin.(12x-4)\n\n\"\"\"\nOne dimensional Liu test function\n (A survey of adaptive sampling for global metamodeling (2017))\n\"\"\"\n1d_liu(x) = x.*x.*exp.(-4x).*(sin.(7x) + cos.(14x))\n\n\"\"\"\nTwo dimensional Branin function from Schonolau's thesis.\n\"\"\"\n2d_branin(x) = (x[2] .- 5.1x[1].*x[1]./(4π*π) .+ 5x[1]/π .- 6).^2 + 10(1 - 1/(8π)).*cos.(x[1]) + 10\n\n\n\nexport 1d_runge, 1d_keane, 1d_liu,\n       2d_branin\n\nend\n\n\n# vim:filetype=julia:foldmethod=syntax\n\n\n", "meta": {"hexsha": "4d0631278f2fc16ef48c0af87acaca11604c692d", "size": 815, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "TestFunctions.jl", "max_stars_repo_name": "devendra-ghate/surrogateModels", "max_stars_repo_head_hexsha": "c238ad05f058bf106dd619ed0b93c380a6ade678", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TestFunctions.jl", "max_issues_repo_name": "devendra-ghate/surrogateModels", "max_issues_repo_head_hexsha": "c238ad05f058bf106dd619ed0b93c380a6ade678", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TestFunctions.jl", "max_forks_repo_name": "devendra-ghate/surrogateModels", "max_forks_repo_head_hexsha": "c238ad05f058bf106dd619ed0b93c380a6ade678", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8974358974, "max_line_length": 99, "alphanum_fraction": 0.6503067485, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8558511396138366, "lm_q1q2_score": 0.7909278333698038}}
{"text": "function euler_step(f, t::Number, x, len)\n    return len' .* f(t, x)\nend\n\nfunction mod_euler_step(f, t::Number, x, len)\n    whole_step = len' .* f(t, x)\n    return (whole_step + len' .* f(t .+ len, x .+ whole_step))/2\nend\n\nfunction heum_step(f, t::Number, x, len)\n    whole_step = len' .* f(t, x)\n    return (whole_step + 3*len' .* f(t .+ 2/3*len, x .+ 2/3*whole_step))/4\nend\n\nfunction RK4_step(f, t::Number, x, len)\n    k1 = len' .* f(t, x)\n    k2 = len' .* f(t .+ len/2, x .+ k1/2)\n    k3 = len' .* f(t .+ len/2, x .+ k2/2)\n    k4 = len' .* f(t .+ len, x .+ k3)\n    return (k1 + 2*k2 + 2*k3 + k4)/6\nend\n\nmacro define_order(f, ord::Integer)\n    @eval function $f(s::Symbol)\n        if s == :order\n            return $ord\n        end\n        throw(ErrorException(\"Invalid symbol. Use :order\"))\n    end\nend\n\n@define_order(euler_step, 1)\n@define_order(mod_euler_step, 2)\n@define_order(heum_step, 2)\n@define_order(RK4_step, 4)\n\nfunction fixed_step_ode_solver(\n    f,\n    t0::Number,\n    x0;\n    method=RK4_step,\n    step::Number = 1e-3,\n    iter::Integer = 10000\n)\n    t = t0\n    x = Array{typeof(x0 + step*f(t0, x0))}(undef, iter+1)\n    x[1] = x0\n    for j = 1:iter\n        x[j+1] = x[j] + method(f, t, x[j], step)\n        t += step\n    end\n    return x\nend\n\nfunction fixed_step_ode_solver(\n    f,\n    t0::Number,\n    x0,\n    stop_cond;\n    method=RK4_step,\n    step::Number = 1e-3,\n    maxit::Integer = 10000\n)\n    t = t0\n    x = Array{typeof(x0 + method(f, t, x0, step)), 1}()\n    push!(x, x0)\n    for j = 1:maxit\n        push!(x, last(x) + method(f, t, last(x), step))\n        t += step\n        if stop_cond(t, x)\n            break\n        end\n    end\n    return x\nend\n\n", "meta": {"hexsha": "b97eae7b7ab495beee9afcbad1933ea532731270", "size": 1671, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FixedStepMethods.jl", "max_stars_repo_name": "useredsa/numeric-differential-equations", "max_stars_repo_head_hexsha": "7647a20120ce0a05ee5223b0ce81ad63d8aee115", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FixedStepMethods.jl", "max_issues_repo_name": "useredsa/numeric-differential-equations", "max_issues_repo_head_hexsha": "7647a20120ce0a05ee5223b0ce81ad63d8aee115", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FixedStepMethods.jl", "max_forks_repo_name": "useredsa/numeric-differential-equations", "max_forks_repo_head_hexsha": "7647a20120ce0a05ee5223b0ce81ad63d8aee115", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7012987013, "max_line_length": 74, "alphanum_fraction": 0.5421903052, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7909278331914265}}
{"text": "\nmodule CoDa\n\nexport alpha, alphaTransform, Helmert\nexport ilr, clr \n\n\"\"\"\n    Helmert(n)\n\nCalculate ``n×n`` Helmert matrix\n\"\"\"\nfunction Helmert(n)\n    H = zeros(n,n)\n  for i = 1:n, j = 1:n\n      if i==1\n        H[i,j] = 1.0/sqrt(n)\n      elseif j < i\n        H[i,j] = 1.0/sqrt(i*(i-1))\n      elseif i==j\n        H[i,j] = (1.0-i)/sqrt(i*(i-1))\n      end\n  end\n    return -H\nend\n\n\"\"\"\n    alphaTransform(X::Matrix, α::Float64)\n\nApply alpha-transform with Helmert product to ``X``\n\"\"\"\nfunction alphaTransform(X::Matrix{Float64}, α::Float64)\n    D = size(X,2)\n    H = Helmert(D)[2:end,:]\n    Xᵃ = X.^α\n    Xs = sum(Xᵃ, dims=2)    \n    U = (D*Xᵃ./Xs .- 1)./α\n    return U*transpose(H)    \nend\n\n\n\"\"\"\n    alpha(X::Matrix, α::Float64)\n\nApply alpha-transform without Helmert product\n\"\"\"\nfunction alpha(X::Matrix{Float64}, α::Float64)\n    D = size(X,2)\n#    H = Helmert(D)[2:end,:]\n    Xᵃ = X.^α\n    Xs = sum(Xᵃ,dims=2)    \n    U = (D*Xᵃ./Xs .- 1)./α\n    return U    \nend\n\n\n\"\"\"\n    ilr(X::Matrix)\n\nIsometric logratio transform\n\"\"\"\nfunction ilr(X::Matrix{Float64})\n    D = size(X,2)  \n    H = Helmert(D)[2:end,:]\n    return log.(X) * transpose(H)  \nend    \n\n\n\"\"\"\n    clr(X::Matrix)\n\nCentered logratio transform\n\"\"\"\nfunction clr(X::Matrix{Float64})\n    D = size(X,2)\n    ratio = X ./ (prod(X,2).^(1/D))\n    return log.(ratio)\nend\n\n\nend", "meta": {"hexsha": "37264e865252778d3d79745350f42dc55daf2d02", "size": 1322, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CoDa.jl", "max_stars_repo_name": "Mattriks/alphaPredictableComponents.jl", "max_stars_repo_head_hexsha": "33146047179dfc883ba92f02f3cd40dce92eac91", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CoDa.jl", "max_issues_repo_name": "Mattriks/alphaPredictableComponents.jl", "max_issues_repo_head_hexsha": "33146047179dfc883ba92f02f3cd40dce92eac91", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CoDa.jl", "max_forks_repo_name": "Mattriks/alphaPredictableComponents.jl", "max_forks_repo_head_hexsha": "33146047179dfc883ba92f02f3cd40dce92eac91", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.525, "max_line_length": 55, "alphanum_fraction": 0.5453857791, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7909075976866762}}
{"text": "# Linear Discriminant Analysis\n\n#### Type to represent a linear discriminant functional\n\n\"\"\"\nA linear discriminant functional can be written as\n\n```math\n    f(\\\\mathbf{x}) = \\\\mathbf{w}^T \\\\mathbf{x} + b\n```\n\nHere, ``w`` is the coefficient vector, and ``b`` is the bias constant.\n\"\"\"\nstruct LinearDiscriminant{T<:Real} <: RegressionModel\n    w::Vector{T}\n    b::T\nend\n\n#### function to solve linear discriminant\n\"\"\"\n    ldacov(C, μp, μn)\n\nPerforms LDA given a covariance matrix `C` and both mean vectors `μp` & `μn`.  Returns a linear discriminant functional of type [`LinearDiscriminant`](@ref).\n\n*Parameters*\n- `C`: The pooled covariane matrix (*i.e* ``(Cp + Cn)/2``)\n- `μp`: The mean vector of the positive class.\n- `μn`: The mean vector of the negative class.\n\"\"\"\nfunction ldacov(C::DenseMatrix{T},\n                μp::DenseVector{T},\n                μn::DenseVector{T}) where T<:Real\n\n    w = cholesky(C) \\ (μp - μn)\n    ap = w ⋅ μp\n    an = w ⋅ μn\n    c = 2 / (ap - an)\n    LinearDiscriminant(rmul!(w, c), 1 - c * ap)\nend\n\n\"\"\"\n    ldacov(Cp, Cn, μp, μn)\n\nPerforms LDA given covariances and mean vectors. Returns a linear discriminant functional of type [`LinearDiscriminant`](@ref).\n\n*Parameters*\n- `Cp`: The covariance matrix of the positive class.\n- `Cn`: The covariance matrix of the negative class.\n- `μp`: The mean vector of the positive class.\n- `μn`: The mean vector of the negative class.\n\n**Note:** The coefficient vector is scaled such that ``w'μp + b = 1`` and ``w'μn + b = -1``.\n\"\"\"\nldacov(Cp::DenseMatrix{T},\n       Cn::DenseMatrix{T},\n       μp::DenseVector{T},\n       μn::DenseVector{T}) where T<:Real = ldacov(Cp + Cn, μp, μn)\n\n\"\"\"\n    evaluate(f, x::AbstractVector)\n\nEvaluate the linear discriminant value, *i.e* ``w'x + b``, it returns a real value.\n\"\"\"\nevaluate(f::LinearDiscriminant, x::AbstractVector) = dot(f.w, x) + f.b\n\n\"\"\"\n    evaluate(f, X::AbstractMatrix)\n\nEvaluate the linear discriminant value, *i.e* ``w'x + b``, for each sample in columns of `X`. The function returns a vector of length `size(X, 2)`.\n\"\"\"\nfunction evaluate(f::LinearDiscriminant, X::AbstractMatrix)\n    R = transpose(X) * f.w\n    if f.b != 0\n        broadcast!(+, R, R, f.b)\n    end\n    return R\nend\n\n# RegressionModel interface\n\n\"\"\"\n    predict(f, x::AbstractVector)\n\nMake prediction for the vector `x`. It returns `true` iff `evaluate(f, x)` is positive.\n\"\"\"\npredict(f::LinearDiscriminant, x::AbstractVector) = evaluate(f, x) > 0\n\n\"\"\"\n    predict(f, X::AbstractMatrix)\n\nMake predictions for the matrix `X`.\n\"\"\"\npredict(f::LinearDiscriminant, X::AbstractMatrix) = Bool[y > 0 for y in evaluate(f, X)]\n\n\"\"\"\n    coef(f::LinearDiscriminant)\n\nReturn the coefficients of the linear discriminant model.\n\"\"\"\ncoef(f::LinearDiscriminant) = (f.b, f.w)\n\n\"\"\"\n    coef(f::LinearDiscriminant)\n\nReturn the coefficients' names of the linear discriminant model.\n\"\"\"\ncoefnames(f::LinearDiscriminant) = [\"Bias\", \"Weights\"]\n\n\"\"\"\n    dof(f::LinearDiscriminant)\n\nReturn the number of degrees of freedom in the linear discriminant model.\n\"\"\"\ndof(f::LinearDiscriminant) = length(f.w)+1\n\n\"\"\"\n    weights(f::LinearDiscriminant)\n\nReturn the linear discriminant model coefficient vector.\n\"\"\"\nweights(f::LinearDiscriminant) = f.w\n\n\"\"\"\nGet the length of the coefficient vector.\n\"\"\"\nlength(f::LinearDiscriminant) = length(f.w)\n\n\"\"\"\n    fit(LinearDiscriminant, Xp, Xn; covestimator = SimpleCovariance())\n\nPerforms LDA given both positive and negative samples. The function accepts follwing parameters:\n\n**Parameters**\n- `Xp`: The sample matrix of the positive class.\n- `Xn`: The sample matrix of the negative class.\n\n**Keyword arguments:**\n- `covestimator`: Custom covariance estimator for between-class covariance. The covariance matrix will be calculated as `cov(covestimator_between, #=data=#; dims=2, mean=zeros(#=...=#)`. Custom covariance estimators, available in other packages, may result in more robust discriminants for data with more features than observations.\n\"\"\"\nfunction fit(::Type{LinearDiscriminant}, Xp::DenseMatrix{T}, Xn::DenseMatrix{T};\n             covestimator::CovarianceEstimator = SimpleCovariance()) where T<:Real\n    μp = vec(mean(Xp, dims=2))\n    μn = vec(mean(Xn, dims=2))\n    Zp = Xp .- μp\n    Zn = Xn .- μn\n    Cp = calcscattermat(covestimator, Zp)\n    Cn = calcscattermat(covestimator, Zn)\n    ldacov(Cp, Cn, μp, μn)\nend\n\n#==============================================================================#\n\n#### Multiclass LDA Stats\n\n\"\"\"\nResulting statistics of the multi-class LDA evaluation.\n\"\"\"\nmutable struct MulticlassLDAStats{T<:Real, M<:AbstractMatrix{T}, N<:AbstractMatrix{T}}\n    dim::Int              # sample dimensions\n    nclasses::Int         # number of classes\n    cweights::Vector{T}   # class weights\n    tweight::T            # total sample weight\n    mean::Vector{T}       # overall sample mean\n    cmeans::Matrix{T}     # class-specific means\n    Sw::M                 # within-class scatter matrix\n    Sb::N                 # between-class scatter matrix\nend\n\nmean(S::MulticlassLDAStats) = S.mean\nclassweights(S::MulticlassLDAStats) = S.cweights\nclassmeans(S::MulticlassLDAStats) = S.cmeans\n\nwithclass_scatter(S::MulticlassLDAStats) = S.Sw\nbetweenclass_scatter(S::MulticlassLDAStats) = S.Sb\n\nfunction MulticlassLDAStats(cweights::Vector{T},\n                            mean::Vector{T},\n                            cmeans::Matrix{T},\n                            Sw::AbstractMatrix{T},\n                            Sb::AbstractMatrix{T}) where T<:Real\n    d, nc = size(cmeans)\n    length(mean) == d || throw(DimensionMismatch(\"Incorrect length of mean\"))\n    length(cweights) == nc || throw(DimensionMismatch(\"Incorrect length of cweights\"))\n    tw = sum(cweights)\n    size(Sw) == (d, d) || throw(DimensionMismatch(\"Incorrect size of Sw\"))\n    size(Sb) == (d, d) || throw(DimensionMismatch(\"Incorrect size of Sb\"))\n    MulticlassLDAStats(d, nc, cweights, tw, mean, cmeans, Sw, Sb)\nend\n\nfunction multiclass_lda_stats(nc::Int, X::AbstractMatrix{T}, y::AbstractVector{Int};\n                              covestimator_within::CovarianceEstimator=SimpleCovariance(),\n                              covestimator_between::CovarianceEstimator=SimpleCovariance()) where T<:Real\n    # check sizes\n    d = size(X, 1)\n    n = size(X, 2)\n    n ≥ nc || throw(ArgumentError(\"The number of samples is less than the number of classes\"))\n    length(y) == n || throw(DimensionMismatch(\"Inconsistent array sizes.\"))\n\n    # compute class-specific weights and means\n    cmeans, cweights, Z = center(X, y, nc)\n\n    Sw = calcscattermat(covestimator_within, Z)\n\n    # compute between-class scattering\n    mean = cmeans * Vector{T}(cweights ./ n)\n    U = rmul!(cmeans .- mean, Diagonal(sqrt.(cweights)))\n    Sb = calcscattermat(covestimator_between, U)\n\n    return MulticlassLDAStats(Vector{T}(cweights), mean, cmeans, Sw, Sb)\nend\n\n\n#### Multiclass LDA\n\n\"\"\"\nA multi-class linear discriminant model type has following fields:\n- `proj` is the projection matrix\n- `pmeans` is the projected means of all classes\n- `stats` is an instance of [`MulticlassLDAStats`](@ref) type that captures all statistics computed to train the model (which we will discuss later).\n\"\"\"\nmutable struct MulticlassLDA{T<:Real} <: RegressionModel\n    proj::Matrix{T}\n    pmeans::Matrix{T}\n    stats::MulticlassLDAStats{T}\nend\n\n\"\"\"\n    size(M::MulticlassLDA)\n\nGet the input (*i.e* the dimension of the observation space) and output (*i.e* the dimension of the transformed features) dimensions of the model `M`.\n\"\"\"\nsize(M::MulticlassLDA) = size(M.proj)\n\"\"\"\n    length(M::MulticlassLDA)\n\nGet the sample dimensions.\n\"\"\"\nlength(M::MulticlassLDA) = M.stats.dim\n\"\"\"\n    projection(M::MulticlassLDA)\n\nGet the projection matrix (of size *d x p*).\n\"\"\"\nprojection(M::MulticlassLDA) = M.proj\n\"\"\"\n    mean(M::MulticlassLDA)\n\nGet the overall sample mean vector (of length *d*).\n\"\"\"\nmean(M::MulticlassLDA) = mean(M.stats)\n\n\"\"\"\n    classmeans(M)\n\nGet the matrix comprised of class-specific means as columns (of size ``(d, m)``).\n\"\"\"\nclassmeans(M::MulticlassLDA) = classmeans(M.stats)\n\"\"\"\n    classweights(M)\n\nGet the weights of individual classes (a vector of length ``m``). If the samples are not weighted,\nthe weight equals the number of samples of each class.\n\"\"\"\nclassweights(M::MulticlassLDA) = classweights(M.stats)\n\"\"\"\nwithinclass_scatter(M)\n\n    Get the within-class scatter matrix (of size ``(d, d)``).\n\"\"\"\nwithclass_scatter(M::MulticlassLDA) = withclass_scatter(M.stats)\n\"\"\"\nbetweenclass_scatter(M)\n\n    Get the between-class scatter matrix (of size ``(d, d)``).\n\"\"\"\nbetweenclass_scatter(M::MulticlassLDA) = betweenclass_scatter(M.stats)\n\n\"\"\"\n    predict(M::MulticlassLDA, x)\n\nTransform input sample(s) in `x` to the output space of MC-LDA model `M`. Here, `x` can be either a sample vector or a matrix comprised of samples in columns.\n\"\"\"\npredict(M::MulticlassLDA, x::AbstractVecOrMat{T}) where {T<:Real} = M.proj'x\n\n\"\"\"\n    fit(MulticlassLDA, nc, X, y; ...)\n\nPerform multi-class LDA over a given data set `X` and collecttion of labels `y`.\n\nThis function returns the resultant multi-class LDA model as an instance of [`MulticlassLDA`](@ref).\n\n*Parameters*\n\n- `nc`:  the number of classes\n- `X`:   the matrix of input samples, of size `(d, n)`. Each column in `X` is an observation.\n- `y`:   the vector of class labels, of length `n`. Each element of `y` must be an integer between `1` and `nc`.\n\n**Keyword arguments**\n\n- `method`: The choice of methods:\n    - `:gevd`: based on generalized eigenvalue decomposition (*default*).\n    - `:whiten`: first derive a whitening transform from `Sw` and then solve the problem based on eigenvalue\n    decomposition of the whiten `Sb`.\n- `outdim`: The output dimension, i.e. dimension of the transformed space `min(d, nc-1)`\n- `regcoef`: The regularization coefficient (*default:* `1.0e-6`). A positive value `regcoef * eigmax(Sw)`\n    is added to the diagonal of `Sw` to improve numerical stability.\n- `covestimator_between`: Custom covariance estimator for between-class covariance (*default:* `SimpleCovariance()`).\n    The covariance matrix will be calculated as `cov(covestimator_between, #=data=#; dims=2, mean=zeros(#=...=#))`.\n    Custom covariance estimators, available in other packages, may result in more robust discriminants for data\n    with more features than observations.\n- `covestimator_within`:  Custom covariance estimator for within-class covariance (*default:* `SimpleCovariance()`).\n    The covariance matrix will be calculated as `cov(covestimator_within, #=data=#; dims=2, mean=zeros(nc))`.\n    Custom covariance estimators, available in other packages, may result in more robust discriminants for data\n    with more features than observations.\n\n**Notes:**\n\nThe resultant projection matrix ``P`` satisfies:\n```math\n\\\\mathbf{P}^T (\\\\mathbf{S}_w + \\\\kappa \\\\mathbf{I}) \\\\mathbf{P} = \\\\mathbf{I}\n```\nHere, ``\\\\kappa`` equals `regcoef * eigmax(Sw)`. The columns of ``P`` are arranged in descending order of\nthe corresponding generalized eigenvalues.\n\nNote that [`MulticlassLDA`](@ref) does not currently support the normalized version using ``\\\\mathbf{S}_w^*`` and\n``\\\\mathbf{S}_b^*`` (see [`SubspaceLDA`](@ref)).\n\"\"\"\nfunction fit(::Type{MulticlassLDA}, nc::Int, X::DenseMatrix{T}, y::AbstractVector{Int};\n             method::Symbol=:gevd,\n             outdim::Int=min(size(X,1), nc-1),\n             regcoef::T=T(1.0e-6),\n             covestimator_within::CovarianceEstimator=SimpleCovariance(),\n             covestimator_between::CovarianceEstimator=SimpleCovariance()) where T<:Real\n\n    multiclass_lda(multiclass_lda_stats(nc, X, y;\n                                        covestimator_within=covestimator_within,\n                                        covestimator_between=covestimator_between);\n                   method=method,\n                   regcoef=regcoef,\n                   outdim=outdim)\nend\n\nfunction multiclass_lda(S::MulticlassLDAStats{T};\n                        method::Symbol=:gevd,\n                        outdim::Int=min(S.dim, S.nclasses-1),\n                        regcoef::T=T(1.0e-6)) where T<:Real\n\n    P = mclda_solve(S.Sb, S.Sw, method, outdim, regcoef)\n    MulticlassLDA(P, P'S.cmeans, S)\nend\n\nmclda_solve(Sb::AbstractMatrix{T}, Sw::AbstractMatrix{T}, method::Symbol, p::Int, regcoef::T) where T<:Real =\n    mclda_solve!(copy(Sb), copy(Sw), method, p, regcoef)\n\nfunction mclda_solve!(Sb::AbstractMatrix{T},\n                      Sw::AbstractMatrix{T},\n                      method::Symbol, p::Int, regcoef::T) where T<:Real\n\n    p <= size(Sb, 1) || throw(ArgumentError(\"p cannot exceed sample dimension.\"))\n\n    if method == :gevd\n        regularize_symmat!(Sw, regcoef)\n        E = eigen!(Symmetric(Sb), Symmetric(Sw))\n        ord = sortperm(E.values; rev=true)\n        P = E.vectors[:, ord[1:p]]\n\n    elseif method == :whiten\n        W = _lda_whitening!(Sw, regcoef)\n        wSb = transpose(W) * (Sb * W)\n        Eb = eigen!(Symmetric(wSb))\n        ord = sortperm(Eb.values; rev=true)\n        P = W * Eb.vectors[:, ord[1:p]]\n\n    else\n        throw(ArgumentError(\"Invalid method name $(method)\"))\n    end\n    return P::Matrix{T}\nend\n\nfunction _lda_whitening!(C::AbstractMatrix{T}, regcoef::T) where T<:Real\n    n = size(C,1)\n    E = eigen!(Symmetric(C))\n    v = E.values\n    a = regcoef * maximum(v)\n    for i = 1:n\n        @inbounds v[i] = 1.0 / sqrt(v[i] + a)\n    end\n    return rmul!(E.vectors,  Diagonal(v))\nend\n\n#### SubspaceLDA\n\n\"\"\"Subspace LDA model type has following fields:\n- `projw`: the projection matrix of the subspace spanned by the between-class scatter\n- `projLDA`: the projection matrix of the subspace spanned by the within-class scatter\n- `λ`: the projection eigenvalues\n- `cmeans`: the class centroids\n- `cweights`: the class weights\n\"\"\"\nstruct SubspaceLDA{T<:Real} <: RegressionModel\n    projw::Matrix{T}\n    projLDA::Matrix{T}\n    λ::Vector{T}\n    cmeans::Matrix{T}\n    cweights::Vector{Int}\nend\n\n\"\"\"\n    size(M)\n\nGet the input (*i.e* the dimension of the observation space) and output (*i.e* the dimension of the subspace projection)\ndimensions of the model `M`.\n\"\"\"\nsize(M::SubspaceLDA) = (size(M.projw,1), size(M.projLDA, 2))\n\"\"\"\n    length(M)\n\nGet dimension of the LDA model.\n\"\"\"\nlength(M::SubspaceLDA) = size(M.projLDA, 2)\n\"\"\"\n    predict(M::SubspaceLDA, x)\n\nTransform input sample(s) in `x` to the output space of LDA model `M`.\nHere, `x` can be either a sample vector or a matrix comprised of samples in columns.\n\"\"\"\npredict(M::SubspaceLDA, x::AbstractVecOrMat{T}) where {T<:Real} = M.projLDA' * (M.projw' * x)\n\"\"\"\n    projection(M)\n\nGet the projection matrix.\n\"\"\"\nprojection(M::SubspaceLDA) = M.projw * M.projLDA\n\n\"\"\"\n    mean(M::SubspaceLDA)\n\nReturns the mean vector of the subspace LDA model `M`.\n\"\"\"\nmean(M::SubspaceLDA) = vec(sum(M.cmeans * Diagonal(M.cweights / sum(M.cweights)), dims=2))\n\n\"\"\"\n    eigvals(M::SubspaceLDA)\n\nGet the eigenvalues of the subspace LDA model `M`.\n\"\"\"\neigvals(M::SubspaceLDA) = M.λ\n\nclassmeans(M::SubspaceLDA) = M.cmeans\nclassweights(M::SubspaceLDA) = M.cweights\nfit(::Type{F}, X::AbstractMatrix{T}, nc::Int, label::AbstractVector{Int}) where {T<:Real, F<:SubspaceLDA} =\n    fit(F, X, label, nc)\n\n\"\"\"\n    fit(SubspaceLDA, X, labels; normalize=true)\n\nFit an subspace projection of LDA model using the equivalent of ``\\\\mathbf{S}_w^*`` and ``\\\\mathbf{S}_b^*```.\n\nNote: Subspace LDA also supports the normalized version of LDA via the `normalize` keyword.\n\"\"\"\nfunction fit(::Type{F}, X::AbstractMatrix{T},\n             label::AbstractVector{Int},\n             nc=maximum(label);\n             normalize::Bool=false) where {T<:Real, F<:SubspaceLDA}\n    d, n = size(X, 1), size(X, 2)\n    n ≥ nc || throw(ArgumentError(\"The number of samples is less than the number of classes\"))\n    length(label) == n || throw(DimensionMismatch(\"Inconsistent array sizes.\"))\n    # Compute centroids, class weights, and deviation from centroids\n    # Note Sb = Hb*Hb', Sw = Hw*Hw'\n    cmeans, cweights, Hw = center(X, label, nc)\n    dmeans = cmeans .- (normalize ? mean(cmeans, dims=2) : cmeans * (cweights / T(n)))\n    Hb = normalize ? dmeans : dmeans * Diagonal(convert(Vector{T}, sqrt.(cweights)))\n    if normalize\n        Hw /= T(sqrt(n))\n    end\n    # Project to the subspace spanned by the within-class scatter\n    # (essentially, PCA before LDA)\n    Uw, Σw, _ = svd(Hw, full=false)\n    keep = Σw .> sqrt(eps(T)) * maximum(Σw)\n    projw = Uw[:,keep]\n    pHb = projw' * Hb\n    pHw = projw' * Hw\n    λ, G = lda_gsvd(pHb, pHw, cweights)\n    SubspaceLDA(projw, G, λ, cmeans, cweights)\nend\n\n# Reference: Howland & Park (2006), \"Generalizing discriminant analysis\n# using the generalized singular value decomposition\", IEEE\n# Trans. Patt. Anal. & Mach. Int., 26: 995-1006.\nfunction lda_gsvd(Hb::AbstractMatrix{T}, Hw::AbstractMatrix{T}, cweights::AbstractVector{Int}) where T<:Real\n    nc = length(cweights)\n    K = vcat(Hb', Hw')\n    P, R, Q = svd(K, full=false)\n    keep = R .> sqrt(eps(T))*maximum(R)\n    R = R[keep]\n    Pk = P[1:nc, keep]\n    U, ΣA, W = svd(Pk)\n    ncnz = sum(cweights .> 0)\n    G = Q[:,keep]*(Diagonal(1 ./ R) * W[:,1:ncnz-1])\n    # Normalize\n    Gw = G' * Hw\n    nrm = Gw * Gw'\n    G = G ./ reshape(sqrt.(diag(nrm)), 1, ncnz-1)\n    # Also get the eigenvalues\n    Gw = G' * Hw\n    Gb = G' * Hb\n    λ = diag(Gb * Gb')./diag(Gw * Gw')\n    λ, G\nend\n\nfunction center(X::AbstractMatrix{T}, label::AbstractVector{Int}, nc=maximum(label)) where T<:Real\n    d, n = size(X,1), size(X,2)\n    # Calculate the class weights and means\n    cmeans = zeros(T, d, nc)\n    cweights = zeros(Int, nc)\n    for j = 1:n\n        k = label[j]\n        for i = 1:d\n            cmeans[i,k] += X[i,j]\n        end\n        cweights[k] += 1\n    end\n    for j = 1:nc\n        cw = cweights[j]\n        cw == 0 && continue\n        for i = 1:d\n            cmeans[i,j] /= cw\n        end\n    end\n    # Compute differences from the means\n    dX = Matrix{T}(undef, d, n)\n    for j = 1:n\n        k = label[j]\n        for i = 1:d\n            dX[i,j] = X[i,j] - cmeans[i,k]\n        end\n    end\n    cmeans, cweights, dX\nend\n", "meta": {"hexsha": "08d8738eda56f517cbfd25e52b12c5700738eb5d", "size": 17998, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lda.jl", "max_stars_repo_name": "KronosTheLate/MultivariateStats.jl", "max_stars_repo_head_hexsha": "99ee965df3a8e136ff2d0fcb10456b434e1f9001", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lda.jl", "max_issues_repo_name": "KronosTheLate/MultivariateStats.jl", "max_issues_repo_head_hexsha": "99ee965df3a8e136ff2d0fcb10456b434e1f9001", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lda.jl", "max_forks_repo_name": "KronosTheLate/MultivariateStats.jl", "max_forks_repo_head_hexsha": "99ee965df3a8e136ff2d0fcb10456b434e1f9001", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3296296296, "max_line_length": 332, "alphanum_fraction": 0.6467940882, "num_tokens": 5171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966656805269, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7908659362694771}}
{"text": "# Density utilities\n# Author: Gabrio Rizzuti, rizzuti.gabrio@gatech.edu\n# Date: August 2020\n\nexport sample_gaussmixture, negLogDensity_gaussmixture\n\nfunction sample_gaussmixture(nsamples::Int64, mu::Array{Float32, 2}, sigma2::Array{Float32, 1})\n    nmodes = length(sigma2)\n    X = Array{Float32, 4}(undef, (1, 1, 2, nsamples))\n    for i = 1:nsamples\n        imode = rand(1:nmodes)\n        X[1, 1, :, i] = mu[imode, :]+sqrt(sigma2[imode])*randn(Float32, 2)\n    end\n    return X\nend\n\nfunction negLogDensity_gaussmixture(X::Array{Float32, 4}, mu::Array{Float32, 2}, sigma2::Array{Float32, 1}; ε::Float32 = 1f-10)\n    nmodes = length(sigma2)\n    p = zeros(Float32, 1, 1, 1, size(X, 4))\n    g = zeros(Float32, size(X))\n    for i = 1:nmodes\n        p_i = exp.(-((X[:, :, 1:1, :].-mu[i, 1]).^2f0+(X[:, :, 2:2, :].-mu[i, 2]).^2f0)/(2f0*sigma2[i]))/(nmodes*2f0*pi*sigma2[i])\n        p += p_i\n        g += -p_i.*(X.-reshape(mu[i, :], 1, 1, 2, 1))/sigma2[i]\n    end\n    return -log.(p.+ε), -g./(p.+ε)\nend\n", "meta": {"hexsha": "a61628e8e712c024401b43c70bdfaa0699e4e481", "size": 994, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "rizzuti2020SEGuqavp/src/utils/density_utils.jl", "max_stars_repo_name": "slimgroup/Software.SEG2020", "max_stars_repo_head_hexsha": "e7dd34d803a4936b369b7d49f7a992445121c533", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-04-25T15:00:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T22:29:18.000Z", "max_issues_repo_path": "rizzuti2020SEGuqavp/src/utils/density_utils.jl", "max_issues_repo_name": "slimgroup/Software.SEG2020", "max_issues_repo_head_hexsha": "e7dd34d803a4936b369b7d49f7a992445121c533", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rizzuti2020SEGuqavp/src/utils/density_utils.jl", "max_forks_repo_name": "slimgroup/Software.SEG2020", "max_forks_repo_head_hexsha": "e7dd34d803a4936b369b7d49f7a992445121c533", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-04-27T09:14:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-06T10:30:24.000Z", "avg_line_length": 35.5, "max_line_length": 130, "alphanum_fraction": 0.5955734406, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7908626951676567}}
{"text": "\"\"\"\n    Dᶜ(N, Δ)\n\nReturns a discrete 1D derivative operator for taking the derivative of a face-centered field with `N+1` grid points and `Δ` grid spacing and producing a cell-centered field with `N` grid points.\n\"\"\"\nfunction Dᶜ(N, Δ)\n    D = zeros(N, N+1)\n    for k in 1:N\n        D[k, k]   = -1.0\n        D[k, k+1] =  1.0\n    end\n    D = 1/Δ * D\n    return D\nend\n\n\"\"\"\n    Dᶠ(N, Δ)\n\nReturns a discrete 1D derivative operator for taking the derivative of a cell-centered field with `N` grid points and `Δ` grid spacing and producing a face-centered field with `N+1` grid points.\n\"\"\"\nfunction Dᶠ(N, Δ)\n    D = zeros(N+1, N)\n    for k in 2:N\n        D[k, k-1] = -1.0\n        D[k, k]   =  1.0\n    end\n    D = 1/Δ * D\n    return D\nend\n\nfunction cell_to_cell_derivative(D, data)\n    face_data = D * data\n    cell_data = 0.5 .* (@view(face_data[1:end-1]) + @view(face_data[2:end]))\n    return cell_data\nend\n", "meta": {"hexsha": "c227bf1d4a16f3c874546e6730e6f64c0e654e12", "size": 901, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/differentiation_operators.jl", "max_stars_repo_name": "CliMA/ClimateParameterizations.jl", "max_stars_repo_head_hexsha": "1263e2edefced4e03e925d6bfa60ba1f1940e8c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2020-12-23T06:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:05:51.000Z", "max_issues_repo_path": "src/differentiation_operators.jl", "max_issues_repo_name": "CliMA/OceanParameterizations.jl", "max_issues_repo_head_hexsha": "5942c66ba8724b9661db170acb239ca3a2abd5c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-12-05T02:43:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T14:27:03.000Z", "max_forks_repo_path": "src/differentiation_operators.jl", "max_forks_repo_name": "ali-ramadhan/ClimateParameterizations.jl", "max_forks_repo_head_hexsha": "1263e2edefced4e03e925d6bfa60ba1f1940e8c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-17T18:06:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T18:06:40.000Z", "avg_line_length": 25.0277777778, "max_line_length": 194, "alphanum_fraction": 0.6037735849, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542829224748, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.7907861836536496}}
{"text": "\"\"\"\nCheck if a solution x is in the core of G. Namely,\n\n    - ∑ x < v(N)\n    - ∑ₛ x < v(S) ∀ S\n\n\"\"\"\nfunction isincore(x::Vector{Float64}, G::Game)\n    if sum(x) != G.v(G.N) return false end\n\n    for S in subsets(G.N)\n        if sum(x[S]) < G.v(S) return false end\n    end\n\n    return true\n\nend", "meta": {"hexsha": "1474d46a599bfc53c347559ac57464c86a332712", "size": 293, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solutions/core.jl", "max_stars_repo_name": "NoFishLikeIan/CoordinationGames.jl", "max_stars_repo_head_hexsha": "fa1939552482c785af3cbe3e3a80dd714180d115", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-03-20T18:53:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T22:40:56.000Z", "max_issues_repo_path": "src/solutions/core.jl", "max_issues_repo_name": "NoFishLikeIan/CoordinationGames.jl", "max_issues_repo_head_hexsha": "fa1939552482c785af3cbe3e3a80dd714180d115", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-23T16:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T10:15:39.000Z", "max_forks_repo_path": "src/solutions/core.jl", "max_forks_repo_name": "NoFishLikeIan/CoordinationGames.jl", "max_forks_repo_head_hexsha": "fa1939552482c785af3cbe3e3a80dd714180d115", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-26T18:15:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T18:15:24.000Z", "avg_line_length": 17.2352941176, "max_line_length": 50, "alphanum_fraction": 0.542662116, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9539661028358093, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.7907795325265614}}
{"text": "@doc raw\"\"\"\n```\nFrankot()\n```\nDefines the Frankot integrator which contians the Frankot-Chellappa method of\nintegration. The Frankot-Chellappa method is a fast, reliable method for\nintegration surface normals while enforcing integrability using Fourier methods.\n# Output\n`Frankot()` returns a Frankot integrator which can then be called to run the\nFrankot-Chellappa method on a gradient field.\n# Details\nFrankot-Chellappa method uses Fourier methods to attempt to solve the Poission\nequation ``\\nabla^2z = \\partial_up + \\partial_vq``. By taking the Fourier transform\nof both sides we get:\n```math\n−(\\omega^2_u + \\omega^2_v)\\hat{z}(\\omega_u, \\omega_v) = \\imath \\omega_u\\hat{p}\n(\\omega_u, \\omega_v) + \\imath \\omega_v\\hat{q}(\\omega_u, \\omega_v)\n```\nBy rearranging the above equation we arrive at an equation for ``\\hat{z}``;\n```math\n\\hat{z}(\\omega_u, \\omega_v) = \\frac{\\omega_u\\hat{p}(\\omega_u, \\omega_v) +\n\\omega_v\\hat{q}(\\omega_u, \\omega_v)}{\\imath(\\omega^2_u + \\omega^2_v)}\n```\nFrom which the final surface can be found by taking the inverse Fourier transform\nof ``\\hat{z}``.\n\nDue to the way ``(\\omega_u, \\omega_v)`` is defined the algorithm works best when\nthe input dimensions are odd in length. To accommodate this the integrator will\npad the edge of the inputs if they are even before running the algorithm. This\npadding will be removed before returning a value hence output size will be\nunaffected.\n# Parameters\n`Frankot` integrator take no parameters.\n# Example\nThe following example demonstrates  the use of the `Frankot` integrator.\n```julia\nusing ShapeFromShading, Makie\n\n# Generate synthetic gradients\np, q = synthetic_gradient(SynthSphere(38), img_size = 151)\n\n# Create a Frankot() integrator\nfrankot = Frankot()\n\n# Calculate the heightmap from the gradients\nZ = frankot(p, q)\n\n# Normalize to maximum of 1 (not necessary but makes displaying easier)\nZ = Z./maximum(Z)\n\n# Display using Makie (Note: Makie can often take several minutes first time)\nr = 0.0:0.1:4\nsurface(r, r, Z)\n```\n# Reference\n[1] R. T. Frankot and R. Chellappa, \"A method for enforcing integrability in shape from shading algorithms,\" in IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 10, no. 4, pp. 439-451, July 1988. [doi: 10.1109/34.3909](https://doi.org/10.1109/34.3909 )\n\"\"\"\nfunction (scheme::Frankot)(pin::AbstractArray, qin::AbstractArray)\n    # Resize grid to be odd dimensions. (Requared to setup transofrm values)\n    M, N = size(pin)\n    p = zeros(Complex{Float64}, M + 1 - (M%2), N + 1 - (N%2))\n    p[1:M, 1:N] = Complex{Float64}.(pin)\n    q = zeros(Complex{Float64}, M + 1 - (M%2), N + 1 - (N%2))\n    q[1:M, 1:N] = Complex{Float64}.(qin)\n\n    wx, wy = setup_transform_values(N,M)\n    fft!(p)\n    fft!(q)\n    Z = zeros(Complex{Float64}, size(p))\n    Z = (-1im .* wx .* p .+ 1im .* wy .* q) ./ (2 .* π .* (wx.^2 .+ wy.^2 .+ eps()))\n    ifft!(Z)\n    Z = abs.(Z)\n    return Z[1:M,1:N]\nend\n\n@doc raw\"\"\"\n```\nPath()\n```\nCreates a `Path()` integrator which utilises the average of two path integrals\nalong varying paths. Each path integral reconstructs the surface with\naccumulating error along the path, hence averaging two different paths can\nminimise this error, although the method still suffers if the gradient field is\nnot integrable at some points.\n# Output\n`Path()` returns a Path integrator which can then be called to integrate a\ngradient field.\n# Details\nUnder the assumption that the surface normals are approximately integrable\neverywhere (``\\frac{\\partial p}{\\partial y}\\approx\\frac{\\partial q}{\\partial x}``),\nthen surface can be reconstructed using the path integral defined as:\n```math\nz(x,y)=\\oint_c\\left(\\frac{\\partial z}{\\partial x},\\frac{\\partial z}{\\partial y}\\right)\\cdot dl\n```\nWhich can be broken into two integrals representing the value at each point on\nthe surface as shown below for a path which integrates along the first column\nthen along the row.\n```math\nz(u,v)=\\int_0^v\\frac{\\partial z}{\\partial y}(0,y)dy + \\int_0^u\\frac{\\partial z}{\\partial x}(x,v)dx\n```\nThe second path used in the algorithm is simply the transpose of the first,\nintegrating along the first row then down the column represented mathematically as:\n```math\nz(u,v)=\\int_0^u\\frac{\\partial z}{\\partial x}(x,0)dx + \\int_0^v\\frac{\\partial z}{\\partial y}(u,y)dy\n```\nThe algorithm can be written, then discretised as shown below:\n```math\n\\begin{gathered}\nz(u,v)=\\frac{1}{2}\\left(\\int_0^v\\frac{\\partial z}{\\partial y}(0,y)dy + \\int_0^u\\frac{\\partial z}{\\partial x}(x,v)dx + \\int_0^u\\frac{\\partial z}{\\partial x}(x,0)dx + \\int_0^v\\frac{\\partial z}{\\partial y}(u,y)dy\\right)\\\\\nz(u,v)=\\frac{1}{2}\\left(\\sum_{i=0}^vq(0,i) + \\sum_{j=0}^up(j,v) + \\sum_{j=0}^up(j,0) + \\sum_{i=0}^vq(u,i)\\right)\\\\\nz(u,v)=\\frac{1}{2}\\left(\\sum_{i=0}^v(q(0,i) + q(u,i)) + \\sum_{j=0}^u(p(j,0) + p(j,v))\\right)\\\\\n\\end{gathered}\n```\nIt is important to note as mentioned above if there are non-integrable points in\nthe normal field then artefacts can appear in the reconstruction. This is\nseen in the example below where the otherwise smooth sphere appears \"spiky\".\nThis can be corrected post reconstruction by smoothing but ideally a different\nintegrator should be used.\n# Parameters\n`Path` integrator take no parameters.\n# Example\nThe following example demonstrates the use of the `Path` integrator.\n```julia\nusing ShapeFromShading, Makie\n\n# Generate synthetic gradients\np, q = synthetic_gradient(SynthSphere(38), img_size = 151)\n\n# Create a Path() integrator\npath = Path()\n\n# Calculate the heightmap from the gradients\nZ = path(p, q)\n\n# Normalize to maximum of 1 (not necessary but makes displaying easier)\nZ = Z./maximum(Z)\n\n# Display using Makie (Note: Makie can often take several minutes first time)\nr = 0.0:0.1:4\nsurface(r, r, Z)\n```\n# Reference\n[1] D. Forsyth and J. Ponce, Computer vision: a modern approach. Upper Saddle River, N.J: Prentice Hall, 2003, pp. 84-86.\n\"\"\"\nfunction (scheme::Path)(p::AbstractArray, q::AbstractArray)\n    R, C = size(p)\n    Z₁ = zeros(Float64, size(p))\n    Z₂ = zeros(Float64, size(p))\n\n    #path 1\n    for i = 2:R\n        Z₁[i,1] = Z₁[i-1,1] - q[i,1]\n    end\n    for i = 1:R\n        for j = 2:C\n            Z₁[i,j] = Z₁[i,j-1] + p[i,j]\n        end\n    end\n\n    #path 2\n    for i = 2:C\n        Z₂[1,i] = Z₂[1,i-1] + p[1,i]\n    end\n    for i = 2:R\n        for j = 1:C\n            Z₂[i,j] = Z₂[i-1,j] - q[i,j]\n        end\n    end\n    Z = (Z₁ .+ Z₂) / 2\n    return Z\nend\n\n@doc raw\"\"\"\n```\nSplitPath()\n```\nCreates a `SplitPath()` integrator which utilizes the average of two path integrals\nalong varying paths averaging the value at each step. Each path integral\nreconstructs the surface with accumlating error along the path, hence averaging\ntwo different paths at each step reduces the global error at the cost of local\nerror, although the method still suffers if the gradient field is not integrable\nat some points it does less so the `Path()` from which it extends.\n# Output\n`SplitPath()` returns a SplitPath integrator which can then be called to integrate\na gradient field.\n# Details\nUnder the assumption that the surface normals are approximately integrable\neverywhere (``\\frac{\\partial p}{\\partial y}\\approx\\frac{\\partial q}{\\partial x}``),\nthen surface can be reconstructed using the path integral defined as:\n```math\nz(x,y)=\\oint_c\\left(\\frac{\\partial z}{\\partial x},\\frac{\\partial z}{\\partial y}\\right)\\cdot dl\n```\nBy expanding on this principle and the discreate summation from `Path()` we can\narrive at the discreate expresion for the value at each point, assuming all\nvalues prior to that point have been calculated, as follows:\n```math\nz_{u,v} = \\frac{1}{2}(z_{u-1,v}+p_{u-1,v}+z_{u,v-1}+q_{u,v-1})\n```\nAs with other similar methods (see `Horn()`) care must be taken with regards to\nboundaries which can be calculated, to a constant value ``z(0,0)`` which is assumed\nto be the zero point, using:\n```math\n\\begin{gathered}\nz_{u,0} = z_{u-1,0}+p_{u-1,0}\\\\\nz_{0,v} = z_{0,v-1}+q_{0,v-1}\n\\end{gathered}\n```\nIt is important to note as mentioned above if there are non-integrable points in\nthe normal field then artefacts can appear in the reconstruction. These errors\ngradually average out but will lead to \"streaks\" appearing in the reconstruction.\nThis is seen in the example below where the otherwise smooth sphere appears has\nripple like structures pointing toward to top right corner. This can be corrected\npost reconstruction by smoothing but ideally a different integrator should be used.\nIt is also interesting to note the parallels between this method and the Horn\nand Brooks method, with this method being effectively the forward component of\nHorn's method. As such this algorithm provided a useful middle ground between\ndirect integration algorithms and iterative algorithms such as the Horn and Brooks\nmethod.\n# Parameters\n`SplitPath` integrator take no parameters.\n# Example\nThe following example demonstrates the use of the `SplitPath` integrator.\n```julia\nusing ShapeFromShading, Makie\n\n# Generate synthetic gradients\np, q = synthetic_gradient(SynthSphere(38), img_size = 151)\n\n# Create a Path() integrator\nsplitPath = SplitPath()\n\n# Calculate the heightmap from the gradients\nZ = splitPath(p, q)\n\n# Normalize to maximum of 1 (not necessary but makes displaying easier)\nZ = Z./maximum(Z)\n\n# Display using Makie (Note: Makie can often take several minutes first time)\nr = 0.0:0.1:4\nsurface(r, r, Z)\n```\n# Reference\n[1] D. Forsyth and J. Ponce, Computer vision: a modern approach. Upper Saddle River, N.J: Prentice Hall, 2003, pp. 84-86.\n[2] B. Horn and M. Brooks, \"The variational approach to shape from shading\", Computer Vision, Graphics, and Image Processing, vol. 33, no. 2, pp. 174-208, 1986. [doi: 10.1016/0734-189x(86)90114-3](https://doi.org/10.1016/0734-189x(86)90114-3 )\n\"\"\"\nfunction (scheme::SplitPath)(p::AbstractArray, q::AbstractArray)\n    R, C = size(p)\n    Z = zeros(Float64, size(p))\n    for i = 2:R\n        Z[i,1]=Z[i-1,1] + q[i,1]\n        Z[1,i]=Z[1,i-1] - p[1,i]\n    end\n    for i = 2:R\n        for j = i:R\n            Z[i,j] = ((Z[i,j-1] + p[i,j]) + (Z[i-1,j] - q[i,j])) / 2\n            Z[j,i] = ((Z[j,i-1] + p[j,i]) + (Z[j-1,i] - q[j,i])) / 2\n        end\n    end\n    return Z\nend\n\n@doc raw\"\"\"\n```\nHorn(ϵ::Real = 1.0, max_iter::Real = 10000)\n```\nImplements the Horn and Brook's method of integrating surface normals. This\nalgorithm offers an iterative solution to the Poisson equation describing the\nsurface providing good reconstructions under most conditions.\n# Output\n`Horn()` returns a Horn integrator which can then be called to integrate\na gradient field.\n# Details\nThe Horn and Brook's method attempts to solve the Poisson equation ``\\nabla^2z = \\partial_up + \\partial_vq``\nby the discretization given below:\n```math\nz_{u+1,v}+z_{u,v+1}+z_{u-1,v}+z_{u,v-1}-4z_{u,v}=\\frac{p_{u+1,v}-p_{u-1,v}}{2}+\\frac{q_{u,v+1}-q_{u,v-1}}{2}\n```\nWhich can be rearranged to give the iterative scheme provided by:\n```math\nz_{u,v}^{k+1}= \\frac{z_{u+1,v}^k + z_{u,v+1}^k + z_{u-1,v}^k + z_{u,v-1}^k}{4} - \\frac{p_{u+1,v}-p_{u-1,v}}{8} - \\frac{q_{u,v+1}-q_{u,v-1}}{8}\n```\nThis scheme will always converge to a solution however the rate of convergence\nmay depend upon the initial solution. This implementation will initilize with a\nzero solution. Neumann boundary conditions are imposed at the edges where the\nscheme would otherwise go out of bounds.\n# Parameters\nThe function parameters are described in more detail below.\n##  `Max_iter`:\nAn `Int` which controls the number of iterations the algorithm will run for.\n## `ϵ`:\nA `Real` representing the distance between pixels. This will Control how tall\nthe final reconstruction is relative the array grid.\n# Example\nThe following example demonstrates the use of the `Horn` integrator.\n```julia\nusing ShapeFromShading, Makie\n\n# Generate synthetic gradients\np, q = synthetic_gradient(SynthSphere(38), img_size = 151)\n\n# Create a Horn() integrator\nhorn = Horn(ϵ = 0.03, max_iter = 10000)\n\n# Calculate the heightmap from the gradients\nZ = horn(p, q)\n\n# Display using Makie (Note: Makie can often take several minutes first time)\nr = 0.0:0.1:4\nsurface(r, r, Z)\n```\n# Reference\n[1] B. Horn and M. Brooks, \"The variational approach to shape from shading\", Computer Vision, Graphics, and Image Processing, vol. 33, no. 2, pp. 174-208, 1986. [doi: 10.1016/0734-189x(86)90114-3](https://doi.org/10.1016/0734-189x(86)90114-3 )\n\"\"\"\nfunction (scheme::Horn)(p::AbstractArray, q::AbstractArray)\n    iter = copy(scheme.max_iter)\n    ϵ = copy(scheme.ϵ)\n    Z = zeros(Float64, size(p))\n    Zᵏ⁺¹ = zeros(Float64, size(p))\n    h = zeros(Float64, size(p))\n    v = zeros(Float64, size(p))\n    hv = zeros(Float64, size(p))\n    R, C = size(p)\n    for i = 1:R\n        Z[i,1] = p[i,1]\n        Z[i,R] = p[i,R]\n    end\n    for i = 1:C\n        Z[1,i] = q[1,i]\n        Z[C,i] = q[C,i]\n    end\n    for i = 2:(R-1)\n        for j = 2:(C-1)\n            h[i,j] = (p[i,j+1] - p[i,j-1]) / 2.0\n            v[i,j] = (q[i+1,j] - q[i-1,j]) / 2.0\n            hv[i,j] = (ϵ / 4) * (h[i,j] - v[i,j])\n        end\n    end\n    for k = 1:iter\n        copyto!(Zᵏ⁺¹, Z)\n        for i = 2:(R-1)\n            for j = 2:(C-1)\n                Zᵏ⁺¹[i,j] = (Z[i-1,j] + Z[i+1,j] + Z[i,j-1] + Z[i,j+1]) / 4.0\n                Zᵏ⁺¹[i,j] = Zᵏ⁺¹[i,j] - hv[i,j]\n            end\n        end\n        Z = Zᵏ⁺¹\n    end\n    return Z\nend\n\n@doc raw\"\"\"\n```\nDurou(ϵ::Real = 1.0, max_iter::Real = 1000)\n```\nImplements the Durou and Courteille method of integrating surface normals. This\nalgorithm offers an iterative solution to the Poisson equation describing the\nsurface extending Horn and Brook's method by improving the boundary approximation\nand providing good reconstructions under most conditions.\n# Output\n`Durou()` returns a Durou integrator which can then be called to integrate\na gradient field.\n# Details\nTheDurou and Courteille's method attempts to solve the Poisson equation\n``\\nabla^2z = \\partial_up + \\partial_vq`` by the discretization given below:\n```math\nz_{u+1,v}+z_{u,v+1}-2z_{u,v}=\\frac{p_{u+1,v}+p_{u,v}}{2}+\\frac{q_{u,v+1}+q_{u,v}}{2}\n```\nWhich can be rearranged to give the iterative scheme provided by:\n```math\nz_{u,v}^{k+1}= \\frac{z_{u+1,v}^k + z_{u,v+1}^k}{2} - \\frac{p_{u+1,v}+p_{u,v}}{4} - \\frac{q_{u,v+1}+q_{u,v}}{4}\n```\nThis scheme will always converge to a solution however the rate of convergence\nmay depend upon the initial solution. This implementation will initialize with a\nzero solution. Natural boundary conditions are imposed at the edges using the\ncondition ``\\partial_uz-p+\\partial_v-q=0``. Although faster then the Horn and Brook's\nmethod and better at handling boundaries, it can generate a worse solution under\nsome conditions.\n# Parameters\nThe function parameters are described in more detail below.\n##  `Max_iter`:\nAn `Int` which controls the number of iterations the algorithm will run for.\nthe range [0,1].\n## `ϵ`:\nA `Real` representing the distance between pixels. This will Control how tall\nthe final reconstruction is relative the array grid.\n# Example\nThe following example demonstrates the use of the `Durou` integrator.\n```julia\nusing ShapeFromShading, Makie\n\n# Generate synthetic gradients\np, q = synthetic_gradient(SynthSphere(38), img_size = 151)\n\n# Create a Durou() integrator\ndurou = Durou(ϵ = 0.03, max_iter = 10000)\n\n# Calculate the heightmap from the gradients\nZ = durou(p, q)\n\n# Display using Makie (Note: Makie can often take several minutes first time)\nr = 0.0:0.1:4\nsurface(r, r, Z)\n```\n# Reference\n[1] Y. Quéau, J. Durou and J. Aujol, \"Normal Integration: A Survey\", Journal of Mathematical Imaging and Vision, vol. 60, no. 4, pp. 576-593, 2017. [doi: 10.1007/s10851-017-0773-x](https://doi.org/10.1007/s10851-017-0773-x )\n\"\"\"\nfunction (scheme::Durou)(p::AbstractArray, q::AbstractArray)\n    iter = copy(scheme.max_iter)\n    ϵ = copy(scheme.ϵ)\n    Z = zeros(Float64, size(p))\n    Zᵏ⁺¹ = zeros(Float64, size(p))\n    h = zeros(Float64, size(p))\n    v = zeros(Float64, size(p))\n    hv = zeros(Float64, size(p))\n    R, C = size(p)\n    for i = 1:(R-1)\n        for j = 1:(C-1)\n            h[i,j] = (p[i,j+1] + p[i,j]) / 2\n            v[i,j] = (q[i+1,j] + q[i,j]) / 2\n            hv[i,j] = (ϵ / 2) * (h[i,j] - v[i,j])\n        end\n    end\n    for k = 1:iter\n        copyto!(Zᵏ⁺¹, Z)\n        for i = 1:(R-1)\n            for j = 1:(C-1)\n                Zᵏ⁺¹[i,j] = (Z[i+1,j] + Z[i,j+1]) / 2\n                Zᵏ⁺¹[i,j] = Zᵏ⁺¹[i,j] - hv[i,j]\n            end\n        end\n        Z = Zᵏ⁺¹\n    end\n    return Z\nend\n\n# Generates matricies Dᵤ⁺, Dᵤ⁻, Dᵥ⁺ and Dᵥ⁻ as per eq 11, 12, 13, 14 and 17\nfunction gen_matrix(Dᵤ⁺, Dᵤ⁻, Dᵥ⁺, Dᵥ⁻,T,mask)\n    U,V = size(mask)\n    for i in CartesianIndices(mask)\n        #u+\n        if i[1] + 1 <= U && mask[i] == 1 && mask[i[1]+1,i[2]] == 1\n            Dᵤ⁺[i[1]+(i[2]-1)*U, i[1]+(i[2]-1)*U] = -1.0\n            Dᵤ⁺[i[1]+(i[2]-1)*U, i[1]+(i[2]-1)*U+1] = 1.0\n        end\n        #u-\n        if i[1] - 1 > 0 && mask[i] == 1 && mask[i[1]-1,i[2]] == 1\n            Dᵤ⁻[i[1]+(i[2]-1)*U, i[1]+(i[2]-1)*U] = 1.0\n            Dᵤ⁻[i[1]+(i[2]-1)*U, i[1]+(i[2]-1)*U-1] = -1.0\n        end\n        #v+\n        if i[2] + 1 <= V && mask[i] == 1 && mask[i[1],i[2]+1] == 1\n            Dᵥ⁺[i[1]+(i[2]-1)*V, i[1]+(i[2]-1)*V] = -1.0\n            Dᵥ⁺[i[1]+(i[2]-1)*V, i[1]+(i[2])*V] = 1.0\n        end\n        #v-\n        if i[2] - 1 > 0 && mask[i] == 1 && mask[i[1],i[2]-1] == 1\n            Dᵥ⁻[i[1]+(i[2]-1)*V, i[1]+(i[2]-1)*V] = 1.0\n            Dᵥ⁻[i[1]+(i[2]-1)*V, i[1]+(i[2]-2)*V] = -1.0\n        end\n    end\nend\n\n@doc raw\"\"\"\n```\nQuadratic(z::AbstractArray, λ::AbstractArray = fill(10.0^-6, size(z)), mask::AbstractArray = fill(1.0, size(z)))\n```\nImplements the quadratic variational least squared method proposed by Aujol, Durou\nand Quéau. The algorithm solves the least squares system generated from minimizing\na fidelity term ``\\mathcal{F}(z) = \\iint_{(u,v)\\in \\Omega}\\Phi(||\\nabla z(u,v) - g(u,v)||)dudv``\nand a regularization term ``\\mathcal{R}(z) = \\iint_{(u,v)\\in \\Omega}\\lambda \\left[z(u,v)-z^0(u,v)\\right]^2dudv``\nwhere ``\\Phi(s) = s^2``. This method is able to quickly produce good solutions on\na smooth surface and can easily handle non-rectangular domains or sub-divided\ndomains and can provide a good starting solution for other algorithms.\n# Output\n`Quadratic()` returns a Quadratic integrator which can then be called to run the\nquadratic method on a gradient field.\n# Details\nAs mentioned above the quadratic variational least squared method aims to minimize\na fidelity term ``\\mathcal{F}(z) = \\iint_{(u,v)\\in \\Omega}\\Phi(||\\nabla z(u,v) - g(u,v)||)dudv``\nand a regulization term ``\\mathcal{R}(z) = \\iint_{(u,v)\\in \\Omega}\\lambda \\left[z(u,v)-z^0(u,v)\\right]^2dudv``\nwhere ``\\Phi(s) = s^2``.\n\nThis leads to the minimization problem given by:\n```math\nmin\\iint_{(u,v)\\in \\Omega}||\\nabla z(u,v)-\\mathbf{g}(u,v)||^2+\\lambda(u,v)\\left[z(u,v)-z^0(u,v)\\right]^2dudv\n```\nBy discretizing the problem we can arrive at the functional:\n```math\n\\begin{aligned}\nE(z) = \\frac{1}{2}\\Big(\\sum_{(u,v)\\in \\Omega_u^+}[\\partial_u^+z_{u,v}-p_{u,v}]^2 \\\\+ \\sum_{(u,v)\\in \\Omega_u^-}[\\partial_u^-z_{u,v}-p_{u,v}]^2 \\\\+ \\sum_{(u,v)\\in \\Omega_v^+}[\\partial_v^+z_{u,v}-q_{u,v}]^2 \\\\+ \\sum_{(u,v)\\in \\Omega_v^-}[\\partial_v^-z_{u,v}-q_{u,v}]^2\\Big) \\\\+ \\sum_{(u,v)\\in \\Omega}[z_{u,v}-z^0_{u,v}]^2\n\\end{aligned}\n```\nwhere ``\\Omega_u^+`` represents the domain where ``(u,v)\\in\\{(u,v)\\in\\Omega|(u,v)(u+1,v)\\in\\Omega\\}`` etc..\nUsing this definition the discrete differences can be converted into matrix form,\nwhere ``p_{u,v}=z_{u+1,v}-z_{u,v}`` is the forward difference in the u direction etc.\nThis data is then stacked into three vectors; ``\\mathbf{z},\\mathbf{p},\\mathbf{q}\\in\\R^{|\\Omega|}``.\nThus the matrix reresenting each of these is defined as below where m(i) is the\nmapping of the ith element of this vector to its corresponding point in ``(u,v)``\nand ``D_u^+`` is a ``|\\Omega|\\times|\\Omega|`` matrix.\n```math\nD_u^+[i,j]=\\begin{cases}\n   0 &\\text{if } m(i)\\notin\\Omega_u^+ \\text{or } j \\ne i \\text{or } j \\ne i+1\\\\\n   -1 &\\text{if } j = i \\text {and } m(i)\\in\\Omega_u^+\\\\\n   1 &\\text{if } j = i+1 \\text {and } m(i)\\in\\Omega_u^+\n\\end{cases}\n```\nFor a 2X2 domain this looks like:\n```math\nD_u^+ = \\begin{bmatrix}\n   -1 & 1 & 0 & 0 \\\\\n   0 & 0 & 0 & 0 \\\\\n   0 & 0 & -1 & 1 \\\\\n   0 & 0 & 0 & 0\n\\end{bmatrix}\n```\nThe other three discrete differences matrices are similarly defined from there\ndefinitions to be ``D_u^-``, ``D_v^+`` and ``D_v^-``. These can then be used to\nredefine the minimization problem to be in the form:\n```math\nE(\\mathbf{z})=\\frac{1}{2}\\left(||D_u^+\\mathbf{z}-\\mathbf{p}||^2+||D_u^-\\mathbf{z}-\\mathbf{p}||^2+||D_v^+\\mathbf{z}-\\mathbf{q}||^2+||D_v^-\\mathbf{z}-\\mathbf{q}||^2\\right)+||\\Lambda(\\mathbf{z}-\\mathbf{z}^0)||^2\n```\nWhere ``\\Lambda`` is the ``|\\Omega|\\times|\\Omega|`` diagonal matrix containing\nthe values of ``\\sqrt{\\lambda_{u,v}}``. Using the above definitions the negative\nLaplacian matrix can then be defined as:\n```math\nL=\\frac{1}{2}[D_u^{+\\top}D_u^++D_u^{-\\top}D_u^-+D_v^{+\\top}D_v^++D_v^{-\\top}D_v^-]\n```\nFinally the least minimization problem can be represented in the form of a least\nsquares problem of the form ``A\\mathbf{z}=\\mathbf{b}`` where:\n```math\n\\begin{gathered}\nA=L+\\Lambda^2\\\\\n\\mathbf{b}=\\frac{1}{2}\\left[D_u^{+\\top}+D_u^{-\\top}\\right]\\mathbf{p}+\\frac{1}{2}\\left[D_v^{+\\top}+D_v^{-\\top}\\right]\\mathbf{q}+\\Lambda^2\\mathbf{z}^0\\\\\n=D_u\\mathbf{p}+D_v\\mathbf{q}+\\Lambda^2\\mathbf{z}^0\n\\end{gathered}\n```\nThis system is then solved using a standard conjugate gradient algorithm where\nthe initialization has only a slight impact on the runtime and no impact on the\nfinal solution. The algorithm provides good results on smooth surfaces but\nstruggles in the presence of discontinuities.\n# Parameters\n## `z`:\nAn `AbstractArray` which defines the value of ``z^0`` the initial solution and\nprior to be used in the regularization term. Must be provided.\n## `λ`:\nAn `AbstractArray` the same size as `z`, defaulting to ``10.0^{-6}`` everywhere.\nThis defines theregulization weight at each point. Large values will force the\nalgorithm to keep the solution near to ``z^0`` at that position. Can be used to\nkeep the solution near the initial solution or guide the solution to a certain\nknown value at points (i.e. known maxima and minima). This value should be set\nuniformly small otherwise.\n## `mask`:\nAn `AbstractArray` the same size as `z`, which guides the algorithm as to where\nthe valid domain is. Values of `1` will be in the domain ``\\Omega`` while other\nvalues will be ignored and set to ``z^0``. This can be used to\nintegrate over sub-domain or to segment the domain into parts. The `gen_mask()`\nfuntion can be used to generate a mask which will remove non-integrable regions\ndramatically improving the solution under most condition at the cost of not\nintegrating the entire solution.\n# Example\nThe following example demonstrates the use of the `Quadratic` integrator.\n```julia\nusing ShapeFromShading, Makie\n\n# Generate synthetic gradients\np, q = synthetic_gradient(Prism(75), img_size = 151)\n\n# Create a Quadratic() integrator\nquadratic = Quadratic(z=zeros(size(p)))\nquadraticMasked = Quadratic(z=zeros(size(p)), mask=gen_mask(p,q,1.0)[:,:,1])\n\n# Calculate the heightmap from the gradients\nZ = quadratic(p, q)\nZ2 = quadraticMasked(p, q)\n\n# Normalize to maximum of 1 (not necessary but makes displaying easier)\nZ = Z./maximum(Z)\nZ2 = Z2./maximum(Z2)\n\n# Display using Makie (Note: Makie can often take several minutes first time)\nr = 0.0:0.1:4\nvbox(surface(r, r, Z), surface(r, r, Z2))\n```\n# Reference\n[1] Y. Quéau, J. Durou and J. Aujol, \"Variational Methods for Normal Integration\", Journal of Mathematical Imaging and Vision, vol. 60, no. 4, pp. 609-632, 2017. [doi: 10.1007/s10851-017-0777-6](https://doi.org/10.1007/s10851-017-0777-6 )\n\"\"\"\nfunction (scheme::Quadratic)(pIn::AbstractArray, qIn::AbstractArray)\n    z⁰ = copy(scheme.z)\n    λ = copy(scheme.λ)\n    mask = copy(scheme.mask)\n    z = copy(z⁰)\n    mask = rotr90(mask)\n    λ = rotr90(λ)\n    p = rotr90(copy(pIn)).*mask\n    q = rotr90(copy(qIn)).*mask\n    T = first(size(z))\n    index = CartesianIndices(z)\n    index = reshape(index, length(index),1)\n\n    Dᵤ⁺ = spzeros(Float64, T^2, T^2)\n    Dᵤ⁻ = spzeros(Float64, T^2, T^2)\n    Dᵥ⁺ = spzeros(Float64, T^2, T^2)\n    Dᵥ⁻ = spzeros(Float64, T^2, T^2)\n    gen_matrix(Dᵤ⁺, Dᵤ⁻, Dᵥ⁺, Dᵥ⁻, T, mask)\n\n    # Calculate Dᵤ, Dᵥ and L as per eq 23 and 24\n    Dᵤ = 0.5*(transpose(Dᵤ⁺) .+ transpose(Dᵤ⁻))\n    Dᵥ = 0.5*(transpose(Dᵥ⁺) .+ transpose(Dᵥ⁻))\n    L = 0.5*((transpose(Dᵤ⁺) * Dᵤ⁺) .+ (transpose(Dᵤ⁻) * Dᵤ⁻) .+ (transpose(Dᵥ⁺) * Dᵥ⁺) .+ (transpose(Dᵥ⁻) * Dᵥ⁻))\n\n    Λ = spzeros(Float64,T^2,T^2)\n    A = spzeros(Float64,T^2,T^2)\n    P = zeros(Float64,T^2)\n    Q = zeros(Float64,T^2)\n    Z⁰ = zeros(Float64,T^2)\n    Z = zeros(Float64,T^2)\n\n    # Vectorize inputs\n    for j in CartesianIndices(z)\n        Λ[j[1]+(j[2]-1)*T,j[1]+(j[2]-1)*T] = sqrt(λ[j])\n        P[j[1]+(j[2]-1)*T] = p[j]\n        Q[j[1]+(j[2]-1)*T] = q[j]\n        Z⁰[j[1]+(j[2]-1)*T] = z⁰[j]\n        Z[j[1]+(j[2]-1)*T] = z[j]\n    end\n\n    # Calculate A and b as per eq 23 abd 24\n    A = L .+ (Λ^2)\n    b = Dᵤ*P .+ Dᵥ*Q .+ (Λ^2)*Z⁰\n\n    # Solve system\n    pl = AMGPreconditioner{RugeStuben}(A)\n    cg!(Z, A, b, tol=10.0^-4, Pl = pl)\n\n    for j in eachindex(index)\n        z[index[j]] = Z[j]\n    end\n    z = z.*mask\n    z = rotl90(z)\n    return z\nend\n\n@doc raw\"\"\"\n```\nTotalVariation(z::AbstractArray, α::Real = 1.0, λ::AbstractArray = fill(10.0^-6, size(z)), mask::AbstractArray = fill(1.0, size(z)), max_iter::Int = 100)\n```\nImplements the total variational method proposed by Aujol, Durou and Quéau. The\nalgorithm solves the same minimization problem as th `Quadratic`method exept the\nfidelity terms function ``\\Phi(s)=||s||_{L_1}``. This method is able to produce\ngood solutions on a smooth and piecewise smooth surface and can easily handle\nnon-rectangular domains or sub-divided domains.\n# Output\n`TotalVariation()` returns a TotalVariation integrator which can then be called to run the\nquadratic method on a gradient field.\n# Details\nAs discussed above this algorithm used the same fidelity and regularization terms\nas the `Quadratic` method exept the ``\\Phi(s)=s^2`` term is replaced with\n``\\Phi(s)=||s||_{L_1}``. This leads to the minimization problem defined by:\n```math\nmin\\iint_{(u,v)\\in \\Omega}||\\nabla z(u,v)-\\mathbf{g}(u,v)||+\\lambda(u,v)\\left[z(u,v)-z^0(u,v)\\right]^2dudv\n```\nBy considering the four posible discreatisations of ``∇z(u,v)`` we can generate\nfour posible domains to consider given by; ``\\Omega^{UV}=\\Omega_u^U\\cup\\Omega_v^V, (U,V)\\in\\{+,-\\}^2``\nwhere ``\\{+,-\\}^2`` refers to all posible combinations of +,-.\nUsing these the following discreate functional can be generated:\n```math\n\\begin{aligned}\nE(\\mathbf{z})=\\frac{1}{4}\\Big(&\\sum_{(u,v)\\in\\Omega^{++}}\\sqrt{[\\partial_u^+z_{u,v}-p_{u,v}]^2+[\\partial_v^+z_{u,v}-q_{u,v}]^2}\\\\\n+&\\sum_{(u,v)\\in\\Omega^{+-}}\\sqrt{[\\partial_u^+z_{u,v}-p_{u,v}]^2+[\\partial_v^-z_{u,v}-q_{u,v}]^2}\\\\\n+&\\sum_{(u,v)\\in\\Omega^{-+}}\\sqrt{[\\partial_u^-z_{u,v}-p_{u,v}]^2+[\\partial_v^+z_{u,v}-q_{u,v}]^2}\\\\\n+&\\sum_{(u,v)\\in\\Omega^{--}}\\sqrt{[\\partial_u^-z_{u,v}-p_{u,v}]^2+[\\partial_v^-z_{u,v}-q_{u,v}]^2}\\Big)\\\\\n+&\\sum_{(u,v)\\in\\Omega}\\lambda_{u,v}\\left[z_{u,v}-z^0_{u,v}\\right]^2\n\\end{aligned}\n```\nWhich simplifies to the minimization problem:\n```math\n\\begin{gathered}\nmin\\frac{1}{4}\\sum_{(U,V)\\in\\{+,-\\}^2}\\sum_{(u,v)\\in\\Omega^{UV}}||\\mathbf{r}_{(u,v)}^{UV}||+\\sum_{(u,v)\\in\\Omega}\\lambda_{u,v}\\left[z_{u,v}-z^0_{u,v}\\right]^2\\\\\n\\mathbf{r}_(u,v)^{UV}=\\nabla^{UV}z_{u,v}-\\mathbf{g}_{u,v}\n\\end{gathered}\n```\nThis leads to the optimization scheme using an ADMM algorithm defined by:\n```math\n\\begin{aligned}\nz^{(k+1)}=&min\\frac{\\alpha}{8}\\sum_{(U,V)\\in\\{+,-\\}^2}\\sum_{(u,v)\\in\\Omega^{UV}}||\\nabla^{UV}z_{u,v}-(\\mathbf{g}_{u,v}+\\mathbf{r}_{(u,v)}^{UV^{(k)}}-\\mathbf{b}_{(u,v)}^{UV^{(k)}})||\\\\&+\\sum_{(u,v)\\in\\Omega}\\lambda_{u,v}\\left[z_{u,v}-z^0_{u,v}\\right]^2\\\\\n\\mathbf{r}_{(u,v)}^{UV^{(k+1)}}=&min\\frac{\\alpha}{8}||\\mathbf{r}-(\\nabla^{UV}z_{u,v}-\\mathbf{g}_{u,v}+\\mathbf{b}_{(u,v)}^{UV^{(k)}})||+||\\mathbf{r}||\\\\\n\\mathbf{b}_{(u,v)}^{UV^{(k+1)}}=&\\mathbf{b}_{(u,v)}^{UV^{(k)}})+\\nabla^{UV}z_{u,v}-\\mathbf{g}_{u,v}-\\mathbf{r}_{(u,v)}^{UV^{(k+1)}}\n\\end{aligned}\n```\nThe z update then can be solved using the linear system defined below, where D_{u,v}^{U,V}\nand ``\\Lambda`` are the same at those defined in [`Quadratic`](@ref).\n```math\n\\begin{aligned}\n    A_{TV}&\\mathbf{z}^{(k+1)}=b_{TV}^{(k)}\\\\\n    A_{TV}&=\\frac{\\alpha}{8}\\sum_{(U,V)\\in\\{+,-\\}^2}\\left[D_u^{U\\top}D_u^{U}+D_v^{V\\top}D_v^{V}\\right] + \\Lambda^2\\\\\n    b_{TV}^{(k)}&=\\frac{\\alpha}{8}\\sum_{(U,V)\\in\\{+,-\\}^2}\\left[D_u^{U\\top}\\mathbf{P}^{UV^{(k)}} + D_v^{V\\top}\\mathbf{Q}^{UV^{(k)}}\\right]+ \\Lambda^2\\mathbf{z}^0\\\\\n\\end{aligned}\n```\nWhere ``\\mathbf{P}^{UV^{(k)}}, \\mathbf{Q}^{UV^{(k)}}`` are the u and v components\nof ``\\mathbf{g}+\\mathbf{r}^{UV^{(k)}}-\\mathbf{b}^{UV^{(k)}}``. This can be solved\nusing conjugate gradient. Finally the update to ``\\mathbf{r}^{UV}`` can be computed\nas:\n```math\n\\begin{aligned}\n    \\mathbf{r}^{UV^{(k+1)}}&=max\\Big\\{||\\mathbf{s}_{u,v}^{UV^{(k+1)}}||-\\frac{4}{\\alpha},0\\Big\\}\\frac{\\mathbf{s}_{u,v}^{UV^{(k+1)}}}{||\\mathbf{s}_{u,v}^{UV^{(k+1)}}||}\\\\\n    \\text{Where:}&\\\\\n    \\mathbf{s}^{UV^{(k+1)}}&=\\nabla^{UV}z_{u,v}^{(k+1)}-\\mathbf{g}_{u,v}+\\mathbf{b}_{u,v}^{UV^{(k)}}\n\\end{aligned}\n```\n# Parameters\n## `z`:\nAn `AbstractArray` which defines the value of ``z^0`` the initial solution and\nprior to be used in the regulization term. Must be provided.\n## `α`:\nA `Real` with defult value of `1.0` which controls the step size. In theory this\nvalue should have no impact on final solution but in practice larger values can\nlead to worse solutions while values which are two small may lead non-convergance\nin the least square update step, causing the algorithm to hang for long periods\nof time. Values below `0.25` are not recomended but may work depending on domain\nsize and inputs.\n## `λ`:\nAn `AbstractArray` the same size as `z` defulting to ``10.0^{-6}`` everywhere.\nThis defines theregulization weight at each point. Large valueas will force the\nalgorithm to keep the solution near to ``z^0`` at that position. Can be used to\nkeep the solution near the initial solution or guide the solution to a certian\nknown value at points (i.e. known maxima and minima). This value should be set\nuniformly small otherwise.\n## `mask`:\nAn `AbstractArray` the same size as `z`, which guides the algorithm as to where\nthe valid domain is. Values of `1` will be in the domain ``\\Omega`` while other\nvalues will be ignored and set to ``z^0``. This can be used to\nintegrate over sub-domain or to segment the domain into parts. The `gen_mask()`\nfuntion can be used to generate a mask which will remove non-integrable regions\ndramatically improving the solution under most condition at the cost of not\nintegrating the entire solution.\n# Example\nThe following example demonstrates the use of the `TotalVariation` integrator.\n```julia\nusing ShapeFromShading, Makie\n\n# Generate synthetic gradients\np, q = synthetic_gradient(Prism(75), img_size = 151)\n\n# Create a TotalVariation() integrator\ntotalVariation = TotalVariation(z=zeros(size(p)), α=1.0)\ntotalVariationMasked = TotalVariation(z=zeros(size(p)), α=0.5, mask=gen_mask(p,q,1.0)[:,:,1])\n\n# Calculate the heightmap from the gradients\nZ = totalVariation(p, q)\nZ2 = totalVariationMasked(p, q)\n\n# Normalize to maximum of 1 (not necessary but makes displaying easier)\nZ = Z./maximum(Z)\nZ2 = Z2./maximum(Z2)\n\n# Display using Makie (Note: Makie can often take several minutes first time)\nr = 0.0:0.1:4\nvbox(surface(r, r, Z), surface(r, r, Z2))\n```\n# Reference\n[1] Y. Quéau, J. Durou and J. Aujol, \"Variational Methods for Normal Integration\", Journal of Mathematical Imaging and Vision, vol. 60, no. 4, pp. 609-632, 2017. [doi: 10.1007/s10851-017-0777-6](https://doi.org/10.1007/s10851-017-0777-6 )\n\"\"\"\nfunction (scheme::TotalVariation)(pIn::AbstractArray, qIn::AbstractArray)\n    z⁰ = copy(scheme.z)\n    λ = copy(scheme.λ)\n    mask = copy(scheme.mask)\n    α = copy(scheme.α)\n    max_iter = copy(scheme.max_iter)\n    z = copy(z⁰)\n    mask = rotr90(mask)\n    λ = rotr90(λ)\n    p = rotr90(copy(pIn)).*mask\n    q = rotr90(copy(qIn)).*mask\n    T = first(size(z))\n    index = CartesianIndices(z)\n    index = reshape(index, length(index),1)\n\n    Dᵤ⁺ = spzeros(Float64,T^2,T^2)\n    Dᵤ⁻ = spzeros(Float64,T^2,T^2)\n    Dᵥ⁺ = spzeros(Float64,T^2,T^2)\n    Dᵥ⁻ = spzeros(Float64,T^2,T^2)\n    gen_matrix(Dᵤ⁺, Dᵤ⁻, Dᵥ⁺, Dᵥ⁻, T, mask)\n    Λ = spzeros(Float64,T^2,T^2)\n    A = spzeros(Float64,T^2,T^2)\n    P = zeros(Float64,T^2)\n    Q = zeros(Float64,T^2)\n    Z⁰ = zeros(Float64,T^2)\n    Z = zeros(Float64,T^2)\n\n    # Vectorize inputs\n    for j in CartesianIndices(z)\n        Λ[j[1]+(j[2]-1)*T,j[1]+(j[2]-1)*T] = sqrt(λ[j])\n        P[j[1]+(j[2]-1)*T] = p[j]\n        Q[j[1]+(j[2]-1)*T] = q[j]\n        Z⁰[j[1]+(j[2]-1)*T] = z⁰[j]\n        Z[j[1]+(j[2]-1)*T] = z[j]\n    end\n\n    # Calculate A as per eq 59\n    A = (α/8)*(((transpose(Dᵤ⁺) * Dᵤ⁺) .+ (transpose(Dᵥ⁺) * Dᵥ⁺)) .+ ((transpose(Dᵤ⁻) * Dᵤ⁻) .+ (transpose(Dᵥ⁻) * Dᵥ⁻)) .+ ((transpose(Dᵤ⁻) * Dᵤ⁻) .+ (transpose(Dᵥ⁺) * Dᵥ⁺)) .+ ((transpose(Dᵤ⁺) * Dᵤ⁺) .+ (transpose(Dᵥ⁻) * Dᵥ⁻))) .+ (Λ^2)\n    pl = AMGPreconditioner{RugeStuben}(A)\n\n    # Calculate b, s, r, P and Q in each combination of {+,-} as per equations 57, 61, 62\n    bᵤ⁺⁺ = zeros(Float64,T^2)\n    bᵥ⁺⁺ = zeros(Float64,T^2)\n    sᵤ⁺⁺ = Dᵤ⁺*Z - P + bᵤ⁺⁺\n    sᵥ⁺⁺ = Dᵥ⁺*Z - Q + bᵥ⁺⁺\n    rᵤ⁺⁺ = max(norm(sᵤ⁺⁺) - (4/α),0)*(sᵤ⁺⁺./(norm(sᵤ⁺⁺)+eps(Float64)))\n    rᵥ⁺⁺ = max(norm(sᵥ⁺⁺) - (4/α),0)*(sᵥ⁺⁺./(norm(sᵥ⁺⁺)+eps(Float64)))\n    bᵤ⁺⁺ = bᵤ⁺⁺ + Dᵤ⁺*Z - P - rᵤ⁺⁺\n    bᵥ⁺⁺ = bᵥ⁺⁺ + Dᵥ⁺*Z - Q - rᵥ⁺⁺\n    P⁺⁺ = P + rᵤ⁺⁺ - bᵤ⁺⁺\n    Q⁺⁺ = Q + rᵥ⁺⁺ - bᵥ⁺⁺\n\n    bᵤ⁺⁻ = zeros(Float64,T^2)\n    bᵥ⁺⁻ = zeros(Float64,T^2)\n    sᵤ⁺⁻ = Dᵤ⁺*Z - P + bᵤ⁺⁻\n    sᵥ⁺⁻ = Dᵥ⁻*Z - Q + bᵥ⁺⁻\n    rᵤ⁺⁻ = max(norm(sᵤ⁺⁻) - (4/α),0)*(sᵤ⁺⁻./(norm(sᵤ⁺⁻)+eps(Float64)))\n    rᵥ⁺⁻ = max(norm(sᵥ⁺⁻) - (4/α),0)*(sᵥ⁺⁻./(norm(sᵥ⁺⁻)+eps(Float64)))\n    bᵤ⁺⁻ = bᵤ⁺⁻ + Dᵤ⁺*Z - P - rᵤ⁺⁻\n    bᵥ⁺⁻ = bᵥ⁺⁻ + Dᵥ⁻*Z - Q - rᵥ⁺⁻\n    P⁺⁻ = P + rᵤ⁺⁻ - bᵤ⁺⁻\n    Q⁺⁻ = Q + rᵥ⁺⁻ - bᵥ⁺⁻\n\n    bᵤ⁻⁺ = zeros(Float64,T^2)\n    bᵥ⁻⁺ = zeros(Float64,T^2)\n    sᵤ⁻⁺ = Dᵤ⁻*Z - P + bᵤ⁻⁺\n    sᵥ⁻⁺ = Dᵥ⁺*Z - Q + bᵥ⁻⁺\n    rᵤ⁻⁺ = max(norm(sᵤ⁻⁺) - (4/α),0)*(sᵤ⁻⁺./(norm(sᵤ⁻⁺)+eps(Float64)))\n    rᵥ⁻⁺ = max(norm(sᵥ⁻⁺) - (4/α),0)*(sᵥ⁻⁺./(norm(sᵥ⁻⁺)+eps(Float64)))\n    bᵤ⁻⁺ = bᵤ⁻⁺ + Dᵤ⁻*Z - P - rᵤ⁻⁺\n    bᵥ⁻⁺ = bᵥ⁻⁺ + Dᵥ⁺*Z - Q - rᵥ⁻⁺\n    P⁻⁺ = P + rᵤ⁻⁺ - bᵤ⁻⁺\n    Q⁻⁺ = Q + rᵥ⁻⁺ - bᵥ⁻⁺\n\n    bᵤ⁻⁻ = zeros(Float64,T^2)\n    bᵥ⁻⁻ = zeros(Float64,T^2)\n    sᵤ⁻⁻ = Dᵤ⁻*Z - P + bᵤ⁻⁻\n    sᵥ⁻⁻ = Dᵥ⁻*Z - Q + bᵥ⁻⁻\n    rᵤ⁻⁻ = max(norm(sᵤ⁻⁻) - (4/α),0)*(sᵤ⁻⁻./(norm(sᵤ⁻⁻)+eps(Float64)))\n    rᵥ⁻⁻ = max(norm(sᵥ⁻⁻) - (4/α),0)*(sᵥ⁻⁻./(norm(sᵥ⁻⁻)+eps(Float64)))\n    bᵤ⁻⁻ = bᵤ⁻⁻ + Dᵤ⁻*Z - P - rᵤ⁻⁻\n    bᵥ⁻⁻ = bᵥ⁻⁻ + Dᵥ⁻*Z - Q - rᵥ⁻⁻\n    P⁻⁻ = P + rᵤ⁻⁻ - bᵤ⁻⁻\n    Q⁻⁻ = Q + rᵥ⁻⁻ - bᵥ⁻⁻\n\n    # Calculate bₜᵥ as per eq 60\n    bₜᵥ = (transpose(Dᵤ⁺) * P⁺⁺) .+ (transpose(Dᵥ⁺) * Q⁺⁺) .+ (transpose(Dᵤ⁺) * P⁺⁻) .+ (transpose(Dᵥ⁻) * Q⁺⁻) .+ (transpose(Dᵤ⁻) * P⁻⁺) .+ (transpose(Dᵥ⁺) * Q⁻⁺) .+ (transpose(Dᵤ⁻) * P⁻⁻) .+ (transpose(Dᵥ⁻) * Q⁻⁻) .+ (Λ^2)*Z⁰\n    for i = 1:max_iter\n        cg!(Z, A, bₜᵥ, tol=10.0^-4, Pl = pl)\n\n        # Recalculate b, s, r, P and Q in each combination of {+,-} as per equations 57, 61, 62\n        sᵤ⁺⁺ = Dᵤ⁺*Z - P + bᵤ⁺⁺\n        sᵥ⁺⁺ = Dᵥ⁺*Z - Q + bᵥ⁺⁺\n        rᵤ⁺⁺ = max(norm(sᵤ⁺⁺) - (4/α),0)*(sᵤ⁺⁺./(norm(sᵤ⁺⁺)+eps(Float64)))\n        rᵥ⁺⁺ = max(norm(sᵥ⁺⁺) - (4/α),0)*(sᵥ⁺⁺./(norm(sᵥ⁺⁺)+eps(Float64)))\n        bᵤ⁺⁺ = bᵤ⁺⁺ + Dᵤ⁺*Z - P - rᵤ⁺⁺\n        bᵥ⁺⁺ = bᵥ⁺⁺ + Dᵥ⁺*Z - Q - rᵥ⁺⁺\n        P⁺⁺ = P + rᵤ⁺⁺ - bᵤ⁺⁺\n        Q⁺⁺ = Q + rᵥ⁺⁺ - bᵥ⁺⁺\n\n        sᵤ⁺⁻ = Dᵤ⁺*Z - P + bᵤ⁺⁻\n        sᵥ⁺⁻ = Dᵥ⁻*Z - Q + bᵥ⁺⁻\n        rᵤ⁺⁻ = max(norm(sᵤ⁺⁻) - (4/α),0)*(sᵤ⁺⁻./(norm(sᵤ⁺⁻)+eps(Float64)))\n        rᵥ⁺⁻ = max(norm(sᵥ⁺⁻) - (4/α),0)*(sᵥ⁺⁻./(norm(sᵥ⁺⁻)+eps(Float64)))\n        bᵤ⁺⁻ = bᵤ⁺⁻ + Dᵤ⁺*Z - P - rᵤ⁺⁻\n        bᵥ⁺⁻ = bᵥ⁺⁻ + Dᵥ⁻*Z - Q - rᵥ⁺⁻\n        P⁺⁻ = P + rᵤ⁺⁻ - bᵤ⁺⁻\n        Q⁺⁻ = Q + rᵥ⁺⁻ - bᵥ⁺⁻\n\n        sᵤ⁻⁺ = Dᵤ⁻*Z - P + bᵤ⁻⁺\n        sᵥ⁻⁺ = Dᵥ⁺*Z - Q + bᵥ⁻⁺\n        rᵤ⁻⁺ = max(norm(sᵤ⁻⁺) - (4/α),0)*(sᵤ⁻⁺./(norm(sᵤ⁻⁺)+eps(Float64)))\n        rᵥ⁻⁺ = max(norm(sᵥ⁻⁺) - (4/α),0)*(sᵥ⁻⁺./(norm(sᵥ⁻⁺)+eps(Float64)))\n        bᵤ⁻⁺ = bᵤ⁻⁺ + Dᵤ⁻*Z - P - rᵤ⁻⁺\n        bᵥ⁻⁺ = bᵥ⁻⁺ + Dᵥ⁺*Z - Q - rᵥ⁻⁺\n        P⁻⁺ = P + rᵤ⁻⁺ - bᵤ⁻⁺\n        Q⁻⁺ = Q + rᵥ⁻⁺ - bᵥ⁻⁺\n\n        sᵤ⁻⁻ = Dᵤ⁻*Z - P + bᵤ⁻⁻\n        sᵥ⁻⁻ = Dᵥ⁻*Z - Q + bᵥ⁻⁻\n        rᵤ⁻⁻ = max(norm(sᵤ⁻⁻) - (4/α),0)*(sᵤ⁻⁻./(norm(sᵤ⁻⁻)+eps(Float64)))\n        rᵥ⁻⁻ = max(norm(sᵥ⁻⁻) - (4/α),0)*(sᵥ⁻⁻./(norm(sᵥ⁻⁻)+eps(Float64)))\n        bᵤ⁻⁻ = bᵤ⁻⁻ + Dᵤ⁻*Z - P - rᵤ⁻⁻\n        bᵥ⁻⁻ = bᵥ⁻⁻ + Dᵥ⁻*Z - Q - rᵥ⁻⁻\n        P⁻⁻ = P + rᵤ⁻⁻ - bᵤ⁻⁻\n        Q⁻⁻ = Q + rᵥ⁻⁻ - bᵥ⁻⁻\n\n        # Recalculate bₜᵥ as per eq 60\n        bₜᵥ = (transpose(Dᵤ⁺) * P⁺⁺) .+ (transpose(Dᵥ⁺) * Q⁺⁺) .+ (transpose(Dᵤ⁺) * P⁺⁻) .+ (transpose(Dᵥ⁻) * Q⁺⁻) .+ (transpose(Dᵤ⁻) * P⁻⁺) .+ (transpose(Dᵥ⁺) * Q⁻⁺) .+ (transpose(Dᵤ⁻) * P⁻⁻) .+ (transpose(Dᵥ⁻) * Q⁻⁻) .+ (Λ^2)*Z⁰\n    end\n    for j in eachindex(index)\n        z[index[j]] = Z[j]\n    end\n    z = z.*mask\n    z = rotl90(z)\n    return z\nend\n\n@doc raw\"\"\"\n```\nNonConvex1(z::AbstractArray, β::Real = 0.5, λ::AbstractArray = fill(10.0^-6, size(z)), mask::AbstractArray = fill(1.0, size(z)), max_iter::Int = 100)\n```\nThe first of two non-convex regularization methods proposed by Aujol, Durou and\nQuéau. The same fidelity and regularization terms to minimize as [`Quadratic`](@ref)\nare used, but the convexity of ``\\Phi`` is sacrificed in order to gain better\nbehaviour around discontinuities and outliers.\n# Output\n`NonConvex1()` returns a NonConvex1 integrator which can then be called to run the\nnon-convex regularization method method on a gradient field.\n# Details\nThe initial minimization problem is the same as in [`TotalVariation`](@ref)\nas given below exept ``Phi`` is defined using the given function instead of the\n``L_1`` norm.\n```math\n\\begin{aligned}\n&min\\iint_{(u,v)\\in \\Omega}||\\nabla z(u,v)-\\mathbf{g}(u,v)||+\\lambda(u,v)\\left[z(u,v)-z^0(u,v)\\right]^2dudv\\\\\n&\\text{where:}\\\\\n&\\Phi(s)=log(s^2+\\beta^2)\n\\end{aligned}\n```\nThe problem can then be discretized to form the following functional where ``D_{u,v}^{UV}``\nis a ``2\\times|\\Omega|`` matrix formed from stacking the vectors of the finite\ndiferences.\n```math\n\\begin{aligned}\nE(\\mathbf{z})&=\\frac{1}{4}\\sum_{(U,V)\\in\\{+,-\\}^2}\\sum_{(u,v)\\in\\Omega^{UV}}\\Phi(||\\nabla z_{u,v}-\\mathbf{g}_{u,v}||)+\\sum_{(u,v)\\in\\Omega}\\lambda_{u,v}\\left[z_{u,v}-z^0_{u,v}\\right]^2\\\\\n&=\\frac{1}{4}\\sum_{(U,V)\\in\\{+,-\\}^2}\\sum_{(u,v)\\in\\Omega^{UV}}\\Phi(||D_{u,v}^{UV}\\mathbf{z}-\\mathbf{g}_{u,v}||)+||\\Lambda\\left(\\mathbf{z}-\\mathbf{z}^0\\right)||^2\\\\\n&=f(\\mathbf{z})+g(\\mathbf{z})\n\\end{aligned}\n```\nAs ``f(\\mathbf{z})`` is smooth but not convex and ``g(\\mathbf{z})`` is convex\nthe iPiano algorithm is then used to iterativly solve the minimization of the\nfunctional such that:\n```math\n\\mathbf{z}^{(k+1)}=(I+\\alpha_1\\partial g)^{-1}(\\mathbf{z}^{(k)}-\\alpha_1\\nabla f(\\mathbf{z}^{(k)})+\\alpha_2(\\mathbf{z}^{(k)}-z^{(k+1)}))\n```\nwhere ``(I+\\alpha_1\\partial g)^{-1}`` is a proximal operator defined as:\n```math\n(I+\\alpha_1\\partial g)^{-1}(\\mathbf{\\hat{x}})=(I+2\\alpha_1\\Lambda^2)^{-1}(\\mathbf{\\hat{x}}+2\\alpha_1\\Lambda\\mathbf{z}^0)\n```\nUsing the definition of ``\\Phi`` given above, the derivative of ``f(\\mathbf{z})``\ncan be computed as below:\n```math\n\\nabla f(\\mathbf{z})=\\frac{1}{4}\\sum_{(U,V)\\in\\{+,-\\}^2}\\sum_{(u,v)\\in\\Omega^{UV}}\\frac{D_{u,v}^{UV^\\top}(D_{u,v}^{UV}\\mathbf{z}-\\mathbf{g}_{u,v})}{||D_{u,v}^{UV}\\mathbf{z}-\\mathbf{g}_{u,v}||^2+\\beta^2}\n```\nThe values of ``\\alpha_1`` and ``\\aplha_2`` control the step size of the algorith\nand are chosen such that ``\\alpha_2`` is fixed at 0.8 while ``\\alpha_1`` is chosen\nusing the lazy backtracking method, which uses a Lipschitz constant to caculate\na suitably small step size at each step using the below relationship where ``\\eta>1``\nis a constant:\n```math\n\\begin{aligned}\n&\\alpha_1 < 2(1-\\alpha_2)/L_n\\\\\n&\\text{where:}\\\\\n&L_k\\in\\{L_{k-1},\\eta L_{k-1},\\eta^2L_{k-1},...\\}\\\\\n&\\text{such that it is minimal and satisfies:}\\\\\n&f(x^{(k+1)})\\le f(x^{(k)}) + \\left\\langle\\nabla f(x^{(k)}), x^{(k+1)}-x^{(k)}\\right\\rangle+\\frac{L_k}{2}||x^{(k+1)}-x^{(k)}||^2\n\\end{aligned}\n```\nThis method, being non-convex, highly relies on a good initial solution and will\noften only provide a minimal improvment to the solution. A bad initial solution\nwill produce a final solution which does not resemble the surface under most\nconditions.\n# Parameters\n## `z`:\nAn `AbstractArray` which defines the value of ``z^0`` the initial solution and\nprior to be used in the regulization term.\n## `β`:\nA `Real` which acts as a hyper-parameter to the function. Large values for β will\nproduce smoother functions but loose discontinuities. Smaller value will preserve\ndiscontinuities but lead to staircassing in the solution. Defults to `0.5`.\n## `λ`:\nAn `AbstractArray` the same size as `z` defulting to ``10.0^-6`` everywhere.\nThis defines theregulization weight at each point. Large valueas will force the\nalgorithm to keep the solution near to ``z^0`` at that position. Can be used to\nkeep the solution near the initial solution or guide the solution to a certian\nknown value at points (i.e. known maxima and minima). This value should be set\nuniformly small otherwise.\n## `mask`:\nAn `AbstractArray` the same size as `z`, which guides the algorithm as to where\nthe valid domain is. Values of `1` will be in the domain ``\\Omega`` while other\nvalues will be ignored and set to ``z^0``. This can be used to\nintegrate over sub-domain or to segment the domain into parts. The `gen_mask()`\nfuntion can be used to generate a mask which will remove non-integrable regions\ndramatically improving the solution under most condition at the cost of not\nintegrating the entire solution.\n# Example\nThe following example demonstrates the use of the `NonConvex1` integrator.\n```julia\nusing ShapeFromShading, Makie\n\n# Generate synthetic gradients\np, q = synthetic_gradient(Prism(75), img_size = 151)\n\n# Create a NonConvex1() integrator\nnonConvex1 = NonConvex1(z=zeros(size(p)), β=0.5)\nnonConvex1Init = NonConvex1(z=Horn()(p,q), β=0.5)\n\n# Calculate the heightmap from the gradients\nZ = nonConvex1(p, q)\nZ2 = nonConvex1Init(p, q)\n\n# Normalize to maximum of 1 (not necessary but makes displaying easier)\nZ = Z./maximum(Z)\nZ2 = Z2./maximum(Z2)\n\n# Display using Makie (Note: Makie can often take several minutes first time)\nr = 0.0:0.1:4\nvbox(surface(r, r, Z), surface(r, r, Z2))\n```\n# Reference\n[1] Y. Quéau, J. Durou and J. Aujol, \"Variational Methods for Normal Integration\", Journal of Mathematical Imaging and Vision, vol. 60, no. 4, pp. 609-632, 2017. [doi: 10.1007/s10851-017-0777-6](https://doi.org/10.1007/s10851-017-0777-6 )\n\"\"\"\nfunction (scheme::NonConvex1)(pIn::AbstractArray, qIn::AbstractArray)\n    z⁰ = copy(scheme.z)\n    λ = copy(scheme.λ)\n    mask = copy(scheme.mask)\n    β = copy(scheme.β)\n    max_iter = copy(scheme.max_iter)\n    z = copy(z⁰)\n    mask = rotr90(mask)\n    λ = rotr90(λ)\n    p = rotr90(copy(pIn)).*mask\n    q = rotr90(copy(qIn)).*mask\n    T = first(size(z))\n    index = CartesianIndices(z)\n    index = reshape(index, length(index),1)\n\n    Dᵤ⁺ = spzeros(Float64,T^2,T^2)\n    Dᵤ⁻ = spzeros(Float64,T^2,T^2)\n    Dᵥ⁺ = spzeros(Float64,T^2,T^2)\n    Dᵥ⁻ = spzeros(Float64,T^2,T^2)\n    gen_matrix(Dᵤ⁺, Dᵤ⁻, Dᵥ⁺, Dᵥ⁻, T, mask)\n    Λ = zeros(Float64,T^2,T^2)\n    P = zeros(Float64,T^2)\n    Q = zeros(Float64,T^2)\n    Z⁰ = zeros(Float64,T^2)\n    Z = zeros(Float64,T^2)\n\n    # Vectorize inputs\n    for j in CartesianIndices(z)\n        Λ[j[1]+(j[2]-1)*T,j[1]+(j[2]-1)*T] = sqrt(λ[j])\n        P[j[1]+(j[2]-1)*T] = p[j]\n        Q[j[1]+(j[2]-1)*T] = q[j]\n        Z⁰[j[1]+(j[2]-1)*T] = z⁰[j]\n        Z[j[1]+(j[2]-1)*T] = z[j]\n    end\n    Λ = Diagonal(Λ)\n    Zold = copy(Z)\n    Ztemp = copy(Z)\n    α₁ = 0.8\n    α₂ = 0.8\n\n    # Initialize Lₙ (Lipschitz constant) such that lazy backtracking starts with α₁ = α₂.\n    # This is mostly arbitary and value will approach needed value over time.\n    Lₙ = (18.0/α₁)*(1-α₂)\n    η = 1.1\n    i = 1\n    while i <= max_iter && (norm(Z - Zold) > 10.0^-4.0 || i == 1)\n        # Calculate f₁, ∇f₁ and previous f₁ (f₁ⁿ⁻¹ )\n        ∇f₁ = ((transpose(Dᵤ⁺)*(Dᵤ⁺*Z-P))/(norm(Dᵤ⁺*Z-P)^2+β^2)) + ((transpose(Dᵥ⁺)*(Dᵥ⁺*Z-Q))/(norm(Dᵥ⁺*Z-Q)^2+β^2)) + ((transpose(Dᵤ⁻)*(Dᵤ⁻*Z-P))/(norm(Dᵤ⁻*Z-P)^2+β^2)) + ((transpose(Dᵥ⁻)*(Dᵥ⁻*Z-Q))/(norm(Dᵥ⁻*Z-Q)^2+β^2))\n        f₁ⁿ⁻¹ = log(norm(Dᵤ⁺*Zold-P)^2+β^2) + log(norm(Dᵥ⁺*Zold-Q)^2+β^2) + log(norm(Dᵤ⁻*Zold-P)^2+β^2) + log(norm(Dᵥ⁻*Zold-Q)^2+β^2)\n        f₁ = log(norm(Dᵤ⁺*Z-P)^2+β^2) + log(norm(Dᵥ⁺*Z-Q)^2+β^2) + log(norm(Dᵤ⁻*Z-P)^2+β^2) + log(norm(Dᵥ⁻*Z-Q)^2+β^2)\n\n        # Calculate lazy backtracking condition as per ipiano algortihm 4\n        while f₁ > f₁ⁿ⁻¹  + dot(∇f₁, Z - Zold) + (Lₙ/2)*norm(Z - Zold)\n            Lₙ = Lₙ*η\n        end\n\n        # Calculate new α₁ as per ipiano algortihm 4\n        α₁ = (2*(1-α₂)/Lₙ)*0.9\n\n        # Calcualte x̂ as per eq 69 then calculate new Z as per eq 71\n        x̂ = Z - α₁.*∇f₁ + α₂.*(Z-Zold)\n        Ztemp = inv(I+(2*α₁).*Λ^2)*(x̂+(2*α₁).*Λ*Z⁰)\n        copyto!(Zold, Z)\n        copyto!(Z, Ztemp)\n        i += 1\n    end\n    println(\"Converged after \", i-1, \" iterations\")\n    for j in eachindex(index)\n        z[index[j]] = Z[j]\n    end\n    z = rotl90(z)\n    return z\nend\n\n@doc raw\"\"\"\n```\nNonConvex2(z::AbstractArray, γ::Real = 1.0, λ::AbstractArray = fill(10.0^-6, size(z, mask::AbstractArray = fill(1.0, size(z)), max_iter::Int = 100)\n```\nThe second of two non-convex regularization methods proposed by Aujol, Durou and\nQuéau. The same as [`NonConvex1`](@ref) exept ``\\Phi`` has been replaced with a\ndifferent non-convex function.\n# Output\n`NonConvex2()` returns a NonConvex2 integrator which can then be called to run the\nnon-convex regularization method method on a gradient field.\n# Details\nThe implimentation is the same as the one in [`TotalVariation`](@ref)\nas given below exept ``Phi`` is defined as below:\n```math\n\\Phi(s)=\\frac{s^2}{s^2+\\gamma^2}\n```\nUsing the definition of ``\\Phi`` given above, the derivative of ``f(\\mathbf{z})``\ncan be computed as below:\n```math\n\\nabla f(\\mathbf{z})=\\frac{1}{4}\\sum_{(U,V)\\in\\{+,-\\}^2}\\sum_{(u,v)\\in\\Omega^{UV}}\\frac{\\gamma^2D_{u,v}^{UV^\\top}(D_{u,v}^{UV}\\mathbf{z}-\\mathbf{g}_{u,v})}{()||D_{u,v}^{UV}\\mathbf{z}-\\mathbf{g}_{u,v}||^2+\\gamma^2)^2}\n```\nThis method, being non-convex, highly relies on a good initial solution and will\noften only provide a minimal improvment to the solution. A bad initial solution\nwill produce a final solution which does not resemble the surface under most\nconditions.\n# Parameters\n## `z`:\nAn `AbstractArray` which defines the value of ``z^0`` the initial solution and\nprior to be used in the regulization term.\n## `γ`:\nA `Real` which acts as a hyper-parameter to the function. Large values for γ will\nproduce smoother functions but loose discontinuities. Smaller value will preserve\ndiscontinuities but lead to staircassing in the solution. Defults to `1.0`.\n## `λ`:\nAn `AbstractArray` the same size as `z` defulting to ``10.0^-6`` everywhere.\nThis defines theregulization weight at each point. Large valueas will force the\nalgorithm to keep the solution near to ``z^0`` at that position. Can be used to\nkeep the solution near the initial solution or guide the solution to a certian\nknown value at points (i.e. known maxima and minima). This value should be set\nuniformly small otherwise.\n## `mask`:\nAn `AbstractArray` the same size as `z`, which guides the algorithm as to where\nthe valid domain is. Values of `1` will be in the domain ``\\Omega`` while other\nvalues will be ignored and set to ``z^0``. This can be used to\nintegrate over sub-domain or to segment the domain into parts. The `gen_mask()`\nfuntion can be used to generate a mask which will remove non-integrable regions\ndramatically improving the solution under most condition at the cost of not\nintegrating the entire solution.\n# Example\nThe following example demonstrates the use of the `NonConvex2` integrator.\n```julia\nusing ShapeFromShading, Makie\n\n# Generate synthetic gradients\np, q = synthetic_gradient(Prism(75), img_size = 151)\n\n# Create a NonConvex2() integrator\nnonConvex2 = NonConvex2(z=zeros(size(p)), γ=1.0)\nnonConvex2Init = NonConvex2(z=Horn()(p,q), γ=1.0)\n\n# Calculate the heightmap from the gradients\nZ = nonConvex2(p, q)\nZ2 = nonConvex2Init(p, q)\n\n# Normalize to maximum of 1 (not necessary but makes displaying easier)\nZ = Z./maximum(Z)\nZ2 = Z2./maximum(Z2)\n\n# Display using Makie (Note: Makie can often take several minutes first time)\nr = 0.0:0.1:4\nvbox(surface(r, r, Z), surface(r, r, Z2))\n```\n# Reference\n[1] Y. Quéau, J. Durou and J. Aujol, \"Variational Methods for Normal Integration\", Journal of Mathematical Imaging and Vision, vol. 60, no. 4, pp. 609-632, 2017. [doi: 10.1007/s10851-017-0777-6](https://doi.org/10.1007/s10851-017-0777-6 )\n\"\"\"\nfunction (scheme::NonConvex2)(pIn::AbstractArray, qIn::AbstractArray)\n    z⁰ = copy(scheme.z)\n    λ = copy(scheme.λ)\n    mask = copy(scheme.mask)\n    γ = copy(scheme.γ)\n    max_iter = copy(scheme.max_iter)\n    z = copy(z⁰)\n    mask = rotr90(mask)\n    λ = rotr90(λ)\n    p = rotr90(copy(pIn)).*mask\n    q = rotr90(copy(qIn)).*mask\n    T = first(size(z))\n    index = CartesianIndices(z)\n    index = reshape(index, length(index),1)\n\n    Dᵤ⁺ = spzeros(Float64,T^2,T^2)\n    Dᵤ⁻ = spzeros(Float64,T^2,T^2)\n    Dᵥ⁺ = spzeros(Float64,T^2,T^2)\n    Dᵥ⁻ = spzeros(Float64,T^2,T^2)\n    gen_matrix(Dᵤ⁺, Dᵤ⁻, Dᵥ⁺, Dᵥ⁻, T, mask)\n    Λ = zeros(Float64,T^2,T^2)\n    P = zeros(Float64,T^2)\n    Q = zeros(Float64,T^2)\n    Z⁰ = zeros(Float64,T^2)\n    Z = zeros(Float64,T^2)\n\n    # Vectorize inputs\n    for j in CartesianIndices(z)\n        Λ[j[1]+(j[2]-1)*T,j[1]+(j[2]-1)*T] = sqrt(λ[j])\n        P[j[1]+(j[2]-1)*T] = p[j]\n        Q[j[1]+(j[2]-1)*T] = q[j]\n        Z⁰[j[1]+(j[2]-1)*T] = z⁰[j]\n        Z[j[1]+(j[2]-1)*T] = z[j]\n    end\n    Λ = Diagonal(Λ)\n    Zold = copy(Z)\n    Ztemp = copy(Z)\n    α₁ = 0.8\n    α₂ = 0.8\n\n    # Initialize Lₙ (Lipschitz constant) such that lazy backtracking starts with α₁ = α₂.\n    # This is mostly arbitary and value will approach needed value over time.\n    Lₙ = (18.0/α₁)*(1-α₂)\n    η = 1.1\n    i = 1\n    while i <= max_iter && (norm(Z - Zold) > 10.0^-4.0 || i == 1)\n        # Calculate f₁, ∇f₁ and previous f₁ (f₁ⁿ⁻¹ )\n        ∇f₁ = (((γ^2)*transpose(Dᵤ⁺)*(Dᵤ⁺*Z-P))/(norm(Dᵤ⁺*Z-P)^2+γ^2)^2) + (((γ^2)*transpose(Dᵥ⁺)*(Dᵥ⁺*Z-Q))/(norm(Dᵥ⁺*Z-Q)^2+γ^2)^2) + (((γ^2)*transpose(Dᵤ⁻)*(Dᵤ⁻*Z-P))/(norm(Dᵤ⁻*Z-P)^2+γ^2)^2) + (((γ^2)*transpose(Dᵥ⁻)*(Dᵥ⁻*Z-Q))/(norm(Dᵥ⁻*Z-Q)^2+γ^2)^2)\n        f₁ⁿ⁻¹ = (norm(Dᵤ⁺*Zold-P)^2)/(norm(Dᵤ⁺*Zold-P)^2+γ^2) + (norm(Dᵥ⁺*Zold-Q)^2)/(norm(Dᵥ⁺*Zold-Q)^2+γ^2) + (norm(Dᵤ⁻*Zold-P)^2)/(norm(Dᵤ⁻*Zold-P)^2+γ^2) + (norm(Dᵥ⁻*Zold-Q)^2)/(norm(Dᵥ⁻*Zold-Q)^2+γ^2)\n        f₁ = (norm(Dᵤ⁺*Z-P)^2)/(norm(Dᵤ⁺*Z-P)^2+γ^2) + (norm(Dᵥ⁺*Z-Q)^2)/(norm(Dᵥ⁺*Z-Q)^2+γ^2) + (norm(Dᵤ⁻*Z-P)^2)/(norm(Dᵤ⁻*Z-P)^2+γ^2) + (norm(Dᵥ⁻*Z-Q)^2)/(norm(Dᵥ⁻*Z-Q)^2+γ^2)\n\n        # Calculate lazy backtracking condition as per ipiano algortihm 4\n        while f₁ > f₁ⁿ⁻¹ + dot(∇f₁, Z - Zold) + (Lₙ/2)*norm(Z - Zold)\n            Lₙ = Lₙ*η\n        end\n\n        # Calculate new α₁ as per ipiano algortihm 4\n        α₁ = (2*(1-α₂)/Lₙ)*0.9\n\n        # Calcualte x̂ as per eq 69 then calculate new Z as per eq 71\n        x̂ = Z - α₁.*∇f₁ + α₂.*(Z-Zold)\n        Ztemp = inv(I+(2*α₁).*Λ^2)*(x̂+(2*α₁).*Λ*Z⁰)\n        copyto!(Zold, Z)\n        copyto!(Z, Ztemp)\n        i += 1\n    end\n    println(\"Converged after \", i-1, \" iterations\")\n    for j in eachindex(index)\n        z[index[j]] = Z[j]\n    end\n    z = rotl90(z)\n    return z\nend\n\n@doc raw\"\"\"\n```\nAnisotropicDiffusion(z::AbstractArray, μ::Real = 5.0, ν::Real = 10., λ::AbstractArray = fill(10.0^-6, size(z)), mask::AbstractArray = fill(1.0, size(z)), max_iter::Int = 10)\n```\nDefines the anisotropic diffusion method as proposed by Aujol, Durou and Quéau.\nIt utilizes an anisotropic diffusion like process to create a weighted version\nof the least squares problem solved in the [`Quadratic`](@ref) method.\n# Output\n`AnisotropicDiffusion()` returns a AnisotropicDiffusion integrator which can then be called to run the\nanisotropic diffusion method method on a gradient field.\n# Details\nThe minimization problem from [`Quadratic`](@ref) is modified with the addition\nweighting term ``W(u,v)`` to reach the following minimization problem.\n```math\nmin\\iint_{(u,v)\\in \\Omega}||W(u,v)[\\nabla z(u,v)-\\mathbf{g}(u,v)]||^2+\\lambda(u,v)\\left[z(u,v)-z^0(u,v)\\right]^2dudv\n```\nThe weighting term can be defined as below where ``\\mu`` and ``\\nu`` are parameters\nwhich control the impact of gradient of the reconstruction at each iteration and\nthe input gradients.\n```math\nW(u,v)=\\frac{1}{\\sqrt{\\left(\\frac{||\\nabla z(u,v)||}{\\mu}\\right)^2+1}}\\begin{bmatrix}\\frac{1}{\\sqrt{1+\\left(\\frac{p(u,v)}{\\nu}\\right)^2}} &0\\\\ 0 &\\frac{1}{\\sqrt{1+\\left(\\frac{q(u,v)}{\\nu}\\right)^2}}\\end{bmatrix}\n```\nThis lends itself to the creation of the terms ``A^{UV}`` and ``B^{UV}`` which\nare ``|\\Omega|\\times|\\Omega|`` diagonal matrices, respectively,  contianing the\nvalues of;\n```math\n    \\frac{1}{\\sqrt{1+\\left(\\frac{p(u,v)}{\\nu}\\right)^2}\\sqrt{\\frac{(\\partial^U_uz_{u,v})^2+(\\partial^V_vz_{u,v})^2}{\\mu^2}+1}}\n```\nand\n```math\n    \\frac{1}{\\sqrt{1+\\left(\\frac{q(u,v)}{\\nu}\\right)^2}\\sqrt{\\frac{(\\partial^U_uz_{u,v})^2+(\\partial^V_vz_{u,v})^2}{\\mu^2}+1}}\n```\nwhere ``(U,V)\\in\\{+,-\\}^2``. Using these definititions the original minimization\nproblem can be rewriten as the following iterative scheme:\n```math\n\\begin{aligned}\nz^{(k+1)}=&min\\frac{1}{4}\\sum_{(U,V)\\in\\{+,-\\}^2}\\left\\{||A^{UV}(D^U_u\\mathbf{z}-\\mathbf{p})||^2+||B^{UV}(D^V_v\\mathbf{z}-\\mathbf{q})||^2\\right\\}\\\\\n&+||\\Lambda(\\mathbf{z}-\\mathbf{z}^0)||\n\\end{aligned}\n```\nwhich is then solved using Cholesky factorization.\n# Parameters\n## `z`:\nAn `AbstractArray` which defines the value of ``z^0`` the initial solution and\nprior to be used in the regulization term.\n## `μ`:\nA `Real` which acts as a hyper-parameter to the function. Allows for the tuning\nof discontinuities. Defults to `5.0`.\n## `ν`:\nA `Real` which acts as a hyper-parameter to the function. Allows for the tuning\nof discontinuities. Unlike `μ` is has a minimal impact on the solution and generally\ndoes not need adjusting unless an extreme value for `μ` is used where it can help\nto balance out the two terms. Defults to `10.0`.\n## `λ`:\nAn `AbstractArray` the same size as `z` defulting to ``10.0^-6`` everywhere.\nThis defines theregulization weight at each point. Large valueas will force the\nalgorithm to keep the solution near to ``z^0`` at that position. Can be used to\nkeep the solution near the initial solution or guide the solution to a certian\nknown value at points (i.e. known maxima and minima). This value should be set\nuniformly small otherwise.\n## `mask`:\nAn `AbstractArray` the same size as `z`, which guides the algorithm as to where\nthe valid domain is. Values of `1` will be in the domain ``\\Omega`` while other\nvalues will be ignored and set to ``z^0``. This can be used to\nintegrate over sub-domain or to segment the domain into parts. The `gen_mask()`\nfuntion can be used to generate a mask which will remove non-integrable regions\ndramatically improving the solution under most condition at the cost of not\nintegrating the entire solution.\n# Example\nThe following example demonstrates the use of the `AnisotropicDiffusion` integrator.\n```julia\nusing ShapeFromShading, Makie\n\n# Generate synthetic gradients\np, q = synthetic_gradient(Prism(75), img_size = 151)\n\n# Create a AnisotropicDiffusion() integrator\nanisotropicDiffusion = AnisotropicDiffusion(z=zeros(size(p)), γ=1.0)\nanisotropicDiffusionInit = AnisotropicDiffusion(z=Horn()(p,q), γ=1.0)\n\n# Calculate the heightmap from the gradients\nZ = anisotropicDiffusion(p, q)\nZ2 = anisotropicDiffusionInit(p, q)\n\n# Normalize to maximum of 1 (not necessary but makes displaying easier)\nZ = Z./maximum(Z)\nZ2 = Z2./maximum(Z2)\n\n# Display using Makie (Note: Makie can often take several minutes first time)\nr = 0.0:0.1:4\nvbox(surface(r, r, Z), surface(r, r, Z2))\n```\n# Reference\n[1] Y. Quéau, J. Durou and J. Aujol, \"Variational Methods for Normal Integration\", Journal of Mathematical Imaging and Vision, vol. 60, no. 4, pp. 609-632, 2017. [doi: 10.1007/s10851-017-0777-6](https://doi.org/10.1007/s10851-017-0777-6 )\n\"\"\"\nfunction (scheme::AnisotropicDiffusion)(pIn::AbstractArray, qIn::AbstractArray)\n    λ = copy(scheme.λ)\n    z⁰ = copy(scheme.z)\n    mask = copy(scheme.mask)\n    ν = copy(scheme.ν)\n    μ = copy(scheme.μ)\n    max_iter = copy(scheme.max_iter)\n    z = copy(z⁰)\n    mask = rotr90(mask)\n    λ = rotr90(λ)\n    p = rotr90(copy(pIn)).*mask\n    q = rotr90(copy(qIn)).*mask\n    T = first(size(z))\n    index = CartesianIndices(z)\n    index = reshape(index, length(index),1)\n\n    Dᵤ⁺ = spzeros(Float64,T^2,T^2)\n    Dᵤ⁻ = spzeros(Float64,T^2,T^2)\n    Dᵥ⁺ = spzeros(Float64,T^2,T^2)\n    Dᵥ⁻ = spzeros(Float64,T^2,T^2)\n    gen_matrix(Dᵤ⁺, Dᵤ⁻, Dᵥ⁺, Dᵥ⁻,T,mask)\n    Λ = zeros(Float64,T^2,T^2)\n    P = zeros(Float64,T^2)\n    Q = zeros(Float64,T^2)\n    Z⁰ = zeros(Float64,T^2)\n    Z = zeros(Float64,T^2)\n\n    # Vectorize inputs\n    for j in CartesianIndices(z)\n        Λ[j[1]+(j[2]-1)*T,j[1]+(j[2]-1)*T] = sqrt(λ[j])\n        P[j[1]+(j[2]-1)*T] = p[j]\n        Q[j[1]+(j[2]-1)*T] = q[j]\n        Z⁰[j[1]+(j[2]-1)*T] = z⁰[j]\n        Z[j[1]+(j[2]-1)*T] = z[j]\n    end\n    Λ = sparse(Diagonal(Λ))\n\n    # Calcualte A and B for each conination in {+,-} as per eq 90 and 91\n    A⁺⁺ = Diagonal(1.0./(sqrt.(1.0.+(P./ν).^2) .* sqrt.(((Dᵤ⁺*Z).^2 .+ (Dᵥ⁺*Z).^2)./(μ^2) .+ 1)))\n    A⁻⁺ = Diagonal(1.0./(sqrt.(1.0.+(P./ν).^2) .* sqrt.(((Dᵤ⁻*Z).^2 .+ (Dᵥ⁺*Z).^2)./(μ^2) .+ 1)))\n    A⁺⁻ = Diagonal(1.0./(sqrt.(1.0.+(P./ν).^2) .* sqrt.(((Dᵤ⁺*Z).^2 .+ (Dᵥ⁻*Z).^2)./(μ^2) .+ 1)))\n    A⁻⁻ = Diagonal(1.0./(sqrt.(1.0.+(P./ν).^2) .* sqrt.(((Dᵤ⁻*Z).^2 .+ (Dᵥ⁻*Z).^2)./(μ^2) .+ 1)))\n    B⁺⁺ = Diagonal(1.0./(sqrt.(1.0.+(Q./ν).^2) .* sqrt.(((Dᵤ⁺*Z).^2 .+ (Dᵥ⁺*Z).^2)./(μ^2) .+ 1)))\n    B⁻⁺ = Diagonal(1.0./(sqrt.(1.0.+(Q./ν).^2) .* sqrt.(((Dᵤ⁻*Z).^2 .+ (Dᵥ⁺*Z).^2)./(μ^2) .+ 1)))\n    B⁺⁻ = Diagonal(1.0./(sqrt.(1.0.+(Q./ν).^2) .* sqrt.(((Dᵤ⁺*Z).^2 .+ (Dᵥ⁻*Z).^2)./(μ^2) .+ 1)))\n    B⁻⁻ = Diagonal(1.0./(sqrt.(1.0.+(Q./ν).^2) .* sqrt.(((Dᵤ⁻*Z).^2 .+ (Dᵥ⁻*Z).^2)./(μ^2) .+ 1)))\n\n    # Calculate A and b as derived from eq 92 in form Az=b\n    A = (A⁺⁺*Dᵤ⁺)*transpose(A⁺⁺*Dᵤ⁺) + (B⁺⁺*Dᵥ⁺)*transpose(B⁺⁺*Dᵥ⁺) + (A⁺⁻*Dᵤ⁺)*transpose(A⁺⁻*Dᵤ⁺) + (B⁺⁻*Dᵥ⁻)*transpose(B⁺⁻*Dᵥ⁻) + (A⁻⁺*Dᵤ⁻)*transpose( A⁻⁺*Dᵤ⁻) + (B⁻⁺*Dᵥ⁺)*transpose(B⁻⁺*Dᵥ⁺) + (A⁻⁻*Dᵤ⁻)*transpose(A⁻⁻*Dᵤ⁻) + (B⁻⁻*Dᵥ⁻)*transpose(B⁻⁻*Dᵥ⁻)\n    A = A/4.0 + Λ^2\n    b = (transpose(A⁺⁺*Dᵤ⁺)*A⁺⁺)*P + (transpose(B⁺⁺*Dᵥ⁺)*B⁺⁺)*Q + (transpose(A⁺⁻*Dᵤ⁺)*A⁺⁻)*P + (transpose(B⁺⁻*Dᵥ⁻)*B⁺⁻)*Q + (transpose(A⁻⁺*Dᵤ⁻)*A⁻⁺)*P + (transpose(B⁻⁺*Dᵥ⁺)*B⁻⁺)*Q + (transpose(A⁻⁻*Dᵤ⁻)*A⁻⁻)*P + (transpose(B⁻⁻*Dᵥ⁻)*B⁻⁻)*Q\n    b = b/4.0 + (Λ^2)*Z⁰\n    A₀ = factorize(A)\n    for i = 1:max_iter\n        # Solve system at iteration k\n        Z = A₀\\b\n\n        # Recalcualte A and B for each conination in {+,-} as per eq 90 and 91\n        A⁺⁺ = Diagonal(1.0./(sqrt.(1.0.+(P./ν).^2) .* sqrt.(((Dᵤ⁺*Z).^2 .+ (Dᵥ⁺*Z).^2)./(μ^2) .+ 1)))\n        A⁻⁺ = Diagonal(1.0./(sqrt.(1.0.+(P./ν).^2) .* sqrt.(((Dᵤ⁻*Z).^2 .+ (Dᵥ⁺*Z).^2)./(μ^2) .+ 1)))\n        A⁺⁻ = Diagonal(1.0./(sqrt.(1.0.+(P./ν).^2) .* sqrt.(((Dᵤ⁺*Z).^2 .+ (Dᵥ⁻*Z).^2)./(μ^2) .+ 1)))\n        A⁻⁻ = Diagonal(1.0./(sqrt.(1.0.+(P./ν).^2) .* sqrt.(((Dᵤ⁻*Z).^2 .+ (Dᵥ⁻*Z).^2)./(μ^2) .+ 1)))\n        B⁺⁺ = Diagonal(1.0./(sqrt.(1.0.+(Q./ν).^2) .* sqrt.(((Dᵤ⁺*Z).^2 .+ (Dᵥ⁺*Z).^2)./(μ^2) .+ 1)))\n        B⁻⁺ = Diagonal(1.0./(sqrt.(1.0.+(Q./ν).^2) .* sqrt.(((Dᵤ⁻*Z).^2 .+ (Dᵥ⁺*Z).^2)./(μ^2) .+ 1)))\n        B⁺⁻ = Diagonal(1.0./(sqrt.(1.0.+(Q./ν).^2) .* sqrt.(((Dᵤ⁺*Z).^2 .+ (Dᵥ⁻*Z).^2)./(μ^2) .+ 1)))\n        B⁻⁻ = Diagonal(1.0./(sqrt.(1.0.+(Q./ν).^2) .* sqrt.(((Dᵤ⁻*Z).^2 .+ (Dᵥ⁻*Z).^2)./(μ^2) .+ 1)))\n\n        # Recalculate A and b as derived from eq 92 in form Az=b\n        A = (A⁺⁺*Dᵤ⁺)*transpose(A⁺⁺*Dᵤ⁺) + (B⁺⁺*Dᵥ⁺)*transpose(B⁺⁺*Dᵥ⁺) + (A⁺⁻*Dᵤ⁺)*transpose(A⁺⁻*Dᵤ⁺) + (B⁺⁻*Dᵥ⁻)*transpose(B⁺⁻*Dᵥ⁻) + (A⁻⁺*Dᵤ⁻)*transpose( A⁻⁺*Dᵤ⁻) + (B⁻⁺*Dᵥ⁺)*transpose(B⁻⁺*Dᵥ⁺) + (A⁻⁻*Dᵤ⁻)*transpose(A⁻⁻*Dᵤ⁻) + (B⁻⁻*Dᵥ⁻)*transpose(B⁻⁻*Dᵥ⁻)\n        A = A/4.0 + Λ^2\n        b = (transpose(A⁺⁺*Dᵤ⁺)*A⁺⁺)*P + (transpose(B⁺⁺*Dᵥ⁺)*B⁺⁺)*Q + (transpose(A⁺⁻*Dᵤ⁺)*A⁺⁻)*P + (transpose(B⁺⁻*Dᵥ⁻)*B⁺⁻)*Q + (transpose(A⁻⁺*Dᵤ⁻)*A⁻⁺)*P + (transpose(B⁻⁺*Dᵥ⁺)*B⁻⁺)*Q + (transpose(A⁻⁻*Dᵤ⁻)*A⁻⁻)*P + (transpose(B⁻⁻*Dᵥ⁻)*B⁻⁻)*Q\n        b = b/4.0 + (Λ^2)*Z⁰\n        A₀ = factorize(A)\n    end\n\n    for j in eachindex(index)\n        z[index[j]] = Z[j]\n    end\n    z = z.*mask\n    z = rotl90(z)\n    return z\nend\n\n@doc raw\"\"\"\n```\nMumfordShah(z::AbstractArray, μ::Real = 10.0, ϵ::Real = 0.1, λ::AbstractArray = fill(10.0^-6, size(z, mask::AbstractArray = fill(1.0, size(z)), max_iter::Int = 50)\n```\nDefines the Mumford-Shah method, the final method proposed by Aujol, Durou and\nQuéau. It utilizes an adepted version of Mumford and Shah functional to provide\na good reconstruction in the presence of discontinuities at the const of a longer\nruntime then other methods.\n!!! warning\n    This function can take several minutes to run on grids larger then 64X64.\n# Output\n`MumfordShah()` returns a MumfordShah integrator which can then be called to run the\nMumford-Shah method method on a gradient field.\n# Details\nThis method involves modifying the minimization problem given by the Mumford and\nShah functional given below:\n```math\nmin\\;\\mu\\iint_{(u,v)\\in\\Omega\\backslash K}||\\nabla z(u,v)||dudv+\\int_Kd\\sigma\\\\+\\lambda\\iint_{(u,v)\\in\\Omega\\backslash K}[z(u,v)-z^0(u,v)]^2dudv\n```\nWhere ``K`` is the set of discontinuities. This can then be adapted to our problem\nby utilizing a Ambrosio-Tortelli approximation to achaive the following functional\nwhere ``\\epsilon\\to0``.\n```math\n\\begin{aligned}\nE(z)=\\mu&\\iint_{(u,v)\\in\\Omega}w(u,v)^2||\\nabla z(u,v)-\\mathbf{g}(u,v)||^2dudv\\\\\n+&\\iint_{(u,v)}\\left[\\epsilon||\\nabla w(u,v)||^2+\\frac{1}{4\\epsilon}(w(u,v)-1)^2\\right]dudv\\\\\n+&\\iint_{(u,v)}\\lambda(u,v)\\left[z(u,v)-z^0(u,v)\\right]dudv\n\\end{aligned}\n```\nThis leads to the following discretization of the functional where ``\\mathbf{w}^{+/-}_{u/v}``\nare thevecotr of weights in each forward and backward direction and the matrix\n``W^{+/-}_{u/v}`` is the diagonal matrix formed from this vector.\n```math\n\\begin{aligned}\nE(\\mathbf{z},\\mathbf{w}^{+}_{u},\\mathbf{w}^{-}_{u},\\mathbf{w}^{+}_{v},\\mathbf{w}^{-}_{v})&=\\frac{\\mu}{2}\\Big(||W^+_u(D^+_u\\mathbf{z}-\\mathbf{p})||^2+||W^-_u(D^-_u\\mathbf{z}-\\mathbf{p})||^2\\\\\n&+||W^+_v(D^+_v\\mathbf{z}-\\mathbf{q})||^2+||W^-_v(D^-_v\\mathbf{z}-\\mathbf{q})||^2\\Big)\\\\\n&+\\frac{\\epsilon}{2}\\Big(||D^+_u\\mathbf{w}^{+}_{u}||^2+||D^-_u\\mathbf{w}^{-}_{u}||^2+||D^+_v\\mathbf{w}^{+}_{v}||^2\\\\\n&+||D^-_v\\mathbf{w}^{-}_{v}||^2\\Big)+\\frac{1}{8\\epsilon}\\Big(||\\mathbf{w}^{+}_{u}-\\mathbf{1}||^2+||\\mathbf{w}^{-}_{u}-\\mathbf{1}||^2\\\\\n&+||\\mathbf{w}^{+}_{v}-\\mathbf{1}||^2+||\\mathbf{w}^{-}_{v}-\\mathbf{1}||^2\\Big)+||\\Lambda(\\mathbf{z}-\\mathbf{z}^0)||^2\n\\end{aligned}\n```\nThis is then solved with a conjugate gradient algorithm and an alternating optimization\nscheme at each step where the updates are found using the relationships below:\n```math\n\\begin{gathered}\n\\mathbf{z}^{(k+1)}=min\\;E(\\mathbf{z}^{(k)},\\mathbf{w}^{+(k)}_{u},\\mathbf{w}^{-(k)}_{u},\\mathbf{w}^{+(k)}_{v},\\mathbf{w}^{-(k)}_{v})\\\\\n\\mathbf{w}^{+/-(k+1)}_{u/v}=min\\;E(\\mathbf{z}^{(k+1},\\mathbf{w}^{+(k)}_{u},\\mathbf{w}^{-(k)}_{u},\\mathbf{w}^{+(k)}_{v},\\mathbf{w}^{-(k)}_{v})\\\\\n\\end{gathered}\n```\nThis method can produce good results if the parameters are appropriotly tuned.\nIf the parameters are too large the solution will suffer heavily from staircasing\nartifacts while setting it too small will result in a smooth solution. Even if the\nvalue is chosen correctly the algorithm tends to overfit the final solution to the\ndiscontinuities and they will extend into parts of the solution which are actually\nsmooth.\n# Parameters\n## `z`:\nAn `AbstractArray` which defines the value of ``z^0`` the initial solution and\nprior to be used in the regulization term.\n## `ϵ`:\nA `Real` which acts as a hyper-parameter to the function. Controls how the final\nsolution will converge. Large values will lead to staircasing while small values\nwill over-smooth the surface. Must be relativly small to achieve convergence to a\nsolution. Defults to `0.1`.\n## `μ`:\nA `Real` which acts as a hyper-parameter to the function. This value controls the\nsmoothness of the final solution. Large values will lead to staircasing while\nsmall values will lead to over-smoothed solutions. Defults to `10.0`.\n## `λ`:\nAn `AbstractArray` the same size as `z` defulting to ``10.0^-6`` everywhere.\nThis defines the regulization weight at each point. Large values will force the\nalgorithm to keep the solution near to ``z^0`` at that position. Can be used to\nkeep the solution near the initial solution or guide the solution to a certian\nknown value at points (i.e. known maxima and minima). This value should be set\nuniformly small otherwise.\n## `mask`:\nAn `AbstractArray` the same size as `z`, which guides the algorithm as to where\nthe valid domain is. Values of `1` will be in the domain ``\\Omega`` while other\nvalues will be ignored and set to ``z^0``. This can be used to\nintegrate over sub-domain or to segment the domain into parts. The `gen_mask()`\nfuntion can be used to generate a mask which will remove non-integrable regions\ndramatically improving the solution under most condition at the cost of not\nintegrating the entire solution.\n# Example\nThe following example demonstrates the use of the `MumfordShah` integrator.\n```julia\nusing ShapeFromShading, Makie\n\n# Generate synthetic gradients\np, q = synthetic_gradient(Prism(75), img_size = 151)\n\n# Create a MumfordShah() integrator\nmumfordShah = MumfordShah(z=zeros(size(p)), γ=1.0)\nmumfordShahInit = MumfordShah(z=Horn()(p,q), γ=1.0)\n\n# Calculate the heightmap from the gradients\nZ = mumfordShah(p, q)\nZ2 = mumfordShahInit(p, q)\n\n# Normalize to maximum of 1 (not necessary but makes displaying easier)\nZ = Z./maximum(Z)\nZ2 = Z2./maximum(Z2)\n\n# Display using Makie (Note: Makie can often take several minutes first time)\nr = 0.0:0.1:4\nvbox(surface(r, r, Z), surface(r, r, Z2))\n```\n# Reference\n[1] Y. Quéau, J. Durou and J. Aujol, \"Variational Methods for Normal Integration\", Journal of Mathematical Imaging and Vision, vol. 60, no. 4, pp. 609-632, 2017. [doi: 10.1007/s10851-017-0777-6](https://doi.org/10.1007/s10851-017-0777-6 )\n\"\"\"\nfunction (scheme::MumfordShah)(pIn::AbstractArray, qIn::AbstractArray)\n    z⁰ = copy(scheme.z)\n    λ = copy(scheme.λ)\n    mask = copy(scheme.mask)\n    ϵ = copy(scheme.ϵ)\n    μ = copy(scheme.μ)\n    max_iter = copy(scheme.max_iter)\n    z = copy(z⁰)\n    mask = rotr90(mask)\n    λ = rotr90(copy(λ))\n    p = rotr90(copy(pIn)).*mask\n    q = rotr90(copy(qIn)).*mask\n    T = first(size(z))\n    index = CartesianIndices(z)\n    index = reshape(index, length(index),1)\n\n    Dᵤ⁺ = spzeros(Float64,T^2,T^2)\n    Dᵤ⁻ = spzeros(Float64,T^2,T^2)\n    Dᵥ⁺ = spzeros(Float64,T^2,T^2)\n    Dᵥ⁻ = spzeros(Float64,T^2,T^2)\n    gen_matrix(Dᵤ⁺, Dᵤ⁻, Dᵥ⁺, Dᵥ⁻,T,mask)\n    Λ = zeros(Float64,T^2,T^2)\n    P = zeros(Float64,T^2)\n    Q = zeros(Float64,T^2)\n    Z⁰ = zeros(Float64,T^2)\n    Z = zeros(Float64,T^2)\n    # Vectorize inputs\n    for j in CartesianIndices(z)\n        Λ[j[1]+(j[2]-1)*T,j[1]+(j[2]-1)*T] = sqrt(λ[j])\n        P[j[1]+(j[2]-1)*T] = p[j]\n        Q[j[1]+(j[2]-1)*T] = q[j]\n        Z⁰[j[1]+(j[2]-1)*T] = z⁰[j]\n        Z[j[1]+(j[2]-1)*T] = z[j]\n    end\n    Λ = sparse(Diagonal(Λ))\n    wᵤ⁺ = fill(1.0, T^2)\n    wᵤ⁻ = fill(1.0, T^2)\n    wᵥ⁺ = fill(1.0, T^2)\n    wᵥ⁻ = fill(1.0, T^2)\n\n    Wᵤ⁺ = Diagonal(wᵤ⁺)\n    Wᵤ⁻ = Diagonal(wᵤ⁻)\n    Wᵥ⁺ = Diagonal(wᵥ⁺)\n    Wᵥ⁻ = Diagonal(wᵥ⁻)\n\n    A1 = μ*(transpose(Dᵤ⁺)*transpose(Wᵤ⁺)*Wᵤ⁺*Dᵤ⁺ + transpose(Dᵤ⁻)*transpose(Wᵤ⁻)*Wᵤ⁻*Dᵤ⁻ + transpose(Dᵥ⁺)*transpose(Wᵥ⁺)*Wᵥ⁺*Dᵥ⁺ + transpose(Dᵥ⁻)*transpose(Wᵥ⁻)*Wᵥ⁻*Dᵥ⁻)\n    A1 = A1 + Λ^2\n    b = μ*((transpose(Dᵤ⁺)*transpose(Wᵤ⁺)*Wᵤ⁺)*P + (transpose(Dᵤ⁻)*transpose(Wᵤ⁻)*Wᵤ⁻)*P + (transpose(Dᵥ⁺)*transpose(Wᵥ⁺)*Wᵥ⁺)*Q + (transpose(Dᵥ⁻)*transpose(Wᵥ⁻)*Wᵥ⁻)*Q)\n    b = b + (Λ^2)*Z⁰\n\n    b₀ =  Diagonal(fill(1.0/(4.0*ϵ), T^2))\n    DDᵤ⁺ = (ϵ*transpose(Dᵤ⁺)*Dᵤ⁺+b₀)\n    DDᵤ⁻ = (ϵ*transpose(Dᵤ⁻)*Dᵤ⁻+b₀)\n    DDᵥ⁺ = (ϵ*transpose(Dᵥ⁺)*Dᵥ⁺+b₀)\n    DDᵥ⁻ = (ϵ*transpose(Dᵥ⁻)*Dᵥ⁻+b₀)\n    A2 = ((Diagonal(Dᵤ⁻*Z-P)^2)*μ) + DDᵤ⁻\n    b2 = fill(1.0/(4.0*ϵ), T^2)\n    for i = 1:max_iter\n        cg!(Z, A1, b)\n\n        A2 = ((Diagonal(Dᵤ⁺*Z-P)^2)*μ) + DDᵤ⁺\n        cg!(wᵤ⁺, A2, b2)\n        Wᵤ⁺ = Diagonal(wᵤ⁺)\n\n        A2 = ((Diagonal(Dᵤ⁻*Z-P)^2)*μ) + DDᵤ⁻\n        cg!(wᵤ⁻, A2, b2)\n        Wᵤ⁻ = Diagonal(wᵤ⁻)\n\n        A2 = ((Diagonal(Dᵥ⁺*Z-Q)^2)*μ) + DDᵥ⁺\n        cg!(wᵥ⁺, A2, b2)\n        Wᵥ⁺ = Diagonal(wᵥ⁺)\n\n        A2 = ((Diagonal(Dᵥ⁻*Z-Q)^2)*μ) + DDᵥ⁻\n        cg!(wᵥ⁻, A2, b2)\n        Wᵥ⁻ = Diagonal(wᵥ⁻)\n\n        A1 = μ*(transpose(Dᵤ⁺)*transpose(Wᵤ⁺)*Wᵤ⁺*Dᵤ⁺ + transpose(Dᵤ⁻)*transpose(Wᵤ⁻)*Wᵤ⁻*Dᵤ⁻ + transpose(Dᵥ⁺)*transpose(Wᵥ⁺)*Wᵥ⁺*Dᵥ⁺ + transpose(Dᵥ⁻)*transpose(Wᵥ⁻)*Wᵥ⁻*Dᵥ⁻)\n        A1 = A1 + Λ^2\n        b = μ*((transpose(Dᵤ⁺)*transpose(Wᵤ⁺)*Wᵤ⁺)*P + (transpose(Dᵤ⁻)*transpose(Wᵤ⁻)*Wᵤ⁻)*P + (transpose(Dᵥ⁺)*transpose(Wᵥ⁺)*Wᵥ⁺)*Q + (transpose(Dᵥ⁻)*transpose(Wᵥ⁻)*Wᵥ⁻)*Q)\n        b = b + (Λ^2)*Z⁰\n    end\n\n    for j in eachindex(index)\n        z[index[j]] = Z[j]\n    end\n    z = z.*mask\n    z = rotl90(z)\n    return z\nend\n\n\n\n# function (scheme::Horn)(p::AbstractArray, q::AbstractArray, μ, ν)\n#     @show \"new\"\n#     iter = copy(scheme.max_iter)\n#     ϵ = copy(scheme.ϵ)\n#     Z = zeros(Float64, size(p))\n#     Zᵏ⁺¹ = zeros(Float64, size(p))\n#     R, C = size(p)\n#     wᵤ⁺ = zeros(Float64, size(p))\n#     wᵤ⁻ = zeros(Float64, size(p))\n#     wᵥ⁺ = zeros(Float64, size(p))\n#     wᵥ⁻ = zeros(Float64, size(p))\n#     for i in CartesianIndices(p)\n#         u,v=i.I\n#         wᵤ⁺[i] = 1.0 / (sqrt((((q[min(u+1,R),v]-q[u,v])-(p[u,min(v+1,C)]-p[u,max(v-1,1)]))/μ)^2 + 1)*sqrt(((Z[min(u+1,R),v]-Z[u,v])^2/(ν^2)+1)))\n#         wᵤ⁻[i] = 1.0 / (sqrt((((q[u,v]-q[max(u-1,1),v])-(p[u,min(v+1,C)]-p[u,max(v-1,1)]))/μ)^2 + 1)*sqrt(((Z[u,v]-Z[max(u-1,1),v])^2/(ν^2)+1)))\n#         wᵥ⁺[i] = 1.0 / (sqrt((((q[min(u+1,R),v]-q[max(u-1,1),v])-(p[u,min(v+1,C)]-p[u,v]))/μ)^2 + 1)*sqrt(((Z[u,min(v+1,C)]-Z[u,v])^2/(ν^2)+1)))\n#         wᵥ⁻[i] = 1.0 / (sqrt((((q[min(u+1,R),v]-q[max(u-1,1),v])-(p[u,v]-p[u,max(v-1,1)]))/μ)^2 + 1)*sqrt(((Z[u,v]-Z[u,max(v-1,1)])^2/(ν^2)+1)))\n#     end\n#     H = zeros(Float64, size(p))\n#     V = zeros(Float64, size(p))\n#     hv = zeros(Float64, size(p))\n#     for i = 1:R\n#         Z[i,1] = p[i,1]\n#         Z[i,R] = p[i,R]\n#     end\n#     for i = 1:C\n#         Z[1,i] = q[1,i]\n#         Z[C,i] = q[C,i]\n#     end\n#     for i = 2:(R-1)\n#         for j = 2:(C-1)\n#             H[i,j] = (wᵥ⁻[i,j+1]*(p[i,j+1]-p[i,j]) + wᵥ⁺[i,j-1]*(p[i,j]-p[i,j-1])) / 2\n#             V[i,j] = (wᵤ⁻[i+1,j]*(q[i+1,j]-q[i,j]) + wᵤ⁺[i-1,j]*(q[i,j]-q[i-1,j])) / 2\n#             # h[i,j] = (p[i,j+1] - p[i,j-1]) / 2\n#             # v[i,j] = (q[i+1,j] - q[i-1,j]) / 2\n#             hv[i,j] = ϵ * (H[i,j] - V[i,j])\n#             # hv[i,j] = hv[i,j]\n#         end\n#     end\n#     for k = 1:iter\n#         for i in CartesianIndices(p)\n#             u,v=i.I\n#             wᵤ⁺[i] = 1.0 / (sqrt((((q[min(u+1,R),v]-q[u,v])-(p[u,min(v+1,C)]-p[u,max(v-1,1)]))/μ)^2 + 1)*sqrt(((Z[min(u+1,R),v]-Z[u,v])^2/(ν^2)+1)))\n#             wᵤ⁻[i] = 1.0 / (sqrt((((q[u,v]-q[max(u-1,1),v])-(p[u,min(v+1,C)]-p[u,max(v-1,1)]))/μ)^2 + 1)*sqrt(((Z[u,v]-Z[max(u-1,1),v])^2/(ν^2)+1)))\n#             wᵥ⁺[i] = 1.0 / (sqrt((((q[min(u+1,R),v]-q[max(u-1,1),v])-(p[u,min(v+1,C)]-p[u,v]))/μ)^2 + 1)*sqrt(((Z[u,min(v+1,C)]-Z[u,v])^2/(ν^2)+1)))\n#             wᵥ⁻[i] = 1.0 / (sqrt((((q[min(u+1,R),v]-q[max(u-1,1),v])-(p[u,v]-p[u,max(v-1,1)]))/μ)^2 + 1)*sqrt(((Z[u,v]-Z[u,max(v-1,1)])^2/(ν^2)+1)))\n#         end\n#         copyto!(Zᵏ⁺¹, Z)\n#         for i = 2:(R-1)\n#             for j = 2:(C-1)\n#                 H[i,j] = (wᵥ⁻[i,j+1]*(p[i,j+1]-p[i,j]) + wᵥ⁺[i,j-1]*(p[i,j]-p[i,j-1])) / 2\n#                 V[i,j] = (wᵤ⁻[i+1,j]*(q[i+1,j]-q[i,j]) + wᵤ⁺[i-1,j]*(q[i,j]-q[i-1,j])) / 2\n#                 hv[i,j] = ϵ * (H[i,j] - V[i,j])\n#                 Zᵏ⁺¹[i,j] = (wᵤ⁺[i-1,j]*Z[i-1,j] + wᵤ⁻[i+1,j]*Z[i+1,j] + wᵥ⁺[i,j-1]*Z[i,j-1] + wᵥ⁻[i,j+1]*Z[i,j+1])\n#                 Zᵏ⁺¹[i,j] = Zᵏ⁺¹[i,j] - hv[i,j]\n#                 Zᵏ⁺¹[i,j] = Zᵏ⁺¹[i,j] / (wᵤ⁻[i+1,j] + wᵤ⁺[i-1,j] + wᵥ⁻[i,j+1] + wᵥ⁺[i,j-1])\n#             end\n#         end\n#         Z = Zᵏ⁺¹\n#     end\n#     return Z\n# end\n", "meta": {"hexsha": "c6dc9acb61516277e8e4c7d3a7e540c633b077f7", "size": 72186, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/integration.jl", "max_stars_repo_name": "betttris13/ShapeFromShading.jl", "max_stars_repo_head_hexsha": "c486ad60d1675a65aacfe61dc1ef4d308bd534e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/integration.jl", "max_issues_repo_name": "betttris13/ShapeFromShading.jl", "max_issues_repo_head_hexsha": "c486ad60d1675a65aacfe61dc1ef4d308bd534e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/integration.jl", "max_forks_repo_name": "betttris13/ShapeFromShading.jl", "max_forks_repo_head_hexsha": "c486ad60d1675a65aacfe61dc1ef4d308bd534e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9422962522, "max_line_length": 319, "alphanum_fraction": 0.615493309, "num_tokens": 29496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.8333246035907932, "lm_q1q2_score": 0.7907561056772283}}
{"text": "\"\"\"\n    is_graphical(degs::Vector{Int})\n\nCheck whether the degree sequence `degs` is graphical, according to\n[Erdös-Gallai condition](http://mathworld.wolfram.com/GraphicSequence.html).\n\nTime complexity: O(length(degs)^2)\n\"\"\"\nfunction is_graphical(degs::Vector{Int})\n    iseven(sum(degs)) || return false\n    n = length(degs)\n    cumdeg = cumsum(degs)\n    for r=1:n-1\n        cond = cumdeg[r] <= r*(r-1) + sum(i->min(r,degs[i]), r+1:n)\n        cond || return false\n    end\n    return true\nend\n\n\"\"\"\n    has_self_loops(g)\n\nReturns true if `g` has any self loops.\n\"\"\"\nhas_self_loops(g::AGraphOrDiGraph) = any(v->has_edge(g, v, v), vertices(g))\n\n\"\"\"\n    num_self_loops(g)\n\nReturns the number of self loops in `g`.\n\"\"\"\nnum_self_loops(g::AGraphOrDiGraph) = count(v->has_edge(g, v, v), vertices(g))\n", "meta": {"hexsha": "81342a00f127692fe3f4bcdd3e3c1ef787e3b489", "size": 792, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/core/misc.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Erdos.jl-90d7349d-81aa-5495-813a-883243abfe31", "max_stars_repo_head_hexsha": "2eb248772a05eac35823a07373dd5644913c6dbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2017-02-24T15:54:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T19:59:23.000Z", "max_issues_repo_path": "src/core/misc.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Erdos.jl-90d7349d-81aa-5495-813a-883243abfe31", "max_issues_repo_head_hexsha": "2eb248772a05eac35823a07373dd5644913c6dbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 76, "max_issues_repo_issues_event_min_datetime": "2017-02-23T09:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T09:10:31.000Z", "max_forks_repo_path": "src/core/misc.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Erdos.jl-90d7349d-81aa-5495-813a-883243abfe31", "max_forks_repo_head_hexsha": "2eb248772a05eac35823a07373dd5644913c6dbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-03-04T21:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:54:44.000Z", "avg_line_length": 24.0, "max_line_length": 77, "alphanum_fraction": 0.6553030303, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7907560997853276}}
{"text": "using Random, Plots, Distributions, Measures; pyplot()\n\nN = 5*10^3\nalpha = 0.05\nconfLevel = 1 - alpha\nz = quantile(Normal(),1-alpha/2) \n\nfunction randCI(n,p)\n    sample = rand(n) .< p\n    pHat = sum(sample)/n \n    serr = sqrt(pHat*(1-pHat)/n)\n    (pHat - z*serr, pHat + z*serr) \nend\ncover(p,ci) = ci[1] <= p && p <= ci[2]\n\npGrid = 0.1:0.01:0.9\nnGrid = 5:1:50\nerrs = zeros(length(nGrid),length(pGrid))\n\nfor i in 1:length(nGrid)\n    for j in 1:length(pGrid)\n        Random.seed!(0)\n        n, p = nGrid[i], pGrid[j]\n        coverageRatio = sum([cover(p,randCI(n,p)) for _ in 1:N])/N\n        errs[i,j] = confLevel - coverageRatio\n    end\nend\n\ndefault(xlabel = \"p\", ylabel = \"n\", \n    xticks =([1:5:length(pGrid);], minimum(pGrid):0.05:maximum(pGrid)),\n    yticks =([1:5:length(nGrid);], minimum(nGrid):5:maximum(nGrid)))\n\np1 = heatmap(errs, c=cgrad([:white, :black]))\np2 = heatmap(abs.(errs) .<= 0.04, legend = false, c=cgrad([:black, :white]))\nplot(p1,p2, size = (1000,400), margin = 5mm)", "meta": {"hexsha": "eee47138bff958b40614a8c123a80b6dc8541906", "size": 986, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "6_chapter/propCIcoverageAccuracy.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "6_chapter/propCIcoverageAccuracy.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "6_chapter/propCIcoverageAccuracy.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 28.1714285714, "max_line_length": 76, "alphanum_fraction": 0.5983772819, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7907389885899967}}
{"text": "## Exercise 5-2\n## The function time returns the current Greenwich Mean Time in seconds since “the epoch”, which is an arbitrary time used as a reference point. On UNIX systems, the epoch is 1 January 1970.\n\n## julia> time()\n## 1.554236060271472e9\n\n## Write a script that reads the current time and converts it to a time of day in hours, minutes, and seconds, plus the number of days since the epoch.\nprintln(\"Ans: \")\nusing Printf\n\ncurr_time = time()\n\nseconds = curr_time % 60\nh = 60 * 60\nminutes = ((curr_time - seconds) % (h))/h\nd = 60 * 60 * 24\nhours = ((curr_time - (seconds + minutes)) % (d)) / d\ndays = (curr_time - (seconds + minutes + hours)) / (60 * 60 * 24)\n\n@printf(\"%d Days, %d Hours, %d Minutes, %d Seconds\\n\", days, hours, minutes, seconds)\n\nprintln(\"End.\")\n", "meta": {"hexsha": "09843d350a7df1f438c989585c2ca8e5b8b48279", "size": 772, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter5/ex2.jl", "max_stars_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_stars_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-13T14:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T14:11:30.000Z", "max_issues_repo_path": "Chapter5/ex2.jl", "max_issues_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_issues_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter5/ex2.jl", "max_forks_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_forks_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5652173913, "max_line_length": 190, "alphanum_fraction": 0.6813471503, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8740772466456688, "lm_q1q2_score": 0.790734444403559}}
{"text": "#' ---\r\n#' title: Intro to Julia\r\n#' ---\r\n\r\n#' **Originally Contributed by**: Juan Pablo Vielma\r\n\r\n#' ## Introduction\r\n\r\n#' Since JuMP is embedded in Julia, knowing some basic Julia is important \r\n#' for learning JuMP. This notebook is designed to provide a minimalist \r\n#' crash course in the basics of Julia. You can find resources that provide \r\n#' a more comprehensive introduction to Julia [here](https://julialang.org/learning/).\r\n\r\n#' ### How to Print\r\n#' In Julia, we usually use println() to print\r\n\r\nprintln(\"Hello, World!\")\r\n\r\n#' ### Basic Data Types\r\n#' Integers\r\n\r\ntypeof(1 + -2)\r\n\r\n#' Floating point numbers\r\n\r\ntypeof(1.2 - 2.3)\r\n\r\n#' There are also some cool things like an irrational representation of π. To make π \r\n#' (and most other greek letters), type \\pi and then press [TAB].\r\n\r\nπ\r\n\r\n#+\r\n\r\ntypeof(π)\r\n\r\n#' Julia has native support for complex numbers\r\n\r\ntypeof(2 + 3im)\r\n\r\n#' Double quotes are used for strings\r\n\r\ntypeof(\"This is Julia\")\r\n\r\n#' Unicode is fine in strings\r\n\r\ntypeof(\"π is about 3.1415\")\r\n\r\n#'Julia symbols provide a way to make human readable unique identifiers.\r\n\r\n:my_id\r\ntypeof(:my_id)\r\n\r\n#' ### Arithmetic and Equality Testing\r\n\r\n#' Julia is great for math\r\n\r\n1 + 1\r\n\r\n#'Even math involving complex numbers\r\n\r\n(2 + 1im) * (1 - 2im)\r\n\r\n#' We can also write things like the following using √ (\\sqrt)\r\n\r\nsin(2π/3) == √3/2\r\n\r\n#' Wait. What???\r\n\r\nsin(2π/3) - √3/2\r\n\r\n#' Let's try again using ≈ (\\approx).\r\n\r\nsin(2π/3) ≈ √3/2\r\n\r\n#' Note that this time we used ≈ instead of ==. That is because computers don't use \r\n#' real numbers. They use a discrete representation called floating point. If you aren't \r\n#' careful, this can throw up all manner of issues. For example:\r\n\r\n1 + 1e-16 == 1\r\n\r\n#' It even turns out that floating point numbers aren't associative!\r\n\r\n(1 + 1e-16) - 1e-16 == 1 + (1e-16 - 1e-16)\r\n\r\n#' ### Vectors, Matrices and Arrays\r\n#' Similar to Matlab, Julia has native support for vectors, matrices and tensors; all of which are represented by arrays of different dimensions.\r\n#' Vectors are constructed by comma-separated elements surrounded by square brackets:\r\n\r\nb = [5, 6]\r\n\r\n#' Matrices can by constructed with spaces separating the columns, and semicolons separating the rows:\r\n\r\nA = [1 2; 3 4]\r\n\r\n#' We can do linear algebra: \r\n\r\nx = A \\ b\r\n\r\n#+ \r\n\r\nA * x\r\n\r\n#+ \r\n\r\nA * x == b\r\n \r\n#' Note that when multiplying vectors and matrices, dimensions matter. For example, you can't multiply a vector by a vector:\r\n#+ tangle = false\r\n\r\nb * b\r\n\r\n#' But multiplying transposes works: \r\n\r\n@show b' * b\r\n@show b * b';\r\n\r\n#' ### Tuples \r\n#' Julia makes extensive use of a simple data structure called Tuples.  Tuples are immutable collections of values.\r\n#' For example,\r\n\r\nt = (\"hello\", 1.2, :foo)\r\n\r\n#+ \r\n\r\ntypeof(t)\r\n \r\n#' Tuples can be accessed by index, similar to arrays, \r\n\r\nt[2]\r\n\r\n#' And can be \"unpacked\" like so, \r\n\r\na, b, c = t\r\nb\r\n\r\n#' The values can also be given names, which is a convenient way of making light-weight data structures. \r\n\r\nt = (word=\"hello\", num=1.2, sym=:foo)\r\n\r\n#' Then values can be accessed using a dot syntax, \r\n\r\nt.word\r\n\r\n#' ### Dictionaries\r\n#' Similar to Python, Julia has native support for dictionaries.  Dictionaries provide a very generic way of mapping keys to values.  For example, a map of integers to strings, \r\n\r\nd1 = Dict(1 => \"A\", 2 => \"B\", 4 => \"D\")\r\n\r\n#' Looking up a values uses the bracket syntax, \r\n\r\nd1[2]\r\n\r\n#' Dictionaries support non-integer keys and can mix data types, \r\n\r\nDict(\"A\" => 1, \"B\" => 2.5, \"D\" => 2 - 3im)\r\n\r\n#' Dictionaries can be nested \r\n\r\nd2 = Dict(\"A\" => 1, \"B\" => 2, \"D\" => Dict(:foo => 3, :bar => 4))\r\n\r\n#+ \r\n\r\nd2[\"B\"]\r\n\r\n#+ \r\n\r\nd2[\"D\"][:foo]\r\n \r\n#' ### For-Each Loops \r\n#' Julia has native support for for-each style loops with the syntax `for <value> in <collection> end`.\r\n\r\nfor i in 1:5\r\n    println(i)\r\nend\r\n\r\n#+ \r\n\r\nfor i in [1.2, 2.3, 3.4, 4.5, 5.6]\r\n    println(i)\r\nend\r\n \r\n#' This for-each loop also works with dictionaries. \r\n\r\nfor (key, value) in Dict(\"A\" => 1, \"B\" => 2.5, \"D\" => 2 - 3im)\r\n    println(\"$key: $value\")\r\nend\r\n\r\n#' Note that in contrast to vector languages like Matlab and R, loops do not result in a significant performance degradation in Julia.\r\n\r\n#' ### Control Flow\r\n#' Julia control flow is similar to Matlab, using the keywords `if-elseif-else-end`, and the logical operators `||` and `&&` for *or* and *and* respectively. \r\n\r\ni = 10\r\nfor i in 0:3:15\r\n    if i < 5 \r\n        println(\"$(i) is less than 5\")\r\n    elseif i < 10\r\n        println(\"$(i) is less than 10\")\r\n    else\r\n        if i == 10\r\n            println(\"the value is 10\")\r\n        else\r\n            println(\"$(i) is bigger than 10\")\r\n        end\r\n    end\r\nend\r\n\r\n#' ### Comprehensions\r\n#' Similar to languages like Haskell and Python, Julia supports the use of simple loops in the construction of arrays and dictionaries, called comprehenions.\r\n#' \r\n#' A list of increasing integers,\r\n\r\n[i for i in 1:5]\r\n\r\n#' Matrices can be built by including multiple indices, \r\n\r\n[i*j for i in 1:5, j in 5:10]\r\n\r\n#' Conditional statements can be used to filter out some values, \r\n\r\n[i for i in 1:10 if i%2 == 1]\r\n\r\n#' A similar syntax can be used for building dictionaries \r\n\r\nDict(\"$i\" => i for i in 1:10 if i%2 == 1)\r\n\r\n#' ### Functions \r\n#' A simple function is defined as follows,\r\n\r\nfunction print_hello()\r\n    println(\"hello\")\r\nend\r\nprint_hello()\r\n\r\n#' Arguments can be added to a function, \r\n\r\nfunction print_it(x)\r\n    println(x)\r\nend\r\nprint_it(\"hello\")\r\nprint_it(1.234)\r\nprint_it(:my_id)\r\n\r\n#' Optional keyword arguments are also possible  \r\n\r\nfunction print_it(x; prefix=\"value:\")\r\n    println(\"$(prefix) $x\")\r\nend\r\nprint_it(1.234)\r\nprint_it(1.234, prefix=\"val:\")\r\n\r\n#' The keyword `return` is used to specify the return values of a function. \r\n\r\nfunction mult(x; y=2.0)\r\n    return x * y\r\nend\r\nmult(4.0)\r\n\r\n#+ \r\n\r\nmult(4.0, y=5.0)\r\n \r\n#' ### Other notes on types \r\n#' Usually, specifing types is not required to use Julia.  However, it can be helpful to understand the basics of Julia types for debugging.\r\n#' For example this list has a type of `Array{Int64,1}` indicating that it is a one dimensional array of integer values.\r\n\r\n[1, 5, -2, 7]\r\n\r\n#' In this example, the decimal values lead to a one dimensional array of floating point values, i.e. `Array{Float64,1}`.  Notice that the integer `7` is promoted to a `Float64`, because all elements in the array need share a common type. \r\n\r\n[1.0, 5.2, -2.1, 7]\r\n\r\n#' ### Mutable vs immutable objects \r\n#' Some types in Julia are *mutable*, which means you can change the values inside them. A good example is an array. You can modify the contents of an array without having to make a new array.\r\n#' In contrast, types like `Float64` are *immutable*. You can't modify the contents of a `Float64`.\r\n#' This is something to be aware of when passing types into functions. For example:\r\n\r\nfunction mutability_example(mutable_type::Vector{Int}, immutable_type::Int)\r\n    mutable_type[1] += 1\r\n    immutable_type += 1\r\n    return\r\nend\r\n\r\nmutable_type = [1, 2, 3]\r\nimmutable_type = 1\r\n\r\nmutability_example(mutable_type, immutable_type)\r\n\r\nprintln(\"mutable_type: $(mutable_type)\")\r\nprintln(\"immutable_type: $(immutable_type)\")\r\n\r\n#' Because `Vector{Int}` is a mutable type, modifying the variable inside the function changed the value outside of the function. In constrast, the change to `immutable_type` didn't modify the value outside the function. \r\n#' You can check mutability with the `isimmutable` function.\r\n\r\n@show isimmutable([1, 2, 3])\r\n@show isimmutable(1);\r\n\r\n#' ### Using Packages and the Package Manager \r\n#' No matter how wonderful Julia's base language is, at some point you will want to use an extension package.  Some of these are built-in, for example random number generation is available in the `Random` package in the standard library. These packages are loaded with the commands `using` and `import`.\r\n\r\nusing Random\r\nRandom.seed!(33);\r\n\r\n[rand() for i in 1:10]\r\n\r\n#' The Package Manager is used to install packages that are not part of Julia's standard library. \r\n#' For example the following can be used to install JuMP,\r\n#+ tangle = false\r\n\r\nusing Pkg\r\nPkg.add(\"JuMP\")\r\n\r\n#' For a complete list of registed Julia packages see the package listing at https://pkg.julialang.org/.\r\n#' From time to you may wish to use a Julia package that is not registered.  In this case a git repository URL can be used to install the package.\r\n#+ tangle = false\r\n\r\nusing Pkg\r\nPkg.add(\"https://github.com/user-name/MyPackage.jl.git\")\r\n\r\n#' Note that for clarity this example uses the package manager `Pkg`.  Julia includes an interactive package manager that can be accessed using `]`.  [This video](https://youtu.be/76KL8aSz0Sg) gives an overview of using the interactive package manager environment. \r\n#' The state of installed packages can also be saved in two files: `Project.toml` and `Manifest.toml`. If these files are stored in the same directory than a notebook, the state of the packages can be recovered by running\r\n#+ tangle = false\r\nimport Pkg\r\nPkg.activate(@__DIR__)\r\nPkg.instantiate()\r\n\r\n#' ### HELP! \r\n#' Julia includes a help mode that can be accessed using `?`.  Entering any object (e.g. function, type, struct, ...) into the help mode will show its documentation, if any is available.\r\n\r\n#' ### Some Common Gotchas\r\n\r\n#' #### MethodError\r\n#' A common error in Julia is `MethodError`, which indicates that the function is not defined for the given value.  For example, by default the `ceil` function is not defined for complex numbers.  The \"closest candidates\" list suggest some Julia types that the function is defined for.\r\n#+ tangle = false\r\n\r\nceil(1.2 + 2.3im)\r\n", "meta": {"hexsha": "4bd93af65668939cbc77e18abe727877f34515e4", "size": 9655, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/introduction/an_introduction_to_julia.jl", "max_stars_repo_name": "mtanneau/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-07T20:43:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-06T17:51:12.000Z", "max_issues_repo_path": "script/introduction/an_introduction_to_julia.jl", "max_issues_repo_name": "mtanneau/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-05T21:03:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-05T21:03:40.000Z", "max_forks_repo_path": "script/introduction/an_introduction_to_julia.jl", "max_forks_repo_name": "mtanneau/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-18T01:29:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-18T01:29:51.000Z", "avg_line_length": 28.5650887574, "max_line_length": 304, "alphanum_fraction": 0.6702226825, "num_tokens": 2542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.9046505280315008, "lm_q1q2_score": 0.7907344293647509}}
{"text": "# poissonreg.jl\n#\n# Code for poisson regression.\n\nusing Distributions;\n\n# (A, b, x) = GeneratePoissonData(m::Int64 = 200, n::Int64 = 20)\n#\n# Generates an m-by-n matrix A of measurement vectors a_i = A[i, :], where each\n# a_i is uniform on the unit sphere. Chooses x uniformly from the sphere of\n# radius sqrt(n), and draws b_i as\n#\n#   b_i ~ Poisson(exp(a_i' * x))\nfunction GeneratePoissonData(m::Int64 = 200, n::Int64 = 20;\n                             generate_gaussian::Bool = false,\n                             condition_number::Float64 = 1.0)\n  A = randn(m, n);\n  if (!generate_gaussian)\n    A = A ./ sqrt.(repeat(sum(A.^2, dims=2), outer = (1, n)));\n  end\n  if (condition_number > 1.0)\n    # Make A have condition number given\n    condition_vec = Vector(LinRange(1.0, condition_number, n));\n    condition_vec = condition_vec / norm(condition_vec);\n    A = A .* repeat(condition_vec', outer = (m, 1));\n  end\n  x = randn(n);\n  x = sqrt(n) * x / norm(x);\n  b = zeros(Int64, m);\n  for ii = 1:m\n    R = Poisson(exp(dot(A[ii, :], x)));\n    b[ii] = rand(R);\n  end\n  return (A, b, x);\nend\n\n# PoissonObj(A::Matrix{Float64}, b::Vector{Int64}, x::Vector{Float64})\n#\n# Computes the (average) log loss for the poisson regression problem,\n# where we recall that the log-likelihood for b ~ Poisson(lambda) is\n#\n#  p(b | lambda) = exp(-lambda) * lambda^b / b!\n#\n# For a data vector a, the parameter lambda = exp(a' * x), so we have log loss\n# (ignoring the factorial term)\n#\n# l(x; (a, b)) = -b * dot(a, x) + exp(dot(a, x)).\nfunction PoissonObj(A::Matrix{Float64}, b::Vector{Int64}, x::Vector{Float64})\n  mm = size(A, 1);\n  objective = -sum(b .* (A * x)) + sum(exp.(A*x)); # no need to add b!\n  return objective / mm;\nend\n\n# g = FullPoissonGradient(A, b, x)\n#\n# Sets g to be the gradient of the poisson objective and returns it.\nfunction FullPoissonGradient(A::Matrix{Float64}, b::Vector{Int64},\n                             x::Vector{Float64})\n  mm = size(A, 1);\n  grad = (-A' * b + A' * exp.(A * x)) / mm;\n  return grad;\nend\n\n# x = ProximalUpdatePoisson(a::Vector{Float64}, b::Float64,\n#                              x_init::Vector, stepsize::Float64; accuracy)\n#\n# Sets x to minimize\n#\n#  -b * a' * x + exp(x' * a) + norm(x - x_init)^2 / (2 * stepsize).\n#\n# Returns the minimizing x. The accuracy parameter governs the\n# accuracy of the solution: we recommend a line search.\nfunction ProximalUpdatePoisson(a::Vector{Float64}, b::Int64,\n                               x_init::Vector{Float64}, stepsize::Float64;\n                               eps_accuracy::Float64 = 1e-10)\n  # Replace this code to return the correct update\n  return x_init;\nend\n\n# x = TruncatedUpdatePoisson(a::Vector{Float64}, b::Int64,\n#                            x_init::Vector{Float64}, stepsize::Float64)\n#\n# Let l(x; (a, b)) = -b * a' * x + exp(a' * x). Sets x to minimize the\n# lower-bounded approximation to F at x_init, that is, for\n#\n#  l_approx(x) = max{ l(x_init) + l'(x_init) * (x - x_init)),\n#                     inf_x l(x; (a, b)) }\n#\n# sets x to minimize\n#\n#  l_approx(x) + norm(x - x_init)^2 / (2 * stepsize).\n#\n# Returns the minimizing x.\nfunction TruncatedUpdatePoisson(a::Vector{Float64}, b::Int64,\n                                x_init::Vector{Float64}, stepsize::Float64)\n  # Replace this code to return the correct update\n  return x_init;\nend\n\n# x = SGUpdatePoisson(a::Vector{Float64}, b::Int64,\n#                     x_init::Vector{Float64}, stepsize::Float64)\n#\n# Computes the stochastic gradient update for Poisson regression.\nfunction SGUpdatePoisson(a::Vector{Float64}, b::Int64,\n                         x_init::Vector{Float64}, stepsize::Float64)\n  # Replace this code to return the correct update\n  return x_init;\nend\n", "meta": {"hexsha": "bea07782b2fbac36962fe651e810b744ee9cd77b", "size": 3713, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Machine Learning Summer School 2019 (London, UK)/tutorials/optimization/poissonreg.jl", "max_stars_repo_name": "xuedong/rlss2019", "max_stars_repo_head_hexsha": "d7468c2fcf269d8afd6fb0f44993aa9797867944", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Machine Learning Summer School 2019 (London, UK)/tutorials/optimization/poissonreg.jl", "max_issues_repo_name": "xuedong/rlss2019", "max_issues_repo_head_hexsha": "d7468c2fcf269d8afd6fb0f44993aa9797867944", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Machine Learning Summer School 2019 (London, UK)/tutorials/optimization/poissonreg.jl", "max_forks_repo_name": "xuedong/rlss2019", "max_forks_repo_head_hexsha": "d7468c2fcf269d8afd6fb0f44993aa9797867944", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0642201835, "max_line_length": 79, "alphanum_fraction": 0.6089415567, "num_tokens": 1122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.8740772253241803, "lm_q1q2_score": 0.7907344251150633}}
{"text": "# граница xэмминга про упаковку шарами\nfunction hammingND(n, d)\n  t = div(d - 1, 2)\n  binoms = [binomial(n, i) for i in 0:t]\n  println(\"binoms = $binoms\")\n  z = sum(binoms)\n  println(\"z = $z\")\n  M = 2^n / z\n  return (M, log2(M))\nend\n\nfunction hammingNK(n, k)\n  t = 0\n  b = 2^(n - k)\n  while sum([binomial(n, i) for i in 0:t]) ≤ b\n    t += 1\n  end\n  return t - 1\nend\n\nfunction varshamovGuilbertND(n, d)\n  k = 0\n  binomSum = sum([binomial(n - 1, i) for i in 0:d-2])\n  println(\"binomSum = $binomSum\")\n\n  while 2^(n - k) > binomSum\n    k += 1\n  end\n\n  return k - 1\nend\n\nfunction varshamovGuilbertNK(n, k)\n  d = 2\n  b = 2^(n - k)\n  while b > sum([binomial(n - 1, i) for i in 0:d-2])\n    d += 1\n  end\n  return d - 1\nend\n\nfunction graismer(k, d)\n  n = 0\n  for i = 0:k-1\n    n += ceil(Int64, d / 2^i)\n  end\n  return n\nend\n\nfunction graismerD(n, k)\n  # n > sum(d/2^i) from 0 to k\n  d = 0\n  while true\n    sums = sum([ceil(Int64, d / 2^i) for i in 0:k-1])\n    if n > sums\n      d += 1\n    else\n      break\n    end\n  end\n\n  return d - 1\nend\n\nn, k, d = 21, 13, 14\n\n# наxождение k по n и d\n#\n# M, klog = hammingND(n, d)\n# println(\"граница Хэмминга: M ≤ $M, k ≈ $(klog)\")\n\n# println(\"==============================\")\n\n# mink = varshamovGuilbertND(n, d)\n# println(\"граница Варшамова-Гилберта: k ≥ $mink\")\n\n# println(\"==============================\")\n# println(graismer(9, d))\n# println(\"###################################\")\n\n# наxождение d по n и k\n#\nt = hammingNK(n, k)\nprintln(\"граница Хэмминга: t ≤ $t\")\n\nprintln(\"==============================\")\n\nmind = varshamovGuilbertNK(n, k)\nprintln(\"граница Варшамова-Гилберта: d ≥ $mind\")\n\nprintln(\"==============================\")\nprintln(\"граница Грайсмера: $(graismerD(n, k))\")\nprintln(\"###################################\")\n\n", "meta": {"hexsha": "fff6eeadb1e5089512ed3a4667c2083a2d416196", "size": 1759, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "coding-theory/ch3/border.jl", "max_stars_repo_name": "ChShersh/university-courses", "max_stars_repo_head_hexsha": "b78ab71d9b62e31de34efa4a93ac6fbe684c4ac0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "coding-theory/ch3/border.jl", "max_issues_repo_name": "ChShersh/university-courses", "max_issues_repo_head_hexsha": "b78ab71d9b62e31de34efa4a93ac6fbe684c4ac0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coding-theory/ch3/border.jl", "max_forks_repo_name": "ChShersh/university-courses", "max_forks_repo_head_hexsha": "b78ab71d9b62e31de34efa4a93ac6fbe684c4ac0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5157894737, "max_line_length": 53, "alphanum_fraction": 0.5127913587, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.8479677526147222, "lm_q1q2_score": 0.7906903430992811}}
{"text": "### ntt.jl\n#\n# Copyright (C) 2019 Jakub Wronowski.\n#\n# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>\n# Keywords: number theoretic transform\n#\n# This file is a part of NumberTheoreticTransforms.jl.\n#\n# License is MIT.\n#\n### Commentary:\n#\n# This file contains implementation of general Number Theoretic Transform.\n#\n### Code:\n\nexport ntt, intt\n\n\"\"\"\nConstraints on NTT params to ensure that inverse can be computed\n\"\"\"\nfunction validate(N, g, q)\n    @assert mod(q - 1, N) == 0 \n    @assert powermod(g, N, q) == 1\n    @assert !(1 in powermod.(g, 2:N-1, q)) # this may be redundant\n    @assert gcd(N, q) == 1\nend\n\n\"\"\"\n    ntt(x::Array{T,1}, g, q) -> Array{T,1}\n\nThe [Number Theoretic Transform](https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general)#Number-theoretic_transform)\ntransforms data in a similar fashion to DFT, but instead complex roots of unity\nit uses integer roots with all operation defined in a finite field (modulo an\ninteger number).\n\n`ntt` function implements Number Theoretic Transform directly from the formula,\nso it is flexible about choosing transformation params but lacks performance.\n\n``\\\\bar{x}_k = \\\\sum_{n=1}^N{x_n g^{(n-1)(k-1)} } \\\\mod q``\n\nThere is also a few constraints on choosing parameters and input length to\nensure that inverse exists and equals to the original input:\n-   ``g`` must ``N``-th root of one in modulo ``q`` arithmetic\n-   ``q-1`` mod ``N`` must be equal zero\n-   ``q`` must be grater than maximum element present in transformed array\n\nTo find parameter set you may use fint-ntt script.\n\nThe arguments of `ntt` function are\n\n-   `x`: input data, its elements must be smaller than q\n-   `g`: transform power base, must have inversion modulo q \n-   `q`: defines modulo arithmetic\n\"\"\"\nfunction ntt(x::Array{T,1}, g::T, q::T) where {T<:Integer}\n    N = length(x)\n    #TODO: more validation of p,q, decompose it to struct\n    #TODO: create transform object that validates input in the constructor\n\n    validate(N, g, q)\n    (lo, hi) = extrema(x)\n    @assert lo >= 0\n    @assert hi <= q-1\n\n\n    t = [powermod(g, n * k, q) for n in 0:N-1, k in 0:N-1]\n    #TODO: make result of ntt a struct that will hold infrmation about g\n    return mod.(t * x, q)\nend\n\n# TODO: change implementation to handle any number of dimensions\n# it can be done calling N-1 dimensional transform in a loop\n\nfunction ntt(x::Array{T,2}, g::T, q::T) where {T<:Integer}\n    N, M = size(x)\n    @assert N == M #TODO: make it work for N != M (need different g for each dim)\n    y = zeros(T, size(x))\n\n    for n in 1:N\n        y[n, :] = ntt(x[n, :], g, q)\n    end\n\n    for m in 1:M\n        y[:, m] = ntt(y[:, m], g, q)\n    end\n\n    return y\nend\n\n\"\"\"\n    intt(y::Array{T,1}, g, q) -> Array{T,1}\n\nInverse Number Theoretic Transform implementation directly from the formula.\n\n``x_k = N^{-1} \\\\sum_{n=1}^N{\\\\bar{x}_n g^{-(n-1)(k-1)} } \\\\mod q``\n\nThe same input parameters constraints as for `ntt` function must be applied\n\"\"\"\nfunction intt(y::Array{T,1}, g::T, q::T) where {T<:Integer}\n    N = length(y)\n   \n    validate(N, g, q)\n    \n    inv_g = invmod(g, q)\n    inv_N = invmod(N, q)\n    t = [powermod(inv_g, l * k, q) for k in 0:N-1, l in 0:N-1]\n    return mod.(inv_N * t * y, q)\nend\n\nfunction intt(y::Array{T,2}, g::T, q::T) where {T<:Integer}\n    N, M = size(y)\n    x = zeros(T, size(y))\n\n    for m in 1:M\n        x[:, m] = intt(y[:, m], g, q)\n    end\n\n    for n in 1:N\n        x[n, :] = intt(x[n, :], g, q)\n    end\n    \n    return x\nend\n\n# those implementations are incorrect but transform results were interesing anyway\n# TODO: check if those calculations are useful\n\n# function ntt(g::T, q::T, x::Array{T,N}) where {T <: Integer,N}\n#     return reshape(ntt(g, q, reshape(x, length(x))), size(x))\n# end\n\n# function intt(g::T, q::T, y::Array{T,N}) where {T <: Integer,N}\n#     return reshape(intt(g, q, reshape(y, length(y))), size(y))\n# end\n", "meta": {"hexsha": "1aab85b4152065bb59b65592900543cb088c4784", "size": 3882, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ntt.jl", "max_stars_repo_name": "jakubwro/NumberTheoreticTransforms.jl", "max_stars_repo_head_hexsha": "5e933d4edcbb05926be2ede4e2c2105d381ebd7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-02-07T16:55:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T21:41:34.000Z", "max_issues_repo_path": "src/ntt.jl", "max_issues_repo_name": "jakubwro/NumberTheoreticTransforms.jl", "max_issues_repo_head_hexsha": "5e933d4edcbb05926be2ede4e2c2105d381ebd7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-10T20:53:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-17T13:53:27.000Z", "max_forks_repo_path": "src/ntt.jl", "max_forks_repo_name": "jakubwro/NumberTheoreticTransforms.jl", "max_forks_repo_head_hexsha": "5e933d4edcbb05926be2ede4e2c2105d381ebd7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3357664234, "max_line_length": 127, "alphanum_fraction": 0.6373003606, "num_tokens": 1219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7906903427050461}}
{"text": "\"\"\"\nArea scaling factor for a function f with partial derivatives fx, fy\n    * fx::Function\n    * fy::Function\n\nReturns:\n    * [Function] : Area scaling factor at x.\n\"\"\"\nfunction af(fx, fy)\n    return x -> norm(fx(x)×fy(x))\nend\n\n\nfunction af(f)\n    # Find partial derivatives\n    fx(x) = ForwardDiff.derivative(z -> f([z, x[2]]), x[1])\n    fy(x) = ForwardDiff.derivative(z -> f([x[1], z]), x[2])\n    \n    # Compute area scaling factor\n    return x -> norm(fx(x)×fy(x))\nend\n\n\"\"\"\nDerivative of area scaling factor for a function f with derivatives \n    * fx::Function\n    * fy::Function\n    * fxx::Function\n    * fxy::Function\n    * fyy::Function\n\nReturns:\n    * [Function] : Derivative of area scaling factor at x.\n\"\"\"\nfunction Daf(af, fx, fy, fxx, fxy, fyy)\n    return x -> [\n        (fxx(x) × fy(x) - fxy(x) × fx(x)) ⋅ (fx(x) × fy(x)) / af(x)\n        (fxy(x) × fy(x) - fyy(x) × fx(x)) ⋅ (fx(x) × fy(x)) / af(x)\n    ]\nend\n\n\n\"\"\"\nGet q-map and derivative of a given function\n    * f::Function\n\nReturns:\n    * q::Function, Dq::Function\n\"\"\"\nfunction Qmap(f)\n    # Find partial derivatives\n    fx(x) = ForwardDiff.derivative(z -> f([z, x[2]]), x[1])\n    fy(x) = ForwardDiff.derivative(z -> f([x[1], z]), x[2])\n    \n    # Compute area scaling factor\n    a = af(fx, fy)\n    \n    # Return q-map and derivative \n    q(x) = √a(x) * f(x)\n    Dq(x) = ForwardDiff.jacobian(q, x)\n    return q, Dq\nend\n\n\n\"\"\"\nGet q-map and derivative of a given function with derivatives\n    * f::Function\n    * fx::Function\n    * fy::Function\n\nReturns:\n    * q::Function, Dq::Function\n\"\"\"\nfunction Qmap(f, fx, fy)\n    a = af(fx, fy)\n    \n    q(x) = √a(x) * f(x)\n    Dq(x) = ForwardDiff.jacobian(q, x)\n    return q, Dq\nend\n\n\n\"\"\"\nGet q-map and derivative of a given function with derivatives\n    * f::Function\n    * fx::Function\n    * fy::Function\n    * fxx::Function\n    * fxy::Function\n    * fyy::Function\n\nReturns:\n    * q::Function, Dq::Function\n\"\"\"\nfunction Qmap(f, fx, fy, fxx, fxy, fyy)\n    a = af(fx, fy)\n    Da = Daf(a, fx, fy, fxx, fxy, fyy)\n    \n    Df(x) = [fx(x) fy(x)]\n    q(x) = √a(x) * f(x)\n    Dq(x) = 1. / (2. * √a(x)) * f(x) * Da(x)' + √a(x) * Df(x)\n    return q, Dq\nend\n\n\"\"\"\nCompute the centroid of the parametric surface.\n    * f::Function\n    * af:: Function\n\nReturns: \n    * [Array{Float}] : Vector value of surface centre\n\"\"\"\nfunction surface_centroid(f, af)\n    return hcubature(x -> f(x)*af(x), [0, 0], [1, 1])[1] / hcubature(af, [0, 0], [1, 1])[1]\nend\n\n\n\"\"\"\nTranslate function so that centroid coincides with the origin.\n    * f::Function\n    * af:: Function\n\nReturns: \n    * [Function] : Translated Surface\n\"\"\"\nfunction centered(f, af)\n    c = surface_centroid(f, af)\n    return x -> f(x) - c\nend\n\n\n\"\"\"\nCompute the parametric surface area.\n    * f::Function\n    * af:: Function\n\nReturns: \n    * [Float] : Surface Area\n\"\"\"\nfunction surface_area(f, af)\n    return hcubature(af, [0, 0], [1, 1])[1]\nend\n\n\n\"\"\"\nScale surface to unit area.\n    * f::Function\n    * af:: Function\n\nReturns: \n    * [Function] : Scaled Surface\n\"\"\"\nfunction scale_surface(f, af)\n    s = surface_area(f, af)\n    return x -> f(x) / s\nend\n\n\n\"\"\"\nTranslate and scale surface \n    * f::Function\n\nReturns: \n    * [Function] : Scaled Surface\n\"\"\"\nfunction normalize_surface(f)\n    # Find partial derivatives\n    fx(x) = ForwardDiff.derivative(z -> f([z, x[2]]), x[1])\n    fy(x) = ForwardDiff.derivative(z -> f([x[1], z]), x[2])\n    \n    # Compute area scaling factor\n    a = af(fx, fy)\n    \n    c = surface_centroid(f, a)\n    s = surface_area(f, a)\n    return x -> (f(x) - c) / s\nend\n\n\n\"\"\"\nTranslate and scale surface \n    * f::Function\n    * af:: Function\n\nReturns: \n    * [Function] : Scaled Surface\n\"\"\"\nfunction normalize_surface(f, af)\n    c = surface_centroid(f, af)\n    s = surface_area(f, af)\n    return x -> (f(x) - c) / s\nend", "meta": {"hexsha": "5e8a8d0ef5c9a994c7bce2c56de17fc84aaf7289", "size": 3790, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/qmap.jl", "max_stars_repo_name": "jorgenriseth/SurfaceRegistration.jl", "max_stars_repo_head_hexsha": "6b0305fedc552e6fe5c5d74aa0df8a1cc27971ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/qmap.jl", "max_issues_repo_name": "jorgenriseth/SurfaceRegistration.jl", "max_issues_repo_head_hexsha": "6b0305fedc552e6fe5c5d74aa0df8a1cc27971ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/qmap.jl", "max_forks_repo_name": "jorgenriseth/SurfaceRegistration.jl", "max_forks_repo_head_hexsha": "6b0305fedc552e6fe5c5d74aa0df8a1cc27971ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8429319372, "max_line_length": 91, "alphanum_fraction": 0.5715039578, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7906903335490946}}
{"text": "using Plots; plotlyjs()  \nusing FFTW \n\n# Construct a signal \nf = 1\nfs = 5\nts = 1 / fs \nl = 2^10 + 1\nt = (-(l - 1) ÷ 2 : (l - 1) ÷ 2) * ts \nx = sinc.(f * t) \n\n# Construct the frequency spectrum \nxf = fft(x)\nff = (0 : 1 / (l - 1) : 1) * fs \n\n# Signal energy \nΔt = ts \nΔf = fs / (l - 1)\nEt = sum(abs.(x).^2) * Δt \nEf = sum(abs.(xf).^2) * Δf / (fs^2)\n@show Et, Ef\n\n# Plots \nplt = plot(layout=2) \nplot!(t, x, subplot=1) \nplot!(ff, abs.(xf), subplot=2) \ndisplay(plt) \n", "meta": {"hexsha": "c3acc6db4d77aebb5ce50977805f2330ff0c40ce", "size": 462, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/dsp/sinc.jl", "max_stars_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_stars_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-03T20:02:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T06:43:38.000Z", "max_issues_repo_path": "example/dsp/sinc.jl", "max_issues_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_issues_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-11-26T21:56:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-03T19:54:59.000Z", "max_forks_repo_path": "example/dsp/sinc.jl", "max_forks_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_forks_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-20T12:53:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T12:53:43.000Z", "avg_line_length": 16.5, "max_line_length": 38, "alphanum_fraction": 0.5151515152, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214511730025, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7906407272513744}}
{"text": "# This file is pat of RLinearAlgebra.jl\n# 1. Specifies type\n# 2. Implements rsubsolve function\n# 3. Exports Type\n\n#using LinearAlgebra\n\n\"\"\"\n    LinSysVecRowProjFO <: LinSysVecRowProjection\n\nA mutable structure that represents the standard row projection method\nwith full orthogonalization against all previous projections. Equivalently, this type\nrepresents a solver for incrementally constructed matrix sketches.\n\nSee McCormick, S. F. \"The methods of Kaczmarz and row orthogonalization for solving linear\n    equations and least squares problems in Hilbert space.\" Indiana University Mathematics\n    Journal 26.6 (1977): 1137-1150. https://www.jstor.org/stable/24891603\n\nSee Patel, Vivak, Mohammad Jahangoshahi, and Daniel Adrian Maldonado. \"An Implicit\n    Representation and Iterative Solution of Randomly Sketched Linear Systems.\"\n    SIAM Journal on Matrix Analysis and Applications (2021) 42:2, 800-831.\n    https://doi.org/10.1137/19M1259481\n\n# Fields\n\n- `S::Union{Matrix{Float64}, Nothing}` is a matrix used for orthogonalizing against\n    all previous search directions.\n\nCalling `LinSysVecRowProjFO()` defaults to `LinSysVecRowProjFO(nothing)`.\n\"\"\"\nmutable struct LinSysVecRowProjFO <: LinSysVecRowProjection\n    S::Union{Matrix{Float64}, Nothing}\nend\nLinSysVecRowProjFO() = LinSysVecRowProjFO(nothing)\n\n# Common rsubsolve interface for linear systems\nfunction rsubsolve!(\n    type::LinSysVecRowProjFO,\n    x::AbstractVector,\n    samp::Tuple{U,V} where {U<:AbstractVector,V<:Real},\n    iter::Int64,\n)\n    # samp[1] is vector in the row space of the coefficient matrix\n    # samp[2] is a scalar corresponding to samp[1]\n\n    # Allocate space for orthogonalization matrix S\n    if iter == 1\n        d = length(x)\n        type.S = diagm(ones(Float64, d))\n    end\n\n    #Compute orthogonal component of q using S (projection matrix)\n    u = type.S * samp[1]\n\n    if dot(u,u) < eps()^2 * length(x)\n        return nothing\n    end\n\n    #Update Iterate\n    res = samp[2] - dot(samp[1], x)\n    γ = dot(u, samp[1])\n    x .= x + u * ( res / γ )\n\n    #Update Projection matrix\n    type.S .= (I - (u/γ)*samp[1]')*type.S\n\n    return nothing\nend\n", "meta": {"hexsha": "4a59b6474ed86b7c61d1ada0f63296598fc0423c", "size": 2140, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear_solver_routines/vec_row_projection_fortho.jl", "max_stars_repo_name": "numlinalg/RLinearAlgebra.jl", "max_stars_repo_head_hexsha": "757cc7e581303c4fb6db228618f4be5caa02d3b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-05-28T17:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T05:23:14.000Z", "max_issues_repo_path": "src/linear_solver_routines/vec_row_projection_fortho.jl", "max_issues_repo_name": "numlinalg/RLinearAlgebra.jl", "max_issues_repo_head_hexsha": "757cc7e581303c4fb6db228618f4be5caa02d3b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-06-16T16:01:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-16T12:28:20.000Z", "max_forks_repo_path": "src/linear_solver_routines/vec_row_projection_fortho.jl", "max_forks_repo_name": "numlinalg/RLinearAlgebra.jl", "max_forks_repo_head_hexsha": "757cc7e581303c4fb6db228618f4be5caa02d3b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0144927536, "max_line_length": 90, "alphanum_fraction": 0.7154205607, "num_tokens": 594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.8596637577007394, "lm_q1q2_score": 0.7905833559870409}}
{"text": "function isValid(input::String)\n    checkNine(n) = n > 9 ? n - 9 : n\n\n    input = filter(x -> x != ' ' ,collect(input))\n\n    length(input) <= 1 && return false\n\n    parsedArr = try\n        map(x -> parse(Int,x), input)\n    catch\n        return false\n    end\n\n    flag = true\n    result = 0\n    for i in reverse(parsedArr)\n        if flag\n            result += i\n        else\n            result += checkNine(2 * i)\n        end\n        flag = !flag\n    end\n\n    0 == (result % 10)\nend\n", "meta": {"hexsha": "222d1727bf721d8e15dfb1d18a0274784fea89d4", "size": 483, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Luhn-Algorithm/LA.jl", "max_stars_repo_name": "ccqpein/Arithmetic-Exercises", "max_stars_repo_head_hexsha": "748d7ac1313892d47eb0a66a0b7705e6d33b43ad", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-07-11T03:07:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T06:46:10.000Z", "max_issues_repo_path": "Luhn-Algorithm/LA.jl", "max_issues_repo_name": "ccqpein/Arithmetic-Exercises", "max_issues_repo_head_hexsha": "748d7ac1313892d47eb0a66a0b7705e6d33b43ad", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Luhn-Algorithm/LA.jl", "max_forks_repo_name": "ccqpein/Arithmetic-Exercises", "max_forks_repo_head_hexsha": "748d7ac1313892d47eb0a66a0b7705e6d33b43ad", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-12-06T22:19:33.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T22:19:33.000Z", "avg_line_length": 17.8888888889, "max_line_length": 49, "alphanum_fraction": 0.4865424431, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7905833545738676}}
{"text": "using Pkg\nPkg.activate(pwd())\n\n# # Neural networks\n# ## Prepare data\n\nusing RDatasets\n\niris = dataset(\"datasets\", \"iris\")\nX = Matrix(iris[:, 1:4])\ny = iris.Species\n\n#### Exercise:\n#Write the `split` function, which randomly splits the dataset and the labels into training \n#and testing sets. Its input should be the dataset `X` and the labels `y`. It should have \n#four outputs. Include 80% of data in the training set and 20% of data in the testing set \n# by default.\n#\n#**Hints:**\n#- Use the `randperm` function from the `Random` package.\n#- While `y` can be assumed to a vector, `X` is a matrix or a more-dimensional array. Then \n#it is beneficial to use the `selectdim` function to select subindices along the correct \n#dimension.\n#\n#---\n#### Solution:\n\nusing Random\n\nfunction split(X, y::AbstractVector; dims=1, ratio_train=0.8, kwargs...)\n    n = length(y)\n    size(X, dims) == n || throw(DimensionMismatch(\"...\"))\n\n    n_train = round(Int, ratio_train*n)\n    i_rand = randperm(n)\n    i_train = i_rand[1:n_train]\n    i_test = i_rand[n_train+1:end]\n\n    return selectdim(X, dims, i_train), y[i_train], selectdim(X, dims, i_test), y[i_test]\nend\n\n#+\n\nX_train, y_train, X_test, y_test = split(X, y)\n\n# ---\n# \n# ### Exercise:\n# Write the `normalize` functions as described above. It should have two inputs and two \n# outputs. The keyword argument `dims` should also be included.\n# \n# **Hint**: check the help for the `mean` function.\n# \n# ---\n# ### Solution:\n\nusing Statistics\n\nfunction normalize(X_train, X_test; dims=1, kwargs...)\n    col_mean = mean(X_train; dims)\n    col_std = std(X_train; dims)\n\n    return (X_train .- col_mean) ./ col_std, (X_test .- col_mean) ./ col_std\nend\n\n#+\n\nX_train, X_test = normalize(X_train, X_test)\n\n# ---\n# \n# ### Exercise:\n# Write the `onehot` function that converts the labels `y` into their one-hot \n# representation. The samples should be along the second dimension. Write the `onecold` \n# function that converts the one-hot representation into the one-cold (original)\n# representation. Both these functions need to have two arguments; the second one is \n# `classes`, which equals `unique(y)`.\n# \n# Write a check that both functions work correctly.\n# \n# **Hints:**\n# - The one-hot representation for a label has the size equalling to the number of classes. \n# All entries besides one are zeros.\n# - Since the one-hot representation represents probabilities, the prediction is the class \n# with the highest probability.\n# \n# ---\n# ### Solution:\n\nfunction onehot(y, classes)\n    y_onehot = falses(length(classes), length(y))\n    for (i, class) in enumerate(classes)\n        y_onehot[i, y .== class] .= 1\n    end\n    return y_onehot\nend\n\nonecold(y, classes) = [classes[argmax(y_col)] for y_col in eachcol(y)]\n\n#+\n\nclasses = unique(y)\nisequal(onecold(onehot(y, classes), classes), y)\n\n# ---\n\nusing LinearAlgebra\n\nfunction prepare_data(X, y; do_normal=true, do_onehot=true, kwargs...)\n    X_train, y_train, X_test, y_test = split(X, y; kwargs...)\n\n    if do_normal\n        X_train, X_test = normalize(X_train, X_test; kwargs...)\n    end\n\n    classes = unique(y)\n\n    if do_onehot\n        y_train = onehot(y_train, classes)\n        y_test = onehot(y_test, classes)\n    end\n\n    return X_train, y_train, X_test, y_test, classes\nend\n\n#+\n\nRandom.seed!(666)\n\niris = dataset(\"datasets\", \"iris\")\nX = Matrix(iris[:, 1:4])\ny = iris.Species\n\nX_train, y_train, X_test, y_test, classes = prepare_data(X', y; dims=2)\n\n#+\n\nRandom.seed!(666)\naux1 = prepare_data(X, y; dims=1)\n\n#+\n\nRandom.seed!(666)\naux2 = prepare_data(X', y; dims=2)\n\n#+\n\nnorm(aux1[1] - aux2[1]')\n\n# ## Create the network\n\nstruct SimpleNet{T<:Real}\n    W1::Matrix{T}\n    b1::Vector{T}\n    W2::Matrix{T}\n    b2::Vector{T}\nend\n\n# ### Exercise:\n# Write an outer constructor for `SimpleNet`. Its inputs should be three integers \n# representing the input size of the three layers. All matrices should be initialized based \n# on the normal distribution.\n# \n# **Hint**: think about the representation of the dense layer.\n# \n# ---\n# ### Solution:\n\nSimpleNet(n1, n2, n3) = SimpleNet(randn(n2, n1), randn(n2), randn(n3, n2), randn(n3))\n\n# ---\n\nRandom.seed!(666)\nm = SimpleNet(size(X_train,1), 5, size(y_train,1))\n\n# ### Exercise:\n# Write a functor `function (m::SimpleNet)(x)` which computes the prediction (forward pass) \n# of the neural network `SimpleNet`.\n# \n# **Bonus**: try to make the functor work for both vectors (one sample) and matrices \n# (multiple samples) `x`.\n# \n# ---\n# ### Solution:\n\nfunction (m::SimpleNet)(x)\n    z1 = m.W1*x .+ m.b1\n    a1 = max.(z1, 0)\n    z2 = m.W2*a1 .+ m.b2\n    return exp.(z2) ./ sum(exp.(z2), dims=1)\nend\n\n# ---\n\nm(X_train[:,1:2]) \n\n# ## Train the network\n\nfunction grad(m::SimpleNet, x::AbstractVector, y; ϵ=1e-10)\n    z1 = m.W1*x .+ m.b1\n    a1 = max.(z1, 0)\n    z2 = m.W2*a1 .+ m.b2\n    a2 = exp.(z2) ./ sum(exp.(z2), dims=1)\n    l = -sum(y .* log.(a2 .+ ϵ))\n\n    e_z2 = exp.(z2)\n    l_part = (- e_z2 * e_z2' + Diagonal(e_z2 .* sum(e_z2))) / sum(e_z2)^2\n\n    l_a2 = - y ./ (a2 .+ ϵ)\n    l_z2 = l_part * l_a2\n    l_a1 = m.W2' * l_z2\n    l_z1 = l_a1 .* (a1 .> 0)\n    l_x = m.W1' * l_z1\n\n    l_W2 = l_z2 * a1'\n    l_b2 = l_z2\n    l_W1 = l_z1 * x'\n    l_b1 = l_z1\n\n    return l, l_W1, l_b1, l_W2, l_b2\nend\n\n#+\n\ng_all = [grad(m, X_train[:,k], y_train[:,k]) for k in 1:size(X_train,2)]\ntypeof(g_all)\n\n#+\n\nfunction mean_tuple(d::AbstractArray{<:Tuple})\n    Tuple([mean([d[k][i] for k in 1:length(d)]) for i in 1:length(d[1])])\nend\n\n#+\n\ng_mean = mean_tuple(g_all)\ntypeof(g_mean)\n\n# ### Exercise:\n# Train the network with a gradient descent with stepsize ``\\alpha=0.1`` for ``200`` \n# iterations. Save the objective value at each iteration and plot the results.\n# \n# ---\n# ### Solution:\n\nα = 1e-1\nmax_iter = 200\nL = zeros(max_iter)\n\nfor iter in 1:max_iter\n    grad_all = [grad(m, X_train[:,k], y_train[:,k]) for k in 1:size(X_train,2)]\n    grad_mean = mean_tuple(grad_all)\n\n    L[iter] = grad_mean[1]\n\n    m.W1 .-= α*grad_mean[2]\n    m.b1 .-= α*grad_mean[3]\n    m.W2 .-= α*grad_mean[4]\n    m.b2 .-= α*grad_mean[5]\nend\n\n# ---\n\nusing Plots\n\nplot(L;\n    xlabel=\"Iteration\",\n    ylabel=\"Loss function\",\n    label=\"\",\n    title=\"Loss function on the training set\"\n)\n\n# ## Prediction\n# ### Exercise:\n# \n# Write a function which predict the labels for samples. Show the accuracy on both training # and testing sets.\n# \n# ---\n# ### Solution:\n\npredict(X) = m(X)\naccuracy(X, y) = mean(onecold(predict(X), classes) .== onecold(y, classes))\n\nprintln(\"Train accuracy = \", accuracy(X_train, y_train))\nprintln(\"Test accuracy = \", accuracy(X_test, y_test))", "meta": {"hexsha": "4cf46be6e4e6abe70e383bbc162048aac6a53944", "size": 6553, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_10/01-nn-solved.jl", "max_stars_repo_name": "JuliaTeachingCTU/Julia-for-Optimization-and-Learning-Scripts", "max_stars_repo_head_hexsha": "8e00299449736e4ccf47c247aa9d80f99a7e5b92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lecture_10/01-nn-solved.jl", "max_issues_repo_name": "JuliaTeachingCTU/Julia-for-Optimization-and-Learning-Scripts", "max_issues_repo_head_hexsha": "8e00299449736e4ccf47c247aa9d80f99a7e5b92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecture_10/01-nn-solved.jl", "max_forks_repo_name": "JuliaTeachingCTU/Julia-for-Optimization-and-Learning-Scripts", "max_forks_repo_head_hexsha": "8e00299449736e4ccf47c247aa9d80f99a7e5b92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9929824561, "max_line_length": 111, "alphanum_fraction": 0.6464214863, "num_tokens": 2015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7905833545738676}}
{"text": "# NOTE: we now have an AbstractODEProblem\nabstract type AbstractODEProblem end\n\nstruct ODEProblem{F,T<:Tuple{Number,Number},U<:AbstractVector,P<:AbstractVector} <: AbstractODEProblem\n    f::F\n    tspan::T\n    u0::U\n    θ::P\nend\n\n\nabstract type ODESolver end\n\nstruct Euler{T} <: ODESolver\n    dt::T\nend\n\nfunction (solver::Euler)(prob::AbstractODEProblem, u, t)\n    f, θ, dt  = prob.f, prob.θ, solver.dt\n    (u + dt*f(u,θ), t+dt)\nend\nstruct RK2{T} <: ODESolver\n    dt::T\nend\nfunction (solver::RK2)(prob::AbstractODEProblem, u, t)\n    f, θ, dt  = prob.f, prob.θ, solver.dt\n    du = f(u,θ)\n    uh = u + du*dt\n    u + dt/2*(du + f(uh,θ)), t+dt\nend\n\n\nfunction solve(prob::AbstractODEProblem, solver::ODESolver)\n    t = prob.tspan[1]; u = prob.u0\n    us = [u]; ts = [t]\n    while t < prob.tspan[2]\n        (u,t) = solver(prob, u, t)\n        push!(us,u)\n        push!(ts,t)\n    end\n    # NOTE: we are not `reduce(hcat,us)`ing any more\n    ts, us\nend\n", "meta": {"hexsha": "5bf1edee00804c8ce520f3487cd772d3aabb7305", "size": 942, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/lecture_13/lab/ode-solver.jl", "max_stars_repo_name": "JuliaTeachingCTU/Scientific-Programming-in-Julia", "max_stars_repo_head_hexsha": "7e978fc27ae547fbf95d1367ef1d1d029267e356", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2021-11-12T10:17:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T21:40:39.000Z", "max_issues_repo_path": "docs/src/lecture_13/lab/ode-solver.jl", "max_issues_repo_name": "JuliaTeachingCTU/Scientific-Programming-in-Julia", "max_issues_repo_head_hexsha": "7e978fc27ae547fbf95d1367ef1d1d029267e356", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-10-06T09:32:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T15:15:03.000Z", "max_forks_repo_path": "docs/src/lecture_13/lab/ode-solver.jl", "max_forks_repo_name": "JuliaTeachingCTU/Scientific-Programming-in-Julia", "max_forks_repo_head_hexsha": "7e978fc27ae547fbf95d1367ef1d1d029267e356", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-05T16:45:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T18:21:34.000Z", "avg_line_length": 21.4090909091, "max_line_length": 102, "alphanum_fraction": 0.6061571125, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7905833425209946}}
{"text": "\"\"\"\npolyinterp(t,y)\n\nReturn a callable polynomial interpolant through the points in\nvectors `t`,`y`. Uses the barycentric interpolation formula.\n\"\"\"\nfunction polyinterp(t,y)\n    n = length(t)-1\n    C = (t[end]-t[1]) / 4       # scaling factor to ensure stability\n    tc = t/C\n\n    # Adding one node at a time, compute inverses of the weights.\n    omega = ones(n+1)\n    for m = 1:n\n        d = tc[1:m] .- tc[m+1]      # vector of node differences\n        omega[1:m] = omega[1:m].*d  # update previous\n        omega[m+1] = prod( -d )     # compute the new one\n    end\n    w = 1 ./ omega                  # go from inverses to weights\n\n    p = function (x)\n        # Compute interpolant.\n        terms = @. w / (x - t)\n        if any(isinf.(terms))       # divided by zero here\n            # Apply L'Hopital's Rule exactly.\n            idx = findfirst(x.==t)\n            f = y[idx]\n        else\n            f = sum(y.*terms) / sum(terms)\n        end\n    end\n    return p\nend\n\n\"\"\"\ntriginterp(t,y)\n\nReturn trigonometric interpolant for points defined by vectors `t`\nand `y`.\n\"\"\"\nfunction triginterp(t,y)\n    N = length(t)\n\n    function trigcardinal(x)\n        if isodd(N)      # odd\n            tau = sin(N*pi*x/2) / (N*sin(pi*x/2))\n        else             # even\n            tau = sin(N*pi*x/2) / (N*tan(pi*x/2))\n        end\n        if isnan(tau)\n            tau = 1\n        end\n        return tau\n    end\n\n    p = function (x)\n        sum( y[k]*trigcardinal(x-t[k]) for k=1:N )\n    end\n    return p\nend\n\n\"\"\"\nccint(f,n)\n\nPerform Clenshaw-Curtis integration for the function `f` on `n`+1\nnodes in [-1,1]. Return integral and a vector of the nodes used.\nNote: `n` must be even.\n\"\"\"\nfunction ccint(f,n)\n    # Find Chebyshev extreme nodes.\n    theta = [ i*pi/n for i=0:n ]\n    x = -cos.(theta)\n\n    # Compute the C-C weights.\n    c = zeros(n+1)\n    c[[1,n+1]] .= 1/(n^2-1)\n    v = 1 .- 2*sum( cos.(2*k*theta[2:n])/(4*k^2-1) for k=1:n/2-1 )\n    v -= cos.(n*theta[2:n])/(n^2-1)\n    c[2:n] = 2*v/n\n\n    # Evaluate integrand and integral.\n    I = dot(c,f.(x))   # use vector inner product\n    return I,x\nend\n\n\"\"\"\nglint(f,n)\n\nPerform Gauss-Legendre integration for the function `f` on `n` nodes\nin (-1,1). Return integral and a vector of the nodes used.\n\"\"\"\nfunction glint(f,n)\n    # Nodes and weights are found via a tridiagonal eigenvalue problem.\n    beta = @. 0.5/sqrt(1-(2*(1:n-1))^(-2))\n    T = diagm(-1=>beta,1=>beta)\n    lambda,V = eigen(T)\n    p = sortperm(lambda)\n    x = lambda[p]           # nodes\n    c = @. 2*V[1,p]^2       # weights\n\n    # Evaluate the integrand and compute the integral.\n    I = dot(c,f.(x))      # vector inner product\n    return I,x\nend\n\n\"\"\"\nintde(f,h,M)\n\nPerform doubly-exponential integration of function `f` over\n(-Inf,Inf), using discretization size `h` and truncation point `M`.\nReturn integral and a vector of the nodes used.\n\"\"\"\nfunction intde(f,h,M)\n    # Find where to truncate the trapezoid sum.\n    K = ceil( log(4/pi*log(2*M))/h )\n\n    # Integrate by trapezoids in a transformed variable t.\n    t = h*(-K:K)\n    x = @. sinh(pi/2*sinh(t))\n    dxdt = @. pi/2*cosh(t)*cosh(pi/2*sinh(t))\n\n    I = h*dot(f.(x),dxdt)\n    return I,x\nend\n\n\"\"\"\nintsing(f,h,delta)\n\nIntegrate function `f` (possibly singular at 1 and -1) over\n[-1+`delta`,1-`delta`] using discretization size `h`. Return\nintegral and a vector of the nodes used.\n\"\"\"\nfunction intsing(f,h,delta)\n    # Find where to truncate the trapezoid sum.\n    K = ceil(log(-2/pi*log(delta/2))/h)\n\n    # Integrate over a transformed variable.\n    t = h*(-K:K)\n    x = @. tanh(pi/2*sinh(t))\n    dxdt = @. pi/2*cosh(t) / (cosh(pi/2*sinh(t))^2)\n\n    I = h*dot(f.(x),dxdt)\n    return I,x\nend\n", "meta": {"hexsha": "28ece9e155702f1d21a09f2f4e0c64d28d08a366", "size": 3663, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter09.jl", "max_stars_repo_name": "tobydriscoll/fnc", "max_stars_repo_head_hexsha": "dde6097e6a9efff3c8cd7748c96214b4fcec2dc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2020-07-15T15:31:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T14:48:49.000Z", "max_issues_repo_path": "src/chapter09.jl", "max_issues_repo_name": "tobydriscoll/fnc", "max_issues_repo_head_hexsha": "dde6097e6a9efff3c8cd7748c96214b4fcec2dc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-07-20T15:42:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T19:08:43.000Z", "max_forks_repo_path": "src/chapter09.jl", "max_forks_repo_name": "tobydriscoll/fnc", "max_forks_repo_head_hexsha": "dde6097e6a9efff3c8cd7748c96214b4fcec2dc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-07-26T17:42:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T06:10:19.000Z", "avg_line_length": 25.2620689655, "max_line_length": 71, "alphanum_fraction": 0.5672945673, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7905833403876013}}
{"text": "\"\"\"\n**Nadam constructor (Nesterov Adam)**\n\n```julia\n     Nadam(;η::Real=0.001, β₁::Real=0.9, β₂::Real=0.999, ϵ::Real=10e-8)\n```\n\nAlgorithm :\n\n```math\n\\\\begin{align*}\nm_t =& \\\\beta_1 m_{t-1} + (1-\\\\beta_1)g_t\\\\\\\\\nv_t =& \\\\beta_2 v_{t-1} + (1-\\\\beta_2)g_t^2\\\\\\\\\n\\\\hat{m}_t =& \\\\frac{m_t}{1-\\\\beta_1^t}\\\\\\\\\n\\\\hat{v}_t =& \\\\frac{v_t}{1-\\\\beta_2^t}\\\\\\\\\n\\\\Delta x_t =&\\\\frac{\\\\eta}{\\\\sqrt{\\\\hat{v}_t+\\\\epsilon}}(\\\\beta_1\\\\hat{m}_t+\\\\frac{(1-\\\\beta_1)g_t}{1-\\\\beta_1^t})\n\\\\end{align*}\n```\n\n[Algorithm Reference](http://cs229.stanford.edu/proj2015/054_report.pdf) and [other reference](http://www.cs.toronto.edu/~fritz/absps/momentum.pdf)\n\"\"\"\nmutable struct Nadam <: Optimizer\n    opt_type::String\n    t::Int64\n    ϵ::Float64\n    η::Float64\n    β₁::Float64\n    β₂::Float64\n    m_t::AbstractArray\n    v_t::AbstractArray\nend\n\n\"Construct Nadam optimizer\"\nfunction Nadam(;η::Real=0.001, β₁::Real=0.9, β₂::Real=0.999, ϵ::Real=10e-8)\n    @assert η > 0.0 \"η must be greater than 0\"\n    @assert β₁ > 0.0 \"β₁ must be greater than 0\"\n    @assert β₂ > 0.0 \"β₂ must be greater than 0\"\n    @assert ϵ > 0.0 \"ϵ must be greater than 0\"\n\n    Nadam(\"Nadam\", 0, ϵ, η, β₁, β₂, [], [])\nend\n\nparams(opt::Nadam) = \"ϵ=$(opt.ϵ), η=$(opt.η), β₁=$(opt.β₁), β₂=$(opt.β₂)\"\n\nfunction update(opt::Nadam, g_t::AbstractArray{T}) where {T<:Real}\n    # resize biased moment estimates if first iteration\n    if opt.t == 0\n        opt.m_t = zero(g_t)\n        opt.v_t = zero(g_t)\n    end\n\n    # update timestep\n    opt.t += 1\n\n    # update biased first moment estimate\n    opt.m_t = opt.β₁ * opt.m_t + (one(T) - opt.β₁) * g_t\n\n    # update biased second raw moment estimate\n    opt.v_t = opt.β₂ * opt.v_t + (one(T) - opt.β₂) * ((g_t) .^2)\n\n    # compute bias corrected first moment estimate\n    m̂_t = opt.m_t / (one(T) - opt.β₁^opt.t)\n\n    # compute bias corrected second raw moment estimate\n    v̂_t = opt.v_t / (one(T) - opt.β₂^opt.t)\n\n    # apply update\n    ρ = opt.η ./ (sqrt.(v̂_t .+ opt.ϵ))\n    ρ .*= (opt.β₁ * m̂_t + (one(T) - opt.β₁) * g_t / (one(T) - opt.β₁^opt.t))\n\n    return ρ\nend\n", "meta": {"hexsha": "d947f60ac695f7a041b3d171a315b2da52d40743", "size": 2048, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NadamOptimizer.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_stars_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2017-08-20T00:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T03:09:32.000Z", "max_issues_repo_path": "src/NadamOptimizer.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_issues_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-11-19T22:38:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-25T20:33:14.000Z", "max_forks_repo_path": "src/NadamOptimizer.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_forks_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-08-03T16:14:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:48:41.000Z", "avg_line_length": 28.0547945205, "max_line_length": 147, "alphanum_fraction": 0.5893554688, "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748209, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7905626470223851}}
{"text": "\"\"\"\n    Hm... Power method should work well for symmatric tridiagonal matrix that is \n    always changing its size... In fact it does, let's try inverse iterations \n    instead. \n\"\"\"\n\n\n\"\"\"\n    Left and right boundary can actually be infinite. \n    Because of left and right bound, we have to restrict it to type Abstract Floats so that it's \n    comparable, which is going to be used a lot for search the eigen values of the matrix. \n\"\"\"\nfunction InversePowerIterSearch(\n        A::AbstractMatrix{T}, \n        left_bound::T, \n        right_bound::T\n    ) where {T<: AbstractFloat}\n    # Get the mid point. \n    @assert size(A, 1) == size(A, 2) \"It has to be square matrix.\"\n    @assert left_bound != right_bound \"The interval must be non-degenerate.\"\n    if left_bound > right_bound\n        left_bound, right_bound = right_bound, left_bound\n    end\n    if left_bound == -Inf && right_bound == Inf\n        error(\"Left and right bound cannot both be Inf, then it's unbounded. \")\n    end\n    v = randn(T, size(A, 1))    # previous iterations\n    u = similar(v)                 # current iterations\n    Au = similar(v)\n    t = similar(v)              # temp \n    MaxItr = 100\n    while MaxItr > 0\n        # Choose the right point. \n        if left_bound == -Inf || right_bound == Inf\n            θ = left_bound == -Inf ? 2*left_bound : 2*right_bound\n            if θ == -Inf || θ == Inf\n                error(\"Inverse Iteration Igen Search failed, bound limit reached for half opened interval.  \")\n            end\n        else\n            θ = (left_bound + right_bound)/2\n        end\n        println(\"θ: $θ ∈ [$left_bound, $right_bound]\")\n        # Inverse Power iterations.\n        λ = θ\n        while λ == θ || norm(Au - λ*u, 1) > 1e-10\n            println(λ)\n            t .= u\n            u .= (A - λ*I)\\v\n            u ./= norm(u)\n            if norm(u) == NaN\n                u .= v\n                println(\"coverted to $λ\")\n                break\n            else\n                v .= t\n                Au = A*u\n                λ = dot(u, Au)\n            end\n        end\n        # Interval shrink.\n        if λ > left_bound && λ < right_bound\n            \n            return λ, u\n        else\n            if λ <= left_bound\n                left_bound = θ\n                \n            else\n                right_bound = θ\n            end\n        end\n        MaxItr -= 1\n    end\n    if MaxItr == 0\n       error(\"Inverse Power iterations method reached maximal iterations without convergence. \") \n    end\nend\n\n# Basic Tests and shit\nusing LinearAlgebra\nA = Diagonal(sort(randn(10)))\ndisplay(A)\nλ, v = InversePowerIterSearch(A, A[1, 1], A[3, 3])\nprint(\"λ = $λ\")\n# λ, v = InversePowerIterSearch(A, -Inf, A[2, 2])\n# print(\"λ = $λ\")", "meta": {"hexsha": "ca7121b1dee87a2c353d17872218ccc99f3c62a3", "size": 2727, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scratch_papers/scratch_paper2.jl", "max_stars_repo_name": "iluvjava/Subspace_Projection_Method", "max_stars_repo_head_hexsha": "0728d708b18a2f0bca763c1061eb729eb0b79c3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scratch_papers/scratch_paper2.jl", "max_issues_repo_name": "iluvjava/Subspace_Projection_Method", "max_issues_repo_head_hexsha": "0728d708b18a2f0bca763c1061eb729eb0b79c3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scratch_papers/scratch_paper2.jl", "max_forks_repo_name": "iluvjava/Subspace_Projection_Method", "max_forks_repo_head_hexsha": "0728d708b18a2f0bca763c1061eb729eb0b79c3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7093023256, "max_line_length": 110, "alphanum_fraction": 0.5324532453, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8688267643505194, "lm_q1q2_score": 0.790551559915906}}
{"text": "\"\"\"\n    fakedata_gaussian(pts_per_clust::Int = 10, nclust::Int = 2, xmin = 0.0, xmax = nclust * 7.0, nx = round(Int, (xmax - xmin) * 10), σ = 1.0, amin = 1.0, amax = 2.0)\n\nDOCSTRING\n\n# Arguments:\n- `pts_per_clust`: DESCRIPTION\n- `nclust`: DESCRIPTION\n- `xmin`: DESCRIPTION\n- `xmax`: DESCRIPTION\n- `nx`: DESCRIPTION\n- `σ`: DESCRIPTION\n- `amin`: DESCRIPTION\n- `amax`: DESCRIPTION\n\"\"\"\nfunction fakedata_gaussian(\n    pts_per_clust::Int = 10,\n    nclust::Int        = 2,\n    xmin               = 0.0,\n    xmax               = nclust * 7.0,\n    nx                 = round(Int, (xmax - xmin) * 10),\n    σ                  = 1.0,\n    amin               = 1.0,\n    amax               = 2.0,\n)\n    x = LinRange(xmin, xmax, nx)\n    μ = LinRange(xmin, xmax, nclust + 2)[2:end-1]\n    a = LinRange(xmin, xmax, pts_per_clust + 2)[2:end-1]\n\n    npts = pts_per_clust * nclust\n    data = zeros(nx, npts)\n    labels = zeros(Int, npts)\n\n    i = 1\n    for c = 1:nclust\n        for n = 1:pts_per_clust\n            data[:, i] = gauss_func.(a[n], μ[c], σ, x)\n            labels[i] = c\n            i += 1\n        end\n    end\n\n    return data, labels\nend\n\ngauss_func(a, μ, σ, x) = a * exp((-(x - μ) .^ 2) / (2 * σ^2))\n", "meta": {"hexsha": "213c53dca9b6780e7082cea6601e1e4bb11c853b", "size": 1193, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/datasets/fake_datasets.jl", "max_stars_repo_name": "paciops/DynamicAxisWarping.jl", "max_stars_repo_head_hexsha": "1c7dc135fd2964868fe148049a888538c3f3c21a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2020-04-24T13:09:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T23:34:19.000Z", "max_issues_repo_path": "src/datasets/fake_datasets.jl", "max_issues_repo_name": "paciops/DynamicAxisWarping.jl", "max_issues_repo_head_hexsha": "1c7dc135fd2964868fe148049a888538c3f3c21a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2020-04-25T08:24:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T06:46:00.000Z", "max_forks_repo_path": "src/datasets/fake_datasets.jl", "max_forks_repo_name": "paciops/DynamicAxisWarping.jl", "max_forks_repo_head_hexsha": "1c7dc135fd2964868fe148049a888538c3f3c21a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-05-14T10:47:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T13:14:10.000Z", "avg_line_length": 25.3829787234, "max_line_length": 166, "alphanum_fraction": 0.5020955574, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939024820841433, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7904951813164923}}
{"text": "# A version of the conjugate gradient method for linesearch.\n\n\"\"\"A version of the conjugate gradient method for linesearch.\nCG(A, b, ϵa, ϵr, itmax; quad) solves the symmetric linear system 'A * x = b'\nIf quad = true, the values of the quadratic model are computed\nA can be positive definite or not.\n\"\"\"\nfunction CGlin(A, b, ϵa::Float64=1e-8, ϵr::Float64=1e-6, itmax::Int=0, ε::Float64=1e-6; quad::Bool=false)\n    n = size(b, 1) # size of the problem\n    (size(A, 1) == n & size(A, 2) == n) || error(\"Inconsistent problem size\")\n    @info(loggerCGlin, @sprintf(\"CGlin: system of %d equations in %d variables\", n, n))\n\n    x = zeros(n) # initial estimation x = 0\n    xNorm = 0.0\n    xNorms = [xNorm] # Values of ‖x‖\n    r = -b # initial residual r = Ax-b = -b\n    d = b # first descent direction\n    rNorm = norm(r, 2)\n    ϵ = ϵa + ϵr * rNorm\n\n    iter = 0\n    itmax == 0 && (itmax = 2 * n)\n\n    if quad\n        q = 0.0\n        qvalues = [q] # values of the quadratic model\n        @info(loggerCGlin, @sprintf(\"%5s %10s %10s\\n\", \"Iter\", \"‖r‖\", \"q\"))\n        @info(loggerCGlin, @sprintf(\"    %d    %8.1e    %8.1e\", iter, rNorm, q))\n    end\n\n    solved = rNorm ≤ ϵ\n    tired = iter ≥ itmax\n\n    while ! (solved || tired)\n        iter += 1\n        Ad = A * d\n        dAd = dot(d, Ad)\n\n        # if the model is not convexe, the algorithm stops\n        if dAd ≤ ε * dot(d, d)\n            @debug(loggerCGlin, @sprintf(\"non positive curvature dAd = %8.1e\", dAd))\n            iter == 1 && return b\n            return x\n        end\n\n        α = rNorm^2 / dAd # step for x estimation\n        x = x + α * d # new estimation\n        xNorm = norm(x, 2)\n        push!(xNorms, xNorm)\n        roldNorm = rNorm\n        r = r + α * Ad # new residual\n        rNorm = norm(r, 2)\n\n        if quad\n            q = -dot(b, x) + 0.5 * dot(x, A * x)\n            push!(qvalues, q)\n            @info(loggerCGlin, @sprintf(\"    %d    %8.1e    %8.1e\", iter, rNorm, q))\n        end\n\n        solved = rNorm ≤ ϵ\n        tired = iter ≥ itmax\n\n        (solved || tired) && continue\n        β = rNorm^2 / roldNorm^2 # step for the next descent direction\n        d = -r + β * d # new descent direction\n\n        end\n        return x\n    end\n", "meta": {"hexsha": "6075055890770b2ecfd7da831c0a6416f9dc02fe", "size": 2203, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CGlin.jl", "max_stars_repo_name": "DahitoMA/Linesearch.jl", "max_stars_repo_head_hexsha": "b27f91be32716e25ce24805b372dde7cfbcc8246", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CGlin.jl", "max_issues_repo_name": "DahitoMA/Linesearch.jl", "max_issues_repo_head_hexsha": "b27f91be32716e25ce24805b372dde7cfbcc8246", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CGlin.jl", "max_forks_repo_name": "DahitoMA/Linesearch.jl", "max_forks_repo_head_hexsha": "b27f91be32716e25ce24805b372dde7cfbcc8246", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4714285714, "max_line_length": 105, "alphanum_fraction": 0.5329096686, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7904951699809869}}
{"text": "@doc doc\"\"\"\nApproximation de la solution du sous-problème ``q_k(s) = s^{t}g + (1/2)s^{t}Hs`` \n        avec ``s=-t g_k,t > 0,||s||< \\delta_k ``\n\n\n# Syntaxe\n```julia\ns1, e1 = Pas_De_Cauchy(gradient,Hessienne,delta)\n```\n\n# Entrées\n * **gradfk** : (Array{Float,1}) le gradient de la fonction f appliqué au point ``x_k``\n * **hessfk** : (Array{Float,2}) la Hessienne de la fonction f appliqué au point ``x_k``\n * **delta**  : (Float) le rayon de la région de confiance\n\n# Sorties\n * **s** : (Array{Float,1}) une approximation de la  solution du sous-problème\n * **e** : (Integer) indice indiquant l'état de sortie:\n        si g != 0\n            si on ne sature pas la boule\n              e <- 1\n            sinon\n              e <- -1\n        sinon\n            e <- 0\n\n# Exemple d'appel\n```julia\ng1 = [0; 0]\nH1 = [7 0 ; 0 2]\ndelta1 = 1\ns1, e1 = Pas_De_Cauchy(g1,H1,delta1)\n```\n\"\"\"\nfunction Pas_De_Cauchy(g,H,delta)\n\n  a = (1/2)*g'*H*g\n  b = norm(g)\n\n  if (b > 0)\n    t = (b^2)/(2*a)\n    s = -t*g\n    e = 1\n    if norm(s)>delta\n        t = delta/b\n        s = -t*g\n        e = -1\n    end\n  else\n    t = 0\n    s = -t*g\n    e = 0\n  end\n    \n  return s, e\nend\n", "meta": {"hexsha": "bf359a0a030002238202e0255a1836265abcfc06", "size": 1151, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2A/S7/UE Optimisation et RO/Optimisation/Optinum/src/Pas_De_Cauchy.jl", "max_stars_repo_name": "badrs26/ENSEEIHT", "max_stars_repo_head_hexsha": "7d04264c1be2c3993bfbcd8f7cdd64b4fb780b8f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-02T15:42:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T20:31:09.000Z", "max_issues_repo_path": "2A/S7/UE Optimisation et RO/Optimisation/Optinum/src/Pas_De_Cauchy.jl", "max_issues_repo_name": "Sajid-Badr/ENSEEIHT", "max_issues_repo_head_hexsha": "7d04264c1be2c3993bfbcd8f7cdd64b4fb780b8f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2A/S7/UE Optimisation et RO/Optimisation/Optinum/src/Pas_De_Cauchy.jl", "max_forks_repo_name": "Sajid-Badr/ENSEEIHT", "max_forks_repo_head_hexsha": "7d04264c1be2c3993bfbcd8f7cdd64b4fb780b8f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-12-07T22:15:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T21:49:50.000Z", "avg_line_length": 20.1929824561, "max_line_length": 88, "alphanum_fraction": 0.5186794092, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8791467738423874, "lm_q1q2_score": 0.7904596628724978}}
{"text": "@doc raw\"\"\"\n    rigid_body_velocity(vel_P, ω, r_PQ)\n\nCalculate rigid solid velocity field.\n\nReturn velocity of a point Q of a rigid solid given the velocity of a point P (vel_P), the\nrotational velocity of the solid (ω) and the relative position of Q with respect to P.\n\nIf the reference frame 1 is attached to the solid and the velocity is calculated with\nrespect to reference frame 0:\n\n``v_{10}^{Q} = v_{10}^{P} + \\omega_{10} \\times r^{PQ}``\n\nbeing:\n- ``v_{10}^{Q}`` the velocity of point Q, fixed to 1, wrt 0\n- ``\\omega_{10}`` the angular velocity of the solid 1 wrt 0\n- ``r^{PQ}`` the position of Q wrt P (``r^{Q}-r^{P}``)\n\nEvery vector needs to be expressed in the same coordinate system.\n\n# References\n\n1. Stevens, B. L., Lewis, F. L., (1992). Aircraft control and simulation: dynamics, controls\n   design, and autonomous systems. John Wiley & Sons. (Section 1.3, page 26)\n\"\"\"\nfunction rigid_body_velocity(vel_P, ω, r_PQ)\n    vel_Q = vel_P + ω × r_PQ\n    return vel_Q\nend\n\n\n@doc raw\"\"\"\n    rigid_body_acceleration(acc_P, ω, ω_dot, r_PQ)\n\nCalcualte rigid body acceleration field.\n\nReturn the acceleration of a point Q of a rigid solid given the acceleration of a point P\n(acc_P), the rotational velocity of the solid (ω), the rotational acceleration of the solid\n(ω_dot) and the relative position of Q with respect to P.\n\n``a_{10}^{Q} = a_{10}^{P} + \\omega_{10} \\times (\\omega_{10} \\times r^{PQ}) + \\dot{\\omega}_{10} \\times r^{PQ}``\n\nbeing:\n- ``a_{10}^{Q}`` the acceleration of point Q, fixed to 1, wrt 0\n- ``\\omega_{10}`` the angular velocity of the solid 1 wrt 0\n- ``\\dot{\\omega}_{10}`` the angular acceleration of the solid 1 wrt 0\n- ``r^{PQ}`` the position of Q wrt P (``r^{Q}-r^{P}``)\n\n# References\n\n1. Stevens, B. L., Lewis, F. L., (1992). Aircraft control and simulation: dynamics, controls\n   design, and autonomous systems. John Wiley & Sons. (Section 1.3, Formaula 1.3-14c, page 26)\n\"\"\"\nfunction rigid_body_acceleration(acc_P, ω, ω_dot, r_PQ)\n    acc_Q = acc_P + ω × (ω × r_PQ) + ω_dot × r_PQ\n    return acc_Q\nend\n\n\n\"\"\"\n    pqr_2_ψθϕ_dot(p, q, r, ψ, θ, ϕ)\n\nTransform body angular velocity (p, q, r) [rad/s] to Euler angles rates (ψ_dot, θ_dot,\nϕ_dot) [rad/s] given the euler angles (θ, ϕ) [rad] using kinematic angular equations.\n\n# See also\n\n[`ψθϕ_dot_2_pqr`](@ref), [`pqr_2_quat_dot`](@ref)\n\n# References\n\n1. Stevens, B. L., Lewis, F. L., & Johnson, E. N. (2015). Aircraft control and simulation:\n   dynamics, controls design, and autonomous systems. John Wiley & Sons. Equation (1.4-4) (page 20)\n\"\"\"\nfunction pqr_2_ψθϕ_dot(p, q, r, θ, ϕ)\n\n    sθ, cθ = sin(θ), cos(θ)\n    sϕ, cϕ = sin(ϕ), cos(ϕ)\n\n    ψ_dot = (q * sϕ + r * cϕ) / cθ\n    θ_dot = q * cϕ - r * sϕ\n    # ϕ_dot = p + (q * sϕ + r * cϕ) * tan(θ)\n    ϕ_dot = p + ψ_dot * sθ\n\n    return [ψ_dot, θ_dot, ϕ_dot]\nend\n\n\n\"\"\"\n    ψθϕ_dot_2_pqr(ψ_dot, θ_dot, ϕ_dot, ψ, θ, ϕ)\n\nTransform Euler angles rates (ψ_dot, θ_dot, ϕ_dot) [rad/s] to body angular velocity (p, q,\nr) [rad/s] given the euler angles (θ, ϕ) [rad] using kinematic angular equations.\n\n# See also\n\n[`pqr_2_ψθϕ_dot`](@ref)\n\n# References\n\n1. Stevens, B. L., Lewis, F. L., & Johnson, E. N. (2015). Aircraft control and simulation:\n   dynamics, controls design, and autonomous systems. John Wiley & Sons. Equation (1.4-3) (page 20)\n\"\"\"\nfunction ψθϕ_dot_2_pqr(ψ_dot, θ_dot, ϕ_dot, θ, ϕ)\n\n    sθ, cθ = sin(θ), cos(θ)\n    sϕ, cϕ = sin(ϕ), cos(ϕ)\n\n    p = ϕ_dot - sθ * ψ_dot\n    q = cϕ * θ_dot + sϕ*cθ * ψ_dot\n    r = -sϕ * θ_dot + cϕ*cθ * ψ_dot\n\n    return [p, q, r]\nend\n\n\n\"\"\"\n    pqr_2_quat_dot(p, q, r, q0, q1, q2, q3)\n\nTransform body angular velocity (p, q, r) [rad/s] to quaternion rates [1/s].\n\n# See also\n\n[`pqr_2_ψθϕ_dot`](@ref)\n\n# References\n\n1. Stevens, B. L., Lewis, F. L., & Johnson, E. N. (2015). Aircraft control and simulation:\n   dynamics, controls design, and autonomous systems. John Wiley & Sons. Equation (1.8-15)\n   (page 51).\n\"\"\"\nfunction pqr_2_quat_dot(p, q, r, q0, q1, q2, q3)\n\n    Ω = [\n        0 -p -q -r;\n        p  0  r -q;\n        q -r  0  p;\n        r  q -p  0;\n    ]\n    q = [q0; q1; q2; q3]\n    q_dot = 0.5 * Ω * q\n\n    return q_dot\nend\n\n\n\"\"\"\n    uvw_to_tasαβ(u, v, w)\n\nCalculate true air speed (TAS), angle of attack (α) and angle of side slip (β) from velocity\nexpressed in body axis.\n\n# Notes\n\nThis function assumes that u, v, w are the body components of the aerodynamic speed. This is\nnot true in genreal (wind speed different from zero), as u, v, w represent velocity with\nrespect to an inertial reference frame.\n\n# References\n\n1. Stevens, B. L., Lewis, F. L., & Johnson, E. N. (2015). Aircraft control and simulation:\n   dynamics, controls design, and autonomous systems. John Wiley & Sons. Equation (2.3-6b)\n   (page 78).\n\"\"\"\nfunction uvw_to_tasαβ(u, v, w)\n\n    tas = sqrt(u*u + v*v + w*w)\n    α = atan(w, u)\n    β = asin(v / tas)\n    return [tas, α, β]\nend\n\n\n\"\"\"\n    uvw_dot_to_tasαβ_dot(u, v, w, u_dot, v_dot, w_dot)\n\nCalculate time derivatives of velocity expressed as TAS, AOA, AOS.\n\n# Notes\nNote that tas here is not necessarily true air speed. Could also be inertial speed in the\ndirection of airspeed. It will concide whith TAS for no wind.\n\n# See also\n\n[`tasαβ_dot_to_uvw_dot`](@ref)\n\n# References\n1. Morelli, Eugene A., and Vladislav Klein. Aircraft system identification: Theory and\n   practice. Williamsburg, VA: Sunflyte Enterprises, 2016. Equation 3.33 (page 44).\n2. Stevens, B. L., Lewis, F. L., & Johnson, E. N. (2015). Aircraft control and simulation:\n   dynamics, controls design, and autonomous systems. John Wiley & Sons. Equation (2.3-10)\n   (page 81).\n\"\"\"\nfunction uvw_dot_to_tasαβ_dot(u, v, w, u_dot, v_dot, w_dot)\n\n    # [1] 3.31\n    tas = sqrt(u*u + v*v + w*w)\n    # [1] 3.33a\n    tas_dot = (u * u_dot + v * v_dot + w * w_dot) / tas\n    # [1] 3.33b\n    β_dot = ((u*u + w*w) * v_dot - v * (u * u_dot + w * w_dot)) / (tas^2 * sqrt(u*u + w*w))\n    # [2] 2.3.10b\n    # β_dot = (v_dot * tas - v * tas_dot) / (tas * sqrt(u*u + w*w))\n    # [1] 3.33c\n    α_dot = (w_dot * u - w * u_dot) / (u*u + w*w)\n\n    return [tas_dot, α_dot, β_dot]\nend\n\n\n\"\"\"\n    tasαβ_dot_to_uvw_dot(tas, α, β, tas_dot, α_dot, β_dot)\n\nObatain body velocity derivatives given velocity in wind axis and its derivatives.\n\n# See also\n\n[`uvw_dot_to_tasαβ_dot`](@ref)\n\n# References\n\n1. Morelli, Eugene A., and Vladislav Klein. Aircraft system identification: Theory and\n   practice. Williamsburg, VA: Sunflyte Enterprises, 2016. Derived from equation 3.32\n   (page 44).\n\"\"\"\nfunction tasαβ_dot_to_uvw_dot(tas, α, β, tas_dot, α_dot, β_dot)\n    u_dot = tas_dot * cos(α) * cos(β) - tas * (α_dot * sin(α) * cos(β) + β_dot * cos(α) * sin(β))\n    v_dot = tas_dot * sin(β) + tas * β_dot * cos(β)\n    w_dot = tas_dot * sin(α) * cos(β) + tas * (α_dot * cos(α) * cos(β) - β_dot * sin(α) * sin(β))\n    return [u_dot, v_dot, w_dot]\nend\n\n\n@doc raw\"\"\"\n    rate_of_climb_constrain_no_wind(γ, α, β, ϕ)\n\nCalculate pitch angle (θ rad) to obtain a flight path angle (γ rad) at certain angle of\nattack (α rad), angle of sideslip (β rad) and roll (ϕ rad).\n\nInertial velocity and aerodynamic velocity are equivalent in the absence of wind:\n\n`` v_{cg-e}^e = R_{eb} R_{bw} v_{cg-air}^w ``\n\n# References\n\n1. Stevens, B. L., Lewis, F. L., (1992). Aircraft control and simulation: dynamics, controls\n   design, and autonomous systems. John Wiley & Sons. (Section 3.6, equation 3.6-3,\n   page 187)\n\"\"\"\nfunction rate_of_climb_constrain_no_wind(γ, α, β, ϕ)\n    a = cos(α) * cos(β)\n    b = sin(ϕ) * sin(β) + cos(ϕ) * sin(α) * cos(β)\n    sq = sqrt(a^2 - sin(γ)^2 + b^2)\n    θ = (a * b + sin(γ) * sq) / (a^2 - sin(γ)^2)\n    θ = atan(θ)\n    return θ\nend\n", "meta": {"hexsha": "fcd1c9f806887dd5b282fe672177d266ccb571e3", "size": 7563, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kinematics.jl", "max_stars_repo_name": "AlexS12/FlightMechanicsUtils.jl", "max_stars_repo_head_hexsha": "862f3cdac936c65881bc2aa8f1168ead8d5284d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-06-24T17:05:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T16:56:11.000Z", "max_issues_repo_path": "src/kinematics.jl", "max_issues_repo_name": "AlexS12/FlightMechanicsUtils.jl", "max_issues_repo_head_hexsha": "862f3cdac936c65881bc2aa8f1168ead8d5284d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-03-13T19:26:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-06T11:41:07.000Z", "max_forks_repo_path": "src/kinematics.jl", "max_forks_repo_name": "AlexS12/FlightMechanicsUtils.jl", "max_forks_repo_head_hexsha": "862f3cdac936c65881bc2aa8f1168ead8d5284d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3139534884, "max_line_length": 110, "alphanum_fraction": 0.6402221341, "num_tokens": 2733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7904445206709307}}
{"text": "#=\n  From https://math.stackexchange.com/questions/3633307/bayes-rule-broken\n  \"\"\"\n  Bayes' Rule broken?!?!\n\n  This question has been driving me CRAZY for 4 days now. The question comes from \n  the textbook 'One Thousand Exercises in Probability', specifically Exercise 3 in \n  section 1.4. The solution does not make sense! The question goes as follows:\n\n     'A man possesses five coins, two double-headed, two normal and one double-tailed. \n     The man shuts his eyes, picks a coin at random, and tosses the coin. He opens \n     his eyes, sees a head: what is the probability the lower face is also a head?.\n\n  The book gives an answer that is 2/3\n  ....\n  \"\"\"\n\n  Distributions of variable coin (num:0)\n  1.00000 =>    6585  (0.658500)\n  2.00000 =>    3415  (0.341500)\n\n  Distributions of variable flip_is_head (num:0)\n  1.00000 =>    6585  (0.658500)\n  0.00000 =>    3415  (0.341500)\n\n   Cf ~/blog/five_coins.blog\n      ~/webppl/family_out_problem.wppl\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n@model function five_coins()\n    doubleHead = 1\n    normalCoin = 2\n    doubleTail = 3\n\n    head = 1\n    tail = 2\n    \n    coin ~ Categorical([2/5,2/5,1/5]) # [doubleHead,normalCoin,doubleTail]\n    \n    #  Toss the coin\n    toss ~ \n        (coin == doubleHead) ? Dirac(head) :\n        (coin == doubleTail) ? Dirac(tail) : \n        Categorical([1/2,1/2]) # [head,tail]\n\n    #  Flip the coin (i.e. turn it around)\n    flip ~ Dirac((coin == doubleHead) ? head :\n                 (coin == doubleTail) ? tail : \n                 (toss == head) ? tail : head\n                 )\n\n    #  We observe that the toss give a head.\n    true ~ Dirac(toss == head);\n\n    #  What is the probability that the other side (flip side)\n    #  is head?\n    flip_is_head ~ Dirac(flip == head)\nend\n\nmodel = five_coins()\n\nnum_chains = 4\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(5), 10_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 10_000)\n\ndisplay(chns)\n# display(plot(chns))\n\nshow_var_dist_pct(chns,:coin)\nshow_var_dist_pct(chns,:flip_is_head)\n\n", "meta": {"hexsha": "1205ce20a2f434fc90d8207d9910e730e778528a", "size": 2129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/five_coins.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/five_coins.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/five_coins.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 26.9493670886, "max_line_length": 87, "alphanum_fraction": 0.6345702208, "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.8723473663814338, "lm_q1q2_score": 0.7903378359941781}}
{"text": "\"\"\"\n    fixedStateCV(\n        states :: Vector{<:AbstractMatrix},\n        kraus_ops :: Vector{<:AbstractMatrix}\n    ) :: Tuple{Float64, Vector{Matrix{ComplexF64}}}\n\nFor a fixed ensemble of `states` and quantum channel described by `kraus_ops`,\nthe communication value (CV) is evaluated by maximizing over all POVM measurements.\nThis optimization is expressed in primal form as the semidefinite program:\n\n```math\n\\\\begin{matrix}\n    \\\\text{fixedStateCV}(\\\\mathcal{N})&= \\\\max_{\\\\{\\\\Pi_x\\\\}_{x}} \\\\sum_x \\\\text{Tr}\\\\left[\\\\Pi_x\\\\mathcal{N}(\\\\rho_x)\\\\right] \\\\\\\\\n    & \\\\\\\\\n    & \\\\text{s.t.} \\\\quad \\\\sum_x\\\\Pi_x = \\\\mathbb{I} \\\\;\\\\; \\\\text{and} \\\\;\\\\; \\\\Pi_x \\\\geq 0\n\\\\end{matrix}\n```\n\nwhere each state ``\\\\rho_x`` satisfies ``\\\\text{Tr}[\\\\rho_x] = 1`` and ``\\\\rho_x \\\\geq 0``.\nThe channel ``\\\\mathcal{N}`` is applied to each state as\n``\\\\mathcal{N}(\\\\rho_x) = \\\\sum_j k \\\\rho_x k^\\\\dagger``.\n\n# Returns\n\nA `Tuple`, `(cv, opt_povm)` where `cv` is the evaluated communication value and\n`opt_povm` is the optimal POVM measurement.\n\"\"\"\nfunction fixedStateCV(\n    states :: Vector{<:AbstractMatrix},\n    kraus_ops :: Vector{<:AbstractMatrix}\n) :: Tuple{Float64, Vector{Matrix{ComplexF64}}}\n    d = size(kraus_ops[1],1)\n    n = length(states)\n\n    # add povm variables and constraints\n    povm_vars = map(i -> HermitianSemidefinite(d), 1:n)\n    constraints = sum(map(Πy -> real(Πy), povm_vars)) == Matrix{Float64}(I, d, d)\n    constraints += sum(map(Πy -> imag(Πy), povm_vars)) == zeros(Float64, d, d)\n\n    # apply channel to states\n    evolved_states = map(ρ ->  sum(k -> k * ρ * k' , kraus_ops), states)\n\n    # maximize CV over POVM measurements\n    objective = maximize(real(sum(tr.(povm_vars .* evolved_states))), constraints)\n    qsolve!(objective)\n\n    cv = objective.optval\n    opt_povm = map(Πy -> Πy.value, povm_vars)\n\n    return cv, opt_povm\nend\n\n\"\"\"\n    fixedMeasurementCV(\n        povm :: Vector{<:AbstractMatrix},\n        kraus_ops :: Vector{<:AbstractMatrix}\n    ) :: Tuple{Float64, Vector{Matrix{ComplexF64}}}\n\nFor a fixed `povm` measurement and quantum channel described by `kraus_ops`, the\ncommunication value (CV) and optimal state encodings are computed.\nThe fixed measurement CV is evaluated as\n\n```math\n\\\\text{fixedMeasurementCV}(\\\\mathcal{N}) = \\\\sum_y ||\\\\mathcal{N}^{\\\\dagger}(\\\\Pi_y)||_{\\\\infty}\n```\n\nwhere ``||\\\\mathcal{N}^{\\\\dagger}(\\\\Pi_y)||_{\\\\infty}`` is the largest eigenvalue\nof the POVM element ``\\\\Pi_y`` evolved by the adjoint channel,\n``\\\\mathcal{N}^{\\\\dagger}(\\\\Pi_y) = \\\\sum_j k^{\\\\dagger}_j \\\\Pi_y k_j``.\nThe states which maximize the CV are simply the eigenvectors corresponding to the\nlargest eigenvalue of each respective POVM element.\n\n# Returns\n\nA `Tuple`, `(cv, opt_states)` where `cv` is the communication value and\n`opt_states` is the set of optimal states.\n\"\"\"\nfunction fixedMeasurementCV(\n    povm :: Vector{<:AbstractMatrix},\n    kraus_ops :: Vector{<:AbstractMatrix}\n) :: Tuple{Float64, Vector{Matrix{ComplexF64}}}\n    d = size(kraus_ops[1],2)\n    n = length(povm)\n\n    # apply adjoint channel to POVM\n    evolved_povm = map(Π ->  sum(k -> k' * Π * k , kraus_ops), povm)\n\n\n    opt_states = Vector{Matrix{ComplexF64}}(undef, n)\n    cv = 0\n    for i in 1:n\n        povm_el = evolved_povm[i]\n        vals, vecs = eigen(povm_el)\n\n        opt_states[i] = vecs[:,end] * vecs[:,end]'\n        cv += real(vals[end])\n    end\n\n    return cv, opt_states\nend\n\n\"\"\"\n    seesawCV(\n        init_states :: Vector{<:AbstractMatrix},\n        kraus_ops :: Vector{<:AbstractMatrix},\n        num_steps :: Int64;\n        verbose :: Bool = false\n    )\n\nPerforms the see-saw optimization technique to maximize the communication\nvalue (CV) of the channel described by `kraus_ops` over all states and measurements.\nThis iterative and biconvex optimization technique combines coordinate ascent\nmaximization with semidefinite programming.\nThe number of iterations is determined by `num_steps` where each iteration\nconsists of a two-step procedure:\n\n1. The POVM measurement is optimized with respect to a fixed state ensemble\n   using the [`fixedStateCV`](@ref) function.\n2. The state ensemble is optimized with respect to a fixed povm state using\n   the [`fixedMeasurementCV`](@ref) function.\n\nThis procedure is initialized with `init_states` and after many iterations, a\nlocal maximum of the CV is found.\nThe `verbose` keyword argument can be used to print out the CV evaluated in each\nstep.\n\nThe see-saw method has shown success in similar encoding/decoding\noptimization problems in quantum information, *e.g.*,\n[https://arxiv.org/abs/quant-ph/0307138v2](https://arxiv.org/abs/quant-ph/0307138v2)\nand [https://arxiv.org/abs/quant-ph/0606078v1](https://arxiv.org/abs/quant-ph/0606078v1).\nWe note that our implementation is quite distinct from previous works, however,\nthe core iterative approach remains the same.\n\n# Returns\n\nA `Tuple` containing the following data in order:\n\n1. `max_cv_tuple :: Tuple`, `(max_cv, opt_states, opt_povm)` A 3-tuple containing the maximal\n   communication value and the optimal states/POVM that achieve this value.\n2. `cvs :: Vector{Float64}`, A list of each evaluated CV. Since states and measurements\n   are optimized in each iteration, we have `length(cvs) == 2 * num_steps`.\n3. `opt_ensembles :: Vector{Vector{Matrix{ComplexF64}}}`, A list of state ensembles\n   optimized in each step, where `length(opt_ensembles) == num_steps`.\n4. `opt_povms :: Vector{Vector{Matrix{ComplexF64}}}`, A list of POVM measurements\n   optimized in each step, where `length(opt_povms) == num_steps`.\n\n!!! warning \"Optimum Not Guaranteed\"\n    This function is not guaranteed to find a global or local optima. However,\n    `seesawCV` will always provide a lower bound on the communication value.\n\"\"\"\nfunction seesawCV(\n    init_states :: Vector{<:AbstractMatrix},\n    kraus_ops :: Vector{<:AbstractMatrix},\n    num_steps :: Int64;\n    verbose :: Bool = false\n) :: Tuple\n    opt_ensembles = Vector{Vector{Matrix{ComplexF64}}}(undef, num_steps)\n    opt_povms = Vector{Vector{Matrix{ComplexF64}}}(undef, num_steps)\n    cvs = zeros(Float64, 2*num_steps)\n    cv_id = 1\n\n    max_cv_tuple = (1, [], [])\n\n    for i in 1:num_steps\n        # maximizing CV over POVMs\n        opt_states = (i == 1) ? init_states : opt_ensembles[i-1]\n\n        fixed_state_cv, opt_povm = fixedStateCV(opt_states, kraus_ops)\n\n        cvs[cv_id] = fixed_state_cv\n        cv_id += 1\n        opt_povms[i] = opt_povm\n\n        if fixed_state_cv > max_cv_tuple[1]\n            max_cv_tuple = (fixed_state_cv, opt_states, opt_povm)\n        end\n\n        # maximizing CV over states\n        fixed_povm_cv, opt_states = fixedMeasurementCV(opt_povm, kraus_ops)\n\n        cvs[cv_id] = fixed_povm_cv\n        cv_id += 1\n        opt_ensembles[i] = opt_states\n\n        if fixed_povm_cv > max_cv_tuple[1]\n            max_cv_tuple = (fixed_povm_cv, opt_states, opt_povm)\n        end\n\n        if verbose\n            println(\"i = \", i)\n            println(\"fixed_state_cv = \", fixed_state_cv)\n            println(\"fixed_povm_cv = \", fixed_povm_cv)\n            println(\"max_cv = \", max_cv_tuple[1])\n        end\n    end\n\n    return max_cv_tuple, cvs, opt_ensembles, opt_povms\nend\n", "meta": {"hexsha": "135a43a86a559eaef68cd939a637a461d40e051d", "size": 7154, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/see-saw_optimization.jl", "max_stars_repo_name": "ChitambarLab/CVChannel.jl", "max_stars_repo_head_hexsha": "479fa1e70d19b5434137f9017d99830796802d87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/see-saw_optimization.jl", "max_issues_repo_name": "ChitambarLab/CVChannel.jl", "max_issues_repo_head_hexsha": "479fa1e70d19b5434137f9017d99830796802d87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-09-21T00:29:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-15T00:35:15.000Z", "max_forks_repo_path": "src/see-saw_optimization.jl", "max_forks_repo_name": "ChitambarLab/cv-channel", "max_forks_repo_head_hexsha": "479fa1e70d19b5434137f9017d99830796802d87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9497487437, "max_line_length": 131, "alphanum_fraction": 0.6772435001, "num_tokens": 2066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7903210549963302}}
{"text": "#=\nSection Allocation\n\n   Suppose you have $n$ students in a class who need to be assigned to\n      $m$ discussion sections. Each student needs to be assigned to exactly\n      one section. Each discussion section should have between 6 and 10\n      students. Suppose an $n \\times m$ preference matrix $P$ is given,\n      where $P_{ij}$ gives student $i$'s ranking for section $j$\n      (1 would mean it is the student's top choice, 10,000 or a large number\n      would mean the student can not attend that section).\n\n   The goal will be to get an allocation matrix $X$, where $X_{ij} = 1$\n      if student $i$ is assigned to section $j$ and $0$ otherwise.\n\n\n  source: https://github.com/JuliaOpt/Convex.jl/blob/master/examples/\n                             section_allocation/section_allocation.ipynb                      \n=#\n\n\nusing Convex, GLPKMathProgInterface\n\ninclude(\"data.jl\"); # data.jl has our preference matrix, P\n\nX = Variable(size(P), :Bin)\n\n#=\n   We want every student to be assigned to exactly one section.\n   So, every row must have exactly one non-zero entry.\n   In other words, the sum of all the columns for every row is 1.\n   We also want each section to have between 6 and 10 students,\n       so the sum of all the rows for every column should be between\n       these constraints = [sum(X, 2) == 1, sum(X, 1) <= 10, sum(X, 1) >= 6]\n\n   Our objective is simple sum(X .* P), which can be more efficiently\n       represented as vec(X)' * vec(P).\n   Since each entry of X is either 0 or 1, this is basically summing up\n       the rankings of students that were assigned to them.\n   If all students got their first choice, this value will be the number\n       of students since the ranking of the first choice is 1.\n=#\n\np = minimize(vec(X)' * vec(P), constraints)\n\nsolve!(p, GLPKSolverMIP())\n", "meta": {"hexsha": "3b49af176c3539eeac5137c088ac3db448bd7de1", "size": 1806, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "refs/MILP/examples/SectionAllocation.jl", "max_stars_repo_name": "JuliaTagBot/GUI.jl", "max_stars_repo_head_hexsha": "b2ab393c6286ede8d0b7d00929098f99699de226", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-09-20T20:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T21:00:59.000Z", "max_issues_repo_path": "refs/MILP/examples/SectionAllocation.jl", "max_issues_repo_name": "JuliaTagBot/GUI.jl", "max_issues_repo_head_hexsha": "b2ab393c6286ede8d0b7d00929098f99699de226", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "refs/MILP/examples/SectionAllocation.jl", "max_forks_repo_name": "JuliaTagBot/GUI.jl", "max_forks_repo_head_hexsha": "b2ab393c6286ede8d0b7d00929098f99699de226", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:26:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:26:06.000Z", "avg_line_length": 39.2608695652, "max_line_length": 94, "alphanum_fraction": 0.6760797342, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370535, "lm_q2_score": 0.826711787666479, "lm_q1q2_score": 0.7903210509476177}}
{"text": "####\n#### Parametric gates\n####\n\n\"\"\"\n    Rphi(ϕ)\n\nThe phase shift gate ``R_ϕ``.\nThis is equivalent to qiskit's `u1` gate.\n\"\"\"\nfunction Rphi(ϕ)\n    return [1 0; 0 cis(ϕ)]\nend\n\n# Could use complex(reverse(sincospi(z))...)\n\"\"\"\n    _exp_ipi(z)\n\nReturn `exp(im * pi * z)`. This uses the accurate `cospi` and `sinpi` functions.\n\"\"\"\n_exp_ipi(z) = cispi(z)\n\n\"\"\"\n    Rphipi(z)\n\nReturn the ``R_ϕ`` gate for ``ϕ = zπ``. This is more accurate\nthan `Rphi(pi * z)`.\n\"\"\"\nfunction Rphipi(z)\n    return [1 0; 0 _exp_ipi(z)]\nend\n\n\"\"\"\n    U2(ϕ, λ)\n\nu2 gate. Need to put math definitions in here.\n\"\"\"\nfunction U2(ϕ, λ)\n    return [1 -cis(λ); cis(ϕ) cis(ϕ + λ)] / sqrt(2)\nend\n\n# This does not appar any faster than computing each separately\n# function RXalt(θ)\n#     (s, c) = sincos(θ/2)\n#     si = - im * s\n#     return [c si; si c]\n# end\n\nfunction RX(θ)\n    c = cos(θ/2)\n    s = - im * sin(θ/2)\n    return [c s; s c]\nend\n\nfunction RXpi(z)\n    c = cospi(z/2)\n    s = -im * sinpi(z/2)\n    return [c s; s c]\nend\n\nfunction RY(θ)\n    c = cos(θ/2)\n    s = sin(θ/2)\n    return [c -s; s c]\nend\n\nfunction RYpi(z)\n    c = cospi(z/2)\n    s = sinpi(z/2)\n    return [c -s; s c]\nend\n\nfunction RZ(θ)\n    return [cis(-θ/2) 0; 0 cis(θ/2)]\nend\n\nfunction RZpi(z)\n    return [_exp_ipi(-z/2) 0; 0 _exp_ipi(z/2)]\nend\n\n\"\"\"\n    Ualt(θ, ϕ, λ)\n\nMatrix from SU(2).\nAlternative parameterization.\n\"\"\"\nfunction Ualt(θ, ϕ, λ)\n    c = cos(θ/2)\n    s = sin(θ/2)\n    fpl =  (ϕ + λ) / 2\n    cfpl = cos(fpl)\n    sfpl = sin(fpl)\n    fml =  (ϕ - λ) / 2\n    cfml = cos(fml)\n    sfml = sin(fml)\n    f00 = complex(cfpl, -sfpl) * c\n    f01 = complex(-cfml, sfml) * s\n    f10 = complex(cfml, sfml) * s\n    f11 = complex(cfpl, sfpl) * c\n    return [f00 f01; f10 f11]\nend\n\n\"\"\"\n    U(θ, ϕ, λ)\n\nMatrix from SU(2). This is\nthe same as qiskit's U or U3.\n\"\"\"\nfunction U(θ, ϕ, λ)\n    c = cos(θ/2)\n    s = sin(θ/2)\n    fpl =  (ϕ + λ)\n    cfpl = cos(fpl)\n    sfpl = sin(fpl)\n    f00 = c\n    f01 = -s * complex(cos(λ), sin(λ))\n    f10 = s * complex(cos(ϕ), sin(ϕ))\n    f11 = c * complex(cfpl, sfpl)\n    return [f00 f01; f10 f11]\nend\n\n\"\"\"\n    Ualtpi(θ, ϕ, λ)\n\nMatrix from SU(2), with `θ`, `ϕ`, and `λ` given as multiples of `π`.\nThis is more accurate than `Ualt`.\n\"\"\"\nfunction Ualtpi(θ, ϕ, λ)\n    c = cospi(θ/2)\n    s = sinpi(θ/2)\n    fpl =  (ϕ + λ) / 2\n    fml =  (ϕ - λ) / 2\n    cfpl = cospi(fpl)\n    sfpl = sinpi(fpl)\n    cfml = cospi(fml)\n    sfml = sinpi(fml)\n    f00 = complex(cfpl, -sfpl) * c\n    f01 = complex(-cfml, sfml) * s\n    f10 = complex(cfml, sfml) * s\n    f11 = complex(cfpl, sfpl) * c\n    return [f00 f01; f10 f11]\nend\n\n@doc raw\"\"\"\n    R(θ, ϕ)\n\nThe R gate.\n```math\nR(\\theta, \\phi) = e^{-i \\frac{\\theta}{2} (\\cos{\\phi} x + \\sin{\\phi} y)}\n```\n\"\"\"\nfunction R(θ, ϕ)\n    c = cos(θ/2)\n    s = sin(θ/2)\n    return [c -im*exp(-im*ϕ)*s;\n            -im*exp(im*ϕ)*s c]\nend\n\n@doc raw\"\"\"\n    Rpi(θ, ϕ)\n\nThe R gate with θ and ϕ reduced by π. This is may be more accurate,\nfor example with integral and half-integral multiples of π.\n```math\nRpi(\\theta, \\phi) = e^{-i \\frac{\\pi\\theta}{2} (\\cos{\\pi\\phi} x + \\sin{\\pi\\phi} y)}\n```\n\"\"\"\nfunction Rpi(θ, ϕ)\n    c = cospi(θ/2)\n    s = sinpi(θ/2)\n    return [c -im*cispi(-ϕ)*s;\n            -im*cispi(ϕ)*s c]\nend\n\n\"\"\"\n    RXXYY(θ)\n\nThe R_XXYY gate, `exp(-im θ / 2 (X⊗X + Y⊗Y))`.\n\"\"\"\nfunction RXXYY(θ)\n    _RXXYY(θ, cos, sin)\nend\n\n\"\"\"\n    RXXYYpi(θ)\n\nThe R_XXYY gate with `θ` scaled by `π`. `exp(-im * pi * θ / 2 * (X⊗X + Y⊗Y))`\n\"\"\"\nfunction RXXYYpi(θ)\n    _RXXYY(θ, cospi, sinpi)\nend\n\n\nfunction _RXXYY(θ, cfunc, sfunc)\n    II = I2 ⊗ I2 / 2\n    XX = X ⊗ X / 2\n    YY = Y ⊗ Y / 2\n    ZZ = Z ⊗ Z / 2\n    return II + ZZ + cfunc(θ) * (II - ZZ) -im * sfunc(θ) * (XX + YY)\nend\n", "meta": {"hexsha": "eb6ab92ad54d60445d02257696aecc2cb58407d8", "size": 3641, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/parametric.jl", "max_stars_repo_name": "jlapeyre/QMatrices.jl", "max_stars_repo_head_hexsha": "eb20d94a69775fb5d6867b0996ae634d3329a5a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/parametric.jl", "max_issues_repo_name": "jlapeyre/QMatrices.jl", "max_issues_repo_head_hexsha": "eb20d94a69775fb5d6867b0996ae634d3329a5a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/parametric.jl", "max_forks_repo_name": "jlapeyre/QMatrices.jl", "max_forks_repo_head_hexsha": "eb20d94a69775fb5d6867b0996ae634d3329a5a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.1144278607, "max_line_length": 82, "alphanum_fraction": 0.5300741555, "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7902912996329543}}
{"text": "# # [Basic Epidemiology Models](@id epidemiology_example)\n#\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/examples/epidemiology.ipynb)\n\nusing Petri\nusing LabelledArrays\nusing Plots\nusing DiffEqJump\nusing StochasticDiffEq\nusing OrdinaryDiffEq\n\n# ### SIR Model\n#\n# The SIR model represents the epidemiological dynamics of an infectious disease\n# that causes immunity in its victims. There are three *states:* `Suceptible\n# ,Infected, Recovered`. These states interact through two *transitions*.\n# Infection has the form `S+I -> 2I` where a susceptible person meets an\n# infected person and results in two infected people. The second transition is\n# recovery `I -> R` where an infected person recovers spontaneously.\n\nS  = [:S,:I,:R]\nΔ  = LVector(\n       inf=(LVector(S=1, I=1), LVector(I=2)),\n       rec=(LVector(I=1),      LVector(R=1)),\n     )\nsir = Petri.Model(S, Δ)\n\nGraph(sir)\n\n# Once a model is defined, we can define out initial parameters `u0`, a time\n# span `tspan`, and the transition rates of the interactions `β`\n\nu0 = LVector(S=990.0, I=10.0, R=0.0)\ntspan = (0.0,40.0)\n# add a dynamic transition rate for infection\n# where the rate of infection decreases over time\n# as is dependent on the current state of the system\nβ = LVector(inf=((u,t)->((3/sum(u))/(t+1))), rec=0.25);\n\n# each transition rates can one of three options:\n#\n# - constant: `β = [.25]`\n#   - where the rate is specified by a value of type `Number`\n# - time dependent: `β = [t->((3/1000)/(t+1))]`\n#   - where `t` is the current time step\n# - state and time dependent: `β = [(u,t)->((3/sum(u))/(t+1))]`\n#   - where `u` is the current state of `u0` and `t` is the current time step\n\n# Petri.jl provides interfaces to StochasticDiffEq.jl, DiffEqJump.jl, and\n# OrdinaryDiffEq.jl Here, we call the `JumpProblem` function that returns an\n# DiffEqJump problem object that can be passed to the DiffEqJump solver which\n# can then be plotted and visualized\n\nprob = JumpProblem(sir, u0, tspan, β)\nsol = DiffEqJump.solve(prob,SSAStepper())\n\nplot(sol)\n\n# Similarly, we can generated `SDEProblem` statements that can be used with\n# StochasticDiffEq solvers\n\nprob, cb = SDEProblem(sir, u0, tspan, β)\nsol = StochasticDiffEq.solve(prob,LambaEM(),callback=cb)\n\nplot(sol)\n\n# Lastly, we can generated `ODEProblem` statements that can be used with\n# OrdinOrdinaryDiffEq solvers\n\nprob = ODEProblem(sir, u0, tspan, β)\nsol = OrdinaryDiffEq.solve(prob,Tsit5(),reltol=1e-8,abstol=1e-8)\n\nplot(sol)\n\n# ### SEIR Model\n\nS = [:S,:E,:I,:R]\nΔ = LVector(\n      exp=(LVector(S=1, I=1), LVector(I=1, E=1)),\n      inf=(LVector(E=1),      LVector(I=1)),\n      rec=(LVector(I=1),      LVector(R=1)),\n    )\nseir = Petri.Model(S, Δ)\n\nGraph(seir)\n#-\nu0 = LVector(S=990.0, E=10.0, I=0.0, R=0.0)\ntspan = (0.0,40.0)\nβ = LVector(exp=0.7/sum(u0), inf=0.5, rec=0.25)\n\nprob, cb = SDEProblem(seir, u0, tspan, β)\nsol = StochasticDiffEq.solve(prob,LambaEM(),callback=cb)\n\nplot(sol)\n\n# ### SEIRD Model\n\nS = [:S,:E,:I,:R, :D]\nΔ = LVector(\n      exp=(LVector(S=1, I=1), LVector(I=1, E=1)),\n      inf=(LVector(E=1),      LVector(I=1)),\n      rec=(LVector(I=1),      LVector(R=1)),\n      die=(LVector(I=1),      LVector(D=1)),\n    )\nseird = Petri.Model(S, Δ)\n\nGraph(seird)\n#-\nu0 = LVector(S=990.0, E=10.0, I=0.0, R=0.0, D=0.0)\ntspan = (0.0,40.0)\nβ = LVector(exp=0.9/sum(u0), inf=0.9, rec=0.25, die=0.03)\n\nprob, cb = SDEProblem(seird, u0, tspan, β)\nsol = StochasticDiffEq.solve(prob,LambaEM(),callback=cb)\n\nplot(sol)\n", "meta": {"hexsha": "e07abdf2643b1cc2ee66bcf0fb69ce0acd7660ba", "size": 3480, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/epidemiology.jl", "max_stars_repo_name": "stjordanis/Petri.jl", "max_stars_repo_head_hexsha": "1db4ec9d43aa9f0334ccb581a47d119f329bf05a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2019-11-01T17:12:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:08:18.000Z", "max_issues_repo_path": "examples/epidemiology.jl", "max_issues_repo_name": "stjordanis/Petri.jl", "max_issues_repo_head_hexsha": "1db4ec9d43aa9f0334ccb581a47d119f329bf05a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2019-10-03T19:43:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T15:52:19.000Z", "max_forks_repo_path": "examples/epidemiology.jl", "max_forks_repo_name": "stjordanis/Petri.jl", "max_forks_repo_head_hexsha": "1db4ec9d43aa9f0334ccb581a47d119f329bf05a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-19T13:29:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T22:56:19.000Z", "avg_line_length": 29.7435897436, "max_line_length": 118, "alphanum_fraction": 0.6686781609, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7902912927935387}}
{"text": "\r\ngrid_size = 25  \r\ngamma_vals = linspace(0.05, 0.95, grid_size)  \r\nw_bar_vals = similar(gamma_vals)\r\n\r\nmcm = McCallModel()\r\n\r\nfor (i, gamma) in enumerate(gamma_vals)\r\n    mcm.gamma = gamma\r\n    w_bar = compute_reservation_wage(mcm)\r\n    w_bar_vals[i] = w_bar\r\nend\r\n\r\nplot(gamma_vals, \r\n    w_bar_vals, \r\n    lw=2, \r\n    alpha=0.7, \r\n    xlabel=\"job offer rate\",\r\n    ylabel=\"reservation wage\",\r\n    label=L\"$\\bar w$ as a function of $\\gamma$\")\r\n", "meta": {"hexsha": "266b31466139b78f210decfb6103544cc99f83dd", "size": 446, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "mccall/mccall_resw_gamma.jl", "max_stars_repo_name": "parkjt0506/QuantEconPractice", "max_stars_repo_head_hexsha": "2d83848dab7ed8d40efc9bbcf1e73aed7e5e532f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-06T04:09:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-06T04:09:21.000Z", "max_issues_repo_path": "mccall/mccall_resw_gamma.jl", "max_issues_repo_name": "zhouweimin-econ/QuantEcon.lectures.code", "max_issues_repo_head_hexsha": "a8a17e753857e0157f18337264114ce7cb23e841", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mccall/mccall_resw_gamma.jl", "max_forks_repo_name": "zhouweimin-econ/QuantEcon.lectures.code", "max_forks_repo_head_hexsha": "a8a17e753857e0157f18337264114ce7cb23e841", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-04-21T21:41:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T22:09:19.000Z", "avg_line_length": 21.2380952381, "max_line_length": 49, "alphanum_fraction": 0.6278026906, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7902912866331786}}
{"text": "module p3\n\n# Return boundary conditions values and indices, ϕb and β, for problem 2, \n# with N subdivisions\nfunction boundaryconditions3(N::Integer)\n    ϕb = zeros(N+1,N+1)                 # boundary conditions\n    β  = zeros(Int,N+1,N+1)             # boundary condition locations\n\n    # Conditions on the perimeter\n    ϕb[:,1] = ϕb[:,N+1] = ϕb[1,:] = ϕb[N+1,:] = 0.0\n    β[:,1]  = β[:,N+1]  = β[1,:]  = β[N+1,:]  = 1\n\n    # Conditions on the interior\n    # xmin < x < xmax  →  N*xmin + 1 < i < N*xmax + 1\n    xmin = 0.5\n    xmax = 0.75\n    ymin = 0.625\n    ymax = 0.875\n\n    xs = int([ceil(N*xmin+1):floor(N*xmax+1)])\n    ys = int([ceil(N*ymin+1):floor(N*ymax+1)])\n\n    ϕb[xs,ys] = 0.0\n    β[xs,ys]  = 1\n\n    return ϕb, β\nend\n\n# Calculate the potential\nfunction V(x::Real, y::Real, N::Integer, q::Real)\n\n    a = b = 1:(N+1)\n    a .-= (N*x + 0.5)           # avoid singularity\n    b .-= (N*y + 0.5)\n    a .*= a\n    b .*= b\n    return -N*q ./ √(a .+ b')\n\nend\n\nV(N::Integer, q::Real) = V(0.5, 0.25, N, q)\n\nfunction minor(A::Matrix, β::Vector)\n    \n    size(A)[1] == size(A)[2] || error(\"Matrix must be square\")\n\n    N = sum(1 .- β)             # dimensions of new matrix\n\n    B = Array(typeof(A[1]),N,N)\n\n    ii = 1\n    jj = 1\n\n    for j in 1:size(A)[1]\n        β[j] == 1 && continue\n        for i in 1:size(A)[2]\n            β[i] == 1 && continue\n            B[ii,jj] = A[i,j]\n            ii += 1\n        end\n        jj +=1\n        ii = 1\n    end\n\n    return B\nend\n\n# repopulate a vector v with zeros for fixed parameters\nfunction addwater(v::Vector, β::Vector)\n\n    vf = Array(typeof(v[1]),length(β))\n    ii = 1\n\n    length(v) == sum(1-β) || error(\"v and β have different num free params\")\n\n    for i in 1:length(β)\n        if β[i] == 1\n            vf[i] = 0               # put zero for a fixed value\n        elseif β[i] == 0\n            vf[i] = v[ii]           # fill in the free value\n            ii += 1                 # prep the next free value\n        else\n            error(\"β can only have 0 or 1 values\")\n        end\n    end\n    return vf\n\nend\n\nend\n", "meta": {"hexsha": "28be47b812a1393e6df390853f69cb4204728a3b", "size": 2060, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "set05/p3.jl", "max_stars_repo_name": "stefco/g6080", "max_stars_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "set05/p3.jl", "max_issues_repo_name": "stefco/g6080", "max_issues_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "set05/p3.jl", "max_forks_repo_name": "stefco/g6080", "max_forks_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6373626374, "max_line_length": 76, "alphanum_fraction": 0.486407767, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.8615382058759128, "lm_q1q2_score": 0.7902912836892237}}
{"text": "using Flux\nusing Statistics\nusing Plots\nusing DifferentialEquations\n\n\n# Solve the ode given by $$ u' = \\cos 2\\pi t $$ by approximation of $u$ with a Neural Network\nNNODE = Chain(x -> [x], # Take in a scalar and transform it into an array\n              Dense(1,32,tanh),\n              Dense(32,1),\n              first) # Take first value, i.e. return a scalar\nNNODE(1.0)\n\n# construct function $g(t)$ to enforce initial condition $$ g(t) = t NNODE(t) + u(0)\nu₀ = 1.0\ng(t) = t*NNODE(t) + u₀\n\n\n\n#Construct loss function to numericaly compute derivative and check against R.H.S.\nϵ = sqrt(eps(Float32))\nloss() = mean(abs2(((g(t+ϵ)-g(t))/ϵ) - cos(2π*t)) for t in 0:1f-2:1f0)\n\n\nopt = Flux.Descent(0.01)\ndata = Iterators.repeated((), 5000)\niter = 0\ncb = function () #callback function to observe training\n    global iter += 1\n    if iter % 500 == 0\n        display(loss())\n    end\nend\ndisplay(loss())\nFlux.train!(loss, Flux.params(NNODE), data, opt; cb=cb)\n\n\n\n# compare against true solution\nt = 0:1e-3:1.0\n\nplot(t, g.(t), label=\"NN\")\nplot!(t, u₀ .+ sin.(2π.*t)/2π, label=\"True Solution\")\n\n\n\n", "meta": {"hexsha": "12cc9e1b369b6aa29052b8f1f7a036198dee0904", "size": 1083, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "NN_Diffeq_Fitting.jl", "max_stars_repo_name": "john-waczak/SciML_SHO", "max_stars_repo_head_hexsha": "180d46e9755e6a70f281086a373e183b57544275", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NN_Diffeq_Fitting.jl", "max_issues_repo_name": "john-waczak/SciML_SHO", "max_issues_repo_head_hexsha": "180d46e9755e6a70f281086a373e183b57544275", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NN_Diffeq_Fitting.jl", "max_forks_repo_name": "john-waczak/SciML_SHO", "max_forks_repo_head_hexsha": "180d46e9755e6a70f281086a373e183b57544275", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0425531915, "max_line_length": 93, "alphanum_fraction": 0.6278855032, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574668, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.790277869299459}}
{"text": "const AbstractVec = SVector{3, T} where T <: AbstractFloat\nconst Vec = AbstractVec{Float64}\n\nfunction normalize(v::AbstractVec)::AbstractVec\n    v / norm(v)\nend\n\n@inline function x(v::AbstractVec)::AbstractFloat\n    v[1]\nend\n\n@inline function y(v::AbstractVec)::AbstractFloat\n    v[2]\nend\n\n@inline function z(v::AbstractVec)::AbstractFloat\n    v[3]\nend\n\nfunction random_on_unit_disk()::AbstractVec\n    v::AbstractVec = Vec(randn(), randn(), 0.0)\n    normalize(v)\nend\n\nfunction random_in_unit_disk()::AbstractVec\n    v::AbstractVec = random_on_unit_disk()\n    r::AbstractFloat = rand()\n    sqrt(r) * v\nend\n\nfunction random_on_unit_sphere()::AbstractVec\n    v::AbstractVec = Vec(randn(), randn(), randn())\n    normalize(v)\nend\n\nfunction random_in_unit_sphere()::AbstractVec\n    v::AbstractVec = random_on_unit_disk()\n    r::AbstractFloat = rand()\n    cbrt(r) * v\nend\n\nfunction reflect(v::AbstractVec, n::AbstractVec)::AbstractVec\n    v::AbstractVec = normalize(v)\n    v - 2dot(v, n)n\nend\n\nfunction refract(v::AbstractVec, n::AbstractVec, index::AbstractFloat)::Tuple{Bool, Union{Nothing, AbstractVec}}\n    v::AbstractVec = normalize(v)\n    dt::AbstractFloat = dot(v, n)\n    discriminant::AbstractFloat = 1.0 - index^2 * (1.0 - dt^2)\n    if discriminant > 0\n        refracted::AbstractVec = index * (v - n * dt) - n * sqrt(discriminant)\n        true, refracted\n    end\n    false, nothing\nend\n", "meta": {"hexsha": "bd503b2f6f20cafe10c73295fa6eb2eafe016c5d", "size": 1389, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vector.jl", "max_stars_repo_name": "goooxu/JuliaRayTracing", "max_stars_repo_head_hexsha": "222dc1f10aca5ea6f5989edf66b31c9cda62f84d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-02-28T06:56:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-10T11:38:28.000Z", "max_issues_repo_path": "src/vector.jl", "max_issues_repo_name": "goooxu/JuliaRayTracing", "max_issues_repo_head_hexsha": "222dc1f10aca5ea6f5989edf66b31c9cda62f84d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vector.jl", "max_forks_repo_name": "goooxu/JuliaRayTracing", "max_forks_repo_head_hexsha": "222dc1f10aca5ea6f5989edf66b31c9cda62f84d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-28T07:02:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-28T07:02:39.000Z", "avg_line_length": 24.3684210526, "max_line_length": 112, "alphanum_fraction": 0.6861051116, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.958537726104152, "lm_q2_score": 0.8244619328462579, "lm_q1q2_score": 0.7902778663698862}}
{"text": "function nominal_diameter(method,P,Hn,Vdotn)\r\n        if method == \"Bier\" # default\r\n            D = 0.176*(P/Hn)^0.466\r\n        elseif method == \"Sarkaria\"\r\n            D = 0.71*P^0.43/Hn^0.65\r\n        elseif method == \"Warnick\"\r\n            D = 0.72*P^0.43/Hn^0.63\r\n        elseif method == \"Moffat\"\r\n            D = 0.52*P^0.43/Hn^0.6\r\n        # methods not depending on efficiency\r\n        elseif method == \"USBR\"\r\n            D = 1.517*Vdotn^0.5/Hn^0.25\r\n        elseif method == \"Fahlbusch\"\r\n            D = 1.12*Vdotn^0.45/Hn^0.12\r\n        end\r\n    return D*1.5\r\nend\r\n# for darcys friction factor Sami and Jain\r\nfunction f_Darcy(NRe, pipe_roughness,D)\r\n    f = 1/(1.8*log10(6.9/NRe+(pipe_roughness/D/3.7)^1.1))^2\r\n    return f\r\nend\r\n# for Reynolds number\r\nfunction renoldsnum(rho,v,D,mu)\r\n    return rho*v*D/mu\r\nend\r\n#\r\n", "meta": {"hexsha": "c47eb902b2153a2507b4260207ab5655217eb99a", "size": 827, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fluid.jl", "max_stars_repo_name": "pandeysudan27/OpenHPLJulia.jl", "max_stars_repo_head_hexsha": "feaec57dc1c9b609bc3f3533cf55929643f5298a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fluid.jl", "max_issues_repo_name": "pandeysudan27/OpenHPLJulia.jl", "max_issues_repo_head_hexsha": "feaec57dc1c9b609bc3f3533cf55929643f5298a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fluid.jl", "max_forks_repo_name": "pandeysudan27/OpenHPLJulia.jl", "max_forks_repo_head_hexsha": "feaec57dc1c9b609bc3f3533cf55929643f5298a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5357142857, "max_line_length": 60, "alphanum_fraction": 0.5441354293, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241956308277, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7902245769932447}}
{"text": "using LinearAlgebra\n\n\"\"\"\n    angularWaveVectorComponent(n, L)\n    \nReturns the angular wave vector component for a rectangular room given the\nmode index and room length along the required component cartesian direction, in\nmeters.\n# Example\n```jldoctest\njulia> nx = 7\n7\n\njulia> Lx = 5\n5\n\njulia> kx = angularWaveVectorComponent(nx, Lx)\n4.39822971502571\n```\n\"\"\"\nfunction angularWaveVectorComponent(n::Integer, L::Real)\n    return n * π / L\nend\n\n\"\"\"\n    angularWaveVector(nx, ny, nz, Lx, Ly, Lz)\n    \nReturns the angular wave vector of a rectangular room mode. Mode numbers along\nthe cartesian directions are nx ny and nz, the room sizes along the cartesian\ndirections are Lx, Ly and Lz meters.\n# Example\n```jldoctest\njulia> angularWaveVector(1, 4, 7, 5.0, 4.0, 3.0)\n3-element Array{Float64,1}:\n 0.6283185307179586\n 3.141592653589793 \n 7.330382858376184 \n```\n\"\"\"\nfunction angularWaveVector(\n    nx::Integer, ny::Integer, nz::Integer,\n    Lx::Real, Ly::Real, Lz::Real\n    )\n\n    return [\n        angularWaveVectorComponent(nx, Lx);\n        angularWaveVectorComponent(ny, Ly);\n        angularWaveVectorComponent(nz, Lz)\n        ]\n\nend\n\n\"\"\"\n    modeFrequency(nx, ny, nz, Lx, Ly, Lz, c)\n    \nReturns the modal frequency of a mode characterized by indeces nx, ny and nz\nalong the cartesian directions for a rectangular room of sizes Lx, Ly and Lz\nmeters along the cartesian directions. c is the speed of sound in air, by\ndefault 343.0 meters per second (speed at standard conditions).\n# Example\n```jldoctest\njulia> modeFrequency(1, 4, 7, 5.0, 4.0, 3.0)\n436.7174156260672\n\njulia> modeFrequency(1, 4, 7, 5.0, 4.0, 3.0, 340.0)\n432.89772977511035\n```\n\"\"\"\nfunction modeFrequency(\n    nx::Integer, ny::Integer, nz::Integer,\n    Lx::Real, Ly::Real, Lz::Real,\n    c::Real = 343.0\n    )\n\n    return norm(angularWaveVector(nx, ny, nz, Lx, Ly, Lz)) * c / 2π\n\nend\n\n\"\"\"\n    mode(x, y, z, nx, ny, nz, Lx, Ly, Lz)\n    \nReturns the modal shape at coordinates in x, y, z for mode characterized by\nindeces nx, ny and nz along the cartesian directions for a rectangular room of\nsizes Lx, Ly and Lz meters along the cartesian directions. Result returned\nnormalized between 1 and -1, arbitrary units.\n# Example\n```jldoctest\njulia> mode(2.5, 2.0, 1.5, 1, 4, 7, 5.0, 4.0, 3.0)\n0.0\n\njulia> mode.([3.0; 2.5], [1.0; 2.0], [0.75; 1.5], 1, 4, 7, 5.0, 4.0, 3.0)\n2-element Array{Float64,1}:\n 0.2185080122244105\n 0.0\n```\n\"\"\"\nfunction mode(\n    x::Real, y::Real, z::Real,\n    nx::Integer, ny::Integer, nz::Integer,\n    Lx::Real, Ly::Real, Lz::Real\n    )\n\nreturn cospi(nx * x / Lx) * cospi(ny * y / Ly) * cospi(nz * z / Lz)\n\nend\n\n\"\"\"\n    meshGrid(x, y, z)\n    \nReturns the 3-D grid coordinates defined by the vectors x, y, and z.\nThe grid is represented by three matrices of size length(y) by length(x) by \nlength(z). This is similar to MATLAB's meshgrid.\n# Example\n```jldoctest\njulia> x = [1; 2]\n2-element Array{Int64,1}:\n 1\n 2\n \njulia> y = [3; 4]\n2-element Array{Int64,1}:\n 3\n 4\n \njulia> z = [5; 6]\n2-element Array{Int64,1}:\n 5\n 6\n \njulia> X, Y, Z = meshGrid(x, y, z)\n([1 2; 1 2]\n\n[1 2; 1 2], [3 3; 4 4]\n\n[3 3; 4 4], [5 5; 5 5]\n\n[6 6; 6 6])\n```\n\"\"\"\nfunction meshGrid(x::AbstractArray, y::AbstractArray, z::AbstractArray)\n\n    X = zeros(eltype(x), length(y), length(x), length(z))\n    fX(i, j, k) = X[i, j, k] = x[j]\n    [fX(i, j, k) for i in 1:length(y), j in 1:length(x), k in 1:length(z)]\n\n    Y = zeros(eltype(y), length(y), length(x), length(z))\n    fY(i, j, k) = Y[i, j, k] = y[i]\n    [fY(i, j, k) for i in 1:length(y), j in 1:length(x), k in 1:length(z)]\n\n    Z = zeros(eltype(z), length(y), length(x), length(z))\n    fZ(i, j, k) = Z[i, j, k] = z[k]\n    [fZ(i, j, k) for i in 1:length(y), j in 1:length(x), k in 1:length(z)]\n\n    return X, Y, Z\n\nend\n\n\"\"\"\n    indexGrid(Nx, Ny, Nz)\n    \nReturns a 3-D grid up to indeces Nx, Ny and Nz along the 3 cartesian\ndirections. The grid is represented by three matrices of size Ny by Nx by Nz.\n# Example\n```jldoctest\njulia> Gx, Gy, Gz = indexGrid(3, 4, 5)\n([1 2 3; 1 2 3; 1 2 3; 1 2 3]\n\n[1 2 3; 1 2 3; 1 2 3; 1 2 3]\n\n[1 2 3; 1 2 3; 1 2 3; 1 2 3]\n\n[1 2 3; 1 2 3; 1 2 3; 1 2 3]\n\n[1 2 3; 1 2 3; 1 2 3; 1 2 3], [1 1 1; 2 2 2; 3 3 3; 4 4 4]\n\n[1 1 1; 2 2 2; 3 3 3; 4 4 4]\n\n[1 1 1; 2 2 2; 3 3 3; 4 4 4]\n\n[1 1 1; 2 2 2; 3 3 3; 4 4 4]\n\n[1 1 1; 2 2 2; 3 3 3; 4 4 4], [1 1 1; 1 1 1; 1 1 1; 1 1 1]\n\n[2 2 2; 2 2 2; 2 2 2; 2 2 2]\n\n[3 3 3; 3 3 3; 3 3 3; 3 3 3]\n\n[4 4 4; 4 4 4; 4 4 4; 4 4 4]\n\n[5 5 5; 5 5 5; 5 5 5; 5 5 5])\n\n```\n\"\"\"\nfunction indexGrid(Nx::Integer, Ny::Integer, Nz::Integer)\n    return meshGrid(0:Nx, 0:Ny, 0:Nz)\nend\n\n\"\"\"\n    roomAxes(rx, ry, rz, Lx, Ly, Lz)\n    \nReturns the 1-D axes coordinates along the sides of a rectangular room with\nreference to a corner. The room has sizes Lx, Ly and Lz meters along the\ncartesian directions, while rx, ry and rz express the step of the axes along\neach cartesian direction.\n\"\"\"\nfunction roomAxes(\n    rx::Real, ry::Real, rz::Real,\n    Lx::Real, Ly::Real, Lz::Real\n    )\n    \n    x = range(0.0, stop = Lx, length = round(Integer, 1 + Lx / rx))\n    y = range(0.0, stop = Ly, length = round(Integer, 1 + Ly / ry))\n    z = range(0.0, stop = Lz, length = round(Integer, 1 + Lz / rz))\n    \n    return x, y, z\n    \nend\n\n\"\"\"\n    roomGrid(rx, ry, rz, Lx, Ly, Lz)\n    \nReturns the 3-D grid coordinates inside a rectangular room with reference to a\ncorner. The room has sizes Lx, Ly and Lz meters along the cartesian directions,\nwhile rx, ry and rz express the step of the grid along each cartesian direction.\n\"\"\"\nfunction roomGrid(\n    rx::Real, ry::Real, rz::Real,\n    Lx::Real, Ly::Real, Lz::Real\n    )\n\n    x, y, z = roomAxes(rx, ry, rz, Lx, Ly, Lz)\n\n    return meshGrid(x, y, z)\n\nend\n", "meta": {"hexsha": "7b5695e6bd2e43de90998c626ab2b57f1558fb59", "size": 5624, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "RectangularRoom.jl", "max_stars_repo_name": "CrocoDuckoDucks/RectangularRoom", "max_stars_repo_head_hexsha": "a777346d12aff8d2f6e48806c57d21adc919b044", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-01T13:43:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-01T13:43:23.000Z", "max_issues_repo_path": "RectangularRoom.jl", "max_issues_repo_name": "CrocoDuckoDucks/RectangularRoom", "max_issues_repo_head_hexsha": "a777346d12aff8d2f6e48806c57d21adc919b044", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RectangularRoom.jl", "max_forks_repo_name": "CrocoDuckoDucks/RectangularRoom", "max_forks_repo_head_hexsha": "a777346d12aff8d2f6e48806c57d21adc919b044", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8305084746, "max_line_length": 80, "alphanum_fraction": 0.6225106686, "num_tokens": 2255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464604, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7902066696559275}}
{"text": "using Distributions, Random, Plots; pyplot()\nRandom.seed!(0)\n\nn, N, alpha = 3, 10^7, 0.1\n\nmyT(nObs) = rand(Normal())/sqrt(rand(Chisq(nObs-1))/(nObs-1))\nmcQuantile = quantile([myT(n) for _ in 1:N],alpha)\nanalyticQuantile = quantile(TDist(n-1),alpha)\n\nprintln(\"Quantile from Monte Carlo: \", mcQuantile)\nprintln(\"Analytic qunatile: \", analyticQuantile)\n\nxGrid = -5:0.1:5\nplot(xGrid, pdf.(Normal(), xGrid), c=:black, label=\"Normal Distribution\")\nscatter!(xGrid, pdf.(TDist(1) ,xGrid), \n\tc=:blue, msw=0, label=\"DOF = 1\")\nscatter!(xGrid, pdf.(TDist(3), xGrid), \n\tc=:red, msw=0, label=\"DOF = 3\")\nscatter!(xGrid, pdf.(TDist(100),xGrid), \n\tc=:green, msw=0, label=\"DOF = 100\", \n\txlims=(-4,4), ylims=(0,0.5), xlabel=\"X\", ylabel=\"Density\")", "meta": {"hexsha": "a7b81751c54ca7912bf3c473f37547a3eb3c0f52", "size": 727, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5_chapter/tDistribution.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "5_chapter/tDistribution.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "5_chapter/tDistribution.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 34.619047619, "max_line_length": 73, "alphanum_fraction": 0.6602475928, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876287, "lm_q2_score": 0.8354835411997898, "lm_q1q2_score": 0.7902013995840689}}
{"text": "\"\"\"\r\n    rkf45(f,a,b,y0,M,delta)\r\nberisi program untuk mencari solusi persamaan\r\ndifferensial `y' = f(t,y)` dengan `y(a) = y0` pada interval `[a, b]`. Program ini secara\r\ndefault berisi 6 masukan, yaitu fungsi `f(t,y)`,\r\ntitik ujung interval penyelesaian `[a,b]`,\r\nnilai awal `y0`, jumlah sub-interval `M` dan nilai toleransi error `delta`\r\n\r\n# Example\r\n```jl\r\njulia> f(t,y) = 1+y^2;\r\n\r\njulia> sol = rkf45(f,0,1.4,0,7,2e-5)\r\n14×2 Array{Float64,2}:\r\n 0.0     0.0\r\n 0.2     0.20271\r\n 0.6     0.684165\r\n 0.8     1.02968\r\n ⋮\r\n 1.35    4.45586\r\n 1.375   5.04273\r\n 1.3875  5.39534\r\n 1.4     5.79895\r\n```\r\nreturn solusi masalah nilai awal `sol`.\r\n\"\"\"\r\nfunction rkf45(f,a,b,y0,M,delta)\r\n  M = round(M)\r\n  a2=1/4;b2=1/4;a3=3/8;b3=3/32;c3=9/32;\r\n  a4=12/13;b4=1932/2197;c4=-7200/2197;d4=7296/2197;\r\n  a5=1;b5=439/216;c5=-8;d5=3680/513;e5=-845/4104;\r\n  a6=1/2;b6=-8/27;c6=2;d6=-3544/2565;e6=1859/4104;f6=-11/40;\r\n  r1=1/360;r3=-128/4275;r4=-2197/75240;r5=1/50;r6=2/55;\r\n  n1=25/216;n3=1408/2565;n4=2197/4104;n5=-1/5;\r\n  big=1e15;\r\n  h=(b-a)/M;\r\n  hmin=h/64;\r\n  hmax=h*64;\r\n  maxi=200;\r\n  j=1;\r\n  Y = y0;\r\n  T = a;\r\n  br= b-0.001*abs(b);\r\n  err=NaN\r\n  while T[j]<b\r\n    if (T[j]+h)>br;h=b-T[j];end\r\n    #% Hitung koefisien\r\n    k1=h*f(T[j],Y[j]);\r\n    y2=Y[j]+b2*k1;\r\n    k2=h*f(T[j]+a2*h,y2);\r\n    y3=Y[j]+b3*k1+c3*k2;\r\n    k3=h*f(T[j]+a3*h,y3);\r\n    y4=Y[j]+b4*k1+c4*k2+d4*k3;\r\n    k4=h*f(T[j]+a4*h,y4);\r\n    y5=Y[j]+b5*k1+c5*k2+d5*k3+e5*k4;\r\n    k5=h*f(T[j]+a5*h,y5);\r\n    y6=Y[j]+b6*k1+c6*k2+d6*k3+e6*k4+f6*k5;\r\n    k6=h*f(T[j]+a6*h,y6);\r\n    err=abs(r1*k1+r3*k3+r4*k4+r5*k5+r6*k6);\r\n    ynew=Y[j]+n1*k1+n3*k3+n4*k4+n5*k5;\r\n    #% Perbarui ukuran langkah\r\n    if (err<delta) || (h<2*hmin)\r\n      Y = [Y; ynew];\r\n      if (T[j]+h)>br\r\n        T = [T; b];\r\n      else\r\n        T = [T; T[j]+h];\r\n      end\r\n      j=j+1;\r\n    end\r\n    if (err==0)\r\n      s=0;\r\n    else\r\n      s=0.84*(delta*h/err)^(0.25);\r\n    end\r\n    if (s<0.75)&&(h>2*hmin);h = h/2;end\r\n    if (s>1.50)&&(2*h<hmax);h = 2*h;end\r\n    if abs(Y[j])>big || maxi==j;break;end\r\n  end\r\n  sol = [T Y];\r\n  return sol\r\nend\r\n", "meta": {"hexsha": "3b287c4d79f359e626ff6d4a42c78d233dbbf609", "size": 2070, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rkf45.jl", "max_stars_repo_name": "mkhoirun-najiboi/metnum.jl", "max_stars_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rkf45.jl", "max_issues_repo_name": "mkhoirun-najiboi/metnum.jl", "max_issues_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rkf45.jl", "max_forks_repo_name": "mkhoirun-najiboi/metnum.jl", "max_forks_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9397590361, "max_line_length": 89, "alphanum_fraction": 0.522705314, "num_tokens": 1018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801274759925, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7902013983076975}}
{"text": "export getEdgeLength, getFaceArea, getCellVolume\n\nfunction getEdgeLength(mesh::TetraMesh)\n# get edge length\n\nif isempty(mesh.L)\n\n  ne = mesh.ne\n  L = zeros(ne)\n\n  for i=1:ne\n    i1 = mesh.edges[i,1]\n    i2 = mesh.edges[i,2]\n\n    L[i] = getEdgeLength(mesh.Points[i1,:],  mesh.Points[i2,:])\n  end\n\n  mesh.L = L\n\nend\n\nreturn mesh.L\nend\n\n\nfunction getFaceArea(mesh::TetraMesh)\n# get face size\n\nif isempty(mesh.F)\n  nf = mesh.nf\n  F = zeros(nf)\n  for i=1:nf\n    i1 = mesh.faces[i,1]\n    i2 = mesh.faces[i,2]\n    i3 = mesh.faces[i,3]\n\n    F[i] = getFaceArea(mesh.Points[i1,:], mesh.Points[i2,:], mesh.Points[i3,:])\n  end\n\nmesh.F = F\nend\n\nreturn mesh.F\nend\n\n\nfunction getCellVolume(mesh::TetraMesh)\n# get volume\n\nif isempty(mesh.V)\n\n  nc = mesh.nc\n  T  = mesh.Tetras\n  V = zeros(nc)\n\n  for i=1:nc\n    i1 = T[i,1]\n    i2 = T[i,2]\n    i3 = T[i,3]\n    i4 = T[i,4]\n\n    V[i] = getCellVolume(mesh.Points[i1,:], mesh.Points[i2,:], mesh.Points[i3,:], mesh.Points[i4,:])\n  end\n\n  mesh.V = V\n\nend\n\nreturn mesh.V\nend\n\n\nfunction getEdgeLength(P1::Array{Float64,1}, P2::Array{Float64,1})\n\treturn sqrt((P1[1] - P2[1])^2 + (P1[2] - P2[2])^2 + (P1[3] - P2[3])^2)\nend\n\nfunction getFaceArea(P1::Array{Float64,1}, P2::Array{Float64,1}, P3::Array{Float64,1})\n\treturn norm(cross(P3 - P1, P3 - P2))/2\nend\n\nfunction getCellVolume(P1::Array{Float64,1}, P2::Array{Float64,1}, P3::Array{Float64,1}, P4::Array{Float64,1})\n\treturn 1/6.0*abs(dot(P4 - P3, cross(P4 - P1, P4 - P2)))\nend\n", "meta": {"hexsha": "0c94fb70ffb4bdf8c22beb714038e765538a3029", "size": 1450, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/getSizes.jl", "max_stars_repo_name": "JuliaInv/JTetra", "max_stars_repo_head_hexsha": "f443c7086bbc89a150d34abc158e6d16289212c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/getSizes.jl", "max_issues_repo_name": "JuliaInv/JTetra", "max_issues_repo_head_hexsha": "f443c7086bbc89a150d34abc158e6d16289212c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-12-15T05:51:34.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-15T05:51:34.000Z", "max_forks_repo_path": "src/getSizes.jl", "max_forks_repo_name": "JuliaInv/JTetra", "max_forks_repo_head_hexsha": "f443c7086bbc89a150d34abc158e6d16289212c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-26T18:44:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:13:51.000Z", "avg_line_length": 17.2619047619, "max_line_length": 110, "alphanum_fraction": 0.6234482759, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799410139922, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7901967572866995}}
{"text": "using StaticArrays: SArray, @SMatrix\nusing LinearAlgebra: I, norm\n\n# This matrix-based implementation is very cool (IMO)\n# and only ~25% slower than the reference implementation for addition, multiplication, subtraction\n#\n# We get a 10x speedup for division and abs (although, for abs in particular, base widens to guard against overflow)\nstruct ComplexNumber{T<:Real} <: Number\n    mat::SArray{Tuple{2,2},T,2,4}\n    ComplexNumber(mat) = new{eltype(mat)}(mat)\n    ComplexNumber(real::T1,imag::T2) where {T1 <: Real, T2 <: Real} = new{promote_type(T1,T2)}(@SMatrix([real  -imag; imag real]))\nend\n\nBase.:*(l::ComplexNumber,r::ComplexNumber) = ComplexNumber(l.mat * r.mat)\nBase.:+(l::ComplexNumber,r::ComplexNumber) = ComplexNumber(l.mat + r.mat)\nBase.:-(l::ComplexNumber,r::ComplexNumber) = ComplexNumber(l.mat - r.mat)\nBase.:/(l::ComplexNumber,r::ComplexNumber) = ComplexNumber(l.mat * inv(r.mat))\nBase.:*(z::ComplexNumber,r::Real) = ComplexNumber(r*z.mat)\nBase.:*(r::Real, z::ComplexNumber) = z*r\nBase.:+(z::ComplexNumber,r::Real) = ComplexNumber(r*I + z.mat)\nBase.:+(r::Real, z::ComplexNumber) = z + r\n\nBase.show(io::IO, z::ComplexNumber) = print(io, \"ComplexNumber(\", Re(z), \", \", Im(z), \")\")\nBase.:≈(l::ComplexNumber,r::ComplexNumber) = l.mat ≈ r.mat # I had to make one of the division tests ≈ to pass it\nBase.:(==)(l::ComplexNumber,r::ComplexNumber) = l.mat == r.mat \n\nBase.abs(z::ComplexNumber) = norm(z.mat[:,1])\n\n# Sorry about the capital letter. That's what maths does.\n@inline Re(z::ComplexNumber) = @inbounds z.mat[1,1]\n@inline Im(z::ComplexNumber) = @inbounds z.mat[2,1]\n\nBase.real(z::ComplexNumber) = Re(z)\nBase.imag(z::ComplexNumber) = Im(z)\n\nBase.conj(z::ComplexNumber) = ComplexNumber(transpose(z.mat))\n\nBase.exp(z::ComplexNumber) = ComplexNumber(exp(z.mat))\n\n# There's not an iota of a chance that ι will take off as the sensible symbol to use for the imaginary unit\nconst ι = jm = ComplexNumber(0,1)\n", "meta": {"hexsha": "e0bc3fab9d28f7ff8fb648541eb931c8bd2cdea0", "size": 1918, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "complex-numbers/complex-numbers.jl", "max_stars_repo_name": "bovine3dom/exercism-julia", "max_stars_repo_head_hexsha": "9794db44d862fefb21c178d7c28e6af615185685", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "complex-numbers/complex-numbers.jl", "max_issues_repo_name": "bovine3dom/exercism-julia", "max_issues_repo_head_hexsha": "9794db44d862fefb21c178d7c28e6af615185685", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "complex-numbers/complex-numbers.jl", "max_forks_repo_name": "bovine3dom/exercism-julia", "max_forks_repo_head_hexsha": "9794db44d862fefb21c178d7c28e6af615185685", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6666666667, "max_line_length": 130, "alphanum_fraction": 0.700729927, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.8376199714402813, "lm_q1q2_score": 0.7901667685717936}}
{"text": "# This file includes the MonteCarlo simulation of ASK modulation scheme and compares \n# the numerical results with the theoretical results. \n\nusing DigitalCommunications \nusing Plots \n\n# Simulation parameters \nk = 3\nM = 2^k \nnsymbols = Int(1e6) \nnbits = k * nsymbols\nEp = 100.                       # Modulating pulse energy. \nebno = collect(0 : 10)          # Snr per bit \nesno = ebno .+ 10 * log10(k)    # Snr ber symbol  \n\n# Communcation system components  \ngen = BitGenerator(nbits) \ncoding = GrayCoding(M)\nmodulator = Modulator(PAM(M))\nchannel = AWGNChannel() \ndetector = Detector(alphabet(modulator))\n\n# Monte Carlo simulation \nmessage = coding(gen.bits)  # Message signal \nsymerr = zeros(length(esno))\nfor i in 1 : length(symerr)\n    channel.esno = esno[i]  # Update channel snr\n    mbar = gen.bits |> coding |> modulator |> channel |> detector  # Extracted message signal \n    symerr[i] = sum(mbar .!= message) / length(message)  # Symbol error rate \nend\n\n# Plots\nplt = plot(title=\"$M-PAM\", xlabel=\"ebno [dB]\", ylabel=\"Pe\") \nplot!(ebno, berpam.(ebno, M), marker=:circle, yscale=:log10, label=\"theoretical\")\nplot!(ebno, symerr, marker=:circle, yscale=:log10, label=\"montecarlo\")\n", "meta": {"hexsha": "4b0bae93f31796494203ff0ae983c00376f7baf1", "size": 1186, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/vector_simulations/montecarlopam.jl", "max_stars_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_stars_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-03T20:02:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T06:43:38.000Z", "max_issues_repo_path": "example/vector_simulations/montecarlopam.jl", "max_issues_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_issues_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-11-26T21:56:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-03T19:54:59.000Z", "max_forks_repo_path": "example/vector_simulations/montecarlopam.jl", "max_forks_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_forks_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-20T12:53:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T12:53:43.000Z", "avg_line_length": 32.9444444444, "max_line_length": 94, "alphanum_fraction": 0.6829679595, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475810629194, "lm_q2_score": 0.8376199572530449, "lm_q1q2_score": 0.7901667605246859}}
{"text": "#==============================================================================\n    Code for solving the Hamiltonian Jacboi Bellman for\n\t   an basic model: a neoclassical growth model: ρV(k) = max_{c} U(c) + V'(k)[F(k)-δk - c]\n\t   Where s(k) = F(k) - δk - c(k) and c(k) = U'^{-1}(V'(k))\n\n\tTranslated Julia code from Matlab code by Ben Moll:\n        http://www.princeton.edu/~moll/HACTproject.htm\n\n\t\tUpdated to julia 1.0.0\n==============================================================================#\n\nusing Distributions, Plots\n\n\nσ= 2.0 #\nρ = 0.05 #the discount rate\nδ = 0.05 # the depreciation rate\nA = 1.0\nα= 0.3\n\nk_ss = (α*A/(ρ+δ))^(1/(1-α))\n\nH= 150\nk_min = 0.001*k_ss\nk_max = 2.0*k_ss\n\nk = LinRange(k_min, k_max, H)\nk = convert(Array, k) # create grid for a values\ndk = (k_max-k_min)/(H-1)\n\nmaxit = 1000\nε = 10e-6\n\ndVf, dVb = [zeros(H,1) for i=1:2]\n\n#initial guess for V\nv0 = (A.*k.^α).^(1-σ)/(1-σ)/ρ\nv= v0\n\ndist=[]\n\nfor n=1:maxit\n\tV=v\n\n    # forward difference\n\tdVf[1:H-1] = (V[2:H]-V[1:H-1])/dk\n\tdVf[H] = 0\n\n\t# backward difference\n\tdVb[2:H] = (V[2:H]-V[1:H-1])/dk\n\tdVb[1] = 0 # the boundary condition\n\n\tI_concave = dVb .> dVf\n\n    # consumption and savings with forward difference\n    cf = dVf.^(-1/σ)\n    μ_f = A.*k.^α - δ.*k -cf\n\n    # consumption and savings with backward difference\n    cb = dVb.^(-1/σ)\n    μ_b = A.*k.^α - δ.*k -cb\n\n\tc0 = A.*k.^α - δ.*k\n    dV0 = c0.^(-σ)\n\n    # Now to make a choice between forward and backward difference\n    If = μ_f .> 0\n    Ib = μ_b .< 0\n    I0 = 1.0.-If-Ib\n    Ib[1] = false\n    If[1] = true\n    Ib[H] = true\n    If[H] = false\n\n    global dV_Upwind= dVf.*If + dVb.*Ib + dV0.*I0\n\n    global c = dV_Upwind.^(-1/σ)\n    V_change = c.^(1-σ)/(1-σ) + dV_Upwind.*(A.*k.^α - δ.*k-c) -ρ.*V\n\n\t# update\n\tΔ = .9*dk/(findmax(A.*k.^α- δ.*k-c)[1])\n\tglobal v = v + Δ*V_change\n\tpush!(dist,findmax(abs.(V_change))[1])\n\tif dist[n] .< ε\n\t\tprintln(\"Value Function Converged Iteration=\")\n\t\tprintln(n)\n\t\tbreak\n\tend\n\nend\n\nplot(dist, grid=false,\n\t\txlabel=\"Iteration\", ylabel=\"||V^{n+1} - V^n||\",\n\t\tylims=(-0.001,0.030),\n\t\tlegend=false, title=\"\")\npng(\"Convergence\")\n\n\nv_err = c.^(1-σ)/(1-σ) + dV_Upwind.*(A.*k.^α - δ.*k -c) - ρ.*v\n\nplot(k, v_err, grid=false,\n\t\txlabel=\"k\", ylabel=\"Error in the HJB equation\",\n\t\txlims=(k_min,k_max),\n\t\tlegend=false, title=\"\")\npng(\"HJB_error\")\n\n\nplot(k, v, grid=false,\n\t\txlabel=\"k\", ylabel=\"V(k)\",\n\t\txlims=(k_min,k_max),\n\t\tlegend=false, title=\"\")\npng(\"Value_function_vs_k\")\n\nplot(k, c, grid=false,\n\t\txlabel=\"k\", ylabel=\"c(k)\",\n\t\txlims=(k_min,k_max),\n\t\tlegend=false, title=\"\")\npng(\"c(k)_vs_k\")\n\n# approximation at the borrowing constraint\nk_dot = (A.*k.^α - δ.*k -c)\n\nplot(k, k_dot, grid=false,\n\t\txlabel=\"k\", ylabel=\"s(k)\",\n\t\txlims=(k_min,k_max), title=\"\", label=\"s(k)\", legend=:topright)\nplot!(k, zeros(H,1), label=\"\", line=:dash)\npng(\"stateconstraint\")\n", "meta": {"hexsha": "3a14a32122d11e7a5589a74284c53802b8346941", "size": 2811, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Moll_Code/Section15-General_Continuous_Time_Models/HJB_NGM/HJB_NGM.jl", "max_stars_repo_name": "chandlerlester/Radio_Free_Julia", "max_stars_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-02-26T11:52:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T12:41:38.000Z", "max_issues_repo_path": "Moll_Code/Section15-General_Continuous_Time_Models/HJB_NGM/HJB_NGM.jl", "max_issues_repo_name": "chandlerlester/Radio_Free_Julia", "max_issues_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Moll_Code/Section15-General_Continuous_Time_Models/HJB_NGM/HJB_NGM.jl", "max_forks_repo_name": "chandlerlester/Radio_Free_Julia", "max_forks_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-11T08:09:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-30T18:54:12.000Z", "avg_line_length": 21.9609375, "max_line_length": 90, "alphanum_fraction": 0.5535396656, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.790126328432845}}
{"text": "using Distributions\nusing StatsBase\n\nfunction Binom(k, N, p)\n    return pdf(Binomial(N, p), k)\nend\n\nfunction Binom_sum(N, p)\n    if iseven(N)\n        N -= 1\n    end\n    return sum([Binom(k, N, p) for k = N:-1:N/2])\nend\n\n\nfunction compute_analytical_accuracy(; N, p_GC_sig, p_GC_bkg, weight = [1, 1])\n    p_α_sig = 1 - p_GC_sig\n    p_α_bkg = 1 - p_GC_bkg\n    return mean([Binom_sum(N, p_α_sig), Binom_sum(N, p_α_bkg)], weights(weight))\nend\n\nfunction compute_analytical_accuracies(;\n    N_half,\n    p_GC_sig = 0.4,\n    p_GC_bkg = 0.5,\n    weight = [1, 1],\n)\n    bases_included = 1:N_half\n    analytical_accuracies = [\n        compute_analytical_accuracy(\n            N = i * 2,\n            p_GC_sig = p_GC_sig,\n            p_GC_bkg = p_GC_bkg,\n            weight = weight,\n        ) for i in bases_included\n    ]\n    return analytical_accuracies\nend\n\n#%%\n\nusing CairoMakie\nusing ColorSchemes\n\nN_half = 38\nx = 1:N_half\n\nanalytical_accuracies = compute_analytical_accuracies(;N_half=N_half)\n\ncolormap = [x for x in ColorSchemes.Set1_9.colors]\n\n#%%\n\nf = Figure()\nax = Axis(\n    f[1, 1],\n    title = \"Analytical accuracy\",\n    xlabel = \"# bases included (centered)\",\n    ylabel = \"Accuracy\",\n    # limits = (0.5, half_seq_length + 0.5, 0.634, 0.701),\n    # limits = (0.5, half_seq_length + 0.5, ylimits...),\n    xticks = 1:2:N_half,\n)\n\nscatterlines!(\n    ax,\n    x,\n    analytical_accuracies,\n    color = colormap[3],\n    markercolor = colormap[3],\n    label = \"Analytical\",\n)\n\naxislegend(position = :rb)\nf\n\n\n#%%\n\n\ncompute_analytical_accuracy(N=1, p_GC_sig = 0.4, p_GC_bkg = 0.5)\ncompute_analytical_accuracy(N=2, p_GC_sig = 0.4, p_GC_bkg = 0.5)\ncompute_analytical_accuracy(N=3, p_GC_sig = 0.4, p_GC_bkg = 0.5)\ncompute_analytical_accuracy(N=4, p_GC_sig = 0.4, p_GC_bkg = 0.5)\ncompute_analytical_accuracy(N=5, p_GC_sig = 0.4, p_GC_bkg = 0.5)\ncompute_analytical_accuracy(N=6, p_GC_sig = 0.4, p_GC_bkg = 0.5)\n\n", "meta": {"hexsha": "a2d59b1afd5a0491f446293358a3cb524be0e943", "size": 1900, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "analytical.jl", "max_stars_repo_name": "ChristianMichelsen/reference-free", "max_stars_repo_head_hexsha": "cc8c5d60d2597e81cf0922def0364ae685d72b8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analytical.jl", "max_issues_repo_name": "ChristianMichelsen/reference-free", "max_issues_repo_head_hexsha": "cc8c5d60d2597e81cf0922def0364ae685d72b8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analytical.jl", "max_forks_repo_name": "ChristianMichelsen/reference-free", "max_forks_repo_head_hexsha": "cc8c5d60d2597e81cf0922def0364ae685d72b8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5909090909, "max_line_length": 80, "alphanum_fraction": 0.6468421053, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.790126326594897}}
{"text": "\"\"\"\n    dualgraph(dist::Matrix{Float64}; method::Symbol = :inverse, σ::Float64 = 1.0)\n\nbuild the dual graph's weight matrix based on the given non-trivial eigenvector\nmetric.\n\n# Input Arguments\n- `dist::Matrix{Float64}`: eigenvector distance matrix\n- `method::Symbol`: default is by taking inverse of the distance between\n    eigenvectors. Ways to build the dual graph edge weights. Option: `:inverse`,\n    `:gaussian`.\n- `σ::Float64`: default is `1.0`. Gaussian variance parameter.\n\n# Output Argument\n- `G_star::GraphSig`: A `GraphSig` object containing the weight matrix of the\n    dual graph.\n\n\"\"\"\nfunction dualgraph(dist::Matrix{Float64}; method::Symbol = :inverse, σ::Float64 = 1.0)\n    N = Base.size(dist, 1)\n    W_star = zeros(N, N)\n    if method == :inverse\n        for i = 1:(N - 1), j = (i + 1):N\n            W_star[i, j] = 1 / dist[i, j]\n        end\n    elseif method == :gaussian\n        for i = 1:(N - 1), j = (i + 1):N\n            W_star[i, j] = exp(-dist[i, j] / σ^2)\n        end\n    else\n        error(\"method must be :inverse or :gaussian.\")\n    end\n    W_star = W_star + W_star'\n    G_star = GraphSig(sparse(W_star); name = \"dual graph\")\n    return G_star\nend\n", "meta": {"hexsha": "1292e423e0e577b5812368f4bacd2c3a8576be1e", "size": 1178, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dualgraph.jl", "max_stars_repo_name": "BoundaryValueProblems/MTSG.jl", "max_stars_repo_head_hexsha": "8cf8e2b3035876b5ceda45109b0847a60b581a7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-02T18:39:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-19T15:45:17.000Z", "max_issues_repo_path": "src/dualgraph.jl", "max_issues_repo_name": "haotian127/MultiscaleGraphSignalTransforms.jl", "max_issues_repo_head_hexsha": "85ba99e505283491ac69e979737bbb712b698a6e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2021-04-27T23:00:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-03T11:03:17.000Z", "max_forks_repo_path": "src/dualgraph.jl", "max_forks_repo_name": "haotian127/MultiscaleGraphSignalTransforms.jl", "max_forks_repo_head_hexsha": "85ba99e505283491ac69e979737bbb712b698a6e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-04-24T21:46:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T04:32:31.000Z", "avg_line_length": 31.8378378378, "max_line_length": 86, "alphanum_fraction": 0.6213921902, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802364, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7901204913142104}}
{"text": "using Random, Statistics\nRandom.seed!(1)\nallData = [rand(24), rand(15), rand(73)]\n\nxBarArray = mean.(allData)\nnArray = length.(allData)\nxBarTotal = mean(vcat(allData...))\nL = length(nArray)\n\nssBetween=sum([nArray[i]*(xBarArray[i] - xBarTotal)^2 for i in 1:L])\nssWithin=sum([sum([(ob - xBarArray[i])^2 for ob in allData[i]]) for i in 1:L])\nssTotal=sum([sum([(ob - xBarTotal)^2 for ob in allData[i]]) for i in 1:L])\n\nprintln(\"Sum of squares between groups: \", ssBetween)\nprintln(\"Sum of squares within groups: \", ssWithin)\nprintln(\"Sum of squares total: \", ssTotal)", "meta": {"hexsha": "86decf5227d46a6d104a7d392c4d4a4c64c50436", "size": 563, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "7_chapter/ssDecomposition.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "7_chapter/ssDecomposition.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "7_chapter/ssDecomposition.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 35.1875, "max_line_length": 78, "alphanum_fraction": 0.6909413854, "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9664104953173167, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7901125523492908}}
{"text": "import Random\nusing Plots\n\nprintln(\"Pool Testing Optimization\\nMonte Carlo Simulation\")\n\nmin_total = 1\nmax_total = 100\nmin_infected = 0\niterations = 100\n\nfunction run(total, infected, n_groups)\n\t# Trivial cases\n\t# No one is infected or testing everybody\n\tif infected==0 || n_groups==total\n\t\treturn n_groups\n\t# Only 1 group (there is only 1 grouping step)\n\telseif n_groups==1\n\t\treturn total+1\n\tend\n\n\tpeople = zeros(Bool, total)\n\tpeople[1:infected] .= true\n\tRandom.shuffle!(people)\n\n\tn_per_group = total ÷ n_groups\n\tn_plus_groups = total % n_groups\n\n\tgroups = zeros(UInt, n_groups)\n\n\tfor i in 1:infected\n\t\tj = 1+(Random.rand(UInt) % n_groups)\n\t\tgroups[j] += 1\n\tend\n\n\tinfected_groups = count(g -> g>0, groups)\n\n\ttests = n_groups\n\n\tfor (index, value) in enumerate(groups)\n\t\tif value>0\n\t\t\tif index<=n_plus_groups\n\t\t\t\ttests += n_per_group+1\n\t\t\telse\n\t\t\t\ttests += n_per_group\n\t\t\tend\n\t\tend\n\tend\n\n\t#=\n\tprintln(\"Total   \\t\", total)\n\tprintln(\"Infected\\t\", infected)\n\tprintln(\"People\\t\", people)\n\tprintln(\"People per group\\t\", n_per_group)\n\tprintln(\"# groups with 1 more\\t\", n_plus_groups)\n\tprintln(\"Infected per group\\t\", groups)\n\tprintln(\"Number of infected groups\\t\", infected_groups)\n\tprintln(\"Number of tests\\t\", tests)\n\t=#\n\n\treturn tests\nend\n\nn = binomial(max_total+2-min_infected, 2) - binomial(min_total+1-min_infected, 2)\nresults = Array{UInt, 2}(undef, n, 3)\n\ni = 1\nfor total in min_total:max_total\n\tfor infected in min_infected:total\n\t\tprintln(\"total \", total, \"  infected \", infected)\n\n\t\toptimum_n_groups = total\n\t\tprevious_sum_tests = iterations*total\n\n\t\tfor n_groups in 1:total\n\t\t\tsum_tests = 0\n\n\t\t\tfor iteration in 1:iterations\n\t\t\t\ttests = run(total, infected, n_groups)\n\t\t\t\tsum_tests += tests\n\t\t\t\t#println(\"total \", total, \"  infected \", infected, \"  n_groups \", n_groups, \"  iteration \", iteration, \"  tests \", tests)\n\t\t\tend\n\n\t\t\tif sum_tests<previous_sum_tests\n\t\t\t\toptimum_n_groups = n_groups\n\t\t\tend\n\t\tend\n\n\t\tglobal i\n\t\tresults[i, :] = [total, infected, optimum_n_groups]\n\t\ti += 1\n\tend\nend\n\nprintln(\"Calculated\")\n\nmatrix = zeros(Float32, (max_total+1-min_total, max_total+1-min_infected))\nfor k = 1:size(results, 1)\n\tlocal i = results[k, 1] + 1 - min_total\n\tlocal j = results[k, 2] + 1 - min_infected\n\tmatrix[i, j] = results[k, 3]/results[k, 1]\nend\n\n#println(\"results \", results)\n#println(\"matrix \", matrix)\n\nheatmap(min_total:max_total, min_infected:max_total, matrix',\n\t\txlabel=\"Total\", ylabel=\"Infected\",\n\t\ttitle=\"Optimal number of groups / Total\",\n\t\taspect_ratio=:equal,\n\t\tshow=true)\nprintln(\"Plotted\")\nreadline()\n\nprintln(\"End\")\n", "meta": {"hexsha": "654045c5837710d7aef91b391da1a0da817fa9bc", "size": 2538, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "old.jl", "max_stars_repo_name": "gonced8/pool-testing", "max_stars_repo_head_hexsha": "34432553d95708b7ccfada039bf24b16892349a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "old.jl", "max_issues_repo_name": "gonced8/pool-testing", "max_issues_repo_head_hexsha": "34432553d95708b7ccfada039bf24b16892349a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "old.jl", "max_forks_repo_name": "gonced8/pool-testing", "max_forks_repo_head_hexsha": "34432553d95708b7ccfada039bf24b16892349a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0695652174, "max_line_length": 125, "alphanum_fraction": 0.6993695823, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467158, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7900697546828797}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.2\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 0a5335e0-ab9e-11eb-0a85-139ff5cf0b1d\nmd\"# Chapter 02 from NNFS book\"\n\n# ╔═╡ 0c5d667f-0ea5-4d21-80ad-58d144470a73\nmd\"### A Single Neuron (4 inputs, 1 output)\"\n\n# ╔═╡ d85b097d-c7c7-439f-80ec-a1b75c696cb1\nmd\"\"\" \nfor **each input** we need **one weigth** and for **each output** we need **one bias**.\nSo, for this simple example with 1 neuron with 4 inputs we are gonna have:\n\n- **3** inputs\n- **3** weights\n- **1** bias.\n\"\"\"\n\n# ╔═╡ ef746509-f29b-42ae-b9ec-a2e18ad4b327\nbegin\n\tinputs = [1; 2; 3; 2.5]\n\tweights = [0.2; 0.8; -0.5; 1.0]\n\tbias = 2.0\n\n\tinputs'*weights + bias # or dot(inputs, weights) + bias\nend\n\n# ╔═╡ a3acafe8-6a4b-4438-84d9-16a00cb21997\nmd\"### A Layer of 03 Neurons (4 inputs, 3 outputs)\"\n\n# ╔═╡ 9fbc1e4c-52c0-4b99-92dc-4969b55f645d\nbegin\n\t#inputs = [1, 2, 3, 2.5]\n\tweights1 = [0.2, 0.8, -0.5, 1.0]\n\tweights2 = [0.5, -0.91, 0.26, -0.5]\n\tweights3 = [-0.26, -0.27, 0.17, 0.87]\n\tbias1 = 2.0\n\tbias2 = 3.0\n\tbias3 = 0.5\n\n\t[inputs'*weights1 + bias1,\n\tinputs'*weights2 + bias2,\n\tinputs'*weights3 + bias3]\nend\n\n# ╔═╡ 3613059e-501d-4cb0-bd73-8e42e6395e16\nmd\" with only one unique matrix of weights we use matrix multiplication from linear algebra\"\n\n# ╔═╡ 0e309e2a-59e8-4fce-819d-afeec8c21ca8\nbegin\n\tweights_array = [\n\t\t0.2    0.8  -0.5   1.0;\n\t\t0.5   -0.91  0.26 -0.5;\n\t\t-0.26 -0.27  0.17  0.87;\n\t]\n\tbias_vec = [2.0 3.0 0.5]\n\t\n\t(weights_array * inputs) .+ bias_vec\nend\n\n# ╔═╡ d27568ac-934c-4408-880d-4bd34ccead72\nmd\"### A Layer of Neurons with multiple batch of Data\"\n\n# ╔═╡ 91d6b3e6-5124-4963-b6c2-f2c65b67b045\nmd\"Now we are gonna need use transpose operation to match the right vectors in matrix multiplication\"\n\n# ╔═╡ 7ae39d13-e448-4c91-81be-d44a15f1a414\nbegin\n\tinputs_batch = [\n\t\t1.0 2.0 3.0 2.5\n\t\t2.0 5.0 -1.0 2.0\n\t\t-1.5 2.7 3.3 -0.8\n\t]\n\t\n\t(inputs_batch * weights_array') .+ bias_vec \nend\n\n# ╔═╡ Cell order:\n# ╟─0a5335e0-ab9e-11eb-0a85-139ff5cf0b1d\n# ╟─0c5d667f-0ea5-4d21-80ad-58d144470a73\n# ╟─d85b097d-c7c7-439f-80ec-a1b75c696cb1\n# ╠═ef746509-f29b-42ae-b9ec-a2e18ad4b327\n# ╟─a3acafe8-6a4b-4438-84d9-16a00cb21997\n# ╠═9fbc1e4c-52c0-4b99-92dc-4969b55f645d\n# ╟─3613059e-501d-4cb0-bd73-8e42e6395e16\n# ╠═0e309e2a-59e8-4fce-819d-afeec8c21ca8\n# ╟─d27568ac-934c-4408-880d-4bd34ccead72\n# ╟─91d6b3e6-5124-4963-b6c2-f2c65b67b045\n# ╠═7ae39d13-e448-4c91-81be-d44a15f1a414\n", "meta": {"hexsha": "2a09df7e4218aad466a413e6c640c615bd4b0700", "size": 2349, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapters/Chapter02_old.jl", "max_stars_repo_name": "AugustoCL/Neural_Network_From_Scratch_in_Julia", "max_stars_repo_head_hexsha": "33f0f479c2e935b179306418e860dfa4e7cec07b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-20T16:40:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T16:40:27.000Z", "max_issues_repo_path": "Chapters/Chapter02_old.jl", "max_issues_repo_name": "AugustoCL/Neural_Network_From_Scratch_in_Julia", "max_issues_repo_head_hexsha": "33f0f479c2e935b179306418e860dfa4e7cec07b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapters/Chapter02_old.jl", "max_forks_repo_name": "AugustoCL/Neural_Network_From_Scratch_in_Julia", "max_forks_repo_head_hexsha": "33f0f479c2e935b179306418e860dfa4e7cec07b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9893617021, "max_line_length": 101, "alphanum_fraction": 0.6764580673, "num_tokens": 1238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7900697530378935}}
{"text": "# function nint(x::Float64)\n#     return round(Int, x)\n# end\n\n# function geo_coordinate(x, y)\n#     PI = 3.141592\n    \n#     deg = nint(x)    \n#     m = x - deg\n#     latitude = PI * (deg + 5.0 * m / 3.0) / 180.0\n\n#     deg = nint(y)\n#     m = y - deg\n#     longitude = PI * (deg + 5.0 * m / 3.0) / 180.0 \n\n#     return latitude, longitude\n# end\n\n# function distance2D(xi, yi, xj, yj; dist=\"EUC_2D\")\n#     if dist == \"EUC_2D\"\n#         xd = xi - xj\n#         yd = yi - yj\n#         return nint(sqrt(xd*xd + yd*yd))\n#     elseif dist == \"MAN_2D\"\n#         xd = abs(xi - xj)\n#         yd = abs(yi - yj)\n#         return nint(xd + yd)\n#     elseif dist == \"MAX_2D\"\n#         xd = abs(xi - xj)\n#         yd = abs(yi - yj)\n#         return max(nint(xd), nint(yd))      \n#     elseif dist == \"GEO\"\n#         lat_i, long_i = geo_coordinate(xi, yi)\n#         lat_j, long_j = geo_coordinate(xj, yj)\n#         RRR = 6378.388\n#         q1 = cos(long_i - long_j)\n#         q2 = cos(lat_i - lat_j)\n#         q3 = cos(lat_i + lat_j)\n#         dij =  RRR * acos( 0.5*((1.0+q1)*q2 - (1.0-q1)*q3) ) + 1.0\n#         return floor(Int, dij) \n#     else\n#         error(\"Distance function $dist is not supported.\")\n#     end\n# end\n\n# function dist_matrix(x::Vector{Float64}, y::Vector{Float64}; dist=\"EUC_2D\")\n#     n_nodes = length(x)\n#     @assert length(x) == length(y)\n    \n#     M = Matrix{Int}(undef, n_nodes, n_nodes)\n\n#     for i in 1:n_nodes\n#         for j in i:n_nodes\n#             if i == j \n#                 M[i, j] = 0 \n#             else\n#                 M[i, j] = distance2D(x[i], y[i], x[j], y[j]; dist=dist)\n#                 M[j, i] = M[i, j]\n#             end\n#         end\n#     end\n#     return M\n# end", "meta": {"hexsha": "78bf9e7a169600612df3f403aa7692229ee9bc6f", "size": 1706, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dist.jl", "max_stars_repo_name": "chkwon/Concorde.jl", "max_stars_repo_head_hexsha": "7547b18ba18303a63753fd32115292ad47084b1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-11T01:49:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:12:09.000Z", "max_issues_repo_path": "src/dist.jl", "max_issues_repo_name": "chkwon/Concorde.jl", "max_issues_repo_head_hexsha": "7547b18ba18303a63753fd32115292ad47084b1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-02-25T04:58:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T23:40:54.000Z", "max_forks_repo_path": "src/dist.jl", "max_forks_repo_name": "chkwon/Concorde.jl", "max_forks_repo_head_hexsha": "7547b18ba18303a63753fd32115292ad47084b1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0793650794, "max_line_length": 77, "alphanum_fraction": 0.4613130129, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7900131154518496}}
{"text": "#' ---\n#' title: Geographical Clustering With Additional Constraint\n#' ---\n\n#' **Originally Contributed by**: Matthew Helm ([with help from Mathieu Tanneau on Julia Discourse](https://discourse.julialang.org/t/which-jump-jl-solver-for-this-problem/43350/17?u=mthelm85))\n\n#' The goal of this exercise is to cluster $n$ cities into $k$ groups, minimizing the total pairwise distance between cities \n#' *and* ensuring that the variance in the total populations of each group is relatively small. \n\n#' For this example, we'll use the 20 most populous cities in the United States.\n\nusing Cbc\nusing DataFrames\nusing Distances\nusing JuMP\nusing LinearAlgebra\n\ncities = DataFrame(\n    city=[ \"New York, NY\", \"Los Angeles, CA\", \"Chicago, IL\", \"Houston, TX\", \"Philadelphia, PA\", \"Phoenix, AZ\", \"San Antonio, TX\", \"San Diego, CA\", \"Dallas, TX\", \"San Jose, CA\", \"Austin, TX\", \"Indianapolis, IN\", \"Jacksonville, FL\", \"San Francisco, CA\", \"Columbus, OH\", \"Charlotte, NC\", \"Fort Worth, TX\", \"Detroit, MI\", \"El Paso, TX\", \"Memphis, TN\"],\n    population=[8405837,3884307,2718782,2195914,1553165,1513367,1409019,1355896,1257676,998537,885400,843393,842583,837442,822553,792862,792727,688701,674433,653450],\n    lat=[40.7127,34.0522,41.8781,29.7604,39.9525,33.4483,29.4241,32.7157,32.7766,37.3382,30.2671,39.7684,30.3321,37.7749,39.9611,35.2270,32.7554,42.3314,31.7775,35.1495],\n    lon=[-74.0059,-118.2436,-87.6297,-95.3698,-75.1652,-112.0740,-98.4936,-117.1610,-96.7969,-121.8863,-97.7430,-86.1580,-81.6556,-122.4194,-82.9987,-80.8431,-97.3307,-83.0457,-106.4424,-90.0489])\n\n#' ### Model Specifics\n\n#' We will cluster these 20 cities into 3 different groups and we will assume that the ideal or target population $P$ for a\n#' group is simply the total population of the 20 cities divided by 3:\n\nn = size(cities,1)\nk = 3\nP = sum(cities.population) / k\n\n#' ### Obtaining the distances between each city\n\n#' Let's leverage the *Distances.jl* package to compute the pairwise Haversine distance between each of the cities in our data\n#' set and store the result in a variable we'll call `dm`:\n\ndm = Distances.pairwise(Haversine(6372.8), Matrix(cities[:, [3,4]])', dims=2)\n\n#' Our distance matrix is symmetric so we'll convert it to a `LowerTriangular` matrix so that we can better interpret the\n#' objective value of our model (if we don't do this the total distance will be doubled):\n\ndm = LowerTriangular(dm)\n\n#' ### Build the model\n#' Now that we have the basics taken  care of, we can set up our model, create decision variables, add constraints, and then\n#' solve.\n\n#' First, we'll set up a model that leverages the [Cbc](https://github.com/coin-or/Cbc) solver. Next, we'll set up a binary\n#' variable $x_{i,k}$ that takes the value $1$ if city $i$ is in group $k$ and $0$ otherwise. Each city must be in a group, so\n#' we'll add the constraint $\\sum_kx_{i,k} = 1$ for every $i$.\n\nmodel = Model(Cbc.Optimizer)\n\n@variable(model, x[1:n, 1:k], Bin)\n\nfor i in 1:n\n    @constraint(model, sum(x[i,:]) == 1)\nend\n\n#'The total population of a group $k$ is $Q_k = \\sum_ix_{i,k}q_i$ where $q_i$ is simply the $i$th value from the `population`\n#' column in our `cities` DataFrame. Let's add constraints so that $\\alpha \\leq (Q_k - P) \\leq \\beta$. We'll set $\\alpha$\n#' equal to -2,500,000 and $\\beta$ equal to 2,500,000. By adjusting these thresholds you'll find that there is a tradeoff\n#' between having relatively even populations between groups and having geographically close cities within each group. In\n#' other words, the larger the absolute values of $\\alpha$ and $\\beta$, the closer together the cities in a group will be but\n#' the variance between the group populations will be higher.\n\nα = -2_500_000\nβ = 2_500_000\n\nfor i in 1:k\n    @constraint(model, (x' * cities.population)[i] - P <= β)\n    @constraint(model, (x' * cities.population)[i] - P >= α)\nend\n\n#' Now we need to add one last binary variable $z_{i,j}$ to our model that we'll use to compute the total distance between the \n#' cities in our groups, defined as  $\\sum_{i,j}d_{i,j}z_{i,j}$. Variable $z_{i,j}$ will equal $1$ if cities $i$ and $j$ are \n#' in the same group, and $0$ if they are not in the same group.\n\n#' To ensure that $z_{i,j} = 1$ if and only if cities $i$ and $j$ are in the same group, we add the constraints $z_{i,j} \\geq \n#' x_{i,k} + x_{j,k} - 1$ for every pair $i,j$ and every $k$:\n\n@variable(model, z[1:n,1:n], Bin)\n\nfor k in 1:k, i in 1:n, j in 1:n\n    @constraint(model, z[i,j] >= x[i,k] + x[j,k] - 1)\nend\n\n#' We can now add an objective to our model which will simply be to minimize the dot product of $z$ and our distance matrix,\n#' `dm`. We can then call `optimize!` and review the results.\n\n@objective(model, Min, dot(z,dm));\n\noptimize!(model)\n\n#' ### Reviewing the Results\n\n#' Now that we have results, we can add a column to our `cities` DataFrame for the group and then loop through our $x$\n#' variable to assign each city to its group. Once we have that, we can look at the total population for each group and also\n#' plot the cities and their groups to verify visually that they are grouped by geographic proximity.\n\ncities.group = zeros(n)\n\nfor i in 1:n, j in 1:k\n    if round(value.(x)[i,j]) == 1.0\n        cities.group[i] = j\n    end\nend\n\nfor group in groupby(cities, :group)\n    @show group\n    println(\"\")\n    @show sum(group.population)\n    println(\"\")\nend\n\n#' The populations of each group are fairly even and we can see from the plot below that the groupings look good in terms of\n#' geographic proximity:\n\n#' <img src=\"img/geo_clusters.png\" style=\"width: auto; height: auto\" alt=\"Geographic Clusters\">\n", "meta": {"hexsha": "af470cc29d43483a41b66d80a55dd2ffdec925fc", "size": 5589, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/modelling/geographic_clustering.jl", "max_stars_repo_name": "ferrolho/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "3e50e6f12d0542fd598d1cdbe0c602a6ae5ea271", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 75, "max_stars_repo_stars_event_min_datetime": "2020-06-15T13:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T12:58:48.000Z", "max_issues_repo_path": "script/modelling/geographic_clustering.jl", "max_issues_repo_name": "ferrolho/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "3e50e6f12d0542fd598d1cdbe0c602a6ae5ea271", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-05-27T05:36:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T09:52:29.000Z", "max_forks_repo_path": "script/modelling/geographic_clustering.jl", "max_forks_repo_name": "mthelm85/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "b2285a74d05dc0c0e99df2ac999277c34e670afd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-10-09T09:32:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T17:41:21.000Z", "avg_line_length": 46.1900826446, "max_line_length": 348, "alphanum_fraction": 0.7004830918, "num_tokens": 1715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7900131116785101}}
{"text": "\"\"\"\n    id(k::Int64) -> SparseMatrixCSC{ℤ₂, Int64}\n\nGenerate and return a `k × k` identity-matrix.\n\"\"\"\nfunction id(k::Int64)::SparseMatrixCSC{ℤ₂, Int64}\n    I = sparse(zeros(ℤ₂, k, k))\n    for i = 1:k\n        I[i,i] = one(ℤ₂)\n    end\n    return I\nend\n\n\n\n\"\"\"\n    anti_id(k::Int64) -> SparseMatrixCSC{ℤ₂, Int64}\n\nGenerate and return a `k × k` anti-identity-matrix.\n\"\"\"\nfunction anti_id(k::Int64)::SparseMatrixCSC{ℤ₂, Int64}\n    antiid = ones(ℤ₂, k, k)\n    for i = 1:k\n        antiid[i,i] = zero(ℤ₂)\n    end\n    return sparse(antiid)\nend", "meta": {"hexsha": "4c3e436979cb16e9709c2d0dfc041dad21da9aee", "size": 534, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/anti-identity.jl", "max_stars_repo_name": "Fhoeddinghaus/AntiIdClosedGroup.jl", "max_stars_repo_head_hexsha": "47576926259d8fc27128fab8b9c0b03d70b653c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/anti-identity.jl", "max_issues_repo_name": "Fhoeddinghaus/AntiIdClosedGroup.jl", "max_issues_repo_head_hexsha": "47576926259d8fc27128fab8b9c0b03d70b653c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/anti-identity.jl", "max_forks_repo_name": "Fhoeddinghaus/AntiIdClosedGroup.jl", "max_forks_repo_head_hexsha": "47576926259d8fc27128fab8b9c0b03d70b653c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7777777778, "max_line_length": 54, "alphanum_fraction": 0.5973782772, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7900131097918403}}
{"text": "using Images, Colors\r\n\r\nfunction filter_sobel(image::AbstractMatrix, direction::String=\"-\")\r\n\r\n  tipo = typeof(image)\r\n\r\n  try\r\n    image = convert(Array{Float32}, image)\r\n  catch er\r\n    error(er,\"\\nProblem converting the image into an array.\\n\")\r\n  end\r\n\r\n  if direction==\"-\"\r\n    mask_x = [-1 0 1; -2 0 2; -1 0 1];\r\n    mask_y = [1 2 1; 0 0 0; -1 -2 -1];\r\n\r\n    Gx = imfilter(image,centered(mask_x));\r\n    Gy = imfilter(image,centered(mask_y));\r\n\r\n    d1 = size(Gx);\r\n    d2 = size(Gy);\r\n\r\n    if d1!=d2\r\n      error(\"Problem during the function's execution.\")\r\n    end\r\n\r\n    img_final = zeros(d1[1],d1[2])\r\n\r\n    for i = 1:d1[1]\r\n      for j = 1:d1[2]\r\n\r\n        img_final[i,j] = sqrt((Gx[i,j]^2)+(Gy[i,j]^2))\r\n\r\n        if img_final[i,j]>1.0\r\n          img_final[i,j]=1.0;\r\n        elseif img_final[i,j]<0.0\r\n          img_final[i,j]=0.0;\r\n        end\r\n\r\n      end\r\n    end\r\nelseif direction==\"W->E\"\r\n    mask = [1 2 1; 0 0 0; -1 -2 -1];\r\n    img_final = imfilter(image,centered(mask));\r\n    d1 = size(img_final);\r\n    for i = 1:d1[1]\r\n      for j = 1:d1[2]\r\n        if img_final[i,j]>1.0\r\n          img_final[i,j]=1.0;\r\n        elseif img_final[i,j]<0.0\r\n          img_final[i,j]=0.0;\r\n        end\r\n      end\r\n    end\r\nelseif direction==\"N->S\"\r\n    mask = [-1 0 1; -2 0 2; -1 0 1];\r\n    img_final = imfilter(image,centered(mask));\r\n    d1 = size(img_final);\r\n    for i = 1:d1[1]\r\n      for j = 1:d1[2]\r\n        if img_final[i,j]>1.0\r\n          img_final[i,j]=1.0;\r\n        elseif img_final[i,j]<0.0\r\n          img_final[i,j]=0.0;\r\n        end\r\n      end\r\n    end\r\n  elseif direction==\"NW->SE\"\r\n    mask = [0 1 2; -1 0 1; -2 -1 0];\r\n    img_final = imfilter(image,centered(mask));\r\n    d1 = size(img_final);\r\n    for i = 1:d1[1]\r\n      for j = 1:d1[2]\r\n        if img_final[i,j]>1.0\r\n          img_final[i,j]=1.0;\r\n        elseif img_final[i,j]<0.0\r\n          img_final[i,j]=0.0;\r\n        end\r\n      end\r\n    end\r\n  elseif direction==\"SW->NE\"\r\n    mask = [-2 -1 0; -1 0 1; 0 1 2];\r\n    img_final = imfilter(image,centered(mask));\r\n    d1 = size(img_final);\r\n    for i = 1:d1[1]\r\n      for j = 1:d1[2]\r\n        if img_final[i,j]>1.0\r\n          img_final[i,j]=1.0;\r\n        elseif img_final[i,j]<0.0\r\n          img_final[i,j]=0.0;\r\n        end\r\n      end\r\n    end\r\n  else\r\n    error(\"The position value must be an Text variable. Available values are: W->E, N->S, NW->SE, and SW->NE. This is not a mandatory field.\\n\");\r\n  end\r\n\r\n  img_final = convert(tipo, img_final)\r\n  return(img_final)\r\nend\r\n", "meta": {"hexsha": "73f7cc4d6691bddb0d43cedf51563a6f01f28bea", "size": 2499, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/filter_sobel.jl", "max_stars_repo_name": "menimato/IMGedu.jl", "max_stars_repo_head_hexsha": "71c753d214afe2dbc7e1afb832df6e3ea6ad6289", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-19T22:53:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-19T22:53:02.000Z", "max_issues_repo_path": "src/filter_sobel.jl", "max_issues_repo_name": "menimato/IMGedu.jl", "max_issues_repo_head_hexsha": "71c753d214afe2dbc7e1afb832df6e3ea6ad6289", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/filter_sobel.jl", "max_forks_repo_name": "menimato/IMGedu.jl", "max_forks_repo_head_hexsha": "71c753d214afe2dbc7e1afb832df6e3ea6ad6289", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7425742574, "max_line_length": 146, "alphanum_fraction": 0.5118047219, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7900130976541434}}
{"text": "module Quadratic\n\nusing STMO: Tracker, notrack, PathTrack, trace\n\nexport fquad, plot_quadratic, solve_quadratic, quadratic_ls, gradient_descent\n\nusing LinearAlgebra, Plots\n\n\"\"\"Compute a quadratic function.\"\"\"\nfquad(x::Vector, P::Matrix, q::Vector, r::Real=0.0) = 0.5x' * P * x + q' * x + r\n\n\"\"\"Plot a 1-D quadratic function.\"\"\"\nfunction plot_quadratic(p::Real, q::Real, r::Real, (xl, xu), stepsize=0.1; kwargs...)\n    return plot(x -> p*x^2 + q*x+r, xl:stepsize:xu, xlabel=\"\\$x\\$\"; kwargs...)\nend\n\n\"\"\"Plot a 2-D quadratic function.\"\"\"\nfunction plot_quadratic(P::AbstractMatrix, q::AbstractVector, r::Real,\n                            (x1l, x1u), (x2l, x2u), stepsize=0.1; kwargs...)\n    fun = (x1, x2) -> [x1,x2] |> x -> 0.5x' * P * x + q' * x + r\n    return contour(x1l:stepsize:x1u, x2l:stepsize:x2u, fun, xlabel=\"\\$x_1\\$\",\n                                            ylabel=\"\\$x_2\\$\"; kwargs...)\nend\n\n\n\"\"\"\n    solve_quadratic(p::Real, q::Real[, r::Real=0.0])\n\nFinds the minimizer of an 1-D quadratic system. If the quadratic term `p` is\nnegative, the function raises an error.\n\nInputs:\n    - `p`, `q`, `r`: the terms of the 1-D quadratic system\n\nOutput:\n    - xstar: the minimizer, a number\n\"\"\"\nfunction solve_quadratic(p::Real, q::Real, r::Real=0.0)\n    @assert p > 0.0\n    return - q / p\nend\n\n\n\"\"\"\n    solve_quadratic(P::AbstractMatrix, q::AbstractVector, r::Real=0)\n\nFinds the minimizer of an N-D quadratic system.\nP is assumed to be a symmetric positive-definite matrix.\n\nInputs:\n    - P, q, r: the terms of the nD quadratic system\n\nOutput:\n    - xstar: the minimizer, an (n x 1) vector\n\"\"\"\nfunction solve_quadratic(P::AbstractMatrix, q::AbstractVector, r::Real=0.0)\n    return - P \\ q\nend\n\n\n\"\"\"\n    quadratic_ls(P::AbstractMatrix, q::AbstractVector, Δx::AbstractVector,\n                                    x::AbstractVector)\n\nFind the exact step size that minimized a quadratic system in\na given point x for a given search direction Dx\n\nInputs:\n    - P, q: the terms of the nD quadratic system\n    - x: starting point\n    - Δx: search direction\n\nOutput:\n    - t: optimal step size\n\"\"\"\nfunction quadratic_ls(P::AbstractMatrix, q::AbstractVector, Δx::AbstractVector,\n                                    x::AbstractVector)\n    t = solve_quadratic(Δx' * P * Δx, Δx' * P * x + Δx ⋅ q)\n    return t\nend\n\n\"\"\"\n    gradient_descent(P::AbstractArray, q::AbstractVector,\n            x₀::AbstractVector; β::Real=0.0, ϵ::Real=1e-6,\n            tracker::Tracker=notrack)\n\nComputes the minimizes of a quadratic system using gradient descent. Optionally\nprovide momentum.\n\nInputs:\n    - P, q: the terms of the nD quadratic system\n    - x₀: starting point\n    - ϵ: convergence parameter\n    - β: momentum parameter\n    - tracker: object of the type `Tracker` to save the steps\n\nOutputs:\n    - xstar: the found minimum\n\"\"\"\nfunction gradient_descent(P::AbstractArray, q::AbstractVector,\n            x₀::AbstractVector; β::Real=0.0, ϵ::Real=1e-6,\n            tracker::Tracker=notrack)\n    @assert 0 ≤ β < 1\n    x = x₀  # initial value\n    Δx = zero(x)  # pre-allocate a vector for the gradient\n    while true\n        Δx .= (1.0 - β) * (- P * x .- q) .+ β *  Δx\n        if norm(Δx) < ϵ\n            break\n        end\n        # determine stepsize using exact line search\n        t = quadratic_ls(P, q, Δx, x)\n        # perform step\n        x .+= t * Δx\n        trace(tracker, x)  # saves the steps\n    end\n    return x\nend\n\n\n# SIGNAL RECOVERY\n# ---------------\n\nmodule SignalRecovery\nusing LinearAlgebra: I\n\nsignalfun(x, n) = 3sin(x * 2 * pi / n) +\n            2cos(x * 4 * pi / n) +\n            sin(x * 4 * pi / n) + 0.8 * cos(x * 12 * pi / n)\n\n\"\"\"\n    generate_noisy_measurements(m, n; σ=1.0)\n\nGenerate noisy measurements according to some function f\n\nInputs:\n    - m : number of observations\n    - n : dim of x\n    - σ : normally distributed noise (default = 1)\n\nOutput:\n    - y : vector of noisy measurements\n    - ind : vector of indices\n\"\"\"\nfunction generate_noisy_measurements(m, n; σ=1.0)\n    ind = rand(1:n, m)\n    y = signalfun.(ind, n) .+ randn(m) * σ\n    return y, ind\nend\n\n\n\"\"\"\n    make_connection_matrix(n, γ=100)\n\nGenerates the kernel matrix and the inverse kernel matrix\n\nUses γ as a characteristic length scale of the radial basis kernel,\nassumes periodic boundaries.\n\nInputs:\n    - n : number of points\n    - γ : length scale\n\nOutput:\n    - K\n    - Kinv\n\"\"\"\nfunction make_connection_matrix(n, γ=100)\n    # cyclic distance\n    d(i, j) = min((i-j)^2, ((i-n)-j)^2, ((j-n)-i)^2)\n    # distance matrix\n    D = [d(i, j) for i in 1:n, j in 1:n]\n    # kernel matrix\n    K = exp.(-D / γ^2) + 1e-2I\n    return K, inv(K)\nend\n\n\"\"\"\n    make_bookkeeping(I, n)\n\nConstructs the bookkeeping matrix R\n\nInputs:\n    - ind : the indices of the measurements\n    - n : dimensionality of signal vector\n\nOutput:\n    - R : m x n bookkeeping matrix\n\"\"\"\nfunction make_bookkeeping(ind, n)\n    m = length(ind)\n    R = zeros(Int, m, n)\n    for (i, j) in enumerate(ind)\n        R[i,j] = 1\n    end\n    return R\nend\n\nexport generate_noisy_measurements, make_connection_matrix, make_bookkeeping, signalfun\n\nend # module SignalRecovery\n\nexport SignalRecovery\n\nend  # module Quadratic\n", "meta": {"hexsha": "b18243c27a801e181e4bec4e8b6470b41d55f4ff", "size": 5151, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/quadratic.jl", "max_stars_repo_name": "f6v/STMO", "max_stars_repo_head_hexsha": "cbbb8083caeaef361fbcaa7e60c687ff6f0db17e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2020-01-28T15:43:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T07:35:52.000Z", "max_issues_repo_path": "src/quadratic.jl", "max_issues_repo_name": "f6v/STMO", "max_issues_repo_head_hexsha": "cbbb8083caeaef361fbcaa7e60c687ff6f0db17e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-02-04T16:30:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-30T11:24:57.000Z", "max_forks_repo_path": "src/quadratic.jl", "max_forks_repo_name": "f6v/STMO", "max_forks_repo_head_hexsha": "cbbb8083caeaef361fbcaa7e60c687ff6f0db17e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2020-02-09T15:13:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T18:32:40.000Z", "avg_line_length": 25.0048543689, "max_line_length": 87, "alphanum_fraction": 0.6169675791, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7899975613531787}}
{"text": "using Distributions\nusing Optim\nusing HTTP\nusing GLM\nusing LinearAlgebra\nusing Random\nusing Statistics\nusing DataFrames\nusing CSV\nusing FreqTables\n\n #:::::::::::::::::::::::::::::::::::::::::::::::::::\n # question 1\n #:::::::::::::::::::::::::::::::::::::::::::::::::::\n \nurl = \"https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2021/master/ProblemSets/PS4-mixture/nlsw88t.csv\"\ndf = CSV.read(HTTP.get(url).body,DataFrame)\nX = [df.age df.white df.collgrad]\nZ = hcat(df.elnwage1, df.elnwage2, df.elnwage3, df.elnwage4,\ndf.elnwage5, df.elnwage6, df.elnwage7, df.elnwage8)\ny = df.occ_code\n\n\nfunction mlogit_with_Z(theta, X, Z, y)\n        \n    alpha = theta[1:end-1]\n    gamma = theta[end]\n    K = size(X,2)\n    J = length(unique(y))\n    N = length(y)\n    bigY = zeros(N,J)\n    for j=1:J\n        bigY[:,j] = y.==j\n    end\n    bigAlpha = [reshape(alpha,K,J-1) zeros(K)]\n        \n    T = promote_type(eltype(X),eltype(theta))\n    num   = zeros(T,N,J)\n    dem   = zeros(T,N)\n    for j=1:J\n        num[:,j] = exp.(X*bigAlpha[:,j] .+ (Z[:,j] .- Z[:,J])*gamma)\n        dem .+= num[:,j]\n    end\n        \n    P = num./repeat(dem,1,J)\n        \n    loglike = -sum( bigY.*log.(P) )\n        \n    return loglike\nend\nstartvals = [2*rand(7*size(X,2)).-1; .1]\ntd = TwiceDifferentiable(theta -> mlogit_with_Z(theta, X, Z, y), startvals; autodiff = :forward)\n# run the optimizer\ntheta_hat_optim_ad = optimize(td, startvals, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\ntheta_hat_mle_ad = theta_hat_optim_ad.minimizer\n# evaluate the Hessian at the estimates\nH  = Optim.hessian!(td, theta_hat_mle_ad)\ntheta_hat_mle_ad_se = sqrt.(diag(inv(H)))\nprintln([theta_hat_mle_ad theta_hat_mle_ad_se]) # these standard errors match Stata\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 2\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n\n#Yes. Estimated gamma in PS3 is -0.09419383447879262. Yet gamma/100 is the change in utility with a 1% increase in expected wage.\n#It should not be negative. Here I got a postitive number(1.3074804109794527) so it is more reasonable.\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 3\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n\n#(a)\ninclude(\"lgwt.jl\") # make sure the function gets read in\n# define distribution\nd = Normal(0,1) # mean=0, standard deviation=1\n# get quadrature nodes and weights for 7 grid points\nnodes, weights = lgwt(7,-4,4)\n# now compute the integral over the density and verify it\nprintln(sum(weights.*pdf.(d,nodes)))\n# now compute the expectation and verify it\nprintln(sum(weights.*nodes.*pdf.(d,nodes)))\n\n\n\n#(b)\n#(1)\nd = Normal(0,2) \nnodes, weights = lgwt(7,-5,5)\nprintln(sum(weights.*(nodes.^2).*pdf.(d,nodes)))\n#(2)\nd = Normal(0,2) \nnodes, weights = lgwt(10,-5,5)\nprintln(sum(weights.*(nodes.^2).*pdf.(d,nodes)))\n#(3)\n#As the number of quadrature points increase, the quadrature approximates closer to the true value.\n\n#(c)\n#(1)\nd = Normal(0,2) \na = -5*2\nb = 5*2\nz = Uniform(a,b)\nx = rand(z,1000000)\nprintln((b-a)*mean((x.^2).*pdf.(d,x)))\n#(2)\nprintln((b-a)*mean(x.*pdf.(d,x)))\n#(3)\nprintln((b-a)*mean(pdf.(d,x)))\n#(4)\nx = rand(z,1000)\nprintln((b-a)*mean((x.^2).*pdf.(d,x)))\nprintln((b-a)*mean(x.*pdf.(d,x)))\nprintln((b-a)*mean(pdf.(d,x)))\n#when D = 1000000, the simulated integral approximates the true value better than that when D = 1000\n\n\n\n\nfunction mixed_logit_normal(theta, X, Z, y)\n        \n    alpha = theta[1:end-2]\n    mu_gamma = theta[end-1]\n    sigma_gamma = theta[end]\n    K = size(X,2)\n    J = length(unique(y))\n    N = length(y)\n    bigY = zeros(N,J)\n    for j=1:J\n        bigY[:,j] = y.==j\n    end\n    bigAlpha = [reshape(alpha,K,J-1) zeros(K)]\n        \n    T = promote_type(eltype(X),eltype(theta))\n    num   = zeros(T,N,J)\n    dem   = zeros(T,N)\n    d = Normal(mu_gamma,sigma_gamma) \n    gammas, weights = lgwt(10,-4,4)\n    M = size(gammas,1)\n    F = ones(N,M)\n    for i =1:M\n        for j=1:J\n            num[:,j] = exp.(X*bigAlpha[:,j] .+ (Z[:,j] .- Z[:,J]).*gammas[i])\n            dem .+= num[:,j]\n        end\n        P = (num./repeat(dem,1,J))\n        \n        for j=1:J\n            P[:,j]=P[:,j].^bigY[:,j]\n            F[:,i].*=P[:,j]\n        end\n    end          \n        \n    loglike = -sum([log(sum(weights.*F[i,:].*pdf.(d,gammas))) for i = 1:N])\n        \n    return loglike\nend\n\n\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 4\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n\n\nstartvals = [2*rand(7*size(X,2)).-1; 0; 1]\nobj = optimize(alpha->mixed_logit_normal(alpha, X, Z, y), startvals, LBFGS(), Optim.Options(g_tol=1e-5, iterations=100_000, show_trace=true, show_every=50))\nbeta = obj.minimizer[1:end-2]\nmu_gamma = obj.minimizer[end-1]\nsigma_gamma = obj.minimizer[end]\nprintln('beta is ',beta)\nprintln('mu_gamma is ',mu_gamma)\nprintln('sigma_gamma is ', sigma_gamma)\n\n\n\n#I also tried this code yet MethodError: no method matching Float64(::ForwardDiff.Dual{ForwardDiff.Tag{var\"#7#8\", Float64}, Float64, 12})\n# startvals = [2*rand(7*size(X,2)).-1; 0; 1]\n# td = TwiceDifferentiable(theta -> mixed_logit_normal(theta, X, Z, y), startvals; autodiff = :forward)\n# theta_hat_optim_ad = optimize(td, startvals, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100000, show_trace=true, show_every=50))\n# theta_hat_mle_ad = theta_hat_optim_ad.minimizer\n# H  = Optim.hessian!(td, theta_hat_mle_ad)\n# theta_hat_mle_ad_se = sqrt.(diag(inv(H)))\n# println([theta_hat_mle_ad theta_hat_mle_ad_se]) # these standard errors match Stata\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 5\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n\n\nfunction mixed_logit_normal2(theta, X, Z, y)\n        \n    alpha = theta[1:end-2]\n    mu_gamma = theta[end-1]\n    sigma_gamma = theta[end]\n    K = size(X,2)\n    J = length(unique(y))\n    N = length(y)\n    bigY = zeros(N,J)\n    for j=1:J\n        bigY[:,j] = y.==j\n    end\n    bigAlpha = [reshape(alpha,K,J-1) zeros(K)]\n        \n    T = promote_type(eltype(X),eltype(theta))\n    num   = zeros(T,N,J)\n    dem   = zeros(T,N)\n    d = Normal(mu_gamma,sigma_gamma) \n    gammas, weights = lgwt(10,-4,4)\n    M = size(gammas,1)\n    F = ones(N,M)\n    for i =1:M\n        for j=1:J\n            num[:,j] = exp.(X*bigAlpha[:,j] .+ (Z[:,j] .- Z[:,J]).*gammas[i])\n            dem .+= num[:,j]\n        end\n        P = (num./repeat(dem,1,J))\n        \n        for j=1:J\n            P[:,j]=P[:,j].^bigY[:,j]\n            F[:,i].*=P[:,j]\n        end\n    end     \n    \n    a = -5*sigma_gamma \n    b = 5*sigma_gamma \n    z = Uniform(a,b)\n    x = rand(z,1000000)\n    loglike = -sum([log((b-a)*mean(F[i,:].*pdf.(d,gammas))) for i = 1:N])\n        \n    return loglike\nend\n\nstartvals = [2*rand(7*size(X,2)).-1; 0; 1]\nobj = optimize(alpha->mixed_logit_normal2(alpha, X, Z, y), startvals, LBFGS(), Optim.Options(g_tol=1e-5, iterations=100_000, show_trace=true, show_every=50))\nbeta = obj.minimizer[1:end-2]\nmu_gamma = obj.minimizer[end-1]\nsigma_gamma = obj.minimizer[end]\nprintln('beta is ',beta)\nprintln('mu_gamma is ',mu_gamma)\nprintln('sigma_gamma is ', sigma_gamma)\n\n\n", "meta": {"hexsha": "64083127161116a49733b2127caeca84b22a963f", "size": 7060, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS4-mixture/PS4_ping.jl", "max_stars_repo_name": "babymetal287/fall-2021", "max_stars_repo_head_hexsha": "804f7fec898a0fccd018c8bc5d520d8f9156d62a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSets/PS4-mixture/PS4_ping.jl", "max_issues_repo_name": "babymetal287/fall-2021", "max_issues_repo_head_hexsha": "804f7fec898a0fccd018c8bc5d520d8f9156d62a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS4-mixture/PS4_ping.jl", "max_forks_repo_name": "babymetal287/fall-2021", "max_forks_repo_head_hexsha": "804f7fec898a0fccd018c8bc5d520d8f9156d62a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0534979424, "max_line_length": 157, "alphanum_fraction": 0.5703966006, "num_tokens": 2277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.789997554393576}}
{"text": "# utilitaries\nusing LinearAlgebra\n\ninclude(\"quadrature.jl\")\n# include(\"connectique.jl\")\n\n@inline function mod_wrap(x, a)\n    #= return the index x modulo a =#\n    return mod(x-1, a) + 1\nend\n\nfunction polygonArea(vtx)\n    area = 0.\n    N = size(vtx, 2)\n    for i=1:N\n        j = mod_wrap(i+1, N)\n        area += vtx[1, i]*vtx[2, j] - vtx[2, i]*vtx[1, j]\n    end\n    return 0.5*abs(area)\nend\n\nfunction polygonDiameter(vtx)\n    diameter = 0.\n    N = size(vtx, 2)\n    for i=1:(N-1)\n        for j=(i+1):N\n            diameter = max(diameter, norm(vtx[:, i] - vtx[:, j]))\n        end\n    end\n    return diameter\nend\n\nfunction polygonCentroid(vtx)\n    N        = size(vtx, 2)\n    centroid = zeros(Float64, 2)\n    #\n    den = 0.\n    for i=1:N\n        j = mod_wrap(i+1, N)\n        w = (vtx[1, i]*vtx[2, j] - vtx[1, j]*vtx[2, i])\n        centroid[1] += (vtx[1, i] + vtx[1, j])*w\n        centroid[2] += (vtx[2, i] + vtx[2, j])*w\n        den += w\n    end\n    #\n    return centroid/(3 * den)\nend\n\n# INTEGRATION OF MULTIPLE FUNCTIONS OVER A POLYGON\nfunction integratePolygon(pverts::Array{Float64,2}, xE::Array{Float64,1},\n    ref::Quadrature2d, fs::Array{Function, 1})\n    #=\n    Integration of all functions in fs over a polygon by subdividing it\n    into triangles\n    =#\n    n   = size(pverts, 2)\n    nf  = length(fs)\n    res = zeros(Float64, nf)\n    for i=1:n\n        ip = mod_wrap(i+1, n)\n        @inbounds quadT = quadGL2d(ref, [pverts[1,i] pverts[1,ip] xE[1];\n        pverts[2,i] pverts[2,ip] xE[2]])\n        for f = 1:nf\n            @inbounds res[f] += integrate(quadT, fs[f])\n        end\n    end\n    return  res\nend\n\n\nfunction integratePolygon(pverts::Array{Float64,2}, xE::Array{Float64,1},\n    ref::Quadrature2d, fs::Function)\n    #= Same as before, but for a single function fs =#\n    n   = size(pverts, 2)\n    res = 0.\n    for i=1:n\n        ip = mod_wrap(i+1, n)\n        @inbounds quadT = quadGL2d(ref, [pverts[1,i] pverts[1,ip] xE[1];\n        pverts[2,i] pverts[2,ip] xE[2]])\n        res += integrate(quadT, fs)\n    end\n    return  res\nend\n", "meta": {"hexsha": "8e92f58af9ed4b1d622332c9f30b19940bbd68cc", "size": 2041, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "utils.jl", "max_stars_repo_name": "marcbakry/vem_acoustics", "max_stars_repo_head_hexsha": "c41da8c1c3027337511fd0a394dd3782cfe79d88", "max_stars_repo_licenses": ["X11", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils.jl", "max_issues_repo_name": "marcbakry/vem_acoustics", "max_issues_repo_head_hexsha": "c41da8c1c3027337511fd0a394dd3782cfe79d88", "max_issues_repo_licenses": ["X11", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils.jl", "max_forks_repo_name": "marcbakry/vem_acoustics", "max_forks_repo_head_hexsha": "c41da8c1c3027337511fd0a394dd3782cfe79d88", "max_forks_repo_licenses": ["X11", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2976190476, "max_line_length": 73, "alphanum_fraction": 0.556099951, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7899975525225714}}
{"text": "using Statistics\nusing BenchmarkTools\nusing LinearAlgebra\n\n\n# Looking into pointers from http://fa.bianp.net/blog/2019/evaluate_logistic/\n#\n\n\n\nσ(x) = 1 / (1 + exp(-x))\n\n## Order 0\nfunction f_naive(x, A, b)\n    z = A*x\n    tmp = σ.(z)\n    @. tmp = - b * log(tmp) - (1 - b) * log(1 - tmp)\n    return sum(tmp)/length(tmp)\nend\n\n\n## blog logistic\nfunction logsig_naive(t)\n    return log(1 / (1 + exp(-t)))\nend\n\nfunction logsig_log1pexp(t)\n    if t < -33.3\n        return t\n    elseif t <= -18\n        return t - exp(t)\n    elseif t <= 37\n        return -log1p(exp(-t))\n    else\n        return -exp(-t)\n    end\nend\n\nfunction f_logsumexp(x, A, b, logsig)\n    m = size(A, 1)\n\n    Ax = A * x\n    fval = 0.0\n    @inbounds @simd for i in 1:m\n        fval += -logsig(b[i] * Ax[i])\n    end\n    fval /= m\n\n    return fval\nend\n\n\n\n### Order 1\nfunction ∇f_current(x, A, b)\n    m = size(A, 1)\n\n    σbAx = σ.(-b .* (A * x))\n    res = transpose(A) * (σbAx .* -b)\n\n    res /= m\n    return res\nend\n\n\n\nfunction expit_b(x, b)\n    out = zeros(size(x))\n\n    @inbounds for (i, xi) in enumerate(x)\n        if xi < 0\n            out[i] = ((1 - b[i]) * exp(xi) - b[i]) / (1 + exp(xi))\n        else\n            out[i] = ((1 - b[i]) - b[i] * exp(-xi)) / (1 + exp(-xi))\n        end\n    end\n    return out\nend\n\n\nfunction ∇f_prop(x, A, b)\n    \"\"\"Computes the gradient of the logistic loss.\n\n    Parameters\n    ----------\n    x: array-like, shape (n_features,)\n        Coefficients\n\n    A: array-like, shape (n_samples, n_features)\n        Data matrix\n\n    b: array-like, shape (n_samples,)\n        Labels\n\n    Returns\n    -------\n    grad: array-like, shape (n_features,)\n    \"\"\"\n    z = A*x\n    s = expit_b(z, b)\n    return A'*s / size(A, 1)\nend\n\nfunction main()\n    A = [1 1;]\n    b = [1]\n    x = [20, 20]\n\n    # mode = [:fvals]\n    mode = [:∇f]\n\n    if :fvals in mode\n        @show f_naive(x, A, b)\n        @show f_logsumexp(x, A, b, logsig_naive)\n        @show f_logsumexp(x, A, b, logsig_log1pexp)\n    elseif :∇f in mode\n        @show ∇f_current(x, A, b)\n        @show ∇f_prop(x, A, b)\n    end\n\n    println(\"\")\n    println(\"\")\n\n    println(\"Larger test\")\n    n, m = 500, 400\n    A = rand(m, n)\n    x = rand(n)\n    b = rand(m)\n\n    if :fvals in mode\n        @show f_naive(x, A, b)\n        @show f_logsumexp(x, A, b, logsig_naive)\n        @show f_logsumexp(x, A, b, logsig_log1pexp)\n\n        @btime f_naive($x, $A, $b)\n        @btime f_logsumexp($x, $A, $b, $logsig_naive)\n        @btime f_logsumexp($x, $A, $b, $logsig_log1pexp)\n    elseif :∇f in mode\n        ∇f_cu = ∇f_current(x, A, b)\n        ∇f_pr = ∇f_prop(x, A, b)\n\n        @show norm(∇f_cu - ∇f_pr)\n\n        @btime ∇f_current($x, $A, $b)\n        @btime ∇f_prop($x, $A, $b)\n    end\n\n    return\nend\n\n\nmain()\n", "meta": {"hexsha": "99e875226337054cfcff4ff3a9ee7aec40ea6e7f", "size": 2732, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmark/logistic_test.jl", "max_stars_repo_name": "GillesBareilles/CompositeProblems.jl", "max_stars_repo_head_hexsha": "d5cc1b99a00bf61614af9a750fc93bf718d3151b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmark/logistic_test.jl", "max_issues_repo_name": "GillesBareilles/CompositeProblems.jl", "max_issues_repo_head_hexsha": "d5cc1b99a00bf61614af9a750fc93bf718d3151b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark/logistic_test.jl", "max_forks_repo_name": "GillesBareilles/CompositeProblems.jl", "max_forks_repo_head_hexsha": "d5cc1b99a00bf61614af9a750fc93bf718d3151b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8562091503, "max_line_length": 77, "alphanum_fraction": 0.5091508053, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.789984132670922}}
{"text": "\nusing FastGaussQuadrature\n\nget_nodes(::Val{:gauss_legendre}, n, T=Float64) = convert(Array{T}, gausslegendre(n)[1])\nget_nodes(::Val{:lobatto_legendre}, n, T=Float64) = convert(Array{T}, gausslobatto(n)[1])\n\nfunction get_nodes(::Val{:gauss_chebyshev}, n, T=Float64; k=1)\n    x = zeros(T, n)\n    if k == 1\n        for i in eachindex(x)\n            x[i] = sin( π*(n-2i+1) / (2n) )\n        end\n        return x[end:-1:1]\n    elseif k == 2\n        for i in eachindex(x)\n            x[i] = cos( π*i / (n-1) )\n        end\n        return x\n    end\nend\n\nfunction get_nodes(::Val{:lobatto_chebyshev}, n, T=Float64)\n    x = zeros(T, n)\n    for i in eachindex(x)\n        x[i] = cos( (i-1)*π / (n-1) )\n    end\n    return x[end:-1:1]\nend\n", "meta": {"hexsha": "88249ef633f9b0b28658fc5401b73face701196b", "size": 725, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bases/generic/nodes.jl", "max_stars_repo_name": "ToBlick/MoreBasisFunctions.jl", "max_stars_repo_head_hexsha": "fd3ed5c3a58077c33cf1799cf86479abdd40f7b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bases/generic/nodes.jl", "max_issues_repo_name": "ToBlick/MoreBasisFunctions.jl", "max_issues_repo_head_hexsha": "fd3ed5c3a58077c33cf1799cf86479abdd40f7b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-02T09:46:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-02T09:46:12.000Z", "max_forks_repo_path": "src/bases/generic/nodes.jl", "max_forks_repo_name": "ToBlick/MoreBasisFunctions.jl", "max_forks_repo_head_hexsha": "fd3ed5c3a58077c33cf1799cf86479abdd40f7b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-01T15:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-01T15:51:57.000Z", "avg_line_length": 25.0, "max_line_length": 89, "alphanum_fraction": 0.5503448276, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.8558511506439707, "lm_q1q2_score": 0.7899841272351714}}
{"text": "\n#=\nAccurate simple zeros of polynomials in floating point arithmetic\nStef Graillat\nComputers and Mathematics with Applications 56 (2008) 1114–1120\n\n   poly has N+1 coefficients a_0,a_1,..,a_N for x^0,x^1,..,x^N \n   \n   poly = polynomial(coeffs[a_0,a_1,..,a_N])\n   poly(x) = sum[i=0:1:N]( a_i * x^i )          this the the classical Horner scheme\n   \n   function classicalHorner{R<:Real}(p::Poly,x::R)\n      n = length(p.a)\n      s = zeros(R, n)       # one-based indexing\n      s[:] = p.a[:]\n      for i in (n-1):(-1):1\n          s[i] += s[i+1]*x\n      end\n      s[1]\n    end  \n\n\nAlgorithms for Accurate, Validated and Fast Polynomial Evaluation\nStef Graillat, Philippe Langlois and Nicolas Louvet\nJapan J. Indust. Appl. Math., 26 (2009), 191–214\n\neftHorner(p_n,x) computes\n(i)  the floating point evaluation Horner(p_n,x)\n(ii) two polynomials pa, pb, of degree n-1\nsuch that\n  Horner(p_n,x), pa, pb = eftHorner(p_n,x)\n  p_n(x) == Horner(p_n,x) + (pa + pb)(x)\nso\n  eftHorner is an errorfree transformation for polynomial evaluation with the Horner algorithm\n     (unless there is underflow)\n=#\n\nfunction eftHorner{T<:AbstractFloat}(p::Poly{T},x::T)\n   deg = degree(p); n=deg+1\n   cofs = coeffs(p)\n   pa = zeros(T,n)\n   pb = zeros(T,n)\n   r = cofs[n]\n   for i in deg:(-1):1\n      t, pa[i] = eftMul(r, x)\n      r, pb[i] = eftAdd(t, cofs[i])\n    end\n    r, pa, pb\nend\n\n# expects length(a) == length(b), length(a)>0\nfunction sumHorner{T<:AbstractFloat}(a::Vector{T}, b::Vector{T}, x::T)\n   n = length(a)\n   if ((n == 0)|(n != length(b)))\n      throw(ErrorException(\"vectors must be of the same nonzero length\"))\n   end\n   r = a[n]+b[n]\n   for i in (n-1): -1: 1\n     r = r * x + (a[i]+b[i])\n   end\n   r\nend\n\nfunction csdHornerA{T<:AbstractFloat}(p::Poly{T}, x::T)\n    r, pa, pb = eftHorner(p,x)\n    c = sumHorner(pa,pb,x)\n    r + c\nend\n\n# as accurate as if computed at twice the working precision and then rounded to working precision\nfunction csdHorner{T<:AbstractFloat}(p::Poly{T}, x::T)\n    r, pa, pb = eftHorner(p,x)\n    pab = Poly(pa + pb)\n    c = polyval(pab, x)\n    r + c\nend\n", "meta": {"hexsha": "e640f343fa24bc4654ca885306aca7c40ec843fd", "size": 2079, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/horner.jl", "max_stars_repo_name": "Jeffrey-Sarnoff/CompensatedArithmetic.jl", "max_stars_repo_head_hexsha": "8f1df2b2a653c2ef84c738e3f12d3e6c02a5cc1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/horner.jl", "max_issues_repo_name": "Jeffrey-Sarnoff/CompensatedArithmetic.jl", "max_issues_repo_head_hexsha": "8f1df2b2a653c2ef84c738e3f12d3e6c02a5cc1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/horner.jl", "max_forks_repo_name": "Jeffrey-Sarnoff/CompensatedArithmetic.jl", "max_forks_repo_head_hexsha": "8f1df2b2a653c2ef84c738e3f12d3e6c02a5cc1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 97, "alphanum_fraction": 0.6132756133, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868805, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7899841222595912}}
{"text": "# A palindromic number reads the same both ways.\n# The largest palindrome made from the product\n# of two 2-digit numbers is 9009 = 91 × 99.\n# Find the largest palindrome made from the product of two 3-digit numbers.\n\nfunction is_palindrome(n)\n    s = string(n)\n    return s == reverse(s)\nend\n\n\n@assert is_palindrome(2)\n@assert is_palindrome(11)\n@assert is_palindrome(9009)\n@assert is_palindrome(90109)\n@assert is_palindrome(90209)\n\n\nfunction find_next_palindrome_decreasing(n)\n    while !is_palindrome(n)\n        n -= 1\n    end\n    return n\nend\n\n@assert find_next_palindrome_decreasing(10000) == 9999\n@assert find_next_palindrome_decreasing(9998) == 9889\n\nfunction is_divisible_by_digits(n, digits)\n    # Checks if a number is divisible by two x digits number\n    max = (10 ^ digits) - 1\n    min = minimum([max, trunc(Int, n / (10 ^ digits) + 1)])\n\n    for i in range(max, -1, max-min)\n        if n % i == 0 && (n / i) <= max\n            return true\n        end\n    end\n    return false\nend\n\n@assert is_divisible_by_digits(9999, 2) == false\n@assert is_divisible_by_digits(9779, 2) == false\n@assert is_divisible_by_digits(9009, 2) == true\n\n\nfunction compute_palindrome_by_factors(n, digit)\n    while !is_palindrome(n) || !is_divisible_by_digits(n, digit)\n        n = find_next_palindrome_decreasing(n-1)\n    end\n    return n\nend\n@assert compute_palindrome_by_factors(99*99,2) == 9009\nprintln(compute_palindrome_by_factors(999*999, 3))\n", "meta": {"hexsha": "d02ac6179b50f86af92f528178caac97f9d228aa", "size": 1434, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4.jl", "max_stars_repo_name": "ddugue/project-euler", "max_stars_repo_head_hexsha": "ab373d896ac5051bb53a706cccfdfa3987ca9272", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4.jl", "max_issues_repo_name": "ddugue/project-euler", "max_issues_repo_head_hexsha": "ab373d896ac5051bb53a706cccfdfa3987ca9272", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4.jl", "max_forks_repo_name": "ddugue/project-euler", "max_forks_repo_head_hexsha": "ab373d896ac5051bb53a706cccfdfa3987ca9272", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0727272727, "max_line_length": 75, "alphanum_fraction": 0.7050209205, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109784205502, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7899274832852238}}
{"text": "# Make the Convex.jl module available\nusing Convex, SCS, ECOS\nusing LinearAlgebra\n\n# Generate random problem data\nm = 4;  n = 5\nA = randn(m, n); b = randn(m, 1)\n\n# Create a (column vector) variable of size n x 1.\nx = Convex.Variable(n)\n\n# The problem is to minimize ||Ax - b||^2 subject to x >= 0\n# This can be done by: minimize(objective, constraints)\nproblem = minimize(sumsquares(A * x - b), [x >= 0])\n\n# Solve the problem by calling solve!\nsolve!(problem, ECOS.Optimizer; silent_solver = true)\n\n# Check the status of the problem\nproblem.status # :Optimal, :Infeasible, :Unbounded etc.\n\n# Get the optimum value\nproblem.optval\n\n# minimum distance spheres \npa = Variable(3)\npb = Variable(3) \nxa = [0.0; 0.0; 0.0]\nxb = [1.0; 0.0; 0.0]\nra = 0.1 \nrb = 0.1\n\nproblem = minimize(norm(pa - pb), [norm(pa - xa) <= ra, norm(pb - xb) <= rb])\n\n# Solve the problem by calling solve!\nsolve!(problem, ECOS.Optimizer; silent_solver = true)\n\n# Check the status of the problem\nproblem.status # :Optimal, :Infeasible, :Unbounded etc.\n\n# Get the optimum value\nproblem.optval\npa\npb\n\n# minimum distance ellipsoids \npa = Variable(3)\npb = Variable(3) \nxa = [0.0; 0.0; 0.0]\nxb = [1.0; 0.0; 0.0]\nax = 0.3 \nay = 0.1 \naz = 0.1\nbx = 0.1 \nby = 0.2\nbz = 0.1\n\nproblem = minimize(norm(pa - pb), \n    [\n        quadform(pa - xa, Array(Diagonal([1.0 / ax^2, 1.0 / ay^2, 1.0 / az^2]))) <= 1.0, \n        quadform(pb - xb, Array(Diagonal([1.0 / bx^2, 1.0 / by^2, 1.0 / bz^2]))) <= 1.0,\n    ])\n\n# Solve the problem by calling solve!\nsolve!(problem, ECOS.Optimizer; silent_solver = true)\n\n# Check the status of the problem\nproblem.status # :Optimal, :Infeasible, :Unbounded etc.\n\n# Get the optimum value\nproblem.optval\npa\npb\n\n### minimum distance cylinders \npa = Variable(3)\npb = Variable(3) \nsa = Variable(3) \nsb = Variable(3)\nxa = [-1.0; 0.0; 0.0]\nxb = [1.0; 0.0; 0.0]\nra = 0.1\nha = 1.0\nrb = 0.1\nhb = 1.0\n\nproblem = minimize(norm(pa - pb), \n    [\n        sa == pa - xa,\n        sb == pb - xb,\n        norm(sa[1:2]) <= ra,\n        sa[3] <= 0.5 * ha + sqrt(ra * ra - dot(sa[1:2], sa[1:2])),\n        -0.5 * ha - sqrt(ra * ra - dot(sa[1:2], sa[1:2])) <= sa[3],\n        norm(sb[1:2]) <= rb,\n        sb[3] <= 0.5 * hb + sqrt(rb * rb - dot(sb[1:2], sb[1:2])),\n        -0.5 * hb - sqrt(rb * rb - dot(sb[1:2], sb[1:2])) <= sb[3],\n    ])\n\npa.value = [-1.0; 0.0; 0.0]\npb.value = [1.0; 0.0; 0.0]\n# Solve the problem by calling solve!\nsolve!(problem, ECOS.Optimizer; silent_solver = false)\n\n# Check the status of the problem\nproblem.status # :Optimal, :Infeasible, :Unbounded etc.\n\n# Get the optimum value\nproblem.optval\npa\npb\n\n## line segment \nza = Convex.Variable(3) \nzb = Convex.Variable(3)\nta = Convex.Variable(1)\ntb = Convex.Variable(1) \n\nxa = [-1.0; 0.0; 0.0]\nqa = Quaternion(RotY(-0.25 * π) * RotX(0.0 * π))\nqa = [qa.w; qa.x; qa.y; qa.z]\n\nxb = [1.0; 0.0; 0.0]\nqb = Quaternion(RotZ(0.0 * π) * RotY(0.0 * π) * RotX(0.0))\nqb = [qb.w; qb.x; qb.y; qb.z]\nra = 0.1\nha = 1.0\nrb = 0.1\nhb = 1.0\n\np1a = xa + rotation_matrix(qa) * [0.0; 0.0; 0.5 * ha]\np2a = xa + rotation_matrix(qa) * [0.0; 0.0; -0.5 * ha]\n\np1b = xb + rotation_matrix(qb) * [0.0; 0.0;  0.5 * hb]\np2b = xb + rotation_matrix(qb) * [0.0; 0.0; -0.5 * hb]\n\n\nproblem = minimize(norm(za - zb), \n    [\n        za == ta * p1a + (1.0 - ta) * p2a,\n        zb == tb * p1b + (1.0 - tb) * p2b,\n        ta >= 0.0, \n        ta <= 1.0, \n        tb >= 0.0, \n        tb <= 1.0,\n    ])\n\n\n# Solve the problem by calling solve!\nsolve!(problem, ECOS.Optimizer; silent_solver = false)\n\n# Check the status of the problem\nproblem.status # :Optimal, :Infeasible, :Unbounded etc.\n\n# Get the optimum value\nproblem.optval\nza\nzb", "meta": {"hexsha": "f59f39b81445799641c5152e68b8ea2011b66097", "size": 3610, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/simulation/dev/convex.jl", "max_stars_repo_name": "rejuvyesh/Dojo.jl", "max_stars_repo_head_hexsha": "6c9f8bdb31de3e2068ea1a51afe317ada3922379", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70, "max_stars_repo_stars_event_min_datetime": "2022-03-02T01:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:14:51.000Z", "max_issues_repo_path": "examples/simulation/dev/convex.jl", "max_issues_repo_name": "dojo-sim/Dojo.jl", "max_issues_repo_head_hexsha": "33ccdde8d7f74c4ea3c3bffdebcc6ed65959a5be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2022-03-02T06:58:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T17:17:26.000Z", "max_forks_repo_path": "examples/simulation/dev/convex.jl", "max_forks_repo_name": "rejuvyesh/Dojo.jl", "max_forks_repo_head_hexsha": "6c9f8bdb31de3e2068ea1a51afe317ada3922379", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2022-03-07T01:47:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T19:13:07.000Z", "avg_line_length": 22.9936305732, "max_line_length": 89, "alphanum_fraction": 0.5861495845, "num_tokens": 1421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109756113862, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7899274769752316}}
{"text": "using NumericalIntegration\nusing LinearAlgebra\nusing FFTW\n\n#=\nThis function computes the Fourier modes either integrating \"by hand\" or using FFTW. We split the comlex modes, associated to the complex exponentials into a and b, associated to the cos and sin functions by a(kx,ky) = 2*Re(f(kx,ky)) and b(kx,ky) = -2*Im(f(kx,ky)).\n=#\n\n\nfunction Fourier_modes_2D(e :: Array{T,2}, x :: Array{T,1}, y :: Array{T,1}, order_x :: Integer, order_y :: Integer, integration_method :: String) where {T<:Real}\n    Lx, Ly = x[end]-x[1], y[end]-y[1]\n    xmid, ymid = (x[end]+x[1])/2, (y[end]+y[1])/2\n    nx, ny = length(x),length(y)\n\n    if order_x > Integer(floor(nx)) || order_y > Integer(floor(ny))\n        print(\"\\n Error, requested order is higher than the number of grid points\\n\")\n        nothing\n    end\n    \n    if integration_method == \"trapezoidal\"\n\n        a, b = zeros(order_x+1,order_y+1), zeros(order_x+1,order_y+1)\n        xx, yy = zeros(nx,ny), zeros(nx,ny)\n        #We create the 2D grid\n        for i in 1:ny\n            xx[:,i] = x\n        end\n        for i in 1:nx\n            yy[i,:] = y\n        end\n\n        for my in 0:order_y\n            for mx in 0:order_x\n                integral_cos, integral_sin = zeros(nx), zeros(nx)\n                integrand_cos = 2/(Lx*Ly).*e.*cos.(2*π*(mx/Lx.*(xx.-xmid).+my/Ly.*(yy.-ymid)))\n                integrand_sin = 2/(Lx*Ly).*e.*sin.(2*π*(mx/Lx.*(xx.-xmid).+my/Ly.*(yy.-ymid)))\n                for i in 1:nx\n                    integral_cos[i] = integrate(y,integrand_cos[i,:], Trapezoidal())\n                    integral_sin[i] = integrate(y,integrand_sin[i,:], Trapezoidal())\n                end\n                a[mx+1,my+1] = integrate(x,integral_cos, Trapezoidal())\n                b[mx+1,my+1] = integrate(x,integral_sin, Trapezoidal())\n            end\n        end\n\n    elseif integration_method == \"FFTW\"\n\n        plan = plan_rfft(e)\n        fft_z = (1/(nx*ny).*(plan*e)[1:order_x+1,1:order_y+1])\n        a = 2 .*real(fft_z) \n        b = -2 .*imag(fft_z)\n\n    else\n        print(\"\\n No such integration method\\n\")\n        nothing\n    end\n    return a, b\nend\n", "meta": {"hexsha": "6479a51febee123294d3ca569e68c0a250e6cd3e", "size": 2109, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/Fourier_modes.jl", "max_stars_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_stars_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-09-08T23:37:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:19:01.000Z", "max_issues_repo_path": "scripts/Fourier_modes.jl", "max_issues_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_issues_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-02T17:57:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-02T17:57:23.000Z", "max_forks_repo_path": "scripts/Fourier_modes.jl", "max_forks_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_forks_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-02-26T15:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T08:46:55.000Z", "avg_line_length": 35.7457627119, "max_line_length": 265, "alphanum_fraction": 0.5576102418, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.789927476502282}}
{"text": "export gaussian, xavier, xavier_uniform, xavier_normal, bilinear\nusing Random: randn, rand\n\n\"\"\"\n\n    gaussian(a...; mean=0.0, std=0.01)\n\nReturn a Gaussian array with a given mean and standard deviation.  The\n`a` arguments are passed to `randn`.\n\n\"\"\"\nfunction gaussian(a...; mean=0.0, std=0.01)\n    r = randn(a...)\n    T = eltype(r)\n    r .* T(std) .+ T(mean)\nend\n\n\n\"\"\"\n\n    xavier_uniform(a...; gain=1)\n    xavier(a...; gain=1)\n\nReturn uniform random weights in the range `± gain * sqrt(6 / (fanin + fanout))`.  The `a`\narguments are passed to `rand` to specify type and dimensions.  See ([Glorot and Bengio\n2010](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf)) or the [PyTorch\ndocs](https://pytorch.org/docs/stable/nn.init.html#torch.nn.init.xavier_uniform_) for a\ndescription.  The function implements equation (16) of the referenced paper. Also known as\nGlorot initialization. The function `xavier` is an alias for `xavier_uniform`. See also\n`xavier_normal`.\n\n\"\"\"\nxavier, xavier_uniform\n\nfunction xavier_uniform(a...; gain=1)\n    w = rand(a...)\n    if ndims(w) == 1\n        fanout = 1\n        fanin = length(w)\n    elseif ndims(w) == 2\n        fanout = size(w,1)\n        fanin = size(w,2)\n    else\n        # if a is (3,3,16,8), then there are 16 input channels and 8 output channels\n        # fanin = 3*3*16 = (3*3*16*8) ÷ 8\n        # fanout = 3*3*8 = (3*3*16*8) ÷ 16\n        fanin = div(length(w),  a[end])\n        fanout = div(length(w), a[end-1])\n    end\n    s = convert(eltype(w), gain*sqrt(6 / (fanin + fanout)))\n    return 2s .* w .- s\nend\n\nconst xavier = xavier_uniform\n\n\n\"\"\"\n\n    xavier_normal(a...; gain=1)\n\nReturn normal distributed random weights with mean 0 and std `gain * sqrt(2 / (fanin +\nfanout))`.  The `a` arguments are passed to `rand`.  See ([Glorot and Bengio\n2010](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf)) and [PyTorch\ndocs](https://pytorch.org/docs/stable/nn.init.html#torch.nn.init.xavier_normal_) for a\ndescription. Also known as Glorot initialization. See also `xavier_uniform`.\n\n\"\"\"\nfunction xavier_normal(a...; gain=1)\n    w = randn(a...)\n    if ndims(w) == 1\n        fanout = 1\n        fanin = length(w)\n    elseif ndims(w) == 2\n        fanout = size(w,1)\n        fanin = size(w,2)\n    else\n        # if a is (3,3,16,8), then there are 16 input channels and 8 output channels\n        # fanin = 3*3*16 = (3*3*16*8) ÷ 8\n        # fanout = 3*3*8 = (3*3*16*8) ÷ 16\n        fanin = div(length(w),  a[end])\n        fanout = div(length(w), a[end-1])\n    end\n    s = convert(eltype(w), gain*sqrt(2 / (fanin + fanout)))\n    return s .* w\nend\n\n\n\"\"\"\n\nBilinear interpolation filter weights; used for initializing deconvolution layers.\n\nAdapted from https://github.com/shelhamer/fcn.berkeleyvision.org/blob/master/surgery.py#L33\n\nArguments:\n\n`T` : Data Type\n\n`fw`: Width upscale factor\n\n`fh`: Height upscale factor\n\n`IN`: Number of input filters\n\n`ON`: Number of output filters\n\n\nExample usage:\n\nw = bilinear(Float32,2,2,128,128)\n\n\"\"\"\nfunction bilinear(T,fw,fh,IN,ON)\n    @assert fw == fh \"Filter must be square\"\n    @assert IN == ON \"Number of input and output filters must be equal\"\n    f=fw; N=IN;\n\n    sz = 2*f-f%2\n    center = f-0.5\n    if sz%2 == 1\n        center = f-1\n    end\n    r = range(0,stop=sz-1,length=sz)\n    c = range(0,stop=sz-1,length=sz)'\n\n    kernel = (1 .- abs.(r .- center) ./ f) .* (1 .- abs.(c .- center) ./ f)\n    w = zeros(T,sz,sz,N,N);\n    for i=1:N\n        w[:,:,i,i] = kernel\n    end\n    return w\nend\n", "meta": {"hexsha": "8c4d836826f73effebd771dd59eb043343040b66", "size": 3489, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/train20/distributions.jl", "max_stars_repo_name": "AndrewSerra/Knet.jl", "max_stars_repo_head_hexsha": "cbbcb670667b1707ad1b1d7c637784e36a98b81e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1492, "max_stars_repo_stars_event_min_datetime": "2015-09-30T07:05:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T14:48:46.000Z", "max_issues_repo_path": "src/train20/distributions.jl", "max_issues_repo_name": "AndrewSerra/Knet.jl", "max_issues_repo_head_hexsha": "cbbcb670667b1707ad1b1d7c637784e36a98b81e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 604, "max_issues_repo_issues_event_min_datetime": "2016-02-05T06:32:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T20:09:19.000Z", "max_forks_repo_path": "src/train20/distributions.jl", "max_forks_repo_name": "AndrewSerra/Knet.jl", "max_forks_repo_head_hexsha": "cbbcb670667b1707ad1b1d7c637784e36a98b81e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 340, "max_forks_repo_forks_event_min_datetime": "2015-10-28T07:47:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:51:11.000Z", "avg_line_length": 26.4318181818, "max_line_length": 91, "alphanum_fraction": 0.6205216394, "num_tokens": 1161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.789927476502282}}
{"text": "using SimpleGraphs, SimpleGraphAlgorithms\n\nconst DEFAULT_FILE_NAME = \"tree_codes.jl\"\n\n# initialize the table of unlabeled trees\n\n\"\"\"\n    init_trees_table()\nCreate a new table of distinct trees on 1 and 2 vertices.\n\"\"\"\nfunction init_trees_table()\n    TT = Dict{Int,Vector{SimpleGraph{Int}}}()\n\n    TT[1] = [IntGraph(1)]\n    T = IntGraph(2)\n    add!(T, 1, 2)\n    TT[2] = [T]\n\n    return TT\nend\n\n\"\"\"\n    check_in(G,S)\nSee if the set `S` contains a graph isomorphic to `G`. Return `true` if so.\n\"\"\"\nfunction check_in(G::SimpleGraph{Int}, S::Set{SimpleGraph{Int}})\n    if isempty(S)\n        return false\n    end\n    for H ∈ S\n        if uhash(G) == uhash(H) #is_iso(G, H)\n            return true\n        end\n    end\n    return false\nend\n\n\"\"\"\n    extend_trees_table!(TT)\nGiven a table of distinct trees up to size `n`, extend that table to include \nall distinct trees of size `n+1`.\n\"\"\"\nfunction extend_trees_table!(TT::Dict{Int,Vector{SimpleGraph{Int}}})::Nothing\n    n = maximum(keys(TT))\n    outset = Set{SimpleGraph{Int}}()  # set of trees with n+1 vertices\n    for T ∈ TT[n]\n        for w = 1:n\n            X = deepcopy(T)\n            add!(X, w, n + 1)\n            if check_in(X, outset)\n                continue\n            end\n            push!(outset, X)\n        end\n    end\n\n    TT[n+1] = collect(outset)\n\n    @info \"Added $(length(TT[n+1])) new trees with $(n+1) vertices\"\n    nothing\nend\n\nfunction build_trees_table(nmax::Int)\n    TT = init_trees_table()\n    while maximum(keys(TT)) < nmax\n        @info \"Adding trees of size $(maximum(keys(TT))+1)\"\n        extend_trees_table!(TT)\n    end\n    return TT\nend\n\n\"\"\"\n    create_codes_table(TT)\nGiven a table of distinct trees, convert that into a table of Prufer codes.\nThis is used by `save_trees_table` and not useful to be called directly. \n\"\"\"\nfunction create_codes_table(TT::Dict{Int64,Vector{SimpleGraph{Int}}})\n    codes = Dict{Int64,Vector{Vector{Int}}}()\n    codes[2] = [Int[]]\n    for n = 3:maximum(keys(TT))\n        codes[n] = prufer_code.(TT[n])\n    end\n    return codes\nend\n\n\"\"\"\n    save_tree_table(TT, filename)\nSave a trees table into a file specified by `filename`.\nIf the file name is omitted, use `codes.jl`.\n\"\"\"\nfunction save_trees_table(\n    TT::Dict{Int64,Vector{SimpleGraph{Int}}},\n    filename::String = DEFAULT_FILE_NAME,\n)\n    outfile = open(filename, \"w\")\n    codes = create_codes_table(TT)\n    println(outfile, \"codes = Dict{Int,Vector{Vector{Int}}}()\")\n    for n = 2:maximum(keys(TT))\n        print(outfile, \"codes[$n] = \")\n        println(outfile, codes[n])\n    end\n    close(outfile)\n    nothing\nend\n\n\"\"\"\n    load_trees_table(filename)\nCreate a table of distinct trees by reading in a file that has been\nprecomputed (and presumably saved using `save_tree_table`). If `filename`\nis omitted, use `codes.jl`.\n\"\"\"\nfunction load_trees_table(filename::String = DEFAULT_FILE_NAME)\n    include(filename)\n    TT = init_trees_table()\n    nmax = maximum(keys(codes))\n\n    for n = 3:nmax\n        TT[n] = prufer_restore.(codes[n])\n    end\n    @info \"Read in table of distinct trees up to $nmax vertices\"\n    return TT\n\nend\n", "meta": {"hexsha": "f08bca9922d899d6632abcccdbaf8530aa341bf5", "size": 3091, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "extras/distinct_trees.jl", "max_stars_repo_name": "scheinerman/SimpleGraphs.jl", "max_stars_repo_head_hexsha": "01ad710f29f72c3bc7e823180c11ffd554bef296", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2015-03-08T00:51:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T18:54:27.000Z", "max_issues_repo_path": "extras/distinct_trees.jl", "max_issues_repo_name": "scheinerman/SimpleGraphs.jl", "max_issues_repo_head_hexsha": "01ad710f29f72c3bc7e823180c11ffd554bef296", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-08-15T11:25:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T22:46:00.000Z", "max_forks_repo_path": "extras/distinct_trees.jl", "max_forks_repo_name": "scheinerman/SimpleGraphs.jl", "max_forks_repo_head_hexsha": "01ad710f29f72c3bc7e823180c11ffd554bef296", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-07-04T01:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-11T09:09:06.000Z", "avg_line_length": 24.9274193548, "max_line_length": 77, "alphanum_fraction": 0.6350695568, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7899178024878898}}
{"text": "## PCA vs LDA\n## Height Weight data\n# Grab data from https://www.kaggle.com/mustafaali96/weight-height\n# https://opendata.stackexchange.com/questions/7793/age-weight-and-height-dataset\n# https://www.reddit.com/r/datasets/comments/1dii3t/data_sets_for_heights_and_weights/\n\n# https://vincentarelbundock.github.io/Rdatasets/datasets.html\n\n# a related tutorial\n# http://goelhardik.github.io/2016/10/04/fishers-lda/\n\n##\nusing Plots\n##\n# https://vincentarelbundock.github.io/Rdatasets/csv/carData/Davis.csv\nusing CSV\ndf = CSV.read(download(\"https://vincentarelbundock.github.io/Rdatasets/csv/carData/Davis.csv\"))\nX = Float64.([df[:weight] df[:height]])\n\n##\ng = df[:sex]\n\n##\nscatter(X[:,1],X[:,2])\nxlabel!(\"Weight\")\nylabel!(\"Height\")\n\n## Filter the data\ngoodpts = X[:,1] .<= 115\nXf = X[goodpts,:]\ngf = g[goodpts]\n\n##\ntheme(:dark)\nscatter(Xf[:,1],Xf[:,2],color=2)\nxlabel!(\"Weight\")\nylabel!(\"Height\")\n\n## Save a picture\npyplot()\nscatter(Xf[:,1],Xf[:,2],color=2,size=(300,300), legend=false)\nxlabel!(\"Weight\")\nylabel!(\"Height\")\nsavefig(\"weight-height-1.pdf\")\n\n## Partition by classes\ns1 = gf .== \"F\"\ns2 = gf .== \"M\"\nX1 = Xf[s1,:]\nX2 = Xf[s2,:]\ngr()\nscatter(X1[:,1],X1[:,2])\nscatter!(X2[:,1],X2[:,2])\n\n## Save a picture\npyplot()\nscatter(X1[:,1],X1[:,2],size=(300,300), legend=false)\nscatter!(X2[:,1],X2[:,2])\nsavefig(\"weight-height-2.pdf\")\n##\nusing Statistics\nm = mean(Xf,dims=1)\nm1 = mean(X1,dims=1)\nm2 = mean(X2,dims=1)\nn1 = size(X1,1)\nn2 = size(X2,1)\n\nB = (m1-m)'*n1*(m1-m) + (m2-m)'*n2*(m2-m)\nW = (X1.-m1)'*(X1.-m1) + (X2.-m2)'*(X2.-m2)\n\n## The matrices B and W add up to the total covariance\nusing LinearAlgebra\nC = (Xf.-m)'*(Xf.-m)\nnorm(B+W - C)\n\n##\nlams,V = eigen(B,W)\n\n##\nv = V[:,2]\np1 = histogram((X1)*v,nbins=10)\nhistogram!((X2)*v,nbins=10)\n## Save\nplot!(size=(300,300),legend=false)\nsavefig(\"weight-height-lda.pdf\")\n##\n\n## Compare to PCA\nlams,V = eigen(C)\nv2 = V[:,2]\np2 = histogram(X1*v2,nbins=10)\nhistogram!(X2*v2,nbins=10)\nplot(p1,p2)\n##\n## Save\nplot(p2)\nplot!(size=(300,300),legend=false)\nsavefig(\"weight-height-pca.pdf\")\n##\nX1c = X1.-m\nX2c = X2.-m\nscatter(X1c[:,1],X1c[:,2], label=\"\")\nscatter!(X2c[:,1],X2c[:,2], label=\"\")\nPlots.abline!(v[2]/v[1],0,label=\"LDA\")\nPlots.abline!(v2[2]/v2[1],0,label=\"PCA\")\n##\nplot!(size=(300,300),legend=false)\nsavefig(\"weight-height-lda-pca.pdf\")\n", "meta": {"hexsha": "f1778e4c15fae7f935f44a9e37e3e981feb1a039", "size": 2284, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4-unit-3-demos/lda-pca.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "4-unit-3-demos/lda-pca.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4-unit-3-demos/lda-pca.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 20.9541284404, "max_line_length": 95, "alphanum_fraction": 0.6471103327, "num_tokens": 846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.8633916047011594, "lm_q1q2_score": 0.7899177976639636}}
{"text": "\"\"\"\n    _setdiff(x::Interval{T}, y::Interval{T})\n\nComputes the set difference x\\\\y and always returns a tuple of two intervals.\nIf the set difference is only one interval or is empty, then the returned tuple contains 1\nor 2 empty intervals.\n\"\"\"\nfunction _setdiff(x::Interval{T}, y::Interval{T}) where T\n    intersection = x ∩ y\n\n    isempty(intersection) && return (x, emptyinterval(T))\n    intersection == x && return (emptyinterval(T), emptyinterval(T))  # x is subset of y; setdiff is empty\n\n    x.lo == intersection.lo && return (Interval(intersection.hi, x.hi), emptyinterval(T))\n    x.hi == intersection.hi && return (Interval(x.lo, intersection.lo), emptyinterval(T))\n\n    return (Interval(x.lo, y.lo), Interval(y.hi, x.hi))\n\nend\n\n\n\"\"\"\n    setdiff(A::IntervalBox{N,T}, B::IntervalBox{N,T})\n\nReturns a vector of `IntervalBox`es that are in the set difference `A ∖ B`,\ni.e. the set of `x` that are in `A` but not in `B`.\n\nAlgorithm: Start from the total overlap (in all directions);\nexpand each direction in turn.\n\"\"\"\nfunction setdiff(A::IntervalBox{N,T}, B::IntervalBox{N,T}) where {N,T}\n\n    intersection = A ∩ B\n    isempty(intersection) && return [A]\n\n    result_list = fill(IntervalBox(emptyinterval(T), N), 2*N)\n    offset = 0\n    x = A.v\n    @inbounds for i = 1:N\n        tmp = _setdiff(A[i], B[i])\n        @inbounds for j = 1:2\n            x = setindex(x, tmp[j], i)\n            result_list[offset+j] = IntervalBox{N, T}(x)\n        end\n        offset += 2\n        x = setindex(x, intersection[i], i)\n    end\n    filter!(!isempty, result_list)\nend\n", "meta": {"hexsha": "553edbba04e24738f25782b4eb4764383c336759", "size": 1560, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/multidim/setdiff.jl", "max_stars_repo_name": "lucaferranti/IntervalArithmetic.jl", "max_stars_repo_head_hexsha": "c7602f4941b550e6a8f11aa2d4cfe774a60f8afc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 203, "max_stars_repo_stars_event_min_datetime": "2017-04-18T21:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:27:34.000Z", "max_issues_repo_path": "src/multidim/setdiff.jl", "max_issues_repo_name": "lucaferranti/IntervalArithmetic.jl", "max_issues_repo_head_hexsha": "c7602f4941b550e6a8f11aa2d4cfe774a60f8afc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 503, "max_issues_repo_issues_event_min_datetime": "2017-04-03T01:10:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:09:39.000Z", "max_forks_repo_path": "src/multidim/setdiff.jl", "max_forks_repo_name": "lucaferranti/IntervalArithmetic.jl", "max_forks_repo_head_hexsha": "c7602f4941b550e6a8f11aa2d4cfe774a60f8afc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 76, "max_forks_repo_forks_event_min_datetime": "2017-04-10T20:49:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T22:41:01.000Z", "avg_line_length": 31.2, "max_line_length": 106, "alphanum_fraction": 0.6416666667, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.8705972633721708, "lm_q1q2_score": 0.7899035391226437}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ c96551a0-881e-11eb-0d92-61edbb6c86e6\nbegin\n\tusing Pkg; Pkg.activate(\"MLJ_env\", shared=true)\n  using PlutoUI\n\tusing Test\n\t\nend\n\n# ╔═╡ accc6f84-881d-11eb-3b49-e9cd25a3b6fd\nmd\"\"\"\n## Linear Algebra\n\nref. from book **\"Data Science from Scratch\"**, Chap 4\n\n$(html\"<div><sub>&copy; Pascal, March 2021</sub></div>\")\n\"\"\"\n\n# ╔═╡ 136cdd48-8835-11eb-0482-737cf7bd5a3e\nPlutoUI.TableOfContents(indent=true, depth=4, aside=true)\n\n# ╔═╡ b22cf860-8834-11eb-02de-d3ad803d1db6\nhtml\"\"\"\n<style>\n  main {\n\tmax-width: calc(800px + 25px + 6px);\n  }\n  .plutoui-toc.aside {\n    background: linen;\n  }\n  h3, h4 {\n\tbackground: wheat;\n  }\n</style>\n\"\"\"\n\n# ╔═╡ b1e26cfa-8834-11eb-16f5-85efb64c6a4c\nmd\"\"\"\n### Vectors\nPoints in some finite dimensional space. A vector has a direction and a magnitude.$(html\"<br />\")\nVectors are useful to represent data (which lie in some multi-finite-dimensional space).  \nWe will want to perform operations on those vectors, so let defines and implements those operations. $(html\"<br />\")\nWe will be using the `Vector` type from `Julia`.\n\"\"\"\n\n# ╔═╡ 9b2a7694-881e-11eb-325c-f3edd9178641\nbegin\n\timport Base: +, -\n\n\tfunction +(v₁::Vector{T}, v₂::Vector{T})::Vector{T} where T <: Number\n\t\t\"\"\"\n\t\tVector Additon is component-wise \n\t\t\"\"\"\n\t\t@assert length(v₁) == length(v₂)\n\t\tv₁ .+ v₂\n\tend\n\t\n\tfunction +(vc::Vector{Vector{T}})::Vector{T} where T <: Number\n\t\t\"\"\"\n\t\tSum all corresponding components of a collection of vector to return\n\t\tone vector\n\t\t\"\"\"\n\t\t@assert length(vc) > 0 \"expect the collection to have at leat one vector element\"\n\t\tn = length(vc[1])\n\t\t@assert all(v -> length(v) == n, vc) \"Expect all vectors to be of he same length\"\n\t\tv = zeros(T, n)\n\t\tfor v₀ ∈ vc\n\t\t\tv .+= v₀\n\t\tend\t\n\t\tv\n\tend\n\t\n\tfunction -(v₁::Vector{T}, v₂::Vector{T})::Vector{T} where T <: Number\n\t\t\"\"\"\n\t\tVector Additon is component-wise \n\t\t\"\"\"\n\t\t@assert length(v₁) == length(v₂)\t\n\t\tv₁ .- v₂\n\tend\nend\n\n# ╔═╡ 21a74512-881f-11eb-31e6-974bcaf59141\nbegin\n\t@test +([1, 2, 3], [4, 5, 6]) == [5, 7, 9]\n\t@test [1, 2, 3] + [4, 5, 6] == [5, 7, 9]\n\t\n\tvᵣ = [1.0, -1.0, π, ℯ]\n\t@test vᵣ + [-1.0, 1.0, -π, -ℯ] == zeros(eltype(vᵣ), length(vᵣ))\nend\n\n# ╔═╡ 11ff42a0-8828-11eb-3ba5-dbd12b5ffdda\nmd\"\"\"\nSometimes we want to sum a collection of vector component wise. that is create a new vector whose first component is the sum of evry first comp[onent of thew collection and  so for for the other components.\n\nHere the collection is itsef a vector in `Julia`'s term.\ncf. celle above for implementation\n\"\"\"\n\n# ╔═╡ 7dc3365c-8828-11eb-3c57-69dae41619cd\nbegin\n\t@test +([[1, 2], [3, 4], [5, 6], [7, 8]]) == [16, 20]\n\t@test +([[1, 3, 2] for _ ∈ 1:3]) == [3, 9, 6]\nend\n\n# ╔═╡ e9b7d526-8829-11eb-34d1-e317fdc7a1d0\nmd\"\"\"\n`Multiplication` by a scalar, `Mean` and `dot` product.\n\"\"\"\n\n# ╔═╡ 3a7741c2-882a-11eb-2ffd-65b97e75a0b2\nbegin\n\timport Base.*\n\t\n\t*(x::T, v::Vector{T}) where T <: Number = v .* x\n\t*(v::Vector{T}, x::T) where T <: Number = v .* x\n\t\n\tfunction μ(vc::Vector{Vector{T}})::Vector{AbstractFloat} where T <: Number\n\t\t\"\"\"Element-wise mean\"\"\"\n\t\t@assert length(vc) > 0 \n\t\tn = length(vc[1])\n\t\t@assert all(v -> length(v) == n, vc) \n\t\treduce(+, vc) / n\n \tend\n\n\tfunction dot(v₁::Vector{T}, v₂::Vector{T})::T where T <: Number\n\t\t@assert length(v₁) == length(v₂)\n\t\tsum(v₁ .* v₂)\n\tend\nend\n\n# ╔═╡ b3f61d4e-881f-11eb-2dcb-4dd0fd7fba06\nbegin\n\t@test -([1, 2, 3], [4, 5, 6]) == [-3, -3, -3]\n\t@test [1, 2, 3] - [4, 5, 6] == [-3, -3, -3]\n\t\n\t# vᵣ = [1.0, -1.0, π, ℯ]\n\t@test vᵣ - [-1.0, 1.0, -π, -ℯ] == [2.0, -2.0, 2π, 2ℯ]\nend\n\n# ╔═╡ 19f5b176-882b-11eb-3713-73c85f599be1\nbegin\n\t@test *(2, [1, 2, 3]) == [2, 4, 6]\n\t@test *(2, [1, 2, 3]) == *([1, 2, 3], 2)\n\t@test 2 * [1, 2, 3] == [1, 2, 3] * 2  ==  [2, 4, 6]\nend\n\n# ╔═╡ 50444c92-882b-11eb-2893-bf66b63ee595\nbegin\n\tμ([[1, 2, 1, 2], [3, 4, 3, 4], [5, 6, 5, 6]]) == Float64[3., 4., 3., 4.]\nend\n\n# ╔═╡ d358476c-882d-11eb-26bd-c167cabd7b28\nbegin\n\t@test dot([1, 2, 3], [4, 5, 6]) == 32\nend\n\n# ╔═╡ d33d417e-882d-11eb-0aae-a1d10512920f\nfunction sum_of_square(v::Vector{T})::T where T <: Number\n\t\"\"\"\n\treturn vᵢ * vᵢ ∀ i ∈ 1:length(v)\n\t\"\"\"\n\tdot(v, v)\nend\n\n# ╔═╡ d3202a62-882d-11eb-2e24-6d874dce773d\nbegin\n\t@test sum_of_square([1, 2, 3]) == 14\n\t@test sum_of_square([4, 5, 6]) == 77\nend\n\n# ╔═╡ 9db8e630-882e-11eb-07e5-0d5036f7e8e2\nmd\"\"\"\nLet's now implement L₂ norm and euclidean distance.\n\"\"\"\n\n# ╔═╡ ba1d63da-882e-11eb-1736-37a246585172\nfunction norm(v::Vector{T})::AbstractFloat where T <: Number\n\t√ sum(v .* v)\nend\n\n# ╔═╡ 9da1fcfc-882e-11eb-021f-1f89149817a9\nbegin\n\t@test norm([3, 4]) == 5\n\t@test norm([1, 0, 2]) ≈ √5\nend\n\n# ╔═╡ 9d8634ae-882e-11eb-15ad-75b06c847379\nfunction distance(v₁::Vector{T}, v₂::Vector{T})::AbstractFloat where T <: Number\n\t\"\"\"\n\tdistance(v₁, v₂) ≡ √(Σ (v₁ᵢ - v₂ᵢ)²)\n\t\"\"\"\n\t@assert length(v₁) == length(v₂)\n\t√ sum((v₁ .- v₂).^2)  # == norm(v₁ .- v₂)\nend\n\n# ╔═╡ 9d69ec22-882e-11eb-0637-d7e29f7b9f37\nbegin\n\t@test distance([2, 6, 7, 7, 5, 13, 14, 17, 11, 8],\n\t\t[3, 5, 5, 3, 7, 12, 13, 19, 22, 7]) ≈ 12.409673645990857\nend\n\n# ╔═╡ 0539916a-8835-11eb-3407-41f17efc2ee4\nhtml\"\"\"\n<hr />\n\"\"\"\n\n# ╔═╡ 73e7de7a-8830-11eb-05ef-b93f6c774587\nmd\"\"\"\n### Matrices\n\nA two-dimensional collection of numbers.\n\"\"\"\n\n# ╔═╡ 7f051430-8830-11eb-1e43-797df6b195ed\nfunction shape(m::Matrix{T})::Tuple{Integer, Integer} where T <: Number\n\tsize(m)\nend\n\n# ╔═╡ 7ee4e642-8830-11eb-3d15-813c4dbb6420\n@test shape([1 2 3; 4 5 6]) == (2, 3) # 2 rows, 3 columns\n\n# ╔═╡ 7ec91688-8830-11eb-18a0-d5a67e267f9b\nfunction get_row(m::Matrix{T}, r::Integer)::Vector{T}  where T <: Number\n\t@assert 1 ≤ r ≤ size(m)[1]\n\tview(m, r, :)  ## no copy!\nend\n\n# ╔═╡ 7e9afe92-8830-11eb-3772-150255e27923\nbegin\n\t@test get_row([1 2 3; 4 5 6], 1) == [1, 2, 3]\n\t@test get_row([1 2 3; 4 5 6], 2) == [4, 5, 6]\t\n\t@test_throws AssertionError get_row([1 2 3; 4 5 6], 0) \nend\n\n# ╔═╡ 648af952-8831-11eb-340b-5bc7ef7aaa73\nfunction get_column(m::Matrix{T}, c::Integer)::Vector{T}  where T <: Number\n\t@assert 1 ≤ c ≤ size(m)[2]\n\tview(m, :, c)  ## no copy!\nend\n\n# ╔═╡ 6470ad90-8831-11eb-0413-5d016bf66536\nbegin\n\t@test get_column([1 2 3; 4 5 6], 1) == [1, 4]\n\t@test get_column([1 2 3; 4 5 6], 2) == [2, 5]\n\t@test get_column([1 2 3; 4 5 6], 3) == [3, 6]\n\t@test_throws AssertionError get_column([1 2 3; 4 5 6], 0) \nend\n\n# ╔═╡ 6458987c-8831-11eb-2b89-efac8fabf803\nmd\"\"\"\nWe will want to be able to create a new matrix given its shape and a function generator.\n\"\"\"\n\n# ╔═╡ c832331c-8831-11eb-0b7c-9f978c82f890\nfunction make_matrix(nrows::Integer, ncols::Integer, fn::Function;\n\t\tDT::DataType=Float64)::Matrix\n\t@assert 1 ≤ nrows && 1 ≤ ncols\n\t\n\tm = zeros(DT, (nrows, ncols))\n\tfor c ∈ 1:ncols, r ∈ 1:nrows\n\t\tm[r, c] = fn(r, c)\n\tend\n\tm\nend\n\n# ╔═╡ be10ce56-8832-11eb-0742-d90fa7f6f669\nfunction identity_matrix(n::Integer; DT::DataType=Float64)::Matrix\n\t\"\"\"Returns the n × n identity matrix\"\"\"\t\n\tmake_matrix(n, n, (i, j) -> i == j ? one(DT) : zero(DT); DT)\nend\n\n# ╔═╡ c81a12dc-8831-11eb-27e9-07132c6310a1\n@test identity_matrix(5) == [1. 0. 0. 0. 0.; 0. 1. 0. 0. 0.; 0. 0. 1. 0. 0.; 0. 0. 0. 1. 0.; 0. 0. 0. 0. 1.]\n\n# ╔═╡ 3c69e83a-8835-11eb-218e-0bb108ad7b9c\nhtml\"\"\"\n<hr />\n<sub><em>Mar 2021, Corto Inc</em></sub>\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─accc6f84-881d-11eb-3b49-e9cd25a3b6fd\n# ╟─136cdd48-8835-11eb-0482-737cf7bd5a3e\n# ╟─b22cf860-8834-11eb-02de-d3ad803d1db6\n# ╟─b1e26cfa-8834-11eb-16f5-85efb64c6a4c\n# ╠═c96551a0-881e-11eb-0d92-61edbb6c86e6\n# ╠═9b2a7694-881e-11eb-325c-f3edd9178641\n# ╠═21a74512-881f-11eb-31e6-974bcaf59141\n# ╠═b3f61d4e-881f-11eb-2dcb-4dd0fd7fba06\n# ╟─11ff42a0-8828-11eb-3ba5-dbd12b5ffdda\n# ╠═7dc3365c-8828-11eb-3c57-69dae41619cd\n# ╟─e9b7d526-8829-11eb-34d1-e317fdc7a1d0\n# ╠═3a7741c2-882a-11eb-2ffd-65b97e75a0b2\n# ╠═19f5b176-882b-11eb-3713-73c85f599be1\n# ╠═50444c92-882b-11eb-2893-bf66b63ee595\n# ╠═d358476c-882d-11eb-26bd-c167cabd7b28\n# ╠═d33d417e-882d-11eb-0aae-a1d10512920f\n# ╠═d3202a62-882d-11eb-2e24-6d874dce773d\n# ╟─9db8e630-882e-11eb-07e5-0d5036f7e8e2\n# ╠═ba1d63da-882e-11eb-1736-37a246585172\n# ╠═9da1fcfc-882e-11eb-021f-1f89149817a9\n# ╠═9d8634ae-882e-11eb-15ad-75b06c847379\n# ╠═9d69ec22-882e-11eb-0637-d7e29f7b9f37\n# ╟─0539916a-8835-11eb-3407-41f17efc2ee4\n# ╟─73e7de7a-8830-11eb-05ef-b93f6c774587\n# ╠═7f051430-8830-11eb-1e43-797df6b195ed\n# ╠═7ee4e642-8830-11eb-3d15-813c4dbb6420\n# ╠═7ec91688-8830-11eb-18a0-d5a67e267f9b\n# ╠═7e9afe92-8830-11eb-3772-150255e27923\n# ╠═648af952-8831-11eb-340b-5bc7ef7aaa73\n# ╠═6470ad90-8831-11eb-0413-5d016bf66536\n# ╟─6458987c-8831-11eb-2b89-efac8fabf803\n# ╠═c832331c-8831-11eb-0b7c-9f978c82f890\n# ╠═be10ce56-8832-11eb-0742-d90fa7f6f669\n# ╠═c81a12dc-8831-11eb-27e9-07132c6310a1\n# ╟─3c69e83a-8835-11eb-218e-0bb108ad7b9c\n", "meta": {"hexsha": "9e2000a4aab80b16493aa66319d9065e7a748793", "size": 8561, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Data Science From Scratch/04_Linear_Algebra.jl", "max_stars_repo_name": "pascal-p/julia-notebooks", "max_stars_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-01T20:34:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-01T20:34:56.000Z", "max_issues_repo_path": "Data Science From Scratch/04_Linear_Algebra.jl", "max_issues_repo_name": "pascal-p/julia-notebooks", "max_issues_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Science From Scratch/04_Linear_Algebra.jl", "max_forks_repo_name": "pascal-p/julia-notebooks", "max_forks_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-10T09:03:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T09:03:18.000Z", "avg_line_length": 26.5869565217, "max_line_length": 206, "alphanum_fraction": 0.6458357668, "num_tokens": 4268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.9019206824612296, "lm_q1q2_score": 0.7898904099699173}}
{"text": "##################################################\n## Classical derivative-based, iterative, root-finding algorithms\n##\n## If ri = f^(i-1)/f^(i), then these have an update step `xn - delta` where:\n##\n## * Newton: delta = r1  # order 2 if simple root (multiplicity 1)\n## * Halley: delta = 2*r2/(2r2 - r1) * r1 # order 3 if simple root\n## * Schroder: delta = r2  / (r2 - r1) * r1  # order 2\n## * Thukral(3): delta =  (-2*r3)*(r2 - r1)/(r1^2 - 3*r1*r3 + 2*r2*r3) * r1 # order 3\n## * Thukral(4): delta =  3*r1*r2*r4*(r1^2 - 3*r1*r3 + 2*r2*r3)/(-r1^3*r2 + 4*r1^2*r2*r4 + 3*r1^2*r3*r4 - 12*r1*r2*r3*r4 + 6*r2^2*r3*r4) # order 4\n##\n## The latter two come from\n## [Thukral](http://article.sapub.org/10.5923.j.ajcam.20170702.05.html). They are not implemented.\n\n\n## Newton\nabstract type AbstractNewtonLikeMethod <: AbstractUnivariateZeroMethod end\nfn_argout(::AbstractNewtonLikeMethod) = 2\nstruct Newton <: AbstractNewtonLikeMethod end\n\"\"\"\n\n    Roots.Newton()\n\nImplements Newton's [method](http://tinyurl.com/b4d7vls):\n`xᵢ₊₁ =  xᵢ - f(xᵢ)/f'(xᵢ)`.  This is a quadratically convergent method requiring\none derivative. Two function calls per step.\n\nExample\n```\nfind_zero((sin,cos), 3.0, Roots.Newton())\n```\n\nIf function evaluations are expensive one can pass in a function which returns (f, f/f') as follows\n\n```\nfind_zero(x -> (sin(x), sin(x)/cos(x)), 3.0, Roots.Newton())\n```\n\nThis can be advantageous if the derivative is easily computed from the\nvalue of f, but otherwise would be expensive to compute.\n\nThe error, `eᵢ = xᵢ - α`, can be expressed as `eᵢ₊₁ = f[xᵢ,xᵢ,α]/(2f[xᵢ,xᵢ])eᵢ²` (Sidi, Unified treatment of regula falsi, Newton-Raphson, secant, and Steffensen methods for nonlinear equations).\n\n\"\"\"\nNewton\n\n# we store x0,x1,fx0,fx1 **and** Δ = fx1/f'(x1)\nstruct NewtonState{T,S} <: AbstractUnivariateZeroState{T,S}\n    xn1::T\n    xn0::T\n    Δ::T\n    fxn1::S\n    fxn0::S\nend\n\n\nfunction init_state(M::Newton, F::Callable_Function, x)\n    x₀ = float(first(x))\n    fx₀, Δ = F(x₀)\n    x₁ = x₀ - Δ\n    state = init_state(M, F, x₀, x₁, fx₀, fx₀)\nend\n\n# compute fx₁, Δ\nfunction init_state(::Newton, F, x₀, x₁, fx₀, fx₁)\n    fx₁, Δ = F(x₁)\n    NewtonState(x₁, x₀, Δ, fx₁, fx₀)\nend\n\ninitial_fncalls(M::Newton) = 2\n\n\nfunction update_state(method::Newton, F, o::NewtonState{T,S}, options, l=NullTracks()) where {T, S}\n\n    xn0, xn1 = o.xn0, o.xn1\n    fxn0, fxn1 = o.fxn0, o.fxn1\n    Δ = o.Δ\n\n    if isissue(Δ)\n        log_message(l, \"Issue with `f/f′'\")\n        return o, true\n    end\n\n    xn0, xn1 = xn1, xn1-Δ\n    fxn0 = fxn1\n    fxn1, Δ = F(xn1)\n    incfn(l,2)\n\n    @set! o.xn0 = xn0\n    @set! o.xn1 = xn1\n    @set! o.Δ = Δ\n    @set! o.fxn0 = fxn0\n    @set! o.fxn1 = fxn1\n\n    return o, false\n\n\n\nend\n\n\n\"\"\"\n    Roots.newton(f, fp, x0; kwargs...)\n\nImplementation of Newton's method: `xᵢ₊₁ =  xᵢ - f(xᵢ)/f'(xᵢ)`.\n\nArguments:\n\n* `f::Function` -- function to find zero of\n\n* `fp::Function` -- the derivative of `f`.\n\n* `x0::Number` -- initial guess. For Newton's method this may be complex.\n\nWith the `FowardDiff` package derivatives may be computed automatically. For example,  defining\n`D(f) = x -> ForwardDiff.derivative(f, float(x))` allows `D(f)` to be used for the first derivative.\n\nKeyword arguments are passed to `find_zero` using the `Roots.Newton()` method.\n\nSee also `Roots.newton((f,fp), x0)` and `Roots.newton(fΔf, x0)` for simpler implementations.\n\n\"\"\"\nnewton(f, fp, x0; kwargs...) = find_zero((f, fp), x0, Newton(); kwargs...)\n\n\n## Halley\nabstract type AbstractHalleyLikeMethod <: AbstractUnivariateZeroMethod end\nfn_argout(::AbstractHalleyLikeMethod) = 3\n\n\"\"\"\n    Roots.Halley()\n\nImplements Halley's [method](http://tinyurl.com/yd83eytb),\n`xᵢ₊₁ = xᵢ - (f/f')(xᵢ) * (1 - (f/f')(xᵢ) * (f''/f')(xᵢ) * 1/2)^(-1)`\nThis method is cubically converging, but requires more function calls per step (3) than\nother methods.\n\nExample\n```\nfind_zero((sin, cos, x->-sin(x)), 3.0, Roots.Halley())\n```\n\nIf function evaluations are expensive one can pass in a function which\nreturns `(f, f/f',f'/f'')` as follows\n\n```\nfind_zero(x -> (sin(x), sin(x)/cos(x), -cos(x)/sin(x)), 3.0, Roots.Halley())\n```\n\nThis can be advantageous if the derivatives are easily computed from\nthe computation for f, but otherwise would be expensive to compute separately.\n\nThe error, `eᵢ = xᵢ - α`, satisfies\n`eᵢ₊₁ ≈ -(2f'⋅f''' -3⋅(f'')²)/(12⋅(f'')²) ⋅ eᵢ³` (all evaluated at `α`).\n\n\"\"\"\nstruct Halley <: AbstractHalleyLikeMethod\nend\n\nstruct HalleyState{T,S} <: AbstractUnivariateZeroState{T,S}\n    xn1::T\n    xn0::T\n    Δ::T\n    ΔΔ::T\n    fxn1::S\n    fxn0::S\nend\n\n# we compute one step here to get x₁\nfunction init_state(M::AbstractHalleyLikeMethod, F::Callable_Function, x)\n    x₀ = float(first(x))\n    fx₀, (Δ, ΔΔ) = F(x₀)\n    x₁ = x₀ - 2ΔΔ/(2ΔΔ - Δ) * Δ\n    state = init_state(M, F, x₀, x₁, fx₀, fx₀)\nend\n\nfunction init_state(::AbstractHalleyLikeMethod, F, x₀, x₁, fx₀, fx₁)\n    fx₁, (Δ, ΔΔ) = F(x₁)\n    HalleyState(x₁, x₀, Δ, ΔΔ, fx₁, fx₀)\nend\n\ninitial_fncalls(M::AbstractHalleyLikeMethod) = 2*3\n\nfunction update_state(method::Halley, F, o::HalleyState{T,S}, options::UnivariateZeroOptions, l=NullTracks()) where {T,S}\n    xn = o.xn1\n    fxn = o.fxn1\n    r1, r2 = o.Δ, o.ΔΔ\n\n    Δ =  2*r2/(2r2 - r1) * r1\n    if isissue(Δ)\n        log_message(l, \"Issue with computing `Δ`\")\n        return (o, true)\n    end\n\n    xn1::T = xn - Δ\n    fxn1::S, (r1::T, r2::T) = F(xn1)\n    incfn(l,3)\n\n\n    @set! o.xn0 = xn\n    @set! o.xn1 = xn1\n    @set! o.fxn0 = fxn\n    @set! o.fxn1 = fxn1\n    @set! o.Δ = r1\n    @set! o.ΔΔ = r2\n\n    return o, false\n\nend\n\n\"\"\"\n    Roots.halley(f, fp, fpp, x0; kwargs...)\n\nImplementation of Halley's method (cf `?Roots.Halley()`).\n\nArguments:\n\n* `f::Function` -- function to find zero of\n\n* `fp::Function` -- derivative of `f`.\n\n* `fpp:Function` -- second derivative of `f`.\n\n* `x0::Number` -- initial guess\n\nWith the `FowardDiff` package derivatives may be computed automatically. For example,  defining\n`D(f) = x -> ForwardDiff.derivative(f, float(x))` allows `D(f)` and `D(D(f))` to be used for the first and second\nderivatives, respectively.\n\nKeyword arguments are passed to `find_zero` using the `Roots.Halley()` method.\n\n\n\"\"\"\nhalley(f, fp, fpp, x0; kwargs...) = find_zero((f, fp, fpp), x0, Halley(); kwargs...)\n", "meta": {"hexsha": "04b112398d2fa641333ebefef9ed5f55561f097b", "size": 6194, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/newton.jl", "max_stars_repo_name": "devmotion/Roots.jl", "max_stars_repo_head_hexsha": "a77396c329a7587ac8eed01a63f4651ad2628423", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/newton.jl", "max_issues_repo_name": "devmotion/Roots.jl", "max_issues_repo_head_hexsha": "a77396c329a7587ac8eed01a63f4651ad2628423", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/newton.jl", "max_forks_repo_name": "devmotion/Roots.jl", "max_forks_repo_head_hexsha": "a77396c329a7587ac8eed01a63f4651ad2628423", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3574468085, "max_line_length": 195, "alphanum_fraction": 0.6315789474, "num_tokens": 2288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625145783431, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7898501840787134}}
{"text": "using DifferentialEquations\nusing IterableTables, DataFrames\nusing NamedTuples\nusing Gadfly\n\n\nfunction F(du,u,p,t)\n    S_H, E_H, I_H, R_H, S_V, E_V, I_V = u\n    \n    # host dynamics\n    host_infection = (p.β*S_H*I_V)/p.N_H\n    host_mortality = p.μ_H .* u[1:4] # include S_H, so easier to remove mortality\n    host_births = sum(host_mortality)\n    host_progression = p.σ_H*E_H\n    recovery = p.λ*I_H\n    \n    du[1] = -host_infection + host_births\n    du[2] = host_infection - host_progression\n    du[3] = host_progression - recovery\n    du[4] = recovery\n    du[1:4] -= host_mortality\n    \n    # vector dynamics\n    vec_infection = (p.β*S_V*I_H)/p.N_H\n    vec_mortality = p.μ_V .* u[5:7] # include S_V, so easier to remove mortality\n    vec_births = sum(vec_mortality)\n    vec_progression = p.σ_V*E_V\n    \n    du[5] = -vec_infection + vec_births\n    du[6] = vec_infection - vec_progression\n    du[7] = vec_progression\n    du[5:7] -= vec_mortality\n    \nend\n\n# nb: in >= Julia v0.7, can eliminate this import\n#  and the @NT syntax\nu0 = [\n    S_H=100.0,   E_H=0.0, I_H=1.0, R_H=0.0,\n    S_V=10000.0, E_V=0.0, I_V=0.0\n]\np = @NT(\n  μ_H=1/365, μ_V=1/30, σ_H=1/3, σ_V=1/7, λ=1/14,\n  β=0.05, N_H = sum(u0[1:4])\n)\ntspan = (0.0, 365.0)\nprob = ODEProblem(F, u0, tspan, p)\nsol = @time solve(prob,Tsit5(),reltol=1e-8,abstol=1e-8,saveat=linspace(0,365,365*10+1))\n\ndf = DataFrame(sol)\nrename!(df, Dict(:timestamp => :t,\n  :value1 => :S_H, :value2 => :E_H, :value3 => :I_H, :value4 => :R_H,\n  :value5 => :S_V, :value6 => :E_V, :value7 => :I_V\n))\nmlt = melt(df,:t) # convert results into long format for plotting\nmlt[:host] = contains.(string.(mlt[:variable]),\"H\"); # tag which entries are host vs vector\ndf\n\n# Plot\nfig1a = plot(mlt[mlt[:host] .== true,:], x=:t, y=:value, color=:variable, Geom.line)\nfig1b = plot(mlt[mlt[:host] .!= true,:], x=:t, y=:value, color=:variable, Geom.line)\nvstack(fig1a,fig1b)\n", "meta": {"hexsha": "51a4dc0acf22474c0e8435595afa4fc885530e1b", "size": 1887, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/host_vector_models/1host_1vector.jl", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/host_vector_models/1host_1vector.jl", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/host_vector_models/1host_1vector.jl", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 29.9523809524, "max_line_length": 91, "alphanum_fraction": 0.635400106, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7898501790626833}}
{"text": "# f(x)=abs(x)\n\nfunction Fabs(x)\n    return (abs(x),nothing)\nend\n\nfunction Fabs_inplace(value::Array,auxvalue,x) # inplace\n    copy!(value,abs(x))\nend\n\n\nfunction Dabs(derivativeIDX,f_c,faux_c,grad_c,grad_n,x)\n    axpy!(1.0,sign(x).*grad_c,grad_n)\nend\n\nif PROC==\"GPU\" \n    function Fabs_inplace(value::CudaArray,auxvalue,x::CudaArray) # inplace\n        fill!(value,0.0)\n        abs!(x,value)\n    end\n\n    function Dabs(derivativeIDX,f_c,faux_c,grad_c,grad_n,x::CudaArray)\n        xsigny_update!(grad_c,x,grad_n)\n    end\nend\n\nDerivative[Fabs]=Dabs # Define dictionary lookup\nInplace[Fabs]=Fabs_inplace\n\nimport Base.abs\n\nabs(n::ADnode)=ADnode(Fabs,n)\n\n###abs(A::ADtrans)=transpose(abs(node[A.parent])) # abs(A')=(abs(A))' TODO:check\n\nexport abs\n", "meta": {"hexsha": "a1683d5725ea3b5ab6ad00c955fa657642b0447b", "size": 741, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/Fabs.jl", "max_stars_repo_name": "davidbarber/AutoDiff", "max_stars_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2016-03-20T20:52:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T07:31:59.000Z", "max_issues_repo_path": "src/functions/Fabs.jl", "max_issues_repo_name": "davidbarber/AutoDiff", "max_issues_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-06-17T20:12:48.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-17T20:12:48.000Z", "max_forks_repo_path": "src/functions/Fabs.jl", "max_forks_repo_name": "davidbarber/AutoDiff", "max_forks_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-01-11T21:36:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-06T21:04:40.000Z", "avg_line_length": 20.027027027, "max_line_length": 80, "alphanum_fraction": 0.6882591093, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7898501656279218}}
{"text": "export poisson, poisson!\n\n # get the maximum intensity of an image\nmymax(X::AbstractArray{<:RGB}) = max_rgb(X)\nmymax(X::AbstractArray{<:Gray}) = gray(maximum(X))\nmymax(X::AbstractArray) = maximum(X)\n\n\n # noise function for poisson\nfunction noise_f(x, scaling, max_intens)\n    # scale image to max_intensity and apply poisson noise\n    # after Poisson noise scale it back\n    return pois_rand(x * scaling / max_intens) * max_intens / scaling\nend\n\nf_pois(scaling, max_intens) = x -> scaling == nothing ? pois_rand(x) : noise_f(x, scaling, max_intens) \n\ncomb_pois(x, n) = n\n\npoisson(X::AbstractArray, scaling=nothing; clip=false) = poisson!(copy(X), scaling, clip=clip)\nfunction poisson!(X::AbstractArray, scaling=nothing; clip=false)\n    max_intens = convert(Float64, mymax(X))\n    return apply_noise!(comb_pois, f_pois(scaling, max_intens), X, clip)\nend\n\n\"\"\"\n    poisson(X; scaling=nothing, clip=false)\n\nReturns the array `X` affected by Poisson noise. \nAt every position the Poisson noise affects the intensity individually \nand the values at the positions represent the expected value of the Poisson\nDistribution. \nSince Poisson Noise due to discrete events you should\nprovide the optional argument `scaling`. This `scaling` connects\nthe highest value of the array with the discrete number of events.\nThe highest value will be then scaled and the poisson noise is applied\nAfterwards we scale the whole array back so that the initial intensity\nis preserved but with applied Poisson noise.\n`clip` is a keyword argument. If given, it clips the values to [0, 1]\n\"\"\"\npoisson\n", "meta": {"hexsha": "0be7fcd513dc69e2266d5f997c1b2e20ea7c8ad0", "size": 1571, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/poisson.jl", "max_stars_repo_name": "roflmaostc/Noise.jl", "max_stars_repo_head_hexsha": "249122da40136635ebbe0efa5a6a9e731e6ae3f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-04-15T14:29:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T04:34:33.000Z", "max_issues_repo_path": "src/poisson.jl", "max_issues_repo_name": "roflmaostc/Noise", "max_issues_repo_head_hexsha": "19133cc94e8f7d0d0c1be01cd63b593bfe9c4142", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-04-21T13:34:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T15:46:37.000Z", "max_forks_repo_path": "src/poisson.jl", "max_forks_repo_name": "roflmaostc/Noise", "max_forks_repo_head_hexsha": "19133cc94e8f7d0d0c1be01cd63b593bfe9c4142", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4047619048, "max_line_length": 103, "alphanum_fraction": 0.7549331636, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.8577680977182186, "lm_q1q2_score": 0.7898240049585785}}
{"text": "### PARALLELISATION:\n# start julia with \"julia -p auto\" or \"julia -p 4\" to use multiple processors\nusing Revise\nusing Random\nusing SpecialFunctions\nusing PyCall\nusing PyPlot\nusing Plots\nusing StatsPlots\nusing CmdStan\n\n#%%\n\n# If run from command line externally:\n#projDir = dirname(@__FILE__)\n\n# If run from Jupyter/Hydrogen, maybe change to suit you:\nprojDir= \"/home/johhub/Desktop/ABDA/A4\"\n#projDir= \"/lhome/johhub/Desktop/ABDA/A4\"\ntmpDir = projDir*\"/tmp\"\n\n################################################################\n\nfunction runStanMC(y,a,b,burnIn,N,projDir,tmpDir,keepchains=false,noOfChains=4)\n    # REQUIRES MODULES:\n    # CmdStan\n    #\n    # INPUT:\n    # y --> observed data\n    # burnIn --> number of bur in samples\n    # N --> total number of sample points\n    # projDir --> directory where the analysis should be conducted, and plots should be saved\n    # tmpDir --> directory where the temp files can be stored\n    # keepchains (optional) --> keep all vectors of the various chains, false\n    #                           per defaul, i.e. all chain are thrown in one vector\n    #\n    # OUTPUT:\n    # x_s --> sampled x values for all chains (Nx4 array)\n\n    ### 1) Define the Stan model, note that variable names must\n    # correspond to observed data later\n    # dichtonomous model\n    dichtModel = \"\n    data {\n    int<lower=0> J; // number of flips in the observed data, setting the minimum amount of data under lower\n    int<lower=0,upper=1> y[J];  // coin flips\n    }\n    parameters {\n    real<lower=0,upper=1> theta; // prob of getting a head\n    }\n    transformed parameters { // no transformed variables to use\n    }\n    model {\n    theta ~ beta($a, $b);         // prior distribution for theta\n    y ~ bernoulli(theta);       // likelihood, note that stan will create the posterior automatically.\n    }\n    \";\n\n    ### 2) Data for the Stan model, note that variable names must\n    # correspond to defined model in stan-code\n    observedData = Dict(\"J\" => length(y), \"y\" => y);\n\n    ### 3) Chain specs\n    myModel = Stanmodel(\n                    Sample(save_warmup=true,\n                           num_warmup=burnIn,\n                           num_samples=N,\n                           thin=1),   # thin: Period between saved samples\n                    name = \"flipping\",\n                    model = dichtModel,\n                    printsummary = false,\n                    tmpdir = tmpDir,\n                    nchains = noOfChains);    # number of chains (4 default)\n\n    ### 4) Run CmdStan:\n    # rc:     return code (0 if all is fine)\n    # chn:    chain results\n    # cnames: vector of variable names\n    rc, chn, cnames = stan(myModel,\n                           observedData,\n                           projDir,\n                           diagnostics = false,\n                           CmdStanDir = CMDSTAN_HOME);\n\n    ### Results without burn-in\n    #chns = chn[(n_burnin+1):end, :, :]\n    # the 7th (out of 8) coulmn in the .value method are the actual sampled points\n    # the 3rd dimension are the different chains: 1,2,3 --> chain 1,2,3\n\n    x_s = 1* chn.value[(burnIn+1):end,7,:]  # the 1* converts the \"Axis Array\" in the chain into an Array{Float64,2}\n\n    if keepchains == false\n        x_s = reshape(x_s,:);   # Throw all the chain samples in a single vetor\n    end\n\n    return x_s\nend\n\n#%%\n\n# Chain inputs:\nN = 10^6\nN_burnin = 1000\n\n#%%\n\n# First Column of Figure 6.4:\na = 100 # prior specs\nb = 100 # prior specs\ny = [ones(Int64,17); zeros(Int64,3)];    # make an Array{Intt64,1} array\n\n# to receive the prior curve, just set the data to empty array []:\nchain = runStanMC([],a,b,N_burnin,N,projDir,tmpDir);\nhistogram(chain, bins=100, normalize=:pdf, label=\"prior\")\ndensity!(chain,linewidth=3,label=\"prior\")\n\n# to receive the likelihood curve, just set the prior to a=1, b=1 (flat):\nchain = runStanMC(y,1,1,N_burnin,N,projDir,tmpDir);\nhistogram!(chain, bins=100, normalize=:pdf, label=\"likelihood\")\ndensity!(chain,linewidth=3,label=\"likelihood\")\n\nposterior1 = runStanMC(y,a,b,N_burnin,N,projDir,tmpDir);\nhistogram!(posterior1, bins=100, normalize=:pdf, label=\"posterior\")\ndensity!(posterior1,linewidth=3,label=\"posterior\")\n\nPlots.savefig(\"A4-A-C1_Stan.pdf\")\n\n#%%\n# Second Column\na = 18.25\nb = 6.75\ny = [ones(Int64,17); zeros(Int64,3)];    # make an Array{Intt64,1} array\n\n# to receive the prior curve, just set the data to empty array []:\nchain = runStanMC([],a,b,N_burnin,N,projDir,tmpDir);\nhistogram(chain, bins=100, normalize=:pdf, label=\"prior\")\ndensity!(chain,linewidth=3,label=\"prior\")\n\n# to receive the likelihood curve, just set the prior to a=1, b=1 (flat):\nchain = runStanMC(y,1,1,N_burnin,N,projDir,tmpDir);\nhistogram!(chain, bins=100, normalize=:pdf, label=\"likelihood\")\ndensity!(chain,linewidth=3,label=\"likelihood\")\n\nposterior2 = runStanMC(y,a,b,N_burnin,N,projDir,tmpDir);\nhistogram!(posterior2, bins=100, normalize=:pdf, label=\"posterior\")\ndensity!(posterior2,linewidth=3,label=\"posterior\")\n\nPlots.savefig(\"A4-A-C2_Stan.pdf\")\n\n#%%\n# Third Column\na = 1\nb = 1\ny = [ones(Int64,17); zeros(Int64,3)];    # make an Array{Intt64,1} array\n\n# to receive the prior curve, just set the data to empty array []:\nchain = runStanMC([],a,b,N_burnin,N,projDir,tmpDir);\nhistogram(chain, bins=100, normalize=:pdf, label=\"prior\")\ndensity!(chain,linewidth=3,label=\"prior\")\n\n# to receive the likelihood curve, just set the prior to a=1, b=1 (flat):\nchain = runStanMC(y,1,1,N_burnin,N,projDir,tmpDir);\nhistogram!(chain, bins=100, normalize=:pdf, label=\"likelihood\")\ndensity!(chain,linewidth=3,label=\"likelihood\")\n\nposterior3 = runStanMC(y,a,b,N_burnin,N,projDir,tmpDir);\nhistogram!(posterior3, bins=100, normalize=:pdf, label=\"posterior\")\ndensity!(posterior3,linewidth=3,label=\"posterior\")\n\nPlots.savefig(\"A4-A-C3_Stan.pdf\")\n\n#%%\n\ndensity(posterior1, label=\"a=100, b=100\")\ndensity!(posterior2, label=\"a=18.25, b=6.75\")\ndensity!(posterior3, label=\"a=1, b=1\")\nPlots.savefig(\"A4-A-all_Stan.pdf\")\n", "meta": {"hexsha": "42b0828097ef9bb411b433e60fc75a51e13ce29e", "size": 5926, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "A4/A4-TaskA_Stan.jl", "max_stars_repo_name": "vis-florum/Applied-Bayesian-Data-Analysis", "max_stars_repo_head_hexsha": "6d460443269d920ea61859df9434938139245c2b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A4/A4-TaskA_Stan.jl", "max_issues_repo_name": "vis-florum/Applied-Bayesian-Data-Analysis", "max_issues_repo_head_hexsha": "6d460443269d920ea61859df9434938139245c2b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A4/A4-TaskA_Stan.jl", "max_forks_repo_name": "vis-florum/Applied-Bayesian-Data-Analysis", "max_forks_repo_head_hexsha": "6d460443269d920ea61859df9434938139245c2b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2921348315, "max_line_length": 116, "alphanum_fraction": 0.6415794803, "num_tokens": 1696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.8856314723088732, "lm_q1q2_score": 0.7898159368322768}}
{"text": "#=\nPentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are:\n\n1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...\n\nIt can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal.\n\nFind the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of D?\n=#\nfunction pent(x)\n  div(x*(3x-1),2)\nend\n\nfunction ispent(x)\n  n = (sqrt(24x+1)+1)/6\n  return n == round(Int,n) && n > 0\nend\n\nfunction calc()\n  i = 0\n  pentagonals = Int64[]\n  while true\n    i += 1\n    p = pent(i)\n    for j in pentagonals\n      diff = abs(p-j)\n      if ispent(diff)\n        intsum = p + j\n        if ispent(intsum)\n          return diff\n        end\n      end\n    end\n    push!(pentagonals, p)\n  end\nend\n@time println(calc())\n", "meta": {"hexsha": "c00cdf3a05a71b1bb7d3c225c3e022f9258827d5", "size": 857, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p44.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p44.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p44.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 22.5526315789, "max_line_length": 153, "alphanum_fraction": 0.6044340723, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436405, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7897736009199536}}
{"text": "#----------------- Get the A matrix\nfunction getDivGrad(n1,n2,n3)\n    # the Divergence\n    D1 = kron(speye(n3),kron(speye(n2),ddx(n1)))\n    D2 = kron(speye(n3),kron(ddx(n2),speye(n1)))\n    D3 = kron(ddx(n3),kron(speye(n2),speye(n1)))\n    # DIV from faces to cell-centers\n\n    Div = [D1 D2 D3]\n\n    return Div*Div'\nend\n#----------------- 1D finite difference on staggered grid\n\n# generate 1D derivatives\nddx(n)=spdiags(ones(n)*[-1 1],[0,1],n,n+1)\n\n#------------- Build a diagonal matrix\nfunction spdiags(B,d,m,n)\n    # spdiags(B,d,m,n)\n    # creates a sparse matrix from its diagonals\n    d = d[:]\n    p = length(d)\n\n    len = zeros(p+1,1)\n    for k = 1:p\n        len[k+1] = Int(len[k]+length(max(1,1-d[k]):min(m,n-d[k])))\n    end\n    a = zeros(round(Int, len[p+1]), 3)\n    for k = 1:p\n        # Append new d[k]-th diagonal to compact form\n        i = max(1,1-d[k]):min(m,n-d[k])\n        a[(round(Int, len[k])+1):round(Int, len[k+1]),:] = [i i+d[k] B[i+(m >= n)*d[k], k]]\n    end\n\n    sparse(round(Int, a[:,1]), round(Int, a[:,2]), a[:,3], m, n)\nend\n", "meta": {"hexsha": "0f38eab508dc7aa2da8f788c918b51f792bced68", "size": 1049, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/getDivGrad.jl", "max_stars_repo_name": "zhangwen0411/MyIterativeSolvers.jl", "max_stars_repo_head_hexsha": "846d00bce67d73da0d9bc521732e0348f23fe490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/getDivGrad.jl", "max_issues_repo_name": "zhangwen0411/MyIterativeSolvers.jl", "max_issues_repo_head_hexsha": "846d00bce67d73da0d9bc521732e0348f23fe490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/getDivGrad.jl", "max_forks_repo_name": "zhangwen0411/MyIterativeSolvers.jl", "max_forks_repo_head_hexsha": "846d00bce67d73da0d9bc521732e0348f23fe490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6052631579, "max_line_length": 91, "alphanum_fraction": 0.5338417541, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828602, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7897621961518383}}
{"text": "# using LinearAlgebra\n# include(\"sphere.jl\")\n##\n\n\"\"\"\nThis function compute the associated Legendre polynomial P(l,m,x)\n    for m >= 0, l >= m, and abs(x) <= 1\n\"\"\"\nfunction Plm(l::Int, m::Int, x::AbstractFloat)\n    @assert 0 <= m <= l\n    pmm = 1.0\n    if m > 0\n        somx2 = sqrt((1.0 - x) * (1.0 + x))\n        fact = 1.0\n        for i = 1:m\n            pmm *= (-fact) * somx2\n            fact += 2.0\n        end\n    end\n\n    if l == m\n        return pmm\n    end\n    pmmp1 = x * (2.0 * m + 1.0) * pmm\n    if (l == (m + 1))\n        return pmmp1\n    end\n\n    pll = 0.0\n\n    for ll = (m+2):l\n        pll = ((2.0 * ll - 1.0) * x * pmmp1 - (ll + m - 1.0) * pmm) / (ll - m)\n        pmm = pmmp1\n        pmmp1 = pll\n    end\n\n    return pll\nend\n\"\"\"\nThis function compute the normalized associated Legendre polynomial P(l,m,x)\n    for m >= 0, l >= m, and abs(x) <= 1. It is alias  of GSL sf_legendre_Plm\n\"\"\"\nfunction sph_Plm(l::Int, m::Int, x::AbstractFloat)\n    @assert 0 <= m <= l\n    return sf_legendre_sphPlm(l, m, x)\nend\n\"\"\"\nThis function compute all of the normalized associated Legendre polynomial P(l,m)\n    for m >= 0, l >= m, and abs(x) <= 1. It is alias  of GSL sf_legendre_array.\n    This implementation include the Condon-Shortley phase factor.\n\"\"\"\nfunction Plm_array(l_max::Int, x::AbstractFloat; normal = :SPHARM)\n    normalization = Dict(\n        :SPHARM => GSL_SF_LEGENDRE_SPHARM,\n        :NONE => GSL_SF_LEGENDRE_NONE,\n        :SCHMIDT => GSL_SF_LEGENDRE_SCHMIDT,\n        :FULL => GSL_SF_LEGENDRE_FULL,\n    )\n    return sf_legendre_array_e(normalization[normal], l_max, x,1)\nend\n\"\"\"\nThis function returns the index of Plm_array corresponding to P(l,m)\n\"\"\"\nfunction Plm_array_index(l::Int, m::Int)\n    @assert 0 <= m <= l\n    return sf_legendre_array_index(l,m) + 1\nend\n\"\"\"\nThis function returns the the general real spherical harmonics function Y(l,m) at\n    pol angle and az_angle. l ∈ (0,..,n) and ∈ (-l,..l) m are the\n    order and degree of spherical harmonics respectively.\n    Pol_angle ∈ (0,..pi) and az_angle ∈ (0,2pi) are the polar angle and azimuthal angle\n    coordinate.\n\"\"\"\nfunction real_spharm(l::Int, m::Int, pol_angle, az_angle)\n    sqrt2 = sqrt(2.0)\n    if m == 0\n        return sph_Plm(l, m, cos(pol_angle))\n    elseif m > 0\n        return sqrt2 * cos(m * az_angle) * sph_Plm(l, m, cos(pol_angle))\n    elseif m < 0\n        return sqrt2 * sin(-m * az_angle) * sph_Plm(l, -m, cos(pol_angle))\n    end\nend\n\"\"\"\nThis function returns all of general real spherical harmonics function Y(l,m)\n    with order l.\n    Pol_angle ∈ (0,..pi) and az_angle ∈ (0,2pi) are the polar angle and azimuthal angle\n    coordinate.\n\"\"\"\nfunction real_spharm_array(l_max::Int, pol_angle, az_angle)\n    sqrt2 = sqrt(2.0)\n    len_array = (l_max + 1)^2\n    plm_array = Plm_array(l_max, cos(pol_angle); normal = :SPHARM)\n    spharm_array = Vector{Float64}(undef, len_array)\n    for j = 1:len_array\n        l, m = j2lm(j)\n        idx = Plm_array_index(l, abs(m))\n        if m == 0\n            spharm_array[j] = plm_array[idx]\n        elseif m > 0\n            spharm_array[j] = sqrt2 * cos(m * az_angle) * plm_array[idx]\n        elseif m < 0\n            spharm_array[j] = sqrt2 * sin(-m * az_angle) * plm_array[idx]\n        end\n    end\n    return spharm_array\nend\n\n\n\"\"\"\nThis function returns the order l and degree m of Y(l,m) from linear\n    index j of spharm_array\n\"\"\"\nfunction j2lm(j)\n    j = j - 1\n    l = floor(Int, sqrt(j))\n    m = j - l * (l + 1)\n    return l, m\nend\n\"\"\"\nThis function returns the linear index j of spharm_array\n    from the order l and degree m of Y(l,m)\n\"\"\"\nfunction lm2j(l, m)\n    return l^2 + l + m + 1\nend\n\n\"\"\"\nThis function returns the The matrix of general real spherical\n    harmonics function Y(l,m). The row index i  corresponds to points x_i and\n    column index j obtained from j =  l^2 + l + m +1 where l and m are the order\n    and degree of spherical harmonics respectively.\n\"\"\"\nfunction spharm_mat(l_max, pol_angle::T, az_angle::T) where {T<:AbstractVector}\n    n_row = length(pol_angle)\n    n_column = (l_max + 1)^2\n    mat = Matrix{eltype(pol_angle)}(undef, n_row, n_column)\n    for i = 1:n_row\n        mat[i, :] .= real_spharm_array(l_max, pol_angle[i], az_angle[i])\n    end\n    return mat\nend\n\n\"\"\"\nThis function returns the The matrix of coefficient of SH function Y(l,m). The\n    row index i  corresponds to points x_i and column index j obtained from j =  l^2 + l + m +1 where l and m are the order\n    and degree of spherical harmonics respectively.\n\"\"\"\nfunction spharm_coefs(l_max::Int, x, pol_angle,az_angle)\n    mat = spharm_mat(l_max, pol_angle, az_angle)\n    coefs = mat \\ x\n    return coefs\nend\n", "meta": {"hexsha": "91eeb5581a6fee8c4a823f107a7b01d712232920", "size": 4641, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spharm.jl", "max_stars_repo_name": "yusri-dh/MovingFrame.jl", "max_stars_repo_head_hexsha": "1be0d7e4ec1f20d898dfbaf9f85e5b9ac86c7b6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-28T07:25:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T11:59:15.000Z", "max_issues_repo_path": "src/spharm.jl", "max_issues_repo_name": "yusri-dh/MovingFrame.jl", "max_issues_repo_head_hexsha": "1be0d7e4ec1f20d898dfbaf9f85e5b9ac86c7b6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spharm.jl", "max_forks_repo_name": "yusri-dh/MovingFrame.jl", "max_forks_repo_head_hexsha": "1be0d7e4ec1f20d898dfbaf9f85e5b9ac86c7b6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9419354839, "max_line_length": 123, "alphanum_fraction": 0.6203404439, "num_tokens": 1472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122684798183, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7897621921048239}}
{"text": "# Problem 1\n# If we list all the natural numbers below 10 that are multiples of 3 or 5,\n# we get 3, 5, 6 and 9. The sum of these multiples is 23.\n# Find the sum of all the multiples of 3 or 5 below 1000.\n\nmultiple_3_5(x) = ((x % 3) == 0) || ((x % 5) == 0)\n\n∑ = 0\nfor i in 1:1000-1\n    global ∑ += multiple_3_5(i) ? i : 0\nend\nprint(∑)\n", "meta": {"hexsha": "fccc1a58f2453b93343aa4fde3d80f14a53102b8", "size": 334, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "euler_1.jl", "max_stars_repo_name": "pedvide/project-euler", "max_stars_repo_head_hexsha": "8e8e1e57b2c4d7e70a7127483539dca060c50a38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "euler_1.jl", "max_issues_repo_name": "pedvide/project-euler", "max_issues_repo_head_hexsha": "8e8e1e57b2c4d7e70a7127483539dca060c50a38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "euler_1.jl", "max_forks_repo_name": "pedvide/project-euler", "max_forks_repo_head_hexsha": "8e8e1e57b2c4d7e70a7127483539dca060c50a38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6923076923, "max_line_length": 75, "alphanum_fraction": 0.6167664671, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240211961401, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7897368687912653}}
{"text": "using SpecialFunctions\n\n\n@doc raw\"\"\"\nEvaluates the Boys function ``Fₘ(x) = ∫₀¹ t²ᵐ \\exp(-xt²) dt``.\n`IND==0` gives around 14 digits, `IND==1` around 6 and `IND==3` around 3.\n\"\"\"\nfunction boys(m::Int, x::T, IND=0) where T <: Real\n    x < 0 && throw(DomainError(x, \"`x` must be nonnegative.\"))\n    if x > 0\n        # gamma_inc returns tuple of incomplete Γ function ratios,\n        # we only care about the first returned result\n        Px, _ = gamma_inc(m + 1 / T(2), x, IND)\n        1 / 2x^(m + 1 / T(2)) * gamma(m + 1 / T(2)) * Px\n    else\n        1 / T(2m + 1)\n    end\nend\n\n\nfunction doublefactorial(n::Integer)\n    n < 0 && throw(DomainError(n, \"`n` must be nonnegative.\"))\n    start = iseven(n) ? 2 : 1\n    f::typeof(n*n) = 1\n    for i::typeof(n*n) = start:2:n\n        f *= i\n    end\n    return f\nend\n", "meta": {"hexsha": "28849a443a2f385ff261b98381959af97f526165", "size": 805, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/special_functions.jl", "max_stars_repo_name": "mfherbst/ObaraSaika.jl", "max_stars_repo_head_hexsha": "091bbfa88d05b902770d74a7ef5f1d77964cae92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-15T18:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-08T12:28:37.000Z", "max_issues_repo_path": "src/special_functions.jl", "max_issues_repo_name": "mfherbst/ObaraSaika.jl", "max_issues_repo_head_hexsha": "091bbfa88d05b902770d74a7ef5f1d77964cae92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/special_functions.jl", "max_forks_repo_name": "mfherbst/ObaraSaika.jl", "max_forks_repo_head_hexsha": "091bbfa88d05b902770d74a7ef5f1d77964cae92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8333333333, "max_line_length": 73, "alphanum_fraction": 0.5614906832, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.789628734020743}}
{"text": "#! /usr/bin/julia\n\n# Rosetta Code, Arithmetic-geometric mean/Calculate Pi\n\nfunction agm_step{T<:FloatingPoint}(x::T, y::T)\n    (0.5*(x + y), sqrt(x*y))\nend\n\nfunction approx_pi_step{T<:FloatingPoint,U<:Integer}(x::T, y::T, z::T, n::U)\n    (a, g) = agm_step(x, y)\n    k = n + 1\n    s = z + 2^(k+1)*(a^2 - g^2)\n    return (a, g, s, k)\nend\n\nfunction approx_pi{T<:FloatingPoint}(a::T, g::T, s::T)\n    4a^2/(1 - s)\nend\n\nprec = 512\nset_bigfloat_precision(prec)\nprintln(\"Approximating pi using \", prec, \"-bit floats.\")\nprintln(\"   k     Error  Result\")\na = big(1.0)\ng = a/sqrt(big(2.0))\ns = big(0.0)\nk = 0\noldagpi = big(0.0)\nfor i in 1:100\n    (a, g, s, k) = approx_pi_step(a, g, s, k)\n    agpi = approx_pi(a, g, s)\n    2eps(agpi) < abs(agpi-oldagpi) || break\n    oldagpi = agpi\n    err = pi - agpi\n    print(@sprintf(\"  %2d \", i))\n    print(@sprintf(\" %9.1e\", err))\n    println(@sprintf(\" %.60e\", agpi))\nend\n\n\n", "meta": {"hexsha": "5cebd2a6cd2b36c7f1f6831c66e92614ad9c344a", "size": 903, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/completed/ag_mean_pi.jl", "max_stars_repo_name": "MichaeLeroy/rosetta-code", "max_stars_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/completed/ag_mean_pi.jl", "max_issues_repo_name": "MichaeLeroy/rosetta-code", "max_issues_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/completed/ag_mean_pi.jl", "max_forks_repo_name": "MichaeLeroy/rosetta-code", "max_forks_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0243902439, "max_line_length": 76, "alphanum_fraction": 0.5736434109, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7896287324541854}}
{"text": "\ninclude(\"../optimizers/linesearch.jl\")\ninclude(\"../utils/functions.jl\")\nusing Gadfly\n\nfunction optimize_linear_constraints(f, A, f_g, f_h, yinit=0)\n    \"\"\"\n    Convert constrained optimization problem min f(x) s.t. Ax = b \n        to unconstrained problem min g(y) = f(B*y + x0), where x0 is a solution to Ax = b\n        and B is a basis for the kernel of A.\n    \n    Defaults to using Newton's line search algorithm.\n    \n    f: constrained objective\n    A: constraint matrix\n    f_g: gradient of f\n    f_h: hessian of f\n    yinit: init y with a vector of all yinit values\n    \"\"\"\n    \n    m, n = size(A)\n    b = zeros(m)\n    x0 = A \\ b\n    B = nullspace(A)\n    \n    y0 = ones(size(B)[2]) .* yinit\n    \n    g(y) = f(B*y + x0)\n    g_g(y) = B' * f_g(B*y + x0)\n    g_h(y) = B' * f_h(B*y + x0) * B\n    \n    yvals = line_search(g, y0, g_g, g_h, \"newton\", 5000)\n    xvals = [B*y + x0 for y in yvals]\n    lambdas = [A' \\ f_g(x) for x in xvals]\n    \n    return yvals, xvals, lambdas\nend\n\nfunction generate_constraint_matrix(n)\n    A = ones(2,n)\n    for i in 1:n\n        if i % 2 == 1\n            A[2,i] = -1\n        end\n    end\n    return A\nend\n\nA = generate_constraint_matrix(30)\nb = zeros(2)\nx0 = A \\ b; B = nullspace(A)\nf = cute\nf_g = cute_g\nf_h = cute_h\ng(y) = f(B*y + x0)\ng_g(y) = B' * f_g(B*y + x0)\ng_h(y) = B' * f_h(B*y + x0) * B\n\nyvals, xvals, lambdas = optimize_linear_constraints(f, A, f_g, f_h, 0);\n\nniters = length(xvals)\nfx = [f(x) for x in xvals]\nGadfly.plot(x=1:niters, y=fx, Geom.line, \n    Guide.xlabel(\"iteration\"), Guide.ylabel(\"f(x)\"), Guide.title(\"Value of function\"),\n    Scale.x_log10, Scale.y_log10)\n\ngrads = [norm(g_g(y),2) for y in yvals]\nratios = grads[2:niters,:]./grads[1:niters-1,:]\nGadfly.plot(x=1:niters-1, y=ratios, Geom.line, \nGuide.xlabel(\"iteration\"), Guide.ylabel(\"f_g(x)\"), Guide.title(\"Gradient norm ratios\"),\n    Scale.x_log10, Scale.y_log10)\n\nGadfly.plot(x=1:niters, y=grads, Geom.line, \nGuide.xlabel(\"iteration\"), Guide.ylabel(\"f_g(x)\"), Guide.title(\"Gradient norm\"),\n    Scale.x_log10, Scale.y_log10)\n\n# Lagrange multipliers\nlambdas[end]\n\nA = generate_constraint_matrix(100)\nx0 = A \\ b; B = nullspace(A)\nf = cute\nf_g = cute_g\nf_h = cute_h\ng(y) = f(B*y + x0)\ng_g(y) = B' * f_g(B*y + x0)\ng_h(y) = B' * f_h(B*y + x0) * B\n\nyvals, xvals, lambdas = optimize_linear_constraints(f, A, f_g, f_h, 0);\n# Lagrange multipliers\nprintln(lambdas[end])\n# Final value\nprintln(f(xvals[end]))\n\nniters = length(xvals)\nfx = [f(x) for x in xvals]\n#gy = [g(y) for y in yvals]\n\nGadfly.plot(x=1:niters, y=fx, Geom.line, \n    Guide.xlabel(\"iteration\"), Guide.ylabel(\"f(x)\"), Guide.title(\"Value of function\"),\n    Scale.x_log10, Scale.y_log10)\n\ngrads = [norm(g_g(y),2) for y in yvals]\nratios = grads[2:niters,:]./grads[1:niters-1,:]\nGadfly.plot(x=1:niters-1, y=ratios, Geom.line, \nGuide.xlabel(\"iteration\"), Guide.ylabel(\"f_g(x)\"), Guide.title(\"Gradient norm ratios\"),\n    Scale.x_log10, Scale.y_log10)\n\nGadfly.plot(x=1:niters, y=grads, Geom.line, \nGuide.xlabel(\"iteration\"), Guide.ylabel(\"f_g(x)\"), Guide.title(\"Gradient norm\"),\n    Scale.x_log10, Scale.y_log10)\n\n\n", "meta": {"hexsha": "71ae72f853d0121f5fbdbd4cc98bb8a2bccd31a2", "size": 3075, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jupyter/linear_constraints.jl", "max_stars_repo_name": "dicai/descent.jl", "max_stars_repo_head_hexsha": "f684b69f6c8dadc86402fc465455b51c0484cedf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-08-12T22:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-25T01:37:28.000Z", "max_issues_repo_path": "jupyter/linear_constraints.jl", "max_issues_repo_name": "dicai/descent.jl", "max_issues_repo_head_hexsha": "f684b69f6c8dadc86402fc465455b51c0484cedf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jupyter/linear_constraints.jl", "max_forks_repo_name": "dicai/descent.jl", "max_forks_repo_head_hexsha": "f684b69f6c8dadc86402fc465455b51c0484cedf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9736842105, "max_line_length": 89, "alphanum_fraction": 0.6260162602, "num_tokens": 1076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308054739519, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7896287324541853}}
{"text": "abstract type AbstractUtility end\n\n#\n# Separable utility\n#\n\n# Consumption utility\n\n@doc doc\"\"\"\nType used to evaluate log utility. Log utility takes the form\n\nu(c) = \\log(c)\n\nAdditionally, this code assumes that if c < 1e-10 then\n\nu(c) = log(1e-10) + 1e10*(c - 1e-10)\n\n\"\"\"\nstruct LogUtility <: AbstractUtility\n    ξ::Float64\nend\n\nLogUtility() = LogUtility(1.0)\n\n(u::LogUtility)(c::Float64) =\n    c > 1e-10 ? u.ξ*log(c) : u.ξ*(log(1e-10) + 1e10*(c - 1e-10))\nderivative(u::LogUtility, c::Float64) =\n    c > 1e-10 ? u.ξ / c : u.ξ*1e10\n\n\"\"\"\nType used to evaluate CRRA utility. CRRA utility takes the form\n\nu(c) = ξ c^(1 - γ) / (1 - γ)\n\nAdditionally, this code assumes that if c < 1e-10 then\n\nu(c) = ξ (1e-10^(1 - γ) / (1 - γ) + 1e-10^(-γ) * (c - 1e-10))\n\"\"\"\nstruct CRRAUtility <: AbstractUtility\n    γ::Float64\n    ξ::Float64\n\n    function CRRAUtility(γ, ξ=1.0)\n        if abs(γ - 1.0) < 1e-8\n            error(\"Your value for γ is very close to 1... Consider using LogUtility\")\n        end\n\n        return new(γ, ξ)\n    end\nend\n\n(u::CRRAUtility)(c::Float64) =\n    c > 1e-10 ?\n           u.ξ * (c^(1.0 - u.γ) - 1.0) / (1.0 - u.γ) :\n           u.ξ * ((1e-10^(1.0 - u.γ) - 1.0) / (1.0 - u.γ) + 1e-10^(-u.γ)*(c - 1e-10))\nderivative(u::CRRAUtility, c::Float64) =\n    c > 1e-10 ? u.ξ * c^(-u.γ) : u.ξ*1e-10^(-u.γ)\n\n\n# Labor Utility\n\n\"\"\"\nType used to evaluate constant Frisch elasticity (CFE) utility. CFE\nutility takes the form\n\nv(l) = ξ l^(1 + 1/ϕ) / (1 + 1/ϕ)\n\nAdditionally, this code assumes that if l < 1e-10 then\n\nv(l) = ξ (1e-10^(1 + 1/ϕ) / (1 + 1/ϕ) - 1e-10^(1/ϕ) * (1e-10 - l))\n\"\"\"\nstruct CFEUtility <: AbstractUtility\n    ϕ::Float64\n    ξ::Float64\n\n    function CFEUtility(ϕ, ξ=1.0)\n        if abs(ϕ - 1.0) < 1e-8\n            error(\"Your value for ϕ is very close to 1... Consider using LogUtility\")\n        end\n\n        return new(ϕ, ξ)\n    end\nend\n\n(u::CFEUtility)(l::Float64) =\n    l > 1e-10 ?\n           -u.ξ * l^(1.0 + 1.0/u.ϕ)/(1.0 + 1.0/u.ϕ) :\n           -u.ξ * (1e-10^(1.0 + 1.0/u.ϕ)/(1.0 + 1.0/u.ϕ) + 1e-10^(1.0/u.ϕ) * (l - 1e-10))\nderivative(u::CFEUtility, l::Float64) =\n    l > 1e-10 ? -u.ξ * l^(1.0/u.ϕ) : -u.ξ * 1e-10^(1.0/u.ϕ)\n\n\n\"\"\"\nType used to evaluate elliptical utility function. Elliptical utility takes form\n\nv(l) = b (1 - l^μ)^(1 / μ)\n\"\"\"\nstruct EllipticalUtility <: AbstractUtility\n    b::Float64\n    μ::Float64\nend\n\n# These defaults are pulled straight from Evans Phillips 2017\nEllipticalUtility(;b=0.5223, μ=2.2926) = EllipticalUtility(b, μ)\n\n(u::EllipticalUtility)(l::Float64) =\n    u.b * (1.0 - l^u.μ)^(1.0 / u.μ)\nderivative(u::EllipticalUtility, l::Float64) =\n    -u.b * (1.0 - l^u.μ)^(1.0/u.μ - 1.0) * l^(u.μ - 1.0)\n", "meta": {"hexsha": "797ba7e0a69f31e119c1fd50a416067ba43a2f7c", "size": 2643, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/modeltools/utility.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/QuantEcon.jl-fcd29c91-0bd7-5a09-975d-7ac3f643a60c", "max_stars_repo_head_hexsha": "ff4697f2be73edbc905373fdf268056bdc93d129", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 455, "max_stars_repo_stars_event_min_datetime": "2015-01-16T18:10:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T20:08:45.000Z", "max_issues_repo_path": "src/modeltools/utility.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/QuantEcon.jl-fcd29c91-0bd7-5a09-975d-7ac3f643a60c", "max_issues_repo_head_hexsha": "ff4697f2be73edbc905373fdf268056bdc93d129", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 236, "max_issues_repo_issues_event_min_datetime": "2015-01-26T20:56:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T15:19:56.000Z", "max_forks_repo_path": "src/modeltools/utility.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/QuantEcon.jl-fcd29c91-0bd7-5a09-975d-7ac3f643a60c", "max_forks_repo_head_hexsha": "ff4697f2be73edbc905373fdf268056bdc93d129", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 364, "max_forks_repo_forks_event_min_datetime": "2015-01-15T18:04:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T21:24:53.000Z", "avg_line_length": 24.0272727273, "max_line_length": 89, "alphanum_fraction": 0.5660234582, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8459424295406087, "lm_q1q2_score": 0.7896287280903547}}
{"text": "# Julia translation of http://nbviewer.jupyter.org/github/barbagroup/AeroPython/blob/master/lessons/04_Lesson04_vortex.ipynb\n# Lesson 3 doublet\n\nusing PyPlot\nusing Distributions\n\nclose(\"all\")\nmeshgrid(x,y) = (repmat(x',length(y),1),repmat(y,1,length(x)))\n\nN = 50                                # number of points in each direction\nx_start, x_end = -2.0, 2.0            # boundaries in the x-direction\ny_start, y_end = -1.0, 1.0            # boundaries in the y-direction\nx = linspace(x_start, x_end, N)    # creates a 1D-array with the x-coordinates\ny = linspace(y_start, y_end, N)    # creates a 1D-array with the y-coordinates\n\nX,Y=meshgrid(x,y)\n\ngamma = 5.0\n\nx_vortex, y_vortex = 0.0, 0.0   # location of the source\n\nfunction get_velocity_vortex(strength, xv, yv, X, Y):\n      \"\"\"Returns the velocity field generated by a vortex.\n\n      Arguments\n      ---------\n      strength -- strength of the vortex.\n      xv, yv -- coordinates of the vortex.\n      X, Y -- mesh grid.\n      \"\"\"\n      u = + strength/(2*pi).*(Y-yv)./((X-xv).^2+(Y-yv).^2)\n      v = - strength/(2*pi).*(X-xv)./((X-xv).^2+(Y-yv).^2)\n\n      return u, v\n    end\n\nfunction get_stream_function_vortex(strength, xv, yv, X, Y):\n    \"\"\"Returns the stream-function generated by a vortex.\n\n    Arguments\n    ---------\n    strength -- strength of the vortex.\n    xv, yv -- coordinates of the vortex.\n    X, Y -- mesh grid.\n    \"\"\"\n    psi = strength/(4*pi).*log((X-xv).^2+(Y-yv).^2)\n\n    return psi\n  end\n\n\n  # computes the velocity field on the mesh grid\n  u_vortex, v_vortex = get_velocity_vortex(gamma, x_vortex, y_vortex, X, Y)\n\n  # computes the stream-function on the mesh grid\n  psi_vortex = get_stream_function_vortex(gamma, x_vortex, y_vortex, X, Y)\n\n  # plots the streamlines\n  size = 10\n  PyPlot.figure(figsize=(size, (y_end-y_start)/(x_end-x_start)*size))\n  PyPlot.grid(true)\n  PyPlot.xlabel(\"x\", fontsize=16)\n  PyPlot.ylabel(\"y\", fontsize=16)\n  PyPlot.xlim(x_start, x_end)\n  PyPlot.ylim(y_start, y_end)\n  PyPlot.streamplot(X, Y, u_vortex, v_vortex, density=2, linewidth=1, arrowsize=1, arrowstyle=\"->\")\n  PyPlot.scatter(x_vortex, y_vortex, color=\"#CD2305\", s=80, marker=\"o\")\n\n\n\nstrength_sink = -1.0            # strength of the sink\nx_sink, y_sink = 0.0, 0.0       # location of the sink\n\nfunction get_velocity_sink(strength, xs, ys, X, Y):\n    \"\"\"Returns the velocity field generated by a sink.\n\n    Arguments\n    ---------\n    strength -- strength of the sink.\n    xs, ys -- coordinates of the sink.\n    X, Y -- mesh grid.\n    \"\"\"\n    u = strength/(2*pi).*(X-xs)./((X-xs).^2+(Y-ys).^2)\n    v = strength/(2*pi).*(Y-ys)./((X-xs).^2+(Y-ys).^2)\n\n    return u, v\n  end\n\nfunction get_stream_function_sink(strength, xs, ys, X, Y):\n      \"\"\"Returns the stream-function generated by a sink.\n\n      Arguments\n      ---------\n      strength -- strength of the sink.\n      xs, ys -- coordinates of the sink.\n      X, Y -- mesh grid.\n      \"\"\"\n      psi = strength/(2*pi)*atan2((Y-ys), (X-xs))\n\n      return psi\n    end\n\n    # computes the velocity field on the mesh grid\nu_sink, v_sink = get_velocity_sink(strength_sink, x_sink, y_sink, X, Y)\n\n# computes the stream-function on the mesh grid\npsi_sink = get_stream_function_sink(strength_sink, x_sink, y_sink, X, Y)\n\n# superposition of the sink and the vortex\nu = u_vortex + u_sink\nv = v_vortex + v_sink\npsi = psi_vortex + psi_sink\n\n# plots the streamlines\nsize = 10\nPyPlot.figure(figsize=(size, (y_end-y_start)/(x_end-x_start)*size))\nPyPlot.xlabel(\"x\", fontsize=16)\nPyPlot.ylabel(\"y\", fontsize=16)\nPyPlot.xlim(x_start, x_end)\nPyPlot.ylim(y_start, y_end)\nPyPlot.streamplot(X, Y, u, v, density=2, linewidth=1, arrowsize=1, arrowstyle=\"->\")\nPyPlot.scatter(x_vortex, y_vortex, color=\"#CD2305\", s=80, marker=\"o\");\n", "meta": {"hexsha": "d6585e081b6de8004ecdd04a7e654d63a1ea97d3", "size": 3722, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Lesson4_Vortex.jl", "max_stars_repo_name": "moore54/JuliaPotentialFlowTranslations", "max_stars_repo_head_hexsha": "2aad7750c23057518ca988ba4a02a4c99f4fde5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lesson4_Vortex.jl", "max_issues_repo_name": "moore54/JuliaPotentialFlowTranslations", "max_issues_repo_head_hexsha": "2aad7750c23057518ca988ba4a02a4c99f4fde5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lesson4_Vortex.jl", "max_forks_repo_name": "moore54/JuliaPotentialFlowTranslations", "max_forks_repo_head_hexsha": "2aad7750c23057518ca988ba4a02a4c99f4fde5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2601626016, "max_line_length": 124, "alphanum_fraction": 0.6429339065, "num_tokens": 1129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308054739519, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7896287270160834}}
{"text": "using JuMP\nusing Ipopt\nusing CSV, DataFrames, DataStructures, MathOptFormat\nusing Statistics,Distributions, StatsFuns, StatsBase\nusing PyPlot\n\n\nfunction critical_fractile(dist_type)\n    #closed form of solution for newsvendor for normal distribution\n    # dist_type - str, \"norm\" or \"exp\" for normal or exponential distribution, respectively\n    \n    b = 1 #underage cost\n    h = 1 #overage cost\n    \n    if dist_type == \"norm\"\n        mean = 50\n        var = 50\n\n        beta = b/(b+h)\n        \n        b_inv = norminvcdf(beta) #inverse of the cdf for normal distribution \n        \n        return mean + b_inv * var\n        \n    elseif dist_type == \"exp\"\n        # plugged and chugged with cdf of exponential function to get warm start value (solver kept converging to point of infeasibility)\n        cdf_func(x) = cdf(Exponential(50),x)\n        \n        # print(cdf_func(34.65))\n        \n        model3 = Model(with_optimizer(Ipopt.Optimizer,print_level=0))\n\n        @variable(model3, x_var, start=34) #use warm start to avoid converge to infeasible point (see above)\n\n        JuMP.register(model3, :cdf_func, 1, cdf_func; autodiff = true)  #to use cdf function in constraint\n\n        @NLconstraint(model3,con1, cdf_func(x_var) >= b/(b+h))\n\n        @objective(model3,Min,x_var)\n        optimize!(model3)\n\n        return value(x_var)\n        \n    else\n        return nothing \n    end\nend\n\nfunction scarf(df)\n    #closed form scarf solution\n    # df - dataframe, data of observed demand \n    \n    b = 1 #underage cost\n    h = 1 #overage cost\n    \n    mu_hat = mean(df[:,\"Column1\"]) #sample mean\n    sigma_sq_hat = var(df[:,\"Column1\"]) #sample variance\n    \n    return mu_hat + sigma_sq_hat/2 * (sqrt(b / h) - sqrt(h / b))\nend\n\n\nfunction SAA(df)\n    # compute SAA solution (empirical risk minimization)\n    # df - dataframe, data of observed demand \n    \n    b = 1 #underage cost\n    h = 1 #overage cost\n    \n    model = Model(with_optimizer(Ipopt.Optimizer,print_level=0))\n\n    data_size = length(df[:,\"Column1\"])\n\n    @variable(model, x_var) #stocking quantity \n    @variable(model, y_vars[1:data_size]) #variable to linearize max(d_i - x, x - d_i) in objective function\n\n    @constraint(model,con1[i = 1:data_size], y_vars[i] >= x_var - df[:,\"Column1\"][i])\n    @constraint(model, con2[i = 1:data_size], y_vars[i] >= df[:,\"Column1\"][i] - x_var )\n\n    @NLobjective(model,Min, 1 / data_size * sum(y_vars[i] for i = 1:data_size))\n    \n    optimize!(model)\n    \n    return value(x_var)\nend", "meta": {"hexsha": "96bd58b61a5630f771b788a5adeca99cbb11550a", "size": 2486, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "non_DRO_methods.jl", "max_stars_repo_name": "cmjohnston39/DSO670_Final_Project", "max_stars_repo_head_hexsha": "a06fe91bbf6270180d0f59049844bb04ad4c9744", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "non_DRO_methods.jl", "max_issues_repo_name": "cmjohnston39/DSO670_Final_Project", "max_issues_repo_head_hexsha": "a06fe91bbf6270180d0f59049844bb04ad4c9744", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "non_DRO_methods.jl", "max_forks_repo_name": "cmjohnston39/DSO670_Final_Project", "max_forks_repo_head_hexsha": "a06fe91bbf6270180d0f59049844bb04ad4c9744", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2470588235, "max_line_length": 137, "alphanum_fraction": 0.6379726468, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741322079104, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7896256680029958}}
{"text": "\nusing DifferentialEquations\nusing ModelingToolkit\nusing OrdinaryDiffEq\nusing DataFrames\nusing DataFrames\nusing StatsPlots\nusing BenchmarkTools\n\n\n@parameters t β c γ\n@variables S(t) I(t) R(t)\n@derivatives D'~t\nN=S+I+R # This is recognized as a derived variable\neqs = [D(S) ~ -β*c*I/N*S,\n       D(I) ~ β*c*I/N*S-γ*I,\n       D(R) ~ γ*I];\n\n\nsys = ODESystem(eqs)\nsys = ode_order_lowering(sys);\n\n\nδt = 0.1\ntmax = 40.0\ntspan = (0.0,tmax)\nt = 0.0:δt:tmax;\n\n\nu0 = [S => 990.0,\n      I => 10.0,\n      R => 0.0];\n\n\np = [β=>0.05,\n     c=>10.0,\n     γ=>0.25];\n\n\nprob_ode = ODEProblem(sys,u0,tspan,p;jac=true)\n\n\nsol_ode = solve(prob_ode);\n\n\ndf_ode = DataFrame(sol_ode(t)')\ndf_ode[!,:t] = t;\n\n\n@df df_ode plot(:t,\n    [:x1 :x2 :x3],\n    label=[\"S\" \"I\" \"R\"],\n    xlabel=\"Time\",\n    ylabel=\"Number\")\n\n\n@benchmark solve(prob_ode)\n\n\ninclude(joinpath(@__DIR__,\"tutorials\",\"appendix.jl\"))\nappendix()\n\n", "meta": {"hexsha": "69c2b7f3578cf2a0d0f56336f9d0233afee78822", "size": 881, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_mtk/ode_mtk.jl", "max_stars_repo_name": "ChrisRackauckas/sir-julia", "max_stars_repo_head_hexsha": "688271620f442634617dc8ce8a35b0f370bda7c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/ode_mtk/ode_mtk.jl", "max_issues_repo_name": "ChrisRackauckas/sir-julia", "max_issues_repo_head_hexsha": "688271620f442634617dc8ce8a35b0f370bda7c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/ode_mtk/ode_mtk.jl", "max_forks_repo_name": "ChrisRackauckas/sir-julia", "max_forks_repo_head_hexsha": "688271620f442634617dc8ce8a35b0f370bda7c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.9841269841, "max_line_length": 53, "alphanum_fraction": 0.608399546, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574129515172, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7896256637581165}}
{"text": "function generate_primes(target)\n    primes = [2]\n    i = 3\n\n    while length(primes) != target\n        square_root = sqrt(i)\n        for prime in primes\n\n            if prime > square_root\n                push!(primes, i)\n                break\n            end\n\n            if i % prime == 0\n                break\n            end\n\n        end\n        i += 2\n    end\n\n    return primes[end]\nend\n\nprintln(generate_primes(10001))\n", "meta": {"hexsha": "c98dcf4dfa954b9b0a98c994c45b31c3db8c7ece", "size": 427, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/problem_7.jl", "max_stars_repo_name": "HarrisonGreen/Project-Euler-Solutions", "max_stars_repo_head_hexsha": "e2599e406c8a1c997bf620e1c35045303b12091e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Julia/problem_7.jl", "max_issues_repo_name": "HarrisonGreen/Project-Euler-Solutions", "max_issues_repo_head_hexsha": "e2599e406c8a1c997bf620e1c35045303b12091e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/problem_7.jl", "max_forks_repo_name": "HarrisonGreen/Project-Euler-Solutions", "max_forks_repo_head_hexsha": "e2599e406c8a1c997bf620e1c35045303b12091e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.4230769231, "max_line_length": 34, "alphanum_fraction": 0.4683840749, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741295151718, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7896256617453523}}
{"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 9af04825-842b-4794-a317-6f1b78a64fb5\nbegin\n\tusing Statistics, CSV, DataFrames\n\tusing ForwardDiff\nend\n\n# ╔═╡ be7baa4f-6871-4d74-b4d2-1c2534cdfa17\n# Row Orientation\nbegin\n\tusing Random\n\tRandom.seed!(0)\n\t\n\tstruct Layer_dense\n\t\tw::Matrix{Float64}\n\t\tb::Matrix{Float64}\n\t\tσ::Function\n\t\n\t\tfunction Layer_dense(n_in::Int, n_out::Int; σ::Function = identity)\n\t\t\tw = 0.01 .* randn(n_out, n_in)\n\t\t\tb = reshape(zeros(n_out), (1, n_out)) \n\t\t\treturn new(w, b, σ)\n\t\tend\n\tend\n\n\tfunction (L::Layer_dense)(input) \n\t\tW, b, σ = L.w, L.b, L.σ\n\t\tσ( (input * W') .+ b )\n\tend\nend\n\n# ╔═╡ c4ea1432-abb4-11eb-1cf5-edac0735d67d\nmd\"# LayerDense\"\n\n# ╔═╡ 45d31083-883b-4e84-913e-c040c6fdfd5f\nmd\"\"\"\n>No futuro, podemos pensar em novas formas de fazer esse objeto. Por exemplo, passando a matriz W como input construtor do layer.\n\"\"\"\n\n# ╔═╡ dc76be1b-292e-4545-887e-1e62faf8e1b6\nmd\"\"\"\n### Struct by Column Orientation\n\"\"\"\n\n# ╔═╡ fe237f5f-8f90-429a-8ddc-e5933b8fd808\nbegin\n\tRandom.seed!(0)\n\t\n\tstruct LayerDense{T<:Real, F<:Function}\n\t\tW::Matrix{T}\n\t\tb::Vector{T}\n\t\tσ::F\n\n\t\tfunction LayerDense(W::Matrix{T}, \n\t\t\t\t\t\t\tb::Vector{T}, \n\t\t\t\t\t\t\tσ::Function = identity) where {T<:Real}                \n\t\t\t@assert size(W, 1) == length(b)\n\n\t\t\tnew{T, typeof(σ)}(W, b, σ)\n\t\tend\n\tend\n\n\tfunction LayerDense(W::Matrix{T}, \n\t\t\t\t\t\tb::Vector{S}, \n\t\t\t\t\t\tσ::Function = identity) where {T<:Real, S<:Real}\n\t\tR = promote_type(T, S)\n\t\treturn LayerDense(Matrix{R}(W), Vector{R}(b), σ)\n\tend\n\n\tfunction LayerDense(W::Matrix{T}, σ::Function = identity) where {T<:Real}\n\t\tb = zeros(T, size(W, 1))\n\t\treturn LayerDense(W, b, σ)\n\tend\n\n\tfunction LayerDense(n_in::Int, n_out::Int, σ::Function = identity)\n\t\tW = 0.01 * randn(n_out, n_in)\n\t\tb = zeros(n_out) \n\t\treturn LayerDense(W, b, σ)\n\tend\n\n\tfunction (L::LayerDense)(input::AbstractVector{<:Real})\n\t\tW, b, σ = L.W, L.b, L.σ\n\t\treturn σ(W * input + b)\n\tend\n\n\tfunction (L::LayerDense)(input::AbstractMatrix{<:Real})\n\t\tW, b, σ = L.W, L.b, L.σ\n\t\treturn σ(W * input .+ b)\n\tend\nend\n\n# ╔═╡ 4e6d165a-9707-4029-af4a-2356b0fe9c41\nmd\"#### Example using the struct LayerDense\"\n\n# ╔═╡ 5d3ae0e6-7c5d-48b7-9845-d204a1df9934\nW = rand(3, 4)\n\n# ╔═╡ e85bc0f7-65ab-4a41-a4ba-e63c8b7c8184\nB = LayerDense(W) # Layer de 4 inputs e 3 outputs\n\n# ╔═╡ 142bb8f9-4188-46d2-94a2-8407d633c496\nbegin\n\tobs01 = [2, 3, 4, 5]\n\tobs02 = [2, 3, 4, 5]\n\tinput = [obs01 obs02] # Each observation must be on a colunm\nend \n\n# ╔═╡ 2377f014-0bd0-457b-b9e9-3ace1ad7c331\nB(input) # Each column is an output\n\n# ╔═╡ c99c7f4f-7e62-4036-ba08-4478e5480d19\nmd\"#### Adding sigmoid functions\"\n\n# ╔═╡ 96ce3aa7-9261-4e60-93ce-4d9321657d85\nmd\"\"\"\nFunção **Logística**: \\\n$$\\;\\;\\;\\;\\;$$ $$\\sigma(x) = {1 \\over 1 + e^{-x}}$$ \n\nNa implementação via código é necessário fazer uma adaptação que evita problemas numéricos de *Overflow* resultando na seguinte função: \\\n$$\\sigma(x) = \\left\\{\n  \\begin{array}{lr}\n    {1 \\over 1 + e^{-|x|}}, & x \\ge 0\\\\\n    {e^{-|x|} \\over 1 + e^{-|x|}}, & x < 0\n  \\end{array}\n\\right.$$ \\\n\n\nPara isso, utilizamos o módulo de $$x$$ na expressão $$e^{-|x|}$$ que possui a seguinte propriedade: \\\n$$e^{-|x|} = \\left\\{\n  \\begin{array}{lr}\n    e^{-x}, & x \\ge 0\\\\\n    e^x, & x < 0\n  \\end{array}\n\\right.$$ \n\nCom o modulo, quando x é positivo ou zero ($$x ≥ 0$$) a adaptação resulta na própria função logística, mas quando x é negativo são necessários os seguintes passos: \\\n$$Se \\space x \\ge 0:$$  $$\\;\\;\\;\\;\\;$$  $$\\sigma(x) = {1 \\over 1 + e^{-|x|}}$$ \\\n$$Se \\space x < 0:$$ $$\\;\\;\\;\\;\\;$$ $$1 = e^{-x} ⋅ e^x → {1 \\over 1 + e^{-x}} = {e^{-x} ⋅ e^x \\over e^{-x} ⋅ e^x + e^{-x}} = {e^{-x} ⋅ e^x \\over e^{-x}(e^x + 1)} = {e^x \\over 1 + e^x} = {e^{-|x|} \\over 1 + e^{-|x|}}$$\n\"\"\"\n\n# ╔═╡ 58265283-a36a-4c83-9101-3387165da021\nbegin\n\tfunction σ(x::Real) \n\t\tt = exp(-abs(x))\n\t\treturn ifelse(x ≥ 0, inv(1 + t), t / (1 + t))\n\tend\t\n\t\n\tσ(x::AbstractVecOrMat{T}) where {T<:Real} = σ.(x)\n\t\n\tconst sigmoid = σ\nend\n\n# ╔═╡ fc1ddc84-62dc-4af1-9b9e-9d37f581a252\nmd\"\"\"\n#### ReLU function\n$$ReLU(x) = \\left\\{\n  \\begin{array}{lr}\n    x, & x \\ge 0\\\\\n    0, & x < 0\n  \\end{array}\n\\right.$$\n$$Or$$\n$$ReLU(x) = max(0, x)$$\n\"\"\"\n\n# ╔═╡ 45bafada-34ec-4c41-b0a2-000f35ebffef\nbegin\n\trelu(x::Real) = max(zero(x), x) # zero function keep the type of x\n\trelu(x::AbstractVecOrMat{<:Real}) = relu.(x)\nend\n\n# ╔═╡ c85cd202-7223-4c46-80ef-afd750f28ead\nmd\"\"\"\n$$softplus(x) = ln(1 + e^x)$$\n$$For \\space x > 0:$$\n$$1 = e^{-x} ⋅ e^x → ln(1 + e^x) = ln(e^{-x} ⋅ e^x + e^x) = ln(e^x(e^{-x} + 1)) = ln(e^x) + ln(1 + e^{-x})$$\n$$softplus(x) = x + ln(1 + e^{-x})$$\n\"\"\"\n\n# ╔═╡ d6fce490-1498-469d-8ecc-55d0a71d1565\nbegin\n\t#log1p(x) is the seme as log(1 + x)\n\tsoftplus(x::Real) = ifelse(x > 0, x + log(1 + exp(-x)), log(1 + exp(x)))\n\tsoftplus(x::AbstractVecOrMat{<:Real}) = softplus.(x)\nend\n\n# ╔═╡ 04cadf6a-4fd1-4b5f-aa4d-140ea6e5cff2\nfunction softmax(x::Vector{T}) where {T<:Real}\n\tm = maximum(x)\n\texp_val = exp.(x .- m)\n\ts = sum(exp_val)\n\treturn exp_val ./ s\nend\n\n# ╔═╡ a7898ffd-1acb-4220-bbc8-3b428b95db85\nfunction softmax(x::Matrix{T}) where {T<:Real}\n\tm = maximum(x, dims = 1)\n\texp_val = exp.(x .- m)\n\ts = sum(exp_val, dims = 1)\n\treturn exp_val ./ s\nend\n\n# ╔═╡ c116a1e4-fd4d-446f-bdea-02301f43b2c0\nmd\"##### Example with sigmoid functions\"\n\n# ╔═╡ d0c91a1c-8798-4985-978b-4c47d1abc212\nC = LayerDense(2, 3, σ)\n\n# ╔═╡ 3de0841e-f0f3-436c-a891-dd4af32d2af6\n# C(randn(2, 3))\nC([[1, 4] [2, 3] [3, 5]])\n\n# ╔═╡ 963f6276-2440-4bfe-ae0f-539d8bfae0a2\nD = LayerDense(2, 3, softmax)\n\n# ╔═╡ 56191b0c-fe49-4ed4-9ca7-2e22e7b028ba\nmd\"\"\"\n#### Cost Function\n\"\"\"\n\n# ╔═╡ 7b5a6859-a9e1-48b1-a0fd-1cde06249d03\nbegin\n\tfunction xlogy(x::Real, y::Real) \n\t\tresult = x * log(y)\n\t\tifelse(iszero(x) && !isnan(y), zero(result), result)\n\tend\n\t\n\tfunction crossentropy(ŷ::AbstractVecOrMat{<:Real},\n\t\t\t\t\t\t  y::AbstractVecOrMat{<:Real};\n\t\t\t\t\t\t  dims::Int = 1,\n\t\t\t\t\t\t  agg::Function = mean)\n    \tagg(.-sum(xlogy.(y, ŷ), dims = dims))\n\tend\nend\n\n# ╔═╡ 4b070348-fdbc-46cd-85f0-29b64432ae21\nbegin\n\toutp2 = D([1 4; 2 3; 3 5]')\n\ttarget2 = [0, 1, 0]\n\tcrossentropy(outp2, target2)\nend\n\n# ╔═╡ e3ec0333-14ad-42a8-9cd3-4e3937dc5ff0\nbegin\n\toutp1 = [0.7 0.1 0.2\n\t\t\t 0.1 0.5 0.4\n\t   \t\t 0.02 0.9 0.08]'\n\ttarget1 = [1 0 0\n\t\t\t   0 1 0\n\t\t  \t   0 1 0]'\n\tcrossentropy(outp1, target1)\nend\n\n# ╔═╡ 8f3cbc01-53ba-4ff0-8245-564f8fee53f2\nmd\"##### Importing data from nnfs python package\"\n\n# ╔═╡ 099f5fa8-6687-4c77-9f61-119d75377bab\ndata = CSV.read(\"spiral_data.csv\", DataFrame)\n\n# ╔═╡ b5981a68-16e7-451f-9e13-d74b2b78a958\nmd\"#### Chain type, params(), gradient()\"\n\n# ╔═╡ d2fa0422-7f39-4365-8f3b-bfa6997ae0ae\nbegin\n\tRandom.seed!(1998)\n\t\n\tL1 = LayerDense(10, 5, σ)\n\tL2 = LayerDense(5, 2, softmax)\n\t\n\toutput = L2(L1(rand(10)))\nend\n\n# ╔═╡ 72f68243-8ae1-465c-854d-a76c07c5e346\nfunction params(layers)\n\tp = []\n\tfor layer in layers\n\t\tpush!(p, layer.W[:], layer.b )\n\tend\n\treturn vcat(p...)\nend\n\n# ╔═╡ e84cff98-1bea-42cb-8e8d-6f5ef08226f4\nbegin \n\tΘ = params([L1, L2])\n\t\n\tU = ( \n\t\tsize(L1.W, 1)*size(L1.W, 2), length(L1.b),\n\t\tsize(L2.W, 1)*size(L2.W, 2), length(L2.b),\n\t)\n\tU = cumsum(U)\n\t\n\tL1w = reshape( Θ[ 1:U[1] ], size(L1.W, 1), size(L1.W, 2))\n\t\n\tL1b = Θ[ U[1]+1:U[2] ]\n\t\n\tL2w = reshape( Θ[ U[2]+1:U[3] ], size(L2.W, 1), size(L2.W, 2))\n\t\n\tL2b = Θ[ U[3]+1:U[4] ]\n\t\n\t( length(Θ), U, (L1w, L1b, L2w, L2b) )\nend\n\n# ╔═╡ a5a511f7-38f0-4074-9192-7f11d611bf42\nbegin\n\t\n\tstruct Chain2\n\t\tLayers::Vector{LayerDense{Float64}}\n\t\tWl::Vector{Int}\n\t\tWc::Vector{Int}\n\t\tb::Vector{Int}\n\t\t\n\t\tfunction Chain(L...)\n\t\t\tWl = Int[]\n\t\t\tWc = Int[]\n\t\t\tb = Int[]\n\t\t\tfor (i, l) in enumerate(L)\n\t\t\t\tWl[i], Wc[i] = size(l.W)\n\t\t\t\tb[i] = length(l.b)\n\t\t\tend\n\t\t\treturn new{}(L, Wl, Wc, b)\n\t\tend\n\n\tend\n\nend\n\n# ╔═╡ 154e4560-0769-429e-89bd-3b0392209d6d\ntypeof( (1.3,2.12) )\n\n# ╔═╡ 74ccd8c6-f513-4178-a41f-7b70835516e7\nbegin\n\tstruct Chain{T<:Tuple}\n\t\tlayers::T\n\t\tChain(layers...) = new{typeof(layers)}(layers)\t\t\n\tend\n\t\n\tfunction (L::Chain)(input::AbstractVecOrMat{<:Real})\n\t\treturn ∘(reverse(L.layers)...)(input)\n\tend\nend\n\n# ╔═╡ 4504eaff-0c86-4606-a410-c94a8e8a653e\nbegin\n\t#L1 = LayerDense(10, 5, σ)\n\t#L2 = LayerDense(5, 2, softmax)\n\t\n\tC1 = Chain(L1, L2)\n\ttypeof(C1.layers)\nend\n\n# ╔═╡ ac678c79-a804-44e0-80d8-15a40dff327d\nbegin\n\tp = []\n\tfor layer in C1.layers\n\t\tpush!(p, layer.W[:], layer.b )\n\tend\n\tvcat(p...)\nend\n\n# ╔═╡ 4b019add-7eb4-496a-b0ef-3c3eee9d85bd\nbegin\n\tC1(rand(10,12))\nend\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nCSV = \"336ed68f-0bac-5ca0-87d4-7b16caf5d00b\"\nDataFrames = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nForwardDiff = \"f6369f11-7733-5829-9624-2563aa707210\"\nRandom = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\nStatistics = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[compat]\nCSV = \"~0.8.5\"\nDataFrames = \"~1.2.2\"\nForwardDiff = \"~0.10.19\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[CSV]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"PooledArrays\", \"SentinelArrays\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"b83aa3f513be680454437a0eee21001607e5d983\"\nuuid = \"336ed68f-0bac-5ca0-87d4-7b16caf5d00b\"\nversion = \"0.8.5\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"bdc0937269321858ab2a4f288486cb258b9a0af7\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.3.0\"\n\n[[CommonSubexpressions]]\ndeps = [\"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"7b8a93dba8af7e3b42fecabf646260105ac373f7\"\nuuid = \"bbf7d656-a473-5ed7-a52c-81e309532950\"\nversion = \"0.3.0\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"727e463cfebd0c7b999bbf3e9e7e16f254b94193\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.34.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Crayons]]\ngit-tree-sha1 = \"3f71217b538d7aaee0b69ab47d9b7724ca8afa0d\"\nuuid = \"a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f\"\nversion = \"4.0.4\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"ee400abb2298bd13bfc3df1c412ed228061a2385\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.7.0\"\n\n[[DataFrames]]\ndeps = [\"Compat\", \"DataAPI\", \"Future\", \"InvertedIndices\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"Markdown\", \"Missings\", \"PooledArrays\", \"PrettyTables\", \"Printf\", \"REPL\", \"Reexport\", \"SortingAlgorithms\", \"Statistics\", \"TableTraits\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"d785f42445b63fc86caa08bb9a9351008be9b765\"\nuuid = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nversion = \"1.2.2\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[DiffResults]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"c18e98cba888c6c25d1c3b048e4b3380ca956805\"\nuuid = \"163ba53b-c6d8-5494-b064-1a9d43ac40c5\"\nversion = \"1.0.3\"\n\n[[DiffRules]]\ndeps = [\"NaNMath\", \"Random\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"3ed8fa7178a10d1cd0f1ca524f249ba6937490c0\"\nuuid = \"b552c78f-8df3-52c6-915a-8e097449b14b\"\nversion = \"1.3.0\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"a32185f5428d3986f47c2ab78b1f216d5e6cc96f\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.5\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[ForwardDiff]]\ndeps = [\"CommonSubexpressions\", \"DiffResults\", \"DiffRules\", \"LinearAlgebra\", \"NaNMath\", \"Printf\", \"Random\", \"SpecialFunctions\", \"StaticArrays\"]\ngit-tree-sha1 = \"b5e930ac60b613ef3406da6d4f42c35d8dc51419\"\nuuid = \"f6369f11-7733-5829-9624-2563aa707210\"\nversion = \"0.10.19\"\n\n[[Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[InvertedIndices]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"15732c475062348b0165684ffe28e85ea8396afc\"\nuuid = \"41ab1584-1d38-5bbf-9106-f11c6c58b48f\"\nversion = \"1.0.0\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"f76424439413893a832026ca355fe273e93bce94\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"DocStringExtensions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"3d682c07e6dd250ed082f883dc88aee7996bf2cc\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.0\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"0fb723cd8c45858c22169b2e42269e53271a6df7\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.7\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"2ca267b08821e86c5ef4376cffed98a46c2cb205\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.1\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"bfd7d8c7fd87f04543810d9cbd3995972236ba1b\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"1.1.2\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PooledArrays]]\ndeps = [\"DataAPI\", \"Future\"]\ngit-tree-sha1 = \"a193d6ad9c45ada72c14b731a318bedd3c2f00cf\"\nuuid = \"2dfb63ee-cc39-5dd5-95bd-886bf059d720\"\nversion = \"1.3.0\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[PrettyTables]]\ndeps = [\"Crayons\", \"Formatting\", \"Markdown\", \"Reexport\", \"Tables\"]\ngit-tree-sha1 = \"0d1245a357cc61c8cd61934c07447aa569ff22e6\"\nuuid = \"08abe8d2-0d0c-5749-adfa-8a2ac140af0d\"\nversion = \"1.1.0\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[SentinelArrays]]\ndeps = [\"Dates\", \"Random\"]\ngit-tree-sha1 = \"54f37736d8934a12a200edea2f9206b03bdf3159\"\nuuid = \"91c51154-3ec4-41a3-a24f-3f23e20d615c\"\nversion = \"1.3.7\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"LogExpFunctions\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"a322a9493e49c5f3a10b50df3aedaf1cdb3244b7\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.6.1\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3240808c6d463ac46f1c1cd7638375cd22abbccb\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.12\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"d0c690d37c73aeb5ca063056283fde5585a41710\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.5.0\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─c4ea1432-abb4-11eb-1cf5-edac0735d67d\n# ╟─45d31083-883b-4e84-913e-c040c6fdfd5f\n# ╟─dc76be1b-292e-4545-887e-1e62faf8e1b6\n# ╠═fe237f5f-8f90-429a-8ddc-e5933b8fd808\n# ╟─4e6d165a-9707-4029-af4a-2356b0fe9c41\n# ╠═5d3ae0e6-7c5d-48b7-9845-d204a1df9934\n# ╠═e85bc0f7-65ab-4a41-a4ba-e63c8b7c8184\n# ╠═142bb8f9-4188-46d2-94a2-8407d633c496\n# ╠═2377f014-0bd0-457b-b9e9-3ace1ad7c331\n# ╟─c99c7f4f-7e62-4036-ba08-4478e5480d19\n# ╟─96ce3aa7-9261-4e60-93ce-4d9321657d85\n# ╠═58265283-a36a-4c83-9101-3387165da021\n# ╟─fc1ddc84-62dc-4af1-9b9e-9d37f581a252\n# ╠═45bafada-34ec-4c41-b0a2-000f35ebffef\n# ╟─c85cd202-7223-4c46-80ef-afd750f28ead\n# ╠═d6fce490-1498-469d-8ecc-55d0a71d1565\n# ╠═04cadf6a-4fd1-4b5f-aa4d-140ea6e5cff2\n# ╠═a7898ffd-1acb-4220-bbc8-3b428b95db85\n# ╟─c116a1e4-fd4d-446f-bdea-02301f43b2c0\n# ╠═d0c91a1c-8798-4985-978b-4c47d1abc212\n# ╠═3de0841e-f0f3-436c-a891-dd4af32d2af6\n# ╠═963f6276-2440-4bfe-ae0f-539d8bfae0a2\n# ╟─56191b0c-fe49-4ed4-9ca7-2e22e7b028ba\n# ╠═7b5a6859-a9e1-48b1-a0fd-1cde06249d03\n# ╠═4b070348-fdbc-46cd-85f0-29b64432ae21\n# ╠═e3ec0333-14ad-42a8-9cd3-4e3937dc5ff0\n# ╟─8f3cbc01-53ba-4ff0-8245-564f8fee53f2\n# ╟─099f5fa8-6687-4c77-9f61-119d75377bab\n# ╠═9af04825-842b-4794-a317-6f1b78a64fb5\n# ╟─b5981a68-16e7-451f-9e13-d74b2b78a958\n# ╠═d2fa0422-7f39-4365-8f3b-bfa6997ae0ae\n# ╠═ac678c79-a804-44e0-80d8-15a40dff327d\n# ╠═72f68243-8ae1-465c-854d-a76c07c5e346\n# ╠═e84cff98-1bea-42cb-8e8d-6f5ef08226f4\n# ╠═a5a511f7-38f0-4074-9192-7f11d611bf42\n# ╠═154e4560-0769-429e-89bd-3b0392209d6d\n# ╠═74ccd8c6-f513-4178-a41f-7b70835516e7\n# ╠═4504eaff-0c86-4606-a410-c94a8e8a653e\n# ╠═4b019add-7eb4-496a-b0ef-3c3eee9d85bd\n# ╟─be7baa4f-6871-4d74-b4d2-1c2534cdfa17\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "7690da51c0abb3ce6dc691e0cd565452248fd798", "size": 20786, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Layer_dense.jl", "max_stars_repo_name": "AugustoCL/Neural_Network_From_Scratch_in_Julia", "max_stars_repo_head_hexsha": "33f0f479c2e935b179306418e860dfa4e7cec07b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-20T16:40:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T16:40:27.000Z", "max_issues_repo_path": "Layer_dense.jl", "max_issues_repo_name": "AugustoCL/Neural_Network_From_Scratch_in_Julia", "max_issues_repo_head_hexsha": "33f0f479c2e935b179306418e860dfa4e7cec07b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Layer_dense.jl", "max_forks_repo_name": "AugustoCL/Neural_Network_From_Scratch_in_Julia", "max_forks_repo_head_hexsha": "33f0f479c2e935b179306418e860dfa4e7cec07b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5466155811, "max_line_length": 280, "alphanum_fraction": 0.6875781776, "num_tokens": 9829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.8740772466456689, "lm_q1q2_score": 0.7895489040046088}}
{"text": "export tanhActivation, tanhActivation!\n\n\"\"\"\n hyperbolic tan activation A = tanh(Y)\n\n Input:\n\n   Y - array of features\n\n Optional Input:\n\n   doDerivative - flag for computing derivative, set via varargin\n                  Ex: tanhActivation(Y,true);\n\n Output:\n\n  A  - activation\n  dA - derivatives\n\"\"\"\nfunction tanhActivation(Y::Array{T,2},doDerivative::Bool=false) where {T <: Number}\n\n    A = tanh.(Y)\n    dA = zeros(A)\n    if doDerivative\n         dA .= one(T) .- A.^2\n    end\n    return A, dA\nend\n\nfunction tanhActivation!(A::Array{T,2},dA=[],doDerivative::Bool=false) where {T <: Number}\n\n    A .= tanh.(A)\n    if doDerivative\n        if isempty(dA)\n            dA = one(T) .- A.^2\n        else\n            dA .= one(T) .- A.^2\n        end\n    end\n    return A, dA\nend\n", "meta": {"hexsha": "aa491dcef581ebf1cfca9dce715fe778fd9bc984", "size": 773, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/activations/tanhActivation.jl", "max_stars_repo_name": "lruthotto/Meganet.jl", "max_stars_repo_head_hexsha": "0357da5cc2a7f87e26c5a5bda26cfd521552fcad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2018-01-08T18:14:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-02T23:30:00.000Z", "max_issues_repo_path": "src/activations/tanhActivation.jl", "max_issues_repo_name": "lruthotto/Meganet.jl", "max_issues_repo_head_hexsha": "0357da5cc2a7f87e26c5a5bda26cfd521552fcad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 56, "max_issues_repo_issues_event_min_datetime": "2018-01-17T19:57:07.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-06T21:17:55.000Z", "max_forks_repo_path": "src/activations/tanhActivation.jl", "max_forks_repo_name": "lruthotto/Meganet.jl", "max_forks_repo_head_hexsha": "0357da5cc2a7f87e26c5a5bda26cfd521552fcad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2018-01-06T08:03:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-02T18:51:35.000Z", "avg_line_length": 18.4047619048, "max_line_length": 90, "alphanum_fraction": 0.5795601552, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7895275262043924}}
{"text": "# # Minimizing the sum of the k-largest λ\n#\n# We show how to find the sum of absolute value of the `k` largest eigenvalues of a symmetric matrix $A \\in \\mathbb{S}^n$. This problem can be solved as a semidefinite program. The primal and dual forms are stated in *Alizadeh* \\[1\\]:\n# $$\n# \\begin{array}{llll} \\text{maximize} &   \\text{Tr}(AY) - \\text{Tr}(AW) &    \\text{minimize} &  kz + Tr(U) + Tr(V)            \\\\\n# \\text{subject to} &  \\text{Tr}(Y + W) = k                             &   \\text{subject to} &   zI + V - A \\succeq 0            \\\\\n#                   &  0 \\preceq  Y \\preceq I                           &  &                    zI + U + A \\succeq 0             \\\\\n#                   &  0 \\preceq  W \\preceq I                           & &                     U, V \\succeq 0,\n# \\end{array}\n# $$\n# where $Y, W$ are the variables of the primal and $U, V$ are the variables of the dual problem.\n#-\nusing LinearAlgebra, JuMP, COSMO, Random\nrng = Random.MersenneTwister(212)\n\nn = 10\nA = 5 .* randn(rng, 10, 10)\nA = Symmetric(A, :U)\n\n# We are interested in minimizing the sum of absolute values of the `k=3` largest eigenvalues. Let's formulate the problem in `JuMP` with `COSMO` as the backend solver:\n\nk = 3\nmodel = JuMP.Model(optimizer_with_attributes(COSMO.Optimizer, \"verbose\" => true));\n@variable(model, Y[1:n, 1:n], PSD);\n@variable(model, W[1:n, 1:n], PSD);\n\n@objective(model, Max, tr(A * Y) - tr(A * W));\n@constraint(model, tr(Y + W) == k);\n@constraint(model, Symmetric(I - Y) in PSDCone());\n@constraint(model, Symmetric(I - W) in PSDCone());\nstatus = JuMP.optimize!(model)\n\n#-\nopt_objective = JuMP.objective_value(model)\n\n# Now, we can check the solution by computing the sum of the absolute value of the 3-largest eigenvalues:\nk_λ_abs = sum(sort(abs.(eigen(A).values), rev = true)[1:k])\n\n# ### Solve the dual\n#\n# Alternatively, we can solve the dual problem:\n#-\nmodel = JuMP.Model(with_optimizer(COSMO.Optimizer, verbose=true));\n@variable(model, V[1:n, 1:n], PSD);\n@variable(model, U[1:n, 1:n], PSD);\n@variable(model, z);\n\n@objective(model, Min, k * z + tr(V) + tr(U));\n@constraint(model, Symmetric(z .* diagm(0 => ones(n)) + V - A) in PSDCone());\n@constraint(model, Symmetric(z .* diagm(0 => ones(n)) + U + A) in PSDCone());\nstatus = JuMP.optimize!(model)\n\n#-\nopt_objective = JuMP.objective_value(model)\n\n# This gives the same result.\n# ## Problem with A as variable\n#\n# Above problems are mostly helpful for illustrative purpose. It is obviously easier to find the sum of the k-largest eigenvalues by simply computing the eigenvalues of $A$. However, above results become useful if finding $A$ itself is part of the problem. For example, assume we want to find a valid matrix $A$ under the constraints: $C\\, \\text{vec}(A) = b$ with the minimum sum of absolute values of the k-largest eigenvalues. We can then solve the equivalent problem:\n# $$\n# \\begin{array}{ll} \\text{minimize} &  kz + Tr(U) + Tr(V)     \\\\\n#  \\text{subject to} &   C \\text{vec}(A) = b \\\\\n#                    & zI + V - A \\succeq 0            \\\\\n#                    &    zI + U + A \\succeq 0             \\\\\n#                    &   U, V \\succeq 0.\n# \\end{array}\n# $$\n#\n# ## References\n# [1] Alizadeh - Interior point methods in semidefinite programming with applications to combinatorial optimization (1995)\n", "meta": {"hexsha": "112ba1cce3b1df731a6b4ba417d4eeee3eaa2e7c", "size": 3298, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/sum_abs_k_eigenvalues.jl", "max_stars_repo_name": "blegat/COSMO.jl", "max_stars_repo_head_hexsha": "88d03d4c676051f5aaa1c7aac0b17fe2026b9797", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 210, "max_stars_repo_stars_event_min_datetime": "2018-12-11T23:45:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T23:11:26.000Z", "max_issues_repo_path": "examples/sum_abs_k_eigenvalues.jl", "max_issues_repo_name": "blegat/COSMO.jl", "max_issues_repo_head_hexsha": "88d03d4c676051f5aaa1c7aac0b17fe2026b9797", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 110, "max_issues_repo_issues_event_min_datetime": "2018-12-12T15:52:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T00:44:39.000Z", "max_forks_repo_path": "examples/sum_abs_k_eigenvalues.jl", "max_forks_repo_name": "blegat/COSMO.jl", "max_forks_repo_head_hexsha": "88d03d4c676051f5aaa1c7aac0b17fe2026b9797", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2019-03-10T06:40:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T08:53:29.000Z", "avg_line_length": 46.4507042254, "max_line_length": 470, "alphanum_fraction": 0.6106731352, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7895275223451116}}
{"text": "using CompScienceMeshes\nusing SauterSchwabQuadrature\n\n\n\npI = point(1,5,3)\npII = point(2,5,3)\npIII = point(7,1,0)\n\nSourcechart = simplex(pI, pII, pIII)\nTestchart = simplex(pII, pIII, pI)\n\nAccuracy = 12\n\nfunction integrand(x,y)\n\t\t\treturn(((x-pI)'*(y-pII))*exp(-im*1*norm(x-y))/(4pi*norm(x-y)))\nend\n\n\n\n\nresult = sauterschwabintegral(Sourcechart, Testchart, integrand, Accuracy, Accuracy)\nprintln(result)\n\n#=For those who want to test the sauterschwab_nonparameterized() function,\nmay uncomment the following five lines=#\n\n#sourcechart = simplex(pI,pII,pIII)\n#testchart = simplex(pI,pII,pIII)\n#cf = CommonFace(Accuracy)\n#result2 = sauterschwab_nonparameterized(sourcechart, testchart, integrand, cf)\n#println(result2)\n\n#=sourcechart = testchart, hence the required condition is fulfilled.\nThe user may also compare the two results and see that both are equal=#\n", "meta": {"hexsha": "1a383f3cbee6c2f462a0100c2e2e60e1a8332303", "size": 857, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/common_face_non_parameterized.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SauterSchwabQuadrature.jl-535c7bfe-2023-5c1d-b712-654ef9d93a38", "max_stars_repo_head_hexsha": "419fb564912814b5e033df52e255db707349b600", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-23T16:54:33.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-23T16:54:33.000Z", "max_issues_repo_path": "examples/common_face_non_parameterized.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SauterSchwabQuadrature.jl-535c7bfe-2023-5c1d-b712-654ef9d93a38", "max_issues_repo_head_hexsha": "419fb564912814b5e033df52e255db707349b600", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-23T12:35:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-23T12:44:53.000Z", "max_forks_repo_path": "examples/common_face_non_parameterized.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SauterSchwabQuadrature.jl-535c7bfe-2023-5c1d-b712-654ef9d93a38", "max_forks_repo_head_hexsha": "419fb564912814b5e033df52e255db707349b600", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-10-31T14:02:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-25T06:47:26.000Z", "avg_line_length": 23.8055555556, "max_line_length": 84, "alphanum_fraction": 0.7502917153, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591979, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.7895275126557809}}
{"text": "function normalize(array, target_range)\n    target_min, target_max = target_range\n    orig_min, orig_max = minimum(array), maximum(array)\n    normalized_array = target_min .+ ((target_max-target_min).*(array.-orig_min))./(orig_max-orig_min)\n    return normalized_array\nend\na = [1,2,3,4]\nprint(normalize(a, [-1,1]))\n", "meta": {"hexsha": "14468bebf16cf50369b0701667d36f2855a658fe", "size": 315, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "functions.jl", "max_stars_repo_name": "Srujan35007/My-Julia-Snippets", "max_stars_repo_head_hexsha": "1c730f9d1827fea667a5b7bd1efb18768124b4c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions.jl", "max_issues_repo_name": "Srujan35007/My-Julia-Snippets", "max_issues_repo_head_hexsha": "1c730f9d1827fea667a5b7bd1efb18768124b4c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions.jl", "max_forks_repo_name": "Srujan35007/My-Julia-Snippets", "max_forks_repo_head_hexsha": "1c730f9d1827fea667a5b7bd1efb18768124b4c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0, "max_line_length": 102, "alphanum_fraction": 0.7238095238, "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810511092411, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7894759388650374}}
{"text": "## Nerlove model by OLS (fminunc)\n# and fmincon, imposing that factor shares are in (0,1) and sum to 1\nusing DelimitedFiles, Econometrics\n## prepare the data\ncd(@__DIR__)\ndata = readdlm(\"../Data/nerlove.data\")\ndata = log.(data[:,2:end])\nn = size(data,1)\ny = data[:,1]\nx = [ones(n,1) data[:,2:5]]\n\n## bounds and restriction\nlb = [-1e6, -1e6, 0., 0., 0.0]\nub = [1e6, 1e6, 1., 1., 1.]\nR = [0. 0. 1. 1. 1.]\nr = [1.0]\n\n## define the objective function and start value\nobj = theta -> (y-x*theta)'*(y-x*theta)\nstartval = (ub+lb)/2.0\n\n## OLS\nthetahat, objvalue = fminunc(obj, startval) \nprintln(\"the OLS estimates: obj. value: \", round(objvalue,digits=5))\nprettyprint(thetahat)\n\n## restricted LS\nthetahat, objvalue_r, flag = fmincon(obj, startval, R, r, lb, ub) # both lower and upper bounds\nprintln(\"the restricted LS estimates: obj. value: \", round(objvalue_r,digits=5))\nprettyprint(thetahat)\n\nprintln(\"Exercise: you should construct a qF test using the unrestricted and\")\nprintln(\"restricted objective function values\")\n", "meta": {"hexsha": "a5d75c019f8d51ece62cb43f731ae417e8f5ccb6", "size": 1015, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/NonlinearOptimization/EstimateRestrictedNerlove.jl", "max_stars_repo_name": "mcreel/EconometricsNotes", "max_stars_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-19T18:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T18:23:45.000Z", "max_issues_repo_path": "Examples/NonlinearOptimization/EstimateRestrictedNerlove.jl", "max_issues_repo_name": "mcreel/EconometricsNotes", "max_issues_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/NonlinearOptimization/EstimateRestrictedNerlove.jl", "max_forks_repo_name": "mcreel/EconometricsNotes", "max_forks_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8529411765, "max_line_length": 95, "alphanum_fraction": 0.684729064, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810525948928, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7894759361814927}}
{"text": "function hailstonelength(n::Integer)\n    len = 1\n    while n > 1\n        n = ifelse(iseven(n), n ÷ 2, 3n + 1)\n        len += 1\n    end\n    return len\nend\n\n@show hailstonelength(27); nothing\n@show findmax([hailstonelength(i) for i in 1:100_000]); nothing\n", "meta": {"hexsha": "eccd70bd3137716d208764b5dbd73dfbe0a9a120", "size": 254, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/hailstone-sequence-1.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/hailstone-sequence-1.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/hailstone-sequence-1.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1666666667, "max_line_length": 63, "alphanum_fraction": 0.6141732283, "num_tokens": 93, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810466522862, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7894759292685849}}
{"text": "\n# Load Turing.\nusing Turing\n\n# Load RDatasets.\nusing RDatasets\n\n# Load StatsPlots for visualizations and diagnostics.\nusing StatsPlots\n\n# Functionality for splitting and normalizing the data.\nusing MLDataUtils: shuffleobs, splitobs, rescale!\n\n# We need a softmax function which is provided by NNlib.\nusing NNlib: softmax\n\n# Set a seed for reproducibility.\nusing Random\nRandom.seed!(0)\n\n# Hide the progress prompt while sampling.\nTuring.setprogress!(false);\n\n\n# Import the \"iris\" dataset.\ndata = RDatasets.dataset(\"datasets\", \"iris\");\n\n# Show twenty random rows.\ndata[rand(1:size(data, 1), 20), :]\n\n\n# Recode the `Species` column.\nspecies = [\"setosa\", \"versicolor\", \"virginica\"]\ndata[!, :Species_index] = indexin(data[!, :Species], species)\n\n# Show twenty random rows of the new species columns\ndata[rand(1:size(data, 1), 20), [:Species, :Species_index]]\n\n\n# Split our dataset 50%/50% into training/test sets.\ntrainset, testset = splitobs(shuffleobs(data), 0.5)\n\n# Define features and target.\nfeatures = [:SepalLength, :SepalWidth, :PetalLength, :PetalWidth]\ntarget = :Species_index\n\n# Turing requires data in matrix and vector form.\ntrain_features = Matrix(trainset[!, features])\ntest_features = Matrix(testset[!, features])\ntrain_target = trainset[!, target]\ntest_target = testset[!, target]\n\n# Standardize the features.\nμ, σ = rescale!(train_features; obsdim = 1)\nrescale!(test_features, μ, σ; obsdim = 1);\n\n\n# Bayesian multinomial logistic regression\n@model function logistic_regression(x, y, σ)\n    n = size(x, 1)\n    length(y) == n || throw(DimensionMismatch(\"number of observations in `x` and `y` is not equal\"))\n\n    # Priors of intercepts and coefficients.\n    intercept_versicolor ~ Normal(0, σ)\n    intercept_virginica ~ Normal(0, σ)\n    coefficients_versicolor ~ MvNormal(4, σ)\n    coefficients_virginica ~ MvNormal(4, σ)\n\n    # Compute the likelihood of the observations.\n    values_versicolor = intercept_versicolor .+ x * coefficients_versicolor\n    values_virginica = intercept_virginica .+ x * coefficients_virginica\n    for i in 1:n\n        # the 0 corresponds to the base category `setosa`\n        v = softmax([0, values_versicolor[i], values_virginica[i]])\n        y[i] ~ Categorical(v)\n    end\nend;\n\n\nchain = sample(logistic_regression(train_features, train_target, 1), HMC(0.05, 10), MCMCThreads(), 1500, 3)\n\n\nplot(chain)\n\n\ncorner(\n    chain, MCMCChains.namesingroup(chain, :coefficients_versicolor);\n    label=[string(i) for i in 1:4]\n)\n\n\ncorner(\n    chain, MCMCChains.namesingroup(chain, :coefficients_virginica);\n    label=[string(i) for i in 1:4]\n)\n\n\nfunction prediction(x::Matrix, chain)\n    # Pull the means from each parameter's sampled values in the chain.\n    intercept_versicolor = mean(chain, :intercept_versicolor)\n    intercept_virginica = mean(chain, :intercept_virginica)\n    coefficients_versicolor = [\n        mean(chain, k) for k in\n        MCMCChains.namesingroup(chain, :coefficients_versicolor)\n    ]\n    coefficients_virginica = [\n        mean(chain, k) for k in\n        MCMCChains.namesingroup(chain, :coefficients_virginica)\n    ]\n\n    # Compute the index of the species with the highest probability for each observation.\n    values_versicolor = intercept_versicolor .+ x * coefficients_versicolor\n    values_virginica = intercept_virginica .+ x * coefficients_virginica\n    species_indices = [argmax((0, x, y)) for (x, y) in zip(values_versicolor, values_virginica)]\n    \n    return species_indices\nend;\n\n\n# Make the predictions.\npredictions = prediction(test_features, chain)\n\n# Calculate accuracy for our test set.\nmean(predictions .== testset[!, :Species_index])\n\n\nfor s in 1:3\n    rows = testset[!, :Species_index] .== s\n    println(\"Number of `\", species[s], \"`: \", count(rows))\n    println(\"Percentage of `\", species[s], \"` predicted correctly: \",\n        mean(predictions[rows] .== testset[rows, :Species_index]))\nend\n\n\nif isdefined(Main, :TuringTutorials)\n    Main.TuringTutorials.tutorial_footer(WEAVE_ARGS[:folder], WEAVE_ARGS[:file])\nend\n\n", "meta": {"hexsha": "260da1fc28b1eed9eac6c67ca2c1d3f514e301f0", "size": 3997, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/08-multionomial-regression/08_multinomial-logistic-regression.jl", "max_stars_repo_name": "leachim/TuringTutorials", "max_stars_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 154, "max_stars_repo_stars_event_min_datetime": "2018-08-13T17:04:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T06:28:19.000Z", "max_issues_repo_path": "script/08-multionomial-regression/08_multinomial-logistic-regression.jl", "max_issues_repo_name": "leachim/TuringTutorials", "max_issues_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 137, "max_issues_repo_issues_event_min_datetime": "2018-09-06T21:56:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T07:36:07.000Z", "max_forks_repo_path": "script/08-multionomial-regression/08_multinomial-logistic-regression.jl", "max_forks_repo_name": "leachim/TuringTutorials", "max_forks_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 82, "max_forks_repo_forks_event_min_datetime": "2018-09-17T15:57:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T04:54:57.000Z", "avg_line_length": 28.7553956835, "max_line_length": 107, "alphanum_fraction": 0.7170377783, "num_tokens": 1082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092412, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7894759290611002}}
{"text": "# This file contains some implementations of prox-operators\n\n# L1 - PROX - OPERATOR\n# Param : vector to\nfunction L1prox(x, lambda)\n    prox = zeros(size(x,1))\n    for index in 1:size(x,1)\n        if x[index] < -lambda\n            prox[index] = x[index] + lamda\n        elseif x[index] > lambda\n            prox[index] = x[index] - lambda\n        else\n            prox[index] = 0\n        end\n    end\n    return prox\nend\n\n\n# L2 - PROX - OPERATOR\n# Param :\n#   - x = vector to apply proxity\n#   - λ = regularization parameter\nfunction L2prox(x,lambda)\n    # create empty prox vector\n    prox = zeros(size(x,1))\n    l2norm = norm(x,2)\n    if l2norm > lambda\n        return (1-lambda/l2norm)*x \n    else\n        return zeros(size(x,1))\n    end\nend\n", "meta": {"hexsha": "327282bf6cca6bdfd433fb07850a80198721abab", "size": 743, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Prox.jl", "max_stars_repo_name": "zagazao/num-opt", "max_stars_repo_head_hexsha": "54444008be831a7bb51e845b688f41b5239d285d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-02-01T11:02:20.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-11T22:51:30.000Z", "max_issues_repo_path": "src/Prox.jl", "max_issues_repo_name": "zagazao/num-opt", "max_issues_repo_head_hexsha": "54444008be831a7bb51e845b688f41b5239d285d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Prox.jl", "max_forks_repo_name": "zagazao/num-opt", "max_forks_repo_head_hexsha": "54444008be831a7bb51e845b688f41b5239d285d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8529411765, "max_line_length": 59, "alphanum_fraction": 0.5787348587, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810481379379, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7894759265850401}}
{"text": "# Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/\n#  Niccolò Antonello <nantonel@idiap.ch>\n\n# Semiring definitions\nabstract type Semiring end\n\nimport Base: zero, one, +, *, /\nimport Base: isapprox, parse, reverse, convert, get\nisapprox(a::T,b::T) where { T <: Semiring } = isapprox(a.x,b.x)\nreversetype(::Type{S}) where {S <: Semiring} = S\nreverse(a::S) where { S <: Semiring } = a\nreverseback(a::S) where { S <: Semiring } = a\nget(a::S) where { S <: Semiring } = a.x\n\n# properties\n\"\"\"\n`isleft(::Type{W})`\n\nCheck if the semiring type `W` satisfies:\n\n``\\\\forall a,b,c \\\\in \\\\mathbb{W} : c \\\\otimes(a \\\\oplus b) = c \\\\otimes a \\\\oplus c \\\\otimes b``\n\"\"\"\nisleft(::Type{W}) where {W} = false             # ∀ a,b,c: c*(a+b) = c*a + c*b\n\n\"\"\"\n`isright(::Type{W})`\n\nCheck if the semiring type `W` satisfies:\n\n``\\\\forall a,b,c \\\\in \\\\mathbb{W} : c \\\\otimes(a \\\\oplus b) = a \\\\otimes c \\\\oplus b \\\\otimes c``\n\"\"\"\nisright(::Type{W}) where {W}  = false           # ∀ a,b,c: c*(a+b) = a*c + b*c\n\n\"\"\"\n`isweaklydivisible(::Type{W})`\n\nCheck if the semiring type `W` satisfies:\n\n``\\\\forall a,b \\\\in \\\\mathbb{W} \\\\ \\\\text{s.t.} \\\\ a \\\\oplus b \\\\neq \\\\bar{0} \\\\ \\\\exists z : x = (x \\\\oplus y ) \\\\otimes z``\n\"\"\"\nisweaklydivisible(::Type{W}) where {W}  = false # a+b ≂̸ 0: ∃ z s.t. x = (x+y)*z\n\n\"\"\"\n`ispath(::Type{W})`\n\nCheck if the semiring type `W` satisfies:\n\n``\\\\forall a,b \\\\in \\\\mathbb{W}: a \\\\oplus b = a \\\\lor a \\\\oplus b = b``\n\"\"\"\nispath(::Type{W}) where {W}  = false            # ∀ a,b: a+b = a or a+b=b\n\n\"\"\"\n`isidempotent(::Type{W})`\n\nCheck if the semiring type `W` satisfies:\n\n``\\\\forall a \\\\in \\\\mathbb{W}: a \\\\oplus a = a``\n\"\"\"\nisidempotent(::Type{W}) where {W} = false       # ∀ a: a+a = a\n\n\"\"\"\n`iscommulative(::Type{W})`\n\nCheck if the semiring type `W` satisfies:\n\n``\\\\forall a,b \\\\in \\\\mathbb{W}: a \\\\otimes b = b \\\\otimes a``\n\"\"\"\niscommulative(::Type{W}) where {W} = false      # ∀ a,b: a*b = b*a\niscomplete(::Type{W}) where {W} = false\n\nBase.show(io::IO, T::Semiring) = Base.show(io, T.x)\n", "meta": {"hexsha": "b5977c5650b20d50d124a516b01ff0f8fc876b7b", "size": 2005, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/semirings/semirings.jl", "max_stars_repo_name": "idiap/FiniteStateTransducers.jl", "max_stars_repo_head_hexsha": "430bf273960bd3f43f4042ee85a7c9f3d846d37f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-20T10:41:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-20T10:41:21.000Z", "max_issues_repo_path": "src/semirings/semirings.jl", "max_issues_repo_name": "idiap/FiniteStateTransducers.jl", "max_issues_repo_head_hexsha": "430bf273960bd3f43f4042ee85a7c9f3d846d37f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-02-09T16:54:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-14T00:10:46.000Z", "max_forks_repo_path": "src/semirings/semirings.jl", "max_forks_repo_name": "idiap/FiniteStateTransducers.jl", "max_forks_repo_head_hexsha": "430bf273960bd3f43f4042ee85a7c9f3d846d37f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8472222222, "max_line_length": 125, "alphanum_fraction": 0.5680798005, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7894624477203555}}
{"text": "module kmean\nusing Distributions\nusing Random\nusing Printf\n\nfunction k_mean(X::AbstractMatrix{<:Real},\n     k::Integer,\n     w::Array{<:Real};\n     maxiter::Integer=200, # maximun iteration\n     tol::Real=1e-6 # tolearance of change at converage\n     )\n     d, n = size(X)\n     (2 <= k < n) || throw(ArgumentError(\"k must be 2 <= k < n, k=$k given.\"))\n     centers =  init_centers(X, k)\n     # println(centers)\n     centers_new = Array{Float64, 2}(undef, d, k)\n     # println(centers)\n     clustDist = zeros(n, 2)\n     delta = 1.0\n     iter_num = 1\n     inertia = 0\n     while delta > tol\n         if iter_num > maxiter\n             break\n         end\n\n         for i in range(1, length=n, step =1)\n             distList = Float64[]\n             for j in range(1, length=k, step=1)\n                 append!(distList, distance(centers[:,j], X[:, i]))\n             end\n             # println(distList)\n             dist, ind = findmin(distList)\n             # print(ind)\n             # * w[i]\n             clustDist[i, :] = [dist, ind]\n         end\n         inertia = 0\n         for j in range(1, length = k, step = 1)\n              dInx = clustDist[:, 2].==j\n              dist_t = clustDist[:, 1].==j\n              inertia += mean(dist_t)\n              # println(dInx)\n              ptInCluster = X[:, dInx]\n              # ptWeight = w[dInx]\n              # ptWeight = ptWeight ./ sum(ptWeight)\n              #* ptWeight\n              centers_new[:,j] = mean(ptInCluster, dims=2)\n              # println(centers_new[:,j])\n         end\n         # println(centers_new)\n         # println(centers_new - centers)\n         delta = sum((centers_new - centers).^2)\n         centers = copy(centers_new)\n         @printf(\"iter:\\t%d\\tdelta:\\t%0.4f\\n\", iter_num, delta)\n         # println(\"delta: $delta\")\n         iter_num += 1\n     end\n     # println(centers)\n     cent = deepcopy(centers)\n     inertia -= sum(var(cent, dims=2))/k\n     # println(centers)\n     return centers, inertia\nend\n\nfunction init_centers(X::AbstractMatrix{<:Real},\n     k::Integer)\n     d, n = size(X)\n\n     # init_index = rand(1:n, k)\n     # init_centers = X[:,init_index]\n     init_index = Inf64[]\n     index = rand(1:n)\n     init_cluster = X[:,index]\n     init_centers = Array{Float64, 2}(undef, d, k)\n     distListTotal = Array{Float64, 1}(undef, n)\n     init_centers[:,1] = init_cluster\n\n     for i in 2:k\n         sum_all = 0\n         for j in 1:n\n             distList = Float64[]\n             for j in 1:i\n                 append!(distList, distance(init_centers[:,i], X[:, j]))\n             end\n             dist, ind = findmin(distList)\n             distListTotal[j] = dist\n             sum_all += dist\n         end\n         sum_all *= rand()\n         for j in 1:n\n             di = distListTotal[k]\n             sum_all -= di\n             if sum_all > 0\n                 continue\n             end\n             init_centers[:,i] = X[:, j]\n             break\n         end\n     end\n     return init_centers\nend\n\nfunction distance(v1, v2)\n    sqrt(sum((v1 - v2).^2))\nend\n\nfunction k_mean_predict(X::AbstractMatrix{<:Real},\n    centers::AbstractMatrix{<:Real})\n    d, n = size(X)\n    d2, k = size(centers)\n    (d == d2) || throw(ArgumentError(\n    \"dims of data $d and center $d2 should be equal\"))\n    clustInd = Int[]\n    for i in range(1, length=n, step =1)\n        distList = Float64[]\n        for j in range(1, length=k, step=1)\n            append!(distList, distance(centers[:,j], X[:, i]))\n        end\n        # println(distList)\n        dist, ind = findmin(distList)\n        # print(ind)\n        append!(clustInd, ind)\n    end\n    return clustInd\nend\n\nfunction K_mean(X::AbstractMatrix{<:Real},\n     k::Integer,\n     w::Array{<:Real};\n     maxiter::Integer=100, # maximun iteration\n     tol::Real=1e-4, # tolearance of change at converage\n     random_state::Integer=10\n     )\n     d, n = size(X)\n     centers_ls = Array{Float64, 3}(undef, random_state, d, k)\n     inertia_ls = []\n    for iter in 1:random_state\n        centers, inertia = k_mean(X, k, w)\n        if sum(isnan.(centers)) > 0\n            continue\n        end\n        # println(centers_ls)\n        # println(typeof(centers_ls))\n        println(size(centers))\n        centers_ls[iter,:,:] = centers\n        append!(inertia_ls, inertia)\n    end\n    inertia_min, min_ind = findmin(inertia_ls)\n    return centers_ls[min_ind,:,:]\nend\n\nend  # module kmean\n", "meta": {"hexsha": "c42a225e9ea81146d96e1aeedd6bfdf2da4a65b6", "size": 4392, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kmean.jl", "max_stars_repo_name": "JackSnowWolf/VE414_final_project", "max_stars_repo_head_hexsha": "b766b84886f41d79ff9a18e4e0f676037d1124a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kmean.jl", "max_issues_repo_name": "JackSnowWolf/VE414_final_project", "max_issues_repo_head_hexsha": "b766b84886f41d79ff9a18e4e0f676037d1124a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kmean.jl", "max_forks_repo_name": "JackSnowWolf/VE414_final_project", "max_forks_repo_head_hexsha": "b766b84886f41d79ff9a18e4e0f676037d1124a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-02T00:56:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-02T00:56:44.000Z", "avg_line_length": 28.5194805195, "max_line_length": 78, "alphanum_fraction": 0.5255009107, "num_tokens": 1238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7894624441375344}}
{"text": "function sma(ta::TimeArray, n::Integer)\n  tstamps = timestamp(ta)[n:end]\n\n  vals = zeros(size(values(ta),1) - (n-1), size(values(ta),2))\n  for i in 1:size(values(ta),1) - (n-1)\n    for j in 1:size(values(ta),2)\n      vals[i,j] = nanmean(values(ta)[i:i+(n-1),j])[1]\n    end\n  end\n\n  cname = Symbol[]\n  cols  = colnames(ta)\n  for c in 1:length(cols)\n    push!(cname, Symbol(string(cols[c], \"_sma_\", n)))\n  end\n\n  TimeArray(tstamps, vals, cname, meta(ta))\nend\n\nfunction ema(ta::TimeArray, n::Integer; wilder::Bool = false)\n  k = (1 + !wilder) / (n + !wilder)\n\n  tstamps = timestamp(ta)[n:end]\n\n  vals    =  zeros(size(values(ta),1), size(values(ta),2))\n  # seed with first value with an sma value\n  vals[n,:] = values(sma(ta, n))[1,:]\n\n  for i in n+1:size(values(ta),1)\n    for j in 1:size(values(ta),2)\n      _v = values(ta)[i,j]\n      vals[i,j] = isnan(_v) ? vals[i-1, j] : _v * k + vals[i-1, j] * (1-k)\n    end\n  end\n\n  cname   = Symbol[]\n  cols    = colnames(ta)\n  for c in 1:length(cols)\n    push!(cname, Symbol(string(cols[c], \"_ema_\", n)))\n  end\n\n  TimeArray(tstamps, vals[n:length(ta),:], cname, meta(ta))\nend\n\nfunction kama(ta::TimeArray, n::Integer = 10, fn::Integer = 2, sn::Integer = 30)\n  vola = moving(nansum, abs.(ta .- lag(ta)), n)\n  change = abs.(ta .- lag(ta, n))\n  er = safediv.(change, vola)  # Efficiency Ratio\n\n  # Smooth Constant\n  sc = (er .* (2 / (fn + 1) - 2 / (sn + 1)) .+ 2 / (sn + 1)).^2\n\n  cl = ta[n+1:end]\n\n  vals = similar(Array{Float64}, axes(values(cl)))\n  # using simple moving average as initial kama\n  pri_kama = nanmean(values(ta[1:n]))\n\n  @assert length(cl) == length(sc)\n\n  for idx ∈ 1:length(cl)\n    _p_k = pri_kama .+ values(sc[idx]) .* (values(cl[idx]) .- pri_kama)\n\n    #Added check for NaN and adequately backfill with the correct last available pri_kama\n    if typeof(pri_kama) == Float64\n      pri_kama = isnan.(_p_k)[1] ? pri_kama : _p_k\n    else\n      _p_k[isnan.(_p_k)] .= pri_kama[isnan.(_p_k)]\n      pri_kama = _p_k\n    end\n\n    vals[idx, :] = pri_kama\n\n  end\n\n  cols =\n  if length(colnames(ta)) == 1\n    [:kama]\n  else\n    [Symbol(\"$(c)_kama\") for c in colnames(ta)]\n  end\n\n  TimeArray(timestamp(cl), vals, cols)\nend\n\nfunction env(ta::TimeArray, n::Integer; e::AbstractFloat = 0.1)\n  tstamps = timestamp(ta)[n:end]\n\n  s = sma(ta, n)\n\n  upper = values(s) .* (1 + e)\n  lower = values(s) .* (1 - e)\n\n  up_cnames = Symbol.([\"$(string.(c_name))_env_$(n)_up\" for c_name in colnames(ta)])\n  lw_cnames = Symbol.([\"$(string.(c_name))_env_$(n)_low\" for c_name in colnames(ta)])\n\n  u = TimeArray(tstamps, upper, up_cnames, meta(ta))\n  l = TimeArray(tstamps, lower, lw_cnames, meta(ta))\n\n  merge(l, u; method = :inner)\nend\n\n# Array dispatch for use by other algorithms\n\nfunction sma(a::Array, n::Integer)\n  vals = zeros(size(a,1) - (n-1), size(a,2))\n\n  for i in 1:size(a,1) - (n-1)\n    for j in 1:size(a,2)\n      vals[i,j] = nanmean(a[i:i+(n-1),j])\n    end\n  end\n\n  vals\nend\n\nfunction ema(a::Array, n::Integer; wilder = false)\n  k = (1 + !wilder) / (n + !wilder)\n\n  vals = zeros(size(a,1), size(a,2))\n  # seed with first value with an sma value\n  vals[n,:] = sma(a, n)[1,:]\n\n  for i in n+1:size(a,1)\n    for j in 1:size(a,2)\n      vals[i,j] = a[i,j] * k + vals[i-1, j] * (1-k)\n    end\n  end\n\n  vals[n:end, :]\nend\n\nfunction env(a::AbstractArray, n::Integer; e::AbstractFloat = 0.1)\n  s = sma(a, n)\n\n  upper = @. s * (1 + e)\n  lower = @. s * (1 - e)\n\n  [lower upper]\nend\n\n@doc raw\"\"\"\n    sma(ta::TimeArray, n)\n    sma(A::Array, n)\n\nSimple Moving Average\n\n# Formula\n\n```math\n\\text{SMA} = \\frac{\\sum_i^n{P_i}}{n}\n```\n\"\"\"\nsma\n\n@doc raw\"\"\"\n    ema(ta::TimeArray, n, wilder = false)\n    ema(A::Array, n, wilder = false)\n\nExponemtial Moving Average\n\nA.k.a. exponentially weighted moving average (EWMA)\n\n# Formula\n\nLet ``k`` denote the degree of weighting decrease.\n\nIf parameter `wilder` is `true`, ``k = \\frac{1}{n}``,\nelse ``k = \\frac{2}{n + 1}``.\n\n```math\n\\text{EMA}_t = k \\times P_t + (1 - k) \\times \\text{EMA}_{t - 1}\n```\n\"\"\"\nema\n\n@doc raw\"\"\"\n    kama(ta::TimeArray, n = 10, fn = 2, sn = 30)\n\nKaufman's Adaptive Moving Average\n\n# Arguments\n\n- `n`: period\n\n- `fn`: the fastest EMA constant\n\n- `sn`: the slowest EMA constant\n\n# Formula\n\n```math\n\\begin{align*}\n  \\text{KAMA}_t     & = \\text{KAMA}_{t-1} + \\text{SC} \\times (\\text{Price} - \\text{KAMA}_{t-1}) \\\\\n  \\text{SC}         & = (\\text{ER} \\times (\\frac{2}{fn + 1} - \\frac{2}{sn + 1}) + \\frac{2}{sn + 1})^2 \\\\\n  \\text{ER}         & = \\frac{Change}{Volatility} \\\\\n  \\text{Change}     & = | \\text{Price} - \\text{Price}_{t-n} | \\\\\n  \\text{Volatility} & = \\sum_{i}^{n} | \\text{Price}_i - \\text{Price}_{i - 1} |\n\\end{align*}\n```\n\"\"\"\nkama\n\n@doc raw\"\"\"\n    env(ta::TimeArray, n; e = 0.1)\n    env(A::AbstractArray, n; e = 0.1)\n\nMoving Average Envelope\n\n```math\n\\begin{align*}\n  \\text{Upper Envelope} & = \\text{SMA}(n) \\times (1 + e) \\\\\n  \\text{Lower Envelope} & = \\text{SMA}(n) \\times (1 - e)\n\\end{align*}\n```\n\n# Arguments\n\n- `e`: the envelope, `0.1` implies the `10%` envelope.\n\n# References\n\n- [TradingView](https://www.tradingview.com/wiki/Envelope_(ENV))\n\"\"\"\nenv\n", "meta": {"hexsha": "3a8453ebdfbf3879bcc517449783ec3846ead24c", "size": 5046, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/movingaverages.jl", "max_stars_repo_name": "millerjoey/MarketTechnicals.jl", "max_stars_repo_head_hexsha": "9e09b8fc7b1f324725f83a3edff8117cffc455f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 101, "max_stars_repo_stars_event_min_datetime": "2015-02-03T22:03:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:57:13.000Z", "max_issues_repo_path": "src/movingaverages.jl", "max_issues_repo_name": "millerjoey/MarketTechnicals.jl", "max_issues_repo_head_hexsha": "9e09b8fc7b1f324725f83a3edff8117cffc455f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 85, "max_issues_repo_issues_event_min_datetime": "2015-02-21T02:31:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T21:29:40.000Z", "max_forks_repo_path": "src/movingaverages.jl", "max_forks_repo_name": "millerjoey/MarketTechnicals.jl", "max_forks_repo_head_hexsha": "9e09b8fc7b1f324725f83a3edff8117cffc455f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2015-04-25T19:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T01:19:01.000Z", "avg_line_length": 22.3274336283, "max_line_length": 104, "alphanum_fraction": 0.5832342449, "num_tokens": 1887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067163548471, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7894624431047493}}
{"text": "\"\"\"\nPackage: Smoothers\n\n    filter(b,a,x,si)\n\nApply a digital filter to x using the following linear, time-invariant difference equation\n\n```math\ny(n) = \\\\sum_{k=0}^M d_{k+1} \\\\cdot x_{n-k}-\\\\sum_{k=1}^N c_{k+1} \\\\cdot y_{n-k} \n\\\\\\\\ \\\\forall n | 1\\\\le n \\\\le \\\\left\\\\| x \\\\right\\\\| | c=a/a_1, d=b/a_1\n```\n\nThe implementation follows the description of [Octave filter function](https://octave.sourceforge.io/octave/function/filter.html)\n\n# Arguments\n- `a`: Vector of numerator coefficients for the filter rational transfer function.\n- `b`: Vector of denominator coefficients for the filter rational transfer function.\n- `x`: Vector of data.\n- `si`: Vector of initial states.\n\n# Returns\n\nVector of filtered data\n\n# Examples\n```julia-repl\nusing Plots\n\nt = Array(LinRange(-pi,pi,100));\nx = sin.(t) .+ 0.25*rand(length(t));\n\n# Moving Average Filter\nw = 5; \nb = ones(w)/w;\na = [1];\n\nplot(t,x,label=\"sin(x)\",legend=:bottomright)\ny1 = filter(b,a,x)\nsi = x[1:4] .+ .1;\ny2 = filter(b,a,x,si)\nplot!(t,y1,label=\"MA\")\nplot!(t,y2,label=\"MA with si\")\n```\n\"\"\"\n@inline function filter(b::AbstractVector{A},\n                        a::AbstractVector{B},\n                        x::AbstractVector{C},\n                        si::AbstractVector{D}=zeros(C,max(length(a),length(b))-1)\n                        ) where {A<:Real,B<:Real,C<:Real,D<:Real}\n\n    @assert a[1] != 0 \"a[1] must not be zero\"\n\n    T = Base.promote_op(/,C,Base.promote_op(/,B,A))\n    a,b,x,si,_ = Base.promote(a,b,x,si,[T(1.0)])\n    \n    Na,Nb,Nx = length(a),length(b),length(x)\n    Nsi = max(Na,Nb)-1\n    @assert Nsi == length(si) \"length(si) must be max(length(a),length(b))-1)\"\n    \n    N,M = Na-1,Nb-1\n    c,d = a/a[1],b/a[1]\n    \n    y = zeros(T,Nx)\n    y[1:Nsi] = si\n\n    for n in 1:Nx\n        for k in 0:min(n-1,M)\n            @inbounds y[n] += d[k+1]*x[n-k]\n        end\n        for k in 1:min(n-1,N)\n            @inbounds y[n] -= c[k+1]*y[n-k]\n        end\n    end\n    \n    return y\nend\n", "meta": {"hexsha": "fad9934da6f5ec77f5e937abdbb1903181ab5137", "size": 1944, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/filter.jl", "max_stars_repo_name": "viraltux/Smoothers.jl", "max_stars_repo_head_hexsha": "3dff0ba13001cbc9982700875c9776d2d4a1cd40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2021-09-02T14:40:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T07:40:56.000Z", "max_issues_repo_path": "src/filter.jl", "max_issues_repo_name": "viraltux/Smoothers.jl", "max_issues_repo_head_hexsha": "3dff0ba13001cbc9982700875c9776d2d4a1cd40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-08-15T22:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T04:37:45.000Z", "max_forks_repo_path": "src/filter.jl", "max_forks_repo_name": "viraltux/Smoothers.jl", "max_forks_repo_head_hexsha": "3dff0ba13001cbc9982700875c9776d2d4a1cd40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2467532468, "max_line_length": 129, "alphanum_fraction": 0.5694444444, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067147399244, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7894624417520579}}
{"text": "using Distributions, CSV, Printf\n\n# Load observed data\nx_samples = CSV.read(\"hmm_observations.csv\")[:,1]\n\n\n# Gives P(Y_k = 1 | All other variables)\n# Inputs\n# - x: The vector of (observed) X variables\n# - y: The current sample of Y variables\n# - θ_k: The vector parameters in the form [q, σ²]\n# - k: The index of the Y variable of interest\n# Outputs\n# The probability that Y_k = 1 given all other variables\nfunction conditional_probability(x, y, θ_k, k)\n    # Extract density parameters\n    q, σ² = θ_k\n    σ = sqrt(σ²)\n\n    n = length(x)\n\n    𝒩₁ = Normal(1, σ)\n    𝒩₀ = Normal(0, σ)\n\n    if k == 1\n        joint = (q*(y[k+1] == 1) + (1-q)*(y[k+1] == 0))*pdf(𝒩₁, x[k])\n\n        marginal = joint + (q*(y[k+1] == 0) + (1-q)*(y[k+1] == 1))*pdf(𝒩₀,x[k])\n    elseif k == n\n        joint = (q*(y[k-1] == 1) + (1-q)*(y[k-1] == 0))*pdf(𝒩₁, x[k])\n\n        marginal = joint + (q*(y[k-1] == 0) + (1-q)*(y[k-1] == 1))*pdf(𝒩₀,x[k])\n\n    else\n        joint = (q*(y[k-1] == 1) + (1-q)*(y[k-1] == 0))*(q*(y[k+1] == 1) + (1-q)*(y[k+1] == 0))*pdf(𝒩₁,x[k])\n\n        marginal = joint + (q*(y[k-1] == 0) + (1-q)*(y[k-1] == 1))*(q*(y[k+1] == 0) + (1-q)*(y[k+1] == 1))*pdf(𝒩₀, x[k])\n    end\n\n    return joint/marginal\nend\n\n\n# Performs one single Gibbs sampler iteration of Y\n# Inputs\n# - x: The vector of (observed) X variables\n# - y: The current sample of Y variables\n# - θ_k: The vector parameters in the form [q, σ²]\n# - k: The index of the Y variable of interest\n# Outputs\n# A Y sample where each index of Y is sampled by conditioning on all other\n# variables\nfunction get_single_gibbs_sample(x, y, θ_k)\n    n = length(x)\n\n    for k = 1:n\n        y[k] = rand() < conditional_probability(x, y, θ_k, k)\n    end\n\n    return y\nend\n\n# Returns a sample of Y\n# Inputs\n# - x: The vector of (observed) X variables\n# - θ_k: The vector parameters in the form [q, σ²]\n# Outputs\n# A Y sample where Y ~ P(Y|X = x)\nfunction gibbs_sampler(x, θ_k)\n    n = length(x)\n\n    y = rand(0:1, n)\n\n    for i = 1:75 # Burn-in period\n        y = get_single_gibbs_sample(x, y, θ_k)\n    end\n\n    return y\nend\n\n# Estimates the values of a,b,c (as defined in example) via Monte Carlo\n# Inputs\n# - x: The vector of (observed) X variables\n# - θ_k: The vector parameters in the form [q, σ^2]\n# Outputs\n# A vector in the form [a,b,c] representing a MC estimate of a,b, and c\nfunction estimate_a_b_c(x, θ_k)\n    n = length(x)\n\n    # Number of MC samples\n    num_samples = 100\n\n    # Estimate sum\n    total_a = 0\n    total_b = 0\n    total_c = 0\n\n    for k = 1:num_samples\n        y_samples = gibbs_sampler(x, θ_k)\n        estimate_a = sum(y_samples[1:(n-1)] .== y_samples[2:n])\n        estimate_b = sum(y_samples[1:(n-1)] .!= y_samples[2:n])\n        estimate_c = sum((x - y_samples).^2)\n\n\n        total_a += estimate_a\n        total_b += estimate_b\n        total_c += estimate_c\n    end\n\n    return [total_a, total_b, total_c]./num_samples\nend\n\n# Performs EM algorithm to estimate θ\n# Inputs\n# - x: The vector of (observed) X variables\n# Outputs\n# An estimate of θ = [q, σ²]\nfunction em_algorithm(x)\n    # Initialize theta parameter [q, σ²]\n    θ_k = [0.5, 1]\n    @printf(\"k = 0: [%f, %f]\\n\", θ_k[1], θ_k[2])\n\n    num_iterations = 500\n\n    for i = 1:num_iterations\n        a, b, c = estimate_a_b_c(x, θ_k)\n        q_1 = a/(a+b)\n        σ²_1 = c/(a+b+1)\n        θ_k = [q_1, σ²_1]\n\n        @printf(\"k = %d: [%f, %f]\\n\", i, θ_k[1], θ_k[2])\n    end\n\n    return θ_k\nend\n\nem_algorithm(x_samples)\n", "meta": {"hexsha": "241091b7933ca0d21f9ff47cee09077ef9cb6e59", "size": 3433, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/bayesian-inference-and-graphical-models/code/em_hmm_ex.jl", "max_stars_repo_name": "seanrattana/courses", "max_stars_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-08-21T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T15:46:58.000Z", "max_issues_repo_path": "content/bayesian-inference-and-graphical-models/code/em_hmm_ex.jl", "max_issues_repo_name": "seanrattana/courses", "max_issues_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-08-23T06:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-26T12:47:12.000Z", "max_forks_repo_path": "content/bayesian-inference-and-graphical-models/code/em_hmm_ex.jl", "max_forks_repo_name": "seanrattana/courses", "max_forks_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-08-18T21:23:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T19:14:33.000Z", "avg_line_length": 24.8768115942, "max_line_length": 120, "alphanum_fraction": 0.5790853481, "num_tokens": 1249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.8376199552262966, "lm_q1q2_score": 0.7894624403170868}}
{"text": "#Copyright 2015-16 Julia Computing Inc. All rights reserved\n\n#This file is used as an example to demo the functionality of this package. \n\nusing Distributions\nusing JuliaInXL\nusing Logging\nLogging.configure(level=DEBUG)\n\nf(u) = exp(-u^2/2)/√(2pi)\n\nconst u1=Uniform(-5.0,+5.0)\nconst u2=Uniform(0.0, 0.5)\n\nfunction simulate_pt()\n    x=rand(u1)\n    y=rand(u2)\n    y<f(x)\nend\n\nfunction simulate(num::Number)\n     hits=0\n     for i in 1:num\n        hits = hits + simulate_pt()\n    end\n    return hits/num*(0.5*10)\nend\n\nfunction simulateTime(num)\n    tic()\n    r = simulate(num)\n    t = toc()\n    return (r, t)\nend\n\nsimulateArray(x::Array) = [simulate(i) for i in x]\n\n\n#process_async([simulate, simulateTime], \"tcp://127.0.0.1:9999\"; bind=true)\n", "meta": {"hexsha": "0cb7381fa561c2fa2f2d5348ba07134fab4c6d4e", "size": 739, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/sim.jl", "max_stars_repo_name": "JuliaComputing/JuliaInXL.jl", "max_stars_repo_head_hexsha": "522245643593f0231cc6d31900a00b69debdc2b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-15T12:51:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T04:57:34.000Z", "max_issues_repo_path": "test/sim.jl", "max_issues_repo_name": "JuliaComputing/JuliaInXL.jl", "max_issues_repo_head_hexsha": "522245643593f0231cc6d31900a00b69debdc2b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/sim.jl", "max_forks_repo_name": "JuliaComputing/JuliaInXL.jl", "max_forks_repo_head_hexsha": "522245643593f0231cc6d31900a00b69debdc2b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-07T23:19:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T23:19:34.000Z", "avg_line_length": 18.475, "max_line_length": 76, "alphanum_fraction": 0.6617050068, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697694, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7894624349063221}}
{"text": "# Normalises array with options to choose:\n# 1) dimension along which to normalise: dim=1 means features are rows, dim=2 means cols\n# 2) subset of features to be normalised\n# returns new array X_out and μ and σ\nfunction normalise(X::Array; dim::Int=2, subset::Vector=collect(1:size(X, dim)))\n\n    # Normalise each column - default\n    if dim == 2\n        data = X[:, subset]\n        μ = mean(data, 1)\n        σ = std(data, 1)\n        X_out = copy(X)\n        for i = 1:length(subset)\n            X_out[:, subset[i]] = (X_out[:, subset[i]] .- μ[i]) ./ σ[i]\n        end\n        return X_out, μ, σ\n\n    # Normalise each row\n    elseif dim == 1\n        data = X[subset, :]\n        μ = mean(data, 2)\n        σ = std(data, 2)\n        X_out = copy(X)\n        for i = 1:length(subset)\n            X_out[subset[i], :] = (X_out[subset[i], :] .- μ[i]) ./ σ[i]\n        end\n        return X_out, μ, σ\n\n    # If dim entered is not in range i.e. must be 1 or 2\n    else throw(DimensionMismatch(\"Dimension must be 1 (features are rows) or 2, the default, (features are cols).\"))\n\n    end\nend\n\n# Normalises array with options to choose:\n# 1) dimension along which to normalise: dim=1 means features are rows, dim=2 means cols\n# 2) subset of features to be normalised\n# modifies X and returns μ and σ\nfunction normalise!(X::Array; dim::Int=2, subset::Vector=collect(1:size(X, dim)))\n\n    # Normalise each column - default\n    if dim == 2\n        data = X[:, subset]\n        μ = mean(data, 1)\n        σ = std(data, 1)\n        for i = 1:length(subset)\n            X[:, subset[i]] = (X[:, subset[i]] .- μ[i]) ./ σ[i]\n        end\n        return μ, σ\n\n    # Normalise each row\n    elseif dim == 1\n        data = X[subset, :]\n        μ = mean(data, 2)\n        σ = std(data, 2)\n        for i = 1:length(subset)\n            X[subset[i], :] = (X[subset[i], :] .- μ[i]) ./ σ[i]\n        end\n        return μ, σ\n\n    # If dim entered is not in range i.e. must be 1 or 2\n    else throw(DimensionMismatch(\"Dimension must be 1 (features are rows) or 2, the default, (features are cols).\"))\n\n    end\nend\n\n# Normalises array with given μ (mean) and σ (standard deviation)\n# Same options as above for dimension and subset of features\nfunction normalise(X::Array, μ::Array, σ::Array; dim::Int=2, subset::Vector=collect(1:size(X, dim)))\n\n    # Check lengths\n    length(μ) != length(σ) && throw(\"μ and σ must be same length\")\n    length(μ) != length(subset) && throw(\"μ and subset must be same length\")\n\n    # Normalise each column - default\n    if dim == 2\n        X_out = copy(X)\n        for i = 1:length(subset)\n            X_out[:, subset[i]] = (X_out[:, subset[i]] .- μ[i]) ./ σ[i]\n        end\n        return X_out\n\n    # Normalise each row\n    elseif dim == 1\n        X_out = copy(X)\n        for i = 1:length(subset)\n            X_out[subset[i], :] = (X_out[subset[i], :] .- μ[i]) ./ σ[i]\n        end\n        return X_out\n\n    # If dim entered is not in range i.e. must be 1 or 2\n    else throw(DimensionMismatch(\"Dimension must be 1 (features are rows) or 2, the default, (features are cols).\"))\n\n    end\nend\n\n# Normalises array with given μ (mean) and σ (standard deviation)\n# Same options as above for dimension and subset of features\nfunction normalise!(X::Array, μ::Array, σ::Array; dim::Int=2, subset::Vector=collect(1:size(X, dim)))\n\n    # Check lengths\n    length(μ) != length(σ) && throw(\"μ and σ must be same length\")\n    length(μ) != length(subset) && throw(\"μ and subset must be same length\")\n\n    # Normalise each column - default\n    if dim == 2\n        for i = 1:length(subset)\n            X[:, subset[i]] = (X[:, subset[i]] .- μ[i]) ./ σ[i]\n        end\n\n    # Normalise each row\n    elseif dim == 1\n        for i = 1:length(subset)\n            X[subset[i], :] = (X[subset[i], :] .- μ[i]) ./ σ[i]\n        end\n\n    # If dim entered is not in range i.e. must be 1 or 2\n    else throw(DimensionMismatch(\"Dimension must be 1 (features are rows) or 2, the default, (features are cols).\"))\n\n    end\nend\n", "meta": {"hexsha": "c5816bf5db8d901db27ae7928332cbe997bc8237", "size": 3978, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/normalise.jl", "max_stars_repo_name": "Wedg/MLTools.jl", "max_stars_repo_head_hexsha": "950220ef92a16c16de5051545845a4697ef15cb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-09-25T12:57:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-10T23:54:02.000Z", "max_issues_repo_path": "src/normalise.jl", "max_issues_repo_name": "Wedg/MLTools.jl", "max_issues_repo_head_hexsha": "950220ef92a16c16de5051545845a4697ef15cb0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/normalise.jl", "max_forks_repo_name": "Wedg/MLTools.jl", "max_forks_repo_head_hexsha": "950220ef92a16c16de5051545845a4697ef15cb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.606557377, "max_line_length": 116, "alphanum_fraction": 0.5761689291, "num_tokens": 1186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.789461747150129}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,jl:hydrogen\n#     text_representation:\n#       extension: .jl\n#       format_name: hydrogen\n#       format_version: '1.3'\n#       jupytext_version: 1.10.3\n#   kernelspec:\n#     display_name: Julia 1.6.3\n#     language: julia\n#     name: julia-1.6\n# ---\n\n# %%\nusing Distributions\nusing StatsPlots\n\n# warm up (少し時間を取られる。その間に下のセルでコードを入力する)\nhistogram(randn(10^5); norm=true, alpha=0.3, size=(300, 200))\nplot!(Normal())\n\n# %%\n# コインを20回投げたときの表が出る回数の分布は正規分布で近似される。\n\nn = 20\np = 0.5\nsample_of_means = rand(Binomial(n, p), 10^5)\nhistogram(sample_of_means; norm=true, alpha=0.3, bin=-0.5:n+0.5, label=\"rand(Binomial($n, $p))\")\nplot!(Normal(n*p, √(n*p*(1-p))), 0, 20; label=\"normal approx.\", lw=2)\n\n# %%\n# 回数n、確率パラメータpの二項分布オブジェクトを次のように作れる。\n\nbin = Binomial(n, p)\n\n# %%\n# 確率分布オブジェクトの乱数\n\nrand(bin)\n\n# %%\n# 確率分布オブジェクトの乱数を複数個生成\n\n@show rand(bin, 20);\n\n# %%\n# サンプルのヒストグラム\n# norm = true で確率密度函数と比較できるようにする。\n# alpha = 0.3 で半透明化pp\n# bin = -0.5:n+0.5 で 1 刻みの適切なビンを設定\n\nhistogram(sample_of_means; norm=true, alpha=0.3, bin=-0.5:n+0.5, label=\"sample of means\")\n\n# %%\n# -0.5:n+0.5 は [-0.5, 0.5, 1.5, 2.5, ..., 19.5, 20.5] とほぼ等価\n\n-0.5:n+0.5\n\n# %%\n@show collect(-0.5:n+0.5);\n\n# %%\n# 平均μ、標準偏差σの正規分布オブジェクトは次にようにして作れる。\n\nnormal = Normal(n*p, √(n*p*(1-p)))\n\n# %%\n# 確率分布オブジェクト dist は plot(dist) でプロットできる。\n# lw = 2 で2倍の太さでプロット\n\nplot(normal, 0, 20; label=\"normal dist.\", lw=2)\n\n# %%\n# 以上を重ねてプロット\n\nhistogram(sample_of_means; norm=true, alpha=0.3, bin=-0.5:n+0.5, label=\"rand(Binomial($n, $p))\")\nplot!(Normal(n*p, √(n*p*(1-p))), 0, 20; label=\"normal approx.\", lw=2)\n\n# %%\n# サイコロを10回振って出た目の平均値の分布は正規分布でよく近似される。\n\nn = 10\nM = [mean(rand(1:6, n)) for _ in 1:10^5]\nhistogram(M; norm=true, alpha=0.3, bin=0.95:0.1:6.05, label=\"mean(rand(1:6, 10))\")\nplot!(Normal(mean(1:6), std(1:6; corrected=false)/√n), 1, 6; label=\"normal approx.\", lw=2)\n\n# %%\n# 2つの確率パラメータ(比率パラメータ)が等しい二項分布で生成されたサンプルのZ統計量は\n# 近似的に標準正規分布に従う。\n\n\"\"\"\"\"\"\nfunction gensample(bin1, bin2)\n    m, n = ntrials(bin1), ntrials(bin2)\n    a, b = rand(bin1), rand(bin2)\n    c, d = m - a, n - b\n    a, b, c, d\nend\n\n\"\"\"Z statistic of 2×2 contingency table\"\"\"\nfunction zstat(a, b, c, d)\n    a*d - b*c == 0 && return zero(inv(a))\n    m, n = a + c, b + d\n    N = a + b + c + d\n    p = (a + b)/N\n    Z = (a/m - b/n) / √(p*(1-p)*(1/m + 1/n))\n    Z\nend\n\nm, n, p = 30, 20, 0.3\nbin1 = Binomial(m, p)\nbin2 = Binomial(n, p)\nZ = [zstat(gensample(bin1, bin2)...) for _ in 1:10^5]\n\nhistogram(Z; norm=true, alpha=0.3, bin=-4.25:0.5:4.25, label=\"Z statistics\")\nplot!(Normal(), -4, 4; label=\"std normal dist.\", lw=2)\n\n# %%\n@code_warntype zstat(1, 2, 3, 4)\n\n# %%\n# 数式処理を使って、Z統計量の2乗がPearsonのχ²統計量に一致することを確認。\n# 上の数値計算で使ったzstat函数をそのまま数式処理で利用する。\n\nusing SymPy\n\n@syms a b c d\nZ = zstat(a, b, c, d)\n\n# %%\n# Z^2 |> factor は factor(Z^2) に等価\n# 以下の計算結果はPearsonのχ²統計量の有名な表示に一致\n\nZ^2 |> factor\n\n# %%\n# (O - E)²/E の和で定義されたPearsonのχ²統計量\n\n\"\"\"Pearson's χ² statistic of 2×2 contingency table\"\"\"\nfunction chisqstat(a, b, c, d)\n    a*d - b*c == 0 && return zero(inv(a))\n    N = a + b + c + d\n    s, f = a + b, c + d\n    m, n = a + c, b + d\n    Ea, Eb, Ec, Ed = m*s/N, n*s/N, m*f/N, n*f/N\n    X² = (a - Ea)^2/Ea + (b - Eb)^2/Eb + (c - Ec)^2/Ec + (d - Ed)^2/Ed\nend\n\nX² = chisqstat(a, b, c, d)\n\n# %%\n# 以下の計算結果は2×2の分割表のPearson χ²統計量に関する有名な公式\n\nX² |> factor\n\n# %%\n# 正確二項検定のP値の定義\n\n# \\lessapprox TAB → ⪅\n# \\approx TAB → ≈\nx ⪅ y = x < y || x ≈ y\n\n\"\"\"p-value function of exact binomial test\"\"\"\npval_exact(dist, k) = sum(pdf(dist, j) for j in support(dist) if pdf(dist, j) ⪅ pdf(dist, k))\n\n# %%\n# 正確二項検定のP値の例　(パラメータpを固定した場合(1))\n\nn, p = 20, 0.3\nbin = Binomial(n, p)\n\nk = support(bin)\ny = pval_exact.(bin, k)\nplot(k, y; label=\"\", marker=:o)\nplot!(; xtick=0:20, ytick=0:0.05:1)\nplot!(; xlabel=\"data k\", ylabel=\"p-value for parameter n = $n, p = $p\")\n\n# %%\n# 正確二項検定のP値の例　(データkを固定した場合)\n\nn, k = 20, 6\n\np = 0:0.002:1\ny = @. pval_exact(Binomial(n, p), k)\nplot(p, y; label=\"\")\nplot!(; xtick=0:0.1:1, ytick=0:0.05:1)\nplot!(; xlabel=\"parameter p\", ylabel=\"p-value for data n = $n, k = $k\")\n\n# %%\n# 信頼区間函数の定義\n\nusing Roots\n\n\"\"\"generic confidence interval function\"\"\"\nfunction confint(pvalfunc, mlefunc, n, k, pmin, pmax; α = 0.05)\n    f(p) = pvalfunc(n, p, k) - α\n    ci = find_zeros(f, pmin, pmax)\n    length(ci) ≥ 2 && return ci\n    pmle = mlefunc(n, k)\n    first(ci) > pmle ? [pmin, first(ci)] : [first(ci), pmax]\nend\n\n\"\"\"confidence interval function for exact binomial test\"\"\"\nfunction confint_bin(n, k; α = 0.05)\n    pvalfunc(n, p, k) = pval_exact(Binomial(n, p), k)\n    mlefunc(n, k) = k/n\n    pmin, pmax = 0.0, 1.0\n    confint(pvalfunc, mlefunc, n, k, pmin, pmax; α)\nend\n\n# %%\n# 正確二項検定のデータkを固定した場合のP値函数のプロットに\n# 95%信頼区間のプロットを追加\n\nn, k = 20, 6\nα = 0.05\nci = confint_bin(n, k; α)\n\np = 0:0.002:1\ny = @. pval_exact(Binomial(n, p), k)\nplot(p, y; label=\"\")\nplot!(ci, [α, α]; label=\"$(100(1 - α))% confidence interval\", lw=3)\nplot!(; xtick=0:0.1:1, ytick=0:0.05:1)\nplot!(; xlabel=\"parameter p\", ylabel=\"p-value for data n = $n, k = $k\")\n\n# %% tags=[]\n# データkを動かして信頼区間をプロット (1)\n\nn = 20\nk = 0:n\nα = 0.05\nci = confint_bin.(n, k; α)\nciL, ciR = first.(ci), last.(ci)\n\nplot(; legend=:topleft)\nplot!(k, ciL; label=\"min. of confidence interval\")\nplot!(k, ciR; label=\"max. of confidenceinterval\")\nplot!(k, ciL; label=\"$(100(1 - α))% confidence interval (n = $n)\", lw=0, frange=ciR, fa=0.1)\nplot!(; xtick=0:n, ytick=0:0.1:1)\nplot!(; xlabel=\"data k\", ylabel=\"parameter p\")\n\n# %% tags=[]\n# データkを動かして信頼区間をプロット (2)\n\nn = 20\nk = 0:n\nα = 0.05\nci = confint_bin.(n, k; α)\n\nplot(; legend=:topleft)\nfor i in eachindex(ci)\n    plot!([k[i], k[i]], ci[i]; label=\"\", lw=5)\nend\nplot!(; xtick=0:n, ytick=0:0.1:1)\nplot!(; xlabel=\"data k\", ylabel=\"parameter p\")\ntitle!(\"$(100(1 - α))% confidence intervals (n = $n)\"; titlefontsize=12)\n\n# %% tags=[]\n# データkを動かして信頼区間をプロット (3)\n\nn = 20\nk = 0:n\nα = 0.05\nci = confint_bin.(n, k; α)\n\nplot(; legend=:topleft)\nfor i in eachindex(ci)\n    plot!([k[i], k[i]], ci[i]; label=\"\", lw=5, c=1)\nend\nplot!(; xtick=0:n, ytick=0:0.1:1)\nplot!(; xlabel=\"data k\", ylabel=\"parameter p\")\ntitle!(\"$(100(1 - α))% confidence intervals (n = $n)\"; titlefontsize=12)\n\n# %%\n# P値函数のヒートマップ\n\nn = 20\np = 0:0.002:1\nk = 0:n\nα = 0.05\nci = confint_bin.(n, k; α)\n\nz = @. pval_exact(Binomial(n, p), k')\nheatmap(k, p, z; clim=(-0.2, 1.2), colorbar_title=\"p-value\")\nplot!(; xtick=0:n, ytick=0:0.1:1)\nplot!(; xlabel=\"data k\", ylabel=\"parameter p\")\nplot!(; size=(680, 400))\n\n# %%\n# P値函数のヒートマップと信頼区間\n\nn = 20\np = 0:0.002:1\nk = 0:n\nα = 0.05\nci = confint_bin.(n, k; α)\n\nz = @. pval_exact(Binomial(n, p), k')\nheatmap(k, p, z; clim=(-0.2, 1.2), colorbar_title=\"p-value\")\nplot!(; xtick=0:n, ytick=0:0.1:1)\nplot!(; xlabel=\"data k\", ylabel=\"parameter p\")\nplot!(; size=(680, 400))\nfor i in eachindex(ci)\n    plot!([k[i], k[i]], ci[i]; label=\"\", lw=3, c=:cyan, alpha=0.8)\nend\nplot!(xlim=(-0.5, n+0.5), ylim=(0, 1))\ntitle!(\"$(100(1 - α))% confidence intervals (n = $n)\"; titlefontsize=12)\n\n# %%\n", "meta": {"hexsha": "d5a367aebbeb0bfde6481f3a4e30629950812b47", "size": 6871, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0024/JuliaLang examples of probability and statistics.jl", "max_stars_repo_name": "genkuroki/public", "max_stars_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-06-06T00:33:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T06:56:08.000Z", "max_issues_repo_path": "0024/JuliaLang examples of probability and statistics.jl", "max_issues_repo_name": "genkuroki/public", "max_issues_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0024/JuliaLang examples of probability and statistics.jl", "max_forks_repo_name": "genkuroki/public", "max_forks_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-02T11:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T11:46:05.000Z", "avg_line_length": 22.0224358974, "max_line_length": 96, "alphanum_fraction": 0.5936544899, "num_tokens": 3362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8652240791017536, "lm_q1q2_score": 0.7894617325674336}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 9d286b46-73ae-49f7-b834-791b9ef95420\nbegin\n\tusing PlutoUI\nend\n\n# ╔═╡ 4abf8eda-2c36-11ec-3cdb-4104751a59ad\nmd\"\"\"\n\n#### Solution: Flash Practice Problem\n\n\"\"\"\n\n# ╔═╡ c017ef4d-a828-4f46-922a-453d72636c39\nmd\"\"\"$(PlutoUI.LocalResource(\"./figs/Fig-VLE-Ideal-Pxy-P2-F19.png\"))\"\"\"\n\n# ╔═╡ d5b781d8-6e6a-4bc9-9b45-1272e1b86e61\nmd\"\"\"\na) What temperature $T$ (K) is the Flash drum operating at?\n\nTo find the temperature, we can solve the Antoine equation for $T$. \nAs a reminder, the Antoine equation is given by (note this is the $\\log_{10}$ version):\n\n$$\\begin{equation}\n\\log_{10}\\left(P_{i}^{sat}~[\\mathrm{bar}]\\right) = A - \\frac{B}{C+T[K]}\n\\end{equation}$$\n\nwhere the Antoine parameters are given in the problem. We can solve for $T$ to get the expression:\n\n$$T = - \\left(C + \\frac{B}{\\log_{10}P^{sat}_{i} - A}\\right)$$\n\nWe can choose _either_ pure component endpoints, let's choose pure component 1 which gives $P_{1}^{sat}\\simeq$ 15.9 bar.\n\"\"\"\n\n# ╔═╡ e86e41b3-d39b-4986-b1cd-4ed34eaabae5\nbegin\n\t\n\t# what are the A, B, and C for component 1?\n\tA₁ = 4.45 \t\t# units: AU\n\tB₁ = 718.1 \t\t# units: 1/K\n\tC₁ = -22.01 \t# units: K\n\t\n\tA₂ = 3.98 \t\t# units: AU\n\tB₂ = 677.1 \t\t# units: 1/K\n\tC₂ = -24.51 \t# units: K\n\t\n\tP1sat = 15.9 \t# units: bar\n\tP2sat = 7.5 \t# units: bar\n\tP = 10.5 \t\t# units: bar\n\t\n\t# esimate T -\n\tT = -(C₁ + B₁/(log10(P1sat) - A₁))\n\t\n\twith_terminal() do\n\t\tprintln(\"T = $(round(T; digits=2)) K\")\n\tend\nend\n\n# ╔═╡ 796fd591-bf7f-4b94-af8f-f5b7ab25e563\nmd\"\"\"\nb) Estimate the outlet composition and the mol flow rates for the input, liqud and vapor streams\n\nThe equlibrium compositions can be estimated directly from the _Pxy_ diagram: \n\n* The composition of the liquid stream exiting the drum $x^{eq}_{1}\\simeq$ 0.34\n* The composition of the vapor stream exiting the drum $y^{eq}_{1}\\simeq$ 0.53\n\nTo estimate the mol flow rate of liquid and vapor that leaves the flash drum, we can use the lever rule and the species mol balance (as discussed in lecture and discussion). The Flash Lever Rule (FLR) is given as:\n\n$$\\frac{\\dot{L}}{\\dot{V}} = \\frac{y^{eq}_{i} - z_{i}}{z_{i} - x_{i}^{eq}}$$\n\n_Substitution_: We can re-arrange the FLR, to solve for $\\dot{L}$ in terms of $\\dot{V}$, and then subsutute that into the total mol balance to solve for $\\dot{V}$:\n\n$$\\dot{V} = \\dot{F}\\left(\\frac{b}{a} + 1\\right)^{-1}$$ \nOnce we have $\\dot{V}$ we can then solve for $\\dot{L}$. \n\n_Matrix-vector_: Alternatively, we could set this problem up in matrix vector form:\n\n$$\\begin{pmatrix}\n1 & 1 \\\\\n1 & -\\frac{b}{a}\n\\end{pmatrix}\n\\begin{pmatrix}\n\\dot{L} \\\\\n\\dot{V}\n\\end{pmatrix} = \n\\begin{pmatrix}\n\\dot{F} \\\\\n0\n\\end{pmatrix}$$\n\nand solve for $\\dot{L}$ and $\\dot{V}$ directly by inverting the 2$\\times$2 matrix.\n\n\"\"\"\n\n# ╔═╡ 453aba4c-fc32-46a7-ad1c-0c360a5dc886\nbegin\n\t\n\t# from the diagram -\n\ty1_eq = 0.53\n\tx1_eq = 0.34\n\tz1 = 0.42\n\tF_dot = 10 # units: mol/t\n\t\n\t# compte b and a -\n\tb = (y1_eq - z1)\n\ta = (z1 - x1_eq)\n\t\n\t# setup Ax = b\n\tA = [1 1 ; 1 -(b/a)]\n\tb = [F_dot; 0];\n\t\n\t# solve for L_dot and V_dot -\n\tx_graph = inv(A)*b\n\tL_dot = x_graph[1]\n\tV_dot = x_graph[2]\n\t\n\twith_terminal() do \n\t\tprintln(\"L_dot = $(round(L_dot; digits=1)) mol/t and V_dot = $(round(V_dot; digits=1)) mol/t\")\n\tend\nend\n\n# ╔═╡ c4f4a653-cd23-4c9a-9b3d-10da27ca9d79\nmd\"\"\"\nc) Numerical check on graphically values. If the pressure summation expression:\n\n$$\\begin{equation}\n        \\sum_{i=1}^{\\mathcal{M}}z_{i}\\left[\\frac{P_{i}^{sat}}{P}\\left(\\frac{\\dot{V}}{\\dot{F}}\\right)+\\frac{\\dot{L}}{\\dot{F}}\\right]^{-1} = 1\n\\end{equation}$$ \n\nis _significantly_ different than 1 (greater than $\\pm$ 10% difference), please re-estimate your graphical values (show your work).\n\"\"\"\n\n# ╔═╡ 2c1378b9-08e3-42ef-9239-fd86fd85cd38\nbegin\n\t\n\t# we only have two terms, since we are binary\n\tterm_1 = z1*((P1sat/P)*(V_dot/F_dot)+(L_dot/F_dot))^-1\n\tterm_2 = (1-z1)*((P2sat/P)*(V_dot/F_dot)+(L_dot/F_dot))^-1\n\ttest_value = (term_1 + term_2)\n\tfrac_error = (1.0 - test_value)*100\n\t\n\twith_terminal() do\n\t\tprintln(\"Percentage diff: $(round(frac_error; digits=2))%\")\n\tend\nend\n\n# ╔═╡ 91f257b4-b480-4179-b68a-760824600949\nmd\"\"\"\n\nd) _Analytically_ check your graphical composition estimates by computing $x^{eq}_{1}$ and $y^{eq}_{1}$ using the your VLE model and mol balances.\n\nStrategy:\n* Solve for $P_{i}^{sat}$ using the estimated $T$ from part a)\n* Solve for $x^{eq}_{1}$ using the pressure expression (then $x^{eq}_{2}$ = $1 - x^{eq}_{1}$).\n* Solve for $y^{eq}_{1}$ using the VLE model: $y^{eq}_{1}P$ = $x^{eq}_{1}P_{1}^{sat}$. (and then $y^{eq}_{2}$ = $1 - y^{eq}_{1}$).\n* Solve 2$\\times$2 system for $\\dot{L}$ and $\\dot{V}$ (either 2 species balances, or 1 species balance and the total mol balance)\n\n\"\"\"\n\n# ╔═╡ f167be1a-2801-4cc6-b036-6d6688dddb44\nbegin\n\t\n\t# 1) compute the saturation pressures -\n\tP1sat_aeq = 10^(A₁ - (B₁/(C₁ + T)))\n\tP2sat_aeq = 10^(A₂ - (B₂/(C₂ + T)))\n\t\n\twith_terminal() do\n\t\tprintln(\"P1sat_aeq = $(round(P1sat_aeq; digits=2)) bar and P2sat_aeq = $(round(P2sat_aeq; digits=2)) bar\")\n\tend\nend\n\n# ╔═╡ b8002941-f892-46b8-9c27-1cb08cc3c71b\nbegin\n\t\n\t# 2) estimate x1_eq from the pressure expression -\n\tx1_eq_a = (P - P2sat_aeq)/(P1sat_aeq - P2sat_aeq)\n\tx2_eq_a = 1 - x1_eq_a\n\t\n\twith_terminal() do\n\t\tprintln(\"x1_eq = $(round(x1_eq_a; digits=2)) and x2_eq = $(round(x2_eq_a; digits=2))\")\n\tend\nend\n\n# ╔═╡ 52fba159-cafc-4293-ab32-6b965ca957b8\nbegin\n\t\n\t# 3) estimate y1_eq and y2_eq -\n\ty1_eq_a = (x1_eq_a)*(P1sat_aeq/P)\n\ty2_eq_a = 1 - y1_eq_a\n\t\n\twith_terminal() do\n\t\tprintln(\"y1_eq = $(round(y1_eq_a; digits=2)) and y2_eq = $(round(y2_eq_a; digits=2))\")\n\tend\nend\n\n# ╔═╡ ed9fe0d8-0d9b-4ad2-b327-44d9798cc666\nbegin\n\t\n\t# 4) solve for the flow rates. We could do this as a traditional substitution, but lets be quick and setup as matrix vector \n\tA_flow = [x1_eq_a y1_eq_a ; x2_eq_a y2_eq_a]\n\tb_flow = [F_dot*z1 ; F_dot*(1 - z1)]\n\tflow_vec = inv(A_flow)*b_flow\n\t\n\t# out -\n\twith_terminal() do\n\t\tprintln(\"L_dot = $(round(flow_vec[1]; digits=1)) mol/t and V_dot = $(round(flow_vec[2]; digits=1)) mol/t\")\n\tend\nend\n\n# ╔═╡ dbfacc23-773b-49bb-a531-f460aacf5f98\nhtml\"\"\"\n<style>\nmain {\n    max-width: 1200px;\n    width: 90%;\n    margin: auto;\n    font-family: \"Roboto, monospace\";\n}\n\na {\n    color: blue;\n    text-decoration: none;\n}\n\n.H1 {\n    padding: 0px 30px;\n}\n</style>\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\n\n[compat]\nPlutoUI = \"~0.7.16\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[HypertextLiteral]]\ngit-tree-sha1 = \"f6532909bf3d40b308a0f360b6a0e626c0e263a8\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.1\"\n\n[[IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"a8709b968a1ea6abc2dc1967cb1db6ac9a00dfb6\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.5\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"4c8a7d080daca18545c56f1cac28710c362478f3\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.16\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─4abf8eda-2c36-11ec-3cdb-4104751a59ad\n# ╟─c017ef4d-a828-4f46-922a-453d72636c39\n# ╠═d5b781d8-6e6a-4bc9-9b45-1272e1b86e61\n# ╠═e86e41b3-d39b-4986-b1cd-4ed34eaabae5\n# ╟─796fd591-bf7f-4b94-af8f-f5b7ab25e563\n# ╠═453aba4c-fc32-46a7-ad1c-0c360a5dc886\n# ╟─c4f4a653-cd23-4c9a-9b3d-10da27ca9d79\n# ╠═2c1378b9-08e3-42ef-9239-fd86fd85cd38\n# ╟─91f257b4-b480-4179-b68a-760824600949\n# ╠═f167be1a-2801-4cc6-b036-6d6688dddb44\n# ╠═b8002941-f892-46b8-9c27-1cb08cc3c71b\n# ╠═52fba159-cafc-4293-ab32-6b965ca957b8\n# ╠═ed9fe0d8-0d9b-4ad2-b327-44d9798cc666\n# ╟─dbfacc23-773b-49bb-a531-f460aacf5f98\n# ╟─9d286b46-73ae-49f7-b834-791b9ef95420\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "125a21f7131d11993c24dfc0261e7f00a5d3639c", "size": 9500, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "prelims/P1/practice/Soln-Practice-Prelim-Flash.jl", "max_stars_repo_name": "agansky/ENGRI-1120-Cornell-Varner", "max_stars_repo_head_hexsha": "1a2103ed3a9cd94a677f09083c1bbef27db90a86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-15T20:05:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T20:05:45.000Z", "max_issues_repo_path": "prelims/P1/practice/Soln-Practice-Prelim-Flash.jl", "max_issues_repo_name": "agansky/ENGRI-1120-Cornell-Varner", "max_issues_repo_head_hexsha": "1a2103ed3a9cd94a677f09083c1bbef27db90a86", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prelims/P1/practice/Soln-Practice-Prelim-Flash.jl", "max_forks_repo_name": "agansky/ENGRI-1120-Cornell-Varner", "max_forks_repo_head_hexsha": "1a2103ed3a9cd94a677f09083c1bbef27db90a86", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-11-10T20:59:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T06:58:07.000Z", "avg_line_length": 26.7605633803, "max_line_length": 213, "alphanum_fraction": 0.6821052632, "num_tokens": 4075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.8652240808393983, "lm_q1q2_score": 0.7894617320927393}}
{"text": "export\n    isprime, iscoprime, ismersenneprime, isrieselprime,\n    primes, primesmask, primepi,\n    nthprime, nextprime, prevprime,\n    twinprimes\n\nNemo.isprime(n::UInt) = is_prime(n)\nNemo.isprime(n::Integer) = typemin(UInt) <= n <= typemax(UInt) ? (isprime ∘ UInt)(n) : (isprime ∘ fmpz)(n)\nNemo.isprime(n::Integer, mask) = n <= length(mask) ? mask[n] : isprime(n)\n\niscoprime(n::Integer, m::Integer) = n != 0 && m != 0 && gcd(n, m) == 1\n\nPrimes.primes(r::UnitRange{<:Integer}) = primes(first(r), last(r))\n\nPrimes.primesmask(r::UnitRange{<:Integer}) = primesmask(first(r), last(r))\n\nprimepi(a::Integer, b::Integer) = (count ∘ primesmask)(a, b)\nprimepi(r::UnitRange{<:Integer}) = primepi(first(r), last(r))\nprimepi(n::Integer) = primepi(1, n)\n\nnthprime(a::Integer, b::Integer) = (n = ceil(typeof(b), b*log(b+2) + b*(log∘log)(b+2)); primes(n)[a:b])\nnthprime(r::UnitRange{<:Integer}) = nthprime(first(r), last(r))\nnthprime(n::Integer) = nthprime(n, n)[1]\n\n# https://github.com/hwborchers/Numbers.jl/blob/master/src/primes.jl\nnextprime(n::T) where {T<:Integer} = begin\n    n <= 1 && return convert(T, 2)\n    n == 2 && return convert(T, 3)\n\n    n += iseven(n) ? one(T) : convert(T, 2)\n    isprime(n) && return n\n\n    m = mod(n, 3)\n    if m == 1\n        a = convert(T, 4); b = convert(T, 2)\n    elseif m == 2\n        a = convert(T, 2); b = convert(T, 4)\n    else\n        n += 2\n        a = convert(T, 2); b = convert(T, 4)\n    end\n\n    p = n\n    while !isprime(p)\n        p += a\n        isprime(p) && break\n        p += b\n    end\n    p\nend\n\n# https://github.com/hwborchers/Numbers.jl/blob/master/src/primes.jl\nprevprime(n::T) where {T<:Integer} = begin\n    n <= 2 && return zero(T)\n    n == 3 && return convert(T, 2)\n\n    n -= iseven(n) ? one(T) : convert(T, 2)\n    isprime(n) && return n\n\n    m = mod(n, 3)\n    if m == 1\n        a = convert(T, 2); b = convert(T, 4)\n    elseif m == 2\n        a = convert(T, 4); b = convert(T, 2)\n    else\n        n -= 2\n        a = convert(T, 2); b = convert(T, 4)\n    end\n\n    p = n\n    while !isprime(p)\n        p -= a\n        isprime(p) && break\n        p -= b\n    end\n    p\nend\n\n##  Find all twin primes\n# https://github.com/hwborchers/Numbers.jl/blob/master/src/primes.jl\ntwinprimes(a::Integer, b::Integer) = begin\n    P = primes(a, b)\n    inds = find(diff(P) .== 2)\n    hcat(P[inds], P[inds+1])\nend\ntwinprimes(r::UnitRange{<:Integer}) = twinprimes(first(r), last(r))\n", "meta": {"hexsha": "8e3d210de9be432b2eee7cda13cdae7c76fcec43", "size": 2400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Math/NumberTheory/primes.jl", "max_stars_repo_name": "Samayel/Brainstorm.jl", "max_stars_repo_head_hexsha": "9d83bb0a104973e498ba4ca84b0a27ede6c053ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-12-22T17:56:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T21:13:36.000Z", "max_issues_repo_path": "src/Math/NumberTheory/primes.jl", "max_issues_repo_name": "Samayel/Brainstorm.jl", "max_issues_repo_head_hexsha": "9d83bb0a104973e498ba4ca84b0a27ede6c053ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/NumberTheory/primes.jl", "max_forks_repo_name": "Samayel/Brainstorm.jl", "max_forks_repo_head_hexsha": "9d83bb0a104973e498ba4ca84b0a27ede6c053ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5862068966, "max_line_length": 106, "alphanum_fraction": 0.5683333333, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7893343467664888}}
{"text": "using LinearAlgebra\nusing DataDrivenDiffEq\nusing Plots\nusing ModelingToolkit\n\n# Frist we define a set of variables and parameters\n@variables u[1:3]\n@parameters w[1:2]\n\n# Now the equations which form our basis\nh = [u[1]; u[2]; cos(w[1]*u[2]+w[2]*u[3]); u[3]+u[2]]\n\n# Then we simply create a basis\nb = Basis(h, u, parameters = w)\n\n# And look at the corresponding eqs\nprintln(b)\n\n# Suppose we want to add another equation, say sin(u[1])\n# The basis behaves like an array\npush!(b, sin(u[1]))\nsize(b) # (5)\n\n# Adding an equation which is already present, does not change the basis\npush!(b, sin(u[1]))\nsize(b) # Still 5\n\n# We can iterate over the basis\nfor bi in b\n    println(bi)\nend\n\n# Index specific eqs\nb[3]\n\n# And of course evaluate\n# With fixed parameters\nb([1;2;3], p = [2; 4])\n# And without\nb([1;2;3])\n# Or for trajectories\nX = randn(3, 40)\nY_p = b(X)\nY = b(X, p = [2;4])\n\n\n# This allows you to transform a basis simply via\n@variables x[1:2]\ny = [sin(x[1]); cos(x[1]); x[2]]\nb2 = Basis(b(y), x, parameters = w)\nprintln(b2)\n\n\n# We can merge basis\nb3 = merge(b, b2)\n\n# Also in place\nmerge!(b3, b2)\nprintln(b3)\n\n# Get the variables or parameters\nvariables(b)\nparameters(b)\n\n# We can also check if two bases are equal\nb == b\n", "meta": {"hexsha": "b11f27aa6e3e682dd87921a747001b43a30c2382", "size": 1223, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Basis_Creation.jl", "max_stars_repo_name": "DanielParraUnam/DataDrivenDiffEq.jl", "max_stars_repo_head_hexsha": "8e81616be8463983fb0be9cf14f273b49c2a81ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-23T15:35:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-23T15:35:00.000Z", "max_issues_repo_path": "examples/Basis_Creation.jl", "max_issues_repo_name": "DanielParraUnam/DataDrivenDiffEq.jl", "max_issues_repo_head_hexsha": "8e81616be8463983fb0be9cf14f273b49c2a81ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Basis_Creation.jl", "max_forks_repo_name": "DanielParraUnam/DataDrivenDiffEq.jl", "max_forks_repo_head_hexsha": "8e81616be8463983fb0be9cf14f273b49c2a81ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.2537313433, "max_line_length": 72, "alphanum_fraction": 0.6672117743, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392797, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7893343336536301}}
{"text": "function theta2delta(th,dim)\r\n    return beta_inc((dim-1)/2,1/2,sin(th)^2)[1]\r\nend\r\nfunction delta2theta(delt,dim)\r\n    sintheta = sqrt(beta_inc_inv((dim-1)/2,1/2,delt)[1])\r\n    return asin(sintheta)\r\nend\r\n\r\nfunction epsilon2beta(ep,dim,numMode,N)\r\n    return numMode*(1-theta2delta(delta2theta(ep,dim)/2,dim)/numMode)^N/theta2delta(delta2theta(ep,dim)/4,dim)\r\nend\r\n\r\nfunction looseningratio_quad(ep,dim,kappaP)\r\n    loosenfactor = (1-kappaP*(1-cos(delta2theta(ep,dim))))\r\n    if loosenfactor <= 0\r\n        println(\"Insufficient samples!\")\r\n        return Inf\r\n    else\r\n        return 1/(1-kappaP*(1-cos(delta2theta(ep,dim))))\r\n    end\r\nend\r\n\r\nfunction beta2epsilon(beta,dim,numMode,N)\r\n    ep_u = 1.0\r\n    ep_l = 0.0\r\n    while ep_u - ep_l > 1e-10\r\n        ep = (ep_u+ep_l)/2\r\n        beta_ep = epsilon2beta(ep,dim,numMode,N)\r\n        if beta_ep > beta\r\n            ep_l = ep\r\n        else\r\n            ep_u = ep\r\n        end\r\n    end\r\n    return ep_u\r\nend\r\n\r\nfunction probabilistc_stability_certificate(state0,state;B,numMode,d,batchsize,K0,beta=0.01,tol=1e-4)\r\n    dim = size(B,1)\r\n    N = size(state0,2)\r\n    K,ga,P = soslyap_alternating(state0,state;B=B,d=d,batchsize=batchsize,K0=K0,tol=tol)\r\n    eigP = eigvals(P)\r\n    kappaP = maximum(eigP)/minimum(eigP)\r\n    if d == 1\r\n        ep = beta2epsilon(beta,dim,numMode,N)\r\n        return K,ga*looseningratio_quad(ep,dim,kappaP),ga,P\r\n    else\r\n        epsos = beta2epsilon(beta,dim,numMode,N)\r\n        stateK = zeros(dim,N)\r\n        for i in 1:N\r\n            stateK[:,i] = state[:,i]+B*K*state0[:,i]\r\n        end\r\n        boundnorm = norm_max(state0,stateK)/cos(delta2theta(epsos,dim))\r\n\r\n        phid = 0.0\r\n        for i in 1:d\r\n            phid += (2-2*cos(delta2theta(epsos,dim)))^(i/2)*binomial(d,i)\r\n        end\r\n        bound = (ga^d*(1+sqrt(kappaP)*phid)+boundnorm^d*sqrt(kappaP)*phid)^(1/d)\r\n\r\n        #=for betasos in 0.1*beta:0.1*beta:0.9*beta\r\n            epsos = beta2epsilon(betasos,dim,numMode,N)\r\n        \r\n            epnorm = minimum([numMode*(1-(beta-betasos)^(1/N)),1])\r\n\r\n            stateK = zeros(dim,N)\r\n            for i in 1:N\r\n                stateK[:,i] = state[:,i]+B*K*state0[:,i]\r\n            end\r\n\r\n            boundnorm = norm_max(state0,stateK)/cos(delta2theta(epnorm,dim))\r\n            \r\n            phid = 0.0\r\n            for i in 1:d\r\n                phid += (2-2*cos(delta2theta(epsos,dim)))^(i/2)*binomial(d,i)\r\n            end\r\n            boundnormclosed = boundnorm #+ opnorm(B*K)\r\n            bound = (ga^d*(1+sqrt(kappaP)*phid)+boundnormclosed^d*sqrt(kappaP)*phid)^(1/d)\r\n            push!(boundsearch,bound)\r\n        end=#\r\n        #println(\"Probability bisection: $boundsearch\")\r\n        return K,bound,ga,P\r\n        \r\n    end\r\n\r\nend\r\n\r\nfunction norm_max(state0,state)\r\n    traj_norm = 0.0\r\n    numTraj = size(state0)[2]\r\n    \r\n    for i = 1:numTraj\r\n        traj_norm_i = norm(state[:,i])/norm(state0[:,i])\r\n        if traj_norm_i > traj_norm\r\n            traj_norm = traj_norm_i\r\n        end\r\n    end\r\n    \r\n    return traj_norm\r\nend\r\n    \r\nfunction probabilistc_LQR_certificate(state0,state;B,numMode,Q,R,kappaU,K0,beta=0.01,tol=1e-4)\r\n    dim = size(B,1)\r\n    N = size(state0,2)\r\n\r\n    ep = beta2epsilon(beta,dim,numMode,N)\r\n\r\n    lowbound = 1-kappaU*(1-cos(delta2theta(ep,dim)))\r\n    #println(\"lowbound: $lowbound\")\r\n    if lowbound < 0\r\n        lowbound = 0\r\n    end\r\n\r\n    K, xi, P = LQR_alternating(state0,state;B=B,Q=Q,R=R,kappaU=kappaU,lowbound=lowbound,K0=K0,ep=ep,tol=tol)\r\n\r\n    Z = P-Q-K'*R*K\r\n    eigZ = eigvals(Z)\r\n\r\n    ratio = 1-(maximum(eigZ)/minimum(eigZ))*(1-cos(delta2theta(ep,dim)))\r\n    #println(\"ratio: $ratio\")\r\n    #println(\"eigZ: $eigZ\")\r\n\r\n    if ratio < xi\r\n        println(\"Infeasible!\")\r\n    else\r\n        println(\"A feasible solution is found!\")\r\n    end\r\n    return K,xi,P,ratio\r\n\r\n\r\nend\r\n\r\n\r\n    ", "meta": {"hexsha": "eb4d00d2030b5f32bf4bafa5f1ecb634a7a4b1bb", "size": 3832, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ProbabilisticCertificates.jl", "max_stars_repo_name": "zhemingwang/DataDrivenSwitchControl", "max_stars_repo_head_hexsha": "2bb43ad448d77d52a8c1633a225549c3160f2eb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ProbabilisticCertificates.jl", "max_issues_repo_name": "zhemingwang/DataDrivenSwitchControl", "max_issues_repo_head_hexsha": "2bb43ad448d77d52a8c1633a225549c3160f2eb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ProbabilisticCertificates.jl", "max_forks_repo_name": "zhemingwang/DataDrivenSwitchControl", "max_forks_repo_head_hexsha": "2bb43ad448d77d52a8c1633a225549c3160f2eb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5970149254, "max_line_length": 111, "alphanum_fraction": 0.5668058455, "num_tokens": 1208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535723, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7893110960708372}}
{"text": "using TriangleMesh\nusing Plots\nusing Triplot\nusing LinearAlgebra\nusing SparseArrays\nusing ForwardDiff\nusing UnPack\ninclude(\"./TriFEMUtils.jl\") # plotting and misc routines\n\npoly = polygon_unitSquare()\n# poly = polygon_regular(5)\n# poly = polygon_Lshape()\nmax_triangle_area = .05/64\nmesh = create_mesh(poly, quality_meshing=true,\n                   add_switches=\"penva\"*string(max_triangle_area)*\"q\") # switches\n\n# manufactured solution\nuexact(x,y) = exp(sin(1+pi*x)*sin(pi*y))\nuBC(x,y) = uexact(x,y)\ndudx(x,y) = ForwardDiff.derivative(x->uexact(x,y),x)\ndudy(x,y) = ForwardDiff.derivative(y->uexact(x,y),y)\nf(x,y) = -(ForwardDiff.derivative(x->dudx(x,y),x) +\n           ForwardDiff.derivative(y->dudy(x,y),y)) # -(du^2/dx^2 + du^2/dy^2)\n\n# define Dirichlet and Neumann boundaries\non_Neumann_boundary(x,y) = x ≈ 1 && y > 0 && y < 1 # right face x = 1 (excluding corners)\non_Dirichlet_boundary(x,y) = !on_Neumann_boundary(x,y) # Dirichlet boundary = everywhere else\n∇u_dot_n(x,y) = dudx(x,y) # note that n = [1,0] on the Neumann face\n\n# ordering of reference element vertices\n# 3\n# |`.\n# 1--2\nreference_vertices = [[-1,1,-1],[-1,-1,1]] # stored as [r,s]\nreference_face_indices = [[1,2],[2,3],[1,3]] # ordering of faces for the reference element\nreference_elem_info = (;reference_face_indices,reference_vertices)\n\n# define reference basis functions\nλ1(r,s) = -(r+s)/2\nλ2(r,s) = (1+r)/2\nλ3(r,s) = (1+s)/2\nλ(r,s) = [λ1.(r,s) λ2.(r,s) λ3.(r,s)]\ndλr() = [-.5 .5 0.0]\ndλs() = [-.5 0.0 .5]\n\n# x,y = lists of vertices\nfunction compute_geometric_terms(x,y)\n    # dx(r,s)/dr = dλ1/dr*x1 + dλ2/dr*x2 + dλ3/dr*x3 = [dλ1/dr dλ2/dr dλ3/dr] * [x1; x2; x3]\n    dxdr,dydr = dλr()*x, dλr()*y\n    dxds,dyds = dλs()*x, dλs()*y\n    G = [dxdr dxds; dydr dyds] # G*r = x, r = inv(G)*x\n    J = det(G) # change of variables det(Jacobian) for integration\n    drdx, dsdx, drdy, dsdy = inv(G)\n    return J, drdx, dsdx, drdy, dsdy\nend\n\n# assemble stiffness matrix and RHS vector\nfunction assemble_FE_matrix(mesh)\n    VX,VY,EToV = unpack_mesh_info(mesh)\n    num_vertices = length(VX)\n    num_elements = size(EToV,2) # number of elements = of columns\n\n    A = spzeros(num_vertices, num_vertices)\n    b = zeros(num_vertices)\n    for e = 1:num_elements # loop through all elements\n        ids = EToV[:,e] # vertex ids = local to global index maps\n        xv,yv = VX[ids],VY[ids]\n\n        # compute geometric mappings\n        J,drdx,dsdx,drdy,dsdy = compute_geometric_terms(xv,yv)\n        dλdx = drdx*dλr() + dsdx*dλs() # dλr() = [dλ1/dr dλ2/dr dλ3/dr]\n        dλdy = drdy*dλr() + dsdy*dλs() # dλs() = [dλ1/ds dλ2/ds dλ3/ds]\n        reference_elem_area = 2.0\n        @. A[ids,ids] += J*reference_elem_area*(dλdx'*dλdx + dλdy'*dλdy) # (dλdx'*dλdx)_ij = dλj/dx * dλi/dx\n\n        # midpoint quadrature rule\n        x_mid,y_mid = sum(xv)/3, sum(yv)/3 # midpoint rule = averages of vertex locations\n        w_mid = 2.0\n        b[ids] .+= J*vec(λ(-1/3,-1/3))*(w_mid.*f(x_mid,y_mid)) # λ at midpt = 1/3 constant\n    end\n    return A,b\nend\n\nfunction impose_Neumann_BCs!(b,mesh,reference_elem_info)\n\n    @unpack reference_face_indices, reference_vertices = reference_elem_info\n    VX,VY,EToV = unpack_mesh_info(mesh)\n    boundary_indices, boundary_faces = get_boundary_info(reference_face_indices, mesh)\n    # contributions from Neumann BCs\n    for (f,e) in boundary_faces\n        ref_fids = reference_face_indices[f]\n        fids = EToV[ref_fids,e]\n        xf,yf = VX[fids],VY[fids]\n        x_mid,y_mid = sum(xf)/2,sum(yf)/2\n\n        if on_Neumann_boundary(x_mid,y_mid)\n            r,s = reference_vertices\n            r_mid, s_mid = sum(r[ref_fids])/2, sum(s[ref_fids])/2\n            w_mid = 2.0\n\n            ids = EToV[:,e]\n            face_length = sqrt((xf[1]-xf[2])^2 + (yf[1]-yf[2])^2)\n            b[ids] .+= face_length/2 * vec(λ(r_mid,s_mid)) * w_mid * ∇u_dot_n(x_mid,y_mid) # ∫ ∇u⋅n ϕ_i on each Neumann face\n        end\n    end\n    return b\nend\nfunction impose_Dirichlet_BCs!(A,b,mesh,reference_elem_info)\n\n    @unpack reference_face_indices, reference_vertices = reference_elem_info\n    VX,VY,EToV = unpack_mesh_info(mesh)\n    boundary_indices, boundary_faces = get_boundary_info(reference_face_indices, mesh)\n\n    # impose Dirichlet BCs\n    for i in boundary_indices\n        xi,yi = VX[i],VY[i]\n        if on_Dirichlet_boundary(xi,yi)\n            b -= Vector(A[:,i]*uBC(xi,yi))\n            A[:,i] .= 0\n            A[i,:] .= 0\n            A[i,i] = 1.0\n        end\n    end\n    for i in boundary_indices\n        xi,yi = VX[i],VY[i]\n        if on_Dirichlet_boundary(xi,yi)\n            b[i] = uBC(xi,yi)\n        end\n    end\n    return A,b\nend\n\nA,b = assemble_FE_matrix(mesh)\nb   = impose_Neumann_BCs!(b,mesh,reference_elem_info)\nA,b = impose_Dirichlet_BCs!(A,b,mesh,reference_elem_info)\nu = A\\b\nVX,VY,EToV = unpack_mesh_info(mesh)\n@show maximum(abs.(u .- uexact.(VX,VY)))\ntriplot(VX,VY,u .- uexact.(VX,VY),EToV)\n# triplot(VX,VY,uexact.(VX,VY),EToV)\n", "meta": {"hexsha": "e40ddc8003e9e1f6a810ca8885c8f6f7b5e699f0", "size": 4910, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "weeks9_to_10/fem_laplace_2D.jl", "max_stars_repo_name": "jlchan/caam452_s21", "max_stars_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:38:43.000Z", "max_issues_repo_path": "weeks9_to_10/fem_laplace_2D.jl", "max_issues_repo_name": "jlchan/caam452_s21", "max_issues_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "weeks9_to_10/fem_laplace_2D.jl", "max_forks_repo_name": "jlchan/caam452_s21", "max_forks_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8226950355, "max_line_length": 124, "alphanum_fraction": 0.6366598778, "num_tokens": 1698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693716759489, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7893110920603674}}
{"text": "\"\"\"\n    LinearRegression()\nClassic regression model. This struct has no parameter.\nIf you want to use polynomial model, use `Regression.make_design_matrix()`.\n\nsee also: [`make_design_matrix`](@ref)\n\n# Example\n```jldoctest regression\njulia> x = [\n    16.862463771320925 68.10823385851712\n    15.382965696961577 65.4313485700859\n    8.916228406218375 53.92034559524475\n    10.560285659132695 59.17305391117168\n    12.142253214135884 62.28708207525656\n    5.362107221163482 43.604947901567414\n    13.893239446341777 62.44348617377496\n    11.871357065173395 60.28433066289655\n    29.83792267802442 69.22281924803998\n    21.327107214235483 70.15810991597944\n    23.852372696012498 69.81780163668844\n    26.269031430914108 67.61037566099782\n    22.78907104644012 67.78105545358633\n    26.73342178134947 68.59263965946904\n    9.107259141706415 56.565383817343495\n    29.38551885863976 68.1005579469209\n    7.935966787763017 53.76264777936664\n    29.01677894379809 68.69484161138638\n    6.839609488194577 49.69794758177567\n    13.95215840314148 62.058116579899085]; #These data are also used to explanations of other functions.\n\njulia> t = [169.80980778351542, 167.9081124078835, 152.30845618985222, 160.3110300206261, 161.96826472170756, 136.02842285615077, 163.98131131382686, 160.117817321485, 172.22758529098235, 172.21342437006865, 171.8939175591617, 169.83018083884602, 171.3878062674257, 170.52487535026015, 156.40282783981309, 170.6488327896672, 151.69267899906185, 172.32478221316322, 145.14365314788827, 163.79383292080666];\n\njulia> model = LinearRegression()\nLinearRegression(Float64[])\n\njulia> fit!(model, x, t)\n3-element Vector{Float64}:\n -0.04772448076255398\n  1.395963968616736\n 76.7817095600793\n\njulia> model(x)\n20-element Vector{Float64}:\n 171.05359766482795\n 167.38737053144575\n 151.62704681535598\n 158.88117658330424\n 163.15274911747872\n 137.3967419011542\n 163.28751869479999\n 160.3699086857777\n 171.99027166957023\n 173.70207799107243\n 173.10650291105486\n 169.9096820022986\n 170.31402414534642\n 171.25872436348817\n 155.31030802635905\n 170.44522606721017\n 151.45368882321284\n 171.29242257091374\n 145.83183688699864\n 162.74674475052848\n```\n\"\"\"\nmutable struct LinearRegression\n    w::Array\n    LinearRegression() = new(Array{Float64}(undef, 0))\nend\n\n\"\"\"\n    fit!(model, x, t)\n`x` must be the number of features in the first dimension and the second dimension must be the number of data.\n\"\"\"\nfunction fit!(model::LinearRegression, x, t)\n    check_size(x, t)\n    x = expand(x)\n    model.w = inv(x * x') * x * t\nend\n\n(model::LinearRegression)(x) = expand(x)' * model.w", "meta": {"hexsha": "af46be1a385df11fe455dc8e886522e8eeabf8d1", "size": 2574, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Regression/Base.jl", "max_stars_repo_name": "MommaWatasu/LearningHorse.jl", "max_stars_repo_head_hexsha": "f7cd74a3c2a1b09bd736844e30970b19cd3ae1d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-12-08T05:42:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T08:14:39.000Z", "max_issues_repo_path": "src/Regression/Base.jl", "max_issues_repo_name": "MommaWatasu/LearningHorse.jl", "max_issues_repo_head_hexsha": "f7cd74a3c2a1b09bd736844e30970b19cd3ae1d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-12T12:32:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-12T12:45:49.000Z", "max_forks_repo_path": "src/Regression/Base.jl", "max_forks_repo_name": "MommaWatasu/LearningHorse.jl", "max_forks_repo_head_hexsha": "f7cd74a3c2a1b09bd736844e30970b19cd3ae1d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-06T08:14:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T08:14:43.000Z", "avg_line_length": 31.3902439024, "max_line_length": 405, "alphanum_fraction": 0.7777777778, "num_tokens": 991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913356558485, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7892771740559009}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n\nfunction _co_aberration(jd::T, ra::T, dec::T, eps::T) where {T<:AbstractFloat}\n    t = (jd - J2000) / JULIANCENTURY\n    if isnan(eps)\n        eps = true_obliquity(jd)\n    end\n    sunlong = sunpos(jd, radians=true)[3]\n    e = @evalpoly t 0.016708634 -0.000042037 -0.0000001267\n    pe = @evalpoly t 102.93735 1.71946 0.00046\n    sd, cd = sincos(deg2rad(dec))\n    ce = cos(eps)\n    te = tan(eps)\n    sp, cp = sincos(deg2rad(pe))\n    ss, cs = sincos(sunlong)\n    sa, ca = sincos(deg2rad(ra))\n    t1 = (cs*ce*(te*cd - sa*sd) + ca*sd*ss)\n    t2 = (cp*ce*(te*cd - sa*sd) + ca*sd*sp)\n    d_ra = 20.49552*(e*(ca*cp*ce + sa*sp) - ca*cs*ce - sa*ss)/cd\n    d_dec = 20.49552*(e*t2 - t1)\n    return d_ra, d_dec\nend\n\n\"\"\"\n    co_aberration(jd, ra, dec[, eps=NaN]) -> d_ra, d_dec\n\n### Purpose ###\n\nCalculate changes to right ascension and declination due to the effect\nof annual aberration\n\n### Explanation ###\n\nWith reference to Meeus, Chapter 23\n\n### Arguments ###\n\n* `jd`: julian date, scalar or vector\n* `ra`: right ascension in degrees, scalar or vector\n* `dec`: declination in degrees, scalar or vector\n* `eps` (optional): true obliquity of the ecliptic (in radians). It will be\n  calculated if no argument is specified.\n\n### Output ###\n\nThe 2-tuple `(d_ra, d_dec)`:\n\n* `d_ra`: correction to right ascension due to aberration, in arc seconds\n* `d_dec`: correction to declination due to aberration, in arc seconds\n\n### Example ###\n\nCompute the change in RA and Dec of Theta Persei (RA = 2h46m,11.331s, Dec = 49d20',54.5'')\ndue to aberration on 2028 Nov 13.19 TD\n\n```jldoctest\njulia> using AstroLib\n\njulia> jd = jdcnv(2028,11,13,4, 56)\n2.4620887055555554e6\n\njulia> co_aberration(jd,ten(2,46,11.331)*15,ten(49,20,54.54))\n(30.04404628365077, 6.699400463119431)\n```\n\nd_ra = 30.04404628365103'' (≈ 2.003s)\nd_dec = 6.699400463118504''\n\n### Notes ###\n\nCode of this function is based on IDL Astronomy User's Library.\n\nThe output d_ra is *not* multiplied by cos(dec), so that\napparent_ra = ra + d_ra/3600.\n\nThese formula are from Meeus, Chapters 23.  Accuracy is much better than 1\narcsecond. The maximum deviation due to annual aberration is 20.49'' and occurs when the\nEarth's velocity is perpendicular to the direction of the star.\n\nThis function calls [`true_obliquity`](@ref) and [`sunpos`](@ref).\n\"\"\"\nco_aberration(jd::Real, ra::Real, dec::Real, eps::Real=NaN) =\n    _co_aberration(promote(float(jd), float(ra), float(dec), float(eps))...)\n\nfunction co_aberration(jd::AbstractVector{R}, ra::AbstractVector{R},\n                       dec::AbstractVector{R}, eps::Real=NaN) where {R<:Real}\n    @assert length(jd) == length(ra) == length(dec) \"jd, ra and dec vectors should be of the same length\"\n    typejd = float(R)\n    ra_out  = similar(ra,  typejd)\n    dec_out = similar(dec, typejd)\n    for i in eachindex(jd)\n        ra_out[i], dec_out[i] = co_aberration(jd[i], ra[i], dec[i], eps)\n    end\n    return ra_out, dec_out\nend\n", "meta": {"hexsha": "4a498a3a600b5de3e47f1fc7a83531630eea8f3d", "size": 2973, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/co_aberration.jl", "max_stars_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_stars_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2016-09-11T14:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T20:45:36.000Z", "max_issues_repo_path": "src/co_aberration.jl", "max_issues_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_issues_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 64, "max_issues_repo_issues_event_min_datetime": "2017-01-19T21:03:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:27:46.000Z", "max_forks_repo_path": "src/co_aberration.jl", "max_forks_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_forks_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:11:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:55:21.000Z", "avg_line_length": 30.96875, "max_line_length": 105, "alphanum_fraction": 0.6656575849, "num_tokens": 1013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.789277173114062}}
{"text": "\na = [-0.1,0.2,0.3]\nA = BandedMatrix(-2 => Vcat([1], Fill(1,∞)),  0 => Vcat(a, Fill(0,∞)), 1 => Vcat([1/4], Fill(1/4,∞)))\nℓ = λ -> ql(A-λ*I).L[1,1]\nx,y = range(-2,2; length=200),range(-2,2;length=200)\n    z = abs.(ℓ.(x' .+ y.*im))\n    contour(x,y,z; nlevels=50, title=\"z^2 + 1/(4z)\")\n     scatter!(eigvals(Matrix(A[1:100,1:100])))\n     scatter!(eigvals(Matrix(A[1:100,1:100]')))\n\na = [-0.5,0.2,0.3]\nA = BandedMatrix(-2 => Vcat([1], Fill(1,∞)),  0 => Vcat(a, Fill(0,∞)), 1 => Vcat([1/4], Fill(1/4,∞)))\nℓ = λ -> ql(A-λ*I).L[1,1]\nx,y = range(-2,2; length=200),range(-2,2;length=200)\n    z = abs.(ℓ.(x' .+ y.*im))\n    contour(x,y,z; nlevels=50, title=\"z^2 + 1/(4z)\")\n     scatter!(eigvals(Matrix(A[1:100,1:100])); label=\"A finite section\")\n     scatter!(eigvals(Matrix(A[1:100,1:100]')); label=\"A' finite section\")\n\na = [-0.5,0.2,0.5]\nA = BandedMatrix(-2 => Vcat([1], Fill(1,∞)),  0 => Vcat(a, Fill(0,∞)), 1 => Vcat([1/4], Fill(1/4,∞)))\nℓ = λ -> ql(A-λ*I).L[1,1]\nx,y = range(-2,2; length=200),range(-2,2;length=200)\n    z = abs.(ℓ.(x' .+ y.*im))\n    contour(x,y,z; nlevels=50, title=\"z^2 + 1/(4z)\")\n    scatter!(eigvals(Matrix(A[1:100,1:100]')); label=\"A' finite section\")     \n    scatter!(eigvals(Matrix(A[1:100,1:100])); label=\"A finite section\")\n\nx = range(-2,2,length=1_000)\n    plot(x, abs.(ℓ.(x.+eps()im)); label=\"abs(L[1,1])\")    \n\na = [-0.1,0.2,0.3]\nA = BandedMatrix(-2 => Vcat([1], Fill(1,∞)),  0 => Vcat(a, Fill(0,∞)), 1 => Vcat([1/4], Fill(1/4,∞)))\nQ,L = ql(A-(0.5+0.1im)*I)\nQ[1:10,1:11]*L[1:11,1:10] - (A-(0.5+0.1im)*I)[1:10,1:10]\n\nℓ(0.5+0.1im)\nql((A-(0.5+0.1im)*I)[1:1000,1:1000]).L[1,1]\n\n", "meta": {"hexsha": "050513c74daffdaa57f6295223799b8dda817010", "size": 1599, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/perttoeplitz.jl", "max_stars_repo_name": "UnofficialJuliaMirror/InfiniteLinearAlgebra.jl-cde9dba0-b1de-11e9-2c62-0bab9446c55c", "max_stars_repo_head_hexsha": "7e4896c12e635a591063ddc1a34d09ee64c10bb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-07-29T10:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T20:35:46.000Z", "max_issues_repo_path": "examples/perttoeplitz.jl", "max_issues_repo_name": "UnofficialJuliaMirror/InfiniteLinearAlgebra.jl-cde9dba0-b1de-11e9-2c62-0bab9446c55c", "max_issues_repo_head_hexsha": "7e4896c12e635a591063ddc1a34d09ee64c10bb0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 60, "max_issues_repo_issues_event_min_datetime": "2019-07-29T09:16:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T20:09:00.000Z", "max_forks_repo_path": "examples/perttoeplitz.jl", "max_forks_repo_name": "UnofficialJuliaMirror/InfiniteLinearAlgebra.jl-cde9dba0-b1de-11e9-2c62-0bab9446c55c", "max_forks_repo_head_hexsha": "7e4896c12e635a591063ddc1a34d09ee64c10bb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:51:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:51:02.000Z", "avg_line_length": 39.975, "max_line_length": 101, "alphanum_fraction": 0.5196998124, "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133565584851, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7892771665162519}}
{"text": "function trust_region(x0, deltahat, delta0, eta, f, g, h, max_iter=100, method=\"cauchy\", tol=10e-7)\n\n    \"\"\"\n    x0: vector of the initial starting point of the algorithm\n    deltahat: bound on the step length\n    delta0: starting trust region radius\n    eta: acceptance threshold\n    f: objective function\n    g: gradient function\n    h: Hessian function\n\tmethod: method to use for solving subproblem\n        \"cauchy\" - Cauchy point algorithm for Newton\n        \"dogleg\" - dogleg algorithm for Newton\n        \"cg_steihaug\" - Steihaug algorithm, CG method\n        \"SR1\" - symmetric rank 1 updating for quasi-Newton\n    max_iter: maximum number of iterations\n    tol: when to break out\n    \"\"\"\n\n    @assert deltahat > 0\n    @assert eta >= 0 && eta < 1/4\n    @assert delta0 > 0 && delta0 < deltahat\n\n    delta = delta0\n    n = length(x0)\n    xvals = Vector{Vector{Float64}}(); push!(xvals, x0)\n    ncalls = 0\n\n    for i in 1:max_iter\n        i % 100 == 0 && println(\"Iteration: \", i)\n\n        xcurr = xvals[end]\n\n        fk = f(xcurr)\n        gk = g(xcurr)\n        Bk = h(xcurr)\n\n        if !check_posdef(Bk)\n            Bk = cholesky_mod(1e-3, Bk)\n            ncalls += 1\n        end\n\n        p = solve_subproblem(delta, gk, Bk, method)\n        rho = compute_rho(xcurr, f, gk, Bk, p)\n\n        # decrease trust region radius\n        if rho < 1/4\n            delta *= 1/4\n\n        else\n            # increase trust region radius\n            if rho > 3/4 && norm(p,2) == delta\n                delta = min(2*delta, deltahat)\n            end\n        end\n\n        # accept the step\n        if rho > eta\n            xnew = xcurr + p\n        # reject the step\n        else\n            xnew = xcurr\n        end\n\n        push!(xvals, xnew)\n\n        if abs(mean(xnew - xcurr)) <= tol\n            println(\"Number of indefinite fixes \", ncalls)\n            println(\"Number of iterations: \", i)\n            return xvals\n        end\n\n    end\n    println(\"Finished algorithm without converging.\")\n    return xvals\n\nend\n\nfunction model(p, xcurr, fk, gk, Bk)\n    \"\"\"\n    p: vector in which to step in\n    xcurr: vector of the current iterate\n    fk: scalar, f(xk)\n    gk: vector, gradient(xk)\n    Bk: symmetric matrix, e.g., Hessian(xk)\n    \"\"\"\n    return fk + gk' * p + 1/2 * p' * Bk * p\nend\n\nfunction compute_rho(xcurr, f, gk, Bk, p)\n    \"\"\"\n    xcurr: vector of the current iterate\n    f: the objective function\n    gk: gradient(xk)\n    Bk: symmetric matrix\n    p: step\n    \"\"\"\n    fk = f(xcurr)\n    n = length(p)\n    return ((fk - f(xcurr + p)) ./ (model(zeros(n), xcurr, fk, gk, Bk) - model(p, xcurr, fk, gk, Bk)))[1]\nend\n\nfunction cholesky_mod(beta, H, max_iter=1000)\n    @assert beta > 0\n    if minimum(diag(H)) > 0\n        tau = 0\n    else\n        tau = -minimum(diag(H)) + beta\n    end\n    #while true\n    for i in 1:max_iter\n        candidate = H + tau * eye(H)\n        check_posdef(candidate) && return candidate\n        tau = max(2*tau, beta)\n    end\n\n    error(\"Infinite loop encountered\")\nend\n\nfunction check_posdef(A)\n    try\n        L = chol(A)\n        return true\n    catch\n        return false\n    end\nend\n\n\n\nfunction solve_subproblem(delta, gk, Bk, method=\"cauchy\")\n\t\"\"\"\n    Solves the trust-region subproblem, returning a search direction pk.\n\n    delta: trust-region radius\n    gk: gradient at current iterate\n    Bk: Hessian (or symmetric PD matrix) at current iterate\n    method: method to use for solving subproblem\n        \"cauchy\" - Cauchy point algorithm for Newton\n        \"dogleg\" - dogleg algorithm for Newton\n        \"cg_steihaug\" - Steihaug algorithm, CG method\n        \"SR1\" - symmetric rank 1 updating for quasi-Newton\n    \"\"\"\n\n    if method == \"cauchy\"\n        return cauchy_point(delta, gk, Bk)\n    elseif method == \"dogleg\"\n        p_U = -gk' * gk ./ ((gk' * Bk * gk)' .* gk)\n        p_B = -Bk \\ gk\n        pnorm = norm(p_B, 2)\n        if pnorm > delta\n            return cauchy_point(delta, gk, Bk)\n        elseif pnorm < delta\n            return p_B\n        else\n            return dogleg(delta, gk, Bk, p_U)\n        end\n\telseif method == \"cg_steihaug\"\n        return cg_steihaug(delta, gk, Bk)\n    elseif method == \"SR1\"\n        println(\"\")\n    else\n        println(\"defaulting to Cauchy point\")\n        return cauchy_point(delta, gk, Bk)\n    end\nend\n\n\nfunction cauchy_point(delta, gk, Bk)\n    \"\"\"\n    delta: positive scalar, trust-region radius at current iteration\n    gk: gradient at current iterate\n    Bk: symmetric matrix, e.g., Hessian\n\n    Returns the cauchy point, a vector.\n    \"\"\"\n    tau = 1\n    if (gk' * Bk * gk)[1] > 0\n        tau = min(norm(gk,2)^3 ./ (delta * gk'*Bk*gk), 1)[1]\n    end\n\n    # Cauchy point equation\n    return -tau * delta / norm(gk, 2) * gk\nend\n\n\nfunction dogleg(delta, gk, Bk, p_U)\n    p_B = -Bk \\ gk\n    #p_U = -gk' * gk ./ ((gk' * Bk * gk)' .* gk)\n\n    # compute tau\n    diff = p_B - p_U\n    a = norm(diff, 2)^2\n    b = (2 * p_U' * diff)[1]\n    c = norm(p_U, 2)^2 - delta^2\n    tau = (1 + (-b + sqrt(b^2 - 4 * a *c)) / (2*a))\n\n    try\n        @assert tau >=0 && tau <= 2\n    catch\n        println(tau)\n    end\n\n    if tau <= 1\n        return tau * p_U\n    else\n        return p_U + (tau-1) * diff\n    end\n\nend\n\n\nfunction cg_steihaug(delta, gk, Bk)\n    gradnorm = norm(gk, 2)[1]\n    tol = min(0.5, sqrt(gradnorm)) * gradnorm\n    z = zeros(gk); r = gk; d = -gk\n\n    if norm(r, 2) < tol\n        return z\n    end\n\n    while true\n        # negative curvature\n        if (d' * Bk * d)[1] <= 0\n            return cauchy_point(delta, gk, Bk)\n        end\n        a = (r'*r ./ (d' * Bk * d))[1]\n        z += a * d\n\n        # violates trust region bound\n        if norm(z, 2) >= delta\n            return cauchy_point(delta, gk, Bk)\n        end\n        rold = r\n        r += a * Bk * d\n\n        # convergence tolerance satisfied\n        if norm(r, 2) <= tol\n            return z\n        end\n        beta = ((r' * r) ./ (rold' * rold))[1]\n        d = -r + beta * d\n    end\nend\n", "meta": {"hexsha": "1ea332aeb7664104edca103e9f46151908d81d80", "size": 5922, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "optimizers/trustregion.jl", "max_stars_repo_name": "dicai/descent.jl", "max_stars_repo_head_hexsha": "f684b69f6c8dadc86402fc465455b51c0484cedf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-08-12T22:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-25T01:37:28.000Z", "max_issues_repo_path": "optimizers/trustregion.jl", "max_issues_repo_name": "dicai/descent.jl", "max_issues_repo_head_hexsha": "f684b69f6c8dadc86402fc465455b51c0484cedf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimizers/trustregion.jl", "max_forks_repo_name": "dicai/descent.jl", "max_forks_repo_head_hexsha": "f684b69f6c8dadc86402fc465455b51c0484cedf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1714285714, "max_line_length": 105, "alphanum_fraction": 0.5447483958, "num_tokens": 1886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7892771636895006}}
{"text": "# ---\n# title: 453. Minimum Moves to Equal Array Elements\n# id: problem453\n# author: Indigo\n# date: 2021-02-02\n# difficulty: Easy\n# categories: Math\n# link: <https://leetcode.com/problems/minimum-moves-to-equal-array-elements/description/>\n# hidden: true\n# ---\n# \n# Given a **non-empty** integer array of size _n_ , find the minimum number of\n# moves required to make all array elements equal, where a move is incrementing\n# _n_ \\- 1 elements by 1.\n# \n# **Example:**\n# \n#     \n#     \n#     Input:\n#     [1,2,3]\n#     \n#     Output:\n#     3\n#     \n#     Explanation:\n#     Only three moves are needed (remember each move increments two elements):\n#     \n#     [1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]\n#     \n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction min_moves_453(nums::Vector{Int})\n    sum(nums) - minimum(nums) * length(nums)\nend\n## @lc code=end\n", "meta": {"hexsha": "d93cdea69c8c4247a5385d220e966ee9b630a311", "size": 860, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/453.minimum-moves-to-equal-array-elements.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/453.minimum-moves-to-equal-array-elements.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/453.minimum-moves-to-equal-array-elements.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 21.5, "max_line_length": 90, "alphanum_fraction": 0.6093023256, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7892771622773586}}
{"text": "\nusing PyPlot, PyCall\nusing Distributions\nimport StatsFuns.logsumexp\nPyDict(matplotlib[\"rcParams\"])[\"mathtext.fontset\"] = \"cm\"\nPyDict(matplotlib[\"rcParams\"])[\"mathtext.rm\"] = \"serif\"\nPyDict(matplotlib[\"rcParams\"])[\"lines.linewidth\"] = 1.5\nPyDict(matplotlib[\"rcParams\"])[\"font.family\"] = \"TakaoPGothic\"\n\nfunction expt(a, b, sigma, Y, X, N_s)\n    S = rand(Gamma(a, 1.0/b), N_s)\n    C = mean([exp(sum(logpdf.(Normal(s, sigma), Y))) for s in S])\n    curve = [exp(sum(logpdf.(Normal(mu, sigma), Y))) * pdf(Gamma(a, 1.0/b), mu) for mu in X]\n    m = mean([s*exp(sum(logpdf.(Normal(s, sigma), Y)))/C for s in S])\n    v = mean([(s-m)^2 * exp(sum(logpdf.(Normal(s, sigma), Y)))/C for s in S])\n    return curve/C, m, v\nend\n\nX = linspace(-5, 10, 1000)\n\na = 2.0\nb = 2.0\nmu = 1.0\nsigma=1.0\n\n# data\nN = 10\nY = rand(Normal(mu, sigma), N)\n\n# calc posterior\nN_s = 100000\nposterior, m, v = expt(a, b, sigma, Y, X, N_s)\n\na_h = m^2 / v\nb_h = m / v\n\nfigure()\nplot(X, pdf(Normal(mu,sigma), X))\nplot(X, pdf(Gamma(a,1.0/b), X))\nplot(X, posterior)\nplot(X, pdf(Gamma(a_h,1.0/b_h), X))\nplot(Y, 0.02*ones(N), \"o\")\nlegend([\"generator\", \"prior\", \"posterior\", \"approx\", \"samples\"])\n#legend([\"データ生成分布\", \"事前分布\", \"事後分布\", \"近似分布\", \"データ\"], fontsize=12)\nxlim([-3, 6])\nylim([0, 1.8])\n\n\n", "meta": {"hexsha": "abf19ae19596da2539fdf298b182ac380d049745", "size": 1246, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/demo_nonconjugate.jl", "max_stars_repo_name": "triwave33/BayesBook", "max_stars_repo_head_hexsha": "86967e67381b01181ae3b3ad28d46011140dcc5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 158, "max_stars_repo_stars_event_min_datetime": "2017-10-19T13:33:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:59:21.000Z", "max_issues_repo_path": "src/demo_nonconjugate.jl", "max_issues_repo_name": "triwave33/BayesBook", "max_issues_repo_head_hexsha": "86967e67381b01181ae3b3ad28d46011140dcc5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2018-01-29T08:36:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-01T14:32:34.000Z", "max_forks_repo_path": "src/demo_nonconjugate.jl", "max_forks_repo_name": "triwave33/BayesBook", "max_forks_repo_head_hexsha": "86967e67381b01181ae3b3ad28d46011140dcc5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2017-10-20T00:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T20:34:22.000Z", "avg_line_length": 25.4285714286, "max_line_length": 92, "alphanum_fraction": 0.6107544141, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7892771589778369}}
{"text": "using Plots\n# plots the contours of the OLS objective function,\n# with the true and estimated coefficients\n# generate data\nn = 20\nx = [ones(n) randn(n)]\nbeta = randn(2)\ny = x*beta+randn(n)\n# ols estimate and objective function\nbetahat = x\\y\ns = (a,b)-> (1/n)*sum((y - x*[a,b]).^2)\n# plot the contours and the points\ncloseall()\nb1 = range(-4.0,stop=4.0,length=100) \nb2 = range(-4.0,stop=4.0,length=100)\np = contour(b1,b2,(b1,b2)->s(b1,b2),fill=true, c=:viridis)\nscatter!([beta[1]],[beta[2]], markersize=10, label=\"true\")\nscatter!([betahat[1]],[betahat[2]], markersize=10, label=\"estimated\")\n", "meta": {"hexsha": "65167db1731b8e14f35356dafc43c51b646017e3", "size": 590, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/NonlinearOptimization/OLScontours.jl", "max_stars_repo_name": "nilshg/Econometrics", "max_stars_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "Examples/NonlinearOptimization/OLScontours.jl", "max_issues_repo_name": "nilshg/Econometrics", "max_issues_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "Examples/NonlinearOptimization/OLScontours.jl", "max_forks_repo_name": "nilshg/Econometrics", "max_forks_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 31.0526315789, "max_line_length": 69, "alphanum_fraction": 0.6694915254, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811621568289, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7892709915410309}}
{"text": "\"\"\"\n    variance(a)\n\nFind the variance from a set of data.\n\n# Arguments:\n- `a`: holds the set of data\n\n# Reference\n    - According to Ronald E. Walpole, `variance` is used to measure the variability of a set of data. -- Introduction to Statistics by Ronald E. Walpole\n\n# Contributors:\n- [Aru Bhardwaj](https://github.com/arubhardwaj)\n\"\"\"\nfunction variance(a)\n    avg = sum(a) / length(a)\n    x = sum((a .- avg).^2)\n    s_sq = x / (length(a) - 1)\n    return(s_sq)\nend\n", "meta": {"hexsha": "57527cad188e0a954f984e788826d4f448af5b68", "size": 467, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/statistics/variance.jl", "max_stars_repo_name": "KohRongSoon/Julia", "max_stars_repo_head_hexsha": "e0276ab9224e191452f7932343f8b24ea8625eea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 190, "max_stars_repo_stars_event_min_datetime": "2021-06-06T10:00:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:00:33.000Z", "max_issues_repo_path": "src/statistics/variance.jl", "max_issues_repo_name": "KohRongSoon/Julia", "max_issues_repo_head_hexsha": "e0276ab9224e191452f7932343f8b24ea8625eea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 82, "max_issues_repo_issues_event_min_datetime": "2021-06-09T14:08:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:31:04.000Z", "max_forks_repo_path": "src/statistics/variance.jl", "max_forks_repo_name": "KohRongSoon/Julia", "max_forks_repo_head_hexsha": "e0276ab9224e191452f7932343f8b24ea8625eea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 70, "max_forks_repo_forks_event_min_datetime": "2021-06-06T15:14:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T09:19:17.000Z", "avg_line_length": 22.2380952381, "max_line_length": 152, "alphanum_fraction": 0.6466809422, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7892634370731901}}
{"text": "using JuliaWeBWorK\nusing SymPy\n\nqs = JuliaWeBWorK.QUESTIONS()\n\n## --------------------------------------------------\n\nmeta=(Project=\"Some sample calculus questions\",\n     Question=\"3\"\n      )\n\nintro = jmt\"\"\"\n\n[Details for students](https://webwork.maa.org/wiki/Student_Information)\n\n----\n\n# Sample test\n\nJustify answers and show all work for full credit. No graphing calculators. No internet.\n\n(Wait, that is **joke**).\n\n\"\"\"\n\n## --------------------------------------------------\n\nnumericq(jmt\"\"\"\n# Problem 1\nLet\n\n```math\nf(x) = \\frac{4}{5} x^5 + 2x^4 - 20x^3 +  9\n```\n\n(a) Find the critical points of  ``f(x)``\n\"\"\",\n         () -> begin\n         @syms x\n         ex = 4//5 * x^5 + 2x^4  -  20x^3 + 9\n         cps = solve(diff(ex,x))\n         List(cps) \n         end,\n         ()) |> qs\n\n\n## --------------------------------------------------\n\nnumericq(jmt\"\"\"\n(b) Specify all intervals where \\(f(x)\\) is *increasing*.\n\"\"\",\n         () -> begin\n         @syms x\n         ex = 4//5 * x^5 + 2x^4  -  20x^3 + 9\n         dex = diff(ex,x)\n         cps = sort(solve(dex))\n         delta = minimum(diff(cps))/2\n         l = -Inf\n         Ints = []\n         for  r in cps\n         if dex(r-delta) > 0\n         push!(Ints, Interval(l,r))\n         end\n         l = r\n         end\n         if dex(l+delta) > 0\n         push!(Ints, Interval(l, Inf))\n         end\n         List(Ints)\n         end,\n         ()) |> qs\n\n\n## --------------------------------------------------\n\nnumericq(jmt\"\"\"\n\n(c) For which critical points does the first derivative change sign from positive to negative?\"\n\n\"\"\",\n         () -> begin\n         @syms x\n         ex = 4//5 * x^5 + 2x^4  -  20x^3 + 9\n         dex = diff(ex,x)\n         cps = sort(solve(dex))\n         delta = minimum(diff(cps))/2\n         xs =  []\n         for r in cps\n         if (dex(r-delta) > 0) && (dex(r+delta) < 0)\n         push!(xs, r)\n         end\n         end\n         List(xs)\n         end,\n         ()) |> qs\n\n## --------------------------------------------------\n\nr  = randomizer(8:15) |> qs\nfunction q4_helper(a)\n    @vars x\n    ex = x^4 - 12x^2 + a\n    dp = diff(ex,x)\n    dpp = diff(ex,(x,2))\n    cps =  (sort∘solve)(dp)\n    ips =  (sort∘solve)(dpp)\n    (ex, cps, ips)\nend\n\nnumericq(jmt\"\"\"\n\n# Problem 2\nLet \n\n```math\nf(x) = x^4 -  12x^2  + {{:a1}}\n```\n\n(a) Find the critical points  of ``f(x)``.\n\"\"\",\n         (a) -> begin\n         ex,cps,ips = q4_helper(a)\n         List(cps)\n         end,\n         r) |> qs\n\nnumericq(jmt\"\"\"\n\n(b) Find  the inflection points of  ``f(x)``.\n\n\"\"\",\n         (a) -> begin\n         ex,cps,ips = q4_helper(a)\n         List(ips)\n         end,\n         r) |> qs\n         \nnumericq(jmt\"\"\"\n\n(c) Find the intervals where  ``f(x)``  is concave  down.\n\n\"\"\",\n         (a) -> begin\n         ex,cps,ips = q4_helper(a)\n         x = free_symbols(ex)[1]\n         dex = diff(ex,x)\n         ddex = diff(ex,x,x)\n         \n         δ = minimum(diff(ips))/2\n         Ints =  []\n         l =  -Inf\n         for r in ips\n         if  ddex(r-δ) <  0\n         push!(Ints, Interval(l,r))\n         end\n         l = r\n         end\n         if ddex(l + δ) < 0\n         push!(Ints,  Interval(l,Inf))\n         end\n         List(Ints)\n         end,\n         r) |> qs\n\nnumericq(jmt\"\"\"\n\n(d) Which critical points have a negative second derivative?\n\n\"\"\",\n         (a)  -> begin\n         ex,cps,ips = q4_helper(a)\n         x = free_symbols(ex)[1]\n         xs =  []\n         for c  in  cps\n         diff(ex,(x,2))(c) < 0 && push!(xs,  c)\n         end\n         List(xs)\n         end,\n         r) |> qs\n\n                           \n                           \n##\n## --------------------------------------------------\n##\np  =  Page(intro, qs; context=\"Interval\", meta...)  #  Interval here  is needed\n                \n\n", "meta": {"hexsha": "01afcf06d588411410fbcabf8299592d9b02196b", "size": 3755, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/symbolic_calculus.jl", "max_stars_repo_name": "mth229/JuliaWeBWorK.jl", "max_stars_repo_head_hexsha": "10a04eeaa45c29158e8a6e6613a1b4d6472c8913", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-25T01:43:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-25T01:43:39.000Z", "max_issues_repo_path": "examples/symbolic_calculus.jl", "max_issues_repo_name": "mth229/JuliaWeBWorK.jl", "max_issues_repo_head_hexsha": "10a04eeaa45c29158e8a6e6613a1b4d6472c8913", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/symbolic_calculus.jl", "max_forks_repo_name": "mth229/JuliaWeBWorK.jl", "max_forks_repo_head_hexsha": "10a04eeaa45c29158e8a6e6613a1b4d6472c8913", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8677248677, "max_line_length": 95, "alphanum_fraction": 0.4042609854, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777987970316, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.789239093944865}}
{"text": "using NLopt\n\nfunction myfunc(x::Vector, grad::Vector)\n    if length(grad) > 0\n        grad[1] = 0\n        grad[2] = 0.5/sqrt(x[2])\n    end\n    return sqrt(x[2])\nend\n\nfunction myconstraint(x::Vector, grad::Vector, a, b)\n    if length(grad) > 0\n        grad[1] = 3a * (a*x[1] + b)^2\n        grad[2] = -1\n    end\n    (a*x[1] + b)^3 - x[2]\nend\n\nopt = Opt(:LD_SLSQP, 2)\nopt.lower_bounds = [-Inf, 0.]\nopt.xtol_rel = 1e-4\n\nopt.min_objective = myfunc\nequality_constraint!(opt, (x,g) -> sum(x)==3, 1e-8)\ninequality_constraint!(opt, (x,g) -> myconstraint(x,g,-1,1), 1e-8)\n\n(minf,minx,ret) = optimize(opt, [1.234, 5.678])\nnumevals = opt.numevals # the number of function evaluations\nprintln(\"got $minf at $minx after $numevals iterations (returned $ret)\")", "meta": {"hexsha": "f4b0b61c01b474906f3b170ea264e81d8882e6bc", "size": 744, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".stack/nlopt.jl", "max_stars_repo_name": "stevengogogo/PotentialMap.jl", "max_stars_repo_head_hexsha": "bb8fe3df8bf20c9ee30e17dd61640a3546befd83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-20T06:05:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-20T06:05:07.000Z", "max_issues_repo_path": ".stack/nlopt.jl", "max_issues_repo_name": "stevengogogo/PotentialMap.jl", "max_issues_repo_head_hexsha": "bb8fe3df8bf20c9ee30e17dd61640a3546befd83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-01-04T00:26:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T06:41:56.000Z", "max_forks_repo_path": ".stack/nlopt.jl", "max_forks_repo_name": "stevengogogo/PotentialMap.jl", "max_forks_repo_head_hexsha": "bb8fe3df8bf20c9ee30e17dd61640a3546befd83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-02T03:43:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-02T03:43:40.000Z", "avg_line_length": 25.6551724138, "max_line_length": 72, "alphanum_fraction": 0.6102150538, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474246069458, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.789218287139672}}
{"text": "using ForwardDiff\nusing LinearAlgebra\n\nfunction marquardt(f, x₀; ε=1e-6, maxiter=1000, λ=10.0^4, α=2)\n    x = x₀\n    fx = f(x)\n    for i in 1:maxiter\n        g = ForwardDiff.gradient(f, x)\n        norm(g) ≤ ε && return (x=x, converged=true, iters=i)\n        x′ = x .- (ForwardDiff.hessian(f, x) + λ*I) \\ g\n        fx′ = f(x′)\n        if fx′ < fx\n            λ *= 0.5\n            fx = fx′\n            x = x′\n        else\n            λ *= 2.0\n        end\n    end\n    (x=x, converged=false, iters=maxiter)\nend\n", "meta": {"hexsha": "6e5535dff60735e6a337b32391c6604b61828b60", "size": 507, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter04/08. Writing a simple optimization routine/marquardt.jl", "max_stars_repo_name": "lytemar/Julia-1.0-Programming-Cookbook", "max_stars_repo_head_hexsha": "5d42b72b6bd2b53a22dcf78364d7603fa3735a2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2018-11-21T22:47:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T21:07:01.000Z", "max_issues_repo_path": "Chapter04/08. Writing a simple optimization routine/marquardt.jl", "max_issues_repo_name": "lytemar/Julia-1.0-Programming-Cookbook", "max_issues_repo_head_hexsha": "5d42b72b6bd2b53a22dcf78364d7603fa3735a2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-08T23:29:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-09T05:09:35.000Z", "max_forks_repo_path": "Chapter04/08. Writing a simple optimization routine/marquardt.jl", "max_forks_repo_name": "lytemar/Julia-1.0-Programming-Cookbook", "max_forks_repo_head_hexsha": "5d42b72b6bd2b53a22dcf78364d7603fa3735a2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2019-03-13T03:04:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-08T15:00:01.000Z", "avg_line_length": 23.0454545455, "max_line_length": 62, "alphanum_fraction": 0.4733727811, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474194456935, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7892182869486355}}
{"text": "#References: Sandoval, Steven, and Phillip L. De Leon. \"The Instantaneous Spectrum: A General Framework for Time-Frequency Analysis.\" IEEE Transactions on Signal Processing 66.21 (2018): 5679-5693.\n\n\"\"\"\n    S = fourierSeries(T, aₖ, kInds)\n\nCreate a 'AMFMmodel' by specifiying components drawn from a Fourier Series\n  where 'T' is the fundemental period, 'aₖ' is a function specifying the Fourier\n  series coefficients, and 'kInds' is a vector containing values of `k` to\n  consider in the partial sum.\n\n# Examples\n```@example\nusing ISA, Plots\nT = 1.0\naₖ(k) = 1.0\nkInds = collect(-25:25)\nz = fourierSeries(T, aₖ, kInds)\nplot(z; timeaxis=-1.0:0.001:1.0)\n```\n\"\"\"\nfunction fourierSeries(T::Real, aₖ::Function, kInds::Array{Int,1}=Vector(-100:100))\n  function getIA(k)\n    function a(t::Real)\n      ia = abs(aₖ(k))\n      return ia::Real\n    end\n    return a\n  end\n  function getIF(k)\n      function ω(t::Real)\n        omega = 2*π*k/T\n        return omega::Real\n      end\n    return ω\n  end\n  function getPh(k)\n    ph = angle(aₖ(k))\n    return ph\n  end\n  S = [ AMFMcomp( getIA(k), getIF(k), getPh(k) ) for k ∈ kInds]\n  return compSet(S)\nend\n\n# CONSTRUCTIONS\nfourierSeries(T::Real, aₖ::Function, kInds::StepRangeLen) = fourierSeries(T, aₖ, collect(kInds))\nfourierSeries(T::Real, aₖ::Function, kInds::UnitRange) = fourierSeries(T, aₖ, collect(kInds))\n", "meta": {"hexsha": "857f73f45ef9116e3b324569d386f14f8dbb120f", "size": 1343, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/fourierSeries.jl", "max_stars_repo_name": "NMSU-ISA/ISA.jl", "max_stars_repo_head_hexsha": "7e503b50a0fdf5fe81d697120c84a495bceb0120", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/models/fourierSeries.jl", "max_issues_repo_name": "NMSU-ISA/ISA.jl", "max_issues_repo_head_hexsha": "7e503b50a0fdf5fe81d697120c84a495bceb0120", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/fourierSeries.jl", "max_forks_repo_name": "NMSU-ISA/ISA.jl", "max_forks_repo_head_hexsha": "7e503b50a0fdf5fe81d697120c84a495bceb0120", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5744680851, "max_line_length": 197, "alphanum_fraction": 0.6753536858, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.789169534289518}}
{"text": "\"\"\"\n`SqExponentialKernel([ρ=1.0])`\n\nThe squared exponential kernel is an isotropic Mercer kernel given by the formula:\n```\n    κ(x,y) = exp(-ρ²‖x-y‖²)\n```\nSee also [`ExponentialKernel`](@ref) for a\nrelated form of the kernel or [`GammaExponentialKernel`](@ref) for a generalization.\n\"\"\"\nstruct SqExponentialKernel{Tr} <: Kernel{Tr}\n    transform::Tr\nend\n\n@inline kappa(κ::SqExponentialKernel, d²::Real) = exp(-d²)\n@inline iskroncompatible(::SqExponentialKernel) = true\n\nmetric(::SqExponentialKernel) = SqEuclidean()\n\n## Aliases ##\nconst RBFKernel = SqExponentialKernel\nconst GaussianKernel = SqExponentialKernel\n\n\"\"\"\n`ExponentialKernel([ρ=1.0])`\nThe exponential kernel is an isotropic Mercer kernel given by the formula:\n```\n    κ(x,y) = exp(-ρ‖x-y‖)\n```\n\"\"\"\nstruct ExponentialKernel{Tr} <: Kernel{Tr}\n    transform::Tr\nend\n\n@inline kappa(κ::ExponentialKernel, d::Real) = exp(-d)\n@inline iskroncompatible(::ExponentialKernel) = true\nmetric(::ExponentialKernel) = Euclidean()\n\n## Alias ##\nconst LaplacianKernel = ExponentialKernel\n\n\"\"\"\n`GammaExponentialKernel([ρ=1.0, [γ=2.0]])`\nThe γ-exponential kernel is an isotropic Mercer kernel given by the formula:\n```\n    κ(x,y) = exp(-ρ^(2γ)‖x-y‖^(2γ))\n```\n\"\"\"\nstruct GammaExponentialKernel{Tr, Tγ<:Real} <: Kernel{Tr}\n    transform::Tr\n    γ::Tγ\n    function GammaExponentialKernel{Tr,Tγ}(t::Tr, γ::Tγ) where {Tr<:Transform,Tγ<:Real}\n        @check_args(GammaExponentialKernel, γ, γ >= zero(Tγ), \"γ > 0\")\n        return new{Tr, Tγ}(t, γ)\n    end\nend\n\nparams(k::GammaExponentialKernel) = (params(transform),γ)\nopt_params(k::GammaExponentialKernel) = (opt_params(transform),γ)\n\nfunction GammaExponentialKernel(ρ::Real=1.0, γ::Real=2.0)\n    GammaExponentialKernel(ScaleTransform(ρ), γ)\nend\n\nfunction GammaExponentialKernel(ρ::AbstractVector{<:Real}, γ::Real=2.0)\n    GammaExponentialKernel(ARDTransform(ρ), γ)\nend\n\nfunction GammaExponentialKernel(t::Tr, γ::Tγ=2.0) where {Tr<:Transform, Tγ<:Real}\n    GammaExponentialKernel{Tr, Tγ}(t, γ)\nend\n\n@inline kappa(κ::GammaExponentialKernel, d²::Real) = exp(-d²^κ.γ)\n@inline iskroncompatible(::GammaExponentialKernel) = true\nmetric(::GammaExponentialKernel) = SqEuclidean()\n", "meta": {"hexsha": "0302128c1c4c169255e649e1df0720578748d654", "size": 2156, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/exponential.jl", "max_stars_repo_name": "IsakFalk/KernelFunctions.jl", "max_stars_repo_head_hexsha": "d629d2f8d26e31fa4a07d417d115416292aa7c62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/exponential.jl", "max_issues_repo_name": "IsakFalk/KernelFunctions.jl", "max_issues_repo_head_hexsha": "d629d2f8d26e31fa4a07d417d115416292aa7c62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/exponential.jl", "max_forks_repo_name": "IsakFalk/KernelFunctions.jl", "max_forks_repo_head_hexsha": "d629d2f8d26e31fa4a07d417d115416292aa7c62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3684210526, "max_line_length": 87, "alphanum_fraction": 0.711038961, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7891670550388018}}
{"text": "\"\"\"\n    integrate_gauss_legendre(f, a::Arb, b::Arb)\n\nCompute an enclosure of the integral of `f` on the interval `[a, b]`\nusing a Gauss-Legendre quadrature of order 2.\n\nThe approximation is given by\n```\n(b - a) / 2 * (f(x₁) + f(x₂))\n```\nwhere\n```\nx₁ = (b - a) / 2 * sqrt(3) / 3 + (b + a) / 2\nx₂ = -(b - a) / 2 * sqrt(3) / 3 + (b + a) / 2\n```\nare quadrature nodes. The remainder term is enclosed by\n```\n(b - a)^5 / 4320 * d4f\n```\nwhere `d4f` is an enclosure of the fourth derivative of `f` on the\ninterval `[a, b]`.\n\nIf it happens to be that `d4f` is not finite, for example because `f`\nis not differentiable on the interval, it instead computes a naive\nenclosure of the integral using the enclosure of `f` evaluated on the\ninterval `[a, b]`.\n\nThe function `f` should support evaluation on both `Arb` and\n`ArbSeries` and should return an enclosure of the result in both\ncases. For `ArbSeries` it is enough that it supports evaluation up to\ndegree 4 and only the zeroth and fourth order term are ever used.\n\n- **TODO:** Optimize for performance\n- **TODO:** Add option for computing integral of absolute value?\n- **TODO:** Allow giving an separate function for computing derivative?\n\"\"\"\nfunction integrate_gauss_legendre(f, a::Arb, b::Arb)\n    bma = b - a\n\n    # x_series = ArbSeries((union(a, b), 1), degree = 4)\n    x_series = ArbSeries(degree = 4, prec = precision(bma))\n    # We need to do it in this order so that the degree of the\n    # polynomial is correct when we set the constant coefficient.\n    x_series[1] = 1\n    Arblib.union!(Arblib.ref(x_series, 0), a, b)\n\n    f_series = f(x_series)\n\n    # If the fourth derivative of f is not finite compute an enclosure\n    # of the integral using the enclosure of f on the interval [a, b].\n    isfinite(Arblib.ref(f_series, 4)) ||\n        return Arblib.mul!(bma, bma, Arblib.ref(f_series, 0))\n\n    # remainder = (b - a)^5 / 4320 * f_series[4] * factorial(4)\n    remainder = Arblib.pow!(zero(bma), bma, UInt(5))\n    Arblib.mul!(remainder, remainder, Arblib.ref(f_series, 4))\n    Arblib.div!(remainder, remainder, 180)\n\n    # v = (b - a) / 2 * sqrt(Arb(3)) / 3\n    v = Arblib.sqrt!(zero(bma), UInt(3))\n    Arblib.mul!(v, v, bma)\n    Arblib.div!(v, v, 6)\n\n    # Set x₁ = (b + a) / 2 to begin with\n    x₁ = b + a\n    Arblib.mul_2exp!(x₁, x₁, -1)\n\n    # x₂ = (b + a) / 2 - v = x₁ - v\n    x₂ = Arblib.sub!(zero(bma), x₁, v)\n\n    # x₁ = (b + a) / 2 - v = x₁ - v\n    Arblib.add!(x₁, x₁, v)\n\n    # approximation = (b - a) / 2 * (f(x₁) + f(x₂))\n    approximation = f(x₁)\n    Arblib.add!(approximation, approximation, f(x₂))\n    Arblib.mul!(approximation, approximation, bma)\n    Arblib.mul_2exp!(approximation, approximation, -1)\n\n    # Return approximation + remainder\n    return Arblib.add!(approximation, approximation, remainder)\nend\n\n\"\"\"\n    integrate(f, a::Arb, b::Arb; atol, rtol, depth_start, maxevals, depth, verbose)\n\nCompute an enclosure of the integral of `f on the interval `[a, b]`.\n\nIt uses a Guass-Legendre quadrature of order 2 through\n[`integrate_gauss_legendre`](@ref) together with bisection of the\ninterval. On each subinterval the integral is computed using\n[`integrate_gauss_legendre`](@ref) and it checks if the result\nsatisfies the required tolerance, if it doesn't the interval is\nbisected. For more details about the integration method see\n[`integrate_gauss_legendre`](@ref).\n\nNotice that the tolerance is checked on each **subinterval** and not\non the interval as a whole. This means that even if it finishes before\nreaching the maximum depth or the maximum number of evaluations the\nresult as a whole might not satisfy the given tolerance.\n\nThe argument `depth_start` bisect the interval using\n[`bisect_interval_recursive`](@ref) before starting to compute the\nintegral. This can be useful if it is known beforehand that a certain\nnumber of bisections will be necessary before the enclosures get good\nenough. It defaults to `0` which corresponds to not bisecting the\ninterval at all before starting.\n\nThe arguments `maxevals` and `depth` can be used to limit the number\nof function evaluations and the number of bisections of the interval\nrespectively.\n\nIf `verbose = true` then output information about the process.\n\"\"\"\nfunction integrate(\n    f,\n    a::Arb,\n    b::Arb;\n    atol = 0,\n    rtol = sqrt(eps(one(a))),\n    depth_start::Integer = 0,\n    maxevals::Integer = 1000,\n    depth::Integer = 20,\n    verbose = false,\n)\n    isfinite(a) && isfinite(b) || return Arblib.indeterminate!(zero(a))\n\n    intervals = bisect_interval_recursive(a, b, depth_start)\n\n    integral = zero(a)\n\n    verbose && @info \"iteration: $(lpad(0, 2)), \" *\n          \"starting intervals: $(lpad(length(intervals), 4))\"\n\n    iterations = 0\n    evals = 0\n    while !isempty(intervals)\n        iterations += 1\n        evals += length(intervals)\n\n        # If we have reached the maximum number of iterations or\n        # evaluations then we don't split any further.\n        finished = iterations >= depth || evals >= maxevals\n\n        # The number of intervals that had to be split further. The\n        # only reason we store this in a separate variable is to\n        # correctly count the number during the last iteration when\n        # finished = true.\n        remaining_intervals = 0\n\n        next_intervals = empty(intervals)\n\n        for (a, b) in intervals\n            integral_part = integrate_gauss_legendre(f, a, b)\n\n            if check_tolerance(integral_part; atol, rtol)\n                integral += integral_part\n            elseif finished\n                remaining_intervals += 1\n                integral += integral_part\n            else\n                remaining_intervals += 1\n                push!(next_intervals, bisect_interval(a, b)...)\n            end\n        end\n\n        intervals = next_intervals\n\n        verbose && @info \"iteration: $(lpad(iterations, 2)), \" *\n              \"remaining intervals: $(lpad(remaining_intervals, 3)), \" *\n              \"current integral: $integral\"\n    end\n\n    return integral\nend\n", "meta": {"hexsha": "27edfaa70e0df007279d1bb6f49d0829e944d8fa", "size": 5983, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/integrate.jl", "max_stars_repo_name": "Joel-Dahne/ArbExtras.jl", "max_stars_repo_head_hexsha": "efe098023f35519be07504fe08c71bae433de36b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-05T15:31:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T15:31:45.000Z", "max_issues_repo_path": "src/integrate.jl", "max_issues_repo_name": "Joel-Dahne/ArbExtras.jl", "max_issues_repo_head_hexsha": "efe098023f35519be07504fe08c71bae433de36b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-03-05T15:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T16:14:47.000Z", "max_forks_repo_path": "src/integrate.jl", "max_forks_repo_name": "Joel-Dahne/ArbExtras.jl", "max_forks_repo_head_hexsha": "efe098023f35519be07504fe08c71bae433de36b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9943181818, "max_line_length": 83, "alphanum_fraction": 0.6575296674, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7891670532978399}}
{"text": "export lanczosTridiag\n\n\"\"\"\nT,V = lanczosTridiag(A,b,k;tol,doReorth)\n\nLanczos method for getting a factorization of\n\n   A = Vk Tk Vk'\n\nwhere A is a real symmetric n by n matrix, Tk is a tridiagonal k by k matrix and the columns of \nthe n by k matrix Vk are orthogonal.\n\nImplementation follows:\n\nPaige, C. C. (1972). \nComputational variants of the Lanczos method for the eigenproblem. \nIMA Journal of Applied Mathematics. \n\nRequired input:\n\n  A       - function computing A*x, e.g., x -> A*x\n  b       - right hand side vector\n  k       - dimension of Krylov subspace\n\nOptional input:\n \n  tol      - stopping tolerance\n  doReorth - (default=false) set to true to perform full reorthogonalization\n\nOutput:\n\n Tk    - sparse tridiagonal matrix\n Vk    - basis vectors\n\"\"\"\nfunction lanczosTridiag{T1,T2}(A::SparseMatrixCSC{T1,Int},b::Array{T2,1},k; kwargs...) \n\tx = zeros(promote_type(T1,T2),size(A,2)) # pre-allocate\n\treturn lanczosTridiag(v -> At_mul_B!(1.0,A,v,0.0,x),b,k;kwargs...) # multiply with transpose of A for efficiency\nend\n\n\nlanczosTridiag(A,b,k;kwargs...) = lanczosTridiag(x -> A*x,b,k;kwargs...)\n\n\nfunction lanczosTridiag(A::Function,b::Vector,k::Int;tol=1e-5,doReorth::Bool=false)\n\nn   = length(b)\nx   = zeros(n)\n\n# pre-allocate space for tridiagonalization and basis\nbeta  = zeros(k)\nalpha = zeros(k)\nV     = zeros(n,k)\n\n\nbeta[1] = norm(b)\nV[:,1]  = copy(b)/beta[1]\nu       = A(V[:,1])\n\nj = 1 # brings j to scope of function\nfor j=1:k-1\n    alpha[j] = dot(V[:,j],u)\n    u        = u - alpha[j]*V[:,j]\n    if doReorth # full re-orthogonalization\n        for i=1:j\n            u -= V[:,i]*dot(V[:,i],u)\n        end\n    end\n    gamma     = norm(u)\n    V[:,j+1]  = u/gamma\n    beta[j+1] = gamma\n    if beta[j+1]<tol\n        break\n    end\n    u = A(V[:,j+1]) - beta[j+1]*V[:,j]\nend\n\nT = spdiagm((beta[2:j],alpha[1:j],beta[2:j]),-1:1,j,j)\nreturn T,V[:,1:j]\nend\n", "meta": {"hexsha": "f5c411e00c8ef4290248e292c95c282db04f5316", "size": 1865, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lanczosTridiag.jl", "max_stars_repo_name": "JuliaPackageMirrors/KrylovMethods.jl", "max_stars_repo_head_hexsha": "964bca6c9ab389b7c5bfa33f5a9c943dc54901b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lanczosTridiag.jl", "max_issues_repo_name": "JuliaPackageMirrors/KrylovMethods.jl", "max_issues_repo_head_hexsha": "964bca6c9ab389b7c5bfa33f5a9c943dc54901b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lanczosTridiag.jl", "max_forks_repo_name": "JuliaPackageMirrors/KrylovMethods.jl", "max_forks_repo_head_hexsha": "964bca6c9ab389b7c5bfa33f5a9c943dc54901b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3125, "max_line_length": 113, "alphanum_fraction": 0.6278820375, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250325, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.7891670498082176}}
{"text": "using ApproxBayes\nusing Distributions\nusing Random\n\nfunction getnormal(params, constants, targetdata)\n\n  simdata = rand(Normal(params...), 100)\n  ApproxBayes.ksdist(simdata, targetdata), 1\nend\n\nfunction getbinomial(params, constants, targetdata)\n\n  simdata = rand(Binomial(round(params[1]), params[2]), 100)\n  ApproxBayes.ksdist(simdata, targetdata), 1\nend\n\nfunction getpoisson(params, constants, targetdata)\n\n  simdata = rand(Poisson(params...), 100)\n  ApproxBayes.ksdist(simdata, targetdata), 1\nend\n\nfunction getuniformdist(params, constants, targetdata)\n\n  simdata = rand(Uniform(params...), 100)\n  ApproxBayes.ksdist(simdata, targetdata), 1\nend\n\n#generate sime synthetic data\nRandom.seed!(1)\ntargetdata = rand(Normal(2, 0.4), 100)\n\n#setup ABC alogrithm specifications for Rejection algorithm\nsetup = ABCRejection(getnormal,\n  2,\n  0.1,\n  Prior([Uniform(0, 20.0), Uniform(0, 2.0)]);\n  maxiterations = 10^6,\n  )\n# run ABC inference\n@time resrejection = runabc(setup, targetdata, parallel=true);\n#print summary of inference\nshow(resrejection)\n\n#do the same with ABC SMC algorithm\nsetup = ABCSMC(getnormal,\n  2,\n  0.1,\n  Prior([Uniform(0, 20.0), Uniform(0, 2.0)])\n  )\n@time ressmc = runabc(setup, targetdata, verbose=true, progress=false, parallel=true);\nshow(ressmc)\n\n\nsmcefficiency = ressmc.accratio/resrejection.accratio\nprintln()\nprintln(\"SMC algorithm is $(round(smcefficiency, 2)) times more efficient\")\n", "meta": {"hexsha": "ba7a719f4a977f60c0163eed84bbba9cf76312cd", "size": 1410, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/normaldist.jl", "max_stars_repo_name": "wilwxk/ApproxBayes.jl", "max_stars_repo_head_hexsha": "8ca364c66a9f94ccd09910a4f73232909d91c399", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 43, "max_stars_repo_stars_event_min_datetime": "2017-10-14T22:35:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T05:30:13.000Z", "max_issues_repo_path": "examples/normaldist.jl", "max_issues_repo_name": "wilwxk/ApproxBayes.jl", "max_issues_repo_head_hexsha": "8ca364c66a9f94ccd09910a4f73232909d91c399", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47, "max_issues_repo_issues_event_min_datetime": "2017-06-15T08:38:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-27T10:24:48.000Z", "max_forks_repo_path": "examples/normaldist.jl", "max_forks_repo_name": "wilwxk/ApproxBayes.jl", "max_forks_repo_head_hexsha": "8ca364c66a9f94ccd09910a4f73232909d91c399", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-07-28T09:49:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T14:39:00.000Z", "avg_line_length": 24.3103448276, "max_line_length": 86, "alphanum_fraction": 0.7432624113, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.924141826246517, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7891364909679789}}
{"text": "\r\ninclude(\"../../../../std/util/src/util_module.jl\") # for binary search\r\n# include(\"../../datastructs/src/datastructs_module.jl\") # for stack\r\n\r\nmodule numint\r\nusing ..util\r\n# using ..datastructs\r\n\r\nstruct Interval\r\n    x_lo::Float64\r\n    x_hi::Float64\r\n    function Interval(x_lo, x_hi)\r\n        (x_lo, x_hi) = (x_lo < x_hi) ? (x_lo, x_hi) : (x_hi, x_lo)\r\n        return new(x_lo, x_hi)\r\n    end\r\nend\r\nfunction range(interval::Interval)\r\n    return interval.x_hi - interval.x_lo\r\nend\r\n\r\n\r\n\r\nfunction trapezoidal(fcn, interval::Interval, N::Int)\r\n\r\n    int_range = range(interval)\r\n    dx = int_range / N\r\n    I  = 0.0\r\n    x1 = interval.x_lo\r\n    f1 = fcn(x1)\r\n    @inbounds for kk = 1:N\r\n        x2 = x1 + dx\r\n        f2 = fcn(x2)\r\n        I += 0.5 * (f1 + f2) * dx\r\n        x1 = x2\r\n        f1 = f2\r\n    end\r\n    return I\r\nend\r\n\r\nfunction trapezoidal(fcn, interval::Interval, xs::Vector)\r\n    I  = 0.0\r\n    x1 = interval.x_lo\r\n    f1 = fcn(x1)\r\n    @inbounds for kk = 2:length(xs)\r\n        x2 = xs[kk]\r\n        dx = x2 - x1\r\n        f2 = fcn(x2)\r\n        I += 0.5 * (f1 + f2) * dx\r\n        x1 = x2\r\n        f1 = f2\r\n    end\r\n    return I\r\nend\r\n\r\n\r\n\r\nstruct RombergOptions\r\n    N::Int\r\n    abs_tol::Float64\r\n    rel_tol::Float64\r\nend\r\nfunction RombergOptions()\r\n    return RombergOptions(128, 1e-8, 1e-8)\r\nend\r\nfunction RombergOptions(;N = 128, abs_tol = 1e-8, rel_tol = 1e-8)\r\n    return RombergOptions(N, abs_tol, rel_tol)\r\nend\r\n\r\n\r\n@enum StoppingCrit begin\r\n    max_iter_reached\r\n    rel_tol\r\n    abs_tol\r\n    unknown\r\nend\r\n\r\nstruct RombergResult\r\n    integral::Float64\r\n    n_fcn_eval::Int\r\n    stopping_crit::StoppingCrit\r\n    I::Vector{Float64}\r\nend\r\n\r\n\r\nfunction romberg(\r\n    fcn,\r\n    interval::Interval,\r\n    options::RombergOptions = RombergOptions()\r\n    )\r\n\r\n    # allocations\r\n    int_range   = range(interval)\r\n    Nmax        = ceil(Int, log2(options.N)) + 1\r\n    I           = zeros(Nmax)\r\n\r\n    # N == 2\r\n    # stat\r\n    n_fcn_eval    = 2\r\n    stopping_crit = unknown::StoppingCrit\r\n\r\n    idxi    = 1\r\n    fi_a    = fcn(interval.x_lo)\r\n    fi_b    = fcn(interval.x_hi)\r\n    I[idxi] = 0.5 * (fi_a + fi_b) * int_range\r\n    \r\n    # R = datastructs.Stack{Float64}()\r\n    R    = zeros(Nmax)\r\n    R[1] = I[1]\r\n\r\n    # auxilary arrays\r\n    r   = zeros(Nmax)\r\n    tmp = zeros(Nmax)\r\n\r\n    # main loop\r\n    @inbounds for N = 2:Nmax\r\n        \r\n        # fill up the trapezoidal table first column\r\n        hn = int_range / 2^(N-1)\r\n\r\n        # evaluate the function or steal it from the previous iteration\r\n        I_partial = 0.0\r\n        @inbounds for kk = 1:2^(N-2)\r\n            x = interval.x_lo + hn * (2 * kk - 1)\r\n            n_fcn_eval += 1\r\n            I_partial  += fcn(x)\r\n        end\r\n        R[N] = 0.5 * R[N-1] + hn * I_partial\r\n\r\n        copyto!(r, R)\r\n        @inbounds for jj = 2:N\r\n            @inbounds for ii = jj:N\r\n                R_n_m1  = r[ii]\r\n                R_n1_m1 = r[ii-1]\r\n                tmp[ii] = R_n_m1 + (R_n_m1 - R_n1_m1) / (4^(jj-1)-1)\r\n            end\r\n            # swap the arrays such that the previous array is always in r\r\n            r, tmp = tmp, r\r\n        end\r\n\r\n\r\n        idxi    += 1\r\n        I[idxi] = r[N]\r\n        if idxi >= 2\r\n            dI = abs(I[idxi-1] - I[idxi]) \r\n            if dI <= options.abs_tol\r\n                stopping_crit = abs_tol::StoppingCrit\r\n                break\r\n            end\r\n            if  dI / abs(I[idxi]) <= options.rel_tol\r\n                stopping_crit = rel_tol::StoppingCrit\r\n                break\r\n            end\r\n        end\r\n\r\n    end\r\n\r\n    if idxi == Nmax\r\n        stopping_crit = max_iter_reached::StoppingCrit\r\n    end\r\n\r\n    stat = RombergResult(I[idxi], n_fcn_eval, stopping_crit, I)\r\n    return stat\r\nend\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nstruct GaussKronrodOptions\r\n    abs_tol::Float64\r\n    rel_tol::Float64\r\n    min_interval::Float64\r\nend\r\nfunction GaussKronrodOptions(;\r\n    abs_tol = 1e-8,\r\n    rel_tol = 1e-8,\r\n    min_interval = 1e-10\r\n    )\r\n    return GaussKronrodOptions(abs_tol, rel_tol, min_interval)\r\nend\r\n\r\nstruct GaussKronrodResult\r\n    integral::Float64\r\n    n_fcn_eval::Int\r\nend\r\n\r\n\r\nfunction gauss_kronrod(\r\n    fcn,\r\n    interval::Interval,\r\n    options::GaussKronrodOptions = GaussKronrodOptions()\r\n    )\r\n\r\n\r\n    (gi_idx,\r\n    kronrod_weights,\r\n    kronrod_nodes,\r\n    gauss_weights) = __gk_nodes_weights()\r\n\r\n    n_fcn_eval = 0\r\n    x_lo = interval.x_lo\r\n    x_hi = interval.x_hi\r\n\r\n    (K15, n_fcn_eval) = __rec_gk(\r\n        fcn,\r\n        x_lo,\r\n        x_hi,\r\n        options,\r\n        gi_idx,\r\n        kronrod_weights,\r\n        kronrod_nodes,\r\n        gauss_weights,\r\n        n_fcn_eval)\r\n\r\n    stat = GaussKronrodResult(K15, n_fcn_eval)\r\n    return stat\r\nend\r\n\r\nfunction __rec_gk(\r\n    fcn,\r\n    x_lo,\r\n    x_hi,\r\n    options,\r\n    gi_idx,\r\n    kronrod_weights,\r\n    kronrod_nodes,\r\n    gauss_weights,\r\n    n_fcn_eval)\r\n\r\n    # constants\r\n    Nk = 15\r\n    Ng = 7\r\n\r\n\r\n    int_range = x_hi - x_lo\r\n    mid_point = (x_lo + x_hi) / 2\r\n\r\n    if int_range < options.min_interval\r\n        return (0.0, n_fcn_eval)\r\n    end\r\n\r\n    fi = zeros(Nk)\r\n    @inbounds for ii = 1:Nk\r\n        xi = int_range/2 * kronrod_nodes[ii] + mid_point\r\n        fi[ii] = fcn(xi)\r\n    end\r\n    n_fcn_eval += 15\r\n\r\n    gi = fi[gi_idx]\r\n\r\n    K15 = 0.0\r\n    @inbounds for ii = 1:Nk\r\n        K15 += kronrod_weights[ii] * fi[ii]\r\n    end\r\n    K15 *= int_range/2\r\n\r\n    G7 = 0.0\r\n    @inbounds for ii = 1:Ng\r\n        G7 += gauss_weights[ii] * gi[ii]\r\n    end\r\n    G7 *= int_range/2\r\n\r\n    error_est = abs(G7 - K15)\r\n    if error_est <= options.abs_tol\r\n        return (K15, n_fcn_eval)\r\n    end\r\n    if error_est / abs(K15) <= options.rel_tol\r\n        return (K15, n_fcn_eval)\r\n    end\r\n    \r\n    # subdivide the interval\r\n    x_mid = mid_point\r\n\r\n    (K15_left, n_fcn_eval) = __rec_gk(\r\n        fcn,\r\n        x_lo,\r\n        x_mid,\r\n        options,\r\n        gi_idx,\r\n        kronrod_weights,\r\n        kronrod_nodes,\r\n        gauss_weights,\r\n        n_fcn_eval)\r\n\r\n    (K15_right, n_fcn_eval) = __rec_gk(\r\n        fcn,\r\n        x_mid,\r\n        x_hi,\r\n        options,\r\n        gi_idx,\r\n        kronrod_weights,\r\n        kronrod_nodes,\r\n        gauss_weights,\r\n        n_fcn_eval)\r\n    \r\n    return (K15_left + K15_right, n_fcn_eval)\r\nend\r\n\r\n\r\nfunction __gk_nodes_weights()\r\n# gauss_nodes = [\r\n    # -0.949107912342759  # 1\r\n    # -0.741531185599394  # 2\r\n    # -0.405845151377397  # 3\r\n    # 0.0                 # 4\r\n    # +0.405845151377397\r\n    # +0.741531185599394\r\n    # +0.949107912342759\r\n    # ]\r\n\r\n    gauss_weights = [\r\n        0.129484966168870\r\n        0.279705391489277\r\n        0.381830050505119\r\n\r\n        0.417959183673469\r\n\r\n        0.381830050505119\r\n        0.279705391489277\r\n        0.129484966168870\r\n    ]\r\n    \r\n    kronrod_nodes = [\r\n        -0.991455371120813\r\n        -0.949107912342759  # 1\r\n        -0.864864423359769\r\n        -0.741531185599394  # 2\r\n        -0.586087235467691\r\n        -0.405845151377397  # 3\r\n        -0.207784955007898\r\n\r\n        0.0                 # 4\r\n\r\n        0.207784955007898\r\n        0.405845151377397\r\n        0.586087235467691\r\n        0.741531185599394\r\n        0.864864423359769\r\n        0.949107912342759\r\n        0.991455371120813\r\n    ]\r\n\r\n    kronrod_weights = [\r\n        0.022935322010529\r\n        0.063092092629979\r\n        0.104790010322250\r\n        0.140653259715525\r\n        0.169004726639267\r\n        0.190350578064785\r\n        0.204432940075298\r\n\r\n        0.209482141084728\r\n\r\n        0.204432940075298\r\n        0.190350578064785\r\n        0.169004726639267\r\n        0.140653259715525\r\n        0.104790010322250\r\n        0.063092092629979\r\n        0.022935322010529\r\n    ]\r\n\r\n\r\n    gi_idx = [  2, 4, 6, \r\n                8,\r\n                10, 12, 14\r\n            ]\r\n    \r\n    return (gi_idx, kronrod_weights, kronrod_nodes, gauss_weights)\r\nend\r\n\r\n\r\n\r\nend # module\r\n\r\n\r\n", "meta": {"hexsha": "13304cf36b54e80b1275e0b0a35654a73b784fb7", "size": 7831, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/common/numint/src/numint_module.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "__lib__/math/common/numint/src/numint_module.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "__lib__/math/common/numint/src/numint_module.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6078947368, "max_line_length": 74, "alphanum_fraction": 0.5295619972, "num_tokens": 2469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7891364819153913}}
{"text": "struct Dual{V<:Real} <: Real\n    value::V\n    partials::AbstractVector{V}\nend\npartials(d::Dual) = d.partials\nvalue(d::Dual) = d.value\n\nDual(v::V,ps...) where V<:Real = Dual{V}(v,collect(ps))\n\nfunction Base.show(io::IO, d::Dual{V}) where V\n    print(io, \"Dual(\", d.value)\n    for p in d.partials\n        print(io,\",\",p)\n    end\n    print(io, \")\")\nend\n\nfunction jacobian(f, x::AbstractVector{T}) where T\n    duals = map(1:length(x)) do i\n        ps = map(1:length(x)) do j\n            i==j ? T(1) : T(0)\n        end\n        Dual(x[i], ps)\n    end\n    mapreduce(r->reshape(partials(r),1,:), vcat, f(duals))\nend\n\n##########  RULES  #############################################################\n\nBase.:+(a::Dual, b::Dual) = Dual(a.value + b.value, a.partials + b.partials)\nBase.:*(a::Dual, b::Dual) = Dual(a.value * b.value, b.value * a.partials + a.value * b.partials)\n\nfunction cprod(x::AbstractVector)\n    y = similar(x)\n    y[1] = x[1]\n    for i in 2:length(y)\n        y[i] = y[i-1]*x[i]\n    end\n    y\nend\n\n\nx = collect(1:4)\n#csum(x) |> display\n\ndx = [Dual(x[1], 1, 0, 0),\n      Dual(x[2], 0, 1, 0),\n      Dual(x[3], 0, 0, 1)]\ncprod(dx) |> display\ncsum(dx)\n\njacobian(cprod, x)\n", "meta": {"hexsha": "b6722b4b3541ec77732586a4088e945aeea3dbf4", "size": 1176, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/forward.jl", "max_stars_repo_name": "JuliaTeachingCTU/Scientific-Programming-in-Julia", "max_stars_repo_head_hexsha": "7e978fc27ae547fbf95d1367ef1d1d029267e356", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2021-11-12T10:17:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T21:40:39.000Z", "max_issues_repo_path": "scripts/forward.jl", "max_issues_repo_name": "JuliaTeachingCTU/Scientific-Programming-in-Julia", "max_issues_repo_head_hexsha": "7e978fc27ae547fbf95d1367ef1d1d029267e356", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-10-06T09:32:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T15:15:03.000Z", "max_forks_repo_path": "scripts/forward.jl", "max_forks_repo_name": "JuliaTeachingCTU/Scientific-Programming-in-Julia", "max_forks_repo_head_hexsha": "7e978fc27ae547fbf95d1367ef1d1d029267e356", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-05T16:45:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T18:21:34.000Z", "avg_line_length": 22.1886792453, "max_line_length": 96, "alphanum_fraction": 0.5170068027, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.789120728278241}}
{"text": "using LinearAlgebra\nusing Random\nusing ForwardDiff\nusing DataFrames\nusing GLM\n\nfunction marquardt(f, x₀; ε=1e-6, maxiter=1000, λ=10.0^4, α=2)\n    x = x₀\n    fx = f(x)\n    converged = false\n    i = 0\n    while i < maxiter\n        i += 1\n        ∇f = ForwardDiff.gradient(f, x)\n        if norm(∇f) ≤ ε\n            converged = true\n            break\n        end\n        ∇²f = ForwardDiff.hessian(f, x)\n        x′ = x - (∇²f + λ*I) \\ ∇f\n        fx′ = f(x′)\n        if fx′ < fx\n            λ *= 0.5\n            fx = fx′\n            x = x′\n        else\n            λ *= 2.0\n        end\n    end\n    (x=x, fx=fx, converged=converged, iters=i)\nend\n\nrosenbrock(x) = sum((1-x[i])^2 + 100(x[i+1]-x[i]^2)^2 for i in 1:length(x)-1)\n\nRandom.seed!(1234)\nx = rand(20);\nmarquardt(rosenbrock, x)\n\nRandom.seed!(123)\nN = 1000\ndf = DataFrame(rand(N, 4))\ndf.y = sum.(eachrow(df)) + randn(N);\nlm(@formula(y~x1+x2+x3+x4), df)\n\n# This is not very efficient, but is good enough in our case\nfunction ssq(x)\n    m = Matrix(df)[:, startswith.(string.(names(df)), \"x\")]\n    norm(df.y - fill(x[1], nrow(df)) - m * x[2:end])\nend\nmarquardt(ssq, rand(5))\n", "meta": {"hexsha": "7f7ba5a308bcecea52841bad3e9c97490d20a05f", "size": 1120, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4. Optimization/optimziation.jl", "max_stars_repo_name": "bkamins/UEP-Workshop-20190405", "max_stars_repo_head_hexsha": "7fcbb371c3c2efd862ce58752cb1a6cef4300fea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-03-25T20:10:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T01:24:01.000Z", "max_issues_repo_path": "4. Optimization/optimziation.jl", "max_issues_repo_name": "bkamins/UEP-Workshop-20190405", "max_issues_repo_head_hexsha": "7fcbb371c3c2efd862ce58752cb1a6cef4300fea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4. Optimization/optimziation.jl", "max_forks_repo_name": "bkamins/UEP-Workshop-20190405", "max_forks_repo_head_hexsha": "7fcbb371c3c2efd862ce58752cb1a6cef4300fea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-04-03T19:31:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-09T06:11:08.000Z", "avg_line_length": 21.9607843137, "max_line_length": 77, "alphanum_fraction": 0.5258928571, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7891207229052513}}
{"text": "\"\"\"\n    continuedfraction(x::arb)\nCompute a continued fraction representation of `x`.\n\"\"\"\nfunction continuedfraction(x::arb)\n    i = floor(x)\n\n    if isint(i)\n        return [i; continuedfraction(inv(x - i))]\n    else\n        return [i]\n    end\nend\n\n\"\"\"\n    convergents(expansion::Vector{T}) where {T <: Integer}\nCompute the convergents given a continued faction expansion `as`.\n\"\"\"\nfunction convergents(as::Vector{T}) where {T<:Integer}\n    hs = zeros(T, length(as))\n    ks = zeros(T, length(as))\n\n    hs[1] = as[1]\n    ks[1] = one(T)\n\n    hs[2] = as[1] * as[2] + 1\n    ks[2] = as[2]\n\n    for n = 3:length(as)\n        hs[n] = as[n] * hs[n-1] + hs[n-2]\n        ks[n] = as[n] * ks[n-1] + ks[n-2]\n    end\n\n    return hs .// ks\nend\n\n\"\"\"\n    convergents(expansion::Vector{arb})\nCompute the convergents given a continued faction expansion `as`. The\ncomputations are done using ball arithmetic and it returns a list of\npairs corresponding to the nominator and denominator of the\nconvergents.\n\"\"\"\nfunction convergents(as::Vector{arb})\n    hs = similar(as)\n    ks = similar(as)\n\n    hs[1] = as[1]\n    ks[1] = one(as[1])\n\n    hs[2] = as[1] * as[2] + 1\n    ks[2] = as[2]\n\n    for n = 3:length(as)\n        hs[n] = as[n] * hs[n-1] + hs[n-2]\n        ks[n] = as[n] * ks[n-1] + ks[n-2]\n    end\n\n    return collect(zip(hs, ks))\nend\n", "meta": {"hexsha": "9047c8cade16a55472fe964e233f58731c4b3ae2", "size": 1316, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/examples/denominators.jl", "max_stars_repo_name": "Joel-Dahne/MethodOfParticularSolutions.jl", "max_stars_repo_head_hexsha": "4025aa47f972c6d0f8f9593f6bf2dfe297172ba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/examples/denominators.jl", "max_issues_repo_name": "Joel-Dahne/MethodOfParticularSolutions.jl", "max_issues_repo_head_hexsha": "4025aa47f972c6d0f8f9593f6bf2dfe297172ba3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-05T10:50:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-05T11:34:50.000Z", "max_forks_repo_path": "src/examples/denominators.jl", "max_forks_repo_name": "Joel-Dahne/MethodOfParticularSolutions.jl", "max_forks_repo_head_hexsha": "4025aa47f972c6d0f8f9593f6bf2dfe297172ba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5737704918, "max_line_length": 69, "alphanum_fraction": 0.5782674772, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7891207176932735}}
{"text": "using DifferentialEquations\nusing Plots\n\n\nfunction SIR(du,u,p,t)\n    s,i,r = u\n    b,k = p\n    du[1] = -b*s*i\n    du[2] = b*s*i - k*i\n    du[3] = k*i\nend\n\n#initian conditions\np = [0.5/7900000.0,0.33]\nu0 = [7900000.0,10.0,0.0]\n# u0 = [1.,1.27e-6,0.]\ntspan = (0.0,140.0)\n\n#solve\nsir = ODEProblem(SIR,u0,tspan,p)\nsol_sir = solve(sir)\n\n#plot\nplot(sol_sir)   ", "meta": {"hexsha": "54eb556ed1a0f64bd9c50153f2aeae74a89e3e61", "size": 354, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Randoms/SIR.jl", "max_stars_repo_name": "Ved-Mahajan/JustForFun", "max_stars_repo_head_hexsha": "4e2c7a69074ca20e0ab7b11e8ca4928a2043aabb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Randoms/SIR.jl", "max_issues_repo_name": "Ved-Mahajan/JustForFun", "max_issues_repo_head_hexsha": "4e2c7a69074ca20e0ab7b11e8ca4928a2043aabb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Randoms/SIR.jl", "max_forks_repo_name": "Ved-Mahajan/JustForFun", "max_forks_repo_head_hexsha": "4e2c7a69074ca20e0ab7b11e8ca4928a2043aabb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.75, "max_line_length": 32, "alphanum_fraction": 0.581920904, "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9678992905050948, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.7890629567304547}}
{"text": "using Distributions\n\n\"\"\"\nExample of a computation of beta credible interval\n\"\"\"\nfunction betaCredibleInt()\n    S = 47\n    N = 100\n    a = S+1\n    b = (N-S)+1\n    α = .05\n    β = Beta(a, b)\n    CI = quantile(β, [α/2, 1-α/2])\nend\n\n", "meta": {"hexsha": "8ea285e618a3a4807c45b1c86d1933665beaeeed", "size": 229, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BayesianStatistics/betaCredibleInt.jl", "max_stars_repo_name": "aoboturov/PMTK4BookDemos.jl", "max_stars_repo_head_hexsha": "f44853081139b358e0e9a2bb36a3d35ac35dcb39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-25T15:50:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-25T15:50:42.000Z", "max_issues_repo_path": "src/BayesianStatistics/betaCredibleInt.jl", "max_issues_repo_name": "aoboturov/PMTK4BookDemos.jl", "max_issues_repo_head_hexsha": "f44853081139b358e0e9a2bb36a3d35ac35dcb39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BayesianStatistics/betaCredibleInt.jl", "max_forks_repo_name": "aoboturov/PMTK4BookDemos.jl", "max_forks_repo_head_hexsha": "f44853081139b358e0e9a2bb36a3d35ac35dcb39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.3125, "max_line_length": 50, "alphanum_fraction": 0.5545851528, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632329799585, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7890363800651624}}
{"text": "include(\"differentiation.jl\")\nusing Plots\n\nh = 2.0 .^ (-2:-1:-52)\nffderr = []\nbfderr = []\ncfderr = []\nf(x) = exp(x)\nx = 1.0\ndfexact = exp(1.0)\nfor h0 in h\n    append!(ffderr, abs(ffd(f, x, h0 )-dfexact))\n    append!(bfderr, abs(bfd(f, x, h0 )-dfexact))\n    append!(cfderr, abs(cfd(f, x, h0 )-dfexact))\nend\n\nplot(h, ffderr, xaxis=:log, yaxis=:log)\nplot!(h, bfderr, xaxis=:log, yaxis=:log)\nplot!(h, cfderr, xaxis=:log, yaxis=:log)", "meta": {"hexsha": "3e99f980a09c74fcbd878271d238f6f0dd28d830", "size": 428, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/differentiation_demo.jl", "max_stars_repo_name": "hessianguo/NumericalMethod.jl", "max_stars_repo_head_hexsha": "bd6c00a88c8168e39b2ba1894466a6b6f6e24984", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/differentiation_demo.jl", "max_issues_repo_name": "hessianguo/NumericalMethod.jl", "max_issues_repo_head_hexsha": "bd6c00a88c8168e39b2ba1894466a6b6f6e24984", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/differentiation_demo.jl", "max_forks_repo_name": "hessianguo/NumericalMethod.jl", "max_forks_repo_head_hexsha": "bd6c00a88c8168e39b2ba1894466a6b6f6e24984", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5263157895, "max_line_length": 48, "alphanum_fraction": 0.6051401869, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632329799585, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7890363760426388}}
{"text": "# # Chapter 3 - 数学のおさらい\n\n\n## #src\n# ## 3.1 線形代数\n# ### 3.1.1 スカラーとベクトル\n## 列ベクトル: 2行1列のArrayを定義\n## Juliaはcolumn-major\nw = [5.0, 3.0]\n\n\n## #src\n## 行ベクトル\n#-\n## 行ベクトル: 1行2列\nx = [5.0 3.0]\n\n\n## #src\n#-\n## すべての要素が0の1行5列のArrayを生成\nx_zeros = zeros(1, 5)\n\n\n## #src\n#-\n## すべての要素が1の1行5列のArrayを生成\nx_ones = ones(1, 5)\n\n\n## #src\n#-\n## 一様分布または正規分布にしたがってランダムに1行5列のArrayを生成\nusing Random\nRandom.seed!(1234)\n\n## 一様分布\nuniform = rand(1, 5)\n\n\n## #src\n#-\n## 正規分布\nnormal = randn(1, 5)\n\n\n## #src\n#-\n## 標準出力\nfor s in (:w, :x, :x_zeros, :x_ones, :uniform, :normal)\n    y = eval(s)\n    println(\"ベクトル $(s)) 形: $(size(y)), 要素の型:$(eltype(y))\\n$(y)\\n\")\nend\n\n\n## #src\n### 3.1.2 ベクトルの内積\n## 列ベクトル: 2行1列のArrayを定義\nw = [5.0, 3.0]\n\n## 行ベクトル: 1行2列\nx = [1.0 5.0]\n\n## 内積の計算\n## \\cdot\nusing LinearAlgebra\nxw = x ⋅ w\n\n\n## #src\n#-\n## wのノルムの計算: wの転置(行ベクトル)とw(列ベクトル)の掛け算\nww = transpose(w) ⋅ w\n\n\n## #src\n#-\n## ノルムを計算する関数が用意されている\nnorm(w)\n\n\n## #src\n#-\nprintln(\"xとwの内積) 形: $(size(xw)), 型:$(typeof(xw))\\n$(xw)\\n\")\nprintln(\"wのノルム) 形: $(size(ww)), 型:$(typeof(ww))\\n$(ww)\\n\")\n\n\n## #src\n# ### 3.1.5 行列とベクトルの関係\n## 行列: 3行2列のArrayを定義\nX = [1.0 2.0; 2.0 4.0; 3.0 6.0]\n\n\n## #src\n#-\n## 1行目の行ベクトル(1行2列)の取り出し\nXrow1 = X[[1], :]\n\n\n## #src\n#-\n## 2列目の列ベクトル(3行1列)の取り出し\nXcol2 = X[:, [2]]\n\n\n## #src\n#-\n## 標準出力\nprintln(\"行列X) 形:$(size(X)), 要素の型:$(eltype(X))\\n$(X)\\n\")\nprintln(\"1行目) 形:$(size(Xrow1)), 要素の型:$(eltype(Xrow1))\\n$(Xrow1)\\n\")\nprintln(\"2列目) 形:$(size(Xcol2)), 要素の型:$(eltype(Xcol2))\\n$(Xcol2)\\n\")\n\n\n## #src\n#-\n## リストなしの場合\nX[1, :]\n\n\n## #src\n#-\n## リストありの場合\nX[[1], :]\n\n\n## #src\n# ### 3.1.6 行列の積と和\n## 行列 X: 3行2列のArrayを定義\nX = [1.0 2.0; 2.0 4.0; 3.0 6.0]\n\n## 列ベクトル b: 2行1列のArrayを定義\nw = [5.0, 3.0]\n\n## 列ベクトル b: 3行1列のArrayを定義\nb = [1.0, 1.0, 1.0]\n\n## 行列とベクトルの積と和\nres = X * w .+ b\nprintln(\"積和の結果 \\n$(res)\")\n\n\n## #src\n# ### 3.1.8 行列の階数\n## 行列: 2行2列のArrayを定義\nA = [6.0 2.0; 2.0 5.0]\nB = [6.0 3.0; 2.0 1.0]\n\n## 行列のランクの計算\nprintln(\"Rank of A: $(rank(A))\")\nprintln(\"Rank of B: $(rank(B))\")\n\n\n## #src\n#-\nfunction find_inv(mat)\n    if rank(mat) == size(mat)[1]\n        println(\"行列:\\n$(mat)\\nランク$(rank(mat))\\n逆行列:\\n$(inv(mat))\\n\")\n    else\n        println(\"行列:\\n$(mat)\\nランク$(rank(mat))\\n特異行列\")\n    end\nend\n\nfind_inv(A)\nfind_inv(B)\n\n\n## #src\n# ### 3.1.10 行列と行列式の関係\n## 行列: 2行2列のArrayを定義\nA = [6.0 2.0; 2.0 5.0]\nB = [6.0 3.0; 2.0 1.0]\n\n## 行列式の計算\nprintln(\"行列Aの行列式: $(det(A))\")\nprintln(\"行列Bの行列式: $(det(B))\")\n\n\n## #src\n# ### 3.1.12 固有値問題の解法\n## 行列Aの定義\nA = [3 2; 4 1]\n\n## 固有値問題の解\neig_A = eigen(A)\n\n\n## #src\n# ### 3.1.13 固有値と固有ベクトルの性質\n## 行列Aの定義\nA = [3 1; 1 3]\n\n## 固有値・固有ベクトル\neig_A = eigen(A)\n\nprintln(\"行列Aの固有値:\\n$(eig_A.values)\")\nprintln(\"行列Aの固有ベクトル:\\n$(eig_A.vectors)\")\nprintln(\"固有ベクトルの内積:$(eig_A.vectors[:, 1] ⋅ eig_A.vectors[:, 2])\")\nprintln(\"固有値の和:$(sum(eig_A.values))\")\nprintln(\"行列Aのトレース(対角成分の和):$(tr(A))\")\nprintln(\"固有値の積:$(prod(eig_A.values))\")\nprintln(\"行列Aの行列式:$(det(A))\")\nprintln(\"固有ベクトルがなす行列の逆行列:\\n$(eig_A.vectors)\")\nprintln(\"固有ベクトルがなす行列の転置行列:\\n$(eig_A.vectors')\")\n\n\n## #src\n# ## 3.2 最適化\n## 行列Aの定義\nA = [2 -3; 4 1]\n\n## 列ベクトルbの定義\nb = [5, -2]\n\n\n## #src\n#-\n## 行列が非ゼロか否かを確認\nif det(A) != 0\n    ## Aの逆行列とベクトルbの積から解を求める\n    w = inv(A) * b\n    println(\"wの解\\n$(w)\")\nelse\n    ## 解が存在しない\n    println(\"解が存在しません.\")\nend\n\n\n## #src\n#-\n# ### 3.2.2 微分を用いた解放\n## 最急降下法による最適化\n## 学習率の設定\nα = 0.2\n\n## パラメーターの初期化\nw = 1\n\nfor ite in 1:50\n    println(\"反復$(ite), w=$(round(w; digits = 2))\")\n    ## 最急降下法によるパラメーターの更新\n    global w-= α * 3 * w^2\nend\n\n\n## #src\n#-\n### 3.3.2 ベルヌーイ分布\n## p=6/13(青色のボールの確率)のベルヌーイ分布に従って10回試行を行う\nusing Distributions\n\nb = Bernoulli(6/13)\n\nX1 = rand(b, 10)\nX2 = rand(b, 10)\nX3 = rand(b, 10)\n\n## 標準出力\nprintln(\"データ X1:\\n$(X1)\")\nprintln(\"データ X2:\\n$(X2)\")\nprintln(\"データ X3:\\n$(X3)\")\n\n\n## #src\n### 3.3.9 正規分布\n## 平均0, 分散1の正規分布に従って10回試行を行う\nX1 = rand(Normal(0, 1), 10)\n## 平均3, 分散1の正規分布に従って10回試行を行う\nX2 = rand(Normal(3, 1), 10)\n## 平均-3, 分散1の正規分布に従って10回試行を行う\nX3 = rand(Normal(-3, 1), 10)\n\n## 標準出力\nprintln(\"データ X1:\\n$(X1)\")\nprintln(\"データ X2:\\n$(X2)\")\nprintln(\"データ X3:\\n$(X3)\")\n\n\n## #src\n# ## 3.4 統計\n# ### 3.4.1 中心の統計量\n## 3種類(身長、体重、胸囲)のデータを格納する8行3列の行列\nX = [\n    170 60 80;\n    167 52 93;\n    174 57 85;\n    181 70 80;\n    171 62 70;\n    171 66 95;\n    171 66 95;\n    168 54 85;\n]\n\n## 行方向(dims=1)に対して、平均値を計算\nmeans = mean(X; dims=1)\n\n## 行方向(dims=1)に対して、中央値を計算\nmedians = median(X; dims=1)\n\n## 標準出力\nprintln(\"データ X:\\n$X\")\nprintln(\"身長の平均値: $(means[1]), 体重の平均値:$(means[2]), 胸囲の平均値$(means[3])\")\nprintln(\"身長の中央値: $(medians[1]), 体重の中央値:$(medians[2]), 胸囲の中央値$(medians[3])\")\n\n\n## src\n#-\n## 分散共分散行列の計算\n## 3種類(身長、体重、胸囲)のデータを格納する8行3列の行列\nX = [\n    170 60 80;\n    167 52 93;\n    174 57 85;\n    181 70 80;\n    171 62 70;\n    171 66 95;\n    171 66 95;\n    168 54 85;\n]\nvars = var(X; corrected=false, dims=1)\nstds = std(X; corrected=false, dims=1)\ncov_bias = cov(X)\ncov_nobias = cov(X; corrected=false)\nprintln(\"データ X:\\n$X\")\nprintln(\"分散) 身長:$(vars[1]), 体重:$(vars[2]), 胸囲:$(vars[3])\")\nprintln(\"標準偏差) 身長:$(stds[1]), 体重:$(stds[2]), 胸囲:$(stds[3])\")\nprintln(\"分散共分散行列 バイアスあり:\\n$(cov_bias)\")\nprintln(\"分散共分散行列 バイアスなし:\\n$(cov_nobias)\")\n\n\n## #src\n# ### 3.4.7 相関係数と相関行列\n## 3種類(身長、体重、胸囲)のデータを格納する8行3列の行列\nX = [\n    170 60 80;\n    167 52 93;\n    174 57 85;\n    181 70 80;\n    171 62 70;\n    171 66 95;\n    171 66 95;\n    168 54 85;\n]\nprintln(\"データ X:\\n$X\")\nprintln(\"相関行列:\\n$(cor(X))\")\n", "meta": {"hexsha": "b8b094afc1c193efc18f69ab9a95e860933e1a2c", "size": 5133, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebook_script/chapter3.jl", "max_stars_repo_name": "matsueushi/machine-learning-from-scratch-with-julia", "max_stars_repo_head_hexsha": "46ee819a59df9e73bee5ec166d9bf9548ee3a803", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebook_script/chapter3.jl", "max_issues_repo_name": "matsueushi/machine-learning-from-scratch-with-julia", "max_issues_repo_head_hexsha": "46ee819a59df9e73bee5ec166d9bf9548ee3a803", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebook_script/chapter3.jl", "max_forks_repo_name": "matsueushi/machine-learning-from-scratch-with-julia", "max_forks_repo_head_hexsha": "46ee819a59df9e73bee5ec166d9bf9548ee3a803", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.8782608696, "max_line_length": 75, "alphanum_fraction": 0.566725112, "num_tokens": 3267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7890363708881731}}
{"text": "# Spherical and cartesian coordinate conversions\n\n\"\"\"\n    azimuth(lon1, lat1, lon2, lat2, degrees::Bool=true) -> az\n\nCompute the azimuth `az` from point (`lon1`, `lat1`) to (`lon2`, `lat2`) on the sphere.\nPoints and azimuth are read and returned in degrees by default; use `degrees=false`\nfor radians.\n\"\"\"\nfunction azimuth(lon1, lat1, lon2, lat2, degrees::Bool=true)\n    if degrees\n        lon1, lat1, lon2, lat2 = deg2rad(lon1), deg2rad(lat1), deg2rad(lon2), deg2rad(lat2)\n    end\n    azimuth = atan(sin(lon2-lon1)*cos(lat2),\n                   cos(lat1)*sin(lat2) - sin(lat1)*cos(lat2)*cos(lon2-lon1))\n    degrees ? rad2deg(azimuth) : azimuth\nend\n\n\"\"\"\n    cart2geog(x, y, z, degrees::Bool=true) -> lon, lat, r\n\nCompute the longitude, latitude and radius given the cartesian coordinates `x`,\n`y` and `z`, where `x` is at (lon,lat) = (0,0), `y` is at (90°,0) and `z` is\nthrough lat = 90°.\n\"\"\"\nfunction cart2geog(x, y, z, degrees::Bool=true)\n    r = sqrt(x^2 + y^2 + z^2)\n    r == 0. && return zero(x), zero(x), zero(x)\n    lon = atan(y, x)\n    lat = asin(z/r)\n    degrees ? (rad2deg(lon), rad2deg(lat), r) : (lon, lat, r)\nend\n\nfunction cart2geog(x::AbstractArray, y::AbstractArray, z::AbstractArray, degrees::Bool=true)\n    dims = size(x)\n    dims == size(y) == size(z) || throw(ArgumentError(\"All arrays must have same length\"))\n    T = promote_type(float.(eltype.((x, y, z)))...)\n    lon, lat, r = Array{T}(dims), Array{T}(dims), Array{T}(dims)\n    for i in eachindex(lon)\n        lon[i], lat[i], r[i] = cart2geog(x[i], y[i], z[i], degrees)\n    end\n    lon, lat, r\nend\n\n\"\"\"\n    delta(lon1, lat1, lon2, lat2, degrees::Bool=true) -> d\n\nCompute the angular distance `d` on the sphere between two points, (`lon1`, `lat1`)\nand (`lon2`, `lat2`).  Points and distance are read and returned in degrees\nby default; use `degrees=false` for radians.\n\"\"\"\nfunction delta(lon1, lat1, lon2, lat2, degrees::Bool=true)\n    if degrees\n        lon1, lat1, lon2, lat2 = deg2rad(lon1), deg2rad(lat1), deg2rad(lon2), deg2rad(lat2)\n    end\n    d = atan(sqrt(\n               (cos(lat2)*sin(lon2-lon1))^2 + (cos(lat1)*sin(lat2) -\n                sin(lat1)*cos(lat2)*cos(lon2-lon1))^2),\n               sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2)*cos(lon2-lon1)\n              )\n    degrees ? rad2deg(d) : d\nend\n\n\"\"\"\n    geog2cart(lon, lat, r, degrees::Bool=true) -> x, y, z\n    geog2cart(lon, lat, degrees::Bool=true) -> x, y, z\n\nReturn the cartesian coordinates given the geographic longitude, latitude and\nradius `lon`, `lat` and `r`.\n\nIf `r` is not given, points are returned on the unit sphere.\n\"\"\"\nfunction geog2cart(lon, lat, r, degrees::Bool=true)\n    points_valid(lon, lat, degrees) || error(\"geog2cart: Points are not on the sphere\")\n    degrees && begin lon, lat = deg2rad(lon), deg2rad(lat) end\n    x = r*cos(lon)*cos(lat)\n    y = r*sin(lon)*cos(lat)\n    z = r*sin(lat)\n    x, y, z\nend\nfunction geog2cart(lon::AbstractArray, lat::AbstractArray, r::AbstractArray, degrees::Bool=true)\n    size(lon) == size(lat) == size(r) ||\n        throw(ArgumentError(\"Sizes of lon, lat and r must be the same\"))\n    T = promote_type(float.(eltype.((lon, lat, r)))...)\n    x = Array{T}(undef, size(lon))\n    y, z = similar(x), similar(x)\n    for i in eachindex(lon)\n        x[i], y[i], z[i] = geog2cart(lon[i], lat[i], r[i], degrees)\n    end\n    x, y, z\nend\ngeog2cart(lon::AbstractArray, lat::AbstractArray, degrees::Bool=true) =\n    geog2cart(lon, lat, fill(one(eltype(lon)), size(lon)), degrees)\n\n\"\"\"\n    points_valid(lon, lat, degrees::Bool=true) -> ::Bool\n\nReturn `true` if all points in arrays `lon` and `lat` are on the sphere.\n`lon` is ignored, but `lat` is checked to see if points are in the range\n-90°–90° (-π–π).  Points are read and returned in degrees by default; use\n`degrees=false` for radians.\n\"\"\"\npoints_valid(lon, lat, degrees::Bool=true) =\n    degrees ? !any(abs.(lat) .> 90.) : !any(abs.(lat) .> pi/2.)\n\n\"\"\"\n    geodesic_endpoint(lon, lat, az, delta, degrees::Bool=true) -> lon1, lat1\n\nCompute the end point (`lon1`, `lat1`) reached by travelling on the sphere along\nazimuth `az` for `delta` angular distance.  Points, angles and distance are read\nand returned in degrees by default; use `degrees=false` for radians.\n\"\"\"\nfunction geodesic_endpoint(lon, lat, az, delta, degrees::Bool=true)\n    if degrees\n        lon, lat, az, delta = deg2rad(lon), deg2rad(lat), deg2rad(az), deg2rad(delta)\n    end\n    lat2 = asin(sin(lat)*cos(delta) + cos(lat)*sin(delta)*cos(az))\n    lon2 = lon + atan(sin(az)*sin(delta)*cos(lat),\n                      cos(delta)-sin(lat)*sin(lat2))\n    if degrees\n        lon2, lat2 = rad2deg(lon2), rad2deg(lat2)\n    end\n    lon2, lat2\nend\n", "meta": {"hexsha": "8c94e2a11a1b24281f60ee21b6e31947116e69d4", "size": 4649, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sphericalgeom.jl", "max_stars_repo_name": "anowacki/Beamforming", "max_stars_repo_head_hexsha": "0f5ccd393d64bd28210410972b50989189b28728", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-05-18T16:07:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T00:14:14.000Z", "max_issues_repo_path": "src/sphericalgeom.jl", "max_issues_repo_name": "anowacki/Beamforming", "max_issues_repo_head_hexsha": "0f5ccd393d64bd28210410972b50989189b28728", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sphericalgeom.jl", "max_forks_repo_name": "anowacki/Beamforming", "max_forks_repo_head_hexsha": "0f5ccd393d64bd28210410972b50989189b28728", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-10T08:27:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T02:30:53.000Z", "avg_line_length": 37.192, "max_line_length": 96, "alphanum_fraction": 0.629812863, "num_tokens": 1462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7890278685313092}}
{"text": "# https://www.juliabox.com/notebook/notebooks/tutorials/intro-to-julia/AutoDiff.ipynb\n# Dual Number\n\nusing InteractiveUtils \nversioninfo()\n\nstruct D <: Number \n    f::Tuple{Float64,Float64}\nend \n\nBase.show(io::IO, x::D) = print(io,x.f[1],\" + \", x.f[2],\"ϵ\")\n\nimport Base: +, -, *, /, convert, promote_rule\n+(x::D, y::D) = D(x.f .+ y.f)\n-(x::D, y::D) = D(x.f .- y.f)\n*(x::D, y::D) = D((x.f[1] .* y.f[1], x.f[2] * y.f[1] + x.f[1] * y.f[2]))\n/(x::D, y::D) = D((x.f[1] / y.f[1], (y.f[1] * x.f[2] - x.f[1] * y.f[2]) / y.f[1]^2))\nconvert(::Type{D}, x::Real) = D((x,zero(x)))\npromote_rule(::Type{D}, ::Type{<:Number}) = D\n\nϵ = D((0,1))\n\n@show ϵ * ϵ, ϵ^2\n@show 1/(1+ϵ)\n@show (1+ϵ)^10\n\nfunction nthroot(x, n=2; t=1, N = 10) \n    for i in 1:N\n        t += (x/t^(n-1)-t)/n\n    end\n    t\nend\n\n@show nthroot(2,3), ∛2\n@show nthroot(7,12), 7^(1/12)\nx=17.0; @show nthroot(x+ϵ, 3), ∛x, 1/x^(2/3)/3\n\n#= output\nJulia Version 0.7.0\nCommit a4cb80f3ed (2018-08-08 06:46 UTC)\nPlatform Info:\n  OS: macOS (x86_64-apple-darwin14.5.0)\n  CPU: Intel(R) Core(TM) M-5Y51 CPU @ 1.10GHz\n  WORD_SIZE: 64\n  LIBM: libopenlibm\n  LLVM: libLLVM-6.0.0 (ORCJIT, broadwell)\n(ϵ * ϵ, ϵ ^ 2) = (0.0 + 0.0ϵ, 0.0 + 0.0ϵ)\n1 / (1 + ϵ) = 1.0 + -1.0ϵ\n(1 + ϵ) ^ 10 = 1.0 + 10.0ϵ\n(nthroot(2, 3), ∛2) = (1.2599210498948732, 1.2599210498948732)\n(nthroot(7, 12), 7 ^ (1 / 12)) = (1.1760474285795146, 1.1760474285795146)\n(nthroot(x + ϵ, 3), ∛x, (1 / x ^ (2 / 3)) / 3) = (2.571281590658235 + 0.05041728609133794ϵ, 2.571281590658235, 0.05041728609133795)\n=#", "meta": {"hexsha": "de0a7a4cad1a6017f609d028f01ce1b6ca032453", "size": 1497, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "officialTutorial/dual_number.jl", "max_stars_repo_name": "terasakisatoshi/juliaExer", "max_stars_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-02T01:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-04T12:03:25.000Z", "max_issues_repo_path": "officialTutorial/dual_number.jl", "max_issues_repo_name": "terasakisatoshi/juliaExer", "max_issues_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "officialTutorial/dual_number.jl", "max_forks_repo_name": "terasakisatoshi/juliaExer", "max_forks_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2452830189, "max_line_length": 131, "alphanum_fraction": 0.5597862391, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7890278630233173}}
{"text": "\nabstract type lossFun end\n\nexport lossFun\n\n### binaryCrossentropy\n\n\"\"\"\n    return the average cross entropy loss over vector of labels and predictions\n\n    input:\n        a := (?1, c,m) matrix of predicted values, where c is the number of classes\n        y := (?1, c,m) matrix of predicted values, where c is the number of classes\n\n        Note: in case the number of classes is one (1) it is okay to have\n              a scaler values for a and y\n\n    output:\n        J := scaler value of the cross entropy loss\n\"\"\"\nabstract type binaryCrossentropy <: lossFun end\n\nfunction binaryCrossentropy(a, y)\n\n    aNew = prevnextfloat.(a)\n    J = .-(y .* log.(aNew) .+ (1 .- y) .* log.(1 .- aNew))\n    return J\nend #binaryCrossentropy\n\nexport binaryCrossentropy\n\n\"\"\"\n    compute the drivative of cross-entropy loss function to the input of the\n    layer dZ\n\"\"\"\nfunction dbinaryCrossentropy(a, y)\n    dJ = a .- y\n    return dJ\nend #dbinaryCrossentropy\n\nexport dbinaryCrossentropy\n\n\n### categoricalCrossentropy\n\nabstract type categoricalCrossentropy <: lossFun end\n\nfunction categoricalCrossentropy(a, y)\n    aNew = prevnextfloat.(a)\n    J = .-(y .* log.(aNew))\n    return J\nend\n\n\nfunction dcategoricalCrossentropy(a, y)\n    dJ = a .- y\n    return dJ\nend\n\nexport categoricalCrossentropy, dcategoricalCrossentropy\n\n\n\"\"\"\n    return previous float if x == 1 and nextfloat if x == 0\n\"\"\"\nprevnextfloat(x) = x==0 ? nextfloat(x) : x==1 ? prevfloat(x) : x\n\nexport prevnextfloat\n\n\n### cost function\n\n\"\"\"\n    function cost(\n        loss::Type{categoricalCrossentropy},\n        A::AbstractArray{T1,N},\n        Y::AbstractArray{T2,N},\n    ) where {T1, T2, N}\n\nCompute the cost for `categoricalCrossentropy` loss function\n\n\"\"\"\nfunction cost(\n    loss::Type{categoricalCrossentropy},\n    A::AbstractArray{T1,N},\n    Y::AbstractArray{T2,N},\n) where {T1, T2, N}\n\n    c, m = size(A)[N-1:N]\n    costs = sum(loss(Float64.(A),Y)) / m\n    return Float64.(costs)\n\nend #function cost\n\n\"\"\"\n    function cost(\n        loss::Type{binaryCrossentropy},\n        A::AbstractArray{T1,N},\n        Y::AbstractArray{T2,N},\n    ) where {T1, T2, N}\n\nCompute the cost for `binaryCrossentropy` loss function\n\n\"\"\"\nfunction cost(\n    loss::Type{binaryCrossentropy},\n    A::AbstractArray{T1,N},\n    Y::AbstractArray{T2,N},\n) where {T1, T2, N}\n\n    c, m = size(A)[N-1:N]\n    costs = sum(loss(Float64.(A),Y)) / (c*m)\n    return Float64.(costs)\n\nend #function cost\n", "meta": {"hexsha": "07112cc83b5cb391d4d493f1e61ef9eb263cbbba", "size": 2411, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lossFuns.jl", "max_stars_repo_name": "MohHizzani/NumNN.jl", "max_stars_repo_head_hexsha": "1a753a20cc2bcd8bde789aa12d7fbb1b31506512", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-04-15T13:45:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T11:43:26.000Z", "max_issues_repo_path": "src/lossFuns.jl", "max_issues_repo_name": "MohHizzani/NumNN.jl", "max_issues_repo_head_hexsha": "1a753a20cc2bcd8bde789aa12d7fbb1b31506512", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lossFuns.jl", "max_forks_repo_name": "MohHizzani/NumNN.jl", "max_forks_repo_head_hexsha": "1a753a20cc2bcd8bde789aa12d7fbb1b31506512", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7844827586, "max_line_length": 83, "alphanum_fraction": 0.6491082538, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.8558511506439707, "lm_q1q2_score": 0.7890278594924998}}
{"text": "## Exercise 4-5\n## Make a copy of square and change the name to polygon. Add another parameter named n and modify the body so it draws an n-sided regular polygon.\n\n## TIP\n## The exterior angles of an n-sided regular polygon are 360/n degrees.\nusing ThinkJulia\n\nprintln(\"Ans: \")\n\nfunction polygon(turtle::Turtle, nsides::Int, len::Int = 100)\n    angle = Int(360 / nsides)\n    println(\"Angle: \" * string(angle))\n\n    for i in 1:nsides\n        forward(turtle, len)\n        turn(turtle, -angle)\n    end\nend\n\n# (a) Try 1 \n# @svg begin\n#     polygon(Turtle(), 5)\n# end\n\n# (b) Try 2 \n@svg begin\n    polygon(Turtle(), 9)\nend\n\nprintln(\"End.\")\n", "meta": {"hexsha": "6c589dc2a9f9746bb2198a038f7319c157232620", "size": 634, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter4/ex5.jl", "max_stars_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_stars_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-13T14:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T14:11:30.000Z", "max_issues_repo_path": "Chapter4/ex5.jl", "max_issues_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_issues_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter4/ex5.jl", "max_forks_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_forks_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4516129032, "max_line_length": 146, "alphanum_fraction": 0.6498422713, "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7890278563852136}}
{"text": "using ForwardDiff\nusing Plots\nusing ReverseDiff\nusing DifferentialEquations\nusing Flux\nusing Statistics\n# gr()\n# pyplot()\nplotly()\n\n# Define SHO Hamiltonian Function\nH(q, p) = 0.5*q^2 + 0.5*p^2\n\n\nfunction dH(q, p)\n    dHdq, dHdp = ForwardDiff.gradient(x->H(x[1], x[2]), [q, p])\n    return dHdq, dHdp\nend\n\nfunction dH_analytic(q, p)\n    return q, p\nend\n\nfunction H_vec_field(q, p)\n    dHdq, dHdp = dH(q, p)\n    q̇ = dHdp\n    ṗ = - dHdq\n\n    return q̇, ṗ\nend\n\n\n# Visualize the H, it's level curves, and the flow as\n# as tangent vectors to level curves\n# i.e. governing idea is H = const\nqs = -1.5:0.1:1.5\nps = -1.5:0.1:1.5\n\nQ = []\nP = []\nQ̇ = []\nṖ = []\n\nfor q ∈ qs[1:2:end], p ∈ ps[1:2:end]\n    q̇, ṗ = H_vec_field(q, p)\n    push!(Q, q)\n    push!(P, p)\n    push!(Q̇, q̇)\n    push!(Ṗ, ṗ)\nend\n\np1 = contour(qs, ps, H, xlabel=\"q\", ylabel=\"p\", aspect_ratio=1.0, fill=true, colorbar_title=\"H\", size=(800,800), c=:viridis)\nα=0.1\nquiver!(p1, Q, P, quiver=(α .* Q̇, α .* Ṗ), aspect_ratio=1.0, color=:white)\nxlims!(p1, -1.5, 1.5)\nylims!(p1, -1.5, 1.5)\n\n\n\n\n\nHam(q,p, param) = q^2 + p^2\np0=1.0\nq0=0.0\ntspan=(0.0, 10.0)\nprob = HamiltonianProblem(Ham, p0, q0, tspan, dt=0.01)\nsol = solve(prob, SymplecticEuler())\n\nplot!(p1, sol[1,:], sol[2, :], color=:green, label=\"q₀=$(q0), p₀=$(p0)\")\n\np0=1.5\nq0=0.0\ntspan=(0.0, 10.0)\nprob = HamiltonianProblem(Ham, p0, q0, tspan, dt=0.01)\nsol = solve(prob, SymplecticEuler())\n\nplot!(p1, sol[1,:], sol[2, :], color=:cyan, label=\"q₀=$(q0), p₀=$(p0)\")\n\n\n\n# Let's set up the Neural Network to approximate the Hamiltonian\n# generate training data with H(q,p) <= 1\nNpoints = 500\nr_train = sqrt.(rand(1, Npoints))\nφ_train = 2π.*rand(1, Npoints)\ndata = vcat(r_train .* cos.(φ_train), r_train .* sin.(φ_train))\n\n\n# set up target data: here we use analytic result for time derivatives\ntarget = zero(data)\n# i.e. q̇= dHdp, ṗ = -dHdq\ntarget[1,:] .= data[2, :]\ntarget[2,:] .= -data[1, :]\n\n\np2 =  scatter!(p1, data[1,:], data[2,:], c=:green, label=\"training points\")\np3 = plot(Q, P, H.(Q, P), st = :surface, xlabel = \"q\", ylabel = \"p\", zlabel = \"H\")\n\n\n\n# -------------------------------------------------------------------------------------------------------\n# create model for HNN\n\n# define the struct\nstruct HNN{M, R, P}\n    model::M  # the internal NN\n    re::R   # for recreating internal NN\n    p::P  # for holding current params of internal NN\n\n\n    # define the constructor\n    function HNN(model)\n        p, re = Flux.destructure(model)\n        return new{typeof(model), typeof(re), typeof(p)}(model, re, p)\n    end\nend\n\n# define the trainable paramaters\nFlux.trainable(hnn::HNN) = (hnn.p,)\n\nfunction _hamiltonian_flow(re, p, x)\n    dHdX = Flux.gradient(x->sum(re(p)(x)), x)[1]  # note: re(p)(x) == Model(x)\n    n = size(x,1) ÷ 2  # i.e. how many p's and q's\n    return cat(dHdX[(n+1):2n, :], dHdX[1:n, :], dims=1)\nend\n\n# define how to call the HNN on data\n(hnn::HNN)(X, p=hnn.p) = _hamiltonian_flow(hnn.re, p, X)\n\n\nhnn = HNN(\n    Chain(Dense(2, 200, relu), Dense(200, 200, relu), Dense(200, 1))\n)\n\ndataloader = Flux.Data.DataLoader((data, target), batchsize=500, shuffle=true)\n\np = hnn.p\n\nopt = ADAM(10^(-3))\n\nloss(x, y, p) = mean((hnn(x, p) .- y) .^ 2)\nloss(data, target, p)\n\n\ncallback() = println(\"Loss Neural Hamiltonian DE = $(loss(data, target, p))\")\ncallback()\n\n\ntest_gs = ReverseDiff.gradient(p -> loss(data, target, p), p)\n\nepochs = 2000\nfor epoch in 1:epochs\n    for (x, y) in dataloader\n        gs = ReverseDiff.gradient(p -> loss(x, y, p), p)\n        Flux.Optimise.update!(opt, p, gs)\n    end\n    if epoch % 100 == 1\n        callback()\n    end\nend\ncallback()\n\n\n#p3 = plot(Q, P, H.(Q, P), st = :surface, xlabel = \"q\", ylabel = \"p\", zlabel = \"H\")\n#p3 = plot(Q, P, HNN.model.(Q, P), st = :surface, xlabel = \"q\", ylabel = \"p\", zlabel = \"H\")\n", "meta": {"hexsha": "aabfef61b64346d7ab16bcc6a28a3493c8b22d57", "size": 3772, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "old_news/john/hamiltonian_nn.jl", "max_stars_repo_name": "john-waczak/SciML_SHO", "max_stars_repo_head_hexsha": "180d46e9755e6a70f281086a373e183b57544275", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "old_news/john/hamiltonian_nn.jl", "max_issues_repo_name": "john-waczak/SciML_SHO", "max_issues_repo_head_hexsha": "180d46e9755e6a70f281086a373e183b57544275", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "old_news/john/hamiltonian_nn.jl", "max_forks_repo_name": "john-waczak/SciML_SHO", "max_forks_repo_head_hexsha": "180d46e9755e6a70f281086a373e183b57544275", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7228915663, "max_line_length": 124, "alphanum_fraction": 0.5829798515, "num_tokens": 1429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7889986049026583}}
{"text": "\n# Using Base modules.\nusing Random\n\n# Load a plotting library.\nusing Plots\n\n# Load the distributions library.\nusing Distributions\n\n\n# Set the true probability of heads in a coin.\np_true = 0.5\n\n# Iterate from having seen 0 observations to 100 observations.\nNs = 0:100;\n\n\n# Draw data from a Bernoulli distribution, i.e. draw heads or tails.\nRandom.seed!(12)\ndata = rand(Bernoulli(p_true), last(Ns))\n\n# Here's what the first five coin flips look like:\ndata[1:5]\n\n\n# Our prior belief about the probability of heads in a coin toss.\nprior_belief = Beta(1, 1);\n\n\n# Import StatsPlots for animating purposes.\nusing StatsPlots\n\n# Make an animation.\nanimation = @gif for (i, N) in enumerate(Ns)\n\n    # Count the number of heads and tails.\n    heads = sum(data[1:i-1])\n    tails = N - heads\n    \n    # Update our prior belief in closed form (this is possible because we use a conjugate prior).\n    updated_belief = Beta(prior_belief.α + heads, prior_belief.β + tails)\n\n    # Plotting\n    plot(updated_belief, \n        size = (500, 250), \n        title = \"Updated belief after $N observations\",\n        xlabel = \"probability of heads\", \n        ylabel = \"\", \n        legend = nothing,\n        xlim = (0,1),\n        fill=0, α=0.3, w=3)\n    vline!([p_true])\nend\n\n\n# Load Turing and MCMCChains.\nusing Turing, MCMCChains\n\n# Load the distributions library.\nusing Distributions\n\n# Load StatsPlots for density plots.\nusing StatsPlots\n\n\n@model coinflip(y) = begin\n    \n    # Our prior belief about the probability of heads in a coin.\n    p ~ Beta(1, 1)\n    \n    # The number of observations.\n    N = length(y)\n    for n in 1:N\n        # Heads or tails of a coin are drawn from a Bernoulli distribution.\n        y[n] ~ Bernoulli(p)\n    end\nend;\n\n\n# Settings of the Hamiltonian Monte Carlo (HMC) sampler.\niterations = 1000\nϵ = 0.05\nτ = 10\n\n# Start sampling.\nchain = sample(coinflip(data), HMC(ϵ, τ), iterations, progress=false);\n\n\n# Construct summary of the sampling process for the parameter p, i.e. the probability of heads in a coin.\np_summary = chain[:p]\nplot(p_summary, seriestype = :histogram)\n\n\n# Compute the posterior distribution in closed-form.\nN = length(data)\nheads = sum(data)\nupdated_belief = Beta(prior_belief.α + heads, prior_belief.β + N - heads)\n\n# Visualize a blue density plot of the approximate posterior distribution using HMC (see Chain 1 in the legend).\np = plot(p_summary, seriestype = :density, xlim = (0,1), legend = :best, w = 2, c = :blue)\n\n# Visualize a green density plot of posterior distribution in closed-form.\nplot!(p, range(0, stop = 1, length = 100), pdf.(Ref(updated_belief), range(0, stop = 1, length = 100)), \n        xlabel = \"probability of heads\", ylabel = \"\", title = \"\", xlim = (0,1), label = \"Closed-form\",\n        fill=0, α=0.3, w=3, c = :lightgreen)\n\n# Visualize the true probability of heads in red.\nvline!(p, [p_true], label = \"True probability\", c = :red)\n\n\nisdefined(Main, :TuringTutorials) && Main.TuringTutorials.tutorial_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])\n\n", "meta": {"hexsha": "3845d8b6d984874a1a040b5e24f9a9a088505a73", "size": 3001, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/00-introduction/00_introduction.jl", "max_stars_repo_name": "leachim/TuringTutorials", "max_stars_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/00-introduction/00_introduction.jl", "max_issues_repo_name": "leachim/TuringTutorials", "max_issues_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/00-introduction/00_introduction.jl", "max_forks_repo_name": "leachim/TuringTutorials", "max_forks_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-25T15:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-25T15:43:34.000Z", "avg_line_length": 26.3245614035, "max_line_length": 112, "alphanum_fraction": 0.6797734089, "num_tokens": 837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582535657919, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7889986049026582}}
{"text": "####################\n# Helper Constants #\n####################\n\n# Intermidiate calculations calculations\nconst ECC2 = WGS84_f * (2.0 - WGS84_f) # Square of eccentricisty\n\n##############\n# Geocentric #\n##############\n\nexport sGEOCtoECEF\n\"\"\"\nConvert geocentric position to equivalent Earth-fixed position.\n\nArguments:\n- `geoc::Array{<:Real, 1}`: Geocentric coordinates (lon, lat, altitude) [rad] / [deg]\n- `use_degrees:Bool`: If `true` interpret input as being in degrees.\n\nReturns:\n- `ecef::Array{<:Real, 1}`: Earth-fixed coordinates [m]\n\"\"\"\nfunction sGEOCtoECEF(geoc::Array{<:Real, 1} ; use_degrees::Bool=false)\n    # Extract lat and lon\n    lon = geoc[1]\n    lat = geoc[2]\n    \n    # Handle non-explict use-degrees\n    if length(geoc) == 3\n        alt = geoc[3]\n    else\n        alt = 0.0\n    end\n\n    # Convert input to radians\n    if use_degrees\n        lat = lat*pi/180.0\n        lon = lon*pi/180.0\n    end\n\n    # Check validity of input\n    if lat < -pi/2 || lat > pi/2\n        throw(ArgumentError(\"Lattiude, $lat, out of range. Must be between -90 and 90 degrees.\"))\n    end\n\n    # Compute Earth fixed coordinates\n    r       = WGS84_a + alt\n    x = r*cos(lat)*cos(lon)\n    y = r*cos(lat)*sin(lon)\n    z = r*sin(lat)\n    \n    return [x, y, z]\nend\n\nexport sECEFtoGEOC\n\"\"\"\nConvert Earth-fixed position to geocentric location.\n\nArguments:\n- `ecef::Array{<:Real, 1}`: Earth-fixed coordinated [m]\n- `use_degrees:Bool`: If `true` returns result in units of degrees\n\nReturns:\n- `geoc`: Geocentric coordinates (lon, lat, altitude) [rad] / [deg]\n\"\"\"\nfunction sECEFtoGEOC(ecef::Array{<:Real, 1} ; use_degrees::Bool=false)\n    # Expand ECEF coordinates\n    x, y, z = ecef\n\n    # Compute geocentric coordinates\n    lat = atan(z, sqrt(x*x + y*y))\n    lon = atan(y, x)\n    alt = sqrt(x*x + y*y + z*z) - WGS84_a\n\n    # Convert output to degrees\n    if use_degrees\n        lat = lat*180.0/pi\n        lon = lon*180.0/pi\n    end\n\n    return [lon, lat, alt]\nend\n\n########################\n# Geodetic Convertions #\n########################\n\nexport sGEODtoECEF\n\"\"\"\nConvert geodetic position to equivalent Earth-fixed position.\n\nArguments:\n- `geod::Array{<:Real, 1}`: Geodetic coordinates (lon, lat, altitude) [rad] / [deg]\n- `use_degrees:Bool`: If `true` interpret input as being in degrees.\n\nReturns:\n- `ecef::Array{<:Real, 1}`: Earth-fixed coordinates [m]\n\"\"\"\nfunction sGEODtoECEF(geod::Array{<:Real, 1} ; use_degrees::Bool=false)\n    # Extract lat and lon\n    lon = geod[1]\n    lat = geod[2]\n    \n    # Handle non-explict use-degrees\n    if length(geod) == 3\n        alt = geod[3]\n    else\n        alt = 0.0\n    end\n\n    # Convert input to radians\n    if use_degrees\n        lat = lat*pi/180.0\n        lon = lon*pi/180.0\n    end\n\n    # Check validity of input\n    if lat < -pi/2 || lat > pi/2\n        throw(ArgumentError(\"Lattiude, $lat, out of range. Must be between -90 and 90 degrees.\"))\n    end\n\n    # Compute Earth-fixed position vector\n    N = WGS84_a / sqrt(1.0 - ECC2*sin(lat)^2)\n    x =           (N+alt)*cos(lat)*cos(lon)\n    y =           (N+alt)*cos(lat)*sin(lon)\n    z =  ((1.0-ECC2)*N+alt)*sin(lat)\n    \n    return [x, y, z]\nend\n\nexport sECEFtoGEOD\n\"\"\"\nConvert geodetic coordinaties to Earth-fixed position\n\nArguments:\n- `ecef::Array{<:Real, 1}`: Earth-fixed position [m]\n- `use_degrees:Bool`: If `true` returns result in units of degrees\n\nReturns:\n- `geod::Array{<:Real, 1}`: Geocentric coordinates (lon, lat, altitude) [rad] / [deg]\n\"\"\"\nfunction sECEFtoGEOD(ecef::Array{<:Real, 1} ; use_degrees::Bool=false)\n    # Expand ECEF coordinates\n    x, y, z = ecef\n\n    # Compute intermediate quantities\n    epsilon  = eps(Float64) * 1.0e3 * WGS84_a # Convergence requirement as function of machine precision\n    rho2 = x^2 + y^2                      # Square of the distance from the z-axis\n    dz   = ECC2 * z\n    N    = 0.0\n\n    # Iteratively compute refine coordinates\n    while true\n        zdz    = z + dz\n        Nh     = sqrt(rho2 + zdz^2)\n        sinphi = zdz / Nh\n        N      = WGS84_a / sqrt(1.0 - ECC2 * sinphi^2)\n        dz_new = N * ECC2 * sinphi\n\n        # Check convergence requirement\n        if abs(dz - dz_new) < epsilon\n            break\n        end\n\n        dz = dz_new\n    end\n\n    # Extract geodetic coordinates\n    zdz = z + dz\n    lat = atan(zdz, sqrt(rho2))\n    lon = atan(y, x)\n    alt = sqrt(rho2 + zdz^2) - N\n\n    # Convert output to degrees\n    if use_degrees\n        lat = lat*180.0/pi\n        lon = lon*180.0/pi\n    end\n\n    return [lon, lat, alt]\nend\n\n#######\n# ENZ #\n#######\n\nexport rECEFtoENZ\n\"\"\"\nCompute the rotation matrix from the Earth-fixed to the East-North-Up\ncoorindate basis.\n\nArguments:\n- `station_ecef::Array{<:Real, 1}`: Earth-fixed cartesian station coordinates\n- `conversion::Bool`: Conversion type to use. Can be \"geocentric\" or \"geodetic\"\n\nReturns:\n- `E::Array{Real, 2}`: Topocentric rotation matrix\n\"\"\"\nfunction rECEFtoENZ(ecef::Array{<:Real, 1} ; conversion::String=\"geodetic\")   \n    if length(ecef) < 3\n        throw(ArgumentError(\"Input coordinates must be length 3.\"))\n    end\n\n    # Compute Station Lat-Lon-Altitude\n    if conversion == \"geodetic\"\n        lon, lat, = sECEFtoGEOD(ecef, use_degrees=false)\n    elseif conversion == \"geocentric\"\n        lon, lat, = sECEFtoGEOC(ecef, use_degrees=false)\n    else\n        throw(ArgumentError(\"Unknown conversion method: $conversion\"))\n    end\n\n    # Compute ENZ basis vectors\n    eE = [-sin(lon) ; cos(lon) ; 0]\n    eN = [-sin(lat)*cos(lon) ; -sin(lat)*sin(lon) ; cos(lat)]\n    eZ = [cos(lat)*cos(lon) ; cos(lat)*sin(lon) ; sin(lat)]\n\n    # Construct Rotation matrix\n    E = hcat(eE, eN, eZ)'\n\n    # Return Result\n    return E\nend\n\nexport rENZtoECEF\n\"\"\"\nCompute the rotation matrix from the Earth-fixed to the South-East-Zenith \ncoorindate basis.\n\nArguments:\n- `station_ecef::Array{<:Real, 1}`: Earth-fixed cartesian station coordinates\n- `conversion::Bool`: Conversion type to use. Can be \"geocentric\" or \"geodetic\"\n\nReturns:\n- `E::Array{Float64, 2}`: Topocentric rotation matrix\n\"\"\"\nfunction rENZtoECEF(ecef::Array{<:Real, 1} ; conversion::String=\"geodetic\")\n    # Check input coordinates\n    if length(ecef) < 3\n        throw(ArgumentError(\"Input coordinates must be length 3.\"))\n    end\n\n    return rECEFtoENZ(ecef, conversion=conversion)'\nend\n\nexport sECEFtoENZ\n\"\"\"\nCompute the coordinates of an object in the topocentric frame of an\nEarth-fixed frame\n\nArguments:\n- `station_ecef::Array{<:Real, 1}`: Earth-fixed cartesian station coordinates\n- `ecef::Array{<:Real, 1}`: Coordinates of the object in Earth-fixed station\n- `conversion::Bool`: Conversion type to use. Can be \"geocentric\" or \"geodetic\"\n\nReturns:\n- `E::Array{Float64, 2}`: Topocentric rotation matrix\n\"\"\"\nfunction sECEFtoENZ(station_ecef::Array{<:Real, 1}, ecef::Array{<:Real, 1} ; conversion::String=\"geodetic\")\n    # Check input sizes\n    if length(ecef) < 3\n        throw(ArgumentError(\"Input ecef state must be at least length 3.\"))\n    end\n\n    if length(station_ecef) < 3\n        throw(ArgumentError(\"Input station coordinates must be length 3.\"))\n    end\n\n    # Compute ENZ Rotation matrix\n    E = rECEFtoENZ(station_ecef, conversion=conversion)\n\n    # Transform range\n    range_ecef = ecef[1:3] - station_ecef\n    range_enz  = E * range_ecef\n\n    # Transform range-rate (if necessary)\n    if length(ecef) == 6\n        range_rate_ecef = ecef[4:6]\n        range_rate_enz  = E * range_rate_ecef\n    end\n\n    # Return\n    if length(ecef) == 6\n        sat_enz = vcat(range_enz, range_rate_enz)\n    else\n        sat_enz = range_enz\n    end\n    \n    return sat_enz\nend\n\nexport sENZtoECEF\n\"\"\"\nCompute the coordinates of an object in the topocentric frame of an\nEarth-fixed frame\n\nArguments:\n- `station_ecef::Array{<:Real, 1}`: Earth-fixed cartesian station coordinates\n- `sez::Array{<:Real, 1}`: SEZ coordinates of the object\n- `conversion::Bool`: Conversion type to use. Can be \"geocentric\" or \"geodetic\"\n\nReturns:\n- `E::Array{Float64, 2}`: Topocentric rotation matrix\n\"\"\"\nfunction sENZtoECEF(station_ecef::Array{<:Real, 1}, enz::Array{<:Real, 1} ; conversion::String=\"geodetic\")\n    # Check input sizes\n    if length(enz) < 3\n        throw(ArgumentError(\"Input ENZ state must be at least length 3.\"))\n    end\n\n    if length(station_ecef) < 3\n        throw(ArgumentError(\"Input station coordinates must be length 3.\"))\n    end\n\n    # Compute ENZ Rotation matrix\n    E = rENZtoECEF(station_ecef, conversion=conversion)\n\n    # Transform range\n    range_enz  = enz[1:3]\n    range_ecef = E * range_enz\n\n    # Transform range-rate (if necessary)\n    if length(enz) == 6\n        range_rate_enz  = enz[4:6]\n        range_rate_ecef = E * range_rate_enz\n    end\n\n    # Return\n    if length(enz) == 6\n        sat_ecef = vcat(range_ecef + station_ecef, range_rate_ecef)\n    else\n        sat_ecef = range_ecef + station_ecef\n    end\n    \n    return sat_ecef\nend\n\n#######\n# SEZ #\n#######\n\nexport rECEFtoSEZ\n\"\"\"\nCompute the rotation matrix from the Earth-fixed to the South-East-Zenith \ncoorindate basis.\n\nArguments:\n- `station_ecef::Array{<:Real, 1}`: Earth-fixed cartesian station coordinates\n- `conversion::Bool`: Conversion type to use. Can be \"geocentric\" or \"geodetic\"\n\nReturns:\n- `E::Array{Float64, 2}`: Topocentric rotation matrix\n\"\"\"\nfunction rECEFtoSEZ(ecef::Array{<:Real, 1} ; conversion::String=\"geodetic\")    \n    if length(ecef) < 3\n        throw(ArgumentError(\"Input coordinates must be length 3.\"))\n    end\n\n    # Compute Station Lat-Lon-Altitude\n    if conversion == \"geodetic\"\n        lon, lat, = sECEFtoGEOD(ecef, use_degrees=false)\n    elseif conversion == \"geocentric\"\n        lon, lat, = sECEFtoGEOC(ecef, use_degrees=false)\n    else\n        throw(ArgumentError(\"Unknown conversion method: $conversion\"))\n    end\n\n    # Compute SEZ basis vectors\n    eS = [sin(lat)*cos(lon) ; sin(lat)*sin(lon) ; -cos(lat)]\n    eE = [-sin(lon) ; cos(lon) ; 0]\n    eZ = [cos(lat)*cos(lon) ; cos(lat)*sin(lon) ; sin(lat)]\n\n    # Construct Rotation matrix\n    E = hcat(eS, eE, eZ)'\n\n    # Return Result\n    return E\nend\n\n\nexport rSEZtoECEF\n\"\"\"\nCompute the rotation matrix from the Earth-fixed to the South-East-Zenith \ncoorindate basis.\n\nArguments:\n- `station_ecef::Array{<:Real, 1}`: Earth-fixed cartesian station coordinates\n- `conversion::Bool`: Conversion type to use. Can be \"geocentric\" or \"geodetic\"\n\nReturns:\n- `E::Array{Float64, 2}`: Topocentric rotation matrix\n\"\"\"\nfunction rSEZtoECEF(ecef::Array{<:Real, 1} ; conversion::String=\"geodetic\")\n    # Check input coordinates\n    if length(ecef) < 3\n        throw(ArgumentError(\"Input coordinates must be length 3.\"))\n    end\n\n    return rECEFtoSEZ(ecef, conversion=conversion)'\nend\n\n\nexport sECEFtoSEZ\n\"\"\"\nCompute the coordinates of an object in the topocentric frame of an\nEarth-fixed frame\n\nArguments:\n- `station_ecef::Array{<:Real, 1}`: Earth-fixed cartesian station coordinates\n- `ecef::Array{<:Real, 1}`: Coordinates of the object in Earth-fixed station\n- `conversion::Bool`: Conversion type to use. Can be \"geocentric\" or \"geodetic\"\n\nReturns:\n- `E::Array{Float64, 2}`: Topocentric rotation matrix\n\"\"\"\nfunction sECEFtoSEZ(station_ecef::Array{<:Real, 1}, ecef::Array{<:Real, 1} ; conversion::String=\"geodetic\")    \n    # Check input sizes\n    if length(ecef) < 3\n        throw(ArgumentError(\"Input ecef state must be at least length 3.\"))\n    end\n\n    if length(station_ecef) < 3\n        throw(ArgumentError(\"Input station coordinates must be length 3.\"))\n    end\n\n    # Construct SEZ Rotation matrix\n    E = rECEFtoSEZ(station_ecef, conversion=conversion)\n\n    # Transform range\n    range_ecef = ecef[1:3] - station_ecef\n    range_sez  = E * range_ecef\n\n    # Transform range-rate (if necessary)\n    if length(ecef) == 6\n        range_rate_ecef = ecef[4:6]\n        range_rate_sez  = E * range_rate_ecef\n    end\n\n    # Return\n    if length(ecef) == 6\n        sez = vcat(range_sez, range_rate_sez)\n    else\n        sez = range_sez\n    end\n    \n    return sez\nend\n\nexport sSEZtoECEF\n\"\"\"\nCompute the coordinates of an object in the topocentric frame of an\nEarth-fixed frame\n\nArguments:\n- `station_ecef::Array{<:Real, 1}`: Earth-fixed cartesian station coordinates\n- `sez::Array{<:Real, 1}`: SEZ coordinates of the object\n- `conversion::Bool`: Conversion type to use. Can be \"geocentric\" or \"geodetic\"\n\nReturns:\n- `E::Array{Float64, 2}`: Topocentric rotation matrix\n\"\"\"\nfunction sSEZtoECEF(station_ecef::Array{<:Real, 1}, sez::Array{<:Real, 1} ; conversion::String=\"geodetic\")\n    # Check input sizes\n    if length(sez) < 3\n        throw(ArgumentError(\"Input SEZ state must be at least length 3.\"))\n    end\n\n    if length(station_ecef) < 3\n        throw(ArgumentError(\"Input station coordinates must be length 3.\"))\n    end\n\n    # Compute ENZ Rotation matrix\n    E = rSEZtoECEF(station_ecef, conversion=conversion)\n\n    # Transform range\n    range_sez  = sez[1:3]\n    range_ecef = E * range_sez\n\n    # Transform range-rate (if necessary)\n    if length(sez) >= 6\n        range_rate_sez  = sez[4:6]\n        range_rate_ecef = E * range_rate_sez\n    end\n\n    # Return\n    if length(sez) >= 6\n        sat_ecef = vcat(range_ecef + station_ecef, range_rate_ecef)\n    else\n        sat_ecef = range_ecef + station_ecef\n    end\n    \n    return sat_ecef\nend\n\n###############\n# Topocentric #\n###############\n\nexport sENZtoAZEL\n\"\"\"\nConvert East-North-Zenith topocentric state to azimuth, elevation, and range.\n\nArguments:\n- `x::Array{<:Real, 1}`: East-North-Up state\n- `use_degrees:Bool`: If `true` returns result in units of degrees\n\nReturns:\n- `azel::Array{<:Real, 1}`: Azimuth, elevation and range [rad; rad; m]\n\"\"\"\nfunction sENZtoAZEL(x::Array{<:Real, 1} ; use_degrees::Bool=false)\n    # Check inputs\n    if !(length(x) == 3 || length(x) == 6)\n        throw(ArgumentError(\"Input ENZ state must be length 3 or 6.\"))\n    end\n\n    # Expand values\n    rE, rN, rZ = x[1], x[2], x[3]\n    \n    # Range\n    rho = norm(x[1:3])\n\n    # Elevation\n    el = atan(rZ, sqrt(rE^2 + rN^2))\n\n    # Azimuth\n    az = 0.0\n    if el != pi/2 # Non-singular azimuth \n        az = atan(rE, rN)\n        if az < 0\n            az += 2*pi\n        end\n    else # Azimuth may be singular for 90 deg elevation\n        if length(x) != 6\n            az = 0.0\n            # @warn \"Could not resolve singularity calculating azimuth.\"\n        else\n            # Use rate information to get azimuth if there is a singularity\n            # in the position\n            az = atan(x[4], x[5])\n        end\n    end\n\n    # Output\n    azel = [az ; el ; rho]\n\n    if use_degrees\n        azel[1] *= 180.0/pi\n        azel[2] *= 180.0/pi\n    end\n\n    # Process Rate information\n    if length(x) == 6\n        rdE, rdN, rdZ = x[4], x[5], x[6]\n\n        # Range-rate\n        rhod = dot(x[1:3], x[4:6])/rho\n\n        # Elevation-rate\n        eld = (rdZ - norm(x[4:6])*sin(el))/sqrt(rE^2 + rN^2)\n\n        # Azimuth-rate\n        azd = (rdE*rN - rdN*rE)/(rE^2 + rN^2)\n\n        # Output\n        azel_rate = [azd ; eld ; rhod]\n        if use_degrees\n            azel_rate[1] *= 180/pi\n            azel_rate[2] *= 180/pi\n        end\n    end\n\n    # Return\n    if length(x) == 6\n        return vcat(azel, azel_rate)\n    else\n        return azel\n    end\nend\n\nexport sSEZtoAZEL\n\"\"\"\nConvert South-East-Zenith topocentric state to azimuth, elevation, and range.\n\nArguments:\n- `x::Array{<:Real, 1}`: South-East-Zenith state\n- `use_degrees:Bool`: If `true` returns result in units of degrees\n\nReturns:\n- `azel::Array{<:Real, 1}`: Azimuth, elevation and range [rad; rad; m]\n\"\"\"\nfunction sSEZtoAZEL(x::Array{<:Real, 1} ; use_degrees::Bool=false)\n    # Check inputs\n    if !(length(x) == 3 || length(x) == 6)\n        throw(ArgumentError(\"Input rECEFtoSEZ state must be length 3 or 6.\"))\n    end\n\n    # Expand values\n    rS, rE, rZ = x[1], x[2], x[3]\n    \n    # Range\n    rho = norm(x[1:3])\n\n    # Elevation\n    el = atan(rZ, sqrt(rS^2 + rE^2))\n\n    # Azimuth\n    az = 0.0\n    if el != pi/2\n        az = atan(rE, -rS)\n        if az < 0\n            az += 2*pi\n        end\n    else\n        if length(x) != 6\n            az = 0.0\n            # @warn \"Could not resolve singularity calculating azimuth.\"\n        else\n            # Use rate information to get azimuth if there is a singularity\n            # in the position\n            az = atan(x[6], -x[5])\n        end\n    end\n\n    # Output\n    azel = [az ; el ; rho]\n\n    if use_degrees\n        azel[1] *= 180.0/pi\n        azel[2] *= 180.0/pi\n    end\n\n    # Process Rate information\n    if length(x) == 6\n        rdS, rdE, rdZ = x[4], x[5], x[6]\n\n        # Range-rate\n        rhod = dot(x[1:3], x[4:6])/rho\n\n        # Elevation-rate\n        eld = (rdZ - norm(x[4:6])*sin(el))/sqrt(rS^2 + rE^2)\n\n        # Azimuth-rate\n        azd = (rdS*rE - rdE*rS)/(rS^2 + rE^2)\n\n        # Output\n        azel_rate = [azd ; eld ; rhod]\n        if use_degrees\n            azel_rate[1] *= 180/pi\n            azel_rate[2] *= 180/pi\n        end\n    end\n\n    # Return\n    if length(x) == 6\n        return vcat(azel, azel_rate)\n    else\n        return azel\n    end\nend", "meta": {"hexsha": "944499254cb41c706e7d64f0ef127acd406518f1", "size": 16924, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/coordinates.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SatelliteDynamics.jl-0e7c1a32-1b9f-5532-88a4-e668712d6a4c", "max_stars_repo_head_hexsha": "8afaaf79609b6710fd433bb6d423f1b5af98a386", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-01-02T17:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:40:54.000Z", "max_issues_repo_path": "src/coordinates.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SatelliteDynamics.jl-0e7c1a32-1b9f-5532-88a4-e668712d6a4c", "max_issues_repo_head_hexsha": "8afaaf79609b6710fd433bb6d423f1b5af98a386", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-01-14T10:38:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-10T16:07:56.000Z", "max_forks_repo_path": "src/coordinates.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SatelliteDynamics.jl-0e7c1a32-1b9f-5532-88a4-e668712d6a4c", "max_forks_repo_head_hexsha": "8afaaf79609b6710fd433bb6d423f1b5af98a386", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-02-08T08:12:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-29T20:48:52.000Z", "avg_line_length": 25.6813353566, "max_line_length": 111, "alphanum_fraction": 0.6159300402, "num_tokens": 5347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806521, "lm_q2_score": 0.8479677641409289, "lm_q1q2_score": 0.788998599997046}}
{"text": "function derivative(f::Function, x::Array{T, 1}) where T <: AbstractFloat\n\n  n = length(f(x))\n  m = length(x)\n\n\te  = eps(T)^(1/3)*maximum(abs,[x;one(T)])\n  dh = Matrix{Float64}(I, m, m)*e\n\tderiv = Array{T}(undef,n,m)\n\n  for i = 1:m\n    deriv[:,i] = (-f(x+2*dh[:,i])+8*f(x+dh[:,i])-8*f(x-dh[:,i])+f(x-2*dh[:,i]))/(12*e)\n  end\n\n  return deriv\n\nend\n", "meta": {"hexsha": "54a4f71dc73c8ba1b6d6249adf618daf4ae1d126", "size": 346, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/derivative.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SolveDSGE.jl-00bf1f32-23ad-54cc-bf6e-3216db8a43a2", "max_stars_repo_head_hexsha": "ab3d113fd08cb569b44798588f369f3f6c642168", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2015-09-20T07:02:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:38:12.000Z", "max_issues_repo_path": "src/derivative.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SolveDSGE.jl-00bf1f32-23ad-54cc-bf6e-3216db8a43a2", "max_issues_repo_head_hexsha": "ab3d113fd08cb569b44798588f369f3f6c642168", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 53, "max_issues_repo_issues_event_min_datetime": "2017-03-03T15:53:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:41:07.000Z", "max_forks_repo_path": "src/derivative.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SolveDSGE.jl-00bf1f32-23ad-54cc-bf6e-3216db8a43a2", "max_forks_repo_head_hexsha": "ab3d113fd08cb569b44798588f369f3f6c642168", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2016-01-27T16:29:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-03T23:53:53.000Z", "avg_line_length": 20.3529411765, "max_line_length": 86, "alphanum_fraction": 0.5375722543, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7889985958132081}}
{"text": "function michaelis_menten_model(concentration, Vm, K)\n    (Vm * concentration) / (K + concentration)\nend\n\n# MicMen data is taken from the README of the NLReg.jl package: https://github.com/dmbates/NLreg.jl\n# 1st column is concentration and 2nd column is the Rate\nMicMenData = [\n    0.02 76;\n    0.02 47;\n    0.06 97;\n    0.06 107;\n    0.11 123;\n    0.11 139;\n    0.22 159;\n    0.22 152;\n    0.56 191;\n    0.56 201;\n    1.1  207;\n    1.1  200\n];\n\nMicMenConcentration = MicMenData[:, 1];\nMicMenRate = MicMenData[:, 2];\n\n# Fitness function takes a vector of Vm and K and calculates the RSS\nfunction mic_men_fitness(params)\n    Vm, K = params\n    yhat = Float64[michaelis_menten_model(c, Vm, K) for c in MicMenConcentration]\n    sumabs2(MicMenRate .- yhat)\nend\n\nusing BlackBoxOptim\nresult = bboptimize(mic_men_fitness; \n  SearchRange = (-1000.0, 1000.0), NumDimensions = 2, MaxSteps = 1e4)\nVm, K = best_candidate(result)\nRSS = best_fitness(result)\n\nprintln(\"NLReg.jl uses specific MicMen object and fit method to find:\")\nprintln(\"Vm = 212.684, K = 0.0641212, RSS = 1195.45\")\nprintln(\"\\nUsing BlackBoxOptim.jl we find:\")\nprintln(\"Vm = $(Vm), K = $(K), RSS = $(RSS)\")\n", "meta": {"hexsha": "685416262073ad64e5aeebfdbc1dd14a26843830", "size": 1162, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/nonlinear_regression_michaelis_menten.jl", "max_stars_repo_name": "devmotion/BlackBoxOptim.jl", "max_stars_repo_head_hexsha": "252b373da6571b209f82660839923add60eba34d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 322, "max_stars_repo_stars_event_min_datetime": "2015-02-15T19:35:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T07:03:29.000Z", "max_issues_repo_path": "examples/nonlinear_regression_michaelis_menten.jl", "max_issues_repo_name": "tpapp/BlackBoxOptim.jl", "max_issues_repo_head_hexsha": "b36833ef59966c16ed026dc9bc2e3c165c79c909", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 167, "max_issues_repo_issues_event_min_datetime": "2015-04-30T19:40:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T07:12:53.000Z", "max_forks_repo_path": "examples/nonlinear_regression_michaelis_menten.jl", "max_forks_repo_name": "tpapp/BlackBoxOptim.jl", "max_forks_repo_head_hexsha": "b36833ef59966c16ed026dc9bc2e3c165c79c909", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 66, "max_forks_repo_forks_event_min_datetime": "2015-05-05T20:23:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T15:30:29.000Z", "avg_line_length": 27.6666666667, "max_line_length": 99, "alphanum_fraction": 0.6772805508, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7889985926950385}}
{"text": "# Ridge Regression (Tikhonov regularization)\n\n#### auxiliary\n\nfunction lreg_chkdims(X::AbstractMatrix, Y::AbstractVecOrMat, trans::Bool)\n    mX, nX = size(X)\n    dX = ifelse(trans, mX, nX)\n    dY = ifelse(trans, nX, mX)\n    size(Y, 1) == dY || throw(DimensionMismatch(\"Dimensions of X and Y mismatch.\"))\n    return dX\nend\n\nlrsoltype(::AbstractVector{T}) where T = Vector{T}\nlrsoltype(::AbstractMatrix{T}) where T = Matrix{T}\n\n_vaug(X::AbstractMatrix{T}) where T = vcat(X, ones(T, 1, size(X,2)))::Matrix{T}\n_haug(X::AbstractMatrix{T}) where T = hcat(X, ones(T, size(X,1), 1))::Matrix{T}\n\n\n## linear least square\n\nfunction llsq(X::AbstractMatrix{T}, Y::AbstractVecOrMat{T};\n              trans::Bool=false, bias::Bool=true) where T<:AbstractFloat\n    if trans\n        mX, nX = size(X)\n        size(Y, 1) == nX || throw(DimensionMismatch(\"Dimensions of X and Y mismatch.\"))\n        mX <= nX || error(\"mX <= nX is required when trans is false.\")\n    else\n        mX, nX = size(X)\n        size(Y, 1) == mX || throw(DimensionMismatch(\"Dimensions of X and Y mismatch.\"))\n        mX >= nX || error(\"mX >= nX is required when trans is false.\")\n    end\n    _ridge(X, Y, zero(T), trans, bias)\nend\n\n## ridge regression\n\nfunction ridge(X::AbstractMatrix{T}, Y::AbstractVecOrMat{T}, r::Real;\n               trans::Bool=false, bias::Bool=true) where T<:AbstractFloat\n    lreg_chkdims(X, Y, trans)\n    r >= zero(r) || error(\"r must be non-negative.\")\n    _ridge(X, Y, convert(T, r), trans, bias)\nend\n\nfunction ridge(X::AbstractMatrix{T}, Y::AbstractVecOrMat{T}, r::AbstractVector{T};\n               trans::Bool=false, bias::Bool=true) where T<:AbstractFloat\n    d = lreg_chkdims(X, Y, trans)\n    length(r) == d || throw(DimensionMismatch(\"Incorrect length of r.\"))\n    _ridge(X, Y, r, trans, bias)\nend\n\nfunction ridge(X::AbstractMatrix{T}, Y::AbstractVecOrMat{T}, r::AbstractMatrix{T};\n               trans::Bool=false, bias::Bool=true) where T<:AbstractFloat\n    d = lreg_chkdims(X, Y, trans)\n    size(r) == (d, d) || throw(DimensionMismatch(\"Incorrect size of r.\"))\n    _ridge(X, Y, r, trans, bias)\nend\n\n## implementation\n\nfunction _ridge(X::AbstractMatrix{T}, Y::AbstractVecOrMat{T},\n                r::Union{Real, AbstractVecOrMat}, trans::Bool, bias::Bool) where T<:AbstractFloat\n    if bias\n        if trans\n            X_ = _vaug(X)\n            A = cholesky!(Hermitian(_ridge_reg!(X_ * transpose(X_), r, bias))) \\ (X_ * Y)\n        else\n            X_ = _haug(X)\n            A = cholesky!(Hermitian(_ridge_reg!(X_'X_, r, bias))) \\ (X_'Y)\n        end\n    else\n        if trans\n            A = cholesky!(Hermitian(_ridge_reg!(X * X', r, bias))) \\ (X * Y)\n        else\n            A = cholesky!(Hermitian(_ridge_reg!(X'X, r, bias))) \\ (X'Y)\n        end\n    end\n    return A::lrsoltype(Y)\nend\n\nfunction _ridge_reg!(Q::Matrix, r::Real, bias::Bool)\n    if r > zero(r)\n        n = size(Q, 1) - Int(bias)\n        for i = 1:n\n            @inbounds Q[i,i] += r\n        end\n    end\n    return Q\nend\n\nfunction _ridge_reg!(Q::AbstractMatrix, r::AbstractVector, bias::Bool)\n    n = size(Q, 1) - Int(bias)\n    @assert length(r) == n\n    for i = 1:n\n        @inbounds Q[i,i] += r[i]\n    end\n    return Q\nend\n\nfunction _ridge_reg!(Q::AbstractMatrix, r::AbstractMatrix, bias::Bool)\n    n = size(Q, 1) - Int(bias)\n    @assert size(r) == (n, n)\n    for j = 1:n, i = 1:n\n        @inbounds Q[i,j] += r[i,j]\n    end\n    return Q\nend\n", "meta": {"hexsha": "e4f06d5a7ea51b05bb6436130fd6f02586b7776f", "size": 3400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lreg.jl", "max_stars_repo_name": "zgornel/MultivariateStats.jl", "max_stars_repo_head_hexsha": "bbae611ae270c91cde36b3bd314411725c2c0e77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lreg.jl", "max_issues_repo_name": "zgornel/MultivariateStats.jl", "max_issues_repo_head_hexsha": "bbae611ae270c91cde36b3bd314411725c2c0e77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lreg.jl", "max_forks_repo_name": "zgornel/MultivariateStats.jl", "max_forks_repo_head_hexsha": "bbae611ae270c91cde36b3bd314411725c2c0e77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-22T09:38:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T09:38:33.000Z", "avg_line_length": 31.4814814815, "max_line_length": 97, "alphanum_fraction": 0.5935294118, "num_tokens": 1079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7889680784579276}}
{"text": "using Distributions, Plots, LaTeXStrings; pyplot()\n\nprior(lam) = pdf(TriangularDist(0, 10, 3), lam)\ndata = [2,1,0,0,1,0,2,2,5,2,4,0,3,2,5,0]\n\nlike(lam) = *([pdf(Poisson(lam),x) for x in data]...)\nposteriorUpToK(lam) = like(lam)*prior(lam)\n\ndelta = 10^-4.\nlamRange = 0:delta:10\nK = sum([posteriorUpToK(lam)*delta for lam in lamRange])\nposterior(lam) = posteriorUpToK(lam)/K\n\nbayesEstimate = sum([lam*posterior(lam)*delta for lam in lamRange])\nprintln(\"Bayes estimate: \",bayesEstimate)\n\nplot(lamRange, prior.(lamRange), \n\tc=:blue, label=\"Prior distribution\")\nplot!(lamRange, posterior.(lamRange), \n\tc=:red, label=\"Posterior distribution\", \n\txlims=(0, 10), ylims=(0, 1.2),\n\txlabel=L\"\\lambda\",ylabel=\"Density\")", "meta": {"hexsha": "83ab0d4285fda56afb2ec0818caef9c078492374", "size": 706, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5_chapter/bayesUnivariate.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "5_chapter/bayesUnivariate.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "5_chapter/bayesUnivariate.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 32.0909090909, "max_line_length": 67, "alphanum_fraction": 0.6940509915, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7889680758884077}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.4\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\tdist = TriangularDist(4,6,5)\n\tN = 10^6\n\tdata = rand(dist,N)\n\tyData=(data .- 5).^2\nend\n\n# ╔═╡ 0b18657a-1f96-11eb-0dbe-614426f96594\n(\"Mean: $(mean(yData)), Variance: $(var(data))\")\n\n# ╔═╡ 0b18a3f0-1f96-11eb-1f2b-0f12d42055fa\nbegin\n\tp1 = histogram(data, xlabel=\"x\", bins=80, normed=true, ylims=(0,1.1))\n\tp2 = histogram(yData, xlabel=\"y\", bins=80, normed=true, ylims=(0,15))\n\tplot(p1, p2, ylabel=\"Proportion\", size=(800, 400), legend=:none)\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.4\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═0b18657a-1f96-11eb-0dbe-614426f96594\n# ╠═0b18a3f0-1f96-11eb-1f2b-0f12d42055fa\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "0cf884c5ec9e032aa976fb8a1ae2a87489af0c11", "size": 1255, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.04.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.04.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.04.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.612244898, "max_line_length": 70, "alphanum_fraction": 0.7155378486, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765257642906, "lm_q2_score": 0.8633916152464017, "lm_q1q2_score": 0.7888606513923514}}
{"text": "module Example1\n\nexport Point\nstruct Point{T}\n    x::T\n    y::T\nend\n\nfunction Base. +(p::Point, q::Point)\n    Point(p.x+ q.x, p.y + q.y)\nend\n\nexport MPoint\nmutable struct MPoint{T}\n    x::T\n    y::T\nend\n\ngreet() = println(\"Hello World!\")\n\n################################################################\n\nexport Polynomial\nstruct Polynomial{T}\n    coeffs::Vector{T}\nend\n\nexport evaluate\nfunction evaluate(p::Polynomial,x)\n    sum(c * x^(i-1) for (i,c) in enumerate(p.coeffs))\nend\n\n\nfunction Base. +(p::Polynomial, q::Polynomial)\n    l = max(length(p.coeffs), length(q.coeffs))\n    rcoeffs = zeros(l)\n    for (i,c) in enumerate(p.coeffs)\n        rcoeffs[i] +=c\n    end\n    Polynomial(rcoeffs)\nend\n\nfunction Base. *(a, p::Polynomial)\n    Polynomial(map(x->a*x, p.coeffs)) \nend\n\n#Base .*(p::Polynomial,a) = a*p\n\nexport deriv\nfunction deriv(p::Polynomial)\n    Polynomial([(i-1) * c for (i,c) in enumerate(p.coeffs)][2::end])\nend\n\n\nend # module\n", "meta": {"hexsha": "dc6e2dc0e459e659d9288ffac5686bd2d6bede57", "size": 940, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Example1.jl", "max_stars_repo_name": "Seth-Kurankyi/Example1", "max_stars_repo_head_hexsha": "574b29c605fcf56fc9b864785a4fd1f4d453d645", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Example1.jl", "max_issues_repo_name": "Seth-Kurankyi/Example1", "max_issues_repo_head_hexsha": "574b29c605fcf56fc9b864785a4fd1f4d453d645", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Example1.jl", "max_forks_repo_name": "Seth-Kurankyi/Example1", "max_forks_repo_head_hexsha": "574b29c605fcf56fc9b864785a4fd1f4d453d645", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.7857142857, "max_line_length": 68, "alphanum_fraction": 0.5914893617, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159727, "lm_q2_score": 0.863391599428538, "lm_q1q2_score": 0.7888606430283038}}
{"text": "#=\n# Based on the file JacobiP.m from the book:\n# Nodal Discontinuous Galerkin Method - Hesthaven, Warburton\n#  https://link.springer.com/book/10.1007/978-0-387-72067-8\n=#\n\n# Evaluate Nth order Jacobi Polynomial of type (alpha,beta) at points x.\n# Note   : They are normalized to be orthonormal.\nfunction jacobi_polynomial(x, alpha::Int, beta::Int, N::Int)\n    PL = zeros(N+1,length(x));\n    \n    # Initial values P_0(x) and P_1(x)\n    gamma0 = 2^(alpha+beta+1)/(alpha+beta+1)*factorial(alpha)*\n                factorial(beta)/factorial(alpha+beta);\n    PL[1,:] = 1.0/sqrt(gamma0) .* ones(length(x));\n    if N==0\n        return PL[1,:];\n    end\n    gamma1 = (alpha+1)*(beta+1)/(alpha+beta+3) * gamma0;\n    PL[2,:] = ((alpha+beta+2)/(2*sqrt(gamma1))) .* x .* ones(length(x)) .+ (alpha-beta)/(2*sqrt(gamma1));\n    if N==1\n        return PL[2,:];\n    end\n    \n    # Higher orders are generated by this recurrence.\n    # P(i+1) = -(a(i-1)/a(i))P(i-1) + ((x-b(i))/a(i))P(i)\n    aold = 2/(2+alpha+beta)*sqrt((alpha+1)*(beta+1)/(alpha+beta+3));\n    for i=1:N-1\n      h1 = 2*i+alpha+beta;\n      anew = 2/(h1+2)*sqrt( (i+1)*(i+1+alpha+beta)*(i+1+alpha)*\n          (i+1+beta)/((h1+1)*(h1+3)));\n      bnew = - (alpha^2-beta^2)/(h1*(h1+2));\n      PL[i+2,:] = (-aold/anew) .* PL[i,:] + ((x.-bnew)./anew) .* PL[i+1,:];\n      aold =anew;\n    end;\n    \n    return PL[N+1,:];\nend\n\n# sqrt(N*(N+alpha+beta+1))*JacobiP(r(:),alpha+1,beta+1, N-1);\nfunction grad_jacobi_polynomial(x, alpha::Int, beta::Int, N::Int)\n    if N < 1\n        return zeros(size(x));\n    end\n    \n    return sqrt(N*(N+alpha+beta+1)) .* jacobi_polynomial(x, alpha+1, beta+1, N-1);\nend", "meta": {"hexsha": "4f0e8472861f3dce9830964d7e0466d859fe83f3", "size": 1635, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/jacobi_polynomial.jl", "max_stars_repo_name": "aa25desh/femshop", "max_stars_repo_head_hexsha": "8a75639ea0b7740d378b3f863bd6584f4cdd5ec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-10-06T16:09:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T20:56:15.000Z", "max_issues_repo_path": "src/jacobi_polynomial.jl", "max_issues_repo_name": "aa25desh/femshop", "max_issues_repo_head_hexsha": "8a75639ea0b7740d378b3f863bd6584f4cdd5ec1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-12-15T16:03:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-24T16:10:55.000Z", "max_forks_repo_path": "src/jacobi_polynomial.jl", "max_forks_repo_name": "aa25desh/femshop", "max_forks_repo_head_hexsha": "8a75639ea0b7740d378b3f863bd6584f4cdd5ec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-10T17:48:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-19T12:12:49.000Z", "avg_line_length": 34.7872340426, "max_line_length": 105, "alphanum_fraction": 0.5639143731, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768635777511, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7888442314346911}}
{"text": "#=\n    For this particular positions\n        r = [1 2; 3 5]\n    the expression below are exact solutions.\n\n    Check sagemath notebook for the proof.\n=#\nN = 2\nr = [1 2; 3 5]\n    \nusing SpecialFunctions, LinearAlgebra\nH_0 = [1 besselh.(0,sqrt(13)); besselh.(0,sqrt(13)) 1]\nH_m = [0 exp(-2im*atan(3,2))*besselh.(2,sqrt(13));\n            exp(-2im*atan(3,2))*besselh.(2,sqrt(13)) 0]\n\nH_p = [0 exp(+2im*atan(3,2))*besselh.(2,sqrt(13));\n    exp(+2im*atan(3,2))*besselh.(2,sqrt(13)) 0]\n\nK_exact = [H_0 H_p; H_m H_0]\n\n\n\n\n#=\n        Creating matrices individually\n=#\nlet\n    N = 2\n    r = [1 2; 3 5]\n    Dx = [r[j,1] - r[l,1] for j=1:N, l=1:N]\n    Dy = [r[j,2] - r[l,2] for j=1:N, l=1:N]\n    r_jl = sqrt.( Dx.^2 + Dy.^2  )\n    φ_jl = atan.(Dy, Dx)\n    \n    #Hankel functions\n    H0 = besselh.(0,r_jl)\n    H0[findall(  isnan.(H0) )] .= 0.0\n    H0[diagind(H0)] .= 1\n\n    Hp = exp.(+2*1im*φ_jl).*besselh.(2,r_jl)\n    Hp[diagind(Hp)] .= 0\n    Hm = exp.(-2*1im*φ_jl).*besselh.(2,r_jl)\n    Hm[diagind(Hm)] .= 0\n\n    K = [H0 Hp; Hm H0]\n    K .≈ K_exact\nend\n\n\n\n\n#=\n        Creating matrices generically\n=#\nlet\n    N = 2\n    r = [1 2; 3 5]\n    δ(x,y) = Int(==(x,y))\n    Dx = [r[j,1] - r[l,1] for j=1:N, l=1:N]\n    Dy = [r[j,2] - r[l,2] for j=1:N, l=1:N]\n    r_jl = sqrt.( Dx.^2 + Dy.^2  )\n    φ_jl = atan.(Dy, Dx)\n\n    H0 = besselh.(0,r_jl)\n    H2 = besselh.(2,r_jl)\n\n    A = []\n    α_range = β_range = [-1, +1]\n    for (α_idx, α) ∈ enumerate(α_range)\n        B = []\n        for (β_idx, β) ∈ enumerate(β_range)\n            term1 = I(N)*δ(α,β)\n            term2 = ones(N, N) - I(N)\n            \n            term3 = δ(α,β)*H0\n            term3[findall(isnan.(term3))] .= 0\n            term3[findall(isinf.(term3))] .= 0\n\n            term4 = (1 - δ(α,β))*exp.(2*α*im*φ_jl).*H2\n            term4[findall(isnan.(term4))] .= 0\n            \n            temp =  term1 + term2.*(term3 + term4 )\n\n            push!(B, temp)\n        end\n        push!(A, vcat(B[1:length(β_range)]...)  )\n    end\n\n    K = hcat(A[1:length(α_range)]...)\n    K .≈ K_exact\nend\n\n\n", "meta": {"hexsha": "91baa1bc86db77f7673c189fa1fa409e17ed8b41", "size": 2028, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/benchmarks/benchmark_2D_vetorial.jl", "max_stars_repo_name": "is-jow/CoupledDipoles.jl", "max_stars_repo_head_hexsha": "cb602d83e190ecfb2c9ed79cf90eecef8de284e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/benchmarks/benchmark_2D_vetorial.jl", "max_issues_repo_name": "is-jow/CoupledDipoles.jl", "max_issues_repo_head_hexsha": "cb602d83e190ecfb2c9ed79cf90eecef8de284e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-30T19:38:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T19:38:02.000Z", "max_forks_repo_path": "test/benchmarks/benchmark_2D_vetorial.jl", "max_forks_repo_name": "is-jow/CoupledDipoles.jl", "max_forks_repo_head_hexsha": "cb602d83e190ecfb2c9ed79cf90eecef8de284e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-30T18:46:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T18:46:40.000Z", "avg_line_length": 21.5744680851, "max_line_length": 55, "alphanum_fraction": 0.4807692308, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768604361741, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7888442268761144}}
{"text": "using FdeSolver\nusing Plots\n\n## inputs\ntSpan = [0, 25]        # [intial time, final time]\ny0 = [34, 6]           # initial values\nβ = [0.98, 0.99]       # order of derivatives\n\n## ODE model\n\npar = [0.55, 0.028, 0.84, 0.026] # model parameters\n\nfunction F(t, y, par)\n\n    α1 = par[1]      # growth rate of the prey population\n    β1 = par[2]      # rate of shrinkage relative to the product of the population sizes\n    γ = par[3]       # shrinkage rate of the predator population\n    δ = par[4]       # growth rate of the predator population as a factor of the product\n                     # of the population sizes\n\n    u = y[1]         # population size of the prey species at time t[n]\n    v = y[2]         # population size of the predator species at time t[n]\n\n    F1 = α1 .* u .- β1 .* u .* v\n    F2 = - γ .* v .+ δ .* u .* v\n\n    [F1, F2]\n\nend\n\n## Solution\nt, Yapp = FDEsolver(F, tSpan, y0, β, par)\n\n# plotting\nplot(t, Yapp, linewidth = 5, title = \"Solution to LV model with 2 FDEs\",\n     xaxis = \"Time (t)\", yaxis = \"y(t)\", label = [\"Prey\" \"Predator\"])\nplot!(legendtitle = \"Population of\")\n", "meta": {"hexsha": "b6fbd130f989b6f50465528e72aae78b26ccab9b", "size": 1097, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/fLV.jl", "max_stars_repo_name": "FDE-Solver/FDE_Solver", "max_stars_repo_head_hexsha": "f0f06cff60d8bccbb61c588e0aba9df3bc4dd961", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-10-01T00:17:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T09:21:11.000Z", "max_issues_repo_path": "examples/fLV.jl", "max_issues_repo_name": "FDE-Solver/FDE_Solver", "max_issues_repo_head_hexsha": "f0f06cff60d8bccbb61c588e0aba9df3bc4dd961", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2021-09-13T10:53:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T08:00:50.000Z", "max_forks_repo_path": "examples/fLV.jl", "max_forks_repo_name": "moeinkh88/FDE_Solver", "max_forks_repo_head_hexsha": "f0f06cff60d8bccbb61c588e0aba9df3bc4dd961", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-10T12:59:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T12:59:53.000Z", "avg_line_length": 28.8684210526, "max_line_length": 88, "alphanum_fraction": 0.5761166819, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768604361742, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7888442249422737}}
{"text": "module Parameters\n\nexport FreeParameters, lognormal, ScaledLogitNormal\n\nusing Oceananigans.Architectures: CPU, arch_array, architecture\nusing Oceananigans.Utils: prettysummary\nusing Oceananigans.TurbulenceClosures: AbstractTurbulenceClosure\nusing Oceananigans.TurbulenceClosures: AbstractTimeDiscretization, ExplicitTimeDiscretization\n\nusing Printf\nusing Distributions\nusing DocStringExtensions\nusing LinearAlgebra\n\nusing SpecialFunctions: erfinv\nusing Distributions: AbstractRNG, ContinuousUnivariateDistribution\n\n#####\n##### Priors\n#####\n\n\"\"\"\n    lognormal(; mean, std)\n\nReturn `Lognormal` distribution parameterized by \nthe distribution `mean` and standard deviation `std`.\n\nNotes\n=====\n\nA variate `X` is `LogNormal` distributed if\n\n```math\n\\\\log(X) ∼ 𝒩(μ, σ²) ,\n```\n\nwhere ``𝒩(μ, σ²)`` is the `Normal` distribution with mean ``μ``\nand variance ``σ²``.\n\nThe `mean` and variance ``s²`` (where ``s`` is the standard\ndeviation or `std`) are related to the parameters ``μ``\nand ``σ²`` via\n\n```math\n m = \\\\exp(μ + σ² / 2),\n```\n```math\ns² = [\\\\exp(σ²) - 1] m².\n```\n\nThese formula allow us to calculate ``μ`` and ``σ`` given\n``m`` and ``s²``, since rearranging the formula for ``s²``\ngives\n\n```math\n\\\\exp(σ²) = m² / s² + 1\n```\n\nwhich then yields\n\n```math\nσ = \\\\sqrt{\\\\log(m² / s² + 1)}.\n```\n\nWe then find that\n\n```math\nμ = \\\\log(m) - σ² / 2 .\n```\n\nSee also\n[wikipedia](https://en.wikipedia.org/wiki/Log-normal_distribution#Generation_and_parameters).\n\"\"\"\nfunction lognormal(; mean, std)\n    k = std^2 / mean^2 + 1 # intermediate variable\n    σ = sqrt(log(k))\n    μ = log(mean) - σ^2 / 2\n    return LogNormal(μ, σ)\nend\n\nstruct ScaledLogitNormal{T} <: ContinuousUnivariateDistribution\n    μ :: T\n    σ :: T\n    lower_bound :: T\n    upper_bound :: T\n\n    ScaledLogitNormal{T}(μ, σ, L, U) where T = new{T}(T(μ), T(σ), T(L), T(U))\nend\n\n\"\"\"Return a logit-normally distributed variate given the normally-distributed variate `X`.\"\"\"\nnormal_to_scaled_logit_normal(L, U, X) = L + (U - L) / (1 + exp(X))\n\n\"\"\"Return a normally-distributed variate given the logit-normally distributed variate `Y`.\"\"\"\nscaled_logit_normal_to_normal(L, U, Y) = log((U - Y) / (Y - L))\n\nBase.rand(rng::AbstractRNG, d::ScaledLogitNormal) =\n    normal_to_scaled_logit_normal(d.lower_bound, d.upper_bound, rand(rng, Normal(d.μ, d.σ)))\n\nunit_normal_std(mass) = 1 / (2 * √2 * erfinv(mass))\n\n\"\"\"\n    ScaledLogitNormal([FT=Float64;] bounds=(0, 1), mass=0.5, interval=nothing, μ=nothing, σ=nothing)\n\nReturn a `ScaledLogitNormal` distribution with compact support within `bounds`.\n\n`interval` is an optional 2-element tuple or Array. When specified,\nthe parameters `μ` and `σ` of the underlying `Normal` distribution\nare calculated so that `mass` fraction of the probability density\nlies within `interval`.\n\nIf `interval` is not specified, then `μ=0` and `σ=1` by default.\n\nNotes\n=====\n\n`ScaledLogitNormal` is a four-parameter distribution\ngenerated by the transformation\n\n```math\nY = L + (U - L) / [1 + \\\\exp(X)],\n```\n\nof the normally-distributed variate ``X ∼ 𝒩(μ, σ)``. The four parameters\ngoverning the distribution of ``Y`` are thus\n\n- ``L``:  lower bound (0 for the `LogitNormal` distribution)\n- ``U``:  upper bound (1 for the `LogitNormal` distribution)\n- ``μ``:  mean of the underlying `Normal` distribution\n- ``σ²``: variance of the underlying `Normal` distribution\n\"\"\"\nfunction ScaledLogitNormal(FT=Float64; bounds=(0, 1), mass=0.5, interval=nothing, μ=nothing, σ=nothing)\n    L, U = bounds\n\n    if isnothing(interval) # use default μ=0 and σ=1 if not set\n        isnothing(μ) && (μ = 0)\n        isnothing(σ) && (σ = 1)\n\n    elseif !isnothing(interval) # try to compute μ and σ\n\n        Li, Ui = interval\n\n        # User friendliness\n        (!isnothing(μ) || !isnothing(σ)) && @warn \"Using interval and mass to determine μ and σ.\"\n        0 < mass < 1 || throw(ArgumentError(\"Mass must lie between 0 and 1.\"))\n        Li > L && Ui < U || throw(ArgumentError(\"Interval limits must lie between `bounds`.\"))\n\n        # Compute lower and upper limits of midspread in unconstrained space\n        #\n        # Note that the _lower_ bound in unconstrained space is associated with the\n        # _upper_ bound in constrained space, and vice versa.\n        L̃i = scaled_logit_normal_to_normal(L, U, Ui)\n        Ũi = scaled_logit_normal_to_normal(L, U, Li)\n        \n        μ = (Ũi + L̃i) / 2\n\n        # Note that the mass beneath a half-width `δ` of the\n        # standard Normal distribution is\n        #\n        # mass = 2 / √(2π) ∫₀ᵟ exp(-x^2 / 2) dx\n        #      = erf(δ / √2)\n        #\n        # For an `interval = (Ũi, L̃i)` of the normal distribution,\n        # the non-dimensional half-width is\n        #\n        # δ = (Ũi - L̃i) / 2σ\n        #\n        # where σ is the distribution's standard deviation.\n        # We then find\n        #\n        # erfinv(mass) = (Ũi - L̃i) / (2 * √2 * σ) ,\n        #\n        # and rearranging to solve for σ yields\n        # \n        σ = (Ũi - L̃i) / (2 * √2 * erfinv(mass))\n    end\n\n    return ScaledLogitNormal{FT}(μ, σ, L, U)\nend\n\n# Calculate the prior in unconstrained space given a prior in constrained space\nunconstrained_prior(Π::LogNormal)         = Normal(Π.μ / abs(Π.μ), Π.σ / abs(Π.μ))\nunconstrained_prior(Π::Normal)            = Normal(0, 1)\nunconstrained_prior(Π::ScaledLogitNormal) = Normal(Π.μ, Π.σ)\n\n\"\"\"\n    transform_to_unconstrained(Π, Y)\n\nTransform the \"constrained\" (physical) variate `Y` into it's\nunconstrained (normally-distributed) counterpart `X` through the\nforward map associated with `Π`.\n\nIf some mapping between ``Y`` and the normally-distributed ``X`` is\ndefined via\n\n```math\nY = g(X).\n```\n\nThen `transform_to_unconstrained` is the inverse ``X = g^{-1}(Y)``.\nThe change of variables ``g(X)`` determines the distribution `Π` of `Y`.\n\nExample\n=======\n\nThe logarithm of a `LogNormal(μ, σ)` distributed variate is normally-distributed,\nsuch that the forward trasform ``f ≡ \\\\exp``,\n\n```math\nY = \\\\exp(X),\n```\n\nand the inverse trasnform is the natural logarithm ``f^{-1} ≡ \\\\log``,\n\n```math\n\\\\log(Y) = X ∼ 𝒩(μ, σ).\n```\n\"\"\"\ntransform_to_unconstrained(Π::Normal,    Y) = (Y - Π.μ) / Π.σ\ntransform_to_unconstrained(Π::LogNormal, Y) = log(Y^(1 / abs(Π.μ))) # log(Y) / abs(Π.μ)\n\ntransform_to_unconstrained(Π::ScaledLogitNormal, Y) =\n    scaled_logit_normal_to_normal(Π.lower_bound, Π.upper_bound, Y)\n\n\"\"\"\n    transform_to_constrained(Π, X)\n\nTransform an \"unconstrained\", normally-distributed variate `X`\nto \"constrained\" (physical) space via the map associated with\nthe distribution `Π` of `Y`.\n\"\"\"\ntransform_to_constrained(Π::Normal, X)    = X * Π.σ + Π.μ\ntransform_to_constrained(Π::LogNormal, X) = exp(X * abs(Π.μ))\ntransform_to_constrained(Π::ScaledLogitNormal, X) =\n    normal_to_scaled_logit_normal(Π.lower_bound, Π.upper_bound, X)\n\n# Convenience vectorized version\ntransform_to_constrained(priors::NamedTuple, X::AbstractVector) =\n    NamedTuple(name => transform_to_constrained(priors[name], X[i])\n               for (i, name) in enumerate(keys(priors)))\n\n# Convenience matrixized version assuming particles vary on 2nd dimension\ntransform_to_constrained(priors::NamedTuple, X::AbstractMatrix) =\n    [transform_to_constrained(priors, X[:, k]) for k = 1:size(X, 2)]\n\nfunction inverse_covariance_transform(Π, X, covariance)\n    diag = [covariance_transform_diagonal(Π[i], X[i]) for i=1:length(Π)]\n    dT = Diagonal(diag)\n    return dT * covariance * dT'\nend\n\ncovariance_transform_diagonal(::LogNormal, X) = exp(X)\ncovariance_transform_diagonal(::Normal, X)    = 1\ncovariance_transform_diagonal(Π::ScaledLogitNormal, X) = - (Π.upper_bound - Π.lower_bound) * exp(X) / (1 + exp(X))^2\n\n#####\n##### Free parameters\n#####\n\n\"\"\"\n    struct FreeParameters{N, P, D}\n\nA container for free parameters that includes the parameter names and their\ncorresponding prior distributions.\n\n$(FIELDS)\n\"\"\"\nstruct FreeParameters{N, P, D}\n    \"free parameters\"\n    names :: N\n    \"prior distributions for free parameters\"\n    priors :: P\n    \"dependent parameters\"\n    dependent_parameters :: D\nend\n\n\"\"\"\n    FreeParameters(priors; names = Symbol.(keys(priors)), dependent_parameters=NamedTuple())\n\nReturn named `FreeParameters` with priors. Free parameter `names` are inferred from\nthe keys of `priors` if not provided. Optionally, `dependent_parameters` are prescribed\nas a `NamedTuple` whose keys are the names of \"additional\" parameters, and whose values\nare functions that return those parameters given a vector of free parameters in `names`.\n\nExample\n=======\n\n```jldoctest\njulia> using Distributions, ParameterEstimocean\n\njulia> priors = (ν = Normal(1e-4, 1e-5), κ = Normal(1e-3, 1e-5))\n(ν = Normal{Float64}(μ=0.0001, σ=1.0e-5), κ = Normal{Float64}(μ=0.001, σ=1.0e-5))\n\njulia> free_parameters = FreeParameters(priors)\nFreeParameters with 2 parameters\n├── names: (:ν, :κ)\n├── priors: Dict{Symbol, Any}\n│   ├── ν => Normal{Float64}(μ=0.0001, σ=1.0e-5)\n│   └── κ => Normal{Float64}(μ=0.001, σ=1.0e-5)\n└── dependent parameters: Dict{Symbol, Any}\n\njulia> c(p) = p.ν + p.κ # compute a third dependent parameter `c` as a function of `ν` and `κ`\nc (generic function with 1 method)\n\njulia> free_parameters_with_a_dependent = FreeParameters(priors, dependent_parameters=(; c))\nFreeParameters with 2 parameters and 1 dependent parameter\n├── names: (:ν, :κ)\n├── priors: Dict{Symbol, Any}\n│   ├── ν => Normal{Float64}(μ=0.0001, σ=1.0e-5)\n│   └── κ => Normal{Float64}(μ=0.001, σ=1.0e-5)\n└── dependent parameters: Dict{Symbol, Any}\n    └── c => c (generic function with 1 method)\n```\n\"\"\"\nfunction FreeParameters(priors; names = Symbol.(keys(priors)), dependent_parameters=NamedTuple())\n    priors = NamedTuple(name => priors[name] for name in names)\n    return FreeParameters(Tuple(names), priors, dependent_parameters)\nend\n\nBase.summary(fp::FreeParameters) = \"$(fp.names)\"\n\nfunction prior_show(io, priors, name, prefix, width)\n    print(io, @sprintf(\"%s %s => \", prefix, lpad(name, width, \" \")))\n    show(io, priors[name])\n    return nothing\nend\n\nfunction dependent_parameter_show(io, dependent_parameters, name, prefix, width)\n    print(io, @sprintf(\"%s %s => \", prefix, lpad(name, width, \" \")))\n    print(io, prettysummary(dependent_parameters[Symbol(name)]))\n    return nothing\nend\n\nparameter_str(N) = N>1 ? \"parameters\" : \"parameter\"\n\nfunction Base.show(io::IO, p::FreeParameters)\n    Np, Nd = length(p), length(p.dependent_parameters)\n\n    free_parameters_summary = \"FreeParameters with $Np \" * parameter_str(Np)\n\n    title = Nd > 0 ?\n            free_parameters_summary * \" and $Nd dependent \" * parameter_str(Nd) : \n            free_parameters_summary\n\n    print(io, title, '\\n',\n              \"├── names: $(p.names)\", '\\n',\n              \"├── priors: Dict{Symbol, Any}\")\n\n    maximum_name_length = maximum([length(string(name)) for name in p.names]) \n\n    for (i, name) in enumerate(p.names)\n        prefix = i == length(p.names) ? \"│   └──\" : \"│   ├──\"\n        print(io, '\\n')\n        prior_show(io, p.priors, name, prefix, maximum_name_length)\n    end\n    \n    print(io, '\\n')\n\n    print(io, \"└── dependent parameters: Dict{Symbol, Any}\")\n\n    if !isempty(p.dependent_parameters)\n        maximum_name_length = maximum([length(string(name)) for name in p.dependent_parameters]) \n\n        for (i, name) in enumerate(p.dependent_parameters)\n            prefix = i == length(p.dependent_parameters) ? \"    └──\" : \"    ├──\"\n            print(io, '\\n')\n            dependent_parameter_show(io, p.dependent_parameters, name, prefix, maximum_name_length)\n        end\n    end\n\n    return nothing\nend\n\nBase.length(p::FreeParameters) = length(p.names)\n\nfunction build_parameters_named_tuple(p::FreeParameters, free_θ)\n    if free_θ isa Dict # convert to NamedTuple with\n        free_θ = NamedTuple(name => free_θ[name] for name in p.names)\n    elseif !(free_θ isa NamedTuple) # mostly likely a Vector: convert to NamedTuple with\n        free_θ = NamedTuple{p.names}(Tuple(free_θ))\n    end\n\n    # Compute dependent parameters\n    dependent_names = keys(p.dependent_parameters) \n    maps = values(p.dependent_parameters)\n    dependent_θ = NamedTuple(name => maps[name](free_θ) for name in dependent_names)\n\n    return merge(dependent_θ, free_θ) # prioritize free_θ\nend\n\n#####\n##### Setting parameters\n#####\n\nconst ParameterValue = Union{Number, AbstractArray}\n\n\"\"\"\n    construct_object(specification_dict, parameters; name=nothing, type_parameter=nothing)\n    \n    construct_object(d::ParameterValue, parameters; name=nothing)\n\nReturn a composite type object whose properties are prescribed by the `specification_dict`\ndictionary. All parameter values are given the values in `specification_dict` *unless* they\nare included as a parameter name-value pair in the named tuple `parameters`, in which case\nthe value in `parameters` is asigned.\n\nThe `construct_object` is recursively called upon every property that is included in `specification_dict`\nuntil a property with a numerical value is reached. The object's constructor name must be\nincluded in `specification_dict` under key `:type`.\n\nExample\n=======\n\n```jldoctest; filter = [r\".*Dict{Symbol.*\", r\".*:type       => Closure.*\", r\".*:c          => 3.*\", r\".*:subclosure => Dict{Symbol.*\"]\njulia> using ParameterEstimocean.Parameters: construct_object, dict_properties, closure_with_parameters\n\njulia> struct Closure; subclosure; c end\n\njulia> struct ClosureSubModel; a; b end\n\njulia> sub_closure = ClosureSubModel(1, 2)\nClosureSubModel(1, 2)\n\njulia> closure = Closure(sub_closure, 3)\nClosure(ClosureSubModel(1, 2), 3)\n\njulia> specification_dict = dict_properties(closure)\nDict{Symbol, Any} with 3 entries:\n  :type       => Closure\n  :c          => 3\n  :subclosure => Dict{Symbol, Any}(:a=>1, :b=>2, :type=>ClosureSubModel)\n\njulia> new_closure = construct_object(specification_dict, (a=2.1,))\nClosure(ClosureSubModel(2.1, 2), 3)\n  \njulia> another_new_closure = construct_object(specification_dict, (b=π, c=2π))\nClosure(ClosureSubModel(1, π), 6.283185307179586)\n```\n\"\"\"\nconstruct_object(d::ParameterValue, parameters; name=nothing) =\n    name ∈ keys(parameters) ? getproperty(parameters, name) : d\n\nfunction construct_object(specification_dict, parameters;\n                          name=nothing, type_parameter=nothing)\n\n    type = Constructor = specification_dict[:type]\n    kwargs_vector = [construct_object(specification_dict[name], parameters; name)\n                        for name in fieldnames(type) if name != :type]\n\n    return isnothing(type_parameter) ? Constructor(kwargs_vector...) : \n                                       Constructor{type_parameter}(kwargs_vector...)\nend\n\n\"\"\"\n    dict_properties(object)\n\nReturn a dictionary with all properties of an `object` and their values, including the \n`object`'s type name. If any of the `object`'s properties is not a numerical value but\ninstead a composite type, then `dict_properties` is called recursively on that `object`'s\nproperty returning a dictionary with all properties of that composite type. Recursion\nends when properties of type `ParameterValue` are found.\n\"\"\"\nfunction dict_properties(object)\n    p = Dict{Symbol, Any}(n => dict_properties(getproperty(object, n)) for n in propertynames(object))\n    p[:type] = typeof(object).name.wrapper\n\n    return p\nend\n\ndict_properties(object::ParameterValue) = object\n\n\"\"\"\n    closure_with_parameters(closure, parameters)\n\nReturn a new object where for each (`parameter_name`, `parameter_value`) pair \nin `parameters`, the value corresponding to the key in `closure` that matches\n`parameter_name` is replaced with `parameter_value`.\n\nExample\n=======\n\nCreate a placeholder `Closure` type that includes a parameter `c` and a sub-closure\nwith two parameters: `a` and `b`. Then construct a closure with values `a, b, c = 1, 2, 3`.\n\n```jldoctest closure_with_parameters\njulia> struct Closure; subclosure; c end\n\njulia> struct ClosureSubModel; a; b end\n\njulia> sub_closure = ClosureSubModel(1, 2)\nClosureSubModel(1, 2)\n\njulia> closure = Closure(sub_closure, 3)\nClosure(ClosureSubModel(1, 2), 3)\n```\n\nProviding `closure_with_parameters` with a named tuple of parameter names and values,\nand a recursive search in all types and subtypes within `closure` is done and whenever\na parameter is found whose name exists in the named tuple we provided, its value is \nthen replaced with the value provided.\n\n```jldoctest closure_with_parameters\njulia> new_parameters = (a = 12, d = 7)\n(a = 12, d = 7)\n\njulia> using ParameterEstimocean.Parameters: closure_with_parameters\n\njulia> closure_with_parameters(closure, new_parameters)\nClosure(ClosureSubModel(12, 2), 3)\n```\n\"\"\"\nclosure_with_parameters(closure, parameters) = construct_object(dict_properties(closure), parameters)\n\nclosure_with_parameters(closure::AbstractTurbulenceClosure{ExplicitTimeDiscretization}, parameters) =\n    construct_object(dict_properties(closure), parameters, type_parameter=nothing)\n\nclosure_with_parameters(closure::AbstractTurbulenceClosure{TD}, parameters) where {TD <: AbstractTimeDiscretization} =\n    construct_object(dict_properties(closure), parameters; type_parameter=TD)\n\nclosure_with_parameters(closures::Tuple, parameters) =\n    Tuple(closure_with_parameters(closure, parameters) for closure in closures)\n\n\"\"\"\n    update_closure_ensemble_member!(closures, p_ensemble, parameters)\n\nUse `parameters` to update the `p_ensemble`-th closure from and array of `closures`.\nThe `p_ensemble`-th closure corresponds to ensemble member `p_ensemble`.\n\"\"\"\nupdate_closure_ensemble_member!(closure, p_ensemble, parameters) = nothing\n\nupdate_closure_ensemble_member!(closures::AbstractVector, p_ensemble, parameters) =\n    closures[p_ensemble] = closure_with_parameters(closures[p_ensemble], parameters)\n\nfunction update_closure_ensemble_member!(closures::AbstractMatrix, p_ensemble, parameters)\n    for j in 1:size(closures, 2) # Assume that ensemble varies along first dimension\n        closures[p_ensemble, j] = closure_with_parameters(closures[p_ensemble, j], parameters)\n    end\n    \n    return nothing\nend\n\nfunction update_closure_ensemble_member!(closure_tuple::Tuple, p_ensemble, parameters)\n    for closure in closure_tuple\n        update_closure_ensemble_member!(closure, p_ensemble, parameters)\n    end\n    return nothing\nend\n\n\"\"\"\n    new_closure_ensemble(closures, θ, arch=CPU())\n\nReturn a new set of `closures` in which all closures that have free parameters are updated.\nClosures with free parameters are expected as `AbstractArray` of `TurbulenceClosures`, and\nthis allows `new_closure_ensemble` to go through all closures in `closures` and only update\nthe parameters for the any closure that is of type `AbstractArray`. The `arch`itecture\n(`CPU()` or `GPU()`) defines whethere `Array` or `CuArray` is returned.\n\"\"\"\nfunction new_closure_ensemble(closures::AbstractArray, θ, arch)\n    cpu_closures = arch_array(CPU(), closures)\n\n    for (p, θp) in enumerate(θ)\n        update_closure_ensemble_member!(cpu_closures, p, θp)\n    end\n\n    return arch_array(arch, cpu_closures)\nend\nnew_closure_ensemble(closures::Tuple, θ, arch) = \n    Tuple(new_closure_ensemble(closure, θ, arch) for closure in closures)\n\nnew_closure_ensemble(closure, θ, arch) = closure\n\nend # module\n", "meta": {"hexsha": "0ba269c7d73612fb4679aafc0cd39d5ff94a0e81", "size": 19093, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Parameters.jl", "max_stars_repo_name": "CliMA/ParameterEstimocean.jl", "max_stars_repo_head_hexsha": "c94bc6e98422d8458ad0cf3fc0529d1bada8dd96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-09T13:10:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T13:10:41.000Z", "max_issues_repo_path": "src/Parameters.jl", "max_issues_repo_name": "CliMA/OceanLearning.jl", "max_issues_repo_head_hexsha": "48204cfea9116fdd3be5edb5e7bbe7598e2fae2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2022-03-09T05:47:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T04:58:22.000Z", "max_forks_repo_path": "src/Parameters.jl", "max_forks_repo_name": "CliMA/ParameterEstimocean.jl", "max_forks_repo_head_hexsha": "c94bc6e98422d8458ad0cf3fc0529d1bada8dd96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3793706294, "max_line_length": 134, "alphanum_fraction": 0.6987901325, "num_tokens": 5286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7888400421370247}}
{"text": "function makePlots()\n\nprintln(\"Generating plots\")\n\nplotsDir = (pwd()[end-3:end] == \"docs\") ? \"build/plots\" : \"docs/build/plots\"\nmkdir(plotsDir)\nPlots.pyplot()\n\n\n# PID design functions\nP = tf(1,[1,1])^4\ngangoffourplot(P,tf(1))\nPlots.savefig(plotsDir*\"/pidgofplot.svg\")\n\nωp = 0.8\nkp,ki,C = loopshapingPI(P,ωp,phasemargin=60, doplot=false)\ngangoffourplot(P, [tf(1), C])\nPlots.savefig(plotsDir*\"/pidgofplot2.svg\")\nnyquistplot([P, P*C])\nPlots.savefig(plotsDir*\"/pidnyquistplot.svg\")\n\n\nωp = 2\nkp,ki,C60 = loopshapingPI(P,ωp,rl=1,phasemargin=60, doplot=true)\ngangoffourplot(P, [tf(1), C60])\nPlots.savefig(plotsDir*\"/pidgofplot3.svg\")\nnyquistplot([P, P*C60])\nPlots.savefig(plotsDir*\"/pidnyquistplot2.svg\")\n\n# Advanced pole placement\nζ = 0.2\nω = 1\nB = [1]\nA   = [1, 2ζ*ω, ω^2]\nP  = tf(B,A)\n# Control design\nζ0 = 0.7\nω0 = 2\nAm = [1, 2ζ0*ω0, ω0^2]\nAo = conv(2Am, [1/2, 1]) # Observer polynomial\nAR = [1,0] # Force the controller to contain an integrator\n\nB⁺  = [1] # The process numerator polynomial can be facored as B = B⁺B⁻ where B⁻ contains the zeros we do not want to cancel (non-minimum phase and poorly damped zeros)\nB⁻  = [1]\nBm  = conv(B⁺, B⁻) # In this case, keep the entire numerator polynomial of the process\n\nR,S,T = rstc(B⁺,B⁻,A,Bm,Am,Ao,AR) # Calculate the 2-DOF controller polynomials\n\nGcl = tf(conv(B,T),zpconv(A,R,B,S)) # Form the closed loop polynomial from reference to output\n\nstepplot([P,Gcl]) # Visualize the open and closed loop responses.\nPlots.savefig(plotsDir*\"/ppstepplot.svg\")\ngangoffourplot(P, tf(-S,R)) # Plot the gang of four to check that all tranfer functions are OK\nPlots.savefig(plotsDir*\"/ppgofplot.svg\")\n\nP1 = \"exp(-sqrt(s))\"\nf1 = stabregionPID(P1,logspace(-5,1,1000)); Plots.savefig(plotsDir*\"/stab1.svg\")\nP2 = \"100*(s+6).^2./(s.*(s+1).^2.*(s+50).^2)\"\nf2 = stabregionPID(P2,logspace(-5,2,1000)); Plots.savefig(plotsDir*\"/stab2.svg\")\nP3 = tf(1,[1,1])^4\nf3 = stabregionPID(P3,logspace(-5,0,1000)); Plots.savefig(plotsDir*\"/stab3.svg\")\n\n\n\n\n# PID plots\n\nP = tf([1.],[1., 1])\nζ = 0.5 # Desired damping\nws = logspace(-1,2,8) # A vector of closed-loop bandwidths\nkp = 2*ζ*ws-1 # Simple pole placement with PI given the closed-loop bandwidth, the poles are placed in a butterworth pattern\nki = ws.^2\npidplots(P,:nyquist,;kps=kp,kis=ki, ω= logspace(-2,2,500))\nPlots.savefig(plotsDir*\"/pidplotsnyquist1.svg\")\npidplots(P,:gof,;kps=kp,kis=ki, ω= logspace(-2,2,500))\nPlots.savefig(plotsDir*\"/pidplotgof1.svg\")\n\nkp = linspace(-1,1,8) # Now try a different strategy, where we have specified a gain crossover frequency of 0.1 rad/s\nki = sqrt(1-kp.^2)/10\npidplots(P,:nyquist,;kps=kp,kis=ki)\nPlots.savefig(plotsDir*\"/pidplotsnyquist2.svg\")\npidplots(P,:gof,;kps=kp,kis=ki)\nPlots.savefig(plotsDir*\"/pidplotsgof2.svg\")\n\n#AR = [1,0]\n#B⁺  = [1]\n#B⁻  = [1]\n#Bm  = conv(B⁺, B⁻)\n#R,S,T = rstc(B⁺,B⁻,A,bm,Am,Ao,AR)\n#Gcl = tf(conv(B,T),zpconv(A,R,B,S))\n#f1 = stepplot([P,Gcl])\n#f2 = gangoffourplot(P, tf(-S,R))\n#Plots.savefig(f1, \"$plotsDir/rstcstepplot.svg\")\n#Plots.savefig(f2, \"$plotsDir/rstcgofplot.svg\")\nend\n", "meta": {"hexsha": "0874de3d20f5586efeff9774b09d6f4f948219e6", "size": 3012, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/makeplots.jl", "max_stars_repo_name": "JuliaPackageMirrors/ControlSystems.jl", "max_stars_repo_head_hexsha": "575f355ba878ea9d512a0770027f2edd420e71f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/src/makeplots.jl", "max_issues_repo_name": "JuliaPackageMirrors/ControlSystems.jl", "max_issues_repo_head_hexsha": "575f355ba878ea9d512a0770027f2edd420e71f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/src/makeplots.jl", "max_forks_repo_name": "JuliaPackageMirrors/ControlSystems.jl", "max_forks_repo_head_hexsha": "575f355ba878ea9d512a0770027f2edd420e71f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.375, "max_line_length": 168, "alphanum_fraction": 0.6852589641, "num_tokens": 1171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801888, "lm_q2_score": 0.8577681122619885, "lm_q1q2_score": 0.7888400398133573}}
{"text": "\"\"\"\n    expectation_step(X, z, dists)\n\nComputes the expectation step with:\n- `X`: (m×n) multi-variate observations (rows are observations, columns are variables)\n- `dists`: distributions, one for each category (unique label)\n- `prior`: prior probability of each label\nReturns `Z`: (m×n) matrix of probability distributions of each label for each observation\n\"\"\"\nfunction expectation_step(X, dists, prior)\n    n = size(X, 1)\n    Z = Matrix{Float64}(undef, n, length(prior))\n    for k in eachindex(prior)\n        for i in 1:n\n            Z[i,k] = prior[k] * pdf(dists[k], X[i,:]) /\n                     sum(\n                        prior[j] * pdf(dists[j], X[i,:])\n                        for j in eachindex(prior)\n                     )\n        end\n    end\n    return Z\nend\n\n\"\"\"\n    maximization_step(::Type{<:D}, X, Z)\n\nMaximization step, parameterized by the type of distribution used.\nReturns a tuple (dists, π, loglike) with:\n- `dists`: the created vector of distributions\n- `prior` vector of updated prior probabilities of each label\n\"\"\"\nfunction maximization_step(::Type{<:MvNormal}, X, Z)\n    n = size(X, 1)\n    Nk = size(Z, 2)\n    µ = map(1:Nk) do k\n        num = sum(Z[i,k] .* X[i,:] for i in 1:n)\n        den = sum(Z[i,k] for i in 1:n)\n        num / den\n    end\n\n    Σ = map(1:Nk) do k\n        num = zeros(size(X, 2), size(X, 2))\n        for i in 1:n\n            r = X[i,:] .- µ[k]\n            num .= num .+ Z[i,k] .* (r * r')\n        end\n        den = sum(Z[i,k] for i in 1:n)\n        num ./ den\n    end\n    prior = [inv(n) * sum(Z[i,k] for i in 1:n)\n            for k in 1:Nk\n        ]\n    dists = map(1:Nk) do k\n        MvNormal(µ[k], Σ[k] + 10e-7I)\n    end\n    return (dists, prior)\nend\n\n\"\"\"\n    expectation_maximization(D::Type{<:Distribution}, X, Nk, maxiter::Integer = 500, loglike_diff = 10e-5; all_dists = nothing)\n\nComplete EM algorithm, takes a type of distribution `D` used to\ndetermine the maximization step, observations `X` and number of classes `Nk`.\n\"\"\"\nfunction expectation_maximization(D::Type{<:Distribution}, X, Nk, maxiter::Integer = 500, loglike_diff = 10e-5; all_dists = nothing)\n    # initialize classes\n    n = size(X,1)\n    Z = zeros(n, Nk)\n    for i in 1:n\n        j0 = mod(i,Nk)+1\n        j1 = j0 > 1 ? j0-1 : 2\n        Z[i,j0] = 0.75\n        Z[i,j1] = 0.25\n    end\n    (dists, prior) = maximization_step(D, X, Z)\n    all_dists isa Vector && push!(all_dists, (dists, prior))\n    l = loglike_mixture(X, dists, prior)\n    lprev = 0.0\n    iter = 0\n    # EM iterations\n    while iter < maxiter && abs(lprev-l) > loglike_diff\n        Z = expectation_step(X, dists, prior)\n        (dists, prior) = maximization_step(D, X, Z)\n        all_dists isa Vector && push!(all_dists, (dists, prior))\n        lprev = l\n        l = loglike_mixture(X, dists, prior)\n        iter += 1\n    end\n    return (dists, prior, Z, l, iter)\nend\n\nfunction loglike_mixture(X, dists, prior)\n    l = zero(eltype(X))\n    n = size(X,1)\n    for i in 1:n\n        l += log(\n            sum(prior[k] * pdf(dists[k], X[i,:]) for k in eachindex(prior))\n        )\n    end\n    return l\nend\n\nlet\n    Random.seed!(42)\n    X = [randn(1000, 2); 3.0 .+ randn(1000, 2)]\n    n = size(X, 1)\n    for maxiter in (1, 5, 10, 100, 150, 250)\n        (dists, prior, Z, l, iter) = expectation_maximization(MvNormal, X, 2, maxiter)\n        contour_mixture(x1, x2) = maximum([pdf(dists[k], [x1,x2]) for k in 1:2])\n        colors = map(1:n) do i\n            (_, j) = findmax(Z[i,:])\n            j == 1 ? :red : :blue\n        end\n        plt = Plots.contour(-2.8:0.05:6.0, -2.8:0.05:6.0, contour_mixture, contours = false, legend = nothing)\n        Plots.scatter!(plt, X[:,1],X[:,2], label = \"\", color = colors)\n        Plots.savefig(joinpath(base_img, \"mixture_iter$(maxiter)_$iter.pdf\"))\n    end\nend\n", "meta": {"hexsha": "e740c0342f84dbd04c4cf0a480983af878189655", "size": 3776, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/expectation_maximization.jl", "max_stars_repo_name": "matbesancon/DistributionsExamples.jl", "max_stars_repo_head_hexsha": "c2186b35d0f94400bb7ca67f7d3adb4a33886b39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/expectation_maximization.jl", "max_issues_repo_name": "matbesancon/DistributionsExamples.jl", "max_issues_repo_head_hexsha": "c2186b35d0f94400bb7ca67f7d3adb4a33886b39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/expectation_maximization.jl", "max_forks_repo_name": "matbesancon/DistributionsExamples.jl", "max_forks_repo_head_hexsha": "c2186b35d0f94400bb7ca67f7d3adb4a33886b39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4666666667, "max_line_length": 132, "alphanum_fraction": 0.5606461864, "num_tokens": 1242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.8577681104440171, "lm_q1q2_score": 0.7888400362523285}}
{"text": "using DiscreteFiltering\nusing OrdinaryDiffEq: ODEProblem, solve, Tsit5\nusing LinearAlgebra\nusing Plots\nusing SparseArrays\n\n\n## Domain\na = 0.0\nb = 2π\ndomain = PeriodicIntervalDomain(a, b)\n# domain = ClosedIntervalDomain(a, b)\n\n\n## Discretization\nN = 100\nM = N\nx = discretize(domain, M)\nξ = discretize(domain, N)\nΔx = (b - a) / N\n\n\n## Filter\nh₀ = 2.1Δx\nh(x) = h₀ * (1 - 1 / 2 * cos(x))\ndh(x) = h₀ / 2 * sin(x)\nα(x) = 1 / 3 * dh(x) * h(x)\nf = TopHatFilter(h)\n\n# h₀ = 5.1Δx\n# h(x) = h₀ # * (1 - 1 / 2 * cos(x))\n# dh(x) = 0.0 # h₀ / 2 * sin(x)\n# α(x) = 1 / 3 * dh(x) * h(x)\n# f = GaussianFilter(h, Δx / 2)\n\n\n## Time\nT = 1.5\nt = T\n\n\n## Plot filter\nplot(x, h)\nylims!((0, ylims()[2]))\n\n\n## Get matrices\nC = advection_matrix(domain, N)\nD = diffusion_matrix(domain, N)\nW = filter_matrix(f, domain, M, N)\nR = reconstruction_matrix(f, domain, M, N)\nA = spdiagm(α.(ξ))\n\n## Inspect matrices\nspy(W)\nspy(R)\n\n\n## Exact solutions\nu(ξ, t) = sin(ξ - t) + 3 / 5 * cos(5(ξ - t)) + 1 / 25 * sin(20(ξ - 1 - t))\nu_int(ξ, t) = -cos(ξ - t) + 3 / 25 * sin(5(ξ - t)) - 1 / 25 / 20 * cos(20(ξ - 1 - t))\nū(x, t) = 1 / 2h(x) * (u_int(x + h(x), t) - u_int(x - h(x), t))\n\n\n## Discrete initial conditions\nuₕ = u.(ξ, 0.0)\nūₕ = ū.(x, 0.0)\nuₕ_allbar = W * uₕ\n\nplot(x, uₕ, label = \"Discretized\")\nplot!(x, ūₕ, label = \"Filtered-then-discretized\")\nplot!(x, uₕ_allbar, label = \"Discretized-then-filtered\")\n\n\n## Solve discretized problem\nduₕ(uₕ, p, t) = -C * uₕ\nprob = ODEProblem(duₕ, uₕ, (0, T))\nsol = solve(prob, Tsit5(), abstol = 1e-6, reltol = 1e-4)\n\nplot(x, uₕ, label = \"Initial conditions\")\nplot!(x, sol(t), label = \"Discretized\")\nplot!(x, u.(x, t), label = \"Exact\")\n\n\n## Solve filtered-and-then-discretized problem\ndūₕ(ūₕ, p, t) = (-C + A * D) * ūₕ\nprob_bar = ODEProblem(dūₕ, ūₕ, (0, T))\nsol_bar = solve(prob_bar, Tsit5(), abstol = 1e-6, reltol = 1e-4)\n\nplot(x, uₕ, label = \"Initial\")\nplot!(x, ūₕ, label = \"Initial filtered\")\nplot!(x, sol_bar(t), label = \"Filtered-then-discretized\")\nplot!(x, ū.(x, t), label = \"Filtered exact\")\n# plot!(x, 500*α.(ξ))\n\n\n## Solve discretized-and-then-filtered problem\nduₕ_allbar(uₕ_allbar, p, t) = -W * (C * (R * uₕ_allbar))\n# duₕ_allbar(uₕ_allbar, p, t) = -W * (C * (W \\ uₕ_allbar))\nprob_allbar = ODEProblem(duₕ_allbar, W * uₕ, (0, T))\nsol_allbar = solve(prob_allbar, Tsit5(), abstol = 1e-6, reltol = 1e-4)\n\nplot(x, uₕ, label = \"Initial\")\nplot!(x, uₕ_allbar, label = \"Initial discretized-then-filtered\")\nplot!(x, sol_allbar(t), label = \"Discretized-then-filtered\")\nplot!(x, W * u.(ξ, t), label = \"Exact\")\n\n## PGFPlotsX\npgfplotsx()\n\n## Comparison\np = plot(\n    size = (400, 300),\n    xlabel = \"\\$x\\$\",\n    legend = :topright,\n)\nplot!(p, x, uₕ, label = \"\\$u(x, t = 0.0)\\$\")\n# plot!(p, x, ūₕ, label = \"Initial filtered\")\n# plot!(p, x, sol(t), label = \"Discretized\")\n# plot!(p, x, sol_bar(t), label = \"Filtered-then-discretized\")\n# plot!(p, x, sol_allbar(t), label = \"Discretized-then-filtered\")\n# plot!(p, x, [u.(x, t), ū.(x, t)], label = \"Exact\")\nplot!(p, x, u.(x, t), label = \"\\$u(x, t = $t)\\$\")\nplot!(p, x, ū.(x, t), label = \"\\$u(x, t = $t)\\$\")\n# ylims!(p, minimum(uₕ), maximum(uₕ))\ndisplay(p)\nsavefig(p, \"output/advection/solution.tikz\")\n\n\n## Relative error\nu_exact = u.(ξ, t)\nū_exact = ū.(x, t)\nerr = abs.(sol(t) - u_exact) ./ maximum(abs.(u_exact))\nerr_bar = abs.(sol_bar(t) - u_exact) ./ maximum(abs.(u_exact))\nerr_allbar = abs.(sol_allbar(t) - u_exact) ./ maximum(abs.(u_exact))\n\nplot()\nplot!(ξ, err, label = \"Unfiltered discretized\")\nplot!(x, err_bar, label = \"Filtered-then-discretized\")\nplot!(x, err_allbar, label = \"Discretized-then-filtered\")\n", "meta": {"hexsha": "ec198dbf88601de2fcb60852d2d734be29a26080", "size": 3553, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/advection.jl", "max_stars_repo_name": "agdestein/DiscreteFiltering.jl", "max_stars_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-23T12:51:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T12:51:11.000Z", "max_issues_repo_path": "examples/advection.jl", "max_issues_repo_name": "agdestein/DiscreteFiltering.jl", "max_issues_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/advection.jl", "max_forks_repo_name": "agdestein/DiscreteFiltering.jl", "max_forks_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1985815603, "max_line_length": 85, "alphanum_fraction": 0.5994933859, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.8577681031721324, "lm_q1q2_score": 0.7888400352322289}}
{"text": "# # Variational problems \n#\n# In this example, we will numerically simulate an entropy-regularised Wasserstein gradient flow \n# approximating the Fokker-Planck and porous medium equations. \n# \n# The connection between Wasserstein gradient flows and (non)-linear PDEs is due to Jordan, Kinderlehrer and Otto [^JKO98], and \n# an easy-to-read overview of the topic is provided in Section 9.3 [^PC19]\n#\n# [^JKO98]: Jordan, Richard, David Kinderlehrer, and Felix Otto. \"The variational formulation of the Fokker--Planck equation.\" SIAM journal on mathematical analysis 29.1 (1998): 1-17.\n# [^PC19]: Peyré, Gabriel, and Marco Cuturi. \"Computational optimal transport: With applications to data science.\" Foundations and Trends® in Machine Learning 11.5-6 (2019): 355-607.\n#\n# ## Fokker-Planck equation as a $W_2$ gradient flow\n# For a potential function $\\Psi$ and noise level $\\sigma^2$, the Fokker-Planck equation (FPE) is \n# ```math\n# \\partial_t \\rho_t = \\nabla \\cdot (\\rho_t \\nabla \\Psi) + \\frac{\\sigma^2}{2} \\Delta \\rho_t,\n# ```\n# and we take no-flux (Neumann) boundary conditions. \n#\n# This describes the evolution of a massless particle undergoing both diffusion (with diffusivity $\\sigma^2$) and drift (along potential $\\Psi$) according to the stochastic differential equation\n# ```math\n# dX_t = -\\nabla \\Psi(X_t) dt + \\sigma dB_t. \n# ```\n# The result of Jordan, Kinderlehrer and Otto (commonly referred to as the JKO theorem) states that \n# $\\rho_t$ evolves following the 2-Wasserstein gradient flow of the Gibbs free energy functional\n# ```math\n#   F(\\rho) = \\int \\Psi d\\rho + \\int \\log(\\rho) d\\rho. \n# ```\n#\n# ## Implicit schemes for gradient flows\n# In an Euclidean space, the gradient flow of a functional $F$ is simply the solution of an ordinary differential equation\n# ```math\n#  \\dfrac{dx(t)}{dt} = -\\nabla F(x(t)).\n# ```\n# Of course, there is a requirement that $F$ is smooth. A more general formulation of a gradient flow that allows\n# $F$ to be non-smooth is the implicit scheme\n# ```math\n#   x_{t+\\tau} = \\operatorname{argmin}_x \\frac{1}{2} \\| x - x_t \\|_2^2 + \\tau F(x).\n# ```\n# As the timestep $\\tau$ shrinks, $x_t$ becomes a better and better approximation to the gradient flow of $F$. \n#\n# ## Wasserstein gradient flow\n# In the context of the JKO theorem, we seek $\\rho_t$ that is the gradient flow of $F$ with \n# respect to the 2-Wasserstein distance. This can be achieved by choosing the $W_2$ metric in the implicit step:\n# ```math\n#   \\rho_{t + \\tau} = \\operatorname{argmin}_{\\rho} d_{W_2}^2(\\rho_{t}, \\rho) + \\tau F(\\rho). \n# ```\n# Finally, a numerical scheme for computing this gradient flow can be developed by using the entropic regularisation\n# of optimal transport on a discretised domain \n# ```math\n#   \\rho_{t + \\tau} = \\operatorname{argmin}_{\\rho} \\operatorname{OT}_\\varepsilon(\\rho_{t}, \\rho) + \\tau F(\\rho),\n# ```\n# where \n# ```math\n#   \\operatorname{OT}_\\varepsilon(\\alpha, \\beta) = \\min_{\\gamma \\in \\Pi(\\alpha, \\beta)} \\sum_{i,j} \\frac{1}{2} \\| x_i - x_j \\|_2^2 \\gamma_{ij} + \\varepsilon \\sum_{i, j} \\gamma_{ij} \\log(\\gamma_{ij}). \n# ```\n# Each step of this problem is a minimisation problem with respect to $\\rho$. \n# Since we use entropic optimal transport which is differentiable, this can be solved using gradient-based methods.\n\n# ## Problem setup\n#\nusing OptimalTransport\nusing Distances\nusing LogExpFunctions\nusing Optim\nusing Plots\nusing StatsBase\n\nusing LinearAlgebra\nusing Logging\n\n# Here, we set up the computational domain that we work on - we discretize the interval $[-1, 1]$. \n# The natural boundary conditions to use will be Neumann (zero flux), see e.g. [^Santam2017]\n#\n# [^Santam2017]: Santambrogio, Filippo. \"{Euclidean, metric, and Wasserstein} gradient flows: an overview.\" Bulletin of Mathematical Sciences 7.1 (2017): 87-154.\n\nsupport = range(-1, 1; length=64)\nC = pairwise(SqEuclidean(), support');\n\n# Now we set up various functionals that we will use.\n#\n# We define the generalised entropy (Equation (4.4) of [^Peyre2015]) as follows. For $m = 1$ this is just the \"regular\" entropy, and $m = 2$ this is squared $L_2$. \n#\n# [^Peyre2015]: Peyré, Gabriel. \"Entropic approximation of Wasserstein gradient flows.\" SIAM Journal on Imaging Sciences 8.4 (2015): 2323-2351.\nfunction E(ρ; m=1)\n    if m == 1\n        return sum(xlogx.(ρ)) - sum(ρ)\n    elseif m > 1\n        return dot(ρ, @. (ρ^(m - 1) - m) / (m - 1))\n    end\nend;\n\n# Now define $\\psi(x)$ to be a potential energy function that has two potential wells at $x = ± 0.5$. \nψ(x) = 10 * (x - 0.5)^2 * (x + 0.5)^2;\nplot(support, ψ.(support); color=\"black\", label=\"Scalar potential\")\n\n# Having defined $\\psi$, this induces a potential energy functional $\\Psi$ on probability distributions $\\rho$:\n# ```math\n#    \\Psi(\\rho) = \\int \\psi(x) \\rho(x) dx = \\langle \\psi, \\rho \\rangle . \n# ```\nΨ = ψ.(support);\n\n# Define the time step $\\tau$ and entropic regularisation level $\\varepsilon$, and form the associated Gibbs kernel $K = e^{-C/\\varepsilon}$. \nτ = 0.05\nε = 0.01\nK = @. exp(-C / ε)\n\n# We define the (non-smooth) initial condition $\\rho_0$ in terms of step functions. \nH(x) = x > 0\nρ0 = @. H(support + 0.25) - H(support - 0.25)\nρ0 = ρ0 / sum(ρ0)\nplot(support, ρ0; label=\"Initial condition ρ0\", color=\"blue\")\n\n# `G_fpe` is the objective function for the implicit step scheme  \n# ```math\n# G_\\mathrm{fpe}(\\rho) = \\operatorname{OT}_\\varepsilon(\\rho_{t}, \\rho) + \\tau F(\\rho),\n# ```\n# and we seek to minimise in $\\rho$. \nfunction G_fpe(ρ, ρ0, τ, ε, C)\n    return sinkhorn2(ρ, ρ0, C, ε; regularization=true, maxiter=250) + τ * (dot(Ψ, ρ) + E(ρ))\nend;\n\n# `step` solves the implicit step problem to produce $\\rho_{t + \\tau}$ from $\\rho_t$. \nfunction step(ρ0, τ, ε, C, G)\n    ## only print error messages\n    opt = with_logger(SimpleLogger(stderr, Logging.Error)) do\n        optimize(\n            u -> G(softmax(u), ρ0, τ, ε, C),\n            ones(size(ρ0)),\n            LBFGS(),\n            Optim.Options(; iterations=50, g_tol=1e-6);\n            autodiff=:forward,\n        )\n    end\n    return softmax(Optim.minimizer(opt))\nend\n# Now we simulate `N = 10` iterates of the gradient flow and plot the result. \nN = 10\nρ = similar(ρ0, size(ρ0, 1), N)\nρ[:, 1] = ρ0\nfor i in 2:N\n    ρ[:, i] = step(ρ[:, i - 1], τ, ε, C, G_fpe)\nend\ncolors = range(colorant\"red\"; stop=colorant\"blue\", length=N)\nplot(\n    support,\n    ρ;\n    title=raw\"$F(\\rho) = \\langle \\psi, \\rho \\rangle + \\langle \\rho, \\log(\\rho) \\rangle$\",\n    palette=colors,\n    legend=nothing,\n)\n\n# ## Porous medium equation \n#\n# The porous medium equation (PME) is the nonlinear PDE \n# ```math\n# \\partial_t \\rho = \\nabla \\cdot (\\rho \\nabla \\Psi) + \\Delta \\rho^m,\n# ```\n# again with Neumann boundary conditions. The value of $m$ in the PME corresponds to picking $m$ in the generalised entropy functional.  \n# Now, we will solve the PME with $m = 2$ as a Wasserstein gradient flow.\n#\nfunction G_pme(ρ, ρ0, τ, ε, C)\n    return sinkhorn2(ρ, ρ0, C, ε; regularization=true, maxiter=250) +\n           τ * (dot(Ψ, ρ) + E(ρ; m=2))\nend;\n\n# set up as previously \nN = 10\nρ = similar(ρ0, size(ρ0, 1), N)\nρ[:, 1] = ρ0\nfor i in 2:N\n    ρ[:, i] = step(ρ[:, i - 1], τ, ε, C, G_pme)\nend\nplot(\n    support,\n    ρ;\n    title=raw\"$F(\\rho) = \\langle \\psi, \\rho \\rangle + \\langle \\rho, \\rho - 1\\rangle$\",\n    palette=colors,\n    legend=nothing,\n)\n", "meta": {"hexsha": "b288d5fde80b181015cbdf608f686a86413664b4", "size": 7276, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/variational/script.jl", "max_stars_repo_name": "zsteve/OptimalTransport.jl", "max_stars_repo_head_hexsha": "ab9bc76a13c106f451ef58126cab07758f905f3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2020-05-07T13:52:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T21:34:03.000Z", "max_issues_repo_path": "examples/variational/script.jl", "max_issues_repo_name": "zsteve/OptimalTransport.jl", "max_issues_repo_head_hexsha": "ab9bc76a13c106f451ef58126cab07758f905f3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 49, "max_issues_repo_issues_event_min_datetime": "2020-05-15T16:48:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-18T18:38:46.000Z", "max_forks_repo_path": "examples/variational/script.jl", "max_forks_repo_name": "zsteve/OptimalTransport.jl", "max_forks_repo_head_hexsha": "ab9bc76a13c106f451ef58126cab07758f905f3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-05-27T21:56:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-19T19:15:09.000Z", "avg_line_length": 40.4222222222, "max_line_length": 200, "alphanum_fraction": 0.6623144585, "num_tokens": 2362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642528975397, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7888400243318817}}
{"text": "function parametrized_kuramoto(du,u,p,t)\n    # NumberOfOscillators, CouplingConstant, and NaturalFreqs\n    N,K,w = p\n    # Centroid\n    u[1] = 0\n    for i in 1:N\n        u[1] += cos(u[i+1]) + sin(u[i+1])*im\n    end\n    u[1] = u[1]/N\n    r = abs(u[1])\n    ψ = angle(u[1])\n    # Oscillators\n    for i in 1:N\n    \tdu[i+1] = w[i] + K*r*sin(ψ-u[i+1])\n    end\nend\n\nfunction getparameters_kuramoto(N,K,γ,distribution)\n    distribution == \"Uniform\" ? nothing : error(\"$(distribution) is not yet supported\")\n    j = collect(1:N)\n    w = broadcast(j->((2j-N-1)/(N-1))*((pi*γ)/2),j)\n    p = (N=N, K=K, w=w)\n    return p\nend\n\n\nfunction getstartpoints_kuramoto(N)\n    d = Uniform(-pi,pi)\n    u0::Array{ComplexF64} = rand(d,N)\n    pushfirst!(u0,mean(u0))\n    return u0\nend\n\nfunction kuramoto(N,K,T,fs,γ,distribution)\n    tspan = (0.0,T)\n    u0 = getstartpoints_kuramoto(N)\n    p = getparameters_kuramoto(N,K,γ,distribution)\n    prob = ODEProblem(parametrized_kuramoto,u0,tspan,p)\n    sol = solve(prob,RK4(),saveat=collect(0:1/fs:T),progress=true)\nend\n\n", "meta": {"hexsha": "eb9f4873b033d2b34e89209a493e2d34742ccc26", "size": 1038, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kuramoto.jl", "max_stars_repo_name": "VMHidalgo/CoupledOscillators.jl", "max_stars_repo_head_hexsha": "267a51f4880c3bdf09f370b1716b78a94cca361d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kuramoto.jl", "max_issues_repo_name": "VMHidalgo/CoupledOscillators.jl", "max_issues_repo_head_hexsha": "267a51f4880c3bdf09f370b1716b78a94cca361d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kuramoto.jl", "max_forks_repo_name": "VMHidalgo/CoupledOscillators.jl", "max_forks_repo_head_hexsha": "267a51f4880c3bdf09f370b1716b78a94cca361d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7142857143, "max_line_length": 87, "alphanum_fraction": 0.6078998073, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075755433747, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7888255938540396}}
{"text": "# ---\n# title: 96. Unique Binary Search Trees\n# id: problem96\n# author: zhwang\n# date: 2022-02-23\n# difficulty: Medium\n# categories: Dynamic Programming, Tree\n# link: <https://leetcode.com/problems/unique-binary-search-trees/description/>\n# hidden: true\n# ---\n# \n# Given _n_ , how many structurally unique **BST 's** (binary search trees) that\n# store values 1 ...  _n_?\n# \n# **Example:**\n# \n#     \n#     \n#     Input: 3\n#     Output: 5\n#     Explanation: Given _n_ = 3, there are a total of 5 unique BST's:\n#     \n#        1         3     3      2      1\n#         \\       /     /      / \\      \\\n#          3     2     1      1   3      2\n#         /     /       \\                 \\\n#        2     1         2                 3\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= n <= 19`\n# \n# \n## @lc code=start\nusing LeetCode\n\nnum_of_trees(n::Int) = binomial(2 * n, n) - binomial(2 * n, n + 1)\n## @lc code=end\n", "meta": {"hexsha": "2bff636360f9fb694108d440ea5eda5dc34b12d3", "size": 912, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/96.unique-binary-search-trees.jl", "max_stars_repo_name": "RexWzh/LeetCode.jl", "max_stars_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/96.unique-binary-search-trees.jl", "max_issues_repo_name": "RexWzh/LeetCode.jl", "max_issues_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/96.unique-binary-search-trees.jl", "max_forks_repo_name": "RexWzh/LeetCode.jl", "max_forks_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7142857143, "max_line_length": 80, "alphanum_fraction": 0.4682017544, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7888222929957623}}
{"text": "module TF\n\nimport ..d; import ..dxasy\n\nsigmoid{F <: AbstractFloat}(x::F) = one(F)/(one(F) + exp(-x))\ndasysigmoid{F <: AbstractFloat}(y::F) = y * (one(F) - y)\n#explicitly reinterpret the dasysigmoid.\ndsigmoid{F <: AbstractFloat}(x::F) = dasysigmoid(sigmoid(x))\n\nid{F <: AbstractFloat}(x::F) = x\n\nsoftplus{F <: AbstractFloat}(x::F) = log(one(F) + exp(x))\ndasysoftplus{F <: AbstractFloat}(y::F) = (exp(y) - one(F)) / exp(y)\n\n#broadcast functions over arrays.\nsigmoid{F <: AbstractFloat}(a::Array{F})      = sigmoid.(a)\ndasysigmoid{F <: AbstractFloat}(a::Array{F})  = dasysigmoid.(a)\ndsigmoid{F <: AbstractFloat}(a::Array{F})     = dsigmoid.(a)\nid{F <: AbstractFloat}(a::Array{F})           = a\nsoftplus{F <: AbstractFloat}(a::Array{F})     = softplus.(a)\ndasysoftplus{F <: AbstractFloat}(a::Array{F}) = dasysoftplus.(a)\n\n#non-simple transfer functions.\nfunction softmax{F <: AbstractFloat}(a::Array{F})\n  #go over the entire array and add up the values.\n  totalexpsum = zero(F)\n  for idx = 1:length(a)\n    totalexpsum += exp(a[idx])\n  end\n  exp.(a) / totalexpsum\nend\ndsoftmax{F <: AbstractFloat}(a::Array{F}) = dasysigmoid.(softmax(a))\n\ndxasy(::typeof(sigmoid)) = dasysigmoid\ndxasy(::typeof(id)) = one\ndxasy(::typeof(softplus)) = dasysoftplus\ndxasy(::typeof(softmax)) = dasysigmoid\n\nd(::typeof(sigmoid)) = dsigmoid\nd(::typeof(id)) = one\nd(::typeof(softplus)) = sigmoid\nd(::typeof(softmax)) = dsoftmax\n\nend\n", "meta": {"hexsha": "bc4f3fa8adf8069ac3c2c6c853533d20a03b2842", "size": 1403, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transferfunctions.jl", "max_stars_repo_name": "interplanetary-robot/GenML", "max_stars_repo_head_hexsha": "f99015ab404250861334e75445b3a701293349e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/transferfunctions.jl", "max_issues_repo_name": "interplanetary-robot/GenML", "max_issues_repo_head_hexsha": "f99015ab404250861334e75445b3a701293349e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/transferfunctions.jl", "max_forks_repo_name": "interplanetary-robot/GenML", "max_forks_repo_head_hexsha": "f99015ab404250861334e75445b3a701293349e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1777777778, "max_line_length": 68, "alphanum_fraction": 0.6571632217, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870767, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7888222846073807}}
{"text": "module supply_allocation\n\nusing JuMP\nusing Cbc\nusing CSV\n\nfunction solve_supply_allocation()\n\n    #------\n    # DATA\n    #------\n\n    n = 4;\n    m = 3;\n    Q = [30 15 20 35];\n    d = [40 10 35];\n\n    c = [\n        40\t39\t40;\n        35\t36\t31;\n        33\t43\t42;\n        37\t35\t38\n    ];\n\n    #------\n    # MODEL\n    #------\n\n    model = Model(with_optimizer(Cbc.Optimizer));\n\n    @variable(model, x[1:n,1:m] >= 0)\n\n    @objective(model, Min, sum(c[i,j] * x[i,j] for i in 1:n, j in 1:m));\n\n    @constraint(model,[j = 1:m],sum(x[i,j] for i in 1:n) == d[j]);\n\n    @constraint(model,[i = 1:n],sum(x[i,j] for j in 1:m) <= Q[i]);\n\n    f = open(\"supply_allocation.lp\", \"w\")\n    print(f, model)\n    close(f)\n\n    #-------\n    # SOLVE\n    #-------\n\n    optimize!(model)\n\n    #------------------------\n    # WRITE SOLUTION TO FILE\n    #------------------------\n\n    f = open(\"supply_allocation.csv\",\"w\");\n\n    print(f,\",\");\n    print(f,\"Munich,Salzburg,Prague\");\n    println(f,\"\");\n\n    ports = [\"Rotterdam\" \"Wilhelmshaven\" \"Bremerhaven\" \"Hamburg\" ];\n\n    for i = 1:n\n        print(f,ports[i],\",\");\n        for j = 1:m\n            print(f,value(x[i,j]),\",\");\n        end\n        println(f,\"\");\n    end\n\n    close(f);\n\nend\n\nsolve_supply_allocation();\n\nend\n", "meta": {"hexsha": "9dfd10d7e4c8d1a54e89b730faf99b3f4868d0a3", "size": 1242, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/network/supply-net/supply_allocation.jl", "max_stars_repo_name": "edxu96/MatrixOptim", "max_stars_repo_head_hexsha": "97ef8b1311351291427f8f650b0215c7ff00bddc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/network/supply-net/supply_allocation.jl", "max_issues_repo_name": "edxu96/MatrixOptim", "max_issues_repo_head_hexsha": "97ef8b1311351291427f8f650b0215c7ff00bddc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/network/supply-net/supply_allocation.jl", "max_forks_repo_name": "edxu96/MatrixOptim", "max_forks_repo_head_hexsha": "97ef8b1311351291427f8f650b0215c7ff00bddc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-04T09:41:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-04T09:41:13.000Z", "avg_line_length": 16.3421052632, "max_line_length": 72, "alphanum_fraction": 0.460547504, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966641739773, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7888222840556549}}
{"text": "#The key to the non-parametric method describedhere \n#is that the sum of squared distances between pointsand \n#their centroid is equal to (and can be calculateddirectly from) \n#the sum of squared interpoint distancesdivided by the number of points\n# https://onlinelibrary.wiley.com/doi/epdf/10.1111/j.1442-9993.2001.01070.pp.x\nSSₜ(D,N) = sum(D .^2)/N # given a triangular dist matrix\nfunction SS_W(D,N,n)\n    return  SSₜ(D,N)/n\nend\n\nfunction F(D,W,N,n,a)\n    SST = SSₜ(D,N)\n    SSW = SS_W(W,N,n)\n    A = SST - SSW\n    F = (A/(a-1))/(W/(N-a))\nend\n\npermutest(D,group,N,n,a, n_perm = 1000)\n    N =  length(group)\n    a = length(unique(group))\n    n = N/a\n    W_inds = [CartesianIndex(i,j) for i in 1:(N-1) for j in i+1:N if group[i] == group[j]]\n    W = D[W_inds]\n    notW = D[.!W_inds]\n    D = vcat(W,notW)\n    \n\n    f = F(D,W,N,n,a)\n    Fs = Vector{Float64}(undef,n_perm)\n    inds = 1:length(W)\n\n    for i in 1:n_perm\n        shuffle!.(D)\n        Fs[i] = Fknown(view(D,inds),N,n,a)\n    end\n    P = sum(Fs .>= f)/n_perm\n    return P\nend\n\n\n", "meta": {"hexsha": "0b119b45a9e57e51ab9e3e07852ed905e5225d72", "size": 1037, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "hydra1.jl", "max_stars_repo_name": "EvoArt/Hydra", "max_stars_repo_head_hexsha": "eb7927d7878485fdd48a155f3f43555e4f46e2ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hydra1.jl", "max_issues_repo_name": "EvoArt/Hydra", "max_issues_repo_head_hexsha": "eb7927d7878485fdd48a155f3f43555e4f46e2ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-03T20:32:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T23:36:05.000Z", "max_forks_repo_path": "hydra1.jl", "max_forks_repo_name": "EvoArt/Hydra", "max_forks_repo_head_hexsha": "eb7927d7878485fdd48a155f3f43555e4f46e2ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2926829268, "max_line_length": 90, "alphanum_fraction": 0.6113789778, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966656805269, "lm_q2_score": 0.8333245953120234, "lm_q1q2_score": 0.7888222833519358}}
{"text": "\n#=\ndef sample_actual_demand(price): \n    avg_demand = 65 + (-0.8) * price\n    theta = 0.1/4\n    k = avg_demand / theta\n    return np.random.gamma(k*theta, k*theta**2, 1)[0]\n=#\n\nfunction sample_actual_demand(price)\n    avg_demand = 65 + (-0.8) * price\n    theta = 0.1/4\n    k = avg_demand / theta\n    return rand(Gamma(k*theta, k*theta^2), 1)\nend\n\n#=\ndef emperical_mean(sampler, n): \n    mean = 0 \n    for i in range(1, n): \n        mean = mean + sampler() \n    return mean/n\n=#\n\nfunction emperical_mean(sampler, n)\n    mean = 0\n    for i in 1:n-1\n        mean += sampler()[1]\n    end\n    return mean / n\nend\n\n\n#=\ndef emperical_demand_curve(min_price, max_price, n): \n    prices = np.linspace(min_price, max_price, n) \n    sampling = 5000 \n    demands = map(lambda p: emperical_mean(functools.partial(sample_actual_demand, p), sampling), prices) \n    return np.dstack((prices, list(demands)))[0]\n=#\n\nfunction emperical_demand_curve(min_price, max_price, n)\n    prices = range(min_price, max_price, length=n) \n    sampling = 5000\n    demands = []\n    for p in prices\n        sampler() = sample_actual_demand(p)\n        demands = append!(demands, emperical_mean(sampler, sampling))\n    end\n    return DataFrame(\n        :prices => prices,\n        :demands => demands\n        )\nend\n\n", "meta": {"hexsha": "5cbc65126f5439191e4f969f12444653773fbfe2", "size": 1280, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "approaches/dynamic_pricing/actual_demand/actual_demand_curve.jl", "max_stars_repo_name": "StatisticalRethinkingJulia/DynamicPricingExamples.jl", "max_stars_repo_head_hexsha": "a6fae1736bf30f7aeed22452630c3ca3f018c50a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-02-19T06:59:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T07:57:57.000Z", "max_issues_repo_path": "approaches/dynamic_pricing/actual_demand/actual_demand_curve.jl", "max_issues_repo_name": "StatisticalRethinkingJulia/DynamicPricingExamples.jl", "max_issues_repo_head_hexsha": "a6fae1736bf30f7aeed22452630c3ca3f018c50a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "approaches/dynamic_pricing/actual_demand/actual_demand_curve.jl", "max_forks_repo_name": "StatisticalRethinkingJulia/DynamicPricingExamples.jl", "max_forks_repo_head_hexsha": "a6fae1736bf30f7aeed22452630c3ca3f018c50a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8571428571, "max_line_length": 106, "alphanum_fraction": 0.625, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603708, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.788801830206138}}
{"text": "#############################\n##  Numerical experiments associated with section 5.3\n#############################\n## This file contains the numerical experiments used for the highly oscillatory Bessel kernel example,\n## which was originally featured by Nick Hale in https://doi.org/10.1093/imanum/dry042\n##\n\nusing ApproxFun, MultivariateOrthogonalPolynomials, BandedMatrices, BlockBandedMatrices, SpecialFunctions, Plots\nusing SparseVolterraExamples\n\n####\n## First we define the Kernel and g(x) as in section 5.3.\n## As mentioned in the paper, it is sensible to use pre-existing implementations to compute the Bessel functions\nKfun(x,y)=besselj(μ,ω*(x-y))\ng(x) = besselj(μ+ν,ω*x)+1/(2*x^2)*((ν-1)*(ν-2)*besselj(ν-1,ω*x)+(ν+1)*(ν+2)*besselj(ν+1,ω*x))\n\n#####\n## Solver function with step-by-step explanation for given polynomial degree 'n'\n## Note the factor 10^(-3) placed as discussed in the paper.\nfunction solveSec54(n,g,Kfun,ν,μ,ω)\n    gF = Fun(x->g(x),Jacobi(2,3, 0..1))\n    V = triVolterraFullKernelOpP01(Kfun,n+2,true,339)\n        V = reflectPabtoPba(n+2)*WLoweringP01P00(n+2)*V[1:n+2,1:n+2]\n        V = Conversion(Jacobi(0,0,0..1),Jacobi(2,3,0..1))[1:n+2,1:n+2]*V[1:n+2,1:n+2]\n        V = 10^(-3)*Derivative(Jacobi(0,1,0..1),2)[1:n+2,1:n+2]+ω^2*Conversion(Jacobi(0,1,0..1),Jacobi(2,3,0..1))[1:n+2,1:n+2]+ω*V\n    coeff = [DirectEvalLHSP10at0(n+2);DirectEvalLHSP10atPrime0(n+2)*Derivative(Jacobi(0,1,0..1),1)[1:n+2,1:n+2];V[1:n,1:n+2]] \\ [0.0;0.0;pad(gF.coefficients,n)]\n    return Fun(Jacobi(0,1, 0..1), coeff)\nend\n\n####\n## Compute the solution with same parameters as discussed by Hale and in our paper\n## This correponds to computing the solution in Figure 7(a).\nν = 3\nμ = 2\nω = 20\nu = solveSec54(2000,g,Kfun,ν,μ,ω)\nplot(u,color=:black, legend=:false, xlabel = \"x\", ylabel = \"u(x)\", legendfontsize=12, tickfontsize=10, thickness_scaling = 1 , grid=:none)\n\n####\n## A basic loop to compute errors between the above high order solution and increasingly accurate approximations\nfunction errorvals(max,step,u)\n    errorvec = []\n    for n=10:step:max\n        diff = maximum(abs.([maximum(solveSec54(n,g,Kfun,ν,μ,ω)-u),minimum(solveSec54(n,g,Kfun,ν,μ,ω)-u)]))\n        errorvec = push!(errorvec,diff)\n    end\n    return errorvec\nend\n####\n## Plot successive errors to produce something like Figure 7(b). The exact shape of the plot depends on how dense we make the steps in n.\n## Note that for low polynomial orders, since the order is too low to resolve the oscillations, the error varies a lot.\n## Only once the polynomial order can resolve the oscillations do we see sensible convergence.\nerrorvec = errorvals(450,40,u)\nplot(Array(10:40:450),errorvec,color=:black, legend=:bottomleft , yscale=:log10 , xlabel = \"n\", label=\"sparse method\" , ylabel = \"error\", legendfontsize=12, tickfontsize=10, thickness_scaling = 1.2 , grid=:none)\n", "meta": {"hexsha": "17cbf00a04e84b1d08cd878e9de361799463e9f2", "size": 2834, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Section 5-3 - Bessel kernels with highly oscillatory solutions.jl", "max_stars_repo_name": "TSGut/SparseVolterraExamples.jl", "max_stars_repo_head_hexsha": "277733c70dfe78b65d1d9ad289de9dbeacda27b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-18T16:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T16:58:42.000Z", "max_issues_repo_path": "examples/Section 5-3 - Bessel kernels with highly oscillatory solutions.jl", "max_issues_repo_name": "TSGut/SparseVolterraExamples.jl", "max_issues_repo_head_hexsha": "277733c70dfe78b65d1d9ad289de9dbeacda27b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-09T15:39:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T15:59:37.000Z", "max_forks_repo_path": "examples/Section 5-3 - Bessel kernels with highly oscillatory solutions.jl", "max_forks_repo_name": "TSGut/SparseVolterraExamples.jl", "max_forks_repo_head_hexsha": "277733c70dfe78b65d1d9ad289de9dbeacda27b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.5272727273, "max_line_length": 211, "alphanum_fraction": 0.6859562456, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7888018247737312}}
{"text": "function eye(tpe::Type,n::S) where {S <: Integer}\n\n    if tpe <: Number\n        return Matrix{tpe}(I,n,n)\n    end\n\nend\n\neye(n::Integer) = eye(Float64,n::Integer)\n\nfunction tracem(x::Array{T,2}) where {T <: Real}\n\n  # Computes the matrix-trace as defined by Gomme and Klein (2011)\n\n  # We require the number of rows to be greater than the number of columns, so\n  # that m is greater than one.\n\n  trans = false\n\n  if size(x,1) < size(x,2)\n    x = Matrix(x')\n    trans = true\n  end\n\n  n = size(x,2)\n  m = Int(size(x,1)/n)\n\n  y = zeros(m,1)  # We want this to be a 2-d array for subsequent matrix multiplication\n\n  @inbounds for i = 1:m\n    @views y[i,1] = tr(x[(n*(i-1)+1):i*n,1:n])\n  end\n\n  if trans == true\n    y = y'\n  end\n\n  return Matrix(y)\n\nend\n\nfunction kron_prod_times_vector(a::AbstractArray{T,2},b::AbstractArray{T,2},v::AbstractArray{T,1}) where {T <: Real}\n\n    # This function efficiently computes kron(a,b)*v where a and b are matrices\n    # and v is a vector.\n\n    (n1,n2) = size(a)\n    (n3,n4) = size(b)\n    n5      = length(v)\n\n    if n5 != n2*n4\n        error(\"a, b, and v do not have the correct sizes\")\n    end\n\n    p = vec(b*reshape(v,n4,n2)*a')\n\n    return p\n\nend\n\nfunction vector_times_kron_prod(v::AbstractArray{T,1},a::AbstractArray{T,2},b::AbstractArray{T,2}) where {T <: Real}\n\n    product = Matrix(kron_prod_times_vector(a',b',v')')\n\n    return product\n\nend\n\nfunction kron_prod_times_matrix(a::AbstractArray{T,2},b::AbstractArray{T,2},v::AbstractArray{T,2}) where {T <: Real}\n\n    # This function efficiently computes kron(a,b)*v where a, b, and v are\n    # conformable matrices.\n\n    (n1,n2) = size(a)\n    (n3,n4) = size(b)\n    (n5,n6) = size(v)\n\n    if n5 != n2*n4\n        error(\"a, b, and v do not have the correct sizes\")\n    end\n\n    p = zeros(n1*n3,n6)\n    for i = 1:n6\n        @views p[:,i] = kron_prod_times_vector(a,b,v[:,i])\n    end\n\n    return p\n\nend\n\nfunction matrix_times_kron_prod(v::AbstractArray{T,2},a::AbstractArray{T,2},b::AbstractArray{T,2}) where {T <: Real}\n\n    product = Matrix(kron_prod_times_matrix(a',b',v')')\n\n    return product\n\nend\n\nfunction kron_prod_times_vector(a::AbstractArray{T,2},b::AbstractArray{T,2},c::AbstractArray{T,2},v::AbstractArray{T,1}) where {T <: Real}\n\n    # This function efficiently computes kron(a,kron(b,c))*v where a, b, and c\n    # are matrices and v is a vector.  Included for completeness, but not\n    # actually used.\n\n    (n1,n2) = size(a)\n    (n3,n4) = size(b)\n    (n5,n6) = size(c)\n    n7      = length(v)\n\n    if n7 != n2*n4*n6\n        error(\"a, b, c, and v do not have the correct sizes\")\n    end\n\n    v_tilda = reshape(v,n4*n6,n2)*a'\n    p = vec(kron_prod_times_matrix(b,c,v_tilda))\n\n    return p\n\nend\n\nfunction vector_times_kron_prod(v::AbstractArray{T,1},a::AbstractArray{T,2},b::AbstractArray{T,2},c::AbstractArray{T,2}) where {T <: Real}\n\n    product = Matrix(kron_prod_times_vector(a',b',c',v')')\n\n    return product\n\nend\n\nfunction kron_prod_times_matrix(a::AbstractArray{T,2},b::AbstractArray{T,2},c::AbstractArray{T,2},v::AbstractArray{T,2}) where {T <: Real}\n\n    # This function efficiently computes kron(a,kron(b,c))*v where a, b, c and\n    # v are comformable matrices.\n\n    (n1,n2) = size(a)\n    (n3,n4) = size(b)\n    (n5,n6) = size(c)\n    (n7,n8) = size(v)\n\n    if n7 != n2*n4*n6\n        error(\"a, b, c, and v do not have the correct sizes\")\n    end\n\n    p = zeros(n1*n3*n5,n8)\n    for i = 1:n8\n        @views v_tilda = reshape(v[:,i],n4*n6,n2)*a'\n        p[:,i] .= vec(kron_prod_times_matrix(b,c,v_tilda))\n    end\n\n    return p\n\nend\n\nfunction matrix_times_kron_prod(v::AbstractArray{T,2},a::AbstractArray{T,2},b::AbstractArray{T,2},c::AbstractArray{T,2}) where {T <: Real}\n\n    product = Matrix(kron_prod_times_matrix(a',b',c',v')')\n\n    return product\n\nend\n\nfunction dsylvester(a::AbstractArray{T,2}, b::AbstractArray{T,2}, c::Union{AbstractArray{T,1},AbstractArray{T,2}}) where {T <: Real}\n\n    #= Uses the Hessenberg-Schur method to find the bounded solution of the\n       discrete Sylvester equation:\n\n             X + A*X*B = C\n\n       Based on Golub, Nash, and Van Loan (1979).\n\n    =#\n\n    n = size(a, 1)\n    m = size(b, 1)\n    x = zeros(size(c))\n\n    (s,u) = schur(Matrix(b'))\n    (v,t) = hessenberg(a)\n\n    c = v'*c*u\n\n    j = m\n    while j > 0\n        j1 = j\n        if j == 1\n            block_size = 1\n        elseif isequal(s[j,j-1],0.0) == false\n            block_size = 2\n            j -= 1\n        else;\n            block_size = 1\n        end\n        @views ajj = kron(s[j:j1,j:j1],t) + I\n        @views rhs = vec(c[:,j:j1])\n        if j1 < m\n            @views rhs2 = t*(x[:,(j+1):m]*s[j:j1,(j+1):m]')\n            rhs -= vec(rhs2)\n        end\n        w = ajj\\rhs\n        @views x[:,j] = w[1:n]\n        if block_size == 2\n            @views x[:,j1] = w[(n+1):2*n]\n        end\n        j -= 1\n    end\n\n    x = v*x*u'\n\n    return x\n\nend\n\nfunction trm(x::AbstractArray{T,2}) where {T <: Real}\n\n    # Computes the matrix trace as defined by Binning (2013).  Used for\n    # computing the second-order terms, hss, gss.\n\n    (n1,n2) = size(x)\n    k = Int(round(sqrt(n2)))\n\n    y = zeros(n1)\n    for i = 1:k\n        @views y += x[:,i+(i-1)*k]\n    end\n\n    return y\n\nend\n\nfunction trm2(x::AbstractArray{T,2}) where {T <: Real}\n\n    # Computes the matrix trace as defined by Binning (2013).  Used for\n    # computing the third-order terms, hssx, gssx.\n\n    (n1,n2) = size(x)\n    k = Int(round(n2^(1//3)))\n\n    y = zeros(n1,k)\n    for j = 1:k\n        for i = 1:k\n            @views y[:,j] += x[:,(j-1)+i+(i-1)*k^2]\n        end\n    end\n\n    return y\n\nend\n\nfunction create_omega3(n::S) where {S <: Integer}\n\n    # Creates the combination matrix for a third-order perturbation as defined in Levintal (2017).\n\n    # This function is a simplified version of the create_OMEGA function originally written in\n    # Matlab by Oren Levintal for his paper \"Fifth Order Perturbation Solution to DSGE Models\"\n    # published in the Journal of Economic Dynamics and Control, 2017.  Permission to translate\n    # this function into Julia and release it within the SolveDSGE module was granted by Oren\n    # Levintal on February 5, 2020.\n\n    ind = [1:n^3;]\n    M = reshape(ind,1,n,n,n)\n    Ix = eye(S,n^3)\n    omega3 = (reshape(Ix[:,PermutedDimsArray(M,[1,4,2,3])],n^3,n^3)\n           + reshape(Ix[:,PermutedDimsArray(M,[1,2,4,3])],n^3,n^3)\n           + reshape(Ix[:,PermutedDimsArray(M,[1,2,3,4])],n^3,n^3))\n\n    return omega3\n\nend\n\nfunction kron_prod_times_vector(A::Union{Array{Array{T,2},1},Array{Array{Complex{T},2},1}},x::Union{Array{T,1},Array{Complex{T},1}},n::Array{S,1},p::S) where {T <: Real, S <: Integer}\n\n    # Computes y = (A[p] * A[p-1] * ... * A[1] )*x\n\n    N = prod(n[1:p])\n    z = copy(x)\n    for i = 1:p\n        z = (A[i]*reshape(z,n[i],Int(N/n[i])))'\n    end\n    y = reshape(Matrix(z),N)\n\n    return y\n\nend\n\nfunction kron_prod_times_matrix(A::Union{Array{Array{T,2},1},Array{Array{Complex{T},2},1}},x::Union{Array{T,2},Array{Complex{T},2}},n::Array{S,1},p::S) where {T <: Real, S <: Integer}\n\n    # Computes y = (A[p] * A[p-1] * ... * A[1] )*x\n\n    N = prod(n[1:p])\n    y = Array{Complex{T}}(undef,N,size(x,2))\n    for j = 1:size(x,2)\n        @views z = x[:,j]\n        for i = 1:p\n            z = (A[i]*reshape(z,n[i],Int(N/n[i])))'\n        end\n        y[:,j] .= reshape(Matrix(z),N)\n    end\n\n    return y\n\nend\n\nfunction KPShiftSolve(TT::Union{Array{Array{T,2},1},Array{Array{Complex{T},2},1}},n::Array{S,1},c::Union{Array{T,1},Array{Complex{T},1}},lambda::T,alpha::Union{T,Complex{T}}) where {T <: Real, S <: Integer}\n\n    p = length(n)\n    N = prod(n)\n\n    c = copy(c)\n\n    TT[p] = alpha*TT[p]\n    if p == 1\n        y = (TT[1] + lambda*Matrix{T}(I,n[1],n[1]))\\c\n    else\n        y = Array{Complex{T}}(undef,N)\n        mp = Int(N/n[p])\n        for i = n[p]:-1:1\n            idx = ((i-1)*mp+1):(i*mp)\n            y[idx] = KPShiftSolve(TT[1:(p-1)],n[1:(p-1)],c[idx],lambda,TT[p][i,i])\n            z = kron_prod_times_vector(TT[1:p],y[idx],n,p-1)\n            for j = 1:(i-1)\n                jdx = ((j-1)*mp+1):(j*mp)\n                c[jdx] = c[jdx] - TT[p][j,i]*z\n            end\n        end\n    end\n\n    return y\n\nend\n\nfunction martin_van_loan(a::Array{T,2},b::Array{T,2},c::Array{T,2},d::Array{T,2},k::S) where {T <: Real, S <: Integer}\n\n    #= Uses a recursive Schur method to find the bounded solution of the Sylvester\n       equation:\n\n       AX + B*X*(Kron^(k)C) = D\n\n       Based on Martin and Van Loan (2006).  This is a simplified implementation\n       of their algorithm, but it captures most of the gains over Golub, Nash,\n       and van Loan (1979).\n\n    =#\n\n    a = copy(a)\n    b = a\\copy(b)\n    c = copy(c)\n    d = a\\copy(d)\n\n    (v,s) = hessenberg(b)       # v*s*v' = b\n    (t,q) = schur(complex(c'))  # q*t*q' = c'\n\n    v = Matrix(v)\n\n    p = k + 2\n    TT = Array{typeof(t)}(undef,p)\n    TT[1] = s\n    for i = 2:p\n        TT[i] = conj(t)\n    end\n\n    Q     = fill(q,k+1)\n    inv_Q = fill(Matrix(q'),k+1)\n\n    n = fill(size(c,1),p)\n    n[1] = size(b,1)\n    N = prod(n)\n\n    lambda = 1.0\n\n    e = vec(v'*kron_prod_times_matrix(inv_Q,Matrix(d'),n[2:end],k+1)')\n\n    y = reshape(KPShiftSolve(TT,n,e,lambda,1.0),size(d))\n    x = real(Matrix(v*kron_prod_times_matrix(Q,Matrix(y'),n[2:end],k+1)'))\n\n    return x\n\nend\n\nfunction dlyap(a::Array{T,2}, b::Array{T,2}) where {T <: Real}\n\n    n = size(a,1)\n    x = zeros(n,n)\n    j = n\n\n    (s,u) = schur(a)\n    b = u'b*u\n\n    while j > 0\n        j1 = j\n        if j == 1\n            block = 1\n        elseif !isequal(s[j,j-1],0.0)\n            block = 2\n            j -= 1\n        else\n            block = 1\n        end\n        @views lhs = kron(s[j:j1,j:j1],s) - I # I = eye(block*n)\n        @views rhs = vec(b[:,j:j1])\n        if j1 < n\n            @views rhs2 = s*(x[:,(j1+1):n]*s[j:j1,(j1+1):n]')\n            rhs += vec(rhs2)\n        end\n        w = -lhs\\rhs\n        @views x[:,j] = w[1:n]\n        if block == 2\n            @views x[:,j1] = w[(n+1):block*n]\n        end\n        j -= 1\n    end\n\n    x = u*x*u'\n\n    return x\n\nend\n\nfunction ind2sub(i::S,dims::Tuple{S,Vararg{S}}) where {S <: Integer}\n\n    if i < 1 || i > prod(dims)\n        error(\"index is out of bounds.\")\n    end\n\n    subs = Tuple(CartesianIndices(dims)[i])\n\n    return subs\n\nend\n\nfunction compute_variances(soln::FirstOrderSolutionStoch)\n\n    hx = soln.hx\n    k = soln.k\n    gx = soln.gx\n    sigma = soln.sigma\n\n    var_states = dlyap(hx,k*sigma*k')\n    var_jumps  = gx*var_states*gx'\n\n  return var_states,var_jumps\n\nend\n\nfunction compute_chebyshev_integrals(eps_nodes,eps_weights,nodes,order,rho,sigma)\n\n  # A simplified implementation of the integration described in Judd et al (2017, section 5.1);\n  # it uses the mean integral across the nodes.\n  # Using integrals[i] = sum(exp.(sqrt(2)*sigma*(i-1)*eps_nodes).*eps_weights)*pi^(-1/2)\n  # leads to something much simplier and equally accurate, but is less recognizably appropriate\n  # for the case where the shocks are AR(1) processes and ordinary polynomials are not being used.\n\n  terms_num  = Array{Float64}(undef,length(eps_nodes))\n  integrals  = Array{Float64}(undef,order+1,length(nodes))\n  integrals2 = Array{Float64}(undef,order+1)\n  for i = 1:(order+1)\n    integrals2[i] = sum(exp.(sqrt(2)*sigma*(i-1)*eps_nodes).*eps_weights)*pi^(-1/2)\n    for j = 1:length(nodes)\n      terms_num     .= rho*nodes[j] .+ sqrt(2)*sigma*eps_nodes\n      terms_den      = rho*nodes[j]\n      terms_num     .= chebyshev_polynomial(i,terms_num)[:,i]\n      terms_den      = chebyshev_polynomial(i,terms_den)[i]\n      integrals[i,j] = sum((terms_num/terms_den).*eps_weights)*pi^(-1/2)\n     end\n  end\n\n  nodetoosmall = abs.(nodes) .< sqrt(eps())\n  if sum(nodetoosmall) > 0\n    if length(nodes) == 1\n      integrals[:,1] .= integrals2\n    else\n      for i = 1:length(nodes)\n        if nodetoosmall[i] == 1\n          if i == 1\n            integrals[:,i] .= integrals[:,i+1]\n        elseif i == length(nodes)\n            integrals[:,i] .= integrals[:,i-1]\n          else\n            integrals[:,i] .= (integrals[:,i-1]+integrals[:,i+1])/2\n          end\n        end\n      end\n    end\n  end\n\n  return reshape(sum(integrals,dims=2)/length(nodes),order+1)\n\n#  integrals = Array{Float64}(undef,order+1)\n#  for i = 1:(order+1)\n#    integrals[i] = sum(exp.(sqrt(2)*sigma*(i-1)*eps_nodes).*eps_weights)*pi^(-1/2)\n#  end\n#  return integrals\n\nend\n\nfunction compute_smolyak_integrals(eps_nodes,eps_weights,nx,order,grid,RHO,sigma)\n\n  integrals = ones(nx,order+1)\n  for j = 1:size(sigma,2)\n      nodes = unique(grid[:,j])\n      integrals[j,:] .= compute_chebyshev_integrals(eps_nodes,eps_weights,nodes,order,RHO[j,j],sigma[j,j])\n  end\n\n#  for j = 1:size(sigma,2)\n#      for i = 1:(order+1)\n#          integrals[j,i] = sum(exp.(sqrt(2)*sigma[j,j]*(i-1)*eps_nodes).*eps_weights)*pi^(-1/2)\n#      end\n#  end\n\n  return integrals\n\nend\n\nfunction weight_scale_factors(eps_nodes,eps_weights,multi_index,nx,grid,RHO,sigma)\n\n  unique_multi_index = sort(unique(multi_index))\n  unique_orders = SmolyakApprox.m_i(unique_multi_index).-1\n\n  # Here we construct the base integrals\n\n  base_integrals = Array{Array{Float64,2}}(undef,length(unique_orders))\n  for i = 1:length(unique_orders)\n    base_integrals[i] = compute_smolyak_integrals(eps_nodes,eps_weights,nx,unique_orders[i],grid,RHO,sigma)\n  end\n\n  # Compute the unique polynomial terms from the base polynomials\n\n  unique_base_integrals = Array{Array{Float64,2}}(undef,length(unique_orders))\n  for i = length(unique_orders):-1:2\n    unique_base_integrals[i] = base_integrals[i][:,size(base_integrals[i-1],2)+1:end]\n  end\n  unique_base_integrals[1] = base_integrals[1]\n\n  # Construct the first row of the interplation matrix\n\n  new_integrals = unique_base_integrals[multi_index[1,1]][1,:]\n  for i = 2:size(multi_index,2)\n    new_integrals = kron(new_integrals,unique_base_integrals[multi_index[1,i]][i,:])\n  end\n\n  weight_scale_factor = copy(new_integrals)\n\n  # Iterate over nodes, doing the above three steps at each iteration\n\n  for j = 2:size(multi_index,1)\n\n    new_integrals = unique_base_integrals[multi_index[j,1]][1,:]\n    for i = 2:size(multi_index,2)\n      new_integrals = kron(new_integrals,unique_base_integrals[multi_index[j,i]][i,:])\n    end\n    weight_scale_factor = [weight_scale_factor; new_integrals]\n\n  end\n\n  return weight_scale_factor\n\nend\n\nfunction scale_weights(weights,weight_scale_factor)\n\n    scaled_weights = weights.*weight_scale_factor\n\n    return scaled_weights\n\nend\n\nfunction compute_piecewise_linear_integrals(eps_nodes,eps_weights,sigma)\n\n  integral = 1.0\n  #integral = sum(exp.(sqrt(2)*sigma*eps_nodes).*eps_weights)*pi^(-1/2)\n\n  return integral\n\nend\n", "meta": {"hexsha": "a61ce2070c0bfa3913ee823f701377125feb3fc2", "size": 14580, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/auxiliary_functions.jl", "max_stars_repo_name": "azev77/SolveDSGE.jl", "max_stars_repo_head_hexsha": "41245dd87389ba322f26db8f7779bdc2dd0a963e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/auxiliary_functions.jl", "max_issues_repo_name": "azev77/SolveDSGE.jl", "max_issues_repo_head_hexsha": "41245dd87389ba322f26db8f7779bdc2dd0a963e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/auxiliary_functions.jl", "max_forks_repo_name": "azev77/SolveDSGE.jl", "max_forks_repo_head_hexsha": "41245dd87389ba322f26db8f7779bdc2dd0a963e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.445026178, "max_line_length": 206, "alphanum_fraction": 0.5943072702, "num_tokens": 4854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915912, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.78880182229421}}
{"text": "\"\"\"\n    eom_linear3d_nonlinearcoupling(x, p, n) -> Function\n\n\nEquations of motion for a 3d linear system with nonlinear coupling [1].\nThe difference equations are\n\n```math\n\\\\begin{aligned}\nx_1(t+1) &= a_1 x_1 (1-x_1(t))^2  e^{-x_2(t)^2} + 0.4 \\\\xi_{1}(t) \\\\\nx_2(t+1) &= a_1 x_2 (1-x_2(t))^2  e^{-x_2(t)^2} + 0.4 \\\\xi_{2}(t) + b x_1 x_2 \\\\\nx_3(t+1) &= a_3 x_3 (1-x_3(t))^2  e^{-x_3(t)^2} + 0.4 \\\\xi_{3}(t) + c x_{2}(t) \\\\\n         &+ d x_{1}(t)^2.\n\\\\end{aligned}\n```\n\nHere, ``\\\\xi_{1,2,3}(t)`` are independent normally distributed noise processes,\nrepresenting dynamical noise in the system, with zero mean and standard\ndeviations ``\\\\sigma_1``, ``\\\\sigma_2``, ``\\\\sigma_3``, respectively.\n\n\n# References\n1. Gourévitch, B., Le Bouquin-Jeannès, R., & Faucon, G. (2006). Linear and\nnonlinear causality between signals: methods, examples and neurophysiological\napplications. Biological Cybernetics, 95(4), 349–369.\n\"\"\"\nfunction eom_linear3d_nonlinearcoupling(x, p, n)\n    x₁, x₂, x₃ = (x...,)\n    a₁, a₂, a₃, b, c, d, σ₁, σ₂, σ₃ = (p...,)\n    ξ₁ = rand(Normal(0, σ₁))\n    ξ₂ = rand(Normal(0, σ₂))\n    ξ₃ = rand(Normal(0, σ₃))\n\n    dx₁ = a₁*x₁*(1-x₁)^2 * exp(-x₁^2) + 0.4*ξ₁\n    dx₂ = a₂*x₂*(1-x₂)^2 * exp(-x₂^2) + 0.4*ξ₂ + b*x₁*x₂\n    dx₃ = a₃*x₃*(1-x₃)^2 * exp(-x₃^2) + 0.4*ξ₃ + c*x₂ + d*x₁^2\n\n    return SVector{3}(dx₁, dx₂, dx₃)\nend\n\n\nfunction linear3d_nonlinearcoupling(uᵢ, a₁, a₂, a₃, b, c, d, σ₁, σ₂, σ₃)\n    p = [a₁, a₂, a₃, b, c, d, σ₁, σ₂, σ₃]\n    s = DiscreteDynamicalSystem(eom_linear3d_nonlinearcoupling, uᵢ, p)\n    return s\nend\n\n\"\"\"\n    linear3d_nonlinearcoupling(;uᵢ = rand(3), σ₁ = 1.0, σ₂ = 1.0, σ₃ = 1.0,\n        a₁ = 3.4, a₂ = 3.4, a₃ = 3.4, b = 0.5, c = 0.3, d = 0.5) -> DiscreteDynamicalSystem\n\nA 3d linear system with nonlinear coupling [1]. The difference equations are\n\n```math\n\\begin{aligned}\nx_1(t+1) &= a_1 x_1 (1-x_1(t))^2  e^{-x_2(t)^2} + 0.4 \\\\xi_{1}(t) \\\\\nx_2(t+1) &= a_1 x_2 (1-x_2(t))^2  e^{-x_2(t)^2} + 0.4 \\\\xi_{2}(t) + b x_1 x_2 \\\\\nx_3(t+1) &= a_3 x_3 (1-x_3(t))^2  e^{-x_3(t)^2} + 0.4 \\\\xi_{3}(t) + c x_{2}(t) \\\\\n         &+ d x_{1}(t)^2.\n\\end{aligned}\n```\n\nHere, ``\\\\xi_{1,2,3}(t)`` are independent normally distributed noise processes,\nrepresenting dynamical noise in the system, with zero mean and standard\ndeviations ``\\\\sigma_1``, ``\\\\sigma_2``, ``\\\\sigma_3``, respectively.\n\n\n# References\n1. Gourévitch, B., Le Bouquin-Jeannès, R., & Faucon, G. (2006). Linear and\nnonlinear causality between signals: methods, examples and neurophysiological\napplications. Biological Cybernetics, 95(4), 349–369.\n\"\"\"\nlinear3d_nonlinearcoupling(;uᵢ = rand(3), σ₁ = 1.0, σ₂ = 1.0, σ₃ = 1.0,\n        a₁ = 3.4, a₂ = 3.4, a₃ = 3.4, b = 0.5, c = 0.3, d = 0.5) =\n    linear3d_nonlinearcoupling(uᵢ, a₁, a₂, a₃, b, c, d, σ₁, σ₂, σ₃)\n", "meta": {"hexsha": "8147f3b60f7501dfcd94a3e67f2af3e1ae1cb01b", "size": 2745, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/systems/discretemaps/linearmap3d_nonlinearcoupling.jl", "max_stars_repo_name": "tormolle/CausalityTools.jl", "max_stars_repo_head_hexsha": "b8c1014349358d8cdb5eddc1bcac9303f475d90b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/systems/discretemaps/linearmap3d_nonlinearcoupling.jl", "max_issues_repo_name": "tormolle/CausalityTools.jl", "max_issues_repo_head_hexsha": "b8c1014349358d8cdb5eddc1bcac9303f475d90b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/systems/discretemaps/linearmap3d_nonlinearcoupling.jl", "max_forks_repo_name": "tormolle/CausalityTools.jl", "max_forks_repo_head_hexsha": "b8c1014349358d8cdb5eddc1bcac9303f475d90b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1184210526, "max_line_length": 91, "alphanum_fraction": 0.6029143898, "num_tokens": 1252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7888018215979389}}
{"text": "\"\"\"\n    trianglecircumcenter(pt1::Point, pt2::Point, pt3::Point)\n\nReturn the circumcenter of the triangle defined by `pt1`,\n`pt2`, and `pt3`. The circumcenter is the center of a circle\nthat passes through the vertices of the triangle.\n\n\"\"\"\nfunction trianglecircumcenter(pt1::Point, pt2::Point, pt3::Point)\n    d = 2(pt1.x * (pt2.y - pt3.y) + pt2.x * (pt3.y - pt1.y) + pt3.x * (pt1.y - pt2.y))\n    x = ((pt1.x^2 + pt1.y^2) * (pt2.y - pt3.y) + (pt2.x^2 + pt2.y^2) * (pt3.y - pt1.y) + (pt3.x^2 + pt3.y * pt3.y) * (pt1.y - pt2.y)) / d\n    y = ((pt1.x^2 + pt1.y^2) * (pt3.x - pt2.x) + (pt2.x^2 + pt2.y^2) * (pt1.x - pt3.x) + (pt3.x^2 + pt3.y * pt3.y) * (pt2.x - pt1.x)) / d\n    return Point(x, y)\nend\n\n# \"\"\"\n#     trianglecircumcenter(pt1::Point, pt2::Point, pt3::Point)\n# \"\"\"\n# function trianglecircumcenter(pt1::Point, pt2::Point, pt3::Point)\n#     ap1, ap2 = perpendicular(pt1, pt2)\n#     bp1, bp2 = perpendicular(pt2, pt3)\n#     flag, ip = intersectionlines(ap1, ap2, bp1, bp2)\n#     if flag\n#         return ip\n#     else\n#         throw(error(\"trianglecircumcenter(): triangle is not valid\"))\n#     end\n# end\n\n\"\"\"\n    triangleincenter(pt1::Point, pt2::Point, pt3::Point)\n\nReturn the incenter of the triangle defined by `pt1`, `pt2`,\nand `pt3`. The incenter is the center of a circle inscribed\ninside the triangle.\n\"\"\"\nfunction triangleincenter(pt1::Point, pt2::Point, pt3::Point)\n    a = distance(pt2, pt3)\n    b = distance(pt1, pt3)\n    c = distance(pt1, pt2)\n    x = ((a * pt1.x) + (b * pt2.x) + (c * pt3.x)) / (a + b + c)\n    y = ((a * pt1.y) + (b * pt2.y) + (c * pt3.y)) / (a + b + c)\n    return Point(x, y)\nend\n\n\"\"\"\n    trianglecenter(pt1::Point, pt2::Point, pt3::Point)\n\nReturn the centroid of the triangle defined by `pt1`, `pt2`, and `pt3`.\n\"\"\"\nfunction trianglecenter(pt1::Point, pt2::Point, pt3::Point)\n    return 1/3 * (pt1 + pt2  + pt3)\nend\n\n\"\"\"\n    triangleorthocenter(pt1::Point, pt2::Point, pt3::Point)\n\nReturn the orthocenter of the triangle defined by `pt1`, `pt2`, and `pt3`.\n\"\"\"\nfunction triangleorthocenter(pt1::Point, pt2::Point, pt3::Point)\n    return pt1 + pt2 + pt3 - 2trianglecircumcenter(pt1, pt2, pt3)\nend\n", "meta": {"hexsha": "f1bdfc7354821d0c0621bdb8ea63aaecdbf568d3", "size": 2134, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/triangles.jl", "max_stars_repo_name": "guo-yong-zhi/Luxor.jl", "max_stars_repo_head_hexsha": "3b4fe34fe1e05c17bfcc9cc5b074fa527e5d1ebf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 463, "max_stars_repo_stars_event_min_datetime": "2017-01-07T00:48:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T07:06:58.000Z", "max_issues_repo_path": "src/triangles.jl", "max_issues_repo_name": "guo-yong-zhi/Luxor.jl", "max_issues_repo_head_hexsha": "3b4fe34fe1e05c17bfcc9cc5b074fa527e5d1ebf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 200, "max_issues_repo_issues_event_min_datetime": "2017-01-03T12:35:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T16:39:00.000Z", "max_forks_repo_path": "src/triangles.jl", "max_forks_repo_name": "guo-yong-zhi/Luxor.jl", "max_forks_repo_head_hexsha": "3b4fe34fe1e05c17bfcc9cc5b074fa527e5d1ebf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 86, "max_forks_repo_forks_event_min_datetime": "2017-01-15T17:36:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T13:55:02.000Z", "avg_line_length": 33.873015873, "max_line_length": 137, "alphanum_fraction": 0.6082474227, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8705972667296309, "lm_q1q2_score": 0.7887522613106813}}
{"text": "using Random, Statistics, Distributions, Plots; pyplot()\nRandom.seed!(0)\n\nmu, sig = 50, 5\ndist = Normal(mu, sig)\nalpha = 0.01\nnMax = 40\n\nobservations = rand(dist,1)\npiLarray, piUarray = [], []\n\nfor _ in 2:nMax\n    xNew = rand(dist)\n    push!(observations,xNew)\n\n    xbar, sd = mean(observations), std(observations)\n    n = length(observations)\n    tVal = quantile(TDist(n-1),1-alpha/2)\n    delta = tVal * sd * sqrt(1+1/n)\n    piL, piU = xbar - delta, xbar + delta\n    \n    push!(piLarray,piL); push!(piUarray,piU)\nend\n\nscatter(1:nMax, observations, \n\tc=:blue, msw=0, label=\"Observations\")\nplot!(2:nMax, piUarray, \n\tc=:red, shape=:xcross, msw=0, label=\"Prediction Interval\")\nplot!(2:nMax, piLarray, \n\tc=:red, shape=:xcross, msw=0, label=\"\", \n\tylims=(0,100), xlabel=\"Number of observations\", ylabel=\"Value\")", "meta": {"hexsha": "2be9150ffce347f01e6e4753a7c79d467e3ef0b1", "size": 805, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "6_chapter/predictionInterval.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "6_chapter/predictionInterval.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "6_chapter/predictionInterval.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 25.9677419355, "max_line_length": 64, "alphanum_fraction": 0.6534161491, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.8376199694135333, "lm_q1q2_score": 0.7887483268134617}}
{"text": "\"\"\"\n    second-order cone\n\"\"\"\nfunction second_order_cone_projection(z)\n    n = length(z)\n\n    z0 = z[1]\n    z1 = view(z, 2:n)\n\n    if norm(z1) <= z0\n        return z, true\n    elseif norm(z1) <= -z0\n        return zero(z), false\n    else\n        a = 0.5 * (1.0 + z0 / norm(z1))\n        z_proj = zero(z)\n        z_proj[1] = a * norm(z1)\n        z_proj[2:end] = a * z1\n        return z_proj, false\n    end\nend\n\nfunction second_order_cone_product(z, s)\n    n = length(z)\n    SVector{n}([z' * s; z[1] * view(s, 2:n) + s[1] * view(z, 2:n)])\nend\n\n# check that second-order cone constraints are satisfied\nfunction second_order_cone_check(x, idx_soc)\n    for idx in idx_soc\n        !second_order_cone_projection(view(x, idx))[2] && return false\n    end\n    return true\nend\n\n# check that inequality (non-negative orthant) constraints are satisfied\nfunction inequality_check(x, idx_ineq)\n    for i in idx_ineq\n        if x[i] <= 0.0\n            return false\n        end\n    end\n    return true\nend\n\nfunction cone_check(x, idx_ineq, idx_soc)\n    !inequality_check(x, idx_ineq) && return true\n    !second_order_cone_check(x, idx_soc) && return true\nend\n", "meta": {"hexsha": "869512aa2ff91bfe700dab0e10933ef677a2d849", "size": 1141, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/implicit_dynamics/solver/cones.jl", "max_stars_repo_name": "thowell/motion_planning", "max_stars_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2021-02-07T10:46:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:30:20.000Z", "max_issues_repo_path": "examples/implicit_dynamics/solver/cones.jl", "max_issues_repo_name": "thowell/DirectMotionPlanning", "max_issues_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-10-07T05:36:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-11T17:16:28.000Z", "max_forks_repo_path": "examples/implicit_dynamics/solver/cones.jl", "max_forks_repo_name": "thowell/motion_planning", "max_forks_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-01-25T19:23:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T06:43:01.000Z", "avg_line_length": 22.82, "max_line_length": 72, "alphanum_fraction": 0.6108676599, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541593883189, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7887483224594829}}
{"text": "import Remez\nusing SpecialFunctions: erfcx\nusing PyPlot\n\nT = Float64\n\nfunction g(y::T) where T <: AbstractFloat\n    two = parse(T, \"2\")\n    rootpi = sqrt(convert(T, π))\n    if -one(T) ≤ y ≤ -one(T) + eps(T)\n        return ( 1 / two - 1 / rootpi )\n    elseif one(T) - eps(T) ≤ y ≤ one(T)\n        return ( -1 + 1/rootpi ) / 2\n    else\n        x = (1+y) / (1-y)\n        return ( 2*erfcx(x) / (1-y) - 1 ) / (1+y)\n    end\nend\n\nfunction erfcx_approx(x)\n    y = (x-1) / (x+1)\n    return (1-y)*(1+(1+y)*g_approx(y)) / 2\nend\n\nn = 15\niterations = 6\npt, ddp, E = Remez.minimax(T, g, n, iterations)\n\ng_approx(y) = Remez.Newton_poly(ddp[0:n], pt[0:n], y)\n\nfigure(1)\ny = range(-one(T), one(T), length=201)\n\nplot(y, g.(y))\ngrid(true)\nxlabel(L\"$y$\")\nylabel(L\"$g(y)$\")\n\nfigure(2)\nplot(y, g.(y)-g_approx.(y))\ngrid(true)\nxlabel(L\"$y$\")\nylabel(L\"error in $g$\")\n\nfigure(3)\nx = range(0, 10, length=201)\nplot(x, erfcx_approx.(x) - erfcx.(x))\ngrid(true)\nxlabel(L\"$x$\")\nylabel(\"error in erfcx\")\n", "meta": {"hexsha": "fe5017aea464741f5bbf9ae9ff316c97fb99c6ef", "size": 970, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/erfcx_Remez.jl", "max_stars_repo_name": "billmclean/MittagLefflerFunctions.jl", "max_stars_repo_head_hexsha": "5244e7fce7efeee160edfc76eb7cab5e7624ae8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/erfcx_Remez.jl", "max_issues_repo_name": "billmclean/MittagLefflerFunctions.jl", "max_issues_repo_head_hexsha": "5244e7fce7efeee160edfc76eb7cab5e7624ae8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/erfcx_Remez.jl", "max_forks_repo_name": "billmclean/MittagLefflerFunctions.jl", "max_forks_repo_head_hexsha": "5244e7fce7efeee160edfc76eb7cab5e7624ae8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0196078431, "max_line_length": 53, "alphanum_fraction": 0.5597938144, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633821, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7887084805392893}}
{"text": "using FdeSolver\nusing Plots\n\n## inputs\ntSpan = [0, 10]     # [intial time, final time]\nx0 = [1, 1]             # intial value\nβ = 2            # order of the derivative\npar = [16.0, 4.0] # [spring constant for a mass on a spring, inertial mass]\nh = 0.01\n\n## Equation\nfunction F(t, n, β, x, par)\n\n      K = par[1]\n      m = par[2]\n\n      - K ./ m .* x[n]\n\nend\n\n## Numerical solution\nt, Yapp = FDEsolver(F, tSpan, x0, β, nothing, par, h = h)\n\n#plot\nplot(t, Yapp, linewidth = 5, title = \"Simple harmonic motion (order=2)\",\n     xaxis = \"Time (t)\", yaxis = \"x(t)\", label = \"Approximation\")\na = x0[1] .* map(cos, sqrt(par[1] / par[2]) .* t) .+ x0[2] ./ sqrt(par[1] / par[2]) .* map(sin, sqrt(par[1] / par[2]) .* t)\nplot!(t, a, lw = 3, ls = :dash, label = \"Exact solution\")\n", "meta": {"hexsha": "e2b0724002d1a4ef72ec89d9f989d5a1e430db88", "size": 768, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/SimpleHarmonicMotion.jl", "max_stars_repo_name": "moeinkh88/FdeSolver.jl", "max_stars_repo_head_hexsha": "21c2922de90484328d794465cb5000db0281fcfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/SimpleHarmonicMotion.jl", "max_issues_repo_name": "moeinkh88/FdeSolver.jl", "max_issues_repo_head_hexsha": "21c2922de90484328d794465cb5000db0281fcfb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/SimpleHarmonicMotion.jl", "max_forks_repo_name": "moeinkh88/FdeSolver.jl", "max_forks_repo_head_hexsha": "21c2922de90484328d794465cb5000db0281fcfb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4827586207, "max_line_length": 123, "alphanum_fraction": 0.5481770833, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342024724487, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.7887084732820665}}
{"text": "using SMM, DataFrames, CSV, HTTP, Random, LinearAlgebra, Statistics, Optim, DataFramesMeta, GLM\r\n\r\nfunction PS7()\r\n\t#question 1\r\n\turl = \"https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2021/master/ProblemSets/PS1-julia-intro/nlsw88.csv\"\r\n\tdf = CSV.read(HTTP.get(url).body, DataFrames)\r\n\tX = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\r\n\ty = log.(df.wage);\r\n\r\n\tfunction ols_gmm(beta, X, y)\r\n\t\treturn (y.-X*beta)'*(y.-X*beta)\r\n\tend\r\n\r\n\r\n\tfunction ols_gmm_with_sigma(beta, X, y)\r\n\t\tg = vcat(y .- X*beta[1:end-1],( (size(y,1)-1)/(size(y,1)-size(X,2)) )*var(y .- X*beta[1:end-1]) .- beta[end]^2)\r\n\t\treturn g'*g\r\n\tend\r\n\r\n\tbeta_gmm = optimize(b -> ols_gmm(b, X, y), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-6, iterations=100_000))\r\n\tprintln(beta_gmm.minimizer)\r\n\r\n\tbeta_gmm_sigma = optimize(b -> ols_gmm_with_sigma(b, X, y), rand(size(X,2)+1), LBFGS(), Optim.Options(g_tol=1e-6, iterations=100_000))\r\n\tprintln(beta_gmm_sigma.minimizer)\r\n\r\n\r\n\t#Question 2\r\n\tdf = dropmissing(df, :occupation)\r\n\tdf[df.occupation.>7,:occupation] .= 7\r\n\tX = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\r\n\ty = df.occupation;\r\n\r\n\r\n\t#from PS2\r\n\tfunction mlogit_mle(alpha, X, y)\r\n\t\t\t\r\n\t\t\tK = size(X,2)\r\n\t\t\tJ = length(unique(y))\r\n\t\t\tN = length(y)\r\n\t\t\tbigY = zeros(N,J)\r\n\t\t\tfor j=1:J\r\n\t\t\t\tbigY[:,j] = y.==j\r\n\t\t\tend\r\n\t\t\tA = [reshape(alpha,K,J-1) zeros(K)]\r\n\t\t\t\r\n\t\t\tP = exp.(X*A) ./ sum.(eachrow(exp.(X*A))) \r\n\t\t\t\r\n\t\t\treturn -sum( bigY.*log.(P) )\r\n\tend\r\n\r\n\talpha_hat= optimize(a -> mlogit_mle(a, X, y), rand(6*size(X,2)), LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\r\n\r\n\tprint(alpha_hat.minimizer)\r\n\r\n\tfunction mlogit_gmm(α, X, y)\r\n\t\t\tK = size(X,2)\r\n\t\t\tJ = length(unique(y))\r\n\t\t\tN = length(y)\r\n\t\t\tbigY = zeros(N,J)\r\n\t\t\tfor j=1:J\r\n\t\t\t\tbigY[:,j] = y.==j\r\n\t\t\tend\r\n\t\t\tbigα = [reshape(α,K,J-1) zeros(K)]\r\n\t\t\t\r\n\t\t\tP = exp.(X*bigα) ./ sum.(eachrow(exp.(X*bigα)))\r\n\t\t\t\r\n\t\t\tg = bigY[:] .- P[:]\r\n\r\n\t\t\tJ = g'*I*g\r\n\t\t\treturn J\r\n\tend\r\n\r\n\tα_hat_gmm = optimize(a -> mlogit_gmm(a, X, y), alpha_hat.minimizer, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=10_000, show_trace=true, show_every=100))\r\n\tprint(α_hat_gmm.minimizer)\r\n\r\n\ttd = TwiceDifferentiable(b -> mlogit_gmm(b, X, y), alpha_hat.minimizer; autodiff = :forward)\r\n\tα_hat_gmm_random=optimize(td, rand(6*size(X,2)), LBFGS(), Optim.Options(g_tol = 1e-5, iterations=10_000, show_trace=true, show_every=100))\r\n\r\n\tprint(α_hat_gmm_random.minimizer)\r\n\r\n\t#Question 3\r\n\r\n\t#Question4\r\n\tMA = SMM.parallelNormal()\r\n\tdc = SMM.history(MA.chains[1])\r\n\tdc = dc[dc[:accepted].==true, :]\r\n\tprintln(describe(dc))\r\n\r\n\t#Question 5\r\nend\r\n\r\nPS7()\r\n", "meta": {"hexsha": "28296585cd5ba052b11d236d55d7fca95210e060", "size": 2620, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS7-smm/PS-7.jl", "max_stars_repo_name": "jmalpert/fall-2021", "max_stars_repo_head_hexsha": "651db827087ef463219f6496043eb70064b89bd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSets/PS7-smm/PS-7.jl", "max_issues_repo_name": "jmalpert/fall-2021", "max_issues_repo_head_hexsha": "651db827087ef463219f6496043eb70064b89bd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS7-smm/PS-7.jl", "max_forks_repo_name": "jmalpert/fall-2021", "max_forks_repo_head_hexsha": "651db827087ef463219f6496043eb70064b89bd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1720430108, "max_line_length": 159, "alphanum_fraction": 0.622519084, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7886859957263281}}
{"text": "module problem114\n\ndescription = \"\"\"\nCounting block combinations I\nA row measuring seven units in length has red blocks with a minimum length of three units placed on it, \n such that any two red blocks (which are allowed to be different lengths) are separated by at least one black square. \nThere are exactly seventeen ways of doing this.\nHow many ways can a row measuring fifty units in length be filled?\n\"\"\"\n\nfunction block_combinations(n :: Integer, memo = zeros(Int, n))\n  # trivial cases\n  if n < 1 return 1 end\n\n  # Count the total with each block size, and block position, \n  # recursively counting the ways to fill the remaining space at the end of the row.  \n  if memo[n] == 0\n    total = 1\n    for blocksize = 3:n, blockpos = 1:(n-blocksize+1)\n      total += block_combinations(n - blockpos - blocksize, memo)\n    end\n    memo[n] = total\n  end\n  return memo[n]\nend\n\n\nusing Base.Test\n\n@test block_combinations(3) == 2 #empty or 1 block\n@test block_combinations(4) == 4 #empty or length 3 at pos 1, or length 3 at pos 2, or length 4 at pos 1\n@test block_combinations(7) == 17\n\nend", "meta": {"hexsha": "36fb60c8d2d6965eb4740bdd85c745a915c805c9", "size": 1088, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem114.jl", "max_stars_repo_name": "mbuhot/mbuhot-euler-solutions", "max_stars_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-12-18T13:25:41.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-18T13:25:41.000Z", "max_issues_repo_path": "julia/problem114.jl", "max_issues_repo_name": "mbuhot/mbuhot-euler-solutions", "max_issues_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/problem114.jl", "max_forks_repo_name": "mbuhot/mbuhot-euler-solutions", "max_forks_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0, "max_line_length": 118, "alphanum_fraction": 0.7169117647, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875642, "lm_q2_score": 0.8311430478583169, "lm_q1q2_score": 0.7886859873715708}}
{"text": "using LinearAlgebra, LowRankApprox, Formatting, ImageFiltering, Images, Plots, ImageMagick, Colors, TestImages, ImageView, ImageTransformations\n\nI=load(\"rgb.jpg\");\n\nG=Gray.(I);\n# size(G)\n\nA=imresize(G, ratio=1/3);\n# rank(A), size(A), eltype(A)\n\n(p,q)=size(A);\nB=Array{Float64}(A);\n\nusing DSP, Wavelets\nB1=dwt(B, wavelet(WT.haar), 1);\nB2=dwt(B, wavelet(WT.haar), 2);\nB3=dwt(B, wavelet(WT.haar), 3);\nB4=dwt(B, wavelet(WT.haar), 4);\n\nB1a=zeros(Float64, p, q);\nB2a=zeros(Float64, p, q);\nB3a=zeros(Float64, p, q);\nB4a=zeros(Float64, p, q);\n\nB1a[1:Int(p/2),1:Int(q/2)]=B1[1:Int(p/2),1:Int(q/2)];\nB2a[1:Int(p/4),1:Int(q/4)]=B2[1:Int(p/4),1:Int(q/4)];\nB3a[1:Int(p/8),1:Int(q/8)]=B3[1:Int(p/8),1:Int(q/8)];\nB4a[1:Int(p/16),1:Int(q/16)]=B4[1:Int(p/16),1:Int(q/16)];\nB1d=B1-B1a;\nB2d=B2-B2a;\nB3d=B3-B3a;\nB4d=B4-B4a;\n\nC1a=idwt(B1a, wavelet(WT.haar), 1);\nC2a=idwt(B2a, wavelet(WT.haar), 2);\nC3a=idwt(B3a, wavelet(WT.haar), 3);\nC4a=idwt(B4a, wavelet(WT.haar), 4);\nC1d=idwt(B1d, wavelet(WT.haar), 1);\nC2d=idwt(B2d, wavelet(WT.haar), 2);\nC3d=idwt(B3d, wavelet(WT.haar), 3);\nC4d=idwt(B4d, wavelet(WT.haar), 4);\n\nA1a=Gray.(C1a);\nA1d=Gray.(C1d);\nA2a=Gray.(C2a);\nA2d=Gray.(C2d);\nA3a=Gray.(C3a);\nA3d=Gray.(C3d);\nA4a=Gray.(C4a);\nA4d=Gray.(C4d);\n\nplot(Gray.(A), \n    xaxis=false, \n    xticks=false, \n    yaxis=false, \n    yticks=false, \n    grid=false, \n    title=\"Level 0: Original Grayscale Image\")\nsavefig(\"grayscale_haar_level0.png\")\n\nplot(Gray.(B1), \n    xaxis=false, \n    xticks=false, \n    yaxis=false, \n    yticks=false, \n    grid=false, \n    title=\"Level 1 (haar)\")\nsavefig(\"grayscale_haar_level1.png\")\n\nplot(Gray.(C1a), \n    xaxis=false, \n    xticks=false, \n    yaxis=false, \n    yticks=false, \n    grid=false, \n    title=\"Level 1 Approximation (haar)\")\nsavefig(\"grayscale_haar_level1_a.png\")\n\nplot(Gray.(C2a), \n    xaxis=false, \n    xticks=false, \n    yaxis=false, \n    yticks=false, \n    grid=false, \n    title=\"Level 2 Approximation (haar)\")\nsavefig(\"grayscale_haar_level2_a.png\")\n\nplot(Gray.(C3a), \n    xaxis=false, \n    xticks=false, \n    yaxis=false, \n    yticks=false, \n    grid=false, \n    title=\"Level 3 Approximation (haar)\")\nsavefig(\"grayscale_haar_level3_a.png\")\n\nplot(Gray.(C4a), \n    xaxis=false, \n    xticks=false, \n    yaxis=false, \n    yticks=false, \n    grid=false, \n    title=\"Level 4 Approximation (haar)\")\nsavefig(\"grayscale_haar_level4_a.png\")\n\nplot(Gray.(C4d), \n    xaxis=false, \n    xticks=false, \n    yaxis=false, \n    yticks=false, \n    grid=false, \n    title=\"Level 4 Detail (haar)\")\nsavefig(\"grayscale_haar_level4_d.png\")\n", "meta": {"hexsha": "766484331f2c701e5c861ecb154f9cd8177b8f4f", "size": 2536, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "grayscale_haar.jl", "max_stars_repo_name": "hiroyuki-chihara/julia.samples", "max_stars_repo_head_hexsha": "3341be942f2d9c087dc7201c7a6c1fff714632ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-24T22:19:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T22:19:52.000Z", "max_issues_repo_path": "grayscale_haar.jl", "max_issues_repo_name": "hiroyuki-chihara/julia.samples", "max_issues_repo_head_hexsha": "3341be942f2d9c087dc7201c7a6c1fff714632ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grayscale_haar.jl", "max_forks_repo_name": "hiroyuki-chihara/julia.samples", "max_forks_repo_head_hexsha": "3341be942f2d9c087dc7201c7a6c1fff714632ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2456140351, "max_line_length": 143, "alphanum_fraction": 0.6411671924, "num_tokens": 1020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7886859818350812}}
{"text": "\"\"\"\n    MVCalc(μstar,μ,Σ)\n\nCalculate the std and weights of a portfolio (with mean return μstar) on MVF of risky assets.\n\n# Remark\n- Only (λ,δ) and thus (w,stdRp) depend on μstar. We could therefore speed up the computations a bit\nby doing the loop over different μstar values inside the function (and thus not recalculate Σ_1,a,b,c).\n\"\"\"\nfunction MVCalc(μstar,μ,Σ)\n    n    = length(μ)\n    Σ_1  = inv(Σ)\n    a    = μ'Σ_1*μ\n    b    = μ'Σ_1*ones(n)\n    c    = ones(n)'Σ_1*ones(n)\n    λ    = (c*μstar - b)/(a*c-b^2)\n    δ    = (a-b*μstar)/(a*c-b^2)\n    w    = Σ_1 *(μ*λ.+δ)\n    StdRp = sqrt(w'Σ*w)\n    return StdRp,w\nend\n\n\n\"\"\"\n    MVCalcRf(μstar,μ,Σ,Rf)\n\nCalculate the std and portfolio weights of a portfolio (with a given mean, μstar) on MVF of (risky assets,riskfree)\n\"\"\"\nfunction MVCalcRf(μstar,μ,Σ,Rf)\n    μe    = μ .- Rf\n    Σ_1   = inv(Σ)\n    w     = (μstar-Rf)/(μe'Σ_1*μe) * Σ_1*μe\n    StdRp = sqrt(w'Σ*w)\n    return StdRp,w                    #std and portfolio weights\nend\n\n\n\"\"\"\n    MVTangencyP(μ,Σ,Rf)\n\nCalculate the tangency portfolio\n\"\"\"\nfunction MVTangencyP(μ,Σ,Rf)           #calculates the tangency portfolio\n    n    = length(μ)\n    μe   = μ .- Rf                    #expected excess returns\n    Σ_1  = inv(Σ)\n    w    = Σ_1 *μe/(ones(n)'Σ_1*μe)\n    muT  = w'μ + (1-sum(w))*Rf\n    StdT = sqrt(w'Σ*w)\n    return w,muT,StdT                  #portolio weights, mean and std\nend\n", "meta": {"hexsha": "f51387591085c8ccc3b50ca04232681745d1f227", "size": 1391, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jlFiles/MvCalculations.jl", "max_stars_repo_name": "snowdj/FinancialTheoryMSc", "max_stars_repo_head_hexsha": "a380bd733883d2bb3970b80604e86e70f27cd3f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-10-22T20:52:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T22:53:06.000Z", "max_issues_repo_path": "jlFiles/MvCalculations.jl", "max_issues_repo_name": "snowdj/FinancialTheoryMSc", "max_issues_repo_head_hexsha": "a380bd733883d2bb3970b80604e86e70f27cd3f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jlFiles/MvCalculations.jl", "max_forks_repo_name": "snowdj/FinancialTheoryMSc", "max_forks_repo_head_hexsha": "a380bd733883d2bb3970b80604e86e70f27cd3f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2017-11-27T21:34:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-11T05:58:09.000Z", "avg_line_length": 26.75, "max_line_length": 115, "alphanum_fraction": 0.5794392523, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172572644806, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7886859773992274}}
{"text": "function asinh(x::DoubleFloat{T}) where {T<:IEEEFloat}\n    isnan(x) && return x\n    isinf(x) && return x\n    signbit(x) && return - asinh(-x)\n    result = abs(x)\n    result = result + sqrt(square(result) + 1.0)\n    result = log(result)\n    return copysign(result, x)\nend\n\nfunction acosh(x::DoubleFloat{T}) where {T<:IEEEFloat}\n    isnan(x) && return x\n    isinf(x) && !signbit(x) && return x\n    (x < 1.0 || isinf(x)) && throw(DomainError(\"$x\"))\n    result = x + sqrt(square(x) - 1.0)\n    result = log(result)\n    return result\nend\n\nfunction atanh(x::DoubleFloat{T}) where {T<:IEEEFloat}\n    isnan(x) && return x\n    (abs(x) > 1.0 || isinf(x)) && throw(DomainError(\"$x\"))\n    twox = DoubleFloat{T}(x.hi+x.hi, x.lo+x.lo)\n    result = 1.0 + twox / (1.0 - x)\n    result = log(result)\n    result = DoubleFloat{T}(result.hi*0.5, result.lo*0.5)\n    return result\nend\n\nfunction acsch(x::DoubleFloat{T}) where {T<:IEEEFloat}\n    isnan(x) && return x\n    isinf(x) && return zero(DoubleFloat{T})\n    iszero(x) && return signbit(x) ? -DoubleFloat{T}(Inf) : DoubleFloat{T}(Inf)\n    invx = inv(x)\n    invx2 = inv(x*x)\n    result = log(sqrt(1 + invx2) + invx)\n    return result\nend\n\nfunction asech(x::DoubleFloat{T}) where {T<:IEEEFloat}\n    isnan(x) && return x\n    (x < 0.0 || x > 1.0 || isinf(x)) && throw(DomainError(\"$x\"))\n    iszero(x) && return inf(DoubleFloat{T})\n    isone(x) && return zero(DoubleFloat{T})\n    invx = inv(x)\n    result = fma(sqrt(invx + 1), sqrt(invx - 1), invx)\n    return log(result)\nend\n\nfunction acoth(x::DoubleFloat{T}) where {T<:IEEEFloat}\n    isnan(x) && return x\n    isinf(x) && return copysign(zero(DoubleFloat{T}), x)\n    isone(x) && return inf(DoubleFloat{T})\n    isone(-x) && return -inf(DoubleFloat{T})\n    (-1.0 < x < 1.0) && throw(DomainError(\"$x\"))\n    invx = inv(x)\n    result = (log(1+invx) - log(1-invx))/2\n    return result\nend\n", "meta": {"hexsha": "01e02a9027f781f97ab0c07ac61c6349d9f7264a", "size": 1860, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/elementary/archyptrig.jl", "max_stars_repo_name": "UnofficialJuliaMirror/DoubleFloats.jl-497a8b3b-efae-58df-a0af-a86822472b78", "max_stars_repo_head_hexsha": "ccf0c6a690f81eec84caf080c99d58d11e72432d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 107, "max_stars_repo_stars_event_min_datetime": "2018-02-07T14:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:44:41.000Z", "max_issues_repo_path": "src/math/elementary/archyptrig.jl", "max_issues_repo_name": "UnofficialJuliaMirror/DoubleFloats.jl-497a8b3b-efae-58df-a0af-a86822472b78", "max_issues_repo_head_hexsha": "ccf0c6a690f81eec84caf080c99d58d11e72432d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 125, "max_issues_repo_issues_event_min_datetime": "2018-04-15T13:56:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:12:12.000Z", "max_forks_repo_path": "src/math/elementary/archyptrig.jl", "max_forks_repo_name": "UnofficialJuliaMirror/DoubleFloats.jl-497a8b3b-efae-58df-a0af-a86822472b78", "max_forks_repo_head_hexsha": "ccf0c6a690f81eec84caf080c99d58d11e72432d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2018-04-27T10:17:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:44:20.000Z", "avg_line_length": 31.0, "max_line_length": 79, "alphanum_fraction": 0.5962365591, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090975, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7886859746309829}}
{"text": "## Julia program for Hierarchical Modeling of means and variances\r\n## author: weiya <szcfweiya@gmail.com>\r\n## date: 27 August, 2018\r\n\r\nusing Distributions\r\nusing SpecialFunctions\r\nusing StatsBase\r\nusing DelimitedFiles\r\n\r\nfunction higibbs(Y, T, mu0 = 50.0, gamma20 = 25.0, nu0 = 1.0, sigma20 = 100.0, eta0 = 1.0, tau20 = 100.0, a = 1.0, b = 1/100.0, alpha = 1.0, NUMAX = 40)\r\n    m = size(unique(Y[:,1]), 1)\r\n    # starting value\r\n    ybar = ones(m)\r\n    sv = ones(m)\r\n    n = ones(m)\r\n    for j = 1:m\r\n        yj = Y[ [Y[i,1] == j for i = 1:end], 2]\r\n        ybar[j] = mean(yj)\r\n        sv[j] = var(yj)\r\n        n[j] = size(yj, 1)\r\n    end\r\n    theta = ybar\r\n    sigma2 = copy(sv)\r\n#    sigma20 = 1 / mean(sigma2)\r\n#    nu0 = 2 * mean(sigma2)^2 / var(sigma2)\r\n    mu = mean(theta)\r\n    tau2 = var(theta)\r\n\r\n    THETA = ones(T, m)\r\n    SIGMA2 = ones(T, m)\r\n    # mu tau2 sigma20 nu0\r\n    MTSN = ones(T, 4)\r\n\r\n    for t = 1:T        \r\n        # sample mu\r\n        varmu = 1 / (m / tau2 + 1 / gamma20)\r\n        meanmu = varmu * (m * mean(theta) / tau2 + mu0 / gamma20)\r\n        rnorm = Normal(meanmu, sqrt(varmu))\r\n        mu = rand(rnorm, 1)[1]\r\n\r\n        # sample 1/tau2\r\n        shapetau = (eta0 + m) / 2\r\n        ratetau = ( eta0 * tau20 + sum((theta .- mu).^2) ) / 2\r\n        rgamma = Gamma(shapetau, 1/ratetau)\r\n        tau2 = 1 / rand(rgamma, 1)[1]\r\n\r\n        # sample theta\r\n        for j = 1:m\r\n            vartheta = 1 / (n[j] / sigma2[j] + 1 / tau2)\r\n            meantheta = vartheta * ( n[j] * mean(Y[ [Y[i,1] == j for i = 1:end], 2]) / sigma2[j] + mu / tau2) \r\n            rnorm = Normal(meantheta, sqrt(vartheta))\r\n            theta[j] = rand(rnorm, 1)[1]\r\n        end\r\n        THETA[t, :] .= theta\r\n        \r\n        # sample sigma2\r\n        for j = 1:m\r\n            shapesig = (nu0 + n[j])/2\r\n            yj = Y[ [Y[i,1] == j for i = 1:end], 2]\r\n            ratesig = ( nu0*sigma20 + sum( (yj .- theta[j]).^2 ) )/2\r\n            rgamma = Gamma(shapesig, 1/ratesig)\r\n            sigma2[j] = 1 / rand(rgamma, 1)[1]            \r\n        end\r\n        SIGMA2[t, :] .= sigma2\r\n        \r\n        # sample sigma20\r\n        shapesig = a + 0.5 * m * nu0\r\n        ratesig = b + 0.5 * nu0 * sum(1 ./ sigma2)\r\n        rgamma = Gamma(shapesig, 1/ratesig)\r\n        sigma20 = rand(rgamma, 1)[1]\r\n        \r\n        # sample nu0\r\n        x = 1:NUMAX\r\n        lpnu0 = ones(NUMAX)\r\n        lpnu0 .= m * ( .5 * x .* log.(sigma20 * x / 2) .- lgamma.(x/2) ) .+ (x / 2 .+ 1) * sum(log.(1 ./ sigma2)) .- x .* (alpha + .5 * sigma20 * sum(1 ./ sigma2))\r\n        #println(lpnu0)\r\n        nu0 = sample(x, pweights(exp.(lpnu0 .- maximum(lpnu0))))\r\n#        println(pweights(exp.(lpnu0 .- maximum(lpnu0))))\r\n        \r\n        # store results\r\n        MTSN[t, :] .= [mu, tau2, sigma20, nu0]\r\n    end\r\n    return THETA, SIGMA2, MTSN, sv, n\r\nend\r\n\r\n# run\r\nY = readdlm(\"math-score-Y.csv\")\r\nTHETA, SIGMA2, MTSN, sv, n = higibbs(Y, 5000)\r\n\r\nusing PyPlot\r\n# histogram\r\nplt[:subplot](221)\r\nplt[:hist](MTSN[:,2])\r\nylabel(L\"$\\mu$\")\r\nplt[:subplot](222)\r\nplt[:hist](MTSN[:,2])\r\nylabel(L\"$\\tau^2$\")\r\nplt[:subplot](223)\r\nplt[:hist](MTSN[:,3])\r\nylabel(L\"$\\nu_0$\")\r\nplt[:subplot](224)\r\nplt[:hist](MTSN[:,4])\r\nylabel(L\"$\\sigma_0^2$\")\r\nplt[:tight_layout]()\r\nshow()\r\n\r\n# shrinkage\r\nf, (ax1, ax2) = plt[:subplots](1, 2)\r\nax1[:scatter](sv, SIGMA2[end,:])\r\nax1[:plot](sv, sv)\r\nax1[:set_xlabel](L\"$s^2$\")\r\nax1[:set_ylabel](L\"$\\hat \\sigma^2$\")\r\nax2[:scatter](n, sv-SIGMA2[end,:])\r\nax2[:plot](n, zeros(size(n, 1)))\r\nax2[:set_xlabel](\"sample size\")\r\nax2[:set_ylabel](L\"$s^2-\\hat \\sigma^2$\")\r\nplt[:tight_layout]()\r\nshow()", "meta": {"hexsha": "d9379863528551e67d3b9edccd78784aec860785", "size": 3575, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Gibbs/hierarchical-model-mu-var.jl", "max_stars_repo_name": "szcf-weiya/MCMC", "max_stars_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-07-19T12:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T08:06:50.000Z", "max_issues_repo_path": "Gibbs/hierarchical-model-mu-var.jl", "max_issues_repo_name": "szcf-weiya/MCMC", "max_issues_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-02-03T15:08:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-05T15:41:39.000Z", "max_forks_repo_path": "Gibbs/hierarchical-model-mu-var.jl", "max_forks_repo_name": "szcf-weiya/MCMC", "max_forks_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-07-19T12:50:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T08:06:52.000Z", "avg_line_length": 30.2966101695, "max_line_length": 164, "alphanum_fraction": 0.4984615385, "num_tokens": 1305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660989095221, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7886550312214767}}
{"text": "\nusing ForwardDiff\nfunction cournot_newton(eta, c1, c2, guess, tolerance) # note that guess is a 1*2 array\n    profit_1(guess) = (sum(guess))^(-1/eta)*guess[1] - 0.5*c1*guess[1]^2\n    profit_2(guess) = (sum(guess))^(-1/eta)*guess[2] - 0.5*c2*guess[2]^2\n\n    diff = 1e3\n    while diff > tolerance #here diff is the distance matrix\n        println(\"Now the guess for q1 is $(guess[1]), the guess for q2 is $(guess[2]).\")\n        f1 = guess -> ForwardDiff.gradient(profit_1,guess) # calculate FOC w.r.t q1\n        f2 = guess -> ForwardDiff.gradient(profit_2,guess) # calculate FOC w.r.t q2\n        f1_prime = guess -> ForwardDiff.hessian(profit_1,guess) # calculate SOC w.r.t q1\n        f2_prime = guess -> ForwardDiff.hessian(profit_2,guess) # calculate SOC w.r.t q2\n        new_guess_q1 = guess[1] - f1(guess)[1] / f1_prime(guess)[1,1]\n        new_guess_q2 = guess[2] - f2(guess)[2] / f2_prime(guess)[2,2]\n        diff = sqrt((guess[1]-new_guess_q1)^2 + (guess[2]-new_guess_q2)^2) # eclidean distance from old guess\n        guess = [new_guess_q1 new_guess_q2] # form new guess\n    end\n    println(\"The optimal quantity for firm 1 is $(guess[1]), for firm 2 is $(guess[2])\")\nend\n", "meta": {"hexsha": "a14a53a168c603e4bcfe0a80127ce10d071a00d0", "size": 1177, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "hw2_part_3.jl", "max_stars_repo_name": "jh2737/problem-set-1-q-3", "max_stars_repo_head_hexsha": "c923c0fd1bac9614b497800d8eda8c3c4326d071", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw2_part_3.jl", "max_issues_repo_name": "jh2737/problem-set-1-q-3", "max_issues_repo_head_hexsha": "c923c0fd1bac9614b497800d8eda8c3c4326d071", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw2_part_3.jl", "max_forks_repo_name": "jh2737/problem-set-1-q-3", "max_forks_repo_head_hexsha": "c923c0fd1bac9614b497800d8eda8c3c4326d071", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.0476190476, "max_line_length": 109, "alphanum_fraction": 0.6491079014, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182845, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7886550282305232}}
{"text": "#=\n\nA Pythagorean triplet is a set of three natural numbers, a < b < c, for which,\na2 + b2 = c2\n\nFor example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.\n\nThere exists exactly one Pythagorean triplet for which a + b + c = 1000.\nFind the product abc.\n\n=#\n\np = 12\n\nfunction pythagorean_triplet(perimeter)\n    for b in 2:Int(ceil((perimeter-1)/2))\n        for a in 1:b-1\n            if 2*perimeter*(a+b) == perimeter^2 + 2*a*b\n                #println(a, \", \", b, \", \", perimeter-a-b)\n                return a, b, perimeter-a-b\n            end\n            #println(a, \", \", b, \", \", perimeter-a-b)\n        end\n    end\nend\n\nres = pythagorean_triplet(1000)\nprod(res)\n", "meta": {"hexsha": "39940095f2e7200e920441935188d5b520517a18", "size": 649, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "euler_9.jl", "max_stars_repo_name": "pedvide/project-euler", "max_stars_repo_head_hexsha": "8e8e1e57b2c4d7e70a7127483539dca060c50a38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "euler_9.jl", "max_issues_repo_name": "pedvide/project-euler", "max_issues_repo_head_hexsha": "8e8e1e57b2c4d7e70a7127483539dca060c50a38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "euler_9.jl", "max_forks_repo_name": "pedvide/project-euler", "max_forks_repo_head_hexsha": "8e8e1e57b2c4d7e70a7127483539dca060c50a38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3793103448, "max_line_length": 78, "alphanum_fraction": 0.5531587057, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9539660949832345, "lm_q2_score": 0.8267117855317473, "lm_q1q2_score": 0.7886550137203382}}
{"text": "function mandelbrot(a)\n    z = 0\n    for i=1:50\n        z = z^2 + a\n    end\n    return z\nend\n\nfor y=1.0:-0.05:-1.0\n    for x=-2.0:0.0315:0.5\n        abs(mandelbrot(complex(x, y))) < 2 ? print(\"*\") : print(\" \")\n    end\n    println()\nend\n\n# Taken from: https://rosettacode.org/wiki/Mandelbrot_set#Julia", "meta": {"hexsha": "0c4e8cac4741579a27d6531a12515d05b3d30457", "size": 300, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/mandelbrot.jl", "max_stars_repo_name": "Manojkl/Open-computer-vision-Raspberry-Pi-", "max_stars_repo_head_hexsha": "830103e60af430ddfe97aa8071a0e7ad76ee18b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-08T15:57:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T15:57:54.000Z", "max_issues_repo_path": "Julia/mandelbrot.jl", "max_issues_repo_name": "Manojkl/Open-computer-vision-Raspberry-Pi", "max_issues_repo_head_hexsha": "830103e60af430ddfe97aa8071a0e7ad76ee18b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/mandelbrot.jl", "max_forks_repo_name": "Manojkl/Open-computer-vision-Raspberry-Pi", "max_forks_repo_head_hexsha": "830103e60af430ddfe97aa8071a0e7ad76ee18b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.75, "max_line_length": 68, "alphanum_fraction": 0.5533333333, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542829224748, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7886062300913983}}
{"text": "using DrWatson\n@quickactivate \"StatReth\"\n\n# %% 3.1\nPr_Positive_Vampire = 0.95\nPr_Positive_Mortal = 0.01\nPr_Vampire = 0.001\nPr_Positive = Pr_Positive_Vampire * Pr_Vampire + Pr_Positive_Mortal * (1 - Pr_Vampire)\nPr_Vampire_Positive = Pr_Positive_Vampire * Pr_Vampire / Pr_Positive\n", "meta": {"hexsha": "32cfe4b510447a8f763326fbe755fe2ab864f7d6", "size": 279, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/snippet_03_01.jl", "max_stars_repo_name": "karajan9/statisticalrethinking", "max_stars_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-06-03T14:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T16:52:26.000Z", "max_issues_repo_path": "scripts/snippet_03_01.jl", "max_issues_repo_name": "karajan9/statisticalrethinking", "max_issues_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-13T05:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T14:05:57.000Z", "max_forks_repo_path": "scripts/snippet_03_01.jl", "max_forks_repo_name": "karajan9/statisticalrethinking", "max_forks_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-01T13:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-03T23:40:53.000Z", "avg_line_length": 27.9, "max_line_length": 86, "alphanum_fraction": 0.7921146953, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9591542840900507, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7886062289618846}}
{"text": "export NumberTheory\n\nmodule NumberTheory\n\nexport Z_star, Eulerφ, continued_fraction, mod_inverse, rand_primeto, factor_a_power_b\nexport is_order, order_from_float, find_order\n\n\"\"\"\n    Z_star(N::Int) -> Vector\n\nreturns the Z* group elements of `N`, i.e. {x | gcd(x, N) == 1}\n\"\"\"\nZ_star(N::Int) = filter(i->gcd(i, N)==1, 0:N-1)\nEulerφ(N) = length(Z_star(N))\n\n\"\"\"\n    continued_fraction(ϕ, niter::Int) -> Rational\n\nobtain `s` and `r` from `ϕ` that satisfies `|s/r - ϕ| ≦ 1/2r²`\n\"\"\"\ncontinued_fraction(ϕ, niter::Int) = niter==0 ? floor(Int, ϕ) : floor(Int, ϕ) + 1//continued_fraction(1/mod(ϕ, 1), niter-1)\ncontinued_fraction(ϕ::Rational, niter::Int) = niter==0 || ϕ.den==1 ? floor(Int, ϕ) : floor(Int, ϕ) + 1//continued_fraction(1/mod(ϕ, 1), niter-1)\n\n\"\"\"\n    mod_inverse(x::Int, N::Int) -> Int\n\nReturn `y` that `(x*y)%N == 1`, notice the `(x*y)%N` operations in Z* forms a group and this is the definition of inverse.\n\"\"\"\nfunction mod_inverse(x::Int, N::Int)\n    for i=1:N\n        (x*i)%N == 1 && return i\n    end\n    throw(ArgumentError(\"Can not find the inverse, $x is probably not in Z*($N)!\"))\nend\n\n\"\"\"\n    is_order(r, x, N) -> Bool\n\nReturns true if `r` is the order of `x`, i.e. `r` satisfies `x^r % N == 1`.\n\"\"\"\nis_order(r, x, N) = powermod(x, r, N) == 1\n\n\"\"\"\n    find_order(x::Int, N::Int) -> Int\n\nFind the order of `x` by brute force search.\n\"\"\"\nfunction find_order(x::Int, N::Int)\n    findfirst(r->is_order(r, x, N), 1:N)\nend\n\n\"\"\"\n    rand_primeto(N::Int) -> Int\n\nReturns a random number `2 ≦ x < N` that is prime to `N`.\n\"\"\"\nfunction rand_primeto(N::Int)\n    while true\n        x = rand(2:N-1)\n        d = gcd(x, N)\n        if d == 1\n            return x\n        end\n    end\nend\n\n\"\"\"\n    order_from_float(ϕ, x, L) -> Int\n\nEstimate the order of `x` to `L`, `r`, from a floating point number `ϕ ∼ s/r` using the continued fraction method.\n\"\"\"\nfunction order_from_float(ϕ, x, L)\n    k = 1\n    rnum = continued_fraction(ϕ, k)\n    while rnum.den < L\n        r = rnum.den\n        if is_order(r, x, L)\n            return r\n        end\n        k += 1\n        rnum = continued_fraction(ϕ, k)\n    end\n    return nothing\nend\n\n\"\"\"\n    factor_a_power_b(N::Int) -> (Int, Int) or nothing\n\nFactorize `N` into the power form `a^b`.\n\"\"\"\nfunction factor_a_power_b(N::Int)\n    y = log2(N)\n    for b = 2:ceil(Int, y)\n        x = 2^(y/b)\n        u1 = floor(Int, x)\n        u1^b == N && return (u1, b)\n        (u1+1)^b == N && return (u1+1, b)\n    end\nend\n\nend\n", "meta": {"hexsha": "355e281ae8dfaf5d2cbd038a6a77555fdc79b8c9", "size": 2445, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/number_theory.jl", "max_stars_repo_name": "Neuromancer43/QuAlgorithmZoo.jl", "max_stars_repo_head_hexsha": "8fdef4c1d44d4a7fbaeec9ac9304448fa8cf09fa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2018-08-09T11:07:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T10:59:43.000Z", "max_issues_repo_path": "src/number_theory.jl", "max_issues_repo_name": "Neuromancer43/QuAlgorithmZoo.jl", "max_issues_repo_head_hexsha": "8fdef4c1d44d4a7fbaeec9ac9304448fa8cf09fa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2018-08-18T18:50:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-05T16:43:24.000Z", "max_forks_repo_path": "src/number_theory.jl", "max_forks_repo_name": "Neuromancer43/QuAlgorithmZoo.jl", "max_forks_repo_head_hexsha": "8fdef4c1d44d4a7fbaeec9ac9304448fa8cf09fa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-03-04T11:32:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T21:58:09.000Z", "avg_line_length": 23.9705882353, "max_line_length": 144, "alphanum_fraction": 0.5824130879, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576266, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7886062236534068}}
{"text": "using LinearAlgebra, Optim\n\nexport tracenorm, tracedist, frobdist, isunitary, ishermitian_tol, \n        isspecial, offdiag, jacobi_simultaneous_diag\n\nϵ = sqrt(eps(Float64))\n\n\"\"\"\nCompute the trace norm of a matrix ``A``\n\"\"\"\nfunction tracenorm(A::Matrix{T}) where T<:Number\n    #Compute the trace norm of a matrix A\n    if ishermitian(A)\n        return sum(abs.(eigvals(A)))\n    else\n        return sum(svd(A).S)\n    end\nend\n   \n\"\"\"\nCompute the trace distance between matrices ``A``, ``B``.\n\"\"\"     \nfunction tracedist(A::Matrix{T}, B::Matrix{T}) where T<:Number\n    #Compute trace distance between matrices A, B\n    return 0.5*tracenorm(A-B)\nend\n\n\"\"\"\nCompute the Frobenius distance between matrices ``A``, ``B``.\n\"\"\"\nfunction frobdist(A::Matrix{T}, B::Matrix{T}) where T<:Number\n    return norm(A-B, p=2)\nend\n\n\"\"\"\nCheck if a matrix is unitary up to a tolerance ``\\epsilon``.\n\"\"\"\nfunction isunitary(A::Matrix{T}; tol=ϵ) where T <: Number\n    return tracenorm(A'A - I) < tol\nend\n\n\"\"\"\nCheck if a matrix is Hermitian up to a tolerance ``\\epsilon``.\n\"\"\"\nfunction ishermitian_tol(A::Matrix{T}; tol=ϵ) where T <: Number\n    return tracedist(A, Matrix(A')) < tol\nend\n\n\"\"\"\nCheck if a matrix is special up to a tolerance ``\\epsilon``.\n\"\"\"\nfunction isspecial(A::Matrix{T}; tol=ϵ) where T <: Number\n    return isapprox(det(A), 1.0, rtol=tol)\nend\n\n\"\"\"\nSum of the off-diagonal elements of a matrix.\n\"\"\"\nfunction offdiag(A::Matrix{T}) where T <: Number\n    return sum(tril(A,-1).^2) + sum(triu(A,1).^2)\nend\n\n\"\"\"\nFunction which implements the Jacobi algorithm for simultaneous (possibly approxiamate)\ndiagonalization of two real, symmetric matrices A, B. \n\nAlgorithm is from:\n\nV. Kuleshov, A. Chaganty, P. Liang. \"Simultaneous diagonalization: the asymmetric, \nlow-rank, and noisy settings\" arXiv: 1051.06318 (2015)\n\nJ.-F. Cardoso, A. Soulomiac. \"Jacobi angles for simultaneous diagonalization\" \nSIAM J. Matrix Anal. Appl. 17(1), 161-164. (1996)\n\n\"\"\"\nfunction jacobi_simultaneous_diag(A::Matrix{T}, B::Matrix{T}; \n        tol=sqrt(eps(T)), maxiter=1000) where T<:Real\n    \n    @assert ishermitian_tol(A) && ishermitian_tol(B) \"A, B must be symmetric!\"\n    \n    (m,mm) = size(A)\n    done = false\n    \n    U = Float64.(Matrix(I, (m,mm)))\n    Λa = A\n    Λb = B\n    \n    #Cost function for minimization of \"off-diagonal-ness\"\n    #TODO: I was not able to succesfully implement the exact solution for the minimizer from the \n    #Cardoso paper...\n    \n    cost(X,Y) = offdiag(X)+offdiag(Y)\n    \n    start_cost = cost(A,B)\n    \n    function minims_lsq(X, Y, i, j)\n        function f(x)\n            g = LinearAlgebra.Givens(i,j, cos(x), sin(x))\n            return cost(g'*X*g, g'*Y*g)\n        end\n        xopt = Optim.minimizer(optimize(f, -π/4, π/4)) #are these the correct limits?\n        return (cos(xopt), sin(xopt))\n    end\n    \n    target = tol*(norm(A,2)+norm(B,2))\n    \n    n = 1\n    while ((cost(Λa,Λb) > tol) && (n < maxiter))\n        for j=1:m-1\n            for k=j+1:m\n                (c, s) = minims_lsq(Λa, Λb, j, k)\n                Γ = LinearAlgebra.Givens(j, k, c, s)\n                U = U*Γ\n                Λa = Γ'*Λa*Γ\n                Λb = Γ'*Λb*Γ\n            end\n        end\n    end\n        \n    final_cost = cost(Λa,Λb)\n\n    success = true\n        \n    if ((n >= maxiter) || (final_cost > tol))\n        @warn \"Was unable to find a simultaneous diagonalization: start \n                cost function: $(start_cost), final: $(final_cost).\"\n        success = false\n    end\n    \n    return (U, Diagonal(Λa), Diagonal(Λb), success)\nend \n", "meta": {"hexsha": "fbc3b51310f93b318e13f4fb8875d46533b28ddb", "size": 3527, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "BBN-Q/GateDecompositions.jl", "max_stars_repo_head_hexsha": "a3f98d72c69dc7df8371b4c8ea0c797720954c44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "BBN-Q/GateDecompositions.jl", "max_issues_repo_head_hexsha": "a3f98d72c69dc7df8371b4c8ea0c797720954c44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "BBN-Q/GateDecompositions.jl", "max_forks_repo_head_hexsha": "a3f98d72c69dc7df8371b4c8ea0c797720954c44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7196969697, "max_line_length": 97, "alphanum_fraction": 0.6061808903, "num_tokens": 1090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542794197472, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.788606218853566}}
{"text": "using SymPy\n\nfunction ry_mat(ang)\n    return [SymPy.cos(ang/2) -SymPy.sin(ang/2); SymPy.sin(ang/2) SymPy.cos(ang/2)]\nend\n\nfunction rz_mat(ang)\n    return [SymPy.exp(-1im*ang/2) 0; 0 SymPy.exp(1im*ang/2)]\nend\n\nfunction gen_mat(a,b,c,d)\n    return SymPy.exp(1im*d).*ry_mat(c)*rz_mat(b)*ry_mat(a)\nend\n\nfunction _params_zyz(mat::Matrix{<:Symbol})\n    \"\"\"Return the euler angles and phase for the ZYZ basis.\"\"\"\n    # We rescale the input matrix to be special unitary (det(U) = 1)\n    # This ensures that the quaternion representation is real\n    coeff = sympy.sqrt(sympy.det(mat))\n    phase = -sympy.atan2(real(coeff),imag(coeff))\n    su_mat = coeff * mat  # U in SU(2)\n    # OpenQASM SU(2) parameterization:\n    # U[0, 0] = exp(-i(phi+lambda)/2) * cos(theta/2)\n    # U[0, 1] = -exp(-i(phi-lambda)/2) * sin(theta/2)\n    # U[1, 0] = exp(i(phi-lambda)/2) * sin(theta/2)\n    # U[1, 1] = exp(i(phi+lambda)/2) * cos(theta/2)\n    theta = 2 * sympy.atan2(abs(su_mat[2, 1]), abs(su_mat[1, 1]))\n    phiplambda = 2 * sympy.atan2(real(su_mat[2, 2]), imag(su_mat[2, 2]))\n    phimlambda = 2 * sympy.atan2(real(su_mat[2, 1]), imag(su_mat[2, 1]))\n    phi = (phiplambda + phimlambda) / 2\n    lam = (phiplambda - phimlambda) / 2\n    return theta, phi, lam, phase\nend\n\nfunction _params_zyz(mat::Matrix{<:Number})\n    \"\"\"Return the euler angles and phase for the ZYZ basis.\"\"\"\n    # We rescale the input matrix to be special unitary (det(U) = 1)\n    # This ensures that the quaternion representation is real\n    coeff = sqrt(det(mat) +0im)\n    phase = -atan(real(coeff), imag(coeff))\n    su_mat = coeff * mat  # U in SU(2)\n    # OpenQASM SU(2) parameterization:\n    # U[0, 0] = exp(-i(phi+lambda)/2) * cos(theta/2)\n    # U[0, 1] = -exp(-i(phi-lambda)/2) * sin(theta/2)\n    # U[1, 0] = exp(i(phi-lambda)/2) * sin(theta/2)\n    # U[1, 1] = exp(i(phi+lambda)/2) * cos(theta/2)\n    theta = 2 * atan(abs(su_mat[2, 1]), abs(su_mat[1, 1]))\n    phiplambda = 2 * atan(real(su_mat[2, 2]), imag(su_mat[2, 2]))\n    phimlambda = 2 * atan(real(su_mat[2, 1]), imag(su_mat[2, 1]))\n    phi = (phiplambda + phimlambda) / 2\n    lam = (phiplambda - phimlambda) / 2\n    return theta, phi, lam, phase\nend", "meta": {"hexsha": "b120a7313a465fbcbbd34460bfa3f5a66ce3372f", "size": 2157, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/symbolics.jl", "max_stars_repo_name": "ICHEC/QuantExQASM.jl", "max_stars_repo_head_hexsha": "83a96deb65b471fd015dc40b08b7b9474a687bb6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-25T09:51:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-08T15:58:29.000Z", "max_issues_repo_path": "src/symbolics.jl", "max_issues_repo_name": "ICHEC/QuantExQASM.jl", "max_issues_repo_head_hexsha": "83a96deb65b471fd015dc40b08b7b9474a687bb6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-20T12:08:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-20T17:09:02.000Z", "max_forks_repo_path": "src/symbolics.jl", "max_forks_repo_name": "ICHEC/QuantExQASM.jl", "max_forks_repo_head_hexsha": "83a96deb65b471fd015dc40b08b7b9474a687bb6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-30T18:25:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-30T18:25:26.000Z", "avg_line_length": 40.6981132075, "max_line_length": 82, "alphanum_fraction": 0.6175243394, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542805873231, "lm_q2_score": 0.8221891218080991, "lm_q1q2_score": 0.7886062156345702}}
{"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENCE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    variation(table)\n\nReturn the variation matrix `Τ` of the `table` such that:\n\n- `Τ[i,j] = Var(log(x[i]/x[j]))` for `i, j = 1, ..., D`\n\"\"\"\nfunction variation(table)\n  X = Tables.matrix(table)\n  n = Tables.columnnames(table) |> collect\n  D = size(X, 2)\n  L = log.(X .+ eps())\n\n  T = Matrix{Float64}(undef, D, D)\n  for j in 1:D\n    for i in j+1:D\n      lr = L[:,i] .- L[:,j]\n      T[i,j] = var(lr)\n    end\n    T[j,j] = 0.0\n    for i in 1:j-1\n      T[i,j] = T[j,i]\n    end\n  end\n\n  AxisArray(T, row=n, col=n)\nend\n\n\"\"\"\n    alrcov(table)\n\nReturn the log-ratio covariance matrix `Σ` of the `table` such that:\n\n- `Σ[i,j] = cov(log(x[i]/x[D]), log(x[j]/x[D]))` for `i, j = 1, ..., d`\n\"\"\"\nfunction alrcov(table)\n  alrtable = table |> ALR()\n\n  Σ = cov(Tables.matrix(alrtable), dims=1)\n\n  vars = Tables.columnnames(alrtable) |> collect\n  AxisArray(Σ, row=vars, col=vars)\nend\n\n\"\"\"\n    clrcov(table)\n\nReturn the centered log-ratio covariance matrix `Γ` of the `table` such that:\n\n- `Γ[i,j] = cov(log(x[i]/g(x)), log(x[j]/g(x)))` for `i, j = 1, ..., D`,\nwhere `g(x)` is the geometric mean.\n\"\"\"\nfunction clrcov(table)\n  clrtable = table |> CLR()\n\n  Γ = cov(Tables.matrix(clrtable), dims=1)\n\n  vars = Tables.columnnames(clrtable) |> collect\n  AxisArray(Γ, row=vars, col=vars)\nend\n\n\"\"\"\n    lrarray(table)\n\nReturn the variation array `A` of the `table` such that:\n\n- `A[i,j] = E[log(x[i]/x[j])]` for `i > j`\n- `A[i,j] = Var(log(x[i]/x[j]))` for `i < j`\n- `A[i,j] = 0` for `i = j`\n\"\"\"\nfunction lrarray(table)\n  X = Tables.matrix(table)\n  D = size(X, 2)\n  L = log.(X .+ eps())\n\n  A = Matrix{Float64}(undef, D, D)\n  for i in 1:D\n    for j in i+1:D\n      lr = L[:,i] .- L[:,j]\n      A[j,i] = mean(lr)\n      A[i,j] = var(lr)\n    end\n    A[i,i] = 0.0\n  end\n\n  vars = Tables.columnnames(table) |> collect\n  AxisArray(A, row=vars, col=vars)\nend", "meta": {"hexsha": "9b3d5d716e0bd9ead742d65cdd34f69b9882c554", "size": 2030, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/covariances.jl", "max_stars_repo_name": "OkonSamuel/CoDa.jl", "max_stars_repo_head_hexsha": "cae693f6662085280c09a2b4b9a05e7093851e8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-12-21T01:16:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-08T13:42:09.000Z", "max_issues_repo_path": "src/covariances.jl", "max_issues_repo_name": "OkonSamuel/CoDa.jl", "max_issues_repo_head_hexsha": "cae693f6662085280c09a2b4b9a05e7093851e8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/covariances.jl", "max_forks_repo_name": "OkonSamuel/CoDa.jl", "max_forks_repo_head_hexsha": "cae693f6662085280c09a2b4b9a05e7093851e8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:31:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-08T21:48:36.000Z", "avg_line_length": 22.0652173913, "max_line_length": 77, "alphanum_fraction": 0.5246305419, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.788571846341222}}
{"text": "\nusing DifferentialEquations\n\nfunction parameterized_lorenz(du,u,p,t)\n  x,y,z = u\n  σ,ρ,β = p\n  du[1] = dx = σ*(y-x)\n  du[2] = dy = x*(ρ-z) - y\n  du[3] = dz = x*y - β*z\nend\n\nusing ParameterizedFunctions\ng = @ode_def begin\n  dx = σ*(y-x)\n  dy = x*(ρ-z) - y\n  dz = x*y - β*z\nend σ ρ β\n\n# using LinearAlgebra\n# f(du,u,p,t) = mul!(du,A,u)\n\nu0 = [1.0;0.0;0.0]\ntspan = (0.0,100.0)\np = [10.0,28.0,8/3]\nprob = ODEProblem(g,u0,tspan,p)\n\n\nusing StaticArrays, DifferentialEquations\nA  = @SMatrix [ 1.0  0.0 0.0 -5.0\n                4.0 -2.0 4.0 -3.0\n               -4.0  0.0 0.0  1.0\n                5.0 -2.0 2.0  3.0]\nu0 = @SMatrix rand(4,2)\ntspan = (0.0,1.0)\nf(u,p,t) = A*u\nprob = ODEProblem(f,u0,tspan)\nsol = solve(prob)\nusing Plots;\nplot(sol)\n\n\n# const κ = 1; const tau = 2 * pi\nconst out = zeros(2) # Define a cache variable\nfunction delay_mathieu_model(du,u,h,p,t)\n  δ, ϵ, b, κ = p\n  h(out, p, t-tau)\n  du[1] = - κ *u[1] - (δ+ϵ*cos(t)) *u[2] -b * out[2]\n  du[2] = u[1]\nend\n\np = [1.0,2.0,1,0.1]\ntau=2*pi\nT=2*pi\nlags = [tau]\nh(out, p, t) = (out.=1.0)\n# h(out, p, t, deriv::Type{Val{i}})\ntspan = (0.0,T)\nu0 = [1.0,1.0]\nprob = DDEProblem(delay_mathieu_model,h,tspan,p; constant_lags=lags)\n\n\nalg = MethodOfSteps(Tsit5())\n# alg = MethodOfSteps(BS3())\n# alg = MethodOfSteps(Vern6())\nsol = solve(prob,alg)#,reltol=1e-8,abstol=1e-8)\n\nusing Plots\nplot(sol,vars=(0,2))\n\n# plot(sol,linewidth=5,title=\"Solution to the linear ODE with a thick line\",\n#      xaxis=\"Time (t)\",yaxis=\"u(t) (in μm)\",label=\"My Thick Line!\") # legend=false\n# plot!(sol.t, t->0.5*exp(1.01t),lw=3,ls=:dash,label=\"True Solution!\")\nsol[2][3]\nplot(sol,vars=(0,2))\n", "meta": {"hexsha": "cfe98ec5d3c74898ac0ceb8d5c7f7b5cd6e14d5f", "size": 1617, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scr/issi_diffeq.jl", "max_stars_repo_name": "bachrathyd/ISSI_test", "max_stars_repo_head_hexsha": "6bf6b10c3cffe7eb204d85e09dffde042f6e8e22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scr/issi_diffeq.jl", "max_issues_repo_name": "bachrathyd/ISSI_test", "max_issues_repo_head_hexsha": "6bf6b10c3cffe7eb204d85e09dffde042f6e8e22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scr/issi_diffeq.jl", "max_forks_repo_name": "bachrathyd/ISSI_test", "max_forks_repo_head_hexsha": "6bf6b10c3cffe7eb204d85e09dffde042f6e8e22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.56, "max_line_length": 83, "alphanum_fraction": 0.5794681509, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678381, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7885315012264273}}
{"text": "# This file is part of IntegerSequences.\n# Copyright Peter Luschny. License is MIT.\n\n(@__DIR__) ∉ LOAD_PATH && push!(LOAD_PATH, (@__DIR__))\n\nmodule BinaryInteger\n\nexport ModuleBinaryInteger\nexport V001855, V003314, V033156, V054248, V061168, V083652, V097383, V123753\nexport V295513, BinaryIntegerLength, Bil\n\n\"\"\"\nFor positive n, BinaryIntegerLength is ``⌊ log[2](n) ⌋ + 1``, BinaryIntegerLength(0) = 0.\n\n* BinaryIntegerLength, Bil, V001855, V003314, V033156, V054248, V061168, V083652, V097383, V123753, V295513\n\"\"\"\nconst ModuleBinaryInteger = \"\"\n\n\"\"\"\nReturn the length of the binary extension of an integer ``n``, which is defined as ``0`` if ``n = 0`` and for ``n > 0`` as ``⌊ log[2](n) ⌋ + 1``.\n\"\"\"\nBinaryIntegerLength(n) = n == 0 ? 0 : floor(Int, log2(n)) + 1\n\n\"\"\"\nAlias for the function BinaryIntegerLength.\n\"\"\"\nBil(n) = BinaryIntegerLength(n)\n\n\"\"\"\nReturn ``n`` Bil``(n) - 2^{\\\\text{Bil}(n)}`` where Bil``(n)`` is the binary integer length of ``n``.\n\"\"\"\nV295513(n) = n*Bil(n) - 2^Bil(n)\n\n\"\"\"\nMaximal number of comparisons for sorting ``n`` elements by binary insertion.\n\"\"\"\nV001855(n) = V295513(n) + 1\n\n\"\"\"\nReturn the sum of lengths of binary expansions of ``0`` through ``n``.\n\"\"\"\nV083652(n) = V295513(n+1) + 2\n\n\"\"\"\nRecurrence ``a(n) = a(n-1) + ⌊ a(n-1)/(n-1) ⌋ + 2`` for ``m ≥ 2`` and ``a(1) = 1``.\n\"\"\"\nV033156(n) = V295513(n) + 2n\n\n\"\"\"\nBinary entropy function: ``a(n) = n + `` min ``( a(k) + a(n-k) : 1 ≤ k ≤ n-1 )`` for ``n > 1,`` and ``a(1) = 0``.\n\"\"\"\nV003314(n) = V295513(n) + n\n\n\"\"\"\nBinary entropy: ``a(n) = n +`` min ``{ a(k) + a(n-k) : 1 ≤ k ≤ n-1 }.``\n\"\"\"\nV054248(n) = V295513(n) + n + rem(n, 2)\n\n\"\"\"\nMinimum total number of comparisons to find each of the values ``1`` through ``n`` using a binary search with ``3``-way comparisons.\n\"\"\"\nV097383(n) = V295513(n+1) - div(n-1, 2)\n\n\"\"\"\nPartial sums of the sequence ``⌊ log[2](n) ⌋``.\n\"\"\"\nV061168(n) = V295513(n+1) - n + 1\n\n\"\"\"\nPartial sums of the sequence of length of the binary expansion of ``2n+1``.\n\"\"\"\nV123753(n) = V295513(n+1) + n + 2\n\n#START-TEST-########################################################\n\nusing Test, SeqTests\n\nfunction test()\n    @testset \"BinaryInteger\" begin\n\n        @test V295513(0) == -1\n        @test V295513(1) == -1\n        @test V295513(2) == 0\n        @test V295513(3) == 2\n\n        if is_oeis_installed()\n            V = [V001855, V003314, V033156, V054248, V061168, V097383]\n            for v in V SeqTest(v , 'V', 1) end\n\n            V = [V083652, V123753]\n            for v in V SeqTest(v , 'V', 0) end\n        end\n    end\nend\n\nfunction demo()\n    println([V295513(n) for n in 0:12])\n    println([V123753(n) for n in 0:12])\n    println([V001855(n) for n in 1:12])\n    println([V083652(n) for n in 1:12])\n    println([V033156(n) for n in 1:12])\n    println([V003314(n) for n in 1:12])\n    println([V054248(n) for n in 1:12])\n    println([V097383(n) for n in 1:12])\n    println([V061168(n) for n in 1:12])\nend\n\n\"\"\"\n[V295513(k) for k in 0:100000]\n    0.014412 seconds (2 allocations: 781.391 KiB)\n\"\"\"\nfunction perf()\n    @time [V295513(k) for k in 0:100000]\nend\n\nfunction main()\n    test()\n    demo()\n    perf()\nend\n\nmain()\n\nend # module\n", "meta": {"hexsha": "41d6c4c80b66a20ffc4c90cf9254f88967230bd6", "size": 3136, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BinaryInteger.jl", "max_stars_repo_name": "UnofficialJuliaMirror/IntegerSequences.jl-b4b868b0-69a7-11e9-2db0-173b4e8e576c", "max_stars_repo_head_hexsha": "5718a938e44b1f14c7115f2940f96fa344b72ce8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BinaryInteger.jl", "max_issues_repo_name": "UnofficialJuliaMirror/IntegerSequences.jl-b4b868b0-69a7-11e9-2db0-173b4e8e576c", "max_issues_repo_head_hexsha": "5718a938e44b1f14c7115f2940f96fa344b72ce8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BinaryInteger.jl", "max_forks_repo_name": "UnofficialJuliaMirror/IntegerSequences.jl-b4b868b0-69a7-11e9-2db0-173b4e8e576c", "max_forks_repo_head_hexsha": "5718a938e44b1f14c7115f2940f96fa344b72ce8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.088, "max_line_length": 145, "alphanum_fraction": 0.5841836735, "num_tokens": 1131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248208414329, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7885310404310205}}
{"text": "# this function shows the behavior of the \n# likelihood, the log-likelihood and the average\n# log-likelihood as the sample size increases\nusing Distributions\nn = 10 # try increasing this to 50, 1000, etc.\np = 0.3\ny = rand(Bernoulli(p),n)\nf =  pdf.(Bernoulli(p), y)\n@show n\n@show ℒ = prod(f)\n@show lnℒ = sum(log.(f)) \n@show avglnℒ = (1/n)*sum(log.(f))\nnothing\n\n\n", "meta": {"hexsha": "4268bb5b57736626b12c857eac893b1cb24e4816", "size": 361, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/MLE/PlainLF.jl", "max_stars_repo_name": "mcreel/EconometricsNotes", "max_stars_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-19T18:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T18:23:45.000Z", "max_issues_repo_path": "Examples/MLE/PlainLF.jl", "max_issues_repo_name": "mcreel/EconometricsNotes", "max_issues_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/MLE/PlainLF.jl", "max_forks_repo_name": "mcreel/EconometricsNotes", "max_forks_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5625, "max_line_length": 48, "alphanum_fraction": 0.6842105263, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9390248140158416, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7885310403487306}}
{"text": "using LPVSpectral, Statistics, Random\r\nexport Sinusoidal\r\n\r\n\"\"\"\r\n    Sinusoidal(fs)\r\nDecompose a timeseries `s` into a **sum** `x + r`, where `x`\r\nare sinusoidal components with the given frequencies `fs` that minimize\r\ncoefficients ``A, \\\\phi`` of the expression\r\n```math\r\ns \\\\approx A_0 + \\\\sum_i A_i \\\\cos(2\\\\pi f_i t + \\\\phi_i)\r\n```\r\nwith ``A_0 = \\\\bar{s}`` the mean.\r\n\r\nThis method uses a new least-squares algorithm in frequency domain using the package\r\n[LPVSpectral.jl](https://github.com/baggepinnen/LPVSpectral.jl), see[^Bagge2017].\r\nIt works for non-equispaced `t` axis (and also normal), is generally very accurate\r\n(if choosen frequencies are not too close), but has performance scaling of\r\nO(N^2.4) instead of O(n log(n)) of [`Fourier`](@ref).\r\n\r\nBecause it can work with arbitrary signal length the method always estimates the\r\nzero-frequency Fourier component, and attributes it to `x`.\r\nThe fitted coefficients ``A, \\\\phi`` are available as fields `.A` and `.φ` of the struct\r\n(first entry is zero-frequency component ``A_0, \\\\phi_0``).\r\n\r\n[^Bagge2017]: F. Bagge Carlson et al., [Linear Parameter-Varying Spectral Decomposition](https://lup.lub.lu.se/search/publication/ac32368e-e199-44ff-b76a-36668ac7d595).\r\n\"\"\"\r\nstruct Sinusoidal{F<:AbstractArray{<:AbstractFloat}} <: Decomposition\r\n    fs::F\r\n    A::Vector{Float64}\r\n    φ::Vector{Float64}\r\nend\r\nSinusoidal(fs) = Sinusoidal(fs, zeros(length(fs)+1), zeros(length(fs)+1))\r\n\r\nfunction decompose(t, s, method::Sinusoidal)\r\n    @assert 0 ∉ method.fs\r\n    fs = [0, method.fs...]\r\n    χ, = ls_spectral(s, t, fs)\r\n    As = abs.(χ) ./ sqrt(2*length(fs))\r\n    φs = angle.(χ)\r\n    method.A .= As\r\n    method.φ .= φs\r\n    x = fill(As[1], length(s))\r\n    for i in 2:length(fs)\r\n        @. x += As[i]*cos(2π*fs[i]*t + φs[i])\r\n    end\r\n    return x, s .- x\r\nend\r\n", "meta": {"hexsha": "4bdd5f04df72920af578cf562fb46443846fa7ac", "size": 1819, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear/lpv.jl", "max_stars_repo_name": "JuliaDynamics/SignalDecomposition.jl", "max_stars_repo_head_hexsha": "e865058d48a5e28e827b97ed05e99952f86e9a66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2020-04-04T14:49:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T19:36:47.000Z", "max_issues_repo_path": "src/linear/lpv.jl", "max_issues_repo_name": "JuliaDynamics/SignalDecomposition.jl", "max_issues_repo_head_hexsha": "e865058d48a5e28e827b97ed05e99952f86e9a66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-04-04T09:29:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T14:33:06.000Z", "max_forks_repo_path": "src/linear/lpv.jl", "max_forks_repo_name": "JuliaDynamics/SignalDecomposition.jl", "max_forks_repo_head_hexsha": "e865058d48a5e28e827b97ed05e99952f86e9a66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8958333333, "max_line_length": 169, "alphanum_fraction": 0.6641011545, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422255326288, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7884387049869349}}
{"text": "#!/usr/bin/julia\n\n# Trizen\n# 15 November 2021\n# https://github.com/trizen\n\n# Compute the multiplicative order of `a` modulo `n`: znorder(a, n).\n# This is the smallest positive integer k such that a^k == 1 (mod n).\n\nusing Primes\n\nfunction divisors(n)\n\n    d = Int64[1]\n\n    for (p,e) in factor(n)\n        t = Int64[]\n        r = 1\n\n        for i in 1:e\n            r *= p\n            for u in d\n                push!(t, u*r)\n            end\n        end\n\n        append!(d, t)\n    end\n\n    return sort(d)\nend\n\nfunction znorder(a, n)\n\n    if isprime(n)\n        for d in divisors(n-1)\n            if (powermod(a, d, n) == 1)\n                return d\n            end\n        end\n    end\n\n    f = factor(n)\n\n    if (length(f) == 1)         # is prime power\n\n        p = first(first(f))\n        z = znorder(a, p)\n\n        while (powermod(a, z, n) != 1)\n            z *= p\n        end\n\n        return z\n    end\n\n    pp_orders = Int64[]\n\n    for (p,e) in f\n        push!(pp_orders, znorder(a, p^e))\n    end\n\n    return lcm(pp_orders)\nend\n\nisequal(znorder(97, factorial(14)), 25920)          || print(\"error\")\nisequal(znorder(53, factorial(15)), 2419200)        || print(\"error\")\nisequal(znorder(37, factorial(16)), 116121600)      || print(\"error\")\nisequal(znorder(31, factorial(17)), 6220800)        || print(\"error\")\nisequal(znorder(89, factorial(18)), 1045094400)     || print(\"error\")\nisequal(znorder(101,factorial(19)), 1254113280)     || print(\"error\")\nisequal(znorder(97, factorial(20)), 2239488000)     || print(\"error\")\n\nprintln(znorder(2, 341))        #> 10\nprintln(znorder(97, 5040))      #> 12\n", "meta": {"hexsha": "aabc45080b5068d7a6c5584317d5f0bf1e713b21", "size": 1597, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Math/multiplicative_order.jl", "max_stars_repo_name": "trizen/julia-scripts", "max_stars_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-03-22T09:38:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T21:38:31.000Z", "max_issues_repo_path": "Math/multiplicative_order.jl", "max_issues_repo_name": "trizen/julia-scripts", "max_issues_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/multiplicative_order.jl", "max_forks_repo_name": "trizen/julia-scripts", "max_forks_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0131578947, "max_line_length": 69, "alphanum_fraction": 0.5291170946, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422269175634, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7884387041252225}}
{"text": "# Polynomial kernel function\n\n\"\"\"\n    Poly <: Kernel\n\nPolynomial kernel (covariance)\n```math\nk(x,x') = σ²(xᵀx' + c)ᵈ\n```\nwith signal standard deviation ``σ``, additive constant ``c``, and degree ``d``.\n\"\"\"\nmutable struct Poly{T<:Real} <: Kernel\n    \"Constant\"\n    c::T\n    \"Signal variance\"\n    σ2::T\n    \"Degree of polynomial\"\n    deg::Int\n    \"Priors for kernel parameters\"\n    priors::Array\nend\n\n\"\"\"\nPolynomial kernel function\n\n    Poly(lc::Real, lσ::Real, deg::Int)\n\n# Arguments\n  - `lc::Real`: additive constant (given on log scale)\n  - `lσ::Real`: signal standard deviation (given on log scale)\n  - `deg::Int`: degree of polynomial  \n\"\"\"\nPoly(lc::T, lσ::T, deg::Int) where T = Poly{T}(exp(lc), exp(2 * lσ), deg, [])\n\nfunction KernelData(k::Poly, X1::AbstractMatrix, X2::AbstractMatrix)\n    XtX=X1'*X2\n\tif X1==X2\n    \tLinearAlgebra.copytri!(XtX, 'U')\n\tend\n    LinIsoData(XtX)\nend\nkernel_data_key(k::Poly, X1::AbstractMatrix, X2::AbstractMatrix) = \"LinIsoData\"\n\n_cov(poly::Poly, xTy) = poly.σ2*(poly.c.+xTy).^poly.deg\nfunction cov(poly::Poly, x::AbstractVector, y::AbstractVector)\n    K = _cov(poly, dot(x,y))\nend\nfunction cov!(cK::AbstractMatrix, poly::Poly, X::AbstractMatrix, data::LinIsoData)\n    cK .= _cov(poly, data.XtX)\nend\n@inline @inbounds function cov_ij(poly::Poly, X1::AbstractMatrix, X2::AbstractMatrix, i::Int, j::Int, dim::Int)\n    return _cov(poly, dotij(X1, X2, i, j, dim))\nend\n@inline @inbounds function cov_ij(poly::Poly, X1::AbstractMatrix, X2::AbstractMatrix, data::LinIsoData, i::Int, j::Int, dim::Int)\n    return _cov(poly, data.XtX[i, j])\nend\ncov(poly::Poly, X1::AbstractMatrix, X2::AbstractMatrix, data::LinIsoData) = _cov(poly, data.XtX)\n\nget_params(poly::Poly) = [log(poly.c), log(poly.σ2) / 2]\nget_param_names(poly::Poly) = [:lc, :lσ]\nnum_params(poly::Poly) = 2\n\nfunction set_params!(poly::Poly, hyp::AbstractVector)\n    length(hyp) == 2 || throw(ArgumentError(\"Polynomial function has two parameters\"))\n    poly.c = exp(hyp[1])\n    poly.σ2 = exp(2 * hyp[2])\nend\n\n@inline dk_dlc(poly::Poly, xTy::Real) = poly.c*poly.deg*poly.σ2*(poly.c+xTy).^(poly.deg-1)\n@inline dk_dlσ(poly::Poly, xTy::Real) = 2 * _cov(poly,xTy)\n@inline function dKij_dθp(poly::Poly, X1::AbstractMatrix, X2::AbstractMatrix, i::Int, j::Int, p::Int, dim::Int)\n    if p==1\n        return dk_dlc(poly, dotij(X1,X2,i,j,dim))\n    else\n        return dk_dlσ(poly, dotij(X1, X2,i,j,dim))\n    end\nend\n@inline function dKij_dθp(poly::Poly, X1::AbstractMatrix, X2::AbstractMatrix, data::LinIsoData, i::Int, j::Int, p::Int, dim::Int)\n    if p==1\n        return dk_dlc(poly, data.XtX[i,j])\n    else\n        return dk_dlσ(poly, data.XtX[i,j])\n    end\nend\n", "meta": {"hexsha": "c7260bfee2ec4087d985959d6dc2d42039d915ec", "size": 2642, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/poly.jl", "max_stars_repo_name": "mcusi/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 284, "max_stars_repo_stars_event_min_datetime": "2015-07-31T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T07:08:58.000Z", "max_issues_repo_path": "src/kernels/poly.jl", "max_issues_repo_name": "mcusi/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 171, "max_issues_repo_issues_event_min_datetime": "2015-05-28T12:04:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T06:48:23.000Z", "max_forks_repo_path": "src/kernels/poly.jl", "max_forks_repo_name": "mcusi/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-05-31T12:44:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:21:38.000Z", "avg_line_length": 31.0823529412, "max_line_length": 129, "alphanum_fraction": 0.659348978, "num_tokens": 898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928904, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7884387003948308}}
{"text": "\r\n# =========================================================================== #\r\n# Error Functions\r\n# =========================================================================== #\r\n\r\nabstract type AbstractErrorFunction\r\nend\r\n\r\nstruct LeastSquaresErrorFunction <: AbstractErrorFunction\r\nend\r\n\r\nfunction (error_fcn::LeastSquaresErrorFunction)(meas::T, x::T) where {T <: Number}\r\n    dx = -meas + x\r\n    return dx^2\r\nend\r\nfunction (error_fcn::LeastSquaresErrorFunction)(meas::Vector{T}, x::Vector{T}) where {T}\r\n    dx = sum( (-meas .+ x).^2 )\r\n    return dx\r\nend\r\nfunction (error_fcn::LeastSquaresErrorFunction)(meas, x::Vector{T}) where {T}\r\n    dx = sum( (-meas .+ x).^2 )\r\n    return dx\r\nend\r\n\r\n\r\nfunction differentiate(error_fcn::LeastSquaresErrorFunction, meas, x)\r\n    return -meas + x\r\nend\r\n\r\nfunction eval(error_fcn::LeastSquaresErrorFunction, meas, x)\r\n    return error_fcn(meas, x)\r\nend\r\n\r\nfunction gradient!(error_fcn::LeastSquaresErrorFunction, y_meas, y_out, delta_e)\r\n    for kk = 1:length(delta_e)\r\n        delta_e[kk] = differentiate(error_fcn, y_meas[kk], y_out[kk])\r\n    end\r\n    return delta_e\r\nend\r\n\r\n# function error_gradient!(nn::NeuralNetwork, y_meas, y_out, delta_e)\r\n#     return gradient!(nn.error_function, y_meas, y_out, delta_e)\r\n# end\r\n", "meta": {"hexsha": "c3c5292a6e625835f6dea3dce8c03e72af097ff2", "size": 1266, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "neural_networks/src/error_measure.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "neural_networks/src/error_measure.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neural_networks/src/error_measure.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7727272727, "max_line_length": 89, "alphanum_fraction": 0.6018957346, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7884386992468047}}
{"text": "# ------------------------------------------------------------------\n# Copyright (c) 2017, Júlio Hoffimann Mendes <juliohm@stanford.edu>\n# Licensed under the ISC License. See LICENCE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    Ellipsoidal(semiaxes, angles)\n\nA distance defined by an ellipsoid with given `semiaxes` and rotation `angles`.\n\n- For 2D ellipsoids, there are two semiaxes and one rotation angle.\n- For 3D ellipsoids, there are three semiaxes and three rotation angles.\n\n## Examples\n\n2D ellipsoid making 45ᵒ with the horizontal axis:\n\n```julia\njulia> Ellipsoidal([1.0,0.5], [π/2])\n```\n\n3D ellipsoid rotated by 45ᵒ in the xy plane:\n\n```julia\njulia> Ellipsoidal([1.0,0.5,0.5], [π/2,0.0,0.0])\n```\n\"\"\"\nstruct Ellipsoidal{N,T} <: Metric\n  dist::Mahalanobis{T}\n\n  function Ellipsoidal{N,T}(semiaxes, angles) where {N,T<:Real}\n    @assert length(semiaxes) == N \"number of semiaxes must match spatial dimension\"\n    @assert all(semiaxes .> zero(T)) \"semiaxes must be positive\"\n    @assert N ∈ [2,3] \"dimension must be either 2 or 3\"\n\n    # scaling matrix\n    Λ = Diagonal(one(T)./semiaxes.^2)\n\n    # rotation matrix\n    if N == 2\n      θ = angles[1]\n\n      cosθ = cos(θ)\n      sinθ = sin(θ)\n\n      P = [cosθ -sinθ\n           sinθ  cosθ]\n    end\n    if N == 3\n      θxy, θyz, θzx = angles\n\n      cosxy = cos(θxy)\n      sinxy = sin(θxy)\n      cosyz = cos(θyz)\n      sinyz = sin(θyz)\n      coszx = cos(θzx)\n      sinzx = sin(θzx)\n\n      _1 = one(T)\n      _0 = zero(T)\n\n      Rxy = [cosxy -sinxy _0\n             sinxy  cosxy _0\n             _0     _0 _1]\n\n      Ryz = [_1    _0     _0\n             _0 cosyz -sinyz\n             _0 sinyz  cosyz]\n\n      Rzx = [ coszx _0 sinzx\n             _0 _1    _0\n             -sinzx _0 coszx]\n\n      P = Rzx*Ryz*Rxy\n    end\n\n    # ellipsoid matrix\n    Q = P*Λ*P'\n\n    new(Mahalanobis(Q))\n  end\nend\n\nEllipsoidal(semiaxes::AbstractVector{T}, angles::AbstractVector{T}) where {T<:Real} =\n  Ellipsoidal{length(semiaxes),T}(semiaxes, angles)\n\nfunction Distances.evaluate(dist::Ellipsoidal{N,T}, a::AbstractVector, b::AbstractVector) where {N,T<:Real}\n  evaluate(dist.dist, a, b)\nend\n", "meta": {"hexsha": "e916522ef6f2ccbfd7c3ba38b5df6d035180c1e3", "size": 2167, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances.jl", "max_stars_repo_name": "riyadm/GeoStatsDevTools.jl", "max_stars_repo_head_hexsha": "4e4a30809ea20695247cb12b85db16e4a44178bf", "max_stars_repo_licenses": ["ISC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distances.jl", "max_issues_repo_name": "riyadm/GeoStatsDevTools.jl", "max_issues_repo_head_hexsha": "4e4a30809ea20695247cb12b85db16e4a44178bf", "max_issues_repo_licenses": ["ISC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distances.jl", "max_forks_repo_name": "riyadm/GeoStatsDevTools.jl", "max_forks_repo_head_hexsha": "4e4a30809ea20695247cb12b85db16e4a44178bf", "max_forks_repo_licenses": ["ISC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0777777778, "max_line_length": 107, "alphanum_fraction": 0.5676049838, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7884386978096936}}
{"text": "using GeometryTypes\nusing SurfaceTopology\nusing LinearAlgebra\n\nfunction quadraticform(vects,vnormal)\n    \n    Lx = [0 0 0; 0 0 -1; 0 1 0]\n    Ly = [0 0 1; 0 0 0; -1 0 0]\n    Lz = [0 -1 0; 1 0 0; 0 0 0]\n\n    d = [0,0,1] + vnormal\n    d /= norm(d)\n        \n    Ln = d[1]*Lx + d[2]*Ly + d[3]*Lz\n    R = exp(pi*Ln)\n\n    vects = copy(vects)\n    for vj in 1:length(vects)\n        vects[vj] = R*vects[vj]\n    end\n\n    ### Construction of the system\n    A = Array{Float64}(undef,3,3)\n    B = Array{Float64}(undef,3)\n\n    vects_norm2 = Array{Float64}(undef,length(vects))\n    for vj in 1:length(vects)\n       vects_norm2[vj] = norm(vects[vj])^2\n    end\n\n    A[1,1] = sum((v[1]^4 for v in vects) ./ vects_norm2)\n    A[1,2] = sum((v[1]^3*v[2] for v in vects) ./ vects_norm2)\n    A[1,3] = sum((v[1]^2*v[2]^2 for v in vects) ./ vects_norm2)\n    A[2,1] = A[1,2]\n    A[2,2] = A[1,3]\n    A[2,3] = sum( (v[2]^3*v[1] for v in vects) ./vects_norm2)\n    A[3,1] = A[1,3]\n    A[3,2] = A[2,3]\n    A[3,3] = sum((v[2]^4 for v in vects) ./vects_norm2)\n\n    \n    B[1] = sum((v[3]*v[1]^2 for v in vects) ./vects_norm2)\n    B[2] = sum((v[1]*v[2]*v[3] for v in vects) ./vects_norm2)\n    B[3] = sum((v[2]^2*v[3] for v in vects) ./vects_norm2)\n    \n    C,D,E = A\\B\n    return C,D,E\nend\n\nfunction meancurvature(points,topology)\n    curvatures = Array{Float64}(undef,length(points))\n    for v in 1:length(points)\n\n        s = Point(0,0,0)\n        for (v1,v2) in EdgeRing(v,topology)\n            s += cross(points[v2],points[v1])\n        end\n        normal = s ./ norm(s)\n\n        vring = collect(VertexRing(v,topology))\n        vects = [points[vi] - points[v] for vi in vring]\n\n        C,D,E = quadraticform(vects,normal)\n\n        A = [C D/2;D/2 E]\n        k1,k2 = eigvals(-A)\n        H = (k1 + k2)/2\n\n        curvatures[v] = H\n    end\n    return curvatures\nend\n\n### Testing\nt = ( 1 + sqrt( 5 ) ) / 2;\n\nvertices = Point{3,Float64}[\n    [ -1,  t,  0 ], [  1, t, 0 ], [ -1, -t,  0 ], [  1, -t,  0 ],\n    [  0, -1,  t ], [  0, 1, t ], [  0, -1, -t ], [  0,  1, -t ],\n    [  t,  0, -1 ], [  t, 0, 1 ], [ -t,  0, -1 ], [ -t,  0,  1 ]\n] ./ sqrt(1 + t^2)\n\nfaces = Face{3,Int64}[\n    [1, 12, 6], [1, 6, 2], [1, 2, 8], [1, 8, 11], [1, 11, 12], [2, 6, 10], [6, 12, 5], \n    [12, 11, 3], [11, 8, 7], [8, 2, 9], [4, 10, 5], [4, 5, 3], [4, 3, 7], [4, 7, 9],  \n    [4, 9, 10], [5, 10, 6], [3, 5, 12], [7, 3, 11], [9, 7, 8], [10, 9, 2] \n]\n\n### As paraboloid grows faster than sphere the estimated curvature for a coarse mesh would be lower\ncurvatures = meancurvature(vertices,faces)\n", "meta": {"hexsha": "11f926879b328b879457411f75761f30d7f39df7", "size": 2534, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/curvature.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SurfaceTopology.jl-1db0cb78-5717-11e9-0361-01e0964942ce", "max_stars_repo_head_hexsha": "da31ee3ff9309fa703a83a0d6858db6c2c7496bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-06-28T09:39:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-08T19:33:52.000Z", "max_issues_repo_path": "examples/curvature.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SurfaceTopology.jl-1db0cb78-5717-11e9-0361-01e0964942ce", "max_issues_repo_head_hexsha": "da31ee3ff9309fa703a83a0d6858db6c2c7496bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-08-12T22:39:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-12T22:39:35.000Z", "max_forks_repo_path": "examples/curvature.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SurfaceTopology.jl-1db0cb78-5717-11e9-0361-01e0964942ce", "max_forks_repo_head_hexsha": "da31ee3ff9309fa703a83a0d6858db6c2c7496bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:02:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:02:48.000Z", "avg_line_length": 27.8461538462, "max_line_length": 99, "alphanum_fraction": 0.4968429361, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214470715364, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7884046084012918}}
{"text": "#===============================================================================\n\nUsing all of the digits 1 through 9 and concatenating them freely to form\ndecimal integers, different sets can be formed. Interestingly with the set\n{2,5,47,89,631}, all of the elements belonging to it are prime.\n\nHow many distinct sets containing each of the digits one through nine exactly\nonce contain only prime elements?\n\n--------------------------------------------------------------------------------\n\nThe algorithm proposed is based on the association of a number to its digits.\n\nLet n=d1...dn be a number made of n digits. Then\n\n    encode(n) = 0 if n contains 0 or if a digit appears multiple times.\n              = (Σ 2^di)/2\n\nThe division by 2 results from the fact the 0 is not allowed, so Σ 2^di is\nalways odd. Thus the range of encode(n) is 1 to 511 (9 bits set to 1).\n\nEach prime up to 987654321 are encoded as explained above, and each code is\nassociated with the number of primes it corresponds to, excepted for primes\nencoded as 0, which are discarded.\n\nA similar code is also associated to a set of primes, by computing it over all\nthe digits of all the primes belonging to the set.\n\nWith this, a prime p can be added to the set S if encode(p) and encode(S) have\nno digits in common, i.e. if encode(p) & encode(S) is null. The code of the new\nset is encode(p) | encode(S).\n\nOf course, this applies to all primes whose code is the same as encode(p).\n\nThen the solution is built by exploring recursively the tree of the\npossibilities.\n\n===============================================================================#\n\nimport Primes\n\nfunction encode(n::Int)\n    result::UInt16 = 0\n\n    while (n != 0)\n        n, digit = divrem(n, 10)\n\n        bit = 1 << digit\n\n        if (digit == 0 || result & bit != 0)\n            return 0\n        end\n\n        result |= bit\n    end\n\n    result >> 1\nend\n\nprimes = Primes.primes(1, 987654321);\n\nfunction compute_codes(primes)\n    result = zeros(Int64, 511)\n\n    for p in primes\n        code = encode(p)\n        if code != 0\n            result[code] += 1\n        end\n    end\n\n    result;\nend\n\nconst allcodes = compute_codes(primes)\n\nconst fullcode = encode(123456789)\n\nfunction compute_nbr_sets(code_idx, code_of_set, nbr_of_prime_sets)\n\n    if code_of_set == fullcode\n        return nbr_of_prime_sets\n    end\n\n    if code_idx == 512\n        return 0\n    end\n\n    result = compute_nbr_sets(code_idx+1, code_of_set, nbr_of_prime_sets);\n\n    nbr_assoc_primes = allcodes[code_idx]\n\n    if nbr_assoc_primes != 0 && code_of_set & code_idx == 0\n        result += compute_nbr_sets(code_idx+1,\n                                   code_of_set|code_idx,\n                                   nbr_assoc_primes * nbr_of_prime_sets)\n    end\n\n    result\nend\n\nprintln(\"Euler 118: \", compute_nbr_sets(1, 0, 1));\n", "meta": {"hexsha": "f5e90662a702725ecdf193364824a318f5c8e0cb", "size": 2826, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0118.jl", "max_stars_repo_name": "dpieroux/euler", "max_stars_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "0118.jl", "max_issues_repo_name": "dpieroux/euler", "max_issues_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0118.jl", "max_forks_repo_name": "dpieroux/euler", "max_forks_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4368932039, "max_line_length": 80, "alphanum_fraction": 0.6125265393, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214491222695, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7884046057915962}}
{"text": "\"\"\"\n    heapify(array::Array{Int64,1})\n\nThe heapify function merges the two subroutines for:\n    1) Put elements of the array in heap order\n    2) Repair the heap elements `i` whose root element, if is not at the index `largest`\nFor more information see: https://en.wikipedia.org/wiki/Heapsort\n\n\n# Arguments\n- `array::Array{Int64,1}`: Unsorted array of integers\n- `n::Int64`: Length of the array\n- `i::Int64`: Current index of the array\n\n\"\"\"\nfunction heapify(array::Array{Int64,1}, n::Int64, i::Int64)\n    # Initialize largest as root and left and right subarrays\n    largest = i\n    # Julia notations, which starts with 1\n    left = 2 * i\n    right = 2 * i + 1\n\n    # See if left child of root exists and is greater than root\n    if left <= n && array[i] < array[left]\n        largest = left\n    end\n    # See if right child of root exists and is greater than root\n    if right <= n && array[largest] < array[right]\n        largest = right\n    end\n    # Change root, if needed\n    if largest != i\n        array[i], array[largest] = array[largest], array[i]\n        # Heapify the root again\n        array = heapify(array, n, largest)\n    end\n    return array\nend\n\n\n\"\"\"\n    heap_sorting(array::Array{Int64,1})\n\nAs a comparison-based sorting algorithm, the heapsort algorithm (HSA) divides its input\ninto a sorted and an unsorted region, and it iteratively shrinks the unsorted region by\nextracting the largest element from it and inserting it into the sorted region. A specialty\nis that the HSA keeps the unsorted region in a heap data structure to find the largest\nelement in each step more quickly. In more detail, in the first part of the HSA\n(while-loop), the largest value has to be found and set to position one. In the second part\nof the HSA (while-loop), the array's first and largest value has to be swap to the last\nindex of the array, and the swapping-procedure starts again for a new interval n-1. For\nmore information see: [https://en.wikipedia.org/wiki/Heapsort](https://en.wikipedia.org/wiki/Heapsort)\n\n\n# Arguments\n- `array::Array{Int64,1}`: Unsorted array of integers\n\n\n# Examples\n```julia-repl\njulia> import ClassicAlgorithmsCollections\njulia> arr = [64, 34, 25, 12, 22, 11, 90]\njulia> ClassicAlgorithmsCollections.heap_sorting(arr)\n[11, 12, 22, 25, 34, 64, 90]\n```\n\"\"\"\nfunction heap_sorting(array::Array{Int64,1})\n    # Base case. A array of zero or one elements is sorted, by definition.\n    n = length(array)\n\n    # Shrink the active space\n    i = fld(n, 2)\n    # Build a maxheap\n    while i > 0\n        array = heapify(array, n, i)\n        i -= 1\n\n    end\n\n    # One by one extract elements\n    i = n\n    while i > 1\n        array[i], array[1] = array[1], array[i]\n        # Julia specific reducing effectiv index\n        array = heapify(array, i - 1, 1)\n        i -= 1\n    end\n\n    return array\nend\n", "meta": {"hexsha": "0445c0fcfa263c208a4dd133481ad3367c25d8a0", "size": 2821, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SortingAndSearching/HeapSorting.jl", "max_stars_repo_name": "Anselmoo/ClassicAlgorithmsCollections", "max_stars_repo_head_hexsha": "9f802c4f317492e19b0b8bb6d9020d8450e00772", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SortingAndSearching/HeapSorting.jl", "max_issues_repo_name": "Anselmoo/ClassicAlgorithmsCollections", "max_issues_repo_head_hexsha": "9f802c4f317492e19b0b8bb6d9020d8450e00772", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2020-09-03T06:47:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-20T06:58:58.000Z", "max_forks_repo_path": "src/SortingAndSearching/HeapSorting.jl", "max_forks_repo_name": "Anselmoo/ClassicAlgorithmsCollections", "max_forks_repo_head_hexsha": "9f802c4f317492e19b0b8bb6d9020d8450e00772", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0, "max_line_length": 102, "alphanum_fraction": 0.6760014179, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.8652240930029118, "lm_q1q2_score": 0.7883746402445021}}
{"text": "##  Eratosthenes' prime number sieve\nfunction primesieve(n::Int64)\n    if n <= 1\n        return Integer[]\n    end\n\n    p = [i for i in 1:2:n]\n    q = length(p)\n    p[1] = 2\n    if n >= 9\n        for k in 3:2:isqrt(n)\n            if p[(k+1)÷2] != 0\n                p[(k*k+1).÷2:k:q] .= 0\n            end\n        end\n    end\n\n    return p[p .> 0]\nend\n\n\n##  Find all prime numbers in  a given interval\nfunction primes2(n::Int64, m::Int64)\n    if n > m\n        error(\"Argument 'm' must be bigger than 'n'.\")\n    end\n    if m <= 1000\n        P = primesieve(m)\n        return P[P .>= n]\n    end\n\n    myPrimes = primesieve(isqrt(m))\n    N = [n:m]\n    l = length(N)  # m-n+1\n    A = zeros(Int8, l)\n    if n == 1\n        A[1] = -1\n    end\n\n    for p in myPrimes\n        r = n % p\n        if r == 0\n            i = 1\n        else\n            i = p - r + 1\n        end\n        if i <= l && N[i] == p\n            i = i + p\n        end\n        while i <= l\n            A[i] = 1\n            i = i + p\n        end\n    end\n    return N[A .== 0]\nend\n\n\n##  Return unique prime factors of n sorted\nfunction primefactors(n::Int64)\n    if n <= 0\n        error(\"Argument 'n' to be factored must be a positive integer.\")\n    end\n\n    f = Primes.factor(n)\n    return sort(collect(keys(f)))\nend\n\n\n##  Find prime number following n\nfunction nextprime2(n::Int64)\n    if n <= 1; return 2; end\n    if n == 2; return 3; end\n    if iseven(n)\n        n += 1\n    else\n        n += 2\n    end\n    if isprime(n); return(n); end\n\n    if mod(n, 3) == 1\n        a = 4; b = 2\n    elseif mod(n, 3) == 2\n        a = 2; b = 4\n    else\n        n += 2\n        a = 2; b = 4\n    end\n\n    p = n\n    while !isprime(p)\n        p += a\n        if isprime(p); break; end\n        p += b\n    end\n\n    return p\nend\n\n\n## Find prime number preceeding n\nfunction prevprime2(n::Int64)\n    if n <= 2\n        return Array(typeof(n), 0)\n    elseif n <= 3\n        return 2\n    end\n\n    if iseven(n)\n        n -= 1\n    else\n        n -= 2\n    end\n    if isprime(n); return n; end\n\n    if mod(n, 3) == 1\n        a = 2; b = 4\n    elseif mod(n, 3) == 2\n        a = 4; b = 2\n    else\n        n -= 2\n        a = 2; b = 4\n    end\n\n    p = n\n    while !isprime(p)\n        p -= a\n        if isprime(p); break; end\n        p -= b\n    end\n\n    return p\nend\n\n\n##  Find all twin primes\nfunction twinprimes(n::Int64, m::Int64)\n    P = primes2(n, m)\n    inds = findall(diff(P) .== 2)\n\n    return hcat(P[inds], P[inds.+1])\nend\n\n\n##  Coprimality\nfunction coprime(n::Int64, m::Int64)\n    if n == 0 && m == 0\n        return false\n    end\n\n    if gcd(n, m) > 1\n        false\n    else\n        true\n    end\nend\n\n\n##  Solve linear modulo equations\nfunction linmod(a::Int64, b::Int64, m::Int64)\n    m > 1 || error(\"Argument 'm' must be an integer greater 1\")\n    T = typeof(m)\n    g, e, f = gcdx(a, m)\n\n    x = T[]\n    if mod(b, g) == 0\n        x0 = mod(e * div(b, g), m)\n        for i = 0:(g-1)\n            x = [x, mod(x0 + i * div(m, g) , m)]\n        end\n    end\n\n    return x\nend\n\n\n##  Order of the element n (in the ring) modulo m\nfunction ordermod(n::Int64, m::Int64)\n    if n <= 0 || m <= 0\n        error(\"Arguments 'n' and 'm' must be positive integers.\")\n    end\n    if m == 1 || gcd(n, m) > 1; return 0; end\n    if n == 1; return 1; end\n\n    r = mod(n, m)\n    if r == 0; return 0; end\n\n    k = 1\n    while r != 1\n        r = mod(n*r, m)\n        k += 1\n    end\n\n    return k\nend\n\n\n##  Find a primitive root modulo m\nfunction primroot(m::Int64)\n    if !isprime(m)\n        error(\"Argument 'm' must be a prime number\")\n    end\n    if m == 2; return 1; end\n\n    P = primefactors(m-1)\n    for r = 2:(m-1)\n        not_found = true\n        for p in P\n            if powermod(r, div(m-1, p), m) == 1\n                not_found = false\n            end\n        end\n        if not_found\n            return r\n        end\n    end\n\n    return 0\nend\n\n\n##  Euler's Phi (or: totient) function\nfunction eulerphi(n::Int64)\n    if n <= 0\n        error(\"Argument 'n' must be a (positive) natural number.\")\n    end\n\n    m = n\n    for p in primefactors(n)    # must be unique\n        m = m - div(m, p)       # m = m * (1 - 1/p)\n    end\n\n    return Integer(round(m))\nend\n", "meta": {"hexsha": "be579ddb9119abab8bae9392dc279dbf9513188a", "size": 4166, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/primes.jl", "max_stars_repo_name": "jmgraham30/BasicNT.jl", "max_stars_repo_head_hexsha": "2b211bb668aebb13ae79e06aec493c0f105b97cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/primes.jl", "max_issues_repo_name": "jmgraham30/BasicNT.jl", "max_issues_repo_head_hexsha": "2b211bb668aebb13ae79e06aec493c0f105b97cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/primes.jl", "max_forks_repo_name": "jmgraham30/BasicNT.jl", "max_forks_repo_head_hexsha": "2b211bb668aebb13ae79e06aec493c0f105b97cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7276595745, "max_line_length": 72, "alphanum_fraction": 0.4656745079, "num_tokens": 1474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748207, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7883551629400458}}
{"text": "# This program solves the Laplace-Beltrami PDE on a unit sphere.\n# In strong form, the problem can be stated as:\n# find u s.t.\n#   -Δ_S(u) = f on \\Omega\n# Where Δ_S is the spherical Laplacian defined as Δ_S = ∇_S⋅(∇_S(u)),\n# with ∇_S() and  ∇_S⋅ being the spherical gradient and spherical\n# divergence, resp.\n\n# Given a known analytical solution u(x), the program manufactures f(x)\n# by applying -Δ_S to u, and then performs an error convergence analysis.\n# For the discretization of the sphere, it uses the so-called cubed sphere\n# mesh\n\nfunction u(x)\n  sin(π*x[1])*cos(π*x[2])*exp(x[3])\nend\nfunction uθϕ(θϕ)\n  u(θϕ2xyz(θϕ))\nend\nfunction f(x)\n  -(laplacian_unit_sphere(uθϕ)(xyz2θϕ(x)))\nend\nfunction Gridap.∇(::typeof(u))\n  gradient_unit_sphere(uθϕ)\nend\n\nfunction solve_laplace_beltrami(model,order,degree,ls=BackslashSolver())\n    V = FESpace(model,ReferenceFE(lagrangian,Float64,order); conformity=:H1)\n    U = TrialFESpace(V)\n\n    Ω = Triangulation(model)\n    dΩ = Measure(Ω,degree)\n\n    a(u,v) = ∫(∇(v)⋅∇(u))dΩ\n    b(v)   = ∫(v*f)dΩ\n\n    op = AffineFEOperator(a,b,U,V)\n    fels = LinearFESolver(ls)\n    uh = solve(fels,op)\n\n    e=u-uh\n    ∇e = ∇(uh)-∇(u)∘xyz2θϕ\n\n    # H1-norm\n    # sqrt(sum(∫( e*e + (∇e)⋅(∇e) )dΩ))\n    sqrt(sum(∫( (∇e)⋅(∇e) )dΩ))#,uh\nend\n", "meta": {"hexsha": "965e7871f7816866370c9d59d25896107c06ef8b", "size": 1261, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/LaplaceBeltramiCubedSphereTests.jl", "max_stars_repo_name": "santiagobadia/GridapGeosciences", "max_stars_repo_head_hexsha": "c9bfdd7bbd33a8464376d1d102a44d78ccd11069", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-19T11:54:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-19T11:54:42.000Z", "max_issues_repo_path": "test/LaplaceBeltramiCubedSphereTests.jl", "max_issues_repo_name": "santiagobadia/GridapGeosciences", "max_issues_repo_head_hexsha": "c9bfdd7bbd33a8464376d1d102a44d78ccd11069", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/LaplaceBeltramiCubedSphereTests.jl", "max_forks_repo_name": "santiagobadia/GridapGeosciences", "max_forks_repo_head_hexsha": "c9bfdd7bbd33a8464376d1d102a44d78ccd11069", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2708333333, "max_line_length": 76, "alphanum_fraction": 0.6526566217, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748209, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7883551523611142}}
{"text": "#=\n  Two children problem in Turing.jl\n\n  https://robeastaway.com/blog/boy-girl\n  \"\"\"\n  I have two children, at least one of whom is a boy.  \n  What is the chance that the second child is also a boy?\n\n  ...\n\n  The classic, surprising answer is that the chance of a second \n  boy is 1/3, not 1/2 as most would expect.  Why?  Because if I \n  have two children, there is an equal chance that they will be \n  Boy-Boy, Boy-Girl, Girl-Boy or Girl-Girl.  There are three \n  equally likely combinations in which at least one child is \n  a boy (BB, BG and GB) and only in the first scenario is the \n  other child also a boy.\n  \"\"\"\n\n  We assume the inital probability of a boy/girl as 0.5.\n\n  Here we model two similiar but different problems to show\n  the difference between these two views of the problem.\n\n  Cf ~/webppl/two_children_problem.wppl\n\n=#\n\nusing Turing\ninclude(\"jl_utils.jl\")\n\n#=\n  First model: \n  \"\"\"\n  I have two children, _at least one of whom_ is a boy.  \n  What is the chance that the second child is also a boy?\n  \"\"\"\n\n  Probability of 2 boys: 1/3.\n  Probability of 1 boy and 1 girl: 2/3.\n\n  Distributions of variable twoBoys (num:0)\n  0.00000 =>    6601  (0.660100)\n  1.00000 =>    3399  (0.339900)\n\n  Distributions of variable oneBoyOneGirl (num:0)\n  1.00000 =>    6601  (0.660100)\n  0.00000 =>    3399  (0.339900)\n\n=#\n@model function two_children_problem_1()\n    boy = 1\n    girl = 2\n\n    child1 ~ Categorical([0.5,0.5])\n    child2 ~ Categorical([0.5,0.5])\n\n    # Note: it's important that we state the condition\n    #   \"at least one of whom is a boy\"\n    # as something like this.\n    true ~ Dirac((child1 == boy) + (child2 == boy) >= 1)\n    \n    twoBoys ~ Dirac((child1 == boy) + (child2 == boy) == 2)\n    oneBoyOneGirl ~ Dirac((child1 == boy) + (child2 == boy) == 1)\n\nend\n\nprintln(\"\\nModel 1\")\nmodel = two_children_problem_1()\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(5), 10_000)\n# chns = sample(model, IS(), 10_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, NUTS(), 10_000)\n# chns = sample(model, HMC(0.1,10), 10_000)\n\n# display(chns)\nshow_var_dist_pct(chns,:twoBoys)\nshow_var_dist_pct(chns,:oneBoyOneGirl)\n\n\n#=\n Second model:\n  \"\"\"\n  I have two children, the eldest is a boy.  \n  What is the chance that the second child is also a boy?\n  \"\"\"\n\n  Probability that the second child is also a boy: 1/2\n  Probability that the second child is a girl: 1/2\n\n  Distributions of variable twoBoys (num:0)\n  0.00000 =>    5067  (0.506700)\n  1.00000 =>    4933  (0.493300)\n  Distributions of variable oneBoyOneGirl (num:0)\n  1.00000 =>    5067  (0.506700)\n  0.00000 =>    4933  (0.493300)\n\n=#\n@model function two_children_problem_2()\n    boy = 1\n    girl = 2\n\n    child1 ~ Categorical([0.5,0.5])\n    child2 ~ Categorical([0.5,0.5])\n    \n    # \"The eldest is a boy\"\n    true ~ Dirac(child1 == boy)\n    \n    twoBoys ~ Dirac((child1 == boy) + (child2 == boy) == 2)\n    oneBoyOneGirl ~ Dirac((child1 == boy) + (child2 == boy) == 1)\n\nend\n\nprintln(\"\\nModel 2\")\nmodel = two_children_problem_2()\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(5), 10_000)\n# chns = sample(model, IS(), 10_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, NUTS(), 10_000)\n# chns = sample(model, HMC(0.1,10), 10_000)\n\n# display(chns)\nshow_var_dist_pct(chns,:twoBoys)\nshow_var_dist_pct(chns,:oneBoyOneGirl)\n", "meta": {"hexsha": "03bf4a9523c027ad45cf99234cf7152e3f131b8a", "size": 3433, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/two_children_problem.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/two_children_problem.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/two_children_problem.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 26.6124031008, "max_line_length": 65, "alphanum_fraction": 0.6539469851, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8740772368049822, "lm_q1q2_score": 0.7883483373668915}}
{"text": "\"\"\"\nDiscrete Laplacian in d dimensions and n equidistant discretization points in each direction\n\"\"\"\nfunction Lap(n::Integer,d::Integer) #returns the tensor of the discrete Laplacian in a box [0,1]^d with n equidistant discretization points in each direction\n    A = zeros(n^d,n^d)    \n    for j in 0:n^d-1\n        J = digits(j,base=n,pad=d) #corresponding index as d-tuples\n        for k in 0:d-1\n            if J[k+1]==0\n                A[j+1,j+1] = 2*d\n                A[j+1,j+n^k+1] = -1\n            elseif J[k+1]==n-1\n                A[j+1,j+1] = 2*d\n                A[j+1,j-n^k+1] = -1\n            else\n                A[j+1,j+1] = 2*d\n                A[j+1,j-n^k+1] = -1\n                A[j+1,j+n^k+1] = -1\n            end\n        end\n    end\n    return A\nend\n", "meta": {"hexsha": "2c139a8f7540dd5876d9940d8421a8c20a89da01", "size": 767, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/discrete_laplacian.jl", "max_stars_repo_name": "msdupuy/Tensor-Train-Julia", "max_stars_repo_head_hexsha": "327545d2e690c40d218d6316b69cf912963591e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-30T11:39:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T10:05:54.000Z", "max_issues_repo_path": "test/discrete_laplacian.jl", "max_issues_repo_name": "msdupuy/Tensor-Train-Julia", "max_issues_repo_head_hexsha": "327545d2e690c40d218d6316b69cf912963591e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/discrete_laplacian.jl", "max_forks_repo_name": "msdupuy/Tensor-Train-Julia", "max_forks_repo_head_hexsha": "327545d2e690c40d218d6316b69cf912963591e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9583333333, "max_line_length": 157, "alphanum_fraction": 0.4837027379, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769120761569, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.788331712438498}}
{"text": "\"\"\" \n    legendre(x, b)\n\nCompute Legendre polynomials.\n\nLegendre polynomials are Jacobi polynomials with parameters a and b equals to zero.\n\nSame interface as `jacobi`. `dlegendre` computes the derivative of the Legendre \npolynomial.\n\n# Example\n```julia-repl\njulia> x = legendre(0.4, 5)\n0.27063999999999994\n\njulia> x = legendre(2//5, 5)\n3383//12500\n\njulia> x = dlegendre(0.4, 5)\n-1.3170000000000002\n\njulia> x = dlegendre(2//5, 5)\n-1317//1000\n```\n\"\"\"\nfunction legendre(x, n)\n\n\n    if n==0\n        return one(x)\n    elseif n==1\n        return(x)\n    end\n\n    p0 = one(x)\n    p1 = x\n\n    for i = 2:n\n        p2 = ( (2i-1)*x*p1 - (i-1)*p0 ) / i\n        p0 = p1\n        p1 = p2\n    end\n\n    return p1\nend\n\n\n\ndlegendre(x, n) = djacobi(x, n)\n\n\nlegendre_zeros(m) = jacobi_zeros(m)\n\n@doc (@doc legendre) dlegendre\n@doc (@doc jacobi_zeros!) legendre_zeros\n\n\n\n", "meta": {"hexsha": "f9ae40685184a1c1ee99ada9764c3660c7eeba27", "size": 849, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/legendre.jl", "max_stars_repo_name": "pjabardo/Jacobi.jl", "max_stars_repo_head_hexsha": "c1bfe73688ca47da70a5dc3b46083237382d41c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2015-11-23T03:17:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T16:38:43.000Z", "max_issues_repo_path": "src/legendre.jl", "max_issues_repo_name": "pjabardo/Jacobi.jl", "max_issues_repo_head_hexsha": "c1bfe73688ca47da70a5dc3b46083237382d41c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2018-08-08T20:38:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-09T15:22:25.000Z", "max_forks_repo_path": "src/legendre.jl", "max_forks_repo_name": "pjabardo/Jacobi.jl", "max_forks_repo_head_hexsha": "c1bfe73688ca47da70a5dc3b46083237382d41c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2016-01-08T20:07:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:22:22.000Z", "avg_line_length": 14.3898305085, "max_line_length": 83, "alphanum_fraction": 0.6136631331, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388754, "lm_q2_score": 0.8519528019683105, "lm_q1q2_score": 0.7882522614354976}}
{"text": "\"\"\"\r\n`prepare_interpolation(nodes::Matrix{T}, kernel::RK = RK_H0()) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nPrepare the interpolating normal spline by constructing and factoring Gram matrix of the problem.\r\nInitialize the `NormalSpline` object.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space and\r\n           `n_1` is the number of function value nodes. It means that each column in the matrix defines one node.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H0` if the spline is constructing as a continuous function,\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n\r\nReturn: prepared `NormalSpline` object.\r\n\"\"\"\r\nfunction prepare_interpolation(nodes::Matrix{T},\r\n                               kernel::RK = RK_H0()\r\n                              ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n     spline = _prepare_interpolation(nodes, kernel)\r\n     return spline\r\nend\r\n\r\n\"\"\"\r\n`construct_interpolation(spline::NormalSpline{T, RK}, values::Vector{T}) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nConstruct the interpolating normal spline by calculating its coefficients and\r\ncompletely initializing the `NormalSpline` object.\r\n# Arguments\r\n- `spline`: the prepared `NormalSpline` object.\r\n- `values`: function values at interpolation nodes.\r\n\r\nReturn: constructed `NormalSpline` object.\r\n\"\"\"\r\nfunction construct_interpolation(spline::NormalSpline{T, RK},\r\n                                 values::Vector{T}\r\n                                ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n    spline = _construct_interpolation(spline, values)\r\n    return spline\r\nend\r\n\r\n\"\"\"\r\n`interpolate(nodes::Matrix{T}, values::Vector{T}, kernel::RK = RK_H0()) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nPrepare and construct the interpolating normal spline.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space\r\n           and `n_1` is the number of function value nodes.\r\n           It means that each column in the matrix defines one node.\r\n- `values`: function values at interpolation nodes.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H0` if the spline is constructing as a continuous function,\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\nReturn: constructed `NormalSpline` object.\r\n\"\"\"\r\nfunction interpolate(nodes::Matrix{T},\r\n                     values::Vector{T},\r\n                     kernel::RK = RK_H0()\r\n                    ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n     spline = _prepare_interpolation(nodes, kernel)\r\n     spline = _construct_interpolation(spline, values)\r\n     return spline\r\nend\r\n\r\n########\r\n\r\n\"\"\"\r\n`prepare_interpolation(nodes::Matrix{T}, d_nodes::Matrix{T}, es::Matrix{T}, kernel::RK = RK_H1())\r\n                       where {T <: AbstractFloat, RK <: ReproducingKernel_1}`\r\n\r\nPrepare the spline by constructing and factoring a Gram matrix of the interpolation problem.\r\nInitialize the `NormalSpline` object.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space and\r\n           `n_1` is the number of function value nodes.\r\n            It means that each column in the matrix defines one node.\r\n- `d_nodes`: function directional derivatives nodes.\r\n             This should be an `n×n_2` matrix, where `n` is dimension of the sampled space and\r\n             `n_2` is the number of function directional derivative nodes.\r\n- `es`: Directions of the function directional derivatives.\r\n        This should be an `n×n_2` matrix, where `n` is dimension of the sampled space and\r\n        `n_2` is the number of function directional derivative nodes.\r\n        It means that each column in the matrix defines one direction of the function directional derivative.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n\r\nReturn: prepared `NormalSpline` object.\r\n\"\"\"\r\nfunction prepare_interpolation(nodes::Matrix{T},\r\n                               d_nodes::Matrix{T},\r\n                               es::Matrix{T},\r\n                               kernel::RK = RK_H1()\r\n                              ) where {T <: AbstractFloat, RK <: ReproducingKernel_1}\r\n     spline = _prepare_interpolation(nodes, d_nodes, es, kernel)\r\n     return spline\r\nend\r\n\r\n\"\"\"\r\n`construct_interpolation(spline::NormalSpline{T, RK}, values::Vector{T}, d_values::Vector{T})\r\n                         where {T <: AbstractFloat, RK <: ReproducingKernel_1}`\r\n\r\nConstruct the interpolating normal spline by calculating its coefficients and\r\ncompletely initializing the `NormalSpline` object.\r\n# Arguments\r\n- `spline`: the prepared `NormalSpline` object.\r\n- `values`: function values at interpolation nodes.\r\n- `d_values`: function directional derivative values at function derivative nodes.\r\n\r\nReturn: constructed `NormalSpline` object.\r\n\"\"\"\r\nfunction construct_interpolation(spline::NormalSpline{T, RK},\r\n                                 values::Vector{T},\r\n                                 d_values::Vector{T}\r\n                                ) where {T <: AbstractFloat, RK <: ReproducingKernel_1}\r\n     spline = _construct_interpolation(spline, values, d_values)\r\n     return spline\r\nend\r\n\r\n\"\"\"\r\n`interpolate(nodes::Matrix{T}, values::Vector{T}, d_nodes::Matrix{T}, es::Matrix{T}, d_values::Vector{T}, kernel::RK = RK_H1())\r\n             where {T <: AbstractFloat, RK <: ReproducingKernel_1}`\r\n\r\nPrepare and construct the interpolating normal spline.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space\r\n           and `n_1` is the number of function value nodes.\r\n           It means that each column in the matrix defines one node.\r\n- `values`: function values at interpolation nodes.\r\n- `d_nodes`: function directional derivative nodes.\r\n            This should be an `n×n_2` matrix, where `n` is dimension of the sampled space and\r\n            `n_2` is the number of function directional derivative nodes.\r\n- `es`: Directions of the function directional derivatives.\r\n       This should be an `n×n_2` matrix, where `n` is dimension of the sampled space and\r\n       `n_2` is the number of function directional derivative nodes.\r\n       It means that each column in the matrix defines one direction of the function directional derivative.\r\n- `d_values`: function directional derivative values at function derivative nodes.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n\r\nReturn: constructed `NormalSpline` object.\r\n\"\"\"\r\nfunction interpolate(nodes::Matrix{T},\r\n                     values::Vector{T},\r\n                     d_nodes::Matrix{T},\r\n                     es::Matrix{T},\r\n                     d_values::Vector{T},\r\n                     kernel::RK = RK_H1()\r\n                    ) where {T <: AbstractFloat, RK <: ReproducingKernel_1}\r\n     spline = _prepare_interpolation(nodes, d_nodes, es, kernel)\r\n     spline = _construct_interpolation(spline, values, d_values)\r\n     return spline\r\nend\r\n\r\n############################## One-dimensional case\r\n\r\n\"\"\"\r\n`prepare_interpolation(nodes::Vector{T}, kernel::RK = RK_H0()) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nPrepare the 1D interpolating normal spline by constructing and factoring a Gram matrix of the problem.\r\nInitialize the `NormalSpline` object.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n           This should be an `n_1` vector where `n_1` is the number of function value nodes.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H0` if the spline is constructing as a continuous function,\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n\r\nReturn: prepared `NormalSpline` object.\r\n\"\"\"\r\nfunction prepare_interpolation(nodes::Vector{T},\r\n                               kernel::RK = RK_H0()\r\n                              ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n     spline = _prepare_interpolation(Matrix(nodes'), kernel)\r\n     return spline\r\nend\r\n\r\n\"\"\"\r\n`interpolate(nodes::Vector{T}, values::Vector{T}, kernel::RK = RK_H0()) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nPrepare and construct the 1D interpolating normal spline.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n           This should be an `n_1` vector where `n_1` is the number of function value nodes.\r\n- `values`: function values at `n_1` interpolation nodes.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H0` if the spline is constructing as a continuous function,\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n\r\nReturn: constructed `NormalSpline` object.\r\n\"\"\"\r\nfunction interpolate(nodes::Vector{T},\r\n                     values::Vector{T},\r\n                     kernel::RK = RK_H0()\r\n                    ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n     spline = _prepare_interpolation(Matrix(nodes'), kernel)\r\n     spline = _construct_interpolation(spline, values)\r\n     return spline\r\nend\r\n\r\n\"\"\"\r\n`prepare_interpolation(nodes::Vector{T}, d_nodes::Vector{T}, kernel::RK = RK_H1()) where {T <: AbstractFloat, RK <: ReproducingKernel_1}`\r\n\r\nPrepare the 1D interpolating normal spline by constructing and factoring a Gram matrix of the problem.\r\nInitialize the `NormalSpline` object.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n           This should be an `n_1` vector where `n_1` is the number of function value nodes.\r\n- `d_nodes`: The function derivatives nodes.\r\n             This should be an `n_2` vector where `n_2` is the number of function derivatives nodes.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n\r\nReturn: prepared `NormalSpline` object.\r\n\"\"\"\r\nfunction prepare_interpolation(nodes::Vector{T},\r\n                               d_nodes::Vector{T},\r\n                               kernel::RK = RK_H1()\r\n                              ) where {T <: AbstractFloat, RK <: ReproducingKernel_1}\r\n\r\n     es = ones(T, length(d_nodes))\r\n     spline = _prepare_interpolation(Matrix(nodes'), Matrix(d_nodes'), Matrix(es'), kernel)\r\n     return spline\r\nend\r\n\r\n\"\"\"\r\n`interpolate(nodes::Vector{T}, values::Vector{T}, d_nodes::Vector{T}, d_values::Vector{T},\r\n             kernel::RK = RK_H1())\r\n             where {T <: AbstractFloat, RK <: ReproducingKernel_1}`\r\n\r\nprepare_interpolation and construct the 1D interpolating normal spline.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n           This should be an `n_1` vector where `n_1` is the number of function value nodes.\r\n- `values`: function values at `nodes` nodes.\r\n- `d_nodes`: The function derivatives nodes.\r\n             This should be an `n_2` vector where `n_2` is the number of function derivatives nodes.\r\n- `d_values`: function derivative values at function derivative nodes.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n\r\nReturn: constructed `NormalSpline` object.\r\n\"\"\"\r\nfunction interpolate(nodes::Vector{T},\r\n                     values::Vector{T},\r\n                     d_nodes::Vector{T},\r\n                     d_values::Vector{T},\r\n                     kernel::RK = RK_H1()\r\n                    ) where {T <: AbstractFloat, RK <: ReproducingKernel_1}\r\n     es = ones(T, length(d_nodes))\r\n     spline = _prepare_interpolation(Matrix(nodes'), Matrix(d_nodes'), Matrix(es'), kernel)\r\n     spline = _construct_interpolation(spline, values, d_values)\r\n     return spline\r\nend\r\n", "meta": {"hexsha": "cb49ff10f52ffc2ba4eadb87a2d8042c5e5960e3", "size": 13631, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NormalInterpolatingSplines.jl", "max_stars_repo_name": "IgorKohan/NormalSmoothingSplines.jl", "max_stars_repo_head_hexsha": "828b167daba02bf637463fe00afb53ea349058fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NormalInterpolatingSplines.jl", "max_issues_repo_name": "IgorKohan/NormalSmoothingSplines.jl", "max_issues_repo_head_hexsha": "828b167daba02bf637463fe00afb53ea349058fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NormalInterpolatingSplines.jl", "max_forks_repo_name": "IgorKohan/NormalSmoothingSplines.jl", "max_forks_repo_head_hexsha": "828b167daba02bf637463fe00afb53ea349058fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.1139705882, "max_line_length": 138, "alphanum_fraction": 0.6549776245, "num_tokens": 2897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229961215457, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7882522544446523}}
{"text": "#=\n\n# 107: 1D Nonlinear Storage \n([source code](SOURCE_URL))\n\nThis equation comes from the transformation of the nonlinear diffuision equation.\n```math\n\\partial_t u^\\frac{1}{m} -\\Delta u = 0\n```\nin $\\Omega=(-1,1)$ with homogeneous Neumann boundary conditions.\nWe can derive an exact solution from the Barenblatt solution of the previous\nexample.\n\n=#\n\nmodule Example107_NonlinearStorage1D\nusing Printf\nusing VoronoiFVM\nusing ExtendableGrids\nusing GridVisualize\n\nfunction barenblatt(x,t,m)\n    tx=t^(-1.0/(m+1.0))\n    xx=x*tx\n    xx=xx*xx\n    xx=1- xx*(m-1)/(2.0*m*(m+1));\n    if xx<0.0\n        xx=0.0\n    end\n    return tx*xx^(1.0/(m-1.0))\nend\n\n\nfunction main(;n=20,m=2.0,Plotter=nothing,verbose=false, unknown_storage=:sparse,tend=0.01,tstep=0.0001)\n    \n    ## Create a one-dimensional discretization\n    h=1.0/convert(Float64,n/2)\n    X=collect(-1:h:1)\n    grid=VoronoiFVM.Grid(X)\n\n    ## Flux function which describes the flux\n    ## between neigboring control volumes\n    function flux!(f,u0,edge)\n        u=unknowns(edge,u0)\n        f[1]=u[1,1]-u[1,2]\n    end\n\n    ϵ=1.0e-10\n\n    ## Storage term\n    ## This needs to be regularized as its derivative\n    ## at 0 is infinity\n    function storage!(f,u,node)\n        f[1]=(ϵ+u[1])^(1.0/m)\n    end\n    \n    ## Create a physics structure\n    physics=VoronoiFVM.Physics(\n        flux=flux!,\n        storage=storage!)\n    \n    \n    ## Create a finite volume system - either\n    ## in the dense or  the sparse version.\n    ## The difference is in the way the solution object\n    ## is stored - as dense or as sparse matrix\n    sys=VoronoiFVM.System(grid,physics,unknown_storage=unknown_storage)\n\n    ## Add species 1 to region 1\n    enable_species!(sys,1,[1])\n    \n    ## Create a solution array\n    inival=unknowns(sys)\n    solution=unknowns(sys)\n    t0=0.001\n\n    ## Broadcast the initial value\n    inival[1,:].=map(x->barenblatt(x,t0,m)^m,X)\n    solution.=inival\n\n    ## Create solver control info\n    control=VoronoiFVM.NewtonControl()\n    control.verbose=verbose\n    time=t0\n    p=GridVisualizer(Plotter=Plotter,layout=(2,1))\n    while time<tend\n        time=time+tstep\n        solve!(solution,inival,sys,control=control,tstep=tstep)\n        inival.=solution\n        scalarplot!(p[1,1],grid,solution[1,:],title=@sprintf(\"numerical, t=%.5f\",time),clear=true)\n        scalarplot!(p[2,1],grid,map(x->barenblatt(x,time,m)^m,grid),title=@sprintf(\"exact, t=%.4f\",time),clear=true)\n        sleep(1.0e-5)\n#        yield()\n    end\n    return sum(solution)\nend\n\n\nfunction test()\n    testval=173.84998139534142\n    main(unknown_storage=:sparse) ≈ testval && main(unknown_storage=:dense) ≈ testval\nend\n\nend \n\n", "meta": {"hexsha": "83194895de7951b9120506ff87ad8156d9bb91f3", "size": 2649, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Example107_NonlinearStorage1D.jl", "max_stars_repo_name": "NunoEdgarGFlowHub/VoronoiFVM.jl", "max_stars_repo_head_hexsha": "c9f5834a2052414e9d174e7c423d9d68e1406fd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Example107_NonlinearStorage1D.jl", "max_issues_repo_name": "NunoEdgarGFlowHub/VoronoiFVM.jl", "max_issues_repo_head_hexsha": "c9f5834a2052414e9d174e7c423d9d68e1406fd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Example107_NonlinearStorage1D.jl", "max_forks_repo_name": "NunoEdgarGFlowHub/VoronoiFVM.jl", "max_forks_repo_head_hexsha": "c9f5834a2052414e9d174e7c423d9d68e1406fd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9905660377, "max_line_length": 116, "alphanum_fraction": 0.650811627, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.7882522527057088}}
{"text": "import Distributions: logpdf, DiscreteUnivariateDistribution\n\n\"\"\"\nNumerically stable Poisson log likelihood function. Accepts log of rate parameter.\n\"\"\"\nstruct LogPoisson{T<:Real} <: DiscreteUnivariateDistribution\n    logλ::T\nend\n\nfunction logpdf(lp::LogPoisson, k::Int)\n    return k * lp.logλ - exp(lp.logλ) - loggamma(k + 1)\nend\n\n@model AHMCpoisson(y, x, idx, N, Ns) = begin\n  a0 ~ Normal(0, 10)\n  a1 ~ Normal(0, 1)\n  a0_sig ~ Truncated(Cauchy(0, 1), 0.0, Inf)\n  a0s ~ MvNormal(zeros(Ns), a0_sig)\n  for i ∈ 1:N\n    λ = a0 + a0s[idx[i]] + a1 * x[i]\n    y[i] ~ LogPoisson(λ)\n  end\nend\n\nAHMCconfig = Turing.NUTS(1000, .80)\n\nfunction simulatePoisson(; Nd=1, Ns=10, a0=1.0, a1=.5, a0_sig=.3, kwargs...)\n  N = Nd * Ns\n  y = fill(0, N)\n  x = fill(0.0, N)\n  idx = similar(y)\n  i = 0\n  for s in 1:Ns\n    a0s = rand(Normal(0, a0_sig))\n    logpop = rand(Normal(9, 1.5))\n    λ = exp(a0 + a0s + a1 * logpop)\n    for nd in 1:Nd\n      i += 1\n      x[i] = logpop\n      idx[i] = s\n      y[i] = rand(Poisson(λ))\n    end\n  end\n  return (y=y, x=x, idx=idx, N=N, Ns=Ns)\n end\n\nCmdStanPoisson = \"\ndata {\n  int N;\n  int y[N];\n  int Ns;\n  int idx[N];\n  real x[N];\n}\nparameters {\n  real a0;\n  vector[Ns] a0s;\n  real a1;\n  real<lower=0> a0_sig;\n}\nmodel {\n  vector[N] mu;\n  a0 ~ normal(0, 10);\n  a1 ~ normal(0, 1);\n  a0_sig ~ cauchy(0, 1);\n  a0s ~ normal(0, a0_sig);\n  for(i in 1:N) mu[i] = exp(a0 + a0s[idx[i]] + a1 * x[i]);\n  y ~ poisson(mu);\n}\n\"\n\nCmdStanConfig = Stanmodel(\n  name=\"CmdStanPoisson\", model=CmdStanPoisson, nchains=1, output_format=:mcmcchains,\n  Sample(num_samples=1000, num_warmup=1000, adapt=CmdStan.Adapt(delta=0.8), save_warmup=true)\n)\n\nstruct PoissonProb\n  y::Array{Int64,1}\n  x::Array{Float64,1}\n  idx::Array{Int64,1}\n  N::Int64\n  Ns::Int64\nend\n\nfunction (problem::PoissonProb)(θ)\n  @unpack y, x, idx, N, Ns = problem   # extract the data\n  @unpack a0, a1, a0s, a0_sig = θ\n  LL = 0.0\n  LL += logpdf(Truncated(Cauchy(0, 1), 0.0, Inf), a0_sig)\n  LL += sum(logpdf(MvNormal(zeros(Ns), a0_sig), a0s))\n  LL += logpdf.(Normal(0, 10), a0)\n  LL += logpdf.(Normal(0, 1), a1)\n  for i in 1:N\n    λ = a0 + a0s[idx[i]] + a1 * x[i]\n    LL += logpdf(LogPoisson(λ), y[i])\n  end\n  return LL\nend\n\n# Define problem with data and inits.\nfunction sampleDHMC(y, x, idx, N, Ns, nsamples, autodiff)\n  p = PoissonProb(y, x, idx, N, Ns)\n  p((a0=0.0, a1=0.0, a0s=fill(0.0, Ns), a0_sig=.3))\n  # Write a function to return properly dimensioned transformation.\n  trans = as((a0=asℝ, a1=asℝ, a0s=as(Array, Ns), a0_sig=asℝ₊))\n  P = TransformedLogDensity(trans, p)\n  ∇P = ADgradient(autodiff, P)\n  # Sample from the posterior.\n  results = mcmc_with_warmup(Random.GLOBAL_RNG, ∇P, nsamples; reporter = NoProgressReport())\n  # Undo the transformation to obtain the posterior from the chain.\n  posterior = TransformVariables.transform.(trans, results.chain)\n  chns = nptochain(results, posterior)\n  return chns\nend\n", "meta": {"hexsha": "4b47e065486b5fdf432a9c8ba102a0c793786aba", "size": 2875, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Hierarchical_Poisson/Hierarhical_Poisson_Models.jl", "max_stars_repo_name": "StatisticalRethinkingJulia/MCMCBenchmarkSuite", "max_stars_repo_head_hexsha": "6e3e460d9b19b2c370d4046f5d89e80c3ae02003", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-01-04T14:22:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-10T13:02:48.000Z", "max_issues_repo_path": "src/Hierarchical_Poisson/Hierarhical_Poisson_Models.jl", "max_issues_repo_name": "StatisticalRethinkingJulia/MCMCBenchmarkSuite.jl", "max_issues_repo_head_hexsha": "6e3e460d9b19b2c370d4046f5d89e80c3ae02003", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-01-04T15:16:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-25T15:52:58.000Z", "max_forks_repo_path": "src/Hierarchical_Poisson/Hierarhical_Poisson_Models.jl", "max_forks_repo_name": "StatisticalRethinkingJulia/MCMCBenchmarkSuite.jl", "max_forks_repo_head_hexsha": "6e3e460d9b19b2c370d4046f5d89e80c3ae02003", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-04T14:05:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-25T16:28:55.000Z", "avg_line_length": 25.0, "max_line_length": 93, "alphanum_fraction": 0.6326956522, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317102, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7882320725364067}}
{"text": "\"\"\"\r\n    kompsimp(f,a,b,M)\r\nadalah fungsi yang digunakan untuk menghitung nilai integral `f` secara numerik\r\npada interval `[a,b]` menggunakan komposit Simpson dengan `M` sub-interval.\r\n\r\n# Example\r\n```jl\r\njulia> a = 1; b = 6;\r\n\r\njulia> f(x) = 2+sin(2*sqrt(x));\r\n\r\njulia> y = kompsimp(f,a,b,10)\r\n8.183447496636239\r\n```\r\nreturn solusi `y`\r\n\"\"\"\r\nfunction kompsimp(f,a,b,M)\r\n  h = (b-a)/(2*M);\r\n  s1 = 0;   s2 = 0;\r\n  for k = 1:M\r\n    x = a + (2*k-1)*h;\r\n    s1 = s1 + f(x);\r\n  end\r\n  for k = 1:M-1\r\n    x = a + (2*k)*h;\r\n    s2 = s2 + f(x);\r\n  end\r\n  y = h/3*(f(a)+f(b)+4*s1+2*s2)\r\nend\r\n", "meta": {"hexsha": "f33956b1660335d5f4b839ef0f4a06f59bc05556", "size": 585, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kompsimp.jl", "max_stars_repo_name": "mkhoirun-najiboi/metnum.jl", "max_stars_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kompsimp.jl", "max_issues_repo_name": "mkhoirun-najiboi/metnum.jl", "max_issues_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kompsimp.jl", "max_forks_repo_name": "mkhoirun-najiboi/metnum.jl", "max_forks_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5, "max_line_length": 80, "alphanum_fraction": 0.5282051282, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7882320723688416}}
{"text": "\"\"\"\n    function length_conversion(value, from_type, to_type)\n\nA function that converts a value from a measurement unit to another one\n\nAccepted units are: millimeter(s), centimeter(s), meter(s), kilometer(s),\ninch(es), feet, foot, yard(s), mile(s). Abbreviations are also supported.\n\n# Examples/Tests (optional but recommended)\n```julia\nlength_conversion(10, \"METERS\", \"cm\")\nlength_conversion(12345, \"yards\", \"FEET\")\n```\n\nBecause the algorithm converts values to meters, and from meters to the final type,\nsome imperial system units may have errors:\nlength_conversion(1, \"yards\", \"FEET\") returns 3.000000096, intead of 3.\n\n# Contributed by:- [Fernanda Kawasaki](https://github.com/fernandakawasaki)\n\"\"\"\n\n# Lookup table that returns conversion of 1 unit of type to meters\nMETER_CONVERSION = Dict{String,Float64}(\n    \"mm\" => 0.001,\n    \"cm\" => 0.01,\n    \"m\" => 1,\n    \"km\" => 1000,\n    \"in\" => 0.0254,\n    \"ft\" => 0.3048,\n    \"yd\" => 0.9144,\n    \"mi\" => 1609.34,\n)\n\n# Lookup table that returns the conversion of 1 meter to type\nTYPE_CONVERSION = Dict{String,Float64}(\n    \"mm\" => 1000,\n    \"cm\" => 100,\n    \"m\" => 1,\n    \"km\" => 0.001,\n    \"in\" => 39.3701,\n    \"ft\" => 3.28084,\n    \"yd\" => 1.09361,\n    \"mi\" => 0.000621371,\n)\n\nNAME_CONVERSION = Dict{String,String}(\n    \"millimeter\" => \"mm\",\n    \"millimeters\" => \"mm\",\n    \"centimeter\" => \"cm\",\n    \"centimeters\" => \"cm\",\n    \"meter\" => \"m\",\n    \"meters\" => \"m\",\n    \"kilometer\" => \"km\",\n    \"kilometers\" => \"km\",\n    \"inch\" => \"in\",\n    \"inches\" => \"in\",\n    \"feet\" => \"ft\",\n    \"foot\" => \"ft\",\n    \"yard\" => \"yd\",\n    \"yards\" => \"yd\",\n    \"mile\" => \"mi\",\n    \"miles\" => \"mi\",\n)\n\nfunction normalize_type(type)\n    l_type = lowercase(type)\n    if !haskey(METER_CONVERSION, l_type)\n        if !haskey(NAME_CONVERSION, l_type)\n            throw(\n                error(\n                    \"Invalid 'type' value: $(type)\\n\",\n                    \"Supported values are: $(keys(NAME_CONVERSION))\\n\",\n                    \"Supported abbreviations are: $(keys(METER_CONVERSION))\\n\",\n                ),\n            )\n        end\n        return NAME_CONVERSION[l_type]\n    end\n    return l_type\nend\n\nfunction length_conversion(value, from_type, to_type)\n    from_type_norm = normalize_type(from_type)\n    to_type_norm = normalize_type(to_type)\n    value_in_meters = value * METER_CONVERSION[from_type_norm]\n    return value_in_meters * TYPE_CONVERSION[to_type_norm]\nend\n", "meta": {"hexsha": "cca0f8a872331af67233632ca0ca8d32dd67c4b2", "size": 2409, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/conversions/length_conversion.jl", "max_stars_repo_name": "Whiteshark-314/Julia", "max_stars_repo_head_hexsha": "3285d8d6b7585cc1075831c2c210b891151da0c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-14T21:48:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-14T21:48:50.000Z", "max_issues_repo_path": "src/conversions/length_conversion.jl", "max_issues_repo_name": "AugustoCL/Julia", "max_issues_repo_head_hexsha": "1bf4e4a7829fafc64290d903bcbfdd48eab839e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/conversions/length_conversion.jl", "max_forks_repo_name": "AugustoCL/Julia", "max_forks_repo_head_hexsha": "1bf4e4a7829fafc64290d903bcbfdd48eab839e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.375, "max_line_length": 83, "alphanum_fraction": 0.601494396, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8615382058759128, "lm_q1q2_score": 0.788222127318811}}
{"text": "### Error functions.\n\nfunction error_function_selector(error::ASCIIString)\n\tif error == \"absolute_error\"\n\t\treturn \"absolute_error\", absolute_error!, absolute_error_prime!\n\telseif error == \"cross_entropy\"\n\t\treturn \"cross_entropy\", cross_entropy!, cross_entropy_prime!\n\telse\n\t\treturn \"squared_error\", squared_error!, squared_error_prime!\n\tend\nend\n\nfunction absolute_error!{T<:FloatingPoint}(YH::AbstractVector{T}, Y::AbstractVector{T}, E::AbstractVector{T}; eta::T=1e-10)\n\t@inbounds begin\n\t\tfor i = 1:length(E)\n\t\t\tif YH[i] > Y[i]\n\t\t\t\tE[i] = YH[i] - Y[i]\n\t\t\telse\n\t\t\t\tE[i] = Y[i] - YH[i]\n\t\t\tend\n\t\tend\n\tend\nend\n\nfunction absolute_error_prime!{T<:FloatingPoint}(YH::AbstractVector{T}, Y::AbstractVector{T}, DE_DYH::AbstractVector{T}; eta::T=1e-10)\n\t@inbounds begin\n\t\tfor i = 1:length(Y)\n\t\t\tif YH[i] > Y[i]\n\t\t\t\tDE_DYH[i] = 1.0\n\t\t\telse\n\t\t\t\tDE_DYH[i] = -1.0\n\t\t\tend\n\t\tend\n\tend\nend\n\nfunction cross_entropy!{T<:FloatingPoint}(YH::AbstractVector{T}, Y::AbstractVector{T}, E::AbstractVector{T}; eta::T=1e-10)\n\t@inbounds begin\n\t\tfor i = 1:length(E)\n\t\t\tE[i] = -((Y[i] * log(YH[i] + eta)) + ((1.0 - Y[i]) * log(1.0 - YH[i] + eta)))\n\t\tend\n\tend\nend\n\nfunction cross_entropy_prime!{T<:FloatingPoint}(YH::AbstractVector{T}, Y::AbstractVector{T}, DE_DYH::AbstractVector{T}; eta::T=1e-10)\n\t@inbounds begin\n\t\tfor i = 1:length(Y)\n\t\t\tDE_DYH[i] = ((1.0 - Y[i]) / (1.0 - YH[i] + eta)) - (Y[i] / (YH[i] + eta))\n\t\tend\n\tend\nend\n\nfunction squared_error!{T<:FloatingPoint}(YH::AbstractVector{T}, Y::AbstractVector{T}, E::AbstractVector{T})\n\t@inbounds begin\n\t\tfor i = 1:length(E)\n\t\t\tE[i] = 0.5 * abs2(YH[i] - Y[i])\n\t\tend\n\tend\nend\n\nfunction squared_error_prime!{T<:FloatingPoint}(YH::AbstractVector{T}, Y::AbstractVector{T}, DE_DYH::AbstractVector{T})\n\t@inbounds begin\n\t\tfor i = 1:length(Y)\n\t\t\tDE_DYH[i] = YH[i] - Y[i]\n\t\tend\n\tend\nend", "meta": {"hexsha": "6baaf20822b4e8c9dc92faa106958725047b8ebb", "size": 1797, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/error_functions.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/StackedNets.jl-cde04a67-da5f-5e53-93c0-2a9e1e7feaac", "max_stars_repo_head_hexsha": "c18da9d82faa41042a7e4425438a249e5e57691f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/error_functions.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/StackedNets.jl-cde04a67-da5f-5e53-93c0-2a9e1e7feaac", "max_issues_repo_head_hexsha": "c18da9d82faa41042a7e4425438a249e5e57691f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/error_functions.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/StackedNets.jl-cde04a67-da5f-5e53-93c0-2a9e1e7feaac", "max_forks_repo_head_hexsha": "c18da9d82faa41042a7e4425438a249e5e57691f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8208955224, "max_line_length": 134, "alphanum_fraction": 0.6605453534, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7881949154968289}}
{"text": "\"\"\"\n```\ninitialize_stategrid(method::Symbol, dims::Vector{Int})\n```\nconstructs a state grid (using the implementation in EconPDEs)\nusing various methods, such as Chebyshev points.\n\"\"\"\nfunction initialize_stategrid(method::Symbol, grid_info::OrderedDict{Symbol, Tuple{T, T, Int}};\n                              get_stategrid::Bool = true) where {T <: Real}\n    stategrid_init = OrderedDict{Symbol, Vector{T}}()\n    if method == :uniform\n        for (k, v) in grid_info\n            stategrid_init[k] = range(v[1], stop = v[2], length = v[3])\n        end\n    elseif method == :chebyshev\n        for (k, v) in grid_info\n            stategrid_init[k] = v[1] .+ 1. / 2. * (v[2] - v[1]) .* (1. .- cos(pi * (0:(v[3] - 1))' / (v[3] - 1)))\n        end\n    elseif method == :exponential\n        for (k, v) in grid_info\n            stategrid_init[k] = exp.(range(log(v[1]), stop = log(v[2]), length = v[3]))\n        end\n    elseif method == :smolyak\n        error(\"Construction of a Smolyak interpolation grid has not been implemented yet.\")\n        # This should make a call to BasisMatrices from QuantEcon, as they have a nice user-friendly implementation of Smolyak.\n        # Alternatively, we can try SmolyakApprox, tho QuantEcon seems more likely to be well-maintained.\n    else\n        error(\"Grid construction method $method has not been implemented.\")\n    end\n\n    if get_stategrid\n        return StateGrid(stategrid_init)\n    else\n        return stategrid_init\n    end\nend\n", "meta": {"hexsha": "4f2b59fc730d92929e91b7c7fd470b8c1cb96c84", "size": 1471, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/auxiliary/initialize_grid.jl", "max_stars_repo_name": "chenwilliam77/EconFixedPointPDEs", "max_stars_repo_head_hexsha": "50ce1f61fc796605a2d0e81b08dd472444182e2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-31T00:29:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T00:29:04.000Z", "max_issues_repo_path": "src/auxiliary/initialize_grid.jl", "max_issues_repo_name": "chenwilliam77/EconFixedPointPDEs", "max_issues_repo_head_hexsha": "50ce1f61fc796605a2d0e81b08dd472444182e2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/auxiliary/initialize_grid.jl", "max_forks_repo_name": "chenwilliam77/EconFixedPointPDEs", "max_forks_repo_head_hexsha": "50ce1f61fc796605a2d0e81b08dd472444182e2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-19T16:40:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T16:40:44.000Z", "avg_line_length": 39.7567567568, "max_line_length": 127, "alphanum_fraction": 0.6206662135, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7881949103494362}}
{"text": "\"\"\"\nnonparametric regression and quantile regression\n* uses pre-generated kernel weights\n* can be local constant, local linear, or local quadratic\n\ny is n X p\n\nx is n X dimx\n\nxeval is neval X dimx\n\nweights is n X neval (different weights for each eval. point)\n\nweights should sum to one by columns, they are typical \nnonparametric weights from a kernel.\n\nkeyword order=0,1 or 2 for local consant, local linear, or local quadratic\n(default local linear)\n\nkeyword do_median (default false)\nkeyword do_ci to compute .05 and 0.95 quantiles\n\nexecute npreg() for an example\n\"\"\"\n\nusing Random, Econometrics, Plots\nfunction npreg(bandwidth=-1)\n    println(\"npreg(), with no arguments, runs a simple example\")\n    println(\"npreg(bw) will run the example with your chosen bandwidth (Float64)\")\n    println(\"execute edit(npreg,()) to see the code\")\n    k = 1 # number of regressors\n    Random.seed!(1) # set seed to \n    n = 1000\n    bandwidth == -1 ? bandwidth = 0.25*n^(-1.0/(4 + k)) : nothing\n    neval = 100\n    x = rand(n)*pi*2.0 # from 0 to 2π   \n    xeval = collect(range(pi/2., stop=pi*1.5, length=neval)) # from π/2 to 3π/2  \n    y = cos.(x) .+ 0.25 .* cos.(3.0.*x) + 0.1*randn(n)\n    # npreg wants args to be matrices, not vectors, so convert them\n    y = reshape(y,n,1)\n    x = reshape(x,n,1)\n    xeval = reshape(xeval,neval,1)\n    ytrue = cos.(xeval) .+ 0.25.*cos.(3.0*xeval)\n    weights = kernelweights(x, xeval, bandwidth, true, \"knngaussian\", 200)\n    yhat, y50, y05, y95 = npreg(y, x, xeval, weights, order=1, do_median=true, do_ci=true)\n    labels = [\"true\" \"mean\" \"median\" \"0.05 quantile\" \"0.95 quantile\"]\n    title = \"Kernel regression and quantiles\"\n    p = Plots.plot(xeval, [ytrue yhat y50 y05 y95], labels=labels, title=title)\n    display(p)\n    nothing\nend \n\nfunction npreg(y, x, xeval, weights; order=1, do_median=false, do_ci=false)\n    weights = sqrt.(weights)\n    neval, dimx = size(xeval)\n    n, dimy = size(y)\n    # local constant\n    if order==0            \n        X = ones(n,1)\n        Xeval = ones(neval,1)\n    elseif order==1    \n    # local linear    \n        X = [ones(n,1) x]\n        Xeval = [ones(neval,1) xeval]\n    else\n    # local quadratic\n        stacked = [x; xeval]\n        # cross products\n        CP = zeros(n+neval, Int((dimx-1)*dimx/2))\n        cpind = 0\n        for i = 1:dimx-1\n            for j = (i+1):dimx\n                cpind += 1\n                CP[:,cpind] = stacked[:,[i]].*stacked[:,[j]]\n            end\n        end\n        ZZ = [ones(n+neval,1) stacked CP]\n        X = view(ZZ,1:n,:)\n        Xeval = view(ZZ,(n+1):n+neval,:)\n    end\n    # do the fit\n    yhat = zeros(neval, dimy)\n    y50 = nothing\n    y05 = nothing\n    y95 = nothing\n    if do_median y50 = zeros(neval, dimy) end\n    if do_ci\n        y05 = zeros(neval, dimy)\n        y95 = zeros(neval, dimy)\n    end\n    for i = 1:neval\n        WX = weights[:,i] .* X\n        Wy = weights[:,i] .* y\n        b = WX\\Wy\n        yhat[i,:] = Xeval[i:i,:]*b\n        if do_median\n            for j = 1:dimy\n                y50[i,j] = (Xeval[i:i,:]*qreg_coef(Wy[:,j], WX, 0.5))[1,1]\n            end\n        end    \n        if do_ci\n            for j = 1:dimy\n                y05[i,j] = (Xeval[i:i,:]*qreg_coef(Wy[:,j], WX, 0.05))[1,1]\n                y95[i,j] = (Xeval[i:i,:]*qreg_coef(Wy[:,j], WX, 0.95))[1,1]\n            end\n        end    \n    end\n    if do_median==false\n        return yhat\n    elseif do_ci==false\n        return yhat, y50\n    else\n        return yhat, y50, y05, y95\n    end    \nend\n", "meta": {"hexsha": "cf9a9adcee8cf43e39a9f340e13b40872992af8f", "size": 3497, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NP/npreg.jl", "max_stars_repo_name": "Hiroakiyusheng/Econometrics", "max_stars_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-19T18:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T18:23:45.000Z", "max_issues_repo_path": "src/NP/npreg.jl", "max_issues_repo_name": "Hiroakiyusheng/Econometrics", "max_issues_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NP/npreg.jl", "max_forks_repo_name": "Hiroakiyusheng/Econometrics", "max_forks_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1465517241, "max_line_length": 90, "alphanum_fraction": 0.5661995997, "num_tokens": 1157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144265, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7881887209125706}}
{"text": "\nfunction harmonic(n::Integer)\n    H = 0.0\n    for i in n:-1:1\n        H += 1 / i\n    end\n    return H\nend\n\nfunction harmonic(n::Integer, m::Integer)\n    H = 0.0\n    for i in n:-1:1\n        H += 1 / (i ^ m)\n    end\n    return H\nend\n\ntd_a1(n::Integer) = harmonic(n - 1)\n\ntd_a2(n::Integer) = harmonic(n - 1, 2)\n\ntd_b1(n::Integer) = (n + 1) / (3 * (n - 1))\n\nfunction td_b2(n::Integer)\n    return (2 * ((n ^ 2) + n + 3)) / ((9 * n) * (n - 1))\nend\n\ntd_c1(a1::AbstractFloat, b1::AbstractFloat) = b1 - 1 / a1\n\nfunction td_c2(n::Integer, a1::AbstractFloat, a2::AbstractFloat, b2::AbstractFloat)\n    return b2 - ((n + 2) / (a1 * n)) + a2 / (a1 ^ 2)\nend\n\ntd_e1(a1::AbstractFloat, c1::AbstractFloat) = c1 / a1\n\ntd_e2(a1::AbstractFloat, a2::AbstractFloat, c2::AbstractFloat) = c2 / (a1 ^ 2 + a2)\n\nfunction tajimad(π::AbstractFloat, S::Integer, a1::AbstractFloat, e1::AbstractFloat, e2::AbstractFloat)\n    return (π - S / a1) / sqrt(e1 * S + e2 * S * (S - 1))\nend\n\n\"\"\"\n    tajimad(π::AbstractFloat, S::Integer, n::Integer)\n\nCompute Tajima's D from:\n\n* `π`: The average number of SNPs found in (n choose 2) pairwise comparisons of\n       a sample of sequences.\n\n* `S`: The number of segregating sites in a sample of sequences.\n\n* `n`: The number of sequences in your sample.\n\n*Example*\n\n```julia\ntajimad(3.88888, 16, 10)\n```\n\n\"\"\"\nfunction tajimad(π::AbstractFloat, S::Integer, n::Integer)\n    a1 = td_a1(n)\n    a2 = td_a2(n)\n    b1 = td_b1(n)\n    b2 = td_b2(n)\n    c1 = td_c1(a1, b1)\n    c2 = td_c2(n, a1, a2, b2)\n    e1 = td_e1(a1, c1)\n    e2 = td_e2(a1, a2, c2)\n    return tajimad(π, S, a1, e1, e2)\nend\n\n\"\"\"\n    tajimad(seqs)\n\nCompute Tajima's D from a collection of BioSequences{DNAAlphabet{n}} (n = 2 or 4).\n\nThis will estimate the `π`, `S`, and `n` parameters from the sequences and use\nthose parameters to estimate Tajima's D.\n\n*Example*\n\n```julia\n\nsample = [dna\"ATAATAAAAAAATAATAAAAAAATAAAAAAAATAAAAAAAA\",\n          dna\"AAAAAAAATAAATAATAAAAAAATAAAAAAAAAAAAAAAAA\",\n          dna\"AAAATAAAAATATAATAAAAAAATATAAAAAAAAAAAAAAA\",\n          dna\"AAAAAAAAAAAATAATAAAAAAATAAATAAATAAAAAAAAA\",\n          dna\"AAAATAAAAAAAATATAAAAAAATAAAAAAAAAAAAAAAAA\",\n          dna\"AAAATAAAAAAAAAATAAAAAAAAAAAAAAAAAAATAAAAA\",\n          dna\"AAAAAATAAAAATAATAAAAAAATAAAAAAAAAAAAAAAAA\",\n          dna\"AAAAAAAAAAAAAAATAAAAAAATAAAAAAAAAAAAAAATA\",\n          dna\"AAAAAAAAAAAAAAAAAAAAAAATAAAAAAAAAAAAAAAAA\",\n          dna\"AAAAAAAAAAAAAAATAAAAAAATAATAAAAAAAAAAAAAA\"]\n\ntajimad(sample)\n```\n\n\"\"\"\nfunction tajimad(seqs)\n    π = avg_mut(seqs)\n    S = count(Segregating, seqs)\n    n = length(seqs)\n    return tajimad(π, S[1], n)\nend\n", "meta": {"hexsha": "95315aeac435382fc91c04744a23afa014329a65", "size": 2581, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tajima.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NaturalSelection.jl-509eaf56-8f8f-530b-95ce-37fd3147b88c", "max_stars_repo_head_hexsha": "d545f6cdb488b7feb9fc37274cd59963eedcf3f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-09-25T12:48:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-16T07:57:06.000Z", "max_issues_repo_path": "src/tajima.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/NaturalSelection.jl-509eaf56-8f8f-530b-95ce-37fd3147b88c", "max_issues_repo_head_hexsha": "d545f6cdb488b7feb9fc37274cd59963eedcf3f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2017-08-30T17:59:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-16T08:24:47.000Z", "max_forks_repo_path": "src/tajima.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/NaturalSelection.jl-509eaf56-8f8f-530b-95ce-37fd3147b88c", "max_forks_repo_head_hexsha": "d545f6cdb488b7feb9fc37274cd59963eedcf3f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:30:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-09T20:41:26.000Z", "avg_line_length": 24.3490566038, "max_line_length": 103, "alphanum_fraction": 0.6416117784, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7881594608115079}}
{"text": "module Excercise_4\n\n# Exercise 4 (JULIA)\n# 1. Create two matrices of the same layout and test if addition and subtraction of the matrix works as expected: C = A + B \n# 2. Now compare matrix multiplication either this way A * B and this way A .* B. Whats the difference?!\n# 3. What about matrix division with \"/\" or \"\\\"?!\n# 4. Create a 3x3 integer matrix A with useful numbers. Now try A+1, A-1, A*2, A/2.\n# 5. Now multiply a 3x4 matrix with a suitable (4)vector. \n\n\n# Part 1\nmatrix_a = rand(0:10, 4,4)\nmatrix_b = rand(0:10, 4,4)\nprintln(\"Matrix A:\")\nprintln(matrix_a)\nprintln(\"Matrix B:\")\nprintln(matrix_b)\nprintln(\"A + B:\")\naddition = matrix_a + matrix_b\nprintln(addition)\nprintln(\"A - B:\")\nsubtraction = matrix_a -matrix_b\nprintln(subtraction)\n\n# Part 2\n\n# Matrix multiplication\nprintln(\"A * B\")\nmulti_1 = matrix_a * matrix_b\nprintln(multi_1)\n\n# Element-wise multiplication\nprintln(\"A .* B:\")\nmulti_2 = matrix_a .* matrix_b\nprintln(multi_2)\n# Part 3\n\n# Part 4\n\nmatrix_c = [1 2 3; 3 2 1; 2 3 1]\nprintln(\"Matrix C:\")\nprintln(matrix_c)\nprintln(\"C+1:\")\n# println(matrix_c-1)\nprintln(\"C*2:\")\nprintln(matrix_c*2)\nprintln(\"C/2:\")\nprintln(matrix_c/2)\n\n# Part 5\n\nmatrix_d = rand(0:10, 3,4)\n\nprintln(\"Matrix D:\")\nprintln(matrix_d)\n\n\nend", "meta": {"hexsha": "0c133cccece45ee93b3038da24c3f509dcf5ea92", "size": 1228, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "04_Exercise_4.jl", "max_stars_repo_name": "MaxMali/MM_05_R_and_Julia_Excercise", "max_stars_repo_head_hexsha": "52d12e694c8090d83ec4d95c6673d160c4a560b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "04_Exercise_4.jl", "max_issues_repo_name": "MaxMali/MM_05_R_and_Julia_Excercise", "max_issues_repo_head_hexsha": "52d12e694c8090d83ec4d95c6673d160c4a560b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "04_Exercise_4.jl", "max_forks_repo_name": "MaxMali/MM_05_R_and_Julia_Excercise", "max_forks_repo_head_hexsha": "52d12e694c8090d83ec4d95c6673d160c4a560b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1724137931, "max_line_length": 124, "alphanum_fraction": 0.6954397394, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475794701961, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7881513782101518}}
{"text": "\n# Energy\n\nfunction NbodyEnergy(u,Gm)\n\"\"\"\n     Nbody problem Hamiltonian (Cartesian Coordinates)\n\"\"\"\n\n    dim=2\n    nbody=length(Gm)\n\n @inbounds begin\n    x = view(u,1:7)   # x\n    y = view(u,8:14)  # y\n    v = view(u,15:21) # x′\n    w = view(u,22:28) # y′\n\n    H=zero(eltype(u))\n    P=zero(eltype(u))\n\n    for i in 1:nbody\n        H+=Gm[i]*(v[i]*v[i]+w[i]*w[i])\n        for j in i+1:nbody\n            r = ((x[i]-x[j])^2+(y[i]-y[j])^2)^(1/2)\n            P+=(Gm[i]/r)*Gm[j]\n        end\n    end\n\n    return(H/2-P)\n    end\n\nend\n\n\n# OdeProblem\n\n\nfunction f(du,u,p,t)\n  @inbounds begin\n  x = view(u,1:7)   # x\n  y = view(u,8:14)  # y\n  v = view(u,15:21) # x′\n  w = view(u,22:28) # y′\n  du[1:7] .= v\n  du[8:14].= w\n  for i in 15:28\n    du[i] = zero(u[1])\n  end\n  for i=1:7,j=1:7\n    if i != j\n      r = ((x[i]-x[j])^2 + (y[i] - y[j])^2)^(3/2)\n      du[14+i] += j*(x[j] - x[i])/r\n      du[21+i] += j*(y[j] - y[i])/r\n    end\n  end\n  end\nend\n\n\n# DynamicalOdeProblem\n\n\nfunction dotv(dv,q,v,par,t)\n@inbounds begin\n  x = view(q,1:7)   # x\n  y = view(q,8:14)  # y\n  vx = view(v,1:7)   # x′\n  vy = view(v,8:14)  # y′\n  for i in 1:14\n    dv[i] = zero(x[1])\n  end\n  for i=1:7,j=1:7\n    if i != j\n      r = ((x[i]-x[j])^2 + (y[i] - y[j])^2)^(3/2)\n      dv[i] += j*(x[j] - x[i])/r\n      dv[7+i] += j*(y[j] - y[i])/r\n    end\n  end\n  end\nend\n\n\nfunction dotq(dq,q,v,par,t)\n@inbounds begin\n  x = view(q,1:7)   # x\n  y = view(q,8:14)  # y\n  vx = view(v,1:7)   # x′\n  vy = view(v,8:14)  # y′\n  dq[1:7] .= vx\n  dq[8:14].= vy\n  end\nend\n\n\n#\n#  Second Order Problem\n#\n\nfunction f2nd!(ddu,du,u,p,t)\n  @inbounds begin\n  x = view(u,1:7)   # x\n  y = view(u,8:14)  # y\n  vx = view(du,1:7) # x′\n  vy = view(du,8:14) # y′\n\n  for i in 1:14\n    ddu[i] = zero(x[1])\n  end\n\n  for i=1:7,j=1:7\n    if i != j\n      r = ((x[i]-x[j])^2 + (y[i] - y[j])^2)^(3/2)\n      ddu[i] += j*(x[j] - x[i])/r\n      ddu[7+i] += j*(y[j] - y[i])/r\n    end\n  end\n  end\nend\n", "meta": {"hexsha": "cf5188ab21e44d4dfd9968345b4d3c1de09d61ad", "size": 1911, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ODEProblems/Pleiades.jl", "max_stars_repo_name": "mikelehu/IRKGL16.jl", "max_stars_repo_head_hexsha": "2cf769cebef40d5a1587d77330c3088c28c1f8af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-10-20T22:06:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:57:29.000Z", "max_issues_repo_path": "ODEProblems/Pleiades.jl", "max_issues_repo_name": "mikelehu/IRKGL16.jl", "max_issues_repo_head_hexsha": "2cf769cebef40d5a1587d77330c3088c28c1f8af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-10-14T12:55:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-02T10:48:57.000Z", "max_forks_repo_path": "ODEProblems/Pleiades.jl", "max_forks_repo_name": "mikelehu/IRKGL16.jl", "max_forks_repo_head_hexsha": "2cf769cebef40d5a1587d77330c3088c28c1f8af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-01-26T23:53:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T18:20:15.000Z", "avg_line_length": 16.0588235294, "max_line_length": 54, "alphanum_fraction": 0.4458398744, "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7881513697523367}}
{"text": "module PassiveCable\n\nusing Unitful: uconvert, NoUnits\n\nexport cable_normalize, cable, rallpack1\n\n# Compute solution g(x, t) to\n#\n#     ∂²g/∂x² - g - ∂g/∂t = 0\n#\n# on [0, L] × [0,∞), subject to:\n#\n#     g(x, 0) = 0\n#     ∂g/∂x (0, t) = 1\n#     ∂g/∂x (L, t) = 0\n#\n# Parameters:\n#     x, t, L:  as described above\n#   tol:  absolute error tolerance in result\n#\n# Return:\n#     g(x, t)\n#\n# TODO: verify correctness when L≠1\n\nfunction cable_normalized(x::Float64, t::Float64, L::Float64; tol=1e-8)\n    if t<=0\n        return 0.0\n    else\n        ginf = -cosh(L-x)/sinh(L)\n        sum = exp(-t/L)\n        Ltol = L*tol\n\n        for k = Iterators.countfrom(1)\n            a = k*pi/L\n            b = exp(-t*(1+a^2))\n\n            sum += 2*b*cos(a*x)/(1+a^2)\n            resid_ub = b/(a^3*t)\n\n            if resid_ub<Ltol\n                break\n            end\n        end\n        return ginf+sum/L;\n     end\nend\n\n\n# Compute solution f(x, t) to\n#\n#     λ²∂²f/∂x² - f - τ∂f/∂t = 0\n#\n# on [0, L] x [0, ∞), subject to:\n#\n#     f(x, 0) = V\n#     ∂f/∂x (0, t) = I·r\n#     ∂f/∂x (L, t) = 0\n#\n# where:\n#\n#     λ² = 1/(r·g)   length constant\n#     τ  = r·c       time constant\n#\n# In the physical model, the parameters correspond to the following:\n#\n#     L:  length of cable\n#     r:  linear axial resistivity\n#     g:  linear membrane conductivity\n#     c:  linear membrane capacitance\n#     V:  membrane reversal potential\n#     I:  injected axial current on the left end (x = 0) of the cable.\n#\n# Note that r, g and c are specific 1-d quantities that differ from\n# the cable resistivity r_L, specific membrane conductivity ḡ and\n# specific membrane capacitance c_m as used elsewhere. If the\n# cross-sectional area is A and cable circumference is f, then\n# these quantities are related by:\n#\n#     r = r_L/A\n#     g = ḡ·f\n#     c = c_m·f\n#\n# Parameters:\n#     x:  displacement along cable\n#     t:  time\n#     L, lambda, tau, r, V, I:  as described above\n#   tol:  absolute error tolerance in result\n#\n# Return:\n#     computed potential at (x,t) on cable.\n\nfunction cable(x, t, L, lambda, tau, r, V, I; tol=1e-8)\n    scale = I*r*lambda;\n    if scale == 0\n        return V\n    else\n        tol_n = abs(tol/scale)\n        return scale*cable_normalized(uconvert(NoUnits, x/lambda), uconvert(NoUnits, t/tau), uconvert(NoUnits, L/lambda), tol=tol_n) + V\n    end\nend\n\n\n# Rallpack 1 test\n#\n# One sided cable model with the following parameters:\n#\n#     RA = 1 Ω·m    bulk axial resistivity\n#     RM = 4 Ω·m²   areal membrane resistivity\n#     CM = 0.01 F/m²  areal membrane capacitance\n#     d  = 1 µm     cable diameter\n#     EM = -65 mV   reversal potential\n#     I  = 0.1 nA   injected current\n#     L  = 1 mm     cable length.\n#\n# (This notation aligns with that used in the Rallpacks paper.)\n#\n# Note that the injected current as described in the Rallpack model\n# is trans-membrane, not axial. Consequently we need to swap the\n# sign on I when passing to the cable function.\n#\n# Parameters:\n#     x:  displacement along cable [m]\n#     t:  time [s]\n#   tol:  absolute tolerance for reported potential.\n#\n# Return:\n#     computed potential at (x,t) on cable.\n\nfunction rallpack1(x, t; tol=1e-8)\n    RA = 1\n    RM = 4\n    CM = 1e-2\n    d  = 1e-6\n    EM = -65e-3\n    I  = 0.1e-9\n    L  = 1e-3\n\n    r = 4*RA/(pi*d*d)\n    lambda = sqrt(d/4 * RM/RA)\n    tau = CM*RM\n\n    return cable(x, t, L, lambda, tau, r, EM, -I, tol=tol)\nend\n\nend # module PassiveCable\n", "meta": {"hexsha": "9f5858bff8eae46e6ed2f1dc5e12ee2f6f9f035e", "size": 3432, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "validation/ref/numeric/PassiveCable.jl", "max_stars_repo_name": "kanzl/arbor", "max_stars_repo_head_hexsha": "86b1eb065ac252bf0026de7cf7cbc6748a528254", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 53, "max_stars_repo_stars_event_min_datetime": "2018-10-18T12:08:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T22:03:51.000Z", "max_issues_repo_path": "validation/ref/numeric/PassiveCable.jl", "max_issues_repo_name": "kanzl/arbor", "max_issues_repo_head_hexsha": "86b1eb065ac252bf0026de7cf7cbc6748a528254", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 864, "max_issues_repo_issues_event_min_datetime": "2018-10-01T08:06:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T08:06:48.000Z", "max_forks_repo_path": "validation/ref/numeric/PassiveCable.jl", "max_forks_repo_name": "kanzl/arbor", "max_forks_repo_head_hexsha": "86b1eb065ac252bf0026de7cf7cbc6748a528254", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2019-03-03T16:18:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T10:39:51.000Z", "avg_line_length": 23.3469387755, "max_line_length": 136, "alphanum_fraction": 0.5792540793, "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7881513658880521}}
{"text": "using ViewerGL, LinearAlgebraicRepresentation\nGL = ViewerGL\nLar = LinearAlgebraicRepresentation\n\n# input of primitive shape\nV, (VV,EV,FV) = Lar.cuboid([1,1], true)\nsquare = (V,EV)\nmodel = Lar.Struct([ square,\n\t\t\tLar.r(π), square ])\nV,EV = Lar.struct2lar(model)\nVV = [[k] for k=1:size(V,2)]\n\nGL.VIEW( GL.numbering(.4)((V,[VV, EV]),GL.COLORS[1]) );\n\n# arrangement of input data\nW = convert(Lar.Points, V')\ncop_EV = Lar.coboundary_0(EV)\nV, copEV, copFE = Lar.planar_arrangement(W, cop_EV)\n\n# compute containment graph of components\nbicon_comps = Lar.Arrangement.biconnected_components(copEV)\n\n# compute euler characteristic\nχ = Lar.euler_characteristic(V, copEV, copFE)\nprintln(\"χ = $χ ; bicon_comps = $(length(bicon_comps))\");\n\nEW = Lar.cop2lar(copEV)\nW = convert(Lar.Points, V')\ncomps = [ GL.GLLines(W,EW[comp],GL.COLORS[(k-1)%12+1]) for (k,comp) in enumerate(bicon_comps) ];\nGL.VIEW(comps);\n\n# final solid visualization\ntriangulated_faces = Lar.triangulate2D(V, [copEV, copFE])\nV = convert(Lar.Points, V')\nFVs = convert(Array{Lar.Cells}, triangulated_faces)\nGL.VIEW(GL.GLExplode(V,FVs,1.2,1.2,1.2,99,1));\n\n# polygonal face boundaries\nEVs = Lar.FV2EVs(copEV, copFE)\nEVs = convert(Array{Array{Array{Int64,1},1},1}, EVs)\nGL.VIEW(GL.GLExplode(V,EVs,1.2,1.2,1.2,1,1));\n", "meta": {"hexsha": "1691684e8504864ca2798c52ab7b563ba038ae19", "size": 1264, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/euler_twoTangentSquares-VV.jl", "max_stars_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_stars_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/euler_twoTangentSquares-VV.jl", "max_issues_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_issues_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/euler_twoTangentSquares-VV.jl", "max_forks_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_forks_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0952380952, "max_line_length": 96, "alphanum_fraction": 0.710443038, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582426, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7881354887530584}}
{"text": "function circHohmann(r₁,r₂,μ)\r\n#[dV1,dV2,T] = circHohmann(r1,r2,μ)\r\n#   calculates circular Hohmann transfer details given two radii\r\n#   input and output are the same units\r\n#\r\n# Alex Hoffman\r\n# 10/31/2020\r\n\r\naₜ   = 0.5(r₁ + r₂) #transfer semi-major axis\r\nv1 = sqrt(μ/r₁)\r\nv2 = sqrt(μ/r₂)\r\nvt1 = sqrt(μ*(2/r₁-1/aₜ))\r\nvt2 = sqrt(μ*(2/r₂-1/aₜ))\r\ndV1 = vt1 - v1\r\ndV2 = v2 - vt2\r\nT = 2pi*sqrt(aₜ^3/μ)\r\n\r\nreturn [dV1, dV2, T]\r\nend\r\n", "meta": {"hexsha": "f769475aa7715b206dda0171034a6d1672ddf96c", "size": 428, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/circularHohmann.jl", "max_stars_repo_name": "greatblueship/astrofunk.jl", "max_stars_repo_head_hexsha": "28693efeb2db3536fd96cc4ab6053955683f81f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/circularHohmann.jl", "max_issues_repo_name": "greatblueship/astrofunk.jl", "max_issues_repo_head_hexsha": "28693efeb2db3536fd96cc4ab6053955683f81f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/circularHohmann.jl", "max_forks_repo_name": "greatblueship/astrofunk.jl", "max_forks_repo_head_hexsha": "28693efeb2db3536fd96cc4ab6053955683f81f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4, "max_line_length": 65, "alphanum_fraction": 0.6238317757, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197139, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7880993048886443}}
{"text": "module GaussianProcesses\n\nexport k, K, GP_Regressor\n\nusing LinearAlgebra, Distributions\n\n# exponential quadratic kernel\nk(a::Array, b::Array; h::Real, d::Function) = exp(-d(a,b)^2 / (2 * h^2))\nk(a::Real, b::Real; h::Real, d::Function) = k([a], [b]; h=h, d=d)\n\n# kernel matrix\nK(A::Vector, B::Vector; h::Real, d::Function) = [k(a, b; h = h, d = d) for a in A, b in B]\n\n# prior distribution: mean 0, covariance K\nmutable struct GP_Regressor\n\t\"MVN distribution of prior\"\n\tprior::Distributions.MvNormal\n\t\"MVN distribution of posterior\"\n\tposterior::Distributions.MvNormal\n\t\"equivalent smoothing kernel weights (rows of matrix)\"\n\tequiv_weights::Array\n\t\"input points for sampling and plotting\"\n\tx_grid::Vector\n\t\"sample observations\"\n\tx_train::Vector\n\t\"sample outcomes\"\n\ty_train::Vector\n\t\"standard deviation of iid Gaussian noise in observations\"\n\tσ::Real\n\t\"characteristic length scale\"\n\th::Real\n\t\"distance function\"\n\td::Function\n\n\t# inner constructor: call this function to instantiate\n\tfunction GP_Regressor(X_train::Vector, y_train::Vector, X::Vector; σ::Real, h::Real, d::Function)\n\n\t\t# prior\n\t\tKpred = K(X, X; h=h, d=d)  # covariance\n\t\tprior = MvNormal(Kpred)\n\n\t\t# posterior terms\n\t\tKinv = inv(K(X_train, X_train; h=h, d=d) + σ^2 * I)\n\t\tKcross = K(X, X_train; h=h, d=d)\n\t\tKequiv = Kcross * Kinv  # equivalent smoothing kernel weights (each row)\n\n\t\tmean_posterior = Kequiv * y_train\n\t\tcov_posterior = Kpred .- Kequiv * Kcross'\n\n\t\tposterior = MvNormal(mean_posterior, Matrix(Hermitian(cov_posterior)))\n\n\t\tnew(prior, posterior, Kequiv, X, X_train, y_train, σ, h, d)\n\tend\nend\n\nend  # module\n", "meta": {"hexsha": "df275314bad0f214638bd5d061040a9115dd5f28", "size": 1584, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GaussianProcesses.jl", "max_stars_repo_name": "tobanw/gaussian-process-regression", "max_stars_repo_head_hexsha": "1e9774791664ded2cb06aa83d181c4835dda056a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GaussianProcesses.jl", "max_issues_repo_name": "tobanw/gaussian-process-regression", "max_issues_repo_head_hexsha": "1e9774791664ded2cb06aa83d181c4835dda056a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GaussianProcesses.jl", "max_forks_repo_name": "tobanw/gaussian-process-regression", "max_forks_repo_head_hexsha": "1e9774791664ded2cb06aa83d181c4835dda056a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7894736842, "max_line_length": 98, "alphanum_fraction": 0.7039141414, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377284730285, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7880993015457247}}
{"text": "function rk4(f::Function, x₀::Float64, y₀::Float64, x₁::Float64, n)\n    vx = Vector{Float64}(n + 1)\n    vy = Vector{Float64}(n + 1)\n    vx[1] = x = x₀\n    vy[1] = y = y₀\n    h = (x₁ - x₀) / n\n    for i in 1:n\n        k₁ = h * f(x, y)\n        k₂ = h * f(x + 0.5h, y + 0.5k₁)\n        k₃ = h * f(x + 0.5h, y + 0.5k₂)\n        k₄ = h * f(x + h, y + k₃)\n        vx[i + 1] = x = x₀ + i * h\n        vy[i + 1] = y = y + (k₁ + 2k₂ + 2k₃ + k₄) / 6\n    end\n    return vx, vy\nend\n\nvx, vy = rk4(f, 0.0, 1.0, 10.0, 100)\nfor (x, y) in Iterators.take(zip(vx, vy), 10)\n    @printf(\"%4.1f %10.5f %+12.4e\\n\", x, y, y - theoric(x))\nend\n", "meta": {"hexsha": "77601d87c3800fa3e331c2d4d8ffa3cf92e294bb", "size": 615, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/runge-kutta-method-2.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/runge-kutta-method-2.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/runge-kutta-method-2.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9545454545, "max_line_length": 67, "alphanum_fraction": 0.4390243902, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.958537722550837, "lm_q2_score": 0.8221891305219505, "lm_q1q2_score": 0.7880992966765633}}
{"text": "# Solves the SVM classification problem using the barrier method.\n\n# The main function.\n# This implementation is deterministic for illustration purpose.\n# In practice we may want to use random starting point.\nfunction svmbarrier(X::AbstractMatrix,\n                    Y::AbstractVector,\n                    C::Real,\n                    ϵ::Real;\n                    t0::Real=1., \n                    μ::Real=100.,\n                    α::Real=0.01, β::Real=0.05)\n  w = zeros(size(X, 2))\n  z = ones(Y)*2\n  x0 = [w; z]\n  A = [-Y.*X (-eye(size(Y, 1))); zeros(X) (-eye(size(Y, 1)))]\n  b = [-1.*ones(Y); zeros(Y)]\n  wsize = size(w, 1)\n  f(x) = sum(x[1: wsize].^2)/2 + C*sum(x[wsize+1: end])\n  ∇f(x) = [x[1: size(w, 1)]; C*ones(Y)]\n  Hf(x) = Diagonal([ones(wsize); zeros(Y)])\n  x, αdual, numstepsarray = barriermethod(\n    f, ∇f, Hf, A, b, x0; ϵ=ϵ, t0=t0, μ=μ, α=α, β=β)\n  x[1: wsize], αdual[1: size(Y, 1)], numstepsarray\nend\n\n# Implements the barrier method given the objective function and its\n# first and second derivatives.\n# The problem is supposed to have a linear constraint Ax ≤ b.\nfunction barriermethod(f, ∇f, Hf,\n                       A::AbstractMatrix,\n                       b::AbstractVector,\n                       x0::AbstractVector;\n                       ϵ::Real=1e-3,\n                       t0::Real=1.,\n                       μ::Real=100.,\n                       α::Real=0.01, β::Real=0.05)\n  (all(A*x0.<b)\n   || throw(DomainError(\"x0 must be strictly feasible.\")))\n  m = float(size(Y, 1))\n  x, t = x0, t0\n  numstepsarray::Vector{Int} = []\n  while true\n    x, numsteps = centeringstep(f, ∇f, Hf, A, b, x, t; α=α, β=β)\n    push!(numstepsarray, numsteps)\n    m/t < ϵ && break\n    t *= μ\n  end\n  αdual = 1./(t*(b-A*x))\n  x, αdual, numstepsarray\nend\n\n# Carries out a single centering step of the barrier method.\n# The problem is supposed to have a linear constraint Ax ≤ b.\nfunction centeringstep(f, ∇f, Hf,\n                       A::AbstractMatrix,\n                       b::AbstractVector,\n                       x0::AbstractVector,\n                       t::Real;\n                       ϵ::Real=1e-8,\n                       α::Real=0.01, β::Real=0.05)\n  x = copy(x0)\n  numsteps = 0\n  obj(x) = t*f(x)-sum(log.(b-A*x))\n  while true\n    d = 1./(b-A*x)\n    ∇ = t*∇f(x)+A'*d\n    H = t*Hf(x)+A'*Diagonal(d)^2*A\n    Δxnt = -H\\∇\n    λ² = -∇⋅Δxnt\n    λ²/2 < ϵ && break\n    tbacktrace = 1\n    xtest = x + tbacktrace*Δxnt\n    while(any(A*xtest .≥ b) || obj(xtest) > obj(x)-tbacktrace*α*λ²)\n      tbacktrace *= β\n      xtest = x + tbacktrace*Δxnt\n    end\n    # numeric limit\n    obj(xtest) == obj(x) && break\n    x = xtest\n    numsteps += 1\n  end\n  x, numsteps\nend\n", "meta": {"hexsha": "b6a4bcc7764755f72e6109612e84c3fbf0a619e7", "size": 2665, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SVM/barrier.jl", "max_stars_repo_name": "cyber-meow/Optimization_algos", "max_stars_repo_head_hexsha": "ae38b156fbd6ca71bf200fb8d2af7a5d5f817b68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SVM/barrier.jl", "max_issues_repo_name": "cyber-meow/Optimization_algos", "max_issues_repo_head_hexsha": "ae38b156fbd6ca71bf200fb8d2af7a5d5f817b68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SVM/barrier.jl", "max_forks_repo_name": "cyber-meow/Optimization_algos", "max_forks_repo_head_hexsha": "ae38b156fbd6ca71bf200fb8d2af7a5d5f817b68", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3529411765, "max_line_length": 68, "alphanum_fraction": 0.5144465291, "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464604, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.788083726739547}}
{"text": "#############################################################################\n#############################################################################\n#\n# This file implements polynomial addition \n#                                                                               \n#############################################################################\n#############################################################################\n\n\"\"\"\nAdd two polynomials.\n\"\"\"\nfunction +(p1::Polynomial, p2::Polynomial)::Polynomial\n    p1, p2 = deepcopy(p1), deepcopy(p2)\n    p3 = Polynomial()\n    while !iszero(p1) && !iszero(p2)\n        t1, t2 = trailing(p1), trailing(p2) \n        if t1.degree == t2.degree\n            push!(p3, popfirst!(p1)+popfirst!(p2))\n        elseif t1.degree < t2.degree\n            push!(p3,popfirst!(p1))\n        else\n            push!(p3,popfirst!(p2))\n        end\n    end\n    while !iszero(p1)\n        push!(p3,popfirst!(p1))\n    end\n    while !iszero(p2)\n        push!(p3,popfirst!(p2))\n    end\n    return p3\nend\n\n\"\"\"\nAdd a polynomial and a term.\n\"\"\"\n+(p::Polynomial, t::Term) = p + Polynomial(t)\n+(t::Term, p::Polynomial) = p + t\n\n\"\"\"\nAdd a polynomial and an integer.\n\"\"\"\n+(p::Polynomial, n::Int) = p + Term(n,0)\n+(n::Int, p::Polynomial) = p + Term(n,0)\n", "meta": {"hexsha": "4c0a5d5c086055897d0b299aefd801e396f16fd0", "size": 1279, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basic_polynomial_operations/polynomial_addition.jl", "max_stars_repo_name": "ILikeTheCodespace/William-Idoine-2504-2021-PROJECT1", "max_stars_repo_head_hexsha": "2c1cf923b17dd97c91e80baab58890bfd33fc987", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basic_polynomial_operations/polynomial_addition.jl", "max_issues_repo_name": "ILikeTheCodespace/William-Idoine-2504-2021-PROJECT1", "max_issues_repo_head_hexsha": "2c1cf923b17dd97c91e80baab58890bfd33fc987", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basic_polynomial_operations/polynomial_addition.jl", "max_forks_repo_name": "ILikeTheCodespace/William-Idoine-2504-2021-PROJECT1", "max_forks_repo_head_hexsha": "2c1cf923b17dd97c91e80baab58890bfd33fc987", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-23T22:26:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T22:26:51.000Z", "avg_line_length": 28.4222222222, "max_line_length": 80, "alphanum_fraction": 0.3885848319, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.788083717502186}}
{"text": "include(\"/home/jefter66/Workspace/lablib/src/calcs/Uncertainty.jl\")\n\nfunction I1()\n    Δr = 0.01\n    r1 = 0.0335\n    r2 = 0.06\n\n    m = 2.2429\n    Δm = 0.0001 \n\n    I1 = (1/2)*m*(r1^2 + r2^2)\n    ΔI1 = (1/2)*((Δm*(r1^2 + r2^2) + 2*m*(r1*Δr + r2*Δr)))\n    println(\" Ig ± Δ Ig = \", I1, \" ± \", ΔI1)\n#    return [I1,ΔI1]\nend\n\nfunction I2(ω1, ω)\n   Δω=1e-3\n   I2 = I1()[1]*( ω1/(ω1 - ω))\n   ΔI2   =  (I1()[2]  + (I1()[2]*ω +  Δω*I1()[1])/(ω^2))\n    println(\"I2 ± Δ I2 = \", I2, \" ± \", ΔI2)\n    return [I2, ΔI2]\nend\n\nfunction equivalencia(v1,v2,σ1, σ2)\n    abs(v1-v2) < 2*(σ1 + σ2)\nend\n\nfunction ΔE(ω1, ω,I1, I2)\n    Δω = 0.001\n    Ef = (1/2)*(I1[1] + I2[1])*ω^2\n    Ei = (1/2)*(I1[1])*ω1^2\n\n    δE = ((1/2)*(I1[2] + I2[2])*ω^2 + (I1[1] + I2[1])*ω*Δω) + (1/2)*(I1[2]*ω1^2 + 2*ω1*Δω*I1[1])          \n    \n    println(\"E ± ΔE = \", Ef - Ei, \" ± \", δE)\nend\n\nfunction results()\nω1 = [14.444, 22.765,24.353]\nω   = [7.453,12.777,13.629]\nprint(\"(1) : \")\nI2_1 = I2(ω1[1], ω[1])\nprint(\"(2) : \")\nI2_2 = I2(ω1[2],ω[2])\nprint(\"(3) : \")\nI2_3 = I2(ω1[3],ω[3])\n\nprintln(\"==============================================\")\n\nprintln(\"(1) & (2) : \", equivalencia(I2_1[1], I2_1[2], I2_2[1] , I2_2[2]))\nprintln(\"(1) & (3) : \", equivalencia(I2_1[1],I2_1[2], I2_3[1],I2_3[2]))\nprintln(\"(2) & (3) : \", equivalencia(I2_2[1],I2_2[2], I2_3[1], I2_3[2]))\n   \nprintln(\"==========================\")\n\nE1 = ΔE(ω1[1], ω[1], I1(), I2_1)\nE2 = ΔE(ω1[2], ω[2], I1(), I2_2)\nE3 = ΔE(ω1[3], ω[3], I1(), I2_3)\n#println(\"ΔE1 ± δ E1 = \", E1[1], \" ± \", E1[2])\n#println(\"ΔE2 ± δ E2 =\",  E2[1], \" ± \", E2[2])\n#println(\"ΔE3 ± δ E3 = \", E3[1] , \" ± \", E3[2])\n\nend\n\n\n", "meta": {"hexsha": "0a92c4cdb95719baf7313db87de9e2a1a58078fb", "size": 1609, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Fisica experimental/02/01/src/exp2.jl", "max_stars_repo_name": "jefter66/notes", "max_stars_repo_head_hexsha": "adf8753b166162dcb898470932db2235c5d5966b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Fisica experimental/02/01/src/exp2.jl", "max_issues_repo_name": "jefter66/notes", "max_issues_repo_head_hexsha": "adf8753b166162dcb898470932db2235c5d5966b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Fisica experimental/02/01/src/exp2.jl", "max_forks_repo_name": "jefter66/notes", "max_forks_repo_head_hexsha": "adf8753b166162dcb898470932db2235c5d5966b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0149253731, "max_line_length": 106, "alphanum_fraction": 0.4474829086, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856297, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7880589093609711}}
{"text": "g = [\n  [08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08]\n  [49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00]\n  [81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65]\n  [52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91]\n  [22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80]\n  [24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50]\n  [32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70]\n  [67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21]\n  [24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72]\n  [21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95]\n  [78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92]\n  [16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57]\n  [86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58]\n  [19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40]\n  [04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66]\n  [88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69]\n  [04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36]\n  [20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16]\n  [20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54]\n  [01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48]\n]\n\nl = 4\nm, n = size(g)\nmaxsofar = 0\nfor i = 1:m-(l-1)\n  global maxsofar\n  for j = 1:n-(l-1)\n    p_col = prod(g[i:i+(l-1), j])\n    p_row = prod(g[i,j:j+(l-1)])\n    p_dia1 = g[i,j] * g[i+1,j+1] * g[i+2,j+2] * g[i+3,j+3]\n    p_dia2 = g[i,j+3] * g[i+1,j+2] * g[i+2,j+1] * g[i+3,j]\n    maxsofar = max(maxsofar, p_col)\n    maxsofar = max(maxsofar, p_row)\n    maxsofar = max(maxsofar, p_dia1)\n    maxsofar = max(maxsofar, p_dia2)\n  end\nend\nprintln(maxsofar)\n", "meta": {"hexsha": "c73720c68ddf987254a2b1554abb5621a1d80e6e", "size": 1738, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ans11.jl", "max_stars_repo_name": "sujimodern/project-euler-jl", "max_stars_repo_head_hexsha": "7abbf39014cc39b39ed84ebf698d45d09fadea1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ans11.jl", "max_issues_repo_name": "sujimodern/project-euler-jl", "max_issues_repo_head_hexsha": "7abbf39014cc39b39ed84ebf698d45d09fadea1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ans11.jl", "max_forks_repo_name": "sujimodern/project-euler-jl", "max_forks_repo_head_hexsha": "7abbf39014cc39b39ed84ebf698d45d09fadea1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3902439024, "max_line_length": 63, "alphanum_fraction": 0.6018411968, "num_tokens": 1050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.8311430520409024, "lm_q1q2_score": 0.7880520514374882}}
{"text": "# Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/\n#  Niccolò Antonello <nantonel@idiap.ch>\n\nexport TropicalWeight\n\n\"\"\"\n`TropicalWeight(x)`\n\n| Set                                 | ``\\\\oplus``|   ``\\\\otimes`` | ``\\\\bar{0}`` | ``\\\\bar{1}`` |\n|:-----------------------------------:|:----------:|:--------------:|:------------:|:------------:|\n|``\\\\mathbb{R}\\\\cup\\\\{\\\\pm\\\\infty\\\\}``|  ``\\\\min`` |     ``+``      |``\\\\infty``   |   ``0``      | \n\"\"\"\nstruct TropicalWeight{T <: AbstractFloat} <: Semiring\n  x::T\nend\n\nzero(::Type{TropicalWeight{T}}) where T = TropicalWeight{T}(T(Inf))\none(::Type{TropicalWeight{T}}) where T = TropicalWeight{T}(zero(T))\n\n*(a::TropicalWeight{T}, b::TropicalWeight{T}) where {T <: AbstractFloat} = TropicalWeight{T}(a.x + b.x)\n+(a::TropicalWeight{T}, b::TropicalWeight{T}) where {T <: AbstractFloat} = TropicalWeight{T}( min(a.x,b.x) )\n/(a::TropicalWeight{T}, b::TropicalWeight{T}) where {T <: AbstractFloat} = TropicalWeight{T}( a.x-b.x )\n\n# parsing\nparse(::Type{S},str) where {T, S <: TropicalWeight{T}} = S(parse(T,str))\n\n#properties\nisidempotent(::Type{W}) where {W <: TropicalWeight} = true\niscommulative(::Type{W}) where {W <: TropicalWeight} = true\nisleft(::Type{W}) where {W <: TropicalWeight}= true\nisright(::Type{W}) where {W <: TropicalWeight}= true\nisweaklydivisible(::Type{W}) where {W <: TropicalWeight}= true\niscomplete(::Type{W}) where {W <: TropicalWeight}= true\nispath(::Type{W}) where {W <: TropicalWeight}= true\n", "meta": {"hexsha": "bf98ad24cabdf66d13915fc3242a81555084c983", "size": 1475, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/semirings/tropical.jl", "max_stars_repo_name": "idiap/FiniteStateTransducers.jl", "max_stars_repo_head_hexsha": "430bf273960bd3f43f4042ee85a7c9f3d846d37f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-20T10:41:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-20T10:41:21.000Z", "max_issues_repo_path": "src/semirings/tropical.jl", "max_issues_repo_name": "idiap/FiniteStateTransducers.jl", "max_issues_repo_head_hexsha": "430bf273960bd3f43f4042ee85a7c9f3d846d37f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-02-09T16:54:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-14T00:10:46.000Z", "max_forks_repo_path": "src/semirings/tropical.jl", "max_forks_repo_name": "idiap/FiniteStateTransducers.jl", "max_forks_repo_head_hexsha": "430bf273960bd3f43f4042ee85a7c9f3d846d37f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1428571429, "max_line_length": 108, "alphanum_fraction": 0.5803389831, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7880520395402758}}
{"text": "\"\"\"\n    bresenham(start::Tuple{<:T, <:T}, stop::Tuple{<:T, <:T}) where T<:Number\n\nImplements the [Bresenham's line algorithm](https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm).\n\n# Examples\n\n```jldoctest\njulia> bresenham()\n\n```\n\"\"\"\nfunction bresenham(start::Tuple{T, T}, stop::Tuple{T, T}) where T<:Integer\n    x0, y0 = start\n    x1, y1 = stop\n    if abs(y1 - y0) < abs(x1 - x0)\n        if x0 > x1\n            reverse!(low_line(stop, start))\n        else\n            low_line(start, stop)\n        end\n    else\n        if y0 > y1\n            reverse!(high_line(stop, start))\n        else\n            high_line(start, stop)\n        end\n    end\nend\n\n\"\"\"\n    low_line(start::Tuple{T, T}, stop::Tuple{T, T}) where T<:Integer\n\n\n\n# Examples\n\n```jldoctest\njulia> low_line()\n\n```\n\"\"\"\nfunction low_line(start::Tuple{T, T}, stop::Tuple{T, T}) where T<:Integer\n    x0, y0 = start\n    x1, y1 = stop\n    line = fill((zero(T), zero(T)), length(x0:x1))\n    dx = x1 - x0\n    dy = y1 - y0\n    yi = 1\n    if dy < 0\n        yi = -1\n        dy = -dy\n    end\n    D = 2*dy - dx\n    y = y0\n\n    for x in x0:x1\n        line[x - x0 + 1] =  (x, y)\n        if D > 0\n            y = y + yi\n            D = D - 2*dx\n        end\n        D = D + 2*dy\n    end\n\n    line\nend\n\n\"\"\"\n    high_line(start::Tuple{T, T}, stop::Tuple{T, T}) where T<:Integer\n\n\n\n# Examples\n\n```jldoctest\njulia> high_line()\n\n```\n\"\"\"\nfunction high_line(start::Tuple{T, T}, stop::Tuple{T, T}) where T<:Integer\n    x0, y0 = start\n    x1, y1 = stop\n    line = fill((zero(T), zero(T)), length(y0:y1))\n    dx = x1 - x0\n    dy = y1 - y0\n    xi = 1\n    if dx < 0\n        xi = -1\n        dx = -dx\n    end\n    D = 2*dx - dy\n    x = x0\n\n    for y in y0:y1\n        line[y - y0 + 1] =  (x, y)\n        if D > 0\n            x = x + xi\n            D = D - 2*dy\n        end\n        D = D + 2*dx\n    end\n\n    line\nend\n", "meta": {"hexsha": "38880818665c33697c74ef1c837d6582869ead2f", "size": 1848, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/other/bresenham.jl", "max_stars_repo_name": "control13/SearchBall.jl", "max_stars_repo_head_hexsha": "622a69b264e4e22717a023d849cdd6ad155e342d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/other/bresenham.jl", "max_issues_repo_name": "control13/SearchBall.jl", "max_issues_repo_head_hexsha": "622a69b264e4e22717a023d849cdd6ad155e342d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/other/bresenham.jl", "max_forks_repo_name": "control13/SearchBall.jl", "max_forks_repo_head_hexsha": "622a69b264e4e22717a023d849cdd6ad155e342d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4339622642, "max_line_length": 104, "alphanum_fraction": 0.4826839827, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7880242799662621}}
{"text": "#=\n    Cheating model.\n\n    From \n    https://discourse.julialang.org/t/fitting-a-observed-value-to-a-binomial-distribution-turing/66619\n    \"\"\"\n    Fitting a observed value to a Binomial Distribution Turing\n\n    I am new to Turing and trying to learn it by trying to replicate the Chapters from the book \n    https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers 2 .\n\n    Here is my problem (from Chapter 2) :\n\n    1.) Have a probability p ~ Uniform(0,1) which I have to infer the “number_of_cheaters”\n    2.) p_skewed = p*(0.5) + (0.25) (deterministic value)\n    3.) with model:\n    yes_responses = pm.Binomial(“number_of_cheaters”, 100, p_skewed, observed=35)\n\n    How do I write this in Turing ?\n\n    ...\n\n    @model function model(yes_responses,N)\n        p ~ Uniform(0,1)\n        p_skewed = p*(0.5)+0.25\n        rv_yes_responses ~ Binomial(N,p_skewed)\n\n        // This line on how to include yes_responses i am unable to figure out\n\n        return p_skewed\n\n    end\n   \"\"\"\n    \n   The model refered to is in \n   https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/master/Chapter2_MorePyMC/Ch2_MorePyMC_PyMC3.ipynb\n\n\n    Output of this Turing.jl model:\n        Summary Statistics\n    parameters      mean       std   naive_se      mcse        ess      rhat   ess_per_sec \n        Symbol   Float64   Float64    Float64   Float64    Float64   Float64       Float64 \n\n               p    0.2042    0.0993     0.0031    0.0040   446.4728    0.9990      394.4106\n        p_skewed    0.3521    0.0497     0.0016    0.0020   446.4728    0.9990      394.4106\n\n    Quantiles\n    parameters      2.5%     25.0%     50.0%     75.0%     97.5% \n        Symbol   Float64   Float64   Float64   Float64   Float64 \n\n               p    0.0349    0.1325    0.2020    0.2749    0.3981\n        p_skewed    0.2674    0.3162    0.3510    0.3875    0.4490\n\n    Summary Stats:\n    Length:         1000\n    Missing Count:  0\n    Mean:           0.352105\n    Minimum:        0.250395\n    1st Quartile:   0.316228\n    Median:         0.350993\n    3rd Quartile:   0.387453\n    Maximum:        0.494718\n\n\n=#\n\nusing Turing, StatsPlots, Distributions, StatsBase\nusing CSV\ninclude(\"jl_utils.jl\")\n\n@model function cheating_model2(yes_responses,N)\n    p ~ Uniform(0,1)\n    # Using Dirac(.) makes p_skewed in the chain\n    p_skewed ~ Dirac(p*(0.5)+0.25)\n    # p_skewed = p*(0.5)+0.25\n    yes_responses ~ Binomial(N,p_skewed)\n\n    # An alternative is to return the variable (see below how to handle this)\n    return p_skewed\nend\n\nyes_response = 35\nN = 100\nmodel = cheating_model2(yes_response,N)\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(5),  1_000)\n# chns = sample(model, PG(5),  MCMCThreads(), 10_000, 4)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 10_000)\n\n# chns = sample(model, HMC(0.1,6), 1_000)\n# chns = sample(model, NUTS(), 1_000)\n\ndisplay(chns)\n# display(plot(chns))\n\nchains_params = Turing.MCMCChains.get_sections(chns, :parameters)\ngenq = generated_quantities(model, chains_params)\ndisplay(summarystats(vcat(genq...)))\n", "meta": {"hexsha": "1849bfde798948c951dd46bd4c9d3c070f849a4f", "size": 3172, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/cheating2.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/cheating2.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/cheating2.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 31.0980392157, "max_line_length": 152, "alphanum_fraction": 0.6374527112, "num_tokens": 1045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7880242785757121}}
{"text": "#    Problem : GROUP A\n#    *********\n#\t The extended Woods problem.\n#\t This problem is a sum of n/4 sets of 6 terms, each of which is\n#    assigned its own group.  For a given set i, the groups are\n#    A(i), B(i), C(i), D(i), E(i) and F(i). Groups A(i) and C(i) contain 1\n#    nonlinear element each, denoted Y(i) and Z(i).\n#\n#    The problem dimension is defined from the number of these sets.\n#    The number of problem variables is then 4 times larger.\n#\n#\t This version uses a slightly unorthodox expression of Woods\n#    function as a sum of squares (see Buckley)\n#\n#    Origonal SIF Source: problem 14 in\n#    J.J. More', B.S. Garbow and K.E. Hillstrom,\n#    \"Testing Unconstrained Optimization Software\",\n#    ACM Transactions on Mathematical Software, vol. 7(1), pp. 17-41, 1981.\n#\n#    See also Toint#27, Buckley#17 (p. 101), Conn, Gould, Toint#7\n#\n#    WOODS.SIF classification SUR2-AN-V-0\n#\n#\t This problem is decomposed in n linear groups, the last n-1 of which\n#    are 2 x 2 and singular.\n#\n#    NS is the number of sets (= n/4)\n#\n# Daniel Henderson, 08/2021  \n\nf = (x) -> begin\n\tfx = 0.0\n\tfor i in 1:Int(lastindex(x)/4)\n\t\tfx += (100*(x[4*i-2]-x[4*i-3]^2)^2 + (1-x[4*i-3])^2 + 90*(x[4*i]-x[4*i-1]^2)^2 + (1-x[4*i-1])^2 + 10*(x[4*i-2]+x[4*i]-2)^2 + 0.1*(x[4*i-2]-x[4*i])^2)\n\tend\n    return fx\nend\n\ng! = (g, x) -> begin\n\tfor i in 1:Int(lastindex(x)/4)\n\t\tg[4i-3] = -2(1-x[4i-3]) - 400*x[4i-3]*(x[4i-2]-x[4i-3]^2)\n\t\tg[4i-2] = 200(x[4i-2]-x[4i-3]^2) + 0.2(x[4i-2]-x[4i]) + 20(x[4i-2] + x[4i]-2)\n\t\tg[4i-1] = -2(1-x[4i-1]) - 360*x[4i-1]*(x[4i]-x[4i-1]^2)\n\t\tg[4i] = -0.2(x[4i-2]-x[4i]) + 20(x[4i-2] + x[4i]-2) + 180(x[4i]-x[4i-1]^2)\n\tend\n    return g\nend\n\nfg! = (g, x) -> begin\n\tfx = 0.0\n\tfor i in 1:Int(lastindex(x)/4)\n\t\tfx += (100*(x[4*i-2]-x[4*i-3]^2)^2 + (1-x[4*i-3])^2 + 90*(x[4*i]-x[4*i-1]^2)^2 + (1-x[4*i-1])^2 + 10*(x[4*i-2]+x[4*i]-2)^2 + 0.1*(x[4*i-2]-x[4*i])^2)\n\t\tg[4i-3] = -2(1-x[4i-3]) - 400*x[4i-3]*(x[4i-2]-x[4i-3]^2)\n\t\tg[4i-2] = 200(x[4i-2]-x[4i-3]^2) + 0.2(x[4i-2]-x[4i]) + 20(x[4i-2] + x[4i]-2)\n\t\tg[4i-1] = -2(1-x[4i-1]) - 360*x[4i-1]*(x[4i]-x[4i-1]^2)\n\t\tg[4i] = -0.2(x[4i-2]-x[4i]) + 20(x[4i-2] + x[4i]-2) + 180(x[4i]-x[4i-1]^2)\n\tend\n    return fx, g\nend\n\ninit = (n::Int=4000) -> begin\n\tmod(n, 4) > 0 && @warn \"WOODS: number of variables must be divisible by 4\" \n\tq = max(1, div(n, 4))\n\tn = 4*q\n\n\tx0 = [j % 2 == 1 ? -3.0 : -1.0 for j in 1:n]\n    return n, x0\nend\n\nTestSet[\"WOODS\"] = UncProgram(\"WOODS\", f, g!, fg!, init)", "meta": {"hexsha": "77b928ab01a1ba3fb3a033baa9fde214040c17cc", "size": 2446, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/programs/WOODS.jl", "max_stars_repo_name": "danphenderson/UncNLPrograms.jl", "max_stars_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/programs/WOODS.jl", "max_issues_repo_name": "danphenderson/UncNLPrograms.jl", "max_issues_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/programs/WOODS.jl", "max_forks_repo_name": "danphenderson/UncNLPrograms.jl", "max_forks_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9428571429, "max_line_length": 151, "alphanum_fraction": 0.5506950123, "num_tokens": 1191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384731, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7880242667770867}}
{"text": "using OrdinaryDiffEq, ParameterizedFunctions, ForwardDiff\n\nf = @ode_def begin\n  dx = a*x - b*x*y\n  dy = -c*y + x*y\nend a b c\n\np = [1.5,1.0,3.0]\nprob = ODEProblem(f,[1.0;1.0],(0.0,10.0),p)\nt = 0.0:0.5:10.0\n\nfunction G(p)\n  tmp_prob = remake(prob,u0=convert.(eltype(p),prob.u0),p=p)\n  sol = solve(tmp_prob,Vern9(),abstol=1e-14,reltol=1e-14,saveat=t)\n  A = convert(Array,sol)\n  sum(((1 .- A).^2)./2)\nend\n# G([1.5,1.0,3.0])\n# res2 = ForwardDiff.gradient(G,[1.5,1.0,3.0])\n\n@info(\"Running forwarddiff\")\n# G([1.5,1.0,3.0])\nes2 = ForwardDiff.gradient(G,[1.5,1.0,3.0])\n# using Zygote\n# Zygote.gradient(G,[1.5,1.0,3.0])", "meta": {"hexsha": "b53c116adeb16f3d102aa6c541763604b1a2ab95", "size": 609, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/gradient_diffeq_example.jl", "max_stars_repo_name": "zzumbo/6.338-final-project", "max_stars_repo_head_hexsha": "696fdc095dc831abbe2c47b5a0186d95a9949e15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/gradient_diffeq_example.jl", "max_issues_repo_name": "zzumbo/6.338-final-project", "max_issues_repo_head_hexsha": "696fdc095dc831abbe2c47b5a0186d95a9949e15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/gradient_diffeq_example.jl", "max_forks_repo_name": "zzumbo/6.338-final-project", "max_forks_repo_head_hexsha": "696fdc095dc831abbe2c47b5a0186d95a9949e15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.36, "max_line_length": 66, "alphanum_fraction": 0.619047619, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731765, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.787963672051604}}
{"text": "using Revise\nusing DrWatson\n@quickactivate \"SICMModelingToolkit\"\nDrWatson.greet()\nusing ModelingToolkit, Unitful, DifferentialEquations, Optim\nusing Latexify\nusing BenchmarkTools, LinearAlgebra, ForwardDiff, Zygote\nusing Quadrature, StaticArrays\nusing SICMModelingToolkit\nusing Plots\nusing Measures\n\n\n#### section 1.4\n\n@parameters t m k\nD = Differential(t)\n\n\n\n\nlocals1 = generate_generic_localtuple(1)\nlocals2 = generate_generic_localtuple(2)\nlocals3 = generate_generic_localtuple(3)\n\nvelocity(locals3)\n\nL_free_mass = L_free_particle(m)\n\nLagrange_equations(L_free_mass, locals3)\n\nL_harmonic_spring_apply = L_harmonic_spring(m, k)\nLagrange_equations(L_harmonic_spring_apply, locals1)\nLagrange_equations(L_harmonic_spring_apply, locals3)\n\n\n\node_generator = ode_problem_generator(L_free_particle, locals3, [m])\n#Lagrangian_pre_param, locals, params = L_free_particle, locals3, [m]\n\n#ode_func = ODEFunction(ode_generator[1])\n\n#du = [0., 0., 0., 0., 0., 0.]\n#u0 = @SVector [1., 0.5, 0.25, 0., 0., 0.]\n#p0 = @SVector [1.0]\n#ode_func(du, u0, p0, 0.0)\n\n#@show du\n\n#dyn_ode_func(du, u, p, t) = DynamicalODEFunction{true}(ode_func)\n\n\n\ndu = [0., 0., 0.]\nq0 = [0., 0., 0.]\nqv0 = [1.0, 0.5, 0.25]\n#u0 = [1., 0.5, 0.25, 0., 0., 0.]\nu0 = ArrayPartition(qv0, q0)\np0 = [1.0]\nt0 = 0.0\n\ntspan = (0.0, 2.0)\n\nprob = ode_generator(qv0, q0, tspan, p0; saveat=0.05)\n\n\nsol = solve(prob, McAte5(); dt=0.05)\n\nplot(sol, vars=(4,5,6); dpi=350)\n\n\n### kepler \n\nkepler_ode_generator = ode_problem_generator(L_kepler, locals2, [m, k])\n\nbegin \n    q0_kep = [0.0, 1.0]\n    qv0_kep = [-1.0, 0.0]\n\ttspan_kep = (0.0, 5.0)\n    p_kep = [3.0, 10.0]\n    dt = 0.01\n\n    kepler_prob = kepler_ode_generator(qv0_kep, q0_kep, tspan_kep, p_kep)\nend\n\nkepler_sol = solve(kepler_prob, McAte5(); dt=dt)\nkepler_sol_nosymp = solve(kepler_prob, Tsit5(); dt=dt)\n\ncurxlims = (-1.1, 1.1)\ncurylims = (9.0/16) .* curxlims \ncur_left_margin = Measures.Length{:mm, Float64}(12)\ncur_bottom_margin = Measures.Length{:mm, Float64}(7)\ngr()\nellipseplot = plot(kepler_sol, vars=(4,3); dpi=500, ylims=curylims, xlims=curxlims,\n    label=\"orbiter\", xlabel=\"x\", ylabel=\"y\", title=\"Kepler Orbital Problem Symplectic\", \n    left_margin=cur_left_margin, bottom_margin=cur_bottom_margin)\nscatter!(ellipseplot, [0.0], [0.0]; label=\"planet\")\nsave(\"kepler_symplectic.png\", ellipseplot)\nellipseplot_nosymp = plot(kepler_sol_nosymp, vars=(4,3); dpi=500, ylims=curylims, xlims=curxlims,\n    label=\"orbiter\", xlabel=\"x\", ylabel=\"y\", title=\"Kepler Orbital Problem Nonsymplectic\", \n    left_margin=cur_left_margin, bottom_margin=cur_bottom_margin)\nscatter!(ellipseplot_nosymp, [0.0], [0.0]; label=\"planet\")\nsave(\"kepler_nosymplectic.png\", ellipseplot_nosymp)\nplot(kepler_sol, vars=(0,3,4); dpi=350)\n\n\n#### harmonic \n\n\nharmonic_ode_generator = ode_problem_generator(L_harmonic_spring, locals1, [m, k])\n\nbegin \n    q0_harm = [1.0]\n    qv0_harm = [0.0]\n\ttspan_harm = (0.0, 5.0)\n    p_harm = [1.0, 1.0]\n    dt = 0.01\n\n    harmonic_prob = harmonic_ode_generator(qv0_harm, q0_harm, tspan_harm, p_harm)\nend\n\nharmonic_sol = solve(harmonic_prob, McAte5(); dt=dt)\nplot(harmonic_sol; dpi=500, left_margin=cur_left_margin, bottom_margin=cur_bottom_margin)\n\n", "meta": {"hexsha": "5bade6e49207c72f00d048bb631615c937c139e6", "size": 3160, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/chapter1.jl", "max_stars_repo_name": "zoemcc/SICMModelingToolkit", "max_stars_repo_head_hexsha": "7e5bc5f137f8fc255fd7dbcabd9dfc185fed707a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/chapter1.jl", "max_issues_repo_name": "zoemcc/SICMModelingToolkit", "max_issues_repo_head_hexsha": "7e5bc5f137f8fc255fd7dbcabd9dfc185fed707a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/chapter1.jl", "max_forks_repo_name": "zoemcc/SICMModelingToolkit", "max_forks_repo_head_hexsha": "7e5bc5f137f8fc255fd7dbcabd9dfc185fed707a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.28, "max_line_length": 97, "alphanum_fraction": 0.7161392405, "num_tokens": 1171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7879636513420762}}
{"text": "\n# A Julia-native gamma function. Pretty darn accurate and fast, and using this\n# instead of SpecialFunctions.gamma would mean that the dependency can be\n# removed. That doesn't seem worth it to me at this point in time, but putting\n# this here in case.\n\nconst _G  = 607/128 \nconst _C1 = 0.99999999999999709182\nconst _C  = (57.156235665862923517,\n            -59.597960355475491248,\n             14.136097974741747174,\n            -0.49191381609762019978,\n            .33994649984811888699e-4,\n            .46523628927048575665e-4,\n           -.98374475304879564677e-4,\n            .15808870322491248884e-3,\n           -.21026444172410488319e-3,\n            .21743961811521264320e-3,\n           -.16431810653676389022e-3,\n            .84418223983852743293e-4,\n           -.26190838401581408670e-4,\n            .36899182659531622704e-5)\nconst _Cl = length(_C)\nconst SQRT_2_PI = sqrt(2*pi)\n\n# Lanczos approximation. \n@inline function _gamma_pos(_z::T) where{T}\n  T_one    = one(T)\n  T_half   = T_one/(T_one+T_one)\n  z_half   = _z-T_half\n  z_g_half = z_half+_G\n  out = 0.99999999999999709182 \n  zpj = _z \n  @inbounds for c in _C\n    out += c/zpj \n    zpj += T_one \n  end\n  out*SQRT_2_PI*exp(z_half*log(z_g_half) - z_g_half)\nend\n\nfunction _gamma(x)\n  iszero(x) && return Inf\n  (isinteger(x) && x < zero(x)) && return NaN\n  x > zero(x) && return _gamma_pos(x)\n  flx = floor(x)\n  xf  = x - flx\n  g   = _gamma_pos(xf) \n  _x  = xf-one(x)\n  for _ in 1:Int(-flx)\n    g  /= _x\n    _x -= one(x)\n  end\n  g\nend\n\n", "meta": {"hexsha": "546a99c3dc7cd8e8cd9d87958eabe1a3411db438", "size": 1498, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/notinuse/gamma.jl", "max_stars_repo_name": "cgeoga/BesselK.jl", "max_stars_repo_head_hexsha": "ba87f86f5fb42919da6ba0f928cae31fd26fc8e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-12-19T20:28:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T16:22:03.000Z", "max_issues_repo_path": "src/notinuse/gamma.jl", "max_issues_repo_name": "cgeoga/BesselK.jl", "max_issues_repo_head_hexsha": "ba87f86f5fb42919da6ba0f928cae31fd26fc8e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-12-20T16:14:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T03:39:49.000Z", "max_forks_repo_path": "src/notinuse/gamma.jl", "max_forks_repo_name": "cgeoga/BesselK.jl", "max_forks_repo_head_hexsha": "ba87f86f5fb42919da6ba0f928cae31fd26fc8e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-04T20:05:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T20:05:15.000Z", "avg_line_length": 26.75, "max_line_length": 78, "alphanum_fraction": 0.6315086782, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951703918909, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7878778918343544}}
{"text": "# Hello!\r\n# This is the second Project Euler question where I find the sum of the\r\n# even-valued terms of the Fibonacci Sequence under 4 million!\r\n\r\n# I am using Binet's Formula to calculate the terms in the Fibonacci Sequence!\r\n\r\n# The Golden Ratio!\r\nφ = (1 + sqrt(5))/2\r\n\r\n# The Binet's Formula is :\r\n# the golden ratio (~ 1.618) raised to the nth power and divide it by sqrt of 5\r\n# and rounding the answer to the nearest integer. The error approaches 0 as you\r\n# approach the infinitely big terms!\r\n\r\nfibonacci_term = 0\r\na = (φ ^ fibonacci_term)/sqrt(5)\r\nb = round(Int, a)\r\n\r\n# I can calculate many Fibonacci Numbers at once!\r\n# Binet's Formula in ACTION!!!\r\n\r\nc = 100\r\nd = 1 : c\r\ne = φ .^ d\r\nf = e/sqrt(5)\r\nfibonacci_numbers = round.(f)\r\n\r\n# I can just find the even-valued Fibonacci terms!\r\n# Every third Fibonacci term is even!\r\n\r\ng = 100\r\nh = 1 : g\r\n# 3 * h is too skip 2 terms and go to the next even-valued Fibonacci Number.\r\ni = φ .^ (3 * h)\r\nj = i / sqrt(5)\r\neven_valued_fibonacci_numbers = round.(j)\r\n\r\n# I control the size of the Fibonacci Numbers.\r\n# I am just setting the domain for the Fibonacci Numbers because I do not want\r\n# them to be too big (The even-valued Fibonacci terms cannot be greater than\r\n# 4 million).\r\n\r\nk = 1\r\nsum = 0\r\nwhile even_valued_fibonacci_numbers[k] < 4000000\r\n\tk = k + 1\r\n\tsum = sum + even_valued_fibonacci_numbers[k - 1]\r\nend\r\nprintln(sum)\r\n", "meta": {"hexsha": "a2008d972ccb537a7205d57d7ee22d37b507d8b0", "size": 1387, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/Project_Euler_2_Julia.jl", "max_stars_repo_name": "tinfungster/Project_Euler", "max_stars_repo_head_hexsha": "86282921d7c489f8c8b06f95f84cc972266ca231", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-22T19:55:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-22T19:55:01.000Z", "max_issues_repo_path": "Solutions/Project_Euler_2_Julia.jl", "max_issues_repo_name": "tinfungster/Project_Euler", "max_issues_repo_head_hexsha": "86282921d7c489f8c8b06f95f84cc972266ca231", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/Project_Euler_2_Julia.jl", "max_forks_repo_name": "tinfungster/Project_Euler", "max_forks_repo_head_hexsha": "86282921d7c489f8c8b06f95f84cc972266ca231", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.74, "max_line_length": 80, "alphanum_fraction": 0.6863734679, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966410494349896, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7878492287064701}}
{"text": "using LinearAlgebraicRepresentation\nLar = LinearAlgebraicRepresentation\nusing Plasm\n\nVOID = [[]], [[1]]\n\n\n# example 1\n\nV = [[0,0] [1,0] [2,0] [0,1] [1,1] [2,1] [0,2] [1,2] [2,2]];\nFV = [[1,2,4],[2,3,5],[3,5,6],[4,5,7],[5,7,8],[6,8,9]];\npattern = repeat([1,2,-3],outer=4);\nmodel = (V,FV);\nW,FW = Lar.extrudeSimplicial(model, pattern);\nPlasm.view(W,FW)\n\n# example 2\n\nmodel = Lar.extrudeSimplicial( VOID, ones(10) )\nPlasm.view(model)\nmodel = Lar.extrudeSimplicial( model, ones(10) )\nPlasm.view(model)\nmodel = Lar.extrudeSimplicial( model, ones(10) )\nPlasm.view(model)\n\n\n# example 3\n\nmodel = Lar.extrudeSimplicial( VOID, repeat([1,-1],outer=10) )\nPlasm.view(model)\nmodel = Lar.extrudeSimplicial( model, repeat([1,-1],outer=10) )\nPlasm.view(model)\n\n\n# example 4\n\ngrid_2d = Lar.simplexGrid([3,3])\nPlasm.view(grid_2d)\ngrid_3d = Lar.simplexGrid([2,3,4])\nPlasm.view(grid_3d)\nV,CV = Lar.simplexGrid([1,1,1])\nPlasm.view(V,CV)\n\n# example 5\n\nSK2 = Lar.simplexFacets(CV)\nPlasm.view(V, SK2)\nSK1 = Lar.simplexFacets(SK2)\nPlasm.view(V, SK1)\n\n", "meta": {"hexsha": "5cd2f11a9aa98a0781f541ae1b8932b5dc206a4f", "size": 1025, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/3d/simplexn_examples.jl", "max_stars_repo_name": "eOnofri04/LinearAlgebraicRepresentation.jl", "max_stars_repo_head_hexsha": "11d5a283dc55929c0654b63b7847b01c0a4e6956", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/3d/simplexn_examples.jl", "max_issues_repo_name": "eOnofri04/LinearAlgebraicRepresentation.jl", "max_issues_repo_head_hexsha": "11d5a283dc55929c0654b63b7847b01c0a4e6956", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-03T11:48:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-03T11:48:14.000Z", "max_forks_repo_path": "examples/3d/simplexn_examples.jl", "max_forks_repo_name": "eOnofri04/LinearAlgebraicRepresentation.jl", "max_forks_repo_head_hexsha": "11d5a283dc55929c0654b63b7847b01c0a4e6956", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0980392157, "max_line_length": 63, "alphanum_fraction": 0.6663414634, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.787843057207196}}
{"text": "using Pkg\nPkg.activate(pwd())\n\n# # Constrained Optimization\n# ## Numerical method\n\nusing Plots, Random\n\nfunction create_anim(\n    f,\n    path,\n    xlims,\n    ylims,\n    file_name = joinpath(pwd(), randstring(12) * \".gif\");\n    xbounds = xlims,\n    ybounds = ylims,\n    fps = 15,\n)\n    xs = range(xlims...; length = 100)\n    ys = range(ylims...; length = 100)\n    plt = contourf(xs, ys, f; color = :jet)\n\n    # add constraints if provided\n    if !(xbounds == xlims && ybounds == ylims)\n        x_rect = [xbounds[1]; xbounds[2]; xbounds[2]; xbounds[1]; xbounds[1]]\n        y_rect = [ybounds[1]; ybounds[1]; ybounds[2]; ybounds[2]; ybounds[1]]\n\n        plot!(x_rect, y_rect; line = (2, :dash, :red), label=\"\")\n    end\n\n    # add an empty plot\n    plot!(Float64[], Float64[]; line = (4, :arrow, :black), label = \"\")\n\n    # extract the last plot series\n    plt_path = plt.series_list[end]\n\n    # create the animation and save it\n    anim = Animation()\n    for x in eachcol(path)\n        push!(plt_path, x[1], x[2]) # add a new point\n        frame(anim)\n    end\n    gif(anim, file_name; fps = fps, show_msg = false)\n    return nothing\nend\n\nf(x) = sin(x[1] + x[2]) + cos(x[1])^2\nf(x1,x2) = f([x1;x2])\ng(x) = [cos(x[1] + x[2]) - 2*cos(x[1])*sin(x[1]); cos(x[1] + x[2])]\n\n#+\n\nfunction optim(f, g, P, x, α; max_iter=100)\n    xs = zeros(length(x), max_iter+1)\n    ys = zeros(length(x), max_iter)\n    xs[:,1] = x\n    for i in 1:max_iter\n        ys[:,i] = xs[:,i] - α*g(xs[:,i])\n        xs[:,i+1] = P(ys[:,i])\n    end\n    return xs, ys\nend\n\n#+\n\nP(x, x_min, x_max) = min.(max.(x, x_min), x_max)\n\nx_min = [-1; -1]\nx_max = [0; 0]\n\nxs, ys = optim(f, g, x -> P(x,x_min,x_max), [0;-1], 0.1)\n\nxlims = (-3, 1)\nylims = (-2, 1)\n\n#+\n\ncreate_anim(f, xs, xlims, ylims, joinpath(pwd(), \"lecture_08\", \"anim6.gif\");\n    xbounds=(x_min[1], x_max[1]),\n    ybounds=(x_min[2], x_max[2]),\n)\n\n#+\n\nxys = hcat(reshape([xs[:,1:end-1]; ys][:], 2, :), xs[:,end])\n\ncreate_anim(f, xys, xlims, ylims, joinpath(pwd(), \"lecture_08\", \"anim7.gif\");\n    xbounds=(x_min[1], x_max[1]),\n    ybounds=(x_min[2], x_max[2]),\n)", "meta": {"hexsha": "afd358cba38e2e3740e6ce1469724cbf7797dd0b", "size": 2071, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_08/02-constrained.jl", "max_stars_repo_name": "JuliaTeachingCTU/Julia-for-Optimization-and-Learning-Scripts", "max_stars_repo_head_hexsha": "8e00299449736e4ccf47c247aa9d80f99a7e5b92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lecture_08/02-constrained.jl", "max_issues_repo_name": "JuliaTeachingCTU/Julia-for-Optimization-and-Learning-Scripts", "max_issues_repo_head_hexsha": "8e00299449736e4ccf47c247aa9d80f99a7e5b92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecture_08/02-constrained.jl", "max_forks_repo_name": "JuliaTeachingCTU/Julia-for-Optimization-and-Learning-Scripts", "max_forks_repo_head_hexsha": "8e00299449736e4ccf47c247aa9d80f99a7e5b92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0111111111, "max_line_length": 77, "alphanum_fraction": 0.5523901497, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582995, "lm_q2_score": 0.8670357563664174, "lm_q1q2_score": 0.7878042033697134}}
{"text": "module NumericError\n\nimport Base: convert, promote_rule, +, -, *, /, ^\n\nexport Measure\n\ntype Measure <: Number\n  x::Float64\n  σ::Float64\n  Measure(x::Real) = new(Float64(x), 0)\n  Measure(x::Real, σ::Real) = new(Float64(x), σ)\nend\n\nBase.show(io::IO, x::Measure) = print(io, string(x.x, \" ± \", x.σ))\n\nBase.convert(::Type{Measure}, x::Real) = Measure(Float64(x), 0.0)\nBase.promote_rule(::Type{Float64}, ::Type{Measure}) = Measure\nBase.promote_rule(::Type{Int64}, ::Type{Measure}) = Measure\n\n+(a::Measure, b::Measure) = Measure(a.x + b.x, sqrt(a.σ ^ 2 + b.σ ^ 2))\n-(a::Measure, b::Measure) = Measure(a.x - b.x, sqrt(a.σ ^ 2 + b.σ ^ 2))\n-(a::Measure) = Measure(-a.x, a.σ)\n\n*(a::Measure, b::Measure) = begin\n  x = a.x * b.x\n  σ = sqrt(x ^ 2 * ((a.σ / a.x) ^ 2 + (b.σ / b.x) ^ 2))\n  Measure(x, σ)\nend\n/(a::Measure, b::Measure) = begin\n  x = a.x / b.x\n  σ = sqrt(x ^ 2 * ((a.σ / a.x) ^ 2 + (b.σ / b.x) ^ 2))\n  Measure(x, σ)\nend\n\n^(a::Measure, b::Float64) = begin\n  x = a.x ^ b\n  σ = abs(x * b * a.σ / a.x)\n  Measure(x, σ)\nend\n\nBase.sqrt(a::Measure) = a ^ .5\n\nend  # module NumericError\n\nusing NumericError\n\n# x1 = 100 ± 1.1\n# y1 = 50 ± 1.2\n# x2 = 200 ± 2.2\n# y2 = 100 ± 2.3\n\nx1 = Measure(100, 1.1)\ny1 = Measure(50,  1.2)\nx2 = Measure(200, 2.2)\ny2 = Measure(100, 2.3)\n\nd = sqrt((x1 - x2) ^ 2 + (y1 - y2) ^ 2)\n\n@show x1 y1 x2 y2 sqrt((x1 - x2) ^ 2 + (y1 - y2) ^ 2)\n", "meta": {"hexsha": "ecbd1e155f8b9ddff049a37deb10e3e18aa776ba", "size": 1355, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/numeric-error-propagation.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/numeric-error-propagation.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/numeric-error-propagation.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5833333333, "max_line_length": 71, "alphanum_fraction": 0.5512915129, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.8633916064587, "lm_q1q2_score": 0.7877897223851946}}
{"text": "using QuantEcon.compute_fixed_point, QuantEcon.DiscreteRV, QuantEcon.draw, QuantEcon.LinInterp\r\n\r\n\"\"\"\r\nFor a given probability return expected loss of choosing model 0\r\n\"\"\"\r\nexpect_loss_choose_0(p::Real, L0::Real) = (1 - p) * L0\r\n\r\n\"\"\"\r\nFor a given probability return expected loss of choosing model 1\r\n\"\"\"\r\nexpect_loss_choose_1(p::Real, L1::Real) = p * L1\r\n\r\n\"\"\"\r\nWe will need to be able to evaluate the expectation of our Bellman\r\nequation J. In order to do this, we need the current probability\r\nthat model 0 is correct (p), the distributions (f0, f1), and a\r\nfunction that can evaluate the Bellman equation\r\n\"\"\"\r\nfunction EJ(p::Real, f0::AbstractVector, f1::AbstractVector, J::LinInterp)\r\n    # Get the current distribution we believe (p * f0 + (1 - p) * f1)\r\n    curr_dist = p * f0 + (1 - p) * f1\r\n\r\n    # Get tomorrow's expected distribution through Bayes law\r\n    tp1_dist = clamp.((p * f0) ./ (p * f0 + (1 - p) * f1), 0, 1)\r\n\r\n    # Evaluate the expectation\r\n    EJ = dot(curr_dist, J.(tp1_dist))\r\n\r\n    return EJ\r\nend\r\n\r\nexpect_loss_cont(p::Real, c::Real,\r\n                 f0::AbstractVector, f1::AbstractVector, J::LinInterp) =\r\n    c + EJ(p, f0, f1, J)\r\n\r\n\"\"\"\r\nEvaluates the value function for a given continuation value\r\nfunction; that is, evaluates\r\n\r\n    J(p) = min(pL0, (1-p)L1, c + E[J(p')])\r\n\r\nUses linear interpolation between points\r\n\"\"\"\r\nfunction bellman_operator(pgrid::AbstractVector,\r\n                          c::Real,\r\n                          f0::AbstractVector,\r\n                          f1::AbstractVector,\r\n                          L0::Real,\r\n                          L1::Real,\r\n                          J::AbstractVector)\r\n    m = length(pgrid)\r\n    @assert m == length(J)\r\n\r\n    J_out = zeros(m)\r\n    J_interp = LinInterp(pgrid, J)\r\n\r\n    for (p_ind, p) in enumerate(pgrid)\r\n        # Payoff of choosing model 0\r\n        p_c_0 = expect_loss_choose_0(p, L0)\r\n        p_c_1 = expect_loss_choose_1(p, L1)\r\n        p_con = expect_loss_cont(p, c, f0, f1, J_interp)\r\n\r\n        J_out[p_ind] = min(p_c_0, p_c_1, p_con)\r\n    end\r\n\r\n    return J_out\r\nend\r\n\r\n# Create two distributions over 50 values for k\r\n# We are using a discretized beta distribution\r\n\r\np_m1 = linspace(0, 1, 50)\r\nf0 = clamp.(pdf.(Beta(1, 1), p_m1), 1e-8, Inf)\r\nf0 = f0 / sum(f0)\r\nf1 = clamp.(pdf.(Beta(9, 9), p_m1), 1e-8, Inf)\r\nf1 = f1 / sum(f1)\r\n\r\n# To solve\r\npg = linspace(0, 1, 251)\r\nJ1 = compute_fixed_point(x -> bellman_operator(pg, 0.5, f0, f1, 5.0, 5.0, x),\r\n    zeros(length(pg)), err_tol=1e-6, print_skip=5);\r\n", "meta": {"hexsha": "9057a919456d2988adbefdba6c09647920143f3e", "size": 2517, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "wald_friedman/wf_first_pass.jl", "max_stars_repo_name": "QuantEcon/QuantEcon.lectures.code", "max_stars_repo_head_hexsha": "d61ac7bc54529dd5c77470c17539eb2418b047c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2017-05-09T10:45:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:33:27.000Z", "max_issues_repo_path": "wald_friedman/wf_first_pass.jl", "max_issues_repo_name": "QuantEcon/QuantEcon.lectures.code", "max_issues_repo_head_hexsha": "d61ac7bc54529dd5c77470c17539eb2418b047c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2017-06-30T01:52:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-01T20:09:47.000Z", "max_forks_repo_path": "wald_friedman/wf_first_pass.jl", "max_forks_repo_name": "QuantEcon/QuantEcon.lectures.code", "max_forks_repo_head_hexsha": "d61ac7bc54529dd5c77470c17539eb2418b047c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 117, "max_forks_repo_forks_event_min_datetime": "2017-04-25T16:09:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T02:30:29.000Z", "avg_line_length": 30.6951219512, "max_line_length": 95, "alphanum_fraction": 0.6015097338, "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362486, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7877746035822822}}
{"text": "function log_taylor(x::Number)\n    if x <= 0\n        return undef\n    end\n\n    e = float(Base.MathConstants.e)\n    lb = 0.546\n    ub = lb * e\n\n    res = 0\n\n    while x < lb\n        x *= e\n        res -= 1\n    end\n\n    while x > ub\n        x /= e\n        res += 1\n    end\n\n    s = 1\n\n    for i in 1 : 40\n        res += s * (x - 1)^i / i\n        s *= -1\n    end\n\n    return res\nend\n", "meta": {"hexsha": "d1dbaef8411912e9221af4780ff15f7dc686af71", "size": 380, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "18Host/TDT4120/AtomProjectFolder/Project1/MathUtil.jl", "max_stars_repo_name": "MarcusTL12/School", "max_stars_repo_head_hexsha": "f7302f2d390e99ad9d06004e15da032c05ec59e7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "18Host/TDT4120/AtomProjectFolder/Project1/MathUtil.jl", "max_issues_repo_name": "MarcusTL12/School", "max_issues_repo_head_hexsha": "f7302f2d390e99ad9d06004e15da032c05ec59e7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "18Host/TDT4120/AtomProjectFolder/Project1/MathUtil.jl", "max_forks_repo_name": "MarcusTL12/School", "max_forks_repo_head_hexsha": "f7302f2d390e99ad9d06004e15da032c05ec59e7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.2580645161, "max_line_length": 35, "alphanum_fraction": 0.4, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565738, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7877745911034689}}
{"text": "using DrWatson\n@quickactivate \"StatReth\"\n\n# %%\nusing CSV\nusing DataFrames\nusing Turing\nusing Plots\n\ninclude(srcdir(\"quap.jl\"))\ninclude(srcdir(\"tools.jl\"))\n\n# %%\n# This is from the chapter\nd = DataFrame(CSV.File(datadir(\"exp_raw/Howell_1.csv\")))\nsort!(d, :weight)  # to make the plots look nice\n\nz_weight, unz_weight = zscore_transform(d.weight)\nd.weight_s = z_weight(d.weight)\n\nf_parabola(weight_s, a, b1, b2) = a + b1 * weight_s + b2 * weight_s^2\n\n@model function parabola(weight_s, height)\n    a ~ Normal(178, 20)\n    b1 ~ LogNormal(0, 1)\n    b2 ~ Normal(0, 1)\n    σ ~ Uniform(0, 50)\n    μ = f_parabola.(weight_s, a, b1, b2)\n    height ~ MvNormal(μ, σ)\nend\n\nmparab = parabola(d.weight_s, d.height)\nprior = sample(mparab, Prior(), 1_000) |> DataFrame\n\n# %%\nplot(legend = false)\nfor c in eachrow(prior[1:100, :])\n    p = f_parabola.(d.weight_s, c.a, c.b1, c.b2)\n    plot!(d.weight_s, p, color = :black, alpha = 0.2)\nend\nplot!()\n\n# %%\n\"\"\"\nThinking about the cbrt explanation, b2 should be negative so I get a right turn here as\nwell. Since I don't want the extremum to be in the range of my data I need the maximum to\nbe at like 3 or 4 or something like that. Over the range of ~4 stddev I want the height to\nchange 100 cm or so.\nf(x) = b₂ * x² + b₁ * x + a\nf'(x) = 2b₂ * x + b₁\n\nf(2) - f(-2) = 100\nf'(3) = 0\nb₂ < 0\n\nf(2) - f(-2) = (b₂ * 4 + b₁ * 2 + a) - (b₂ * 4 + b₁ * -2 + a)\n             = 4b₁ = 100\n            =>  b₁ =  25\nf'(3) = 2b₂ * 3 + b₁ = 0 => -b₁ = 6b₂\n     => b₂ = -25 / 6 ≈ -4\n\nI'll move a by hand until it seams reasonable.\n\"\"\"\n\n@model function parabola(weight_s, height)\n    a ~ Normal(130, 20)\n    b1 ~ Normal(25, 5)\n    b2 ~ truncated(Normal(-4, 2), -Inf, 0)\n    σ ~ Exponential(5)\n    μ = f_parabola.(weight_s, a, b1, b2)\n    height ~ MvNormal(μ, σ)\nend\n\nmparab = parabola(d.weight_s, d.height)\nprior = sample(mparab, Prior(), 100) |> DataFrame\n\nplot(legend = false)\nfor c in eachrow(prior)\n    p = f_parabola.(d.weight_s, c.a, c.b1, c.b2)\n    plot!(d.weight_s, p, color = :black, alpha = 0.2)\nend\nplot!(ylims = (0, 200))\n", "meta": {"hexsha": "398aedde4680f6ba9aa192d1a6eb412302554262", "size": 2042, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/ch04/4H4.jl", "max_stars_repo_name": "karajan9/statisticalrethinking", "max_stars_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-06-03T14:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T16:52:26.000Z", "max_issues_repo_path": "exercises/ch04/4H4.jl", "max_issues_repo_name": "karajan9/statisticalrethinking", "max_issues_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-13T05:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T14:05:57.000Z", "max_forks_repo_path": "exercises/ch04/4H4.jl", "max_forks_repo_name": "karajan9/statisticalrethinking", "max_forks_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-01T13:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-03T23:40:53.000Z", "avg_line_length": 24.6024096386, "max_line_length": 90, "alphanum_fraction": 0.6175318315, "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.8438951045175642, "lm_q1q2_score": 0.7877176902708871}}
{"text": "\n\"\"\"\n    generate_conditioned_dist(covar::CovarianceAtDate, conditioning_draws::Array{Symbol,T}) where T<:Real\nGiven some subset of known stochastic integral values this generates a conditional multivariate normal distribution.\n\"\"\"\nfunction generate_conditioned_distribution(covar::CovarianceAtDate, conditioning_draws::Dict{Symbol,T}) where T<:Real\n    # https://stats.stackexchange.com/questions/30588/deriving-the-conditional-distributions-of-a-multivariate-normal-distribution\n    what_conditioned_on = collect(keys(conditioning_draws))\n    len = length(what_conditioned_on)\n    if len < 1 error(\"Nothing that was input was in the covariance matrix. So nothing to condition on.\") end\n    conditioning_indices = Array{typeof(Integer(1)),1}()\n    for i in 1:len\n        append!(conditioning_indices, findall(what_conditioned_on[i] .==  covar.covariance_labels_))\n    end\n    other_indices = setdiff(1:length(covar.covariance_labels_), conditioning_indices)\n    labels = covar.covariance_labels_[other_indices]\n    # Segmenting the covariance matrix.\n    sigma11 = covar.covariance_[other_indices,other_indices]\n    sigma12 = covar.covariance_[other_indices,conditioning_indices]\n    sigma21 = covar.covariance_[conditioning_indices,other_indices]\n    sigma22 = covar.covariance_[conditioning_indices,conditioning_indices]\n    mu1     = zeros(length(other_indices))\n    mu2     = zeros(length(conditioning_indices))\n    conditioned_values = map( x -> conditioning_draws[x], what_conditioned_on)\n    sigma12_invsigma22 = sigma12 * inv(sigma22)\n    conditional_mu = mu1 + sigma12_invsigma22 * (conditioned_values - mu2)\n    conditional_sigma = sigma11 -  sigma12_invsigma22 * sigma21\n    return conditional_mu, conditional_sigma, labels\nend\n", "meta": {"hexsha": "318a905cb5f29ded376abc6dd7414200e9d2840e", "size": 1740, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/5_conditional_distributions.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StochasticIntegrals.jl-b15139f2-feda-5ba7-9a2a-3fc816fb5551", "max_stars_repo_head_hexsha": "028a8545ff58091768ff1a77fc388eb8738c3492", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/5_conditional_distributions.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StochasticIntegrals.jl-b15139f2-feda-5ba7-9a2a-3fc816fb5551", "max_issues_repo_head_hexsha": "028a8545ff58091768ff1a77fc388eb8738c3492", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/5_conditional_distributions.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StochasticIntegrals.jl-b15139f2-feda-5ba7-9a2a-3fc816fb5551", "max_forks_repo_head_hexsha": "028a8545ff58091768ff1a77fc388eb8738c3492", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.0, "max_line_length": 130, "alphanum_fraction": 0.7770114943, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7877176889776998}}
{"text": "# Pkg.add(\"ForwardDiff\")\nusing ForwardDiff\n\n\"\"\"\n```\nf(x) = x^2 - 2;\nx0 = 1;\nx = newton(f, x0);\n```\n\"\"\"\nfunction newton(f, x0)\n  # 求目标函数导数\n  Δf = x -> ForwardDiff.derivative(f, x);\n\n  xk = Base.float(x0);\n  xk_1 = Base.float(x0);\n\n  # 比机器精度少一个数量级\n  epsilon = Base.eps(xk) * 10;\n\n  while true\n    xk_1 = xk - f(xk)/Δf(xk);\n    if Base.abs(xk_1 - xk) < epsilon || Base.abs(f(xk_1)) < epsilon\n      break;\n    end\n    xk = xk_1;\n  end\n\n  return xk_1;\nend", "meta": {"hexsha": "fde8a1ccdb557ebebd3493f5ef513003d27fb5c7", "size": 450, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tex/code/find_zero_newton.jl", "max_stars_repo_name": "HereChen/Algorithm", "max_stars_repo_head_hexsha": "c3da049641513ecbeea3e3cdb3feaae6acabe94c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/code/find_zero_newton.jl", "max_issues_repo_name": "HereChen/Algorithm", "max_issues_repo_head_hexsha": "c3da049641513ecbeea3e3cdb3feaae6acabe94c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/code/find_zero_newton.jl", "max_forks_repo_name": "HereChen/Algorithm", "max_forks_repo_head_hexsha": "c3da049641513ecbeea3e3cdb3feaae6acabe94c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.0, "max_line_length": 67, "alphanum_fraction": 0.5577777778, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7877176863366184}}
{"text": "\"\"\"\n    bernoulli(n)\n\n Calculates the first 35 Bernoulli numbers ``B_n``  (of the first-kind or NIST type) \n e.g., see\n\n + [http://mathworld.wolfram.com/BernoulliNumber.html](http://mathworld.wolfram.com/BernoulliNumber.html)\n + [https://en.wikipedia.org/wiki/Bernoulli_number](https://en.wikipedia.org/wiki/Bernoulli_number)\n + [http://dlmf.nist.gov/24](http://dlmf.nist.gov/24)\n\n N.B. Bernoulli numbers of second kind only seem to differ in that ``B_1 = + 1/2`` (instead of -1/2)\n\n## Arguments\n* ``n`` `::Integer`: the index into the series, ``n=0,1,2,3,...,35`` (for larger ``n`` use `bernoulli(n,0.0)` )\n\n We only provide the 1st 36 values as beyond this, we can't\n return Int64 rationals, so best to compute the real approximation\n using `bernoulli(n,0.0)`. \n\n Odd values for ``n>1`` are all zero.\n\n## Examples\n```jldoctest; setup = :(using Polylogarithms)\njulia> bernoulli(6)\n1//42\n```\n\"\"\"\nfunction bernoulli(n::Integer)\n    # this just does a lookup -- seemed like it would be easier to code and faster\n    # for the size of numbers I am working with\n    if n<0\n        throw(DomainError(n))\n    elseif n > 1 && isodd(n)\n        return 0 // 1\n    elseif n > 35\n        throw(DomainError(n, \"If n > 35, then the numerator needs Int128 at least, and worse, so this code is not the code you want. Try using bernoulli(n, 0.0) to get a floating point approximation to the result.\"))\n    end\n\n    # Denominator of Bernoulli number B_n\n    #   http://oeis.org/A027642\n    D = [2, 6, 1, 30, 1, 42, 1, 30, 1, 66, 1, 2730, 1, 6, 1, 510, 1, 798, 1, 330, 1, 138, 1, 2730, 1, 6, 1, 870, 1, 14322, 1, 510, 1, 6, 1, 1919190, 1, 6, 1, 13530, 1, 1806, 1, 690, 1, 282, 1, 46410, 1, 66, 1, 1590, 1, 798, 1, 870, 1, 354, 1, 56786730]\n\n    # Numerator of Bernoulli number B_n (storing 62 of these because they are easy)\n    #   http://oeis.org/A027641\n    N = [-1, 1, 0, -1, 0, 1, 0, -1, 0, 5, 0, -691, 0, 7, 0, -3617, 0, 43867, 0, -174611, 0, 854513, 0, -236364091, 0, 8553103, 0, -23749461029, 0, 8615841276005, 0, -7709321041217, 0, 2577687858367, 1]\n    \n    if n==0\n        return 1 \n    else\n        return N[n] // D[n]\n    end\nend\n", "meta": {"hexsha": "b08dbe9c861f452bfa0cf6f67bc8e752f02184b8", "size": 2124, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bernoulli_n.jl", "max_stars_repo_name": "AshtonSBradley/Polylogarithms.jl", "max_stars_repo_head_hexsha": "f52e3075cd1d87b0d67d26c72cd1a79a365eddcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-08-24T09:17:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T10:54:45.000Z", "max_issues_repo_path": "src/bernoulli_n.jl", "max_issues_repo_name": "AshtonSBradley/Polylogarithms.jl", "max_issues_repo_head_hexsha": "f52e3075cd1d87b0d67d26c72cd1a79a365eddcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-11-18T00:06:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-18T10:35:43.000Z", "max_forks_repo_path": "src/bernoulli_n.jl", "max_forks_repo_name": "AshtonSBradley/Polylogarithms.jl", "max_forks_repo_head_hexsha": "f52e3075cd1d87b0d67d26c72cd1a79a365eddcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-17T16:20:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T09:32:06.000Z", "avg_line_length": 40.0754716981, "max_line_length": 252, "alphanum_fraction": 0.6313559322, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7877176811091622}}
{"text": "module DataGenerator\n\nimport Distributions; D = Distributions\nusing LinearAlgebra\n\nexport linregdata, logregdata, poissonregdata\n\neye(p) = Matrix(1.0 * I, p, p)\n\ndefaultβ(p) = collect(range(-1, stop=1, length=p))\n\nfunction linregdata(n, p; β = defaultβ(p), V = eye(p), μ = zeros(p), σ = 1.0)\n\tx = rand(D.MvNormal(μ, V), n)'\n\ty = x * β + σ * randn(n)\n\treturn x, y, β\nend\n\nfunction logregdata(n, p, sgn = true; β = defaultβ(p), V = eye(p), μ = zeros(p))\n\tx = rand(D.MvNormal(μ, V), n)'\n\ty = Float64[rand(D.Bernoulli(1 / (1 + exp(-η)))) for η in x * β]\n\tif sgn\n\t\ty = 2y .- 1\n\tend\n\treturn x, y, β\nend\n\nfunction poissonregdata(n, p, β = defaultβ(p), V = eye(p), μ = zeros(p))\n\tx = rand(D.MvNormal(μ, V), n)'\n\ty = Float64[rand(D.Poisson(exp(η))) for η in x * β]\n\treturn x, y, β\nend\n\nend\n", "meta": {"hexsha": "2e31cc70154ee3744f3d20e2331340ae085d3718", "size": 781, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DataGenerator.jl", "max_stars_repo_name": "JuliaTagBot/DataGenerator.jl", "max_stars_repo_head_hexsha": "fd8b4ad0f82e166f048ffbfac9dfd11e1b014ade", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-15T02:57:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T04:21:34.000Z", "max_issues_repo_path": "src/DataGenerator.jl", "max_issues_repo_name": "JuliaTagBot/DataGenerator.jl", "max_issues_repo_head_hexsha": "fd8b4ad0f82e166f048ffbfac9dfd11e1b014ade", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-08-13T07:28:05.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-13T13:13:34.000Z", "max_forks_repo_path": "src/DataGenerator.jl", "max_forks_repo_name": "JuliaTagBot/DataGenerator.jl", "max_forks_repo_head_hexsha": "fd8b4ad0f82e166f048ffbfac9dfd11e1b014ade", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:05:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:05:40.000Z", "avg_line_length": 22.9705882353, "max_line_length": 80, "alphanum_fraction": 0.6133162612, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436404, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7876242572661969}}
{"text": "\"\"\" \n    randSphere(K::Int)\n    \nReturns a random K-vector from the unit sphere\n\"\"\"\nrandSphere(K::Int) = normalize(randn(K))\n\n\"Computes `γ` from `ρ`\"\ngammasoc(ρ::Float64) = sqrt(1 - ρ^2) / ρ\n\n\"Computes `ρ` from `γ`\"\nrhosoc(γ::Float64)   = 1/ sqrt(1 + γ^2)\n\n\"Computes `ϵ` from `μ` and `s^2`\"\nepssoc(μ::Float64, s2::Float64) = phi(μ/sqrt(1+s2))\n\n\"The cumulative function of the Normal distribution\"\nphi(x::Real) = cdf(Normal(), x)\n\n\"The density function of the Normal distribution\"\nG(x::Real) = pdf(Normal(), x)\n\n\"Returns the two modulation functions: Fw and Fϵ\"\nfunction modfunc(hσ1γ::Float64, μ1sqs2::Float64)\n    phiϵ = phi(μ1sqs2)\n    phiw = phi(hσ1γ)\n    Z    = phiϵ + phiw - 2*phiϵ*phiw\n    \n    Fw = (1 - 2phiϵ) * G(hσ1γ) / Z \n    Fϵ = (1 - 2phiw) * G(μ1sqs2) / Z\n\n    return (Fw, Fϵ)\nend\n", "meta": {"hexsha": "0245e8d17f39bd4c8760d5eab9e6d39847cdd5ed", "size": 794, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "kaslusimoes/SocialSystems.jl", "max_stars_repo_head_hexsha": "eb127e3fc82bc65fc66387f553ce33f47fc1c6a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2015-10-05T18:22:15.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-04T18:25:37.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "lssimoes/SocialSystems.jl", "max_issues_repo_head_hexsha": "eb127e3fc82bc65fc66387f553ce33f47fc1c6a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-10-27T22:44:56.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-27T22:44:56.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "lssimoes/SocialSystems.jl", "max_forks_repo_head_hexsha": "eb127e3fc82bc65fc66387f553ce33f47fc1c6a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2015-11-04T14:54:53.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-04T14:54:53.000Z", "avg_line_length": 23.3529411765, "max_line_length": 52, "alphanum_fraction": 0.6171284635, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874229, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7875850642506707}}
{"text": "# L0 pseudo-norm (times a constant)\n\nexport NormL0\n\n\"\"\"\n**``L_0`` pseudo-norm**\n\n    NormL0(λ=1)\n\nReturns the function\n```math\nf(x) = λ\\\\cdot\\\\mathrm{nnz}(x)\n```\nfor a nonnegative parameter `λ`.\n\"\"\"\nstruct NormL0{R <: Real} <: ProximableFunction\n    lambda::R\n    function NormL0{R}(lambda::R) where {R <: Real}\n        if lambda < 0\n            error(\"parameter λ must be nonnegative\")\n        else\n            new(lambda)\n        end\n    end\nend\n\nNormL0(lambda::R=1) where {R <: Real} = NormL0{R}(lambda)\n\nfunction (f::NormL0)(x::AbstractArray{T}) where {R, T <: RealOrComplex{R}}\n    return f.lambda * R(count(v -> v != 0, x))\nend\n\nfunction prox!(y::AbstractArray{T}, f::NormL0, x::AbstractArray{T}, gamma::Real=1) where {R, T <: RealOrComplex{R}}\n    countnzy = R(0)\n    gl = gamma * f.lambda\n    for i in eachindex(x)\n        over = abs(x[i]) > sqrt(2 * gl)\n        y[i] = over * x[i]\n        countnzy += over\n    end\n    return f.lambda * countnzy\nend\n\nfun_name(f::NormL0) = \"weighted L0 pseudo-norm\"\nfun_dom(f::NormL0) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::NormL0) = \"x ↦ λ countnz(x)\"\nfun_params(f::NormL0) = \"λ = $(f.lambda)\"\n\nfunction prox_naive(f::NormL0, x::AbstractArray{T}, gamma::Real=1) where {R, T <: RealOrComplex{R}}\n    over = abs.(x) .> sqrt(2 * gamma * f.lambda)\n    y = x.*over\n    return y, f.lambda * R(count(v -> v != 0, y))\nend\n", "meta": {"hexsha": "22750f29304b2da55e59994596f647e85cdef1b9", "size": 1377, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/normL0.jl", "max_stars_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_stars_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2016-10-29T12:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:11:52.000Z", "max_issues_repo_path": "src/functions/normL0.jl", "max_issues_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_issues_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2016-10-26T16:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T20:38:48.000Z", "max_forks_repo_path": "src/functions/normL0.jl", "max_forks_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_forks_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T10:40:24.000Z", "avg_line_length": 25.5, "max_line_length": 115, "alphanum_fraction": 0.5969498911, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8596637577007394, "lm_q1q2_score": 0.7875462348530199}}
{"text": "#! /usr/bin/julia\n\n# Rosetta Code, Fibonacci n-step number sequences\n\ntype NFib{T<:Integer}\n    n::T\n    klim::T\n    seeder::Function\nend\n\ntype FState\n    a::Array{BigInt,1}\n    adex::Integer\n    k::Integer\nend\n\nfunction Base.start{T<:Integer}(nf::NFib{T})\n    a = nf.seeder(nf.n)\n    adex = 1\n    k = 1\n    return FState(a, adex, k)\nend\n\nfunction Base.done{T<:Integer}(nf::NFib{T}, fs::FState)\n    fs.k > nf.klim\nend\n\nfunction Base.next{T<:Integer}(nf::NFib{T}, fs::FState)\n    f = sum(fs.a)\n    fs.a[fs.adex] = f\n    fs.adex = rem1(fs.adex+1, nf.n)\n    fs.k += 1\n    return (f, fs)\nend\n\nfunction fib_seeder{T<:Integer}(n::T)\n    a = zeros(BigInt, n)\n    a[1] = one(BigInt)\n    return a\nend\n\nfunction fib{T<:Integer}(n::T, k::T)\n    NFib(n, k, fib_seeder)\nend\n\nfunction luc_rc_seeder{T<:Integer}(n::T)\n    a = zeros(BigInt, n)\n    a[1] = 3\n    a[2] = -1\n    return a\nend\n\nfunction luc_rc{T<:Integer}(n::T, k::T)\n    NFib(n, k, luc_rc_seeder)\nend\n\nfunction luc_seeder{T<:Integer}(n::T)\n    a = -ones(BigInt, n)\n    a[end] = big(n)\n    return a\nend\n\nfunction luc{T<:Integer}(n::T, k::T)\n    NFib(n, k, luc_seeder)\nend\n\nlo = 2\nhi = 10\nklim = 16\n\nprint(\"n-step Fibonacci for n = (\", lo, \",\", hi)\nprintln(\") up to k = \", klim, \":\")\nfor i in 2:10\n    print(@sprintf(\"%5d => \", i))\n    for j in fib(i, klim)\n        print(j, \" \")\n    end\n    println()\nend\n\nprintln()\nprint(\"n-step Rosetta Code Lucas for n = (\", lo, \",\", hi)\nprintln(\") up to k = \", klim, \":\")\nfor i in 2:10\n    print(@sprintf(\"%5d => \", i))\n    for j in luc_rc(i, klim)\n        print(j, \" \")\n    end\n    println()\nend\n\nprintln()\nprint(\"n-step MathWorld Lucas for n = (\", lo, \",\", hi)\nprintln(\") up to k = \", klim, \":\")\nfor i in 2:10\n    print(@sprintf(\"%5d => \", i))\n    for j in luc(i, klim)\n        print(j, \" \")\n    end\n    println()\nend\n", "meta": {"hexsha": "c31a3fa5147744de505d52576c605ab0decd6dbc", "size": 1802, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/completed/fibonacci_n_seq.jl", "max_stars_repo_name": "MichaeLeroy/rosetta-code", "max_stars_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/completed/fibonacci_n_seq.jl", "max_issues_repo_name": "MichaeLeroy/rosetta-code", "max_issues_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/completed/fibonacci_n_seq.jl", "max_forks_repo_name": "MichaeLeroy/rosetta-code", "max_forks_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.6666666667, "max_line_length": 57, "alphanum_fraction": 0.5577136515, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7875462295902623}}
{"text": "# # Comparison with MathOptInterface on a Probability Simplex\n\n# In this example, we project a random point onto a probability simplex with the Frank-Wolfe algorithm using\n# either the specialized LMO defined in the package or a generic LP formulation using `MathOptInterface.jl` (MOI) and\n# `GLPK` as underlying LP solver.\n# It can be found as Example 4.4 [in the paper](https://arxiv.org/abs/2104.06675).\n\nusing FrankWolfe\n\nusing LinearAlgebra\nusing LaTeXStrings\n\nusing Plots\n\nusing JuMP\nconst MOI = JuMP.MOI\n\nimport GLPK\n\nn = Int(1e3)\nk = 10000\n\nxpi = rand(n);\ntotal = sum(xpi);\nconst xp = xpi ./ total;\n\nf(x) = norm(x - xp)^2\nfunction grad!(storage, x)\n    @. storage = 2 * (x - xp)\n    return nothing\nend\n\nlmo_radius = 2.5\nlmo = FrankWolfe.FrankWolfe.ProbabilitySimplexOracle(lmo_radius)\n\nx00 = FrankWolfe.compute_extreme_point(lmo, zeros(n))\ngradient = collect(x00)\n\nx_lmo, v, primal, dual_gap, trajectory_lmo = FrankWolfe.frank_wolfe(\n    f,\n    grad!,\n    lmo,\n    collect(copy(x00)),\n    max_iteration=k,\n    line_search=FrankWolfe.Shortstep(),\n    L=2,\n    print_iter=k / 10,\n    emphasis=FrankWolfe.memory,\n    verbose=false,\n    trajectory=true,\n);\n\n# Create a MathOptInterface Optimizer and build the same linear constraints:\n\no = GLPK.Optimizer()\nx = MOI.add_variables(o, n)\n\nfor xi in x\n    MOI.add_constraint(o, xi, MOI.GreaterThan(0.0))\nend\n\nMOI.add_constraint(\n    o,\n    MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(1.0, x), 0.0),\n    MOI.EqualTo(lmo_radius),\n)\n\nlmo_moi = FrankWolfe.MathOptLMO(o)\n\nx, v, primal, dual_gap, trajectory_moi = FrankWolfe.frank_wolfe(\n    f,\n    grad!,\n    lmo_moi,\n    collect(copy(x00)),\n    max_iteration=k,\n    line_search=FrankWolfe.Shortstep(),\n    L=2,\n    print_iter=k / 10,\n    emphasis=FrankWolfe.memory,\n    verbose=false,\n    trajectory=true,\n);\n\n# Alternatively, we can use one of the modelling interfaces based on `MOI` to formulate the LP.\n# The following example builds the same set of constraints using `JuMP`:\n\nm = JuMP.Model(GLPK.Optimizer)\n@variable(m, y[1:n] ≥ 0)\n\n@constraint(m, sum(y) == lmo_radius)\n\nlmo_jump = FrankWolfe.MathOptLMO(m.moi_backend)\n\nx, v, primal, dual_gap, trajectory_jump = FrankWolfe.frank_wolfe(\n    f,\n    grad!,\n    lmo_jump,\n    collect(copy(x00)),\n    max_iteration=k,\n    line_search=FrankWolfe.Shortstep(),\n    L=2,\n    print_iter=k / 10,\n    emphasis=FrankWolfe.memory,\n    verbose=false,\n    trajectory=true,\n);\n\nx_lmo, v, primal, dual_gap, trajectory_lmo_blas = FrankWolfe.frank_wolfe(\n    f,\n    grad!,\n    lmo,\n    x00,\n    max_iteration=k,\n    line_search=FrankWolfe.Shortstep(),\n    L=2,\n    print_iter=k / 10,\n    emphasis=FrankWolfe.blas,\n    verbose=false,\n    trajectory=true,\n);\n\nx, v, primal, dual_gap, trajectory_jump_blas = FrankWolfe.frank_wolfe(\n    f,\n    grad!,\n    lmo_jump,\n    x00,\n    max_iteration=k,\n    line_search=FrankWolfe.Shortstep(),\n    L=2,\n    print_iter=k / 10,\n    emphasis=FrankWolfe.blas,\n    verbose=false,\n    trajectory=true,\n);\n\n\niteration_list = [[x[1] + 1 for x in trajectory_lmo], [x[1] + 1 for x in trajectory_moi]]\ntime_list = [[x[5] for x in trajectory_lmo], [x[5] for x in trajectory_moi]]\nprimal_gap_list = [[x[2] for x in trajectory_lmo], [x[2] for x in trajectory_moi]]\ndual_gap_list = [[x[4] for x in trajectory_lmo], [x[4] for x in trajectory_moi]]\n\nlabel = [L\"\\textrm{Closed-form LMO}\", L\"\\textrm{MOI LMO}\"]\n\nFrankWolfe.plot_results(\n    [primal_gap_list, primal_gap_list, dual_gap_list, dual_gap_list],\n    [iteration_list, time_list, iteration_list, time_list],\n    label,\n    [\"\", \"\", L\"\\textrm{Iteration}\", L\"\\textrm{Time}\"],\n    [L\"\\textrm{Primal Gap}\", \"\", L\"\\textrm{Dual Gap}\", \"\"],\n    xscalelog=[:log, :identity, :log, :identity],\n    yscalelog=[:log, :log, :log, :log],\n    legend_position=[:bottomleft, nothing, nothing, nothing]\n)\n", "meta": {"hexsha": "4b40e832bcf88edbc45b8df06ac98a83296c829c", "size": 3797, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/docs_1_mathopt_lmo.jl", "max_stars_repo_name": "gdalle/FrankWolfe.jl-2", "max_stars_repo_head_hexsha": "c3b3903c4808e24aa9e0f655aa2f8de0f2c1571c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2021-03-27T15:50:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T15:11:21.000Z", "max_issues_repo_path": "examples/docs_1_mathopt_lmo.jl", "max_issues_repo_name": "gdalle/FrankWolfe.jl-2", "max_issues_repo_head_hexsha": "c3b3903c4808e24aa9e0f655aa2f8de0f2c1571c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 132, "max_issues_repo_issues_event_min_datetime": "2021-03-29T18:49:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T01:33:22.000Z", "max_forks_repo_path": "docs/src/examples/1_mathopt_lmo.jl", "max_forks_repo_name": "dviladrich95/FrankWolfe.jl", "max_forks_repo_head_hexsha": "bcb441e52918bd1103f13296082cd7a8bc22607b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-06-02T13:38:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T10:04:42.000Z", "avg_line_length": 24.6558441558, "max_line_length": 117, "alphanum_fraction": 0.6850144851, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.7875462262964714}}
{"text": "# mathematical constants related to statistics\n\n@irrational twoπ   6.2831853071795864769 big(π) * 2.0\n@irrational fourπ  12.566370614359172954 big(π) * 4.0\n@irrational halfπ  1.5707963267948966192 big(π) * 0.5\n@irrational quartπ 0.7853981633974483096 big(π) * 0.25\n\n@irrational invπ     0.31830988618379067154 inv(big(π))\n@irrational twoinvπ  0.63661977236758134308 big(invπ) * 2.0\n@irrational fourinvπ 1.27323954473516268615 big(invπ) * 4.0\n@irrational inv2π    0.159154943091895335769 big(invπ) * 0.5\n@irrational inv4π    0.079577471545947667884 big(invπ) * 0.25\n\n@irrational sqrt2     1.4142135623730950488 sqrt(big(2.0))\n@irrational sqrt3     1.7320508075688772935 sqrt(big(3.0))\n@irrational sqrtπ     1.7724538509055160273 sqrt(big(π))\n@irrational sqrt2π    2.5066282746310005024 sqrt(big(π) * 2.0)\n@irrational sqrt4π    3.5449077018110320546 sqrt(big(π) * 4.0)\n@irrational sqrthalfπ 1.2533141373155002512 sqrt(big(0.5)*π)\n\n@irrational invsqrt2  0.7071067811865475244 inv(big(sqrt2))\n@irrational invsqrt2π 0.3989422804014326779 inv(big(sqrt2π))\n", "meta": {"hexsha": "6688dfaa486bdf330ce415efbbc381e13813aca0", "size": 1050, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/constants.jl", "max_stars_repo_name": "blackeneth/StatsFuns.jl", "max_stars_repo_head_hexsha": "f9fa86bdd76e36944f17d9c8954e67a9ccf95a6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/constants.jl", "max_issues_repo_name": "blackeneth/StatsFuns.jl", "max_issues_repo_head_hexsha": "f9fa86bdd76e36944f17d9c8954e67a9ccf95a6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/constants.jl", "max_forks_repo_name": "blackeneth/StatsFuns.jl", "max_forks_repo_head_hexsha": "f9fa86bdd76e36944f17d9c8954e67a9ccf95a6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.652173913, "max_line_length": 62, "alphanum_fraction": 0.7685714286, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96323053709097, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.787512710378819}}
{"text": "# 1D diffusion problem\n\n# TODO: Add more complex tests.\n\n# Packages and inclusions\nusing ModelingToolkit,DiffEqOperators,DiffEqBase,LinearAlgebra,Test\n\n# Tests\n@testset \"Test 00: Dt(u(t,x)) ~ Dxx(u(t,x))\" begin\n    # Parameters, variables, and derivatives\n    @parameters t x\n    @variables u(..)\n    @derivatives Dt'~t\n    @derivatives Dxx''~x\n\n    # 1D PDE and boundary conditions\n    eq  = Dt(u(t,x)) ~ Dxx(u(t,x))\n    bcs = [u(0,x) ~ -x*(x-1)*sin(x),\n           u(t,0) ~ 0.0,\n           u(t,1) ~ 0.0]\n\n    # Space and time domains\n    domains = [t ∈ IntervalDomain(0.0,1.0),\n               x ∈ IntervalDomain(0.0,1.0)]\n\n    # PDE system\n    pdesys = PDESystem(eq,bcs,domains,[t,x],[u])\n\n    # Method of lines discretization\n    dx = 0.1\n    order = 2\n    discretization = MOLFiniteDifference(dx,order)\n\n    # Convert the PDE problem into an ODE problem\n    prob = discretize(pdesys,discretization)\n\n    # Solve ODE problem\n    using OrdinaryDiffEq\n    sol = solve(prob,Tsit5(),saveat=0.1)\n\n    #Plot and save results\n    # using Plots\n    # plot(prob.space[2],Array(prob.extrapolation[1]*sol[:,1,1]))\n    # plot!(prob.space[2],Array(prob.extrapolation[1]*sol[:,1,2]))\n    # plot!(prob.space[2],Array(prob.extrapolation[1]*sol[:,1,3]))\n    # plot!(prob.space[2],Array(prob.extrapolation[1]*sol[:,1,4]))\n    # savefig(\"MOL_1D_Linear_Diffusion_Test00.png\")\n\n    # Test\n    n = size(sol,1)\n    t_f = size(sol,3)\n\n    @test sol[:,1,t_f] ≈ zeros(n) atol = 0.001;\nend\n\n@testset \"Test 01: Dt(u(t,x)) ~ D*Dxx(u(t,x))\" begin\n    # Parameters, variables, and derivatives\n    @parameters t x D\n    @variables u(..)\n    @derivatives Dt'~t\n    @derivatives Dxx''~x\n\n    D = 1.1\n\n    # 1D PDE and boundary conditions\n    eq  = Dt(u(t,x)) ~ D*Dxx(u(t,x))\n    bcs = [u(0,x) ~ -x*(x-1)*sin(x),\n           u(t,0) ~ 0.0,\n           u(t,1) ~ 0.0]\n\n    # Space and time domains\n    domains = [t ∈ IntervalDomain(0.0,1.0),\n               x ∈ IntervalDomain(0.0,1.0)]\n\n    # PDE system\n    pdesys = PDESystem(eq,bcs,domains,[t,x,D],[u])\n\n    # Method of lines discretization\n    dx = 0.1\n    order = 2\n    discretization = MOLFiniteDifference(dx,order)\n\n    # Convert the PDE problem into an ODE problem\n    prob = discretize(pdesys,discretization)\n\n    # Solve ODE problem\n    using OrdinaryDiffEq\n    sol = solve(prob,Tsit5(),saveat=0.1)\n\n    # Plot and save results\n    # using Plots\n    # plot(prob.space[2],Array(prob.extrapolation[1]*sol[:,1,1]))\n    # plot!(prob.space[2],Array(prob.extrapolation[1]*sol[:,1,2]))\n    # plot!(prob.space[2],Array(prob.extrapolation[1]*sol[:,1,3]))\n    # plot!(prob.space[2],Array(prob.extrapolation[1]*sol[:,1,4]))\n    # savefig(\"MOL_1D_Linear_Diffusion_Test01.png\")\n\n    # Test\n    n = size(sol,1)\n    t_f = size(sol,3)\n    @test sol[:,1,t_f] ≈ zeros(n) atol = 0.001;\nend\n\n@testset \"Test 02: Dt(u(t,x)) ~ Dx(D(t,x))*Dx(u(t,x))+D(t,x)*Dxx(u(t,x))\" begin\n    # Parameters, variables, and derivatives\n    @parameters t x\n    @variables u(..) D(..)\n    @derivatives Dt'~t\n    @derivatives Dx'~x\n    @derivatives Dxx''~x\n\n    # 1D PDE and boundary conditions\n\n    eq  = [ Dt(u(t,x)) ~ Dx(D(t,x))*Dx(u(t,x))+D(t,x)*Dxx(u(t,x)),\n            D(t,x) ~ 0.999 + 0.001 * t * x  ]\n\n    bcs = [u(0,x) ~ -x*(x-1)*sin(x),\n           u(t,0) ~ 0.0,\n           u(t,1) ~ 0.0,\n           D(0,x) ~ 0.999,\n           D(t,0) ~ 0.999,\n           D(t,1) ~ 0.999 + 0.001 * t ]\n\n    # Space and time domains\n    domains = [t ∈ IntervalDomain(0.0,1.0),\n               x ∈ IntervalDomain(0.0,1.0)]\n\n    # PDE system\n    pdesys = PDESystem(eq,bcs,domains,[t,x],[u,D])\n\n    # Method of lines discretization\n    dx = 0.1\n    order = 2\n    discretization = MOLFiniteDifference(dx,order)\n\n    # Convert the PDE problem into an ODE problem\n    prob = discretize(pdesys,discretization)\n\n    # Solve ODE problem\n    using OrdinaryDiffEq\n    sol = solve(prob,Tsit5(),saveat=0.1)\n    \n    # Plot and save results\n    # using Plots\n    # plot(prob.space[2],Array(prob.extrapolation[1]*sol[:,1,1]))\n    # plot!(prob.space[2],Array(prob.extrapolation[1]*sol[:,1,2]))\n    # plot!(prob.space[2],Array(prob.extrapolation[1]*sol[:,1,3]))\n    # plot!(prob.space[2],Array(prob.extrapolation[1]*sol[:,1,4]))\n    # savefig(\"MOL_1D_Linear_Diffusion_Test02.png\")\n\n    # Test\n    n = size(sol,1)\n    t_f = size(sol,3)\n    @test sol[:,1,t_f] ≈ zeros(n) atol = 0.1;\nend\n", "meta": {"hexsha": "19b720e2f36945c00871d6e99b9f51855dd06b69", "size": 4334, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/MOL_1D_Linear_Diffusion.jl", "max_stars_repo_name": "mindlike/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "f9dc4c1888341c6fde162f647b90763d7f2d69c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/MOL_1D_Linear_Diffusion.jl", "max_issues_repo_name": "mindlike/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "f9dc4c1888341c6fde162f647b90763d7f2d69c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/MOL_1D_Linear_Diffusion.jl", "max_forks_repo_name": "mindlike/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "f9dc4c1888341c6fde162f647b90763d7f2d69c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7820512821, "max_line_length": 79, "alphanum_fraction": 0.5839870789, "num_tokens": 1534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100816, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.7874873364087388}}
{"text": "#############################################################################\n#############################################################################\n#\n# This file implements polynomial division \n#                                                                               \n#############################################################################\n#############################################################################\n\n\"\"\"  Modular algorithm.\nf divide by g\n\nf = q*g + r\n\np is a prime\n\"\"\"\n\nfunction divide(num::Polynomial, den::Polynomial)\n    function division_function(p::Int)\n        f, g = mod(num,p), mod(den,p)\n        degree(f) < degree(num) && return nothing \n        iszero(g) && throw(DivideError())\n        q = Polynomial()\n        prev_degree = degree(f)\n        while degree(f) ≥ degree(g) \n            h = Polynomial( (leading(f) ÷ leading(g))(p) )  #syzergy \n            f = mod((f - h*g), p)\n            q = mod((q + h), p)  \n            prev_degree == degree(f) && break\n            prev_degree = degree(f)\n        end\n        \n        @assert iszero( mod((num  - (q*g + f)),p))\n        return q, f\n    end\n    return division_function\nend \n\nfunction divide(num::PolynomialModP, den::PolynomialModP)\n    p = num.mod\n    @assert num.mod == den.mod\n    f, g = num, den\n    if degree(g) > degree(f)\n        output =  [zero(PolynomialModP,p) , f]\n        return output\n    end\n\n    iszero(g) && throw(DivideError())\n    iszero(f) && return zero(PolynomialModP,p), zero(PolynomialModP,p)\n    \n\n    q = PolynomialModP(f.mod)\n    prev_degree = degree(f)\n    while degree(f) ≥ degree(g) \n        h = (leading(f) ÷ leading(g))(p) #syzergy \n        hg = - h*g\n        f = f+hg\n        q = q+h\n        prev_degree == degree(f) && break\n        prev_degree = degree(f)\n    end\n\n    @assert iszero(num - (q*g + f))\n    \n    return q,f \nend\n\n\n\"\"\"\nThe quotient from polynomial division. Returns a function of an integer.\n\"\"\"\n÷(num::Polynomial, den::Polynomial)  = (p::Int) -> first(divide(num,den)(p)) \n÷(num::PolynomialModP, den::PolynomialModP) = first(divide(num,den))\n\n\"\"\"\nThe remainder from polynomial division. Returns a function of an integer.\n\"\"\"\nrem(num::Polynomial, den::Polynomial)  = (p::Int) -> last(divide(num,den)(p))\nrem(num::PolynomialModP, den::PolynomialModP)  = last(divide(num,den))", "meta": {"hexsha": "c38b3630b27c951fd0c650556d49a7489fa14539", "size": 2325, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basic_polynomial_operations/polynomial_division.jl", "max_stars_repo_name": "Talis0/2504_2021_project1", "max_stars_repo_head_hexsha": "c2c73a74e5b909b404ea8ed8ee42e1cddeacbb2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basic_polynomial_operations/polynomial_division.jl", "max_issues_repo_name": "Talis0/2504_2021_project1", "max_issues_repo_head_hexsha": "c2c73a74e5b909b404ea8ed8ee42e1cddeacbb2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basic_polynomial_operations/polynomial_division.jl", "max_forks_repo_name": "Talis0/2504_2021_project1", "max_forks_repo_head_hexsha": "c2c73a74e5b909b404ea8ed8ee42e1cddeacbb2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8076923077, "max_line_length": 80, "alphanum_fraction": 0.4787096774, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065459, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.787487333749011}}
{"text": "using Symata\n\n@sym begin\n  ClearAll(f, y0, a, l, x)\n  y0(x_) := (e*x)*(l^3 - 2*l*x^2 + x^3)\n  \n  # Stodola-Vianello method, e.g. see Den Hartog, Advanced Strength of Materials, pg 268\n  f(maxiters_, y0_) := Module([i, yder, res=ConstantArray(0.0,[maxiters,6])],\n    (\n      # Initialize the first row of the res matrix\n      res[1,2] = y0(x),\n      For(i=1, i<=4, Increment(i),\n        [\n          yder(x_) = Simplify(D(y0, x, i))\n          res[1, 2+i] = yder(x)\n        ]\n      ),\n      Println(\"N[res[1, 1]]: \", res[1,1]),\n      # Start the loop to improve accuracy stored in subsequent rows,\n      # res[i, 1] contains the Euler ratio.\n      For(i=2, i<=maxiters, Increment(i),\n        begin\n          res[i, 6] = Simplify(w/(EI)*((x-l)*res[i-1,4] + res[i-1,3]))\n          # Above the basic Euler equation for a pinned-pinned flagpole\n          ClearAll(K1, K11, tmpy5, tmpy4, tmp)\n          tmpy5(x_) = Simplify(Integrate(res[i,6], x) + K1)\n          tmpy4(x_) = Simplify(Integrate(tmpy5(x), x))\n          # Use first pinned constraint at x=l to resolve K1\n          K11 = Solve(-tmpy4(l), K1)[1]\n          res[i,5] = Simplify( tmpy5(x) ./ K11 )\n          res[i,4] = Simplify( tmpy4(x) ./ K11 )\n          ClearAll(K2, K22, tmpy3, tmpy2, tmp)\n          tmpy3(x_) = Simplify(Integrate(res[i,4], x) + K2)\n          tmpy2(x_) = Simplify(Integrate(tmpy3(x), x))\n          # Use second pinned constraint at x=l to resolve K2\n          K22 = Solve(-tmpy2(l), K2)[1]\n          res[i,3] = Simplify( tmpy3(x) ./ K22 )\n          res[i,2] = Simplify( tmpy2(x) ./ K22 )\n          tmp = Simplify( (((l^3)*w)/EI)*(res[i-1,3]/res[i, 3]) )\n          res[i,1] = N(Simplify(ReplaceAll(tmp, x => l)))\n          Println(\"N[res[$i, 1]]: \", N(res[i,1], 4))\n        end\n      ),\n      Println(),\n      Return(res)\n    )\n  )\n\n  r = f(8, y0(x))\n  Println(N(Transpose(r)[1], 4))\nend\n", "meta": {"hexsha": "4a7c2f3052f7594d2d080473723d7790214017e2", "size": 1860, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/vianello_symata.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "test/vianello_symata.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "test/vianello_symata.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 35.7692307692, "max_line_length": 88, "alphanum_fraction": 0.5172043011, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7874488576613585}}
{"text": "module FirstOrder\n\nusing LinearAlgebra\n\nimport ..LocalDescent:\nsearch,\nLineSearch, StrongBacktracking\n\nstruct Termination\n    max_iter\n    ϵ_abs\n    ϵ_rel\n    ϵ_grad\n    Termination(;\n        max_iter = 10_000,\n        ϵ_abs = eps(),\n        ϵ_rel = eps(),\n        ϵ_grad = eps()) =\n        new(max_iter, ϵ_abs, ϵ_rel, ϵ_grad)\n    Termination(ϵ;\n        max_iter = 10_000) =\n        new(max_iter, ϵ, ϵ, ϵ)\nend\n\nmutable struct TerminationConditions\n    abs\n    rel\n    grad\n    TerminationConditions(term::Termination) = \n    new((fx, fx_next)->fx - fx_next < term.ϵ_abs,\n        (fx, fx_next)->fx - fx_next < term.ϵ_abs * abs(fx),\n        ∇fx_next->norm(∇fx_next) < term.ϵ_grad)\nend\n\nfunction descent_until(term::Termination, descent_method, f, ∇f, X, trace)\n    term_cond = TerminationConditions(term)\n    for _ = 1:term.max_iter\n        x = X[:, end]\n        x_next = descent_method(f, ∇f, x)\n        if trace\n            X = hcat(X, x_next)\n        else\n            X = x_next\n        end\n        fx, fx_next, ∇fx_next = f(x), f(x_next), ∇f(x_next)\n        if term_cond.abs(fx, fx_next) ||\n            term_cond.rel(fx, fx_next) ||\n            term_cond.grad(∇fx_next)\n            return X\n        end\n    end\n    @warn \"descent_until: max number of iterations reached\"\n    X\nend\n\nabstract type FirstOrderMethods end\n\n# Maximum Gradient Descent\n\nstruct MaximumGradientDescent <: FirstOrderMethods end\n\nfunction search(::MaximumGradientDescent, f, ∇f, x_0; term = Termination(), trace = false)\n    descent_until(term, descent_step_maxgd, f, ∇f, x_0, trace)\nend\n\nfunction descent_step_maxgd(f, ∇f, x)\n    \"\"\"\n    Maximum Gradient Descent\n\n    A step of maximum gradient descent produces the value of x(k+1)\n    where f(x) in the direction of maximum descent is at its local\n    minimum.\n    \"\"\"\n    g = ∇f(x)\n    d = direction_maxgd(g)\n    search(LineSearch(), f, x, d)\nend\n\nfunction direction_maxgd(g)\n    -g / norm(g)\nend\n\n# Gradient Descent\n\nstruct GradientDescent <: FirstOrderMethods\n    α\n    GradientDescent(; α = 0.001) = new(α)\nend\n\nfunction search(params::GradientDescent, f, ∇f, x_0; term = Termination(), trace = false)\n    descent_step = (f, ∇f, x)->descent_step_gd(params.α, f, ∇f, x)\n    descent_until(term, descent_step, f, ∇f, x_0, trace)\nend\n\nfunction descent_step_gd(α, f, ∇f, x)\n    \"\"\"\n    Gradient Descent\n    Algorithm 5.1\n\n    A step of a gradient descent algorithm with fixed learning rate α.\n    \"\"\"\n    g = ∇f(x)\n    x - α * g\nend\n\n# Conjugate Gradient Descent\n\nstruct ConjugateGradientDescent <: FirstOrderMethods end\n\nmutable struct CGDProblemState\n    g\n    d\n    CGDProblemState(dim) = new(ones(dim), zeros(dim))\nend\n\nfunction search(params::ConjugateGradientDescent, f, ∇f, x_0; term = Termination(), trace = false)\n    state = CGDProblemState(size(x_0))\n    descent_step = (f, ∇f, x)->descent_step_cgd!(state, f, ∇f, x)\n    descent_until(term, descent_step, f, ∇f, x_0, trace)\nend\n\nfunction descent_step_cgd!(state, f, ∇f, x)\n    \"\"\"\n    Conjugate Gradient Descent\n    Algorithm 5.2\n\n    https://en.wikipedia.org/wiki/Nonlinear_conjugate_gradient_method\n    \"\"\"\n    g = ∇f(x)\n    d = direction_cgd(g, state.g, state.d)\n    state.g = g\n    state.d = d\n    search(StrongBacktracking(), f, ∇f, x, d)\nend\n\nfunction direction_cgd(g, gm1, dm1)\n    \"\"\"\n    Polak-Ribiere update\n    Notation:\n        g is for g(k)\n        dm1 is for d(k-1)\n        gm1 indicates g(k-1)\n    \"\"\"\n    β_PR = (g' * (g - gm1)) / (gm1'gm1)\n    β = max(β_PR, 0)\n    -g + β * dm1\nend\n\nend # module\n", "meta": {"hexsha": "00491806d01b0cc144c3c1a6b05b6a4af17ec563", "size": 3500, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FirstOrder.jl", "max_stars_repo_name": "gshaikov/Algopt.jl", "max_stars_repo_head_hexsha": "0fced0ae1963b68cf1c6118ab03e6eb6ccc0e6c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FirstOrder.jl", "max_issues_repo_name": "gshaikov/Algopt.jl", "max_issues_repo_head_hexsha": "0fced0ae1963b68cf1c6118ab03e6eb6ccc0e6c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FirstOrder.jl", "max_forks_repo_name": "gshaikov/Algopt.jl", "max_forks_repo_head_hexsha": "0fced0ae1963b68cf1c6118ab03e6eb6ccc0e6c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3333333333, "max_line_length": 98, "alphanum_fraction": 0.6268571429, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697695, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7874488522643945}}
{"text": "include(\"kruskal.jl\")\n\n\"\"\"\n    count_spanning_trees(g::AGraph)\n\nReturns the number of spanning trees of `g`, computed through\n[Kirchhoff's theorem](https://en.wikipedia.org/wiki/Kirchhoff%27s_theorem).\nThe return type is a float, since the number can be very large.\n\"\"\"\nfunction count_spanning_trees(g::AGraph)\n    @assert is_connected(g) \"The graph has to be connected\"\n    nv(g) <= 1 && return 1.\n    Δ = laplacian_matrix(g)[2:nv(g),2:nv(g)]\n    return round(det(Δ))\nend\n", "meta": {"hexsha": "b0528dfe77ad1a327c656bc96cb5b6651b618639", "size": 473, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spanningtrees/spanningtrees.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Erdos.jl-90d7349d-81aa-5495-813a-883243abfe31", "max_stars_repo_head_hexsha": "2eb248772a05eac35823a07373dd5644913c6dbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2017-02-24T15:54:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T19:59:23.000Z", "max_issues_repo_path": "src/spanningtrees/spanningtrees.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Erdos.jl-90d7349d-81aa-5495-813a-883243abfe31", "max_issues_repo_head_hexsha": "2eb248772a05eac35823a07373dd5644913c6dbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 76, "max_issues_repo_issues_event_min_datetime": "2017-02-23T09:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T09:10:31.000Z", "max_forks_repo_path": "src/spanningtrees/spanningtrees.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Erdos.jl-90d7349d-81aa-5495-813a-883243abfe31", "max_forks_repo_head_hexsha": "2eb248772a05eac35823a07373dd5644913c6dbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-03-04T21:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:54:44.000Z", "avg_line_length": 29.5625, "max_line_length": 75, "alphanum_fraction": 0.7061310782, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9425067179697695, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.787448840681874}}
{"text": "\"\"\"\n    gpw(ζ, φ; k=1)\n    \nClosure that defines a generalized plane wave in polar coordinates.\n\nThe closure captures the values of the evanescence parameter ``ζ``, the\nangle ``φ`` and the wavenumber ``k``.\nIt does not include any normalization.\nThe function can then be evaluated at any ``(r,θ)`` point.\n\nThe generalized plane wave in polar coordinates is defined by\n```math\nϕ := (r,θ) ↦ e^{ı k \\\\mathbf{d} ⋅ \\\\mathbf{x}},\n```\nwhere\n```math\n\\\\mathbf{d} = (\\\\cos[φ+ıζ], \\\\sin[φ+ıζ]),\n\\\\qquad\\\\text{and}\\\\qquad\n\\\\mathbf{x} = (r \\\\cos θ, r\\\\sin θ).\n```\n\"\"\"\nfunction gpw(ζ,φ;k=1)\n    d = [cos(φ+im*ζ), sin(φ+im*ζ)] # Direction\n    return (r,θ) -> exp(im * k * [r*cos(θ), r*sin(θ)] ⋅ d)\nend\n\n\"\"\"\n    approximation_set(Y, W; k=1)\n    \nGenerate a set of generalized plane waves.\n\nThe parameters `Y` and `W` are respectively the sets of complex angles\n``(ζ_j,φ_j)`` and associated weights ``ω_j`` corresponding to the generalized\nplane waves, see [`gpw`](@ref)\n```math\nϕ_j := (r,θ) ↦ e^{ı k \\\\mathbf{d}_j ⋅ \\\\mathbf{x}},\n```\nwhere\n```math\n\\\\mathbf{d}_j = (\\\\cos[φ_j+ıζ_j], \\\\sin[φ_j+ıζ_j]),\n\\\\qquad\\\\text{and}\\\\qquad\n\\\\mathbf{x} = (r \\\\cos θ, r\\\\sin θ).\n```\nApproximations are constructed in the form of\n```math\n(r, θ) ↦ \\\\sum_j ξ_j ω_j ϕ_j(r, θ),\n```\nwhere ``(ξ_j)_j`` is the set of unknown coefficients.\n\nThe value of the wavenumber `k` defaults to ``1`` and can be provided as an\noptional parameter.\n\"\"\"\nfunction approximation_set(Y, W; k=1)\n    @assert length(Y) == length(W)\n    return [(r, θ) -> w * gpw(y...;k=k)(r, θ) for (y, w) in zip(Y, W)]\nend\n\n\"\"\"\n    approximation_set(N; k=1)\n    \nGenerate a set of ``N`` propagative plane waves with equispaced angles.\n\nThe equispaced angles are defined by\n```math\nθ_n := 2π s / R, \\\\qquad n = 0,…,N-1.\n```\n\nThe value of the wavenumber `k` defaults to ``1`` and can be provided as an\noptional parameter.\n\"\"\"\nfunction approximation_set(N; k=1)\n    Y = [(0, 2π * n / N) for n in 0:N-1]\n    W = ones(Int64, N) ./ sqrt(N)\n    return approximation_set(Y, W; k=k)\nend\n\n\"\"\"\n    approximation_set(N, qs, smpl_type; k=1)\n    approximation_set(N, Q::Integer, smpl_type; k=1)\n    \nGenerate a set of ``N`` evanescent plane waves according to some sampling type.\n\nThe second parameter can be an integer ``Q`` which controls the truncation\nparameter of the [`TruncKernel`](@ref), or a set of integers `qs` to specify\nonly some specific terms in the expansion.\nThe parameter `smpl_type` should be a function name: see\n[`uniform_sampling`](@ref), [`sobol_sampling`](@ref) and\n[`random_sampling`](@ref).\n\nThe value of the wavenumber `k` defaults to ``1`` and can be provided as an\noptional parameter.\n\"\"\"\nfunction approximation_set(N, qs, smpl_type; k=1)\n    K = TruncKernel(Tuple(qs), logwz(;k=k));\n    smpl = Sampler(K)\n    Y, W = smpl_type(smpl, N)\n    W ./= sqrt(N)\n    return approximation_set(Y, W; k=k)\nend\nfunction approximation_set(N, Q::Int64, smpl_type; k=1)\n    return approximation_set(N, -Q:Q, smpl_type; k=k)\nend", "meta": {"hexsha": "cebc85b866b7314cebf22cacf0b90e416f0564ca", "size": 2951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/plane-waves.jl", "max_stars_repo_name": "EmileParolin/STrAW", "max_stars_repo_head_hexsha": "beea3b830a66d1fad257e455fba06bb8614b1abb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/plane-waves.jl", "max_issues_repo_name": "EmileParolin/STrAW", "max_issues_repo_head_hexsha": "beea3b830a66d1fad257e455fba06bb8614b1abb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plane-waves.jl", "max_forks_repo_name": "EmileParolin/STrAW", "max_forks_repo_head_hexsha": "beea3b830a66d1fad257e455fba06bb8614b1abb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.931372549, "max_line_length": 79, "alphanum_fraction": 0.6489325652, "num_tokens": 991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092412, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7874091743021505}}
{"text": "# # Geometry \n\n# The `WaveProp.Geometry` module handles everything related to the geometrical\n# descriptions of curves/surfaces. Its main interface is exposed through\n# `AbstractElement`, which represents an `M`-dimensional geometical object\n# embedded in ℝᴺ. In abstract terms, an *element* τ is a subset of ℝᴺ described\n# by \n# * a reference element ``\\tau \\subset \\mathbb{R}^N``\n# * a *push-forward map* χ : τ̂ → τ ⊂ ℝᴺ.\n\n# Concrete implementations of `AbstractElement`s are responsible for\n# implementing a few crucial methods used to derive almost all functionality of\n# an `el::AbstractElement` used throughout this package. In the [next section](#interface) we\n# describe this interface.\n\n# ## Interface<a id='interface'></a>\n\n# The interface is composed of the following methods:\n# - `domain(el)` : return the reference element `R::AbstractReferenceElement`\n# - `el(u)` : evaluate the parametrization of the element at (parametric).\n#   coordinate `u ∈ domain(el)`.\n# - `jacobian(u)` : evaluate the jacobian of the parametrization at (parametric)\n#   coordinate `u ∈ domain(el)`.\n\n# ## Lagrangian elements<a id='lagrange-element'></a>\n\n# An concrete implementation of `AbstractElement` is the parametric type\n# `LagrangeElement{D,Np,N,T}`. The type parameters represent:\n# - `D` : the domain of the element. Thus, `domain(el)` return an instance of\n#   the singleton type `R`.\n# - `Np` : the number of points/DOF which describe the element. For example, for\n#   a flat triangle, `Np=3`, while for a flat quadrilateral element `Np=4`.\n# - `N` : the dimension of the ambient/embedding space. \n# - `T` : the data type used in the presentation of `el`. Defaults to `Float64`.\n\n\n\n\n", "meta": {"hexsha": "bb4a07ee3554e1e8157e8bd35f676aa2384b22bd", "size": 1684, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tutorials/geometry_tutorial.jl", "max_stars_repo_name": "WaveProp/WaveProp", "max_stars_repo_head_hexsha": "4d589a093d6d590d2f7bf0bfdf2cc8e2da1b1fec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-15T13:46:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T07:16:38.000Z", "max_issues_repo_path": "tutorials/geometry_tutorial.jl", "max_issues_repo_name": "WaveProp/WaveProp", "max_issues_repo_head_hexsha": "4d589a093d6d590d2f7bf0bfdf2cc8e2da1b1fec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-06-24T20:14:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-25T11:07:01.000Z", "max_forks_repo_path": "tutorials/geometry_tutorial.jl", "max_forks_repo_name": "WaveProp/WaveProp", "max_forks_repo_head_hexsha": "4d589a093d6d590d2f7bf0bfdf2cc8e2da1b1fec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-15T17:31:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T09:43:13.000Z", "avg_line_length": 43.1794871795, "max_line_length": 93, "alphanum_fraction": 0.7203087886, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7873986911710282}}
{"text": "# Fourier demo with gtk-server\r\n# #\r\n# Note: requires package Gaston for plotting, or adjust the code to work with your\r\n# plotting front-end.\r\n\r\nusing GtkServer, Gaston, FFTW\r\n\r\n# plot\r\nfunction doplots(t, A, f₀, ϕ, fs)\r\n    s = A.*sin.(2π*f₀*t .+ ϕ)\r\n    S = fftshift(fft(s))./length(s)\r\n    F = fftshift(fftfreq(length(s), fs))\r\n\r\n    p1 = plot(t, s, handle = 1,\r\n              Axes(title = \"'Sinusoidal in time domain'\", xlabel = \"'Time (s)'\",\r\n                   ylabel = \"'Amplitude'\", yrange = (-5.5, 5.5), ytics = -6:2:6))\r\n    p2 = plot(F, abs.(S), handle = 2,\r\n              Axes(title = \"'Magnitude spectrum'\", xlabel = \"'Frequency (Hz)'\",\r\n                   yrange = (0, 3)))\r\n    p3 = plot(F, angle.(S), handle = 3,\r\n              Axes(title = \"'Phase spectrum'\", xlabel = \"'Frequency (Hz)'\",\r\n                   yrange = (-3, 3)))\r\n    P = plot([p1, p2, p3], handle = 4)\r\n    display(P)\r\nend\r\n\r\nfunction demo()\r\n    # Set initial values for amplitude, frequency and phase, and display\r\n    # the sine function.\r\n    fs = 100\r\n    t = 0.0:1.0/fs:1.0\r\n    A = 1.0\r\n    f₀ = 1.0\r\n    ϕ = 0.0\r\n\r\n    # Do initial plot with default values\r\n    doplots(t, A, f₀, ϕ, fs)\r\n\r\n    # Main program\r\n    # This program interactively plots a sine function in time, and its\r\n    # magnitude and phase spectra. The amplitude, frequency and phase of\r\n    # sine function are selected through three sliders.\r\n    gtk_init()\r\n    # 'win' is a handle (ID number) to the main GUI window.\r\n    gtk_send(\"gtk_init NULL NULL\")\r\n    win = gtk_send(\"gtk_window_new 0\")\r\n    # Set window's title, size and position.\r\n    # Note that the message sent to gtk-server is always a string.\r\n    gtk_send(\"gtk_window_set_title $win 'Fourier Series Demo'\")\r\n    gtk_send(\"gtk_window_set_default_size $win 300 200\")\r\n    gtk_send(\"gtk_window_set_position $win 1\")\r\n    # We'll set our widgets in a table, one widget per row-column combination.\r\n    tbl = gtk_send(\"gtk_table_new 8 10 0\")\r\n    gtk_send(\"gtk_container_add $win $tbl\")\r\n    # Create three labels...\r\n    lblA = gtk_send(\"gtk_label_new Amplitude:\")\r\n    lblF = gtk_send(\"gtk_label_new Frequency:\")\r\n    lblP = gtk_send(\"gtk_label_new Phase:\")\r\n    # and put them in specific position on our table.\r\n    gtk_send(\"gtk_table_attach_defaults $tbl $lblA 1 3 1 2\")\r\n    gtk_send(\"gtk_table_attach_defaults $tbl $lblF 1 3 3 4\")\r\n    gtk_send(\"gtk_table_attach_defaults $tbl $lblP 1 3 5 6\")\r\n    # horizontal separator\r\n    hsep = gtk_send(\"gtk_hseparator_new\")\r\n    gtk_send(\"gtk_table_attach_defaults $tbl $hsep 1 9 6 7\")\r\n    # Some Julia advertisement\r\n    adv = gtk_send(\"gtk_label_new 'Created with Julia!'\")\r\n    gtk_send(\"gtk_table_attach_defaults $tbl $adv 1 6 7 8\")\r\n    # Create (and put on the table) the quit button.\r\n    but = gtk_send(\"gtk_button_new_from_stock 'gtk-quit'\")\r\n    gtk_send(\"gtk_table_attach_defaults $tbl $but 7 9 7 8\")\r\n    # Create three sliders...\r\n    sliA = gtk_send(\"gtk_hscale_new_with_range 1 5 0.5\")\r\n    sliF = gtk_send(\"gtk_hscale_new_with_range 1 40 1\")\r\n    sliP = gtk_send(\"gtk_hscale_new_with_range -1.6 1.6 0.1\")\r\n    # and put them on the table.\r\n    gtk_send(\"gtk_table_attach_defaults $tbl $sliA 4 9 1 2\")\r\n    gtk_send(\"gtk_table_attach_defaults $tbl $sliF 4 9 3 4\")\r\n    gtk_send(\"gtk_table_attach_defaults $tbl $sliP 4 9 5 6\")\r\n    # Now we need to actually display all the widgets we've created.\r\n    gtk_send(\"gtk_widget_show_all $win\")\r\n\r\n    # endless loop; we only break out of it when the quit button is clicked\r\n    while true\r\n        # Up to this point, we have sent commands to gtk-server in order\r\n        # to set up the GUI and display it. However, once the GUI is\r\n        # created, gtk-server will send messages (events) to us whenever\r\n        # the user clicks something on the GUI. In order to read these\r\n        # events, we send gtk-server the message \"gtk_server_callback wait\".\r\n        # So, if the user has clicked on a widget on the GUI, then\r\n        # 'event' contains the widget's handle (ID number).\r\n        event = gtk_send(\"gtk_server_callback wait\")\r\n        # The user clicked on the windows 'close' button.\r\n        if event == win\r\n            break\r\n        end\r\n        # The user clicked on the quit button.\r\n        if event == but\r\n            break\r\n        end\r\n        # The user clicked on the 'amplitude' slider. Now we need\r\n        # to go to gtk-server again to ask for the new slider's value.\r\n        if event == sliA\r\n            # here we get the new value\r\n            A_g = gtk_send(\"gtk_range_get_value $sliA\")\r\n            A = parse(Float32, A_g)\r\n            # plot again with the new sine values\r\n            P = doplots(t, A, f₀, ϕ, fs)\r\n        end\r\n        # Frequency slider.\r\n        if event == sliF\r\n            f₀_g = gtk_send(\"gtk_range_get_value $sliF\")\r\n            f₀ = parse(Float32, f₀_g)\r\n            P = doplots(t, A, f₀, ϕ, fs)\r\n        end\r\n        # ϕ slider.\r\n        if event == sliP\r\n            ϕ_g = gtk_send(\"gtk_range_get_value $sliP\")\r\n            ϕ = parse(Float32, ϕ_g)\r\n            P = doplots(t, A, f₀, ϕ, fs)\r\n        end\r\n    end\r\n\r\n    # Clean up -- close all figures and tell gtk-server to quit.\r\n    closeall()\r\n    gtk_exit()\r\nend\r\n", "meta": {"hexsha": "42d17051351f4cd6597680c40354ad9c31ee6b31", "size": 5218, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demo/fourier.jl", "max_stars_repo_name": "mbaz/GtkServer.jl", "max_stars_repo_head_hexsha": "fc3b3f0a622029e26dbc8251571127abdd3b4d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-27T02:37:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T14:26:50.000Z", "max_issues_repo_path": "demo/fourier.jl", "max_issues_repo_name": "mbaz/GtkServer.jl", "max_issues_repo_head_hexsha": "fc3b3f0a622029e26dbc8251571127abdd3b4d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo/fourier.jl", "max_forks_repo_name": "mbaz/GtkServer.jl", "max_forks_repo_head_hexsha": "fc3b3f0a622029e26dbc8251571127abdd3b4d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.765625, "max_line_length": 83, "alphanum_fraction": 0.6067458796, "num_tokens": 1475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392797, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.787398683246429}}
{"text": "# Practical Machine learning\n# Regression Analysis - Linear Regression example \n# Chapter 10\n\nusing Gadfly\n\n# Normalizes the features in x\n# The mean value of each feature is 0 and the standard deviation is 1\n# Returns normalized x, μ and σ\nfunction featureNormalize(x)\nrows = size(x,1)\ncols = size(x,2)\n\nμ = mean(x,1)\nσ = std(x,1)\nxNorm = zeros(x)\n\n# normalize\nfor i in 1:cols\n\tfor j in 1:rows\n\t\txNorm[j,i] = (x[j,i] - μ[i]) / σ[i];\n\tend\nend\n\n(xNorm, μ, σ)\nend\n\n\nprintln(\"Loading data ... \")\ndata = readdlm(\"data.txt\",',')\nx = data[:,1:2]\ny = data[:, 3]\nm = length(y)\n\n@printf(\"First 10 examples from the dataset: \\n\");\nt = [x[1:10,:] y[1:10,:]]'\nfor i in 1:10\n  @printf(\" x = [%.0f %.0f], y = %.0f \\n\", t[1,i], t[2,i], t[3,i]);\nend\n\n# Scale features and set them to zero mean\n(x, μ, σ) = featureNormalize(x);\n\n# Add intercept term to x\nx = [ones(m,1) x]\n\n#### Run Gradient Descent\nα = 0.001\nnumIter = 4000\nθ = zeros(3,1)\njHist = zeros(numIter, 1)\n\nfor i in 1:numIter\n  # next theta\n  θ = θ - (α/m) * (x' * ((x*θ)-y))\n  # compute cost\n  jHist[i] = sum((x*θ-y).^2)/(2m)\nend\n\n# plot convergence graph\npl = plot(\n  x=collect(1:numIter),\n  y=jHist,\n  Guide.xlabel(\"Iterations\"),\n  Guide.ylabel(\"Error\"),\n  Guide.title(\"Convergence Graph\"),\n  Geom.line\n  )\ndraw(SVGJS(\"jHist.js.svg\", 6inch, 6inch), pl)\n\n# Estimate the price of a 1650 sq-ft, 3 br house\nprice = [1, (1650-μ[1])/σ[1], (3-μ[2])/σ[2]]' * θ\nprintln(\"Estimated price for a 1650 sq-ft, 3 br house: $price\")\n\nprintln(\"done!\")\n", "meta": {"hexsha": "ec5ebb1d15ef4be26baba27021c5f498794c1430", "size": 1481, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/chapter10/linearregressionexample/linearregression-multivariable.jl", "max_stars_repo_name": "PacktPublishing/Practical-Machine-Learning", "max_stars_repo_head_hexsha": "7f33295766aa494a48e235db10af9897c7851fde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-08T22:17:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T18:58:02.000Z", "max_issues_repo_path": "julia/chapter10/linearregressionexample/linearregression-multivariable.jl", "max_issues_repo_name": "PacktPublishing/Practical-Machine-Learning", "max_issues_repo_head_hexsha": "7f33295766aa494a48e235db10af9897c7851fde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/chapter10/linearregressionexample/linearregression-multivariable.jl", "max_forks_repo_name": "PacktPublishing/Practical-Machine-Learning", "max_forks_repo_head_hexsha": "7f33295766aa494a48e235db10af9897c7851fde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-03-29T17:54:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T07:28:03.000Z", "avg_line_length": 19.4868421053, "max_line_length": 69, "alphanum_fraction": 0.6185010128, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7873986825690183}}
{"text": "using LinearAlgebra, SparseArrays, Random, Statistics\nusing Plots, Plots.PlotMeasures\n\nfunction gomp(y0::AbstractVector, Ψ::AbstractMatrix, \n    K::Int = 2, S::Int = 1; \n    max_iter::Int = 100, ϵ::Real = eps())\n\n\t# Get the dimensions\n\tm = length(y0)\n\tm_psi, n = size(Ψ)\n\t# Assert the dimensionality\n\t@assert m == m_psi \"Please provide consistent input sizes\"\n\t# Assert the selector\n\t@assert S <=  min(K, m/K) \"S <= min(K, m/K)\"\n\t\n\t# Normalize\n\tψ = deepcopy(Ψ)\n    # Inplace\n\tnormalize!.(eachcol(ψ), 2)\n\t\n\t\n\t# Preconditioning\n\tP = ψ'pinv(ψ*ψ')\n\t# New matrix\n\tψ = P*ψ\n\ty = P*y0\n\t# Iteration\n\titers = 0\n\t\n\t# Support\n\tΛ = zeros(Bool, n)\n\tu = zeros(eltype(y), n)\n\tr = y\n\tamps = zeros(eltype(y), n)\n\t\n\t# Find the magnitudes\n\tfor i in 1:max_iter\n\t\t# Compute the similarities via magnitude\n\t\tamps .= ψ'r\n\t\t# Get the largest entry\n\t\tidx = sortperm(abs.(amps), rev = true)[1:S]\n\t\t# Update the support \n\t\tΛ[idx] .= true\n\t\t# Update the coefficients\n\t\tu[Λ] .= (y' / ψ')[1, Λ]\n\t\t# Update r\n\t\tr .= y - ψ*u\n\t\t# Convergence\n\t\t(norm(r,2) < ϵ || sum(Λ) >= K) && break\n\tend\n\t\n    # Last time to get the right coefficients\n\tu[Λ] .= (y0' / Ψ')[1, Λ]\n    \n\treturn u\nend\n\n## Test data\nRandom.seed!(1111) # Lucky\nx̂ = sprandn(Float64, 100, 0.1)\nk_opt = Int(norm(x̂, 0))\nA = randn(Float64, 300, 100)\ny = A*x̂\n\n# Evaluate\nx = gomp(y, A, k_opt)\n\n# Check for different sparsties levels\nsp_n = map(0.01:0.01:0.2) do i\n\tx̃ = sprandn(Float64, 100, i)\n\tỹ = A*x̃\n\tnorm(gomp(ỹ, A, 50, 1, ϵ = 0.01), 0), norm(x̃, 0)\nend\n\ngr()\npl_1 = scatter(x̂, label = \"Ground Truth\", markeralpha = 0.5, xlabel = \"Index\", ylabel = \"x\", legend = :bottomright)\nscatter!(x, label = \"Estimated\", markershape = :cross, markersize = 12, markerstrokewidth = 5)\nsavefig(joinpath(pwd(), \"figures\", \"gomp.pdf\"))\n\nxs, ys = first.(sp_n), last.(sp_n)\npl_2 = scatter(ys, xlabel = \"Run\", ylabel = \"Sparsity\", label = \"Ground Truth\", legend = :topleft)\nscatter!(xs, label = \"Estimated\", markershape = :cross, markersize = 12, markerstrokewidth = 5)\nsavefig(joinpath(pwd(), \"figures\", \"gomp_vary.pdf\"))\n\nplot(pl_1, pl_2, layout = (1,2), size = (900, 300), margins = 5mm)\nsavefig(joinpath(pwd(), \"figures\", \"merged.pdf\"))\n", "meta": {"hexsha": "4b253cff26ccb9ab5c7fb507c8908d75abcd8286", "size": 2155, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/gomp.jl", "max_stars_repo_name": "AlCap23/ScientificComputingSeminar2021", "max_stars_repo_head_hexsha": "1adf9984f2948d3b990036ffb616fd1b2ffc2ae6", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/gomp.jl", "max_issues_repo_name": "AlCap23/ScientificComputingSeminar2021", "max_issues_repo_head_hexsha": "1adf9984f2948d3b990036ffb616fd1b2ffc2ae6", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/gomp.jl", "max_forks_repo_name": "AlCap23/ScientificComputingSeminar2021", "max_forks_repo_head_hexsha": "1adf9984f2948d3b990036ffb616fd1b2ffc2ae6", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7701149425, "max_line_length": 116, "alphanum_fraction": 0.6236658933, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7873986754841872}}
{"text": "using ApproxFun\n\n#The following solves the Airy ODE with dirichlet boundary conditions\n\nx=Fun(identity,-1000..15)   # Fun corresponding to multiplication by x, on [-100,15]\nd=domain(x)\nD=Derivative()             # The derivative operator\nB=Dirichlet()              # Dirichlet boundary conditions, [u(-100),u(15)]\n\n#Construct operator\n\nA=[B;D^2-x]                # This is dirichlet conditions and u'' - x u\nb=[airyai(leftendpoint(d)),0]     # We want it to equal airyai(-100) at -100, and 0 at\n                           # 10, with 0 rhs\n#Solve ODE\n\nu=A\\[b,0]                  # u satisfies A*u = b, or in other words,\n                           # B*u = [airyai(-100.),0.] and (D2 - x)*u = 0.\n\n# Check the accuracy\nnorm(u - Fun(airyai,d))\n\n\n## We now solve with Neumann conditions\n\nB=Neumann()\nA=[B;D^2-x]\nb=[[airyaiprime(leftendpoint(d)),0.],0.]\n\nu=A\\b\n\n\n# Check the accuracy\nnorm(u - Fun(airyai,d))\n", "meta": {"hexsha": "b1d1bbc340feb2308fb5e4d56d6d08ba9039b3b9", "size": 902, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ODEs/Airy equation.jl", "max_stars_repo_name": "putianyi889/ApproxFunExamples", "max_stars_repo_head_hexsha": "b519a2b2a197607561028fea53a327493bfb344e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2018-06-01T04:19:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T10:15:11.000Z", "max_issues_repo_path": "ODEs/Airy equation.jl", "max_issues_repo_name": "putianyi889/ApproxFunExamples", "max_issues_repo_head_hexsha": "b519a2b2a197607561028fea53a327493bfb344e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-03-27T09:32:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-30T08:52:42.000Z", "max_forks_repo_path": "ODEs/Airy equation.jl", "max_forks_repo_name": "putianyi889/ApproxFunExamples", "max_forks_repo_head_hexsha": "b519a2b2a197607561028fea53a327493bfb344e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-07-25T00:08:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T12:38:42.000Z", "avg_line_length": 25.7714285714, "max_line_length": 86, "alphanum_fraction": 0.588691796, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361162033533, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7873937125950611}}
{"text": "#\n# Denoise an SPD Example with Douglas Rachford\n#\n# L2-TV functional with anisotropic TV\n#\n#\n#\nusing Manopt, Manifolds\nusing Images, CSV, DataFrames, LinearAlgebra, JLD2, Dates\n#\n# Settings\nExportOrig = false\nExportResult = true\nExportTable = true\nasy_render_detail = 2\nresultsFolder = \"examples/Total_Variation/SPD_TV/\"\ncomparisonData = \"ImageCPPA-CostValue.jld2\"\nexperimantName = \"ImageDR\"\nif !isdir(resultsFolder)\n    mkdir(resultsFolder)\nend\n#\n# Manifold & Data\nf = artificial_SPD_image2(32)\nif ExportOrig\n    asymptote_export_SPD(resultsFolder*experimantName*\"orig.asy\"; data=f, scaleAxes=(7.5,7.5,7.5))\n    render_asymptote(resultsFolder * experimentName * \"-orig.asy\", render=asy_render_detail)\nend\n#\n# Parameters\nη  = 0.58\nλ = 0.93\nα = 6.\n#\n# Build Problem for L2-TV\npixelM = SymmetricPositiveDefinite(3);\nM = PowerManifold(pixelM, NestedPowerRepresentation(), size(f)...)\nd = length(size(f))\nrep(d) = (d>1) ? [ones(Int,d)...,d] : d\nfidelity(x) = 1/2*distance(M,x,f)^2\nΛ(x) = forward_logs(M,x) # on T_xN\nprior(x) = norm(norm.(Ref(pixelM), repeat(x,rep(d)...), Λ(x)),1)\n#\n# Setup & Optimize\nprint(\"--- Douglas–Rachford with η: $(η) and λ: $(λ) ---\\n\")\ncost(x) = fidelity(x) + α*prior(x)\nN = PowerManifold(pixelM, NestedPowerRepresentation(),5)\nprox1 = (η,x) -> cat( prox_distance(M,η,f,get_component(N,x,1)), prox_parallel_TV(M,α*η,get_component(N,x,2:5)), dims=1)\nprox2 = (η,x) -> fill(mean(M,x;stopping_criterion=StopAfterIteration(20)),5)\nsC = StopAfterIteration(400)\ntry\n    cost_threshold = load(resultsFolder*comparisonData)[\"compareCostFunctionValue\"]\n    global sC = StopWhenCostLess(cost_threshold)\n    @info \"Comparison to CPPA (`SPDImage_CPPA.jl`) and its cost of $cost_threshold.\"\ncatch y\n    if isa(y, SystemError)\n        @info \"Comparison to CPPA only possible after runninng `SPDImage_CPPA.jl` its cost was stored.\"\n    end\nend\nx0 = f\n@time o = DouglasRachford(M, cost, [prox1,prox2], f;\n    λ = i -> η, α = i -> λ, # map from Paper notation of BPS16 to toolbox notation\n    debug = [:Iteration,\" | \", :Change, \" | \", :Cost,\"\\n\",10,:Stop],\n    record = [:Iteration, :Cost ],\n    stopping_criterion = sC,\n    parallel=5,\n    return_options = true\n)\ny = get_solver_result(o)\nr = get_record(o)\n#\n# Result\nnumIter = length(r)\nif ExportResult\n    asymptote_export_SPD(resultsFolder*experimantName*\"img-result-$(numIter)-α$(replace(string(α), \".\" => \"-\")).asy\"; data=y, render=4, scaleAxes=(7.5,7.5,7.5) )\n    render_asymptote(resultsFolder * experimentName * \"img-result-$(numIter)-α$(replace(string(α), \".\" => \"-\")).asy\", render=asy_render_detail)\nend\nif ExportTable\n    A = cat( [ri[1] for ri in r], [ri[2] for ri in r]; dims=2 )\n    CSV.write(resultsFolder*experimantName*\"-Cost.csv\",  DataFrame(A), writeheader=false);\nend", "meta": {"hexsha": "414e380e3865395ea81c7e05df8badda82e3d8a3", "size": 2745, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Total_Variation/SPDImage_DR_vs_CPPA.jl", "max_stars_repo_name": "matbesancon/Manopt.jl", "max_stars_repo_head_hexsha": "25671e4c56728b7ab3ce82321d063308095750da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Total_Variation/SPDImage_DR_vs_CPPA.jl", "max_issues_repo_name": "matbesancon/Manopt.jl", "max_issues_repo_head_hexsha": "25671e4c56728b7ab3ce82321d063308095750da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Total_Variation/SPDImage_DR_vs_CPPA.jl", "max_forks_repo_name": "matbesancon/Manopt.jl", "max_forks_repo_head_hexsha": "25671e4c56728b7ab3ce82321d063308095750da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8888888889, "max_line_length": 161, "alphanum_fraction": 0.6932604736, "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973294, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7873314705611589}}
{"text": "# Arvind Prasadan\n# 2019 January\n# DMF Package Code\n# Optshrink Function\n\n\"\"\"\n\toptshrink(Y, r)\n\nPerform a rank-r denoising of a data matrix Y via the OptShrink algorithm, described in http://doi.org/10.1109/TIT.2014.2311661 (R R Nadakuditi, 2014)\n\n# Arguments\n- `Y`: 2D Array (Data Matrix), where Y = X + Noise, and we want to find X\n- `r`: An estimate of the rank of X (Integral)\n\n# Output\n- `Xh`: An estimate of X\n- `w`: The shrunken singular values; if r = rank(Y), w is all zero\n\"\"\"\nfunction optshrink(Y, r)\n\n    r = round(abs(r[1])) # Sanity check rank\n    r = (1 <= r) ? r : 1\n\n    (m, n) = size(Y)\n    r = minimum([r, m, n]) # ensure r <= min(m, n)\n    if r == m || r == n\n\treturn Y, zeros(r)\n    end\n\n    # U is [m, min(m, n)], s is min(m, n), V is [n, min(n, m)]\n    (U, s, V) = svd(Y, full = false)\n\n    sv = s[(r + 1):end] # tail singular values for noise estimation\n\n    w = zeros(r)\n    for k = 1:1:r\n        (D, Dder) = D_transform_from_vector(s[k], sv, max(m, n) - r, min(m, n) - r)\n        w[k] = -2.0 * D / Dder\n    end\n\n    w[isnan.(w)] .= 0.0\n\n    Xh = U[:, 1:r] * Diagonal(w) * V[:, 1:r]'\n\n    return Xh, w\nend\n\n\"\"\"\n\t D_transform_from_vector(z, sn, m, n)\n\nFind the D Transform of the singular value spectrum sn at a point z, for an m x n matrix.\n\n# Arguments\n- `z`: Point to evaluate transform\n- `sn`: Vector of singular values\n- `m`: Matrix dimension\n- `n`: Matrix dimension\n\n# Outputs\n- `D`: D Transform \n- `D_der`: D Transform Derivative\n\"\"\"\nfunction D_transform_from_vector(z, sn, m, n)\n    # sn is of length n <= m\n\n    sm = [sn; zeros(m - n)] # m x 1\n\n    inv_n = 1.0 ./ (z^2.0 .- sn.^2.0) # vector corresponding to diagonal\n    inv_m = 1.0 ./ (z^2.0 .- sm.^2.0)\n\n    D1 = (1.0 / n) * sum(z * inv_n)\n    D2 = (1.0 / m) * sum(z * inv_m)\n\n    D = D1 * D2 # eq (16a) in paper\n\n    # derivative of D transform\n    D1_der = (1.0 / n) * sum(-2.0 * z^2.0 .* inv_n.^2.0 + inv_n)\n    D2_der = (1.0 / m) * sum(-2.0 * z^2.0 .* inv_m.^2.0 + inv_m)\n\n    D_der = D1 * D2_der + D2 * D1_der # eq (16b) in paper\n\n    return (D, D_der)\nend\n\n", "meta": {"hexsha": "9d33ac46b15237ea7d824ce0a8a903b034945d1e", "size": 2049, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/optshrink.jl", "max_stars_repo_name": "JuliaTagBot/DMF.jl", "max_stars_repo_head_hexsha": "8f1605f9edcb5ae2729ee1c1c61c13c4b14e51cc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-09T21:27:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-02T14:13:39.000Z", "max_issues_repo_path": "src/optshrink.jl", "max_issues_repo_name": "JuliaTagBot/DMF.jl", "max_issues_repo_head_hexsha": "8f1605f9edcb5ae2729ee1c1c61c13c4b14e51cc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optshrink.jl", "max_forks_repo_name": "JuliaTagBot/DMF.jl", "max_forks_repo_head_hexsha": "8f1605f9edcb5ae2729ee1c1c61c13c4b14e51cc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:26:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-06T12:46:03.000Z", "avg_line_length": 24.1058823529, "max_line_length": 150, "alphanum_fraction": 0.5632015617, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7873314671336248}}
{"text": "using JuMP\n\n##### Simple LP\n# Example taken directly from https://jump.readthedocs.org/en/latest/quickstart.html\n\nprintln(\"***** Problem 1 *****\")\n\nm = Model()\n@variable(m, 0 <= x <= 2 )\n@variable(m, 0 <= y <= 30 )\n\n@objective(m, Max, 5x + 3*y )\n@constraint(m, 1x + 5y <= 3.0 )\n\nprint(m)\n\nstatus = solve(m)\n\nprintln(\"Objective value: \", getobjectivevalue(m))\nprintln(\"x = \", getvalue(x))\nprintln(\"y = \", getvalue(y))\n\n##### Another simple LP with logical conditions in constraint definition\n# Example from https://groups.google.com/forum/#!topic/julia-opt/pMHz-9YHN2o\n# Note: This example only works with Julia-v0.4 and later\n\nprintln(\" \")\nprintln(\"***** Problem 2 *****\")\n\nm = Model()\n\nI = 1:5\n\n@variable(m, 0 <= x[I] <= 10)\n@variable(m, 0 <= y[I] <= 10)\n\n# This constraint is only considered when i + j are less than or equal to 3\n# Note: Only supported by Julia-v0.4 and later\n@constraint(m, constr[i=I,j=I; i+j <= 3], x[i] - y[j] == 1)\n\n@objective(m, Min, sum{x[i] + y[i], i=I})\n\nprint(m)\n\nstatus = solve(m)\n\nprintln(\" \")\nprintln(\"Objective value: \", getobjectivevalue(m))\nprintln(\"x = \", getvalue(x))\nprintln(\"y = \", getvalue(y))", "meta": {"hexsha": "8f22c6ac173b510f7007bbc5ba56d9989bbc4518", "size": 1134, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/basic_JuMP_ex1.jl", "max_stars_repo_name": "etatara/DegeneracyHunter.jl", "max_stars_repo_head_hexsha": "df9afb36d30860ff64fd54fd0866fc5e840b5595", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2016-09-06T18:15:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-04T14:10:38.000Z", "max_issues_repo_path": "Examples/basic_JuMP_ex1.jl", "max_issues_repo_name": "etatara/DegeneracyHunter.jl", "max_issues_repo_head_hexsha": "df9afb36d30860ff64fd54fd0866fc5e840b5595", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2016-09-02T00:32:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-26T12:12:28.000Z", "max_forks_repo_path": "Examples/basic_JuMP_ex1.jl", "max_forks_repo_name": "etatara/DegeneracyHunter.jl", "max_forks_repo_head_hexsha": "df9afb36d30860ff64fd54fd0866fc5e840b5595", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-04-13T13:07:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-27T18:15:06.000Z", "avg_line_length": 22.68, "max_line_length": 84, "alphanum_fraction": 0.6331569665, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7873252163777459}}
{"text": "# Parts of this code were taken / derived from NetworkX. See LICENSE for\n# licensing details.\n\nusing Base.Threads\n\n\"\"\"\n    pagerank(g, α=0.85, n=100, ϵ=1.0e-6)\n\nCalculate the [PageRank](https://en.wikipedia.org/wiki/PageRank) of the\ngraph `g` parameterized by damping factor `α`, number of iterations \n`n`, and convergence threshold `ϵ`. Return a vector representing the\ncentrality calculated for each node in `g`, or an error if convergence\nis not reached within `n` iterations.\n\"\"\"\nfunction pagerank(\n    g::AbstractGraph{U}, \n    α=0.85, \n    n::Integer=100,\n    ϵ=1.0e-6\n    ) where U <: Integer\n    α_div_outdegree = Vector{Float64}(undef,nv(g))\n    dangling_nodes = Vector{U}()\n    for v in vertices(g)\n        if outdegree(g, v) == 0\n            push!(dangling_nodes, v)\n        end\n        α_div_outdegree[v] = (α/outdegree(g, v))\n    end\n    N = Int(nv(g))\n    # solution vector and temporary vector\n    x = fill(1.0 / N, N)\n    xlast = copy(x)\n    for _ in 1:n\n        dangling_sum = 0.0\n        for v in dangling_nodes\n            dangling_sum += x[v]\n        end\n        # flow from teleprotation\n        for v in vertices(g)\n            xlast[v] = (1 - α + α * dangling_sum) * (1.0 / N)\n        end\n        # flow from edges\n        \n        for v in vertices(g)\n            for u in inneighbors(g, v)\n                xlast[v] += (x[u] * α_div_outdegree[u])\n            end\n        end\n        # l1 change in solution convergence criterion\n        err = 0.0\n        for v in vertices(g)\n            err += abs(xlast[v] - x[v])\n            x[v] = xlast[v]\n        end\n        if (err < N * ϵ)\n            return x\n        end\n    end\n    error(\"Pagerank did not converge after $n iterations.\") # TODO 0.7: change to InexactError with appropriate msg.\nend\n", "meta": {"hexsha": "b34d43b5f2268e431e3fbc061043df36b99018df", "size": 1767, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/centrality/pagerank.jl", "max_stars_repo_name": "blepabyte/LightGraphs.jl", "max_stars_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 745, "max_stars_repo_stars_event_min_datetime": "2015-03-19T03:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-07T00:59:06.000Z", "max_issues_repo_path": "src/centrality/pagerank.jl", "max_issues_repo_name": "blepabyte/LightGraphs.jl", "max_issues_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1491, "max_issues_repo_issues_event_min_datetime": "2015-03-19T17:04:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T14:47:57.000Z", "max_forks_repo_path": "src/centrality/pagerank.jl", "max_forks_repo_name": "blepabyte/LightGraphs.jl", "max_forks_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 288, "max_forks_repo_forks_event_min_datetime": "2015-04-04T14:31:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T10:37:21.000Z", "avg_line_length": 28.9672131148, "max_line_length": 116, "alphanum_fraction": 0.571590266, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7873252147699877}}
{"text": "export armijo\nexport goldenLS\n\n\"\"\"\narmijo(f,fk,dfk,xk,pk)\n\nBacktracked Armijo linesearch\n\"\"\"\nfunction armijo(f::Function,fk,dfk,xk,pk;maxIter=10, c1=1e-4,b=0.5)\nLS = 1\nt  = 1\nwhile LS<=maxIter\n    if f(xk+t*pk) <= fk + t*c1*dot(dfk,pk)\n        break\n    end\n    t *= b\n    LS += 1\nend\nif LS>maxIter\n\tLS= -1\n\tt = 0.0\nend\nreturn t,LS\nend\n\n\"\"\"\ngoldenLS(f,xk,pk,a,b)\n\nGolden section linesearch\n\"\"\"\nfunction goldenLS(f::Function,xk,pk,a,b;atol=1e-2,maxIter=40)\n\tratio = (sqrt(5)-1)/2.0\n\t# make sure points we have an interval\n\ta,b   = (a<b)? (a,b) :  (b,a)\n\t# evaluate f at left point\n\tal    = b - ratio*(b-a)\n\tfl    = f(xk + al*pk)\n\t# evaluate f at right point\n\tar    = a + ratio*(b-a)\n\tfr    = f(xk + ar*pk)\n\t\n\tLS    = 0\n\twhile (LS<maxIter && abs(ar-al)>atol)\n\t\tif fl<fr # continue search in [a,ar]\n\t\t\tb  = ar\n\t\t\tar = al\n\t\t\tfr = fl\n\t\t\tal = b - ratio*(b-a)\n\t\t\tfl = f(xk + al*pk)\n\t\telse # continue search in [al,b]\n\t\t\ta  = al\n\t\t\tal = ar\n\t\t\tfl = fr\n\t\t\tar = a + ratio*(b-a)\n\t\t\tfr = f(xk + ar*pk)\n\t\tend\n\t\t# @printf \"iter=%d, [al,ar]=[%1.2f,%1.2f], [fl,fr]=[%1.2e,%1.2e]\\n\" LS al ar fl fr\n\t\tLS += 1\n\tend\n\treturn (al+ar)/2,LS\nend\n", "meta": {"hexsha": "7c638926286108f3b2c1e99e93f33a775674a4f2", "size": 1120, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lineSearch.jl", "max_stars_repo_name": "lruthotto/OptimTools.jl", "max_stars_repo_head_hexsha": "977feb8f2fd5e04d3f3b2a700b8abc992740cedb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lineSearch.jl", "max_issues_repo_name": "lruthotto/OptimTools.jl", "max_issues_repo_head_hexsha": "977feb8f2fd5e04d3f3b2a700b8abc992740cedb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lineSearch.jl", "max_forks_repo_name": "lruthotto/OptimTools.jl", "max_forks_repo_head_hexsha": "977feb8f2fd5e04d3f3b2a700b8abc992740cedb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.064516129, "max_line_length": 84, "alphanum_fraction": 0.5571428571, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002491, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7873252059133073}}
{"text": "\n# # Coriolis Parameter\n#\n#md # [![](https://mybinder.org/badge_logo.svg)](@__BINDER_ROOT_URL__/notebooks/example_f.ipynb)\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/notebooks/example_f.ipynb)\n#\n# [from wikipedia:](https://en.wikipedia.org/wiki/Coriolis_frequency)\n#\n# The Coriolis frequency `ƒ`, also called the Coriolis parameter or Coriolis\n# coefficient, is equal to twice the rotation rate `Ω` of the Earth multiplied\n# by the `sine` of the latitude `φ`.\n#\n# $$f=2\\Omega \\sin \\varphi$$\n\nusing PhysicalOceanography\nisapprox(f(45),1.03125867182e-4)\n", "meta": {"hexsha": "839ba59fa72cf931358a65779cef45a0ac23e467", "size": 599, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Parameters/example_f.jl", "max_stars_repo_name": "gaelforget/PhysicalOceanography.jl", "max_stars_repo_head_hexsha": "2b7e7f44d2d24a62eed5e4bedfbbd76d24a4a26b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Parameters/example_f.jl", "max_issues_repo_name": "gaelforget/PhysicalOceanography.jl", "max_issues_repo_head_hexsha": "2b7e7f44d2d24a62eed5e4bedfbbd76d24a4a26b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-04T16:57:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-16T15:02:48.000Z", "max_forks_repo_path": "examples/Parameters/example_f.jl", "max_forks_repo_name": "gaelforget/PhysicalOceanography.jl", "max_forks_repo_head_hexsha": "2b7e7f44d2d24a62eed5e4bedfbbd76d24a4a26b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2352941176, "max_line_length": 116, "alphanum_fraction": 0.7412353923, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7872901846274167}}
{"text": "function constantdiffusionproblem(stepper; nx=128, Lx=2π, kappa=1e-2, nsteps=1000, dev=CPU())\n   τ = 1/kappa  # time-scale for diffusive decay\n  dt = 1e-9 * τ # dynamics are resolved\n\n  prob = Diffusion.Problem(nx=nx, Lx=Lx, kappa=kappa, dt=dt, stepper=stepper, dev=dev)\n  g = prob.grid\n\n  # a gaussian initial condition c(x, t=0)\n  c0ampl, σ = 0.01, 0.2\n  c0func(x) = @. c0ampl*exp(-x^2/(2σ^2))\n  c0 = c0func.(g.x)\n\n  # analytic solution for for 1D heat equation with constant κ\n  tfinal = nsteps*dt\n  σt = sqrt(2*kappa*tfinal + σ^2)\n  cfinal = @. c0ampl*σ/σt * exp(-g.x^2/(2*σt^2))\n\n  Diffusion.set_c!(prob, c0)\n  tcomp = @elapsed stepforward!(prob, nsteps)\n  Diffusion.updatevars!(prob)\n\n  prob, c0, cfinal, nsteps, tcomp\nend\n\nfunction constantdiffusionproblem2D(stepper; nx=128, ny=64, Lx=2π, Ly=4π, kappa=1e-2, nsteps=1000, dev=CPU())\n    τ = 1/kappa  # time-scale for diffusive decay\n    dt = 1e-9 * τ # dynamics are resolved\n\nprob = Diffusion2D.Problem(nx=nx, ny=ny, Lx=Lx, Ly=Ly, kappa=kappa, dt=dt, stepper=stepper, dev=dev)\ng = prob.grid\n\n#Gaussian Initial Condition\nc0, σ0 = 0.1, 0.2\nc1, σ1 = 0.1, 0.2\n\nc0_x_func(x) = @. c0*exp(-x^2/(2*(σ0)^2))\nc0_y_func(y) = @. c1*exp(-y^2/(2*(σ1)^2))\n\nc0_val = c0_x_func.(g.x) .* c0_y_func.(g.y)\n\n#Analytic Solution\ntfinal = nsteps*dt\n\nσ0t = sqrt(2*kappa*tfinal + (σ0)^2)\nσ1t = sqrt(2*kappa*tfinal + (σ1)^2)\n\ncfinal_x = @. c0 * (σ0/σ0t) * exp(-g.x^2/(2*(σ0t)^2))\ncfinal_y = @. c1 * (σ1/σ1t) * exp(-g.y^2/(2*(σ1t)^2))\n\ncfinal_val = cfinal_x .* cfinal_y\n\n#Numerical Solution\nDiffusion2D.set_c!(prob, c0_val)\ntcomp = @elapsed stepforward!(prob, nsteps)\nDiffusion2D.updatevars!(prob)\n\nprob, c0_val, cfinal_val, nsteps, tcomp\nend \n\nfunction varyingdiffusionproblem(stepper; nx=128, Lx=2π, kappa=1e-2, nsteps=1000, dev=CPU())\n   τ = 1/kappa  # time-scale for diffusive decay\n  dt = 1e-9 * τ # dynamics are resolved\n\n  kappa = kappa*ones(nx) # this is actually a constant diffusion but defining it\n                         # as an array makes stepforward! call function calcN!\n                         # instead of just the linear coefficients L*sol\n\n  prob = Diffusion.Problem(nx=nx, Lx=Lx, kappa=kappa, dt=dt, stepper=stepper, dev=dev)\n  g = prob.grid\n\n  # a gaussian initial condition c(x, t=0)\n  c0ampl, σ = 0.01, 0.2\n  c0func(x) = @. c0ampl*exp(-x^2/(2σ^2))\n  c0 = c0func.(g.x)\n\n  # analytic solution for for 1D heat equation with constant κ\n  tfinal = nsteps*dt\n  σt = sqrt(2*kappa[1]*tfinal + σ^2)\n  cfinal = @. c0ampl*σ/σt * exp(-g.x^2/(2*σt^2))\n\n  Diffusion.set_c!(prob, c0)\n  tcomp = @elapsed stepforward!(prob, nsteps)\n  Diffusion.updatevars!(prob)\n\n  prob, c0, cfinal, nsteps, tcomp\nend\n\n\nfunction constantdiffusiontest(stepper, dev::Device=CPU(); kwargs...)\n  prob, c0, c1, nsteps, tcomp = constantdiffusionproblem(stepper; kwargs...)\n  normmsg = \"$stepper: relative error =\"\n  @printf(\"% 40s %.2e (%.3f s)\\n\", normmsg, norm(c1-prob.vars.c)/norm(c1), tcomp)\n  isapprox(c1, prob.vars.c, rtol=nsteps*rtol_timesteppers)\nend\n\nfunction constantdiffusiontest2D(stepper, dev::Device=CPU(); kwargs...)\n    prob, ci, cf, nsteps, tcomp = constantdiffusionproblem2D(stepper; kwargs...)\n    normmsg = \"$stepper: relative error =\"\n    @printf(\"% 40s %.2e (%.3f s)\\n\", normmsg, norm(cf-prob.vars.c)/norm(cf), tcomp)\n    isapprox(cf, prob.vars.c, rtol=nsteps*rtol_timesteppers)\nend\n\nfunction varyingdiffusiontest(stepper, dev::Device=CPU(); kwargs...)\n  prob, c0, c1, nsteps, tcomp = varyingdiffusionproblem(stepper; kwargs...)\n  normmsg = \"$stepper: relative error =\"\n  @printf(\"% 40s %.2e (%.3f s)\\n\", normmsg, norm(c1-prob.vars.c)/norm(c1), tcomp)\n  isapprox(c1, prob.vars.c, rtol=nsteps*rtol_timesteppers)\nend\n", "meta": {"hexsha": "3d89f3ec785b730d740a688d23c0f712174262bc", "size": 3652, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_timesteppers.jl", "max_stars_repo_name": "FChaosi/FourierFlows.jl", "max_stars_repo_head_hexsha": "e870394a56e0eeb551b08c44b7c6498be5c88656", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_timesteppers.jl", "max_issues_repo_name": "FChaosi/FourierFlows.jl", "max_issues_repo_head_hexsha": "e870394a56e0eeb551b08c44b7c6498be5c88656", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_timesteppers.jl", "max_forks_repo_name": "FChaosi/FourierFlows.jl", "max_forks_repo_head_hexsha": "e870394a56e0eeb551b08c44b7c6498be5c88656", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.504587156, "max_line_length": 109, "alphanum_fraction": 0.6651150055, "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7872607329284409}}
{"text": "# ------------------------------------------------------------------------------------------\n# # Minimizing functions - how a computer learns\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# In the previous notebooks, we've seen that by changing **parameters** in a function, we\n# could find a \"best fit\" of that function to some data. We use a **loss function** to\n# quantify the \"goodness\" of a set of parameters and we look for those parameters that\n# **optimize**, in fact **minimize**, the loss function. If we teach a machine how to\n# minimize the loss function on its own, we say that machine is able to **learn** how to\n# model our data.\n#\n# In the last notebook, we threw around terms like **derivative**, **gradient**, and\n# **gradient descent** to give you a rough sense of how we minimize a function on a\n# computer. In this notebook, we will step through these concepts more carefully, with the\n# aim of being able to implement them using Julia.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## Minimizing a 1D function using calculus\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Let's draw the 1D loss function $L_1$ from a previous notebook again:\n# ------------------------------------------------------------------------------------------\n\nσ(x) = 1 / (1 + exp(-x))\nf(x, w) = σ(w * x)\n\nx1 = 2\ny1 = 0.8\n\nL1(w) = (y1 - f(x1, w))^2\n\nusing Plots; gr()\nusing Interact\n\nplot(L1, -2, 1.5, xlabel=\"w\", ylabel=\"L1(w)\", leg=false)\n\n# ------------------------------------------------------------------------------------------\n# By eye, we can see that the minimum is around $w=0.6$. But how can we get the computer to\n# work this out on its own?\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# In the previous notebook, we thought of this function plot as a hill, viewed from the\n# side. We could find the minimum by making the hill sticky, and letting a ball roll down\n# it. The ball will find and settle in the minimum of the function.  Now let's see how to\n# teach a computer to do this.\n#\n# We need to find the downhill direction along the hill, which is related to its *slope*\n# (how steep it is). Calculus provides us with tools to calculate that slope!\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Namely, the slope of a curve $L_1(w)$ at $w$ is given by its **derivative** $L_1'(w)$;\n# geometrically, this is the slope of the **tangent line** to the curve at that point, i.e.\n# the straight line which touches the curve at that point.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Calculus provides us with some rules to calculate an analytical formula for the\n# derivative, and we will see later how to apply these rules, albeit indirectly, for machine\n# learning.\n# To gain understanding, however, we will see here how to get the computer to help us out by\n# calculating the derivatives numerically instead!\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## Approximating derivatives\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Let's recall that the derivative $L_1'(w)$ of a function is defined as\n#\n# $$L_1'(w) \\simeq \\frac{L_1(w+h) - L_1(w)}{h},$$\n#\n# for a small step size $h$. (Strictly speaking, we must take the limit when $h$ tends to\n# $0$ to obtain the exact value of the derivative.)\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 1\n#\n# Write a function to calculate the derivative of a function at a given point. Note that in\n# Julia, we can easily pass functions as arguments to other functions!\n# The function should take the function, the point $w$ at which to calculate the derivative,\n# and the value of $h$, which should have a default value of 0.001.\n#\n# *Note*: A function input argument can have a *default value* if we set the input argument\n# equal to that default value when we define the function. For example,\n#\n# ```julia\n# f(x, a = 3) = a * x^2\n# ```\n#\n# The function `f` will square the input we give it and multiply by `a`. However,  if we\n# choose to call `f(x)` *without* passing it an `a` input, it will assume `a` is `3` and\n# return `3*x^2`.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 2\n#\n# Write an interactive visualization of the tangent line to the graph of $L_1$, so that we\n# can visualize the tangent at any point on $L_1$. Include the current value of the\n# derivative in the title.\n#\n# *Hint*: Recall that the straight line through the point $(x_0, y_0)$ with slope $m$ is\n# given by\n#\n# $$ \\frac{y - y_0}{x - x_0} = m,$$\n#\n# so\n#\n# $$y = y_0 + m*(x - x_0).$$\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 3\n#\n# What is the value of the derivative (slope of the tangent line) at a minimum? Can this\n# happen anywhere else?\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## Minimization by gradient descent\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# The tangent line at a point is a good approximation of the function near that point.\n# Therefore the derivative tells us in which direction, and how fast, a function grows or\n# shrinks when we move a small distance away from that point.\n#\n# As we saw in the previous notebook, we can think of the function as being a hill, and\n# having a ball that we want to move down the hill. Gravity will automatically pull the ball\n# in the direction *down* the hill; we want to emulate this in the computer!\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 4\n#\n# When the derivative $L_1'(w)$ is positive, that means that $L_1$ increases from left to\n# right at point $w$.\n#\n# If the derivative $L_1'(w)$ is positive (> 0), in which direction should we move $w$ to\n# *decrease* $L_1$?\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 5\n#\n# If the derivative $L_1'(w)$ is negative (< 0), in which direction should we move $w$ to\n# *decrease* $L_1$?\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# We can use this information to tell the computer which way to take a step. This\n# constitutes the numerical algorithm called **gradient descent**; it is called this since\n# we are descending (moving downwards) along the graph of the function by using information\n# about its gradient (slope).\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 6\n#\n# Implement gradient descent by following this prescription for an **iterative (repetitive)\n# algorithm**:\n#\n# 1. Start at an initial guess $w_0$ for $w$.\n#\n# 2. At each step, calculate the derivative, $L_1'(w_n)$ at the current value of $w_n$ using\n# the function that you created above.\n#\n# 3. Modify the value of $w$ by a small multiple (for example, $\\eta=0.01$) of the value of\n# the derivative you just created, via $w_{n+1} = w_n - \\eta L_1'(w_n)$.\n#\n# For this problem, start with $w_0 = -2.0$. Repeat steps 2 and 3 a total of `2000` times.\n#\n# Package this code into a function called `gradient_descent` that takes two inputs, a\n# function and a range for values of $w$, and returns the final value of $w$ and $L_1(w)$.\n#\n# Using `L1` and `-2:0.01:1.5` as your inputs to `gradient_descent`, for what value of $w$\n# is $L_1$ at a minimum?\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 7\n#\n# Modify your code for gradient descent to return the result once it has found an answer\n# within some *tolerance*, rather than taking a set number of steps. The new prescription\n# for this algorithm is:\n#\n# 1. Start at an initial guess $w_0$ for $w$.\n#\n# 2. At each step, calculate the derivative, $L_1'(w_n)$ at the current value of $w_n$,\n# using the function that you created above.\n#\n# 3. Modify the value of $w$ by a small multiple (for example, $\\eta=0.01$) of the value of\n# the derivative you just created, via $w_{n+1} = w_n - \\eta L_1'(w_n)$.\n#\n# 4. Check how different $w_{n+1}$ is from $w_n$. If you're satisfied that $L_1(w_{n+1})$ is\n# minimized, return $w_{n+1}$ and $L_1(w_{n+1})$. Otherwise, go to step (2) and continue.\n#\n# Edit `gradient_descent` so that it takes three inputs: a function, a range for values of\n# $w$, and a tolerance that tells you how close $w_{n+1}$ must be to $w_n$ before you can\n# stop iterating.\n#\n# Using `L1`, `-2:0.01:1.5`, and `.000001` as your inputs to `gradient_descent`, for what\n# value of $w$ is $L_1$ at a minimum?\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 8\n#\n# Alter the function `gradient_descent` so that it stores the results `(w, L1(w))` at each\n# step of the algorithm as an array and returns this array. How many steps does the\n# algorithm take for input parameters `(L1, -2:0.01:1.5, .000001)` before terminating? You\n# should count your starting $w_0$ as your first step.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 9\n#\n# Overlay the steps taken in the last exercise with a plot of $L_1(w)$ vs. $w$.\n#\n# Where does our algorithm take the largest steps? (Where does the ball move fastest down\n# the hill?)\n#\n# A) Between w = -2:-1<br>\n# B) Between w = -1:0<br>\n# C) Between w = 0:.6\n#\n# *Hint*: It may be easier to see what's going on if you only plot, for example, every 15th\n# step.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# B) The following code generates the desired figure:\n#\n# ```julia\n# wsteps = gradient_descent(C1, -2:0.01:1.5, .000001)\n# fig1 = plot(C1, -2, 1.5, xlabel=\"w\", ylabel=\"C1(w)\", leg=false)\n# for step in wsteps[1:15:end]\n#    scatter!([step[1]], [step[2]])\n# end\n# display(fig1)\n# ```\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## Functions of 2 variables and their derivatives\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# So far, we have been looking at the minimizing a loss function $L_1(w)$ that depends on a\n# single parameter, $w$. Now let's turn to the cost function $L_2(w, b)$ from a previous\n# notebook, that is a function of *two* parameters, $w$ and $b$, and try to minimize it.\n#\n# As we've seen, we get a **surface**, instead of a curve, when we graph $L_2$ as a function\n# of both of its parameters.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# **Exercise 10**\n#\n# Draw a surface plot of $L_2$, given by\n#\n# $$L_{2}(w, b) = \\sum_i(y_i - g(x_i, w, b))^2$$\n#\n# using the `surface` function from `Plots.jl`. For this plot, use the values of `xs` and\n# `ys` from notebook 5:\n#\n# ```julia\n# xs = [2, -3, -1, 1]\n# ys = [0.8, 0.3, 0.4, 0.4]\n# ```\n#\n# We can get a nice interactive 3D plot by using the Plotly backend of `Plots.jl` by\n# executing the command\n#\n#     plotly()\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ### Finding the minimum\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# We can just about see, by rotating the graph, that $L_2$ has a single minimum. We want to\n# find the values of $w$ and $b$ where this minimum value is reached.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Following what we did for the function $L_1$ above, we expect that we will need to\n# calculate derivatives of $L_2$. Since the function is more complicated, though, the\n# derivatives are too!\n#\n# It turns out that the right concept is that of the\n# [**gradient**](https://en.wikipedia.org/wiki/Gradient) of $L_2$, denoted $\\nabla L_2(w,\n# b)$. This is a **vector** consisting of $2$ numbers if there are $2$ parameters [or, in\n# general, $n$ numbers if there are $n$ parameters].\n#\n# The numbers that form the gradient $\\nabla L_2(w, b)$ are called the **partial\n# derivatives** of $L_2$ with respect to $w$ and $b$,  written as\n#\n# $$\\frac{\\partial L_2}{\\partial w} \\quad \\text{and} \\quad \\frac{\\partial L_2}{\\partial\n# b}.$$\n#\n# Although this notation might look complicated, all it means is that we calculate\n# derivatives just like we did before, except that we fix the value of the other variable.\n# For example, to calculate $\\frac{\\partial L_2}{\\partial w}$, the partial derivative of\n# $L_2$ with respect to $w$, we fix the value of $b$ and think of the resulting function as\n# a function of the single variable $w$; then we use the formula for derivatives of\n# functions of a single variable.\n#\n# [Note that $\\frac{\\partial L_2}{\\partial w}$ is itself a function of $w$ and $b$; we could\n# write $\\frac{\\partial L_2}{\\partial w}(w, b)$.]\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 11\n#\n# Write functions that will allow you to calculate the partial derivatives of a function $f$\n# of two variables.\n#\n# In particular, declare functions called `partial_w` and `partial_b`. Each should take four\n# inputs - a function $f$ of two variables, the first input argument to $f$, the second\n# input argument to $f$, and a step size `h` with default value `0.001`. `partial_w` should\n# return the partial derivative of $f$ with respect to its first input argument and\n# `partial_b` should return the partial derivative of $f$ with respect to its second input\n# argument.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 12\n#\n# Use `partial_b` from the last exercise to find the partial derivative of $L_2$ with\n# respect to $w$ at b = 0.3, $\\frac{\\partial L_2}{\\partial w}|_{b = 0.3}$ for `w =\n# -2:0.01:1`\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 13\n#\n# Plot the cross section of the surface of $L_2(w, b)$ at $b = 0.3$. Make this plot\n# interactive with `@manipulate` to show that the function `partial_w` gives the slope of\n# the tangent to this cross section for any point `w` in the range `-2:0.01:1`.\n#\n# For what value of $w$ in this range is the slope of the cross section closest to -1?\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## ***Optional**: Functions with $n$ inputs\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# If a function $f$ takes $n$ input arguments, we can write them as $p_1, \\ldots, p_n$,\n# where $p_i$ means the \"$i$th parameter\". In Julia, we can wrap them up into a single\n# **vector**. Now we can calculate the partial derivative $\\frac{\\partial L_2}{\\partial\n# p_i}$ with respect to the $i$th variable.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 14\n#\n# For the next exercise, you will need to use the splat command, `...`. You can use this\n# command to \"open up\" a collection and pass all the elements of that collection as inputs\n# to a function.\n#\n# For example, say you have an array, `numbers`,\n#\n# ```julia\n# numbers = [4, 3, 2]\n# ```\n#\n# and you want to use `numbers` to create a $4\\times3\\times3$ randomly populated array via\n# `rand`. `rand(numbers)` will not do what you want. You could index into `numbers` to grab\n# the values you want and pass them to `rand`, as in\n#\n# ```julia\n# rand(numbers[1], numbers[2], numbers[3])\n# ```\n#\n# or you could use a splat:\n#\n# ```julia\n# rand(numbers...)\n# ```\n#\n# Use `...` to pass the contents of `inputs`\n#\n# ```julia\n# inputs = [30, 12, \"cats\"]\n# ```\n#\n# to the function `dreams`\n#\n# ```julia\n# dreams(i, j, perfect_mammal) = \"I wish I had $(i + j) $perfect_mammal.\"\n# ```\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 15:\n#\n# Write a function, `partial`, to calculate the $i$th partial derivative of a function. This\n# function should have four inputs\n#\n# * a function, $f$, for which you want to compute the partial derivative\n# * an array, *p*, specifying the values of all input arguments to $f$ at the point where\n# you want $\\frac{\\partial f}{\\partial p_i}$ computed\n# * the index, $i$, of the variable with respect to which you want to calculate the partial\n# derivative of $f$\n# * a step size with default value 0.001\n#\n# Hint: you will need to `copy` and modify `p` within `partial`.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## Gradient descent in 2 dimensions\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# It turns out that the gradient vector of the function $L_2(w, b)$ gives the direction in\n# the plane $(w, b)$ in which the function $L_2$ **increases fastest**.\n#\n# In other words, if you start at the position $(w_0, b_0)$ and take a small step of length\n# $\\eta$ to new values $(w', b')$, the value of the function will change to a new value\n# $L_2(w', b')$. How do we get to the minimum of $L_2(w, b)$ as fast as possible? We want to\n# step in the direction where $L_2$ decreases fastest!\n#\n# In multivariable calculus courses, it is shown that $L_2$ will *increase* fastest if you\n# take a step **in the direction of the gradient $\\nabla L_2(w, b)$**! To decrease $L_2$ the\n# fastest, we should take a step in the *opposite* direction, $-\\nabla L_2(w, b)$.\n#\n# Let's now generalize the gradient descent algorithm that we wrote previously to work our\n# 2-dimensional function.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 16\n#\n# Extend your 1D implementation of `gradient_descent` so that it will minimize the function\n# $L_2$.\n#\n# Requirements:\n#\n# * Your new method for `gradient_descent` will take four input arguments: the function $f$\n# for which you seek the minimum, the range of values for $f$'s first input argument that\n# you will consider, the range of values for $f$'s second input argument that you will\n# consider, and a tolerance that will specify the maximum allowable step size, $\\sum_i \\eta\n# \\frac{\\partial f}{\\partial p_i}$\n#\n# * Use $\\eta = .01$. For example, for a function $f(w, b)$, update $w$ such that $w_{n+1} =\n# w_n - 0.01 * \\frac{\\partial f}{\\partial w_n}$\n#\n# * Seed `gradient_descent` with the starting coordinates [-2.0, -2.0], i.e. $w_0 = -2.0$\n# and $b_0 = -2.0$.\n#\n# * Return all steps (their coordinates) taken during gradient descent and the values of the\n# loss function at these coordinates.\n#\n# Once you have done this, execute\n#\n# ```julia\n# gradient_descent(L2, -2:0.02:2, -2:0.02:2, .001)\n# ```\n#\n# How many steps were taken by gradient descent?\n#\n# Hint: Do not count your starting coordinates `[-2.0, -2.0]` as a step.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 17\n#\n# Use the `surface` and `scatter!` commands to illustrate the path taken by\n# `gradient_descent` from [-2.0, -2.0] to wherever the algorithm terminates.\n#\n# Where do the scattered points representing the steps of gradient descent appear the most\n# dense?\n#\n# A) Near the starting point at [-2.0, -2.0]<br>\n# B) Near the point [-1.8, 0] where $C_2$ appears nearly flat<br>\n# C) Near the minimum of $C_2$\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## What we have learnt\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# To recap, in this notebook, we have seen that the computer can calculate approximate\n# derivatives, and that we can use those inside a relatively simple algorithm, gradient\n# descent, to minimize functions of 1 and 2 variables!\n#\n# Now that we've used gradient descent to **learn** the best values of `b` and `w` for a\n# cost function, we can imagine how we could do our classification of apples vs. bananas by\n# allowing the machine to choose our parameters! To do this, we need to define a loss\n# function for apple vs. banana classification, using images that have already been\n# categorised as apples or bananas.\n# ------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "0cc968433f56b20bc5503948a20b3d448649dbfa", "size": 24437, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/10. Tools - Minimizing functions - how a computer learns.jl", "max_stars_repo_name": "grenkoca/JuliaTutorials", "max_stars_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 535, "max_stars_repo_stars_event_min_datetime": "2020-07-15T14:56:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T12:50:32.000Z", "max_issues_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/10. Tools - Minimizing functions - how a computer learns.jl", "max_issues_repo_name": "grenkoca/JuliaTutorials", "max_issues_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2018-02-25T22:53:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-14T02:15:50.000Z", "max_forks_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/10. Tools - Minimizing functions - how a computer learns.jl", "max_forks_repo_name": "grenkoca/JuliaTutorials", "max_forks_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 394, "max_forks_repo_forks_event_min_datetime": "2020-07-14T23:22:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:12:57.000Z", "avg_line_length": 48.4861111111, "max_line_length": 92, "alphanum_fraction": 0.4716209027, "num_tokens": 5133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.7872607311449356}}
{"text": "# L-infinity norm\n\nexport NormLinf\n\n\"\"\"\n**``L_∞`` norm**\n\n    NormLinf(λ=1.0)\n\nReturns the function\n```math\nf(x) = λ⋅\\\\max\\\\{|x_1|, …, |x_n|\\\\},\n```\nfor a nonnegative parameter `λ`.\n\"\"\"\nNormLinf(lambda::R=1.0) where {R <: Real} = Conjugate(IndBallL1(lambda))\n\nfunction (f::Conjugate{IndBallL1{R}})(x::AbstractArray{S}) where {R <: Real, S <: RealOrComplex}\n  return (f.f.r)*norm(x, Inf)\nend\n\nfunction gradient!(y::AbstractArray{T}, f::Conjugate{IndBallL1{R}}, x::AbstractArray{T}) where {T <: RealOrComplex, R <: Real}\n  absxi, i = findmax(abs.(x)) # Largest absolute value\n  y .= 0\n  y[i] = f.f.r*sign(x[i])\n  return f.f.r*absxi\nend\n\nfun_name(f::Postcompose{Conjugate{IndBallL1{R}}, R}) where {R <: Real} = \"weighted L-infinity norm\"\nfun_expr(f::Postcompose{Conjugate{IndBallL1{R}}, R}) where {R <: Real} = \"x ↦ λ||x||_∞ = λ⋅max(abs(x))\"\nfun_params(f::Postcompose{Conjugate{IndBallL1{R}}, R}) where {R <: Real} = \"λ = $(f.a*(f.f.f.r))\"\n", "meta": {"hexsha": "a76b8a012d7eb2b652e64a8ba62ec289a3d80e6b", "size": 937, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/normLinf.jl", "max_stars_repo_name": "lostella/ProximalOperators.jl", "max_stars_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-15T13:57:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T13:57:52.000Z", "max_issues_repo_path": "src/functions/normLinf.jl", "max_issues_repo_name": "lostella/ProximalOperators.jl", "max_issues_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/normLinf.jl", "max_forks_repo_name": "lostella/ProximalOperators.jl", "max_forks_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.28125, "max_line_length": 126, "alphanum_fraction": 0.6296691569, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129327, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7872607279931982}}
{"text": "using SpecialFunctions # for gamma function reasons\nusing LinearAlgebra    # for Gauss quadrature\nusing OffsetArrays     # for notational clarity\nusing SparseArrays     # for data structures\n\nusing GLMakie          # plotting\nusing LaTeXStrings     # plotting\n\n\"\"\"\nunimesh1D(xmin, xmax, K)\n# Description\n    Generates a uniform 1D mesh\n# Arguments\n    xmin: smallest value of array\n    xmax: largest values of array\n    K: number of elements in an array\n# Return Values: VX, EtoV\n    VX: vertex values | an Array of size K+1\n    EtoV: element to node connectivity | a Matrix of size Kx2\n# Example\nxmin = -1\nxmax =  1\nK    =  4\nVX, EtoV = unimesh1D(xmin, xmax, K)\n\"\"\"\nfunction unimesh1D(xmin, xmax, K)\n    VX = collect(0:K) ./ K .* (xmax - xmin) .+ xmin\n    EtoV = Int.(ones(K, 2))\n    for i = 1:K\n        EtoV[i,1] = Int(i)\n        EtoV[i,2] = Int(i+1)\n    end\n    return VX, EtoV\nend\n\n# Mathy aliases\nconst Γ = gamma\n\n# Coefficients in the Jacobi polynomial recurrence relations.\naᴾ(α, β, n) = 2/(2n+α+β) * √(n * (n+α+β) * (n+α) * (n+β) / (2n+α+β-1) / (2n+α+β+1))\nbᴾ(α, β, n) = -(α^2 - β^2) / (2n+α+β) / (2n+α+β+2)\n\n# code checked against the matlab code\n\"\"\"\njacobi(x, α, β, n)\n# Description\n- Evaluates the jacobi polynomial at the point x\n# Arguments\n- `x`: point at which you will evaluate the jacobi polynomial\n- `α`: first parameter for Jacobi polynomials\n- `β`: second parameter for Jacobi polynomials\n- `n` : order\n# Return\n-  `y`: the value of the of the Jacobi polynomial\n\"\"\"\nfunction jacobi(x, α, β, n::Int)\n    Pᵅᵝ = n <= 1 ? OffsetArray(zeros(2), 0:1) : OffsetArray(zeros(n+1), 0:n)\n    Pᵅᵝ[0] = √(2.0^-(α+β+1) * Γ(α+β+2) / Γ(α+1) / Γ(β+1))\n    Pᵅᵝ[1] = Pᵅᵝ[0]/2 * √((α+β+3) / (α+1) / (β+1)) * ((α+β+2)*x + α - β)\n    for n′ in 1:n-1\n        Pᵅᵝ[n′+1] = ((x - bᴾ(α,β,n′)) * Pᵅᵝ[n′] - aᴾ(α,β,n′) * Pᵅᵝ[n′-1]) / aᴾ(α, β, n′+1)\n    end\n    return Pᵅᵝ[n]\nend\n\n\"\"\"\ndjacobi(x, α, β, n)\n# Description\n- Evaluates the derivative of the jacobi polynomial at the point x\n# Arguments\n- `x`: point at which you will evaluate the derivative of the jacobi polynomial\n- `α`: first parameter for Jacobi polynomials\n- `β`: second parameter for Jacobi polynomials\n- `n` : order\n# Return\n-  `y`: the derivative of the of the Jacobi polynomial\n\"\"\"\ndjacobi(x, α, β, n::Int) = √(n * (n+α+β+1)) * jacobi(x, α+1, β+1, n-1)\n\n\"\"\"\nvandermonde(x, α, β, N)\n# Description\n    Return vandermonde matrix of order N at the values x\n    Allocates a little bit of memory\n# Arguments\n-   `x`: points at which to evaluate the Jacobi polynomials\n-   `α`: first parameter for Jacobi polynomials\n-   `β`: second parameter for Jacobi polynomials\n-   `N`: maximum order of Jacobi polynomial to include\n# Return Values\n-   `v`: vandermonde matrix\n# Example\n    See LegendreTests.jl\n\"\"\"\nfunction vandermonde(x, α, β, N)\n    # compute first two coefficients\n    γ0 = 2^(α + β + 1) * factorial(α) * factorial(β) / ((α + β + 1) * factorial(α + β))\n    γ1 = (α + 1) * (β + 1) / (α + β + 3) * γ0\n\n    # create view to assign values\n    v = zeros(length(x), N+1)\n    v1 = view(v, :, 1)\n    @. v1 = 1 / sqrt(γ0)\n\n    # explicitly compute second coefficient\n    if N == 0\n        return v\n    end\n\n    v2 = view(v, :, 2)\n    @. v2 = ( (α + β + 2) * x/2 + (α - β)/2) / sqrt(γ1)\n\n    if N == 1\n        return v\n    end\n\n    aʲ = 2 / (2 + α + β) * sqrt((α+1) * (β+1) / (α + β + 3))\n\n    for i in 3:(N+1)\n        # get views for ith, i-1th, and i-2th columns\n        vi = view(v, :, i)\n        vM1 = view(v, :, i-1)\n        vM2 = view(v, :, i-2)\n\n        # compute new a and b values\n        h1 = 2 * (i-2) + α + β\n        aⁱ = 2 / (h1 + 2) * sqrt((i-1) * (i-1 + α + β) * (i-1 + α) * (i-1 + β) / ((h1 + 1) * (h1 + 3)))\n        bⁱ = - (α^2 - β^2) / (h1 * (h1 + 2))\n\n        # compute coefficients for ith column\n        @. vi = 1 / aⁱ * (-aʲ * vM2 + (x - bⁱ) * vM1)\n\n        # save a coefficient for next iteration\n        aʲ = aⁱ\n    end\n\n    return v\nend\n\n\"\"\"\ndvandermonde(x, α, β, N)\n# Description\n    Return the gradient of the vandermonde matrix of order N at the values x\n    Allocates a little bit of memory\n# Arguments\n-   `x`: points at which to evaluate the Jacobi polynomials\n-   `α`: first parameter for Jacobi polynomials\n-   `β`: second paramater for Jacobi polynomials\n-   `N`: maximum order of Jacobi polynomial to include\n# Return Values\n-   `vr`: gradient of vandermonde matrix\n# Example\n    See LegendreTests.jl\n\"\"\"\nfunction dvandermonde(x, α, β, N)\n    # create empty matrix (also handles first set of derivatives)\n    vr = zeros(length(x), N+1)\n\n    if N == 0\n        return vr\n    end\n\n    # set values using vandermonde matrix\n    v = vandermonde(x, α+1, β+1, N)\n    for i in 1:N\n        vi = view(v, :, i)\n        vrP1 = view(vr, :, i+1)\n        @. vrP1 = sqrt(i * (α + β + i+1)) * vi\n    end\n\n    return vr\nend\n\n\"\"\"\ndmatrix(x, α, β, N)\n# Description\n    Return the differentiation matrix of order N at the values x\n    Allocates too much memory\n# Arguments\n-   `x`: points at which to evaluate the Jacobi polynomials\n-   `α`: first parameter for Jacobi polynomials\n-   `β`: second paramater for Jacobi polynomials\n-   `N`: maximum order of Jacobi polynomial to include\n# Return Values\n-   `D`: the differentiation matrix\n# Example\n    See LegendreTests.jl\n\"\"\"\nfunction dmatrix(x, α, β, N)\n    # calculate vandermonde matrix and grad of vandermonde matrix\n    vr = dvandermonde(x, α, β, N)\n    v  =  vandermonde(x, α, β, N)\n\n    # calculate values using D = vr * v^-1\n    d = vr / v\n\n    return d\nend\n\n\"\"\"\nlift1D(V, y)\nfor computing fluxes\nhelps compute a surface integral of a quantity\nnote that the parentheses are necessary to prevent too much multiplcation\nthe E function takes the surface integrals are presents it\nwith respect to the full space inside an element\nthe entire operator represents how fluxes flow\ninto the interior of an element\n\"\"\"\nfunction lift1D(V)\n    m,n = size(V)\n\n    E = zeros(m , 2)\n    E[1,1] = 1.0\n    E[m,2] = 1.0\n\n    return V * (transpose(V) * E)\nend\n\n\"\"\"\nlift1D_v2(V, y)\nfor computing fluxes\nnodal form\nhelps compute a surface integral of a quantity\nnote that the parantheses are necessary to prevent too much multiplcation\nthe E function takes the surface integrals are presents it\nwith respect to the full space inside an element\nthe entire operator represents how fluxes flow\ninto the interior of an element\n\"\"\"\nfunction lift1D_v2(V)\n    m,n = size(V)\n\n    E = zeros(m , 2)\n    E[1,1] = 1.0\n    E[m,2] = 1.0\n\n    return E\nend\n\n\n\"\"\"\njacobiGQ(α, β, N)\n# Description\n    Guass Quadrature points and weights for the Jacobi Polynomial (α,β)\n# Input\nα, β: Jacobi polynomial descriptors\nN:    order of quadrature points\n# Return: x,w\nx: quadrature points | array of size N+1\nw: quadrature weights | array of size N+1\n#Example\nα = 0\nβ = 0\nN = 4\nx, w = jacobiGQ(α, β, N)\n\"\"\"\nfunction jacobiGQ(α, β, N)\n    N == 0 && return [(α-β) / (α+β+2)], [2]\n\n    # Form symmetric matrix from recurrence.\n    dv = OffsetArray(zeros(N+1), 0:N)  # diagonal vector\n    ev = OffsetArray(zeros(N+1), 0:N)  # sub/super-diagonal vector\n\n    for n in 0:N\n        dv[n] = bᴾ(α, β, n)\n        ev[n] = aᴾ(α, β, n)\n    end\n\n    # Create full matrix combining the two.\n    # Need to pass arrays that are not offset.\n    J = SymTridiagonal(dv[0:N], ev[1:N])\n    (α + β) ≈ 0 && (J[1, 1] = 0)\n\n    # Compute quadrature points and weights by eigenvalue solve.\n    x, V = eigen(J)\n    w = @. V[1, :]^2 * 2^(α+β+1) / (α+β+1)\n    @. w *= factorial(α) * factorial(β) / factorial(α+β)\n\n    return x, w\nend\n\n\"\"\"\njacobiGL(α, β, N)\n# Description\n    Guass Labatto quadrature points for the Jacobi Polynomial (α,β)\n    The quadrature weights are computed as well (but not returned)\n# Arguments\n- `α, β`: Jacobi polynomial descriptors\n- `N`:    order of quadrature\n# Return: x\n- `x`: quadrature points  | array of size N+1\n# Examples\n```julia-repl\njulia> x = jacobiGL(0, 0, 4)\n5-element Array{Float64,1}:\n -1.0\n -0.6546536707079759\n  4.440892098500626e-16\n  0.6546536707079771\n  1.0\n```\n\"\"\"\nfunction jacobiGL(α, β, N)\n    N == 0 && error(\"What are you doing? Go back to finite volume land.\")\n    N == 1 && return [-1, 1]\n\n    x = zeros(N+1)\n    x[1], x[N+1] = -1, 1\n\n    x_GQ, _ = jacobiGQ(α+1, β+1, N-2)\n    x[2:N] .= x_GQ\n\n    return x\nend\n\nabstract type AbstractMesh end\n\n\"\"\"\ngridvalues1D(xmin, xmax, K)\n\n# Description\n\n    Generates physical gridpoints with each element\n\n# Arguments\n\n    VX: vertex values | an Array of size K+1\n\n    EtoV: element to node connectivity | a Matrix of size Kx2\n\n    r: LGL nodes in reference element | an array\n\n# Return Values: x\n\n    x: physical coordinates of solution\n\n# Example (uses ../utils.jl as well)\n\nxmin = 0\nxmax = 2π\nK = 4\n# call functions\nVX, EtoV = unimesh1D(xmin, xmax, K)\nr = jacobiGL(0, 0, 4)\nx = gridvalues1D(VX, EtoV, r)\n# x[:,1] is the physical coordinates within the first element\n# for plotting\nf(x) = sin(x)\nplot(x, f.(x))\n# scatter(x,f.(x)) tends to work better\n\"\"\"\nfunction gridvalues1D(VX, EtoV, r)\n    # get low and high edges\n    va = view(EtoV, :, 1)\n    vb = view(EtoV, :, 2)\n\n    # compute physical coordinates of the grid points\n    x = ones(length(r),1) * (VX[va]') .+ 0.5 .* (r .+ 1 ) * ((VX[vb] - VX[va])')\n    return x\nend\n\n\"\"\"\nfacemask1D(r)\n\n# Description\n\n    creates face mask\n\n# Arguments\n\n    r: GL points\n\n# Return Values: x\n\n    fmask1: standard facemask\n    fmask2: alternate form\n\n# Example | ../utils.jl\n\nr = jacobiGL(0, 0, 4)\nfmask = fmask1D(r)\n\n\"\"\"\nfunction fmask1D(r)\n    # check if index is left or right edge\n    fm1 = @. abs(r+1) < eps(1.0);\n    fm2 = @. abs(r-1) < eps(1.0);\n    fmask1 = (fm1,fm2)\n\n    # alternate form\n    tmp = collect(1:length(r))\n    fmask2  = [tmp[fm1]; tmp[fm2]]\n\n    fmask = (fmask1, fmask2)\n    return fmask\nend\n\n\"\"\"\nedgevalues1D(fmask, x)\n\n# Description\n\n    calculates edge values\n\n# Arguments\n\n    fmask: face mask for GL edges\n\n    x:  physical coordinates of solution on each element\n\n# Return Values: x\n\n    fx: face values of x\n\n# Example | ../utils.jl\n\nr = jacobiGL(0, 0, 4)\nx = gridvalues1D(VX, EtoV, r)\nfmask = fmask1D(r)[1]\nfx = edgevalues1D(fmask,x)\n\n# the locations of the edges in element 1 is fx[:, 1]\n\n\n\"\"\"\nfunction edgevalues1D(fmask, x)\n    # compute x values at selected indices\n    fx1 = x[fmask[1],:]\n    fx2 = x[fmask[2],:]\n\n    # return list of physical edge positions\n    fx = [fx1; fx2]\n    return fx\nend\n\n\"\"\"\nnormals1D(K)\n\n# Description\n\n    calculates face normals\n\n# Arguments\n\n    K: number of elements\n\n# Return Values: normals\n\n    normals: face normals along each grid\n\n# Example\n\n\"\"\"\nfunction normals1D(K)\n    normals  = ones(2,K)\n    @. normals[1,:] *= -1\n    return normals\nend\n\n\"\"\"\ngeometric_factors(x, Dʳ)\n\n# Description\n\n    computes the geometric factors for local mappings of 1D elements\n\n# Arguments\n\n    x: physical coordinates of solution for each element\n\n    Dʳ:\n\n# Return Values: rx, J\n\n    rx: inverse jacobian\n\n    J: jacobian (in 1D a scalar)\n\n# Example\n\n\"\"\"\nfunction geometric_factors(x, Dʳ)\n    J = Dʳ * x\n    rx = 1 ./ J # for 1D\n    return rx, J\nend\n\n\"\"\"\nconnect1D(EtoV)\n\n# Description\n\n    builds global connectivity arrays for 1D\n\n# Arguments\n\n    EtoV: element to node connectivity | a Matrix of size Kx2\n\n# Return Values: EtoE, EtoF\n\n    EtoE: element to element connectivity\n    EtoF: element to face connectivity\n\n# Example\n\n\"\"\"\nfunction connect1D(EtoV)\n    nFaces = 2 # for 1d elements\n\n    # Find number of elements and vertices\n    K = size(EtoV,1)\n    total_faces = nFaces * K\n    Nv = K+1\n\n    # list of local face to local vertex connections\n    vn = [1, 2]\n\n    # build global face to vertex array\n    FtoV = Int.(spzeros(total_faces, Nv))\n    let sk = 1\n        for k = 1:K\n            for faces = 1:nFaces\n                FtoV[sk, EtoV[k, vn[faces]]] = 1;\n                sk += 1\n            end\n        end\n    end\n\n    # build global face to face array\n    FtoF = FtoV * (FtoV') - sparse(I, total_faces, total_faces)\n\n    # find all face to face connections\n    # check\n    #(faces1, faces2) = findnz(FtoF)\n    faces1, faces2 = findnz(FtoF .== 1)\n\n    # convert global face number to element and face numbers\n    element1 = @. floor(Int, (faces1 - 1) / nFaces) + 1\n    face1    = @. Int( mod( (faces1 - 1),  nFaces) + 1)\n    element2 = @. floor(Int, (faces2 - 1) / nFaces) + 1\n    face2    = @. Int( mod( (faces2 - 1),  nFaces) + 1)\n\n    # Rearrange into Nelement x Nfaces sized arrays\n    ind = diag( LinearIndices(ones(K, nFaces))[element1,face1] ) # this line is a terrible idea.\n    EtoE = collect(1:K) * ones(1, nFaces)\n    EtoF = ones(K, 1) * (collect(1:nFaces)')\n    EtoE[ind] = copy(element2);\n    EtoF[ind] = face2;\n    return EtoE, EtoF\nend\n\n\"\"\"\nbuildmaps1D(K, nGL, nFP, nFaces, fmask, EtoE, EtoF, x)\n# Description\n\n    connectivity matrices for element to elements and elements to face\n\n# Arguments\n\n-   `K`: number of elements\n-   `nGL`: number of points within an element (polynomial degree + 1)\n-   `nFP`: 1\n-   `nFaces`: 2\n-   `fmask`: an element by element mask to extract edge values\n-   `EtoE`: element to element connectivity\n-   `EtoF`: element to face connectivity\n-   `x`: Guass lobatto points\n\n# Return Values: vmapM, vmapP, vmapB, mapB, mapI, mapO, vmapI, vmapO\n\n-   `vmapM`: vertex indices, (used for interior u values)\n-   `vmapP`: vertex indices, (used for exterior u values)\n-   `vmapB`: vertex indices, corresponding to boundaries\n-   `mapB`: use to extract vmapB from vmapM\n-   `mapI`: Index of left boundary condition\n-   `mapO`: Index of right boundary condition\n\n# Example | uses ../utils.jl\n\nK = 3\nn = 3; α = 0; β = 0; xmin = 0; xmax = 2π;\nnGL = n + 1\nnFP = 1\nnFaces = 2\n\nr = jacobiGL(α, β, n)\n\nVX, EtoV = unimesh1D(xmin, xmax, K)\nEtoE, EtoF = connect1D(EtoV)\nx = gridvalues1D(VX, EtoV, r)\nfx = edgevalues1D(r,x)\n\nvmapM, vmapP, vmapB, mapB, mapI, mapO, vmapI, vmapO = buildmaps1D(K, nGL, nFP, nFaces, fmask, EtoE, EtoF, x)\n\"\"\"\nfunction buildmaps1D(K, nGL, nFP, nFaces, fmask, EtoE, EtoF, x)\n    # number volume nodes consecutively\n    nodeids = reshape(collect(1:(K*nGL)), nGL, K)\n    vmapM = zeros(nFP, nFaces, K)\n    vmapP = zeros(nFP, nFaces, K)\n    # find index of face nodes wrt volume node ordering\n    for k1 in 1:K\n        for f1 in 1:nFaces\n            vmapM[:, f1, k1] = nodeids[fmask[f1], k1]\n        end\n    end\n\n    for k1 = 1:K\n        for f1 = 1:nFaces\n            # find neighbor\n            k2 = Int.( EtoE[k1, f1])\n            f2 = Int.( EtoF[k1, f1])\n\n            # find volume node numbers of left and right nodes\n            vidM = Int.( vmapM[:, f1, k1])\n            vidP = Int.( vmapM[:, f2, k2])\n\n            x1 = x[vidM]\n            x2 = x[vidP]\n\n            # compute distance matrix\n            # need to figure out this part\n            D = @. (x1 - x2)^2\n            m = length(x1)\n            for j = 1:m\n                if D[j] < eps(1.0)*10^5\n                    vmapP[j, f1, k1] = vidP[j]\n                end\n            end\n        end\n    end\n\n    # reshape arrays\n    vmapP = Int.( reshape(vmapP, length(vmapP)) )\n    vmapM = Int.( reshape(vmapM, length(vmapM)) )\n\n    # Create list of boundary nodes\n    mapB = Int.( collect(1:length(vmapP))[vmapP .== vmapM] )\n    vmapB = Int.( vmapM[mapB] )\n\n    # inflow and outflow maps\n    mapI = 1\n    mapO = K * nFaces\n    vmapI = 1\n    vmapO = K*nGL\n    return vmapM, vmapP, vmapB, mapB, mapI, mapO, vmapI, vmapO\nend\n\n\"\"\"\nmake_periodic1D!(vmapP, u)\n\n# Description\n\n    makes the grid periodic by modifying vmapP.\n    Assumes that the first node is connected to the last.\n\n# Arguments\n\n    vmapP: exterior vertex map\n    u: vertex vector\n\n# Return Values: none\n\n# Example\n\n\"\"\"\nfunction make_periodic1D!(vmapP, u)\n    vmapP[1] = length(u)\n    vmapP[end] = 1\n\n    return nothing\nend\n\nstruct Mesh{T,S,U,W} <: AbstractMesh\n    # inputs\n    K::S\n    n::S\n\n    # face stuff\n    nFP::S\n    nFaces::S\n\n    # GL points\n    r::U\n    x::T\n\n    # vertex maps\n    vmapM::W\n    vmapP::W\n    vmapB::W\n    mapB::W\n\n    # inflow/outflow maps\n    mapI::S\n    mapO::S\n    vmapI::S\n    vmapO::S\n\n    # structures for computation\n    D::T\n    M::T\n    Mi::T\n    lift::T\n    rx::T\n    normals::T\n    fscale::T\nend\n\n\"\"\"\nmesh(K, n, xmin, xmax)\n\n# Description\n\n    outer_constructor mesh struct\n\n# Arguments\n\n- `K`: number of elements\n- `n`: polynomial order\n- `xmin`: lower bound\n- `xmax`: upper bound\n\n\n# Return Values: x\n    return grid values\n\n\"\"\"\nfunction Mesh(KK, nn, xmin, xmax; periodic = false)\n    # initialize parameters\n    K = KK\n    α = 0; β = 0;\n    n = nn\n\n    # number of vertices\n    nGL = n+1\n    nFP = 1\n    nFaces = 2\n\n    # compute Gauss Lobatto grid\n    r = jacobiGL(α, β, n)\n\n    # build grid\n    VX, EtoV = unimesh1D(xmin, xmax, K)\n\n    # build coordinates of all the nodes\n    x = gridvalues1D(VX, EtoV, r)\n\n    # build connectivity matrix\n    EtoE, EtoF = connect1D(EtoV)\n\n    # build face masks\n    fmask1,fmask2 = fmask1D(r)\n\n    # build connectivity maps\n    vmapM,vmapP,vmapB,mapB, mapI,mapO,vmapI,vmapO = buildmaps1D(K, nGL,nFP,nFaces, fmask1, EtoE,EtoF, x)\n\n    # build differentiation matrix\n    D = dmatrix(r, α, β, n)\n\n    # build surface integral terms\n    V = vandermonde(r, α, β, n)\n    lift = lift1D(V)\n\n    # build mass matrix and inverse of mass matrix\n    Mi = V * V'\n    M = inv(Mi)\n\n    # calculate geometric factors\n    rx,J = geometric_factors(x, D)\n\n    # build surface normals\n    normals = normals1D(K)\n\n    # build inverse metric at the surface\n    fscale = 1 ./ J[fmask2,:]\n\n    # hack for periodicity\n    if periodic\n        vmapP[1] = vmapM[end]\n        vmapP[end] = vmapM[1]\n    end\n\n    return Mesh{typeof(x),typeof(K),typeof(r),typeof(vmapP)}(K, n, nFP, nFaces, r, x, vmapM, vmapP, vmapB, mapB, mapI, mapO, vmapI, vmapO, D, M, Mi, lift, rx, normals, fscale)\nend\n\nfunction compute_volume_terms(data::AbstractArray, mesh::Mesh)\n    q = mesh.D * data\n    @. q *= mesh.rx\n    return q\nend\n\nfunction compute_surface_terms(data::AbstractArray, 𝒢::Mesh)\n    diffs = reshape( (data[𝒢.vmapM] - data[𝒢.vmapP]), (𝒢.nFP * 𝒢.nFaces, 𝒢.K ))\n    # Include factor of 2 for the weak-strong form\n    @. diffs *= 1.0 / 2.0\n    # Compute Lift Operator\n    lifted = - 𝒢.lift * (𝒢.fscale .* 𝒢.normals .* diffs)\n    return lifted\nend", "meta": {"hexsha": "7c88566a32c8541b55af6d0a63efdea6004ce35a", "size": 18106, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "utils_dg.jl", "max_stars_repo_name": "sandreza/HeldSuarezVisualizationScripts", "max_stars_repo_head_hexsha": "904ce7f44e965618b0ba6f5fa89015ba02aaf44a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils_dg.jl", "max_issues_repo_name": "sandreza/HeldSuarezVisualizationScripts", "max_issues_repo_head_hexsha": "904ce7f44e965618b0ba6f5fa89015ba02aaf44a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils_dg.jl", "max_forks_repo_name": "sandreza/HeldSuarezVisualizationScripts", "max_forks_repo_head_hexsha": "904ce7f44e965618b0ba6f5fa89015ba02aaf44a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6608260325, "max_line_length": 175, "alphanum_fraction": 0.6063183475, "num_tokens": 6389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7872408066299628}}
{"text": "\n\n# function Crst_direct(r::Int, s::Int, t::Int)\n#     # direct method to calculate Crst\n#     # see Products of Laguerre Polynomials\n#     # Joseph Gillis and  George Weiss\n#     # Mathematics of Computation, Vol. 14, No. 69 (Jan., 1960), pp. 60-63\n#     # this function implements equation (7)\n#     # this is computationally expensive.\n#     # use recurrence relation instead.\n#     (r >= 0 && s >= 0 && t >= 0) || throw(\"negative orders not allowed.\")\n#     # t needs to be in |r-s| and r+s\n#     # otherwise the coef is zero\n#     if t < abs(r - s) || t > r + s\n#         return 0\n#     end\n\n#     p = r + s - t\n#     # define nmax and nmin and find them\n#     nmax = r\n#     if s < nmax\n#         nmax =  s\n#     end\n#     if p < nmax\n#         nmax = p\n#     end\n#     nmin = ceil(Int, p / 2)\n#     # use rational numbers for now to keep it exact.\n#     C = 0 // 1\n#     for n in nmin:nmax\n#         C += (2 // 1)^(2 * n) * factorial(r + s - n) / ( factorial(r - n) * factorial(s - n) * factorial(2n - p) * factorial(p - n))\n#     end\n#     # prefactor\n#     C *= (-1 // 2)^p\n# end\n\n\nfunction Crst(r::Int, s::Int, t::Int)\n    # this implements equation (22) and (23) in the same paper.\n    if r < 0 || s < 0 || t < 0 \n        return 0 // 1\n    end\n    # (r >= 0 && s >= 0 && t >= 0) || throw(\"negative orders not allowed.\")\n    # notice that C_{rst} is symmetric with respect to any swapping of indices.\n    # take r to be the larer one of r and s\n    # the recurrence is given for t+1\n    # shift it to calculate for t;\n    if r < s\n        r, s = s, r # swap.\n    end\n    # t needs to be in |r-s| and r+s\n    # otherwise the coef is zero\n    if t < r - s || t > r + s\n        return 0 // 1\n    end\n\n    sigma = r + s + 1 // 1\n    delta = r - s\n    if t == delta\n        return Rational(binomial(r, s))\n    end\n\n    # handle general case.\n    f1 = t * (delta^2 - t^2)\n    f2 = (2t - 1) * (delta^2 - (t - 1)^2 + t * (sigma - t ))\n    f3 = -(t - 1) * (delta^2 - (t - 2)^2 + (4t - 3) * (sigma - t + 1))\n    f4 = 2(t - 1) * (t - 2) * (sigma - t + 2)\n    return (f2 * Crst(r, s, t - 1) + f3 * Crst(r, s, t - 2) + f4 * Crst(r, s, t - 3) ) / f1\nend\n\n\n\nfunction laprodexpand(r::Int, s::Int)\n    # expand the product of two Laguerre polynomials (with coefficients being 1) into a linear\n    # combination of Laguerre polynomials.\n    # Lr(x)Ls(x) into sum_{t}C_{rst}Lt(x)\n    orders = abs(r - s):(r + s) |> collect\n    coeffs = [Crst(r, s, t) for t in orders]\n    return orders, coeffs\nend\n\n\n\n\n\nfunction Base.:*(l1::LaguerrePolynomial{T}, l2::LaguerrePolynomial{S}) where {T,S}\n    # take two linear combinations of Laguerre polynomials.\n    # and reexpand into a single Laguerre polynomial series.\n    lst = []\n    R = promote_type(T, S)\n    for (r, c1) in l1\n        for (s, c2) in l2\n            # construct the product \n            orders, coeffs = laprodexpand(r, s)\n            # convert to type R\n            coeffs = R.(coeffs)\n            # add this to the list\n            la = LaguerrePolynomial(orders, coeffs)\n            la = la * c1 * c2\n            push!(lst, la)\n        end\n    end\n    # add elements in the list.\n    la = lst[1]\n    if length(lst) > 1\n        for i = 2:length(lst)\n            la += lst[i]\n        end\n    end\n    return la\nend", "meta": {"hexsha": "e7120d1fef9feed3d98d91cdc8bd1e70c6a2109f", "size": 3262, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lpolyprod.jl", "max_stars_repo_name": "zpeng2/Laguerre.jl", "max_stars_repo_head_hexsha": "e993b4bd894b902f4dc53b38a7010cda3ff95018", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lpolyprod.jl", "max_issues_repo_name": "zpeng2/Laguerre.jl", "max_issues_repo_head_hexsha": "e993b4bd894b902f4dc53b38a7010cda3ff95018", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lpolyprod.jl", "max_forks_repo_name": "zpeng2/Laguerre.jl", "max_forks_repo_head_hexsha": "e993b4bd894b902f4dc53b38a7010cda3ff95018", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3873873874, "max_line_length": 134, "alphanum_fraction": 0.5214592275, "num_tokens": 1126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7872407978251225}}
{"text": "\"\"\"\n    Lennard-Jones Potential\n\"\"\"\nmutable struct LennardJones <: Potential\n    ε::Float64\n    σ::Float64\nend\n\n\"\"\"\n    LennardJones(params::Dict)\n    \nCreates the LennardJones potential.\n\"\"\"\nfunction LennardJones(params::Dict)\n    # Creates the LennardJones model\n    ε = params[\"ε\"]\n    σ = params[\"σ\"]\n    return LennardJones(ε, σ)\nend\n\n\"\"\"\n    potential_energy(p::LennardJones, r::Position, args...)\n    \nCalculates LennardJones potential energy.\n\"\"\"\nfunction potential_energy(p::LennardJones, r::Position, args...)\n    return 4.0 * p.ε * ((p.σ / norm(r))^12 - (p.σ / norm(r))^6)\nend\n\n", "meta": {"hexsha": "83e3cbc27a3872cb2d64f335b4c4c600d0f54c9e", "size": 589, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Potentials/LennardJones.jl", "max_stars_repo_name": "cesmix-mit/PotentialLearning.jl", "max_stars_repo_head_hexsha": "931305f95df29a0648cc40b9fc3362e2065125d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-07-09T14:30:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T12:24:57.000Z", "max_issues_repo_path": "src/Potentials/LennardJones.jl", "max_issues_repo_name": "cesmix-mit/PotentialLearning.jl", "max_issues_repo_head_hexsha": "931305f95df29a0648cc40b9fc3362e2065125d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-08T21:35:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-01T17:40:57.000Z", "max_forks_repo_path": "src/Potentials/LennardJones.jl", "max_forks_repo_name": "cesmix-mit/PotentialLearning.jl", "max_forks_repo_head_hexsha": "931305f95df29a0648cc40b9fc3362e2065125d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6333333333, "max_line_length": 64, "alphanum_fraction": 0.6485568761, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.949669363129097, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.787217794184844}}
{"text": "# Polynomial mean function\n\n\"\"\"\n    MeanPoly <: Mean\n\nPolynomial mean function\n```math\nm(x) = ∑ᵢⱼ βᵢⱼxᵢʲ\n```\nwith polynomial coefficients ``βᵢⱼ`` of shape ``d × D`` where ``d`` is the dimension of\nobservations and ``D`` is the degree of the polynomial.\n\"\"\"\nmutable struct MeanPoly <: Mean\n    \"Polynomial coefficients\"\n    β::Matrix{Float64}\n    \"Priors for mean parameters\"\n    priors::Array\n\n    \"\"\"\n        MeanPoly(β::Matrix{Float64})\n\n    Create `MeanPoly` with polynomial coefficients `β`.\n    \"\"\"\n    MeanPoly(β::Matrix{Float64}) = new(β, [])\nend\n\nfunction mean(mPoly::MeanPoly, x::AbstractVector)\n    dim = length(x)\n    deg = size(mPoly.β, 2)\n    dim == size(mPoly.β, 1) || throw(ArgumentError(\"Observations and mean function have inconsistent dimensions\"))\n    return sum(dot(x.^j, mPoly.β[:,j]) for j in 1:deg)\nend\n\n\nget_params(mPoly::MeanPoly) = vec(mPoly.β)\nget_param_names(mPoly::MeanPoly) = get_param_names(vec(mPoly.β), :β)\nnum_params(mPoly::MeanPoly) = length(mPoly.β)\n\nfunction set_params!(mPoly::MeanPoly, hyp::AbstractVector)\n    length(hyp) == num_params(mPoly) || throw(ArgumentError(\"Polynomial mean function has $(num_param) parameters\"))\n    copyto!(mPoly.β, hyp)\nend\n\n\nfunction grad_mean(mPoly::MeanPoly, x::AbstractVector)\n    dim = length(x)\n    deg = size(mPoly.β, 2)\n    dM_theta = Array{Float64}(undef, dim, deg)\n    for i in 1:dim\n        for j in 1:deg\n            dM_theta[i,j] = x[i].^j\n        end\n    end\n    return vec(dM_theta)\nend\n", "meta": {"hexsha": "3c9b4c0cc7c24b04e56df0efbefb476254f32957", "size": 1471, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/means/mPoly.jl", "max_stars_repo_name": "mcusi/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 284, "max_stars_repo_stars_event_min_datetime": "2015-07-31T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T07:08:58.000Z", "max_issues_repo_path": "src/means/mPoly.jl", "max_issues_repo_name": "mcusi/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 171, "max_issues_repo_issues_event_min_datetime": "2015-05-28T12:04:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T06:48:23.000Z", "max_forks_repo_path": "src/means/mPoly.jl", "max_forks_repo_name": "mcusi/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-05-31T12:44:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:21:38.000Z", "avg_line_length": 26.2678571429, "max_line_length": 116, "alphanum_fraction": 0.6614547927, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693688269985, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7872177908815503}}
{"text": "# indexing convention for ∂G_ij/∂p^k: (i, j, k)\n# indexing convention Γ^k_ij: (i, j, k)\nfunction christoffel_symbols(pn, task::Task{<:TaskMapT{M,N,S}}, C::Chart{I,N}) where {M,N,I,S}\n    n = dim(T{N})\n    Ginv = inv(metric_chart(pn, task, C))\n    ∂G_∂xn_matrix = ForwardDiff.jacobian(pn -> reshape(metric_chart(pn, task, C), Size(n^2)), pn)\n    ∂G_∂xn_matrix == (@SMatrix zeros(n^2,n)) && return @SArray zeros(n,n,n)\n    ∂G_∂xn = reshape(∂G_∂xn_matrix, Size(n,n,n))\n    inds = static(1):static(n)\n    Γ = SArray{Tuple{n,n,n},S}([0.5*sum(Tuple(Ginv[k,l]*(∂G_∂xn[j,l,i]+∂G_∂xn[i,l,j]-∂G_∂xn[i,j,l])\n        for l in inds)) for i in inds, j in inds, k in inds])\nend\n\nfunction christoffel_symbols(pn, task::Task{<:BaseTaskMap}, CN)\n    n, S = dim(codomain_manifold(task)), eltype(pn)\n    Ginv = inv(metric_chart(pn, task, CN))\n    ∂G_∂xn_matrix = ForwardDiff.jacobian(pn -> reshape(metric_chart(pn, task, CN), Size(n^2)), pn)\n    ∂G_∂xn_matrix == (@SMatrix zeros(n^2,n)) && return @SArray zeros(n,n,n)\n    ∂G_∂xn = reshape(∂G_∂xn_matrix, Size(n,n,n))\n    inds = static(1):static(n)\n    Γ = SArray{Tuple{n,n,n},S}([0.5*sum(Tuple(Ginv[k,l]*(∂G_∂xn[j,l,i]+∂G_∂xn[i,l,j]-∂G_∂xn[i,j,l])\n        for l in inds)) for i in inds, j in inds, k in inds])\nend\n\nfunction christoffel_symbols_chart_transition(pn1, Γ1, C1::Chart{I,N},\n        C2::Chart{J,N}) where {N,I,J}\n    n, S = dim(N), eltype(pn1)\n    Γ1 == (@SArray zeros(n,n,n)) && return @SArray zeros(n,n,n)\n    pn2 = chart_transition(pn1, C1, C2)\n    ∂pn1_∂pn2 = chart_transition_jacobian(pn2, C2, C1)\n    ∂pn2_∂pn1 = inv(∂pn1_∂pn2)\n    Hpn2_pn1 = chart_transition_hessian(pn2, C2, C1)\n    inds = static(1):static(n)\n    Γ2 = SArray{Tuple{n,n,n},S}([sum(Tuple(∂pn2_∂pn1[k,l]*∂pn1_∂pn2[r,i]*∂pn1_∂pn2[s,j]*Γ1[r,s,l] \n        for l in inds, r in inds, s in inds)) + sum(Hpn2_pn1[l,i,j]*∂pn2_∂pn1[k,l] for l in inds) \n        for i in inds, j in inds, k in inds])\nend", "meta": {"hexsha": "0b198054600c997564ccf757fffba1c609a0cd99", "size": 1906, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/connections.jl", "max_stars_repo_name": "sid-dey/PBDS.jl", "max_stars_repo_head_hexsha": "d4d1d2af0753c60d7082e24c714734eb3ad5fda6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/connections.jl", "max_issues_repo_name": "sid-dey/PBDS.jl", "max_issues_repo_head_hexsha": "d4d1d2af0753c60d7082e24c714734eb3ad5fda6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/connections.jl", "max_forks_repo_name": "sid-dey/PBDS.jl", "max_forks_repo_head_hexsha": "d4d1d2af0753c60d7082e24c714734eb3ad5fda6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.5135135135, "max_line_length": 99, "alphanum_fraction": 0.6133263379, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7872177853325152}}
{"text": "#Dot product using LoopVectorization (real ⋅ real)\n\"\"\"\n    l2inner(a,b)\n\nComputes the inner product in the l2 vector space (dot product) between Real or Complex vectors `a` and `b`. The lenghts of `a` and `b` must match.\n\nSee also [`l2norm`](@ref), [`l2dist`](@ref), [`sql2norm`](@ref), [`sql2dist`](@ref).\n\n# Example\n```jldoctest\na = [1,2,3]\nb = [2,0,4]\nl2inner(a,b)\n\n# output\n\n14\n```\n\"\"\"\nfunction l2inner(a::AbstractVector{T}, b::AbstractVector{T}) where {T}\n    s = zero(T)\n    @turbo for i ∈ eachindex(a,b)\n        s += a[i] * b[i]\n    end\n    return s\nend\n\n#Dot product using LoopVectorization (real ⋅ complex)\nfunction l2inner(a::AbstractVector{T}, cb::AbstractVector{Complex{T}}) where {T}\n    re = zero(T)\n    im = zero(T)\n    b = reinterpret(reshape, T, cb)\n    @turbo for i ∈ eachindex(a)\n        re += a[i] * b[1,i]\n        im += a[i] * b[2,i]\n    end\n    return Complex(re, im)\nend\n\n#Dot product using LoopVectorization (real ⋅ complex)\nfunction l2inner(ca::AbstractVector{Complex{T}}, b::AbstractVector{T}) where {T}\n    re = zero(T)\n    im = zero(T)\n    a = reinterpret(reshape, T, ca)\n    @turbo for i ∈ eachindex(b)\n        re += a[1,i] * b[i]\n        im += - (a[2,i] * b[i])\n    end\n    return Complex(re, im)\nend\n\n#Dot product using LoopVectorization (complex ⋅ complex)\nfunction l2inner(ca::AbstractVector{Complex{T}}, cb::AbstractVector{Complex{T}}) where {T}\n    re = zero(T)\n    im = zero(T)\n    a = reinterpret(reshape, T, ca)\n    b = reinterpret(reshape, T, cb)\n    @turbo for i ∈ axes(a,2) #Conjugate(a) × b\n        re += (a[1,i] * b[1,i]) + (a[2,i] * b[2,i])\n        im += (a[1,i] * b[2,i]) - (a[2,i] * b[1,i])\n    end\n    return Complex(re, im)\nend\n\n\n#L2 Norm square using LoopVectorization (real)\n\"\"\"\n    l2inner(a)\n\nComputes the inner product in the l2 vector space (dot product) of the Real or Complex vectors `a` with itself. i.e., the Squared l2 norm of `a`. This is identical to calling `sql2norm(a)`.\n\"\"\"\nfunction l2inner(a::AbstractVector{T}) where {T}\n    s = zero(T)\n    @turbo for i ∈ eachindex(a)\n        s += a[i] * a[i]\n    end\n    return s\nend\n\n\"\"\"\n    sql2norm(a)\n\nCompute the square of the l2 norm of a real valued vector `a`. This is identical to calling `l2inner(a)`.\n\"\"\"\nsql2norm(a::AbstractVector{T}) where {T} = l2inner(a)\n\n\"\"\"\n    l2norm(a)\n\nCompute the l2 norm of a real valued vector `a`.\n\"\"\"\nl2norm(a::AbstractVector{T}) where {T} = sqrt(l2inner(a))\n\n#L2 Distance square using LoopVectorization (real)\n\"\"\"\n    sql2dist(a,b)\n\nCompute the square of the l2 distance between two real vectors `a` and `b`. The lengths of `a` and `b` must match.\n\"\"\"\nfunction sql2dist(a::AbstractVector{T}, b::AbstractVector{T}) where {T}\n    s = zero(T)\n    @turbo for i ∈ eachindex(a,b)\n        t = a[i] - b[i]\n        s += t * t\n    end\n    return s\nend\n\n\"\"\"\n    l2dist(a,b)\n\nCompute the l2 distance between two real vectors `a` and `b`. The lengths of `a` and `b` must match.\n\"\"\"\nl2dist(a::AbstractVector{T}, b::AbstractVector{T}) where {T} = sqrt(sql2dist(a,b))\n\n\n#L1 Norm of real vectors\n\"\"\"\n    l1norm(a)\n\nCompute the l1 norm of a real valued vector `a`.\n\"\"\"\nfunction l1norm(a::AbstractVector{T}) where {T}\n    s = zero(T)\n    @turbo for i ∈ eachindex(a)\n        s += abs(a[i])\n    end\n    return s\nend\n\n#L1 distance between real vectors\n\"\"\"\n    l1dist(a,b)\n\nCompute the l1 distance between two real vectors `a` and `b`. The lengths of `a` and `b` must match.\n\"\"\"\n function l1dist(a::AbstractVector{T}, b::AbstractVector{T}) where {T}\n    s = zero(T)\n    @turbo for i ∈ eachindex(a,b)\n        t = a[i] - b[i]\n        s += abs(t)\n    end\n    return s\n end", "meta": {"hexsha": "e69b8009bdeea86fc83327b26c69b955be114a9e", "size": 3591, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Lp.jl", "max_stars_repo_name": "vidhyasaharan/VectorDataUtils.jl", "max_stars_repo_head_hexsha": "aca5ae177446bf5db37f2cd823579679baa6830a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Lp.jl", "max_issues_repo_name": "vidhyasaharan/VectorDataUtils.jl", "max_issues_repo_head_hexsha": "aca5ae177446bf5db37f2cd823579679baa6830a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Lp.jl", "max_forks_repo_name": "vidhyasaharan/VectorDataUtils.jl", "max_forks_repo_head_hexsha": "aca5ae177446bf5db37f2cd823579679baa6830a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9375, "max_line_length": 189, "alphanum_fraction": 0.6087440824, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642906, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.7871672315096719}}
{"text": "#Some useful functions\n\n#Define the sigmoid function & its derivative\nsigmoid(x)  = 1.0 / (1.0 + exp(-x));\ndsigmoid(x)  = (1.0 / (1.0 + exp(-x))^2)*exp(-x);\n", "meta": {"hexsha": "1e356409f46b646c872202bfdc0ade18bd67a579", "size": 157, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nnUtils.jl", "max_stars_repo_name": "krometis/SimpleNeuralNet", "max_stars_repo_head_hexsha": "6cbcfe89c173b45b7f6f127df74935fe8f78c681", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nnUtils.jl", "max_issues_repo_name": "krometis/SimpleNeuralNet", "max_issues_repo_head_hexsha": "6cbcfe89c173b45b7f6f127df74935fe8f78c681", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nnUtils.jl", "max_forks_repo_name": "krometis/SimpleNeuralNet", "max_forks_repo_head_hexsha": "6cbcfe89c173b45b7f6f127df74935fe8f78c681", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1666666667, "max_line_length": 49, "alphanum_fraction": 0.5987261146, "num_tokens": 59, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9770226287518852, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7871208790856016}}
{"text": "function iterate(m::Integer)\n    while m != 1 && m != 89\n        s = 0\n        while m > 0 # compute sum of squares of digits\n            m, d = divrem(m, 10)\n            s += d ^ 2\n        end\n        m = s\n    end\n    return m\nend\nitercount(k::Integer) = count(x -> iterate(x) == 89, 1:k)\n", "meta": {"hexsha": "da29ca5abd0ae147375067f6a5ac74e7de182229", "size": 291, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/iterated-digits-squaring-1.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/iterated-digits-squaring-1.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/iterated-digits-squaring-1.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3846153846, "max_line_length": 57, "alphanum_fraction": 0.4673539519, "num_tokens": 96, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7871141297117226}}
{"text": "\"\"\"\nApproximates the arc length of a line segment by treating the curve as a\nsequence of linear lines and summing their lengths.\n\nArguments:\n - f: function that returns the arc\n - x_start: starting x value\n - x_end: ending x_value\n - steps: steps to take for accurace, more the steps greater the accuracy\n\"\"\"\nfunction line_length(f, x_start, x_end, steps=100)\n\tx1 = x_start\n\tfx1 = f(x1)\n\tlen = 0.0\n\n\tfor step in 1:steps\n\t\tx2 = ((x_end - x_start) / steps) + x1\n\t\tfx2 = f(x2)\n\t\tlen += hypot(x2 - x1, fx2 - fx1)\n\n\t\tx1 = x2\n\t\tfx1 = fx2\n\tend\n\n\treturn len\nend\n", "meta": {"hexsha": "0161ae01921e0f4bcb292a710cef5bfc51747a16", "size": 554, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/line_length.jl", "max_stars_repo_name": "madisonestabrook/Julia", "max_stars_repo_head_hexsha": "799508e2b8a3087bdd7fb4d2a23a2ab4788ea854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math/line_length.jl", "max_issues_repo_name": "madisonestabrook/Julia", "max_issues_repo_head_hexsha": "799508e2b8a3087bdd7fb4d2a23a2ab4788ea854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/line_length.jl", "max_forks_repo_name": "madisonestabrook/Julia", "max_forks_repo_head_hexsha": "799508e2b8a3087bdd7fb4d2a23a2ab4788ea854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5185185185, "max_line_length": 73, "alphanum_fraction": 0.6823104693, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7871141279047946}}
{"text": "# additional math functions & functors\n\nsqr(x::Number) = x * x\nrcp(x::Number) = one(x) / x\n\nrsqrt(x::Number) = one(x) / sqrt(x)\nrcbrt(x::Real) = one(x) / cbrt(x)\n\nxlogx(x::AbstractFloat) = x > zero(x) ? x * log(x) : zero(x)\nxlogx(x::Real) = xlogx(float(x))\n\nxlogy{T<:AbstractFloat}(x::T, y::T) = x > zero(T) ? x * log(y) : zero(x)\nxlogy{T<:Real}(x::T, y::T) = xlogy(float(x), float(y))\nxlogy(x::Real, y::Real) = xlogy(promote(x, y)...)\n\nlogistic(x::AbstractFloat) = rcp(one(x) + exp(-x))\nlogistic(x::Real) = logistic(float(x))\n\nlogit(x::AbstractFloat) = log(x / (one(x) - x))\nlogit(x::Real) = logit(float(x))\n\nsoftplus(x::AbstractFloat) = x <= 0 ? log1p(exp(x)) : x + log1p(exp(-x))\nsoftplus(x::Real) = softplus(float(x))\n\ninvsoftplus(x::AbstractFloat) = log(exp(x) - one(x))\ninvsoftplus(x::Real) = invsoftplus(float(x))\n\nlogsumexp{T<:AbstractFloat}(x::T, y::T) = x > y ? x + log1p(exp(y - x)) : y + log1p(exp(x - y))\nlogsumexp{T<:Real}(x::T, y::T) = logsumexp(float(x), float(y))\nlogsumexp(x::Real, y::Real) = logsumexp(promote(x, y)...)\n\n@vectorize_1arg Number sqr\n@vectorize_1arg Number rcp\n@vectorize_1arg Real rsqrt\n@vectorize_1arg Real rcbrt\n\n@vectorize_1arg Real xlogx\n@vectorize_2arg Real xlogy\n@vectorize_1arg Real logistic\n@vectorize_1arg Real logit\n@vectorize_1arg Real softplus\n@vectorize_1arg Real invsoftplus\n\nconst sigmoid = logistic\n", "meta": {"hexsha": "74d8c164b4c3605cea69b592e536705fea871e39", "size": 1349, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mathfuns.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericFuns.jl-2d52b4ab-c3e3-5ee9-8cd7-16337136d172", "max_stars_repo_head_hexsha": "0176b6febf1e543d1a735f6d151305f77a410ca3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2015-06-17T21:29:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:23:55.000Z", "max_issues_repo_path": "src/mathfuns.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/NumericFuns.jl-2d52b4ab-c3e3-5ee9-8cd7-16337136d172", "max_issues_repo_head_hexsha": "0176b6febf1e543d1a735f6d151305f77a410ca3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2015-02-10T05:11:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:33:20.000Z", "max_forks_repo_path": "src/mathfuns.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/NumericFuns.jl-2d52b4ab-c3e3-5ee9-8cd7-16337136d172", "max_forks_repo_head_hexsha": "0176b6febf1e543d1a735f6d151305f77a410ca3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2015-01-06T16:15:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-26T18:31:54.000Z", "avg_line_length": 29.9777777778, "max_line_length": 95, "alphanum_fraction": 0.6597479615, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7871141262734962}}
{"text": "# psf-gauss.jl\n\nexport psf_gauss\n\n\"\"\"\n    psf_gauss( ; nx, nx_psf, fwhm_start, fwhm_end, fwhm, T)\n\nCreate depth-dependent Gaussian PSFs\nhaving specified full-width half-maximum (FHWM) values.\n\n# Options\n- 'nx::Int = 128'\n- 'nx_psf::Int = 11' (should be odd)\n- 'fwhm_start::Real = 1'\n- 'fwhm_end::Real = 4'\n- 'fwhm::AbstractVector{<:Real} = LinRange(fwhm_start, fwhm_end, nx)'\n- 'T::DataType == Float32'\n\nReturned `psf` is `[nx_psf, nx_psf, nx]` where each PSF sums to 1.\n\"\"\"\nfunction psf_gauss( ;\n    nx::Int = 128,\n    nx_psf::Int = 11,\n    fwhm_start::Real = 1,\n    fwhm_end::Real = 4,\n    fwhm::AbstractVector{<:Real} = LinRange(fwhm_start, fwhm_end, nx),\n    T::DataType = Float32,\n)\n    isodd(nx_psf) || @warn(\"even nx_psf = $nx_psf ?\")\n    psf = zeros(T, nx_psf, nx_psf, nx)\n\n    for iy in 1:nx # depth-dependent blur\n        r = (-(nx_psf-1)÷2):((nx_psf-1)÷2)\n        σ = fwhm[iy] / sqrt(log(256))\n        r2 = abs2.(r / σ)\n        tmp = @. exp(-π * (r2 + r2'))\n        psf[:,:,iy] = tmp / sum(tmp)\n    end\n    return psf\nend\n", "meta": {"hexsha": "a7d7d728caad21391441348546a213f62865cb0b", "size": 1033, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/psf-gauss.jl", "max_stars_repo_name": "ZongyuLi-umich/SPECTrecon.jl", "max_stars_repo_head_hexsha": "db722f13229285da4a127cefbdd251b3ee05a3a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/psf-gauss.jl", "max_issues_repo_name": "ZongyuLi-umich/SPECTrecon.jl", "max_issues_repo_head_hexsha": "db722f13229285da4a127cefbdd251b3ee05a3a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/psf-gauss.jl", "max_forks_repo_name": "ZongyuLi-umich/SPECTrecon.jl", "max_forks_repo_head_hexsha": "db722f13229285da4a127cefbdd251b3ee05a3a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1951219512, "max_line_length": 70, "alphanum_fraction": 0.5934172314, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7871141193970436}}
{"text": "\n\"\"\"\n    Fourier\n\nA functor struct representing the Fourier basis.\n\"\"\"\nstruct Fourier end\n\n\"\"\"\n    fourier_basis(k,x)\n\nEvaluate the `k`-th Fourier basis function at `x`.\n\"\"\"\nfunction fourier_basis(k,x)\n    cos((div(k,2)*x - iseven(k)/2)*π)\nend\n\nfourier_basis(k,x::AbstractVector) = fourier_basis.(k,x)\n\n(::Fourier)(k,x) = fourier_basis(k,x)", "meta": {"hexsha": "5dcbf16509d68f283ecffc6417956136420b0f42", "size": 340, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/parametric_functions/fourier_basis.jl", "max_stars_repo_name": "csimal/SpectralLearning.jl", "max_stars_repo_head_hexsha": "4999657700a0d84dfff470a52ddb3e3b37a44aae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/parametric_functions/fourier_basis.jl", "max_issues_repo_name": "csimal/SpectralLearning.jl", "max_issues_repo_head_hexsha": "4999657700a0d84dfff470a52ddb3e3b37a44aae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/parametric_functions/fourier_basis.jl", "max_forks_repo_name": "csimal/SpectralLearning.jl", "max_forks_repo_head_hexsha": "4999657700a0d84dfff470a52ddb3e3b37a44aae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0, "max_line_length": 56, "alphanum_fraction": 0.6705882353, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8459424295406087, "lm_q1q2_score": 0.7871141139762595}}
{"text": "# # Logistic regression\nusing DataFrames\nusing Plots\nusing RDatasets\nusing Convex\nusing SCS\n\n\n# This is an example logistic regression using `RDatasets`'s iris data.\n# Our goal is to gredict whether the iris species is versicolor\n# using the sepal length and width and petal length and width.\niris = dataset(\"datasets\", \"iris\");\niris[1:10,:]\n\n# We'll define `Y` as the outcome variable: +1 for versicolor, -1 otherwise.\nY = [species == \"versicolor\" ? 1.0 : -1.0 for species in iris.Species]\n\n# We'll create our data matrix with one column for each feature\n# (first column corresponds to offset).\nX = hcat(ones(size(iris, 1)), iris.SepalLength, iris.SepalWidth, iris.PetalLength, iris.PetalWidth);\n\n# Now to solve the logistic regression problem.\nn, p = size(X)\nbeta = Variable(p)\nproblem = minimize(logisticloss(-Y.*(X*beta)))\nsolve!(problem, SCS.Optimizer(verbose=false))\n\n# Let's see how well the model fits.\nusing Plots\nlogistic(x::Real) = inv(exp(-x) + one(x))\nperm = sortperm(vec(X*beta.value))\nplot(1:n, (Y[perm] .+ 1)/2, st=:scatter)\nplot!(1:n, logistic.(X*beta.value)[perm])\n", "meta": {"hexsha": "c63a726affcd30542ccee7206740c0e24f1d2b6c", "size": 1083, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/general_examples/logistic_regression.jl", "max_stars_repo_name": "danspielman/Convex.jl", "max_stars_repo_head_hexsha": "fb7098c983553458a2e636e105f1fed97c72a7f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/examples_literate/general_examples/logistic_regression.jl", "max_issues_repo_name": "danspielman/Convex.jl", "max_issues_repo_head_hexsha": "fb7098c983553458a2e636e105f1fed97c72a7f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/examples_literate/general_examples/logistic_regression.jl", "max_forks_repo_name": "danspielman/Convex.jl", "max_forks_repo_head_hexsha": "fb7098c983553458a2e636e105f1fed97c72a7f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8529411765, "max_line_length": 100, "alphanum_fraction": 0.7202216066, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971129093889291, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.787079643747833}}
{"text": "using DifferentialEquations\nusing Plots\n\nfunction lotka_volterra(du,u,p,t)\n  x, y = u\n  a, b, c, d = p\n  du[1] = dx = a*x - b*x*y\n  du[2] = dy = -c*y + d*x*y\nend\n\n# Initial condition\nu0 = [1.0, 1.0]\n\n# Simulation interval and intermediary points\ntspan = (0.0, 10.0)\ntsteps = 0.0:0.1:10.0\n\n# LV equation parameter. p = [α, β, δ, γ]\np = [1.5, 1.0, 3.0, 1.0]\n\n# Setup the ODE problem, then solve\nprob = ODEProblem(lotka_volterra, u0, tspan, p)\nsol = solve(prob, Tsit5())\n\n# Plot the solution\nplot(sol)\nsavefig(\"LV_ode.png\")\n\nfunction loss(p)\n  sol = solve(prob, Tsit5(), p=p, saveat = tsteps)\n  loss = sum(abs2, sol.-1)\n  return loss, sol\nend\n\ncallback = function (p, l, pred)\n  display(l)\n  plt = plot(pred, ylim = (0, 6))\n  display(plt)\n  # Tell sciml_train to not halt the optimization. If return true, then\n  # optimization stops.\n  return false\nend\n\nresult_ode = DiffEqFlux.sciml_train(loss, p,\n                                    cb = callback,\n                                    maxiters = 100)\n\n\nprob_final = ODEProblem(lotka_volterra, u0, tspan, result_ode)\nsol_final = solve(prob_final,Tsit5())\nplot(sol_final)\nsavefig(\"LV_ode_optimized.png\") # Both state components close to 1\n\n# Start julia interpreter and type the following\n# include(\"neural_ode.jl\") # This will take a while\n# After finishing\n# Now you can change u0, tspan, p and re-run\n# prob = ODEProblem(lotka_volterra,u0,tspan,p)\n# sol=solve(prob);plot(sol); # This will be superfast (JIT)", "meta": {"hexsha": "9c3e279c52e07eb5712ec756b34de15ad0f6420e", "size": 1457, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "NODE_Julia/Prelim_studies/neural_ode.jl", "max_stars_repo_name": "Romit-Maulik/Tutorials-Demos-Practice", "max_stars_repo_head_hexsha": "a58ddc819f24a16f7059e63d7f201fc2cd23e03a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-09-02T14:46:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T15:27:05.000Z", "max_issues_repo_path": "NODE_Julia/Prelim_studies/neural_ode.jl", "max_issues_repo_name": "Romit-Maulik/Tutorials-Demos-Practice", "max_issues_repo_head_hexsha": "a58ddc819f24a16f7059e63d7f201fc2cd23e03a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2020-11-13T18:49:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:54:43.000Z", "max_forks_repo_path": "NODE_Julia/Prelim_studies/neural_ode.jl", "max_forks_repo_name": "Romit-Maulik/Tutorials-Demos-Practice", "max_forks_repo_head_hexsha": "a58ddc819f24a16f7059e63d7f201fc2cd23e03a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-09-25T23:57:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-18T08:15:34.000Z", "avg_line_length": 24.6949152542, "max_line_length": 71, "alphanum_fraction": 0.6513383665, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.855851154320682, "lm_q1q2_score": 0.7870771275256772}}
{"text": "\"\"\"\n    DiscreteUniform(a,b)\n\nA *Discrete uniform distribution* is a uniform distribution over a consecutive sequence of integers between `a` and `b`, inclusive.\n\n```math\nP(X = k) = 1 / (b - a + 1) \\\\quad \\\\text{for } k = a, a+1, \\\\ldots, b.\n```\n\n```julia\nDiscreteUniform(a, b)   # a uniform distribution over {a, a+1, ..., b}\n\nparams(d)       # Get the parameters, i.e. (a, b)\nspan(d)         # Get the span of the support, i.e. (b - a + 1)\nprobval(d)      # Get the probability value, i.e. 1 / (b - a + 1)\nminimum(d)      # Return a\nmaximum(d)      # Return b\n```\n\nExternal links\n\n* [Discrete uniform distribution on Wikipedia](http://en.wikipedia.org/wiki/Uniform_distribution_(discrete))\n\"\"\"\nstruct DiscreteUniform <: DiscreteUnivariateDistribution\n    a::Int\n    b::Int\n    pv::Float64 # individual probabilities\n\n    function DiscreteUniform(a::Real, b::Real; check_args::Bool=true)\n        check_args && @check_args(DiscreteUniform, a <= b)\n        new(a, b, 1 / (b - a + 1))\n    end\n    DiscreteUniform(b::Real; check_args::Bool=true) = DiscreteUniform(0, b; check_args=check_args)\n    DiscreteUniform() = new(0, 1, 0.5)\nend\n\n@distr_support DiscreteUniform d.a d.b\n\n### Parameters\n\nspan(d::DiscreteUniform) = d.b - d.a + 1\nprobval(d::DiscreteUniform) = d.pv\nparams(d::DiscreteUniform) = (d.a, d.b)\n\n### Show\n\nshow(io::IO, d::DiscreteUniform) = show(io, d, (:a, :b))\n\n\n### Statistics\n\nmean(d::DiscreteUniform) = middle(d.a, d.b)\n\nmedian(d::DiscreteUniform) = fld(d.a + d.b, 2)\n\nvar(d::DiscreteUniform) = (span(d)^2 - 1.0) / 12.0\n\nskewness(d::DiscreteUniform) = 0.0\n\nfunction kurtosis(d::DiscreteUniform)\n    n2 = span(d)^2\n    -1.2 * (n2 + 1.0) / (n2 - 1.0)\nend\n\nentropy(d::DiscreteUniform) = log(span(d))\n\nmode(d::DiscreteUniform) = d.a\nmodes(d::DiscreteUniform) = [d.a:d.b]\n\n\n### Evaluation\n\npdf(d::DiscreteUniform, x::Real) = insupport(d, x) ? d.pv : zero(d.pv)\nlogpdf(d::DiscreteUniform, x::Real) = log(pdf(d, x))\n\nfunction cdf(d::DiscreteUniform, x::Int)\n    a = d.a\n    result = (x - a + 1) * d.pv\n    return if x < a\n        zero(result)\n    elseif x >= d.b\n        one(result)\n    else\n        result\n    end\nend\n\nquantile(d::DiscreteUniform, p::Real) = iszero(p) ? d.a : d.a - 1 + ceil(Int, p * span(d))\n\nfunction mgf(d::DiscreteUniform, t::Real)\n    a, b = d.a, d.b\n    u = b - a + 1\n    result = (exp(t*a) * expm1(t*u)) / (u*expm1(t))\n    return iszero(t) ? one(result) : result\nend\n\nfunction cf(d::DiscreteUniform, t::Real)\n    a, b = d.a, d.b\n    u = b - a + 1\n    result = (im*cos(t*(a+b)/2) + sin(t*(a-b-1)/2)) / (u*sin(t/2))\n    return iszero(t) ? one(result) : result\nend\n\n\n### Sampling\n\nrand(rng::AbstractRNG, d::DiscreteUniform) = rand(rng, d.a:d.b)\n\n# Fit model\n\nfunction fit_mle(::Type{DiscreteUniform}, x::AbstractArray{<:Real})\n    if isempty(x)\n        throw(ArgumentError(\"data set must be non-empty.\"))\n    end\n    return DiscreteUniform(extrema(x)...)\nend\n", "meta": {"hexsha": "c6a0b1735f629164617fbea857656cdb7135bdb2", "size": 2890, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/discrete/discreteuniform.jl", "max_stars_repo_name": "pdeffebach/Distributions.jl", "max_stars_repo_head_hexsha": "8aea3cc82ee2f8ffe1e8cd754e7fcd99369c7a1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/discrete/discreteuniform.jl", "max_issues_repo_name": "pdeffebach/Distributions.jl", "max_issues_repo_head_hexsha": "8aea3cc82ee2f8ffe1e8cd754e7fcd99369c7a1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/discrete/discreteuniform.jl", "max_forks_repo_name": "pdeffebach/Distributions.jl", "max_forks_repo_head_hexsha": "8aea3cc82ee2f8ffe1e8cd754e7fcd99369c7a1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7008547009, "max_line_length": 131, "alphanum_fraction": 0.6141868512, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.855851154320682, "lm_q1q2_score": 0.7870771181010615}}
{"text": "gaussKern(x::Array{Float64,1}, y::Array{Float64,1}; σ::Float64=1.0) = kernel(GaussianKernel(σ), x, y)\n\nfunction train_model(Fs::Array{Float64,1}, X::Array{Float64,2}; k::Kernel = GaussianKernel(1.0), λ::Float64 = 0.0 )\n    \"\"\"\n    X is a N×D, that contains N row vectors in R^D\n    \"\"\"\n\n    N, D = size(X)\n\n    A = ones(N+1, N+1)\n\n    y = zeros(N+1)\n    y[1:N] = Fs\n\n    for i = 1:N\n        for j = 1:N\n            A[i, j] = kernel(k, X[i,:], X[j,:])\n        end\n\n        A[i, i] += λ\n    end\n\n    A[N+1, N+1] = 0.0\n\n    # y = Ab\n    # b = A⁻¹ ⋅ y\n    \n    b = inv(A) * y\n\n    return b\n\n\nend\n\nfunction train_model(Fs::Array{Float64,1}, X_train::Array{Float64,1}; k::Kernel = GaussianKernel(1.0), λ::Float64 = 0.0 )\n    train_model(Fs, reshape(X_train, length(X_train), 1), k = k)\nend\n\n\nF̂(x::Array{Float64,1}, b::Array{Float64,1}, X::Array{Float64}; k::Kernel = GaussianKernel()) = dot( b[1:end-1], [kernel(k,x, X[i,:]) for i = 1:size(X,1)] ) + b[end]\n\n\napprox_values(α::Array{Float64,1}, X::Array{Float64,2}, X_train::Array{Float64,2}; k::Kernel = GaussianKernel()) = [F̂(X[i,:], α, X_train, k = k) for i = 1:size(X, 1)]\n\nfunction kernel_approx_ul(Fs::Array{Float64,1},\n                     X_test::Array{Float64,2},\n                    X_train::Array{Float64,2};\n                     k::Kernel=GaussianKernel(1.0))\n\n    \"\"\"\n    X is a N×D matrix, that contains N row vectors in R^D\n    \"\"\"\n\n    α = train_model(Fs, X_train, k = k)\n\n    return approx_values(α, X_test, X_train, k = k), α\n    \nend\n\nfunction kernel_approx_ul(Fs::Array{Float64,1},\n                     X_test::Array{Float64,1},\n                    X_train::Array{Float64,1};\n                     k::Kernel=GaussianKernel(1.0))\n\n    \"\"\"\n    X is a N×1 array, that contains N row vectors in R^D\n    \"\"\"\n\n\n\n    return kernel_approx_ul(Fs, reshape(X_test, length(X_test), 1), reshape(X_train, length(X_train), 1), k=k)\n    \nend", "meta": {"hexsha": "0495e8621f306d8f9a349bdfe567dc9cab19166c", "size": 1889, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/deprecated.jl", "max_stars_repo_name": "jmejia8/BiApprox", "max_stars_repo_head_hexsha": "14904f15141d906236681641bda156e7e096c753", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-29T09:32:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T08:10:03.000Z", "max_issues_repo_path": "src/deprecated.jl", "max_issues_repo_name": "jmejia8/BiApprox", "max_issues_repo_head_hexsha": "14904f15141d906236681641bda156e7e096c753", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/deprecated.jl", "max_forks_repo_name": "jmejia8/BiApprox", "max_forks_repo_head_hexsha": "14904f15141d906236681641bda156e7e096c753", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8767123288, "max_line_length": 167, "alphanum_fraction": 0.550026469, "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682086, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.787077112640585}}
{"text": "####################\r\n#\r\n# Coordinate Conversions\r\n#\r\n####################\r\n\r\n# Identity i.e. no change - use the given coordinates\r\nidentity(xLon, yLat) = Base.identity(xLon), Base.identity(yLat)\r\n\r\n#=\r\nConverts WGS84 coordinates to Web Mercator projection (without zoom level)\r\nSee:\r\nhttp://earth-info.nga.mil/GandG/wgs84/web_mercator/(U)%20NGA_SIG_0011_1.0.0_WEBMERC.pdf\r\n=#\r\nfunction lonlat_to_webmercator(xLon, yLat)\r\n\r\n    # Check coordinates are in range\r\n    abs(xLon) <= 180 || throw(\"Maximum longitude is 180.\")\r\n    abs(yLat) < 85.051129 || throw(\"Web Mercator maximum lattitude is 85.051129. This is the lattitude at which the full map becomes a square.\")\r\n\r\n    # Ellipsoid semi-major axis for WGS84 (metres)\r\n    # This is the equatorial radius - the Polar radius is 6356752.0\r\n    a = 6378137.0\r\n\r\n    # Convert to radians\r\n    λ = xLon * 0.017453292519943295    # λ = xLon * π / 180\r\n    ϕ = yLat * 0.017453292519943295    # ϕ = yLat * π / 180\r\n\r\n    # Convert to Web Mercator\r\n    # Note that:\r\n    # atanh(sin(ϕ)) = log(tan(π/4 + ϕ/2)) = 1/2 * log((1 + sin(ϕ)) / (1 - sin(ϕ)))\r\n    x = a * λ\r\n    y = a * atanh(sin(ϕ))\r\n\r\n    return x, y\r\nend\r\n\r\n#=\r\nInverse of the above function - converts back to longitude and lattitude coordinates\r\n=#\r\nfunction webmercator_to_lonlat(x, y)\r\n    a = 6378137.0\r\n    xLon = x / (a * 0.017453292519943295)\r\n    yLat = asin(tanh(y / a)) / 0.017453292519943295\r\n    return xLon, yLat\r\nend\r\n\r\n#=\r\nConverts WGS84 coordinates to Web Mercator projection pixel numbers for use with\r\nthe Google API\r\n=#\r\nfunction lonlat_to_pixels(xLon, yLat, zoom)\r\n\r\n    # Check coordinates are in range\r\n    abs(xLon) <= 180 || throw(\"Maximum longitude is 180.\")\r\n    abs(yLat) < 85.051129 || throw(\"Web Mercator maximum lattitude is 85.051129. This is the lattitude at which the full map becomes a square.\")\r\n\r\n    # Convert to radians\r\n    λ = xLon * 0.017453292519943295    # λ = xLon * π / 180\r\n    ϕ = yLat * 0.017453292519943295    # ϕ = yLat * π / 180\r\n\r\n    # Convert to Web Mercator projection pixel number\r\n    # E.g. world coordinate range x ∈ (0,256) and y ∈ (0,256) at zoom level 0\r\n    # Note that:\r\n    # atanh(sin(ϕ)) = log(tan(π/4 + ϕ/2)) = 1/2 * log((1 + sin(ϕ)) / (1 - sin(ϕ)))\r\n    # 256/2π = 40.74366543152521\r\n    px = 40.74366543152521 * 2^zoom * (λ + π)\r\n    py = 40.74366543152521 * 2^zoom * (π - atanh(sin(ϕ)))\r\n\r\n    return px, py\r\nend\r\n\r\n#=\r\nReturns WGS84 coordinates given the pixel numbers and zoom level\r\nNote: This is the inverse of the above function - lonlat_to_pixels\r\n=#\r\nfunction pixels_to_lonlat(px, py, zoom)\r\n\r\n    xLon = 180 * (px / (128 * 2^zoom) - 1)\r\n    yLat = 180 / π * asin(tanh(π - py * π / (128 * 2^zoom)))\r\n\r\n    return xLon, yLat\r\nend\r\n", "meta": {"hexsha": "83f4de72673427abbe109b656c780b6167eabf65", "size": 2715, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/coordinate_conversions.jl", "max_stars_repo_name": "PythonNut/PlotShapefiles.jl", "max_stars_repo_head_hexsha": "c0d74bf1cba5e84cb8fd78c668ddd885693a3d6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2017-10-25T18:19:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T13:03:25.000Z", "max_issues_repo_path": "src/coordinate_conversions.jl", "max_issues_repo_name": "PythonNut/PlotShapefiles.jl", "max_issues_repo_head_hexsha": "c0d74bf1cba5e84cb8fd78c668ddd885693a3d6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2018-04-23T00:53:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-23T16:58:31.000Z", "max_forks_repo_path": "src/coordinate_conversions.jl", "max_forks_repo_name": "PythonNut/PlotShapefiles.jl", "max_forks_repo_head_hexsha": "c0d74bf1cba5e84cb8fd78c668ddd885693a3d6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-12-02T10:40:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-15T06:02:06.000Z", "avg_line_length": 32.3214285714, "max_line_length": 145, "alphanum_fraction": 0.623572744, "num_tokens": 915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474181553805, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7870704473240477}}
{"text": "\"\"\"\n    BernLik <: Likelihood\n\nBernoulli likelihood\n```math\np(y = k | f) = θᵏ (1 - θ)^{1-k}\n```\nfor ``k ∈ \\\\{0,1\\\\}``, where ``θ = Φ(f)`` and ``f`` is the latent Gaussian process.\n\"\"\"\nstruct BernLik <: Likelihood end\n\nfunction log_dens(bernoulli::BernLik, f::VecF64, y::Vector{Bool})\n    return Float64[yi ? log(Φ(fi)) : log(1.0 - Φ(fi)) for (fi,yi) in zip(f,y)]\nend\n\nfunction dlog_dens_df(bernoulli::BernLik, f::VecF64, y::Vector{Bool})\n    return Float64[yi ? φ(fi)/Φ(fi) : -φ(fi)/(1.0 - Φ(fi)) for (fi,yi) in zip(f,y)]\nend\n\n#mean and variance under the likelihood\nmean_lik(bernoulli::BernLik, f::VecF64) = Float64[Φ(fi) for fi in f]\nvar_lik(bernoulli::BernLik, f::VecF64) = Float64[Φ(fi)*(1-Φ(fi)) for fi in f]\n\nget_params(bernoulli::BernLik) = []\nnum_params(bernoulli::BernLik) = 0\n\n\n#Computes the predictive mean and variance\nfunction predict_obs(bernoulli::BernLik, fmean::VecF64, fvar::VecF64)\n    p = Float64[Φ(fm./sqrt(1+fv)) for (fm,fv) in zip(fmean,fvar)]\n    return p, p-p.*p\nend\n", "meta": {"hexsha": "07ca0a6823e657916b6487badbd88a4879290ae5", "size": 992, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/likelihoods/bernoulli.jl", "max_stars_repo_name": "jbrea/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/likelihoods/bernoulli.jl", "max_issues_repo_name": "jbrea/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/likelihoods/bernoulli.jl", "max_forks_repo_name": "jbrea/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0606060606, "max_line_length": 83, "alphanum_fraction": 0.6522177419, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778036723354, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7870634029839257}}
{"text": "using FEM_P2\nusing PyPlot\n\nbc = (Dirichlet, Neumann)\nL = 3.0\na(x) = exp(x)\nc(x) = exp(-x)\nf(x) = c(x) * sin(x) - exp(x) * ( cos(x) - sin(x) ) \nexact_u(x) = sin(x)\nγ0 = 0.0\nγL = a(L) * cos(L)\n\n#mesh = Mesh(L .* [0.0, 0.25, 0.6, 1.0], bc)\nmesh = Mesh(L .* collect(0.0:0.25:1.0), bc)\nA = assemble_matrix(mesh, deriv_times_deriv!, a)\nC = assemble_matrix(mesh, func_times_func!, c)\nA = A + C\nF = assemble_vector(mesh, f)\nG = Neumann_bc_vector(mesh, [γL])\nF .+= G\nufix = [γ0]\nndof = mesh.ndof\nF .-= A[:,ndof+1:end] * ufix\n\nufree = A[:,1:ndof] \\ F\nUnd = [ ufree; ufix ]\nx, u = evaluate_from_ndvals(mesh, Und)\nxnd, und = evaluate_from_ndvals(mesh, Und, 2)\n\nfigure(1)\nplot(x, u, \"y-\" , xnd, und, \"o\", x, exact_u.(x), \"r:\")\nlegend((\"FEM\", \"Nodal values\", \"Exact solution\"), \n       loc=\"lower center\")\ngrid(true)\nxlabel(L\"x\")\ntitle(\"Quadratic Finite Elements\")\n", "meta": {"hexsha": "3f54028150b4fd1825b90910b5697e6c5710f09f", "size": 851, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chap2/test2.jl", "max_stars_repo_name": "billmclean/ComputationalMathsNotes", "max_stars_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T21:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:30:20.000Z", "max_issues_repo_path": "src/chap2/test2.jl", "max_issues_repo_name": "billmclean/ComputationalMathsNotes", "max_issues_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chap2/test2.jl", "max_forks_repo_name": "billmclean/ComputationalMathsNotes", "max_forks_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0, "max_line_length": 54, "alphanum_fraction": 0.598119859, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778000158576, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7870633978922152}}
{"text": "################################################################################\n#################### Scaled Grid Interpolation #################################\n################################################################################\n# The following code generates three objects:\n    # 1) A \"TypeScale\" type that transforms ranges into a type of scaled ranges\n    # 2) A \"TypeRange\" type that foroms scaled ranges of a given type.\n    #   These ranges behave \"just as\" normal ranges\n    # 3) A ScaledInterpolations function that wraps \"interpolations.jl\" to be used\n    #   with TypeRange ranges\n# Types of Scales: parameters bounds for grid (a,b) and curvature (θ)\n    # p = PolyScale(a,b,θ)\n        # Maps a number x∈[0,1] to a polynomial grid with curvature θ: p(x)∈[a,b]\n        # Usage: p(x), where x is a number, or p.(x) where x is vector/range\n        # p(x) = a + (b - a) * x^θ\n    # p = InvPolyScale(a,b,θ)\n        # Maps a number y∈[a,b] from a polynomial grid with curvature θ to the unit interval: p(x)∈[0,1]\n        # Usage: p(y), where x is a number, or p.(y) where y is vector/range\n        # p(y) = ((y-a) / (b-a) )^(1/θ)\n    # p = ExpScale(a,b,θ)\n        # Maps a number x∈[0,1] to a exponential grid with curvature θ: p(x)∈[a,b]\n        # Usage: p(x), where x is a number, or p.(x) where x is vector/range\n        # p(x) = a + (b - a) * ( (exp(θ*x) - 1)/(exp(θ) - 1) )\n    # p = LogScale(a,b,θ)\n        # Maps a number y∈[a,b] from an exponential grid with curvature θ to the unit interval: p(x)∈[0,1]\n        # Usage: p(y), where x is a number, or p.(y) where y is vector/range\n        # p(y) = log( (y-a)*(exp(θ) - 1)/(b - a) + 1 ) / θ\n# Types of Scaled Ranges\n    # grid = PolyRange(a,b,θ=t,N=n) = PolyScale(a,b,t)(range(0,1,length=n))\n    # grid =  ExpRange(a,b,θ=t,N=n) =  ExpScale(a,b,t)(range(0,1,length=n))\n# ScaledInterpolations\n    # itp = ScaledInterpolations(grid,f_grid,Itp_Type)\n        # grid is either a PolyRange or ExpRange type\n        # f_grid is a vector with the values of the function at the grid nodes\n        # Itp_Type is a type from the interpolations.jl package\n            # Examples: BSpline(Cubic(Line(OnGrid()))) // shortcut: CubicSpline\n            #           BSpline(Cubic(Flat(OnGrid())))\n            #           FritschButlandMonotonicInterpolation() // shortcut: MonotoneSpline\n            #           BSpline(Linear()) // shortcut: LinearInterp\n# ScaledInterpolations with multiple dimensions\n    # itp_md = ScaledInterpolations( (grid_1,...,grid_N) , (f_grid_1,...,f_grid_N) , (Type_1,...,Type_N)  )     \n# Jacob Adenbaum, 2020\n\n\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\n# Define Scaled types\n    #-------------------------------------------------------------------------------\n    # Polynomial Scaling\n    abstract type Scale{T}       end\n    abstract type ScaledRange{T} end\n\n    for Foo in [:PolyScale, :InvPolyScale]\n\n        @eval struct $Foo{T,TF} <: Scale{T}\n            a::T\n            b::T\n            θ::TF\n        end\n\n        @eval function $Foo(a, b, θ = 1)\n            T = reduce(promote_type, map(typeof, (a,b)))\n            $Foo(convert(T, a), convert(T, b), θ)\n        end\n    end\n\n\n    (p::PolyScale)(x)           = p.a + (p.b - p.a) * x^p.θ\n    (p::InvPolyScale)(y)        = ((y-p.a) / (p.b-p.a) )^(1/p.θ)\n    Base.inv(p::PolyScale)      = InvPolyScale(p.a, p.b, p.θ)\n    Base.inv(p::InvPolyScale)   = PolyScale(p.a, p.b, p.θ)\n\n    #-------------------------------------------------------------------------------\n    # Exponential Scaling\n    for Foo in [:ExpScale, :LogScale]\n\n        @eval struct $Foo{T, TF} <: Scale{T}\n            a::T\n            b::T\n            θ::TF\n            et::T\n            s::T\n        end\n\n        @eval function $Foo(a, b, θ = 1)\n            s = (exp(θ) - 1)/(b - a)\n            et= exp(θ)\n            T = reduce(promote_type, map(typeof, (a,b,θ, et,s)))\n            $Foo(convert(T, a), convert(T, b), θ, et,s)\n        end\n    end\n\n    function (p::ExpScale)(x)\n        t  = (exp(p.θ * x) - 1)/(p.et - 1)\n        return p.a + (p.b - p.a) * t\n    end\n\n    function (p::LogScale)(y)\n        θ  = p.θ\n        log( (y-p.a)*p.s + 1 ) / p.θ\n    end\n\n    Base.inv(p::ExpScale)       = LogScale(p.a, p.b, p.θ)\n    Base.inv(p::LogScale)       = ExpScale(p.a, p.b, p.θ)\n\n    #-------------------------------------------------------------------------------\n    # Finalize Types\n    scales = Dict(:PolyRange => :PolyScale, :ExpRange => :ExpScale)\n\n\n    Base.inv(::Type{ExpScale}) = LogScale\n    Base.inv(::Type{LogScale}) = ExpScale\n    Base.inv(::Type{PolyScale})= InvPolyScale\n    Base.inv(::Type{InvPolyScale}) = PolyScale\n\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\n# Define Scaled Ranges types\n    #-------------------------------------------------------------------------------\n    # Polynomial Range\n    for Typ in [:PolyRange] @eval begin\n        struct $Typ{T,TF} <: AbstractRange{T}\n            a::T\n            b::T\n            θ::TF\n            N::Int\n            vals::Vector{Float64}\n            scale::$(scales[Typ]){T,TF}\n            invscale::inv($(scales[Typ])){T,TF}\n        end\n\n        function $Typ(a,b; θ = 1, N = 100)\n            T       = reduce(promote_type, map(typeof, (a,b,θ, 1.0)))\n            Ta      = convert(T, a)\n            Tb      = convert(T, b)\n\n            vals    = domscale($Typ)(Ta,Tb,θ).(LinRange(0, 1, N))\n            scale   = $(scales[Typ])(Ta, Tb, θ)\n            invscale= inv($(scales[Typ])(Ta, Tb, θ))\n            $Typ(convert(T, a), convert(T, b), θ, N, vals, scale, invscale)\n        end\n\n        domscale(p::$Typ)      = p.scale\n        domscale(::Type{$Typ}) = $(scales[Typ])\n\n        function rangescale(r::$Typ, x)\n            r.invscale(x)*(length(r)-1) + 1\n        end\n\n        Base.getindex(p::$Typ, i::Int) = p.vals[i]\n        Base.length(p::$Typ)  = p.N\n        Base.show(io::IO, p::$Typ) = begin\n            Typ = $Typ\n            print(io, \"$Typ($(p.a), $(p.b), $(p.θ), $(p.N))\")\n        end\n\n        function Base.searchsortedfirst(p::$Typ, x, args...)\n            searchsortedfirst(p.vals, x, args...)\n        end\n\n\n    end end\n\n    #-------------------------------------------------------------------------------\n    # Exponential Range\n    for Typ in [:ExpRange] @eval begin\n        struct $Typ{T,TF} <: AbstractRange{T}\n            a::T\n            b::T\n            θ::TF\n            N::Int\n            vals::Vector{Float64}\n            scale::$(scales[Typ]){T,TF}\n            invscale::inv($(scales[Typ])){T,TF}\n        end\n\n        function $Typ(a,b; θ = 1, N = 100)\n            vals    = domscale($Typ)(a,b,θ).(LinRange(0, 1, N))\n            scale   = $(scales[Typ])(a, b, θ)\n            invscale= inv($(scales[Typ])(a, b, θ))\n            T       = reduce(promote_type, map(typeof, (a,b,θ,scale.s)))\n            $Typ(convert(T, a), convert(T, b), θ, N, vals, scale, invscale)\n        end\n\n        domscale(p::$Typ)      = p.scale\n        domscale(::Type{$Typ}) = $(scales[Typ])\n\n        function rangescale(r::$Typ, x)\n            r.invscale(x)*(length(r)-1) + 1\n        end\n\n        Base.getindex(p::$Typ, i::Int) = p.vals[i]\n        Base.length(p::$Typ)  = p.N\n        Base.show(io::IO, p::$Typ) = begin\n            Typ = $Typ\n            print(io, \"$Typ($(p.a), $(p.b), $(p.θ), $(p.N))\")\n        end\n\n        function Base.searchsortedfirst(p::$Typ, x, args...)\n            searchsortedfirst(p.vals, x, args...)\n        end\n    end end\n\n    #-------------------------------------------------------------------------------\n    # Finalize Ranges\n    function rangescale(r::AbstractRange, x)\n        ((x - first(r)))/(last(r) - first(r)) * (length(r) -1) + 1\n    end\n\n    rangescale(r::UnitRange, x::Int) = x\n\n\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\n# Scaled Interpolation Wraper\n    mutable struct ScaledInterpolations{T, N, IT <: Interpolations.AbstractInterpolation,\n                                RT <: NTuple{N, AbstractRange},\n                                VT <: AbstractArray{T, N}, AT}\n        r::RT       # Interpolation grid (ranges)\n        v::VT       # Interpolation values\n        itp::IT     # Interpolation object\n        args::AT    # Arguments to pass to construct interpolant\n    end\n\n    function ScaledInterpolations(r, v, args...)\n        itp = extrapolate(interpolate(v, args...), Interpolations.Flat())\n        return ScaledInterpolations(tuplefy(r), v, itp, args)\n    end\n\n    tuplefy(x::Tuple) = x\n    tuplefy(x)        = tuple(x)\n\n    \"\"\"\n    ```\n    fit!(s::ScaledInterpolations, [v])\n    ```\n    Re-fit the interpolation after the underlying data has updated.  Works well if\n    you use a view into the original array.  If an array of values is passed, copies\n    the values to the scaled interpolations value array and then refits the\n    interpolation.\n    \"\"\"\n    function fit!(s::ScaledInterpolations)\n        s.itp = extrapolate(interpolate(s.v, s.args...), Interpolations.Flat())\n    end\n\n    function fit!(s::Array{T,N}) where {T <: ScaledInterpolations, N}\n        for v in s\n            fit!(v)\n        end\n    end\n\n    dim(::Type{ScaledInterpolations{T, N, IT, RT, VT, AT}}) where {T, N, IT, RT, VT, AT} = N\n    Base.eltype(::Type{ScaledInterpolations{T, N, IT, RT, VT, AT}}) where {T, N, IT, RT, VT, AT} = T\n    dim(itp::ScaledInterpolations) = dim(typeof(itp))\n    Base.eltype(itp::ScaledInterpolations) = eltype(typeof(itp))\n\n    @generated function (s::ScaledInterpolations)(x::Vararg)\n        Ns = dim(s)\n        Nx = length(x)\n        Ns == Nx || begin\n            return quote\n                Ns = $Ns\n                Nx = $Nx\n                throw(ArgumentError(\"Must have $Ns arguments.  You passed $Nx\"))\n            end\n        end\n\n        ex = Expr(:call, :(s.itp))\n        for i = 1:Ns\n            push!(ex.args, :(rangescale(s.r[$i], x[$i])))\n        end\n        ex\n    end\n\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\n# Scaled Interpolation Shortcuts for Itp_Type\n    const CubicSpline    = BSpline(Cubic(Natural(OnGrid())))\n    const MonotoneSpline = FritschButlandMonotonicInterpolation()\n    const LinearInterp   = BSpline(Linear())\n    const LinearInterp2  = BSpline(Linear())\n\n    function ScaledInterpolations(grid, values, type::FritschButlandMonotonicInterpolation)\n        return interpolate(collect(grid), values, type)\n    end\n", "meta": {"hexsha": "9de49c0baa441d53403ac1ceada30b6631d9e3a4", "size": 11082, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Scaled_Interpolation_Functions.jl", "max_stars_repo_name": "py-r-hans/AdvMacro", "max_stars_repo_head_hexsha": "338dda55de397fc1da40e2fb80f29f045714c206", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Scaled_Interpolation_Functions.jl", "max_issues_repo_name": "py-r-hans/AdvMacro", "max_issues_repo_head_hexsha": "338dda55de397fc1da40e2fb80f29f045714c206", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scaled_Interpolation_Functions.jl", "max_forks_repo_name": "py-r-hans/AdvMacro", "max_forks_repo_head_hexsha": "338dda55de397fc1da40e2fb80f29f045714c206", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3460207612, "max_line_length": 112, "alphanum_fraction": 0.4536184804, "num_tokens": 2995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731105140616, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7870569619347415}}
{"text": "\n# cartesian distance\n\ndistance(a::ENU, b::ENU) = _distance(a.east, a.north, a.up,\n                                     b.east, b.north, b.up)\n\ndistance(a::ECEF, b::ECEF) = _distance(a.x, a.y, a.z,\n                                       b.x, b.y, b.z)\n\nfunction _distance(x1, y1, z1, x2, y2, z2)\n    Δx = x2 - x1\n    Δy = y2 - y1\n    Δz = z2 - z1\n\n    return hypot(hypot(Δx,  Δy), Δz)\nend\n\n# haversine (spherical)\n\nfunction haversine_distance{T}(a::LL{T}, b::LL{T})\n    r = 6_371_009 # reduces average rather than maximum error\n\n    # Using deg2rad is faster and a tiny bit less accurate than sind/cosd --\n    #   already very rough, might as well keep it fast.\n    ϕ₁, λ₁ = deg2rad(a.lat), deg2rad(a.lon)\n    ϕ₂, λ₂ = deg2rad(b.lat), deg2rad(b.lon)\n\n    hϕ = haversin(ϕ₂ - ϕ₁)\n    hλ = haversin(λ₂ - λ₁)\n\n    h = hϕ + cos(ϕ₁)*cos(ϕ₂)*hλ\n\n    return 2r * asin(sqrt(h))\nend\n\nfunction haversin(θ)\n    s = sin(θ/2)\n    return s*s\nend\n\n# vicenty's (ellipsoidal)\n\ndistance{T}(a::LL{T}, b::LL{T}) = vicentys_inverse(a, b)[1]\n", "meta": {"hexsha": "ff62ffbd9131655ee15888555498315edf70b03c", "size": 1019, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distance.jl", "max_stars_repo_name": "FugroRoames/Geodesy.jl", "max_stars_repo_head_hexsha": "e6cc9500ad014b6677453b05aee6ec6897702361", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-08T22:09:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-08T22:09:57.000Z", "max_issues_repo_path": "src/distance.jl", "max_issues_repo_name": "FugroRoames/Geodesy.jl", "max_issues_repo_head_hexsha": "e6cc9500ad014b6677453b05aee6ec6897702361", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-03-29T07:20:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-25T06:21:45.000Z", "max_forks_repo_path": "src/distance.jl", "max_forks_repo_name": "FugroRoames/Geodesy.jl", "max_forks_repo_head_hexsha": "e6cc9500ad014b6677453b05aee6ec6897702361", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1590909091, "max_line_length": 76, "alphanum_fraction": 0.5652600589, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811631528336, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7870100909774497}}
{"text": "#######################\n# basic setup\n#######################\n\n# simulation time and interval\ntmin = 0.0\ntmax = 4.0\ndt = 0.01\n\n# domain and spacing\nxmin = -π\nxmax = π\ndx = 0.02\n\nc = π/2 # celerity\nλ² = (c*dt/dx)^2\n\nnx = convert(Int64, round((xmax-xmin)/dx) + 1)\nnt = convert(Int64, round((tmax-tmin)/dt) + 1)\n\nX = collect(Float64, LinRange(xmin, xmax, nx))\nT = collect(Float64, LinRange(tmin, tmax, nt))\n\n#######################\n\n\n#######################\n# general solution\n#######################\n# Gaussian distribution\nσ = 1/sqrt(2pi)\nU(x,t) = 0.5*(1/(sqrt(2pi)σ))*exp(-(x-c*t)^2/(2σ^2)) + 0.5*(1/(sqrt(2pi)σ))*exp(-(x+c*t)^2/(2σ^2))\nu_solution = [ U(x,t) for x in X, t in T ]\n#######################\n\n\n#######################\n# numerical simulation\n#######################\n# preallocate\nu = zeros(nx, nt)\n\n# initial condition\n# Gaussian distribution\nf(x) = 1/(sqrt(2pi)σ)*exp(-x^2/(2σ^2))\nu_0 = map(f, X)\nu[:,1] = u_0\n\n\n# 2nd step\n#u[:,2] = u[:,1]\nfor x in 2:nx-1\n    u[x,2] = 2(1-λ²)*u[x,1] -u[x,1] +λ²*(u[x-1,1]+u[x+1,1])\n    #u[x,2] = u[x,1] + λ²*(u[x+1,1] - 2u[x,1] + u[x-1,1])\nend\n# Neumann boundary condition\nu[1,2] = u[2,2]\nu[nx,2] = u[nx-1,2]\n\n#\nfor t = 3:nt\n    for x in 2:nx-1\n        u[x,t] = 2(1-λ²)*u[x,t-1] -u[x,t-2] +λ²*(u[x-1,t-1]+u[x+1,t-1])\n    end\n    # Neumann boundary condition\n    u[1,t] = u[2,t]\n    u[nx,t] = u[nx-1,t]\nend\n#######################\n\n\n#######################\n# plot\n#######################\n# directory where figures are printed\nfigdir=\"./fig\"\nif !isdir(figdir); mkdir(figdir); end\n\nusing Printf\nusing Plots\npyplot()\n\n# 軸目盛り\nxt = -π:π/2:π\nxtl = [\"-π\",\"-π/2\",\"0\",\"π/2\",\"π\"]\n\n\n# profiles\nd = 50\nplt = plot3d(repeat(X,outer=(1,length(1:d:nt))),\n             permutedims(repeat(T[1:d:nt],outer=(1,nx))),\n             u[:,1:d:nt],\n             legend=false,\n             )\nplt = plot3d!(plt, aspect_ratio=1.0, view_angle=(55,35))\nplt = plot3d!(plt, xlabel=\"space\", ylabel=\"time\", guidefont=9, xtick=(xt, xtl))\nsavefig(joinpath(figdir,\"WaveProfiles.svg\"))\n##\n\n##\n# animation\nanim = @animate for t = 1:5:nt\n    @printf(\"%d, \",t)\n    Plots.plot(X, u[:,t], linestyle=:solid, lw=2.0,\n               ylim=(-0.5,1.0), xtick=(xt, xtl), tickfont=10,\n               title=@sprintf(\"%0.3f s\", (t-1)*dt), legend=false)\nend\ngifname = joinpath(figdir,\"WaveEq.gif\")\nif isfile(gifname); rm(gifname); end\ngif(anim, gifname, fps=20) #save the animation\n##\n\n#######################\n", "meta": {"hexsha": "a677857f2c47c40b4082598a57445c6a98041455", "size": 2400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "EX8_DiffEq.jl", "max_stars_repo_name": "hydrocoast/julia_training", "max_stars_repo_head_hexsha": "d8d103b5254f1f1b3c3c5435bf23a30772d85ecb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-03-16T12:02:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-11T01:20:59.000Z", "max_issues_repo_path": "EX8_DiffEq.jl", "max_issues_repo_name": "hydrocoast/julia_training", "max_issues_repo_head_hexsha": "d8d103b5254f1f1b3c3c5435bf23a30772d85ecb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EX8_DiffEq.jl", "max_forks_repo_name": "hydrocoast/julia_training", "max_forks_repo_head_hexsha": "d8d103b5254f1f1b3c3c5435bf23a30772d85ecb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-11T01:21:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-11T01:21:10.000Z", "avg_line_length": 21.0526315789, "max_line_length": 98, "alphanum_fraction": 0.5, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7870077408281356}}
{"text": "# https://fenicsproject.org/docs/dolfin/latest/python/demos/maxwell-eigenvalues/demo_maxwell-eigenvalues.py.html\n\nmodule maxwell_eigenvalues\n\nusing FenicsPy\n\n@assert has_linear_algebra_backend(\"PETSc\") \"DOLFIN has not been configured with PETSc. \"\n@assert has_slepc() \"DOLFIN has not been configured with SLEPc. \"\n\nfunction eigenvalues(V, bcs)\n    # Define the bilinear forms on the right- and left-hand sides\n    u = TrialFunction(V)\n    v = TestFunction(V)\n    a = inner(curl(u), curl(v))*dx\n    b = inner(u, v)*dx\n    \n    # Assemble into PETSc matrices\n    dummy = v[1]*dx\n    A = PETScMatrix()\n    assemble_system(a, dummy, bcs, A_tensor=A)\n    B = PETScMatrix()\n    assemble_system(b, dummy, bcs, A_tensor=B)\n    \n    [bc.zero(B) for bc in bcs]\n    \n    solver = SLEPcEigenSolver(A, B)\n    solver.parameters[\"solver\"] = \"krylov-schur\"\n    solver.parameters[\"problem_type\"] = \"gen_hermitian\"\n    \n    solver.parameters[\"spectrum\"] = \"target magnitude\"\n    solver.parameters[\"spectral_transform\"] = \"shift-and-invert\"\n    solver.parameters[\"spectral_shift\"] = 5.5\n    neigs = 12\n    solver.solve(neigs)\n    \n    # Return the computed eigenvalues in a sorted array\n    computed_eigenvalues = []\n    for i in 1:min(neigs, solver.get_number_converged())\n        r, _ = solver.get_eigenvalue(i-1) # ignore the imaginary part\n        push!(computed_eigenvalues, r)\n    end\n    return sort(computed_eigenvalues)\nend\n\nfunction print_eigenvalues(mesh)\n    nedelec_V   = FunctionSpace(mesh, \"N1curl\", 1)\n    nedelec_bcs = [DirichletBC(nedelec_V, Constant((0.0, 0.0)), DomainBoundary())]\n    nedelec_eig = eigenvalues(nedelec_V, nedelec_bcs)\n    \n    lagrange_V   = VectorFunctionSpace(mesh, \"Lagrange\", 1)\n    lagrange_bcs = [DirichletBC(lagrange_V.sub(1), 0, \"near(x[0], 0) || near(x[0], pi)\"),\n\t\t                         DirichletBC(lagrange_V.sub(0), 0, \"near(x[1], 0) || near(x[1], pi)\")]\n    lagrange_eig = eigenvalues(lagrange_V, lagrange_bcs)\n    \n    true_eig = sort([float((m-1)^2 + (n-1)^2) for m in 1:6 for n in 1:6])[1:13]\n    \n    println(\"Nedelec:  $nedelec_eig\")\n    println(\"Lagrange: $lagrange_eig\")\n    println(\"Exact:    $true_eig\")\nend\n\nmesh = RectangleMesh(Point(0, 0), Point(pi, pi), 40, 40)\nprintln(\"\\ndiagonal mesh\")\nprint_eigenvalues(mesh)\n\nmesh = RectangleMesh(Point(0, 0), Point(pi, pi), 40, 40, \"crossed\")\nprintln(\"\\ncrossed mesh\")\nprint_eigenvalues(mesh)\n\n\n\nend # module maxwell_eigenvalues\n", "meta": {"hexsha": "f95fc1bbf12e9eccb4610da1198b6e1fa5e7b0e0", "size": 2415, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/demo-maxwell-eigenvalue.jl", "max_stars_repo_name": "chaoskey/FenicsPy.jl", "max_stars_repo_head_hexsha": "18b42f6b193a220702d544560f403a9917adda6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/demo-maxwell-eigenvalue.jl", "max_issues_repo_name": "chaoskey/FenicsPy.jl", "max_issues_repo_head_hexsha": "18b42f6b193a220702d544560f403a9917adda6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/demo-maxwell-eigenvalue.jl", "max_forks_repo_name": "chaoskey/FenicsPy.jl", "max_forks_repo_head_hexsha": "18b42f6b193a220702d544560f403a9917adda6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0821917808, "max_line_length": 112, "alphanum_fraction": 0.6720496894, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7870077360032443}}
{"text": "using BenchmarkTools\n\n# see this section of docs https://docs.julialang.org/en/v1/base/arrays/#Broadcast-and-vectorization-1\n\nfunction G_single(t::T) where T<:Real\n\n   G = 1. + 2. *exp(-t*(2. /3.)) + 4. *exp(-t*(4. /5.))\n   \nend\n\nfunction G_vec(t::Vector{T}) where T<:Real\n    \n   G = 1. .+ 2. .* exp.(-t .* (2. /3.)) .+ 4. .* exp.(-t .* (4. /5.))\n\nend\n\nfunction G_arraycomp(t::Vector{T}) where T<:Real\n    [G_single(ti) for ti in t]\nend\n\nfunction G_loop(t::Vector{T}) where T<:Real\n\n    out = Array{T}(undef, length(t))\n\n    for (i,ti) in enumerate(t)\n        out[i] = G_single(ti)\n    end\n\n    out\nend\n\nt = collect(0.0:0.1:10000)\n\nprintln(\"test vectorised version of function\")\n@btime G_vec($t)\nprintln(\"\\n\")\n\nprintln(\"test broadcasting using . notation\")\n@btime G_single.($t)\nprintln(\"\\n\")\n\nprintln(\"test broadcast function explicitly (should be the same as . notation)\")\n@btime broadcast($G_single, $t)\nprintln(\"\\n\")\n\nprintln(\"test using array comprehension\")\n@btime G_arraycomp($t)\nprintln(\"\\n\")\n\nprintln(\"test using for loop\")\n@btime G_loop($t)\nprintln(\"\\n\")\n\nprintln(\"Benchmarks complete\")\n", "meta": {"hexsha": "fcefc3953c9e3c394e3f1dd89d03c50d629ba624", "size": 1097, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "20190321_alex follow up 1.jl", "max_stars_repo_name": "JuliaRheology/RheoBenchAndTest", "max_stars_repo_head_hexsha": "479aa036b9e3351ea58594546b76d86bf269d13c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "20190321_alex follow up 1.jl", "max_issues_repo_name": "JuliaRheology/RheoBenchAndTest", "max_issues_repo_head_hexsha": "479aa036b9e3351ea58594546b76d86bf269d13c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "20190321_alex follow up 1.jl", "max_forks_repo_name": "JuliaRheology/RheoBenchAndTest", "max_forks_repo_head_hexsha": "479aa036b9e3351ea58594546b76d86bf269d13c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9454545455, "max_line_length": 102, "alphanum_fraction": 0.6399270738, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8918110511888303, "lm_q1q2_score": 0.7869589176662101}}
{"text": "\nimport FastGaussQuadrature\nimport FastTransforms\n\nusing DecFP: Dec128\n\nusing ..CommonFunctions\n\n\nstruct Quadrature{T,N}\n    order::Int\n    nodes::Vector{T}\n    weights::Vector{T}\nend\n\nfunction Quadrature(order, nodes::Vector{T}, weights::Vector{T}) where {T}\n    @assert length(nodes) == length(weights)\n    Quadrature{T, length(nodes)}(order, nodes, weights)\nend\n\nCommonFunctions.nnodes(Q::Quadrature{T,N}) where {T,N} = N\nCommonFunctions.nodes(Q::Quadrature) = Q.nodes\nCommonFunctions.order(Q::Quadrature) = Q.order\nweights(Q::Quadrature) = Q.weights\nBase.eachindex(Q::Quadrature) = eachindex(Q.nodes, Q.weights)\n\n\n\"\"\"\nIntegrate a function `f(x)` over the interval [0,1] using the quadrature `quad`.\n\"\"\"\nfunction quadrature(quad::Quadrature, f::Function)\n    sum(quad.weights[i] * f(quad.nodes[i]) for i in eachindex(quad))\nend\n\n\n\"Scale nodes and weights from the interval [-1,+1] to the interval [0,1].\"\nfunction shift!(b,c)\n    b .= b ./ 2\n    c .= (c .+ 1) ./ 2\nend\n\n\"Scale nodes and weights from the interval [0,1] to the interval [-1,+1].\"\nfunction unshift!(b,c)\n    b .= b .* 2\n    c .= 2 .* c .- 1\nend\n\n\nfunction RiemannQuadratureLeft(T=Float64)\n    Quadrature(1, [0.0,], [1.0,])\nend\n\nfunction RiemannQuadratureRight(T=Float64)\n    Quadrature(1, [1.0,], [1.0,])\nend\n\n\nfunction GaussLegendreQuadrature(s, T=Float64; shift=true)\n    c, b = FastGaussQuadrature.gausslegendre(s)\n    if shift shift!(b,c) end\n    Quadrature(2s, c, b)\nend\n\n\nfunction LobattoLegendreQuadrature(s, T=Float64; shift=true)\n    c, b = FastGaussQuadrature.gausslobatto(s)\n    if shift shift!(b,c) end\n    Quadrature(2s-2, c, b)\nend\n\n\nfunction get_nodes_gauss_chebyshev(s, k=1, T=Float64)\n    x = zeros(T, s)\n    if k == 1\n        for i in eachindex(x)\n            x[i] = @dec128 ( sin( π*(s-2i+1) / (2s) ) + 1 ) / 2\n        end\n        return x[end:-1:1]\n    elseif k == 2\n        for i in eachindex(x)\n            x[i] = @dec128 ( cos( π*i / (s-1) ) + 1 ) / 2\n        end\n        return x\n    end\nend\n\nfunction GaussChebyshevQuadrature(s, k=1, T=Float64; shift=true)\n    c = get_nodes_gauss_chebyshev(s,k,T)\n    b = zeros(c)\n\n    tj::Dec128 = 0\n    th::Dec128 = 0\n\n    if k == 1\n        for i in eachindex(b)\n            tj = 0\n            th = @dec128 π * (2i-1) / (2s)\n            for j in 1:div(s,2)\n                tj += @dec128 cos(2j*th) / (4j^2 - 1)\n            end\n            b[i] = @dec128 (1 - 2tj) / s\n        end\n    elseif k == 2\n        for i in eachindex(b)\n            tj = 0\n            th = @dec128 π * i / (s+1)\n            for j in 1:div(s+1,2)\n                tj += @dec128 sin((2j-1) * th) / (2j - 1)\n            end\n            b[i] = @dec128 (2tj * sin(th)) / (s+1)\n        end\n    else\n        error(\"GaussChebyshevQuadrature: k=\", k, \" not supported.\")\n    end\n\n    if !shift unshift!(b,c) end\n\n    Quadrature(2s-2,c,b)\nend\n\n\nfunction get_nodes_lobatto_chebyshev(s, T=Float64)\n    x = zeros(T, s)\n    for i in eachindex(x)\n        x[i] = @dec128 ( cos( (i-1)*π / (s-1) ) + 1 ) / 2\n    end\n    return x[end:-1:1]\nend\n\nfunction LobattoChebyshevQuadrature(s, T=Float64)\n    c = get_nodes_lobatto_chebyshev(s)\n    b = zeros(c)\n\n    # TODO compute weights\n\n    error(\"LobattoChebyshevQuadrature not implemented, yet!\")\nend\n\n\nfunction ClenshawCurtisQuadrature(s, T=Float64; shift=true)\n    c, b = FastTransforms.clenshawcurtis(s, zero(T), zero(T))\n    c = flipdim(c,1)\n    if shift shift!(b,c) end\n    Quadrature(s^2, c, b)\nend\n", "meta": {"hexsha": "8002d59005595dcff7c01ca75f04f70c24a955c7", "size": 3431, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/quadratures/quadrature.jl", "max_stars_repo_name": "krystophny/GeometricIntegrators.jl", "max_stars_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-04T11:52:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T11:52:47.000Z", "max_issues_repo_path": "src/quadratures/quadrature.jl", "max_issues_repo_name": "krystophny/GeometricIntegrators.jl", "max_issues_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/quadratures/quadrature.jl", "max_forks_repo_name": "krystophny/GeometricIntegrators.jl", "max_forks_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5, "max_line_length": 80, "alphanum_fraction": 0.591955698, "num_tokens": 1199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7869165646590596}}
{"text": "#! /usr/bin/env julia\n\nusing QuadGK\n\nfunction Ei(x, minfloat=1e-3, maxfloat=100)\n    f = t -> exp(-t) / t  # inline function\n    if x > 0\n        return quadgk(f, -x, -minfloat)[1]\n             + quadgk(f, minfloat, maxfloat)[1]\n    else\n        return quadgk(f, -x, maxfloat)[1]\n    end\nend\n\nX = linspace(-1, 1, 1000)   # 1000 points\nY = [ Ei(x) for x in X ]\n\nusing Winston\nplot(X, Y)\ntitle(\"The function Ei(x)\")\nxlabel(\"x\"); ylabel(\"y\")\nsavefig(\"figures/Ei_integral.png\")\n", "meta": {"hexsha": "f7ccb4f3d97a6ef8d014273ee316b234f68fdc1d", "size": 474, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2018_06__Julia_my_new_optimization_friend__introduction_for_MATLAB_users__at_IETR_seminar/examples/1D_numerical_integration_and_plot.jl", "max_stars_repo_name": "pierre-haessig/slides", "max_stars_repo_head_hexsha": "b16071df486b1d093976c1670e64debd98863a67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-07-06T13:25:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T14:35:24.000Z", "max_issues_repo_path": "2018_06__Julia_my_new_optimization_friend__introduction_for_MATLAB_users__at_IETR_seminar/examples/1D_numerical_integration_and_plot.jl", "max_issues_repo_name": "pierre-haessig/slides", "max_issues_repo_head_hexsha": "b16071df486b1d093976c1670e64debd98863a67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2017-07-12T16:14:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-15T04:30:39.000Z", "max_forks_repo_path": "2018_06__Julia_my_new_optimization_friend__introduction_for_MATLAB_users__at_IETR_seminar/examples/1D_numerical_integration_and_plot.jl", "max_forks_repo_name": "pierre-haessig/slides", "max_forks_repo_head_hexsha": "b16071df486b1d093976c1670e64debd98863a67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-09T08:45:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T21:01:23.000Z", "avg_line_length": 20.6086956522, "max_line_length": 47, "alphanum_fraction": 0.5864978903, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.786916563755988}}
{"text": "function HMMforward(v,phghm,ph1,pvgh;UseLogArray=true)\n    #HMMFORWARD HMM Forward Pass\n    # [alpha,loglik]=HMMforward(v,phghm,ph1,pvgh)\n    #\n    # Inputs:\n    # v : visible (observation) sequence being a vector v=[2 1 3 3 1 ...]\n    # phghm : homogeneous transition distribution phghm(i,j)=p(h(t)=i|h(t-1)=j)\n    # ph1 : initial distribution\n    # pvgh : homogeneous emission distribution pvgh(i,j)=p(v(t)=i|h(t)=j)\n    #\n    # Outputs:\n    # alpha : p(h(t)|v(1:t))\n    #           p(h(t)|v(1:t)) = p(v(t)|h(t)) * sum_{h(t-1)} {p(h(t)|h(t-1)) * p(h(t-1)|v(1:t-1))}\n    #           alpha(t) = p(h(t)|v(1:t))\n    #           alpha(t-1) = p(h(t-1)|v(1:t-1))\n    # loglik : sequence log likelihood log p(v(1:T))\n\n    T=length(v); H=length(ph1);\n\n    pvghtrans=pvgh'\n    z=zeros(1,T) # local normalisation factors\n    alpha=zeros(H,T)\n    alpha[:,1] = pvghtrans[:,v[1]].*ph1\n    z[1]=sum(alpha[:,1])\n    alpha[:,1]=alpha[:,1]./z[1]\n    for t=2:T\n        alpha[:,t]=pvghtrans[:,v[t]].*(phghm*alpha[:,t-1])\n        z[t]=sum(alpha[:,t])\n        alpha[:,t]=alpha[:,t]./z[t]\n    end\n    loglik = sum(log.(z)) # log likelihood\n\n    return alpha, loglik\n\nend\n\n", "meta": {"hexsha": "e8a8021054f8cfbdecc2489483b93352940e25c3", "size": 1151, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HMM/HMMforward.jl", "max_stars_repo_name": "davidbarber/Julia0p6ProbabilisticInferenceEngine", "max_stars_repo_head_hexsha": "df932959bf88b53fc076633167df4e497367e7fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2017-09-07T22:15:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T20:30:14.000Z", "max_issues_repo_path": "src/HMM/HMMforward.jl", "max_issues_repo_name": "davidbarber/Julia0p6ProbabilisticInferenceEngine", "max_issues_repo_head_hexsha": "df932959bf88b53fc076633167df4e497367e7fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HMM/HMMforward.jl", "max_forks_repo_name": "davidbarber/Julia0p6ProbabilisticInferenceEngine", "max_forks_repo_head_hexsha": "df932959bf88b53fc076633167df4e497367e7fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2017-10-22T20:10:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-01T22:52:22.000Z", "avg_line_length": 31.1081081081, "max_line_length": 98, "alphanum_fraction": 0.5377932233, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488964, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7869165587889716}}
{"text": "# # [Lotka-Volterra Model](@id predation_example)\n#\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/examples/predation/lotka-volterra.ipynb)\n\nusing AlgebraicPetri\n\nusing Petri\nusing OrdinaryDiffEq\nusing Plots\n\nusing Catlab\nusing Catlab.Theories\nusing Catlab.Programs\nusing Catlab.CategoricalAlgebra.ShapeDiagrams\nusing Catlab.WiringDiagrams\nusing Catlab.Graphics\n\ndisplay_wd(ex) = to_graphviz(ex, orientation=LeftToRight, labels=true);\n\n# #### Step 1: Define the building block Petri nets needed to construct the model\n\nbirth_petri = PetriCospan([1], Petri.Model([1], [(Dict(1=>1), Dict(1=>2))]), [1]);\nGraph(decoration(birth_petri))\n#-\npredation_petri = PetriCospan([1,2], Petri.Model(1:2, [(Dict(1=>1,2=>1), Dict(2=>1.15))]), [2]);\nGraph(decoration(predation_petri))\n#-\ndeath_petri = PetriCospan([1], Petri.Model([1], [(Dict(1=>1), Dict{Int,Int}())]), [1]);\nGraph(decoration(death_petri))\n\n# #### Step 2: Define a presentation of the free biproduct category\n# that encodes the domain specific information\n\n@present Predation(FreeBiproductCategory) begin\n    prey::Ob\n    predator::Ob\n    birth::Hom(prey,prey)\n    predation::Hom(prey⊗predator,predator)\n    death::Hom(predator,predator)\nend;\n\nrabbits,wolves,birth,predation,death = generators(Predation);\n\nF(ex) = functor((PetriCospanOb, PetriCospan), ex, generators=Dict(\n                 rabbits=>PetriCospanOb(1),wolves=>PetriCospanOb(1),\n                 birth=>birth_petri, predation=>predation_petri, death=>death_petri));\n\n# #### Step 3: Generate models using the hom expression or program notations\n\nlotka_volterra = (birth ⊗ id(wolves)) ⋅ predation ⋅ death\nlotka_petri = decoration(F(lotka_volterra))\ndisplay_wd(lotka_volterra)\n#-\nGraph(lotka_petri)\n\n# Generate appropriate vector fields, define parameters, and visualize solution\n\nu0 = [40, 2];\np = [4.0, 1.0, 2.0];\nprob = ODEProblem(lotka_petri,u0,(0.0,8.0),p);\nsol = solve(prob,Tsit5(),abstol=1e-6);\nplot(sol)\n\n# There is also a second syntax that is easier to write for programmers\n# than the hom expression syntax. Here is an example of the same model\n# as before along with a test of equivalency\n\nlotka_volterra2 = @program Predation (r::prey, w::predator) begin\n  r_2 = birth(r)\n  w_2 = predation(r_2, w)\n  return death(w_2)\nend\nlotka_petri2 = decoration(F(to_hom_expr(FreeBiproductCategory, lotka_volterra2)))\nlotka_petri == lotka_petri2\n\n# #### Step 4: Extend your presentation to handle more complex phenomena\n# such as a small food chain\n\n@present DualPredation <: Predation begin\n    Predator::Ob\n    Predation::Hom(predator⊗Predator,Predator)\n    Death::Hom(Predator,Predator)\nend;\n\nfish,Fish,Shark,birth,predation,death,Predation,Death = generators(DualPredation);\n\nF(ex) = functor((PetriCospanOb, PetriCospan), ex, generators=Dict(\n                 fish=>PetriCospanOb(1),Fish=>PetriCospanOb(1),\n                 birth=>birth_petri, predation=>predation_petri, death=>death_petri,\n                 Shark=>PetriCospanOb(1),Predation=>predation_petri, Death=>death_petri));\n\n# Define a new model where fish are eaten by Fish which are then eaten by Sharks\n\ndual_lv = @program DualPredation (fish::prey, Fish::predator, Shark::Predator) begin\n  f_2 = birth(fish)\n  F_2 = predation(f_2, Fish)\n  F_3 = death(F_2)\n  S_2 = Predation(F_3, Shark)\n  S_3 = Death(S_2)\nend\ndisplay_wd(dual_lv)\n#-\ndual_lv_petri = decoration(F(to_hom_expr(FreeBiproductCategory, dual_lv)))\nGraph(dual_lv_petri)\n\n# Generate a new solver, provide parameters, and analyze results\n\nu0 = [40, 2, 1];\np = [4.0, 1.0, 2.0, 2.5, 1.5];\nprob = ODEProblem(dual_lv_petri,u0,(0.0,8.0),p);\nsol = solve(prob,Tsit5(),abstol=1e-6);\nplot(sol)", "meta": {"hexsha": "c98d8f3490145b25b46b31eff39eb4ad77aa8499", "size": 3660, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/predation/lotka-volterra.jl", "max_stars_repo_name": "olynch/AlgebraicPetri.jl", "max_stars_repo_head_hexsha": "26de81cdac3ee3a4274c6779665a5b56019848d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/predation/lotka-volterra.jl", "max_issues_repo_name": "olynch/AlgebraicPetri.jl", "max_issues_repo_head_hexsha": "26de81cdac3ee3a4274c6779665a5b56019848d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/predation/lotka-volterra.jl", "max_forks_repo_name": "olynch/AlgebraicPetri.jl", "max_forks_repo_head_hexsha": "26de81cdac3ee3a4274c6779665a5b56019848d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6785714286, "max_line_length": 130, "alphanum_fraction": 0.7234972678, "num_tokens": 1171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7869165576600708}}
{"text": "\"\"\"\n    Ormsby(; <keyword arguments>)\n\nCreate a Ormsby wavelet sampled every dt seconds with corner frequencies\ndefined by the vector f = [f1, f2, f3, f4]. The final wavelet is multiplied by\na Hamming window. \n\n# Arguments\n\n**Keyword arguments**\n\n* `dt::Real=0.002`: sampling interval in secs.\n* `f::Vector{Real}=[2.0, 10.0, 40.0, 60.0]`: corner frequencies in Hz.\n\n      ^\n    1 |     ***************\n      |    *               *\n      |   *                 *\n      |  *                   * \n      | *                     * \n      -----------------------------> f \n        f1  f2           f3  f4\n\n# Example\n```julia\njulia> w = Ormsby(); plot(w);\n```\n\"\"\"\n\nfunction Ormsby{T<:Real}(; dt::Real=0.002, f::Vector{T}=[2.0, 10.0, 40.0, 60.0])\n\n    f1 = f[1]\n    f2 = f[2]\n    f3 = f[3]\n    f4 = f[4]\n   \n    fc = (f2+f3)/2.0\n    nw = 2.2/(fc*dt)\n    nc = floor(Int, nw/2)\n    t = dt*collect(-nc:1:nc)\n    nw = 2*nc + 1 \n    a4 = (pi*f4)^2/(pi*(f4-f3))\n    a3 = (pi*f3)^2/(pi*(f4-f3))\n    a2 = (pi*f2)^2/(pi*(f2-f1))\n    a1 = (pi*f1)^2/(pi*(f2-f1))\n    \n    u = a4*(sinc(f4*t)).^2 - a3*(sinc(f3*t)).^2 \n    v = a2*(sinc(f2*t)).^2 - a1*(sinc(f1*t)).^2 \n    \n    w = u - v\n    w = w.*Hamming(nw)/maximum(w)\n\nend\n", "meta": {"hexsha": "a45e0bda7043baff0b45323152d61f50e7e59337", "size": 1204, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Wavelets/Ormsby.jl", "max_stars_repo_name": "JuliaPackageMirrors/Seismic.jl", "max_stars_repo_head_hexsha": "7fb94347c2486f8de3185edf92bbf023f9e68cc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Wavelets/Ormsby.jl", "max_issues_repo_name": "JuliaPackageMirrors/Seismic.jl", "max_issues_repo_head_hexsha": "7fb94347c2486f8de3185edf92bbf023f9e68cc5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Wavelets/Ormsby.jl", "max_forks_repo_name": "JuliaPackageMirrors/Seismic.jl", "max_forks_repo_head_hexsha": "7fb94347c2486f8de3185edf92bbf023f9e68cc5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-07T17:48:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-07T17:48:25.000Z", "avg_line_length": 22.2962962963, "max_line_length": 80, "alphanum_fraction": 0.4368770764, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488964, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7869165526930544}}
{"text": "include(\"utils.jl\")\n\nusing Plots\nusing LaTeXStrings\nusing Statistics\n\n\nn = 100\nmaxk = 50\nrepeats = 20\n\nA = hilbert(n)\nks = 1:maxk\nλ = 1e-4\n\nerrors = zeros(maxk, repeats, 3)\n\nmethods = [\n    ridge_weights(A, λ),\n    uniform_weights(A),\n    squared_norms_weights(A)\n]\n\nfor k in ks\n    for rep = 1:repeats\n        for (i, w) in enumerate(methods)\n            C = samplemat(A, w, k)\n            C = unique(C, dims=2)\n            errors[k, rep, i] = approxerror(A, C)\n        end\n    end\nend\n\nbest_approx_errors = zeros(maxk)\n\nfor k in ks\n    C = best_approx(A, k)\n    best_approx_errors[k] = approxerror(A, C)\nend\n\n\nmeans = mean(errors, dims=2)[:, 1, :]\nstds = std(errors, dims=2)[:, 1, :]\n\nplot(xlabel=L\"k\", ylabel=L\"\\textrm{error}\")\nplot!(ks, means[:, 2], yaxis=:log, label=\"uniform\", w=2)\nplot!(ks, means[:, 3], yaxis=:log, label=\"squared norm\", w=2)\nplot!(ks, means[:, 1], yaxis=:log, label=\"ridge\", w=2)\np = plot!(ks, best_approx_errors, yaxis=:log, label=\"best\", c=:gray, w=2, ls=:dashdot)\nsavefig(p, \"./plot.pdf\")\ndisplay(p)  # sometimes the display doesn't work", "meta": {"hexsha": "baffb64c0accacf0397203e534c5fc694c3188bf", "size": 1065, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code/main.jl", "max_stars_repo_name": "qrebjock/low-rank-approximation-techniques", "max_stars_repo_head_hexsha": "c39c1774a7a4503047025bc93ac6481f9b464cab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/main.jl", "max_issues_repo_name": "qrebjock/low-rank-approximation-techniques", "max_issues_repo_head_hexsha": "c39c1774a7a4503047025bc93ac6481f9b464cab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/main.jl", "max_forks_repo_name": "qrebjock/low-rank-approximation-techniques", "max_forks_repo_head_hexsha": "c39c1774a7a4503047025bc93ac6481f9b464cab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8823529412, "max_line_length": 86, "alphanum_fraction": 0.6103286385, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7868927741254595}}
{"text": "## quadrature.jl : nystrom integration methods\n\nabstract type QuadratureRule end\n\nstruct GaussLegendre <: QuadratureRule end\nstruct EOLE <: QuadratureRule end\nstruct Simpson <: QuadratureRule end\nstruct Midpoint <: QuadratureRule end\nstruct Trapezoidal <: QuadratureRule end\n\n# get nodes and weights of Gauss-Legendre quadrature on [a,b]\nfunction get_nodes_and_weights(n,a,b,q::GaussLegendre)\n    nodes, weights = gausslegendre(n)\n    weights = (b-a)/2*weights\n    nodes = (b-a)/2*nodes .+ (a+b)/2\n    return nodes, weights\nend\n\n# get nodes and weights of structured grid on [a,b]\nfunction get_nodes_and_weights(n,a,b,q::EOLE)\n    nodes = range(a,stop = b,length = n)\n    weights = (b-a)/n*fill(1.0, size(nodes))\n    return nodes, weights\nend\n\n# get nodes and weights of Simpson's rule on [a,b]\nfunction get_nodes_and_weights(n,a,b,q::Simpson)\n    n % 2 == 0 || begin\n        warn(\"to use Simpson's rule, n must be even (received $(n)). I will continue with n = $(n+1)\") \n        n += 1\n    end\n    Δx = (b-a)/n\n    nodes = a:Δx:b\n    weights = repeat(2:2:4, outer=Int(n/2))\n    weights[1] = 1\n    push!(weights,1)\n    weights *= Δx/3\n    return nodes, weights\nend\n\n# get nodes and weights of Midpoint rule on [a,b]\nfunction get_nodes_and_weights(n,a,b,q::Midpoint)\n    Δx = (b-a)/n\n    nodes = a+Δx/2:Δx:b-Δx/2\n    weights = Δx*fill(1.0, size(nodes))\n    return nodes, weights\nend\n\n# get nodes and weights of Trapezoidal rule on [a,b]\nfunction get_nodes_and_weights(n,a,b,q::Trapezoidal)\n    Δx = (b-a)/n\n    nodes = a:Δx:b\n    weights = Δx*fill(1.0, size(nodes))\n    weights[1] /= 2\n    weights[end] /= 2\n    return nodes, weights\nend\n", "meta": {"hexsha": "ecaaa49b9774f141a4a293e0f197d384a482b323", "size": 1637, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/generators/quadrature.jl", "max_stars_repo_name": "devmotion/GaussianRandomFields.jl", "max_stars_repo_head_hexsha": "6a3ba77bb38d7ee8cb510fc4cee97376794d9577", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/generators/quadrature.jl", "max_issues_repo_name": "devmotion/GaussianRandomFields.jl", "max_issues_repo_head_hexsha": "6a3ba77bb38d7ee8cb510fc4cee97376794d9577", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/generators/quadrature.jl", "max_forks_repo_name": "devmotion/GaussianRandomFields.jl", "max_forks_repo_head_hexsha": "6a3ba77bb38d7ee8cb510fc4cee97376794d9577", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.224137931, "max_line_length": 103, "alphanum_fraction": 0.664019548, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7868927720486606}}
{"text": "\"\"\"\n    logit10(x::Real)\nFunction transforming interval [0,1] to [-Inf, Inf] using logit transformation.\n\"\"\"\nfunction logit10(x::Real)\n    log10(x / (1.0 - x))\nend\n\n\"\"\"\n    logistic10(x::Real)\nFunction transforming interval [-Inf, Inf] to [0,1] using logistic transformation.\nInverse function for [`logit10`](@ref).\n\"\"\"\nfunction logistic10(x::Real)\n    exp10(x) / (exp10(x) + 1.0)\nend\n\n\"\"\"\n    scaling(x::Real, scale::Symbol = :direct)\nTransforms values from specific scale to range [-Inf, Inf] based on option.\n\n## Return\nTransformed value.\n\n## Arguments\n* `x`: input value.\n* `scale`: transformation type: `:direct` (`:lin`), `:log`, `:logit`.\n\"\"\"\nfunction scaling(x::Real, scale::Symbol = :direct)\n    if scale == :direct || scale == :lin\n        return x\n    elseif scale == :log\n        return log10(x)\n    elseif scale == :logit\n        return logit10(x)\n    else\n        throw(DomainError(scale, \"scale type is not supported\"))\n    end\nend\n\n\"\"\"\n    unscaling(x::Real, scale::Symbol = :direct)\nTransforms values from [-Inf, Inf] to specific scale based on option. Inverse function\nfor [`scaling`](@ref).\n\n## Return\nTransformed value.\n\n## Arguments\n* `x`: input value.\n* `scale`: transformation type: `:direct` (`:lin`), `:log`, `:logit`.\n\"\"\"\nfunction unscaling(x::Real, scale::Symbol = :direct)\n    if scale == :direct || scale == :lin\n        return x\n    elseif scale == :log\n        return exp10(x)\n    elseif scale == :logit\n        return logistic10(x)\n    else\n        throw(DomainError(scale, \"scale type is not supported\"))\n    end\nend\n\nscaling(x_tup::Tuple{Float64,Float64}, scale::Symbol = :direct) = scaling.(x_tup, scale)\n\nunscaling(x_tup::Tuple{Float64,Float64}, scale::Symbol = :direct) = unscaling.(x_tup, scale)\n\nscaling(::Nothing, ::Symbol) = nothing\n\nunscaling(::Nothing, ::Symbol) = nothing\n\n\"\"\"\n    function get_endpoint(\n        theta_init::Vector{Float64},\n        theta_num::Int,\n        loss_func::Function,\n        method::Symbol,\n        direction::Symbol = :right;\n\n        loss_crit::Float64 = 0.0,\n        scale::Vector{Symbol} = fill(:direct, length(theta_init)),\n        theta_bounds::Vector{Tuple{Float64,Float64}} = unscaling.(\n            fill((-Inf, Inf), length(theta_init)),\n            scale\n            ),\n        scan_bound::Float64 = unscaling(\n            (direction==:left) ? -9.0 : 9.0,\n            scale[theta_num]\n            ),\n        scan_tol::Float64 = 1e-3,\n        loss_tol::Float64 = 0.,\n        local_alg::Symbol = :LN_NELDERMEAD,\n        max_iter::Int = 10^5,\n        loss_grad::Union{Function, Symbol} = :EMPTY,\n        silent::Bool = false\n    )\n\nCalculates confidence interval's right or left endpoints for a given parameter `theta_num`.\n\n## Return\n[`EndPoint`](@ref) object storing confidence interval's endpoint and intermediate profile points.\n\n## Arguments\n- `theta_init`: starting values of parameter vector ``\\\\theta``. The starting values should not necessary be the optimum values of `loss_func` but `loss_func(theta_init)` should be lower than `loss_crit`.\n- `theta_num`: index of vector component for identification: `theta_init(theta_num)`.\n- `loss_func`: loss function ``\\\\Lambda\\\\left(\\\\theta\\\\right)`` for profile likelihood-based (PL) identification. Usually we use log-likelihood for PL analysis: ``\\\\Lambda( \\\\theta ) = - 2 ln\\\\left( L(\\\\theta) \\\\right)``.\n- `method`: computational method to estimate confidence interval's endpoint. Currently the following methods are implemented: `:CICO_ONE_PASS`, `:LIN_EXTRAPOL`, `:QUADR_EXTRAPOL`.\n- `direction`: `:right` or `:left` endpoint to estimate.\n\n## Keyword arguments\n- `loss_crit` : critical level of loss function. Confidence interval's endpoint value is the intersection point of profile likelihood and `loss_crit` level.\n- `scale` : vector of scale transformations for each parameters' component. Possible values: `:direct` (`:lin`), `:log`, `:logit`. This option can speed up the optimization, especially for wide `theta_bounds`. The default value is `:direct` (no transformation) for all parameters.\n- `theta_bounds` : vector of tuple `(lower_bound, upper_bound)` for each parameter. Bounds define the ranges for possible parameter values. Default bounds are `(-Inf,Inf)`.\n- `scan_bound` : value which states the area of confidence point analysis.\n- `scan_tol` : Absolute tolerance for `theta_num` parameter used as termination criterion.\n- `loss_tol` : Absolute tolerance controlling `loss_func` closenes to `loss_crit` (termination criterion). Currently doesn't work for `:CICO_ONE_PASS` method because of limitation in `LN_AUGLAG` interface.\n- `local_alg` : algorithm of optimization. Derivative-free and gradient-based algorithms form NLopt package. \n- `max_iter` : maximal number of fitter iterations. If reaches the result status will be `:MAX_ITER_STOP`.\n- `loss_grad` : For gradient optimization methods it is necessary to set how the gradient of `loss_func` should be calculated.\n    There are options:\n    - `:EMPTY` (default) no gradient is set. It works only for gradient-free methods.\n    - `:AUTODIFF` means autodifferentiation from `ForwardDiff` package is used.\n    - `:FINITE` means finite difference method from `Calculus` is used.\n    - It is also possible to set gradient function here `function(x::Vector{Float64})` which returns gradient vector.\n- `silent` : Boolean argument declaring whether we display the optimization progress. Default is `false`\n\nSee also [`get_interval`](@ref)\n\"\"\"\nfunction get_endpoint(\n    theta_init::Vector{Float64},\n    theta_num::Int,\n    loss_func::Function,\n    method::Symbol,\n    direction::Symbol = :right;\n\n    loss_crit::Float64 = 0.0,\n    scale::Vector{Symbol} = fill(:direct, length(theta_init)), # :direct, :lin, :log, :logit\n    theta_bounds::Vector{Tuple{Float64,Float64}} = unscaling.(\n        fill((-Inf, Inf), length(theta_init)),\n        scale\n        ),\n    scan_bound::Float64 = unscaling(\n        (direction==:left) ? -9.0 : 9.0,\n        scale[theta_num]\n        ),\n    scan_tol::Float64 = 1e-3,\n    loss_tol::Float64 = 0.,\n    local_alg::Symbol = :LN_NELDERMEAD,\n    max_iter::Int = 10^5,\n    loss_grad::Union{Function, Symbol} = :EMPTY,\n    silent::Bool = false,\n    #kwargs... # other options for get_right_endpoint\n)\n    isLeft = direction == :left\n    n_theta = length(theta_init)\n\n    # checking arguments\n    # theta_bound[1] < theta_init < theta_bound[2]\n    theta_init_outside_theta_bounds = .! [theta_bounds[i][1] < theta_init[i] < theta_bounds[i][2] for i in 1:length(theta_init)]\n    if any(theta_init_outside_theta_bounds)\n        throw(ArgumentError(\"theta_init is outside theta_bound: $(findall(theta_init_outside_theta_bounds))\"))\n    end\n    # scan_bound should be within theta_bounds\n    !(theta_bounds[theta_num][1] < scan_bound < theta_bounds[theta_num][2]) &&\n        throw(ArgumentError(\"scan_bound are outside of the theta_bounds $(theta_bounds[theta_num])\"))\n    # theta_init should be within scan_bound\n    if (theta_init[theta_num] >= scan_bound && !isLeft) || (theta_init[theta_num] <= scan_bound && isLeft)\n        throw(ArgumentError(\"init values are outside of the scan_bound $scan_bound\"))\n    end\n    # 0 <= theta_bound[1] for :log\n    less_than_zero_theta_bounds = (scale .== :log) .& [theta_bounds[i][1] < 0 for i in 1:length(theta_init)]\n    if any(less_than_zero_theta_bounds)\n        throw(ArgumentError(\":log scaled theta_bound min is negative: $(findall(less_than_zero_theta_bounds))\"))\n    end\n    # 0 <= theta_bounds <= 1 for :logit\n    less_than_zero_theta_bounds = (scale .== :logit) .& [theta_bounds[i][1] < 0 || theta_bounds[i][2] > 1 for i in 1:length(theta_init)]\n    if any(less_than_zero_theta_bounds)\n        throw(ArgumentError(\":logit scaled theta_bound min is outside range [0,1]: $(findall(less_than_zero_theta_bounds))\"))\n    end\n    # loss_func(theta_init) < loss_crit\n    !(loss_func(theta_init) < loss_crit) &&\n        throw(ArgumentError(\"Check theta_init and loss_crit: loss_func(theta_init) should be < loss_crit\"))\n\n    # set counter in the scope\n    counter::Int = 0\n    # set supreme, maximal or minimal value of scanned parameter inside critical\n    supreme_gd = nothing\n\n    # progress info\n    prog = ProgressUnknown(\"$direction CP counter:\"; spinner=false, enabled=!silent, showspeed=true)\n\n    # transforming loss\n    theta_init_gd = scaling.(theta_init, scale)\n    if isLeft theta_init_gd[theta_num] *= -1 end # change direction\n\n    function loss_func_gd(theta_gd)\n        theta_g = copy(theta_gd)\n        if isLeft theta_g[theta_num] *= -1 end # change direction\n        theta = unscaling.(theta_g, scale)\n        # calculate function\n        loss_norm = loss_func(theta) - loss_crit\n\n        # update counter\n        counter += 1\n        # update supreme ?\n        update_supreme = (loss_norm < 0.) &&\n            (typeof(supreme_gd)==Nothing || (theta_gd[theta_num] > supreme_gd))\n        if update_supreme\n            supreme_gd = theta_gd[theta_num]\n        end\n        # display current\n        supreme = if (isLeft && typeof(supreme_gd)!==Nothing)\n            unscaling(-supreme_gd, scale[theta_num])\n        else\n            unscaling(supreme_gd, scale[theta_num])\n        end\n        ProgressMeter.update!(prog, counter, spinner=\"⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏\"; showvalues = [(:supreme,round(supreme; sigdigits=4))])\n\n        return loss_norm\n    end\n    theta_bounds_gd = scaling.(theta_bounds, scale)\n    if isLeft theta_bounds_gd[theta_num] = (-1*theta_bounds_gd[theta_num][2], -1*theta_bounds_gd[theta_num][1]) end # change direction\n\n    scan_bound_gd = scaling(scan_bound, scale[theta_num])\n    if isLeft scan_bound_gd *= -1 end # change direction\n\n    # transform gradient\n    loss_grad_gd = loss_grad\n    loss_grad_gd = if isa(loss_grad, Function)\n        function(theta_gd)\n            theta_g = copy(theta_gd)\n            if isLeft theta_g[theta_num] *= -1 end # change direction\n            theta = unscaling.(theta_g, scale)\n            loss_grad_value = loss_grad(theta)\n            loss_grad_value_gd = zeros(n_theta)\n\n            for i in 1:n_theta\n                if scale[i] == :log\n                    loss_grad_value_gd[i] = loss_grad_value[i] * theta[i] * log(10.)\n                elseif scale[i] == :logit\n                    loss_grad_value_gd[i] = loss_grad_value[i] * theta[i] * (1. - theta[i]) * log(10.)\n                else # for :direct and :lin\n                    loss_grad_value_gd[i] = loss_grad_value[i]\n                end\n            end\n\n            if isLeft loss_grad_value_gd[theta_num] *= -1 end # change direction\n\n            return loss_grad_value_gd\n        end\n    else\n        loss_grad\n    end\n\n    # calculate endpoint using base method\n    (optf_gd, pp_gd, status) = get_right_endpoint(\n        theta_init_gd,\n        theta_num,\n        loss_func_gd,\n        Val(method);\n        theta_bounds = theta_bounds_gd,\n        scan_bound = scan_bound_gd,\n        scan_tol,\n        loss_tol,\n        local_alg,\n        max_iter,\n        loss_grad = loss_grad_gd\n        #kwargs...\n    )\n\n    # transforming back\n    if (isLeft && typeof(optf_gd)!==Nothing) optf_gd *= -1 end # change direction\n    optf = unscaling(optf_gd, scale[theta_num])\n    temp_fun = (pp::ProfilePoint) -> begin\n        if isLeft pp.params[theta_num] *= -1 end # change direction\n        ProfilePoint(\n            unscaling(pp.params[theta_num], scale[theta_num]),\n            pp.loss + loss_crit,\n            unscaling.(pp.params, scale),\n            pp.ret,\n            pp.counter\n        )\n    end\n    pps = [ temp_fun(pp_gd[i]) for i in 1:length(pp_gd) ]\n    # transforming supreme back\n    supreme = if (isLeft && typeof(supreme_gd)!==Nothing) \n        unscaling(-supreme_gd, scale[theta_num])\n    else\n        unscaling(supreme_gd, scale[theta_num])\n    end\n    ProgressMeter.finish!(prog)\n\n    EndPoint(optf, pps, status, direction, counter, supreme)\nend\n\n\"\"\"\n    function get_endpoint(\n        theta_init::Vector{Float64},\n        scan_func::Function,\n        loss_func::Function,\n        method::Symbol,\n        direction::Symbol = :right;\n\n        loss_crit::Float64 = 0.0,\n        scale::Vector{Symbol} = fill(:direct, length(theta_init)),\n        theta_bounds::Vector{Tuple{Float64,Float64}} = unscaling.(\n            fill((-Inf, Inf), length(theta_init)),\n            scale\n            ),\n        scan_bound::Float64 = unscaling(\n            (direction==:left) ? -9.0 : 9.0,\n            scale[theta_num]\n            ),\n        scan_tol::Float64 = 1e-3,\n        loss_tol::Float64 = 0.,\n        local_alg::Symbol = :LN_NELDERMEAD,\n        kwargs...\n        )\n\nCalculates confidence interval's right or left endpoints for a function of parameters `scan_func`.\n\n## Return\n[`EndPoint`](@ref) object storing confidence interval's endpoint and intermediate profile points.\n\n## Arguments\n- `theta_init`: starting values of parameter vector ``\\\\theta``. The starting values should not necessary be the optimum values of `loss_func` but `loss_func(theta_init)` should be lower than `loss_crit`.\n- `scan_func`: function of parameters.\n- `loss_func`: loss function ``\\\\Lambda\\\\left(\\\\theta\\\\right)`` for profile likelihood-based (PL) identification. Usually we use log-likelihood for PL analysis: ``\\\\Lambda( \\\\theta ) = - 2 ln\\\\left( L(\\\\theta) \\\\right)``.\n- `method`: computational method to estimate confidence interval's endpoint. Currently the only supported method is: `:CICO_ONE_PASS`.\n- `direction`: `:right` or `:left` endpoint to estimate.\n\n## Keyword arguments\n- `loss_crit`: critical level of loss function. Confidence interval's endpoint value is the intersection point of profile likelihood and `loss_crit` level.\n- `scale`: vector of scale transformations for each parameters' component. Possible values: `:direct` (`:lin`), `:log`, `:logit`. This option can speed up the optimization, especially for wide `theta_bounds`. The default value is `:direct` (no transformation) for all parameters.\n- `theta_bounds`: vector of tuple `(lower_bound, upper_bound)` for each parameter. Bounds define the ranges for possible parameter values. Default bounds are `(-Inf,Inf)`.\n- `scan_bound`: value which states the area of confidence point analysis.\n- `scan_tol`: Absolute tolerance for `theta_num` parameter used as termination criterion.  \n- `loss_tol`: Absolute tolerance controlling `loss_func` closenes to `loss_crit` (termination criterion). Currently doesn't work for `:CICO_ONE_PASS` method because of limitation in `LN_AUGLAG` interface.\n- `local_alg`: algorithm of optimization. Derivative-free and gradient-based algorithms form NLopt package. \n- `max_iter` : maximal number of fitter iterations. If reaches the result status will be `:MAX_ITER_STOP`.\n- `scan_grad` : For gradient optimization methods it is necessary to set how the gradient of `scan_func` should be calculated.\n    - `:EMPTY` (default) no gradient is set. It works only for gradient-free methods.\n    - `:AUTODIFF` means autodifferentiation from `ForwardDiff` package is used.\n    - `:FINITE` means finite difference method from `Calculus` is used.\n    - `function(x::Vector{Float64})` which returns gradient vector.\n- `loss_grad` : For gradient optimization methods it is necessary to set how the gradient of `loss_func` should be calculated.\n    - `:EMPTY` (default) no gradient is set. It works only for gradient-free methods.\n    - `:AUTODIFF` means autodifferentiation from `ForwardDiff` package is used.\n    - `:FINITE` means finite difference method from `Calculus` is used.\n    - `function(x::Vector{Float64})` which returns gradient vector.\n- `silent` : Boolean argument declaring whether we display the optimization progress. Default is `false`\n\nSee also [`get_interval`](@ref)\n\"\"\"\nfunction get_endpoint(\n    theta_init::Vector{Float64},\n    scan_func::Function,\n    loss_func::Function,\n    method::Symbol,\n    direction::Symbol = :right;\n\n    loss_crit::Float64 = 0.0,\n    # :direct, :lin, :log, :logit\n    scale::Vector{Symbol} = fill(:direct, length(theta_init)),\n    theta_bounds::Vector{Tuple{Float64,Float64}} = unscaling.(\n        fill((-Inf, Inf), length(theta_init)),\n        scale\n        ),\n    scan_bound::Float64 = (direction==:left) ? -1e9 : 1e9, # log scan bound is not implemented\n    scan_tol::Float64 = 1e-3,\n    loss_tol::Float64 = 0.,\n    local_alg::Symbol = :LN_NELDERMEAD,\n    max_iter::Int = 10^5,\n    scan_grad::Union{Function, Symbol} = :EMPTY,\n    loss_grad::Union{Function, Symbol} = :EMPTY,\n    silent::Bool = false,\n    #kwargs... # other options for get_right_endpoint\n)\n    isLeft = direction == :left\n    n_theta = length(theta_init)\n    loss_init = loss_func(theta_init)\n\n    # checking arguments\n    # theta_bound[1] < theta_init < theta_bound[2]\n    theta_init_outside_theta_bounds = .! [theta_bounds[i][1] < theta_init[i] < theta_bounds[i][2] for i in 1:length(theta_init)]\n    if any(theta_init_outside_theta_bounds)\n        throw(ArgumentError(\"theta_init is outside theta_bound: $(findall(theta_init_outside_theta_bounds))\"))\n    end\n\n    # 0 <= theta_bound[1] for :log\n    less_than_zero_theta_bounds = (scale .== :log) .& [theta_bounds[i][1] < 0 for i in 1:length(theta_init)]\n    if any(less_than_zero_theta_bounds)\n        throw(ArgumentError(\":log scaled theta_bound min is negative: $(findall(less_than_zero_theta_bounds))\"))\n    end\n    # 0 <= theta_bounds <= 1 for :logit\n    less_than_zero_theta_bounds = (scale .== :logit) .& [theta_bounds[i][1] < 0 || theta_bounds[i][2] > 1 for i in 1:length(theta_init)]\n    if any(less_than_zero_theta_bounds)\n        throw(ArgumentError(\":logit scaled theta_bound min is outside range [0,1]: $(findall(less_than_zero_theta_bounds))\"))\n    end\n    # loss_func(theta_init) < loss_crit\n    !(loss_init < loss_crit) &&\n        throw(ArgumentError(\"Check theta_init and loss_crit: loss_func(theta_init) should be < loss_crit\"))\n\n    # set counter in the scope\n    prog = ProgressUnknown(\"Fitter counter:\"; spinner=false, enabled=!silent, showspeed=true)\n    counter::Int = 0\n    # set supreme, maximal or minimal value of loss_func inside critical\n    supreme_gd = nothing\n    scan_val_gd = nothing\n\n    # transforming\n    theta_init_gd = scaling.(theta_init, scale)\n    \n    function scan_func_gd(theta_gd)\n        theta = unscaling.(theta_gd, scale)\n        scan_val = scan_func(theta)\n        scan_val_gd = isLeft ? (-1)*scan_val : scan_val\n        \n        return scan_val_gd\n    end\n\n    function loss_func_gd(theta_gd)\n        #theta_g = copy(theta_gd) # why copy?\n        theta = unscaling.(theta_gd, scale)\n        loss_value = loss_func(theta) - loss_crit\n\n        counter += 1\n        #println(\"$loss_value => $supreme_gd\")\n        should_update = (loss_value < 0.) &&\n            !isa(scan_val_gd, Nothing) &&\n            (isa(supreme_gd, Nothing) || (scan_val_gd > supreme_gd)) &&\n            !isa(scan_val_gd, ForwardDiff.Dual)\n        if should_update\n            supreme_gd = scan_val_gd\n        end\n        supreme = if isa(supreme_gd, Nothing)\n            \"-\"\n        elseif isLeft\n            round(-supreme_gd; sigdigits=4)\n        else\n            round(supreme_gd; sigdigits=4)\n        end\n        ProgressMeter.update!(prog, counter; showvalues = [(:supreme,supreme)])\n\n        return loss_value\n    end\n    theta_bounds_gd = scaling.(theta_bounds, scale)\n\n    # TODO: transformed by scan_scale: scaling(scan_bound, scan_scale)\n    scan_bound_gd = scan_bound\n    if isLeft scan_bound_gd *= -1 end # change direction\n\n    # transform gradients\n    scan_grad_gd = if isa(scan_grad, Function)\n        function(theta_gd)\n            theta = unscaling.(theta_gd, scale)\n            scan_grad_value = scan_grad(theta)\n            scan_grad_value_gd = zeros(n_theta)\n\n            for i in 1:n_theta\n                if scale[i] == :log\n                    scan_grad_value_gd[i] = scan_grad_value[i] * theta[i] * log(10.)\n                elseif scale[i] == :logit\n                    scan_grad_value_gd[i] = scan_grad_value[i] * theta[i] * (1. - theta[i]) * log(10.)\n                else # for :direct and :lin\n                    scan_grad_value_gd[i] = scan_grad_value[i]\n                end\n            end\n\n            return scan_grad_value_gd\n        end\n    else\n        scan_grad\n    end\n    \n    loss_grad_gd = if isa(loss_grad, Function)\n        function(theta_gd)\n            theta = unscaling.(theta_gd, scale)\n            loss_grad_value = loss_grad(theta)\n            loss_grad_value_gd = zeros(n_theta)\n\n            for i in 1:n_theta\n                if scale[i] == :log\n                    loss_grad_value_gd[i] = loss_grad_value[i] * theta[i] * log(10.)\n                elseif scale[i] == :logit\n                    loss_grad_value_gd[i] = loss_grad_value[i] * theta[i] * (1. - theta[i]) * log(10.)\n                else # for :direct and :lin\n                    loss_grad_value_gd[i] = loss_grad_value[i]\n                end\n            end\n\n            return loss_grad_value_gd\n        end\n    else\n        loss_grad\n    end\n\n    # calculate endpoint using base method\n    (optf_gd, pp_gd, status) = get_right_endpoint(\n        theta_init_gd,\n        scan_func_gd,\n        loss_func_gd,\n        Val(method);\n\n        theta_bounds = theta_bounds_gd,\n        scan_bound = scan_bound_gd,\n        scan_tol,\n        loss_tol,\n        local_alg,\n        max_iter,\n        scan_grad = scan_grad_gd,\n        loss_grad = loss_grad_gd,\n        #kwargs...\n    )\n\n    # transforming back\n    temp_fun = (pp::ProfilePoint) -> begin\n        value = isLeft ? (-1)*pp.value : pp.value # TODO: scan_scale\n        ProfilePoint(\n            value,\n            pp.loss + loss_crit,\n            unscaling.(pp.params, scale),\n            pp.ret,\n            pp.counter\n        )\n    end\n    pps = [ temp_fun(pp_gd[i]) for i in 1:length(pp_gd) ]\n    # transforming supreme back\n    if (isLeft && typeof(supreme_gd)!==Nothing) supreme_gd *= -1 end # change direction\n\n    if (isLeft && typeof(optf_gd)!==Nothing) optf_gd *= -1 end # change direction\n    # optf = unscaling(optf_gd, scan_scale)\n    optf = optf_gd\n\n    EndPoint(optf, pps, status, direction, counter, supreme_gd)\nend\n", "meta": {"hexsha": "419f5cdac7a4ecc0192cd0e6ce25d184a45ccfda", "size": 22048, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/get_endpoint.jl", "max_stars_repo_name": "metelkin/LikelihoodProfiler.jl", "max_stars_repo_head_hexsha": "ead95214dd4a08dd69453e4c73c409cffcdb7515", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/get_endpoint.jl", "max_issues_repo_name": "metelkin/LikelihoodProfiler.jl", "max_issues_repo_head_hexsha": "ead95214dd4a08dd69453e4c73c409cffcdb7515", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/get_endpoint.jl", "max_forks_repo_name": "metelkin/LikelihoodProfiler.jl", "max_forks_repo_head_hexsha": "ead95214dd4a08dd69453e4c73c409cffcdb7515", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9814126394, "max_line_length": 280, "alphanum_fraction": 0.6528029753, "num_tokens": 5706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7868057922907097}}
{"text": "module IntervalAnalysis\nusing Plots \nusing Base \nusing Random \nusing Symbolics\nusing Documenter\n\nexport Interval,*,+,-,subdivide\n\n\"\"\"\n    Interval\n\nDefines a single interval between two real numbers.\n\n# Examples\n```jldoctest\njulia> Interval(-1,1)\n-1.0 ←-→ 1.0\n```\n\"\"\"\nstruct Interval\n\t\"Lower interval value\"\n\tl::Real\n\t\"Upper interval value\"\n\tu::Real\n\tInterval(l,u) = l > u ? new(u,l) : new(l,u)\n\t\nend\n\nBase.show(io::IO, x::Interval) = print(io,round(x.l,digits=6),\" ←-→ \",round(x.u,digits=6))\n\n\"\"\"\n\n\t+(x₁::Interval, x₂::Interval)\n\nAdds two intervals\n\n# Examples\n```jldoctest\njulia> Interval(-1,1) + Interval(-2,4)\n-3.0 ←-→ 5.0\n```\n\"\"\"\nfunction Base.:+(x₁::Interval, x₂::Interval)\n\tInterval(x₁.l + x₂.l,x₁.u + x₂.u)\n    end\n\n\n\nfunction Base.:+(x₁::Real, x₂::Interval)\n\tInterval(x₁ + x₂.l,x₁ + x₂.u)\n    end\n\nfunction Base.:+(x₁::Interval, x₂::Real)\n\tInterval(x₁.l + x₂,x₁.u + x₂)\n    end\n\n \"\"\"\n\n\t-(x₁::Interval, x₂::Interval)\n\nSubtracts one interval from another\n\n# Examples\n```jldoctest\njulia> Interval(-1,1) - Interval(-2,4)\n-5.0 ←-→ 3.0\n```\n\"\"\"\nfunction Base.:-(x₁::Interval, x₂::Interval)\n\tInterval(x₁.l - x₂.u,x₁.u - x₂.l)\n    end\n\nfunction Base.:-(x::Interval)\n\tInterval(-x.l,-x.u)\n    end\n\nfunction Base.:-(x₁::Interval, x₂::Real)\n\tInterval(x₁.l - x₂,x₁.u - x₂)\n    end\n\n    function Base.:-(x₁::Real, x₂::Interval)\n\tInterval(x₁ - x₂.l,x₁ - x₂.u)\n    end\n\n\"\"\"\n\n\t*(x₁::Interval, x₂::Interval)\n\nMultiplies two intervals\n\n# Examples\n```jldoctest\njulia> Interval(-1,1) * Interval(-2,4)\n-4.0 ←-→ 4.0\n```\n\"\"\"\nfunction Base.:*(x₁::Interval, x₂::Interval)\n\tif 0 ≤ x₁.l \n\t\tif 0 ≤ x₂.l \n\t\t\treturn Interval(x₁.l*x₂.l,x₁.u*x₂.u)\n\t\telseif x₂.l < 0 < x₂.u \n\t\t\treturn Interval(x₁.u*x₂.l,x₁.u*x₂.u)\n\t\telseif x₂.u ≤ 0 \n\t\t\treturn Interval(x₁.u*x₂.l,x₁.l*x₂.u)\n\t\tend\n\telseif x₁.l < 0 < x₁.u\n\t\tif 0 ≤ x₂.l \n\t\t\treturn Interval(x₁.l*x₂.u,x₁.u*x₂.u)\n\t\telseif x₂.u ≤ 0 \n\t\t\treturn Interval(x₁.u*x₂.l,x₁.l*x₂.l)\n\t\telseif x₂.l < 0 < x₂.u \n\t\t\treturn Interval(min(x₁.l*x₂.u,x₁.u*x₂.l),max(x₁.l*x₂.l,x₁.u*x₂.u))\n\t\tend\n\telseif x₁.u ≤ 0\n\t\tif 0 ≤ x₂.l \n\t\t\treturn Interval(x₁.l*x₂.u,x₁.u*x₂.l)\n\t\telseif x₂.l < 0 < x₂.u \n\t\t\treturn Interval(x₁.l*x₂.u,x₁.l*x₂.l)\n\t\telseif x₂.u ≤ 0 \n\t\t\treturn Interval(x₁.u*x₂.u,x₁.l*x₂.l)\n\t\tend\n\tend\nend\n\nfunction Base.:*(x₁::Interval,x₂::Real)\n\tInterval(x₁.l*x₂,x₁.u*x₂)\nend\n\nfunction Base.:*(x₁::Real,x₂::Interval)\n\tInterval(x₁*x₂.l,x₁*x₂.u)\nend\n\n\"\"\"\n\n\t/(x₁::Interval, x₂::Interval)\n\nDivides two intervals\n\n# Examples\n```jldoctest\njulia> Interval(-1,1) / Interval(-2,4)\n-0.5 ←-→ 0.5\n```\n\"\"\"\nfunction Base.:/(x₁::Interval, x₂::Interval)\n\tx₁ * Interval(1/x₂.u,1/x₂.l)\n    end\n\nfunction Base.:/(x₁::Real, x₂::Interval)\n\tInterval(x₁/x₂.u,x₁/x₂.l)\n    end\n\nfunction Base.:/(x₁::Interval, x₂::Real)\n\tInterval(x₁.l/x₂,x₁.u/x₂)\n    end\n\nfunction w(x::Interval)\n\tx.u-x.l\nend\n\nfunction w(X::Vector{Interval})\n\twidths = w.(X)\n\td,i = findmax(widths)\nend\n\nfunction m(x::Interval)\n\t(x.u+x.l)/2\nend\n\nfunction m(X::Vector{Interval})\n\tm.(X)\nend\n\n\nfunction Base.sqrt(x::Interval)\n\tInterval(sqrt(x.l),sqrt(x.u))\nend\n\nfunction Base.:^(x::Interval,p::Integer)\n\tif x.l > 0 || p%2 != 0 \n\t\treturn Interval(x.l^p,x.u^p)\n\telseif x.u < 0 && p%2 == 0 \n\t\treturn Interval(x.u^p,x.l^p)\n\telse\n\t\treturn Interval(0,abs(x)^p)\n\tend\nend\n\nfunction Base.exp(x::Interval)\n\tInterval(exp(x.l),exp(x.u))\nend\n\nfunction Base.log(x::Interval)\n\tInterval(log(x.l),log(x.u))\nend\n\nfunction Base.log10(x::Interval)\n\tInterval(log10(x.l),log10(x.u))\nend\n\nfunction Base.log2(x::Interval)\n\tInterval(log2(x.l),log2(x.u))\nend\n\nfunction Base.sin(x::Interval)\n\tif x.l ≥ -(π/2) && x.u ≤ π/2\n\t\t\treturn Interval(sin(x.l),sin(x.u))\n\tend\n\treturn Interval(-1,1)\nend\n\nfunction Base.cos(x::Interval)\n\tif x.l ≥ 0 && x.u ≤ π\n\t\t\treturn Interval(cos(x.l),cos(x.u))\n\tend\n\treturn Interval(-1,1)\nend\n\nfunction Base.abs(x::Interval)\n\tmax(abs(x.l),abs(x.u))\nend\n\n\nfunction qdist(x₁::Interval,x₂::Interval)\n\tmax(abs(x₁.l-x₂.l),abs(x₁.u-x₂.u))\nend\n\n\"\"\"\n\n\tsubdivide(x::Interval,N::Integer)\n\nSubdivides an interval into N intervals.\n\n# Examples\n```jldoctest\njulia> subdivide(Interval(0,1),5)\n[0.0 ←-→ 0.2, 0.2 ←-→ 0.4, 0.4 ←-→ 0.6, 0.6 ←-→ 0.8, 0.8 ←-→ 1.0]\n```\n\"\"\"\nfunction subdivide(x::Interval,N::Integer)\n\tA = Array{Interval}(undef,N)\n\tw_x = w(x)/N\n\tfor j ∈ 1:N \n\t\tA[j] = Interval(x.l+(j-1)*w_x,x.l+j*w_x)\n\tend\n\treturn A \nend\n\nfunction subdivide_vector(X::Vector{Interval},N::Integer)\n\tA = Array{Vector{Interval}}(undef,length(X))\n\tfor i ∈ 1:length(X)\n\t\tA[i] = subdivide(X[i],N)\n\tend\n\treturn A\nend\n\nfunction bisect_box(X::Vector{Interval})\n\t# bisects a box over the largest axis \n\td,i = w(X)\n\tX_s = subdivide(X[i],2)\n\tX₁ = copy(X)\n\tX₁[i] = X_s[1]\n\tX₂ = copy(X)\n\tX₂[i] = X_s[2]\n\treturn X₁,X₂\nend\n\n\nfunction hull(X::Vector{Interval})\n\tl = [x.l for x ∈ X]\n\tu = [x.u for x ∈ X]\n\tInterval(minimum(l),maximum(u))\nend\n\nfunction refinement(x,f,N)\n\tX = subdivide(x,N)\n\tY = f.(X)\n\thull(Y)\nend\n\nfunction plot_refinement(x,f,∇f,N)\n\tplot(f,x.l,x.u,c=\"black\",linewidth=3,label=\"\")\n\tX = subdivide(x,N)\n\tY = f.(X)\t\n\tYₘᵥ = mean_value_form.(f,∇f,X)\n\tfor i ∈ 1:length(X)\n\t\tif i == 1\n\t\t\tplot!([X[i].l,X[i].u],[Y[i].l,Y[i].l],fillrange=[Y[i].u,Y[i].u],linewidth=0,c=\"black\",label=\"Interval Extension\",fillalpha=0.15)\n\t\t\tplot!([X[i].l,X[i].u],[Yₘᵥ[i].l,Yₘᵥ[i].l],fillrange=[Yₘᵥ[i].u,Yₘᵥ[i].u],linewidth=0,c=\"red\",label=\"Mean Value Form\",fillalpha=0.25)\n\t\telse\n\t\t\tplot!([X[i].l,X[i].u],[Y[i].l,Y[i].l],fillrange=[Y[i].u,Y[i].u],linewidth=0,c=\"black\",label=\"\",fillalpha=0.15)\n\t\t\tplot!([X[i].l,X[i].u],[Yₘᵥ[i].l,Yₘᵥ[i].l],fillrange=[Yₘᵥ[i].u,Yₘᵥ[i].u],linewidth=0,c=\"red\",label=\"\",fillalpha=0.25)\n\t\tend\n\n\tend\n\tdisplay(plot!(dpi=600))\nend\n\nfunction skelboe_moore(f,X)\n\n\tfᵤ = f(X).u # smallest upper bound (AKA the only upper bound at this stage)\n\n\t# creating a store of intervals, mean values, and interval values \n\tL = [Dict(\"X\"=>X,\"f_m\"=>f(m(X)),\"F\"=>f(X))]\n\tLᵣ = []\n\tit_count = 0 \n\n\t# until tolerance...\n\tfor it ∈ 1:30\n\t\t\n\t\t\n\t\t# initialise list of intervals to sack off \n\t\tdel_index =[]\n\t\tfor i in 1:length(L)\n\t\t\t# if the lowest interval value is above the smallest upper bound..\n\t\t\tif L[i][\"F\"].l > fᵤ\n\t\t\t\t# remove interval, we know global minimum is not here...\n\t\t\t\tpush!(del_index,i)\n\t\t\tend\n\t\tend\n\n\t\t# delete all the ones we said we would \n\t\tfor d_i ∈ del_index\n\t\t\tpush!(Lᵣ,L[d_i])\n\t\tend\n\t\tdeleteat!(L,del_index)\n\n\n\t\t# pick the remaining interval with smallest mean value \t\n\t\ts = argmin([l[\"f_m\"] for l ∈ L])\n\n\t\t# divide the box into two \n\t\tX_s = bisect_box(L[s][\"X\"])\n\n\t\t# get rid of the containing interval \n\t\tdeleteat!(L,s)\n\n\t\tfor x ∈ X_s\n\t\t\t# evaluate interval values \n\t\t\tF = f(x)\n\n\t\t\t# check if we find a smallest upper bound \n\t\t\tif F.u < fᵤ\n\t\t\t\tfᵤ = F.u\n\t\t\tend\n\t\t\t# add new interval information to store\n\t\t\tpush!(L,Dict(\"X\"=>x,\"f_m\"=>f(m(x)),\"F\"=>F))\n\n\t\tend\n\n\tend\n\treturn L,Lᵣ\nend\n\n\nfunction plot_boxes(L,Lᵣ)\n\tfor l ∈ L \n\t\tx1 = l[\"X\"][1]\n\t\tx2 = l[\"X\"][2]\n\t\tplot!(Shape([x1.l,x1.l,x1.u,x1.u] , [x2.u,x2.l,x2.l,x2.u]),label=\"\",linewidth=1,alpha=0,linealpha=1)\n\tend\n\tfor l ∈ Lᵣ\n\t\tx1 = l[\"X\"][1]\n\t\tx2 = l[\"X\"][2]\n\t\tplot!(Shape([x1.l,x1.l,x1.u,x1.u] , [x2.u,x2.l,x2.l,x2.u]),c=\"black\",alpha=0.55,label=\"\",linewidth=1)\n\tend\nend\n\n\n\n\nfunction mean_value_form(f,∇f,X)\n\tif typeof(X) == Interval\n\t\tD = ∇f(X)[1]\n\telse\n\t\tD = ∇f(X)\n\tend\n\tmean = m(X)\n\tfₘ = f(mean)\n\tif typeof(X) == Interval\n\t\treturn fₘ + D*(X-mean)\n\telse\n\t\treturn fₘ + sum(D[i]*(X[i]-mean[i]) for i ∈ 1:length(X))\n\tend\n\nend\n\nfunction build_gradient(f,len_x)\n\tif len_x > 1\n\t\t@variables x[1:len_x]\n\t\t∇f = Symbolics.gradient(f(x),[x[i] for i ∈ 1:len_x])\n\t\t∇f_expr = build_function(∇f, x)\n\t\t∇f = eval(∇f_expr[1])\n\t\treturn ∇f\n\telse\n\t\t@variables x\n\t\t∇f = Symbolics.gradient(f(x),[x])\n\t\t∇f_expr = build_function(∇f, x)\n\t\t∇f = eval(∇f_expr[1])\n\t\treturn ∇f\n\tend\n\nend \n\nfunction g(x1,x2)\n\treturn x1*exp(x1+x2^2)-x2^2\nend\n\nfunction g_vec(X)\n\treturn g(X[1],X[2])\nend\n\n\n# f(x) = x^3 - x^2\n# ∇f = build_gradient(f,1)\n# plot_refinement(Interval(0,1),f,∇f,20)\n# print(Interval(-1,1) / Interval(-2,4))\n\nend", "meta": {"hexsha": "a17832e7f6e3cb24b3fe7c70d85dadc2d2c92de4", "size": 7855, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/IntervalAnalysis.jl", "max_stars_repo_name": "trsav/interval_analysis", "max_stars_repo_head_hexsha": "1e885e49ecddeb4fb6eb73224c0fac25c761edb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/IntervalAnalysis.jl", "max_issues_repo_name": "trsav/interval_analysis", "max_issues_repo_head_hexsha": "1e885e49ecddeb4fb6eb73224c0fac25c761edb6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IntervalAnalysis.jl", "max_forks_repo_name": "trsav/interval_analysis", "max_forks_repo_head_hexsha": "1e885e49ecddeb4fb6eb73224c0fac25c761edb6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7023809524, "max_line_length": 134, "alphanum_fraction": 0.6160407384, "num_tokens": 3061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.8723473647220787, "lm_q1q2_score": 0.7867881345579985}}
{"text": "import Base: exp, log, sqrt, ^\nimport Base: cos, sin, tan, cosh, sinh, tanh, acos, asin, atan, acosh, asinh, atanh\n\nfunction exp(q::Quaternion)\n    z = sqrt(q.q1*q.q1 + q.q2*q.q2 + q.q3*q.q3)\n    return exp(q.q0)*(cos(z) + imag(q)*(z != zero(q.q0) ? sin(z)/z : one(q.q0)))\nend\n\nfunction log(q::Quaternion)\n    z = abs(imag(q))\n    return log(abs(q)) + ((imag(q)!=zero(q)) ? imag(q)/z*atan(z,q.q0) :\n    q.q0 < zero(q.q0) ? quaternion(pi*im) : zero(q))\nend\n\nfunction cos(q::Quaternion)\n    z = abs(imag(q))\n    return cos(q.q0)*cosh(z)-imag(q)*sin(q.q0)*(z != zero(q.q0) ? sinh(z)/z : one(q.q0))\nend\n\nfunction sin(q::Quaternion)\n    z = abs(imag(q))\n    return sin(q.q0)*cosh(z)+imag(q)*cos(q.q0)*(z != zero(q.q0) ? sinh(z)/z : one(q.q0))\nend\n\nfunction tan(q::Quaternion)\n    return sin(q)/cos(q)\nend\n\nfunction cosh(q::Quaternion)\n    return (exp(q)+exp(-q))/2\nend\n\nfunction sinh(q::Quaternion)\n    return (exp(q)-exp(-q))/2\nend\n\nfunction tanh(q::Quaternion)\n    return sinh(q)/cosh(q)\nend\n\nfunction sqrt(q::Quaternion)\n    return exp(log(q)/2)\nend\n\nfunction (^)(q::Quaternion, p::AbstractFloat)\n    return exp(p*log(q))\nend\n\nfunction (^)(q::Quaternion, p::Quaternion)\n    return exp(p*log(q))\nend\n\nfunction acos(q::Quaternion)\n    x = imag(q)\n    y = abs(x)\n    z = y!=zero(q.q0) ? x/y : quaternion(one(q.q0)*im)\n\n    return -z*log(q + z*sqrt(one(q.q0) - q*q))\n    # return -z*log(q - z*sqrt(one(q.q0) - q*q))\nend\n\nfunction asin(q::Quaternion)\n    x = imag(q)\n    y = abs(x)\n    z = y!=zero(q.q0) ? x/y : quaternion(one(q.q0)*im)\n\n    return -z*log(z*q + sqrt(one(q.q0) - q*q))\n    #= return -z*log(z*q - sqrt(one(q.q0) - q*q)) =#\nend\n\nfunction atan(q::Quaternion)\n    x = imag(q)\n    y = abs(x)\n    z = y!=zero(q.q0) ? x/y : quaternion(one(q.q0)*im)\n\n    return -z*log((one(q.q0)+z*q)/(one(q.q0)-z*q))/2\nend\n", "meta": {"hexsha": "e2b2d08259081f23cb612ea4358f686f1770c11e", "size": 1809, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/qmath.jl", "max_stars_repo_name": "peakbook/Quaternion.jl", "max_stars_repo_head_hexsha": "de4d6bde36b83081d5ce5c77a6e1a920d55062a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-11-04T17:54:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:16:46.000Z", "max_issues_repo_path": "src/qmath.jl", "max_issues_repo_name": "peakbook/Quaternion.jl", "max_issues_repo_head_hexsha": "de4d6bde36b83081d5ce5c77a6e1a920d55062a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-11-11T03:11:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-25T10:10:07.000Z", "max_forks_repo_path": "src/qmath.jl", "max_forks_repo_name": "peakbook/Quaternion.jl", "max_forks_repo_head_hexsha": "de4d6bde36b83081d5ce5c77a6e1a920d55062a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-06-21T17:44:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:14:42.000Z", "avg_line_length": 23.1923076923, "max_line_length": 88, "alphanum_fraction": 0.580983969, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992905050947, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7867736936280247}}
{"text": "\"\"\"\n    erlang_rng(k, λ, shape=1; seed=nothing)\n\nGenerate a `shape` element array of random variables from a Erlang_{`k`}(`λ`) distribution. Optionally you can set a specific seed.\n\n# Notes\n\nThe pdf of an Erlang_{k}(λ) distribution is given as:\n\n``f(x, k, λ) = \\\\frac{λ^k e^{-λx} x^{k-1}}{(k-1)!} \\\\quad x ≥ 0``\n\n# Examples\n\n```julia-repl\njulia> erlang_rng(5, .5)\n1-element Vector{Float64}:\n 10.803989701023117\n\njulia> erlang_rng(3, 1, (2,2))\n2×2×1 Array{Float64, 3}:\n[:, :, 1] =\n 2.19956  4.18505\n 5.46892  2.5633\n```\n\n# References\n\nD. Goldsman, P. Goldsman. A first course in probability and statistics. 2021.\n\nL. Martino, D. Luengo. Extremely efficient generation of Gamma random variables for α ≥ 1. 2013.\n\"\"\"\nfunction erlang_rng(k::Int, λ::Real, shape::Union{Int, Tuple{Vararg{Int}}}=1; seed::Union{Int, Nothing}=nothing)\n    U = get_std_uniform((shape..., k), seed=seed)\n    k_dim = ndims(U)  # k is final dimension\n    X = (-1/λ) .* log.(prod(U, dims=k_dim))  # Here (-1/λ) represents mean\n    return X\nend\n", "meta": {"hexsha": "db79c5b60123e0be6411ab12d01c7a4431bbbc64", "size": 1014, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/erlang.jl", "max_stars_repo_name": "chris-santiago/RandomVariates.jl", "max_stars_repo_head_hexsha": "75cf7057d06482f5208233f0f78f08e0dcfee58f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/erlang.jl", "max_issues_repo_name": "chris-santiago/RandomVariates.jl", "max_issues_repo_head_hexsha": "75cf7057d06482f5208233f0f78f08e0dcfee58f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/erlang.jl", "max_forks_repo_name": "chris-santiago/RandomVariates.jl", "max_forks_repo_head_hexsha": "75cf7057d06482f5208233f0f78f08e0dcfee58f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6842105263, "max_line_length": 131, "alphanum_fraction": 0.6538461538, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8311430562234878, "lm_q1q2_score": 0.7867572519854674}}
{"text": "## Spectral clustering on artists\nusing DelimitedFiles\nusing SparseArrays\nnames = readlines(\"../2-unit-1-demos/artistsim.names\")\ndata = readdlm(\"../2-unit-1-demos/artistsim.smat\")\nxy = readdlm(\"artistsim.xy\")\nA = sparse(Int.(data[2:end,1]).+1,\n           Int.(data[2:end,2]).+1,\n           Int.(data[2:end,3]),\n           Int(data[1,1]),Int(data[1,1]))\nn = size(A,1)\n##\nfunction simplepagerank(A,α,v)\n  @assert(0 ≤ α < 1, \"needs probably α\")\n  @assert(all(vi -> vi ≥ 0, v), \"needs non-negative v\")\n  v = v ./ sum(v) # we can normalize for them.\n  d = vec(sum(A,dims=2)) # compute the degrees\n  x = copy(v) # start of with v\n  nsteps = 2*ceil(Int,log(eps(1.0))/log(α)) # upper bound on steps\n  for i=1:nsteps\n    x = α*(A'*(x./d)) .+ (1-α).*v\n  end\n  return x./sum(x) # renormalize to probability\nend\n##\nusing MatrixNetworks\npr = MatrixNetworks.pagerank(A,0.85)\n##\nx = simplepagerank(A,0.85,ones(n)./n)\n##\nusing LinearAlgebra\n@show norm(x-pr)\n\n##\n@time pr = MatrixNetworks.pagerank(A,0.85)\n@time x = simplepagerank(A,0.85,ones(n)./n)\n@show norm(x-pr)\n## Let's watch PageRank converge\nusing Plots\nfunction pagerank_converence_animation(A,xy,α,nsteps)\n  n = size(A,1)\n  v = ones(n)/n\n  @assert(0 ≤ α < 1, \"needs probably α\")\n  @assert(all(vi -> vi ≥ 0, v), \"needs non-negative v\")\n  v = v ./ sum(v) # we can normalize for them.\n  d = vec(sum(A,dims=2)) # compute the degrees\n  x = copy(v) # start of with v\n\n  @assert(nsteps <= size(A,1))\n  anim = @animate for i=1:nsteps\n    x = α*(A'*(x./d)) .+ (1-α).*v\n    f2 = copy(x)\n    f2 = f2/sum(f2)\n    p = sortperm(f2) # this gets things to draw in the right z-order\n    scatter(xy[p,1],xy[p,2], marker_z=-abs.(log10.(f2[p])).^0.5,colorbar=false,alpha=0.5,\n      color=:magma,\n      size=(1200,1200),\n      markerstrokecolor=nothing,markerstrokewidth=0,label=\"\",framestyle=:none,background=:black)\n  end\n  return anim\nend\nanim = pagerank_converence_animation(A,xy,0.85,25)\ngif(anim,\"pagerank-convergence-artistsim.gif\",fps=5)\n\n## Change between iterates\nfunction pagerank_converence_plot(A,xy,α,nsteps)\n  n = size(A,1)\n  v = ones(n)/n\n  @assert(0 ≤ α < 1, \"needs probably α\")\n  @assert(all(vi -> vi ≥ 0, v), \"needs non-negative v\")\n  v = v ./ sum(v) # we can normalize for them.\n  d = vec(sum(A,dims=2)) # compute the degrees\n  x = copy(v) # start of with v\n  y = copy(v)\n  hist = zeros(0)\n  for i=1:nsteps\n    x = α*(A'*(x./d)) .+ (1-α).*v\n    push!(hist, norm(y - x/sum(x),1))\n    y = x/sum(x)\n  end\n  return hist\nend\nhist = pagerank_converence_plot(A,xy,0.85,100)\n##\npyplot()\ntheme(:dark)\nplot(hist, yscale=:log10, legend=false, size=(300,300))\nxlabel!(\"Iteration\")\nylabel!(\"1-norm change in normalized vector\")\nsavefig(\"pagerank-convergence-artistsim-norm.pdf\")\n##\nx85 = simplepagerank(A,0.85,ones(n)./n)\nx99 = simplepagerank(A,0.99,ones(n)./n)\nx5 = simplepagerank(A,0.5,ones(n)./n)\n##\n\n## Show a few different vectors\ngr()\np=sortperm(x99)\nscatter(xy[p,1],xy[p,2],marker_z=-abs.(log10.(x99[p])).^0.5,markerstrokewidth=0,\ncolor=:magma)\n##\ngr()\np=sortperm(x5)\nscatter(xy[p,1],xy[p,2],marker_z=-abs.(log10.(x5[p])).^0.5,markerstrokewidth=0,\ncolor=:magma)\n\n## Now show the entire graph\nusing GraphRecipes\nusing LinearAlgebra\nusing Plots\n\nei, ej = findnz(A)\ngraphplot(ei, ej, x =xy[:,1], y=xy[:,2],\n  markercolor=:black, markerstrokecolor=:white,\n  size=(1200,1200),dpi=300,\n  markersize=0, linecolor=1, linealpha=0.01, linewidth=0.5,\n  markeralpha=0.2,colorbar=false,\n  axis_buffer=0.02, background=nothing)\np=sortperm(x5)\nscatter!(xy[p,1],xy[p,2],marker_z=-abs.(log10.(x5[p])).^0.5,markerstrokewidth=0)\nsavefig(\"artistsim-pagerank-50.png\")\n\n##\nei, ej = findnz(A)\ngraphplot(ei, ej, x =xy[:,1], y=xy[:,2],\n  markercolor=:black, markerstrokecolor=:white,\n  size=(1200,1200),dpi=300,\n  markersize=0, linecolor=1, linealpha=0.01, linewidth=0.5,\n  markeralpha=0.2,colorbar=false,\n  axis_buffer=0.02, background=nothing)\np=sortperm(x99)\nscatter!(xy[p,1],xy[p,2],marker_z=-abs.(log10.(x99[p])).^0.5,markerstrokewidth=0)\nsavefig(\"artistsim-pagerank-99.png\")\n", "meta": {"hexsha": "84899338d7ea3002a03528a828fa0f36dae3360b", "size": 3992, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5-unit-4-demos/pagerank-artistsim.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "5-unit-4-demos/pagerank-artistsim.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5-unit-4-demos/pagerank-artistsim.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 29.5703703704, "max_line_length": 96, "alphanum_fraction": 0.6533066132, "num_tokens": 1451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966762263736, "lm_q2_score": 0.8311430520409024, "lm_q1q2_score": 0.7867572505305621}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, StatsBase, Distributions, Plots, LaTeXStrings\n\tRandom.seed!(0)\nend\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.16\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tmu0, mu1a, mu1b, mu1c, sd = 15, 16, 18, 20, 2\n\ttauGrid = 5:0.1:25\n\n\tdist0 = Normal(mu0,sd)\n\tdist1a, dist1b, dist1c  = Normal(mu1a,sd), Normal(mu1b,sd), Normal(mu1c,sd)\n\n\tfalsePositive = ccdf.(dist0,tauGrid)\n\ttruePositiveA, truePositiveB, truePositiveC = \n\t    ccdf.(dist1a,tauGrid), ccdf.(dist1b,tauGrid), ccdf.(dist1c,tauGrid)\nend\n\n# ╔═╡ a80f7e58-3af9-11eb-04b3-57fcb9ee857c\nbegin\n\tplot(falsePositive, [truePositiveA truePositiveB truePositiveC], \n\t\tc=[:blue :red :green], \n\t\tlabel=[L\"H1a: \\mu_1 = 16\" L\"H1b: \\mu_1 = 18\" L\"H1c: \\mu_1 = 20\"])\n\tplot!([0,1], [0,1], c=:black, ls=:dash, label=\"H0 = H1 = 15\", \n\t\txlims=(0,1), ylims=(0,1), xlabel=L\"\\alpha\", ylabel=\"Power\", \n\t\tratio=:equal, legend=:bottomright)\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.16\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═a80f7e58-3af9-11eb-04b3-57fcb9ee857c\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "219da222f6377a01fdeee0e352fa72e76c918114", "size": 1486, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/listing5.16.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/05/listing5.16.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/05/listing5.16.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 28.0377358491, "max_line_length": 76, "alphanum_fraction": 0.7072678331, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7867572455219296}}
{"text": "#\"Read\" data for parametric sinusoidal \"simulation\" & parameter extraction\n#-------------------------------------------------------------------------------\n\nusing CMDimData\nusing CMDimData.MDDatasets\n\nconst π = MathConstants.π\n\n#==Emulate reading in simulated data file\n===============================================================================#\n\n#=COMMENT\nThe code below emulates a parametric \"simulation\" of a sinusoidal response where\nthe 𝜙, A, and 𝑓 parameters of `signal = A * sin(𝜔*t + 𝜙); 𝜔 = 2π*𝑓` are varied.\n\nThe parametric signal can therefore be fully represented as:\n\tsignal(𝜙, A, 𝑓, t)\n=#\n\n#But really construct multidimensional DataRS dataset manually:\nsignal = fill(DataRS, PSweep(\"phi\", [0, 0.5, 1] .* (π/4))) do 𝜙\n\tfill(DataRS, PSweep(\"A\", [1, 2, 4] .* 1e-3)) do A\n\t#Inner-most sweep: need to specify element type (DataF1):\n\t#(Other (scalar) element types: DataInt/DataFloat/DataComplex)\n\tfill(DataRS{DataF1}, PSweep(\"freq\", [1, 4, 16] .* 1e3)) do 𝑓\n\t\t𝜔 = 2π*𝑓\n\t\tT = 1/𝑓\n\t\tΔt = T/100 #Define resolution from # of samples per period\n\t\tTsim = 4T #Simulated time\n\n\t\tt = DataF1(0:Δt:Tsim) #DataF1 creates a t:{y, x} container with y == x\n\t\tsig = A * sin(𝜔*t + 𝜙) #Still a DataF1 sig:{y, x=t} container\n\t\treturn sig\nend; end; end\n\nreturn signal\n", "meta": {"hexsha": "887ac6c8290f0cd708001d0ce894558a57801aeb", "size": 1263, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "sample/analysis_fmtfiles/parametric_sin_data.jl", "max_stars_repo_name": "ma-laforge/CMDimData.jl", "max_stars_repo_head_hexsha": "f543265841b81dc20f5dca18a37cd642371a0a34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sample/analysis_fmtfiles/parametric_sin_data.jl", "max_issues_repo_name": "ma-laforge/CMDimData.jl", "max_issues_repo_head_hexsha": "f543265841b81dc20f5dca18a37cd642371a0a34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sample/analysis_fmtfiles/parametric_sin_data.jl", "max_forks_repo_name": "ma-laforge/CMDimData.jl", "max_forks_repo_head_hexsha": "f543265841b81dc20f5dca18a37cd642371a0a34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1351351351, "max_line_length": 80, "alphanum_fraction": 0.60253365, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7867365514245809}}
{"text": "#######################################################################################################################################################################################################\n#\n# Changes made to this function\n# General\n#     2020-Mar-30: migrate the function from SCOPE\n#     2021-Oct-21: rename the function to average_transmittance\n#     2022-Feb-02: fix documentation\n# To do\n#     TODO: figure out where does this equation comes from\n#\n#######################################################################################################################################################################################################\n\"\"\"\n\n    average_transmittance(α::FT, nr::FT) where {FT<:AbstractFloat}\n\nReturn the average transmittance of isotropic radiation across an interface between two dielectrics, given\n- `α` angle of incidence\n- `nr` Index of refraction\n\n# References\n- Stern (1964) Transmission of isotropic radiation across an interface between two dielectrics. Applied Optics 3(1): 111-113.\n- Allen (1973) Transmission of isotropic light across a dielectric surface in two and three dimensions. Journal of the Optical Society of America 63(6): 664-666.\n\"\"\"\nfunction average_transmittance(α::FT, nr::FT) where {FT<:AbstractFloat}\n    @assert 0 < α <= 90;\n\n    # some shortcuts to avoid overly comlicated equation\n    _a     = (nr + 1) ^ 2 / 2;\n    _a³    = _a ^ 3;\n    _n²    = nr ^ 2;\n    _n⁴    = nr ^ 4;\n    _n⁶    = nr ^ 6;\n    _n²p   = _n² + 1;\n    _n²p²  = _n²p ^ 2;\n    _n²p³  = _n²p ^ 3;\n    _n²m²  = (_n² - 1) ^ 2;\n    _k     = -1 * _n²m² / 4;\n    _k²    = _k ^ 2;\n    _sin²α = sind(α) ^ 2;\n    _b₂    = _sin²α - _n²p/2;\n    _b₁    = (α==90 ? 0 : sqrt(_b₂ ^ 2 + _k));\n    _b     = _b₁ - _b₂;\n    _b³    = _b ^ 3;\n    _npanm = 2 * _n²p * _a - _n²m²;\n    _npbnm = 2 * _n²p * _b - _n²m²;\n\n    # S polarization\n    _ts  = ( _k² / (6*_b³) + _k/_b - _b/2 ) - ( _k² / (6*_a³) + _k/_a - _a/2 );\n\n    # P polarization\n    _tp₁ = -2 * _n² * (_b - _a) / _n²p²;\n    _tp₂ = -2 * _n² * _n²p * log(_b / _a) / _n²m²;\n    _tp₃ = _n² * (1/_b - 1/_a) / 2;\n    _tp₄ = 16 * _n⁴ * (_n⁴ + 1) * log(_npbnm / _npanm) / (_n²p³ * _n²m²);\n    _tp₅ = 16 * _n⁶ * (1/_npbnm - 1/_npanm) / _n²p³;\n    _tp  = _tp₁ + _tp₂ + _tp₃ + _tp₄ + _tp₅;\n\n    return  (_ts + _tp) / (2 * _sin²α)\nend\n", "meta": {"hexsha": "35021f888ca237147623c92d2fe2ba82fc5ea7a8", "size": 2307, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transmittance.jl", "max_stars_repo_name": "Yujie-W/LeafOptics.jl", "max_stars_repo_head_hexsha": "7088cecf32d7d6664012c3cfacc3bedc6626e93b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/transmittance.jl", "max_issues_repo_name": "Yujie-W/LeafOptics.jl", "max_issues_repo_head_hexsha": "7088cecf32d7d6664012c3cfacc3bedc6626e93b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-02T22:12:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T22:21:25.000Z", "max_forks_repo_path": "src/transmittance.jl", "max_forks_repo_name": "Yujie-W/LeafOptics.jl", "max_forks_repo_head_hexsha": "7088cecf32d7d6664012c3cfacc3bedc6626e93b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.45, "max_line_length": 199, "alphanum_fraction": 0.4824447334, "num_tokens": 821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.786736549495907}}
{"text": "export logadd, logsub, log1mexp, log1pexp, inf\n\n\nfunction inf(::Type{T})::T where T\n    one(T) / zero(T)\nend\n\nfunction inf(x::T)::T where T\n    inf(T)\nend\n\n\n\"log(x+y) from log(x) and log(y)\"\nfunction logadd(lx, ly)\n    if lx > ly\n        return logadd(ly, lx)\n    elseif -Inf < lx ≤ ly < Inf\n        return ly + log1p(exp(lx - ly))\n    else\n        return ly\n    end\nend\n\nlogadd(lx, ly, lz, ls...) = foldl(logadd, (logadd(logadd(lx,ly),lz), ls...))\n\n\n\"log(|x-y|) from log(x) and log(y)\"\nfunction logsub(lx, ly)\n    if min(lx, ly) > -Inf\n        return max(lx, ly) + log1mexp(abs(lx - ly))\n    else\n        return max(lx, ly)\n    end\nend\n\n\n\"log(1 - exp(-x)), x ≥ 0\"\nfunction log1mexp(x)\n    # https://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf, Eq. 7\n    x ≥ 0 || throw(DomainError())\n    if x ≤ log(2)\n        log(-expm1(-x))\n    else\n        log1p(-exp(-x))\n    end\nend\n\n\n\"log(1 + exp(x))\"\nfunction log1pexp(x)\n    # https://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf, Eq. 10\n    if x ≤ -37\n        exp(x)\n    elseif -37 < x ≤ 18\n        log1p(exp(x))\n    elseif 18 < x ≤ 33.3\n        x + exp(-x)\n    else\n        x\n    end\nend\n", "meta": {"hexsha": "b47bcea8ec60c48caa494634d307f94198a519f5", "size": 1175, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math.jl", "max_stars_repo_name": "cossio/LogMath.jl", "max_stars_repo_head_hexsha": "b02e607145cd569a9cb3cbe5942fffcdeddce722", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math.jl", "max_issues_repo_name": "cossio/LogMath.jl", "max_issues_repo_head_hexsha": "b02e607145cd569a9cb3cbe5942fffcdeddce722", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math.jl", "max_forks_repo_name": "cossio/LogMath.jl", "max_forks_repo_head_hexsha": "b02e607145cd569a9cb3cbe5942fffcdeddce722", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9516129032, "max_line_length": 87, "alphanum_fraction": 0.5514893617, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877684006775, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.7867219565277043}}
{"text": "module SDM\n\nusing LinearAlgebra\nusing Printf\n\ninclude(\"utility.jl\")\ninclude(\"graphics.jl\")\n\nexport sdm\n\nfunction sdm(fun, fun_derivative, starting_point, step_size_params, epsilon; display_g=true)\n    type = get(step_size_params, \"type\", \"constant\")\n    method = get(SDM_step_size_methods, type, constant_step_size_sdm)\n    return method(fun, fun_derivative, starting_point, step_size_params, epsilon, display_g)\nend\n\nfunction constant_step_size_sdm(fun, fun_derivative, starting_point, step_size_params, epsilon, display_g)\n    @printf(\"Press enter to continue with iterations\\n\")\n    @printf(\"step\\t\\tposition\\t\\tgradient_norm\\n\")\n\n    gradient = fun_derivative(starting_point[1], starting_point[2])\n    x = [starting_point[1], starting_point[2]]\n\n    step_counter = 1\n    while(true)\n        \n        #we move in the opposite direction of the gradient\n        d = -gradient\n        #step size is constant\n        alpha = get(step_size_params, \"step_size\", 0.1)\n        #move to the next point\n        movement = alpha*d\n        if display_g\n            display(add_vector(x, movement))\n        end\n        x = x + movement\n\n        gradient_norm = norm(gradient, 2)\n        @printf(\"%d\\t\\t[%g,%g]\\t\\t%g\", step_counter, x[1], x[2], gradient_norm)\n\n        #we stop whenever the norm of the gradient is lower than a certain epsilon\n        if (gradient_norm < epsilon)\n            break\n        end\n        \n        wait_for_key(\"\")\n\n        step_counter += 1\n\n        #calculate the gradient for the new iteration\n        gradient = fun_derivative(x[1], x[2])\n    end\n\n    @printf(\"\\n\")\n    return x\nend\n\nfunction quadratic_step_size_sdm(fun, fun_derivative, starting_point, step_size_params, epsilon, display_g)\n    @printf(\"Press enter to continue with iterations\\n\")\n    @printf(\"step\\t\\tposition\\t\\tgradient_norm\\n\")\n\n    Q = get(step_size_params, \"Q\", false)\n    if Q==false error(\"Q not set in step_size_params\"); return; end;\n\n    gradient = fun_derivative(starting_point[1], starting_point[2])\n    x = [starting_point[1], starting_point[2]]\n\n    step_counter = 1\n    while(true)\n        \n        #we move in the opposite direction of the gradient\n        d = -gradient\n        #best step size, if the function is a quadratic function\n        alpha = (norm(d,2)^2)/(d'*Q*d)\n        #move to the next point\n        movement = alpha*d\n        if display_g\n            display(add_vector(x, movement))\n        end\n        x = x + movement\n\n        gradient_norm = norm(gradient, 2)\n        @printf(\"%d\\t\\t[%f,%f]\\t\\t%g\", step_counter, x[1], x[2], gradient_norm)\n\n        #we stop whenever the norm of the gradient is lower than a certain epsilon\n        if (gradient_norm < epsilon)\n            break\n        end\n        \n        wait_for_key(\"\")\n\n        step_counter += 1\n\n        #calculate the gradient for the new iteration\n        gradient = fun_derivative(x[1], x[2])\n    end\n\n    @printf(\"\\n\")\n    return x\nend\n\nSDM_step_size_methods = Dict([\n    (\"constant\", constant_step_size_sdm), \n    (\"quadratic\", quadratic_step_size_sdm)\n])\n\nend\n", "meta": {"hexsha": "4bc7dafe2261801bf7cd83b52fa4c72facb2d78f", "size": 3051, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SDM.jl", "max_stars_repo_name": "WilliamSimoni/Computational-Mathematics-Resources", "max_stars_repo_head_hexsha": "67aa6cd3f9125d26ad54c3027be8cd680ac88393", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SDM.jl", "max_issues_repo_name": "WilliamSimoni/Computational-Mathematics-Resources", "max_issues_repo_head_hexsha": "67aa6cd3f9125d26ad54c3027be8cd680ac88393", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SDM.jl", "max_forks_repo_name": "WilliamSimoni/Computational-Mathematics-Resources", "max_forks_repo_head_hexsha": "67aa6cd3f9125d26ad54c3027be8cd680ac88393", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.25, "max_line_length": 107, "alphanum_fraction": 0.6404457555, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.7867049172835618}}
{"text": "\"\"\" Predator prey model with logistic function from http://www.math.lsa.umich.edu/~rauch/256/F2Lab5.pdf \"\"\"\nfunction foxes_and_rabbits(oct::Bool = true)\n    m = Model(SOLVER_SILENT)\n    t = 20\n    r = 0.2\n    x1 = 0.6\n    y1 = 0.5\n    @variable(m, x[1:t] >= 0.01) # Note: Ipopt solution does not converge with an upper bound!!\n    @variable(m, dx[1:t-1])\n    @variable(m, y[1:t] >= 0.01)\n    @variable(m, dy[1:t-1])\n    @constraint(m, x[1] == x1)\n    @constraint(m, y[1] == y1)\n    @constraint(m, [i=2:t], x[i] == x[i-1] + dx[i-1])\n    @constraint(m, [i=2:t], y[i] == y[i-1] + dy[i-1])\n    \n    # GlobalModel representation\n    set_upper_bound.(x, 1)\n    set_upper_bound.(dx, 1)\n    set_lower_bound.(dx, -1)\n    set_upper_bound.(y, 1)\n    set_upper_bound.(dy, 1)\n    set_lower_bound.(dy, -1)\n\n    if !oct\n        @NLconstraint(m, [i=1:t-1], dx[i] == x[i]*(1-x[i]) - x[i]*y[i]/(x[i]+1/5))\n        @NLconstraint(m, [i=1:t-1], dy[i] == r*y[i]*(1-y[i]/x[i]))\n        return m\n    else\n        gm = GlobalModel(model = m, name = \"foxes_rabbits\")\n        add_nonlinear_constraint(gm, :((x, y, dx) -> dx[1] - (x[1]*(1-x[1]) -x[1]*y[1]/(x[1]+$(r)))), \n                                vars = [x[1], y[1], dx[1]], equality=true)\n        add_nonlinear_constraint(gm, :((x, y, dy) -> dy[1] - $(r)*y[1]*(1-y[1]/x[1])), \n                                vars = [x[1], y[1], dy[1]], equality=true)\n        for i = 2:t-1\n            add_linked_constraint(gm, gm.bbls[1], [x[i], y[i], dx[i]])\n            add_linked_constraint(gm, gm.bbls[2], [x[i], y[i], dy[i]])\n        end\n        return gm\n    end\nend", "meta": {"hexsha": "bf8e5843eddee1079cbaea11cf0d18d1d5e02f27", "size": 1587, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "data/foxes_and_rabbits.jl", "max_stars_repo_name": "1ozturkbe/OCTHaGOn.jl", "max_stars_repo_head_hexsha": "222a73c8da834c8e4114b6f29492d8ab917f6722", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data/foxes_and_rabbits.jl", "max_issues_repo_name": "1ozturkbe/OCTHaGOn.jl", "max_issues_repo_head_hexsha": "222a73c8da834c8e4114b6f29492d8ab917f6722", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2022-02-13T15:33:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T15:45:11.000Z", "max_forks_repo_path": "data/foxes_and_rabbits.jl", "max_forks_repo_name": "1ozturkbe/OCTHaGOn.jl", "max_forks_repo_head_hexsha": "222a73c8da834c8e4114b6f29492d8ab917f6722", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7073170732, "max_line_length": 107, "alphanum_fraction": 0.5072463768, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8633916064587, "lm_q1q2_score": 0.7867049156821269}}
{"text": "#' ## What is learning?\n#'\n#' Computers read data, as we saw in notebooks 1 and 2. We can then build\n#' functions that model that data to make decisions, as we saw in notebooks\n#' 3 and 5.\n#'\n#' But how do you make sure that the model actually fits the data well?\n#' In the last notebook, we saw that we can fiddle with the parameters of our\n#' function defining the model to reduce the loss function. However,\n#' we don't want to have to pick the model parameters ourselves.\n#' Choosing parameters ourselves works *well enough* when we have a\n#' simple model and only a few data points, but can quickly become\n#' extremely complex for more detailed models and larger data sets.\n#'\n#' Instead, we want our machine to *learn* the parameters that fit the model\n#' to our data, without needing us to fiddle with the parameters ourselves.\n#' In this notebook, we'll talk about the \"learning\" in machine learning.\n\n#' ### Motivation: Fitting parameters by hand\n#'\n#' Let's go back to our example of fitting parameters from notebook 3.\n#' Recall that we looked at whether the amount of green in the pictures\n#' could distinguish between an apple and a banana, and used a sigmoid\n#' function to model our choice of \"apple or banana\" using the amount of\n#' green in an image.\n\nusing Plots\ngr()\nusing Images, Statistics\n\nsigma(x,w,b) = 1/(1 + exp(-w*x + b))\n\napple = load(\"data/10_100.jpg\")\nbanana = load(\"data/104_100.jpg\")\napple_g = mean(Float64.(green.(apple)))\nbanana_g = mean(Float64.(green.(banana)))\n\nw = 10.0 # Try manipulating w between 0 and 30 to see how the plot changes\nb = 15.0 # Try manipulating b bewteen 0 and 30\n\npl = plot(x->sigma(x,w,b), xlims=(0, 1))\nscatter!([apple_g], [0.0], label=\"Apple\")\nscatter!([banana_g], [1.0], label=\"Banana\")\n\n#' Intuitively, how did you tweak the sliders so that way the model sends\n#' apples to 0 and bananas to 1? Most likely, you did the following:\n\n#' #### Move the sliders a bit, see whether the curve moves in the right\n#' direction, and if it did, keep doing it.\n\n#' For a machine, \"learning\" is that same process, translated into math!\n\n#' ## \"Learning by nudging\": The process of descent\n#'\n#' Let's start to formalize this idea. In order to push the curve in the\n#' \"right direction\", we need some measurement of \"how right\" and \"how wrong\"\n#' the model is. When we translate the idea of a \"right direction\" into math,\n#' we end up with a **loss function**, `L(w, b)`, as we saw in notebook 5.\n#' We say that the loss function is lowest when the model `σ(x, w, b)`\n#' performs the best.\n#'\n#' Now we want to create a loss function that is the lowest when the apple is\n#' at `0` and the banana is at `1`. If the data (the amount of green) for\n#' our apple is $x_1$, then our model will output $σ(x_1,w, b)$ for our apple.\n#' So, we want the difference $0 - σ(x_1, w, b)$ to be small. Similarly, if our\n#' data for our banana (the banana's amount of green) is $x_2$, we want the\n#' difference $1 - σ(x_2, w, b)$ to be small.\n#'\n#' To create our loss function, let's add together the squares of the\n#' difference of the model's output from the desired output for the apple\n#' and the banana. We get\n#'\n#' $$ L(w,b) = (0 - σ(x_1, w, b))^2 + (1 - σ(x_2, w, b))^2. $$\n#'\n#' $L(w, b)$ is lowest when it outputs `0` for the apple and `1` for the\n#' banana, and thus the cost is lowest when the model \"is correct\".\n#'\n#' We can visualize this function by plotting it in 3D with the\n# `surface` function or in 2D with contour lines\n\n# plotly() # The plotly backend is nice for 3d surface plots\n# gr() # The GR backend is good for faster interactive plots\n\nL(w,b) = (0 - sigma(apple_g,w,b))^2 + (1 - sigma(banana_g,w,b))^2\n\nw_range = 10:0.1:13\nb_range = 0:1:20\nL_values = [L(w,b) for b in b_range, w in w_range]\n\nw = 11.5 # Try manipulating w with values from w_range (between 10 and 13)\nb = 7 # Try manipulating b with values from b_range (between 0 and 20)\n##     p1 = surface(w_range, b_range, L_values, xlabel=\"w\", ylabel=\"b\", cam=(70,40), cbar=false, leg=false)\n##     scatter!(p1, [w], [b], [L(w,b)+1e-2], markersize=5, color = :blue)\np1 = contour(w_range, b_range, L_values, levels = 0.05:0.1:1,\n    xlabel=\"w\", ylabel=\"b\", cam=(70,40), cbar=false, legend=false)\nscatter!(p1, [w], [b], markersize=5, color=RGB(0.05, 0.05, 0.90))\n\np2 = plot(x->sigma(x,w,b), 0, 1, label=\"Model\", legend=(0.1,0.9), lw=3)\nscatter!(p2, [apple_g], [0.0], label=\"Apple\", markersize=8)\nscatter!(p2, [banana_g], [1.0], label=\"Banana\", markersize=8, xlim=(0,1),\n    ylim=(-0.1,1.1))\nplot(p1, p2, layout=(2,1))\n\n#' The blue ball on the 3D plot shows the current parameter choices,\n#' plotted as `(w,b)`. Shown below the 3D plot is a 2D plot of the\n#' corresponding model with those parameters. Notice that as the blue ball\n#' rolls down the hill, the model becomes a better fit. Our loss function\n#' gives us a mathematical notion of a \"hill\", and the process of\n#' \"learning by nudging\" is simply rolling the ball down that hill.\n\n#' To do this mathematically, we need to know which direction is \"downhill\".\n#' Recall from calculus that the derivative of `L` with respect to `b` tells\n#' you how `L` changes when `b` changes. Thus to roll downhill, we should go\n#' in the direction where the derivative is negative (the function goes down)\n#' for each parameter. This direction is the negative of what's called the\n#' **gradient**, $\\nabla L$. This means that the \"learn by nudging method\"\n#' can be rephrased in mathematical terms as:\n#'\n#' 1. Calculate the gradient\n#' 2. Move a little bit in the direction of the negative gradient\n#' 3. Repeat\n\n#' This process of rolling the ball in the direction of the negative gradient\n#' is called **gradient descent**; written mathematically, it is\n#'\n#' $$p_{n+1} = p_n - \\eta \\nabla L(p_n).$$\n#'\n#' Here, $p_n$ represents the vector of current parameters\n#' $(w, b)$; $\\nabla L(p_n)$ is the gradient of the loss function, given\n#' those parameters. We start from $p_n$ and change it by $\\eta \\nabla L(p_n)$,\n#' where $\\eta$ is a small step size that determines how far we move the\n#' parameters in the direction of the negative gradient; notice that if you\n#' step too far, you'll overshoot the minimum!. The result is\n#' $p_{n+1}$, the new vector of parameters.\n#'\n#' [Picture of Gradient Descent Vectors]\n#'\n#' If we repeat this process, then we will end up at parameters where the\n#' model correctly labels apples as `0` and bananas as `1`. When this happens,\n#' the model has learned from the data and can then read pictures and tell\n#' you whether they are apples or bananas!\n\n#' #### Exercise 1\n#'\n#' Use the following terms to fill in the sentences below.\n#' Terms may be used more than once or not at all:\n#' > gradient, loss function, derivative, gradient descent, learning.\n#'\n#' * We can think of a _(A)_ as a 1D version of a _(B)_.\n#' * We can visualize a _(C)_ as a hill.\n#' * In the explanation above, rolling downhill is called _(D)_ and means traveling along the _(E)_.\n#' * To quantify the correctness of a model we use a _(F)_.\n#' * When our program can minimize a _(G)_ on its own, we say it is _(H)_.\n#'\n#' <br><br>\n#'\n#' A)<br>\n#' B)<br>\n#' C)<br>\n#' D)<br>\n#' E)<br>\n#' F)<br>\n#' G)<br>\n#' H)<br>\n", "meta": {"hexsha": "828f45d5aa90821099635282711104a0985528e2", "size": 7184, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JuliaAcademy/FundMachLearn/ch0900.jl", "max_stars_repo_name": "ykyang/org.allnix.julia", "max_stars_repo_head_hexsha": "58933a5848dec81c53d591b4163e9a70df62ddd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JuliaAcademy/FundMachLearn/ch0900.jl", "max_issues_repo_name": "ykyang/org.allnix.julia", "max_issues_repo_head_hexsha": "58933a5848dec81c53d591b4163e9a70df62ddd8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JuliaAcademy/FundMachLearn/ch0900.jl", "max_forks_repo_name": "ykyang/org.allnix.julia", "max_forks_repo_head_hexsha": "58933a5848dec81c53d591b4163e9a70df62ddd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5393939394, "max_line_length": 107, "alphanum_fraction": 0.6895879733, "num_tokens": 2084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.8670357529306639, "lm_q1q2_score": 0.7866721328175686}}
{"text": "# Linear ODE\nlinear = (u,p,t) -> (p*u)\nlinear_analytic = (u0,p,t) -> u0*exp(p*t)\n\"\"\"\nLinear ODE\n\n```math\n\\\\frac{du}{dt} = αu\n```\n\nwith initial condition ``u0=1/2``, ``α=1.01``, and solution\n\n```math\nu(t) = u0e^{αt}\n```\n\nwith Float64s. The parameter is ``α``\n\"\"\"\nprob_ode_linear = ODEProblem(\n                  ODEFunction(linear,analytic=linear_analytic),\n                  1/2,(0.0,1.0),1.01)\n\n\"\"\"\nLinear ODE\n\n```math\n\\\\frac{du}{dt} = αu\n```\n\nwith initial condition ``u0=1/2``, ``α=1.01``, and solution\n\n```math\nu(t) = u0e^{αt}\n```\n\nwith BigFloats\n\"\"\"\nprob_ode_bigfloatlinear = ODEProblem(\n                          ODEFunction(linear,analytic=linear_analytic),\n                          big(0.5),(0.0,1.0),big(1.01))\n\nf_2dlinear = (du,u,p,t) -> (@. du = p*u)\nf_2dlinear_analytic = (u0,p,t) -> @. u0*exp(p*t)\n\"\"\"\n4x2 version of the Linear ODE\n\n```math\n\\\\frac{du}{dt} = αu\n```\n\nwith initial condition ``u0=1/2``, ``α=1.01``, and solution\n\n```math\nu(t) = u0e^{αt}\n```\n\nwith Float64s\n\"\"\"\nprob_ode_2Dlinear = ODEProblem(\n                    ODEFunction(f_2dlinear,analytic=f_2dlinear_analytic),\n                    rand(4,2),(0.0,1.0),1.01)\n\n\"\"\"\n100x100 version of the Linear ODE\n\n```math\n\\\\frac{du}{dt} = αu\n```\n\nwith initial condition ``u0=1/2``, ``α=1.01``, and solution\n\n```math\nu(t) = u0e^{αt}\n```\n\nwith Float64s\n\"\"\"\nprob_ode_large2Dlinear = ODEProblem(\n                    ODEFunction(f_2dlinear,analytic=f_2dlinear_analytic),\n                    rand(100,100),(0.0,1.0),1.01)\n\n\"\"\"\n4x2 version of the Linear ODE\n\n```math\n\\\\frac{du}{dt} = αu\n```\n\nwith initial condition ``u0=1/2``, ``α=1.01``, and solution\n\n```math\nu(t) = u0e^{αt}\n```\n\nwith BigFloats\n\"\"\"\nprob_ode_bigfloat2Dlinear = ODEProblem(\n                    ODEFunction(f_2dlinear,analytic=f_2dlinear_analytic),\n                    BigFloat.(rand(4,2)).*ones(4,2)/2,(0.0,1.0),big(1.01))\n\nf_2dlinear_notinplace = (u,p,t) -> p*u\n\"\"\"\n4x2 version of the Linear ODE\n\n```math\n\\\\frac{du}{dt} = αu\n```\n\nwith initial condition ``u0=1/2``, ``α=1.01``, and solution\n\n```math\nu(t) = u0e^{αt}\n```\n\non Float64. Purposefully not in-place as a test.\n\"\"\"\nprob_ode_2Dlinear_notinplace = ODEProblem(\n                    ODEFunction(f_2dlinear_notinplace,analytic=f_2dlinear_analytic),\n                    rand(4,2),(0.0,1.0),1.01)\n", "meta": {"hexsha": "901e657878bd6851af213ded1c457c06be042c34", "size": 2272, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ode/ode_linear_prob.jl", "max_stars_repo_name": "EdelmanJonathan/DiffEqProblemLibrary.jl", "max_stars_repo_head_hexsha": "aead926134a936ffd4fba453586390074d64d6bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ode/ode_linear_prob.jl", "max_issues_repo_name": "EdelmanJonathan/DiffEqProblemLibrary.jl", "max_issues_repo_head_hexsha": "aead926134a936ffd4fba453586390074d64d6bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ode/ode_linear_prob.jl", "max_forks_repo_name": "EdelmanJonathan/DiffEqProblemLibrary.jl", "max_forks_repo_head_hexsha": "aead926134a936ffd4fba453586390074d64d6bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9333333333, "max_line_length": 84, "alphanum_fraction": 0.5761443662, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.7866721275272344}}
{"text": "######### Stan program example  ###########\n\nusing Mamba, Stan\n\nProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n\n  bernoullimodel = \"\n  data { \n    int<lower=1> N; \n    int<lower=0,upper=1> y[N];\n  } \n  parameters {\n    real<lower=0,upper=1> theta;\n  } \n  model {\n    theta ~ beta(1,1);\n    y ~ bernoulli(theta);\n  }\n  \"\n\n  observeddata = [\n    Dict(\"N\" => 10, \"y\" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]),\n    Dict(\"N\" => 10, \"y\" => [0, 1, 0, 0, 0, 0, 1, 0, 0, 1]),\n    Dict(\"N\" => 10, \"y\" => [0, 0, 0, 0, 0, 0, 1, 0, 1, 1]),\n    Dict(\"N\" => 10, \"y\" => [0, 0, 0, 1, 0, 0, 0, 1, 0, 1])\n  ]\n\n  initparms = Dict{String, Any}[\n    Dict(\"theta\" => 0.1),\n    Dict(\"theta\" => 0.4),\n    Dict(\"theta\" => 0.5),\n    Dict(\"theta\" => 0.9),\n  ]\n\n  monitor = [\"theta\", \"lp__\", \"accept_stat__\"]\n\n  global stanmodel, rc, sim1\n  stanmodel = Stanmodel(name=\"bernoulli\", model=bernoullimodel, num_warmup=1);\n  rc, sim1 = stan(stanmodel, observeddata, init=initparms, CmdStanDir=CMDSTAN_HOME)\n  \n  rc == 0 && sim1.value[1, end, :] |> display\nend # cd\n", "meta": {"hexsha": "b5af897d4c61370830c4463e5ae4d0c8658d66e8", "size": 1021, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/Mamba/BernoulliInitTheta/bernoulliinittheta.jl", "max_stars_repo_name": "fpmenninger/Stan.jl", "max_stars_repo_head_hexsha": "671e03a6e40748b070db206b0d8e907dbf90b86b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Examples/Mamba/BernoulliInitTheta/bernoulliinittheta.jl", "max_issues_repo_name": "fpmenninger/Stan.jl", "max_issues_repo_head_hexsha": "671e03a6e40748b070db206b0d8e907dbf90b86b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/Mamba/BernoulliInitTheta/bernoulliinittheta.jl", "max_forks_repo_name": "fpmenninger/Stan.jl", "max_forks_repo_head_hexsha": "671e03a6e40748b070db206b0d8e907dbf90b86b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2045454545, "max_line_length": 83, "alphanum_fraction": 0.5161606268, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678381, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7865978103246978}}
{"text": "# sample from a harmonic potential in 1D using GJF\nusing Plots\nusing Printf\nusing Random\nusing LinearAlgebra\nusing ForwardDiff\nusing BasicMD\n\ninclude(\"potentials.jl\")\n\nβ = 5.0;\nγ = 1.5;\n# M = Float64[2.1];\nM = 2.1;\nq₀ = [0.0];\np₀ = [0.0];\nΔt = 1e-1;\nn_iters = 10^4;\n\nV = x->Harmonic(x);\ncfg = ForwardDiff.GradientConfig(V, q₀);\ngradV! = (gradV, x)-> ForwardDiff.gradient!(gradV, V, x, cfg);\n\nsampler = GJF(gradV!, β, γ, M, Δt)\n\nRandom.seed!(100);\nQ₀ = copy(q₀);\nP₀ = copy(p₀);\nsample_trajectory!([Q₀, P₀], sampler, options=MDOptions(n_iters=n_iters));\n@printf(\"In Place (Q,P) after %d iterations: (%g,%g)\\n\",n_iters, Q₀[1], P₀[1]);\n#\nRandom.seed!(100);\nXvals = sample_trajectory([q₀, p₀], sampler, options=MDOptions(n_iters=n_iters,n_save_iters=n_iters));\nQ = Xvals[end][1][1]\nP = Xvals[end][2][1]\n@printf(\"(Q,P) after %d iterations: (%g,%g)\\n\",n_iters, Q[1], P[1]);\n#\nRandom.seed!(100);\nXvals = sample_trajectory([q₀, p₀], sampler, options=MDOptions(n_iters=n_iters));\nhistogram([X[1][1] for X in Xvals],label=\"Samples\",normalize=true)\nqq=LinRange(-2,2,200)\nplot!(qq, sqrt((β)/(2*π))*exp.(-0.5 * β * qq.^2),label=\"Density\")\nxlabel!(\"q\")\nylabel!(\"Frequency\")\n", "meta": {"hexsha": "e182b61b881237f295ee5887ee1b40272ae4bea2", "size": 1159, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/harmonic_gjf1.jl", "max_stars_repo_name": "gideonsimpson/JuBasicMD", "max_stars_repo_head_hexsha": "c9580315b444af066ef7208fa3f20d0753837417", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-04-18T15:52:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-25T23:39:35.000Z", "max_issues_repo_path": "examples/harmonic_gjf1.jl", "max_issues_repo_name": "gideonsimpson/BasicMD.jl", "max_issues_repo_head_hexsha": "2cae68a202b69aa0cac9f005a8559d55613f23be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-16T19:39:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-19T01:43:16.000Z", "max_forks_repo_path": "examples/harmonic_gjf1.jl", "max_forks_repo_name": "gideonsimpson/BasicMD.jl", "max_forks_repo_head_hexsha": "2cae68a202b69aa0cac9f005a8559d55613f23be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-15T16:47:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-15T16:47:46.000Z", "avg_line_length": 25.7555555556, "max_line_length": 102, "alphanum_fraction": 0.6600517688, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.8418256393148981, "lm_q1q2_score": 0.7865978096925795}}
{"text": "# basisfunctions.jl\r\n\r\n\"\"\"\r\n    fourier(k::Int)\r\n\r\nfourier implements the Fourier basis of functions ϕ_k, defined by ϕ_0≡1, and if k≥1 and k is odd, by\r\nϕ_k(x)=sqrt(2)sin((k+1)*π*x) and if k≥1 and even, by ϕ_k(x)=sqrt(2)cos(π*k*x).\r\nThis function is defined for k≥0.\r\n\r\n# Examples\r\n\r\n```julia \r\nx = -1.0:0.01:2.0\r\ny = fourier(3).(x)\r\n```\r\n\"\"\"\r\nfunction fourier(k::Int)\r\n  k ≥ 0 || throw(AssertionError(\"k should be non-negative\"))\r\n  if k == 0\r\n    return x -> 1.0\r\n  elseif isodd(k)\r\n    kplusonefloat = float(k+1)\r\n    return x -> 1.4142135623730951 * sinpi(kplusonefloat*x)\r\n  else\r\n    kfloat = float(k)\r\n    return x -> 1.4142135623730951 * cospi(kfloat*x)\r\n  end\r\nend\r\n\r\n\"\"\"\r\n    faberschauderone(x)\r\n\r\nImplements the first Faber-Schauder function defined by 1-2x for 0≤x≤1/2 and\r\n-1+2x for 0.5≤x≤1, and is 1-periodically extended to all x∈R.\r\n\r\n#See also: faberschauder\r\n\r\n#Warning\r\n\r\nNote the difference between faberschauderone and faberschauder. The first is a \r\nfunction that takes a Float64 and returns a Float64, the second takes (j,k) and\r\nreturns an anonymous function that takes a Float64 and returns a Float64.\r\n\r\n#Examples\r\n\r\n```julia\r\nx=-2.0:0.001:2.0\r\ny=faberschauderone.(x)\r\n```\r\n\"\"\"\r\nfunction faberschauderone(x)\r\n    y = mod(x, 1.0)\r\n    if 0≤y≤0.5\r\n        return 1.0 - 2*y\r\n    else\r\n        return -1.0 + 2*y\r\n    end\r\nend\r\n\r\n\"\"\"\r\n    faberschauder(j::Int, k::Int)\r\n\r\nfaberschauder implements the k-th Faber-Schauder function of level j. Here, j≥0 and 1≤k≤2^j.\r\nIt is a one-periodic function and defined on [0,1] by 2^(j+1)(x-(k-1)2^(-j)) on\r\n(k-1)2^(-j)≤x≤(k-1/2)2^(-j) and 1 - 2^(j+1)(x-(k-1/2)2^(-j)) on\r\n[(k-1/2)2^(-j), k2^(-j)] and zero outside these intervals.\r\n\r\n# See also: faberschauderone.\r\n\r\n#Warning\r\n\r\nNote the difference between faberschauderone and faberschauder. The first is a\r\nfunction that takes a Float64 and returns a Float64, the second takes (j,k) and\r\nreturns an anonymous function that takes a Float64 and returns a Float64.\r\n\r\n#Example with Plots\r\n```julia\r\nusing Plots\r\nJ=2\r\nx=0.0:0.001:1.0\r\np=plot()\r\nfor j in 0:J\r\n  for k in 1:2^j\r\n      y = faberschauder(j,k).(x)\r\n      plot!(p,x,y)\r\n  end\r\nend\r\ndisplay(p)\r\n```\r\n\"\"\"\r\nfunction faberschauder(j::Int,k::Int)\r\n  j ≥ 0 || throw(AssertionError(\"j should be a nonnegative integer.\"))\r\n  1≤k≤2^j || throw(AssertionError(\"k should be an integer between 1 and 2^j.\"))\r\n  return function(x::Float64)\r\n    y = mod(x,1.0)\r\n    if y ≤ ldexp(float(k-1), -j) || y ≥ ldexp(float(k), -j)\r\n      return 0.0\r\n    elseif ldexp(float(k-1), -j) < y ≤ ldexp(k-0.5, -j)\r\n      return ldexp(y, j+1)-2*(k-1)\r\n    else\r\n      return 2*k - ldexp(y, j+1)\r\n    end\r\n  end\r\nend\r\n", "meta": {"hexsha": "5df9e54e1558e41b56c709f39554f8cd86d3cf1b", "size": 2655, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/version0dot7and1dotX/basisfunctions.jl", "max_stars_repo_name": "Jan-van-Waaij/BayesianNonparametricStatistics", "max_stars_repo_head_hexsha": "8ab5c9f995d83528688f061212b2580a53c226ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/version0dot7and1dotX/basisfunctions.jl", "max_issues_repo_name": "Jan-van-Waaij/BayesianNonparametricStatistics", "max_issues_repo_head_hexsha": "8ab5c9f995d83528688f061212b2580a53c226ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/version0dot7and1dotX/basisfunctions.jl", "max_forks_repo_name": "Jan-van-Waaij/BayesianNonparametricStatistics", "max_forks_repo_head_hexsha": "8ab5c9f995d83528688f061212b2580a53c226ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2857142857, "max_line_length": 101, "alphanum_fraction": 0.6244821092, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951570602081, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.786597802318951}}
{"text": "export cellvolume\n\n\"\"\"\n    cellvolume(a, b, c, α, β, γ)\n\nCalculates the cell volume from 6 cell parameters.\n\"\"\"\ncellvolume(a, b, c, α, β, γ) =\n    a * b * c * sqrt(sind(α)^2 - cosd(β)^2 - cosd(γ)^2 + 2 * cosd(α) * cosd(β) * cosd(γ))\n\"\"\"\n    cellvolume(l::Lattice)\n    cellvolume(c::Cell)\n\nCalculates the cell volume from a `Lattice` or a `Cell`.\n\"\"\"\ncellvolume(lattice::AbstractLattice) = abs(det(lattice.data))\ncellvolume(cell::Cell) = cellvolume(cell.lattice)\n\"\"\"\n    cellvolume(g::MetricTensor)\n\nCalculates the cell volume from a `MetricTensor`.\n\"\"\"\ncellvolume(g::MetricTensor) = sqrt(det(g.data))  # `sqrt` is always positive!\n", "meta": {"hexsha": "3546d9f543d01ae70d0898815902cfb0572719b5", "size": 631, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/volume.jl", "max_stars_repo_name": "MineralsCloud/CrystallographyBase.jl", "max_stars_repo_head_hexsha": "08f3e9e033e260eccd1cc0b508cd91981215ff8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/volume.jl", "max_issues_repo_name": "MineralsCloud/CrystallographyBase.jl", "max_issues_repo_head_hexsha": "08f3e9e033e260eccd1cc0b508cd91981215ff8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-06-24T23:21:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T17:52:01.000Z", "max_forks_repo_path": "src/volume.jl", "max_forks_repo_name": "MineralsCloud/CrystallographyBase.jl", "max_forks_repo_head_hexsha": "08f3e9e033e260eccd1cc0b508cd91981215ff8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-08T21:14:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-08T21:14:33.000Z", "avg_line_length": 26.2916666667, "max_line_length": 89, "alphanum_fraction": 0.6529318542, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298657, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7865945894521338}}
{"text": "import MathOptInterface\nconst MOI = MathOptInterface\n\n\"\"\"\n    strengthen(a, u0, v0, ::MOI.Nonnegatives)\n\nCompute strenghtened coefficient for non-negative variable.\n\nThe strengthened coefficient is given by\n```\nα = min(-u0 * ⌊π⌋, a + v0 * ⌊π⌋) \n```\nwhere ``π = -a / (u0 + v0)``\n\"\"\"\nfunction strengthen(a::Float64, u0::Float64, v0::Float64, k::MOI.Nonnegatives)\n\n    # Sanity checks\n    MOI.dimension(k) == 1 || error(\"Trying to strengthen a $(typeof(k)) of dimension $(MOI.dimension(k)) (should be 1)\")\n    @assert u0 + v0 > 1e-4  \"u0 + v0 = $(u0 + v0) (should be > 1e-4)\"  # Otherwise cut is essentially a K* cut\n\n    π = -a / (u0 + v0)\n    return min(\n        -u0 * floor(π),\n        a + v0 * ceil(π)\n    )\nend\n\n\"\"\"\n    strengthen(a, u0, v0, ::MOI.Nonpositive)\n\nCompute strenghtened coefficient for non-positive variable.\n\nThe strengthened coefficient is given by\n```\nα = min(-u0 * ⌊π⌋, a + v0 * ⌊π⌋) \n```\nwhere ``π = -a / (u0 + v0)``\n\"\"\"\nfunction strengthen(a::Float64, u0::Float64, v0::Float64, k::MOI.Nonpositives)\n    \n    # Sanity checks\n    MOI.dimension(k) == 1 || error(\"Trying to strengthen a $(typeof(k)) of dimension $(MOI.dimension(k)) (should be 1)\")\n    @assert u0 + v0 > 1e-4  # Otherwise cut is essentially a K* cut\n    \n    π = -a / (u0 + v0)\n    return max(\n        -u0 * ceil(π),\n        a + v0 * floor(π)\n    )\nend\n\n# TODO: strengthening for conic components", "meta": {"hexsha": "df7c33d2ce4b668bb5df6b99945d20a173f72a52", "size": 1380, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/strengthening.jl", "max_stars_repo_name": "mtanneau/CLaP", "max_stars_repo_head_hexsha": "172d9ce666f97acf1348b0e6e93397a2acdf14eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-26T22:13:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-26T22:13:58.000Z", "max_issues_repo_path": "src/strengthening.jl", "max_issues_repo_name": "mtanneau/CLaP", "max_issues_repo_head_hexsha": "172d9ce666f97acf1348b0e6e93397a2acdf14eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/strengthening.jl", "max_forks_repo_name": "mtanneau/CLaP", "max_forks_repo_head_hexsha": "172d9ce666f97acf1348b0e6e93397a2acdf14eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5384615385, "max_line_length": 120, "alphanum_fraction": 0.602173913, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342049451595, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.786534243107426}}
{"text": "function gausschebyshev( n::Int32, kind::Int32=1 )\n# GAUSS-CHEBYSHEV NODES AND WEIGHTS. \n\nx = (Array(Float64,n), Array(Float64,n))\n# Use known explicit formulas. Complexity O(n).\nif kind == 1 \n    # Gauss-ChebyshevT quadrature, i.e., w(x) = 1/sqrt(1-x^2)\n    x = (cos((2*[n:-1:1]-1)*pi/2n), pi./n*ones(n))\nelseif kind == 2 \n    # Gauss-ChebyshevU quadrature, i.e., w(x) = sqrt(1-x^2)\n    x = (cos([n:-1:1]*pi./(n+1)), pi/(n+1)*sin([n:-1:1]./(n+1)*pi).^2 )\nelseif kind == 3 \n    # Gauss-ChebyshevV quadrature, i.e., w(x) = sqrt((1+x)/(1-x))\n    x = (cos(([n:-1:1]-.5)*pi/(n+.5)), 2*pi/(n+.5)*cos(([n:-1:1]-.5)*pi/(2(n+.5))).^2)\nelseif kind == 4 \n    # Gauss-ChebyshevW quadrature, i.e., w(x) = sqrt((1-x)/(1+x))\n    x = (cos([n:-1:1]*pi/(n+.5)), 2*pi/(n+.5)*sin([n:-1:1]*pi/(2(n+.5))).^2)\nelse \n   throw(ArgumentError(\"Chebyshev kind should be 1, 2, 3, or 4\")) \nend\nreturn x \nend\n", "meta": {"hexsha": "efa9dfaa429faf84cc2cae7fb72411fb49b30eb4", "size": 879, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gausschebyshev.jl", "max_stars_repo_name": "ChristoSilvia/FastGaussQuadrature32.jl", "max_stars_repo_head_hexsha": "29ed114cc8dd5a4209eeb9413e215b17b36c01b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gausschebyshev.jl", "max_issues_repo_name": "ChristoSilvia/FastGaussQuadrature32.jl", "max_issues_repo_head_hexsha": "29ed114cc8dd5a4209eeb9413e215b17b36c01b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gausschebyshev.jl", "max_forks_repo_name": "ChristoSilvia/FastGaussQuadrature32.jl", "max_forks_repo_head_hexsha": "29ed114cc8dd5a4209eeb9413e215b17b36c01b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2173913043, "max_line_length": 86, "alphanum_fraction": 0.550625711, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.956634196290671, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7865342401597837}}
{"text": "using DimensionalData\n\n@inline gaussian(t, t₀, w) = exp(-((t - t₀) / w)^2)\n\nconst KDM = 4.148808e3 # MHz^2 pc^-1 cm^3 s\n\n\"\"\"\nΔt(DM, ν₁, ν₂)\nCalculates the time delay corresponding to a dispersed pulse at dispersion measure `DM` in pc/cc between\nfrequencies `ν₁` and `ν₂`\n\"\"\"\nΔt(DM, ν₁, ν₂) = KDM * DM * (ν₁^-2 - ν₂^-2)\n\n\"\"\"\nfake_pulse(DM,f_low,f_high)\n\nGenerates a `Filterbank` file corresponding to a fake pulse of dispersion measure `DM`\nfrom frequencies `f_low` to `f_high` (MHz).\n\n# Optional Arguments\n- `channels`: Number of frequency channels\n- `samples`: Number of time samples\n- 'δt`: The time step (s) represented by one sample\n- `w`: Width of the pulse in time samples\n- `A`: Amplitude of pulse in SNR\n- `α`: Spectral index, i.e. attenuation of pulse over frequency\n- `start`: Index of start of pulse\n- `noise_floor`: Value of the top of the noise floor. This is 1 for `dtype` of Floats and one tenth `typemax` for integers by default.\n- `dtype`: Data type of data\n\"\"\"\nfunction fake_pulse(DM, f_low, f_high;\n                    channels=1024,\n                    samples=1024,\n                    δt=1e-3,\n                    w=8,\n                    A=2,\n                    α=4,\n                    start=1,\n                    noise_floor::Union{T,Nothing}=nothing,\n                    dtype::Type{T}=Float32) where {T}\n    @assert start < samples \"Starting sample must be less than the number of samples\"\n\n    if isnothing(noise_floor)\n        if dtype <: Integer\n            # Default to one tenth the range of the integer type\n            noise_floor = typemax(T) ÷ 0xA\n        else\n            noise_floor = one(T)\n        end\n    end\n\n    freqs = range(; start=f_high, stop=f_low, length=channels)\n    time = range(; start=0, step=δt, length=samples)\n\n    t_start = start * δt\n\n    # Caclulate shifts\n    shifts = @. Δt(DM, freqs', f_high)\n\n    # Generate the raw pulse, these are floats at this point\n    raw_pulse = @. gaussian(time, t_start + shifts, w * δt) * A * noise_floor * (freqs' / f_high)^α\n\n    # Prep the dynamic spectrum with the background noise\n    dyn_spec = rand(zero(T):noise_floor, samples, channels)\n\n    # Add in the pulse\n    if dtype <: Integer\n        dyn_spec += round.(dtype,raw_pulse)\n    else\n        dyn_spec += raw_pulse\n    end\n\n    # Build Filterbank\n    return Filterbank(DimArray(dyn_spec,\n                               (Ti(time),\n                                Freq(freqs))),\n                      Dict(\"tsamp\" => δt,\n                           \"nbits\" => sizeof(dtype) * 8,\n                           \"nsamples\" => samples,\n                           \"nchans\" => channels,\n                           \"fch1\" => f_high,\n                           \"foff\" => step(freqs)))\nend\n\nexport fake_pulse\n", "meta": {"hexsha": "a521be9f1fcbb4b68ef6c66c5c6ed3172d91b74e", "size": 2749, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fake.jl", "max_stars_repo_name": "kiranshila/SIGPROC.jl", "max_stars_repo_head_hexsha": "4dbb964ad3fced2abee6d1e1ad14d66050cf9936", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-03T13:22:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T13:22:29.000Z", "max_issues_repo_path": "src/fake.jl", "max_issues_repo_name": "kiranshila/RadioTransients.jl", "max_issues_repo_head_hexsha": "4dbb964ad3fced2abee6d1e1ad14d66050cf9936", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fake.jl", "max_forks_repo_name": "kiranshila/RadioTransients.jl", "max_forks_repo_head_hexsha": "4dbb964ad3fced2abee6d1e1ad14d66050cf9936", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9651162791, "max_line_length": 134, "alphanum_fraction": 0.5652964714, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966101527047, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7865087379920862}}
{"text": "\n\"\"\"\n    boys_quadgk(x, n::Int; rtol=1e-12)\n\nCalculates Boys function with Gaussian Quadrature using QuadGK.jl.\nAccuracy can be tuned with `rtol` argument.\nThis is accurate, but slow.\n\"\"\"\nfunction boys_quadgk(x, n::Int; rtol=1e-12)\n    tmp = quadgk( 0, 1; rtol=rtol) do t\n        t^(2n) * exp( -x*t^2 )\n    end\n    return tmp[1]\nend\n\n\"\"\"\n    boys_gamma(x, n::Int)\n\nEvaluate Boys function with gamma function.\nThis is accurate.\n\"\"\"\nfunction boys_gamma(x, n::Int)\n    upper = gamma( n + 1//2 ) - gamma( n + 1//2, x )\n    lower = 2x^( n + 1//2 )\n    return upper / lower\nend\n\n\n\"\"\"\n    boys_rec_largex(x, n::Int)\n\nFor large `x` > 30. Calculate using recursion.\nUses approximations.\nThis is fast, but loses accuracy on high `n` values.\n\nBased on:\nA. K. H. Weiss, C. Ochsenfeld J. Comput.\nChem. 2015, 36, 1390–1398. DOI: 10.1002/jcc.23935\n\"\"\"\nfunction boys_rec_largex(x, n::Int)\n    if n == 0\n        return √π / (2√x)\n    else\n        return ( n - 1//2 ) * boys_rec_largex(x, n-1) / x\n    end\nend", "meta": {"hexsha": "2989423e1f91cec773ca43d7898b41f865908ee6", "size": 991, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "tjjarvinen/BoysFunction.jl", "max_stars_repo_head_hexsha": "d4f6463cdea6c29f193084f91fd1df05b4568626", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions.jl", "max_issues_repo_name": "tjjarvinen/BoysFunction.jl", "max_issues_repo_head_hexsha": "d4f6463cdea6c29f193084f91fd1df05b4568626", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions.jl", "max_forks_repo_name": "tjjarvinen/BoysFunction.jl", "max_forks_repo_head_hexsha": "d4f6463cdea6c29f193084f91fd1df05b4568626", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5434782609, "max_line_length": 66, "alphanum_fraction": 0.6185671039, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660989095221, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7865087255475991}}
{"text": "\"\"\"\n    expand_poly(x, [degree = 5], [obsdim]) -> Matrix\n\nPerform a simple polynomial basis expansion of the given `degree`\nfor the vector `x`.\n\nThe optional parameter `obsdim` can be used to specify which\ndimension of the resulting `Matrix` should correspond to the\nobservations. By default each column will denote an observation,\nwhich means that the resulting `Matrix` would have the size\n`(degree, length(x))`.\n\n```@jldoctest\njulia> expand_poly(1:5, degree = 3)\n3×5 Array{Int64,2}:\n 1  2   3   4    5\n 1  4   9  16   25\n 1  8  27  64  125\n\njulia> expand_poly(1f0:5f0, 3) # positional arguments are type-stable\n3×5 Array{Float32,2}:\n 1.0  2.0   3.0   4.0    5.0\n 1.0  4.0   9.0  16.0   25.0\n 1.0  8.0  27.0  64.0  125.0\n```\n\nAlternatively it is also possible to specify `obsdim = 1`, which\nwill cause each row to denote an observation.\n\n```@jldoctest\njulia> expand_poly(1:5, degree = 3, obsdim = 1)\n5×3 Array{Int64,2}:\n 1   1    1\n 2   4    8\n 3   9   27\n 4  16   64\n 5  25  125\n\njulia> expand_poly(1:5, 3, ObsDim.First()); # same but type-stable\n```\n\"\"\"\nfunction expand_poly(x::AbstractVector; degree::Integer = 5, obsdim = ObsDim.Last())\n    expand_poly(x, degree, convert(LearnBase.ObsDimension, obsdim))\nend\n\nfunction expand_poly(x::AbstractVector, degree::Integer, ::ObsDim.Last)\n    expand_poly(x, degree, ObsDim.Constant{2}())\nend\n\nfunction expand_poly(\n    x::AbstractVector{T},\n    degree::Integer,\n    ::ObsDim.Constant{2} = ObsDim.Constant{2}()\n) where T\n\n    n = length(x)\n    X = zeros(floattype(T), (degree, n))\n    for i in 1:n\n        for d in 1:degree\n            @inbounds X[d, i] += float(x[i])^d\n        end\n    end\n    return X\nend\n\nfunction expand_poly(\n    x::AbstractVector{T},\n    degree::Integer,\n    ::ObsDim.Constant{1}\n) where T\n\n    n = length(x)\n    X = zeros(floattype(T), (n, degree))\n    for d in 1:degree\n        for i in 1:n\n            @inbounds X[i, d] += float(x[i])^d\n        end\n    end\n    return X\nend\n\n\nfloattype(::Type{T}) where T = float(T)\nfloattype(::Type{Missing}) = Missing\nfloattype(U::Union) = Union{floattype(U.a), floattype(U.b)}\n", "meta": {"hexsha": "a1f90300e9749f732bf3f120d40f8bf7f2cf18e9", "size": 2087, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basis_expansion.jl", "max_stars_repo_name": "Evizero/MLPreprocessing.jl", "max_stars_repo_head_hexsha": "034834245c27d20fb1a7f91fa350d1e97425b8be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-09-17T09:36:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T06:58:27.000Z", "max_issues_repo_path": "src/basis_expansion.jl", "max_issues_repo_name": "Evizero/MLPreprocessing.jl", "max_issues_repo_head_hexsha": "034834245c27d20fb1a7f91fa350d1e97425b8be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-04-30T20:17:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-25T18:14:56.000Z", "max_forks_repo_path": "src/basis_expansion.jl", "max_forks_repo_name": "Evizero/MLPreprocessing.jl", "max_forks_repo_head_hexsha": "034834245c27d20fb1a7f91fa350d1e97425b8be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-02-05T10:54:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T06:58:36.000Z", "avg_line_length": 24.2674418605, "max_line_length": 84, "alphanum_fraction": 0.6367992333, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.8962513800615313, "lm_q1q2_score": 0.7864397932392232}}
{"text": "using SparseArrays\nusing LinearAlgebra\n\nfunction euler_fluxes(r, ru, rv, rE)\n    gamma = 7.0/5\n    u = @. ru/r\n    v = @. rv/r\n    p = @. (gamma - 1.0)*(rE-(ru^2/r+rv^2/r)/2.0)\n\n    Frx = ru\n    Fry = rv\n    Frux= @. r*u^2+p\n    Fruy= @. ru*v\n    Frvx= @. ru*v\n    Frvy= @. r*v^2+p\n    FrEx= @. u*(rE+p)\n    FrEy= @. v*(rE+p)\n    return Frx, Fry, Frux, Fruy, Frvx, Frvy, FrEx, FrEy\nend\n\n\nfunction compact_div(Fx, Fy, h)\n    global m\n    m=ceil(Int,1/h)\n    #x = h * (1:m)\n    #m = 4  # testing purpose\n    #println(\"m=\",m)\n    LHS = SymTridiagonal(ones(m), ones(m-1)/4);\n    #println(LHS)\n    RHS = (3 / 4h) * Tridiagonal(-ones(m-1), zeros(m), ones(m-1));\n    #println(RHS)\n    RHS = sparse(RHS)\n    #println(RHS)\n    dFx = LHS \\ (RHS * Fx)\n    dFy = LHS \\ (RHS * Fy)\n    divF = dFx+dFy\n    return divF\nend\n\nfunction compact_filter(u, alpha)\n    a = 5/8+3*alpha/4\n    b = alpha+1/2\n    c = alpha/4-1/8\n    global m\n    LHS = SymTridiagonal(ones(m), alpha*ones(m-1));\n    RHS=sparse([1:m;2:m;1:m-1;3:m;1:m-2], [1:m;1:m-1;2:m;1:m-2;3:m],\n           [a*ones(m); b/2.0*ones(2*(m-1)); c/2.0*ones(2*(m-2))])\n    u_filt = LHS \\ (RHS * u)\n    return u_filt\nend\n\nfunction euler_rhs(r, ru, rv, rE, h)\n    Frx, Fry, Frux, Fruy, Frvx, Frvy, FrEx, FrEy = euler_fluxes(r, ru, rv, rE)\n    #println(\"Frx=\",Frx)\n    #println(\"Fry=\",Fry)\n    fr  =-compact_div(Frx,  Fry,  h)\n    fru =-compact_div(Frux, Fruy, h)\n    frv =-compact_div(Frvx, Frvy, h)\n    frE =-compact_div(FrEx, FrEy, h)\n    return fr, fru, frv, frE\nend\n\n\nfunction ff(u,h)\n    #println(\"size of u in ff=\",size(u))\n    #println(\"u in ff=\",u)\n    fr, fru, frv, frE = euler_rhs(u[:,1], u[:,2], u[:,3], u[:,4], h)\n    return [fr fru frv frE]\nend\n\nfunction euler_rk4step(r, ru, rv, rE, h, k, alpha)\n    u = [r ru rv rE]\n    #println(\"u=\",u)\n    #println(\"size of u=\",size(u))\n    k1 = k * ff(u, h)\n    k2 = k * ff(u + 0.5k1, h)\n    k3 = k * ff(u + 0.5k2, h)\n    k4 = k * ff(u + k3, h)\n    u = u + (k1 + 2k2 + 2k3 + k4) / 6\n    #println(u)\n    u = compact_filter(u,alpha)\n    return u[:,1], u[:,2], u[:,3], u[:,4]\nend\n\nif true\n  ru = [1;2;3;4]\n  rv = [5;6;7;8]\n  r  = [2;3;4;2]\n  rE = [1;2;2;2]\n  println(euler_rk4step(r, ru, rv, rE, 0.25, 0.2, 0.3))\nend\n\n\n#f(x, y) = x * sqrt(y)\nfunction rk4(f::Function, x0::Float64, y0::Float64, x1::Float64, n)\n    vx = Array{Float64}(undef, n+1)\n    vy = Array{Float64}(undef, n+1)\n    vx[1] = x = x0\n    vy[1] = y = y0\n    h = (x1 - x0) / n\n    for i in 1:n\n        k1 = h * f(x, y)\n        k2 = h * f(x + 0.5h, y + 0.5k1)\n        k3 = h * f(x + 0.5h, y + 0.5k2)\n        k4 = h * f(x + h, y + k3)\n        vx[i + 1] = x = x0 + i * h\n        vy[i + 1] = y = y + (k1 + 2k2 + 2k3 + k4) / 6\n    end\n    return vx, vy\nend\n", "meta": {"hexsha": "7283030e6e36f7b6bc94d3440926320485465587", "size": 2696, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "euler_compact.jl", "max_stars_repo_name": "edhschen/228bCode", "max_stars_repo_head_hexsha": "70cfb5547a6ec93244c7d2a303ab272b0a44a016", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "euler_compact.jl", "max_issues_repo_name": "edhschen/228bCode", "max_issues_repo_head_hexsha": "70cfb5547a6ec93244c7d2a303ab272b0a44a016", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "euler_compact.jl", "max_forks_repo_name": "edhschen/228bCode", "max_forks_repo_head_hexsha": "70cfb5547a6ec93244c7d2a303ab272b0a44a016", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2882882883, "max_line_length": 78, "alphanum_fraction": 0.4985163205, "num_tokens": 1246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542887603538, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7864042136886022}}
{"text": "# Pulse Parameters\nvmax = 5  # volts\nfc = 5e9  # GHz\nbw = 50  # percent\nv0 = 0.00001  # Maximum voltage allowed at t = 0\nptype = \"normal\"\n\n# Time vector\nt = linspace(0, 5e-9, 2001);\n\n# Compute sigma (control's pulse width)\nsigma = 1/(2*pi*(fc*bw/100)/2.354820045030949);\n\n# Compute mu (time offset)\n# Note that this is only approximate for the Differentiated Pulse.\nmu = sigma*sqrt(-2*log(v0/vmax));\n\nif ptype == \"normal\"\n    pulse = vmax*exp.(-(t - mu).^2/(2*sigma^2));\nelseif ptype == \"diff\"\n    pulse = -vmax/sigma*(t - mu).*exp.(0.5-(t - mu).^2/(2*sigma^2));\nelseif ptype == \"sinmod\"\n    pulse = vmax*exp.(-(t - mu).^2/(2*sigma^2)).*cos.(2*pi*fc*(t - mu));\nelse\n    error(\"Unsupported pulse type\")\nend\n\nusing PyPlot\nplot(t*1e9, pulse, linewidth=2.0)\nxlabel(\"Time (ns)\")\nylabel(\"Amplitude (Volts)\")\ngrid(true)\n", "meta": {"hexsha": "b12f126758504a1c3725633c6f37922ce48fd91f", "size": 813, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "gaussian_pulse_demo.jl", "max_stars_repo_name": "engineeringterminal/gaussian-pulses", "max_stars_repo_head_hexsha": "8fa711afd4cef11165db4764c1e3f9f4d7bb74a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gaussian_pulse_demo.jl", "max_issues_repo_name": "engineeringterminal/gaussian-pulses", "max_issues_repo_head_hexsha": "8fa711afd4cef11165db4764c1e3f9f4d7bb74a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gaussian_pulse_demo.jl", "max_forks_repo_name": "engineeringterminal/gaussian-pulses", "max_forks_repo_head_hexsha": "8fa711afd4cef11165db4764c1e3f9f4d7bb74a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6363636364, "max_line_length": 72, "alphanum_fraction": 0.63099631, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542817548989, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.786404212165977}}
{"text": "function score(x, y)\n    dist = sqrt(x^2 + y^2)\n    if dist > 10\n        return 0\n    elseif 5 < dist <= 10\n        return 1\n    elseif 1 < dist <= 5\n        return 5\n    else\n        return 10\n    end\nend\n", "meta": {"hexsha": "b4117f547297e270c282ca6a741d78fb5412c51b", "size": 206, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/darts/darts.jl", "max_stars_repo_name": "AbstractGeek/exercism-expeditions", "max_stars_repo_head_hexsha": "13f8b01bda4db74ef46e646c28cc3f1fa74757cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/darts/darts.jl", "max_issues_repo_name": "AbstractGeek/exercism-expeditions", "max_issues_repo_head_hexsha": "13f8b01bda4db74ef46e646c28cc3f1fa74757cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/darts/darts.jl", "max_forks_repo_name": "AbstractGeek/exercism-expeditions", "max_forks_repo_head_hexsha": "13f8b01bda4db74ef46e646c28cc3f1fa74757cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.8461538462, "max_line_length": 26, "alphanum_fraction": 0.4805825243, "num_tokens": 73, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542887603537, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7864042052464005}}
{"text": "## anisotropic_exponential.jl : implementation of anisotropic exponential covariance function\n\n## AnisotropicExponential ##\nstruct AnisotropicExponential{T,M} <: AnisotropicCovarianceStructure{T}\n    A::M\n    σ::T\nend\n    \n\"\"\"\n    AnisotropicExponential(A, σ=1)\n\nCreate an anisotropic exponential covariance structure with anisotropy matrix A and (optional) marginal standard deviation `σ`.\n\n# Examples\n```jldoctest\njulia> A = [1 0.5; 0.5 1]\n2×2 Array{Float64,2}:\n 1.0  0.5\n 1.0  0.5\n\njulia> a1 = AnisotropicExponential(A)\nanisotropic exponential (A=[1.0 0.5; 0.5 1.0], σ=1.0)\n\n```\n\"\"\"\nfunction AnisotropicExponential(A::Matrix{T} where {T<:Real}; σ=1.0::T where {T<:Real}) \n\tisposdef(A) || throw(ArgumentError(\"anisotropy matrix A must be positive definite\"))\n    σ > 0 || throw(ArgumentError(\"marginal standard deviation σ of exponential covariance cannot be negative or zero\"))\n\tT = promote_type(eltype(A),typeof(σ))\n\tAnisotropicExponential{T,typeof(A)}(A,convert(T,σ)) \nend\n\n# evaluate exponential covariance\nfunction apply(a::AnisotropicExponential,x::Vector{T}) where {T<:Real}\n    exp(-x'*a.A*x)\nend\n\nshow(io::IO, a::AnisotropicExponential) = print(io, \"anisotropic exponential (A=$(a.A), σ=$(a.σ))\")\n", "meta": {"hexsha": "2691147b495af509ce6b84b52a736076b2c9fec8", "size": 1208, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/covariance_functions/anisotropic_exponential.jl", "max_stars_repo_name": "devmotion/GaussianRandomFields.jl", "max_stars_repo_head_hexsha": "6a3ba77bb38d7ee8cb510fc4cee97376794d9577", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/covariance_functions/anisotropic_exponential.jl", "max_issues_repo_name": "devmotion/GaussianRandomFields.jl", "max_issues_repo_head_hexsha": "6a3ba77bb38d7ee8cb510fc4cee97376794d9577", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/covariance_functions/anisotropic_exponential.jl", "max_forks_repo_name": "devmotion/GaussianRandomFields.jl", "max_forks_repo_head_hexsha": "6a3ba77bb38d7ee8cb510fc4cee97376794d9577", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9743589744, "max_line_length": 127, "alphanum_fraction": 0.7177152318, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7863858112359013}}
{"text": "## MNIST data using Non-negative matrix Factorization\nusing MLDatasets\ntrain_x, train_y = MNIST.traindata()\ntest_x,  test_y  = MNIST.testdata()\n\n## Create the input for NMF\nm = size(train_x,1)*size(train_x,2)\nn = size(train_x,3)\nX = Float64.(reshape(train_x, m, n))\nA = copy(X') # input\n\n## Show the average image\nusing Images\nheatmap(Gray.(reshape(sum(A;dims=1)/size(A,1),28,28)'),\n  framestyle=:none,yflip=true,colorbar=true)\n\n## Show a random set of images\nimgs = Gray.(reshape(A[1:25,:]',28,28,25))\np = plot([heatmap(imgs[:,:,i]') for i=1:25]...,framestyle=:none,yflip=true)\n## Turn this into a function\nmyheatmap(X) = heatmap(Gray.(X'./maximum(X)),framestyle=:none,yflip=true)\nplotimgs(X) = plot([myheatmap(X[:,:,i]) for i=1:size(X,3)]...)\nplotimgs(reshape(A[1:25,:]',28,28,25))\n## Use NMF to find structure\n#using ImageMagick\nusing NMF\n## Make a rank 5 factorization\nk = 5\nW, H = NMF.nndsvd(A, k; variant= :ar)\n# alginst = NMF.MultUpdate{Float64}(obj=:mse, maxiter=1000, verbose=false)\nalginst = NMF.ALSPGrad{Float64}(maxiter=100)\nr = NMF.solve!(alginst, A, W, H)\n## show the images\nplotimgs(reshape(r.H',28,28,k))\n## Turn this into a method\nfunction nmf(A,k)\n  W, H = NMF.nndsvd(A, k; variant= :ar)\n  alginst = NMF.ALSPGrad{Float64}(maxiter=100)\n  r = NMF.solve!(alginst, A, W, H)\n  p = plotimgs(reshape(r.H',28,28,k))\n  savefig(\"nmf-mnist-$k.pdf\")\n  return p, r\nend\np5, r5 = nmf(A,5)\np5\n\n## Run a set of these\np8, r8 = nmf(A,8)\np10, r10 = nmf(A,10)\np15, r15 = nmf(A,15)\np25, r25 = nmf(A,25)\np35, r35 = nmf(A,35)\np50, r50 = nmf(A,50)\np100, r100 = nmf(A,100)\n\n## Use these to re-assemble digits\nndig = 60\nXs = reshape((r10.W*r10.H)[1:ndig,:]',28,28,ndig)\nAs = reshape(A[1:ndig,:]',28,28,ndig)\nanim = @animate for i=1:60\n  plot(myheatmap(Xs[:,:,i]),myheatmap(As[:,:,i]))\nend\ngif(anim, \"nmf-mnist-10-approx.gif\",fps=3)\n\n##\nndig = 60\nXs = reshape((r50.W*r50.H)[1:ndig,:]',28,28,ndig)\nAs = reshape(A[1:ndig,:]',28,28,ndig)\nanim = @animate for i=1:60\n  plot(myheatmap(Xs[:,:,i]),myheatmap(As[:,:,i]))\nend\ngif(anim, \"nmf-mnist-50-approx.gif\",fps=3)\n", "meta": {"hexsha": "51b2dec8bfd7ed34e2854008d4767d2388719e28", "size": 2049, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4-unit-3-demos/non-neg-matrix-factorization.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "4-unit-3-demos/non-neg-matrix-factorization.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4-unit-3-demos/non-neg-matrix-factorization.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 28.0684931507, "max_line_length": 75, "alphanum_fraction": 0.6559297218, "num_tokens": 793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.7863741784160135}}
{"text": "\"\"\"\n$(TYPEDSIGNATURES)\n\nResurrect linspace despite https://github.com/JuliaLang/julia/pull/25896#issuecomment-363769368\n\"\"\"\nlinspace(a,b,n)=collect(range(a,b,length=n))\n\n\n\"\"\"\n$(TYPEDSIGNATURES)\n\n(Try to) create a subdivision of interval (a,b) stored in the \nreturned array X such that \n  - `X[1]==a, X[end]==b`\n  - `(X[2]-X[1])<=ha+tol*(b-a)`\n  - `(X[end]-X[end-1])<=hb+tol*(b-a)`\n  - There is a number q such that  `X[i+1]-X[i] == q*(X[i]-X[i-1])`\n  - X is the array with the minimal possible number of points with the above property\n  \nCaveat: the algorithm behind this is  tested for many cases but unproven.\n\nReturns an Array containing the points of the subdivision.\n\"\"\"\nfunction geomspace(a, b, ha, hb ; tol=1.0e-10, maxiterations=100)\n    a=Float64(a)\n    b=Float64(b)\n    ha=Float64(ha)\n    hb=Float64(hb)\n    \n    function _geomspace0(l,h0, hl, tol=1.0e-10)\n        @assert (l>0.0)\n        @assert (h0>0.0)\n        @assert (hl>=h0)\n        @assert((hl+h0)<l)\n        \n        #  We need to  adjust two things:\n        \n        # The sum of the geometric progression must\n        # match the length of the interval, so lmismatch\n        # should be zero:\n        function lmismatch(q,k)\n            return l - h0*(1-q^k)/(1-q)\n        end\n        \n        # The claim from experimenral evidence (Wolfram) \n        # is that, if written as a polynomial,\n        # it has two real zeros: one and the value searched for which\n        # is slightly larger than one. All other zeros are on one circle.\n        \n        # The size of the last interval should be close to \n        # to hl, so hmismatch should be close to one and not larger than one\n        function  hmismatch(q,k)\n            return  h0*q^(k-1)/hl\n        end\n\n        # define initial number of intervals from\n        # average of minmal and maximal h\n        n=Int(ceil((2.0*l/(h0+hl))))\n        \n\n        if n==1\n            n=2\n        end\n        \n        # define initial q such that hmismatch is one.\n        q=(hl/h0)^(1.0/(n-1.0))\n        \n        # Iteration until both mismatches are satisfactory\n        # Outer loop runs until hmismatch is less than 1\n        hmiss=10.0 # some initial value >1 just to run the loop at least once\n        if abs(q-1.0)<tol\n            hmiss=1.0\n        end\n\n        while  hmiss>1.0\n            # increase number of intervals until\n            # lmismatch becomes less than zero\n            while  lmismatch(q,n)>tol\n                n+=1\n            end\n\n\n            # find initial interval for q containing\n            # value with zero lmismatch \n            ns=0\n            \n            while lmismatch(q,n)<tol &&  ns<maxiterations\n                q*=0.99\n                ns+=1\n            end\n            \n            ql=q*0.9\n            qr=q*1.1\n            @assert ns<maxiterations \"Unable to determine geomspace data after $(maxiterations) iterations\"\n            \n            # bisection to define q with zero lmismatch\n            ns=0\n            qm=0.5*(ql+qr)\n            while abs(qr-ql)>tol && ns<maxiterations\n                ns+=1\n                mmm=lmismatch(qm,n)\n                if abs(mmm)<0\n                    break\n                elseif lmismatch(ql,n)*mmm<0\n                    qr=qm\n                else\n                    ql=qm\n                end\n                qm=0.5*(ql+qr)\n            end\n            # increase q slightly to increase probability\n            # for last interval to be <=hl\n            q=qm*(1.0+tol)\n            @assert ns<maxiterations \"Unable to determine geomspace data after $(maxiterations) iterations\"\n            hmiss=hmismatch(q,n)\n            if hmiss>1.0+tol \n                n=n+1\n            end\n        end\n        #  printf(\"%d %g %g %g\\n\",n,q,lmismatch(q,n),hmismatch(q,n))\n\n        X = Array{Float64,1}(undef,n+1)\n        X[1]=0\n        h=h0\n        for i=1:n\n            X[i+1]=X[i]+h\n            h*=q\n        end\n        X[n+1]=l\n\n\n        # Fix last interval and remove \"overshoots\"\n        if X[end]>l\n            X[end]=l\n        end\n        \n        while X[end-1]+tol>X[end]\n            pop!(X)\n            X[end]=l\n        end\n        \n        return X\n    end\n\n    @assert (ha>0.0) \"Start step size $(ha) should be positive\"\n    @assert (hb>0.0) \"End step size $(hb) should be positive\"\n    @assert (a<b)    \"Interval ends $(a), $(b) should be increasing\"\n    @assert ((ha+hb)<b-a) \"Sum of step sizes $(ha)+$(hb) should not exceed interval size $(b)-$(a)\"\n\n    \n    # Map things to [0,b-a]\n    tol=tol*(b-a)\n    if ha<hb-tol\n        X=_geomspace0(b-a,ha,hb,tol)\n        X.+=a\n    elseif ha>hb+tol\n        X=-reverse(_geomspace0(b-a,hb,ha,tol))\n        X.+=b\n    else\n        n=Int(ceil((b-a)/ha))\n        X=collect(range(a,b,length=n+1))\n    end\n#    @show X[2]-X[1],ha, X[end]-X[end-1],hb\n\n\n    @assert (X[2]-X[1])<=ha+tol  \"First interval turned out to be larger than $(ha)\"\n    @assert (X[2]-X[1])>ha/2  \"First interval turned out to be less  than $(ha)/10\"\n    @assert (X[end]-X[end-1])<=hb+tol  \"Last interval turned out to be larger than $(hb)\"\n    @assert (X[end]-X[end-1])>=hb/2  \"Last interval turned out to be less than $(hb)/10\"\n    @assert abs(X[1]-a)<tol  \"Range start $(X[1]) differs from $(a)\"\n    @assert abs(X[end]-b)<tol \"Range end $(X[end])  differs from $(b)\"\n   \n    return X\nend\n\n\n\ncollect_or_assign(X)=X\ncollect_or_assign(X::AbstractRange)=collect(X)\nis_monotone(X)=all(X[2:end]-X[1:end-1].>0)\n\n\"\"\"\n    c=glue(a,b)\n\nGlue together two vectors `a` and b resulting in a vector c. They last element \nof `a` shall be equal (up to tol) to the first element of b.\nThe result fulfills `length(c)=length(a)+length(b)-1`\n\"\"\"\nfunction glue(_a::AbstractVector, _b::AbstractVector; tol=1.0e-10)\n    a=collect_or_assign(_a)\n    b=collect_or_assign(_b)\n\n    is_monotone(a) || error(\"non-monotonous first argument of glue\")\n    is_monotone(b) || error(\"non-monotonous second argument of glue\")\n    Tv=promote_type(eltype(a),eltype(b))\n    na=length(a)\n    nb=length(b)\n    \n    d=b[1]-a[na-1]\n    @assert(d>0)\n    d=b[1]-a[na]\n    @assert(d>-tol)\n    @assert(d<tol)\n\n    c=Vector{Tv}(undef,na+nb-1)\n    ic=0\n    for ia=1:na\n        ic+=1\n        c[ic]=a[ia]\n    end\n    for ib=2:nb\n        ic+=1\n        c[ic]=b[ib]\n    end\n    return c\nend\n", "meta": {"hexsha": "ddbdf9bf1347306cc12eb9dd294f3263e0d29253", "size": 6246, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/arraytools.jl", "max_stars_repo_name": "j-fu/ExtendableGrids.jl", "max_stars_repo_head_hexsha": "98d1da9e1570164224e73966057bf48a47430118", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-03-10T23:35:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T20:04:52.000Z", "max_issues_repo_path": "src/arraytools.jl", "max_issues_repo_name": "j-fu/ExtendableGrids.jl", "max_issues_repo_head_hexsha": "98d1da9e1570164224e73966057bf48a47430118", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2020-07-12T15:26:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T20:18:23.000Z", "max_forks_repo_path": "src/arraytools.jl", "max_forks_repo_name": "j-fu/ExtendableGrids.jl", "max_forks_repo_head_hexsha": "98d1da9e1570164224e73966057bf48a47430118", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-12-08T16:02:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T20:10:50.000Z", "avg_line_length": 28.7834101382, "max_line_length": 107, "alphanum_fraction": 0.5374639769, "num_tokens": 1882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7863741748530199}}
{"text": "function ctr(f::Function, box=[0;1], N = 10)\n    h = (box[2]-box[1])/N\n    val = 0\n    val += f(box[1])/2\n    for j = 1:N-1\n        x = box[1] + j*h\n        val += f(x)\n    end\n    val += f(box[2])/2\n    val *= h\n    return val\nend", "meta": {"hexsha": "3bd24e77e7e085b889a1499125e3c938e55f01a8", "size": 231, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/quadrature.jl", "max_stars_repo_name": "hessianguo/NumericalMethod.jl", "max_stars_repo_head_hexsha": "bd6c00a88c8168e39b2ba1894466a6b6f6e24984", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/quadrature.jl", "max_issues_repo_name": "hessianguo/NumericalMethod.jl", "max_issues_repo_head_hexsha": "bd6c00a88c8168e39b2ba1894466a6b6f6e24984", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/quadrature.jl", "max_forks_repo_name": "hessianguo/NumericalMethod.jl", "max_forks_repo_head_hexsha": "bd6c00a88c8168e39b2ba1894466a6b6f6e24984", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.25, "max_line_length": 44, "alphanum_fraction": 0.4242424242, "num_tokens": 97, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.786320488190761}}
{"text": "# basis functions\nlinear(x::Number) = vcat(1, x)\nlinear(x::AbstractArray{T, 1}) where {T} = hcat(linear.(x)...)'\n\ngaussian(x::Number, μ, σ=0.1) = vcat(1, exp.(-0.5*(x .- μ).^2/σ^2))\ngaussian(x::AbstractArray{T, 1}, μ, σ=0.1) where {T} = hcat(gaussian.(x, Ref(μ), Ref(σ))...)'\n\npolynomial(x::Number, r) = x.^r\npolynomial(x::AbstractArray{T, 1}, r) where {T} = hcat(polynomial.(x, Ref(r))...)'\n\n\"\"\"\n    posterior(Y, ϕX, α, β)\n\nCompute the posterior mean and variance given the observations Y,\nregressor matrix ϕX, prior precision α, and the additive noise precision β.\n\"\"\"\nfunction posterior(Y, ϕX, α, β)\n    Σ = inv(α*I + β*ϕX'*ϕX)\n    μ = β*Σ*ϕX'*Y\n    return μ, Σ\nend\n\n\"\"\"\n    predict(ϕx, μ, Σ, β)\n\nCompute the predictive distribution and standard deviation given the\nregressed test point ϕx, posterior mean μ, posterior variance Σ, and\nthe additive noise precision β.\n\"\"\"\nfunction predict(ϕx, μ, Σ, β)\n    μy = μ'*ϕx\n    Σy = 1/β + ϕx'*Σ*ϕx\n    return μy, √Σy\nend\n\n\"\"\"\n    regress(Xo, Yo, Xt, Yt, ϕ, α, β)\n\nPlot the point predictions given the observed data (Xo, Yo), test data (Xt, Yt),\nbasis functions ϕ, prior precision α, and the additive noise precision β.\n\"\"\"\nfunction regress(Xo, Yo, Xt, Yt, ϕ, α, β, ϕargs...)\n    μ, Σ = posterior(Yo, ϕ(Xo, ϕargs...), α, β)\n\n    # predictions\n    Yμ = similar(Xt); Yσ = similar(Xt)\n    for (i, xt) in enumerate(Xt)\n        yμ, yσ = predict(ϕ(xt, ϕargs...), μ, Σ, β)\n        Yμ[i] = yμ; Yσ[i] = yσ\n    end\n\n    Prediction1D(Xo, Yo, Xt, Yt, Yμ, Yσ)\nend\n\nstruct Prediction1D{T}\n    Xo::T\n    Yo::T\n    Xt::T\n    Yt::T\n    μ::T\n    σ::T\nend\n\n@recipe function f(p::Prediction1D)\n    legend --> false\n    @series begin\n        fillcolor --> :grey\n        fillalpha --> 0.2\n        linewidth --> 1.0\n        linecolor --> :grey\n        ribbon := p.σ\n        (p.Xt, p.μ)\n    end\n    @series begin\n        linewidth --> 2.0\n        linecolor --> :black\n        linestyle --> :dash\n        (p.Xt, p.Yt)\n    end\n    @series begin\n        seriestype --> :scatter\n        markercolor --> :red\n        markershape --> :circle\n        markersize --> 3.0\n        markerstrokecolor --> :red\n        (p.Xo, p.Yo)\n    end\nend\n\nfunction linefit(N, α=2.0, β=25.0; seeded=false)\n    f(x, β=Inf) = -0.3 + 0.5*x + 1/β*randn()\n    if seeded\n        seed!(1729)\n    end\n    Xo = 2.0*rand(N) .- 1.0\n    Yo = f.(Xo, β)\n    Xt = collect(-1.0:0.01:1.0)\n    Yt = f.(Xt)\n    regress(Xo, Yo, Xt, Yt, linear, α, β)\nend\n\nfunction gaussfit(N, α=1.0, β=25.0, μ=0:0.1:3; seeded=false)\n    f(x, β=Inf) = 0.5 + x*sin(2*π*x) + 1/β*randn()\n    if seeded\n        seed!(1729)\n    end\n    Xo = rand(N)*3.0\n    Yo = f.(Xo, β)\n    Xt = collect(0.0:0.01:3.0)\n    Yt = f.(Xt)\n    regress(Xo, Yo, Xt, Yt, gaussian, α, β, μ)\nend\n\nfunction polyfit(N, α=0.005, β=1/(0.3^2), r=0:5; seeded=false)\n    f(x, β=Inf) = 0.5 + sin(2*π*x) + 1/β*randn()\n    if seeded\n        seed!(1729)\n    end\n    Xo = rand(N)\n    Yo = f.(Xo, β)\n    Xt = collect(0.0:0.005:1.0)\n    Yt = f.(Xt)\n    regress(Xo, Yo, Xt, Yt, polynomial, α, β, r)\nend\n", "meta": {"hexsha": "e095b977593e4c7335baa0aa5b4132cd4c450224", "size": 3014, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "bayeslin.jl", "max_stars_repo_name": "gbarsih/Safe-Optimal-Rendezvous", "max_stars_repo_head_hexsha": "6acc9f11c092c81dbe19daeb0ff7363f7ab5bd5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bayeslin.jl", "max_issues_repo_name": "gbarsih/Safe-Optimal-Rendezvous", "max_issues_repo_head_hexsha": "6acc9f11c092c81dbe19daeb0ff7363f7ab5bd5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bayeslin.jl", "max_forks_repo_name": "gbarsih/Safe-Optimal-Rendezvous", "max_forks_repo_head_hexsha": "6acc9f11c092c81dbe19daeb0ff7363f7ab5bd5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.112, "max_line_length": 93, "alphanum_fraction": 0.5497677505, "num_tokens": 1203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7862740470295705}}
{"text": "\"\"\"\n    σ(x) = 1 / (1 + exp(-x))\n\nClassic [sigmoid](https://en.wikipedia.org/wiki/Sigmoid_function) activation\nfunction.\n\"\"\"\nσ(x) = one(x) / (one(x) + exp(-x))\n\nconst sigmoid = σ\n\n# ForwardDiff numerical stability hack\nσ_stable(x) = ifelse(x < -80, zero(x), one(x) / (one(x) + exp(-x)))\n\nσ(x::Float32) = σ_stable(x)\n\n@require ForwardDiff begin\n  import ForwardDiff: Dual\n  σ(x::Dual{T,Float32}) where T = σ_stable(x)\nend\n\n\"\"\"\n    logσ(x)\n\nReturn `log(σ(x))` which is computed in a numerically stable way.\n\n    julia> logσ(0.)\n    -0.6931471805599453\n    julia> logσ.([-100, -10, 100.])\n    3-element Array{Float64,1}:\n     -100.0\n      -10.0\n       -0.0\n\"\"\"\nfunction logσ(x)\n  max_v = max(zero(x), -x)\n  z = exp(-max_v) + exp(-x-max_v)\n  -(max_v + log(z))\nend\n\nconst logsigmoid = logσ\n\n\"\"\"\n    relu(x) = max(0, x)\n\n[Rectified Linear Unit](https://en.wikipedia.org/wiki/Rectifier_(neural_networks))\nactivation function.\n\"\"\"\nrelu(x) = max(zero(x), x)\n\n\n\"\"\"\n    leakyrelu(x) = max(0.01x, x)\n\nLeaky [Rectified Linear Unit](https://en.wikipedia.org/wiki/Rectifier_(neural_networks))\nactivation function.\nYou can also specify the coefficient explicitly, e.g. `leakyrelu(x, 0.01)`.\n\"\"\"\nleakyrelu(x, a = oftype(x/1, 0.01)) = max(a*x, x/1)\n\n\"\"\"\n    elu(x, α = 1) =\n      x > 0 ? x : α * (exp(x) - 1)\n\nExponential Linear Unit activation function.\nSee [Fast and Accurate Deep Network Learning by Exponential Linear Units](https://arxiv.org/abs/1511.07289).\nYou can also specify the coefficient explicitly, e.g. `elu(x, 1)`.\n\"\"\"\nelu(x, α = one(x)) = ifelse(x ≥ 0, x/1, α * (exp(x) - one(x)))\n\n\"\"\"\n    swish(x) = x * σ(x)\n\nSelf-gated actvation function.\nSee [Swish: a Self-Gated Activation Function](https://arxiv.org/pdf/1710.05941.pdf).\n\"\"\"\nswish(x) = x * σ(x)\n\n\"\"\"\n    selu(x) = λ * (x ≥ 0 ? x : α * (exp(x) - 1))\n\n    λ ≈ 1.0507\n    α ≈ 1.6733\n\nScaled exponential linear units.\nSee [Self-Normalizing Neural Networks](https://arxiv.org/pdf/1706.02515.pdf).\n\"\"\"\nfunction selu(x)\n  λ = oftype(x/1, 1.0507009873554804934193349852946)\n  α = oftype(x/1, 1.6732632423543772848170429916717)\n  λ * ifelse(x > 0, x/1, α * (exp(x) - 1))\nend\n\n\"\"\"\n    softsign(x) = x / (1 + |x|)\n\nSee [Quadratic Polynomials Learn Better Image Features](http://www.iro.umontreal.ca/~lisa/publications2/index.php/attachments/single/205).\n\"\"\"\nsoftsign(x) = x / (one(x) + abs(x))\n\n\n\"\"\"\n    softplus(x) = log(exp(x) + 1)\n\nSee [Deep Sparse Rectifier Neural Networks](http://proceedings.mlr.press/v15/glorot11a/glorot11a.pdf).\n\"\"\"\nsoftplus(x) = log1p(exp(x))\n", "meta": {"hexsha": "d5c5092ecdb003c91d265153aa385bfef570e112", "size": 2514, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/activation.jl", "max_stars_repo_name": "gustafsson/NNlib.jl", "max_stars_repo_head_hexsha": "6b58df43a4de71bda3246e6cac2e073af10da899", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/activation.jl", "max_issues_repo_name": "gustafsson/NNlib.jl", "max_issues_repo_head_hexsha": "6b58df43a4de71bda3246e6cac2e073af10da899", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/activation.jl", "max_forks_repo_name": "gustafsson/NNlib.jl", "max_forks_repo_head_hexsha": "6b58df43a4de71bda3246e6cac2e073af10da899", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4953271028, "max_line_length": 138, "alphanum_fraction": 0.6320604614, "num_tokens": 872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7862740453179544}}
{"text": "using MathGL\n\n# Create the graph, using a sufficient resolution for 4x2 pictures here\ngr = MathGL.Graph(2400, 1200)\n\n# Standard sine and cosine plots with grid ect.\n@mglplot gr [\n    # Give position of the next plot: In a grid of 4x2 plots take the first (top left)\n    subplot 4 2 1\n    # The title for this subplot\n    title \"Sine and cosine plot\"\n    # The xticks, given as array of values and array of corresponding strings\n    xtick [-2pi, -pi, 0, pi, 2pi] [\"-2\\\\pi\", \"-\\\\pi\", \"0\", \"\\\\pi\", \"2\\\\pi\"]\n    # Set the ranges for x and y respectively. Each range is -1 to 1 by default\n    xrange -2pi 2pi; yrange -1 1\n    # Plot the axis (meaning: plot tics and tic labels) and the grid with style \"h=\" \n    # 'h' is a lighter gray, '=' is a type of dashed line\n    axis; grid stl=\"h=\"\n    # Labels for the x and y axis\n    xlabel \"x\"; ylabel \"y\"\n    # The x-values (as array, not as linspace!) that shall be used for plotting\n    x = Array(linspace(-2pi,2pi,100))\n    # The values for the two curves\n    y1 = 0.5sin(x); y2 = 0.5cos(x)\n    # Plot with style options \"B\" (dark Blue) and \"G\" (dark green)\n    plot x y1 stl=\"B\"\n    plot x y2 stl=\"G\"\n    # Reset the tics\n    xtick\n]\n\n# Some log-log plot \n@mglplot gr [\n    # Same as before\n    subplot 4 2 2\n    title \"Log-log plot\"\n    # This time: set x and y range in one command, ranges, instead of\n    # xrange and yrange\n    ranges 1e-2 1e2 7e-1 1e1\n    # Set logscale axis by defining the coordinate transformations for the\n    # x respectively y values. So we have  φ: xrange x yrange --> ℝ²,\n    # φ(x,y) = (lg(x), lg(y)) as transformation applied before plotting\n    coords X=\"lg(x)\" Y=\"lg(y)\"\n    # Plot the ticks and tick labels, plot the grid for minor ticks\n    # (subgrid) and the ordinary grid\n    axis; subgrid; grid \n    # Once again the labels. MathGL supports some light form of support for\n    # latex-like commands\n    xlabel \"x\"; ylabel \"y = \\\\sqrt{1+x^2}\"\n    # Generate the data and plot\n    x = 1logspace(-2, 2, 200)\n    plot x sqrt(1+x)\n]\n\n# Using cylindrical coordinates\n@mglplot gr [\n    subplot 4 2 3\n    title \"Cylindrical plot\"\n    # This range will be fed to the transformation of cylindrical coordinates\n    # The xrange has the role of the angle / times 2pi, so it is between 0 and 1\n    # The yrange has the role of the radius, it is also between 0 and 1\n    # The zrange stays the same, so it stays from -1 to 1\n    ranges 0 1 0 1 -1 1\n    coords X=\"y*sin(2*pi*x)\" Y=\"y*cos(2*pi*x)\"\n    # Rotate the picture. 50 degrees away from top view, -60 degrees around\n    # z axis\n    rotate 50 -60\n    # Plot 6 circles\n    x = Array(linspace(0,1,50))\n    o = ones(50)\n    # The numbers in the style string determine the width of the line to be\n    # drawn\n    plot x 0.80o 0.7o  stl=\"b9\"\n    plot x 0.65o 0.3o  stl=\"B7\"\n    plot x 0.50o 0.0o  stl=\"r5\"\n    plot x 0.30o -0.3o stl=\"G3\"\n    plot x 0.10o -0.7o stl=\"g1\"\n    # Set the origin to a margin value so that it does not disturb drawing the grid\n    origin -1 1 -1\n    # Plot a grid with light grey color ('h') and undashed lines ('-')\n    grid stl=\"h-\"\n    # reset coordinates\n    coords\n]\n\n# A plot marking the area between the y values and the x-axis\n@mglplot gr [\n    subplot 4 2 4\n    title \"Area plot\"\n    # Set ticks and ranges like before\n    xtick [-2pi, -pi, 0, pi, 2pi] [\"-2\\\\pi\", \"-\\\\pi\", \"0\", \"\\\\pi\", \"2\\\\pi\"]\n    xrange -2pi 2pi; yrange -1 1; zrange 0 0\n    # As an alternative: set the origin to the top of the drawing. This\n    # affects the axis command and the xlabel / ylabel commands so that the\n    # ticks ect. for the x-axis are now drawn above the graph\n    origin -2pi 1\n    box; axis\n    xlabel \"x\"; ylabel \"y\"\n    # Set the origin back to 0. This is important for the area-plot, since\n    # the area marked is the area between the x-axis defined by the origin\n    origin 0 0\n    # Prepare data\n    x = Array(linspace(-2pi,2pi,100))\n    y1 = 0.5sin(x)+0.4sin(3x); y2 = 0.8cos(x); y3 = -0.3cos(x)\n    # Do the plots. g,G: light,dark green; k: black; y: yellow, c: cyan, b:\n    # blue, #: special style for the area drawing: draw lines instead of\n    # filling the full area\n    area x y1 stl=\"gG#\"\n    plot x y1 stl=\"k\"\n    area x y2 stl=\"yr#\"\n    plot x y2 stl=\"k\"\n    area x y3 stl=\"cb#\"\n    plot x y3 stl=\"k\"\n    # reset the xticks\n    xtick\n]\n\n# A default chart plot (as implemented in MathGL)\n@mglplot gr [\n    subplot 4 2 5\n    title \"Chart plot\"\n    # Use light-effects. One can also set up different light sources of different color and type\n    light true\n    rotate 50 60\n    # Prepare data by constructing a random 7x2 matrix. So we compare\n    # 2 datasets with 7 values each\n    data = rand(7,2)+0.1\n    # Here '#' means that the edges shall be plotted as lines (black by default)\n    chart data stl=\"#\"\n]\n\n# A ring like chart plot\n@mglplot gr [\n    subplot 4 2 6\n    title \"Ring chart plot\"\n    light true\n    # Will again use something like cylinder coordinates, but won't let the radius go to 0,\n    # so y ∈ [-1, 1] with r = y+2\n    xrange 0 1\n    coords X=\"(y+2)/3*cos(2*pi*x)\" Y=\"(y+2)/3*sin(2*pi*x)\"\n    rotate 50 100\n    # Prepare data by constructing a random 7x2 matrix. So we compare\n    # 2 datasets with 7 values each\n    data = rand(7,2)+0.1\n    # The last values will be made invisible (by the space ' ' in the style string), \n    # define some fixed values for it so that one can see the rings internals\n    data[7,:] = [0.25,0.5]\n    # \"bgrcmy \": use colors blue,green,red,cyan,mangenta,yellow,invisible\n    # in this order for the 7 values supplied. '#': plot the edges as black lines\n    chart data stl=\"bgrcmy #\"\n    # Reset the coordinate system\n    coords\n]\n\n# Prepare some data that will be used in the next two plots\nv = Array(linspace(-1,1,9))\nx = Array(0:49)/49\ny = Array(0:39)/39\na = 0.6sin(2pi*x).*sin(3pi*y') + 0.4cos(3pi*x.*y')\nb = 0.6cos(2pi*x).*cos(3pi*y') + 0.4cos(3pi*x.*y')\n\n# A surface plot with density plot at the bottom\n@mglplot gr [\n    subplot 4 2 7\n    title \"Surface plot\"\n    ranges -1 1 -1 1 -1 1\n    light true\n    rotate 50 60\n    # Plots a bounding box around the 3d figure to be plotted\n    box\n    # Surface plot with \"wire\"-option '#' and optional parameter meshnum=12\n    surf a stl=\"#\" opt=\"meshnum 12\"\n    # density plot with \"wire\"-option '#' and optional parameter meshnum=12\n    # and alpha=0.75 (meaning transparency). (The density plot can of course\n    # also be given at other positions than at the bottom).\n    dens a stl=\"#\" opt=\"meshnum 12; alpha 0.75\"\n]\n\n# Create a very nice contour plot using 3 different ways of drawing contours\n@mglplot gr [\n    subplot 4 2 8\n    title \"Contour plot\"\n    light true\n    rotate 50 60\n    box\n    # This is responsible for the vertical areas\n    contv a\n    # This is responsible for the horizontal areas\n    contf a\n    # This is responsible for drawing black lines at the meeting edges\n    # between vertical + horizontal areas\n    cont  a stl=\"k\"\n]\n\nMathGL.write(gr, \"../graphs/main_example.png\")\n", "meta": {"hexsha": "5a74e33873853c160a019ac479db00d8486319a5", "size": 6968, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/main_example.jl", "max_stars_repo_name": "thomastaudt/MathGL.jl", "max_stars_repo_head_hexsha": "1c07f01d82a19047be3b8a53015bd68f8db5742b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-28T22:31:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-04T10:55:59.000Z", "max_issues_repo_path": "examples/main_example.jl", "max_issues_repo_name": "thomastaudt/MathGL.jl", "max_issues_repo_head_hexsha": "1c07f01d82a19047be3b8a53015bd68f8db5742b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/main_example.jl", "max_forks_repo_name": "thomastaudt/MathGL.jl", "max_forks_repo_head_hexsha": "1c07f01d82a19047be3b8a53015bd68f8db5742b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-29T10:16:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-29T10:16:27.000Z", "avg_line_length": 35.5510204082, "max_line_length": 96, "alphanum_fraction": 0.6423650976, "num_tokens": 2252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7862740400386032}}
{"text": "# The functions below check if a matrix is approximately Hermitian\nusing Compat.LinearAlgebra: RealHermSymComplexHerm\n\nconst ERR = 1E-13\n\nisapproxhermitian(A::RealHermSymComplexHerm) = true\n\nfunction isapproxhermitian(A::AbstractMatrix)\n    m, n = size(A)\n    m == n || return false\n    @inbounds for j = 1:m\n        for i = 1:j-1\n            Aij, Aji = A[i,j], A[j,i]\n            if abs(real(Aij)-real(Aji)) > ERR || abs(imag(Aij)+imag(Aji)) > ERR\n                return false\n            end\n        end\n        abs(imag(A[j,j])) > ERR && return false\n    end\n    return true\nend\n\nfunction isapproxhermitian(A::SparseMatrixCSC)\n    # Modified from base\n    m, n = size(A)\n    m == n || return false\n    colptr = A.colptr\n    rowval = A.rowval\n    nzval = A.nzval\n    @inbounds for col = 1:m\n        for p = colptr[col]:colptr[col+1]-1\n            val = nzval[p]\n            row = rowval[p]\n            if val == 0 # ignore stored zeros\n                continue\n            end\n            if row == col # diagonal element\n                abs(imag(val)) > ERR && return false\n            else # off-diagonal element\n                val2 = A[col,row]\n                if abs(real(val)-real(val2)) > ERR || abs(imag(val)+imag(val2)) > ERR\n                    return false\n                end\n            end\n        end\n    end\n    return true\nend\n\nfunction hermitianize!(A::AbstractMatrix)\n    m = checksquare(A)\n    @inbounds for j = 1:m\n         for i = 1:j-1\n            A[i,j] = conj(A[j,i])\n        end\n        A[j,j] = real(A[j,j])\n    end\n    return A\nend\n\nfunction isunitary(A::AbstractMatrix{T}) where {T}\n    # check efficiently if A'*A = I\n    m, n = size(A)\n    m == n || return false\n    @inbounds for i = 1:m, j = 1:m\n        a = zero(T)\n        for k = 1:m\n            a += conj(A[k,i]) * A[k,j]\n        end\n        if i == j\n            a == 1 || return false\n        else\n            a == 0 || return false\n        end\n    end\n    return true\nend\n\nfunction isunitary(A::SparseMatrixCSC{T,S}) where {T,S}\n    # check efficiently if A'*A = I\n    m, n = size(A)\n    m == n || return false\n    colptr = A.colptr\n    rowval = A.rowval\n    nzval = A.nzval\n    @inbounds for i = 1:m, j = 1:m\n        a = zero(T)\n        for p1 = colptr[i]:colptr[i+1]-1, p2 = colptr[j]:colptr[j+1]-1\n            if rowval[p1] < rowval[p2]\n                continue\n            elseif rowval[p1]==rowval[p2]\n                a += conj(nzval[p1]) * nzval[p2]\n                continue\n            end\n        end\n        if i == j\n            a == 1 || return false\n        else\n            a == 0 || return false\n        end\n    end\n    return true\nend\n\nfunction isapproxunitary(A::AbstractMatrix{T}) where {T}\n    # check efficiently if A'*A ≈ I\n    m, n = size(A)\n    m == n || return false\n    @inbounds for i = 1:m, j = 1:m\n        a = zero(T)\n        for k = 1:m\n            a += conj(A[k,i]) * A[k,j]\n        end\n        if i == j\n            if abs(1-real(a)) > ERR || abs(imag(a)) > ERR\n                return false\n            end\n        else\n            if abs(real(a)) > ERR || abs(imag(a)) > ERR\n                return false\n            end\n        end\n    end\n    return true\nend\n\nfunction isapproxunitary(A::SparseMatrixCSC{T,S}) where {T,S}\n    # check efficiently if A'*A ≈ I\n    m, n = size(A)\n    m == n || return false\n    colptr = A.colptr\n    rowval = A.rowval\n    nzval = A.nzval\n    @inbounds for i = 1:m, j = 1:m\n        a = zero(T)\n        for p1 = colptr[i]:colptr[i+1]-1, p2 = colptr[j]:colptr[j+1]-1\n            if rowval[p1] < rowval[p2]\n                continue\n            elseif rowval[p1]==rowval[p2]\n                a += conj(nzval[p1]) * nzval[p2]\n                continue\n            end\n        end\n        if i == j\n            if abs(1-real(a)) > ERR || abs(imag(a)) > ERR\n                return false\n            end\n        else\n            if abs(real(a)) > ERR || abs(imag(a)) > ERR\n                return false\n            end\n        end\n    end\n    return true\nend\n", "meta": {"hexsha": "4aac999a0db3834b119d9c56e250892b76398f4f", "size": 4000, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/misc/checks.jl", "max_stars_repo_name": "peterse/Schrodinger.jl", "max_stars_repo_head_hexsha": "dfcc66872b801413e5e665853e665fc02321f9da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/misc/checks.jl", "max_issues_repo_name": "peterse/Schrodinger.jl", "max_issues_repo_head_hexsha": "dfcc66872b801413e5e665853e665fc02321f9da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/misc/checks.jl", "max_forks_repo_name": "peterse/Schrodinger.jl", "max_forks_repo_head_hexsha": "dfcc66872b801413e5e665853e665fc02321f9da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.641025641, "max_line_length": 85, "alphanum_fraction": 0.47975, "num_tokens": 1207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7862530838410599}}
{"text": "#### Number theory and combinatorics.\n\nimport Primes\nimport Combinatorics\nimport Polynomials\n\n### BinarySearch\n\n@mkapprule BinarySearch\n\n@sjdoc BinarySearch \"\"\"\n    BinarySearch(list,item)\n\nreturns a list of the indices at which `item` appears in the sorted list `list`.\n\"\"\"\n\n@doap BinarySearch(a::ListT,x) = tolist(searchsorted(margs(a),x))\n\n## TODO: We have a julia package that is much more efficient\n## at functions related to primes and factoring. Find a way to make an optional Symata package.\n\n### FactorInteger\n\n@sjdoc FactorInteger \"\"\"\n    FactorInteger(n)\n\ngive a list of prime factors of `n` and their multiplicities.\n\"\"\"\n@mkapprule FactorInteger nargs => 1:2\n@doap FactorInteger(x) = tolistoflistsfixed(Primes.factor(x))\n\n### PrimeList\n\n@sjdoc PrimeList \"\"\"\n    PrimeList(n)\n\nreturn the list of all prime numbers `<= n`.\n\"\"\"\n\n## Convert `n` to Int to work around julia bug\n@mkapprule PrimeList nargs => 1\n@doap PrimeList(n::Integer) = tolistfixed(Primes.primes(convert(Int,n)))\n\n### Prime\n\n@sjdoc Prime \"\"\"\n    Prime(n)\n\nreturns the `n`th prime number.\n\"\"\"\n@mkapprule Prime :nargs => 1\n@doap Prime(n::Integer) = sympy.prime(n)\n\n### PrimePi\n\n@mkapprule PrimePi nargs => 1  \"\"\"\n    PrimePi(n)\n\nreturns the number of primes less than or equal to `n`.\n\"\"\"\n\n@doap PrimePi(n::Integer) = sympy.primepi(n)\n\n### Permutations\n\n@mkapprule Permutations nargs => 1:2  \"\"\"\n    Permutations(expr)\n\ngive a list of all permutations of elements in `expr`.\n\"\"\"\n\n@doap Permutations(x::Mxpr) = tolistoflistsfixed(Combinatorics.permutations(margs(x)))\n\n### IntegerPartitions\n\n## The Mathematica \"way\" is not very convenient. It is clumsy to controll what you\n## want (regardless of the implmentation here, it is clumsy for the user.) But, it\n## is not clear how to avoid this kind of interface to julia `partitions`\n\n## Setting \"fixed\" below increases speed by 3 or 5 times in some tests.\n\n@mkapprule IntegerPartitions\n@doap IntegerPartitions(n::Integer) = tolistoflistsfixed(Combinatorics.partitions(n))\n@doap IntegerPartitions(n::Integer, m::Integer) = _integer_partitions_range(n,1,m)\n\nfunction _integer_partitions_range(n,m1,m2)\n    a = collect(Combinatorics.partitions(n,m1))\n    for i in (m1+1):m2\n        c = collect(Combinatorics.partitions(n,i))\n        isempty(c) && continue\n        append!(a,c)\n    end\n    tolistoflists(a)\nend\n\n@doap IntegerPartitions(n::Integer, ls::ListT) = listofintegersq(ls) ?  _integer_partitions_list(mx,n,margs(ls)...) : mx\n_integer_partitions_list(mx,n,m) = tolistoflistsfixed(collect(Combinatorics.partitions(n,m)))\n_integer_partitions_list(mx,n,m1,m2) = _integer_partitions_range(n,m1,m2)\n_integer_partitions_list(mx,n,m,args...) = mx\n\n@mkapprule NumberOfPartitions nargs => 1  \"\"\"\n    NumberOfPartitions(n)\n\ngives the number of integer partitions of `n`.\n\"\"\"\n\n@doap NumberOfPartitions(n::Integer) = n <= 405 ? length(Combinatorics.partitions(n)) : bnpartitions(n)\n\n## copied from partitions.jl. We just add the BigInt dict\n## If n > 405, we need BigInt.\n## We intentionally eschew type stability.\nbnpartitions(n::Integer) = _bnpartitions_func(convert(Int,n))\n\nlet _bnpartitions = Dict{Int,BigInt}()\n    global _bnpartitions_func\n    function _bnpartitions_func(n::Int)\n        if n < 0\n            0\n        elseif n < 2\n            1\n        elseif (np = get(_bnpartitions, n, 0)) > 0\n            np\n        else\n            np = 0\n            sgn = 1\n            for k = 1:n\n                np += sgn * (bnpartitions(n - (k * (3k - 1)) >> 1) + bnpartitions(n - (k * (3k + 1)) >> 1))\n                sgn = -sgn\n            end\n            _bnpartitions[convert(Int,n)] = np\n        end\n    end\nend\n\n### Named polynomial sequences.\n\n## @runtime_include is defined in util.jl\n\n@runtime_include \"PolynomialSequences.jl\" _init_polys\n\n### Fibonaccci\n\n@mkapprule Fibbonaci nargs => 1:2\n\n@doap function Fibbonaci(n::Integer)\n    n < 0 && return mx\n    Combinatorics.fibonaccinum(n)\nend\n\n# The choice of n <= 92 is arbitrary. This is where evaluation with x = 1 causes Int overflow\n@doap function Fibbonaci(n::Integer,x)\n    n < 0 && return mx\n    _init_polys() || return mx\n    p =  n <= 92 ? fibpoly(n) :\n          fibpoly(big(n))\n    fromjuliaPolynomial(p,x)\nend\n\n### LucasL\n\n@mkapprule LucasL nargs => 1:2\n\n@doap function LucasL(n::Integer)\n    n < 0 && return mx\n    Combinatorics.lucasnum(n)\nend\n\n@doap function LucasL(n::Integer,x)\n    n < 0 && return mx\n    _init_polys() || return mx\n    p =  n <= 90 ? lucaspoly(n) :\n          lucaspoly(big(n))\n    fromjuliaPolynomial(p,x)\nend\n\n### Interface to Julia Polynomials.jl\n\n## TODO: why do we have to do mergesyms here, but not when \"var\" is a Mxpr, as below\n## ... a method is missing in evaluation.jl ?\nfunction fromjuliaPolynomial(p::Polynomials.Poly, var::Symbol)\n    res = _fromjuliaPolynomial(p,var)\n    mergesyms(res,var)  # force evaluation when var changes.\n    if isa(res,Mxpr)\n        a = margs(res)\n        foreach(setfixed, a)\n    end\n    setfixed(res)\nend\n\n## symbols are merged correctly automatically.\n## TODO: It is probably faster to merge symbols here\nfunction fromjuliaPolynomial(p::Polynomials.Poly, var)\n    _fromjuliaPolynomial(p,var)\nend\n\nfunction _fromjuliaPolynomial(p::Polynomials.Poly, var)\n    cs = Polynomials.coeffs(p)\n    nc = length(cs)\n    nargs = newargs()\n    if nc > 0\n        if cs[1] != 0\n            push!(nargs,cs[1])\n        end\n    end\n    if nc > 1\n        if cs[2] > 1\n            push!(nargs, mmul(cs[2], var))\n        elseif cs[2] == 1\n            push!(nargs,var)\n        end\n    end\n    for i in 3:length(cs)\n        c = cs[i]\n        c == 0 && continue\n        n = i - 1\n        push!(nargs, _monomial(var, c, n))\n    end\n    mxpra(:Plus,nargs)\nend\n\n## assumes n != 0,  n != 1\nfunction _monomial(var,c,n)\n    if c == 1\n        mpow(var,n)\n    else\n        mmul(c, mpow(var, n))\n    end\nend\n", "meta": {"hexsha": "8c86fdd35b977451d25ec60478adfb2c90e33a01", "size": 5819, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/numcomb.jl", "max_stars_repo_name": "jlapeyre/Symata.jl", "max_stars_repo_head_hexsha": "bfe97c96176853d80e7fbb15f35aa9a3d3a4534f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 149, "max_stars_repo_stars_event_min_datetime": "2016-10-09T07:17:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T02:18:19.000Z", "max_issues_repo_path": "src/numcomb.jl", "max_issues_repo_name": "jlapeyre/Symata.jl", "max_issues_repo_head_hexsha": "bfe97c96176853d80e7fbb15f35aa9a3d3a4534f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 183, "max_issues_repo_issues_event_min_datetime": "2016-10-14T15:49:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-01T12:20:47.000Z", "max_forks_repo_path": "src/numcomb.jl", "max_forks_repo_name": "jlapeyre/SJulia.jl", "max_forks_repo_head_hexsha": "bfe97c96176853d80e7fbb15f35aa9a3d3a4534f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2016-10-09T07:08:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-29T10:37:49.000Z", "avg_line_length": 25.4104803493, "max_line_length": 120, "alphanum_fraction": 0.6545798247, "num_tokens": 1739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7862530769244287}}
{"text": "struct LinearLS{T<:Real}\n    x :: Vector{T}  # x data\n    y :: Vector{T}  # y data\n    f :: Function   # y = m*f(x) + q\n    w :: Vector{T}  # weights (inverse a priori error on the `y`'s)\n    m :: Float64    # slope\n    q :: Float64    # intercept\n    function LinearLS(x::AbstractVector{<:Real}, y::AbstractVector{<:Real}, \n        f::Function, w::AbstractVector{<:Real}, m::Real, q::Real) \n        T = promote_type(eltype(x), eltype(y), eltype(w))\n        new{T}(Vector{T}(x), Vector{T}(y), f, Vector{T}(w), m, q)\n    end\nend\n\nfunction Base.show(io::IO, ls::LinearLS)\n    println(io, \"Linear fit Y ~ m*f(X) + q\")\n    println(io, \"\\tf = \", ls.f)\n    println(io, \"\\tm = \", ls.m)\n    println(io, \"\\tq = \", ls.q)\nend\n\n\"\"\"\n    linearls(x::AbstractVector, y::AbstractVector, f::Function=identity;\n        weights=ones(length(x)))\n \nLinear fit for `y = m*f(x) + q`.\nReturn a `LinearLS` object storing the estimated `m, q` \nOptionally provide `weights` for Weighted LS\n\n\"\"\"\nfunction linearls(x::AbstractVector, y::AbstractVector, f::Function=identity;\n        weights=ones(length(x)))\n    X = diagm(weights) * [f.(x) ones(length(x))]\n    Y = weights .* y\n    m, q = X \\ Y\n    LinearLS(x, y, f, weights, m, q)\nend\n\n\"\"\"\n    predict(ls::LinearLS, x::AbstractVector)\n\nPredict new values based on the linear fit object `ls`. See `linearls`\n\n\"\"\"\nfunction predict(ls::LinearLS, x::AbstractVector)\n    ls.f.(x) .* ls.m .+ ls.q\nend\n", "meta": {"hexsha": "3f6a84c26e530a4676c492825e8d07e407063e48", "size": 1417, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LinearLS.jl", "max_stars_repo_name": "stecrotti/JuliaUtils.jl", "max_stars_repo_head_hexsha": "51e09a622a0ae96de6b8cc162ef985fc9b11c915", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LinearLS.jl", "max_issues_repo_name": "stecrotti/JuliaUtils.jl", "max_issues_repo_head_hexsha": "51e09a622a0ae96de6b8cc162ef985fc9b11c915", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LinearLS.jl", "max_forks_repo_name": "stecrotti/JuliaUtils.jl", "max_forks_repo_head_hexsha": "51e09a622a0ae96de6b8cc162ef985fc9b11c915", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5208333333, "max_line_length": 77, "alphanum_fraction": 0.5942131263, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7862303212558852}}
{"text": "\"\"\"\r\n    relax(t, M0, T1, T2)\r\n\r\nSimulate relaxation.\r\n\r\n# Arguments\r\n- `t::Real`: Duration of relaxation\r\n- `M0::Real`: Equilibrium magnetization\r\n- `T1::Real`: Spin-lattice recovery time constant\r\n- `T2::Real`: Spin-spin recovery time constant\r\n\r\n## Note\r\nInputs `t`, `T1`, and `T2` should all have the same units, typically ms.\r\n\r\n# Return\r\n- `A::Matrix`: 3×3 matrix that describes relaxation\r\n- `B::Vector`: 3-vector that describes recovery\r\n\r\n# Examples\r\n```jldoctest\r\njulia> (A, B) = relax(100, 1, 1000, 100); A * [1, 0, 0] + B\r\n3-element Array{Float64,1}:\r\n 0.36787944117144233\r\n 0.0\r\n 0.09516258196404048\r\n```\r\n\"\"\"\r\nfunction relax(t::Real, M0::Real, T1::Real, T2::Real)\r\n\r\n    E1 = exp(-t/T1)\r\n    E2 = exp(-t/T2)\r\n    A = [E2 0 0; 0 E2 0; 0 0 E1]\r\n    B = [0, 0, M0 * (1 - E1)]\r\n    return (A, B)\r\n\r\nend\r\n\r\n\"\"\"\r\n    rotatex(α)\r\n\r\nSimulate left-handed rotation about the x-axis.\r\n\r\n# Arguments\r\n- `α::Real`: Rotation angle (rad)\r\n\r\n# Return\r\n- `R::Matrix`: 3×3 matrix that describes rotation about the x-axis by angle `α`\r\n\r\n# Examples\r\n```jldoctest\r\njulia> R = rotatex(π/2); R * [0, 0, 1]\r\n3-element Array{Float64,1}:\r\n 0.0\r\n 1.0\r\n 6.123233995736766e-17\r\n```\r\n\"\"\"\r\nfunction rotatex(α::Real)\r\n\r\n    return [1 0 0; 0 cos(α) sin(α); 0 -sin(α) cos(α)]\r\n\r\nend\r\n\r\n\"\"\"\r\n    rotatey(α)\r\n\r\nSimulate left-handed rotation about the y-axis.\r\n\r\n# Arguments\r\n- `α::Real`: Rotation angle (rad)\r\n\r\n# Return\r\n- `R::Matrix`: 3×3 matrix that describes rotation about the y-axis by angle `α`\r\n\r\n# Examples\r\n```jldoctest\r\njulia> R = rotatey(π/2); R * [0, 0, 1]\r\n3-element Array{Float64,1}:\r\n -1.0\r\n  0.0\r\n  6.123233995736766e-17\r\n```\r\n\"\"\"\r\nfunction rotatey(α::Real)\r\n\r\n    return [cos(α) 0 -sin(α); 0 1 0; sin(α) 0 cos(α)]\r\n\r\nend\r\n\r\n\"\"\"\r\n    rotatez(ϕ)\r\n\r\nSimulate left-handed rotation about the z-axis.\r\n\r\n# Arguments\r\n- `ϕ::Real`: Rotation angle (rad)\r\n\r\n# Return\r\n- `R::Matrix`: 3×3 matrix that describes rotation about the z-axis by angle `ϕ`\r\n\r\n# Examples\r\n```jldoctest\r\njulia> R = rotatez(π/2); R * [0, 1, 0]\r\n3-element Array{Float64,1}:\r\n 1.0\r\n 6.123233995736766e-17\r\n 0.0\r\n```\r\n\"\"\"\r\nfunction rotatez(ϕ::Real)\r\n\r\n    return [cos(ϕ) sin(ϕ) 0; -sin(ϕ) cos(ϕ) 0; 0 0 1]\r\n\r\nend\r\n\r\n\"\"\"\r\n    rotatetheta(θ, α)\r\n\r\nSimulate left-handed rotation about an axis in the x-y plane that makes angle\r\n`θ` with the negative y-axis.\r\n\r\n# Arguments\r\n- `θ::Real`: Orientation of the axis about which to rotate (rad)\r\n- `α::Real`: Rotation angle (rad)\r\n\r\n# Return\r\n- `R::Matrix`: 3×3 matrix that describes rotation by angle `α` about an axis in\r\n    the x-y plane that makes angle `θ` with the negative y-axis\r\n\r\n## Note\r\n`rotatetheta(θ, α) == rotatez(θ) * rotatey(-α) * rotatez(-θ)`\r\n\r\n# Examples\r\n```jldoctest\r\njulia> R = rotatetheta(π/4, π/2); R * [0, 0, 1]\r\n3-element Array{Float64,1}:\r\n  0.7071067811865476\r\n -0.7071067811865475\r\n  6.123233995736766e-17\r\n```\r\n\"\"\"\r\nfunction rotatetheta(θ::Real, α::Real)\r\n\r\n    return [ sin(θ)^2+cos(α)*cos(θ)^2           sin(θ)*cos(θ)-cos(α)*sin(θ)*cos(θ)  sin(α)*cos(θ);\r\n             sin(θ)*cos(θ)-cos(α)*sin(θ)*cos(θ) cos(θ)^2+cos(α)*sin(θ)^2           -sin(α)*sin(θ);\r\n            -sin(α)*cos(θ)                      sin(α)*sin(θ)                       cos(α)]\r\n\r\nend\r\n\r\n\"\"\"\r\n    freeprecess(t, M0, T1, T2, Δf)\r\n\r\nSimulate free-precession, i.e., relaxation and off-resonance precession.\r\n\r\n# Arguments\r\n- `t::Real`: Duration of free-precession (ms)\r\n- `M0::Real`: Equilibrium magnetization\r\n- `T1::Real`: Spin-lattice recovery time constant (ms)\r\n- `T2::Real`: Spin-spin recovery time constant (ms)\r\n- `Δf::Real`: Off-resonance frequency (Hz)\r\n\r\n# Return\r\n- `A::Matrix`: 3×3 matrix that describes relaxation and precession\r\n- `B::Vector`: 3-vector that describes recovery\r\n\r\n# Examples\r\n```jldoctest\r\njulia> (A, B) = freeprecess(100, 1, 1000, 100, 3.75); A * [1, 0, 0] + B\r\n3-element Array{Float64,1}:\r\n -0.2601300475114444\r\n -0.2601300475114445\r\n  0.09516258196404048\r\n```\r\n\"\"\"\r\nfunction freeprecess(t::Real, M0::Real, T1::Real, T2::Real, Δf::Real)\r\n\r\n    (A, B) = relax(t, M0, T1, T2)\r\n    C = rotatez(2π * Δf * t/1000)\r\n    return (C * A, B)\r\n\r\nend\r\n", "meta": {"hexsha": "4ceed482674697342c1cac73aaf697cb4bc3ae37", "size": 4071, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/helpers.jl", "max_stars_repo_name": "UnofficialJuliaMirror/BlochSim.jl-5c0f8cbe-99a4-11e9-108b-216da9629524", "max_stars_repo_head_hexsha": "353bf6611820c31ce2933748046a31008e596be0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/helpers.jl", "max_issues_repo_name": "UnofficialJuliaMirror/BlochSim.jl-5c0f8cbe-99a4-11e9-108b-216da9629524", "max_issues_repo_head_hexsha": "353bf6611820c31ce2933748046a31008e596be0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/helpers.jl", "max_forks_repo_name": "UnofficialJuliaMirror/BlochSim.jl-5c0f8cbe-99a4-11e9-108b-216da9629524", "max_forks_repo_head_hexsha": "353bf6611820c31ce2933748046a31008e596be0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3681318681, "max_line_length": 99, "alphanum_fraction": 0.5991156964, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480347, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7862303208711866}}
{"text": "# Exercise 1a\nusing LinearAlgebra\n\n\nfunction trap_weights(x)\n    return step(x) * [0.5; ones(length(x) - 2); 0.5]\nend\nx = range(0.0, 1.0, length = 10)\nω = trap_weights(x)\nf(x) = x^2\ndot(f.(x), ω)\n\nstruct UniformTrapezoidal\n    count::Int\n    Δ::Float64\nend\n\nBase.iterate(S::UniformTrapezoidal, state=1) = state > S.count ? nothing : (if state == 1 || state == count; Δ*0.5 else Δ*1.0 end, state+1)\n\nfunction integration(f, x::AbstractArray; count = 10)\n    Δ = step(x)\n    int = similar(x)\n    for (i,value) in enumerate(UniformTrapezoidal(count,Δ))\n        int[i] = f(x[i]) * value\n    end\n    return sum(int)\nend\n\ncount = 100\nx = range(0.0, 1.0, length = count)\n@show Δ = step(x)\nf(x) = x^2\n\nintegral = integration(f,x,count = count)\n\n\nstruct Squares\n    count::Int\nend\n\nBase.iterate(S::Squares, state=1) = state > S.count ? nothing : (state*state, state+1)\n\nfor i in Squares(7)\n    println(i)\nend\n\nstruct SquaresVector <: AbstractArray{Int, 1}\n    count::Int\nend\nBase.size(S::SquaresVector) = (S.count,)\nBase.IndexStyle(::Type{<:SquaresVector}) = IndexLinear()\nBase.getindex(S::SquaresVector, i::Int) = i*i\n\ns = SquaresVector(4)\ns[2]\n\n\n# Exercise 1b\n\nstruct TrapezoidalVector <: AbstractArray{Int, 1}\n    count::Int\nend\nBase.size(S::TrapezoidalVector) = (S.count,)\nBase.IndexStyle(::Type{<:TrapezoidalVector}) = IndexLinear()\nBase.getindex(S::TrapezoidalVector, i::Int) = 1\nBase.setindex!(S::TrapezoidalVector, v, 2) = 2\n\n\nV = TrapezoidalVector(4)\n", "meta": {"hexsha": "f5d30562602fc70e99f335b8a541d2f549a742de", "size": 1451, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Packages_GenericProgramming.jl", "max_stars_repo_name": "shanemcmiken/quantecon-notebooks-julia", "max_stars_repo_head_hexsha": "c9968403bc866fe1f520762619055bd21e09ad10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Packages_GenericProgramming.jl", "max_issues_repo_name": "shanemcmiken/quantecon-notebooks-julia", "max_issues_repo_head_hexsha": "c9968403bc866fe1f520762619055bd21e09ad10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Packages_GenericProgramming.jl", "max_forks_repo_name": "shanemcmiken/quantecon-notebooks-julia", "max_forks_repo_head_hexsha": "c9968403bc866fe1f520762619055bd21e09ad10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7285714286, "max_line_length": 139, "alphanum_fraction": 0.6623018608, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8757869835428965, "lm_q1q2_score": 0.7861898568094093}}
{"text": "# This file is a part of JuliaFEM.\n# License is MIT: see https://github.com/JuliaFEM/JuliaFEM.jl/blob/master/LICENSE.md\n\n# some preliminary code for constructing hierarchical elements\n\nabstract Hierarchical <: Element\n\nbin(n, k) = prod([(n + 1 - i)/i for i=1:k])\n\n\"\"\"\nReturn Legendgre polynomial of order n to inverval ξ ∈  [-1, 1]\n\nParameters\n----------\nn :: Int\n    order of polynomial\n\nReturns\n-------\nfunction\n    Legendgre polynomial of order n in interval ξ ∈ [-1, 1]\n\"\"\"\nfunction get_legendre_polynomial(n::Int)\n    P(xi) = 2^n*sum([xi.^k*bin(n, k)*bin(1/2*(n+k-1), n) for k=0:n])\n    P\nend\n\n\"\"\"\nReturn derivative of Legendgre polynomial of order n to inverval ξ ∈  [-1, 1]\n\"\"\"\nfunction get_legendre_polynomial_derivative(n::Int)\n    dP(xi) = 2^n*sum([k*xi.^(k-1)*bin(n, k)*bin(1/2*(n+k-1), n) for k=1:n])\n    dP\nend\n\n\"\"\"\nReturn Legendgre polynomial of order n to inverval ξ ∈ [1, 1].\n\nParameters\n----------\nn :: Int\n    order of polynomial\n\nReturns\n-------\nfunction\n    Legendgre polynomial of order n in interval ξ ∈ [-1, 1]\n\nNotes\n-----\nUses Bonnet's recursion formula. See\nhttps://en.wikipedia.org/wiki/Legendre_polynomials\n\"\"\"\nfunction get_legendre_polynomial_recursive(n)\n    if n == 0\n        P(xi) = 1\n    elseif n == 1\n        P(xi) = xi\n    else\n        Pm1 = get_legendre_polynomial(n-1)\n        Pm2 = get_legendre_polynomial(n-2)\n        P(xi) = 1/n*((2*n-1)*xi*Pm1(xi) - (n-1)*Pm2(xi))\n    end\n    return P\nend\n\n\"\"\"\nReturn derivative of Legendgre polynomial of order n to inverval ξ ∈  [-1, 1]\n\"\"\"\nfunction get_legendre_polynomial_derivative_recursive(n)\n    if n == 0\n        P(xi) = 0\n    elseif n == 1\n        P(xi) = 1\n    else\n        Pm1 = get_legendre_polynomial_derivative(n-1)\n        Pm2 = get_legendre_polynomial_derivative(n-2)\n        P(xi) = 1/(n-1)*( (2*(n-1)+1)*xi.*Pm1(xi) - (n+1-1)*Pm2(xi))\n    end\n    return P\nend\n\n\"\"\"\nReturn hierarchical shape function of order N\n\"\"\"\nfunction get_hierarchial_basis(n)\n    if n == 1\n        N(xi) = 1/2*(1 - xi)\n    elseif n == 2\n        N(xi) = 1/2*(1 + xi)\n    else\n        j = n-1\n        Pj = get_legendre_polynomial(j)\n        Pjm2 = get_legendre_polynomial(j-2)\n        N(xi) = 1/sqrt(2*(2*j-1))*(Pj(xi) - Pjm2(xi))\n    end\n    return N\nend\n\n\"\"\"\nReturn derivative of hierarchical shape function of order N\n\"\"\"\nfunction get_hierarchial_basis_derivative(n)\n    if n == 1\n        dN(xi) = -1/2\n    elseif n == 2\n        dN(xi) = 1/2\n    else\n        j = n-1\n        Pj = get_legendre_polynomial_derivative(j)\n        Pjm2 = get_legendre_polynomial_derivative(j-2)\n        dN(xi) = 1/sqrt(2*(2*j-1))*(Pj(xi) - Pjm2(xi))\n    end\n    return dN\nend\n\n\"\"\"\nSet degree of hierarchical element\n\"\"\"\nfunction set_degree(el::Hierarchical, degree)\n    el.degree = degree\nend\n\n\"\"\"\nGet degree of hierarchical element\n\"\"\"\nfunction get_degree(el::Hierarchical)\n    el.degree\nend\n\n\"\"\"\nHierarchical 1d segment element.\n\"\"\"\ntype PSeg <: Hierarchical\n    connectivity :: Array{Int, 1}\n    fields :: Dict{Any, Any}\n    degree :: Int\nend\nPSeg(connectivity) = PSeg(connectivity, Dict{Any,Any}(), 1)\nget_number_of_basis_functions(el::Type{PSeg}) = 2\nget_number_of_basis_functions(el::PSeg) = 2 + el.degree - 1\nget_element_dimension(el::Type{PSeg}) = 1\nfunction get_basis(el::PSeg, xi)\n    m = get_number_of_basis_functions(el)\n    out = zeros(m)\n    for n=1:m\n        N = get_hierarchial_basis(n)\n        out[n] = N(xi[1])\n    end\n    return out\nend\nfunction get_dbasisdxi(el::PSeg, xi)\n    m = get_number_of_basis_functions(el)\n    out = zeros(m)\n    for n=1:m\n        dN = get_hierarchial_basis_derivative(n)\n        out[n] = dN(xi[1])\n    end\n    return out\nend\n", "meta": {"hexsha": "f0775f390433966625043361ff58e300b87f2db0", "size": 3617, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/elements_hierarchical.jl", "max_stars_repo_name": "JuliaPackageMirrors/JuliaFEM.jl", "max_stars_repo_head_hexsha": "9b1cc3e1347ccc8e798630a8805e3917934eadaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/elements_hierarchical.jl", "max_issues_repo_name": "JuliaPackageMirrors/JuliaFEM.jl", "max_issues_repo_head_hexsha": "9b1cc3e1347ccc8e798630a8805e3917934eadaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/elements_hierarchical.jl", "max_forks_repo_name": "JuliaPackageMirrors/JuliaFEM.jl", "max_forks_repo_head_hexsha": "9b1cc3e1347ccc8e798630a8805e3917934eadaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4658385093, "max_line_length": 84, "alphanum_fraction": 0.6231683716, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338068793908, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7861254920910002}}
{"text": "XYTuple{T} = Tuple{Real, Real}\n\n+(p1::XYTuple, p2::XYTuple) = (p1[1] + p2[1], p1[2] + p2[2])\n-(p1::XYTuple, p2::XYTuple) = (p1[1] - p2[1], p1[2] - p2[2])\n*(p::XYTuple, c::Real) = (c * p[1], c * p[2])\n*(c::Real, p::XYTuple) = (c * p[1], c * p[2])\n/(p::XYTuple, c::Real) = (p[1] / c, p[2] / c)\n\n\n\"\"\"\n    partition(start, stop, N)\n\nGenerates N equally spaced, centered points between start and stop.\n\"\"\"\nfunction partition(start::XYTuple, stop::XYTuple, N::Integer)\n    dist = stop -start\n    step = dist / N\n    [start + (i - 0.5) * step for i in 1:N]\nend\n", "meta": {"hexsha": "d6e584f211ca49438995812961f4fdb19b24dd36", "size": 554, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TupleMath.jl", "max_stars_repo_name": "ffreyer/VisualCircuits.jl", "max_stars_repo_head_hexsha": "7e0216ab09953211d8058f58704b798b0b09ceee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TupleMath.jl", "max_issues_repo_name": "ffreyer/VisualCircuits.jl", "max_issues_repo_head_hexsha": "7e0216ab09953211d8058f58704b798b0b09ceee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TupleMath.jl", "max_forks_repo_name": "ffreyer/VisualCircuits.jl", "max_forks_repo_head_hexsha": "7e0216ab09953211d8058f58704b798b0b09ceee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7, "max_line_length": 67, "alphanum_fraction": 0.5523465704, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7861147398236902}}
{"text": "module LinearAlgebraStudy\nusing Symbolics\nusing SymbolicUtils\nusing Plots\nusing LinearAlgebra\n\n\nexport drawVector, testVectorsIndependance, transformVectorBasis2D, transformVectorBasis4D\n\n\n\n\"\"\"\n    drawVector(f, V::Vector, origin::Vector = [0,0], xlim=(0,5), ylim=(0,5), title=\"Vector Plot\", label = \"Vector 1\"))\n\n    Draws a Vector V in the current plot at the origin.\n\n    # Parameters\n    f: Plot function\n        plot or plot!\n    V : Vector\n        The vector to be drawn.\n    origin : Origin Coordinate\n        The origin of the coordinate system. \n\n    # Returns\n    plot : \n        The plot of the vector.\n\n    # Example\n   ```julia\n    using LinearAlgebraStudy\n    V = Vector([1,2])\n    origin = [0,0]\n    drawVector(V, origin, (0,5), (0,5), \"Vector Plot\", \"Vector 1\")\n    ```\n\"\"\"\nfunction drawVector(f, V::Vector, origin::Vector = [0,0], xlim=(0,5), ylim=(0,5), title=\"Vector Plot\", label = \"Vector 1\")\n\n    return f([origin[1], V[1] + origin[1]], [origin[2], V[2] + origin[2]],  xlims = xlim, ylims = ylim, line=:arrow, title = title, label = label)\n\nend\n\n\"\"\"\ntestVectorsIndependance(kwargs...)\n    This function will take a variable number of vectors and test if they are independant.\n    A Matrix \"M\" will be created with the vectors as columns.\n    The rank of the Matrix will then be calculated.\n    If the rank is equal to the number of vectors, then the vectors are independant.\n\n    # Parameters\n    kwargs : Vectors\n        The vectors to be tested.\n\n    # Returns\n    result : Bool\n        True if the vectors are independant, false otherwise.\n\n\"\"\"\nfunction testVectorsIndependance(kwargs...)\n    M = hcat(kwargs...)\n    rk = rank(M)\n    if rk == size(M)[2]\n        return true\n    else\n        return false\n    end\nend\n\n   \n\n\"\"\"\n    transformVectorBasis2D(P::Vector, BX::Vector, BY::Vector) \n        Function to transform a given Vector P point to a new Basis. Original Basis is assumed to be\n        the standard cartesian basis.\n        The transformed Vector is the equivalent of the original Vector P in the new Basis.\n\n        Vectors can be described in terms of scalar multiplication of the basis vectors:\n        Example:\n            P=[2,1] is the original Vector with standard cartersian basis (X=[1,0],Y=[0,1]).\n            This can be written as linear combination of the basis vectors:\n                P=2*X+1*Y\n            \n            If we want to transform this Vector to a new basis (X'=[1,1],Y'=[0,2]), we can write the\n            new vector on the new basis as a linear combination and then solve for the new scalar coefficients:\n                \n             ```\n            \n            P'=c₁*X'+ c₂*Y'  ⟹ c₁ * [1,1] + c₂ * [0,2] = [2,1]\n\n            let A = [1 0   # Matrix A with new basis vectors\n                     1 2]\n            \n            let b = [2 1] # Vector b with original coordinates of point P.\n\n            let c = Vector of new coordinates on new Basis corresponding to original coordinates point P.\n\n                c = A\\b\n\n            ```\n\n    # Parameters\n    b::Vector\n        Vector to be transformed.\n    BX::Vector\n        X-component of the new basis.\n    BY::Vector\n        Y-component of the new basis.\n\n    # Returns\n    p::Vector\n        Transformed vector.\n\n    # Examples\n\n    \n    \n        \n\n\n\"\"\"\nfunction transformVectorBasis2D(b::Vector, BX::Vector, BY::Vector)\n    A = [BX BY] # Matrix A with new basis vectors as columns\n    \n    c = A\\b # Solve for new coordinates on new Basis corresponding to original coordinates point P.\n\n    return c\nend\n\n\"\"\"\n    transformVectorBasis2D(P::Vector, BX::Vector, BY::Vector) \n        Function to transform a given Vector P point to a new Basis. Original Basis is assumed to be\n        the standard cartesian basis.\n        The transformed Vector is the equivalent of the original Vector P in the new Basis.\n\n        Vectors can be described in terms of scalar multiplication of the basis vectors:\n        Example:\n            P=[2,1] is the original Vector with standard cartersian basis (X=[1,0],Y=[0,1]).\n            This can be written as linear combination of the basis vectors:\n                P=2*X+1*Y\n            \n            If we want to transform this Vector to a new basis (X'=[1,1],Y'=[0,2]), we can write the\n            new vector on the new basis as a linear combination and then solve for the new scalar coefficients:\n                \n             ```\n            \n            P'=c₁*X'+ c₂*Y'  ⟹ c₁ * [1,1] + c₂ * [0,2] = [2,1]\n\n            let A = [1 0   # Matrix A with new basis vectors\n                     1 2]\n            \n            let b = [2 1] # Vector b with original coordinates of point P.\n\n            let c = Vector of new coordinates on new Basis corresponding to original coordinates point P.\n\n                c = A\\b\n\n            ```\n\n    # Parameters\n    b::Vector\n        Vector to be transformed.\n    BX::Vector\n        X-component of the new basis.\n    BY::Vector\n        Y-component of the new basis.\n\n    # Returns\n    p::Vector\n        Transformed vector.\n\n    # Examples\n\n    \n    \n        \n\n\n\"\"\"\nfunction transformVectorBasis4D(b::Vector, BX::Vector, BY::Vector, BZ::Vector, BW::Vector)\n    A = [BX BY BZ BW] # Matrix A with new basis vectors as columns\n    \n    c = A\\b # Solve for new coordinates on new Basis corresponding to original coordinates point P.\n\n    return c\nend\n\n\n\nend\n", "meta": {"hexsha": "dc3f84008a28b451dc5d2422fe9d2d657858bf2c", "size": 5350, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LinearAlgebraStudy.jl", "max_stars_repo_name": "gjunqueira-sys/LinearAlgebraStudy", "max_stars_repo_head_hexsha": "26e5c55e3099c699be730ce35bd3544a8a335d53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-23T12:49:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T12:49:28.000Z", "max_issues_repo_path": "src/LinearAlgebraStudy.jl", "max_issues_repo_name": "gjunqueira-sys/LinearAlgebraStudy.jl", "max_issues_repo_head_hexsha": "26e5c55e3099c699be730ce35bd3544a8a335d53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LinearAlgebraStudy.jl", "max_forks_repo_name": "gjunqueira-sys/LinearAlgebraStudy.jl", "max_forks_repo_head_hexsha": "26e5c55e3099c699be730ce35bd3544a8a335d53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1578947368, "max_line_length": 146, "alphanum_fraction": 0.5985046729, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7861147385733224}}
{"text": "include(\"featurescaling.jl\")\n\n\nX = [randn(100); 5+10*randn(100); 50+2*randn(100)]\n\nX = reshape(X,(100,3))'\n\nX_stand = standardization(X)\nmean(X_stand,2)\nstd(X_stand,2)\n\nstandardization!(X)\nmean(X,2)\nstd(X,2)\n\n\nX = [randn(100); 5+10*randn(100); 50+2*randn(100)]\n\nX = reshape(X,(100,3))\n\nX_stand = standardization(X)\nmean(X_stand,2)\nstd(X_stand,2)\n\nstandardization!(X)\nmean(X,1)\nstd(X,1)\n\n\nX = 5+10*randn(100)\n\nX_stand = standardization(X)\nmean(X_stand)\nstd(X_stand)\n\nstandardization!(X)\nmean(X)\nstd(X)\n", "meta": {"hexsha": "f1b9293a6d8856278a5d8c422e31962796377038", "size": 501, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "utilities/test_featurescaling.jl", "max_stars_repo_name": "SamuelWiqvist/adamcmcpaper", "max_stars_repo_head_hexsha": "39f595b7c1834b61cd5bb4d4cf29d23a4a8f7a36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-06-24T21:31:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-25T19:29:03.000Z", "max_issues_repo_path": "utilities/test_featurescaling.jl", "max_issues_repo_name": "SamuelWiqvist/adamcmcpaper", "max_issues_repo_head_hexsha": "39f595b7c1834b61cd5bb4d4cf29d23a4a8f7a36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utilities/test_featurescaling.jl", "max_forks_repo_name": "SamuelWiqvist/adamcmcpaper", "max_forks_repo_head_hexsha": "39f595b7c1834b61cd5bb4d4cf29d23a4a8f7a36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.8461538462, "max_line_length": 50, "alphanum_fraction": 0.6746506986, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920262, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7861147378712509}}
{"text": "function dp(M, i, p, memo)\n    # Base case\n    if i == 1\n        return M[i][p]\n    end\n\n    #Memorized\n    if memo[i, p] > 0\n        return memo[i, p]\n    end\n    \n    # Recursion\n    if p == 1\n        return memo[i, p] = M[i][p] + max(dp(M, i-1, 2, memo), dp(M, i-1, 3, memo))\n    elseif p == 2\n        return memo[i, p] = M[i][p] + max(dp(M, i-1, 1, memo), dp(M, i-1, 3, memo))\n    elseif p == 3\n        return memo[i, p] = M[i][p] + max(dp(M, i-1, 1, memo), dp(M, i-1, 2, memo))\n    end\nend\n\nfunction main()\n    N = parse(Int, readline())\n    M = [parse.(Int, split(readline())) for _ in 1:N]\n    memo = zeros(Int, N, 3)\n\n    println(max(dp(M, N, 1, memo), dp(M, N, 2, memo), dp(M, N, 3, memo)))\nend\n\nmain()", "meta": {"hexsha": "d5f7714b6e364e6b1ede861e28e1a46a8613ac64", "size": 711, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/chapter05/nicetak/dp_c.jl", "max_stars_repo_name": "tokuma09/algorithm_problems", "max_stars_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-07T15:46:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T15:46:58.000Z", "max_issues_repo_path": "problems/chapter05/nicetak/dp_c.jl", "max_issues_repo_name": "tokuma09/algorithm_problems", "max_issues_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-06-05T14:16:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-10T07:08:28.000Z", "max_forks_repo_path": "problems/chapter05/nicetak/dp_c.jl", "max_forks_repo_name": "tokuma09/algorithm_problems", "max_forks_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7, "max_line_length": 83, "alphanum_fraction": 0.4781997187, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7861147359188113}}
{"text": "# common_funcs.jl\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_x5plusy5\n\n  Calculates and returns x^5 + y^5\n\"\"\"->\nfunction calc_x5plusy5(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n\n  x = coords[1]\n  y = coords[2]\n  u = x^5 + y^5\n  \n  return u\nend # end function calc_x5plusy5\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_exp_xplusy\n\n  Calculates and returns e^(x + y)\n\"\"\"->\nfunction calc_exp_xplusy(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n\n  x = coords[1]\n  y = coords[2]\n  u = exp(x+y)\n\n  return u\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_sinwave\n\n  Calculates and returns sin(-x + t)\n\"\"\"->\nfunction calc_sinwave(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n \n  x = coords[1]\n  y = coords[2]\n\n  return sin(-x + t)\n#  return sin( (-x + -y)/2 + t)\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_sinwavey\n\n  Calculates and returns sin(y)^2 + 5*sin(y) + 3/sin(y)\n\"\"\"->\nfunction calc_sinwavey(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  y = coords[2]\n  return sin(y)^2 + 5*sin(y) + 3/sin(y)\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_sinwavey_pert\n\n  Calculates and returns 1000*sin(x)*calc_sinwavey\n\"\"\"->\nfunction calc_sinwavey_pert(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  return calc_sinwavey(coords, t)*1000*sin(x)\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_sinwave_ampl\n\n  Calculates and returns A*sin(-x + omega*t)\n\"\"\"->\nfunction calc_sinwave_ampl(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n\n  x = coords[1]\n  y = coords[2]\n\n  # omega = 1.0\n  # A = 2.0\n  omega = params.omega\n  A = params.sin_amplitude\n\n  return A*sin(-x + omega*t)\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_mms1\n\n  Calculates and returns the value of the solution for doing Method of \n  Manufactured solutions.  This is for debugging only, and could change\n  at any time.\n\"\"\"->\n\nfunction calc_mms1(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  px = 1.5\n  py = 1.5\n  return sin(px*x)*cos(py*y) + sin(px*x)*cos(py*y)\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_mms1dx\n\n  Calculates and returns the x derivative of calc_mms1\n\"\"\"->\nfunction calc_mms1dx(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  px = 1.5\n  py = 1.5\n  return px*cos(px*x)*cos(py*y) + px*cos(px*x)*cos(py*y)\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_x4\n\n  Calculates and returns a 4th order polynomial in x\n\"\"\"->\nfunction calc_x4(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  return x.^4 + x.^3 + x.^2 + x + 1\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_x5plusy5\n\n  Calculates and returns the x derivative of calc_x4\n\"\"\"->\nfunction calc_x4der(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  return 4*x.^3 + 3*x.^2 + 2*x + 1\nend\n\n\"\"\"\n  calculates and returns a degree 0 polynomial (ie. a constant)\n\"\"\"\nfunction calc_p0(params::ParamTypes, coords::AbstractArray{Tmsh}, t) where Tmsh\n\n  return 1\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p1\n\n  Calculates and returns a 1st order polynomial of x and y\n\"\"\"->\nfunction calc_p1(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  return  x + 1 + y\nend\n\nfunction calc_p1(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  z = coords[3]\n  return x + y + z + 1\nend\n  \n@doc \"\"\"\n### AdvectionEquationMod.calc_p1dx\n\n  Calculates and returns the x derivative of calc_p1\n\"\"\"->\nfunction calc_p1dx(params::ParamTypes, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  return 1\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p1dy\n\n  Calculates and returns the y derivative of calc_p1\n\"\"\"->\nfunction calc_p1dy(params::ParamTypes, coords::AbstractArray{Tmsh}, t) where Tmsh\n  y = coords[2]\n  return 1\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p1dz\n\n  Calculates and returns the z derivative of calc_p1\n\"\"\"->\nfunction calc_p1dz(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n  return 1\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p2\n\n  Calculates and returns a 2nd order polynomial in x and y\n\"\"\"->\nfunction calc_p2(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  return x^2 + x + 1 + y^2 + y\nend\n\nfunction calc_p2(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  z = coords[3]\n  return x^2 + x + 1 + y^2 + y + z^2 + z\nend\n\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p2dx\n\n  Calculates and returns a the x derivative of calc_p2\n\"\"\"->\nfunction calc_p2dx(params::ParamTypes, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  return 2*x + 1\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p2dy\n\n  Calculates and returns the y derivative of calc_p2\n\"\"\"->\nfunction calc_p2dy(params::ParamTypes, coords::AbstractArray{Tmsh}, t) where Tmsh\n  y = coords[2]\n  return 2*y + 1\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p2dz\n\n  Calculates and returns the z derivative of calc_p2\n\"\"\"->\n\nfunction calc_p2dz(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n  z = coords[3]\n  return 2*z + 1\nend\n\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p3\n\n  Calculates and returns a 3rd order polynomial in x and y (and z in 3d)\n\"\"\"->\nfunction calc_p3(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  return x^3 + x^2 + x + 1 + y^3 + y^2 + y\nend\n\nfunction calc_p3(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  z = coords[3]\n  return x^3 + x^2 + x + 1 + y^3 + y^2 + y + z^3 + z^2 + z\nend\n\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p3dx\n\n  Calculates and returns the x derivataive of calc_p3\n\"\"\"->\nfunction calc_p3dx(params::ParamTypes, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  return 3*x^2 + 2*x + 1\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p3dy\n\n  Calculates and returns the y derivative of calc_p3\n\"\"\"->\nfunction calc_p3dy(params::ParamTypes, coords::AbstractArray{Tmsh}, t) where Tmsh\n  y = coords[2]\n  return 3*y^2 + 2*y + 1\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p3dz\n\n  Calculates and returns the z derivative of calc_p3\n\"\"\"->\nfunction calc_p3dz(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n  z = coords[3]\n  return 3*z^2 + 2*z + 1\nend\n\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p4\n\n  Calculates and returns a 4th order polynomial in x and y\n\"\"\"->\nfunction calc_p4(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  return (x^4 + x^3 + x^2 + x + 1) + (y^4 + y^3 + y^2 + y)\nend\n\nfunction calc_p4(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  z = coords[3]\n  return (x^4 + x^3 + x^2 + x + 1) + (y^4 + y^3 + y^2 + y) + (z^4 + z^3 + z^2 + z)\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p4x\n\n  Calculates and returns the x derivative of calc_p4\n\"\"\"->\n\nfunction calc_p4dx(params::ParamTypes, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  return 4*x^3 + 3*x^2 + 2*x + 1\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p4dy\n\n  Calculates and returns the y derivative of calc_p4\n\"\"\"->\nfunction calc_p4dy(params::ParamTypes, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  return 4*y^3 + 3*y^2 + 2*y + 1\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p4dz\n\n  Calculates and returns the z derivative of calc_p4\n\"\"\"->\nfunction calc_p4dz(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n  z = coords[3]\n  return 4*z^3 + 3*z^2 + 2*z + 1\nend\n\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p5\n\n  Calculates and returns a 5th order polynomial in x and y (and z in 3d)\n\"\"\"->\nfunction calc_p5(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  return (x.^5 + x^4 + x^3 + x^2 + x + 1) + (y^5 + y^4 + y^3 + y^2 + y)\nend\n\nfunction calc_p5(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  z = coords[3]\n  return (x.^5 + x^4 + x^3 + x^2 + x + 1) + (y^5 + y^4 + y^3 + y^2 + y) + (z^5 + z^4 + z^3 + z^2 + z)\nend\n\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p5dx\n\n  Calculates and returns the x derivative of calc_p5\n\"\"\"->\nfunction calc_p5dx(params::ParamTypes, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  return 5*x^4 + 4*x^3 + 3*x^2 + 2*x + 1\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p5y\n\n  Calculates and returns the y derivative of calc_p5\n\"\"\"->\n\nfunction calc_p5dy(params::ParamTypes, coords::AbstractArray{Tmsh}, t) where Tmsh\n  y = coords[2]\n  return 5*y^4 + 4*y^3 + 3*y^2 + 2*y + 1\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_p5z\n\n  Calculates and returns the z derivative of calc_p5\n\"\"\"->\n\nfunction calc_p5dz(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n  z = coords[3]\n  return 5*z^4 + 4*z^3 + 3*z^2 + 2*z + 1\nend\n\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_exp5xplus4yplus2\n\nCalculates and returns the expression u = exp(5*x + 4*y +2)\n\"\"\"->\n\nfunction calc_exp5xplus4yplus2(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  return exp(5*x + 4*y +2)\nend\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_exp5xplusy\n\nCalculates and return the expression u = exp(5*x + y)\n\"\"\"->\n\nfunction calc_exp5xplusy(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  return exp(5*x + y)\nend\n\nfunction calc_exp5xplusy(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  z = coords[3]\n  return exp(5*x + y + z)\nend\n\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_exp3xplusy\n\nCalculates and return the expression u = exp(3*x + y)\n\"\"\"->\n\nfunction calc_exp3xplusy(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  return exp(3*x + y)\nend\n\nfunction calc_exp3xplusy(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  z = coords[3]\n  return exp(3*x + y + z)\nend\n\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_exp2xplus2y\n\nCalculates and return the expression u = exp(2*x + 2*y)\n\"\"\"->\n\nfunction calc_exp2xplus2y(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  return exp(2*x + 2*y)\nend\n\nfunction calc_exp2xplus2y(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  z = coords[3]\n  return exp(2*x + 2*y + z*z)\nend\n\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_exp_xy\n\nCalculates and returns u = exp(x*y)\n\"\"\"->\n\nfunction calc_exp_xy(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  return exp(x*y)\nend\n\nfunction calc_exp_xy(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  z = coords[3]\n  return exp(x*y*z)\nend\n\n\n@doc \"\"\"\n### AdvectionEquationMod.calc_x5plusy5\n\nCalculates and returns u = x+y\n\"\"\"->\n\nfunction calc_xplusy(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  return x + y\nend\n\nfunction calc_xplusy(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  z = coords[3]\n  return x + y + z\nend\n\n\n\"\"\"\n  u = exp(x + y + z + t) in 3d (z = 0 in 2d)\n\"\"\"\nfunction calc_unsteadymms(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n\n  return exp(x + y + t)\nend\n\nfunction calc_unsteadymms(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n  z = coords[3]\n\n  return exp(x + y + z + t)\nend\n\n\nfunction calc_unsteadymmsdx(params::ParamType, coords::AbstractArray{Tmsh}, t) where Tmsh\n\n  calc_unsteadymms(params, coords, t)\nend\n\nfunction calc_unsteadymmsdy(params::ParamType, coords::AbstractArray{Tmsh}, t) where Tmsh\n\n  calc_unsteadymms(params, coords, t)\nend\n\nfunction calc_unsteadymmsdz(params::ParamType3, coords::AbstractArray{Tmsh}, t) where Tmsh\n\n  calc_unsteadymms(params, coords, t)\nend\n\n\nfunction calc_unsteadymmsdt(params::ParamType, coords::AbstractArray{Tmsh}, t) where Tmsh\n\n  calc_unsteadymms(params, coords, t)\nend\n\nfunction calc_unsteadypoly(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n\n  return x + 1 + y + t \nend\n\nfunction calc_unsteadypolydx(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n\n  return 1\nend\n\nfunction calc_unsteadypolydy(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n\n  return 1\nend\n\nfunction calc_unsteadypolydt(params::ParamType2, coords::AbstractArray{Tmsh}, t) where Tmsh\n  x = coords[1]\n  y = coords[2]\n\n  return 1\nend\n\n\n", "meta": {"hexsha": "e952b8bebb08287abfe26851869f5bc3c9a34cdc", "size": 12721, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solver/advection/common_funcs.jl", "max_stars_repo_name": "OptimalDesignLab/PDESolver.jl", "max_stars_repo_head_hexsha": "328ef45f764ab99a9d5cc3c5e4c0a4c56b263279", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2016-10-30T17:12:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-02T10:29:45.000Z", "max_issues_repo_path": "src/solver/advection/common_funcs.jl", "max_issues_repo_name": "tangwang-USTC/PDESolver.jl", "max_issues_repo_head_hexsha": "328ef45f764ab99a9d5cc3c5e4c0a4c56b263279", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 163, "max_issues_repo_issues_event_min_datetime": "2015-07-14T19:15:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-08T21:24:41.000Z", "max_forks_repo_path": "src/solver/advection/common_funcs.jl", "max_forks_repo_name": "tangwang-USTC/PDESolver.jl", "max_forks_repo_head_hexsha": "328ef45f764ab99a9d5cc3c5e4c0a4c56b263279", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-05-20T15:36:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T17:57:33.000Z", "avg_line_length": 22.2395104895, "max_line_length": 101, "alphanum_fraction": 0.6819432435, "num_tokens": 4444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.7860823794221012}}
{"text": "export ket,\n       bra,\n       ketbra,\n       partialtrace,\n       projector,\n       trnormalize,\n       trnormalize!,\n       purify,\n       fidelity,\n       concurrence,\n       avgfidelity,\n       ispossemidef,\n       pauli_decomp\n\ntrnorm(M::AbstractMatrix) = sum(svdvals(M))\n\n\"\"\"\n`basis_vector(T,i,d)`\n\nReturns the `(i+1)`th basis element in a `d` dimensional Euclidean space\nas a vector of type `t`.\n\"\"\"\nfunction basis_vector( t::Type{T}, i::Int, d::Int ) where T\n  result = zeros(T, d)\n  result[i+1] = 1\n  result\nend\n\n\"\"\"\n`ket`\n\nReturns a vector corresponding to a particular basis unit vector in some\nHilbert space.\n\nThe vector can be specified in a number of different ways:\n   + by a string and a base\n   + by a integer and a dimension\n\nIf the vector is specified by a string and a base, the dimension is\ninferred from the length of the string. The base is assumed to be 2\nunless explicitly specified.\n\nIf the basis element is specified by an integer, the dimension is\nassumed to be 2 unless explicitly specified. The integer values\nallowed are 0 through the dimension minus 1.\n\nOptionally, the type of the elements of the vector can be specified\nin the first argument.\n\"\"\"\nfunction ket(t::Type, label::AbstractString, base::Int)\n  basis_vector( t, parseint(label, base), base^length(label) )\nend\nket( label::AbstractString, base=2 ) = ket(Float64, label, base)\nket( t::Type, label::AbstractString ) = ket(t, label, 2)\n\nket( i::Int, d=2 ) = basis_vector( Float64, i, d )\n\n# the duals of the above\n\"\"\"\n`bra`\n\nReturns a dual vector (row vector) corresponding to a particular basis\nunit vector in some Hilbert space.\n\nSee `ket` for details on how the corresponding vector may be specified.\n\"\"\"\nfunction bra( t::Type, label::AbstractString, base::Int )\n  return ket( t, label, base )'\nend\n\nbra( label::AbstractString, base::Int ) = bra( Float64, label, base )\nbra( label::AbstractString ) = bra( Float64, label, 2 )\nbra( t::Type, label::AbstractString ) = bra( t, label, 2 )\nbra( i::Int, d::Int ) = ket( i, d )'\n\n\"\"\"\n`ketbra`\n\nReturns the outer product between a dual vector (row vector) and a vector,\neach corresponding to a particular basis unit vector in some Hilbert space.\nThis can also be interpreted as a matrix unite element specified by two\nunit vectors for a row and a column.\n\nSee `ket` for details on how the corresponding vectors may be specified.\n\"\"\"\nketbra( t::Type, label_left::AbstractString, label_right::AbstractString, base::Int ) = ket( t, label_left, base ) * bra( t, label_right, base )\nketbra( label_left::AbstractString, label_right::AbstractString, base::Int ) = ket( label_left, base ) * bra( label_right, base )\nketbra( label_left::AbstractString, label_right::AbstractString ) = ket( label_left ) * bra( label_right )\nketbra( t::Type, label_left::AbstractString, label_right::AbstractString ) = ket( t, label_left ) * bra( t, label_right )\nketbra( i::Int, j::Int, d::Int ) = ket( i, d ) * bra( j, d )\n\n\"\"\"\n`projector(v)`\n\nComputes the rank-1 projector operator corresponding to a given vector. If more than one\nvector is given, the projector into the space spanned by the vectors is computed.\n\"\"\"\nfunction projector( v::AbstractVector )\n    v*v'/norm(v,2)^2\nend\n\n\"\"\"\n`trnormalize(m)`\n\nNormalizes a matrix with respect to the trace norm (Schatten 1 norm).\n\"\"\"\ntrnormalize( m::AbstractMatrix ) = m/trnorm(m)\n\n\"\"\"\n`trnormalize!(v)`\n\nNormalizes a matrix with respect to the trace norm (Schatten 1\nnorm) in place.\n\"\"\"\nfunction trnormalize!( m::AbstractMatrix{T} ) where T <: ComplexF64\n    n = convert(ComplexF64, trnorm(m))\n    lmul!(1/n,m)\nend\n\nfunction trnormalize!( m::AbstractMatrix{T} ) where T <: Float64\n    n = trnorm(m)\n    lmul!(1/n,m)\nend\n\nfunction trnormalize!( m::AbstractMatrix{T} ) where T <: Int64\n    n = convert(Float64, trnorm(m))\n    m = convert(Array{Float64}, m)\n    lmul!(1/n,m)\nend\n\n\"\"\"\nComputes the partial trace of a matrix `m`.\n\"\"\"\nfunction partialtrace( m::AbstractMatrix{T}, ds::AbstractVector, dt::Int ) where T\n  s = size(m)\n  l = length(ds);\n  if s[1] != s[2]\n    error(\"Partial trace only defined for square matrices.\")\n  elseif prod(ds) != s[1] || prod(ds) != s[2]\n    error(\"Subsystem decomposition does not match matrix dimensions.\")\n  end\n  # the way we order subsystems is the opposite of the way we order\n  # significant digits, so we must changes the index of the subsystem\n  ds = reverse(ds)\n  dt = l - dt + 1\n  m = reshape( m, tuple(ds..., ds...))\n  # get a list of the indices not traced over\n  indices = [1:l;]\n  filter!(x -> x != dt, indices)\n  # reshape the matrix so that subsystem to be traced over is\n  # the \"last\" subsystem\n  m = permutedims(m, tuple(indices..., map(x->x+l,indices)..., dt, dt+l))\n  m = reshape( m, (prod(ds[indices])^2, ds[dt], ds[dt]))\n  # now trace over the last subsystem\n  new_m = zeros( T, prod(ds[indices])^2 )\n  for ii in 1:prod(ds[indices])^2\n    new_m[ii] = tr(reshape(m[ii,:,:],(ds[dt],ds[dt])))\n  end\n  reshape(new_m, (prod(ds[indices]),prod(ds[indices])) )\nend\n\n# TODO: specialized, fast versions of partial trace\n\nfunction _max_entangled_state( d::Int )\n  me = zeros(Float64,d^2)\n  for ii=0:d-1\n    me += kron(ket(ii,d),ket(ii,d))/sqrt(d)\n  end\n  return me\nend\n\n\"\"\"\nComputes a purification of `rho`\n\"\"\"\nfunction purify( rho::AbstractMatrix )\n  d = size(rho,1)\n  (vals,vecs) = eig(rho)\n  psi = zeros(eltypeof(rho), d^2)\n  for ii=1:d\n    psi += sqrt(vals[ii]) * kron(vecs[:,ii],ket(ii-1,d))\n  end\n  psi\nend\n\n\"\"\"\nComputes the concurrence of a bipartite qubit state.\n\"\"\"\nfunction concurrence(m)\n    ms = conj(m)\n    σy = [0 -1im; 1im 0];\n    mt = kron(σy,σy)*ms*kron(σy,σy)\n    R = sqrt(sqrt(m)*mt*sqrt(m))\n    res = dot(sort(real(eigvals(R)),rev=true),[1,-1,-1,-1])\n\n    return res\nend\n\n\"\"\"\nComputes the fidelity between two quantum states. By default, the Josza convention\nis used. The Uhlmann fidelity may be calculated by using the `kind` keyword argument\nwith the value `:uhlmann`.\n\"\"\"\nfunction fidelity(a::AbstractMatrix,b::AbstractMatrix;kind=:josza)\n    fu = trnorm(sqrt(a)*sqrt(b))\n    if kind==:josza\n        return fu^2\n    elseif kind==:uhlmann\n        return fu\n    end\nend\n\nfunction fidelity(a::AbstractVector,b::AbstractVector;kind=:josza)\n    return fidelity(projector(a),projector(b),kind=kind)\nend\n\nfunction fidelity(a::AbstractVector,b::AbstractMatrix;kind=:josza)\n    return fidelity(projector(a),b,kind=kind)\nend\n\nfunction fidelity(a::AbstractMatrix,b::AbstractVector;kind=:josza)\n    return fidelity(b,a,kind=kind)\nend\n\n\"\"\"\nComputes the average fidelity of the outputs of two quantum operations in the Liouville\nrepresentation. One of the operations is assumed to be a unitary quantum operation. The\nfidelity measure used is the one defined by Josza.\n\"\"\"\nfunction avgfidelity(liou,liou_uni;kind=:josza)\n    d = sqrt(size(liou,2))\n    f = (real(tr(liou*liou_uni'))+d)/(d^2+d)\n    return f\nend\n\n# TODO: entfidelity(liou,liou_uni)\n#       avg2entfidelity()\n#       ent2avgfidelity()\n\n# fidelity AbstractVector AbstractVector\n# fidelity AbstractVector AbstractMatrix\n# fidelity AbstractMatrix AbstractMatrix\n# superfidelity AbstractMatrix AbstractMatrix\n# subfidelity AbstractMatrix AbstractMatrix\n\n\"\"\"\nTests if a matrix is positive semidefinite within a given tolerance.\n\"\"\"\nfunction ispossemidef(m;tol=0.0)\n    evs = eigvals(m)\n    tol = tol==0.0 ? 1e2*eps(abs.(one(eltype(m)))) : tol\n    all(real(evs) .> -tol) && all(abs.(imag(evs)) .< tol)\nend\n\n\"\"\"\nDecompose a density matrix into Pauli operators with a given cutoff.\n\"\"\"\nfunction pauli_decomp(ρ::AbstractMatrix, cutoff=1e-3)\n    r = Dict{Pauli,Float64}()\n    d2 = size(ρ, 1)\n    d = round(Int, sqrt(d2))\n    for p in allpaulis(d)\n        val = real(tr(ρ * p)) / d2\n        if val > cutoff\n            r[p] = val\n        end\n    end\n    return r\nend\n", "meta": {"hexsha": "3dfe97c9844db43b9bd85bd60cf84bc2870af019", "size": 7729, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basics.jl", "max_stars_repo_name": "UnofficialJuliaMirror/QuantumInfo.jl-bedefb8d-ef00-5401-aa81-ae9c3f6f84cc", "max_stars_repo_head_hexsha": "f72846cce89e0a45a952d2290ba7472b4e506374", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basics.jl", "max_issues_repo_name": "UnofficialJuliaMirror/QuantumInfo.jl-bedefb8d-ef00-5401-aa81-ae9c3f6f84cc", "max_issues_repo_head_hexsha": "f72846cce89e0a45a952d2290ba7472b4e506374", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basics.jl", "max_forks_repo_name": "UnofficialJuliaMirror/QuantumInfo.jl-bedefb8d-ef00-5401-aa81-ae9c3f6f84cc", "max_forks_repo_head_hexsha": "f72846cce89e0a45a952d2290ba7472b4e506374", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7323420074, "max_line_length": 144, "alphanum_fraction": 0.6830120326, "num_tokens": 2234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7860823792008248}}
{"text": "# # Maximum Likelihood Estimation: The Normal Linear Model\n#\n#-\n#md # !!! tip\n#md #     This example is also available as a Jupyter notebook:\n#md #     [`maxlikenlm.ipynb`](@__NBVIEWER_ROOT_URL__examples/generated/maxlikenlm.ipynb)\n#-\n#\n# The following tutorial will introduce maximum likelihood estimation\n# in Julia for the normal linear model.\n#\n# The normal linear model (sometimes referred to as the OLS model) is\n# the workhorse of regression modeling and is utilized across a number\n# of diverse fields.  In this tutorial, we will utilize simulated data\n# to demonstrate how Julia can be used to recover the parameters of\n# interest.\n#\n# The first order of business is to use the `Optim` package\n# and also include the `NLSolversBase` routine:\n#\n\nusing Optim, NLSolversBase, Random\nusing LinearAlgebra: diag\nRandom.seed!(0);                            # Fix random seed generator for reproducibility\n\n#md # !!! tip\n#md #     Add Optim with the following command at the Julia command prompt:\n#md #     `Pkg.add(\"Optim\")`\n#\n# The first item that needs to be addressed is the data generating process or DGP.\n# The following code will produce data from a normal linear model:\n\n\nn = 500                             # Number of observations\nnvar = 2                            # Number of variables\nβ = ones(nvar) * 3.0                # True coefficients\nx = [ones(n) randn(n, nvar - 1)]    # X matrix of explanatory variables plus constant\nε = randn(n) * 0.5                  # Error variance\ny = x * β + ε;                      # Generate Data\n\n# In the above example, we have 500 observations, 2 explanatory\n# variables plus an intercept, an error variance equal to 0.5,\n# coefficients equal to 3.0, and all of these are subject to change by\n# the user. Since we know the true value of these parameters, we\n# should obtain these values when we maximize the likelihood function.\n#\n# The next step in our tutorial is to define a Julia function for the\n# likelihood function. The following function defines the likelihood\n# function for the normal linear model:\n\nfunction Log_Likelihood(X, Y, β, log_σ)\n    σ = exp(log_σ)\n    llike = -n/2*log(2π) - n/2* log(σ^2) - (sum((Y - X * β).^2) / (2σ^2))\n    llike = -llike\nend\n\n# The log likelihood function accepts 4 inputs: the matrix of\n# explanatory variables (X), the dependent variable (Y), the β's, and\n# the error varicance. Note that we exponentiate the error variance in\n# the second line of the code because the error variance cannot be\n# negative and we want to avoid this situation when maximizing the\n# likelihood.\n#\n# The next step in our tutorial is to optimize our function. We first\n# use the `TwiceDifferentiable` command in order to obtain the Hessian\n# matrix later on, which will be used to help form t-statistics:\n\nfunc = TwiceDifferentiable(vars -> Log_Likelihood(x, y, vars[1:nvar], vars[nvar + 1]),\n                           ones(nvar+1); autodiff=:forward);\n\n# The above statment accepts 4 inputs: the x matrix, the dependent\n# variable y, and a vector of β's and the error variance.  The\n# `vars[1:nvar]` is how we pass the vector of β's and the `vars[nvar +\n# 1]` is how we pass the error variance. You can think of this as a\n# vector of parameters with the first 2 being β's and the last one is\n# the error variance.\n#\n# The `ones(nvar+1)` are the starting values for the parameters and\n# the `autodiff=:forward` command performs forward mode automatic\n# differentiation.\n#\n# The actual optimization of the likelihood function is accomplished\n# with the following command:\n\nopt = optimize(func, ones(nvar+1))\n\n## Test the results                #src\nusing Test                    #src\n@test Optim.converged(opt)         #src\n@test Optim.g_residual(opt) < 1e-8 #src\n\n\n# The first input to the command is the function we wish to optimize\n# and the second input are the starting values.\n#\n# After a brief period of time, you should see output of the\n# optimization routine, with the parameter  estimates being very close\n# to our simulated values.\n#\n# The optimization routine stores several quantities and we can obtain\n# the maximim likelihood estimates with the following command:\n\nparameters = Optim.minimizer(opt)\n@test parameters ≈ [3.00279, 2.96455, -0.648693] atol=1e-5 #src\n\n# !!! Note\n#     Fieldnames for all of the quantities can be obtained with the following command:\n#     fieldnames(opt)\n#\n# Since we paramaterized our likelihood to use the exponentiated\n# value, we need to exponentiate it to get back to our original log\n# scale:\n\nparameters[nvar+1] = exp(parameters[nvar+1])\n\n# In order to obtain the correct Hessian matrix, we have to \"push\" the\n# actual parameter values that maximizes the likelihood function since\n# the `TwiceDifferentiable` command uses the next to last values to\n# calculate the Hessian:\n\nnumerical_hessian = hessian!(func,parameters)\n\n# We can now invert our Hessian matrix to obtain the variance-covariance matrix:\n\nvar_cov_matrix = inv(numerical_hessian)\n\n# In this example, we are only interested in the statistical\n# significance of the coefficient estimates so we obtain those with\n# the following command:\n\nβ = parameters[1:nvar]\n@test β ≈ [3.00279, 2.96455] atol=1e-5 #src\n\n# We now need to obtain those elements of the variance-covariance\n# matrix needed to obtain our t-statistics, and we can do this with\n# the following commands:\n\ntemp = diag(var_cov_matrix)\ntemp1 = temp[1:nvar]\n\n# The t-statistics are formed by dividing element-by-element the\n# coefficients by their standard errors, or the square root of the\n# diagonal elements of the variance-covariance matrix:\n\nt_stats = β./sqrt.(temp1)\n@test t_stats ≈ [39.7191, 39.9506] atol=1e-4 #src\n\n# From here, one may examine other statistics of interest using the\n# output from the optimization routine.\n\n#md # ## [Plain Program](@id maxlikenlm-plain-program)\n#md #\n#md # Below follows a version of the program without any comments.\n#md # The file is also available here: [maxlikenlm.jl](maxlikenlm.jl)\n#md #\n#md # ```julia\n#md # @__CODE__\n#md # ```\n", "meta": {"hexsha": "02f5a863b945f4d393b9a6a39d7d4c81e947e661", "size": 6025, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/maxlikenlm.jl", "max_stars_repo_name": "rcurtin/Optim.jl", "max_stars_repo_head_hexsha": "7223a64d32f9c88fae03f0ea49b48530fde2ed15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-12T11:27:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T11:27:21.000Z", "max_issues_repo_path": "docs/src/examples/maxlikenlm.jl", "max_issues_repo_name": "efmanu/Optim.jl", "max_issues_repo_head_hexsha": "887dee0eadaf392baf5031c5cf4468f474e015e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/src/examples/maxlikenlm.jl", "max_forks_repo_name": "efmanu/Optim.jl", "max_forks_repo_head_hexsha": "887dee0eadaf392baf5031c5cf4468f474e015e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.893081761, "max_line_length": 91, "alphanum_fraction": 0.7176763485, "num_tokens": 1536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7860823715617453}}
{"text": "\"\"\"\n    unitRandom3Cartesian(rng = MersenneTwister())\n\nReturns a unit vector pointing in a random direction in Cartesian coordinates.\n\"\"\"\nfunction unitRandom3Cartesian(rng = MersenneTwister())\n    θ = π*rand(rng)\n    ϕ = 2.0*π*rand(rng)\n    return Vector([\n        cos(ϕ)*sin(θ),\n        sin(ϕ)*sin(θ),\n        cos(θ)\n    ])\nend\n\nexport unitRandom3Cartesian\n\n\"\"\"\n    randbtw(a::T,b::T,rng=MersenneTwister()) where {T<:Real}\n\nGenerates a random number between a and b.\n\"\"\"\nfunction randbtw(a::T,b::T,rng=MersenneTwister()) where {T<:Real}\n    if a > b\n        return randbtw(b,a,rng)\n    end\n    return a+rand(rng)*(b-a)\nend\n\nexport randbtw\n\"\"\"\n    dist(n,func,domain,range,rng=MersenneTwister())\n\nGenerates n values following the distribution func in a given domain and range\n    - SLOW\n    - Can be used on any distribution function\n\"\"\"\nfunction dist(n,func,domain,range,rng=MersenneTwister())\n    out = zeros(n)\n    for i=1:n\n        val = 0.0\n        tryagain = true\n        while tryagain\n            xtest = randbtw(domain...,rng)\n            fxtest = abs(func(xtest))\n            if abs(randbtw(range...,rng)) < fxtest\n                val = xtest\n                tryagain = false\n            end\n        end\n        out[i] = val\n    end\n    return out\nend\n\nexport dist\n\n\"\"\"\n    PowerLaw\n\nSampler for a power law distribution\n\"\"\"\nstruct PowerLaw <: Sampleable{Univariate, Continuous}\n    α::Real\n    domain::Tuple{T,T} where {T<:Real}\nend\n\nexport PowerLaw\n\n\"\"\"\n    rand(rng::AbstractRNG,s::PowerLaw)\n\nGenerate one sample from a power law distribution\n\"\"\"\nfunction Base.rand(rng::AbstractRNG,s::PowerLaw)\n    ξ = rand(rng)\n    γ = 1.0-s.α\n    e0γ= s.domain[1]^(γ)\n    efγ = s.domain[2]^(γ)\n    out = (efγ-e0γ)*ξ+e0γ\n    return out^(1/γ)\nend\n\n\"\"\"\n    BrokenPowerLaw\n\nSampler for a broken power law distribution\n\"\"\"\nstruct BrokenPowerLaw <: Sampleable{Univariate, Continuous}\n    α::Array{T} where {T<:Real}\n    domain::Array{T} where {T<:Real}\n    function BrokenPowerLaw(α::Array{T}, domain::Array{T}) where {T<:Real}\n        @assert length(α)+1 == length(domain) \"Requires length(α) == length(domain)-1\"\n        bOrder = true\n        for i=1:(length(domain)-1)\n            bOrder *= domain[i] < domain[i+1]\n        end\n\n        @assert bOrder \"domain breaks must be in order\"\n        new(α, domain)\n    end\nend\n\nexport BrokenPowerLaw\n\nfunction afterIndex(val,vec)\n\tfor i=1:(length(vec)-1)\n\t\tcheck = vec[i] < val\n\t\tcheck *= val < vec[i+1]\n\t\tif check\n\t\t\treturn i\n\t\tend\n\tend\n\treturn 0\nend\n\n\"\"\"\n    rand(rng::AbstractRNG,s::BrokenPowerLaw)\n\nGenerate one sample from a broken power law distribution.\n\"\"\"\nfunction Base.rand(rng::AbstractRNG,s::BrokenPowerLaw)\n\tξ = rand(rng)\n\tγ = 1 .- s.α\n\n\n\tcx = ones(length(s.α))\n\tfor i = 1:(length(cx)-1)\n\t\tβ = s.α[i]/s.α[i+1]\n\t\tcx[i+1] = cx[i]^β*s.domain[i+1]^(β-1)\n\tend\n\tcx = map(/,cx,γ)\n\n\n\tarts = [\n\t\tbegin\n\t\t\t(s.domain[i+1]^γ[i] - s.domain[i]^γ[i])*cx[i]\n\t\tend for i=1:length(γ)\n\t\t\t]\n\n\tparts = vcat([0],arts)\n\tsumParts = cumsum(parts)\n\n\tnorm = sumParts[end]\n\tcnorm = ξ*norm\n\n\tsupIndex = afterIndex(cnorm,sumParts)\n\n\tout = cnorm - sumParts[supIndex]\n\tout /= cx[supIndex]\n\tout += s.domain[supIndex]^γ[supIndex]\n\tout = out^(1/γ[supIndex])\n\treturn out\nend\n", "meta": {"hexsha": "7ef6cddc54691320b3bd8c353ec0617e7c921610", "size": 3191, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Generator.jl", "max_stars_repo_name": "ProjectStarStuff/StarStuff.jl", "max_stars_repo_head_hexsha": "4c423580425b93f5f9d75956e76a5cdd307b8cfe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Generator.jl", "max_issues_repo_name": "ProjectStarStuff/StarStuff.jl", "max_issues_repo_head_hexsha": "4c423580425b93f5f9d75956e76a5cdd307b8cfe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Generator.jl", "max_forks_repo_name": "ProjectStarStuff/StarStuff.jl", "max_forks_repo_head_hexsha": "4c423580425b93f5f9d75956e76a5cdd307b8cfe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5870967742, "max_line_length": 86, "alphanum_fraction": 0.6148542777, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7860566490032599}}
{"text": "# Compute the finite difference approximation of ∂ₓy and ∂ₓₓy at node (i) on an even/uneven grid\nfunction fntdiff1d(x::StaticVector{N,T}, y::AbstractArray{T,1}, i::Int64) where {T<:Union{Float64, BigFloat}, N}\n    length(y) == N || throw(DimensionMismatch(\"x and y in fntdiff1d\"))\n\n    if 1 < i < N\n        ∂ₓy = /( y[i+1] - y[i-1] , x[i+1] - x[i-1] )\n        \n        ∂ₓₓy = /(+ *(x[i]   - x[i-1] , y[i+1])\n                 - *(x[i+1] - x[i-1] , y[i]  )\n                 + *(x[i+1] - x[i]   , y[i-1])\n                ,\n                 *(1/2            ,\n                   x[i+1] - x[i-1],\n                   x[i+1] - x[i]  ,\n                   x[i]   - x[i-1])\n                )\n    elseif 1 == i\n        ∂ₓy = /( y[i+1] - y[i] , x[i+1] - x[i] )\n        \n        ∂ₓₓy = /(+ *(x[i+1] - x[i]   , y[i+2])\n                 - *(x[i+2] - x[i]   , y[i+1])\n                 + *(x[i+2] - x[i+1] , y[i]  )\n                ,\n                 *(1/2            ,\n                   x[i+2] - x[i]  ,\n                   x[i+2] - x[i+1],\n                   x[i+1] - x[i]  )\n                )\n    elseif N == i\n        ∂ₓy = /( y[i] - y[i-1] , x[i] - x[i-1] )\n        \n        ∂ₓₓy = /(+ *(x[i-1] - x[i-2] , y[i]  )\n                 - *(x[i]   - x[i-2] , y[i-1])\n                 + *(x[i]   - x[i-1] , y[i-2])\n                ,\n                 *(1/2            ,\n                   x[i]   - x[i-2],\n                   x[i]   - x[i-1],\n                   x[i-1] - x[i-2])\n                )\n    else\n        throw(BoundsError(x, i))\n    end\n    \n    return ∂ₓy, ∂ₓₓy\nend \n\n\n\n# Compute the finite difference approximation of ∂ₓy and ∂ₓₓy at all nodes on an even/uneven grid\nfunction fntdiff1d!(∂ₓy::AbstractArray{T,1}, ∂ₓₓy::AbstractArray{T,1}, x::StaticVector{N,T}, y::AbstractArray{T,1}) where {T<:Union{Float64, BigFloat}, N}\n    length(y) == length(∂ₓy) == length(∂ₓₓy) == N || throw(DimensionMismatch(\"x, y, ∂ₓy, and ∂ₓₓy in fntdiff1d!\"))\n    \n    for i in 1:N\n        ∂ₓy[i], ∂ₓₓy[i] = fntdiff1d(x, y, i)\n    end\n    return nothing\nend\n", "meta": {"hexsha": "3082669f9578c74de8da8680660dbce2196b9928", "size": 2026, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FDapproxOnGrid.jl", "max_stars_repo_name": "cziFinEcon/HPCT", "max_stars_repo_head_hexsha": "3253a2f365cabffa9ca024e744bd2498f21b6da5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-22T18:52:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-22T18:52:24.000Z", "max_issues_repo_path": "src/FDapproxOnGrid.jl", "max_issues_repo_name": "cziFinEcon/GP2015_RepEx.jl", "max_issues_repo_head_hexsha": "3253a2f365cabffa9ca024e744bd2498f21b6da5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FDapproxOnGrid.jl", "max_forks_repo_name": "cziFinEcon/GP2015_RepEx.jl", "max_forks_repo_head_hexsha": "3253a2f365cabffa9ca024e744bd2498f21b6da5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3389830508, "max_line_length": 154, "alphanum_fraction": 0.3627838105, "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.786056645569198}}
{"text": "\nmodule HWfuncapp\n\n\tusing FastGaussQuadrature # to get chebyshevnodes\n\n\t# you dont' have to use PyPlot. I did much of it in PyPlot, hence\n\t# you will see me often qualify code with `PyPlot.plot` or so.\n\t#using PyPlot\n\tusing LinearAlgebra\n\timport ApproXD: getBasis, BSpline\n\tusing Distributions\n\tusing ApproxFun\n\tusing Plots\n\n\texport scalemap, unitmap, TT, ChebyT, q1, q2, q3, q7, runall\n\n\tChebyT(x,deg) = cos(acos(x)*deg)\n\tunitmap(x,lb,ub) = 2 .* (x .- lb) ./ (ub .- lb) .- 1\t#[a,b] -> [-1,1]\n\tscalemap(x,lb,ub) = 0.5 .* (lb .+ ub) .+ 0.5 .* (ub .- lb) .* x #scaling to [a,b]\n\n\tfunction TT(x,J,lb,ub)\n\t\tM = length(x)\n\t\tPhi = zeros(M,J)\n\t\tfor i in 1:M\n\t\t\tfor j in 1:J\n\t\t\t\tPhi[i,j] = ChebyT(unitmap(x[i],lb,ub),j-1)\n\t\t\tend\n\t\tend\n\t\treturn Phi\n\tend\n\n\n\t#function IPmatCh(n) #Chebyshev interpolation matrix\n\t#\tM = zeros(n,n)\n\t#\tfor i in 1:n\n\t#\t\tfor j in 1:n\n\t#\t\t\tM[i,j] = cos(((n - i + 0.5)*(j - 1)*(pi))/(n))\n\t#\t\tend\n\t#\tend\n\t#end\n\n\t#function cHat(n)\n\t#\treturn inv(IPmatCh(n)) * f(gch(-3,3,n))\n\t#end\n\t#f(x) = x .+ 2x.^2 - exp.(-x)\n\n\t#function gch(lb, ub, nnodes)\n\t#\treturn scalemap(gausschebyshev(nnodes)[1], lb, ub)\n\t#end\n\n\n\tfunction q1(n=15)\n\t\tlb = -3\n\t\tub = 3\n\t\tn_new = 100\n\t\tf(x) = x .+ 2x.^2 - exp.(-x)\n\t\tchNodes = scalemap(gausschebyshev(n)[1], lb, ub)\n\t\tcIP = inv(TT(chNodes,n,lb,ub))*f(chNodes)\n\t\tgrid = Vector(range(lb,length = n_new,stop = ub))\n\t\ttrue_new = f(grid)\n\t\tIP_new = (TT(grid,n,lb,ub))*cIP\n\t\terr = true_new .- IP_new\n\t\tp = Plots.plot(layout = 2, dpi = 400)\n\t\tPlots.plot!(p[1],grid,true_new,label = \"True\",lw = 1,linecolor = \"black\")\n\t\tPlots.plot!(p[1],grid,IP_new, label = \"IP Approx\", lw = 2,linestyle = :dot, linecolor = \"red\")\n\t\tPlots.plot!(p[2],grid,err, label = \"error\", lw = 1, linecolor = \"green\")\n\t\t# without using PyPlot, just erase the `PyPlot.` part\n\t\tPlots.savefig(p,joinpath(dirname(@__FILE__),\"..\",\"q1.png\"))\n\t\treturn Dict(:error=>maximum(abs,err))\n\tend\n\n\tfunction q2(b::Number = 4)\n\t\t@assert b > 0\n\t\t# use ApproxFun.jl to do the same:\n\t\tS = Chebyshev(-b..b)\n\t\tft = Fun(x -> x .+ 2x.^2 - exp.(-x),-b..b)\n\t\tn,m = 100,50\n\t\tgrid = Vector(range(-b, stop = b, length = n))\n\t\ttrue_v = ft.(grid)\n\t\tV = zeros(n,m)\n\t\tfor k = 1:m\n    \t\tV[:,k] = Fun(S,[zeros(k-1);1]).(grid)\n\t\tend\n\t\tfa = Fun(S,V\\true_v)\n\t\tapprox_v = fa.(grid)\n\t\terr = approx_v .- true_v\n\t\tp = Plots.plot(layout = 2, dpi = 400)\n\t\tPlots.plot!(p[1],grid,true_v,label = \"True\",lw = 1,linecolor = \"black\")\n\t\tPlots.plot!(p[1],grid,approx_v, label = \"IP Approx\", lw = 2,linestyle = :dot, linecolor = \"red\")\n\t\tPlots.plot!(p[2],grid,err, label = \"error\", lw = 1, linecolor = \"green\")\n\t\tPlots.savefig(p,joinpath(dirname(@__FILE__),\"..\",\"q2.png\"))\n\tend\n\n\tfunction q3(b::Number = 10)\n\t\t@assert b > 0\n\t\tx = Fun(identity,-b..b)\n\t\tf = sin(x^2)\n\t\tg = cos(x)\n\t\th = f - g\n\t\trh = roots(h)\n\t\tp = Plots.plot(h, label = \"h(x)\", dpi = 400, lw = 1, linecolor = \"black\")\n\t\tPlots.scatter!(p,rh,h.(rh), label = \"roots of h(x)\", markercolor = \"green\", markersize = 5)\n\t\tPlots.savefig(p,joinpath(dirname(@__FILE__),\"..\",\"q3.png\"))\n\t\ty = Fun(identity,-10..0)\n\t\thh = sin(y^2) - cos(y)\n\t\thh_int1 = cumsum(hh)\n\t\thh_int = hh_int1 + hh(-10)\n\t\tintegral = ApproxFun.norm(hh_int(0) - hh_int(-10))\n\t\treturn (p,integral)\n\tend\n\n\t# optinal\n\tfunction q4()\n\n\t\treturn fig\n\tend\n\n\n\t# I found having those useful for q5\n\tmutable struct ChebyType\n\t\tf::Function # fuction to approximate\n\t\tnodes::Union{Vector,LinRange} # evaluation points\n\t\tbasis::Matrix # basis evaluated at nodes\n\t\tcoefs::Vector # estimated coefficients\n\n\t\tdeg::Int \t# degree of chebypolynomial\n\t\tlb::Float64 # bounds\n\t\tub::Float64\n\n\t\t# constructor\n\t\tfunction ChebyType(_nodes::Union{Vector,LinRange},_deg,_lb,_ub,_f::Function)\n\t\t\tn = length(_nodes)\n\t\t\ty = _f(_nodes)\n\t\t\t_basis = Float64[ChebyT(unitmap(_nodes[i],_lb,_ub),j) for i=1:n,j=0:_deg]\n\t\t\t_coefs = _basis \\ y  # type `?\\` to find out more about the backslash operator. depending the args given, it performs a different operation\n\t\t\t# create a ChebyComparer with those values\n\t\t\tnew(_f,_nodes,_basis,_coefs,_deg,_lb,_ub)\n\t\tend\n\tend\n\n\t# function to predict points using info stored in ChebyType\n\tfunction predict(Ch::ChebyType,x_new)\n\n\t\ttrue_new = Ch.f(x_new)\n\t\tbasis_new = Float64[ChebyT(unitmap(x_new[i],Ch.lb,Ch.ub),j) for i=1:length(x_new),j=0:Ch.deg]\n\t\tbasis_nodes = Float64[ChebyT(unitmap(Ch.nodes[i],Ch.lb,Ch.ub),j) for i=1:length(Ch.nodes),j=0:Ch.deg]\n\t\tpreds = basis_new * Ch.coefs\n\t\tpreds_nodes = basis_nodes * Ch.coefs\n\n\t\treturn Dict(\"x\"=> x_new,\"truth\"=>true_new, \"preds\"=>preds, \"preds_nodes\" => preds_nodes)\n\tend\n\n\tfunction q5(deg=(5,9,15),lb=-1.0,ub=1.0)\n\n\t\trunge(x) = 1.0 ./ (1 .+ 25 .* x.^2)\n\n\n\t\tPyPlot.savefig(joinpath(dirname(@__FILE__),\"..\",\"q5.png\"))\n\n\tend\n\n\n\n\tfunction q6()\n\n\t\t# compare 2 knot vectors with runge's function\n\n\t\tPyPlot.savefig(joinpath(dirname(@__FILE__),\"..\",\"q6.png\"))\n\n\tend\n\n\tfunction q7(pr = 0.025)\n\t\tdeg = 3\n\t\tlb = -1\n\t\tub = 1\n\t\tnk = 13\n\t\tnev = 65\n\t\tf(x) = (abs.(x)).^0.5\n\t\tbs1 = BSpline(nk,deg,lb,ub)\n\t\tknots2 = vcat(range(lb,stop = -pr, length = 5),0,0,0,range(pr,stop = ub, length = 5))\n\t\tbs2 = BSpline(knots2,deg)\n\t\teval = Vector(range(lb,stop = ub, length = nev))\n\t\tc1 = getBasis(eval,bs1) \\ f(eval)\n\t\tc2 = getBasis(eval,bs2) \\ f(eval)\n\t\tgrid = Vector(range(lb, stop = ub, length = 1000))\n\t\ttr = f(grid)\n\t\ta1 = getBasis(grid, bs1) * c1\n\t\ta2 = getBasis(grid, bs2) * c2\n\t\terr1 = a1 .- tr\n\t\terr2 = a2 .- tr\n\t\tp = Plots.plot(layout = 3, dpi = 400)\n\t\tPlots.plot!(p[1],grid,tr,label = \"True\",lw = 1.5,linecolor = \"black\")\n\t\tPlots.plot!(p[2],grid,a1, label = \"Approx1\", lw = 1.5, linecolor = \"blue\")\n\t\tPlots.plot!(p[2],grid,a2, label = \"Approx2\", lw = 1.5, linecolor = \"red\")\n\t\tPlots.plot!(p[3],grid,err1, label = \"error1\", lw = 1.5, linecolor = \"blue\")\n\t\tPlots.plot!(p[3],grid,err2, label = \"error2\", lw = 1.5, linecolor = \"red\")\n\t\tPlots.savefig(p,joinpath(dirname(@__FILE__),\"..\",\"q7.png\"))\n\t\treturn (p,maximum(abs,err2))\n\tend\n\n\t#function q7bis()\n\t#\tG = Vector(range(0.001, stop = 0.2, length = 1000))\n\t#\treturn Plots.plot(G,q7.(G))\n\t#end\n\n\n\t# function to run all questions\n\tfunction runall()\n\t\t@info(\"running all questions of HW-funcapprox:\")\n\t\tq1(15)\n\t\tq2(3)\n\t\tq3(10)\n\t\t#q4()\n\t\t#q5()\n\t\t#q6()\n\t\tq7()\n\tend\n\n\n\nend # module\n", "meta": {"hexsha": "23984af9a498dd9b0f2e460cbda937c2dd42e055", "size": 6124, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HWfuncapp.jl", "max_stars_repo_name": "DanielGy95/HWfuncapp.jl", "max_stars_repo_head_hexsha": "ea76dda905fc2572a690177f98bd7b3323cab8a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HWfuncapp.jl", "max_issues_repo_name": "DanielGy95/HWfuncapp.jl", "max_issues_repo_head_hexsha": "ea76dda905fc2572a690177f98bd7b3323cab8a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HWfuncapp.jl", "max_forks_repo_name": "DanielGy95/HWfuncapp.jl", "max_forks_repo_head_hexsha": "ea76dda905fc2572a690177f98bd7b3323cab8a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5855855856, "max_line_length": 142, "alphanum_fraction": 0.6205094709, "num_tokens": 2408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7860143578629459}}
{"text": "\"\"\"\nThe Kernels module defines a collection of kernels to avoid namespace collisions:\n\n- `biweight`\n- `cosine`\n- `epanechnikov`\n- `triangular`\n- `tricube`\n- `triweight`\n- `uniform`\n- `gaussian`\n- `logistic`\n\"\"\"\nmodule Kernels\ninrange(u::Float64) = abs(u) <= 1.0\n\nbiweight(u::Float64)        = inrange(u) ? (1.0 - u ^ 2) ^ 2 : 0.0\ncosine(u::Float64)          = inrange(u) ? cos(0.5 * π * u) : 0.0\nepanechnikov(u::Float64)    = inrange(u) ? 1.0 - u ^ 2 : 0.0\ntriangular(u::Float64)      = inrange(u) ? 1.0 - abs(u) : 0.0\ntricube(u::Float64)         = inrange(u) ? (1.0 - abs(u) ^ 3) ^ 3 : 0.0\ntriweight(u::Float64)       = inrange(u) ? (1.0 - u ^ 2) ^ 3 : 0.0\nuniform(u::Float64)         = inrange(u) ? 0.5 : 0.0\n\ngaussian(u::Float64) = exp(-0.5 * u ^ 2)\nlogistic(u::Float64) = 1.0 / (exp(u) + 2.0 + exp(-u))\nend\n", "meta": {"hexsha": "1dc39755e8356f658f0f7ef9d0da104e6aa35976", "size": 811, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/AverageShiftedHistograms.jl-77b51b56-6f8f-5c3a-9cb4-d71f9594ea6e", "max_stars_repo_head_hexsha": "4e12bd778d15a92330e00e73000d607904c9d006", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/AverageShiftedHistograms.jl-77b51b56-6f8f-5c3a-9cb4-d71f9594ea6e", "max_issues_repo_head_hexsha": "4e12bd778d15a92330e00e73000d607904c9d006", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/AverageShiftedHistograms.jl-77b51b56-6f8f-5c3a-9cb4-d71f9594ea6e", "max_forks_repo_head_hexsha": "4e12bd778d15a92330e00e73000d607904c9d006", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9642857143, "max_line_length": 81, "alphanum_fraction": 0.5598027127, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.8354835432479663, "lm_q1q2_score": 0.7860143545490395}}
{"text": "#!/usr/bin/julia\n\n# Trizen\n# 09 November 2016\n# https://github.com/trizen\n\n# A simple implementation of Euler's totient function.\n\n# See also:\n#   https://www.youtube.com/watch?v=fq6SXByItUI\n#   https://en.wikipedia.org/wiki/Euler%27s_totient_function\n\nusing Primes\n\nfunction Φ(n::Int64)\n\n    for p in keys(factor(n))\n        n -= div(n, p)\n    end\n\n    n\nend\n\n# Φ(240) = Φ(2^4 * 3^1 * 5^1)\n# Φ(240) = (2^4 - 2^3) * (3^1 - 3^0) * (5^1 - 5^0)\n# Φ(240) = 64\n\nprintln(Φ(240))\n", "meta": {"hexsha": "54f98961060f9f7cc38cceb53ff7fe35b38c9f55", "size": 473, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Math/euler_totient_function.jl", "max_stars_repo_name": "trizen/julia-scripts", "max_stars_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-03-22T09:38:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T21:38:31.000Z", "max_issues_repo_path": "Math/euler_totient_function.jl", "max_issues_repo_name": "trizen/julia-scripts", "max_issues_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/euler_totient_function.jl", "max_forks_repo_name": "trizen/julia-scripts", "max_forks_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.3103448276, "max_line_length": 60, "alphanum_fraction": 0.6025369979, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7860143429876187}}
{"text": "#    Problem : GROUP A\n#    *********\n#\t A nondiagonal quartic test problem.\n#\t \n#\t This problem has an arrow-head type Hessian with a tridiagonal\n#    central part and a border of width 1.\n#    The Hessian is singular at the solution.\n#\n#    Origonal SIF Source:\n#    A.R. Conn, N.I.M. Gould, M. Lescrenier and Ph.L. Toint,\n#    \"Performance of a multi-frontal scheme for partially separable\n#    optimization\"\n#    Report 88/4, Dept of Mathematics, FUNDP (Namur, B), 1988.\n#\n#    NONDQUAR.SIF classification OUR2-AN-V-0\n#\n#    Number of variables is variable\n#\n# Daniel Henderson, 08/2021  \n\nf = (x) -> begin\n\tn  = lastindex(x)\n\tfx =  (x[1]-x[2])^2 + (x[n-1] - x[n])^2\n\tfor i in 1:n-2\n      \tfx += (x[i]+x[i+1]+x[n])^4\n\tend\n    return fx\nend\n\ng! = (g, x) -> begin\n\tn    = lastindex(x)\n\tg[1] = 2(x[1] - x[2]) + 4(x[1] + x[2] + x[n])^3\n\tg[2] = -2(x[1] - x[2]) + 4(x[1] + x[2] + x[n])^3 + 4(x[2] + x[3] + x[n])^3\n\tgn   = 4(x[1] + x[2] + x[n])^3 +  4(x[2] + x[3] + x[n])^3\n\tfor i in 3:n-2\n\t\tg[i] += 4(x[i] + x[i+1] + x[n])^3 + 4(x[i+1] + x[i+2] + x[n])^3\n\t\tgn   += 4(x[i] + x[i+1] + x[n])^3\n\tend\n\tg[n-1] = 2(x[n-1] - x[n]) + 4(x[n-2] + x[n-1] + x[n])^3\n\tg[n]   = gn - 2(x[n-1] - x[n])\n\treturn g\nend\n\nfg! = (g, x) -> begin\n\tn    = lastindex(x)\n\tfx   =  (x[1]-x[2])^2 + (x[n-1] - x[n])^2 + (x[1]+x[2]+x[n])^4 + (x[2]+x[3]+x[n])^4\n\tg[1] = 2(x[1] - x[2]) + 4(x[1] + x[2] + x[n])^3 \n\tg[2] = -2(x[1] - x[2]) + 4(x[1] + x[2] + x[n])^3 + 4(x[2] + x[3] + x[n])^3\n\tgn   = 4(x[1] + x[2] + x[n])^3 +  4(x[2] + x[3] + x[n])^3\n\tfor i in 3:n-2\n\t\tg[i] += 4(x[i] + x[i+1] + x[n])^3 + 4(x[i+1] + x[i+2] + x[n])^3\n\t\tgn   += 4(x[i] + x[i+1] + x[n])^3\n\t\tfx += (x[i]+x[i+1]+x[n])^4\n\tend\n\tg[n-1] = 2(x[n-1] - x[n]) + 4(x[n-2] + x[n-1] + x[n])^3\n\tg[n]   = gn - 2(x[n-1] - x[n])\n\treturn fx, g\nend\n\ninit = (n::Int=5000) -> begin\n\tmod(n, 2) > 0 && @warn \"NONDQUAR: number of variables must be even\" \n\tq = max(1, div(n, 2))\n\tn = 2q\n\tx0 = [j % 2 == 0 ? -1.0 : 1.0 for j in 1:n]\n    return n, x0\nend\n\n#TestSet[\"NONDQUAR\"] = UncProgram(\"NONDQUAR\", f, g!, fg!, init)\n", "meta": {"hexsha": "b712722b77056514202316be2445d5cfec3d767d", "size": 2033, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/programs/NONDQUAR.jl", "max_stars_repo_name": "danphenderson/UncNLPrograms.jl", "max_stars_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/programs/NONDQUAR.jl", "max_issues_repo_name": "danphenderson/UncNLPrograms.jl", "max_issues_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/programs/NONDQUAR.jl", "max_forks_repo_name": "danphenderson/UncNLPrograms.jl", "max_forks_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4637681159, "max_line_length": 84, "alphanum_fraction": 0.4731923266, "num_tokens": 1030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.7860143341256987}}
{"text": "#############################################################################\n# lambdamin_max.jl\n# Handles maximum and minimum eigenvalue of a symmetric positive definite matrix\n# (and imposes the constraint that its argument be PSD)\n# All expressions and atoms are subtypes of AbstractExpr.\n# Please read expressions.jl first.\n#############################################################################\nexport lambdamax, lambdamin\n\n### Lambda max\n\nstruct LambdaMaxAtom <: AbstractExpr\n    head::Symbol\n    id_hash::UInt64\n    children::Tuple{AbstractExpr}\n    size::Tuple{Int, Int}\n\n    function LambdaMaxAtom(x::AbstractExpr)\n        children = (x,)\n        m, n = size(x)\n        if m == n\n            return new(:lambdamax, hash(children), children, (1, 1))\n        else\n            error(\"lambdamax can only be applied to a square matrix.\")\n        end\n    end\nend\n\nfunction sign(x::LambdaMaxAtom)\n    return Positive()\nend\n\nfunction monotonicity(x::LambdaMaxAtom)\n    return (Nondecreasing(),)\nend\n\nfunction curvature(x::LambdaMaxAtom)\n    return ConvexVexity()\nend\n\nfunction evaluate(x::LambdaMaxAtom)\n    eigvals(evaluate(x.children[1]))[end]\nend\n\nlambdamax(x::AbstractExpr) = LambdaMaxAtom(x)\n\n# Create the equivalent conic problem:\n#   minimize t\n#   subject to\n#            tI - A is positive semidefinite\n#            A      is positive semidefinite\nfunction conic_form!(x::LambdaMaxAtom, unique_conic_forms)\n    if !has_conic_form(unique_conic_forms, x)\n        A = x.children[1]\n        m, n = size(A)\n        t = Variable()\n        p = minimize(t, t*Matrix(1.0I, n, n) - A ⪰ 0)\n        cache_conic_form!(unique_conic_forms, x, p)\n    end\n    return get_conic_form(unique_conic_forms, x)\nend\n\n### Lambda min\n\nstruct LambdaMinAtom <: AbstractExpr\n    head::Symbol\n    id_hash::UInt64\n    children::Tuple{AbstractExpr}\n    size::Tuple{Int, Int}\n\n    function LambdaMinAtom(x::AbstractExpr)\n        children = (x,)\n        m, n = size(x)\n        if m == n\n            return new(:lambdamin, hash(children), children, (1,1))\n        else\n            error(\"lambdamin can only be applied to a square matrix.\")\n        end\n    end\nend\n\nfunction sign(x::LambdaMinAtom)\n    return Positive()\nend\n\nfunction monotonicity(x::LambdaMinAtom)\n    return (Nondecreasing(),)\nend\n\nfunction curvature(x::LambdaMinAtom)\n    return ConcaveVexity()\nend\n\nfunction evaluate(x::LambdaMinAtom)\n    eigvals(evaluate(x.children[1]))[1]\nend\n\nlambdamin(x::AbstractExpr) = LambdaMinAtom(x)\n\n# Create the equivalent conic problem:\n#   maximize t\n#   subject to\n#            A - tI is positive semidefinite\n#            A      is positive semidefinite\nfunction conic_form!(x::LambdaMinAtom, unique_conic_forms)\n    if !has_conic_form(unique_conic_forms, x)\n        A = x.children[1]\n        m, n = size(A)\n        t = Variable()\n        p = maximize(t, A - t*Matrix(1.0I, n, n) ⪰ 0)\n        cache_conic_form!(unique_conic_forms, x, p)\n    end\n    return get_conic_form(unique_conic_forms, x)\nend\n", "meta": {"hexsha": "1f46f6d22183799ddf3fb5de97853ccaa952c16a", "size": 2980, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/atoms/sdp_cone/lambda_min_max.jl", "max_stars_repo_name": "ranocha/Convex.jl", "max_stars_repo_head_hexsha": "ee58743611756e5cbb104682686031ab8d0feec4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-10-10T16:38:59.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-13T06:35:58.000Z", "max_issues_repo_path": "src/atoms/sdp_cone/lambda_min_max.jl", "max_issues_repo_name": "ranocha/Convex.jl", "max_issues_repo_head_hexsha": "ee58743611756e5cbb104682686031ab8d0feec4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/atoms/sdp_cone/lambda_min_max.jl", "max_forks_repo_name": "ranocha/Convex.jl", "max_forks_repo_head_hexsha": "ee58743611756e5cbb104682686031ab8d0feec4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-10-19T20:58:10.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-20T01:12:01.000Z", "avg_line_length": 25.9130434783, "max_line_length": 80, "alphanum_fraction": 0.6234899329, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813476288299, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7859974771672897}}
{"text": "\"\"\"\n    parameter(sma, ecc)\n\nGet the parameter (semi-latus rectum) of the orbit.\n\"\"\"\nparameter(sma, ecc) = sma * (1 - ecc * ecc)\n\n\"\"\"\n    periapsis_radius(sma, ecc)\n\nGet the smallest radius along the orbit.\n\"\"\"\nperiapsis_radius(sma, ecc) = sma * (1 - ecc)\n\n\"\"\"\n    apoapsis_radius(sma, ecc)\n\nGet the largest radius along the orbit.\n\"\"\"\napoapsis_radius(sma, ecc) = sma * (1 + ecc)\n\n\"\"\"\n    radius(sma, ecc, ta)\n\nCompute the radius of the orbit at the specified true anomaly\n\"\"\"\nradius(sma, ecc, ta) = parameter(sma, ecc) / (1 + ecc * cos(ta))\n\n\"\"\"\n    true_longitude(raan, aop, ta)\n\nCompute the true longitude\n\"\"\"\ntrue_longitude(raan, aop, ta) = raan + aop + ta\n\n\"\"\"\n    isclosed(ecc)\n\nReturn true if the two-body orbit is closed, false otherwise.\n\"\"\"\nisclosed(ecc) = ecc < 1\n\n\"\"\"\n    isopen(ecc)\n\nReturn true if the two-body orbit is open, false otherwise.\n\"\"\"\nisopen(ecc) = !isclosed(ecc)\n\n\"\"\"\n    iscircular(ecc)\n\nReturn true if the two-body orbit is circular (``e = 0``), false otherwise.\n\"\"\"\niscircular(ecc) = ecc == 0\n\n\"\"\"\n    iselliptical(ecc)\n\nReturn true if the two-body orbit is elliptical (``e < 1``), false otherwise.\n\"\"\"\niselliptical(ecc) = ecc < 1\n\n\"\"\"\n    isparabolic(ecc)\n\nReturn true if the two-body orbit is parabolic (``e = 1``), false otherwise.\n\"\"\"\nisparabolic(ecc) = ecc == 1\n\n\"\"\"\n    ishyperbolic(ecc)\n\nReturn true if the two-body orbit is hyperbolic (``e > 1``), false otherwise.\n\"\"\"\nishyperbolic(ecc) = ecc > 1\n\n# Defining this allows us to write f(x) rather than f(x) _and_ f(cb::CelestialBody)\n_GM(x) = gravitational_parameter(x)\n_GM(x::Real) = x\n\n\"\"\"\n    circular_velocity(gm, r)\n    circular_velocity(cb::CelestialBody, r)\n\nCompute the circular velocity of a two-body orbit with circular radius `r`.\n\"\"\"\ncircular_velocity(gm, r) = sqrt(_GM(gm) / r)\n\n\"\"\"\n    mean_motion(gm, sma)\n    mean_motion(cb::CelestialBody, sma)\n\nCompute the mean motion of an orbit with semi-major axis, `sma`.\n\"\"\"\nmean_motion(gm, sma) = circular_velocity(_GM(gm), sma) / sma\n\n\"\"\"\n    period(gm, sma)\n    period(cb::CelestialBody, sma)\n\nCompute the period of an orbit with semi-major axis, `sma`.\n\"\"\"\nperiod(gm, sma) = 2π / mean_motion(_GM(gm), sma)\n\n\"\"\"\n    angular_momentum(gm, sma, ecc)\n    angular_momentum(cb::CelestialBody, sma, ecc)\n\nCompute the angular momentum of the two-body orbit.\n\"\"\"\nangular_momentum(gm, sma, ecc) = sqrt(_GM(gm) * parameter(sma, ecc))\n\n\"\"\"\n    flight_path_angle(sma, ecc, ta)\n\nCompute the angle between the velocity vector and the local horizon.\n\nA positive flight path angle corresponds to a negative rotation from the local horizon to\nthe velocity vector around the angular momentum.\n\"\"\"\nfunction flight_path_angle(sma, ecc, ta)\n    r = radius(sma, ecc, ta)\n    return acos(sqrt(sma^2 * (1 - ecc^2) / (r * (2sma - r))))\nend\n\ninclude(\"elements.jl\")\ninclude(\"keplerian.jl\")\n", "meta": {"hexsha": "a8c5fccc35b5bd308d469cd5099425139f703f35", "size": 2807, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/twobody/twobody.jl", "max_stars_repo_name": "rjpower4/Pat.jl", "max_stars_repo_head_hexsha": "79893b6f76b24db89ae6f06524a759c8210c8515", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/twobody/twobody.jl", "max_issues_repo_name": "rjpower4/Pat.jl", "max_issues_repo_head_hexsha": "79893b6f76b24db89ae6f06524a759c8210c8515", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-11-22T19:39:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T06:30:29.000Z", "max_forks_repo_path": "src/twobody/twobody.jl", "max_forks_repo_name": "rjpower4/Pat.jl", "max_forks_repo_head_hexsha": "79893b6f76b24db89ae6f06524a759c8210c8515", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7596899225, "max_line_length": 89, "alphanum_fraction": 0.669754186, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7859620945647773}}
{"text": "#### Lagrange Interpolation Formula\n\nusing DelimitedFiles\nusing LinearAlgebra\nusing Plots; pyplot()\n\nto = time()\n\nfunction lagrange_interpolate(X,Y,t)\n    C = ones(length(X))\n    d = 0.0\n    for i = 1:length(X)\n        for j = [1:i-1;i+1:length(X)]\n            C[i] = C[i]*(t-X[j])/(X[i]-X[j])\n        end\n        d = d + Y[i]*C[i]\n    end\n    return d\nend \n\nfunction lagrange_interpolate_plus(X,Y,t)\n    idxs = eachindex(X)\n    sum(Y[i] * prod((t-X[j])/(X[i]-X[j]) for j in idxs if j != i) for i in idxs)\nend\n\nA = readdlm(\"Data/dataSim.dat\")\nX = view(A,:,1)\nY = view(A,:,2)\nT = 1.0:0.1:2.0\nU = [lagrange_interpolate_plus(X, Y, t) for t in T]\n\ntd = time() - to\nprintln(\"The time interval is $td s.\")\n\nplot(fontfamily=(\"Serif\"),dpi=512)\nplot!(X,Y,color=\"#32B432\",marker=(:circle,10,Plots.stroke(:white)),label=\"Source\")\nplot!(T,U,color=\"#00B4DC\",marker=(:cross,10,Plots.stroke(:white)),label=\"Foreast\")\n\nsavefig(\"L.pdf\")\n\n#### Shanks Transform\n\nusing DelimitedFiles\nusing LinearAlgebra\nusing Plots; pyplot()\n\n\"\"\"\nL[i] = (S[i]^2-S[i-1]*S[i+1])/(2*S[i]-S[i-1]-S[i+1])\n\"\"\"\n\nA = readdlm(\"Data/Tr.dat\")\nX = view(A,:,1)\nY = view(A,:,2)\n\ncount = length(X)\n\nL1 = ones(count)\nfor i in range(1; stop = count)\n    if i in 2:count-1\n        L1[i] = (Y[i]^2-Y[i-1]*Y[i+1])/(2*Y[i]-Y[i-1]-Y[i+1])\n    else\n        L1[i] = 0\n    end\n    i = i + 1\nend\n\nL2 = ones(count)\nfor i in range(1; stop = count)\n    if i in 2:count-1\n        L2[i] = (L1[i]^2-L1[i-1]*L1[i+1])/(2*L1[i]-L1[i-1]-L1[i+1])\n    else\n        L2[i] = 0\n    end\n    i = i + 1\nend\n\nL3 = ones(count)\nfor i in range(1; stop = count)\n    if i in 2:count-1\n        L3[i] = (L2[i]^2-L2[i-1]*L2[i+1])/(2*L2[i]-L2[i-1]-L2[i+1])\n    else\n        L3[i] = 0\n    end\n    i = i + 1\nend\n\nL4 = ones(count)\nfor i in range(1; stop = count)\n    if i in 2:count-1\n        L4[i] = (L3[i]^2-L3[i-1]*L3[i+1])/(2*L3[i]-L3[i-1]-L3[i+1])\n    else\n        L4[i] = 0\n    end\n    i = i + 1\nend\n\nplot(fontfamily=(\"Serif\"),dpi=512)\nscatter!(X,Y, color=\"#B4B4B4\",marker=(:circle,10,Plots.stroke(:white)),label=\"Source\")\nplot!(X[2:count-1],L1[2:count-1],color=\"#FF1E14\",label=\"Foreast\")\nplot!(X[3:count-2],L2[3:count-2],color=\"#FFC814\",label=\"Foreast\")\nplot!(X[4:count-3],L3[4:count-3],color=\"#1978F0\",label=\"Foreast\")\nplot!(X[5:count-4],L4[5:count-4],color=\"#A064DC\",label=\"Foreast\")\n\n#### Richardson Extrapolation\n\n\"\"\"\nSn = 1 + 1/2^2 + 1/3^2 + 1/4^2 + ... + 1/n^2\nlim(n->∞)Sn = π^2/6 ≈ 1.6449340668482264\n\nR1(n) = ((n+1)*S(n+1)-n*S(n))/factorial(1)\nR2(n) = ((n+2)^2*S(n+1)-2*(n+1)^2*S(n+1)+n^2*S(n))/factorial(2)\n……\n\"\"\"\n\nto = time()\n\nA = readdlm(\"Data/Td.dat\")\nX = view(A,:,1)\nY = view(A,:,2)\n\ncount = length(X)\n\nfunction RE1(Y)\n    R1 = ones(count)\n    for i in range(1; stop=count)\n        if i in 1:count - 1\n            R1[i] = ((i+1)*Y[i+1]-i*Y[i])/factorial(1)\n        else\n            R1[i] = 0\n        end\n        i = i + 1\n    end\n    return R1\nend\n\nfunction RE2(Y)\n    R2 = ones(count)\n    for i in range(1; stop=count)\n        if i in 1:count - 2\n            R2[i] = ((i+2)^2*Y[i+2]-2*(i+1)^2*Y[i+1]+i^2*Y[i])/factorial(2)\n        else\n            R2[i] = 0\n        end\n        i = i + 1\n    end\n    return R2\nend\n\nU1 = RE1(Y)\nU2 = RE2(Y)\n\ntd = time() - to\nprintln(\"The time interval is $td s.\")\n\nplot(fontfamily=(\"Serif\"),dpi=512)\nscatter!(X,Y, color=\"#B4B4B4\",marker=(:circle,10,Plots.stroke(:white)),label=\"Source\")\nplot!(X[1:count-1],U1[1:count-1],color=\"#FF1E14\",label=\"Foreast\")\nplot!(X[1:count-2],U2[1:count-2],color=\"#1978F0\",label=\"Foreast\")\n\nsavefig(\"R.pdf\")\n", "meta": {"hexsha": "765e6e94dd0a2fa19f8d28a482b28bec7f7a7f75", "size": 3498, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Test/Julia.jl", "max_stars_repo_name": "ConAntares/Photonica", "max_stars_repo_head_hexsha": "f8e61b6927ea237996528298c45c631ce810494a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Test/Julia.jl", "max_issues_repo_name": "ConAntares/Photonica", "max_issues_repo_head_hexsha": "f8e61b6927ea237996528298c45c631ce810494a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Test/Julia.jl", "max_forks_repo_name": "ConAntares/Photonica", "max_forks_repo_head_hexsha": "f8e61b6927ea237996528298c45c631ce810494a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7267080745, "max_line_length": 86, "alphanum_fraction": 0.5451686678, "num_tokens": 1459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802364, "lm_q2_score": 0.8289388083214155, "lm_q1q2_score": 0.7859620914086834}}
{"text": "module ReferenceStates\n\nusing Polynomials\nusing Unitful, UnitfulAtomic\nusing ..HKQM\n\n\nexport HarmonicEigenstate,\n       harmonic_state\n\nfunction hermite_polynomial(ν)\n    if ν == 0\n        return Polynomial([1])\n    elseif ν == 1\n        return Polynomial([0, 2])\n    else\n        p1 = Polynomial([0,2])*hermite_polynomial(ν-1)\n        p2 = 2(ν-1)*hermite_polynomial(ν-2)\n        return p1 - p2\n    end\nend\n\n\nstruct HarmonicEigenstate\n    ν::Int\n    α::Float64\n    ω::Float64\n    N::Float64\n    hp::Polynomial{Int}\n    function HarmonicEigenstate(ν::Int; ω=1)\n        α = 1/sqrt(ω)\n        hp = hermite_polynomial(ν)\n        N = (2^ν*factorial(ν)*sqrt(π)*α)^(-1//2)\n        new(ν, α, ω, N, hp)\n    end\nend\n\nfunction (HE::HarmonicEigenstate)(v::AbstractVector)\n    return prod(HE, v)\nend\n\nfunction (HE::HarmonicEigenstate)(x::Real)\n    y = x/HE.α\n    return HE.N*HE.hp(y)*exp(-0.5*y^2)\nend\n\nfunction harmonic_state(ceg, hx, hy=hx, hz=hx)\n    r = position_operator(ceg)\n    ψ = map(r-> hx(r[1])*hy(r[2])*hz(r[3]), ceg)\n    return QuantumState(ceg, ψ)\nend\n\nfunction energy(he::HarmonicEigenstate)\n    return he.ω*(he.ν+0.5)*u\"hartree\"\nend\n\n\nend  # module\n", "meta": {"hexsha": "2e81339ad5b5a808280c6e6dd6826bb9943d54e6", "size": 1152, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/submodules/ReferenceStates.jl", "max_stars_repo_name": "tjjarvinen/HKQM.jl", "max_stars_repo_head_hexsha": "4e2f4cf58aae6afee54ebac62b3656a26b8641e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-08-13T01:28:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T23:14:36.000Z", "max_issues_repo_path": "src/submodules/ReferenceStates.jl", "max_issues_repo_name": "tjjarvinen/HKQM.jl", "max_issues_repo_head_hexsha": "4e2f4cf58aae6afee54ebac62b3656a26b8641e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2021-01-14T17:41:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T12:07:42.000Z", "max_forks_repo_path": "src/submodules/ReferenceStates.jl", "max_forks_repo_name": "tjjarvinen/HKQM.jl", "max_forks_repo_head_hexsha": "4e2f4cf58aae6afee54ebac62b3656a26b8641e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5254237288, "max_line_length": 54, "alphanum_fraction": 0.6206597222, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7859389729993046}}
{"text": "function GCD(a::Int64,b::Int64)\n\t\n\twhile !(mod(a,b) == 0)\n\t\t\n\t\tc = mod(a,b);\n\t\ta = b;\n\t\tb = c;\n\tend\n\treturn b\nend\n\nfunction LCM(a::Int64, b::Int64)\n\treturn div(a*b,GCD(a,b))\nend\n\nfunction LCMMulti(N::Array{Int64,1})\n\treturn reduce(LCM, N)\nend\n\nfunction Euler5()\n\tprintln(LCMMulti([1:20]))\nend\n\n@time Euler5()", "meta": {"hexsha": "0bcc8c44970edcd210951985ac01aa32d6df33a7", "size": 308, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/OldFiles/problem_5.jl", "max_stars_repo_name": "gribeill/ProjectEuler", "max_stars_repo_head_hexsha": "540b027394f191696f7fab59d4fc88501d5c971a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Julia/OldFiles/problem_5.jl", "max_issues_repo_name": "gribeill/ProjectEuler", "max_issues_repo_head_hexsha": "540b027394f191696f7fab59d4fc88501d5c971a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/OldFiles/problem_5.jl", "max_forks_repo_name": "gribeill/ProjectEuler", "max_forks_repo_head_hexsha": "540b027394f191696f7fab59d4fc88501d5c971a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.8333333333, "max_line_length": 36, "alphanum_fraction": 0.6201298701, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750373915658, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7859389675271562}}
{"text": "\"\"\"\r\nprecision(ArbFloat)           # show the current default precision  \r\nsetprecision(ArbFloat, 120)   # change the current default precision  \r\nsetprecision(ArbFloat, 53+7)  # akin to setprecision(BigFloat, 53)  \r\n\r\nArbFloat(12)       # use the default precision, at run time  \r\nArbFloat{200}(12)  # use specified precision, at run time  \r\nArbFloat(200,\"12\") # use the specified precision, at run time  \r\n@ArbFloat(12)      # use the default precision, at compile time  \r\n@ArbFloat(200,12)  # use specified precision, at compile time  \r\n\r\n@ArbFloat(1.2345) == ArbFloat(\"1.2345\")\r\n\r\n          remember to do this        and           to avoid this\r\n\r\n    goodValue = @ArbFloat(1.2345)         wrongValue = ArbFloat(1.2345);\r\n        1.234500000000000000                   1.2344999999999999307\r\n\r\n     ArbFloat(12345)/ArbFloat(1000)        ArbFloat(12.345)/ArbFloat(10)\r\n        1.234500000000000000                   1.234500000000000064\r\n\r\n\r\n```\r\nsetprecision(ArbFloat, 80)\r\n\r\nexp1 = exp(ArbFloat(1));\r\nstringsmall(exp1),stringcompact(exp1),string(exp1),stringall(exp1)\r\n> (\"2.7182818\",\"2.71828182845905\",\"2.71828182845904523536029\",\"2.71828182845904523536029\")\r\nshowall_pm(exp1)\r\n> 2.718281828459045235360286±3.3216471534462276e-24\r\nbounds(exp1)\r\n> ( 2.71828182845904523536028,  2.718281828459045235360293 )\r\n\r\nsetprecision(ArbFloat, 116); # the initial default precision\r\nfuzzed_e = tan(atanh(tanh(atan(exp(one(ArbFloat))))))\r\n> 2.718281828459045235360287\r\nshowall(fuzzed_e)\r\n> 2.7182818284590452353602874713527\r\nbounds(fuzzed_e)\r\n> ( 2.718281828459045235360287,   \r\n    2.718281828459045235360287 )\r\n> they are not really the same ...    \r\nlo, hi = bounds(fuzzed_e); showall(lo,hi)\r\n> ( 2.7182818284590452353602874713526543,  \r\n    2.7182818284590452353602874713526701 )\r\n\r\nsmartstring(fuzzed_e)  \r\n> \"2.7182818284590452353602874713527-\"\r\n```\r\n\"\"\"\r\nmodule ArbFloats\r\n\r\n\r\nexport ArbFloat,      # co-matched decimal rounding, n | round(hi,n,10) == round(lo,n,10)\r\n       @ArbFloat,     # converts string form of argument, precision is optional first arg\r\n       simeq, nsime, prec, preceq, succ, succeq, # non-strict total ordering comparisons\r\n       (≃), (≄), (≺), (⪯), (≻), (⪰),           #    matched binary operators\r\n       upperbound, lowerbound, bounds,\r\n       midpoint, radius, midpoint_radius,\r\n       bounding_midpoint, bounding_radius, bounding_midpoint_radius,\r\n       stringsmall, stringcompact, stringmedium, stringlarge, stringall,\r\n       stringsmall_pm, stringcompact_pm, string_pm,\r\n       stringlarge_pm, stringall_pm, string_exact,\r\n       showsmall, showcompact, showlarge, showall, showpretty,\r\n       showsmall_pm, showcompact_pm, show_pm,\r\n       showlarge_pm, showall_pm,\r\n       stringpretty, smartvalue, smartstring, showsmart,\r\n       readable, show_readable, ReadableNumStyle,\r\n       two, three, four, copymidpoint, copyradius, deepcopyradius,\r\n       get_emax, get_emin, bounded, boundedrange,\r\n       fmod, decompose, \r\n       integerpart, decimalpart, fractionalpart, smartmodf,\r\n       isexact, notexact,\r\n       isposinf, isneginf,\r\n       notnan, notinf, notposinf, notneginf, notfinite,\r\n       iszero, notzero, nonzero, isone, notone, notinteger,\r\n       ispositive, notpositive, isnegative, notnegative,\r\n       includes_integer, excludes_integer, includes_zero, excludes_zero,\r\n       includes_positive, excludes_positive, includes_negative, excludes_negative,\r\n       includes_nonpositive,  includes_nonnegative,\r\n       areequal, notequal, approxeq, (≊),\r\n       narrow, overlap, donotoverlap,\r\n       contains, iscontainedby, doesnotcontain, isnotcontainedby,\r\n       absz, absz2, invsqrt, pow, root, \r\n       tanpi, cotpi, logbase, sincos, sincospi, sinhcosh,\r\n       doublefactorial, risingfactorial, rgamma, agm, polylog,\r\n       relative_error, relative_accuracy, midpoint_precision, trimmed,\r\n       PI,SQRTPI,LOG2,LOG10,EXP1,EULER,CATALAN,KHINCHIN,GLAISHER,APERY, # constants\r\n       get_midpoint_digits_shown, get_radius_digits_shown,  # some interface control\r\n       set_midpoint_digits_shown, set_radius_digits_shown,\r\n       isolate_nonnegative_content, isolate_positive_content, # for interval algorithms\r\n       force_nonnegative_content, force_positive_content,\r\n       sort_intervals                                         # uses weak total ordering over intervals \r\n\r\nimport Base: stdout,\r\n    hash, convert, promote_rule, isa,\r\n    string, show, parse,\r\n    finalizer, decompose, precision, setprecision,\r\n    typemin, typemax, floatmin, floatmax,\r\n    copy, deepcopy,\r\n    size, length,\r\n    zero, one, isinteger,\r\n    ldexp, frexp, modf, eps,\r\n    isequal, isless, (==),(!=),(<),(<=),(>=),(>),\r\n    min, max, minmax,\r\n    typemax, typemin, floatmax, floatmin,\r\n    float, nextfloat, prevfloat,\r\n    isnan, isinf, isfinite, issubnormal,\r\n    signbit, sign, flipsign, copysign, abs, abs2,\r\n    (+),(-),(*),(/),(\\),(%),(^), inv, sqrt, hypot,\r\n    trunc, round, ceil, floor,\r\n    fld, cld, div, mod, rem, divrem, fldmod,\r\n    muladd, fma,\r\n    exp, expm1, log, log1p, log2, log10,\r\n    sin, cos, tan, csc, sec, cot, asin, acos, atan,\r\n    sinh, cosh, tanh, csch, sech, coth, asinh, acosh, atanh,\r\n    sinc, factorial,\r\n    in, union, intersect,\r\n    rand, randn, sort,\r\n    BigInt, BigFloat, Rational\r\n\r\nimport Base.Rounding: rounding_raw, setrounding_raw, rounding, setrounding\r\n\r\nusing Serialization\r\nusing SpecialFunctions\r\n\r\nimport SpecialFunctions: gamma, lgamma, digamma, zeta\r\n\r\nif isdefined(Base, :iszero)\r\n  import Base:iszero\r\nelse\r\n  export iszero\r\nend          \r\n\r\nNotImplemented(info::AbstractString=\"\") = error(string(\"this is not implemented\\n\\t\",info,\"\\n\"))\r\n\r\ninclude(\"support/libarb.jl\")                 # for precompiled libraries\r\n#include(\"support/NemoLibs.jl\")                 # for precompiled libraries\r\n\r\nusing ReadableNumbers\r\n\r\ninclude(\"type/ArbCstructs.jl\")\r\ninclude(\"type/MagFloat.jl\")\r\ninclude(\"type/ArfFloat.jl\")\r\ninclude(\"type/ArbFloat.jl\")\r\ninclude(\"type/ArbInterval.jl\")\r\n\r\n\r\ninclude(\"basics/primitive.jl\")\r\ninclude(\"basics/IEEEfp.jl\")\r\n\r\ninclude(\"basics/predicates.jl\")\r\ninclude(\"basics/convert.jl\")\r\ninclude(\"basics/compare.jl\")\r\ninclude(\"basics/sort.jl\")\r\n\r\ninclude(\"basics/string.jl\")\r\ninclude(\"basics/smartstring.jl\")\r\ninclude(\"basics/show.jl\")\r\ninclude(\"basics/serialize.jl\")\r\n\r\ninclude(\"math/arith.jl\")\r\ninclude(\"math/round.jl\")\r\ninclude(\"math/elementary.jl\")\r\ninclude(\"math/constants.jl\")\r\ninclude(\"math/special.jl\")\r\n\r\ninclude(\"math/rounding.jl\")\r\ninclude(\"math/rand.jl\")\r\ninclude(\"math/arrayops.jl\")\r\n\r\n\r\n#=\r\n# precision is significand precision, significand_bits(FloatNN) + 1, for the hidden bit\r\n=#\r\nconst ArbFloat16 = ArbFloat{ 11}  # read   2 ? 3 or fewer decimal digits to write the same digits ( 16bit Float)\r\nconst ArbFloat32 = ArbFloat{ 24}  # read   6 ? 7 or fewer decimal digits to write the same digits ( 32bit Float)\r\nconst ArbFloat64  = ArbFloat{ 53}  # read  15 ?15 or fewer decimal digits to write the same digits ( 64bit Float)\r\nconst ArbFloat128 = ArbFloat{113}  # read  33 ?34 or fewer decimal digits to write the same digits (128bit Float)\r\nconst ArbFloat256 = ArbFloat{237}  # read  71 ?71 or fewer decimal digits to write the same digits (256bit Float)\r\nconst ArbFloat512 = ArbFloat{496}  # read 148?149 or fewer decimal digits to write the same digits (512bit Float)\r\n\r\nend # ArbFloats\r\n", "meta": {"hexsha": "0946f39121aa6f57448d561cc88ca2d3716b8e0a", "size": 7319, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ArbFloats.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ArbFloats.jl-9689d877-bbb0-593d-8021-de8e3bedf7bf", "max_stars_repo_head_hexsha": "9710fb9b65adff5a62336b6eff50b4d55f378f75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2016-08-21T11:31:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T00:32:14.000Z", "max_issues_repo_path": "src/ArbFloats.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ArbFloats.jl-9689d877-bbb0-593d-8021-de8e3bedf7bf", "max_issues_repo_head_hexsha": "9710fb9b65adff5a62336b6eff50b4d55f378f75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2016-07-06T16:05:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T11:52:18.000Z", "max_forks_repo_path": "src/ArbFloats.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ArbFloats.jl-9689d877-bbb0-593d-8021-de8e3bedf7bf", "max_forks_repo_head_hexsha": "9710fb9b65adff5a62336b6eff50b4d55f378f75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2016-07-01T12:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T11:48:28.000Z", "avg_line_length": 39.777173913, "max_line_length": 114, "alphanum_fraction": 0.6842464818, "num_tokens": 2102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8740772318846386, "lm_q1q2_score": 0.785901524572416}}
{"text": "#! /usr/bin/julia\n\n# Rosetta Code, Vampire number\n\nfunction divisors{T<:Integer}(n::T)\n    !isprime(n) || return [one(T), n]\n    d = [one(T)]\n    for (k, v) in factor(n)\n        e = T[k^i for i in 1:v]\n        append!(d, vec([i*j for i in d, j in e]))\n    end\n    sort(d)\nend\n\nfunction vampirefangs{T<:Integer}(n::T)\n    fangs = T[]\n    isvampire = false\n    vdcnt = ndigits(n)\n    fdcnt = vdcnt>>1\n    iseven(vdcnt) || return (isvampire, fangs)\n    !isprime(n) || return (isvampire, fangs)\n    vdigs = sort(digits(n))\n    d = divisors(n)\n    len = length(d)\n    len = iseven(len) ? len>>1 : len>>1 + 1\n    for f in d[1:len]\n        ndigits(f) == fdcnt || continue\n        g = div(n, f)\n        f%10!=0 || g%10!=0 || continue\n        sort([digits(f), digits(g)]) == vdigs || continue\n        isvampire = true\n        append!(fangs, [f, g])\n    end\n    if isvampire\n        fangs = reshape(fangs, (2,length(fangs)>>1))'\n    end\n    return (isvampire, fangs)\nend\n\nfunction showvampire{T<:Integer}(i::T, n::T, fangs::Array{T,2})\n    s = @sprintf \"%6d  %14d %s\\n\" i n join(fangs[1,:], \"\\u00d7\")\n    for i in 2:size(fangs)[1]\n        s *= \" \"^23*join(fangs[i,:], \"\\u00d7\")*\"\\n\"\n    end\n    return s\nend\n\nvgoal = 25\nvcnt = 0\ndcnt = 0\nprintln(\"Finding the first \", vgoal, \" vampire numbers.\")\nprintln(\"     N         Vampire Fangs\")\nwhile vcnt < vgoal\n    dcnt += 2\n    for i in (10^(dcnt-1)):(10^dcnt-1)\n        (isvampire, fangs) = vampirefangs(i)\n        isvampire || continue\n        vcnt += 1\n        print(showvampire(vcnt, i, fangs))\n        vcnt < vgoal || break\n    end\nend\n\ntest = [16758243290880, 24959017348650, 14593825548650]\nprintln()\nprintln(\"Checking a few numbers.\")\nprintln(\"     N         Vampire Fangs\")\nfor (i, v) in enumerate(test)\n    (isvampire, fangs) = vampirefangs(v)\n    if isvampire\n        print(showvampire(i, v, fangs))\n    else\n        println(@sprintf \"%6d  %14d is not a vampire\" i v)\n    end\nend\n\n\n        \n    \n    \n    \n", "meta": {"hexsha": "cb8ddaf5fff77590634daee5727be500ec372161", "size": 1952, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/completed/vampire_number.jl", "max_stars_repo_name": "MichaeLeroy/rosetta-code", "max_stars_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/completed/vampire_number.jl", "max_issues_repo_name": "MichaeLeroy/rosetta-code", "max_issues_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/completed/vampire_number.jl", "max_forks_repo_name": "MichaeLeroy/rosetta-code", "max_forks_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8048780488, "max_line_length": 64, "alphanum_fraction": 0.5512295082, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7858096105427348}}
{"text": "# Solves the primal problem of a soft-margin SVM classifier using\n# the ACCPM algorithm.\n\n# The main function.\n# This implementation is deterministic for illustration purpose.\n# In practice we may want to use random starting point.\nfunction svmaccpm(X::AbstractMatrix,\n                  Y::AbstractVector,\n                  C::Real,\n                  ϵ::Real,\n                  droppingstrategy::Symbol=:None;\n                  α::Real=0.01, β::Real=0.05)\n  w = zeros(size(X, 2))\n  z = ones(Y)*2\n  x0 = [w; z]\n  A, b = initialpolytope(X, Y, C, w, z)\n  wsize = size(w, 1)\n  f(x) = sum(x[1: wsize].^2)/2 + C*sum(x[wsize+1: end])\n  ∇f(x) = [x[1: size(w, 1)]; C*ones(Y)]\n  x, optdistances, numconstraints = accpm(\n    f, ∇f, A, b, x0, ϵ, droppingstrategy; α=α, β=β)\n  x[1: wsize], optdistances, numconstraints\nend\n\n# Computes the initial polyhedron for the SVM problem with some given\n# initial point.\n# Notes that in the original problem formulation the polyhedron assocaited\n# with the constraint is not bounded, but once given some possible value\n# of the objective we can easily give an upper bound to |w| and z.\nfunction initialpolytope(X::AbstractMatrix,\n                         Y::AbstractVector,\n                         C::Real,\n                         w::AbstractVector,\n                         z::AbstractVector)\n  objvalue = sum(w.^2)/2 + C*sum(z)\n  wupper = √(2*objvalue)\n  zupper = objvalue/C\n  A = [-Y.*X (-eye(size(Y, 1)));\n       zeros(X) (-eye(size(Y, 1)));\n       -eye(size(w, 1)) zeros(X)';\n       eye(size(w, 1)+size(z, 1));]\n  b = [-1.*ones(Y); zeros(Y);\n       fill(wupper, 2*size(w, 1)); fill(zupper, size(z))]\n  A, b\nend\n\n# The general ACCPM algorithm to minimize `f` using the first-order\n# derivative information.\n# We suppose a linear constraint Ax ≤ b exists for the original problem.\nfunction accpm(f, ∇f,\n               A::AbstractMatrix,\n               b::AbstractVector, \n               x0::AbstractVector,\n               ϵ::Real,\n               droppingstrategy::Symbol=:None;\n               α::Real=0.01, β::Real=0.05)\n  (all(A*x0.<b)\n   || throw(DomainError(\"x0 must be strictly feasible.\")))\n  (droppingstrategy in [:None, :DropRedundant, :KeepConstant]\n   || throw(ArgumentError(\n        \"droppingstrategy must be one of the three:\"\n        * \":None, :DropRedundant or :KeepConstant.\")))\n  x = copy(x0)\n  ms = [size(A, 1)]\n  u, l = f(x), -Inf\n  optdistances::Vector{Float64} = []\n  while true\n    x, H = polytope_analcenter(A, b, x, 1e-6; α=α, β=β)\n    ∇, fx = ∇f(x), f(x)\n    u = min(u, fx)\n    l = max(l, fx - ms[end]*√(∇'*(H\\∇)))\n    push!(optdistances, u - l)\n    u - l < ϵ && break\n    if droppingstrategy ≠ :None\n      A, b = dropconstraint(A, b, x, H, droppingstrategy)\n    end\n    A, b = [A; ∇'], [b; ∇'*x]\n    x = nextstartpoint(A, b, x)\n    push!(ms, size(A, 1))\n  end\n  x, optdistances, ms\nend\n\n# In the ACCPM algorithm, at the end of each iteration, the vector `x`\n# is found on the face of the polytope. However, to run the Newton method\n# that gives the analytic center, a strictly feasible point must be given.\n# This function supposes that we have Ax ≤ b but with eqaulity only\n# on the last line and try to move `x` a little to get a new `x'` such\n# that Ax' ≤ b (the last line to `A` is suppose to be not all zero).\nfunction nextstartpoint(A::AbstractMatrix,\n                        b::AbstractVector,\n                        x::AbstractVector)\n  a = A[end, :]\n  upperbound = (b-A*x)[1: end-1]\n  lowerbound = max.(0, -(A*a)[1: end-1])\n  δ = minimum(upperbound./lowerbound)\n  x - δ*a/2\nend\n\n# Drop the constraints according to different strategies.\n#\n# :DropRedundant:\n#   Guarantees not to change the polytope in question.\n#\n# :KeepConstant:\n#   Keeps a fixed number of constraints which are the most relevant.\n#   Here I choose to keep 3n constraints where n is the variable dimension.\n#   However, we shouldn't end up with something that doesn't satisfy the\n#   initial constraints, so this implementation can have bugs in some\n#   particular cases.\nfunction dropconstraint(A::AbstractMatrix,\n                        b::AbstractVector,\n                        x::AbstractVector,\n                        H::AbstractMatrix,\n                        droppingstrategy::Symbol)\n  m = size(A, 1)\n  Hinv = inv(H)\n  relevemeasure = (b-A*x)./[√((A*Hinv)[i, :]⋅A[i, :]) for i=1:m]\n  if droppingstrategy == :DropRedundant\n    tokeep = relevemeasure .< m\n  end\n  if droppingstrategy == :KeepConstant\n    tokeep = sortperm(relevemeasure)[1: min(3*size(A, 2), end)]\n  end\n  A[tokeep, :], b[tokeep]\nend\n", "meta": {"hexsha": "62830574a6e65f100661b19bd0813ddf3e47e97c", "size": 4544, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SVM/accpm.jl", "max_stars_repo_name": "cyber-meow/Optimization_algos", "max_stars_repo_head_hexsha": "ae38b156fbd6ca71bf200fb8d2af7a5d5f817b68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SVM/accpm.jl", "max_issues_repo_name": "cyber-meow/Optimization_algos", "max_issues_repo_head_hexsha": "ae38b156fbd6ca71bf200fb8d2af7a5d5f817b68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SVM/accpm.jl", "max_forks_repo_name": "cyber-meow/Optimization_algos", "max_forks_repo_head_hexsha": "ae38b156fbd6ca71bf200fb8d2af7a5d5f817b68", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7795275591, "max_line_length": 75, "alphanum_fraction": 0.6010123239, "num_tokens": 1355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240211961401, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7857914101377298}}
{"text": "\n######################################################################\n# points.jl: projective points on elliptic curves\n######################################################################\n\nexport EllipticPoint, Point\n\nexport coordinates, base_curve, isinfinity, normalize!, normalized, samefields\n\n\"\"\"\nConcrete type for projective points on elliptic curves given by a projective planar equation.\n\"\"\"\n\nmutable struct EllipticPoint{T<:Nemo.RingElem} <: ProjectivePoint{T}\n\tX::T\n\tY::T\n\tZ::T\n\tcurve::EllipticCurve{T}\nend\n\ncoordinates(P::EllipticPoint) = (P.X, P.Y, P.Z)\n\nbase_curve(P::EllipticPoint) = P.curve\n\n######################################################################\n# Calling with the 'Point' constructor\n######################################################################\n\nfunction Point(x::T, y::T, curve::EllipticCurve{T}) where T\n\tR = base_ring(x)\n\treturn EllipticPoint(x, y, R(1), curve)\nend\n\nfunction Point(X::T, Y::T, Z::T, curve::EllipticCurve{T}) where T\n\treturn EllipticPoint(X, Y, Z, curve)\nend\n\n######################################################################\n# Basic methods for projective points\n######################################################################\n\n\n\nbase_ring(P::EllipticPoint) = parent(P.X)\n\n\"\"\"\nDecide whether a given elliptic point is valid.\n\"\"\"\nfunction isvalid(P::EllipticPoint)\n\tEq = projective_equation(P.curve)\n\tx, y, z = coordinates(P)\n\treturn Eq(x, y, z) == 0 && (x, y, z) != (0, 0, 0)\nend\n\n\n\"\"\"\nDecide whether two projective points are given by the exact same coordinates.\n\"\"\"\nsamefields(P::EllipticPoint, Q::EllipticPoint) = (P.curve == Q.curve) & (P.X == Q.X) & (P.Y == Q.Y) & (P.Z == Q.Z)\n\n\"\"\"\nDescribe a projective point giving its X, Y and Z coordinates, and the curve it lives on.\n\"\"\"\nshow(io::IO, P::EllipticPoint) = print(\"Point (\", P.X, \":\", P.Y, \":\", P.Z, \") on \", P.curve)\n\n\n\"\"\"\nDecide whether a projective point is at infinity.\n\"\"\"\nisinfinity(P::EllipticPoint) = iszero(P.Z)\n\n\"\"\"\nGet a new normalized projective point from any projective point.\n\"\"\"\nfunction normalized(P::EllipticPoint)\n    K = base_ring(P)\n    if isinfinity(P)\n        return EllipticPoint(zero(K),\n                               one(K),\n                               zero(K),\n                               P.curve)\n    else\n        return EllipticPoint(P.X // P.Z,\n                               P.Y // P.Z,\n                               one(K),\n                               P.curve)\n    end\nend\n\n\"\"\"\nNormalize a projective point in place.\n\"\"\"\nfunction normalize!(P::EllipticPoint{T}) where T<:Nemo.FieldElem\n    K = base_ring(P)\n    if isinfinity(P)\n        P.X = zero(K)\n        P.Y = one(K)\n        P.Z = zero(K)\n    else\n        P.X = P.X // P.Z\n        P.Y = P.Y // P.Z\n        P.Z = one(K)\n    end\n    return\nend\n\n\"\"\"\nDecides whether two projective points are the same.\n\"\"\"\n\n==(P::EllipticPoint, Q::EllipticPoint) = samefields(normalized(P), normalized(Q))\n\n", "meta": {"hexsha": "e78f3c86abe48989d4af9a230bbddc877bdaf92d", "size": 2921, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/points.jl", "max_stars_repo_name": "defeo/EllipticCurves.jl", "max_stars_repo_head_hexsha": "c69fa0b38f59b0bca0f98eccce425fcbb2489f57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-27T03:56:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-27T03:56:51.000Z", "max_issues_repo_path": "src/points.jl", "max_issues_repo_name": "defeo/EllipticCurves.jl", "max_issues_repo_head_hexsha": "c69fa0b38f59b0bca0f98eccce425fcbb2489f57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/points.jl", "max_forks_repo_name": "defeo/EllipticCurves.jl", "max_forks_repo_head_hexsha": "c69fa0b38f59b0bca0f98eccce425fcbb2489f57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-11T08:00:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T02:05:17.000Z", "avg_line_length": 25.8495575221, "max_line_length": 114, "alphanum_fraction": 0.5169462513, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240160063031, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7857914057906187}}
{"text": "@doc \"\"\"\n\tdensity(pts::IndexablePoints2D) -> Real\n\nHere density is defined as the minimum radius of a covering of\nthe GeometricalPredicates region with equal-sized balls centered at the \npoints in `pts`.\n\nBy definition of the Voronoi tesselation this radius is the maximum\ndistance from a Voronoi cell vertix to its generator.\n\"\"\"->\nfunction density(generators::IndexablePoints2D)\n\tcorn = voronoicells(generators)\n\tdensity(generators, corn)\nend\n\nfunction density(generators::IndexablePoints2D, corners::Tessellation)\n\tsort!(generators, by=getindex)\n\tdens = 0.0\n\n\tfor idx in keys(corners)\n\t\tgen = generators[idx]\n\t\tfor C in corners[idx]\n\t\t\tdens = max(dens, dist_squared(gen,C))\n\t\tend\n\tend\n\n\treturn sqrt(dens)\nend\n\n@doc \"\"\"\n\tdensity(x::Vector, y::Vector; rw) -> Real\n\nCompute the density for points with coordinates `x` and `y` in the window `rw`.\n\nThe vector `rw` specifies the boundary rectangle as `[xmin, xmax, ymin, ymax]`.\nBy default, `rw` is the unit rectangle.\n\"\"\"->\nfunction density{T<:Real}(x::AbstractVector{T}, y::AbstractVector{T}, rw::Vector{Float64}=[0.0;1.0;0.0;1.0])\n\tpts, SCALEX, SCALEY = fit2boundingbox(x, y, rw)\n\n\tdensity(pts) * sqrt(SCALEX*SCALEY)\nend\n\n", "meta": {"hexsha": "54ce4e60ea816c59a46d1f0f1b7ac4aaaa1c56eb", "size": 1173, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Density.jl", "max_stars_repo_name": "JuliaPackageMirrors/VoronoiCells.jl", "max_stars_repo_head_hexsha": "dc0d518b0b29aae339b05ea407d538b6e1bb6540", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Density.jl", "max_issues_repo_name": "JuliaPackageMirrors/VoronoiCells.jl", "max_issues_repo_head_hexsha": "dc0d518b0b29aae339b05ea407d538b6e1bb6540", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Density.jl", "max_forks_repo_name": "JuliaPackageMirrors/VoronoiCells.jl", "max_forks_repo_head_hexsha": "dc0d518b0b29aae339b05ea407d538b6e1bb6540", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6590909091, "max_line_length": 108, "alphanum_fraction": 0.7306052856, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7857860071856634}}
{"text": "### A Pluto.jl notebook ###\n# v0.11.14\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ bbd5a62e-fbcd-11ea-2bbd-e7be1b736f9f\nusing Plots\n\n# ╔═╡ afa5cbc0-fbcc-11ea-0dd2-35821062dd18\nc = 3\n\n# ╔═╡ 59ddff8e-fbcd-11ea-1124-d308b43c24d9\nacr =10\n\n# ╔═╡ d8f55b7e-fbcc-11ea-1881-15dbeb706e20\nxvars = [float(c) - i for i in 0:acr]\n\n# ╔═╡ 1c685b10-fbcd-11ea-1ecd-75e8c03e7f87\nbegin\n\tfunction f(x)\n\t\treturn cos(x)\n\tend\nend\n\n# ╔═╡ 29568700-fbcf-11ea-3096-7f18898aeba0\nbegin \n\tfunction slope(xl,xr,yl,yr,x)\n\t\tm = (yr-yl)/(xr-xl)\n\t\tb = yl - m*xl\n\t\treturn m*x + b\n\tend\nend\n\n\n# ╔═╡ 358ecd40-fbcd-11ea-00fe-755c43fd372e\nyvals = [f(xvars[i]) for i in 1:acr]\n\n# ╔═╡ 55799400-fbcd-11ea-05dc-85c5e87f6f63\nsecs = [(yvals[i]-f(c))/(xvars[i]-c) for i in 1:acr]\n\n# ╔═╡ ae19b810-fbcd-11ea-2ee7-a9f08af0abaf\nbegin\n\tplt = plot((x)->f(x),-2c,2c, title =\"Limits of secant lines at x=$c\",lw=3,legend=false)\n\txlabel!(\"x\")\n\tylabel!(\"f(x) \")\n\tfor i in 1:acr \n\t\tplot!((x)->slope(xvars[i],c,yvals[i],f(c),x),xvars[i]-1,c+1)\n\t\t\n\tend\n\tplt\n\tsavefig(\"cos(x)-secants.png\")\nend\n\n\n# ╔═╡ 12bbbe30-fbce-11ea-289f-ff4eeafbdcbf\ncd(#= type where you want the images to save on your machine=#)\n\n# ╔═╡ Cell order:\n# ╠═bbd5a62e-fbcd-11ea-2bbd-e7be1b736f9f\n# ╠═afa5cbc0-fbcc-11ea-0dd2-35821062dd18\n# ╠═59ddff8e-fbcd-11ea-1124-d308b43c24d9\n# ╠═d8f55b7e-fbcc-11ea-1881-15dbeb706e20\n# ╠═1c685b10-fbcd-11ea-1ecd-75e8c03e7f87\n# ╠═29568700-fbcf-11ea-3096-7f18898aeba0\n# ╠═358ecd40-fbcd-11ea-00fe-755c43fd372e\n# ╠═55799400-fbcd-11ea-05dc-85c5e87f6f63\n# ╠═ae19b810-fbcd-11ea-2ee7-a9f08af0abaf\n# ╠═12bbbe30-fbce-11ea-289f-ff4eeafbdcbf", "meta": {"hexsha": "05d7fc03793ab51531baf456dc723b4036d22788", "size": 1569, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "derivatives/secant_lines.jl", "max_stars_repo_name": "thomastjdavis/CalculusViz.jl", "max_stars_repo_head_hexsha": "225eefeb88f42689e05b50deed50101faaeb447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-17T05:15:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T05:15:52.000Z", "max_issues_repo_path": "derivatives/secant_lines.jl", "max_issues_repo_name": "thomastjdavis/CalculusViz.jl", "max_issues_repo_head_hexsha": "225eefeb88f42689e05b50deed50101faaeb447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "derivatives/secant_lines.jl", "max_forks_repo_name": "thomastjdavis/CalculusViz.jl", "max_forks_repo_head_hexsha": "225eefeb88f42689e05b50deed50101faaeb447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7391304348, "max_line_length": 88, "alphanum_fraction": 0.6883365201, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7857860037746467}}
{"text": "# # Preorders\n#\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/generated/sketches/Preorders.ipynb)\n#\n# Many of the ideas in category theory can be viewed as generalizations of\n# preorders or monoids. This sketch shows some features of Catlab through the \n# lens of preorders.\n# You will see examples of defining GATs, Presentations, Syntax, and Functors.\n# These are illustrated with preorders or thin categories, which are particularly \n# simple cases of categories. \n\nusing Core: GeneratedFunctionStub\nusing Test\n\nusing Catlab, Catlab.Theories, Catlab.CategoricalAlgebra\nimport Catlab.Theories: compose\n\n#=\n# Definition of a Preorder formalized as a GAT\n\nThe following definitions can be found in the `Catlab.Theories` module. \n\n```julia\n\"\"\" Theory of *preorders*\n\nPreorders encode the axioms of reflexivity and transitivity as term constructors.\n\"\"\"\n@theory Preorder{El,Leq} begin\n  El::TYPE\n  Leq(lhs::El, rhs::El)::TYPE\n  @op (≤) := Leq\n\n  # Preorder axioms are lifted to term constructors in the GAT.\n  reflexive(A::El)::(A≤A) # ∀ A there is a term reflexive(A) which implies A≤A\n  transitive(f::(A≤B), g::(B≤C))::(A≤C) ⊣ (A::El, B::El, C::El)\n\n  # Axioms of the GAT are equivalences on terms or simplification rules in the logic\n  f == g ⊣ (A::El, B::El, f::(A≤B), g::(A≤B))\n  # Read as (f⟹ A≤B ∧ g⟹ A≤B) ⟹ f ≡ g\nend\n```\n\n# Preorders are Thin Categories\n\nDefinition of a thin category\n```julia\n@theory ThinCategory{Ob,Hom} <: Category{Ob,Hom} begin\n  f == g ⊣ (A::Ob, B::Ob, f::Hom(A,B), g::Hom(A,B))\nend\n```\n\nof course this definition extends the GAT of categories\n\n```julia\n@theory Category{Ob,Hom} begin\n  # Unicode aliases.\n  @op begin\n  (→) := Hom\n  (⋅) := compose\n  end\n\n  \"\"\" Object in a category \"\"\"\n  Ob::TYPE\n\n  \"\"\" Morphism in a category \"\"\"\n  Hom(dom::Ob,codom::Ob)::TYPE\n\n  id(A::Ob)::(A → A)\n  compose(f::(A → B), g::(B → C))::(A → C) ⊣ (A::Ob, B::Ob, C::Ob)\n\n  # Category axioms.\n  ((f ⋅ g) ⋅ h == f ⋅ (g ⋅ h)\n  ⊣ (A::Ob, B::Ob, C::Ob, D::Ob, f::(A → B), g::(B → C), h::(C → D)))\n  f ⋅ id(B) == f ⊣ (A::Ob, B::Ob, f::(A → B))\n  id(A) ⋅ f == f ⊣ (A::Ob, B::Ob, f::(A → B))\nend\n```\n\nExercise: construct an isomorphism between the theory of thin categories and\nthe theory of preorders. Show that they have the same models.\n=#\n\n# Once you have a GAT defined using the `@theory` macro, you can define presentations,\n# which are logical syntax for giving examples of the theory. The GAT contains type\n# and term constructors that you can use to write expressions. A presentation uses\n# those expressions to create a specific example of the theory. We define `P` to be a preorder\n# with 3 elements and 2 ≤ relationships.\n@present P(FreeThinCategory) begin\n  (X,Y,Z)::Ob\n  f::Hom(X,Y)\n  g::Hom(Y,Z)\nend\n\n# another example\n\n@present Q(FreeThinCategory) begin\n  (X,Y,Z)::Ob\n  f::Hom(X,Y)\n  g::Hom(Y,Z)\n  Y′::Ob\n  f′::Hom(X,Y′)\n  g′::Hom(Y′,Z)\nend\n\n# Exercise: draw the Hasse diagrams for these preorders by hand.\n\n# # Composition is transitivity\n# expressions in the presentation are paths in the Hasse Diagram\n\nfunction compose(P::Presentation, vs::Vector{Symbol})\n  compose(collect(generator(P, v) for v in vs))\nend\n\n# expressions are represented at expression trees\nex = compose(P, [:f, :g])\n# the head of an expression is the root of the expression tree\nCatlab.head(ex)\n# the julia type of the expression\ntypeof(ex)\n# the GAT type of the expression\ngat_typeof(ex)\n# the parameters of the GAT Type\ngat_type_args(ex)\n\n# in any thin category there is at most one morphism between any pair of objects.\n# In symbols: ex₁::Hom(X,Y) ∧ ex₂::Hom(X,Y) ⟹ ex₁ == ex₂\n\nfunction thinequal(ex₁::FreeThinCategory.Hom, ex₂::FreeThinCategory.Hom)\n  dom(ex₁) == dom(ex₂) && codom(ex₁) == codom(ex₂)\nend\n\n@test thinequal(ex, compose(P, [:f,:g])⋅id(generator(P,:Z)))\n\n# Thinking in terms of preorders, the composite f⋅g::Hom(X,Z) is a proof that X ≤ Z\n# in logical notation you would say f::Hom(X,Y) and g::Hom(Y,Z) ⊢ f⋅g::Hom(X,Z)\n# given a proof that X≤Y and a proof of Y≤Z then ⋅ will create a proof of X≤Z\n# by composing the proofs sequentially like chaining inequalities in math\n# a key aspect of category theory is that you want to work constructively\n# you don't want to know that there exists a composite, you want to hold onto that composite.\n# in programming, the way that you hold onto things is putting data into data structures.\n# While computers can access things by offset or addresses, programmers want to use names\n# so when we prove in P that X≤Z, we name that proof by adding it as a generator\n@present P₂(FreeThinCategory) begin\n  (X,Y,Z)::Ob\n  f::Hom(X,Y)\n  g::Hom(Y,Z)\n  h::Hom(X,Z)\nend\n\nex = compose(P₂, [:f, :g])\n\n# Now that we have a name for h, we can see that thinequal knows that f⋅g == h because\n# according to the definition of a thin category, any two morphisms with the same\n# domain and codomain are equal.\n@test thinequal(ex, generator(P₂, :h))\n\n# There is an imperative interface to manipulating presentations by mutating them for this purpose\nP₂′ = copy(P)\nadd_generator!(P₂′, Hom(:h, P[:X], P[:Z]))\ngenerators(P₂′)\n\n\n# We could avoid this naming the homs situation by giving all the homs the same name\n# however, then when you tried to write down a morphism, you wouldn't be able to refer\n# to a specific one by name, because they are all named ≤.\n@present R(FreeThinCategory) begin\n  (x,y,z)::Ob\n  (≤)::Hom(x,y)\nend\ngenerators(R)\n\n#=\nCatlab won't let you make a presentation where the homs have the same exact name.\nSo, this will error:\n\n```julia\n@present Q(FreeThinCategory) begin\n  (x,y,z)::Ob\n  (≤)::Hom(x,y)\n  (≤)::Hom(y,z)\n  (≤)::Hom(x,z)\nend\n```\n\nHowever, you can omit the names for homs with the following syntax, which is useful for thin categories.\n  \n```julia\n@present Q(FreeThinCategory) begin\n  (x,y,z)::Ob\n  ::Hom(x,y)\n  ::Hom(y,z)\n  ::Hom(x,z)\nend\n```\n=#\n\n# In a thin category, all the homs with the same domain and codomain are the same,\n# so why don't we name them by their the domain and codomain and then use the property\n# that any two homs with the same name are the same to encode the thinness. This is what\n# the Hasse diagram representation does for us. The edges in the diagram are encoding the\n# presentation data into a combinatorial object that we can visualize. There are many\n# reasons to encode a logical structure into a combinatorial strucuture, one is that \n# we generally have ways of drawing combinatorial objects that convey their saliant structure\n# and enable visual reasoning. Another is algorithms, isomorphism between the combinatorial representations\n# provide some of the isomorphisms between the logical structures. in this case, a graph homomorphism between Hasse Diagrams\n# construct isomorphisms between the preorders they present. The converse is not true since there can be many Graphs\n# that present the same preorder.\n\n# # Monotone Maps\n\n# a generator is in the set of homs if it is in the list of generators\nin_homs(f::FreeThinCategory.Hom{:generator}, C::FinCat) =\n  f in hom_generators(C)\n\n# a composite hom is in the list set of homs if all of its components are.\nin_homs(f::FreeThinCategory.Hom{:compose}, C::FinCat) =\n  all(fᵢ->in_homs(fᵢ, C), args(f))\n\n\n# we can check if a map is functorial, which is called monotone for preorders.\n# 1. make sure all the objects in the domain are sent to objects in the codomain\n# 2. make sure all the homs are sent to homs in the codomain\n# 3. check that the domains and codomainss of the homs match\nfunction is_functorial(F::FinFunctor)\n  pₒ = map(ob_generators(dom(F))) do X\n    F(X) in ob_generators(codom(F))\n  end |> all\n\n  pₕ = map(hom_generators(dom(F))) do f\n    in_homs(F(f), codom(F))\n  end |> all\n\n  pᵩ = map(hom_generators(dom(F))) do f\n    FX = F(dom(f))\n    FY = F(codom(f))\n    Ff = F(f)\n    dom(Ff) == FX && codom(Ff) == FY\n  end |> all\n  return pₒ && pₕ && pᵩ\nend\n\n@present Q(FreeThinCategory) begin\n  (a,b,c,d)::Ob\n  ab::Hom(a,b)\n  bc::Hom(b,c)\n  cd::Hom(c,d)\nend\ngenerators(Q)\n\nFₒ = Dict(:X=>:a, :Y=>:b, :Z=>:c)\nFₕ = Dict(:f=>:ab, :g=>:bc)\nF = FinFunctor(Fₒ, Fₕ, P, Q)\n@test is_functorial(F)\n\nFₒ = Dict(:X=>:a, :Y=>:b, :Z=>:d)\nFₕ = Dict(:f=>:ab, :g=>[:bc, :cd])\nF = FinFunctor(Fₒ, Fₕ, P, Q)\n@test is_functorial(F)\n\n\nFₒ = Dict(:X=>:a, :Y=>:b, :Z=>:c)\nFₕ = Dict(:f=>:ab, :g=>[:bc, :cd])\nF = FinFunctor(Fₒ, Fₕ, P, Q)\n@test !is_functorial(F)\n\n#=\nMonotone maps are functors for thin categories. One of the benefits of \ncategory theory is that we find abstractions that work in multiple domains.\nThe abstraction of preserving the domains and codomains of morphisms is\na key abstraction that we can use to define many notions in mathematics. \n=#\n", "meta": {"hexsha": "49f7801d622cb1b2f126eaff9475675512e1c450", "size": 8628, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/literate/sketches/preorders.jl", "max_stars_repo_name": "AlgebraicJulia/Catlab.jl", "max_stars_repo_head_hexsha": "c23d6cf7fe6e48f86acb66e8fa71c13f0eb4e83a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 262, "max_stars_repo_stars_event_min_datetime": "2020-06-17T23:35:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T07:08:49.000Z", "max_issues_repo_path": "docs/literate/sketches/preorders.jl", "max_issues_repo_name": "AlgebraicJulia/Catlab.jl", "max_issues_repo_head_hexsha": "c23d6cf7fe6e48f86acb66e8fa71c13f0eb4e83a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 293, "max_issues_repo_issues_event_min_datetime": "2020-06-18T17:14:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T02:04:55.000Z", "max_forks_repo_path": "docs/literate/sketches/preorders.jl", "max_forks_repo_name": "AlgebraicJulia/Catlab.jl", "max_forks_repo_head_hexsha": "c23d6cf7fe6e48f86acb66e8fa71c13f0eb4e83a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2020-06-17T22:19:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T21:07:51.000Z", "avg_line_length": 31.7205882353, "max_line_length": 125, "alphanum_fraction": 0.6933240612, "num_tokens": 2723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308128813471, "lm_q2_score": 0.8418256472515684, "lm_q1q2_score": 0.7857859982183977}}
{"text": "@doc raw\"\"\"\n    Circle{𝔽} <: Manifold{𝔽}\n\nThe circle $𝕊^1$ is a manifold here represented by\nreal-valued points in $[-π,π)$ or complex-valued points $z ∈ ℂ$ of absolute value\n$\\lvert z\\rvert = 1$.\n# Constructor\n\n    Circle(𝔽=ℝ)\n\nGenerate the `ℝ`-valued Circle represented by angles, which\nalternatively can be set to use the [`AbstractNumbers`](@ref) `𝔽=ℂ` to obtain the circle\nrepresented by `ℂ`-valued circle of unit numbers.\n\"\"\"\nstruct Circle{𝔽} <: Manifold{𝔽} end\n\nCircle(𝔽::AbstractNumbers = ℝ) = Circle{𝔽}()\n\n@doc raw\"\"\"\n    check_manifold_point(M::Circle, p)\n\nCheck whether `p` is a point on the [`Circle`](@ref) `M`.\nFor the real-valued case, `x` is an angle and hence it checks that $p  ∈ [-π,π)$.\nfor the complex-valued case, it is a unit number, $p ∈ ℂ$ with $\\lvert p \\rvert = 1$.\n\"\"\"\ncheck_manifold_point(::Circle, ::Any...)\n\nfunction check_manifold_point(M::Circle{ℝ}, p; kwargs...)\n    if !isapprox(sym_rem(p), p; kwargs...)\n        return DomainError(\n            p,\n            \"The point $(p) does not lie on $(M), since its is not in [-π,π).\",\n        )\n    end\n    return nothing\nend\nfunction check_manifold_point(M::Circle{ℂ}, p; kwargs...)\n    if !isapprox(sum(abs.(p)), 1.0; kwargs...)\n        return DomainError(\n            abs(p),\n            \"The point $(p) does not lie on the $(M) since its norm is not 1.\",\n        )\n    end\n    return nothing\nend\n\n\"\"\"\n    check_tangent_vector(M::Circle, p, X; check_base_point, kwargs...)\n\nCheck whether `X` is a tangent vector in the tangent space of `p` on the\n[`Circle`](@ref) `M`.\nFor the real-valued case represented by angles, all `X` are valid, since the tangent space is the whole real line.\nFor the complex-valued case `X` has to lie on the line parallel to the tangent line at `p`\nin the complex plane, i.e. their inner product has to be zero.\nThe optional parameter `check_base_point` indicates, whether to call [`check_manifold_point`](@ref)  for `p`.\n\"\"\"\ncheck_tangent_vector(::Circle{ℝ}, ::Any...; ::Any...)\n\nfunction check_tangent_vector(M::Circle{ℝ}, p, X; check_base_point = true, kwargs...)\n    if check_base_point\n        perr = check_manifold_point(M, p; kwargs...)\n        return perr # if x is valid all v that are real numbers are valid\n    end\n    return nothing\nend\nfunction check_tangent_vector(M::Circle{ℂ}, p, X; check_base_point = true, kwargs...)\n    if check_base_point\n        perr = check_manifold_point(M, p)\n        perr === nothing || return perr\n    end\n    if !isapprox(abs(complex_dot(p, X)), 0.0; kwargs...)\n        return DomainError(\n            abs(complex_dot(p, X)),\n            \"The value $(X) is not a tangent vector to $(p) on $(M), since it is not orthogonal in the embedding.\",\n        )\n    end\n    return nothing\nend\n\n@doc raw\"\"\"\n    complex_dot(a, b)\n\nCompute the inner product of two (complex) numbers with in the complex plane.\n\"\"\"\ncomplex_dot(a, b) = dot(map(real, a), map(real, b)) + dot(map(imag, a), map(imag, b))\ncomplex_dot(a::Number, b::Number) = (real(a) * real(b) + imag(a) * imag(b))\n\n@doc raw\"\"\"\n    distance(M::Circle, p, q)\n\nCompute the distance on the [`Circle`](@ref) `M`, which is\nthe absolute value of the symmetric remainder of `p` and `q` for the real-valued\ncase and the angle between both complex numbers in the Gaussian plane for the\ncomplex-valued case.\n\"\"\"\ndistance(::Circle, ::Any...)\ndistance(::Circle{ℝ}, p::Real, q::Real) = abs(sym_rem(p - q))\ndistance(::Circle{ℝ}, p, q) = abs(sum(sym_rem.(p - q)))\ndistance(::Circle{ℂ}, p, q) = acos(clamp(complex_dot(p, q), -1, 1))\n\n@doc raw\"\"\"\n    exp(M::Circle, p, X)\n\nCompute the exponential map on the [`Circle`](@ref).\n````math\n\\exp_p X = (p+X)_{2π},\n````\nwhere $(\\cdot)_{2π}$ is the (symmetric) remainder with respect to division by $2π$, i.e. in $[-π,π)$.\n\nFor the complex-valued case, the same formula as for the [`Sphere`](@ref) $𝕊^1$ is applied to values in the\ncomplex plane.\n\"\"\"\nexp(::Circle, ::Any...)\nBase.exp(::Circle{ℝ}, p::Real, X::Real) = sym_rem(p + X)\nfunction Base.exp(M::Circle{ℂ}, x::Number, v::Number)\n    θ = norm(M, x, v)\n    return cos(θ) * x + usinc(θ) * v\nend\n\nexp!(::Circle{ℝ}, q, p, X) = (q .= sym_rem(p + X))\nfunction exp!(M::Circle{ℂ}, q, p, X)\n    θ = norm(M, p, X)\n    q .= cos(θ) * p + usinc(θ) * X\n    return q\nend\n\nflat(::Circle, ::Number, X::TFVector) = FVector(CotangentSpace, X.data)\n\nflat!(::Circle, ξ::CoTFVector, p, X::TFVector) = copyto!(ξ, X)\n\nfunction get_basis(M::Circle{ℝ}, p, B::DiagonalizingOrthonormalBasis)\n    sbv = sign(B.frame_direction[])\n    vs = @SVector [@SVector [sbv == 0 ? one(sbv) : sbv]]\n    return CachedBasis(B, (@SVector [0]), vs)\nend\nget_coordinates(M::Circle{ℝ}, p, X, B::DefaultOrthonormalBasis) = X\nfunction get_coordinates(M::Circle{ℝ}, p, X, B::DiagonalizingOrthonormalBasis)\n    sbv = sign(B.frame_direction[])\n    return X .* (sbv == 0 ? 1 : sbv)\nend\n\"\"\"\n    get_coordinates(M::Circle{ℂ}, p, X, B::DefaultOrthonormalBasis)\n\nReturn tangent vector coordinates in the Lie algebra of the [`Circle`](@ref).\n\"\"\"\nfunction get_coordinates(M::Circle{ℂ}, p, X, B::DefaultOrthonormalBasis)\n    X, p = X[1], p[1]\n    Xⁱ = imag(X) * real(p) - real(X) * imag(p)\n    return @SVector [Xⁱ]\nend\n\neval(\n    quote\n        @invoke_maker 1 Manifold get_coordinates(\n            M::Circle,\n            e::Identity,\n            X,\n            B::VeeOrthogonalBasis,\n        )\n    end,\n)\n\nfunction get_coordinates!(M::Circle, Y::AbstractArray, p, X, B::DefaultOrthonormalBasis)\n    Y[] = get_coordinates(M, p, X, B)[]\n    return Y\nend\nfunction get_coordinates!(\n    M::Circle,\n    Y::AbstractArray,\n    p,\n    X,\n    B::DiagonalizingOrthonormalBasis,\n)\n    Y[] = get_coordinates(M, p, X, B)[]\n    return Y\nend\n\neval(\n    quote\n        @invoke_maker 1 Manifold get_coordinates!(\n            M::Circle,\n            Y::AbstractArray,\n            p,\n            X,\n            B::VeeOrthogonalBasis,\n        )\n    end,\n)\n\n\nget_vector(::Circle{ℝ}, p, X, ::AbstractBasis) = X\nfunction get_vector(M::Circle{ℝ}, p, X, B::DiagonalizingOrthonormalBasis)\n    sbv = sign(B.frame_direction[])\n    return X .* (sbv == 0 ? 1 : sbv)\nend\n\"\"\"\n    get_vector(M::Circle{ℂ}, p, X, B::DefaultOrthonormalBasis)\n\nReturn tangent vector from the coordinates in the Lie algebra of the [`Circle`](@ref).\n\"\"\"\nget_vector(M::Circle{ℂ}, p, X, B::AbstractBasis) = @SVector [1im * X[1] * p[1]]\n\nfunction get_vector!(M::Circle, Y::AbstractArray, p, X, B::AbstractBasis)\n    Y[] = get_vector(M, p, X, B)[]\n    return Y\nend\nfor BT in ManifoldsBase.DISAMBIGUATION_BASIS_TYPES\n    eval(\n        quote\n            @invoke_maker 5 $(supertype(BT)) get_vector!(\n                M::Circle,\n                Y::AbstractArray,\n                p,\n                X,\n                B::$BT,\n            )\n        end,\n    )\nend\n\n@doc raw\"\"\"\n    injectivity_radius(M::Circle[, p])\n\nReturn the injectivity radius on the [`Circle`](@ref) `M`, i.e. $π$.\n\"\"\"\ninjectivity_radius(::Circle) = π\ninjectivity_radius(::Circle, ::ExponentialRetraction) = π\ninjectivity_radius(::Circle, ::Any) = π\ninjectivity_radius(::Circle, ::Any, ::ExponentialRetraction) = π\neval(\n    quote\n        @invoke_maker 1 Manifold injectivity_radius(\n            M::Circle,\n            rm::AbstractRetractionMethod,\n        )\n    end,\n)\n\n@doc raw\"\"\"\n    inner(M::Circle, p, X, Y)\n\nCompute the inner product of the two tangent vectors `X,Y` from the tangent plane at `p` on\nthe [`Circle`](@ref) `M` using the restriction of the metric from the embedding,\ni.e.\n\n````math\ng_p(X,Y) = X*Y\n````\n\nfor the real case and\n\n````math\ng_p(X,Y) = Y^\\mathrm{T}X\n````\n\nfor the complex case interpreting complex numbers in the Gaussian plane.\n\"\"\"\ninner(::Circle, ::Any...)\n@inline inner(::Circle{ℝ}, p, X, Y) = dot(X, Y)\n@inline inner(::Circle{ℝ}, p::Real, X::Real, Y::Real) = X * Y\n@inline inner(::Circle{ℂ}, p, X, Y) = complex_dot(X, Y)\n\nfunction inverse_retract(M::Circle, x::Number, y::Number)\n    return inverse_retract(M, x, y, LogarithmicInverseRetraction())\nend\nfunction inverse_retract(M::Circle, x::Number, y::Number, ::LogarithmicInverseRetraction)\n    return log(M, x, y)\nend\n\n@doc raw\"\"\"\n    log(M::Circle, p, q)\n\nCompute the logarithmic map on the [`Circle`](@ref) `M`.\n````math\n\\log_p q = (q-p)_{2π},\n````\nwhere $(\\cdot)_{2π}$ is the (symmetric) remainder with respect to division by $2π$, i.e. in $[-π,π)$.\n\nFor the complex-valued case, the same formula as for the [`Sphere`](@ref) $𝕊^1$ is applied to values in the\ncomplex plane.\n\"\"\"\nlog(::Circle, ::Any...)\nBase.log(::Circle{ℝ}, p::Real, q::Real) = sym_rem(q - p)\nfunction Base.log(M::Circle{ℂ}, p::Number, q::Number)\n    cosθ = complex_dot(p, q)\n    if cosθ ≈ -1  # appr. opposing points, return deterministic choice from set-valued log\n        X = real(p) ≈ 1 ? 1im : 1 + 0im\n        X = X - complex_dot(p, X) * p\n        X *= π / norm(X)\n    else\n        cosθ = cosθ > 1 ? one(cosθ) : cosθ\n        θ = acos(cosθ)\n        X = (q - cosθ * p) / usinc(θ)\n    end\n    return project(M, p, X)\nend\n\nlog!(::Circle{ℝ}, X, p, q) = (X .= sym_rem(q - p))\nfunction log!(M::Circle{ℂ}, X, p, q)\n    cosθ = complex_dot(p, q)\n    if cosθ ≈ -1\n        X .= sum(real.(p)) ≈ 1 ? 1.0im : 1.0 + 0.0im\n        X .= X - complex_dot(p, X) * p\n        X .*= π / norm(X)\n    else\n        cosθ = cosθ > 1 ? one(cosθ) : cosθ\n        θ = acos(cosθ)\n        X .= (q - cosθ * p) / usinc(θ)\n    end\n    return project!(M, X, p, X)\nend\n\n@doc raw\"\"\"\n    manifold_dimension(M::Circle)\n\nReturn the dimension of the [`Circle`](@ref) `M`,\ni.e. $\\dim(𝕊^1) = 1$.\n\"\"\"\nmanifold_dimension(::Circle) = 1\n\n@doc raw\"\"\"\n    mean(M::Circle{ℝ}, x::AbstractVector[, w::AbstractWeights])\n\nCompute the Riemannian [`mean`](@ref mean(M::Manifold, args...)) of `x` of points on\nthe [`Circle`](@ref) $𝕊^1$, reprsented by real numbers, i.e. the angular mean\n````math\n\\operatorname{atan}\\Bigl( \\sum_{i=1}^n w_i\\sin(x_i),  \\sum_{i=1}^n w_i\\sin(x_i) \\Bigr).\n````\n\"\"\"\nmean(::Circle{ℝ}, ::Any)\nfunction Statistics.mean(::Circle{ℝ}, x::AbstractVector{<:Real}; kwargs...)\n    return atan(1 / length(x) * sum(sin, x), 1 / length(x) * sum(cos, x))\nend\nfunction Statistics.mean(\n    ::Circle{ℝ},\n    x::AbstractVector{<:Real},\n    w::AbstractVector;\n    kwargs...,\n)\n    return atan(sum(w .* sin.(x)), sum(w .* cos.(x)))\nend\n@doc raw\"\"\"\n    mean(M::Circle{ℂ}, x::AbstractVector[, w::AbstractWeights])\n\nCompute the Riemannian [`mean`](@ref mean(M::Manifold, args...)) of `x` of points on\nthe [`Circle`](@ref) $𝕊^1$, reprsented by complex numbers, i.e. embedded in the complex plade.\nComuting the sum\n````math\ns = \\sum_{i=1}^n x_i\n````\nthe mean is the angle of the complex number $s$, so represented in the complex plane as\n$\\frac{s}{\\lvert s \\rvert}$, whenever $s \\neq 0$.\n\nIf the sum $s=0$, the mean is not unique. For example for opposite points or equally spaced\nangles.\n\"\"\"\nmean(::Circle{ℂ}, ::Any)\nfunction Statistics.mean(M::Circle{ℂ}, x::AbstractVector{<:Complex}; kwargs...)\n    s = sum(x)\n    abs(s) == 0 &&\n        return error(\"The mean for $(x) on $(M) is not defined/unique, since the sum of the complex numbers is zero\")\n    return s / abs(s)\nend\nfunction Statistics.mean(\n    M::Circle{ℂ},\n    x::AbstractVector{<:Complex},\n    w::AbstractVector;\n    kwargs...,\n)\n    s = sum(w .* x)\n    abs(s) == 0 &&\n        error(\"The mean for $(x) on $(M) is not defined/unique, since the sum of the complex numbers is zero\")\n    return s /= abs(s)\nend\n\nmid_point(M::Circle{ℝ}, p1, p2) = exp(M, p1, 0.5 * log(M, p1, p2))\nmid_point(::Circle{ℂ}, p1::Complex, p2::Complex) = exp(im * (angle(p1) + angle(p2)) / 2)\nmid_point(M::Circle{ℂ}, p1::StaticArray, p2::StaticArray) = SA[mid_point(M, p1[], p2[])]\n\n@inline LinearAlgebra.norm(::Circle, p, X) = sum(abs, X)\n\nnumber_of_coordinates(::Circle, ::AbstractBasis) = 1\n\n@doc raw\"\"\"\n    project(M::Circle, p)\n\nProject a point `p` onto the [`Circle`](@ref) `M`.\nFor the real-valued case this is the remainder with respect to modulus $2π$.\nFor the complex-valued case the result is the projection of `p` onto the unit circle in the\ncomplex plane.\n\"\"\"\nproject(::Circle, ::Any)\nproject(::Circle{ℝ}, p::Real) = sym_rem(p)\nproject(::Circle{ℂ}, p::Number) = p / abs(p)\n\nproject!(::Circle{ℝ}, q, p) = copyto!(q, sym_rem(p))\nproject!(::Circle{ℂ}, q, p) = copyto!(q, p / sum(abs.(p)))\n\n@doc raw\"\"\"\n    project(M::Circle, p, X)\n\nProject a value `X` onto the tangent space of the point `p` on the [`Circle`](@ref) `M`.\n\nFor the real-valued case this is just the identity.\nFor the complex valued case `X` is projected onto the line in the complex plane\nthat is parallel to the tangent to `p` on the unit circle and contains `0`.\n\"\"\"\nproject(::Circle, ::Any, ::Any)\nproject(::Circle{ℝ}, p::Real, X::Real) = X\nproject(::Circle{ℂ}, p::Number, X::Number) = X - complex_dot(p, X) * p\n\nproject!(::Circle{ℝ}, Y, p, X) = (Y .= X)\nproject!(::Circle{ℂ}, Y, p, X) = (Y .= X - complex_dot(p, X) * p)\n\nretract(M::Circle, p, q) = retract(M, p, q, ExponentialRetraction())\nretract(M::Circle, p, q, m::ExponentialRetraction) = exp(M, p, q)\n\nrepresentation_size(::Circle) = ()\n\nsharp(::Circle, p::Number, ξ::CoTFVector) = FVector(TangentSpace, ξ.data)\n\nsharp!(::Circle, X::TFVector, p, ξ::CoTFVector) = copyto!(X, ξ)\n\nBase.show(io::IO, ::Circle{𝔽}) where {𝔽} = print(io, \"Circle($(𝔽))\")\n\n@doc raw\"\"\"\n    sym_rem(x,[T=π])\n\nCompute symmetric remainder of `x` with respect to the interall 2*`T`, i.e.\n`(x+T)%2T`, where the default for `T` is $π$\n\"\"\"\nfunction sym_rem(x::N, T = π) where {N<:Number}\n    return (x ≈ T ? convert(N, -T) : rem(x, convert(N, 2 * T), RoundNearest))\nend\nsym_rem(x, T = π) where {N} = map(sym_rem, x, Ref(T))\n\n@doc raw\"\"\"\n    vector_transport_to(M::Circle, p, X, q, ::ParallelTransport)\n\nCompute the parallel transport of `X` from the tangent space at `p` to the tangent space at\n`q` on the [`Circle`](@ref) `M`.\nFor the real-valued case this results in the identity.\nFor the complex-valud case, the formula is the same as for the [`Sphere`](@ref)`(1)` in the\ncomplex plane.\n````math\n\\mathcal P_{q←p} X = X - \\frac{⟨\\log_p q,X⟩_p}{d^2_{ℂ}(p,q)}\n\\bigl(\\log_p q + \\log_q p \\bigr),\n````\nwhere [`log`](@ref) denotes the logarithmic map on `M`.\n\"\"\"\nvector_transport_to(::Circle, ::Any, ::Any, ::Any, ::ParallelTransport)\nvector_transport_to(::Circle{ℝ}, p::Real, X::Real, q::Real, ::ParallelTransport) = X\nfunction vector_transport_to(\n    M::Circle{ℂ},\n    p::Number,\n    X::Number,\n    q::Number,\n    ::ParallelTransport,\n)\n    X_pq = log(M, p, q)\n    Xnorm = norm(M, p, X_pq)\n    Y = X\n    if Xnorm > 0\n        factor = 2 * complex_dot(X, q) / (abs(p + q)^2)\n        Y -= factor .* (p + q)\n    end\n    return Y\nend\n\nvector_transport_to!(::Circle{ℝ}, Y, p, X, q, ::ParallelTransport) = (Y .= X)\nfunction vector_transport_to!(M::Circle{ℂ}, Y, p, X, q, ::ParallelTransport)\n    X_pq = log(M, p, q)\n    Xnorm = norm(M, p, X_pq)\n    Y .= X\n    if Xnorm > 0\n        factor = 2 * complex_dot(X, q) / (sum(abs.(p + q) .^ 2))\n        Y .-= factor .* (p + q)\n    end\n    return Y\nend\n\nfunction vector_transport_direction(\n    M::Circle,\n    p::Number,\n    X::Number,\n    Y::Number,\n    m::AbstractVectorTransportMethod,\n)\n    q = exp(M, p, Y)\n    return vector_transport_to(M, p, X, q, m)\nend\n\nzero_tangent_vector(::Circle, p::Number) = zero(p)\nzero_tangent_vector!(::Circle, X, p) = fill!(X, 0)\n", "meta": {"hexsha": "fc3f6ae2790a2e10ee50f0d9d6ae81816eeee60c", "size": 15160, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/manifolds/Circle.jl", "max_stars_repo_name": "stevengj/Manifolds.jl", "max_stars_repo_head_hexsha": "af7f72f29d0f0d1c558d6b1e05c7b22d265362da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/manifolds/Circle.jl", "max_issues_repo_name": "stevengj/Manifolds.jl", "max_issues_repo_head_hexsha": "af7f72f29d0f0d1c558d6b1e05c7b22d265362da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/manifolds/Circle.jl", "max_forks_repo_name": "stevengj/Manifolds.jl", "max_forks_repo_head_hexsha": "af7f72f29d0f0d1c558d6b1e05c7b22d265362da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6262626263, "max_line_length": 117, "alphanum_fraction": 0.6165567282, "num_tokens": 4924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7857859956868285}}
{"text": "function normalize_node(node::R,domain::Array{T,1}) where {R<:Number,T<:AbstractFloat}\n\n  if domain[1] == domain[2]\n    norm_node = zero(T)\n    return norm_node\n  else\n    norm_node = 2.0*(node-domain[2])/(domain[1]-domain[2])-1.0\n    return norm_node\n  end\n  \nend\n  \nfunction normalize_node(node::AbstractArray{R,1},domain::Array{T,1}) where {R<:Number,T<:AbstractFloat}\n  \n  norm_nodes = similar(node)\n  for i in eachindex(node)\n    norm_nodes[i] = normalize_node(node[i],domain)\n  end\n  \n  return norm_nodes\n  \nend\n  \nfunction normalize_node!(node::AbstractArray{R,1},domain::Array{T,1}) where {R<:Number,T<:AbstractFloat}\n  \n  for i in eachindex(node)\n    node[i] = normalize_node(node[i],domain)\n  end\n  \nend", "meta": {"hexsha": "dcd4d9b43a5599e8e1c62a957b151e0ded6a14c4", "size": 713, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/normalize_node.jl", "max_stars_repo_name": "RJDennis/ChebyshevApprox", "max_stars_repo_head_hexsha": "9b43654b3b7d00210ca2191b1173c79c7333dad3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-05-15T13:28:38.000Z", "max_stars_repo_stars_event_max_datetime": "2015-05-15T13:28:38.000Z", "max_issues_repo_path": "src/normalize_node.jl", "max_issues_repo_name": "RJDennis/ChebyshevApprox", "max_issues_repo_head_hexsha": "9b43654b3b7d00210ca2191b1173c79c7333dad3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/normalize_node.jl", "max_forks_repo_name": "RJDennis/ChebyshevApprox", "max_forks_repo_head_hexsha": "9b43654b3b7d00210ca2191b1173c79c7333dad3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7666666667, "max_line_length": 104, "alphanum_fraction": 0.683029453, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308054739519, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7857859938347453}}
{"text": "# The fraction 49/98 is a curious fraction, as an inexperienced mathematician\n# in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which\n# is correct, is obtained by cancelling the 9s.\n#\n# We shall consider fractions like, 30/50 = 3/5, to be trivial examples.\n#\n# There are exactly four non-trivial examples of this type of fraction, less\n# than one in value, and containing two digits in the numerator and denominator.\n#\n# If the product of these four fractions is given in its lowest common terms,\n# find the value of the denominator.\n\nusing ProjectEulerSolutions\n\n# Cycle through numbers using Julia's built-in digits, and store the fractions\n# as rationals.  Julia's built-in rationals solve the common denominator\n# problem easily.\nfunction p033solution()::Integer\n    rationals = Rational[]\n    for a in 10:98\n        for b in (a+1):99\n            if a != b\n                val = a / b\n                da = digits(a)\n                db = digits(b)\n                if da[1] == db[1] && da[1] != 0 && da[2] / db[2] == val\n                    push!(rationals, a // b)\n                elseif da[1] == db[2] && da[2] / db[1] == val\n                    push!(rationals, a // b)\n                elseif da[2] == db[1] && da[1] / db[2] == val\n                    push!(rationals, a // b)\n                elseif da[2] == db[2] && da[1] / db[1] == val\n                    push!(rationals, a // b)\n                end\n            end\n        end\n    end\n    return denominator(prod(rationals))\nend\n\np033 = Problems.Problem(p033solution)\n\nProblems.benchmark(p033)", "meta": {"hexsha": "a51914bd14cce50dc79f2ff70f4fde2e83560775", "size": 1576, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/033.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/033.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/033.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6511627907, "max_line_length": 80, "alphanum_fraction": 0.5824873096, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7857859864264132}}
{"text": "#Compute approximate errors at tend with analytical solution\nfunction mesh_norm(u, mesh::Uniform1DFVMesh, p)\n    mesh_norm(u, mesh.Δx, p)\nend\nfunction mesh_norm(u, dx::Real, p)\n    @assert p > 0.0 \"p must be a positive number\"\n    if p == Inf\n        maximum(abs.(u))\n    else\n        (sum(abs,(u).^p)*dx)^(1/p)\n    end\nend\n\n\"\"\"\nfunction get_LP_error(ref::Function, sol::AbstractFVSolution; relative = true, p = 1.0, pointwise::Bool = false)\n    Compute Lp errores of FVSolution `sol` against reference solution `ref`.\n    Additional options:\n    `relative`: default true. Compute relative or absolute error\n    `p`: parameter to define Lp norm\n    `poitwise` default false. Compute errors against pointwise values of reference solution or cell averages\n\"\"\"\nfunction get_LP_error(ref::Function, sol::AbstractFVSolution{T}; relative::Bool = true, p = 1.0, pointwise::Bool = false) where {T}\n    x = cell_centers(getmesh(sol))\n    #tspan = sol.prob.tspan\n    Tend = gettimes(sol)[end]\n    uexact = fill!(similar(getvalues(sol)[end]), zero(T))\n    faces = cell_facets(getmesh(sol))\n    _compute_exact_sol!(uexact, Tend, sol, x, faces, ref, pointwise)\n    relative ? 100*mesh_norm((getvalues(sol)[end] - uexact), getmesh(sol), p)/mesh_norm(uexact, getmesh(sol), p) : mesh_norm((getvalues(sol)[end] - uexact), getmesh(sol), p)\nend\n\nfunction _compute_exact_sol!(uexact::AbstractArray{T,2},Tend, sol, x, faces, ref, pointwise) where {T}\n    for i in 1:getncells(getmesh(sol))\n        if pointwise\n            uexact[:,i] = ref(x[i], Tend)\n        else\n            uexact[:,i] = num_integrate(x->ref(x, Tend),faces[i], faces[i+1])/cell_volume(getmesh(sol), i)\n        end\n    end\nend\n\nfunction _compute_exact_sol!(uexact::AbstractArray{T,1},Tend, sol, x, faces, ref, pointwise) where {T}\n    for i in 1:getncells(getmesh(sol))\n        if pointwise\n            uexact[i] = ref(x[i], Tend)\n        else\n            uexact[i] = num_integrate(x->ref(x, Tend),faces[i], faces[i+1])/cell_volume(getmesh(sol), i)\n        end\n    end\nend\n\nfunction get_L1_error(ref::Function, sol::AbstractFVSolution)\n    get_LP_error(ref, sol; relative = false)\nend\n\nfunction get_relative_L1_error(ref::Function, sol::AbstractFVSolution)\n    get_LP_error(ref, sol)\nend\n\n# \"Compute aproximate L1 errors with numerical reference solution\"\nfunction get_num_LP_error(reference,M, uu,N,dx; relative::Bool = true, p = 1.0)\n    uexact = fill!(similar(uu), zero(eltype(uu)))\n    R = Int(round(M/N))\n    for i = 1:N\n        uexact[:,i] = 1.0/R*sum(reference[:,R*(i-1)+1:R*i],dims=1)\n    end\n    relative ? 100.0*mesh_norm((uu - uexact), dx, p)/mesh_norm(uexact, dx, p) : mesh_norm((uu - uexact), dx, p)\nend\n\nfunction approx_L1_error(sol_ref::AbstractFVSolution, sol::AbstractFVSolution)\n    M = getncells(getmesh(sol_ref))\n    N = getncells(getmesh(sol))\n    dx = cell_volume(getmesh(sol), 1)\n    return get_num_LP_error(getvalues(sol_ref)[end],M, getvalues(sol)[end],N,dx;relative = false)\nend\n\nfunction approx_relative_L1_error(sol_ref::AbstractFVSolution, sol::AbstractFVSolution)\n    M = getncells(getmesh(sol_ref))\n    N = getncells(getmesh(sol))\n    dx = cell_volume(getmesh(sol), 1)\n    return get_num_LP_error(getvalues(sol_ref)[end],M, getvalues(sol)[end],N,dx;relative = true)\nend\n\n# # function estimate_error_cubic(reference,M, xx,uu,N)\n# #   uexact = zeros(N)\n# #   itp = interpolate(reference[:,2], BSpline(Cubic(Flat())),OnCell())\n# #   i = (M-1)/(reference[M,1]-reference[1,1])*(xx - reference[1,1])+1\n# #   uexact = itp[i]\n# #   sum(1.0/N*abs(uu - uexact))\n# # end\n\n## Order of convergence Tables\nstruct FVOOCTable{T,ntype}\n  data::Matrix{T}\n  alg_name::ntype\nend\n\nscheme_short_name(alg::AbstractFVAlgorithm) =  string(typeof(alg))\n\n\"\"\"\nget_conv_order_table(alg, get_problem, u_exact, mesh_ncells; relative = true, kwargs...)\nCompute a table of errors and approximate order of convergence for numerical scheme `alg`\nby solving a Conservations Laws problem in a sequence of meshes of cell size given by\n`mesh_ncells`.\n`get_problem` is a function that returns a ConservationLawsProblem given a number of cells `N`\n`kwargs` extra arguments are passed to `solve` function\n\"\"\"\nfunction get_conv_order_table(alg,solve, get_problem, u_exact::Function, mesh_ncells, TimeIntegrator; relative::Bool = true, kwargs...)\n    errors = fill(zero(Float64),size(mesh_ncells,1),2)\n    @assert size(mesh_ncells,1) > 2 \"mesh_sizes must have at least two elements\"\n    for (i,N) in enumerate(mesh_ncells)\n        prob,mesh,cb,dt = get_problem(N, alg)\n        sol_ode = solve(prob, TimeIntegrator;dt = dt, callback = cb, kwargs...);\n        sol = fv_solution(sol_ode, mesh)\n        errors[i,1] = relative ? get_relative_L1_error(u_exact, sol) : get_L1_error(u_exact, sol)\n    end\n    @. errors[2:end,2] = -log(errors[1:(end-1),1]/errors[2:end,1])/log(mesh_ncells[1:(end-1)]/mesh_ncells[2:end]);\n    return FVOOCTable([mesh_ncells errors[:,1] errors[:,2]],scheme_short_name(alg))\nend\n\nfunction get_conv_order_table(alg,solve, get_problem, u_exact::AbstractFVSolution, mesh_ncells, TimeIntegrator; relative::Bool = true, kwargs...)\n    errors = fill(zero(Float64),size(mesh_ncells,1),2)\n    @assert size(mesh_ncells,1) > 2 \"mesh_sizes must have at least two elements\"\n    for (i,N) in enumerate(mesh_ncells)\n        prob,mesh,cb,dt = get_problem(N, alg)\n        sol_ode = solve(prob, TimeIntegrator;dt = dt, callback = cb, kwargs...);\n        sol = fv_solution(sol_ode, mesh)\n        errors[i,1] = relative ? approx_relative_L1_error(u_exact, sol) : approx_L1_error(u_exact, sol)\n    end\n    @. errors[2:end,2] = -log(errors[1:(end-1),1]/errors[2:end,1])/log(mesh_ncells[1:(end-1)]/mesh_ncells[2:end]);\n    return FVOOCTable([mesh_ncells errors[:,1] errors[:,2]],scheme_short_name(alg))\nend\n", "meta": {"hexsha": "4ef7a550e55366c1041ad3e775a6626da8e721b3", "size": 5742, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/errors.jl", "max_stars_repo_name": "Paulms/ConservationLawsDiffEq.jl", "max_stars_repo_head_hexsha": "9b7e5f13865a65a0d77614eae508044d0528c9a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-07-10T00:00:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T15:45:29.000Z", "max_issues_repo_path": "src/errors.jl", "max_issues_repo_name": "jamesamiller/ConservationLawsDiffEq.jl", "max_issues_repo_head_hexsha": "9b7e5f13865a65a0d77614eae508044d0528c9a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2018-06-01T15:01:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T08:08:21.000Z", "max_forks_repo_path": "src/errors.jl", "max_forks_repo_name": "jamesamiller/ConservationLawsDiffEq.jl", "max_forks_repo_head_hexsha": "9b7e5f13865a65a0d77614eae508044d0528c9a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-08-02T13:11:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T22:21:30.000Z", "avg_line_length": 43.1729323308, "max_line_length": 173, "alphanum_fraction": 0.6870428422, "num_tokens": 1723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8856314723088733, "lm_q1q2_score": 0.7857363158554844}}
{"text": "function sigmoid(x::Float64)::Float64\n    return (MathConstants.e^x)/(1 + MathConstants.e^x)\nend\n\nfunction sigmoid_p(x::Float64)::Float64\n    return (MathConstants.e^x)/(1 + 2MathConstants.e^x + MathConstants.e^(2x))\nend\n\nfunction MSE(a::Vector{Float64},l::Vector{Float64})::Float64\n    return 0.5*(sum((a.-l).^2))\nend\n\nfunction MSE_p(a::Vector{Float64},l::Vector{Float64})::Float64\n    return sum(a.-l)\nend\n", "meta": {"hexsha": "f097fe32814a0c0fc884e3c1ea8de19cc616bde9", "size": 408, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ian/helpers.jl", "max_stars_repo_name": "ian-double-u/NNfromScratch", "max_stars_repo_head_hexsha": "e2cbe8c298171a2359b27241ed6552c20d9b41e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ian/helpers.jl", "max_issues_repo_name": "ian-double-u/NNfromScratch", "max_issues_repo_head_hexsha": "e2cbe8c298171a2359b27241ed6552c20d9b41e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ian/helpers.jl", "max_forks_repo_name": "ian-double-u/NNfromScratch", "max_forks_repo_head_hexsha": "e2cbe8c298171a2359b27241ed6552c20d9b41e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5, "max_line_length": 78, "alphanum_fraction": 0.6960784314, "num_tokens": 135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410982634296, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7857159766735592}}
{"text": "function perform_conjugate_gradient(A,y)\n\n    \"\"\"\n     perform_conjugate_gradient - perform (bi)-conjugate gradient\n\n         x = perform_conjugate_gradient(A,y);\n\n       Solves for A*x=y.\n       Works for vector x,y\n\n       Important: the algorithm assumes that the matrix is symmetric definite\n       positive.\n\n       Copyright (c) 2007 Gabriel Peyre\n    \"\"\"\n\n    niter = 100\n    epsilon = 1e-5\n    is_sdp = 1\n    x = zeros(size(A,2),1)\n    normb = epsilon\n    r  = y - A*x\n    p = r\n    r0 = sum(vec(r).^2)\n\n\n    err = [sum(r0)]\n    for it in 1:niter\n        # auxiliary vector\n        w  = A*p\n\n        d = sum(vec(p) .* vec(w));\n\n        if abs(d)<eps()\n            d=1\n        end\n        alpha = repeat( [r0 / d], outer=(size(x,1), 1) );           # found optimal alpha in line search\n        x = x + alpha.*p                       # new guess\n        r = r - alpha.*w                       # the residual is in fact r=b-A*x\n\n        rprev = r0;                             # save norm of the old residual\n        r0 = sum(r.^2);                         # compute norm of new residual\n\n        append!(err, sqrt( sum(r.^2) ))\n\n        if err[end]<normb\n            break\n        end\n\n        # search direction\n        beta = r0./rprev;\n        p = r + repeat([beta], outer=(size(x,1), 1)).*p\n\n    end\n    return x\nend\n", "meta": {"hexsha": "913ad0a3264ef681651b03080cc95e452774a4b2", "size": 1327, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/perform_conjugate_gradient.jl", "max_stars_repo_name": "sparda117/NtToolBox", "max_stars_repo_head_hexsha": "9c2065f002a48991af42c9788fc897149206e55a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/perform_conjugate_gradient.jl", "max_issues_repo_name": "sparda117/NtToolBox", "max_issues_repo_head_hexsha": "9c2065f002a48991af42c9788fc897149206e55a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/perform_conjugate_gradient.jl", "max_forks_repo_name": "sparda117/NtToolBox", "max_forks_repo_head_hexsha": "9c2065f002a48991af42c9788fc897149206e55a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2807017544, "max_line_length": 104, "alphanum_fraction": 0.4800301432, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410972802222, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7857159624586512}}
{"text": "\n\n\ntype PCA\n    solver::String\n    n_components::Integer\n    components::Matrix\n    mean_::Vector\nend\n\nfunction PCA(;\n             solver::String = \"svd\",\n             n_components::Integer = 2,\n             components::Matrix = zeros(4,4),\n             mean_::Vector = zeros(4))\n    return PCA(solver, n_components, components, mean_)\nend\n\n\nfunction train!(model::PCA, X::Matrix)\n    model.mean_ = vec(mean(X,1))\n    n_sample = size(X, 1)\n    X_de_mean = X - repmat(model.mean_', n_sample, 1)\n\n    if model.solver == \"svd\"\n        U,S,V = svd(X_de_mean)\n    elseif model.solver == \"eig\"\n        cov_ = cov(X_de_mean)\n        D,V = eigs(cov_, nev = model.n_components)\n    end\n    model.components = V[:, 1:model.n_components]\nend\n\nfunction transform(model::PCA, \n                 x::Matrix)\n    n = size(x,1)\n    res = zeros(n, model.n_components)\n    for i = 1:n \n        res[i, :] = transform(model, x[i,:])\n    end\n    return res\nend\n\nfunction transform(model::PCA,\n                 x::Vector)\n    x = x - model.mean_\n    x = vec(x' * model.components)\n    return x\nend\n\nfunction plot_in_2d(model::PCA, X::Matrix, y::Vector, title::String)\n    X = transform(model, X)\n    x1 = X[:, 1]\n    x2 = X[:, 2]\n    df = DataFrame(x = x1, y = x2, clu = y)\n    println(\"Computing finished\")\n    println(\"Drawing the plot.....Please Wait(Actually Gadfly is quite slow in drawing the first plot)\")\n    Gadfly.plot(df, x = \"x\", y = \"y\", color = \"clu\", Geom.point, Guide.title(title))\nend\n\n\nfunction test_PCA()\n    X_train, X_test, y_train, y_test = make_digits()\n    model = PCA()\n    train!(model,X_train)\n    plot_in_2d(model, X_train, y_train, \"PCA\")\nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "e19d252abf8ea45c193d387083eab94295ebee07", "size": 1661, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unsupervised_learning/principalComponentAnalysis.jl", "max_stars_repo_name": "zhuzhenping/LightML.jl", "max_stars_repo_head_hexsha": "6be734bbdc9d3b9df33640c26051b6d750540ccd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 428, "max_stars_repo_stars_event_min_datetime": "2017-03-09T12:33:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T19:32:22.000Z", "max_issues_repo_path": "src/unsupervised_learning/principalComponentAnalysis.jl", "max_issues_repo_name": "afcarl/LightML.jl", "max_issues_repo_head_hexsha": "c6aa43c1bc85250873759f97db561f9be2c89f13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-03-09T11:45:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-27T18:04:38.000Z", "max_forks_repo_path": "src/unsupervised_learning/principalComponentAnalysis.jl", "max_forks_repo_name": "afcarl/LightML.jl", "max_forks_repo_head_hexsha": "c6aa43c1bc85250873759f97db561f9be2c89f13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 92, "max_forks_repo_forks_event_min_datetime": "2017-03-10T08:48:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T15:56:27.000Z", "avg_line_length": 20.5061728395, "max_line_length": 104, "alphanum_fraction": 0.5857916918, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109713976399, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7857159592685943}}
{"text": "# p33.jl - solve linear BVP u_xx = exp(4x), u'(-1)=u(1)=0\n\nN = 16;\n(D,x) = cheb(N);\nD2 = D^2;\nD2[N+1,:] = D[N+1,:];            # Neumann condition at x = -1\nD2 = D2[2:N+1,2:N+1];\nf = @. exp(4*x[2:N]);\nu = D2\\[f;0];\nu = [0;u];\nclf();\nplot(x,u,\".\",markersize=10);\naxis([-1,1,-4,0]);\nxx = -1:.01:1;\nuu = polyval(polyfit(x,u),xx);\nplot(xx,uu); grid(true);\nexact = @. (exp(4*xx) - 4*exp(-4)*(xx-1) - exp(4))/16;\ntitle(\"max err = $(signif(norm(uu-exact,Inf),5))\",fontsize=12);\n", "meta": {"hexsha": "b911f33cf8dd33d605a5ca4d59e63da2de03b79f", "size": 471, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p33.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p33.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p33.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7894736842, "max_line_length": 63, "alphanum_fraction": 0.5053078556, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517083920618, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.78564958322901}}
{"text": "# Empirical estimation of CDF and PDF\n\n\n## Empirical CDF\n\nstruct ECDF{T <: AbstractVector{<:Real}}\n    sorted_values::T\nend\n\nfunction (ecdf::ECDF)(x::Real)\n    searchsortedlast(ecdf.sorted_values, x) / length(ecdf.sorted_values)\nend\n\nfunction (ecdf::ECDF)(v::RealVector)\n    ord = sortperm(v)\n    m = length(v)\n    r = similar(ecdf.sorted_values, m)\n    r0 = 0\n    i = 1\n    n = length(ecdf.sorted_values)\n    for x in ecdf.sorted_values\n        while i <= m && x > v[ord[i]]\n            r[ord[i]] = r0\n            i += 1\n        end\n        r0 += 1\n        if i > m\n            break\n        end\n    end\n    while i <= m\n        r[ord[i]] = n\n        i += 1\n    end\n    return r / n\nend\n\n\"\"\"\n    ecdf(X)\n\nReturn an empirical cumulative distribution function (ECDF) based on a vector of samples\ngiven in `X`.\n\nNote: this function that returns a callable composite type, which can then be applied to\nevaluate CDF values on other samples.\n\n`extrema`, `minimum`, and `maximum` are supported to for obtaining the range over which\nfunction is inside the interval ``(0,1)``; the function is defined for the whole real line.\n\"\"\"\necdf(X::RealVector{T}) where T<:Real = ECDF(sort(X))\n\nminimum(ecdf::ECDF) = first(ecdf.sorted_values)\n\nmaximum(ecdf::ECDF) = last(ecdf.sorted_values)\n\nextrema(ecdf::ECDF) = (minimum(ecdf), maximum(ecdf))\n", "meta": {"hexsha": "3e9c31ef58142b7bdff1b72693410007a6bc6b06", "size": 1326, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/empirical.jl", "max_stars_repo_name": "jgoldfar/StatsBase.jl", "max_stars_repo_head_hexsha": "f4567cb9f5a8bd00c146eadae781bdf1b467938a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-27T00:22:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-27T00:22:00.000Z", "max_issues_repo_path": "src/empirical.jl", "max_issues_repo_name": "jgoldfar/StatsBase.jl", "max_issues_repo_head_hexsha": "f4567cb9f5a8bd00c146eadae781bdf1b467938a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-20T17:06:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-24T17:33:55.000Z", "max_forks_repo_path": "src/empirical.jl", "max_forks_repo_name": "jgoldfar/StatsBase.jl", "max_forks_repo_head_hexsha": "f4567cb9f5a8bd00c146eadae781bdf1b467938a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-04-29T08:53:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-29T08:53:23.000Z", "avg_line_length": 23.2631578947, "max_line_length": 91, "alphanum_fraction": 0.6304675716, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896132, "lm_q2_score": 0.8824278633625322, "lm_q1q2_score": 0.7856204240151342}}
{"text": "export ortho_latin, check_ortho\n\n\"\"\"\n`A,B = ortho_latin(n)` returns a pair of orthogonal `n`-by-`n`\nLatin squares.\n\n`A,B = ortho_latin(n,true)` returns a pair of orthogonal Latin squares\nthat are transposes of each other.\n\n`A,B = ortho_latin(n,r,s)` builds the Latin squares `latin(n,r)`\nand `latin(n,s)` and, if they are orthogonal, returns them as the\nanswer. (Otherwise, throws an error.) See: `find_ortho_parameters`.\n\"\"\"\nfunction ortho_latin(n::Int, self::Bool = false)\n    if !self\n        try\n            r, s = find_ortho_parameters(n)\n            return ortho_latin(n, r, s)\n        catch\n        end\n    end\n    println(\"No quick solution. Using integer programming.\")\n\n    return ortho_latin_IP(n, self)\nend\n\nfunction ortho_latin_IP(n::Int, self::Bool = false)\n    MOD = Model(get_solver())\n    # Z[i,j,k,l] is an indicator that there is a k in A[i,j] and\n    # an l in B[i,j]\n    @variable(MOD, Z[1:n, 1:n, 1:n, 1:n], Bin)\n\n    # one entry per cell constraint\n    for i = 1:n\n        for j = 1:n\n            @constraint(MOD, sum(Z[i, j, k, l] for k = 1:n for l = 1:n) == 1)\n        end\n    end\n\n    # Top row 11 22 33 ... nn\n    if !self\n        for i = 1:n\n            @constraint(MOD, Z[1, i, i, i] == 1)  # A[1,i] = B[1,i] = i\n        end\n    end\n\n    # orthogonality constraint\n    for k = 1:n\n        for l = 1:n\n            @constraint(MOD, sum(Z[i, j, k, l] for i = 1:n for j = 1:n) == 1)\n        end\n    end\n\n    # Row constraints\n\n    for i = 1:n\n        for k = 1:n\n            @constraint(MOD, sum(Z[i, j, k, l] for j = 1:n for l = 1:n) == 1)\n        end\n    end\n\n    for i = 1:n\n        for l = 1:n\n            @constraint(MOD, sum(Z[i, j, k, l] for j = 1:n for k = 1:n) == 1)\n        end\n    end\n\n    # Col constraints\n    for j = 1:n\n        for k = 1:n\n            @constraint(MOD, sum(Z[i, j, k, l] for i = 1:n for l = 1:n) == 1)\n        end\n    end\n\n    for j = 1:n\n        for l = 1:n\n            @constraint(MOD, sum(Z[i, j, k, l] for i = 1:n for k = 1:n) == 1)\n        end\n    end\n\n    if self   # force A^T==B\n        for i = 1:n\n            for j = 1:n\n                for k = 1:n\n                    for l = 1:n\n                        @constraint(MOD, Z[i, j, k, l] == Z[j, i, l, k])\n                    end\n                end\n            end\n        end\n    end\n\n\n    optimize!(MOD)\n    status = Int(termination_status(MOD))\n\n    if status != 1\n        error(\"No pair of orthogonal Latin squares of order $n can be found.\")\n    end\n\n    ZZ = value.(Z)\n    A = zeros(Int, n, n)\n    B = zeros(Int, n, n)\n\n    for i = 1:n\n        for j = 1:n\n            for k = 1:n\n                for l = 1:n\n                    if ZZ[i, j, k, l] > 0\n                        A[i, j] = k\n                        B[i, j] = l\n                    end\n                end\n            end\n        end\n    end\n\n    return A, B\nend\n\n\n\n\n\nfunction ortho_latin(n::Int, r::Int, s::Int)\n    A = latin(n, r)\n    B = latin(n, s)\n    @assert check_ortho(A, B) \"Parameters n=$n, r=$r, and s=$s do not generate a pair of orthogonal Latin squares\"\n    return A, B\nend\n\n\"\"\"\n`find_ortho_parameters(n)` tries to find parameters `r` and `s`\nso that `ortho_latin(n,r,s)` will succeed. Returns `(r,s)` if\nsuccessful or throws an error if not.\n\"\"\"\nfunction find_ortho_parameters(n::Int)\n    for r = 1:n-1\n        for s = 1:n-1\n            if gcd(n, r) == 1 && gcd(n, s) == 1 && gcd(n, r - s) == 1\n                return r, s\n            end\n        end\n    end\n    error(\"No parameters for n=$n found\")\nend\n\n\n\"\"\"\n`check_ortho(A,B)` checks that matrices `A` and `B` are a pair of\northogonal Latin squares.\n\"\"\"\nfunction check_ortho(A::Matrix{Int}, B::Matrix{Int})::Bool\n    if size(A) != size(B)\n        return false\n    end\n    if !check_latin(A) || !check_latin(B)\n        return false\n    end\n    n, r = size(A)\n\n    vals = unique((n + 1) * A + B)\n    return length(vals) == n * n\nend\n", "meta": {"hexsha": "0e6c0bcc9890451318015f72c6cdb9198c1a556e", "size": 3880, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ortho_latin.jl", "max_stars_repo_name": "scheinerman/LatinSquares.jl", "max_stars_repo_head_hexsha": "cc0c79128904b6c38fbf65be89faa9109f69ad13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-02-20T03:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-01T20:42:42.000Z", "max_issues_repo_path": "src/ortho_latin.jl", "max_issues_repo_name": "scheinerman/LatinSquares.jl", "max_issues_repo_head_hexsha": "cc0c79128904b6c38fbf65be89faa9109f69ad13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ortho_latin.jl", "max_forks_repo_name": "scheinerman/LatinSquares.jl", "max_forks_repo_head_hexsha": "cc0c79128904b6c38fbf65be89faa9109f69ad13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5151515152, "max_line_length": 114, "alphanum_fraction": 0.4961340206, "num_tokens": 1278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103777, "lm_q2_score": 0.8633916187614822, "lm_q1q2_score": 0.7856060913029516}}
{"text": "# This file is a part of SimilaritySearch.jl\n# License is Apache 2.0: https://www.apache.org/licenses/LICENSE-2.0.txt\n\nexport l1_distance, l2_distance, squared_l2_distance, linf_distance, lp_distance\n\n\"\"\"\n    l1_distance(a, b)::Float64\n\nComputes the Manhattan's distance between `a` and `b`\n\"\"\"\nfunction l1_distance(a, b)::Float64\n    d::Float64 = 0.0 #zero(eltype(a))\n\n    @inbounds @simd for i = 1:length(a)\n\t    m = a[i] - b[i]\n        d += ifelse(m > 0, m, -m)\n    end\n\n    d\nend\n\n\"\"\"\n    l2_distance(a, b)::Float64\n    \nComputes the Euclidean's distance betweem `a` and `b`\n\"\"\"\nfunction l2_distance(a, b)::Float64\n    #d = zero(eltype(a))\n    d::Float64 = 0.0\n\n    @inbounds @simd for i = 1:length(a)\n        m = a[i] - b[i]\n        d += m * m\n    end\n\n    sqrt(d)\nend\n\n\"\"\"\n    squared_l2_distance(a, b)::Float64\n\nComputes the squared Euclidean's distance between `a` and `b`\n\"\"\"\nfunction squared_l2_distance(a, b)::Float64\n    # d = zero(eltype(a))\n    d::Float64 = 0.0\n\n    @inbounds @simd for i = 1:length(a)\n        m = a[i] - b[i]\n        d += m * m\n    end\n\n    d\nend\n\n\n\"\"\"\n    linf_distance(a, b)::Float64\n\nComputes the max or Chebyshev'se distance\n\"\"\"\nfunction linf_distance(a, b)::Float64\n   d::Float64 = 0.0 # d = zero(eltype(a))\n\n    @inbounds @simd for i = 1:length(a)\n        m = abs(a[i] - b[i])\n        d = max(d, m)\n    end\n\n    d\nend\n\n\"\"\"\n    lp_distance(p_::Real)\n\nCreates a function that computes computes generic Minkowski's distance with the given `p_`\n\"\"\"\nfunction lp_distance(p::Real)\n    p = convert(Float64, p)\n    invp = 1.0 / p\n\n    function _lp(a, b)::Float64\n        d::Float64 = 0.0 # d = zero(eltype(a))\n\n        @inbounds @simd for i = 1:length(a)\n            m = abs(a[i] - b[i])\n            d += m ^ p\n        end\n\n        d ^ invp\n    end\nend\n", "meta": {"hexsha": "69864c38233c7bf36725ea3c718be82d194df96e", "size": 1783, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances/vectors.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SimilaritySearch.jl-053f045d-5466-53fd-b400-a066f88fe02a", "max_stars_repo_head_hexsha": "f6815ebd4f018ee3536f5b3be4e39640b344b5e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distances/vectors.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SimilaritySearch.jl-053f045d-5466-53fd-b400-a066f88fe02a", "max_issues_repo_head_hexsha": "f6815ebd4f018ee3536f5b3be4e39640b344b5e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distances/vectors.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SimilaritySearch.jl-053f045d-5466-53fd-b400-a066f88fe02a", "max_forks_repo_head_hexsha": "f6815ebd4f018ee3536f5b3be4e39640b344b5e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1720430108, "max_line_length": 90, "alphanum_fraction": 0.5765563657, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.7856060632338681}}
{"text": "## Derivative related code\n\n\"\"\"\n    tangent(f::Function, c)\n\nReturns a function describing the tangent line to the graph of `f` at `x=c`.\n\nExample. Where does the tangent line intersect the y axis?\n```\nf(x) = sin(x)\ntl(x) = tangent(f, pi/4)(x)  # or tl = tangent(f, pi/3) to use a non-generic function\ntl(0)\n```\n\nUses the automatic derivative of `f` to find the slope of the tangent line at `x=c`.\n\n\"\"\"\ntangent(f,c) = x -> f(c) + f'(c) * (x-c)\n\n\"\"\"\n    secant(f::Function, a, b)\n\nReturns a function describing the secant line to the graph of `f` at `x=a` and `x=b`.\n\nExample. Where does the secant line intersect the `y` axis?\n\n```\nf(x) = sin(x)\na, b = pi/4, pi/3\nsl(x) = secant(f, a, b)(x)  # or sl = sl(f, a, b) to use a non-generic function\nsl(0)\n```\n\n\n\"\"\"\nsecant(f, a, b) = x -> f(a) + (f(b) - f(a)) / (b-a) * (x - a)\n\n\n\n\"\"\"\n    D(f)\n\nFunction interface to `ForwardDiff.derivative`.\n\nAlso *overrides* `f'` to take take a derivative.\n\"\"\"\nfunction D(f, n::Int=1)\n    n < 0 && throw(ArgumentError(\"n is a non-negative integer\"))\n    n == 0 && return f\n    n == 1 && return t -> ForwardDiff.derivative(f, float(t))\n    D(D(f), n-1)\nend\n\n## Create r' to mean the derivative for functions\n## warning, this would be odd for [sin, cos]' as\n## is it [sin', cos'] or the transpose...\nBase.adjoint(r::Function) = D(r)\n", "meta": {"hexsha": "818dfaf269be6135013cc2b9775d070724a50333", "size": 1311, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/derivatives.jl", "max_stars_repo_name": "jverzani/CalculusWithJulia.jl", "max_stars_repo_head_hexsha": "6ee5135e82c11a1f83b024556be55ad6cbf2622d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-08-29T02:00:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T11:15:12.000Z", "max_issues_repo_path": "src/derivatives.jl", "max_issues_repo_name": "jverzani/CalculusWithJulia.jl", "max_issues_repo_head_hexsha": "6ee5135e82c11a1f83b024556be55ad6cbf2622d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2020-12-03T15:00:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T00:57:57.000Z", "max_forks_repo_path": "src/derivatives.jl", "max_forks_repo_name": "jverzani/CalculusWithJulia.jl", "max_forks_repo_head_hexsha": "6ee5135e82c11a1f83b024556be55ad6cbf2622d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-01-07T10:53:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T06:08:38.000Z", "avg_line_length": 22.6034482759, "max_line_length": 85, "alphanum_fraction": 0.6064073227, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8723473829749843, "lm_q1q2_score": 0.7855748022109662}}
{"text": "export jaccard_distance, dice_distance, union_intersection, intersection_distance\n\nfunction union_intersection(a::T, b::T) where {T <: AbstractVector}\n    len_a::Int = length(a)\n    len_b::Int = length(b)\n    ia::Int = 1\n    ib::Int = 1\n    intersection_size::Int = 0\n    c::Int = 0\n    @inbounds while ia <= len_a && ib <= len_b\n        c = cmp(a[ia], b[ib])\n        if c == 0\n            ia += 1\n            ib += 1\n            intersection_size += 1\n        elseif c < 0\n            ia += 1\n        else\n            ib += 1\n        end\n    end\n\n    return len_a + len_b - intersection_size, intersection_size\nend\n\n\"\"\"\nsim_jaccard computes the Jaccard's coefficient between two sets\nrepresented as sorted arrays.\nNote: 1.0 - sim_jaccard computes the Jaccard's distance\n\"\"\"\n\nfunction jaccard_distance(a::T, b::T)::Float64 where {T <: AbstractVector}\n    u, i = union_intersection(a, b)\n    return 1.0 - i / u\nend\n\nfunction dice_distance(a::T, b::T)::Float64 where {T <: AbstractVector}\n    u, i = union_intersection(a, b)\n    return 1.0 - 2 * i / (length(a) + length(b))\nend\n\nmutable struct IntersectionDistance\n    calls::Int\n    IntersectionDistance() = new(0)\nend\n\nfunction intersection_distance(a::T, b::T)::Float64 where {T <: AbstractVector}\n    u, i = union_intersection(a, b)\n\n    return 1.0 - i / min(length(a), length(b))\nend", "meta": {"hexsha": "ece633ae2d4485e5ca67420ee90064307e97a9b9", "size": 1336, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances/sets.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SimilaritySearch.jl-053f045d-5466-53fd-b400-a066f88fe02a", "max_stars_repo_head_hexsha": "70c46490431ca7d0e5cf41052bc36afc4ba3c8fa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distances/sets.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SimilaritySearch.jl-053f045d-5466-53fd-b400-a066f88fe02a", "max_issues_repo_head_hexsha": "70c46490431ca7d0e5cf41052bc36afc4ba3c8fa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distances/sets.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SimilaritySearch.jl-053f045d-5466-53fd-b400-a066f88fe02a", "max_forks_repo_head_hexsha": "70c46490431ca7d0e5cf41052bc36afc4ba3c8fa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1960784314, "max_line_length": 81, "alphanum_fraction": 0.619760479, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7855748000568625}}
{"text": "##########################################################\n# Rafał Nowak\n#\n# Instytut Informatyki\n# Uniwersytet Wrocławski\n#\n#\n# Pomocniczne materiały do wykładu z analizy numerycznej\n#\n##########################################################\n\nwartoscDokladna_1e5 = 1.6449240668982262698057485033127;\nwartoscDokladna_1e6 = 1.6449330668487264363057484999794;\nwartoscDokladna_1e7 = 1.6449339668482314364722484999793;\nwartoscDokladna_1e8 = 1.6449340568482264864724149999793;\nwartoscDokladna_1e9 = 1.6449340658482264369724151664793;\n\nreal = Float32\n\nfunction algorytm1(n)\n  suma = zero(real);\n  for k = 1:1:n\n    suma = suma + one(real)/convert(real, k)/convert(real,k);\n  end\n  return suma\nend\n\nfunction algorytm2(n)\n  suma = zero(real);\n  for k = n:-1:1\n    suma = suma + one(real)/convert(real, k)/convert(real,k);\n  end\n  return suma\nend\n\n\nfunction doTest(x, algorytm, n)\n  println(algorytm, \" n=\", n)\n  @printf(\"Wynik dokładny  = %.16f\\n\", x);\n  y = algorytm(n);\n  @printf(\"Wynik obliczony = %.16f   błąd względny = %.3e\\n\", y, abs(x-y)/x);\nend\n\ndoTest(wartoscDokladna_1e5, algorytm1, 1e5);\ndoTest(wartoscDokladna_1e5, algorytm2, 1e5);\n\ndoTest(wartoscDokladna_1e6, algorytm1, 1e6);\ndoTest(wartoscDokladna_1e6, algorytm2, 1e6);\n\n\n@printf(\"Precyzja arytmetyki = %.3e\\n\", 0.5*eps(real));\n", "meta": {"hexsha": "b427ec6d25aba67764993601204e7f288b7ca7ae", "size": 1288, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Analiza_Numeryczna_M/Przyklady/w2-01-suma.jl", "max_stars_repo_name": "Magikis/Uniwersity", "max_stars_repo_head_hexsha": "06964ef31d721af85740df1dce3f966006ab9f78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-11-30T08:45:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-26T14:15:45.000Z", "max_issues_repo_path": "Analiza_Numeryczna_M/Przyklady/w2-01-suma.jl", "max_issues_repo_name": "Magikis/Uniwersity", "max_issues_repo_head_hexsha": "06964ef31d721af85740df1dce3f966006ab9f78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Analiza_Numeryczna_M/Przyklady/w2-01-suma.jl", "max_forks_repo_name": "Magikis/Uniwersity", "max_forks_repo_head_hexsha": "06964ef31d721af85740df1dce3f966006ab9f78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2017-10-16T09:42:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-27T19:48:45.000Z", "avg_line_length": 24.7692307692, "max_line_length": 77, "alphanum_fraction": 0.6638198758, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7855747953992785}}
{"text": "# # Finding patterns in signals using Optimal Transport and Dynamic Time Warping\n\n# In this example we will compare different distances when used as the inner metric in a dynamic time-warping of spectrograms.\n# Setup\nusing DynamicAxisWarping, SpectralDistances, LPVSpectral, DSP, Plots, Statistics, BenchmarkTools, Distances, Random, ThreadTools, AlphaStableDistributions, SlidingDistancesBase\ntheme(:default)\ngr();\nRandom.seed!(0);\n\n# We start by creating a short patter, the *query*, we then create a long time series that contains a quite similar sound, but where the frequencies of the chirp are slightly higher. This is a realistic scenario when doing, e.g., acoustic detection. Different individuals within the same animal species might have similar calls, but slightly different pitch etc. We also add some alpha sub-gaussian noise in order to make the problem a bit harder.\n\nN       = 48_000 ÷ 2\nnfft    = 4096\nf1      = range(0.01, stop = 1, length = N)\nf2      = range(1, stop = 0.1, length = N) .^ 2\ng(x, N) = exp(-10 * (x - N / 2)^2 / N^2)\nt       = 1:N\ny10     = (sin.(t .* f1) .+ sin.(t .* (f2 .+ 0.4))) .* g.(t, N)\ny20     = (sin.(t .* (f1 .+ 0.5)) .+ sin.(t .* (f2 .+ 0.5))) .* g.(t, N)\nq       = Float32.(y10 .+ 0.2 .* randn.())\ny       = Float32.([0y20; 0y20; y20; 0y20; 0y20] .+ 1 .* randn.())\ny     .+= v1(rand(AlphaSubGaussian(n=length(y))));\n# y = repeat(y, 40) #src\n\nQ = melspectrogram(q, nfft, window = hanning, fmin = 400, fs = 48_000)\nY = melspectrogram(y, nfft, window = hanning, fmin = 400, fs = 48_000)\nplot(plot(Q, title = \"Query\"), plot(Y, title = \"Data\"), link = :both, layout = (2, 1))\n# We now see if we can detect the pattern using DTW with the standard squared Euclidean distance\nrad  = 10 # This is the maximum allowed warping radius\ndist = SqEuclidean()\nw    = DTWWorkspace(sqrt.(Q.power), dist, rad, Nothing)\nres  = dtwnn(w, sqrt.(Y.power))\nplot(Y);\nvline!([Y.time[res.loc]], l = (4, :blue), primary=false, yscale=:identity)\n# That did probably not go well at all! The line indicates where the smallest distance to the pattern was, i.e., where the nearest neighbor search thinks the *onset* of the pattern is.\n#---\n# Let's do the same with a transport-based distance\nn, m = size(Q.power)\ndist = DiscreteGridTransportDistance(Cityblock(), Float32, n, n)\nw    = DTWWorkspace(sqrt.(Q.power), dist, rad, Nothing)\nres  = dtwnn(w, sqrt.(Y.power))\nplot(Y);\nvline!([Y.time[res.loc]], l = (4, :blue), primary=false)\n# The line should now be a better indication of the onset of the pattern\n#---\n# Next, we plot the cost function for each time shift to see how they behave\nfunction naive(a, b, dist = SqEuclidean(), r = 7)\n    dists = map(1:lastlength(b)-lastlength(a)) do i\n        dtw_cost(a, b[!, i:i+lastlength(a)-1], dist, r)\n    end\nend\n\nplot()\nfor dist in [DiscreteGridTransportDistance(Cityblock(), Float32, n, n), SqEuclidean()]\n    @time res = naive(Q.power, Y.power, dist, rad)\n    res .-= minimum(res)\n    res ./= maximum(res)\n    plot!(res, lab = string(typeof(dist).name))\nend\nfig1 = vline!([2 * size(Y.power, 2) / 5], l = (4, :blue), primary=false)\n# The Euclidean distance is rather terrible for this task. The transport based distance seems to be doing the right thing.\n#---\n# unfortunately, calculating this using the transport-based distance takes quite a while\n@btime dtwnn($w, $(sqrt.(Y.power)), prune_endpoints=false)\n# while that might not seem like much, the data we're searching through only corresponds to this many seconds, if the sample rate is 48kHz\nlength(y) / 48000\n#---\n# We are thus intersted in distances that are faster to compute. We'll explore the OTRD distance, which performs optimal transport between the roots of a linear-system representation of the signal.\nfm  = TimeWindow(inner = LS(na = 8, λ=1e-3), n = nfft, noverlap = nfft÷2)\nQm  = fm(q) |> change_precision(Float64)\nYm  = fm(y) |> change_precision(Float64);\n# Let's see how the world looks like through the lens of autoregressive models\nplot(Qm, LPVSpectral.mel_to_hz(Q.mels)./48000, rad=false)\n#---\ndist  = OptimalTransportRootDistance(p = 1, β = 0.5)\ndistf = (x, y) -> evaluate(dist, x, y, tol = 1e-3)\nres   = naive(Qm.models, Ym.models, distf, rad)\nres .-= minimum(res)\nres ./= maximum(res)\nplot!(fig1, res, lab = \"OTRD\")\n# This should do an okay job, but is it fast?\n#---\nw = DTWWorkspace(Qm.models, distf, rad)\n@btime dtwnn($w, $(Ym.models), prune_endpoints=false)\n# About the same, but it could be much faster if the allocations were taken care of.\n# Let's speed up even further, using the root distance (RD)\nQe     = Float32.(reduce(hcat, embedding.(Qm.models))) # This extracts the roots of the linear system into a real vector\nYe     = Float32.(reduce(hcat, embedding.(Ym.models)))\ndist   = SqEuclidean();\n# dist   = EuclideanRootDistance(p=1, weight=e->sqrt.(residueweight(e))) #src\nres    = naive(Qe, Ye, dist, rad)\nres  .-= minimum(res)\nres  ./= maximum(res)\nplot!(res, lab = \"RD\")\n# This should do an okay job, but is it fast?\n#---\nw = DTWWorkspace(Qe, dist, rad)\ndtwnn(w, (Ye), prune_endpoints=false)\n@btime dtwnn($w, $(Ye), prune_endpoints=false)\n# That should be fast very, but there are still some room for improvements through early-termination heuristics.\nGC.gc(true); GC.gc(true) #src\n\n# ## Notes on futher performance improvements\n# Searching for the nearest neighbor using DTW tends to become relatively cheaper the longer the data searched through is. This is due to pruning heauristics that abort the search early based on the smallest distance found so far.\n# The main thing to watch out for is the length (in time) of the query sequence. Using a larger `nfft` effectively reduces the time resolution which greatly reduces the time-complexity, 𝒪(t²) if pruning heuristics are not effective.\n# Let's see how long time it takes to search through a much longer time series (note that estimating the models also takes quite a while, but this is 𝒪(t) expensive and can be easily parallelized so I don't count that for now)\nyl  = Float32.(repeat(y, 400) .+ 0.2 .* randn.())\nprintln(\"Length of singal: \", length(yl)/48_000/60, \" minutes, at 48kHz\")\nYml = fm(yl) |> change_precision(Float32);\nYel = reduce(hcat, embedding.(Yml.models))\nsleep(2) #src\n@btime dtwnn($w, $(Yel), prune_endpoints=true)\n\n\n# ### Future work\n# The mass normalization for spectrograms has to be improved. Currently, each spectrum (per time point) is normalized to sum to one. A perhaps better strategy is to normalize the entire spectrogram and then use unbalanced mass transport per time point.\n\nGC.gc(true); GC.gc(true) #src\n\n#---\n# # Transport in time\n# We can also consider using optimal transport along the time axis instead of DTW. Let's do the same stuff as above for the TimeDistance from SpectralDistances.jl\ndist = TimeDistance(inner=OptimalTransportRootDistance(p=1, β=0.5),tp=1,c=0.1)\nres   = SpectralDistances.distance_profile(dist, Qm, Ym)\nres .-= minimum(res)\nres ./= maximum(res)\nplot!(fig1, res, lab = \"Time transport\")\n#---\nfunction naive_time(a, b, dist)\n    n = length(a)\n    dists = map(1:length(b.models)-length(a.models)) do i\n        Y = TimeVaryingAR(b.models[i:i+length(a.models)-1])\n        dist(a, Y, tol=1e-3, check_interval=2)\n    end\nend\n@btime naive_time($Qm, $Ym, $dist);\n@btime SpectralDistances.distance_profile($dist, $(change_precision(Float32,Qm)), $(change_precision(Float32,Ym)), check_interval=5)\n# It appears to be surprisingly competitive, both in terms of accuracy and performance, even though it's evaluated using a rather naive method. Since the solver used to find the `TimeDistance` internally solves the *dual* problem, a lower bound of the objective function is always available for free during the optimization. This lower bound could be used to terminate the optimization early if it rises above the smallest distance found so far.\n\n@test mean(abs2, SpectralDistances.distance_profile(dist, Qm, Ym) - naive_time(Qm, Ym, dist)) < 1e-4\n", "meta": {"hexsha": "6f291ec21191c650bd12299ae1467a4180ed5e6c", "size": 7904, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/frequency_warping2.jl", "max_stars_repo_name": "paciops/DynamicAxisWarping.jl", "max_stars_repo_head_hexsha": "1c7dc135fd2964868fe148049a888538c3f3c21a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2020-04-24T13:09:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T23:34:19.000Z", "max_issues_repo_path": "examples/frequency_warping2.jl", "max_issues_repo_name": "paciops/DynamicAxisWarping.jl", "max_issues_repo_head_hexsha": "1c7dc135fd2964868fe148049a888538c3f3c21a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2020-04-25T08:24:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T06:46:00.000Z", "max_forks_repo_path": "examples/frequency_warping2.jl", "max_forks_repo_name": "paciops/DynamicAxisWarping.jl", "max_forks_repo_head_hexsha": "1c7dc135fd2964868fe148049a888538c3f3c21a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-05-14T10:47:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T13:14:10.000Z", "avg_line_length": 56.0567375887, "max_line_length": 447, "alphanum_fraction": 0.7096406883, "num_tokens": 2281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.7854939144500814}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.5\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 06240e71-df45-4f63-b797-4042432e6716\nusing FFTW, Plots, SampledSignals\n\n# ╔═╡ f8ba933c-a1e3-11eb-2263-17f14870c1fa\nmd\"# Basic Waveforms\nFirst let's see what basic waveforms can be made directly.\"\n\n# ╔═╡ bfacded1-6007-4e18-aba1-1b7325878dd2\nbegin\n    fs = 8000\n\tfreqs = SampleBuf(Array(LinRange(0, 2*pi*220, fs)), fs)\n\tt = Array(0:1/100:1) * 2 * pi\nend\n\n# ╔═╡ 65dbcdfe-2dbd-4b28-ab59-fb12425913ca\nfunction plotfreqs(tone, title)\n\tfreqs = fft(tone) |> fftshift\n\tdomain = FFTW.fftfreq(length(tone), fs) |> fftshift  \n    plot(domain, 10*log10.(abs.(freqs)/fs), title=title,\n\t\txlimit=(0, fs/2), ylimit=(-50, 0))\nend\n\n# ╔═╡ 4bd75a55-4457-4625-a184-a2f7490cbf0e\nmd\"## Sinusoids\nThe builtin sin() and cos() functions produce sinusoidal waves, they are roughly\nequivalent for this, being phase shifted versions of each other.\"\n\n# ╔═╡ 664b9502-13de-4fdf-971c-66cf0ea47c3b\nplot(t, sin.(t))\n\n# ╔═╡ 5e805acc-c6b1-4de5-8bc1-5bdcbd84ca04\nsine_tone = sin.(freqs)\n\n# ╔═╡ 2a51d397-322b-414b-9d9f-a1e8ba6b2364\nplotfreqs(sine_tone, \"Sine Spectrum\")\n\n# ╔═╡ dd813478-66a1-4d3e-9872-322e7b521e11\nmd\"## Modulo waveforms\n### Sawtooth\nUsing the periodic behavior of the remainder operator we get a sawtooth wave.\nHowever, making a sawtooth directly like this gives aliasing\nsince this equivalent to sampling an analog sawtooth wave with all harmonics.\nHarmonics higher than half the sampling rate cannot accurately be represented\nand appear as lower frequencies when reproducing the sound.\nThis aliasing shows up as noise in the signal that is visible on the frequency graph.\n\"\n\n# ╔═╡ a2357e48-116a-4df1-a52d-100533bad25d\nfunction saw(t)\n\tt/pi % 2 - 1\nend\n\n# ╔═╡ 50824ffc-622d-4a00-acce-558cecf79e55\nplot(t, saw.(t))\n\n# ╔═╡ 3ae066cb-b5f2-4913-8a73-20348a401026\nsaw_tone = saw.(freqs)\n\n# ╔═╡ 7bd89cfd-9894-4644-b0e4-cae8a63cda9a\nplotfreqs(saw_tone, \"Aliased Saw Spectrum\")\n\n# ╔═╡ dfa8eb03-2955-4bb6-b9ca-eb7cd6583e57\nmd\"\n### Triangle\nThe jagged shape of the sawtooth wave, with it's sharp discontinuity,\nis why it's higher harmonics are so loud.\nIf we use two ramps to remove the discontinuity we get a triangle wave \nwith harmonics that fall off more quickly.\nThe aliasing is reduced since the harmonics are softer by the time they reach the frequency limit. It also no longer has even harmonics, since the second half is the first half upside down.\"\n\n# ╔═╡ a9f4a512-c8b4-474a-a93c-2cef99db534c\nfunction tri(t)\n\tabs(t/pi%2-1)*2-1\nend\n\n# ╔═╡ f6f28913-cbfa-48f8-98ab-0d5ed267b350\nplot(t, tri.(t))\n\n# ╔═╡ 231185ea-8913-490d-8fe8-261983552457\ntri_tone = tri.(freqs)\n\n# ╔═╡ b627d7af-55d1-4d97-8f15-7f0d172f9b5a\nplotfreqs(tri_tone, \"Triangle Spectrum\")\n\n# ╔═╡ 99708158-d74e-4311-a10f-d0ac4f79d4f2\nmd\" ### Polynomial waveforms\nWe can use polynomials of a sawtooth wave to get various periodic waveforms.\nIf the two endpoints are equal the wave will be continuous.\nIf the derivitives at the endpoints are equal the waveform will be smooth.\nSmooth waveforms have harmonics that fall off even faster than continuous waveforms.\n\nUsing a parabola we get harmonic roll-off similar to a triangle wave\nbut including the even harmonics:\n\"\n\n# ╔═╡ 1f127661-47b0-4498-9fc2-857f314b6869\nfunction poly2(t)\n\t\"\"\"\n\tParabolic waveform\n\tsince t^2 gives output in [0, 1] we use 2t^2-1 to get output in [-1,1]\n\t\n\tNote that since f' = 2x + b is linear we can't make a smooth function\n\tsince no two points can be equal\n\t\"\"\"\n\tt = t/pi %2 -1\n\t2*t*t - 1\nend\n\n# ╔═╡ 99f21cb1-b50f-4e8b-9d97-8bf5297afbec\npoly2_tone = poly2.(freqs)\n\n# ╔═╡ 8802e5fe-8416-4c67-a1f0-b99bb6af3e3f\nplot(t, poly2.(t))\n\n# ╔═╡ b561d76e-e2a7-4c3d-9677-42f8b5661b7c\n# Kind of like a triangle wave but with even harmonics\nplotfreqs(poly2_tone, \"Poly2 Spectrum\")\n\n# ╔═╡ 09d7e4f3-fed8-4fc8-b598-03ecc8e75d6f\nmd\"With a cubic we can get a smooth function.\nThis has harmonics that fall off quickly enough that there is no noticable aliasing,\neven at this low of a samplerate.\n\"\n\n# ╔═╡ aff77549-c6da-4329-8e92-5f1fb561ece6\nfunction poly3(t)\n\t\"\"\"\n\tf(x) = x^3 + bx^2 + cx\n\tfunction is continuous when\n\t1 + b + c = f(1) = f(-1) = -1 + b - c\n\t2c = -2, c = -1\n\t\n\tf'(x) = 3x^2 + 2bx - 1\n\tfunction is smooth when\n    3 + 2b - 1 = f'(1) = f'(-1) = 3 - 2b - 1\n\t4b = 0, b = 0\n\n\tf(x) = x^3 - x\n\tf'(x) = 3x^2-1 = 0  when x = +-1/sqrt(3)\n\tf(-1/sqrt(3)) = -1/sqrt(3)/3+1/sqrt(3) = 2/(3sqrt(3))\n\tWe scale by the inverse 3sqrt(3)/2\n\t\"\"\"\n\tt = t/pi%2-1\n\tx = 3*sqrt(3)/2*t*(t*t - 1)\nend\n\n# ╔═╡ e91b624c-cef9-4f74-8bf0-76a484c9c895\npoly3_tone = poly3.(freqs)\n\n# ╔═╡ 6880cf94-23ee-4a96-8b9f-0417fc239374\nplot(t, poly3.(t))\n\n# ╔═╡ 4caa26e8-c5ce-4d30-b80b-d3ed7659efa0\n# Here there is no aliasing >-40db\nplotfreqs(poly3_tone, \"Poly3 Spectrum\")\n\n# ╔═╡ 1701a11b-b17b-499a-bf5f-0d721c026590\nmd\"As we smooth the function more by setting higher derivitives equal\nthe polynomials approach a pure sine tone\"\n\n# ╔═╡ e060b886-4af2-4692-8882-79ceabe64ff1\nfunction normalize(tone)\n\t\"\"\" Normalizing polynomial waveforms directly is annoying\n\tso we will use this function instead of calculating minimum and maximums\"\"\"\n\tm = minimum(tone)\n\tM = maximum(tone)\n\t2*(tone.-m)/(M-m) .-1\nend\n\n# ╔═╡ 85236c40-9c9c-4e00-b8e8-54787a5760af\nfunction poly4(t, b)\n\t\"\"\"\n\tf = x^4 + bx^3 + cx^2 + dx\n\t1+b+c+d = f(1) = f(-1) = 1-b+c-d\n\t2(b+d) = 0, b+d = 0, d = -b\n\t-4+3b+2c-b = f'(1) = f'(-1) = -4+3b-2c-b\n\t2(4+2c) = 0, 4+2c = 0, c = -2\n\tf = x^4 + bx^3 - 2x^2 - bx\n\t\"\"\"\n\tt = t/pi%2-1\n\tt = (((t + b)*t -2)*t - b)*t\nend\n\n# ╔═╡ f1a60f5c-53c6-4533-b3ed-e715fb67d7ba\npoly4_tone = normalize(poly4.(freqs, 0))\n\n# ╔═╡ 788ec89e-c1d0-498b-8e8c-82de0bc4eda6\nplot(t, normalize(poly4.(t, 0)))\n\n# ╔═╡ e24388fa-d474-4770-95a0-d34627ae7a04\n# No overtones reach the niquist rate, no aliasing at all\nplotfreqs(poly4_tone, \"Poly4 Spectrum\")\n\n# ╔═╡ bf89825a-944b-4771-a619-e4c5d1220f61\nfunction poly5(t)\n\t\"\"\"\n\tf = ax^5 + bx^4 + cx^3 + dx^2 + ex + f\n\tf(-1) = 0 = -a + b -c + d + -e + f\n\ta+c+e = b+d+f\n\tf(1) = 0 = a+b+c+d+e+f = 2*(a+c+e) => a+c+e = 0\n\t5a-4b+3c-2d+e = f'(-1) = f'(1) = 5a+4b+3c+2d+e\n\t<=> 4b + 2d = 0 <=> d = -2b\n\tb - 2b + f = 0\n\tf = b\n\t20a+12b+6c+2d = f''(1) = f''(-1) = -20a +12b -6c +2d\n\t40a + 12 c = 0\n\tc = -10/3a\n\t60a+24b+6c = f'''(1) = f'''(-1) = 60a -24b + 6c\n\tb = 0\n\t\"\"\"\n    t = t/pi%2-1\n\ta = 1\n\tc = -10/3*a\n\tb = 0\n\t((((a*t + b)*t + c)*t - 2*b)*t-(c + a))*t + b\nend\n\n# ╔═╡ 076a215e-1335-4974-b61e-06fa4c9e9295\nbegin\n\tplot(t, -normalize(poly5.(t)))\n\tplot!(t, sin.(t))\nend\n\n# ╔═╡ e5ac5d3e-1240-4a3c-bc9a-d8e8e6fec60f\npoly5_tone = normalize(poly5.(freqs))\n\n# ╔═╡ 82c3a459-0944-4637-a481-cafd15402afe\n# We can see the progression of higher degree waveforms approaching the sine wave spectrum\nplotfreqs(poly5_tone, \"Poly5 Spectrum\")\n\n# ╔═╡ 36e284d1-a982-45c2-a0cc-dae1cc355362\nmd\"## Odd harmonics\nTo get only odd harmonics \nwe need the second half of the waveform \nto be the negative of the first half.\nThis sounds like we need an odd function where $f(-x) = -f(x)$,\nbut this would have the second half in reverse order.\nWe actually need a function where for some a, $f(x+a) = -f(x)$.\nThe only functions like that everywhere are already periodic,\nsince $f(x+2a) = -f(x+a) = f(x)$. \nSo we can't solve for polynomials like before.\n\nHowever a waveform with this property can be constructed very easily piecewise\nas $g(x) = \\{f(x)$ if $x > 0$ else $-f(x+1)\\}$ from any function defined on the interval $[0,1]$.\nUsing the sign of $x$ we can remove the if statement by taking\n$g(x) = \\text{sign}(x)f(2x-\\text{sign}(x))$ on the interval $[-1, 1]$, \nfor a function $f(x)$ on $[-1, 1]$.\n\nFor the resulting function to be connected we need $f(-1) = f(1) = 0$.\nFor this function to be smooth we need $f'(-1) = -f'(1)$ as well.\nAny even function ($f(x) = f(-x)$ everywhere) has both these properties,\nprovided that it is smooth on the interval and it is translated so that it's\nendpoints are $0$.\n\"\n\n\n\n# ╔═╡ 3e73b73b-79a3-4ba6-bfc5-94f39816680f\nfunction para(t)\n\t\"\"\" f(x) = x^2-1\n\tg(x) = sign(x)f(2x-sign(x)) \n\t= sign(x)((2x-sign(x))^2-1) = sign(x)((4x^2 -4xsign(x) + 1)-1)\n\t= 4*x(abs(x)-1)\n\t\"\"\"\n\tt = t/pi%2-1\n\t4*t*(abs(t)-1)\nend\n\n# ╔═╡ 97ec7198-36e8-410b-9602-d6b61f31db6b\nbegin\n\tplot(t, para.(t))\n\tplot!(t, sin.(t))\nend\n\n# ╔═╡ 2765c9be-3636-45de-9804-7fecb69f4a7b\npara_tone = para.(freqs)\n\n# ╔═╡ 52f4cba9-6eb4-42fe-bef5-8ea1a0f4e18a\nplotfreqs(para_tone, \"Parabola Spectrum\")\n\n# ╔═╡ 0ade700b-6193-4518-8470-bb787f87ba47\nfunction ecubic(t)\n\t\"\"\" \n\tf(x) = abs(x)^3-1\n\tg(x) = sign(x)f(2x-sign(x))\n         = sign(x)(abs(2x-sign(x))^3-1)\n\t\"\"\"\n\tt = t/pi%2-1\n\ts = sign(t)\n\tt = s*(abs(2*t-s)^3-1)\nend\n\n# ╔═╡ f116f443-0643-4cbb-8da8-4f9a312fd82f\nplot(t, ecubic)\n\n# ╔═╡ 35acdceb-34f5-4a39-aa06-569ab6f16205\necubic_tone = ecubic.(freqs)\n\n# ╔═╡ d7f37c37-a912-4324-8ca2-063f7c1f3ebc\nplotfreqs(ecubic_tone, \"Even Cubic Spectrum\")\n\n# ╔═╡ f86cda73-edd8-4905-81e0-83a6529daacc\nfunction quart(t)\n\t\"\"\" \n\tf(x) = x^4-1\n\tg(x) = sign(x)((2x-sign(x))^4-1)\n\t\"\"\"\n\tt = t/pi%2-1\n\ts = sign(t)\n\tt = s*((2*t-s)^4-1)\nend\n\n# ╔═╡ 89fee0e4-7e7f-400b-9cc2-8b3186ab0384\nplot(t, quart.(t))\n\n# ╔═╡ b649ead1-acf8-4390-bb9e-ae876a1c7f48\nquart_tone = quart.(freqs)\n\n# ╔═╡ c492d40f-fc0d-4b06-a925-7c75bff32503\nplotfreqs(quart_tone, \"Quartic Spectrum\")\n\n# ╔═╡ d5e54701-36a3-45f9-ac2c-8917b2e3a09d\nmd\"Polynomial methods are cheap to compute and have more tone than a pure sine wave but aren't inherently bandlimited and so can't make brighter sounds similar to analog square or saw waves without aliasing.\"\n\n# ╔═╡ Cell order:\n# ╟─f8ba933c-a1e3-11eb-2263-17f14870c1fa\n# ╠═06240e71-df45-4f63-b797-4042432e6716\n# ╠═bfacded1-6007-4e18-aba1-1b7325878dd2\n# ╠═65dbcdfe-2dbd-4b28-ab59-fb12425913ca\n# ╟─4bd75a55-4457-4625-a184-a2f7490cbf0e\n# ╠═664b9502-13de-4fdf-971c-66cf0ea47c3b\n# ╠═5e805acc-c6b1-4de5-8bc1-5bdcbd84ca04\n# ╠═2a51d397-322b-414b-9d9f-a1e8ba6b2364\n# ╠═dd813478-66a1-4d3e-9872-322e7b521e11\n# ╠═a2357e48-116a-4df1-a52d-100533bad25d\n# ╠═50824ffc-622d-4a00-acce-558cecf79e55\n# ╠═3ae066cb-b5f2-4913-8a73-20348a401026\n# ╠═7bd89cfd-9894-4644-b0e4-cae8a63cda9a\n# ╠═dfa8eb03-2955-4bb6-b9ca-eb7cd6583e57\n# ╠═a9f4a512-c8b4-474a-a93c-2cef99db534c\n# ╠═f6f28913-cbfa-48f8-98ab-0d5ed267b350\n# ╠═231185ea-8913-490d-8fe8-261983552457\n# ╠═b627d7af-55d1-4d97-8f15-7f0d172f9b5a\n# ╟─99708158-d74e-4311-a10f-d0ac4f79d4f2\n# ╠═1f127661-47b0-4498-9fc2-857f314b6869\n# ╠═99f21cb1-b50f-4e8b-9d97-8bf5297afbec\n# ╠═8802e5fe-8416-4c67-a1f0-b99bb6af3e3f\n# ╠═b561d76e-e2a7-4c3d-9677-42f8b5661b7c\n# ╠═09d7e4f3-fed8-4fc8-b598-03ecc8e75d6f\n# ╠═aff77549-c6da-4329-8e92-5f1fb561ece6\n# ╠═e91b624c-cef9-4f74-8bf0-76a484c9c895\n# ╠═6880cf94-23ee-4a96-8b9f-0417fc239374\n# ╠═4caa26e8-c5ce-4d30-b80b-d3ed7659efa0\n# ╠═1701a11b-b17b-499a-bf5f-0d721c026590\n# ╠═e060b886-4af2-4692-8882-79ceabe64ff1\n# ╠═85236c40-9c9c-4e00-b8e8-54787a5760af\n# ╠═f1a60f5c-53c6-4533-b3ed-e715fb67d7ba\n# ╠═788ec89e-c1d0-498b-8e8c-82de0bc4eda6\n# ╠═e24388fa-d474-4770-95a0-d34627ae7a04\n# ╠═bf89825a-944b-4771-a619-e4c5d1220f61\n# ╠═076a215e-1335-4974-b61e-06fa4c9e9295\n# ╠═e5ac5d3e-1240-4a3c-bc9a-d8e8e6fec60f\n# ╠═82c3a459-0944-4637-a481-cafd15402afe\n# ╠═36e284d1-a982-45c2-a0cc-dae1cc355362\n# ╠═3e73b73b-79a3-4ba6-bfc5-94f39816680f\n# ╠═97ec7198-36e8-410b-9602-d6b61f31db6b\n# ╠═2765c9be-3636-45de-9804-7fecb69f4a7b\n# ╠═52f4cba9-6eb4-42fe-bef5-8ea1a0f4e18a\n# ╠═0ade700b-6193-4518-8470-bb787f87ba47\n# ╠═f116f443-0643-4cbb-8da8-4f9a312fd82f\n# ╠═35acdceb-34f5-4a39-aa06-569ab6f16205\n# ╠═d7f37c37-a912-4324-8ca2-063f7c1f3ebc\n# ╠═f86cda73-edd8-4905-81e0-83a6529daacc\n# ╠═89fee0e4-7e7f-400b-9cc2-8b3186ab0384\n# ╠═b649ead1-acf8-4390-bb9e-ae876a1c7f48\n# ╠═c492d40f-fc0d-4b06-a925-7c75bff32503\n# ╟─d5e54701-36a3-45f9-ac2c-8917b2e3a09d\n", "meta": {"hexsha": "1e941312944a5fe1d663f148ae17c75e1982c1b2", "size": 11532, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "DirectSynthesis.jl", "max_stars_repo_name": "jnha/music", "max_stars_repo_head_hexsha": "b46dadd8b1e972a6d3441c09d1f1bba8b786087a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DirectSynthesis.jl", "max_issues_repo_name": "jnha/music", "max_issues_repo_head_hexsha": "b46dadd8b1e972a6d3441c09d1f1bba8b786087a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DirectSynthesis.jl", "max_forks_repo_name": "jnha/music", "max_forks_repo_head_hexsha": "b46dadd8b1e972a6d3441c09d1f1bba8b786087a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.03125, "max_line_length": 208, "alphanum_fraction": 0.6971037114, "num_tokens": 5554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.785493912753285}}
{"text": "\n\"\"\"\n    normalize(x)\n\nTransforms a univariate array into a 0 mean and unit standard deviation array.\n\n# Examples\n\n```jldoctest\njulia> GrammianAngularFields.normalize(collect(1:5))\n5-element Array{Float64,1}:\n -1.2649110640673518\n -0.6324555320336759\n  0.0               \n  0.6324555320336759\n  1.2649110640673518\n```\n\"\"\"\nfunction normalize(x::AbstractVector)\n    m = StatsBase.mean(x)\n    (x .- m) ./ StatsBase.stdm(x, m)\nend\n\n\"\"\"\n    standardize(x)\n\nTransforms a univariate array into a 0, 1 range.\n\"\"\"\nfunction standardize(x::AbstractVector)\n    (x .- minimum(x)) ./ (maximum(x)-minimum(x))\nend\n\n\"\"\"\n    standardize(x, a, b)\n\nTransforms a univariate array into a a, b range.\n\"\"\"\nfunction standardize(x::AbstractVector, a::Number, b::Number)\n    standardize(x) .* (b-a) .+ a\nend\n\n\n", "meta": {"hexsha": "0363472cd0fec074b9c7f7d8053d9906d82e1754", "size": 783, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transformations.jl", "max_stars_repo_name": "DoktorMike/GrammianAngularFields.jl", "max_stars_repo_head_hexsha": "56678d5cfa5b3b382b4df5ea3cd41ae4ebf17192", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/transformations.jl", "max_issues_repo_name": "DoktorMike/GrammianAngularFields.jl", "max_issues_repo_head_hexsha": "56678d5cfa5b3b382b4df5ea3cd41ae4ebf17192", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/transformations.jl", "max_forks_repo_name": "DoktorMike/GrammianAngularFields.jl", "max_forks_repo_head_hexsha": "56678d5cfa5b3b382b4df5ea3cd41ae4ebf17192", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.2093023256, "max_line_length": 78, "alphanum_fraction": 0.6692209451, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418199787566, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7854939092016746}}
{"text": "#!/usr/bin/env julia\nusing Printf\n\nfunction ζ(N::Int64,a::Int64)\n  s = 0.0\n  @simd for i ∈ 1:N\n    s+=(1.0/i)^a\n  end\n  s\nend\n\nN = 16000000000\n@time ζ_2 = ζ(N,2)\nπ_squared_over_6 = π^2 / 6.0;\n\n@printf \"      ζ(2) = %18.16f\\n\" ζ_2\n@printf \"π^2 / 6.0  = %18.16f\\n\" π_squared_over_6\n@printf \"     error = %18.16f\\n\" π_squared_over_6 - ζ_2\n", "meta": {"hexsha": "f19b642d772e8049dc41fa7c7279fede6c4ab5e0", "size": 336, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/rzf_simd.jl", "max_stars_repo_name": "joelandman/rzf", "max_stars_repo_head_hexsha": "11f88f846da27ea355578c517fe5a3caf8b80315", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-11-15T23:33:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T06:01:16.000Z", "max_issues_repo_path": "julia/rzf_simd.jl", "max_issues_repo_name": "joelandman/rzf", "max_issues_repo_head_hexsha": "11f88f846da27ea355578c517fe5a3caf8b80315", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/rzf_simd.jl", "max_forks_repo_name": "joelandman/rzf", "max_forks_repo_head_hexsha": "11f88f846da27ea355578c517fe5a3caf8b80315", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.6842105263, "max_line_length": 55, "alphanum_fraction": 0.5892857143, "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7854939074851257}}
{"text": "# Uncomment below if the package is not already installed\n#using Pkg; Pkg.add(\"DifferentialEquations\") \n\nusing DifferentialEquations, PyPlot\nf(y,p,t) = [y[2], -sin(y[1])]\ny0 = [2.5, 0]\n\ntspan = (0.0, 10.0)\n\nprob = ODEProblem(f, y0, tspan)\nsol = solve(prob, abstol=1e-8, reltol=1e-8);\n\ndisplay(hcat(sol.t, collect(sol.u)))\n\ntt = 0:0.1:10\nplot(tt, sol.(tt));\nlegend((\"\\$\\\\theta(t)\\$\", \"\\$\\\\theta'(t)\\$\"));\n\ncondition(y, t, integrator) = y[2]\n\naffect!(integrator) = terminate!(integrator)\n\ncb = ContinuousCallback(condition, affect!)\nsol = solve(prob, callback=cb, abstol=1e-8, reltol=1e-8)\nprintln(\"Period = $(2sol.t[end])\")\n\n\n", "meta": {"hexsha": "0838b4c975221e18d914cbd37dd3b439448f7a26", "size": 625, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Differential_Equations/DifferentialEquations_Package.jl", "max_stars_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_stars_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "textbook/_build/jupyter_execute/content/Differential_Equations/DifferentialEquations_Package.jl", "max_issues_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_issues_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "textbook/_build/jupyter_execute/content/Differential_Equations/DifferentialEquations_Package.jl", "max_forks_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_forks_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3214285714, "max_line_length": 57, "alphanum_fraction": 0.6528, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217417, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.785493905610559}}
{"text": "\n\n\nfunction bracket_sign_change(f′, a, b; k=2)\n    if a > b; a,b = b,a; end # ensure a < b\n    center, half_width = (b+a)/2, (b-a)/2\n    while f′(a)*f′(b) > 0\n        half_width *= k\n        a = center - half_width\n        b = center + half_width\n    end\n    return (a,b)\nend\n    \n\ndf(x) = 10*cos(10*x)-3*sin(3*x)\n\nas,bs = bracket_sign_change(df,3.4,3.8)\nas,df(as),bs,df(bs)", "meta": {"hexsha": "ff2f97f3766cf44632d5ae7b2712ea17479d9f5a", "size": 374, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Bracket_Sign_Change.jl", "max_stars_repo_name": "GilbertoLucas/Structural_Optimization", "max_stars_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Bracket_Sign_Change.jl", "max_issues_repo_name": "GilbertoLucas/Structural_Optimization", "max_issues_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Bracket_Sign_Change.jl", "max_forks_repo_name": "GilbertoLucas/Structural_Optimization", "max_forks_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6842105263, "max_line_length": 43, "alphanum_fraction": 0.5347593583, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7854939038742583}}
{"text": "##############################################################################\n#\n# REFERENCES: Using definition from Devroye, IX.7\n#  This definition differs from definitions on Wikipedia and other sources,\n#  where distribution is over [0, 1] rather than [-1, 1].\n#\n##############################################################################\n\nimmutable Arcsine <: ContinuousUnivariateDistribution\nend\n\nfunction cdf(d::Arcsine, x::Number)\n    if x < -1.0\n        return 0.0\n    elseif x > 1.0\n        return 1.0\n    else\n        return (2.0 / pi) * asin(sqrt((x + 1.0) / 2.0))\n    end\nend\n\nentropy(d::Arcsine) = -log(2.0) / pi\n\nfunction insupport(d::Arcsine, x::Number)\n    if -1.0 <= x <= 1.0\n        return true\n    else\n        return false\n    end\nend\n\nmean(d::Arcsine) = 0.0\n\nmedian(d::Arcsine) = 0.0\n\nfunction pdf(d::Arcsine, x::Number)\n    if insupport(d, x)\n        return 1.0 / (pi * sqrt(1.0 - x^2))\n    else\n        return 0.0\n    end\nend\n\nquantile(d::Arcsine, p::Real) = 2.0 * sin((pi / 2.0) * p)^2 - 1.0\n\nrand(d::Arcsine) = sin(2.0 * pi * rand())\n\nskewness(d::Arcsine) = 0.0\n\nvar(d::Arcsine) = 1.0 / 2.0\n", "meta": {"hexsha": "3591a5232b9fa8b5e14a100d365eb9ac4688be3f", "size": 1120, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/arcsine.jl", "max_stars_repo_name": "mewo2/Distributions.jl", "max_stars_repo_head_hexsha": "00dd06fb13632b9f0259f036bb861e47b7170a76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-16T01:43:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-16T01:43:20.000Z", "max_issues_repo_path": "src/univariate/arcsine.jl", "max_issues_repo_name": "mewo2/Distributions.jl", "max_issues_repo_head_hexsha": "00dd06fb13632b9f0259f036bb861e47b7170a76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/arcsine.jl", "max_forks_repo_name": "mewo2/Distributions.jl", "max_forks_repo_head_hexsha": "00dd06fb13632b9f0259f036bb861e47b7170a76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9607843137, "max_line_length": 78, "alphanum_fraction": 0.5044642857, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7854939003819046}}
{"text": "# This module solves the Ramsey problem for the quasi linear case\n# We'll try to replicate figures from quant econ https://python-advanced.quantecon.org/opt_tax_recur.html#top\n\n#----------------- CHECKING WITH QUANTECON ---------------------------------------------------#\n## Parameters\nβ = 0.9;\nσ = 2;\nγ = 2;\n\n## Utility functions\nu(x) = x^(1 - σ) / (1 - σ);\nv(x) = x^(1 + γ) / (1 + γ);\nU(c, n) = u(c) - v(n);\n\n## Differentials\nUc(c) = ForwardDiff.derivative(u, c);\nUcc(c) = ForwardDiff.derivative(Uc, c);\n\nUn(n) = -ForwardDiff.derivative(v, n);\nUnn(n) = ForwardDiff.derivative(Un, n);\n\n## Defining states\ng = [0.1; 0.1; 0.1; 0.1; 0.2; 0.1];\nθ = ones(length(g));\ns = [(1.0, g[i]) for i in 1:6];\nPs = [0.0 1.0 0.0 0.0 0.0 0.0;\n      0.0 0.0 1.0 0.0 0.0 0.0;\n      0.0 0.0 0.0 0.5 0.5 0.0;\n      0.0 0.0 0.0 0.0 0.0 1.0;\n      0.0 0.0 0.0 0.0 0.0 1.0;\n      0.0 0.0 0.0 0.0 0.0 1.0];\n\ninclude(\"NewtonRoot.jl\");\n\n## This function calculates Ramsey Allocation, given Φ and initial state s0 \nfunction RamseyAllocation(Φ::Real, s0::Tuple)\n\n    function time1_allocation(s::Tuple)\n        θ, g = s[1], s[2];\n        n(c::Real) = (g + c) / θ;\n        res1(c::Real) = (1 + Φ) * (Uc(c) * θ + Un(n(c))) + Φ * (c * Ucc(c) * θ + n(c) * Unn(n(c)));\n        c = NewtonRoot(c -> res1(c), 0.5);\n\n        return c, n(c)\n    end\n\n    c_time1 = [time1_allocation(s[i])[1] for i in 1:length(s)];\n    n_time1 = [time1_allocation(s[i])[2] for i in 1:length(s)];\n\n    function time0_allocation(s::Tuple)\n        θ, g = s[1], s[2];\n        n(c::Real) = (g + c) / θ;\n        b0(c::Real) = 1.0;\n        res0(c::Real) = (1 + Φ) * (Uc(c) * θ + Un(n(c))) + Φ * (c * Ucc(c) * θ + n(c) * Unn(n(c))) - Φ * Ucc(c) * b0(c) * θ\n        c = NewtonRoot(c -> res0(c), 0.5)\n\n        return c, n(c)\n    end\n\n    c_time0, n_time0 = time0_allocation(s0)[1], time0_allocation(s0)[2];\n\n    return c_time1, n_time1, c_time0, n_time0\n\nend\n\nc_time1, n_time1, c_time0, n_time0 = RamseyAllocation(0.06175628494006816, s[1])\n\nsum_mat = inv(1.0I - β * Ps) * (Uc.(c_time1) .* c_time1 .+ Un.(n_time1) .* n_time1);\n\nResImC = Uc(c_time0) - Uc(c_time0) * c_time0 - Un(n_time0) * n_time0 - β * sum([Ps[1,i]*sum_mat[i] for i in 1:length(sum_mat)]);\n\nb_time1 = sum_mat ./ Uc.(c_time1);\nb_time0 = 1.0;\n\nτ_time1 = [1.0 + Un(n_time1[i]) / Uc(c_time1[i]) for i in 1:length(s)];\n\n\n\n\nfunction search_Φ(Φ::Real, s0::Tuple)\n    c_time1, n_time1, c_time0, n_time0 = RamseyAllocation(Φ, s0);\n    \n    i_s0 = findfirst(isequal(s0), s);\n\n    sum_mat = inv(1.0I - β * Ps) * (Uc.(c_time1) .* c_time1 .+ Un.(n_time1) .* n_time1); #this sum is independent of s0\n\n    implementCons = Uc(c_time0) - Uc(c_time0) * c_time0 - Un(n_time0) * n_time0 - β * sum([Ps[i_s0,i] * sum_mat[i] for i in 1:length(sum_mat)]);\n\n    return implementCons\n\nend\n\nΦ_est = NewtonRoot(x -> search_Φ(x, s[1]), 0.1); # 0.06175628494006816\n\nτ_time0 = 0.0;\n\n## Plotting\nsHist_h = [2, 3, 4, 6, 6, 6];\nsHist_l = [2, 3, 5, 6, 6, 6];\n\nc_sim_h = [c_time1[i] for i in sHist_h];\nc_sim_l = [c_time1[i] for i in sHist_l];\n\nn_sim_h = [n_time1[i] for i in sHist_h];\nn_sim_l = [n_time1[i] for i in sHist_l];\n\nb_sim_h = [b_time1[i] for i in sHist_h];\nb_sim_l = [b_time1[i] for i in sHist_l];\n\nτ_sim_h = [τ_time1[i] for i in sHist_h];\nτ_sim_l = [τ_time1[i] for i in sHist_l];\n\nc_plot_h = vcat(c_time0, c_sim_h)\nc_plot_l = vcat(c_time0, c_sim_l)\n\nn_plot_h = vcat(n_time0, n_sim_h)\nn_plot_l = vcat(n_time0, n_sim_l)\n\nb_plot_h = vcat(b_time0, b_sim_h)\nb_plot_l = vcat(b_time0, b_sim_l)\n\nτ_plot_h = vcat(τ_time0, τ_sim_h)\nτ_plot_l = vcat(τ_time0, τ_sim_l)\n\n\nplot(c_plot_h, label=\"g high\")\nplot!(c_plot_l, label = \"g low\")\n\nplot(n_plot_h, label=\"g high\")\nplot!(n_plot_l, label = \"g low\")\n\nplot(b_plot_l, label=\"g high\")\nplot!(b_plot_h, label = \"g low\")\n\nplot(τ_plot_l, label=\"g high\")\nplot!(τ_plot_h, label = \"g low\")", "meta": {"hexsha": "67910ddfdfa618f239dbbc5b70e144efc70cb60b", "size": 3793, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Anmol/PS2/QuantEcon_check.jl", "max_stars_repo_name": "wongr003/ECON8185", "max_stars_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Anmol/PS2/QuantEcon_check.jl", "max_issues_repo_name": "wongr003/ECON8185", "max_issues_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Anmol/PS2/QuantEcon_check.jl", "max_forks_repo_name": "wongr003/ECON8185", "max_forks_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8897058824, "max_line_length": 144, "alphanum_fraction": 0.5889796994, "num_tokens": 1571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.785475711772849}}
{"text": "#=\n    Network generation.\n=#\n\n\"\"\"\n    Returns an Erdos-Renyi random graph according to the G(N, p) model.\n\n    Args:\n        N:\n            Total number of nodes of the graph.\n        p:\n            Probability of existence between pair of nodes.\n        is_directed:\n            Boolean to signal whether the final graph is undirected or \n            directed.\n        self:\n            {default=false} Boolean to signal whether self-loops are allowed.\n    Return:\n        graph:\n            'Graph' structure representing the final graph according to G(N,p).\n\"\"\"\nfunction erdos_renyi_net(N::Int, p::Float64, is_directed::Bool, self=false)\n    if p<=0 || p>=1\n        return\n    end\n\n    graph = Graph(is_directed)\n    for i in 1:N\n        add_node(graph)\n    end\n\n    w = -1\n    lp = log(1.0-p)\n\n    if is_directed # ----- directed -----\n        v = 0\n        while v < N\n            mu = rand(1)[1]\n            lr =  log(1.0 - mu)\n            w += (1 +  floor(Int, lr/lp))\n            while v<N && N<=w\n                w -= N\n                v += 1\n            end\n            if v < N\n                if v==w && self\n                    add_edge(v+1, w+1, graph)\n                elseif v!=w\n                    add_edge(v+1, w+1, graph)\n                end\n            end\n        end\n    else # ----- undirected -----\n        v = 1\n        while v < N\n            mu = rand(1)[1]\n            lr = log(1.0 - mu)\n            w += 1 + floor(Int, lr/lp)\n            while w >= v && v < N\n                w -= v\n                v += 1\n            end\n            if v < N\n                add_edge(v+1, w+1, graph)\n            end\n        end\n    end\n    return graph\nend\n\n\"\"\"\n    Generate a random graph by parsing G(N, \\$\\\\langle k \\\\rangle\\$) where \n    \\$\\\\langle k \\\\rangle\\$ is the desired mean degree of the final graph.\n\n    Args:\n        N:\n            Total number of nodes of the graph.\n        k_mean:\n            Expected mean degree of the generated graph.\n        is_directed:\n            Boolean to signal whether the final graph is undirected or \n            directed.\n        self:\n            {default=false} Boolean to signal whether self-loops are allowed.\n    Return:\n        graph:\n            'Graph' structure representing the final ER graph with the expected \n            mean degree.\n\"\"\"\nfunction ER_k(N::Int, k_mean::Float64, is_directed::Bool, self=false)\n    p = k_mean/(N-1)\n    graph = erdos_renyi_net(N, p, is_directed, self)\n    return graph\nend\n\n\"\"\"\n    Generate a random graph by parsing the total number of nodes, expected \n    mean degree and number of edge types.\n\n    Args:\n        N:\n            Total number of nodes of the graph.\n        k_mean:\n            Expected mean degree of the generated graph.\n        n_types:\n            Number of edge types for the final graph.\n        is_directed:\n            Boolean to signal whether the final graph is undirected or \n            directed.\n        self:\n            {default=false} Boolean to signal whether self-loops are allowed.\n    Return:\n        graph:\n            'Graph' structure representing the final ER graph with the expected \n            mean degree and number of edge types. This final graph contains an \n            edge property with name \"edgetype\".\n\"\"\"\nfunction ER_multi(N::Int, k_mean::Float64, n_types::Int, is_directed::Bool, self=false)\n    graph = ER_k(N, k_mean, is_directed, self)\n    possible_types = [j for j in 1:n_types]\n\n    edgetypes_prop = [ rand(possible_types) for j in 1:length(graph.edges) ]\n    set_edges_properties(\"edgetype\", edgetypes_prop, graph)\n    return graph\nend\n\n\"\"\"\n    Specific for exporting the generated Erdos-Renyi random graphs.\n    The only metadata exported together with the edgelist is the integer\n    \"edgetype\" property\n\n    Args:\n        graph:\n            'Graph' structure containing the \"edgetype\" integer property.\n        fout:\n            filename to where the edgelist should be exported.\n\"\"\"\nfunction export_edgefile_csv(graph::Graph, fout::String)\n    edges = graph.edges\n    edgetype = graph.int_eproperties[\"edgetype\"]\n    source_arr, target_arr = Int[], Int[]\n    type_arr = Int[]\n    for edge in edges\n        push!(source_arr, edge.source)\n        push!(target_arr, edge.target)\n        push!(type_arr, edgetype[edge.index])\n    end\n    CSV.write(fout, DataFrame([source_arr, target_arr, type_arr], [:Source, :Target, :Type]))\nend\n\n# To delete\n\"\"\"\n    Function specific for exporting the generated random networks.\n    The only metadata exported together is the \"edgetype\" property.\n\"\"\"\nfunction export_edgefile(graph::Graph, fout::String)\n    edges = graph.edges\n    edgetype = graph.int_eproperties[\"edgetype\"]\n    open(\"$fout.txt\", \"w\") do f\n        for edge in edges\n            write(f, \"$(edge.source)\\t$(edge.target)\\t$(edgetype[edge.index])\\n\")\n        end\n    end\nend", "meta": {"hexsha": "1e0eaa9d80cb3b4b22008c58ba6359296a587e97", "size": 4843, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "fast-fibration/src/generation.jl", "max_stars_repo_name": "higorsmonteiro/mynet_jl", "max_stars_repo_head_hexsha": "c5b5f80cb8b993950d6ad4b2424973236ced8a1d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fast-fibration/src/generation.jl", "max_issues_repo_name": "higorsmonteiro/mynet_jl", "max_issues_repo_head_hexsha": "c5b5f80cb8b993950d6ad4b2424973236ced8a1d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fast-fibration/src/generation.jl", "max_forks_repo_name": "higorsmonteiro/mynet_jl", "max_forks_repo_head_hexsha": "c5b5f80cb8b993950d6ad4b2424973236ced8a1d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5304878049, "max_line_length": 93, "alphanum_fraction": 0.5674168904, "num_tokens": 1186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.8479677622198947, "lm_q1q2_score": 0.785475699588147}}
{"text": "#linear_ker.jl\n\n\nsrand(1234)\n\n\"\"\"\nCompute the kernal, (linear) described \n\nThe kernal can be expressed mathematically as k(x,y)=<x,y>\n\nArguments\n---------\nx\n    First Argument \ny\n    Second Argument \n\n\n\"\"\"\n\nfunction linear_ker(x,y)\n    if size(x)!==size(y)\n        error(\"Error: Input vectors must have the same dimension and shape\")\n    end\n    return dot(x,y)\nend\n\n\n\n\n\n#std_exp_square_ker.jl\n\n\"\"\"\nCompute the kernal, exponential squared (standard i.e. no parameters), as described in A Tutorial on Bayesian \nOptimization of Expensive Cost Functions, with Application to Active User Modeling and  Hierarchical Reinforcement \nLearning Eric Brochu, Vlad M. Cora and Nando de Freitas December 14, 2010.\n\nThe kernal can be expressed mathematically as k(x,y)=exp(-1/2||x-y||^2)\n\nArguments\n---------\nx\n    First Argument \ny\n    Second Argument \n\n\n\"\"\"\n\nfunction std_exp_square_ker(x,y)\n    if size(x)!==size(y)\n        error(\"Error: Input vectors must have the same dimension and shape\")\n    end\n    return exp(-0.5*(dot(x-y,x-y)))\nend\n\n\n\n\n\n#hyper_exp_square_ker\n\n\n\"\"\"\nCompute the kernal, exponential squared (with parameters), as described in A Tutorial on Bayesian \nOptimization of Expensive Cost Functions, with Application to Active User Modeling and  Hierarchical Reinforcement \nLearning Eric Brochu, Vlad M. Cora and Nando de Freitas December 14, 2010.\n\nThe kernal can be expressed mathematically as k(x,y)=exp(-1/2(theta)||x-y||^2)\n\nArguments\n---------\nx\n    First Argument \ny\n    Second Argument \ntheta\n    Hyper-parameter\n\n\"\"\"\n\nfunction hyper_exp_square_ker(x,y,theta)\n    if size(x)!==size(y)\n        error(\"Error: Input vectors must have the same dimension and shape\")\n    end\n    return exp(-0.5*(dot(x-y,x-y))/theta)\nend\n\n\n\n\n\n\n\n\n#matern_ker\n\"\"\"\nCompute the matern kernal, as described in A Tutorial on Bayesian \nOptimization of Expensive Cost Functions, with Application to Active User Modeling and  Hierarchical Reinforcement \nLearning Eric Brochu, Vlad M. Cora and Nando de Freitas December 14, 2010.\n\n\nArguments\n---------\nx\n    First Argument \ny\n    Second Argument \nh\n    Hyper-parameter\n\n\n\"\"\"\nfunction matern_ker(x,y,h)\n    if size(x)!==size(y)\n        error(\"Error: Input vectors must have the same dimension and shape\")\n    end\n\n    \n\n    return ((0.5^(h-1))/(gamma(h)))*(2*sqrt(h)*sqrt(dot(x-y,x-y)))^h*besselj(h,2*sqrt(h)*sqrt(dot(x-y,x-y)))\nend\n\n\n\n\n\n\n\n#cov_gen.jl\n\n\"\"\"\nCreate the varience-covarience matrix K, as described in A Tutorial on Bayesian \nOptimization of Expensive Cost Functions, with Application to Active User Modeling and  Hierarchical Reinforcement \nLearning Eric Brochu, Vlad M. Cora and Nando de Freitas December 14, 2010. \n\nArguments\n---------\nKer\n    Kernal function\nx\n    Dataset\n\n\n\"\"\"\n\n\nfunction cov_gen(ker,x,y)\n    return [ker(x[i],y[j]) for i=1:size(x)[1], j=1:size(y)[1]]\nend\n\n\"\"\"\nUpdate Both of these to make them both quicker\n\"\"\"\n\n#Second one here need to format and look nice;\nfunction cov_gen2(ker,x,y)\n    return cov_gen(ker,x,y)\nend\n\n\nfunction diag_cov_gen(ker,x)\n    K=[ker(x[i],x[i]) for i=1:length(x)]\n    return K\nend\n\n\n\n\n\n#comb.jl\n\n\"\"\"\nGiven two arrays with single arrays inside generate the cartesian product set\nCredit to: Vandan Parmar\nArguments\n---------\n\na\n    array of array 1\nb\n    array of array 2\n\n\"\"\"\n\nfunction comb(a,b)\n\n\n    function op1(a,b)\n        return [a,b]\n    end\n\n    function op2(a,b)\n        return cat(1,[a],b)\n    end\n\n    function op3(a,b)\n        return cat(1,a,[b]) \n    end\n\n    function op4(a,b)\n        return cat(1,a,b)\n    end\n    a=a[1]\n\n\n    #shout out to nando\n    b=b[1] #Set the array of arrays to be an array so Vandan does not commit at this current time\n \n    if (size(a[1])==())\n        if(size(b[1])==())\n            op_i = op1\n        else\n   \n            op_i = op2\n        end\n    else\n        if(size(b[1])==())\n            op_i = op3\n        else\n            op_i = op4\n        end\n    end\n\n    # print(cat(,map(y -> op_i(1,y),b)))\n    print(\"\\n\")\n    print(\"\\n\")\n    toReturn = []\n    map(x -> map(y -> push!(toReturn,op_i(x,y)),b), a)\n    # show(string(toReturn))\n\n    # toReturn = []\n\n    # for ai in a\n    #     for bj in b\n    #         push!(toReturn,op_i(ai,bj))\n    #         print(ai,\"\\r\")\n    #     end\n    # end\n\n    return [toReturn]\nend\n\n\n\n\n\n\n\n#gen_points.jl\n\n\"\"\"\nGiven an array of arrays where each array is the set of values each variable can take, for example \nthe first array may be learning rate (size 10), the second may be Hyper-parameter 1 size(1000), ect ect,\nthe function gen_points will generate the set of all possible points considering a point in dimenstion R^n\nwhere n is the number of variables one uses.\n\nArguments\n---------\nS\n    Array of all arrays containing variable values\n\n\"\"\"\n\nfunction gen_points(S)\n    print(\"gen_points\")\n    if size(S)[1]==1\n        return S[1]\n    else\n        divider=convert(Int64,round( size(S)[1] /2) )    #Rounds up number of sets divided by two\n        \n        ar1=S[1:divider]\n        ar2=S[divider+1:end] #Splits S into two\n        \n        if size(ar2)[1]==1\n            if size(ar1)[1]==1\n                return comb(ar1,ar2)\n            else \n                ar1=gen_points(ar1)\n                return comb(ar1,ar2)\n            end\n        else\n            ar1=gen_points(ar1)\n            ar2=gen_points(ar2)\n            return comb(ar1,ar2)\n            \n        end\n    end\nend\n\n\n\n\n\n", "meta": {"hexsha": "7de728c0b4938a0dc98ec561d2eff0dad3d8c4d1", "size": 5356, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Kernals.jl", "max_stars_repo_name": "LawrenceMMStewart/Bayesian_Optimization", "max_stars_repo_head_hexsha": "e04aa7c8447d3226ae712eee563def0b5e55f843", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-08-09T21:17:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T16:49:48.000Z", "max_issues_repo_path": "Kernals.jl", "max_issues_repo_name": "LawrenceMMStewart/Bayesian_Optimization", "max_issues_repo_head_hexsha": "e04aa7c8447d3226ae712eee563def0b5e55f843", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Kernals.jl", "max_forks_repo_name": "LawrenceMMStewart/Bayesian_Optimization", "max_forks_repo_head_hexsha": "e04aa7c8447d3226ae712eee563def0b5e55f843", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0945945946, "max_line_length": 115, "alphanum_fraction": 0.6232262883, "num_tokens": 1463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.7854756977000746}}
{"text": "module ManifoldProjections\n# Manifold interface: every manifold (subtype of Manifold) defines the functions\n# project_tangent!(m, g, x): project g on the tangent space to m at x\n# retract!(m, x): map x back to a point on the manifold m\n\n# For mathematical references, see e.g.\n\n# The Geometry of Algorithms with Orthogonality Constraints\n# Alan Edelman, Tomás A. Arias, and Steven T. Smith\n# SIAM. J. Matrix Anal. & Appl., 20(2), 303–353. (51 pages)\n\n# Optimization Algorithms on Matrix Manifolds\n# P.-A. Absil, R. Mahony, R. Sepulchre\n# Princeton University Press, 2008\n\nimport NLSolversBase\nusing LinearAlgebra\n\nabstract type Manifold\nend\n\n# fallback for out-of-place ops\nretract(M::Manifold, x) = retract!(M, copy(x))\nproject_tangent(M::Manifold, g, x) = project_tangent!(M, copy(g), x)\n\n# Fake objective function implementing a retraction\nmutable struct ManifoldObjective{T<:NLSolversBase.AbstractObjective} <: NLSolversBase.AbstractObjective\n    manifold::Manifold\n    inner_obj::T\nend\n# TODO: is it safe here to call retract! and change x?\nfunction NLSolversBase.value!(obj::ManifoldObjective, x)\n    xin = retract(obj.manifold, x)\n    value!(obj.inner_obj, xin)\nend\nfunction NLSolversBase.value(obj::ManifoldObjective)\n    value(obj.inner_obj)\nend\nfunction NLSolversBase.gradient(obj::ManifoldObjective)\n    gradient(obj.inner_obj)\nend\nfunction NLSolversBase.gradient(obj::ManifoldObjective,i::Int)\n    gradient(obj.inner_obj,i)\nend\nfunction NLSolversBase.gradient!(obj::ManifoldObjective,x)\n    xin = retract(obj.manifold, x)\n    gradient!(obj.inner_obj,xin)\n    project_tangent!(obj.manifold,gradient(obj.inner_obj),xin)\n    return gradient(obj.inner_obj)\nend\nfunction NLSolversBase.value_gradient!(obj::ManifoldObjective,x)\n    xin = retract(obj.manifold, x)\n    value_gradient!(obj.inner_obj,xin)\n    project_tangent!(obj.manifold,gradient(obj.inner_obj),xin)\n    return value(obj.inner_obj)\nend\n\n\"\"\"Flat Euclidean space {R,C}^N, with projections equal to the identity.\"\"\"\nstruct Flat <: Manifold\nend\n# all the functions below are no-ops, and therefore the generated code\n# for the flat manifold should be exactly the same as the one with all\n# the manifold stuff removed\nretract(M::Flat, x) = x\nretract!(M::Flat, x) = x\nproject_tangent(M::Flat, g, x) = g\nproject_tangent!(M::Flat, g, x) = g\n\n\"\"\"Spherical manifold {||x|| = r}.\"\"\"\nstruct Sphere{T} <: Manifold where {T <: Real}\n    r::T\n    Sphere(r::T) where {T <: Real} = r < 0 ? error(\"radius has to be a positive number!\") : new{T}(r)\nend\nSphere() = Sphere(1)\nretract!(S::Sphere, x) = rmul!(x, S.r/norm(x))\nproject_tangent!(S::Sphere,g,x) = (g .-= (real(dot(x,g))/S.r^2).*x)\n\n\"\"\"\nN x n matrices with orthonormal columns, i.e. such that X'X = I.\nSpecial cases: N x 1 = sphere, N x N = orthogonal/unitary group.\nStiefel() uses a SVD algorithm to compute the retraction. To use a Cholesky-based orthogonalization (faster but less stable), use Stiefel(:CholQR).\nWhen the function to be optimized depends only on the subspace X*X' spanned by a point X in the Stiefel manifold, first-order optimization algorithms are equivalent for the Stiefel and Grassmann manifold, so there is no separate Grassmann manifold.\n\"\"\"\nabstract type Stiefel <: Manifold end\nstruct Stiefel_CholQR <: Stiefel end\nstruct Stiefel_SVD <: Stiefel end\nfunction Stiefel(retraction=:SVD)\n    if retraction == :CholQR\n        Stiefel_CholQR()\n    elseif retraction == :SVD\n        Stiefel_SVD()\n    end\nend\nfunction retract!(S::Stiefel_SVD, X)\n    U,S,V = svd(X)\n    X .= U*V'\nend\nfunction retract!(S::Stiefel_CholQR, X)\n    overlap = X'X\n    X .= X/cholesky(overlap).U\nend\n#For functions depending only on the subspace spanned by X, we always have G = A*X for some A, and so X'G = G'X, and Stiefel == Grassmann\n#Edelman et al. have G .-= X*G'X (2.53), corresponding to a different metric (\"canonical metric\"). We follow Absil et al. here and use the metric inherited from Nxn matrices.\nproject_tangent!(S::Stiefel, G, X) = (XG = X'G; G .-= X*((XG .+ XG')./2))\n\n\"\"\"\nMultiple copies of the same manifold. Points are stored as inner_dims x outer_dims,\ne.g. the product of 2x2 Stiefel manifolds of dimension N x n would be a N x n x 2 x 2 matrix.\n\"\"\"\nstruct PowerManifold<:Manifold\n    \"Type of embedded manifold\"\n    inner_manifold::Manifold\n    \"Dimension of the embedded manifolds\"\n    inner_dims::Tuple\n    \"Number of embedded manifolds\"\n    outer_dims::Tuple\nend\nfunction retract!(m::PowerManifold, x)\n    for i=1:prod(m.outer_dims) # TODO: use for i in LinearIndices(m.outer_dims)?\n        retract!(m.inner_manifold,get_inner(m, x, i))\n    end\n    x\nend\nfunction project_tangent!(m::PowerManifold, g, x)\n    for i=1:prod(m.outer_dims)\n        project_tangent!(m.inner_manifold,get_inner(m, g, i),get_inner(m, x, i))\n    end\n    g\nend\n@inline function get_inner(m::PowerManifold, x, i::Int)\n    size_inner = prod(m.inner_dims)\n    size_outer = prod(m.outer_dims)\n    @assert 1 <= i <= size_outer\n    return reshape(view(x, (i-1)*size_inner+1:i*size_inner), m.inner_dims)\nend\n\n\"\"\"\nProduct of two manifolds {P = (x1,x2), x1 ∈ m1, x2 ∈ m2}.\nP is stored as a flat 1D array, and x1 is before x2 in memory.\nUse get_inner(m, x, {1,2}) to access x1 or x2 in their original format.\n\"\"\"\nstruct ProductManifold<:Manifold\n    m1::Manifold\n    m2::Manifold\n    dims1::Tuple\n    dims2::Tuple\nend\nfunction retract!(m::ProductManifold, x)\n    retract!(m.m1, get_inner(m,x,1))\n    retract!(m.m2, get_inner(m,x,2))\n    x\nend\nfunction project_tangent!(m::ProductManifold, g, x)\n    project_tangent!(m.m1, get_inner(m, g, 1), get_inner(m, x, 1))\n    project_tangent!(m.m2, get_inner(m, g, 2), get_inner(m, x, 2))\n    g\nend\nfunction get_inner(m::ProductManifold, x, i::Integer)\n    N1 = prod(m.dims1)\n    N2 = prod(m.dims2)\n    @assert length(x) == N1+N2\n    if i == 1\n        return reshape(view(x, 1:N1),m.dims1)\n    elseif i == 2\n        return reshape(view(x, N1+1:N1+N2), m.dims2)\n    else\n        error(\"Only two components in a product manifold\")\n    end\nend\n\n\nexport Manifold,\n    Flat, Sphere, Stiefel, Stiefel_CholQR, Stiefel_SVD, PowerManifold, ProductManifold,\n    project_tangent, project_tangent!,\n    retract, retract!,\n    get_inner\n\nend # module\n", "meta": {"hexsha": "ade26146b42214fab30cc515bc49204fd87131a7", "size": 6174, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ManifoldProjections.jl", "max_stars_repo_name": "JuliaTagBot/ManifoldProjections.jl", "max_stars_repo_head_hexsha": "a3ee11f1382e3c14dedda1175948120cfcee73f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-01-29T06:58:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T01:19:55.000Z", "max_issues_repo_path": "src/ManifoldProjections.jl", "max_issues_repo_name": "JuliaTagBot/ManifoldProjections.jl", "max_issues_repo_head_hexsha": "a3ee11f1382e3c14dedda1175948120cfcee73f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-12-03T19:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-06T13:26:04.000Z", "max_forks_repo_path": "src/ManifoldProjections.jl", "max_forks_repo_name": "JuliaTagBot/ManifoldProjections.jl", "max_forks_repo_head_hexsha": "a3ee11f1382e3c14dedda1175948120cfcee73f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-12-04T10:49:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T02:02:07.000Z", "avg_line_length": 34.4916201117, "max_line_length": 248, "alphanum_fraction": 0.7057013282, "num_tokens": 1869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7854756959206133}}
{"text": "\nmodule ClosedIntervals\n\nimport Base.show, Base.isempty, Base.in, Base.length, Base.<<, Base.>>\nimport Base.isequal, Base.isless\nimport Base.*, Base.+, Base.==, Base.hash, Base.issubset\nimport Base.⊊, Base.⊇, Base.⊋\n\nimport AbstractLattices: ∨, ∧\n\nexport ClosedInterval, EmptyInterval, ⊇, ⊋\nexport show, left, right, .., ±, ∨, ∧\n\n# Create the ClosedInterval type\nstruct ClosedInterval{T}\n    L::T       # left end point\n    R::T       # right end point\n    nil::Bool  # signal if this is an empty interval\nend\n\n# Construct from two distinct end points\nfunction ClosedInterval(l,r)\n    (a,b) = promote(l,r)\n    if a>b\n        a,b = b,a\n    end\n    return ClosedInterval(a,b,false)\nend\n\n# dot-dot Construction\n(..)(a,b) = ClosedInterval(a,b)\n\n# plus-minus consruction\n±(a,b) = ClosedInterval(a-b,a+b)\n\n\n# Construct from a 2-tuple\nfunction ClosedInterval(ab::Tuple{S,T}) where {S,T}\n    return ClosedInterval(ab[1],ab[2]) # use 2-arg to test order\nend\n\n# Construct from one end point: assume L and R are the same\nClosedInterval(a) = ClosedInterval(a,a,false)\n\n# Construction with no specified end points: assume [0,1]\nfunction ClosedInterval(T::DataType = Float64)\n    ClosedInterval(zero(T),one(T),false)\nend\n\n# Create an empty interval\n\"\"\"\n`EmptyInterval(T::DataType = Float64)` creates an empty\n`ClosedInterval` of a given type.\n\"\"\"\nfunction EmptyInterval(T::DataType = Float64)\n    return ClosedInterval(zero(T),zero(T), true)\nend\n\n# Fetch the left end point\n\"\"\"\nFor a `ClosedInterval` `I`, `left(I)` returns its left end point.\n\"\"\"\nfunction left(J::ClosedInterval)\n    if isempty(J)\n        error(\"An empty interval does not have a left end point\")\n    end\n    return J.L\nend\n\n# Fetch the right end point\n\"\"\"\nFor a `ClosedInterval` `I`, `right(I)` returns its right end point.\n\"\"\"\nfunction right(J::ClosedInterval)\n    if isempty(J)\n        error(\"An empty interval does not have a right end point\")\n    end\n    return J.R\nend\n\n# Is this an empty interval?\n\"\"\"\nFor a `ClosedInterval I`, `isempty(I)` tests if `I` is an empty interval.\n\"\"\"\nisempty(J::ClosedInterval) = J.nil\n\n# Print as a closed interval should be printed\nfunction show(io::IO, J::ClosedInterval)\n    if J.nil\n        print(io,\"[]\")\n    else\n        print(io,\"[\", J.L, \",\", J.R, \"]\")\n    end\nend\n\n# The length of an interval is R-L unless it's empty. In that case, we\n# throw an error.\n\"\"\"\n`length(I)` is the length of the `ClosedInterval` `I`.\n\"\"\"\nfunction length(J::ClosedInterval{T}) where T\n    if isempty(J)\n      return zero(T)\n    end\n    return J.R - J.L\nend\n\n# Test point for membership\n\"\"\"\nFor a number `x` and a `ClosedInterval` `I` (of the same type)\n`in(x,I)` tests if `x` is contained in the interval `I`.\n\"\"\"\nfunction in(x, J::ClosedInterval)\n    return J.L <= x <= J.R\nend\n\n# The intersection of two intervals is the largest interval contained\n# in both. If the intervals are disjoint, we return an empty interval.\n\"\"\"\nFor `ClosedInterval`s `J` and `K`, `J*K` is their intersection.\nAlso available as `J ∧ K`.\n\"\"\"\nfunction *(J::ClosedInterval, K::ClosedInterval)\n\n    a = max(J.L, K.L)   # left end point of result\n    b = min(J.R, K.R)   # right end point of result\n\n    a,b = promote(a,b)\n    # if either interval is nil, so is their *\n    if J.nil || K.nil\n        return EmptyInterval(typeof(a))\n    end\n\n    if a>b  # uh oh, they're disjoint\n        return EmptyInterval(typeof(a))\n    end\n\n    return ClosedInterval(a,b,false)\nend\n\n\"\"\"\n`J ∧ K` is the largest `ClosedInterval` contained in both.\nSee also `*`.\n\"\"\"\n(∧)(J::ClosedInterval, K::ClosedInterval) = J*K\n\n# The + of two intervals is the smallest interval containing them\n# both. This is the same as their union if they overlap.\n\n\"\"\"\nFor `ClosedInterval`s `J` and `K`, `J+K` is the smallest `ClosedInterval`\ncontaining them both. This is also available as `J ∨ K`.\n\"\"\"\nfunction +(J::ClosedInterval, K::ClosedInterval)\n    # The empty interval acts as an identity element for this\n    # operation, so we check if either interval is empty first.\n\n    if J.nil\n        return K\n    end\n    if K.nil\n        return J\n    end\n\n    a = min(J.L, K.L)   # left end point of result\n    b = max(J.R, K.R)   # right end point of result\n\n    return ClosedInterval(a,b,false)\nend\n\n\"\"\"\n`J ∨ K` is the smalles `ClosedInterval` containing both. See also `+`.\n\"\"\"\n(∨)(J::ClosedInterval, K::ClosedInterval)= J+K\n\n\n# Compare intervals for equality\nfunction isequal(I::ClosedInterval, J::ClosedInterval)\n    if I.nil && J.nil\n        return true\n    end\n    if I.nil != J.nil\n        return false\n    end\n    return I.L==J.L && I.R==J.R\nend\n\n==(I::ClosedInterval, J::ClosedInterval) = isequal(I,J)\n\n# Sort intervals lexicographically, but put empty intervals at the\n# bottom of the order.\n\"\"\"\nLexicographic ordering of `ClosedInterval`s.\n\"\"\"\nfunction isless(I::ClosedInterval, J::ClosedInterval)\n    if J.nil\n        return false\n    end\n    if I.nil\n       return true\n    end\n\n    if I.L < J.L\n        return true\n    end\n\n    if I.L > J.L\n        return false\n    end\n\n    return I.R < J.R\nend\n\n\n# We use << to mean \"completely to the left of\"\n\"\"\"\nFor `ClosedInterval`s `I` and `J`, `I<<J` tests if `I` is completely\nto the left of `J`.\n\"\"\"\nfunction <<(I::ClosedInterval, J::ClosedInterval)\n    if I.nil || J.nil\n        return false\n    end\n    return I.R < J.L\nend\n\n# Likewise, >> means \"completely to the right of\"\n\"\"\"\nFor `ClosedInterval`s `I` and `J`, `I>>J` tests if `I` is completely\nto the right of `J`.\n\"\"\"\n>>(I::ClosedInterval, J::ClosedInterval) = J << I\n\n\nfunction hash(J::ClosedInterval, h::UInt64=UInt64(0))\n  if isempty(J)\n    return hash(false,h)\n  end\n  v = [J.L, J.R]\n  return hash(v,h)\nend\n\nfunction issubset(J::ClosedInterval, K::ClosedInterval)\n  if isempty(J)\n    return true\n  end\n  if isempty(K)\n    return false\n  end\n\n  return in(J.L,K) && in(J.R,K)\nend\n\n(⊇)(J::ClosedInterval,K::ClosedInterval) = issubset(K,J)\n\n(⊊)(J::ClosedInterval,K::ClosedInterval) = issubset(J,K) && !(J==K)\n(⊋)(J::ClosedInterval,K::ClosedInterval) = issubset(K,J) && !(J==K)\n\nend # module\n", "meta": {"hexsha": "b4090556d536eb941839be9059c582ef7b0d9d12", "size": 6018, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ClosedIntervals.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ClosedIntervals.jl-059b0e18-018a-5deb-a5b2-c624ee85784b", "max_stars_repo_head_hexsha": "f6cbc6976b18a6e0ead1672fba7ee9fd9aac441a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-08-16T20:35:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T23:47:34.000Z", "max_issues_repo_path": "src/ClosedIntervals.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ClosedIntervals.jl-059b0e18-018a-5deb-a5b2-c624ee85784b", "max_issues_repo_head_hexsha": "f6cbc6976b18a6e0ead1672fba7ee9fd9aac441a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-01-31T21:17:51.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-31T21:18:56.000Z", "max_forks_repo_path": "src/ClosedIntervals.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ClosedIntervals.jl-059b0e18-018a-5deb-a5b2-c624ee85784b", "max_forks_repo_head_hexsha": "f6cbc6976b18a6e0ead1672fba7ee9fd9aac441a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-03T12:14:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:14:40.000Z", "avg_line_length": 23.1461538462, "max_line_length": 73, "alphanum_fraction": 0.6490528415, "num_tokens": 1739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8596637559030337, "lm_q1q2_score": 0.7854545857361969}}
{"text": "using IntervalArithmetic\nusing IntervalRootFinding\n\n##\n# Available strategies\n##\n\nf(x) = sin(x)\ncontractor = Newton(f, cos)\n\n@info \"Bread first search.\"\n# A search takes a starting region, a contractor and a tolerance as argument\nsearch = BreadthFirstSearch(-10..10, contractor, 1e-10)\n\n# This is needed to avoid the data being discarded at the end of the loop use\n# `local tree` instead inside a function.\nglobal endtree\nfor (k, tree) in enumerate(search)\n    println(\"Tree at iteration $k\")\n    println(tree)  # The tree has custom printing\n    global endtree = tree\nend\n\nrts = data(endtree)  # Use `data` to only get the leaves marked as `:final`\nprintln(\"Final $(length(rts)) roots: $rts\")\nprintln()\n\n@info \"Depth first search.\"\n# The second available type of root search is depth first\nsearch = DepthFirstSearch(-10..10, contractor, 1e-10)\nfor tree in search\n    global endtree = tree\nend  # Go to the end of the iteration\n\n# Since the index of each node is printed and indices are attributed in the\n# order nodes are processed, comparing this tree with the last iteration of the\n# preceding show the difference between breadth first and depth first searches.\nprintln(endtree)\n\n\n##\n# Custom strategy\n##\n\n# Define custom BBSearch that store empty intervals rather than discarding it\n# Functions of the interface must be explicitely imported\nimport IntervalRootFinding\n\nstruct MySearch{R <: Region, C <: Contractor, T <: Real} <: BreadthFirstBBSearch{Root{R}}\n    initial::Root{R}\n    contractor::C\n    tol::T\nend\n\n# This must be implemented, other functions needed are already implemented for\n# BBSearch using Root as data (bisect function) or the general fallback match\n# this case (root_element function)\nfunction IntervalRootFinding.process(search::MySearch, r::Root)\n    contracted_root = search.contractor(r, search.tol)\n    status = root_status(contracted_root)\n\n    # We only store the unrefined intervals so the final intervals cover all\n    # the initial region\n    unrefined_root = Root(r.interval, status)\n    status == :unique && return :store, unrefined_root\n    status == :empty && return :store, unrefined_root # Store largest known empty intervals\n    status == :unknown && diam(contracted_root) < search.tol && return :store, unrefined_root\n    return :bisect, unrefined_root  # Always bisect the original interval to bypass [NaN, NaN]\nend\n\n@info \"Search with no interval discarded.\"\n\nsearch = MySearch(Root(-10..10, :unknown), contractor, 1e-10)\nfor tree in search\n    global endtree = tree\nend  # Go to the end of the iteration\n\n# In these tree we can see that the union of the resulting intervals (including\n# those containing no solution) covers the starting interval.\nprintln(endtree)\n", "meta": {"hexsha": "2ed854fee25dcc964839b8d544caa894546df170", "size": 2711, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/root_search_iterator.jl", "max_stars_repo_name": "eschnett/IntervalRootFinding.jl", "max_stars_repo_head_hexsha": "a58edadf76bf5928b21f4c2cf70025e15fc9fa17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/root_search_iterator.jl", "max_issues_repo_name": "eschnett/IntervalRootFinding.jl", "max_issues_repo_head_hexsha": "a58edadf76bf5928b21f4c2cf70025e15fc9fa17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/root_search_iterator.jl", "max_forks_repo_name": "eschnett/IntervalRootFinding.jl", "max_forks_repo_head_hexsha": "a58edadf76bf5928b21f4c2cf70025e15fc9fa17", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4691358025, "max_line_length": 94, "alphanum_fraction": 0.7443747695, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.8596637433190939, "lm_q1q2_score": 0.7854545843420064}}
{"text": "function gaussian(A::AbstractMatrix, b::AbstractVector)\n  #= Solve linear systems using Gaussian elimination\n\n    Linear systems should be in the form of Ax=b where A is a matrix and b & x \n    are column vectors.\n    \n    Keyword arguments:\n      A -- A matrix containing the coefficients of the variables to solve for\n      b -- A column vector containing the RHS of the linear system\n    Returns:\n      A column vector containing the solutions for x1..xn\n  =#\n  N, M = size(A);\n  x = zeros(M);\n\n  # Copies of A & b to avoid mutation\n  cpA = copy(A);\n  cpb = copy(b);\n\n  for j = 1:M\n    # Maximise the pivot point by looking for larger pivot points in the rows\n    # beneath the current point's row.\n    maxPivotRowIndex = indmax(abs(cpA[j:end, j])) + (j - 1);\n    cpA[maxPivotRowIndex, :], cpA[j, :] = cpA[j, :], cpA[maxPivotRowIndex, :];\n    cpb[maxPivotRowIndex, :], cpb[j, :] = cpb[j, :], cpb[maxPivotRowIndex, :];\n\n    # Iterate through the columns then rows of the linear system\n    for i = j+1:N\n      # If the current element is 0 then it is already reduced\n      if cpA[i, j] == 0\n        continue\n      end\n\n      # Perform row reduction on the current element's row using the pivot\n      # point.\n      multFactor = cpA[i,j] / cpA[j,j];\n      cpA[i, :] = cpA[i, :] - multFactor * cpA[j, :];\n      cpb[i] = cpb[i] - multFactor*cpb[j];\n    end\n  end\n\n  # Perform a back substitution for x1, x2, ..., xn.\n  x[end] = cpb[end] / cpA[end, end]; # Calculate xn\n  for i = N:-1:1 # Calculate xn-1...x1\n    x[i] = (cpb[i] - sum(cpA[i, i+1:N] * x[i+1:N])) / cpA[i,i];\n  end\n  return x;\nend\n", "meta": {"hexsha": "b3369f34e226d143796e8fcee3da639634884a31", "size": 1592, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/Linear Algebra/gaussian.jl", "max_stars_repo_name": "alexjohnj/numerical-methods", "max_stars_repo_head_hexsha": "152c24a5ab297cf2e7486e96c3f986dbe536537d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Julia/Linear Algebra/gaussian.jl", "max_issues_repo_name": "alexjohnj/numerical-methods", "max_issues_repo_head_hexsha": "152c24a5ab297cf2e7486e96c3f986dbe536537d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/Linear Algebra/gaussian.jl", "max_forks_repo_name": "alexjohnj/numerical-methods", "max_forks_repo_head_hexsha": "152c24a5ab297cf2e7486e96c3f986dbe536537d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-16T23:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-16T23:12:40.000Z", "avg_line_length": 32.4897959184, "max_line_length": 79, "alphanum_fraction": 0.6105527638, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191259110588, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7854530098283118}}
{"text": "# Example model ZIPoisson provided by Chris Fisher\n\nusing Pkg, DrWatson\n\n@quickactivate \"StatisticalRethinkingTuring\"\nusing Turing\nusing StatisticalRethinking\n\nimport Distributions: logpdf, rand\n\nstruct ZIPoisson{T1,T2} <: DiscreteUnivariateDistribution\n    logλ::T1\n    w::T2\nend\n\nfunction logpdf(d::ZIPoisson, y::Int)\n    LL = 0.0\n    if y == 0\n        LLs = zeros(typeof(d.logλ), 2)\n        LLs[1] = log(d.w)\n        LLs[2] = log(1 - d.w) - exp(d.logλ)\n        LL = logsumexp(LLs)\n    else\n        LL = log(1 - d.w) + logpdf(LogPoisson(d.logλ), y)\n    end\n    return LL\nend\n\nfunction rand(d::ZIPoisson)\n    return rand() <= d.w ? 0 : rand(Poisson(exp(d.logλ)))\nend\n\nrand(d::ZIPoisson, N::Int) = map(_->rand(d), 1:N)\n\n\ninv_logit(x) = 1/(1 + exp(-x))\n\n@model ppl12_3bt(data) = begin\n    a1 ~ Normal(1, .5)\n    logλ ~ Normal(-1.5, 1)\n    w = inv_logit(a1)\n    data .~ ZIPoisson(logλ, w)\nend\n\n#Random.seed!(74591)\ndata = rand(ZIPoisson(-1.5, .70), 1000)\n\nn_samples = 3000\nn_adapt = 1500\nconfig = NUTS(n_adapt, .65)\nn_chains = 4\nchns12_3bt = sample(ppl12_3bt(data), config, MCMCThreads(), n_samples, n_chains, progress=true)\nchns12_3bt |> display\n", "meta": {"hexsha": "bf5c1cfce399ee13dc1a8de71131f20e3643a95b", "size": 1145, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/12/m12.3b.jl", "max_stars_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_stars_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2020-10-01T23:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T11:48:45.000Z", "max_issues_repo_path": "models/12/m12.3b.jl", "max_issues_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_issues_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-11-24T21:59:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T12:34:49.000Z", "max_forks_repo_path": "models/12/m12.3b.jl", "max_forks_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_forks_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-11-30T18:25:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T06:59:27.000Z", "avg_line_length": 21.2037037037, "max_line_length": 95, "alphanum_fraction": 0.6419213974, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482725, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7854422422735885}}
{"text": "using Distributions, Plots, LaTeXStrings; pyplot()\n\nalpha, beta = 8, 2\ndata = [2,1,0,0,1,0,2,2,5,2,4,0,3,2,5,0]\n\nnewAlpha, newBeta = alpha + sum(data), beta + length(data)\npost = Gamma(newAlpha, 1/newBeta)\n\nxGrid = quantile(post,0.01):0.001:quantile(post,0.99)\nsignificance = 0.9; halfAlpha = (1-significance)/2\n\ncoverage(l,u) = cdf(post,u) - cdf(post,l)\n\nfunction classicalCI(dist)\n    l, u = mode(dist),mode(dist)\n    bestl, bestu = l, u\n    while  coverage(l,u) < significance \n        l -= 0.00001; u += 0.00001\n    end\n    (l,u)\nend\nequalTailCI(dist) = (quantile(dist,halfAlpha), quantile(dist,1-halfAlpha))\nfunction highestDensityCI(dist)\n    height = 0.999 * maximum(pdf.(dist,xGrid))\n    l,u = mode(dist),mode(dist)\n    while coverage(l,u) <= significance\n        range = filter(theta -> pdf(dist,theta) > height, xGrid)\n        l,u = minimum(range), maximum(range)\n        height -= 0.00001\n    end\n    (l,u)\nend\n\nl1, u1 = classicalCI(post)\nl2, u2 = equalTailCI(post)\nl3, u3 = highestDensityCI(post)\nprintln(\"Classical: \", (l1,u1), \"\\tWidth: \",u1-l1, \n\t\"\\tCoverage: \", coverage(l1,u1))\nprintln(\"Equal tails: \", (l2,u2), \"\\tWidth: \",u2-l2, \n\t\"\\tCoverage: \", coverage(l2,u2))\nprintln(\"Highest density: \", (l3,u3), \"\\tWidth: \",u3-l3, \n\t\"\\tCoverage: \", coverage(l3,u3))\n\nplot(xGrid,pdf.(post,xGrid),  yticks=(0:0.25:1.25),\n\tc=:black, label=\"Gamma Posterior Distribution\",\n    \txlims=(1.4, 2.9), ylims=(-0.4,1.25))\nplot!([l1,u1],[-0.1,-0.1], label=\"Classic CI\", \n    \tc=:blue, shape=:vline, ms=16)\nplot!([l2,u2],[-0.2,-0.2], label=\"Equal Tail CI\", \n    \tc=:red, shape=:vline, ms=16)\nplot!([l3,u3],[-0.3,-0.3], label=\"Highest Density CI\", \n\tc=:green, shape=:vline, ms=16, xlabel=L\"\\lambda\", ylabel=\"Density\")", "meta": {"hexsha": "f822060556f00475ea6457e424a9511f7a9f72a0", "size": 1711, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "6_chapter/credible.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "6_chapter/credible.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "6_chapter/credible.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 32.9038461538, "max_line_length": 74, "alphanum_fraction": 0.6241963764, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7854422422735883}}
{"text": "\n\nfunction floyd_warshall(d, n, f, g)\n\tfor k in 1 : n\n\t\tfor i in 1 : n\n\t\t\tfor j in 1 : n\n\t\t\t\td[i, j] = f(d[i, j], g(d[i, k], d[k, j]))\n\t\t\tend\n\t\tend\n\tend\n\treturn d\nend\n\n\nfunction transitive_closure(d, n)\n\td .= reshape([i < Inf ? 1 : 0 for i in d], (n, n))\n\tor(a, b) = (a != 0 || b != 0) ? 1 : 0\n\tand(a, b) = (a != 0 && b != 0) ? 1 : 0\n\treturn floyd_warshall(d, n, or, and)\nend\n\n\nfunction create_preference_matrix(b, v, c)\n\tind(c)::Int = c - 'A' + 1\n\tchk_list::Array{Bool, 1} = Array{Bool, 1}(undef, c)\n\tret::Array{Int, 2} = fill(0, c, c)\n\tfor i in b\n\t\tfill!(chk_list, false)\n\t\tfor j in i\n\t\t\tchk_list[ind(j)] = true\n\t\t\tfor k in 1 : c\n\t\t\t\tif !chk_list[k]\n\t\t\t\t\tret[ind(j), k] += 1\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n\treturn ret\nend\n\n\nfunction find_strongest_paths(p, c)\n\tfor i in 1 : c - 1\n\t\tfor j in i + 1 : c\n\t\t\tif p[i, j] < p[j, i]\n\t\t\t\tp[i, j] = 0\n\t\t\telse\n\t\t\t\tp[j, i] = 0\n\t\t\tend\n\t\tend\n\tend\n\tfloyd_warshall(p, c, max, min)\n\tfor i in 1 : c\n\t\tp[i, i] = 0\n\tend\n\treturn p\nend\n\n\nfind_schulze_ranking(sp, c) = String([i[2] for i in sort([(sum([sp[j, i] > sp[i, j] ? 0 : 1 for i in 1 : c]), Char(j + 64)) for j in 1 : c])])\n\n", "meta": {"hexsha": "799615cdf097395651aff9f97ccc9c7eb63aa5c5", "size": 1107, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "18Host/TDT4120/AtomProjectFolder/Project1/Oving11/Ov11.jl", "max_stars_repo_name": "MarcusTL12/School", "max_stars_repo_head_hexsha": "f7302f2d390e99ad9d06004e15da032c05ec59e7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "18Host/TDT4120/AtomProjectFolder/Project1/Oving11/Ov11.jl", "max_issues_repo_name": "MarcusTL12/School", "max_issues_repo_head_hexsha": "f7302f2d390e99ad9d06004e15da032c05ec59e7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "18Host/TDT4120/AtomProjectFolder/Project1/Oving11/Ov11.jl", "max_forks_repo_name": "MarcusTL12/School", "max_forks_repo_head_hexsha": "f7302f2d390e99ad9d06004e15da032c05ec59e7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8548387097, "max_line_length": 142, "alphanum_fraction": 0.5266485998, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7854422419112435}}
{"text": "using LinearAlgebra\n\nT = SymTridiagonal(2ones(5), -ones(4))\n\nT * randn(5)     # Matrix-vector multiplication\nT^3              # Matrix cube\n\nT + 2I     # OK, since T is 3-by-3\n\nI4 = Matrix{Float64}(I, 4, 4)\n", "meta": {"hexsha": "039f1cda7ecc0544c0b32ed1df8485a0d09910eb", "size": 207, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Linear_Algebra/Special_Matrices.jl", "max_stars_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_stars_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "textbook/_build/jupyter_execute/content/Linear_Algebra/Special_Matrices.jl", "max_issues_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_issues_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "textbook/_build/jupyter_execute/content/Linear_Algebra/Special_Matrices.jl", "max_forks_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_forks_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8181818182, "max_line_length": 47, "alphanum_fraction": 0.5990338164, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7854422370086716}}
{"text": "function distance_matrix_float(x, y)\n    @assert length(x) == length(y)\n    n = length(x)\n    M = zeros(n, n)\n    for i in 1:n \n        for j in i+1:n \n            if i != j\n                M[i, j] = sqrt( (x[i]-x[j])^2 + (y[i]-y[j])^2 )\n                M[j, i] = M[i, j]\n            end \n        end \n    end \n    return M\nend\n\nfunction distance_matrix(x, y)\n    M = distance_matrix_float(x, y)\n    return Int.(round.(M))\nend\n\nfunction tour_length(tour, M::Matrix{T}) where T\n    sum = zero(T) \n    for i in 1:length(tour) \n        if i < length(tour)\n            sum += M[tour[i], tour[i+1]]\n        else \n            sum += M[tour[i], tour[1]]\n        end\n    end\n    return sum\nend\n\n# function tour_length(tour, x, y) \n#     M = distance_matrix(x, y)\n#     return tour_length(tour, M)\n# end \n\nfunction solve_TSP_Concorde(x, y; norm=\"EUC_2D\",)\n    Concorde = pyimport(\"concorde.tsp\")\n    solver = Concorde.TSPSolver.from_data(x, y, norm)\n    tour_data = solver.solve()\n    tour_concorde = tour_data[1] .+ 1  # 0-index -> 1-index\n    # length_concorde = tour_length(tour_concorde, x, y) \n    length_concorde = Int(tour_data[2])\n    return tour_concorde, length_concorde\nend\n\nfunction solve_TSP_LKH(M::Matrix{T}) where T\n    Elkai = pyimport(\"elkai\")\n    if T == Int\n        tour_LKH = Elkai.solve_int_matrix(M) .+ 1 #adding 1 for indexing\n    else\n        tour_LKH = Elkai.solve_float_matrix(M) .+ 1 #adding 1 for indexing\n    end\n    length_LKH = tour_length(tour_LKH, M)\n    return tour_LKH, length_LKH\nend\n\nfunction solve_TSP_LKH(x, y)\n    M = distance_matrix(x, y)\n    return solve_TSP_LKH(M)\nend\n", "meta": {"hexsha": "4585816032184e767a80d9e06d27bdb2517dbef3", "size": 1603, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tsp_solvers.jl", "max_stars_repo_name": "chkwon/PyTSP.jl", "max_stars_repo_head_hexsha": "fba57ddc52cf27e1e7187cbe78cd72293ea79ff4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-12T10:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-12T10:48:11.000Z", "max_issues_repo_path": "src/tsp_solvers.jl", "max_issues_repo_name": "chkwon/PyTSP.jl", "max_issues_repo_head_hexsha": "fba57ddc52cf27e1e7187cbe78cd72293ea79ff4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-02-21T18:02:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-24T19:00:58.000Z", "max_forks_repo_path": "src/tsp_solvers.jl", "max_forks_repo_name": "chkwon/PyTSP.jl", "max_forks_repo_head_hexsha": "fba57ddc52cf27e1e7187cbe78cd72293ea79ff4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4444444444, "max_line_length": 74, "alphanum_fraction": 0.58827199, "num_tokens": 522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370312, "lm_q2_score": 0.8397339676722394, "lm_q1q2_score": 0.7854422328307892}}
{"text": "using LinearAlgebra\n\nfunction scalarproduct(a::AbstractVector{T}, b::AbstractVector{T}, c::AbstractVector{T}) where {T<:Number}\n    return dot(a, cross(b, c))\nend\n\nfunction vectorproduct(a::AbstractVector{T}, b::AbstractVector{T}, c::AbstractVector{T}) where {T<:Number}\n    return cross(a, cross(b, c))\nend\n\nconst a = [3, 4, 5]\nconst b = [4, 3, 5]\nconst c = [-5, -12, -13]\n\nprintln(\"Test Vectors:\")\n@show a b c\n\nprintln(\"\\nVector Products:\")\n@show dot(a, b)\n@show cross(a, b)\n@show scalarproduct(a, b, c)\n@show vectorproduct(a, b, c)\n", "meta": {"hexsha": "598fd813ee79a3760cc5a77ab871449160d55cea", "size": 535, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/vector-products.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/vector-products.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/vector-products.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2608695652, "max_line_length": 106, "alphanum_fraction": 0.6691588785, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9719924785827002, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7854352582552897}}
{"text": "\n\"\"\"\n    KernelFormulation\n\nAbstract supertype for functors that calculate the probability density based on distance.\n\nConcrete implementations must define functor methods with the form:\n\n```julia\n(k::SomeKernel)(distance) = # do something with `distance` and `k`\"\n```\n\nUsing an anonymous function would not allow rebuildable model parameters.\n\"\"\"\nabstract type KernelFormulation end\n\n\"\"\"\n    ExponentialKernel <: KernelFormulation\n\n    ExponentialKernel(λ)\n\nProbability density function of distance ``d``.\n\n```math\ny = e^{-d/λ}\n```\n\nwhere λ is a shape parameter.\n\"\"\"\nBase.@kwdef struct ExponentialKernel{P} <: KernelFormulation\n    λ::P = Param(1.0, bounds=(0.0, 2.0))\nend\n(f::ExponentialKernel)(d) = exp(-d / f.λ)\n\n\"\"\"\n    GeometricKernel <: KernelFormulation\n\n    GeometricKernel(α)\n\nProbability density function of distance ``d``.\n\nThe Geometric kernel has a power-law decrease.\n\n```math\ny = (1+d)^α (α+1)(α+2) / (2 π)\n```\n\nwhere α is a shape parameter.\n\"\"\"\nBase.@kwdef struct GeometricKernel{P} <: KernelFormulation\n    α::P = Param(1.0, bounds=(-1000.0, 1000.0))\nend\n(f::GeometricKernel)(d) = (1 + d)^f.α * ((f.α + 1)*(f.α + 2)) / (2 * π)\n\n\"\"\"\n    GaussianKernel <: KernelFormulation\n\n    GaussianKernel(α)\n\nProbability density function of distance ``d``.\n\n```math\ny = 1/ (π α^2) e^{-d^2/α^2} \n```\n\nwhere α is a positive parameter.\n\"\"\"\nBase.@kwdef struct GaussianKernel{P} <: KernelFormulation\n    α::P = Param(1.0, bounds=(0.0, 1000.0))\nend\n(f::GaussianKernel)(d) = 1 / (π * f.α^2) * exp(- d^2 / f.α^2)\n\n\"\"\"\n    WeibullKernel <: KernelFormulation\n\n    WeibullKernel(α,β)\n\nProbability density function of distance ``d``.\n\n```math\ny =β /(2 π α^2) d^{β-2} e^{ -d^β/α^β} \n```\n\nwhere α and β are positive parameters.\n\"\"\"\nBase.@kwdef struct WeibullKernel{A,B} <: KernelFormulation\n    α::A = Param(1.0, bounds=(0.0, 1000.0))\n    β::B = Param(2.0, bounds=(0.0, 1000.0))\nend\n(f::WeibullKernel)(d) = f.β / (2 * π * f.α^2) * d^(f.β - 2) * exp(- d^f.β / f.α^f.β)", "meta": {"hexsha": "626792fa8642eafebd02997b4db30d30ed20f62b", "size": 1958, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernel/formulations.jl", "max_stars_repo_name": "rafaqz/Dispersal.jl", "max_stars_repo_head_hexsha": "9c03aca80b3ca7bf00901eaa0641dcd06f4f04a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-01-05T11:50:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T21:42:36.000Z", "max_issues_repo_path": "src/kernel/formulations.jl", "max_issues_repo_name": "cesaraustralia/Dispersal.jl", "max_issues_repo_head_hexsha": "9d70c05f80a4d10c34b58cab731acebf0a42fd9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2019-09-26T09:52:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T12:44:03.000Z", "max_forks_repo_path": "src/kernel/formulations.jl", "max_forks_repo_name": "rafaqz/Dispersal.jl", "max_forks_repo_head_hexsha": "9c03aca80b3ca7bf00901eaa0641dcd06f4f04a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-09-27T07:09:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-09T23:17:46.000Z", "avg_line_length": 21.7555555556, "max_line_length": 89, "alphanum_fraction": 0.6460674157, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.785433887124889}}
{"text": "str = \"\"\"\n73167176531330624919225119674426574742355349194934\n96983520312774506326239578318016984801869478851843\n85861560789112949495459501737958331952853208805511\n12540698747158523863050715693290963295227443043557\n66896648950445244523161731856403098711121722383113\n62229893423380308135336276614282806444486645238749\n30358907296290491560440772390713810515859307960866\n70172427121883998797908792274921901699720888093776\n65727333001053367881220235421809751254540594752243\n52584907711670556013604839586446706324415722155397\n53697817977846174064955149290862569321978468622482\n83972241375657056057490261407972968652414535100474\n82166370484403199890008895243450658541227588666881\n16427171479924442928230863465674813919123162824586\n17866458359124566529476545682848912883142607690042\n24219022671055626321111109370544217506941658960408\n07198403850962455444362981230987879927244284909188\n84580156166097919133875499200524063689912560717606\n05886116467109405077541002256983155200055935729725\n71636269561882670428252483600823257530420752963450\"\"\"\n\nstr = join(split(str), \"\")\nl = map(x->parse(Int, x), collect(str))\nprintln(l)\n\n#kernel1 = [1,1,1]\n#results1 = conv(l, kernel1)[2:end-2]\n#println(results1) # can be used to find max sum\n\nprods = [prod(l[i:i+3]) for i in 1:length(l)-3]\nprintln(maximum(prods))\n\nprods = [prod(l[i:i+12]) for i in 1:length(l)-12]\nprintln(maximum(prods))\n", "meta": {"hexsha": "f08f967cd191c3f731c711acb5bece9e280cfd23", "size": 1367, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "algo/su.8.jl", "max_stars_repo_name": "cdluminate/MyNotes", "max_stars_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algo/su.8.jl", "max_issues_repo_name": "cdluminate/MyNotes", "max_issues_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algo/su.8.jl", "max_forks_repo_name": "cdluminate/MyNotes", "max_forks_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9722222222, "max_line_length": 53, "alphanum_fraction": 0.8902706657, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7854338851074382}}
{"text": "#=\n  Coupon collecter's problem, or card collecter's problem.\n\n  There are N different collecter's cards hidden in a package, but we don't\n  know which card there is in the package we buy.\n  We want to collect all of them, how many packages must one buy to collect\n  all the different cards?\n\n  See https://en.wikipedia.org/wiki/Coupon_collector%27s_problem\n  \"\"\"\n  In probability theory, the coupon collector's problem describes 'collect all coupons and win' \n  contests. It asks the following question: If each box of a brand of cereals contains a \n  coupon, and there are n different types of coupons, what is the probability that more \n  than t boxes need to be bought to collect all n coupons? \n\n  An alternative statement is: Given n coupons, how many coupons do you expect you need \n  to draw with replacement before having drawn each coupon at least once? The mathematical \n  analysis of the problem reveals that the expected number of trials needed grows as \n  Θ(n log(n).\n  For example, when n = 50 it takes about 225[b] trials on average to collect all 50 coupons. \n\n  ...\n\n  [b]: E(50) = 50(1 + 1/2 + 1/3 + ... + 1/50) = 224.9603, the expected number of trials to \n  collect all 50 coupons. \n\n   The approximation n*log(n) + γ*n + 1/2 for this expected number gives in this case \n   ≈ 195.6011 + 28.8608 + 0.5 ≈ 224.9619.  [log is the natural logarithm]\n  \"\"\" \n\n  Note: The assumptions are that the slots are filled using a Poisson process\n  and the parameter will influence the result much.\n\n  p (mean): 5.7496\n\n  Distributions of variable p (num:0)\n  7.00000 =>    3172  (0.317200)\n  6.00000 =>    2920  (0.292000)\n  5.00000 =>    2349  (0.234900)\n  4.00000 =>    1317  (0.131700)\n  3.00000 =>     242  (0.024200)\n\n  Distributions of variable total_filled (num:0)\n  50.00000 =>   10000  (1.000000)\n\n  Distributions of variable theoretical (num:0)\n  224.96027 =>   10000  (1.000000)\n\n  mean sumx: 288.7327\n\n\n\n  See ~/blog/coupon_collector.blog\n      ~/webppl/cookie_problem.wppl\n\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n@model function coupon_collector()\n    n = 50\n    m = round(Int,sqrt(n))\n    #  \"Exact\" probability from https:# en.wikipedia.org/wiki/Coupon_collector%27s_problem (footnote [b])\n    theoretical ~ Dirac(n*sum([1/i for i in 1:n])) #  N*Math.log(N,Math.e);\n    \n    #  p = beta(14,14);\n    p ~ DiscreteUniform(1,m)\n\n    #  Fill this slot with cards\n    fill ~ filldist(Poisson(p),n)\n\n    #  How many slots are filled (i.e. > 0)?\n    total_filled ~ Dirac(sum([fill[c] > 0 for c in 1:n]))\n\n    true ~ Dirac(total_filled == n)\n\n    sumx ~ Dirac(sum(fill))\n    sum0s ~ Dirac(sum([fill[c] == 0 for c in 1:n] ))\n    \nend\n\nmodel = coupon_collector()\nnum_chains = 4\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(5), 10_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 10_000)\n\ndisplay(chns)\n# display(plot(chns))\n\nshow_var_dist_pct(chns, :p)\nshow_var_dist_pct(chns, :total_filled)\nshow_var_dist_pct(chns, :theoretical)\nprintln([\"mean sumx: \", mean(chns[:sumx].data)])\n\nshow_var_dist_pct(chns, Symbol(\"fill[1]\"))\nshow_var_dist_pct(chns, Symbol(\"fill[2]\"))\nshow_var_dist_pct(chns, Symbol(\"fill[3]\"))\nshow_var_dist_pct(chns, Symbol(\"fill[4]\"))\nshow_var_dist_pct(chns, Symbol(\"fill[5]\"))\nshow_var_dist_pct(chns, Symbol(\"fill[6]\"))\nshow_var_dist_pct(chns, Symbol(\"fill[7]\"))\nshow_var_dist_pct(chns, Symbol(\"fill[8]\"))\nshow_var_dist_pct(chns, Symbol(\"fill[9]\"))\nshow_var_dist_pct(chns, Symbol(\"fill[10]\"))\n\n\n", "meta": {"hexsha": "218f8745be9fb05bbe85c7ed7e3272461e6fceac", "size": 3529, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/coupon_collector.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/coupon_collector.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/coupon_collector.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 31.5089285714, "max_line_length": 105, "alphanum_fraction": 0.6880136016, "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.785433884822713}}
{"text": "#=\n145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.\n\nFind the sum of all numbers which are equal to the sum of the factorial of their digits.\n\nNote: as 1! = 1 and 2! = 2 are not sums they are not included.\n=#\nfunction calc()\n  total = 0\n  for i in 3:9_999_999\n    if sum(map((x)->factorial(x),digits(i))) == i\n      total += i\n    end\n  end\n  total\nend\n@time println(calc())\n", "meta": {"hexsha": "98339101394f6e5292a5f04137b4887b5d6da932", "size": 389, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p34.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p34.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p34.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 21.6111111111, "max_line_length": 88, "alphanum_fraction": 0.616966581, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9425067147399244, "lm_q2_score": 0.8333245911726381, "lm_q1q2_score": 0.7854140227381138}}
{"text": "# QR-decomposition using the MSG algorithm\n\nR = zeros(n,n) \n\nfor k=1:n\n    R[k,k] = norm(A[:,k])\n    A[:,k] /= R[k,k]\n    R[k:k,k+1:n] = A[:,k]’*A[:,k+1:n]\n    A[:,k+1:n]  -= A[:,k]*R[k:k,k+1:n]\nend", "meta": {"hexsha": "0bf86931edb2fcb567d2b434b42d9d8af20399ba", "size": 198, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Code/Numerical Analysis & Machine Learning/Numerical Linear Algebra/QRDecomposition.jl", "max_stars_repo_name": "BambooFlower/Math-Scripts", "max_stars_repo_head_hexsha": "ee89c4f8a1fe80f355e2daa0baa4f94374ee3ab5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-03-10T13:21:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-20T19:52:53.000Z", "max_issues_repo_path": "Code/Numerical Analysis & Machine Learning/Numerical Linear Algebra/QRDecomposition.jl", "max_issues_repo_name": "BambooFlower/Math-Scripts", "max_issues_repo_head_hexsha": "ee89c4f8a1fe80f355e2daa0baa4f94374ee3ab5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-25T14:25:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-25T14:28:07.000Z", "max_forks_repo_path": "Code/Numerical Analysis & Machine Learning/Numerical Linear Algebra/QRDecomposition.jl", "max_forks_repo_name": "BambooFlower/Math-Scripts", "max_forks_repo_head_hexsha": "ee89c4f8a1fe80f355e2daa0baa4f94374ee3ab5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-25T13:17:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T15:11:25.000Z", "avg_line_length": 19.8, "max_line_length": 42, "alphanum_fraction": 0.4545454545, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9579122768904644, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.785385898535706}}
{"text": "using SciPyDiffEq\n\n\n# Definition of parameters\nconst a = 1.0\nconst b = 0.1\nconst c = 1.5\nconst d = 0.75\n\n\nfunction diffeq(u,p,t)\n    du = zeros(2)\n    # u1: rabbits\n    # u2: foxes\n    du[1] = a*u[1] - b*u[1]*u[2]\n    du[2] = -c*u[2] + d*b*u[1]*u[2]\n    \n    return du\n\nend\n\n# Simulation time\nconst tspan = (0.0,18.0)\n\n\n# Initial condition\nu0 = zeros(2)\nu0[1] = 10\nu0[2] = 5\n\n\n# Solve ODE\nprob = ODEProblem(diffeq,u0,tspan)\nsol = solve(prob,SciPyDiffEq.BDF(),saveat=(tspan[end]-tspan[1])/999)\n\n\n#= Visualization of Results\nusing PyPlot\nfigure(figsize=(20,8))\nplot(sol.t,sol.u)\nshow()\n=#", "meta": {"hexsha": "35ff07509e29c03e5bedf8695a8704fdc1ced188", "size": 586, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/test_SciPyDiffEq.jl", "max_stars_repo_name": "camrepo/ode_solver", "max_stars_repo_head_hexsha": "facb6d026440db51b3052e7a6b88184d749b5be0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-07T10:33:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T17:29:25.000Z", "max_issues_repo_path": "julia/test_SciPyDiffEq.jl", "max_issues_repo_name": "camrepo/ode_solver", "max_issues_repo_head_hexsha": "facb6d026440db51b3052e7a6b88184d749b5be0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/test_SciPyDiffEq.jl", "max_forks_repo_name": "camrepo/ode_solver", "max_forks_repo_head_hexsha": "facb6d026440db51b3052e7a6b88184d749b5be0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-15T02:33:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T02:33:12.000Z", "avg_line_length": 13.9523809524, "max_line_length": 68, "alphanum_fraction": 0.6092150171, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828602, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7853858915022938}}
{"text": "#=\nThe prime 41, can be written as the sum of six consecutive primes:\n\n41 = 2 + 3 + 5 + 7 + 11 + 13\nThis is the longest sum of consecutive primes that adds to a prime below one-hundred.\n\nThe longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.\n\nWhich prime, below one-million, can be written as the sum of the most consecutive primes?\n=#\nusing Primes\n\nfunction calc()\n\n  x = 10^6\n  p = primes(x-1)\n  largestrun = largestprime = 0\n\n  for i in 1:length(p)\n    currentsum = 0\n    for j in i:length(p)\n      currentsum += p[j]\n      if currentsum >= x\n        break\n      end\n      if isprime(currentsum) && j-i > largestrun\n        largestrun = j-i\n        largestprime = currentsum\n      end\n    end\n  end\n  largestprime\nend\n@time println(calc())\n", "meta": {"hexsha": "e35d5f0bc88f2dee1f54bf6e38d1f07c2c4ef6e4", "size": 807, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p50.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p50.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p50.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 23.0571428571, "max_line_length": 118, "alphanum_fraction": 0.6579925651, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9579122744874228, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7853858902420159}}
{"text": "# cross ratio for 4 numbers\nfunction crossratio(a,b,c,d)\n    d_ab = norm(a - b)\n    d_bd = norm(b - d)\n    d_ac = norm(a - c)\n    d_cd = norm(c - d)\n    (d_ab/d_bd)/(d_ac/d_cd)\nend\nexport crossratio\n\n\n# modulo that starts from one\n# imod(1,3) = 1\n# imod(2,3) = 2\n# imod(3,3) = 3\n# imod(4,3) = 1\nfunction imod(i, n)\n  return (i-1)%n + 1\nend\nexport imod\n\n#TODO handle zero deviation\n# l1 = [(x1,y1), (x2,y2)]\n# l2 = [(x3,y3), (x4,y4)]\nfunction intersection_point(l1, l2)\n  x1 = l1[1][1]\n  y1 = l1[1][2]\n\n  x2 = l1[2][1]\n  y2 = l1[2][2]\n\n  x3 = l2[1][1]\n  y3 = l2[1][2]\n\n  x4 = l2[2][1]\n  y4 = l2[2][2]\n\n  denominator = (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4)\n  x = (x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4)\n  y = (x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4)\n  return [x,y]/denominator\nend\nexport intersection_point\n\n\"\"\"\n    calcualte_rigid(source_pts,target_pts)\n\nfind (R,T) rigid transformation matrix and translation vector\nsuch that target_pts ≈ R * source_pts + T\nin the least-square sense\n\"\"\"\nfunction rigid_trans(src_pts,dst_pts)\n  to_array(vv) = [vv[i][j] for i=1:length(vv) , j=1:length(vv[1])]\n  n = length(src_pts)\n  dim = size(src_pts[1])[1]\n  dst_bar = mean(dst_pts)\n  src_bar = mean(src_pts)\n  dst_centered = dst_pts .- [dst_bar]\n  src_centered = src_pts .- [src_bar]\n\n  C = to_array(src_centered)' * to_array(dst_centered) / n\n  U,s,V = svd(C)\n  # Rotation R in least squares sense:\n  Rr = (U * diagm(vcat(ones(dim-1), det(U*V.'))) * V.' ).'\n  Tr = -Rr*src_bar + dst_bar\n\n  Pr = PM(Rr,Tr)\n  reproj_error = mean(norm.([Rr] .* src_pts .+ [Tr] - dst_pts))\n  (Rr,Tr,reproj_error)\nend\nexport rigid_trans\n", "meta": {"hexsha": "13ff9fdc2a79d3cf891bbb395669bbb7c9e3306a", "size": 1604, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math.jl", "max_stars_repo_name": "TsurHerman/CommonTools.jl", "max_stars_repo_head_hexsha": "f9104c4644bcb1de56a5a71196cd8905dea7c242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math.jl", "max_issues_repo_name": "TsurHerman/CommonTools.jl", "max_issues_repo_head_hexsha": "f9104c4644bcb1de56a5a71196cd8905dea7c242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math.jl", "max_forks_repo_name": "TsurHerman/CommonTools.jl", "max_forks_repo_head_hexsha": "f9104c4644bcb1de56a5a71196cd8905dea7c242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2777777778, "max_line_length": 66, "alphanum_fraction": 0.6103491272, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828601, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7853858809632066}}
{"text": "\"\"\"\n    parity(char)\n\nCompute whether a characteristic is even or odd.\n\n# Arguments\n- `char::Array{}`: array consisting of two arrays of the same length with 0 or 1 entries.\n\"\"\"\nfunction parity_char(char::Array{})\n    return rem.((transpose(char[1])*char[2]),2);\nend\n\n\n\"\"\"\n    remainder_char(char)\n\nCompute remainder modulo 2 of all the entries of a characteristic.\n\n# Arguments\n- `char::Array{}`: array consisting of two arrays of the same length with 0 or 1 entries.\n\"\"\"\nfunction remainder_char(char::Array{})\n    return [rem.(char[1], 2), rem.(char[2], 2)];\nend\n\n\"\"\"\n    theta_char(g)\n\nCompute all theta characteristics of genus g.\n\n# Arguments\n- `g::Integer`: genus\n\n# Examples\n```julia\njulia> theta_char(4)\n```\n\"\"\"\nfunction theta_char(g::Integer)\n    chars = [digits(i, base=2, pad=2*g) for i = 0:2^(2*g)-1];\n    return [[c[1:g], c[g+1:2*g]] for c in chars];\nend\n\n\"\"\"\n    even_theta_char(g)\n\nCompute all even theta characteristics of genus g.\n\n# Arguments\n- `g::Integer`: genus\n\n# Examples\n```julia\njulia> even_theta_char(4)\n```\n\"\"\"\nfunction even_theta_char(g::Integer)\n    char = theta_char(g);\n    even_char = filter(x -> parity_char(x) == 0, char);\n    return even_char;\nend\n\n\"\"\"\n    odd_theta_char(g)\n\nCompute all odd theta characteristics of genus g.\n\n# Arguments\n- `g::Integer`: genus\n\n# Examples\n```julia\njulia> odd_theta_char(4)\n```\n\"\"\"\nfunction odd_theta_char(g::Integer)\n    char = theta_char(g);\n    odd_char = filter(x -> parity_char(x) == 1, char);\n    return odd_char;\nend\n\n\"\"\"\n    check_azygetic(chars)\n\nCheck if a list of characteristics is azygetic.\n\n# Arguments\n- `chars::Array{}`: array where each entry is an array consisting of two arrays of the same length with 0 or 1 entries.\n\n# Examples\n```julia\njulia> check_azygetic([[[1,0,1,0], [1,0,1,0]], [[0,0,0,1], [1,0,0,0]], [[0,0,1,1], [1,0,1,1]]])\n\"\"\"\nfunction check_azygetic(chars::Array{})\n    for i = 1:length(chars), j = i+1:length(chars), k = j+1:length(chars)\n        if parity_char(remainder_char(chars[i] + chars[j] + chars[k])) == 0\n            return false\n        end\n    end\n    return true\nend\n\n\n", "meta": {"hexsha": "e297937bbba41a3d171ad7eb77e324b6d1fd45ca", "size": 2083, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/characteristics.jl", "max_stars_repo_name": "vchuravy/Theta.jl", "max_stars_repo_head_hexsha": "c18971456d4aa36bf0f109366ee897e68a413152", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-09-17T23:51:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T17:20:32.000Z", "max_issues_repo_path": "src/characteristics.jl", "max_issues_repo_name": "vchuravy/Theta.jl", "max_issues_repo_head_hexsha": "c18971456d4aa36bf0f109366ee897e68a413152", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-04T16:32:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T08:18:16.000Z", "max_forks_repo_path": "src/characteristics.jl", "max_forks_repo_name": "vchuravy/Theta.jl", "max_forks_repo_head_hexsha": "c18971456d4aa36bf0f109366ee897e68a413152", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T23:19:24.000Z", "avg_line_length": 20.0288461538, "max_line_length": 119, "alphanum_fraction": 0.6500240038, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7853804103905229}}
{"text": "function d1hat(n::Int64, dx::Float64 )\r\n    operator = zeros(n,n) # initialize\r\n    for k in 1:n\r\n        try operator[k, k+1] = 1. catch; Nothing end    \r\n        try operator[k, k-1] = -1. catch; Nothing end\r\n    end\r\n\r\n    return operator./(2*dx)\r\nend\r\n\r\nfunction d2hat(n::Int64, dx::Float64 )\r\n    operator = zeros(n,n)\r\n    for k in 1:n\r\n        operator[k,k] = -2.\r\n        try operator[k, k+1] = 1. catch; Nothing end    \r\n        try operator[k, k-1] = 1. catch; Nothing end\r\n    end\r\n\r\n    return operator./(dx^2)\r\nend\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "63fa6a8a82c302a2fecf11f117cf2547d650bcc8", "size": 541, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/diff_operators.jl", "max_stars_repo_name": "leogabac/FiscomTools.jl", "max_stars_repo_head_hexsha": "6f47512c3ccc1a866088141fc367554cdf88dc84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/diff_operators.jl", "max_issues_repo_name": "leogabac/FiscomTools.jl", "max_issues_repo_head_hexsha": "6f47512c3ccc1a866088141fc367554cdf88dc84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/diff_operators.jl", "max_forks_repo_name": "leogabac/FiscomTools.jl", "max_forks_repo_head_hexsha": "6f47512c3ccc1a866088141fc367554cdf88dc84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.037037037, "max_line_length": 57, "alphanum_fraction": 0.5341959335, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7853804020121475}}
{"text": "\n\n\"\"\"\n    find_ratbasis(list::AbstractVector{<:StaticVector{N,<:Rational{T}}}) where {N,T}\n\nGiven a list of `N`-dimensional rational vectors, return a `N×N` matrix whose columns\nare independent vectors from the list.\nIf no such `N` vectors exist, the returned matrix will not be invertible.\n\"\"\"\nfunction find_ratbasis(list::AbstractVector{<:StaticVector{N,<:Rational{T}}}) where {N,T}\n    U = widen(T)\n    n = length(list)\n    ratbasis = zero(SizedMatrix{N,N,Rational{U}})\n    i = 1\n    @inbounds while i <= n\n        l = list[i]\n        if !iszero(l)\n            ratbasis[:,1] .= l\n            i += 1\n            break\n        end\n        i += 1\n    end\n    j = 2\n    while i <= n && j <= N\n        l = list[i]\n        if iszero(l)\n            i += 1\n            continue\n        end\n        ratbasis[:,j] .= l\n        if rank(@view ratbasis[:,1:j]) == j\n            j += 1\n        end\n        i += 1\n    end\n    return ratbasis\nend\n\n# Specialized version for N = 3\nfunction find_ratbasis(list::AbstractVector{<:StaticVector{3,<:Rational{T}}}) where T\n    U = widen(T)\n    n = length(list)\n    ratbasis = zero(SizedMatrix{3,3,Rational{U}})\n    # We start by computing a basis for the i first vectors of v where i (≤ n) is minimal\n    i = 1\n    @inbounds while i <= n\n        if !iszero(list[i])\n            ratbasis[:,3] .= list[i]\n            i += 1\n            break\n        end\n        i += 1\n    end\n    @inbounds while i <= n\n        v = list[i]\n        valid = false\n        # v is valid if it is linearly independant of ratbasis[:,3]\n        if iszero(v[1])\n            valid = (!iszero(ratbasis[1,3]) & (!iszero(v[2]) | !iszero(v[3]))) ||\n                    (v[2] * ratbasis[3,3] != v[3] * ratbasis[2,3])\n        else\n            x = ratbasis[1,3] // v[1]\n            valid = ratbasis[2,3] != x * v[2] || ratbasis[3,3] != x * v[3]\n        end\n        if valid\n            ratbasis[:,2] .= v\n            i += 1\n            break\n        end\n        i += 1\n    end\n    d = zero(Rational{U})\n    @inbounds while i <= n\n        v = list[i]\n        ratbasis[:,1] .= v\n        d = det(ratbasis)\n        iszero(d) || break\n        i += 1\n    end\n    # At this point ratbasis is a basis in which the i-1 first coordinates are\n    # [0, 0, 1] followed by a (possibly empty) series of [0, 0, x], then\n    # [0, 1, 0] followed by a (possibly empty) series of [0, x, y], then [1, 0, 0]\n    @inbounds if d < 0\n        ratbasis[:,1] .= .-ratbasis[:,1] # Ensure a direct transformation\n    end\n    return SMatrix{3,3,Rational{U}}(ratbasis)\nend\n\n# Specialized version for N = 2\nfunction find_ratbasis(list::AbstractVector{<:StaticVector{2,<:Rational{T}}}) where T\n    U = widen(T)\n    n = length(list)\n    ratbasis = zero(SizedMatrix{2,2,Rational{U}})\n    i = 1\n    @inbounds while i <= n\n        if !iszero(list[i])\n            ratbasis[:,1] .= list[i]\n            i += 1\n            break\n        end\n        i += 1\n    end\n    d = zero(Rational{U})\n    @inbounds while i <= n\n        v = list[i]\n        ratbasis[:,2] .= v\n        d = det(ratbasis)\n        iszero(d) || break\n        i += 1\n    end\n    @inbounds if d < 0\n        ratbasis[:,1] .= .-ratbasis[:,1]\n    end\n    return SMatrix{2,2,Rational{U}}(ratbasis)\nend\n\n\"\"\"\n    normal_basis_rational(list::AbstractVector{<:StaticVector{N,<:Rational{T}}}) where {N,T}\n\nGiven a list of `N`-dimensional rational vectors, return a basis for the space\nspanned by integer combinations of these vectors.\n\nThis basis is deterministically computed from the input.\n\nIt should depend only on the spanned space, not on the exact input (although this\nassertion should be considered experimental for now).\n\"\"\"\nfunction normal_basis_rational(list::AbstractVector{<:StaticVector{N,<:Rational{T}}}) where {N,T}\n    U = widen(T)\n    n = length(list)\n    ratbasis = find_ratbasis(list)\n    # ratbasis should always be invertible in our setting: if not, it means that\n    # we missed the fact that the dimensionality of the graph was strictly lower\n    # than N, which should have been detected much earlier.\n    # In this case, the definition of invratbasis will cause a failure.\n\n    lcms = SizedVector{N,T}(ones(T, N))\n    # per-column lcm of the vectors expressed in ratbasis\n    expressed_in_ratbasis = Vector{SVector{N,Rational{T}}}(undef, n)\n    invratbasis = inv(ratbasis) # See comment above in case of error here.\n    @inbounds for j in 1:n\n        expressed_in_ratbasis[j] = invratbasis * list[j]\n        lcms .= lcm.(lcms, denominator.(expressed_in_ratbasis[j]))\n    end\n\n    expressed_in_basis = [MVector{N,Int}(undef) for _ in 1:n]\n    @inbounds for j in 1:n\n        x = expressed_in_ratbasis[j]\n        expressed_in_basis[j] .= div.(numerator.(x).*lcms, denominator.(x))\n    end\n    #= lcms contains the lcm of all denominators of the coordinates of translations\n       expressed in ratbasis.\n       We now work in an artificial basis in which the coordinates are all integers.\n       The integer coordinates are stored in expressed_in_basis.\n       expressed_in_basis is now going to be reduced to its normal form.\n    =#\n\n    intbasis, _ = PeriodicGraphs.normal_basis(expressed_in_basis)\n\n    # We finally go back from the integer normal form to a rational basis that expresses\n    # all the original vectors with integer coordinates\n    return SMatrix{N,N,Rational{U}}(ratbasis * [@inbounds(intbasis[i,j] // lcms[i]) for i in 1:N, j in 1:N])\n\n    # newcoords = [SVector{N,Int}(normalization * x) for x in intcoords]\n    # @toggleassert (newbasis,) .* newcoords == list\n\n    # return newbasis, newcoords\nend\n\n# Specialized version for N = 1\nfunction normal_basis_rational(list::AbstractVector{<:StaticVector{1,<:Rational{T}}}) where T\n    nzl = [x[] for x in list if !iszero(x[])]\n    den = lcm(denominator.(nzl))\n    S = widen(T)\n    num = minimum(S[abs(S(den*x)) for x in nzl])\n    return SMatrix{1,1,Rational{S}}((num // den,))\nend\n", "meta": {"hexsha": "4a8618360a8fa3b4f37eb0650de83ad03e475b11", "size": 5881, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/arithmetics.jl", "max_stars_repo_name": "coudertlab/CrystalNet.jl", "max_stars_repo_head_hexsha": "5d38d226bb492985e748f785c082dda0e3b3f2de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/arithmetics.jl", "max_issues_repo_name": "coudertlab/CrystalNet.jl", "max_issues_repo_head_hexsha": "5d38d226bb492985e748f785c082dda0e3b3f2de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/arithmetics.jl", "max_forks_repo_name": "coudertlab/CrystalNet.jl", "max_forks_repo_head_hexsha": "5d38d226bb492985e748f785c082dda0e3b3f2de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8547486034, "max_line_length": 108, "alphanum_fraction": 0.5964971944, "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7853803982789788}}
{"text": "using SpecialFunctions\n\n\"\"\"\nStandard deviation of the standard deviation of a Normal sample with size nObs\n\nSource: http://stats.stackexchange.com/questions/631/standard-deviation-of-standard-deviation\n\nIN\n  xStd\n     std dev of x\n  nObs\n     no of observations\n\"\"\"\nfunction std_std(xStdV :: Vector{T1}, nObsV :: Vector{T2}, dbg :: Bool) where \n\t{T1 <: AbstractFloat, T2 <: Integer}\n\n\tn = length(xStdV);\n\n\tstdStdV = zeros(n);\n\tfor ix = 1 : n\n\t   nObs = Float64(nObsV[ix]);\n\t   if nObs < 300\n\t\t   # Gamma function from SpecialFunctions\n\t\t  gamma1 = gamma((nObs - 1.0) / 2.0)\n\t\t  gamma2 = gamma(nObs / 2.0)\n\t   else\n\t\t  # Approximation\n\t\t  #  See https://en.wikipedia.org/wiki/Gamma_function#Approximations\n\t\t  z1 = (nObs - 1.0) / 2.0 - 1.0;\n\t\t  z2 = nObs / 2.0 - 1.0;\n\t\t  gamma2 = 1.0;\n\t\t  gamma1 = exp(0.5 * log(z1) + z1 * (log(z1) - 1) - 0.5 * log(z2) - z2 * (log(z2) - 1));\n\t   end\n\n\t   # Ratio of gamma2 / gamma1\n\t   g21 = gamma2 / gamma1;\n\n\t   stdStdV[ix] = xStdV[ix] / g21 * sqrt((nObs-1) / 2 - g21 ^ 2);\n\tend\n\n\n\t##  Output check\n\tif dbg\n\t   @assert (all(stdStdV .>= 0));\n\tend\n\n\treturn stdStdV\nend\n", "meta": {"hexsha": "0a001898d7d31c8394b1201c6300f0aa7e86b0d7", "size": 1103, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stats/std_std.jl", "max_stars_repo_name": "hendri54/CommonLH", "max_stars_repo_head_hexsha": "aba46201434da0c3fec6476b66de750eb1f7e493", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stats/std_std.jl", "max_issues_repo_name": "hendri54/CommonLH", "max_issues_repo_head_hexsha": "aba46201434da0c3fec6476b66de750eb1f7e493", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stats/std_std.jl", "max_forks_repo_name": "hendri54/CommonLH", "max_forks_repo_head_hexsha": "aba46201434da0c3fec6476b66de750eb1f7e493", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5102040816, "max_line_length": 93, "alphanum_fraction": 0.6083408885, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7853803948003557}}
{"text": "##  SCRIPT NAME:   getEquiprobNormalDeviates.jl\r\n##  DATE:          Jnauary 2015\r\n#\r\n#   This script generates N equiprobable line segments in the stationary\r\n#   univariate normal distribution of income Y:\r\n#          Y ~ N [ alpha/1-rho  ;  sigma_epsilon^2/(1-rho)^2 ]\r\n#   where the mean of the above distribution is declared below as 'Ymean'\r\n#   and the standard deviation as 'Ysd'. It delivers two arrays: 'Bounaries'\r\n#   which holds the N+1 bounds of the N equiprobable segments, and\r\n#   'ExpValues' which holds the expected value in each segment.\r\n#\r\n#\r\n##  ALEXANDROS THELOUDIS, UCL\r\n#\r\n#  Needs: A constant called \"normBnd\"\r\n\r\n##  ---------------------------------------------------------------------------------------------\r\n\r\nfunction getEquiprobNormalDeviates(Ymean, Ysd, N)\r\n\r\n  #  Initialise output:\r\n  Boundaries = zeros(N+1)\r\n  ExpValues  = zeros(N)\r\n\r\n\r\n  #  --------------------------------------------------------------------------------------------\r\n  #  Calculate applicable support of univariate normal distribution (first and\r\n  #  last point in the range that I divide equiprobably). Note: in principle\r\n  #  this is +-infinity but I am ruling some extremely unlikely values out:\r\n  Boundaries[1]   = Ymean - normBnd * Ysd\r\n  Boundaries[N+1] = Ymean + normBnd * Ysd\r\n\r\n\r\n  #  --------------------------------------------------------------------------------------------\r\n  #  Sequentially calculate the remaining bounds of the equiprobable regions:\r\n  for ixi = 2:1:N\r\n    Boundaries[ixi] = quantile(TruncatedNormal(Ymean,Ysd,Boundaries[1],Boundaries[N+1]), (ixi-1)/N)\r\n  end\r\n\r\n\r\n  #  --------------------------------------------------------------------------------------------\r\n  #  Calculate the expected value of a random variable X ~ N[Ymean,Ysd^2] which\r\n  #  is bounded by the equiprobable line segment above. Note: this is essentially\r\n  #  the mean of a univariate 2-sided truncated normal distribution; read more\r\n  #  on http://en.wikipedia.org/wiki/Truncated_normal_distribution\r\n  for ixi = 1:1:N\r\n    ExpValues[ixi] = Ymean + Ysd * N * (pdf(Normal(),(Boundaries[ixi]-Ymean)/Ysd) - pdf(Normal(),(Boundaries[ixi+1]-Ymean)/Ysd))\r\n  end\r\n\r\n  return (Boundaries, ExpValues)\r\n\r\nend\r\n\r\n", "meta": {"hexsha": "9c00319861c5f72413d1240adab4e9fe1460212d", "size": 2219, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LifecycleCostaDias/v5_julia/code_numericTools/getEquiprobNormalDeviates.jl", "max_stars_repo_name": "floswald/ucl-econ-julia", "max_stars_repo_head_hexsha": "c0b9077382d4245fb1276ae2f517cc9372259c25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-08-18T00:50:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-18T00:50:53.000Z", "max_issues_repo_path": "LifecycleCostaDias/v5_julia/code_numericTools/getEquiprobNormalDeviates.jl", "max_issues_repo_name": "floswald/ucl-econ-julia", "max_issues_repo_head_hexsha": "c0b9077382d4245fb1276ae2f517cc9372259c25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-05-01T13:10:23.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-14T08:44:31.000Z", "max_forks_repo_path": "LifecycleCostaDias/v5_julia/code_numericTools/getEquiprobNormalDeviates.jl", "max_forks_repo_name": "floswald/ucl-econ-julia", "max_forks_repo_head_hexsha": "c0b9077382d4245fb1276ae2f517cc9372259c25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-04-25T11:54:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T01:23:04.000Z", "avg_line_length": 41.0925925926, "max_line_length": 129, "alphanum_fraction": 0.5682739973, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574129515172, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7853610977279922}}
{"text": "using LinearAlgebra\nusing Plots\n\nexport plotnormal2d\n\n\"\"\"\n    plotnormal2d(p, μ::AbstractVector, Σ::AbstractMatrix; ncontours=2, args...)\n\nPlot the contours of a 2d Normal density. `ncontours` is the number of\ncontour line to plots.\n\"\"\"\nfunction plotnormal2d(p, μ::AbstractVector, Σ::AbstractMatrix; ncontours=2, color=\"blue\", label=\"\", args...)\n    λ, U = eigen(Σ)\n    for i in 1:ncontours\n        B = U * diagm(i * sqrt.(λ))\n        θ = range(0, stop=2 * pi, length=1000)\n        circle = hcat(sin.(θ), cos.(θ))'\n        contour = B * circle .+ μ\n        plot!(p, contour[1, :], contour[2, :]; color=color, label=i > 1 ? \"\" : label, args...)\n    end\n    p\nend\n\n", "meta": {"hexsha": "49526b7190430c440f8505fc1af6114dd80ad8d5", "size": 663, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Plotting.jl", "max_stars_repo_name": "fnlandini/BayesianModels", "max_stars_repo_head_hexsha": "a8a6769561431faa2b1ec04ee4ca73a9d3baa896", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Plotting.jl", "max_issues_repo_name": "fnlandini/BayesianModels", "max_issues_repo_head_hexsha": "a8a6769561431faa2b1ec04ee4ca73a9d3baa896", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Plotting.jl", "max_forks_repo_name": "fnlandini/BayesianModels", "max_forks_repo_head_hexsha": "a8a6769561431faa2b1ec04ee4ca73a9d3baa896", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-19T09:10:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-19T09:10:07.000Z", "avg_line_length": 27.625, "max_line_length": 108, "alphanum_fraction": 0.6078431373, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809826, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.785320917378795}}
{"text": "function adaptive_simpsons_inner(f::Function, a::Real, b::Real,\n                                 epsilon::Real, S::Real,\n                                 fa::Real, fb::Real, fc::Real, bottom::Int)\n    c = (a + b) / 2\n    h = b - a\n    d = (a + c) / 2\n    g = (c + b) / 2\n    fd = f(d)\n    fe = f(g)\n    Sleft = (h / 12) * (fa + 4 * fd + fc)\n    Sright = (h / 12) * (fc + 4 * fe + fb)\n    S2 = Sleft + Sright\n    if bottom <= 0 || abs(S2 - S) <= 15 * epsilon\n        return S2 + (S2 - S) / 15\n    end\n    return adaptive_simpsons_inner(f, a, c, epsilon / 2, Sleft,  fa, fc, fd, bottom - 1) +\n           adaptive_simpsons_inner(f, c, b, epsilon / 2, Sright, fc, fb, fe, bottom - 1)\nend\n\nfunction adaptive_simpsons_outer(f::Function, a::Real, b::Real, accuracy::Real, max_iterations::Int)\n    c = (a + b) / 2\n    h = b - a\n    fa = f(a)\n    fb = f(b)\n    fc = f(c)\n    S = (h / 6) * (fa + 4 * fc + fb)\n  return adaptive_simpsons_inner(f, a, b, accuracy, S, fa, fb, fc, max_iterations)\nend\nadaptive_simpsons_outer(f::Function, a::Real, b::Real) = adaptive_simpsons_outer(f, a, b, 10e-10, 50)\n\nfunction monte_carlo(f::Function, a::Real, b::Real, iterations::Int)\n    estimate = 0.0\n    width = (b - a)\n    for i in 1:iterations\n        x = width * rand() + a\n        estimate += f(x) * width\n    end\n    return estimate / iterations\nend\n\nfunction integrate(f::Function, a::Real, b::Real, method::Symbol)\n    if method == :simpsons\n        adaptive_simpsons_outer(f, a, b)\n    elseif method == :monte_carlo\n        monte_carlo(f, a, b, 10_000)\n    else\n        error(\"Unknown method of integration: $(method)\")\n    end\nend\nintegrate(f::Function, a::Real, b::Real) = integrate(f, a, b, :simpsons)\n", "meta": {"hexsha": "a9fdc4c6af7d91cf4cba5170689dd2037657927c", "size": 1690, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/integrate.jl", "max_stars_repo_name": "aviks/Calculus.jl", "max_stars_repo_head_hexsha": "4a80d5903bfda4b02bc17331734d756009a08fa6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-22T09:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-22T09:31:52.000Z", "max_issues_repo_path": "src/integrate.jl", "max_issues_repo_name": "aviks/Calculus.jl", "max_issues_repo_head_hexsha": "4a80d5903bfda4b02bc17331734d756009a08fa6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/integrate.jl", "max_forks_repo_name": "aviks/Calculus.jl", "max_forks_repo_head_hexsha": "4a80d5903bfda4b02bc17331734d756009a08fa6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.137254902, "max_line_length": 101, "alphanum_fraction": 0.550295858, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7853209142976879}}
{"text": "@inline function add_ddfp_dd(x::Tuple{T,T}, y::T) where {T<:IEEEFloat}\n    hi, lo = x\n    hi, lo = two_sum(hi, y, lo)\n    return hi, lo\nend\n\n@inline function sub_ddfp_dd(x::Tuple{T,T}, y::T) where {T<:IEEEFloat}\n    hi, lo = x\n    hi, lo = two_sum(hi, lo, -y)\n    return hi, lo\nend\n\n#=\n@inline function mul_ddfp_dd(x::Tuple{T,T}, y::T) where {T<:IEEEFloat}\n    hi, lo = x\n    hihi, hilo = two_prod(y, hi)\n    lohi, lolo = two_prod(y, lo)\n    hi, lo = two_sum(hihi, hilo, lohi, lolo)\n    return hi, lo\nend\n=#\n\n# Algorithm 12 from Tight and rigourous error bounds.  relative error <= 5u²\n@inline function mul_ddfp_dd(x::Tuple{T,T}, y::T) where T<:IEEEFloat\n    xhi, xlo = x\n    hi, lo = two_prod(xhi, y)\n    t = xlo * y\n    t = t + lo\n    hi, lo = two_hilo_sum(hi, t)\n    return hi, lo\nend\n\n@inline function dvi_ddfp_dd(x::Tuple{T,T}, y::T) where {T<:IEEEFloat}\n    xhi, xlo = x    \n    hi = xhi / y\n    uh, ul = two_prod(hi, y)\n    lo = ((((xhi - uh) - ul) + xlo))/y\n    hi,lo = two_hilo_sum(hi, lo)\n    return hi, lo\nend\n", "meta": {"hexsha": "1539bd1d209107b59eb5a59c45e0a5a4a6587dc4", "size": 1021, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/ops/op_ddfp_dd.jl", "max_stars_repo_name": "Mechachleopteryx/DoubleFloats.jl", "max_stars_repo_head_hexsha": "caad59ed87fa86af3df7c13ab8c86b49faaf436c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 107, "max_stars_repo_stars_event_min_datetime": "2018-02-07T14:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:44:41.000Z", "max_issues_repo_path": "src/math/ops/op_ddfp_dd.jl", "max_issues_repo_name": "Mechachleopteryx/DoubleFloats.jl", "max_issues_repo_head_hexsha": "caad59ed87fa86af3df7c13ab8c86b49faaf436c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 125, "max_issues_repo_issues_event_min_datetime": "2018-04-15T13:56:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:12:12.000Z", "max_forks_repo_path": "src/math/ops/op_ddfp_dd.jl", "max_forks_repo_name": "Mechachleopteryx/DoubleFloats.jl", "max_forks_repo_head_hexsha": "caad59ed87fa86af3df7c13ab8c86b49faaf436c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2018-04-27T10:17:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:44:20.000Z", "avg_line_length": 24.9024390244, "max_line_length": 76, "alphanum_fraction": 0.5857002938, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666345, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.785320912604936}}
{"text": "module ols\n\nexport tols, summary\n\n# Author: Adam Savitzky\n# Email: asavitzky@forio.com\n# Github: github.com/adambom\n\n# Ported from the Python implemented by Vincent Nijs\n# http://www.scipy.org/Cookbook/OLS?action=AttachFile&do=get&target=ols.0.2.py\n\n# Julia type for multiple (multivariate) regression using OLS\n# For least squared regression on linear equations of multiple independent variables\n# y = a1 * x1 + a2 * x2 + ... an * xn\n# Y = AX + E\n\n# Input\n## y = dependent variable\n## y_varnm = string with the variable label for y\n## x = independent variables, note that a constant is added by default\n## x_varnm = list of variable labels for the independent variables\n\n# Usage\n## Instantiate a new ols type\n### reg = ols(y, x, \"y\", [\"x1\", \"x2\", \"x3\"])\n### Coefficients: reg.b\n### R-Squared: reg.R2\n### F-Statistic: reg.F\n### Summary: summary(reg)\n\ntype tols\n    y::Array{Float64}\n    x::Array{Float64}\n    y_varnm::String\n    x_varnm::Array{String, 1}\n    inv_xx::Array{Float64}\n    b::Array{Float64, 1}\n    nobs::Int\n    ncoef::Int\n    df_e::Int\n    df_r::Int\n    er::Array\n    sse::Float64\n    se::Array{Float64, 1}\n    t::Array{Float64}\n    #p::Array\n    R2::Float64\n    R2adj::Float64\n    F::Float64\n    #Fpv::Float64\n    \n    function tols(y, x, y_varnm, x_varnm)\n        x = hcat(ones(size(x, 1)), x)\n        xT = transpose(x)\n\n        inv_xx = inv(xT * x)\n        xy = xT * y\n        b = inv_xx * xy           # estimate coefficients\n\n        nobs = size(y, 1)         # number of observations\n        ncoef = size(x, 2)        # number of coefficients\n        df_e = nobs - ncoef       # degrees of freedom, error \n        df_r = ncoef - 1          # degrees of freedom, regression\n\n        er = y - x * b            # residuals\n        sse = e^2/df_e            # SSE\n        se = sqrt(diag(sse * inv_xx)) # coef. standard errors\n        t = b / se                # coef. t-statistics\n        # p = (1 - cdf(abs(t), df_e)) * 2 # coef. p-values\n\n        R2 = 1 - var(er) / var(y) # model R-squared\n        R2adj = 1 - (1 - R2) * ((nobs - 1) / (nobs - ncoef)) # adjusted R-square\n\n        F = (R2 / df_r) / ((1 - R2) / df_e) # model F-statistic\n        # Fpv = 1 - cdf(F, df_r, df_e) # F-statistic p-value\n\n        new(y, x, y_varnm, x_varnm, inv_xx, b, nobs, ncoef, df_e, df_r, er, sse, se, t, R2, R2adj, F)\n    end\nend\n\nfunction dw(self::tols)\n    # Calculates the Durbin-Waston statistic\n    de = self.er - 1.\n    result = dot(de, de) / dot(self.er, self.er)\n    return result\nend\n\nfunction ll(self::tols)\n    # Calculate model log-likelihood and two information criteria\n        \n    # Model log-likelihood, AIC, and BIC criterion values \n    loglike = -(self.nobs / 2) * (1 + log(2pi)) - (self.nobs / 2) * log(dot(self.er, self.er) / self.nobs)\n    aic = -2loglike / self.nobs + (2 * self.ncoef / self.nobs)\n    bic = -2loglike / self.nobs + (self.ncoef * log(self.nobs)) / self.nobs\n\n    return loglike, aic, bic\nend\n\nfunction summary(self::tols)\n    # print model output to screen\n\n    t = time()\n\n    # extra stats\n    loglike, aic, bic = ll(self)\n    #JB, JBpv, skew, kurtosis = self.JB()\n    #omni, omnipv = self.omni()\n\n    println(\"==============================================================================\")\n    #println(\"Dependent Variable: \" + self.y_varnm)\n    println(\"Method: Least Squares\")\n    println(\"Time: $t\")\n    println(\"No. obs:               $(self.nobs)\")\n    println(\"No. variables:         $(self.ncoef)\")\n    println(\"==============================================================================\")\n    println(\"variable             coefficient             std. Error              t-statistic\")\n    println(\"==============================================================================\")\n    for i in 1:length(self.x_varnm)\n        println(\"$(self.x_varnm[i])         $(self.b[i])        $(self.se[i])        $(self.t[i])\")\n    end\n    println(\"========================================================================================\")\n    println(\"Model Stats                                    Residual Stats\")\n    println(\"========================================================================================\")\n    println(\"R-Squared            $(self.R2)        Durbin-Watson Stat: $(dw(self))\")\n    println(\"Adjusted R-Squared   $(self.R2adj)        Omnimbus Stat:      ?\")\n    println(\"F-Statistic          $(self.F)        Prob(Omnibus stat): ?\")\n    println(\"Log-Likelihood       $loglike       Prob(JB):           ?\")\n    println(\"AIC Criterion        $aic        Skew:               ?\")\n    println(\"BIC Criterion        $bic         Kurtosis:           ?\")\n    println(\"========================================================================================\")\nend\n\nfunction linreg{T<:Number}(X::StridedVecOrMat{T}, y::Vector{T})\n    hcat(ones(T, size(X,1)), X)\\y\nend\n\nend\n", "meta": {"hexsha": "c9280282eb6e64e50ea60ef7c3908164c57518eb", "size": 4834, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chp06/Code/ols.jl", "max_stars_repo_name": "PetrKryslUCSD/Mastering-Julia-1.0", "max_stars_repo_head_hexsha": "375342d933a48142b5b605b9c39cb5922e010691", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2017-02-12T15:36:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T03:30:39.000Z", "max_issues_repo_path": "Module 3/Chapter05/ols.jl", "max_issues_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_issues_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Module 3/Chapter05/ols.jl", "max_forks_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_forks_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-02-10T16:19:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T11:46:44.000Z", "avg_line_length": 35.0289855072, "max_line_length": 106, "alphanum_fraction": 0.5033098883, "num_tokens": 1359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.7853209122958967}}
{"text": "using PyPlot\nusing LinearAlgebra\n\na = [ 0.5  -1.0   0.25\n      1.0   0.5  -1.0 ]\n\nfunction points(λ, offset)\n    x = zeros(2,3)\n    x[:,1] .= (1-2λ) * a[:,1] +      λ * a[:,2] +      λ * a[:,3]\n    x[:,2] .=      λ * a[:,1] + (1-2λ) * a[:,2] +      λ * a[:,3]\n    x[:,3] .=      λ * a[:,1] +      λ * a[:,2] + (1-2λ) * a[:,3]\n    m = zeros(2,3)\n    m[:,1] = 0.5 * a[:,3] + 0.5 * a[:,2]\n    m[:,2] = 0.5 * a[:,1] + 0.5 * a[:,3]\n    m[:,3] = 0.5 * a[:,2] + 0.5 * a[:,1]\n    J = [1, 2, 3, 1]\n    plot(a[1,J], a[2,J], \"-k\")\n    c = sum(a, dims=2) / 3\n    for j = 1:3\n        plot([a[1,j], m[1,j]], [a[2,j], m[2,j]], \"--k\")\n        text(x[1,j] + offset[1,j], x[2,j] + offset[2,j], \n             latexstring(\"x^{\\\\langle K\\\\rangle}_\", j), color=\"r\",\n             verticalalignment=\"center\", horizontalalignment=\"center\")\n        v = a[:,j] - c\n        v = 0.1 * v / LinearAlgebra.norm(v)\n        text(a[1,j] + v[1] , a[2,j] + v[2], latexstring(\"a_\", j), \n             verticalalignment=\"center\", horizontalalignment=\"center\")\n    end\n    plot(x[1,:], x[2,:], \"or\", markeredgecolor=\"w\")\n    plot(a[1,:], a[2,:], \"ok\", markersize=5.0)\nend\n\nfigure(1)\nsubplot(1, 2, 1)\noffset = [ -0.10  0.10  0.15\n            0.05  0.10  0.05  ]\npoints(1/6, offset)\naxis(\"equal\")\naxis((-1.2, 0.7, -1.2, 1.2))\naxis(\"off\")\n\nsubplot(1, 2, 2)\noffset = [ -0.12  0.15  0.0\n           -0.10  0.0   0.15  ]\npoints(1/2, offset)\naxis(\"equal\")\naxis((-1.2, 0.7, -1.2, 1.2))\naxis(\"off\")\n\nsavefig(\"quadrature_points.pdf\")\n", "meta": {"hexsha": "a03a454381f06ec89b221ccd035f80f11b9bf5a8", "size": 1482, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chap6/quadrature.jl", "max_stars_repo_name": "billmclean/ComputationalMathsNotes", "max_stars_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T21:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:30:20.000Z", "max_issues_repo_path": "src/chap6/quadrature.jl", "max_issues_repo_name": "billmclean/ComputationalMathsNotes", "max_issues_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chap6/quadrature.jl", "max_forks_repo_name": "billmclean/ComputationalMathsNotes", "max_forks_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0588235294, "max_line_length": 70, "alphanum_fraction": 0.4358974359, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682086, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.785294474587919}}
{"text": "\n#=\nBibText\n@TECHREPORT{Benner95acollection,\nauthor = {Peter Benner and Alan J. Laub and Volker Mehrmann},\ntitle = {A Collection of Benchmark Examples for the Numerical Solution of\nAlgebraic Riccati Equations II: Discrete-Time Case},\ninstitution = {FAK. F. MATHEMATIK, TU CHEMNITZ--ZWICKAU},\nyear = {1995}\n}\n    \n=#\n\n# ------------------------------------------------------------------\n# ejm1 collection of benchmark examples\nA1 = [4. 3.;-4.5 -3.5]\nB1 = [1. -1]'\nR1 = 1.\nQ1 = [9. 6.;6. 4.]\nX1 = (1+sqrt(5))/2*[9 6;6 4] # theoretical solucion\n\nX11 = dare(A1,B1,Q1,R1) # computed solution\n    \n# --------------------------------------------------------------------\n# ejm computed with mathematica\nAm = [1. -1 1;0 1 1;0 0 1]\nBm = [1. 0;1 0;0 1]\nRm = [10 0;0 0.1]\nQm = [10 0 0;0 1 0;0 0 0.1]\nXm = [42.2835 -68.5247 -3.94783;-68.5247 154.043 16.0017;-3.94783 16.0017 8.33197] # mathematica solution\n    \nXmm = dare(Am,Bm,Qm,Rm) # computed solution\n    \n#####\n    \n\nprint(\"Testing dare: \")\nif (sum((X1-X11).^2) < 1e-6) && (sum((Xm-Xmm).^2) < 1e-6)\n\tprintln(\"OK\")\nend\n", "meta": {"hexsha": "a390d345a82e5a079043d188fd5d903b1add823b", "size": 1061, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dare_test.jl", "max_stars_repo_name": "javiercara/emACQR.jl", "max_stars_repo_head_hexsha": "acd8be36d722a03e47ec8c49dc2f57bba500cfd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dare_test.jl", "max_issues_repo_name": "javiercara/emACQR.jl", "max_issues_repo_head_hexsha": "acd8be36d722a03e47ec8c49dc2f57bba500cfd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dare_test.jl", "max_forks_repo_name": "javiercara/emACQR.jl", "max_forks_repo_head_hexsha": "acd8be36d722a03e47ec8c49dc2f57bba500cfd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-05T03:32:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-05T03:32:32.000Z", "avg_line_length": 25.8780487805, "max_line_length": 105, "alphanum_fraction": 0.5447690858, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913356558485, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.7852821318580299}}
{"text": "using SemiclassicalOrthogonalPolynomials, ClassicalOrthogonalPolynomials, ForwardDiff, Plots, StaticArrays\nimport ForwardDiff: derivative, jacobian, Dual\nimport SemiclassicalOrthogonalPolynomials: Weighted\nimport ClassicalOrthogonalPolynomials: associated, affine\n\nBase.floatmin(::Type{Dual{T,V,N}}) where {T,V,N} = Dual{T,V,N}(floatmin(V))\nBase.big(d::Dual{T,V,N}) where {T,V,N} = Dual{T}(big(d.value), ForwardDiff.Partials(map(big,d.partials.values)))\n\n#### \n#\n# We first do a single interval.\n# Equilibrium measures for a symmetric potential\n#  with one interval of support \n# a measure w(x) supported on\n# [-b,b]\n# such that\n#       1. H*w == V'\n#       2. sum(w) == 1\n#       3.  w is bounded\n# \n#  rescaling x == b*t these becomes find \n# a measure w̃(t) supported on\n# [-1,1]\n# such that\n#       1. H*w̃ == V'(b*t)\n#       2. sum(w̃) == 1/b\n#       3.  w is bounded\n#\n# Note (1) and (2) can always be satisfied\n# thus the constraint comes from (3).\n# The following gives the evaluation of the\n# unweighted-component of the measure evaluated\n# at (a,b)\n#####\n\n\nV = x -> x^2\nfunction equilibriumcoefficients(T, b)\n    U = associated(T)\n    W = Weighted(T)\n    t = axes(W,1)\n    H = @. inv(t - t')\n    H̃ = U \\H*W\n    [1/(b*sum(W[:,1])); 2H̃[:,2:end] \\ ( U \\ derivative.(V, b*t))]\nend\nfunction equilibriumendpointvalue(b::Number)\n    T = ChebyshevT{typeof(b)}()\n    dot(T[end,:], equilibriumcoefficients(T,b))\nend\n\nfunction equilibrium(b::Number)\n    T = ChebyshevT{typeof(b)}()\n    U = ChebyshevU{typeof(b)}()\n    # convert to Weighted(U) to make value at ±b accurate\n    Weighted(U)[affine(-b..b,axes(T,1)),:] * ((Weighted(T) \\ Weighted(U))[3:end,:] \\ equilibriumcoefficients(T,b)[3:end])\nend\n\nμ = equilibrium(sqrt(2))\n\nT = Chebyshev()\nb = sqrt(2)\nμ = Weighted(T) * equilibriumcoefficients(T, b)\nx = axes(μ,1)\n\nplot(μ)\n\nxx = 0.7; 2b*(log.(abs.(x .- x'))*μ)[xx] - V(b*xx)\n\n\n\nb = 1.0 # initial guess\nfor _ = 1:10\n    b -= derivative(equilibriumendpointvalue,b) \\ equilibriumendpointvalue(b)\nend\nb\n\nplot(equilibrium(b))\n\n\n#####\n# Equilibrium measures for a symmetric potential \n# with two intervals of support consists of finding \n# a measure w(x) supported on\n# [-b,-a] ∪ [a,b]\n# such that\n#       1. H*w == V'\n#       2. sum(w) == 1\n#       3.  w is bounded\n# \n#  rescaling x == b*t these becomes find \n# a measure w̃(t) supported on\n# [-1,-a/b] ∪ [a/b,1]\n# such that\n#       1. H*w̃ == V'(b*t)\n#       2. sum(w̃) == 1/b\n#       3.  w is bounded\n#\n# Note (1) and (2) can always be satisfied\n# thus the two constraints come from (3).\n# The following gives the evaluation of the\n# unweighted-component of the measure evaluated\n# at (a,b)\n#####\nV = x -> x^4 - 10x^2\nfunction equilibriumcoefficients(P,a,b)\n    W = Weighted(P)\n    Q = associated(P)\n    t = axes(W,1)\n    x = axes(Q,1)\n    H = @. inv(x - t')\n    H̃ = Q \\ H*W\n    [1/(b*sum(W[:,1])); 2H̃[:,2:end] \\( Q \\ derivative.(V, b*x))]\nend\nfunction equilibriumendpointvalues(ab::SVector{2})\n    a,b = ab\n    # orthogonal polynomials w.r.t.\n    # abs(x) / (sqrt(1-x^2) * sqrt(x^2 - ρ^2))\n    P = TwoBandJacobi(a/b, -one(a)/2, -one(a)/2, one(a)/2)\n    Vector(P[[a/b,1],:] * equilibriumcoefficients(P,a,b))\nend\n\nfunction equilibrium(ab)\n    a,b = ab\n    P = TwoBandJacobi(a/b, -1/2, -1/2, 1/2)\n    Weighted(P) * equilibriumcoefficients(P,a,b)\nend\n\nab = SVector(2.,3.)\nab -= jacobian(equilibriumendpointvalues,ab) \\ equilibriumendpointvalues(ab)\na,b = ab\nxx = range(-4,4;length=1000)\nμ = equilibrium(ab)\nμx = x -> a < abs(x) < b ? μ[x/b] : 0.0\nplot!(xx, μx.(xx))\n\nplot(equilibrium(ab))\n\n", "meta": {"hexsha": "5decb35cad3660b50810f72194e7271c34243d37", "size": 3539, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/equilibriummeasure.jl", "max_stars_repo_name": "JuliaApproximation/SemiclassicalOrthogonalPolynomials.jl", "max_stars_repo_head_hexsha": "6cdfc10f706edb7e64c9248ad4b3864079d21771", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-02-12T14:02:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-08T22:35:28.000Z", "max_issues_repo_path": "examples/equilibriummeasure.jl", "max_issues_repo_name": "JuliaApproximation/SemiclassicalOrthogonalPolynomials.jl", "max_issues_repo_head_hexsha": "6cdfc10f706edb7e64c9248ad4b3864079d21771", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2020-02-11T14:32:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T19:36:18.000Z", "max_forks_repo_path": "examples/equilibriummeasure.jl", "max_forks_repo_name": "JuliaApproximation/SemiclassicalOrthogonalPolynomials.jl", "max_forks_repo_head_hexsha": "6cdfc10f706edb7e64c9248ad4b3864079d21771", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-15T11:29:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-15T11:29:07.000Z", "avg_line_length": 25.6449275362, "max_line_length": 121, "alphanum_fraction": 0.615428087, "num_tokens": 1219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913354875362, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7852821285266999}}
{"text": "# Description:\n# Dimensions: d\n\n# The Zakharov function has no local minima except the global one. It is shown here in its two-dimensional form.\n\n# Input Domain:\n# The function is usually evaluated on the hypercube xi ∈ [-5, 10], for all i = 1, …, d.\n\n# Global Minimum:\n# https://www.sfu.ca/~ssurjano/zakharov3.png\n\nfunction zakharov(xx)\n    d = length(xx);\n    sum1 = 0;\n    sum2 = 0;\n\n    for ii = 1:d\n       \txi = xx[ii];\n       \tsum1 = sum1 + xi^2;\n       \tsum2 = sum2 + 0.5 * ii * xi;\n    end\n\n    y = sum1 + sum2^2 + sum2^4;\n\n    return [y]\nend\n", "meta": {"hexsha": "123d4ce51049c661a274a4c693f3d30e5c959226", "size": 551, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "zakharov.jl", "max_stars_repo_name": "cagataycali/bacterial-foraging-optimization-algorithm", "max_stars_repo_head_hexsha": "b84ac0667707e36dbaa4a50457074245b174b491", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "zakharov.jl", "max_issues_repo_name": "cagataycali/bacterial-foraging-optimization-algorithm", "max_issues_repo_head_hexsha": "b84ac0667707e36dbaa4a50457074245b174b491", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "zakharov.jl", "max_forks_repo_name": "cagataycali/bacterial-foraging-optimization-algorithm", "max_forks_repo_head_hexsha": "b84ac0667707e36dbaa4a50457074245b174b491", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4074074074, "max_line_length": 112, "alphanum_fraction": 0.5952813067, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.785282127639365}}
{"text": "\"\"\"\n    LexicographicallyLessThan(row_dim::Int, column_dim::Int)\n\nEnsures that each column of the matrix is lexicographically less than \nthe next column. \n\nFormally, for two columns:\n\n``\\\\{(x, y) \\\\in \\\\mathbb{R}^\\\\mathtt{column\\\\_dim} \\\\times \\\\mathbb{R}^\\\\mathtt{column\\\\_dim} | \\\\exists j \\\\in \\\\{1, 2 \\\\dots \\\\mathtt{column\\\\_dim}\\\\}: x_j < y_j, \\\\forall i < j, x_i = y_i \\\\}``.\n\nAlso called [`lex_less`](https://sofdem.github.io/gccat/gccat/Clex_less.html).\n\nThe matrix is encoded by stacking the columns, matching the behaviour of\nJulia's `vec` function.\n\"\"\"\nstruct LexicographicallyLessThan <: MOI.AbstractVectorSet\n    row_dim::Int\n    column_dim::Int\nend\n\nfunction LexicographicallyLessThan(column_dim::Int)\n    # By default, only two columns.\n    return LexicographicallyLessThan(2, column_dim)\nend\n\nMOI.dimension(set::LexicographicallyLessThan) = set.row_dim * set.column_dim\n\n\"\"\"\n    LexicographicallyGreaterThan(row_dim::Int, column_dim::Int)\n\nEnsures that each column of the matrix is lexicographically greater than \nthe next column. \n\nFormally, for two columns:\n\n``\\\\{(x, y) \\\\in \\\\mathbb{R}^\\\\mathtt{column\\\\_dim} \\\\times \\\\mathbb{R}^\\\\mathtt{column\\\\_dim} | \\exists j \\\\in \\\\{1, 2 \\\\dots \\\\mathtt{column\\\\_dim}\\\\}: x_j > y_j, \\\\forall i < j, x_i = y_i \\\\}``.\n\nAlso called [`lex_greater`](https://sofdem.github.io/gccat/gccat/Clex_greater.html).\n\nThe matrix is encoded by stacking the columns, matching the behaviour of\nJulia's `vec` function.\n\"\"\"\nstruct LexicographicallyGreaterThan <: MOI.AbstractVectorSet\n    row_dim::Int\n    column_dim::Int\nend\n\nfunction LexicographicallyGreaterThan(column_dim::Int)\n    # By default, only two columns.\n    return LexicographicallyGreaterThan(2, column_dim)\nend\n\nMOI.dimension(set::LexicographicallyGreaterThan) = set.row_dim * set.column_dim\n\n# TODO: bridge to LexicographicallyLessThan.\n\n\"\"\"\n    DoublyLexicographicallyLessThan(dimension::Int)\n\nEnsures that each column of the matrix is lexicographically less than \nthe next column, and that each row of the matrix is lexicographically less \nthan the next row. \n\nAlso called [`lex2`](https://sofdem.github.io/gccat/gccat/Clex2.html).\n\nThe matrix is encoded by stacking the columns, matching the behaviour of\nJulia's `vec` function.\n\"\"\"\nstruct DoublyLexicographicallyLessThan <: MOI.AbstractVectorSet\n    row_dim::Int\n    column_dim::Int\nend\n\nMOI.dimension(set::DoublyLexicographicallyLessThan) = set.row_dim * set.column_dim\n\n\"\"\"\n    DoublyLexicographicallyGreaterThan(dimension::Int)\n\nEnsures that each column of the matrix is lexicographically greater than \nthe next column, and that each row of the matrix is lexicographically greater \nthan the next row. \n\nThe matrix is encoded by stacking the columns, matching the behaviour of\nJulia's `vec` function.\n\"\"\"\nstruct DoublyLexicographicallyGreaterThan <: MOI.AbstractVectorSet\n    row_dim::Int\n    column_dim::Int\nend\n\nMOI.dimension(set::DoublyLexicographicallyGreaterThan) = set.row_dim * set.column_dim\n\n# TODO: bridge to LexicographicallyLessThan.\n\n\"\"\"\n    Sort(dimension::Int)\n\nEnsures that the first `dimension` elements is a sorted copy of the next\n`dimension` elements.\n\n## Example\n\n    [a, b, c, d] in Sort(2)\n    # Enforces that:\n    # - the first part is sorted: a <= b\n    # - the first part corresponds to the second one:\n    #     - either a = c and b = d\n    #     - or a = d and b = c\n\"\"\"\nstruct Sort <: MOI.AbstractVectorSet\n    dimension::Int\nend\n\nMOI.dimension(set::Sort) = 2 * set.dimension\n\n\"\"\"\n    SortPermutation(dimension::Int)\n\nEnsures that the first `dimension` elements is a sorted copy of the next\n`dimension` elements.\n\nThe last `dimension` elements give a permutation to get from the original array\nto its sorted version.\n\n## Example\n\n    [a, b, c, d, i, j] in SortPermutation(2)\n    # Enforces that:\n    # - the first part is sorted: a <= b\n    # - the first part corresponds to the second one:\n    #     - either a = c and b = d: in this case, i = 1 and j = 2\n    #     - or a = d and b = c: in this case, i = 2 and j = 1\n\"\"\"\nstruct SortPermutation <: MOI.AbstractVectorSet\n    dimension::Int\nend\n\nMOI.dimension(set::SortPermutation) = 3 * set.dimension\n\n\"\"\"\n    MinimumAmong(dimension::Int)\n\nEnsures that the first element is the minimum value among the next \n`dimension` elements.\n\n## Example\n\n    [a, b, c] in MinimumAmong(2)\n    # Enforces that a == min(b, c)\n\"\"\"\nstruct MinimumAmong <: MOI.AbstractVectorSet\n    dimension::Int\nend\n\nMOI.dimension(set::MinimumAmong) = 1 + set.dimension\n\n\"\"\"\n    ArgumentMinimumAmong(dimension::Int)\n\nEnsures that the first element is the index of the minimum value among the \nnext `dimension` elements.\n\n## Example\n\n    [a, b, c] in ArgumentMinimumAmong(2)\n    # Enforces that a == argmin(b, c)\n    # I.e., if b < c, a = 1, if b > c, a = 2\n\"\"\"\nstruct ArgumentMinimumAmong <: MOI.AbstractVectorSet\n    dimension::Int\nend\n\nMOI.dimension(set::ArgumentMinimumAmong) = 1 + set.dimension\n\n\"\"\"\n    MaximumAmong(dimension::Int)\n\nEnsures that the first element is the maximum value among the next \n`dimension` elements.\n\n## Example\n\n    [a, b, c] in MaximumAmong(2)\n    # Enforces that a == max(b, c)\n\"\"\"\nstruct MaximumAmong <: MOI.AbstractVectorSet\n    dimension::Int\nend\n\nMOI.dimension(set::MaximumAmong) = 1 + set.dimension\n\n\"\"\"\n    ArgumentMaximumAmong(dimension::Int)\n\nEnsures that the first element is the index of the maximum value among the \nnext `dimension` elements.\n\n## Example\n\n    [a, b, c] in ArgumentMaximumAmong(2)\n    # Enforces that a == argmax(b, c)\n    # I.e., if b > c, a = 1, if b < c, a = 2\n\"\"\"\nstruct ArgumentMaximumAmong <: MOI.AbstractVectorSet\n    dimension::Int\nend\n\nMOI.dimension(set::ArgumentMaximumAmong) = 1 + set.dimension\n\n\"\"\"\n    Increasing(dimension::Int)\n\nEnsures that the elements of the vector are in increasing order (<= operation).\n\n## Example\n\n    [a, b, c] in Increasing(3)\n    # Enforces that a <= b <= c\n\"\"\"\nstruct Increasing <: MOI.AbstractVectorSet\n    dimension::Int\nend\n\n\"\"\"\n    Decreasing(dimension::Int)\n\nEnsures that the elements of the vector are in decreasing order (>= operation).\n\n## Example\n\n    [a, b, c] in Decreasing(3)\n    # Enforces that a >= b >= c\n\"\"\"\nstruct Decreasing <: MOI.AbstractVectorSet\n    dimension::Int\nend\n\n# isbits types, nothing to copy\nfunction copy(\n    set::Union{\n        LexicographicallyLessThan,\n        LexicographicallyGreaterThan,\n        DoublyLexicographicallyLessThan,\n        DoublyLexicographicallyGreaterThan,\n        Sort,\n        SortPermutation,\n        MinimumAmong,\n        ArgumentMinimumAmong,\n        MaximumAmong,\n        ArgumentMaximumAmong,\n        Increasing,\n        Decreasing,\n    },\n)\n    return set\nend\n", "meta": {"hexsha": "44fba9eae08b66a1910cb7180b57e7ad0ad0bd7c", "size": 6632, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sets_sorting.jl", "max_stars_repo_name": "dourouc05/ConstraintProgrammingExtensions.jl", "max_stars_repo_head_hexsha": "3e21c47050e3fc72630c3cbd8546db3e86b1cfcb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-02-13T23:30:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T09:07:26.000Z", "max_issues_repo_path": "src/sets_sorting.jl", "max_issues_repo_name": "JuliaConstraints/ConstraintProgrammingExtensions.jl", "max_issues_repo_head_hexsha": "24b9288a85df0bc994a63658e1db4bebcbc34d77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-02-16T04:43:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-17T00:14:37.000Z", "max_forks_repo_path": "src/sets_sorting.jl", "max_forks_repo_name": "JuliaConstraints/ConstraintProgrammingExtensions.jl", "max_forks_repo_head_hexsha": "24b9288a85df0bc994a63658e1db4bebcbc34d77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-15T17:30:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-15T17:30:16.000Z", "avg_line_length": 25.8054474708, "max_line_length": 198, "alphanum_fraction": 0.7000904704, "num_tokens": 1793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913343093499, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7852821244584728}}
{"text": "function toCartesian(lon, lat; r = 1, cxyz = (0,0,0) )\n    lat, lon = lat*π/180, lon*π/180\n    cxyz[1] + r * cos(lat) * cos(lon), cxyz[2] + r * cos(lat) * sin(lon), cxyz[3] + r *sin(lat)\nend\nfunction lonlat3D(lon, lat, data; cxyz = (0,0,0))\n    xyzw = zeros(size(data)..., 3)\n    for (i,lon) in enumerate(lon), (j,lat) in enumerate(lat)\n        x, y, z = toCartesian(lon, lat; cxyz = cxyz)\n        xyzw[i,j,1] = x\n        xyzw[i,j,2] = y\n        xyzw[i,j,3] = z\n    end\n    xyzw[:,:,1], xyzw[:,:,2], xyzw[:,:,3]\nend\n\nfunction SphereBall(; r = 0.995, cxyz = (0,0,0))\n    Θ = LinRange(0, 2π, 500) # 50\n    Φ = LinRange(0, π, 500)\n    x0 = [cxyz[1] + r * cos(θ) * sin(ϕ)      for θ in Θ, ϕ in Φ]\n    y0 = [cxyz[2] + r * sin(θ) * sin(ϕ)      for θ in Θ, ϕ in Φ]\n    z0 = [cxyz[3] + r * cos(ϕ) for θ in Θ, ϕ in Φ]\n    x0, y0, z0\nend\n", "meta": {"hexsha": "15609845e9e6f8b7b8bf94c3ea0c9e6fd060b044", "size": 828, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vizSpheres.jl", "max_stars_repo_name": "lazarusA/GeoCubesPlots.jl", "max_stars_repo_head_hexsha": "39d5813af2ed2400b649ddf1c3f2399a2070edeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-08T08:00:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T00:09:31.000Z", "max_issues_repo_path": "src/vizSpheres.jl", "max_issues_repo_name": "lazarusA/GeoCubesPlots.jl", "max_issues_repo_head_hexsha": "39d5813af2ed2400b649ddf1c3f2399a2070edeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vizSpheres.jl", "max_forks_repo_name": "lazarusA/GeoCubesPlots.jl", "max_forks_repo_head_hexsha": "39d5813af2ed2400b649ddf1c3f2399a2070edeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5, "max_line_length": 95, "alphanum_fraction": 0.5012077295, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305339244012, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7852568324770717}}
{"text": "#Load the required Packages\nusing JLD2, Random, LinearAlgebra, Statistics, CSV, DataFrames, FreqTables, Distributions\n#Set the seed\nRandom.seed!(1234)\n#(a)Create the following four matrices of random numbers \n#(i) A 10 by 7 matrix drawn randomly from a uniform distribution U[-5,10]\nA = rand(Uniform(-5,10),10,7)\n#(ii) A 10 by 7 matrix drawn randomly from a normal distribution N[-2,15]\nB = rand(Normal(-2,15),10,7)", "meta": {"hexsha": "a085e96bd86522bea8d3d77969850fd79150f5d0", "size": 415, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS1-julia-intro/problemset1.jl", "max_stars_repo_name": "mrJohnMburu/fall-2020", "max_stars_repo_head_hexsha": "69e27b32d3c44e3f213f80a0bd120e58dec6bff3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSets/PS1-julia-intro/problemset1.jl", "max_issues_repo_name": "mrJohnMburu/fall-2020", "max_issues_repo_head_hexsha": "69e27b32d3c44e3f213f80a0bd120e58dec6bff3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS1-julia-intro/problemset1.jl", "max_forks_repo_name": "mrJohnMburu/fall-2020", "max_forks_repo_head_hexsha": "69e27b32d3c44e3f213f80a0bd120e58dec6bff3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.1111111111, "max_line_length": 89, "alphanum_fraction": 0.7469879518, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96323053709097, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.785256824248518}}
{"text": "function CroutLU(A::Array)\r\n\r\n  #A = the matrix of coefficients 'A' must be squared\r\n\r\n    m,n =size(A)\r\n\r\n    if m != n\r\n        error(\"Matrix must be squared\")\r\n    end\r\n\r\n    # System of equations\r\n    L=zeros(m,m)\r\n    U=Matrix{Float64}(I,m,m)\r\n\r\n    for i=1:m\r\n        L[i,1]=A[i,1]\r\n    end\r\n\r\n    for j=2:m\r\n       U[1,j]=A[1,j]/L[1,1]\r\n    end\r\n\r\n    for j=2:m-1\r\n       for i=j:m\r\n           L[i,j]=A[i,j]- (L[i,1:j-1]'*U[1:j-1,j])\r\n        end\r\n\r\n        for k=j:m\r\n           U[j,k]=(A[j,k]-(L[j,1:j-1]'*U[1:j-1,k]))/L[j,j]\r\n        end\r\n    end\r\n\r\n\r\n       L[m,m]=A[m,m]-(L[m,1:m-1]'*U[1:m-1,m])\r\n\r\n    return L, U\r\nend\r\n", "meta": {"hexsha": "9a183071efd8d906ab324c0f5f646779d2ffc4d7", "size": 633, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CroutLU.jl", "max_stars_repo_name": "scuervo91/LinearSolvers.jl", "max_stars_repo_head_hexsha": "471102b870dde6cb4c3b80c976381db31198faaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CroutLU.jl", "max_issues_repo_name": "scuervo91/LinearSolvers.jl", "max_issues_repo_head_hexsha": "471102b870dde6cb4c3b80c976381db31198faaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CroutLU.jl", "max_forks_repo_name": "scuervo91/LinearSolvers.jl", "max_forks_repo_head_hexsha": "471102b870dde6cb4c3b80c976381db31198faaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.6578947368, "max_line_length": 59, "alphanum_fraction": 0.4139020537, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305297023094, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7852568225490593}}
{"text": "using LinearAlgebra, StatsBase\n\n# Transition probability matrix\nP = [0.5 0.4 0.1;\n     0.3 0.2 0.5;\n     0.5 0.3 0.2]\n\n# First way\nP^100\npiProb1 = (P^100)[1,:]\n\n# Second way\nA = vcat((P' - Matrix{Float64}(I, 3, 3))[1:2,:],ones(3)')\nb = [0 0 1]'\npiProb2 = A\\b\n\n# Third way\neigVecs = eigvecs(copy(P'))\nhighestVec = eigVecs[:,findmax(abs.(eigvals(P)))[2]]\npiProb3 = Array{Float64}(highestVec)/norm(highestVec,1);\n\n# Fourth way\nnumInState = zeros(3)\nstate = 1\nN = 10^6\nfor t in 1:N\n    numInState[state] += 1\n    global state = sample(1:3,weights(P[state,:]))\nend\npiProb4 = numInState/N\n\n[piProb1 piProb2 piProb3 piProb4]\n", "meta": {"hexsha": "123084b311a7541d6ffb3ef4f11cf69b7d52502c", "size": 618, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/stats/multiWayMarkovChainStationary.jl", "max_stars_repo_name": "mikiec84/SemanticModels.jl", "max_stars_repo_head_hexsha": "f81baf0789cc547375f300429d0fd49c866d5339", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-21T15:52:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-21T15:52:41.000Z", "max_issues_repo_path": "examples/stats/multiWayMarkovChainStationary.jl", "max_issues_repo_name": "mikiec84/SemanticModels.jl", "max_issues_repo_head_hexsha": "f81baf0789cc547375f300429d0fd49c866d5339", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/stats/multiWayMarkovChainStationary.jl", "max_forks_repo_name": "mikiec84/SemanticModels.jl", "max_forks_repo_head_hexsha": "f81baf0789cc547375f300429d0fd49c866d5339", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7272727273, "max_line_length": 57, "alphanum_fraction": 0.6391585761, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305339244013, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7852568195050195}}
{"text": "using DifferentialEquations\r\nusing ModelingToolkit\r\nusing DataDrivenDiffEq\r\nusing LinearAlgebra, DiffEqSensitivity, Optim\r\nusing DiffEqFlux, Flux\r\nusing Plots\r\ngr()\r\n\r\n# function triNN!(du,u,p,t,dens,cons)\r\n#     # unpack rates and constants\r\n#     nᵣ,nₓ,n₃ = u\r\n#     k₁,k₋₁,k₂,k₋₂ = cons\r\n#     mᵣ,mₗ,mₓ,A = dens\r\n#     z = L(u,p)\r\n#     # model\r\n#     du[1] = dnᵣ = A*k₁*mᵣ*mₗ - k₋₁*nᵣ + z[1]\r\n#     du[2] = dnₓ = A*k₂*mₓ*mₗ - k₋₂*nₓ + z[2]\r\n#     du[3] = dn₃ = z[1] + z[2]\r\n#\r\n# end\r\nfunction bimolecular!(du,u,p,t,dens,cons)\r\n    # unpack rates and constants\r\n    nᵣ = u[1]\r\n    k₁,k₋₁  = p\r\n    mᵣ,mₗ,A = dens\r\n    # model\r\n    du[1] = dnᵣ = A*k₁*mᵣ*mₗ - k₋₁*nᵣ\r\n\r\nend\r\n\r\ndens = [100.,10.,1.]\r\ncons = Float64[]\r\nf = (du,u,p,t) -> bimolecular!(du,u,p,t,dens,cons)\r\n# Define the experimental parameter\r\ntspan = (0.0f0,10.0f0)\r\nu0 = Float32[0.]\r\np_ = Float32[1e-4, 0.5]\r\nprob = ODEProblem(f, u0,tspan, p_)\r\nsolution = solve(prob, Tsit5(), saveat = 0.1)\r\n\r\nscatter(solution, alpha = 0.25)\r\nplot!(solution, alpha = 0.5)\r\n\r\n# Ideal data\r\nX = Array(solution)\r\n# Add noise to the data\r\nprintln(\"Generate noisy data\")\r\nXₙ = X + Float32(1e-2)*randn(eltype(X), size(X))\r\n\r\n# function dudt_(u, p,t)\r\n#     x = u\r\n#     z = L(u,p)\r\n#     [p_[1]*x + z[1],\r\n#     -p_[4]*y + z[2]]\r\n# end\r\nfunction biNN!(du,u,p,t,dens,cons)\r\n    # unpack rates and constants\r\n    nᵣ = u[1]\r\n    k₁,k₋₁  = p\r\n    mᵣ,mₗ,A = dens\r\n    z = L(u,p)\r\n    # model\r\n    du[1] = dnᵣ = z[1]\r\n\r\nend\r\n\r\nL = FastChain(FastDense(1, 32, tanh),FastDense(32, 32, tanh), FastDense(32, 1))\r\n#L = FastChain(FastDense(3, 20, tanh),FastDense(20, 20, tanh), FastDense(20, 2))\r\np = initial_params(L)\r\n\r\n#\r\nfNN = (du,u,p,t) -> biNN!(du,u, p,t,dens,cons)\r\nprob_nn = ODEProblem(fNN,u0, tspan, p)\r\nsol_nn = solve(prob_nn, Tsit5(), saveat =  solution.t)\r\n\r\nplot(solution)\r\nplot!(sol_nn)\r\n# summ = reduce(vcat,sum(sol_nn,dims=1))\r\n# h = plot!(sol_nn.t,summ,linecolor=:black)\r\n\r\nfunction predict(θ)\r\n\r\n    tmp_prob = remake(prob_nn,u0=u0,p=θ)\r\n    tmp_sol =  solve(tmp_prob, VCABM(), saveat = solution.t,\r\n                  abstol=1e-5, reltol=1e-5)\r\n                  # backsolve=true)\r\n    # Σ_sol = sum(Array(tmp_sol),dims=1) # Note: this returns a row vector!\r\n    Array(tmp_sol)\r\nend\r\n\r\nfunction loss(θ)\r\n    pred = predict(θ)\r\n    sum(abs2, Xₙ .- pred), pred\r\nend\r\n\r\n# Test\r\n@time loss(p)\r\n\r\nconst losses = []\r\n\r\ncallback(θ,l,pred) = begin\r\n    push!(losses, l)\r\n    @show l\r\n    if length(losses)%50==0\r\n        println(\"Current loss after $(length(losses)) iterations: $(losses[end])\")\r\n    end\r\n    h = plot(solution.t, pred')\r\n    scatter!(h, solution.t, Xₙ')\r\n    display(h)\r\n    false\r\nend\r\n\r\np = initial_params(L)\r\n# First train with ADAM for better convergence\r\n@time res1 = DiffEqFlux.sciml_train(loss, p, ADAM(0.01), cb=callback, maxiters = 40)\r\n\r\n# Train with BFGS\r\nres2 = DiffEqFlux.sciml_train(loss, res1.minimizer, BFGS(),\r\n                                cb=callback, maxiters = 100)\r\n\r\n# @time res1 = DiffEqFlux.sciml_train(loss, res2.minimizer, ADAM(0.001), cb=callback, maxiters = 20)\r\n\r\nprintln(\"Final training loss after $(length(losses)) iterations: $(losses[end])\")\r\n\r\n# Plot the losses\r\nimgloss= plot(losses, yaxis = :log, xaxis = :log, xlabel = \"Iterations\", ylabel = \"Loss\",fmt = :svg)\r\nsavefig(imgloss,\"training_loss\")\r\n# Plot the data and the approximation\r\nNNsolution = predict(res2.minimizer)\r\n# Trained on noisy data vs real solution\r\nplot(solution.t, NNsolution',linewidth=3,xlabel = \"t (s)\", ylabel = \"n\",fmt = :svg)\r\nscatter!(solution.t, Xₙ')\r\nsavefig(\"fit\")\r\n\r\n\r\nL̂ = L(Xₙ,res2.minimizer)\r\n## Sparse Identification\r\n#\r\n# # Create a Basis\r\n# @variables u[1:2]\r\n# # Lots of polynomials\r\n# polys = Operation[1]\r\n#\r\n# for i ∈ 1:2\r\n#     push!(polys, u[1]^i)\r\n#     push!(polys, u[2]^i)\r\n#     for j ∈ i:2\r\n#         if i != j\r\n#             push!(polys, (u[1]^i)*(u[2]^j))\r\n#             push!(polys, u[2]^i*u[1]^i)\r\n#         end\r\n#     end\r\n# end\r\n#\r\n# # And some other stuff\r\n# h = [cos.(u)...; sin.(u)...; polys...]\r\n# h = [ polys...]\r\n# basis = Basis(h, u)\r\n#\r\n# # Create an optimizer for the SINDy problem\r\n# opt = SR3()\r\n# # Create the thresholds which should be used in the search process\r\n# λ = exp10.(-7:0.1:3)\r\n# # Target function to choose the results from; x = L0 of coefficients and L2-Error of the model\r\n# g(x) = x[1] < 1 ? Inf : norm(x, 2)\r\n# # Test on original data and without further knowledge\r\n# # println(\"SINDy on full ideal, unavailable data\")\r\n# # Ψ = SINDy(Xₙ[:, :], DX[:, :], basis, λ, opt, g = g, maxiter = 10000) # Fail\r\n# # println(Ψ)\r\n# # print_equations(Ψ)\r\n# #\r\n# # # Test on ideal derivative data for unknown function ( not available )\r\n# # println(\"SINDy on partial ideal, unavailable data\")\r\n# # Ψ = SINDy(Xₙ[:, 1:end], L̄[:, 1:end], basis, λ,opt, g = g, maxiter = 10000) # Succeed\r\n# # println(Ψ)\r\n# # print_equations(Ψ)\r\n#\r\n# # Test on uode derivative data\r\n# println(\"SINDy on learned, partial, available data\")\r\n# Ψ = SINDy(Xₙ[:, 2:end], L̂[:, 2:end], basis, λ,  opt, g = g, maxiter = 100000, normalize = true, denoise = true) # Succeed\r\n# println(Ψ)\r\n# print_equations(Ψ)\r\n#\r\n# # Extract the parameter\r\n# p̂ = parameters(Ψ)\r\n# println(\"First parameter guess : $(p̂)\")\r\n\r\n@variables u[1:1]\r\nh = Operation[u; u.^2; 1]\r\nbasis = Basis(h, u)\r\n\r\n# Create the thresholds which should be used in the search process\r\nλ = exp10.(-7:0.1:3)\r\n# Target function to choose the results from; x = L0 of coefficients and L2-Error of the model\r\ng(x) = x[1] < 1 ? Inf : norm(x, 2)\r\n\r\nopt = SR3(3e-1, 1.0)\r\n# Ψ = SInDy(X[:, 1:1000], DX[:, 1:1000], basis, maxiter = 10000, opt = opt, normalize = true)\r\nΨ = SINDy(Xₙ[:, 2:end], L̂[:, 2:end], basis, λ,  opt, g = g, maxiter = 10000, normalize = true) # Succeed\r\n# Ψ = SINDy(Xₙ[:, 2:end], L̂[:, 2:end], basis, maxiter = 10000, opt = opt, normalize = true,denoise = true)\r\nprintln(Ψ)\r\nprint_equations(Ψ)\r\n\r\nsys = ODESystem(Ψ)\r\np = parameters(Ψ)\r\n\r\ndudt = ODEFunction(sys)\r\n\r\nestimator = ODEProblem(dudt, u0, tspan, p)\r\nestimation = solve(estimator, Tsit5(), saveat = solution.t)\r\n\r\nplot!(estimation,linecolor=:red,linewidth=3)\r\nsavefig(\"sindy_raw_estim\")\r\n\r\nusing DiffEqParamEstim\r\nusing Optim\r\n# cost_function = build_loss_objective(estimator,t,Xₙ,Tsit5(),maxiters=10000)\r\n\r\ncost_function = build_loss_objective(estimator,Tsit5(),L2Loss(solution.t,Xₙ),\r\n                                     maxiters=10000)#,verbose=false)\r\nresult = optimize(cost_function, p, BFGS())\r\ntmp_estimator = remake(estimator, p=result.minimizer)\r\nbetter_estimation = solve(tmp_estimator, Tsit5(), saveat = solution.t)\r\n\r\nplot!(better_estimation,linecolor=:black,linestyle=:dash,linewidth=4)\r\nsavefig(\"sindy_better_estim\")\r\n#\r\n# # The parameters are a bit off, but the equations are recovered\r\n# # Start another SINDy run to get closer to the ground truth\r\n# # Create function\r\n# unknown_sys = ODESystem(Ψ)\r\n# unknown_eq = ODEFunction(unknown_sys)\r\n#\r\n# # Just the equations\r\n# b = Basis((u, p, t)->unknown_eq(u, [1.; 1.], t), u)\r\n#\r\n# # Retune for better parameters -> we could also use DiffEqFlux or other parameter estimation tools here.\r\n# Ψf = SINDy(Xₙ[:, 2:end], L̂[:, 2:end], b, STRRidge(0.01), maxiter = 100, convergence_error = 1e-18) # Succeed\r\n# println(Ψf)\r\n# p̂ = parameters(Ψf)\r\n# println(\"Second parameter guess : $(p̂)\")\r\n#\r\n# # Create function\r\n# recovered_sys = ODESystem(Ψf)\r\n# recovered_eq = ODEFunction(recovered_sys)\r\n# estimator = ODEProblem(dudt, u0, tspan, p)\r\n# estimation = solve(estimator, Tsit5(), saveat = solution.t)\r\n#\r\n# plot!(estimation)\r\n#\r\n#\r\n#\r\n", "meta": {"hexsha": "ee74cd5f9b8a7d1bd8823596dc5cb18db97aec7a", "size": 7502, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "neuralODE modeling/bimolecular_nODE.jl", "max_stars_repo_name": "vaglino/kinetic_modeling", "max_stars_repo_head_hexsha": "2a15f74df5844eb21d5bf47bc9014b6bf74f84e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "neuralODE modeling/bimolecular_nODE.jl", "max_issues_repo_name": "vaglino/kinetic_modeling", "max_issues_repo_head_hexsha": "2a15f74df5844eb21d5bf47bc9014b6bf74f84e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neuralODE modeling/bimolecular_nODE.jl", "max_forks_repo_name": "vaglino/kinetic_modeling", "max_forks_repo_head_hexsha": "2a15f74df5844eb21d5bf47bc9014b6bf74f84e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.652173913, "max_line_length": 125, "alphanum_fraction": 0.6143695015, "num_tokens": 2614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.870597273444551, "lm_q1q2_score": 0.7852096841450436}}
{"text": "const helix = let res_init=zeros(3), jac_init=zeros(3,3), x_init=[-1.0, 0.0, 0.0]\n\n    function res(x, r)\n        theta = atan(x[2], x[1]) / 2pi\n\n        if x[1] <= 0.0 && x[2] <= 0.0\n            theta = theta + 1.0\n        end\n\n        r[1] = 10.0 * (x[3] - 10.0 * theta )\n        r[2] = 10.0 * (sqrt(x[1]^2 + x[2]^2) - 1.0)\n        r[3] = x[3]\n        return r\n    end\n\n    function jac(x, jac)\n        t = x[1]^2 + x[2]^2\n        ti = 100.0 / (2pi * t )\n        jac[1, 1] = ti * x[2]\n        t = 10.0 / sqrt(t)\n        jac[2, 1] = x[1] * t\n        jac[3, 1] = 0.0\n        jac[1, 2] = -ti * x[1]\n        jac[2, 2] = x[2] * t\n        jac[3, 2] = 0.0\n        jac[1, 3] = 10.0\n        jac[2, 3] = 0.0\n        jac[3, 3] = 1.0\n        return jac\n    end\n\n    f(;scale=1, verbose=false, print_steps=false) = testone(\"helix\", res, jac,\n                                                            res_init, jac_init, x_init;\n                                                            scale=scale, verbose=verbose,\n                                                            print_steps=print_steps)\nend\n", "meta": {"hexsha": "85ea4597c12d9696c3d4955a0a5fe825976ae6e7", "size": 1098, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/optests/helix.jl", "max_stars_repo_name": "macd/NL2sol.jl", "max_stars_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-01-19T21:59:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T00:42:56.000Z", "max_issues_repo_path": "test/optests/helix.jl", "max_issues_repo_name": "macd/NL2sol.jl", "max_issues_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/optests/helix.jl", "max_forks_repo_name": "macd/NL2sol.jl", "max_forks_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6756756757, "max_line_length": 89, "alphanum_fraction": 0.3652094718, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7852091716515355}}
{"text": "#######################\n# The Bernstein basis\n#######################\n\nusing BasisFunctions: UnitInterval, PolynomialBasis\nusing BasisFunctions: hasderivative, hasantiderivative, ordering, support\n\nconst BernsteinInterval = UnitInterval\nconst BernsteinIndex = NativeIndex{:bernstein}\n\nget_bernstein_nodes(T,n) = collect(LinRange{T}(0.0, 1.0, n))\n\nstruct Bernstein{T} <: PolynomialBasis{T}\n    n :: Int\n    nodes :: ScatteredGrid{T}\n\n    function Bernstein(nodes::ScatteredGrid{T}) where {T}\n        new{T}(length(nodes.points), nodes)\n    end\n    function Bernstein(ξ::Vector{T}) where {T}\n        Bernstein(ScatteredGrid(ξ, BernsteinInterval{T}()))\n    end\nend\n\nBernstein(n::Int) = Bernstein(get_bernstein_nodes(Float64,n))\nBernstein{T}(n::Int) where {T} = Bernstein(get_bernstein_nodes(T,n))\n\n# Convenience constructor: map the Bernstein basis to the interval [a,b]\nBernstein(ξ, a::Number, b::Number) = rescale(Bernstein(ξ), a, b)\n\n\nnodes(b::Bernstein)  = b.nodes.points\nnnodes(b::Bernstein) = b.n\ndegree(b::Bernstein) = b.n-1\n\nBasisFunctions.native_index(b::Bernstein, idx) = BernsteinIndex(idx)\nBasisFunctions.linear_index(b::Bernstein, idx) = BernsteinIndex(idx)\nBasisFunctions.ordering(b::Bernstein) = Base.OneTo(nnodes(b))\nBasisFunctions.support(b::Bernstein{T}) where {T} = BernsteinInterval{T}()\n\nBasisFunctions.interpolation_grid(b::Bernstein{T}) where {T} = ScatteredGrid(get_bernstein_nodes(T,length(b)), BernsteinInterval{T}())\n\nBasisFunctions.similar(::Bernstein, ::Type{T}, n::Int) where {T} = Bernstein{T}(n)\nBasisFunctions.similar(::Bernstein, ::Type{T}, ξ::Vector{T}) where {T} = Bernstein(ξ)\n\nBase.size(b::Bernstein) = (b.n,)\n\n\nfunction _bernstein(b::Bernstein{T}, i::BernsteinIndex, n::BernsteinIndex, x::T) where {T}\n    if i < 0 || i > n\n        return zero(T)\n    else\n        if n == 0\n            return one(T)\n        else\n            return _bernstein(b, i, n-1, x) * (1-x) + _bernstein(b, i-1, n-1, x) * x\n        end\n    end\nend\n\n_bernstein(b::Bernstein, i, n, x) = _bernstein(b, native_index(b,i), native_index(b,n), x)\n\n\nfunction BasisFunctions.unsafe_eval_element(b::Bernstein, i, x)\n    _bernstein(b, i-1, nnodes(b)-1, x)\nend\n\n\nfunction BasisFunctions.unsafe_eval_element_derivative(b::Bernstein, i, x)\n    (nnodes(b)-1) * ( _bernstein(b, i-2, nnodes(b)-2, x) - _bernstein(b, i-1, nnodes(b)-2, x) )\nend\n", "meta": {"hexsha": "b12394ddda21721de3cdfa46aa3f3279292afe10", "size": 2336, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bases/poly/bernstein.jl", "max_stars_repo_name": "ToBlick/MoreBasisFunctions.jl", "max_stars_repo_head_hexsha": "fd3ed5c3a58077c33cf1799cf86479abdd40f7b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bases/poly/bernstein.jl", "max_issues_repo_name": "ToBlick/MoreBasisFunctions.jl", "max_issues_repo_head_hexsha": "fd3ed5c3a58077c33cf1799cf86479abdd40f7b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bases/poly/bernstein.jl", "max_forks_repo_name": "ToBlick/MoreBasisFunctions.jl", "max_forks_repo_head_hexsha": "fd3ed5c3a58077c33cf1799cf86479abdd40f7b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4444444444, "max_line_length": 134, "alphanum_fraction": 0.6772260274, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7852091704225042}}
{"text": "function f(x::Vector)\n    (x[1] - 5.0)^4\nend\n\nfunction g!(x::Vector, storage::Vector)\n    storage[1] = 4.0 * (x[1] - 5.0)^3\nend\n\nfunction h!(x::Vector, storage::Matrix)\n    storage[1, 1] = 12.0 * (x[1] - 5.0)^2\nend\n\nd = TwiceDifferentiableFunction(f, g!, h!)\n\nresults = Optim.newton(d, [0.0])\n@assert length(results.trace.states) == 0\n@assert results.converged\n@assert norm(results.minimum - [5.0]) < 0.01\n\neta = 0.9\n\nfunction f(x::Vector)\n  (1.0 / 2.0) * (x[1]^2 + eta * x[2]^2)\nend\n\nfunction g!(x::Vector, storage::Vector)\n  storage[1] = x[1]\n  storage[2] = eta * x[2]\nend\n\nfunction h!(x::Vector, storage::Matrix)\n  storage[1, 1] = 1.0\n  storage[1, 2] = 0.0\n  storage[2, 1] = 0.0\n  storage[2, 2] = eta\nend\n\nd = TwiceDifferentiableFunction(f, g!, h!)\nresults = Optim.newton(d, [127.0, 921.0])\n@assert length(results.trace.states) == 0\n@assert results.converged\n@assert norm(results.minimum - [0.0, 0.0]) < 0.01\n", "meta": {"hexsha": "17c3d543023edbd45f3019fc5197334ebf381f17", "size": 912, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/newton.jl", "max_stars_repo_name": "aviks/Optim.jl", "max_stars_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-22T09:32:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-22T09:32:32.000Z", "max_issues_repo_path": "test/newton.jl", "max_issues_repo_name": "aviks/Optim.jl", "max_issues_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/newton.jl", "max_forks_repo_name": "aviks/Optim.jl", "max_forks_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2093023256, "max_line_length": 49, "alphanum_fraction": 0.6195175439, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7852091700241853}}
{"text": "\"\"\"\n    cartesian2jacobi!(r, r_j, m, m_sum) \n\nTransforms cartesian coordinates into jacobi coordinates.\n\n# Args\n\n* `r`: NxD matrix where N is the number of bodies and D is the number of dimensions, each row contains the positions of the bodies in cartesian coordinates.\n* `r_j`: NxD matrix in which the results will be saved.\n* `m`: array of N elements, where element number i contains the mass of i-th body.\n* `m_sum`: array of N elements, where element with index i contains the mass of the bodies from 1 to i\n```math\nm_{sum_{i}} = \\\\sum_{j = 1}^{i} m_{j} \\\\\\\\\n```\n\"\"\"\nfunction cartesian2jacobi!(r, r_j, m, m_sum) \n    R = m[1]*r[1,:]\n    for i in 2:size(r)[1]\n        r_j[i,:] = r[i,:] - (R/m_sum[i-1])\n        R = R*(1.0+m[i]/m_sum[i-1]) + m[i]*r_j[i,:] \n    end\n    r_j[1,:] = R/m_sum[size(r)[1]]\nend\n\n\n\"\"\"\n    jacobi2cartesian!(r, r_j, m, m_sum) \n\nTransforms jacobi coordinates into cartesian coordinates.\n\n# Args\n\n* `r`: NxD matrix in which the results will be saved.\n* `r_j`: NxD matrix where N is the number of bodies and D is the number of dimensions, each row contains the positions of the bodies in jacobi coordinates.\n* `m`: array of N elements, where element number i contains the mass of i-th body.\n* `m_sum`: array of N elements, where element with index i contains the mass of the bodies from 1 to i\n```math\nm_{sum_{i}} = \\\\sum_{j = 1}^{i} m_{j} \\\\\\\\\n```\n\"\"\"\nfunction jacobi2cartesian!(r, r_j, m, m_sum) \n    R = r_j[1,:]*m_sum[size(r)[1]]\n    for i in size(r)[1]:-1:2\n        R = (R - m[i]*r_j[i,:])/m_sum[i]\n        r[i,:] = r_j[i,:] + R\n        R *= m_sum[i-1]\n    end\n    r[1,:] = R/m[1]\nend", "meta": {"hexsha": "0d782a0a1025cad3cf9c56a6a9e95fb4c2d6a4f7", "size": 1612, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/coordinateTransform.jl", "max_stars_repo_name": "salanueva/KeplerFlow", "max_stars_repo_head_hexsha": "4e370d6fd76100974d31ad548629f52217b4e96f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/coordinateTransform.jl", "max_issues_repo_name": "salanueva/KeplerFlow", "max_issues_repo_head_hexsha": "4e370d6fd76100974d31ad548629f52217b4e96f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/coordinateTransform.jl", "max_forks_repo_name": "salanueva/KeplerFlow", "max_forks_repo_head_hexsha": "4e370d6fd76100974d31ad548629f52217b4e96f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8979591837, "max_line_length": 156, "alphanum_fraction": 0.6265508685, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806521, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7852091639131026}}
{"text": "\"\"\"\n   shi(x) \n   \n   hyperbolic sine integral function \n   \n   shi(x) = ₀∫ˣ (sinh(t) / t) δt \n\"\"\" shi\n\n\"\"\"\n    chi(x)\n    \n    hyperbolic cosine integral\n    \nchi(x) = γ + ln(x) + ₀∫ˣ ((cosh(t) - 1) / t) δt \nwhere γ == 0.5772_1566_4901_5328_6060_6512_0901-\n           (the Euler-Mascheroni constant)\n\"\"\" chi\n\n\"\"\"\n    li(x)\n   \n    logarithmic integral\n    \nli(x) =  ᵤ∫ˣ (δt / ln(t))\n\n         where u = 1.4513_6923_4883_3810_5028+\n                   (Soldner's constant)\n\"\"\" li\n\n\"\"\"\n    si(x)\n    \n    sine integral\n    \nsi(x) = ₀∫ˣ (sin(t) / t) δt\n\"\"\" si\n\n\n", "meta": {"hexsha": "29bd9c193f08a49c5f44bb924a2d67abfad47317", "size": 559, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/support/helptext.jl", "max_stars_repo_name": "AdrianDAlessandro/ArbNumerics.jl", "max_stars_repo_head_hexsha": "637f40689b0cfb14c6d6980da4ac6cb02c40ec66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2018-07-18T17:45:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T08:18:57.000Z", "max_issues_repo_path": "src/support/helptext.jl", "max_issues_repo_name": "AdrianDAlessandro/ArbNumerics.jl", "max_issues_repo_head_hexsha": "637f40689b0cfb14c6d6980da4ac6cb02c40ec66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 43, "max_issues_repo_issues_event_min_datetime": "2018-07-29T06:12:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:47:58.000Z", "max_forks_repo_path": "src/support/helptext.jl", "max_forks_repo_name": "AdrianDAlessandro/ArbNumerics.jl", "max_forks_repo_head_hexsha": "637f40689b0cfb14c6d6980da4ac6cb02c40ec66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2018-08-07T14:06:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T08:19:27.000Z", "avg_line_length": 14.3333333333, "max_line_length": 48, "alphanum_fraction": 0.4973166369, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611586300241, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7851667648205832}}
{"text": "# Descriptive Statistics\n\n\n#############################\n#\n#   Location\n#\n#############################\n\n# Geometric mean\nfunction geomean(a::RealArray)\n    s = 0.0\n    n = length(a)\n    for i = 1 : n\n        @inbounds s += log(a[i])\n    end\n    return exp(s / n)\nend\n\n# Harmonic mean\nfunction harmmean(a::RealArray)\n    s = 0.0\n    n = length(a)\n    for i in 1 : n\n        @inbounds s += inv(a[i])\n    end\n    return n / s\nend\n\n# Trimmed mean\nfunction trimmean(x::RealArray, p::Real)\n    n = length(x)\n    n > 0 || error(\"x can not be empty.\")\n    0 <= p < 1 || error(\"p must be non-negative and less than 1.\")\n    rn = min(iround(n * p), n-1)\n\n    sx = sort(x)\n    nl = rn >> 1\n    nh = (rn - nl)\n    s = 0.0\n    for i = (1+nl) : (n-nh)\n        @inbounds s += x[i]\n    end\n    return s / (n - rn)\nend\n\n# compute mode, given the range of integer values\nfunction mode{T<:Integer}(a::AbstractArray{T}, rgn::UnitRange{T})\n    isempty(a) && error(\"mode: input array cannot be empty.\")\n    len = length(a)\n    r0 = rgn[1]  \n    r1 = rgn[end]\n    cnts = zeros(Int, length(rgn))\n    mc = 0    # maximum count\n    mv = r0   # a value corresponding to maximum count\n    for i = 1:len\n        @inbounds x = a[i]\n        if r0 <= x <= r1\n            @inbounds c = (cnts[x - r0 + 1] += 1)\n            if c > mc\n                mc = c\n                mv = x\n            end\n        end\n    end\n    return mv\nend\n\nfunction modes{T<:Integer}(a::AbstractArray{T}, rgn::UnitRange{T})\n    r0 = rgn[1]  \n    r1 = rgn[end]\n    n = length(rgn)\n    cnts = zeros(Int, n)\n    # find the maximum count\n    mc = 0 \n    for i = 1:length(a)\n        @inbounds x = a[i]\n        if r0 <= x <= r1\n            @inbounds c = (cnts[x - r0 + 1] += 1)\n            if c > mc\n                mc = c\n            end\n        end\n    end\n    # find all values corresponding to maximum count\n    ms = T[]\n    for i = 1:n\n        @inbounds if cnts[i] == mc\n            push!(ms, rgn[i])\n        end\n    end\n    return ms\nend\n\n# compute mode over arbitrary array\nfunction mode{T}(a::AbstractArray{T})\n    isempty(a) && error(\"mode: input array cannot be empty.\")\n    cnts = Dict{T,Int}()\n    # first element\n    mc = 1\n    mv = a[1]\n    cnts[mv] = 1\n    # find the mode along with table construction\n    for i = 2 : length(a)\n        @inbounds x = a[i]\n        if haskey(cnts, x)\n            c = (cnts[x] += 1)\n            if c > mc\n                mc = c\n                mv = x\n            end\n        else\n            cnts[x] = 1\n            # in this case: c = 1, and thus c > mc won't happen\n        end\n    end\n    return mv\nend\n\nfunction modes{T}(a::AbstractArray{T})\n    isempty(a) && error(\"modes: input array cannot be empty.\")\n    cnts = Dict{T,Int}()\n    # first element\n    mc = 1\n    cnts[a[1]] = 1\n    # find the mode along with table construction\n    for i = 2 : length(a)\n        @inbounds x = a[i]\n        if haskey(cnts, x)\n            c = (cnts[x] += 1)\n            if c > mc\n                mc = c\n            end\n        else\n            cnts[x] = 1\n            # in this case: c = 1, and thus c > mc won't happen\n        end\n    end\n    # find values corresponding to maximum counts\n    ms = T[]\n    for (x, c) in cnts\n        if c == mc\n            push!(ms, x)\n        end\n    end\n    return ms\nend\n\n\n#############################\n#\n#   quantile and friends\n#\n#############################\n\npercentile{T<:Real}(v::AbstractArray{T}, p) = quantile(v, p * 0.01)\n\nquantile{T<:Real}(v::AbstractArray{T}) = quantile(v, [.0, .25, .5, .75, 1.0])\nnquantile{T<:Real}(v::AbstractArray{T}, n::Integer) = quantile(v, (0:n)/n)\n\n\n#############################\n#\n#   Dispersion\n#\n#############################\n\n# Variation coefficient: std / mean\nvariation{T<:Real}(x::AbstractArray{T}, m::Real) = stdm(x, m) / m\nvariation{T<:Real}(x::AbstractArray{T}) = variation(x, mean(x))\n\n# Standard error of the mean: std(a) / sqrt(len)\nsem{T<:Real}(a::AbstractArray{T}) = sqrt(var(a) / length(a))\n\n# Median absolute deviation\nmad{T<:Real}(v::AbstractArray{T}, args...;arg...) = mad!(copy(v), args...;arg...)\nmad{T<:Real}(v::Range{T}, args...;arg...) = mad!([v], args...;arg...)\n\nfunction mad!{T<:Real}(v::AbstractArray{T}, center::Real=median!(v); constant::Real=1.4826)\n    for i in 1:length(v)\n        @inbounds v[i] = abs(v[i]-center)\n    end\n    constant * median!(v)\nend\n\n# Interquartile range\niqr{T<:Real}(v::AbstractArray{T}) = (q = quantile(v, [.25, .75]); q[2] - q[1])\n\n\n#############################\n#\n#   Z-scores\n#\n#############################\n\nfunction _zscore!(Z::AbstractArray, X::AbstractArray, μ::Real, σ::Real)\n    # Z and X are assumed to have the same size\n    iσ = inv(σ)\n    if μ == zero(μ)\n        for i = 1 : length(X)\n            @inbounds Z[i] = X[i] * iσ\n        end\n    else\n        for i = 1 : length(X)\n            @inbounds Z[i] = (X[i] - μ) * iσ\n        end\n    end\n    return Z\nend\n\n@ngenerate N typeof(Z) function _zscore!{S,T,N}(Z::AbstractArray{S,N}, X::AbstractArray{T,N}, μ::AbstractArray, σ::AbstractArray)\n    # Z and X are assumed to have the same size\n    # μ and σ are assumed to have the same size, that is compatible with size(X)\n    siz1 = size(X, 1)\n    @nextract N ud d->size(μ, d)\n    if size(μ, 1) == 1 && siz1 > 1\n        @nloops N i d->(d>1 ? (1:size(X,d)) : (1:1)) d->(j_d = ud_d ==1 ? 1 : i_d) begin\n            v = (@nref N μ j)\n            c = inv(@nref N σ j)\n            for i_1 = 1:siz1\n                (@nref N Z i) = ((@nref N X i) - v) * c\n            end\n        end\n    else\n        @nloops N i X d->(j_d = ud_d ==1 ? 1 : i_d) begin\n            (@nref N Z i) = ((@nref N X i) - (@nref N μ j)) / (@nref N σ j)\n        end\n    end\n    return Z\nend\n\nfunction _zscore_chksize(X::AbstractArray, μ::AbstractArray, σ::AbstractArray)\n    size(μ) == size(σ) || throw(DimensionMismatch(\"μ and σ should have the same size.\"))\n    for i=1:ndims(X)\n        dμ_i = size(μ,i)\n        (dμ_i == 1 || dμ_i == size(X,i)) || throw(DimensionMismatch(\"X and μ have incompatible sizes.\"))\n    end\nend\n\nfunction zscore!{ZT<:FloatingPoint,T<:Real}(Z::AbstractArray{ZT}, X::AbstractArray{T}, μ::Real, σ::Real)\n    size(Z) == size(X) || throw(DimensionMismatch(\"Z and X must have the same size.\"))\n    _zscore!(Z, X, μ, σ)\nend\n\nfunction zscore!{ZT<:FloatingPoint,T<:Real,U<:Real,S<:Real}(Z::AbstractArray{ZT}, X::AbstractArray{T}, \n                                                            μ::AbstractArray{U}, σ::AbstractArray{S})\n    size(Z) == size(X) || throw(DimensionMismatch(\"Z and X must have the same size.\"))\n    _zscore_chksize(X, μ, σ)\n    _zscore!(Z, X, μ, σ)\nend\n\nzscore!{T<:FloatingPoint}(X::AbstractArray{T}, μ::Real, σ::Real) = _zscore!(X, X, μ, σ)\n\nzscore!{T<:FloatingPoint,U<:Real,S<:Real}(X::AbstractArray{T}, μ::AbstractArray{U}, σ::AbstractArray{S}) = \n    (_zscore_chksize(X, μ, σ); _zscore!(X, X, μ, σ))\n\nfunction zscore{T<:Real}(X::AbstractArray{T}, μ::Real, σ::Real)\n    ZT = typeof((zero(T) - zero(μ)) / one(σ))\n    _zscore!(Array(ZT, size(X)), X, μ, σ)\nend\n\nfunction zscore{T<:Real,U<:Real,S<:Real}(X::AbstractArray{T}, μ::AbstractArray{U}, σ::AbstractArray{S})\n    _zscore_chksize(X, μ, σ)\n    ZT = typeof((zero(T) - zero(U)) / one(S))\n    _zscore!(Array(ZT, size(X)), X, μ, σ)\nend\n\nzscore{T<:Real}(X::AbstractArray{T}) = ((μ, σ) = mean_and_std(X); zscore(X, μ, σ))\nzscore{T<:Real}(X::AbstractArray{T}, dim::Int) = ((μ, σ) = mean_and_std(X, dim); zscore(X, μ, σ))\n\n\n\n#############################\n#\n#   entropy and friends\n#\n#############################\n\nfunction entropy{T<:Real}(p::AbstractArray{T})\n    s = 0.\n    z = zero(T)\n    for i = 1:length(p)\n        @inbounds pi = p[i]\n        if pi > z\n            s += pi * log(pi)\n        end\n    end\n    return -s\nend\n\nfunction crossentropy{T<:Real}(p::AbstractArray{T}, q::AbstractArray{T})\n    length(p) == length(q) || throw(DimensionMismatch(\"Inconsistent array length.\"))\n    s = 0.\n    z = zero(T)\n    for i = 1:length(p)\n        @inbounds pi = p[i]\n        @inbounds qi = q[i]\n        if pi > z\n            s += pi * log(qi)\n        end\n    end\n    return -s\nend\n\nfunction kldivergence{T<:Real}(p::AbstractArray{T}, q::AbstractArray{T})\n    length(p) == length(q) || throw(DimensionMismatch(\"Inconsistent array length.\"))\n    s = 0.\n    z = zero(T)\n    for i = 1:length(p)\n        @inbounds pi = p[i]\n        @inbounds qi = q[i]\n        if pi > z\n            s += pi * log(pi / qi)\n        end\n    end\n    return s\nend\n\n\n#############################\n#\n#   summary\n#\n#############################\n\nimmutable SummaryStats{T<:FloatingPoint}\n    mean::T\n    min::T\n    q25::T    \n    median::T    \n    q75::T\n    max::T\nend\n\nfunction summarystats{T<:Real}(a::AbstractArray{T})\n    m = mean(a)\n    qs = quantile(a, [0.00, 0.25, 0.50, 0.75, 1.00])    \n    R = typeof(convert(FloatingPoint, zero(T)))\n    SummaryStats{R}(\n        convert(R, m), \n        convert(R, qs[1]),\n        convert(R, qs[2]),\n        convert(R, qs[3]),\n        convert(R, qs[4]),\n        convert(R, qs[5]))\nend\n\nfunction Base.show(io::IO, ss::SummaryStats)\n    println(io, \"Summary Stats:\")\n    @printf(io, \"Mean:         %.6f\\n\", ss.mean)\n    @printf(io, \"Minimum:      %.6f\\n\", ss.min)\n    @printf(io, \"1st Quartile: %.6f\\n\", ss.q25)\n    @printf(io, \"Median:       %.6f\\n\", ss.median)\n    @printf(io, \"3rd Quartile: %.6f\\n\", ss.q75)\n    @printf(io, \"Maximum:      %.6f\\n\", ss.max)\nend\n\ndescribe{T<:Real}(a::AbstractArray{T}) = show(summarystats(a))\n\n", "meta": {"hexsha": "dd79a319e76897f4ebbdf184191019cbc48f4cd4", "size": 9401, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scalarstats.jl", "max_stars_repo_name": "jpata/StatsBase.jl", "max_stars_repo_head_hexsha": "3148a43686962e096f3ccbc063264908e42fb2c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/scalarstats.jl", "max_issues_repo_name": "jpata/StatsBase.jl", "max_issues_repo_head_hexsha": "3148a43686962e096f3ccbc063264908e42fb2c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scalarstats.jl", "max_forks_repo_name": "jpata/StatsBase.jl", "max_forks_repo_head_hexsha": "3148a43686962e096f3ccbc063264908e42fb2c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1138888889, "max_line_length": 129, "alphanum_fraction": 0.5113285821, "num_tokens": 3075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.8774767858797979, "lm_q1q2_score": 0.7851569724453883}}
{"text": "test_str = \"35\n20\n15\n25\n47\n40\n62\n55\n65\n95\n102\n117\n150\n182\n127\n219\n299\n277\n309\n576\"\n\ntest_list = split(test_str, '\\n')\n\nlist = readlines(\"day9_input.txt\")\n\nfunction check(sublist)\n    sublen = length(sublist)\n    last = sublist[end]\n    for j in 1:sublen-2\n        for k in j+1:sublen-1\n            if sublist[j] + sublist[k] == last\n                return true\n            end\n        end\n    end\n    return false\nend\n\nfunction invalid(preamble, list)\n    int_list = map(x-> parse(Int, x), list)\n    for i in preamble+1:length(int_list)\n        if !check(int_list[i-preamble:i])\n            return i, int_list[i]\n        end\n    end\n    return nothing, nothing\nend\n\n@show invalid(5, test_list)\n@show invalid(25, list)\n\nfunction contiguous(preamble, list)\n    i_inv, num_inv = invalid(preamble, list)\n    int_list = map(x-> parse(Int, x), list)\n    len = length(list)\n    for i in 1:len\n        j = i\n        sublistsum = int_list[i]\n        while sublistsum <= num_inv\n            if sublistsum == num_inv\n                return minimum(int_list[i:j]) + maximum(int_list[i:j])\n            end\n            j += 1\n            sublistsum += int_list[j]\n        end\n    end\nend\n\n@show contiguous(5, test_list)\n@show contiguous(25, list)\n\nnothing\n#= \n```julia\njulia> @btime invalid(25, list);\n  166.235 μs (526 allocations: 155.34 KiB)\n\njulia> @btime contiguous(25, list);\n  503.429 μs (531 allocations: 163.75 KiB)\n```\n =#\n# I restart counting with the second counter j every time I step up the\n# first counter i, but that is indeed a waste. I could just subtract the\n# first value in the sublist\n", "meta": {"hexsha": "c3d5399a01df531df368bcbb40fb48202b8a4639", "size": 1593, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "aoc2020/day09_invalid_encoding.jl", "max_stars_repo_name": "rmsrosa/adventofcode2020", "max_stars_repo_head_hexsha": "7a14a4c08eb33c9d02b97b1fbe63a150c81b2ade", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aoc2020/day09_invalid_encoding.jl", "max_issues_repo_name": "rmsrosa/adventofcode2020", "max_issues_repo_head_hexsha": "7a14a4c08eb33c9d02b97b1fbe63a150c81b2ade", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aoc2020/day09_invalid_encoding.jl", "max_forks_repo_name": "rmsrosa/adventofcode2020", "max_forks_repo_head_hexsha": "7a14a4c08eb33c9d02b97b1fbe63a150c81b2ade", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7411764706, "max_line_length": 72, "alphanum_fraction": 0.6120527307, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7850745388786314}}
{"text": "# https://adventofcode.com/2020/day/25\n\n\"\"\"\nSingle transformation step\n\"\"\"\nfunction transform(value::Integer, subject_number::Integer)\n    return rem(value * subject_number, 20201227)\nend\n\n\"\"\"\nUsing the `subject_number` and `loop_size`, calculate the `key`\n\"\"\"\nfunction get_key(subject_number::Integer, loop_size::Integer)\n    value = 1\n    for _ in 1:loop_size\n        value = transform(value, subject_number)\n    end\n    return value\nend\n\n# example: subject number -> public key\n@assert get_key(7, 8) == 5764801\n@assert get_key(7, 11) == 17807724\n# example: public key -> encryption key\n@assert get_key(17807724, 8) == 14897079\n@assert get_key(5764801, 11) == 14897079\n\n\"\"\"\nUsing the `subject_number` and `public_key`, guess the `loop_size`\n\"\"\"\nfunction get_loop_size(subject_number::Integer, public_key::Integer)\n    loop_size = 0\n    value = 1\n    while value != public_key\n        loop_size += 1\n        value = transform(value, subject_number)\n    end\n    return loop_size\nend\n\n# example: (subject number, public key) -> loop size\n@assert get_loop_size(7, 5764801) == 8\n@assert get_loop_size(7, 17807724) == 11\n# example: (public key, encryption key) -> loop size\n@assert get_loop_size(17807724, 14897079) == 8\n@assert get_loop_size(5764801, 14897079) == 11\n\nfunction part1(card_key, door_key)\n    card_loop_size = get_loop_size(7, card_key)\n    door_loop_size = get_loop_size(7, door_key)\n\n    card_encryption_key = get_key(card_key, door_loop_size)\n    door_encryption_key = get_key(door_key, card_loop_size)\n\n    @assert card_encryption_key == door_encryption_key\n\n    return card_encryption_key\nend\n\n@assert part1(5764801, 17807724) == 14897079\n\ntest = (14205034, 18047856)\nprintln(\"Part 1: $(result1 = part1(test...))\")\n# println(\"Part 2: $(result2 = part2(test...))\")\n\n@assert result1 == 297257\n# @assert result2 == 418819514477", "meta": {"hexsha": "673a7112f354e31612e5da0681ccba9152641bfd", "size": 1840, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2020/day-25.jl", "max_stars_repo_name": "twolodzko/advent-of-code", "max_stars_repo_head_hexsha": "8d0e41b20aa9007cad4d99aa5043648e0807d565", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2020/day-25.jl", "max_issues_repo_name": "twolodzko/advent-of-code", "max_issues_repo_head_hexsha": "8d0e41b20aa9007cad4d99aa5043648e0807d565", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/day-25.jl", "max_forks_repo_name": "twolodzko/advent-of-code", "max_forks_repo_head_hexsha": "8d0e41b20aa9007cad4d99aa5043648e0807d565", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4626865672, "max_line_length": 68, "alphanum_fraction": 0.7157608696, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7850745292042645}}
{"text": "using ViewerGL, LinearAlgebraicRepresentation\nGL = ViewerGL\nLar = LinearAlgebraicRepresentation\n\nV = [0.3307458 0.2735878 0.2527472 0.1955892 0.8735746 0.9604089 1.3600696 1.4469038 0.8952041 0.4087921 0.7697594 0.2833474 0.4465003 0.3177087 0.1293396 0.000548 1.1021824 0.6979647 1.0492281 0.6450104; 1.80716725 1.73722735 1.87091125 1.80097145 1.10328515 1.58712345 1.01597415 1.49981235 1.15705855 1.04345955 1.69419185 1.58059285 2.30620035 1.78225795 2.38416245 1.86022005 1.24012995 1.20346525 1.82393505 1.78727025]\nEV = Array{Int64,1}[[1, 2], [3, 4], [1, 3], [2, 4], [5, 6], [7, 8], [5, 7], [6, 8], [9, 10], [11, 12], [9, 11], [10, 12], [13, 14], [15, 16], [13, 15], [14, 16], [17, 18], [19, 20], [17, 19], [18, 20]]\nVV = [[k] for k=1:size(V,2)]\n\nGL.VIEW( GL.numbering(.05)((V,[VV, EV]),GL.COLORS[1]) );\n\n# arrangement of input data\nW = convert(Lar.Points, V')\ncop_EV = Lar.coboundary_0(EV)\nW, copEV, copFE = Lar.planar_arrangement(W, cop_EV)\n\n# compute containment graph of components\nbicon_comps = Lar.Arrangement.biconnected_components(copEV)\n\n# compute euler characteristic\nχ = Lar.euler_characteristic(W, copEV, copFE)\nprintln(\"χ = $χ ; bicon_comps = $(length(bicon_comps))\");\n\n# triangulation\ntriangulated_faces = Lar.triangulate2D(W, [copEV, copFE]);\nFVs = convert(Array{Lar.Cells}, triangulated_faces);\nV = convert(Lar.Points, W');\nGL.VIEW( GL.GLExplode(V,FVs, 1.5,1.5,1.5,99,0.6) );\n\nEVs = Lar.FV2EVs(copEV, copFE); # polygonal face fragments\nGL.VIEW( GL.GLExplode(V,EVs,1.5,1.5,1.5,99,1) );\n\n# visualization of component graphs\n# EW = Lar.cop2lar(copEV)\n# w = convert(Lar.Points, W')\n# comps = [ GL.GLLines(w,EW[comp],GL.COLORS[(k-1)%12+1]) for (k,comp) in enumerate(bicon_comps) ]\n# GL.VIEW(comps);\n", "meta": {"hexsha": "b353a21accbb1a2169ead74b39ceae3114b1cdaf", "size": 1718, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/euler_cuboids2D.jl", "max_stars_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_stars_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/euler_cuboids2D.jl", "max_issues_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_issues_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/euler_cuboids2D.jl", "max_forks_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_forks_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.4324324324, "max_line_length": 425, "alphanum_fraction": 0.6955762515, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7850745260801524}}
{"text": "using Bridge, Distributions, StaticArrays\nusing Plots\nusing LinearAlgebra\n\n#\nt = 2. \nn = 100\ndt = t / n\nx0 = 1.\n\n# define a Float64 Wiener process\nP = Wiener() #returns object representing standard Brownian motion\n\ntypeof(P)\n#prints Bridge.Wiener{Float64}\n\nsupertype(typeof(P))\n#prints Bridge.ContinuousTimeProcess{Float64}\n\n \n\n# sample Brownian motion on an equidistant grid\nW = sample(range(0., stop=t, length=n), P)\nW = sample(0:dt:t, P) # similar way\n\nprintln(W.tt) \n# prints [0.0,0.03,0.06,..., 0.93.96,0.99]\nplot(W.tt, W.yy) \n# plots path \n\nplot(W) \n# Bridge defines a plot @recipe (via RecipesBase)\n\n\n# sample complex Brownian motion on a nonequidistant grid\n\nX = sample(sort(rand(1000)), Wiener{Complex{Float64}}())\nplot(real(X.yy), imag(X.yy))\n\n# sample a standard Brownian bridge ending in v at time s\ns = 1.\nv = 0.\n\nB = sample(0:dt:s, WienerBridge(s, v)) \nplot(W.tt, W.yy, color=\"blue\")\nplot!(B.tt, B.yy, color=\"red\")\n# displays X and  Brownian bridge B in red\n\n\n# Define a diffusion process\nstruct OrnsteinUhlenbeck  <: ContinuousTimeProcess{Float64}\n    β::Float64 # drift parameter (also known as inverse relaxation time)\n    σ::Float64 # diffusion parameter\n    function OrnsteinUhlenbeck(β::Float64, σ::Float64)\n        isnan(β) || β > 0. || error(\"Parameter λ must be positive.\")\n        isnan(σ) || σ > 0. || error(\"Parameter σ must be positive.\")\n        new(β, σ)\n    end\nend\n\n# define drift and sigma of OrnsteinUhlenbeck\nimport Bridge: b, σ, a, transitionprob\nBridge.b(t,x, P::OrnsteinUhlenbeck) = -P.β*x\nBridge.σ(t, x, P::OrnsteinUhlenbeck) = P.σ\nBridge.a(t, x, P::OrnsteinUhlenbeck) = P.σ^2\n\n# simulate OrnsteinUhlenbeck using Euler scheme\nW = sample(0:0.01:10, Wiener{Float64}()) \nX = solve(EulerMaruyama(), 0.1, W, OrnsteinUhlenbeck(20., 1.))\n\nplot(X.tt, X.yy)\n\n# define transition density\ntransitionprob(s, x, t, P::OrnsteinUhlenbeck) = Normal(x*exp(-P.β*(t-s)), sqrt((0.5P.σ^2/P.β) *(1-exp(-2*P.β*(t-s)))))\n\n# plot likelihood of β \nLL = [(β, llikelihood(X, OrnsteinUhlenbeck(β, 1.))) for β in 1.:30.]\nfor (β, ll) in LL\n    println(\"β $β loglikelihood \", ll )\nend\nplot(Float64[β for (β, ll) in LL], Float64[ll for (β, ll) in LL])\n\n\n# sample OrnsteinUhlenbeck exactly. compare with euler scheme which degrates as dt = 0.07\nX = solve(EulerMaruyama(), 0.1, sample(0:0.07:10, Wiener{Float64}()), OrnsteinUhlenbeck(20., 1.))\nX2 = sample(0:0.07:10, OrnsteinUhlenbeck(20., 1.), 0.1)\nplot(X.tt, 1 .+ X.yy)\nplot!(X2.tt, X2.yy)\n\n# sample vector Brownian motion\nW2 = sample(0:0.1:10, Wiener{SVector{4,Float64}}())\nllikelihood(W2,Wiener{SVector{4,Float64}}())\n\nP = BridgeProp(OrnsteinUhlenbeck(3., 1.), 0:0.01:1,  (0., 1.), 1.)\nX = solve(EulerMaruyama(), 0.1, sample(0:0.01:1, Wiener{Float64}()),P)\n\nP2 = PBridgeProp(OrnsteinUhlenbeck(3., 1.), 0., 0., 1., 2., 2., 0., 1., 0.3, 1.)\nY = solve(EulerMaruyama(), 0.1, sample(0:0.01:2, Wiener{Float64}()),P2)\np = plot(Y.tt, Y.yy, xlim=(0, 2), ylim=(-3,3), legend=false)\n\nfor i in 1:100\n    global Y = solve(EulerMaruyama(), 0.1, sample(0:0.01:2, Wiener{Float64}()),P2)\n    plot!(p, Y.tt, Y.yy, xlim=(0, 2), ylim=(-3,3), linewidth=0.2)\nend\ndisplay(p)\n\n\n# Define a diffusion process\nstruct VOrnsteinUhlenbeck{d}  <: ContinuousTimeProcess{SVector{d,Float64}}\n    β # drift parameter (also known as inverse relaxation time)\n    σ # diffusion parameter\n    function VOrnsteinUhlenbeck{d}(β, σ) where d\n           new(β, σ)\n    end\nend\n\n# define drift and sigma of VOrnsteinUhlenbeck\n \nBridge.b(t, x, P::VOrnsteinUhlenbeck) = -P.β*x\nBridge.σ(t, x, P::VOrnsteinUhlenbeck) = P.σ*I\nBridge.a(t, x, P::VOrnsteinUhlenbeck) = P.σ*P.σ'*I\n\n# Simulate\ntt = 0.:0.003:10.\nX = solve(EulerMaruyama(), SVector(0., 0.), sample(tt, Wiener{SVector{2,Float64}}()), VOrnsteinUhlenbeck{2}(3., 1.)) \n\n\nyy = Bridge.mat(X.yy)\nplot(yy[1,:], yy[2,:], xlim=(-2, 2), ylim=(-2,2), linewidth=0.5)\n\n\n", "meta": {"hexsha": "dde614fe5d4d4921d543c784204868b5d659f775", "size": 3822, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/tutorial.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Bridge.jl-2d3116d5-4b8f-5680-861c-71f149790274", "max_stars_repo_head_hexsha": "e0a387537c4761c95bc91c29a9656dfb5265fe53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 98, "max_stars_repo_stars_event_min_datetime": "2015-10-02T18:39:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T09:22:06.000Z", "max_issues_repo_path": "example/tutorial.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Bridge.jl-2d3116d5-4b8f-5680-861c-71f149790274", "max_issues_repo_head_hexsha": "e0a387537c4761c95bc91c29a9656dfb5265fe53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2016-06-10T08:58:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T10:06:34.000Z", "max_forks_repo_path": "example/tutorial.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Bridge.jl-2d3116d5-4b8f-5680-861c-71f149790274", "max_forks_repo_head_hexsha": "e0a387537c4761c95bc91c29a9656dfb5265fe53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2016-01-12T09:53:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T11:59:22.000Z", "avg_line_length": 28.9545454545, "max_line_length": 118, "alphanum_fraction": 0.6640502355, "num_tokens": 1427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.7850283896593503}}
{"text": "using DataArrays\nusing DataFrames\nusing Gadfly\n\nfunction θestimation_()\n    # 1970 batting averages for 18 major league players. first column = batting average for first 45 at bats 2nd column = batting everage for remainder of season\n    data = [.400 .346\n            .378 .298\n            .356 .276\n            .333 .222\n            .311 .273\n            .311 .270\n            .289 .263\n            .267 .210\n            .244 .269\n            .244 .230\n            .222 .264\n            .222 .256\n            .222 .303\n            .222 .264\n            .222 .226\n            .200 .285\n            .178 .316\n            .156 .200]\n    \n    # data transformation\n    y = data[:,1]\n    ytest = data[:,2]\n    n = 45\n    # arcsin transform\n    x = sqrt(n).*asin(2.*y-1)\n    \n    # shrinkage estimate\n    μBar = mean(x)\n    V    = sumabs2(x - μBar)\n    d    = length(x)\n    s2   = V/d\n    # by construction of the arcsin transform\n    σ2   = 1\n    B    = σ2/(σ2 + max(0, s2-σ2))\n    μShrunk = μBar + (1-B).*(x-μBar)\n    \n    # back transform\n    θShrunk = 0.5*(sin(μShrunk/sqrt(n))+1)\n    θMLE    = y\n    (ytest, θShrunk, θMLE)\nend\n\n\"\"\"\nBaseball Batting Average Shrinkage Estimates\nReproduce example from \"Data Analysis Using Stein's Estimator and its Generalizations\" Bradley Efron; Carl Morris JASA Vol. 70, No. 350. (Jun., 1975), pp. 311-319.\n\"\"\"\nfunction shrinkageDemoBaseball()\n    θtrue, θShrunk, θMLE = θestimation_()\n    # plot Shrinkage Estimates\n    p1 = plot([layer(x=[θMLE[i] θShrunk[i]], y=[1 0], Geom.line) for i=1:d]...,\n              layer(x=θMLE, y=ones(1, d), Geom.point),\n              layer(x=θShrunk, y=zeros(1, d), Geom.point),\n              Theme(default_color=colorant\"blue\"))\n    \n    # histograms\n    df = DataFrame(PN=[1:d, 1:d, 1:d], Theta=[ytest, θShrunk, θMLE], Type=[ones(d), 2*ones(d), 3*ones(d)])\n    p2 = plot(df, y=\"Theta\", x=\"PN\", color=\"Type\", Geom.bar(position=:dodge))\n    \n    [p1, p2]\nend\n\nfunction shrinkageMSEBaseball()\n    θtrue, θShrunk, θMLE = θestimation_()\n    mseMLE = mean((θtrue-θMLE).^2)\n    mseShrink = mean((θtrue-θShrunk).^2)\n    [mseMLE, mseShrink, mseMLE/mseShrink]\nend\n\n", "meta": {"hexsha": "7647d6a8b212e69912842e90c3b97611c4a2ccf3", "size": 2123, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BayesianStatistics/shrinkageDemoBaseball.jl", "max_stars_repo_name": "aoboturov/PMTK4BookDemos.jl", "max_stars_repo_head_hexsha": "f44853081139b358e0e9a2bb36a3d35ac35dcb39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-25T15:50:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-25T15:50:42.000Z", "max_issues_repo_path": "src/BayesianStatistics/shrinkageDemoBaseball.jl", "max_issues_repo_name": "aoboturov/PMTK4BookDemos.jl", "max_issues_repo_head_hexsha": "f44853081139b358e0e9a2bb36a3d35ac35dcb39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BayesianStatistics/shrinkageDemoBaseball.jl", "max_forks_repo_name": "aoboturov/PMTK4BookDemos.jl", "max_forks_repo_head_hexsha": "f44853081139b358e0e9a2bb36a3d35ac35dcb39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3066666667, "max_line_length": 163, "alphanum_fraction": 0.553462082, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180243, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7850264822044287}}
{"text": "@doc doc\"\"\"\nmlr_beta{Float64}(y::Vector{Float64}, n::Int64=10)\n\nMoving linear regression intercept (column 1) and slope (column 2)\n\"\"\" ->\nfunction mlr_beta{Float64}(y::Vector{Float64}, n::Int64=10)\n    @assert n<length(y) && n>0 \"Argument n out of bounds.\"\n    out = zeros(Float64, (length(y),2))\n    out[1:n-1,:] = NaN\n    xi = collect(1.0:n)\n    xbar = mean(xi)\n    ybar = runmean(y, n, false)\n    @inbounds for i = n:length(y)\n        yi = y[i-n+1:i]\n        out[i,2] = cov(xi,yi) / var(xi)\n        out[i,1] = ybar[i] - out[i,2]*xbar\n    end\n    return out\nend\n\n@doc doc\"\"\"\nmlr_slope{Float64}(y::Vector{Float64}, n::Int64=10)\n\nMoving linear regression slope\n\"\"\" ->\nfunction mlr_slope{Float64}(y::Vector{Float64}, n::Int64=10)\n    @assert n<length(y) && n>0 \"Argument n out of bounds.\"\n    out = zeros(y)\n    out[1:n-1] = NaN\n    xi = collect(1.0:n)\n    @inbounds for i = n:length(y)\n        yi = y[i-n+1:i]\n        out[i] = cov(xi,yi) / var(xi)\n    end\n    return out\nend\n\n@doc doc\"\"\"\nmlr_intercept{Float64}(y::Vector{Float64}, n::Int64=10)\n\nMoving linear regression y-intercept\n\"\"\" ->\nfunction mlr_intercept{Float64}(y::Vector{Float64}, n::Int64=10)\n    @assert n<length(y) && n>0 \"Argument n out of bounds.\"\n    out = zeros(y)\n    out[1:n-1] = NaN\n    xi = collect(1.0:n)\n    xbar = mean(xi)\n    ybar = runmean(y, n, false)\n    @inbounds for i = n:length(y)\n        yi = y[i-n+1:i]\n        out[i] = ybar[i] - xbar*(cov(xi,yi)/var(xi))\n    end\n    return out\nend\n\n@doc doc\"\"\"\nmlr{Float64}(y::Vector{Float64}, n::Int64=10)\n\nMoving linear regression estimates\n\"\"\" ->\nfunction mlr{Float64}(y::Vector{Float64}, n::Int64=10)\n    b = mlr_beta(y, n)\n    return b[:,1] + b[:,2]*float(n)\nend\n\n@doc doc\"\"\"\nmlr_se{Float64}(y::Vector{Float64}, n::Int64=10)\n\nMoving linear regression standard error of estimate\n\"\"\" ->\nfunction mlr_se{Float64}(y::Vector{Float64}, n::Int64=10)\n    yhat = mlr(y, n)\n    r = zeros(Float64, n)\n    out = zeros(y)\n    out[1:n-1] = NaN\n    nf = float(n)\n    @inbounds for i = n:length(y)\n        r = y[i-n+1:i] - yhat[i]\n        out[i] = sqrt(sum(r.^2)/nf)\n    end\n    return out\nend\n\n@doc doc\"\"\"\nmlr_ub{Float64}(y::Vector{Float64}, n::Int64=10, se::Float64=2.0)\n\nMoving linear regression upper bound\n\"\"\" ->\nfunction mlr_ub{Float64}(y::Vector{Float64}, n::Int64=10, se::Float64=2.0)\n    return y + se*mlr_se(y,n)\nend\n\n@doc doc\"\"\"\nmlr_lb{Float64}(y::Vector{Float64}, n::Int64=10, se::Float64=2.0)\n\nMoving linear regression lower bound\n\"\"\" ->\nfunction mlr_lb{Float64}(y::Vector{Float64}, n::Int64=10, se::Float64=2.0)\n    return y - se*mlr_se(y,n)\nend\n\n@doc doc\"\"\"\nmlr_bands{Float64}(y::Vector{Float64}, n::Int64=10, se::Float64=2.0)\n\nMoving linear regression bands\n\n`Output:`\n\nColumn 1: Lower bound\n\nColumn 2: Regression estimate\n\nColumn 3: Upper bound\n\"\"\" ->\nfunction mlr_bands{Float64}(y::Vector{Float64}, n::Int64=10, se::Float64=2.0)\n    out = zeros(Float64, (length(y),3))\n    out[1:n-1,:] = NaN\n    out[:,2] = mlr(y, n)\n    out[:,1] = mlr_lb(y, n, se)\n    out[:,1] = mlr_ub(y, n, se)\n    return out\nend\n\n@doc doc\"\"\"\nmlr_rsq{Float64}(y::Vector{Float64}, n::Int64=10; adjusted::Bool=false)\n\nMoving linear regression R-squared (and adjusted R-squared)\n\"\"\" ->\nfunction mlr_rsq{Float64}(y::Vector{Float64}, n::Int64=10; adjusted::Bool=false)\n    yhat = mlr(y, n)\n    rsq = runcor(y, yhat, n, false) .^ 2\n    if adjusted\n        return rsq - (1.0-rsq)*(1.0/(float(n)-2.0))\n    else\n        return rsq\n    end\nend\n\n", "meta": {"hexsha": "58f2ec9a2c1b2452d60fe24549bcf9321db23c43", "size": 3431, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/reg.jl", "max_stars_repo_name": "JuliaPackageMirrors/Indicators.jl", "max_stars_repo_head_hexsha": "2131c08307f01f17542321a315e20aa21931f65c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/reg.jl", "max_issues_repo_name": "JuliaPackageMirrors/Indicators.jl", "max_issues_repo_head_hexsha": "2131c08307f01f17542321a315e20aa21931f65c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/reg.jl", "max_forks_repo_name": "JuliaPackageMirrors/Indicators.jl", "max_forks_repo_head_hexsha": "2131c08307f01f17542321a315e20aa21931f65c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5071428571, "max_line_length": 80, "alphanum_fraction": 0.6091518508, "num_tokens": 1236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029487, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7850264725294811}}
{"text": "#=\nA palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.\n\nFind the largest palindrome made from the product of two 3-digit numbers.\n=#\n\nfunction calc()\n  min = 100; max = 999\n  maxPalindrome = 0\n  for i in min:max, j in min:max\n      current = i * j\n      if string(current) == reverse(string(current))\n        maxPalindrome = current > maxPalindrome ? current : maxPalindrome\n      end\n  end\n  maxPalindrome\nend\n@time println(calc())\n", "meta": {"hexsha": "9782ffe08ea5d758b0da642ec121a209aec1a9bb", "size": 515, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p4.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p4.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p4.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 27.1052631579, "max_line_length": 133, "alphanum_fraction": 0.6932038835, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107896491797, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7850264691609989}}
{"text": "using Zygote, StaticArrays\n\n# Naive Matrix Multiply\n\nfunction mul(a::AbstractMatrix, b::AbstractMatrix)\n  [sum(a[i, k]*b[k,j] for k = 1:size(a, 2))\n   for i = 1:size(a, 1), j = 1:size(b, 2)]\nend\n\na = [1 2; 3 4]\n\nmul(a, a)\n\n# Static Matrix Multiple\n\n_sum(xs) = reduce((a, b) -> :($a+$b), xs)\n\n@generated function mul(a::SMatrix{M,N}, b::SMatrix{N,O}) where {M,N,O}\n  :(SMatrix{M,O}(\n      $([_sum(:(a[$i, $k]*b[$k,$j]) for k = 1:size(a, 2))\n         for i = 1:size(a, 1), j = 1:size(b, 2)]...),))\nend\n\n@generated function mul(a::SMatrix{M,N}, b::SMatrix{N,O}) where {M,N,O}\n  quote\n    Base.@_inline_meta\n    SMatrix{M,O}(\n      $([_sum(:(a[$i, $k]*b[$k,$j]) for k = 1:size(a, 2))\n        for i = 1:size(a, 1), j = 1:size(b, 2)]...),)\n  end\nend\n\na = @SArray [1 2; 3 4]\n\nmul(a, a)\n\nsqmul(a) = sum(mul(a, a))\n\n@code_llvm sqmul(a)\n\n# See the code output\n\nfunction _mul(a::SMatrix{M,N}, b::SMatrix{N,O}) where {M,N,O}\n  :(SMatrix{M,O}(\n      $([_sum(:(a[$i, $k]*b[$k,$j]) for k = 1:size(a, 2))\n         for i = 1:size(a, 1), j = 1:size(b, 2)]...),))\nend\n\n_mul(a, a)\n", "meta": {"hexsha": "6c4509e077420cc43c4bb1d91328c2cc9ef53657", "size": 1061, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "staging/staticarray.jl", "max_stars_repo_name": "MikeInnes/zygote-paper", "max_stars_repo_head_hexsha": "9f1ecc895b2ab825b5d4c0bdca746d9660117d11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 72, "max_stars_repo_stars_event_min_datetime": "2019-05-07T19:59:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T13:45:35.000Z", "max_issues_repo_path": "staging/staticarray.jl", "max_issues_repo_name": "MikeInnes/zygote-paper", "max_issues_repo_head_hexsha": "9f1ecc895b2ab825b5d4c0bdca746d9660117d11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-05-15T14:31:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T12:34:00.000Z", "max_forks_repo_path": "staging/staticarray.jl", "max_forks_repo_name": "MikeInnes/zygote-paper", "max_forks_repo_head_hexsha": "9f1ecc895b2ab825b5d4c0bdca746d9660117d11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-05-14T19:00:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-20T00:18:39.000Z", "avg_line_length": 21.22, "max_line_length": 71, "alphanum_fraction": 0.5240339303, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878722, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7850264609550425}}
{"text": "export RandomizedKaczmarz, RandomizedBlockKaczmarz\n\n\"\"\"\nRandomized Kaczmarz\n\nSection 3.3 in Gower, R. M., & Richtárik, P. (2015).\nRandomized iterative methods for linear systems.\nSIAM Journal on Matrix Analysis and Applications, 36(4), 1660-1690.\n\nRK takes a step in the direction of the negative stochastic gradient.\nThis means that it is equivalent to the SGD method.\nHowever, the stepsize choice is very special: RK chooses the stepsize which leads to the point\nwhich is closest to x* in the Euclidean norm.\n\"\"\"\nfunction RandomizedKaczmarz(stp::AbstractStopping; is_zero_start::Bool = false, kwargs...)\n  A, b = get_matrix(stp.pb), get_vector(stp.pb)\n  state = stp.current_state\n  m = size(A, 1)\n  if is_zero_start\n    state.res .= b\n  else\n    state.res .= b .- A * state.x\n  end\n  OK = start!(stp, no_opt_check = true)\n\n  while !OK\n    i = Int(floor(rand() * m) + 1)\n    Ai = view(A, i, :)\n    AiAi = dot(Ai, Ai)\n    if AiAi != 0\n      Aix = dot(Ai, state.x)\n      state.x .-= (Aix - b[i]) / AiAi * Ai\n    end\n    state.res = b - A * state.x\n    OK = cheap_stop!(stp)\n  end\n\n  return stp\nend\n\n\"\"\"\nRandomized block Kaczmarz\n\nSection 3.5 in Gower, R. M., & Richtárik, P. (2015).\nRandomized iterative methods for linear systems.\nSIAM Journal on Matrix Analysis and Applications, 36(4), 1660-1690.\n\"\"\"\nfunction RandomizedBlockKaczmarz(\n  stp::AbstractStopping;\n  is_zero_start::Bool = false,\n  r::Int = 15,\n  rand_r::Bool = false,\n  kwargs...,\n)\n  A, b = get_matrix(stp.pb), get_vector(stp.pb)\n  state = stp.current_state\n  m = size(A, 1)\n  if is_zero_start\n    state.res .= b\n  else\n    state.res .= b .- A * state.x\n  end\n  OK = start!(stp, no_opt_check = true)\n\n  while !OK\n    r = rand_r ? Int(floor(rand() * m) + 1) : min(r, m)\n    sub = zeros(Int64, r)\n    #sample!(1:m, sub) #x is a subset of [1,...,m] of size r #sample repeat entries\n    sub = StatsBase.randperm(m)[1:r]\n\n    Ai = view(A, sub, :)\n    resk = state.res[sub]\n    if !(Ai == 0)\n      state.x .-= Ai' * pinv(Matrix(Ai * Ai')) * resk\n    end\n    state.res .= A * state.x .- b\n    OK = cheap_stop!(stp)\n  end\n\n  return stp\nend\n", "meta": {"hexsha": "5c0852789e3f54bca0e92db4f8900f75dcc1cdd3", "size": 2097, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/random_Kaczmarcz.jl", "max_stars_repo_name": "tmigot/RandomLinearAlgebraSolvers.jl", "max_stars_repo_head_hexsha": "e4f53b533f8f4bed61d5dc40ce75ff74d95e0d28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-23T19:07:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T19:08:09.000Z", "max_issues_repo_path": "src/random_Kaczmarcz.jl", "max_issues_repo_name": "tmigot/RandomLinearAlgebraSolvers.jl", "max_issues_repo_head_hexsha": "e4f53b533f8f4bed61d5dc40ce75ff74d95e0d28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-11-26T17:38:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T01:21:44.000Z", "max_forks_repo_path": "src/random_Kaczmarcz.jl", "max_forks_repo_name": "tmigot/RandomLinearAlgebraSolvers.jl", "max_forks_repo_head_hexsha": "e4f53b533f8f4bed61d5dc40ce75ff74d95e0d28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5731707317, "max_line_length": 94, "alphanum_fraction": 0.6409155937, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7850161337554973}}
{"text": "# # An equation of second order in two dimmensions\n#\n# Let \\\\(\\Omega = (0, 1)^3\\\\) the unit cube and denote \\\\( \\Gamma = \\partial \\Omega\\\\) its boundary.\n# Consider the following problem. Given \\\\(f \\in C(\\Omega)\\\\), find a function \\\\(u\\\\) satisfying\n# -\\Delta u + u = f in \\Omega\n# u = 0 on \\Gamma\n\nusing Revise\nusing SymFEL\nusing SymPy\nusing LinearAlgebra\nusing SparseArrays\nusing JLD2\nusing WriteVTK\n\n## discretization parameters\n# we use the mesh square.msh (in gmsh format)\n# obtained from square.geo using gmsh\n# this mesh is formed by quad elements\n# we use gmsh module for read the mesh\n# there are some problems using Threads and gmsh (in linux)\n# the file is square.jld2 is prepared separetely\n@load \"cube.jld2\"\n\n\n# elementary matrices -\nelem_Mx = SymFEL.get_lagrange_em(1, 0, 0)\nelem_Kx = SymFEL.get_lagrange_em(1, 1, 1)\n\nnc = ([1, 2, 2, 1, 1, 2, 2, 1],\n      [1, 1, 2, 2, 1, 1, 2, 2],\n      [1, 1, 1, 1, 2, 2, 2, 2])\nnr = nc\n\nelem_Mxyz = SymFEL.get_cube_em(elem_Mx,\n                               elem_Mx,\n                               elem_Mx,\n                               nc,\n                               nr)\n\nelem_Kxyz = SymFEL.get_cube_em(elem_Kx,\n                               elem_Mx,\n                               elem_Mx,\n                               nc,\n                               nr) +\n            SymFEL.get_cube_em(elem_Mx,\n                               elem_Kx,\n                               elem_Mx,\n                               nc,\n                               nr) +\n            SymFEL.get_cube_em(elem_Mx,\n                               elem_Mx,\n                               elem_Kx,\n                               nc,\n                               nr)\n\n\ndx = norm(nodes_coordinate[:, elements_bound[1,1]] - nodes_coordinate[:, elements_bound[2,1]])\n\nelem_Kxyz_dx = convert(Matrix{Float64}, elem_Kxyz.subs(h, dx))\nelem_Mxyz_dx = convert(Matrix{Float64}, elem_Mxyz.subs(h, dx));\n\n# global matrices\nK = SymFEL.assemble_cubemesh_FE_matrix(elem_Kxyz_dx, elements_int, order1=1, order2=1)\nM = SymFEL.assemble_cubemesh_FE_matrix(elem_Mxyz_dx, elements_int, order1=1, order2=1)\n\nf = (3*pi^2 + 1) * (sin.(pi * nodes_coordinate[1,:])\n                    .* sin.(pi * nodes_coordinate[2,:])\n                    .* sin.(pi * nodes_coordinate[3,:]))\n\nF = M * f\n\nA = K + M\n\n# boundary condition\ntgv = 1e30\nA[nodes_boundary, nodes_boundary] += tgv * sparse(Matrix{Float64}(I, nodes_boundary_N, nodes_boundary_N))\n\nu = A \\ F\nu_exact = sin.(pi*nodes_coordinate[1,:]) .* sin.(pi*nodes_coordinate[2,:]) .* sin.(pi*nodes_coordinate[3,:])\nerr = u - u_exact\n\nprintln(\"L2 error : \", sqrt(err' * M * err))\nprintln(\"H1 error : \", sqrt(err' * K * err))\n\n\n# export to vtk\ncells = [MeshCell(VTKCellTypes.VTK_HEXAHEDRON, elements_int[1:8, i]) for i = 1:elements_int_N]\n\n\npoints_x = nodes_coordinate[1, :]\npoints_y = nodes_coordinate[2, :]\npoints_z = nodes_coordinate[3, :]\nvtkfile = vtk_grid(\"ex5-output\", points_x, points_y, points_z, cells)\n\nvtkfile[\"u\", VTKPointData()] = u\noutfiles = vtk_save(vtkfile)\n", "meta": {"hexsha": "11fa20e37a0abc20e422a64fb5212808495524e6", "size": 3029, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ex5-lagrange3d.jl", "max_stars_repo_name": "ncindea/SymFE.jl", "max_stars_repo_head_hexsha": "886e7fe844d0833bda4ab721414111f8fe353915", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-12T22:24:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T12:06:02.000Z", "max_issues_repo_path": "examples/ex5-lagrange3d.jl", "max_issues_repo_name": "ncindea/SymFEL.jl", "max_issues_repo_head_hexsha": "886e7fe844d0833bda4ab721414111f8fe353915", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ex5-lagrange3d.jl", "max_forks_repo_name": "ncindea/SymFEL.jl", "max_forks_repo_head_hexsha": "886e7fe844d0833bda4ab721414111f8fe353915", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9081632653, "max_line_length": 108, "alphanum_fraction": 0.5671838891, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374443, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7849631118434168}}
{"text": "\"\"\"\n    kernel = Skernel(k,σ=1.0)\n\nConstruct the scattering kernel functions in momentum space.\nThe kernel function is used to construct both the energy-damping term, and noise in the energy-damped\nstochastic projected Gross-Pitaevskii equation.\n\n`k`: momentum-space grid in where scattering is to be evaluated.\n\n`σ`: width parameter for `k`-space degrees of freedom in the case of N=1,2 spatial dimensions.\n\nExternal links\n\n[Low-Dimensional Stochastic Projected Gross-Pitaevskii Equation, Bradley, Rooney, MacDonald, Physical Review A 92, 033631 (2015)](https://arxiv.org/abs/1507.02023)\n\n\"\"\"\nfunction Skernel1(k,σ=1.0)\n    erfcx(abs(k)*σ/sqrt(2))/sqrt(8*π*σ^2)\nend\nfunction Skernel2(k,σ=1.0)\n    k==0.0 ? 0.0 : exp(abs(k*σ/2)^2)*besselk(0,abs(k*σ/2)^2)/(2*π)\nend\nfunction Skernel3(k)\n    k==0.0 ? 0.0 : 1/abs(k)\nend\n\nSkernel(k::Array{Float64,1},σ=1.0) = Skernel1.(k,σ)\nSkernel(k::Array{Float64,2},σ=1.0) = Skernel2.(k,σ)\nSkernel(k::Array{Float64,3},σ=1.0) = Skernel3.(k)\n", "meta": {"hexsha": "529bed04d8908721bc44324b89b2691660b6986d", "size": 973, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Skernel.jl", "max_stars_repo_name": "AshtonSBradley/ProjectedGPE.jl", "max_stars_repo_head_hexsha": "16623c1e00bbbae73e7448bd9b38f5b7e97979e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-06-05T09:44:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T17:59:48.000Z", "max_issues_repo_path": "src/Skernel.jl", "max_issues_repo_name": "AshtonSBradley/ProjectedGPE.jl", "max_issues_repo_head_hexsha": "16623c1e00bbbae73e7448bd9b38f5b7e97979e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-08-30T05:46:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-30T05:46:58.000Z", "max_forks_repo_path": "src/Skernel.jl", "max_forks_repo_name": "AshtonSBradley/ProjectedGPE.jl", "max_forks_repo_head_hexsha": "16623c1e00bbbae73e7448bd9b38f5b7e97979e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-06-05T09:53:03.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-05T09:53:03.000Z", "avg_line_length": 32.4333333333, "max_line_length": 163, "alphanum_fraction": 0.7091469681, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832974, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7849631105332232}}
{"text": "\n#functions for computing mutual informations (in bits)\n#po is the distribution where the KL is averaged over\n#the KL measures going from px to pxgy\nfunction mutualinformation(py::Vector, px::Vector, pxgy::Matrix)    \n    card_y = size(py,1)\n    card_x = size(px,1)\n    if (size(pxgy,1)!=card_x) || (size(pxgy,2)!=card_y)\n        error(\"Dimensionality of p(x|y) does not match p(x), p(y)!\")\n    end\n    \n    MI = 0\n    for i in 1:card_y\n        MI += py[i] * kl_divergence_bits(vec(pxgy[:,i]),px)\n    end\n    \n    return MI\nend\n\n\n#functions for computing the conditional mutual information\n#I(X;Y|Z)(in bits)\nfunction conditional_mutualinformation(py::Vector, pzgy::Matrix, pxgz::Matrix, pxgzy)  \n    #I(X;Y|Z) = ∑_y p(y) DKL( p(x|z,y)||p(x|z) )\n    #I(X;Y|Z) = ∑_y p(y) ∑_z p(z|y) ∑_x p(x|z,y) log( p(x|z,y)/p(x|z) )\n    \n    card_y = length(py)\n    card_z = size(pzgy,1)    \n    \n    \n    MI = 0\n    for j in 1:card_y\n        for k in 1:card_z\n            MI += py[j]*pzgy[k,j] * kl_divergence_bits( vec(pxgzy[:,k,j]), vec(pxgz[:,k]))\n        end\n    end   \n    \n    return MI\nend\n\n\n\n\n#function for computing the expected utility\n#pagw and U_pre must have the same dimensionality\nfunction expectedutility(pw::Vector, pagw::Matrix, U_pre::Matrix)\n    #E[U] = ∑_a,w p(w)p(a|w) U(a,w)\n    card_w = size(pw,1)\n    card_a = size(pagw,1)\n    if (size(pagw,2)!=card_w) || (size(U_pre,1)!=card_a) || (size(U_pre,2)!=card_w)\n        error(\"Dimensionality of p(a|w), U_pre(a,w) and p(w) does not match!\")\n    end\n    \n    EU = 0\n    for i in 1:card_w\n            EU += pw[i] * sum(pagw[:,i] .* U_pre[:,i])\n    end\n        \n    return EU\nend\n\n\n#This function assumes that the utility function U(a,w) is not a function of the percept o\nfunction expectedutility(pw::Vector, pogw::Matrix, pagow, U_pre::Matrix)\n    #E[U] = ∑_a,o,w p(w)p(o|w)p(a|o,w) U(a,w)\n    \n    #reuse the function that computes E[U] for ∑_a,w p(w)p(a|w) U(a,w)\n    #to do so, compute p(a|w)\n    pagw = marginalizeo(pogw,pagow)\n    \n    return expectedutility(pw,pagw,U_pre)\nend\n\n\n\n\n#Entropy in bits (using entropy from Distributions.jl)\nfunction entropybits(d::Distribution)\n    return Distributions.entropy(d,2) #in bits\nend\n\n#Entropy in bits for an discrete distribution represented as a vector\nfunction entropybits(p::Vector)\n    return entropybits(Categorical(p))\nend\n\n#Explicitly provide a function for the log in bits here.\n#The rationale behind this is that it makes it easily possible to spot all the \n#places (in the code) to change if one wants to use the nats (natural logarithm) intead of bits.\nfunction log_bits(x)\n    return log2(x)\nend\n\n#Kullback-Leibler divergence in bits \nfunction kl_divergence_bits(p_x::Vector, p0_x::Vector)\n    #D_KL_bits = ∑_x p(x) log2 (p(x)/p0(x))\n\n    if sum(p0_x.==0) > 0\n        error(\"Zeros in denominator before kl_divergence computation!\")\n    end\n\n    kl_div = kl_divergence(p_x, p0_x)/log(2) #using function from Distances.jl\n\n    return kl_div\nend\n\n\n\n\n\n#compute value of rate-distortion objective (avg ΔF)\nfunction RDobjective(EU,I,β)\n    return EU-I/β\nend\n\n#Objective-value for the three-variable general case\nfunction ThreeVArRDobjective(EU, I_ow, I_ao, I_awgo, β1, β2, β3)\n    if(β3==0)\n        #sequential case - I(A;W|O) should be zero and since β3=Inf → ∞ * 0 = NaN\n        #handle this by using a tiny β3 - if I(A;W|O) is nonzero, this should be easily detectable through the huge\n        #value of the objective\n        β3 = eps()\n    end\n    return EU - (1/β1)*I_ow - (1/β2)*I_ao - (1/β3)*I_awgo\nend\n\n\n\n\n\n#compute I(A;W), H(A), H(A|W), E[U] and E[U]-I(A;W)/β\nfunction analyzeBAsolution(pw::Vector, pa::Vector, pagw::Matrix, U_pre::Matrix, β)\n    #compute I(A;W)\n    I = mutualinformation(pw,pa,pagw)\n    #compute H(A)\n    Ha = entropybits(pa)\n    #compute H(A|W)\n    Hagw = Ha-I\n    #compute EU\n    EU = expectedutility(pw,pagw,U_pre)\n    #compute value of objective\n    RDobj = RDobjective(EU,I,β)\n\n    return I, Ha, Hagw, EU, RDobj\nend\n\n\n\n#compute mutual informations, entropies and value of objective for three-variable general case\nfunction analyze_three_var_BAsolution(pw::Vector, po::Vector, pa::Vector, pogw::Matrix,\n    pago::Matrix, pagow, pagw::Matrix, U_pre::Matrix, β1, β2, β3)\n    \n    #compute I(O;W)\n    I_ow = mutualinformation(pw,po,pogw)\n    \n    #compute I(A;O)\n    I_ao = mutualinformation(po,pa,pago)\n    \n    #compute I(A;W|O)\n    I_awgo = conditional_mutualinformation(pw, pogw, pago, pagow)\n\n    #compute I(A;W)\n    I_aw = mutualinformation(pw,pa,pagw)\n    \n    #compute H(O) \n    #println(\"1: ∑p(o) = $(sum(po))\")\n    Ho = entropybits(po)\n    \n    #compute H(A)\n    #println(\"2: ∑p(a) =  $(sum(pa))\") \n    Ha = entropybits(pa)\n    \n    #compute H(O|W)\n    Hogw = Ho - I_ow\n    \n    #compute H(A|O)\n    Hago = Ha - I_ao\n    \n    #compute H(A|O,W)\n    Hagow = Hago - I_awgo\n\n    #compute H(A|W)\n    Hagw = Ha - I_aw\n    \n    #compute EU\n    EU = expectedutility(pw,pagw,U_pre)\n    \n    #compute value of objective\n    ThreeVarRDobj = ThreeVArRDobjective(EU, I_ow, I_ao, I_awgo, β1, β2, β3)\n\n    return I_ow, I_ao, I_awgo, I_aw, Ho, Ha, Hogw, Hago, Hagow, Hagw, EU, ThreeVarRDobj\nend\n\n", "meta": {"hexsha": "87765f6ae369a8730005560fcc4e2fb91c777a1a", "size": 5126, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "NotebooksAndCode/InformationTheoryFunctions.jl", "max_stars_repo_name": "tgenewein/LossyCompressionAndDecisionMaking", "max_stars_repo_head_hexsha": "1bc07dd93057b05db2ec14453801719f34ebcfa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-22T10:12:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-17T14:36:56.000Z", "max_issues_repo_path": "NotebooksAndCode/InformationTheoryFunctions.jl", "max_issues_repo_name": "tgenewein/LossyCompressionAndDecisionMaking", "max_issues_repo_head_hexsha": "1bc07dd93057b05db2ec14453801719f34ebcfa3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2015-06-24T11:34:13.000Z", "max_issues_repo_issues_event_max_datetime": "2015-09-27T14:01:51.000Z", "max_forks_repo_path": "NotebooksAndCode/InformationTheoryFunctions.jl", "max_forks_repo_name": "tgenewein/LossyCompressionAndDecisionMaking", "max_forks_repo_head_hexsha": "1bc07dd93057b05db2ec14453801719f34ebcfa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-30T06:19:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T06:19:24.000Z", "avg_line_length": 26.4226804124, "max_line_length": 115, "alphanum_fraction": 0.6330472103, "num_tokens": 1720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7849631078731548}}
{"text": "module Basis\n\nexport basis, nodes\n\nimport FastGaussQuadrature: gausslegendre\nimport Polynomials: Poly\n\nfunction lagrange(x, w)\n  \"\"\"\n  Taken from SciPy 0.18.1:\n\n  Return a Lagrange interpolating polynomial.\n  Given two 1-D arrays `x` and `w,` returns the Lagrange interpolating\n  polynomial through the points ``(x, w)``.\n  Warning: This implementation is numerically unstable. Do not expect to\n  be able to use more than about 20 points even if they are chosen optimally.\n  Parameters\n  ----------\n  x : array_like\n      `x` represents the x-coordinates of a set of datapoints.\n  w : array_like\n      `w` represents the y-coordinates of a set of datapoints, i.e. f(`x`).\n  Returns\n  -------\n      The Lagrange interpolating polynomial.\n  \"\"\"\n  M = size(x)[1]\n  p = Poly([0])\n  for j=1:M\n    pt = Poly([w[j]])\n    for k=1:M\n      if k != j\n        fac = x[j]-x[k]\n        pt *= Poly([-x[k], 1.0]) / fac\n      end\n    end\n    p += pt\n  end\n  return p\nend\n\nfunction nodes(N)\n  # Returns Legendre-Gauss nodes, scaled to [0,1]\n  return 0.5 * (1 + gausslegendre(N+1)[1])\nend\n\nfunction basis(N)\n  # Returns basis polynomials\n  nodeArray = nodes(N)\n  return [lagrange(nodeArray, eye(N+1)[:,i]) for i in 1:N+1]\nend\n\nend   # module Basis\n", "meta": {"hexsha": "7ccde1443c01d819140e2f8a77fcf6ae06f81dc4", "size": 1229, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Basis.jl", "max_stars_repo_name": "haranjackson/Julia-WENO", "max_stars_repo_head_hexsha": "60fcbf5cada2fbb910a1395f39bf6b959b1a752a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-09-14T02:32:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T21:56:59.000Z", "max_issues_repo_path": "src/Basis.jl", "max_issues_repo_name": "wme7/Julia-WENO", "max_issues_repo_head_hexsha": "60fcbf5cada2fbb910a1395f39bf6b959b1a752a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Basis.jl", "max_forks_repo_name": "wme7/Julia-WENO", "max_forks_repo_head_hexsha": "60fcbf5cada2fbb910a1395f39bf6b959b1a752a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-06T02:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-18T09:14:58.000Z", "avg_line_length": 22.7592592593, "max_line_length": 77, "alphanum_fraction": 0.6403580146, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7849631015524802}}
{"text": "doc\"\"\"\n    Gumbel(μ, θ)\n\nThe *Gumbel distribution*  with location `μ` and scale `θ` has probability density function\n\n$f(x; \\mu, \\theta) = \\frac{1}{\\theta} e^{-(z + e^z)},\n\\quad \\text{ with } z = \\frac{x - \\mu}{\\theta}$\n\n```julia\nGumbel()            # Gumbel distribution with zero location and unit scale, i.e. Gumbel(0, 1)\nGumbel(u)           # Gumbel distribution with location u and unit scale, i.e. Gumbel(u, 1)\nGumbel(u, b)        # Gumbel distribution with location u and scale b\n\nparams(d)        # Get the parameters, i.e. (u, b)\nlocation(d)      # Get the location parameter, i.e. u\nscale(d)         # Get the scale parameter, i.e. b\n```\n\nExternal links\n\n* [Gumbel distribution on Wikipedia](http://en.wikipedia.org/wiki/Gumbel_distribution)\n\"\"\"\nimmutable Gumbel{T<:Real} <: ContinuousUnivariateDistribution\n    μ::T  # location\n    θ::T  # scale\n\n    Gumbel(μ::T, θ::T) = (@check_args(Gumbel, θ > zero(θ)); new(μ, θ))\nend\n\nGumbel{T<:Real}(μ::T, θ::T) = Gumbel{T}(μ, θ)\nGumbel(μ::Real, θ::Real) = Gumbel(promote(μ, θ)...)\nGumbel(μ::Integer, θ::Integer) = Gumbel(Float64(μ), Float64(θ))\nGumbel(μ::Real) = Gumbel(μ, 1.0)\nGumbel() = Gumbel(0.0, 1.0)\n\n@distr_support Gumbel -Inf Inf\n\nconst DoubleExponential = Gumbel\n\n#### Conversions\n\nconvert{T <: Real, S <: Real}(::Type{Gumbel{T}}, μ::S, θ::S) = Gumbel(T(μ), T(θ))\nconvert{T <: Real, S <: Real}(::Type{Gumbel{T}}, d::Gumbel{S}) = Gumbel(T(d.μ), T(d.θ))\n\n#### Parameters\n\nlocation(d::Gumbel) = d.μ\nscale(d::Gumbel) = d.θ\nparams(d::Gumbel) = (d.μ, d.θ)\n@inline partype{T<:Real}(d::Gumbel{T}) = T\n\n\n#### Statistics\n\nmean(d::Gumbel) = d.μ + d.θ * γ\n\nmedian{T<:Real}(d::Gumbel{T}) = d.μ - d.θ * log(T(logtwo))\n\nmode(d::Gumbel) = d.μ\n\nvar{T<:Real}(d::Gumbel{T}) = T(π)^2/6 * d.θ^2\n\nskewness{T<:Real}(d::Gumbel{T}) = 112*sqrt(T(6))*zeta(T(3))/π/π/π\n\nkurtosis{T<:Real}(d::Gumbel{T}) = T(12)/5\n\nentropy(d::Gumbel) = log(d.θ) + 1 + γ\n\n\n#### Evaluation\n\nzval(d::Gumbel, x::Real) = (x - d.μ) / d.θ\nxval(d::Gumbel, z::Real) = x * d.θ + d.μ\n\nfunction pdf(d::Gumbel, x::Real)\n    z = zval(d, x)\n    exp(-z - exp(-z)) / d.θ\nend\n\nfunction logpdf(d::Gumbel, x::Real)\n    z = zval(d, x)\n    - (z + exp(-z) + log(d.θ))\nend\n\ncdf(d::Gumbel, x::Real) = exp(-exp(-zval(d, x)))\nlogcdf(d::Gumbel, x::Real) = -exp(-zval(d, x))\n\nquantile(d::Gumbel, p::Real) = d.μ - d.θ * log(-log(p))\n\ngradlogpdf(d::Gumbel, x::Real) = - (1 + exp((d.μ - x) / d.θ)) / d.θ\n\n\n#### Sampling\n\nrand(d::Gumbel) = quantile(d, rand())\n", "meta": {"hexsha": "3b2a073dbda46a7fadd5bf9d201a66496fa8df84", "size": 2440, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/gumbel.jl", "max_stars_repo_name": "JuliaPackageMirrors/Distributions.jl", "max_stars_repo_head_hexsha": "091cad865281c92746dc455cc50f4b2a311d3dd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/gumbel.jl", "max_issues_repo_name": "JuliaPackageMirrors/Distributions.jl", "max_issues_repo_head_hexsha": "091cad865281c92746dc455cc50f4b2a311d3dd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/gumbel.jl", "max_forks_repo_name": "JuliaPackageMirrors/Distributions.jl", "max_forks_repo_head_hexsha": "091cad865281c92746dc455cc50f4b2a311d3dd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4166666667, "max_line_length": 94, "alphanum_fraction": 0.587704918, "num_tokens": 1004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520764, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7849631002422863}}
{"text": "# function Mvx(vx_pml::SparseMatrixCSC{Float64,Int64}, rho::Array{Float64,2}, dx::Float64, dt::Float64, ext::Int64, iflag::Int64)\n#     rho = modExpand(rho, ext, iflag)\n#     (m,n) = size(rho)\n#     a1 = 9/8;   a2 = -1/24;\n#     c1 = a1/dx; c2 = a2/dx;\n#     C3 = zeros(m*n)\n#     denum = zeros(m*n)\n#     for ix = 1 : n\n#         for iz = 1 : m\n#             if ix < n\n#                a = (rho[iz,ix+1]+rho[iz,ix]) / (2*dt)\n#             else\n#                a = rho[iz,ix] / dt\n#             end\n#             b = vx_pml[iz,ix] / 2\n#             denum[(ix-1)*m+iz] = 1 / (a+b)\n#             C3[(ix-1)*m+iz]= (a-b) / (a+b)\n#         end\n#     end\n#     tmp = spzeros(n, n)\n#     tmp[1,1] = -c1; tmp[1,2] = c1; tmp[1,3] = c2;\n#     for ix = 2: n-2\n#         tmp[ix,ix  ] = -c1; tmp[ix, ix+1] = c1;\n#         tmp[ix,ix-1] = -c2; tmp[ix, ix+2] = c2;\n#     end\n#     tmp[n-1,n-1] = -c1; tmp[n-1, n  ] = c1; tmp[n-1,n-2] = -c2;\n#     tmp[n  ,n  ] = -c1; tmp[n  , n-1] =-c2;\n#     MvxBvx = spdiagm(C3)\n#     MvxBp = spdiagm(denum) * kron(tmp, speye(m))\n#     return MvxBvx, MvxBp\n# end\n\nfunction Mvx(vx_pml::SparseMatrixCSC{Float64,Int64}, dx::Float64, dt::Float64, ext::Int64, iflag::Int64)\n    (m,n) = size(vx_pml)\n    a1 = 9/8;   a2 = -1/24;\n    c1 = a1/dx; c2 = a2/dx;\n    C3 = zeros(m*n)\n    denum = zeros(m*n)\n    for ix = 1 : n\n        for iz = 1 : m\n            a = 1/dt + vx_pml[iz,ix]/2\n            b = 1/dt - vx_pml[iz,ix]/2\n            denum[(ix-1)*m+iz] = 1 / a\n            C3[(ix-1)*m+iz]= b / a\n        end\n    end\n    tmp = spzeros(n, n)\n    tmp[1,1] = -c1; tmp[1,2] = c1; tmp[1,3] = c2;\n    for ix = 2: n-2\n        tmp[ix,ix  ] = -c1; tmp[ix, ix+1] = c1;\n        tmp[ix,ix-1] = -c2; tmp[ix, ix+2] = c2;\n    end\n    tmp[n-1,n-1] = -c1; tmp[n-1, n  ] = c1; tmp[n-1,n-2] = -c2;\n    tmp[n  ,n  ] = -c1; tmp[n  , n-1] =-c2;\n    MvxBvx = spdiagm(C3)\n    MvxBp  = spdiagm(denum) * kron(tmp, speye(m))\n    return MvxBvx, MvxBp\nend\n\n\nfunction Mvx_back(vx_pml::SparseMatrixCSC{Float64,Int64}, dx::Float64, dt::Float64, ext::Int64, iflag::Int64)\n    (m,n) = size(vx_pml)\n    a1 = 9/8;   a2 = -1/24;\n    c1 = a1/dx; c2 = a2/dx;\n    C3 = zeros(m*n)\n    denum = zeros(m*n)\n    for ix = 1 : n\n        for iz = 1 : m\n            a = 1/dt - vx_pml[iz,ix]/2\n            b = 1/dt + vx_pml[iz,ix]/2\n            denum[(ix-1)*m+iz] = 1 / a\n            C3[(ix-1)*m+iz]= b / a\n        end\n    end\n    tmp = spzeros(n, n)\n    tmp[1,1] = -c1; tmp[1,2] = c1; tmp[1,3] = c2;\n    for ix = 2: n-2\n        tmp[ix,ix  ] = -c1; tmp[ix, ix+1] = c1;\n        tmp[ix,ix-1] = -c2; tmp[ix, ix+2] = c2;\n    end\n    tmp[n-1,n-1] = -c1; tmp[n-1, n  ] = c1; tmp[n-1,n-2] = -c2;\n    tmp[n  ,n  ] = -c1; tmp[n  , n-1] =-c2;\n    MvxBvx = spdiagm(C3)\n    MvxBp  = -spdiagm(denum) * kron(tmp, speye(m))\n    return MvxBvx, MvxBp\nend\n", "meta": {"hexsha": "82cada263b75e805e1b7284d188ffa95627c2802", "size": 2798, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FDMtx/Mvx.jl", "max_stars_repo_name": "WneleiGao/AcousticWaveLab", "max_stars_repo_head_hexsha": "133e605e13d30b6292b66bef19ec9a2357c58b0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FDMtx/Mvx.jl", "max_issues_repo_name": "WneleiGao/AcousticWaveLab", "max_issues_repo_head_hexsha": "133e605e13d30b6292b66bef19ec9a2357c58b0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FDMtx/Mvx.jl", "max_forks_repo_name": "WneleiGao/AcousticWaveLab", "max_forks_repo_head_hexsha": "133e605e13d30b6292b66bef19ec9a2357c58b0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1609195402, "max_line_length": 129, "alphanum_fraction": 0.4485346676, "num_tokens": 1318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474155747541, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7849007348054257}}
{"text": "#!/usr/bin/env julia\n\nfunction main()\n    accum = 0\n    fib_n  = 1\n    fib_nn = 2\n    fib_max = 4_000_000\n    while fib_n <= fib_max\n        if fib_n % 2 == 0\n            accum += fib_n\n        end\n        tmp = fib_n + fib_nn\n        fib_n = fib_nn\n        fib_nn = tmp\n    end\n    @printf(\"The sum of even Fibonacci numbers up to %d is %d\\n\",\n            fib_max, accum)\nend\n\nmain()\n", "meta": {"hexsha": "638254ff09cc6f458715c6d86c11514ea1b395ed", "size": 385, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problem_002.jl", "max_stars_repo_name": "bpr/Project_Euler", "max_stars_repo_head_hexsha": "afb13c6b07c608a0a39c634d6481db604320c015", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problem_002.jl", "max_issues_repo_name": "bpr/Project_Euler", "max_issues_repo_head_hexsha": "afb13c6b07c608a0a39c634d6481db604320c015", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem_002.jl", "max_forks_repo_name": "bpr/Project_Euler", "max_forks_repo_head_hexsha": "afb13c6b07c608a0a39c634d6481db604320c015", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.3333333333, "max_line_length": 65, "alphanum_fraction": 0.5168831169, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9572778036723354, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7848657002745791}}
{"text": "# implement QZ-40 algorithm\n# Dellnitz, M., Schütze, O., & Zheng, Q. (2002). Locating all the zeros of an analytic function in one complex variable. Journal of Computational and Applied Mathematics, 138(2), 325–333. https://doi.org/10.1016/S0377-0427(01)00371-5\n# currently assumes all roots have multiplicity one\n\nusing QuadGK\n\nfunction winding_number(dlogfdz::Function, rectangle::Array{Float64,1}, maxevals::Int = 10^4)::Int\n    (x_min, x_max, y_min, y_max) = rectangle\n    (bl, br, tr, tl) = (x_min + y_min*im, x_max + y_min*im, x_max + y_max*im, x_min + y_max*im)\n    round(Int,real(1 ./(2*pi*im)*quadgk(dlogfdz,bl,br,tr,tl,bl,rtol=0, atol=0.45*2*pi,maxevals=maxevals)[1]))\nend\n\nfunction qz40(dlogfdz::Function, rectangle::Array{Float64,1}, verbose::Bool=false, maxevals::Int=10^4)\n\n    rectangles = Array{Float64,1}[rectangle]\n    zeroes = Complex[]\n    wn = -1\n    qz40_recursive(dlogfdz,rectangles,zeroes,wn,verbose,maxevals)\nend\n\nfunction locate_root(dlogfdz::Function, rectangle::Array{Float64,1}, maxevals::Int = 10^4)\n    (x_min, x_max, y_min, y_max) = rectangle\n    (bl, br, tr, tl) = (x_min + y_min*im, x_max + y_min*im, x_max + y_max*im, x_min + y_max*im)\n    integrand(z::Complex) = z*dlogfdz(z)\n    location = 1 ./(2*pi*im)*quadgk(integrand,bl,br,tr,tl,bl,maxevals=maxevals)[1]\n    if (real(location) < x_min || real(location) > x_max || imag(location) < y_min || imag(location) > y_max)\n        error(\"Root location $(location) outside of rectangle (x_min, x_max, y_min, y_max) $(x_min),$(x_max),$(y_min),$(y_max).\")\n    end\n    return location\nend\n\nfunction random_subdivide(rectangle::Array{Float64,1})\n\n    (x_min, x_max, y_min, y_max) = rectangle\n    x_mid = x_min + rand()*(x_max - x_min)\n    y_mid = y_min + rand()*(y_max - y_min)\n    # rectangles = Array{Array{Float64,1},1}[]\n    rectangles = Array{Array{Float64,1},1}(undef,0)\n    push!(rectangles,[x_min, x_mid, y_min, y_mid]);\n    push!(rectangles,[x_mid, x_max, y_min, y_mid]);\n    push!(rectangles,[x_mid, x_max, y_mid, y_max]);\n    push!(rectangles,[x_min, x_mid, y_mid, y_max]);\n    return rectangles\nend\n\nfunction qz40_recursive(dlogfdz::Function, rectangles::Array{Array{Float64,1},1},zeroes::Vector{Complex},nroots::Int,verbose::Bool,maxevals::Int)\n    # the rows of rectangles are the delimiters (x_min, x_max, y_min, y_max) of the rectangles\n    new_rectangles = Array{Float64,1}[]\n    n_rectangles = size(rectangles)[1]\n    if (verbose)\n        println(\"Number of rectangles: $(n_rectangles)\")\n    end\n    nroots_new = length(zeroes)\n    for i in 1:n_rectangles\n        rect = rectangles[i]\n        wn = winding_number(dlogfdz,rect,maxevals)\n        nroots_new += wn\n        if (wn == 1)\n            push!(zeroes,locate_root(dlogfdz,rect,maxevals))\n        elseif (wn > 1)\n            append!(new_rectangles,random_subdivide(rect))\n        elseif (wn < 0)\n            error(\"Negative winding numbers\")\n        end\n    end\n    if (nroots > 0 && nroots_new != nroots)\n        error(\"Expected number of roots: $(nroots), new number of roots: $(nroots_new).\")\n    end\n    if (nroots == -1)\n        println(\"Number of roots: $(nroots_new)\")\n    end\n    if size(new_rectangles)[1] == 0\n        return zeroes\n    else\n        return qz40_recursive(dlogfdz, new_rectangles, zeroes, nroots_new, verbose,maxevals)\n    end\nend\n\nfunction newton(f, dfdz, z_init, n_iter)\n\n    z_current = z_init\n    for i in 1:n_iter\n        z_current = z_current - f(z_current)/dfdz(z_current)\n    end\n    z_current\nend\n", "meta": {"hexsha": "4d898732825b601f250791657b92cdefb581b4b7", "size": 3480, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "complex_roots.jl", "max_stars_repo_name": "jbierkens/spectral", "max_stars_repo_head_hexsha": "7ed39880c11ae3962e83f9aea9dafb5707e34a52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "complex_roots.jl", "max_issues_repo_name": "jbierkens/spectral", "max_issues_repo_head_hexsha": "7ed39880c11ae3962e83f9aea9dafb5707e34a52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "complex_roots.jl", "max_forks_repo_name": "jbierkens/spectral", "max_forks_repo_head_hexsha": "7ed39880c11ae3962e83f9aea9dafb5707e34a52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0, "max_line_length": 233, "alphanum_fraction": 0.6635057471, "num_tokens": 1132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778000158576, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7848656909573936}}
{"text": "export real_matrix, complex_matrix\n\n\"\"\"\n`real_matrix(x::SimpleQuaternion)` returns a 4-by-4 real matrix that represents\n`x`. \n\"\"\"\nfunction real_matrix(x::SimpleQuaternion)\n    a, b, c, d = get_parts(x)\n    M = [\n        a -b -c -d\n        b a -d c\n        c d a -b\n        d -c b a\n    ]\n    return M\nend\n\n\"\"\"\n`complex_matrix(x::SimpleQuaternion)` returns a 2-by-2 complex matrix \nthat represents `x`.\n\"\"\"\nfunction complex_matrix(x::SimpleQuaternion)\n    a, b, c, d = get_parts(x)\n    M = [\n         a+b*im     c+d*im\n        -c+d*im     a-b*im\n    ]\n    return M\nend\n\n\nfunction SimpleQuaternion(A::AbstractMatrix{T}) where T\n    r,c = size(A)\n    if r!=c || !in(r,[2,4])\n        error(\"Matrix must be 2-by-2 or 4-by-4; got $r-by-$c.\")\n    end\n\n    if r==4  \n        v = A[:,1]\n        x = SimpleQuaternion(v...)\n        if real_matrix(x) != A \n            error(\"Matrix not derived from a quaternion\")\n        end \n        return x\n    end \n\n    a,b = reim(A[1,1])\n    c,d = reim(A[1,2])\n    x = SimpleQuaternion(a,b,c,d)\n    if complex_matrix(x) != A \n        error(\"Matrix not derived from a quaternion\")\n    end\n    return x \nend \n\n\n\n\n\n\n\n", "meta": {"hexsha": "4a32cf0f9b38b43fc4e8ecc242eef62bda7ab821", "size": 1142, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrices.jl", "max_stars_repo_name": "scheinerman/SimpleQuaternions.jl", "max_stars_repo_head_hexsha": "ad494b7d866fc74c359177155bc58fa2c6b66f07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matrices.jl", "max_issues_repo_name": "scheinerman/SimpleQuaternions.jl", "max_issues_repo_head_hexsha": "ad494b7d866fc74c359177155bc58fa2c6b66f07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrices.jl", "max_forks_repo_name": "scheinerman/SimpleQuaternions.jl", "max_forks_repo_head_hexsha": "ad494b7d866fc74c359177155bc58fa2c6b66f07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-13T11:56:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T11:56:34.000Z", "avg_line_length": 18.4193548387, "max_line_length": 79, "alphanum_fraction": 0.5411558669, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777975782055, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7848656847459363}}
{"text": "abstract type AbstractTrajectory end\n\n\"\"\"\nBezier curve\nθ: a vector whose length is (N+1); each element can also be vector,\ne.g., θ = [[1, 2, 3], [2, 3, 4]]\n\"\"\"\nstruct Bezier <: AbstractTrajectory\n    θ::AbstractVector\n    t0::Real\n    tf::Real\nend\n\nfunction (bezier::Bezier)(t::Real)\n    @unpack t0, tf, θ = bezier\n    N = length(θ) -1\n    @assert t <= tf && t >= t0\n    s = (t-t0)/(tf-t0)\n    basis = 0:N |> Map(i -> binomial(N, i) * s^i * (1-s)^(N-i)) |> collect\n    basis .* θ |> sum  # sum of N_C_i * s^(N-i) * (1-s)^i * θ_i\nend\n", "meta": {"hexsha": "71abde7811dd9e0dabe87461865bdae6d3ac25ba", "size": 533, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/trajectory_generation.jl", "max_stars_repo_name": "JinraeKim/FaultTolerantControl.jl", "max_stars_repo_head_hexsha": "b229934de0436616d590a2c08b17ce1029c3ae5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-06-13T13:10:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T10:27:27.000Z", "max_issues_repo_path": "src/trajectory_generation.jl", "max_issues_repo_name": "JinraeKim/FaultTolerantControl.jl", "max_issues_repo_head_hexsha": "b229934de0436616d590a2c08b17ce1029c3ae5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2021-06-25T02:39:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T07:11:19.000Z", "max_forks_repo_path": "src/trajectory_generation.jl", "max_forks_repo_name": "JinraeKim/FaultTolerantControl.jl", "max_forks_repo_head_hexsha": "b229934de0436616d590a2c08b17ce1029c3ae5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-13T10:52:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T10:52:36.000Z", "avg_line_length": 24.2272727273, "max_line_length": 74, "alphanum_fraction": 0.5590994371, "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9683812309063186, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.7848525543358171}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.12\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\ttriangDist = TriangularDist(0,2,1)\n\txGrid = 0:0.1:2\n\t\tN = 10^6\n\tinverseSampledData = quantile.(triangDist,rand(N))\nend\n\n# ╔═╡ b690890a-2135-11eb-1abc-933c757a93f8\nbegin\n\thistogram( inverseSampledData, bins=30, normed=true,\n\t\tylims=(0,1.1), label=\"Inverse transform data\")\n\tplot!( xGrid, pdf.(triangDist,xGrid), c=:red, lw=4, \n\t\txlabel=\"x\", label=\"PDF\", ylabel = \"Density\", legend=:topright)\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.12\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═b690890a-2135-11eb-1abc-933c757a93f8\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "f17451d1e672e0bdcb7d49c934bb5c1ac8f6eae9", "size": 1170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.12.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.12.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.12.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.4347826087, "max_line_length": 64, "alphanum_fraction": 0.7307692308, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.8688267847293731, "lm_q1q2_score": 0.784806199013344}}
{"text": "\"\"\"\n    ndgrid(x,y,...)\n\nFor d vector inputs, return d matrices representing the coordinate functions on the\ntensor product grid.\n\"\"\"\nfunction ndgrid(x...)\n    I = CartesianIndices( fill(undef,length.(x)) )\n    [ [ x[d][i[d]] for i in I]  for d = 1:length(x) ]\nend\n\n\"\"\"\n    rectdisc(m,xspan,n,yspan)\n\nCreate matrices and helpers for finite-difference discretization of a rectangle that is\nthe tensor  product of intervals `xspan` and `yspan`, using `m`+1 and `n`+1 points in\nthe two coordinates.\n\"\"\"\nfunction rectdisc(m,xspan,n,yspan)\n    # Initialize grid and finite differences.\n    x,Dx,Dxx = diffmat2(m,xspan)\n    y,Dy,Dyy = diffmat2(n,yspan)\n    X = repeat(x,outer=(1,n+1))\n    Y = repeat(y',outer=(m+1,1))\n\n    # Locate boundary points.\n    isbndy = fill(true,m+1,n+1)\n    isbndy[2:m,2:n] .= false\n\n    # Get the diff. matrices recognized as sparse. Also include reshaping functions.\n    disc = (\n        Dx=sparse(Dx), Dxx=sparse(Dxx),\n        Dy=sparse(Dy), Dyy=sparse(Dyy),\n        Ix=Diagonal(ones(m+1)), Iy=Diagonal(ones(n+1)),\n        isbndy=isbndy,\n        vec=vec,\n        unvec=u -> reshape(u,m+1,n+1)\n        )\n    return X,Y,disc\nend\n\n\"\"\"\n    poissonfd(f,g,m,xspan,n,yspan)\n\nSolve Poisson's equation on a rectangle by finite differences. Function `f` is the\nforcing function and function `g` gives the  Dirichlet boundary condition. The rectangle\nis the tensor product of intervals `xspan` and `yspan`,  and the discretization uses\n`m`+1 and `n`+1 points in the two coordinates.\n\nReturn matrices of the solution values, and the coordinate functions, on the grid.\n\"\"\"\nfunction poissonfd(f,g,m,xspan,n,yspan)\n    # Initialize the rectangle discretization.\n    X,Y,d = rectdisc(m,xspan,n,yspan)\n\n    # Form the collocated PDE as a linear system.\n    A = kron(d.Iy,d.Dxx) + kron(d.Dyy,d.Ix)  # Laplacian matrix\n    b = d.vec(f.(X,Y))\n\n    # Replace collocation equations on the boundary.\n    scale = maximum(abs.(A[n+2,:]))\n    I = kron(d.Iy,d.Ix)\n    A[d.isbndy[:],:] = scale*I[d.isbndy[:],:]                 # Dirichet assignment\n    b[d.isbndy[:]] = scale*g.( X[d.isbndy],Y[d.isbndy] )  # assigned values\n\n    # Solve the linear sytem and reshape the output.\n    u = A\\b\n    U = d.unvec(u)\n    return U,X,Y\nend\n\n\"\"\"\n    newtonpde(f,g,m,xspan,n,yspan)\n\nNewton's method with finite differences to solve the PDE `f`(u,x,y,disc)=0 on the\nrectangle `xspan` ``\\times`` `yspan`, subject to `g`(x,y)=0 on the boundary. Use `m`+1\npoints in x by `n`+1 points in y.\n\nReturn matrices of the solution values, and the coordinate functions, on the grid.\n\"\"\"\n\nfunction newtonpde(f,g,m,xspan,n,yspan)\n    # Discretization.\n    X,Y,d = rectdisc(n,xspan,n,yspan)\n\n    # This evaluates the discretized PDE and its Jacobian, with all the\n    # boundary condition modifications applied.\n    function residual(U)\n        R,J = f(U,X,Y,d)\n        Ixy = Diagonal(ones(size(J,1)))   # used for row replacements\n        scale = maximum(abs.(J))\n        J[vec(d.isbndy),:] = scale*Ixy[d.isbndy[:],:]\n        XB = X[d.isbndy];  YB = Y[d.isbndy];\n        @. R[d.isbndy] = scale*(U[d.isbndy] - g(XB,YB))\n        r = d.vec(R)\n        return r,J\n    end\n\n    # Intialize the Newton iteration.\n    U = zeros(size(X))\n    r,J = residual(U)\n    tol = 1e-10;  itermax = 20;\n    s = Inf;  normr = norm(r);  k = 1;\n\n    lambda = 1\n    while (norm(s) > tol) && (normr > tol)\n        s = -(J'*J + lambda*I) \\ Vector(J'*r)  # damped step\n        Unew = U + d.unvec(s)\n        rnew,Jnew = residual(Unew)\n\n        if norm(rnew) < normr\n            # Accept and update.\n            lambda = lambda/6;   # dampen the Newton step less\n            U = Unew;  r = rnew;  J = Jnew;\n            normr = norm(r)\n            k = k+1\n            println(\"Norm of residual = $normr\")\n        else\n            # Reject.\n            lambda = lambda*4;   # dampen the Newton step more\n        end\n\n        if k==itermax\n            @warn \"Maximum number of Newton iterations reached.\"\n            break\n        end\n    end\n    return U,X,Y\nend\n", "meta": {"hexsha": "de49033ed52066daef7a2ae52896733127721318", "size": 4002, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/functions/chapter13.jl", "max_stars_repo_name": "snowdj/fnc-extras", "max_stars_repo_head_hexsha": "ef51fada748de1326a4ce645fbcb0c2499cb2b8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 109, "max_stars_repo_stars_event_min_datetime": "2018-04-21T09:02:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T19:03:54.000Z", "max_issues_repo_path": "julia/functions/chapter13.jl", "max_issues_repo_name": "snowdj/fnc-extras", "max_issues_repo_head_hexsha": "ef51fada748de1326a4ce645fbcb0c2499cb2b8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-12-04T22:17:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T21:04:47.000Z", "max_forks_repo_path": "julia/functions/chapter13.jl", "max_forks_repo_name": "snowdj/fnc-extras", "max_forks_repo_head_hexsha": "ef51fada748de1326a4ce645fbcb0c2499cb2b8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2017-04-02T17:21:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T17:19:57.000Z", "avg_line_length": 30.7846153846, "max_line_length": 88, "alphanum_fraction": 0.6014492754, "num_tokens": 1236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8688267847293731, "lm_q1q2_score": 0.7848061967514876}}
{"text": "# Tools for initial digits stuff\n\nchar2digit(c::Char) = c - '0'\n\nfunction first_digit(x::Real, alert::Bool = false)\n    if x == 0\n        if alert\n            warn(\"Received 0, returning 0\")\n        end\n        return 0\n    end\n\n    x = abs(x) # make sure it's positive\n\n    while x < 1\n        x *= 10\n    end\n\n    c = first(string(x))\n    return char2digit(c)\nend\n\nfunction first_counts(x::Array{T,1}) where {T<:Real}\n    digs = map(first_digit, x)\n    n = length(digs)\n    counts = zeros(Int, 9)\n    for d in digs\n        if d != 0\n            counts[d] += 1\n        end\n    end\n    return counts\nend\n\nfunction first_hists(x::Array{T,1}) where {T<:Real}\n    counts = first_counts(x)\n    hist = zeros(9)\n    S = sum(counts)\n    for k = 1:9\n        hist[k] = counts[k] / S\n    end\n    return counts, hist\nend\n\nfunction report(x::Array{T,1}) where {T<:Real}\n    counts, hist = first_hists(x)\n    for k = 1:9\n        println(\n            k,\n            \"\\t\",\n            counts[k],\n            \"\\t\",\n            round(hist[k] * 100, digits = 1),\n            \"%\\t\",\n            log(10, k + 1) - log(10, k),\n        )\n    end\nend\n\nfunction report_array(x::Array{T,1}) where {T<:Real}\n    counts, hist = first_hists(x)\n    A = Array(Any, (9, 3))\n    for k = 1:9\n        A[k, 1] = k\n        A[k, 2] = counts[k]\n        A[k, 3] = round(hist[k] * 100, digits = 2)\n    end\n    return A\nend\n\n\nfunction experiment()\n    n = 1000\n    x = rand(n)\n    println(\"Initial distribution\")\n    report(x)\n    println(\"\\n\\n\")\n    sleep(1)\n\n    count = 0\n    while count <= 1000\n        m = minimum(x)\n        count += 1\n        if m < 1\n            x *= 100.0\n        end\n        x = x .* rand(n)\n        if count % 25 == 0\n            println(\"step = \", count)\n            report(x)\n            println(\"-------------------------------\")\n            sleep(0.1)\n        end\n    end\nend\n\nfunction digit_split(n::Int)\n    map(char2digit, collect(string(n)))\nend\n\n# create a 9^d multiplication table\nfunction mult_table_old(d::Int)\n    vals = Int[]\n    for n = 10^(d-1):10^d-1\n        digs = digit_split(n)\n        v = prod(digs)\n        # println(digs, \" --> \", v)\n        if v != 0\n            push!(vals, v)\n        end\n    end\n    return vals\nend\n\nfunction mult_table(d::Int)\n    tic()\n    counts = zeros(Int, 9)\n    for n = 10^(d-1):10^d-1\n        digs = digit_split(n)\n        v = prod(digs)\n        if v != 0\n            d = first_digit(v)\n            counts[d] += 1\n        end\n    end\n    toc()\n    return counts\nend\n\nmult_report_old(d::Int) = report(mult_table(d))\n\nfunction mult_report(d::Int)\n    counts = mult_table(d)\n    N = sum(counts)\n\n    A = Array(Any, (9, 3))\n    for k = 1:9\n        A[k, 1] = k\n        A[k, 2] = counts[k]\n        A[k, 3] = round(100 * counts[k] / N, 2)\n    end\n    return A\nend\n", "meta": {"hexsha": "22a6db6a5a698c0edd79b6a8a080fc840a75bd23", "size": 2793, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Benford.jl", "max_stars_repo_name": "scheinerman/Misc.jl", "max_stars_repo_head_hexsha": "2cccc9bf616188c2b1258bdae71123a0d1b37418", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-12T17:02:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T12:31:19.000Z", "max_issues_repo_path": "src/Benford.jl", "max_issues_repo_name": "scheinerman/Misc.jl", "max_issues_repo_head_hexsha": "2cccc9bf616188c2b1258bdae71123a0d1b37418", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Benford.jl", "max_forks_repo_name": "scheinerman/Misc.jl", "max_forks_repo_head_hexsha": "2cccc9bf616188c2b1258bdae71123a0d1b37418", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3958333333, "max_line_length": 54, "alphanum_fraction": 0.4808449696, "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.8688267728417087, "lm_q1q2_score": 0.7848061882752857}}
{"text": "# Probability computations\n\n\n\"\"\"\n\t$(SIGNATURES)\n\nValidate a probability matrix. Elements are expected to sum to 1.\n\"\"\"\nfunction validate_prob_matrix(probM :: AbstractMatrix{T1}) where T1 <: AbstractFloat\n    isValid = all_at_least(probM, 0.0)  &&  all_at_most(probM, 1.0);\n    isValid = isValid  &&  isapprox(sum(probM), 1.0);\n    return isValid\nend\n\n\n\"\"\"\n\t$(SIGNATURES)\n\nValidate a probability vector. Elements are expected to sum to 1.\n\"\"\"\nvalidate_prob_vector(probV :: AbstractVector{T1}) where T1 <: AbstractFloat = \n    validate_prob_matrix(probV');\n\n\n\"\"\"\n\t$(SIGNATURES)\n\nConditional probabilities of rows or columns given a probability matrix.\n\"\"\"\nprob_j(m :: AbstractMatrix{T1}) where T1 <: AbstractFloat = vec(sum(m, dims = 2));\nprob_j(m :: AbstractMatrix{T1}, j :: Integer) where T1 <: AbstractFloat = \n    sum(m[j,:]);\nprob_j(m :: AbstractMatrix{T1}, j) where T1 <: AbstractFloat = \n    sum(m[j, :], dims = 2);\n\n\"\"\"\n\t$(SIGNATURES)\n\nConditional probabilities of rows or columns given a probability matrix.\n\"\"\"\nprob_k(m :: AbstractMatrix{T1}) where T1 <: AbstractFloat = vec(sum(m, dims = 1));\nprob_k(m :: AbstractMatrix{T1}, k :: Integer) where T1 <: AbstractFloat = \n    sum(m[:, k]);\nprob_k(m :: AbstractMatrix{T1}, k) where T1 <: AbstractFloat = \n    vec(sum(m[:, k], dims = 1));\n\n\n\"\"\"\n    $(SIGNATURES)\n\nConditional probability (j | k).\n\"\"\"\nprob_j_k(m :: AbstractMatrix, j, k :: Integer) = \n    m[j, k] ./ prob_k(m, k);\n\n\"\"\"\n    $(SIGNATURES)\n\nConditional probability (k | j).\n\"\"\"\nprob_k_j(m :: AbstractMatrix, k, j :: Integer) =\n    m[j, k] ./ prob_j(m, j);\n\n    \n## -----------  Expected values\n\n\"\"\"\n\t$(SIGNATURES)\n\nCompute expected value of `x`, given row index `j`. Based on matrix of values `xM[j,k]` and matrix of probabilities (sum to 1) `prM[j, k]`.\n\"\"\"\nev_given_j(x :: AbstractMatrix, prM :: AbstractMatrix, j :: Integer) = \n    sum([(prob_k_j(prM, k, j) * x[j, k])  for k = 1 : size(x, 2) ]);\nev_given_j(x :: AbstractMatrix, prM :: AbstractMatrix) = \n    [ev_given_j(x, prM, j)  for j = 1 : size(x, 1)];\n\n\n\"\"\"\n\t$(SIGNATURES)\n\nCompute expected value of `x`, given column index `k`. Based on matrix of values `xM[j,k]` and matrix of probabilities (sum to 1) `prM[j, k]`.\n\"\"\"\nev_given_k(x :: AbstractMatrix, prM :: AbstractMatrix, k :: Integer) = \n    sum([(prob_j_k(prM, j, k) * x[j, k])  for j = 1 : size(x, 1) ]);\nev_given_k(x :: AbstractMatrix, prM :: AbstractMatrix) = \n    [ev_given_k(x, prM, k)  for k = 1 : size(x, 2)];\n\n\n    \"\"\"\n    $(SIGNATURES)\n\nGiven an array of probabilities: ensure that all are in [0, 1]. \nError if bounds violation larger than rounding errors.\nMake sure that sum does not exceed an upper bound.\n\"\"\"\nfunction scale_prob_array!(m :: AbstractArray{F1}; maxSum :: F1 = one(F1)) where F1 <: AbstractFloat\n\n    fSmall = F1(.0000001);\n    pSum = sum(m);\n    @assert (pSum < one(F1) + fSmall)  \"Sum too large: $pSum\"\n    @assert all_at_least(m, -fSmall)  \"Negative probabilities\"\n    @assert all_at_most(m, one(F1) + fSmall)  \"Probabilities above 1\"\n\n    if any(x -> x < zero(F1), m)\n        m[findall(x -> x < zero(F1), m)] .= zero(F1);\n    end\n    if pSum > maxSum\n        m .*= ((maxSum - fSmall) / pSum);\n    end\nend\n\n\n# ---------", "meta": {"hexsha": "4c4b67ef41f903f269d08718c853c13e232b0ddc", "size": 3179, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/probabilities.jl", "max_stars_repo_name": "hendri54/CommonLH", "max_stars_repo_head_hexsha": "aba46201434da0c3fec6476b66de750eb1f7e493", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/probabilities.jl", "max_issues_repo_name": "hendri54/CommonLH", "max_issues_repo_head_hexsha": "aba46201434da0c3fec6476b66de750eb1f7e493", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/probabilities.jl", "max_forks_repo_name": "hendri54/CommonLH", "max_forks_repo_head_hexsha": "aba46201434da0c3fec6476b66de750eb1f7e493", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1327433628, "max_line_length": 142, "alphanum_fraction": 0.6284995282, "num_tokens": 961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8688267643505193, "lm_q1q2_score": 0.7848061828670999}}
{"text": "## GeomUtils.jl --- constructs for geometry\n\nexport distance, anglespan, dihedral\nexport centroid, RMSD\n\n\"\"\"\n    distance(a, b) -> Real\n\nCalculate Euclidean distance from `a` to `b`.\n\"\"\"\ndistance(a, b) = norm(a-b)\n\n\"\"\"\n    anglespan(a, b, c) ∈ [0, π]\n\nCalculate smaller angle between two vectors ``AB`` and ``BC`` meeting at ``B``.\n\"\"\"\nfunction anglespan(a, b, c)\n    Δ1 = a - b; n1 = norm(Δ1)\n    Δ2 = c - b; n2 = norm(Δ2)\n    (n1 == 0 || n2 == 0) && error(\"two positions overlap\")\n    cos_ = Δ1⋅Δ2 / norm(Δ1) / norm(Δ2)\n    cos_ >= 1 && return 0        ## handle \"overflow?\" cases where cos_ ∉ [-1,1]\n    cos_ <= -1 && return π\n    acos(cos_)\nend\n\n\"\"\"\n    dihedral(a, b, c, d) ∈ [-π, π]\n\nCalculate right handed dihedral (torsion) angle between the plane ``ABC`` and\n``BCD`` intersecting along ``BC``. ``ABC`` is determined by the first three\narguments as points, while ``BCD`` is determined by the last three.\n\"\"\"\nfunction dihedral(a, b, c, d)\n    Δ1 = a - b\n    Δ2 = b - c; n2 = norm(Δ2)\n    Δ3 = d - c\n    n2 == 0 && error(\"torque axis is undefined; `b`, `c` overlap\")\n\n    Δ23 = Δ2×Δ3\n    Δ21 = Δ2×Δ1\n    (norm(Δ23) == 0 || norm(Δ21) == 0) && error(\"some points overlap/colinear\")\n    \n    atan(Δ23⋅(Δ21×Δ2) / n2, Δ23⋅Δ21)\nend\n\n\"\"\"\n    centroid(collection) -> eltype(collection)\n\nGet the centroid of a collection of points. The preferred point representation\nis a subtype of `StaticVector`. This centroid is an _unweighted_ average of\npositions.\n\"\"\"\nfunction centroid(collection::Vector{StaticVector})\n    sm_ = sum(collection)\n    sm_ / length(collection)\nend\n\n\"\"\"\n    centered(collection) -> centered positions\n\nGet a copy of the centered positions in collection. The preferred point\nrepresentation is a subtype of `StaticVector`.\n\nEquivalent to `collection .- centroid(collection)`.\n\"\"\"\ncentered(collection) = collection .- centroid(collection)\n\n\"\"\"\n    RMSD(cA, cB) -> Real\n\nCalculate root-mean-square deviation of points in `cA` from those in `cB`.\nPreferred point representation is a subtype of `StaticVector`.\n\"\"\"\nfunction RMSD(cA::Vector{M}, cB::Vector{M}) where M <: StaticVector\n    len = length(cA)\n    @assert length(cB) == len \"arguments don't have the same length\"\n    msd = sum(cA, cB; init=zero(eltype(M))) do (a, b)\n        distance(a, b)\n    end / len\n\n    sqrt(msd)\nend\n\n", "meta": {"hexsha": "b9239d18d4c5d5b8d73e21c6af3bb55e7adc0613", "size": 2295, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GeomUtils.jl", "max_stars_repo_name": "bldamalla/ProtStructs.jl", "max_stars_repo_head_hexsha": "98f73e61d123b8f319c597368f00b4b83a416d62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GeomUtils.jl", "max_issues_repo_name": "bldamalla/ProtStructs.jl", "max_issues_repo_head_hexsha": "98f73e61d123b8f319c597368f00b4b83a416d62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-27T10:43:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T10:43:37.000Z", "max_forks_repo_path": "src/GeomUtils.jl", "max_forks_repo_name": "bldamalla/ProtStructs.jl", "max_forks_repo_head_hexsha": "98f73e61d123b8f319c597368f00b4b83a416d62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6860465116, "max_line_length": 80, "alphanum_fraction": 0.6379084967, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731105140615, "lm_q2_score": 0.8152324871074607, "lm_q1q2_score": 0.7848023941558536}}
{"text": "using Base: IEEEFloat\n\n#=\n\n  - error-free transformations (`two_sum`, `two_diff`, `two_square`, `two_prod`,\n                                `two_hilo_sum`, `two_lohi_sum`, `two_hilo_diff`, `two_lohi_diff`)\n  - least-error transformations (`two_sqrt`, `two_inv`, `two_div`)\n\n nomenclature: \n - `two_<op>`: the \"two\" refers to the number of values returned\n    two and three argument versions of `two_[sum,diff,prod]` are given\n - `two_hilo_<op>` the argments are ordered by non-increasing absolute value\n    - this is `fast_two_sum` in the literature\n - `two_lohi_<op>` the argments are ordered by non-decreasing absolute value\n    - this is not available in the literature\n\n=#\n\n\"\"\"\n    two_sum(a, b)\n    \nComputes `hi = fl(a+b)` and `lo = err(a+b)`.\n- Unchecked Precondition: !(isinf(a) | isinf(b))\n\"\"\"\n@inline function two_sum(a::T, b::T) where {T}\n    hi = a + b\n    v  = hi - a\n    lo = (a - (hi - v)) + (b - v)\n    return hi, lo\nend\n\n\"\"\"\n   two_sum(a, b, c)\n    \nComputes `hi = fl(a+b+c)` and `lo = err(a+b+c)`.\n- Unchecked Precondition: !(isinf(a) | isinf(b) | isinf(c))\n\"\"\"\nfunction two_sum(a::T, b::T, c::T) where {T}\n    a, b, c = magnitude_mintomax(a, b, c)\n    md, lo = two_sum(b, c) \n    hi, md = two_sum(a, md)\n    hi, lo = two_hilo_sum(hi, md+lo)\n    return hi, lo\nend\n\n\"\"\"\n    two_diff(a, b)\n\nComputes `s = fl(a-b)` and `e = err(a-b)`.\n- Unchecked Precondition: !(isinf(a) | isinf(b))\n\"\"\"\n@inline function two_diff(a::T, b::T) where {T}\n    hi = a - b\n    v  = hi - a\n    lo = (a - (hi - v)) - (b + v)\n    return hi, lo\nend\n\n\"\"\"\n    two_diff(a, b, c)\n    \nComputes `s = fl(a-b-c)` and `e1 = err(a-b-c), e2 = err(e1)`.\n- Unchecked Precondition: !(isinf(a) | isinf(b) | isinf(c))\n\"\"\"\nfunction two_diff(a::T,b::T,c::T) where {T}\n    a, b, c = magnitude_maxtomin(a, b, c)\n    s, t = two_diff(-b, c)\n    hi, u = two_sum(a, s)\n    hi, lo = two_hilo_sum(hi, u+t)\n    return hi, lo\nend\n\n\n\"\"\"\n    two_hilo_sum(a, b)\n\n*unchecked* requirement `|a| ≥ |b|`\nComputes `hi = fl(a+b)` and `lo = err(a+b)`.\n- Unchecked Precondition: !(isinf(a) | isinf(b))\n\"\"\"\n@inline function two_hilo_sum(a::T, b::T) where {T}\n    hi = a + b\n    lo = b - (hi - a)\n    return hi, lo\nend\n\n\"\"\"\n    two_lohi_sum(a, b)\n\n*unchecked* requirement `|b| ≥ |a|`\nComputes `hi = fl(a+b)` and `lo = err(a+b)`.\n- Unchecked Precondition: !(isinf(a) | isinf(b))\n\"\"\"\n@inline function two_lohi_sum(a::T, b::T) where {T}\n    hi = b + a\n    lo = a - (hi - b)\n    return hi, lo\nend\n\n\"\"\"\n    two_hilo_diff(a, b)\n    \n*unchecked* requirement `|a| ≥ |b|`\nComputes `hi = fl(a-b)` and `lo = err(a-b)`.\n- Unchecked Precondition: !(isinf(a) | isinf(b))\n\"\"\"\n@inline function two_hilo_diff(a::T, b::T) where {T}\n    hi = a - b\n    lo = (a - hi) - b\n    hi, lo\nend\n\n\"\"\"\n    two_lohi_diff(a, b)\n    \n*unchecked* requirement `|b| ≥ |a|`\nComputes `hi = fl(a-b)` and `lo = err(a-b)`.\n- Unchecked Precondition: !(isinf(a) | isinf(b))\n\"\"\"\n@inline function two_lohi_diff(a::T, b::T) where {T}\n    hi = b - a\n    lo = (b - hi) - a\n    hi, lo\nend\n\n\"\"\"\n    two_square(a)\n\nComputes `hi = fl(a*a)` and `lo = fl(err(a*a))`.\n- Unchecked Precondition: !(isinf(a))\n\"\"\"\n@inline function two_square(a::T) where {T}\n    hi = a * a\n    lo = fma(a, a, -hi)\n    hi, lo\nend\n\n\"\"\"\n    two_prod(a, b)\n\nComputes `hi = fl(a*b)` and `lo = fl(err(a*b))`.\n- Unchecked Precondition: !(isinf(a) | isinf(b))\n\"\"\"\n@inline function two_prod(a::T, b::T) where {T}\n    hi = a * b\n    lo = fma(a, b, -hi)\n    hi, lo\nend\n\n\"\"\"\n    two_prod(a, b, c)\n    \nComputes `hi = fl(a*b*c)` and `lo = err(a*b*c)`.\n- Unchecked Precondition: !(isinf(a) | isinf(b) | isinf(c))\n\"\"\"\nfunction two_prod(a::T, b::T, c::T) where {T}\n    abhi, ablo = two_prod(a, b)\n    hi, abhiclo = two_prod(abhi, c)\n    ablochi, abloclo = two_prod(ablo, c)\n    lo = ablochi + (abhiclo + abloclo)\n    return hi, lo\nend\n\n\"\"\"\n    two_inv(a)\n    \nComputes `hi = fl(inv(a))` and `lo = err(inv(a))`.\n- Unchecked Precondition: !(isinf(a))\n\"\"\"\n@inline function two_inv(a::T) where {T}\n     hi = inv(a)\n     lo = fma(-hi, a, one(T))\n     lo /= a\n     return hi, lo\nend\n\n\"\"\"\n    two_div(a, b)\n    \nComputes `hi = fl(a/b)` and `lo = err(a/b)`.\n- Unchecked Precondition: !(isinf(a) | isinf(b))\n\"\"\"\n@inline function two_div(a::T, b::T) where {T}\n     hi = a / b\n     lo = fma(-hi, b, a)\n     lo /= b\n     return hi, lo\nend\n\n\"\"\"\n    two_sqrt(a)\n    \nComputes `hi = fl(sqrt(a))` and `lo = err(sqrt(a))`.\n- Unchecked Precondition: !(isinf(a))\n\"\"\"\n@inline function two_sqrt(a::T) where {T}\n    hi = sqrt(a)\n    lo = fma(-hi, hi, a)\n    lo /= 2\n    lo /= hi\n    return hi, lo\nend\n\n\n\nBase.:(+)(xhi::T, xlo::T, y::T) where {T<:IEEEFloat} = two_sum(xhi, y, xlo)\nBase.:(-)(xhi::T, xlo::T, y::T) where {T<:IEEEFloat} = two_sum(xhi, xlo, -y)\n\nBase.:(+)(x::Tuple{T,T}, y::T) where {T<:IEEEFloat} = (+)(x[1], x[2], y)\nBase.:(-)(x::Tuple{T,T}, y::T) where {T<:IEEEFloat} = (+)(x[1], x[2], y)\n\n# Algorithm 12 from Tight and rigourous error bounds.  relative error <= 5u²\nfunction Base.:(*)(xhi::T, xlo::T, y::T) where {T<:IEEEFloat}\n    hi, lo = two_prod(xhi, y)\n    t = fma(xlo, y, lo)\n    hi, lo = two_hilo_sum(hi, t)\n    return hi, lo\nend\n\nfunction Base.:(/)(xhi::T, xlo::T, y::T) where {T<:IEEEFloat}\n    hi = xhi / y\n    uh, ul = two_prod(hi, y)\n    lo = ((((xhi - uh) - ul) + xlo))/y\n    hi,lo = two_hilo_sum(hi, lo)\n    return hi, lo\nend\n\nBase.:(*)(x::Tuple{T,T}, y::T) where {T<:IEEEFloat} = (*)(x[1], x[2], y)\nBase.:(/)(x::Tuple{T,T}, y::T) where {T<:IEEEFloat} = (/)(x[1], x[2], y)\n\n# exchange sort for magnitudes, 2 or 3 values\n\n@inline magnitude_minmax(a, b) = abs(a) < abs(b) ? (a, b) : (b, a)\n\n@inline function magnitude_mintomax(a, b, c)\n    b, c = magnitude_minmax(b, c)\n    a, c = magnitude_minmax(a, c)\n    a, b = magnitude_minmax(a, b)\n    return a, b, c\nend\n", "meta": {"hexsha": "80655311cee0a76a7a766699aea849fcfa4b3d30", "size": 5722, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/accurate_pairs.jl", "max_stars_repo_name": "JeffreySarnoff/Double64s.jl", "max_stars_repo_head_hexsha": "e3f3067749a2e3ea782ae8e944bac27eea722063", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/accurate_pairs.jl", "max_issues_repo_name": "JeffreySarnoff/Double64s.jl", "max_issues_repo_head_hexsha": "e3f3067749a2e3ea782ae8e944bac27eea722063", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/accurate_pairs.jl", "max_forks_repo_name": "JeffreySarnoff/Double64s.jl", "max_forks_repo_head_hexsha": "e3f3067749a2e3ea782ae8e944bac27eea722063", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7427385892, "max_line_length": 97, "alphanum_fraction": 0.5566235582, "num_tokens": 2137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632329799585, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.784774998815192}}
{"text": "using PyPlot, SparseArrays\nrows = [2,3,4,4,5,5,5,6,6,7,7,8,8,9,9,10,11]\ncols = [3,2,1,2,2,4,6,2,5,2,5,2,5,2,5,5,5]\nA = sparse(rows, cols, 1, 11, 11)\nA[sum(A,dims=2)[:] .== 0,:] .= 1  # If a vertex has no outbound edges, all edges to all other vertices\nspy(A, marker=\".\");\n\nfunction pagerank(A, d=0.85, tol=1e-6)\n    N = size(A,2)\n    L = sum(A, dims=2)\n    M = (A ./ L)'\n    R = ones(N) / N\n    while true\n        newR = d * (M * R) .+ (1 - d) / N\n        if maximum(abs.(newR - R)) < tol\n            return newR\n        end\n        R = newR\n    end\nend\n\nR = pagerank(A, 0.85)\nround.(100R, digits=1) # Show percentages\n", "meta": {"hexsha": "8462a28515efac24de996a8139bf60160b074d0a", "size": 619, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Sparse_Matrices/Application_Google_Page_Rank.jl", "max_stars_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_stars_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "textbook/_build/jupyter_execute/content/Sparse_Matrices/Application_Google_Page_Rank.jl", "max_issues_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_issues_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "textbook/_build/jupyter_execute/content/Sparse_Matrices/Application_Google_Page_Rank.jl", "max_forks_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_forks_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7916666667, "max_line_length": 102, "alphanum_fraction": 0.52180937, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7847749935838587}}
{"text": "export substellarlatitude, hourangle\nexport diurnalfluxfactor, diurnalfluxfactors\nexport annualfluxfactor, annualfluxfactors\n\n\"\"\"\n    substellarlatitude(f, γ)\n\nCompute the latitude of the substellar point for a given solar longitude `f` (true anomaly) and obliquity `γ`\n\"\"\"\nsubstellarlatitude(f, γ) = asin(cos(f)*sin(γ))\n\n\"\"\"\n    hourangle(θ, θₛ)\n\nCompute the [hour angle](https://en.wikipedia.org/wiki/Hour_angle)\n\"\"\"\nfunction hourangle(θ, θₛ)\n    x = -sin(θ)*sin(θₛ)/(cos(θ)*cos(θₛ))\n    if x <= -1\n        return π\n    elseif x >= 1\n        return 0.0\n    end\n    return acos(x)\nend\n\n#θ - latitude\n#θₛ - substellar latitude\n\"\"\"\n    diurnalfluxfactor(θ, θₛ)\n\nCompute the diurnally averaged fraction of incoming stellar flux received by a point at latitude `θ` when the substellar latitude is `θₛ`\n\"\"\"\nfunction diurnalfluxfactor(θ, θₛ)\n    h = hourangle(θ, θₛ)\n    return (sin(h)*cos(θ)*cos(θₛ) + h*sin(θ)*sin(θₛ))/π\nend\n\n#θ - latitude\n#f - solar longitude\n#γ - obliquity\n\"\"\"\n    diurnalfluxfactor(θ, f, γ)\n\nCompute the diurnally averaged fraction of incoming stellar flux received by a point at latitude `θ` when the planet is at solar longitude (true anomaly) `f`, with obliquity `γ`\n\"\"\"\ndiurnalfluxfactor(θ, f, γ) = diurnalfluxfactor(θ, substellarlatitude(f, γ))\n\n\"\"\"\n    diurnalfluxfactor(t, a, m, e, θ, γ, p)\n\nCompute the diurnally averaged fraction of incoming stellar flux received by a point at latitude `θ` for a general elliptical orbit\n\"\"\"\nfunction diurnalfluxfactor(t, a, m, e, θ, γ, p)\n    f = trueanomaly(t, a, m, e)\n    r = orbitaldistance(a, f, e)\n    return diurnalfluxfactor(θ, f - p, γ)*(a/r)^2\nend\n\n\"\"\"\n    diurnalfluxfactors(γ; nf=251, nθ=181)\n\nCompute a grid of diurnally averaged fractions of incoming stellar flux received by a point at latitude `θ` for a planet with obliquity `γ` in a circular orbit. Returns  a solar longitude vector (column values), latitude vector (row values), and the grid of flux factors. `nf` indicates the number of points around the orbit and `nθ` indicates the number of latitudes.\n\"\"\"\nfunction diurnalfluxfactors(γ; nf::Int=251, nθ::Int=181)\n    θ = LinRange(-π/2, π/2, nθ)\n    f = LinRange(0, 2π, nf)\n    F, Θ = meshgrid(f, θ)\n    return (f, θ, diurnalfluxfactor.(Θ, F, γ))\nend\n\n\"\"\"\n    diurnalfluxfactors(a, m, e, γ, p; nt=251, nθ=181)\n\nCompute a grid of diurnally averaged fractions of incoming stellar flux for a planet in a general elliptical orbit. Returns a time vector (column values) over one orbital period, latitude vector (row values), and the grid of flux factors. `nt` indicates the number of time samples around the orbit and `nθ` indicates the number of latitudes.\n\"\"\"\nfunction diurnalfluxfactors(a, m, e, γ, p; nt::Int=251, nθ::Int=181)\n    t = LinRange(0, orbitalperiod(a, m), nt)\n    θ = LinRange(-π/2, π/2, nθ)\n    T, Θ = meshgrid(t, θ)\n    return (t, θ, diurnalfluxfactor.(T, a, m, e, Θ, γ, p))\nend\n\n\"\"\"\n    annualfluxfactor(e, θ, γ, p)\n\nCompute the annually averaged flux factor for a latitude `θ` on a planet in a general elliptical orbit.\n\"\"\"\nfunction annualfluxfactor(e, θ, γ, p; tol::Float64=1e-4)\n    T = orbitalperiod(1.0, 1.0)\n    f(t) = diurnalfluxfactor(t, 1.0, 1.0, e, θ, γ, p)\n    F, _ = hquadrature(f, 0, T, reltol=tol, abstol=tol)\n    return F/T\nend\n\n\"\"\"\n    annualfluxfactors(e, γ, p; nθ=181)\n\nCompute a range of annually averaged flux factors for a planet in a general elliptical orbit. Returns a latitude vector (row values) and a vector of flux factors. `nθ` indicates the number of latitude samples.\n\"\"\"\nfunction annualfluxfactors(e, γ, p; nθ::Int=181)\n    θ = LinRange(-π/2, π/2, nθ)\n    F = annualfluxfactor.(e, θ, γ, p)\n    return θ, F\nend\n", "meta": {"hexsha": "0a5bd747df8cfb7d16e1da3c2970d8a2782527b0", "size": 3638, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/insolation.jl", "max_stars_repo_name": "markmbaum/ClearSky.jl", "max_stars_repo_head_hexsha": "84e8aec24a648dd7ebbef4c8d1f743bb2669a47d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-31T18:12:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T18:12:56.000Z", "max_issues_repo_path": "src/insolation.jl", "max_issues_repo_name": "wordsworthgroup/ClearSky.jl", "max_issues_repo_head_hexsha": "84e8aec24a648dd7ebbef4c8d1f743bb2669a47d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-23T20:42:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-23T20:42:44.000Z", "max_forks_repo_path": "src/insolation.jl", "max_forks_repo_name": "wordsworthgroup/ClearSky.jl", "max_forks_repo_head_hexsha": "84e8aec24a648dd7ebbef4c8d1f743bb2669a47d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.320754717, "max_line_length": 368, "alphanum_fraction": 0.6885651457, "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7847749892794493}}
{"text": "abstract type AbstractODEProblem end\n\nstruct ODEProblem{F,T,U,P} <: AbstractODEProblem\n    f::F\n    tspan::T\n    u0::U\n    θ::P\nend\n\nabstract type ODESolver end\nstruct Euler{T} <: ODESolver\n    dt::T\nend\nstruct RK2{T} <: ODESolver\n    dt::T\nend\n\nfunction f(x,θ)\n    α, β, γ, δ = θ\n    x₁, x₂ = x\n\n    dx₁ = α*x₁ - β*x₁*x₂\n    dx₂ = δ*x₁*x₂ - γ*x₂\n\n    [dx₁, dx₂]\nend\n\nfunction solve(prob::AbstractODEProblem, solver::ODESolver)\n    t = prob.tspan[1]; u = prob.u0\n    us = [u]; ts = [t]\n    while t < prob.tspan[2]\n        (u,t) = solver(prob, u, t)\n        push!(us,u)\n        push!(ts,t)\n    end\n    ts, reduce(hcat,us)\nend\n\nfunction (solver::Euler)(prob::ODEProblem, u, t)\n    f, θ, dt  = prob.f, prob.θ, solver.dt\n    (u + dt*f(u,θ), t+dt)\nend\n\nfunction (solver::RK2)(prob::ODEProblem, u, t)\n    f, θ, dt  = prob.f, prob.θ, solver.dt\n    uh = u + f(u,θ)*dt\n    u + dt/2*(f(u,θ) + f(uh,θ)), t+dt\nend\n\n\nθ = [0.1,0.2,0.3,0.2]\nu0 = [1.0,1.0]\ntspan = (0.,100.)\ndt = 0.1\nprob = ODEProblem(f,tspan,u0,θ)\n\nt,X=solve(prob, RK2(0.2))\n\n# using Plots\n# p1 = plot(t, X[1,:], label=\"x\", lw=3)\n# plot!(p1, t, X[2,:], label=\"y\", lw=3)\n\n# display(p1)\n\n#\nθ = [0.2,0.2,0.3,0.2]\nu0 = [1.0,1.0]\ntspan = (0.,100.)\ndt = 0.1\nprob2 = ODEProblem(f,tspan,u0,θ)\n\nt,X2=solve(prob2, RK2(0.2))\n\nusing Optim\n\nfunction loss(θin,prob::ODEProblem,Y)\n    prob.θ.=θin\n    t,Xn=solve(prob,RK2(0.2))\n    sum((Y.-Xn).^2)\nend\nθopt = copy(θ)\nO=Optim.optimize(θ->loss(θ,prob,X),θopt)\nO=Optim.optimize(θ->loss(θ,prob,X),θopt,LBFGS())\n\nusing DiffEqFlux\nnn=FastDense(2,2)\np = initial_params(nn)\nnn([1,2],p)\n\n\nfunction fy(x,θ)\n    α, β, γ, δ, ω = θ\n    x₁, x₂ = x\n\n    dx₁ = α*x₁ - β*x₁*x₂ + ω*x₂\n    dx₂ = δ*x₁*x₂ - γ*x₂\n\n    [dx₁, dx₂]\nend\n\n#\nθy = [0.2,0.2,0.3,0.2,0.1]\nu0 = [1.0,1.0]\ntspan = (0.,100.)\ndt = 0.1\nproby = ODEProblem(fy,tspan,u0,θy)\n\nt,Xy=solve(proby, RK2(0.2))\n\n# py = plot(t, Xy[1,:], label=\"x\", lw=3)\n# plot!(py, t, Xy[2,:], label=\"y\", lw=3)\n# savefig(\"LV_omega.svg\")\n\nfunction fnn(x,θ)\n    α, β, γ, δ = θ[1:4]\n    x₁, x₂ = x\n\n    dx₁ = α*x₁ - β*x₁*x₂ \n    dx₂ = δ*x₁*x₂ - γ*x₂\n\n    [dx₁, dx₂]+nn(x,@view θ[5:end])\nend\n\nθnn = [0.2,0.2,0.3,0.2,0.01*initial_params(nn)...]\nprobnn = ODEProblem(fnn,tspan,u0,θnn)\n\nθopt = copy(θnn)\nO=Optim.optimize(θ->loss(θ,probnn,Xy),θopt,Optim.Options(iterations=10000))\n", "meta": {"hexsha": "49df63dfe72db74768c34fc040c85ba852952122", "size": 2278, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/lecture_13/lab_2.jl", "max_stars_repo_name": "JuliaTeachingCTU/Scientific-Programming-in-Julia", "max_stars_repo_head_hexsha": "7e978fc27ae547fbf95d1367ef1d1d029267e356", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2021-11-12T10:17:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T21:40:39.000Z", "max_issues_repo_path": "docs/src/lecture_13/lab_2.jl", "max_issues_repo_name": "JuliaTeachingCTU/Scientific-Programming-in-Julia", "max_issues_repo_head_hexsha": "7e978fc27ae547fbf95d1367ef1d1d029267e356", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-10-06T09:32:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T15:15:03.000Z", "max_forks_repo_path": "docs/src/lecture_13/lab_2.jl", "max_forks_repo_name": "JuliaTeachingCTU/Scientific-Programming-in-Julia", "max_forks_repo_head_hexsha": "7e978fc27ae547fbf95d1367ef1d1d029267e356", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-05T16:45:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T18:21:34.000Z", "avg_line_length": 17.6589147287, "max_line_length": 75, "alphanum_fraction": 0.5601404741, "num_tokens": 1057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7847749840481157}}
{"text": "\"\"\"`care(A, B, Q, R)`\n\nCompute 'X', the solution to the continuous-time algebraic Riccati equation,\ndefined as A'X + XA - (XB)R^-1(B'X) + Q = 0, where R is non-singular.\n\nAlgorithm taken from:\nLaub, \"A Schur Method for Solving Algebraic Riccati Equations.\"\nhttp://dspace.mit.edu/bitstream/handle/1721.1/1301/R-0859-05666488.pdf\n\"\"\"\nfunction care(A, B, Q, R)\n    G = try\n        B*inv(R)*B'\n    catch y\n        if y isa SingularException\n            error(\"R must be non-singular in care.\")\n        else\n            throw(y)\n        end\n    end\n\n    Z = [A  -G;\n        -Q  -A']\n\n    S = schur(Z)\n    S = ordschur(S, real(S.values).<0)\n    U = S.Z\n\n    (m, n) = size(U)\n    U11 = U[1:div(m, 2), 1:div(n,2)]\n    U21 = U[div(m,2)+1:m, 1:div(n,2)]\n    return U21/U11\nend\n\n\"\"\"`dare(A, B, Q, R)`\n\nCompute `X`, the solution to the discrete-time algebraic Riccati equation,\ndefined as A'XA - X - (A'XB)(B'XB + R)^-1(B'XA) + Q = 0, where Q>=0 and R>0\n\nAlgorithm taken from:\nLaub, \"A Schur Method for Solving Algebraic Riccati Equations.\"\nhttp://dspace.mit.edu/bitstream/handle/1721.1/1301/R-0859-05666488.pdf\n\"\"\"\nfunction dare(A, B, Q, R)\n    if (!ishermitian(Q) || minimum(eigvals(real(Q))) < 0)\n        error(\"Q must be positive-semidefinite.\");\n    end\n    if (!isposdef(R))\n        error(\"R must be positive definite.\");\n    end\n\n    n = size(A, 1);\n\n    E = [\n        Matrix{Float64}(I, n, n) B/R*B';\n        zeros(size(A)) A'\n    ];\n    F = [\n        A zeros(size(A));\n        -Q Matrix{Float64}(I, n, n)\n    ];\n\n    QZ = schur(F, E);\n    QZ = ordschur(QZ, abs.(QZ.alpha./QZ.beta) .< 1);\n\n    return QZ.Z[(n+1):end, 1:n]/QZ.Z[1:n, 1:n];\nend\n\n\"\"\"`dlyap(A, Q)`\n\nCompute the solution `X` to the discrete Lyapunov equation\n`AXA' - X + Q = 0`.\n\"\"\"\nfunction dlyap(A::AbstractMatrix, Q)\n    lhs = kron(A, conj(A))\n    lhs = I - lhs\n    x = lhs\\reshape(Q, prod(size(Q)), 1)\n    return reshape(x, size(Q))\nend\n\n\"\"\"`gram(sys, opt)`\n\nCompute the grammian of system `sys`. If `opt` is `:c`, computes the\ncontrollability grammian. If `opt` is `:o`, computes the observability\ngrammian.\"\"\"\nfunction gram(sys::AbstractStateSpace, opt::Symbol)\n    if !isstable(sys)\n        error(\"gram only valid for stable A\")\n    end\n    func = iscontinuous(sys) ? lyap : dlyap\n    if opt == :c\n        # TODO probably remove type check in julia 0.7.0\n        return func(sys.A, sys.B*sys.B')#::Array{numeric_type(sys),2} # lyap is type-unstable\n    elseif opt == :o\n        return func(Matrix(sys.A'), sys.C'*sys.C)#::Array{numeric_type(sys),2} # lyap is type-unstable\n    else\n        error(\"opt must be either :c for controllability grammian, or :o for\n                observability grammian\")\n    end\nend\n\n\"\"\"`obsv(A, C)` or `obsv(sys)`\n\nCompute the observability matrix for the system described by `(A, C)` or `sys`.\n\nNote that checking for observability by computing the rank from `obsv` is\nnot the most numerically accurate way, a better method is checking if\n`gram(sys, :o)` is positive definite.\"\"\"\nfunction obsv(A::AbstractMatrix, C::AbstractMatrix)\n    T = promote_type(eltype(A), eltype(C))\n    n = size(A, 1)\n    ny = size(C, 1)\n    if n != size(C, 2)\n        throw(ArgumentError(\"C must have the same number of columns as A\"))\n    end\n    res = fill(zero(T), n*ny, n)\n    res[1:ny, :] = C\n    for i=1:n-1\n        res[(1 + i*ny):(1 + i)*ny, :] = res[((i - 1)*ny + 1):i*ny, :] * A\n    end\n    return res\nend\nobsv(sys::StateSpace) = obsv(sys.A, sys.C)\n\n\"\"\"`ctrb(A, B)` or `ctrb(sys)`\n\nCompute the controllability matrix for the system described by `(A, B)` or\n`sys`.\n\nNote that checking for controllability by computing the rank from\n`ctrb` is not the most numerically accurate way, a better method is\nchecking if `gram(sys, :c)` is positive definite.\"\"\"\nfunction ctrb(A::AbstractMatrix, B::AbstractMatrix)\n    T = promote_type(eltype(A), eltype(B))\n    n = size(A, 1)\n    nu = size(B, 2)\n    if n != size(B, 1)\n        throw(ArgumentError(\"B must have the same number of rows as A\"))\n    end\n    res = fill(zero(T), n, n*nu)\n    res[:, 1:nu] = B\n    for i=1:n-1\n        res[:, (1 + i*nu):(1 + i)*nu] = A * res[:, ((i - 1)*nu + 1):i*nu]\n    end\n    return res\nend\nctrb(sys::StateSpace) = ctrb(sys.A, sys.B)\n\n\"\"\"`P = covar(sys, W)`\n\nCalculate the stationary covariance `P = E[y(t)y(t)']` of the output `y` of a\n`StateSpace` model `sys` driven by white Gaussian noise `w` with covariance\n`E[w(t)w(τ)]=W*δ(t-τ)` (δ is the Dirac delta).\n\nRemark: If `sys` is unstable then the resulting covariance is a matrix of `Inf`s.\nEntries corresponding to direct feedthrough (D*W*D' .!= 0) will equal `Inf`\nfor continuous-time systems.\"\"\"\nfunction covar(sys::AbstractStateSpace, W)\n    (A, B, C, D) = ssdata(sys)\n    if !isa(W, UniformScaling) && (size(B,2) != size(W, 1) || size(W, 1) != size(W, 2))\n        error(\"W must be a square matrix the same size as `sys.B` columns\")\n    end\n    if !isstable(sys)\n        return fill(Inf,(size(C,1),size(C,1)))\n    end\n    func = iscontinuous(sys) ? lyap : dlyap\n    Q = try\n        func(A, B*W*B')\n    catch\n        error(\"No solution to the Lyapunov equation was found in covar\")\n    end\n    P = C*Q*C'\n    if iscontinuous(sys)\n        #Variance and covariance infinite for direct terms\n        direct_noise = D*W*D'\n        for i in 1:size(C,1)\n            if direct_noise[i,i] != 0\n                P[i,:] .= Inf\n                P[:,i] .= Inf\n            end\n        end\n    else\n        P += D*W*D'\n    end\n    return P\nend\n\ncovar(sys::TransferFunction, W) = covar(ss(sys), W)\n\n\n# Note: the H∞ norm computation is probably not as accurate as with SLICOT,\n# but this seems to be still reasonably ok as a first step\n\"\"\"\n`..  norm(sys, p=2; tol=1e-6)`\n\n`norm(sys)` or `norm(sys,2)` computes the H2 norm of the LTI system `sys`.\n\n`norm(sys, Inf)` computes the H∞ norm of the LTI system `sys`.\nThe H∞ norm is the same as the H∞ for stable systems, and Inf for unstable systems.\nIf the peak gain frequency is required as well, use the function `hinfnorm` instead.\nSee [`hinfnorm`](@ref) for further documentation.\n\n`tol` is an optional keyword argument, used only for the computation of L∞ norms.\nIt represents the desired relative accuracy for the computed L∞ norm\n(this is not an absolute certificate however).\n\n`sys` is first converted to a `StateSpace` model if needed.\n\"\"\"\nfunction LinearAlgebra.norm(sys::AbstractStateSpace, p::Real=2; tol=1e-6)\n    if p == 2\n        return sqrt(tr(covar(sys, I)))\n    elseif p == Inf\n        return hinfnorm(sys; tol=tol)[1]\n    else\n        error(\"`p` must be either `2` or `Inf`\")\n    end\nend\nLinearAlgebra.norm(sys::TransferFunction, p::Real=2; tol=1e-6) = norm(ss(sys), p, tol=tol)\n\n\n\"\"\"\n`   (Ninf, ω_peak) = hinfnorm(sys; tol=1e-6)`\n\nCompute the H∞ norm `Ninf` of the LTI system `sys`, together with a frequency\n`ω_peak` at which the gain Ninf is achieved.\n\n`Ninf := sup_ω σ_max[sys(iω)]`  if `G` is stable (σ_max = largest singular value)\n      :=        `Inf'           if `G` is unstable\n\n`tol` is an optional keyword argument for the desired relative accuracy for\nthe computed H∞ norm (not an absolute certificate).\n\n`sys` is first converted to a state space model if needed.\n\nThe continuous-time L∞ norm computation implements the 'two-step algorithm' in:\\\\\n**N.A. Bruinsma and M. Steinbuch**, 'A fast algorithm to compute the H∞-norm of\na transfer function matrix', Systems and Control Letters (1990), pp. 287-293.\n\nFor the discrete-time version, see:\\\\\n**P. Bongers, O. Bosgra, M. Steinbuch**, 'L∞-norm calculation for generalized\nstate space systems in continuous and discrete time', American Control Conference, 1991.\n\nSee also [`linfnorm`](@ref).\n\"\"\"\nfunction hinfnorm(sys::AbstractStateSpace; tol=1e-6)\n    if iscontinuous(sys)\n        return _infnorm_two_steps_ct(sys, :hinf, tol)\n    else\n        return _infnorm_two_steps_dt(sys, :hinf, tol)\n    end\nend\nhinfnorm(sys::TransferFunction; tol=1e-6) = hinfnorm(ss(sys); tol=tol)\n\n\"\"\"\n`   (Ninf, ω_peak) = linfnorm(sys; tol=1e-6)`\n\nCompute the L∞ norm `Ninf` of the LTI system `sys`, together with a frequency\n`ω_peak` at which the gain `Ninf` is achieved.\n\n`Ninf := sup_ω σ_max[sys(iω)]` (σ_max denotes the largest singular value)\n\n`tol` is an optional keyword argument representing the desired relative accuracy for\nthe computed L∞ norm (this is not an absolute certificate however).\n\n`sys` is first converted to a state space model if needed.\n\nThe continuous-time L∞ norm computation implements the 'two-step algorithm' in:\\\\\n**N.A. Bruinsma and M. Steinbuch**, 'A fast algorithm to compute the H∞-norm of\na transfer function matrix', Systems and Control Letters (1990), pp. 287-293.\n\nFor the discrete-time version, see:\\\\\n**P. Bongers, O. Bosgra, M. Steinbuch**, 'L∞-norm calculation for generalized\nstate space systems in continuous and discrete time', American Control Conference, 1991.\n\nSee also [`hinfnorm`](@ref).\n\"\"\"\nfunction linfnorm(sys::AbstractStateSpace; tol=1e-6)\n    if iscontinuous(sys)\n        return _infnorm_two_steps_ct(sys, :linf, tol)\n    else\n        return _infnorm_two_steps_dt(sys, :linf, tol)\n    end\nend\nlinfnorm(sys::TransferFunction; tol=1e-6) = linfnorm(ss(sys); tol=tol)\n\nfunction _infnorm_two_steps_ct(sys::AbstractStateSpace, normtype::Symbol, tol=1e-6, maxIters=250, approximag=1e-10)\n    # norm type :hinf or :linf the reason that to not use `hinfnorm(sys) = isstable(sys) : linfnorm ? (Inf, Nan)`\n    # is to avoid re computing the poles and return the peak frequencies for, e.g., 1/(s^2 + 1)\n    # `maxIters`: the maximum  number of iterations allowed in the algorithm (default 1000)\n    # approximag is a tuning parameter: what does it mean for a number to be on the imaginary axis\n    # Because of this tuning for example, the relative precision that we provide on the norm computation\n    # is not a true guarantee, more an order of magnitude\n    # outputs: An approximatation of the L∞ norm and the frequency ω_peak at which it is achieved\n    # QUESTION: The tolerance for determining if there are poles on the imaginary axis\n    # would not be very appropriate for systems with slow dynamics?\n    T = promote_type(real(numeric_type(sys)), Float64)\n\n    on_imag_axis = z -> abs(real(z)) < approximag # Helper fcn for readability\n\n    if sys.nx == 0  # static gain\n        return (opnorm(sys.D), T(0))\n    end\n\n    pole_vec = pole(sys)\n\n    # Check if there is a pole on the imaginary axis\n    pidx = findfirst(on_imag_axis, pole_vec)\n    if !(pidx isa Nothing)\n        return (T(Inf), imag(pole_vec[pidx]))\n        # note: in case of cancellation, for s/s for example, we return Inf, whereas Matlab returns 1\n    end\n\n    if normtype == :hinf && any(z -> real(z) > 0, pole_vec)\n        return T(Inf), T(NaN) # The system is unstable\n    end\n\n    # Initialization: computation of a lower bound from 3 terms\n    if isreal(pole_vec)  # only real poles\n        ω_p = minimum(abs.(pole_vec))\n    else  # at least one pair of complex poles\n        maxidx = argmax([abs(imag(p)/real(p))/abs(p) for p in pole_vec])\n        ω_p = abs(pole_vec[maxidx])\n    end\n\n    m_vec_init = [0, ω_p, Inf]\n\n    (lb, idx) = findmax([opnorm(evalfr(sys, im*m_vec_init[1]));\n                         opnorm(evalfr(sys, im*m_vec_init[2]));\n                         opnorm(sys.D)])\n    ω_peak = m_vec_init[idx]\n\n    # Iterations\n    for iter=1:maxIters\n        gamma = (1+2*T(tol))*lb\n        R = sys.D'*sys.D - gamma^2*I\n        S = sys.D*sys.D' - gamma^2*I\n        M = sys.A-sys.B*(R\\sys.D')*sys.C\n        H = [         M              -gamma*sys.B*(R\\sys.B') ;\n               gamma*sys.C'*(S\\sys.C)            -M'            ]\n\n        Λ = complex(eigvals(H)) # To make type stable\n\n        if numeric_type(sys) <: Real\n            # Only need to consider one eigenvalue in each complex-conjugate pairs\n            filter!(z -> imag(z) >= 0, Λ)\n        end\n\n        # Find eigenvalues on the imaginary axis\n        Λ_on_imag_axis = filter(on_imag_axis, Λ)\n\n        ω_vec = imag.(Λ_on_imag_axis)\n\n        sort!(ω_vec)\n\n        if isempty(ω_vec)\n            return (1+T(tol))*lb, ω_peak\n        end\n\n        # Improve the lower bound\n        # if not empty, ω_vec contains at least two values\n        for k=1:length(ω_vec)-1\n            mk = (ω_vec[k] + ω_vec[k+1])/2\n            sigmamax_mk = opnorm(evalfr(sys,mk*1im))\n            if sigmamax_mk > lb\n                lb = sigmamax_mk\n                ω_peak = mk\n            end\n        end\n    end\n    error(\"In _infnorm_two_steps_dt: The computation of the H∞/L∞ norm did not converge in $maxIters iterations\")\nend\n\nfunction _infnorm_two_steps_dt(sys::AbstractStateSpace, normtype::Symbol, tol=1e-6, maxIters=250, approxcirc=1e-8)\n    # Discrete-time version of linfnorm_two_steps_ct above\n    # Compuations are done in normalized frequency θ\n\n    on_unit_circle = z -> abs(abs(z) - 1) < approxcirc # Helper fcn for readability\n\n    T = promote_type(real(numeric_type(sys)), Float64)\n\n    if sys.nx == 0  # static gain\n        return (opnorm(sys.D), T(0))\n    end\n\n    pole_vec = pole(sys)\n\n    # Check if there is a pole on the unit circle\n    pidx = findfirst(on_unit_circle, pole_vec)\n    if !(pidx isa Nothing)\n        return (T(Inf), angle(pole_vec[pidx])/T(sys.Ts))\n    end\n\n    if normtype == :hinf && any(z -> abs(z) > 1, pole_vec)\n        return T(Inf), T(NaN) # The system is unstable\n    end\n\n    # Initialization: computation of a lower bound from 3 terms\n\n    if isreal(pole_vec)  # not just real poles\n        # find frequency of pôle closest to unit circle\n        θ_p = angle(pole_vec[argmin(abs.(abs.(pole_vec).-1))])\n    else\n        θ_p = T(pi)/2\n    end\n\n    if isreal(pole_vec)  # only real poles\n        ω_p = minimum(abs.(pole_vec))\n    else  # at least one pair of complex poles\n        maxidx = argmax([abs(imag(p)/real(p))/abs(p) for p in pole_vec])\n        ω_p = abs(pole_vec[maxidx])\n    end\n\n    m_vec_init = [0, θ_p, pi]\n\n    (lb, idx) = findmax([opnorm(evalfr(sys, exp(im*m))) for m in m_vec_init])\n    θ_peak = m_vec_init[idx]\n\n    # Iterations\n    for iter=1:maxIters\n        gamma = (1+2*T(tol))*lb\n        R = gamma^2*I - sys.D'*sys.D\n        RinvDt = R\\sys.D'\n        L = [ sys.A+sys.B*RinvDt*sys.C  sys.B*(R\\sys.B');\n              zeros(T, sys.nx,sys.nx)      I]\n        M = [ I                                 zeros(T, sys.nx,sys.nx);\n              sys.C'*(I+sys.D*RinvDt)*sys.C     L[1:sys.nx,1:sys.nx]']\n\n        Λ = complex(eigvals(L,M)) # complex is to ensure type stability\n\n        if numeric_type(sys) <: Real\n            # Only need to consider one eigenvalue in each complex-conjugate pairs\n            filter!(z -> imag(z) >= 0, Λ)\n        end\n\n        # Find eigenvalues on the unit circle\n        Λ_on_unit_cirlce = filter(on_unit_circle, Λ)\n\n        θ_vec = angle.(Λ_on_unit_cirlce)\n\n        sort!(θ_vec)\n\n        if isempty(θ_vec)\n            return (1+T(tol))*lb, θ_peak/T(sys.Ts)\n        end\n\n        # Improve the lower bound\n        # if not empty, θ_vec contains at least two values\n        for k=1:length(θ_vec)-1\n            mk = (θ_vec[k] + θ_vec[k+1])/2\n            sigmamax_mk = opnorm(evalfr(sys,exp(mk*1im)))\n            if sigmamax_mk > lb\n                lb = sigmamax_mk\n                θ_peak = mk\n            end\n        end\n    end\n    error(\"In _infnorm_two_steps_dt: The computation of the L∞ norm did not converge in $maxIters iterations\")\nend\n\n\n\"\"\"`S, P, B = balance(A[, perm=true])`\n\nCompute a similarity transform `T` resulting in `B = T\\\\A*T` such that the row\nand column norms of `B` are approximately equivalent. If `perm=false`, the\ntransformation will only scale `A` using diagonal `S`, and not permute `A` (i.e., set `P=I`).\"\"\"\nfunction balance(A, perm::Bool=true)\n    n = LinearAlgebra.checksquare(A)\n    B = copy(A)\n    job = perm ? 'B' : 'S'\n    ilo, ihi, scaling = LAPACK.gebal!(job, B)\n\n    S = diagm(0 => scaling)\n    for j = 1:(ilo-1)   S[j,j] = 1 end\n    for j = (ihi+1):n   S[j,j] = 1 end\n\n    P = Matrix{Int}(I,n,n)\n    if perm\n        if ilo > 1\n            for j = (ilo-1):-1:1 cswap!(j, round(Int, scaling[j]), P) end\n        end\n        if ihi < n\n            for j = (ihi+1):n    cswap!(j, round(Int, scaling[j]), P) end\n        end\n    end\n    return S, P, B\nend\n\nfunction cswap!(i::Integer, j::Integer, X::StridedMatrix)\n    for k = 1:size(X,1)\n        X[i, k], X[j, k] = X[j, k], X[i, k]\n    end\nend\n\n\n\n\"\"\"\n`sysr, G = balreal(sys::StateSpace)`\n\nCalculates a balanced realization of the system sys, such that the observability and reachability gramians of the balanced system are equal and diagonal `G`\n\nSee also `gram`, `baltrunc`\n\nGlad, Ljung, Reglerteori: Flervariabla och Olinjära metoder\n\"\"\"\nfunction balreal(sys::ST) where ST <: AbstractStateSpace\n    P = gram(sys, :c)\n    Q = gram(sys, :o)\n\n    Q1 = try\n        cholesky(Hermitian(Q)).U\n    catch\n        throw(ArgumentError(\"Balanced realization failed: Observability grammian not positive definite, system needs to be observable\"))\n    end\n    U,Σ,V = svd(Q1*P*Q1')\n    Σ .= sqrt.(Σ)\n    Σ1 = diagm(0 => sqrt.(Σ))\n    T = Σ1\\(U'Q1)\n\n    Pz = T*P*T'\n    Qz = inv(T')*Q*inv(T)\n    if norm(Pz-Qz) > sqrt(eps())\n        @warn(\"balreal: Result may be inaccurate\")\n        println(\"Controllability gramian before transform\")\n        display(P)\n        println(\"Controllability gramian after transform\")\n        display(Pz)\n        println(\"Observability gramian before transform\")\n        display(Q)\n        println(\"Observability gramian after transform\")\n        display(Qz)\n        println(\"Singular values of PQ\")\n        display(Σ)\n    end\n\n    sysr = ST(T*sys.A/T, T*sys.B, sys.C/T, sys.D, sys.Ts), diagm(0 => Σ)\nend\n\n\n\"\"\"\n`sysr, G = baltrunc(sys::StateSpace, atol = √ϵ, rtol=1e-3, unitgain=true)`\n\nReduces the state dimension by calculating a balanced realization of the system sys, such that the observability and reachability gramians of the balanced system are equal and diagonal `G`, and truncating it such that all states corresponding to singular values less than `atol` and less that `rtol σmax` are removed. If `unitgain=true`, the matrix `D` is chosen such that unit static gain is achieved.\n\nSee also `gram`, `balreal`\n\nGlad, Ljung, Reglerteori: Flervariabla och Olinjära metoder\n\"\"\"\nfunction baltrunc(sys::ST; atol = sqrt(eps()), rtol = 1e-3, unitgain = true) where ST <: AbstractStateSpace\n    sysbal, S = balreal(sys)\n    S = diag(S)\n    S = S[S .>= atol]\n    S = S[S .>= S[1]*rtol]\n    n = length(S)\n    A = sysbal.A[1:n,1:n]\n    B = sysbal.B[1:n,:]\n    C = sysbal.C[:,1:n]\n    D = sysbal.D\n    if unitgain\n        D = D/(C*inv(-A)*B)\n    end\n\n    return ST(A,B,C,D,sys.Ts), diagm(0 => S)\nend\n\n\"\"\"\n    syst = similarity_transform(sys, T)\nPerform a similarity transform `T : Tx̃ = x` on `sys` such that\n```\nÃ = T⁻¹AT\nB̃ = T⁻¹ B\nC̃ = CT\nD̃ = D\n```\n\"\"\"\nfunction similarity_transform(sys::ST, T) where ST <: AbstractStateSpace\n    Tf = factorize(T)\n    A = Tf\\sys.A*T\n    B = Tf\\sys.B\n    C = sys.C*T\n    D = sys.D\n    ST(A,B,C,D,sys.Ts)\nend\n\n\"\"\"\nsysi = innovation_form(sys, R1, R2)\nsysi = innovation_form(sys; sysw=I, syse=I, R1=I, R2=I)\n\nTakes a system\n```\nx' = Ax + Bu + w ~ R1\ny  = Cx + e ~ R2\n```\nand returns the system\n```\nx' = Ax + Kv\ny  = Cx + v\n```\nwhere `v` is the innovation sequence.\n\nIf `sysw` (`syse`) is given, the covariance resulting in filtering noise with `R1` (`R2`) through `sysw` (`syse`) is used as covariance.\n\nSee Stochastic Control, Chapter 4, Åström\n\"\"\"\nfunction innovation_form(sys::ST, R1, R2) where ST <: AbstractStateSpace\n    K = kalman(sys, R1, R2)\n    ST(sys.A, K, sys.C, Matrix{eltype(sys.A)}(I, sys.ny, sys.ny), sys.Ts)\nend\n# Set D = I to get transfer function H = I + C(sI-A)\\ K\nfunction innovation_form(sys::ST; sysw=I, syse=I, R1=I, R2=I) where ST <: AbstractStateSpace\n\tK = kalman(sys, covar(sysw,R1), covar(syse, R2))\n\tST(sys.A, K, sys.C, Matrix{eltype(sys.A)}(I, sys.ny, sys.ny), sys.Ts)\nend\n", "meta": {"hexsha": "c0904d616a7026b419b813b4fc7a9bbf8107d342", "size": 19783, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix_comps.jl", "max_stars_repo_name": "tallakt/ControlSystems.jl", "max_stars_repo_head_hexsha": "dab68bc41ce55f751aa6cd2d0c955920aeae4dd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matrix_comps.jl", "max_issues_repo_name": "tallakt/ControlSystems.jl", "max_issues_repo_head_hexsha": "dab68bc41ce55f751aa6cd2d0c955920aeae4dd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix_comps.jl", "max_forks_repo_name": "tallakt/ControlSystems.jl", "max_forks_repo_head_hexsha": "dab68bc41ce55f751aa6cd2d0c955920aeae4dd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3251633987, "max_line_length": 402, "alphanum_fraction": 0.6195723601, "num_tokens": 6196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523027, "lm_q2_score": 0.8244619177503206, "lm_q1q2_score": 0.7847749808695346}}
{"text": "\"\"\"\n    horner(c,x)\n\nEvaluate a polynomial whose coefficients are given in descending order in `c`,\nat the point `x`, using Horner's rule.\n\"\"\"\nfunction horner(c,x)\n\n    n = length(c)\n    y = c[1]\n    for k = 2:n\n        y = x*y + c[k]\n    end\n\n    return y\n\nend\n", "meta": {"hexsha": "3d3111d36a7e5d9d532c079dcb95a26ae52f34ca", "size": 262, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/functions/chapter01.jl", "max_stars_repo_name": "math662/fnc-extras", "max_stars_repo_head_hexsha": "daf16d3dc9b4d86ee1b59f170eab107053daa7f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/functions/chapter01.jl", "max_issues_repo_name": "math662/fnc-extras", "max_issues_repo_head_hexsha": "daf16d3dc9b4d86ee1b59f170eab107053daa7f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/functions/chapter01.jl", "max_forks_repo_name": "math662/fnc-extras", "max_forks_repo_head_hexsha": "daf16d3dc9b4d86ee1b59f170eab107053daa7f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.5555555556, "max_line_length": 78, "alphanum_fraction": 0.572519084, "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7847728663791681}}
{"text": "# Bi-objective unidimensionnal 01 knapsack problem (biukp)\n#\n# Exercise 10.2 page 290 of\n# Multicriteria Optimization (2nd edt), M. Ehrgott, Springer 2005.\n\n\n# ---- Packages to use\nusing vOptGeneric, JuMP, GLPK\n\n\n# ---- Values of the instance to solve\np1 = [10, 3,  6, 8, 2]  # coefficients's vector of the objective 1\np2 = [12, 9, 11, 5, 6]  # coefficients's vector of the objective 2\nw  = [ 4, 5,  2, 5, 6]  # coefficients's vector of weights\nc  = 17                 # nominal capacity\nn  = length( p1 )       # number of items\n\n\n# ---- setting the model\nbiukp = vModel( GLPK.Optimizer ) #; JuMP.set_silent( biukp )\n@variable( biukp, x[1:n], Bin )\n@addobjective( biukp, Max, sum( p1[j]*x[j] for j=1:n ) )\n@addobjective( biukp, Max, sum( p2[j]*x[j] for j=1:n ) )\n@constraint( biukp, sum( w[j]*x[j] for j=1:n ) <= c )\n\n\n# ---- Invoking the solver (dichotomic method)\nvSolve( biukp, method=:dichotomy, verbose=false )\n\n\n# ---- Querying the results\nY_N = getY_N( biukp )\n\n\n# ---- Displaying the results (X_{SE} and Y_{SN})\nfor i = 1:length(Y_N)\n    X = value.(x, i)\n    print(\"X = \", findall(elt -> elt ≈ 1, X))\n    println(\" | Z = \",Y_N[i])\nend\n", "meta": {"hexsha": "b099b194f84ef1f5c5df66061e6745fac1081a41", "size": 1144, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/UKnapsackEhrgott2005.jl", "max_stars_repo_name": "vOptSolver/vOptGeneric", "max_stars_repo_head_hexsha": "7c99ecfc5d1a672bdf69b2a557f97d0b964c126a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-10-06T06:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T11:03:38.000Z", "max_issues_repo_path": "examples/UKnapsackEhrgott2005.jl", "max_issues_repo_name": "vOptSolver/vOptGeneric", "max_issues_repo_head_hexsha": "7c99ecfc5d1a672bdf69b2a557f97d0b964c126a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2018-10-26T10:52:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T00:35:22.000Z", "max_forks_repo_path": "examples/UKnapsackEhrgott2005.jl", "max_forks_repo_name": "vOptSolver/vOptGeneric", "max_forks_repo_head_hexsha": "7c99ecfc5d1a672bdf69b2a557f97d0b964c126a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2017-08-28T22:28:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-08T17:57:15.000Z", "avg_line_length": 27.9024390244, "max_line_length": 66, "alphanum_fraction": 0.618006993, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539553, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7847728643888672}}
{"text": "## MIT license (C) 2019 by Andrew Lyasoff\n\n# Julia 1.1.0 code to illustrate the construction of univariate histograms\n# and the Monte Carlo simulation technique for multivariate Gaussian samples with a given covariance matrix.\n#See (3.67), p.91, in \"Stochastic Methods in Asset Pricing.\"\n\nbegin\n    using LinearAlgebra\n    using SpecialFunctions\n    using StatsBase\n    using Random\n    using Plots\n    pyplot()\nend\n\n#We write our own histogram function. It takes as an input a single 1-dimensional array of data.\n#The number of bins in the histogram is determined automatically by using the Diaconis-Friedman rule.\n#The function returns two arrays: the mid-points of the bins and the (unnormalized) heights of the bars.\n\nfunction hstgram(data_sample::Array{Float64,1})\n    data_sorted=sort(data_sample)\n    first=data_sorted[1]\n    last=data_sorted[end]\n    nmb=length(data_sorted)\n    IQR=percentile(data_sorted,75)-percentile(data_sorted,25)\n    bin_size_loc = 2*IQR*(nmb^(-1.0/3))\n    num_bins=Int(floor((last-first)/bin_size_loc))\n    bin_size=(last-first)/(num_bins)\n    bin_end_points=[first+(i-1)*bin_size for i=1:(num_bins+1)]\n    ahist_val=[length(data_sorted[data_sorted .< u]) for u in bin_end_points]\n    hist_val=[ahist_val[i+1]-ahist_val[i] for i=1:num_bins]\n    mid_bins=[first-bin_size/2+i*bin_size for i=1:num_bins]\n    return mid_bins, hist_val\nend\n\n\n## First, create data sampled from the standard univariate normal density.\nval=(x->((2*π)^(-1/2)*exp(-x^2/2))).(-3.3:0.05:3.3);\n\nRandom.seed!(0xabcdef12); # if needed to generate the same samples\n\n#simulate 10,000 standard normals and generate the histogram\nbegin\n    nval=randn!(zeros(10000));\n    U,V=hstgram(nval);\n    VV=V/(sum(V)*(U[2]-U[1]));\nend\n\n#check the length of the bin\nlength(VV)\n\nbegin\n    plot(U.+(U[2]-U[1])/2,VV,line=(:steppre,1),linewidth=0.05,label=\"histogram\")\n    xlabel!(\"samples\")\n    ylabel!(\"frequency\")\n    plot!(-3.3:0.05:3.3,val,label=\"normal density\")\nend\n\n#generate another sample\nbegin\n    nval=randn(10000);\n    U,V=hstgram(nval);\n    VV=V/(sum(V)*(U[2]-U[1]));\n    plot(U.+(U[2]-U[1])/2,VV,line=(:steppre,1),linewidth=0.05,label=\"histogram\")\n    xlabel!(\"samples\")\n    ylabel!(\"frequency\")\n    plot!(-3.3:0.05:3.3,val,label=\"normal density\")\nend\n\n\n# standard normals can be generated by sampling from the uniform distribution\nbegin\n    uval=rand(10000);\n    nval=(x->sqrt(2)*erfinv(2*x-1)).(uval);\n    U,V=hstgram(nval);\n    VV=V/(sum(V)*(U[2]-U[1]));\n    plot(U.+(U[2]-U[1])/2,VV,line=(:steppre,1),linewidth=0.05,label=\"histogram\")\n    xlabel!(\"samples\")\n    ylabel!(\"frequency\")\n    plot!(-3.3:0.05:3.3,val,label=\"normal density\")\nend\n\n#simulate 10,000 standard bi-variate normals\nbegin\n    nval=randn!(zeros(10000));\n    nnval=randn!(zeros(10000));\nend\n\nscatter(nval,nnval,ratio=1,markersize=1,label=\"\")\n\n# to simulate bi-variate normals with a given covariance matrix\n#   first create a fictitios covariance matrix\n\n\nbegin\n    A=rand(2,2);\n    #Cov=A'A; # another alternative that always yields a positive definite matrix\n    Cov=Symmetric(A) # may not produce a positive definite matrix\nend\n\n#check if Cov is positive definite; if not, repeat the last step\neigvals(Cov)\n\nbegin\n    eigdCov=Diagonal(eigvals(Cov).^0.5)\n    eigCov=eigvecs(Cov); # matrix of eigen vectors\n    chlCov=cholesky(Cov); # Cholesky \"square root\" of Cov\n    MM=eigdCov*eigCov; # Spectral \"square root\" of Cov\nend\n\n# check that the factorizations give what is expected\nCov-MM'*MM\nCov-chlCov.L*chlCov.U\nCov-(chlCov.U)'*chlCov.U\nCov-(chlCov.L)*(chlCov.L)'\n\n#this should be an orthogonal matrix\neigCov'*eigCov\n\n\n#Transform the randomly generated standard bi-variate sample through the \"square root\" of the covariance matrix.\n#method 1\nbegin\n    NN=hcat(nval,nnval)';\n    data_2_dim=MM'NN;\n    scatter(data_2_dim[1,:],data_2_dim[2,:],ratio=1,markersize=1,label=\"\")\nend\n\n\n\n#method 2\nbegin\n    data_2_dim=(chlCov.L)*NN;\n    scatter(data_2_dim[1,:],data_2_dim[2,:],ratio=1,markersize=1,label=\"\")\nend\n", "meta": {"hexsha": "9f322fe698ac6a72a4fdbf0e8c67dc8863388e3b", "size": 3973, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Multivariate-Normal-Dist-Examples-Julia.jl", "max_stars_repo_name": "AndrewLyasoff/SMAP", "max_stars_repo_head_hexsha": "6eeea8953a26a05b1e23387067109d23b2011824", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-09-04T19:12:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T02:05:44.000Z", "max_issues_repo_path": "Multivariate-Normal-Dist-Examples-Julia.jl", "max_issues_repo_name": "lhyzh/SMAP", "max_issues_repo_head_hexsha": "f6687291769d4c16a0d51a06a941384f646bb432", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-02-13T14:24:38.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-13T14:24:38.000Z", "max_forks_repo_path": "Multivariate-Normal-Dist-Examples-Julia.jl", "max_forks_repo_name": "lhyzh/SMAP", "max_forks_repo_head_hexsha": "f6687291769d4c16a0d51a06a941384f646bb432", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-02-10T03:43:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-28T03:53:22.000Z", "avg_line_length": 29.2132352941, "max_line_length": 112, "alphanum_fraction": 0.700981626, "num_tokens": 1259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7847728594271529}}
{"text": "## Environment and packages\ncd(@__DIR__)\nusing Pkg; Pkg.activate(\".\"); Pkg.instantiate()\n\nusing OrdinaryDiffEq\nusing ModelingToolkit\nusing DataDrivenDiffEq\nusing LinearAlgebra, Optim\nusing DiffEqFlux, Flux\nusing Plots\ngr()\nusing JLD2, FileIO\nusing Statistics\nusing DelimitedFiles\n# Set a random seed for reproduceable behaviour\nusing Random\nRandom.seed!(5443)\n\n#### NOTE\n# Since the recent release of DataDrivenDiffEq v0.6.0 where a complete overhaul of the optimizers took\n# place, SR3 has been used. Right now, STLSQ performs better and has been changed.\n# Additionally, the behaviour of the optimization has changed slightly. This has been adjusted\n# by decreasing the tolerance of the gradient.\n\n\nsvname = \"HudsonBay\"\n## Data Preprocessing\n# The data has been taken from https://jmahaffy.sdsu.edu/courses/f00/math122/labs/labj/q3v1.htm\n# Originally published in E. P. Odum (1953), Fundamentals of Ecology, Philadelphia, W. B. Saunders\nhudson_bay_data = readdlm(\"hudson_bay_data.dat\", '\\t', Float32, '\\n')\n# Measurements of prey and predator\nXₙ = Matrix(transpose(hudson_bay_data[:, 2:3]))\nt = hudson_bay_data[:, 1] .- hudson_bay_data[1, 1]\n# Normalize the data; since the data domain is strictly positive\n# we just need to divide by the maximum\nxscale = maximum(Xₙ, dims =2)\nXₙ .= 1f0 ./ xscale .* Xₙ\n# Time from 0 -> n\ntspan = (t[1], t[end])\n\n# Plot the data\nscatter(t, transpose(Xₙ), xlabel = \"t\", ylabel = \"x(t), y(t)\")\nplot!(t, transpose(Xₙ), xlabel = \"t\", ylabel = \"x(t), y(t)\")\n\n## Direct Identification via SINDy + Collocation\n\n# Create the problem using a gaussian kernel for collocation\nfull_problem = ContinuousDataDrivenProblem(Xₙ, t, DataDrivenDiffEq.GaussianKernel())\n# Look at the collocation\nplot(full_problem.t, full_problem.X')\nplot(full_problem.t, full_problem.DX')\n\n# Create a Basis\n@variables u[1:2]\n\n# Generate the basis functions, multivariate polynomials up to deg 5\n# and sine\nb = [polynomial_basis(u, 5); sin.(u)]\nbasis = Basis(b, u)\n\n# Create the thresholds which should be used in the search process\nλ = Float32.(exp10.(-7:0.1:5))\n# Create an optimizer for the SINDy problem\nopt = STLSQ(λ)\n\n# Best result so far\nfull_res = solve(full_problem, basis, opt, maxiter = 10000, progress = true, denoise = true, normalize = true)\n\nprintln(full_res)\nprintln(result(full_res))\n\n## Define the network\n# Gaussian RBF as activation\nrbf(x) = exp.(-(x.^2))\n\n# Define the network 2->5->5->5->2\nU = FastChain(\n    FastDense(2,5,rbf), FastDense(5,5, rbf), FastDense(5,5, tanh), FastDense(5,2)\n)\n\n# Get the initial parameters, first two is linear birth / decay of prey and predator\np = [rand(Float32,2); initial_params(U)]\n\n# Define the hybrid model\nfunction ude_dynamics!(du,u, p, t)\n    û = U(u, p[3:end]) # Network prediction\n    # We assume a linear birth rate for the prey\n    du[1] = p[1]*u[1] + û[1]\n    # We assume a linear decay rate for the predator\n    du[2] = -p[2]*u[2] + û[2]\nend\n\n# Define the problem\nprob_nn = ODEProblem(ude_dynamics!,Xₙ[:, 1], tspan, p)\n\n## Function to train the network\n# Define a predictor\nfunction predict(θ, X = Xₙ[:,1], T = t)\n    Array(solve(prob_nn, Vern7(), u0 = X, p=θ,\n                tspan = (T[1], T[end]), saveat = T,\n                abstol=1e-6, reltol=1e-6,\n                sensealg = ForwardDiffSensitivity()\n                ))\nend\n\n\n# Define parameters for Multiple Shooting\ngroup_size = 5\ncontinuity_term = 200.0f0\n\nfunction loss(data, pred)\n\treturn sum(abs2, data - pred)\nend\n\nfunction shooting_loss(p)\n    return multiple_shoot(p, Xₙ, t, prob_nn, loss, Vern7(),\n                          group_size; continuity_term)\nend\n\nfunction loss(θ)\n    X̂ = predict(θ)\n    sum(abs2, Xₙ - X̂) / size(Xₙ, 2) + convert(eltype(θ), 1e-3)*sum(abs2, θ[3:end]) ./ length(θ[3:end])\nend\n\n# Container to track the losses\nlosses = Float32[]\n\n# Callback to show the loss during training\ncallback(θ,args...) = begin\n\tl = loss(θ) # Equivalent L2 loss\n    push!(losses, l)\n    if length(losses)%5==0\n        println(\"Current loss after $(length(losses)) iterations: $(losses[end])\")\n    end\n    false\nend\n\n## Training -> First shooting / batching to get a rough estimate\n\n# First train with ADAM for better convergence -> move the parameters into a\n# favourable starting positing for BFGS\nres1 = DiffEqFlux.sciml_train(shooting_loss, p, ADAM(0.1f0), cb=callback, maxiters = 100)\nprintln(\"Training loss after $(length(losses)) iterations: $(losses[end])\")\n# Train with BFGS to achieve partial fit of the data\nres2 = DiffEqFlux.sciml_train(shooting_loss, res1.minimizer, BFGS(initial_stepnorm=0.01f0), cb=callback, maxiters = 500)\nprintln(\"Training loss after $(length(losses)) iterations: $(losses[end])\")\n# Full L2-Loss for full prediction\nres3 = DiffEqFlux.sciml_train(loss, res2.minimizer, BFGS(initial_stepnorm=0.01f0), cb=callback, maxiters = 10000)\nprintln(\"Final training loss after $(length(losses)) iterations: $(losses[end])\")\n\n\npl_losses = plot(1:101, losses[1:101], yaxis = :log10, xaxis = :log10, xlabel = \"Iterations\", ylabel = \"Loss\", label = \"ADAM (Shooting)\", color = :blue)\nplot!(102:302, losses[102:302], yaxis = :log10, xaxis = :log10, xlabel = \"Iterations\", ylabel = \"Loss\", label = \"BFGS (Shooting)\", color = :red)\nplot!(302:length(losses), losses[302:end], color = :black, label = \"BFGS (L2)\")\nsavefig(pl_losses, joinpath(pwd(), \"plots\", \"$(svname)_losses.pdf\"))\n\n# Rename the best candidate\np_trained = res3.minimizer\n\n## Analysis of the trained network\n# Interpolate the solution\ntsample = t[1]:0.5:t[end]\nX̂ = predict(p_trained, Xₙ[:,1], tsample)\n# Trained on noisy data vs real solution\npl_trajectory = scatter(t, transpose(Xₙ), color = :black, label = [\"Measurements\" nothing], xlabel = \"t\", ylabel = \"x(t), y(t)\")\nplot!(tsample, transpose(X̂), color = :red, label = [\"UDE Approximation\" nothing])\nsavefig(pl_trajectory, joinpath(pwd(), \"plots\", \"$(svname)_trajectory_reconstruction.pdf\"))\n\n# Neural network guess\nŶ = U(X̂,p_trained[3:end])\n\npl_reconstruction = scatter(tsample, transpose(Ŷ), xlabel = \"t\", ylabel =\"U(x,y)\", color = :red, label = [\"UDE Approximation\" nothing])\nplot!(tsample, transpose(Ŷ), color = :red, lw = 2, style = :dash, label = [nothing nothing])\nsavefig(pl_reconstruction, joinpath(pwd(), \"plots\", \"$(svname)_missingterm_reconstruction.pdf\"))\npl_missing = plot(pl_trajectory, pl_reconstruction, layout = (2,1))\nsavefig(pl_missing, joinpath(pwd(), \"plots\", \"$(svname)_reconstruction.pdf\"))\n## Symbolic regression via sparse regression (SINDy based)\n# We reuse the basis and optimizer defined at the beginning\n\nnn_problem = ContinuousDataDrivenProblem(X̂, tsample, DX = Ŷ)\nnn_res = solve(nn_problem, basis, opt, maxiter = 10000, progress = true, normalize = false, denoise = true)\nprintln(nn_res)\nprintln(result(nn_res))\n\n# Define the recovered, hyrid model with the rescaled dynamics\nfunction recovered_dynamics!(du,u, p, t)\n    û = nn_res(u, p[3:end]) # Network prediction\n    du[1] = p[1]*u[1] + û[1]\n    du[2] = -p[2]*u[2] + û[2]\nend\n\n\np_model = [p_trained[1:2];parameters(nn_res)]\n\nestimation_prob = ODEProblem(recovered_dynamics!, Xₙ[:, 1], tspan, p_model)\n# Convert for reuse\nsys = modelingtoolkitize(estimation_prob);\ndudt = ODEFunction(sys);\nestimation_prob = ODEProblem(dudt,Xₙ[:, 1], tspan, p_model)\nestimate = solve(estimation_prob, Tsit5(), saveat = t)\n\n##  Fit the found model\nfunction loss_fit(θ)\n    X̂ = Array(solve(estimation_prob, Tsit5(), p = θ, saveat = t))\n    sum(abs2, X̂ .- Xₙ)\nend\n\n# Post-fit the model\nres_fit = DiffEqFlux.sciml_train(loss_fit, p_model, BFGS(initial_stepnorm = 0.1f0), maxiters = 1000)\np_fitted = res_fit.minimizer\n\n# Estimate\nestimate_rough = solve(estimation_prob, Tsit5(), saveat = 0.1*mean(diff(t)), p = p_model)\nestimate = solve(estimation_prob, Tsit5(), saveat = 0.1*mean(diff(t)), p = p_fitted)\n\n# Plot\npl_fitted = plot(t, transpose(Xₙ), style = :dash, lw = 2,color = :black, label = [\"Measurements\" nothing], xlabel = \"t\", ylabel = \"x(t), y(t)\")\nplot!(estimate_rough, color = :red, label = [\"Recovered\" nothing])\nplot!(estimate, color = :blue, label = [\"Recovered + Fitted\" nothing])\nsavefig(pl_fitted,joinpath(pwd(),\"plots\",\"$(svname)recovery_fitting.pdf\"))\n\n## Simulation\n\n# Look at long term prediction\nt_long = (0.0f0, 50.0f0)\nestimate_long = solve(estimation_prob, Tsit5(), saveat = 0.25f0, tspan = t_long,p = p_fitted)\nplot(estimate_long.t, transpose(xscale .* estimate_long[:,:]), xlabel = \"t\", ylabel = \"x(t),y(t)\")\n\n\n## Save the results\nsave(joinpath(pwd(),\"results\",\"Hudson_Bay_recovery.jld2\"),\n    \"X\", Xₙ, \"t\" , t, \"neural_network\" , U, \"initial_parameters\", p, \"trained_parameters\" , p_trained, # Training\n    \"losses\", losses, \"result\", nn_res, \"recovered_parameters\", parameters(nn_res), # Recovery\n    \"model\", recovered_dynamics!, \"model_parameter\", p_model, \"fitted_parameter\", p_fitted,\n    \"long_estimate\", estimate_long) # Estimation\n\n## Post Processing and Plots\n\nc1 = 3 # RGBA(174/255,192/255,201/255,1) # Maroon\nc2 = :orange # RGBA(132/255,159/255,173/255,1) # Red\nc3 = :blue # RGBA(255/255,90/255,0,1) # Orange\nc4 = :purple # RGBA(153/255,50/255,204/255,1) # Purple\n\np3 = scatter(t, transpose(Xₙ), color = [c1 c2], label = [\"x data\" \"y data\"],\n             title = \"Recovered Model from Hudson Bay Data\",\n             titlefont = \"Helvetica\", legendfont = \"Helvetica\",\n             markersize = 5)\n\nplot!(p3,estimate_long, color = [c3 c4], lw=1, label = [\"Estimated x(t)\" \"Estimated y(t)\"])\nplot!(p3,[19.99,20.01],[0.0,maximum(Xₙ)*1.25],lw=1,color=:black, label = nothing)\nannotate!([(10.0,maximum(Xₙ)*1.25,text(\"Training \\nData\",12 , :center, :top, :black, \"Helvetica\"))])\nsavefig(p3,joinpath(pwd(),\"plots\",\"$(svname)full_plot.pdf\"))\n", "meta": {"hexsha": "b655adf96c88cc46fdb4847b00e1ba712a5432fa", "size": 9613, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LotkaVolterra/hudson_bay.jl", "max_stars_repo_name": "chepyle/universal_differential_equations", "max_stars_repo_head_hexsha": "c10bd27b9a5b158663ca6eeb29dc64e65abb5c74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 173, "max_stars_repo_stars_event_min_datetime": "2020-01-15T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:23:25.000Z", "max_issues_repo_path": "LotkaVolterra/hudson_bay.jl", "max_issues_repo_name": "chepyle/universal_differential_equations", "max_issues_repo_head_hexsha": "c10bd27b9a5b158663ca6eeb29dc64e65abb5c74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-01-28T02:37:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T05:47:26.000Z", "max_forks_repo_path": "LotkaVolterra/hudson_bay.jl", "max_forks_repo_name": "chepyle/universal_differential_equations", "max_forks_repo_head_hexsha": "c10bd27b9a5b158663ca6eeb29dc64e65abb5c74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2020-01-21T08:13:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:43:29.000Z", "avg_line_length": 37.9960474308, "max_line_length": 152, "alphanum_fraction": 0.6944762301, "num_tokens": 2999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336302, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7847728574087753}}
{"text": "# ------------------------------------------------------------------------------------------\n# # Julia for Data Science - Plotting\n#\n# ### Data visualization: generating nice looking plots in Julia is straight forward\n# In what's next, we will see some of the tools that Julia plotting provides to produce high\n# quality figures for your data. In particular we'll look at\n#\n# 1. Plotting mathematical functions\n# 1. Visualizing statistics\n# 1. Subplotting\n# \n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## Part 1: plot math functions (specifically latex equations) in our plots\n# ------------------------------------------------------------------------------------------\n\nusing LaTeXStrings\nusing Plots\npyplot(leg=false)\nx = 1:0.2:4\n\n# ------------------------------------------------------------------------------------------\n# Create three functions and plot them all!\n# ------------------------------------------------------------------------------------------\n\ny1 = sqrt.(x)\ny2 = log.(x)\ny3 = x.^2\n\nf1 = plot(x,y1)\nplot!(f1,x,y2) # \"plot!\" means \"plot on the same canvas we just plot on\"\nplot!(f1,x,y3)\n\n# ------------------------------------------------------------------------------------------\n# Now we can annotate each of these plots! using either text, or latex strings\n# ------------------------------------------------------------------------------------------\n\nannotate!(f1,[(x[6],y1[6],text(L\"\\sqrt{x}\",16,:center)),\n          (x[11],y2[11],text(L\"log(x)\",:right,16)),\n          (x[6],y3[6],text(L\"x^2\",16))])\n\n# ------------------------------------------------------------------------------------------\n# ## Part 2: Visualizing statistics\n#\n# **2D histograms** are really easy!\n# ------------------------------------------------------------------------------------------\n\nn = 1000\nset1 = randn(n)\nset2 = randn(n)\nhistogram2d(set1,set2,nbins=20,colorbar=true)\n\n# ------------------------------------------------------------------------------------------\n# **Let's go back to our houses dataset and learn even more things about it!**\n# ------------------------------------------------------------------------------------------\n\nusing DataFrames\nhouses = readtable(\"houses.csv\")\nfilter_houses = houses[houses[!, :sq__ft].>0,:]\nx = filter_houses[!, :sq__ft]\ny = filter_houses[!, :price]\n\ngh = histogram2d(x,y,nbins=20,colorbar=true)\nxaxis!(gh,\"square feet\")\nyaxis!(gh,\"price\")\n\n# ------------------------------------------------------------------------------------------\n# Interesting!\n#\n# Most houses sold are in the range 1000-1500 and they cost approximately 150,000 dollars\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# *Let's see more stats plots.*\n#\n# We can convince ourselves that random distrubutions are indeed very similar.\n#\n# Let's do that through **box plots** and **violin plots**.\n# ------------------------------------------------------------------------------------------\n\nusing StatsPlots\ny = rand(10000,6) # generate 6 random samples of size 1000 each\nf2 = violin([\"Series 1\" \"Series 2\" \"Series 3\" \"Series 4\" \"Series 5\"],y,leg=false,color=:red)\n\nboxplot!([\"Series 1\" \"Series 2\" \"Series 3\" \"Series 4\" \"Series 5\"],y,leg=false,color=:green)\n\n# ------------------------------------------------------------------------------------------\n# These plots look almost identical, so we do have the same distribution indeed.\n#\n# Let's study the price distributions in different cities in the houses dataset.\n# ------------------------------------------------------------------------------------------\n\nsome_cities = [\"SACRAMENTO\",\"RANCHO CORDOVA\",\"RIO LINDA\",\"CITRUS HEIGHTS\",\"NORTH HIGHLANDS\",\"ANTELOPE\",\"ELK GROVE\",\"ELVERTA\" ] # try picking pther cities!\n\nfh = plot(xrotation=90)\nfor ucity in some_cities\n    subs = filter_houses[filter_houses[!, :city].==ucity,:]\n    city_prices = subs[!, :price]\n    violin!(fh,[ucity],city_prices,leg=false)\nend\ndisplay(fh)\n\n# ------------------------------------------------------------------------------------------\n# ## Part 3: Subplots are very easy!\n#\n# To create a plot with subplots, all we need to do is throw the variables bound to\n# individual plots inside another call to `plot`!\n# ------------------------------------------------------------------------------------------\n\nx = -10:.1:10\np1 = plot(x, x)\np2 = plot(x, x.^2)\np3 = plot(x, x.^3)\np4 = plot(x, x.^4)\nplot(p1,p2,p3,p4,layout=(2,2),legend=false)\n\n# ------------------------------------------------------------------------------------------\n# You can create your own layout as follows.\n# ------------------------------------------------------------------------------------------\n\nmylayout = @layout([a{0.5h};[b{0.7w} c]])\nplot(fh,f2,gh,layout=mylayout,legend=false)\n\n# this layout:\n# 1 \n# 2 3\n\n# ------------------------------------------------------------------------------------------\n# ### Please let us know how we're doing!\n#\n# https://tinyurl.com/JuliaDataScience\n# ------------------------------------------------------------------------------------------\n\n\n", "meta": {"hexsha": "aadfc25c670ecfc072942ce92f256f5f704d3c56", "size": 5280, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-julia-for-data-science/short-version/03.Julia_for_data_science-Plotting.jl", "max_stars_repo_name": "grenkoca/JuliaTutorials", "max_stars_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 535, "max_stars_repo_stars_event_min_datetime": "2020-07-15T14:56:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T12:50:32.000Z", "max_issues_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-julia-for-data-science/short-version/03.Julia_for_data_science-Plotting.jl", "max_issues_repo_name": "grenkoca/JuliaTutorials", "max_issues_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2018-02-25T22:53:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-14T02:15:50.000Z", "max_forks_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-julia-for-data-science/short-version/03.Julia_for_data_science-Plotting.jl", "max_forks_repo_name": "grenkoca/JuliaTutorials", "max_forks_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 394, "max_forks_repo_forks_event_min_datetime": "2020-07-14T23:22:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:12:57.000Z", "avg_line_length": 38.8235294118, "max_line_length": 154, "alphanum_fraction": 0.3994318182, "num_tokens": 1043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.7847728471302328}}
{"text": "#=\nBinary (or 0-1) knapsack problem\n\n    Given a knapsack of some capacity C and n objects\n       with object i having weight wi and profit pi,\n       the goal is to choose some subset of the objects\n       that can fit in the knapsack \n       (i.e. the sum of their weights is no more than C)\n       while maximizing profit.\n\n    This can be formulated as a mixed-integer program as:\n        maximize x' p subject to x∈{0,1}  and  w′x <= C\n        x is a vector is size n, where x_i\n        is 1 if we chose to keep the object in the knapsack, \n           0 otherwise.\n\nsource: https://nbviewer.jupyter.org/github/JuliaOpt/Convex.jl/blob/master/\n                                    examples/binary_knapsack.ipynb\n=#\n\n# Data taken from http://people.sc.fsu.edu/~jburkardt/datasets/knapsack_01/knapsack_01.html\n\nw = [23; 31; 29; 44; 53; 38; 63; 85; 89; 82]\nC = 165 \np =  [92; 57; 49; 68; 60; 43; 67; 84; 87; 72];\nn = length(w)\n\nusing Convex, GLPKMathProgInterface\nx = Variable(n, :Bin)\nproblem = maximize(dot(p, x), dot(w, x) <= C)\nsolve!(problem, GLPKSolverMIP())\n", "meta": {"hexsha": "c4f3e377ca32f02533e80ab3ca4d6dceb57ad27d", "size": 1064, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "refs/MILP/examples/BinaryKnapsack.jl", "max_stars_repo_name": "JuliaTagBot/GUI.jl", "max_stars_repo_head_hexsha": "b2ab393c6286ede8d0b7d00929098f99699de226", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-09-20T20:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T21:00:59.000Z", "max_issues_repo_path": "refs/MILP/examples/BinaryKnapsack.jl", "max_issues_repo_name": "JuliaTagBot/GUI.jl", "max_issues_repo_head_hexsha": "b2ab393c6286ede8d0b7d00929098f99699de226", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "refs/MILP/examples/BinaryKnapsack.jl", "max_forks_repo_name": "JuliaTagBot/GUI.jl", "max_forks_repo_head_hexsha": "b2ab393c6286ede8d0b7d00929098f99699de226", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:26:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:26:06.000Z", "avg_line_length": 33.25, "max_line_length": 91, "alphanum_fraction": 0.6372180451, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290913825542, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7847375766291611}}
{"text": "function newtonRaphson(f::Function, fprime::Function, xi::Number, ea::Number, maxIter::Int64)\n  # Estimate roots of functions using the Newton-Raphson method\n  for i = 1:maxIter\n    xiprev  = xi;\n    xi = xi - (f(xi) / fprime(xi));\n\n    if abs(xi - xiprev) / xi < ea\n      break;\n    end;\n  end\n  return xi;\nend\n", "meta": {"hexsha": "7b300fb74ab8e2c6ca485a2a604a7e745b6312a1", "size": 312, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/Root Estimation/newtonraphson.jl", "max_stars_repo_name": "alexjohnj/numerical-methods", "max_stars_repo_head_hexsha": "152c24a5ab297cf2e7486e96c3f986dbe536537d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Julia/Root Estimation/newtonraphson.jl", "max_issues_repo_name": "alexjohnj/numerical-methods", "max_issues_repo_head_hexsha": "152c24a5ab297cf2e7486e96c3f986dbe536537d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/Root Estimation/newtonraphson.jl", "max_forks_repo_name": "alexjohnj/numerical-methods", "max_forks_repo_head_hexsha": "152c24a5ab297cf2e7486e96c3f986dbe536537d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-16T23:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-16T23:12:40.000Z", "avg_line_length": 24.0, "max_line_length": 93, "alphanum_fraction": 0.6314102564, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9653811581728097, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7847267971112742}}
{"text": "# Univariate Gaussian Mixture Models\n\nstruct UnivariateGMM <: UnivariateMixture{Continuous,Normal}\n    K::Int\n    means::Vector{Float64}\n    stds::Vector{Float64}\n    prior::Categorical\n\n    function UnivariateGMM(ms::Vector{Float64}, ss::Vector{Float64}, pri::Categorical)\n        K = length(ms)\n        length(ss) == K || throw(DimensionMismatch())\n        ncategories(pri) == K ||\n            error(\"The number of categories in pri should be equal to the number of components.\")\n        new(K, ms, ss, pri)\n    end\nend\n\n@distr_support UnivariateGMM -Inf Inf\n\nncomponents(d::UnivariateGMM) = d.K\n\ncomponent(d::UnivariateGMM, k::Int) = Normal(d.means[k], d.stds[k])\n\nprobs(d::UnivariateGMM) = probs(d.prior)\n\nmean(d::UnivariateGMM) = dot(d.means, probs(d))\n\nrand(d::UnivariateGMM) = (k = rand(d.prior); d.means[k] + randn() * d.stds[k])\n\nparams(d::UnivariateGMM) = (d.means, d.stds, d.prior)\n\nstruct UnivariateGMMSampler <: Sampleable{Univariate,Continuous}\n    means::Vector{Float64}\n    stds::Vector{Float64}\n    psampler::AliasTable\nend\n\nrand(s::UnivariateGMMSampler) = (k = rand(s.psampler); s.means[k] + randn() * s.stds[k])\nsampler(d::UnivariateGMM) = UnivariateGMMSampler(d.means, d.stds, sampler(d.prior))\n", "meta": {"hexsha": "435d70fca6ef165ed9153f6e6b19934fb25a3d0c", "size": 1215, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mixtures/unigmm.jl", "max_stars_repo_name": "janrpeters/Distributions.jl", "max_stars_repo_head_hexsha": "0db2a127ffa496586cace8864dadc4fb65c9f3e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-20T03:34:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-20T03:34:59.000Z", "max_issues_repo_path": "src/mixtures/unigmm.jl", "max_issues_repo_name": "janrpeters/Distributions.jl", "max_issues_repo_head_hexsha": "0db2a127ffa496586cace8864dadc4fb65c9f3e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mixtures/unigmm.jl", "max_forks_repo_name": "janrpeters/Distributions.jl", "max_forks_repo_head_hexsha": "0db2a127ffa496586cace8864dadc4fb65c9f3e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-20T03:35:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-20T03:35:17.000Z", "avg_line_length": 30.375, "max_line_length": 97, "alphanum_fraction": 0.6814814815, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7847035785074332}}
{"text": "using ReachabilityAnalysis\n\n@taylorize function lotkavolterra!(dx, x, params, t)\n    local α, β, γ, δ = 1.5, 1., 3., 1.\n    dx[1] = α * x[1] - β * x[1] * x[2]\n    dx[2] = δ * x[1] * x[2] - γ * x[2]\n    return dx\nend\n\nX0 = Hyperrectangle(low=[4.8, 1.8], high=[5.2, 2.2]);\nprob = @ivp(x' = lotkavolterra!(x), dim=2, x(0) ∈ X0)\nsol = solve(prob, T=8.0, alg=TMJets());\nsolz = overapproximate(sol, Zonotope);\n\nusing Plots\n\nplot(solz, vars=(1, 2), alpha=0.3,lw=0., xlab=\"x\", ylab=\"y\", label=\"Flowpipe\", legend=:bottomright)\nplot!(X0, label=\"X(0)\")\n\n@taylorize function f(du, u, p, t)\n    du[1] = u[3] * u[1] - u[4] * (u[1] * u[2]) - u[7] * u[1]^2\n    du[2] = -u[5] * u[2] + u[6] * (u[1] * u[2])\n\n    #encode uncertain params\n    du[3] = zero(u[1]) # p[1]\n    du[4] = zero(u[1]) # p[2]\n    du[5] = zero(u[1]) # p[3]\n    du[6] = zero(u[1]) # p[4]\n    du[7] = zero(u[1]) # p[5]\nend\n\np_int = (0.99..1.01) × (0.99..1.01) × (2.99..3.01) × (0.99..1.01) × (0.099..0.101)\nU0 = Singleton([1.0, 1.0]) × convert(Hyperrectangle, p_int)\nprob = @ivp(u' = f(u), dim: 7, u(0) ∈ U0);\n\nsol = solve(prob, tspan=(0.0, 10.0));\nsolz = overapproximate(sol, Zonotope);\n\nplot(solz, vars=(1, 2), lw=0.3, title=\"Uncertain params\", lab=\"abstol = 1e-15\", xlab=\"u1\", ylab=\"u2\")\n\nu0 = Singleton([1.0, 1.0])\n□(ϵ) = BallInf(zeros(2), ϵ)\nU0 = (u0 ⊕ □(0.05)) × convert(Hyperrectangle, p_int)\n\nprob = @ivp(u' = f(u), dim: 7, u(0) ∈ U0)\n\nsol = solve(prob, tspan=(0.0, 10.0), TMJets(abstol=1e-10))\nsolz = overapproximate(sol, Zonotope)\nplot(solz, vars=(1, 2), color=:orange, lw=0.3,\n     lab=\"eps = 0.05\", title=\"Uncertain u0 and uncertain params\",\n     xlab=\"u1\", ylab=\"u2\")\n\nU0 = (u0 ⊕ □(0.01)) × convert(Hyperrectangle, p_int)\nprob = @ivp(u' = f(u), dim: 7, u(0) ∈ U0)\n\nsol = solve(prob, tspan=(0.0, 10.0), TMJets(abstol=1e-10))\nsolz = overapproximate(sol, Zonotope)\nplot!(solz, vars=(1, 2), color=:blue, lw=0.3,\n  lab=\"eps = 0.01\", title=\"Uncertain u0 and uncertain params\",\n  xlab=\"u1\", ylab=\"u2\")\n\n", "meta": {"hexsha": "7970a753087f79c6827fcced5ccfd1deff9764b7", "size": 1959, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/models/LotkaVolterra.jl", "max_stars_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_stars_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-15T10:47:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-05T10:36:28.000Z", "max_issues_repo_path": "test/models/LotkaVolterra.jl", "max_issues_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_issues_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2020-01-14T18:26:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-29T07:57:50.000Z", "max_forks_repo_path": "test/models/LotkaVolterra.jl", "max_forks_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_forks_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-10T12:21:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-10T12:21:07.000Z", "avg_line_length": 31.5967741935, "max_line_length": 101, "alphanum_fraction": 0.5574272588, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7847035734406451}}
{"text": "\"\"\"\n        wpm(decisionMat, weights, fns)\n\nApply WPM (Weighted Product Method) for a given matrix and weights.\n\n# Arguments:\n - `decisionMat::DataFrame`: n × m matrix of objective values for n alterntives and m criteria \n - `weights::Array{Float64, 1}`: m-vector of weights that sum up to 1.0. If the sum of weights is not 1.0, it is automatically normalized.\n - `fns::Array{Function, 1}`: m-vector of functions to be applied on the columns. \n\n# Description \nwpm() applies the WPM method to rank n alterntives subject to m criteria which are supposed to be \neither maximized or minimized.\n\n# Output \n- `::WPMResult`: WPMResult object that holds multiple outputs including scores, rankings, and best index.\n\n# Examples\n```julia-repl\njulia> decmat = [3        12.5        2        120        14        3;\n       5        15        3        110        38        4;\n       3        13        2        120        19        3;\n       4        14        2        100        31        4;\n       3        15        1.5        125        40        4]\n5×6 Array{Float64,2}:\n 3.0  12.5  2.0  120.0  14.0  3.0\n 5.0  15.0  3.0  110.0  38.0  4.0\n 3.0  13.0  2.0  120.0  19.0  3.0\n 4.0  14.0  2.0  100.0  31.0  4.0\n 3.0  15.0  1.5  125.0  40.0  4.0\n\njulia> df = makeDecisionMatrix(decmat)\n5×6 DataFrame\n Row │ Crt1     Crt2     Crt3     Crt4     Crt5     Crt6    \n     │ Float64  Float64  Float64  Float64  Float64  Float64 \n─────┼──────────────────────────────────────────────────────\n   1 │     3.0     12.5      2.0    120.0     14.0      3.0\n   2 │     5.0     15.0      3.0    110.0     38.0      4.0\n   3 │     3.0     13.0      2.0    120.0     19.0      3.0\n   4 │     4.0     14.0      2.0    100.0     31.0      4.0\n   5 │     3.0     15.0      1.5    125.0     40.0      4.0\n\njulia> weights = [0.221, 0.159, 0.175, 0.127, 0.117, 0.201];\n\njulia> fns = [maximum, minimum, minimum, maximum, minimum, maximum];\n\njulia> result = wpm(df, weights, fns);\n\njulia> result.scores\n5-element Array{Float64,1}:\n 0.7975224331331252\n 0.7532541470584717\n 0.7647463553356331\n 0.7873956894790834\n 0.7674278741781709\n\njulia> result.bestIndex\n1\n```\n\n# References\nZavadskas, E. K., Turskis, Z., Antucheviciene, J., & Zakarevicius, A. (2012). Optimization of Weighted Aggregated Sum Product Assessment. Elektronika Ir Elektrotechnika, 122(6), 3-6. https://doi.org/10.5755/j01.eee.122.6.1810\n\"\"\"\nfunction wpm(decisionMat::DataFrame, weights::Array{Float64,1}, fns::Array{Function,1})::WPMResult\n   \n    row, col = size(decisionMat)\n    normalizedDecisionMat = similar(decisionMat)\n    w = unitize(weights)\n    colminmax = zeros(Float64, col)\n    @inbounds for i in 1:col\n        colminmax[i] = decisionMat[:, i] |> fns[i]\n        if fns[i] == maximum\n            normalizedDecisionMat[:, i] = decisionMat[:, i] ./ colminmax[i] \n        elseif fns[i] == minimum \n            normalizedDecisionMat[:, i] = colminmax[i] ./ decisionMat[:, i]\n        end\n    end    \n    scoreMat = similar(normalizedDecisionMat)\n    for i in 1:col\n        scoreMat[:, i] = normalizedDecisionMat[:, i].^w[i]\n    end\n\n    scores = zeros(Float64, row)\n    for i in 1:row\n        scores[i] = prod(scoreMat[i, :])\n    end\n    rankings = sortperm(scores)\n    \n    bestIndex = rankings |> last\n    \n    result = WPMResult(\n        decisionMat,\n        normalizedDecisionMat,\n        w,\n        scores,\n        rankings,\n        bestIndex\n    )\n\n    return result\nend\n\n\"\"\"\n        wpm(setting)\n\nApply WPM (Weighted Product Method) for a given matrix and weights.\n\n# Arguments:\n - `setting::MCDMSetting`: MCDMSetting object. \n\n# Description \nwpm() applies the WPM method to rank n alterntives subject to m criteria which are supposed to be \neither maximized or minimized.\n\n# Output \n- `::WPMResult`: WPMResult object that holds multiple outputs including scores, rankings, and best index.\n\"\"\"\nfunction wpm(setting::MCDMSetting)::WPMResult\n    wpm(\n        setting.df,\n        setting.weights,\n        setting.fns\n    )\nend ", "meta": {"hexsha": "854199200c99991a0dd069bd7c9a142955f5c38a", "size": 3965, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/wpm.jl", "max_stars_repo_name": "drvinceknight/JMcDM", "max_stars_repo_head_hexsha": "89bec7ead2a7553f9e58fc75f37b5b89a30582fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2021-02-09T17:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T22:21:26.000Z", "max_issues_repo_path": "src/wpm.jl", "max_issues_repo_name": "drvinceknight/JMcDM", "max_issues_repo_head_hexsha": "89bec7ead2a7553f9e58fc75f37b5b89a30582fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-02-09T16:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T18:11:34.000Z", "max_forks_repo_path": "src/wpm.jl", "max_forks_repo_name": "drvinceknight/JMcDM", "max_forks_repo_head_hexsha": "89bec7ead2a7553f9e58fc75f37b5b89a30582fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2021-02-12T16:01:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:02:44.000Z", "avg_line_length": 31.9758064516, "max_line_length": 225, "alphanum_fraction": 0.5861286255, "num_tokens": 1371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7847035699316791}}
{"text": "@doc raw\"\"\"\n    align(a⃗, b⃗, [w])\n\nSolve [Wahba's problem](https://en.wikipedia.org/wiki/Wahba%27s_problem),\nfinding a rotation that aligns the set of points `a⃗` to a corresponding set of\npoints `b⃗` by minimizing the distance between the first set and the rotated\nsecond set.\n\nHere, `a⃗` and `b⃗` must be equally sized arrays of `QuatVec`s.  If present, `w`\nmust be an equally sized array of real numbers; if not, it is taken to be 1.\nWe define the loss function\n```math\nL(ℛ) ≔ Σᵢ wᵢ ‖a⃗ᵢ - ℛ b⃗ᵢ‖²\n```\nwhere ``ℛ`` is a rotation operator, and return the quaternion corresponding to\nthe optimal ``ℛ`` that minimizes this function.\n\nNote that it is possible that the points do not uniquely determine a rotation —\nas when one or both sets of points is rotationally symmetric.  In that case, the\nloss function ``L(ℛ)`` will still be minimized and the points will still be\noptimally aligned by the output quaternion, but that quaternion will not be\nunique.\n\n\n# Notes\n\nIn their book [_Fundamentals of Spacecraft Attitude Determination and Control_\n(2014)](https://doi.org/10.1007/978-1-4939-0802-8), Markley and Crassidis say\nthat \"Davenport’s method remains the best method for solving Wahba’s problem\".\nThis method provides the optimal quaternion as the dominant eigenvector (the one\nwith the largest eigenvalue) of a certain matrix.  We start by defining the\nsupplementary matrix\n```math\nS ≔ Σᵢ wᵢ a⃗ᵢ b⃗ᵢᵀ\n```\nand vector\n```math\ns⃗ ≔ \\begin{bmatrix}\nS₂₃-S₃₂ \\\\\nS₃₁-S₁₃ \\\\\nS₁₂-S₂₁\n\\end{bmatrix}.\n```\nThen the key matrix is\n```math\nM ≔ \\begin{bmatrix}\nS + Sᵀ - (\\mathrm{tr}S)\\, I₃ & s⃗ \\\\\ns⃗ᵀ & \\mathrm{tr}S\n\\end{bmatrix}\n```\nIt is possible for this matrix to have degenerate eigenvalues, corresponding to\ncases where the points do not uniquely determine the rotation, as described\nabove.\n\n\"\"\"\nfunction align(a⃗::AbstractArray{<:QuatVec}, b⃗::AbstractArray{<:QuatVec}, w::AbstractArray{<:Real})\n    # This is Eq. (5.11) from Markley and Crassidis\n    S = sum(w[i] * a⃗[i].vec * b⃗[i].vec' for i in eachindex(a⃗, b⃗, w))\n    return _align_Wahba(S)\nend\n\nfunction align(a⃗::AbstractArray{<:QuatVec}, b⃗::AbstractArray{<:QuatVec})\n    # This is Eq. (5.11) from Markley and Crassidis\n    S = sum(a⃗[i].vec * b⃗[i].vec' for i in eachindex(a⃗, b⃗))\n    return _align_Wahba(S)\nend\n\nfunction _align_Wahba(S)\n    # This is Eq. (5.17) from Markley and Crassidis, modified to suit our\n    # conventions by flipping the sign of ``z``, and moving the final dimension\n    # to the first dimension.\n    M = Symmetric([\n            S[1,1]+S[2,2]+S[3,3]      S[3,2]-S[2,3]         S[1,3]-S[3,1]           S[2,1]-S[1,2]    \n                S[3,2]-S[2,3]      S[1,1]-S[2,2]-S[3,3]     S[1,2]+S[2,1]           S[1,3]+S[3,1]    \n                S[1,3]-S[3,1]         S[1,2]+S[2,1]      -S[1,1]+S[2,2]-S[3,3]      S[2,3]+S[3,2]    \n                S[2,1]-S[1,2]         S[1,3]+S[3,1]         S[2,3]+S[3,2]       -S[1,1]-S[2,2]+S[3,3]\n    ])\n    # This extracts the dominant eigenvector, and interprets it as a Rotor.  In\n    # particular, note that the _last_ eigenvector output by `eigen` (the 4th)\n    # has the largest eigenvalue.\n    return Rotor(eigen(M, 4:4).vectors[:, 1]...)\nend\n\n\n@doc raw\"\"\"\n    align(A, B, [w])\n\nFind a `Rotor` that aligns the set of rotors `A` to a corresponding set `B` by\nminimizing the distance between the first set and the rotated second set.\n\nHere, `A` and `B` must be equally sized arrays of `AbstractQuaternion`s.  If\npresent, `w` must be an equally sized array of real numbers; if not, it is\ntaken to be 1.  We define the loss function\n```math\nL(R) ≔ Σᵢ wᵢ |Aᵢ - R Bᵢ|²\n```\nwhere ``R`` is a `Rotor`, and return the quaternion corresponding to the optimal\n``R`` that minimizes this function.\n\nNote that it is possible that the input data do not uniquely determine a rotor,\nwhich will happen when sum below is zero.  When this happens, the result will\ncontain `NaN`s, but no error will be raised.  When the sum is very close to —\nbut not exactly — zero, the accuracy of the result will be limited.  However,\nthe loss function will not depend strongly on the result in that case.\n\nBe aware that this function _is_ sensitive to the signs of the input\nquaternions.  See the [`unflip`](@ref) function for one way to avoid problems\nrelated to signs.\n\n\n## Notes\n\nWe can ensure that the loss function is minimized by multiplying ``R`` by an\nexponential, differentiating with respect to the argument of the exponential,\nand setting that argument to 0.  This derivative should be 0 at the minimum.  We\nhave\n```math\n∂ⱼ Σᵢ wᵢ |Aᵢ - \\exp[vⱼ] R Bᵢ|²  →  2 ⟨ eⱼ R Σᵢ wᵢ Bᵢ Āᵢ ⟩₀\n```\nwhere → denotes taking ``vⱼ→0``, the symbol ``⟨⟩₀`` denotes taking the scalar\npart, and ``eⱼ`` is the unit quaternionic vector in the ``j`` direction.  The\nonly way for this quantity to be zero for each choice of ``j`` is if\n```math\nR Σᵢ wᵢ Bᵢ Āᵢ\n```\nis itself a pure scalar.  This, in turn, can only happen if either (1) the sum\nis 0 or (2) if ``R`` is proportional to the _conjugate_ of the sum:\n```math\nR ∝ Σᵢ wᵢ Aᵢ B̄ᵢ\n```\nNow, since we want ``R`` to be a rotor, we simply define it to be the normalized\nsum.\n\n\"\"\"\nfunction align(A, B, w)\n    Rotor(sum(w[i] * A[i] * conj(B[i]) for i in eachindex(A, B, w)))\nend\n\nfunction align(A, B)\n    Rotor(sum(A[i] * conj(B[i]) for i in eachindex(A, B)))\nend\n", "meta": {"hexsha": "85f273bb6ab58b4e1aae30caf0cb6f8284798858", "size": 5282, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/alignment.jl", "max_stars_repo_name": "moble/Quaternionic.jl", "max_stars_repo_head_hexsha": "e7bb501093141c3dc653325582c05b92eb57e3a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-06-26T17:12:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T15:42:20.000Z", "max_issues_repo_path": "src/alignment.jl", "max_issues_repo_name": "moble/Quaternionic.jl", "max_issues_repo_head_hexsha": "e7bb501093141c3dc653325582c05b92eb57e3a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2021-06-09T22:50:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T17:44:28.000Z", "max_forks_repo_path": "src/alignment.jl", "max_forks_repo_name": "moble/Quaternionic.jl", "max_forks_repo_head_hexsha": "e7bb501093141c3dc653325582c05b92eb57e3a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1971830986, "max_line_length": 101, "alphanum_fraction": 0.6707686482, "num_tokens": 1864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761565, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7847035594069902}}
{"text": "using LinearAlgebra\nusing ToeplitzMatrices\n\nfunction chebdif(N, M)\n\n    # The function x,DM = chebdif(N,M) computes the differentiation\n    # matrices D1, D2, ..., DM on Chebyshev nodes.\n    # It is adapted from the function with the same name in dmsuite\n    # developed for Matlab by JAC Weideman and SC Reddy.\n    #\n    # Adapted by M. Beneitez at KTH Mechanics.\n    # beneitez@mech.kth.se\n    #\n    # Input:\n    # N:  Size of the differentiation matrix.\n    # M:  Number of derivates required\n    # Note: 0 < M <= N-1.\n    #\n    # Output:\n    # DM: DM[1:N,1:N,ell] contains the ell-th derivative matrix, ell=1...M\n    #\n\n    eye = Matrix{Float64}(I, N, N);        # Identity matrix.\n\n    n1 = Int(floor(N/2)); n2  = Int(ceil(N/2));     # Indices used for flipping trick.\n\n    k = collect(0:N-1);                        # Compute theta vector.\n    th = k.*pi./(N-1)\n\n    x = sin.(pi.*collect(N-1:-2:1-N)./(2*(N-1))); # Compute Chebyshev points.\n\n    T = repeat(th/2,1,N);                \n    DX = 2*sin.(T'+T).*sin.(T'-T);          # Trigonometric identity. \n    DX = [DX[1:n1,:]; -reverse(reverse(DX[1:n2,:], dims = 2), dims=1)];   # Flipping trick. \n    DX[eye.==true] = ones(N,1);                      # Put 1's on the main diagonal of DX.\n\n    C = Matrix(Toeplitz((-1).^vec(k),(-1).^vec(k)));            # C is the matrix with \n    C[1,:] = C[1,:].*2; C[N,:] = C[N,:].*2;     # entries c[k]/c[j]\n    C[:,1] = C[:,1]/2; C[:,N] = C[:,N]/2\n\n    Z = 1 ./DX;                              # Z contains entries 1/(x[k]-x[j])  \n    Z[eye.==true] = zeros(N,1);              # with zeros on the diagonal.\n\n    D  = eye;                                 # D contains diff(). matrices.\n    DM = zeros(N,N,M);\n\n    for ell = 1:M\n        D = ell*Z.*(C.*repeat(diag(D),1,N) - D); # Off-diagonals\n        D[eye.==true] = -sum(D', dims = 1);                            # Correct main diagonal of D\n        DM[:,:,ell] = D;                                   # Store current D in DM\n    end\n\n    return x,DM\n    \nend\n", "meta": {"hexsha": "56156f5b4da7dbca6fc0be2d4edafa539c20e2f4", "size": 2003, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/hydro_cheb/chebdif.jl", "max_stars_repo_name": "harrymd/NonlinearEigenproblems.jl", "max_stars_repo_head_hexsha": "ffb050eb040dc22cb9c3c00c38da117b45ca7937", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2018-06-07T09:54:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T06:57:07.000Z", "max_issues_repo_path": "docs/src/hydro_cheb/chebdif.jl", "max_issues_repo_name": "harrymd/NonlinearEigenproblems.jl", "max_issues_repo_head_hexsha": "ffb050eb040dc22cb9c3c00c38da117b45ca7937", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 180, "max_issues_repo_issues_event_min_datetime": "2018-06-06T11:25:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T21:49:00.000Z", "max_forks_repo_path": "docs/src/hydro_cheb/chebdif.jl", "max_forks_repo_name": "harrymd/NonlinearEigenproblems.jl", "max_forks_repo_head_hexsha": "ffb050eb040dc22cb9c3c00c38da117b45ca7937", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2018-06-05T15:30:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T08:39:25.000Z", "avg_line_length": 35.7678571429, "max_line_length": 99, "alphanum_fraction": 0.4907638542, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7846707215033996}}
{"text": "function rat(x::AbstractFloat, tol::Real=eps(x))::Rational\n    p, q, pp, qq  = copysign(1,x), 0, 0, 1\n    x, y = abs(x), 1.0\n    r, a = modf(x)\n    nt, t, tt = tol, 0.0, tol\n\n    while r > nt        # convergents of the continued fraction: np//nq = (p*a + pp) // (q*a + qq)\n        np, nq = Int(a).*(p,q) .+ (pp,qq)\n        p, pp, q, qq = np, p, nq, q\n\n        x, y = y, r     # instead of the inexact 1/r...\n        a, r = divrem(x,y)\n\n        t, tt = nt, t   # maintain x = (p + (-1)^i * r) / q\n        nt = a*t+tt\n    end\n\n    i = Int(cld(x-tt,y+t))   # find optimal semiconvergent: smallest i such that x-i*y < i*t+tt\n    return (i*p+pp) // (i*q+qq)\nend\n", "meta": {"hexsha": "4a0f1cc60fb11cfb80b36a09b2fe56a7447b2ffc", "size": 658, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/convert-decimal-number-to-rational-2.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/convert-decimal-number-to-rational-2.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/convert-decimal-number-to-rational-2.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3333333333, "max_line_length": 98, "alphanum_fraction": 0.4741641337, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.784670712254027}}
{"text": "using LinearAlgebra\n\n\"\"\"\nGo from `X'Q*X + U'R*U`\ns.t. x+ = Ax+Bu\nto\n`U'F*U + 2U'*G*x(0) + x(0)'H*x(0)`\nand M,N, where X = M*U + N*x(0)\n\"\"\"\nfunction complact_form(A::AbstractArray{T}, B, Q, R, n) where T\n    nu = size(B,2)\n    nx = size(A,1)\n    M = zeros(T, n*nx, n*nu)\n    for i = 0:(n-1)\n        AiB = A^(i)*B\n        for j = 1:(n-i)\n            rows = (nx*(i+j-1)+1):(nx*(i+j))\n            cols = (nu*(j-1)+1):(nu*j)\n            M[rows, cols] .= AiB\n        end\n    end\n    N = vcat([A^i for i in 1:n]...)\n    # Blockdiag\n    Qn = vcat([[zeros(T, size(Q,1), size(Q,1)*i) Q zeros(T, size(Q,1), size(Q,1)*(n-i-1))]  for i = 0:(n-1)]...)\n    Rn = vcat([[zeros(T, size(R,1), size(R,1)*i) R zeros(T, size(R,1), size(R,1)*(n-i-1))]  for i = 0:(n-1)]...)\n    F = M'Qn*M + Rn\n    G = M'Qn*N\n    H = N'Qn*N\n    return F, G, H, M, N\nend\nT = Float64\nA = T.([0.999  -3.008  -0.113  -1.608  ;\n     0      0.986   0.048   0       ;\n     0      2.083   1.009   0       ;\n     0      0.053   0.05    1       ])\nB = T.([-0.080 -0.635  ;\n     -0.029 -0.014  ;\n     -0.868 -0.092  ;\n     -0.022 -0.002  ])\nQ = Matrix{T}(I,4,4)\nR = Matrix{T}(I,2,2)\nn = 10\nF, G, H, M, N = complact_form(A,B,Q,R,n)\n\nx0 = 0.2.*ones(4)\n\nnx = size(A, 1)\nnu = size(B, 2)\n\nxl = -0.2*ones(T, nx)\nxu = 0.2*ones(T, nx)\n\nXl = vcat([xl for i in 1:n]...)\nXu = vcat([xu for i in 1:n]...)\nUl = Xl - N*x0\nUu = Xu - N*x0\n\nUC = M\n\nusing QPDAS\nnU = nu*n\nz = G*x0\n@time qp = QuadraticProgram(zeros(T, 0, nU), zeros(T, 0), [UC;-UC], [Uu; -Ul], z, F, ϵ=1e-6, smartstart=true)\n\n@time sol, val = solve!(qp)\nval = val + 1/2*x0'H*x0\n\nX = M*sol + N*x0\nmaximum(abs, X) - 0.2\nmaximum([UC;-UC]*sol - [Uu; -Ul])\n1/2*sum(abs2, X) + 1/2*sum(abs2, sol)\n", "meta": {"hexsha": "28a9b17dd9d2e3fe6f7d99b18a6488174d972675", "size": 1686, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/mpc.jl", "max_stars_repo_name": "mfalt/QPDAS", "max_stars_repo_head_hexsha": "53d6ccd1dbf0fee029779fc60f2a374b86d1f080", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-03-28T18:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T14:33:37.000Z", "max_issues_repo_path": "examples/mpc.jl", "max_issues_repo_name": "mfalt/QPDAS", "max_issues_repo_head_hexsha": "53d6ccd1dbf0fee029779fc60f2a374b86d1f080", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-08-06T13:54:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-06T13:54:44.000Z", "max_forks_repo_path": "examples/mpc.jl", "max_forks_repo_name": "mfalt/QPDAS", "max_forks_repo_head_hexsha": "53d6ccd1dbf0fee029779fc60f2a374b86d1f080", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-09T14:05:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-09T14:05:53.000Z", "avg_line_length": 23.4166666667, "max_line_length": 112, "alphanum_fraction": 0.4620403321, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.784670711258945}}
{"text": "\"\"\"\n    Polynomial\n\none of functions mapping the set of real numbers is the algebraic polynomials, the set of functions of the form:\n``p_n(x) = a_n x^n + a_{n-1} x^{n-1} + ... +a_{1}x + a_0``\n- nth Larange interpolating polynomial\n- Neville’s Iterated Interpolation\n- Newton’s Divided-Difference Formula\n- Natural Cubic Spline\n- Clamped Cubic Spline\n\"\"\"\nmodule Polynomial\nusing SymPy\nusing LinearAlgebra\nusing Latexify\n\n@inline function product(x::Vector)\n    res = 1\n    for i in 1:size(x)[1]\n        res = res*x[i]\n    end\n    return res\nend\n\n\"\"\"\n    Lagrange(X::Vector, Y::Vector; a::String=\"x\")\n\nuse the ``(x_0, y_0), (x_1, y_1), ..., (x_n, y_n)``, to caculate a polynomial.\ninput X and Y, default use x to express functions.\noutput: function.\n\"\"\"\n@inline function Lagrange(X::Vector, Y::Vector; a::String=\"x\")\n    a = symbols(a)\n    m = size(X)[1]\n    A = ones(m) * X'\n    An = A - A'\n    An[An .== 0] .= 1\n    up = a .- X\n    upr = product(up)\n    sum = 0\n    for i in 1:m\n        down = product(An[:,i])\n        u = upr/up[i]\n        sum = sum + Y[i] * (u/down)\n    end\n    return simplify(sum)\nend\n\n\n\"\"\"\n    Neville(x::Vector, y::Vector, x₀::Real; tab::Bool=false)\n\ninput two vector, x and y. satisfy the function `y=f(x)`, then input x₀, which you want\nto  approximate f(x₀). The default tab setting is false, just output the estimate. you can set true\nto output a result table.\n\"\"\"\n@inline function Neville(x::Vector, y::Vector, x₀::Real; tab::Bool=false)\n    n, = size(x)\n    res = zeros(n, n)\n    for i in 1:n\n        res[i, 1] = y[i]\n    end\n    for i in 2:n\n        for j in 2:i\n            res[i,j] = ((x₀ - x[i-j+1])*res[i, j-1] - (x₀ - x[i])*res[i-1,j-1])/(x[i] - x[i-j+1])\n        end\n    end\n    if tab\n        return res\n    else\n        return res[n, n]\n    end\nend\n\n\"\"\"\n    NDDF(x::Vector, y::Vector; a::String=\"x\", simple::Bool=true, tab::Bool=false, backward::Bool=false)\n\ninput ``x_1, x_2, x_3, ...x_n```,values ``f(x_1), f(x_2), ...,f(x_n)``, set Args `simpel = true`\noutput simplify ans, set tab to output a table. set `backward=true` use the Newton Backward–Difference Formula.\n\"\"\"\n@inline function NDDF(x::Vector, y::Vector; a::String=\"x\", simple::Bool=true, tab=false, backward::Bool=false)\n    a = symbols(a)\n    n, = size(x)\n    res = zeros(n, n)\n    for i in 1:n\n        res[i,1] = y[i]\n    end\n    for i in 2:n\n        for j in 2:i\n            res[i,j] = (res[i, j-1] - res[i-1, j-1])/(x[i] - x[i-j+1])\n        end\n    end\n    sum = res[1,1]\n    for i in 2:n\n        p = 1\n        for j in 1:i-1\n            p = p*(a - x[j])\n        end\n        if backward\n            sum = sum + res[n, i]*p\n        else\n            sum = sum + res[i, i]*p\n        end\n    end\n    if tab\n        return res\n    else\n        if simple\n            return simplify(sum)\n        else\n            return sum\n        end\n    end\nend\n\n\"\"\"\n    NCSpline( NCSpline(x::Vector, y::Vector; Latex::Bool=false, a::String=\"t\")\ninput ``x_1, x_2, x_3, ...x_n```,values ``f(x_1), f(x_2), ...,f(x_n)``, set Args `Latex = true`  to\noutput information about the function.\n\"\"\"\n@inline function NCSpline(x::Vector, y::Vector; Latex::Bool=false, a::String=\"t\")\n    a = symbols(a)\n    n, = size(x)\n    h, α = zeros(n), zeros(n-1)\n\n    for i in 1:n-1\n        h[i] = x[i+1] - x[i]\n    end\n    for i in 2:n-1\n        α[i] = 3/h[i] * (y[i+1] - y[i]) - 3/h[i-1] *(y[i] - y[i-1])\n    end\n\n    l = ones(n)\n    μ = zeros(n)\n    z = zeros(n)\n\n    for i in 2:n-1\n        l[i] = 2*(x[i+1] - x[i-1]) - h[i-1]*μ[i-1]\n        μ[i] = h[i]/l[i]\n        z[i] = (α[i] - h[i-1]*z[i-1])/l[i]\n    end\n\n    c, b, d = zeros(n), zeros(n), zeros(n)\n    for j in reverse(1:n-1)\n        c[j] = z[j] - μ[j]*c[j+1]\n        b[j] = (y[j+1] - y[j])/h[j] - h[j]*(c[j+1]+2*c[j])/3\n        d[j] = (c[j+1] - c[j])/(3*h[j])\n    end\n    A = [b[1:end-1] c[1:end-1] d[1:end-1]]\n    X = []\n    for i in 2:4\n        for j in 1:3\n            push!(X,(a - x[i-1])^(j))\n        end\n    end\n    res = diag(A * reshape(X, (n-1,n-1))) + y[1:end-1]\n\n    if Latex\n        for i in 1:n-1\n            print(res[i], \",\",\"t ∈\",\"[$(x[i]), $(x[i+1])]\")\n            print(\"\\n\")\n\n        end\n    else\n        return res\n    end\nend\n\n\"\"\"\n    CCSpline(x::Vector, y::Vector, endpoint::Vector; Latex::Bool=false, a::String=\"t\")\n\ninput ``x_1, x_2, x_3, ...x_n```,values ``f(x_1), f(x_2), ...,f(x_n)`` and ``f'(x_1), f'(x_n)``, set Args `Latex = true`  to\noutput information about the function.\n\"\"\"\n@inline function CCSpline(x::Vector, y::Vector, endpoint::Vector; Latex::Bool=false, a::String=\"t\")\n    n, = size(x)\n    h = ones(n)\n    α = ones(n)\n    a = symbols(a)\n\n    for i in 1:n-1\n        h[i] = x[i+1] - x[i]\n    end\n    α[1] = 3(y[2] - y[1])/h[1] - 3*endpoint[1]\n    α[n] = 3*endpoint[2] - 3*(y[n] - y[n-1])/h[n-1]\n    for i in 2:n-1\n        α[i] = 3/h[i] * (y[i+1] - y[i]) - 3/h[i-1] *(y[i] - y[i-1])\n    end\n\n    l = ones(n)\n    l[1] = 2*h[1]\n    μ = fill(0.5, n)\n    z = fill(α[1]/l[1], n)\n    for i in 2:n-1\n        l[i] = 2*(x[i+1] - x[i-1]) - h[i-1]*μ[i-1]\n        μ[i] = h[i]/l[i]\n        z[i] = (α[i] - h[i-1]*z[i-1])/l[i]\n    end\n    l[n] = h[n-1]*(2 - μ[n-1])\n    z[n] = (α[n] - h[n-1]*z[n-1])/l[n]\n    c = fill(z[n], n)\n    b, d = zeros(n), zeros(n)\n    for j in reverse(1:n-1)\n        c[j] = z[j] - μ[j]*c[j+1]\n        b[j] = (y[j+1] - y[j])/h[j] - h[j]*(c[j+1]+2*c[j])/3\n        d[j] = (c[j+1] - c[j])/(3*h[j])\n    end\n    A = [b[1:end-1] c[1:end-1] d[1:end-1]]\n    X = []\n    for i in 2:4\n        for j in 1:3\n            push!(X,(a - x[i-1])^(j))\n        end\n    end\n    res = diag(A * reshape(X, (n-1,n-1))) + y[1:end-1]\n    if Latex\n        for i in 1:n-1\n            print(res[i], \",\",\"t ∈\",\"[$(x[i]), $(x[i+1])]\")\n            print(\"\\n\")\n\n        end\n    else\n        return res\n    end\n\nend\n\n\nend\n", "meta": {"hexsha": "29567a29c286dc4d9ef88ac5a61c9b6641f92637", "size": 5754, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Polynomial.jl", "max_stars_repo_name": "ZhouZhuofei/NumericalAnalysis.jl", "max_stars_repo_head_hexsha": "1e4926d6968fa72cc6ba102ad04052a77044351a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Polynomial.jl", "max_issues_repo_name": "ZhouZhuofei/NumericalAnalysis.jl", "max_issues_repo_head_hexsha": "1e4926d6968fa72cc6ba102ad04052a77044351a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-09-24T17:58:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-11T00:37:24.000Z", "max_forks_repo_path": "src/Polynomial.jl", "max_forks_repo_name": "ZhouZhuofei/NumericalAnalysis.jl", "max_forks_repo_head_hexsha": "1e4926d6968fa72cc6ba102ad04052a77044351a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0173913043, "max_line_length": 124, "alphanum_fraction": 0.4829683698, "num_tokens": 2217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7846433677778591}}
{"text": "function Euler2()\n\n\tFa = 1;\n\tFb = 1;\n\n\tsum = 0;\n\n\tF = 0;\n\n\twhile F<4e6\n\t\tF = Fa+Fb;\n\t\tFa = Fb;\n\t\tFb = F;\n\t\n\t\tif mod(F,2) == 0\n\t\t\tsum+=F\n\t\tend\n\tend\n\t\n\n\treturn sum\n\nend\n\n@time Euler2()\nprintln(Euler2())\t\n\t\n\t", "meta": {"hexsha": "8ee06df77c7d30add13d57011d72b7cc3e13a7e4", "size": 205, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/OldFiles/problem_2.jl", "max_stars_repo_name": "gribeill/ProjectEuler", "max_stars_repo_head_hexsha": "540b027394f191696f7fab59d4fc88501d5c971a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Julia/OldFiles/problem_2.jl", "max_issues_repo_name": "gribeill/ProjectEuler", "max_issues_repo_head_hexsha": "540b027394f191696f7fab59d4fc88501d5c971a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/OldFiles/problem_2.jl", "max_forks_repo_name": "gribeill/ProjectEuler", "max_forks_repo_head_hexsha": "540b027394f191696f7fab59d4fc88501d5c971a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 7.3214285714, "max_line_length": 18, "alphanum_fraction": 0.487804878, "num_tokens": 93, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7846433647096266}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots, LaTeXStrings\n\tRandom.seed!(0)\nend\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.18\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tprior(lam) = pdf(TriangularDist(0, 10, 3), lam)\n\tdata = [2,1,0,0,1,0,2,2,5,2,4,0,3,2,5,0]\n\n\tlike(lam) = *([pdf(Poisson(lam),x) for x in data]...)\n\tposteriorUpToK(lam) = like(lam)*prior(lam)\nend\n\n# ╔═╡ 2bd08a88-3afb-11eb-03e1-c3af32635947\nbegin\n\tdelta = 10^-4.\n\tlamRange = 0:delta:10\n\tK = sum([posteriorUpToK(lam)*delta for lam in lamRange])\n\tposterior(lam) = posteriorUpToK(lam)/K\nend\n\n# ╔═╡ 2bd0c412-3afb-11eb-1e28-27323df7bbe6\nbegin\n\tbayesEstimate = sum([lam*posterior(lam)*delta for lam in lamRange])\n\tText(\"Bayes estimate: $(bayesEstimate)\")\nend\n\n# ╔═╡ 2bd13636-3afb-11eb-3c12-2d5a0c0e4b13\nbegin\n\tplot(lamRange, prior.(lamRange), \n\t\tc=:blue, label=\"Prior distribution\")\n\tplot!(lamRange, posterior.(lamRange), \n\t\tc=:red, label=\"Posterior distribution\", \n\t\txlims=(0, 10), ylims=(0, 1.2),\n\t\txlabel=L\"\\lambda\",ylabel=\"Density\")\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.18\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═2bd08a88-3afb-11eb-03e1-c3af32635947\n# ╠═2bd0c412-3afb-11eb-1e28-27323df7bbe6\n# ╠═2bd13636-3afb-11eb-3c12-2d5a0c0e4b13\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "2ad807d380ea0a9b31b86a35f01025ad2433473b", "size": 1678, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/listing5.18.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/05/listing5.18.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/05/listing5.18.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.8153846154, "max_line_length": 68, "alphanum_fraction": 0.7187127533, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951607140232, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7846433594278184}}
{"text": "\"\"\"\n**RMSProp Optimizer**\n```julia\nRMSprop(; η::Real=0.001, γ::Real=0.01, ϵ::Real=1e-8)\n```\n\nAlgorithm\n\n```math\n\\\\begin{align*}\n    E[g^2]_t =& \\\\gamma E[g^2]_{t-1}+(1-\\\\gamma) g_t^2\\\\\\\\\n    \\\\Delta x_t =& \\\\frac{\\\\eta}{\\\\sqrt{E[g^2]_t + \\\\epsilon}}g_t\n\\\\end{align*}\n```\n    [Reference](http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)\n\"\"\"\nmutable struct RMSprop <: Optimizer\n    opt_type::String\n    t::Int64\n    ϵ::Float64\n    η::Float64\n    γ::Float64\n    E_g²_t::AbstractArray\nend\n\nfunction RMSprop(; η::Real=0.001, γ::Real=0.01, ϵ::Real=1e-8)\n    @assert η > 0.0 \"η must be greater than 0\"\n    @assert γ > 0.0 \"γ must be greater than 0\"\n    @assert ϵ > 0.0 \"ϵ must be greater than 0\"\n\n    RMSprop(\"RMSprop\", 0, ϵ, η, γ, [])\nend\n\nparams(opt::RMSprop) = \"ϵ=$(opt.ϵ), η=$(opt.η), γ=$(opt.γ)\"\n\nfunction update(opt::RMSprop, g_t::AbstractArray{T}) where {T<:Real}\n    # resize accumulated and squared updates\n    if opt.t == 0\n        opt.E_g²_t = zero(g_t)\n    end\n\n    # accumulate gradient\n    opt.E_g²_t = opt.γ * opt.E_g²_t + (one(T) - opt.γ) * (g_t .^ 2)\n\n    # compute update\n    RMS_g_t = sqrt.(opt.E_g²_t .+ opt.ϵ)\n    δ = opt.η * g_t ./ RMS_g_t\n\n    return δ\nend\n", "meta": {"hexsha": "c99265bbd85743c73f3caba1f4f5297e4510bc55", "size": 1197, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/RMSpropOptimizer.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_stars_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2017-08-20T00:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T03:09:32.000Z", "max_issues_repo_path": "src/RMSpropOptimizer.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_issues_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-11-19T22:38:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-25T20:33:14.000Z", "max_forks_repo_path": "src/RMSpropOptimizer.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_forks_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-08-03T16:14:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:48:41.000Z", "avg_line_length": 23.4705882353, "max_line_length": 88, "alphanum_fraction": 0.5914786967, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7846433590880888}}
{"text": "using Distributions\nusing Gadfly\nusing GSL\nusing PMTK4Stats\n\nαSS    = [20, 20]\nβSS    = [10, 10]\nαPrior = [20, 30]\nβPrior = [20, 10]\nM = 2\nmixprior = [0.5, 0.5]\nαPost      = αPrior + αSS\nβPost      = βPrior + βSS\n\nfunction mixBetaPost_()\n    logmarglik  = lbeta(αPrior+αSS, βPrior+βSS)-lbeta(αPrior, βPrior)\n    normPost, L = normalizeLogspace(logmarglik .+ log(mixprior))\n    mixpost     = exp(normPost)\nend\n\nfunction mixBetaDemo()\n    mixpost = mixBetaPost_()\n    grid = 0.0001:0.01:0.9999\n    \n    function evalpdf(θ, Z, α, β)\n        sum([Z[i].*pdf(Beta(α[i], β[i]), θ) for i=1:length(Z)])\n    end\n    \n    prior = evalpdf(grid, mixprior, αPrior, βPrior)\n    post  = evalpdf(grid, mixpost, αPost, βPost)\n    \n    lprior = layer(x=grid, y=prior, Geom.line, Theme(default_color=colorant\"red\", line_width=3px, line_style=Gadfly.get_stroke_vector(:dash)))\n    lpost  = layer(x=grid, y=post, Geom.line, Theme(default_color=colorant\"blue\", line_width=3px))\n    [lprior lpost]\nend\n\nfunction mixBetaBiased()\n    mixpost = mixBetaPost_()\n    pbiased = sum(mixpost.*(1-[sf_beta_inc(αPost[i], βPost[i], .5) for i=1:length(αPost)]))\n    pbiasedSimple = 1-sf_beta_inc(αPost[1], βPost[1], .5)\n    [pbiased, pbiasedSimple]\nend\n\n", "meta": {"hexsha": "5b2d0187a1f6912cce7886803b8724c5a0c0e375", "size": 1217, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BayesianStatistics/mixBetaDemo.jl", "max_stars_repo_name": "aoboturov/PMTK4BookDemos.jl", "max_stars_repo_head_hexsha": "f44853081139b358e0e9a2bb36a3d35ac35dcb39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-25T15:50:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-25T15:50:42.000Z", "max_issues_repo_path": "src/BayesianStatistics/mixBetaDemo.jl", "max_issues_repo_name": "aoboturov/PMTK4BookDemos.jl", "max_issues_repo_head_hexsha": "f44853081139b358e0e9a2bb36a3d35ac35dcb39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BayesianStatistics/mixBetaDemo.jl", "max_forks_repo_name": "aoboturov/PMTK4BookDemos.jl", "max_forks_repo_head_hexsha": "f44853081139b358e0e9a2bb36a3d35ac35dcb39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6590909091, "max_line_length": 142, "alphanum_fraction": 0.6516023007, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.784643357893702}}
{"text": "module RFIOD\r\nexport binarysearch, fixedpointiteration, staircasediagram\r\n\r\nusing Plots\r\n\r\n\"\"\"\r\n    binarysearch(f::Function, a::Real, b::Real, [ε::Real])\r\n\r\nUse the binary search algorithm to find a root of `f` between `a` and `b` with maximum trucation error `ε`.\r\n\r\nAlso returns the number of iterations that the algorithm takes.\r\n\r\n# Examples\r\n\r\n```julia-repl\r\njulia> binarysearch(sin,3,4)\r\n(3.141590118408203, 17)\r\n\r\njulia> abs(ans[1] - π) < 5e-6\r\ntrue\r\n```\r\n\"\"\"\r\nfunction binarysearch(f::Function, a::Real, b::Real, ε::Real = 5e-6)\r\n\r\n    # Checks that the initial interval is valid\r\n    fa, fb = f(a), f(b)\r\n    iszero(fa) && return (a,0)\r\n    iszero(fb) && return (b,0)\r\n    fa * fb < 0 || error(\"cannot find a root, function must take opposite signs on each end of the interval\")\r\n\r\n    # Iteratively finds the halfway point of the interval, then keeps the half where the sign of f changes\r\n    N = 0\r\n    while abs(b-a) > 2ε\r\n        N += 1\r\n        m = (a+b)/2\r\n        fm = f(m)\r\n        iszero(fm) && return (m,N)\r\n        (a, b, fa, fb) = ( fa * fm > 0 ? (m, b, fm, fb) : (a, m, fa, fm) )\r\n    end\r\n    # Returns the midpoint of the interval, which is within ε of the root\r\n    return ((a+b)/2,N)\r\n\r\nend\r\n\r\n\"\"\"\r\n    fixedpointiteration(f::Function, x₀::Real, Nₘₐₓ::Int, [ε::Real])\r\n\r\nUse the fixed point iteration algorithm to converge on a fixed point of `f`, with starting value `x₀`.\r\n\r\nTerminate if consecutive iterations differ by less than `ε`, or after `Nₘₐₓ` iterations.\r\n\r\nReturns the sequence resulting from the iteration.\r\n\r\n# Examples\r\n\r\n```julia-repl\r\njulia> xs = fixedpointiteration(cos, 0, 100)\r\n92-element Vector{Float64}:\r\n 0.0\r\n 1.0\r\n [...]\r\n 0.7390851332151607\r\n\r\njulia> cos(xs[end])\r\n0.7390851332151607\r\n```\r\n\"\"\"\r\nfunction fixedpointiteration(f::Function, x₀::Real, Nₘₐₓ::Int, ε::Real = eps(Float64))\r\n\r\n    # Sets up the initial values for the algorithm\r\n    n = 1\r\n    xₙ₋₁ = convert(Float64,x₀)\r\n    xₙ = f(xₙ₋₁)\r\n    xvalues = [xₙ₋₁, xₙ]\r\n\r\n    # Iteratively advances the algorithm by evaluating f at the previous result and storing it\r\n    while abs(xₙ₋₁ - xₙ) ≥ ε && n < Nₘₐₓ\r\n        n += 1\r\n        xₙ₋₁, xₙ = xₙ, f(xₙ)\r\n        push!(xvalues,xₙ)\r\n    end\r\n    # Returns the sequence resulting from the algorithm\r\n    return xvalues\r\n\r\nend\r\n\r\n\"\"\"\r\nstaircasediagram(f::Function, xvalues::Vector{Float64})\r\n\r\nCreate a staircase/cobweb diagram from `xvalues`, the results of the fixed point iteration algorithm on `f`.\r\n\r\n# Examples\r\n\r\n```julia-repl\r\njulia> staircasediagram(cos, fixedpointiteration(cos, 0, 100))\r\n```\r\n\"\"\"\r\nfunction staircasediagram(f::Function, xvalues::Vector{Float64})\r\n\r\n    # Finds the scale at which to draw the diagram\r\n    minx, maxx = min(xvalues...), max(xvalues...)\r\n    δ = (maxx - minx)/100\r\n    xticks = (minx - 10δ):δ:(maxx + 10δ)\r\n\r\n    # Plots y = x and y = f(x), then adds in a marker for the starting point and the lines given by the sequence\r\n    p = plot([x -> x, f], xticks, legend = false)\r\n    scatter!(p, (xvalues[1], xvalues[1]), markercolor = :black)\r\n    for n = 1:(length(xvalues)-1)\r\n        plot!(p, [xvalues[n], xvalues[n], xvalues[n+1]],\r\n            [xvalues[n], xvalues[n+1], xvalues[n+1]], linecolor = :black)\r\n    end\r\n    # Returns the plot\r\n    return p\r\n    \r\nend\r\n\r\nend", "meta": {"hexsha": "cdc7cfaae55e54a6824cdf3d7383d631ac9d3073", "size": 3267, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "introductoryproject/rfiod.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "introductoryproject/rfiod.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "introductoryproject/rfiod.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 27.9230769231, "max_line_length": 113, "alphanum_fraction": 0.6195286195, "num_tokens": 1029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7845651832763325}}
{"text": "function linsolve_cr( LF::LF3dGrid, b::Array{Float64,1};\n                      x0 = nothing,\n                      NiterMax = 1000, TOL=5.e-10,\n                      convmsg=false, showprogress=false )\n  #\n  Npoints = size(b)[1]\n  #\n  if x0 == nothing\n    x = zeros(Float64,Npoints)\n  else\n    x = copy(x0)\n  end\n  #\n  L_x = apply_Laplacian( LF, x )\n  #\n  r = b[:] - L_x[:]\n  p = r[:]\n\n  r_old = r[:]\n  p_old = p[:]\n  #\n  L_p = apply_Laplacian( LF, p )\n  x_old = x[:]\n  #\n  for iter = 1 : NiterMax\n    #\n    L_r = apply_Laplacian( LF, r )\n    #\n    rLr = dot( r, L_r )\n    α = rLr / dot( L_p, L_p )  # ???\n    #\n    x_old = x[:]\n    x[:] = x[:] + α * p[:]  # FIXME use x[:] to force x to be copied, not referenced\n    #\n    r_old = r[:]\n    rLr_old = rLr\n    r[:] = r[:] - α * L_p[:]\n    #\n    norm_res = sqrt( dot( r, r ) )\n    norm_p   = sqrt( dot( p, p ) )\n    Δx = abs(x-x_old)\n    norm_Δx = sqrt( dot( Δx, Δx ) )\n    if showprogress\n      @printf(\"%8d %18.10e %18.10e %18.10e\\n\", iter, norm_res, norm_p, norm_Δx)\n    end\n    #\n    if norm_res < TOL || norm_p < TOL || norm_Δx < TOL\n      if convmsg\n        @printf(\"#Convergence achieved in linsolve_cr: %8d iterations.\\n\", iter )\n      end\n      break\n    end\n    #\n    L_r = apply_Laplacian( LF, r ) # calculate new L_r\n    β = dot( r, L_r ) / rLr_old\n    #\n    p_old = p[:]\n    p = r[:] + β * p[:]\n    #\n    L_p = L_r[:] + β * L_p[:]\n  end\n  #\n  return x\n  #\nend # of function\n", "meta": {"hexsha": "f4e3375ebcef54640b2d4229ba40635a95341bc6", "size": 1435, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LF/v_0.4.5/LF_common/linsolve_cr.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "LF/v_0.4.5/LF_common/linsolve_cr.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LF/v_0.4.5/LF_common/linsolve_cr.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 21.7424242424, "max_line_length": 84, "alphanum_fraction": 0.4773519164, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.784565172757619}}
{"text": "module MonteCarlo\n\nusing Random\nusing Statistics\n\n# European Option Calculation from\n# https://groups.google.com/forum/?hl=en&fromgroups=#!topic/julia-dev/ImhGsqX_IHc\n\nfunction perf_euro_option_devec(npaths)\n    steps = 250\n    r = 0.05\n    sigma = .4\n    T = 1\n    dt = T/steps\n    K = 100\n    S = fill(100.0, npaths)\n    t1 = (r - 0.5*sigma^2)*dt\n    t2 = sigma*sqrt(dt)\n\n    for i=1:steps\n        for j=1:npaths\n            S[j] *= exp(t1 + t2 * randn())\n        end\n    end\n\n    return mean(exp(-r*T) .* max.(K .- S, 0))\nend\n\nfunction perf_euro_option_vec(npaths)\n    steps = 250\n    r = 0.05\n    sigma = .4\n    T = 1\n    dt = T/steps\n    K = 100\n    S = fill(100.0, npaths)\n    t1 = (r - 0.5*sigma^2)*dt\n    t2 = sigma*sqrt(dt)\n    R = Array{Float64}(undef, npaths)\n\n    for i=1:steps\n        S .*= exp.(t2 .* randn!(R) .+ t1)\n    end\n\n    return mean(exp(-r*T) .* max.(K .- S, 0))\nend\n\nend # module\n", "meta": {"hexsha": "46029e368fa5e09f0ce3f8195b0922ed24465510", "size": 905, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problem/MonteCarlo.jl", "max_stars_repo_name": "vilterp/BaseBenchmarks.jl", "max_stars_repo_head_hexsha": "8f68550ddc89311c53b3342f4241dc62a7d65990", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2016-05-11T11:20:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T20:44:39.000Z", "max_issues_repo_path": "src/problem/MonteCarlo.jl", "max_issues_repo_name": "vilterp/BaseBenchmarks.jl", "max_issues_repo_head_hexsha": "8f68550ddc89311c53b3342f4241dc62a7d65990", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 158, "max_issues_repo_issues_event_min_datetime": "2016-01-07T22:09:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T21:54:24.000Z", "max_forks_repo_path": "src/problem/MonteCarlo.jl", "max_forks_repo_name": "vilterp/BaseBenchmarks.jl", "max_forks_repo_head_hexsha": "8f68550ddc89311c53b3342f4241dc62a7d65990", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46, "max_forks_repo_forks_event_min_datetime": "2016-01-07T21:59:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T20:48:30.000Z", "avg_line_length": 18.4693877551, "max_line_length": 81, "alphanum_fraction": 0.5513812155, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7845566891053493}}
{"text": "# # Two-Stage Stochastic Program\n\n# ## Introduction\n# First let's consider a standard two-stage stochastic program. Such problems\n# consider 1st stage variables ``x \\in X \\subseteq \\mathbb{R}^{n_x}`` which denote\n# upfront (here-and-now) decisions made before any realization of the random\n# parameters ``\\xi \\in \\mathbb{R}^{n_\\xi}`` is observed, and 2nd stage variables\n# ``y(\\xi) \\in \\mathbb{R}^{n_y}`` which denote recourse (wait-and-see) decisions\n# that are made in response to realizations of ``\\xi``. Moreover, the objective\n# seeks to optimize 1st stage costs ``f_1(x)`` and second stage costs\n# ``f_2(x, y(\\xi))`` which are evaluated over the uncertain domain via a risk\n# measure ``R_\\xi[\\cdot]`` (e.g., the expectation ``\\mathbb{E}_\\xi[\\cdot]``).\n# Putting this together, we obtain the two-stage stochastic program:\n# ```math\n# \\begin{aligned}\n#     &&\\min_{x, y(\\xi)} &&& f_1(x) + R_\\xi[f_2(x, y(\\xi))] \\\\\n#     &&\\text{s.t.} &&&  g_i(x, y(\\xi)) = 0, && i \\in I\\\\\n#     &&&&& h_j(x, y(\\xi)) \\leq 0, && j \\in J\\\\\n#     &&&&&  x \\in X\\\\\n# \\end{aligned}\n# ```\n# where ``g_i(x, y(\\xi)), \\ i \\in I,`` denote 2nd stage equality constraints,\n# ``h_j(x, y(\\xi)), \\ j \\in J,`` are 2nd stage inequality constraints, and ``X``\n# denotes the set of feasible 1st stage decisions.\n\n# ## Formulation\n\n# For an example, we consider the classic farmer problem. Here the farmer must\n# allocate farmland ``x_c`` for each crop ``c \\in C`` with random yields per acre\n# ``\\xi_c`` such that he minimizes expenses (i.e., maximizes profit) while fulfilling\n# contractual demand ``d_c``. If needed he can purchase crops from other farmers\n# to satisfy his contracts. He can also sell extra crop yield that exceeds his\n# contractual obligations. Thus, here we have 1st stage variables ``x_c`` and\n# 2nd stage variables of crops sold ``w_c(\\xi)`` and crops purchased ``y_c(\\xi)``.\n# Putting this together using the expectation ``\\mathbb{E}_\\xi[\\cdot]`` as our\n# risk measure we obtain:\n# ```math\n# \\begin{aligned}\n#     &&\\underset{x, y(\\xi), w(\\xi)}{\\text{min}} &&& \\sum_{c \\in C} \\alpha_c x_c + \\mathbb{E}_{\\xi}\\left[\\sum_{c \\in C}\\beta_c y_c(\\xi) - \\lambda_c w_c(\\xi)\\right] \\\\\n#     &&\\text{s.t.} &&&  \\sum_{c \\in C} x_c \\leq \\bar{x}\\\\\n#     &&&&& \\xi_c x_c + y_c(\\xi) - w_c(\\xi) \\geq d_c, && c \\in C \\\\\n#     &&&&& 0 \\leq x_c \\leq \\bar{x}, && c \\in C \\\\\n#     &&&&& 0 \\leq y_c(\\xi) \\leq \\bar{y}_c, && c \\in C \\\\\n#     &&&&& 0 \\leq w_c(\\xi) \\leq \\bar{w}_c, && c \\in C \\\\\n#     &&&&& \\xi_c \\in \\Xi_c, && c \\in C\n# \\end{aligned}\n# ```\n# where ``\\alpha_c`` are production costs, ``\\beta_c`` are the purchase prices,\n# ``\\lambda_c`` are the selling prices, ``\\bar{x}`` is the total acreage,\n# ``\\bar{y}_c`` are purchases limits, ``\\bar{w}_c`` are selling limits, and\n# ``\\Xi_c`` are the underlying distributions.\n\n# ## Problem Setup\n\n# First let's import the necessary packages:\nusing InfiniteOpt, Distributions, Ipopt\n\n# Next let's specify the problem data:\nnum_scenarios = 10 # small amount for example\nC = 1:3\nα = [150, 230, 260] # land cost\nβ = [238, 210, 0]   # purchasing cost\nλ = [170, 150, 36]  # selling price\nd = [200, 240, 0]   # contract demand\nxbar = 500          # total land\nwbar3 = 6000        # no upper bound on the other crops\nybar3 = 0           # no upper bound on the other crops\nΞ = [Uniform(0, 5), Uniform(0, 5), Uniform(10, 30)]; # the distributions\n\n# ## Problem Definition\n\n# Let's start by setting up the infinite model that uses Ipopt as the optimizer \n# that will ultimately be used to solve the transcribed variant:\nmodel = InfiniteModel(Ipopt.Optimizer)\nset_optimizer_attribute(model, \"print_level\", 0);\n\n# Now let's define the infinite parameters using [`@infinite_parameter`](@ref):\n@infinite_parameter(model, ξ[c in C] ~ Ξ[c], num_supports = num_scenarios)\n\n# Now let's define all of the decision variables using `@variables`:\n@variables(model, begin \n    ## 1st stage variables\n    0 <= x[C] <= xbar\n    ## 2nd stage variables\n    0 <= y[C], Infinite(ξ)\n    0 <= w[C], Infinite(ξ)\nend)\n\n# Next, the objective is defined using `@objective` and [`𝔼`](@ref):\n@objective(model, Min, sum(α[c] * x[c] for c in C) +\n                       𝔼(sum(β[c] * y[c] - λ[c] * w[c] for c in C), ξ))\n\n# Finally, all we need to do is define the constraints using `@constraints`:\n@constraints(model, begin\n    ## capacity constraint\n    sum(x[c] for c in C) <= xbar\n    ## balances\n    [c in C], ξ[c] * x[c] + y[c] - w[c] >= d[c]\n    ## crop limits\n    w[3] <= wbar3\n    y[3] <= ybar3\nend)\n\n# ## Problem Solution\n\n# With the model defined, let's optimize and get the results\noptimize!(model)\nx_opt = value.(x)\nprofit = -objective_value(model)\n\nprintln(\"Land Allocations: \", [round(x_opt[k], digits = 2) for k in keys(x_opt)])\nprintln(\"Expected Profit: \\$\", round(profit, digits = 2))\n\n# We did it! \n\n# ## CVaR Objective\n\n# An interesting modification to the above problem would be to use a ``CVaR`` \n# risk measure instead of an expectation. This also can be readily achieved via \n# `InfiniteOpt`. The ``CVaR`` measure is defined:\n# ```math\n# CVaR_\\epsilon(X) = \\underset{t \\in \\mathbb{R}}{\\text{inf}}\\left\\{t + \\frac{1}{1-\\epsilon} \\mathbb{E}[\\text{max}(0, X - t)] \\right\\}\n# ```\n# where ``\\epsilon`` is the confidence level. Inserting this into the formulation,\n# we now obtain:\n# ```math\n# \\begin{aligned}\n#     &&\\underset{x, y(\\xi), w(\\xi), t, q(\\xi)}{\\text{min}} &&& \\sum_{c \\in C} \\alpha_c x_c + t + \\frac{1}{1-\\epsilon} \\mathbb{E}_{\\xi}[q(\\xi)] \\\\\n#     &&\\text{s.t.} &&& \\sum_{c \\in C} x_c \\leq \\bar{x}\\\\\n#     &&&&& \\xi_c x_c + y_c(\\xi) - w_c(\\xi) \\geq d_c, && c \\in C \\\\\n#     &&&&& 0 \\leq x_c \\leq \\bar{x}, && c \\in C \\\\\n#     &&&&& 0 \\leq y_c(\\xi) \\leq \\bar{y}_c, && c \\in C \\\\\n#     &&&&& 0 \\leq w_c(\\xi) \\leq \\bar{w}_c, && c \\in C \\\\\n#     &&&&& \\xi_c \\in \\Xi_c, && c \\in C \\\\\n#     &&&&& q(\\xi) \\geq \\sum_{c \\in C}\\beta_c y_c(\\xi) - \\lambda_c w_c(\\xi) - t \\\\\n#     &&&&& q(\\xi) \\geq 0\n# \\end{aligned}\n# ```\n# where ``q(\\xi)`` is introduced to handle the max operator. Let's update and\n# resolve our `InfiniteOpt` model using ``\\epsilon = 0.95``:\n\n# Define the additional variables:\n@variables(model, begin \n    t\n    q >= 0, Infinite(ξ)\nend)\n\n# Redefine the objective:\n@objective(model, Min, sum(α[c] * x[c] for c in C) + t + 1 / (1 - 0.95) * 𝔼(q, ξ))\n\n# Add the max constraint:\n@constraint(model, q >= sum(β[c] * y[c] - λ[c] * w[c] for c in C) - t)\n\n# Optimize and get the results\noptimize!(model)\nx_opt = value.(x)\ny_opt = value.(y)\nw_opt = value.(w)\nprofit = -sum(α[c] * x_opt[c] for c in C) - 1 / num_scenarios *\n            sum(β[c] * y_opt[c][k] - λ[c] * w_opt[c][k] for c in C, k in 1:num_scenarios)\n\nprintln(\"Land Allocations: \", [round(x_opt[k], digits = 2) for k in keys(x_opt)])\nprintln(\"Expected Profit: \\$\", round(profit, digits = 2))\n\n# That's it!\n\n# ### Maintenance Tests\n# These are here to ensure this example stays up to date. \nusing Test\n@test termination_status(model) == MOI.LOCALLY_SOLVED\n@test x_opt isa JuMPC.DenseAxisArray{<:Real}\n@test profit isa Real\n", "meta": {"hexsha": "e2164cc6018874f1a902573a324052d55b260f47", "size": 6994, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/Stochastic Optimization/farmer.jl", "max_stars_repo_name": "bdaves12/InfiniteOpt.jl", "max_stars_repo_head_hexsha": "85e170ac1c749d9e3e21b2f9c9db32ccf99cc5ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 128, "max_stars_repo_stars_event_min_datetime": "2020-03-03T07:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T18:27:13.000Z", "max_issues_repo_path": "docs/src/examples/Stochastic Optimization/farmer.jl", "max_issues_repo_name": "bdaves12/InfiniteOpt.jl", "max_issues_repo_head_hexsha": "85e170ac1c749d9e3e21b2f9c9db32ccf99cc5ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 204, "max_issues_repo_issues_event_min_datetime": "2019-10-02T17:04:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T14:27:11.000Z", "max_forks_repo_path": "docs/src/examples/Stochastic Optimization/farmer.jl", "max_forks_repo_name": "bdaves12/InfiniteOpt.jl", "max_forks_repo_head_hexsha": "85e170ac1c749d9e3e21b2f9c9db32ccf99cc5ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-09-04T00:05:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:49:35.000Z", "avg_line_length": 40.4277456647, "max_line_length": 166, "alphanum_fraction": 0.6191020875, "num_tokens": 2381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7845566873513914}}
{"text": "#! /usr/bin/julia\n\n# Rosetta Code, Digital root/Multiplicative digital root\n\nconst bs = 10\nconst excnt = 5\n\nfunction digitalmultroot{S<:Integer,T<:Integer}(n::S, bs::T=10)\n    -1 < n && 1 < bs || throw(DomainError())\n    ds = n\n    pers = 0\n    while bs <= ds\n        ds = prod(digits(ds, bs))\n        pers += 1\n    end\n    return (pers, ds)\nend\n\nprintln(\"Testing Multiplicative Digital Root.\\n\")\nfor i in [123321, 7739, 893, 899998]\n    (pers, ds) = digitalmultroot(i, bs)\n    print(@sprintf(\"%8d\", i))\n    print(\" has persistence \", pers)\n    println(\" and digital root \", ds)\nend\n\ndmr = zeros(Int, bs, excnt)\nhasroom = trues(bs)\ndex = ones(Int, bs)\n\ni = 0\nwhile any(hasroom)\n    (pers, ds) = digitalmultroot(i, bs)\n    ds += 1\n    if hasroom[ds]\n        dmr[ds, dex[ds]] = i\n        dex[ds] += 1\n        if dex[ds] > excnt\n            hasroom[ds] = false\n        end\n    end\n    i += 1\nend\n\nprintln(\"\\n MDR:    First \", excnt, \" numbers having this MDR\")\nfor (i, d) in enumerate(0:(bs-1))\n    print(@sprintf(\"%4d: \", d))\n    println(join([@sprintf(\"%6d\", dmr[i, j]) for j in 1:excnt], \",\"))\nend\n", "meta": {"hexsha": "3ff9847ea3f064fcc8382db19b50e8beeddf29a8", "size": 1098, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/completed/digital_root_mult.jl", "max_stars_repo_name": "MichaeLeroy/rosetta-code", "max_stars_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/completed/digital_root_mult.jl", "max_issues_repo_name": "MichaeLeroy/rosetta-code", "max_issues_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/completed/digital_root_mult.jl", "max_forks_repo_name": "MichaeLeroy/rosetta-code", "max_forks_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.96, "max_line_length": 69, "alphanum_fraction": 0.5673952641, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7845566801990289}}
{"text": "# This file calculates the third application in Y.-S. Chan, A. C. Fannjiang, and G. H. Paulino,\n# Integral equations with hypersingular kernels -- theory and applications to fracture mechanics,\n# Int. J. Eng. Sci., 41:683--720, 2003.\n\nusing ApproxFun, SingularIntegralEquations\n\n\nx = Fun(identity)\nw = 1/sqrt(1-x^2)\nd = domain(x)\nd2 = d^2\nB = [Dirichlet(d);Neumann(d)]\nH2 = Hilbert(d,2)\nH4 = Hilbert(d,4)\nϵ = 0.2\nL = -6ϵ^2*H4[w] + H2[w]\nf = -Fun(one)\n\nuSIE = [B;L]\\[[0,0],[0,0],f]\n@time uSIE = [B;L]\\[[0,0],[0,0],f]\nprintln(\"The length of uSIE is: \",ncoefficients(uSIE))\nprintln(\"The extrema of uSIE are: \",extrema(uSIE))\n\ntest0 = uSIE/(1-x^2)^2\ntest = Fun(x->test0(x),Ultraspherical(1,d))\ntemp = 0.0\nfor i=1:ncoefficients(test)\n    temp += i*test.coefficients[i]\nend\nprintln(\"The normalized generalized Stress Intensity Factors are: \",3ϵ*temp)\n", "meta": {"hexsha": "bb9799df7a9876c934a02d7507c01d42f6b8503c", "size": 845, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Fracture_c.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SingularIntegralEquations.jl-e094c991-5a90-5477-8896-c1e4c9552a1a", "max_stars_repo_head_hexsha": "8a0ca7376ecad020ef8f8beca90686311fbb9f84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2016-12-02T13:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T18:31:48.000Z", "max_issues_repo_path": "examples/Fracture_c.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SingularIntegralEquations.jl-e094c991-5a90-5477-8896-c1e4c9552a1a", "max_issues_repo_head_hexsha": "8a0ca7376ecad020ef8f8beca90686311fbb9f84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2016-12-19T06:02:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:33:33.000Z", "max_forks_repo_path": "examples/Fracture_c.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SingularIntegralEquations.jl-e094c991-5a90-5477-8896-c1e4c9552a1a", "max_forks_repo_head_hexsha": "8a0ca7376ecad020ef8f8beca90686311fbb9f84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-05-16T06:08:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:20:46.000Z", "avg_line_length": 27.2580645161, "max_line_length": 97, "alphanum_fraction": 0.6698224852, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939024825960626, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.784539790714677}}
{"text": "@doc raw\"\"\"\r\n```\r\nt = find_threshold(Yen(), histogram, edges)\r\n```\r\n\r\nComputes the threshold value using Yen's maximum correlation criterion for\r\nbilevel thresholding.\r\n\r\n# Output\r\n\r\nReturns a real number `t` in `edges`. The `edges` parameter represents an\r\n`AbstractRange` which specifies the intervals associated with the histogram bins.\r\n\r\n\r\n# Details\r\n\r\nThis algorithm uses the concept of *entropic correlation* of a gray level histogram to produce a threshold\r\nvalue.\r\n\r\nLet ``f_1, f_2, \\ldots, f_I`` be the frequencies in the various bins of the\r\nhistogram and ``I`` the number of bins. With ``N = \\sum_{i=1}^{I}f_i``, let\r\n``p_i = \\frac{f_i}{N}`` (``i = 1, \\ldots, I``) denote the probability\r\ndistribution of gray levels. From this distribution one derives two additional\r\ndistributions. The first defined for discrete values ``1`` to ``s`` and the\r\nother, from ``s+1`` to ``I``. These distributions are\r\n\r\n```math\r\nA: \\frac{p_1}{P_s}, \\frac{p_2}{P_s}, \\ldots, \\frac{p_s}{P_s}\r\n\\quad \\text{and} \\quad\r\nB: \\frac{p_{s+1}}{1-P_s}, \\ldots, \\frac{p_n}{1-P_s}\r\n\\quad \\text{where} \\quad\r\nP_s = \\sum_{i=1}^{s}p_i.\r\n```\r\nThe entropic correlations associated with each distribution are\r\n\r\n```math\r\nC(A) = -\\ln \\sum_{i=1}^{s} \\left( \\frac{p_i}{P_s} \\right)^2 \\quad \\text{and} \\quad C(B) = -\\ln \\sum_{i=s+1}^{I} \\left( \\frac{p_i}{1 - P_s} \\right)^2.\r\n```\r\n\r\nCombining these two entropic correlation functions we have\r\n\r\n```math\r\n\\psi(s) = -\\ln \\sum_{i=1}^{s} \\left( \\frac{p_i}{P_s} \\right)^2 -\\ln \\sum_{i=s+1}^{I} \\left( \\frac{p_i}{1 - P_s} \\right)^2.\r\n```\r\nFinding the discrete value ``s`` which maximises the function ``\\psi(s)`` produces\r\nthe sought-after threshold value (i.e. the bin which determines the threshold).\r\n\r\n# Arguments\r\n\r\nThe function arguments are described in more detail below.\r\n\r\n##  `histogram`\r\n\r\nAn `AbstractArray` storing the frequency distribution.\r\n\r\n##  `edges`\r\n\r\nAn `AbstractRange` specifying how the intervals for the frequency distribution\r\nare divided.\r\n\r\n# Example\r\n\r\nCompute the threshold for the \"cameraman\" image in the `TestImages` package.\r\n\r\n```julia\r\n\r\nusing TestImages, ImageContrastAdjustment, HistogramThresholding\r\n\r\nimg = testimage(\"cameraman\")\r\nedges, counts = build_histogram(img, 256)\r\n#=\r\n  The `counts` array stores at index 0 the frequencies that were below the\r\n  first bin edge. Since we are seeking a threshold over the interval\r\n  partitioned by `edges` we need to discard the first bin in `counts`\r\n  so that the dimensions of `edges` and `counts` match.\r\n=#\r\nt = find_threshold(Yen(), counts[1:end], edges)\r\n```\r\n\r\n# Reference\r\n\r\n1. Yen JC, Chang FJ, Chang S (1995), “A New Criterion for Automatic Multilevel Thresholding”, IEEE Trans. on Image Processing 4 (3): 370-378, [doi:10.1109/83.366472](https://doi.org/10.1109/83.366472)\r\n\"\"\"\r\nfunction find_threshold(algorithm::Yen, histogram::AbstractArray, edges::AbstractRange)\r\n    total = sum(histogram)\r\n    m = length(histogram)\r\n    p = zeros(m)\r\n\r\n    # Calulate probability.\r\n    for i in eachindex(p)\r\n        p[i] = histogram[i] / total\r\n    end\r\n\r\n    # Setup sums.\r\n    Pₛ = 0\r\n    Gₛ = 0\r\n    G′ₛ = sum(p.^2)\r\n    maxval = typemin(Float64)\r\n    t = firstindex(edges)\r\n    for s in eachindex(p[1:m-1])\r\n        # Update sums.\r\n        Pₛ += p[s]\r\n        Gₛ += p[s]^2\r\n        G′ₛ -= p[s]^2\r\n\r\n        # Calculate total correlation.\r\n        TC = -log(Gₛ * G′ₛ) + 2 * log(Pₛ * (1 - Pₛ))\r\n        if TC > maxval\r\n            maxval = TC\r\n            t = s\r\n        end\r\n    end\r\n\r\n    return edges[t]\r\nend\r\n", "meta": {"hexsha": "aa794ea7420290914707a139a8531a9c30319812", "size": 3519, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/yen.jl", "max_stars_repo_name": "mkitti/HistogramThresholding.jl", "max_stars_repo_head_hexsha": "dff64b67820f2c4c8fbe6c810cb3f6d80ffdcccd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-01-07T18:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-10T09:10:19.000Z", "max_issues_repo_path": "src/yen.jl", "max_issues_repo_name": "mkitti/HistogramThresholding.jl", "max_issues_repo_head_hexsha": "dff64b67820f2c4c8fbe6c810cb3f6d80ffdcccd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2019-01-07T05:43:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-24T04:03:55.000Z", "max_forks_repo_path": "src/yen.jl", "max_forks_repo_name": "mkitti/HistogramThresholding.jl", "max_forks_repo_head_hexsha": "dff64b67820f2c4c8fbe6c810cb3f6d80ffdcccd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-01-05T02:39:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T20:13:12.000Z", "avg_line_length": 30.3362068966, "max_line_length": 201, "alphanum_fraction": 0.6447854504, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7845397773188543}}
{"text": "@doc \"\"\"\n\nCalculates dfgls point optimal unit-root test statistic of Elliott, Rothenberg, and Stock (1996) value of the largest autorregressive coefficient under the alternative hypothesis given by ρ = 1+c/T, where c=-7 if trend=\"constant\" and c=-13.5 if trend=\"linear\")\n\n\"\"\"->\nfunction dfgls_test(y::Vector{Float64}; nar::Integer=5, trend::String=\"constant\")\n  #rewrite of mw's dfgls.prc\n  t = length(y)\n  dftau = NaN*zeros(1, 2)\n\n  # @ -- GLS estimate of constant term -- @\n  c = -7\n  rho = (1+c/t)\n  yrho = [y[1]; y[2:t]-rho*y[1:t-1]] #@ Quasi Differenced Y series @\n  xcrho = [1.0; (1-rho)*ones(t-1)] #@ Quasi Difference Constant @\n  mu = ((xcrho'*xcrho).^(-1)).*(xcrho'yrho)\n\n  c = -13.5\n  rho = (1+c/t)\n  yrho = [y[1]; y[2:t]-rho*y[1:t-1]] #@ Quasi Differenced Y series @\n  xcrho = [1.0; (1-rho)*ones(t-1)] #@ Quasi Difference Constant @\n  trnd = collect(1:t)\n  xtrho = [trnd[1]; trnd[2:t]-rho*trnd[1:t-1]]\n  x = [xcrho xtrho]\n  mut = inv(x'x)*(x'yrho)\n  #  @ -- detrend y -- @\n  y1 = y - mu.*ones(t)                #@ GLS Demeaned @\n  y2 = y - [ones(t,1) trnd]*mut        #@ GLS Detrended @\n  dy1 = diff(y1)\n  dy2 = diff(y2)\n  #compute adf\n  x1 = ar_lagmatrix(dy1, nar)\n  x2 = ar_lagmatrix(dy2, nar)\n\n  z = [y1[1:size(x1,1)] x1]\n  y = z[:, 1]\n  x = z[:, 2:end]\n  xxi = inv(x'x)\n  xy = x'y\n  bet = xxi*xy\n  ssr = (y'y)-(xy)'bet\n  s2 = ssr/(size(y,1)-size(x,2))\n  b = bet[1]\n  vb = s2.*xxi[1,1]\n  dfmu = (b-1)./sqrt(vb)\n\n  z = [y1[1:size(x1,1)] x1]\n  y = z[:, 1]\n  x = z[:, 2:end]\n  xxi = inv(x'x)\n  xy = x'y\n  bet = xxi*xy\n  ssr = (y'y)-(xy)'bet\n  s2 = ssr/(size(y,1)-size(x,2))\n  b = bet[1]\n  vb = s2.*xxi[1,1]\n  dftau = (b-1)./sqrt(vb)\n  (trend==\"constant\") && return dfmu[1]\n  (trend==\"linear\") && return dftau[1]\n  (trend==\"both\") && return dfmu[1], dftau[1]\n  end\n", "meta": {"hexsha": "5b9494ea9df724151f12d666a7f0d63e6f103850", "size": 1775, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dfgls.jl", "max_stars_repo_name": "p-chaim/unitroot.jl", "max_stars_repo_head_hexsha": "8dca2b72aec7a2ea43336a7796ef0b5e58c62460", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dfgls.jl", "max_issues_repo_name": "p-chaim/unitroot.jl", "max_issues_repo_head_hexsha": "8dca2b72aec7a2ea43336a7796ef0b5e58c62460", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dfgls.jl", "max_forks_repo_name": "p-chaim/unitroot.jl", "max_forks_repo_head_hexsha": "8dca2b72aec7a2ea43336a7796ef0b5e58c62460", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-24T22:22:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-24T22:22:36.000Z", "avg_line_length": 28.6290322581, "max_line_length": 260, "alphanum_fraction": 0.5577464789, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350351, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7845397715489885}}
{"text": "# chebyshev points and chebyshev differentiation matrix \n# Ref: Spectral methods in MATLAB by Trefethen, chapters 1, 5 and 6.\nfunction cheb_pts(n)\n\treturn cos.((0:n)*pi/n)\nend\nfunction cheb_diff_matrix(n)\n\tx = cheb_pts(n)\n\tnp = n+1\n\tD = zeros(np,np)\n\tE = view(D, reverse(1:np*np))\n\tD[1] = (2*n*n + 1)/6.\n\tE[1] = -D[1]\n\n\n\tnhalf = fld(np, 2)\n\txint = view(x,2:n)\n\tD[2:n] .= (-1).^(1:n-1)./(xint .- 1)./2.0\n\tE[2:n] .= -D[2:n]\n\tD[np] = (-1)^np/2.0\n\tE[np] = -D[np]\n\n\tif mod(np,2) != 0\n\t\tj = nhalf + 1\n\t\tA = view(D, (j-1)*np+1:j*np)\n\t\tA .=  1.0./(x .- x[j]).*\n\t\t((-1).^((1 + j):(np + j)))\n\t\tA[j] = -x[j]/2/(1. - x[j]*x[j])\n\t\tA[1] *= 2.0\n\t\tA[np] *= 2.0\n\tend\n\t\n\tfor j=2:nhalf\n\t\tA = view(D, (j-1)*np+1:j*np)\n\t\tB = view(E, (j-1)*np+1:j*np)\n\t\tA .= 1.0./(x .- x[j]).*\n\t\t((-1).^((1 + j):(np + j)))\n\t\tB .= -A\n\t\tA[1] *= 2.0\n\t\tB[1] *= 2.0\n\t\tA[j] = -x[j]/2/(1. - x[j]*x[j])\n\t\tB[j] = -A[j]\n\t\tA[np] *= 2.0\n\t\tB[np] *= 2.0\n\tend\n\t\n\treturn D\nend\n", "meta": {"hexsha": "9d9f4eebe5b035aaedc27106f3cebd517f0afe6f", "size": 922, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/cheb.jl", "max_stars_repo_name": "nishaChandramoorthy/energies", "max_stars_repo_head_hexsha": "17ffd87a976b9a6d23089fc182e16102bf4607c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-24T22:32:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-24T22:32:31.000Z", "max_issues_repo_path": "examples/cheb.jl", "max_issues_repo_name": "nishaChandramoorthy/energies", "max_issues_repo_head_hexsha": "17ffd87a976b9a6d23089fc182e16102bf4607c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/cheb.jl", "max_forks_repo_name": "nishaChandramoorthy/energies", "max_forks_repo_head_hexsha": "17ffd87a976b9a6d23089fc182e16102bf4607c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2083333333, "max_line_length": 68, "alphanum_fraction": 0.464208243, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7845397701233213}}
{"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\n\n\"This routine solves the heat equation using Backwards Euler in time and finite differences\nin space. The output is saved as a .gif file (which should play automatically when this file is run).\"\n\nm = 100 # number of points\ndt = .01 # time-step\nT = 2.0\n\nu0(x) = 0.0 # initial condition\nf(x) = 5*(Float64((x > -.5) && (x <= 0.0)) - Float64((x < .5) && (x >= 0.0)))\nf(x,t) = f(x)*exp(-t)\nα(t) = 1.0\nβ(t) = sin(2*pi*t) # du/dx\n\n# define spatial grid\nx = LinRange(-1,1,m+2)\nxint = x[2:end-1]\nh = x[2]-x[1]\nA = (1/h^2) * spdiagm(0=>2*ones(m),-1=>-ones(m-1),1=>-ones(m-1))\n\nfunction F(xint,t)\n    b = f.(xint,t)\n    b[1] += α(t)/h^2\n    b[end] += β(t)/h^2\n    return b\nend\n\nu = u0.(xint)\nNsteps = ceil(Int,T/dt)\ndt = T / Nsteps\n\ninterval = 2\n@gif for i = 1:Nsteps\n    t = (i+1)*dt\n    u .= (I + dt*A)\\(u + dt*F(xint,t))\n    if i % interval == 0 # % = mod function\n        plot(xint,u,linewidth=2,label=\"Solution\",ylims=(-1.0,3.0))\n        println(\"on timestep $i out of $Nsteps.\")\n    end\nend every interval\n", "meta": {"hexsha": "5bfe1b609475e12e099bd00239268fc6e07e02f8", "size": 1053, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week3/fd_heat_backward_euler.jl", "max_stars_repo_name": "jlchan/caam452_s21", "max_stars_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:38:43.000Z", "max_issues_repo_path": "week3/fd_heat_backward_euler.jl", "max_issues_repo_name": "jlchan/caam452_s21", "max_issues_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week3/fd_heat_backward_euler.jl", "max_forks_repo_name": "jlchan/caam452_s21", "max_forks_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9318181818, "max_line_length": 102, "alphanum_fraction": 0.584045584, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7844959665898393}}
{"text": "# src/secondorder.jl contains function for solving second order ODEs\n# can use either numerical integration or closed for formulas\n# secondorder(a,b,c) generates the function you pass to ODE.jl RK methods\n# solution(a,b,c) is the closed form solver\n# ivp solves the initial value problem.\nusing Optim\nusing NLsolve\n\n\"\"\" secondorder(α,β,γ) yields a function f\n    which calculates the ode rule\n\n        αx'' + βx' + γx = 0\n\n    using the substitution\n\n        y = [x; x']\n\n        y[1]' = y[2]\n\n        y[2]' = -α^-1 (βy[2] + γy[1])\n\n\"\"\"\nfunction secondorder(α, β, γ)\n        return (t, y) -> [y[2]; -(β*y[2] + γ*y[1])/α]\nend\n\nfunction secondorder(x::Vector)\n    return secondorder(x...)\nend\n\n\"\"\"descriminant(a,b,c): quadtratic equation descriminant of ax^2 + bx + c = 0\n\"\"\"\ndescriminant(a,b,c) = √(complex(b^2-4a*c))\n\n\"\"\"roots(a,b,c): solve the quadratic equation ax^2 + bx + c = 0 \"\"\"\nfunction roots(a,b,c) \n    d = descriminant(a,b,c);\n    return (-b+d)/2a, (-b-d)/2a\nend \n\ndoc\"\"\"solution(a,b,c,y₀,t₀) general solution of second order linear homogenous\n\nArguments:\n   - a,b,c::Real the coeffients of the ODE\n\nReturns:\n   - func(t, c₁, c₂): the solution at t when the coefficients are c₁, c₂\n   - deriv(t, c₁, c₂): the derivative at t when the coefficients are c₁, c₂\n\nNotes: func is derived from the textbook definition and deriv is based on\n applying calculus rules to that (a symbolic algebra tool did this).\n\"\"\"\nfunction solution(a,b,c)\n    @show d = descriminant(a,b,c)\n    @show r₁, r₂ = roots(a,b,c)\n    if real(d) == d\n        info(\"characteristic polynomial has real roots\")\n        return (t, c₁, c₂) -> c₁ * exp(r₁*t) + c₂*exp(r₂*t),\n               (t, c₁, c₂) -> c₁*r₁*exp(r₁*t) + c₂*r₂*exp(r₂*t)\n               \n    end\n    if imag(d) != 0.0\n        info(\"characteristic polynomial has complex roots\")\n        @show α, β = -b/2a, imag(d/2a)\n        func(t, c₁, c) = begin\n            return (c₁*exp(α*t)*cos(β*t) + c*exp(α*t)*sin(β*t))\n        end\n        deriv(t,c₁,c₂) = begin\n            expα = exp(α*t)\n            cosβ = cos(β*t)\n            sinβ = sin(β*t)\n            return (-β*c₁*expα*sinβ +\n                    α*c₂*expα*sinβ +\n                    α*c₁*expα*cosβ +\n                    β*c₂*expα*cosβ\n                    )\n            end\n        return func, deriv\n    end\nend\n\n\"\"\"ivp(a,b,c,y₀,t₀) solves second order linear homogenous initial value problem\n\nArguments:\n   - a,b,c::Real the coeffients of the ODE\n   - y₀ the initial value as a vector\n   - t₀ the initial time value\n\nReturns:\n   - result : the Optim.jl result object of solving the equations\n   - general: the general form solution (see `solution`)\n   - deriv:   the general form derivative (see `solution`)\n\nNote: result.zero is the coefficients to plug into the general solution \nto get the correct particular solution.\n\"\"\"\nfunction ivp(a,b,c, y₀, t₀)\n    x₀ = y₀[1]\n    v₀ = y₀[2]\n    general, deriv = solution(a,b,c)\n    \n    function f!(params, fvec)\n        fvec[1] = x₀ - general(t₀, params...)\n        fvec[2] = v₀ - deriv(t₀, params...)\n    end\n    result = nlsolve(f!,\n                     [0.0,0.0],\n                     autodiff=true,\n                     method=:trust_region,\n                     store_trace=true)\n    return result, general, deriv\nend\n", "meta": {"hexsha": "4118687abe82394b98c11439868d20ff9b1e2767", "size": 3257, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/secondorder.jl", "max_stars_repo_name": "jpfairbanks/ODEOpt", "max_stars_repo_head_hexsha": "c9c7df7f3443b062866eeaf01d261762e994b1c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-03-20T22:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2016-03-20T22:12:46.000Z", "max_issues_repo_path": "src/secondorder.jl", "max_issues_repo_name": "jpfairbanks/ODEOpt", "max_issues_repo_head_hexsha": "c9c7df7f3443b062866eeaf01d261762e994b1c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/secondorder.jl", "max_forks_repo_name": "jpfairbanks/ODEOpt", "max_forks_repo_head_hexsha": "c9c7df7f3443b062866eeaf01d261762e994b1c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8230088496, "max_line_length": 79, "alphanum_fraction": 0.5818237642, "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8459424353665382, "lm_q1q2_score": 0.7844959579959945}}
{"text": "using FFTW\r\nexport Fourier, FrequencySplit\r\n\r\n# TODO: Allow width to the removed frequencies, ie. remove\r\n# a Gaussian around the specified frequency\r\n# This is possibly done via a combination of the\r\n# DSP.Filters.Bandstop and probably some windowing function from DSP.\r\n\r\n\"\"\"\r\n    Fourier([s, ] frequencies, x=true) <: Decomposition\r\nDecompose a timeseries `s` into a **sum** `x + r`, by identifying specific `frequencies`\r\nat the Fourier space and removing them from the signal.\r\n`x` is the removed periodic component while `r` is the residual.\r\nIf a given frequency is not exactly matching the Fourier frequencies, the closest one is\r\nremoved.\r\n\r\n**Important**: periods/frequencies are defined with respect to the `t` axis length,\r\nthe actual `t` values are not used in this method. So, frequency `1/12` (a period of `12`)\r\nmeans `12` data points (whose actual value depends on `t`).\r\n\r\nIf you provide `s` the method plans the forward and inverse\r\nFourier transforms (so that it is efficient to re-use it for `s` of same type and length).\r\n\r\nThis method works well when a periodic signal P is superimposed on fluctuations S,\r\nand you have a good educated guess of what frequencies compose P.\r\nThis method works well if the given signal has length multiple of the periods given.\r\n\r\nThere is arbitrarity of which part of the signal `x, r`\r\ngets the mean value of `s`, because it is deducted for a better fit.\r\nThe argument `x=true` attributes it to `x`, use `false` for `r`.\r\n\"\"\"\r\nstruct Fourier{F, I} <: Decomposition\r\n    fs::Vector{Float64}\r\n    forward::F\r\n    inverse::I\r\n    x::Bool\r\nend\r\nFourier(fs, x::Bool=true) = Fourier(fs, nothing, nothing, x)\r\nfunction Fourier(s::AbstractVector, fs::AbstractVector, x::Bool=true)\r\n    forward = plan_rfft(s)\r\n    inverse = plan_irfft(forward*s, length(s))\r\n    return Fourier(fs, forward, inverse, x)\r\nend\r\n\r\nfunction decompose(t, s, method::Fourier)\r\n    isequispaced(t) || error(\"Input time axis must be equispaced for method Fourier.\")\r\n    if length(s) % round(Int, maximum(1/f for f in method.fs)) ≠ 0\r\n        @warn \"The signal length is not a multiple of largest period.\"\r\n    end\r\n\r\n    m = mean(s)\r\n    𝓕 = isnothing(method.forward) ? rfft(s .- m) : method.forward*(s .- m)\r\n    fs = rfftfreq(length(s))\r\n    for f in method.fs\r\n        i = findnearest(f, fs)\r\n        𝓕[i] = 0.0\r\n    end\r\n    inv_𝓕 = isnothing(method.inverse) ? irfft(𝓕, length(s)) : method.inverse*𝓕\r\n    residual = inv_𝓕\r\n    periodic = s .- residual\r\n    if !method.x\r\n        periodic .-= m\r\n        residual .+= m\r\n    end\r\n    return periodic, residual\r\nend\r\n\r\n\r\n\"\"\"\r\n    FrequencySplit([s, ] f::Real) <: Decomposition\r\nSimilar to the [`Fourier`](@ref) method, but now the \"residual\" signal is the part\r\nof `s` with frequencies higher than `f`, while the \"seasonal\" part has frequencies `≤ f`.\r\n\"\"\"\r\nstruct FrequencySplit{F, I} <: Decomposition\r\n    f::Float64\r\n    forward::F\r\n    inverse::I\r\nend\r\nFrequencySplit(fs) = FrequencySplit(fs, nothing, nothing)\r\nfunction FrequencySplit(s, fs)\r\n    forward = plan_rfft(s)\r\n    inverse = plan_irfft(forward*s, length(s))\r\n    return FrequencySplit(fs, forward, inverse)\r\nend\r\n\r\nfunction decompose(t, s, method::FrequencySplit)\r\n    isequispaced(t) || error(\"Input time axis must be equispaced for method FrequencySplit.\")\r\n\r\n    m = mean(s)\r\n    𝓕 = isnothing(method.forward) ? rfft(s .- m) : method.forward*(s .- m)\r\n    fs = rfftfreq(length(s))\r\n    i = findlast(f -> f ≤ method.f, fs)\r\n    𝓕[1:i+1] .= 0.0\r\n    inv_𝓕 = isnothing(method.inverse) ? irfft(𝓕, length(s)) : method.inverse*𝓕\r\n    residual = inv_𝓕\r\n    periodic = s .- residual\r\n    return periodic, residual\r\nend\r\n", "meta": {"hexsha": "10d894b7e668992307ac833eaffcd781fc5b3572", "size": 3654, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear/fourier.jl", "max_stars_repo_name": "JuliaDynamics/SignalDecomposition.jl", "max_stars_repo_head_hexsha": "e865058d48a5e28e827b97ed05e99952f86e9a66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2020-04-04T14:49:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T19:36:47.000Z", "max_issues_repo_path": "src/linear/fourier.jl", "max_issues_repo_name": "JuliaDynamics/SignalDecomposition.jl", "max_issues_repo_head_hexsha": "e865058d48a5e28e827b97ed05e99952f86e9a66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-04-04T09:29:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T14:33:06.000Z", "max_forks_repo_path": "src/linear/fourier.jl", "max_forks_repo_name": "JuliaDynamics/SignalDecomposition.jl", "max_forks_repo_head_hexsha": "e865058d48a5e28e827b97ed05e99952f86e9a66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9090909091, "max_line_length": 94, "alphanum_fraction": 0.6735084839, "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632856092016, "lm_q2_score": 0.8459424314825852, "lm_q1q2_score": 0.7844959526959271}}
{"text": "module SecantMethod\r\n\r\nexport secant_method\r\n\r\nfunction secant_method(f::Function, x0::Number, x1::Number, args::Tuple=();\r\n                       tol::AbstractFloat=1e-5, maxiter::Integer=50)\r\n    for _ in 1:maxiter\r\n       y1 = f(x1, args...)\r\n       y0 = f(x0, args...)\r\n       x = x1 - y1* (x1 - x0)/(y1 - y0)\r\n       if abs(x - x1) < tol\r\n          return x\r\n       end\r\n       x0 = x1\r\n       x1 = x\r\n    end\r\n    error(\"Max iteration exceeded\")\r\nend\r\n\r\nend", "meta": {"hexsha": "d5944c20655d317e61cdc400998693a772ace7be", "size": 463, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SecantMethod.jl", "max_stars_repo_name": "RohitRathore1/NumericalTechniques.jl", "max_stars_repo_head_hexsha": "66eacc0d31c555c42f9712b9187633e2ba0b514c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SecantMethod.jl", "max_issues_repo_name": "RohitRathore1/NumericalTechniques.jl", "max_issues_repo_head_hexsha": "66eacc0d31c555c42f9712b9187633e2ba0b514c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SecantMethod.jl", "max_forks_repo_name": "RohitRathore1/NumericalTechniques.jl", "max_forks_repo_head_hexsha": "66eacc0d31c555c42f9712b9187633e2ba0b514c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.15, "max_line_length": 76, "alphanum_fraction": 0.505399568, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347121, "lm_q2_score": 0.8633916187614823, "lm_q1q2_score": 0.7844930683225377}}
{"text": "doc\"\"\"\n    FDist(ν1,ν2)\n\nThe *F distribution* has probability density function\n\n$f(x; \\nu_1, \\nu_2) = \\frac{1}{x B(\\nu_1/2, \\nu_2/2)}\n\\sqrt{\\frac{(\\nu_1 x)^{\\nu_1} \\cdot \\nu_2^{\\nu_2}}{(\\nu_1 x + \\nu_2)^{\\nu_1 + \\nu_2}}},\n\\quad x>0$\n\nIt is related to the [`Chisq`](:func:`Chisq`) distribution via the property that if $X_1\n\\sim \\operatorname{Chisq}(\\nu_1)$ and $X_2 \\sim \\operatorname{Chisq}(\\nu_2)$, then \n$(X_1/\\nu_1) / (X_2 / \\nu_2) \\sim FDist(\\nu_1, \\nu_2)`.\n\n\n```julia\nFDist(d1, d2)     # F-Distribution with parameters d1 and d2\n\nparams(d)         # Get the parameters, i.e. (d1, d2)\n```\n\nExternal links\n\n* [F distribution on Wikipedia](http://en.wikipedia.org/wiki/F-distribution)\n    \"\"\"\nimmutable FDist <: ContinuousUnivariateDistribution\n    ν1::Float64\n    ν2::Float64\n\n    function FDist(ν1::Real, ν2::Real)\n        @check_args(FDist, ν1 > zero(ν1) && ν2 > zero(ν2))\n        new(ν1, ν2)\n    end\nend\n\n@distr_support FDist 0.0 Inf\n\n\n#### Parameters\n\nparams(d::FDist) = (d.ν1, d.ν2)\n\n\n#### Statistics\n\nmean(d::FDist) = (ν2 = d.ν2; ν2 > 2.0 ? ν2 / (ν2 - 2.0) : NaN)\n\nmode(d::FDist) = ((ν1, ν2) = params(d); ν1 > 2.0 ? ((ν1 - 2.0)/ν1) * (ν2 / (ν2 + 2.0)) : 0.0)\n\nfunction var(d::FDist)\n    (ν1, ν2) = params(d)\n    ν2 > 4.0 ? 2.0 * ν2^2 * (ν1 + ν2 - 2.0) / (ν1 * (ν2 - 2.0)^2 * (ν2 - 4.0)) : NaN\nend\n\nfunction skewness(d::FDist)\n    (ν1, ν2) = params(d)\n    if ν2 > 6.0\n        return (2.0 * ν1 + ν2 - 2.0) * sqrt(8.0 * (ν2 - 4.0)) / ((ν2 - 6.0) * sqrt(ν1 * (ν1 + ν2 - 2.0)))\n    else\n        return NaN\n    end\nend\n\nfunction kurtosis(d::FDist)\n    (ν1, ν2) = params(d)\n    if ν2 > 8.0\n        a = ν1 * (5. * ν2 - 22.) * (ν1 + ν2 - 2.) + (ν2 - 4.) * (ν2 - 2.)^2\n        b = ν1 * (ν2 - 6.) * (ν2 - 8.) * (ν2 - 2.)\n        return 12. * a / b\n    else\n        return NaN\n    end\nend\n\nfunction entropy(d::FDist)\n    (ν1, ν2) = params(d)\n    hν1 = ν1 * 0.5\n    hν2 = ν2 * 0.5\n    hs = (ν1 + ν2) * 0.5\n    return log(ν2 / ν1) + lgamma(hν1) + lgamma(hν2) - lgamma(hs) +\n        (1.0 - hν1) * digamma(hν1) + (-1.0 - hν2) * digamma(hν2) +\n        hs * digamma(hs)\nend\n\n#### Evaluation & Sampling\n\n@_delegate_statsfuns FDist fdist ν1 ν2\n\nrand(d::FDist) = StatsFuns.Rmath.fdistrand(d.ν1, d.ν2)\n", "meta": {"hexsha": "a128f814068e47ad3cadf1213f44042745c65e49", "size": 2190, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/fdist.jl", "max_stars_repo_name": "ericproffitt/Distributions.jl", "max_stars_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/fdist.jl", "max_issues_repo_name": "ericproffitt/Distributions.jl", "max_issues_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/fdist.jl", "max_forks_repo_name": "ericproffitt/Distributions.jl", "max_forks_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.606741573, "max_line_length": 105, "alphanum_fraction": 0.5406392694, "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.863391602943619, "lm_q1q2_score": 0.7844930560866321}}
{"text": "export cg,bicgstab,Lanczos\n\nfunction cg{T1<:Number,T2<:Number}(A::AbstractMatrix{T1},b::Vector{T2})\n\tn=length(b)\n\tn1,n2=size(A)\n\tn == n1 == n2 || throw(DimensionMismatch(\"\"))\n\tT=promote_type(T1,T2)\n\tx=zeros(T,n)\n\tr=b-A*x\n\tp=r\n\trsold=dot(r,r)\n\tTR=typeof(real(rsold))\n\tfor i=1:n\n\t\tAp=A*p\n\t\talpha=rsold/dot(p,Ap)\n\t\tx=x+alpha*p\n\t\tr=r-alpha*Ap\n\t\trsnew=dot(r,r)\n\t\tif real(sqrt(rsnew))<10eps(TR)\n\t\t\treturn x\n\t\tend\n\t\tp=r+rsnew/rsold*p\n\t\trsold=rsnew\n\tend\n\treturn x\nend\n\nfunction cg{T1<:Number,T2<:Number,T3<:Number}(A::AbstractMatrix{T1},b::Vector{T2},P::AbstractMatrix{T3})\n\tn=length(b)\n\tn1,n2=size(A)\n\tn3,n4=size(P)\n\tn == n1 == n2 == n3 == n4 || throw(DimensionMismatch(\"\"))\n\tT=promote_type(T1,T2,T3)\n\tx=P\\b\n\tr=b-A*x\n\tz=P\\r\n\tp=z\n\trsold=dot(r,z)\n\tTR=typeof(real(rsold))\n\tfor i=1:n\n\t\tAp=A*p\n\t\talpha=rsold/dot(p,Ap)\n\t\tx=x+alpha*p\n\t\tr=r-alpha*Ap\n\t\tz=P\\r\n\t\trsnew=dot(r,z)\n\t\tif real(sqrt(rsnew))<10eps(TR)\n\t\t\treturn x\n\t\tend\n\t\tp=z+rsnew/rsold*p\n\t\trsold=rsnew\n\tend\n\treturn x\nend\n\nfunction bicgstab{T1<:Number,T2<:Number}(A::AbstractMatrix{T1},b::Vector{T2})\n\tn=length(b)\n\tn1,n2=size(A)\n\tn == n1 == n2 || throw(DimensionMismatch(\"\"))\n\tT=promote_type(T1,T2)\n\tx=zeros(T,n)\n\tr=b-A*x\n\trhat = r\n\tρold = one(T)\n\tα =one(T)\n\tωold = one(T)\n\tv=zeros(T,n)\n\tp=zeros(T,n)\n\tTR = typeof(real(α))\n\tfor i=1:n\n\t\tρnew = dot(rhat,r)\n\t\tβ = (ρnew/ρold)*(α/ωold)\n\t\tp = r + β*(p-ωold*v)\n\t\tv = A*p\n\t\tα = ρnew/dot(rhat,v)\n\t\ts = r - α*v\n\t\tt = A*s\n\t\tωnew = dot(t,s)/dot(t,t)\n\t\tupd = α*p + ωnew*s\n\t\tx = x + upd\n\t\tif norm(upd)<10eps(TR)\n\t\t\treturn x\n\t\tend\n\t\tr = s - ωnew*t\n\t\tρold = ρnew\n\t\tωold = ωnew\n\tend\n\treturn x\nend\n\nfunction bicgstab{T1<:Number,T2<:Number,T3<:Number}(A::AbstractMatrix{T1},b::Vector{T2},P::AbstractMatrix{T3})\n\tn=length(b)\n\tn1,n2=size(A)\n\tn3,n4=size(P)\n\tn == n1 == n2 == n3 == n4 || throw(DimensionMismatch(\"\"))\n\tT=promote_type(T1,T2,T3)\n\tx=P\\b\n\tr=b-A*x\n\trhat = r\n\tρold = one(T)\n\tα =one(T)\n\tωold = one(T)\n\tv=zeros(T,n)\n\tp=zeros(T,n)\n\tTR = typeof(real(α))\n\tfor i=1:n\n\t\tρnew = dot(rhat,r)\n\t\tβ = (ρnew/ρold)*(α/ωold)\n\t\tp = r + β*(p-ωold*v)\n\t\ty = P\\p\n\t\tv = A*y\n\t\tα = ρnew/dot(rhat,v)\n\t\ts = r - α*v\n\t\tz = P\\s\n\t\tt = A*z\n\t\tzt = P\\t\n\t\tωnew = dot(zt,z)/dot(zt,zt)\n\t\tupd = α*y + ωnew*z\n\t\tx = x + upd\n\t\tif norm(upd)<10eps(TR)\n\t\t\treturn x\n\t\tend\n\t\tr = s - ωnew*t\n\t\tρold = ρnew\n\t\tωold = ωnew\n\tend\n\treturn x\nend\n\nfunction Lanczos{T<:Number}(A::AbstractMatrix{T})\n\tn,n1 = size(A)\n\tn == n1 || throw(DimensionMismatch(\"\"))\n\tz = Array(T,n)\n\tvold = zero(T)\n\tvnew = [one(T),zeros(T,n-1)]\n\tbeta = zeros(T,n)\n\talpha = zeros(T,n)\n\tfor j = 1:n-1\n\t\tw = A*vnew\n\t\talpha[j] = dot(w,vnew)\n\t\tw = w - alpha[j]*vnew - beta[j]*vold\n\t\tbeta[j+1] = norm(w)\n\t\tvold = vnew\n\t\tvnew = w/beta[j+1]\n\tend\n\tw = A*vnew\n\talpha[n] = dot(w,vnew)\n\t@time steig!(alpha,[beta[2:end],zero(T)],z,10000)\n\treturn sort!(alpha)\n end", "meta": {"hexsha": "d1b9c0c0a03228a1d5d5c0ac25acd53a6513f26f", "size": 2747, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/KrylovMethods.jl", "max_stars_repo_name": "MikaelSlevinsky/Sincfun.jl", "max_stars_repo_head_hexsha": "7f8fc1d62322fe26e5ff65e41c022440699ed095", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/KrylovMethods.jl", "max_issues_repo_name": "MikaelSlevinsky/Sincfun.jl", "max_issues_repo_head_hexsha": "7f8fc1d62322fe26e5ff65e41c022440699ed095", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2015-01-14T11:56:26.000Z", "max_issues_repo_issues_event_max_datetime": "2015-01-14T12:23:23.000Z", "max_forks_repo_path": "src/KrylovMethods.jl", "max_forks_repo_name": "MikaelSlevinsky/Sincfun.jl", "max_forks_repo_head_hexsha": "7f8fc1d62322fe26e5ff65e41c022440699ed095", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.3133333333, "max_line_length": 110, "alphanum_fraction": 0.590826356, "num_tokens": 1181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321807, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7844811034461654}}
{"text": "\"\"\"\n Take the L2 Tikhonov regularised inverse of a matrix `m`.\n\n The regularisation parameter is the larger of `delta` (the optional argument that defaults\n to zero) and square root of machine epsilon. The inverse is done using an SVD.\n \"\"\"\n function reginv(a::AbstractMatrix, δ = defaulttol(a))\n     U, S, V = svd(a)\n     Sinv = inv.(hypot.(S, δ))\n     return  V * Diagonal(Sinv) * U'\n end\n\n function posreginv(a::AbstractMatrix, δ = defaulttol(a))\n     # assumes a is positive definite (or close to)\n     D, V = eigen(Hermitian(a))\n     Dinv = inv.(hypot.(D, δ))\n     return  V * Diagonal(Dinv) * V'\n end\n", "meta": {"hexsha": "49cfb10e7db07da45ffda20563d0cc326e13d742", "size": 607, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/common/regularisedinverse.jl", "max_stars_repo_name": "Jutho/CMPSKit.jl", "max_stars_repo_head_hexsha": "462a4f030243061a179d6c9807db61372524cba1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2020-06-18T15:13:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T11:42:14.000Z", "max_issues_repo_path": "src/common/regularisedinverse.jl", "max_issues_repo_name": "Jutho/CMPSKit.jl", "max_issues_repo_head_hexsha": "462a4f030243061a179d6c9807db61372524cba1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/regularisedinverse.jl", "max_forks_repo_name": "Jutho/CMPSKit.jl", "max_forks_repo_head_hexsha": "462a4f030243061a179d6c9807db61372524cba1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-11-25T09:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-16T04:36:43.000Z", "avg_line_length": 31.9473684211, "max_line_length": 91, "alphanum_fraction": 0.6573311367, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172644875642, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7844810941491499}}
{"text": "export Random\n\n\"\"\"\n    Random(;args)\n\nRandomly generated initial data, based on provided (optional arguments) :\n- `L` is the typical wavelength (default is `L=1`)\n- `s` is the (real) Sobolev index regularity (default is `s=∞`)\n- `λ` is the length of spatial localization (default is none)\n\nThe initial data `(η,v)` are generated through randomly chosen Fourier coefficients,\nmultiplied with weigth `w=10^(-|k|L/(2π))` if `s=∞`, or `w=1/(1+9(|k|L/(2π))^(s+1/2))` otherwise.\nIf `λ` is provided, the function in spatial variables is multiplied by `exp(-|x/λ|^2)`,\nand in any case normalized to have maximum absolute value 1.\n\n\n\"\"\"\nstruct Random <: InitialData\n\n    η\n    v\n\n    function Random(;L=1,s=Inf,λ=nothing)\n\n\n        function generate( x )\n\n\n            k = Mesh( x ).k\n            if s == Inf\n                w = 10 .^(-abs.(k*L/(2*π)))\n            else\n                w = 1 ./( 1 .+ 9*abs.(k*L/(2*π)).^(s+1/2) )\n            end\n            if λ == nothing\n                φ = zero(x).+1\n            else\n                φ = exp.(-abs.((x/λ).^2))\n            end\n\n            θ = 2*π*rand(Float64,length(x))\n            r = rand(Float64,length(x))\n            Fourier = r.*exp.(-1im.*θ).*w\n            Physic = real.(ifft(Fourier)).*φ\n            return Physic./maximum(abs.(Physic))\n        end\n        η( x ) = generate( x )\n        v( x ) = generate( x )\n\n\n    \tnew( η,v )\n\n    end\n\nend\n", "meta": {"hexsha": "fe9450236565fde2ef15cc852b5ad37e87313c6f", "size": 1398, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/initialdata/Random.jl", "max_stars_repo_name": "WaterWavesModels/ShallowWaterModels.jl", "max_stars_repo_head_hexsha": "ab745353a2472a76646d976c6fe536f0be664488", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-21T17:07:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-25T20:31:31.000Z", "max_issues_repo_path": "src/initialdata/Random.jl", "max_issues_repo_name": "WaterWavesModels/ShallowWaterModels.jl", "max_issues_repo_head_hexsha": "ab745353a2472a76646d976c6fe536f0be664488", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-07-17T17:38:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T07:36:48.000Z", "max_forks_repo_path": "src/initialdata/Random.jl", "max_forks_repo_name": "WaterWavesModels/ShallowWaterModels.jl", "max_forks_repo_head_hexsha": "ab745353a2472a76646d976c6fe536f0be664488", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9642857143, "max_line_length": 97, "alphanum_fraction": 0.5185979971, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7844810844892542}}
{"text": "\n####### Routines related to Chebyshev interpolation or polynomials that are not about\n#   evaluation nor interpolation set up.\n\n\n\n# scale x ∈ [a,b] to [-1,1].\nfunction scaletoChebyinterval(x::T, a::T, b::T)::T where T\n    @assert a <= x <= b\n    @assert b > a # disallow empty interval.\n\n    Δ::T = b-a\n    return (x-a)/Δ*convert(T,2) - one(T)\nend\n\n# scale y ∈ [-1,1] to [a,b].\nfunction scalefromChebyinterval(y::T, a::T, b::T)::T where T\n    @assert -one(T) <= y <= one(T)\n\n    Δ::T = b-a\n    return (y+1)/2*Δ + a\nend\n\n\nfunction Chebyshev2nd(x::T, L::Int)::T where T\n    two = one(T) + one(T)\n\n    out = zero(T)\n    for l = 0:div(L,2)\n        out += (-one(Int))^l*binomial(L-l,l)*(two*x)^(L-2*l)\n    end\n\n    return out\nend\n\n\nfunction Chebyshev1stall(x::T, L::Int)::Vector{T} where T\n    @assert L >= 2\n\n    # setup.\n    two = one(T)+one(T)\n\n    out = Vector{T}(undef,L+1)\n    out[1] = one(T)\n    out[2] = x\n    for i = 3:length(out)\n        out[i] = two*x*out[i-1] - out[i-2]\n    end\n\n    return out\nend\n\nfunction Chebyshev1st(x::T, L::Int)::T where T\n    @assert L >= 0\n\n    @assert isnumericallyin(x,-one(T),one(T))\n    clamp(x,-one(T),one(T))\n\n    return cos(convert(T,L)*acos(x))\nend\n\n# fill array with function\n# equivalent to: collect( 𝝋[j](y[i]) for j = 1:n+1 for i = 1:m+1 ), but transposed.\nfunction getunivariateChebyVmatrix(𝓧::Vector{T}, L::Int) where T\n    p = length(𝓧)\n    V = Matrix{T}(undef,L+1,p)\n\n    for j = 1:p\n        V[:,j] = Chebyshev1stall(𝓧[j],L)\n    end\n\n    return V\nend\n\nfunction Chebyshev1stnodes(Lp1::Int)::Vector{BigFloat}\n    L = Lp1 - 1\n    half = BigFloat(\"0.5\")\n    return collect( cos( (BigFloat(L-i)+half)*BigFloat(π)/BigFloat(L+1) ) for i = 0:L+1 )\nend\n\n\nfunction Chebyshev2ndnodes(L::Int)::Vector{BigFloat}\n    return collect( cos( (L-i)*BigFloat(π)/BigFloat(L) ) for i = 0:L+1 )\nend\n\nfunction Chebyshev2ndnode(i::Int, L::Int)::BigFloat\n    return cos( (L-i)*BigFloat(π)/BigFloat(L) )\nend\n\n\n# Colleague matrix for a L-degree Chebyshev polynomial of the mth kind.\nfunction constructcolleaguematrix(c::Vector{T}, m::Int) where T\n    @assert m == 1 || m == 2\n\n    L = length(c) - 1\n\n    while isnumericallyclose(c[L+1], zero(T), 1e-9) && L > 2\n        L -= 1\n    end\n\n    # pre-compute.\n    two = convert(T,2)\n    half = one(T)/two\n\n    C = zeros(T,L,L)\n    C[2,1] = half\n\n    # fill out the band.\n    for l = 2:L-1\n        C[l-1,l] = half\n        C[l+1,l] = half\n    end\n    C[L-1,L] = half\n\n    if m == 1\n        C[1,2] = one(T)\n    end\n\n    # fill out bottom row.\n    for l = 1:L\n        C[L,l] = -c[l]/(two*c[L+1])\n    end\n\n    C[L,L-1] += half\n\n    return C\nend\n\n\n\n# polynomial basis is Chebyshev polynomials of the m-th kind.\n# coeffs are a_k for m = 1\n# coeffs are c_k-1 = k*a_k for m = 2\nfunction findChebyitproots(a::Vector{T}, m::Int)::Vector{T} where T\n    if count(!isnumericallyclose(a[i],zero(T)) for i = 1:length(a)) < 2\n        # case, a is the zero vector or a has less than 2 non-zero entries.\n        #   The latter case means constant term and linear term. No local extrema.\n        return Vector{T}(undef,0)\n    end\n\n    C = constructcolleaguematrix(a,m)\n\n    return findChebyitproots(C)\nend\n\nfunction findChebyitproots(C::Matrix{T})::Vector{T} where T\n    C_eig = LinearAlgebra.eigen(convert(Matrix{Float64},C))\n    𝑧 = convert(Vector{T}, real.(C_eig.values))\n    unique!(𝑧)\n    filter!(xx->isnumericallyin(xx,-one(T),one(T)), 𝑧)\n    clamp!(𝑧,-one(T),one(T))\n\n    return 𝑧\nend\n\nfunction findChebyitpextrema(a::Vector{T}) where T\n    L = length(a)-1\n\n    c = collect( k*a[k+1] for k = 1:L)\n\n    extrema_positions = findChebyitproots(c,2)\n\n    return extrema_positions\nend\n\n# remove roots that do not have a zero derivative.\nfunction findChebyitpextremawithchk(a::Vector{T}, tol::T = convert(T,0.2)) where T\n    X = findChebyitpextrema(a)\n\n    𝑑itp_X = evalunivariateChebyshevpolynomialderivative(a,X)\n\n    remove_list = Vector{Int}(undef,0)\n    for i = 1:length(X)\n        if !isnumericallyclose(𝑑itp_X[i],zero(T),tol)\n            push!(remove_list,i)\n        end\n    end\n\n    deleteat!(X,remove_list)\n\n    return X\nend\n\n# N is the number of samples to take between each reference position.\n# 𝓧 is the set of reference positions.\nfunction findChebyitpextremainterval(  𝑒::Function,\n                                    L::Int,\n                                    𝓟_in::Vector{T},\n                                    tol_𝓧_spacing, # was defaulted to convert(T,1e-6/length(𝓟_in)\n                                    tol_derivative_zero) where T\n\n\n    ### get roots.\n    sample_position_template = collect( Chebyshev2ndnode(k,L) for k = 0:L )\n    out, d_set, X_set = getextremafromroots(𝑒, L, 𝓟_in,\n                                            sample_position_template,\n                                            tol_𝓧_spacing, tol_derivative_zero)\n\n    # check each point in out to see if its a stationary point.\n    chkfunc = xx->numericalchkextrema(𝑒, xx, tol_derivative_zero)\n    filter!(chkfunc,out)\n\n    sort!(out)\n    unique!(out)\n\n    return out, d_set, X_set\nend\n\n\nfunction discreteinnerprod(f::Function, g::Function, L::Int)\n\n    ν = collect( Chebyshev2ndnode(k,L) for k = 0:L )\n\n    term1 = 1/2 * f(ν[1]) * g(ν[1])\n\n    term2 = BigFloat(\"0\")\n    for l = 1:L-1\n        term2 += f(ν[l+1]) * g(ν[l+1])\n    end\n\n    term3 = 1/2 * f(ν[L+1]) * g(ν[L+1])\n\n    return term1 + term2 + term3\nend\n", "meta": {"hexsha": "53f60cad92e7f9e76c443ac8d34612e19ae31551", "size": 5353, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/minimax/Chebyshev.jl", "max_stars_repo_name": "RoyCCWang/FIRRemez", "max_stars_repo_head_hexsha": "41a3ad4e8bd851d51a62c7fcd35ac3abf6fdd84c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/minimax/Chebyshev.jl", "max_issues_repo_name": "RoyCCWang/FIRRemez", "max_issues_repo_head_hexsha": "41a3ad4e8bd851d51a62c7fcd35ac3abf6fdd84c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/minimax/Chebyshev.jl", "max_forks_repo_name": "RoyCCWang/FIRRemez", "max_forks_repo_head_hexsha": "41a3ad4e8bd851d51a62c7fcd35ac3abf6fdd84c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7911111111, "max_line_length": 97, "alphanum_fraction": 0.5854660938, "num_tokens": 1826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7844693497118645}}
{"text": "\n\n# export  fit_cubic_spline,\n#       sample_spline,\n#       sample_spline_derivative,\n#       sample_spline_derivative2,\n#       sample_spline_speed,\n#       sample_spline_theta,\n#       sample_spline_curvature,\n#       sample_spline_derivative_of_curvature,\n#       calc_curve_length,\n#       arclength,\n#       calc_curve_param_given_arclen\n\nfunction _integrate_simpsons(f::Function, a::Real, b::Real, n::Int)\n    # integrate using Composite Simpson's rule\n    # reference: https://en.wikipedia.org/wiki/Simpson%27s_rule\n\n    @assert(n > 0) # number of intervals\n    @assert(mod(n,2) == 0) # n must be even\n\n    h = (b-a)/n\n    retval = f(a) + f(b)\n    flip = true\n    for i = 1 : n-1\n        retval += f(a+i*h) * (flip ? 4 : 2)\n        flip = !flip\n    end\n    return h/3*retval\nend\n\nfunction _fit_open(pts::AbstractVector{Float64} )\n    # fits the 1-D spline such that:\n    #   spline goes through each point\n    #   first and second derivatives match at each inner point\n    #   the second derivative at the ends is zero\n    # see: http://mathworld.wolfram.com/CubicSpline.html\n\n    # this function returns a 4×(n-1) spline coefficient matrix, where n = |pts|\n\n    n = length(pts)-1\n    @assert(n > 0)\n\n    M = spzeros(n+1,n+1)\n    for i = 1 : n\n        M[i,i] = 4\n        M[i,i+1] = 1\n        M[i+1,i] = 1\n    end\n    M[n+1,n+1] = 2\n    M[1,1] = 2\n\n    Y = Array{Float64}(n+1)\n    for i = 1 : n+1\n        ind_hi = min(i+1,n)\n        ind_lo = max(1,i-1)\n        Y[i] = 3*(pts[ind_hi] - pts[ind_lo])\n    end\n\n    D = M\\Y\n\n    spline_coeffs = Array{Float64}(4, n) # col is <a,b,c,d>\n    spline_coeffs[1,:] = pts[1:n]\n    spline_coeffs[2,:] = D[1:n]\n    spline_coeffs[3,:] = 3*(pts[2:n+1] - pts[1:n]) -2*D[1:n]-D[2:n+1]\n    spline_coeffs[4,:] = 2*(pts[1:n] - pts[2:n+1]) + D[1:n] + D[2:n+1]\n\n    spline_coeffs\nend\nfunction _fit_closed(pts::AbstractVector{Float64} )\n    # fits the 1-D spline such that:\n    #   spline goes through each point\n    #   first and second derivatives match at each inner point\n    #   first the second derivative at the ends match\n    # see: http://mathworld.wolfram.com/CubicSpline.html\n\n    # this function returns a 4×n spline coefficient matrix, where n = |pts|\n\n    n = length(pts)-1\n    @assert(n > 0)\n\n    M = spzeros(n+1,n+1)\n    for i = 1 : n\n        M[i,i] = 4\n        M[i,i+1] = 1\n        M[i+1,i] = 1\n    end\n    M[n+1,n+1] = 4\n    M[1,n+1] = 1\n    M[n+1,1] = 1\n\n    Y = Array{Float64}(n+1)\n    Y[1] = 3*(pts[2] - pts[n+1])\n    for i = 2 : n\n        Y[i] = 3*(pts[i+1] - pts[i-1])\n    end\n    Y[end] = 3*(pts[1] - pts[n])\n\n    D = M\\Y\n\n    spline_coeffs = Array{Float64}(4, n+1) # col is <a,b,c,d>\n    spline_coeffs[1,:] = pts\n    spline_coeffs[2,:] = D\n    spline_coeffs[3,1:n] = 3*(pts[2:n+1] - pts[1:n]) -2*D[1:n]-D[2:n+1]\n    spline_coeffs[4,1:n] = 2*(pts[1:n] - pts[2:n+1]) + D[1:n] + D[2:n+1]\n    spline_coeffs[3,n+1] = 3*(pts[1] - pts[n+1]) -2*D[n+1]-D[1]\n    spline_coeffs[4,n+1] = 2*(pts[n+1] - pts[1]) + D[n+1] + D[1]\n\n    spline_coeffs\nend\nfunction _fit_open(pts::Matrix{Float64}) # 2×n {x,y}\n\n    # see http://mathworld.wolfram.com/CubicSpline.html\n\n    d,n = size(pts)\n    n -= 1\n\n    Y = Array{Float64}(n+1)\n\n    M = sparse(Int[], Int[], Float64[], n+1,n+1)\n    for i in 1 : n\n        M[i,i] = 4.0\n        M[i,i+1] = 1.0\n        M[i+1,i] = 1.0\n    end\n    M[n+1,n+1] = 2.0\n    M[1,1] = 2.0\n\n    retval = Array{Matrix{Float64}}(d)\n    for k in 1 : d\n\n        for i in 1 : n+1\n            ind_hi = min(i+1,n)\n            ind_lo = max(1,i-1)\n            Y[i] = 3*(pts[k,ind_hi] - pts[k,ind_lo])\n        end\n\n        D = M \\ Y\n\n        spline_coeffs = Array{Float64}(4, n) # col is <a,b,c,d> for a + b⋅t + c⋅t² + d⋅t³\n        spline_coeffs[1,:] = pts[k,1:n] # x₀\n        spline_coeffs[2,:] = D[1:n]     # x'₀\n        spline_coeffs[3,:] = 3*(pts[k,2:n+1]' - pts[k,1:n]') -2*D[1:n] - D[2:n+1] # -3x₀ + 3x₁ - 2x'₀ - x'₁\n        spline_coeffs[4,:] = 2*(pts[k,1:n]' - pts[k,2:n+1]') +  D[1:n] + D[2:n+1] #  2x₀ - 2x₁ +  x'₀ + x'₁\n\n        retval[k] = spline_coeffs\n    end\n    retval\nend\nfunction _fit_closed(pts::AbstractMatrix{Float64})\n    d = size(pts,1)\n    retval = Array{Matrix{Float64}}(d)\n    for i = 1 : d\n        retval[i] = _fit_closed(vec(pts[i,:]))\n    end\n    retval\nend\n\nfunction fit_cubic_spline(pts::AbstractArray{Float64}; open::Bool=true)\n    if open\n        return _fit_open(pts)\n    else\n        return _fit_closed(pts)\n    end\nend\n\nfunction sample_spline(spline_coeffs::AbstractVector{Float64}, t::Float64)\n    # here t is generally expected to be t ∈ [0,1]\n    return spline_coeffs[1] + t*(spline_coeffs[2] + t*(spline_coeffs[3] + t*spline_coeffs[4]))\nend\nfunction sample_spline(spline_coeffs::AbstractMatrix{Float64}, t::Float64)\n    # for t ∈ (-∞,1] we use spline_coeffs[:,1]\n    # for t ∈ [1,2] we use spline_coeffs[:,2]\n    # etc.\n    @assert(size(spline_coeffs, 1) == 4)\n    col_ind = clamp(ceil(Int, t), 1, size(spline_coeffs,2))\n    sample_spline(spline_coeffs[:,col_ind], t-col_ind+1)\nend\nfunction sample_spline(spline_coeffs::AbstractVector{Float64}, t_arr::AbstractVector{Float64})\n    # here t is generally expected to be t ∈ [0,1]\n\n    a = spline_coeffs[1]\n    b = spline_coeffs[2]\n    c = spline_coeffs[3]\n    d = spline_coeffs[4]\n\n    retval = Array{Float64}(length(t_arr))\n    for (i,t) in enumerate(t_arr)\n        retval[i] = a + t*(b + t*(c + t*d))\n    end\n    retval\nend\nfunction sample_spline(spline_coeffs::AbstractMatrix{Float64}, t_arr::AbstractVector{Float64})\n    # for t ∈ (-∞,1] we use spline_coeffs[:,1]\n    # for t ∈ [1,2] we use spline_coeffs[:,2]\n    # etc.\n    @assert(size(spline_coeffs, 1) == 4)\n    retval = Array{Float64}(length(t_arr))\n    for (i,t) in enumerate(t_arr)\n        col_ind = clamp(ceil(Int, t), 1, size(spline_coeffs,2))\n        retval[i] = sample_spline(spline_coeffs[:,col_ind], t-col_ind+1)\n    end\n    retval\nend\n\nfunction sample_spline_derivative(spline_coeffs::AbstractVector{Float64}, t::Float64)\n    # here t is generally expected to be t ∈ [0,1]\n    return spline_coeffs[2] + t*(2spline_coeffs[3] + t*3spline_coeffs[4])\nend\nfunction sample_spline_derivative(spline_coeffs::AbstractMatrix{Float64}, t::Float64)\n    # for t ∈ (-∞,1] we use spline_coeffs[:,1]\n    # for t ∈ [1,2] we use spline_coeffs[:,2]\n    # etc.\n    @assert(size(spline_coeffs, 1) == 4)\n    col_ind = clamp(ceil(Int, t), 1, size(spline_coeffs,2))\n    sample_spline_derivative(spline_coeffs[:,col_ind], t-col_ind+1)\nend\nfunction sample_spline_derivative(spline_coeffs::AbstractVector{Float64}, t_arr::AbstractVector{Float64})\n    # here t is generally expected to be t ∈ [0,1]\n\n    b = spline_coeffs[2]\n    c = spline_coeffs[3]\n    d = spline_coeffs[4]\n\n    retval = Array{Float64}(length(t_arr))\n    for (i,t) in enumerate(t_arr)\n        retval[i] = b + t*(2c + t*3d)\n    end\n    retval\nend\nfunction sample_spline_derivative(spline_coeffs::AbstractMatrix{Float64}, t_arr::AbstractVector{Float64})\n    # for t ∈ (-∞,1] we use spline_coeffs[:,1]\n    # for t ∈ [1,2] we use spline_coeffs[:,2]\n    # etc.\n    @assert(size(spline_coeffs, 1) == 4)\n    retval = Array{Float64}(length(t_arr))\n    for (i,t) in enumerate(t_arr)\n        col_ind = clamp(ceil(Int, t), 1, size(spline_coeffs,2))\n        retval[i] = sample_spline_derivative(spline_coeffs[:,col_ind], t-col_ind+1)\n    end\n    retval\nend\n\nfunction sample_spline_derivative2(spline_coeffs::AbstractVector{Float64}, t::Float64)\n    # here t is generally expected to be t ∈ [0,1]\n    return 2spline_coeffs[3] + t*6spline_coeffs[4]\nend\nfunction sample_spline_derivative2(spline_coeffs::AbstractMatrix{Float64}, t::Float64)\n    # for t ∈ (-∞,1] we use spline_coeffs[:,1]\n    # for t ∈ [1,2] we use spline_coeffs[:,2]\n    # etc.\n    @assert(size(spline_coeffs, 1) == 4)\n    col_ind = clamp(ceil(Int, t), 1, size(spline_coeffs,2))\n    sample_spline_derivative2(spline_coeffs[:,col_ind], t-col_ind+1)\nend\nfunction sample_spline_derivative2(spline_coeffs::AbstractVector{Float64}, t_arr::AbstractVector{Float64})\n    # here t is generally expected to be t ∈ [0,1]\n\n    b = spline_coeffs[2]\n    c = spline_coeffs[3]\n    d = spline_coeffs[4]\n\n    retval = Array{Float64}(length(t_arr))\n    for (i,t) in enumerate(t_arr)\n        retval[i] = 2c + t*6d\n    end\n    retval\nend\nfunction sample_spline_derivative2(spline_coeffs::AbstractMatrix{Float64}, t_arr::AbstractVector{Float64})\n    # for t ∈ (-∞,1] we use spline_coeffs[:,1]\n    # for t ∈ [1,2] we use spline_coeffs[:,2]\n    # etc.\n    @assert(size(spline_coeffs, 1) == 4)\n    retval = Array{Float64}(length(t_arr))\n    for (i,t) in enumerate(t_arr)\n        col_ind = clamp(ceil(Int, t), 1, size(spline_coeffs,2))\n        retval[i] = sample_spline_derivative2(spline_coeffs[:,col_ind], t-col_ind+1)\n    end\n    retval\nend\n\nfunction sample_spline_speed(spline_coeffs_x::AbstractVector{Float64}, spline_coeffs_y::AbstractVector{Float64}, t::Float64)\n    dxdt = sample_spline_derivative(spline_coeffs_x, t)\n    dydt = sample_spline_derivative(spline_coeffs_y, t)\n    hypot(dxdt, dydt)\nend\nfunction sample_spline_speed(spline_coeffs_x::AbstractMatrix{Float64}, spline_coeffs_y::AbstractMatrix{Float64}, t::Float64)\n    # for t ∈ (-∞,1] we use spline_coeffs[:,1]\n    # for t ∈ [1,2] we use spline_coeffs[:,2]\n    # etc.\n    n = size(spline_coeffs_x, 2)\n    @assert(size(spline_coeffs_x, 1) == 4)\n    @assert(size(spline_coeffs_y, 1) == 4)\n    @assert(n == size(spline_coeffs_y, 2))\n    col_ind = clamp(ceil(Int, t), 1, n)::Int\n    sample_spline_speed(spline_coeffs_x[:,col_ind], spline_coeffs_y[:,col_ind], t-col_ind+1)\nend\nfunction sample_spline_speed(spline_coeffs_x::AbstractVector{Float64}, spline_coeffs_y::AbstractVector{Float64}, t_arr::AbstractVector{Float64})\n    # here t is generally expected to be t ∈ [0,1]\n\n    bx = spline_coeffs_x[2]\n    cx = spline_coeffs_x[3]\n    dx = spline_coeffs_x[4]\n\n    by = spline_coeffs_y[2]\n    cy = spline_coeffs_y[3]\n    dy = spline_coeffs_y[4]\n\n    retval = Array{Float64}(length(t_arr))\n    for (i,t) in enumerate(t_arr)\n        dxdt = bx + t*(2cx + t*3dx)\n        dydt = by + t*(2cy + t*3dy)\n        retval[i] = hypot(dxdt, dydt)\n    end\n    retval\nend\nfunction sample_spline_speed(spline_coeffs_x::AbstractMatrix{Float64}, spline_coeffs_y::AbstractMatrix{Float64}, t_arr::AbstractVector{Float64})\n    # for t ∈ (-∞,1] we use spline_coeffs[:,1]\n    # for t ∈ [1,2] we use spline_coeffs[:,2]\n    # etc.\n\n    n = size(spline_coeffs_x, 2)\n    @assert(size(spline_coeffs_x, 1) == 4)\n    @assert(size(spline_coeffs_y, 1) == 4)\n    @assert(n == size(spline_coeffs_y, 2))\n    retval = Array{Float64}(length(t_arr))\n    for (i,t) in enumerate(t_arr)\n        col_ind = clamp(ceil(Int, t), 1, n)\n        retval[i] = sample_spline_speed(spline_coeffs_x[:,col_ind], spline_coeffs_y[:,col_ind], t-col_ind+1)\n    end\n    retval\nend\n\nfunction sample_spline_theta(spline_coeffs_x::AbstractVector{Float64}, spline_coeffs_y::AbstractVector{Float64}, t::Float64;\n    stepsize=1e-4\n    )\n\n    # compute the angle from positive x-axis (counter-clockwise positive) of the curve in the positive t direction at t\n    # uses an approximation via small step size instead of derivative due to zero-derivative issues\n    # uses the forward derivative approximation unless it would put it out of range\n    # result returned is in radians\n\n    t_lo, t_hi = t, t+stepsize\n    if t_hi > 1.0\n        t_lo, t_hi = t-min(1000stepsize,0.1), t\n    end\n\n    x1 = sample_spline(spline_coeffs_x, t_lo)\n    x2 = sample_spline(spline_coeffs_x, t_hi)\n    y1 = sample_spline(spline_coeffs_y, t_lo)\n    y2 = sample_spline(spline_coeffs_y, t_hi)\n\n    # println(\"(t, lo, hi)  $t   $t_lo   $t_hi, ($(atan2(y2-y1, x2-x1)))\")\n\n    atan2(y2-y1, x2-x1)\nend\nfunction sample_spline_theta(spline_coeffs_x::AbstractMatrix{Float64}, spline_coeffs_y::AbstractMatrix{Float64}, t::Float64)\n    # for t ∈ (-∞,1] we use spline_coeffs[:,1]\n    # for t ∈ [1,2] we use spline_coeffs[:,2]\n    # etc.\n    n = size(spline_coeffs_x, 2)\n    @assert(size(spline_coeffs_x, 1) == 4)\n    @assert(size(spline_coeffs_y, 1) == 4)\n    @assert(n == size(spline_coeffs_y, 2))\n    col_ind = clamp(ceil(Int, t), 1, n)\n    sample_spline_theta(spline_coeffs_x[:,col_ind], spline_coeffs_y[:,col_ind], t-col_ind+1)\nend\nfunction sample_spline_theta(spline_coeffs_x::AbstractVector{Float64}, spline_coeffs_y::AbstractVector{Float64}, t_arr::AbstractVector{Float64})\n    # here t is generally expected to be t ∈ [0,1]\n\n    retval = Array{Float64}(length(t_arr))\n    for (i,t) in enumerate(t_arr)\n        retval[i] = sample_spline_theta(spline_coeffs_x, spline_coeffs_y, t)\n    end\n    retval\nend\nfunction sample_spline_theta(spline_coeffs_x::AbstractMatrix{Float64}, spline_coeffs_y::AbstractMatrix{Float64}, t_arr::AbstractVector{Float64})\n    # for t ∈ (-∞,1] we use spline_coeffs[:,1]\n    # for t ∈ [1,2] we use spline_coeffs[:,2]\n    # etc.\n\n    n = size(spline_coeffs_x, 2)\n    @assert(size(spline_coeffs_x, 1) == 4)\n    @assert(size(spline_coeffs_y, 1) == 4)\n    @assert(n == size(spline_coeffs_y, 2))\n    retval = Array{Float64}(length(t_arr))\n    for (i,t) in enumerate(t_arr)\n        col_ind = clamp(ceil(Int, t), 1, n)\n        retval[i] = sample_spline_theta(spline_coeffs_x[:,col_ind], spline_coeffs_y[:,col_ind], t-col_ind+1)\n    end\n    retval\nend\n\nfunction sample_spline_curvature(spline_coeffs_x::AbstractVector{Float64}, spline_coeffs_y::AbstractVector{Float64}, t::Float64)\n    # computes the signed curvature\n\n    dx  = sample_spline_derivative( spline_coeffs_x, t)\n    dy  = sample_spline_derivative( spline_coeffs_y, t)\n    ddx = sample_spline_derivative2(spline_coeffs_x, t)\n    ddy = sample_spline_derivative2(spline_coeffs_y, t)\n\n    (dx*ddy - dy*ddx)/(dx*dx + dy*dy)^1.5\nend\nfunction sample_spline_curvature(spline_coeffs_x::AbstractMatrix{Float64}, spline_coeffs_y::AbstractMatrix{Float64}, t::Float64)\n    # for t ∈ (-∞,1] we use spline_coeffs[:,1]\n    # for t ∈ [1,2] we use spline_coeffs[:,2]\n    # etc.\n    n = size(spline_coeffs_x, 2)\n    @assert(size(spline_coeffs_x, 1) == 4)\n    @assert(size(spline_coeffs_y, 1) == 4)\n    @assert(n == size(spline_coeffs_y, 2))\n    col_ind = clamp(ceil(Int, t), 1, n)\n    sample_spline_curvature(spline_coeffs_x[:,col_ind], spline_coeffs_y[:,col_ind], t-col_ind+1)\nend\nfunction sample_spline_curvature(spline_coeffs_x::AbstractVector{Float64}, spline_coeffs_y::AbstractVector{Float64}, t_arr::AbstractVector{Float64})\n    # here t is generally expected to be t ∈ [0,1]\n\n    retval = Array{Float64}(length(t_arr))\n    for (i,t) in enumerate(t_arr)\n        retval[i] = sample_spline_curvature(spline_coeffs_x, spline_coeffs_y, t)\n    end\n    retval\nend\nfunction sample_spline_curvature(spline_coeffs_x::AbstractMatrix{Float64}, spline_coeffs_y::AbstractMatrix{Float64}, t_arr::AbstractVector{Float64})\n    # for t ∈ (-∞,1] we use spline_coeffs[:,1]\n    # for t ∈ [1,2] we use spline_coeffs[:,2]\n    # etc.\n\n    n = size(spline_coeffs_x, 2)\n    @assert(size(spline_coeffs_x, 1) == 4)\n    @assert(size(spline_coeffs_y, 1) == 4)\n    @assert(n == size(spline_coeffs_y, 2))\n    retval = Array{Float64}(length(t_arr))\n    for (i,t) in enumerate(t_arr)\n        col_ind = clamp(ceil(Int, t), 1, n)\n        retval[i] = sample_spline_curvature(spline_coeffs_x[:,col_ind], spline_coeffs_y[:,col_ind], t-col_ind+1)\n    end\n    retval\nend\n\nfunction sample_spline_derivative_of_curvature(spline_coeffs_x::AbstractVector{Float64}, spline_coeffs_y::AbstractVector{Float64}, t::Float64;\n    stepsize=1e-4\n    )\n\n    # computes the derivative of the signed curvature\n\n    t_lo, t_hi = t, t+stepsize\n    if t_hi > 1.0\n        t_lo, t_hi = t-stepsize, t\n    end\n\n    κ_hi = sample_spline_curvature(spline_coeffs_x, spline_coeffs_y, t_hi)\n    κ_lo = sample_spline_curvature(spline_coeffs_x, spline_coeffs_y, t_lo)\n\n    (κ_hi - κ_lo) / stepsize\nend\nfunction sample_spline_derivative_of_curvature(spline_coeffs_x::AbstractMatrix{Float64}, spline_coeffs_y::AbstractMatrix{Float64}, t::Float64;\n    stepsize=1e-4\n    )\n\n    # for t ∈ (-∞,1] we use spline_coeffs[:,1]\n    # for t ∈ [1,2] we use spline_coeffs[:,2]\n    # etc.\n    n = size(spline_coeffs_x, 2)\n    @assert(size(spline_coeffs_x, 1) == 4)\n    @assert(size(spline_coeffs_y, 1) == 4)\n    @assert(n == size(spline_coeffs_y, 2))\n    col_ind = clamp(ceil(Int, t), 1, n)\n    sample_spline_derivative_of_curvature(spline_coeffs_x[:,col_ind], spline_coeffs_y[:,col_ind], t-col_ind+1, stepsize=stepsize)\nend\nfunction sample_spline_derivative_of_curvature(spline_coeffs_x::AbstractVector{Float64}, spline_coeffs_y::AbstractVector{Float64}, t_arr::AbstractVector{Float64};\n    stepsize=1e-4\n    )\n\n    # here t is generally expected to be t ∈ [0,1]\n\n    retval = Array{Float64}(length(t_arr))\n    for (i,t) in enumerate(t_arr)\n        retval[i] = sample_spline_derivative_of_curvature(spline_coeffs_x, spline_coeffs_y, t, stepsize=stepsize)\n    end\n    retval\nend\nfunction sample_spline_derivative_of_curvature(spline_coeffs_x::AbstractMatrix{Float64}, spline_coeffs_y::AbstractMatrix{Float64}, t_arr::AbstractVector{Float64};\n    stepsize=1e-4\n    )\n\n    # for t ∈ (-∞,1] we use spline_coeffs[:,1]\n    # for t ∈ [1,2] we use spline_coeffs[:,2]\n    # etc.\n\n    n = size(spline_coeffs_x, 2)\n    @assert(size(spline_coeffs_x, 1) == 4)\n    @assert(size(spline_coeffs_y, 1) == 4)\n    @assert(n == size(spline_coeffs_y, 2))\n    retval = Array{Float64}(length(t_arr))\n    for (i,t) in enumerate(t_arr)\n        col_ind = clamp(ceil(Int, t), 1, n)\n        retval[i] = sample_spline_derivative_of_curvature(spline_coeffs_x[:,col_ind], spline_coeffs_y[:,col_ind], t-col_ind+1, stepsize=stepsize)\n    end\n    retval\nend\n\nfunction calc_curve_length(spline_coeffs_x::AbstractVector{Float64}, spline_coeffs_y::AbstractVector{Float64};\n    n_intervals::Int = 100\n    )\n\n    # integrate using Simpson's rule\n    # _integrate_simpsons(t->sample_spline_speed(spline_coeffs_x, spline_coeffs_y, t), 0.0, 1.0, n_intervals)\n\n    a = 0.0\n    b = 1.0\n    n = n_intervals\n\n    h = (b-a)/n\n    retval = sample_spline_speed(spline_coeffs_x, spline_coeffs_y, a) + sample_spline_speed(spline_coeffs_x, spline_coeffs_y, b)\n    flip = true\n    for i = 1 : n-1\n        retval += sample_spline_speed(spline_coeffs_x, spline_coeffs_y, a+i*h) * (flip ? 4 : 2)\n        flip = !flip\n    end\n    return h/3*retval\nend\nfunction calc_curve_length(\n    spline_coeffs_x::AbstractMatrix{Float64},\n    spline_coeffs_y::AbstractMatrix{Float64};\n    n_intervals_per_segment::Int = 100\n    )\n\n    n = size(spline_coeffs_x, 2)\n    @assert(size(spline_coeffs_y, 2) == n)\n    @assert(size(spline_coeffs_x, 1) == size(spline_coeffs_y, 1) == 4)\n\n    len = 0.0\n    for i = 1 : n\n        len += calc_curve_length(spline_coeffs_x[:,i], spline_coeffs_y[:,i], n_intervals = n_intervals_per_segment)\n    end\n    len\nend\n\nfunction arclength(\n    spline_coeffs_x::AbstractVector{Float64},\n    spline_coeffs_y::AbstractVector{Float64},\n    t_min::Real = 0.0,\n    t_max::Real = 1.0,\n    n_intervals::Int = 100\n    )\n\n    if isapprox(t_min, t_max)\n        return 0.0\n    end\n\n    # _integrate_simpsons(t->sample_spline_speed(spline_coeffs_x, spline_coeffs_y, t), t_min, t_max, n_intervals)\n\n    a = t_min\n    b = t_max\n    n = n_intervals\n\n    h = (b-a)/n\n    retval = sample_spline_speed(spline_coeffs_x, spline_coeffs_y, a) + sample_spline_speed(spline_coeffs_x, spline_coeffs_y, b)\n    flip = true\n    for i = 1 : n-1\n        retval += sample_spline_speed(spline_coeffs_x, spline_coeffs_y, a+i*h) * (flip ? 4 : 2)\n        flip = !flip\n    end\n    return h/3*retval\nend\nfunction arclength(\n    spline_coeffs_x::AbstractMatrix{Float64},\n    spline_coeffs_y::AbstractMatrix{Float64},\n    t_min::Real = 0.0,\n    t_max::Real = size(spline_coeffs_x, 2),\n    n_intervals_per_segment::Int = 100\n    )\n\n    n = size(spline_coeffs_x, 2)\n    @assert(size(spline_coeffs_y, 2) == n)\n    @assert(size(spline_coeffs_x, 1) == size(spline_coeffs_y, 1) == 4)\n\n    if isapprox(t_min, t_max)\n        return 0.0\n    end\n\n    # println(\"tmin/tmax: $t_min / $t_max\")\n\n    len = 0.0\n    for i = floor(Int, t_min) : min(floor(Int, t_max), n-1)\n        t_lo, t_hi = float(i), i+1.0\n\n        spline_ind = i+1\n        t_in_min = max(t_lo, t_min) - t_lo\n        t_in_max = min(t_hi, t_max) - t_lo\n        # println(\"($i) t_lo: $t_lo, t_hi: $t_hi, : $t_in_min → $t_in_max\")\n        len += arclength(spline_coeffs_x[:,spline_ind], spline_coeffs_y[:,spline_ind], t_in_min, t_in_max, n_intervals_per_segment)\n    end\n    # println(\"len: \", len)\n    len\nend\n\nfunction calc_curve_param_given_arclen(\n    spline_coeffs_x :: AbstractVector{Float64},\n    spline_coeffs_y :: AbstractVector{Float64},\n    s :: Float64;\n    max_iterations :: Int=100,\n    curve_length :: Float64 = calc_curve_length(spline_coeffs_x, spline_coeffs_y),\n    epsilon::Float64 = 1e-4 # tolerance required before termination\n    )\n\n    # finds t such that p(t) is a distance s from start of curve\n    # returns t=0 if s ≤ 0.0 and t=1 if s > L\n    if s ≤ 0.0\n        return 0.0\n    elseif s ≥ curve_length\n        return 1.0\n    end\n\n    t = s/curve_length\n    lo, hi = 0.0, 1.0\n\n    # @printf(\"%10s %10s %10s %10s %10s %10s\\n\", \"iter\", \"lo\", \"hi\", \"t\", \"s\", \"F\")\n    # println(\"-\"^65)\n\n    for iter = 1 : max_iterations\n        F = arclength(spline_coeffs_x, spline_coeffs_y, 0.0, t) - s\n\n        # @printf(\"%10d %10.5f %10.5f %10.5f %10.5f %10.5f\\n\", iter-1, lo, hi, t, s, F)\n\n        if abs(F) < epsilon\n            # |F(t)| is close enough to zero, report it\n            return t\n        end\n\n        DF = sample_spline_speed(spline_coeffs_x, spline_coeffs_y, t)\n        tCandidate = t - F/DF\n        if F > 0\n            hi = t\n            t = tCandidate ≤ lo ? 0.5*(lo+hi) : tCandidate\n        else\n            lo = t\n            t = tCandidate ≥ hi ? 0.5*(lo+hi) : tCandidate\n        end\n    end\n\n    # @printf(\"%10d %10.5f %10.5f %10.5f %10.5f %10s\\n\", max_iterations, lo, hi, t, s, \"-\")\n\n    t\nend\nfunction calc_curve_param_given_arclen(\n    spline_coeffs_x :: AbstractMatrix{Float64},\n    spline_coeffs_y :: AbstractMatrix{Float64},\n    s :: Float64;\n    max_iterations :: Int=100,\n    n_integration_intervals :: Int=100, # must be multiple of 2\n    curve_length :: Float64 = calc_curve_length(spline_coeffs_x, spline_coeffs_y),\n    epsilon::Float64 = 1e-4 # tolerance required before termination\n    )\n\n    # finds t such that p(t) is a distance s from start of curve\n    # returns t=0 if s ≤ 0.0 and t=t_max if s > L\n\n    n_segments = size(spline_coeffs_x, 2)\n    @assert(size(spline_coeffs_x,1) == size(spline_coeffs_y,1) == 4)\n    @assert(size(spline_coeffs_y,2) == n_segments)\n\n    if s ≤ 0.0\n        return 0.0\n    elseif s ≥ curve_length\n        return float(n_segments)\n    end\n\n    t = s/curve_length\n    lo, hi = 0.0, float(n_segments)\n\n    # @printf(\"%10s %10s %10s %10s %10s %10s\\n\", \"iter\", \"lo\", \"hi\", \"t\", \"s\", \"F\")\n    # println(\"-\"^65)\n\n    for iter = 1 : max_iterations\n        F = arclength(spline_coeffs_x, spline_coeffs_y, 0.0, t, n_integration_intervals) - s\n\n        # @printf(\"%10d %10.5f %10.5f %10.5f %10.5f %10.5f\\n\", iter-1, lo, hi, t, s, F)\n\n        if abs(F) < epsilon\n            return t\n        end\n\n        DF = sample_spline_speed(spline_coeffs_x, spline_coeffs_y, t)\n        tCandidate = t - F/DF\n        if F > 0\n            hi = t\n            t = tCandidate ≤ lo ? 0.5*(lo+hi) : tCandidate\n        else\n            lo = t\n            t = tCandidate ≥ hi ? 0.5*(lo+hi) : tCandidate\n        end\n    end\n\n    # @printf(\"%10d %10.5f %10.5f %10.5f %10.5f %10s\\n\", max_iterations, lo, hi, t, s, \"-\")\n\n    t\nend\nfunction calc_curve_param_given_arclen(\n    spline_coeffs_x :: AbstractVector{Float64},\n    spline_coeffs_y :: AbstractVector{Float64},\n    s_arr :: AbstractVector{Float64}; # assumes s_arr is sorted\n    max_iterations :: Int=100,\n    curve_length :: Float64 = calc_curve_length(spline_coeffs_x, spline_coeffs_y),\n    epsilon::Float64 = 1e-4 # tolerance required before termination\n    )\n\n    n = length(s_arr)\n    t_arr = Array{Float64}(n)\n\n    s = s_arr[1]\n    t = s/curve_length\n    if s ≤ 0.0\n        t = 0.0\n    elseif s ≥ curve_length\n        t = 1.0\n    end\n\n    lo =  0.0\n\n    for (i,s) in enumerate(s_arr)\n\n        if s ≤ 0.0\n            t = 0.0\n            t_arr[i], lo = t, t\n            continue\n        elseif s ≥ curve_length\n            t = 1.0\n            t_arr[i], lo = t, t\n            continue\n        end\n\n        hi = 1.0\n        for iter = 1 : max_iterations\n            F = arclength(spline_coeffs_x, spline_coeffs_y, 0.0, t) - s\n\n            if abs(F) < epsilon\n                t_arr[i], lo = t, t\n                continue\n            end\n\n            DF = sample_spline_speed(spline_coeffs_x, spline_coeffs_y, t)\n            tCandidate = t - F/DF\n            if F > 0\n                hi = t\n                t = tCandidate ≤ lo ? 0.5*(lo+hi) : tCandidate\n            else\n                lo = t\n                t = tCandidate ≥ hi ? 0.5*(lo+hi) : tCandidate\n            end\n        end\n\n        t_arr[i], lo = t, t\n    end\n\n    t_arr\nend\nfunction calc_curve_param_given_arclen(\n    spline_coeffs_x :: AbstractMatrix{Float64},\n    spline_coeffs_y :: AbstractMatrix{Float64},\n    s_arr :: AbstractVector{Float64}; # assumes s_arr is sorted\n    max_iterations :: Int = 50,\n    curve_length :: Float64 = calc_curve_length(spline_coeffs_x, spline_coeffs_y),\n    epsilon::Float64 = 1e-4, # tolerance required before termination\n    n_intervals_in_arclen::Int = 100\n    )\n\n    n_segments = size(spline_coeffs_x, 2)\n    @assert(size(spline_coeffs_x,1) == size(spline_coeffs_y,1) == 4)\n    @assert(size(spline_coeffs_y,2) == n_segments)\n\n    n = length(s_arr)\n    t_arr = Array{Float64}(n)\n\n    s = s_arr[1]\n    t = s/curve_length\n    if s ≤ 0.0\n        t = 0.0\n    elseif s ≥ curve_length\n        return float(n_segments)\n    end\n\n    lo =  0.0\n    # println(\"L: \", curve_length)\n    # println(\"s_max: \", s_arr[end])\n    for (i,s) in enumerate(s_arr)\n\n        # println(\"\\ns: \", s)\n\n        if s ≤ 0.0\n            t = 0.0\n            t_arr[i] = lo = t\n            continue\n        elseif s ≥ curve_length\n            t = float(n_segments)\n            t_arr[i] = lo = t\n            continue\n        end\n\n        hi = float(n_segments)\n        for iter = 1 : max_iterations\n            F = arclength(spline_coeffs_x, spline_coeffs_y, 0.0, t, n_intervals_in_arclen) - s\n\n            if abs(F) < epsilon\n                break\n            end\n\n            DF = sample_spline_speed(spline_coeffs_x, spline_coeffs_y, t)\n            tCandidate = t - F/DF\n            if F > 0\n                hi = t\n                t = tCandidate ≤ lo ? 0.5*(lo+hi) : tCandidate\n            else\n                lo = t\n                t = tCandidate ≥ hi ? 0.5*(lo+hi) : tCandidate\n            end\n        end\n\n        t_arr[i] = lo = t\n    end\n\n    t_arr\nend", "meta": {"hexsha": "1f8b1d3c4cb01d8adf731050bdd4d93e9db7e079", "size": 26712, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/core/splines.jl", "max_stars_repo_name": "Sawato/AutomotiveDrivingModels.jl", "max_stars_repo_head_hexsha": "3fbf6a4a53ebedd710d3dfd9f8440ce87b0573d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/splines.jl", "max_issues_repo_name": "Sawato/AutomotiveDrivingModels.jl", "max_issues_repo_head_hexsha": "3fbf6a4a53ebedd710d3dfd9f8440ce87b0573d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/splines.jl", "max_forks_repo_name": "Sawato/AutomotiveDrivingModels.jl", "max_forks_repo_head_hexsha": "3fbf6a4a53ebedd710d3dfd9f8440ce87b0573d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4174757282, "max_line_length": 162, "alphanum_fraction": 0.6273959269, "num_tokens": 8629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909757, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7844693478600059}}
{"text": "## Exercise 4-8\n## Enter the code in this chapter in a notebook.\n\n## 1. Draw a stack diagram that shows the state of the program while executing circle(🐢, radius). \n## You can do the arithmetic by hand or add print statements to the code.\nprintln(\"Ans 1: \")\n\nprintln(\" turtle --> Turtle\")\nprintln(\"     turtle --> Turtle\")\nprintln(\"     radius --> 100\")\nprintln(\"     circumference --> 628.318...\")\nprintln(\"     n --> 212\")\nprintln(\"     len --> 2\")\nprintln(\"         turtle --> Turtle\")\nprintln(\"         nsides --> 212\")\nprintln(\"         len --> 2\")\nprintln(\"         i --> 1:212\")\nprintln(\" return\")\n\n## 2. The version of arc in Refactoring is not very accurate because the linear approximation of the circle \n## is always outside the true circle. As a result, the turtle ends up a few pixels away from the correct destination. \n## My solution shows a way to reduce the effect of this error. Read the code and see if it makes sense to you. \n## If you draw a diagram, you might see how it works.\nusing ThinkJulia\n\nfunction polyline(t, n, len, angle)\n    for i in 1:n\n        forward(t, len)\n        turn(t, -angle)\n    end\nend\n\n\"\"\"\narc(t, r, angle)\n\nDraws an arc with the given radius and angle:\n\n    t: turtle\n    r: radius\n    angle: angle subtended by the arc, in degrees\n\"\"\"\nfunction arc(t, r, angle)\n    arc_len = 2 * π * r * abs(angle) / 360\n    n = trunc(arc_len / 4) + 3\n    step_len = arc_len / n\n    step_angle = angle / n\n\n    # making a slight left turn before starting reduces\n    # the error caused by the linear approximation of the arc\n    turn(t, -step_angle/2)\n    polyline(t, n, step_len, step_angle)\n    turn(t, step_angle/2)\nend\n\nprintln(\"Ans 2: \")\n\n@svg begin\n    turtle = Turtle()\n    # forward(turtle, 30)  # for checking the position of the turtle\n    arc(turtle, 100, 125)\nend\n\n## \n\nprintln(\"End.\")\n", "meta": {"hexsha": "004f05c8898b7ed033d466a91e51ccba876bdd4a", "size": 1829, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter4/ex8.jl", "max_stars_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_stars_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-13T14:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T14:11:30.000Z", "max_issues_repo_path": "Chapter4/ex8.jl", "max_issues_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_issues_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter4/ex8.jl", "max_forks_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_forks_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7121212121, "max_line_length": 118, "alphanum_fraction": 0.6413340623, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8670357632379241, "lm_q1q2_score": 0.7843643693936746}}
{"text": "using ModelingToolkit\nusing DifferentialEquations\n\n@parameters t α\n@variables x(t) y(t)\nD = Differential(t)\n\neqs = [D(x) ~ y * x,\n       D(y) ~ -α * x]\n\n@named sys = ODESystem(eqs)\n\nu0 = [ x => 1.0, y => 2.0]\ntspan = (0.0, 1.0)\np = [α => 1.0]\nprob = ODEProblem(sys, u0, tspan, p)\nsol = solve(prob)\n\n#=\nusing SymbolicUtils\nr1 = @rule (~y)*(~x) => (~y)^2\nr1(eqs[1].rhs)\n=#\n", "meta": {"hexsha": "59310e815bb8bd98eb42d0050d2954ce6fff5e50", "size": 371, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/atom/diff_eq/04_symbolic.jl", "max_stars_repo_name": "SteffenPL/Julia-for-mathematicians", "max_stars_repo_head_hexsha": "accd6bc8f4e064a1d55ae5f903607778ca84a79a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercises/atom/diff_eq/04_symbolic.jl", "max_issues_repo_name": "SteffenPL/Julia-for-mathematicians", "max_issues_repo_head_hexsha": "accd6bc8f4e064a1d55ae5f903607778ca84a79a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercises/atom/diff_eq/04_symbolic.jl", "max_forks_repo_name": "SteffenPL/Julia-for-mathematicians", "max_forks_repo_head_hexsha": "accd6bc8f4e064a1d55ae5f903607778ca84a79a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.4583333333, "max_line_length": 36, "alphanum_fraction": 0.5687331536, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404116305638, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7843502114913109}}
{"text": "#\n# Computes the density function of a list of values\n#\n\nfunction density(v;nbins=nothing,step=nothing,steptype=\"absolute\",vmin=nothing,vmax=nothing)\n\n  ndata = length(v)\n\n  if vmin == nothing\n    vmin = minimum(v)\n  end\n  if vmax == nothing\n    vmax = maximum(v)\n  end\n  if nbins == nothing\n    nbins = 100\n  end\n  if step == nothing\n    step = (vmax - vmin)/nbins\n  else\n    # By default, the step size is absolute\n    if steptype == \"relative\"\n      step = step*(vmax-vmin)/nbins\n    elseif steptype != \"absolute\"\n      error(\" steptype must be \\\"relative\\\" or \\\"absolute\\\"\")\n    end\n  end\n\n  x = Vector{Float64}(undef,nbins)\n  df = Vector{Float64}(undef,nbins)\n\n  binstep = (vmax - vmin)/nbins\n  for i in 1:nbins\n    x[i] = vmin + (i-1)*binstep + binstep/2\n    nv = 0\n    for j in 1:ndata\n      if ( v[j] > x[i] - step/2 ) && ( v[j] <= x[i] + step/2 )\n        nv = nv + 1\n      end\n    end\n    binsize = min(vmax,x[i]+step/2) - max(vmin,x[i]-step/2)\n    df[i] = nv/(binsize*ndata)\n  end\n\n  return x, df\n\nend\n\n", "meta": {"hexsha": "33b1019658dfa86022b4867c311233e1b4b4df89", "size": 1013, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/density.jl", "max_stars_repo_name": "mcubeg/M3GTools", "max_stars_repo_head_hexsha": "48ab02a23f0095e7964bfb047836f090f8d35331", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-22T05:04:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-30T06:32:25.000Z", "max_issues_repo_path": "src/density.jl", "max_issues_repo_name": "mcubeg/M3GTools", "max_issues_repo_head_hexsha": "48ab02a23f0095e7964bfb047836f090f8d35331", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/density.jl", "max_forks_repo_name": "mcubeg/M3GTools", "max_forks_repo_head_hexsha": "48ab02a23f0095e7964bfb047836f090f8d35331", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-17T10:16:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T10:16:37.000Z", "avg_line_length": 20.6734693878, "max_line_length": 92, "alphanum_fraction": 0.5883514314, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7843502012448365}}
{"text": "# Miscellaneous functions\n\n# Logarithm of multivariate gamma function\n#\n# See: https://en.wikipedia.org/wiki/Multivariate_gamma_function\n#\nfunction logmvgamma(p::Int, a::Real)\n    # NOTE: one(a) factors are here to prevent unnecessary promotion of Float32\n    res = p * (p - 1) * log(pi * one(a)) / 4\n    for ii in 1:p\n        res += lgamma(a + (1 - ii) * one(a)/ 2)\n    end\n    return res\nend\n\n# Remainder term after Stirling's approximation to the log-gamma function\n# lstirling(x) = lgamma(x) + x - (x-0.5)*log(x) - 0.5*log2π\n#              = 1/(12x) - 1/(360x^3) + 1/(1260x^5) + ...\n#\n# Asymptotic expansion from:\n#\n#   Temme, N. (1996) Special functions: An introduction to the classical\n#   functions of mathematical physics, Wiley, New York, ISBN: 0-471-11313-1,\n#   Chapter 3.6, pp 61-65.\n#\n# Relative error of approximation is bounded by\n#   (174611/125400 x^-19) / (1/12 x^-1 - 1/360 x^-3)\n# which is < 1/2 ulp for x >= 10.0\n# total numeric error appears to be < 2 ulps\n#\nfunction lstirling_asym(x::Float64)\n    t = 1.0/(x*x)\n    @horner(t,\n             8.33333333333333333e-2, #  1/12 x^-1\n            -2.77777777777777778e-3, # -1/360 x^-3\n             7.93650793650793651e-4, #  1/1260 x^-5\n            -5.95238095238095238e-4, # -1/1680 x^-7\n             8.41750841750841751e-4, #  1/1188 x^-9\n            -1.91752691752691753e-3, # -691/360360 x^-11\n             6.41025641025641026e-3, #  1/156 x^-13\n            -2.95506535947712418e-2, # -3617/122400 x^-15\n             1.79644372368830573e-1)/x #  43867/244188 x^-17\nend\n\nfunction lstirling_asym(x::Float32)\n    t = 1f0/(x*x)\n    @horner(t,\n             8.333333333333f-2, #  1/12 x^-1\n            -2.777777777777f-3, # -1/360 x^-3\n             7.936507936508f-4, #  1/1260 x^-5\n            -5.952380952381f-4, # -1/1680 x^-7\n             8.417508417508f-4)/x #  1/1188 x^-9\nend\n\nlstirling_asym(x::Integer) = lstirling_asym(float(x))\n", "meta": {"hexsha": "01cf04ae1c6a7082ab00db4989306b3ee40ea9f2", "size": 1903, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/misc.jl", "max_stars_repo_name": "JuliaPackageMirrors/StatsFuns.jl", "max_stars_repo_head_hexsha": "5de325f64b4528273310cdcf5532d994c1aa5067", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/misc.jl", "max_issues_repo_name": "JuliaPackageMirrors/StatsFuns.jl", "max_issues_repo_head_hexsha": "5de325f64b4528273310cdcf5532d994c1aa5067", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/misc.jl", "max_forks_repo_name": "JuliaPackageMirrors/StatsFuns.jl", "max_forks_repo_head_hexsha": "5de325f64b4528273310cdcf5532d994c1aa5067", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9821428571, "max_line_length": 79, "alphanum_fraction": 0.5943247504, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7843501994203248}}
{"text": "\"\"\"\n    eulerivp(dudt,tspan,u0,n)\n\nApply Euler's method to solve the IVP u'=`dudt`(u,t) over the interval `tspan` with\nu(`tspan[1]`)=`u0`, using `n` subintervals/steps. Return vectors of times and solution\nvalues.\n\"\"\"\nfunction eulerivp(dudt,tspan,u0,n)\n    a,b = tspan\n    h = (b-a)/n\n    t = [ a + i*h for i=0:n ]\n    u = zeros(n+1)\n    u[1] = u0\n    for i = 1:n\n      u[i+1] = u[i] + h*dudt(u[i],t[i])\n    end\n    return t,u\nend\n\n\"\"\"\n    eulersys(dudt,tspan,u0,n)\n\nApply Euler's method to solve the vector-valued IVP u'=`dudt`(u,p,t) over the interval\n`tspan` with u(`tspan[1]`)=`u0`, using `n` subintervals/steps.\n\n(This is the same code as `eulerivp`. In the system case it returns a vector of vector\nvalues as the solution.)\n\"\"\"\nfunction eulersys(dudt,tspan,u0,n)\n    # Time discretization.\n    a,b = tspan\n    h = (b-a)/n\n    t = [ a + i*h for i=0:n ]\n\n    # Initial condition and output setup.\n    u = Vector{typeof(u0)}(undef,n+1)\n    u[1] = u0\n\n    # The time stepping iteration.\n    for i = 1:n\n        u[i+1] = u[i] + h*dudt(u[i],t[i])\n    end\n    return t,u\nend\n\n\"\"\"\n    ie2(dudt,tspan,u0,n)\n\nApply the Improved Euler method to solve the vector-valued IVP u'=`dudt`(u,p,t) over the\ninterval `tspan` with u(`tspan[1]`)=`u0`, using `n` subintervals/steps. Returns a vector\nof times and a vector of solution values/vectors.\n\"\"\"\nfunction ie2(dudt,tspan,u0,n)\n    # Time discretization.\n    a,b = tspan\n    h = (b-a)/n\n    t = [ a + i*h for i=0:n ]\n\n    # Initialize output.\n    u = Vector{typeof(u0)}(undef,n+1)\n    u[1] = u0\n\n    # Time stepping.\n    for i = 1:n\n        uhalf = u[i] + h/2*dudt(u[i],t[i]);\n        u[i+1] = u[i] + h*dudt(uhalf,t[i]+h/2);\n    end\n    return t,u\nend\n\n\"\"\"\n    rk4(dudt,tspan,u0,n)\n\nApply \"the\" Runge-Kutta 4th order method to solve the vector-valued IVP u'=`dudt`(u,p,t)\nover the interval `tspan` with u(`tspan[1]`)=`u0`, using `n` subintervals/steps.\nReturn a vector of times and a vector of solution values/vectors.\n\"\"\"\nfunction rk4(dudt,tspan,u0,n)\n    # Time discretization.\n    a,b = tspan\n    h = (b-a)/n\n    t = [ a + i*h for i=0:n ]\n\n    # Initialize output.\n    u = Vector{typeof(u0)}(undef,n+1)\n    u[1] = u0\n\n    # Time stepping.\n    for i = 1:n\n        k1 = h*dudt( u[i],      t[i]     )\n        k2 = h*dudt( u[i]+k1/2, t[i]+h/2 )\n        k3 = h*dudt( u[i]+k2/2, t[i]+h/2 )\n        k4 = h*dudt( u[i]+k3,   t[i]+h   )\n        u[i+1] = u[i] + (k1 + 2*(k2 + k3) + k4)/6\n    end\n    return t,u\nend\n\n\"\"\"\n    rk23(dudt,tspan,u0,tol)\n\nApply adaptive embedded RK formula to solve the vector-valued IVP u'=`dudt`(u,p,t)\nover the interval `tspan` with u(`tspan[1]`)=`u0`, with error tolerance `tol`.\nReturn a vector of times and a vector of solution values/vectors.\n\"\"\"\nfunction rk23(dudt,tspan,u0,tol)\n    # Initialize for the first time step.\n    t = tspan[1]\n    u = [u0];   i = 1;\n    h = 0.5*tol^(1/3)\n    s1 = dudt(u0,t)\n\n    # Time stepping.\n    while t[i] < tspan[2]\n        # Detect underflow of the step size.\n        if t[i]+h == t[i]\n            @warn \"Stepsize too small near t=$(t[i])\"\n            break  # quit time stepping loop\n        end\n\n        # New RK stages.\n        s2 = dudt( u[i]+(h/2)*s1,   t[i]+h/2   )\n        s3 = dudt( u[i]+(3*h/4)*s2, t[i]+3*h/4 )\n        unew2 = u[i] + h*(2*s1 + 3*s2 + 4*s3)/9   # 2rd order solution\n        s4 = dudt( unew2, t[i]+h )\n        err = h*(-5*s1/72 + s2/12 + s3/9 - s4/8)    # 2nd/3rd order difference\n        E = norm(err,Inf)                           # error estimate\n        maxerr = tol*(1 + norm(u[i],Inf))         # relative/absolute blend\n\n        # Accept the proposed step?\n        if E < maxerr     # yes\n            t = [ t; t[i] + h]\n            push!(u,unew2)\n            i = i+1;\n            s1 = s4;      # use FSAL property\n        end\n\n        # Adjust step size.\n        q = 0.8*(maxerr/E)^(1/3)       # conservative optimal step factor\n        q = min(q,4)                   # limit stepsize growth\n        h = min(q*h,tspan[2]-t[i])     # don't step past the end\n    end\n    return t,u\nend\n\n\"\"\"\n    ab4(dudt,tspan,u0,n)\n\nApply the Adams-Bashforth 4th order method to solve the vector-valued IVP u'=`dudt`(u,p,t)\nover the interval `tspan` with u(`tspan[1]`)=`u0`, using `n` subintervals/steps.\n\"\"\"\nfunction ab4(dudt,tspan,u0,n)\n    # Time discretization.\n    a,b = tspan\n    h = (b-a)/n\n    t = [ a + i*h for i=0:n ]\n\n    # Constants in the AB4 method.\n    k = 4;    sigma = [55, -59, 37, -9]/24;\n\n    # Find starting values by RK4.\n    u = Vector{typeof(u0)}(undef,n+1)\n    ts,us = rk4(dudt,[a,a+(k-1)*h],u0,k-1)\n    u[1:k] = us[1:k]\n\n    # Compute history of u' values, from newest to oldest.\n    f = [ dudt(u[k-j],t[k-j]) for j=1:k-1  ]\n\n    # Time stepping.\n    for i = k:n\n      f = [ dudt(u[i],t[i]), f[1:k-1]... ]   # new value of du/dt\n      u[i+1] = u[i] + h*sum(f[j]*sigma[j] for j=1:k)       # advance one step\n    end\n    return t,u\nend\n\n\n\"\"\"\n    am2(dudt,tspan,u0,n)\n\nApply the Adams-Moulton 2nd order method to solve the vector-valued IVP u'=`dudt`(u,p,t)\nover the interval `tspan` with u(`tspan[1]`)=`u0`, using `n` subintervals/steps.\n\"\"\"\nfunction am2(dudt,tspan,u0,n)\n    # Time discretization.\n    a,b = tspan\n    h = (b-a)/n\n    t = [ a + i*h for i=0:n ]\n\n    # Initialize output.\n    u = Vector{typeof(u0)}(undef,n+1)\n    u[1] = u0\n\n    # Time stepping.\n    for i = 1:n\n        # Data that does not depend on the new value.\n        known = u[i] + h/2*dudt(u[i],t[i])\n        # Find a root for the new value.\n        F = z -> z - h/2*dudt(z,t[i+1]) - known\n        unew = levenberg(F,known)\n        u[i+1] = unew[:,end]\n    end\n    return t,u\nend\n\n# This version is needed to work with scalar problems using levenberg().\nfunction am2(dudt,tspan,u0::Number,n)\n    f = (x,t) -> [dudt(x[1],t)]\n    t,u = am2(f,tspan,[u0],n)\n    u = [u[1] for u=u]\n    return t,u\nend\n", "meta": {"hexsha": "10d4d4cd2d159666b33986303f33a894beef9495", "size": 5808, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/functions/chapter06.jl", "max_stars_repo_name": "snowdj/fnc-extras", "max_stars_repo_head_hexsha": "ef51fada748de1326a4ce645fbcb0c2499cb2b8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 109, "max_stars_repo_stars_event_min_datetime": "2018-04-21T09:02:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T19:03:54.000Z", "max_issues_repo_path": "julia/functions/chapter06.jl", "max_issues_repo_name": "snowdj/fnc-extras", "max_issues_repo_head_hexsha": "ef51fada748de1326a4ce645fbcb0c2499cb2b8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-12-04T22:17:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T21:04:47.000Z", "max_forks_repo_path": "julia/functions/chapter06.jl", "max_forks_repo_name": "snowdj/fnc-extras", "max_forks_repo_head_hexsha": "ef51fada748de1326a4ce645fbcb0c2499cb2b8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2017-04-02T17:21:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T17:19:57.000Z", "avg_line_length": 27.2676056338, "max_line_length": 90, "alphanum_fraction": 0.5451101928, "num_tokens": 2151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.8991213671331906, "lm_q1q2_score": 0.7843461671196443}}
{"text": "# # Mass dashpot spring\n\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/models/massDashpotSpring.ipynb)\n#\n\n\n\n# ## Free oscillations\n\nusing StructuralDynamicsODESolvers, Plots, LinearAlgebra\n\nk  = 2 ; m  = .5 ;  c = 0 ;\nu0 = 1 ; v0 = 0 ;\n\nM = m * ones(1, 1)\nC = c * ones(1, 1)\nK = k * ones(1, 1)\nR = zeros(1)\n\nsys = SecondOrderAffineContinuousSystem(M, C, K, R)\n\nU₀ = u0 * ones(1); V₀ = v0 * ones(1);\n\nivp_free = InitialValueProblem(sys, (U₀, V₀))\n\nNSTEPS = 1000 ;\nΔt = 0.005 ;\n\n#-\n\nalg = Bathe(Δt = Δt )\nsol = solve(ivp_free, alg, NSTEPS=NSTEPS);\n\n#-\n\n# The following command is the same as `plot(times(sol), displacements(sol, 1))`.\n\nplot(sol, vars=(0, 1))\n\n# ## Forced oscillations\n#\n# ### Problem definition\n# Let us consider now a forcing term $f(t) = A_f \\sin(ω_f \\cdot t)$\n#\nωN = sqrt(k/m)\nωf = ωN * 2\nAf = 10.0\nR  = [ [ Af * sin(ωf * Δt * (i-1) ) ] for i in 1:NSTEPS+1];\n\n# ### Second order problem resolution\n\nX   = nothing # state constraints are ignored\nB   = ones(1, 1)\nsys = SecondOrderConstrainedLinearControlContinuousSystem(M, C, K, B, X, R)\n\nivp_forced_secOrder = InitialValueProblem(sys, (U₀, V₀))\n\nalg = Bathe(Δt = Δt )\nsol_secOrder = solve(ivp_forced_secOrder, alg, NSTEPS=NSTEPS);\n\n# ### First order homogeneization formulation\n# The problem can be re-formulated as a first order and homogeneous one given by\n#\n#\n# ```math\n# \\left\\{\n# \\begin{array}{l}\n# \\dot{u} = v \\\\\n# \\dot{v} = -\\omega_N^2 u + u_f/m \\\\\n# \\dot{u_f} = v_f \\\\\n# \\dot{v_f} = -\\omega_f^2 u_f\n# \\end{array}\n# \\right.\n# ```\n# The new vector of variables is\n#\n# ```math\n# \\textbf{x} = [ u, v, u_f, v_f ]^T\n# ```\n\nK = [     0 1     0 0 ;\n      -ωN^2 0     1/m 0 ;\n          0 0     0 1 ;\n          0 0 -ωf^2 0 ] ;\n\nC = -Diagonal(ones(4))\nM = zeros(4,4)\nR = zeros(4)\n\nsys = SecondOrderAffineContinuousSystem(M, C, K, R)\n\nU₀ = [u0; v0; 0; ωf*Af ] ;\n\nivp_forced_firOrder = InitialValueProblem(sys, (U₀, U₀) )\n\nalg = BackwardEuler(Δt = Δt )\nsol_firOrderA = solve(ivp_forced_firOrder, alg, NSTEPS=NSTEPS);\n\nNSTEPS = NSTEPS*3 ; alg = BackwardEuler(Δt = Δt/3.0 )\nsol_firOrderB = solve(ivp_forced_firOrder, alg, NSTEPS=NSTEPS);\n\n# The solution obtained is\n\nplot(sol_secOrder, vars=(0, 1), xlab=\"time\" )\nplot!(sol_firOrderA, vars=(0, 1))\nplot!(sol_firOrderB, vars=(0, 1))\n", "meta": {"hexsha": "712b65d1f8d56c6ff0ad570930cf5889ed71b147", "size": 2287, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/massDashpotSpring.jl", "max_stars_repo_name": "ONSAS/StructuralDynamicsODESolvers.jl", "max_stars_repo_head_hexsha": "88fa774de9f57ee789801fb188a4f5e91366dcb5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-09T16:44:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T14:34:41.000Z", "max_issues_repo_path": "examples/massDashpotSpring.jl", "max_issues_repo_name": "ONSAS/StructuralDynamicsODESolvers.jl", "max_issues_repo_head_hexsha": "88fa774de9f57ee789801fb188a4f5e91366dcb5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2021-02-10T12:55:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T11:26:31.000Z", "max_forks_repo_path": "examples/massDashpotSpring.jl", "max_forks_repo_name": "ONSAS/StructuralDynamicsODESolvers.jl", "max_forks_repo_head_hexsha": "88fa774de9f57ee789801fb188a4f5e91366dcb5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3738317757, "max_line_length": 121, "alphanum_fraction": 0.6261477919, "num_tokens": 891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.8723473630627235, "lm_q1q2_score": 0.7843461648928312}}
{"text": "using LinearAlgebra: norm\n\n\"\"\"\nlinearspace(start, stop, N) \n\nGenerate linear space.\n\nGenerate a linear sequence of `N` numbers between  `start` and `stop` (i. e.\nsequence  of number with uniform intervals inbetween).\n\n# Example\n```\njulia> linearspace(2.0, 3.0, 5)\n2.0:0.25:3.0\n```\n\"\"\"\nfunction linearspace(start, stop, N) \n    return collect(range(Float64(start), stop = Float64(stop), length = Int64(N)))\nend\n\n\"\"\"\ngradedspace(start, stop, N, strength=2)\n\nGenerate graded space.\n\nGenerate a graded sequence of `N` numbers between `start` and `stop`. This\nsequence corresponds to separation of adjacent numbers that increases in \nproportion corresponding to the power coefficient `strength`\nfrom start to finish.\n\n# Example\n```\njulia> gradedspace(2.0, 3.0, 5)\n5-element Array{Float64,1}:\n2.0\n2.0625\n2.25\n2.5625\n3.0\n```\n\"\"\"\nfunction gradedspace(start, stop, N, strength=2)\n    N = Int64(N)\n    x = range(0.0, stop = 1.0, length = N);\n    x = x.^strength\n    # for i = 1:strength\n    #     x = cumsum(x);\n    # end\n    x = x./maximum(x);\n    out = Float64(start) .* (1.0 .- x) .+ Float64(stop) .* x;\nend\n", "meta": {"hexsha": "5d410cfca4f085dd15063aa838ba94dd43ff7d6f", "size": 1101, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utilities.jl", "max_stars_repo_name": "PetrKryslUCSD/MeshSteward.jl", "max_stars_repo_head_hexsha": "c3a77c8f357d37c69687d1b2e6814e621e3d836f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utilities.jl", "max_issues_repo_name": "PetrKryslUCSD/MeshSteward.jl", "max_issues_repo_head_hexsha": "c3a77c8f357d37c69687d1b2e6814e621e3d836f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-16T01:14:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-11T19:35:35.000Z", "max_forks_repo_path": "src/utilities.jl", "max_forks_repo_name": "PetrKryslUCSD/MeshSteward.jl", "max_forks_repo_head_hexsha": "c3a77c8f357d37c69687d1b2e6814e621e3d836f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-18T20:07:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-26T17:59:05.000Z", "avg_line_length": 21.1730769231, "max_line_length": 82, "alphanum_fraction": 0.663941871, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.8856314677809303, "lm_q1q2_score": 0.7843430940504124}}
{"text": "using SparseArrays\n\nfunction clique_expansion_homophily(N,k_range)\n    # Compute homophily index in the clique expansion of the hypergraph\n    In1 = 0\n    In2 = 0\n    Cross = 0\n    for k = k_range\n        for j = 1:k+1\n            i = j-1         # number of women in this type hyperedge\n            Hik = N[k,j]    # number of hyperedges of this type\n            In1 += binomial(i,2)*Hik    # number of extra edges of this type\n            In2 += binomial(k-i,2)*Hik\n            Cross += Hik*i*(k-i)\n        end\n    end\n\n    hw = 2*In1/(2*In1 + Cross)\n    hm = 2*In2/(2*In2 + Cross)\n    return hw, hm\nend\n\nfunction n_baselines(k,n,alpha)\n    n1 = round(Int64,floor(n*alpha))\n    n2 = n - n1\n\n    b = zeros(k)\n    for t = 1:k\n        b[t] = binomial(n1-1,t-1)*binomial(n2,k-t)/binomial(n-1,k-1)\n    end\n    return b\n\nend\n\nfunction n1_n2_baselines(k,n1,n2)\n    n = n1+n2\n\n    b1 = zeros(k)\n    b2 = zeros(k)\n    for t = 1:k\n        b1[t] = binomial(n1-1,t-1)*binomial(n2,k-t)/binomial(n-1,k-1)\n        b2[t] = binomial(n2-1,t-1)*binomial(n1,k-t)/binomial(n-1,k-1)\n    end\n    return b1, b2\nend\n\nfunction n_alt_baselines(k,n,alpha)\n    n1 = round(Int64,floor(n*alpha))\n    n2 = n - n1\n\n    b = zeros(k)\n    denom = 0\n    for t = 1:k\n        b[t] = binomial(n1,t)*binomial(n2,k-t)\n    end\n    return b/sum(b)\n\nend\n\nfunction arbitrary_baselines(k,alpha)\n    \"\"\"\n    Returns asymptotic relative baseline scores for a single class that makes up\n        a ratio alpha of the total population. Assumes k-uniform hypergraph.\n\n        k = hyperedge size\n        alpha = proportion of nodes in the class of interest\n    \"\"\"\n    b = zeros(k)\n    for j = 1:k\n        b[j] = alpha^(j-1)*(1-alpha)^(k-j)*binomial(k-1,j-1)\n    end\n    return b\nend\n\nfunction alternative_baselines(k,alpha)\n    \"\"\"\n    This is for the alternative definition of affinity score, that doesn't\n        degree correct.\n\n    Returns asymptotic relative baseline scores for a single class that makes up\n        a ratio alpha of the total population. Assumes k-uniform hypergraph.\n\n        k = hyperedge size\n        alpha = proportion of nodes in the class of interest\n    \"\"\"\n    b = zeros(k)\n    denom = sum(alpha^(i)*(1-alpha)^(k-i)/(factorial(i)*factorial(k-i)) for i = 1:k)\n    for j = 1:k\n        b[j] = alpha^(j)*(1-alpha)^(k-j)/(denom*(factorial(j)*factorial(k-j)))\n    end\n    return b\nend\n\nfunction baselines(r,alpha)\n    \"\"\"\n    Returns asymptotic relative baseline scores for a single class that makes up\n        a ratio alpha of the total population. Does this for all hyperedge sizes\n        from 1 to r.\n    \"\"\"\n    B = zeros(r,r)\n    for k = 1:r\n        for t = 1:k\n            B[k,t] = alpha^(t-1)*(1-alpha)^(k-t)*binomial(k-1,t-1)\n        end\n    end\n    return B\nend\n\nfunction order_degree(H::SparseMatrixCSC{Float64,Int64})\n    \"\"\"Returns hyperedge sizes and degrees for a hypergraph.\"\"\"\n    order = vec(sum(H,dims=2))\n    deg = vec(sum(H,dims=1))\n    return order, degree\nend\n\nfunction get_hyperedge_counts(H::SparseMatrixCSC{Float64,Int64},classes::Vector{Int64})\n    \"\"\"\n    Compute number of each type of hyperedge. Output is a matrix N, such that\n        N[k,j] = number of hyperedge of size k that have j-1 nodes of class 1\n    \"\"\"\n    order, degree = order_degree(H)\n    r = round(Int64,maximum(order))\n\n    # Ensure classes are 0 and 1\n    cs = unique(classes)\n    @assert(length(cs) == 2)\n    @assert(minimum(cs) == 0 && maximum(cs) == 1)\n    Hyp = incidence2elist(H)\n    N = zeros(r,r+1)\n    for edge in Hyp\n        board = classes[edge]\n        w = sum(board)\n        k = length(board)\n        if k > 0\n            N[k,w+1] += 1\n        end\n    end\n    return N\nend\n\nfunction relative_affinities(H::SparseMatrixCSC{Float64,Int64},classes::Vector{Int64},r::Int64=0)\n    \"\"\"\n    Compute relative affinity scores for both classes in a hypergraph H with\n        two classes.\n\n        Aff1[k,t] = type-t relative affinity score for size k hyperedges, for class 1\n        Aff0[k,t] = type-t relative affinity score for size k hyperedges, for class 0\n    \"\"\"\n    N = get_hyperedge_counts(H,classes)\n    if r == 0\n        r = size(N,1)   # max hyperedge size\n    end\n    Aff1 = zeros(r,r)\n    Aff0 = zeros(r,r)\n    for k = 1:r\n        c1_denom = sum(i*N[k,i+1] for i = 1:k)\n        c0_denom = sum(i*N[k,k-i+1] for i = 1:k)\n        for t = 1:k\n            Aff1[k,t] = t*N[k,t+1]/c1_denom\n            Aff0[k,t] = t*N[k,k-t+1]/c0_denom\n        end\n    end\n    return Aff1, Aff0\nend\n\nfunction affinities_from_N(N)\n    r = size(N,1)\n    Aff1 = zeros(r,r)\n    Aff0 = zeros(r,r)\n    for k = 1:r\n        c1_denom = sum(i*N[k,i+1] for i = 1:k)\n        c0_denom = sum(i*N[k,k-i+1] for i = 1:k)\n        for t = 1:k\n            Aff1[k,t] = t*N[k,t+1]/c1_denom\n            Aff0[k,t] = t*N[k,k-t+1]/c0_denom\n        end\n    end\n    return Aff1, Aff0\nend\n\n\nfunction relative_affinities_k(H::SparseMatrixCSC{Float64,Int64},classes::Vector{Int64},k::Int64)\n    \"\"\"\n    Compute relative affinity scores for both classes in a hypergraph H with\n        two classes, only for hyperedges of size k.\n\n        Aff1[t] = type-t relative affinity score for class 1\n        Aff0[t] = type-t relative affinity score for class 0\n    \"\"\"\n    N_all = get_hyperedge_counts(H,classes)\n    N = N_all[k,:]\n    Aff1 = zeros(k)\n    Aff0 = zeros(k)\n    c1_denom = sum(i*N[i+1] for i = 1:k)\n    c0_denom = sum(i*N[k-i+1] for i = 1:k)\n    for t = 1:k\n        Aff1[t] = t*N[t+1]/c1_denom\n        Aff0[t] = t*N[k-t+1]/c0_denom\n    end\n    return Aff1, Aff0\nend\n\nfunction incidence2elist(Hin::SparseMatrixCSC{Float64,Int64})\n    \"\"\" Convert a hyperedge list to a hypergraph binary incidence matrix. \"\"\"\n    H = sparse(Hin')\n    rp = H.rowval\n    ci = H.colptr\n    Hyperedges = Vector{Vector{Int64}}()\n    n,m = size(H)\n    for i = 1:m\n        startedge = ci[i]\n        endedge = ci[i+1]-1\n        edge = rp[startedge:endedge]\n        push!(Hyperedges,edge)\n    end\n    return Hyperedges\nend\n\n\n\nfunction elist2incidence(Hyperedges::Vector{Vector{Int64}}, N::Int64)\n    \"\"\"\n    Take a list of hyperedges and turn it into a hyperedge incidence matrix\n    H. N is the number of nodes in the hypergraph.\n    H(e,u) = 1  iff node u is in hyperedge e.\n    \"\"\"\n    U = Vector{Int64}()\n    E = Vector{Int64}()\n    M = length(Hyperedges)\n    for enum = 1:length(Hyperedges)\n        e = Hyperedges[enum]\n        for node in e\n            push!(U,node)\n            push!(E,enum)\n        end\n    end\n\n    H = sparse(E,U,ones(length(U)),M,N)\n    return H\nend\n\n\nfunction read_hypergraph_data(dataname::String, maxsize::Int64=25)\n    \"\"\"\n    Read data from .txt file to incidence matrix, and extract\n    class labels.\n    \"\"\"\n    classes = Int64[]\n    open(\"../original-data/$dataname/node-labels-$dataname.txt\") do f\n        for line in eachline(f)\n            push!(classes, parse(Int64, line))\n        end\n    end\n    n = length(classes)\n\n    # hyperedges\n    EdgeList = Vector{Vector{Int64}}()\n    open(\"../original-data/$dataname/hyperedges-$dataname.txt\") do f\n        for line in eachline(f)\n            edge = [parse(Int64, v) for v in split(line, ',')]\n            sort!(edge)\n            push!(EdgeList,edge)\n        end\n    end\n\n    H = elist2incidence(EdgeList,n)\n\n    return H,classes\nend\n\n\nfunction Hypergraph_to_Scores(H,classes,r)\n    n = size(H,2)\n    alpha = sum(classes)/n\n    B1 = baselines(r,alpha)\n    B2 = baselines(r,1-alpha)\n    H1, H2 = relative_affinities(H,classes,r)\n\n    N = get_hyperedge_counts(H,classes)\n    N = N[1:r,1:r+1]\n    R1 = H1./B1\n    R2 = H2./B2\n\n    return alpha, B1, B2, H1, H2, R1, R2, N\nend\n\nfunction GHI(H,classes,r)\n    \"\"\"\n    Group homophily index: largest value of j such that the top j affinity\n    scores are above baseline.\n    \"\"\"\n    alpha, B1, B2, H1, H2, R1, R2, N = Hypergraph_to_Scores(H,classes,r)\n    Sets1 = zeros(r)\n    Sets2 = zeros(r)\n    for k = 1:r\n        last1 = k\n        last2 = k\n        c1searching = true\n        c2searching = true\n\n        if R1[k,k] < 1\n            c1searching = false\n            last1 = k+1\n        end\n\n        if R2[k,k] < 1\n            c2searching = false\n            last2 = k+1\n        end\n\n        for j = k:-1:1\n            # @assert(R1[k,k] >= 1)\n            # @assert(R2[k,k] >= 1)\n            if R1[k,j] > 1 && c1searching\n                last1 = j\n            else\n                c1searching = false\n            end\n            if R2[k,j] > 1 && c2searching\n                last2 = j\n            else\n                c2searching = false\n            end\n            if R1[k,j] < 1 && R2[k,j] < 1\n                break\n            end\n        end\n        Sets1[k] = last1\n        Sets2[k] = last2\n    end\n\n    ## Set-in plot\n    S1 = collect(1:r) - Sets1 .+ 1\n    S2 = collect(1:r) - Sets2 .+ 1\n\n    return S1, S2\nend\n\nfunction Bootstrap_Affinities(H,k,B,classes)\n    n = size(H,2)\n    R1 = zeros(B,k)\n    R0 = zeros(B,k)\n\n    A1 = zeros(B,k)\n    A0 = zeros(B,k)\n\n    order = vec(sum(H,dims = 2))\n    Ek = findall(x->x==k,order)\n\n    alpha = sum(classes)/n\n    B1 = arbitrary_baselines(k,alpha)\n    B0 = arbitrary_baselines(k,1-alpha)\n    for i = 1:B\n        sam = sample(Ek,length(Ek))\n        Hnew = H[sam,:]\n        Elist = incidence2elist(Hnew)\n        Nk = zeros(k+1)\n        for edge in Elist\n            elabels = classes[edge]\n            t = sum(elabels)\n            Nk[t+1] += 1\n        end\n        c1_denom = sum(i*Nk[i+1] for i = 1:k)\n        c0_denom = sum(i*Nk[k-i+1] for i = 1:k)\n        for t = 1:k\n            A1[i,t] = (t*Nk[t+1]/c1_denom)\n            A0[i,t] = (t*Nk[k-t+1]/c0_denom)\n            R1[i,t] = (t*Nk[t+1]/c1_denom)/B1[t]\n            R0[i,t] = (t*Nk[k-t+1]/c0_denom)/B0[t]\n        end\n    end\n\n    # Average of the random trials\n    MR1 = vec(mean(R1,dims = 1))\n    MR0 = vec(mean(R0,dims = 1))\n    MA1 = vec(mean(A1,dims = 1))\n    MA0 = vec(mean(A0,dims = 1))\n\n    # Compute standard error\n    SR1 = zeros(k)\n    SR0 = zeros(k)\n    SA1 = zeros(k)\n    SA0 = zeros(k)\n    for t = 1:k\n        SR1[t] = StatsBase.std(R1[:,t])\n        SR0[t] = StatsBase.std(R0[:,t])\n        SA1[t] = StatsBase.std(A1[:,t])\n        SA0[t] = StatsBase.std(A0[:,t])\n    end\n\n    return R0, R1, MR1, MR0, SR1, SR0, A0, A1, MA1, MA0, SA1, SA0\n\nend\n\n\nfunction Bootstrap_From_N(Nk_old,B,alpha)\n\n    k = length(Nk_old)-1\n\n    R1 = zeros(B,k)\n    R0 = zeros(B,k)\n    A1 = zeros(B,k)\n    A0 = zeros(B,k)\n    B1 = arbitrary_baselines(k,alpha)\n    B0 = arbitrary_baselines(k,1-alpha)\n\n    for i = 1:B\n        Nk = zeros(k+1)\n        # @show Nk_old\n        for j = 1:round(Int64,sum(Nk_old))\n            Nk[sample(1:k+1,Nk_old)] += 1\n        end\n        c1_denom = sum(i*Nk[i+1] for i = 1:k)\n        c0_denom = sum(i*Nk[k-i+1] for i = 1:k)\n        for t = 1:k\n            A1[i,t] = (t*Nk[t+1]/c1_denom)\n            A0[i,t] = (t*Nk[k-t+1]/c0_denom)\n            R1[i,t] = (t*Nk[t+1]/c1_denom)/B1[t]\n            R0[i,t] = (t*Nk[k-t+1]/c0_denom)/B0[t]\n        end\n    end\n\n    # Average of the random trials\n    MR1 = vec(mean(R1,dims = 1))\n    MR0 = vec(mean(R0,dims = 1))\n    MA1 = vec(mean(A1,dims = 1))\n    MA0 = vec(mean(A0,dims = 1))\n\n    # Compute standard error\n    SR1 = zeros(k)\n    SR0 = zeros(k)\n    SA1 = zeros(k)\n    SA0 = zeros(k)\n    for t = 1:k\n        SR1[t] = StatsBase.std(R1[:,t])\n        SR0[t] = StatsBase.std(R0[:,t])\n        SA1[t] = StatsBase.std(A1[:,t])\n        SA0[t] = StatsBase.std(A0[:,t])\n    end\n\n    return R0, R1, MR1, MR0, SR1, SR0, A0, A1, MA1, MA0, SA1, SA0\n\nend\n", "meta": {"hexsha": "326aa77cd2ea9f9152c14b8f6dd5fbe2bee01c21", "size": 11426, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hypergraph-affinity-functions.jl", "max_stars_repo_name": "nveldt/HypergraphHomophily", "max_stars_repo_head_hexsha": "f0192317f1bd76c038f25c90f17bf885a1c77e1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-03-23T20:19:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T20:46:56.000Z", "max_issues_repo_path": "src/hypergraph-affinity-functions.jl", "max_issues_repo_name": "nveldt/HypergraphHomophily", "max_issues_repo_head_hexsha": "f0192317f1bd76c038f25c90f17bf885a1c77e1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hypergraph-affinity-functions.jl", "max_forks_repo_name": "nveldt/HypergraphHomophily", "max_forks_repo_head_hexsha": "f0192317f1bd76c038f25c90f17bf885a1c77e1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7342342342, "max_line_length": 97, "alphanum_fraction": 0.5504988622, "num_tokens": 3817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966101527047, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7843405616401171}}
{"text": "#script for solving a 1D BVP of the form\n# -a0(x)*u''(x)+a1(x)*u(x)=f(x) for x ∈ (0,1)\n# Here a0(x)=1, a1(x)=0, f(x)=4*π^2*sin(2*π*x)\n# with Dirichlet boundary conditions u(0) = 0, u(1)=0\ninclude(\"../src/Solver1D.jl\")\n\n\na0(x) = 1\na1(x) = 0\nf(x) = (4*π^2)*sin(2*π*x)\nexact_sol(x) = sin(2*π*x)\n\nptLeft = 0.\nptRight = 1.\nuPtLeft = 0.\nuPtRight = 1.\nnrb = nrbline(ptLeft, ptRight)\n\nsolPtLeft = exact_sol(ptLeft)\nsolPtRight = exact_sol(ptRight)\n\nbound_left = Boundary1D(\"Dirichlet\", ptLeft, uPtLeft, solPtLeft)\nbound_right = Boundary1D(\"Dirichlet\", ptRight, uPtRight, solPtRight)\n\nnumElem = 10\ndegP = 2\nnew_knots = collect(LinRange(ptLeft, ptRight, numElem+1)[2:end-1])\nnrb = nrbdegelev(nrb, [degP-1])\nnrb = nrbkntins(nrb, [new_knots])\n\n\n#refine some more knots at the beginning\nptMid = (ptLeft+ptRight)/2\nnewer_knots = collect(LinRange(ptLeft, ptMid, numElem+1))[2:end-1]\nnewer_knots = setdifftol(newer_knots, new_knots)\n#@show newer_knots\nnrb = nrbkntins(nrb, [newer_knots])\n\n\nprob_sin = Problem1D(f, a0, a1, [bound_left, bound_right], nrb)\nIGAmesh = genMesh(prob_sin.domain)\nplotBasisParam(IGAmesh)\n\ngauss_rule = genGaussLegendre(degP+1)\nstiff = assemble_stiff(IGAmesh, a0, gauss_rule)\nmass = assemble_mass(IGAmesh, a1, gauss_rule)\nrhs = assemble_rhs(IGAmesh, f, gauss_rule)\nlhs, rhs = applyBCnurbs(prob_sin.boundary_cond, stiff, mass, rhs, nrb)\nsol0 = lhs\\rhs\nplotSol(IGAmesh, real(sol0), \"Poisson1D\")\nplotSolError(IGAmesh, real(sol0), exact_sol, \"Poisson1D\")\n", "meta": {"hexsha": "10a212a5059659f9d12fe461759ccf930a88e533", "size": 1458, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/IGA1D.jl", "max_stars_repo_name": "canitesc/IGAPack.jl", "max_stars_repo_head_hexsha": "bb2b5e8d01afd9ca8a59055380ca00d2c8f951b1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-07-30T13:49:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T08:18:26.000Z", "max_issues_repo_path": "examples/IGA1D.jl", "max_issues_repo_name": "canitesc/IGAPack.jl", "max_issues_repo_head_hexsha": "bb2b5e8d01afd9ca8a59055380ca00d2c8f951b1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/IGA1D.jl", "max_forks_repo_name": "canitesc/IGAPack.jl", "max_forks_repo_head_hexsha": "bb2b5e8d01afd9ca8a59055380ca00d2c8f951b1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-30T13:49:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-09T11:32:36.000Z", "avg_line_length": 28.0384615385, "max_line_length": 70, "alphanum_fraction": 0.7139917695, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660962919971, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7843405594140956}}
{"text": "using JuMP, Plots, LinearAlgebra, SparseArrays, Ipopt\r\n\r\n#A JuMP model is initialized\r\nmod = Model(optimizer_with_attributes(Ipopt.Optimizer ,  \"max_iter\" => 100,\r\n                                        \"mumps_mem_percent\" => 500))\r\n#The parameters of the 2-D body\r\nλ = 45.0                            # Conductivity\r\nc = 460.0                           # Specific heat capacitivity\r\nρ = 7800.0                          # Material density\r\nL = 0.1                             #Length and width of body are assumed equivalent\r\nα = λ / (c*ρ)                       # Diffusivity\r\nN = 11                              # Number of Discretization points N_x = N_y\r\nh = L / (N - 1)                     #Δx = Δy = h\r\n\r\n\r\n#System , input and output matrices: θ' = Aθ(t) + Bu(t)\r\nA = spdiagm(0 => -4*ones(N^2))\r\nfor i in 1:N^2\r\n    if i%N == 1\r\n        A[i+1,i] = 2\r\n    elseif i%N == 0\r\n        A[i-1,i] = 2\r\n    else\r\n        A[i-1,i] = 1\r\n        A[i+1,i] = 1\r\n    end\r\n    if (i <= N)\r\n        A[i+N,i] = 2\r\n    elseif N^2 - i < N\r\n        A[i- N,i] = 2\r\n    else\r\n        A[i-N,i] = 1\r\n        A[i+N,i] = 1\r\n    end\r\nend\r\nA *= α / (h^2);\r\n\r\nB = spzeros(3,N^2);\r\nB[1,1] = 1;\r\nB[2,6] = 1;\r\nB[3,11] = 1;\r\nB *= (2/ (c * ρ * h));\r\n#y(t) = Cθ(t)\r\nC = spzeros(N^2,1)\r\nC[111] = 1.0;\r\nC[115] = 1.0;\r\nC[end] = 1.0;\r\n#Integration from t0 = 0 to tf\r\ntf = 40000.0;                   #Final time\r\ndt = 1.6;                       #Sampling period Δt\r\nsteps = round(Int,tf / dt);     #number of time steps in simulation.\r\n\r\nu_min = 0.0                     #lower input bound\r\nu_max = 15000.0                 #upper input bound\r\n@variable(mod,θ[1:N^2,1:steps]);                                      # state vector\r\n@variable(mod,u_min <= u[i = 1:3,k = 1:steps - 1] <= u_max);          # Bounded Input u\r\n\r\nθinit = 273.0                           #initial temperature of the body\r\nθref = 500.0                            #Reference temperature\r\n\r\n@constraint(mod, θ[:,1] .== θinit)      #Initial value added as constraints\r\n#System dynamics\r\nfor k in 1:steps - 1,i in 1:N^2\r\n    @constraint(mod,θ[i,k + 1] .==  θ[i,k] + dt * ((A[:,i]' * θ[:,k]) + B[:,i]' * u[:,k]))\r\nend\r\n#Q and R weighing matrices\r\nQ = 10000 * C * C';\r\nR = 0.0001 * I;\r\n#Cost function\r\n@NLobjective(mod, Min, 0.5 * dt * sum(sum(Q[i,i] *(θref - θ[i,k])^2 for i in 1:N^2)\r\n+ sum(R[i,i] * u[i,k]^2 for i in 1:3) for k in 1:steps - 1))\r\n#Optimization process\r\noptimize!(mod)\r\n\r\n#Plotting results\r\nstates_θstart1 = zeros(steps)\r\nstates_θstart2 = zeros(steps)\r\nstates_θstart3 = zeros(steps)\r\nstates_θend3 = zeros(steps)\r\nstates_θend2 = zeros(steps)\r\nstates_θend1 = zeros(steps)\r\ninput_u1 = zeros(steps - 1)\r\ninput_u2 = zeros(steps - 1)\r\ninput_u3 = zeros(steps - 1)\r\nfor i = 1 : steps-1\r\n    states_θstart1[i] = JuMP.value(θ[1,i])\r\n    states_θstart2[i] = JuMP.value(θ[6,i])\r\n    states_θstart3[i] = JuMP.value(θ[11,i])\r\n    states_θend3[i] = JuMP.value(θ[115,i])\r\n    states_θend2[i] = JuMP.value(θ[85,i])\r\n    states_θend1[i] = JuMP.value(θ[45,i])\r\n    input_u1[i] = JuMP.value(u[1,i])\r\n    input_u2[i] = JuMP.value(u[2,i])\r\n    input_u3[i] = JuMP.value(u[3,i])\r\nend\r\n\r\nstates_θend3[end] = JuMP.value(θ[end,end])\r\nstates_θend2[end] = JuMP.value(θ[end-5,end])\r\nstates_θend1[end] = JuMP.value(θ[end-10,end])\r\nstates_θstart1[end] = JuMP.value(θ[1,end])\r\nstates_θstart2[end] = JuMP.value(θ[6,end])\r\nstates_θstart3[end] = JuMP.value(θ[11,end])\r\n#Plotting temperatures at the input nodes\r\np2 = plot(states_θstart1, label = \"θ_in1\",legend = false)\r\np2 = plot!(states_θstart2,label = \"θ_in2\",legend = false)\r\np2 = plot!(states_θstart3,label = \"θ_in3\",legend = false)\r\nsavefig(\"lq_optimal_2D.png\")\r\n#Plotting temperatures at the output\r\np1 = plot(states_θend3,label = \"output-3\",legend = false)\r\np1 = plot!(states_θend2,label = \"output-2\",legend = false)\r\np1 = plot!(states_θend1,label = \"output-1\",legend = false)\r\nsavefig(\"lq_optimal_2D-output-bounded.png\")\r\n#Plotting the input signals\r\np3 = plot(input_u1,label = \"in_1\",legend = false)\r\np3 = plot!(input_u2,label = \"in_2\",legend = false)\r\np3 = plot!(input_u3,label = \"in_3\",legend = false)\r\nsavefig(\"lq_optimal_2D_inputbounded.png\")\r\n", "meta": {"hexsha": "1515232be9ab10022abe6a418d25e5716aeaa878", "size": 4119, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lq-OCP_heat_2D.jl", "max_stars_repo_name": "jayborkhatariya17/Optimal-boundary-control-of-the-heat-equation", "max_stars_repo_head_hexsha": "a820be2b0d175f1c4bc7093753f0dd591888f668", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lq-OCP_heat_2D.jl", "max_issues_repo_name": "jayborkhatariya17/Optimal-boundary-control-of-the-heat-equation", "max_issues_repo_head_hexsha": "a820be2b0d175f1c4bc7093753f0dd591888f668", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lq-OCP_heat_2D.jl", "max_forks_repo_name": "jayborkhatariya17/Optimal-boundary-control-of-the-heat-equation", "max_forks_repo_head_hexsha": "a820be2b0d175f1c4bc7093753f0dd591888f668", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-21T10:00:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-17T12:51:52.000Z", "avg_line_length": 34.906779661, "max_line_length": 91, "alphanum_fraction": 0.5554746298, "num_tokens": 1433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660949832346, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7843405583380453}}
{"text": "## NACA Parametrisations\n#==========================================================================================#\n\n# NACA 4-digit parameter functions\nnaca4_thickness(t_by_c, xc, sharp_trailing_edge :: Bool) = 5 * t_by_c * (0.2969 * √xc - 0.1260 * xc - 0.3516 * xc^2 + 0.2843 * xc^3 - (ifelse(sharp_trailing_edge, 0.1036, 0.1015) * xc^4))\n\nnaca4_camberline(pos, cam, xc) = ifelse(\n                                        xc < pos, \n                                        (cam / pos^2) * xc * (2 * pos - xc), \n                                        cam / (1 - pos)^2 * ( (1 - 2 * pos) + 2 * pos * xc - xc^2) \n                                       )\n\nnaca4_gradient(pos, cam, xc) = atan(2 * cam / (ifelse(xc < pos, pos^2, (1 - pos)^2)) * (pos - xc))\n\n\"\"\"\n    naca4_coordinates(digits :: NTuple{4, <: Real}, n :: Integer, sharp_trailing_edge :: Bool)\n\nGenerate the coordinates of a NACA 4-digit series profile with a specified number of points, and a Boolean flag to specify a sharp or blunt trailing edge.\n\"\"\"\nfunction naca4_coordinates(digits :: NTuple{4, <: Real}, n :: Integer, sharp_trailing_edge :: Bool)\n    # Camber\n    cam = digits[1] / 100\n    # Position\n    pos = digits[2] / 10\n    # Thickness-to-chord ratio\n    t_by_c = (10 * digits[3] + digits[4]) / 100\n\n    # Cosine spacing\n    xs = cosine_spacing(0.5, 1.0, n)\n\n    # Thickness distribution\n    thickness = naca4_thickness.(Ref(t_by_c), xs, Ref(sharp_trailing_edge))\n    if pos == 0 || cam == 0\n        x_upper = xs\n        y_upper = thickness\n        x_lower = xs\n        y_lower = -thickness\n    else\n        # Compute camberline\n        camber  = naca4_camberline.(Ref(pos), Ref(cam), xs)\n        # Compute gradients\n        grads   = naca4_gradient.(Ref(pos), Ref(cam), xs)\n        # Upper surface\n        x_upper = @. xs - thickness * sin(grads)\n        y_upper = @. camber + thickness * cos(grads)\n        # Lower surface\n        x_lower = @. xs + thickness * sin(grads)\n        y_lower = @. camber - thickness * cos(grads)\n    end\n    coords = [ [x_upper y_upper][end:-1:2,:];\n                x_lower y_lower             ]\nend\n\n\"\"\"\n    naca4(digits :: NTuple{4, <: Real}, n :: Integer = 40; sharp_trailing_edge :: Bool)\n\nGenerate a `Foil` of a NACA 4-digit series profile with a specified number of points (40 by default), and a named option to specify a sharp or blunt trailing edge.\n\"\"\"\nnaca4(digits :: NTuple{4, <: Real}, n = 40; sharp_trailing_edge = true) = Foil(naca4_coordinates(digits, n, sharp_trailing_edge), string(\"NACA \", digits...))\n\nnaca4(a, b, c, d, n = 40; sharp_trailing_edge = true) = naca4((a,b,c,d), n; sharp_trailing_edge = sharp_trailing_edge)\n", "meta": {"hexsha": "c88721c945a8e167a6ca78768816d86aeebc1909", "size": 2644, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Geometry/AircraftGeometry/Foils/naca_airfoils.jl", "max_stars_repo_name": "HKUST-OCTAD-LAB/AeroMDAO.jl", "max_stars_repo_head_hexsha": "0ca9aa924f088cac59d04958eb5c6704b50feb18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Geometry/AircraftGeometry/Foils/naca_airfoils.jl", "max_issues_repo_name": "HKUST-OCTAD-LAB/AeroMDAO.jl", "max_issues_repo_head_hexsha": "0ca9aa924f088cac59d04958eb5c6704b50feb18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Geometry/AircraftGeometry/Foils/naca_airfoils.jl", "max_forks_repo_name": "HKUST-OCTAD-LAB/AeroMDAO.jl", "max_forks_repo_head_hexsha": "0ca9aa924f088cac59d04958eb5c6704b50feb18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6451612903, "max_line_length": 187, "alphanum_fraction": 0.5593797277, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661028358093, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7843405544034485}}
{"text": "##\n# Demo of using DualNumbers to differentiate with respect to\n# changes in parameters\n##\n\n\nusing DualNumbers, ApproxFun\n# What is the derivative of the function (without differentiating the Chebyshev expansion)?\nf=Fun(x->exp(dual(x,1)),[-1,1])\ndualpart(f)\n# check versus differentiate\nnorm(realpart(f)'-dualpart(f))\n\n# What is the derivative of the first coefficient with respect to the left endpoint?\nf=Fun(exp,Interval(dual(1.0,1),dual(2.0)))\ndualpart(f.coefficients[1])\n# check versus finite difference calculation:\nh=0.00001;(Fun(exp,Interval(1.0+h,2.0)).coefficients[1]-Fun(exp,Interval(1.0,2.0)).coefficients[1])/h\n\n# Or an ApproxFun calculation:\nFun(h->Fun(exp,Interval(1.0+h,2.0)).coefficients[1],[0.,.1])'(0.)\n\n# What is the derivative of the first coefficient with respect to the exponential's constant?\nf=Fun(x->exp(dual(x,x)),[-1,1])\ndualpart(f.coefficients[1])\n# check versus finite difference calculation:\nh=0.00001;(Fun(x->exp((1+h)x),[-1,1]).coefficients[1]-Fun(exp,[-1,1]).coefficients[1])/h\n", "meta": {"hexsha": "cfa5e1af0253928e41a853d68a5dc22b42a7cfdd", "size": 1011, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Dual Numbers.jl", "max_stars_repo_name": "JuliaPackageMirrors/ApproxFun.jl", "max_stars_repo_head_hexsha": "f73e9d168b0d139efa2953b1bad7fac808db2d8d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Dual Numbers.jl", "max_issues_repo_name": "JuliaPackageMirrors/ApproxFun.jl", "max_issues_repo_head_hexsha": "f73e9d168b0d139efa2953b1bad7fac808db2d8d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Dual Numbers.jl", "max_forks_repo_name": "JuliaPackageMirrors/ApproxFun.jl", "max_forks_repo_head_hexsha": "f73e9d168b0d139efa2953b1bad7fac808db2d8d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1071428571, "max_line_length": 101, "alphanum_fraction": 0.727992087, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342024724487, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7843380011991057}}
{"text": "using Plots, LaTeXStrings, Statistics\n\nfunction Deposition(;len, tot_time)\n    surf = [0 for i=1:len]\n    AvgList = [0.0 for i=1:tot_time]\n    for n in 2:tot_time+1\n        randsurf = rand(1:len)\n        for i in randsurf\n            MAX = FindMax(surf, i, len)\n            surf[i] = MAX\n        end\n        AvgList[n-1] = mean(surf)\n    end\n    return AvgList\nend\n\nfunction sides(n, L)\n    if n == L\n        return n-1 , 1\n    elseif n == 1\n        return L , n+1\n    else\n        return n-1, n+1\n    end\nend\n\nfunction FindMax(surface, index_,L_surf)\n    i1 , i2 = sides(index_, L_surf)\n    maxlen = max(surface[i1],surface[index_] + 1,surface[i2])\n    return maxlen\nend\nfunction Linear_fit(;Time, AvgList, tot_time)\n    A = [hcat(Time[1:tot_time]) reshape(ones(tot_time), tot_time, 1)]\n    b = reshape(AvgList[1:tot_time], tot_time, 1)\n    line = (A \\ b)\n    return line\nend\n\niternum = 1000\nParameters = Dict(:len => 300,\n                    :tot_time => 50,)\nallAvg = [ [0.0 for i in 1:Parameters[:tot_time]] for j = 1:iternum]\nmeanAvg = [0.0 for i in 1:Parameters[:tot_time]]\nvars = [0.0 for i in 1:Parameters[:tot_time]]\nfor i in 1:iternum\n    AvgList = Deposition(;Parameters...)\n    allAvg[i] = AvgList\n    meanAvg += AvgList\n    print(\"\\r$i\")\nend\nmeanAvg /= iternum\nfor i in 1:Parameters[:tot_time]\n    vars[i] = std(hcat(allAvg...)[i,:])\nend\n\nTime = 0:Parameters[:tot_time]-1\n\nParaline = Dict(\n                :Time => Time[1:end],\n                :AvgList => meanAvg[1:end],\n                :tot_time => 50)\nLine = Linear_fit(;Paraline...)\nX = Time[1]:Time[50]\nY = X .* Line[1] .+ Line[2]\nLine[2]\nplot(X,Y,c=:black,label = L\"y = %$(round(Line[1],digits= 3))x + %$(round(Line[2],digits= 3))\")\nscatter!(Time[1:end], meanAvg[1:end],\n    # xlims = (1, Parameters[:tot_time]),\n    c = :steelblue,\n    xlabel= L\"Time\",\n    ylabel= L\"H_{(t)}\",\n    title= L\"~H_{(t)}-Time~\\ (L = %$(Parameters[:len]))\",\n    label = L\"Data\\ point\",\n    yerror = vars)\n    # legend = nothing)\n\nsavefig(\"../../Figs/Q2/H-t(L=$(Parameters[:len])).pdf\")\n", "meta": {"hexsha": "32a76a23a6c68288f481d6628621fc78d6edea49", "size": 2033, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSet3/Codes/Q2/Q2-H(t).jl", "max_stars_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_stars_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSet3/Codes/Q2/Q2-H(t).jl", "max_issues_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_issues_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSet3/Codes/Q2/Q2-H(t).jl", "max_forks_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_forks_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-21T11:07:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-21T11:07:08.000Z", "avg_line_length": 26.0641025641, "max_line_length": 94, "alphanum_fraction": 0.5745204132, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8872045847699186, "lm_q1q2_score": 0.784323709302873}}
{"text": "# Laplacian Eigenmaps\n# -------------------\n# Laplacian Eigenmaps for Dimensionality Reduction and Data Representation,\n# M. Belkin, P. Niyogi, Neural Computation, June 2003; 15 (6):1373-1396\n\n#### LEM type\nstruct LEM{T <: Real} <: AbstractDimensionalityReduction\n    k::Int\n    λ::AbstractVector{T}\n    t::T\n    proj::Projection{T}\n    component::Vector{Int}\n\n    LEM{T}(k::Int, λ::AbstractVector{T}, t::T, proj::Projection{T})  where T = new(k, λ, t, proj)\n    LEM{T}(k::Int, λ::AbstractVector{T}, t::Float64, proj::Projection{T}, cc::Vector{Int})  where T = new(k, λ, t, proj, cc)\nend\n\n## properties\noutdim(R::LEM) = size(R.proj, 1)\neigvals(R::LEM) = R.λ\nneighbors(R::LEM) = R.k\nvertices(R::LEM) = R.component\n\n## show\nsummary(io::IO, R::LEM) = print(io, \"Laplacian Eigenmaps(outdim = $(outdim(R)), neighbors = $(neighbors(R)), t = $(R.t))\")\n\n## interface functions\nfunction fit(::Type{LEM}, X::AbstractMatrix{T}; maxoutdim::Int=2, k::Int=12, t::Real=1.0) where {T<:Real}\n    # Construct NN graph\n    D, E = find_nn(X, k)\n    G, C = largest_component(SimpleWeightedGraph(adjmat(D,E)))\n\n    # Compute weights\n    W = weights(G)\n    W .^= 2\n    W ./= maximum(W)\n\n    W[W .> eps(T)] = exp.(-W[W .> eps(T)] ./ convert(T,t))\n    D = diagm(0 => sum(W, dims=2)[:])\n    L = D - W\n\n    λ, V = decompose(L, D, maxoutdim)\n    return LEM{T}(k, λ, t, transpose(V), C)\nend\n\ntransform(R::LEM) = R.proj\n", "meta": {"hexsha": "e157dd100e1901cb5054200165a873406c7ba1f8", "size": 1390, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lem.jl", "max_stars_repo_name": "adediego/ManifoldLearning.jl", "max_stars_repo_head_hexsha": "f7969c1b05897659beafa6491d875de5497be1da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lem.jl", "max_issues_repo_name": "adediego/ManifoldLearning.jl", "max_issues_repo_head_hexsha": "f7969c1b05897659beafa6491d875de5497be1da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lem.jl", "max_forks_repo_name": "adediego/ManifoldLearning.jl", "max_forks_repo_head_hexsha": "f7969c1b05897659beafa6491d875de5497be1da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5744680851, "max_line_length": 124, "alphanum_fraction": 0.6043165468, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802529509909, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7843020064511279}}
{"text": "using Plots\nusing FFTW\n\ncos_taylor(x) = 1-( x^2/2 )+( x^4/24.0 )-( x^6/720.0 )+( x^8/40320.0 );\n\n\"\"\"\nCalculate cos(x) with a five-term Taylor series, using only the quarter-waves closest to the origin for increased accuracy.\n\"\"\"\nfunction fast_cos( x::Float64 ) \n        if x < -π/2\n            x = -π/2 + abs(x+π/2);\n            return -cos_taylor(x);\n        elseif π/2 < x\n            x = π/2 - abs(x-π/2);\n            return -cos_taylor(x)\n        else\n            return cos_taylor(x)\n        end\nend\n\nx = LinRange(-π, π, 1000);\n\n\ncosx_taylor = cos_taylor.(x);\ncosx_native = cos.(x);\n\ndelta = cosx_native-cosx_taylor\n\n# Time domain comparison.\nplot( \tx, cosx_native,\n\t \tlabel = \"Julia native cosine\",\n        size = (1024, 720),)\nplot!( \tx, cosx_taylor,\n\t \tlabel = \"5-term Taylor series\",)\nplot!( \tx, delta*100,\n\t \tlabel = \"Difference*100\",)\n\nsavefig(\"figures/cos/time_domain\")\n\n\ntaylor_cos2 = fast_cos.(x);\ndelta2 = cosx_native-taylor_cos2\n\n# Taylor vs first quarter taylor.\nplot( \tx, delta*100,\n\t \tlabel = \"Difference\",\n        size = (1024, 720),)\nplot!( \tx, delta2*100,\n\t \tlabel = \"Difference (first quarter)\",)\n\nsavefig(\"figures/cos/time_domain_comparison2\")\n\n\n\"\"\"\nWrap sample to a -π =< sample < π range.\n\"\"\"\nfunction wrap_phase( sample::Float64 )\n    while π <= sample\n        sample = sample - 2π;\n    end\n    while sample < -π\n        sample = sample + 2π;\n    end\n    return sample;\nend\n\n# Frequency domain analysis\nx = LinRange(0, 1024π, 2^14);\nx = wrap_phase.(x);\ncosx_taylor = cos_taylor.(x);\ncosx_native = cos.(x);\n\n\"\"\"\nCalculate normalized power spectrum for real signals.\n\"\"\"\nfunction frequecny_domain_analysis( signal_t )\n    power_f = abs.(fft(signal_t)).^2;\n    normalized_power = power_f/maximum(power_f);\n    power_dB = 10*log10.(normalized_power);\n    return power_dB[1:Int(size(power_dB)[1]/2)]\nend\n\n\nomega = LinRange(0, 1, Int(size(x)[1]/2));\n\n# Frequency domain.\nplot( \tomega, frequecny_domain_analysis(cosx_native),\n\t \tlabel = \"Julia native cosine\",\n        ylims = [-100, 0],\n        size = (1024, 720),)\nxlabel!(\"Frequency relative to Fs\")\nylabel!(\"Normalized power [dBC]\")\n\nplot!( \tomega, frequecny_domain_analysis(cosx_taylor),\n\t \tlabel = \"5-term Taylor series\",)\n\nsavefig(\"figures/cos/frequency_domain\")\n\n\n# Frequency domain first quarter.\nplot( \tomega, frequecny_domain_analysis(cosx_native),\n\t \tlabel = \"Julia native cosine\",\n        ylims = [-100, 0],\n        size = (1024, 720),)\nxlabel!(\"Frequency relative to Fs\")\nylabel!(\"Normalized power [dBC]\")\n\nplot!( \tomega, frequecny_domain_analysis(fast_cos.(x)),\n\t \tlabel = \"5-term Taylor, first quarter\",)\n\nsavefig(\"figures/cos/frequency_domain2\")", "meta": {"hexsha": "dfe22a179791e222635702ba1aba396e36508713", "size": 2631, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "numerical_verificatons/cosine_verification.jl", "max_stars_repo_name": "ErikBuer/Integer-Array", "max_stars_repo_head_hexsha": "3f0dfe193e7dcca2d2d19aa21b335745cc13b7f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numerical_verificatons/cosine_verification.jl", "max_issues_repo_name": "ErikBuer/Integer-Array", "max_issues_repo_head_hexsha": "3f0dfe193e7dcca2d2d19aa21b335745cc13b7f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical_verificatons/cosine_verification.jl", "max_forks_repo_name": "ErikBuer/Integer-Array", "max_forks_repo_head_hexsha": "3f0dfe193e7dcca2d2d19aa21b335745cc13b7f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7027027027, "max_line_length": 123, "alphanum_fraction": 0.6419612315, "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7843019975182698}}
{"text": "\"\"\" \nJohnson Lindenstrauss effective resistance upperbounding. If retXhat is set to true,\nreturns the vectors necessary for computing the effective resistance bounds instead\nof the actual bounds. \n\n~~~julia\n\tjohnlind(a::SparseMatrixCSC{Tv,Ti}; eps::Tv = 0.5, solver=(la -> augTreeSolver(la,tol=1e-1,maxits=1000,maxtime=10)), retXhat::Bool = false)\n~~~\n\"\"\"\n\nfunction johnlind{Tv,Ti}(a::SparseMatrixCSC{Tv,Ti}; \n\t\t\t\t\t\teps::Tv = 0.5, \n\t\t\t\t\t\tsolver=(la -> augTreeSolver(la,tol=1e-1,maxits=1000,maxtime=10)), \n\t\t\t\t\t\tretXhat::Bool = false)\n\n\tn = a.n\n\tm = length(a.nzval)\n\tdhat = ceil(Int64, 4 * log(m) / eps^2)\n\n\tP = ones(dhat, m)\n\tfor i in 1:dhat\n\t\tfor j in 1:m\n\t\t\tif rand() < 1/2\n\t\t\t\tP[i,j] = -P[i,j]\n\t\t\tend\n\t\tend\n\tend\n\t# we want ||P * x|| = ||x||\n\tP = P / sqrt(dhat)\n\n\t# compute B\n\tU = Ti[]\n\tV = Ti[]\n\tW = Tv[]\n\n\tpos = 1\n\tfor i in 1:length(a.nzval)\n\t\twhile a.colptr[pos + 1] <= i\n\t\t\tpos = pos + 1\n\t\tend\n\n\t\tp = a.rowval[i]\n\t\tq = pos\n\t\tw = sqrt(a.nzval[i])\n\n\t\tif p > q\n\t\t\taux = p\n\t\t\tp = q\n\t\t\tq = aux\n\t\tend\n\n\t\t# multiply B by W\n\t\tpush!(U, i)\n\t\tpush!(V, p)\n\t\tpush!(W, w)\n\n\t\tpush!(U, i)\n\t\tpush!(V, q)\n\t\tpush!(W, -w)\n\tend\n\n\tB = sparse(U, V, W)\n\n\t# Get bs = P * W^(1/2) * B. We already multiplied W by B. Solve for each line. dims are dhat x n\n\tbs = P * B / sqrt(2)\n\n\tf = solver(lap(a) + speye(a.n) * 1e-10)\n\n\t# xhat = P * W^(1/2) * B * L ^-1 * ei\n\txhat = zeros(n, dhat)\n\tfor i in 1:dhat\n\t\tb = reshape(bs[i,:], n)\n\t\tb = b - mean(b)\n\t\txhat[:,i] = f(b)\n\tend\n\n\tif retXhat\n\t\treturn xhat\n\tend\n\n\t# compute the effective resistance\n\treff = copy(a)\n\tpos = 1\n\tfor i in 1:m\n\t\twhile a.colptr[pos + 1] <= i\n\t\t\tpos = pos + 1\n\t\tend\n\n\t\tp = a.rowval[i]\n\t\tq = pos\n\n\t\treff.nzval[i] = norm(xhat[p,:] - xhat[q,:])^2\n\tend\n\n\treturn reff\n\nend", "meta": {"hexsha": "e404b417ae3bd81d5595f9c5b6722029ac2eb8ec", "size": 1709, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/johnlind.jl", "max_stars_repo_name": "JuliaPackageMirrors/Laplacians.jl", "max_stars_repo_head_hexsha": "553ea964b95359462ef4b8b6b01383310ab88f41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/johnlind.jl", "max_issues_repo_name": "JuliaPackageMirrors/Laplacians.jl", "max_issues_repo_head_hexsha": "553ea964b95359462ef4b8b6b01383310ab88f41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/johnlind.jl", "max_forks_repo_name": "JuliaPackageMirrors/Laplacians.jl", "max_forks_repo_head_hexsha": "553ea964b95359462ef4b8b6b01383310ab88f41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.618556701, "max_line_length": 140, "alphanum_fraction": 0.5669982446, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567085, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7843019904908556}}
{"text": "# # 210: 2D Nonlinear Poisson with reaction\n# ([source code](SOURCE_URL))\n\nmodule Example210_NonlinearPoisson2D_Reaction\n\nusing Printf\nusing VoronoiFVM\nusing ExtendableGrids\nusing GridVisualize\n\nfunction main(;n=10,Plotter=nothing,verbose=false, unknown_storage=:sparse)\n\n    h=1.0/convert(Float64,n)\n    X=collect(0.0:h:1.0)\n    Y=collect(0.0:h:1.0)\n\n    grid=VoronoiFVM.Grid(X,Y)\n    data = (eps=1.0e-2, k=1.0)\n\n    function reaction!(f,u,node,data)\n        f[1]=data.k*(u[1]-u[2])\n        f[2]=data.k*(u[2]-u[1])\n    end\n\n    function flux!(f,u0,edge,data)\n        u=unknowns(edge,u0)\n        f[1]=data.eps*(u[1,1]-u[1,2])\n        f[2]=data.eps*(u[2,1]-u[2,2])\n    end\n\n    function source!(f,node,data)\n        x1=node[1]-0.5\n        x2=node[2]-0.5\n        f[1]=exp(-20*(x1^2+x2^2))\n    end\n\n    function storage!(f,u,node,data)\n        f[1]=u[1]\n        f[2]=u[2]\n    end\n\n\n    physics=VoronoiFVM.Physics(num_species=2,\n                               data=data,\n                               flux=flux!,\n                               storage=storage!,\n                               reaction=reaction!,\n                               source=source!)\n\n\n    sys=VoronoiFVM.System(grid,physics,unknown_storage=unknown_storage)\n\n    enable_species!(sys,1,[1])\n    enable_species!(sys,2,[1])\n\n    inival=unknowns(sys)\n    U=unknowns(sys)\n    inival.=0.0\n\n\n    control=VoronoiFVM.NewtonControl()\n    control.verbose=verbose\n    control.tol_linear=1.0e-5\n    control.max_lureuse=0\n    tstep=0.01\n    time=0.0\n    istep=0\n    u15=0\n    p=GridVisualizer(Plotter=Plotter,layout=(2,1))\n    while time<1\n        time=time+tstep\n        solve!(U,inival,sys,control=control,tstep=tstep)\n        inival.=U\n        if verbose\n            @printf(\"time=%g\\n\",time)\n        end\n        u15=U[15]\n        tstep*=1.0\n        istep=istep+1\n        scalarplot!(p[1,1],grid,U[1,:],clear=true)\n        scalarplot!(p[2,1],grid,U[2,:],show=true)\n    end\n    return u15\nend\n\nfunction test()\n    main(unknown_storage=:sparse) ≈ 0.014566189535134827 &&\n        main(unknown_storage=:dense) ≈ 0.014566189535134827\nend\nend\n", "meta": {"hexsha": "8006184a617ed6947799d0141d00bfa896140986", "size": 2099, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Example210_NonlinearPoisson2D_Reaction.jl", "max_stars_repo_name": "NunoEdgarGFlowHub/VoronoiFVM.jl", "max_stars_repo_head_hexsha": "c9f5834a2052414e9d174e7c423d9d68e1406fd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Example210_NonlinearPoisson2D_Reaction.jl", "max_issues_repo_name": "NunoEdgarGFlowHub/VoronoiFVM.jl", "max_issues_repo_head_hexsha": "c9f5834a2052414e9d174e7c423d9d68e1406fd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Example210_NonlinearPoisson2D_Reaction.jl", "max_forks_repo_name": "NunoEdgarGFlowHub/VoronoiFVM.jl", "max_forks_repo_head_hexsha": "c9f5834a2052414e9d174e7c423d9d68e1406fd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0659340659, "max_line_length": 75, "alphanum_fraction": 0.5683658885, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7843019896983705}}
{"text": "using HyperbolicPlane, Plots\n\n\"\"\"\n`regular(n,r)` draw a regular `n`-gon in the hyperbolic plane.\nThe vertices are distance `r` from the origin.\n\"\"\"\nfunction regular(n::Int=5, r::Real=1.0)\n    plot()\n    pts = [ HPoint(r, (k/n)*2pi) for k=0:n ]\n    for P in pts\n        set_radius(P,3)\n    end\n    draw(pts)\n\n    segs = [ HSegment(pts[k],pts[k+1]) for k=1:n ]\n    draw(segs)\n    draw(HPlane())\n    finish()\nend\n", "meta": {"hexsha": "fe824b61c43dcdf82d4f39499e7515ac859beeb9", "size": 410, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/regular.jl", "max_stars_repo_name": "switzel/HyperbolicPlane.jl", "max_stars_repo_head_hexsha": "89ba26e080b520b4f200e985f2b431b1d61ecb21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-01-19T06:12:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T22:18:48.000Z", "max_issues_repo_path": "examples/regular.jl", "max_issues_repo_name": "switzel/HyperbolicPlane.jl", "max_issues_repo_head_hexsha": "89ba26e080b520b4f200e985f2b431b1d61ecb21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-01-31T08:33:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T19:44:39.000Z", "max_forks_repo_path": "examples/regular.jl", "max_forks_repo_name": "switzel/HyperbolicPlane.jl", "max_forks_repo_head_hexsha": "89ba26e080b520b4f200e985f2b431b1d61ecb21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-31T21:10:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T18:49:43.000Z", "avg_line_length": 20.5, "max_line_length": 62, "alphanum_fraction": 0.5926829268, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9648551535992067, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7842992164339193}}
{"text": "##################################################\n## Classical derivative-based, iterative, root-finding algorithms: Newton and Halley\n## Historic, we have derivative free versions of similar order\n\n\n## Newton\n\"\"\"\n\n    Roots.Newton()\n\nImplements Newton's [method](http://tinyurl.com/b4d7vls): `x_n1 = xn -\nf(xn)/f'(xn)`.  This is a quadratically converging method requiring\none derivative. If a derivative is not specified, the `ForwardDiff` package\nwill be used, as applicable.\n\nUnlike other methods, this method accepts complex inputs.\n\"\"\"\nstruct Newton <: UnivariateZeroMethod\nend\n\nfunction callable_function(method::Newton, f::Tuple)\n    length(f) == 1 && return FirstDerivative(f[1], D(f[1]))\n    FirstDerivative(f[1], f[2])\nend\ncallable_function(method::Newton, f::Any) = FirstDerivative(f, D(f))\n\nfunction update_state(method::Newton, fs, o::UnivariateZeroState{T}, options::UnivariateZeroOptions) where {T}\n    xn = o.xn1\n    fxn = o.fxn1\n    fpxn = fs.fp(xn)\n\n    if isissue(fpxn)\n        o.stopped=true\n        return\n    end\n    \n    xn1 = xn - fxn / fpxn\n    fxn1 = fs.f(xn1)\n    incfn(o)\n    \n    o.xn0, o.xn1 = xn, xn1\n    o.fxn0, o.fxn1 = fxn, fxn1\n\n\n    incsteps(o)\n    \nend\n\n## extra work to allow for complex values\n\n## extra work to allow for complex values\nfunction derivative_free_setup(method::Newton, fs::CallableFunction, x0::T;\n                                  bracket=missing,\n                                  xabstol=zero(T), xreltol=zero(T),\n                                  abstol=4*eps(T), reltol=4*eps(T),\n                                  maxevals=40, maxfnevals=typemax(Int),\n                                  verbose::Bool=false) where {T<:AbstractFloat}\n    x = float(x0)\n\n\n    prob = UnivariateZeroProblem(fs, x, bracket)\n    options = UnivariateZeroOptions(xabstol, xreltol, abstol, reltol,  maxevals, maxfnevals, verbose)\n    prob, options\nend\n\nfunction derivative_free_setup(method::Newton, fs::CallableFunction, x0::Complex{T};\n                                  bracket=missing,\n                                  xabstol=zero(T), xreltol=zero(T),\n                                  abstol=4*eps(T), reltol=4*eps(T),\n                                  maxevals=40, maxfnevals=typemax(Int),\n                                  verbose::Bool=false) where {T<:AbstractFloat}\n    x = float(x0)\n    bracket = missing     # bracket makes no sense for complex input, but one is expected\n\n    prob = UnivariateZeroProblem(fs, x, bracket)\n    options = UnivariateZeroOptions(xabstol, xreltol, abstol, reltol,  maxevals, maxfnevals, verbose)\n    prob, options\nend\n\n\"\"\"\n\nImplementation of Newton's method: `x_n1 = x_n - f(x_n)/ f'(x_n)`\n\nArguments:\n\n* `f::Function` -- function to find zero of\n\n* `fp::Function=D(f)` -- derivative of `f`. Defaults to automatic derivative\n\n* `x0::Number` -- initial guess. For Newton's method this may be complex.\n\nKeyword arguments:\n\n* `ftol`. Stop iterating when |f(xn)| <= max(1, |xn|) * ftol.\n\n* `xtol`. Stop iterating when |xn+1 - xn| <= xtol + max(1, |xn|) * xtolrel\n\n* `xtolrel`. Stop iterating when |xn+1 - xn| <= xtol + max(1, |xn|) * xtolrel\n\n* `maxeval`. Stop iterating if more than this many steps, throw error.\n\n* `maxfneval`. Stop iterating if more than this many function calls, throw error.\n\n* `verbose::Bool=false` Set to `true` to see trace.\n\n\"\"\"\nnewton(f, x0; kwargs...) = find_zero(f, x0, Newton(); kwargs...)\nnewton(f, fp, x0; kwargs...) = find_zero((f, fp), x0, Newton(); kwargs...)\n\n\n## Halley\n\n\n\"\"\"\n    \n    Roots.Halley()\n\nImplements Halley's [method](http://tinyurl.com/yd83eytb),\n`x_n1 = xn - (2 f(xn)*f'(xn)) / (2 f'(xn)^2 - f(xn) * f''(xn))`.\nThis method is cubically converging, but requires more function calls per step than\nother methods.\n\"\"\"    \nstruct Halley <: UnivariateZeroMethod\nend\n\nfunction callable_function(method::Halley, f::Tuple)\n    length(f) == 1 && return SecondDerivative(f[1], D(f[1]), D(f[1],2))\n    length(f) == 2 && return SecondDerivative(f[1], f[2], D(f[2],1))\n    SecondDerivative(f[1], f[2], f[3])\nend\ncallable_function(method::Halley, f) = SecondDerivative(f, D(f), D(f, 2))\n\n\nfunction update_state(method::Halley, fs, o::UnivariateZeroState{T}, options::UnivariateZeroOptions) where {T}\n    xn = o.xn1\n    fxn = o.fxn1\n    fpxn = fs.fp(xn); incfn(o)\n    fppxn = fs.fpp(xn); incfn(o)\n    \n    xn1 = xn - 2fxn*fpxn / (2*fpxn*fpxn - fxn * fppxn)\n    fxn1 = fs.f(xn1); incfn(o)\n\n    o.xn0, o.xn1 = xn, xn1\n    o.fxn0, o.fxn1 = fxn, fxn1\n    incsteps(o)\nend\n\n\"\"\"\n\nImplementation of Halley's method. `xn1 = xn - 2f(xn)*f'(xn) / (2*f'(xn)^2 - f(xn) * f''(xn))`\n\nArguments:\n\n* `f::Function` -- function to find zero of\n\n* `fp::Function=D(f)` -- derivative of `f`. Defaults to automatic derivative\n\n* `fpp:Function=D(f,2)` -- second derivative of `f`.\n\n* `x0::Real` -- initial guess\n\nKeyword arguments:\n\n* `ftol`. Stop iterating when |f(xn)| <= max(1, |xn|) * ftol.\n\n* `xtol`. Stop iterating when |xn+1 - xn| <= xtol + max(1, |xn|) * xtolrel\n\n* `xtolrel`. Stop iterating when |xn+1 - xn| <= xtol + max(1, |xn|) * xtolrel\n\n* `maxeval`. Stop iterating if more than this many steps, throw error.\n\n* `verbose::Bool=false` Set to `true` to see trace.\n\n\"\"\"\nhalley(f,  x0; kwargs...) = find_zero(f, x0, Halley(); kwargs...)\nhalley(f, fp, x0; kwargs...) = find_zero((f, fp), x0, Halley(); kwargs...)\nhalley(f, fp, fpp, x0; kwargs...) = find_zero((f, fp, fpp), x0, Halley(); kwargs...)\n", "meta": {"hexsha": "999a03ac7fc3481dcf45fefe1584dc4d92319df9", "size": 5388, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/newton.jl", "max_stars_repo_name": "chriselrod/Roots.jl", "max_stars_repo_head_hexsha": "c05870746fe8655c91065bf842a9b6cd45435de2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/newton.jl", "max_issues_repo_name": "chriselrod/Roots.jl", "max_issues_repo_head_hexsha": "c05870746fe8655c91065bf842a9b6cd45435de2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/newton.jl", "max_forks_repo_name": "chriselrod/Roots.jl", "max_forks_repo_head_hexsha": "c05870746fe8655c91065bf842a9b6cd45435de2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2696629213, "max_line_length": 110, "alphanum_fraction": 0.6104305865, "num_tokens": 1639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7842510144902259}}
{"text": "export GaussianFilter, GaborWavelet, MorletWavelet\n\nabstract type AbstractFilter end\n\n\"\"\"\n    gabor1d(ω, ξ, σ)\n\nCalculate the Fourier transform of a gabor wavelet.\n\n# Arguments\n - `ω::Vector{Float64}`: Frequencies over which to calculate the filter.\n - `σ::Float64`: Bandwidth of the filter\n - `ξ::Float64`: Central frequency\n\"\"\"\nfunction gabor1d(ω::Vector{Float64}, σ::Float64, ξ::Float64)\n    return exp.(-(ω.-ξ).^2 ./ (2*σ^2))\nend\n\"\"\"\n    gabor1d(N, ξ, σ)\n\nConvenience method for calculating the Fourier transform of a gabor wavelet.\n\n# Arguments\n - `ω::Vector{Float64}`: Frequencies over which to calculate the filter.\n - `σ::Float64`: Bandwidth of the filter\n - `ξ::Float64`: Central frequency\n\"\"\"\nfunction gabor1d(N::Int64, σ::Float64, ξ::Float64)\n    ω = FFTW.fftfreq(N)\n    return gabor1d(ω[:], σ, ξ)\nend\n\n\"\"\"\n    gauss1d(ω, σ)\n\nReturn a Fourier transformed Gaussian lowpass filter.\n\n# Arguments\n - `ω::Vector{Float64}`: Frequencies over which to calculate the filter.\n - `σ::Float64`: Bandwidth of lowpass filter.\n\"\"\"\nfunction gauss1d(ω::Vector{Float64}, σ::Float64)\n    return exp.(-(ω.^2)./(2*σ^2))\nend\n\"\"\"\n    gauss1d(N, σ)\n\nConvenience method for calculate the Fourier transform of a Gaussian lowpass filter.\n\n# Argument\n - `N::Int64`: Length of filter in the time domain.\n - `σ::Float64`: Bandwidth of the lowpass filter.\n\"\"\"\nfunction gauss1d(N::Int64, σ::Float64)\n    ω = collect(0.0:N-1)./N\n    return gauss1d(ω[:], σ)\nend\n\n\"\"\"\n    morlet1d(gab, lowpass)\n\nCalculate the Fourier transform of a Morlet wavelet.\n\n# Arguments\n - `gab::Vector{Float64}`: Fourier transformed Gabor wavelet\n - `lowpass::Vector{Float64}`: Fourier transformed Gaussian lowpass filter\n\"\"\"\nfunction morlet1d(gab::Vector{Float64}, lowpass::Vector{Float64})\n    # summation factor to ensure first value is 0\n    κ = gab[1]/lowpass[1]\n    return gab .- κ.*lowpass\nend\n\"\"\"\n    morlet1d(N, ξ, σ)\n\nCalculate the Fourier transform of a Morlet wavelet.\n\n# Arguments\n - `N::Int64`: Length of filter in the time domain.\n - `σ::Float64`: Bandwidth of the lowpass filter.\n - `ξ::Float64`: Central frequency.\n\"\"\"\nfunction morlet1d(N::Int64, σ::Float64, ξ::Float64)\n    gab = gabor1d(N, σ, ξ)\n    lowpass = gauss1d(N, σ)\n    return morlet1d(gab, lowpass)\nend\n\n\"\"\"\n    GaussianFilter\n\nA structure for Fourier transformed Gaussian lowpass Filters\n\n## Fields: GaussianFilter\n | **Field** | **Description** |\n |:----------|:----------------|\n | :σ        | Filter Bandwidth |\n | :ϕ        | Fourier-transformed Gaussian lowpass filter |\n\"\"\"\nstruct GaussianFilter <: AbstractFilter\n    σ::Float64 # filter bandwidth\n\n    ϕ::Vector{Float64} # Fourier-transformed lowpass Gaussian filter\n\n    function GaussianFilter(N::Int64, σ::Float64)\n        ϕ = gauss1d(N, σ)\n        return new(σ, ϕ)\n    end\nend\n\n\"\"\"\n    GaborWavelet\n\nA structure for Fourier transformed Gabor Wavelets\n\n## Fields: GaborWavelet\n | **Field** | **Description** |\n |:----------|:----------------|\n | :σ        | Filter Bandwidth |\n | :ξ        | Central Frequency |\n | :j        | Maximal subsampling |\n | :γ        | Fourier-transformed Gabor wavelet |\n\"\"\"\nstruct GaborWavelet <: AbstractFilter\n    σ::Float64 # filter bandwidth\n    ξ::Float64 # central frequency\n    j::Int64 # 2^j is the maximal subsampling possible without aliasing\n\n    γ::Vector{Float64} # Fourier-transformed Gabor wavelet\n\n    function GaborWavelet(N::Int64, σ::Float64, ξ::Float64, j::Int64)\n        γ = gabor1d(N, σ, ξ)\n        return new(σ, ξ, j, γ)\n    end\nend\n\n\"\"\"\n    MorletWavelet\n\nA structure for Fourier transformed Morlet Wavelets\n\n## Fields: MorletWavelet\n | **Field** | **Description** |\n |:----------|:----------------|\n | :σ        | Filter Bandwidth |\n | :ξ        | Central Frequency |\n | :j        | Maximal subsampling |\n | :ψ        | Fourier-transformed Morlet wavelet |\n\"\"\"\nstruct MorletWavelet <: AbstractFilter\n    σ::Float64 # filter bandwidth\n    ξ::Float64 # central frequency\n    j::Int64 # 2^j is the maximal subsampling possible without aliasing\n\n    ψ::Vector{Float64} # Fourier-transformed Morlet wavelet\n\n    function MorletWavelet(N::Int64, σ::Float64, ξ::Float64, j::Int64)\n        ψ = morlet1d(N, σ, ξ)\n        return new(σ, ξ, j, ψ)\n    end\n    function MorletWavelet(γ::GaborWavelet, ϕ::GaussianFilter)\n        ψ = morlet1d(γ.γ, ϕ.ϕ)\n        return new(γ.σ, γ.ξ, γ.j, ψ)\n    end\nend\n", "meta": {"hexsha": "7cca3f1a5572f909a96aec3dc152fc5c322a68c6", "size": 4332, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/filters/filter.jl", "max_stars_repo_name": "jaredbryan881/Scat.jl", "max_stars_repo_head_hexsha": "743f51629bec62767c64c51ae932e1a8f4926d0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/filters/filter.jl", "max_issues_repo_name": "jaredbryan881/Scat.jl", "max_issues_repo_head_hexsha": "743f51629bec62767c64c51ae932e1a8f4926d0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/filters/filter.jl", "max_forks_repo_name": "jaredbryan881/Scat.jl", "max_forks_repo_head_hexsha": "743f51629bec62767c64c51ae932e1a8f4926d0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0963855422, "max_line_length": 84, "alphanum_fraction": 0.6493536473, "num_tokens": 1316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7842510125926122}}
{"text": "# This file investigates mean square error (MSE) with respect to free variables in 1D interpolation \n\nusing FractalTools \nusing Makie \n\n# Construct interpolation data \nf = FractalTools.wen            # For irregular data \n# f = FractalTools.sinusoid     # For regular data \nline = [[0.], [1.]]\npts = getdata(f, line, 11) \n\n# Construct test data \ntpts = getdata(line, 101)\nnpts = length(tpts) \n\n# Compute errors \nfvals = map(pnt -> f(pnt[1]), tpts)\nfreevars = 0.001 : 0.01 : 0.999\nmse = map(freevars) do freevar \n    interp = interpolate(pts, Interp1D(freevar))\n    ivals = map(pnt -> interp(pnt[1]), tpts)\n    sum((fvals - ivals).^2) / npts \nend \n\n# Plot mse \nfig = Figure() \nax = fig[1, 1] = Axis(fig, xlabel=\"Free Variable\", ylabel=\"MSE\", title=\"1D Interpolation MSE\") \nstem!(ax, freevars, mse, color=:black)\nsave(joinpath(@__DIR__, \"interp1d_mse.png\"), fig)\ndisplay(fig)\n\n", "meta": {"hexsha": "da09f2857d9de2d979d52ffcb3b1e013d2b44248", "size": 875, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiment_2/interpolation_mse_vs_freevars/interp1d/interp1d.jl", "max_stars_repo_name": "zekeriyasari/FractalTools.jl", "max_stars_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-08T12:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T12:50:16.000Z", "max_issues_repo_path": "experiment_2/interpolation_mse_vs_freevars/interp1d/interp1d.jl", "max_issues_repo_name": "zekeriyasari/FractalTools.jl", "max_issues_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-09-05T18:22:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T10:09:46.000Z", "max_forks_repo_path": "experiment_2/interpolation_mse_vs_freevars/interp1d/interp1d.jl", "max_forks_repo_name": "zekeriyasari/FractalTools.jl", "max_forks_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.34375, "max_line_length": 100, "alphanum_fraction": 0.6662857143, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8376199552262966, "lm_q1q2_score": 0.7842510060829004}}
{"text": "# SolarIrradiance.jl\n# Copyright (c) 2021 Pierre Galloo-Beauvais, Pierre Haessig\n# This code is subject to the terms of the MIT license (see LICENSE.txt)\n\nmodule SolarIrradiance\n\nexport dayofyear, declination, EoT, hour_angle, day_bounds\nexport cosθavg, cosθZavg, Rb, global_radiation_tilt\n\ninclude(\"GHIProcess.jl\")\nexport GHIProcess\n\nusing Dates\n\n\n\"\"\"\n    declination(n)\n\nCompute the solar declination angle δ of the day `n`, in radians.\n\nδ is the angle between the Sun-Earth direction and the equatorial plane.\nIt varies between −23.45° on December 21-22 and +23.45° on June 22\nand is zero at the equinoxes.\nSee https://www.pveducation.org/pvcdrom/properties-of-sunlight/declination-angle.\n\n# Examples\n\nDeclination at the summer solstice in the northern hemisphere:\n```jldoctest\njulia> using Dates\n\njulia> n = dayofyear(2021,06,22)\n173\n\njulia> δ = declination(n)\n0.40924559967108437\n\njulia> round(rad2deg(δ); digits=3)\n23.448\n```\n\nDeclination at March equinoxe:\n```jldoctest\njulia> n = dayofyear(2021,03,22)\n81\n\njulia> round(declination(n); digits=3)\n-0.0\n```\n\n\"\"\"\ndeclination(n) = deg2rad(23.45) * sin(2π*(284+n)/365)\n\n\n\"\"\"\n    EoT(n)\n\nEquation of Time on day `n`, in hours.\n\nThe Equation of Time is the difference between the apparent (or true) solar time\nand the mean solar time.\nSee https://www.pveducation.org/pvcdrom/properties-of-sunlight/solar-time\n\n# Examples\n\nMinimal value is about -14 minutes in mid February:\n```jldoctest\njulia> EoT(45)*60\n-14.26116933144462\n```\n\nMaximal value is about +16 minutes in mid November:\n```jldoctest\njulia> EoT(306)*60\n16.388668719846564\n```\n\"\"\"\nfunction EoT(n)\n    B= 2π*(n-1)/365\n    return 3.82*(0.000075+0.001868*cos(B)-0.032077*sin(B)-0.014615*cos(2*B)-0.04089*sin(2*B))\nend\n\n\n\"\"\"\n    hour_angle(n, tc, lon)\n\nCompute the hour angle of the Sun ω (in rad) a civil hour `tc` on day `n`, at longitude `lon` (°). \n\nSee also the inverse function `time_hour_angle`.\n\nL'angle horaire du Soleil donne un renseignement sur le temps solaire vrai, il vaut 0 quand le Soleil est à son point culminant de la journée, est négatif avant ce point et positif après ce point.\n\nTODO: add missing time zone input\n\"\"\"\nhour_angle(n, tc, lon) = (tc + lon/15 + EoT(n) - 12)*deg2rad(15)\n\n\"\"\"\n    time_hour_angle(n, ω, lon)\n\nCompute the civil hour `tc` of an hour angle of the Sun `ω` (in rad) on day `n`,\nat longitude `lon` (°). \n\nIt is the inverse function of `tc -> hour_angle(n, tc, lon)`.\n\nTODO: add missing time zone input\n\"\"\"\ntime_hour_angle(n, ω, lon) = ω/deg2rad(15) - EoT(n) + 12 - lon/15\n\n\"\"\"\n    day_bounds(n, slope, azimuth, lat)\n\nCompute the hour angle bounds when the sun is above a panel during day `n`.\n\nPanel has a `slope` (in [0, 90°]) and `azimuth` (in [-90°, 90°])\nand is located at latitude `lat` (°).\n\nReturn `ωu`, `ωd` (in rad) which are respectively the hour angles of \nsunrise and sunset *over the panel*.\nWhen `slope` is 0, this corresponds to regulat sunrise and sunset (over the ground).\nand there is a dedicated method for this, see `day_bounds(n, lat)`.\n\nMathematically, with θ the angle of incidence of the Sun on the panel,\nthis means that cosθ=0 at hour angle `ωu` and `ωd` and cosθ ≥ 0 in between.\n\"\"\"\nfunction day_bounds(n, slope, azimuth, lat)\n    beta=deg2rad(slope)\n    gamma=deg2rad(azimuth)\n    phi=deg2rad(lat)\n    delta=declination(n)\n\n    sinδ=sin(delta)\n    cosδ=cos(delta)\n    sinϕ=sin(phi) \n    cosϕ=cos(phi)\n    cosβ=cos(beta)\n    sinβ=sin(beta)\n    cosγ=cos(gamma)\n    \n    A = sinδ*sinϕ*cosβ - sinδ*cosϕ*sinβ*cosγ\n    B = cosδ*cosϕ*cosβ + cosδ*sinϕ*sinβ*cosγ\n    C = cosδ*sinβ*sin(gamma)\n\n    D = C^2+B^2-A^2\n    E = A-B\n    if D >= 0\n        ωu = 2*atan((-C+sqrt(D))/E)\n        ωd = 2*atan((-C-sqrt(D))/E)\n    else\n        # quick fix to  avoid sqrt(negative number) error,\n        # but there may be a more physical way to detect this situation\n        ωu = 0.0\n        ωd = 0.0\n    end\n    \n    return ωu, ωd\nend\n\n\"\"\"\n    day_bounds(n, lat)\n\nCompute the hour angle bounds when the sun is above the horizon during day `n`\nat latitude `lat` (°).\n\nReturn `ωu`, `ωd` (in rad) which are respectively the hour angles of sunrise and sunset.\n\nMathematically, with θz the solar zenith angle (angle of incidence of the Sun on the ground),\nthis means that cosθz=0 at hour angle `ωu` and `ωd` and cosθz ≥ 0 in between.\n\"\"\"\nfunction day_bounds(n, lat)\n    phi=deg2rad(lat)\n    \n    # Sunset\n    ωd = acos(-tan(phi)*tan(declination(n)))\n    # Sunrise\n    ωu = -ωd\n    \n    return ωu, ωd\nend\n\n\n\"\"\"\n    cosθavg(n, tcini, dt, slope, azimuth, lat, lon)\n\nCosine of θ, the angle of incidence of the sun on a tilted panel.\n\nPanel has orientation (`slope`, `azimuth` °) and is located at (`lon`, `lat` °).\nValue is computed on day `n`, averaged on a time interval `dt`\nstarting at civil hour `tcini`.\n\nSee also: [`cosθZavg`](@ref) for the incidence on the _ground_.\n\"\"\"\nfunction cosθavg(n, tcini, dt, slope, azimuth, lat, lon)\n    beta=deg2rad(slope)\n    gamma=deg2rad(azimuth)\n    phi=deg2rad(lat)\n    \n    ω1=hour_angle(n, tcini, lon)\n    ω2=hour_angle(n, tcini+dt, lon)\n    \n    ωup, ωdown = day_bounds(n, slope, azimuth, lat)\n    \n    if ω1<ωup && ω2<ωup\n        return 0.0\n    elseif ω1>ωdown && ω2>ωdown\n        return 0.0\n    elseif ω1<ωup && ω2>ωup\n        ω1 = ωup\n        tdebut = time_hour_angle(n, ωup, lon)\n        tfin = tcini+dt\n        dt = tfin-tdebut # TODO: check that the change of `dt` is correct\n    elseif ω1<ωdown && ω2>ωdown\n        ω2 = ωdown\n        tdebut = tcini\n        tfin = time_hour_angle(n, ωdown, lon)\n        dt = tfin-tdebut # TODO: check that the change of `dt` is correct\n    end\n    \n    delta = declination(n)\n\n    sinδ = sin(delta)\n    cosδ = cos(delta)\n    sinϕ = sin(phi)\n    cosϕ = cos(phi)\n    cosβ = cos(beta)\n    sinβ = sin(beta)\n    cosγ = cos(gamma)\n    \n    a = sinδ*sinϕ*cosβ - sinδ*cosϕ*sinβ*cosγ\n    b = cosδ*cosϕ*cosβ + cosδ*sinϕ*sinβ*cosγ\n    c = cosδ*sinβ*sin(gamma)\n    f = ω2 - ω1\n    g = sin(ω2) - sin(ω1)\n    h = cos(ω2) - cos(ω1)\n    x = (a*f + b*g - c*h)*12/(pi*dt)\n    \n    return x\nend\n\n\"\"\"\n    cosθZavg(n, tcini, dt, lat, lon)\n\nCosine of ``θ_Z``, the solar zenith angle, i.e. the angle of incidence of the sun on the ground.\n\nLocation is (`lon`, `lat` °).\nValue is computed on day `n`, averaged on a time interval `dt`\nstarting at civil hour `tcini`.\n\nSee also: [`cosθavg`](@ref) for the incidence on a _tilted panel_.\n\"\"\"\nfunction cosθZavg(n, tcini, dt, lat, lon)\n    phi=deg2rad(lat)\n    \n    ω1=hour_angle(n, tcini, lon)\n    ω2=hour_angle(n, tcini+dt, lon)\n    \n    ωup, ωdown = day_bounds(n, lat)\n    \n    if ω1<ωup && ω2<ωup\n        return 0.0\n    elseif ω1>ωdown && ω2>ωdown\n        return 0.0\n    elseif ω1<ωup && ω2>ωup\n        ω1 = ωup\n        tdebut = time_hour_angle(n, ωup, lon)\n        tfin = tcini+dt\n        dt = tfin-tdebut # TODO: check that the change of `dt` is correct\n    elseif ω1<ωdown && ω2>ωdown\n        ω2 = ωdown\n        tdebut = tcini\n        tfin = time_hour_angle(n, ωdown, lon)\n        dt = tfin-tdebut # TODO: check that the change of `dt` is correct\n    end\n    \n    delta = declination(n)\n    \n    d = cos(phi)*cos(delta)\n    e = sin(phi)*sin(delta)\n    f = ω2 - ω1\n    g = sin(ω2) - sin(ω1)\n    x = (d*g + e*f)*12/(pi*dt)\n    \n    return x\nend\n\n\"\"\"\n    Rb(cosθ, cosθZ, Rbsat=5)\n\nRb = cosθ/cosθZ with special care of zeros and saturation at `Rbsat`\n\"\"\"\nfunction Rb(cosθ, cosθZ, Rbsat=5.)\n    if cosθ==0. || cosθZ==0.\n        return 0.0\n    else\n        x = cosθ/cosθZ\n    end\n    \n    if x>Rbsat\n        return Rbsat\n    else\n        return x\n    end\nend\n\n\"\"\"\n    Rb(n, tcini, dt, slope, azimuth, lat, lon, Rbsat=5)\n\nCette fonction calcule le terme de redressement de GHI direct pour un panneau PV incliné d'un angle `slope`, orienté d'un angle `azimuth`, situé à une latitude `lat` et une longitude `lon` (°). Elle le calcule pour un jour n donné, sur un intervalle donné de durée dt à partir d'un instant initial tcini.\n\n⚠️ Fonction avec encore quelques problèmes. Des pics apparaissent dans certaines conditions, une saturation a été mise en place afin que ces pics n'impactent pas les calculs utilisant cette fonction. Cette saturation, choisie empiriquement, empêche le terme de redressement de dépasser la valeur de 5.\n\"\"\"\nfunction Rb(n, tcini, dt, slope, azimuth, lat, lon, Rbsat=5.)\n    cosθ = cosθavg(n, tcini, dt, slope, azimuth, lat, lon)\n    cosθZ = cosθZavg(n, tcini, dt, lat, lon)\n    \n    return Rb(cosθ, cosθZ, Rbsat)\nend\n\n\"\"\"\n    global_radiation_tilt(GHI::Real, n, tcini, dt, lat, lon, slope, azimuth, albedo;\n                          diffuse_model=:EKD82, transpose_model=:HDKR)\n\nEstimate the global irradiance on a tilted panel from horizontal data `GHI`.\n\nPanel has a orientation (`slope`, `azimuth`) and is located at (`lon`, `lat`).\n`GHI` data is for day `n`, averaged on a time interval `dt`,\nstarting at civil hour `tcini` (UTC).\n\nReflection from surrounding area is modeled by `albedo` in [0,1].\n\n# Empirical models\n\nMany steps of the irradiance transposition from a horizontal plane to a tilted plane\nare deduced from geometry. However, two aspects of the estimation are _empirical_,\nso that several models are available:\n1. splitting the global horizontal irradiance between direct and diffuse components\n2. transposing the diffuse irradiance on a tilted plane\n\n## 1. Diffuse fraction estimation\n\n`diffuse_model` sets the model used to estimate the _fraction of diffuse radiation_\nfrom the clearness index:\n- `:EKD82`: Erbs, Klein & Duffie (1982). Estimation of the diffuse radiation fraction for\n  hourly, daily and monthly-average global radiation. Solar Energy 28 (4), 293–302.\n- `:OH77`: Orgill & Hollands (1977). Correlation equation for hourly diffuse radiation\n  on a horizontal surface. Sol. Energy 19, 357–359.\n- `:CR79`: Collares-Pereira & Rabl (1979), The average distribution of solar radiation\n  —correlations between diffuse and hemispherical and between daily and hourly insolation values.\n  Solar Energy 22, 155.\n\n## 2. Diffuse irradiance transposition\n\n`transpose_model` sets the model to estimate the diffuse radiation on a tilted plane.\nModels differ on their assumption on how the diffuse irradiance is spatially distributed\non the sky hemisphere.\nSee (Demain 2013) for an introduction to those models and Duffie & Beckman's book for HDKR.\nModels are classified between isotropic and anisotropic.\n\nIsotropic models:\n- `:LJ62`: Liu & Jordan (1962). Daily insolation on surfaces tilted towards the equator. ASHRAE, 53:526-41.\n- `:Ko86`: Korokanis (1986). On the choice of the angle of tilt for south facing solar collectors in the Athens basin area. Solar Energy, 36:217-25.\n- `:Ba02`: Badescu (2002). 3D isotropic approximation for solar diffuse irradiance on tilted\nsurfaces. Renewable Energy, 26:221-3.\n\nAnisotropic models:\n- `:Wi82`: Willmot (1982). On the climatic optimization of the tilt and azimuth of\n  flat-plate solar collectors. Solar Energy, 28:205-16.\n- `:Bu77`: Bugler (1977). The determination of hourly insolation on an inclined plane\n  using a diffuse irradiance model based on hourly measured global horizontal insolation.\n  Solar Energy, 19:477-91.\n- `:MI83`: Ma & Iqbal (1983) Statistical comparison of models for estimating solar radiation\n  on inclined surfaces. Solar Energy 31 (3), 313-317.\n- `:Ha79`:  Hay (1979). Study of shortwave radiation on non-horizontal surfaces.\n  Canadian Climate Centre, Report No. 79-12, Downsview, Ontario.\n- `:TC77`:  Temps & Coulson (1977). Solar radiation incident upon slopes of different orientation.\n  Solar Energy, 19:179-84.\n- `:Kl79`: Klucher (1979). Evaluation of models to predict insolation on tilted surfaces.\n  Solar Energy, 23:111-114.\n- `:HDKR`: HDKR model (as named in Duffie & Beckman's book) used by HOMER, proposed by\n  Reindl, Beckman & Duffie (1990). Evaluation of Hourly Tilted Surface Radiation Models.\n  Solar Energy, 45, 9-17.\n\"\"\"\nfunction global_radiation_tilt(GHI::Real, n, tcini, dt, lat, lon, slope, azimuth, albedo;\n                               diffuse_model=:EKD82, transpose_model=:HDKR)\n    delta = declination(n)\n    phi = deg2rad(lat)\n    beta = deg2rad(slope)\n    gamma = deg2rad(azimuth)\n    \n    # Extraterrestrial normal irradiance\n    Gon = 1367*(1+0.033*cos(deg2rad((360*n)/365)))\n    \n    # Averaged horizontal extraterrestrial irradiance\n    ω1 = hour_angle(n, tcini, lon)\n    ω2 = hour_angle(n, tcini+dt, lon)\n    \n    # TODO: use the cosθZavg function here instead:\n    # Goavg = Gon*cosθZavg, I believe\n    a = cos(phi)*cos(delta) * (sin(ω2) - sin(ω1))\n    b = sin(phi)*sin(delta) * (ω2 - ω1)\n    Goavg = Gon*(a+b)*12/(pi*dt)\n    if Goavg < 0\n        Goavg = 0.0\n    end\n    \n    # Clearness index `kt`\n    if Goavg > 0\n        kt = GHI/Goavg\n            if kt > 1\n                kt = 1.0\n            end\n    else\n        kt = 0.0\n    end\n    \n    # Diffuse irradiance, estimated from `kt` and GHI using various models\n    if diffuse_model == :EKD82 # Erbs et al. 1982\n        if kt<=0.22\n            GHIdiffus = (1-0.09*kt)*GHI\n        elseif kt>0.8\n            GHIdiffus = 0.165*GHI\n        else\n            GHIdiffus = (0.9511-0.1604*kt+4.388*kt^2-16.638*kt^3+12.336*kt^4)*GHI\n        end\n        \n    elseif diffuse_model == :OH77 # Orgill & Hollands 1977\n        if kt<=0.35\n            GHIdiffus = (1-0.249*kt)*GHI\n        elseif kt>0.75\n            GHIdiffus = 0.177*GHI\n        else\n            GHIdiffus = (1.557-1.84*kt)*GHI\n        end\n        \n    elseif diffuse_model == :CR79 # Colarres-Pereira & Rabl 1979\n        if kt<=0.17\n            GHIdiffus = 0.99*GHI\n        elseif kt>=0.80\n            GHIdiffus = 0.2*GHI\n        elseif kt>0.17 && kt<0.75\n            GHIdiffus = (1.188-2.272*kt+9.473*kt^2-21.865*kt^3+14.648*kt^4)*GHI\n        else # [0.75, .80[ (not in original publication)\n            GHIdiffus = (0.632-0.54*kt)*GHI\n        end\n    else\n        error(\"unknown diffuse fraction estimation model $diffuse_model\")\n    end \n    \n    # Beam (direct) irradiance:\n    GHIdirect=GHI-GHIdiffus\n    \n    # Direct (beam) radiation on tilted surface\n    # averaged cos(θ) and cos(θz)\n    cosθ = cosθavg(n, tcini, dt, slope, azimuth, lat, lon)\n    cosθZ = cosθZavg(n, tcini, dt, lat, lon)\n    RB=Rb(cosθ, cosθZ)\n    Gdirect=RB*GHIdirect\n    \n    # Diffuse radiation on tilted surface\n    if transpose_model == :LJ62 # Liu & Jordan (1962)\n        Gdiffus=(1+cos(beta))*GHIdiffus/2\n        \n    elseif transpose_model == :Ko86 # Korokanis (1986)\n        Gdiffus=(2+cos(beta))*GHIdiffus/3\n        \n    elseif transpose_model == :Ba02 # Badescu (2002)\n        Gdiffus=(3+cos(2*beta))*GHIdiffus/4\n        \n    elseif transpose_model == :Wi82 # Willmot (1982)\n        if cosθ <= 0\n            AW = 0.0\n            BW = 1.0115-0.20293*beta-0.080823*beta^2\n        else\n            AW = Gdirect*RB/(1367*cosθ)\n            BW = (1.0115-0.20293*beta-0.080823*beta^2)*(1-(Gdirect/(1367*cosθ)))\n        end\n        Gdiffus = (AW+BW) * GHIdiffus\n        \n    elseif transpose_model == :Bu77 # Bugler (1977)\n        AB = (1+cos(beta))/2\n        if GHIdiffus <= 0\n            BB = 0.0\n        else\n            BB = 0.05*(Gdirect/GHIdiffus)\n        end\n        if cosθZ <= 0\n            CB = cosθ\n        else\n            CB = cosθ - (1+cos(beta))/(2*cosθZ)\n        end  \n        Gdiffus = (AB + BB*CB) * GHIdiffus \n        \n    elseif transpose_model == :MI83 # Ma & Iqbal (1983)\n        AM = (1-kt)*(1+cos(beta))/2\n        BM = kt*RB\n        Gdiffus = (AM+BM)*GHIdiffus\n        \n    elseif transpose_model == :Ha79 # Hay (1979)\n        if Goavg <= 0\n            AH = 1.0\n            CH = 0.0\n        else\n            AH = 1 - (GHIdirect/Goavg)\n            CH = RB * (GHIdirect/Goavg)\n        end\n        BH = (1+cos(beta))/2\n        Gdiffus = (AH*BH+CH) * GHIdiffus\n        \n    elseif transpose_model == :TC77 # Temps & Coulson (1977)\n        ATC = (1+cos(beta))/2\n        BTC = 1+(cosθ^2)*(sqrt(1-cosθZ^2))^3\n        CTC = 1+(sin(beta/2))^3\n        Gdiffus = ATC*BTC*CTC*GHIdiffus\n        \n    elseif transpose_model == :Kl79 # Klucher (1979)\n        AK = (1+cos(beta))/2\n        if GHI <= 0\n            FK = 1.0\n        else\n            FK = 1 - (GHIdiffus/GHI)^2\n        end\n        BK = 1 + FK*(cosθ^2)*(sqrt(1-cosθZ^2))^3\n        CK = 1 + FK*(sin(beta/2))^3\n        Gdiffus = AK*BK*CK * GHIdiffus\n        \n    elseif transpose_model == :HDKR # HDKR model from Reindl, Beckman & Duffie (1990)\n        if Goavg > 0\n            Ai = GHIdirect/Goavg\n        else\n            Ai = 0.0\n        end\n        if GHI > 0\n            f = sqrt(GHIdirect/GHI)\n        else\n            f = 0.0\n        end\n        AHDKR = Ai*RB\n        BHDKR = 1 - Ai\n        CHDKR = (1+cos(beta))/2\n        DHDKR = 1 + f*(sin(beta/2))^3\n        Gdiffus = (AHDKR + BHDKR*CHDKR*DHDKR) * GHIdiffus\n    \n    else\n        error(\"unknown diffuse irradiance transposition model $transpose_model\")\n    end\n    \n    # Reflected irradiance\n    Greflechi = GHI * albedo * (1-cos(beta))/2\n    \n    # Total irradiance\n    Gtot = Gdiffus + Gdirect + Greflechi\n    \n    # Saturate output\n    if Gtot>2000. \n        # TODO: transform fixed threshold into parameter\n        Gtot = 2000.\n    elseif Gtot<0\n        Gtot = 0.\n    end\n    \n    return Gtot\nend\n\n\"\"\"\n    global_radiation_tilt(n, tcini, dt, lat, lon, fonctionGHI, diffuse_model, transpose_model, GHI_data, slope, azimuth, albedo)\n\nSame as first `global_radiation_tilt(GHI::Real...)`, but \n\n`GHI_data` is the Vector of hourly GHI of a given year, obtained from function `GHIannee`.\n\nElle prend également en argument une chaîne de caractères `fonctionGHI`, qui permet de choisir l'interpolation des données du GHI. Cette chaîne de caractère peut donc être : \"forwardfill\", \"backwardfill\", \"centeredfill\" et \"interpolation\".\n\"\"\"\nfunction global_radiation_tilt(GHI_data::Vector, fonctionGHI, n, tcini, dt, lat, lon, slope, azimuth, albedo;\n                               diffuse_model=:EKD82, transpose_model=:HDKR)\n    GHI = GHIProcess.GHIavg(GHI_data, n, tcini, dt, fonctionGHI)\n    Gtot = global_radiation_tilt(GHI, n, tcini, dt, lat, lon, slope, azimuth, albedo;\n                                 diffuse_model=:EKD82, transpose_model=:HDKR)\n    return Gtot\nend\n\nend # module\n", "meta": {"hexsha": "b043dd6e4881784d053dbaae978d1e7120657513", "size": 18102, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SolarIrradiance.jl", "max_stars_repo_name": "pierre-haessig/SolarIrradiance.jl", "max_stars_repo_head_hexsha": "c1a122645f5ec646431f9b541239b56058a7723a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SolarIrradiance.jl", "max_issues_repo_name": "pierre-haessig/SolarIrradiance.jl", "max_issues_repo_head_hexsha": "c1a122645f5ec646431f9b541239b56058a7723a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SolarIrradiance.jl", "max_forks_repo_name": "pierre-haessig/SolarIrradiance.jl", "max_forks_repo_head_hexsha": "c1a122645f5ec646431f9b541239b56058a7723a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.156626506, "max_line_length": 304, "alphanum_fraction": 0.634073583, "num_tokens": 5905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422158380861, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7841805517327387}}
{"text": "# Perform a univariate OLS regression (with non-zero intercept) to estimate the\n# per-evaluation execution time of an expression.\n#\n# Arguments:\n#\n#     x::Vector{Float64}: The number of times the expression was evaluated.\n#\n#     y::Vector{Float64}: The total execution time of the expression's\n#         (potentially repeated) evaluation.\n#\n# Returns:\n#\n#     a::Float64: The intercept of the univariate OLS model.\n#\n#     b::Float64: The slope of the univariate OLS model.\n#\n#     r²::Float64: The r-squared of the univariate OLS regresion\n\nfunction ols(x::Vector{Float64}, y::Vector{Float64})\n    a, b = linreg(x, y)\n    r² = 1 - var(a + b * x - y) / var(y)\n    return a, b, r²\nend\n\nfunction sem_ols(x::Vector{Float64}, y::Vector{Float64})\n    a, b = linreg(x, y)\n    n = length(x)\n    residuals = y - (a + b * x)\n    sem_b = sqrt(((1 / (n - 2)) * sum(residuals.^2)) / sum((x - mean(x)).^2))\n    return sem_b\nend\n", "meta": {"hexsha": "fb9ba2fa3e93b28ed5f77cd595dc33f39a889d4e", "size": 917, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ols.jl", "max_stars_repo_name": "johnmyleswhite/Benchmarks.jl", "max_stars_repo_head_hexsha": "0cb8340ce5af3e175c86154cd6202843a4960adf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2015-06-16T06:53:20.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-31T01:37:44.000Z", "max_issues_repo_path": "src/ols.jl", "max_issues_repo_name": "johnmyleswhite/Benchmarks.jl", "max_issues_repo_head_hexsha": "0cb8340ce5af3e175c86154cd6202843a4960adf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 43, "max_issues_repo_issues_event_min_datetime": "2015-06-16T18:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-14T13:12:16.000Z", "max_forks_repo_path": "src/ols.jl", "max_forks_repo_name": "johnmyleswhite/Benchmarks.jl", "max_forks_repo_head_hexsha": "0cb8340ce5af3e175c86154cd6202843a4960adf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2015-06-21T02:47:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:22:23.000Z", "avg_line_length": 28.65625, "max_line_length": 79, "alphanum_fraction": 0.6357688113, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7841805460440547}}
{"text": "##########################################################\n# Rafał Nowak\n#\n# Instytut Informatyki\n# Uniwersytet Wrocławski\n#\n#\n# Pomocniczne materiały do wykładu z analizy numerycznej\n#\n##########################################################\ntwo = Float32(2.0);\n\nd = 32-1;\nt = 23;\n\n#\n# Obliczanie największej liczby dodatniej w arytmetyce Float32\n#\ncmax = 2^(d-t-1)-1; # największa cecha\n\nx1 = two^cmax * ( two - two^(-t) )\n@printf(\"najw. dod. liczba w arytm. Float32 = %.1f =\\n\", x1);\n\n# alternatywny sposób\nx2 = prevfloat(typemax(Float32));\n@printf(\"najw. dod. liczba w arytm. Float32 = %.1f\\n\", x2);\n\nassert( x1==x2 )\n\n#\n# Obliczanie najmniejszej liczby dodatniej (subnormalnej) w arytmetyce Float32\n#\n # największa cecha\ncmin = -2^(d-t-1)+2; # niestety jedna liczba -128 i -127 są już zarezerwowane na (±Inf+NaN i Subnorm)\nx1 = two^cmin * two^(-t)\n@printf(\"najm. dod. liczba subnormalna w arytm. Float32 = %.16e\\n\", x1);\n# alternatywny sposób\nx2 = nextfloat(float32(0.0));\n@printf(\"najm. dod. liczba subnormalna w arytm. Float32 = %.16e\\n\", x2);\nassert( x1==x2 )\n", "meta": {"hexsha": "d9682397697dd91aa7139f1c9133eb8e8bccc5d9", "size": 1070, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Analiza_Numeryczna_M/Przyklady/w1-maxfloat.jl", "max_stars_repo_name": "Magikis/Uniwersity", "max_stars_repo_head_hexsha": "06964ef31d721af85740df1dce3f966006ab9f78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-11-30T08:45:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-26T14:15:45.000Z", "max_issues_repo_path": "Analiza_Numeryczna_M/Przyklady/w1-maxfloat.jl", "max_issues_repo_name": "Magikis/Uniwersity", "max_issues_repo_head_hexsha": "06964ef31d721af85740df1dce3f966006ab9f78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Analiza_Numeryczna_M/Przyklady/w1-maxfloat.jl", "max_forks_repo_name": "Magikis/Uniwersity", "max_forks_repo_head_hexsha": "06964ef31d721af85740df1dce3f966006ab9f78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2017-10-16T09:42:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-27T19:48:45.000Z", "avg_line_length": 26.0975609756, "max_line_length": 101, "alphanum_fraction": 0.6056074766, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7841800685309079}}
{"text": "δ(i, j) = Int64(==(i, j))\n\ndiagm(x::Vector) = [δ(i, j)*x[i] for i in 1:length(x), j in 1:length(x)]\n\nI(n) = [δ(i, j) for i = 1:n, j = 1:n]\n\nvtanh(x::Vector) = tanh.(x)\n\ndtanh(x::Vector) = I(length(x)) - diagm([i^2 for i in x])\n\nrelu(z::Vector) = max.(0, z)\n\nleasSquareCost(o, t) = sum((o - t).^2)/2\ndLeastSquareCost(o, t) = o-t\n\nsoftmaxLikelihood(o, t) = -log(o[argmax(t)])\ndSoftmaxLikelihood(o, t) = o - t\n\nfunction drelu(z::Vector)\n  dvec = Int64.(>(0).(z))\n  return diagm(dvec[:, 1])\nend\n\nfunction softmax(z::Vector)\n  shift = maximum(z)\n\n  z = exp.(z .- shift)\n  total = sum(z)\n  return z ./ total\nend\n\nfunction dsoftmax(z::Vector)\n  n = length(z)\n\n  w = softmax(z)\n  e = ones(n, 1)\n\n  return w * e' .* (I(n) - e * w')\nend\n\nmean(x) = sum(x)/length(x)\n\nactivations = Dict(:vtanh => (vtanh, dtanh), :relu => (relu, drelu), :softmax => (softmax, dsoftmax))", "meta": {"hexsha": "e4043f49f052c3587e2b00846d422ae548988b4f", "size": 857, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "achjaj/shape-recognition", "max_stars_repo_head_hexsha": "ff83b69f65df3a74d28d5eada027420cac4e364f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions.jl", "max_issues_repo_name": "achjaj/shape-recognition", "max_issues_repo_head_hexsha": "ff83b69f65df3a74d28d5eada027420cac4e364f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions.jl", "max_forks_repo_name": "achjaj/shape-recognition", "max_forks_repo_head_hexsha": "ff83b69f65df3a74d28d5eada027420cac4e364f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9302325581, "max_line_length": 101, "alphanum_fraction": 0.5717619603, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542864252023, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7841800633129729}}
{"text": "@doc raw\"\"\"\n    g = first_order_system(K, τ)\n\nconstruct a first-order transfer function with gain `K` and time constant `τ`:\n\n$$g(s)=\\frac{K}{\\tau s+1}$$\n\n# example\n```jldoctest\nK = 1.0\nτ = 3.0\ng = first_order_system(K, τ)\n# output\n    1.0\n-----------\n3.0*s + 1.0\n```\n\n# returns\n* `g::TransferFunction`: the first order transfer function. well, (0, 1) order.\n\"\"\"\nfirst_order_system(K::Float64, τ::Float64) = K / (τ * s + 1)\n\n@doc raw\"\"\"\n    g = second_order_system(K, τ, ξ)\n\nconstruct a second-order transfer function with gain `K`, time constant `τ`, and damping coefficient `ξ`:\n\n$$g(s)=\\frac{K}{\\tau^2 s^2 + 2\\tau \\xi s +1}$$\n\n# example\n```jldoctest\nK = 1.0\nτ = 2.0\nξ = 0.1\ng = second_order_system(K, τ, ξ)\n# output\n         1.0\n---------------------\n4.0*s^2 + 0.4*s + 1.0\n```\n\n# returns\n* `g::TransferFunction`: the second order transfer function. well, (0, 2) order.\n\"\"\"\nsecond_order_system(K::Float64, τ::Float64, ξ::Float64) = K / (τ^2 * s^2 + 2 * τ * ξ * s + 1)\n\n@doc raw\"\"\"\n    τ = time_constant(g)\n\ncompute the time constant τ of an order (0, 1) or order (0, 2) transfer function.\n\norder (0, 1) representation:\n\n$$g(s)=\\frac{K}{\\tau s+1}$$\n\norder (0, 2) representation:\n\n$$g(s)=\\frac{K}{\\tau^2 s^2 + 2\\tau \\xi s +1}$$\n\n# returns\n`τ::Float64`: the time constant.\n\n# examples\n\n```jldoctest\ng = 4 / (6 * s + 2)\ntime_constant(g)\n# output \n3.0\n\ng = 1.0 / (8 * s^2 + 0.8 * s + 2)\ntime_constant(g) \n# output\n2.0\n```\n\"\"\"\nfunction time_constant(g::TransferFunction)\n    if system_order(g) == (0, 1)\n        # xx / (a s + b) ==> τ = a / b\n        return g.denominator[1] / g.denominator[0]\n    elseif system_order(g) == (0, 2)\n        # xx / (a s^2 + b s + c) ==> τ = sqrt(a/c)\n        return sqrt(g.denominator[2] / g.denominator[0])\n    else\n        error(\"`time_constant` only supports order (0, 1) and (0, 2) transfer functions.\")\n    end\nend\n\n@doc raw\"\"\"\n    ξ = damping_coefficient(g)\n\ncompute the damping coefficient ξ of an order (0, 2) transfer function.\n\norder (0, 2) representation:\n\n$$g(s)=\\frac{K}{\\tau^2 s^2 + 2\\tau \\xi s +1}$$\n\n# returns\n`ξ::Float64`: the damping coefficient\n\n# examples\n```jldoctest\ng = 1.0 / (8 * s^2 + 0.8 * s + 2)\ndamping_coefficient(g)\n# output\n0.1\n```\n\"\"\"\nfunction damping_coefficient(g::TransferFunction)\n    if system_order(g) != (0, 2)\n        error(\"`damping_coefficient` only pertains to (0, 2) transfer functions.\")\n    end\n    τ = time_constant(g)\n    # xx / (a s² + b s + c) then 2τξ = b / c\n    τξ2 = g.denominator[1] / g.denominator[0]\n    return τξ2 / (2 * τ)\nend\n", "meta": {"hexsha": "f677aea5c03364dde88f94f4a669ab3084b8caf9", "size": 2513, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/special_tfs.jl", "max_stars_repo_name": "SimonEnsemble/Controlz", "max_stars_repo_head_hexsha": "d09ce3500a954fcb0a7a96001cda1142139fccc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/special_tfs.jl", "max_issues_repo_name": "SimonEnsemble/Controlz", "max_issues_repo_head_hexsha": "d09ce3500a954fcb0a7a96001cda1142139fccc5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/special_tfs.jl", "max_forks_repo_name": "SimonEnsemble/Controlz", "max_forks_repo_head_hexsha": "d09ce3500a954fcb0a7a96001cda1142139fccc5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1176470588, "max_line_length": 105, "alphanum_fraction": 0.5893354556, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757596, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7841290363201988}}
{"text": "\"\"\"\n    statsrank(x::Matrix{T}, ranktol::Real=1e-8) where {T<:AbstractFloat}\n\nReturn the numerical column rank and a pivot vector.\n\nThe rank is determined from the absolute values of the diagonal of R from\na pivoted QR decomposition, relative to the first (and, hence, largest)\nelement of this vector.\n\nIn the full-rank case the pivot vector is `collect(axes(x, 2))`.\n\"\"\"\nfunction statsrank(x::AbstractMatrix{T}; ranktol=1e-8) where {T<:AbstractFloat}\n    m, n = size(x)\n    piv = collect(axes(x, 2))\n\n    iszero(n) && return (rank=n, piv=piv)\n\n    qrpiv = pivoted_qr(x)\n    dvec = abs.(diag(qrpiv.R))\n    fdv = first(dvec)\n    cmp = fdv * ranktol\n    (last(dvec) > cmp) && return (rank=n, piv=piv)\n\n    rank = searchsortedlast(dvec, cmp; rev=true)\n    @assert rank < n\n    piv = qrpiv.p\n    v1 = first(eachcol(x))\n    if all(isone, v1) && first(piv) ≠ 1\n        # make sure the first column isn't moved by inflating v1\n        v1 .*= (fdv + one(fdv)) / sqrt(m)\n        qrpiv = pivoted_qr(x)\n        piv = qrpiv.p\n        fill!(v1, one(T))    # restore the contents of the first column\n    end\n\n    # maintain original column order for the linearly independent columns\n    sort!(view(piv, 1:rank))\n    return (rank=rank, piv=piv)\nend\n", "meta": {"hexsha": "bf1f70e164ccb8c80cb85fea5275b4ffb9bb63f6", "size": 1234, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linalg/pivot.jl", "max_stars_repo_name": "joscani/MixedModels.jl", "max_stars_repo_head_hexsha": "fd79f396a729bf22f237008430a92e7f4aaf0431", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 158, "max_stars_repo_stars_event_min_datetime": "2019-11-21T21:46:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T04:54:32.000Z", "max_issues_repo_path": "src/linalg/pivot.jl", "max_issues_repo_name": "joscani/MixedModels.jl", "max_issues_repo_head_hexsha": "fd79f396a729bf22f237008430a92e7f4aaf0431", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 365, "max_issues_repo_issues_event_min_datetime": "2019-11-22T05:40:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:14:53.000Z", "max_forks_repo_path": "src/linalg/pivot.jl", "max_forks_repo_name": "joscani/MixedModels.jl", "max_forks_repo_head_hexsha": "fd79f396a729bf22f237008430a92e7f4aaf0431", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2015-04-22T12:57:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-16T16:40:13.000Z", "avg_line_length": 30.85, "max_line_length": 79, "alphanum_fraction": 0.6393841167, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7841290347185554}}
{"text": "#src # DGSEM with flux differencing\n\n# This tutorial starts with a presentation of the weak formulation of the discontinuous Galerkin\n# spectral element method (DGSEM) in order to fix the notation of the used operators.\n# Then, the DGSEM formulation with flux differencing (split form DGSEM) and its implementation in\n# [Trixi.jl](https://github.com/trixi-framework/Trixi.jl) is shown.\n\n# We start with the one-dimensional conservation law\n# ```math\n# u_t + f(u)_x = 0, \\qquad t\\in \\mathbb{R}^+, x\\in\\Omega\n# ```\n# with the physical flux $f$.\n\n# We split the domain $\\Omega$ into elements $K$ with center $x_K$ and size $\\Delta x$. With the\n# transformation mapping $x(\\xi)=x_K + \\frac{\\Delta x}{2} \\xi$ we can transform the reference element\n# $[-1,1]$ to every physical element. So, the equation can be restricted to the reference element using the\n# determinant of the Jacobian matrix of the transformation mapping\n# $J=\\frac{\\partial x}{\\partial \\xi}=\\frac{\\Delta x}{2}$.\n# ```math\n# J u_t + f(u)_{\\xi} = 0, \\qquad t\\in \\mathbb{R}^+, \\xi\\in [-1,1]\n# ```\n\n\n# ## The weak form of the DGSEM\n# We consider the so-called discontinuous Galerkin spectral element method (DGSEM) with collocation.\n# It results from choosing a nodal DG ansatz using $N+1$ Gauss-Lobatto nodes $\\xi_i$ in $[-1,1]$\n# with matching interpolation weights $w_i$, which are used for numerical integration and interpolation with\n# the Lagrange polynomial basis $l_i$ of degree $N$. The Lagrange functions are created with those nodes and\n# hence fulfil a Kronecker property at the GL nodes.\n# The weak formulation of the DGSEM for one element is\n# ```math\n# J \\underline{\\dot{u}}(t) = - M^{-1} B \\underline{f}^* + M^{-1} D^T M \\underline{f}\n# ```\n# where $\\underline{u}=(u_0, u_1, \\dots, u_N)^T\\in\\mathbb{R}^{N+1}$ is the collected pointwise evaluation\n# of $u$ at the discretization nodes and $\\dot{u} = \\partial u / \\partial t = u_t$ is the temporal derivative.\n# The nodal values of the flux function $f$ results with collocation in $\\underline{f}$, since\n# $\\underline{f}_j=f(\\underline{u}_j)$. Moreover, we got the numerical flux $f^*=f^*(u^-, u^+)$.\n\n# We will now have a short overview over the operators we used.\n\n# The **derivative matrix** $D\\in\\mathbb{R}^{(N+1)\\times (N+1)}$ mimics a spatial derivation on a\n# discrete level with $\\underline{f}_x \\approx D \\underline{f}$. It is defined by $D_{ij} = l_j'(\\xi_i)$.\n\n# The diagonal **mass matrix** $M$ is defined by $M_{ij}=\\langle l_j, l_i\\rangle_N$ with the\n# numerical scalar product $\\langle \\cdot, \\cdot\\rangle_N$ defined for functions $f$ and $g$ by\n# ```math\n# \\langle f, g\\rangle_N := \\int_{-1, N}^1 f(\\xi) g(\\xi) d\\xi := \\sum_{k=0}^N f(\\xi_k) g(\\xi_k) w_k.\n# ```\n# The multiplication by $M$ matches a discrete integration\n# ```math\n#   \\int_{-1}^1 f(\\xi) \\underline{l}(\\xi) d\\xi \\approx M \\underline{f},\n# ```\n\n# The **boundary matrix** $B=\\text{diag}([-1, 0,..., 0, 1])$ represents an evaluation of a\n# function at the boundaries $\\xi_0=-1$ and $\\xi_N=1$.\n\n# For these operators the following property holds:\n# ```math\n#   M D + (M D)^T = B.\n# ```\n# This is called the summation-by-parts (SBP) property since it mimics integration by parts on a\n# discrete level ([Gassner (2013)](https://doi.org/10.1137/120890144)).\n\n# The explicit definitions of the operators and the contruction of the 1D algorithm can be found\n# for instance in the tutorial [introduction to DG methods](@ref scalar_linear_advection_1d)\n# or in more detail in [Kopriva (2009)](https://link.springer.com/book/10.1007/978-90-481-2261-5).\n\n# This property shows the equivalence between the weak form and the following strong formulation\n# of the DGSEM.\n# ```math\n# \\begin{align*}\n# J \\underline{\\dot{u}}(t)\n# &= - M^{-1} B \\underline{f}^* + M^{-1} D^T M \\underline{f}\\\\[5pt]\n# &= - M^{-1} B \\underline{f}^* + M^{-1} (B - MD) \\underline{f}\\\\[5pt]\n# &= - M^{-1} B (\\underline{f}^* - \\underline{f}) - D \\underline{f}\n# \\end{align*}\n# ```\n# More information about the equivalence you can find in [Kopriva, Gassner (2010)](https://doi.org/10.1007/s10915-010-9372-3).\n\n\n# ## DGSEM with flux differencing\n# When using the diagonal SBP property it is possible to rewrite the application of the derivative\n# operator $D$ in the calculation of the volume integral into a subcell based finite volume type\n# differencing formulation ([Fisher, Carpenter (2013)](https://doi.org/10.1016/j.jcp.2013.06.014)).\n# We replace $D \\underline{f}$ in the strong form by $2D \\underline{f}_{vol}(u^-, u^+)$ with\n# the consistent two-point volume flux $f_{vol}$ and receive the DGSEM formulation with flux differencing\n# (split form DGSEM) ([Gassner, Winters, Kopriva (2016)](https://doi.org/10.1016/j.jcp.2016.09.013)).\n\n# ```math\n# \\begin{align*}\n# J \\underline{\\dot{u}}(t) &= - M^{-1} B (\\underline{f}^* - \\underline{f}) - 2D \\underline{f}_{vol}(u^-, u^+)\\\\[5pt]\n# &= - M^{-1} B (\\underline{f}^* - \\underline{f}_{vol}(\\underline{u}, \\underline{u})) - 2D \\underline{f}_{vol}(u^-, u^+)\\\\[5pt]\n# &= - M^{-1} B \\underline{f}_{sur}^* - (2D - M^{-1} B) \\underline{f}_{vol}\\\\[5pt]\n# &= - M^{-1} B \\underline{f}_{sur}^* - D_{split} \\underline{f}_{vol}\n# \\end{align*}\n# ```\n# This formulation is in a weak form type formulation and can be implemented by using the derivative\n# split matrix $D_{split}=(2D-M^{-1}B)$ and two different fluxes. We divide between the surface\n# flux $f=f_{sur}$ used for the numerical flux $f_{sur}^*$ and the already mentioned volume\n# flux $f_{vol}$ especially for this formulation.\n\n\n# This formulation creates a more stable version of DGSEM, because it fulfils entropy stability.\n# Moreover it allows the construction of entropy conserving discretizations without relying on\n# exact integration. This is achieved when using a two-point entropy conserving flux function as\n# volume flux in the volume flux differencing formulation.\n# Then, the numerical surface flux can be used to control the dissipation of the discretization and to\n# guarantee decreasing entropy, i.e. entropy stability.\n\n\n\n# ## Implementation in Trixi\n# Now, we have a look at the implementation of DGSEM with flux differencing with [Trixi.jl](https://github.com/trixi-framework/Trixi.jl).\nusing OrdinaryDiffEq, Trixi\n\n# We implement a simulation for the compressible Euler equations in 2D\n# ```math\n# \\partial_t \\begin{pmatrix} \\rho \\\\ \\rho v_1 \\\\ \\rho v_2 \\\\ \\rho e \\end{pmatrix}\n# + \\partial_x \\begin{pmatrix} \\rho v_1 \\\\ \\rho v_1^2 + p \\\\ \\rho v_1 v_2 \\\\ (\\rho e +p) v_1 \\end{pmatrix}\n# + \\partial_y \\begin{pmatrix} \\rho v_2 \\\\ \\rho v_1 v_2 \\\\ \\rho v_2^2 + p \\\\ (\\rho e +p) v_2 \\end{pmatrix}\n# = \\begin{pmatrix} 0 \\\\ 0 \\\\ 0 \\\\ 0 \\end{pmatrix}\n# ```\n# for an ideal gas with ratio of specific heats $\\gamma=1.4$.\n# Here, $\\rho$ is the density, $v_1$, $v_2$ the velocities, $e$ the specific total energy and\n# ```math\n# p = (\\gamma - 1) \\left( \\rho e - \\frac{1}{2} \\rho (v_1^2+v_2^2) \\right)\n# ```\n# the pressure.\n\ngamma = 1.4\nequations = CompressibleEulerEquations2D(gamma)\n\n# As our initial condition we will use a weak blast wave from [Hennemann, Gassner (2020)](https://arxiv.org/abs/2008.12044).\n# The primitive variables are defined by\n# ```math\n# \\begin{pmatrix} \\rho \\\\ v_1 \\\\ v_2 \\\\ p \\end{pmatrix}\n# = \\begin{pmatrix} 1.0 \\\\ 0.0 \\\\ 0.0 \\\\ 1.0 \\end{pmatrix} \\text{if } \\|x\\|_2 > 0.5,\\;\n# \\text{and } \\begin{pmatrix} \\rho \\\\ v_1 \\\\ v_2 \\\\ p \\end{pmatrix}\n# = \\begin{pmatrix} 1.1691 \\\\ 0.1882 * \\cos(\\phi) \\\\ 0.1882 * \\sin(\\phi) \\\\ 1.245 \\end{pmatrix} \\text{else}\n# ```\n# with $\\phi = \\tan^{-1}(\\frac{x_2}{x_1})$.\n\n# This initial condition is implemented in Trixi under the name [`initial_condition_weak_blast_wave`](@ref).\ninitial_condition = initial_condition_weak_blast_wave\n\n# In Trixi, flux differencing for the volume integral can be implemented with\n# [`VolumeIntegralFluxDifferencing`](@ref) using symmetric two-point volume fluxes.\n# First, we set up a simulation with the entropy conserving and kinetic energy preserving\n# flux [`flux_ranocha`](@ref) by [Hendrik Ranocha (2018)](https://cuvillier.de/en/shop/publications/7743)\n# as surface and volume flux.\n\n# We will confirm the entropy conservation property numerically.\n\nvolume_flux = flux_ranocha # = f_vol\nsolver = DGSEM(polydeg=3, surface_flux=volume_flux,\n               volume_integral=VolumeIntegralFluxDifferencing(volume_flux))\n\n# Now, we implement Trixi's `mesh`, `semi` and `ode` in a simple framework. For more information please\n# have a look at the documentation, the basic tutorial [introduction to DG methods](@ref scalar_linear_advection_1d)\n# or some basic elixirs.\ncoordinates_min = (-2.0, -2.0)\ncoordinates_max = ( 2.0,  2.0)\nmesh = TreeMesh(coordinates_min, coordinates_max,\n                initial_refinement_level=5,\n                n_cells_max=10_000,\n                periodicity=true)\n\nsemi = SemidiscretizationHyperbolic(mesh, equations, initial_condition, solver,\n                                    boundary_conditions=boundary_condition_periodic)\n\n## ODE solvers\ntspan = (0.0, 0.4)\node = semidiscretize(semi, tspan);\n\n# To analyse the entropy conservation of the approximation, we will use the analysis calllback\n# implemented in Trixi. It provides some information about the approximation including the entropy change.\nanalysis_callback = AnalysisCallback(semi, interval=100);\n\n# We now run the simulation using `flux_ranocha` for both surface and volume flux.\nsol = solve(ode, RDPK3SpFSAL49(), abstol=1.0e-6, reltol=1.0e-6,\n            callback=analysis_callback, save_everystep=false);\n# A look at the change in entropy $\\sum \\partial S/\\partial U \\cdot U_t$ in the analysis callback\n# confirms that the flux is entropy conserving since the change is about machine precision.\n\n# We can plot the approximated solution at the time `t=0.4`.\nusing Plots\nplot(sol)\n\n# Now, we can use for instance the dissipative flux [`flux_lax_friedrichs`](@ref) as surface flux\n# to get an entropy stable method.\nusing OrdinaryDiffEq, Trixi\n\ngamma = 1.4\nequations = CompressibleEulerEquations2D(gamma)\n\ninitial_condition = initial_condition_weak_blast_wave\n\nvolume_flux = flux_ranocha # = f_vol\nsolver = DGSEM(polydeg=3, surface_flux=flux_lax_friedrichs,\n               volume_integral=VolumeIntegralFluxDifferencing(volume_flux))\n\ncoordinates_min = (-2.0, -2.0)\ncoordinates_max = ( 2.0,  2.0)\nmesh = TreeMesh(coordinates_min, coordinates_max,\n                initial_refinement_level=5,\n                n_cells_max=10_000,\n                periodicity=true)\n\nsemi = SemidiscretizationHyperbolic(mesh, equations, initial_condition, solver,\n                                    boundary_conditions=boundary_condition_periodic)\n\n## ODE solvers\ntspan = (0.0, 0.4)\node = semidiscretize(semi, tspan);\n\nanalysis_callback = AnalysisCallback(semi, interval=100);\n\n# We now run the simulation using the volume flux `flux_ranocha` and surface flux `flux_lax_friedrichs`.\nsol = solve(ode, RDPK3SpFSAL49(), abstol=1.0e-6, reltol=1.0e-6,\n            callback=analysis_callback, save_everystep=false);\n# The change in entropy confirms the expected entropy stability.\n\nusing Plots\nplot(sol)\n\n\n# Of course, you can use more than these two fluxes in Trixi. Here, we will give a short list\n# of possible fluxes for the compressible Euler equations.\n# For the volume flux Trixi provides for example [`flux_ranocha`](@ref), [`flux_shima_etal`](@ref),\n# [`flux_chandrashekar`](@ref), [`flux_kennedy_gruber`](@ref).\n# As surface flux you can use all volume fluxes and additionally for instance [`flux_lax_friedrichs`](@ref),\n# [`flux_hll`](@ref), [`flux_hllc`](@ref).\n", "meta": {"hexsha": "634cd8f37179c6b01afd41d317ec00dda830415d", "size": 11505, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/literate/src/files/DGSEM_FluxDiff.jl", "max_stars_repo_name": "panalluri/Trixi.jl", "max_stars_repo_head_hexsha": "faab9964204923c1a21b55ebf788c8a37aa01e90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/literate/src/files/DGSEM_FluxDiff.jl", "max_issues_repo_name": "panalluri/Trixi.jl", "max_issues_repo_head_hexsha": "faab9964204923c1a21b55ebf788c8a37aa01e90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/literate/src/files/DGSEM_FluxDiff.jl", "max_forks_repo_name": "panalluri/Trixi.jl", "max_forks_repo_head_hexsha": "faab9964204923c1a21b55ebf788c8a37aa01e90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.3776824034, "max_line_length": 137, "alphanum_fraction": 0.7001303781, "num_tokens": 3496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7841290310222001}}
{"text": "using PyPlot,LinearAlgebra,Random\n\"\"\"\n```\ngen_ellipse(F1:Vector{Float64},F2=Vector{Float64},\n\ta::Float64,p::Int,npun::Int,ntot::Int,\n\ttmin::Float64,tmax::Float64)\n```\n\nGenerate perturbed points in a ellipse given focus F1 and F2 major axis a. It is mandatory to define the number of points `ntot` the of exacts points `p` and the number of point to compose the ellipse `npun`. \n\n`ntot-npun` is the number of random points\n`npun-p` is the number of points of the ellipse which are normally-distributed.\n`tmin` and `tmax` are parameter to define limits for the figure. \n\n## Example\n\n```julia-repl\njulia> gen_ellipse([1.0,2.0],[3.0,5.0],5.0,0,100,1000,-10,10)\n```\n\n\"\"\"\nfunction gen_ellipse(F1,F2,a,p,npun,ntot,tmin,tmax)\n\tc = norm(F2-F1,2)\n\tif a<=c \n\t\terror(\"a<=c, it isn't an elipse\")\n\tend\n\tb = sqrt(a^2-c^2)\n\t# let us assume β is the rotation angle from (1,0)\n\tcosβ = (F2-F1)[1]/norm(F2-F1,2)\n\tsinβ = sqrt(1.0-cosβ)\n\t\n\tcenter = 0.5*(F1+F2)\n\trng = MersenneTwister(1234)\n\tx = zeros(ntot)\n\ty = zeros(ntot)\n\tθ = shuffle(rng,[0:(2*π)/npun:2*π;])\n\t\n\tfor i=1:p\n\t\tx[i] = center[1]*cosβ+b*cos(θ[i])*cosβ+center[2]*sinβ+a*sin(θ[i])*sinβ\n\t\ty[i] = -center[1]*sinβ -b*cos(θ[i])*sinβ+center[2]*cosβ+a*sin(θ[i])*cosβ\n\tend\n\tfor i=p+1:npun\n\t\tanoise = a+0.1*randn()\n\t\tbnoise = b+0.1*randn()\n\t\tx[i] = center[1]*cosβ+bnoise*cos(θ[i])*cosβ+center[2]*sinβ+anoise*sin(θ[i])*sinβ\n\t\ty[i] = -center[1]*sinβ -bnoise*cos(θ[i])*sinβ+center[2]*cosβ+anoise*sin(θ[i])*cosβ\n\tend\n\n\tx[npun+1:end]= tmin.+(tmax-tmin)*rand(ntot-npun)\n\ty[npun+1:end]= tmin.+(tmax-tmin)*rand(ntot-npun)\n\tplot(x,y,\".\")\n\n\treturn [x y]\nend\n\n", "meta": {"hexsha": "791277f0652f527a7cd222c12760a2ea884d83ea", "size": 1581, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/scripts/gen_ellipse.jl", "max_stars_repo_name": "JuliaTagBot/RAFF.jl", "max_stars_repo_head_hexsha": "901b0fcf0a70dfc18a66160921de6548b712ca3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-03-13T01:33:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T16:23:09.000Z", "max_issues_repo_path": "test/scripts/gen_ellipse.jl", "max_issues_repo_name": "JuliaTagBot/RAFF.jl", "max_issues_repo_head_hexsha": "901b0fcf0a70dfc18a66160921de6548b712ca3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2019-03-12T18:56:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-29T13:58:48.000Z", "max_forks_repo_path": "test/scripts/gen_ellipse.jl", "max_forks_repo_name": "JuliaTagBot/RAFF.jl", "max_forks_repo_head_hexsha": "901b0fcf0a70dfc18a66160921de6548b712ca3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-04-17T08:26:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:17:44.000Z", "avg_line_length": 28.2321428571, "max_line_length": 209, "alphanum_fraction": 0.6571790006, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.8418256452674009, "lm_q1q2_score": 0.784129030775666}}
{"text": "using OrdinaryDiffEq, DiffEqMonteCarlo, Distributions, Test\n\ninclude(\"koopman.jl\")\n\nfunction f(du,u,p,t)\n  du[1] = dx = p[1]*u[1] - u[1]*u[2]\n  du[2] = dy = -3*u[2] + u[1]*u[2]\nend\n\nu0 = [1.0;1.0]\ntspan = (0.0,10.0)\np = [1.5]\nprob = ODEProblem(f,u0,tspan,p)\nsol = solve(remake(prob,u0=u0),Tsit5())\ncost(sol) = sum(max(x[1]-12,0) for x in sol.u)\nu0s = [Uniform(0.25,5.5),Uniform(0.25,5.5)]\nps  = [Uniform(0.5,2.0)]\n@time c1, _ = koopman_cost(u0s, ps, cost, prob, Tsit5();saveat=0.1, use_vegas = true)\n@time c2 = montecarlo_cost(u0s, ps, cost, prob, Tsit5(); num_monte = 100000, saveat = 0.1)\n@show c1, c2\n\n#=function f2(du,u,p,t)\n  du[1] = dx = p[1]*u[1] - p[2]*u[1]*u[2]\n  du[2] = dy = -p[3]*u[2] + p[4]*u[1]*u[2]\nend\n\nu0 = [1.0;1.0]\ntspan = (0.0,10.0)\np = [1.5,1.0,3.0,1.0]\nprob = ODEProblem(f2,u0,tspan,p)\ncost(sol) = sum(max(x[1]-6,0) for x in sol.u)\nu0s = [Uniform(0.25,5.5),Uniform(0.25,5.5)]\nps  = [Uniform(0.5,2.0), Uniform(0.5, 1.5), Uniform(2.5, 3.5), Uniform(0.5, 1.5)]\n@time c1, _ = koopman_cost(u0s, ps, cost, prob, Tsit5();saveat=0.1, use_vegas = true)\n@time c2 = montecarlo_cost(u0s, ps, cost, prob, Tsit5(); num_monte = 100000, saveat = 0.1)\n@show c1, c2\n=#\n", "meta": {"hexsha": "7b9f0281ca8ea89e07561f56afbc3fa77fd410b0", "size": 1173, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/koopmantest.jl", "max_stars_repo_name": "ranjanan/MonteCarloIntegration.jl", "max_stars_repo_head_hexsha": "2a9a1e34609f494fb0f265ca06260d2161650c41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-06-14T17:31:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T07:49:26.000Z", "max_issues_repo_path": "test/koopmantest.jl", "max_issues_repo_name": "ranjanan/MonteCarloIntegration.jl", "max_issues_repo_head_hexsha": "2a9a1e34609f494fb0f265ca06260d2161650c41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-10T12:32:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-16T17:38:51.000Z", "max_forks_repo_path": "test/koopmantest.jl", "max_forks_repo_name": "ranjanan/MonteCarloIntegration.jl", "max_forks_repo_head_hexsha": "2a9a1e34609f494fb0f265ca06260d2161650c41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-06-14T20:07:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T17:57:00.000Z", "avg_line_length": 30.8684210526, "max_line_length": 90, "alphanum_fraction": 0.5967604433, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731765, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7841290291740226}}
{"text": "\"\"\"\nmutable struct InverseDistanceSurrogate{X,Y,P,L,U} <: AbstractSurrogate\n\nThe square polynomial model can be expressed by 𝐲 = 𝐗β + ϵ, with β = 𝐗ᵗ𝐗⁻¹𝐗ᵗ𝐲\n\"\"\"\nmutable struct SecondOrderPolynomialSurrogate{X,Y,B,L,U} <: AbstractSurrogate\n    x::X\n    y::Y\n    β::B\n    lb::L\n    ub::U\nend\n\nfunction SecondOrderPolynomialSurrogate(x,y,lb::Number,ub::Number)\n    n = length(x)\n    d = 1\n    X = ones(eltype(x[1]),n,3*d)\n    X[:,2] = x\n    X[:,3] = x.^2\n    β = X\\y\n    return SecondOrderPolynomialSurrogate(x,y,β,lb,ub)\nend\n\nfunction (sec_ord::SecondOrderPolynomialSurrogate)(val::Number)\n    return sec_ord.β[1] + sec_ord.β[2]*val + sec_ord.β[3]*val^2\nend\n\nfunction SecondOrderPolynomialSurrogate(x,y,lb,ub)\n    n = length(x)\n    d = length(lb)\n    X = ones(eltype(x[1]),n,3*d)\n    for j = 1:d\n        X[:,j+1] =[x[i][j] for i=1:n]\n    end\n    for j = 1:d-1\n        X[:,j+d+1] = [x[i][j]*x[i][j+1] for i = 1:n]\n    end\n    for j = 1:d\n        X[:,j+2*d] = [x[i][j]^2 for i=1:n]\n    end\n    β = X\\y\n    return SecondOrderPolynomialSurrogate(x,y,β,lb,ub)\nend\n\nfunction (my_second_ord::SecondOrderPolynomialSurrogate)(val)\n    #just create the val vector as X and multiply\n    d = length(val)\n    X = [[one(eltype(val[1]))]; [val[j] for j =1:d]; [val[j]*val[j+1] for j = 1:d-1]; [val[j]^2 for j = 1:d]]\n    return my_second_ord.β'*X\nend\n\nfunction add_point!(my_second::SecondOrderPolynomialSurrogate,x_new,y_new)\n    d = length(my_second.lb)\n    if d == 1\n        #1D\n        my_second.x = vcat(my_second.x,x_new)\n        my_second.y = vcat(my_second.y,y_new)\n        n = length(my_second.x)\n        X = ones(eltype(my_second.x[1]),n,3*d)\n        X[:,2] = my_second.x\n        X[:,3] = my_second.x.^2\n        my_second.β = X\\my_second.y\n    else\n        #ND\n        my_second.x = vcat(my_second.x,x_new)\n        my_second.y = vcat(my_second.y,y_new)\n        n = length(my_second.x)\n        X = ones(eltype(my_second.x[1]),n,3*d)\n        for j = 1:d\n            X[:,j+1] =[my_second.x[i][j] for i=1:n]\n        end\n        for j = 1:d-1\n            X[:,j+d+1] = [my_second.x[i][j]*my_second.x[i][j+1] for i = 1:n]\n        end\n        for j = 1:d\n            X[:,j+2*d] = [my_second.x[i][j]^2 for i=1:n]\n        end\n        my_second.β = X\\my_second.y\n    end\n    nothing\nend\n", "meta": {"hexsha": "5b8c009d75fd6bbfe984b99da75cf737ad8da4b6", "size": 2267, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SecondOrderPolynomialSurrogate.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Surrogates.jl-6fc51010-71bc-11e9-0e15-a3fcc6593c49", "max_stars_repo_head_hexsha": "9680039453db69ccc9bad8721287e340381912f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SecondOrderPolynomialSurrogate.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Surrogates.jl-6fc51010-71bc-11e9-0e15-a3fcc6593c49", "max_issues_repo_head_hexsha": "9680039453db69ccc9bad8721287e340381912f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SecondOrderPolynomialSurrogate.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Surrogates.jl-6fc51010-71bc-11e9-0e15-a3fcc6593c49", "max_forks_repo_head_hexsha": "9680039453db69ccc9bad8721287e340381912f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6463414634, "max_line_length": 109, "alphanum_fraction": 0.5668284076, "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7841290238760238}}
{"text": "\"\"\"\nsimple!(FV,x)\nThis is the function for Figure 2.1\nIt also shows up in CI\n\"\"\"\nfunction simple!(FV, x)\n    FV[1] = x[1] * x[1] + x[2] * x[2] - 2.0\n    FV[2] = exp(x[1] - 1) + x[2] * x[2] - 2.0\nend\n\nfunction jsimple!(JacV, FV, x)\n    JacV[1, 1] = 2.0 * x[1]\n    JacV[1, 2] = 2.0 * x[2]\n    JacV[2, 1] = exp(x[1] - 1)\n    JacV[2, 2] = 2 * x[2]\nend\n\n\"\"\"\nJVsimple(v, FV, x)\n\nJacobian-vector product for simple!. There is, of course, no reason \nto use Newton-Krylov for this problem other than CI or demonstrating \nhow to call nsoli.jl.\n\"\"\"\nfunction JVsimple(v, FV, x)\n    jvec = zeros(2)\n    jvec[1] = 2.0 * x' * v\n    jvec[2] = v[1] * exp(x[1] - 1.0) + 2.0 * v[2] * x[2]\n    return jvec\nend\n", "meta": {"hexsha": "4e791370d6c88c547ad619db068e7f527492a618", "size": 690, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TestProblems/Systems/simple!.jl", "max_stars_repo_name": "aliddell/SIAMFANLEquations.jl", "max_stars_repo_head_hexsha": "4a9bad23d726993764c5790d56b9d68cb27dffe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TestProblems/Systems/simple!.jl", "max_issues_repo_name": "aliddell/SIAMFANLEquations.jl", "max_issues_repo_head_hexsha": "4a9bad23d726993764c5790d56b9d68cb27dffe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TestProblems/Systems/simple!.jl", "max_forks_repo_name": "aliddell/SIAMFANLEquations.jl", "max_forks_repo_head_hexsha": "4a9bad23d726993764c5790d56b9d68cb27dffe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2580645161, "max_line_length": 69, "alphanum_fraction": 0.547826087, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7841290222743803}}
{"text": "export Spindle\n\n\"\"\"\n`Spindle()` returns the Moser spindle graph. This is a seven-vertex\nunit distance graph with chromatic number equal to 4.\n\"\"\"\nfunction Spindle()\n    G = IntGraph(7)\n    edges = [\n        (1, 2),\n        (1, 3),\n        (2, 3),\n        (2, 4),\n        (3, 4),\n        (1, 5),\n        (1, 6),\n        (5, 6),\n        (5, 7),\n        (6, 7),\n        (4, 7) ]\n    add_edges!(G,edges)\n\n    d = Dict{Int,Vector}()\n    a = sqrt(3)/2\n\n    pts = [ 0 1/2 -1/2 0 ; 0 a a 2a ]\n\n    theta = acos(5/6)/2\n    R = [ cos(theta) -sin(theta); sin(theta) cos(theta) ]\n\n    p1 = R*pts\n    for k=1:4\n        d[k] = p1[:,k]\n    end\n\n    p2 = R'*pts\n    for k=5:7\n        d[k] = p2[:,k-3]\n    end\n    embed(G,d)\n    SimpleGraphs.name(G,\"Moser Spindle\")\n    return G\nend\n", "meta": {"hexsha": "67f78df015dc8e6f18075fba151c896e86220839", "size": 766, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/embedding/embedded-graphs.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_stars_repo_head_hexsha": "a22fbfc7f37c5b4debf209a11f5b059a688d8676", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/embedding/embedded-graphs.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_issues_repo_head_hexsha": "a22fbfc7f37c5b4debf209a11f5b059a688d8676", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/embedding/embedded-graphs.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_forks_repo_head_hexsha": "a22fbfc7f37c5b4debf209a11f5b059a688d8676", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4090909091, "max_line_length": 67, "alphanum_fraction": 0.4477806789, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475794701961, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7840567804178086}}
{"text": "#=\n\nBy listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.\nWhat is the 10 001st prime number?\n\n=#\n\nis_prime(n) = !any(n%i == 0 for i in 2:BigInt(floor(sqrt(n))))\n\nfunction nth_prime(n)\n    counter = 1\n    i = 2\n    while true\n        if is_prime(i)\n            #println(counter, \", \", i)\n            if counter == n\n                #println()\n                return i\n            end\n            counter += 1\n        end\n        i += 1\n    end\nend\n\nnth_prime(6)\n\nnth_prime(10001)\n", "meta": {"hexsha": "10ac71afa5bfe44071353341e152c17dfdebec75", "size": 526, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "euler_7.jl", "max_stars_repo_name": "pedvide/project-euler", "max_stars_repo_head_hexsha": "8e8e1e57b2c4d7e70a7127483539dca060c50a38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "euler_7.jl", "max_issues_repo_name": "pedvide/project-euler", "max_issues_repo_head_hexsha": "8e8e1e57b2c4d7e70a7127483539dca060c50a38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "euler_7.jl", "max_forks_repo_name": "pedvide/project-euler", "max_forks_repo_head_hexsha": "8e8e1e57b2c4d7e70a7127483539dca060c50a38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.1379310345, "max_line_length": 100, "alphanum_fraction": 0.5095057034, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012717045181, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7840113810740758}}
{"text": "### A Pluto.jl notebook ###\n# v0.18.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 1eb34f10-b4b3-11ec-19f5-c7f26108d374\nbegin\n\tusing LinearAlgebra\n\tusing StatsPlots\nmd\"\"\"\n# HW 11\n\nEric Nguyen\n\"\"\"\nend\n\n# ╔═╡ 6c4b3bf7-26e9-4d6f-9305-65fbc851818f\nlet\nmd\"\"\"\n### Problem 1\n\nUse the properties of determinants to prove that ``\\underline{\\underline{A}} \\,\\underline{\\underline{B}} = \\underline{\\underline{0}}`` implies that either ``|\\underline{\\underline{A}}| = 0`` or ``|\\underline{\\underline{B}}| = 0``, or both, where ``\\underline{\\underline{0}}`` is the matrix of all zeros.\nDemonstrate this with the matrices\n\n$\\underline{\\underline{A}} = \\begin{bmatrix} 1 & 1 \\\\ 2 & 2 \\end{bmatrix} \\qquad\\text{and}\\qquad \\underline{\\underline{B}} = \\begin{bmatrix} a & b \\\\ -a & -b \\end{bmatrix}$\n\nwhere ``a`` and ``b`` can be any complex numbers.\nWhich matrix has zero determinant?\n\"\"\"\nlet\n\tA = [1 1; 2 2]\n\ta = rand(Complex{Float64})\n\tb = rand(Complex{Float64})\n\n\tB = [a b; -a -b]\n\tdet(A), det(B), eigvals(A), eigvals(B)\nend\nmd\"\"\"\n### Problem 1\n\nGiven that ``|\\underline{\\underline{A}} \\,\\underline{\\underline{B}}| = 0`` and using the sixth property of determinants as listed in the course notes, ``|\\underline{\\underline{A}} \\,\\underline{\\underline{B}}| = |\\underline{\\underline{A}}| |\\underline{\\underline{B}}|``, we get\n\n$|\\underline{\\underline{A}} \\,\\underline{\\underline{B}}| = |\\underline{\\underline{A}}| |\\underline{\\underline{B}}| = 0$\n\nwhich implies that at least ``|\\underline{\\underline{A}}| = 0`` or ``|\\underline{\\underline{B}}| = 0``.\nThe determinant ``|\\underline{\\underline{A}}|`` is\n\n$|\\underline{\\underline{A}}| = (1)(2) - (1)(2) = 2 - 2 = 0$\n\nso ``\\underline{\\underline{A}}`` is the matrix with the zero determinant.\n\"\"\"\nend\n\n# ╔═╡ 2743185f-b0d7-4195-8e8e-a1bfcf132934\nlet\nmd\"\"\"\n### Problem 2\n\nFollow the procedure we went through in class to find the symmetry axes of the conic section ``6x^2 + 12xy + y^2 = 16``, and find the angle they make with the ``x,y`` axes.\nWhat kind of curve is this?\nA plot would be helpful.\nYou can do this with MATHEMATICA if you want, but the necessary algebra is rather simple.\n\"\"\"\nmd\"\"\"\n### Problem 2\n\n$\\underline{\\underline{A}} = \\begin{bmatrix} 6 & 6 \\\\ 6 & 1 \\end{bmatrix} \\implies \\underline{\\underline{R}} = \\frac{1}{\\sqrt{13}} \\begin{bmatrix} -2 & 3 \\\\ 3 & 2 \\end{bmatrix} \\implies \\underline{\\underline{R}}^T \\underline{\\underline{A}} \\,\\underline{\\underline{R}} = \\begin{bmatrix} -3 & 0 \\\\ 0 & 10 \\end{bmatrix}$\n\"\"\"\nend\n\n# ╔═╡ 982fab25-1414-4789-bc16-343ab29b4514\nlet\n\tA = [6 6; 6 1]\n\tv1 = eigvecs(A)[:,1]\n\tv2 = eigvecs(A)[:,2]\n\tR = [v1 v2]\n\tR' * A * R\nend\n\n# ╔═╡ 7e53c83c-ead7-484f-8762-4a0956ba7210\nmd\"\"\"\nThis produces the curve\n\n$-3x^2 + 10y^2 = 16$\n\nwhich is a hyperbola\n\"\"\"\n\n# ╔═╡ c8977146-1409-4eb1-bede-13436fd7214b\nlet\n\tplot(x -> sqrt(16 + 3x^2) / 10, color=:black, legend=false)\n\tplot!(x -> -sqrt(16 + 3x^2) / 10, color=:black, legend=false)\nend\n\n# ╔═╡ 201fb421-39b1-47db-8dec-609706461dca\nlet\nmd\"\"\"\n### Problem 3\n\nFind the eigenvalues and eigenvectors for the matrix\n\n$\\underline{\\underline{\\sigma}}_y = \\begin{bmatrix} 0 & -1 \\\\ i & 0 \\end{bmatrix}$\n\none of the three **Pauli matrices**.\nDo this by hand, not with MATHEMATICA.\nNormalize the eigenvectors and show that they are orthogonal.\n\"\"\"\nmd\"\"\"\n### Problem 3\n\nFirst, we find the characteristic polynomial.\n\n$\\det(\\underline{\\underline{\\sigma}}_y - \\lambda \\,\\underline{\\underline{I}}) = \\begin{vmatrix} -\\lambda & -i \\\\ i & -\\lambda \\end{vmatrix} = \\lambda^2 + i^2 = 0 \\implies \\lambda = ±1$\n\nThe eigenvalues are\n\n$\\lambda^{(1)} = -1 \\qquad \\lambda^{(2)} = 1$\n\nFor ``\\lambda^{(1)} = -1`` we have\n\n$\\begin{align*}\n-v_1 - i v_2 &= 0 \\\\\ni v_1 - v_2 &= 0\n\\end{align*}$\n\n$\\implies v_1 = 1, \\, v_2 = i$\n\ngiving the normalized eigenvector\n\n$\\underline{v} = \\frac{1}{\\sqrt{2}} \\begin{bmatrix} 1 \\\\ i \\end{bmatrix}$\n\nFor ``\\lambda^{(2)} = 1`` we have\n\n$\\begin{align*}\nu_1 - i u_2 &= 0 \\\\\ni u_1 - u_2 &= 0\n\\end{align*}$\n\n$\\implies u_1 = 1, \\, u_2 = i$\n\ngiving the normalized eigenvector\n\n$\\underline{u} = \\frac{1}{\\sqrt{2}} \\begin{bmatrix} 1 \\\\ -i \\end{bmatrix}$\n\nWe can show that the eigenvectors are orthogonal:\n\n$⟨v \\vert u⟩ = v_i u_i^* = \\left(\\frac{1}{\\sqrt{2}}\\right)^2 + \\left(\\frac{i}{\\sqrt{2}}\\right)^2 = \\frac{1}{\\sqrt{2}} - \\frac{1}{\\sqrt{2}} = 0$\n\"\"\"\nend\n\n# ╔═╡ e12e34c7-90db-4f31-8792-ce2a39acc435\nlet\nmd\"\"\"\n### Problem 4\n\nFind the eigenvalues, two of which equal each other, of the real symmetric matrix\n\n$\\underline{\\underline{A}} = \\begin{bmatrix} 13 & 4 & -2 \\\\ 4 & 13 & -2 \\\\ -2 & -2 & 10 \\end{bmatrix}$\n\nConstruct the three eigenvectors by hand, not with MATHEMATICA.\nYou will have more freedom than you would have thought.\nDo you see how to use this freedom to make all three eigenvectors mutually orthogonal?\n\"\"\"\nmd\"\"\"\n### Problem 4\n\nWe first calculate the characteristic equation\n\n$\\det(\\underline{\\underline{A}} - \\lambda \\, \\underline{\\underline{I}}) = \\begin{vmatrix} 13 - \\lambda & 4 & -2 \\\\ 4 & 13 - \\lambda & -2 \\\\ -2 & -2 & 10 - \\lambda \\end{vmatrix} = -(\\lambda - 18)(\\lambda - 9)^2$\n\nSo the eigenvalues are\n\n$\\lambda^{(1)} = 9 \\qquad \\lambda^{(2)} = 18$\n\nFor ``\\lambda^{(1)} = 9`` we have\n\n$\\begin{align*}\n4v_1 + 4v_2 - 2v_3 &= 0 \\\\\n4v_1 + 4v_2 - 2v_3 &= 0 \\\\\n-2v_1 - 2v_2 + v_3 &= 0\n\\end{align*}$\n\n$\\implies v_1 = 1, v_2 = 0, v_3 = 2 \\qquad \\text{or} \\qquad v_1 = -1, v_2 = 1, v_3 = 0$\n\nwhich gives the normalized eigenvectors\n\n$\\underline{v} = \\frac{1}{\\sqrt{5}} \\begin{bmatrix} 1 \\\\ 0 \\\\ 2 \\end{bmatrix} \\qquad \\underline{u} = \\frac{1}{\\sqrt{2}} \\begin{bmatrix} -1 \\\\ 1 \\\\ 0 \\end{bmatrix}$\n\nFor ``\\lambda^{(2)} = 18`` we have\n\n$\\begin{align*}\n-5w_1 + 4w_2 - 2w_3 &= 0 \\\\\n4w_1 - 5w_2 - 2w_3 &= 0 \\\\\n-2w_1 - 2w_2 - 8w_3 &= 0\n\\end{align*}$\n\n$\\implies w_1 = -2, w_2 = -2, w_3 = 1$\n\nwhich gives the normalized eigenvector\n\n$\\underline{w} = \\frac{1}{3} \\begin{bmatrix} -2 \\\\ -2 \\\\ 1 \\end{bmatrix}$\n\"\"\"\nend\n\n# ╔═╡ 1aaa8364-b72e-4128-b26a-82d4d4601634\nlet\nmd\"\"\"\n### Problem 5\n\nFind the eigenfrequencies and eigenmodes for the mechanical system\n\n`|~~~k~~~[ m ]~~~k~~~[ m ]~~~k~~~[ m ]~~~k~~~|`\n\nMake a plot that shows the motions of each of the three masses, for the three sets of initial conditions where the masses start at rest with position given by each of the three eigenvectors.\nBriefly describe the motions of the three masses, for each of the eigenmodes.\n\"\"\"\nmd\"\"\"\n### Problem 5\n\nThe coupled differential equations can be written as\n\n$\\begin{align*}\nmẍ_1 &= -kx_1 + k(x_2 - x_1) = -2kx_1 + kx_2 \\\\\nmẍ_2 &= -k(x_2 - x_1) + k(x_3 - x_2) = kx_1 - 2kx_2 + kx_3 \\\\\nmẍ_3 &= -k(x_3 - x_2) + k(-x_3) = kx_2 - 2kx_3\n\\end{align*}$\n\nWe can rewrite them using ``\\omega_0 = \\sqrt{k / m}``,\n\n$\\begin{align*}\nẍ_1 &= -2{\\omega_0}^2 x_1 + {\\omega_0}^2 x_2 \\\\\nẍ_2 &= {\\omega_0}^2 x_1 - 2{\\omega_0}^2 x_2 + {\\omega_0}^2 x_3 \\\\\nẍ_3 &= {\\omega_0}^2 x_2 - 2{\\omega_0}^2 x_3\n\\end{align*}$\n\nIn terms of vectors and matrices, we can write this as\n\n$\\underline{ẍ}(t) = -{\\omega_0}^2 \\underline{\\underline{Ω}} \\,\\underline{x}(t)$\n\nwhere\n\n$\\underline{x} = \\begin{bmatrix} x_1 \\\\ x_2 \\\\ x_3 \\end{bmatrix} \\qquad Ω = \\begin{bmatrix} -2 & 1 & 0 \\\\ 1 & -2 & 1 \\\\ 0 & 1 & -2 \\end{bmatrix}$\n\nwith the help of MATHEMATICA, we find the eigenfrequencies to be\n\n$\\omega_1 = \\sqrt{(2 - \\sqrt{2}) \\omega_0}, \\, \\omega_2 = \\sqrt{2\\omega_0}, \\, \\omega_3 = \\sqrt{(2 + \\sqrt{2}) \\omega_0}$\n\nand the normalized eigenmodes to be\n\n$\\underline{a}^{(1)} = \\frac{1}{2} \\begin{bmatrix} 1 \\\\ -\\sqrt{2} \\\\ 1 \\end{bmatrix} \\qquad \\underline{a}^{(2)} = \\frac{1}{\\sqrt{2}} \\begin{bmatrix} -1 \\\\ 0 \\\\ 1 \\end{bmatrix} \\qquad \\underline{a}^{(3)} = \\frac{1}{2} \\begin{bmatrix} 1 \\\\ \\sqrt{2} \\\\ 1 \\end{bmatrix}$\n\"\"\"\nend\n\n# ╔═╡ 7387c353-51b7-402b-a500-adec0a34b059\nlet\n\tΩ = [-2 1 0; 1 -2 1; 0 1 -2]\n\teigen(Ω)\nend\n\n# ╔═╡ b40838d0-8391-4f1e-a3fc-a4be028b7bc7\n(2 - sqrt(2))\n\n# ╔═╡ ec26fefb-18d1-4ac7-b0c1-0d3c71ae1305\nbegin\n\tω₁ = sqrt(2 - sqrt(2))\n\tω₂ = sqrt(2)\n\tω₃ = sqrt(2 + sqrt(2))\n\n\ta1 = (1/2) .* [1; -sqrt(2); 1]\n\ta2 = (1/sqrt(2)) .* [-1; 0; 1]\n\ta3 = (1/2) .* [1; sqrt(2); 1]\n\t\n\ts1(t, A, ϕ) = A .* a1 .* cos(ω₁ * t + ϕ)\n\ts2(t, A, ϕ) = A .* a2 .* cos(ω₂ * t + ϕ)\n\ts3(t, A, ϕ) = A .* a3 .* cos(ω₃ * t + ϕ)\nend;\n\n# ╔═╡ 355540ec-db9b-4ce5-a5d2-0c10497da934\nlet\n\tx1(t) = s1(t, 1, 0)[1]\n\tx2(t) = s1(t, 1, 0)[2]\n\tx3(t) = s1(t, 1, 0)[3]\n\tplot(x1, label=\"x₁\")\n\tplot!(x2, label=\"x₂\")\n\tplot!(x3, label=\"x₃\")\n\ttitle!(\"Eigenmode 1\")\nend\n\n# ╔═╡ de44b0c7-eee4-49ed-9264-40a5339e7d6c\nmd\"\"\"\nEigenmode 1: x1 and x3 oscillate with each other, opposite to x2\n\"\"\"\n\n# ╔═╡ 6f073f29-39b5-496e-b644-45051c81ab54\nlet\n\tx1(t) = s2(t, 1, 0)[1]\n\tx2(t) = s2(t, 1, 0)[2]\n\tx3(t) = s2(t, 1, 0)[3]\n\tplot(x1, label=\"x₁\")\n\tplot!(x2, label=\"x₂\")\n\tplot!(x3, label=\"x₃\")\n\ttitle!(\"Eigenmode 2\")\nend\n\n# ╔═╡ 5500a012-48fd-4227-a70f-515425c5122a\nmd\"\"\"\nEigenmode 2: x1 and x3 oscillate against each other while x2 remains in place\n\"\"\"\n\n# ╔═╡ e0a8d8ea-e5bd-48ca-b44f-4b6625181a17\nlet\n\tx1(t) = s3(t, 1, 0)[1]\n\tx2(t) = s3(t, 1, 0)[2]\n\tx3(t) = s3(t, 1, 0)[3]\n\tplot(x1, label=\"x₁\")\n\tplot!(x2, label=\"x₂\")\n\tplot!(x3, label=\"x₃\")\n\ttitle!(\"Eigenmode 3\")\nend\n\n# ╔═╡ cc32c2a5-d377-4a77-8477-b3acc63cca3b\nmd\"\"\"\nEigenmode 3: x1, x2, and x3 all oscillate with each other, however x2 oscillation is amplified\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nStatsPlots = \"f3b207a7-027a-5e70-b257-86293d7955fd\"\n\n[compat]\nStatsPlots = \"~0.14.33\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\njulia_version = \"1.8.0-beta1\"\nmanifest_format = \"2.0\"\nproject_hash = \"94b1ff0197986fb39c41ec4fbe1e3c63bdbc66ff\"\n\n[[deps.AbstractFFTs]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"6f1d9bc1c08f9f4a8fa92e3ea3cb50153a1b40d4\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"1.1.0\"\n\n[[deps.Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"af92965fb30777147966f58acb05da51c5616b5f\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.3\"\n\n[[deps.ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\nversion = \"1.1.1\"\n\n[[deps.Arpack]]\ndeps = [\"Arpack_jll\", \"Libdl\", \"LinearAlgebra\", \"Logging\"]\ngit-tree-sha1 = \"91ca22c4b8437da89b030f08d71db55a379ce958\"\nuuid = \"7d9fca2a-8960-54d3-9f78-7d1dccf2cb97\"\nversion = \"0.5.3\"\n\n[[deps.Arpack_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"OpenBLAS_jll\", \"Pkg\"]\ngit-tree-sha1 = \"5ba6c757e8feccf03a1554dfaf3e26b3cfc7fd5e\"\nuuid = \"68821587-b530-5797-8361-c406ea357684\"\nversion = \"3.5.1+1\"\n\n[[deps.Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[deps.AxisAlgorithms]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"66771c8d21c8ff5e3a93379480a2307ac36863f7\"\nuuid = \"13072b0f-2c55-5437-9ae7-d433b7a33950\"\nversion = \"1.0.1\"\n\n[[deps.Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[deps.Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[deps.Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"4b859a208b2397a7a623a03449e4636bdb17bcf2\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+1\"\n\n[[deps.Calculus]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"f641eb0a4f00c343bbc32346e1217b86f3ce9dad\"\nuuid = \"49dc2e85-a5d0-5ad3-a950-438e2897f1b9\"\nversion = \"0.5.1\"\n\n[[deps.ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"9950387274246d08af38f6eef8cb5480862a435f\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.14.0\"\n\n[[deps.ChangesOfVariables]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"bf98fa45a0a4cee295de98d4c1462be26345b9a1\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.2\"\n\n[[deps.Clustering]]\ndeps = [\"Distances\", \"LinearAlgebra\", \"NearestNeighbors\", \"Printf\", \"SparseArrays\", \"Statistics\", \"StatsBase\"]\ngit-tree-sha1 = \"75479b7df4167267d75294d14b58244695beb2ac\"\nuuid = \"aaaa29a8-35af-508c-8bc3-b662a17a0fe5\"\nversion = \"0.14.2\"\n\n[[deps.ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"12fc73e5e0af68ad3137b886e3f7c1eacfca2640\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.17.1\"\n\n[[deps.ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[deps.Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[deps.Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"96b0bc6c52df76506efc8a441c6cf1adcb1babc4\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.42.0\"\n\n[[deps.CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\nversion = \"0.5.0+0\"\n\n[[deps.Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[deps.DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[deps.DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"3daef5523dd2e769dad2365274f760ff5f282c7d\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.11\"\n\n[[deps.DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[deps.DataValues]]\ndeps = [\"DataValueInterfaces\", \"Dates\"]\ngit-tree-sha1 = \"d88a19299eba280a6d062e135a43f00323ae70bf\"\nuuid = \"e7dc6d0d-1eca-5fa6-8ad6-5aecde8b7ea5\"\nversion = \"0.4.13\"\n\n[[deps.Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[deps.DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[deps.DensityInterface]]\ndeps = [\"InverseFunctions\", \"Test\"]\ngit-tree-sha1 = \"80c3e8639e3353e5d2912fb3a1916b8455e2494b\"\nuuid = \"b429d917-457f-4dbc-8f4c-0cc954292b1d\"\nversion = \"0.4.0\"\n\n[[deps.Distances]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"3258d0659f812acde79e8a74b11f17ac06d0ca04\"\nuuid = \"b4f34e82-e78d-54a5-968a-f98e89d6e8f7\"\nversion = \"0.10.7\"\n\n[[deps.Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[deps.Distributions]]\ndeps = [\"ChainRulesCore\", \"DensityInterface\", \"FillArrays\", \"LinearAlgebra\", \"PDMats\", \"Printf\", \"QuadGK\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"Test\"]\ngit-tree-sha1 = \"5a4168170ede913a2cd679e53c2123cb4b889795\"\nuuid = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nversion = \"0.25.53\"\n\n[[deps.DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[deps.Downloads]]\ndeps = [\"ArgTools\", \"FileWatching\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\nversion = \"1.6.0\"\n\n[[deps.DualNumbers]]\ndeps = [\"Calculus\", \"NaNMath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"5837a837389fccf076445fce071c8ddaea35a566\"\nuuid = \"fa6b7ba4-c1ee-5f82-b5fc-ecf0adba8f74\"\nversion = \"0.6.8\"\n\n[[deps.EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[deps.Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"bad72f730e9e91c08d9427d5e8db95478a3c323d\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.4.8+0\"\n\n[[deps.FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[deps.FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[deps.FFTW]]\ndeps = [\"AbstractFFTs\", \"FFTW_jll\", \"LinearAlgebra\", \"MKL_jll\", \"Preferences\", \"Reexport\"]\ngit-tree-sha1 = \"505876577b5481e50d089c1c68899dfb6faebc62\"\nuuid = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nversion = \"1.4.6\"\n\n[[deps.FFTW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea\"\nuuid = \"f5851436-0d7a-5f13-b9de-f02708fd171a\"\nversion = \"3.3.10+0\"\n\n[[deps.FileWatching]]\nuuid = \"7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee\"\n\n[[deps.FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"246621d23d1f43e3b9c368bf3b72b2331a27c286\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.13.2\"\n\n[[deps.FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[deps.Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[deps.Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[deps.FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[deps.FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[deps.GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"51d2dfe8e590fbd74e7a842cf6d13d8a2f45dc01\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.6+0\"\n\n[[deps.GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"RelocatableFolders\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"af237c08bda486b74318c8070adb96efa6952530\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.64.2\"\n\n[[deps.GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"cd6efcf9dc746b06709df14e462f0a3fe0786b1e\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.64.2+0\"\n\n[[deps.GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"83ea630384a13fc4f002b77690bc0afeb4255ac9\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.2\"\n\n[[deps.Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[deps.Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"a32d672ac2c967f3deb8a81d828afc739c838a06\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+2\"\n\n[[deps.Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[deps.Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[deps.HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"0fa77022fe4b511826b39c894c90daf5fce3334a\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.17\"\n\n[[deps.HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"129acf094d168394e80ee1dc4bc06ec835e510a3\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+1\"\n\n[[deps.HypergeometricFunctions]]\ndeps = [\"DualNumbers\", \"LinearAlgebra\", \"SpecialFunctions\", \"Test\"]\ngit-tree-sha1 = \"65e4589030ef3c44d3b90bdc5aac462b4bb05567\"\nuuid = \"34004b35-14d8-5ef3-9330-4cdb6864b03a\"\nversion = \"0.3.8\"\n\n[[deps.IniFile]]\ngit-tree-sha1 = \"f550e6e32074c939295eb5ea6de31849ac2c9625\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.1\"\n\n[[deps.IntelOpenMP_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d979e54b71da82f3a65b62553da4fc3d18c9004c\"\nuuid = \"1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0\"\nversion = \"2018.0.3+2\"\n\n[[deps.InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[deps.Interpolations]]\ndeps = [\"AxisAlgorithms\", \"ChainRulesCore\", \"LinearAlgebra\", \"OffsetArrays\", \"Random\", \"Ratios\", \"Requires\", \"SharedArrays\", \"SparseArrays\", \"StaticArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"b15fc0a95c564ca2e0a7ae12c1f095ca848ceb31\"\nuuid = \"a98d9a8b-a2ab-59e6-89dd-64a1c18fca59\"\nversion = \"0.13.5\"\n\n[[deps.InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"91b5dcf362c5add98049e6c29ee756910b03051d\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.3\"\n\n[[deps.IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[deps.IterTools]]\ngit-tree-sha1 = \"fa6287a4469f5e048d763df38279ee729fbd44e5\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.4.0\"\n\n[[deps.IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[deps.JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"abc9885a7ca2052a736a600f7fa66209f96506e1\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.4.1\"\n\n[[deps.JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"3c837543ddb02250ef42f4738347454f95079d4e\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.3\"\n\n[[deps.JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b53380851c6e6664204efb2e62cd24fa5c47e4ba\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.2+0\"\n\n[[deps.KernelDensity]]\ndeps = [\"Distributions\", \"DocStringExtensions\", \"FFTW\", \"Interpolations\", \"StatsBase\"]\ngit-tree-sha1 = \"591e8dc09ad18386189610acafb970032c519707\"\nuuid = \"5ab0869b-81aa-558d-bb23-cbf5423bbe9b\"\nversion = \"0.6.3\"\n\n[[deps.LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[deps.LERC_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"bf36f528eec6634efc60d7ec062008f171071434\"\nuuid = \"88015f11-f218-50d7-93a8-a6af411a945d\"\nversion = \"3.0.0+1\"\n\n[[deps.LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[deps.LaTeXStrings]]\ngit-tree-sha1 = \"f2355693d6778a178ade15952b7ac47a4ff97996\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.3.0\"\n\n[[deps.Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"6f14549f7760d84b2db7a9b10b88cd3cc3025730\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.14\"\n\n[[deps.LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[deps.LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\nversion = \"0.6.3\"\n\n[[deps.LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\nversion = \"7.81.0+0\"\n\n[[deps.LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[deps.LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\nversion = \"1.10.2+0\"\n\n[[deps.Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[deps.Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"0b4a5d71f3e5200a7dff793393e09dfc2d874290\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+1\"\n\n[[deps.Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[deps.Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[deps.Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[deps.Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[deps.Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[deps.Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"LERC_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"c9551dd26e31ab17b86cbd00c2ede019c08758eb\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+1\"\n\n[[deps.Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[deps.LinearAlgebra]]\ndeps = [\"Libdl\", \"libblastrampoline_jll\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[deps.LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"58f25e56b706f95125dcb796f39e1fb01d913a71\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.10\"\n\n[[deps.Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[deps.MKL_jll]]\ndeps = [\"Artifacts\", \"IntelOpenMP_jll\", \"JLLWrappers\", \"LazyArtifacts\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e595b205efd49508358f7dc670a940c790204629\"\nuuid = \"856f044c-d86e-5d09-b602-aeab76dc8ba7\"\nversion = \"2022.0.0+0\"\n\n[[deps.MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[deps.Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[deps.MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[deps.MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\nversion = \"2.28.0+0\"\n\n[[deps.Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[deps.Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[deps.Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[deps.MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\nversion = \"2022.2.1\"\n\n[[deps.MultivariateStats]]\ndeps = [\"Arpack\", \"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsAPI\", \"StatsBase\"]\ngit-tree-sha1 = \"7008a3412d823e29d370ddc77411d593bd8a3d03\"\nuuid = \"6f286f6a-111f-5878-ab1e-185364afe411\"\nversion = \"0.9.1\"\n\n[[deps.NaNMath]]\ngit-tree-sha1 = \"737a5957f387b17e74d4ad2f440eb330b39a62c5\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"1.0.0\"\n\n[[deps.NearestNeighbors]]\ndeps = [\"Distances\", \"StaticArrays\"]\ngit-tree-sha1 = \"ded92de95031d4a8c61dfb6ba9adb6f1d8016ddd\"\nuuid = \"b8a86587-4115-5ab1-83bc-aa920d37bbce\"\nversion = \"0.4.10\"\n\n[[deps.NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\nversion = \"1.2.0\"\n\n[[deps.Observables]]\ngit-tree-sha1 = \"fe29afdef3d0c4a8286128d4e45cc50621b1e43d\"\nuuid = \"510215fc-4207-5dde-b226-833fc4488ee2\"\nversion = \"0.4.0\"\n\n[[deps.OffsetArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"043017e0bdeff61cfbb7afeb558ab29536bbb5ed\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.8\"\n\n[[deps.Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"887579a3eb005446d514ab7aeac5d1d027658b8f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+1\"\n\n[[deps.OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\nversion = \"0.3.17+2\"\n\n[[deps.OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\nversion = \"0.8.1+0\"\n\n[[deps.OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ab05aa4cc89736e95915b01e7279e61b1bfe33b8\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.14+0\"\n\n[[deps.OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[deps.Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[deps.OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[deps.PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[deps.PDMats]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"SuiteSparse\"]\ngit-tree-sha1 = \"e8185b83b9fc56eb6456200e873ce598ebc7f262\"\nuuid = \"90014a1f-27ba-587c-ab20-58faa44d9150\"\nversion = \"0.11.7\"\n\n[[deps.Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"621f4f3b4977325b9128d5fae7a8b4829a0c2222\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.2.4\"\n\n[[deps.Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[deps.Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\nversion = \"1.8.0\"\n\n[[deps.PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[deps.PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"bb16469fd5224100e422f0b027d26c5a25de1200\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.2.0\"\n\n[[deps.Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"Pkg\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\", \"UnicodeFun\", \"Unzip\"]\ngit-tree-sha1 = \"edec0846433f1c1941032385588fd57380b62b59\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.27.4\"\n\n[[deps.Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"d3538e7f8a790dc8903519090857ef8e1283eecd\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.5\"\n\n[[deps.Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[deps.Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[deps.QuadGK]]\ndeps = [\"DataStructures\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"78aadffb3efd2155af139781b8a8df1ef279ea39\"\nuuid = \"1fd47b50-473d-5c70-9696-f719f8f3bcdc\"\nversion = \"2.4.2\"\n\n[[deps.REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[deps.Random]]\ndeps = [\"SHA\", \"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[deps.Ratios]]\ndeps = [\"Requires\"]\ngit-tree-sha1 = \"dc84268fe0e3335a62e315a3a7cf2afa7178a734\"\nuuid = \"c84ed2f1-dad5-54f0-aa8e-dbefe2724439\"\nversion = \"0.4.3\"\n\n[[deps.RecipesBase]]\ngit-tree-sha1 = \"6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.2.1\"\n\n[[deps.RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"dc1e451e15d90347a7decc4221842a022b011714\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.5.2\"\n\n[[deps.Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[deps.RelocatableFolders]]\ndeps = [\"SHA\", \"Scratch\"]\ngit-tree-sha1 = \"cdbd3b1338c72ce29d9584fdbe9e9b70eeb5adca\"\nuuid = \"05181044-ff0b-4ac5-8273-598c1e38db00\"\nversion = \"0.1.3\"\n\n[[deps.Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.3.0\"\n\n[[deps.Rmath]]\ndeps = [\"Random\", \"Rmath_jll\"]\ngit-tree-sha1 = \"bf3188feca147ce108c76ad82c2792c57abe7b1f\"\nuuid = \"79098fc4-a85e-5d69-aa6a-4863f24498fa\"\nversion = \"0.7.0\"\n\n[[deps.Rmath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"68db32dff12bb6127bac73c209881191bf0efbb7\"\nuuid = \"f50d1b31-88e8-58de-be2c-1cc44531875f\"\nversion = \"0.3.0+0\"\n\n[[deps.SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\nversion = \"0.7.0\"\n\n[[deps.Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[deps.SentinelArrays]]\ndeps = [\"Dates\", \"Random\"]\ngit-tree-sha1 = \"6a2f7d70512d205ca8c7ee31bfa9f142fe74310c\"\nuuid = \"91c51154-3ec4-41a3-a24f-3f23e20d615c\"\nversion = \"1.3.12\"\n\n[[deps.Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[deps.SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[deps.Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[deps.Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[deps.SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[deps.SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[deps.SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"5ba658aeecaaf96923dce0da9e703bd1fe7666f9\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"2.1.4\"\n\n[[deps.StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"4f6ec5d99a28e1a749559ef7dd518663c5eca3d5\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.4.3\"\n\n[[deps.Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[deps.StatsAPI]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"c3d8ba7f3fa0625b062b82853a7d5229cb728b6b\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.2.1\"\n\n[[deps.StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"8977b17906b0a1cc74ab2e3a05faa16cf08a8291\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.16\"\n\n[[deps.StatsFuns]]\ndeps = [\"ChainRulesCore\", \"HypergeometricFunctions\", \"InverseFunctions\", \"IrrationalConstants\", \"LogExpFunctions\", \"Reexport\", \"Rmath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"72e6abd6fc9ef0fa62a159713c83b7637a14b2b8\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.17\"\n\n[[deps.StatsPlots]]\ndeps = [\"AbstractFFTs\", \"Clustering\", \"DataStructures\", \"DataValues\", \"Distributions\", \"Interpolations\", \"KernelDensity\", \"LinearAlgebra\", \"MultivariateStats\", \"Observables\", \"Plots\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"StatsBase\", \"TableOperations\", \"Tables\", \"Widgets\"]\ngit-tree-sha1 = \"4d9c69d65f1b270ad092de0abe13e859b8c55cad\"\nuuid = \"f3b207a7-027a-5e70-b257-86293d7955fd\"\nversion = \"0.14.33\"\n\n[[deps.StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"57617b34fa34f91d536eb265df67c2d4519b8b98\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.5\"\n\n[[deps.SuiteSparse]]\ndeps = [\"Libdl\", \"LinearAlgebra\", \"Serialization\", \"SparseArrays\"]\nuuid = \"4607b0f0-06f3-5cda-b6b1-a6196a1729e9\"\n\n[[deps.TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\nversion = \"1.0.0\"\n\n[[deps.TableOperations]]\ndeps = [\"SentinelArrays\", \"Tables\", \"Test\"]\ngit-tree-sha1 = \"e383c87cf2a1dc41fa30c093b2a19877c83e1bc1\"\nuuid = \"ab02a1b2-a7df-11e8-156e-fb1833f50b87\"\nversion = \"1.2.0\"\n\n[[deps.TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[deps.Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"OrderedCollections\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"5ce79ce186cc678bbb5c5681ca3379d1ddae11a1\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.7.0\"\n\n[[deps.Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\nversion = \"1.10.0\"\n\n[[deps.Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[deps.URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[deps.UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[deps.Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[deps.UnicodeFun]]\ndeps = [\"REPL\"]\ngit-tree-sha1 = \"53915e50200959667e78a92a418594b428dffddf\"\nuuid = \"1cfade01-22cf-5700-b092-accc4b62d6e1\"\nversion = \"0.4.1\"\n\n[[deps.Unzip]]\ngit-tree-sha1 = \"34db80951901073501137bdbc3d5a8e7bbd06670\"\nuuid = \"41fe7b60-77ed-43a1-b4f0-825fd5a5650d\"\nversion = \"0.1.2\"\n\n[[deps.Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[deps.Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4528479aa01ee1b3b4cd0e6faef0e04cf16466da\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.25.0+0\"\n\n[[deps.Widgets]]\ndeps = [\"Colors\", \"Dates\", \"Observables\", \"OrderedCollections\"]\ngit-tree-sha1 = \"505c31f585405fc375d99d02588f6ceaba791241\"\nuuid = \"cc8bc4a8-27d6-5769-a93b-9d913e69aa62\"\nversion = \"0.6.5\"\n\n[[deps.WoodburyMatrices]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"de67fa59e33ad156a590055375a30b23c40299d3\"\nuuid = \"efce3f68-66dc-5838-9240-27a6d6f5f9b6\"\nversion = \"0.5.5\"\n\n[[deps.XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[deps.XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[deps.Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[deps.Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[deps.Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[deps.Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[deps.Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[deps.Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[deps.Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[deps.Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[deps.Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[deps.Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[deps.Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[deps.Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[deps.Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[deps.Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[deps.Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[deps.Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[deps.Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[deps.Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[deps.Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\nversion = \"1.2.12+1\"\n\n[[deps.Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e45044cd873ded54b6a5bac0eb5c971392cf1927\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.2+0\"\n\n[[deps.libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[deps.libblastrampoline_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"OpenBLAS_jll\"]\nuuid = \"8e850b90-86db-534c-a0d3-1478176c7d93\"\nversion = \"5.0.1+0\"\n\n[[deps.libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[deps.libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[deps.libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"b910cb81ef3fe6e78bf6acee440bda86fd6ae00c\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+1\"\n\n[[deps.nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\nversion = \"1.41.0+1\"\n\n[[deps.p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\nversion = \"16.2.1+1\"\n\n[[deps.x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[deps.x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[deps.xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─1eb34f10-b4b3-11ec-19f5-c7f26108d374\n# ╟─6c4b3bf7-26e9-4d6f-9305-65fbc851818f\n# ╟─2743185f-b0d7-4195-8e8e-a1bfcf132934\n# ╠═982fab25-1414-4789-bc16-343ab29b4514\n# ╟─7e53c83c-ead7-484f-8762-4a0956ba7210\n# ╟─c8977146-1409-4eb1-bede-13436fd7214b\n# ╟─201fb421-39b1-47db-8dec-609706461dca\n# ╟─e12e34c7-90db-4f31-8792-ce2a39acc435\n# ╟─1aaa8364-b72e-4128-b26a-82d4d4601634\n# ╠═7387c353-51b7-402b-a500-adec0a34b059\n# ╠═b40838d0-8391-4f1e-a3fc-a4be028b7bc7\n# ╟─ec26fefb-18d1-4ac7-b0c1-0d3c71ae1305\n# ╟─355540ec-db9b-4ce5-a5d2-0c10497da934\n# ╟─de44b0c7-eee4-49ed-9264-40a5339e7d6c\n# ╟─6f073f29-39b5-496e-b644-45051c81ab54\n# ╟─5500a012-48fd-4227-a70f-515425c5122a\n# ╟─e0a8d8ea-e5bd-48ca-b44f-4b6625181a17\n# ╟─cc32c2a5-d377-4a77-8477-b3acc63cca3b\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "196d832f6a3545c348bd4880f501809946ac9df4", "size": 49338, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "homework-11.jl", "max_stars_repo_name": "airicbear/PHYS2502", "max_stars_repo_head_hexsha": "11d7b3de67e6152735abfeff8fa9295b932004ba", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework-11.jl", "max_issues_repo_name": "airicbear/PHYS2502", "max_issues_repo_head_hexsha": "11d7b3de67e6152735abfeff8fa9295b932004ba", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework-11.jl", "max_forks_repo_name": "airicbear/PHYS2502", "max_forks_repo_head_hexsha": "11d7b3de67e6152735abfeff8fa9295b932004ba", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2242424242, "max_line_length": 382, "alphanum_fraction": 0.7170537922, "num_tokens": 22312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.870597273444551, "lm_q1q2_score": 0.7839987764498422}}
{"text": "\nfunction mandelbrot_set(xmin,xmax,ymin,ymax,width,height,maxiter)\n    r1 = float_range(xmin, xmax, width)\n    r2 = float_range(ymin, ymax, height)\n\n    cartesian =  Array{Float64, 3}(undef, 3, height, width)   \n\n    for y = 1:height, x = 1:width\n\tpoint = mandel(ComplexF64(r1[x], r2[y]), maxiter)\n\tif point == maxiter\n\t\tpoint = 0\n\telse\n\t\tpoint /= convert(Float64, maxiter)\n\n\tend\n\n \tred_color, blue_color, green_color = 1.0, 1.0, 1.0\n    \tif point < 0.01\n            red_color, blue_color, green_color = 1.0, 1.0, 1.0\n    \telse\n            red_color = point * 0.80\n            blue_color = point * 0.80\n            green_color = point * 0.15\n    \tend\n\n\tcartesian[1,y,x] = red_color\n\tcartesian[2,y,x] = blue_color\n\tcartesian[3,y,x] = green_color\n    end\n\n    return cartesian\nend\n\n# the mandelbrot iteration function\nfunction mandel(c, maxiter::Int64)\n    z=0+0im\n    for n = 1:maxiter\n        if abs(z) > 2\n            return n-1\n        end\n        z = z^2 + c\n    end\n    return maxiter\nend\n\nfunction float_range(xmin, xmax, width)\n\tr = Array{Float64, 1}(undef, width)\n\n\tdelta = abs(xmax - xmin)/(width - 1)\n\n\tfor i = 1:width\n\t\tr[i] = xmin + (i-1)*delta\n\tend\n\n\treturn r\nend\n\n", "meta": {"hexsha": "212ee88c947afb9e20858dbf70e77d074ea27dc1", "size": 1177, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "mandel.jl", "max_stars_repo_name": "rabarar/juliaFractals", "max_stars_repo_head_hexsha": "485212d17ef9c6c08951628f9071cf149c23dfe3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mandel.jl", "max_issues_repo_name": "rabarar/juliaFractals", "max_issues_repo_head_hexsha": "485212d17ef9c6c08951628f9071cf149c23dfe3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mandel.jl", "max_forks_repo_name": "rabarar/juliaFractals", "max_forks_repo_head_hexsha": "485212d17ef9c6c08951628f9071cf149c23dfe3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2931034483, "max_line_length": 65, "alphanum_fraction": 0.6049277825, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.783983241532735}}
{"text": "using LinearAlgebra\nP = [   0   1   0   0   0;\n        1/4 0   1/4 1/4 1/4;\n        0   1/2 0   0   1/2;\n        0   1/2 0   0   1/2;\n        0   0   0   0   1]\nT = P[1:4,1:4]\np0 = [1 0 0 0]\nfor n in 1:10\n    println(first(p0*sum([T^k for k in 0:n])*ones(4)))\nend\nprintln(\"Using inverse: \", first(p0*inv(I-T)*ones(4)))\nprintln(\"Eigenvalues of T: \", sort(eigvals(T)))", "meta": {"hexsha": "38d98c120caae99b7731f4ec534a108b21bd4fea", "size": 366, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "10_chapter/mcTransientCalculation.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "10_chapter/mcTransientCalculation.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "10_chapter/mcTransientCalculation.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 28.1538461538, "max_line_length": 54, "alphanum_fraction": 0.4836065574, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7839832309773147}}
{"text": "@with_kw struct DGaussianPulse <: AbstractWaveform\n    fc::Float64 = 0.0\n    half_bandwidth::Float64\n    half_width::Float64 = 1 / (2 * sqrt(log(2))) * 1 / (π * half_bandwidth)\n    time_delay::Float64 = 6 * half_width\nend\n(s::DGaussianPulse)(t) = -(t - s.time_delay) / s.half_width * exp(-(t - s.time_delay)^2 / s.half_width^2)\n@with_kw struct GaussianPulse <: AbstractWaveform\n    fc::Float64 = 0.0\n    half_bandwidth::Float64\n    half_width::Float64 = 1 / (2 * sqrt(log(2))) * 1 / (π * half_bandwidth)\n    time_delay::Float64 = 6 * half_width\nend\n\n(s::GaussianPulse)(t) = cos(2π * s.fc * (t - s.time_delay)) * exp(-(t - s.time_delay)^2 / s.half_width^2)\n\nconst GaussianWaveForm = Union{GaussianPulse,DGaussianPulse}\n\n@recipe function f(s::GaussianWaveForm; nsamples = 20, spectrum = true)\n    if spectrum\n        xlabel := \"frequency\"\n        xrange := [-s.fc - 10 * s.half_bandwidth, s.fc + 10 * s.half_bandwidth]\n    else\n        xrange := [s.time_delay - 3s.half_width, s.time_delay + 3s.half_width]\n    end\n    δt = 1 / (s.fc + s.half_bandwidth) / nsamples\n    t_samples = range(s.time_delay - 20s.half_width, s.time_delay + 20s.half_width, step = δt)\n    if spectrum\n        return fourier(t_samples, s.(t_samples))\n    else\n        return (t_samples, s.(t_samples))\n    end\nend\n", "meta": {"hexsha": "0caf1cf4dc298ee2dcff432eda0445ffd45c5710", "size": 1286, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Waveforms/GaussianWaveForm.jl", "max_stars_repo_name": "MKAbdElrahman/FDTDSolver.jl", "max_stars_repo_head_hexsha": "d6f8bd0cabdde3e073a41f0d6c667b69e3873c3e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Waveforms/GaussianWaveForm.jl", "max_issues_repo_name": "MKAbdElrahman/FDTDSolver.jl", "max_issues_repo_head_hexsha": "d6f8bd0cabdde3e073a41f0d6c667b69e3873c3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Waveforms/GaussianWaveForm.jl", "max_forks_repo_name": "MKAbdElrahman/FDTDSolver.jl", "max_forks_repo_head_hexsha": "d6f8bd0cabdde3e073a41f0d6c667b69e3873c3e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8235294118, "max_line_length": 105, "alphanum_fraction": 0.6516329705, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7839832309773147}}
{"text": "eta = 0.9\n\nfunction f1(x)\n    (1.0 / 2.0) * (x[1]^2 + eta * x[2]^2)\nend\n\nfunction g1(x, storage)\n    storage[1] = x[1]\n    storage[2] = eta * x[2]\nend\n\nfunction h1(x, storage)\n    storage[1, 1] = 1.0\n    storage[1, 2] = 0.0\n    storage[2, 1] = 0.0\n    storage[2, 2] = eta\nend\n\nresults = optimize(f1, g1, h1, [127.0, 921.0])\n@assert results.converged\n@assert norm(results.minimum - [0.0, 0.0]) < 0.01\n\nresults = optimize(f1, g1, [127.0, 921.0])\n@assert results.converged\n@assert norm(results.minimum - [0.0, 0.0]) < 0.01\n\nresults = optimize(f1, [127.0, 921.0])\n@assert results.converged\n@assert norm(results.minimum - [0.0, 0.0]) < 0.01\n", "meta": {"hexsha": "8461ee649169420f6d0c2945901ba3f9634f1228", "size": 636, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/optimize.jl", "max_stars_repo_name": "aviks/Optim.jl", "max_stars_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-22T09:32:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-22T09:32:32.000Z", "max_issues_repo_path": "test/optimize.jl", "max_issues_repo_name": "aviks/Optim.jl", "max_issues_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/optimize.jl", "max_forks_repo_name": "aviks/Optim.jl", "max_forks_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2, "max_line_length": 49, "alphanum_fraction": 0.6006289308, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7839832265192973}}
{"text": "# # Variational problems \n#\n# In this example, we will numerically simulate an entropy-regularised Wasserstein gradient flow \n# approximating the Fokker-Planck and porous medium equations. \n# \n# The connection between Wasserstein gradient flows and (non)-linear PDEs is due to Jordan, Kinderlehrer and Otto [^JKO98], and \n# an easy-to-read overview of the topic is provided in Section 9.3 [^PC19]\n#\n# [^JKO98]: Jordan, Richard, David Kinderlehrer, and Felix Otto. \"The variational formulation of the Fokker--Planck equation.\" SIAM journal on mathematical analysis 29.1 (1998): 1-17.\n# [^PC19]: Peyré, Gabriel, and Marco Cuturi. \"Computational optimal transport: With applications to data science.\" Foundations and Trends® in Machine Learning 11.5-6 (2019): 355-607.\n#\n# ## Fokker-Planck equation as a $W_2$ gradient flow\n# For a potential function $\\Psi$ and noise level $\\sigma^2$, the Fokker-Planck equation (FPE) is \n# ```math\n# \\partial_t \\rho_t = \\nabla \\cdot (\\rho_t \\nabla \\Psi) + \\frac{\\sigma^2}{2} \\Delta \\rho_t,\n# ```\n# and we take no-flux (Neumann) boundary conditions. \n#\n# This describes the evolution of a massless particle undergoing both diffusion (with diffusivity $\\sigma^2$) and drift (along potential $\\Psi$) according to the stochastic differential equation\n# ```math\n# dX_t = -\\nabla \\Psi(X_t) dt + \\sigma dB_t. \n# ```\n# The result of Jordan, Kinderlehrer and Otto (commonly referred to as the JKO theorem) states that \n# $\\rho_t$ evolves following the 2-Wasserstein gradient flow of the Gibbs free energy functional\n# ```math\n#   F(\\rho) = \\int \\Psi d\\rho + \\int \\log(\\rho) d\\rho. \n# ```\n#\n# ## Implicit schemes for gradient flows\n# In an Euclidean space, the gradient flow of a functional $F$ is simply the solution of an ordinary differential equation\n# ```math\n#  \\dfrac{dx(t)}{dt} = -\\nabla F(x(t)).\n# ```\n# Of course, there is a requirement that $F$ is smooth. A more general formulation of a gradient flow that allows\n# $F$ to be non-smooth is the implicit scheme\n# ```math\n#   x_{t+\\tau} = \\operatorname{argmin}_x \\frac{1}{2} \\| x - x_t \\|_2^2 + \\tau F(x).\n# ```\n# As the timestep $\\tau$ shrinks, $x_t$ becomes a better and better approximation to the gradient flow of $F$. \n#\n# ## Wasserstein gradient flow\n# In the context of the JKO theorem, we seek $\\rho_t$ that is the gradient flow of $F$ with \n# respect to the 2-Wasserstein distance. This can be achieved by choosing the $W_2$ metric in the implicit step:\n# ```math\n#   \\rho_{t + \\tau} = \\operatorname{argmin}_{\\rho} d_{W_2}^2(\\rho_{t}, \\rho) + \\tau F(\\rho). \n# ```\n# Finally, a numerical scheme for computing this gradient flow can be developed by using the entropic regularisation\n# of optimal transport on a discretised domain \n# ```math\n#   \\rho_{t + \\tau} = \\operatorname{argmin}_{\\rho} \\operatorname{OT}_\\varepsilon(\\rho_{t}, \\rho) + \\tau F(\\rho),\n# ```\n# where \n# ```math\n#   \\operatorname{OT}_\\varepsilon(\\alpha, \\beta) = \\min_{\\gamma \\in \\Pi(\\alpha, \\beta)} \\sum_{i,j} \\frac{1}{2} \\| x_i - x_j \\|_2^2 \\gamma_{ij} + \\varepsilon \\sum_{i, j} \\gamma_{ij} \\log(\\gamma_{ij}). \n# ```\n# Each step of this problem is a minimisation problem with respect to $\\rho$. \n# Since we use entropic optimal transport which is differentiable, this can be solved using gradient-based methods.\n\n# ## Problem setup\n#\nusing OptimalTransport\nusing Distances\nusing LogExpFunctions\nusing Optim\nusing Plots\nusing StatsBase\nusing ReverseDiff\n\nusing LinearAlgebra\nusing Logging\n\n# Here, we set up the computational domain that we work on - we discretize the interval $[-1, 1]$. \n# The natural boundary conditions to use will be Neumann (zero flux), see e.g. [^Santam2017]\n#\n# [^Santam2017]: Santambrogio, Filippo. \"{Euclidean, metric, and Wasserstein} gradient flows: an overview.\" Bulletin of Mathematical Sciences 7.1 (2017): 87-154.\n\nsupport = range(-1, 1; length=64)\nC = pairwise(SqEuclidean(), support');\n\n# Now we set up various functionals that we will use.\n#\n# We define the generalised entropy (Equation (4.4) of [^Peyre2015]) as follows. For $m = 1$ this is just the \"regular\" entropy, and $m = 2$ this is squared $L_2$. \n#\n# [^Peyre2015]: Peyré, Gabriel. \"Entropic approximation of Wasserstein gradient flows.\" SIAM Journal on Imaging Sciences 8.4 (2015): 2323-2351.\nfunction E(ρ; m=1)\n    if m == 1\n        return sum(xlogx.(ρ)) - sum(ρ)\n    elseif m > 1\n        return dot(ρ, @. (ρ^(m - 1) - m) / (m - 1))\n    end\nend;\n\n# Now define $\\psi(x)$ to be a potential energy function that has two potential wells at $x = ± 0.5$. \nψ(x) = 10 * (x - 0.5)^2 * (x + 0.5)^2;\nplot(support, ψ.(support); color=\"black\", label=\"Scalar potential\")\n\n# Having defined $\\psi$, this induces a potential energy functional $\\Psi$ on probability distributions $\\rho$:\n# ```math\n#    \\Psi(\\rho) = \\int \\psi(x) \\rho(x) dx = \\langle \\psi, \\rho \\rangle . \n# ```\nΨ = ψ.(support);\n\n# Define the time step $\\tau$ and entropic regularisation level $\\varepsilon$, and form the associated Gibbs kernel $K = e^{-C/\\varepsilon}$. \nτ = 0.05\nε = 0.01\nK = @. exp(-C / ε);\n\n# We define the (non-smooth) initial condition $\\rho_0$ in terms of step functions. \nH(x) = x > 0\nρ0 = @. H(support + 0.25) - H(support - 0.25)\nρ0 = ρ0 / sum(ρ0)\nplot(support, ρ0; label=\"Initial condition ρ0\", color=\"blue\")\n\n# `G_fpe` is the objective function for the implicit step scheme  \n# ```math\n# G_\\mathrm{fpe}(\\rho) = \\operatorname{OT}_\\varepsilon(\\rho_{t}, \\rho) + \\tau F(\\rho),\n# ```\n# and we seek to minimise in $\\rho$. \nfunction G_fpe(ρ, ρ0, τ, ε, C)\n    return sinkhorn2(ρ, ρ0, C, ε; regularization=true, maxiter=250) + τ * (dot(Ψ, ρ) + E(ρ))\nend;\n\n# `step` solves the implicit step problem to produce $\\rho_{t + \\tau}$ from $\\rho_t$. \nfunction step(ρ0, τ, ε, C, G)\n    ## only print error messages\n    obj = u -> G(softmax(u), ρ0, τ, ε, C)\n    opt = with_logger(SimpleLogger(stderr, Logging.Error)) do\n        optimize(\n            obj,\n            ones(size(ρ0)),\n            LBFGS(),\n            Optim.Options(; iterations=50, g_tol=1e-6);\n            autodiff=:forward,\n        )\n    end\n    return softmax(Optim.minimizer(opt))\nend\n# Now we simulate `N = 10` iterates of the gradient flow and plot the result. \n\nN = 10\nρ = similar(ρ0, size(ρ0, 1), N)\nρ[:, 1] = ρ0\nfor i in 2:N\n    @info i\n    ρ[:, i] = step(ρ[:, i - 1], τ, ε, C, G_fpe)\nend\ncolors = range(colorant\"red\"; stop=colorant\"blue\", length=N)\nplot(\n    support,\n    ρ;\n    title=raw\"$F(\\rho) = \\langle \\psi, \\rho \\rangle + \\langle \\rho, \\log(\\rho) \\rangle$\",\n    palette=colors,\n    legend=nothing,\n)\n\n# ## Porous medium equation \n#\n# The porous medium equation (PME) is the nonlinear PDE \n# ```math\n# \\partial_t \\rho = \\nabla \\cdot (\\rho \\nabla \\Psi) + \\Delta \\rho^m,\n# ```\n# again with Neumann boundary conditions. The value of $m$ in the PME corresponds to picking $m$ in the generalised entropy functional.  \n# Now, we will solve the PME with $m = 2$ as a Wasserstein gradient flow.\n#\nfunction G_pme(ρ, ρ0, τ, ε, C)\n    return sinkhorn2(ρ, ρ0, C, ε; regularization=true, maxiter=250) +\n           τ * (dot(Ψ, ρ) + E(ρ; m=2))\nend;\n\n# set up as previously \nN = 10\nρ = similar(ρ0, size(ρ0, 1), N)\nρ[:, 1] = ρ0\nfor i in 2:N\n    ρ[:, i] = step(ρ[:, i - 1], τ, ε, C, G_pme)\nend\nplot(\n    support,\n    ρ;\n    title=raw\"$F(\\rho) = \\langle \\psi, \\rho \\rangle + \\langle \\rho, \\rho - 1\\rangle$\",\n    palette=colors,\n    legend=nothing,\n)\n\n# ## Exploiting duality \n# \n# The previous examples solved the minimisation problem for the implicit gradient flow step directly, involving automatic differentiation through the Sinkhorn iterations used to compute $\\operatorname{OT}_\\varepsilon(\\rho_t, \\rho)$ each time a gradient needs to be evaluated. \n# While this is straightforward to implement, it is computationally costly. \n# An alternative approach for convex variational problems is to proceed via the [dual problem](https://en.wikipedia.org/wiki/Duality_(optimization)). \n# The benefit of proceeding via the dual problem is that the part of the dual minimisation problem corresponding to the (entropy-regularised) optimal transport loss is typically available in closed form. This is in contrast to the primal problem, where evaluation of the objective and its gradients requires potentially many Sinkhorn iterations.\n#\n# Consider a general convex and unconstrained problem. Under (usually satisfied) conditions for strong duality to hold, we have \n# ```math\n# \\begin{aligned}\n# &\\min_{\\rho} \\operatorname{OT}_{\\varepsilon}(\\rho_0, \\rho) + \\mathcal{F}(\\rho)  \\\\\n# &= \\min_{\\rho} \\sup_{u}\\left[\\langle \\rho, u \\rangle - \\operatorname{OT}^*_{\\varepsilon}(\\rho_0, u)\\right] + \\mathcal{F}(\\rho)  \\\\\n# &= \\sup_{u} \\min_{\\rho} \\langle \\rho, u \\rangle - \\operatorname{OT}^*_{\\varepsilon}(\\rho_0, u) + \\mathcal{F}(\\rho) \\\\\n# &= \\sup_{u} - \\operatorname{OT}^*_{\\varepsilon}(\\rho_0, u) + \\min_{\\rho} \\langle \\rho, u \\rangle + \\mathcal{F}(\\rho) \\\\\n# &= \\sup_{u} - \\operatorname{OT}^*_{\\varepsilon}(\\rho_0, u) - \\sup_{\\rho} \\langle \\rho, -u \\rangle - \\mathcal{F}(\\rho) \\\\\n# &= \\sup_{u} - \\operatorname{OT}^*_{\\varepsilon}(\\rho_0, u) - \\mathcal{F}^*(-u). \n# \\end{aligned}\n# ```\n# Thus, the dual problem is \n# ```math\n# \\min_{u} \\operatorname{OT}^*_{\\varepsilon}(\\rho_0, u) + \\mathcal{F}^*(-u). \n# ```\n#\n# The upshot here is that $u \\mapsto \\operatorname{OT}^*_{\\varepsilon}(\\rho_0, u)$ and its gradient is available in closed form. This is a known result in the literature [^CP18].\n#\n# [^CP18]: Cuturi, Marco, and Gabriel Peyré. “Semi-Dual Regularized Optimal Transport.” ArXiv: Learning, 2018.\n#\n# The formulas we state below are lifted from statements in [^Z21]. \n#\n# [^Z21]: Zhang, Stephen Y. “A Unified Framework for Non-Negative Matrix and Tensor Factorisations with a Smoothed Wasserstein Loss.” ArXiv: Machine Learning, 2021.\n#\n# ```math\n# \\begin{aligned}\n# \\operatorname{OT}^*_{\\varepsilon}(\\rho_0, u) &= -\\varepsilon \\left\\langle \\rho_0, \\log\\left( \\dfrac{\\rho_0}{K e^{u/\\varepsilon}} \\right) - 1\\right\\rangle, \\\\\n# \\nabla_u \\operatorname{OT}^*_{\\varepsilon}(\\rho_0, u) &= K^\\top \\left( \\dfrac{\\rho_0}{K e^{u/\\varepsilon}} \\right) \\odot e^{u/\\varepsilon}. \n# \\end{aligned}\n# ```\n# At optimality, we can recover the primal optimal point $\\rho^\\star$ from the dual optimal point $u^\\star$ following the formula\n# ```math\n# \\rho^\\star = e^{u^\\star/\\varepsilon} \\odot K^\\top \\dfrac{\\rho_0}{K e^{u^\\star/\\varepsilon}}. \n# ```\n# \n# When $\\mathcal{F}^*(\\cdot)$ is also available in closed form (this is not always the case), the dual problem has a closed form objective and can generally be solved much more efficiently than the primal problem. \n#\n# In the setting of the Fokker-Planck and porous medium equations, the function $\\mathcal{F}$ can be identified with\n#\n# ```math\n# \\mathcal{F}(\\rho) = \\tau \\left[ \\langle \\psi, \\rho \\rangle + E_m(\\rho) \\right]. \n# ```\n#\n# A straightforward computation shows that\n# ```math\n# \\mathcal{F}^*(u) = \\tau E_m^*\\left( \\frac{u}{\\tau}-\\psi \\right), \n# ```\n# where \n# ```math\n#     E_m^*(u) = \\begin{cases}\n#     \\langle e^u, \\mathbf{1} \\rangle, & m = 1 \\\\ \n#     \\sum_i \\left[ \\left( u_i + \\frac{m}{m-1} \\right) \\left( \\frac{m-1}{m} u_i + 1 \\right)^{\\frac{1}{m-1}} - \\frac{1}{m-1} \\left( \\frac{m-1}{m} u_i + 1 \\right)^{\\frac{m}{m-1}} \\right], & m > 1.\n#     \\end{cases}\n# ```\n# In particular, for $m = 2$ we have a simpler formula\n# ```math\n# E_2^*(u) = \\left\\| \\frac{u}{2} + 1 \\right\\|_2^2 \n# ```\n#\n# We now implement $E_m^*$ for $m = 1, 2$. \nE_dual(u, m::Val{1}) = sum(exp.(u))\nfunction E_dual(u, m::Val{2})\n    return dot(u / 2 .+ 1, u / 2 .+ 1)\nend;\n# \n# So, the dual problem we are dealing with reads\n# ```math\n# \\min_{u} \\operatorname{OT}^*_{\\varepsilon}(\\rho_0, u) + \\tau E_m^*\\left( \\frac{-u}{\\tau}-\\psi \\right), \n# ```\n# and we can thus set up `G_dual_fpe`, the dual objective. \n#\nfunction G_dual_fpe(u, ρ0, τ, ε, K)\n    return OptimalTransport.Dual.ot_entropic_semidual(ρ0, u, ε, K) +\n           τ * E_dual(-u / τ - Ψ, Val(1))\nend;\n# \n# Now we set up `step` as previously, except this time we need to convert from the optimal dual variable $u^\\star$ to the primal variable $\\rho^\\star$. In the code, this is handled by `getprimal_ot_entropic_semidual`. We use `ReverseDiff` in this problem. \n#\nfunction step(ρ0, τ, ε, K, G)\n    obj = u -> G(u, ρ0, τ, ε, K)\n    opt = optimize(\n        obj,\n        (∇, u) -> ReverseDiff.gradient!(∇, obj, u),\n        zeros(size(ρ0)),\n        LBFGS(),\n        Optim.Options(; iterations=250, g_tol=1e-6),\n    )\n    return OptimalTransport.Dual.getprimal_ot_entropic_semidual(\n        ρ0, Optim.minimizer(opt), ε, K\n    )\nend;\n# \n# Now we can solve the dual problem as previously, and we note that the dual formulation is solved an order of magnitude faster than the primal formulation.\n#\nρ = similar(ρ0, size(ρ0, 1), N)\nρ[:, 1] = ρ0\nfor i in 2:N\n    ρ[:, i] = step(ρ[:, i - 1], τ, ε, K, G_dual_fpe)\nend\ncolors = range(colorant\"red\"; stop=colorant\"blue\", length=N)\nplot(\n    support,\n    ρ;\n    title=raw\"$F(\\rho) = \\langle \\psi, \\rho \\rangle + \\langle \\rho, \\log(\\rho) \\rangle$\",\n    palette=colors,\n    legend=nothing,\n)\n\n# Setting `m = 2`, we can simulate instead the porous medium equation.\n#\nfunction G_dual_pme(u, ρ0, τ, ε, K)\n    return OptimalTransport.Dual.ot_entropic_semidual(ρ0, u, ε, K) +\n           τ * E_dual(-u / τ - Ψ, Val(2))\nend\nρ = similar(ρ0, size(ρ0, 1), N)\nρ[:, 1] = ρ0\nfor i in 2:N\n    @info i\n    ρ[:, i] = step(ρ[:, i - 1], τ, ε, K, G_dual_pme)\nend\ncolors = range(colorant\"red\"; stop=colorant\"blue\", length=N)\nplot(\n    support,\n    ρ;\n    title=raw\"$F(\\rho) = \\langle \\psi, \\rho \\rangle + \\langle \\rho, \\rho - 1\\rangle$\",\n    palette=colors,\n    legend=nothing,\n)\n", "meta": {"hexsha": "d6bc7cdb078010a03f55d18fa65e3e3f10e4dba1", "size": 13544, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/variational/script.jl", "max_stars_repo_name": "zsteve/ot.jl", "max_stars_repo_head_hexsha": "a82e3fb19b00839ba809225e76a4ea43b49a315d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2021-05-28T14:16:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:38:40.000Z", "max_issues_repo_path": "examples/variational/script.jl", "max_issues_repo_name": "zsteve/ot.jl", "max_issues_repo_head_hexsha": "a82e3fb19b00839ba809225e76a4ea43b49a315d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 109, "max_issues_repo_issues_event_min_datetime": "2021-05-18T18:45:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T12:30:01.000Z", "max_forks_repo_path": "examples/variational/script.jl", "max_forks_repo_name": "zsteve/ot.jl", "max_forks_repo_head_hexsha": "a82e3fb19b00839ba809225e76a4ea43b49a315d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-30T12:11:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T19:11:56.000Z", "avg_line_length": 42.325, "max_line_length": 345, "alphanum_fraction": 0.6549763733, "num_tokens": 4520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8615382112085969, "lm_q1q2_score": 0.7839196459289538}}
{"text": "## Laplacian\n\nfunction _imfilter_inbounds!(r::AbstractResource, out, A::AbstractArray, L::Laplacian, border::NoPad, inds)\n    TT = eltype(out) # accumtype(eltype(out), eltype(A))\n    n = 2*length(L.offsets)\n    R = CartesianIndices(inds)\n    @inbounds for I in R\n        tmp = convert(TT, - n * A[I])\n        for J in L.offsets\n            tmp += A[I+J]\n            tmp += A[I-J]\n        end\n        out[I] = tmp\n    end\n    out\nend\n\n## imgradients\n\"\"\"\n```julia\n    imgradients(img, kernelfun=KernelFactors.ando3, border=\"replicate\") -> gimg1, gimg2, ...\n```\nEstimate the gradient of `img` in the direction of the first and second dimension\nat all points of the image, using a kernel specified by `kernelfun`.\n\n# Output\n\nThe gradient is returned as a tuple-of-arrays, one for each dimension of the\ninput; `gimg1` corresponds to the derivative with respect to the first\ndimension, `gimg2` to the second, and so on.\n\n# Details\n\nTo appreciate the difference between various gradient estimation methods\nit is helpful to distinguish between: (1) a continuous scalar-valued\n*analogue* image ``f_\\\\textrm{A}(x_1,x_2)``, where ``x_1,x_2 \\\\in\n\\\\mathbb{R}``, and (2) its discrete *digital* realization\n``f_\\\\textrm{D}(x_1',x_2')``, where ``x_1',x_2' \\\\in \\\\mathbb{N}``, ``1\n\\\\le x_1' \\\\le M`` and ``1 \\\\le x_2' \\\\le N``.\n\n## Analogue image\n\nThe gradient of a continuous analogue image ``f_{\\\\textrm{A}}(x_1,x_2)`` at\nlocation ``(x_1,x_2)`` is defined as the vector\n```math\n\\\\nabla \\\\mathbf{f}_{\\\\textrm{A}}(x_1,x_2) = \\\\frac{\\\\partial\nf_{\\\\textrm{A}}(x_1,x_2)}{\\\\partial x_1} \\\\mathbf{e}_{1} +\n\\\\frac{\\\\partial f_{\\\\textrm{A}}(x_1,x_2)}{\\\\partial x_2} \\\\mathbf{e}_{2},\n```\nwhere ``\\\\mathbf{e}_{d}`` ``(d = 1,2)`` is the unit\nvector in the ``x_d``-direction. The gradient points in the direction of\nmaximum rate of change of ``f_{\\\\textrm{A}}`` at the coordinates\n``(x_1,x_2)``. The gradient can be used to compute the derivative of a\nfunction in an arbitrary direction. In particular, the derivative of\n``f_{\\\\textrm{A}}`` in the direction of a unit vector ``\\\\mathbf{u}`` is\ngiven by ``\\\\nabla_{\\\\mathbf{u}}f_\\\\textrm{A}(x_1,x_2) = \\\\nabla\n\\\\mathbf{f}_{\\\\textrm{A}}(x_1,x_2) \\\\cdot \\\\mathbf{u}``, where\n``\\\\cdot`` denotes the dot product.\n\n## Digital image\n\nIn practice, we acquire a digital image ``f_\\\\textrm{D}(x_1',x_2')`` where\nthe light intensity is known only at a discrete set of locations. This\nmeans that the required partial derivatives are undefined and need to be\napproximated using discrete difference formulae [1].\n\nA straightforward way to approximate the partial derivatives is to use\ncentral-difference formulae\n```math\n \\\\frac{\\\\partial f_{\\\\textrm{D}}(x_1',x_2')}{\\\\partial x_1'}  \\\\approx\n        \\\\frac{f_{\\\\textrm{D}}(x_1'+1,x_2') - f_{\\\\textrm{D}}(x_1'-1,x_2') }{2}\n```\nand\n```math\n \\\\frac{\\\\partial f_{\\\\textrm{D}}(x_1',x_2')}{\\\\partial x_2'}   \\\\approx\n         \\\\frac{f_{\\\\textrm{D}}(x_1',x_2'+1) - f_{\\\\textrm{D}}(x_1',x_2'+1)}{2}.\n```\nHowever, the central-difference formulae are very sensitive to noise.\nWhen working with noisy image data,\none can obtain a better approximation of the partial\nderivatives by using a suitable weighted combination of the neighboring\nimage intensities. The weighted combination can be represented as a\n*discrete convolution* operation between the image and a\n*kernel* which characterizes the requisite weights. In particular,\nif ``h_{x_d}`` (``d = 1,2)`` represents a ``2r+1 \\\\times 2r+1`` kernel, then\n```math\n \\\\frac{\\\\partial f_{\\\\textrm{D}}(x_1',x_2')}{\\\\partial x_d'}  \\\\approx\n\\\\sum_{i = -r}^r \\\\sum_{j = -r}^r\nf_\\\\textrm{D}(x_1'-i,x_2'-j)\n  h_{x_d}(i,j).\n```\nThe kernel is frequently also called a *mask* or *convolution matrix*.\n\n### Weighting schemes and approximation error\n\nThe choice of weights determines the magnitude of the approximation\nerror and whether the finite-difference scheme is *isotropic*. A\nfinite-difference scheme is isotropic if the approximation error does\nnot depend on the orientation of the coordinate system and\n*anisotropic* if the approximation error has a directional bias [2].\nWith a continuous analogue image the magnitude of the gradient would be\ninvariant upon rotation of the coordinate system, but in practice one\ncannot obtain perfect isotropy with a finite set of discrete points.\nHence a finite-difference scheme is typically considered isotropic if\nthe leading error term in the approximation does not have preferred\ndirections.\n\n\nMost finite-difference schemes that are used in image processing are\nbased on ``3 \\\\times 3`` kernels, and as noted by [7], many can also be\nparametrized by a single parameter ``\\\\alpha`` as follows:\n\n```math\n\\\\mathbf{H}_{x_{1}} =\n\\\\frac{1}{4 + 2\\\\alpha}\n\\\\begin{bmatrix}\n-1 & -\\\\alpha & -1 \\\\\\\\\n0 & 0 & 0 \\\\\\\\\n 1 & \\\\alpha & 1\n\\\\end{bmatrix}\n\\\\quad\n\\\\text{and}\n\\\\quad\n\\\\mathbf{H}_{x_{2}} =\n\\\\frac{1}{2 + 4\\\\alpha}\n\\\\begin{bmatrix}\n-1 & 0 & 1 \\\\\\\\\n-\\\\alpha & 0 & \\\\alpha \\\\\\\\\n -1 & 0 & 1\n\\\\end{bmatrix},\n```\nwhere\n```math\n\\\\alpha =\n\\\\begin{cases}\n0,  & \\\\text{Simple Finite Difference}; \\\\\\\\\n1, &  \\\\text{Prewitt}; \\\\\\\\\n2, &  \\\\text{Sobel}; \\\\\\\\\n2.4351, &  \\\\text{Ando}; \\\\\\\\\n\\\\frac{10}{3}, &  \\\\text{Scharr}; \\\\\\\\\n4, &  \\\\text{Bickley}.\n\\\\end{cases}\n```\n\n## Separable kernel\n\nA kernel is called *separable* if it can be expressed as the\nconvolution of two one-dimensional filters. With a matrix representation\nof the kernel, separability means that the kernel matrix can be written\nas an outer product of two vectors. Separable kernels offer\ncomputational advantages since instead of performing a two-dimensional\nconvolution one can perform a sequence of one-dimensional convolutions.\n\n# Options\nYou can specify your choice of the finite-difference scheme via the `kernelfun`\nparameter. You can also indicate how to deal with the pixels on the border\nof the image with the `border` parameter.\n\n## Choices for `kernelfun`\nIn general `kernelfun` can be any function which satisfies the following\ninterface:\n```julia\n    kernelfun(extended::NTuple{N,Bool}, d) -> kern_d,\n```\nwhere `kern_d` is the kernel for producing the derivative with respect to\nthe ``d``th dimension of an ``N``-dimensional array. The parameter `extended[i]` is true\nif the image is of size > 1 along dimension ``i``. The parameter `kern_d` may be\nprovided as a dense or factored kernel, with factored representations\nrecommended when the kernel is separable.\n\nSome valid `kernelfun` options are described below.\n\n### `KernelFactors.prewitt`\n\nWith the *prewit* option [3] the computation of the gradient is based on\nthe kernels\n```math\n\\\\begin{aligned}\n\\\\mathbf{H}_{x_1} & = \\\\frac{1}{6}\n    \\\\begin{bmatrix}\n    -1 & -1 & -1 \\\\\\\\\n    0 & 0 & 0 \\\\\\\\\n    1 & 1 & 1\n    \\\\end{bmatrix}\n&\n\\\\mathbf{H}_{x_2} & =  \\\\frac{1}{6}\n    \\\\begin{bmatrix}\n    -1 & 0 & 1 \\\\\\\\\n    -1 & 0 & 1 \\\\\\\\\n    -1 & 0 & 1\n    \\\\end{bmatrix} \\\\\\\\\n& = \\\\frac{1}{6}\n    \\\\begin{bmatrix}\n    1 \\\\\\\\\n    1  \\\\\\\\\n    1\n    \\\\end{bmatrix}\n    \\\\begin{bmatrix}\n    -1 & 0 & 1\n    \\\\end{bmatrix}\n&\n& = \\\\frac{1}{6}\n    \\\\begin{bmatrix}\n    -1 \\\\\\\\\n    0  \\\\\\\\\n    1\n    \\\\end{bmatrix}\n    \\\\begin{bmatrix}\n    1 & 1 & 1\n    \\\\end{bmatrix}.\n\\\\end{aligned}\n```\nSee also: [`KernelFactors.prewitt`](@ref) and [`Kernel.prewitt`](@ref)\n\n### `KernelFactors.sobel`\n\nThe *sobel* option [4] designates the kernels\n```math\n\\\\begin{aligned}\n\\\\mathbf{H}_{x_1} & = \\\\frac{1}{8}\n    \\\\begin{bmatrix}\n    -1 & -2 & -1 \\\\\\\\\n     0 & 0 & 0 \\\\\\\\\n     1 & 2 & 1\n    \\\\end{bmatrix}\n&\n\\\\mathbf{H}_{x_2} & = \\\\frac{1}{8}\n    \\\\begin{bmatrix}\n    -1 & 0 & 1 \\\\\\\\\n    -2 & 0 & 2 \\\\\\\\\n    -1 & 0 & 1\n    \\\\end{bmatrix} \\\\\\\\\n& = \\\\frac{1}{8}\n    \\\\begin{bmatrix}\n    -1 \\\\\\\\\n    0  \\\\\\\\\n    1\n    \\\\end{bmatrix}\n    \\\\begin{bmatrix}\n    1 & 2 & 1\n    \\\\end{bmatrix}\n&\n& = \\\\frac{1}{8}\n    \\\\begin{bmatrix}\n    1 \\\\\\\\\n    2  \\\\\\\\\n    1\n    \\\\end{bmatrix}\n    \\\\begin{bmatrix}\n    -1 & 0 & 1\n    \\\\end{bmatrix}.\n\\\\end{aligned}\n```\nSee also:  [`KernelFactors.sobel`](@ref) and [`Kernel.sobel`](@ref)\n\n### `KernelFactors.ando3`\nThe *ando3* option [5] specifies the kernels\n```math\n\\\\begin{aligned}\n\\\\mathbf{H}_{x_1} &  =\n    \\\\begin{bmatrix}\n    -0.112737 & -0.274526 & -0.112737 \\\\\\\\\n     0 & 0 & 0 \\\\\\\\\n     0.112737 & 0.274526 & 0.112737\n    \\\\end{bmatrix}\n&\n\\\\mathbf{H}_{x_2}  & =\n    \\\\begin{bmatrix}\n    -0.112737 & 0 & 0.112737 \\\\\\\\\n    -0.274526 & 0 & 0.274526 \\\\\\\\\n    -0.112737 & 0 & 0.112737\n    \\\\end{bmatrix} \\\\\\\\\n&  = \\\\begin{bmatrix}\n    -1 \\\\\\\\\n    0  \\\\\\\\\n    1\n    \\\\end{bmatrix}\n    \\\\begin{bmatrix}\n    0.112737 & 0.274526 & 0.112737\n    \\\\end{bmatrix}\n&\n&  = \\\\begin{bmatrix}\n    0.112737 \\\\\\\\\n    0.274526  \\\\\\\\\n    0.112737\n    \\\\end{bmatrix}\n    \\\\begin{bmatrix}\n    -1 & 0 & 1\n    \\\\end{bmatrix}.\n\\\\end{aligned}\n```\nSee also:  [`KernelFactors.ando3`](@ref), and\n[`Kernel.ando3`](@ref);  [`KernelFactors.ando4`](@ref), and\n[`Kernel.ando4`](@ref); [`KernelFactors.ando5`](@ref), and\n[`Kernel.ando5`](@ref)\n\n### `KernelFactors.scharr`\n\nThe *scharr* option [6] designates the kernels\n```math\n\\\\begin{aligned}\n\\\\mathbf{H}_{x_{1}} & =\n\\\\frac{1}{32}\n\\\\begin{bmatrix}\n-3 & -10 & -3 \\\\\\\\\n0 & 0 & 0 \\\\\\\\\n 3 & 10 & 3\n\\\\end{bmatrix}\n&\n\\\\mathbf{H}_{x_{2}} & =\n\\\\frac{1}{32}\n\\\\begin{bmatrix}\n-3 & 0 & 3 \\\\\\\\\n-10 & 0 & 10\\\\\\\\\n-3 & 0 & 3\n\\\\end{bmatrix} \\\\\\\\\n& = \\\\frac{1}{32}\n\\\\begin{bmatrix}\n    -1 \\\\\\\\\n    0  \\\\\\\\\n    1\n\\\\end{bmatrix}\n\\\\begin{bmatrix}\n    3 & 10 & 3\n\\\\end{bmatrix}\n&\n& = \\\\frac{1}{32}\n\\\\begin{bmatrix}\n    3 \\\\\\\\\n    10  \\\\\\\\\n    3\n\\\\end{bmatrix}\n\\\\begin{bmatrix}\n    -1 & 0 & 1\n\\\\end{bmatrix}.\n\\\\end{aligned}\n```\nSee also:  [`KernelFactors.scharr`](@ref) and [`Kernel.scharr`](@ref)\n\n### `KernelFactors.bickley`\n\nThe *bickley* option [7,8] designates the kernels\n```math\n\\\\begin{aligned}\n\\\\mathbf{H}_{x_1} & = \\\\frac{1}{12}\n    \\\\begin{bmatrix}\n        -1 & -4 & -1 \\\\\\\\\n         0 & 0 & 0 \\\\\\\\\n         1 & 4 & 1\n    \\\\end{bmatrix}\n&\n\\\\mathbf{H}_{x_2} & = \\\\frac{1}{12}\n    \\\\begin{bmatrix}\n        -1 & 0 & 1 \\\\\\\\\n        -4 & 0 & 4 \\\\\\\\\n        -1 & 0 & 1\n    \\\\end{bmatrix} \\\\\\\\\n& = \\\\frac{1}{12}\n    \\\\begin{bmatrix}\n        -1 \\\\\\\\\n        0  \\\\\\\\\n        1\n    \\\\end{bmatrix}\n    \\\\begin{bmatrix}\n        1 & 4 & 1\n    \\\\end{bmatrix}\n&\n&  = \\\\frac{1}{12}\n   \\\\begin{bmatrix}\n        1 \\\\\\\\\n        4  \\\\\\\\\n        1\n   \\\\end{bmatrix}\n   \\\\begin{bmatrix}\n        -1 & 0 & 1\n   \\\\end{bmatrix}.\n\\\\end{aligned}\n```\nSee also:  [`KernelFactors.bickley`](@ref) and [`Kernel.bickley`](@ref)\n\n## Choices for `border`\nAt the image edge, `border` is used to specify the padding which will be used\nto extrapolate the image beyond its original bounds. As an indicative example\nof each option the results of the padding are illustrated on an image consisting of\na row of six pixels which are specified alphabetically: ``\\\\boxed{a \\\\, b \\\\, c \\\\, d \\\\, e \\\\, f}``.\nWe show the effects of padding only on the left and right border, but analogous\nconsequences hold for the top and bottom border.\n\n### `\"replicate\"`\n\nThe border pixels extend beyond the image boundaries.\n```math\n\\\\boxed{\n\\\\begin{array}{l|c|r}\n  a\\\\, a\\\\, a\\\\, a  &  a \\\\, b \\\\, c \\\\, d \\\\, e \\\\, f & f \\\\, f \\\\, f \\\\, f\n\\\\end{array}\n}\n```\nSee also: [`Pad`](@ref), [`padarray`](@ref), [`Inner`](@ref) and\n[`NoPad`](@ref)\n\n### `\"circular\"`\n\nThe border pixels wrap around. For instance, indexing beyond the left border\nreturns values starting from the right border.\n```math\n\\\\boxed{\n\\\\begin{array}{l|c|r}\n  c\\\\, d\\\\, e\\\\, f  &  a \\\\, b \\\\, c \\\\, d \\\\, e \\\\, f & a \\\\, b \\\\, c \\\\, d\n\\\\end{array}\n}\n```\nSee also: [`Pad`](@ref), [`padarray`](@ref), [`Inner`](@ref) and\n[`NoPad`](@ref)\n\n### `\"symmetric\"`\nThe border pixels reflect relative to a position between pixels. That is, the\nborder pixel is omitted when mirroring.\n```math\n\\\\boxed{\n\\\\begin{array}{l|c|r}\n  e\\\\, d\\\\, c\\\\, b  &  a \\\\, b \\\\, c \\\\, d \\\\, e \\\\, f & e \\\\, d \\\\, c \\\\, b\n\\\\end{array}\n}\n```\nSee also: [`Pad`](@ref), [`padarray`](@ref), [`Inner`](@ref) and\n[`NoPad`](@ref)\n\n### `\"reflect\"`\nThe border pixels reflect relative to the edge itself.\n```math\n\\\\boxed{\n\\\\begin{array}{l|c|r}\n  d\\\\, c\\\\, b\\\\, a  &  a \\\\, b \\\\, c \\\\, d \\\\, e \\\\, f & f \\\\, e \\\\, d \\\\, c\n\\\\end{array}\n}\n```\nSee also: [`Pad`](@ref), [`padarray`](@ref), [`Inner`](@ref) and\n[`NoPad`](@ref)\n\n# Example\n\nThis example compares the quality of the gradient estimation methods in terms of\nthe accuracy with which the orientation of the gradient is estimated.\n\n```julia\nusing Images\n\nvalues = LinRange(-1,1,128);\nw = 1.6*pi;\n\n# Define a function of a sinusoidal grating, f(x,y) = sin( (w*x)^2 + (w*y)^2 ),\n# together with its exact partial derivatives.\nI = [sin( (w*x)^2 + (w*y)^2 ) for y in values, x in values];\nIx = [2*w*x*cos( (w*x)^2 + (w*y)^2 ) for y in values, x in values];\nIy = [2*w*y*cos( (w*x)^2 + (w*y)^2 ) for y in values, x in values];\n\n# Determine the exact orientation of the gradients.\ndirection_true = atan.(Iy./Ix);\n\nfor kernelfunc in (KernelFactors.prewitt, KernelFactors.sobel,\n                   KernelFactors.ando3, KernelFactors.scharr,\n                   KernelFactors.bickley)\n\n    # Estimate the gradients and their orientations.\n    Gy, Gx = imgradients(I,kernelfunc, \"replicate\");\n    direction_estimated = atan.(Gy./Gx);\n\n    # Determine the mean absolute deviation between the estimated and true\n    # orientation. Ignore the values at the border since we expect them to be\n    # erroneous.\n    error = mean(abs.(direction_true[2:end-1,2:end-1] -\n                     direction_estimated[2:end-1,2:end-1]));\n\n    error = round(error, digits=5);\n    println(\"Using \\$kernelfunc results in a mean absolute deviation of \\$error\")\nend\n\n# output\n\nUsing ImageFiltering.KernelFactors.prewitt results in a mean absolute deviation of 0.01069\nUsing ImageFiltering.KernelFactors.sobel results in a mean absolute deviation of 0.00522\nUsing ImageFiltering.KernelFactors.ando3 results in a mean absolute deviation of 0.00365\nUsing ImageFiltering.KernelFactors.scharr results in a mean absolute deviation of 0.00126\nUsing ImageFiltering.KernelFactors.bickley results in a mean absolute deviation of 0.00038\n```\n# References\n  1. B. Jahne, *Digital Image Processing* (5th ed.). Springer Publishing Company, Incorporated, 2005. [10.1007/3-540-27563-0](https://doi.org/10.1007/3-540-27563-0)\n  2. M. Patra  and  M. Karttunen, \"Stencils with isotropic discretization error for differential operators,\" *Numer. Methods Partial Differential Eq.*, vol. 22, pp. 936–953, 2006. [doi:10.1002/num.20129](https://doi.org/doi:10.1002/num.20129)\n  3. J. M. Prewitt, \"Object enhancement and extraction,\" *Picture processing and Psychopictorics*, vol. 10, no. 1, pp. 15–19, 1970.\n  4. P.-E. Danielsson and O. Seger, \"Generalized and separable sobel operators,\" in  *Machine Vision for Three-Dimensional Scenes*,  H. Freeman, Ed.  Academic Press, 1990,  pp. 347–379. [doi:10.1016/b978-0-12-266722-0.50016-6](https://doi.org/doi:10.1016/b978-0-12-266722-0.50016-6)\n  5. S. Ando, \"Consistent gradient operators,\" *IEEE Transactions on Pattern Analysis and Machine Intelligence*, vol. 22, no.3, pp. 252–265, 2000. [doi:10.1109/34.841757](https://doi.org/doi:10.1109/34.841757)\n  6. H. Scharr and  J. Weickert, \"An anisotropic diffusion algorithm with optimized rotation invariance,\" *Mustererkennung 2000*, pp. 460–467, 2000. [doi:10.1007/978-3-642-59802-9_58](https://doi.org/doi:10.1007/978-3-642-59802-9_58)\n  7. A. Belyaev, \"Implicit image differentiation and filtering with applications to image sharpening,\" *SIAM Journal on Imaging Sciences*, vol. 6, no. 1, pp. 660–679, 2013. [doi:10.1137/12087092x](https://doi.org/doi:10.1137/12087092x)\n  8. W. G. Bickley, \"Finite difference formulae for the square lattice,\" *The Quarterly Journal of Mechanics and Applied Mathematics*, vol. 1, no. 1, pp. 35–42, 1948.  [doi:10.1093/qjmam/1.1.35](https://doi.org/doi:10.1093/qjmam/1.1.35)\n\n***\n\n\"\"\"\nfunction imgradients(img::AbstractArray, kernelfun::Function, border=\"replicate\")\n    extended = map(isextended, axes(img))\n    _imgradients(extended, img, kernelfun, extended, border)\nend\n\nisextended(ind) = length(ind) > 1\n\n# Add the next dimension to G\nfunction _imgradients(donewhenempty::NTuple{M}, img::AbstractArray{T,N}, kernelfun::Function, extended, border) where {T,M,N}\n    d = N-M+1  # the dimension we're working on now\n    kern = kernelfun(extended, d)\n    return (imfilter(img, kern, border), _imgradients(Base.tail(donewhenempty), img, kernelfun, extended, border)...)\nend\n# When all N gradients have been calculated, return the result\n_imgradients(::Tuple{}, img::AbstractArray, kernelfun::Function, extent, border) = ()\n", "meta": {"hexsha": "09ed1632f8e24e6fbc7df03b95ae008f72b18230", "size": 16472, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/specialty.jl", "max_stars_repo_name": "elronayellin/ImageFiltering.jl", "max_stars_repo_head_hexsha": "8c9f1739a4c1e39a8cffb7aef5fedcb888bc3375", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/specialty.jl", "max_issues_repo_name": "elronayellin/ImageFiltering.jl", "max_issues_repo_head_hexsha": "8c9f1739a4c1e39a8cffb7aef5fedcb888bc3375", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-01-24T02:25:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-26T20:21:55.000Z", "max_forks_repo_path": "src/specialty.jl", "max_forks_repo_name": "elronayellin/ImageFiltering.jl", "max_forks_repo_head_hexsha": "8c9f1739a4c1e39a8cffb7aef5fedcb888bc3375", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9844660194, "max_line_length": 282, "alphanum_fraction": 0.6379310345, "num_tokens": 5655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8652240930029117, "lm_q1q2_score": 0.7838842271997981}}
{"text": "using ApproxFun\n\n###\n# Fractional Derivative\n###\n\nS = Legendre()\n\nn = 50; # number of data points\np = range(-1,stop=1,length=n);   # a non-default grid\n\nv = exp.(p);           # values at the non-default grid\nm = 20   # number of basis functions\nV = Array{Float64}(undef,n,m); # Create a Vandermonde matrix by evaluating the basis at the grid\nfor k = 1:size(V,2)\n   V[:,k] = Fun(S,[zeros(k-1);1]).(p)\nend\nf = Fun(S,V\\v); # least squares fit to data\n\nf_rl = LeftDerivative(0.5)*f # RL left half-derivative\nf_cap = LeftIntegral(0.5)*Fun(f', S) # Caputo left half-derivative\n\n\nusing Plots\nplot(f_rl;ylims=(0,3),legend=:bottomright,label=\"RL\")\nplot!(f_cap; label=\"Caputo\")\nsavefig(\"RLvCaputo.png\")\n", "meta": {"hexsha": "265bea31660af6d4557f18e642ec6f8de6d33ab6", "size": 694, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Extras/Fractional derivatives.jl", "max_stars_repo_name": "putianyi889/ApproxFunExamples", "max_stars_repo_head_hexsha": "b519a2b2a197607561028fea53a327493bfb344e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2018-06-01T04:19:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T10:15:11.000Z", "max_issues_repo_path": "Extras/Fractional derivatives.jl", "max_issues_repo_name": "putianyi889/ApproxFunExamples", "max_issues_repo_head_hexsha": "b519a2b2a197607561028fea53a327493bfb344e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-03-27T09:32:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-30T08:52:42.000Z", "max_forks_repo_path": "Extras/Fractional derivatives.jl", "max_forks_repo_name": "putianyi889/ApproxFunExamples", "max_forks_repo_head_hexsha": "b519a2b2a197607561028fea53a327493bfb344e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-07-25T00:08:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T12:38:42.000Z", "avg_line_length": 24.7857142857, "max_line_length": 96, "alphanum_fraction": 0.6628242075, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9615338068793908, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7838735946619904}}
{"text": "using Random, CSV, Distributions, Plots; pyplot()\nRandom.seed!(0)\n\nsampleData = CSV.read(\"../data/machine1.csv\", header=false)[:,1]\nn, N = length(sampleData), 10^6\nalpha = 0.1\n\nbootstrapSampleMeans = [mean(rand(sampleData, n)) for i in 1:N]\nLmean = quantile(bootstrapSampleMeans, alpha/2)\nUmean = quantile(bootstrapSampleMeans, 1-alpha/2)\n\nbootstrapSampleMedians = [median(rand(sampleData, n)) for i in 1:N]\nLmed = quantile(bootstrapSampleMedians, alpha/2)\nUmed = quantile(bootstrapSampleMedians, 1-alpha/2)\n\nprintln(\"Bootstrap confidence interval for the mean: \", (Lmean, Umean) )\nprintln(\"Bootstrap confidence interval for the median: \", (Lmed, Umed) )\n\nstephist(bootstrapSampleMeans, bins=1000, c=:blue,\n    normed=true, label=\"Sample \\nmeans\")\nplot!([Lmean, Lmean],[0,2], c=:black, ls=:dash, label=\"90% CI\")\nplot!([Umean, Umean],[0,2],c=:black, ls=:dash, label=\"\",\n    xlims=(52,54), ylims=(0,2), xlabel=\"Sample Means\", ylabel=\"Density\")", "meta": {"hexsha": "394cc1dbece6f2ad529ebdb593ab4da8dd17cd17", "size": 941, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "6_chapter/bCI.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "6_chapter/bCI.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "6_chapter/bCI.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 40.9130434783, "max_line_length": 72, "alphanum_fraction": 0.7130712009, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214532237355, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.783865395401013}}
{"text": "export Fourier\n\nstruct Fourier <: AbstractMethod\n    \n    kx   :: Vector{Float64}\n    kv   :: Vector{Float64}\n\n    function Fourier( meshx, meshv )\n    \n        nx  = meshx.len\n        dx  = meshx.step\n        Lx  = meshx.stop - meshx.start\n        kx  = 2π/Lx .* [0:nx÷2-1;-nx÷2:-1]\n\n        nv  = meshv.len\n        dv  = meshv.step\n        Lv  = meshv.stop - meshv.start\n        kv  = 2π/Lv .* [0:nv÷2-1;-nv÷2:-1]\n\n        new( kx, kv)\n\n    end\n  \nend\n\n\nfunction advection_v!(fᵗ  :: Array{ComplexF64,2}, \n                      adv :: Fourier,\n\t\t      e   :: Vector{ComplexF64}, \n\t\t      dt  :: Float64 )\n    fft!(fᵗ, 1)\n    @. fᵗ *= exp(-1im * dt * adv.kv * $transpose(e))\n    ifft!(fᵗ, 1)\n\nend\n\nfunction advection_x!( f   :: Array{ComplexF64,2}, \n                       adv :: Fourier,\n\t\t       e   :: Vector{ComplexF64}, \n\t\t       v   :: Vector{Float64}, \n\t\t       dt  :: Float64 )\n    \n    ev = exp.(-1im*dt * adv.kx * transpose(v))    \n    \n    fft!(f,1)\n    f .= f .* ev\n    dv = v[2]-v[1]\n    ρ = dv * vec(sum(f,dims=2))  \n    for i in 2:length(e)\n        e[i] = -1im * ρ[i] ./ adv.kx[i]\n    end\n    e[1] = 0.0\n    ifft!(f,1)\n    ifft!(e)\n    e .= real(e)\nend\n\n\n", "meta": {"hexsha": "ed6ccbab0ffb709412ba4750d0cc8715ab616f24", "size": 1170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fourier.jl", "max_stars_repo_name": "JuliaVlasov/VlasovSolvers", "max_stars_repo_head_hexsha": "0cefcf2438bdd5c47effe66ea1e78903da75ee79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-12-08T20:06:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T11:03:25.000Z", "max_issues_repo_path": "src/fourier.jl", "max_issues_repo_name": "JuliaVlasov/VlasovSolvers", "max_issues_repo_head_hexsha": "0cefcf2438bdd5c47effe66ea1e78903da75ee79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-03-24T14:53:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-15T07:57:24.000Z", "max_forks_repo_path": "src/fourier.jl", "max_forks_repo_name": "JuliaVlasov/VlasovSolvers", "max_forks_repo_head_hexsha": "0cefcf2438bdd5c47effe66ea1e78903da75ee79", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T20:32:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T13:20:12.000Z", "avg_line_length": 19.8305084746, "max_line_length": 52, "alphanum_fraction": 0.4538461538, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214460461698, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7838653939382126}}
{"text": "CARDPK = 1526110\nDOORPK = 20175123\n\nSUBJECT = 7\nSALT = 20201227\n\nfunction find_loop_size(pk, subject)\n    i = 0\n    n = 1\n    while n != pk\n        i += 1\n        n *= subject\n        n = mod(n, SALT)\n    end\n    return i\nend\n\nfunction enc(subject, loops)\n    n = 1\n    for _ in 1:loops\n        n *= subject\n        n = mod(n, SALT)\n    end\n    return n\nend\n\ncard = find_loop_size(CARDPK, SUBJECT)\ndoor = find_loop_size(DOORPK, SUBJECT)\np1 = enc(DOORPK, card)\n\nprintln(\"-----------------------------------------------------------------------\")\nprintln(\"combo breaker -- part one :: $p1\")\nprintln(\"-----------------------------------------------------------------------\")\n\n@assert(p1 == 10924063)", "meta": {"hexsha": "e1550d115d2d2c44c3b53d07db6282e38817ce6b", "size": 695, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "bin/twentyfive/run.jl", "max_stars_repo_name": "talentdeficit/aoc2020", "max_stars_repo_head_hexsha": "1bdc06f7428c8e8c59a2748fbd1c2fa0e04e67c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bin/twentyfive/run.jl", "max_issues_repo_name": "talentdeficit/aoc2020", "max_issues_repo_head_hexsha": "1bdc06f7428c8e8c59a2748fbd1c2fa0e04e67c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bin/twentyfive/run.jl", "max_forks_repo_name": "talentdeficit/aoc2020", "max_forks_repo_head_hexsha": "1bdc06f7428c8e8c59a2748fbd1c2fa0e04e67c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8571428571, "max_line_length": 82, "alphanum_fraction": 0.4661870504, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321452198369, "lm_q2_score": 0.8128673155708976, "lm_q1q2_score": 0.7838653901959178}}
{"text": "\"\"\"\n    scale(a::Polynomial,ρ::Number)\n\nScale the univariate polynomial `a` with the variable `s` given by ``a(s) = a₀ + a₁ s + a₂ s² + … + aₙ sⁿ`` by the scalar positive real number `ρ`. This amounts to replacing the original variable `s` with a new scaled variable `ρs`.\n\n# Examples\n\n```julia\njulia> a = Polynomial(1:5,:s)\njulia> ρ=10\njulia> scale(a,ρ)\nPolynomial(1 + 20*s + 300*s^2 + 4000*s^3 + 50000*s^4)\n```\n\"\"\"\nfunction scale(a::Polynomial,ρ::Number)\n    c = deepcopy(coeffs(a))     # coefficent vector of the original polynomial\n    for k=1:degree(a)           # k is the power to which s is raised in s^k\n        c[k+1] *= ρ^k           # coefficient vector of the new scaled polynomial\n    end\n    p = Polynomial(c,a.var)     # converting the coefficient vector to a polynomial\nend\n\n\"\"\"\n    cconj(a::Polynomial)\n\nReturn the conjugate of a given univariate polynomial `a` given by ``a(s) = a₀ + a₁ s + a₂ s² + … + aₙ sⁿ`` with respect to the imaginary axis, that is, return the polynomial ``ã(s) = ̄ā(-s)=ā₀ - ̄ā₁s + ā₂ s² + … ± ̄āₙ sⁿ``.\n\nIt is used in the analysis and synthesis of continuous-time filters and controllers. This is reflected in prepending the letter `c` to the `conj` function name.\n\n# Examples\n\n```julia\njulia> a = Polynomial(1:5,:s)\nPolynomial(1 + 2*s + 3*s^2 + 4*s^3 + 5*s^4)\n\njulia> p = cconj(a)\nPolynomial(1 - 2*s + 3*s^2 - 4*s^3 + 5*s^4)\n\njulia> a = Polynomial([1+1im, 2+2im, 3+3im, 4+4im, 5+5im],:s)\nPolynomial((1 + 1im) + (2 + 2im)*s + (3 + 3im)*s^2 + (4 + 4im)*s^3 + (5 + 5im)*s^4)\n\njulia> p = cconj(a)\nPolynomial((1 - 1im) - (2 - 2im)*s + (3 - 3im)*s^2 - (4 - 4im)*s^3 + (5 - 5im)*s^4)\n```\n\"\"\"\nfunction cconj(a::Polynomial)\n    c = conj(a)\n    cc = deepcopy(coeffs(c))\n    cc[2:2:end] = -cc[2:2:end]\n    return Polynomial(cc,a.var)\nend\n\n\"\"\"\n    conjreciprocal(a::Polynomial)\n\nReturn the conjugate reciprocal polynomial for a given polynomial `a`.\n\nFof a polynomial ``a(s) = a₀ + a₁ s + a₂ s² + … + aₙ sⁿ``, return the polynomial ``r(s) = ̄āₙ + ̄āₙ₋₁ s + ̄āₙ₋₂ s² + … + ̄ā₀ sⁿ``.\n\n# Examples\n\n```julia\njulia> a = Polynomial(1:5,:s)\nPolynomial(1 + 2*s + 3*s^2 + 4*s^3 + 5*s^4)\n\njulia> p = conjreciprocal(a)\nPolynomial(5 + 4*s + 3*s^2 + 2*s^3 + s^4)\n\njulia> c = Polynomial([1+1im, 2+2im, 3+3im, 4+4im, 5+5im],:s)\nPolynomial((1 + 1im) + (2 + 2im)*s + (3 + 3im)*s^2 + (4 + 4im)*s^3 + (5 + 5im)*s^4)\n\njulia> p = conjreciprocal(c)\nPolynomial((5 - 5im) + (4 - 4im)*s + (3 - 3im)*s^2 + (2 - 2im)*s^3 + (1 - 1im)*s^4)\n```\n\"\"\"\nfunction conjreciprocal(a::Polynomial)\n    c = conj(a)\n    cc = deepcopy(coeffs(c))\n    pc = cc[end:-1:1]\n    p = Polynomial(pc,a.var)\nend\n\n\"\"\"\n    dconj(a::LaurentPolynomial)\n\nReturn the conjugate polynomial for a given polynomial ``a(z) = a₀ + a₁ z + a₂ z² + ... + aₙ zⁿ`` with respect to the unit circle in the complex plane, that is, return the Laurent polynomial ``ã(z) = āₙ z⁻ⁿ + āₙ₋₁ z⁻ⁿ⁺¹ + āₙ₋₂ z⁻ⁿ⁺² + … + ā₀``.\n\nThe function is only defined for `LaurentPolynomial` type even if it is used to represent a standard polynomial (with no negative powers).\n\nIt is used in the analysis and synthesis of discrete-time filters and controllers. This is reflected in prepending the letter `d` to the `conj` function name.\n\n# Examples\n\n```julia\njulia> a = LaurentPolynomial(1:5,:z)\nLaurentPolynomial(1 + 2*z + 3*z² + 4*z³ + 5*z⁴)\n\njulia> p = dconj(a)\nLaurentPolynomial(5*z⁻⁴ + 4*z⁻³ + 3*z⁻² + 2*z⁻¹ + 1)\n\njulia> c = LaurentPolynomial([1+1im, 2+2im, 3+3im, 4+4im, 5+5im],:z)\nLaurentPolynomial((1 + 1im) + (2 + 2im)*z + (3 + 3im)*z² + (4 + 4im)*z³ + (5 + 5im)*z⁴)\n\njulia> p = dconj(c)\nLaurentPolynomial((5 - 5im)*z⁻⁴ + (4 - 4im)*z⁻³ + (3 - 3im)*z⁻² + (2 - 2im)*z⁻¹ + (1 - 1im))\n```\n\"\"\"\nfunction dconj(a::LaurentPolynomial)\n    ac = deepcopy(coeffs(a))\n    dc = conj.(ac[end:-1:1])             # flipping and conjugating the coeffs\n    fr = -a.n[]:-a.m[]                   # flipping and negating the range\n    d = LaurentPolynomial(dc,fr,a.var)\nend\n\n\"\"\"\n    shift(p::LaurentPolynomial[,k::Integer=1])\n\nIncrease the powers of the variable in the Laurent polynomial by 1 or a given (possibly negative) number.\n\nFor a univariate Laurent polynomial `p(z) = pₘ zᵐ + p₋₁ z⁻¹ +  p₀ + p₁ z + … + pₙ zⁿ` and a given integer `k`, return a Laurent polynomial  `p(z) = pₘ zᵐ⁺ᵏ + p₋₁ z⁻¹⁺ᵏ +  p₀ zᵏ + p₁ zᵏ⁺¹ + … + pₙ zⁿ⁺ᵏ`. If `k` is not specified, it is assumed that `k=1`.\n\n# Examples\n\n```julia\njulia> p = LaurentPolynomial([1,2,3,4],-2:1,:z)\nLaurentPolynomial(z⁻² + 2*z⁻¹ + 3 + 4*z)\n\njulia> shift(p)\nLaurentPolynomial(z⁻¹ + 2 + 3*z + 4*z²)\n\njulia> shift(p,-3)\nLaurentPolynomial(z⁻⁵ + 2*z⁻⁴ + 3*z⁻³ + 4*z⁻²)\n```\n\"\"\"\nfunction shift(p::LaurentPolynomial,k::Integer=1)\n    r = range(p)\n    s = LaurentPolynomial(coeffs(p),r.+k,p.var)\n    return s\nend\n", "meta": {"hexsha": "06e10af6bf14b9946fc722452112a9d8ae219753", "size": 4702, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transformations.jl", "max_stars_repo_name": "hurak/PolynomialEquations.jl", "max_stars_repo_head_hexsha": "e04d78a110a6c221ce34a1257a74b4ba9e71f255", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-27T20:38:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T08:59:25.000Z", "max_issues_repo_path": "src/transformations.jl", "max_issues_repo_name": "hurak/PolynomialEquations.jl", "max_issues_repo_head_hexsha": "e04d78a110a6c221ce34a1257a74b4ba9e71f255", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/transformations.jl", "max_forks_repo_name": "hurak/PolynomialEquations.jl", "max_forks_repo_head_hexsha": "e04d78a110a6c221ce34a1257a74b4ba9e71f255", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-27T20:38:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T20:38:33.000Z", "avg_line_length": 33.5857142857, "max_line_length": 253, "alphanum_fraction": 0.6122926414, "num_tokens": 1938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8933094074745443, "lm_q1q2_score": 0.7838582748225494}}
{"text": "function tophat(x,p)   #first function evaluates the vector input x at parameter p\n    return exp.(-x.^p)\nend\nfunction dtophat(x,p)  #second function is the derivative\n\treturn -p* (x.^(p-1)) .* exp.(-x.^p)\nend\nfunction tophat() #third function, with no input arguments, gives the default range of parameters p\n\treturn [1.1 5;]\nend\n\nfunction gaussian(x) \n\treturn exp.(-x.^2)\nend\nfunction gaussian()\n\treturn []\nend\nfunction dgaussian(x) \n\treturn -2*x .* exp.(-x.^2)\nend\n\nfunction cubic(x)\n\treturn x.^3\nend\nfunction cubic()\n\treturn []\nend\nfunction dcubic(x)\n\treturn 3 .* x.^2\nend\n\nfunction quintic(x)\n\treturn x.^5\nend\nfunction quintic()\n\treturn []\nend\nfunction dquintic(x)\n\treturn 5 .* x.^4\nend\n\nfunction wavelet(x)\n\treturn (2*x.^2-1) .* exp.(-x.^2)\nend\nfunction wavelet()\n\treturn []\nend\nfunction dwavelet(x)\n\treturn (2*x.*(3-2*x.^2)) .* exp.(-x.^2)\nend\n\nfunction sigmoid(x)\n\treturn tanh.( x )\nend\nfunction sigmoid()\n\treturn []\nend\nfunction dsigmoid(x)\n\treturn (1-tanh.( x ).^2)\nend\n\nfunction morlet(x,p)\n\treturn cos.(2*pi*x) .* exp.(-(2*(pi/p)^2)*x.^2) .- exp.(-p^2/2-(2*(pi/p)^2)*x.^2)\nend\nfunction morlet()\n\treturn [1 9;]\nend\nfunction dmorlet(x,p)\n\treturn -2*(pi.*sin(2*pi*x) .+ 2*((pi/p)^2)*x.*cos.(2*pi*x)) .* exp(-(2*(pi/p)^2)*x.^2) .+ (4*((pi/p)^2)*x) .* exp.(-p^2/2-(2*(pi/p)^2)*x.^2)\nend\n\n\n\n\n\n", "meta": {"hexsha": "951741829097e87bb311320b918be431c6a7f1fd", "size": 1299, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "BasisFunctionTypes.jl", "max_stars_repo_name": "m-small/place", "max_stars_repo_head_hexsha": "98a0bc1ffc8e89cc94787b49ac6345bed53b7eb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-07-14T07:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-22T05:04:02.000Z", "max_issues_repo_path": "BasisFunctionTypes.jl", "max_issues_repo_name": "m-small/place", "max_issues_repo_head_hexsha": "98a0bc1ffc8e89cc94787b49ac6345bed53b7eb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BasisFunctionTypes.jl", "max_forks_repo_name": "m-small/place", "max_forks_repo_head_hexsha": "98a0bc1ffc8e89cc94787b49ac6345bed53b7eb1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.32, "max_line_length": 141, "alphanum_fraction": 0.6304849885, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545392102523, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7838505482629815}}
{"text": "using Plots\n\nabstract type DescentMethod end\n\n\nstruct GradientDescent <: DescentMethod\n    α\nend\n\n# init! function does nothing.\ninit!(M::GradientDescent, f, ∇f, x) = M;\n\nfunction step!(M::GradientDescent, f, ∇f, x)\n    α, g = M.α, ∇f(x);\n    return x - α*g;\nend\n\n# test\n\nA = rand(2, 2);\nb = rand(2);\nc = rand(2);\nx = rand(2);\n\n\nf = (x) -> 1/2 * x'*A*x + b'*x .+ c\n∇f = (x) -> 1/2 * (A + A') * x + b\n\n\np = contour(-10:0.1:10, -10:0.1:10, (x, y)->sum(f([x, y])))\nscatter!(p, [x[1]], [x[2]])\n\nm = GradientDescent(0.5);\ninit!(m, f, ∇f, x);\nx_res = [];\ny_res = [];\n\nfor i in 1:100\n    x = step!(m, f, ∇f, x)\n    push!(x_res, [x[1]])\n    push!(y_res, [x[2]])\nend\n\nx_res\ny_res\n\nscatter!(p, x_res, y_res)\n\nx_res\ny_res\n\n\n\n", "meta": {"hexsha": "e6b34d8e54c368136440c084958686d192072f73", "size": 714, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "first-order-methods/5.1-gradient_descent.jl", "max_stars_repo_name": "tor4z/convex_optimization", "max_stars_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "first-order-methods/5.1-gradient_descent.jl", "max_issues_repo_name": "tor4z/convex_optimization", "max_issues_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "first-order-methods/5.1-gradient_descent.jl", "max_forks_repo_name": "tor4z/convex_optimization", "max_forks_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.2222222222, "max_line_length": 59, "alphanum_fraction": 0.5280112045, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545392102522, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7838505340945942}}
{"text": "\nfunction l1_norm(a)\n    return reduce(+, map(x-> abs(x),a))\nend\n\nfunction l2_norm(a)\n    return sqrt(reduce(+, map(x -> x^2,a)))\nend\n\nfunction lp_norm(a,power)\n    return (reduce(+, map(x -> abs(x)^power,a)))^(1/power)\nend\n", "meta": {"hexsha": "c2217198b930828e910bfcd333d38466cc89d16c", "size": 224, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stats.jl", "max_stars_repo_name": "matthewmacleod/Adapt.jl", "max_stars_repo_head_hexsha": "4f01e1e0bf1a45d97ea6c2765b966fc6e13d4c4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stats.jl", "max_issues_repo_name": "matthewmacleod/Adapt.jl", "max_issues_repo_head_hexsha": "4f01e1e0bf1a45d97ea6c2765b966fc6e13d4c4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stats.jl", "max_forks_repo_name": "matthewmacleod/Adapt.jl", "max_forks_repo_head_hexsha": "4f01e1e0bf1a45d97ea6c2765b966fc6e13d4c4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.2307692308, "max_line_length": 58, "alphanum_fraction": 0.6160714286, "num_tokens": 73, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7838505280388971}}
{"text": "using LinearAlgebra\n\n\"\"\"\nA kernel function takes two vectors and calculates\nthe distance between them.\n\"\"\"\nabstract type Kernel end\n\n\"\"\"\n    SquaredExponentialKernel(l, σf, σy)\n\nSquared exponential kernel for noisy observations.\nThe parameter names follow (15.20) in MLAPP. \n\n# Parameters\n- `l`: length scale, which controls the horizontal scale. \n      It can be in either of the forms\n   1. `Float64`: each dimension will have the same length scale\n   2. `Vector{Float64}`: length scale for each dimension.\n- `σf`: vertical scale \n- `σy`: observation noise\n\"\"\"\nmutable struct SquaredExponentialKernel <: Kernel \n    l::Float64\n    σf::Float64\n    σy::Float64\nend\n\nfunction (kernel::SquaredExponentialKernel)(xp, xq, δpq)\n    σf = kernel.σf\n    σy = kernel.σy\n    M = lengthscalematrix(kernel.l, length(xp))\n    return σf^2 * exp(-0.5 * (xp - xq)' * M * (xp - xq)) + σy^2*δpq\nend\n\nlengthscalematrix(l::Float64, dimensionsize) = Diagonal(ones(dimensionsize)) / l^2\n\n\"\"\"\n    MixtureKernel(X, p, q)\n\nA kernel mixture of Gaussian kernel and dot product.\nThe definition follows (6.63) in PRML.\n\"\"\"\nmutable struct MixtureKernel <: Kernel\n    sekernel::SquaredExponentialKernel\n    θ0::Float64\n    θ1::Float64\n\n    function MixtureKernel(l, σf, σy, θ0, θ1)\n        sekernel = SquaredExponentialKernel(l, σf, σy)\n        new(sekernel, θ0, θ1)\n    end\n\nend\n\nfunction (kernel::MixtureKernel)(xp, xq, δpq)\n    sekernel = kernel.sekernel\n    θ0 = kernel.θ0\n    θ1 = kernel.θ1\n    return sekernel(xp, xq, δpq) + θ0 + θ1 * (xp' * xq)\nend\n\nfunction (kernel::Kernel)(inputtuple::Tuple)\n    kernel(inputtuple...)\nend\n\n\"\"\"\n    covarianceblock(kernel, X, Xs)\n\nConstruct covariance matrix between `X` and `Xs` based on\nkernel function.\n\n# Parameters\n\n- `kernel`: kernel function.\n- `X`: input matrix ``X``.\n- `Xs`: another input matrix ``X_*`` (X-star).\n- `addnoise`: if `true`, when building a covariance matrix, we add \n      observation noise to the diagonal term.\n\"\"\"\nfunction covarianceblock(kernel, X, Xs; addnoise=false)\n    N = size(X, 1)\n    Ns = size(Xs, 1)\n    K = zeros(N, Ns)\n    for p in 1:N, q in 1:Ns\n        xp = X[p, :]\n        xq = Xs[q, :]\n        if addnoise\n            K[p, q] = kernel(xp, xq, p==q) \n        else\n            K[p, q] = kernel(xp, xq, false)\n        end\n    end\n    K\nend\n\nfunction covariancematrix(kernel, X; addnoise=true)\n    covarianceblock(kernel, X, X, addnoise=addnoise)\nend\n\n\"\"\"\nBecause inside squared exponential kernel we need Euclidean distance,\nwe can use the shortcut for it following (14.30). This can significantly \nreduce the computational cost.\n\"\"\"\nfunction covariancematrix(kernel::SquaredExponentialKernel, X)\n    l, σf, σy = kernel.l, kernel.σf, kernel.σy\n    N = size(X, 1)\n    euclideandist = X.^2 .+ (X.^2)' .- 2*X*X'\n    return σf^2 * exp.(-0.5/l^2 .* euclideandist) + Diagonal(fill(σy^2, N))\nend\n", "meta": {"hexsha": "a5886a1c6096efcaa60092f114b8a20c2770114b", "size": 2841, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels.jl", "max_stars_repo_name": "Jetafull/AlgorithmsInJulia", "max_stars_repo_head_hexsha": "6e4d8a58e063861967de9260f15d182eb7d35ada", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-21T03:27:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T03:27:23.000Z", "max_issues_repo_path": "src/kernels.jl", "max_issues_repo_name": "Jetafull/algorithms-in-julia", "max_issues_repo_head_hexsha": "6e4d8a58e063861967de9260f15d182eb7d35ada", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels.jl", "max_forks_repo_name": "Jetafull/algorithms-in-julia", "max_forks_repo_head_hexsha": "6e4d8a58e063861967de9260f15d182eb7d35ada", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3660714286, "max_line_length": 82, "alphanum_fraction": 0.6571629708, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7838335687742337}}
{"text": "\n\n\n@doc raw\"\"\"\n    semivariance(x; kind::Symbol=:lower)\n\nReturns the semivariance of vector-like `x`, which is the variance\ncomputed using only the observations below the mean. \n\nDefaults to lower semivariance, but returns upper semivariance if `kind=:upper` is supplied.\n\"\"\"\nfunction semivariance(x; kind::Symbol=:lower)\n    bigN = length(x)\n    mu = mean(x)\n    if kind==:upper\n        tmp = filter(z -> z > mu,x)\n    else\n        tmp = filter(z -> z <= mu,x)\n    end\n    return sum((tmp .- mu).^2)/bigN\nend\n\n\n\n\n\n\n\n\n\"\"\"\n    lowerpartialmom(x,t,n)\n\n`n`-th Lower Partial Moment for vector-like `x` using target `t`. \n\nSource: Harlow (1991)\n\"\"\"\nfunction lowerpartialmom(x,t,n)\n    bigN = length(x)\n    return sum(filter(z->z>=0,t .- x).^n)/bigN\nend\n\n\n\"\"\"\n    upperpartialmom(x,t,n)\n\n`n`-th Upper Partial Moment for vector-like `x` using target `t`. \n\nSource: Harlow (1991)\n\"\"\"\nfunction upperpartialmom(x,t,n)\n    bigN = length(x)\n    return sum(filter(z->z>=0,x .- t).^n)/bigN\nend\n\n\n\n\n\n\"\"\"\n    valueatrisk(D::ContinuousUnivariateDistribution,alpha)\n\nReturns the VaR (value at risk) at the `alpha`-level for the distribution `D`.\n\"\"\"\nvalueatrisk(D::Distributions.ContinuousUnivariateDistribution,alpha::Float64) = quantile(D,1-alpha)\n\n\"\"\"\n    valueatrisk(X::AbstractVector,alpha)\n\nReturns the nonparametric estimate of VaR (value at risk) at the `alpha`-level for `X`.\n\"\"\"\nfunction valueatrisk(X::AbstractVector,alpha::Float64)\n    ecdf = EmpiricalCDF()\n    append!(ecdf,X)\n    sort!(ecdf)\n    icdf = finv(ecdf)\n    return icdf(1-alpha)\nend\n\n\n\n\"\"\"\n    expectedshortfall(D::ContinuousUnivariateDistribution,alpha)\n\nReturns the Expected Shortfall at the `alpha`-level for the distribution `D`.\nAssumes `D` is the distribution of payoffs `X`, not losses (which would be `-X`).\n\"\"\"\nfunction expectedshortfall(D::ContinuousUnivariateDistribution,alpha::Float64)\n    return first(quadgk( x -> -(1/alpha)*valueatrisk(D,x),0.0,alpha))\nend\n\n\n\"\"\"\n    expectedshortfall(X::AbstractVector,alpha)\n\nReturns the nonparametric estimate of Expected Shortfall at the `alpha`-level for `X`.\nAssumes `X` represents payoffs, not losses (which would be `-X`).\n\"\"\"\nfunction expectedshortfall(X::AbstractVector,alpha::Float64)\n    ecdf = EmpiricalCDF()\n    append!(ecdf,X)\n    sort!(ecdf)\n    icdf = finv(ecdf)\n    return first(quadgk( x -> -(1/alpha)*icdf(1-x),0.0,alpha))\nend\n\n\n# Bertsimas, Lauprete, Samarov (2004 JEDC) good source for ES/VaR/LPM\n\n\n\n", "meta": {"hexsha": "c12fc385e76b69c44420d7416b6027fbece8b701", "size": 2427, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate.jl", "max_stars_repo_name": "tbeason/AsymmetricRisk.jl", "max_stars_repo_head_hexsha": "f077a6a6eb634fa2325eccc177be6c0da977bfbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-25T21:16:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-27T02:50:16.000Z", "max_issues_repo_path": "src/univariate.jl", "max_issues_repo_name": "tbeason/AsymmetricRisk.jl", "max_issues_repo_head_hexsha": "f077a6a6eb634fa2325eccc177be6c0da977bfbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-01-01T22:47:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-28T22:19:21.000Z", "max_forks_repo_path": "src/univariate.jl", "max_forks_repo_name": "tbeason/AsymmetricRisk.jl", "max_forks_repo_head_hexsha": "f077a6a6eb634fa2325eccc177be6c0da977bfbc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8648648649, "max_line_length": 99, "alphanum_fraction": 0.6819118253, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368928, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7838335647135576}}
{"text": "using Plots, DataFrames, Flux, Plots, Random, ReverseDiff\nusing Turing # v0.20\n\n# create half-moon data:\nfunction make_moons(n_samples::Int = 100)\n    \n    n = n_samples\n\n    n_samples_out = trunc(Int, round(n_samples / 2))\n    n_samples_in = n_samples - n_samples_out\n\n    outer_circ_x = cos.(LinRange(0, π, n_samples_out))\n    outer_circ_y = sin.(LinRange(0, π, n_samples_out))\n    inner_circ_x = 1 .- cos.(LinRange(0, π, n_samples_in))\n    inner_circ_y = 1 .- sin.(LinRange(0, π, n_samples_in)) .- 0.5\n\n    X = hcat(vcat(outer_circ_x, inner_circ_x), vcat(outer_circ_y, inner_circ_y))\n    Y = hcat(zeros(Int, 1, 2 .* n_samples_out), ones(Int, 1, 2 .* n_samples_in))\n\n    return X, Y, n\n\nend\n\nX, Y, n = make_moons()\n\n# rearrange half-moon data:\nn_2 = trunc(Int, n/2)\nxscatter_0 = X[1:n_2]\nxscatter_1 = X[1+n_2:n]\nyscatter_0 = X[1+n:n+n_2]\nyscatter_1 = X[1+n+n_2:end]\n\n# plot half-moon data:\nplot(\n    xscatter_0, yscatter_0, \n    seriestype = :scatter, \n    legend = true,\n    label = \"Class 0\",\n    title = \"half-moons problem\"\n)\nplot!(\n    xscatter_1, yscatter_1, \n    seriestype = :scatter, \n    legend = true,\n    label = \"Class 1\"\n)\n\n# optional: half-moon data in a dataframe:\nhalf_moon_df = DataFrame(\n    X = vcat(xscatter_0, xscatter_1),\n    Y = vcat(yscatter_0, yscatter_1),\n    Class = vcat(zeros(Int, n_2), ones(Int, n_2))\n)\n\n# Turing settings:\nTuring.setprogress!(true)\nTuring.setadbackend(:reversediff)\n\n# architecture:\nnetwork_shape = [\n    (5,2, :tanh),\n    (5,5, :tanh),\n    (2,5, :σ)]\n\n# Regularization, parameter variance, and total number of parameters.\nalpha = 0.09\nsig = sqrt(1.0 / alpha)\nnum_params = sum([i * o + i for (i, o, _) in network_shape])\n\n# This modification of the unpack function generates a series of vectors given a network shape.\nfunction unpack(θ::AbstractVector, network_shape::AbstractVector)\n    index = 1\n    weights = []\n    biases = []\n    for layer in network_shape\n        rows, cols, _ = layer\n        size = rows * cols\n        last_index_w = size + index - 1\n        last_index_b = last_index_w + rows\n        push!(weights, reshape(θ[index:last_index_w], rows, cols))\n        push!(biases, reshape(θ[last_index_w+1:last_index_b], rows))\n        index = last_index_b + 1\n    end\n    return weights, biases\nend\n\n# Generate an abstract neural network given a shape, and return a prediction.\nfunction nn_forward(x, θ::AbstractVector, network_shape::AbstractVector)\n    weights, biases = unpack(θ, network_shape)\n    layers = []\n    for i in eachindex(network_shape)\n        push!(layers, Dense(weights[i],\n            biases[i],\n            eval(network_shape[i][3])))\n    end\n    nn = Chain(layers...)\n    return nn(x)\nend\n\n# rearrange half-moon data yet again:\nxscatter = vcat(xscatter_0, xscatter_1)\nyscatter = vcat(yscatter_0, yscatter_1)\nxs = Array([[xscatter[i]; yscatter[i]] for i = 1:n])\nts = vcat(zeros(Int, n_2), ones(Int, n_2))\n\n# General Turing specification for a BNN model.\n@model bayes_nn_general(xs, ts, network_shape, num_params) = begin\n    θ ~ MvNormal(zeros(num_params), sig .* ones(num_params))\n    preds = nn_forward(xs, θ, network_shape)\n    for i = 1:length(ts)\n        ts[i] ~ Bernoulli(preds[i])\n    end\nend\n\n# Perform inference.\nnum_samples = 2000\nch2 = sample(bayes_nn_general(hcat(xs...), ts, network_shape, num_params), NUTS(0.65), num_samples);\n\n# This function makes predictions based on network shape.\nfunction nn_predict(x, theta, num, network_shape)\n    mean([nn_forward(x, theta[i,:], network_shape)[1] for i in 1:10:num])\nend;\n\n# Extract the θ parameters from the sampled chain.\nparams2 = MCMCChains.group(ch2, :θ).value\n\n# classification plot\nplot(\n    xscatter_0, yscatter_0, \n    seriestype = :scatter, \n    label = \"Class 0\",\n    title = \"half-moons problem\"\n)\nplot!(\n    xscatter_1, yscatter_1, \n    seriestype = :scatter, \n    legend = :bottomright,\n    label = \"Class 1\"\n)\nx_range = collect(range(-2.5,stop=3.5,length=200))\ny_range = collect(range(-1.2,stop=1.7,length=200))\nZ = [nn_predict([x, y], params2, length(ch2), network_shape)[1] for x=x_range, y=y_range]\ncontour!(x_range, y_range, Z)\n", "meta": {"hexsha": "d70900e4dbc8d9ecde5bba91def3ef0b47dfc9ce", "size": 4087, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter4-NNs/ML_in_Finance-Bayesian-Neural-Network.jl", "max_stars_repo_name": "cb-g/machine-learning-in-finance", "max_stars_repo_head_hexsha": "aab6e93db47ce2e4f3f91ee3da640069c5ec18f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter4-NNs/ML_in_Finance-Bayesian-Neural-Network.jl", "max_issues_repo_name": "cb-g/machine-learning-in-finance", "max_issues_repo_head_hexsha": "aab6e93db47ce2e4f3f91ee3da640069c5ec18f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter4-NNs/ML_in_Finance-Bayesian-Neural-Network.jl", "max_forks_repo_name": "cb-g/machine-learning-in-finance", "max_forks_repo_head_hexsha": "aab6e93db47ce2e4f3f91ee3da640069c5ec18f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3819444444, "max_line_length": 100, "alphanum_fraction": 0.6677269391, "num_tokens": 1290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7838335634753495}}
{"text": "\"\"\"\n    conformal_cubed_sphere_mapping(x, y)\n\nConformal mapping of a cube onto a sphere. Maps `(x, y)` on the north-pole face of a cube\nto (X, Y, Z) coordinates in physical space. The face is oriented normal to Z-axis with\nX and Y increasing with x and y.\n\nThe input coordinates must lie within the range -1 <= x <= 1,  -1 <= y <= 1.\n\nThis numerical conformal mapping is described by Rančić et al. (1996).\n\nThis is a Julia translation of MATLAB code from MITgcm [1] that is based on\nFortran 77 code from Jim Purser & Misha Rančić.\n\n[1] http://wwwcvs.mitgcm.org/viewvc/MITgcm/MITgcm_contrib/high_res_cube/matlab-grid-generator/map_xy2xyz.m?view=markup\n\nRančić et al., (1996): Quarterly Journal of the Royal Meteorological Society, A global shallow-water model\n    using an expanded spherical cube - Gnomonic versus conformal coordinates\n\"\"\"\nfunction conformal_cubed_sphere_mapping(x, y)\n    X = xᶜ = abs(x)\n    Y = yᶜ = abs(y)\n\n    kxy = yᶜ > xᶜ\n\n    xᶜ = 1 - xᶜ\n    yᶜ = 1 - yᶜ\n\n    kxy && (xᶜ = 1 - Y)\n    kxy && (yᶜ = 1 - X)\n\n    Z = ((xᶜ + im * yᶜ) / 2)^4\n    W = W_Rancic(Z)\n\n    im³ = im^(1/3)\n    ra = √3 - 1\n    cb = -1 + im\n    cc = ra * cb / 2\n\n    W = im³ * (W * im)^(1/3)\n    W = (W - ra) / (cb + cc * W)\n    X, Y = reim(W)\n\n    H = 2 / (1 + X^2 + Y^2)\n    X = X * H\n    Y = Y * H\n    Z = H - 1\n\n    if kxy\n        X, Y = Y, X\n    end\n\n    y < 0 && (Y = -Y)\n    x < 0 && (X = -X)\n\n    # Fix truncation for x = 0 or y = 0.\n    x == 0 && (X = 0)\n    y == 0 && (Y = 0)\n\n    return X, Y, Z\nend\n\n\"\"\"\n   conformal_cubed_sphere_inverse_mapping(X, Y, Z)\n\nInverse mapping for conformal cube sphere for quadrant of north-pole face in which X and Y are both\npositive. All other mappings to other cube face coordinates can be recovered from rotations of this map.\nThere a 3 other quadrants for the north-pole face and five other faces for a total of twenty-four quadrants.\nBecause of symmetry only the reverse for a single quadrant is needed. Because of branch cuts and the complex\ntransform the inverse mappings are multi-valued in general, using a single quadrant case allows a simple\nset of rules to be applied.\n\nThe mapping is valid for the cube face quadrant defined by 0 < x < 1 and 0 < y < 1, where a full cube\nface has extent -1 < x < 1 and -1 < y < 1. The quadrant for the mapping is from a cube face that has\n\"north-pole\" at its center (x=0,y=0) i.e has X,Y,Z = (0,0,1) at its center. The valid ranges of X and Y\nfor this mapping and convention are a quadrant defined be geodesics that connect the points A, B, C and D,\non the shell of a sphere of radius R with X,Y coordinates as follows\n\nA = (0,0)\nB = (√2,0)\nC = (√3/3,√3/3)\nD = (0,√2)\n\n\"\"\"\nfunction conformal_cubed_sphere_inverse_mapping(X, Y, Z)\n    H  = Z + 1\n    Xˢ = X/H\n    Yˢ = Y/H\n    ω  = Xˢ + im*Yˢ\n\n    ra = √3 - 1\n    cb = -1 + im\n    cc = ra * cb / 2\n    ω⁰ = (ω*cb + ra)/(1-ω*cc)\n    W⁰ = im*ω⁰^3*im\n    Z  = Z_Rancic(W⁰)\n    z  = (Z^0.25)*2\n    x, y = reim(z)\n\n    kxy = abs(y) > abs(x)\n    xx = x\n    yy = y\n    !kxy && ( x = 1 - abs(yy) )\n    !kxy && ( y = 1 - abs(xx) )\n\n    xf = x\n    yf = y\n    ( X < Y ) && ( xf = y  )\n    ( X < Y ) && ( yf = x  )\n    x = xf\n    y = yf\n\n    return x, y\nend\n\nW_Rancic(Z) = sum(A_Rancic[k] * Z^(k-1) for k in 1:length(A_Rancic))\nZ_Rancic(W) = sum(B_Rancic[k] * W^(k-1) for k in 1:length(B_Rancic))\n", "meta": {"hexsha": "7c53fa3da29aaad5f366c3208fa5589548a07e90", "size": 3312, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/conformal_cubed_sphere.jl", "max_stars_repo_name": "CliMA/CubedSphere.jl", "max_stars_repo_head_hexsha": "57d0a9bda06173e9c28fd7820daaab4a2367e208", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-02-11T19:50:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-15T03:24:12.000Z", "max_issues_repo_path": "src/conformal_cubed_sphere.jl", "max_issues_repo_name": "CliMA/CubedSphere.jl", "max_issues_repo_head_hexsha": "57d0a9bda06173e9c28fd7820daaab4a2367e208", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-02-27T01:28:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-11T05:04:32.000Z", "max_forks_repo_path": "src/conformal_cubed_sphere.jl", "max_forks_repo_name": "CliMA/CubedSphere.jl", "max_forks_repo_head_hexsha": "57d0a9bda06173e9c28fd7820daaab4a2367e208", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0677966102, "max_line_length": 118, "alphanum_fraction": 0.6029589372, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7838335631584975}}
{"text": "\"\"\"\n    Semicircle(r)\n\nThe Wigner semicircle distribution with radius parameter `r` has probability\ndensity function\n\n```math\nf(x; r) = \\\\frac{2}{\\\\pi r^2} \\\\sqrt{r^2 - x^2}, \\\\quad x \\\\in [-r, r].\n```\n\n```julia\nSemicircle(r)   # Wigner semicircle distribution with radius r\n\nparams(d)       # Get the radius parameter, i.e. (r,)\n```\n\nExternal links\n\n* [Wigner semicircle distribution on Wikipedia](https://en.wikipedia.org/wiki/Wigner_semicircle_distribution)\n\"\"\"\nstruct Semicircle{T<:Real} <: ContinuousUnivariateDistribution\n    r::T\n    Semicircle{T}(r::T) where {T <: Real} = new{T}(r)\nend\n\n\nfunction Semicircle(r::T) where {T <: Real}\n    @check_args(Semicircle, r > 0)\n    return Semicircle{T}(r)\nend\n\nSemicircle(r::T, ::NoArgCheck) where {T <: Real} = Semicircle{T}(r)\nSemicircle(r::Integer) = Semicircle(float(r))\n\n@distr_support Semicircle -d.r +d.r\n\nparams(d::Semicircle) = (d.r,)\n\nmean(d::Semicircle) = zero(d.r)\nvar(d::Semicircle) = d.r^2 / 4\nskewness(d::Semicircle) = zero(d.r)\nmedian(d::Semicircle) = zero(d.r)\nmode(d::Semicircle) = zero(d.r)\nentropy(d::Semicircle) = log(π * d.r) - oftype(d.r, 0.5)\n\nfunction pdf(d::Semicircle, x::Real)\n    xx, r = promote(x, float(d.r))\n    if insupport(d, xx)\n        return 2 / (π * r^2) * sqrt(r^2 - xx^2)\n    else\n        return oftype(r, 0)\n    end\nend\n\nfunction logpdf(d::Semicircle, x::Real)\n    xx, r = promote(x, float(d.r))\n    if insupport(d, xx)\n        return log(oftype(r, 2) / π) - 2 * log(r) + log(r^2 - xx^2) / 2\n    else\n        return oftype(r, -Inf)\n    end\nend\n\nfunction cdf(d::Semicircle, x::Real)\n    xx, r = promote(x, float(d.r))\n    if insupport(d, xx)\n        u = xx / r\n        return (u * sqrt(1 - u^2) + asin(u)) / π + one(xx) / 2\n    elseif x < minimum(d)\n        return zero(r)\n    else\n        return one(r)\n    end\nend\n\n@quantile_newton Semicircle\n", "meta": {"hexsha": "8f7118547176386edd0efda907350e9e6b581323", "size": 1833, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/semicircle.jl", "max_stars_repo_name": "uwbanjoman/Distributions.jl", "max_stars_repo_head_hexsha": "3f3dbe911629120e0fd875291aaaec1645b0f855", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/semicircle.jl", "max_issues_repo_name": "uwbanjoman/Distributions.jl", "max_issues_repo_head_hexsha": "3f3dbe911629120e0fd875291aaaec1645b0f855", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/semicircle.jl", "max_forks_repo_name": "uwbanjoman/Distributions.jl", "max_forks_repo_head_hexsha": "3f3dbe911629120e0fd875291aaaec1645b0f855", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8051948052, "max_line_length": 109, "alphanum_fraction": 0.612111293, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294982, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7838335528775804}}
{"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    Scale(; low=0.25, high=0.75)\n\nApplies the scale transform to all columns of the table.\nThe scale transform of the column `x` is defined by `(x .- xl) ./ (xh - xl)`,\nwhere `xl = quantile(x, low)` and `xh = quantile(x, high)`.\n\n# Examples\n\n```julia\nScale()\nScale(low=0, high=1)\nScale(low=0.3, high=0.7)\n```\n\n## Notes\n\n* The `low` and `high` values are restricted to the interval [0, 1].\n\"\"\"\nstruct Scale{T<:Real} <: Colwise\n  low::T\n  high::T\n\n  function Scale(low::T, high::T) where {T<:Real}\n    @assert 0 ≤ low ≤ high ≤ 1 \"invalid quantiles\"\n    new{T}(low, high)\n  end\nend\n\nScale(low::Real, high::Real) = Scale(promote(low, high)...)\n\nScale(; low=0.25, high=0.75) = Scale(low, high)\n\nassertions(::Type{<:Scale}) = [assert_continuous]\n\nisrevertible(::Type{<:Scale}) = true\n\nfunction colcache(transform::Scale, x)\n  levels = (transform.low, transform.high)\n  xl, xh = quantile(x, levels)\n  xl == xh && ((xl, xh) = (zero(xl), one(xh)))\n  (xl=xl, xh=xh)\nend\n\ncolapply(::Scale, x, c)  = @. (x - c.xl) / (c.xh - c.xl)\n\ncolrevert(::Scale, y, c) = @. (c.xh - c.xl) * y + c.xl\n\n\"\"\"\n    MinMax()\n\nThe transform that is equivalent to `Scale(low=0, high=1)`.\n\nSee also [`Scale`](@ref).\n\"\"\"\nMinMax() = Scale(low=0, high=1)\n\n\"\"\"\n    Interquartile()\n\nThe transform that is equivalent to `Scale(low=0.25, high=0.75)`.\n\nSee also [`Scale`](@ref).\n\"\"\"\nInterquartile() = Scale(low=0.25, high=0.75)\n", "meta": {"hexsha": "c5b370d3fdcfa7e128e128f4f0344d91b39163cc", "size": 1594, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transforms/scale.jl", "max_stars_repo_name": "JuliaML/TableTransforms.jl", "max_stars_repo_head_hexsha": "90a30ba6a0d821e15478c2bcdec47fbea3cca1f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2021-10-29T21:22:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:48:35.000Z", "max_issues_repo_path": "src/transforms/scale.jl", "max_issues_repo_name": "JuliaML/TableTransforms.jl", "max_issues_repo_head_hexsha": "90a30ba6a0d821e15478c2bcdec47fbea3cca1f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2021-10-30T10:38:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:14:21.000Z", "max_forks_repo_path": "src/transforms/scale.jl", "max_forks_repo_name": "JuliaML/TableTransforms.jl", "max_forks_repo_head_hexsha": "90a30ba6a0d821e15478c2bcdec47fbea3cca1f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-11-03T22:10:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T11:27:07.000Z", "avg_line_length": 22.7714285714, "max_line_length": 77, "alphanum_fraction": 0.5621079046, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308054739519, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7838335463404873}}
{"text": "#---------------------------------------------------------------------#\n#This function computes the Initial & Analytic Solutions.\n#Written by F.X. Giraldo on 10/2003\n#           Department of Applied Mathematics\n#           Naval Postgraduate School\n#           Monterey; CA 93943-5216\n#---------------------------------------------------------------------#\nfunction exact_solution(coord,Npoin,c,DFloat)\n\n    #Initialize\n    qe=zeros(DFloat,Npoin,1)\n    fe=zeros(DFloat,Npoin,1)\n    cc=c*π\n\n    #Generate Grid Points\n    for I=1:Npoin\n        x=coord[1,I]\n        y=coord[2,I]\n        qe[I]=sin(cc*x)*sin(cc*y)\n        fe[I]=-2*cc^2*sin(cc*x)*sin(cc*y)\n    end #I\n\n    return (qe,fe)\n\nend\n\n\n", "meta": {"hexsha": "303f5f2222bbadf57559b7673736ae2002d8a4f5", "size": 691, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Projects/Project_05_2D_Elliptic/For_Instructors/julia/exact_solution.jl", "max_stars_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_stars_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-12-28T06:19:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:40:33.000Z", "max_issues_repo_path": "Projects/Project_05_2D_Elliptic/For_Instructors/julia/exact_solution.jl", "max_issues_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_issues_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-29T19:12:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-29T21:53:41.000Z", "max_forks_repo_path": "Projects/Project_05_2D_Elliptic/For_Students/julia/exact_solution.jl", "max_forks_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_forks_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:35:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T06:53:34.000Z", "avg_line_length": 24.6785714286, "max_line_length": 71, "alphanum_fraction": 0.479015919, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9559813501370537, "lm_q2_score": 0.8198933447152498, "lm_q1q2_score": 0.7838027466492692}}
{"text": "# Equation 33 of https://www.mdpi.com/2227-7390/6/2/16/htm\n\n# Loaded Packages\nusing FdeSolver\nusing Plots\nusing SpecialFunctions\n\n# Parameters\ntSpan = [0, 5]         # Time Span\ny0 = [1, 0.5, 0.3]     # Initial values\nβ = [0.5, 0.2, 0.6]    # Order of derivation\n\n# Definition of the System\nfunction F(t, n, β, y)\n\n    F1 = 1 / sqrt(pi) * (((y[n, 2] - 0.5) * (y[n, 3] - 0.3))^(1 / 6) + t[n]^(1 / 2))\n    F2 = gamma(2.2) * (y[n, 1] - 1)\n    F3 = gamma(2.8) / gamma(2.2) * (y[n, 2] - 0.5)\n\n    return [F1, F2, F3]\n\nend\n\n# Numerical Solution\nt, Yapp = FDEsolver(F, tSpan, y0, β, nothing, nc = 5)\n\n# Plot\nplot(t, Yapp, linewidth = 5, title = \"Solution of system 33\",\n     xaxis = \"Time (t)\", yaxis = \"y(t)\", label = \"Approximation\")\n\nplot!(t, t -> (t .+ 1), lw = 3, ls = :dash, color= \"red\", label = \"Exact solution\")\nplot!(t, t -> (t.^1.2 .+ 0.5), lw = 3, ls = :dash, color= \"cyan\", label = \"Exact solution\")\nplot!(t, t -> (t.^1.8 .+ 0.3), lw = 3, ls = :dash, color= \"black\" ,label = \"Exact solution\")\n", "meta": {"hexsha": "a316e6472ffbf0ff36b980a29fe243787969d06f", "size": 999, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/fDE3D.jl", "max_stars_repo_name": "moeinkh88/FdeSolver.jl", "max_stars_repo_head_hexsha": "21c2922de90484328d794465cb5000db0281fcfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/fDE3D.jl", "max_issues_repo_name": "moeinkh88/FdeSolver.jl", "max_issues_repo_head_hexsha": "21c2922de90484328d794465cb5000db0281fcfb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/fDE3D.jl", "max_forks_repo_name": "moeinkh88/FdeSolver.jl", "max_forks_repo_head_hexsha": "21c2922de90484328d794465cb5000db0281fcfb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3823529412, "max_line_length": 92, "alphanum_fraction": 0.5475475475, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370537, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7838027445457006}}
{"text": "keys = open(\"public_keys.txt\") do f\n    parse.(Int, readlines(f))\nend\n\nfunction transform(subject_number::Int64, loop_size::Int64)::Int64\n    val = 1\n    for i in 1:loop_size\n        val = (val * subject_number) % 20201227\n    end\n\n    return val\nend\n\nfunction crack(public_keys::Array{Int64, 1}, sn::Int64, ls_range::UnitRange{Int64})::Tuple{Int64, Int64}\n    val = 1\n    for ls in ls_range\n        val = (val * sn) % 20201227\n        if val == public_keys[1]\n            # println(\"sn $(sn), ls $(ls) match first\")\n            val2 = 1\n            for ls2 in ls_range\n                val2 = (val2 * sn) % 20201227\n                if val2 == public_keys[2] && ls != ls2\n                    # println(\"sn $(sn), ls $(ls2) match second\")\n\n                    return ls, ls2\n                end\n            end\n            # println(\"no matching ls2 found\")\n        end\n    end\n\n    return nothing, nothing\nend\n\nls1, ls2 = crack(keys, 7, 1:100_000_000)\n\nprintln(transform(keys[1], ls2))\n# println(transform(keys[2], ls1))\n", "meta": {"hexsha": "3a5d32b0379c919712c5becfa22f7bf8a9746d40", "size": 1020, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day25.jl", "max_stars_repo_name": "kari/aoc2020", "max_stars_repo_head_hexsha": "cbc83cf0b5696171141bc0aca376214a561b0eeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day25.jl", "max_issues_repo_name": "kari/aoc2020", "max_issues_repo_head_hexsha": "cbc83cf0b5696171141bc0aca376214a561b0eeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day25.jl", "max_forks_repo_name": "kari/aoc2020", "max_forks_repo_head_hexsha": "cbc83cf0b5696171141bc0aca376214a561b0eeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5, "max_line_length": 104, "alphanum_fraction": 0.5450980392, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813488829417, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.783802741413894}}
{"text": "#############################################################################\n# eigmin_max.jl\n# Handles maximum and minimum eigenvalue of a symmetric positive definite matrix\n# (and imposes the constraint that its argument be PSD)\n# All expressions and atoms are subtypes of AbstractExpr.\n# Please read expressions.jl first.\n#############################################################################\n\nimport LinearAlgebra: eigmin, eigmax\n\n### Eig max\n\nstruct EigMaxAtom <: AbstractExpr\n    head::Symbol\n    id_hash::UInt64\n    children::Tuple{AbstractExpr}\n    size::Tuple{Int, Int}\n\n    function EigMaxAtom(x::AbstractExpr)\n        children = (x,)\n        m, n = size(x)\n        if m == n\n            return new(:eigmax, hash(children), children, (1, 1))\n        else\n            error(\"eigmax can only be applied to a square matrix.\")\n        end\n    end\nend\n\nfunction sign(x::EigMaxAtom)\n    return NoSign()\nend\n\nfunction monotonicity(x::EigMaxAtom)\n    return (Nondecreasing(),)\nend\n\nfunction curvature(x::EigMaxAtom)\n    return ConvexVexity()\nend\n\nfunction evaluate(x::EigMaxAtom)\n    eigmax(evaluate(x.children[1]))\nend\n\neigmax(x::AbstractExpr) = EigMaxAtom(x)\n\n# Create the equivalent conic problem:\n#   minimize t\n#   subject to\n#            tI - A is positive semidefinite\n#            A      is positive semidefinite\nfunction conic_form!(x::EigMaxAtom, unique_conic_forms)\n    if !has_conic_form(unique_conic_forms, x)\n        A = x.children[1]\n        m, n = size(A)\n        t = Variable()\n        p = minimize(t, t*Matrix(1.0I, n, n) - A ⪰ 0)\n        cache_conic_form!(unique_conic_forms, x, p)\n    end\n    return get_conic_form(unique_conic_forms, x)\nend\n\n### Eig min\n\nstruct EigMinAtom <: AbstractExpr\n    head::Symbol\n    id_hash::UInt64\n    children::Tuple{AbstractExpr}\n    size::Tuple{Int, Int}\n\n    function EigMinAtom(x::AbstractExpr)\n        children = (x,)\n        m, n = size(x)\n        if m == n\n            return new(:eigmin, hash(children), children, (1,1))\n        else\n            error(\"eigmin can only be applied to a square matrix.\")\n        end\n    end\nend\n\nfunction sign(x::EigMinAtom)\n    return NoSign()\nend\n\nfunction monotonicity(x::EigMinAtom)\n    return (Nondecreasing(),)\nend\n\nfunction curvature(x::EigMinAtom)\n    return ConcaveVexity()\nend\n\nfunction evaluate(x::EigMinAtom)\n    eigmin(evaluate(x.children[1]))\nend\n\neigmin(x::AbstractExpr) = EigMinAtom(x)\n\n# Create the equivalent conic problem:\n#   maximize t\n#   subject to\n#            A - tI is positive semidefinite\n#            A      is positive semidefinite\nfunction conic_form!(x::EigMinAtom, unique_conic_forms)\n    if !has_conic_form(unique_conic_forms, x)\n        A = x.children[1]\n        m, n = size(A)\n        t = Variable()\n        p = maximize(t, A - t*Matrix(1.0I, n, n) ⪰ 0)\n        cache_conic_form!(unique_conic_forms, x, p)\n    end\n    return get_conic_form(unique_conic_forms, x)\nend\n", "meta": {"hexsha": "36687faaa18470dcc7e6a326a827984dd00939f9", "size": 2901, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/atoms/sdp_cone/eig_min_max.jl", "max_stars_repo_name": "JinraeKim/Convex.jl", "max_stars_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 123, "max_stars_repo_stars_event_min_datetime": "2020-06-16T21:56:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:05:39.000Z", "max_issues_repo_path": "src/atoms/sdp_cone/eig_min_max.jl", "max_issues_repo_name": "JinraeKim/Convex.jl", "max_issues_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122, "max_issues_repo_issues_event_min_datetime": "2020-06-14T00:19:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T14:02:09.000Z", "max_forks_repo_path": "src/atoms/sdp_cone/eig_min_max.jl", "max_forks_repo_name": "JinraeKim/Convex.jl", "max_forks_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2020-08-21T07:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T13:40:50.000Z", "avg_line_length": 25.0086206897, "max_line_length": 80, "alphanum_fraction": 0.6135815236, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813488829418, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7838027308960513}}
{"text": "\n\n# NOTE: this is mostly just copied from wikipedia\nfunction gmres_cycle(A::SparseMatrixCSC, x0::Vector{Float64}, b::Vector{Float64}, m::Int64; err_thresh = 1e-20)\n\n    # compute initial residual, norm(b) and initial error\n    r = b - A * x0\n    bnorm = norm(b)\n    err = norm(r) / bnorm\n\n    n = length(x0)\n    Q = zeros(Float64, (n,m+1))\n    H = zeros(Float64, (m+2,m+1))\n    sn = zeros(Float64, m)\n    cn = zeros(Float64, m)\n    e1 = zeros(Float64, m+1)\n    e1[1] = 1.0\n\n    beta = norm(r) * e1\n    Q[:,1] = r / norm(r)\n\n    # begin iteration\n    nk = 0\n    for k=1:m\n        nk += 1\n\n        # do arnoldi iteration\n        q = A * Q[:,k]\n        for i=1:k\n            H[i,k] = transpose(q) * Q[:,i]\n            q = q - H[i,k] * Q[:,i]\n        end\n        qnorm = norm(q)\n        H[k+1,k] = qnorm\n        Q[:,k+1] = q / qnorm\n\n        # apply givens rotation\n        for i=1:k-1\n            temp = cn[i] * H[i,k] + sn[i] * H[i+1,k]\n            H[i+1,k] = -sn[i] * H[i,k] + cn[i] * H[i+1,k]\n            H[i,k] = temp\n        end\n\n        # update sn and cn\n        t = sqrt(H[k,k]^2 + H[k+1,k]^2)\n        cn[k] = H[k,k] / t\n        sn[k] = H[k+1,k] / t\n\n        # eliminate H[k+1, k]\n        H[k,k] = cn[k] * H[k,k] + sn[k] * H[k+1,k]\n        H[k+1,k] = 0.0\n\n        # update residual\n        beta[k+1] = -sn[k]*beta[k]\n        beta[k] = cn[k]*beta[k]\n        err = abs(beta[k+1]) / bnorm\n\n        if err < err_thresh\n            break\n        end\n    end\n\n    # compute correction to x\n    y = H[1:nk,1:nk] \\ beta[1:nk]\n    x = x0 + Q[:,1:nk] * y\n    return x, err\nend\n\n\nfunction gmres_solve(A::SparseMatrixCSC, x0::Vector{Float64}, b::Vector{Float64}, m::Int64; maxiters=10000, err_thresh = 1e-8)\n\n    x = x0[:]\n    err = 1.0\n    iteration = 0\n\n    while (err > err_thresh)\n        x, err = gmres_cycle(A, x, b, m, err_thresh=err_thresh)\n        iteration += 1\n\n        if iteration > maxiters\n            @warn \"Iteration limit reached, defaulting to direct solver.\"\n            return A \\ b\n        end\n    end\n\n    return x\nend\n", "meta": {"hexsha": "7a7b41f94c3f7193f408ba457c593b4418d71a5d", "size": 2035, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "old/linsolve/gmres.jl", "max_stars_repo_name": "JakeWillard/GDB.jl", "max_stars_repo_head_hexsha": "9d025feeb47995ac4a880919d801fd2256b826d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-07T19:52:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T19:52:36.000Z", "max_issues_repo_path": "old/linsolve/gmres.jl", "max_issues_repo_name": "JakeWillard/GDB.jl", "max_issues_repo_head_hexsha": "9d025feeb47995ac4a880919d801fd2256b826d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-21T00:18:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-21T00:18:46.000Z", "max_forks_repo_path": "old/linsolve/gmres.jl", "max_forks_repo_name": "JakeWillard/GDB.jl", "max_forks_repo_head_hexsha": "9d025feeb47995ac4a880919d801fd2256b826d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.125, "max_line_length": 126, "alphanum_fraction": 0.4776412776, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7837871697063198}}
{"text": "\nusing JuMP\nusing ECOS\nusing LinearAlgebra\nusing Random\n\nRandom.seed!(1234);\n\n\nu0 = rand(10)\np = rand(10)\nq = rand();\n\n\nmodel = Model(optimizer_with_attributes(ECOS.Optimizer, \"printlevel\" => 0))\n@variable(model, u[1:10])\n@variable(model, t)\n@objective(model, Min, t)\n@constraint(model, [t, (u - u0)...] in SecondOrderCone())\n@constraint(model, u' * p == q)\noptimize!(model)\n\n\n@show objective_value(model);\n@show value.(u);\n\n\ne1 = [1, zeros(10)...]\ndual_model = Model(optimizer_with_attributes(ECOS.Optimizer, \"printlevel\" => 0))\n@variable(dual_model, y1 <= 0)\n@variable(dual_model, y2[1:11])\n@objective(dual_model, Max, q * y1 + dot(vcat(0, u0), y2))\n@constraint(dual_model, e1 - [0, p...] .* y1 - y2 .== 0)\n@constraint(dual_model, y2 in SecondOrderCone())\noptimize!(dual_model)\n\n\n@show objective_value(dual_model);\n\n\nmodel = Model(optimizer_with_attributes(ECOS.Optimizer, \"printlevel\" => 0))\n@variable(model, u[1:10])\n@variable(model, t)\n@objective(model, Min, t)\n@constraint(model, [t, 0.5, (u - u0)...] in RotatedSecondOrderCone())\n@constraint(model, u' * p == q)\noptimize!(model)\n\n\n@show value.(u);\n\n\nn = 15;\nm = 10;\nA = randn(m, n);\nb = rand(m, 1);\n\nmodel = Model(optimizer_with_attributes(ECOS.Optimizer, \"printlevel\" => 0))\n@variable(model, t[1:n])\n@variable(model, x[1:n])\n@objective(model, Max, sum(t))\n@constraint(model, sum(x) == 1)\n@constraint(model, A * x .<= b )\n# Cannot use the exponential cone directly in JuMP, hence we use MOI to specify the set.\n@constraint(model, con[i = 1:n], [1, x[i], t[i]] in MOI.ExponentialCone())\n\noptimize!(model);\n\n\n@show objective_value(model);\n\n\n\n", "meta": {"hexsha": "4b651155850c0d70bfd09d3c63067d6840d3aa5b", "size": 1597, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/optimization_concepts/conic_programming.jl", "max_stars_repo_name": "frapac/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "55374d470e4e1b16a3a16f2ec7088ecf317b48b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-07T20:43:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-06T17:51:12.000Z", "max_issues_repo_path": "test/optimization_concepts/conic_programming.jl", "max_issues_repo_name": "frapac/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "55374d470e4e1b16a3a16f2ec7088ecf317b48b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/optimization_concepts/conic_programming.jl", "max_forks_repo_name": "frapac/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "55374d470e4e1b16a3a16f2ec7088ecf317b48b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5810810811, "max_line_length": 88, "alphanum_fraction": 0.6743894803, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7837871682609789}}
{"text": "\"\"\"\r\nRemove minimum number of nodes so that the graph no longer exists k-core\r\n\"\"\"\r\nfunction decore(g, k=2)\r\n\tattack_nodes = Int[]\r\n\tdeg = degree(g) # adaptive degrees\r\n\tdegmax = maximum(deg)\r\n\tH = [Set{Int}() for i=1:degmax]\r\n\r\n\tfor i in vertices(g)\r\n\t\tif deg[i] > 0\r\n\t\t\tdegi = max(deg[i], k-1)\r\n\t\t\tpush!(H[degi], i)\r\n\t\tend\r\n\tend\r\n\r\n\td = isempty(H[k-1]) ? degmax : k-1\r\n\tcnt = 0\r\n\tdone = false\r\n\twhile cnt < nv(g) && done == false\r\n\t\tcnt += 1\r\n\t\ti = rand(H[d])\r\n\t\tdelete!(H[d], i)\r\n\t\tdeg[i] = 0\r\n\t\td >= k && push!(attack_nodes, i)\r\n\r\n\t\t# update neighbors\r\n\t\tfor j in neighbors(g,i)\r\n\t\t\tif deg[j] >= k\r\n\t\t\t\tdelete!(H[deg[j]], j)\r\n\t\t\t\tdeg[j] -= 1\r\n\t\t\t\tpush!(H[deg[j]],j)\r\n\t\t\tend\r\n\t\tend\r\n\r\n\t\twhile isempty(H[degmax])\r\n\t\t\tdegmax -= 1\r\n\t\t\tdone = degmax < k\r\n\t\tend\r\n\t\td = isempty(H[k-1]) ? degmax : k-1\r\n\tend\r\n\tattack_nodes\r\nend\r\n", "meta": {"hexsha": "6edcb7ff4bc2751ccce907f450f77473924ec671", "size": 825, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/decore.jl", "max_stars_repo_name": "afternone/-NetworkDismantling.jl", "max_stars_repo_head_hexsha": "0b2788602510a07f996a6f5c4070795c45f5bb41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-30T04:37:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T04:37:37.000Z", "max_issues_repo_path": "src/decore.jl", "max_issues_repo_name": "afternone/NetworkDismantle.jl", "max_issues_repo_head_hexsha": "0b2788602510a07f996a6f5c4070795c45f5bb41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/decore.jl", "max_forks_repo_name": "afternone/NetworkDismantle.jl", "max_forks_repo_head_hexsha": "0b2788602510a07f996a6f5c4070795c45f5bb41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.75, "max_line_length": 73, "alphanum_fraction": 0.5406060606, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565739, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.7837871600650338}}
{"text": "function voigt(x, σ, γ)\n    faddeeva(z) = erfcx(-im * z)\n    z = (x + im * γ) / σ / sqrt(2)\n    return real(faddeeva(z)) / (σ * sqrt(2pi))\nend\n\n# J.J.Olivero and R.L. Longbothum in Empirical fits to the Voigt line width: A brief review, JQSRT 17, P233, 1977\n# http://snst-hu.lzu.edu.cn/zhangyi/ndata/Voigt_profile.html\nfunction voigt_fwhm(σ, γ)\n    @assert σ > 0\n    @assert γ > 0\n    fg = σ * 2.355\n    fl = γ * 2\n    return fl * 0.5346 + sqrt(0.2166 * fl^2 + fg^2)\n    #=\n    Introducing dampening parameter:\n    a = fl / fg\n    fwhm = fl * (0.5346 + sqrt(0.2166 + (1/a)^2))\n    =#\nend\n\nfunction voigt_σγ(fwhm, log_a)\n    a = 10. ^log_a\n    fl = fwhm / (0.5346 + sqrt(0.2166 + (1/a)^2))\n    fg = fl / a\n    return (fg / 2.355, fl / 2)\nend\n# log_a = log10((γ * 2) / (σ * 2.355));  QSFit.voigt_σγ(QSFit.voigt_fwhm(σ, γ), log_a), (σ, γ)\n\n\nfunction voigt_γ(fwhm, σ)\n    A = 0.5346\n    B = 0.2166\n    C = (σ * 2.355)^2\n    # fwhm = A * fl + sqrt(B * fl^2 + C)\n    fl = A * fwhm / (A^2 - B) - sqrt((A^2 * C - B * C + B * fwhm^2) / ((A^2 - B)^2))\n    γ = fl / 2\n    @assert (fwhm - voigt_fwhm(σ, γ)) / fwhm < 1e-5\n    return γ\nend\n# QSFit.voigt_γ(QSFit.voigt_fwhm(σ, γ), σ), γ\n", "meta": {"hexsha": "ad624a130634d8b7fec6b56bc9e44db8d1c75d46", "size": 1172, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/components/voigt_profile.jl", "max_stars_repo_name": "gcalderone/QSFIT.jl", "max_stars_repo_head_hexsha": "df4f502e0c60f992979da6cbbf2fee4c057e6947", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/components/voigt_profile.jl", "max_issues_repo_name": "gcalderone/QSFIT.jl", "max_issues_repo_head_hexsha": "df4f502e0c60f992979da6cbbf2fee4c057e6947", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/components/voigt_profile.jl", "max_forks_repo_name": "gcalderone/QSFIT.jl", "max_forks_repo_head_hexsha": "df4f502e0c60f992979da6cbbf2fee4c057e6947", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9047619048, "max_line_length": 113, "alphanum_fraction": 0.5392491468, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739075, "lm_q2_score": 0.8221891370573386, "lm_q1q2_score": 0.7837723836455118}}
{"text": "# ---\n# title: 504. Base 7\n# id: problem504\n# author: zhwang\n# date: 2022-03-10\n# difficulty: Easy\n# categories: \n# link: <https://leetcode.com/problems/base-7/description/>\n# hidden: true\n# ---\n# \n# Given an integer, return its base 7 string representation.\n# \n# **Example 1:**  \n# \n#     \n#     \n#     Input: 100\n#     Output: \"202\"\n#     \n# \n# **Example 2:**  \n# \n#     \n#     \n#     Input: -7\n#     Output: \"-10\"\n#     \n# \n# **Note:** The input will be in range of [-1e7, 1e7].\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction convert_to_base7(num::Int)::String\n    num == 0 && return \"0\"\n    sign = num < 0 ? -1 : 1\n    num *= sign\n    res = Int[]\n    while num > 0\n        push!(res, num % 7)\n        num ÷= 7\n    end\n    reverse!(res)\n    return sign != -1 ? join(res) : \"-\" * join(res)\nend\n\n## @lc code=end\n", "meta": {"hexsha": "08cb3499c7d8c8595ab3731ed53ae63369ff8442", "size": 815, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/504.base-7.jl", "max_stars_repo_name": "RexWzh/LeetCode.jl", "max_stars_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/504.base-7.jl", "max_issues_repo_name": "RexWzh/LeetCode.jl", "max_issues_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/504.base-7.jl", "max_forks_repo_name": "RexWzh/LeetCode.jl", "max_forks_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.3, "max_line_length": 60, "alphanum_fraction": 0.5190184049, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7837225850456538}}
{"text": "# # An equation of second order in two dimmensions\n#\n# Let \\\\(\\Omega = (0, 1)^2\\\\) the unit square and denote \\\\( \\Gamma = \\partial \\Omega\\\\) its boundary.\n# Consider the following problem. Given \\\\(f \\in C(\\Omega)\\\\), find a function \\\\(u\\\\) satisfying\n# -\\Delta u + u = f in \\Omega\n# u = 0 on \\Gamma\n\nusing SymFEL\nusing SymPy\nusing LinearAlgebra\nusing SparseArrays\nusing WriteVTK\nusing JLD2\n\n## discretization parameters\n# we use the mesh square.msh (in gmsh format)\n# obtained from square.geo using gmsh\n# this mesh is formed by quad elements\n# we use gmsh module for read the mesh\n# there are some problems using Threads and gmsh (in linux)\n# the file is square.jld2 is prepared separetely\n@load \"square.jld2\"\n\n# elementary matrices - P2 x P2\nelem_Mxy = SymFEL.get_square_lagrange_em((2, 2), (0, 0), (0, 0))\nelem_Kxy = SymFEL.get_square_lagrange_em((2, 2), (1, 0), (1, 0)) +\n    SymFEL.get_square_lagrange_em((2, 2), (0, 1), (0, 1))\n\ndx = norm(nodes_coordinate[:, elements_bound[1,1]] - nodes_coordinate[:, elements_bound[2,1]])\n\nelem_Kxy_dx = convert(Matrix{Float64}, elem_Kxy.subs(h, dx))\nelem_Mxy_dx = convert(Matrix{Float64}, elem_Mxy.subs(h, dx));\n\n# global matrices\nK = SymFEL.assemble_squaremesh_FE_matrix(elem_Kxy_dx, elements_int, order1=2, order2=2)\nM = SymFEL.assemble_squaremesh_FE_matrix(elem_Mxy_dx, elements_int, order1=2, order2=2)\n\nf = (2*pi^2 + 1) * sin.(pi * nodes_coordinate[1,:]) .* sin.(pi * nodes_coordinate[2,:])\n\nF = M * f\n\nA = K + M\n\n# boundary condition\ntgv = 1e30\nA[nodes_boundary, nodes_boundary] += tgv * sparse(Matrix{Float64}(I, nodes_boundary_N, nodes_boundary_N))\n\nu = A \\ F\nu_exact = sin.(pi*nodes_coordinate[1,:]) .* sin.(pi*nodes_coordinate[2,:])\nerr = u - u_exact\n\nprintln(\"L2 error : \", sqrt(err' * M * err))\nprintln(\"H1 error : \", sqrt(err' * K * err))\n\n\n# export to vtk\ncells = [MeshCell(VTKCellTypes.VTK_QUADRATIC_QUAD, elements_int[1:8, i]) for i = 1:elements_int_N]\n\n\npoints_x = nodes_coordinate[1, :]\npoints_y = nodes_coordinate[2, :]\nvtkfile = vtk_grid(\"ex3-output\", points_x, points_y, cells)\n\nvtkfile[\"my_point_data\", VTKPointData()] = u\noutfiles = vtk_save(vtkfile)\n", "meta": {"hexsha": "e467c0a917f3ef6b0f71f57c9dc7719be8648d7e", "size": 2119, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ex3-lagrange2d.jl", "max_stars_repo_name": "ncindea/SymFE.jl", "max_stars_repo_head_hexsha": "886e7fe844d0833bda4ab721414111f8fe353915", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-12T22:24:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T12:06:02.000Z", "max_issues_repo_path": "examples/ex3-lagrange2d.jl", "max_issues_repo_name": "ncindea/SymFEL.jl", "max_issues_repo_head_hexsha": "886e7fe844d0833bda4ab721414111f8fe353915", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ex3-lagrange2d.jl", "max_forks_repo_name": "ncindea/SymFEL.jl", "max_forks_repo_head_hexsha": "886e7fe844d0833bda4ab721414111f8fe353915", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1060606061, "max_line_length": 105, "alphanum_fraction": 0.704577631, "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7837225770956642}}
{"text": "#=\nfrom \"Error-free transformations in real and complex floating point arithmetics\"\nby Stef Graillat and Valérie Ménissier-Morain\n2007 International Symposium on Nonlinear Theory and its Applications\nNOLTA'07, Vancouver, Canada, September 16-19, 2007\n=#\n@inline function two_sum(a::Complex{T}, b::Complex{T}) where {T<:Real}\n    hi1, lo1 = two_sum(a.re, b.re)\n    hi2, lo2 = two_sum(a.im, b.im)\n    hi = Complex{T}(hi1, hi2)\n    lo = Complex{T}(lo1, lo2)\n    return hi, lo\nend\n\n@inline function one_sum(a::Complex{T}, b::Complex{T}) where {T<:Real}\n    hi1, lo1 = two_sum(a.re, b.re)\n    hi2, lo2 = two_sum(a.im, b.im)\n    hi = Complex{T}(hi1, hi2)\n    return hi\nend\n\ntwo_hilo_sum(a::Complex{T}, b::Complex{T}) where {T<:Real} = two_sum(a, b)\none_hilo_sum(a::Complex{T}, b::Complex{T}) where {T<:Real} = one_sum(a, b)\n\n@inline function two_diff(a::Complex{T}, b::Complex{T}) where {T<:Real}\n    hi1, lo1 = two_diff(a.re, b.re)\n    hi2, lo2 = two_diff(a.im, b.im)\n    hi = Complex{T}(hi1, hi2)\n    lo = Complex{T}(lo1, lo2)\n    return hi, lo\nend\n\n@inline function one_diff(a::Complex{T}, b::Complex{T}) where {T<:Real}\n    hi1, lo1 = two_diff(a.re, b.re)\n    hi2, lo2 = two_diff(a.im, b.im)\n    hi = Complex{T}(hi1, hi2)\n    return hi\nend\n\ntwo_hilo_diff(a::Complex{T}, b::Complex{T}) where {T<:Real} = two_diff(a, b)\none_hilo_diff(a::Complex{T}, b::Complex{T}) where {T<:Real} = one_diff(a, b)\n\n#=\nfrom \"Error-free transformations in real and complex floating point arithmetics\"\nby Stef Graillat and Valérie Ménissier-Morain\n2007 International Symposium on Nonlinear Theory and its Applications\nNOLTA'07, Vancouver, Canada, September 16-19, 2007\nN.B. modified to order q,r,s \n=#\n@inline function four_prod(a::Complex{T}, b::Complex{T}) where {T<:Real}\n    hi1, lo1 = two_prod(a.re, b.re)\n    hi2, lo2 = two_prod(a.im, b.im)\n    hi3, lo3 = two_prod(a.re, b.im)\n    hi4, lo4 = two_prod(a.im, b.re)\n    hi5, lo5 = two_diff(hi1, hi2)\n    hi6, lo6 = two_sum(hi3, hi4)\n    p = Complex{T}(hi5, hi6)\n    q = Complex{T}(lo5, lo6)\n    r = Complex{T}(lo1, lo3)\n    s = Complex{T}(-lo2, lo4)\n    r, s = two_sum(r, s)\n    q, r = two_sum(q, r)\n    return p, q, r, s\nend\n\n@inline function three_prod(a::Complex{T}, b::Complex{T}) where {T<:Real}\n    hi1, lo1 = two_prod(a.re, b.re)\n    hi2, lo2 = two_prod(a.im, b.im)\n    hi3, lo3 = two_prod(a.re, b.im)\n    hi4, lo4 = two_prod(a.im, b.re)\n    hi5, lo5 = two_diff(hi1, hi2)\n    hi6, lo6 = two_sum(hi3, hi4)\n    p = Complex{T}(hi5, hi6)\n    q = Complex{T}(lo5, lo6)\n    r = Complex{T}(lo1, lo3)\n    s = Complex{T}(-lo2, lo4)\n    q, r = two_sum(q, r, s)\n    return p, q, r\nend\n\n@inline function two_prod(a::Complex{T}, b::Complex{T}) where {T<:Real}\n    hi1, lo1 = two_prod(a.re, b.re)\n    hi2, lo2 = two_prod(a.im, b.im)\n    hi3, lo3 = two_prod(a.re, b.im)\n    hi4, lo4 = two_prod(a.im, b.re)\n    hi5, lo5 = two_diff(hi1, hi2)\n    hi6, lo6 = two_sum(hi3, hi4)\n    p = Complex{T}(hi5, hi6)\n    re = one_sum(lo5, lo1, lo2)\n    im = one_sum(lo6, lo3, lo4)\n    q = Complex{T}(re, im)\n    return p, q\nend\n\n@inline function one_prod(a::Complex{T}, b::Complex{T}) where {T<:Real}\n    hi1, lo1 = two_prod(a.re, b.re)\n    hi2, lo2 = two_prod(a.im, b.im)\n    hi3, lo3 = two_prod(a.re, b.im)\n    hi4, lo4 = two_prod(a.im, b.re)\n    hi5, lo5 = two_diff(hi1, hi2)\n    hi6 = hi3 + hi4\n    p = Complex{T}(hi5, hi6)\n    return p\nend\n\n", "meta": {"hexsha": "29529387bf8c4a967a78f06bcd13e792b3568e31", "size": 3351, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/complex.jl", "max_stars_repo_name": "JeffreySarnoff/ErrorfreeArithmetic.jl", "max_stars_repo_head_hexsha": "01fc651ef75ebbdf2d6c4959f32a88779f6bebbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-08-07T17:03:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T11:37:33.000Z", "max_issues_repo_path": "src/complex.jl", "max_issues_repo_name": "JeffreySarnoff/ErrorfreeArithmetic.jl", "max_issues_repo_head_hexsha": "01fc651ef75ebbdf2d6c4959f32a88779f6bebbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2017-04-07T15:19:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-15T03:34:13.000Z", "max_forks_repo_path": "src/complex.jl", "max_forks_repo_name": "JeffreySarnoff/ErrorfreeArithmetic.jl", "max_forks_repo_head_hexsha": "01fc651ef75ebbdf2d6c4959f32a88779f6bebbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2017-04-10T00:18:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:54:51.000Z", "avg_line_length": 31.6132075472, "max_line_length": 80, "alphanum_fraction": 0.6207102358, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574668, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7836759864971623}}
{"text": "\"\"\"\n    lu_decompose(mat)\nDecomposes a `n x n` non singular matrix into a lower triangular matrix (L) and an upper triangular matrix (U)\n\"\"\"\nfunction lu_decompose(mat)\n    n = first(size(mat))\n    L = zeros(n, n)\n    U = zeros(n, n)\n\n    for i in 1:n\n        for j in i:n\n            s = 0\n            for k in 1:i\n                s += L[i, k] * U[k, j]\n            end\n            U[i, j] = mat[i, j] - s\n        end\n\n        for k in i:n\n            if i == k\n                L[i, i] = 1\n            else\n                s = 0\n                for j in 1:i\n                    s += L[k, j] * U[j, i]\n                end\n                L[k, i] = (mat[k, i] - s) / U[i, i]\n            end\n        end\n    end\n\n    return L, U\nend\n", "meta": {"hexsha": "3e0d5cf3c9dbee898fd2325c73d951b7cd436f88", "size": 730, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix/lu_decompose.jl", "max_stars_repo_name": "Whiteshark-314/Julia", "max_stars_repo_head_hexsha": "3285d8d6b7585cc1075831c2c210b891151da0c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-14T21:48:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-14T21:48:50.000Z", "max_issues_repo_path": "src/matrix/lu_decompose.jl", "max_issues_repo_name": "AugustoCL/Julia", "max_issues_repo_head_hexsha": "1bf4e4a7829fafc64290d903bcbfdd48eab839e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix/lu_decompose.jl", "max_forks_repo_name": "AugustoCL/Julia", "max_forks_repo_head_hexsha": "1bf4e4a7829fafc64290d903bcbfdd48eab839e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4705882353, "max_line_length": 110, "alphanum_fraction": 0.3726027397, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.958537730841905, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7836759768139923}}
{"text": "\"\"\"\n    Euler(; h = 0.0) :: ExplicitRungeKuttaSolver\n    ExplicitEuler(args...; kwargs...) :: ExplicitRungeKuttaSolver\n\nreturns an [`ExplicitRungeKuttaSolver`](@ref) for the 1st-order Euler method.\n```\n\"\"\"\nfunction Euler(; h = 0.0)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n        0 0;\n        1 1;\n    ])\n    return ERK(tableau, h)\nend\n@doc (@doc Euler) ExplicitEuler(args...; kwargs...) = Euler(args...; kwargs...)\n\n\"\"\"\n    Heun2(; h = 0.0) :: ExplicitRungeKuttaSolver\n\nreturns an [`ExplicitRungeKuttaSolver`](@ref) for the 2nd-order Heun method.\n\"\"\"\nfunction Heun2(; h = 0.0)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n        0   0   0 ;\n        1   1   0 ;\n        2  1/2 1/2;\n    ])\n    return ERK(tableau, h)\nend\n\n\"\"\"\n    Ralston2(; h = 0.0) :: ExplicitRungeKuttaSolver\n\nreturns an [`ExplicitRungeKuttaSolver`](@ref) for the 2nd-order Ralston method.\n\"\"\"\nfunction Ralston2(; h = 0.0)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n         0   0   0 ;\n        2/3 2/3  0 ;\n         2  1/4 3/4;\n    ])\n    return ERK(tableau, h)\nend\n\n\"\"\"\n    Midpoint(; h = 0.0) :: ExplicitRungeKuttaSolver\n    ExplicitMidpoint(args...; kwargs...) :: ExplicitRungeKuttaSolver\n\nreturns an [`ExplicitRungeKuttaSolver`](@ref) for the 2nd-order midpoint method.\n\"\"\"\nfunction Midpoint(; h = 0.0)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n         0   0   0;\n        1/2 1/2  0;\n         2   0   1;\n    ])\n    return ERK(tableau, h)\nend\n@doc (@doc Midpoint) ExplicitMidpoint(args...; kwargs...) = Midpoint(args...; kwargs...)\n\n\"\"\"\n    Heun3(; h = 0.0) :: ExplicitRungeKuttaSolver\n\nreturns an [`ExplicitRungeKuttaSolver`](@ref) for the 3rd-order Heun method.\n\"\"\"\nfunction Heun3(; h = 0.0)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n         0   0   0   0 ;\n        1/3 1/3  0   0 ;\n        2/3  0  2/3  0 ;\n         3  1/4  0  3/4;\n    ])\n    return ERK(tableau, h)\nend\n\n\"\"\"\n    Kutta3(; h = 0.0) :: ExplicitRungeKuttaSolver\n\nreturns an [`ExplicitRungeKuttaSolver`](@ref) for the 3rd-order Kutta method.\n\"\"\"\nfunction Kutta3(; h = 0.0)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n         0   0   0   0 ;\n        1/2 1/2  0   0 ;\n         1  -1   2   0 ;\n         3  1/6 2/3 1/6;\n    ])\n    return ERK(tableau, h)\nend\n\n\"\"\"\n    Ralston3(; h = 0.0) :: ExplicitRungeKuttaSolver\n\nreturns an [`ExplicitRungeKuttaSolver`](@ref) for the 3rd-order Ralston method.\n\"\"\"\nfunction Ralston3(; h = 0.0)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n         0   0   0   0 ;\n        1/2 1/2  0   0 ;\n        3/4  0  3/4  0 ;\n         3  2/9 1/3 4/9;\n    ])\n    return ERK(tableau, h)\nend\n\n\"\"\"\n    SSPRK3(; h = 0.0) :: ExplicitRungeKuttaSolver\n\nreturns an [`ExplicitRungeKuttaSolver`](@ref) for the 3rd-order Strong-Stability-Preserving Runge-Kutta method.\n\"\"\"\nfunction SSPRK3(; h = 0.0)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n         0   0   0   0 ;\n         1   1   0   0 ;\n        1/2 1/4 1/4  0 ;\n         3  1/6 1/6 2/3;\n    ])\n    return ERK(tableau, h)\nend\n\n\"\"\"\n    RK4(; h = 0.0) :: ExplicitRungeKuttaSolver\n\nreturns an [`ExplicitRungeKuttaSolver`](@ref) for the 4th-order Runge-Kutta method.\n\"\"\"\nfunction RK4(; h = 0.0)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n         0   0   0   0   0 ;\n        1/2 1/2  0   0   0 ;\n        1/2  0  1/2  0   0 ;\n         1   0   0   1   0 ;\n         4  1/6 1/3 1/3 1/6;\n    ])\n    return ERK(tableau, h)\nend\n\n\"\"\"\n    Rule38(; h = 0.0) :: ExplicitRungeKuttaSolver\n\nreturns an [`ExplicitRungeKuttaSolver`](@ref) for the 4th-order 3/8-rule method.\n\"\"\"\nfunction Rule38(; h = 0.0)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n         0    0    0    0    0 ;\n        1/3  1/3   0    0    0 ;\n        2/3 -1/3   1    0    0 ;\n         1    1   -1    1    0 ;\n         4   1/8  3/8  3/8  1/8;\n    ])\n    return ERK(tableau, h)\nend\n\n\"\"\"\n    HeunEuler(; h = 0.0, δ = 0.0, ϵ = 1e-5, K = 100) :: ExplicitRungeKuttaSolver\n\nreturns an [`ExplicitRungeKuttaSolver`](@ref) for the 2nd-order Heun-Euler method with 1st-order error estimate.\n\"\"\"\nfunction HeunEuler(; h = 0.0, δ = 0.0, ϵ = 1e-5, K = 100)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n        0   0   0 ;\n        1   1   0 ;\n        2  1/2 1/2;\n        1   1   0 ;\n    ])\n    adaptive = AdaptiveParameters(δ=δ, ϵ=ϵ, K=K)\n    return ERK(tableau, h, adaptive)\nend\n\n\"\"\"\n    Fehlberg45(; h = 0.0, δ = 0.0, ϵ = 1e-5, K = 100) :: ExplicitRungeKuttaSolver\n    F45(args...; kwargs...) :: ExplicitRungeKuttaSolver\n\nreturns an [`ExplicitRungeKuttaSolver`](@ref) for the 4th-order Fehlberg method with 5th-order error estimate.\n\"\"\"\nfunction Fehlberg45(; h = 0.0, δ = 0.0, ϵ = 1e-5, K = 100)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n          0       0          0          0           0         0    0  ;\n         1/4     1/4         0          0           0         0    0  ;\n         3/8     3/32       9/32        0           0         0    0  ;\n        12/13 1932/2197 -7200/2197  7296/2197       0         0    0  ;\n          1    439/216      -8      3680/513    -845/4104     0    0  ;\n         1/2    -8/27        2     -3544/2565   1859/4104  -11/40  0  ;\n          4     25/216       0      1408/2565   2197/4104   -1/5   0  ;\n          5     16/135       0      6656/12825 28561/56430  -9/50 2/55;\n    ])\n    adaptive = AdaptiveParameters(δ=δ, ϵ=ϵ, K=K)\n    return ERK(tableau, h, adaptive)\nend\n@doc (@doc Fehlberg45) F45(args...; kwargs...) = Fehlberg45(args...; kwargs...)\n\n\"\"\"\n    DormandPrince54(; h = 0.0, δ = 0.0, ϵ = 1e-5, K = 100) :: ExplicitRungeKuttaSolver\n    DP54(args...; kwargs...) :: ExplicitRungeKuttaSolver\n\nreturns an [`ExplicitRungeKuttaSolver`](@ref) for the 5th-order Dormand-Prince method with 4th-order error estimate.\n\"\"\"\nfunction DormandPrince54(; h = 0.0, δ = 0.0, ϵ = 1e-5, K = 100)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n         0        0            0          0          0          0          0      0  ;\n        1/5      1/5           0          0          0          0          0      0  ;\n        3/10     3/40         9/40        0          0          0          0      0  ;\n        4/5     44/45       -56/15      32/9         0          0          0      0  ;\n        8/9  19372/6561  -25360/2187 64448/6561  -212/729       0          0      0  ;\n         1    9017/3168    -355/33   46732/5247    49/176  -5103/18656     0      0  ;\n         1      35/384         0       500/1113   125/192  -2187/6784    11/84    0  ;\n         5      35/384         0       500/1113   125/192  -2187/6784    11/84    0  ;\n         4    5179/57600       0      7571/16695  393/640 -92097/339200 187/2100 1/40;\n    ])\n    adaptive = AdaptiveParameters(δ=δ, ϵ=ϵ, K=K)\n    return ERK(tableau, h, adaptive)\nend\n@doc (@doc DormandPrince54) DP54(args...; kwargs...) = DormandPrince54(args...; kwargs...)\n\n\"\"\"\n    Verner65(; h = 0.0, δ = 0.0, ϵ = 1e-5, K = 100) :: ExplicitRungeKuttaSolver\n    V65(args...; kwargs...) :: ExplicitRungeKuttaSolver\n\nreturns an [`ExplicitRungeKuttaSolver`](@ref) for the 6th-order Verner method with 5th-order error estimate.\n\"\"\"\nfunction Verner65(; h = 0.0, δ = 0.0, ϵ = 1e-5, K = 100)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n         0        0          0         0          0          0       0       0        0   ;\n        1/6      1/6         0         0          0          0       0       0        0   ;\n        4/15     4/75      16/75       0          0          0       0       0        0   ;\n        2/3      5/6       -8/3       5/2         0          0       0       0        0   ;\n        5/6   -165/64      55/6    -425/64      85/96        0       0       0        0   ;\n         1      12/5        -8     4015/612    -11/36      88/255    0       0        0   ;\n        1/15 -8263/15000  124/75   -643/680    -81/250   2484/10625  0       0        0   ;\n         1    3501/1720  -300/43 297275/52632 -319/2322 24068/84065  0   3850/26703   0   ;\n         6       3/40        0      875/2244    23/72     264/1955   0    125/11592 43/616;\n         5      13/160       0     2375/5984     5/16      12/85    3/44     0        0   ;\n    ])\n    adaptive = AdaptiveParameters(δ=δ, ϵ=ϵ, K=K)\n    return ERK(tableau, h, adaptive)\nend\n@doc (@doc Verner65) V65(args...; kwargs...) = Verner65(args...; kwargs...)\n\n\"\"\"\n    BackwardEuler(; h = 0.0, ϵ = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n    ImplicitEuler(args...; kwargs...) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 1st-order backward Euler method.\n\"\"\"\nfunction BackwardEuler(; h = 0.0, ϵ = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n        1 1;\n        1 1;\n    ])\n    newton = NewtonParameters(ϵ=ϵ, K=K)\n    return IRK(tableau, h, newton)\nend\n@doc (@doc BackwardEuler) ImplicitEuler(args...; kwargs...) = BackwardEuler(args...; kwargs...)\n\n\"\"\"\n    ImplicitMidpoint(; h = 0.0, ϵ = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 2nd-order implicit midpoint method.\n\"\"\"\nfunction ImplicitMidpoint(; h = 0.0, ϵ = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n        1/2 1/2;\n         2   1 ;\n    ])\n    newton = NewtonParameters(ϵ=ϵ, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    CrankNicolson(; h = 0.0, ϵ = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 2nd-order Crank-Nicolson method.\n\"\"\"\nfunction CrankNicolson(; h = 0.0, ϵ = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n        0   0   0 ;\n        1  1/2 1/2;\n        2  1/2 1/2;\n    ])\n    newton = NewtonParameters(ϵ=ϵ, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    SDIRK3(; h = 0.0, ϵ = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 3rd-order SDIRK method.\n\"\"\"\nfunction SDIRK3(; h = 0.0, ϵ = 1e-3, K = 10)\n    γ = 1/2 + √3/6\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n         γ    γ   0 ;\n        1-γ 1-2γ  γ ;\n         3   1/2 1/2;\n    ])\n    newton = NewtonParameters(ϵ=ϵ, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    GaussLegendre4(; h = 0.0, ϵ = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n    GL4(args...; kwargs...) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 4th-order Gauss-Legendre method.\n\"\"\"\nfunction GaussLegendre4(; h = 0.0, ϵ = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n        1/2-√3/6   1/4    1/4-√3/6;\n        1/2+√3/6 1/4+√3/6   1/4   ;\n           4       1/2      1/2   ;\n    ])\n    newton = NewtonParameters(ϵ=ϵ, K=K)\n    return IRK(tableau, h, newton)\nend\n@doc (@doc GaussLegendre4) GL4(args...; kwargs...) = GaussLegendre4(args...; kwargs...)\n\n\"\"\"\n    GaussLegendre6(; h = 0.0, ϵ = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n    GL6(args...; kwargs...) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 6th-order Gauss–Legendre method.\n\"\"\"\nfunction GaussLegendre6(; h = 0.0, ϵ = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n        1/2-√15/10     5/36    2/9-√15/15 5/36-√15/30;\n           1/2     5/36+√15/24    2/9     5/36-√15/24;\n        1/2+√15/10 5/36+√15/30 2/9+√15/15     5/36   ;\n            6          5/18       4/9         5/18   ;\n    ])\n    newton = NewtonParameters(ϵ=ϵ, K=K)\n    return IRK(tableau, h, newton)\nend\n@doc (@doc GaussLegendre6) GL6(args...; kwargs...) = GaussLegendre6(args...; kwargs...)\n\n\"\"\"\n    LobattoIIIA4(; h = 0.0, ϵ = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 4th-order Lobatto IIIA method.\n\"\"\"\nfunction LobattoIIIA4(; h = 0.0, ϵ = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n         0   0    0    0  ;\n        1/2 5/24 1/3 -1/24;\n         1  1/6  2/3  1/6 ;\n         4  1/6  2/3  1/6 ;\n    ])\n    newton = NewtonParameters(ϵ=ϵ, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    LobattoIIIB2(; h = 0.0, ϵ = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 2nd-order Lobatto IIIB method.\n\"\"\"\nfunction LobattoIIIB2(; h = 0.0, ϵ = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n        1/2 1/2  0 ;\n        1/2 1/2  0 ;\n         2  1/2 1/2;\n    ])\n    newton = NewtonParameters(ϵ=ϵ, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    LobattoIIIB4(; h = 0.0, ϵ = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 4th-order Lobatto IIIB method.\n\"\"\"\nfunction LobattoIIIB4(; h = 0.0, ϵ = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n         0  1/6 -1/6  0 ;\n        1/2 1/6  1/3  0 ;\n         1  1/6  5/6  0 ;\n         4  1/6  2/3 1/6;\n    ])\n    newton = NewtonParameters(ϵ=ϵ, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    LobattoIIIC2(; h = 0.0, ϵ = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 2nd-order Lobatto IIIC method.\n\"\"\"\nfunction LobattoIIIC2(; h = 0.0, ϵ = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n        0  1/2 -1/2;\n        1  1/2  1/2;\n        2  1/2  1/2;\n    ])\n    newton = NewtonParameters(ϵ=ϵ, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    LobattoIIIC4(; h = 0.0, ϵ = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 4th-order Lobatto IIIC method.\n\"\"\"\nfunction LobattoIIIC4(; h = 0.0, ϵ = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n         0   1/6 -1/3   1/6 ;\n        1/2  1/6  5/12 -1/12;\n         1   1/6  2/3   1/6 ;\n         4   1/6  2/3   1/6 ;\n    ])\n    newton = NewtonParameters(ϵ=ϵ, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    RadauIA3(; h = 0.0, ϵ = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 3rd-order Radau IA method.\n\"\"\"\nfunction RadauIA3(; h = 0.0, ϵ = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n         0  1/4 -1/4 ;\n        2/3 1/4  5/12;\n         3  1/4  3/4 ;\n    ])\n    newton = NewtonParameters(ϵ=ϵ, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    RadauIA5(; h = 0.0, ϵ = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 5th-order Radau IA method.\n\"\"\"\nfunction RadauIA5(; h = 0.0, ϵ = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n            0     1/9   -1/18-√6/18     -1/18+√6/18  ;\n        3/5-√6/10 1/9  11/45+7*√6/360 11/45-43*√6/360;\n        3/5+√6/10 1/9 11/45+43*√6/360  11/45-7*√6/360;\n            5     1/9    4/9+√6/36       4/9-√6/36   ;\n    ])\n    newton = NewtonParameters(ϵ=ϵ, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    RadauIIA3(; h = 0.0, ϵ = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 3rd-order Radau IIA method.\n\"\"\"\nfunction RadauIIA3(; h = 0.0, ϵ = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n        1/3  5/12 -1/12;\n         1   3/4   1/4 ;\n         3   3/4   1/4 ;\n    ])\n    newton = NewtonParameters(ϵ=ϵ, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    RadauIIA5(; h = 0.0, ϵ = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 5th-order Radau IIA method.\n\"\"\"\nfunction RadauIIA5(; h = 0.0, ϵ = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n        2/5-√6/10   11/45-7*√6/360   37/225-169*√6/1800 -2/225+√6/75;\n        2/5+√6/10 37/225+169*√6/1800   11/45+7*√6/360   -2/225-√6/75;\n           1           4/9-√6/36          4/9+√6/36          1/9    ;\n           5           4/9-√6/36          4/9+√6/36          1/9    ;\n    ])\n    newton = NewtonParameters(ϵ=ϵ, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    ExponentialRK4(; h = 0.0) :: ExplicitExponentialRungeKuttaSolver\n\nreturns an [`ExplicitExponentialRungeKuttaSolver`](@ref) for the 4th-order EERK method.\n\"\"\"\nfunction ExponentialRK4(; h = 0.0)\n    return EERK(h)\nend\n@doc (@doc ExponentialRK4) ERK4(args...; kwargs...) = ExponentialRK4(args...; kwargs...)\n", "meta": {"hexsha": "c927feb8779ce353df477b991f64b95b4ad6561f", "size": 16056, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/methods.jl", "max_stars_repo_name": "antonuccig/RungeKutta.jl", "max_stars_repo_head_hexsha": "7476b73367240e17776dc56613bb6ce69f9448bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-30T17:45:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T17:45:14.000Z", "max_issues_repo_path": "src/methods.jl", "max_issues_repo_name": "antonuccig/RungeKutta.jl", "max_issues_repo_head_hexsha": "7476b73367240e17776dc56613bb6ce69f9448bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/methods.jl", "max_forks_repo_name": "antonuccig/RungeKutta.jl", "max_forks_repo_head_hexsha": "7476b73367240e17776dc56613bb6ce69f9448bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.359375, "max_line_length": 116, "alphanum_fraction": 0.5280269058, "num_tokens": 6612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8947894731166139, "lm_q1q2_score": 0.7836449750171998}}
{"text": "using NLsolve, LinearAlgebra\n\"\"\"\n`Base.length(tab::ODERKTableau)`\n\nDefines the length of a Runge-Kutta method to be the number of stages.\n\"\"\"\nBase.length(tab::ODERKTableau) = tab.stages\n\n\"\"\"\n`stability_region(z,tab::ODERKTableau)`\n\nCalculates the stability function from the tableau at `z`. Stable if <1.\n\n```math\nr(z) = \\\\frac{\\\\det(I-zA+zeb^T)}{\\\\det(I-zA)}\n```\n\"\"\"\nstability_region(z,tab::ODERKTableau) = det(Matrix{Float64}(I,tab.stages,tab.stages)- z*tab.A + z*ones(tab.stages)*tab.α')/det(Matrix{Float64}(I,tab.stages,tab.stages)-z*tab.A)\n\n\"\"\"\n`stability_region(tab::ODERKTableau; initial_guess=-3.0)`\n\nCalculates the length of the stability region in the real axis.\n\"\"\"\nfunction stability_region(tab::ODERKTableau; initial_guess=-3.0)\n  residual! = function (resid, x)\n    resid[1] = abs(stability_region(x[1], tab)) - 1\n  end\n  sol = nlsolve(residual!, [initial_guess])\n  sol.zero[1]\nend\n", "meta": {"hexsha": "43ad9666cc8d669d5a3f02314847da148dc97a5b", "size": 896, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tableau_info.jl", "max_stars_repo_name": "UnofficialJuliaMirror/DiffEqDevTools.jl-f3b72e0c-5b89-59e1-b016-84e28bfd966d", "max_stars_repo_head_hexsha": "a5817aef74fab74186db4fcdf893746f6ef52b24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tableau_info.jl", "max_issues_repo_name": "UnofficialJuliaMirror/DiffEqDevTools.jl-f3b72e0c-5b89-59e1-b016-84e28bfd966d", "max_issues_repo_head_hexsha": "a5817aef74fab74186db4fcdf893746f6ef52b24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tableau_info.jl", "max_forks_repo_name": "UnofficialJuliaMirror/DiffEqDevTools.jl-f3b72e0c-5b89-59e1-b016-84e28bfd966d", "max_forks_repo_head_hexsha": "a5817aef74fab74186db4fcdf893746f6ef52b24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0, "max_line_length": 176, "alphanum_fraction": 0.7075892857, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8479677545357569, "lm_q1q2_score": 0.783642467503213}}
{"text": "# # clip-06-10.jl\n\n# Load Julia packages (libraries) needed  for the snippets in chapter 0\n\nusing StatisticalRethinking, Optim\n#gr(size=(600,600));\n\n# ### snippet 3.2\n\np_grid = range(0, step=0.001, stop=1)\nprior = ones(length(p_grid))\nlikelihood = [pdf(Binomial(9, p), 6) for p in p_grid]\nposterior = likelihood .* prior\nposterior = posterior / sum(posterior)\n\n# ### snippet 3.3\n# Draw 10000 samples from this posterior distribution\n\nN = 10000\nsamples = sample(p_grid, Weights(posterior), N);\n\n# In StatisticalRethinkingJulia samples will always be stored\n# in an MCMCChains.Chains object. \n\nchn = MCMCChains.Chains(reshape(samples, N, 1, 1), [\"toss\"]);\n\n# Describe the chain\n\nMCMCChains.describe(chn)\n\n# ### snippet 3.6\n\nv = 0.0\nfor i in 1:length(p_grid)\n  global v\n  if p_grid[i] < 0.5\n    v += posterior[i]\n  end\nend\nv\n\n# ### snippet 3.7\n\nmapreduce(p -> p < 0.5 ? 1 : 0, +, samples) / N   |> display\n\n# ### snippet 3.8\n\nmapreduce(p -> (p > 0.5 && p < 0.75) ? 1 : 0, +, samples) / N   |> display\n\n# ### snippet 3.9\n\nquantile(samples, 0.8) \n\n# ### snippet 3.10\n\nquantile(samples, [0.1, 0.9])\n\n# End of `03/clip-06-10.jl`", "meta": {"hexsha": "7981bc77d87f75777be7daebe234dd8813898c05", "size": 1121, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/03/clip-06-10.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_stars_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/03/clip-06-10.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_issues_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/03/clip-06-10.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_forks_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3275862069, "max_line_length": 74, "alphanum_fraction": 0.6485280999, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.868826784729373, "lm_q1q2_score": 0.7836128437605948}}
{"text": "# indicator of an affine set\n\nusing LinearAlgebra\nusing SparseArrays\nusing SuiteSparse\n\nexport IndAffine\n\n### ABSTRACT TYPE\n\nabstract type IndAffine <: ProximableFunction end\n\nis_affine(f::IndAffine) = true\nis_generalized_quadratic(f::IndAffine) = true\n\nfun_name(f::IndAffine) = \"Indicator of an affine subspace\"\n\n### CONSTRUCTORS\n\n\"\"\"\n**Indicator of an affine subspace**\n\n    IndAffine(A, b; iterative=false)\n\nIf `A` is a matrix (dense or sparse) and `b` is a vector, returns the indicator function of the set\n```math\nS = \\\\{x : Ax = b\\\\}.\n```\nIf `A` is a vector and `b` is a scalar, returns the indicator function of the set\n```math\nS = \\\\{x : \\\\langle A, x \\\\rangle = b\\\\}.\n```\nBy default, a direct method (QR factorization of matrix `A'`) is used to evaluate `prox!`.\nIf `iterative=true`, then `prox!` is evaluated approximately using an iterative method instead.\n\"\"\"\nfunction IndAffine(A::M, b::V; iterative=false) where {M, V}\n    if iterative == false\n        IndAffineDirect(A, b)\n    else\n        IndAffineIterative(A, b)\n    end\nend\n\n### INCLUDE CONCRETE TYPES\n\nusing LinearAlgebra\nusing SparseArrays\nusing SuiteSparse\n\ninclude(\"indAffineDirect.jl\")\ninclude(\"indAffineIterative.jl\")\n", "meta": {"hexsha": "9b4c0257e6e6b7abb62e1cfb3877bad25ef7b15c", "size": 1193, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indAffine.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_stars_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2016-10-29T12:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:11:52.000Z", "max_issues_repo_path": "src/functions/indAffine.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_issues_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2016-10-26T16:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T20:38:48.000Z", "max_forks_repo_path": "src/functions/indAffine.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_forks_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T10:40:24.000Z", "avg_line_length": 22.9423076923, "max_line_length": 99, "alphanum_fraction": 0.7074601844, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.78360699649024}}
{"text": "\"\"\"\r\n    newton(x, xd, yd)\r\nadalah fungsi yang digunakan untuk mencari nilai interpolasi pada titik/vektor `x`, jika\r\ndiketahui suatu himpunan pasangan terurut `(xd,yd)`.\r\n\r\n# Example\r\n```jl\r\njulia> xd = [1,2,3,5];\r\n\r\njulia> yd = [1.06 1.12 1.34 1.78];\r\n\r\njulia> y,D = newton(4,xd,yd);\r\n\r\njulia> y\r\n1.6\r\n\r\njulia> D\r\n4×4 Array{Float64,2}:\r\n 1.06  0.0   0.0    0.0\r\n 1.12  0.06  0.0    0.0\r\n 1.34  0.22  0.08   0.0\r\n 1.78  0.22  0.0   -0.02\r\n```\r\nreturn solusi hampiran interpolasi `y` dan matriks beda-terbagi `D`.\r\n\"\"\"\r\nfunction newton(x, xd, yd)\r\n  m=length(x);\r\n  y=zeros(m)\r\n  if m > 1\r\n    for i=1:m\r\n      # proses satu titik demi satu titik\r\n      y[i],D =newton(x[i], xd, yd);\r\n    end\r\n    return y,D\r\n  end\r\n  #% periksa jumlah titik dan tentukan derajat polinom\r\n  ntitik = length(xd);\r\n  #% hitung tabel beda-terbagi (divided-difference)\r\n  D = zeros(ntitik,ntitik)\r\n  D[:,1]=yd;          #% kolom pertama\r\n  for j=2:ntitik      #% kolom ke-2 dan seterusnya\r\n    for k=j:ntitik\r\n        D[k,j] = (D[k,j-1]-D[k-1,j-1])/(xd[k]-xd[k-j+1]);\r\n    end\r\n  end\r\n  #% hitung interpolasi Newton\r\n  y = D[1,1]; s = 1;\r\n  for i=2:ntitik\r\n    s = s * (x-xd[i-1]);\r\n    y = y + D[i,i]*s;\r\n  end\r\n  return y, D\r\nend\r\n", "meta": {"hexsha": "d0c3e2abbfcca441cafa9e1be05100a0fa0df1b7", "size": 1213, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/newton.jl", "max_stars_repo_name": "mkhoirun-najiboi/metnum.jl", "max_stars_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/newton.jl", "max_issues_repo_name": "mkhoirun-najiboi/metnum.jl", "max_issues_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/newton.jl", "max_forks_repo_name": "mkhoirun-najiboi/metnum.jl", "max_forks_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.462962963, "max_line_length": 89, "alphanum_fraction": 0.5548227535, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7836069769338637}}
{"text": "const TRANSITION = [1.0 1.0; 0.0 1.0]\nconst POS_NOISE = 1.5\nconst NOISE = [POS_NOISE 0.0; 0.0 sqrt(2)*POS_NOISE]\nconst PREDICT_NOISE = [0.1 0.0; 0.0 0.3]\n\nstruct State\n    p::Float64\n    v::Float64\n    Σ::Array{Float64, 2}\nend\nState(p, v) = State(p, v, NOISE)\n\nfunction predict(s::State, noise=PREDICT_NOISE)\n    p, v = TRANSITION * [s.p ; s.v]\n    Σ = TRANSITION * s.Σ * TRANSITION' + noise\n    State(p, v, Σ)\nend\n\nfunction update(predicted::State, observed::State)\n    K = predicted.Σ / (predicted.Σ + observed.Σ)\n    # x = [predicted.p ; predicted.v]\n    # z = [observed.p; observed.v]\n    # p, v = x + K * (z - x)\n    p = observed.p\n    v = observed.v\n    Σ = predicted.Σ - K * predicted.Σ\n    State(p, v, Σ)\nend\n\nfunction smoothed_velocity_estimate(old::State, new::State, λ)\n    diff = new.p - old.p\n    scale = λ\n    #scale = 1.0 - 0.5 * (1 - λ) * (1 + 1.0 / sqrt(2π * old.Σ[2, 2]^2))\n    return scale * diff + (1 - scale) * old.v\nend\n\nfunction pdf(s::State, p::Float64)\n    σ = s.Σ[1, 1]\n    exp(-((s.p - p)^2) / (2σ^2)) / (sqrt(2π * σ^2))\nend\n", "meta": {"hexsha": "0719e1ebb16c0e837619ccdba7cd47c10b045eb9", "size": 1052, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Kalman.jl", "max_stars_repo_name": "safnuk/ObjectTracker.jl", "max_stars_repo_head_hexsha": "fb6b6ee075faa5476a6c2f343866e1c360c8dee5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Kalman.jl", "max_issues_repo_name": "safnuk/ObjectTracker.jl", "max_issues_repo_head_hexsha": "fb6b6ee075faa5476a6c2f343866e1c360c8dee5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Kalman.jl", "max_forks_repo_name": "safnuk/ObjectTracker.jl", "max_forks_repo_head_hexsha": "fb6b6ee075faa5476a6c2f343866e1c360c8dee5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6585365854, "max_line_length": 71, "alphanum_fraction": 0.5741444867, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251321, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7835776734249343}}
{"text": "## activate package environment\ncd(@__DIR__)\nusing Pkg\nPkg.activate(\"Project.toml\")\n\n## parameters (calculation for perpendicular incident)\nλ = 520 # nm\nN = [1.0; 3.812 + 0.1903im; 4.1891+0.3633im] # air - window layer - absorber layer\nD = 100 # thickness of window layer\n# (refractive indices are from https://refractiveindex.info/, data by Aspnes 1986)\n\n## function for fresnel coefficients (for perpendicular incident)\nfunction fresnel_coeff(n,m,pol)\n    if pol == \"s\"\n        r = (n-m)/(n+m)\n        t = (2*n)/(n+m)\n    elseif pol == \"p\"\n        r = (m-n)/(m+n)\n        t = (2*n)/(m+n)\n    end\n    return r,t\nend\n\n## function for interface propagation matrix\nfunction interface_prop(n,m,pol)\n    r,t = fresnel_coeff(n,m,pol)\n    I = 1/t * [1 r;r 1]\n    return I\nend\n\n## function for propagation through film Matrix\nfunction film_prop(d,n)\n    beta = 2*pi*d*n/λ\n    L = [exp(-1im*beta) 0; 0 exp(1im*beta)]\n    return L\nend\n\n## calcuation of scattering matrix\n# Emanuele Centurioni: Generalized matrix method for calculation of internal light energy flux\n# in mixed coherent and incoherent multilayers\nSs = interface_prop(N[1],N[2],\"s\") * film_prop(D,N[2]) * interface_prop(N[2],N[3],\"s\")\nSp = interface_prop(N[1],N[2],\"p\") * film_prop(D,N[2]) * interface_prop(N[2],N[3],\"p\")\n\n## backside transmittance\nTs = abs2(1/Ss[1,1])*real(N[3])/real(N[1])\nTp = abs2(1/Ss[1,1])*real(conj(N[3]))/real(N[1])\nT  = round((Ts+Tp)/2,sigdigits=4)\n\n## ouput result\nprintln(\"\")\nprintln(\"transmission into absorber T = $T\")\n", "meta": {"hexsha": "3a72a15f67745eae8c8db671303a471336226ef5", "size": 1505, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Code/transm_calc.jl", "max_stars_repo_name": "MaxGrossmann/TRPL", "max_stars_repo_head_hexsha": "b27bc01299502e09b997e52da0842edfb7dd61fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/transm_calc.jl", "max_issues_repo_name": "MaxGrossmann/TRPL", "max_issues_repo_head_hexsha": "b27bc01299502e09b997e52da0842edfb7dd61fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/transm_calc.jl", "max_forks_repo_name": "MaxGrossmann/TRPL", "max_forks_repo_head_hexsha": "b27bc01299502e09b997e52da0842edfb7dd61fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9423076923, "max_line_length": 94, "alphanum_fraction": 0.6544850498, "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109784205502, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7835776722669101}}
{"text": "\"\"\"\nCalculates Bézout coefficients (see `gcdx`)\n\"\"\"\nfunction bezout(a::R, b::R) where {R}\n    rev = a < b\n    x, y = rev ? (a,b) : (b,a)\n\n    s0, s1 = oneunit(R), zero(R)\n    t0, t1 = zero(R), oneunit(R)\n\n    while y != zero(R)\n        q = div(x, y)\n        x, y = y, x - y * q\n        s0, s1 = s1, s0 - q * s1\n        t0, t1 = t1, t0 - q * t1\n    end\n\n    s, t = rev ? (s0, t0) : (t0, s0)\n    g = x\n\n    if g == a\n        s = one(R)\n        t = zero(R)\n    elseif g == -a\n        s = -one(R)\n        t = zero(R)\n    end\n\n    return s, t, g\nend\n", "meta": {"hexsha": "6c553eeade9f96eeee0e4ab050c3f5c070574a7e", "size": 545, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SmithNormalForm/src/bezout.jl", "max_stars_repo_name": "kevseryolcu/PolyhedralOmega", "max_stars_repo_head_hexsha": "6781a293cceefc88a333c82145aa59cd22ee7581", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-08-12T22:25:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T03:34:48.000Z", "max_issues_repo_path": "src/SmithNormalForm/src/bezout.jl", "max_issues_repo_name": "kevseryolcu/PolyhedralOmega", "max_issues_repo_head_hexsha": "6781a293cceefc88a333c82145aa59cd22ee7581", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-08-19T16:52:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-09T15:52:09.000Z", "max_forks_repo_path": "src/SmithNormalForm/src/bezout.jl", "max_forks_repo_name": "kevseryolcu/PolyhedralOmega", "max_forks_repo_head_hexsha": "6781a293cceefc88a333c82145aa59cd22ee7581", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-01-07T17:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T11:39:15.000Z", "avg_line_length": 17.5806451613, "max_line_length": 43, "alphanum_fraction": 0.4018348624, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410982634296, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7835776716417417}}
{"text": "using Revise\nusing AdFem\nusing PyPlot \n\n# forward computation\nmmesh = Meh(joinpath(PDATA, \"twoholes_large.stl\"))\nxy = gauss_nodes(mmesh)\nκ = @. sin(xy[:,1]) * (1+xy[:,2]^2) + 1.0\nf = 1e5 * @. xy[:,1] + xy[:,2]\nK = compute_fem_laplace_matrix1(κ, mmesh)\nF = compute_fem_source_term1(f, mmesh)\nbdnode = bcnode(mmesh)\nK, F = impose_Dirichlet_boundary_conditions(K, F, bdnode, zeros(length(bdnode)))\nsol = K\\F\n\n# inverse modeling \nnn_κ = squeeze(fc(xy, [20,20,20,1])) + 1\nK = compute_fem_laplace_matrix1(nn_κ, mmesh)\nF = compute_fem_source_term1(f, mmesh)\nbdnode = bcnode(mmesh)\nK, F = impose_Dirichlet_boundary_conditions(K, F, bdnode, zeros(length(bdnode)))\nnn_sol = K\\F\nloss = sum((nn_sol - sol)^2)\n\nsess = Session(); init(sess)\nBFGS!(sess, loss)\n\nnn_val = run(sess, nn_κ)\nclose(\"all\")\nfigure(figsize=(18,5))\nsubplot(131)\nvisualize_scalar_on_gauss_points(κ, mmesh)\ntitle(\"Reference\")\nsubplot(132)\nvisualize_scalar_on_gauss_points(nn_val, mmesh)\ntitle(\"DNN\")\nsubplot(133)\nvisualize_scalar_on_gauss_points(abs.(κ-nn_val), mmesh)\ntitle(\"Absolute Difference\")\nsavefig(\"poisson_kappa.png\")\nclose(\"all\")\nvisualize_scalar_on_fem_points(sol, mmesh)\nsavefig(\"poisson_solution.png\")", "meta": {"hexsha": "9f0597d79a4230a2582a93130ffb713e7828a11b", "size": 1170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/codes/Poisson/inverse.jl", "max_stars_repo_name": "kailaix/AdFem.jl", "max_stars_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2020-10-18T01:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:13:24.000Z", "max_issues_repo_path": "docs/src/codes/Poisson/inverse.jl", "max_issues_repo_name": "kailaix/AdFem.jl", "max_issues_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-10-19T03:51:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:38:46.000Z", "max_forks_repo_path": "docs/src/codes/Poisson/inverse.jl", "max_forks_repo_name": "kailaix/AdFem.jl", "max_forks_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-11-05T11:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T19:30:09.000Z", "avg_line_length": 27.2093023256, "max_line_length": 80, "alphanum_fraction": 0.7358974359, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068041, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7835776646935956}}
{"text": "function binomial_coeffs(n::Integer)::Vector{Int}\n    if n == 1\n        return [1]\n    end\n    if n == 2\n        return [1, 1]\n    end\n    c = [1, 1]\n    for _ in 3:n\n        c=[1, (view(c[1:end-1]) .+ view(c[2:end])), 1] \n    end\n    return c\nend\n\nfunction binomial_coeffs_2(n::Integer)\n    if n == 1\n        return [1]\n    end\n    if n == 2\n        return [1, 1]\n    end\n    c = [1 , 1]\n    m = 2\n    for _ in 3:n\n        for i in 1:(m - 1)\n            c[i] = c[i] + c[i+1]\n            m += 1\n        end\n        pushfirst!(c, 1)\n    end\n    return c\nend", "meta": {"hexsha": "59755b14faef01b68a9f4e9f3a1de7441508f7ae", "size": 556, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "task_6_4.jl", "max_stars_repo_name": "Litger45/julia-algorithms-2", "max_stars_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "task_6_4.jl", "max_issues_repo_name": "Litger45/julia-algorithms-2", "max_issues_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "task_6_4.jl", "max_forks_repo_name": "Litger45/julia-algorithms-2", "max_forks_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.375, "max_line_length": 55, "alphanum_fraction": 0.4226618705, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849805, "lm_q2_score": 0.8519528057272544, "lm_q1q2_score": 0.7834920403320467}}
{"text": "export nullspacex\n\n\"\"\"\n`nullspacex(A)` returns an exact basis for the matrix `A`\n\"\"\"\nfunction nullspacex(A::AbstractMatrix{T}) where {T}\n    r, c = size(A)\n    B = rrefx(A)\n\n    leads = Int[]\n    # in each row, find first 1\n    for i = 1:r\n        row = B[i, :]\n        if all(row .== 0)\n            continue\n        end\n        k = findfirst(row .!= 0)\n        append!(leads, k)\n    end\n\n    frees = setdiff(collect(1:c), leads)\n\n\n    result = Matrix{T}(undef, c, 0)\n    for f in frees\n        v = zeros(T, c)\n        v[f] = T(1)\n        for i = 1:length(leads)\n            l = leads[i]  # (i,l) is a leading 1\n            if l < f\n                v[l] = -B[i, f]\n            end\n        end\n        result = [result v]\n    end\n    return result\nend\n\n\nfunction nullspacex(A::AbstractMatrix{T}) where {T<:IntegerX}\n    return nullspacex(big.(A) // 1)\nend\n", "meta": {"hexsha": "03f0a6c2d76440399f0b06da1d9540be3bbebca5", "size": 855, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nullspacex.jl", "max_stars_repo_name": "scheinerman/LinearAlgebraX.jl", "max_stars_repo_head_hexsha": "ccb34ba16fc11eb72b6f3ff624bd02310ff69d8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2020-08-04T09:50:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:10:44.000Z", "max_issues_repo_path": "src/nullspacex.jl", "max_issues_repo_name": "scheinerman/LinearAlgebraX.jl", "max_issues_repo_head_hexsha": "ccb34ba16fc11eb72b6f3ff624bd02310ff69d8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-08-04T11:11:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T12:11:30.000Z", "max_forks_repo_path": "src/nullspacex.jl", "max_forks_repo_name": "scheinerman/LinearAlgebraX.jl", "max_forks_repo_head_hexsha": "ccb34ba16fc11eb72b6f3ff624bd02310ff69d8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-08-04T09:53:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-25T20:37:06.000Z", "avg_line_length": 19.8837209302, "max_line_length": 61, "alphanum_fraction": 0.4947368421, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.7834920279371604}}
{"text": "const brown_dennis = let res_init=zeros(20), jac_init=zeros(20,4), x_init=[25., 5., -5., -1.]\n\n    function res(x, r)\n        n = length(r)\n        for i = 1:n\n            ti = 0.2e0 * Float64(i)\n            r[i] = (x[1] + x[2] * ti - exp(ti)) ^ 2 +\n                (x[3] + x[4] * sin(ti) - cos(ti))^2\n        end\n        return r\n    end\n\n    function jac(x, j)\n        n = size(j)[1]\n        for i = 1:n\n            ti = 0.2e0 * Float64(i)\n            j[i, 1] = 2.0e0 * (x[1] + x[2]*ti - exp(ti))\n            j[i, 2] = ti * j[i, 1]\n            t = sin(ti)\n            j[i, 3] = 2.0e0 *(x[3] + x[4]*t - cos(ti))\n            j[i, 4] = t * j[i, 3]\n        end\n        return j\n    end\n\n    f(;scale=1, verbose=false, print_steps=false) = testone(\"brown_dennis\", res, jac,\n                                                            res_init, jac_init, x_init;\n                                                            scale=scale, verbose=verbose,\n                                                            print_steps=print_steps)\nend\n", "meta": {"hexsha": "956d69f87d40efe678eee109f5537f7c4043c717", "size": 1038, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/optests/brown_dennis.jl", "max_stars_repo_name": "macd/NL2sol.jl", "max_stars_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-01-19T21:59:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T00:42:56.000Z", "max_issues_repo_path": "test/optests/brown_dennis.jl", "max_issues_repo_name": "macd/NL2sol.jl", "max_issues_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/optests/brown_dennis.jl", "max_forks_repo_name": "macd/NL2sol.jl", "max_forks_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4838709677, "max_line_length": 93, "alphanum_fraction": 0.3709055877, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682086, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7834920220123578}}
{"text": "function calculate_pi(NBIN::Int= 1000000000)::Float64\n    step = 1/NBIN\n    sum = 0\n    for i=1:NBIN\n        x = (i+0.5)*step;\n        sum += 4 / (1 + x^2)\n    end\n    pi = sum*step\n    return pi\nend\n\nif length(ARGS)>0\n    @time @show calculate_pi(parse(Int, ARGS[1]))\nelse\n    @time @show calculate_pi()\nend\n", "meta": {"hexsha": "fa0bb1fe1dc55bc6a76c44c19fc96f243aa85b74", "size": 309, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "performance_test/pi_test/pi.jl", "max_stars_repo_name": "naezzell/accelqat", "max_stars_repo_head_hexsha": "387c9789c08505349c2a3c8d7c0e6b6008d72705", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-02T23:23:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-02T23:23:56.000Z", "max_issues_repo_path": "performance_test/pi_test/pi.jl", "max_issues_repo_name": "naezzell/accelqat", "max_issues_repo_head_hexsha": "387c9789c08505349c2a3c8d7c0e6b6008d72705", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-30T09:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-09T01:21:37.000Z", "max_forks_repo_path": "performance_test/pi_test/pi.jl", "max_forks_repo_name": "naezzell/accelqat", "max_forks_repo_head_hexsha": "387c9789c08505349c2a3c8d7c0e6b6008d72705", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.1764705882, "max_line_length": 53, "alphanum_fraction": 0.572815534, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7834796439039863}}
{"text": "# //  This is a gear train design problem taken from the GAMS test library\n# //\n# //  A compound gear train is to be designed to achieve a specific\n# //  gear ratio between the driver and driven shafts. The objective\n# //  of the gear train design is to find the number of teeth of the\n# //  four gears and to obtain a required gear ratio of 1/6.931.\n# //\n# //  The problem originated from:\n# //  Deb, K, and Goyal, M, Optimizing Engineering Designs Using a\n# //  Combined Genetic Search. In Back, T, Ed, Proceedings of the\n# //  Seventh International Conference on Genetic Algorithms. 1997,\n# //  pp. 521-528.\n\nfunction gear(oct::Bool = false)\n    m = JuMP.Model()\n    @variable(m, 12 <= i[1:4] <= 60, Int)\n    for j = 1:4\n        JuMP.set_start_value(i[j], 24)\n    end\n    @constraint(m, e2, - i[3] + i[4] >= 0)\n    @constraint(m, e3, i[1] - i[2] >= 0)\n    if !oct\n        @NLobjective(m, Min, (6.931 - i[1]*i[2]/(i[3]*i[4]))^2 + 1)\n        return m\n    else\n        @variable(m, obj)\n        @objective(m, Min, obj)\n        gm = GlobalModel(model = m, name = \"gear\")\n        add_nonlinear_constraint(gm, :((i) -> (6.931 - i[1]*i[2]/(i[3]*i[4]))^2 + 1), dependent_var = obj)\n        return gm\n    end\nend", "meta": {"hexsha": "d29dc0065f50ed9e8b3939fa7f0d7035f8c8b58c", "size": 1206, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "data/baron/gear.jl", "max_stars_repo_name": "1ozturkbe/OCTHaGOn.jl", "max_stars_repo_head_hexsha": "222a73c8da834c8e4114b6f29492d8ab917f6722", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data/baron/gear.jl", "max_issues_repo_name": "1ozturkbe/OCTHaGOn.jl", "max_issues_repo_head_hexsha": "222a73c8da834c8e4114b6f29492d8ab917f6722", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2022-02-13T15:33:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T15:45:11.000Z", "max_forks_repo_path": "data/baron/gear.jl", "max_forks_repo_name": "1ozturkbe/OCTHaGOn.jl", "max_forks_repo_head_hexsha": "222a73c8da834c8e4114b6f29492d8ab917f6722", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6875, "max_line_length": 106, "alphanum_fraction": 0.5986733002, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7834796433005184}}
{"text": "using Measurements\nusing Printf\n\nprintstyled(\"\\nExperimento 1: Capacidade térmica\\n\", color =:blue);\n\n# em gramas\nΔm = 0.01;\nmcopo = 51.82;\nmaq = 122.07;\nmaf = 125.02;\n\n# em graus celsius\nΔT = 0.1;\ntaf = 12.4;\ntaq = 53.2;\ntf = 31.4;\n\n# calor especifico da água\nca = 1; \n@printf(\"%.3f · %.3f ( %.3f - %.3f) / (%.3f - %.3f) - %.3f · %.3f \\n\", maq,ca,taq,tf,tf,taf,maf,ca);\nC = maq * ca * ( (taq - tf) / (tf - taf) ) - maf * ca;\n\nΔC = ((Δm * taq + ΔT * maq) * (tf - taf) + (2 * ΔT) * (maq * taq) ) / (tf - taf)^2\n\nprintln(\"\\nCapacidade térmica do calorimetro\");\n@printf(\"Ccal = %.2f ± %.2f \\n\", C, ΔC);\n\n# em grama \nmcopo = 51.82 ±  Δm;\ncAluminio = 0.218; \nCcopo =  mcopo * cAluminio;\n\nprintln(\"\\nCapacidade térmica do copo\");\n@printf(\"Ccopo = %.3f ± %0.3f \\n\", Ccopo.val, Ccopo.err);\n\n\nprintln(\"\\nRelação de equivalência\");\n@printf(\"| x1 - x2 | < 2 · (σ1 + σ2) \\n\");\n@printf(\"| %.3f - %.3f| < 2 · (%.3f + %.3f) \\n\", C,Ccopo.val,ΔC,Ccopo.err);\nprintln(abs(C - Ccopo.val) < 2 * (ΔC + Ccopo.err));\n\n\nprintstyled(\"\\nExperimento 2: Calor específico de um metal  \", color =:blue);\n\n# em gramas \nmobjeto = 205.75 ± Δm;\nma = 216.07 ± Δm;     \n\n# em graus celsius\nta = 13.1 ± ΔT;\nto = 97.1 ± ΔT;\ntf = 19.2 ± ΔT;\n\n\nco = ((ma * ca + C ) * (ta - tf)) / (mobjeto * (tf - to));\n\nprintln(\"\\nCalor específico de um metal\");\n@printf(\"Co = %.4f ± %.4f \\n\", co.val, co.err);\n\n\nprintstyled(\"\\nExperimento 3: Calor latente de condensação da água\\n\",color=:blue);\n\nta = 8.8  ± ΔT;\ntf = 71.7  ± ΔT;\ntc = 100  ± ΔT;\n\nma = 167.479  ± Δm;\nmc = 187.02 - ma  ± Δm;\n\n@printf(\"Massa condensada = %.3f\", mc.val);\n\nL = (((ma + C) * (ta - tf)) / mc) + (tc - tf);\n\nprintln(\"\\nCalor latente\");\n@printf(\"Lc = %.3f ± %.3f\",L.val, L.err);\n\n", "meta": {"hexsha": "ae401b2ced3637035e16c4ec015165a90b78f16e", "size": 1700, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Fisica experimental/02/05/calcs.jl", "max_stars_repo_name": "jefter66/notes", "max_stars_repo_head_hexsha": "adf8753b166162dcb898470932db2235c5d5966b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Fisica experimental/02/05/calcs.jl", "max_issues_repo_name": "jefter66/notes", "max_issues_repo_head_hexsha": "adf8753b166162dcb898470932db2235c5d5966b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Fisica experimental/02/05/calcs.jl", "max_forks_repo_name": "jefter66/notes", "max_forks_repo_head_hexsha": "adf8753b166162dcb898470932db2235c5d5966b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0779220779, "max_line_length": 100, "alphanum_fraction": 0.5529411765, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7834796379839255}}
{"text": "using Plots;gr()\n\nf(x) = x*x - 2\ndf(x) = 2x\n\nfunction newton(x_0, max_iter)\n    x = x_0\n    error = zeros(max_iter)\n    for i in 1:max_iter\n        x = x - f(x) / df(x)\n        error[i] = abs(x - sqrt(2))\n\n    end\n\n    (x, error)\nend\n\nx_0 = 1.0\nmax_iter = 20\n\nx, error = newton(x_0, max_iter)\nprint(error)\nt = 1:max_iter\n\nplot(t, error, color=:cornflowerblue, label=\"newton\",xlabel=\"t\",ylabel=\"Error\")\nsavefig(\"newton.png\")", "meta": {"hexsha": "a2f105b5167635ff822ed8296017713d3a0eeddc", "size": 423, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "nonlinear_equation/newton.jl", "max_stars_repo_name": "nocotan/numerical_calculus.jl", "max_stars_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-07T06:26:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T06:21:01.000Z", "max_issues_repo_path": "nonlinear_equation/newton.jl", "max_issues_repo_name": "nocotan/numerical_calculus.jl", "max_issues_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-01-10T08:22:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-08T13:31:00.000Z", "max_forks_repo_path": "nonlinear_equation/newton.jl", "max_forks_repo_name": "nocotan/numerical_calculus.jl", "max_forks_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-10T05:59:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T13:22:34.000Z", "avg_line_length": 16.2692307692, "max_line_length": 79, "alphanum_fraction": 0.5910165485, "num_tokens": 161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460244, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7834649122965788}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.10\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, KernelDensity, Plots\n\tRandom.seed!(0)\nend\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing4.16\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tmu1, sigma1 = 10, 5\n\tmu2, sigma2 = 40, 12\n\tdist1, dist2 = Normal(mu1,sigma1), Normal(mu2,sigma2)\n\tp = 0.3\n\tmixRv() = (rand() <= p) ? rand(dist1) : rand(dist2)\n\tmixPDF(x) = p*pdf(dist1,x) + (1-p)*pdf(dist2,x)\n\n\tn = 2000\n\tdata = [mixRv() for _ in 1:n]\n\n\tkdeDist = kde(data)\nend\n\n# ╔═╡ 45f535f0-250a-11eb-2a6b-03853e2d8eb1\nbegin\n\txGrid = -20:0.1:80\n\tpdfKDE = pdf(kdeDist,xGrid)\n\n\tplot(xGrid, pdfKDE, c=:blue, label=\"KDE PDF\")\n\tstephist!(data, bins=50, c=:black, normed=:true, label=\"Histogram\")\n\tp1 = plot!(xGrid, mixPDF.(xGrid), c=:red, label=\"Underlying PDF\",\n\t\txlims=(-20,80), ylims=(0,0.035), legend=:topleft,\n\t\txlabel=\"X\", ylabel = \"Density\")\nend\n\n# ╔═╡ 45f5722a-250a-11eb-2840-a7d3dd59711b\nbegin\n\thVals = [0.5,2,10]\n\tkdeS = [kde(data,bandwidth=h) for h in hVals]\n\tplot(xGrid, pdf(kdeS[1],xGrid), c = :green, label= \"h=$(hVals[1])\")\n\tplot!(xGrid, pdf(kdeS[2],xGrid), c = :blue, label= \"h=$(hVals[2])\")\n\tp2 = plot!(xGrid, pdf(kdeS[3],xGrid), c = :purple, label= \"h=$(hVals[3])\",\n\t\txlims=(-20,80), ylims=(0,0.035), legend=:topleft, \n\t\txlabel=\"X\", ylabel = \"Density\")\n\tplot(p1,p2,size = (800,400))\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing4.16\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═45f535f0-250a-11eb-2a6b-03853e2d8eb1\n# ╠═45f5722a-250a-11eb-2840-a7d3dd59711b\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "469cb0af58ad970d6cc7ad12406f64af3917e662", "size": 1907, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/04/listing4.16.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/04/listing4.16.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/04/listing4.16.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 27.2428571429, "max_line_length": 75, "alphanum_fraction": 0.6764551652, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7834649066094433}}
{"text": "###########################################################################\n# Gauss-Kronrod integration-weight computation for arbitrary floating-point\n# types and precision, implemented based on the description in:\n#\n#    Dirk P. Laurie, \"Calculation of Gauss-Kronrod quadrature rules,\"\n#    Mathematics of Computation, vol. 66, no. 219, pp. 1133-1145 (1997).\n#\n# for the Kronrod rule, and for the Gauss rule from the description in\n#\n#    Lloyd N. Trefethen and David Bau, Numerical Linear Algebra (SIAM, 1997).\n#\n# Arbitrary-precision eigenvalue (eignewt & eigpoly) and eigenvector\n# (eigvec1) routines are written by SGJ, independent of the above sources.\n#\n# Since we only implement Gauss-Kronrod rules for the unit weight function,\n# the diagonals of the Jacobi matrices are zero and certain things simplify\n# compared to the general case of an arbitrary weight function.\n\n# Given a symmetric tridiagonal matrix H with H[i,i] = 0 and\n# H[i-1,i] = H[i,i-1] = b[i-1], compute p(z) = det(z I - H) and its\n# derivative p'(z), returning (p,p').\nfunction eigpoly(b,z,m=length(b)+1)\n    d1 = z\n    d1deriv = d2 = one(z)\n    d2deriv = zero(z)\n    for i = 2:m\n        b2 = b[i-1]^2\n        d = z * d1 - b2 * d2\n        dderiv = d1 + z * d1deriv - b2 * d2deriv\n        d2 = d1\n        d1 = d\n        d2deriv = d1deriv\n        d1deriv = dderiv\n    end\n    return (d1, d1deriv)\nend\n\n# compute the n smallest eigenvalues of the symmetric tridiagonal matrix H\n# (defined from b as in eigpoly) using a Newton iteration\n# on det(H - lambda I).  Unlike eig, handles BigFloat.\nfunction eignewt(b,m,n)\n    # get initial guess from eig on Float64 matrix\n    H = SymTridiagonal(zeros(m), Float64[ b[i] for i in 1:m-1 ])\n    lambda0 = sort(eigvals(H))\n\n    lambda = Array{eltype(b)}(undef, n)\n    for i = 1:n\n        lambda[i] = lambda0[i]\n        for k = 1:1000\n            (p,pderiv) = eigpoly(b,lambda[i],m)\n            lambda[i] = (lamold = lambda[i]) - p / pderiv\n            if abs(lambda[i] - lamold) < 10 * eps(lambda[i]) * abs(lambda[i])\n                break\n            end\n        end\n        # do one final Newton iteration for luck and profit:\n        (p,pderiv) = eigpoly(b,lambda[i],m)\n        lambda[i] = lambda[i] - p / pderiv\n    end\n    return lambda\nend\n\n# given an eigenvalue z and the matrix H(b) from above, return\n# the corresponding eigenvector, normalized to 1.\nfunction eigvec1(b,z::Number,m=length(b)+1)\n    # \"cheat\" and use the fact that our eigenvector v must have a\n    # nonzero first entries (since it is a quadrature weight), so we\n    # can set v[1] = 1 to solve for the rest of the components:.\n    v = Array{eltype(b)}(undef, m)\n    v[1] = 1\n    if m > 1\n        s = v[1]\n        v[2] = z * v[1] / b[1]\n        s += v[2]^2\n        for i = 3:m\n            v[i] = - (b[i-2]*v[i-2] - z*v[i-1]) / b[i-1]\n            s += v[i]^2\n        end\n        rmul!(v, 1 / sqrt(s))\n    end\n    return v\nend\n\n\"\"\"\n    gauss([T,] N, a=-1, b=1)\n\nReturn a pair `(x, w)` of `N` quadrature points `x[i]` and weights `w[i]` to\nintegrate functions on the interval `(a, b)`,  i.e. `sum(w .* f.(x))`\napproximates the integral.  Uses the method described in Trefethen &\nBau, Numerical Linear Algebra, to find the `N`-point Gaussian quadrature\nin O(`N`²) operations.\n\n`T` is an optional parameter specifying the floating-point type, defaulting\nto `Float64`. Arbitrary precision (`BigFloat`) is also supported.\n\"\"\"\nfunction gauss(::Type{T}, N::Integer) where T<:AbstractFloat\n    if N < 1\n        throw(ArgumentError(\"Gauss rules require positive order\"))\n    end\n    o = one(T)\n    b = T[ n / sqrt(4n^2 - o) for n = 1:N-1 ]\n    x = eignewt(b,N,N)\n    w = T[ 2*eigvec1(b,x[i])[1]^2 for i = 1:N ]\n    return (x, w)\nend\n\ngauss(N::Integer) = gauss(Float64, N) # integration on the standard interval (-1,1)\n\n# re-scaled to an arbitrary interval:\ngauss(N::Integer, a::Real, b::Real) = gauss(typeof(float(b-a)), N, a, b)\nfunction gauss(::Type{T}, N::Integer, a::Real, b::Real) where T<:AbstractFloat\n    x, w = gauss(T, N)\n    s = T(b-a)/2\n    x .= a .+ (x .+ 1) .* s\n    w .*= abs(s)\n    return (x, w)\nend\n\n\"\"\"\n    kronrod([T,] n)\n\nCompute `2n+1` Kronrod points `x` and weights `w` based on the description in\nLaurie (1997), appendix A, simplified for `a=0`, for integrating on `[-1,1]`.\nSince the rule is symmetric, this only returns the `n+1` points with `x <= 0`.\nThe function Also computes the embedded `n`-point Gauss quadrature weights `gw`\n(again for `x <= 0`), corresponding to the points `x[2:2:end]`. Returns `(x,w,wg)`\nin O(`n`²) operations.\n\n`T` is an optional parameter specifying the floating-point type, defaulting\nto `Float64`. Arbitrary precision (`BigFloat`) is also supported.\n\nGiven these points and weights, the estimated integral `I` and error `E` can\nbe computed for an integrand `f(x)` as follows:\n\n    x, w, wg = kronrod(n)\n    fx⁰ = f(x[end])                # f(0)\n    x⁻ = x[1:end-1]                # the x < 0 Kronrod points\n    fx = f.(x⁻) .+ f.((-).(x⁻))    # f(x < 0) + f(x > 0)\n    I = sum(fx .* w[1:end-1]) + fx⁰ * w[end]\n    if isodd(n)\n        E = abs(sum(fx[2:2:end] .* wg[1:end-1]) + fx⁰*wg[end] - I)\n    else\n        E = abs(sum(fx[2:2:end] .* wg[1:end])- I)\n    end\n\"\"\"\nfunction kronrod(::Type{T}, n::Integer) where T<:AbstractFloat\n    if n < 1\n        throw(ArgumentError(\"Kronrod rules require positive order\"))\n    end\n    o = one(T)\n    b = zeros(T, 2n+1)\n    b[1] = 2*o\n    for j = 1:div(3n+1,2)\n        b[j+1] = j^2 / (4j^2 - o)\n    end\n    s = zeros(T, div(n,2) + 2)\n    t = zeros(T, div(n,2) + 2)\n    t[2] = b[n+2]\n    for m = 0:n-2\n        u = zero(T)\n        for k = div(m+1,2):-1:0\n            l = m - k + 1\n            k1 = k + n + 2\n            u += b[k1]*s[k+1] - b[l]*s[k+2]\n            s[k+2] = u\n        end\n        s,t = t,s\n    end\n    for j = div(n,2):-1:0\n        s[j+2] = s[j+1]\n    end\n    for m = n-1:2n-3\n        u = zero(T)\n        for k = m+1-n:div(m-1,2)\n            l = m - k + 1\n            j = n - l\n            k1 = k + n + 2\n            u -= b[k1]*s[j+2] - b[l]*s[j+3]\n            s[j+2] = u\n        end\n        k = div(m+1,2)\n        if 2k != m\n            j = n - (m - k + 2)\n            b[k+n+2] = s[j+2] / s[j+3]\n        end\n        s,t = t,s\n    end\n    for j = 1:2n\n        b[j] = sqrt(b[j+1])\n    end\n\n    # get negative quadrature points x\n    x = eignewt(b,2n+1,n+1) # x <= 0\n\n    # get quadrature weights\n    w = T[ 2*eigvec1(b,x[i],2n+1)[1]^2 for i in 1:n+1 ]\n\n    # Get embedded Gauss rule from even-indexed points, using\n    # the method described in Trefethen and Bau.\n    for j = 1:n-1\n        b[j] = j / sqrt(4j^2 - o)\n    end\n    gw = T[ 2*eigvec1(b,x[i],n)[1]^2 for i = 2:2:n+1 ]\n\n    return (x, w, gw)\nend\n\nkronrod(N::Integer) = kronrod(Float64, N)\n\n###########################################################################\n# Type-stable cache of quadrature rule results, so that we don't\n# repeat the kronrod calculation unnecessarily.\n\n# precomputed n=7 rule in double precision (computed in 100-bit arithmetic),\n# since this is the common case.\nconst xd7 = [-9.9145537112081263920685469752598e-01,\n             -9.4910791234275852452618968404809e-01,\n             -8.6486442335976907278971278864098e-01,\n             -7.415311855993944398638647732811e-01,\n             -5.8608723546769113029414483825842e-01,\n             -4.0584515137739716690660641207707e-01,\n             -2.0778495500789846760068940377309e-01,\n             0.0]\nconst wd7 = [2.2935322010529224963732008059913e-02,\n             6.3092092629978553290700663189093e-02,\n             1.0479001032225018383987632254189e-01,\n             1.4065325971552591874518959051021e-01,\n             1.6900472663926790282658342659795e-01,\n             1.9035057806478540991325640242055e-01,\n             2.0443294007529889241416199923466e-01,\n             2.0948214108472782801299917489173e-01]\nconst gwd7 = [1.2948496616886969327061143267787e-01,\n              2.797053914892766679014677714229e-01,\n              3.8183005050511894495036977548818e-01,\n              4.1795918367346938775510204081658e-01]\n\n# cache of T -> n -> (x,w,gw) Kronrod rules, to avoid recomputing them\n# unnecessarily for repeated integration.   We initialize it with the\n# default n=7 rule for double-precision calculations.  We use a cache\n# of caches to allow us to evaluate the cache in a type-stable way with\n# a generated function below.\nconst rulecache = Dict{Type,Dict}(\n    Float64 => Dict{Int,NTuple{3,Vector{Float64}}}(7 => (xd7,wd7,gwd7)),\n    Float32 => Dict{Int,NTuple{3,Vector{Float32}}}(7 => (xd7,wd7,gwd7)))\n\n# for BigFloat rules, we need a separate cache keyed by (n,precision)\nconst bigrulecache = Dict{Tuple{Int,Int}, NTuple{3,Vector{BigFloat}}}()\n\ncachedrule(::Type{T}, n::Integer) where {T<:Number} = cachedrule(typeof(float(real(one(T)))), n::Integer)\n\nfunction cachedrule(::Type{BigFloat}, n::Integer)\n    key = (n, precision(BigFloat))\n    haskey(bigrulecache, key) ? bigrulecache[key] : (bigrulecache[key] = kronrod(BigFloat, n))\nend\n\n# use a generated function to make this type-stable\n@generated function cachedrule(::Type{T}, n::Integer) where {T<:AbstractFloat}\n    cache = haskey(rulecache, T) ? rulecache[T] : (rulecache[T] = Dict{Int,NTuple{3,Vector{T}}}())\n    :(haskey($cache, n) ? $cache[n] : ($cache[n] = kronrod($T, n)))\nend", "meta": {"hexsha": "9d3c53adaaf31e783471c7f26ee90519247b70b0", "size": 9277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gausskronrod.jl", "max_stars_repo_name": "fmeirinhos/QuadGK.jl", "max_stars_repo_head_hexsha": "1fe7a8fb49cfa432117cccc7634c17702746367a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gausskronrod.jl", "max_issues_repo_name": "fmeirinhos/QuadGK.jl", "max_issues_repo_head_hexsha": "1fe7a8fb49cfa432117cccc7634c17702746367a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gausskronrod.jl", "max_forks_repo_name": "fmeirinhos/QuadGK.jl", "max_forks_repo_head_hexsha": "1fe7a8fb49cfa432117cccc7634c17702746367a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6807692308, "max_line_length": 105, "alphanum_fraction": 0.5891990945, "num_tokens": 3122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7834649062581822}}
{"text": "# ------------------------------------------------------------\n# Reconstruction of impulse responses, i.e., a single coefficient in the Haar \n# basis from equidistant frequency samples\n\n\n# Define scaling function and mother wavelet\n\nfunction Haar_scaling(x::Real)\n\tif x >= 0 && x <= 1.0\n\t\treturn 1.0\n\telse\n\t\treturn 0.0\n\tend\nend\n\nfunction Haar_wavelet(x::Real)\n\tif x >= 0 && x < 0.5\n\t\treturn 1.0\n\telseif x >= 0.5 && x <= 1.0\n\t\treturn -1.0\n\telse\n\t\treturn 0.0\n\tend\nend\n\n# ------------------------------------------------------------\n# Reconstruction of scaling function\n\n# Input: \n# M: The number of frequency samples\n# epsislon: The distance between two consecutive samples\n# N: The number of wavelet coefficients recovered\n\nM = 32\nepsilon = 1\n#J = floor(Int, log2(M))\nJ = 2\n\n# Sampling points\nxi = [-M:M;]*epsilon\n\n# Change of basis matrix\nTx, Ty = freq2Haar( xi, xi, J )\nT = kron(Ty, Tx)\n\n# Fourier observations\nbx = FourHaarScaling(xi, J, 3)\nby = FourHaarScaling(xi, J, 3)\nb = bx * by.'\n\n# Scaling function coefficients: 1 in the last (16th) entry, 0 elsewhere\ny = pinv(T)*b[:] # Brute force\nyy = pinv(Tx)*b*pinv(Ty).' # With Kronecker products\n\n", "meta": {"hexsha": "6696ed4196298f5e1b073db3a9bdeabfd61458aa", "size": 1147, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/impulse2d.jl", "max_stars_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_stars_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/impulse2d.jl", "max_issues_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_issues_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/impulse2d.jl", "max_forks_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_forks_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8545454545, "max_line_length": 78, "alphanum_fraction": 0.6050566696, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517083920618, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7833990598501991}}
{"text": "# p1.jl - convergence of fourth-order finite differences\n\n# For various N, set up grid in [-pi,pi] and function u(x):\nNvec = 2.^(3:12);\nclf(); axes([.1,.4,.8,.5]);\nfor N = Nvec\n    h = 2*pi/N; x = -pi + (1:N)*h;\n    u = @. exp(sin(x)^2);\n    uprime = @. 2*sin(x)*cos(x)*u;\n\n    # Construct sparse fourth-order differentiation matrix:\n    e = ones(N);\n    D = sparse(1:N,[2:N;1],2*e/3) - sparse(1:N,[3:N;1:2],e/12);\n    D = (D-D')/h;\n\n    # Plot max(abs(D*u-uprime)):\n    error = norm(D*u-uprime,Inf);\n    loglog(N,error,\"k.\",markersize=6);\nend\ngrid(true); xlabel(\"N\"); ylabel(\"error\");\ntitle(\"Convergence of fourth-order finite differences\");\nloglog(Nvec,1.0./Nvec.^4,\"--\");\ntext(105,5e-8,L\"N^{-4}\",fontsize=18);\n", "meta": {"hexsha": "fc289ca93ea05419637854639062c61d8db38349", "size": 713, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p1.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p1.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p1.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7083333333, "max_line_length": 63, "alphanum_fraction": 0.5764375877, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737735, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7833990567816403}}
{"text": "function linear_index(IND)\n  J = round(Int,floor(-.5 + .5 * sqrt(1 + 8 * (IND - 1))) + 2)\n  I = round(Int,J .* (3 - J) / 2 + IND - 1)\n  return I, J\nend\n", "meta": {"hexsha": "754318cbab75e1046ee22a5962f7f72dea64e284", "size": 152, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear_index.jl", "max_stars_repo_name": "viniciuspiccoli/simulationQP934", "max_stars_repo_head_hexsha": "1187384bddb098dba854d01db66d82891f6d6dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-06T18:14:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T14:26:47.000Z", "max_issues_repo_path": "src/linear_index.jl", "max_issues_repo_name": "viniciuspiccoli/simulationQP934", "max_issues_repo_head_hexsha": "1187384bddb098dba854d01db66d82891f6d6dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/linear_index.jl", "max_forks_repo_name": "viniciuspiccoli/simulationQP934", "max_forks_repo_head_hexsha": "1187384bddb098dba854d01db66d82891f6d6dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-12-04T12:19:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-11T00:24:47.000Z", "avg_line_length": 25.3333333333, "max_line_length": 62, "alphanum_fraction": 0.5131578947, "num_tokens": 66, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9609517050371972, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7833990484876293}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e1a3f480-12e7-11eb-01db-71003ec47f08\nmd\"\"\"\n## What *is* an array, actually?\n\nWe have seen several examples of arrays. \nWhen you think about an array, you probably think of a chain of boxes with the same shape, stored one after the other, consecutively in memory. And indeed this is the original meaning of the word \"array\".\n\nHowever, as a user, we don't actually care about how the data is actually stored! All we really care about is the functionality of an array. Namely, we want the following properties:\n\n- Elements have an integer index (from 1 to `n`);\n- An element at position `i` can be accessed using the syntax `A[i]`;\n- An element at position `i` can be stored using `A[i] = i` (if the array is mutable)\n- We should be able to see the size of an array.\n\"\"\"\n\n# ╔═╡ 51a660b4-12f3-11eb-2b8a-f5544e650b1c\nmd\"\"\"\nJulia provides an **abstraction** of an array called `AbstractArray`. We can define new types of array that \"behave like\" arrays but are stored differently.\n\"\"\"\n\n# ╔═╡ 853ac7d0-12f3-11eb-1b1c-993e336cf23a\nmd\"\"\"\n## How does indexing work?\n\"\"\"\n\n# ╔═╡ 94bb1e6c-12f3-11eb-2e18-bb232d2c9cfe\nmd\"\"\"\nFirst let's think about indexing, which is really the key operation on an array.\nLet's define a vector:\n\"\"\"\n\n# ╔═╡ 314ba27a-12ec-11eb-12ce-67650c0020b7\narr = [34,45,67]\n\n# ╔═╡ ab3afe6e-12f3-11eb-196a-79d26b66f681\nmd\"\"\"\nWe know that we can index into it using square brackets:\n\"\"\"\n\n# ╔═╡ b32acfda-12f3-11eb-323d-ef91b9ff9f0d\narr[2]\n\n# ╔═╡ b53bc5ba-12f3-11eb-2b09-d38cc266b069\nmd\"\"\"\nThis is just syntax? What is actually going on? We can see this by looking at the **lowered** form:\n\"\"\"\n\n# ╔═╡ 3a202684-12ec-11eb-26fc-df7b7484e671\nMeta.@lower arr[2]\n\n# ╔═╡ c225d324-12f3-11eb-23d7-45548e7b32b6\nmd\"\"\"\nWe see that `arr[2]` is just \"syntactic sugar\" for calling the `getindex` function as `getindex(arr, 2)`; in other words, it's just a nice short and suggestive way to write the same thing.\n\"\"\"\n\n# ╔═╡ d92c5aa2-12f3-11eb-286e-8769ecdf03cb\nmd\"\"\"\nSo to implement our own objects that behave like arrays, we will define a new type and extend `getindex` on that type. \n\"\"\"\n\n# ╔═╡ f10cf87a-12f3-11eb-1104-0186b9e43757\nmd\"\"\"\n## Example: A zero-based vector\n\"\"\"\n\n# ╔═╡ f7cadd08-12f3-11eb-1882-8dd4ce8ee2c2\nmd\"\"\"\nThere are interminable discussions online about whether zero-based indexing (i.e. array indices starting at 0) or one-based indexing (starting at 1) is superior. The answer is that *neither* is -- each is more suitable in different contexts.\n\nFortunately Julia is flexible enough to allow you to use *any* type of indexing that suits you -- see e.g. the `OffsetArrays.jl` package.\n\nLet's see how to implement the simplest case, namely a zero-based vector.\n\nSo we define a new type and extend `getindex` on it. In order to use the full Julia machinery we need to extend a couple of other functions too:\n\"\"\"\n\n# ╔═╡ 1ac0095e-12eb-11eb-3df2-e98d0ff66dd5\nstruct ZeroFirstVector{T} <: AbstractVector{T}\n\tarray::Vector{T}\nend\n\n# ╔═╡ a66afe14-12eb-11eb-3afc-fdac2325ff84\nBase.size(vec::ZeroFirstVector) = size(vec.array)\n\n# ╔═╡ e86c53fa-12eb-11eb-0ee4-41455a218d84\nBase.axes(vec::ZeroFirstVector) = (0:length(vec.array)-1,)\n\n# ╔═╡ 69b10842-12eb-11eb-381a-0bda698a59ed\nBase.getindex(vec::ZeroFirstVector, i::Int) = vec.array[i+1]\n\n# ╔═╡ 9c57e4aa-12eb-11eb-16fb-c7a18c238192\nzarr = ZeroFirstVector([1, 3, 4])\n\n# ╔═╡ 3cf51826-12f4-11eb-2405-db9616fa3152\nmd\"\"\"\nNow we are able to use zero-based indexing!:\n\"\"\"\n\n# ╔═╡ fed5e2e4-12eb-11eb-169f-8b050f9eea4a\nzarr[0]\n\n# ╔═╡ 464c22f2-12f4-11eb-0b3c-872621c385f6\nmd\"\"\"\n## Modifying elements: `setindex!`\n\"\"\"\n\n# ╔═╡ 4dec992e-12f4-11eb-1f20-b96632769bed\nmd\"\"\"\nIn a similar way to `getindex`, modifying elements of an array uses the mutating function `setindex!`:\n\"\"\"\n\n# ╔═╡ 5b8f3508-12ec-11eb-0a31-61ddf796ac74\nMeta.@lower arr[2] = 3\n\n# ╔═╡ 0c8ebad2-12ec-11eb-03f1-c5b9c79bb4da\nBase.setindex!(vec::ZeroFirstVector, val, i::Int) = (vec.array[i+1] = val)\n\n# ╔═╡ 8438424c-12ec-11eb-1de2-0bb3924ec78c\nzarr[0] = 55\n\n# ╔═╡ 9cee3206-12ec-11eb-09c7-1f0ebad11b8e\nzarr\n\n# ╔═╡ b0ab2844-12ec-11eb-1908-0318510b3292\nmd\"\"\"\n### Julia gives you added bonuses here:\n\"\"\"\n\n# ╔═╡ bc8154b8-12ec-11eb-1fcc-4765fcd0796d\nzarr[0:1]\n\n# ╔═╡ 8c0c8188-12f4-11eb-1576-23958903a69a\n@which zarr[0:1]\n\n# ╔═╡ 7425ef6e-12f4-11eb-21c3-19c221c1ebdb\nmd\"\"\"\nWe never defined how to index using a *range*, only an integer. Julia has a generic fallback mechanism that understands how to do this once you have implemented `getindex` for a single element.\n\nSimilarly:\n\"\"\"\n\n# ╔═╡ c67fbbbc-12ec-11eb-32be-2ff720964fe6\nzarr[ [2, 1, 0] ]\n\n# ╔═╡ d13a65b6-12ec-11eb-2996-37987cfae782\nzarr[0:1] .= [7,8];\n\n# ╔═╡ dbb95f42-12ec-11eb-01d5-df2e21affd86\nzarr\n\n# ╔═╡ e6428aa6-12ec-11eb-06d0-95404a8a4039\nzarr[ [2, 1, 0] ] .= [1, 2, 3];\n\n# ╔═╡ e21658ec-12ef-11eb-06fd-b1d282edf7b6\nzarr\n\n# ╔═╡ b405b9ac-12f4-11eb-12fa-f7575ff1fa73\nmd\"\"\"\nVarious other functions also automatically work, e.g.:\n\"\"\"\n\n# ╔═╡ e57329a2-12ef-11eb-165d-51f080c73652\nsort!(zarr)\n\n# ╔═╡ e8b34188-12ef-11eb-2d7f-fde100b582d1\nmd\"\"\"\n### Some more examples\n\n\"\"\"\n\n# ╔═╡ bd6bfd10-12f4-11eb-17fe-6f9ce83f0ce8\nmd\"\"\"\nWe have already seen some other examples of array types in the course, e.g. ranges:\n\"\"\"\n\n# ╔═╡ f0d952da-12ef-11eb-2452-471b184bc529\nr = 53:83\n\n# ╔═╡ 0fc7e3e6-12f0-11eb-1b49-e37196154ec6\nsize(r)\n\n# ╔═╡ 03b23fe0-12f0-11eb-0970-33b3b973e902\nr[20]\n\n# ╔═╡ 00088cda-12f0-11eb-36b7-9b900fa6d0bf\ntypeof(r)\n\n# ╔═╡ f6024924-12ef-11eb-1d6c-3ffff2546914\nsupertypes(typeof(r))\n\n# ╔═╡ cdf3e532-12f4-11eb-1ce0-873bcf0dea58\nmd\"\"\"\nLet's also look at what happens if we reshape an array:\n\"\"\"\n\n# ╔═╡ f9bf5200-12ef-11eb-30ee-9b3cbbccc886\nA = reshape(1:12, 3, 4)\n\n# ╔═╡ 07c1cdb6-12f1-11eb-0b31-15b5c88caac6\ntypeof(A)\n\n# ╔═╡ 09d69238-12f1-11eb-1d9f-f72e8c6c14d9\nsupertypes(typeof(A))\n\n# ╔═╡ ff598e1c-12f0-11eb-24f6-bdaa74db2ad7\nsize(A)\n\n# ╔═╡ 2f23dd4e-12f0-11eb-01fc-53f66d2a55e4\nAᵀ = transpose(A)\n\n# ╔═╡ ea8e0794-12f0-11eb-2194-bdc46224dc69\nsize(Aᵀ)\n\n# ╔═╡ 2a76a87a-12f1-11eb-3e58-e5f919ba81e8\n@which Aᵀ[2,3]\n\n# ╔═╡ 892e7c40-12f0-11eb-2871-0d308063f025\nmd\"The `getindex` method for `Transpose` is defined [here](https://github.com/JuliaLang/julia/blob/master/stdlib/LinearAlgebra/src/adjtrans.jl#L190)\"\n\n# ╔═╡ da41895c-12f4-11eb-2ee4-f1ffc4344f61\nmd\"\"\"\n## Conclusions\n\"\"\"\n\n# ╔═╡ dfac92ea-12f4-11eb-1253-b74be632de64\nmd\"\"\"\nSummarising, we see that we -- and Julia -- can think of an array as \"anything that behaves like an array\", i.e. which you can index into.\n\nWhat does it mean for something to behave like an array? In the end it means that we *could* \"materialise\" it to produce an actual array that did live as data stored linearly in memory, and our program would behave in exactly the same way.\n\nBut Julia provides a mechanism by which we can store less data, or store it in a more convenient way, and have indexing be almost as efficient.\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─e1a3f480-12e7-11eb-01db-71003ec47f08\n# ╟─51a660b4-12f3-11eb-2b8a-f5544e650b1c\n# ╟─853ac7d0-12f3-11eb-1b1c-993e336cf23a\n# ╟─94bb1e6c-12f3-11eb-2e18-bb232d2c9cfe\n# ╠═314ba27a-12ec-11eb-12ce-67650c0020b7\n# ╟─ab3afe6e-12f3-11eb-196a-79d26b66f681\n# ╠═b32acfda-12f3-11eb-323d-ef91b9ff9f0d\n# ╟─b53bc5ba-12f3-11eb-2b09-d38cc266b069\n# ╠═3a202684-12ec-11eb-26fc-df7b7484e671\n# ╟─c225d324-12f3-11eb-23d7-45548e7b32b6\n# ╟─d92c5aa2-12f3-11eb-286e-8769ecdf03cb\n# ╟─f10cf87a-12f3-11eb-1104-0186b9e43757\n# ╟─f7cadd08-12f3-11eb-1882-8dd4ce8ee2c2\n# ╠═1ac0095e-12eb-11eb-3df2-e98d0ff66dd5\n# ╠═a66afe14-12eb-11eb-3afc-fdac2325ff84\n# ╠═e86c53fa-12eb-11eb-0ee4-41455a218d84\n# ╠═69b10842-12eb-11eb-381a-0bda698a59ed\n# ╠═9c57e4aa-12eb-11eb-16fb-c7a18c238192\n# ╟─3cf51826-12f4-11eb-2405-db9616fa3152\n# ╠═fed5e2e4-12eb-11eb-169f-8b050f9eea4a\n# ╟─464c22f2-12f4-11eb-0b3c-872621c385f6\n# ╟─4dec992e-12f4-11eb-1f20-b96632769bed\n# ╠═5b8f3508-12ec-11eb-0a31-61ddf796ac74\n# ╠═0c8ebad2-12ec-11eb-03f1-c5b9c79bb4da\n# ╠═8438424c-12ec-11eb-1de2-0bb3924ec78c\n# ╠═9cee3206-12ec-11eb-09c7-1f0ebad11b8e\n# ╟─b0ab2844-12ec-11eb-1908-0318510b3292\n# ╠═bc8154b8-12ec-11eb-1fcc-4765fcd0796d\n# ╠═8c0c8188-12f4-11eb-1576-23958903a69a\n# ╟─7425ef6e-12f4-11eb-21c3-19c221c1ebdb\n# ╠═c67fbbbc-12ec-11eb-32be-2ff720964fe6\n# ╠═d13a65b6-12ec-11eb-2996-37987cfae782\n# ╠═dbb95f42-12ec-11eb-01d5-df2e21affd86\n# ╠═e6428aa6-12ec-11eb-06d0-95404a8a4039\n# ╠═e21658ec-12ef-11eb-06fd-b1d282edf7b6\n# ╟─b405b9ac-12f4-11eb-12fa-f7575ff1fa73\n# ╠═e57329a2-12ef-11eb-165d-51f080c73652\n# ╟─e8b34188-12ef-11eb-2d7f-fde100b582d1\n# ╟─bd6bfd10-12f4-11eb-17fe-6f9ce83f0ce8\n# ╠═f0d952da-12ef-11eb-2452-471b184bc529\n# ╠═0fc7e3e6-12f0-11eb-1b49-e37196154ec6\n# ╠═03b23fe0-12f0-11eb-0970-33b3b973e902\n# ╠═00088cda-12f0-11eb-36b7-9b900fa6d0bf\n# ╠═f6024924-12ef-11eb-1d6c-3ffff2546914\n# ╟─cdf3e532-12f4-11eb-1ce0-873bcf0dea58\n# ╠═f9bf5200-12ef-11eb-30ee-9b3cbbccc886\n# ╠═07c1cdb6-12f1-11eb-0b31-15b5c88caac6\n# ╠═09d69238-12f1-11eb-1d9f-f72e8c6c14d9\n# ╠═ff598e1c-12f0-11eb-24f6-bdaa74db2ad7\n# ╠═2f23dd4e-12f0-11eb-01fc-53f66d2a55e4\n# ╠═ea8e0794-12f0-11eb-2194-bdc46224dc69\n# ╠═2a76a87a-12f1-11eb-3e58-e5f919ba81e8\n# ╟─892e7c40-12f0-11eb-2871-0d308063f025\n# ╟─da41895c-12f4-11eb-2ee4-f1ffc4344f61\n# ╟─dfac92ea-12f4-11eb-1253-b74be632de64\n", "meta": {"hexsha": "4fdd91da2137b0ad1f69adff0e9f20f42603f916", "size": 9149, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_notebooks/week8/what_is_an_array.jl", "max_stars_repo_name": "mathijsvdv/ComputationalThinking", "max_stars_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lecture_notebooks/week8/what_is_an_array.jl", "max_issues_repo_name": "mathijsvdv/ComputationalThinking", "max_issues_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecture_notebooks/week8/what_is_an_array.jl", "max_forks_repo_name": "mathijsvdv/ComputationalThinking", "max_forks_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9087837838, "max_line_length": 241, "alphanum_fraction": 0.7349437097, "num_tokens": 4403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.907312226373181, "lm_q1q2_score": 0.7833657766343385}}
{"text": "# estimate with MCMC (Turing) for conjugate prior\n# compare with jlbayes_conjugate_regression.jl\n\nusing Turing\nusing Distributions\nusing Random\nusing LinearAlgebra\nusing StatsPlots\nusing Optim\n\n# Generate moc data\nn = 50\ndim = 1\nRandom.seed!(99)\nu = rand(Normal(0, 0.7), n) # true value σ² = 0.49\nx = rand(Uniform(-sqrt(3.0), sqrt(3.0)), n, dim) # x generated from Uniform[-√3, √3]\nX = [ones(n) x] # dependent variable matrix with ones\nβ = Vector(1:1:dim+1) # true coefficients\ny = X*β + u # true data generating process\n\n# set prior (conjugate prior for camparison with analytic result)\n# p.78 eq (3.32)\nk = size(X)[2]\nβ0 = zeros(k)\nτ0 = 0.2\nA0 = τ0 * I # Identity matrix\nν0 = 5.0\nλ0 = 7.0\n# H0 = (λ0 / ν0) * inv(A0) # scale matrix for marginal prior of multivariate coefficient (mv Tdist)\n# h0 = diag(sqrt(Matrix(H0, k, k))) # scale params for marginal prior of single coefficient (T dist) H0の対角成分\nsd0 = diag(sqrt(Matrix(A0, k, k))) # the parameter for conditional prior for β|σ² ~ N_k(β0, σ²*inv(A0)), (inv(A0) part)\n\n@model function linear_regression(X, y)\n    # conjugate priors\n    # https://turing.ml/dev/tutorials/05-linear-regression/\n    \n    # Set variance priors\n    σ² ~ InverseGamma(ν0/2, λ0/2)\n\n    # Set the priors on our coefficients.\n    nfeatures = size(X, 2)\n    β ~ MvNormal(β0, σ² * inv(A0))\n\n    # Write likelihood.\n    y ~ MvNormal(X * β, σ² * I)\nend\n\n# Draw random number from posterior.\nmodel = linear_regression(X, y)\nn_draws = 5_000\nn_chains = 4\nn_tune = 1_000\n# sample(model, sampler, parallel_type, n, n_chains)\n# chain = sample(model, NUTS(), MCMCThreads(), n_draws, n_chains, discard_initial=n_tune)\n# How to implement burn-in / warmup? --> discard initial value automatically. ; discard_adapt=false to turn off\nchn = sample(model, NUTS(), MCMCThreads(), n_draws, n_chains)\nchn = sample(model, NUTS(), MCMCThreads(), n_draws, n_chains; discard_adapt=false)\n\n# Chain info.\ntypeof(chn)\nsize(chn)\ndescribe(chn)\nsummarize(chn)\nquantile(chn)\nplot(chn)\n\n# Indexing a Chains object.\nβ1_chn = chn[\"β[1]\"]\nβ2_chn = chn[Symbol(\"β[2]\")]\nσ²_chn = chn[:σ²]\nall_β_chn = group(chn, :β) # get subset of all parameters include \"β\"\n\ntypeof(β1_chn)\nβ1_chn[iter = 1000:5000, chain = 1]\nmean(β1_chn)\nstd(β1_chn)\n\n# Monte Carlo Standard Error\nmcse(θ_chn) = sqrt((1 / (length(θ_chn) * (length(θ_chn) - 1))) * sum((θ_chn .- mean(θ_chn)).^2))\n\n[β1_chn, β2_chn, σ²_chn]\n\nmcse.([β1_chn, β2_chn, σ²_chn])\n\n# without burn-in\nmean(β1_chn[iter = 1:5000])\n\nhistogram(β1_chn[:, 1])\nhistogram!(β1_chn[:, 2])\nhistogram!(β1_chn[:, 3])\nhistogram!(β1_chn[:, 4])\n\n# mode (MLE and MAP) estimates (Optimization with Optim.jl) as an option (continuous only)\n# Note that loading Optim explicitly is required for mode estimation to function,\n# as Turing does not load the opimization suite unless Optim is loaded as well.\n\n# Generate a MLE estimate (default optimizer is LBFGS optimizer).\nmle_estimate = optimize(model, MLE())\n# Use Newton\n# mle_estimate = optimize(model, MLE(), Newton())\n\n# Generate a MAP estimate (default optimizer is LBFGS optimizer).\nmap_estimate = optimize(model, MAP())\n\n# Analyze mode estimate\n# Import StatsBase to use it's statistical methods.\n# using StatsBase\n\n# Print out the coefficient table.\n# coeftable(mle_estimate)\n\n# Analytical Solution\ninv(X' * X) * X' * y", "meta": {"hexsha": "a5d6601832ec0a553a3b84c5e5bfbc1bd9dff57e", "size": 3283, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jlbayes_mcmc_reg_ex1.jl", "max_stars_repo_name": "hessihan/julia_bayes_intro", "max_stars_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jlbayes_mcmc_reg_ex1.jl", "max_issues_repo_name": "hessihan/julia_bayes_intro", "max_issues_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jlbayes_mcmc_reg_ex1.jl", "max_forks_repo_name": "hessihan/julia_bayes_intro", "max_forks_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0530973451, "max_line_length": 119, "alphanum_fraction": 0.7021017362, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7833657617133363}}
{"text": "using LinearAlgebra\nimport LinearAlgebra.Eigen\nusing SparseArrays\n#this lib will be used to estimate the executon time\nusing BenchmarkTools\nusing Test\nusing Distributions\n\n\nstruct SVDCM\n\tU::Matrix{Float64}\n\tS::SparseMatrixCSC{Float64, Int64}\n\tV::Matrix{Float64}\n\n\tfunction SVDCM(A::Matrix{Float64})\n\t\tU, S, V = svdCm(A)\n\t\treturn new( U, S, V)\n\tend\n\tfunction svdCm(A::Matrix{Float64})\n\n\t\tr,c = size(A)\n\t\tshorter=min(r,c)\n\t\tlonger=max(r,c)\n\n\t\tAsq = zeros(shorter,shorter) \n\t\tmul!(Asq, A', A)\n\t\ta, V = eigen!(Asq)\n\n\t\tS = sparse(zeros(longer,shorter))\n\t\tSin = sparse(zeros(shorter,longer))\n\n\t\tS[diagind(S)] .= (sqrt.(a))\n\t\tSin[diagind(Sin)] .= 1 ./ S[diagind(S)]\n\n\t\tU1 = zeros(r,c) \n\t\tU = zeros(longer,longer)\n\n\t\tmul!(U1, A, V)\n\t\tmul!(U,U1,Sin) \n\t\treturn U, S, V\n\tend\nend\n\n\n\nR = rand(Uniform(1., 100.), 10000,1000)\nMM = [1 0 0 0 2; 0 0 3 0 0; 0 0 0 0 0; 0 2 0 0 0; 1 0 0 0 2; 0 0 3 0 0; 0 0 0 0 0; 0 2 0 0 0; 1 0 0 0 2; 0 0 3 0 0; 0 0 0 0 0; 0 2 0 0 0; 1 0 0 0 2; 0 0 3 0 0; 0 0 0 0 0; 0 2 0 0 0;1 0 0 0 2; 0 0 3 0 0; 0 0 0 0 0; 0 2 0 0 0;1 0 0 0 2; 0 0 3 0 0; 0 0 0 0 0; 0 2 0 0 0 ]\n\nC = R\nprintln(\"size of matrix: \", size(C) )\n\nprintln(\"Julia SVD time:\")\nSVD = @time svd(C)\n\nprintln(\"SVD time:\")\nmySvd = @time SVDCM(C)\n\nF = mySvd.U * mySvd.S * mySvd.V'\n#display(F)\n@test F ≈ C atol=1e-5\n\n", "meta": {"hexsha": "b67b2d9995dbad45bf94806873c7a15c07b23bae", "size": 1286, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CM_SVD.jl", "max_stars_repo_name": "MLP-GAF/CM_Project", "max_stars_repo_head_hexsha": "662283ecee17117cb2765255cd956b2e5cd77f11", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CM_SVD.jl", "max_issues_repo_name": "MLP-GAF/CM_Project", "max_issues_repo_head_hexsha": "662283ecee17117cb2765255cd956b2e5cd77f11", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CM_SVD.jl", "max_forks_repo_name": "MLP-GAF/CM_Project", "max_forks_repo_head_hexsha": "662283ecee17117cb2765255cd956b2e5cd77f11", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7419354839, "max_line_length": 268, "alphanum_fraction": 0.6073094868, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7833579174824316}}
{"text": "# Legendre-Gauss quadrature weights and nodes\n# This code was originally written for Matlab\n#  by Greg von Winckel - 02/25/2004\n# posted on Mathworks website and licensed under BSD License\n# http://fr.mathworks.com/matlabcentral/fileexchange/4540-legendre-gauss-quadrature-weights-and-nodes\n# \n# \n\nfunction lgwt(N,a,b)\n\n\tN=N-1;\n\tN1=N+1; N2=N+2;\n\txu= transpose(range(-1,stop = 1, length = N1));\n\n\ty = transpose(cos.((2*transpose(0:N).+1)*pi/(2*N+2))+(0.27/N1)*sin.(pi*xu*N/N2));\n\n\tL = zeros(N1,N2);\n\n\tLp=zeros(N1,N2);\n\ty0=2;\n\n\twhile maximum(abs.(y.-y0))>eps()\t\t\t\t\n\t\tL[:,1] .= 1;\n\t\tLp[:,1] .= 0;\t\t\n\t\tL[:,2] = y;\n\t\tfor k=2:N1\n\t\t\tL[:,k+1]=( (2*k-1)*y.*L[:,k]-(k-1)*L[:,k-1] )/k;\n\t\tend\t \n\t\tLp=(N2)*( L[:,N1] - y .* L[:,N2] )./(1 .- y.^2);   \t\t\n\t\ty0=y;\n\t\ty=y0-L[:,N2]./Lp;\t\t\n\tend\n\n\tx = (a*(1 .- y)+b*(1 .+ y))/2;      \n\n\tw=(b-a)./((1 .- y.^2).*Lp.^2)*(N2/N1)^2;\n\n\treturn x,w\nend", "meta": {"hexsha": "6307b7e3314166e6777658173f41164a65e79efc", "size": 872, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lgwt.jl", "max_stars_repo_name": "flavioluiz/phjulia", "max_stars_repo_head_hexsha": "aee3162f0bec3aed0bed0f6ae4138a7e6a5b5797", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-28T19:34:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-28T19:34:40.000Z", "max_issues_repo_path": "src/lgwt.jl", "max_issues_repo_name": "flavioluiz/phjulia", "max_issues_repo_head_hexsha": "aee3162f0bec3aed0bed0f6ae4138a7e6a5b5797", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-10-31T14:12:22.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-31T14:12:22.000Z", "max_forks_repo_path": "src/lgwt.jl", "max_forks_repo_name": "flavioluiz/phjulia", "max_forks_repo_head_hexsha": "aee3162f0bec3aed0bed0f6ae4138a7e6a5b5797", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-01T17:15:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:15:30.000Z", "avg_line_length": 22.358974359, "max_line_length": 101, "alphanum_fraction": 0.5470183486, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145365, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7833579102270277}}
{"text": "function house!(h, j, X, k)\n    T = eltype(h)\n    n = size(X,1)\n    σ = zero(T)\n    @inbounds @simd for i in j+1:n\n        σ += X[i,k]^2\n    end\n    @inbounds begin\n        h[j] = one(T)\n        @simd for i in j+1:n\n            h[i] = X[i,k]\n        end\n    end\n    if σ == zero(T)\n        β = zero(T)\n    else\n        @inbounds begin\n            μ = sqrt(X[j,k]^2 + σ)\n            if X[j,k] <= zero(T)\n                h[j] = X[j,k] - μ\n            else\n                h[j] = -σ/(X[j,k] + μ)\n            end\n            β = 2*(h[j]^2) / (σ + h[j]^2)\n            d = h[j]\n            @simd for i in j:n\n                h[i] /= d\n            end\n        end\n    end\n    β\nend\n\n\"\"\"\naccumulate!(Q, A, β)\n\nQ: Matrix to be over-written with Q, gets returned\nA: Has the Householder vectors on the lower triangle\nβ: Has the Householder coefficients\n\"\"\"\nfunction accumulate!(Q, A, β)\n    T = eltype(Q)\n    m, n = size(Q)\n    @inbounds begin\n        Q .= zero(T)\n        @simd for i in 1:n\n            Q[i,i] = one(T)\n        end\n    end\n    @inbounds for j in n:-1:1\n        @simd for t in j:n\n            dp = Q[j,t]\n            for i in j+1:m\n                dp += A[i,j]*Q[i,t]\n            end\n            Q[j,t] -= β[j]*dp\n            for i in j+1:m\n                Q[i,t] -= β[j]*dp*A[i,j]\n            end\n        end\n    end\n    Q\nend\n\n\"\"\"\ngetR!(R, A)\n\nCopies the right triangular part of A into the right triangular part of R.\n\"\"\"\nfunction getR!(R, A)\n    T = eltype(R)\n    m, n = size(A)\n    @inbounds @simd for j in 1:n\n        for i in 1:j\n            R[i,j] = A[i,j]\n        end\n    end\n    R\nend\n\n\"\"\"\nqrfact!(A, β, h=zeros(eltype(A), size(A,1)))\n\nA: Matrix to be QR factorized, returned by the function\nβ: Empty buffer to store the Householder coefficients, returned by the function\nh: Empty buffer for in-place operations\n\"\"\"\nfunction qrfact!(A, β, h=zeros(eltype(A), size(A,1)))\n    m, n = size(A)\n    @inbounds for j in 1:n\n        β[j] = house!(h, j, A, j)\n        @simd for k in j:n\n            dp = A[j,k]\n            for i in j+1:m\n                dp += h[i]*A[i,k]\n            end\n            for l in j:m\n                A[l,k] -= (β[j] * dp) * h[l]\n            end\n        end\n        if j < m\n            @simd for k in 1:(m-j)\n                A[k+j,j] = h[k+j]\n            end\n        end\n    end\n    A, β  \nend\n", "meta": {"hexsha": "b45f56ab69851b2b6b679b4b9a992ea0da7ff7b9", "size": 2328, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/qr_fact.jl", "max_stars_repo_name": "mohamed82008/InplaceQR.jl", "max_stars_repo_head_hexsha": "a66208fefb3c8bf861a8acf6d42ee17e56771069", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-23T04:40:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-06T07:56:58.000Z", "max_issues_repo_path": "src/qr_fact.jl", "max_issues_repo_name": "mohamed82008/InplaceQR.jl", "max_issues_repo_head_hexsha": "a66208fefb3c8bf861a8acf6d42ee17e56771069", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/qr_fact.jl", "max_forks_repo_name": "mohamed82008/InplaceQR.jl", "max_forks_repo_head_hexsha": "a66208fefb3c8bf861a8acf6d42ee17e56771069", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-27T16:55:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-27T16:55:50.000Z", "avg_line_length": 21.3577981651, "max_line_length": 79, "alphanum_fraction": 0.4265463918, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145364, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7833579043138551}}
{"text": "\"Evaluate the Laplace 2D single layer potential kernel\"\nfunction laplace_slp(x, y)\n    T = eltype(x)\n    if norm(x-y) < eps(T)\n         return zero(Complex{T})\n    else\n        return complex(1/2/pi*log(norm(x-y)))\n    end\nend\n\n\nexport Laplace_SLP_2D\n\"The single layer potential kernel of the Laplace equation.\"\nstruct Laplace_SLP_2D{T} <: BoundaryKernel\nend\n\nLaplace_SLP_2D() = Laplace_SLP_2D{Float64}()\n\n(kernel::Laplace_SLP_2D)(t, tau, param, x, y) = laplace_slp(x, y)\n(kernel::Laplace_SLP_2D)(x, tau, param, y) = laplace_slp(x, y)\n\nis_symmetric(::Laplace_SLP_2D) = true\n\nsingularity(::Laplace_SLP_2D) = LogSingularDiagonal()\n\n\"Evaluate the Laplace 2D double layer potential kernel\"\nlaplace_dlp(x, y, normal_y, z = norm(x-y)) =\n    (normal_y' * (x-y)) / z^2/2/pi\n\n\"Evaluate the Laplace 2D double layer potential kernel\"\n\nfunction laplace_dlp_kernel(x, y, tau, param)\n    z = norm(x-y)\n    if abs(z) > eps(eltype(x))\n        return Complex{Float64}(laplace_dlp(x, y, normal(param, tau), z))\n    else\n        return Complex{Float64}(0)\n    end\nend\n\nexport Laplace_DLP_2D\n\n\"The double layer potential kernel of the Laplace equation in 2D.\"\nstruct Laplace_DLP_2D{T} <: BoundaryKernel\nend\n\nLaplace_DLP_2D() = Laplace_DLP_2D{Float64}()\n\nBasisFunctions.name(kernel::Laplace_DLP_2D) = \"2D Laplace double layer potential kernel\"\n\n(kernel::Laplace_DLP_2D)(t, tau, param, x, y) =\n    laplace_dlp_kernel(x, y, tau, param)\n(kernel::Laplace_DLP_2D)(x, tau, param, y) =\n    laplace_dlp_kernel(x, y, tau, param)\n\nis_symmetric(::Laplace_DLP_2D) = false\n\n# The kernel is continuous but its derivative is singular\nsingularity(::Laplace_DLP_2D) = LogSingularDiagonal()\n\n\"Adjoint Double layer potential for Laplace equation\"\n\nexport Laplace_adjDLP_2D\n\"The adjoint double layer potential kernel of the Laplace equation in 2D.\"\nstruct Laplace_adjDLP_2D{T} <: BoundaryKernel\nend\n\nlaplace_adjdlp(x, y, normal_x, z = norm(x-y)) =\n    (normal_x' * (y-x)) / z^2/2/pi\n\n\"Evaluate the adjoint of the Laplace 2D double layer potential kernel\"\n\nfunction laplace_adjdlp_kernel(x, y, t, param)\n    z = norm(x-y)\n    if abs(z) > 10*eps(eltype(x))\n        return Complex{Float64}(laplace_adjdlp(x, y, normal(param, t), z))\n    else\n        return Complex{Float64}(0)\n    end\nend\n\nLaplace_adjDLP_2D() = Laplace_adjDLP_2D{Float64}()\n\nBasisFunctions.name(kernel::Laplace_adjDLP_2D) = \"Adjoint of 2D Laplace double layer potential kernel\"\n\n(kernel::Laplace_adjDLP_2D)(t, tau, param, x, y) =\n    laplace_adjdlp_kernel(x, y, t, param)\n\nis_symmetric(::Laplace_adjDLP_2D) = false\n\n# The kernel is continuous but its derivative is singular\nsingularity(::Laplace_adjDLP_2D) = LogSingularDiagonal()\n## Some boundary conditions\n\nexport laplace_bcond_harmonic, laplace_param_bcond_harmonic, laplace_parboundary_condition_potential_flow\n\nharmonic_poly(z) = z^2-z+2\n\nboundary_condition_harmonic(x) = real(harmonic_poly(x[1]+im*x[2]))\n\n\"Return a field function that evaluates to a plane wave.\"\nlaplace_bcond_harmonic() = (x,y) -> boundary_condition_harmonic(SVector(x,y))\n\n\"Return a parametric boundary function that evaluates to a plane wave.\"\nlaplace_param_bcond_harmonic(param) =\n    t -> boundary_condition_harmonic(applymap(param, t))\n\n\"Return a parametric boundary function corresponding to the unperturbed flow at r=∞\"\nlaplace_parboundary_condition_potential_flow(param, velocity) =\n    t -> velocity'*normal(param, t)\n", "meta": {"hexsha": "79b5bfc22c6fe573f9a02fe56a37fde11a8a4e7c", "size": 3376, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/applications/laplace.jl", "max_stars_repo_name": "daanhb/IntegralEquations2D.jl", "max_stars_repo_head_hexsha": "644cc7d1f6494504cfa660542d3e3c7f153d7ef3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/applications/laplace.jl", "max_issues_repo_name": "daanhb/IntegralEquations2D.jl", "max_issues_repo_head_hexsha": "644cc7d1f6494504cfa660542d3e3c7f153d7ef3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/applications/laplace.jl", "max_forks_repo_name": "daanhb/IntegralEquations2D.jl", "max_forks_repo_head_hexsha": "644cc7d1f6494504cfa660542d3e3c7f153d7ef3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4144144144, "max_line_length": 105, "alphanum_fraction": 0.735485782, "num_tokens": 1064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996141, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7833579029716236}}
{"text": "\nusing Images\nusing ImageView\nusing MAT\nusing LinearAlgebra\nusing Statistics\nusing Plots\n\nvars = matread(\"../../DATA/allFaces.mat\")\n\nn = Int(vars[\"n\"])\nm = Int(vars[\"m\"])\nfaces = vars[\"faces\"]\nnfaces = Int.(vars[\"nfaces\"])\n\n# We use the first 36 people for training data\ntrainingFaces = faces[:,1:sum(nfaces[1:36])];\navgFace = mean(trainingFaces, dims = 2) # size n*m by 1\n\n# Compute eigenfaces on mean-subtracted training data\nX = trainingFaces - avgFace * ones(1, size(trainingFaces)[2])\nU, S, V = svd(X)\n\nimshow(reshape(avgFace, n, m)) # Show avg face\nimshow(reshape(U[:,1], n, m))  # Show first eigenface\n\n# Now show eigenface reconstruction of image that was omitted from test set\n\ntestFace = faces[:,1+sum(nfaces[1:36])] # First face of person 37\nimshow(reshape(testFace, n, m))\n\ntestFaceMS = testFace - avgFace\nfor r = [25, 50, 100, 200, 400, 800, 1600]\n    reconFace = avgFace + (U[:,1:r]*(U[:,1:r]'*testFaceMS))\n    imshow(reshape(reconFace, n, m))\nend\n\n\n# Project person 2 and 7 onto PC5 and PC6\n\nP1num = 2; # Person number 2\nP2num = 7; # Person number 7\n\nP1 = faces[:,1+sum(nfaces[1:P1num-1]):sum(nfaces[1:P1num])]\nP2 = faces[:,1+sum(nfaces[1:P2num-1]):sum(nfaces[1:P2num])]\n\nP1 = P1 - avgFace * ones(1, size(P1)[2])\nP2 = P2 - avgFace * ones(1, size(P2)[2])\n\nPCAmodes = [5, 6] # Project onto PCA modes 5 and 6\nPCACoordsP1 = U[:,PCAmodes]'*P1\nPCACoordsP2 = U[:,PCAmodes]'*P2\n\np1 = scatter(PCACoordsP1[1,:], PCACoordsP1[2,:], mc = :blue, legend = false)\nscatter!(PCACoordsP2[1,:], PCACoordsP2[2,:], mc = :red)\n", "meta": {"hexsha": "4e0b005e8b704c1c875e596b341b3dcd7fe0f4a4", "size": 1519, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ddsae/CODE/CH01/CH01_SEC06_2_3_4.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "ddsae/CODE/CH01/CH01_SEC06_2_3_4.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "ddsae/CODE/CH01/CH01_SEC06_2_3_4.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 27.125, "max_line_length": 76, "alphanum_fraction": 0.6695194207, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7833427961823105}}
{"text": "\"\"\"\n    compute_linear_return_array(priceArray::Array{Float64,1})\n\nStuff will go here. Awesome stuff, the most beautiful stuff ever.\n\"\"\"\nfunction compute_linear_return_array(priceArray::Array{Float64,1})::PSResult\n\n    # initialize -\n    linear_return_array = Array{Float64,1}()\n\n    # get the size -\n    number_of_time_steps = length(priceArray)\n    for time_index = 2:number_of_time_steps\n        value = (priceArray[time_index] / priceArray[time_index - 1]) - 1\n        push!(linear_return_array, value)\n    end\n\n    # return -\n    return PSResult(linear_return_array)\nend\n\n\"\"\"\n    compute_linear_return_array(dataTable::DataFrame; key::Symbol = Symbol(\"adjusted_close\"))\n\nStuff will go here. Awesome stuff, the most beautiful stuff ever.\n\"\"\"\nfunction compute_linear_return_array(dataTable::DataFrame; key::Symbol=Symbol(\"adjusted_close\"))\n\n    # initialize -\n    price_array = Float64[]\n\n    # iterate to build the price array -\n    (number_of_rows, number_of_cols) = size(dataTable)\n    for row_index = 1:number_of_rows\n        data_value = dataTable[row_index,key]\n        push!(price_array, data_value)\n    end\n\n    # return -\n    return compute_linear_return_array(price_array)\nend\n\n\"\"\"\n    compute_log_return_array(priceArray::Array{Float64})\n\nStuff will go here. Awesome stuff, the most beautiful stuff ever.\n\"\"\"\nfunction compute_log_return_array(priceArray::Array{Float64})::PSResult\n\n    # initialize -\n    log_return_array = Array{Float64,1}()\n\n    # get the size -\n    number_of_time_steps = length(priceArray)\n    for time_index = 2:number_of_time_steps\n        value = log((priceArray[time_index] / priceArray[time_index - 1]))\n        push!(log_return_array, value)\n    end\n\n    # return -\n    return PSResult(log_return_array)\nend\n\n\"\"\"\n    compute_log_return_array(dataTable::DataFrame; key::Symbol = Symbol(\"adjusted_close\"))\n\nStuff will go here. Awesome stuff, the most beautiful stuff ever.\n\"\"\"\nfunction compute_log_return_array(dataTable::DataFrame; key::Symbol=Symbol(\"adjusted_close\"))::PSResult\n\n    # initialize -\n    price_array = Float64[]\n\n    # iterate to build the price array -\n    (number_of_rows, number_of_cols) = size(dataTable)\n    for row_index = 1:number_of_rows\n        data_value = dataTable[row_index,key]\n        push!(price_array, data_value)\n    end\n\n    # return -\n    return compute_log_return_array(price_array)\nend\n\n\"\"\"\n    compute_return_volatility(dataTable::DataFrame; returnCalcFunction::Function=compute_linear_return_array,\n        key::Symbol = Symbol(\"adjusted_close\"))\n\nStuff will go here. Awesome stuff, the most beautiful stuff ever.\n\"\"\"\nfunction compute_return_volatility(dataTable::DataFrame; returnCalcFunction::Function=compute_linear_return_array,\n    key::Symbol=Symbol(\"adjusted_close\"))::PSResult\n\n    # initialize -\n    price_array = Float64[]\n\n    # iterate to build the price array -\n    (number_of_rows, number_of_cols) = size(dataTable)\n    for row_index = 1:number_of_rows\n        data_value = dataTable[row_index,key]\n        push!(price_array, data_value)\n    end\n\n    # we have the difference -\n    result = returnCalcFunction(price_array)\n    if (isa(result.value, Exception) == true)\n        return result\n    end\n    price_return_array = result.value\n    \n    # compute the std -\n    volatlity = std(price_return_array)\n\n    # return -\n    return PSResult(volatlity)\nend\n\n\"\"\"\n    compute_return_volatility(priceArray::Array{Float64};\n        returnCalcFunction::Function=compute_linear_return_array)\n\nStuff will go here. Awesome stuff, the most beautiful stuff ever.\n\"\"\"\nfunction compute_return_volatility(priceArray::Array{Float64};\n    returnCalcFunction::Function=compute_linear_return_array)::PSResult\n\n    # compute the return array -\n    result = returnCalcFunction(priceArray)\n    if (isa(result.value, Exception) == true)\n        return result\n    end\n    volatlity = std(result.value)\n\n    # return -\n    return PSResult(volatlity)\nend", "meta": {"hexsha": "a7ddfb8248de30eb06d49df33b084d7c8fafb91e", "size": 3924, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/base/Return.jl", "max_stars_repo_name": "Pooksoft/PooksoftAssetModelingKit.jl", "max_stars_repo_head_hexsha": "9be23efe332570960197d464e9e8cf5f35326b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-11T07:33:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T07:33:43.000Z", "max_issues_repo_path": "src/base/Return.jl", "max_issues_repo_name": "Pooksoft/PooksoftAssetModelingKit.jl", "max_issues_repo_head_hexsha": "9be23efe332570960197d464e9e8cf5f35326b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/base/Return.jl", "max_forks_repo_name": "Pooksoft/PooksoftAssetModelingKit.jl", "max_forks_repo_head_hexsha": "9be23efe332570960197d464e9e8cf5f35326b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-05T17:59:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T17:59:06.000Z", "avg_line_length": 28.8529411765, "max_line_length": 114, "alphanum_fraction": 0.7171253823, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538936, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7833427960411796}}
{"text": "function decompose_vector(v::Vector3, k::Vector3)\n    v_parallel = (v ⋅ k) * k\n    v_perpendicular = v - v_parallel\n    v_parallel, v_perpendicular\nend\n\nfunction rotate_around(v::Vector3, k::Vector3, φ::Real)\n    k = normalize(k)\n    v_parallel, v_perpendicular = decompose_vector(v, k)\n    ω = k × v_perpendicular\n    v_parallel + v_perpendicular * cos(φ) + ω * sin(φ)\nend\n\n@_with_default_rng function random_3d_direction()\n    θ = 2π * rand(rng)\n    z = 2 * rand(rng) - 1\n    r = √(1 - z ^ 2)\n    Vector3(r * cos(θ), r * sin(θ), z)\nend\n\n\"\"\"\n    random_direction_on_plane([rng], normal_vector)\n    random_direction_on_plane([rng], u, v)\n\nGenerate a random direction on a plane defined by a normal vector or two vectors on the plane.\n\"\"\"\nrandom_direction_on_plane(rng::AbstractRNG, u::Vector3, v::Vector3) = let φ = 2π * rand(rng)\n    w = cos(φ) * u + sin(φ) * v\nend\n@_with_default_rng function random_direction_on_plane(normal_vector::Vector3)\n    a, b, c = normal_vector\n    u = normalize(Vector3(b - c, -a + c, a - b))\n    v = normalize(normal_vector × u)\n    random_direction_on_plane(rng, u, v)\nend\n", "meta": {"hexsha": "c88ca01791945ef18977d46a71f8a9fc69730deb", "size": 1104, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/3d_math.jl", "max_stars_repo_name": "sunoru/MosiBase.jl", "max_stars_repo_head_hexsha": "2cd8fba1f64cff3c968a6bea9d9944fed8898e30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/3d_math.jl", "max_issues_repo_name": "sunoru/MosiBase.jl", "max_issues_repo_head_hexsha": "2cd8fba1f64cff3c968a6bea9d9944fed8898e30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-24T22:17:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T22:17:11.000Z", "max_forks_repo_path": "src/utils/3d_math.jl", "max_forks_repo_name": "sunoru/MosimoBase.jl", "max_forks_repo_head_hexsha": "1ac9aadc82d299b2c85a900a18e42db5f9f84988", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6666666667, "max_line_length": 94, "alphanum_fraction": 0.6711956522, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7833427874826883}}
{"text": "# using OrdinaryDiffEq\r\nusing ModelingToolkit\r\nusing DataDrivenDiffEq\r\nusing LinearAlgebra, DiffEqSensitivity, Optim\r\nusing DiffEqFlux, Flux\r\nusing Plots\r\nusing DifferentialEquations\r\ngr()\r\n\r\nfunction lotka(du, u, p, t)\r\n    α, β, γ, δ = p\r\n    du[1] = α*u[1] - β*u[2]*u[1]\r\n    du[2] = γ*u[1]*u[2]  - δ*u[2]\r\nend\r\n\r\n# Define the experimental parameter\r\ntspan = (0.0f0,3.0f0)\r\nu0 = Float32[0.44249296,4.6280594]\r\np_ = Float32[1.3, 0.9, 0.8, 1.8]\r\nprob = ODEProblem(lotka, u0,tspan, p_)\r\nsolution = solve(prob, Vern7(), abstol=1e-12, reltol=1e-12, saveat = 0.1)\r\n\r\nscatter(solution, alpha = 0.25)\r\nplot!(solution, alpha = 0.5)\r\n\r\n# Ideal data\r\nX = Array(solution)\r\n# Add noise to the data\r\nprintln(\"Generate noisy data\")\r\nXₙ = X + Float32(1e-3)*randn(eltype(X), size(X))\r\n\r\n# Define the neueral network which learns L(x, y, y(t-τ))\r\n# Actually, we do not care about overfitting right now, since we want to\r\n# extract the derivative information without numerical differentiation.\r\nL = FastChain(FastDense(2, 32, tanh),FastDense(32, 32, tanh), FastDense(32, 2))\r\np = initial_params(L)\r\n\r\nfunction dudt_(u, p,t)\r\n    x, y = u\r\n    z = L(u,p)\r\n    [p_[1]*x + z[1],\r\n    -p_[4]*y + z[2]]\r\nend\r\n\r\nprob_nn = ODEProblem(dudt_,u0, tspan, p)\r\nsol_nn = concrete_solve(prob_nn, Tsit5(), u0, p, saveat = solution.t)\r\n\r\nplot(solution)\r\nplot!(sol_nn)\r\n\r\nfunction predict(θ)\r\n    Array(concrete_solve(prob_nn, Tsit5(), u0, θ, saveat = solution.t,\r\n                         abstol=1e-6, reltol=1e-6,\r\n                         sensealg = InterpolatingAdjoint(autojacvec=ReverseDiffVJP())))\r\n    # @show Array(concrete_solve(prob_nn, Vern7(), u0, θ, saveat = solution.t,\r\n    #                                           abstol=1e-6, reltol=1e-6,\r\n    #                                           sensealg = InterpolatingAdjoint(autojacvec=ReverseDiffVJP())))\r\n  #   tmp_prob = remake(prob_nn,u0=u0,p=θ)\r\n  # tmp_sol =  solve(tmp_prob, Rodas4(), saveat = solution.t,\r\n  #                                           abstol=1e-6, reltol=1e-6,\r\n  #                                           sensealg = InterpolatingAdjoint(autojacvec=ReverseDiffVJP()))\r\n  # # @show size(Array(tmp_sol))\r\n  # pred =  Array(tmp_sol)\r\nend\r\n\r\n# No regularisation right now\r\nfunction loss(θ)\r\n    pred = predict(θ)\r\n    sum(abs2, Xₙ .- pred), pred\r\nend\r\n\r\n# Test\r\nloss(p)\r\n\r\nconst losses = []\r\n\r\ncallback(θ,l,pred) = begin\r\n    @show l\r\n    push!(losses, l)\r\n    if length(losses)%50==0\r\n        println(\"Current loss after $(length(losses)) iterations: $(losses[end])\")\r\n    end\r\n    false\r\nend\r\n\r\n# First train with ADAM for better convergence\r\nres1 = DiffEqFlux.sciml_train(loss, p, ADAM(0.5), cb=callback, maxiters = 100)\r\n\r\n# Train with BFGS\r\nres2 = DiffEqFlux.sciml_train(loss, res1.minimizer, BFGS(initial_stepnorm=0.01), cb=callback, maxiters = 10)\r\n\r\nprintln(\"Final training loss after $(length(losses)) iterations: $(losses[end])\")\r\n\r\n# Plot the losses\r\nplot(losses, yaxis = :log, xaxis = :log, xlabel = \"Iterations\", ylabel = \"Loss\")\r\n\r\n# Plot the data and the approximation\r\nNNsolution = predict(res2.minimizer)\r\n# Trained on noisy data vs real solution\r\nplot(solution.t, NNsolution')\r\nplot!(solution.t, X')\r\n\r\n# Ideal derivatives\r\nDX = Array(solution(solution.t, Val{1}))\r\n\r\nprob_nn2 = ODEProblem(dudt_,u0, tspan, res2.minimizer)\r\n_sol = solve(prob_nn2, Tsit5())\r\nDX_ = Array(_sol(solution.t, Val{1}))\r\n\r\n# The learned derivatives\r\nplot(DX')\r\nplot!(DX_')\r\n\r\n# Ideal data\r\nL̄ = [-p_[2]*(X[1,:].*X[2,:])';p_[3]*(X[1,:].*X[2,:])']\r\n# Neural network guess\r\nL̂ = L(Xₙ,res2.minimizer)\r\n\r\nscatter(L̄')\r\nplot!(L̂')\r\n\r\n# Plot the error\r\nscatter(abs.(L̄-L̂)', yaxis = :log)\r\n\r\n## Sparse Identification \r\n\r\n# Create a Basis\r\n@variables u[1:2]\r\n# Lots of polynomials\r\npolys = Operation[1]\r\n\r\nfor i ∈ 1:5\r\n    push!(polys, u[1]^i)\r\n    push!(polys, u[2]^i)\r\n    for j ∈ i:5\r\n        if i != j\r\n            push!(polys, (u[1]^i)*(u[2]^j))\r\n            push!(polys, u[2]^i*u[1]^i)\r\n        end\r\n    end\r\nend\r\n\r\n# And some other stuff\r\nh = [cos.(u)...; sin.(u)...; polys...]\r\nbasis = Basis(h, u)\r\n\r\n# Create an optimizer for the SINDy problem\r\nopt = SR3()\r\n# Create the thresholds which should be used in the search process\r\nλ = exp10.(-7:0.1:3)\r\n# Target function to choose the results from; x = L0 of coefficients and L2-Error of the model\r\ng(x) = x[1] < 1 ? Inf : norm(x, 2)\r\n# Test on original data and without further knowledge\r\nprintln(\"SINDy on full ideal, unavailable data\")\r\nΨ = SINDy(Xₙ[:, :], DX[:, :], basis, λ, opt, g = g, maxiter = 10000) # Fail\r\nprintln(Ψ)\r\nprint_equations(Ψ)\r\n\r\n# Test on ideal derivative data for unknown function ( not available )\r\nprintln(\"SINDy on partial ideal, unavailable data\")\r\nΨ = SINDy(Xₙ[:, 1:end], L̄[:, 1:end], basis, λ,opt, g = g, maxiter = 10000) # Succeed\r\nprintln(Ψ)\r\nprint_equations(Ψ)\r\n\r\n# Test on uode derivative data\r\nprintln(\"SINDy on learned, partial, available data\")\r\nΨ = SINDy(Xₙ[:, 2:end], L̂[:, 2:end], basis, λ,  opt, g = g, maxiter = 10000, normalize = true, denoise = true) # Succeed\r\nprintln(Ψ)\r\nprint_equations(Ψ)\r\n\r\n# Extract the parameter\r\np̂ = parameters(Ψ)\r\nprintln(\"First parameter guess : $(p̂)\")\r\n\r\n# The parameters are a bit off, but the equations are recovered\r\n# Start another SINDy run to get closer to the ground truth\r\n# Create function\r\nunknown_sys = ODESystem(Ψ)\r\nunknown_eq = ODEFunction(unknown_sys)\r\n\r\n# Just the equations\r\nb = Basis((u, p, t)->unknown_eq(u, [1.; 1.], t), u)\r\n\r\n# Retune for better parameters -> we could also use DiffEqFlux or other parameter estimation tools here.\r\nΨf = SINDy(Xₙ[:, 2:end], L̂[:, 2:end], b, STRRidge(0.01), maxiter = 100, convergence_error = 1e-18) # Succeed\r\nprintln(Ψf)\r\np̂ = parameters(Ψf)\r\nprintln(\"Second parameter guess : $(p̂)\")\r\n\r\n# Create function\r\nrecovered_sys = ODESystem(Ψf)\r\nrecovered_eq = ODEFunction(recovered_sys)\r\n\r\n# Build a ODE for the estimated system\r\nfunction dudt(du, u, p, t)\r\n    # Add SINDy Term\r\n    α, δ, β, γ = p\r\n    z = recovered_eq(u, [β; γ], t)\r\n    du[1] = α*u[1] + z[1]\r\n    du[2] = -δ*u[2] + z[2]\r\nend\r\n\r\n# Create the approximated problem and solution\r\nps = [p_[[1,4]]; p̂]\r\napproximate_prob = ODEProblem(dudt, u0, tspan, ps)\r\napproximate_solution = solve(approximate_prob, Tsit5(), saveat = 0.01)\r\n\r\n# Plot\r\nplot(solution)\r\nplot!(approximate_solution)\r\n\r\n## Simulation\r\n\r\n# Look at long term prediction\r\nt_long = (0.0, 50.0)\r\napproximate_prob = ODEProblem(dudt, u0, t_long, ps)\r\napproximate_solution_long = solve(approximate_prob, Tsit5(), saveat = 0.1) # Using higher tolerances here results in exit of julia\r\nplot(approximate_solution_long)\r\n\r\ntrue_prob = ODEProblem(lotka, u0, t_long, p_)\r\ntrue_solution_long = solve(true_prob, Tsit5(), saveat = approximate_solution_long.t)\r\nplot!(true_solution_long)\r\n\r\n\r\n\r\nusing JLD2\r\n@save \"knowledge_enhanced_NN.jld2\" solution recovered_sys approximate_solution_long NNsolution L true_solution_long Xₙ L̄ L̂\r\n@load \"knowledge_enhanced_NN.jld2\" solution recovered_sys approximate_solution_long NNsolution L true_solution_long Xₙ L̄ L̂\r\n\r\nc1 = 3 # RGBA(174/255,192/255,201/255,1) # Maroon\r\nc2 = :orange # RGBA(132/255,159/255,173/255,1) # Red\r\nc3 = :blue # RGBA(255/255,90/255,0,1) # Orange\r\nc4 = :purple # RGBA(153/255,50/255,204/255,1) # Purple\r\n\r\np1 = plot(0.1:0.1:tspan[end],abs.(Array(solution)[:,2:end] .- NNsolution[:,2:end])' .+ eps(Float32),\r\n          lw = 3, yaxis = :log, title = \"Timeseries of UODE Error\",\r\n          color = [3 :orange], xlabel = \"t\",\r\n          label = [\"x(t)\" \"y(t)\"],\r\n          titlefont = \"Helvetica\", legendfont = \"Helvetica\",\r\n          legend = :topright)\r\n\r\n# Plot L₂\r\np2 = plot(X[1,:], X[2,:], L̂[2,:], lw = 3,\r\n     title = \"Neural Network Fit of U2(t)\", color = c1,\r\n     label = \"Neural Network\", xaxis = \"x\", yaxis=\"y\",\r\n     titlefont = \"Helvetica\", legendfont = \"Helvetica\",\r\n     legend = :bottomright)\r\nplot!(X[1,:], X[2,:], L̄[2,:], lw = 3, label = \"True Missing Term\", color=c2)\r\n\r\np3 = scatter(solution, color = [c1 c2], label = [\"x data\" \"y data\"],\r\n             title = \"Extrapolated Fit From Short Training Data\",\r\n             titlefont = \"Helvetica\", legendfont = \"Helvetica\",\r\n             markersize = 5)\r\n\r\nplot!(p3,true_solution_long, color = [c1 c2], linestyle = :dot, lw=5, label = [\"True x(t)\" \"True y(t)\"])\r\nplot!(p3,approximate_solution_long, color = [c3 c4], lw=1, label = [\"Estimated x(t)\" \"Estimated y(t)\"])\r\nplot!(p3,[2.99,3.01],[0.0,maximum(hcat(Array(solution),Array(approximate_solution_long)))],lw=2,color=:black)\r\nannotate!([(1.5,9,text(\"Training \\nData\", 10, :center, :top, :black, \"Helvetica\"))])\r\nl = @layout [grid(1,2)\r\n             grid(1,1)]\r\nplot(p1,p2,p3,layout = l)\r\n\r\nsavefig(\"sindy_extrapolation.pdf\")", "meta": {"hexsha": "a4715447162c8f4076dfbb27e3e9d99e1b9aba01", "size": 8635, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "neuralODE modeling/nn_ode_lotka_example.jl", "max_stars_repo_name": "vaglino/kinetic_modeling", "max_stars_repo_head_hexsha": "2a15f74df5844eb21d5bf47bc9014b6bf74f84e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "neuralODE modeling/nn_ode_lotka_example.jl", "max_issues_repo_name": "vaglino/kinetic_modeling", "max_issues_repo_head_hexsha": "2a15f74df5844eb21d5bf47bc9014b6bf74f84e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neuralODE modeling/nn_ode_lotka_example.jl", "max_forks_repo_name": "vaglino/kinetic_modeling", "max_forks_repo_head_hexsha": "2a15f74df5844eb21d5bf47bc9014b6bf74f84e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8326996198, "max_line_length": 131, "alphanum_fraction": 0.6289519398, "num_tokens": 2815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640645, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.783308155327408}}
{"text": "using Random\nRandom.seed!(1)\n\nN = 10^5\nprob1 = 0.7\neps0, eps1 = 0.1, 0.05\n\nflipWithProb(bit,prob) = rand() < prob ? xor(bit,1) : bit\n\nTxData = rand(N) .< prob1\nRxData = [x == 0 ? flipWithProb(x,eps0) : flipWithProb(x,eps1) for x in TxData]\n\nnumTx1 = 0\ntotalRx1 = 0\nfor i in 1:N\n   if RxData[i] == 1\n        global totalRx1 += 1\n        global numTx1 += TxData[i]\n    end\nend\n\nmonteCarlo = numTx1/totalRx1\nanalytic = ((1-eps1)*0.7)/((1-eps1)*0.7+0.3*eps0)\n\nprintln(\"Monte Carlo: \", monteCarlo, \"\\t\\tAnalytic: \", analytic)\n", "meta": {"hexsha": "dfd578db4bfcf582dab377b3ecef555d8e59c65d", "size": 521, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2_chapter/txRxBayes.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "2_chapter/txRxBayes.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "2_chapter/txRxBayes.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 20.0384615385, "max_line_length": 79, "alphanum_fraction": 0.6218809981, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7832964463826563}}
{"text": "import Statistics.cor\n\n# Autocorrelation\n\n#TODO: move to another file to maintain a more logical structure\n\nfunction lagindex(x::Vector{Float64}, n::Int=1)::UnitRange{Int}\n    @assert n < size(x,1)\n    N = size(x, 1)\n    idx = 1:N\n    if n == 0\n        return idx\n    elseif n > 0\n        return idx[n+1:N]\n    elseif n < 0\n        return idx[1:N+n]\n    end\nend\n\n\nfunction lag(x::Vector{Float64}, n::Int=1; pad::Bool=true, padval::Float64=NaN)\n    if n==0\n        return x\n    elseif n>0\n        if pad\n            return [ones(n)*padval; x[n+1:end]]\n        else\n            return x[n+1:end]\n        end\n    elseif n<0\n        n *= -1\n        if pad\n            return [x[1:end-n]; ones(n)*padval]\n        else\n            return x[1:end-n]\n        end\n    end\nend\n\n\nfunction corlag(x::AbstractArray{T,1}, n::Int=1) where {T<:Number}\n    if n == 0\n        return 1.0\n    end\n    @assert n > 0\n    @assert n < size(x,1) - 2\n    idx = collect(lagindex(x, n))\n    return cor(x[idx.-n], x[idx])\nend\n\nfunction acf(x::Vector{T}, maxlag::Int=15; lags::AbstractArray{Int,1}=0:maxlag)::Vector{Float64} where {T<:Number}\n    @assert all(lags .< size(x,1)-2)\n    return map((n) -> corlag(x, n), lags)\nend\n\nfunction acf(x::Matrix{T}, maxlag::Int=15; lags::AbstractVector{Int}=0:maxlag)::Matrix{Float64} where {T<:Number}\n    k = size(x,2)\n    out = zeros(Float64, (length(lags), k))\n    @inbounds for j in 1:k\n        out[:,j] = acf(x[:,j], maxlag, lags=lags)\n    end\n    return out\nend\n\n\"\"\"\n    acf(x::TS,maxlag::Int=15;lags::AbstractArray{Int,1}=0:maxlag)\n    acf(x::Vector{T},maxlag::Int=15;lags::AbstractArray{Int,1}=0:maxlag)::Vector{Float64}where{T<:Number}\n    acf(x::Matrix{T},maxlag::Int=15;lags::AbstractVector{Int}=0:maxlag)::Matrix{Float64}where{T<:Number}\n\nCompute the autocorrelation function of a time series.\n\nThe output will be a matrix with the same number of columns as the input time series `x`\nand number of rows equal to the number of lags used as inputs to the autocorrelation function.\n\n...\n# Arguments\n- `x::TS`: Time series object array containing columns on which to compute autocorrelation.\n- `maxlag::Int=15`: Maximum lag of the autocorrelation series.\nOptional args:\n- `lags::AbstractArray{Int,1}=0:maxlag`: Explicitly specified list of lags to use (overrides use of `maxlag`).\n...\n\"\"\"\nacf(x::TS, maxlag::Int=15; lags::AbstractArray{Int,1}=0:maxlag) = acf(x.values, maxlag; lags=lags)\n", "meta": {"hexsha": "52d644ef081efbc77946be1eb2fbfb9709766d7b", "size": 2405, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/calc/models.jl", "max_stars_repo_name": "josecohenca/Temporal.jl", "max_stars_repo_head_hexsha": "6af5b3d3320d8bb15558193c6c35488772a283e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 96, "max_stars_repo_stars_event_min_datetime": "2016-02-25T22:25:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T02:53:09.000Z", "max_issues_repo_path": "src/calc/models.jl", "max_issues_repo_name": "josecohenca/Temporal.jl", "max_issues_repo_head_hexsha": "6af5b3d3320d8bb15558193c6c35488772a283e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44, "max_issues_repo_issues_event_min_datetime": "2016-12-26T22:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-21T19:09:56.000Z", "max_forks_repo_path": "src/calc/models.jl", "max_forks_repo_name": "josecohenca/Temporal.jl", "max_forks_repo_head_hexsha": "6af5b3d3320d8bb15558193c6c35488772a283e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-03-30T02:46:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T00:09:28.000Z", "avg_line_length": 28.630952381, "max_line_length": 114, "alphanum_fraction": 0.6253638254, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.783296444677522}}
{"text": "\"\"\"\n    norm1(v)\n\nNormalize `v` to sum 1.\n\"\"\"\nfunction norm1(v)\n    vs = sum(v)\n    if vs ≈ 1.0\n        return v\n    else\n        return v ./ vs\n    end\nend\n\n\n\"\"\"\n    infovalue(p, q)\n\nCompute the symmetric Relative Entropy (Kullback-Liebler Divergence) between `p` and `q`,\ntwo probability vectors or two frequency count vectors.\nValue is bounded within [0, ∞].\n\"\"\"\nfunction infovalue(p, q)\n    pn = norm1(p)\n    qn = norm1(q)\n\n    kldivergence(pn, qn) + kldivergence(qn, pn)\nend\ninfovalue(f::AbstractMatrix) = infovalue(f[:, 1], f[:, 2])\ninfovalue(f::NamedArray) = infovalue(f.array)\n\n\n\"\"\"\n    cramerv(f::AbstractMatrix{T}) where T <: Real\n\nCompute Cramer's V of a contingency table `f`.\\\\\nϕ coefficient is √(χ²/n), bounded within [0, √min(row-1,col-1)],\nCramer's V is ϕ/√min(row-1,col-1), bounded within [0,1].\n\"\"\"\nfunction cramerv(f::AbstractMatrix{T}) where {T<:Real}\n    minimum(size(f)) >= 2 || throw(ArgumentError(\"Matrix needed, not single row or column\"))\n\n    p = norm1(f)\n    rp = sum(p; dims = 2)               # row marginal\n    cp = sum(p; dims = 1)               # column marginal\n    ep = rp .* cp                       # expected probabilities\n    ϕ² = sum((p .- ep) .^ 2 ./ ep)      # ϕ²\n\n    sqrt(ϕ² / (minimum(size(f)) - 1))   # Cramer's V\nend\ncramerv(f::NamedArray) = cramerv(f.array)\n\n\n\"\"\"\n    cramerv(x::Vector{T} where T<:Integer, y::Vector{T} where T<:Integer)\n\nCompute Cramer's V of two presumed discrete vectors `x` and `y`.\\\\\n\"\"\"\ncramerv(x::Vector{T} where {T<:Integer}, y::Vector{T} where {T<:Integer}) =\n    cramerv(freqtable(x, y).array)\n\n\n\"\"\"\n    cramerv(x::Vector, y::Vector; groups = 10)\n\nCompute Cramer's V of two presumed continuous vectors `x` and `y`,\nvectors are binned into `groups` first.\n\"\"\"\nfunction cramerv(x::AbstractVector, y::AbstractVector; groups = 10)\n    xr = ranks(x; groups = groups)\n    yr = ranks(y, groups = groups)\n\n    cramerv(freqtable(xr, yr).array)\nend\n\n\n\"\"\"\n    mutualinfo(f::AbstractMatrix{T}) where T <: Real\n\nCompute the mutual information of frequency matrix `f`;\nvalue is bounded within [0, log(min(size(`f`)))].\n\"\"\"\nfunction mutualinfo(f::AbstractMatrix{T} where {T<:Real})\n    minimum(size(f)) >= 2 || throw(ArgumentError(\"Matrix needed, not single row or column\"))\n\n    ps = norm1(f)\n    px = sum(ps; dims = 2)\n    py = sum(ps; dims = 1)\n\n    entropy(px) + entropy(py) - entropy(ps)\nend\nmutualinfo(f::NamedArray) = mutualinfo(f.array)\n\n\n\"\"\"\n    mutualinfo(x::Vector{T} where T<:Integer, y::Vector{T} where T<:Integer)\n\nCompute mutual information of two presumed discrete vectors `x` and `y`.\\\\\n\"\"\"\nmutualinfo(x::Vector{T} where {T<:Integer}, y::Vector{T} where {T<:Integer}) =\n    mutualinfo(freqtable(x, y).array)\n\n\n\"\"\"\n    mutualinfo(x::Vector, y::Vector)\n\nCompute the mutual information of two presumed continuous vectors `x` and `y`.\n\"\"\"\nfunction mutualinfo(x::AbstractVector, y::AbstractVector; groups = 10)\n    xr = ranks(x; groups = groups)\n    yr = ranks(y, groups = groups)\n\n    mutualinfo(freqtable(xr, yr).array)\nend\n\n\n\"\"\"\n    eda(df::AbstractDataFrame, target::Symbol)\n\nReturn a dataframe of Mutual Information and Cramer's V between `target` and other\nvariables in `df`. If `target` is binary, Information Value is also returned.\n\nThe dataframe is sorted by descending Mutual Information.\n\"\"\"\nfunction eda(df::AbstractDataFrame, target::Symbol; groups = 20)::AbstractDataFrame\n    t = df[!, target]\n    tnlvl = length(unique(t))\n    tnlvl <= 1 && throw(ArgumentError(\"Target is single valued\"))\n\n    if tnlvl > groups\n        t = ranks(t, groups = groups)\n        tnlvl = length(unique(t))\n    end\n\n    println(\"Target: $target   type: $(typeof(t))   Levels: $tnlvl\")\n\n    lk = ReentrantLock()\n\n    if tnlvl == 2\n        out = DataFrame(\n            Variable   = Symbol[],\n            Vartype    = String[],\n            Varlvls    = Int[],\n            MutualInfo = Float64[],\n            CramerV    = Float64[],\n            InfoValue  = Float64[],\n        )\n\n        Threads.@threads for v in propertynames(df)\n            v == target && continue\n\n            vtype = eltype(df[!, v])\n            if vtype <: Union{Missing,Real}\n                vb = ranks(df[!, v], groups = groups)\n            else\n                vb = df[!, v]\n            end\n\n            frq = proptable(vb, t).array\n            vnlvl = size(frq, 1)\n            if vnlvl == 1\n                println(\"Warning: [$v] is singled valued, skipped.\")\n                continue\n            elseif vnlvl > 50\n                println(\"Note: [$v] has more than 100 levels, consider binning\")\n            end\n\n            mutin = mutualinfo(frq)\n            cramv = cramerv(frq)\n            iv = infovalue(frq[:, 1], frq[:, 2])\n\n            lock(lk)\n            push!(out, (v, string(vtype), vnlvl, mutin, cramv, iv))\n            unlock(lk)\n        end\n    else\n        out = DataFrame(\n            Variable   = Symbol[],\n            Vartype    = String[],\n            Varlvls    = Int[],\n            MutualInfo = Float64[],\n            CramerV    = Float64[],\n        )\n\n        Threads.@threads for v in propertynames(df)\n            v == target && continue\n\n            vtype = eltype(df[!, v])\n            if vtype <: Union{Missing,Real}\n                vb = ranks(df[!, v], groups = groups)\n            else\n                vb = df[!, v]\n            end\n\n            frq = proptable(vb, t).array\n            vnlvl = size(frq, 1)\n            if vnlvl == 1\n                println(\"Warning: [$v] is singled valued, skipped.\")\n                continue\n            elseif vnlvl > 50\n                println(\"Note: [$v] has more than 100 levels, consider binning\")\n            end\n\n            mutin = mutualinfo(frq)\n            cramv = cramerv(frq)\n\n            lock(lk)\n            push!(out, (v, string(vtype), vnlvl, mutin, cramv))\n            unlock(lk)\n        end\n    end\n\n    sort!(out, [:MutualInfo, :CramerV], rev = true)\nend\n", "meta": {"hexsha": "738edbb9cc5e6f928017b9152065dc35e30bb836", "size": 5879, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/eda.jl", "max_stars_repo_name": "DaymondLing/ExploratoryDataAnalysis.jl", "max_stars_repo_head_hexsha": "e9aea2d47d666e869b0566b802945e3ac4235fce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/eda.jl", "max_issues_repo_name": "DaymondLing/ExploratoryDataAnalysis.jl", "max_issues_repo_head_hexsha": "e9aea2d47d666e869b0566b802945e3ac4235fce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eda.jl", "max_forks_repo_name": "DaymondLing/ExploratoryDataAnalysis.jl", "max_forks_repo_head_hexsha": "e9aea2d47d666e869b0566b802945e3ac4235fce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3441860465, "max_line_length": 92, "alphanum_fraction": 0.5614900493, "num_tokens": 1636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7832964412672537}}
{"text": "\"\"\"\n    Multivector2{T <: Real} <: AbstractMultivector{T}\n\nAn immutable 4-tuple of real numbers that represents a member\nof a 2-dimensional multivector algebra.\n\nEach `Multivector2` has the form\n```math\n    p+qB\n```\nwhere ``p`` and ``q`` are 1-dimensional multivectors, or\n```math\n    a+bA+cB+dAB\n```\nwhere ``a``, ``b``, ``c``, and ``d`` are real (and of the same type),\nand ``A * A = 0``, ``B * B = 0``, and ``AB = A * B = -B * A``.\nHere ``*`` is the wedge product.\n\"\"\"\nstruct Multivector2{T <: Real} <: AbstractMultivector{T}\n    l::Multivector1{T}\n    r::Multivector1{T}\n\n    Multivector2{U}(l::Multivector1{U}, r::Multivector1{U}) where {U <: Real} = new(l, r)\nend\n\nfunction Multivector2(x::Multivector1{T}, y::Multivector1{T}) where {T <: Real}\n    Multivector2{T}(x, y)\nend\n\nfunction Multivector2(z::Multivector1)\n    Multivector2(z, zero(z))\nend\n\nfunction Multivector2(a::T, b::T, c::T, d::T) where {T <: Real}\n    Multivector2{T}(Multivector1{T}(a, b), Multivector1{T}(c, d))\nend\n\nfunction Multivector2(a::T, b::T, c::T) where {T <: Real}\n    Multivector2{T}(Multivector1{T}(a, b), Multivector1{T}(c, zero(T)))\nend\n\nfunction Multivector2(a::T, b::T) where {T <: Real}\n    Multivector2{T}(Multivector1{T}(a, b), zero(Multivector1{T}))\nend\n\nfunction Multivector2(a::T) where {T <: Real}\n    Multivector2{T}(Multivector1{T}(a, zero(T)), zero(Multivector1{T}))\nend\n\nfunction Multivector2(a::Real, b::Real, c::Real, d::Real)\n    Multivector2(promote(a, b, c, d)...)\nend\n\nfunction Multivector2(a::Real, b::Real, c::Real)\n    Multivector2(promote(a, b, c)...)\nend\n\nfunction Multivector2(a::Real, b::Real)\n    Multivector2(promote(a, b)...)\nend\n\nfunction Multivector2(x::Multivector1, y::Multivector1)\n    Multivector2(promote(x.l, x.r, y.l, y.r)...)\nend\n\nfunction show(io::IO, z::Multivector2)\n    print(io, \"[1: \")\n    print(io, z.l.l)\n    print(io, \", A: \")\n    print(io, z.l.r)\n    print(io, \", B: \")\n    print(io, z.r.l)\n    print(io, \", AB: \")\n    print(io, z.r.r)\n    print(io, \"]\")\nend\n\nfunction real(z::Multivector2)\n    real(z.l)\nend\n\nfunction unreal(z::Multivector2)\n    vcat(unreal(z.l), asarray(z.r))\nend\n\nfunction zero(z::Multivector2{T}) where {T <: Real}\n    Multivector2{T}(zero(z.l), zero(z.r))\nend\n\nfunction zero(::Type{Multivector2{T}}) where {T <: Real}\n    Multivector2(zero(T), zero(T), zero(T), zero(T))\nend\n\nfunction one(z::Multivector2{T}) where {T <: Real}\n    Multivector2{T}(one(z.l), zero(z.r))\nend\n\nfunction one(::Type{Multivector2{T}}) where {T <: Real}\n    Multivector2(one(T), zero(T), zero(T), zero(T))\nend\n\n\"\"\"\n    conj{T <: Real}(z::Multivector2{T})\n\nThe `Multivector2` conjugate. If ``z=a+bA+cB+dAB``, then `conj(z)` gives\n```math\n    a-bA-cB-dAB\n```\nThis operation is an involution.\n\"\"\"\nfunction conj(z::Multivector2{T}) where {T <: Real}\n    Multivector2{T}(conj(z.l), -z.r)\nend\n\n\"\"\"\n    cloak{T <: Real}(z::Multivector2{T})\n\nThe cloak conjugate changes the sign of even blades. If ``z=a+bA+cB+dAB``, then `cloak(z)` gives\n```math\n    -a+bA+cB-dAB\n```\nThis operation is equivalent to `-dagger(z)` and thus is also an involution.\n\"\"\"\nfunction cloak(z::Multivector2{T}) where {T <: Real}\n    Multivector2{T}(cloak(z.l), dagger(z.r))\nend\n\n\"\"\"\n    dagger{T <: Real}(z::Multivector2{T})\n\nThe dagger conjugate changes the sign of odd blades. If ``z=a+bA+cB+dAB``, then `dagger(z)` gives\n```math\n    a-bA-cB+dAB\n```\nThis operation is an involution.\n\"\"\"\nfunction dagger(z::Multivector2{T}) where {T <: Real}\n    Multivector2{T}(dagger(z.l), cloak(z.r))\nend\n\n\"\"\"\n    star{T <: Real}(z::Multivector2{T})\n\nReturns the Hodge star conjugate. If ``z=a+bA+cB+dAB``, then `star(z)` gives\n```math\n    d-cA+bB+aAB\n```\nThis operation is not an involution, but `star(star(z)) = dagger(z)`.\n\"\"\"\nfunction star(z::Multivector2{T}) where {T <: Real}\n    Multivector2{T}(dagger(star(z.r)), star(z.l))\nend\n\n\"\"\"\n    selfstar(z::Multivector2)\n\nThe self-star-conjugate part.\nThis operation is idempotent.\n\"\"\"\nfunction selfstar(z::Multivector2)\n    (z + star(z) + dagger(z) + star(dagger(z))) / 4\nend\n\n\"\"\"\n    antiselfstar(z::Multivector2)\n\nThe anti-self-star-conjugate part.\nThis operation is idempotent.\n\"\"\"\nfunction antiselfstar(z::Multivector2)\n    (z - star(z) + dagger(z) - star(dagger(z))) / 4\nend\n\nfunction (+)(x::Multivector2, y::Multivector2)\n    Multivector2(x.l + y.l, x.r + y.r)\nend\n\nfunction (+)(x::Multivector2, y::Multivector1)\n    Multivector2(x.l + y, x.r)\nend\n\nfunction (+)(x::Multivector1, y::Multivector2)\n    Multivector2(x + y.l, y.r)\nend\n\nfunction (+)(z::Multivector2, a::Real)\n    Multivector2(z.l + a, z.r)\nend\n\nfunction (+)(a::Real, z::Multivector2)\n    Multivector2(z.l + a, z.r)\nend\n\nfunction (-)(z::Multivector2{T}) where {T <: Real}\n    Multivector2{T}(-z.l, -z.r)\nend\n\nfunction (-)(x::Multivector2, y::Multivector2)\n    Multivector2(x.l - y.l, x.r - y.r)\nend\n\nfunction (-)(x::Multivector2, y::Multivector1)\n    Multivector2(x.l - y, x.r)\nend\n\nfunction (-)(x::Multivector1, y::Multivector2)\n    Multivector2(x - y.l, -y.r)\nend\n\nfunction (-)(z::Multivector2, a::Real)\n    Multivector2(z.l - a, z.r)\nend\n\nfunction (-)(a::Real, z::Multivector2)\n    Multivector2(a - z.l, -z.r)\nend\n\n\"\"\"\n    (*)(x::Multivector2, y::Multivector2)\n\nWedge product of 2-dimensional multivectors.\nThis operation is non-commutative but associative.\n\"\"\"\nfunction (*)(x::Multivector2, y::Multivector2)\n    Multivector2(x.l * y.l,  (y.r * x.l) + (x.r * conj(y.l)))\nend\n\nfunction (*)(x::Multivector2, y::Multivector1)\n    Multivector2(x.l * y, x.r * conj(y))\nend\n\nfunction (*)(x::Multivector1, y::Multivector2)\n    Multivector2(x * y.l,  y.r * x)\nend\n\n\"\"\"\n    (*)(z::Multivector2, a::Real)\n    (*)(a::Real, z::Multivector2)\n\nScaling and/or reflection of a `Multivector2` by a real number.\n\"\"\"\nfunction (*)(z::Multivector2, a::Real)\n    Multivector2(z.l * a, z.r * a)\nend\n\nfunction (*)(a::Real, z::Multivector2)\n    Multivector2(a * z.l, a * z.r)\nend\n\nfunction (/)(x::Multivector2, y::Multivector2)\n    if iszerodivisor(y)\n        error(ZeroDivisorDenominator)\n    end\n\n    x * inv(y)\nend\n\nfunction (\\)(y::Multivector2, x::Multivector2)\n    if iszerodivisor(y)\n        error(ZeroDivisorDenominator)\n    end\n\n    inv(y) * x\nend\n\nfunction (/)(z::Multivector2, a::Real)\n    Multivector2(z.l / a, z.r / a)\nend\n\nfunction (\\)(a::Real, z::Multivector2)\n    Multivector2(a \\ z.l, a \\ z.r)\nend\n\nfunction random(::Type{Multivector2{T}}) where T <: Real\n    Multivector2{T}(random(Multivector1{T}), random(Multivector1{T}))\nend\n", "meta": {"hexsha": "66409c78d8cf062001f166dacd5499870a6e92ac", "size": 6426, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Multivector2.jl", "max_stars_repo_name": "meirizarrygelpi/MultivectorAlgebras.jl", "max_stars_repo_head_hexsha": "e10863368e92a4b66240dff483ca21d3314bad4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Multivector2.jl", "max_issues_repo_name": "meirizarrygelpi/MultivectorAlgebras.jl", "max_issues_repo_head_hexsha": "e10863368e92a4b66240dff483ca21d3314bad4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Multivector2.jl", "max_forks_repo_name": "meirizarrygelpi/MultivectorAlgebras.jl", "max_forks_repo_head_hexsha": "e10863368e92a4b66240dff483ca21d3314bad4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1985559567, "max_line_length": 97, "alphanum_fraction": 0.6342981637, "num_tokens": 2253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7832964267247521}}
{"text": "\"\"\"\n    eom_henon2(dx, x, p, n)\n\nEquations of motion for a 2D Henon system consisting of two identical \nHenon maps with unidirectional forcing ``X \\\\to Y `` [1].\n    \n## Equations of motion \n    \nThe equations of motion are \n    \n```math\n\\\\begin{aligned}\nx_1(t+1) &= 1.4 - x_1^2(t) + 0.3x_2(t) \\\\\\\\\nx_2(t+1) &= x_1(t) \\\\\\\\\ny_1(t+1) &= 1.4 - [c_{xy} x_1(t) y_1(t) + (1-c_{xy}) y_1^2(t)] + 0.3 y_2(t) \\\\\\\\\ny_2(t+1) &= y_1(t)\n\\\\end{aligned}\n```\n    \n## References\n    \n1. Krakovská, A., Jakubík, J., Chvosteková, M., Coufal, D., Jajcay, N., & Paluš, M. (2018). \n    Comparison of six methods for the detection of causality in a bivariate time series. \n    Physical Review E, 97(4), 042207.\n\"\"\"\nfunction eom_henon2(x, p, n)\n    c_xy = p[1]\n    x₁, x₂, y₁, y₂ = (x...,)\n    dx₁ = 1.4 - x₁^2 + 0.3*x₂\n    dx₂ = x₁\n    dy₁ = 1.4 - (c_xy * x₁ * y₁  +  (1 - c_xy)*y₁^2) + 0.3*y₂\n    dy₂ = y₁\n    return SVector{4}(dx₁, dx₂, dy₁, dy₂)\nend\n\nfunction henon2(u₀, c_xy)\n    p = [c_xy]\n    DiscreteDynamicalSystem(eom_henon2, u₀, p)\nend\n\n\"\"\"\n    henon2(;u₀ = rand(4), c_xy = 2.0) -> DiscreteDynamicalSystem\n\nInitialize a 2D Henon system consisting of two identical Henon maps with\nunidirectional forcing ``X \\\\to Y `` [1].\n\n## Equations of motion \n\nThe equations of motion are \n\n```math\n\\\\begin{aligned}\nx_1(t+1) &= 1.4 - x_1^2(t) + 0.3x_2(t) \\\\\\\\\nx_2(t+1) &= x_1(t) \\\\\\\\\ny_1(t+1) &= 1.4 - [c_{xy} x_1(t) y_1(t) + (1-c_{xy}) y_1^2(t)] + 0.3 y_2(t) \\\\\\\\\ny_2(t+1) &= y_1(t)\n\\\\end{aligned}\n```\n\n## References\n\n1. Krakovská, A., Jakubík, J., Chvosteková, M., Coufal, D., Jajcay, N., & Paluš, M. (2018). \n    Comparison of six methods for the detection of causality in a bivariate time series. \n    Physical Review E, 97(4), 042207.\n\"\"\"\nhenon2(;u₀ = rand(4), c_xy = 2.0) = henon2(u₀, c_xy)\n", "meta": {"hexsha": "e1826459f6f8d6e0ec9bd93afad782e1c65e5ee6", "size": 1770, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/systems/discretemaps/henon2.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/CausalityTools.jl-5520caf5-2dd7-5c5d-bfcb-a00e56ac49f7", "max_stars_repo_head_hexsha": "93935b3bc73738c52b004e9cf23d6f6a4778982c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2020-06-11T01:51:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T18:39:43.000Z", "max_issues_repo_path": "src/systems/discretemaps/henon2.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/CausalityTools.jl-5520caf5-2dd7-5c5d-bfcb-a00e56ac49f7", "max_issues_repo_head_hexsha": "93935b3bc73738c52b004e9cf23d6f6a4778982c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2020-12-21T02:52:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T10:40:08.000Z", "max_forks_repo_path": "src/systems/discretemaps/henon2.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/CausalityTools.jl-5520caf5-2dd7-5c5d-bfcb-a00e56ac49f7", "max_forks_repo_head_hexsha": "93935b3bc73738c52b004e9cf23d6f6a4778982c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-09-27T08:56:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T15:05:51.000Z", "avg_line_length": 26.4179104478, "max_line_length": 92, "alphanum_fraction": 0.5875706215, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.841825655188238, "lm_q1q2_score": 0.7832836338034055}}
{"text": "using LifeContingencies\nusing MortalityTables\nusing Dates\nusing DataFrames\n\nmort_table_name = \"2012 IAM Period Table – Male, ANB\"\nimprov_table = \"Projection Scale G2 – Male, ANB\"\niss_date = Date(2017,09,01)\nval_date = Date(2017,12,31)\nissue_age = 65\nannual_income = 12000\ndeferral_period = 0\nbenefit_period = 120\ninterest_rate = 0.04\n\n# Not used because table name provides \n# sex = :M\n# projection_scale = :G2\n# age_rule = :ANB\n\n\nmort = MortalityTables.table(mort_table_name)\nimp = MortalityTables.table(improv_table)\n\ntable_end = omega(mort)\n\n# the projection scale table only goes to age 105, wheras we want  through age 120\nfunction imp_rate(table,age)\n    if age > lastindex(table)\n        return 0.0\n    else\n        return table[age]\n    end\nend\n\nSRA = map(0:(table_end - issue_age)) do time\n    \n    att_age = issue_age + time\n    \n    if time > 1 \n        imp_factor = prod(map(age -> 1 - imp_rate(imp,age),issue_age:(att_age-1)))\n    else\n        imp_factor = 1.0\n    end\n    \n    # returned values for each time\n    \n    (\n        att_age = att_age,\n        t=time,\n        q=mort[att_age],\n        imp_factor = imp_factor,\n        q_imp = mort[att_age] * imp_factor,\n        \n    )\nend\n\n### A type to handle life contingent maths via the LifeContingencies package\nins = LifeContingency(\n    SingleLife(\n        mort = UltimateMortality([x.q_imp for x in SRA],start_age = issue_age), # mort is indexed by attained age, not starting at 1\n        issue_age = issue_age\n    ),\n    InterestRate(interest_rate)\n)\n\n\nä(ins,55) * annual_income\nsum(LifeContingencies.APV.(ins,1:55) * 12000)\n\n\n\nℓ₁ = [43302,42854,42081,41351,40050]\nℓ₂ = [47260,47040,46755,46500,46227]\n\nps₁ =  ℓ₁ ./ ℓ₁[1]\nqs₁ = [1 - ps₁[t] / ps₁[t - 1] for t in 2:5 ] \n\nps₂ =  ℓ₂ ./ ℓ₂[1]\nqs₂ = [1 - ps₂[t] / ps₂[t - 1] for t in 2:5 ] \n\nm1 = UltimateMortality(qs₁, start_age=65)\nm2 = UltimateMortality(qs₂, start_age=60)\n\n\nl1 = SingleLife(mort = m1, issue_age = 65)\nl2 = SingleLife(mort = m2, issue_age = 60)\n\njl = JointLife(lives=(l1, l2), contingency = LastSurvivor(), joint_assumption=Frasier())\n\n\n\nins = LifeContingency(jl,InterestRate(0.05))\nins_l1 = LifeContingency(jl.lives[1],InterestRate(0.05))\nins_l2 = LifeContingency(jl.lives[2],InterestRate(0.05))\n# problem 9.1.f", "meta": {"hexsha": "f8b72a16d98d5cc414f9bf0c2e35246c4f14822e", "size": 2245, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scratchpad.jl", "max_stars_repo_name": "JuliaActuary/LifeContingencies.jl", "max_stars_repo_head_hexsha": "397999a995b45dc3be5c50f8b1f1c27424e22b05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-10-02T02:09:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T04:08:19.000Z", "max_issues_repo_path": "src/scratchpad.jl", "max_issues_repo_name": "JuliaActuary/ActuarialScience.jl", "max_issues_repo_head_hexsha": "9ae50c86bf7344711242ea907c8341438ad34076", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 39, "max_issues_repo_issues_event_min_datetime": "2020-04-21T04:58:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T19:45:58.000Z", "max_forks_repo_path": "src/scratchpad.jl", "max_forks_repo_name": "JuliaActuary/ActuarialScience.jl", "max_forks_repo_head_hexsha": "9ae50c86bf7344711242ea907c8341438ad34076", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-27T16:16:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T12:18:47.000Z", "avg_line_length": 23.3854166667, "max_line_length": 132, "alphanum_fraction": 0.6703786192, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7832836259730144}}
{"text": "# Log sum exp.\nfunction lse(arr)\n    max = maximum(arr)\n    max == -Inf ? -Inf : max + log(sum(exp.(arr .- max)))\nend\n\nfunction lse(x1::Real, x2::Real)\n    m = max(x1, x2)\n    m == -Inf ? m : m + log(exp(x1 - m) + exp(x2 - m))\nend\n\n# Effective sample size.\nfunction ess(lnw::Vector{Float64})\n    log_ess = -lse(2. * lnw)\n    return exp(log_ess)\nend\n\n# Normalize log weights.\nfunction nw(lw::Vector{Float64})\n    lt = lse(lw)\n    lnw = lw .- lt\n    return (lt, lnw)\nend\n", "meta": {"hexsha": "5e0e9a73067292ccd3a34259b4e25a6623f50edc", "size": 469, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/numerical.jl", "max_stars_repo_name": "mschauer/Jaynes.jl", "max_stars_repo_head_hexsha": "f76ec08b4e4eb517ae55c52232b0f6ec0914a469", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/numerical.jl", "max_issues_repo_name": "mschauer/Jaynes.jl", "max_issues_repo_head_hexsha": "f76ec08b4e4eb517ae55c52232b0f6ec0914a469", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-10T14:49:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T14:49:08.000Z", "max_forks_repo_path": "src/utils/numerical.jl", "max_forks_repo_name": "mschauer/Jaynes.jl", "max_forks_repo_head_hexsha": "f76ec08b4e4eb517ae55c52232b0f6ec0914a469", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5416666667, "max_line_length": 57, "alphanum_fraction": 0.5799573561, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191309994468, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7832597828708225}}
{"text": "#=\n  From the WebPPL model:https://github.com/probmods/ppaml2016/blob/gh-pages/chapters/5-data.md\n  \"\"\"\n  Here, we explore the result of an experiment with 15 trials and binary outcomes (e.g., flipping a coin with an \n  uncertain weight, asking people if they'll vote for Hillary Clinton or Donald Trump, ...)\n  \"\"\"\n=#\n\nusing Turing\ninclude(\"jl_utils.jl\")\n\n@model function bda(k=1,n=15)\n    p ~ Uniform(0, 1)\n    \n    # Observed k number of successes, assuming a binomial\n    k ~ Binomial(n, p)\n    \n    # sample from binomial with updated p\n    posteriorPredictive ~ Binomial(n,p)\n    \n    # sample fresh p\n    prior_p ~ Uniform(0,1)\n    # sample from binomial with fresh p\n    priorPredictive ~ Binomial(n,prior_p)\n   \nend\n\n# data\nk = 1  # number of successes\nn = 15 # number of attempts\n\nmodel = bda(k,n)\n\n# chns = sample(model, MH(), 10_000)\n# chns = sample(model, PG(15), 10_000)\n# chns = sample(model, IS(), 10_000)\nchns = sample(model, SMC(), 10_000)\n# chns = sample(model, SMC(), MCMCThreads(), 10_000, 4)\n\ndisplay(chns)\n\nshow_var_dist_pct(chns, :priorPredictive)\nshow_var_dist_pct(chns, :posteriorPredictive)\n", "meta": {"hexsha": "6fdc34aedf3122d7a1cd6c94530d1f9f6f8d567c", "size": 1118, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/bda.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/bda.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/bda.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 25.4090909091, "max_line_length": 113, "alphanum_fraction": 0.6815742397, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810481379379, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7832110900194779}}
{"text": "\"\"\"\nA recursive implementation of divided differences.\n\"\"\"\nmutable struct DividedDifference{T}\n    memo::Dict{Tuple{Int64,Int64},T}\n    DividedDifference{T}() where {T <: Real} = new(Dict{Tuple{Int64,Int64},T}())\nend\n\n\n\"\"\"\nCalculate divided differences of a function f at points τ. This calculates the divided difference\nfrom τ_i to τ_j. The `dd` is a memoization.\n\"\"\"\nfunction divided_difference(i::Integer, j::Integer, τ::Vector, f::Vector, dd::DividedDifference)\n    if (i, j) ∈ keys(dd.memo)\n        return dd.memo[(i, j)]\n    end\n    \n    val = zero(Float64)\n    if i == j\n        val = f[i]\n    elseif i < j\n        val = (divided_difference(i + 1, j, τ, f, dd) - divided_difference(i, j - 1, τ, f, dd)) /\n            (τ[j] - τ[i])\n    else\n        throw(ArgumentError(\"divided_difference needs i <= j, found i = {i}, j = {j}\"))\n    end\n    dd.memo[(i, j)] = val\n    val\nend\n\n\nfunction divided_difference_explicit(\n    i::Integer, k::Integer, τ::Vector, f::Vector{T}) where {T <: Real}\n\n    total = zero(T)\n    for j = i:k\n        denom = one(T)\n        for l = i:k\n            if l != j\n                denom *= τ[j] -τ[l]\n            end\n        end\n        total += f[j] / denom\n    end\n    total\nend\n", "meta": {"hexsha": "6f56c102bbf7522a12e37a9f0df63ec3b6fcb5ee", "size": 1210, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/divided_differences.jl", "max_stars_repo_name": "adolgert/Glissa.jl", "max_stars_repo_head_hexsha": "0b9dfc7cfdbc8a2ea76e96f968a833badd4d95d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/divided_differences.jl", "max_issues_repo_name": "adolgert/Glissa.jl", "max_issues_repo_head_hexsha": "0b9dfc7cfdbc8a2ea76e96f968a833badd4d95d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/divided_differences.jl", "max_forks_repo_name": "adolgert/Glissa.jl", "max_forks_repo_head_hexsha": "0b9dfc7cfdbc8a2ea76e96f968a833badd4d95d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2083333333, "max_line_length": 97, "alphanum_fraction": 0.5661157025, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810525948928, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7832110876368826}}
{"text": "# using JuMP, VariationalInequality\n# using Base.Test\n\nusing JuMP, VariationalInequality\n# include(\"../src/model.jl\")\n# include(\"../src/algorithms.jl\")\n\n# https://cdr.lib.unc.edu/indexablecontent/uuid:778ca632-74ca-4858-8c3c-6dcfc7e6e703\n# Example 4.2. This example is adapted from the example in (Fukushima, 1986). Let\nm = VIPModel()\n@variable(m, x[1:3])\n\n@NLconstraint(m, x[1]^2 + 0.4x[2]^2 + 0.6x[3]^2 <= 1)\n@NLconstraint(m, 0.6x[1]^2 + 0.4x[2]^2 + x[3]^2 <= 1)\n@NLconstraint(m, x[1] + x[2] + x[3] >= sqrt(3))\n\n@NLexpression(m, F1, 2x[1] + 0.2x[1]^3 - 0.5x[2] + 0.1x[3] - 4)\n@NLexpression(m, F2, -0.5x[1] + x[2] + 0.1x[2]^3 + 0.5)\n@NLexpression(m, F3, 0.5x[1] - 0.2x[2] + 2x[3] - 0.5)\n\ncorrespond(m, F1, x[1])\ncorrespond(m, F2, x[2])\ncorrespond(m, F3, x[3])\n# or\n# correspond(m, [F1, F2, F3], x)\n\n\nsolveVIP(m, algorithm=:fixed_point, max_iter=1000, step_size=0.1)\nsol1, Fval1, gap1 = saveSolution(m)\n@assert 0<= gap1 < 1e-6\n\n# The above `solveVIP` sets the value of variables at the solution\nclearValues(m)\n\nsolveVIP(m, algorithm=:extra_gradient, max_iter=1000, step_size=0.1)\nsol2, Fval2, gap2 = saveSolution(m)\n@assert 0<= gap2 < 1e-6\n\n# sol2, Fval2, gap2 = solveVIP(m, algorithm=:hyperplane, max_iter=1000, step_size=0.1)\n\n@show sol1\n@show sol2\n@show gap1\n@show gap2\n\n\n\n# OKAY.\n# x∗ = (0.9168, 0.4850, 0.3303)\n", "meta": {"hexsha": "1d90d372b2e25a8d1ca93480d544a884615b9c83", "size": 1316, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/fukushima2.jl", "max_stars_repo_name": "JuliaPackageMirrors/VariationalInequality.jl", "max_stars_repo_head_hexsha": "95864879a7f1c897d0a07526c2d6c2fb522a3ea2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/fukushima2.jl", "max_issues_repo_name": "JuliaPackageMirrors/VariationalInequality.jl", "max_issues_repo_head_hexsha": "95864879a7f1c897d0a07526c2d6c2fb522a3ea2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/fukushima2.jl", "max_forks_repo_name": "JuliaPackageMirrors/VariationalInequality.jl", "max_forks_repo_head_hexsha": "95864879a7f1c897d0a07526c2d6c2fb522a3ea2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.32, "max_line_length": 86, "alphanum_fraction": 0.6542553191, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666346, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7832110855406623}}
{"text": "factorial_ij(i::Integer, j::Integer) = factorial(big(min(i,j))) / factorial(big(max(i,j)))\n\nz(x::Real, p::Real) = sqrt(2.)*(x + p*im)\nz(x::Vector{<:Real}, p::Vector{<:Real}) = z.(x, p')\n\nα(m::Integer, n::Integer) = n - m\nα(m::Vector{<:Integer}, n::Vector{<:Integer}) = α.(min.(m, n'), max.(m, n'))\n\ngaussian_function(x::Real, p::Real) = exp(-0.5 * abs2(z(x,p))) / π\ngaussian_function(x::Vector{<:Real}, p::Vector{<:Real}) = gaussian_function.(x,p')\n\nneg_one_to_power_of(i::Integer) = (i % 2 == 0) ? 1 : -1\n\nfunction coefficient_of_wave_function(m::Integer, n::Integer)\n    if n ≥ m\n        return neg_one_to_power_of(m) * sqrt(factorial_ij(m, n))\n    else\n        return neg_one_to_power_of(n) * sqrt(factorial_ij(m, n))\n    end\nend\n\ncoefficient_of_wave_function(m::Vector{<:Integer}, n::Vector{<:Integer}) = coefficient_of_wave_function.(m, n')\n\nfunction z_to_power(m::Integer, n::Integer, x::Real, p::Real)\n    if n ≥ m\n        return conj(z(x, p'))^(n - m)\n    else\n        return z(x, p')^(m - n)\n    end\nend\n\nfunction z_to_power(m::Vector{<:Integer}, n::Vector{<:Integer}, x::Vector{<:Real}, p::Vector{<:Real})\n    x = reshape(x, 1, 1, length(x))\n    p = reshape(p, 1, 1, 1, length(p))\n    z_to_power.(m, n', x, p)\nend\n\nfunction z_to_power(m::Vector{<:Integer}, n::Vector{<:Integer})\n    function z_to_power_xp(x::Vector{<:Real}, p::Vector{<:Real})\n        x = reshape(x, 1, 1, length(x))\n        p = reshape(p, 1, 1, 1, length(p))\n        z_to_power.(m, n', x, p)\n    end\n    return z_to_power_xp\nend\n\nfunction z_to_power(x::Vector{<:Real}, p::Vector{<:Real})\n    x = reshape(x, 1, 1, length(x))\n    p = reshape(p, 1, 1, 1, length(p))\n    function z_to_power_mn(m::Vector{<:Integer}, n::Vector{<:Integer})\n        z_to_power.(m, n', x, p)\n    end\n    return z_to_power_mn\nend\n", "meta": {"hexsha": "92a4a118a21c0c2661f96295285ca2b2e294c037", "size": 1782, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "yuehhua/SqState.jl", "max_stars_repo_head_hexsha": "95d06c0478663570181647d1f7cd80ecdd3b69b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "yuehhua/SqState.jl", "max_issues_repo_head_hexsha": "95d06c0478663570181647d1f7cd80ecdd3b69b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "yuehhua/SqState.jl", "max_forks_repo_head_hexsha": "95d06c0478663570181647d1f7cd80ecdd3b69b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4, "max_line_length": 111, "alphanum_fraction": 0.6021324355, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741281688026, "lm_q2_score": 0.8221891392358014, "lm_q1q2_score": 0.7831961024974018}}
{"text": "#############################################################################\n# JuMP\n# An algebraic modelling langauge for Julia\n# See http://github.com/JuliaOpt/JuMP.jl\n#############################################################################\n# minellipse.jl\n#\n# This example is from the Boyd & Vandenberghe book \"Convex Optimization\".\n# If PyPlot is installed, passing the argument `plot` will plot\n# the solution, e.g. julia minellipse.jl plot\n#\n# Given a set of ellipses centered on the origin\n# E(A) = { u | u^T inv(A) u <= 1 }\n# find a \"minimal\" ellipse that contains the provided ellipses\n#\n# We can formulate this as an SDP:\n#     minimize  trace(WX)\n#   subject to  X >= A_i,    i = 1,...,m\n#               X PSD\n# where W is a PD matrix of weights to choose between different solutions\n#############################################################################\n\nusing JuMP\nusing Mosek\nusing PyPlot  # Comment out if not installed\n\n# We will use three ellipses\nm = 3\n# Two \"simple\" ones\nAs = Any[ [2.0  0.0;\n           0.0  1.0],\n          [1.0  0.0;\n           0.0  3.0]]\n# and a random one\nrandA = rand(2,2)\npush!(As, (randA' * randA) * (rand()*2+1))\n\n# We change the weights to see different solutions, if they exist\nW = [1.0 0.0\n     0.0 1.0];\n\nmod = Model()\n@variable(mod, X[1:2,1:2], SDP)\n@objective(mod, Min, trace(W*X))\nfor i = 1:m\n    @SDconstraint(mod, X >= As[i])\nend\nsolve(mod)\n\nX_val = getvalue(X)\nprintln(X_val)\n\n# Plot it, if desired (e.g. julia minellipse.jl plot)\nif length(ARGS) > 0 && Pkg.installed(\"PyPlot\") !== nothing\n    # Setup the figure\n    fig = figure()\n    ax = fig[:gca]()\n    ax[:set_xticks]([-4:+4])\n    ax[:set_yticks]([-4:+4])\n\n    # Draw provided ellipses\n    for i = 1:m\n        xs = Float64[]\n        ys = Float64[]\n        for angle in linspace(0, 2*pi, 100)\n            u = [cos(angle),sin(angle)]\n            x = As[i] * u\n            push!(xs, x[1])\n            push!(ys, x[2])\n        end\n        plot(xs, ys, \"b\", linewidth=2.0)\n    end\n\n    # Draw bounding ellipse\n    xs = Float64[]\n    ys = Float64[]\n    for angle in linspace(0, 2*pi, 100)\n        u = [cos(angle),sin(angle)]\n        x = X_val * u\n        push!(xs, x[1])\n        push!(ys, x[2])\n    end\n    plot(xs, ys, \"r\", linewidth=2.0)\n\n    fig[:canvas][:draw]()\n    readline()\nend\n", "meta": {"hexsha": "b3cd3d5f15d108e3174889b140dde88041bbc8af", "size": 2300, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "public/.julia/v0.5/JuMP/examples/minellipse.jl", "max_stars_repo_name": "Giarcr0b/MVO_Tool", "max_stars_repo_head_hexsha": "8f3348b8b56968febca8307acea3ebe1817fccae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-12T03:24:25.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-12T03:24:25.000Z", "max_issues_repo_path": "public/.julia/v0.5/JuMP/examples/minellipse.jl", "max_issues_repo_name": "Giarcr0b/MVO_Tool", "max_issues_repo_head_hexsha": "8f3348b8b56968febca8307acea3ebe1817fccae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "public/.julia/v0.5/JuMP/examples/minellipse.jl", "max_forks_repo_name": "Giarcr0b/MVO_Tool", "max_forks_repo_head_hexsha": "8f3348b8b56968febca8307acea3ebe1817fccae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1363636364, "max_line_length": 77, "alphanum_fraction": 0.5165217391, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741281688026, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7831960941968128}}
{"text": "# Examples borrowed from: http://arxiv.org/pdf/1211.3759.pdf\n\n# 2/3 N(x|0,1) + 1/3 N(x|0,1/10)\nfunction kurtotic(theta)\n    if theta[3] <= 0 || theta[6] <= 0\n        return -Inf\n    end\n    llk = 0\n    for i in 1:length(y)\n      llk += log(theta[1] * pdf(Normal(theta[2], theta[3]), y[i]) + \n                 theta[4] * pdf(Normal(theta[5], theta[6]), y[i]))\n    end\n    return llk\nend\n\nfunction bimodal_density(x)\n    lik = (1/2) * pdf(Normal(-1,2/3),x) + (1/2) * pdf(Normal(1,2/3),x)\n    return log(lik)\nend\n\n# 1/2 N(x|-1,2/3) + 1/2 N(x|1,2/3)\nfunction bimodal_loglikelihood(theta)\n    if theta[3] < 0 || theta[6] < 0\n        return -Inf\n    end\n    llk = 0\n    for i in 1:length(y)\n      llk += log(theta[1] * pdf(Normal(theta[2], theta[3]), y[i]) + \n                 theta[4] * pdf(Normal(theta[5], theta[6]), y[i]))\n    end\n    return -llk\nend\n\n# requires y and x\nfunction logistic_regression(theta)\n    llk = 0\n    eta = [1 / (1 + exp(- x[i,:] * theta))[1] for i in 1:length(y)]\n    for i = 1:length(y)\n        llk += y[i] * log(eta[i]) + (1-y[i]) * log(1-eta[i])\n    end\n    return llk\nend\n\n", "meta": {"hexsha": "8c5f69743744a6fb6f7bf09d8173ef3559f6cf12", "size": 1098, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmarks/julia/densities.jl", "max_stars_repo_name": "JuliaPackageMirrors/SliceSampler.jl", "max_stars_repo_head_hexsha": "a2ff27b2093e048405d223eba92dabdf9048e823", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2015-06-12T04:11:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T11:41:33.000Z", "max_issues_repo_path": "benchmarks/julia/densities.jl", "max_issues_repo_name": "JuliaPackageMirrors/SliceSampler.jl", "max_issues_repo_head_hexsha": "a2ff27b2093e048405d223eba92dabdf9048e823", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/julia/densities.jl", "max_forks_repo_name": "JuliaPackageMirrors/SliceSampler.jl", "max_forks_repo_head_hexsha": "a2ff27b2093e048405d223eba92dabdf9048e823", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-06-12T04:11:17.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-14T07:49:46.000Z", "avg_line_length": 24.9545454545, "max_line_length": 70, "alphanum_fraction": 0.5282331512, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122684798183, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7831646253996867}}
{"text": "using FastTransforms, LinearAlgebra\n\nfunction oprec!(n::Integer, v::AbstractVector, alpha::Real, delta2::Real)\n    if n > 0\n        v[1] = 1\n    end\n    if n > 1\n        v[2] = (4*alpha+8-(alpha+4)*delta2)/4\n    end\n    for i = 1:n-2\n        v[i+2] = (((2*i+alpha+2)*(2*i+alpha+4)+alpha*(alpha+2))/(2*(i+1)*(2*i+alpha+2))*(2*i+alpha+3)/(i+alpha+3) - delta2/4*(2*i+alpha+3)/(i+1)*(2*i+alpha+4)/(i+alpha+3))*v[i+1] - (i+alpha+1)/(i+alpha+3)*(2*i+alpha+4)/(2*i+alpha+2)*v[i]\n    end\n    return v\nend\n\n\"\"\"\nThis example calculates the spectrum of the nonlocal diffusion operator:\n\n```math\nℒ_δ u = ∫_𝕊² ρ_δ(|𝐱-𝐲|)[u(𝐱) - u(𝐲)] dΩ(𝐲),\n```\n\ndefined in Eq. (2) of\n\n    R. M. Slevinsky, H. Montanelli, and Q. Du, A spectral method for nonlocal diffusion operators on the sphere, J. Comp. Phys., 372:893--911, 2018.\n\navailable at https://doi.org/10.1016/j.jcp.2018.06.024\n\"\"\"\nfunction evaluate_lambda(n::Integer, alpha::T, delta::T) where T\n    delta2 = delta*delta\n    scl = (1+alpha)*(2-delta2/2)\n\n    lambda = Vector{T}(undef, n)\n\n    if n > 0\n        lambda[1] = 0\n    end\n    if n > 1\n        lambda[2] = -2\n    end\n\n    oprec!(n-2, view(lambda, 3:n), alpha, delta2)\n\n    for i = 2:n-1\n        lambda[i+1] *= -scl/(i-1)\n    end\n\n    p = plan_jac2jac(T, n-1, zero(T), zero(T), alpha, zero(T))\n\n    lambda[2:end] .= p'lambda[2:end]\n\n    for i = 2:n-1\n        lambda[i+1] = ((2i-1)*lambda[i+1] + (i-1)*lambda[i])/i\n    end\n\n    for i = 2:n-1\n        lambda[i+1] += lambda[i]\n    end\n\n    return lambda\nend\n\nlambda = evaluate_lambda(1024, -0.5, 1.0)\nlambdabf = evaluate_lambda(1024, parse(BigFloat, \"-0.5\"), parse(BigFloat, \"1.0\"))\n\nnorm(lambda-lambdabf, Inf)/norm(lambda, Inf)\n", "meta": {"hexsha": "102e97bf9c4e4d541772331d80076b9bd31f8b89", "size": 1668, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/nonlocaldiffusion.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/FastTransforms.jl-057dd010-8810-581a-b7be-e3fc3b93f78c", "max_stars_repo_head_hexsha": "766d3076b4e3b32206169a4310d4211c2e0a1902", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-15T03:23:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T03:23:28.000Z", "max_issues_repo_path": "examples/nonlocaldiffusion.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/FastTransforms.jl-057dd010-8810-581a-b7be-e3fc3b93f78c", "max_issues_repo_head_hexsha": "766d3076b4e3b32206169a4310d4211c2e0a1902", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/nonlocaldiffusion.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/FastTransforms.jl-057dd010-8810-581a-b7be-e3fc3b93f78c", "max_forks_repo_head_hexsha": "766d3076b4e3b32206169a4310d4211c2e0a1902", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8955223881, "max_line_length": 237, "alphanum_fraction": 0.571942446, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.8723473763375644, "lm_q1q2_score": 0.7831021352080417}}
{"text": "using DifferentialEquations, Flux, DiffEqFlux\nusing Plots\n\nu0 = [1.0,1.0]\ntspan = (0.0,10.0)\ntsteps = 0.0:0.1:10.0\n\nmy_nn = Chain(\n  Dense(2, 32, relu),\n  Dense(32, 2)) |> f64\n\np, re = Flux.destructure(my_nn)\n\nfunction right_hand_side(du,u,p,t)\n  m = re(p)\n  nn_output = m(u)\n  du[1] = nn_output[1]\n  du[2] = nn_output[2]\nend\n\nprob = ODEProblem(right_hand_side,u0,tspan,p)\nsol = solve(prob, Tsit5())\n\n# Plot the solution\nplot(sol)\nsavefig(\"Initial_NN_ODE.png\")\n\nfunction predict_ode(p)\n  tmp_prob = remake(prob, p = p)\n  Array(solve(tmp_prob, Tsit5(), saveat = tsteps))\nend\n\nfunction loss_ode(p)\n    pred = predict_ode(p)\n    loss = sum(abs2, 1.0 .- pred)\n    return loss, pred\nend\n\ncallback = function (p, l, pred)\n  display(l)\n  plt = plot(pred, ylim = (0, 6))\n  display(plt)\n  # Tell sciml_train to not halt the optimization. If return true, then\n  # optimization stops.\n  return false\nend\n\nresult_ode = DiffEqFlux.sciml_train(loss_ode, p,\n                                    cb = callback,\n                                    maxiters = 100)\n\n\nprob_final = ODEProblem(right_hand_side, u0, tspan, result_ode)\nsol_final = solve(prob_final,Tsit5())\nplot(sol_final)\nsavefig(\"NN_ode_optimized.png\") # Both state components close to 1", "meta": {"hexsha": "16a0c650c6cc2fb7e55dd52e6530e6df7f5f9229", "size": 1232, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "NODE_Julia/Prelim_studies/neural_ode_II.jl", "max_stars_repo_name": "Romit-Maulik/Tutorials-Demos-Practice", "max_stars_repo_head_hexsha": "a58ddc819f24a16f7059e63d7f201fc2cd23e03a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-09-02T14:46:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T15:27:05.000Z", "max_issues_repo_path": "NODE_Julia/Prelim_studies/neural_ode_II.jl", "max_issues_repo_name": "Romit-Maulik/Tutorials-Demos-Practice", "max_issues_repo_head_hexsha": "a58ddc819f24a16f7059e63d7f201fc2cd23e03a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2020-11-13T18:49:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:54:43.000Z", "max_forks_repo_path": "NODE_Julia/Prelim_studies/neural_ode_II.jl", "max_forks_repo_name": "Romit-Maulik/Tutorials-Demos-Practice", "max_forks_repo_head_hexsha": "a58ddc819f24a16f7059e63d7f201fc2cd23e03a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-09-25T23:57:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-18T08:15:34.000Z", "avg_line_length": 22.0, "max_line_length": 71, "alphanum_fraction": 0.6517857143, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.783024192771566}}
{"text": "\"\"\"\n# Algorithms with numbers\n\n- Basic arithmetic\n    - Addition\n    - Bases and logs\n    - Multiplication and division\n- Modular arithmetic\n    - Substitution rule\n    - Modular addition and multiplication\n    - Two's complement\n    - Modular exponentiation\n    - Euclid's algorithm for greatest common divisor\n    - Euclid's rule\n    - An extension of Euclid's algorithm\n    - Modular division\n    - Is your social security number a prime?\n- Primality testing\n    - Fermat's little theorem\n    - Hey, that was group theory!\n    - Generating random primes\n    - Lagrange's prime number theorem\n    - Carmichael numbers\n    - Randomized algorithms: a virtual chapter\n- Cryptography\n    - An application of number theory?\n    - Private-key schemes: one-time pad and AES\n    - RSA\n- Universal Hashing\n    - Hash tables\n    - Families of hash functions\n\"\"\"\nmodule Chapter1\n\nexport\n    multiply,\n    divide,\n    modexp,\n    euclid,\n    extendedeuclid,\n    primality,\n    primality2\n\n\"\"\"\n    multiply(x, y)\n\nCompute the product of two integers `x` and `y`.\n\n# Examples\n```jldoctest\njulia> multiply(7, 8)\n56\n```\n\"\"\"\nfunction multiply(x::Integer, y::Integer)\n    if y == 0\n        return 0\n    end\n\n    z = multiply(x, y ÷ 2)\n    if iseven(y)\n        return 2z\n    else\n        return x + 2z\n    end\nend\n\n\"\"\"\n    divide(x, y)\n\nCompute the quotient and remainder of `x ÷ y`.\n\n# Examples\n```jldoctest\njulia> divide(5, 3)\n(1, 2)\n```\n\"\"\"\nfunction divide(x::Integer, y::Integer)\n    if x == 0\n        return (q,r) = (0,0)\n    end\n\n    (q,r) = divide(x ÷ 2, y)\n    q = 2q\n    r = 2r\n    if isodd(x)\n        r = r + 1\n    end\n    if r >= y\n        r = r - y\n        q = q + 1\n    end\n    return (q,r)\nend\n\n\"\"\"\n    modexp(x, y, N)\n\nCompute the modular exponentation `x^y mod N`.\n\n# Examples\n```jldoctest\njulia> modexp(2, 3, 5)\n3\n```\n\"\"\"\nfunction modexp(x::Integer, y::Integer, N::Integer)\n    if y == 0\n        return 1\n    end\n\n    z = modexp(x, y ÷ 2, N)\n    if iseven(y)\n        return mod(z^2, N)\n    else\n        return mod(x * z^2, N)\n    end\nend\n\n\"\"\"\n    euclid(a, b)\n\nUsing Euclid's algorithm, compute the greatest common divisor\nbetween two integers `a` and `b` where `a >= b >= 0`.\n\n# Examples\n```jldoctest\njulia> euclid(25, 20)\n5\n```\n\"\"\"\nfunction euclid(a::Integer, b::Integer)\n    @assert a >= b >= 0\n    if b == 0\n        return a\n    end\n\n    return euclid(b, mod(a, b))\nend\n\n\"\"\"\n    extendedeuclid(a, b)\n\nA simple extension of Euclid's algorithm.\n\n- Input: Two positive integers `a` and `b` with `a >= b >= 0`.\n- Ouput: Integers `x`, `y`, `d` such that `d = gcd(a,b)` and `ax + by = d`.\n\n# Examples\n```jldoctest\njulia> extendedeuclid(9, 6)\n(1, -1, 3)\n```\n\"\"\"\nfunction extendedeuclid(a::Integer, b::Integer)\n    @assert a >= b && b >= 0\n    if b == 0\n        return (1, 0, a)\n    end\n\n    (x′, y′, d) = extendedeuclid(b, mod(a, b))\n    return (y′, x′ - a ÷ b * y′, d)\nend\n\n\"\"\"\n    isprime(N)\n\nDetermine whether an integer `N` is prime using Fermat's little theorem.\n\n# Examples\n```jldoctest\njulia> primality(5)\ntrue\n```\n\"\"\"\nfunction primality(N::Integer)\n    if N < 2\n        return false\n    end\n\n    a = rand(1:(N - 1))\n    return powermod(a, N - 1, N) == 1\nend\n\n\"\"\"\n    primality2(N)\n\nDetermine whether an integer `N` is prime with low error probability.\n\"\"\"\nfunction primality2(N::Integer)\n    if N < 2\n        return false\n    end\n\n    a = rand(1:(N - 1), N - 1)\n    if all([powermod(a[i], N - 1, N) == 1 for i ∈ 1:(N - 1)])\n        return true\n    else\n        return false\n    end\nend\n\nend # module\n", "meta": {"hexsha": "be2c8db169329d474b8e45877d47ef31341a394f", "size": 3505, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter1.jl", "max_stars_repo_name": "airicbear/CIS3223", "max_stars_repo_head_hexsha": "8769e6b74021e1285114753b49bd6e8e6b822dd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/chapter1.jl", "max_issues_repo_name": "airicbear/CIS3223", "max_issues_repo_head_hexsha": "8769e6b74021e1285114753b49bd6e8e6b822dd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chapter1.jl", "max_forks_repo_name": "airicbear/CIS3223", "max_forks_repo_head_hexsha": "8769e6b74021e1285114753b49bd6e8e6b822dd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0975609756, "max_line_length": 75, "alphanum_fraction": 0.5788873039, "num_tokens": 1141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7830241898410756}}
{"text": "using Distributions, StatsBase, Random\nRandom.seed!(1)\n\ndist1 = TriangularDist(0,10,5)\ndist2 = DiscreteUniform(1,5)\ntheorMean1, theorMean2 = mean(dist1), mean(dist2)\n\nN = 10^6\ndata1 = rand(dist1,N)\ndata2 = rand(dist2,N)\nestMean1, estMean2 = mean(data1), mean(data2)\n\nprintln(\"Symmetric Triangular Distiribution on [0,10] has mean $theorMean1\n\t(estimated: $estMean1)\")\nprintln(\"Discrete Uniform Distiribution on {1,2,3,4,5} has mean $theorMean2\n\t(estimated: $estMean2)\")", "meta": {"hexsha": "3e23994787d8e1f9f3fc4d9eeed37f86b8210092", "size": 469, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/basicDistRand.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "3_chapter/basicDistRand.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "3_chapter/basicDistRand.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 29.3125, "max_line_length": 75, "alphanum_fraction": 0.7441364606, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.7830241837302897}}
{"text": "\"\"\"\n    MeanSquareError(NeuralNetwork)\n\nSum of square error loss function.\n\n    Usage:\n```julia-repl\nMeanSquareError(NeuralNetwork)\n```\nArguments:\n- `NeuralNetwork` : The NeuralNetwork structure.\n\"\"\"\nfunction MeanSquareError(NeuralNetwork)\n\tΣSE = 0.0\n\n\tfor i in 1:size(NeuralNetwork.y, 1)\n\t\tΣSE += (NeuralNetwork.y[i] - NeuralNetwork.output[i]) ^ 2.0\n    end\n\t\n    loss = 1.0 / size(NeuralNetwork.y) * ΣSE\n    return loss\nend", "meta": {"hexsha": "8203c7fbaf10a6e55520c1574784899b94eadfce", "size": 425, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LossFunctions/MeanSquareError.jl", "max_stars_repo_name": "hendersontrent/ScratchNeuralNetwork.jl", "max_stars_repo_head_hexsha": "9ab70442870ef142ba0024b8fb47e0351f1b742c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LossFunctions/MeanSquareError.jl", "max_issues_repo_name": "hendersontrent/ScratchNeuralNetwork.jl", "max_issues_repo_head_hexsha": "9ab70442870ef142ba0024b8fb47e0351f1b742c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-10-06T03:58:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-06T10:38:22.000Z", "max_forks_repo_path": "src/LossFunctions/MeanSquareError.jl", "max_forks_repo_name": "hendersontrent/ScratchNeuralNetwork.jl", "max_forks_repo_head_hexsha": "9ab70442870ef142ba0024b8fb47e0351f1b742c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3181818182, "max_line_length": 61, "alphanum_fraction": 0.6941176471, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878721, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7830241773127197}}
{"text": "# Generates an AR(p) process with coefficients `ϕ`.\n# `ϕ` should be provided as a vector and it represents the coefficients of the AR model.\n# Hence the order of the generated process is equal to the length of `ϕ`.\n# `s` indicates the total length of the series to be generated.\nfunction generate_process(ϕ::AbstractVector{Float32}, s::Int)\n    @assert s > 0 \"s must be positive\"\n    # Generate white noise\n    ϵ = randn(Float32, s)\n    # Initialize time series\n    X = zeros(Float32, s)\n    p = length(ϕ)\n    X[1] = ϵ[1]\n    # Reverse the order of the coefficients for multiplication later on\n    ϕ = reverse(ϕ) \n    # Fill first p observations\n    for t ∈ 1:p-1\n        X[t+1] = X[1:t]'ϕ[1:t] + ϵ[t+1]\n    end\n    # Compute values iteratively\n    for t ∈ p+1:s\n        X[t] = X[t-p:t-1]'ϕ + ϵ[t]\n    end\n    X\nend\n\n# Create batches of a time series `X` by splitting the series into\n# sequences of length `s`. Each new sequence is shifted by `r` steps.\n# When s == r,  the series is split into non-overlapping batches.\nfunction batch_timeseries(X, s::Int, r::Int)\n    @assert r > 0 \"r must be positive\"\n    # If X is passed in format T×1, reshape it\n    if isa(X, AbstractVector)       \n        X = permutedims(X)\n    end\n    T = size(X, 2)\n    @assert s ≤ T \"s cannot be longer than the total series\"\n    # Ensure uniform sequence lengths by dropping the first observations until\n    # the total sequence length matches a multiple of the batchsize\n    X = X[:, ((T - s) % r)+1:end]   \n    [X[:, t:r:end-s+t] for t ∈ 1:s] # Output\nend\n\n", "meta": {"hexsha": "5f512fa0aea72feb14d2967d845fda303a312797", "size": 1537, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "other/autoregressive-process/utils.jl", "max_stars_repo_name": "piotrek124-1/model-zoo", "max_stars_repo_head_hexsha": "91346f8a2fd7aed3e5bf3e1bd6ef846d55b2a4d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "other/autoregressive-process/utils.jl", "max_issues_repo_name": "piotrek124-1/model-zoo", "max_issues_repo_head_hexsha": "91346f8a2fd7aed3e5bf3e1bd6ef846d55b2a4d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "other/autoregressive-process/utils.jl", "max_forks_repo_name": "piotrek124-1/model-zoo", "max_forks_repo_head_hexsha": "91346f8a2fd7aed3e5bf3e1bd6ef846d55b2a4d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7441860465, "max_line_length": 88, "alphanum_fraction": 0.6389069616, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7830190297063296}}
{"text": "using Catlab, Catlab.Theories\nusing Catlab.CategoricalAlgebra\nusing Catlab.Graphs\nusing Catlab.Graphics\nusing Catlab.Graphics.Graphviz\n#import Catlab.Graphics.Graphviz: to_graphviz, to_graphviz_property_graph\n\nusing Colors\ndraw(g) = to_graphviz(g, node_labels=true, edge_labels=true)\n\nGraphvizGraphs.to_graphviz(f::ACSetTransformation; kw...) =\n  to_graphviz(GraphvizGraphs.to_graphviz_property_graph(f; kw...))\n\nfunction GraphvizGraphs.to_graphviz_property_graph(f::ACSetTransformation; kw...)\n  pg = GraphvizGraphs.to_graphviz_property_graph(dom(f); kw...)\n  vcolors = hex.(range(colorant\"#0021A5\", stop=colorant\"#FA4616\", length=nparts(codom(f), :V)))\n  ecolors = hex.(range(colorant\"#6C9AC3\", stop=colorant\"#E28F41\", length=nparts(codom(f), :E)))\n  hex.(colormap(\"Oranges\", nparts(codom(f), :V)))\n  for v in vertices(dom(f))\n    fv = f[:V](v)\n    set_vprops!(pg, v, Dict(:color => \"#$(vcolors[fv])\"))\n  end\n  for e in edges(dom(f))\n    fe = f[:E](e)\n    set_eprops!(pg, e, Dict(:color => \"#$(ecolors[fe])\"))\n  end\n  pg\nend\n\nto_graphviz(Catlab.Graphs.BasicGraphs.TheoryGraph)\n\n# # The Category of Graphs\n#\n# The Theory of Graphs is given by the following Schema:\n# ```julia\n# @present TheoryGraph(FreeSchema) begin\n#   V::Ob\n#   E::Ob\n#   src::Hom(E,V)\n#   tgt::Hom(E,V)\n# end\n\n# \"\"\" Abstract type for graphs, aka directed multigraphs.\n# \"\"\"\n# @abstract_acset_type AbstractGraph <: HasGraph\n\n# \"\"\" A graph, also known as a directed multigraph.\n# \"\"\"\n# @acset_type Graph(TheoryGraph, index=[:src,:tgt]) <: AbstractGraph\n# ```\n#\n# That is all we need to do to generate the functor category [TheoryGraph, FinSet].\n# Catlab knows how to take a finitely presented category and generate all the data structures\n# that you need to represent functors into FinSet and natural transformations between those functors.\n# Note: the index=[:src, :tgt] keyword argument tells Catlab that you want to have an efficient index\n# the preimages of those morphisms. in this example, we want to be able to find the incoming and \n# outgoing edges of a vertex in O(1) time.\n\n# ## Creating some Graphs\n\n# Once you have fixed the schema (aka indexing category or theory), you can make some instances.\n# Catlab has a DSL for specifying instances of any schema. It is called `@acset`.\n# In order to specify a Functor F=(F₀, F₁) into FinSet, you need to provide some data. \n#     1. For every A:Ob(C), you need F₀(A):FinSet\n#     2. For every f:A→B, you need to specify a FinFunction F₁(f):F₀(A)→F₀(B)\n# If the theory C has some equations, the data you provide would have to also satisfy those equations.\n# The theory of graphs has no equations, so there are no constraints on the data you provide, \n# except for those that come from functoriality.\n\ne = @acset Graphs.Graph begin\n    V = 2\n    E = 1\n    src = [1]\n    tgt = [2]\nend\n\ndraw(e)\n\n# a wedge is two edges that share a target\nw = @acset Graphs.Graph begin\n    V = 3\n    E = 2\n    src=[1,3]\n    tgt=[2,2]\nend\n\ndraw(w)\n\n# The CSet API generalizes the traditional Graph API\n\nparts(w, :V)  # vertex set\n\nparts(w,:E) # edge set\n\nw[:src] # source map\n\nw[:tgt] # target map\n\n\nincident(w, 1, :src) # edges out of vertex 1\n\nincident(w, 2, :tgt) # edges into vertex 2\n\nw[incident(w, 2, :tgt), :src] # vertices that are the source of edges whose target is vertex 2\n\nw[incident(w, 1, :src), :tgt] # vertices that are the target of edges whose src is vertex 1\n\n# ### Exercise:\n# 1. Use the @acset macro to make a graph with at least 5 vertices\n# 2. Draw the graph\n# 3. Compute in neighbors and out neighbors and make sure they match your expectations.\n# 4. Write a function that computes the 2-hop out-neighbors of a vertex.\n\n\n# # Graph Homomorphisms\n# We can construct some graph homomorphisms between our two graphs.\n# What data do we need to specify?\n\nϕ = ACSetTransformation(e,w,E=[1], V=[1,2])\n\nis_natural(ϕ)\n\n# The ACSetTransformation constructor does not automatically validate that the naturality squares commute!\n\nϕᵦ = ACSetTransformation(e,w,E=[1], V=[3,2])\nis_natural(ϕᵦ)\n\n# Our ϕᵦ in't natural because the edge map e₁ ↦ e₁ is not consistent with our vertex map, which sends v₁ ↦ v₃ and v₂ ↦ v₂. We can fix this by sending e₁ to e₂\n\nϕᵦ′ = ACSetTransformation(e,w,E=[2], V=[3,2])\nis_natural(ϕᵦ′)\n\n\n# So how does Catlab store the data of the natural transformation? \n# the domain\nϕ.dom\n# the codomain\nϕ.codom\n# the components\nϕ.components\n# you can see the components using standard indexing notation with the object names. Notice that while CSets are indexed by morphisms, natural transformations are indexed by objects.\nϕ[:V]\nϕ[:E]\n# We can check the  naturality squares ourselves\n# The sources are preserved: `src ⋅ ϕᵥ == ϕₑ ⋅ src`\nϕ[:V](dom(ϕ)[:,:src]) == codom(ϕ)[collect(ϕ[:E]), :src]\n# The targets are preserved: `tgt ⋅ ϕᵥ == ϕₑ ⋅ tgt`\nϕ[:V](dom(ϕ)[:,:tgt]) == codom(ϕ)[collect(ϕ[:E]), :tgt]\n\n# This approach generalizes to the following: \n#\n# ```julia\n# function is_natural(α::ACSetTransformation{S}) where {S}\n#    X, Y = dom(α), codom(α)\n#    for (f, c, d) in zip(hom(S), dom(S), codom(S))\n#      Xf, Yf, α_c, α_d = subpart(X,f), subpart(Y,f), α[c], α[d]\n#      all(Yf[α_c(i)] == α_d(Xf[i]) for i in eachindex(Xf)) || return false\n#    end\n#    return true\n# end\n# ```\n#\n# Notice how we iterate over the homs in the schema category S `(f, c, d) in zip(hom(S), dom(S), codom(S))` We get one universally quantified equation `all(Yf[α_c(i)] == α_d(Xf[i]) for i in eachindex(Xf))` for each morphism in the indexing category\n# \n# ### Exercise:\n# 1. Take your graph from the previous exercise and construct a graph homomorphism from the wedge (w) into it.\n# 2. Check that the naturality equations are satisfied.\n# 3. Explain why we don't need to specify any data for the source and target morphisms in TheoryGraph when definining a graph homomorphism\n\n# ## Finding Homomorphisms Automatically\n# As you saw in the previous exercise, constructing a natural transformation can be quite tedious. We want computers to automate tedious things for us. So we use an algorithm to enumerate all the homomorphisms between two CSets.\n\n# CSet homomorphisms f:A→B are ways of finding a part of B that is shaped like A. You can view this as pattern matching. The graph A is the pattern and the graph B is the data. A morphism f:A→B is a collection of vertices and edges in B that is shaped like A. Note that you can ask Catlab to enforce constraints on the homomorphisms it will find including computing monic (injective) morphisms by passing the keyword `monic=true`. A monic morphism into B is a subobject of B.  You can pass `iso=true` to get isomorphisms.\n\nt = @acset Graphs.Graph begin\n    V = 3\n    E = 3\n    src = [1,2,1]\n    tgt = [2,3,3]\nend\n\ndraw(t)\n\nT = @acset Graphs.Graph begin\n    V = 6\n    E = 9\n    src = [1,2,1, 3, 1,5,2,2,4]\n    tgt = [2,3,3, 4, 4,6,5,6,6]\nend\n\ndraw(T)\n\n\n# The simplest pattern in a graph is just a single edge and each homomorphism ϕ:e→G is a single edge in G. \nlength(homomorphisms(e, T, monic=true)) == nparts(T,:E) # number of edges\n\n\nlength(homomorphisms(t, T))\n\n# We can define this helper function to print out all the homomorphisms between graphs. Because all our graphs are simple, we only need to look at the vertex components.\ngraphhoms(g,h) = begin\n    map(homomorphisms(g,h)) do ϕ\n        collect(ϕ[:V])\n    end\nend\n\ngraphhoms(t, T)\n\n# Homs ϕ:t→T are little triangles in T, but homs ϕ:T→t are colorings of T with 3 colors. The fact that there are edges in t that are missing, means that it provides constraints on what graphs have morphisms into it. For example, there are no morphisms T→t.\n\ngraphhoms(T, t)\n\n# The reason we don't have a morphism into t is vertices 2,3,4,5 aren't arranged into a triangle. We can relax those constraints by adding loops to the codomain. Loops in the codomain allow you to merge adjacent vertices when you construct the homomorphism. \n\nadd_loops!(g) = add_parts!(g, :E, nparts(g,:V), src=parts(g,:V), tgt=parts(g,:V))\nadd_loops(g) = begin\n    h = copy(g)\n    add_loops!(h)\n    return h\nend\n\ndraw(add_loops(t))\n\n# Once we add loops, then we have morphisms.\n \nlength(homomorphisms(T,add_loops(t)))\n\n\n# ## Bipartite Graphs\n# Many computer science problems involve graphs that have two types of vertices. For example, when matching students to classes, you might represent the students as one type of vertex and the classes as another type of vertex. Then the edges (s,c) represent \"student s is enrolled in class c\". In this scenario there can be no edges from a class vertex to another class vertex, or from a student vertex to a student vertex. Graphs for which there exists such a classification are called bipartite graphs. In Category Theory, we shift from thinking about graphs with properties to graph homomorphisms that witness that property and think of bipartitioned graphs.\n\n# First we construct a bipartite graph:\nsq = apex(product(add_loops(e), add_loops(e)))\nrem_parts!(sq, :E, [1,5,6,8,9])\ndraw(sq)\n\n# We will use the symmetric edge graph to identify the bipartitions of this graph. \nesym = @acset Graphs.Graph begin\n    V = 2\n    E = 2\n    src = [1,2]\n    tgt = [2,1]\nend\n\ndraw(id(esym))\n# There are two ways to bipartition sq.\ngraphhoms(sq, esym)\n\n# This comes from the fact that esym has 2 automorphisms!\ngraphhoms(esym, esym)\n\n# the first coloring\ndraw(homomorphisms(sq, esym)[1])\n\n# but we can also swap the roles of the colors\ndraw(homomorphisms(sq, esym)[2])\n\n# ### Exercise:\n# 1. Construct a graph representation of a checkerboard\n# 2. Draw the two bipartitions of the checkerboard\n\n# We can generalize the notion of Bipartite graph to any number of parts. I like to call Kₖ the k-coloring classifier because homomorphims into α:G → Kₖ are k-colorings of G.\n\nclique(k::Int) = begin\n    Kₖ = Graphs.Graph(k)\n    for i in 1:k\n        for j in 1:k\n            if j ≠ i\n                add_parts!(Kₖ, :E, 1, src=i, tgt=j)\n            end\n        end\n    end\n    return Kₖ\nend\n\nK₃ = clique(3)\ndraw(id(K₃))\n\n# Our graph T is not 2-colorable,\nlength(homomorphisms(T, esym))\n\n# but we can use 3 colors to color T.\ndraw(homomorphism(T, K₃))\n\n# ### Exercise:\n# 1. Find a graph that is not 3-colorable\n# 2. Find a graph that is not 4-colorable\n\n\n# ## Homomorphisms in [C, Set] are like Types\n# Any graph can play the role of the codomain. If you pick a graph that is incomplete, you get a more constrained notion of coloring where there are color combinations that are forbidden.\ntriloop = @acset Graphs.Graph begin\n    V = 3\n    E = 3\n    src = [1,2,3]\n    tgt = [2,3,1]\nend\n\ndraw(id(triloop))\n\n# With this graph, we can pick out directed 3-cycles in a graph like T2,\nT2 = @acset Graphs.Graph begin\n    V = 6\n    E = 6\n    src = [1,2,3,4,5,6]\n    tgt = [2,3,1,5,6,4]\nend\ngraphhoms(T2, triloop)\n\n# and we can draw those cyclic roles with colors\ndraw(homomorphisms(T2, triloop)[1])\n\nT3 = @acset Graphs.Graph begin\n    V = 6\n    E = 7\n    src = [1,2,3,4,5,6, 2]\n    tgt = [2,3,1,5,6,4, 4]\nend\ngraphhoms(T3, triloop)\n\n# Using the colors as shown:\ndraw(id(triloop))\n\n# We can see our coloring of T3:\ndraw(homomorphisms(T3, triloop)[1])\n", "meta": {"hexsha": "e7e4ec40b44be611a24c493db18a3879ee18b435", "size": 11040, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/literate/graphs/graphs.jl", "max_stars_repo_name": "Xiaoyan-Li/Catlab.jl", "max_stars_repo_head_hexsha": "e4b1b5fed310d473ad94978a9a2930e1abdfa181", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 167, "max_stars_repo_stars_event_min_datetime": "2019-02-15T22:53:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T12:46:02.000Z", "max_issues_repo_path": "docs/literate/graphs/graphs.jl", "max_issues_repo_name": "Xiaoyan-Li/Catlab.jl", "max_issues_repo_head_hexsha": "e4b1b5fed310d473ad94978a9a2930e1abdfa181", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 118, "max_issues_repo_issues_event_min_datetime": "2019-03-03T23:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-17T04:33:49.000Z", "max_forks_repo_path": "docs/literate/graphs/graphs.jl", "max_forks_repo_name": "Xiaoyan-Li/Catlab.jl", "max_forks_repo_head_hexsha": "e4b1b5fed310d473ad94978a9a2930e1abdfa181", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2019-07-06T10:44:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-17T13:26:44.000Z", "avg_line_length": 33.8650306748, "max_line_length": 661, "alphanum_fraction": 0.7027173913, "num_tokens": 3385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7830190277204764}}
{"text": "\"\"\"Calculte the Continuous Ranked Probability Score (CRPS) of an ensemble array wrt\na true observation o. In-place version that will sort the array.\"\"\"\nfunction CRPS!(x::Array{T,1},o::T) where T\n    sort!(x)\n    n = length(x)\n    dp = 1/n                                # probability increment per xi in x\n\n    # find index m to split integration over x into heaviside=0 or 1\n    m = findfirst(xi -> xi >= o,x)   \n    \n    # integration from o to x if o is outside of the range of x\n    s = m==1 ? x[1]-o : 0.0                 \n\n    # integrate over the heaviside=0 part\n    for i in 1:(m == nothing ? n-1 : m-1)\n        s += (i*dp)^2*(x[i+1]-x[i])\n    end\n\n    # integrate over the heaviside=1 part\n    for i in (m == nothing ? n : m):n-1\n        s += (i*dp-1)^2*(x[i+1]-x[i])\n    end\n\n    # integration from x to o if o is outside of the range of x\n    s += (m == nothing) ? o-x[end] : 0.0\n\n    return s\nend\n\n\"\"\"Calculte the Continuous Ranked Probability Score (CRPS) of an ensemble array wrt\na true observation o.\"\"\"\nCRPS(x::Array{T,1},o::T) where T = CRPS!(copy(x),o)\nCRPS(x::Array{T,1},o::Real) where T = CRPS!(copy(x),T(o))\n\n", "meta": {"hexsha": "564e95777069fb2b75604455bfbb80f309765ade", "size": 1131, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/crps.jl", "max_stars_repo_name": "esowc/Elefridge.jl", "max_stars_repo_head_hexsha": "90461a7e0c6b213c4df7d351a36c5665e942e56c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2020-05-11T14:53:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T04:23:46.000Z", "max_issues_repo_path": "src/crps.jl", "max_issues_repo_name": "esowc/Elefridge.jl", "max_issues_repo_head_hexsha": "90461a7e0c6b213c4df7d351a36c5665e942e56c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/crps.jl", "max_forks_repo_name": "esowc/Elefridge.jl", "max_forks_repo_head_hexsha": "90461a7e0c6b213c4df7d351a36c5665e942e56c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-28T19:46:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-28T19:46:22.000Z", "avg_line_length": 32.3142857143, "max_line_length": 83, "alphanum_fraction": 0.575596817, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915912, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7830127233171061}}
{"text": "using Memoize, IterTools, LinearAlgebra\n\n@memoize function mem_det(A::Array{Int,2})\n    return round(Int, det(A))\nend\n\n\"\"\"\n`istum(A)` determines if the integer matrix `A`\nis totally unimodular. This may be called with an\noptional second argument `istum(A,true)` that,\nin case the matrix is not totally unimodular, will\nreport the first submatrix found whose determinant\nis not in `{-1,0,1}`.\n\n**Warning**: This is not an efficient function.\n\"\"\"\nfunction istum(A::Array{Int,2}, verbose::Bool = false)\n    r, c = size(A)\n    n = min(r, c)\n\n    for k = 1:n\n        rows = subsets(collect(1:r), k)\n        cols = subsets(collect(1:c), k)\n        for x in rows\n            for y in cols\n                B = A[x, y]\n                d = mem_det(B)\n                if abs(d) > 1\n                    if verbose\n                        println(\"Rows: \", x)\n                        println(\"Cols: \", y)\n                        println(\"$B has determinant $d\")\n                    end\n                    return false\n                end\n            end\n        end\n    end\n    return true\nend\n", "meta": {"hexsha": "52a8fa8828b0e28e54cf95cd519df57b2ef49c34", "size": 1082, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tum.jl", "max_stars_repo_name": "scheinerman/Misc.jl", "max_stars_repo_head_hexsha": "2cccc9bf616188c2b1258bdae71123a0d1b37418", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-12T17:02:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T12:31:19.000Z", "max_issues_repo_path": "src/tum.jl", "max_issues_repo_name": "scheinerman/Misc.jl", "max_issues_repo_head_hexsha": "2cccc9bf616188c2b1258bdae71123a0d1b37418", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tum.jl", "max_forks_repo_name": "scheinerman/Misc.jl", "max_forks_repo_head_hexsha": "2cccc9bf616188c2b1258bdae71123a0d1b37418", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3902439024, "max_line_length": 56, "alphanum_fraction": 0.5203327172, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.8397339636614178, "lm_q1q2_score": 0.7830127161310083}}
{"text": "#SIR-X Model\n\n\nusing DifferentialEquations\n\n\nbeta = 0.215; gamma = 0.07; N = 7000;\neta0 = 0.003; eta = 0.003\n\n\"\"\"SIR-X Model\nExtension of the basic SIR model\n\n\"\"\"\nfunction SIR_X!(du,u,p,t)\n    du[1] = -beta* u[1]/N*u[2] - eta0*u[1]                          #S\n    du[2] = beta*u[1]/N*u[2] - gamma*u[2] - eta0*u[2] - eta*u[2]    #I\n    du[3] = gamma*u[2] + eta0*u[1]                                  #R\n    du[4] = (eta0 + eta)*u[2]                                       #X\nend\n   \n   \n   u0 = [N-15.0;15.0;0.0;0.0]\n   tspan = (0.0,100.0)\n   prob = ODEProblem(SIR_X!,u0,tspan)\n   sol = solve(prob)\n   \n   plot(sol)\n   ", "meta": {"hexsha": "7ca1e6dc0229acf54f745321e2cd5d8502fc3bbf", "size": 617, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SIR-X-Model.jl", "max_stars_repo_name": "rubsc/COVID01.jl", "max_stars_repo_head_hexsha": "bd2f96439c8397b60598a259c9f397abab4c6793", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SIR-X-Model.jl", "max_issues_repo_name": "rubsc/COVID01.jl", "max_issues_repo_head_hexsha": "bd2f96439c8397b60598a259c9f397abab4c6793", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SIR-X-Model.jl", "max_forks_repo_name": "rubsc/COVID01.jl", "max_forks_repo_head_hexsha": "bd2f96439c8397b60598a259c9f397abab4c6793", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0357142857, "max_line_length": 70, "alphanum_fraction": 0.4489465154, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305370909698, "lm_q2_score": 0.8128673223709252, "lm_q1q2_score": 0.7829786275110447}}
{"text": "# Functions related to the counting bound.\n\nmodule CountingBound\n\nexport countingBound, approxNumMaximalCliques1\n\n\"\"\"\nCounting bound, based on Shannon's argument.\n  m: number of edges\n  w: number of 'wires' -- that is, log2(number of functions),\n    which is the number of bits needed to specify a function\n  Returns: average number of NAND gates (with unbounded fan-in)\n    required to compute any of those functions.\n    (This may not be an integer).\n\"\"\"\nfunction countingBound(m, w)\n  m = BigFloat(m)\n  w = BigFloat(w)\n  b = m - 0.5\n  # the \"-1\" here is because this is the average, not the max.\n  sqrt(2*w + b*b) - b - 1\nend\n\n\"\"\"\n  Approximate number of maximal hypercliques of some size.\n  Note that k < r < n .\n  Also, the precision of what's returned can be set by setprecision().\n  k: number of vertices per hyperedge\n  r: number of vertices in the clique\n  n: vertices in the larger graph\n  Returns: expected number of maximal hypercliques. (This is\n\t\tapproximate, but presumably it's more accurate for larger\n    numbers).\n\"\"\"\nfunction approxNumMaximalCliques1(k, r, n)\n  k = BigInt(k)\n  r = BigInt(r)\n  n = BigInt(n)\n  one = BigInt(1)\n  two = BigInt(2)\n\n  # probability that one of those is not covered by a larger clique\n  a = one << binomial(r, k-one)\n  # print(\"computed a\\n\")\n  pNumerator = (a-one) ^ (n-r)\n  # print(\"computed numerator\\n\")\n  pDenominator = a ^ (n-r)\n  # print(\"computed denominator\\n\")\n\n  # expected number of r-cliques should be equivalent to:\n  # numRCliques = Rational(binomial(n, r), two ^ binomial(r, k))\n  # # result is number of cliques, * prob. they're maximal\n  # numRCliques * (pNumerator / pDenominator)\n  r = (pNumerator * binomial(n, r)) /\n    (pDenominator * (one << binomial(r, k)))\n  # ??? is this off by two? I don't think so.\n  r\nend\n\n\"\"\"\n  Approximate number of maximal hypercliques of some size\n(alternate take).\n  Note that k < r < n .\n  Also, the precision of what's returned can be set by setprecision().\n  k: number of vertices per hyperedge\n  r: number of vertices in the clique\n  n: vertices in the larger graph\n  Returns: number of maximal hypercliques. This is approximate, because\n    it's the expected number. (Presumably it's more accurate for larger\n    numbers).\n\"\"\"\nfunction approxNumMaximalCliques2(k, r, n)\n  k = BigInt(k)\n  r = BigInt(r)\n  n = BigInt(n)\n  one = BigInt(1)\n  two = BigInt(2)\n\n  # probability that one of those is not covered by a larger clique\n  a = one << binomial(r, k-one)\n  print(\"computed a\\n\")\n  pNumerator = (a-one) ^ (n-r)\n\t# ??? how is this implemented for BigInts?\n\t# also, if a = 1111111... in binary, is there a cheaper way to\n\t# compute this?\n  print(\"computed numerator\\n\")\n  pDenominator = a ^ (n-r)\n\t# FIXME is denominator all powers of two? If so, presumably could\n\t# replace the division with a bit shift\n  print(\"computed denominator\\n\")\n\n  # expected number of r-cliques should be equivalent to:\n  # numRCliques = Rational(binomial(n, r), two ^ binomial(r, k))\n  # # result is number of cliques, * prob. they're maximal\n  # numRCliques * (pNumerator / pDenominator)\n  r = (pNumerator * binomial(n, r)) /\n    (pDenominator * (one << binomial(r, k)))\n\n  # ??? is this off by two? (doesn't seem to be, for small k, r, n)\n  r\nend\n\nend\n\n", "meta": {"hexsha": "9fd463dd534844b94af84b2ecd0983e283da9eb5", "size": 3237, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "countingBound/julia/CountingBound.jl", "max_stars_repo_name": "joshtburdick/misc", "max_stars_repo_head_hexsha": "7bb103b4f9d850e3279eb675c6df420aa7b8da22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "countingBound/julia/CountingBound.jl", "max_issues_repo_name": "joshtburdick/misc", "max_issues_repo_head_hexsha": "7bb103b4f9d850e3279eb675c6df420aa7b8da22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "countingBound/julia/CountingBound.jl", "max_forks_repo_name": "joshtburdick/misc", "max_forks_repo_head_hexsha": "7bb103b4f9d850e3279eb675c6df420aa7b8da22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8285714286, "max_line_length": 71, "alphanum_fraction": 0.6793327155, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693688269985, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7829662372439292}}
{"text": "### Edge and Gradient Related Image Operations ###\n\n# Phase (angle of steepest gradient ascent), calculated from X and Y gradient images\n\"\"\"\n    phase(grad_x, grad_y) -> p\n\nCalculate the rotation angle of the gradient given by `grad_x` and\n`grad_y`. Equivalent to `atan(-grad_y, grad_x)`, except that when both `grad_x` and\n`grad_y` are effectively zero, the corresponding angle is set to zero.\n\"\"\"\nfunction phase(grad_x::T, grad_y::T, tol=sqrt(eps(T))) where T<:Number\n    atan(-grad_y, grad_x) * ((abs(grad_x) > tol) | (abs(grad_y) > tol))\nend\nphase(grad_x::Number,   grad_y::Number)   = phase(promote(grad_x, grad_y)...)\nphase(grad_x::NumberLike, grad_y::NumberLike) = phase(gray(grad_x), gray(grad_y))\n\nphase(grad_x::AbstractRGB, grad_y::AbstractRGB) = phase(vecsum(grad_x), vecsum(grad_y))\n\nmagnitude_phase(grad_x::NumberLike, grad_y::NumberLike) =\n    hypot(grad_x, grad_y), phase(grad_x, grad_y)\n\nfunction magnitude_phase(grad_x::AbstractRGB, grad_y::AbstractRGB)\n    gx, gy = vecsum(grad_x), vecsum(grad_y)\n    magnitude_phase(gx, gy)\nend\n\nvecsum(c::AbstractRGB) = float(red(c)) + float(green(c)) + float(blue(c))\n\n## TODO? orientation seems nearly redundant with phase, deprecate?\n\n\"\"\"\n    orientation(grad_x, grad_y) -> orient\n\nCalculate the orientation angle of the strongest edge from gradient images\ngiven by `grad_x` and `grad_y`.  Equivalent to `atan(grad_x, grad_y)`.  When\nboth `grad_x` and `grad_y` are effectively zero, the corresponding angle is set to\nzero.\n\"\"\"\nfunction orientation(grad_x::T, grad_y::T, tol=sqrt(eps(T))) where T<:Number\n    atan(grad_x, grad_y) * ((abs(grad_x) > tol) | (abs(grad_y) > tol))\nend\norientation(grad_x::Number,   grad_y::Number)   = orientation(promote(grad_x, grad_y)...)\norientation(grad_x::NumberLike, grad_y::NumberLike) = orientation(gray(grad_x), gray(grad_y))\n\norientation(grad_x::AbstractRGB, grad_y::AbstractRGB) = orientation(vecsum(grad_x), vecsum(grad_y))\n\n# Magnitude of gradient, calculated from X and Y image gradients\n\"\"\"\n```\nm = magnitude(grad_x, grad_y)\n```\n\nCalculates the magnitude of the gradient images given by `grad_x` and `grad_y`.\nEquivalent to `sqrt(grad_x.^2 + grad_y.^2)`.\n\nReturns a magnitude image the same size as `grad_x` and `grad_y`.\n\"\"\"\nmagnitude(grad_x::AbstractArray, grad_y::AbstractArray) = hypot.(grad_x, grad_y)\n\nBase.hypot(x::AbstractRGB, y::AbstractRGB) = hypot(vecsum(x), vecsum(y))\n\nphase(grad_x::AbstractArray, grad_y::AbstractArray) = phase.(grad_x, grad_y)\n\n# Orientation of the strongest edge at a point, calculated from X and Y gradient images\n# Note that this is perpendicular to the phase at that point, except where\n# both gradients are close to zero.\n\norientation(grad_x::AbstractArray{T}, grad_y::AbstractArray{T}) where {T} = orientation.(grad_x, grad_y)\n\n# Return both the magnitude and phase in one call\n\"\"\"\n    magnitude_phase(grad_x, grad_y) -> m, p\n\nConvenience function for calculating the magnitude and phase of the gradient\nimages given in `grad_x` and `grad_y`.  Returns a tuple containing the magnitude\nand phase images.  See `magnitude` and `phase` for details.\n\"\"\"\nfunction magnitude_phase(grad_x::AbstractArray{T}, grad_y::AbstractArray{T}) where T\n    m = similar(grad_x, eltype(T))\n    p = similar(m)\n    for I in eachindex(grad_x, grad_y)\n        m[I], p[I] = magnitude_phase(grad_x[I], grad_y[I])\n    end\n    m, p\nend\n\n# Return the magnitude and phase of the gradients in an image\nfunction magnitude_phase(img::AbstractArray, method::Function=KernelFactors.ando3, border::AbstractString=\"replicate\")\n    grad_x, grad_y = imgradients(img, method, border)\n    return magnitude_phase(grad_x, grad_y)\nend\n\n# Return the x-y gradients and magnitude and phase of gradients in an image\n\"\"\"\n```\ngrad_y, grad_x, mag, orient = imedge(img, kernelfun=KernelFactors.ando3, border=\"replicate\")\n```\n\nEdge-detection filtering. `kernelfun` is a valid kernel function for\n[`imgradients`](@ref), defaulting to [`KernelFactors.ando3`](@ref).\n`border` is any of the boundary conditions specified in `padarray`.\n\nReturns a tuple `(grad_y, grad_x, mag, orient)`, which are the horizontal\ngradient, vertical gradient, and the magnitude and orientation of the strongest\nedge, respectively.\n\"\"\"\nfunction imedge(img::AbstractArray, kernelfun=KernelFactors.ando3, border::AbstractString=\"replicate\")\n    grad_y, grad_x = imgradients(img, kernelfun, border)\n    mag = magnitude(grad_y, grad_x)\n    orient = orientation(grad_y, grad_x)\n    return (grad_y, grad_x, mag, orient)\nend\n\n# Thin edges\n\"\"\"\n```\nthinned = thin_edges(img, gradientangle, [border])\nthinned, subpix = thin_edges_subpix(img, gradientangle, [border])\nthinned, subpix = thin_edges_nonmaxsup(img, gradientangle, [border]; [radius::Float64=1.35], [theta=pi/180])\nthinned, subpix = thin_edges_nonmaxsup_subpix(img, gradientangle, [border]; [radius::Float64=1.35], [theta=pi/180])\n```\n\nEdge thinning for 2D edge images.  Currently the only algorithm available is\nnon-maximal suppression, which takes an edge image and its gradient angle, and\nchecks each edge point for local maximality in the direction of the gradient.\nThe returned image is non-zero only at maximal edge locations.\n\n`border` is any of the boundary conditions specified in `padarray`.\n\nIn addition to the maximal edge image, the `_subpix` versions of these functions\nalso return an estimate of the subpixel location of each local maxima, as a 2D\narray or image of `Graphics.Point` objects.  Additionally, each local maxima is\nadjusted to the estimated value at the subpixel location.\n\nCurrently, the `_nonmaxsup` functions are identical to the first two function\ncalls, except that they also accept additional keyword arguments.  `radius`\nindicates the step size to use when searching in the direction of the gradient;\nvalues between 1.2 and 1.5 are suggested (default 1.35).  `theta` indicates the\nstep size to use when discretizing angles in the `gradientangle` image, in\nradians (default: 1 degree in radians = pi/180).\n\nExample:\n\n```\ng = rgb2gray(rgb_image)\ngx, gy = imgradients(g)\nmag, grad_angle = magnitude_phase(gx,gy)\nmag[mag .< 0.5] = 0.0  # Threshold magnitude image\nthinned, subpix =  thin_edges_subpix(mag, grad_angle)\n```\n\"\"\"\nthin_edges(img::AbstractArray{T,2}, gradientangles::AbstractArray, border::AbstractString=\"replicate\") where {T} =\n    thin_edges_nonmaxsup(img, gradientangles, border)\nthin_edges_subpix(img::AbstractArray{T,2}, gradientangles::AbstractArray, border::AbstractString=\"replicate\") where {T} =\n    thin_edges_nonmaxsup_subpix(img, gradientangles, border)\n\n# Code below is related to non-maximal suppression, and was ported to Julia from\n# http://www.csse.uwa.edu.au/~pk/research/matlabfns/Spatial/nonmaxsup.m\n# (Please conserve the original copyright below.)\n\n# NONMAXSUP - Non-maxima suppression\n#\n# Usage:\n#          (im,location) = nonmaxsup(img, gradientangles, radius);\n#\n# Function for performing non-maxima suppression on an image using\n# gradient angles.  Gradient angles are assumed to be in radians.\n#\n# Input:\n#   img - image to be non-maxima suppressed.\n#\n#   gradientangles - image containing gradient angles around each pixel in radians\n#                    (-pi,pi)\n#\n#   radius  - Distance in pixel units to be looked at on each side of each\n#             pixel when determining whether it is a local maxima or not.\n#             This value cannot be less than 1.\n#             (Suggested value about 1.2 - 1.5)\n#\n# Returns:\n#   im        - Non maximally suppressed image.\n#   location  - `Graphics.Point` image holding subpixel locations of edge\n#               points.\n#\n# Notes:\n#\n# This function uses bilinear interpolation to estimate\n# intensity values at ideal, real-valued pixel locations on each side of\n# pixels to determine if they are local maxima.\n\n# Copyright (c) 1996-2013 Peter Kovesi\n# Centre for Exploration Targeting\n# The University of Western Australia\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# The Software is provided \"as is\", without warranty of any kind.\n\n# December  1996 - Original version\n# September 2004 - Subpixel localization added\n# August    2005 - Made Octave compatible\n# October   2013 - Final thinning applied to binary image for Octave\n#                  compatbility (Thanks to Chris Pudney)\n# June      2014 - Ported (and modified significantly) to Julia (Kevin Squire)\n\nimport .Point\n\nif !applicable(zero, Point)\n    import Base.zero\n    zero(::Type{Point}) = Point(0.0,0.0)\nend\n\n# Used to encode the sign, integral, and fractional components of\n# an offset from a coordinate\nstruct CoordOffset\n    s::Int      # sign\n    i::Int      # integer part\n    f::Float64  # fractional part\nend\n\nCoordOffset(x::Float64) = ((frac,i) = modf(x); CoordOffset(sign(frac), round(Int, i), abs(frac)))\n(-)(off::CoordOffset) = CoordOffset(-off.s,-off.i, off.f)\n(*)(x::Number, off::CoordOffset) = x*(off.i + off.s*off.f)\n(*)(off::CoordOffset, x::Number) = x*(off.i + off.s*off.f)\n(+)(x::Number, off::CoordOffset) = x + off.i + off.s*off.f\n(+)(off::CoordOffset, x::Number) = x + off.i + off.s*off.f\n\n# Precalculate x and y offsets relative to centre pixel for each orientation angle\nfunction _calc_discrete_offsets(θ, radius)\n\n    θ_count = round(Int, 2π/θ)\n    θ = 2π/θ_count\n    angles = (0:θ_count)*θ\n\n    # x and y offset of points at specified radius and angles\n    # from each reference position.\n\n    xoffs = [CoordOffset( x) for x in  radius * cos.(angles)]\n    yoffs = [CoordOffset(-y) for y in  radius * sin.(angles)]\n\n    return θ, xoffs, yoffs\nend\n\n_discretize_angle(angle::AbstractFloat, invθ) =\n    angle < 0 ? round(Int, (angle + 2π)*invθ)+1 : round(Int, angle*invθ)+1\n\n# Interpolate the value of an offset from a particular pixel\n#\n# Returns (interpolated value, min_value of adjacent pixels in direction of offset)\n#\n# The second value is made available to eliminate double edges; if the value at\n# (x,y) is less than the value or values adjacent to it in the direction of the\n# gradient (xoff,yoff), then it is not a local maximum\n\nfunction _interp_offset(img::AbstractArray, x::Integer, y::Integer, xoff::CoordOffset, yoff::CoordOffset, Ix, Iy, pad)\n    fx = Ix[x + xoff.i + pad]\n    fy = Iy[y + yoff.i + pad]\n    cx = Ix[x + xoff.i + xoff.s + pad]\n    cy = Iy[y + yoff.i + yoff.s + pad]\n\n    tl = img[fy,fx]    # Value at bottom left integer pixel location.\n    tr = img[fy,cx]    # bottom right\n    bl = img[cy,fx]    # top left\n    br = img[cy,cx]    # top right\n\n    upperavg = tl + xoff.f * (tr - tl)  # Now use bilinear interpolation to\n    loweravg = bl + xoff.f * (br - bl)  # estimate value at x,y\n\n    min_adjacent = (fx == x) & (fy == y) ? min(tr,bl) : tl\n\n    return (upperavg + yoff.f * (loweravg - upperavg), min_adjacent)\nend\n\n# Core edge thinning algorithm using nonmaximal suppression\nfunction thin_edges_nonmaxsup_core!(out::AbstractArray{T,2}, location::AbstractArray{Point,2},\n                                    img::AbstractArray{T,2}, gradientangles::AbstractMatrix, radius, border, theta) where T\n    calc_subpixel = !isempty(location)\n\n    # Error checking\n    size(img) == size(gradientangles) == size(out) || error(\"image, gradient angle, and output image must all be the same size\")\n    calc_subpixel && size(location) != size(img) && error(\"subpixel location has a different size than the input image\")\n    radius < 1.0 && error(\"radius must be >= 1\")\n\n    # Precalculate x and y offsets relative to centre pixel for each orientation angle\n    θ, xoffs, yoffs = _calc_discrete_offsets(theta, radius)\n    iθ = 1/θ\n\n    # Indexes to use for border handling\n    pad = ceil(Int, radius)\n    Ix = Images.padindexes(img, 2, pad, pad, border)\n    Iy = Images.padindexes(img, 1, pad, pad, border)\n\n    # Now run through the image interpolating grey values on each side\n    # of the centre pixel to be used for the non-maximal suppression.\n\n    (height,width) = size(img)\n\n    for x = 1:width, y = 1:height\n        (c = img[y,x]) == 0 && continue  # For thresholded images\n\n        or = _discretize_angle(gradientangles[y,x],iθ)   # Disretized orientation\n        v1, n1 = _interp_offset(img, x, y, xoffs[or], yoffs[or], Ix, Iy, pad)\n\n        if (c > v1) & (c >= n1) # We need to check the value on the other side...\n            v2, n2 = _interp_offset(img, x, y, -xoffs[or], -yoffs[or], Ix, Iy, pad)\n\n            if (c > v2) & (c >= n2)  # This is a local maximum.\n                                     # Record value in the output image.\n                if calc_subpixel\n                    # Solve for coefficients of parabola that passes through\n                    # [-1, v2]  [0, img] and [1, v1].\n                    # v = a*r^2 + b*r + c\n\n                    # c = img[y,x]\n                    a = (v1 + v2)/2 - c\n                    b = a + c - v2\n\n                    # location where maxima of fitted parabola occurs\n                    r = -b/2a\n                    location[y,x] = Point(x + r*xoffs[or], y + r*yoffs[or])\n\n                    if T<:AbstractFloat\n                        # Store the interpolated value\n                        out[y,x] = a*r^2 + b*r + c\n                    else\n                        out[y,x] = c\n                    end\n                else\n                    out[y,x] = c\n                end\n            end\n        end\n    end\n\n    out\nend\n\n\n# Main function call when subpixel location of edges is not needed\nfunction thin_edges_nonmaxsup!(out, img, gradientangles, border::AbstractString=\"replicate\";\n                               radius::Float64=1.35, theta=pi/180)\n    thin_edges_nonmaxsup_core!(out, Matrix{Point}(0,0), img, gradientangles, radius, border, theta)\nend\n\nfunction thin_edges_nonmaxsup(img, gradientangles, border::AbstractString=\"replicate\";\n                                 radius::Float64=1.35, theta=pi/180)\n    (height,width) = size(img)\n    out = zeros(eltype(img), height, width)\n    thin_edges_nonmaxsup_core!(out, Matrix{Point}(undef,0,0), img, gradientangles, radius, border, theta)\nend\n\n# Main function call when subpixel location of edges is desired\nfunction thin_edges_nonmaxsup_subpix!(out, location, img, gradientangles,\n                                      border::AbstractString=\"replicate\";\n                                      radius::Float64=1.35, theta=pi/180)\n    eltype(location) != Point && error(\"Preallocated subpixel location array/image must have element type Graphics.Point\")\n\n    thin_edges_nonmaxsup_core!(out, location, img, gradientangles, radius, border, theta)\n    img, location\nend\n\nfunction thin_edges_nonmaxsup_subpix(img, gradientangles,\n                                     border::AbstractString=\"replicate\";\n                                     radius::Float64=1.35, theta=pi/180)\n    (height,width) = size(img)\n    out = zeros(eltype(img), height, width)\n    location = zeros(Point, height, width)\n    thin_edges_nonmaxsup_core!(out, location, img, gradientangles, radius, border, theta)\n    out, location\nend\n\n\"\"\"\n```\ncanny_edges = canny(img, (upper, lower), sigma=1.4)\n```\n\nPerforms Canny Edge Detection on the input image.\n\nParameters :\n\n  (upper, lower) :  Bounds for hysteresis thresholding\n  sigma :           Specifies the standard deviation of the gaussian filter\n\n# Example\n\n```julia\nimgedg = canny(img, (Percentile(80), Percentile(20)))\n```\n\"\"\"\nfunction canny(img_gray::AbstractMatrix{T}, threshold::Tuple{N,N}, sigma::Number = 1.4) where {T<:NumberLike, N<:Union{NumberLike,Percentile{NumberLike}}}\n    img_grayf = imfilter(img_gray, KernelFactors.IIRGaussian((sigma,sigma)), NA())\n    img_grad_y, img_grad_x = imgradients(img_grayf, KernelFactors.sobel)\n    img_mag, img_phase = magnitude_phase(img_grad_x, img_grad_y)\n    img_nonMaxSup = thin_edges_nonmaxsup(img_mag, img_phase)\n    if N<:Percentile{}\n        upperThreshold ,lowerThreshold = StatsBase.percentile(img_nonMaxSup[:], [threshold[i].p for i=1:2])\n    else\n        upperThreshold, lowerThreshold = threshold\n    end\n    img_thresholded = hysteresis_thresholding(img_nonMaxSup, upperThreshold, lowerThreshold)\n    edges = map(i -> i >= 0.9, img_thresholded)\n    edges\nend\n\ncanny(img::AbstractMatrix, threshold::Tuple{N,N}, args...) where {N<:Union{NumberLike,Percentile{NumberLike}}} =\n    canny(convert(Array{Gray}, img), args...)\n\nfunction hysteresis_thresholding(img_nonMaxSup::AbstractArray{T, 2}, upperThreshold::Number, lowerThreshold::Number) where T\n    img_thresholded = map(i -> i > lowerThreshold ? i > upperThreshold ? 1.0 : 0.5 : 0.0, img_nonMaxSup)\n    queue = CartesianIndex{2}[]\n    R = CartesianIndices(size(img_thresholded))\n\n    I1, Iend = first(R), last(R)\n    for I in R\n      if img_thresholded[I] == 1.0\n        img_thresholded[I] = 0.9\n        push!(queue, I)\n        while !isempty(queue)\n          q_top = popfirst!(queue)\n          for J in CartesianIndices(map((f,l)->f:l,(max(I1, q_top - I1)).I, (min(Iend, q_top + I1)).I))\n            if img_thresholded[J] == 1.0 || img_thresholded[J] == 0.5\n              img_thresholded[J] = 0.9\n              push!(queue, J)\n            end\n          end\n        end\n      end\n    end\n    img_thresholded\nend\n\nfunction padindexes(img::AbstractArray{T,n}, dim, prepad, postpad, border::AbstractString) where {T,n}\n    M = size(img, dim)\n    I = Vector{Int}(undef, M + prepad + postpad)\n    I = [(1 - prepad):(M + postpad);]\n    if border == \"replicate\"\n        I = min.(max.(I, 1), M)\n    elseif border == \"circular\"\n        I = 1 .+ mod.(I .- 1, M)\n    elseif border == \"symmetric\"\n        I = [1:M; M:-1:1][1 .+ mod.(I .- 1, 2 * M)]\n    elseif border == \"reflect\"\n        I = [1:M; M-1:-1:2][1 .+ mod.(I .- 1, 2 * M - 2)]\n    else\n        error(\"unknown border condition\")\n    end\n    I\nend\n", "meta": {"hexsha": "f9a7af6d08cf075f613f3ad68d1b5ea1f615f3c5", "size": 17918, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/edge.jl", "max_stars_repo_name": "logankilpatrick/Images.jl", "max_stars_repo_head_hexsha": "23831ec6a1a543a0d71f4ebee7695cea74767705", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 376, "max_stars_repo_stars_event_min_datetime": "2017-01-31T19:49:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T09:41:18.000Z", "max_issues_repo_path": "src/edge.jl", "max_issues_repo_name": "logankilpatrick/Images.jl", "max_issues_repo_head_hexsha": "23831ec6a1a543a0d71f4ebee7695cea74767705", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 431, "max_issues_repo_issues_event_min_datetime": "2015-08-19T10:10:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T07:24:51.000Z", "max_forks_repo_path": "src/edge.jl", "max_forks_repo_name": "logankilpatrick/Images.jl", "max_forks_repo_head_hexsha": "23831ec6a1a543a0d71f4ebee7695cea74767705", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 88, "max_forks_repo_forks_event_min_datetime": "2017-02-03T16:51:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T12:09:44.000Z", "avg_line_length": 39.4669603524, "max_line_length": 154, "alphanum_fraction": 0.6732336198, "num_tokens": 4873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.782966234021482}}
{"text": "\"\"\"\n    CalculusWithJulia\n\nA package to accompany [notes](calculuswithjulia.github.io) on using Julia with calculus.\n\nThis package does two things: 1) it loads several other packages making it easier to use (and install) the functionality provided by them and 2) defines a handful of functions and plot recipes for convenience.\n\n## Packages loaded by `CalculusWithJulia`\n\n### Built in packages.\n\nThe `MathConstants` package is reexported, allowing `e` to be used instead of `\\euler[tab]` for a value of Euler's constant.\n\nThe `SpecialFunctions` is loaded giving access to a few special functions used in these notes, e.g., `airyai`.\n\nThe `LinearAlgebra` package is loaded for access to several of its functions for working with vectors `norm`, `cdot` (`⋅`), `cross` (`×`), `det`.\n\n### Plotting\n\nThe `Plots` package is loaded giving access to `plot`, `scatter`, `annotate`, etc. The backends  used in the notes are `plotly`, `gr`, and `pyplot`.\n\nThe `ImplicitEquations` package is loaded for plotting implicitly defined functions.\n\nIn addition, several plot recipes are provided to ease the creation of plots:\n`plotif`, `trimplot`, and `signchart` are used for plotting univariate functions;\n`plot_polar` and `plot_parametric_curve` are used to plot curves in 2 or 3 dimensions;\n`plot_parametric_surface` makes the plotting os parameterically defined surfaces easier;\n`vectorfieldplot` and `vectorfieldplot3d` can be used to plot vector fields; and\n`arrow` is a simplified interface to `quiver` that also indicates 3D vectors.\n\n\n### Symbolic math\n\nThe `Sympy` package is loaded for symbolic mathematics\n\n### Zeros of functions\n\nThe `Roots` package is loaded for its `fzero` and `fzeros` functions.\n\n### Derivatives\n\nThe `ForwardDiff` package is loaded giving access to its  `derivative`,  `gradient`, `jacobian`, and `hessian` functions for finding automatic derivatives of functions. In addition, this package defines `'` (for functions) to return a derivative (which commits [type piracy](https://docs.julialang.org/en/v1/manual/style-guide/index.html#Avoid-type-piracy-1)), `∇` to find the gradient (`∇(f)`), the divergence (`∇⋅F`). and the curl (`∇×F`), along with `divergence` and `curl`.\n\n### Integration\n\nThis package reexports `QuadGK`, for one-dimensional integrals; `HCubature`, for multidimensional integrals; and provides `riemann`, for Riemann sums, and `fubini`, for iterated integrals over non-rectangular regions based on `QuadGK`.\n\n\"\"\"\nmodule CalculusWithJulia\n\nusing Reexport\n@reexport using Plots\nusing RecipesBase\nimport ImplicitEquations # handle conflict with SymPy in plot-utils.jl\nimport ImplicitEquations: Pred\n@reexport using LinearAlgebra\n@reexport using Base.MathConstants\n@reexport using SpecialFunctions\n@reexport using Roots\n@reexport using SymPy\nimport ForwardDiff\nexport ForwardDiff\n@reexport using QuadGK\n@reexport using HCubature\n\n\n\ninclude(\"multidimensional.jl\")\ninclude(\"derivatives.jl\")\ninclude(\"integration.jl\")\ninclude(\"plot-utils.jl\")\n\nexport unzip, divergence, gradient, curl, ∇\nexport tangent, secant, D\nexport riemann, fubini\nexport plotif, trimplot, signchart,\n       plot_polar, plot_polar!,\n       plot_parametric_curve,   plot_parametric_curve!,\n       plot_parametric_surface, plot_parametric_surface!,\n       vectorfieldplot,   vectorfieldplot!,\n       vectorfieldplot3d, vectorfieldplot3d,\n       arrow, arrow!\n\n\nend # module\n", "meta": {"hexsha": "c0be96fa9d827057a54720edc591bb089b844263", "size": 3376, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CalculusWithJulia.jl", "max_stars_repo_name": "UnofficialJuliaMirror/CalculusWithJulia.jl-a2e0e22d-7d4c-5312-9169-8b992201a882", "max_stars_repo_head_hexsha": "143c1386e139c395d0971a40395aae16a1da9a9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-25T00:45:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T00:45:02.000Z", "max_issues_repo_path": "src/CalculusWithJulia.jl", "max_issues_repo_name": "UnofficialJuliaMirror/CalculusWithJulia.jl-a2e0e22d-7d4c-5312-9169-8b992201a882", "max_issues_repo_head_hexsha": "143c1386e139c395d0971a40395aae16a1da9a9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CalculusWithJulia.jl", "max_forks_repo_name": "UnofficialJuliaMirror/CalculusWithJulia.jl-a2e0e22d-7d4c-5312-9169-8b992201a882", "max_forks_repo_head_hexsha": "143c1386e139c395d0971a40395aae16a1da9a9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-25T00:45:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T00:45:44.000Z", "avg_line_length": 39.2558139535, "max_line_length": 477, "alphanum_fraction": 0.7636255924, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8856314677809303, "lm_q1q2_score": 0.782933012080213}}
{"text": "function recursive_factorial(n)\n    if n == 0\n        return 1\n    else\n        return n*recursive_factorial(n-1)\n    end\nend\n\nrecursive_factorial(7)\n\nfunction recursive_factorial_info(n)\n    if n == 0\n        println(\"n == 0, returning 1\")\n        return 1\n    else\n        println(\"n == \", n, \", calling itself with parameter \", n-1)\n        output = n*recursive_factorial_info(n-1)\n        println(\"n == \", n, \", finished calling itself, multiplying and returning \", n, \"! = \", output)\n        return output\n    end\nend\n\nrecursive_factorial_info(7)\n\nfunction ack(m,n)\n    if m == 0\n        return n + 1\n    elseif m > 0 && n == 0\n        return ack(m-1,1)\n    else\n        return ack(m-1, ack(m,n-1))\n    end\nend\n\nack(3,4)\n\nfunction ack_info(m,n)\n    function printme()\n        print(\"ack(\", m, \",\", n, \"): \")\n    end\n    if m == 0\n        output = n + 1\n        printme()\n        println(\"Case 1: returning n + 1 = \", output)\n        return output\n    elseif m > 0 && n == 0\n        printme()\n        println(\"Case 2: calling itself with parameters m-1,1 == \", m-1, \",\", 1)\n        output = ack_info(m-1,1)\n        printme()\n        println(\"Case 2: finished calling itself, returning with output \", output)\n        return output\n    else\n        printme()\n        println(\"Case 3: calling itself for new n-value with parameters m,n-1 == \", m, \",\", n-1)\n        newn = ack_info(m,n-1)\n        printme()\n        println(\"Case 3: finished calling itself for new n-value == \", newn)\n        printme()\n        println(\"Case 3: calling itself with parameters m-1, A(m,n-1) == \", m-1, \",\", newn)\n        output = ack_info(m-1,newn)\n        printme()\n        println(\"Case 3: finished calling itself, returning \", output)\n        return output\n    end\nend\n\nack_info(2,1)\n\nfunction my_gcd(a,b)\n    if a == 0\n        return b\n    elseif b == 0\n        return a\n    else\n        return my_gcd(b, a % b)\n    end\nend\n\nfactor = 123_456_789\nprime1 = 67_867_979\nprime2 = 86_028_121\nmy_gcd(prime1*factor, prime2*factor)\n\nusing PyPlot\n\nfunction drawTriangle(x, y, level)\n    # Draw recursively colored triangles.\n    # x,y are 3-vectors that define the vertices of a triangle.\n    \n    if level == 0\n        # Recursion limit (depth) reached\n        fill(x, y, \"y\") # Color whole triangle yellow\n    else\n        # Draw the triangle...\n        plot(x[[1,2,3,1]], y[[1,2,3,1]], \"k\", linewidth=0.5)\n        # Determine the midpoints...\n        a = (x + x[[2,3,1]]) / 2\n        b = (y + y[[2,3,1]]) / 2\n        # Draw and color the interior triangle mauve\n        fill(a, b, \"m\")\n        # Apply the process to the three \"corner\" triangles...\n        newx = [x a a[[3,1,2]]]\n        newy = [y b b[[3,1,2]]]\n        for i = 1:3\n            drawTriangle(newx[i,:], newy[i,:], level - 1)\n        end\n    end\nend\n\n# Equilateral triangle\nx = [0, 1, 0.5]\ny = [0, 0, 1/sqrt(2)]\n\ndrawTriangle(x, y, 5)\n\nfunction mergeLR!(L, R, x)\n    # Merge the *already sorted arrays* L and R into a sorted array x\n    i = j = k = 1\n        \n    # Merge L and R into x\n    while i <= length(L) && j <= length(R)\n        if L[i] < R[j]\n            x[k] = L[i]\n            i += 1\n        else\n            x[k] = R[j]\n            j += 1\n        end\n        k += 1\n    end\n\n    # Copy remaining elements\n    while i <= length(L)\n        x[k] = L[i]\n        i += 1\n        k += 1\n    end\n    while j <= length(R)\n        x[k] = R[j]\n        j += 1\n        k += 1\n    end\nend\n\nfunction mergesort!(x)\n    # Sort the elements of the array x using the Mergesort algorithm\n    if length(x) <= 1\n        return x\n    else\n        mid = length(x) ÷ 2   # Find the midpoint of the array\n        L = x[1:mid]          # Divide array into 2 halves\n        R = x[mid+1:end]\n\n        mergesort!(L)         # Sort first half\n        mergesort!(R)         # Sort second half\n        \n        mergeLR!(L, R, x)\n    end\nend\n\n# Example: Sort random integers\nx = rand(1:1000, 10)\nprintln(x)\nmergesort!(x)\nprintln(x)\n\nfor array_size = Int64[1e3, 1e4, 1e5, 1e6, 1e7]\n    x = rand(array_size)   # Random floating point numbers\n    println(\"n = \", array_size)\n    @time mergesort!(x)\nend\n\nfunction Mvalues(n)\n    returned_values = Int64[]\n\n    function M(n)\n        if n > 100\n            newval = n - 10\n        else\n            newval = M(M(n + 11))\n        end\n        push!(returned_values, newval)\n        return newval\n    end\n\n    M(n)\n    return returned_values\nend\n\nMvalues(105)     # Easy - terminates immediately, M(105) = 95\n\nMvalues(97)      # More complex - finally returns M(97) = 91\n", "meta": {"hexsha": "707d9886197df73e018037b164923939ef036b50", "size": 4533, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Recursion/Recursion.jl", "max_stars_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_stars_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "textbook/_build/jupyter_execute/content/Recursion/Recursion.jl", "max_issues_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_issues_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "textbook/_build/jupyter_execute/content/Recursion/Recursion.jl", "max_forks_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_forks_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3659793814, "max_line_length": 103, "alphanum_fraction": 0.5316567395, "num_tokens": 1413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.8856314632529871, "lm_q1q2_score": 0.7829329972543847}}
{"text": "function mk_score(x)\n    s = 0\n    n = length(x)\n    \n    for i = 1:n-1\n        for j = i : n\n            s = s + sign(x[j] - x[i])\n        end\n    end\n    \n    return s\nend\n\nfunction variance_s(x, n)\n    # calculate the unique data\n    unique_x = unique(x)\n    g = length(unique_x)\n\n    # calculate the var(s)\n    if n == g            # there is no tie\n        var_s = (n*(n-1)*(2*n+5))/18\n        \n    else                 # there are some ties in data\n        tp = zeros(length(unique_x))\n        demo = ones(n)\n        \n        for i in 1:g\n            tp[i] = sum(demo[x == unique_x[i]])\n        end\n        var_s = (n*(n-1)*(2*n+5) - sum(tp*(tp-1)*(2*tp+5)))/18\n    end\n        \n    return var_s\nend\n\nfunction z_score(s, var_s)\n    if s > 0\n        z = (s - 1)/sqrt(var_s)\n    elseif s == 0\n        z = 0\n    elseif s < 0\n        z = (s + 1)/sqrt(var_s)\n    end\n    \n    return z\nend\n\nfunction p_value(z, α)\n    # two tail test\n    p = 2*(1-normcdf(abs(z)))  \n    h = abs(z) > norminvcdf(1-α/2)\n\n    if (z < 0) && h\n        trend = \"decreasing\"\n    elseif (z > 0) && h\n        trend = \"increasing\"\n    else\n        trend = \"no trend\"\n    end\n    \n    return p, h, trend\nend", "meta": {"hexsha": "a0ae08bf16eb067708914d6a02c2c26e0d48d3e4", "size": 1179, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "mmhs013/MannKendall.jl", "max_stars_repo_head_hexsha": "5abca406894ba04acf850790d70ca59085d8d3b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-23T17:05:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T15:29:34.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "mmhs013/MannKendall.jl", "max_issues_repo_head_hexsha": "5abca406894ba04acf850790d70ca59085d8d3b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-06-04T17:32:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-07T17:49:36.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "mmhs013/MannKendall.jl", "max_forks_repo_head_hexsha": "5abca406894ba04acf850790d70ca59085d8d3b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-21T15:54:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T15:54:05.000Z", "avg_line_length": 19.0161290323, "max_line_length": 62, "alphanum_fraction": 0.4503816794, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611643025386, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.782917624806912}}
{"text": "using Plots\n#using LsqFit\nimport Distributions as di\nusing Random\nusing Turing\nusing Statistics\nusing StatsPlots\nusing FillArrays\n\nn = di.Normal(1,2)\nsample_n = rand(n,20)\n\n@model function normal_fit(data)\n\tμ ~ Uniform(-10,10)\n\tσ ~ Uniform(0,20)\n    data ~ MvNormal(Fill(μ,length(data)),σ)\nend\n\nmodel1 = normal_fit(sample_n)\nchain = Turing.sample(model1,NUTS(0.65),1000)\nplot(chain)\n\nrwd = Normal(0,1)\nrw_steps = rand(rwd,999)\n\nx = [0.0]\nfor step in rw_steps\n    push!(x,x[end]+step)\nend\nplot(x)\n\nsteps = []\nfor i in 1:length(x)-1\n    push!(steps,x[i+1]-x[i])\nend\n\nrw_steps\nsteps\n\n@model function diffusion_fit(data)\n\tμ = 0\n\tσ ~ Uniform(0,20)\n\tfor i in 1:length(data)\n\t\tdata[i] ~ Normal(μ,σ)\n\tend\nend\n\nmodel2 = diffusion_fit(steps)\nchain2 = Turing.sample(model2,NUTS(0.65),1000)", "meta": {"hexsha": "96ea936b4be433e1cbab203dc28cdab0f9e688c6", "size": 778, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "probabilistic_prog.jl", "max_stars_repo_name": "hstrey/BME-502-2022", "max_stars_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "probabilistic_prog.jl", "max_issues_repo_name": "hstrey/BME-502-2022", "max_issues_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "probabilistic_prog.jl", "max_forks_repo_name": "hstrey/BME-502-2022", "max_forks_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-15T18:19:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T18:26:08.000Z", "avg_line_length": 15.8775510204, "max_line_length": 46, "alphanum_fraction": 0.6979434447, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561694652216, "lm_q2_score": 0.8080672204860317, "lm_q1q2_score": 0.7829009119105054}}
{"text": "#### TriDiagSolverFuncs\n\n# A module with functions to solve tridiagonal\n# systems of equations using the Thomas algorithm.\n\nexport solve_tridiag!\nexport solve_tridiag_stored!\nexport init_β_γ!\n\n\"\"\"\n    solve_tridiag!(x, B, a, b, c, n, xtemp, γ, β)\n\nSolves for `x` in the equation\n          `Ax = B`\nwhere `A` is a tridiagonal matrix:\n```\n           _                                           _ -1\n          |  b[1] c[1]                                   |\n          |  a[1] b[2]  c[2]                             |\n          |       a[2]  b[3]  c[3]                       |\n x    =   |           *     *     *                      |   B\n          |                 *     *     *                |\n          |                    a[n-2] b[n-1]  c[n-1]     |\n          |_                           a[n-1]  b[n]     _|\n\n          |______________________________________________|\n                                 A\n```\nand given arguments:\n--------------------------------------------\n| x[1:n]       | the result                |\n| B[1:n]       | right hand side           |\n| a[1:n-1]     | sub-diagonal              |\n| b[1:n]       | main diagonal             |\n| c[1:n-1]     | super-diagonal            |\n| n            | system size               |\n| xtemp[1:n]   | temporary                 |\n| γ[1:n-1]     | temporary                 |\n| β[1:n]       | temporary                 |\n--------------------------------------------\n\"\"\"\nfunction solve_tridiag!(x, B, a, b, c, n, xtemp, γ, β)\n  # Define coefficients:\n  β[1] = b[1]\n  γ[1] = c[1]/β[1]\n  for i in 2:n-1\n    β[i] = b[i]-a[i-1]*γ[i-1]\n    γ[i] = c[i]/β[i]\n  end\n  β[n] = b[n]-a[n-1]*γ[n-1]\n\n  # Forward substitution:\n  xtemp[1] = B[1]/β[1]\n  for i = 2:n\n    m = B[i] - a[i-1]*xtemp[i-1]\n    xtemp[i] = m/β[i]\n  end\n\n  # Backward substitution:\n  x[n] = xtemp[n]\n  for i in n-1:-1:1\n    x[i] = xtemp[i]-γ[i]*x[i+1]\n  end\nend\n\n\n\"\"\"\n    solve_tridiag_stored!(x, B, a, β, γ, n, xtemp)\n\nSolves for `x` in the equation\n          `Ax = B`\nwhere `A` is a tridiagonal matrix.\n\nCoefficients in solve_tridiag! can be pre-computed,\nby applying LU factorization to A (shown below).\nThe coefficients, β and γ, can be computed in init_β_γ!.\n```\n _                                           _\n|  b[1]  c[1]                                 |\n|  a[1]  b[2]  c[2]                           |\n|         a[2]  b[3]  c[3]                    |\n|           *     *     *                     |\n|                 *     *     *               |\n|                    a[n-2]  b[n-1]  c[n-1]   |\n|_                            a[n-1]  b[n]   _|\n\n=\n _                                        _   _                                      _ -1\n|  β[1]                                    | |  1  γ[1]                               |\n|  α[1]  β[2]                              | |        1  γ[2]                         |\n|        α[2]  β[3]                        | |              1  γ[3]                   |\n|           *     *     *                  | |                 *     *                |\n|                 *     *                  | |                       *     *          |\n|                    α[n-2]  β[n-1]        | |                             1   γ[n-1] |\n|_                           α[n-1]  β[n] _| |_                                1     _|\n```\n\nand given arguments:\n--------------------------------------------\n| x[1:n]       | the result                |\n| B[1:n]       | right hand side           |\n| a[1:n-1]     | sub-diagonal              |\n| β[1:n]       | temporary                 |\n| γ[1:n-1]     | temporary                 |\n| n            | system size               |\n| xtemp[1:n]   | temporary                 |\n--------------------------------------------\n\"\"\"\nfunction solve_tridiag_stored!(x, B, a, β, γ, n, xtemp)\n  # Forward substitution:\n  xtemp[1] = B[1]/β[1]\n  for i = 2:n\n    m = B[i] - a[i-1]*xtemp[i-1]\n    xtemp[i] = m/β[i]\n  end\n\n  # Backward substitution:\n  x[n] = xtemp[n]\n  for i = n-1:-1:1\n    x[i] = xtemp[i]-γ[i]*x[i+1]\n  end\nend\n\n\"\"\"\n    init_β_γ!(β, γ, a, b, c, n)\n\nReturns the pre-computed coefficients, from applying\nLU factorization, for the tridiagonal system. These\ncoefficients can be passed as arguments to solve_tridiag_stored!.\n--------------------------------------------\n| β[1:n]       | temporary                 |\n| γ[1:n-1]     | temporary                 |\n| a[1:n-1]     | sub-diagonal              |\n| b[1:n]       | main diagonal             |\n| c[1:n-1]     | super-diagonal            |\n| n            | system size               |\n--------------------------------------------\n\"\"\"\nfunction init_β_γ!(β, γ, a, b, c, n)\n  β[1] = b[1]\n  γ[1] = c[1]/β[1]\n  for i = 2:n-1\n    β[i] = b[i]-a[i-1]*γ[i-1]\n    γ[i] = c[i]/β[i]\n  end\n  β[n] = b[n]-a[n-1]*γ[n-1]\nend\n", "meta": {"hexsha": "a3ce5e642a7fd39e69291d260457a004ca87604f", "size": 4749, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Atmos/Parameterizations/TurbulenceConvection/LinearSolvers/TriDiagSolverFuncs.jl", "max_stars_repo_name": "akshaysridhar/CLIMA", "max_stars_repo_head_hexsha": "a96ccc971e231a5de7b8a6a9f5f862d078d0ad4b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-16T22:35:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-16T22:35:45.000Z", "max_issues_repo_path": "src/Atmos/Parameterizations/TurbulenceConvection/LinearSolvers/TriDiagSolverFuncs.jl", "max_issues_repo_name": "akshaysridhar/CLIMA", "max_issues_repo_head_hexsha": "a96ccc971e231a5de7b8a6a9f5f862d078d0ad4b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Atmos/Parameterizations/TurbulenceConvection/LinearSolvers/TriDiagSolverFuncs.jl", "max_forks_repo_name": "akshaysridhar/CLIMA", "max_forks_repo_head_hexsha": "a96ccc971e231a5de7b8a6a9f5f862d078d0ad4b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0878378378, "max_line_length": 89, "alphanum_fraction": 0.3246999368, "num_tokens": 1403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.8824278664544911, "lm_q1q2_score": 0.7828940646376578}}
{"text": "function EuropeanSpreadOptionMC(K, T, S1, S2, sig1, sig2, div1, div2, rho, r, N, M)\n\n## setting parameters\n\ndt = T/N\nnu1dt = (r - div1 - 0.5 * sig1^2) * dt\nnu2dt = (r - div2 - 0.5 * sig2^2) * dt\nsig1sdt = sig1 * sqrt(dt)\nsig2sdt = sig2 * sqrt(dt)\nsrho = sqrt(1 - rho^2)\n\n\n## variables to store the sums of the option values\n\nsum_CT = 0\nsum_CT2 = 0\n\n## outer loop is the number of simulations bigger is better\n\nfor j = 1:M\n\n\tSt1 = S1\n\tSt2 = S2\n\n\n\n\n\t## inner loop is simulating each price path of length N\n\tfor i = 1:N\n\n\t\terror1 = randn()\n\t\terror2 = randn()\n\n\t\tz1 = error1\n\t\tz2 = rho * error1 + srho * error2\n\n\t\tSt1 = St1 * exp(nu1dt + sig1sdt * z1)\n\t\tSt2 = St2 * exp(nu2dt + sig2sdt * z2)\n\n\tend\n\n    \t## wraps up and stores all the values of each path\n\tCT = max(0, St1 - St2 - K)\n\tsum_CT = sum_CT + CT\n\tsum_CT2 = sum_CT2 + CT^2\n\nend\n\n## discounting the average call value\ncall_value = sum_CT / M * exp(-r*T)\n\n\nSD = (sqrt(sum_CT2 - 1/M * (sum_CT^2)) * exp(-2*r*T)) / (M-1)\nSE = SD / sqrt(M)\n\nprintln(\"The Call Value is $call_value\")\nprintln(\"The SD is $SD\")\nprintln(\"The SE is $SE\")\n\nMC = [call_value, SD, SE]\n\nend\n", "meta": {"hexsha": "97a64e22326f3653fb6a6b3af1333126c91698dd", "size": 1113, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/IB/PricingEngines/EuropeanSpreadOptionMC copy.jl", "max_stars_repo_name": "SvenDuve/JuliaAOT.jl", "max_stars_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/IB/PricingEngines/EuropeanSpreadOptionMC copy.jl", "max_issues_repo_name": "SvenDuve/JuliaAOT.jl", "max_issues_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IB/PricingEngines/EuropeanSpreadOptionMC copy.jl", "max_forks_repo_name": "SvenDuve/JuliaAOT.jl", "max_forks_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-27T15:45:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-27T15:45:30.000Z", "avg_line_length": 17.6666666667, "max_line_length": 83, "alphanum_fraction": 0.619047619, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995723244552, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7828412312626557}}
{"text": "include(\"Lanczos_Ritz_Utilities.jl\")\ninclude(\"../../src/iterative_lanczos.jl\")\n\n# ------------------------------------------------------------------------------\n# Demonstrating the loss of orthogonality of the lanczos vectors. \n# And the linear dependence of eigenvalues of the exterior of the spectrum. \n# ------------------------------------------------------------------------------\nn = 64\nA = Diagonal(LinRange(-1, 1, n).^3)\nil = IterativeLanczos(A, rand(n))\nfor _ in 1: n - 1\n    il()\nend\nQ = GetQMatrix(il)\nT = GetTMatrix(il)\n\nfig = heatmap(Q'*Q, size=(722, 512))\nfig2 = heatmap(Q'*A*Q, size=(722, 512))\nfig3 = heatmap(\n    (A*Q[:, 1:end - 1] - Q*T[:, 1:end - 1]).|> abs, \n    size=(1200, 768), dpi=250\n)\nsavefig(fig, \"$(@__DIR__)/plots/fig3.png\")\nsavefig(fig2, \"$(@__DIR__)/plots/fig4.png\")\n\n\n\n# ------------------------------------------------------------------------------\n# All the ritz values during the computations process. and plotting it. \n# ------------------------------------------------------------------------------\n\nfunction RiztTrajectoryPlot(filename, n=64; itr_offset=20, full_ortho=false, title=\"\")\n    A = Diagonal(LinRange(-1, 1, n).^3)\n    il = IterativeLanczos(A, ones(n))\n    il.reorthogonalize = full_ortho\n    FoundRitzValues = Vector{Vector{Float64}}()\n    # push!(FoundRitzValues, [GetTMatrix(il)])\n    TrueEigenValues = diag(A)\n    \n    for II in 1: n - 1\n        il()\n        T = GetTMatrix(il)\n        λs, _ = eigen(T)\n        if II >= itr_offset\n            push!(FoundRitzValues, λs)\n        end\n    end\n    \n    for RitzValue in FoundRitzValues\n        sort!(RitzValue, rev=true)\n    end\n    \n    fig4 = scatter(title=title, legend=false)\n    for Idx in 1: div(itr_offset,2)\n        RitzTrajectory = Vector{Float64}()\n        for RitzValues in FoundRitzValues\n            if Idx <= length(RitzValues)\n                push!(RitzTrajectory, RitzValues[Idx])\n            end\n        end\n        plot!(\n            fig4, \n            # Idx: length(RitzTrajectory) + Idx - 1, \n            itr_offset:(length(RitzTrajectory) + itr_offset - 1), \n            RitzTrajectory, size=(750,750), \n            dpi=250, \n            markershape=:cross, \n            linestyle=:solid\n        )\n    end\n    for Idx in 1:div(itr_offset, 2)\n        RitzTrajectory = Vector{Float64}()\n        for RitzValues in FoundRitzValues\n            if Idx <= length(RitzValues)\n                push!(RitzTrajectory, RitzValues[end - Idx + 1])\n            end\n        end\n        plot!(\n            fig4, \n            # Idx: length(RitzTrajectory) + Idx - 1, \n            itr_offset:(length(RitzTrajectory) + itr_offset - 1),\n            RitzTrajectory,\n            dpi=250, \n            markershape=:xcross,\n            linestyle=:solid\n        )\n    end\n    xlabel!(fig4, \"iterations\")\n    ylabel!(fig4, \"ritz values\")\n    display(fig4)\n    savefig(fig4, \"$(@__DIR__)/plots/$(filename).png\")\n    \nreturn end \n\nRiztTrajectoryPlot(\"ritz_trajectory_plot_floats\", title=\"ritz trajectory no-reorthgonalization\")\nRiztTrajectoryPlot(\"ritz_trajectory_plot_exact\", full_ortho=true, title=\"ritz trajectory with full-reorthogonalizatoin\")\n\n", "meta": {"hexsha": "11715f4efa4e811d417574f2b56c1617063311f1", "size": 3140, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "numerical_experiments/Lanczos_Ritz/Lanczos_Ritz.jl", "max_stars_repo_name": "iluvjava/Subspace_Projection_Method", "max_stars_repo_head_hexsha": "0728d708b18a2f0bca763c1061eb729eb0b79c3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numerical_experiments/Lanczos_Ritz/Lanczos_Ritz.jl", "max_issues_repo_name": "iluvjava/Subspace_Projection_Method", "max_issues_repo_head_hexsha": "0728d708b18a2f0bca763c1061eb729eb0b79c3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical_experiments/Lanczos_Ritz/Lanczos_Ritz.jl", "max_forks_repo_name": "iluvjava/Subspace_Projection_Method", "max_forks_repo_head_hexsha": "0728d708b18a2f0bca763c1061eb729eb0b79c3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0408163265, "max_line_length": 120, "alphanum_fraction": 0.5369426752, "num_tokens": 851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.782809042892983}}
{"text": "############\n## d1, d2 ##\n############\n\nfunction bsDs(sigma::Float64, S::Float64, K::Int, r::Float64, T::Float64)\n    d1 = log(S/(K*exp(-r*T)))/(sigma*sqrt(T)) + 0.5*sigma*sqrt(T)\n    d2 = d1 - sigma*sqrt(T)\n    \n    return (d1, d2)\nend\n\n###############\n## BS Prices ##\n###############\n\nfunction bsCall(sigma::Float64, S::Float64, K::Int, r::Float64, T::Float64)\n    d1, d2 = bsDs(sigma, S, K, r, T)\n    \n    return S*cdf(Normal(), d1) - K*exp(-r*T)*cdf(Normal(), d2)\nend\n\nfunction bsPut(sigma::Float64, S::Float64, K::Int, r::Float64, T::Float64)\n    d1, d2 = bsDs(sigma, S, K, r, T)\n    \n    return K*exp(-r*T)*cdf(Normal(), -d2) - S*cdf(Normal(), -d1)\nend\n\n###########\n## Delta ##\n###########\n\nfunction bsDeltaCall(sigma::Float64, S::Float64, K::Int, r::Float64, T::Float64)\n    d1, d2 = bsDs(sigma, S, K, r, T)\n    return cdf(Normal(), d1)\nend\n\nfunction bsDeltaPut(sigma::Float64, S::Float64, K::Int, r::Float64, T::Float64)\n    d1, d2 = bsDs(sigma, S, K, r, T)\n    return -cdf(Normal(), -d1)\nend\n\n###########\n## Gamma ##\n###########\n\nfunction bsGamma(sigma::Float64, S::Float64, K::Int, r::Float64, T::Float64)\n    d1, d2 = bsDs(sigma, S, K, r, T)\n    return pdf(Normal(), d1)/(S*sigma*sqrt(T))\nend\n\n##########\n## Vega ##\n##########\n\nfunction bsVega(sigma::Float64, S::Float64, K::Int, r::Float64, T::Float64)\n    d1, d2 = bsDs(sigma, S, K, r, T)\n    return S*pdf(Normal(), d1)*sqrt(T)\nend\n\n###########\n## Theta ##\n###########\n\nfunction bsThetaCall(sigma::Float64, S::Float64, K::Int, r::Float64, T::Float64)\n    d1, d2 = bsDs(sigma, S, K, r, T)\n    return -r*exp(-r*T)*K*cdf(Normal(), d2) - sigma*S*pdf(Normal(), d1)/(2*sqrt(T))\nend\n\nfunction bsThetaPut(sigma::Float64, S::Float64, K::Int, r::Float64, T::Float64)\n    d1, d2 = bsDs(sigma, S, K, r, T)\n    return r*exp(-r*T)*K*cdf(Normal(), -d2) - sigma*S*pdf(Normal(), d1)/(2*sqrt(T))\nend\n\n#########\n## Rho ##\n#########\n\nfunction bsRhoCall(sigma::Float64, S::Float64, K::Int, r::Float64, T::Float64)\n    d1, d2 = bsDs(sigma, S, K, r, T)\n    return exp(-r*T)*K*T*cdf(Normal(), d2)\nend\n\nfunction bsRhoPut(sigma::Float64, S::Float64, K::Int, r::Float64, T::Float64)\n    d1, d2 = bsDs(sigma, S, K, r, T)\n    return -exp(-r*T)*K*T*cdf(Normal(), -d2)\nend\n\n########################\n## Implied volatility ##\n########################\n\nfunction implVola(sigma0::Float64, P::Float64, S::Float64, K::Int,\n                  r::Float64, T::Float64, prec::Float64, isCall::Bool)\n    iv = []\n    if isCall\n        iv = implVolaCall(sigma0, P, S, K, r, T, prec)\n    else\n        iv = implVolaPut(sigma0, P, S, K, r, T, prec)\n    end\n    return iv\nend\n\nfunction implVolaCall(sigma0::Float64, P::Float64, S::Float64, K::Int, r::Float64, T::Float64, prec::Float64)\n    # define maximum iteration size\n    maxIter = 1000\n    \n    # calculate deviation\n    stdNorm = Normal(0, 1)\n    d1, d2 = bsDs(sigma0, S, K, r, T)\n    currVega = S*pdf(stdNorm, d1)*sqrt(T)\n    currPrice = S*cdf(stdNorm, d1) - K*exp(-r*T)*cdf(stdNorm, d2)\n    priceDiff = P - currPrice\n\n    iterCounter = 0\n    while (abs(priceDiff) > prec) && (iterCounter < maxIter)\n        # Newton Raphson\n        sigma0 = sigma0 + priceDiff/currVega\n        \n        # new d1, d2, delta, price and deviation\n        d1, d2 = bsDs(sigma0, S, K, r, T)\n        currVega = S*pdf(stdNorm, d1)*sqrt(T)\n        currPrice = S*cdf(stdNorm, d1) - K*exp(-r*T)*cdf(stdNorm, d2)\n        priceDiff = P - currPrice\n        iterCounter += 1\n    end\n    return (sigma0, priceDiff, iterCounter)\nend\n\nfunction implVolaPut(sigma0::Float64, P::Float64, S::Float64, K::Int, r::Float64, T::Float64, prec::Float64)\n    # define maximum iteration size\n    maxIter = 1000\n    \n    # calculate deviation\n    stdNorm = Normal(0, 1)\n    d1, d2 = bsDs(sigma0, S, K, r, T)\n    currVega = S*pdf(stdNorm, d1)*sqrt(T)\n    currPrice = K*exp(-r*T)*cdf(stdNorm, -d2) - S*cdf(stdNorm, -d1)\n    priceDiff = P - currPrice\n\n    iterCounter = 0\n    while (abs(priceDiff) > prec) && (iterCounter < maxIter)\n        # Newton Raphson\n        sigma0 = sigma0 + priceDiff/currVega\n        \n        # new d1, d2, delta, price and deviation\n        d1, d2 = bsDs(sigma0, S, K, r, T)\n        currVega = S*pdf(stdNorm, d1)*sqrt(T)\n        currPrice = K*exp(-r*T)*cdf(stdNorm, -d2) - S*cdf(stdNorm, -d1)\n        priceDiff = P - currPrice\n        iterCounter += 1\n    end\n    return (sigma0, priceDiff, iterCounter)\nend\n", "meta": {"hexsha": "f3faf51f516a6e64d2ecf0d31d33e96327d64fcf", "size": 4359, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bsOptions.jl", "max_stars_repo_name": "JuliaFinMetriX/Econometrics.jl", "max_stars_repo_head_hexsha": "6647c4a009e2c3074524b7b644ed293f79c0732f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-02-29T01:19:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T12:53:59.000Z", "max_issues_repo_path": "src/bsOptions.jl", "max_issues_repo_name": "jngod2011/Econometrics.jl", "max_issues_repo_head_hexsha": "6647c4a009e2c3074524b7b644ed293f79c0732f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-09-24T08:59:16.000Z", "max_issues_repo_issues_event_max_datetime": "2015-09-24T08:59:16.000Z", "max_forks_repo_path": "src/bsOptions.jl", "max_forks_repo_name": "jngod2011/Econometrics.jl", "max_forks_repo_head_hexsha": "6647c4a009e2c3074524b7b644ed293f79c0732f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-04-27T20:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:49:48.000Z", "avg_line_length": 28.3051948052, "max_line_length": 109, "alphanum_fraction": 0.5620555173, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639669551472, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7827232031663813}}
{"text": "## To get this as a string I pasted into vim and then did :%s/\\n  //\nstr = \"7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450\"\n\nmax = 1\nfor i = 1:(length(str)-13)\n    product = 1\n    substr = str[i:i+13]\n    for j = 1:13\n        digit = parse(Int, substr[j])\n        product = product * digit\n        if product > max\n            max = product\n        end\n    end\nend\n\nprintln(max)\n", "meta": {"hexsha": "95f0c93d3e70e2311d7961efcf70408618eaa53f", "size": 1333, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "largestproduct8.jl", "max_stars_repo_name": "vmchale/julia-problem-solving", "max_stars_repo_head_hexsha": "beac7fcf80f551b3f88eb190e12dead42ccf098a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "largestproduct8.jl", "max_issues_repo_name": "vmchale/julia-problem-solving", "max_issues_repo_head_hexsha": "beac7fcf80f551b3f88eb190e12dead42ccf098a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "largestproduct8.jl", "max_forks_repo_name": "vmchale/julia-problem-solving", "max_forks_repo_head_hexsha": "beac7fcf80f551b3f88eb190e12dead42ccf098a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 74.0555555556, "max_line_length": 1008, "alphanum_fraction": 0.8814703676, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474142844409, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7827090573201683}}
{"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\n\n\"This routine solves the periodic wave equation using finite volumes.\"\n\nm = 200 # number of points\n\n# define spatial grid\nxv = LinRange(-1,1,m+2)\nΔx = xv[2]-xv[1]\nx = xv[1:end-1] .+ Δx/2 # m+1 cell centers\n\nΔt = .9*Δx # timestep\nT = 2.0 # final time\n\n# initial condition and forcing\np0(x) = exp(-100*(x+.5)^2)\nu0(x) = 0.\n\n# finite volume flux function\nfunction f(pL,uL,pR,uR)\n    # transform to characteristic variables V = inv(R)*U\n    # v1L = -pL+uL\n    v2L = pL+uL\n    v1R = pR-uR # ??\n    # v2R = pR+uR\n    v1 = v1R # right characteristic\n    v2 = v2L # left characteristic\n    pflux = .5*(-v1 + v2)\n    uflux = .5*(v1 + v2)\n    return pflux, uflux\nend\nfunction f(pL,uL,pR,uR)\n    pflux = .5*(uL+uR) - .5*(pR-pL)\n    uflux = .5*(pL+pR) - .5*(uR-uL)\n    return pflux,uflux\nend\n\np = p0.(x)\nu = u0.(x)\nNsteps = ceil(Int,T/Δt)\nΔt = T / Nsteps\n\nindex_left = [m+1; 1:m+1]\nindex_right = [1:m+1; 1]\n\ninterval = 10\nplot()\nunorm = zeros(Nsteps)\npflux = zeros(m+2)\nuflux = zeros(m+2)\n@gif for k = 1:Nsteps\n    global u,f\n    for i = 1:m+2 # loop over cell interfaces\n        left = index_left[i]\n        right = index_right[i]\n        flux_i = f(p[left],u[left],p[right],u[right])\n        pflux[i] = flux_i[1]\n        uflux[i] = flux_i[2]\n    end\n    p .= p .- Δt/Δx .* diff(pflux)\n    u .= u .- Δt/Δx .* diff(uflux)\n\n    if k % interval==0\n        plot(x,p,linewiΔth=2,legend=false,title=\"Solution at time $(k*Δt)\",ylims=(-1.5,1.5))\n        println(\"on timestep $k out of $Nsteps.\")\n    end\nend every interval\n# plot(x,u,linewiΔth=2,legend=false,title=\"Solution at final time $(T)\",ylims=(-1.5,1.5))\n", "meta": {"hexsha": "294ac46e5dd52d879658aeb3d2e2dc2bff7fecf3", "size": 1646, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "weeks11_to_12/fv_wave.jl", "max_stars_repo_name": "jlchan/caam452_s21", "max_stars_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:38:43.000Z", "max_issues_repo_path": "weeks11_to_12/fv_wave.jl", "max_issues_repo_name": "jlchan/caam452_s21", "max_issues_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "weeks11_to_12/fv_wave.jl", "max_forks_repo_name": "jlchan/caam452_s21", "max_forks_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1830985915, "max_line_length": 92, "alphanum_fraction": 0.5947752126, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.8479677641409289, "lm_q1q2_score": 0.7827074581645791}}
{"text": "\"\"\"\n    SEIso <: Isotropic{SqEuclidean}\n\nIsotropic Squared Exponential kernel (covariance)\n```math\nk(x,x') = σ²\\\\exp(- (x - x')ᵀ(x - x')/(2ℓ²))\n```\nwith length scale ``ℓ`` and signal standard deviation ``σ``.\n\"\"\"\nmutable struct SEIso <: Isotropic{SqEuclidean}\n    \"Squared length scale\"\n    ℓ2::Float64\n    \"Signal variance\"\n    σ2::Float64\n    \"Priors for kernel parameters\"\n    priors::Array\n\n    \"\"\"\n        SEIso(ll::Float64, lσ::Float64)\n\n    Create `SEIso` with length scale `exp(ll)` and signal standard deviation `exp(lσ)`.\n    \"\"\"\n    SEIso(ll::Float64, lσ::Float64) = new(exp(2 * ll), exp(2 * lσ), [])\nend\n\nfunction set_params!(se::SEIso, hyp::VecF64)\n    length(hyp) == 2 || throw(ArgumentError(\"Squared exponential only has two parameters\"))\n    se.ℓ2, se.σ2 = exp(2 * hyp[1]), exp(2 * hyp[2])\nend\n\nget_params(se::SEIso) = Float64[log(se.ℓ2) / 2, log(se.σ2) / 2]\nget_param_names(se::SEIso) = [:ll, :lσ]\nnum_params(se::SEIso) = 2\n\nStatistics.cov(se::SEIso, r::Float64) = se.σ2*exp(-0.5*r/se.ℓ2)\n\n@inline dk_dll(se::SEIso, r::Float64) = r/se.ℓ2*cov(se,r)\n@inline function dk_dθp(se::SEIso, r::Float64, p::Int)\n    if p==1\n        return dk_dll(se, r)\n    elseif p==2\n        return dk_dlσ(se, r)\n    else\n        return NaN\n    end\nend\n", "meta": {"hexsha": "12288c77b541992d13518212c155ba9497d2d708", "size": 1246, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/se_iso.jl", "max_stars_repo_name": "jbrea/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/se_iso.jl", "max_issues_repo_name": "jbrea/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/se_iso.jl", "max_forks_repo_name": "jbrea/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5106382979, "max_line_length": 91, "alphanum_fraction": 0.6195826645, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210671, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.782707447525439}}
{"text": "# Two Factor Designs\n#\n# author: yizhan miao\n# email: yzmiao@protonmail.com\n# last update: Oct 26 2018\n\n\"\"\"Two-way ANOVA\n\nSyntax:\n- `Result = anova2(Y::Array{T, 1}, A::Array{D, 1}, B::Array{D, 1};names=(:A, :B), preview::Bool=true) where {T <: Number, D <: Integer}`\n\nArguments:\n- `Y`: data set in 1d vector\n- `A`: corresponding factor A marker, as Array{Integer, 1}\n- `B`: corresponding factor B marker, as Array{Integer, 1}\n\nKeywords:\n- `names`: the name of the factor [default: `(:A, :B)`]\n- `preview`: print anova table [default: `true`]\n\nReturn:\n- ANOVA Result\n\n\"\"\"\nfunction anova2(Y::Array{T, 1}, A::Array{D, 1}, B::Array{D, 1};names=(:A, :B), preview::Bool=true) where {T <: Number, D <: Integer}\n    # check balance\n    _factor_A = unique(A)\n    _n_factor_A = zeros(Int64, length(_factor_A))\n    for (idx, each) in enumerate(_factor_A)\n        _n_factor_A[idx] = A[A .== each] |> length\n    end\n    \n    _factor_B = unique(B)\n    _n_factor_B = zeros(Int64, length(_factor_B))\n    for (idx, each) in enumerate(_factor_B)\n        _n_factor_B[idx] = B[B .== each] |> length\n    end\n    \n    _rep = length(Y) / length(_factor_A) / length(_factor_B)\n    \n    @assert(length(unique(_n_factor_A)) == 1, \"input data is not balanced across factor A.\")\n    @assert(length(unique(_n_factor_B)) == 1, \"input data is not balanced across factor B.\")\n    #TODO: support unbalanced ANOVA\n    \n    _mean_total = mean(Y)\n    _mean_A = [mean(Y[A .== _A]) for _A in _factor_A]\n    _mean_B = [mean(Y[B .== _B]) for _B in _factor_B]\n    _mean_BA = [mean(Y[(A .== _A) .& (B .== _B)]) for _A in _factor_A, _B in _factor_B]\n    \n    _SS_total = (Y .- _mean_total).^2 |> sum\n    _SS_A = sum((_mean_A .- _mean_total).^2) * _rep * length(_factor_B)\n    _SS_B = sum((_mean_B .- _mean_total).^2) * _rep * length(_factor_A)\n    _SS_S_BA = [sum((Y[(A .== _A) .& (B .== _B)] .- _mean_BA[idx_A, idx_B]).^2) for (idx_A, _A) in enumerate(_factor_A), (idx_B, _B) in enumerate(_factor_B)] |> sum\n    _SS_BA = _SS_total - _SS_A - _SS_B - _SS_S_BA\n    \n    _df_total = length(Y) - 1\n    _df_A = length(_factor_A) - 1\n    _df_B = length(_factor_B) - 1\n    _df_BA = _df_A * _df_B\n    _df_S_BA = _df_total - _df_A - _df_B - _df_BA\n    \n    ##### rm anova #####\n    _MS_A = _SS_A / _df_A\n    _MS_B = _SS_B / _df_B\n    _MS_BA = _SS_BA / _df_BA\n    _MS_S_BA = _SS_S_BA / _df_S_BA\n    \n    _F_A = _MS_A / _MS_S_BA\n    _F_B = _MS_B / _MS_S_BA\n    _F_BA = _MS_BA / _MS_S_BA\n\n    _p_A = ccdf(FDist(_df_A, _df_S_BA), _F_A)\n    _p_B = ccdf(FDist(_df_B, _df_S_BA), _F_B)\n    _p_BA = ccdf(FDist(_df_BA, _df_S_BA), _F_BA)\n    \n    TOTAL = anova_entry(:total, _SS_total, _df_total, NaN, NaN, NaN)\n    _A = anova_entry(names[1], _SS_A, _df_A, _MS_A, _F_A, _p_A)\n    _B = anova_entry(names[2], _SS_B, _df_B, _MS_B, _F_B, _p_B)\n    _BA = anova_entry(Symbol(\"$(names[2])*$(names[1])\"), _SS_BA, _df_BA, _MS_BA, _F_BA, _p_BA)\n    _S_BA = anova_entry(:error, _SS_A, _df_A, _MS_A, NaN, NaN)\n    \n    RESULT = anova_result(\"Two-way ANOVA\", [_A, _B, _BA, _S_BA, TOTAL])\n    \n    preview&&preview_anova_result(RESULT)\n    \n    RESULT\nend", "meta": {"hexsha": "19d186ed24a09c6c92aa3ee08a1bcde75754cd8d", "size": 3078, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/two_factor_designs.jl", "max_stars_repo_name": "ZaneMuir/ANOVA.jl", "max_stars_repo_head_hexsha": "9eeae3a2fdc8f84647d8f6da4bd3ddc53c647615", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-25T08:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-23T04:10:02.000Z", "max_issues_repo_path": "src/two_factor_designs.jl", "max_issues_repo_name": "ZaneMuir/ANOVA.jl", "max_issues_repo_head_hexsha": "9eeae3a2fdc8f84647d8f6da4bd3ddc53c647615", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/two_factor_designs.jl", "max_forks_repo_name": "ZaneMuir/ANOVA.jl", "max_forks_repo_head_hexsha": "9eeae3a2fdc8f84647d8f6da4bd3ddc53c647615", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3793103448, "max_line_length": 164, "alphanum_fraction": 0.6205328135, "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210671, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.782707447525439}}
{"text": "module UtilityFunctions890\r\n\r\n# Write your package code here.\r\n\r\n# Code for utility functions in the Permanent Income Model\r\n\r\n# This is the interfaca (API) visible from outside of the module.\r\nexport AbstractUtility, UtilityLog, UtilityCRRA\r\nexport utility, marg_utility, inv_utility, inv_marg_utility, c_growth, euler_dev\r\n\r\n\r\n## ----------  Generic\r\n# Here we define and document the interface that is common \r\n# to all concrete types\r\n\r\nabstract type AbstractUtility end\r\n\r\n\"\"\"\r\n    utility(u, c)\r\n\r\nUtility level.\r\n\r\nThis is a generic documentation that applies to all concrete types.\r\nBut there is no generic implementation, hence no function body (no methods yet).\r\n\"\"\"\r\nfunction utility end\r\n\r\n\"\"\"\r\n    marg_utility(u, c)\r\n\r\nMarginal utility. Also a generic documentation.\r\n\"\"\"\r\nfunction marg_utility end\r\n\r\n\"\"\"\r\n\teuler_dev(u, cV, betaR)\r\n\r\nEuler equation deviation. Generic!\r\nReturns u'(c) / u'(c') - β R\r\n\r\nThis is a generic function with an implementation that is common to all concrete types.\r\nSo it has a function body.\r\n\"\"\"\r\nfunction euler_dev(\r\n    u :: AbstractUtility, \r\n    cV :: AbstractVector{Float64}, \r\n    betaR :: Float64\r\n    )\r\n    muV = marg_utility(u, cV);\r\n    T = length(cV);\r\n    devV = muV[1 : (T-1)] ./ muV[2 : T] .- betaR;\r\n    return devV\r\nend\r\n\r\n\r\n## ----------  Log\r\n\r\nstruct UtilityLog <: AbstractUtility end\r\n\r\n# Note the broadcasting dot. This now works for scalars and arrays.\r\nutility(u :: UtilityLog, c) = log.(c);\r\nmarg_utility(u :: UtilityLog, c) = 1.0 ./ c;\r\ninv_utility(u :: UtilityLog, util) = exp.(util);\r\ninv_marg_utility(u :: UtilityLog, mu) = 1.0 ./ mu;\r\nc_growth(u :: UtilityLog, betaR) = betaR;\r\n\r\n\r\n## -----------  CRRA\r\n\r\nstruct UtilityCRRA <: AbstractUtility \r\n    sigma :: Float64\r\nend\r\n\r\nutility(u :: UtilityCRRA, c) = (c .^ (1.0 - u.sigma)) ./ (1.0 - u.sigma) .- 1.0;\r\nmarg_utility(u :: UtilityCRRA, c) = c .^ (-u.sigma);\r\ninv_utility(u :: UtilityCRRA, util) = ((util .+ 1.0) .* (1.0 - u.sigma)) .^ (1.0 / (1.0 - u.sigma));\r\ninv_marg_utility(u :: UtilityCRRA, mu) = mu .^ (-1.0 / u.sigma);\r\nc_growth(u :: UtilityCRRA, betaR) = betaR .^ (1.0 / u.sigma);\r\n\r\n\r\nend # module\r\n\r\n\r\n\r\n", "meta": {"hexsha": "92781f4e7838e57327f18ecd9f37a8c7f6edca92", "size": 2138, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/UtilityFunctions890.jl", "max_stars_repo_name": "mariyas24/UtilityFunctions890", "max_stars_repo_head_hexsha": "068d0eb227550c4d474e7cf0d6529e6cfe316e43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/UtilityFunctions890.jl", "max_issues_repo_name": "mariyas24/UtilityFunctions890", "max_issues_repo_head_hexsha": "068d0eb227550c4d474e7cf0d6529e6cfe316e43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/UtilityFunctions890.jl", "max_forks_repo_name": "mariyas24/UtilityFunctions890", "max_forks_repo_head_hexsha": "068d0eb227550c4d474e7cf0d6529e6cfe316e43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1529411765, "max_line_length": 101, "alphanum_fraction": 0.6407857811, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.8791467675095292, "lm_q1q2_score": 0.7826992807914792}}
{"text": "# Author: Ali Siahkoohi, alisk@gatech.edu\n# Date: September 2020\n# Copyright: Georgia Institute of Technology, 2020\n\nexport logpdf, gradlogpdf\n\nfunction logpdf(μ::Float32, σ::Float32, X)\n\n    f = -.5f0*((X .- μ)/σ).^2\n    f = f .+ -5f-1 * log(2f0π) .- log(σ)\n\n    return f\nend\n\nfunction gradlogpdf(μ::Float32, σ::Float32, X)\n\n    g = -(X .- μ)/σ^2\n\n    return g\nend\n\n", "meta": {"hexsha": "c6b3b8492b1dc918dae8265cc33df52c512bc31a", "size": 367, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "WavefieldRecoveryUQ.jl/src/utils/logpdf.jl", "max_stars_repo_name": "slimgroup/Software.SEG2021", "max_stars_repo_head_hexsha": "d3b97a2c08fc7cdb9435f974fb3b3a1fe8bbeda4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-05-11T03:14:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T19:57:09.000Z", "max_issues_repo_path": "WavefieldRecoveryUQ.jl/src/utils/logpdf.jl", "max_issues_repo_name": "slimgroup/Software.SEG2021", "max_issues_repo_head_hexsha": "d3b97a2c08fc7cdb9435f974fb3b3a1fe8bbeda4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WavefieldRecoveryUQ.jl/src/utils/logpdf.jl", "max_forks_repo_name": "slimgroup/Software.SEG2021", "max_forks_repo_head_hexsha": "d3b97a2c08fc7cdb9435f974fb3b3a1fe8bbeda4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-01T18:01:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:01:08.000Z", "avg_line_length": 16.6818181818, "max_line_length": 50, "alphanum_fraction": 0.6185286104, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299653388754, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7826912919496406}}
{"text": "using OrdinaryDiffEq, DiffEqSensitivity, Flux\nusing ComponentArrays, LinearAlgebra, Optimization, Test\n\nconst nknots = 10\nconst h = 1.0/(nknots+1)\nx = range(0, step=h, length=nknots)\nu0 = sin.(π*x)\n\n@inline function f(du,u,p,t)\n  du .= zero(eltype(u))\n  u₃ = @view u[3:end]\n  u₂ = @view u[2:end-1]\n  u₁ = @view u[1:end-2]\n  @. du[2:end-1] = p.k*((u₃ - 2*u₂ + u₁)/(h^2.0))\n  nothing\nend\n\np_true = ComponentArray(k=0.42)\njac_proto = Tridiagonal(similar(u0,nknots-1), similar(u0), similar(u0, nknots-1))\nprob = ODEProblem(ODEFunction(f,jac_prototype=jac_proto), u0, (0.0,1.0), p_true)\n@time sol_true = solve(prob, Rodas4P(), saveat=0.1)\n\nfunction loss(p)\n  _prob = remake(prob, p=p)\n  sol = solve(_prob, Rodas4P(autodiff=false), saveat=0.1, sensealg=ForwardDiffSensitivity())\n  sum((sol .- sol_true).^2)\nend\n\np0 = ComponentArray(k=1.0)\n\noptf = Optimization.OptimizationFunction((x,p) -> loss(x), Optimization.AutoZygote())\noptprob = Optimization.OptimizationProblem(optf, p0)\nres = Optimization.solve(optprob, ADAM(0.01), maxiters = 100)\n\n@test res.u.k ≈ 0.42461977305259074 rtol=1e-1\n", "meta": {"hexsha": "1614000a873f867fa5c77f712da6ff957a1921d2", "size": 1082, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/forwarddiffsensitivity_sparsity_components.jl", "max_stars_repo_name": "JuliaDiffEq/DiffEqSensitivity.jl", "max_stars_repo_head_hexsha": "4ca100b4c6dd87fb5a6c43abde500b61f04928d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2017-05-08T20:25:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T02:50:34.000Z", "max_issues_repo_path": "test/forwarddiffsensitivity_sparsity_components.jl", "max_issues_repo_name": "JuliaDiffEq/DiffEqSensitivity.jl", "max_issues_repo_head_hexsha": "4ca100b4c6dd87fb5a6c43abde500b61f04928d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 119, "max_issues_repo_issues_event_min_datetime": "2016-12-09T19:15:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-21T07:08:20.000Z", "max_forks_repo_path": "test/forwarddiffsensitivity_sparsity_components.jl", "max_forks_repo_name": "JuliaDiffEq/DiffEqSensitivity.jl", "max_forks_repo_head_hexsha": "4ca100b4c6dd87fb5a6c43abde500b61f04928d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-11-04T12:18:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-21T05:46:04.000Z", "avg_line_length": 30.0555555556, "max_line_length": 92, "alphanum_fraction": 0.6950092421, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069105, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7826912779442544}}
{"text": "module RSA\n\nusing Random\n\ninclude(\"utils.jl\")\ninclude(\"primality.jl\")\ninclude(\"process.jl\")\n\nstruct CipherText\n    data::Any\n    is_str::Bool\nend\n\n\"\"\"\nRSA Crypto RSASystem\n\"\"\"\nstruct RSASystem{T <: Integer}\n    bit_size::T\n    primality_test::Function\n    p::BigInt\n    q::BigInt\n    n::BigInt\n    phi::BigInt\n    public_key::Tuple{BigInt, BigInt}\n    private_key::Tuple{BigInt, BigInt}\nend\n\nfunction RSASystem(bit_size::T = 256, primality_test::Function = miller_rabin) where {T <: Integer}\n    p = generate_large_prime(bit_size, primality_test)\n    q = generate_large_prime(bit_size, primality_test)\n    \n    while p == q\n        q = generate_large_prime(bit_size, primality_test)\n    end\n    n = p * q\n    phi = (p - 1) * (q - 1)\n    public_key, private_key = generate_keys(n, phi)\n    RSASystem(bit_size, primality_test, p, q, n, phi, public_key, private_key)\nend\n\n\"\"\"\nGenerates public and private keys\n\"\"\"\nfunction generate_keys(n::BigInt, phi::BigInt) \n    e = rand(2:phi-1)\n    \n    while gcd(e, phi) != 1\n        e = rand(2:phi-1)\n    end\n    \n    d = inverse(e, phi)\n    public_key = (e, n)\n    private_key = (d, n)\n    public_key, private_key\nend\n\ninclude(\"encrypt.jl\")\n\nexport encrypt!, decrypt!, RSASystem\n\nend # module\n", "meta": {"hexsha": "fad7089d194df2b1aaac2012775e9a316fb69a9b", "size": 1232, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/RSA.jl", "max_stars_repo_name": "theobori/RSA.jl", "max_stars_repo_head_hexsha": "b123c118722bcc0f140ea66b48946663e35a3191", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/RSA.jl", "max_issues_repo_name": "theobori/RSA.jl", "max_issues_repo_head_hexsha": "b123c118722bcc0f140ea66b48946663e35a3191", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RSA.jl", "max_forks_repo_name": "theobori/RSA.jl", "max_forks_repo_head_hexsha": "b123c118722bcc0f140ea66b48946663e35a3191", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8709677419, "max_line_length": 99, "alphanum_fraction": 0.6534090909, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768604361742, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7826648435296386}}
{"text": "## template\n\n## binary search\nfunction search_left_border(left::Int, right::Int, key::Function)\n    ## e.g. search_left_border(1, 10, >(3)) | returns 4\n    while left <= right\n        mid = left + (right - left) >> 1\n        if key(mid) ## lies in the right part\n            right = mid - 1\n        else\n            left = mid + 1\n        end\n    end\n    left\nend\n\n## segment tree\nmutable struct SegmentTree{T<:Real}\n    n::Int\n    tree::Vector{T}\n    \n    function SegmentTree(nums::Vector{T}) where T\n        n = length(nums)\n        tree = append!(zeros(Int, n - 1), nums)\n        for i in (n - 1):-1:1\n            tree[i] = tree[i << 1] + tree[i << 1 | 1]\n        end\n        new{T}(n, tree)\n    end\nend\n\nfunction update!(ST::SegmentTree, ind::Int, val::Int)::Nothing\n    tree = ST.tree\n    ind += ST.n - 1\n    delta = val - tree[ind]\n    while ind > 0\n        tree[ind] += delta\n        ind >>= 1\n    end\nend\n\nfunction sum_range(ST::SegmentTree, left::Int, right::Int)::Int\n    left += ST.n - 1\n    right += ST.n - 1\n    res, tree = 0, ST.tree\n    while left <= right\n        if isodd(left) ## right child\n            res += tree[left] ## record outside value\n            left += 1\n        end\n        left >>= 1\n        if iseven(right) ## left child\n            res += tree[right] ## record outside value\n            right -= 1\n        end\n        right >>= 1\n    end\n    res\nend\n\n## merge sort\nfunction merge_sort(arr::AbstractArray)::AbstractArray\n    (n = length(arr)) == 1 && return arr\n    mid = n >> 1\n    lpart = merge_sort(@view(arr[1:mid]))\n    rpart = merge_sort(@view(arr[mid + 1:end]))\n    return merge_sorted(lpart, rpart)\nend\n\nfunction merge_sorted(lpart::AbstractArray{T}, rpart::AbstractArray{T})::AbstractArray{T} where T\n    l1, l2 = length(lpart), length(rpart)\n    combined = Array{T}(undef, l1 + l2)\n    p1 = p2 = 1\n    for pos in eachindex(combined)\n        if p2 > l2 || p1 <= l1 && lpart[p1] <= rpart[p2]\n            combined[pos] = lpart[p1]\n            p1 += 1\n        else\n            combined[pos] = rpart[p2]\n            p2 += 1\n        end\n    end\n    combined\nend\n\n## 二叉树遍历\n## 先序遍历 + 中序遍历\ntraversal(::Nothing) = Int[]\nfunction traversal(root::TreeNode)::Vector{Int}\n    res, stack = Int[], []\n    while !isempty(stack) || !isnothing(root)\n        while !isnothing(root)\n            push!(stack, root)\n            ## preorder traversal\n            root = root.left\n        end\n        root = pop!(stack) \n        ## inorder traversal\n        root = root.right\n    end\n    res\nend", "meta": {"hexsha": "e7109159aaa6d5004df9c388b895202a178c924b", "size": 2516, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/template/general.jl", "max_stars_repo_name": "RexWzh/leetcode_note.jl", "max_stars_repo_head_hexsha": "eae55703e771485d5eff37010f34967694a4158b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/template/general.jl", "max_issues_repo_name": "RexWzh/leetcode_note.jl", "max_issues_repo_head_hexsha": "eae55703e771485d5eff37010f34967694a4158b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/template/general.jl", "max_forks_repo_name": "RexWzh/leetcode_note.jl", "max_forks_repo_head_hexsha": "eae55703e771485d5eff37010f34967694a4158b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6666666667, "max_line_length": 97, "alphanum_fraction": 0.5337837838, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7826586494428217}}
{"text": "\"\"\"\r\nAnalyses for hypergraphs: degree assortativity and intersection profiles.\r\n\r\nBased on \"Configuration Models of Random Hypergraphs\" by Philip S. Chodrow.\r\nThe original paper may be found at https://arxiv.org/abs/1902.09302.\r\n\"\"\"\r\n\r\nusing Random # Used to randomly sample pairs of adjacent nodes\r\n\r\n\"\"\"\r\n`choose_pairs`\r\n==============\r\n\r\nSample random pairs of nodes in the hypergraph that share an edge.\r\n\r\nArguments\r\n---------\r\n    - `H::Hypergraph`: The hypergraph from which to select the pairs\r\n    - `n_pairs::Int64`: The number of pairs to sample\r\n    - `choice_function::Function`: The method for choosing the nodes from each edge.\r\n                                   Options are `uniform`, `top_2`, and `top_bottom`.\r\n\r\nReturns\r\n-------\r\n    - An `n_pairs` x 2 matrix, where each row is a pair and each entry is the\r\n      degree of one of the nodes.\r\n\"\"\"\r\nfunction choose_pairs(H::Hypergraph, n_pairs::Int64, choice_function::Function)\r\n    candidates = filter(x -> H.K[x] >= 2, 1:H.m) # Filters out singleton edges\r\n    if n_pairs > size(candidates,1) # Adjust n_pairs if too large\r\n        n_pairs = size(candidates,1)\r\n    end\r\n\r\n    # Randomly sample edges, and replace only if uniformly selecting nodes\r\n    edges = sample(candidates, n_pairs, replace=string(choice_function) == \"uniform\")\r\n    pairs = [H.D[v] for e in edges for v in choice_function(H, e)] # Choose from edges and convert to degrees\r\n\r\n    return reshape(pairs, 2, size(pairs,1) ÷ 2)'\r\nend\r\n\r\n\"\"\"\r\n`assortativity`\r\n===============\r\n\r\nCalculate the degree assortativity of a hypergraph (pp. 13).\r\nDegree assortativity measures how much nodes tend to associate with other\r\nnodes of similar degree.\r\n\r\nArguments\r\n---------\r\n    - `H::Hypergraph`: The hypergraph to be analyzed\r\n    - `choice_function::String (=\"uniform\")`: The method used to select nodes from edges. Options are\r\n                                                - `\"uniform\"`, which selects two nodes from each edge u.a.r.,\r\n                                                - `\"top_2\"`, which selects the two highest-degree nodes from each edge, and\r\n                                                - `\"top_bottom\"`, which selects the highest- and lowest-degree nodes from each edge.\r\n    - `method::String (=\"spearman\")`: The type of correlation coefficient. Options are\r\n                                        - `\"spearman\"`, which measures monotonic non-decreasing correlation, and\r\n                                        - `\"pearson\"`, which measures linear correlation.\r\n    - `samples::Int64 (=H.m)`: The number of edges to sample\r\n\r\nReturns\r\n-------\r\n    - The correlation coefficient `r` ∈ [-1,1]\r\n\r\nExample\r\n--------\r\n~~~~\r\nassortativity(H; choice_function=\"top_bottom\", method=\"pearson\", samples=100)\r\n~~~~\r\n\"\"\"\r\n\r\nfunction assortativity(H::Hypergraph; choice_function::String=\"uniform\", method::String=\"spearman\", samples::Int64=H.m)\r\n    function uniform(H::Hypergraph, e::Int64)\r\n        return sample(H.edges[e], 2, replace=false)\r\n    end\r\n\r\n    function top_2(H::Hypergraph, e::Int64)\r\n        return shuffle(H.edges[e][1:2])\r\n    end\r\n\r\n    function top_bottom(H::Hypergraph, e::Int64)\r\n        return shuffle([H.edges[e][1], H.edges[e][H.K[e]]])\r\n    end\r\n\r\n    choice_functions = Dict(\"uniform\" => uniform, \"top_2\" => top_2, \"top_bottom\" => top_bottom)\r\n\r\n    pairs = choose_pairs(h, samples, choice_functions[choice_function])\r\n\r\n    if method == \"spearman\"\r\n        # Rank degrees within each column\r\n        pairs = [sortperm(sortperm(pairs[:,1])) sortperm(sortperm(pairs[:,2]))]\r\n    end\r\n\r\n    return cor(pairs[:,1], pairs[:,2])\r\nend\r\n\r\n\"\"\"\r\n`conditional_profile`\r\n=====================\r\n\r\nComputes the probability that two randomly selected edges of sizes `k` and `l`\r\nhave an intersection of size `j`. (pp. 14-15)\r\n\r\nArguments:\r\n----------\r\n    - `H::Hypergraph`: The hypergraph to be analyzed\r\n    - `j::Int64`: The intersection size to look for\r\n    - `k::Int64`: Edge size\r\n    - `l::Int64`: Edge size\r\n\r\nExample\r\n-------\r\n~~~~\r\nconditional_profile(H, 4, 6, 10)\r\n~~~~\r\n\"\"\"\r\nfunction conditional_profile(H::Hypergraph, j::Int64, k::Int64, l::Int64)\r\n    if (j > k || j > l) # Can't have intersection of size j if edge size is less than j\r\n        return 0\r\n    end\r\n\r\n    k_i = findall(i -> H.K[i] == k, 1:H.m) # Find indices of edges of size k\r\n    if size(k_i) == 0 # No k, no way!\r\n        return 0\r\n    end\r\n\r\n    if k == l\r\n        l_i = k_i\r\n    else\r\n        l_i = findall(i -> H.K[i] == l, 1:H.m) # Find indices of edges of size l\r\n    end\r\n\r\n    if size(l_i) == 0\r\n        return 0\r\n    end\r\n\r\n    return mean(\r\n                [length(edge_intersect(h, x, y)) == j ? 1 : 0\r\n                for x in k_i for y in l_i if x != y]\r\n                )\r\nend\r\n\r\n\"\"\"\r\n`conditional_average`\r\n=====================\r\n\r\nCompute the average intersection size of all edges of sizes `k` and `l`. (pp. 15, last paragraph)\r\n\r\nArguments:\r\n----------\r\n    - `H::Hypergraph`: The hypergraph to be analyzed\r\n    - `k::Int64`: Edge size\r\n    - `l::Int64`: Edge size\r\n\"\"\"\r\nfunction conditional_average(H::Hypergraph, k::Int64, l::Int64)\r\n    k_i = findall(i -> H.K[i] == k, 1:H.m)\r\n    if size(k_i) == 0\r\n        return 0\r\n    end\r\n\r\n    if k == l\r\n        l_i = k_i\r\n    else\r\n        l_i = findall(i -> H.K[i] == l, 1:H.m)\r\n    end\r\n\r\n    if size(l_i) == 0\r\n        return 0\r\n    end\r\n\r\n    return mean(\r\n                [length(edge_intersect(h, x, y))\r\n                for x in k_i for y in l_i if x != y]\r\n                )\r\nend\r\n\r\n\"\"\"\r\n`marginal_profile`\r\n==================\r\n\r\nComputes the probability that two randomly selected edges have an intersection of size `j`. (pp. 15, Definition 8)\r\n\r\nArguments:\r\n----------\r\n    - `H::Hypergraph`: The hypergraph to be analyzed\r\n    - `j::Int64`: The intersection size to look for\r\n\"\"\"\r\nfunction marginal_profile(H::Hypergraph, j::Int64)\r\n    return mean(\r\n                [length(edge_intersect(h, x, y)) == j ? 1 : 0\r\n                for x in 1:H.m for y in x+1:H.m]\r\n                )\r\nend\r\n", "meta": {"hexsha": "e28d955b72bcf9d53d3a11362abff2c7ab9e18d6", "size": 6010, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HypergraphAnalysis.jl", "max_stars_repo_name": "charunupara/HigherOrderNetworks.jl", "max_stars_repo_head_hexsha": "f0e72ea4134e40a19529f501f39448b8ba665906", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-18T23:21:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-18T23:21:16.000Z", "max_issues_repo_path": "src/HypergraphAnalysis.jl", "max_issues_repo_name": "joshua-matt/HigherOrderNetworks.jl", "max_issues_repo_head_hexsha": "a52750b619dfd58f311941162e14faeca076c5e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HypergraphAnalysis.jl", "max_forks_repo_name": "joshua-matt/HigherOrderNetworks.jl", "max_forks_repo_head_hexsha": "a52750b619dfd58f311941162e14faeca076c5e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-31T21:22:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-03T06:00:42.000Z", "avg_line_length": 30.9793814433, "max_line_length": 133, "alphanum_fraction": 0.5757071547, "num_tokens": 1541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8577681031721324, "lm_q1q2_score": 0.7826586387228301}}
{"text": "α = 0.3\nδ = 0.1\nβ = 0.9\n\n\nkupper = 2\nklower = 0.001\nn = 10\nkgrid = collect(range(klower, stop = kupper, length = n))\nv = zeros(length(kgrid))\n\nc = zeros(n, n)\nfor i in 1:n\n    for j in 1:n\n        c[i,j] = kgrid[i]^α + (1-δ)*kgrid[i] - kgrid[j]\n    end\n    # vnew = maximum(log.(c) .+ β*v, dims = 2)\nend\n\nc\n\nusing Plots\nheatmap(kgrid, kgrid, c, dims = 2,\n        xlab = \"k prime\",\n        ylab = \"k\",\n        xmirror = true,\n        yflip = true)\n\n\n\n## Fixing negative consumption problem\nvnew = Array{Float64, n}\nc = zeros(n, n)\nfor i in 1:n\n    for j in 1:n\n        c[i,j] = kgrid[i]^α + (1-δ)*kgrid[i] - kgrid[j]\n        if c[i,j] <= 0\n            c[i,j] = 10^-10\n        end\n    end\n    vnew = maximum(log.(c) .+ β*v', dims = 2)\nend\n\nheatmap(kgrid, kgrid, c, dims = 2,\n        xlab = \"k prime\",\n        ylab = \"k\",\n        xmirror = true,\n        yflip = true)\n\nscatter(kgrid, vnew)\n\n## Iterate\ntolerance = 0.001\nimax = 1000\nvnew = zeros(length(kgrid))\nv = vnew .+ 2*tolerance\nglobal cartesianindex = Array{CartesianIndex{2}, n}\ni = 1\nwhile maximum(abs.(v - vnew)) > tolerance && i<=imax\n    v = vnew;\n    c = zeros(n, n);\n    for i in 1:n\n        for j in 1:n\n            c[i,j] = kgrid[i]^α + (1-δ)*kgrid[i] - kgrid[j];\n            if c[i,j] <= 0\n                c[i,j] = 10^-10;\n            end\n        end\n        # vnew = maximum(log.(c) .+ β*v', dims = 2);\n        (vnew, cartesianindex) = findmax(log.(c) .+ β*v', dims = 2);\n    end\n    i += 1\nend\n\nscatter(kgrid, vnew, title = \"v(k)\")\n\nkprimeindex = getindex.(cartesianindex, 2)\nkprime = kgrid[kprimeindex]\nscatter(kgrid, kprime, title = \"k'(k)\")\n\n\n", "meta": {"hexsha": "ec8b9d5626d1f8373d9803e7ef78d8ba2046d9cd", "size": 1611, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vf_iteration_intuitive_steps.jl", "max_stars_repo_name": "PhilipCaoChicago/ECON602_2021", "max_stars_repo_head_hexsha": "ef62b3763663c076ab5ea40009a57232ba338885", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-17T23:05:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T04:17:50.000Z", "max_issues_repo_path": "src/vf_iteration_intuitive_steps.jl", "max_issues_repo_name": "PhilipCaoChicago/ECON602_2021", "max_issues_repo_head_hexsha": "ef62b3763663c076ab5ea40009a57232ba338885", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vf_iteration_intuitive_steps.jl", "max_forks_repo_name": "PhilipCaoChicago/ECON602_2021", "max_forks_repo_head_hexsha": "ef62b3763663c076ab5ea40009a57232ba338885", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-09-21T19:07:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T22:37:40.000Z", "avg_line_length": 19.6463414634, "max_line_length": 68, "alphanum_fraction": 0.5139664804, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7826586362967523}}
{"text": "#=\nThe fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s.\n\nWe shall consider fractions like, 30/50 = 3/5, to be trivial examples.\n\nThere are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator.\n\nIf the product of these four fractions is given in its lowest common terms, find the value of the denominator.\n=#\nfunction isdigitcancelling(a,b)\n  da = digits(a)\n  db = digits(b)\n  if a / b > 1 || da[1] == db[1]\n    return false\n  end\n\n  ra,rb = Int64[],Int64[]\n  for i in intersect(da,db)\n    if da[1] == db[2]\n      push!(ra,da[2])\n      push!(rb,db[1])\n    end\n  end\n  return (length(ra) == 1 && length(rb) == 1 && (a/b) == (ra[1]/rb[1])) ? true : false\nend\n\nfunction calc()\n  numerators = Int64[]\n  denominators = Int64[]\n  for i in 10:99\n    for j in 10:99\n      if isdigitcancelling(i,j)\n        push!(numerators, i)\n        push!(denominators, j)\n      end\n    end\n  end\n  f1,f2 = prod(numerators),prod(denominators)\n  d = gcd(f1,f2)\n  f1 /= d\n  f2 /= d\n  Int64(f2)\nend\n@time println(calc())\n", "meta": {"hexsha": "384811b0b8c494286b602a12c48e1f30998c8e29", "size": 1230, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p33.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p33.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p33.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 27.3333333333, "max_line_length": 198, "alphanum_fraction": 0.6536585366, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630935, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7826493166920984}}
{"text": "#This file implements a number of popular covariance functions\nusing SpecialFunctions\nusing IntelVectorMath\nfunction matern( r::Float64, l::Float64, nu::Float64 )\n  if r == 0\n    return 1.0\n  else\n    return 2.0^(1.0 - nu) / gamma(nu) * (sqrt( 2.0 * nu ) * r / l )^nu * besselk( nu, sqrt( 2.0 * nu ) * r / l ) \n  end\nend\n\nfunction matern12( r, l )\n  exp( - r / l )\nend\n\nfunction matern12!( r, l )\n  r ./= -l\n  IntelVectorMath.exp!(r)\nend\n\n\nfunction matern32( r, l )\n  ( 1 + sqrt(3) * r / l ) * exp( - sqrt(3) * r / l )\nend\n\nfunction matern32!( r, l )\n  r .= - sqrt(3) .* r ./ l\n  rtemp = 1 .- r\n  IntelVectorMath.exp!(r)\n  r .*= rtemp\nend\n\n\nfunction matern52( r, l )\n  ( 1 + sqrt(5) * r / l + 5 * r^2 / 3 / l^2 ) * exp( - sqrt(5) * r / l )\nend\n\nfunction matern52!( r, l )\n  rtemp = ( 1 .+ sqrt(5) * r / l .+ 5 * r.^2 / 3 / l^2 )\n  r .= -sqrt(5) .* r ./ l\n  IntelVectorMath.exp!(r)\n  r .*= rtemp\nend\n\n\nfunction gaussian( r::Float64, l::Float64 )\n  return exp( - ( r/ l )^2 )\nend\n\nfunction exponential( r::Float64, l::Float64 )\n  return exp( -r/l )\nend\n\nfunction exponential!(r, l)\n  r ./= -l\n  IntelVectorMath.exp!(r)\nend\n\n\nfunction invMultiquadratic( r::Float64, l::Float64, c::Float64 = 1. )\n  return 1/sqrt( c + ( r / l )^2 )\nend\n\nfunction ratQuadratic( r::Float64, l::Float64, c::Float64 = 1. )\n  return 1 - (r/l)^2/( (r/l)^2 + c )\nend\n\nfunction cauchy( r::Float64, l::Float64, alpha::Float64, beta::Float64 )\n  return ( 1 + (r/l)^alpha )^(-beta/alpha)\nend\n", "meta": {"hexsha": "c07d38182796e277c030507b2fea037e36821a2b", "size": 1460, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CovFuncs.jl", "max_stars_repo_name": "f-t-s/cholesky_by_KL_minimization", "max_stars_repo_head_hexsha": "f9a7d10932c422bde9f1fcfc950321c8c7b460a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-05-08T16:15:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T04:50:40.000Z", "max_issues_repo_path": "src/CovFuncs.jl", "max_issues_repo_name": "f-t-s/cholesky_by_KL_minimization", "max_issues_repo_head_hexsha": "f9a7d10932c422bde9f1fcfc950321c8c7b460a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CovFuncs.jl", "max_forks_repo_name": "f-t-s/cholesky_by_KL_minimization", "max_forks_repo_head_hexsha": "f9a7d10932c422bde9f1fcfc950321c8c7b460a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-24T06:31:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-24T06:31:39.000Z", "avg_line_length": 20.5633802817, "max_line_length": 113, "alphanum_fraction": 0.5760273973, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541659378681, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7826493154753555}}
{"text": "function duffing(du,u,p,t)\r\n\tx = u[1]\r\n\tdx = u[2]\r\n\tdu[1] = dx\r\n\tdu[2] = -p[3]*dx - p[1]*x - p[2]*x^3 + p[4]*cos(p[5]*t)\r\nend\r\nparameters = [-1.0,1.0,0.3,0.2,1.2] #[alpha,beta,delta,gamma,omega]\r\ntspan = (0.0,10.0)\r\ndx0 = 0.0\r\nx0 = 1.0\r\nprob = ODEProblem(duffing,[x0,dx0],tspan,parameters)\r\nsol = solve(prob)\r\nsol = sol(0.0:0.001:10.0)\r\nX = getindex.(sol.u,1)\r\nY = getindex.(sol.u,2)\r\n\r\nplot(X,Y,label = false)\r\n", "meta": {"hexsha": "6ad7554e45b21dc4625fc32de9b2a1ba476ea973", "size": 412, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scipython_blogs/duffing_oscillator/duffing_oscillator.jl", "max_stars_repo_name": "Ved-Mahajan/JustForFun", "max_stars_repo_head_hexsha": "4e2c7a69074ca20e0ab7b11e8ca4928a2043aabb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scipython_blogs/duffing_oscillator/duffing_oscillator.jl", "max_issues_repo_name": "Ved-Mahajan/JustForFun", "max_issues_repo_head_hexsha": "4e2c7a69074ca20e0ab7b11e8ca4928a2043aabb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scipython_blogs/duffing_oscillator/duffing_oscillator.jl", "max_forks_repo_name": "Ved-Mahajan/JustForFun", "max_forks_repo_head_hexsha": "4e2c7a69074ca20e0ab7b11e8ca4928a2043aabb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8888888889, "max_line_length": 68, "alphanum_fraction": 0.5631067961, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.7826493132177602}}
{"text": "include(\"../../../src/plotSol.jl\")\nusing LinearAlgebra\nusing DifferentialEquations\nusing Revise\n\nfunction DoublePendulumMinReal(m,l,theta1,theta2, tInt, tEnd)\n    grav = -9.806\n    function thdotDouble(x)\n        thDiff = x[3] - x[1] # theta2 - theta1\n        A = zeros(4,4); b = zeros(4)\n        A[1,1] = 1; b[1] = x[2]\n        A[2,:] = [0 4/3 0 cos(thDiff)/2]; b[2] = 3*grav/2/l*sin(x[1]) + sin(thDiff)/2*(x[4]^2)\n        A[3,3] = 1; b[3] = x[4]\n        A[4,:] = [0 cos(thDiff)/2 0 1/3]; b[4] = grav/2/l*sin(x[3]) - sin(thDiff)/2*(x[2]^2)\n        xdot = A\\b\n        return xdot\n    end\n\n    function mainDynMinRealDouble(x,p,t)\n        dx = thdotDouble(x)\n        return dx\n    end\n\n    x0 = [theta1; 0.0; theta2; 0.0]\n    prob = ODEProblem(mainDynMinRealDouble,x0,(0.0,tEnd))\n    sol = solve(prob,Tsit5(),saveat = tInt,reltol=1e-10,abstol=1e-10)\n    tSim = sol.t\n    th1Sol = sol[1,:]\n    th1DotSol = sol[2,:]\n    th2Sol = sol[3,:]\n    th2DotSol = sol[4,:]\n    x1Sol = zeros(length(tSim)); x2Sol = zeros(length(tSim));\n    z1Sol = zeros(length(tSim)); z2Sol = zeros(length(tSim));\n    y1Sol = zeros(length(tSim));\n    v1Sol = zeros(length(tSim),3); v2Sol = zeros(length(tSim),3);\n    r2Sol = zeros(length(tSim),3);\n    for i=1:length(tSim)\n        x1Sol[i] = l/2*sin(th1Sol[i])\n        z1Sol[i] = -l/2*cos(th1Sol[i])\n        v1Sol[i,:] = [l/2*cos(th1Sol[i])*th1DotSol[i] 0.0 l/2*sin(th1Sol[i])*th1DotSol[i]];\n\n        x2Sol[i] = l*sin(th1Sol[i]) + l/2*sin(th2Sol[i])\n        z2Sol[i] = -l*cos(th1Sol[i]) - l/2*cos(th2Sol[i])\n        v2Sol[i,:] = 2*v1Sol[i,:] + permutedims([l/2*cos(th2Sol[i])*th2DotSol[i] 0.0 l/2*sin(th2Sol[i])*th2DotSol[i]]);\n    end\n    r1Sol = [x1Sol y1Sol z1Sol]\n    r2Sol = [x2Sol y1Sol z2Sol]\n    ω1Sol = [y1Sol -th1DotSol y1Sol]\n    ω2Sol = [y1Sol -th2DotSol y1Sol]\n    return r1Sol, r2Sol, v1Sol, v2Sol, ω1Sol, ω2Sol\nend", "meta": {"hexsha": "3d5cb4f921882a336f39e92fc78ff4b7466d13c9", "size": 1849, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "UdKaDyn/Examples/Benchmark/DoublePendulum/DoublePendulumMinReal.jl", "max_stars_repo_name": "isrlab/Multibody-Dynamics", "max_stars_repo_head_hexsha": "bcf46b5b2b197c867c40114d8da208de06a4804a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-04-29T23:58:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T19:48:58.000Z", "max_issues_repo_path": "UdKaDyn/Examples/Benchmark/DoublePendulum/DoublePendulumMinReal.jl", "max_issues_repo_name": "isrlab/Multibody-Dynamics", "max_issues_repo_head_hexsha": "bcf46b5b2b197c867c40114d8da208de06a4804a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UdKaDyn/Examples/Benchmark/DoublePendulum/DoublePendulumMinReal.jl", "max_forks_repo_name": "isrlab/Multibody-Dynamics", "max_forks_repo_head_hexsha": "bcf46b5b2b197c867c40114d8da208de06a4804a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2549019608, "max_line_length": 119, "alphanum_fraction": 0.5684153597, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778024535095, "lm_q2_score": 0.8175744850834649, "lm_q1q2_score": 0.7826459064227588}}
{"text": "#***********************************************************************\n#  Copyright 2006 John A. Trangenstein\n#\n#  This software is made available for research and instructional use \n#  only. \n#  You may copy and use this software without charge for these \n#  non-commercial purposes, provided that the copyright notice and \n#  associated text is reproduced on all copies.  \n#  For all other uses (including distribution of modified versions), \n#  please contact the author at\n#    John A. Trangenstein\n#    Department of Mathematics\n#    Duke University\n#    Durham, NC 27708-0320\n#    USA\n#  or\n#    johnt@math.duke.edu\n#  \n#  This software is made available \"as is\" without any assurance that it\n#  is completely correct, or that it will work for your purposes.  \n#  Use the software at your own risk.\n#***********************************************************************\n\nconst ncells=10000\n\nfunction main()\n\n    #   integer nsteps\n    #   double precision cfl,tmax\n    #   double precision jump,x_left,x_right,statelft,statergt,velocity\n    #   double precision\n    #  &  u(-2:ncells+1),\n    #  &  x(0:ncells),\n    #  &  flux(0:ncells)\n\n    u    = Array{Float64}(undef, ncells+4)\n    x    = Array{Float64}(undef, ncells+1)\n    flux = Array{Float64}(undef, ncells+1)\n\n   #   integer fc,lc,ifirst,ilast\n   #   integer ic,ie,ijump,istep\n   #   double precision dt,dx,frac,mindx,t,vdt\n#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n    #     problem-specific parameters:\n    @time begin # tic()\n    local jump     =  0.0\n    local x_left   = -0.2\n    local x_right  =  1.0\n    local statelft =  2.0\n    local statergt =  0.0\n    local velocity =  1.0\n\n    local nsteps   =  10000\n    local tmax     =  0.8\n    local cfl      =  0.9\n\n    # array bounds:\n    local fc=-2\n    local lc=ncells+1\n    local ifirst=0\n    local ilast=ncells-1\n\n    # uniform mesh:\n    dx=(x_right-x_left)/ncells\n    @inbounds for ie in ifirst:ilast+1\n        x[ie+1]=x_left+ie*dx\n    end\n\n    # initial values for diffential equation:\n    ijump=max(ifirst-1,min(convert(Int,round(ncells*(jump-x_left)/(x_right-x_left))),ilast+1))\n\n    # left state to left of jump\n    @inbounds for ic=ifirst:ijump-1\n        u[ic+3]=statelft\n    end\n\n    # volume-weighted average in cell containing jump\n    frac=(jump-x_left-ijump*dx)/(x_right-x_left)\n    u[ijump+3]=statelft*frac+statergt*(1.0-frac)\n\n    # right state to right of jump\n    @inbounds for ic=ijump+1:ilast\n        u[ic+3]=statergt\n    end\n\n    # stable timestep (independent of time for linear advection):\n    mindx=1.0e300\n    @inbounds for ic=ifirst:ilast\n        mindx=min(mindx,x[ic+2]-x[ic+1])\n    end\n    dt=cfl*mindx/abs(velocity)\n\n    istep=0\n    t=0.0\n\n    # loop over timesteps\n    while istep < nsteps && t < tmax\n        # right boundary condition: outgoing wave\n        @inbounds for ic=ncells:lc\n            u[ic+3]=u[ncells+2]\n        end\n\n        # left boundary condition: specified value\n        @inbounds for ic=fc:-1\n          u[ic+3]=statelft\n        end\n\n        # upwind fluxes times dt (ie, flux time integral over cell side)\n        # assumes velocity > 0\n        vdt=velocity*dt\n        @inbounds for ie=ifirst:ilast+1\n          flux[ie+1]=vdt*u[ie+2]\n        end\n\n        # conservative difference\n        @inbounds for ic=ifirst:ilast\n          u[ic+3] -= (flux[ic+2]-flux[ic+1]) / (x[ic+2]-x[ic+1])\n        end\n\n        # update time and step number\n        t=t+dt\n        istep=istep+1\n    end\n\n    # write final results (plot later)\n    @inbounds for ic=0:ncells-1\n        xc = (x[ic+1]+x[ic+2])*0.5\n        uc = u[ic+3]\n        #@printf(\"%e %e\\n\",xc,uc)\n    end\n\n    end #toc()\nend # main\n\n@time main()\n@time main()\n\n# @profile main()\n# Profile.print()\n\n", "meta": {"hexsha": "47e68c133b04e4cac2a5dc06cac3a0a1feb10c74", "size": 3744, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scalar_law/PROGRAM0/main.jl", "max_stars_repo_name": "alsam/hyperbolic_PDE.jl", "max_stars_repo_head_hexsha": "3576a8ec641aaf9c81a3d35e35aec88595ed364e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-01-04T19:53:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T14:56:17.000Z", "max_issues_repo_path": "scalar_law/PROGRAM0/main.jl", "max_issues_repo_name": "alsam/hyperbolic_PDE.jl", "max_issues_repo_head_hexsha": "3576a8ec641aaf9c81a3d35e35aec88595ed364e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scalar_law/PROGRAM0/main.jl", "max_forks_repo_name": "alsam/hyperbolic_PDE.jl", "max_forks_repo_head_hexsha": "3576a8ec641aaf9c81a3d35e35aec88595ed364e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-07-12T02:33:29.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-12T02:33:29.000Z", "avg_line_length": 26.5531914894, "max_line_length": 94, "alphanum_fraction": 0.5763888889, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856297, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7826446889909319}}
{"text": "\"\"\"\n    lagrange_point(sp::AbstractVector{T}, x) where {T<:Real}\n\nCalculate Legendre polynomials of solution points sp at location x\n\"\"\"\nfunction lagrange_point(sp::AbstractVector{T}, x::Real) where {T<:Real}\n    l = similar(sp)\n    nsp = length(sp)\n\n    for k = 1:nsp\n        tmp = 1.0\n        for j = 1:nsp\n            if j != k\n                tmp *= (x - sp[j]) / (sp[k] - sp[j])\n            end\n        end\n        l[k] = tmp\n    end\n\n    return l\nend\n\nfunction lagrange_point(sp, x::AbstractVector{T}) where {T<:Real}\n    lp = zeros(eltype(sp), axes(x, 1), axes(sp, 1))\n\n    for i in axes(lp, 1)\n        lp[i, :] .= lagrange_point(sp, x[i])\n    end\n\n    return lp\nend\n\n\n\"\"\"\n    ∂lagrange(sp::T) where {T<:AbstractVector{<:Real}}\n    ∂lagrange(V, Vr)\n    ∂lagrange(V, Vr, Vs)\n\nCalculate derivatives of Lagrange polynomials dlⱼ(rᵢ)\n\"\"\"\nfunction ∂lagrange(sp::T) where {T<:AbstractVector{<:Real}}\n    nsp = length(sp)\n    lpdm = similar(sp, nsp, nsp)\n\n    for k = 1:nsp, m = 1:nsp\n        lsum = 0.0\n        for l = 1:nsp\n            tmp = 1.0\n            for j = 1:nsp\n                if j != k && j != l\n                    tmp *= (sp[m] - sp[j]) / (sp[k] - sp[j])\n                end\n            end\n            if l != k\n                lsum += tmp / (sp[k] - sp[l])\n            end\n        end\n        lpdm[m, k] = lsum\n    end\n\n    return lpdm\nend\n\n# ------------------------------------------------------------\n# Vandermonde matrix based evaluation\n# ------------------------------------------------------------\n\nfunction ∂lagrange(V, Vr)\n    Np = size(V, 1)\n\n    ∂l = zeros(Np, Np)\n    for i = 1:Np\n        ∂l[i, :] .= V' \\ Vr[i, :]\n    end\n\n    return ∂l\nend\n\nfunction ∂lagrange(V, Vr, Vs)\n    Np = size(V, 1)\n\n    ∂l = zeros(Np, Np, 2)\n    for i = 1:Np\n        ∂l[i, :, 1] .= V' \\ Vr[i, :]\n        ∂l[i, :, 2] .= V' \\ Vs[i, :]\n    end\n\n    return ∂l\nend\n\n\n\"\"\"\nOne-shot calculation of derivatives of Lagrange polynomials and the values at cell edge\n\n\"\"\"\nfunction standard_lagrange(x)\n    ll = lagrange_point(x, -1.0)\n    lr = lagrange_point(x, 1.0)\n    lpdm = ∂lagrange(x)\n\n    return ll, lr, lpdm\nend\n", "meta": {"hexsha": "0677db2a0f45ab43e66ee3ef6147627fb938f47d", "size": 2114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Polynomial/poly_lagrange.jl", "max_stars_repo_name": "vavrines/FR.jl", "max_stars_repo_head_hexsha": "0108d769f4f9df7401d5fa3e8d8ca269cabacdd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-07-01T07:16:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T11:22:48.000Z", "max_issues_repo_path": "src/Polynomial/poly_lagrange.jl", "max_issues_repo_name": "vavrines/FR.jl", "max_issues_repo_head_hexsha": "0108d769f4f9df7401d5fa3e8d8ca269cabacdd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-25T20:31:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T10:24:59.000Z", "max_forks_repo_path": "src/Polynomial/poly_lagrange.jl", "max_forks_repo_name": "vavrines/FR.jl", "max_forks_repo_head_hexsha": "0108d769f4f9df7401d5fa3e8d8ca269cabacdd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-24T04:02:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-24T04:02:48.000Z", "avg_line_length": 20.5242718447, "max_line_length": 87, "alphanum_fraction": 0.4697256386, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896737173119, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7826446762538083}}
{"text": "## Load the packages.\nusing LoopVectorization\nusing Statistics\nusing BenchmarkTools\nusing PyPlot\n\n\n## Create the refine function.\nfunction refine_field_int!(hi, hi_tmp, lo, n_hi, n_lo)\n    if n_hi ÷ n_lo == 2\n        @tturbo for j in 0:size(lo, 2)-3\n            for i in 0:size(lo, 1)-3\n                i_lo = i + 2\n                j_lo = j + 2\n                i_hi = i*2 + 2\n                j_hi = j*2 + 2\n                for jj in 0:1, ii in 0:1\n                    hi_tmp[i_hi+ii, j_hi+jj] = lo[i_lo, j_lo]\n                end\n            end\n        end\n\n        hi_tmp[1, :] = hi_tmp[end-1, :]\n        hi_tmp[end, :] = hi_tmp[2, :]\n        hi_tmp[:, 1] = hi_tmp[:, end-1]\n        hi_tmp[:, end] = hi_tmp[:, 2]\n\n        # hi[:, :] = hi_tmp[:, :]\n\n        @tturbo for j in 2:size(hi, 2)-1\n            for i in 2:size(hi, 1)-1\n                hi[i, j] = ( 1//16*hi_tmp[i-1, j-1] + 1//8*hi_tmp[i, j-1] + 1//16*hi_tmp[i+1, j-1]\n                           + 1// 8*hi_tmp[i-1, j  ] + 1//4*hi_tmp[i, j  ] + 1// 8*hi_tmp[i+1, j  ]\n                           + 1//16*hi_tmp[i-1, j+1] + 1//8*hi_tmp[i, j+1] + 1//16*hi_tmp[i+1, j+1] )\n            end\n        end\n    elseif n_hi ÷ n_lo == 3\n        @tturbo for j in 0:size(lo, 2)-3\n            for i in 0:size(lo, 1)-3\n                i_lo = i + 2\n                j_lo = j + 2\n                i_hi = i*3 + 2\n                j_hi = j*3 + 2\n                for jj in 0:2, ii in 0:2\n                    hi_tmp[i_hi+ii, j_hi+jj] = lo[i_lo, j_lo]\n                end\n            end\n        end\n\n        hi_tmp[1, :] = hi_tmp[end-1, :]\n        hi_tmp[end, :] = hi_tmp[2, :]\n        hi_tmp[:, 1] = hi_tmp[:, end-1]\n        hi_tmp[:, end] = hi_tmp[:, 2]\n\n        @tturbo for j in 2:size(hi, 2)-1\n            for i in 2:size(hi, 1)-1\n                hi[i, j] = ( 1//9*hi_tmp[i-1, j-1] + 1//9*hi_tmp[i, j-1] + 1//9*hi_tmp[i+1, j-1]\n                           + 1//9*hi_tmp[i-1, j  ] + 1//9*hi_tmp[i, j  ] + 1//9*hi_tmp[i+1, j  ]\n                           + 1//9*hi_tmp[i-1, j+1] + 1//9*hi_tmp[i, j+1] + 1//9*hi_tmp[i+1, j+1] )\n            end\n        end\n    else\n        throw(DomainError(n_hi/n_lo, \"Refinement should be 2 or 3\"))\n    end\nend\n\n\n## Set up the grids.\nn_hi = 12\nn_lo = n_hi ÷ 3\n\na_lo = rand(n_lo, n_lo)\na_hi = zeros(n_hi, n_hi)\n\na_hi_gc = zeros(n_hi+2, n_hi+2)\na_lo_gc = zeros(n_lo+2, n_lo+2)\n\na_hi_gc[2:n_hi+1, 2:n_hi+1] = a_hi[:, :]\na_lo_gc[2:n_lo+1, 2:n_lo+1] = a_lo[:, :]\n\na_hi_gc[1, :] = a_hi_gc[end-1, :]\na_hi_gc[end, :] = a_hi_gc[2, :]\na_hi_gc[:, 1] = a_hi_gc[:, end-1]\na_hi_gc[:, end] = a_hi_gc[:, 2]\n\na_lo_gc[1, :] = a_lo_gc[end-1, :]\na_lo_gc[end, :] = a_lo_gc[2, :]\na_lo_gc[:, 1] = a_lo_gc[:, end-1]\na_lo_gc[:, end] = a_lo_gc[:, 2]\n\ndx_hi = 1/n_hi; dx_lo = 1/n_lo\nx_hi = dx_hi/2:dx_hi:1 |> collect\nx_lo = dx_lo/2:dx_lo:1 |> collect\n\n\n## Compute.\na_hi_tmp = zeros(size(a_hi_gc))\n@btime refine_field_int!(a_hi_gc, a_hi_tmp, a_lo_gc, n_hi, n_lo)\na_hi_int = a_hi_gc[2:end-1, 2:end-1]\n\nprintln(mean(a_lo) ≈ mean(a_hi_int))\n\n\n## Plot the output.\nfigure()\nplot(x_hi, a_hi_int[1, :], \"C0-o\")\nplot(x_hi, a_hi_int[2, :], \"C1-+\")\nif n_hi ÷ n_lo == 3\n    plot(x_hi, a_hi_int[3, :], \"C2-^\")\nend\nplot(x_lo, a_lo[1, :], \"k:\")\ndisplay(gcf())\n\nxh_hi = 0:dx_hi:1 |> collect\nxh_lo = 0:dx_lo:1 |> collect\n\nfigure(figsize=(10, 5))\nsubplot(121)\npcolormesh(xh_lo, xh_lo, a_lo, vmin=0, vmax=1)\nsubplot(122)\npcolormesh(xh_hi, xh_hi, a_hi_int, vmin=0, vmax=1)\ntight_layout()\ndisplay(gcf())\nshow()\n", "meta": {"hexsha": "5cd8458640a41720b136d9a01c98d2f0ef15f2b7", "size": 3432, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/refine_2d.jl", "max_stars_repo_name": "Chiil/MicroHH.jl", "max_stars_repo_head_hexsha": "54c364c40548c1976ebc65161669f48be631bd95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/refine_2d.jl", "max_issues_repo_name": "Chiil/MicroHH.jl", "max_issues_repo_head_hexsha": "54c364c40548c1976ebc65161669f48be631bd95", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-26T12:58:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T14:10:17.000Z", "max_forks_repo_path": "test/refine_2d.jl", "max_forks_repo_name": "Chiil/MicroHH.jl", "max_forks_repo_head_hexsha": "54c364c40548c1976ebc65161669f48be631bd95", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.456, "max_line_length": 100, "alphanum_fraction": 0.4903846154, "num_tokens": 1367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7826446761559401}}
{"text": "module MixingRules\n\nexport bruggemanspheres, looyengacylinders, looyengaspheres, lorentzlorenz, maxwellgarnettspheres, monecke, gedf, gem\n\n\"\"\"\nCalculates the complex refractive index of a porous material using Bruggeman model, for nonmagnetic and isotropic materials. Source: PHYSICAL REVIEW B VOLUME 61, NUMBER 15 15 APRIL 2000-I. It considers spheres (n1) hosted in another material (n2).\nUsage: neff = bruggemanspheres(n1,n2,p)\nInput:\n       n1:    refractive index of material 1\n       n2:    refractive index of material 2\n       p:     porosity parameter (real number, 0<p<1), proportion of n1 over total\nOutput:\n       neff:  effective refractive index\n\"\"\"\nfunction bruggemanspheres(n1::AbstractArray{T,N}, n2::AbstractArray{T,N}, p::S) where {T<:Number, N, S<:Float64}\n    # dielectric function of each media\n    df1 = n1.^2\n    df2 = n2.^2\n    # effective dielectric function: PHYSICAL REVIEW B VOLUME 61, NUMBER 15 15 APRIL 2000-I. solved with mathematica for dfeff.\n    dfeff = 0.25 .* (-df1 + 2 .* df2 + 3 .* df1.*p - 3 .* df2 .* p + sqrt.( 8 .* df1 .* df2 + (-df1 + 2 .* df2 + 3 .* df1.*p - 3 .* df2 .* p).^2 ) )\n    # compute effective refractive index\n    neff = dfeff.^0.5\n    return neff\nend # EOF bruggemanspheres(...)\n\n\"\"\"\nCalculates the complex refractive index of the porous material using Looyenga-Landau-Lifshitz model, for nonmagnetic and isotropic materials. Source: Langmuir 2013, 29, 2784−2789. It considers cylinders (n1) hosted in another material (n2).\nUsage:\n       neff = looyengacylinders(n1,n2,p)\nInput:\n       n1:    refractive index of material 1\n       n2:    refractive index of material 2\n       p:     porosity parameter (real number, 0<p<1), proportion of n1 over total\nOutput:\n       neff:  effective refractive index\n\"\"\"\nfunction looyengacylinders(n1::AbstractArray{T,N}, n2::AbstractArray{T,N}, p::S) where {T<:Number, N, S<:Float64}\n    # compute effective reractive index\n    neff = (1-p) .* n2.^2  + n1.^2 .* p\nend # function looyengacylinders(...)\n\n\"\"\"\nCalculates the complex refractive index of the porous material using Looyenga-Landau-Lifshitz model, for nonmagnetic and isotropic materials. Source: IEEE TRANSACTIONS ON GEOSCIENCE AND REMOTE SENSING, VOL. 38, NO. 3, MAY 2000. It considers spheres (n1) hosted in another material (n2).\nUsage:\n       neff = looyengaspheres(n1,n2,p)\nInput:\n       n1:    refractive index of material 1\n       n2:    refractive index of material 2\n       p:     porosity parameter (real number, 0<p<1), proportion of n1 over total\nOutput:\n       neff:  effective refractive index\n\"\"\"\nfunction looyengaspheres(n1::AbstractArray{T,N}, n2::AbstractArray{T,N}, p::S) where {T<:Number, N, S<:Float64}\n    # dielectric function of each media\n    df1 = n1.^2\n    df2 = n2.^2\n    # compute effective reractive index\n    neff = ( ( ( (1-p) .* (df2.^(1/3)) ) + ( (df1.^(1/3)) .* p) ).^3 ).^0.5\n    return neff\nend # function looyengaspheres(...)\n\n\"\"\"\nReturns the effective dielectric function of a binary liquid mixture. p is the proportion of component n1.\nUsage:\n       neff = lorentzlorenz(n1,n2,p)\nInput:\n       n1:    refractive index of material 1\n       n2:    refractive index of material 2\n       p:     proportion of n1 over total, parameter (real number, 0<p<1)\nOutput:\n       neff:  effective refractive index\n\"\"\"\nfunction lorentzlorenz(n1::AbstractArray{T,N}, n2::AbstractArray{T,N}, p::S) where {T<:Number, N, S<:Float64}\n    neff = sqrt.( ( n2.^2 .* ( -n1.^2 + 2 * p^2 - 2 - 2 .* p .* n1^2) ) ./ ( n1.^2 .* (p-1) - 2 - p .* n2.^2 )  )\nend\n\n\"\"\"\nCalculates the complex refractive index of the porous material using Maxwell-Garnett model, for nonmagnetic and isotropic materials. Source: IEEE TRANSACTIONS ON GEOSCIENCE AND REMOTE SENSING, VOL. 38, NO. 3, MAY 2000. It considers spheres (n1) hosted in another material (n2).\nUsage:\n       neff = maxwellgarnettspheres(n1,n2,p)\nInput:\n       n1:    refractive index of material 1\n       n2:    refractive index of material 2\n       p:     porosity parameter (real number, 0<p<1), proportion of n1 over total\nOutput:\n       neff:  effective refractive index\n\"\"\"\nfunction maxwellgarnettspheres(n1::AbstractArray{T,N}, n2::AbstractArray{T,N}, p::S) where {T<:Number, N, S<:Float64}\n    # dielectric function of each media\n    df1 = n1.^2\n    df2 = n2.^2\n    # compute effective reractive index\n    nfeff = ( df1 + ( (2 .* p .* df1) .* (df2-df1) ./ ( df2 + df1 - p .* (df2-df1) ) ) ).^0.5\n    return neff\nend # EOF maxwellgarnettspheres(n1,n2,p)\n\n\"\"\"\nCalculates the complex refractive index of the porous material using Monecke model, for nonmagnetic and isotropic materials. Source: Phys. Rev. B, Vol. 61, Num. 15, 15 April, 2000-I.\nUsage:\n        neff = monecke(n1, n2, p)\nInput:\n        n1:    refractive index of material 1\n        n2:    refractive index of material 2\n        p:     porosity parameter (real number, 0<p<1), proportion of n1 over total\nOutput:\n        neff:  effective refractive index\n\"\"\"\nfunction monecke(n1::AbstractArray{T,N}, n2::AbstractArray{T,N}, p::S) where {T<:Number, N, S<:Float64}\n    # dielectric function of each media\n    df1 = n1.^2\n    df2 = n2.^2\n    # compute effective dielectric function\n    dfeff = ( 2 * ( p * df1 + (1-p) .* df2 ).^2 ) + ( df1 .* df2) ./ ( ( 1 + p) .* df1 ) + ( (2 - p) .* df2 )\n    # compute effective reractive index\n    neff = dfeff.^0.5\n    return neff\nend # EOF monecke(...)\n\n\"\"\"\nCalculates the complex refractive index of a porous material using a general dielectric model, for nonmagnetic and isotropic materials. Source: Appl. Phys. Lett. 108, 102902 (2016); doi: 10.1063/1.4943639. It considers n1) hosted in another material (n2).\nUsage: neff = gedf(n1, n2, p, β)\nInput:\n       n1:    refractive index of filling material\n       n2:    refractive index of host material\n       p:     porosity parameter (real number, 0<p<1), proportion of n1 over total\n       β:     either 1 or 3\nOutput:\n       neff:  effective refractive index\n\"\"\"\nfunction gedf(n1::AbstractArray{T,N}, n2::AbstractArray{T,N}, p::S, β::S) where {T<:Number, N, S<:Number}\n    # dielectric function of each media\n    df1 = n1.^2\n    df2 = n2.^2\n    deff = df2 .* ( df1 + (β * df2) + (β * p * df1) - (β * p * df2) ) ./ ( df1 + (β * df2) - (p * df1) + (p * df2) )\n    # compute effective refractive index\n    neff = dfeff.^0.5\n    return neff\nend # EOF gedf(...)\n\n\"\"\"\nSource: Carbon 40 (2002) 2801–2815. Here we used equation (3) and the parameters ϕ, ϕc and tp as fitted. For a more detailed analysis and relation to the depolarization factors see the reference. It considers (n1) hosted in another material (n2).\nUsage: neff = gedf(n1, n2, ϕ, ϕc, tp)\nInput:\n    n1:    refractive index of filling material (lower index)\n    n2:    refractive index of host material (higher index)\n    ϕ:     porosity parameter (real number, 0<ϕ<1), proportion of n1 over total\n    ϕc:    critical volume fraction at which the high-index phase first percolates\n    tp:    exponent related both to ϕc and to the shape of the grains\nOutput:\n    neff:  effective refractive index\n\"\"\"\nfunction gem(n1::AbstractArray{T,N}, n2::AbstractArray{T,N}, ϕ::S, ϕc::S, tp::S) where {T<:Number, N, S<:Number}\n    # dielectric function of each media\n    α = (1-ϕc)/ϕc\n    β = 1/tp\n    df1 = (n1.^2).^β\n    df2 = (n2.^2).^β\n    deff = ((α*df1 - ϕ*df1 - α*ϕ*df1 - df2 + ϕ*df2 + α*ϕ*df2 + sqrt.(4*α*df1*df2 + ((α*(ϕ-1) + ϕ)*df1 + df2 - (1 + α)*ϕ*df2).^2))/(2*α)).^tp\n    # compute effective refractive index\n    neff = dfeff.^0.5\n    return neff\nend # EOF gem(...)\n\nend # module MixingRules\n", "meta": {"hexsha": "86354ff2c058749394b65abc39f6a5d4284066a3", "size": 7524, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/MixingRules.jl", "max_stars_repo_name": "lnacquaroli/OpticalTransferMatrix.jl", "max_stars_repo_head_hexsha": "e96a6d7395b05ce24a141705c4ef121284bc76aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2018-12-18T21:33:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-19T12:25:55.000Z", "max_issues_repo_path": "examples/MixingRules.jl", "max_issues_repo_name": "lnacquaroli/OpticalTransferMatrix.jl", "max_issues_repo_head_hexsha": "e96a6d7395b05ce24a141705c4ef121284bc76aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-09-21T02:49:01.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-24T17:10:30.000Z", "max_forks_repo_path": "examples/MixingRules.jl", "max_forks_repo_name": "lnacquaroli/ThinFilmOptics.jl", "max_forks_repo_head_hexsha": "e96a6d7395b05ce24a141705c4ef121284bc76aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-02T01:50:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-02T01:50:20.000Z", "avg_line_length": 45.6, "max_line_length": 286, "alphanum_fraction": 0.6553694843, "num_tokens": 2525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632275178339, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.782611601482304}}
{"text": "\"\"\"\"\r\n    `dare(A, B, Q, R)`\r\n\r\n\r\nCompute `X`, the solution to the discrete-time algebraic Riccati equation,\r\ndefined as A'XA - X - (A'XB)(B'XB + R)^-1(B'XA) + Q = 0, where Q>=0 and R>0\r\n\r\n\r\nAlgorithm taken from:\r\nLaub, \"A Schur Method for Solving Algebraic Riccati Equations.\"\r\n[http://dspace.mit.edu/bitstream/handle/1721.1/1301/R-0859-05666488.pdf](http://dspace.mit.edu/bitstream/handle/1721.1/1301/R-0859-05666488.pdf)\r\n\r\n\r\nFunction taken from the official `ControlSystems.jl` repository\r\n[https://github.com/JuliaControl/ControlSystems.jl](https://github.com/JuliaControl/ControlSystems.jl)\r\n\"\"\"\r\nfunction dare(A, B, Q, R)\r\n    if (!ishermitian(Q) || minimum(eigvals(real(Q))) < 0)\r\n        error(\"Q must be positive-semidefinite.\");\r\n    end\r\n    if (!isposdef(R))\r\n        error(\"R must be positive definite.\");\r\n    end\r\n\r\n    n = size(A, 1);\r\n\r\n    E = [\r\n        Matrix{Float64}(I, n, n) B/R*B';\r\n        zeros(size(A)) A'\r\n    ];\r\n    F = [\r\n        A zeros(size(A));\r\n        -Q Matrix{Float64}(I, n, n)\r\n    ];\r\n\r\n    QZ = schur(F, E);\r\n    QZ = ordschur(QZ, abs.(QZ.alpha./QZ.beta) .< 1);\r\n\r\n    return QZ.Z[(n+1):end, 1:n]/QZ.Z[1:n, 1:n];\r\nend\r\n\r\n\r\n\"\"\"\r\n    `dlqr(A, B, Q, R)`, `dlqr(sys, Q, R)`\r\n\r\n\r\nCalculate the optimal gain matrix `K` for the state-feedback law `u[k] = K*x[k]` that\r\nminimizes the cost function:\r\n\r\nJ = sum(x'Qx + u'Ru, 0, inf).\r\n\r\nFor the discrte time model `x[k+1] = Ax[k] + Bu[k]`. See also `lqg`.\r\n\r\n\r\nUsage example:\r\n\r\n```julia\r\nusing LinearAlgebra # For identity matrix I\r\nh = 0.1\r\nA = [1 h; 0 1]\r\nB = [0;1]\r\nC = [1 0]\r\nsys = ss(A,B,C,0, h)\r\nQ = I\r\nR = I\r\nL = dlqr(A,B,Q,R) # lqr(sys,Q,R) can also be used\r\nu(x,t) = -L*x # Form control law,\r\nt=0:h:5\r\nx0 = [1,0]\r\ny, t, x, uout = lsim(sys,u,t,x0=x0)\r\nplot(t,x, lab=[\"Position\"  \"Velocity\"], xlabel=\"Time [s]\")\r\n```\r\n\r\n\r\nFunction taken from the official `ControlSystems.jl` repository\r\n[https://github.com/JuliaControl/ControlSystems.jl](https://github.com/JuliaControl/ControlSystems.jl)\r\n\"\"\"\r\nfunction dlqr(A, B, Q, R)\r\n    S = dare(A, B, Q, R)\r\n    K = (B'*S*B + R)\\(B'S*A)\r\n    return K\r\nend\r\n\r\n\r\n\"\"\"\r\n    `dkalman(A, C, R1, R2)` kalman(sys, R1, R2)`\r\n\r\n\r\nCalculate the optimal Kalman gain for discrete time systems.\r\n\r\n\r\nFunction taken from the official `ControlSystems.jl` repository\r\n[https://github.com/JuliaControl/ControlSystems.jl](https://github.com/JuliaControl/ControlSystems.jl)\r\n\"\"\"\r\ndkalman(A, C, R1,R2) = Matrix(dlqr(A',C',R1,R2)')\r\n\r\n\r\n\"\"\"\r\n`place(A, B, p)`, `place(sys::StateSpace, p)`\r\n\r\n\r\nCalculate gain matrix `K` such that the poles of `(A-BK)` in are in `p`. Uses\r\nAckermann's formula.\r\n\r\n\r\nFunction taken from the official `ControlSystems.jl` repository\r\n[https://github.com/JuliaControl/ControlSystems.jl](https://github.com/JuliaControl/ControlSystems.jl)\r\n\"\"\"\r\nfunction place(A, B, p)\r\n    n = length(p)\r\n    n != size(A,1) && error(\"Must define as many poles as states\")\r\n    n != size(B,1) && error(\"A and B must have same number of rows\")\r\n    if size(B,2) == 1\r\n        acker(A,B,p)\r\n    else\r\n        error(\"place only implemented for SISO systems\")\r\n    end\r\nend\r\n", "meta": {"hexsha": "2f6835192691625b5e1144d00a367a8122f63788", "size": 3090, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dkalman.jl", "max_stars_repo_name": "cu-sense-lab/GNSSTools.jl", "max_stars_repo_head_hexsha": "6077629b969b7ab8434c6060a317cea818d9c7d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-20T20:22:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T20:22:43.000Z", "max_issues_repo_path": "src/dkalman.jl", "max_issues_repo_name": "cu-sense-lab/GNSSTools.jl", "max_issues_repo_head_hexsha": "6077629b969b7ab8434c6060a317cea818d9c7d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dkalman.jl", "max_forks_repo_name": "cu-sense-lab/GNSSTools.jl", "max_forks_repo_head_hexsha": "6077629b969b7ab8434c6060a317cea818d9c7d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-20T20:22:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T20:22:46.000Z", "avg_line_length": 25.9663865546, "max_line_length": 145, "alphanum_fraction": 0.6038834951, "num_tokens": 1032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.8221891218080991, "lm_q1q2_score": 0.7826115911143108}}
{"text": "### Creating destination popularity: INPUT is datamatrix, e, T, number_zones and OUTPUT is p_dest\n\nfunction createpdestin(datamatrix, number_zones)\n    p_dest = zeros(number_zones, number_zones, T);\n    max_x = zeros(number_zones, number_zones);\n    min_x = zeros(number_zones, number_zones);\n    normalization_factor = zeros(number_zones, T);\n        \n    ## Calculating the minima and maxima of mean travel time \n    for i=1:number_zones \n        # Calculating the minima and maxima\n        for j=1:number_zones # destination zone ID\n            max_x[i,j] = maximum(datamatrix[i, j, :, 1])\n            min_x[i,j] = minimum(datamatrix[i, j, :, 1])\n        end\n    end\n        \n    ## Calculating the unnormalized p_dest\n    for i=1:number_zones \n        for j=1:number_zones\n            for t=1:T\n                if (max_x[i, j] > 0)\n                    mean = datamatrix[i, j, t, 1];\n                    p_dest[i, j, t] = ((mean - min_x[i, j])/ (max_x[i, j] - min_x[i, j]))^e_dest;\n                end\n            end\n        end\n    end\n        \n    ## Calculating normalization factors\n    for i=1:number_zones\n        for t=1:T\n            normalization_factor[i, t] = sum(p_dest[i, :, t]);\n        end\n    end\n        \n    ## Normalizing the probability distributions of p_dest\n    for i=1:number_zones \n        for t=1:T\n            if(normalization_factor[i, t] > 0) # A zero would lead to infinity given the formula below and create NaN entries.\n                for j=1:number_zones\n                    p_dest[i, j, t] = p_dest[i, j, t] / normalization_factor[i, t];\n                end\n            end\n        end\n    end\n\n    return p_dest\n\nend", "meta": {"hexsha": "131302d93aceb4de67441b615e736068cc8db49b", "size": 1656, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/createpdestin.jl", "max_stars_repo_name": "ArsamAryandoust/CarParkingMaps", "max_stars_repo_head_hexsha": "c7aebb51192a3b821be657ddf4523297cc1978f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/createpdestin.jl", "max_issues_repo_name": "ArsamAryandoust/CarParkingMaps", "max_issues_repo_head_hexsha": "c7aebb51192a3b821be657ddf4523297cc1978f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/createpdestin.jl", "max_forks_repo_name": "ArsamAryandoust/CarParkingMaps", "max_forks_repo_head_hexsha": "c7aebb51192a3b821be657ddf4523297cc1978f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.12, "max_line_length": 126, "alphanum_fraction": 0.5634057971, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7825973469996598}}
{"text": "\n@doc raw\"\"\"\nModels.CorrelatedGaussian(ndims)\n\nCreates a highly-correlated Gaussian with the given dimensionality.\n\n```math\n\\mathbf\\theta \\sim \\mathcal{N}\\left(2\\mathbf{1}, \\mathbf{I}\\right)\n```\n```math\n\\Sigma_{ij} = \\begin{cases} 1 &\\quad i=j \\\\ 0.95 &\\quad i\\neq j \\end{cases}\n```\n```math\n\\mathcal{L}(\\mathbf\\theta) = \\mathcal{N}\\left(\\mathbf\\theta | \\mathbf{0}, \\mathbf\\Sigma \\right)\n```\n\nthe analytical evidence of the model is\n\n```math\nZ = \\mathcal{N}\\left(2\\mathbf{1} | \\mathbf{0}, \\mathbf\\Sigma + \\mathbf{I} \\right)\n```\n\n## Examples\n```jldoctest\njulia> model, lnZ = Models.CorrelatedGaussian(10);\n\njulia> lnZ\n-12.482738597926607\n```\n\"\"\"\nfunction CorrelatedGaussian(ndims)\n    priors = fill(Normal(2, 1), ndims)\n    Σ = fill(0.95, ndims, ndims)\n    Σ[diagind(Σ)] .= 1\n    cent_dist = MvNormal(Σ)\n    loglike(X) = logpdf(cent_dist, X)\n\n    model = NestedModel(loglike, priors)\n    true_lnZ = logpdf(MvNormal(fill(2, ndims), Σ + I), zeros(ndims))\n    return model, true_lnZ\nend\n", "meta": {"hexsha": "b1dcfe7d34f4980229e0586a1048c65ae88b7a93", "size": 982, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/correlated.jl", "max_stars_repo_name": "aplavin/NestedSamplers.jl", "max_stars_repo_head_hexsha": "3e6b6eae4620a1bdef46e81ac1a9c9801a364327", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2020-04-02T20:09:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-01T22:55:14.000Z", "max_issues_repo_path": "src/models/correlated.jl", "max_issues_repo_name": "aplavin/NestedSamplers.jl", "max_issues_repo_head_hexsha": "3e6b6eae4620a1bdef46e81ac1a9c9801a364327", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 65, "max_issues_repo_issues_event_min_datetime": "2020-04-02T20:08:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T00:32:12.000Z", "max_forks_repo_path": "src/models/correlated.jl", "max_forks_repo_name": "aplavin/NestedSamplers.jl", "max_forks_repo_head_hexsha": "3e6b6eae4620a1bdef46e81ac1a9c9801a364327", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-06-21T18:50:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T19:08:49.000Z", "avg_line_length": 23.380952381, "max_line_length": 95, "alphanum_fraction": 0.6608961303, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966762263736, "lm_q2_score": 0.8267118026095992, "lm_q1q2_score": 0.7825626445473605}}
{"text": "function calc_Energies( LF::LF3dGrid, Vpot, psi::Array{Float64,2} )\n  #\n  Ncol = size(psi)[2]\n  ΔV = LF.LFx.h * LF.LFy.h * LF.LFz.h\n  Etot = 0.0\n  Ekin = 0.0\n  Epot = 0.0\n  #\n  for ic = 1:Ncol\n    nabla2_v = op_nabla2( LF, psi[:,ic] )\n    Ekin = Ekin + -0.5*dot( psi[:,ic], nabla2_v ) * ΔV\n    Epot = Epot + sum( Vpot .* psi[:,ic].^2 ) * ΔV\n  end\n  Etot = Ekin + Epot\n  return EnergiesT( Etot, Ekin, Epot )\nend\n\n\nfunction calc_Energies( LF::LF3dGrid, ∇2::SparseMatrixCSC{Float64,Int64},\n                        Vpot, psi::Array{Float64,2} )\n  #\n  Ncol = size(psi)[2]\n  ΔV = LF.LFx.h * LF.LFy.h * LF.LFz.h\n  Etot = 0.0\n  Ekin = 0.0\n  Epot = 0.0\n  #\n  for ic = 1:Ncol\n    nabla2_v = ∇2 * psi[:,ic]\n    Ekin = Ekin + -0.5*dot( psi[:,ic], nabla2_v ) * ΔV\n    Epot = Epot + sum( Vpot .* psi[:,ic].^2 ) * ΔV\n  end\n  Etot = Ekin + Epot\n  return EnergiesT( Etot, Ekin, Epot )\nend\n", "meta": {"hexsha": "445792f4d069ef64e193e87e60137ec07fbc606a", "size": 872, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LF/sch_3d/calc_Energies.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "LF/sch_3d/calc_Energies.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LF/sch_3d/calc_Energies.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 24.2222222222, "max_line_length": 73, "alphanum_fraction": 0.5504587156, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7825626335032426}}
{"text": "push!(LOAD_PATH, \"/Users/eroesch/Documents/phd/neural-ode/\")\nusing Flux, DiffEqFlux, DifferentialEquations, Plots\n\n## Setup ODE to optimize\nfunction lotka_volterra(du,u,p,t)\n  x, y = u\n  α, β, δ, γ = p\n  du[1] = dx = α*x - β*x*y\n  du[2] = dy = -δ*y + γ*x*y\nend\nu0 = [1.0,1.0]\ntspan = (0.0,10.0)\np = [1.5,1.0,3.0,1.0]\nprob = ODEProblem(lotka_volterra,u0,tspan,p)\n\n# Verify ODE solution\nsol = solve(prob,Tsit5())\nplot(sol)\n\n# Generate data from the ODE\nsol = solve(prob,Tsit5(),saveat=0.1)\nA = sol[1,:] # length 101 vector\nt = 0:0.1:10.0\nscatter!(t,A)\n\n# Build a neural network that sets the cost as the difference from the\n# generated data and 1\n\np = param([2.2, 1.0, 2.0, 0.4]) # Initial Parameter Vector\nfunction predict_rd() # Our 1-layer neural network\n  diffeq_rd(p,prob,Tsit5(),saveat=0.1)[1,:]\nend\nloss_rd() = sum(abs2,x-1 for x in predict_rd()) # loss function\n\n# Optimize the parameters so the ODE's solution stays near 1\n\ndata = Iterators.repeated((), 100)\nopt = ADAM(0.1)\ncb = function () #callback function to observe training\n  display(loss_rd())\n  # using `remake` to re-create our `prob` with current parameters `p`\n  display(plot(solve(remake(prob,p=Flux.data(p)),Tsit5(),saveat=0.1),ylim=(0,6)))\nend\n# Display the ODE with the initial parameter values.\ncb()\nFlux.train!(loss_rd, [p], data, opt, cb = cb)\n", "meta": {"hexsha": "36e5d965be7e2098d42d07e891766972ef4a5282", "size": 1320, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "other/diffeq/lis_two_stage.jl", "max_stars_repo_name": "LislPisl/model-zoo", "max_stars_repo_head_hexsha": "e0684ddcf027d9509461fc1024ee53327fb6a65d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "other/diffeq/lis_two_stage.jl", "max_issues_repo_name": "LislPisl/model-zoo", "max_issues_repo_head_hexsha": "e0684ddcf027d9509461fc1024ee53327fb6a65d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "other/diffeq/lis_two_stage.jl", "max_forks_repo_name": "LislPisl/model-zoo", "max_forks_repo_head_hexsha": "e0684ddcf027d9509461fc1024ee53327fb6a65d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.085106383, "max_line_length": 81, "alphanum_fraction": 0.6772727273, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7825626311775}}
{"text": "# ------------------------------------------------------------------------------\n# Computations involving triangles\n# -------------------------------------------------------------------------------\n\nusing SymPy\n\n\"\"\"\n    equipoints(A, B)\n\nFind the two points the can form an equilateral triangle with `A` and `B`\n\"\"\"\nfunction equipoints(A, B)\n    x, y = @vars x y\n    pt = Point(x, y)\n    dist1 = squaredist(pt, A)\n    dist2 = squaredist(pt, B)\n    dist3 = squaredist(A, B)\n    sol = solve([dist1-dist3, dist2-dist3], [x,y])\n    [Point(simplify(s[1]), simplify(s[2])) for s in sol]\nend\n\n\"\"\"\n    outer_equitri(A, B, C)\n\nFind the outer equilateral triangle of `Triangle(A, B, C)` which is incident to `Edge(A, B)`.\n\"\"\"\nfunction outer_equitri(A, B, C)\n    ptAB = equipoints(A, B)\n    dist = map(pt->squaredist(pt, C), ptAB)\n    d = simplify(dist[1]-dist[2])\n    if simplify(d>=0)\n        return Triangle(A, B, ptAB[1])\n    else\n        return Triangle(A, B, ptAB[2])\n    end\nend\n\n\"\"\"\n    outer_equitriangles(📐️)\n\nFind all three outer equilateral triangles of the triangle `📐️`.\n\"\"\"\nfunction outer_equitriangles(📐️)\n    pts = vertices(📐️)\n    triangles = map(i->outer_equitri(circshift(pts, i)...), 0:2)\n    triangles\nend\n\n\n\"\"\"\n    isequilateral(📐️)\n\nCheck if `📐️` is equilateral, i.e., if the three edges of `📐️` are of the same length.\n\"\"\"\nfunction isequilateral(📐️)\n    dist = [squaredist(e.src, e.dst) for e in edges(📐️)]\n    if (dist[1] == dist[2]) && (dist[1] == dist[3])\n        return true\n    else\n        return false\n    end\nend\n\n\"\"\"\n    median(A::Point, B::Point, C::Point)\n\nFind the edge from the midpoint of `A` and `B` to `C`.\n\"\"\"\nfunction median(A::Point, B::Point, C::Point)\n    Edge(midpoint(A, B), C)\nend\n", "meta": {"hexsha": "04264fc0a098cc3d005edde529c8e774ab8848cb", "size": 1719, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/triangle.jl", "max_stars_repo_name": "newptcai/PlaneGeometry.jl", "max_stars_repo_head_hexsha": "fe2644fdf824a364daa1ce362bf5557d40775226", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-05-12T04:22:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:20:31.000Z", "max_issues_repo_path": "src/triangle.jl", "max_issues_repo_name": "newptcai/PlaneGeometry.jl", "max_issues_repo_head_hexsha": "fe2644fdf824a364daa1ce362bf5557d40775226", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/triangle.jl", "max_forks_repo_name": "newptcai/PlaneGeometry.jl", "max_forks_repo_head_hexsha": "fe2644fdf824a364daa1ce362bf5557d40775226", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.875, "max_line_length": 93, "alphanum_fraction": 0.5491564863, "num_tokens": 522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7825626282163007}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.20\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ a3c276fe-30e3-11eb-3e4c-fb31d63eabf6\nusing ModelingToolkit, OrdinaryDiffEq, Plots, PlutoUI\n\n# ╔═╡ dc926c2c-30e4-11eb-0b88-05fc45844731\nimport Pkg; Pkg.add(\"OrdinaryDiffEq\")\n\n# ╔═╡ e0f36006-3ba1-11eb-3a47-193462d57302\nmd\"Enter a value for α - natural exponential growth of the prey\n$(@bind α Slider(1.0 : 1 : 10; default=1.0, show_value=true))\n\nEnter a value for β - rate of decrease in prey from predators\n$(@bind β Slider(1.0 : 1 : 10; default=2.0, show_value=true))\n\nEnter a value for δ - rate of predators growth by eating prey\n$(@bind δ Slider(0.5 : .05 : 5; default=1.5, show_value=true))\n\nEnter a value for γ - natural exponential decline of the predator\n$(@bind γ Slider(0.5 : .05 : 2; default=1.25, show_value=true))\n\nEnter a value for x0 - Initial Prey count \n$(@bind x0 Slider(1 : .1 : 10; default=1, show_value=true))\n\nEnter a value for y0 - Initial Predator count \n$(@bind y0 Slider(1 : .1 : 10; default=1, show_value=true))\n\"\n\n# ╔═╡ 7ebba51a-30e3-11eb-364e-f1255f41a963\nfunction fn_Lotka_Volterra(a,b,c,d,x0,y0)\n\t@parameters t α β δ γ\n\t@variables x(t) y(t) \n\t@derivatives D'~t\n\n\teqs = [D(x) ~ α*x-β*x*y,\n\t\t   D(y) ~ δ*x*y-γ*y]\n\n\tLotka_Volterra = ODESystem(eqs,name=:Lotka_Volterra)\n\n\tsys = ODESystem(eqs)\n\n\tu0 = [x => x0,\n\t\t  y => y0]\n\t\n    p = [α=>a, β=>b, δ=>c, γ=>d];\n\t\n\ttspan = (0.0,10.0)\n\tprob = ODEProblem(sys,u0,tspan,p)\n\tsol = solve(prob, Tsit5())\nend\t\n\n# ╔═╡ cb68360a-3b2f-11eb-3bef-b5e530f74f2e\nbegin\n\tsol1=fn_Lotka_Volterra(α,β,δ,γ,x0,y0)\n    plot(sol1)\nend\n\n# ╔═╡ 5edf7256-3bbc-11eb-027d-a990de629754\nmd\"### Here are some specific scenarios.\n##### α=2.2,β=3.2,δ=1.6,γ=1.45  x0=2,y0=3 \"\n\n\n# ╔═╡ c9c12e30-3bbb-11eb-308c-b5bc17e4706e\nbegin\n\tsol2=fn_Lotka_Volterra(2.2,3.2,1.6,1.45,2,3)\n    plot(sol2)\nend\n\n# ╔═╡ Cell order:\n# ╠═dc926c2c-30e4-11eb-0b88-05fc45844731\n# ╠═a3c276fe-30e3-11eb-3e4c-fb31d63eabf6\n# ╠═7ebba51a-30e3-11eb-364e-f1255f41a963\n# ╟─e0f36006-3ba1-11eb-3a47-193462d57302\n# ╠═cb68360a-3b2f-11eb-3bef-b5e530f74f2e\n# ╟─5edf7256-3bbc-11eb-027d-a990de629754\n# ╠═c9c12e30-3bbb-11eb-308c-b5bc17e4706e\n", "meta": {"hexsha": "40b58adb1de43031f5feff3a9f1f6df8a3f89513", "size": 2492, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "calculus/modeling_predprey.jl", "max_stars_repo_name": "22natarajank/Highschool-Julia", "max_stars_repo_head_hexsha": "9d37e181178876c84aae3ebad7071cd61757daa7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-02-04T11:01:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-19T08:36:58.000Z", "max_issues_repo_path": "calculus/modeling_predprey.jl", "max_issues_repo_name": "22natarajank/Highschool-Julia", "max_issues_repo_head_hexsha": "9d37e181178876c84aae3ebad7071cd61757daa7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calculus/modeling_predprey.jl", "max_forks_repo_name": "22natarajank/Highschool-Julia", "max_forks_repo_head_hexsha": "9d37e181178876c84aae3ebad7071cd61757daa7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6888888889, "max_line_length": 195, "alphanum_fraction": 0.6849919743, "num_tokens": 1070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.8774767922879692, "lm_q1q2_score": 0.7825435055704183}}
{"text": "## Accurate Summation\n# See what happens in two floatint Point\n# precisions\nusing Printf\n\"\"\" Run an example where we compute\na sum in a low-precision and compare with\na high-precision sum. You can use BigFloat\nin case you need to check Float64. \"\"\"\nfunction sum_example_1(ns, Tlow, Thigh=Float64)\n  for n in ns\n    x = randn(Tlow, n)\n    y = Thigh.(x) # convert to high-precision\n    s1 = sum(x) # sum in low-precision\n    s2 = sum(y) # sum in high-precision\n    @printf(\"%10i - %20s - %20s\\n\", n, \"$s1\", \"$s2\")\n  end\nend\nsum_example_1([10^3 10^4 10^5 10^6], Float16)\n## Let's do the same example but where we control the sum\n# and don't allocate vectors.\nusing Printf\nfunction sum_example(ns, Tlow, Thigh=Float64)\n  for n in ns\n    s1 = zero(Tlow)\n    s2 = zero(Thigh)\n    for i =1:n\n      x = randn(Tlow)\n      s1 += x\n      s2 += Thigh.(x)\n      x = rand(Tlow)\n      x *= 2*rand(Bool)-1 # random sign\n      s1 += x\n      s2 += Thigh.(x)\n    end\n    @printf(\"%10i - %20s - %20s\\n\", n, \"$s1\", \"$s2\")\n  end\nend\nsum_example([10^3 10^4 10^5 10^6], Float16)\n\n## Kahan Summation\n\n\"\"\"\nkahan_sum implements one step of the Kahan summation procedure.\nfunction KahanSum(input)\n  variables sum,c,y,t,i          // Local to the routine.\n    sum = 0.0                    // Prepare the accumulator.\n    c = 0.0                      // A running compensation for lost low-order bits.\n    for i = 1 to input.length do // The array input has elements indexed input[1] to input[input.length].\n        y = input[i] - c         // c is zero the first time around.\n        t = sum + y              // Alas, sum is big, y small, so low-order digits of y are lost.\n        c = (t - sum) - y        // (t - sum) cancels the high-order part of y; subtracting y recovers negative (low part of y)\n        sum = t                  // Algebraically, c should always be zero. Beware overly-aggressive optimizing compilers!\n    next i                       // Next time around, the lost low part will be added to y in a fresh attempt.\n    return sum\n\"\"\"\nfunction kahan_sum(x,sum,c)\n  y = x-c\n  t = sum+y\n  c = (t-sum)-y\n  sum = t\n  return sum,c\nend\n\nfunction ksum(xs::AbstractArray)\n  sum = zero(eltype(xs))\n  c = zero(eltype(xs))\n  for x in xs\n    sum,c = kahan_sum(x, sum, c)\n  end\n  return sum\nend\nksum(randn(Float16,1000))\n\n##\nusing Printf\nfunction sum_example_kahan(ns, Tlow, Thigh=Float64)\n  for n in ns\n    s0 = zero(Tlow)\n    s1 = zero(Tlow)\n    c1 = zero(Tlow)\n    s2 = zero(Thigh)\n    for i =1:n\n      x = randn(Tlow)\n      s0 += x\n      s1,c1 = kahan_sum(x, s1, c1)\n      s2 += Thigh.(x)\n      x = rand(Tlow)\n      x *= 2*rand(Bool)-1 # random sign\n      s0 += x\n      s1,c1 = kahan_sum(x, s1, c1)\n      s2 += Thigh.(x)\n    end\n    @printf(\"%10i - %8s - %8s - %20s\\n\", n, \"$s0\",\"$s1\", \"$s2\")\n  end\nend\nusing Random\nRandom.seed!(0)\nsum_example_kahan([10^3 10^4 10^5 10^6], Float16)\n", "meta": {"hexsha": "d7407c74c605fe839e324d14377de0becea490ad", "size": 2864, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3-unit-2-demos/summation.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "3-unit-2-demos/summation.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3-unit-2-demos/summation.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 28.9292929293, "max_line_length": 127, "alphanum_fraction": 0.5897346369, "num_tokens": 949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.8918110526265554, "lm_q1q2_score": 0.7825434974995488}}
{"text": "\n \n\ntype LDA\n    n_components::Integer\n    method::String\n    w::Vector\nend\n\nfunction LDA(;\n             n_components::Integer = 2,\n             method = \"svd\",\n             w::Vector = zeros(10))\n    return LDA(n_components, method, w)\nend\n\n\nfunction calc_Sw_Sb(model::LDA, X::Matrix, y::Vector)\n    n_feature = size(X, 2)\n    n_sample = size(X, 1)\n    labels = unique(y)\n    Sw = zeros(n_feature, n_feature)\n    for label in labels\n        X_ = X[find(y.==label),:]\n        Sw += size(X_, 1) * cov(X_)\n    end\n\n    total_mean = mean(X, 1)\n    Sb = zeros(n_feature , n_feature)\n    for label in labels\n        X_ = X[find(y .== label),:]\n        mean_ = (mean(X_,1) - total_mean)\n        Sb += size(X_, 1) * mean_' * mean_\n    end\n    return Sw, Sb \n\n\nend\nfunction transform_(model::LDA, X::Matrix, y::Vector)\n    Sw, Sb = calc_Sw_Sb(model, X, y)\n\n    if model.method == \"svd\"\n        U, S, V = svd(Sw)\n        S = diagm(S)\n        Sw_inverse = V * pinv(S) * U'\n        A = Sw_inverse * Sb\n    else \n        A = inv(Sw) * Sb\n    end\n\n    eigval, eigvec = eig(A)\n    eigval = eigval[1:model.n_components]\n    eigvec = eigvec[:, 1:model.n_components]\n    X_transformed = X * eigvec\n    model.w = eigvec[:,1]\n\n    return X_transformed\n\nend\n\n\nfunction plot_in_2d(model::LDA, X::Matrix, y::Vector)\n    X_transformed = transform_(model, X, y)\n    X_transformed = convert(Array{Real,2}, X_transformed)\n    x1 = X_transformed[:, 1]\n    x2 = X_transformed[:, 2]\n    df = DataFrame(x = x1, y = x2, clu = y)\n    println(\"Computing finished\")\n    println(\"Drawing the plot.....Please Wait(Actually Gadfly is quite slow in drawing the first plot)\")\n    Gadfly.plot(df, x = \"x\", y = \"y\", color = \"clu\", Geom.point)\nend\n\nfunction train!(model::LDA, X::Matrix, y::Vector)\n    transform_(model, X, y)\nend\n\nfunction predict(model::LDA, X::Matrix)\n    temp = X * model.w\n    temp = sign(temp)\n    return temp\nend\n\nfunction test_LDA()\n    X_train, X_test, y_train, y_test = make_cla()\n    model = LDA()\n    train!(model, X_train, y_train)\n    predictions = predict(model, X_test)\n    print(\"classification accuracy\", accuracy(y_test, predictions))\n\n    plot_in_2d(model, X_train, y_train)\nend\n\nfunction test_LDA_reduction()\n    X_train, X_test, y_train, y_test = make_cla()\n    model = LDA()\n    plot_in_2d(model, X_train, y_train)\nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "fdb9ee391070cfa0cb3386bc5c78e24e0f8a5260", "size": 2331, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/supervised_learning/linearDiscriminantAnalysis.jl", "max_stars_repo_name": "zhuzhenping/LightML.jl", "max_stars_repo_head_hexsha": "6be734bbdc9d3b9df33640c26051b6d750540ccd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 428, "max_stars_repo_stars_event_min_datetime": "2017-03-09T12:33:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T19:32:22.000Z", "max_issues_repo_path": "src/supervised_learning/linearDiscriminantAnalysis.jl", "max_issues_repo_name": "afcarl/LightML.jl", "max_issues_repo_head_hexsha": "c6aa43c1bc85250873759f97db561f9be2c89f13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-03-09T11:45:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-27T18:04:38.000Z", "max_forks_repo_path": "src/supervised_learning/linearDiscriminantAnalysis.jl", "max_forks_repo_name": "afcarl/LightML.jl", "max_forks_repo_head_hexsha": "c6aa43c1bc85250873759f97db561f9be2c89f13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 92, "max_forks_repo_forks_event_min_datetime": "2017-03-10T08:48:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T15:56:27.000Z", "avg_line_length": 20.8125, "max_line_length": 104, "alphanum_fraction": 0.6006006006, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7825124754501565}}
{"text": "\"\"\"\n    NormalInverseChisq(μ, σ2, κ, ν)\n\nA Normal-χ^-2 distribution is a conjugate prior for a Normal distribution with\nunknown mean and variance.  It has parameters:\n\n* μ: expected mean\n* σ2 > 0: expected variance\n* κ ≥ 0: mean confidence\n* ν ≥ 0: variance confidence\n\nThe parameters have a natural interpretation when used as a prior for a Normal\ndistribution with unknown mean and variance: μ and σ2 are the expected mean and\nvariance, while κ and ν are the respective degrees of confidence (expressed in\n\"pseudocounts\").  When interpretable parameters are important, this makes it a\nslightly more convenient parametrization of the conjugate prior.\n\nEquivalent to a `NormalInverseGamma` distribution with parameters:\n\n* m0 = μ\n* v0 = 1/κ\n* shape = ν/2\n* scale = νσ2/2\n\nBased on Murphy \"Conjugate Bayesian analysis of the Gaussian distribution\".\n\"\"\"\nstruct NormalInverseChisq{T<:Real} <: ContinuousUnivariateDistribution\n    μ::T\n    σ2::T\n    κ::T\n    ν::T\n\n    function NormalInverseChisq{T}(μ::T, σ2::T, κ::T, ν::T) where T<:Real\n        if ν < 0 || κ < 0 || σ2 ≤ 0\n            throw(ArgumentError(\"Variance and confidence (κ and ν) must all be positive\"))\n        end\n        new{T}(μ, σ2, κ, ν)\n    end\nend\n\nNormalInverseChisq() = NormalInverseChisq{Float64}(0.0, 1.0, 0.0, 0.0)\n\nfunction NormalInverseChisq(μ::Real, σ2::Real, κ::Real, ν::Real)\n    T = promote_type(typeof(μ), typeof(σ2), typeof(κ), typeof(ν))\n    NormalInverseChisq{T}(T(μ), T(σ2), T(κ), T(ν))\nend\n\nBase.convert(::Type{NormalInverseGamma}, d::NormalInverseChisq) =\n    NormalInverseGamma(d.μ, 1/d.κ, d.ν/2, d.ν*d.σ2/2)\n\nBase.convert(::Type{NormalInverseChisq}, d::NormalInverseGamma) =\n    NormalInverseChisq(d.mu, d.scale/d.shape, 1/d.v0, d.shape*2)\n\ninsupport(::Type{NormalInverseChisq}, μ::T, σ2::T) where T<:Real =\n    isfinite(μ) && zero(σ2) <= σ2 < Inf\n\nparams(d::NormalInverseChisq) = d.μ, d.σ2, d.κ, d.ν\n\nfunction pdf(d::NormalInverseChisq, μ::T, σ2::T) where T<:Real\n    Zinv = sqrt(d.κ / 2pi) / gamma(d.ν*0.5) * (d.ν * d.σ2 / 2)^(d.ν*0.5)\n    Zinv * σ2^(-(d.ν+3)*0.5) * exp( (d.ν*d.σ2 + d.κ*(d.μ - μ)^2) / (-2 * σ2))\nend\n\nfunction logpdf(d::NormalInverseChisq, μ::T, σ2::T) where T<:Real\n    logZinv = (log(d.κ) - log(2pi))*0.5 - lgamma(d.ν*0.5) + (log(d.ν) + log(d.σ2) - log(2)) * (d.ν/2)\n    logZinv + log(σ2)*(-(d.ν+3)*0.5) + (d.ν*d.σ2 + d.κ*(d.μ - μ)^2) / (-2 * σ2)\nend\n\nfunction mean(d::NormalInverseChisq)\n    μ = d.μ\n    σ2 = d.ν/(d.ν-2)*d.σ2\n    return μ, σ2\nend\n\nfunction mode(d::NormalInverseChisq)\n    μ = d.μ\n    σ2 = d.ν*d.σ2/(d.ν + 3)\n    return μ, σ2\nend\n\nrand(d::NormalInverseChisq) = rand(convert(NormalInverseGamma, d))\n", "meta": {"hexsha": "8931bfe5923719f045ae227694d3195493eafd04", "size": 2623, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/normalinversechisq.jl", "max_stars_repo_name": "AlexRobson/ConjugatePriors.jl", "max_stars_repo_head_hexsha": "423608902a9a13ccdcd6cfd877b7516092e21443", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2015-07-29T02:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T03:55:56.000Z", "max_issues_repo_path": "src/normalinversechisq.jl", "max_issues_repo_name": "AlexRobson/ConjugatePriors.jl", "max_issues_repo_head_hexsha": "423608902a9a13ccdcd6cfd877b7516092e21443", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2015-04-30T11:00:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T13:12:33.000Z", "max_forks_repo_path": "src/normalinversechisq.jl", "max_forks_repo_name": "AlexRobson/ConjugatePriors.jl", "max_forks_repo_head_hexsha": "423608902a9a13ccdcd6cfd877b7516092e21443", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2015-07-28T06:48:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:14:01.000Z", "avg_line_length": 31.987804878, "max_line_length": 101, "alphanum_fraction": 0.650400305, "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7824267748550402}}
{"text": "type Variance <: ContinuousUnivariateStreamStat\n    m::Float64\n    sum_sqs::Float64\n    v_hat::Float64\n    n::Int\nend\n\nVariance() = Variance(0.0, 0.0, NaN, 0)\n\nfunction update!(stat::Variance, x::Real)\n    stat.n += 1\n\n    if stat.n == 1\n        stat.m = x\n        stat.sum_sqs = 0.0\n        stat.v_hat = NaN\n    else\n        m_new = stat.m + (x - stat.m) / stat.n\n        stat.sum_sqs += (x - stat.m) * (x - m_new)\n        stat.m = m_new\n        stat.v_hat = stat.sum_sqs / (stat.n - 1)\n    end\n\n    return\nend\n\nBase.var(stat::Variance) = stat.v_hat\n\nBase.std(stat::Variance) = sqrt(var(stat))\n\nBase.mean(stat::Variance) = stat.m\n\nstate(stat::Variance) = var(stat)\n\nnobs(stat::Variance) = stat.n\n\nfunction Base.copy(stat::Variance)\n    return Variance(stat.m, stat.sum_sqs, stat.v_hat, stat.n)\nend\n\nfunction Base.merge(a::Variance, b::Variance)\n    n = a.n + b.n\n    m = (a.n / n) * a.m + (b.n / n) * b.m\n    sum_sqs = a.sum_sqs + b.sum_sqs\n    v_hat = (a.n / n) * a.v_hat + (b.n / n) * b.v_hat\n    return Variance(m, sum_sqs, v_hat, n)\nend\n\nfunction Base.empty!(stat::Variance)\n    stat.m = 0.0\n    stat.sum_sqs = 0.0\n    stat.v_hat = NaN\n    stat.n = 0\n    return\nend\n\nfunction Base.show(io::IO, stat::Variance)\n    v = var(stat)\n    s = std(stat)\n    n = nobs(stat)\n    @printf(io, \"Online Variance\\n\")\n    @printf(io, \" * Variance:  %f\\n\", v)\n    @printf(io, \" * Std. Dev.: %f\\n\", v)\n    @printf(io, \" * N:         %d\\n\", n)\n    return\nend", "meta": {"hexsha": "4556bfe17f6fed77e9e43aa818367e7bdf54bb25", "size": 1444, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/var.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StreamStats.jl-1b2943d0-825d-5907-9c5f-04e3ce562884", "max_stars_repo_head_hexsha": "63912dd90fac47151ad054d89e9668cd11911efa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 52, "max_stars_repo_stars_event_min_datetime": "2015-02-07T22:14:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T14:12:56.000Z", "max_issues_repo_path": "src/var.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StreamStats.jl-1b2943d0-825d-5907-9c5f-04e3ce562884", "max_issues_repo_head_hexsha": "63912dd90fac47151ad054d89e9668cd11911efa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2015-02-07T22:19:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:29:52.000Z", "max_forks_repo_path": "src/var.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StreamStats.jl-1b2943d0-825d-5907-9c5f-04e3ce562884", "max_forks_repo_head_hexsha": "63912dd90fac47151ad054d89e9668cd11911efa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2015-02-09T18:52:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-25T22:12:00.000Z", "avg_line_length": 21.8787878788, "max_line_length": 61, "alphanum_fraction": 0.5699445983, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7824267658330601}}
{"text": "# ------------------------------------------------------------\n# Reconstruction of impulse responses, i.e., a single coefficient in the Haar \n# basis from equidistant frequency samples\n\n\n# ------------------------------------------------------------\n# Reconstruction of scaling function\n\n# Input: \n# M: The number of frequency samples\n# epsislon: The distance between two consecutive samples\n# N: The number of wavelet coefficients recovered\n\nM = 8\nepsilon = 0.25\nJ = floor(Int, log2(M))\n\n# Sampling points\nxi = [-M:M;]*epsilon\n\n# Change of basis matrix\nT = freq2Haar(xi, J)\n\n# Fourier observations\nb = FourHaarScaling(xi, J, 3)\n\n# Scaling function coefficients: 1 in the 4th entry, 0 elsewhere\ny = pinv(T)*b\n\n\n# ------------------------------------------------------------\n# Reconstruction of wavelet function\n\nJ2 = [0:2;]\n\n# Change of basis matrix\nT2 = freq2Haar(xi, J2)\n\n# Fourier observations\nb2 = FourHaarWavelet(xi, 2, 1)\n#b2 = FourHaarScaling(xi, 1, 0)\n\n# Wavelet coefficients: 1 in the 5th entry, 0 elsewhere\ny2 = pinv(T2)*b2\n\n", "meta": {"hexsha": "9e0915fe992ae0239450b8f9ac95939a238c0e80", "size": 1035, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/impulse.jl", "max_stars_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_stars_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/impulse.jl", "max_issues_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_issues_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/impulse.jl", "max_forks_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_forks_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5, "max_line_length": 78, "alphanum_fraction": 0.5903381643, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688146, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7824210661244085}}
{"text": "using OrdinaryDiffEq, DifferentialEquations\n\ntspan = (0.0, 200.0)\n\n\"\"\"\nRossler system with chaotic parameter values\n\"\"\"\nfunction rossler_system(du, u, p, t;\n                     U_func_time=U_func_time_trivial,\n                     U_func_space=U_func_space_trivial)\n    a, b, c = p\n    x, y, z = u\n\n    Ft = U_func_time(t)\n    Fs = U_func_space(u)\n\n    du[1] = -y - z\n    du[2] = x + a*y\n    du[3] = b + x*z - c*z\n    du .+= Ft .+ Fs\nend\n\n# Generate data\np = [0.1, 0.1, 14]\nu0 = [1.0, 1.0, 0.0]\nts = range(tspan[1], tspan[2], length=5000)\n\nfunction solve_rossler_system(;U_func_time=U_func_time_trivial,\n                              U_func_space=U_func_space_trivial)\n    prob = ODEProblem((du, u, p, t)->rossler_system(du, u, p, t,\n                                U_func_time=U_func_time,\n                                U_func_space=U_func_space),\n                    u0, tspan, p)\n    sol = solve(prob, Tsit5(), saveat=ts);\n    return Array(sol)\nend\n\n# True model in SINDy syntax\n#     x y z c xx xy xz yy yz zz\n A = [[0 -1 -1 0   0 0 0 0 0 0];\n      [1 0.1 0 0   0 0 0 0 0 0];\n      [0 0 -14 0.1 0 0 1 0 0 0]]\nn = size(A, 1)\nsindy_library = Dict(\n    \"cross_terms\"=>2,\n    \"constant\"=>nothing\n);\ncore_dyn_true = sindyModel(ts, A,\n                            convert_string2function(sindy_library),\n                            [\"x\", \"y\", \"z\"])\n\n# Actually export\nexport ts, solve_rossler_system, rossler_system, core_dyn_true\n", "meta": {"hexsha": "ac08e57890250c19b3dd9af92251eb9ba4eac66c", "size": 1431, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example_rossler.jl", "max_stars_repo_name": "Charles-Fieseler/Learn_Control_Signals", "max_stars_repo_head_hexsha": "987a3775f4f75080c23d631832dd6963e7be078a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-02T15:05:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-02T15:05:34.000Z", "max_issues_repo_path": "examples/example_rossler.jl", "max_issues_repo_name": "Charles-Fieseler/Learn_Control_Signals", "max_issues_repo_head_hexsha": "987a3775f4f75080c23d631832dd6963e7be078a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/example_rossler.jl", "max_forks_repo_name": "Charles-Fieseler/Learn_Control_Signals", "max_forks_repo_head_hexsha": "987a3775f4f75080c23d631832dd6963e7be078a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5, "max_line_length": 67, "alphanum_fraction": 0.5457721873, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.8688267830311354, "lm_q1q2_score": 0.782404406374099}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     text_representation:\n#       extension: .jl\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.5.0\n#   kernelspec:\n#     display_name: Julia 1.4.2\n#     language: julia\n#     name: julia-1.4\n# ---\n\n# # Linear programming using Julia\n\n# - Let's consider a function of two variables $f=f(x,y)$ defined by\n#     \n# $$\n#     f(x,y) = 5x + 3y.\n# $$\n#\n# - We would like find $(x,y)=(\\hat{x}, \\hat{y})$ that maximize the value of f(x,y) with the following contstraits, namely:\n#\n# $$\n# \\begin{aligned}\n# \\text{maximize} &\\ f(x,y) \\\\\n# \\text{subject to}:&\\ 0\\leq x \\leq 2, \\\\\n#                   &\\ 0\\leq y \\leq 30, \\\\\n#                   &\\ 5x + 3y \\leq 3.\n# \\end{aligned}\n# $$\n#\n# - Can we solve this problem using Julia ? Let's find out.\n\n# - JuMP is a domain-specific modeling language for mathematical optimization embedded in Julia.\n# - Tulip is an open-source interior-point solver for linear optimization, written in pure Julia.\n\n# ## Load Packages\n\nusing JuMP\nimport Tulip\nusing LazySets\nusing Plots\nusing LaTeXStrings\nusing Colors\n\n# Models are created with the Model function. The following example adopts `Tulip` as a solver. Note that the version of JuMP should be $\\geq 0.21$\n\n]st JuMP\n\nmodel = Model(Tulip.Optimizer)\n\n# The following commands will create two variables, `x` and `y`, with both lower and upper bounds.\n\nxmin, xmax = 0, 2\nymin, ymax = 0, 30\n# you can use `≤` instead of `<=`\n@variable(model, xmin ≤ x ≤ xmax)\n@variable(model, ymin ≤ y ≤ ymax);\n\n# Next we'll set our objective. Note again the model, so we know which model's objective we are setting! The objective sense, `Max` or `Min`, should be provided as the second argument. Note also that we don't have a multiplication * symbol between 5 and our variable `x` - Julia is smart enough to not need it! \n\nf(x,y)=5x+3y\n@objective(model, Max, 5x+3y)\n\n# Adding constraints is a lot like setting the objective. Here we create a less-than-or-equal-to constraint using `<=`, but we can also create equality constraints using `==` and greater-than-or-equal-to constraints with `>=`\n\n@constraint(model, con, 1x + 5y <= 3)\n\n# ## Summarize model\n\n# Let's see the summary of our `model`. The result should be equivalent to the condition:\n#\n# $$\n# \\begin{aligned}\n# \\text{maximize} &\\ f(x,y) \\\\\n# \\text{subject to}:&\\ 0\\leq x \\leq 2, \\\\\n#                   &\\ 0\\leq y \\leq 30, \\\\\n#                   &\\ 5x + 3y \\leq 3.\n# \\end{aligned}\n# $$\n\nmodel\n\n# - It's time to solve the model using `JuMP.optimize!`:\n\noptimize!(model)\n\n# Done! \n\n# ## Output the result\n\n# We can access the solution via `objective_value` and `value` function.\n\nx̂ = value(x)\nŷ = value(y)\n@assert f̂ = objective_value(model) ≈ f(x̂, ŷ)\n@show x̂, ŷ\n\n# # Visualize result\n\n# - Let's visualize the constraint $x+5y\\leq 3$. It can be written as $\\langle[1,5],[x,y]\\rangle\\leq 3$ where $\\langle\\bullet,\\bullet\\rangle$ stands for inner product of 2-dimensional Euclidian space. LazySets provides a recipe that visualize the half plane of the form $\\langle a,x\\rangle \\leq b$ via `LazySets.HalfSpace(a,b)`.\n# - Note that the version of LazySets should be >= 0.35\n\np = plot(xlims=[xmin, xmax], ylims=[ymin, ymax])\nhs = HalfSpace([1.,5.], 3.)\np = plot!(p, hs)\nhp = Hyperplane([1.,5.], 3.)\np = plot!(p, hp,color=:red)\n\n# Where is the solution, say, $(\\hat{x},\\hat{y})$ ?\n\nscatter!(p, [x̂], [ŷ])\n\n# # Linear programming with multiple constraits\n\n# - Again, let's consider a function of two variables $f(x,y)=5x+3y$. \n# - We would like find $(x,y)=(\\hat{x}, \\hat{y})$ that maximize the value of $f(x,y)$ with the following multiple linear contstraits, namely:\n#\n# $$\n# \\begin{aligned}\n# \\text{maximize} &\\ f(x,y)=3x+5y, \\\\\n# \\text{subject to}:&\\ \n#     \\begin{bmatrix}\n#         2 & 2 \\\\\n#         2 & -4 \\\\\n#         -2 & 1 \\\\\n#         0 & -1 \\\\\n#         0 & 1\n#     \\end{bmatrix}\n#     \\begin{bmatrix} x \\\\ y \\end{bmatrix}\n#     \\leq \n#     \\begin{bmatrix}\n#         33 \\\\\n#         8 \\\\\n#         -5 \\\\\n#         -1 \\\\\n#         8\n#     \\end{bmatrix}.\n# \\end{aligned}\n# $$\n#\n# - This condition is taken from [MML book](https://mml-book.github.io/) p240 Example 7.5. Note that the original example has a typo. See https://github.com/mml-book/mml-book.github.io/issues/547\n# - Can we solve this problem using Julia ? Of course.\n\n# ## Define model and constraits\n\n# +\nf(x,y)=5x+3y\nmodel = Model(Tulip.Optimizer)\n\n@variable(model, x)\n@variable(model, y)\n\n@objective(model, Max, f(x,y))\n\nX=Float64[\n    2   2\n    2  -4\n    -2  1\n    0  -1\n    0   1\n]\n\nbs = Float64[\n    33 \n    8\n    -5 # MML book has typo. I've fixed from 5 to -5\n    -1\n    8\n]\n\n@constraint(model, con, X * [x,y] .≤ bs)\n# -\n\n# ## Optimize model\n\noptimize!(model)\n\nf̂=objective_value(model)\nx̂=value(x)\nŷ=value(y)\n@show x̂, ŷ\n\n# ## Visualize result\n\n# +\np = plot(xlim=[0,16], ylim=[0,10], aspect_ratio=:equal, ticks=0:2:16)\nhs = HalfSpace{Float64, Vector{Float64}}[]\nhp = Hyperplane{Float64, Vector{Float64}}[]\n\ncs = distinguishable_colors(length(bs))\nfor (i, b) in zip(1:size(X)[1], bs)\n    push!(hs, HalfSpace(X[i, 1:2], b))\n    push!(hp, Hyperplane(X[i,1:2], b))\nend\n\nph = HPolyhedron(hs)\nplot!(p, convert(HPolytope, ph))\nplot!.(Ref(p), hp)\nscatter!(p, [x̂], [ŷ], label=L\"(\\hat{x}, \\hat{y})\", marker=:star, msize=8)\nxs = 0:0.01:16\nys = 0:0.01:10\ncontour!(p, xs, ys, f)\n# -\n\n# # References:\n#\n# - JuMP quick start: https://jump.dev/JuMP.jl/v0.21.3/quickstart/\n", "meta": {"hexsha": "58beacc263c04cc3c56ebbd29f04a78f68a76245", "size": 5452, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiments/notebook/hop_step_jump.jl", "max_stars_repo_name": "hsugawa8651/MyWorkflow.jl", "max_stars_repo_head_hexsha": "48edcbcc3fd9e425895ef91bea833ef1e5d4c3fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments/notebook/hop_step_jump.jl", "max_issues_repo_name": "hsugawa8651/MyWorkflow.jl", "max_issues_repo_head_hexsha": "48edcbcc3fd9e425895ef91bea833ef1e5d4c3fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-06T12:34:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-06T12:39:46.000Z", "max_forks_repo_path": "experiments/notebook/hop_step_jump.jl", "max_forks_repo_name": "hsugawa8651/MyWorkflow.jl", "max_forks_repo_head_hexsha": "48edcbcc3fd9e425895ef91bea833ef1e5d4c3fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7169811321, "max_line_length": 328, "alphanum_fraction": 0.616104182, "num_tokens": 1848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.8688267762381844, "lm_q1q2_score": 0.7824043979374509}}
{"text": "export G\n\n\"\"\"\n\n    G(p::Integer, q::Integer, r::Integer)\n\nA convenient method to instantiate a Geometric Algebra with `p` positive, `q` negative and `r` zero dimensions.\n\n`q` and `r` defaults to zero if omitted.\n\nThe basis will be named with prefix `e` and indexed starting from 1.\n\nFor example:\n\n```julia\n# Basic \nHyper   = G(1)       # Hyperbolic numbers. \nℂ       = G(0,1)     # Complex numbers.\nDual    = G(0,0,1)   # Dual numbers.\nℍ       = G(0,2)     # Quaternions.\n\n# Clifford\nCl2 =       G(2)     # Clifford algebra for 2D vector space.\nCl3 =       G(3)     # Clifford algebra for 3D vector space.\nSpacetime = G(1,3)   # Clifford algebra for timespace vectors.\n\n# Geometric\nPGA2D = G(2,0,1)     # Projective Euclidean 2D plane. (dual)\nPGA3D = G(3,0,1)     # Projective Euclidean 3D space. (dual)\nCGA2D = G(3,1)       # conformal 2D space. \nCGA3D = G(4,1)       # Conformal 3D space. \n\n# High-Dimensional GA\nDCGA3D = G(6,2)      # Double Conformal 3D Space.\nTCGA3D = G(9,3)      # Tripple Conformal 3D Space.\nDCGSTA = G(4,8)      # Double Conformal Geometric Space Time Algebra.\nQCGA   = G(9,6)      # Quadric Conformal Geometric Algebra.  \n```\n\nTo instantiate a Geometric Algebra with more parameters, use `galgebra.ga.Ga` instead.\n\nFor example:\n\n```julia\nimport SymPy: sympy\nusing GAlgebra\n\nGa = galgebra.ga.Ga\n\ng3d = Ga(\"e*x|y|z\")\n\n(r, th, phi) = coords = sympy.symbols(\"r theta phi\")\ns3d = Ga(\"e_r e_theta e_phi\", g=[1 0 0; 0 r^2 0; 0 0 r^2 * sympy.sin(th)^2], coords=coords, norm=true)\n(er, eth, ephi) = s3d.mv()\n```\n\nPlease also consult the documentation of [GAlgebra](https://github.com/pygae/galgebra).\n\n\"\"\"\nfunction G(p::Integer, q::Integer, r::Integer)\n    total = p + q + r\n    basis = \"e*\" * join([string(i) for i in 1:total], \"|\")\n    metric = [fill(1, p) ; fill(-1, q) ; fill(0, r)]\n    galgebra.ga.Ga(basis, g=metric)\nend\n\nG(p::Integer, q::Integer) = G(p, q, 0)\n\nG(p::Integer) = G(p, 0, 0)\n\n", "meta": {"hexsha": "f1e02bdc4cd2c8389b6ded3d48b918d57160314d", "size": 1913, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ga.jl", "max_stars_repo_name": "pygae/GAlgebra.jl", "max_stars_repo_head_hexsha": "cd091680d669ea98ce04074ecff6c2a194aab89d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2019-05-22T12:14:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T05:28:08.000Z", "max_issues_repo_path": "src/ga.jl", "max_issues_repo_name": "pygae/GAlgebra.jl", "max_issues_repo_head_hexsha": "cd091680d669ea98ce04074ecff6c2a194aab89d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-05-26T12:13:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-20T02:45:51.000Z", "max_forks_repo_path": "src/ga.jl", "max_forks_repo_name": "pygae/GAlgebra.jl", "max_forks_repo_head_hexsha": "cd091680d669ea98ce04074ecff6c2a194aab89d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-06-10T19:12:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T05:28:10.000Z", "avg_line_length": 26.9436619718, "max_line_length": 111, "alphanum_fraction": 0.6257187663, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8688267677469952, "lm_q1q2_score": 0.7824043833327018}}
{"text": "\"\"\"\n    GibbsKernel(; lengthscale)\n\n# Definition\n\nThe Gibbs kernel is non-stationary generalisation of the squared exponential\nkernel. The lengthscale parameter ``l`` becomes a function of\nposition ``l(x)``.\n\nFor a constant function``l(x) = c``, one recovers the standard squared exponential kernel\nwith lengthscale `c`.\n\n```math\nk(x, y; l) = \\\\sqrt{ \\\\left(\\\\frac{2 l(x) l(y)}{l(x)^2 + l(y)^2} \\\\right) }\n\\\\quad \\\\rm{exp} \\\\left( - \\\\frac{(x - y)^2}{l(x)^2 + l(y)^2} \\\\right)\n```\n\n# References\n\nMark N. Gibbs. \"Bayesian Gaussian Processes for Regression and Classication.\" PhD thesis, 1997\n\nChristopher J. Paciorek and Mark J. Schervish. \"Nonstationary Covariance Functions\nfor Gaussian Process Regression\". NeurIPS, 2003\n\nSami Remes, Markus Heinonen, Samuel Kaski. \"Non-Stationary Spectral Kernels\". arXiV:1705.08736, 2017\n\nSami Remes, Markus Heinonen, Samuel Kaski. \"Neural Non-Stationary Spectral Kernel\". arXiv:1811.10978, 2018\n\"\"\"\nstruct GibbsKernel{T} <: Kernel\n    lengthscale::T\nend\n\nGibbsKernel(; lengthscale) = GibbsKernel(lengthscale)\n\nfunction (k::GibbsKernel)(x, y)\n    lengthscale = k.lengthscale\n    lx = lengthscale(x)\n    ly = lengthscale(y)\n    l = invsqrt2 * hypot(lx, ly)\n    kernel = (sqrt(lx * ly) / l) * with_lengthscale(SqExponentialKernel(), l)\n    return kernel(x, y)\nend\n", "meta": {"hexsha": "4ce416f7f88bc0caafe434d5e840aacfc7d9996c", "size": 1299, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/gibbskernel.jl", "max_stars_repo_name": "Crown421/KernelFunctions.jl", "max_stars_repo_head_hexsha": "979a0198193f42111b27a02bfbc3ac6709e166ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 200, "max_stars_repo_stars_event_min_datetime": "2020-04-07T11:28:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:14:13.000Z", "max_issues_repo_path": "src/kernels/gibbskernel.jl", "max_issues_repo_name": "Crown421/KernelFunctions.jl", "max_issues_repo_head_hexsha": "979a0198193f42111b27a02bfbc3ac6709e166ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 324, "max_issues_repo_issues_event_min_datetime": "2020-03-24T16:26:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T07:34:54.000Z", "max_forks_repo_path": "src/kernels/gibbskernel.jl", "max_forks_repo_name": "Crown421/KernelFunctions.jl", "max_forks_repo_head_hexsha": "979a0198193f42111b27a02bfbc3ac6709e166ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2020-03-25T10:25:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T21:19:06.000Z", "avg_line_length": 30.2093023256, "max_line_length": 106, "alphanum_fraction": 0.6997690531, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767972, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7823461582334655}}
{"text": "\"\"\"\n    angle_adjacent(start::Position, mid::Position, stop::Position, explementary::Bool=false, mercator::Bool=false)\n\nFind the angle formed by two adjacent segments defined by 3 points. The result will be the (positive clockwise)\nangle with origin on the `start-mid` segment, or its explementary angle if required.\n\n# Examples\n```jldoctest\njulia> p1 = Point([-35, 55])\nPoint([-35.0, 55.0])\n\njulia> p2 = Point([-34.8, 57.5])\nPoint([-34.8, 57.5])\n\njulia> p3 = Point([-33.4, 59.1])\nPoint([-33.4, 59.1])\n\njulia> angle_adjacent(p1, p2, p3, false, false)\n202.8279033760424\n\njulia> angle_adjacent(p1, p2, p3, true, false) # explementary angle\n157.1720966239576\n```\n\"\"\"\nfunction angle_adjacent(start::Position, mid::Position, stop::Position, explementary::Bool=false, mercator::Bool=false)\n    azimuth1 = bearing_to_azimuth((mercator !== true) ? bearing(start, mid, false) : rhumb_bearing(start, mid))\n    azimuth2 = bearing_to_azimuth((mercator !== true) ? bearing(stop, mid, false) : rhumb_bearing(stop, mid))\n\n    res = abs(azimuth1 - azimuth2)\n\n    if explementary === true\n        return 360 - res\n    end\n\n    return res\nend\n\nangle_adjacent(start::Point, mid::Point, stop::Point, explementary::Bool=false, mercator::Bool=false) = angle_adjacent(start.coordinates, mid.coordinates, stop.coordinates, explementary, mercator)\n", "meta": {"hexsha": "1e8879227f72d7f6b544f82b4ba7aedad6c0f04b", "size": 1323, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lib/Angle.jl", "max_stars_repo_name": "visr/Turf.jl", "max_stars_repo_head_hexsha": "fe3a61fabe6d5b9e7f0197bf1820be25432c467d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2019-07-08T06:51:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T10:28:51.000Z", "max_issues_repo_path": "src/lib/Angle.jl", "max_issues_repo_name": "visr/Turf.jl", "max_issues_repo_head_hexsha": "fe3a61fabe6d5b9e7f0197bf1820be25432c467d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2019-06-20T13:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-17T19:51:03.000Z", "max_forks_repo_path": "src/lib/Angle.jl", "max_forks_repo_name": "visr/Turf.jl", "max_forks_repo_head_hexsha": "fe3a61fabe6d5b9e7f0197bf1820be25432c467d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-08-01T16:58:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-07T02:30:07.000Z", "avg_line_length": 33.9230769231, "max_line_length": 196, "alphanum_fraction": 0.7120181406, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7822776933746749}}
{"text": "module TensorIntegration\n    export make_tensor, tensor_integrate\n    \n    function simpson(a,b,N)\n        if mod(N,2) == 0\n            N += 1\n        end\n        if N > 1\n            xs = collect(range(a, b, length=N))\n            ws = ones(N)\n            ws[2:2:end-1] .= 4.0\n            ws[3:2:end-2] .= 2.0\n            ws = ws*(xs[2]-xs[1])/3.\n        else\n            xs = [(a+b)/2.]\n            ws = [1.] \n        end\n        return xs, ws\n    end\n\n    function tensor_simpson(a,b,N; lowprecision = false)\n        if lowprecision\n            numbertype = Float32\n        else\n            numbertype = Float64\n        end\n        d = length(N)\n        for i = 1:d\n            if mod(N[i],2) == 0\n                N[i] += 1\n            end\n        end\n\n        xs = [zeros(numbertype, N[d]) for i = 1:d] \n        for i in 1:d\n            if N[i] > 1\n                xs[i] = collect(range(a[i], b[i], length = N[i]))\n            else\n                xs[i] = [(a[i]+b[i])/2.]\n            end\n        end\n        ws = [zeros(numbertype, N[d]) for i = 1:d] \n        for i in 1:d\n            if N[i] > 1\n                ws[i] = ones(N[i])\n                ws[i][2:2:end-1] .= 4.0\n                ws[i][3:2:end-2] .= 2.0\n                ws[i] .= ws[i].*(xs[i][2]-xs[i][1])./3.\n            else\n                ws[i] = [1.]\n            end\n        end\n        xmat, w = tensor_integrate(xs, ws, N)\n        return xmat, w\n    end\n\n    function tensor_integrate(xs, ws, N)\n        totN = prod(N)\n        d = length(N)\n        xmat = zeros(eltype(xs[1]), totN, d) \n        wmat = zeros(eltype(xs[1]), totN, d)\n        for i in 1:d\n            repout = Int(totN/prod(N[1:i]))\n            repin = Int(totN/N[i]/repout)\n            xmat[:, i] .= repeat(xs[i], inner=repin, outer=repout)\n            wmat[:, i] .= repeat(ws[i], inner=repin, outer=repout)\n        end\n        w = prod(wmat, dims = 2)\n        return xmat, w\n    end\n\n    function make_tensor(xs, N)\n        totN = prod(N)\n        d = length(N)\n        xmat = zeros(eltype(xs[1]), totN, d) \n        for i in 1:d\n            repout = Int(totN/prod(N[1:i]))\n            repin = Int(totN/N[i]/repout)\n            xmat[:, i] .= repeat(xs[i], inner=repin, outer=repout)\n        end\n        return xmat\n    end\nend\n\n", "meta": {"hexsha": "bf92a278d09d3291ce387cda9c37f4cde5ca2e09", "size": 2262, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TensorIntegration.jl", "max_stars_repo_name": "chrished/TensorIntegration.jl", "max_stars_repo_head_hexsha": "c97a57557d46eed491f2a3acf104fcd02890471b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TensorIntegration.jl", "max_issues_repo_name": "chrished/TensorIntegration.jl", "max_issues_repo_head_hexsha": "c97a57557d46eed491f2a3acf104fcd02890471b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TensorIntegration.jl", "max_forks_repo_name": "chrished/TensorIntegration.jl", "max_forks_repo_head_hexsha": "c97a57557d46eed491f2a3acf104fcd02890471b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6117647059, "max_line_length": 66, "alphanum_fraction": 0.4133510168, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.7822776875072913}}
{"text": "using NumericalMethodsforEngineers, Plots\n\nProjDir = dirname(@(__FILE__))\n\n#\n# Compute all ytildes:\n#\ncd(ProjDir) do\n  include(joinpath(Pkg.dir(\"NumericalMethodsforEngineers\"), \"test\", \"ch07_wrm.jl\")) \n  \n  y_exact(x) = 7/4*(exp(2x)-exp(-2x))/(exp(2)-exp(-2))-3/4*x\n\n  ytildes_1pt = [\n    (x) -> ytilde_1pt_collocation(x) - y_exact(x),\n    (x) -> ytilde_1pt_subdomain(x) - y_exact(x),\n    (x) -> ytilde_1pt_leastsquares(x) - y_exact(x),\n    (x) -> ytilde_1pt_galerkin(x) - y_exact(x)\n  ]\n\n  ytildes_2pt = [\n    (x) -> ytilde_2pt_collocation(x) - y_exact(x),\n    (x) -> ytilde_2pt_subdomain(x) - y_exact(x),\n    (x) -> ytilde_2pt_leastsquares(x) - y_exact(x),\n    (x) -> ytilde_2pt_galerkin(x) - y_exact(x)\n  ]\n\n  labels_1pt = [\"ytilde_1pt_collocation\", \"ytilde_1pt_subdomain\",\n    \"ytilde_1pt_leastsquares\", \"ytilde_1pt_galerkin\"];\n\n  p1 = plot()\n  for (i, f) in enumerate(ytildes_1pt)\n    lab = labels_1pt[i]\n    if i == 1\n      p1 = plot(f, 0, 1, label=lab, ylabel=\"ÿ - y\")\n    else\n      plot!(p1, f, 0, 1, label=lab)\n    end\n  end\n\n  labels_2pt = [\"ytilde_2pt_collocation\", \"ytilde_2pt_subdomain\",\n    \"ytilde_2pt_leastsquares\", \"ytilde_2pt_galerkin\"];\n\n  p2 = plot()\n  for (i, f) in enumerate(ytildes_2pt)\n    lab = labels_2pt[i]\n    if i == 1\n      p2 = plot(f, 0, 1, label=lab, xlabel=\"x\", ylabel=\"ÿ - y\")\n    else\n      plot!(p2, f, 0, 1, label=lab)\n    end\n  end\n\n  p = plot(\n    p1, p2, layout=(2, 1), link=:both, leg=true\n  )\n  savefig(\"Fig.7.14.png\")\n\nend", "meta": {"hexsha": "2523ed6c8f1352674785d273225b35745d7d5881", "size": 1467, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch07/WRM/Fig.7.14.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "examples/ch07/WRM/Fig.7.14.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "examples/ch07/WRM/Fig.7.14.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 25.2931034483, "max_line_length": 84, "alphanum_fraction": 0.6162235855, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7822776818927857}}
{"text": "using Statistics\n\ninclude(\"common.jl\")\n\nexample = \"16,1,2,0,4,2,7,1,2,14\"\n\nget_locations(input::AbstractString) = map(x -> parse(Int64, x), split(input, \",\"))\n\nfuel_cost(locations::AbstractVector{Int64}, x::Real) = sum(abs.(locations .- x))\n\nfunction get_best_cost(locations::AbstractVector{Int64})\n    optimal_loc = Int64(median(locations))\n    return fuel_cost(locations, optimal_loc)\nend\n\nget_ans(input::AbstractString) = get_best_cost(get_locations(input))\n\n@assert get_ans(example) == 37\nget_ans(load_input(7))\n\n# Part 2\n\nfunction fuel_cost2(loc::Int64, x::Real)\n    d = abs(loc - x)\n    return Int(d * (d + 1) / 2)\nend\nfuel_cost2(locations::AbstractVector{Int64}, x::Real) = sum(fuel_cost2.(locations, x))\n\nfunction get_best_cost2(locations::AbstractVector{Int64})\n    # We're likely to be *close* to the mean, so start there and walk (since the objective\n    # is convex).\n    loc = Int64(round(mean(locations)))\n\n    cost(x) = fuel_cost2(locations, x)\n\n    while cost(loc + 1) < cost(loc)\n        loc += 1\n    end\n\n    while cost(loc - 1) < cost(loc)\n        loc -= 1\n    end\n\n    return cost(loc)\nend\n\nget_ans2(input::AbstractString) = get_best_cost2(get_locations(input))\n\n@assert get_ans2(example) == 168\nget_ans2(load_input(7))\n", "meta": {"hexsha": "8703c0114be3ae7a600ceadfaec6dfc1073e07ba", "size": 1240, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day_07.jl", "max_stars_repo_name": "tpgillam/advent_2021", "max_stars_repo_head_hexsha": "f2191d3c9464aa54f72636392f22027e40c52030", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day_07.jl", "max_issues_repo_name": "tpgillam/advent_2021", "max_issues_repo_head_hexsha": "f2191d3c9464aa54f72636392f22027e40c52030", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day_07.jl", "max_forks_repo_name": "tpgillam/advent_2021", "max_forks_repo_head_hexsha": "f2191d3c9464aa54f72636392f22027e40c52030", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3137254902, "max_line_length": 90, "alphanum_fraction": 0.685483871, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7822776799369909}}
{"text": "# TODO Check faster implementations in computational methods for local regression\n# William S. Cleveland & E. Grosse https://link.springer.com/article/10.1007/BF01890836\nfunction ghat(x::Float64;A,b,d=2,q,rho)\n              \n    xv = A[:,d]\n    yv = b\n    ## lambda q\n    n = length(xv)\n    q = min(q,n)\n    xvx = @. abs(xv-x)\n    qidx = sortperm(xvx)[1:q]\n    qdist = abs(xv[last(qidx)]-x)*max(1,q/n)\n\n    ## upsilon\n    w = zeros(n)\n    for wi in qidx\n        aq = abs(xv[wi]-x)/qdist\n        w[wi] = max((1-aq^3)^3,0)\n    end\n    \n    A = @. A*(w*rho)\n    b = @. b*(w*rho)\n    \n    lsq_x = A \\ b\n\n    d == 1 ? [x,1.0]'*lsq_x : [x^2.0,x,1.0]'*lsq_x\n\nend\n\n\n\"\"\"\nPackage: Forecast\n    loess(xv,yv;\n          d=2,\n          q=Int64(round(3/4*length(xv))),\n          rho=repeat([1.0],inner=length(xv)),  \n          predict = xv)\nSmooth a vector of observations using locally weighted regressions.\nAlthough loess can be used to smooth observations for any given number of independent variables, this implementation is univariate. The speed of loess can be greatly increased by using fast aproximations for the linear fitting calculations, however this implementation calculates only exact results.\nThe loess functionality and nomenclature follows the descriptions in:\n\"STL: A Seasonal, Trend Decomposition Procedure Based on Loess\"\nRobert B. Cleveland, William S. Cleveland, Jean E. McRae, and Irma Terpenning.\nJournal of Official Statistics Vol. 6. No. 1, 1990, pp. 3-73 (c) Statistics Sweden.\n# Arguments\n- `xv`: Observations' support.\n- `yv`: Observation values.\n- `d`: Degree of the linear fit, it accepts values 1 or 2.\n- `q`: As q increases loess becomes smoother, when q tends to infinity loess tends to an ordinary least square poynomial fit of degree `d`. It defaults to the rounding of 3/4 of xv's length.\n- `rho`: Weights expressing the reliability of the observations (e.g. if yi had variances sigma^2*ki where ki where known, the rhoi could be 1/ki). It defaults to 1.0.\n- `predict`: Vector containing the real values to be predicted, by default predicts xv.\n# Returns\nThe loess values for the values contained in `predict`.\n# Examples\n```julia-repl\njulia> loess(rand(5), rand(5); predict=rand(10))\n10-element Array{Float64,1}:\n[...]\n```\n\"\"\"\nfunction loess(xv,yv;\n               d=2,\n               q=Int64(round(3/4*length(xv))),\n               rho=repeat([1.0],inner=length(xv)),  \n               predict = xv)\n    \n    @assert (d==1) | (d==2) \"Linear Regression must be of degree 1 or 2\"\n    @assert length(findall(x -> ismissing(x), xv)) == 0  \"xv should not contain missing values\"\n\n    myi = findall(x -> !ismissing(x),yv)\n    xv = xv[myi]\n    yv = yv[myi]\n    rho = rho[myi]\n    \n    res = zeros(length(predict))\n\n    ## Ax = b\n    A = hcat(xv,repeat([1.0],inner=length(xv)))\n    b = yv\n    d == 2 ? A = hcat(xv .^ 2.0, A) : nothing\n\n    for (i,xi) in enumerate(predict)\n        res[i] = ghat(xi;A=A,b=b,d=d,q=q,rho=rho)\n    end\n    res\nend", "meta": {"hexsha": "e70ee5e09991921e230838a5ac2460b7678c236c", "size": 2956, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/loess.jl", "max_stars_repo_name": "guilhermebodin/SeasonalTrendLoess.jl", "max_stars_repo_head_hexsha": "396e04479197b0e0d8947acc3107d2a29e1fa485", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-06-11T19:53:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T14:48:05.000Z", "max_issues_repo_path": "src/loess.jl", "max_issues_repo_name": "guilhermebodin/SeasonalTrendLoess.jl", "max_issues_repo_head_hexsha": "396e04479197b0e0d8947acc3107d2a29e1fa485", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-06-14T03:39:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-29T02:56:17.000Z", "max_forks_repo_path": "src/loess.jl", "max_forks_repo_name": "guilhermebodin/SeasonalTrendLoess.jl", "max_forks_repo_head_hexsha": "396e04479197b0e0d8947acc3107d2a29e1fa485", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7764705882, "max_line_length": 299, "alphanum_fraction": 0.6336265223, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.782277677728318}}
{"text": "doc\"\"\"\n    Gumbel(μ, θ)\n\nThe *Gumbel distribution*  with location `μ` and scale `θ` has probability density function\n\n$f(x; \\mu, \\theta) = \\frac{1}{\\theta} e^{-(z + e^z)},\n\\quad \\text{ with } z = \\frac{x - \\mu}{\\theta}$\n\n```julia\nGumbel()            # Gumbel distribution with zero location and unit scale, i.e. Gumbel(0.0, 1.0)\nGumbel(u)           # Gumbel distribution with location u and unit scale, i.e. Gumbel(u, 1.0)\nGumbel(u, b)        # Gumbel distribution with location u and scale b\n\nparams(d)        # Get the parameters, i.e. (u, b)\nlocation(d)      # Get the location parameter, i.e. u\nscale(d)         # Get the scale parameter, i.e. b\n```\n\nExternal links\n\n* [Gumbel distribution on Wikipedia](http://en.wikipedia.org/wiki/Gumbel_distribution)\n\"\"\"\nimmutable Gumbel <: ContinuousUnivariateDistribution\n    μ::Float64  # location\n    θ::Float64  # scale\n\n    Gumbel(μ::Real, θ::Real) = (@check_args(Gumbel, θ > zero(θ)); new(μ, θ))\n    Gumbel(μ::Real) = new(μ, 1.0)\n    Gumbel() = new(0.0, 1.0)\nend\n\n@distr_support Gumbel -Inf Inf\n\nconst DoubleExponential = Gumbel\n\n\n#### Parameters\n\nlocation(d::Gumbel) = d.μ\nscale(d::Gumbel) = d.θ\nparams(d::Gumbel) = (d.μ, d.θ)\n\n\n#### Statistics\n\nmean(d::Gumbel) = d.μ + d.θ * 0.57721566490153286\n\nmedian(d::Gumbel) = d.μ + d.θ * 0.366512920581664327\n\nmode(d::Gumbel) = d.μ\n\nvar(d::Gumbel) = 1.6449340668482264 * d.θ^2\n\nskewness(d::Gumbel) = 1.13954709940464866\n\nkurtosis(d::Gumbel) = 2.4\n\nentropy(d::Gumbel) = 1.57721566490153286 + log(d.θ)\n\n\n#### Evaluation\n\nzval(d::Gumbel, x::Float64) = (x - d.μ) / d.θ\nxval(d::Gumbel, z::Float64) = x * d.θ + d.μ\n\nfunction pdf(d::Gumbel, x::Float64)\n    z = zval(d, x)\n    exp(-z - exp(-z)) / d.θ\nend\n\nfunction logpdf(d::Gumbel, x::Float64)\n    z = zval(d, x)\n    - (z + exp(-z) + log(d.θ))\nend\n\ncdf(d::Gumbel, x::Float64) = exp(-exp(-zval(d, x)))\nlogcdf(d::Gumbel, x::Float64) = -exp(-zval(d, x))\n\nquantile(d::Gumbel, p::Float64) = d.μ - d.θ * log(-log(p))\n\ngradlogpdf(d::Gumbel, x::Float64) = - (1.0 + exp((d.μ - x) / d.θ)) / d.θ\n\n\n#### Sampling\n\nrand(d::Gumbel) = quantile(d, rand())\n", "meta": {"hexsha": "630845a84c7afb2e4ab08df0aedce8b2950d8898", "size": 2073, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/gumbel.jl", "max_stars_repo_name": "ericproffitt/Distributions.jl", "max_stars_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/gumbel.jl", "max_issues_repo_name": "ericproffitt/Distributions.jl", "max_issues_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/gumbel.jl", "max_forks_repo_name": "ericproffitt/Distributions.jl", "max_forks_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8275862069, "max_line_length": 98, "alphanum_fraction": 0.6131210806, "num_tokens": 818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7822507121746335}}
{"text": "\"\"\"\nCalculate Jacobians for elements\n\n    rs_jacobi(cells, points)\n\nIsosceles right triangle element\n\nX = [x, y] = λ¹V¹ + λ²V² + λ³V³\n\nλs are linear:  \nλ¹ =  -(r+s)/2  \nλ² = (r+1)/2\nλ³ = (s+1)/2\n\nJacobian:  \n[xr xs  \n yr ys]\n\nXᵣ = -V¹/2 + V²/2  \nXₛ = -V¹/2 + V³/2\n\n\"\"\"\nfunction rs_jacobi(cells, points)\n    ncell = size(cells, 1)\n    J = [\n        begin\n            xr, yr = (points[cells[i, 2], 1:2] - points[cells[i, 1], 1:2]) ./ 2\n            xs, ys = (points[cells[i, 3], 1:2] - points[cells[i, 1], 1:2]) ./ 2\n            [xr xs; yr ys]\n        end for i = 1:ncell\n    ]\n\n    return J\nend\n\n\"\"\"\n    rs_jacobi(r, s, vertices)\n\nQuadrilateral element\n\n```\n4       3\n|-------|\n|       |\n|       |\n|-------|\n1       2\n```\n\nX = λ¹V¹ + λ²V² + λ³V³ + λ⁴V⁴\n\nλs are bilinear rectangle shape functions:  \nλ¹ = (r-1)(s-1)/4  \nλ² = (r+1)(1-s)/4  \nλ³ = (r+1)(s+1)/4  \nλ⁴ = (1-r)(s+1)/4\n\nJacobian:  \nXᵣ = (s-1)V¹/4 + (1-s)V²/4 + (s+1)V³/4 - (s+1)V⁴/4  \nXₛ = (r-1)V¹/4 - (r+1)V²/4 + (r+1)V³/4 + (1-r)V⁴/4\n\nUnlike linear simplex elements,\nJ varies from point to point within an element for a general linear quadrilateral.\nAs a special case, the Jacobian matrix is a constant for each element in rectangular mesh.\n\n\"\"\"\nfunction rs_jacobi(r::T, s::T, vertices::T1) where {T<:Real,T1<:AbstractMatrix}\n    xr, yr = @. (s - 1.0) * vertices[1, :] / 4 +\n       (1.0 - s) * vertices[2, :] / 4 +\n       (s + 1.0) * vertices[3, :] / 4 - (s + 1.0) * vertices[4, :] / 4\n    xs, ys = @. (r - 1.0) * vertices[1, :] / 4 - (r + 1.0) * vertices[2, :] / 4 +\n       (r + 1.0) * vertices[3, :] / 4 +\n       (1.0 - r) * vertices[4, :] / 4\n\n    J = [xr xs; yr ys]\n\n    return J\nend\n\nrs_jacobi(r::T, s::T, vertices::T1) where {T<:AbstractVector,T1<:AbstractMatrix} =\n    [rs_jacobi(r[i], s[i], vertices) for i in eachindex(r)]\n\nrs_jacobi(r::T, s::T, vertices::T1) where {T<:AbstractMatrix,T1<:AbstractMatrix} =\n    [rs_jacobi(r[i], s[i], vertices) for i in axes(r, 1), j in axes(s, 2)]\n\nrs_jacobi(r, s, vertices::AbstractArray{T,4}) where {T<:AbstractFloat} = [\n    rs_jacobi(r, s, @view vertices[i, j, :, :]) for i in axes(vertices, 1),\n    j in axes(vertices, 2)\n]\n\n# syntax sugar for inner points with same samplings in x and y\nrs_jacobi(r::T, vertices::T1) where {T<:AbstractVector,T1<:AbstractMatrix} =\n    [rs_jacobi(r[i], r[j], vertices) for i in eachindex(r), j in eachindex(r)]\n\nrs_jacobi(r, vertices::AbstractArray{T,4}) where {T<:AbstractFloat} = [\n    rs_jacobi(r, @view vertices[i, j, :, :]) for i in axes(vertices, 1),\n    j in axes(vertices, 2)\n]\n", "meta": {"hexsha": "b66d399305fa2b545aa383ae51579a0c405c0dda", "size": 2525, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Geometry/geo_jacobi.jl", "max_stars_repo_name": "vavrines/FR.jl", "max_stars_repo_head_hexsha": "0108d769f4f9df7401d5fa3e8d8ca269cabacdd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Geometry/geo_jacobi.jl", "max_issues_repo_name": "vavrines/FR.jl", "max_issues_repo_head_hexsha": "0108d769f4f9df7401d5fa3e8d8ca269cabacdd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Geometry/geo_jacobi.jl", "max_forks_repo_name": "vavrines/FR.jl", "max_forks_repo_head_hexsha": "0108d769f4f9df7401d5fa3e8d8ca269cabacdd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-23T07:06:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T07:06:02.000Z", "avg_line_length": 25.5050505051, "max_line_length": 90, "alphanum_fraction": 0.5584158416, "num_tokens": 1028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7822507049362222}}
{"text": "\"\"\"\n        saw(decisionMat, weights, fns)\n\nApply SAW (Simple Additive Weighting) method for a given matrix and weights.\nThis method also known as WSM (Weighted Sum Model)\n\n# Arguments:\n - `decisionMat::DataFrame`: n × m matrix of objective values for n candidate (or strategy) and m criteria \n - `weights::Array{Float64, 1}`: m-vector of weights that sum up to 1.0. If the sum of weights is not 1.0, it is automatically normalized.\n - `fns::Array{Function, 1}`: m-vector of functions to be applied on the columns. \n\n# Description \nsaw() applies the SAW method to rank n strategies subject to m criteria which are supposed to be \neither maximized or minimized.\n\n# Output \n- `::SawResult`: SawResult object that holds multiple outputs including scores, rankings, and best index.\n\n# Examples\n```julia-repl\njulia> decmat = [4.0  7  3  2  2  2  2;\n                 4.0  4  6  4  4  3  7;\n                 7.0  6  4  2  5  5  3;\n                 3.0  2  5  3  3  2  5;\n                 4.0  2  2  5  5  3  6];\njulia> df = makeDecisionMatrix(decmat)\n5×7 DataFrame\n Row │ Crt1     Crt2     Crt3     Crt4     Crt5     Crt6     Crt7    \n     │ Float64  Float64  Float64  Float64  Float64  Float64  Float64 \n─────┼───────────────────────────────────────────────────────────────\n   1 │     4.0      7.0      3.0      2.0      2.0      2.0      2.0\n   2 │     4.0      4.0      6.0      4.0      4.0      3.0      7.0\n   3 │     7.0      6.0      4.0      2.0      5.0      5.0      3.0\n   4 │     3.0      2.0      5.0      3.0      3.0      2.0      5.0\n   5 │     4.0      2.0      2.0      5.0      5.0      3.0      6.0\n\njulia> fns = convert(Array{Function,1}, [maximum for i in 1:7])\n7-element Array{Function,1}:\n maximum (generic function with 16 methods)\n maximum (generic function with 16 methods)\n maximum (generic function with 16 methods)\n maximum (generic function with 16 methods)\n maximum (generic function with 16 methods)\n maximum (generic function with 16 methods)\n maximum (generic function with 16 methods)\n\njulia> weights = [0.283, 0.162, 0.162, 0.07, 0.085, 0.162, 0.076];\n\njulia> result = saw(df, weights, fns);\n\njulia> result.scores\n5-element Array{Float64,1}:\n 0.5532285714285714\n 0.7134857142857142\n 0.8374285714285714\n 0.5146571428571429\n 0.5793428571428572\n\njulia> result.bestIndex\n3\n```\n\n# References\nAfshari, Alireza, Majid Mojahed, and Rosnah Mohd Yusuff. \"Simple additive weighting approach to \npersonnel selection problem.\" International Journal of Innovation, Management and Technology \n1.5 (2010): 511.\n\"\"\"\nfunction saw(decisionMat::DataFrame, weights::Array{Float64,1}, fns::Array{Function,1})::SawResult\n    \n    n, p = size(decisionMat)\n    \n    normalizedDecisionMat = similar(decisionMat)\n        \n        w = unitize(weights)\n            \n    colminmax = zeros(Float64, p)\n    @inbounds for i in 1:p\n        colminmax[i] = decisionMat[:, i] |> fns[i]\n        if fns[i] == maximum\n            normalizedDecisionMat[:, i] = decisionMat[:, i] ./ colminmax[i] \n        elseif fns[i] == minimum \n            normalizedDecisionMat[:, i] = colminmax[i] ./ decisionMat[:, i]\n        else\n            @error fns[i]\n            error(\"Function not found\")\n        end\n    end\n    \n    scores = w * normalizedDecisionMat |> rowsums\n\n    rankings = scores |> sortperm |> reverse\n    \n    bestIndex = rankings |> first\n    \n    result = SawResult(\n        decisionMat,\n        normalizedDecisionMat,\n        w,\n        scores,\n        rankings,\n        bestIndex\n    )\n\n    return result\nend\n\n\"\"\"\n        saw(setting)\n\nApply SAW (Simple Additive Weighting) method for a given matrix and weights.\nThis method also known as WSM (Weighted Sum Model)\n\n# Arguments:\n - `setting::MCDMSetting`: MCDMSetting object. \n \n# Description \nsaw() applies the SAW method to rank n strategies subject to m criteria which are supposed to be \neither maximized or minimized.\n\n# Output \n- `::SawResult`: SawResult object that holds multiple outputs including scores, rankings, and best index.\n\"\"\"\nfunction saw(setting::MCDMSetting)::SawResult\n    saw(\n        setting.df,\n        setting.weights,\n        setting.fns\n    )\nend \n", "meta": {"hexsha": "04560d5e89d4f8e190139e025cfc7a456c5d73d9", "size": 4123, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/saw.jl", "max_stars_repo_name": "drvinceknight/JMcDM", "max_stars_repo_head_hexsha": "89bec7ead2a7553f9e58fc75f37b5b89a30582fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2021-02-09T17:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T22:21:26.000Z", "max_issues_repo_path": "src/saw.jl", "max_issues_repo_name": "drvinceknight/JMcDM", "max_issues_repo_head_hexsha": "89bec7ead2a7553f9e58fc75f37b5b89a30582fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-02-09T16:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T18:11:34.000Z", "max_forks_repo_path": "src/saw.jl", "max_forks_repo_name": "drvinceknight/JMcDM", "max_forks_repo_head_hexsha": "89bec7ead2a7553f9e58fc75f37b5b89a30582fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2021-02-12T16:01:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:02:44.000Z", "avg_line_length": 31.7153846154, "max_line_length": 138, "alphanum_fraction": 0.6102352656, "num_tokens": 1291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.7822240166092189}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.6\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 7ccb2b9c-1ecd-11eb-205e-11296dd5bb76\nusing Pkg, DrWatson\n\n# ╔═╡ 855951b0-1ecd-11eb-0108-71f29ba2082f\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing StatsBase, Plots\nend\n\n# ╔═╡ 54e90298-1ecd-11eb-01d6-714cdcc0e877\nmd\"## Listing 2.4\"\n\n# ╔═╡ 97360536-1ecd-11eb-36d6-038ba8a75dc5\nfunction proportionFished(gF, sF, n, N, withReplacement = false)\n\t\n    function fishing()\n        fishInPond = [ones(Int64,gF); zeros(Int64,sF)]\n        fishCaught = Int64[]\n\n        for fish in 1:n\n            fished = rand(fishInPond)\n            push!(fishCaught,fished)\n            if withReplacement == false\n                deleteat!(fishInPond, findfirst(x->x==fished, fishInPond))\n            end\n        end\n        sum(fishCaught)\n    end\n\n    simulations = [fishing() for _ in 1:N]\n    proportions = counts(simulations, 0:n)/N\n\n    if withReplacement\n        plot!(0:n, proportions, \n             line=:stem, marker=:circle, c=:blue, ms=6, msw=0,\n             label=\"With replacement\",\n             xlabel=\"n\",\n             ylims=(0, 0.6), ylabel=\"Probability\")\n    else\n        plot!(0:n, proportions, \n            line=:stem, marker=:xcross, c=:red, ms=6, msw=0,\n            label=\"Without replacement\")\n    end\nend\n\n# ╔═╡ f505b35c-1ecd-11eb-1eef-6fe09900d4be\nbegin\n\tN = 10^6\n\tgoldFish, silverFish, n = 3, 4, 3\n\t\n\tp = plot()\n\tproportionFished(goldFish, silverFish, n, N)\n\tproportionFished(goldFish, silverFish, n, N, true)\n\tp\nend\n\n# ╔═╡ f506085a-1ecd-11eb-1e55-db1a82f7bf85\nmd\"## End of listing 2.4\"\n\n# ╔═╡ Cell order:\n# ╟─54e90298-1ecd-11eb-01d6-714cdcc0e877\n# ╠═7ccb2b9c-1ecd-11eb-205e-11296dd5bb76\n# ╠═855951b0-1ecd-11eb-0108-71f29ba2082f\n# ╠═97360536-1ecd-11eb-36d6-038ba8a75dc5\n# ╠═f505b35c-1ecd-11eb-1eef-6fe09900d4be\n# ╟─f506085a-1ecd-11eb-1e55-db1a82f7bf85\n", "meta": {"hexsha": "f20ec44d250d1449953351807a0eb9640670886a", "size": 1856, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/02/listing2.04.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/02/listing2.04.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/02/listing2.04.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.4246575342, "max_line_length": 74, "alphanum_fraction": 0.640625, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898229217591, "lm_q2_score": 0.863391595913457, "lm_q1q2_score": 0.7822239990937679}}
{"text": "using LinearAlgebra, Random\n\n\"\"\"\n    generate_procrustes_data(m, n, d, σ=0.1, T=Float64)\n\nGenerate random (generalized) Procrustes data.\n\n# Input\n- `m :: Integer`: number of images.\n- `n :: Integer`: number of image landmarks.\n- `d :: Integer`: dimension of image (landmark points).\n- `σ :: Number = 0.1`: noise level adding to each rotated image.\n- `T :: DataType = Float64`: data type.\n\n# Output\n- `A :: Vector{Matrix{T}}`: `m` rotated images.\n- `S :: Matrix{Matrix{T}}`: matrix of `S[i, j]` for OTSM problem.\n- `Ā :: Matrix{T}`: the true/center image.\n- `A_manopt :: Array{T, 3}`: 3D array of data suitable for Manopt software.\n\"\"\"\nfunction generate_procrustes_data(\n    m :: Integer, \n    n :: Integer,\n    d :: Integer, \n    σ :: Number   = 0.1, \n    T :: DataType = Float64\n    )\n    # true center image\n    Ā = randn(T, n, d)\n    # randomly rotated images\n    A = Vector{Matrix{T}}(undef, m)\n    for k in 1:m\n        # Haar measure (uniform) on O(n)\n        # M with iid std normal entries\n        # M = QR\n        Q, R = qr!(randn(T, d, d))\n        O = Matrix(Q)\n        # In Julia, diagonal entries of R not necessarily positive\n        for j in 1:d\n            R[j, j] < 0 && (O[:, j] *= -1)\n        end\n        # now O is uniform on O(n), not on SO(n)\n        # if det(O)=-1 (reflection), swap the first two columns\n        det(O) < 0 && (O[:, [1, 2]] = O[:, [2, 1]])\n        # rotate each point (row) in A\n        A[k] = Ā * transpose(O) + σ * randn(T, n, d)\n    end\n    # set S[i, j]\n    S = [A[i]'A[j] for i in 1:m, j in 1:m]\n    for i in 1:m\n        fill!(S[i, i], 0)\n    end\n    A_manopt = Array{T, 3}(undef, d, n, m)\n    for k in 1:m\n        A_manopt[:, :, k] = transpose(A[k])\n    end\n    A, S, Ā, A_manopt\nend\n", "meta": {"hexsha": "e04f8aedb91dfbae951addd58cee957df73c2802", "size": 1729, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/generate_data.jl", "max_stars_repo_name": "Hua-Zhou/OTSM.jl", "max_stars_repo_head_hexsha": "72fa5d55dbfe2c7cbd4a6bf80091fefbeb078aae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-09T05:27:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-14T01:26:22.000Z", "max_issues_repo_path": "src/generate_data.jl", "max_issues_repo_name": "Hua-Zhou/OTSM.jl", "max_issues_repo_head_hexsha": "72fa5d55dbfe2c7cbd4a6bf80091fefbeb078aae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-06-13T16:03:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-15T16:40:49.000Z", "max_forks_repo_path": "src/generate_data.jl", "max_forks_repo_name": "Hua-Zhou/OTSM.jl", "max_forks_repo_head_hexsha": "72fa5d55dbfe2c7cbd4a6bf80091fefbeb078aae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-13T15:33:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-13T15:33:34.000Z", "avg_line_length": 29.3050847458, "max_line_length": 75, "alphanum_fraction": 0.5407750145, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7821807104501072}}
{"text": "\n\"\"\"\n    simpsons_rule(x::Vector, y::Vector)\n\nNumerical integration via Simpson's rule.\n\nLengths of vectors must be equal to each other, and be odd (to have an even number of intervals).\nValues in `x` represent abcissa values, while `y` are the integrand counterparts.\n\"\"\"\nfunction simpsons_rule(x::Vector, y::Vector)\n    n = length(y)-1\n    n % 2 == 0 || error(\"`y` length (number of intervals) must be odd\")\n    length(x)-1 == n || error(\"`x` and `y` length must be equal\")\n    h = (x[end]-x[1])/n\n    @inbounds @views s = sum(y[1:2:n] .+ 4y[2:2:n] .+ y[3:2:n+1])\n    return h/3 * s\nend\n\n\n\"\"\"\n    trapezoidal_rule(x::Vector, y::Vector)\n\nNumerical integration via the Trapezoidal rule.\n\nLengths of vectors must be equal to each other.\nValues in `x` represent equally-spaced abcissa values, while `y` are the integrand counterparts.\n\"\"\"\nfunction trapezoidal_rule(x::Vector, y::Vector)\n    return (x[2] - x[1]) * ( sum(y) - (y[1] + y[end])/2 )\nend\n\n\n\"\"\"\n    trapezoidal(fun::Function, n, flim...)\n\nApplies the `trapezoidal_rule` using `n` points over the frequency intervals specified by `flim...`.\n\"\"\"\nfunction trapezoidal(fun::Function, n, flim...)\n    ii = 0.0\n    for i in 2:length(flim)\n        xi = collect(range(flim[i-1], stop=flim[i], length=n))\n        yi = fun.(xi)\n        ii += trapezoidal_rule(xi, yi)\n    end\n    return ii\nend\n\n\n\"\"\"\n    gauss_interval(integrand::Function, n, fmin, fmax)\n\nComputes Gauss-Legendre integration using `n` nodes and weights over the intervals `[fmin,fmax]`.\n\"\"\"\nfunction gauss_interval(integrand::Function, n, fmin, fmax)\n    xi, wi = gausslegendre(n)\n    ifi = @. integrand( (fmax-fmin)/2 * xi + (fmin+fmax)/2 )\n    return (fmax-fmin)/2 * dot( wi, ifi )\nend\n\n\n\"\"\"\n    gauss_intervals(fun::Function, n, flim...)\n\nComputes Gauss-Legendre integration using `n` nodes and weights of the intervals specified in `flim...`.\n\"\"\"\nfunction gauss_intervals(fun::Function, n, flim...)\n    xi, wi = gausslegendre(n)\n    ii = 0.0\n    for i in 2:length(flim)\n        ii += (flim[i]-flim[i-1])/2 * dot( wi, fun.( (flim[i]-flim[i-1])/2 * xi .+ (flim[i]+flim[i-1])/2 ) )\n    end\n    return ii\nend\n", "meta": {"hexsha": "5d287bf28366f53c071178153d0e02e9c2b3c5ad", "size": 2123, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rvt/PJSintegration.jl", "max_stars_repo_name": "pstafford/StochasticGroundMotionSimulation.jl", "max_stars_repo_head_hexsha": "963addc75cce6a5d41fa55819a4c80c4214032ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-29T04:08:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T07:55:27.000Z", "max_issues_repo_path": "src/rvt/PJSintegration.jl", "max_issues_repo_name": "pstafford/StochasticGroundMotionSimulation.jl", "max_issues_repo_head_hexsha": "963addc75cce6a5d41fa55819a4c80c4214032ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-10-30T20:02:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T14:16:40.000Z", "max_forks_repo_path": "src/rvt/PJSintegration.jl", "max_forks_repo_name": "pstafford/StochasticGroundMotionSimulation.jl", "max_forks_repo_head_hexsha": "963addc75cce6a5d41fa55819a4c80c4214032ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6891891892, "max_line_length": 108, "alphanum_fraction": 0.6382477626, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7821807075250802}}
{"text": "#= This is one of the famous Interview Problems. You are given \nan array of numbers, treat this array as stone heights. When the rainfalls\nthe water get's filled inside the stone gaps. You need to calculate the amount\nof water which will get trapped inside the stones. \nThe code calculates the answer in the best time complexity.\n=#\n\n## Function\n\nfunction rainWater(n, array)\n    left = zeros(n)\n    left[1] = array[1]\n    for i = 2:n\n        left[i] = max(left[i-1], array[i])\n    end\n    right = zeros(n)\n    right[n] = array[n]\n    for i = n-1:-1:1\n        right[i] = max(right[i+1], array[i])\n    end\n    total = 0\n    for i = 1:n\n        total += min(left[i], right[i]) - array[i]\n    end\n    return total\nend\n\n## Input\n\nprintln(\"Enter the length of array!\")\nn = readline()\nn = parse(Int64, n)\narray = Int64[]\nprintln(\"Enter the array !\")\nfor i = 1:n\n    temp = readline()\n    temp = parse(Int64, temp)\n    push!(array, temp)\nend\n\n## Calling the function\n\nrainWater(n, array)\n\n#=\nSample Test Case:\nInput:\n    n = 3\n    array = 2 0 2\nOutput:\n    2\n\nTime complexity: O ( N )\n=#\n", "meta": {"hexsha": "932ebb62d8b0411a159bb7579e890a09649e8cc8", "size": 1081, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/cp/RainwaterTrapping.jl", "max_stars_repo_name": "TechSpiritSS/NeoAlgo", "max_stars_repo_head_hexsha": "08f559b56081a191db6c6b1339ef37311da9e986", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 897, "max_stars_repo_stars_event_min_datetime": "2020-06-25T00:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:49:31.000Z", "max_issues_repo_path": "Julia/cp/RainwaterTrapping.jl", "max_issues_repo_name": "AnshikaAgrawal5501/NeoAlgo", "max_issues_repo_head_hexsha": "d66d0915d8392c2573ba05d5528e00af52b0b996", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5707, "max_issues_repo_issues_event_min_datetime": "2020-06-24T17:53:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T05:03:15.000Z", "max_forks_repo_path": "Julia/cp/RainwaterTrapping.jl", "max_forks_repo_name": "AnshikaAgrawal5501/NeoAlgo", "max_forks_repo_head_hexsha": "d66d0915d8392c2573ba05d5528e00af52b0b996", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1817, "max_forks_repo_forks_event_min_datetime": "2020-06-25T03:51:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:14:07.000Z", "avg_line_length": 19.6545454545, "max_line_length": 78, "alphanum_fraction": 0.6225716929, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.782180696587592}}
{"text": "\"\"\"\n    NegativeBinomialLikelihood(l=logistic; successes::Real=1)\n\nNegative binomial likelihood with number of successes `successes`.\n\n```math\n    p(k|successes, f) = \\\\frac{\\\\Gamma(k+successes)}{k! \\\\Gamma(successes)} l(f)^successes (1 - l(f))^k\n```\nOn calling, this returns a negative binomial distribution with `successes` successes and \nprobability of success equal to `l(f)`.\n\n!!! warning \"Parameterization\" \n    The parameter `successes` is different from the parameter `r` in the \n    [Wikipedia definition](http://en.wikipedia.org/wiki/Negative_binomial_distribution), \n    which denotes the number of failures.\n    This parametrization is used in order to stay consistent with the parametrization in \n    [Distributions.jl](https://juliastats.org/Distributions.jl/stable/univariate/#Distributions.NegativeBinomial).\n    To use the Wikipedia definition, set `successes` as the number of \"failures\" and\n    change the probability of success from `l(f)` to `1 - l(f)`.\n    Note that with symmetric functions like the [`LogisticLink`](@ref), this corresponds to\n    using `l(-f)`.\n\"\"\"\nstruct NegativeBinomialLikelihood{Tl<:AbstractLink,T<:Real} <: AbstractLikelihood\n    successes::T    # number of successes parameter\n    invlink::Tl\nend\n\nfunction NegativeBinomialLikelihood(l=logistic; successes::Real=1)\n    return NegativeBinomialLikelihood(successes, link(l))\nend\n\n@functor NegativeBinomialLikelihood\n\n(l::NegativeBinomialLikelihood)(f::Real) = NegativeBinomial(l.successes, l.invlink(f))\n\n(l::NegativeBinomialLikelihood)(fs::AbstractVector{<:Real}) = Product(map(l, fs))\n", "meta": {"hexsha": "0b6477da9cbaf10fea2e2854848b77ef5f7c79c4", "size": 1582, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/likelihoods/negativebinomial.jl", "max_stars_repo_name": "simsurace/GPLikelihoods.jl", "max_stars_repo_head_hexsha": "498af318aecb891c1497e1a4a19c26dc7ebd0c47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/likelihoods/negativebinomial.jl", "max_issues_repo_name": "simsurace/GPLikelihoods.jl", "max_issues_repo_head_hexsha": "498af318aecb891c1497e1a4a19c26dc7ebd0c47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/likelihoods/negativebinomial.jl", "max_forks_repo_name": "simsurace/GPLikelihoods.jl", "max_forks_repo_head_hexsha": "498af318aecb891c1497e1a4a19c26dc7ebd0c47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.7567567568, "max_line_length": 114, "alphanum_fraction": 0.7452591656, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576759, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7821806947196273}}
{"text": "module _CoSiEn\nexport CoSiEn\nusing Statistics: std, mean, median\nusing LinearAlgebra: Diagonal, UpperTriangular\n    \"\"\"\n        CoSi, Bm = CoSiEn(Sig) \n\n    Returns the cosine similarity entropy (`CoSi`) and the corresponding\n    global probabilities estimated from the data sequence (`Sig`) using the\n    default parameters:   embedding dimension = 2, time delay = 1, \n    angular threshold = .1,  logarithm = base 2,\n\n        CoSi, Bm = CoSiEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Real=.1, Logx::Real=2, Norm::Int=0)\n\n    Returns the cosine similarity entropy (`CoSi`) estimated from the data\n    sequence (`Sig`) using the specified 'keyword' arguments:\n\n    # Arguments:\n    `m`     - Embedding Dimension, an integer > 1   \\n\n    `tau`   - Time Delay, a positive integer    \\n\n    `r`     - Angular threshold, a value in range [0 < r < 1]   \\n\n    `Logx`  - Logarithm base, a positive scalar (enter 0 for natural log) \\n\n    `Norm`  - Normalisation of `Sig`, one of the following integers:    \\n\n            [0]  no normalisation - default\n            [1]  normalises `Sig` by removing median(`Sig`)\n            [2]  normalises `Sig` by removing mean(`Sig`)\n            [3]  normalises `Sig` w.r.t. SD(`Sig`)\n            [4]  normalises `Sig` values to range [-1 1]\n\n    # See also `PhasEn`, `SlopEn`, `GridEn`, `MSEn`, `cMSEn`\n    \n    # References:\n        [1] Theerasak Chanwimalueang and Danilo Mandic,\n            \"Cosine similarity entropy: Self-correlation-based complexity\n            analysis of dynamical systems.\"\n            Entropy \n            19.12 (2017): 652.\n\n \n    \"\"\"\n    function CoSiEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, \n        r::Real=.1, Logx::Real=2, Norm::Int=0)\n\n    Logx == 0  ? Logx = exp(1) : nothing\n\n    N = size(Sig,1)\n    (N > 10) ? nothing : error(\"Sig:   must be a numeric vector\")\n    (m > 1) ? nothing :  error(\"m:     must be an integer > 1\")\n    (tau>0) ? nothing :  error(\"tau:   must be an integer > 0\")\n    (0<r<1) ? nothing :  error(\"r:     must be a scalar in range [0 1]\")\n    (Logx>0) ? nothing : error(\"Logx:  must be a positive number > 0\")\n    (Norm in collect(0:4)) ? nothing : error(\"Norm:   must be an integer in range [0 4]\")\n\n    if Norm == 1\n        Xi = Sig .- median(Sig);\n    elseif Norm == 2\n        Xi = Sig .- mean(Sig);\n    elseif Norm == 3\n        Xi = (Sig .- mean(Sig))/std(Sig,corrected=false)\n    elseif Norm == 4\n        Xi = (2*(Sig .- minimum(Sig))/(maximum(Sig)-minimum(Sig))) .- 1;\n    else\n        Xi = Sig;\n    end\n\n    Nx = N-((m-1)*tau);\n    Zm = zeros(Nx,m);\n    for n = 1:m\n        Zm[:,n] = Xi[(n-1)*tau+1:Nx+(n-1)*tau]\n    end\n\n    Num = Zm*transpose(Zm); \n    Mag = sqrt.(sum(Diagonal(Num),dims=1))[:]\n    Den = Mag*transpose(Mag)\n    AngDis = round.(acos.(round.(Num./Den,digits=6))/pi,digits=6)\n    if maximum(imag.(AngDis)) < (10^-5)\n        Bm = (sum(UpperTriangular(AngDis .< r))-Nx)/(Nx*(Nx-1)/2)\n    else\n        Bm = (sum(UpperTriangular(real.(AngDis) .< r))-Nx)/(Nx*(Nx-1)/2)\n        @warn(\"Complex values ignored.\")\n    end\n    if Bm == 1 || Bm == 0\n        CoSi = 0\n    else\n        CoSi = -(Bm*log(Logx, Bm)) - ((1-Bm)*log(Logx, 1-Bm))\n    end\n\n    return CoSi, Bm\n    end\n\nend\n\n\"\"\"\nCopyright 2021 Matthew W. Flood, EntropyHub\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nFor Terms of Use see https://github.com/MattWillFlood/EntropyHub\n\"\"\"", "meta": {"hexsha": "60e718c15f09a11b263c8dc522323146744d37e9", "size": 3874, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/_CoSiEn.jl", "max_stars_repo_name": "MattWillFlood/EntropyHub.jl", "max_stars_repo_head_hexsha": "d681c7fad3dbddaa708391b0afef1495c7dde20d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-06-19T19:20:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T16:13:41.000Z", "max_issues_repo_path": "src/_CoSiEn.jl", "max_issues_repo_name": "MattWillFlood/EntropyHub.jl", "max_issues_repo_head_hexsha": "d681c7fad3dbddaa708391b0afef1495c7dde20d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-06-16T21:57:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T01:10:46.000Z", "max_forks_repo_path": "src/_CoSiEn.jl", "max_forks_repo_name": "MattWillFlood/EntropyHub.jl", "max_forks_repo_head_hexsha": "d681c7fad3dbddaa708391b0afef1495c7dde20d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-15T05:41:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T05:41:21.000Z", "avg_line_length": 35.5412844037, "max_line_length": 125, "alphanum_fraction": 0.6024780589, "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182844, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7821504398598591}}
{"text": "#= Sigmoid.jl\n\na quick script to perform a sigmoid transformation using the equation: \n\nσ(X) = 1 /(1 + ℯ ^ vX)\n\nfunction:\n    sigmoid(signal;v) \n    \nwhere signal is the input timeseries and the parameter v determines the how shallow / \nsteep the sigmoid curve will be. Smaller values of v flatten the curve\n\nFrom França et al (2018; https://doi.org/10.3389/fphys.2018.01767): \n    The parameter v was chosen based on its effect on the estimated multifractal width for \n    three types of time series: icEEG (NHNN1-channel 1), surrogate EEG (temporally \n    shuffled values of the original time series from NHNN1-channel 1) and a simulated \n    random series (with the same mean and variance), across the range v = [0.1, 2.0] \n    in steps of 0.1. To find the optimal value for the parameter v, we needed to balance \n    the trade-off between the three series in terms of presenting the most distinct Δα \n    values (Appendix Figure E3A in Supplementary Material), while showing minimum \n    distortion on the recording, or maximum correlation with the original time series\n\n=#\n\nfunction sigmoid(signal; v)\n    sigmoid_transform = 1 ./(1 .+ ℯ .^(v .* signal))\n    return sigmoid_transform\nend", "meta": {"hexsha": "bfefa1af0e8d8829dfc2a62341f48d84195eb200", "size": 1192, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "sigmoid.jl", "max_stars_repo_name": "tehrandavis/data_management_tools", "max_stars_repo_head_hexsha": "3c531c78f85f4de3be20dc4ac35696721fe77290", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sigmoid.jl", "max_issues_repo_name": "tehrandavis/data_management_tools", "max_issues_repo_head_hexsha": "3c531c78f85f4de3be20dc4ac35696721fe77290", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sigmoid.jl", "max_forks_repo_name": "tehrandavis/data_management_tools", "max_forks_repo_head_hexsha": "3c531c78f85f4de3be20dc4ac35696721fe77290", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.5714285714, "max_line_length": 91, "alphanum_fraction": 0.7323825503, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341975270266, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7821197008260087}}
{"text": "# coding: utf-8\n\n# In[1]:\n\n\n#fractal is one of the interesting topics in geometry\n#it is usually described by a recursive function\n#voila,here we are!\nusing Plots\n\n\n# In[2]:\n\n\n#create rectangle shape\nrectangle(top_left,top_right,bottom_left,\n        bottom_right)=Shape([(top_left[1],top_left[2]),\n        (top_right[1],top_right[2]),        \n        (bottom_right[1],bottom_right[2]),\n        (bottom_left[1],bottom_left[2])])\n\n\n# In[3]:\n\n\n#compute euclidean distance\nfunction euclidean_distance(point1,point2)\n    return √((point1[1]-point2[1])^2+(point1[2]-point2[2])^2)\nend\n\n\n# In[4]:\n\n\n#simple solution to get coefficients of the equation\nfunction get_line_params(x1,y1,x2,y2)\n    \n    slope=(y1-y2)/(x1-x2)\n    intercept=y1-slope*x1\n    \n    return slope,intercept\n\nend\n\n\n# In[5]:\n\n\n#standard solution to quadratic equation\nfunction solve_quadratic_equation(A,B,C)\n    x1=(-B+√(B^2-4*A*C))/(2*A)\n    x2=(-B-√(B^2-4*A*C))/(2*A)\n    return [x1,x2]\nend\n\n\n# In[6]:\n\n\n#analytic geometry to compute target datapoints\nfunction get_datapoint(pivot,measure,length,direction=\"inner\")\n    \n    #for undefined slope\n    if pivot[1]==measure[1]\n        y1=pivot[2]+length\n        y2=pivot[2]-length\n        x1=pivot[1]\n        x2=pivot[1]\n    \n    #for general cases\n    else\n\n        #get line equation\n        slope,intercept=get_line_params(pivot[1],pivot[2],\n                                   measure[1],measure[2],)\n\n        #solve quadratic equation\n        A=1\n        B=-2*pivot[1]\n        C=pivot[1]^2-length^2/(slope^2+1)\n        x1,x2=solve_quadratic_equation(A,B,C)\n\n        #get y from line equation\n        y1=slope*x1+intercept\n        y2=slope*x2+intercept\n        \n    end\n    \n    if direction==\"inner\"\n        \n        #take the one between pivot and measure points\n        if euclidean_distance((x1,y1),measure)<euclidean_distance((x2,y2),measure)\n            datapoint=(x1,y1)\n        else\n            datapoint=(x2,y2)\n        end\n        \n    else\n        \n        #take the one farther away from measure points\n        if euclidean_distance((x1,y1),measure)>euclidean_distance((x2,y2),measure)\n            datapoint=(x1,y1)\n        else\n            datapoint=(x2,y2)\n        end\n        \n    end\n    \n    return datapoint\n    \nend\n\n\n# In[7]:\n\n\n#recursively plot symmetric pythagorean tree at 45 degree\n# https//larryriddle.agnesscott.org/ifs/pythagorean/pythTree.htm\nfunction pythagorean_tree(top_left,top_right,bottom_left,\n        bottom_right,current_angle,line_len,n)\n    \n    #plot square\n    plot!(rectangle(top_left,top_right,bottom_left,bottom_right))\n    \n    if n==0\n        return\n    else\n                \n        #find mid point\n        #midpoint has to satisfy two conditions\n        #it has to be on the same line as bottom_left and bottom_right \n        #assume this line follows y=kx+b\n        #the midpoint is (x,kx+b)\n        #bottom_left is (α,kα+b),bottom_right is (δ,kδ+b)\n        #the euclidean distance between midpoint and bottom_left should be\n        #half of the euclidean distance between bottom_left and bottom_right\n        #(x-α)**2+(kx+b-kα-b)**2=((α-δ)**2+(kα+b-kδ-b)**2)/4\n        #apart from x,everything else in the equation is constant\n        #this forms a simple quadratic solution to get two roots\n        #one root would be between bottom_left and bottom_right which yields midpoint\n        #and the other would be farther away from bottom_right\n        #this function solves the equation via (-B+(B**2-4*A*C)**0.5)/(2*A)\n        #alternatively,you can use scipy.optimize.root\n        #the caveat is it does not offer both roots\n        #a wrong initial guess could take you to the wrong root\n        bottom_mid=get_datapoint(bottom_left,bottom_right,line_len/2)\n        top_mid=get_datapoint(top_left,top_right,line_len/2)\n        \n        #compute the top point of a triangle\n        #the computation is similar to midpoint\n        #the euclidean distance between triangle_top and top_mid should be\n        #half of the distance between top_mid and bottom_mid\n        triangle_top=get_datapoint(top_mid,bottom_mid,\n                                   line_len/2,\"outer\")\n    \n        #get top left for right square\n        #the computation is similar to midpoint\n        #the euclidean distance between triangle_top and rightsq_topleft \n        #should be the same as the distance between triangle_top and top_left\n        rightsq_topleft=get_datapoint(triangle_top,top_left,\n                                      line_len/(√(2)),\"outer\")\n        \n        #get midpoint of the diagonal between rightsq_topleft and top_right\n        #the computation is similar to midpoint\n        #the euclidean distance between rightsq_diag_mid and rightsq_topleft \n        #should be half of the distance between rightsq_topleft and top_right\n        rightsq_diag_mid=get_datapoint(top_right,rightsq_topleft,line_len/2)\n        rightsq_topright=get_datapoint(rightsq_diag_mid,triangle_top,\n                                       line_len/2,\"outer\")\n        \n        #get top left and right for left square similar to right square\n        leftsq_topleft=get_datapoint(triangle_top,rightsq_topright,\n                                     line_len,\"outer\")\n        leftsq_topright=get_datapoint(triangle_top,top_right,\n                                      line_len/(√(2)),\"outer\")\n        \n        #recursive do the same for left square\n        pythagorean_tree(leftsq_topleft,leftsq_topright,\n                         top_left,triangle_top,current_angle+45,\n                         line_len/(√(2)),n-1)\n        \n        #recursive do the same for right square\n        pythagorean_tree(rightsq_topleft,rightsq_topright,\n                         triangle_top,top_right,current_angle-45,\n                         line_len/(√(2)),n-1)\n        \n    end\n    \nend\n\n\n# In[8]:\n\n\n#initialize\ntop_left=(0,0)\ntop_right=(1,0)\nbottom_left=(0,-1)\nbottom_right=(1,-1)\nn=4\ncurrent_angle=0\nline_len=euclidean_distance(top_left,top_right);\n\n\n# In[9]:\n\n\n#viz\ngr(size=(250,200))\nfig=plot(legend=false,grid=false,axis=false,ticks=false,\n    )\n\npythagorean_tree(top_left,top_right,bottom_left,\n                     bottom_right,current_angle,line_len,n)\nfig\n\n\n", "meta": {"hexsha": "7e1ae3330ea7a0ec1a39360e720e3166514e4618", "size": 6182, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "pythagorean tree.jl", "max_stars_repo_name": "je-suis-tm/recursion-and-dynamic-programming", "max_stars_repo_head_hexsha": "55a6085cd45b73426379ff947d9a842ef7d325bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-03-22T10:31:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:30:17.000Z", "max_issues_repo_path": "pythagorean tree.jl", "max_issues_repo_name": "je-suis-tm/recursion-and-dynamic-programming", "max_issues_repo_head_hexsha": "55a6085cd45b73426379ff947d9a842ef7d325bb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pythagorean tree.jl", "max_forks_repo_name": "je-suis-tm/recursion-and-dynamic-programming", "max_forks_repo_head_hexsha": "55a6085cd45b73426379ff947d9a842ef7d325bb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2019-10-27T12:34:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T13:54:37.000Z", "avg_line_length": 28.3577981651, "max_line_length": 85, "alphanum_fraction": 0.6276285992, "num_tokens": 1574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341975270266, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7821196986999319}}
{"text": "# Energy spectrum of oscillations at a fixed point.\n\nusing FFTW, JLD2, CurveFit, PyPlot\nusing Vlasiator: RE\n\nfile = \"satellites_uniform_sampled.jld2\"\n\n\ndata = JLD2.load(file)\n\nnSatellite = length(data[\"t\"])\nnI, nJ = size(data[\"rho\"])[2:3]\n\nt = data[\"t\"]\n# Select spatial point\ni, j = 5, 5\nvar = data[\"rho\"][:,i,j] \n\ndt = t[2] - t[1] # uniform sample interval [s]\nFs = 1 / dt      # sample frequency, [Hz]\nFn = Fs / 2      # Nyquist frequency, [Hz]\n\n## Frequency calculation\n\nnPoints = length(var)\nnFFT = nPoints\ndf = Fs / nFFT\nfreq_fullrange = -Fn:df:Fn\n\nfreq = freq_fullrange[(nPoints ÷ 2 + 1):end-1]\n\nvar_freq = fft(var)\nvar_power = abs.(fftshift(var_freq))[(nPoints ÷ 2 + 1):end]\n\n# k is the exponential coefficient\na, k = @views power_fit(freq[10:end], var_power[10:end])\n\nfigure(figsize=(6,8))\nloglog(freq, var_power)\naxis(\"scaled\")\n\nmin_power, max_power = extrema(@view var_power[10:end])\nxlim(freq[8], Fs)\nylim(min_power * 0.75, max_power * 2.0)\n\nxlabel(\"Frequency [Hz]\"; fontsize=14)\nylabel(\"Power Density \"; fontsize=14)\ntitle(string(round.(data[\"locations\"][i,j]./RE, digits=1))*\"Re\"; fontsize=14)\n\nloglog(freq[10:end], a.*freq[10:end].^k, label=\"k = $(round(k, digits=1))\")\n\nlegend()", "meta": {"hexsha": "e505ca97dacc490c4e67fcc99e1a965fc83ac58f", "size": 1194, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/demo_energy_spectrum.jl", "max_stars_repo_name": "alhom/Vlasiator.jl", "max_stars_repo_head_hexsha": "615333705b5346522479ab72398f059cb94ab026", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/demo_energy_spectrum.jl", "max_issues_repo_name": "alhom/Vlasiator.jl", "max_issues_repo_head_hexsha": "615333705b5346522479ab72398f059cb94ab026", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/demo_energy_spectrum.jl", "max_forks_repo_name": "alhom/Vlasiator.jl", "max_forks_repo_head_hexsha": "615333705b5346522479ab72398f059cb94ab026", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9615384615, "max_line_length": 77, "alphanum_fraction": 0.6658291457, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7821196964694037}}
{"text": "\nfunction euclidian(x::Vector{T},y::Vector{T}) where T<:Real\n  nsz = length(x)\n  dist = zeros(T,nsz,nsz)\n\n  for i in 1:nsz, j in 1:nsz\n    if i<=j\n      xd = (x[i]-x[j])^2\n      yd = (y[i]-y[j])^2\n      dist[i,j] = dist[j,i] = round(sqrt(xd+yd),RoundNearestTiesUp)\n    end\n  end\n  return dist\nend\n\nfunction manhattan(x::Vector{T},y::Vector{T}) where T<:Real\n  nsz = length(x)\n  dist = zeros(T, nsz, nsz)\n\n  for i in 1:nsz, j in 1:nsz\n    if i<=j\n      xd = abs(x[i] - x[j])\n      yd = abs(y[i] - y[j])\n      dist[i, j] = dist[j, i] = round(xd + yd, RoundNearestTiesUp)\n    end\n  end\n  return dist\nend\n\nfunction max_norm(x::Vector{T},y::Vector{T}) where T<:Real\n  nsz = length(x)\n  dist = zeros(T, nsz, nsz)\n\n  for i in 1:nsz, j in 1:nsz\n    if i<=j\n      xd = abs(x[i] - x[j])\n      yd = abs(y[i] - y[j])\n      dist[i, j] = dist[j, i] = max(round(xd, RoundNearestTiesUp), round(yd, RoundNearestTiesUp))\n    end\n  end\n  return dist\nend\n\nfunction att_euclidian(x::Vector{T},y::Vector{T}) where T<:Real\n  nsz = length(x)\n  dist = zeros(T,nsz,nsz)\n\n  for i in 1:nsz, j in 1:nsz\n    if i<=j\n      xd = (x[i]-x[j])^2\n      yd = (y[i]-y[j])^2\n      dist[i,j] = dist[j,i] = ceil(sqrt((xd+yd)/10.0))\n    end\n  end\n  return dist\nend\n\nfunction ceil_euclidian(x::Vector{T},y::Vector{T}) where T<:Real\n  nsz = length(x)\n  dist = zeros(T,nsz,nsz)\n\n  for i in 1:nsz, j in 1:nsz\n    if i<=j\n      xd = (x[i]-x[j])^2\n      yd = (y[i]-y[j])^2\n      dist[i,j] = dist[j,i] = ceil(sqrt(xd+yd))\n    end\n  end\n  return dist\nend\n\nfunction geo(x::Vector{T},y::Vector{T}) where T<:Real\n  PI = 3.141592\n  RRR = 6378.388\n  nsz = length(x)\n  dist = zeros(T,nsz,nsz)\n  degs = trunc.(hcat(x,y))\n  mins = hcat(x,y).-degs\n  coords = PI.*(degs.+(5.0.*(mins./3.0)))./180.0\n  lat = coords[:,1]\n  lon = coords[:,2]\n\n  for i in 1:nsz, j in 1:nsz\n    if i<=j\n      q1 = cos(lon[i]-lon[j])\n      q2 = cos(lat[i]-lat[j])\n      q3 = cos(lat[i]+lat[j])\n      dij = RRR.*acos(0.5.*((1.0.+q1).*q2.-(1.0.-q1).*q3)).+1.0\n      dist[i,j] = dist[j,i] = floor(dij)\n    end\n  end\n  return dist\nend\n", "meta": {"hexsha": "d542f61b009b1cd042975784eefe930e086e2b54", "size": 2047, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances.jl", "max_stars_repo_name": "chkwon/TSPLIB.jl", "max_stars_repo_head_hexsha": "ddc2d22838f7ea015360cfab8c932672b8e695f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-08-02T13:47:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T04:30:02.000Z", "max_issues_repo_path": "src/distances.jl", "max_issues_repo_name": "matago/TSPLIB.jl", "max_issues_repo_head_hexsha": "bbf7f2e9b56b8f78d97e51abf4c9b20935213bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2018-08-02T13:47:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-19T04:48:55.000Z", "max_forks_repo_path": "src/distances.jl", "max_forks_repo_name": "chkwon/TSPLIB.jl", "max_forks_repo_head_hexsha": "ddc2d22838f7ea015360cfab8c932672b8e695f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-11-15T14:18:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T18:58:40.000Z", "avg_line_length": 21.7765957447, "max_line_length": 97, "alphanum_fraction": 0.5417684416, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422255326288, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7820187994133849}}
{"text": "struct CSTShapeFunction{N,T <: AbstractFloat}\n    bino::NTuple{N,Int}\n    CSTShapeFunction(N::Int, ::Type{T}) where T = new{N,T}(tuple((binomial(N, i) for i in 1:N)...))\nend\n\nstruct CSTClassFunction{N1,N2,T}\n    CSTClassFunction(N1::T, N2::T) where T = new{N1,N2,T}()\nend\n\nshape_f(s::CSTShapeFunction{N,T}, i::Int, x::T) where {N,T} =\nif i == 0\n    (1 - x)^N \nelseif i == N\n    x^N\nelse\n    s.bino[i] * x^i * (1 - x)^(N - i)\nend\n\nshape_d(s::CSTShapeFunction{N,T}, i::Int, x::T) where {N,T} = \nif i == 0 \n    -N * (1 - x)^(N - 1)\nelseif i == N \n    N * x^(N - 1)\nelse\n    s.bino[i] * (i * x^(i - 1) * (1 - x)^(N - i) - (N - i) * x^i * (1 - x)^(N - i - 1))\nend\n\nclass_f(::CSTClassFunction{N1,N2,T},x::T) where {N1,N2,T} = x^N1 * (1 - x)^N2\n\nclass_d(::CSTClassFunction{N1,N2,T},x::T) where {N1,N2,T} = N1 * x^(N1 - 1) * (1 - x)^N2 - N2 * x^N1 * (1 - x)^(N2 - 1)\n\n\nfunction cst_preprocess(xx::AbstractVector{T}, yy::AbstractVector{T}) where T\n    xte = (xx[1] + xx[end]) / 2\n    if yy[end-1] > yy[2]\n        reverse!(xx)\n        reverse!(yy)\n    end\n    imin = argmin(xx)\n    x0 = xx[imin]\n    y0 = yy[imin]\n    cc = xte - x0\n    xu_ = @view(xx[imin:-1:1])\n    yu_ = @view(yy[imin:-1:1])\n    xl_ = @view(xx[imin:end] )\n    yl_ = @view(yy[imin:end] )\n    xu = (xu_ .- x0) ./ cc\n    yu = (yu_ .- y0) ./ cc\n    xl = (xl_ .- x0) ./ cc\n    yl = (yl_ .- y0) ./ cc\n    return xu, yu, xl, yl\nend\n\nfunction cst_matrix(\n    class::CSTClassFunction{N1,N2,T}, \n    shape::CSTShapeFunction{N,T},\n    xu::V, yu::V, xl::V, yl::V)　where {T,V <: AbstractVector{T},N1,N2,N}\n    NP = length(xu) + length(xl) - 2\n    A = zeros(T, NP, 2N + 3)\n    b = vcat(yu[2:end], yl[2:end])\n    ip = 1\n    @inbounds for x in @view xu[2:end]\n        c = class_f(class, x)\n        for i in 1:N\n            A[ip, i] = c * shape_f(shape, i, x) # cstShapeF(N, i, x)\n        end\n        A[ip, 2N + 1] = c * shape_f(shape, 0, x) # a_le\n        A[ip, 2N + 2] = x # y_tu\n        ip += 1\n    end\n    @inbounds for x in @view xl[2:end]\n        c = class_f(class, x)\n        for i in 1:N\n            A[ip, i + N] = c * shape_f(shape, i, x)\n        end\n        A[ip, 2N + 1] = -c * shape_f(shape, 0, x) # -a_le\n        A[ip, 2N + 3] = x # y_tl\n        ip += 1\n    end\n    return A, b\nend\n\nfunction cst_fit(\n    class::CSTClassFunction{N1,N2}, \n    shape::CSTShapeFunction{N,T},\n    xu::AbstractVector{T}, yu::AbstractVector{T},\n    xl::AbstractVector{T}, yl::AbstractVector{T} ) where {T,N,N1,N2}\n    A, b = cst_matrix(class, shape, xu, yu, xl, yl)\n    U, S, V = svd(A)\n    params = V * ((transpose(U) * b) ./ S)\n    au = params[1:N]\n    al = params[N + 1:2N]\n    a0 = params[2N + 1]\n    yu = params[2N + 2]\n    yl = params[2N + 3]\n    return au, al, a0, yu, yl\nend", "meta": {"hexsha": "529223093353ec746d7dbcf608bb01f82308b912", "size": 2714, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CST/utils.jl", "max_stars_repo_name": "xue-cheng/ParametricAirfoils.jl", "max_stars_repo_head_hexsha": "3d7e7d281c310921de593417b02a8b3d054e2bcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-04-09T13:47:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:40:05.000Z", "max_issues_repo_path": "src/CST/utils.jl", "max_issues_repo_name": "xue-cheng/ParametricAirfoils.jl", "max_issues_repo_head_hexsha": "3d7e7d281c310921de593417b02a8b3d054e2bcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-05T06:25:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T08:37:07.000Z", "max_forks_repo_path": "src/CST/utils.jl", "max_forks_repo_name": "xue-cheng/ParametricAirfoils.jl", "max_forks_repo_head_hexsha": "3d7e7d281c310921de593417b02a8b3d054e2bcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:43:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:43:50.000Z", "avg_line_length": 27.9793814433, "max_line_length": 119, "alphanum_fraction": 0.5084745763, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7820187918532945}}
{"text": "#=\r\nMacklemore Problem:\r\n\r\nWe are going to the thrift shop and need 99 cents to buy something. What is the\r\nlightest way to carry 99 cents using US currency?\r\n\r\nThis is a Knapsack problem.\r\n\r\nWe specify that you need at least 99 cents - does the answer change if you need exact change?\r\n=#\r\n\r\nusing JuMP\r\nusing Cbc # Must support integer programming.\r\n\r\nm = Model(solver=CbcSolver())\r\n\r\n# Variables represent how many of each coin we want to carry\r\n@defVar(m, pennies >= 0, Int)\r\n@defVar(m, nickels >= 0, Int)\r\n@defVar(m, dimes >= 0, Int)\r\n@defVar(m, quarters >= 0, Int)\r\n\r\n# We need at least 99 cents\r\n@addConstraint(m, 1 * pennies + 5 * nickels + 10 * dimes + 25 * quarters >= 99)\r\n\r\n# Minimize mass (Grams)\r\n# (source: US Mint)\r\n@setObjective(m, Min, 2.5 * pennies + 5 * nickels + 2.268 * dimes + 5.670 * quarters)\r\n\r\n# Solve\r\nstatus = solve(m)\r\n\r\nprintln(\"Minimum mass: \", getObjectiveValue(m), \" grams\")\r\nprintln(\"using:\")\r\nprintln(round(getValue(pennies)), \" pennies\") # \"round\" to cast as integer\r\nprintln(round(getValue(nickels)), \" nickels\")\r\nprintln(round(getValue(dimes)), \" dimes\")\r\nprintln(round(getValue(quarters)), \" quarters\")\r\n", "meta": {"hexsha": "2389b454701d1fec1ef90a4b1866246ecd46a93a", "size": 1144, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Meetups/2015Berkeley/BerkeleyTalk1/src/macklemore.jl", "max_stars_repo_name": "JuliaQuantum/Resources", "max_stars_repo_head_hexsha": "144b774a3a86992cd0e0838d5c2adc94d012ab14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2015-03-15T23:07:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T00:48:58.000Z", "max_issues_repo_path": "Meetups/2015Berkeley/BerkeleyTalk1/src/macklemore.jl", "max_issues_repo_name": "JuliaQuantum/Resources", "max_issues_repo_head_hexsha": "144b774a3a86992cd0e0838d5c2adc94d012ab14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2015-03-21T21:20:56.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-23T17:56:55.000Z", "max_forks_repo_path": "Meetups/2015Berkeley/BerkeleyTalk1/src/macklemore.jl", "max_forks_repo_name": "JuliaQuantum/Resources", "max_forks_repo_head_hexsha": "144b774a3a86992cd0e0838d5c2adc94d012ab14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-03-21T19:56:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T00:59:23.000Z", "avg_line_length": 29.3333333333, "max_line_length": 94, "alphanum_fraction": 0.6783216783, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9766692277960745, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7820112324220145}}
{"text": "if \"./src\" in LOAD_PATH\n    # print(\"in src\")\nelse\n    dir = \"./src\"\n    push!(LOAD_PATH,dir)        \n    # print(\"not in src\")\nend\n\nmodule aerosolGen\n\nusing Distributions\n\n# \"The Mechanism of Breath Formation\"\n# DOI: 10.1089/jamp.2008.0720\n\n# Particle size distribution for young subjects (b-1-0-f3-m-m)\n# Mean = 1.015056269 μm\n# Variance = 0.457766837 μm\n\n# Determining parameters for log(X)\nmean = 1.015056269e-6\nvar = 0.209550477e-6\nstd = sqrt(var)\n\n# mean = 243900.6582\n# var = 93909632285\n\n# std = 0.457766837e-6\n\n\nmu = log((mean^2)/(sqrt(var + mean^2)))\nsigma = sqrt(log(1+((var)/(mean^2))))\n\n# log_mean = exp(mean + var/2)\n# log_var = (exp(var)-1)*exp(2*mean+var)\n\n# log_mean = log(mean)-0.5*log((std/mean)^2 + 1)\n# log_std = sqrt(log((std/mean)^2 + 1))\n\n# println(log_mean)\n# println(\"\\n\")\n# println(log_std)\n# println(mu)\n# println(\"\\n\")\n# println(sigma)\n\n# println(log_mean + \"\\n\" + log_var)\n\ndistrib0 = Distributions.LogNormal(mu, sigma)\n# distrib0 = Distributions.LogNormal(mean, var)\nrange0 = 0.5e-10:0.5e-9:5e-8\n# range0 = 0.5:0.1:4\n# range0=-0.5e-6:0.2e-6:0.5e-6\ndiscrete0 = pdf(distrib0, range0)\n# discrete1 = cdf(distrib0, range0)\n# discrete0=pdf(distrib0, ) \n\n# mean(distrib0)    \n\n# println(discrete0[1])\nprintln(discrete0)\n# println(discrete1)\n# println(params(distrib0))\n# println(meanlogx(distrib0))\n\nend", "meta": {"hexsha": "1daac6e0e8dfc1de84116eae369012f11bf5a0cd", "size": 1327, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/deprecated/aerosolGen.jl", "max_stars_repo_name": "ryanjosephsulit/CENG0038-Droplet-Distribution-research-project", "max_stars_repo_head_hexsha": "cebf01026019b132e2ed5f3b1712acfbf185b68d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/deprecated/aerosolGen.jl", "max_issues_repo_name": "ryanjosephsulit/CENG0038-Droplet-Distribution-research-project", "max_issues_repo_head_hexsha": "cebf01026019b132e2ed5f3b1712acfbf185b68d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/deprecated/aerosolGen.jl", "max_forks_repo_name": "ryanjosephsulit/CENG0038-Droplet-Distribution-research-project", "max_forks_repo_head_hexsha": "cebf01026019b132e2ed5f3b1712acfbf185b68d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1060606061, "max_line_length": 62, "alphanum_fraction": 0.6601356443, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551535992067, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7819947519140215}}
{"text": "\"\"\"\r\n    flow(xy) -> Float64\r\n\r\nAnalyze hydrogen peroxide position to compute the magnitude of flow\r\n\r\nBy laminar flow, all nonzero flow biases the particle downstream\r\nin the positive x direction.\r\n\"\"\"\r\nfunction flow_arlett(xy::Array{Float64,1})\r\n    y = xy[2]\r\n    if !FLOW_BIAS || y <= WALL_Y || inenz(xy)\r\n        return 0.0\r\n    else\r\n        xdisplacementbias = getspeed(y) * SECONDS_PER_STEP\r\n        return xdisplacementbias\r\n    end\r\nend\r\n\r\n# lengths are in microns\r\nconst V_MAX = 6326.0\r\nconst R = 1270.0\r\n\r\n\"\"\"\r\n    getspeed(y) -> Float64\r\n\r\nCompute the approximate laminar flow bias on the particle; magnitude of flow increases with the y-coordinate\r\n\r\nExcerpt from \\\"Simulating Chemical Cross-Talk in High Density Enzymatic Biosensors\\\" by Sonali Madisetti:\r\n\\\" In the experimental conditions, the probe had a constant flow of water, in which water entered the\r\nsystem at 40 mL/s for 700 seconds through a 0.21 in x 0.1 in pipe and exited at a similar rate. The radius\r\nof the rectangular probe apparatus was around 1270 microns. From Q = v_eff * A, where Q represented the\r\nflow-rate, v_eff was approximately 4217 um/s. For a square pipe, it can be derived that v_eff = (2/3)v_max,\r\nand thus that v_max = 6326 um/s. From there, using the velocity equation\r\n                                    v(r) = v_max * (1 - r^2 / R^2)\r\nwhere r is the y-distance from the center and R is the radius of the pipe. \\\"\r\n\"\"\"\r\nfunction getspeed(y::Float64)\r\n    r = R - y\r\n    return V_MAX * (1 - (r^2) / (R^2))\r\nend\r\n", "meta": {"hexsha": "c5bf2612d3cc30449447482b8a708f51bf75cf9b", "size": 1514, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/arlett/flow_arlett.jl", "max_stars_repo_name": "s-y-wu/HMCResearchRandomWalks", "max_stars_repo_head_hexsha": "a41b9b970bcb86fa5199b5ab964a210aa149e948", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/arlett/flow_arlett.jl", "max_issues_repo_name": "s-y-wu/HMCResearchRandomWalks", "max_issues_repo_head_hexsha": "a41b9b970bcb86fa5199b5ab964a210aa149e948", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/arlett/flow_arlett.jl", "max_forks_repo_name": "s-y-wu/HMCResearchRandomWalks", "max_forks_repo_head_hexsha": "a41b9b970bcb86fa5199b5ab964a210aa149e948", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9268292683, "max_line_length": 109, "alphanum_fraction": 0.677014531, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211323, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7819774150968302}}
{"text": "#Basic function to use\n\n\"\"\"\n    absolute_error(x, x̂)\n\nreturn the Absolute error of x and x̂\n\"\"\"\nabsolute_error(x, x̂) = abs(x .- x̂)\n\n\n\n\n\"\"\"\n    relative_error(x, x̂)\n\nThe relative error between X1 and X2\n\"\"\"\nrelative_error(x, x̂) = abs((x .- x̂) ./ x)\n\n\n\"\"\"\n    ξ(x₀, x)\n\nreturn the number ξ(x) bwteen x₀ and x.\n\"\"\"\n@inline ξ(x₀, x) = rand(1)[1] * (x - x₀)/x + x₀\n\n\n\"\"\"\n    NthDrivative(f::Function, x::Real, n::Int)\n\nreturn the nth derivative value at x\n\"\"\"\n@inline function NthDerivative(f::Function, x::Real, n::Int)\n    if n == 0\n        return f(x)\n    else\n        return ForwardDiff.derivative(x->NthDerivative(f, x, n-1), x)\n    end\nend\n\n\n\n\n\"\"\"\n    TaylorPolynomials(f::Function, x::Real, x₀::Real, n::Int)\n\nreturn the value of nth Taylor Ploynomial at x.\n\"\"\"\n@inline function TaylorPolynomials(f::Function, x::Real, x₀::Real, n::Int)\n    result = []\n    for i in 0:n\n        push!(result, NthDerivative(f, x₀, i)*(x - x₀)^i/factorial(i))\n    end\n    return sum(result)\n\nend\n", "meta": {"hexsha": "af84360b8bd87a228f3585f0154a0b4fb76188c4", "size": 985, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basic.jl", "max_stars_repo_name": "ZhouZhuofei/NumericalAnalysis.jl", "max_stars_repo_head_hexsha": "1e4926d6968fa72cc6ba102ad04052a77044351a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basic.jl", "max_issues_repo_name": "ZhouZhuofei/NumericalAnalysis.jl", "max_issues_repo_head_hexsha": "1e4926d6968fa72cc6ba102ad04052a77044351a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-09-24T17:58:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-11T00:37:24.000Z", "max_forks_repo_path": "src/basic.jl", "max_forks_repo_name": "ZhouZhuofei/NumericalAnalysis.jl", "max_forks_repo_head_hexsha": "1e4926d6968fa72cc6ba102ad04052a77044351a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.9827586207, "max_line_length": 74, "alphanum_fraction": 0.5989847716, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993027, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7819774150711041}}
{"text": "\"\"\"\n\tcorrp(x,y)\nCompute Pearson's correlation coefficient (`r`) and corresponding `p` value with\nnull hypothesis of no correlation (against alternative of a non-zero correlation).\n`p` values (two-tailed) below 0.05 typically indicate that `r` is statistically\nsignificant, see e.g., https://www.medcalc.org/manual/correlation.php\n\n**Example**\n```\nx,y = collect(1.:1:10),collect(0.:10:90);\ny[end] = 80;\nr,p = corrp(x,y);\n```\n\"\"\"\nfunction corrp(x::Vector{Float64},y::Vector{Float64})\n\txi,yi = HypoTest.prepdata(x,y);\n\tn = length(xi);\n\tr = Statistics.cor(xi,yi);\n\tt = HypoTest.tpearval(r,n);\n\treturn r, HypoTest.pvalcorr(t,n)\nend\n\n# t-value for Pearson's correlation coefficient: https://www.danielsoper.com/statcalc/formulas.aspx?id=44\ntpearval(r,n) = r/sqrt((1-r^2)/(n-2));\n\n# two-tailed probability for correlation (=t-distribution)\npvalcorr(t,n) = 2*(1-Distributions.cdf(Distributions.TDist(n-2),t));\n", "meta": {"hexsha": "e1211783ea457cbf91054f8bfbeccae41cbc9434", "size": 902, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/othertest.jl", "max_stars_repo_name": "emenems/HypoTest", "max_stars_repo_head_hexsha": "0cdbecb705825fc8bef718565400796aae44db84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/othertest.jl", "max_issues_repo_name": "emenems/HypoTest", "max_issues_repo_head_hexsha": "0cdbecb705825fc8bef718565400796aae44db84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/othertest.jl", "max_forks_repo_name": "emenems/HypoTest", "max_forks_repo_head_hexsha": "0cdbecb705825fc8bef718565400796aae44db84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2142857143, "max_line_length": 105, "alphanum_fraction": 0.7084257206, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065794, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.7819774057777598}}
{"text": "\"\"\"\nFEniCS tutorial demo program: Poisson equation with Dirichlet conditions.\nTest problem is chosen to give an exact solution at all nodes of the mesh.\n  -Laplace(u) = f    in the unit square\n            u = u_D  on the boundary\n  u = 1 + x^2 + 2y^2 = u_D\n  f = -6\nThis is an extended version of the demo program poisson.py which\nencapsulates the solver as a Python function.\n\"\"\"\nmodule ft12\n\nusing FenicsPy\n\nfunction solver(f, u_D, Nx, Ny, degree=1)\n    \"\"\"\n    Solve -Laplace(u) = f on [0,1] x [0,1] with 2*Nx*Ny Lagrange\n    elements of specified degree and u = u_D (Expresssion) on\n    the boundary.\n    \"\"\"\n\n    # Create mesh and define function space\n    mesh = UnitSquareMesh(Nx, Ny)\n    V = FunctionSpace(mesh, \"P\", degree)\n\n    bc = DirichletBC(V, u_D, \"on_boundary\")\n\n    # Define variational problem\n    u = TrialFunction(V)\n    v = TestFunction(V)\n    a = dot(grad(u), grad(v))*dx\n    L = f*v*dx\n\n    # Compute solution\n    u = FeFunction(V)\n    solve(a == L, u, bc)\n\n    return u\nend\n\nfunction run_solver()\n    \"Run solver to compute and post-process solution\"\n\n    # Set up problem parameters and call solver\n    u_D = Expression(\"1 + x[0]*x[0] + 2*x[1]*x[1]\", degree=2)\n    f = Constant(-6.0)\n    u = solver(f, u_D, 8, 8, 1)\n\n    # Plot solution and mesh\n    #plot(u)\n    #plot(u.function_space().mesh())\n\n    # Save solution to file in VTK format\n    vtkfile = File(\"poisson_solver/solution.pvd\")\n    vtkfile << u\nend\n\nfunction test_solver()\n    \"Test solver by reproducing u = 1 + x^2 + 2y^2\"\n\n    # Set up parameters for testing\n    tol = 1E-10\n    u_D = Expression(\"1 + x[0]*x[0] + 2*x[1]*x[1]\", degree=2)\n    f = Constant(-6.0)\n\n    # Iterate over mesh sizes and degrees\n    for Nxy in [(3, 3), (3, 5), (5, 3), (20, 20)]\n        Nx, Ny = Nxy\n        for degree in [1, 2, 3]\n            println(\"Solving on a 2 x (\", Nx,\" x \", Ny, \") mesh with P\", degree, \" elements.\")\n\n            # Compute solution\n            u = solver(f, u_D, Nx, Ny, degree)\n\n            # Extract the mesh\n            mesh = u.function_space().mesh()\n\n            # Compute maximum error at vertices\n            vertex_values_u_D = u_D.compute_vertex_values(mesh)\n            vertex_values_u  = u.compute_vertex_values(mesh)\n            error_max = max(abs.(vertex_values_u_D - vertex_values_u)...)\n\n            # Check maximum error\n            msg = string(\"error_max = \" , error_max)\n            @assert error_max<tol msg\n        end\n    end\nend\n\nrun_solver()\nprintln(\"------------------\")\ntest_solver()\n\n\nend # module ft12\n", "meta": {"hexsha": "784495792d91b2f80d828f3c5a315c301cfa800c", "size": 2522, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ft12_poisson_solver.jl", "max_stars_repo_name": "chaoskey/FenicsPy.jl", "max_stars_repo_head_hexsha": "18b42f6b193a220702d544560f403a9917adda6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/ft12_poisson_solver.jl", "max_issues_repo_name": "chaoskey/FenicsPy.jl", "max_issues_repo_head_hexsha": "18b42f6b193a220702d544560f403a9917adda6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ft12_poisson_solver.jl", "max_forks_repo_name": "chaoskey/FenicsPy.jl", "max_forks_repo_head_hexsha": "18b42f6b193a220702d544560f403a9917adda6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2708333333, "max_line_length": 94, "alphanum_fraction": 0.594369548, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8558511506439707, "lm_q1q2_score": 0.7819711038800234}}
{"text": "\nusing Polynomials: Poly, polyint\n\n\nstruct LagrangeBasis{T,N} <: PolynomialBasis{T,N}\n    x::Vector{T}\n\n    denom::Vector{T}\n    diffs::Matrix{T}\n    vdminv::Matrix{T}\n\n    function LagrangeBasis{T,N}(x) where {T,N}\n        @assert length(x) == N\n\n        local p::T\n\n        denom = zeros(N)\n        diffs = zeros(N,N)\n\n        for i in eachindex(x)\n            p = 1\n            for j in eachindex(x)\n                diffs[i,j] = x[i] - x[j]\n                if i ≠ j\n                    p *= diffs[i,j]\n                end\n            end\n            denom[i] = 1/p\n        end\n\n        new(x, denom, diffs, vandermonde_matrix_inverse(x))\n    end\nend\n\nfunction LagrangeBasis(x::Vector{T}) where {T}\n    LagrangeBasis{T, length(x)}(x)\nend\n\nnodes(b::LagrangeBasis{T,N})  where {T,N} = b.x\n\nBase.hash(b::LagrangeBasis, h::UInt) = hash(b.c, h)\n\nBase.:(==)(b1::LagrangeBasis, b2::LagrangeBasis) = (b1.x == b2.x)\n\nBase.isequal(b1::LagrangeBasis{T1,N1}, b2::LagrangeBasis{T2,N2}) where {T1,N1,T2,N2} = (T1 == T2 && N1 == N2)\n\n\n\nfunction eval_basis(b::LagrangeBasis{T,N}, j::Int, x::T) where {T,N}\n    local y::T = 1\n\n    for i in 1:nnodes(b)\n        i ≠ j ? y *= (x - b.x[i]) : nothing\n    end\n    y * b.denom[j]\nend\n\n\nfunction deriv_basis(b::LagrangeBasis{T,N}, j::Int, x::T) where {T,N}\n    local y::T = 0\n    local z::T\n\n    for l in 1:nnodes(b)\n        if l ≠ j\n            z = 1 / b.diffs[j,l]\n            for i in 1:nnodes(b)\n                i ≠ j && i ≠ l ? z *= (x - b.x[i]) / b.diffs[j,i] : nothing\n            end\n            y += z\n        end\n    end\n    y\nend\n\nderiv_basis(b::LagrangeBasis, j::Int, i::Int) = deriv_basis(b, j, b.x[i])\n\n\nfunction int_basis(b::LagrangeBasis{T,N}, j::Int, x::T) where {T,N}\n    y = zero(b.x)\n    y[j] = 1\n    lint = polyint(Poly(*(b.vdminv, y)))\n    return lint(x)\nend\n\nint_basis(b::LagrangeBasis, j::Int, i::Int) = int_basis(b, j, b.x[i])\n", "meta": {"hexsha": "c5125145573bd4088b2dd5c5278d3d252bff5f1d", "size": 1879, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basis_functions/lagrange_basis.jl", "max_stars_repo_name": "krystophny/GeometricIntegrators.jl", "max_stars_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-04T11:52:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T11:52:47.000Z", "max_issues_repo_path": "src/basis_functions/lagrange_basis.jl", "max_issues_repo_name": "krystophny/GeometricIntegrators.jl", "max_issues_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basis_functions/lagrange_basis.jl", "max_forks_repo_name": "krystophny/GeometricIntegrators.jl", "max_forks_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8488372093, "max_line_length": 109, "alphanum_fraction": 0.5151676424, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7819710941534398}}
{"text": "using FractionalDiffEq\nusing Plots, LaTeXStrings\nusing MittagLeffler\n\n#Analytical solution\ntarget = []\n\n#MittagLeffler.jl doesn't support array argument\nfor i in 0:0.01:20\n    push!(target, i^1.8*mittleff(1.8,2.8,-i^1.8))\nend\n\ns=\"\\$D^{1.8}y(x)=1-y(x),\\\\ y(0)=0\\$\"\n\n#Numerical solution\nfun(x, y) = 1-y\nprob = FDEProblem(fun, 1.8, 0, 20, 0.01)\nresult=solve(prob, PECE())\ntspan=collect(0:0.01:20)\n\ngr()\n\nplot(tspan, result, title=s, linewidth=5, label=\"Numerical\", legend=:bottomright)\nplot!(tspan, target, lw=3, ls=:dash, label=\"Analytical\")", "meta": {"hexsha": "574a79aa3afc48622db2c0e452cb377b89a05c14", "size": 539, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example.jl", "max_stars_repo_name": "ERIKQQY6/FractionalDiffEq.jl", "max_stars_repo_head_hexsha": "7638f3b9d31e8e1aaaca0b4328b70e4d45b169c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/example.jl", "max_issues_repo_name": "ERIKQQY6/FractionalDiffEq.jl", "max_issues_repo_head_hexsha": "7638f3b9d31e8e1aaaca0b4328b70e4d45b169c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/example.jl", "max_forks_repo_name": "ERIKQQY6/FractionalDiffEq.jl", "max_forks_repo_head_hexsha": "7638f3b9d31e8e1aaaca0b4328b70e4d45b169c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4583333333, "max_line_length": 81, "alphanum_fraction": 0.6864564007, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542887603537, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7819337449573284}}
{"text": "# this is the log-likelihood for the linear model\n# y = x*b+e, with e~N(0,s^2)\n# the parameter theta = [b' s]\n# this file is used for demonstration of MLE, to compare to OLS\nfunction normal(theta, y, x)\n    b = theta[1:end-1][1]\n    s = theta[end][1]\n    e = (y - x*b)./s\n    logdensity = -log.(sqrt.(2.0*pi)) .- 0.5*log(s.^2) .- 0.5*e.*e\nend\n", "meta": {"hexsha": "51aedf862f7aee62e622afc1b949490974939b1f", "size": 343, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ML/Likelihoods/normal.jl", "max_stars_repo_name": "Vkamalvanshi/Econometrics", "max_stars_repo_head_hexsha": "9bf91e418e8f623a02ee6091af5de29853aecfab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-28T01:07:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T01:07:58.000Z", "max_issues_repo_path": "src/ML/Likelihoods/normal.jl", "max_issues_repo_name": "Vkamalvanshi/Econometrics", "max_issues_repo_head_hexsha": "9bf91e418e8f623a02ee6091af5de29853aecfab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ML/Likelihoods/normal.jl", "max_forks_repo_name": "Vkamalvanshi/Econometrics", "max_forks_repo_head_hexsha": "9bf91e418e8f623a02ee6091af5de29853aecfab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-01T03:41:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T03:41:13.000Z", "avg_line_length": 31.1818181818, "max_line_length": 66, "alphanum_fraction": 0.5918367347, "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154282922475, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7819337380452405}}
{"text": "using FFTW\nusing Plots\nusing Scat\n\n# plot filters in the frequency domain\n# Plot filters for the first layer\nN = 12 # log2 of the length of the signal\nQ = [12, 1] # number of wavelets per octave\nJ = 8 # log2 of the maximum scale\nσ0 = 0.1\n\nFilterBank1, FilterBank2 = get_FilterBanks(N, Q, J, σ0)\n\nω = FFTW.fftshift(FilterBank1.ω)\nplot(ω, FFTW.fftshift(FilterBank1.Λ[1].ψ), xlims=(0.0, 0.5), color=:steelblue, linewidth=2, legend=false)\nfor ψ in FilterBank1.Λ[2:end]\n    plot!(ω, FFTW.fftshift(ψ.ψ), xlims=(0.0, 0.5), color=:steelblue, linewidth=2, legend=false)\nend\nplot!(ω, FFTW.fftshift(FilterBank1.ϕ.ϕ), xlims=(0.0, 0.5), linewidth=2, color=:crimson, legend=false)\nxlabel!(\"Frequency\")\nsavefig(\"FilterBank1.png\")\n\n# Plot filters for the second layer\nω = FFTW.fftshift(FilterBank2.ω)\nplot(ω, FFTW.fftshift(FilterBank2.Λ[1].ψ), xlims=(0.0, 0.5), color=:steelblue, linewidth=2, legend=false)\nfor ψ in FilterBank2.Λ[2:end]\n    plot!(ω, FFTW.fftshift(ψ.ψ), xlims=(0.0, 0.5), color=:steelblue, linewidth=2, legend=false)\nend\nplot!(ω, FFTW.fftshift(FilterBank2.ϕ.ϕ), xlims=(0.0, 0.5), linewidth=2, color=:crimson, legend=false)\nxlabel!(\"Frequency\")\nsavefig(\"FilterBank2.png\")\n\n# plot filter in the time domain\nplot(real.(FFTW.fftshift(FFTW.ifft(FilterBank1.Λ[74].ψ))), linewidth=2, color=:steelblue, label=\"Real\", axis=nothing)\nplot!(imag.(FFTW.fftshift(FFTW.ifft(FilterBank1.Λ[74].ψ))), linewidth=2, linestyle=:dash, color=:black, label=\"Imaginary\", axis=nothing)\nxlabel!(\"Time\")\nsavefig(\"MorletWavelet.png\")\n", "meta": {"hexsha": "a4241e5e9b5e61ffb944dbad21e0bdf9ce22d7f1", "size": 1505, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/plot_filters.jl", "max_stars_repo_name": "jaredbryan881/Scat.jl", "max_stars_repo_head_hexsha": "743f51629bec62767c64c51ae932e1a8f4926d0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/plot_filters.jl", "max_issues_repo_name": "jaredbryan881/Scat.jl", "max_issues_repo_head_hexsha": "743f51629bec62767c64c51ae932e1a8f4926d0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/plot_filters.jl", "max_forks_repo_name": "jaredbryan881/Scat.jl", "max_forks_repo_head_hexsha": "743f51629bec62767c64c51ae932e1a8f4926d0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6052631579, "max_line_length": 136, "alphanum_fraction": 0.7169435216, "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7819308656996086}}
{"text": "# SPDX-License-Identifier: MIT\n\n# Stable implemenation of the log(exp(x) + exp(y)).\nfunction logaddexp(x::T, y::T) where T\n    diff = zero(T)\n    if x < y\n        diff = x - y\n        x = y\n    else y < x\n        diff = y - x\n    end\n\n    if diff >= log(eps(T))\n        return x + log1p(exp(diff))\n    end\n    return x\nend\n\nabstract type Semifield <: Number end\n\nBase.convert(T::Type{<:Number}, x::Semifield) = T(x.val)\nBase.promote(x::SF, y::Real) where SF <: Semifield = x, SF(y)\nBase.promote(x::Real, y::SF) where SF <: Semifield = SF(x), y\nBase.show(io::IO, x::Semifield) = print(io, x.val)\n\n#======================================================================\nLog-semifield:\n    x ⊕ y := log( exp(x) + exp(y))\n    x ⊗ y := x + y\n    x ⊘ y := x - y\n======================================================================#\n\nstruct LogSemifield{T<:AbstractFloat} <: Semifield\n    val::T\nend\n\nBase.:+(x::LogSemifield{T}, y::LogSemifield{T}) where T =\n    LogSemifield{T}(logaddexp(x.val, y.val))\nBase.:*(x::LogSemifield, y::LogSemifield) = LogSemifield(x.val + y.val)\nBase.:/(x::LogSemifield, y::LogSemifield) = LogSemifield(x.val - y.val)\nBase.zero(::Type{LogSemifield{T}}) where T = LogSemifield{T}(T(-Inf))\nBase.zero(::LogSemifield{T}) where T = LogSemifield{T}(T(-Inf))\nBase.one(::Type{LogSemifield{T}}) where T = LogSemifield{T}(T(0))\nBase.one(::LogSemifield{T}) where T = LogSemifield{T}(T(0))\nBase.isless(x::LogSemifield, y::LogSemifield) = isless(x.val, y.val)\nBase.typemin(x::Type{LogSemifield{T}}) where T = LogSemifield{T}(typemin(T))\nBase.typemax(x::Type{LogSemifield{T}}) where T = LogSemifield{T}(typemax(T))\nBase.conj(x::LogSemifield) = conj(x.val)\n\n#======================================================================\nTropical-semifield:\n    x ⊕ y := max(x, y)\n    x ⊗ y := x + y\n    x ⊘ y := x - y\n======================================================================#\n\nstruct TropicalSemifield{T<:AbstractFloat} <: Semifield\n    val::T\nend\n\nBase.:+(x::TropicalSemifield, y::TropicalSemifield) =\n    TropicalSemifield(max(x.val, y.val))\nBase.:*(x::TropicalSemifield, y::TropicalSemifield) =\n    TropicalSemifield(x.val + y.val)\nBase.:/(x::TropicalSemifield, y::TropicalSemifield) =\n    TropicalSemifield(x.val - y.val)\nBase.zero(::Type{TropicalSemifield{T}}) where T = TropicalSemifield{T}(T(-Inf))\nBase.zero(::TropicalSemifield{T}) where T = TropicalSemifield{T}(T(-Inf))\nBase.one(::Type{TropicalSemifield{T}}) where T = TropicalSemifield{T}(T(0))\nBase.one(::TropicalSemifield{T}) where T = TropicalSemifield{T}(T(0))\nBase.isless(x::TropicalSemifield, y::TropicalSemifield) = isless(x.val, y.val)\nBase.typemin(x::Type{TropicalSemifield{T}}) where T =\n    TropicalSemifield{T}(typemin(T))\nBase.typemax(x::Type{TropicalSemifield{T}}) where T =\n    TropicalSemifield{T}(typemax(T))\nBase.conj(x::TropicalSemifield) = conj(x.val)\n", "meta": {"hexsha": "18a73f1f5debc45c2c9c39ac29ac73ef5a24bf41", "size": 2850, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/semifields.jl", "max_stars_repo_name": "MartinKocour/MarkovModels", "max_stars_repo_head_hexsha": "c488c697f6b87420e3222fd1e83d04390e0ec92f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/semifields.jl", "max_issues_repo_name": "MartinKocour/MarkovModels", "max_issues_repo_head_hexsha": "c488c697f6b87420e3222fd1e83d04390e0ec92f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/semifields.jl", "max_forks_repo_name": "MartinKocour/MarkovModels", "max_forks_repo_head_hexsha": "c488c697f6b87420e3222fd1e83d04390e0ec92f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.012987013, "max_line_length": 79, "alphanum_fraction": 0.5929824561, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.781930861355757}}
{"text": "module HWconstrained\r\n\r\ngreet() = print(\"Hello World!\")\r\n\r\n\tusing JuMP, NLopt, DataFrames, Ipopt\r\n\tusing LinearAlgebra\r\n\r\n\texport data, table_NLopt, table_JuMP\r\n\r\n\tfunction data(a=0.5)\r\n        na = 3\r\n\t\tnc = 1\r\n\t\tns = 4\r\n\t\tnss = 16\r\n\t\te = [2,0,0]\r\n\t\tp = [1,1,1]\r\n\t\tz_2 = [0.72,0.92,1.12,1.32]\r\n\t\tz_3 = [0.86,0.96,1.06,1.16]\r\n\t\tz = [[1.0,z_2[j],z_3[k]] for j in 1:4 for k in 1:4]\r\n\t\tpi = 1/16*ones(1,16)\r\n\t\treturn Dict(\"a\"=>a,\"na\"=>na,\"nc\"=>nc,\"ns\"=>ns,\"nss\"=>nss,\"e\"=>e,\"p\"=>p,\"z\"=>z,\"pi\"=>pi)\r\n\tend\r\n\r\n\tfunction maxJuMP(a=0.5)\r\n\t        d = data(a)\r\n\t\t\tn = Model(with_optimizer(Ipopt.Optimizer))\r\n\t\t\t@variable(n, omega[1:3])\r\n\t\t\t@variable(n, c)\r\n\t\t\t@NLobjective(n, Min, exp(-a*c)+sum(d[\"pi\"][i]*exp((-a)*sum(d[\"z\"][i][j]'*omega[j] for j in 1:d[\"na\"])) for i in 1:d[\"nss\"]))\r\n\t\t\t@constraint(n, c + d[\"p\"]'*(omega - d[\"e\"]) <= 0)\r\n\t\t\tJuMP.optimize!(n)\r\n\t  \treturn Dict(\"obj\"=>objective_value(n),\"c\"=>value(c),\"omegas\"=>[value(omega[i]) for i in 1:length(omega)])\r\n\tend\r\n\r\n\tfunction table_JuMP()\r\n\t\td = DataFrame(a=[0.5;1.0;5.0],c = zeros(3),omega1=zeros(3),omega2=zeros(3),omega3=zeros(3),fval=zeros(3))\r\n\t\tfor i in 1:nrow(d)\r\n\t\t\txx = maxJuMP(d[i,:a])\r\n\t\t\td[i,:c] = xx[\"c\"]\r\n\t\t\td[i,:omega1] = xx[\"omegas\"][1]\r\n\t\t\td[i,:omega2] = xx[\"omegas\"][2]\r\n\t\t\td[i,:omega3] = xx[\"omegas\"][3]\r\n\t\t\td[i,:fval] = xx[\"obj\"]\r\n\t\tend\r\n\t\treturn d\r\n\tend\r\n\r\n\tfunction obj(x::Vector,d::Dict)\r\n\t\ta = d[\"a\"]\r\n\t\tz = d[\"z\"]\r\n\t\tpi = d[\"pi\"]\r\n\t\tif length(grad)>0\r\n\t\t\t  grad[1] = sum(d[\"pi\"][i]*(-a)*exp((-a)*z[i][1]*sum(z[i]'*x[1:3])) for i in 1:d[\"nss\"])\r\n\t\t\t  grad[2] = sum(d[\"pi\"][i]*(-a)*exp((-a)*z[i][2]*sum(z[i]'*x[1:3])) for i in 1:d[\"nss\"])\r\n\t\t\t  grad[3] = sum(d[\"pi\"][i]*(-a)*exp((-a)*z[i][3]*sum(z[i]'*x[1:3])) for i in 1:d[\"nss\"])\r\n\t\t\t  grad[4] = (-a)*exp.(-a*x[4])\r\n\t\t  end\r\n\t\treturn (exp(-a*x[4])+sum(d[\"pi\"][i]*exp((-a)*sum(z[i]'*x[1:3])) for i in 1:d[\"nss\"]))\r\n\t  end\r\n\r\n\r\n\tfunction constr(x::Vector,grad::Vector,d::Dict)\r\n\t\tif length(grad)>0\r\n\t\t\t   grad[1] = d[\"p\"][1]\r\n\t\t\t   grad[2] = d[\"p\"][2]\r\n\t\t\t   grad[3] = d[\"p\"][3]\r\n\t\t\t   grad[4] = 1\r\n\t   end\r\n\t   return x[4] + d[\"p\"]'*(x[1:3] - d[\"e\"])\r\n\tend\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\tfunction max_NLopt(a=0.5)\r\n\t\tcount = 0 # keep track of # function evaluations\r\n\t\topt = Opt(:LD_MMA, 4)\r\n\t\tlower_bounds!(opt, [-Inf, -Inf, -Inf, 0.])\r\n\t\txtol_rel!(opt, 1e-7)\r\n\t\tgrad = zeros(4)\r\n\t\tprintln(length(grad))\r\n\t\td = data(a)\r\n\t\tmin_objective!(opt,(x,grad) -> obj(x,grad,d))\r\n\t\tinequality_constraint!(opt, (x,grad) -> constr(x,grad,d))\r\n\t\tftol_rel!(opt,1e-9)\r\n\t\tNLopt.optimize(opt, [0,0,0,0])\r\nend\r\n\r\n\r\n\tfunction table_NLopt()\r\n\t\td = DataFrame(a=[0.5;1.0;5.0],c = zeros(3),omega1=zeros(3),omega2=zeros(3),omega3=zeros(3),fval=zeros(3))\r\n\t\tfor i in 1:nrow(d)\r\n\t\t\txx = max_NLopt(d[i,:a])\r\n\t\t\tfor j in 2:ncol(d)-1\r\n\t\t\t\td[i,j] = xx[2][j-1]\r\n\t\t\tend\r\n\t\t\td[i,end] = xx[1]\r\n\t\tend\r\n\t\treturn d\r\n\tend\r\n\r\n\r\n\r\nend # module\r\n", "meta": {"hexsha": "d7171382ca5c17b8860d62b2ee53aa583995efe6", "size": 2820, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HWconstrained.jl", "max_stars_repo_name": "Zoro20171002/HWconstrained.jl", "max_stars_repo_head_hexsha": "9803a82a566caa679756bdc57fa1bd9bf89680c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HWconstrained.jl", "max_issues_repo_name": "Zoro20171002/HWconstrained.jl", "max_issues_repo_head_hexsha": "9803a82a566caa679756bdc57fa1bd9bf89680c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HWconstrained.jl", "max_forks_repo_name": "Zoro20171002/HWconstrained.jl", "max_forks_repo_head_hexsha": "9803a82a566caa679756bdc57fa1bd9bf89680c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1111111111, "max_line_length": 128, "alphanum_fraction": 0.5173758865, "num_tokens": 1187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384733, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7819308607680878}}
{"text": "#Unary Operators\n\"\"\"\nIdentity: `z=x`\n\"\"\"\nUnaryOps.IDENTITY\njuliaop(::typeof(UnaryOps.IDENTITY)) = identity\nUnaryOps.UnaryOp(::typeof(identity)) = UnaryOps.IDENTITY\n\"\"\"\nAdditive Inverse: `z=-x`\n\"\"\"\nUnaryOps.AINV\njuliaop(::typeof(UnaryOps.AINV)) = -\nUnaryOps.UnaryOp(::typeof(-)) = UnaryOps.AINV\n\"\"\"\nLogical Negation\n\n`z=¬x::Bool`\n\n`Real`:  `z=¬(x::ℝ ≠ 0)`\n\"\"\"\nUnaryOps.LNOT\njuliaop(::typeof(UnaryOps.LNOT)) = !\nUnaryOps.UnaryOp(::typeof(!)) = UnaryOps.LNOT\n\"\"\"\nMultiplicative Inverse: `z=1/x`\n\"\"\"\nUnaryOps.MINV\njuliaop(::typeof(UnaryOps.MINV)) = inv\nUnaryOps.UnaryOp(::typeof(inv)) = UnaryOps.MINV\n\"\"\"\nOne: `z=one(x)`\n\"\"\"\nUnaryOps.ONE\njuliaop(::typeof(UnaryOps.ONE)) = one\nUnaryOps.UnaryOp(::typeof(one)) = UnaryOps.ONE\n\"\"\"\nAbsolute Value: `z=|x|`\n\"\"\"\nUnaryOps.ABS\njuliaop(::typeof(UnaryOps.ABS)) = abs\nUnaryOps.UnaryOp(::typeof(abs)) = UnaryOps.ABS\n\"\"\"\nBitwise Negation: `z=¬x`\n\"\"\"\nUnaryOps.BNOT\njuliaop(::typeof(UnaryOps.BNOT)) = ~\nUnaryOps.UnaryOp(::typeof(~)) = UnaryOps.BNOT\n\"\"\"\nSquare Root: `z=√(x)`\n\"\"\"\nUnaryOps.SQRT\njuliaop(::typeof(UnaryOps.SQRT)) = sqrt\nUnaryOps.UnaryOp(::typeof(sqrt)) = UnaryOps.SQRT\n\"\"\"\nNatural Logarithm: `z=logₑ(x)`\n\"\"\"\nUnaryOps.LOG\njuliaop(::typeof(UnaryOps.LOG)) = log\nUnaryOps.UnaryOp(::typeof(log)) = UnaryOps.LOG\n\"\"\"\nNatural Base Exponential: `z=eˣ`\n\"\"\"\nUnaryOps.EXP\njuliaop(::typeof(UnaryOps.EXP)) = exp\nUnaryOps.UnaryOp(::typeof(exp)) = UnaryOps.EXP\n\"\"\"\nLog Base 2: `z=log₂(x)`\n\"\"\"\nUnaryOps.LOG2\njuliaop(::typeof(UnaryOps.LOG2)) = log2\nUnaryOps.UnaryOp(::typeof(log2)) = UnaryOps.LOG2\n\"\"\"\nSine: `z=sin(x)`\n\"\"\"\nUnaryOps.SIN\njuliaop(::typeof(UnaryOps.SIN)) = sin\nUnaryOps.UnaryOp(::typeof(sin)) = UnaryOps.SIN\n\"\"\"\nCosine: `z=cos(x)`\n\"\"\"\nUnaryOps.COS\njuliaop(::typeof(UnaryOps.COS)) = cos\nUnaryOps.UnaryOp(::typeof(cos)) = UnaryOps.COS\n\"\"\"\nTangent: `z=tan(x)`\n\"\"\"\nUnaryOps.TAN\njuliaop(::typeof(UnaryOps.TAN)) = tan\nUnaryOps.UnaryOp(::typeof(tan)) = UnaryOps.TAN\n\"\"\"\nInverse Cosine: `z=cos⁻¹(x)`\n\"\"\"\nUnaryOps.ACOS\njuliaop(::typeof(UnaryOps.ACOS)) = acos\nUnaryOps.UnaryOp(::typeof(acos)) = UnaryOps.ACOS\n\"\"\"\nInverse Sine: `z=sin⁻¹(x)`\n\"\"\"\nUnaryOps.ASIN\njuliaop(::typeof(UnaryOps.ASIN)) = asin\nUnaryOps.UnaryOp(::typeof(asin)) = UnaryOps.ASIN\n\"\"\"\nInverse Tangent: `z=tan⁻¹(x)`\n\"\"\"\nUnaryOps.ATAN\njuliaop(::typeof(UnaryOps.ATAN)) = atan\nUnaryOps.UnaryOp(::typeof(atan)) = UnaryOps.ATAN\n\"\"\"\nHyperbolic Sine: `z=sinh(x)`\n\"\"\"\nUnaryOps.SINH\njuliaop(::typeof(UnaryOps.SINH)) = sinh\nUnaryOps.UnaryOp(::typeof(sinh)) = UnaryOps.SINH\n\"\"\"\nHyperbolic Cosine: `z=cosh(x)`\n\"\"\"\nUnaryOps.COSH\njuliaop(::typeof(UnaryOps.COSH)) = cosh\nUnaryOps.UnaryOp(::typeof(cosh)) = UnaryOps.COSH\n\"\"\"\nHyperbolic Tangent: `z=tanh(x)`\n\"\"\"\nUnaryOps.TANH\njuliaop(::typeof(UnaryOps.TANH)) = tanh\nUnaryOps.UnaryOp(::typeof(tanh)) = UnaryOps.TANH\n\"\"\"\nInverse Hyperbolic Sine: `z=sinh⁻¹(x)`\n\"\"\"\nUnaryOps.ASINH\njuliaop(::typeof(UnaryOps.ASINH)) = asinh\nUnaryOps.UnaryOp(::typeof(asinh)) = UnaryOps.ASINH\n\"\"\"\nInverse Hyperbolic Cosine: `z=cosh⁻¹(x)`\n\"\"\"\nUnaryOps.ACOSH\njuliaop(::typeof(UnaryOps.ACOSH)) = acosh\nUnaryOps.UnaryOp(::typeof(acosh)) = UnaryOps.ACOSH\n\"\"\"\nInverse Hyperbolic Tangent: `z=tanh⁻¹(x)`\n\"\"\"\nUnaryOps.ATANH\njuliaop(::typeof(UnaryOps.ATANH)) = atanh\nUnaryOps.UnaryOp(::typeof(atanh)) = UnaryOps.ATANH\n\"\"\"\nSign Function: `z=signum(x)`\n\"\"\"\nUnaryOps.SIGNUM\njuliaop(::typeof(UnaryOps.SIGNUM)) = sign\nUnaryOps.UnaryOp(::typeof(sign)) = UnaryOps.SIGNUM\n\"\"\"\nCeiling Function: `z=⌈x⌉`\n\"\"\"\nUnaryOps.CEIL\njuliaop(::typeof(UnaryOps.CEIL)) = ceil\nUnaryOps.UnaryOp(::typeof(ceil)) = UnaryOps.CEIL\n\"\"\"\nFloor Function: `z=⌊x⌋`\n\"\"\"\nUnaryOps.FLOOR\njuliaop(::typeof(UnaryOps.FLOOR)) = floor\nUnaryOps.UnaryOp(::typeof(floor)) = UnaryOps.FLOOR\n\"\"\"\nRound to nearest: `z=round(x)`\n\"\"\"\nUnaryOps.ROUND\njuliaop(::typeof(UnaryOps.ROUND)) = round\nUnaryOps.UnaryOp(::typeof(round)) = UnaryOps.ROUND\n\"\"\"\nTruncate: `z=trunc(x)`\n\"\"\"\nUnaryOps.TRUNC\njuliaop(::typeof(UnaryOps.TRUNC)) = trunc\nUnaryOps.UnaryOp(::typeof(trunc)) = UnaryOps.TRUNC\n\"\"\"\nBase-2 Exponential: `z=2ˣ`\n\"\"\"\nUnaryOps.EXP2\njuliaop(::typeof(UnaryOps.EXP2)) = exp2\nUnaryOps.UnaryOp(::typeof(exp2)) = UnaryOps.EXP2\n\"\"\"\nNatural Exponential - 1: `z=eˣ - 1`\n\"\"\"\nUnaryOps.EXPM1\njuliaop(::typeof(UnaryOps.EXPM1)) = expm1\nUnaryOps.UnaryOp(::typeof(expm1)) = UnaryOps.EXPM1\n\"\"\"\nLog Base 10: `z=log₁₀(x)`\n\"\"\"\nUnaryOps.LOG10\njuliaop(::typeof(UnaryOps.LOG10)) = log10\nUnaryOps.UnaryOp(::typeof(log10)) = UnaryOps.LOG10\n\"\"\"\nNatural Log of x + 1: `z=logₑ(x + 1)`\n\"\"\"\nUnaryOps.LOG1P\njuliaop(::typeof(UnaryOps.LOG1P)) = log1p\nUnaryOps.UnaryOp(::typeof(log1p)) = UnaryOps.LOG1P\n\"\"\"\nLog of Gamma Function: `z=log(|Γ(x)|)`\n\"\"\"\nUnaryOps.LGAMMA\njuliaop(::typeof(UnaryOps.LGAMMA)) = lgamma\nUnaryOps.UnaryOp(::typeof(lgamma)) = UnaryOps.LGAMMA\n\"\"\"\nGamma Function: `z=Γ(x)`\n\"\"\"\nUnaryOps.TGAMMA\njuliaop(::typeof(UnaryOps.TGAMMA)) = gamma\nUnaryOps.UnaryOp(::typeof(gamma)) = UnaryOps.TGAMMA\n\"\"\"\nError Function: `z=erf(x)`\n\"\"\"\nUnaryOps.ERF\njuliaop(::typeof(UnaryOps.ERF)) = erf\nUnaryOps.UnaryOp(::typeof(erf)) = UnaryOps.ERF\n\"\"\"\nComplimentary Error Function: `z=erfc(x)`\n\"\"\"\nUnaryOps.ERFC\njuliaop(::typeof(UnaryOps.ERFC)) = erfc\nUnaryOps.UnaryOp(::typeof(erfc)) = UnaryOps.ERFC\n\n#There is no exact equivalent here, since Julia's frexp returns (frexpx, frexpe).\n\"\"\"\nNormalized Exponent: `z=frexpe(x)`\n\"\"\"\nUnaryOps.FREXPE\nfunction frexpe end\njuliaop(::typeof(UnaryOps.FREXPE)) = frexpe\nUnaryOps.UnaryOp(::typeof(frexpe)) = UnaryOps.FREXPE\n\"\"\"\nNormalized Fraction: `z=frexpx(x)`\n\"\"\"\nUnaryOps.FREXPX\nfunction frexpx end\njuliaop(::typeof(UnaryOps.FREXPX)) = frexpx\nUnaryOps.UnaryOp(::typeof(frexpx)) = UnaryOps.frexpx\n\n\"\"\"\nComplex Conjugate: `z=x̄`\n\"\"\"\nUnaryOps.CONJ\njuliaop(::typeof(UnaryOps.CONJ)) = conj\nUnaryOps.UnaryOp(::typeof(conj)) = UnaryOps.CONJ\n\"\"\"\nReal Part: `z=real(x)`\n\"\"\"\nUnaryOps.CREAL\njuliaop(::typeof(UnaryOps.CREAL)) = real\nUnaryOps.UnaryOp(::typeof(real)) = UnaryOps.CREAL\n\"\"\"\nImaginary Part: `z=imag(x)`\n\"\"\"\nUnaryOps.CIMAG\njuliaop(::typeof(UnaryOps.CIMAG)) = imag\nUnaryOps.UnaryOp(::typeof(imag)) = UnaryOps.CIMAG\n\"\"\"\nAngle: `z=carg(x)`\n\"\"\"\nUnaryOps.CARG\njuliaop(::typeof(UnaryOps.CARG)) = angle\nUnaryOps.UnaryOp(::typeof(angle)) = UnaryOps.CARG\n\"\"\"\nisinf: `z=(x == ±∞)`\n\"\"\"\nUnaryOps.ISINF\njuliaop(::typeof(UnaryOps.ISINF)) = isinf\nUnaryOps.UnaryOp(::typeof(isinf)) = UnaryOps.ISINF\n\"\"\"\nisnan: `z=(x == NaN)`\n\"\"\"\nUnaryOps.ISNAN\njuliaop(::typeof(UnaryOps.ISNAN)) = isnan\nUnaryOps.UnaryOp(::typeof(isnan)) = UnaryOps.ISNAN\n\"\"\"\nisfinite: `z=isfinite(x)`\n\"\"\"\nUnaryOps.ISFINITE\njuliaop(::typeof(UnaryOps.ISFINITE)) = isfinite\nUnaryOps.UnaryOp(::typeof(isfinite)) = UnaryOps.ISFINITE\n\"\"\"\n0-based Row Index: `z=i`\n\"\"\"\nUnaryOps.POSITIONI #No Julia version since it's 0-based.\n\"\"\"\n1-Based Row Index: `z=i + 1`\n\"\"\"\nUnaryOps.POSITIONI1\nfunction positioni end\njuliaop(::typeof(UnaryOps.POSITIONI1)) = positioni\nUnaryOps.UnaryOp(::typeof(positioni)) = UnaryOps.POSITIONI1\n\"\"\"\n0-Based Column Index: `z=j`\n\"\"\"\nUnaryOps.POSITIONJ #No Julia version since it's 0-based.\n\"\"\"\n1-Based Column Index: `z=j + 1`\n\"\"\"\nUnaryOps.POSITIONJ1\nfunction positionj end\njuliaop(::typeof(UnaryOps.POSITIONJ1)) = positionj\nUnaryOps.UnaryOp(::typeof(positionj)) = UnaryOps.POSITIONJ1\n\n#Binary Operators\n\"\"\"\nFirst argument: `f(x::T,y::T)::T = x`\n\"\"\"\nBinaryOps.FIRST\njuliaop(::typeof(BinaryOps.FIRST)) = first\nBinaryOps.BinaryOp(::typeof(first)) = BinaryOps.FIRST\n\"\"\"\nSecond argument: `f(x::T,y::T)::T = y`\n\"\"\"\nBinaryOps.SECOND\nfunction second end\njuliaop(::typeof(BinaryOps.SECOND)) = second\nBinaryOps.BinaryOp(::typeof(second)) = BinaryOps.SECOND\n\"\"\"\nPower: `f(x::T,y::T)::T = xʸ`\n\"\"\"\nBinaryOps.POW\njuliaop(::typeof(BinaryOps.POW)) = ^\nBinaryOps.BinaryOp(::typeof(^)) = BinaryOps.POW\n\"\"\"\nAddition: `f(x::T,y::T)::T = x + y`\n\"\"\"\nBinaryOps.PLUS\njuliaop(::typeof(BinaryOps.PLUS)) = +\nBinaryOps.BinaryOp(::typeof(+)) = BinaryOps.PLUS\n\"\"\"\nSubtraction: `f(x::T,y::T)::T = x - y`\n\"\"\"\nBinaryOps.MINUS\njuliaop(::typeof(BinaryOps.MINUS)) = -\nBinaryOps.BinaryOp(::typeof(-)) = BinaryOps.MINUS\n\"\"\"\nMultiplication: `f(x::T,y::T)::T = xy`\n\"\"\"\nBinaryOps.TIMES\njuliaop(::typeof(BinaryOps.TIMES)) = *\nBinaryOps.BinaryOp(::typeof(*)) = BinaryOps.TIMES\n\"\"\"\nDivision: `f(x::T,y::T)::T = x / y`\n\"\"\"\nBinaryOps.DIV\njuliaop(::typeof(BinaryOps.DIV)) = /\nBinaryOps.BinaryOp(::typeof(/)) = BinaryOps.DIV\n\"\"\"\nReverse Subtraction: `f(x::T,y::T)::T = y - x`\n\"\"\"\nBinaryOps.RMINUS\nfunction rminus end\njuliaop(::typeof(BinaryOps.RMINUS)) = rminus\nBinaryOps.BinaryOp(::typeof(rminus)) = BinaryOps.RMINUS\n\"\"\"\nReverse Division: `f(x::T,y::T)::T = y / x`\n\"\"\"\nBinaryOps.RDIV\njuliaop(::typeof(BinaryOps.RDIV)) = \\\nBinaryOps.BinaryOp(::typeof(\\)) = BinaryOps.RDIV\n\"\"\"\nOne when both x and y exist: `f(x::T,y::T)::T = 1`\n\"\"\"\nBinaryOps.PAIR\nfunction pair end\njuliaop(::typeof(BinaryOps.PAIR)) = pair\nBinaryOps.BinaryOp(::typeof(pair)) = BinaryOps.PAIR\n\"\"\"\nPick x or y arbitrarily: `f(x::T,y::T)::T = x or y`\n\"\"\"\nBinaryOps.ANY\n#This is sort of incorrect\njuliaop(::typeof(BinaryOps.ANY)) = any\nBinaryOps.BinaryOp(::typeof(any)) = BinaryOps.ANY\n\"\"\"\nEqual: `f(x::T,y::T)::T = x == y``\n\"\"\"\nBinaryOps.ISEQ\nfunction iseq end\njuliaop(::typeof(BinaryOps.ISEQ)) = iseq\nBinaryOps.BinaryOp(::typeof(iseq)) = BinaryOps.ISEQ\n\"\"\"\nNot Equal: `f(x::T,y::T)::T = x ≠ y`\n\"\"\"\nBinaryOps.ISNE\nfunction isne end\njuliaop(::typeof(BinaryOps.ISNE)) = isne\nBinaryOps.BinaryOp(::typeof(isne)) = BinaryOps.ISNE\n\"\"\"\nGreater Than: `f(x::ℝ,y::ℝ)::ℝ = x > y`\n\"\"\"\nBinaryOps.ISGT\nfunction isgt end\njuliaop(::typeof(BinaryOps.ISGT)) = isgt\nBinaryOps.BinaryOp(::typeof(isgt)) = BinaryOps.ISGT\n\"\"\"\nLess Than: `f(x::ℝ,y::ℝ)::ℝ = x < y`\n\"\"\"\nBinaryOps.ISLT\nfunction islt end\njuliaop(::typeof(BinaryOps.ISLT)) = islt\nBinaryOps.BinaryOp(::typeof(islt)) = BinaryOps.ISLT\n\"\"\"\nGreater Than or Equal: `f(x::ℝ,y::ℝ)::ℝ = x ≥ y`\n\"\"\"\nBinaryOps.ISGE\nfunction isge end\njuliaop(::typeof(BinaryOps.ISGE)) = isge\nBinaryOps.BinaryOp(::typeof(isge)) = BinaryOps.ISGE\n\"\"\"\nLess Than or Equal: `f(x::ℝ,y::ℝ)::ℝ = x ≤ y`\n\"\"\"\nBinaryOps.ISLE\nfunction isle end\njuliaop(::typeof(BinaryOps.ISLE)) = isle\nBinaryOps.BinaryOp(::typeof(isle)) = BinaryOps.ISLE\n\"\"\"\nMinimum: `f(x::ℝ,y::ℝ)::ℝ = min(x, y)`\n\"\"\"\nBinaryOps.MIN\njuliaop(::typeof(BinaryOps.MIN)) = min\nBinaryOps.BinaryOp(::typeof(min)) = BinaryOps.MIN\n\"\"\"\nMaximum: `f(x::ℝ,y::ℝ)::ℝ = max(x, y)`\n\"\"\"\nBinaryOps.MAX\njuliaop(::typeof(BinaryOps.MAX)) = max\nBinaryOps.BinaryOp(::typeof(max)) = BinaryOps.MAX\n\"\"\"\nLogical OR: `f(x::ℝ,y::ℝ)::ℝ = (x ≠ 0) ∨ (y ≠ 0)`\n\"\"\"\nBinaryOps.LOR\nfunction ∨ end\njuliaop(::typeof(BinaryOps.LOR)) = ∨\nBinaryOps.BinaryOp(::typeof(∨)) = BinaryOps.LOR\n\"\"\"\nLogical AND: `f(x::ℝ,y::ℝ)::ℝ = (x ≠ 0) ∧ (y ≠ 0)`\n\"\"\"\nBinaryOps.LAND\nfunction ∧ end\njuliaop(::typeof(BinaryOps.LAND)) = ∧\nBinaryOps.BinaryOp(::typeof(∧)) = BinaryOps.LAND\n\"\"\"\nLogical AND: `f(x::ℝ,y::ℝ)::ℝ = (x ≠ 0) ⊻ (y ≠ 0)`\n\"\"\"\nBinaryOps.LXOR\nfunction lxor end\njuliaop(::typeof(BinaryOps.LXOR)) = lxor\nBinaryOps.BinaryOp(::typeof(lxor)) = BinaryOps.LXOR\n\"\"\"\n4-Quadrant Arc Tangent: `f(x::F, y::F)::F = tan⁻¹(y/x)`\n\"\"\"\nBinaryOps.ATAN2\njuliaop(::typeof(BinaryOps.ATAN2)) = atan\nBinaryOps.BinaryOp(::typeof(atan)) = BinaryOps.ATAN2\n\"\"\"\nHypotenuse: `f(x::F, y::F)::F = √(x² + y²)`\n\"\"\"\nBinaryOps.HYPOT\njuliaop(::typeof(BinaryOps.HYPOT)) = hypot\nBinaryOps.BinaryOp(::typeof(hypot)) = BinaryOps.HYPOT\n\"\"\"\nFloat remainder of x / y rounded towards zero.\n\"\"\"\nBinaryOps.FMOD\n#Is this available?\nfunction fmod end\njuliaop(::typeof(BinaryOps.FMOD)) = fmod\nBinaryOps.BinaryOp(::typeof(fmod)) = BinaryOps.FMOD\n\"\"\"\nFloat remainder of x / y rounded towards nearest integral value.\n\"\"\"\nBinaryOps.REMAINDER\njuliaop(::typeof(BinaryOps.REMAINDER)) = rem\nBinaryOps.BinaryOp(::typeof(rem)) = BinaryOps.REMAINDER\n\"\"\"\nLDEXP: `f(x::F, y::F)::F = x × 2ⁿ`\n\"\"\"\nBinaryOps.LDEXP\njuliaop(::typeof(BinaryOps.LDEXP)) = ldexp\nBinaryOps.BinaryOp(::typeof(ldexp)) = BinaryOps.LDEXP\n\"\"\"\nCopysign: Value with magnitude of x and sign of y.\n\"\"\"\nBinaryOps.COPYSIGN\njuliaop(::typeof(BinaryOps.COPYSIGN)) = copysign\nBinaryOps.BinaryOp(::typeof(copysign)) = BinaryOps.COPYSIGN\n\"\"\"\nBitwise OR: `f(x::ℤ, y::ℤ)::ℤ = x | y`\n\"\"\"\nBinaryOps.BOR\njuliaop(::typeof(BinaryOps.BOR)) = |\nBinaryOps.BinaryOp(::typeof(|)) = BinaryOps.BOR\n\"\"\"\nBitwise AND: `f(x::ℤ, y::ℤ)::ℤ = x & y`\n\"\"\"\nBinaryOps.BAND\njuliaop(::typeof(BinaryOps.BAND)) = &\nBinaryOps.BinaryOp(::typeof(&)) = BinaryOps.BAND\n\"\"\"\nBitwise XOR: `f(x::ℤ, y::ℤ)::ℤ = x ^ y`\n\"\"\"\nBinaryOps.BXOR\njuliaop(::typeof(BinaryOps.BXOR)) = ⊻\nBinaryOps.BinaryOp(::typeof(⊻)) = BinaryOps.BXOR\n\"\"\"\nBitwise XNOR: : `f(x::ℤ, y::ℤ)::ℤ = ~(x ^ y)`\n\"\"\"\nBinaryOps.BXNOR\njuliaop(::typeof(BinaryOps.BXNOR)) = !⊻\nBinaryOps.BinaryOp(::typeof(!⊻)) = BinaryOps.BXNOR\n\"\"\"\nBGET: `f(x::ℤ, y::ℤ)::ℤ = get bit y of x.`\n\"\"\"\nBinaryOps.BGET\n\"\"\"\nBSET: `f(x::ℤ, y::ℤ)::ℤ = set bit y of x.`\n\"\"\"\nBinaryOps.BSET\n\"\"\"\nBCLR: `f(x::ℤ, y::ℤ)::ℤ = clear bit y of x.`\n\"\"\"\nBinaryOps.BCLR\n\"\"\"\nBSHIFT: `f(x::ℤ, y::Int8)::ℤ = bitshift(x, y)`\n\"\"\"\nBinaryOps.BSHIFT\n\n\"\"\"\nEquals: `f(x::T, y::T)::Bool = x == y`\n\"\"\"\nBinaryOps.EQ\njuliaop(::typeof(BinaryOps.EQ)) = ==\nBinaryOps.BinaryOp(::typeof(==)) = BinaryOps.EQ\n\"\"\"\nNot Equals: `f(x::T, y::T)::Bool = x ≠ y`\n\"\"\"\nBinaryOps.NE\njuliaop(::typeof(BinaryOps.NE)) = !=\nBinaryOps.BinaryOp(::typeof(!=)) = BinaryOps.NE\n\"\"\"\nGreater Than: `f(x::T, y::T)::Bool = x > y`\n\"\"\"\nBinaryOps.GT\njuliaop(::typeof(BinaryOps.GT)) = >\nBinaryOps.BinaryOp(::typeof(>)) = BinaryOps.GT\n\"\"\"\nLess Than: `f(x::T, y::T)::Bool = x < y`\n\"\"\"\nBinaryOps.LT\njuliaop(::typeof(BinaryOps.LT)) = <\nBinaryOps.BinaryOp(::typeof(<)) = BinaryOps.LT\n\"\"\"\nGreater Than or Equal: `f(x::T, y::T)::Bool = x ≥ y`\n\"\"\"\nBinaryOps.GE\njuliaop(::typeof(BinaryOps.GE)) = >=\nBinaryOps.BinaryOp(::typeof(>=)) = BinaryOps.GE\n\"\"\"\nLess Than or Equal: `f(x::T, y::T)::Bool = x ≤ y`\n\"\"\"\nBinaryOps.LE\njuliaop(::typeof(BinaryOps.LE)) = <=\nBinaryOps.BinaryOp(::typeof(<=)) = BinaryOps.LE\n\"\"\"\nComplex: `f(x::F, y::F)::Complex = x + y × i`\n\"\"\"\nBinaryOps.CMPLX\njuliaop(::typeof(BinaryOps.CMPLX)) = complex\nBinaryOps.BinaryOp(::typeof(complex)) = BinaryOps.CMPLX\n\"\"\"\n0-Based row index of a: `f(aᵢⱼ::T, bₖₗ::T)::Int64 = i`\n\"\"\"\nBinaryOps.FIRSTI\n\"\"\"\n1-Based row index of a: `f(aᵢⱼ::T, bₖₗ::T)::Int64 = i + 1`\n\"\"\"\nBinaryOps.FIRSTI1\nfunction firsti end\njuliaop(::typeof(BinaryOps.FIRSTI1)) = firsti\nBinaryOps.BinaryOp(::typeof(firsti)) = BinaryOps.FIRSTI1\n\"\"\"\n0-Based column index of a: `f(aᵢⱼ::T, bₖₗ::T)::Int64 = j`\n\"\"\"\nBinaryOps.FIRSTJ\n\"\"\"\n1-Based column index of a: `f(aᵢⱼ::T, bₖₗ::T)::Int64 = j + 1`\n\"\"\"\nBinaryOps.FIRSTJ1\nfunction firstj end\njuliaop(::typeof(BinaryOps.FIRSTJ1)) = firstj\nBinaryOps.BinaryOp(::typeof(firstj)) = BinaryOps.FIRSTJ1\n\"\"\"\n0-Based row index of b: `f(aᵢⱼ::T, bₖₗ::T)::Int64 = k`\n\"\"\"\nBinaryOps.SECONDI\n\"\"\"\n0-Based row index of b: `f(aᵢⱼ::T, bₖₗ::T)::Int64 = k + 1`\n\"\"\"\nBinaryOps.SECONDI1\nfunction secondi end\njuliaop(::typeof(BinaryOps.SECONDI1)) = secondi\nBinaryOps.BinaryOp(::typeof(secondi)) = BinaryOps.SECONDI1\n\"\"\"\n0-Based column index of b: `f(aᵢⱼ::T, bₖₗ::T)::Int64 = l`\n\"\"\"\nBinaryOps.SECONDJ\n\"\"\"\n1-Based column index of b: `f(aᵢⱼ::T, bₖₗ::T)::Int64 = l + 1`\n\"\"\"\nBinaryOps.SECONDJ1\nfunction secondj end\njuliaop(::typeof(BinaryOps.SECONDJ1)) = secondj\nBinaryOps.BinaryOp(::typeof(secondj)) = BinaryOps.SECONDJ1\n\n#All binary ops will default to emul\ndefaultadd(f) = emul\n# Default to eadd. We're limiting this to + and OR for now to enable easy graph unions.\nfor op ∈ [\n    :+,\n    :∨,\n]\n    funcquote = quote\n        defaultadd(::typeof($op)) = eadd\n    end\n    @eval($funcquote)\nend\n\n\n#Monoid operators\n\"\"\"\nMinimum monoid: `f(x::ℝ, y::ℝ)::ℝ = min(x, y)`\n* Identity: +∞\n* Terminal: -∞\n\"\"\"\nMonoids.MIN_MONOID\nop(::typeof(Monoids.MIN_MONOID)) = BinaryOps.MIN\nMonoids.Monoid(::typeof(min)) = Monoids.MIN_MONOID\n\"\"\"\nMax monoid: `f(x::ℝ, y::ℝ)::ℝ = max(x, y)`\n* Identity: -∞\n* Terminal: +∞\n\"\"\"\nMonoids.MAX_MONOID\nop(::typeof(Monoids.MAX_MONOID)) = BinaryOps.MAX\nMonoids.Monoid(::typeof(max)) = Monoids.MAX_MONOID\n\"\"\"\nPlus monoid: `f(x::T, y::T)::T = x + y`\n* Identity: 0\n* Terminal: nothing\n\"\"\"\nMonoids.PLUS_MONOID\nop(::typeof(Monoids.PLUS_MONOID)) = BinaryOps.PLUS\nMonoids.Monoid(::typeof(+)) = Monoids.PLUS_MONOID\n\"\"\"\nTimes monoid: `f(x::T, y::T)::T = xy`\n* Identity: 1\n* Terminal: 0 for non Floating-point numbers.\n\"\"\"\nMonoids.TIMES_MONOID\nop(::typeof(Monoids.TIMES_MONOID)) = BinaryOps.TIMES\nMonoids.Monoid(::typeof(*)) = Monoids.TIMES_MONOID\n\"\"\"\nAny monoid: `f(x::T, y::T)::T = x or y`\n* Identity: any\n* Terminal: any\n\"\"\"\nMonoids.ANY_MONOID\nop(::typeof(Monoids.ANY_MONOID)) = BinaryOps.ANY\nMonoids.Monoid(::typeof(any)) = Monoids.ANY_MONOID\n\"\"\"\nLogical OR monoid: `f(x::Bool, y::Bool)::Bool = x ∨ y`\n* Identity: false\n* Terminal: true\n\"\"\"\nMonoids.LOR_MONOID\nop(::typeof(Monoids.LOR_MONOID)) = BinaryOps.LOR\nMonoids.Monoid(::typeof(∨)) = Monoids.LOR_MONOID\n\"\"\"\nLogical AND monoid: `f(x::Bool, y::Bool)::Bool = x ∧ y`\n* Identity: true\n* Terminal: false\n\"\"\"\nMonoids.LAND_MONOID\nop(::typeof(Monoids.LAND_MONOID)) = BinaryOps.LAND\nMonoids.Monoid(::typeof(∧)) = Monoids.LAND_MONOID\n\"\"\"\nLogical XOR monoid: `f(x::Bool, y::Bool)::Bool = x ⊻ y`\n* Identity: false\n* Terminal: nothing\n\"\"\"\nMonoids.LXOR_MONOID\nop(::typeof(Monoids.LXOR_MONOID)) = BinaryOps.LXOR\nMonoids.Monoid(::typeof(lxor)) = Monoids.LXOR_MONOID\n\"\"\"\nLogical XNOR monoid: `f(x::Bool, y::Bool)::Bool = x == y`\n* Identity: true\n* Terminal: nothing\n\"\"\"\nMonoids.LXNOR_MONOID\n#Don't care, this is ==.\n\"\"\"\nBoolean Equality `f(x::Bool, y::Bool)::Bool = x == y`.\n\"\"\"\nMonoids.EQ_MONOID\nop(::typeof(Monoids.EQ_MONOID)) = BinaryOps.EQ\nMonoids.Monoid(::typeof(==)) = Monoids.EQ_MONOID\n\"\"\"\nBitwise OR monoid: `f(x::ℤ, y::ℤ)::ℤ = x|y`\n* Identity: All bits `0`.* Terminal: All bits `1`.\n\"\"\"\nMonoids.BOR_MONOID\nop(::typeof(Monoids.BOR_MONOID)) = BinaryOps.BOR\nMonoids.Monoid(::typeof(|)) = Monoids.BOR_MONOID\n\"\"\"\nBitwise AND monoid: `f(x::ℤ, y::ℤ)::ℤ = x&y`\n* Identity: All bits `1`.\n* Terminal: All bits `0`.\n\"\"\"\nMonoids.BAND_MONOID\nop(::typeof(Monoids.BAND_MONOID)) = BinaryOps.BAND\nMonoids.Monoid(::typeof(&)) = Monoids.BAND_MONOID\n\"\"\"\nBitwise XOR monoid: `f(x::ℤ, y::ℤ)::ℤ = x^y`\n* Identity: All bits `0`.\n* Terminal: nothing\n\"\"\"\nMonoids.BXOR_MONOID\nop(::typeof(Monoids.BXOR_MONOID)) = BinaryOps.BXOR\nMonoids.Monoid(::typeof(⊻)) = Monoids.BXOR_MONOID\n\"\"\"\nBitwise XNOR monoid: `f(x::ℤ, y::ℤ)::ℤ = ~(x^y)`\n* Identity: All bits `1`.\n* Terminal: nothing\n\"\"\"\nMonoids.BXNOR_MONOID\nop(::typeof(Monoids.BXNOR_MONOID)) = BinaryOps.BXNOR\nMonoids.Monoid(::typeof(!⊻)) = Monoids.BXNOR_MONOID\n\nmulop(rig::AbstractSemiring) = nothing\naddop(rig::AbstractSemiring) = nothing\n\n# TODO:\n# The definitions below are less than ideal, these should likely be fields of the semiring\n# structs, not evaluated functions.\nfor oplus ∈ [(:max, \"MAX\"), (:min, \"MIN\"), (:+, \"PLUS\"), (:*, \"TIMES\"), (:any, \"ANY\")]\n    for otimes ∈ [\n        (:/, \"DIV\"),\n        (:\\, \"RDIV\"),\n        (:first, \"FIRST\"),\n        (:firsti, \"FIRSTI1\"),\n        (:firstj, \"FIRSTJ1\"),\n        (:iseq, \"ISEQ\"),\n        (:isge, \"ISGE\"),\n        (:isgt, \"ISGT\"),\n        (:isle, \"ISLE\"),\n        (:islt, \"ISLT\"),\n        (:isne, \"ISNE\"),\n        (:∧, \"LAND\"),\n        (:∨, \"LOR\"),\n        (:lxor, \"LXOR\"),\n        (:max, \"MAX\"),\n        (:min, \"MIN\"),\n        (:-, \"MINUS\"),\n        (:rminus, \"RMINUS\"),\n        (:second, \"SECOND\"),\n        (:secondi, \"SECONDI1\"),\n        (:secondj, \"SECONDJ1\"),\n        (:*, \"TIMES\"),\n        (:+, \"PLUS\"),\n        (:pair, \"PAIR\")\n    ]\n    rig = Symbol(oplus[2], \"_\", otimes[2])\n    funcquote = quote\n        Semirings.Semiring(::typeof($(oplus[1])), ::typeof($(otimes[1]))) = $rig\n        addop(::typeof($rig)) = $(oplus[1])\n        mulop(::typeof($rig)) = $(otimes[1])\n    end\n    @eval($funcquote)\n    end\nend\n\nfor otimes ∈ [(:(==), \"EQ\"), (:(>=), \"GE\"), (:(>), \"GT\"), (:(<=), \"LE\"), (:(<), \"LT\"), (:(!=), \"NE\")]\n    oplus = (:any, \"ANY\")\n    rig = Symbol(oplus[2], \"_\", otimes[2])\n    funcquote = quote\n        Semirings.Semiring(::typeof($(oplus[1])), ::typeof($(otimes[1]))) = $rig\n        addop(::typeof($rig)) = $(oplus[1])\n        mulop(::typeof($rig)) = $(otimes[1])\n    end\n    @eval($funcquote)\nend\nfor oplus ∈ [(:(==), \"EQ\"), (:∧, \"LAND\"), (:∨, \"LOR\"), (:lxor, \"LXOR\")]\n    for otimes ∈ [\n        (:(==), \"EQ\"),\n        (:(>=), \"GE\"),\n        (:(>), \"GT\"),\n        (:(<=), \"LE\"),\n        (:(<), \"LT\"),\n        (:(!=), \"NE\"),\n        (:first, \"FIRST\"),\n        (:second, \"SECOND\"),\n        (:∧, \"LAND\"),\n        (:∨, \"LOR\"),\n        (:lxor, \"LXOR\"),\n        (:pair, \"PAIR\")\n    ]\n    rig = Symbol(oplus[2], \"_\", otimes[2])\n    funcquote = quote\n        Semirings.Semiring(::typeof($(oplus[1])), ::typeof($(otimes[1]))) = $rig\n        addop(::typeof($rig)) = $(oplus[1])\n        mulop(::typeof($rig)) = $(otimes[1])\n    end\n    @eval($funcquote)\n    end\nend\n\n#Select Ops\n\n\"\"\"\n    select(SuiteSparseGraphBLAS.TRIL, A, k=0)\n    select(tril, A, k=0)\n\nSelect the entries on or below the `k`th diagonal of A.\n\nSee also: `LinearAlgebra.tril`\n\"\"\"\nTRIL\nSelectOp(::typeof(LinearAlgebra.tril)) = TRIL\n\"\"\"\n    select(SuiteSparseGraphBLAS.TRIU, A, k=0)\n    select(triu, A, k=0)\n\nSelect the entries on or above the `k`th diagonal of A.\n\nSee also: `LinearAlgebra.triu`\n\"\"\"\nTRIU\nSelectOp(::typeof(LinearAlgebra.triu)) = TRIU\n\"\"\"\n    select(DIAG, A, k=0)\n\nSelect the entries on the `k`th diagonal of A.\n\nSee also: `LinearAlgebra.diag`\n\"\"\"\nDIAG\nSelectOp(::typeof(LinearAlgebra.diag)) = DIAG\n\"\"\"\n    select(OFFDIAG, A, k=0)\n\nSelect the entries **not** on the `k`th diagonal of A.\n\"\"\"\nOFFDIAG\nSelectOp(::typeof(offdiag)) = OFFDIAG\n\"\"\"\n    select(NONZERO, A)\n    select(nonzeros, A)\nSelect all entries in A with nonzero value.\n\"\"\"\nNONZERO\nSelectOp(::typeof(nonzeros)) = NONZERO\n\n# I don't believe these should have Julia equivalents.\n# Instead select(==, A, 0) will find EQ_ZERO internally.\n\"\"\"\n    select(EQ_ZERO, A)\n\nSelect all entries in A equal to zero.\n\"\"\"\nEQ_ZERO\n\"\"\"\n    select(GT_ZERO, A)\n\nSelect all entries in A greater than zero.\n\"\"\"\nGT_ZERO\n\"\"\"\n    select(GE_ZERO, A)\n\nSelect all entries in A greater than or equal to zero.\n\"\"\"\nGE_ZERO\n\"\"\"\n    select(LT_ZERO, A)\n\nSelect all entries in A less than zero.\n\"\"\"\nLT_ZERO\n\"\"\"\n    select(LE_ZERO, A)\n\nSelect all entries in A less than or equal to zero.\n\"\"\"\nLE_ZERO\n\"\"\"\n    select(NE, A, k)\n    select(!=, A, k)\nSelect all entries not equal to `k`.\n\"\"\"\nNE\nSelectOp(::typeof(!=)) = NE\n\"\"\"\n    select(EQ, A, k)\n    select(==, A, k)\nSelect all entries equal to `k`.\n\"\"\"\nEQ\nSelectOp(::typeof(==)) = EQ\n\"\"\"\n    select(GT, A, k)\n    select(>, A, k)\nSelect all entries greater than `k`.\n\"\"\"\nGT\nSelectOp(::typeof(>)) = GT\n\"\"\"\n    select(GE, A, k)\n    select(>=, A, k)\nSelect all entries greater than or equal to `k`.\n\"\"\"\nGE\nSelectOp(::typeof(>=)) = GE\n\"\"\"\n    select(LT, A, k)\n    select(<, A, k)\nSelect all entries less than `k`.\n\"\"\"\nLT\nSelectOp(::typeof(<)) = LT\n\"\"\"\n    select(LE, A, k)\n    select(<=, A, k)\nSelect all entries less than or equal to `k`.\n\"\"\"\nLE\nSelectOp(::typeof(<=)) = LE\n", "meta": {"hexsha": "a13a892fa86cc084fe745a6fd4d840a4ac5229d2", "size": 22624, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operators/oplist.jl", "max_stars_repo_name": "JuliaSparse/SuiteSparseGraphBLAS.jl", "max_stars_repo_head_hexsha": "73466763044fb8a8c80c92180b294c482440c2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2021-05-29T03:03:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T21:00:48.000Z", "max_issues_repo_path": "src/operators/oplist.jl", "max_issues_repo_name": "JuliaSparse/SuiteSparseGraphBLAS.jl", "max_issues_repo_head_hexsha": "73466763044fb8a8c80c92180b294c482440c2b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2021-05-21T21:59:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T23:34:24.000Z", "max_forks_repo_path": "src/operators/oplist.jl", "max_forks_repo_name": "abhinavmehndiratta/SuiteSparseGraphBLAS.jl", "max_forks_repo_head_hexsha": "73466763044fb8a8c80c92180b294c482440c2b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-06-08T15:44:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-18T23:38:35.000Z", "avg_line_length": 24.1194029851, "max_line_length": 101, "alphanum_fraction": 0.6448903819, "num_tokens": 7985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7819308534858898}}
{"text": "###############################################################################\n#\n# nanmean, nanmedian, nanstd, nanmax, nanmin\n#\n###############################################################################\n\"\"\"\n\n    nanmax(x::Array)\n\nReturn the maximum of array ommiting the NaN, given\n- `x` Array of numbers, can be NaN\n\n---\nExample\n```julia\nxs = [1, 2, 4, NaN];\nnmax = nanmax(xs);\n```\n\"\"\"\nfunction nanmax(x::Array)\n    _x = filter(!isnan, x);\n\n    if length(_x) == 0 return NaN end;\n\n    return maximum( _x )\nend\n\n\n\n\n\"\"\"\n\n    nanmean(x::Array)\n\nReturn the mean of array by ommiting the NaN, given\n- `x` Array of numbers, can be NaN\n\n---\nExample\n```julia\nxs = [1, 2, 4, NaN];\nnmean = nanmean(xs);\n```\n\"\"\"\nfunction nanmean(x::Array)\n    _x = filter(!isnan, x);\n\n    if length(_x) == 0 return NaN end;\n\n    return mean( _x )\nend\n\n\n\n\n\"\"\"\n\n    nanmedian(x::Array)\n\nReturn the median of array by ommiting the NaN, given\n- `x` Array of numbers, can be NaN\n\n---\nExample\n```julia\nxs = [1, 2, 4, NaN];\nnmed = nanmedian(xs);\n```\n\"\"\"\nfunction nanmedian(x::Array)\n    _x = filter(!isnan, x);\n\n    if length(_x) == 0 return NaN end;\n\n    return median( _x )\nend\n\n\n\n\n\"\"\"\n\n    nanmin(x::Array)\n\nReturn the maximum of array ommiting the NaN, given\n- `x` Array of numbers, can be NaN\n\n---\nExample\n```julia\nxs = [1, 2, 4, NaN];\nnmin = nanmin(xs);\n```\n\"\"\"\nfunction nanmin(x::Array)\n    _x = filter(!isnan, x);\n\n    if length(_x) == 0 return NaN end;\n\n    return minimum( _x )\nend\n\n\n\n\n\"\"\"\n\n    nanpercentile(x::Array, p::Number)\n\nReturn the percentile by excluding the NaN of given\n- `x` Array of data\n- `p` Percentile\n\n---\nExample\n```julia\nxs = rand(100);\npth = nanpercentile(rand(100), 50);\nxs[1:10] .= NaN;\npth = nanpercentile(rand(100), 50);\n```\n\"\"\"\nfunction nanpercentile(x::Array, p::Number)\n    @assert 0 <= p <= 100\n\n    _x = filter(!isnan, x);\n\n    if length(_x) == 0 return NaN end;\n\n    return percentile( _x, p )\nend\n\n\n\n\n\"\"\"\n\n    nanstd(x::Array)\n\nReturn the std of array by ommiting the NaN, given\n- `x` Array of numbers, can be NaN\n\n---\nExample\n```julia\nxs = [1, 2, 4, NaN];\nnstd = nanstd(xs);\n```\n\"\"\"\nfunction nanstd(x::Array)\n    _x = filter(!isnan, x);\n\n    if length(_x) == 0 return NaN end;\n\n    return std( _x )\nend\n\n\n\n\n\n\n\n\n###############################################################################\n#\n# Error measures\n#\n###############################################################################\n\"\"\"\n\n    mae(y::Array, pred::Array)\n\nReturn the mean absolute error by ommiting the NaN, given\n- `y` Array of numbers, can be NaN\n- `pred` Array of predictions, can be NaN\n\n---\nExample\n```julia\nys = [1, 2, 4, NaN];\npreds = [2, 4, 1, NaN];\nnmae = mae(ys, preds);\n```\n\"\"\"\nfunction mae(y::Array, pred::Array)\n    return nanmean( abs.(y .- pred) )\nend\n\n\n\n\n\"\"\"\n\n    mape(y::Array, pred::Array)\n\nReturn the mean absolute percentage error by ommiting the NaN, given\n- `y` Array of numbers, can be NaN\n- `pred` Array of predictions, can be NaN\n\n---\nExample\n```julia\nys = [1, 2, 4, NaN];\npreds = [2, 4, 1, NaN];\nnmape = mape(ys, preds);\n```\n\"\"\"\nfunction mape(y::Array, pred::Array)\n    _mean = abs( nanmean(y) );\n    _diff = abs.(y .- pred) ./ _mean .* 100;\n\n    return nanmean( _diff )\nend\n\n\n\n\n\"\"\"\n\n    mase(y::Array, pred::Array)\n\nReturn the mean absolute standardized error by ommiting the NaN, given\n- `y` Array of numbers, can be NaN\n- `pred` Array of predictions, can be NaN\n\n---\nExample\n```julia\nys = [1, 2, 4, NaN];\npreds = [2, 4, 1, NaN];\nnmase = mase(ys, preds);\n```\n\"\"\"\nfunction mase(y::Array, pred::Array)\n    _nstd = nanstd(y);\n    _diff = abs.(y .- pred) ./ _nstd .* 100;\n\n    return nanmean( _diff )\nend\n\n\n\n\n\"\"\"\n\n    rmse(y::Array, pred::Array)\n\nReturn the root mean square error by ommiting the NaN, given\n- `y` Array of numbers, can be NaN\n- `pred` Array of predictions, can be NaN\n\n---\nExample\n```julia\nys = [1, 2, 4, NaN];\npreds = [2, 4, 1, NaN];\nrmse = rmse(ys, preds);\n```\n\"\"\"\nfunction rmse(y::Array, pred::Array)\n    return sqrt( nanmean( (y .- pred) .^ 2 ) )\nend\n", "meta": {"hexsha": "1a69ff5fd0f837b5f35514e1c59ca4ed90c98b5b", "size": 3985, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/statistics.jl", "max_stars_repo_name": "Yujie-W/PkgUtility.jl", "max_stars_repo_head_hexsha": "aaf056fc29ce9bb3aafac51b324dd13cb84fc361", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-05T21:19:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T16:55:33.000Z", "max_issues_repo_path": "src/math/statistics.jl", "max_issues_repo_name": "Yujie-W/PkgUtility.jl", "max_issues_repo_head_hexsha": "aaf056fc29ce9bb3aafac51b324dd13cb84fc361", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-11-24T19:10:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T22:34:17.000Z", "max_forks_repo_path": "src/math/statistics.jl", "max_forks_repo_name": "Yujie-W/PkgUtility.jl", "max_forks_repo_head_hexsha": "aaf056fc29ce9bb3aafac51b324dd13cb84fc361", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.0946969697, "max_line_length": 79, "alphanum_fraction": 0.5515683814, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.781930851518423}}
{"text": "\"\"\"\n    schottky_genus_4(τ)\n\nCompute the value of the genus 4 Schottky-Igusa polynomial, given as input a 4x4 matrix in the Siegel upper half space.\n\"\"\"\nfunction schottky_genus_4(τ::Array{<:Number})\n    R = RiemannMatrix(τ, siegel=false, ϵ=1.0e-10, nderivs=0);\n    m1 = [[1,0,1,0], [1,0,1,0]];\n    m2 = [[0,0,0,1], [1,0,0,0]];\n    m3 = [[0,0,1,1], [1,0,1,1]];\n    n1 = [[0,0,0,1], [1,1,1,0]];\n    n2 = [[0,0,1,1], [0,0,0,1]];\n    n3 = [[0,0,1,0], [1,0,1,1]];\n    p1 = 1;\n    p2 = 1;\n    p3 = 1;\n    z = [0; 0; 0; 0];\n    for i1=0:1, i2=0:1, i3=0:1\n        n = i1*n1 + i2*n2 + i3*n3;\n        c1 = theta(z, R, char=remainder_char(m1+n));\n        c2 = theta(z, R, char=remainder_char(m2+n));\n        c3 = theta(z, R, char=remainder_char(m3+n));\n        p1 *= c1;\n        p2 *= c2;\n        p3 *= c3;\n    end\n    schottky_poly = p1^2 + p2^2 + p3^2 - 2*p1*p2 - 2*p1*p3 - 2*p2*p3;\n    return schottky_poly\nend\n\n\"\"\"\n    random_nonschottky_genus_4(tol=0.1, trials=100)\n\nFind a random 4x4 matrix in the Siegel upper half space which is not in the Schottky locus, up to the input tolerance and number of trials.\n\"\"\"\nfunction random_nonschottky_genus_4(tol::Real=0.1, trials::Integer=100)\n    t = 0; # largest value of schottky polynomial\n    i = 0; # counter for number of trials\n    max_matrix = rand(4,4); # stores best non-schottky candidate\n    while t < tol && i < trials\n        τ = random_siegel(4);\n        s = schottky_genus_4(τ);\n        if abs(s) > t\n            t = abs(s)\n            max_matrix = τ;\n        end\n        i += 1;\n    end\n    return [max_matrix, t];\nend\n\n", "meta": {"hexsha": "f90ef1c8ff2c4cb6fccc4f11577bef9968e50a1c", "size": 1571, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/schottky4.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Theta.jl-42bdb5c4-78fb-11e9-2233-215979c148c4", "max_stars_repo_head_hexsha": "a34991260be574b5d556a53a2acf59037d4459df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/schottky4.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Theta.jl-42bdb5c4-78fb-11e9-2233-215979c148c4", "max_issues_repo_head_hexsha": "a34991260be574b5d556a53a2acf59037d4459df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/schottky4.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Theta.jl-42bdb5c4-78fb-11e9-2233-215979c148c4", "max_forks_repo_head_hexsha": "a34991260be574b5d556a53a2acf59037d4459df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2115384615, "max_line_length": 139, "alphanum_fraction": 0.5544239338, "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7819050674281371}}
{"text": "# -- PRIVATE METHODS --------------------------------------------------------------------------------------------------- #\n# ---------------------------------------------------------------------------------------------------------------------- #\n\n# -- PUBLIC METHODS ---------------------------------------------------------------------------------------------------- #\nfunction compute_exponential_moving_average(data::DataFrame, startDate::Date, delay::Int64; \n    timestampColKeySymbol::Symbol=Symbol(\"timestamp\"), dataColKeySymbol::Symbol=Symbol(\"adjusted_close\"))::PSResult\n\n    # initialize -\n    price_array = Array{Float64,1}()\n    exponential_moving_average = Array{Float64,1}()\n\n    # check: delay is non-negative?\n    if (delay < 0)\n        return PSResult(ArgumentError(\"delay parameter must be non-negative\"))\n    end\n\n    # check: find the index of this date -\n    idx_start_date = findfirst(x -> x == startDate, data[!, timestampColKeySymbol])\n    if (idx_start_date === nothing)\n        return PSResult(ArgumentError(\"the start date is not contained in the data set\"))\n    end\n\n    try\n\n        # populate the price array -\n        (number_of_days, number_of_cols) = size(data)\n        for index = idx_start_date:number_of_days\n            value = data[index,dataColKeySymbol]\n            push!(price_array, value)\n        end\n\n        # compute the SMA (start point) -\n        tmp_array = Array{Float64,1}()\n        for index = 1:delay\n            value = price_array[index]\n            push!(tmp_array, value)\n        end\n        SMA = mean(tmp_array)\n\n        # what is the weight parameter -\n        ω = 2.0 / (delay + 1.0)\n\n        # compute -\n        push!(exponential_moving_average, SMA)\n        for index = 1:number_of_days\n\n            price_value = price_array[index]\n            EMA_old = exponential_moving_average[index]\n            EMA_new = ω * price_value + (1.0 - ω) * EMA_old\n            push!(exponential_moving_average, EMA_new)\n        end\n\n        # return -\n        return PSResult(exponential_moving_average)\n    catch error\n        return PSResult(error)\n    end\nend\n\nfunction compute_fibonacci_retracement_levels(data::DataFrame; \n    dataColKeySymbol::Symbol=Symbol(\"adjusted_close\"))::PSResult\n\n    # initialize -\n    fnrl_array = zeros(7, 2)\n    fn_array = [0.0 0.236 0.382 0.5 0.618 0.786 1.0];\n\n    try\n\n        # find the min and the max in the data being passed in -\n        min_value = minimum(data[!,dataColKeySymbol])\n        max_value = maximum(data[!,dataColKeySymbol])\n        𝝙 = max_value - min_value\n\n        # compute the levels -\n        for (index, level) in enumerate(fn_array)\n            tmp = max_value - 𝝙 * level\n            fnrl_array[index,1] = level\n            fnrl_array[index,2] = tmp\n        end\n\n        # return -\n        return PSResult{Array{Float64,2}}(fnrl_array)\n    catch error\n        return PSResult(error)\n    end\nend\n# ---------------------------------------------------------------------------------------------------------------------- #", "meta": {"hexsha": "948abc5ddc2bf40c07f227a8f39370f7c4140431", "size": 3026, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/base/Technical.jl", "max_stars_repo_name": "Pooksoft/PooksoftAssetModelingKit.jl", "max_stars_repo_head_hexsha": "9be23efe332570960197d464e9e8cf5f35326b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-11T07:33:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T07:33:43.000Z", "max_issues_repo_path": "src/base/Technical.jl", "max_issues_repo_name": "Pooksoft/PooksoftAssetModelingKit.jl", "max_issues_repo_head_hexsha": "9be23efe332570960197d464e9e8cf5f35326b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/base/Technical.jl", "max_forks_repo_name": "Pooksoft/PooksoftAssetModelingKit.jl", "max_forks_repo_head_hexsha": "9be23efe332570960197d464e9e8cf5f35326b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-05T17:59:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T17:59:06.000Z", "avg_line_length": 34.7816091954, "max_line_length": 122, "alphanum_fraction": 0.529742234, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7817707871736056}}
{"text": "# project x1 on to x2\nproject(x1, x2) = (x1' * x2) / (x2' * x2) * x2\n\n# compute intercept and slope from two points\nfunction get_coefs(x1, x2)\n     β1 = (x2[2] - x1[2]) / (x2[1] - x1[1])\n     return x2[2] - β1 * x2[1], β1\nend\n \n# make a line \nmake_line(β0, β1, x) = β0 .+ β1 .* x ", "meta": {"hexsha": "a4a8072a63e5db83377c4391f6718727c9255753", "size": 280, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/snooker_plot/functions.jl", "max_stars_repo_name": "itsdfish/DifferentialEvolutionMCMC.jl", "max_stars_repo_head_hexsha": "3974509006e3df0eef74cf82be71586f2045d421", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-06-22T07:03:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T06:47:34.000Z", "max_issues_repo_path": "test/snooker_plot/functions.jl", "max_issues_repo_name": "itsdfish/DifferentialEvolutionMCMC.jl", "max_issues_repo_head_hexsha": "3974509006e3df0eef74cf82be71586f2045d421", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 40, "max_issues_repo_issues_event_min_datetime": "2020-05-28T11:51:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T11:59:22.000Z", "max_forks_repo_path": "test/snooker_plot/functions.jl", "max_forks_repo_name": "itsdfish/DifferentialEvolutionMCMC.jl", "max_forks_repo_head_hexsha": "3974509006e3df0eef74cf82be71586f2045d421", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4545454545, "max_line_length": 46, "alphanum_fraction": 0.5535714286, "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7817707836661023}}
{"text": "immutable State\n    intercept::Float64\n    slope::Float64\nend\n\nimmutable Datum\n    x::Float64\n    y::Float64\nend\n\nimmutable LinregMHSampler <: Sampler\n    num_steps::Int\n    prior_std::Float64\n    noise_std::Float64\n    data::Array{Datum,1}\n    function LinregMHSampler(x::Array{Float64,1}, y::Array{Float64,1}, \n                            prior_std::Float64, noise_std::Float64, num_steps::Int)\n        @assert length(x) == length(y)\n        data = Array{Datum,1}()\n        for (xi, yi) in zip(x, y)\n            push!(data, Datum(xi, yi))\n        end\n        new(num_steps, prior_std, noise_std, data)\n    end\nend\n\nfunction prior_sample(sampler::LinregMHSampler)\n    intercept = rand(Normal(0., sampler.prior_std))\n    slope = rand(Normal(0., sampler.prior_std))\n    State(intercept, slope)\nend\n\nfunction log_prior(sampler::LinregMHSampler, state::State)\n    lp = logpdf(Normal(0., sampler.prior_std), state.intercept)\n    lp += logpdf(Normal(0., sampler.prior_std), state.slope)\n    lp\nend\n\nfunction log_likelihood(sampler::LinregMHSampler, state::State)\n    ll = 0.0\n    for datum in sampler.data\n        y_expected = state.intercept + state.slope * datum.x\n        ll += logpdf(Normal(y_expected, sampler.noise_std), datum.y)\n    end\n    ll  \nend\n\nfunction log_unnormalized_posterior(sampler::LinregMHSampler, state::State)\n    log_prior(sampler, state) + log_likelihood(sampler, state)\nend\n\nfunction imh_step(sampler::LinregMHSampler, state::State)\n    # perform one step of independent MH\n    # propose from prior\n    state_proposed = prior_sample(sampler)\n    if log(rand()) <= log_likelihood(sampler, state_proposed) - log_likelihood(sampler, state)\n        # accept\n        new_state = state_proposed\n    else\n        # reject\n        new_state = state\n    end\n    new_state\nend\n\nfunction run_markov_chain(sampler::LinregMHSampler, state::State, steps::Int)\n    for step in 1:steps\n        state = imh_step(sampler, state)\n    end\n    state\nend\n\nfunction run_inference(sampler::LinregMHSampler)\n    init_state = prior_sample(sampler)\n    state = run_markov_chain(sampler, init_state, sampler.num_steps)\n    # returns the initial and final state of the Markov chain\n    # the initial state is all we need from the trace\n    return (init_state, state)\nend\n\nfunction log_weight(sampler::LinregMHSampler, init_state::State, output::State)\n    lw = 0.\n    lw += log_prior(sampler, init_state) \n    lw += log_unnormalized_posterior(sampler, output)\n    lw -= log_unnormalized_posterior(sampler, init_state)\n    lw\nend\n\nfunction simulate(sampler::LinregMHSampler)\n    (init_state, state) = run_inference(sampler)\n    ([state.intercept, state.slope], log_weight(sampler, init_state, state))\nend\n\nfunction regenerate(sampler::LinregMHSampler, intercept_and_slope::Array{Float64,1})\n    @assert length(intercept_and_slope) == 2\n    intercept, slope = intercept_and_slope\n    state = State(intercept, slope)\n    init_state = run_markov_chain(sampler, state, sampler.num_steps)\n    log_weight(sampler, init_state, state)\nend\n\n\nimmutable PriorSampler <: Sampler\n    x::Array{Float64,1}\n    y::Array{Float64,1}\n    prior_std::Float64\n    noise_std::Float64\nend\n\nfunction simulate(sampler::PriorSampler)\n    dist = Normal(0., sampler.prior_std)\n    intercept = rand(dist)\n    slope = rand(dist)\n    ([intercept, slope], logpdf(dist, intercept) + logpdf(dist, slope))\nend\n\nfunction regenerate(sampler::PriorSampler, intercept_and_slope::Array{Float64,1})\n    (intercept, slope) = intercept_and_slope\n    dist = Normal(0., sampler.prior_std)\n    logpdf(dist, intercept) + logpdf(dist, slope)\nend\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "5d810f69491da640da481bba8b376373ee6dd50e", "size": 3597, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear_regression/mcmc.jl", "max_stars_repo_name": "probcomp/nips2017-aide-experiments", "max_stars_repo_head_hexsha": "5c499b297ded992c776cee4268b7152075bcd2e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-12-05T20:19:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-09T19:29:04.000Z", "max_issues_repo_path": "linear_regression/mcmc.jl", "max_issues_repo_name": "probcomp/nips2017-aide-experiments", "max_issues_repo_head_hexsha": "5c499b297ded992c776cee4268b7152075bcd2e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_regression/mcmc.jl", "max_forks_repo_name": "probcomp/nips2017-aide-experiments", "max_forks_repo_head_hexsha": "5c499b297ded992c776cee4268b7152075bcd2e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6692307692, "max_line_length": 94, "alphanum_fraction": 0.699471782, "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7817707836115556}}
{"text": "export sbesselj, shankelh1, diffsbessel, diffbessel\nexport diffbesselj, diffhankelh1, diffsbesselj, diffshankelh1\nexport gaunt_coefficient\nexport associated_legendre_indices, spherical_harmonics_indices, lm_to_spherical_harmonic_index\nexport spherical_harmonics\nexport cartesian_to_radial_coordinates, radial_to_cartesian_coordinates\nexport atan\n\n#NOTE spherical bessel and hankel functions soon coming to SpecialFunctions.jl https://github.com/JuliaMath/SpecialFunctions.jl/pull/196\n\n#NOTE atan(x,y) is defined here but will likely be added to base soon.\n\nimport Base.atan\natan(y::Complex,x::Complex) = - im * log( (x+y*im) / sqrt(x^2+y^2) )\n\n\"\"\"\n    sbesselj(m,x)\n\nReturns the spherical besselj function. The order is 'm' and the argument is 'x'. Note 'x' can be a complex number.\n\"\"\"\n# function sbesselj(m::Number,x::T) where T<: Union{F,Complex{F}} where F <: AbstractFloat\n    # if (abs(x) > eps(F))\n    #     return sqrt(pi/(T(2)*x)) * besselj(m+1/2,x)\n    # else\n    #     return (m > 0 ? zero(T) : one(T))\n    # end\n# end\nfunction sbesselj(nu::Number, x::T) where {T}\n    besselj_nuhalf_x = besselj(nu + one(nu)/2, x)\n    if abs(x) ≤ sqrt(eps(real(zero(besselj_nuhalf_x))))\n        nu == 0 ? one(besselj_nuhalf_x) : zero(besselj_nuhalf_x)\n    else\n        √((float(T))(π)/2x) * besselj_nuhalf_x\n    end\nend\n\n\"\"\"\n    shankelh1(m,x)\n\nReturns the spherical hankel function of the first kind. The order is 'm' and the argument is 'x'. Note 'x' can be a complex number.\n\"\"\"\nshankelh1(nu::Number,x::T) where T = √((float(T))(π)/2x) * hankelh1(nu+one(nu)/2,x)\n\n\"\"\"\n    diffsbessel(f::Function,m,x)\n\nDifferentiates the spherical bessel function 'f' (for any spherical bessel). The order is 'm' and the argument is 'x'. Note 'x' can be a complex number.\n\"\"\"\nfunction diffsbessel(f::Function,n::Number,z::Number)\n    return f(n-1,z) - (n+1) * f(n,z) / z\nend\n\nfunction diffsbesselj(n::Number,z::Number)\n    return if n == 0\n        - sbesselj(1,z) # case due to numerical stability\n    else\n        sbesselj(n-1,z) - (n+1) * sbesselj(n,z) / z\n    end\nend\n\nfunction diffshankelh1(n::Number,z::Number)\n    return shankelh1(n-1,z) - (n+1) * shankelh1(n,z) / z\nend\n\n\"\"\"\n    diffbessel(f::Function,m,x,n::Int)\n\nDifferentiates 'n' times any bessel function 'f' of order 'm' and at the argument 'x'.\n\"\"\"\nfunction diffbessel(f::Function,m::Number,z,n::Int)\n    if n == 0\n        return f(m, z)\n    elseif n > 0\n        n = n - 1\n        return 0.5*(diffbessel(f,m-1,z,n) - diffbessel(f,m+1,z,n))\n    else\n        error(\"Can not differentiate a negative number of times\")\n    end\nend\n\n\n\"\"\"\n    diffhankelh1(m,x,n::Int)\n\nDifferentiates 'n' times the hankelh1 function of order 'm' and at the argument 'x'.\n\"\"\"\nfunction diffhankelh1(m::Number,z::T,n::Int) where T<:Number\n    if n == 0\n        return hankelh1(m, z)\n    elseif n > 0\n        n = n - 1\n        return 0.5*(diffhankelh1(m-1,z,n) - diffhankelh1(m+1,z,n))\n    else\n        error(\"Can not differentiate a negative number of times\")\n    end\nend\n\n\"Derivative of Hankel function of the first kind\"\ndiffhankelh1(n,z) = 0.5*(hankelh1(-1 + n, z) - hankelh1(1 + n, z))\n\n\"Derivative of Bessel function of first kind\"\ndiffbesselj(n::Number,z::T) where T<:Number = 0.5*(besselj(-1 + n, z) - besselj(1 + n, z))\n\n\"m-th Derivative of Hankel function of the first kind\"\nfunction diffbesselj(n::Number,z::T,m::Int) where T<:Number\n    if m == 0\n        return besselj(n, z)\n    elseif m > 0\n        m = m - 1\n        return T(0.5)*(diffbesselj(n-1,z,m) - diffbesselj(n+1,z,m))\n    else\n        error(\"Can not differentiate a negative number of times\")\n    end\nend\n\n\n\"\"\"\n    gaunt_coefficient(l1,m1,l2,m2,l3,m3)\n\nA version of the Gaunt coefficients which are used to write the product of two spherical harmonics. If Y_{l,m} is a complex spherical harmonic, with the typical phase conventions from quantum mechanics, then:\n\n    gaunt_coefficient(l1,m1,l2,m2,l3,m3) = 4*π*im^{l2+l3-l1} Integral[Y_{l1,m1}*conj(Y_{l2,m2})*conj(Y_{l3,m3})]\n\nwhere the integral is over the solid angle.\n\nThe most standard gaunt coefficients `G(l1,m1;l2,m2;l3)` are related through the identity:\n\n    4pi * G(l1,m1;l2,m2;l3) = im^(l1-l2-l3) * (-1)^m2 * gaunt_coefficient(l1,m1,l2,-m2,l3,m1+m2)\n\n\"\"\"\nfunction gaunt_coefficient(T::Type{<:AbstractFloat},l1::Int,m1::Int,l2::Int,m2::Int,l3::Int,m3::Int)\n    # note the wigner3j has only one convention, and is highly symmetric.\n    return (one(T)*im)^(l2+l3-l1) * (-T(1))^m1 * sqrt(4pi*(2*l1+1)*(2*l2+1)*(2*l3+1)) *\n        wigner3j(T,l1,l2,l3,0,0,0) * wigner3j(T,l1,l2,l3,m1,-m2,-m3)\nend\ngaunt_coefficient(l1::Int,m1::Int,l2::Int,m2::Int,l3::Int,m3::Int) = gaunt_coefficient(Float64,l1,m1,l2,m2,l3,m3)\n\nlm_to_spherical_harmonic_index(l::Int,m::Int)::Int = l^2 + m + l + 1\n\nfunction spherical_harmonics_indices(l_max::Int)\n    ls = [l for l in 0:l_max for m in -l:l]\n    ms = [m for l in 0:l_max for m in -l:l]\n\n    return ls, ms\nend\n\nfunction associated_legendre_indices(l_max::Int)\n    ls = [l for l in 0:l_max for m in 0:l]\n    ms = [m for l in 0:l_max for m in 0:l]\n\n    return ls, ms\nend\n\n\"\"\"\n`spherical_harmonics(l_max::Int, θ::T, φ::T)`\n\nreturns a vector of all spherical harmonics with degree `l <= l_max`. The degree and order (indices) of the elements of the vector are given by `spherical_harmonics_indices(l_max::Int)`.\n\nThe associated legendre polynomials are taken from the package GSL.jl.\n\"\"\"\nfunction spherical_harmonics(l_max::Int, θ::Complex{T}, φ::Union{T,Complex{T}}) where T <: AbstractFloat\n\n    throw(DomainError(θ, \"Currently GLS.jl is used to calculate associated legendre polynomials, which only take real angles as arguments. Hopefully soon SpecialFunctions.jl will implement associated Legendre for complex arguments: https://github.com/JuliaMath/SpecialFunctions.jl/pull/175\"))\n\nend\nfunction spherical_harmonics(l_max::Int, θ::T, φ::T) where T <: AbstractFloat\n\n    ls, ms = associated_legendre_indices(l_max)\n    Plm_arr = sf_legendre_array(GSL_SF_LEGENDRE_SPHARM, l_max, cos(θ))[eachindex(ls)]\n\n    Ylm_vec = Vector{Complex{T}}(undef, (l_max+1)^2)\n    Ylm_vec[1] = Plm_arr[1]\n\n    ind1 = 1\n    ind2 = 1\n    for i = 1:l_max\n        inds1 = (ind1+i):(ind1+2i)\n        Ylm_vec[(ind2+i):(ind2+3i)] = [reverse((-1).^ms[inds1[2:end]] .* conj(Plm_arr[inds1[2:end]])); Plm_arr[inds1]]\n        ind1 += i\n        ind2 += 2i\n    end\n\n    ls, ms = spherical_harmonics_indices(l_max)\n    Ylm_vec = (-one(T)) .^ ms .* exp.(ms .* (im*φ)) .* Ylm_vec\n\n    return Ylm_vec\nend\n\ncartesian_to_radial_coordinates(x::Vector) = cartesian_to_radial_coordinates(SVector(x...))\nradial_to_cartesian_coordinates(θ::Vector) = radial_to_cartesian_coordinates(SVector(θ...))\n\nfunction cartesian_to_radial_coordinates(x::SVector{3,CT}) where CT\n    r = sqrt(sum(x .^2)) # note this is, and should be, a complex number when x is a complex vector\n    θ = atan(sqrt(x[1]^2+x[2]^2),x[3])\n    φ = (!iszero(x[1]) || !iszero(x[2])) ? atan(x[2], x[1]) : zero(CT)\n    return [r,θ,φ]\nend\n\nfunction cartesian_to_radial_coordinates(x::SVector{2,CT}) where CT\n    r = sqrt(sum(x .^2)) # note this should be complex if x is complex\n    θ = atan(x[2], x[1])\n    return [r,θ]\nend\n\nfunction radial_to_cartesian_coordinates(rθφ::SVector{3,CT}) where CT\n    r, θ, φ = rθφ\n    x = r * sin(θ) * cos(φ)\n    y = r * sin(θ) * sin(φ)\n    z = r * cos(θ)\n\n    return [x,y,z]\nend\n\nfunction radial_to_cartesian_coordinates(rθ::SVector{2,CT}) where CT\n    r, θ = rθ\n    x = r * cos(θ)\n    y = r * sin(θ)\n\n    return [x,y]\nend\n", "meta": {"hexsha": "cf906f9ee3517bf4f14634a5d3ffe123f4079108", "size": 7448, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/physics/special_functions.jl", "max_stars_repo_name": "andyDoucette/MultipleScattering.jl", "max_stars_repo_head_hexsha": "5f076c1049dddaa7c1c7d73ab8f18b4090eab350", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2020-03-26T17:23:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T21:53:10.000Z", "max_issues_repo_path": "src/physics/special_functions.jl", "max_issues_repo_name": "andyDoucette/MultipleScattering.jl", "max_issues_repo_head_hexsha": "5f076c1049dddaa7c1c7d73ab8f18b4090eab350", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2017-11-10T09:10:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-05T15:14:27.000Z", "max_forks_repo_path": "src/physics/special_functions.jl", "max_forks_repo_name": "andyDoucette/MultipleScattering.jl", "max_forks_repo_head_hexsha": "5f076c1049dddaa7c1c7d73ab8f18b4090eab350", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-02-19T11:17:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T10:51:53.000Z", "avg_line_length": 33.7013574661, "max_line_length": 292, "alphanum_fraction": 0.6640708915, "num_tokens": 2562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7817707836115556}}
{"text": "module SUN_generator\r\n    using LinearAlgebra\r\n\r\n    struct Generator\r\n        NC::Int64\r\n        generator::Array{Array{ComplexF64,2},1}\r\n        function Generator(NC) \r\n            return new(NC,make_generators(NC))\r\n        end\r\n    end\r\n\r\n    function Base.getindex(g::Generator,i)\r\n        return g.generator[i]\r\n    end\r\n\r\n    function Base.length(a::Generator)\r\n        return length(a.generator)\r\n    end\r\n\r\n    function lie2matrix!(matrix,g::Generator,a)\r\n        matrix .= 0\r\n        NC = g.NC\r\n        for (i,genmatrix) in enumerate(g.generator)\r\n            matrix .+= a[i]*genmatrix \r\n        end\r\n        return \r\n    end\r\n\r\n    function matrix2lie!(a,g::Generator,A)\r\n        for i=1:length(a)\r\n            #println(\"i = $i\")\r\n            #display(g.generator[i]*g.generator[i])\r\n            #println(\"\\t\")\r\n            #println(tr(g.generator[i]*A)/2)\r\n            a[i] = tr(g.generator[i]*A)/2\r\n        end\r\n        return\r\n    end\r\n\r\n    sigma = []\r\n    s = ComplexF64[\r\n        0 1\r\n        1 0\r\n    ]\r\n    push!(sigma,s)\r\n    s = ComplexF64[\r\n        0 -im\r\n        im 0\r\n    ]\r\n    push!(sigma,s)\r\n    s = ComplexF64[\r\n        1 0\r\n        0 -1\r\n    ]\r\n    push!(sigma,s)\r\n\r\n    function make_largematrix(σ,i,j,Nc)\r\n        λ = zeros(ComplexF64,Nc,Nc)\r\n        λ[i,i] = σ[1,1]\r\n        λ[i,j] = σ[1,2] \r\n        λ[j,i] = σ[2,1]\r\n        λ[j,j] = σ[2,2]  \r\n        return λ\r\n    end\r\n\r\n    function normalization(A)\r\n        Norm = sqrt(real(tr(A*A))/2)\r\n        #print(\"    Normalization = √\",real(tr(A*A))/2,\"= \")\r\n        #println(\"$Norm\")\r\n        return Norm\r\n    end\r\n\r\n    function make_generators(Nc)\r\n        d=[\"x\",\"y\",\"z\"]\r\n        #\r\n        lams = Array{Complex,2}[]\r\n        #\r\n        if Nc < 2\r\n            error(\"Invalid Nc=$Nc\")\r\n        end\r\n        #\r\n        # off-diagonal part\r\n        #println(\"Off diagonals\")\r\n        for i=1:Nc\r\n            for j=i+1:Nc\r\n                for a = 1:2\r\n                    #println(\"$(d[a]): i j = $i $j\")\r\n                    A = make_largematrix(sigma[a],i,j,Nc)\r\n                    #showmat(A)\r\n                    N=normalization(A)\r\n                    A = A/N\r\n                    push!(lams,A)\r\n                    #println(\" \")\r\n                end\r\n            end\r\n        end\r\n        #\r\n        # diagonal part\r\n        #println(\"diagonals\")\r\n        for a=1:Nc-1\r\n            A = zeros(ComplexF64,Nc,Nc)\r\n            for i=1:a\r\n                A[i,i] = 1\r\n            end\r\n            A[a+1,a+1] = -tr(A)\r\n            #showmat(A)\r\n            N=normalization(A)\r\n            A = A/N\r\n            push!(lams,A)\r\n            #println(\" \")\r\n        end\r\n        return lams\r\n    end\r\nend", "meta": {"hexsha": "cd39f57873102b793453dfebe9b2a948db9c67c1", "size": 2677, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SUN_generator.jl", "max_stars_repo_name": "akio-tomiya/Gaugefields.jl", "max_stars_repo_head_hexsha": "dd2180dfe54eba7826ddd45a13ab2f5a007857d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-24T14:21:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T14:21:45.000Z", "max_issues_repo_path": "src/SUN_generator.jl", "max_issues_repo_name": "akio-tomiya/Gaugefields.jl", "max_issues_repo_head_hexsha": "dd2180dfe54eba7826ddd45a13ab2f5a007857d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2022-01-18T01:51:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T01:14:03.000Z", "max_forks_repo_path": "src/SUN_generator.jl", "max_forks_repo_name": "akio-tomiya/Gaugefields.jl", "max_forks_repo_head_hexsha": "dd2180dfe54eba7826ddd45a13ab2f5a007857d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4824561404, "max_line_length": 61, "alphanum_fraction": 0.412775495, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7817707800222325}}
{"text": "\"\"\"\n    Chebyshev( xmin, xmax, nx )\n\nChebyshev nodes\n\n\"\"\"\nstruct Chebyshev <: NodesType\n\n    nx    :: Int64\n    xmin  :: Float64\n    xmax  :: Float64\n    xk    :: Vector{Float64}\n\n    function Chebyshev( xmin, xmax, nx )\n\n        xk  = zeros(Float64, nx)\n        θ = (π:-π/(nx-1):-1e-14)\n        xk  .= ((cos.(θ).+1)*(xmax-xmin))/2 .+ xmin\n        new( nx, xmin, xmax, xk )\n\n    end\n\nend\n\n", "meta": {"hexsha": "0eec9898aebc434435badf68640c2e41dc08aba6", "size": 389, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chebyshev.jl", "max_stars_repo_name": "JuliaVlasov/HermiteGF.jl", "max_stars_repo_head_hexsha": "e2591e78b08c1982e4d14101cba25c3e5de7f223", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-10-26T19:46:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T06:20:24.000Z", "max_issues_repo_path": "src/chebyshev.jl", "max_issues_repo_name": "JuliaVlasov/HermiteGF.jl", "max_issues_repo_head_hexsha": "e2591e78b08c1982e4d14101cba25c3e5de7f223", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chebyshev.jl", "max_forks_repo_name": "JuliaVlasov/HermiteGF.jl", "max_forks_repo_head_hexsha": "e2591e78b08c1982e4d14101cba25c3e5de7f223", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.56, "max_line_length": 51, "alphanum_fraction": 0.501285347, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240108164657, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7817618136077517}}
{"text": "using Statistics\nfunction fit(x; axis = 1)\n    if axis == 2\n        x = x'\n    end\n    if ndims(x) == 1\n        p = [quantile(x, 1/4), quantile(x, 1/2), quantile(x, 3/4)]\n    else\n        p = []\n        for i in 1:size(x)[2]\n            push!(p, [quantile(x[:, i], 1/4), quantile(x[:, i], 1/2), quantile(x[:, i], 3/4)])\n        end\n    end \n    return p\nend\nfunction transform(x, p; axis = 1)\n    if axis == 2\n        x = x'\n    end\n    if ndims(x) == 1\n        t = (x .- p[2]) / (p[3] - p[1])\n    else\n        t = []\n        for i in 1:size(x)[2]\n            push!(t, (x[:, i] .- p[i][2]) / (p[i][3] - p[i][1]))\n        end\n    end\n    return t\nend\nfunction inverse_transform(x, p; axis = 1)\n    if axis == 2\n        x = x'\n    end\n    if ndims(x) == 1\n        t = (x * (p[3] - p[1])) .+ p[2]\n    else \n        t = []\n        for i in 1:size(x)[2]\n            push!(t, (x[:, i][1] * (p[i][3] - p[i][1])) .+ p[i][2])\n        end\n    end \n    return t\nend\nfunction fit_transform(x; axis = 1)\n    if axis == 2\n        x = x'\n    end\n    if ndims(x) == 1\n        p = [quantile(x, 1/4), quantile(x, 1/2), quantile(x, 3/4)]\n        t = (x .- p[2]) / (p[3] - p[1])\n    else\n        t, p = [], []\n        for i in 1:size(x)[2]\n            push!(p, [quantile(x[:, i], 1/4), quantile(x[:, i], 1/2), quantile(x[:, i], 3/4)])\n            push!(t, (x[:, i] .- p[i][2]) / (p[i][3] - p[i][1]))\n        end\n    end\n    return t, p\nend\n", "meta": {"hexsha": "f34f4693afada67873eae9833ef34ca47e976122", "size": 1420, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Preprocessing/RS.jl", "max_stars_repo_name": "QGMW22/Horse.jl", "max_stars_repo_head_hexsha": "77be589dbf047a029615dde7773360ebcb5d99b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-19T13:09:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-19T13:09:53.000Z", "max_issues_repo_path": "src/Preprocessing/RS.jl", "max_issues_repo_name": "QGMW22/Horse", "max_issues_repo_head_hexsha": "77be589dbf047a029615dde7773360ebcb5d99b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-21T13:52:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-21T13:52:40.000Z", "max_forks_repo_path": "src/Preprocessing/RS.jl", "max_forks_repo_name": "QGMW22/Horse", "max_forks_repo_head_hexsha": "77be589dbf047a029615dde7773360ebcb5d99b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6666666667, "max_line_length": 94, "alphanum_fraction": 0.3943661972, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7817618121661452}}
{"text": "\n# Used \"Conjugate Bayesian analysis of the Gaussian distribution\" by Murphy as\n# a reference.  Note that there were some typos in that document so the code\n# here may not correspond exactly.\n\nstruct NormalGamma{T<:Real} <: ContinuousUnivariateDistribution\n    mu::T\n    nu::T     # scales precision of Normal\n    shape::T  \n    rate::T\n\n    function NormalGamma{T}(mu::T, nu::T, sh::T, r::T) where T<:Real\n    \tnu > zero(nu) && sh > zero(sh) && r > zero(r) || error(\"Both shape and scale must be positive\")\n    \tnew(T(mu), T(nu), T(sh), T(r))\n    end\nend\n\nfunction NormalGamma(mu::Real, nu::Real, sh::Real, r::Real)\n    T = promote_type(typeof(mu), typeof(nu), typeof(sh), typeof(r))\n    return NormalGamma{T}(T(mu),T(nu),T(sh),T(r))\nend\n\nmu(d::NormalGamma) = d.mu\nnu(d::NormalGamma) = d.nu\nshape(d::NormalGamma) = d.shape\nscale(d::NormalGamma) = 1. / d.rate\nrate(d::NormalGamma) = d.rate\n\ninsupport(::Type{NormalGamma}, x::T, tau2::T) where T<:Real = \n    isfinite(x) && zero(tau2) <= tau2 < Inf\n\n# Probably should guard agains dividing by and taking the log of 0.\nfunction pdf(d::NormalGamma, x::T, tau2::T) where T<:Real\n    Zinv = d.rate.^d.shape / gamma(d.shape) * sqrt(d.nu / (2.0*pi))\n    return Zinv * tau2.^(d.shape-0.5) * exp(-0.5*tau2*(d.nu*(x-d.mu).^2 + 2.0*d.rate))\nend\nfunction logpdf(d::NormalGamma, x::T, tau2::T) where T<:Real\n    lZinv = d.shape*log(d.rate) - lgamma(d.shape) + 0.5*(log(d.nu) - log(2.0*pi))\n    return lZinv + (d.shape-0.5)*log(tau2) - 0.5*tau2*(d.nu*(x-d.mu).^2 + 2*d.rate)\nend\n\nfunction rand(d::NormalGamma)\n    # Guard against invalid precisions\n    tau2 = rand(Gamma(d.shape, scale(d)))\n    if tau2 <= zero(Float64)\n        tau2 = eps(Float64)\n    end\n    mu = rand(Normal(d.mu, sqrt(1.0/(tau2*d.nu))))\n    return mu, tau2\nend\n", "meta": {"hexsha": "a2fa416e242095bcd2117b01191352177a95ef87", "size": 1767, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/normalgamma.jl", "max_stars_repo_name": "AlexRobson/ConjugatePriors.jl", "max_stars_repo_head_hexsha": "423608902a9a13ccdcd6cfd877b7516092e21443", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2015-07-29T02:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T03:55:56.000Z", "max_issues_repo_path": "src/normalgamma.jl", "max_issues_repo_name": "AlexRobson/ConjugatePriors.jl", "max_issues_repo_head_hexsha": "423608902a9a13ccdcd6cfd877b7516092e21443", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2015-04-30T11:00:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T13:12:33.000Z", "max_forks_repo_path": "src/normalgamma.jl", "max_forks_repo_name": "AlexRobson/ConjugatePriors.jl", "max_forks_repo_head_hexsha": "423608902a9a13ccdcd6cfd877b7516092e21443", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2015-07-28T06:48:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:14:01.000Z", "avg_line_length": 34.6470588235, "max_line_length": 100, "alphanum_fraction": 0.6332767402, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164657, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.781761807782867}}
{"text": "using LinearAlgebra\n\nfunction backtrackLineSearch(xInit, dirΔ, f, dfdx, paramA, paramB, verbose = false)\n    # Output an updated x\n\n    if verbose\n        println(\"\\nBeginning Line Search\")\n        println(\"xInit = $xInit\")\n        println(\"dirΔ = $dirΔ\")\n        println(\"objective function (current x) = $(f(xInit))\")\n        println(\"Parameters: $paramA and $paramB\")\n        println(\"Verbose = $verbose \\n\")\n    end\n\n    # First, initializae α = 1. This is the \"learning rate\"\n\n    α = 1\n    if verbose\n        print(\"Left side: \")\n        println(f(xInit + α * dirΔ))\n        print(\"Right side: \")\n        print(f(xInit))\n        print(\" + \")\n        print(paramA * α * dirΔ'dfdx(xInit))\n        print(\" = \")\n        println(f(xInit) + paramA * α * dirΔ'dfdx(xInit))\n    end\n\n    # Check the condition:\n    # f(x + alpha * dir) > f(x) + a * grad f of (alpha * delta)\n    while f(xInit + α * dirΔ) > (f(xInit) + paramA * α * (dirΔ'dfdx(xInit))[1])\n        # If the condition passes, set α to b * α\n        if verbose\n            print(\"Left side: \")\n            println(f(xInit + α * dirΔ))\n            print(\"Right side: \")\n            print(f(xInit))\n            print(\" + \")\n            print(paramA * α * dirΔ'dfdx(xInit))\n            print(\" = \")\n            println(f(xInit) + paramA * α * dirΔ'dfdx(xInit))\n        end\n\n        α = paramB * α\n\n        if verbose\n            println(α)\n        end\n    end\n\n    # the updated x is xInit - alpha * gradf(xInit)\n    xUpdated = xInit + α * dirΔ\n    # Return updated x\n    return xUpdated, α\nend\n\n\nrunTest = false\n\nif runTest\n    # Test Script\n\n    # One Dimensional Function\n    xInit1 = 600\n    fFun(x) = x^2\n    dfdx(x) = 2 * x\n    dir = -dfdx(xInit1)\n    aTest = 0.3\n    bTest = 0.707\n\n    xNew = backtrackLineSearch(xInit1, dir, fFun, dfdx, aTest, bTest, true)\n    println(\"New x = $xNew\")\n    println(\"Result should by 0.181\")\n\n\n    # Two Dimensional Function\n    xInit2 = [600, 400]\n    fFun(x) = x'x\n    dfdx(x) = 2 * x\n    dir2 = -dfdx(xInit2)\n    aTest = 0.3\n    bTest = 0.707\n\n    xNew = backtrackLineSearch(xInit2, dir2, fFun, dfdx, aTest, bTest, true)\n    println(\"New x = $xNew\")\n    println(\"Result should by 0.181\")\nend\n", "meta": {"hexsha": "3f41f5b3620b99384f99a6f2c139e59124e36a78", "size": 2192, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solver/backtrackLineSearch.jl", "max_stars_repo_name": "danineamati/TrajOptSOCPs", "max_stars_repo_head_hexsha": "3ff6f89e875d4e9d0b3ec918ceb90bb1295989af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-06T13:14:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T13:14:18.000Z", "max_issues_repo_path": "src/solver/backtrackLineSearch.jl", "max_issues_repo_name": "danineamati/TrajectoryOptimizationWithSOCPs", "max_issues_repo_head_hexsha": "3ff6f89e875d4e9d0b3ec918ceb90bb1295989af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-08-19T16:39:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-19T16:39:35.000Z", "max_forks_repo_path": "src/solver/backtrackLineSearch.jl", "max_forks_repo_name": "danineamati/TrajectoryOptimizationWithSOCPs", "max_forks_repo_head_hexsha": "3ff6f89e875d4e9d0b3ec918ceb90bb1295989af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9090909091, "max_line_length": 83, "alphanum_fraction": 0.5392335766, "num_tokens": 703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7817599971588648}}
{"text": "using FFTW, DSP\n\nconst h1 = [-8, 2, -9, -2, 9, -8, -2]\nconst f1 = [ 6, -9, -7, -5]\nconst g1 = [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10]\n\nconst h2nested = [\n      [-8, 1, -7, -2, -9, 4],\n      [4, 5, -5, 2, 7, -1],\n      [-6, -3, -3, -6, 9, 5]]\nconst f2nested = [\n      [-5, 2, -2, -6, -7],\n      [9, 7, -6, 5, -7],\n      [1, -1, 9, 2, -7],\n      [5, 9, -9, 2, -5],\n      [-8, 5, -2, 8, 5]]\nconst g2nested = [\n      [40, -21, 53, 42, 105, 1, 87, 60, 39, -28],\n      [-92, -64, 19, -167, -71, -47, 128, -109, 40, -21],\n      [58, 85, -93, 37, 101, -14, 5, 37, -76, -56],\n      [-90, -135, 60, -125, 68, 53, 223, 4, -36, -48],\n      [78, 16, 7, -199, 156, -162, 29, 28, -103, -10],\n      [-62, -89, 69, -61, 66, 193, -61, 71, -8, -30],\n      [48, -6, 21, -9, -150, -22, -56, 32, 85, 25]]\n\nconst h3nested = [\n      [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]],\n      [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]\nconst f3nested = [\n      [[-9, 5, -8], [3, 5, 1]],\n      [[-1, -7, 2], [-5, -6, 6]],\n      [[8, 5, 8],[-2, -6, -4]]]\nconst g3nested = [\n      [  [54, 42, 53, -42, 85, -72],\n         [45, -170, 94, -36, 48, 73],\n         [-39, 65, -112, -16, -78, -72],\n         [6, -11, -6, 62, 49, 8]],\n      [  [-57, 49, -23, 52, -135, 66],\n         [-23, 127, -58, -5, -118, 64],\n         [87, -16, 121, 23, -41, -12],\n         [-19, 29, 35, -148, -11, 45]],\n      [  [-55, -147, -146, -31, 55, 60],\n         [-88, -45, -28, 46, -26, -144],\n         [-12, -107, -34, 150, 249, 66],\n         [11, -15, -34, 27, -78, -50]],\n      [  [56, 67, 108, 4, 2, -48],\n         [58, 67, 89, 32, 32, -8],\n         [-42, -31, -103, -30, -23, -8],\n         [6, 4, -26, -10, 26, 12]]]\n\nfunction flatnested2d(a, siz)\n    ret = zeros(Int, prod(siz))\n    for i in 1:length(a), j in 1:length(a[1])\n        ret[siz[2] * (i - 1) + j] = a[i][j]\n    end\n    Float64.(ret)\nend\n\nfunction flatnested3d(a, siz)\n    ret = zeros(Int, prod(siz))\n    for i in 1:length(a), j in 1:length(a[1]), k in 1:length(a[1][1])\n        ret[siz[2] * siz[3] * (i - 1) + siz[3] * (j - 1) + k] = a[i][j][k]\n    end\n    Float64.(ret)\nend\n\ntopow2(siz) = map(x -> nextpow(2, x), siz)\ndeconv1d(f1, g1) = Int.(round.(deconv(Float64.(g1), Float64.(f1))))\n\nfunction deconv2d(f2, g2, xd2)\n    siz = topow2([length(g2), length(g2[1])])\n    h2 = Int.(round.(real.(ifft(fft(flatnested2d(g2, siz)) ./ fft(flatnested2d(f2, siz))))))\n    [[h2[siz[2] * (i - 1) + j] for j in 1:xd2[2]] for i in 1:xd2[1]]\nend\n\nfunction deconv3d(f3, g3, xd3)\n    siz = topow2([length(g3), length(g3[1]), length(g3[1][1])])\n    h3 = Int.(round.(real.(ifft(fft(flatnested3d(g3, siz)) ./ fft(flatnested3d(f3, siz))))))\n    [[[h3[siz[2] * siz[3] *(i - 1) + siz[3] * (j - 1) + k] for k in 1:xd3[3]]\n        for j in 1:xd3[2]] for i in 1:xd3[1]]\nend\n\ndeconvn(f, g, tup=()) = length(tup) < 2 ? deconv1d(f, g) :\n                       length(tup) == 2 ? deconv2d(f, g, tup) :\n                       length(tup) == 3 ? deconv3d(f, g, tup) :\n                       println(\"Array nesting > 3D not supported\")\n\ndeconvn(f1, g1)  # 1D\ndeconvn(f2nested, g2nested, (length(h2nested), length(h2nested[1]))) # 2D\nprintln(deconvn(f3nested, g3nested,\n    (length(h3nested), length(h3nested[1]), length(h3nested[1][1])))) # 3D\n", "meta": {"hexsha": "0fc3cb04134fd2acbc529269f69356087a83f3eb", "size": 3231, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/deconvolution-2d+.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/deconvolution-2d+.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/deconvolution-2d+.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1195652174, "max_line_length": 92, "alphanum_fraction": 0.4413494274, "num_tokens": 1565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7817599953878213}}
{"text": "using Plots: plot3d, plot, Animation, frame, gif, GridLayout, EmptyLayout, create_grid\nusing StaticArrays\n\n\"\"\"\n    Body(m, x, y, z, v)\n\nCreate a celestial body object with mass `m` kilograms, position `x` `y` `z`,\nand 3-component velocity vector `v` (m/s).\n\"\"\"\nmutable struct Body{T <: Float64}\n\t# The mass of the body\n\tm::T\n\n\t# Its coords\n\tx::T\n\ty::T\n\tz::T\n\n\t# Its velocity as a vector of x y z values\n\tv::MVector{3, T}\nend\n\n\"\"\"\n    getforce(b1, b2) -> float\n\nReturn the magnitude of the force between Body objects `b1` and `b2`.\n\nUses the standard gravitational equation.\n\nSee also: [`getforcevector`](@ref)\n\"\"\"\nfunction getforce(b1::Body, b2::Body)::Float64\n\ta = b1.x - b2.x\n\tb = b1.y - b2.y\n\tc = b1.z - b2.z\n\n\tr2 = a^2 + b^2 + c^2\n\tif r2 == 0; error(\"Cannot divide by 0. The positions of two bodies cannot be the same.\"); end\n\n\t# G \\frac{m_1 m_2}{r^2}\n\t(6.674e-11 * b1.m * b2.m) / r2\nend\n\n\"\"\"\n    getforcevector(b1, b2) -> [float, float, float]\n\nReturn the 3D vector of the force from Body object `b1` towards `b2`.\n\nExpressed as a 3-component vector. Magnitude can be computed\nby `getforce(b1, b2)`. Angles must be computed separately.\n\nSee also: [`getforce`](@ref)\n\"\"\"\nfunction getforcevector(b1::Body, b2::Body)::MVector{3, Float64}\n\t# azimuth is the angle on the x-y plane\n\tΔx = b2.x - b1.x\n\tΔy = b2.y - b1.y\n\n\tazimuth = atan(Δy, Δx)\n\n\t# altitude is the angle from the x-y plane in the z axis\n\thyp = sqrt(Δx^2 + Δy^2)\n\tΔz = b2.z - b1.z\n\taltitude = atan(Δz, hyp)\n\n\tF = getforce(b1, b2)\n\n\t# We use F to compute the z component and the new hypotenuse to use\n\t# for computing the x and y components\n\tvec_z = F * sin(altitude)\n\txy_plane_hyp = F * cos(altitude)\n\n\t# We then do some more trig to compute the x and y components\n\tvec_y = xy_plane_hyp * sin(azimuth)\n\tvec_x = xy_plane_hyp * cos(azimuth)\n\n\tMVector{3, Float64}(vec_x, vec_y, vec_z)\nend\n\n\"\"\"\n    step!(bodies, Δt)\n\nApply forces between all Body objects in `bodies` over time step `Δt` seconds.\n\"\"\"\nfunction step!(bodies::Vector{Body}, Δt::Float64)\n\t# Calculate the force on each body and update its velocity accordingly\n\tfor i in 1:length(bodies)\n\t\tb = bodies[i]\n\n\t\tforceonbody = copy(b.v)\n\t\t# We loop over every body and if it's not the same one, we add the add the force\n\t\tfor j in 1:length(bodies)\n\t\t\tif j != i\n\t\t\t\t# We add the body's velocity to the force applied by gravity\n\t\t\t\t# to get the resultant force\n\t\t\t\tforceonbody .+= getforcevector(b, bodies[j])\n\t\t\tend\n\t\t\t\n\t\tend\n\n\t\t# Update the velocity of the body\n\n\t\t# a = (v - u)/t and F = ma ⟹  F = m * (v - u)/t\n\t\t# ⟹  v = Ft/m + u\n\n\t\t# Since u is the initial value, we can just use +=\n\t\t# We actually need .+= here to broadcast over the MVector\n\t\tb.v .+= ((forceonbody * Δt) / b.m)\n\tend\n\n\t# We need to wait until we've calculated all the forces before we start to change the positions,\n\t# otherwise we would change a position and then calculate a force based on the new position,\n\t# rather than the old one\n\tfor i in 1:length(bodies)\n\t\tb = bodies[i]\n\n\t\t# Then we update the position of the body using its velocity\n\t\tb.x += Δt * b.v[1]\n\t\tb.y += Δt * b.v[2]\n\t\tb.z += Δt * b.v[3]\n\tend\nend\n\n\"\"\"\n    drawframes(bodies, framecount, Δt)\n\nReturn frame data for the list of Body objects `bodies` with time step `Δt`.\n\nThis frame data is a Vector{Vector{SVector{3, Float64}}}. It can be thought of as a list of frames,\nwhere each frame has a list of bodies, and each body has a list of x y z coordinates.\n\nSee also: [`drawgif`](@ref), [`creategif`](@ref)\n\"\"\"\nfunction drawframes(bodies::Vector{Body}, framecount::Int, Δt::Float64)::Vector{Vector{SVector{3, Float64}}}\n\tframes::Vector{Vector{SVector{3, Float64}}} = [[SVector{3, Float64}(bodies[i].x, bodies[i].y, bodies[i].z) for i in 1:length(bodies)]]\n\n\tfor _ in 1:framecount\n\t\tstep!(bodies, Δt)\n\n\t\t# We build the position data for this frame\n\t\tthisframe::Vector{SVector{3, Float64}} = [SVector{3, Float64}(bodies[i].x, bodies[i].y, bodies[i].z) for i in 1:length(bodies)]\n\n\t\tpush!(frames, thisframe)\n\tend\n\n\treturn frames\nend\n\n\"\"\"\n    drawgif(positions, cube=false, bounds=nothing, filename=nothing)\n\nDraw a GIF using the position data.\n\n`positions` is a Vector{Vector{SVector{3, Float64}}}. It can be thought of as a list of frames,\nwhere each frame has a list of bodies, and each body has a list of x y z coordinates.\n\n`cube` is a bool for whether to draw the plot bounds as a cube.\n\n`bounds` is a Vector{Tuple{Float64, Float64}} - a list of xlimits, ylimits, and zlimits.\nIf it's nothing (by default), then the bounds will be auto-generated.\n\n`filename` is an optional filename. If none is provided, one will be programmatically generated,\nfollowing the pattern of `out.gif`, `out_1.gif`, `out_2.gif`, etc.\n\nSee also: [`drawframes`](@ref), [`creategif`](@ref)\n\"\"\"\nfunction drawgif(positions::Vector{Vector{SVector{3, Float64}}}, cube::Bool, bounds::Union{Nothing, Vector{Tuple{Float64, Float64}}}=nothing, filename::Union{String, Nothing}=nothing)\n\t# This is a multiplier to make the bounding box just a bit bigger than strictly necessary,\n\t# just to make it look a bit nicer\n\tmultiplier = 1.05\n\n\tif cube && !isnothing(bounds)\n\t\t# We get the maximum absolute value in the bounds and use that to build the cube\n\t\tmaxbound = multiplier * max(abs.(Iterators.flatten(bounds))...)\n\n\t\txlimits = (-1 * maxbound, maxbound)\n\t\tylimits = (-1 * maxbound, maxbound)\n\t\tzlimits = (-1 * maxbound, maxbound)\n\n\telseif !cube && !isnothing(bounds)\n\t\t# We just use the bounds given, multiplied by the multiplier\n\t\txlimits = multiplier .* bounds[1]\n\t\tylimits = multiplier .* bounds[2]\n\t\tzlimits = multiplier .* bounds[3]\n\n\telseif cube && isnothing(bounds)\n\t\t# This line gets absolute value of every float in positions and then gets the max\n\t\t# Because we're dealing with a nested vector, we have to flatten it, and then\n\t\t# flatten the result, and then splat it for max\n\t\tmaxbound = multiplier * max(abs.(Iterators.flatten(Iterators.flatten(positions)))...)\n\n\t\txlimits = (-1 * maxbound, maxbound)\n\t\tylimits = (-1 * maxbound, maxbound)\n\t\tzlimits = (-1 * maxbound, maxbound)\n\n\t# Not cube or explicit bounds\n\telse\n\t\t# These list comprehensions loop through the list to get the coords\n\t\t# i is every frame in the positions list, and j is every body in each frame\n\t\t# We only need to check length(positions[1]) to get j because the length of\n\t\t# every sub-list is the same because every frame has the same number of bodies\n\t\txs = [positions[i][j][1] for i in 1:length(positions) for j in 1:length(positions[1])]\n\t\tys = [positions[i][j][2] for i in 1:length(positions) for j in 1:length(positions[1])]\n\t\tzs = [positions[i][j][3] for i in 1:length(positions) for j in 1:length(positions[1])]\n\n\t\txlimits = multiplier .* extrema(xs)\n\t\tylimits = multiplier .* extrema(ys)\n\t\tzlimits = multiplier .* extrema(zs)\n\tend\n\n\t# This is just the number of bodies\n\tn = length(positions[1])\n\n\t# We have 4 different subplots. xyz is the 3D perspective camera angle. The others are the orthogonal views.\n\t# We then put these subplots into a full plot to show everything comprehensively\n\txyz = plot3d(n; legend=false, lw=1, title=\"$n Body Gravity Simulation\", xlim=xlimits, ylim=ylimits, zlim=zlimits)\n\t# We're using standard 2D line plots here to avoid issues with cameras in 3D space\n\txy = plot(n; legend=false, lw=0.5, title=\"Plan\", titlefontsize=8, xlim=xlimits, ylim=ylimits, tickfontsize=4)\n\txz = plot(n; legend=false, lw=0.5, title=\"Front\", titlefontsize=8, xlim=xlimits, ylim=zlimits, tickfontsize=4)\n\tyz = plot(n; legend=false, lw=0.5, title=\"Side\", titlefontsize=8, xlim=ylimits, ylim=zlimits, tickfontsize=4)\n\n\t# This is the expanded form of the @gif macro over a for loop\n\t# We're using the expanded form rather than the macro itself because\n\t# that lets us control the filename\n\tanim = Animation()\n\tcounter = 1\n\t# For each frame\n\tfor i = 1:length(positions)\n\t\t# For each body in this frame\n\t\tfor j in 1:length(positions[i])\n\t\t\t# We add the position data of every body to its respective series in the plots\n\t\t\tbodydata = positions[i][j]\n\t\t\tpush!(xyz, j, bodydata[1], bodydata[2], bodydata[3])\n\t\t\tpush!(xy, j, bodydata[1], bodydata[2])\n\t\t\tpush!(xz, j, bodydata[1], bodydata[3])\n\t\t\tpush!(yz, j, bodydata[2], bodydata[3])\n\t\tend\n\n\t\t# Only if this counter is a multiple of 10, do we add this frame to the animation\n\t\tif counter % 10 == 0\n\t\t\t# I can't directly import the @layout macro, so we do it this way\n\t\t\tlayout = eval(create_grid(:([a{0.7h}; b c d])))\n\t\t\tframe(anim, plot(xyz, xy, xz, yz; layout = layout, size = (1000, 1000)))\n\t\tend\n\n\t\tcounter += 1\n\tend\n\n\tif isnothing(filename)\n\t\tif !in(\"out.gif\", readdir())\n\t\t\tfilename = \"out.gif\"\n\t\telse\n\t\t\ti = 1\n\t\t\twhile in(\"out_$i.gif\", readdir())\n\t\t\t\ti += 1\n\t\t\tend\n\t\t\tfilename = \"out_$i.gif\"\n\t\tend\n\tend\n\n\tgif(anim, filename)\nend\n\n\"\"\"\n    creategif(bodies, framecount, Δt, cube=false, bounds=nothing, filename=nothing)\n\nGenerate a GIF from the list of Body objects `bodies`, with `framecount` frames and a time step of `Δt` seconds.\n\n`cube` is a bool for whether to draw the plot bounds as a cube.\n\n`bounds` is a Vector{Tuple{Float64, Float64}} - a list of xlimits, ylimits, and zlimits.\nIf it's nothing (by default), then the plot bounds will be auto-generated.\n\n`filename` is an optional filename. If none is provided, one will be programmatically generated,\nfollowing the pattern of `out.gif`, `out_1.gif`, `out_2.gif`, etc.\n\nSee also: [`drawgif`](@ref), [`drawframes`](@ref)\n\"\"\"\ncreategif(bodies::Vector{Body}, framecount::Int, Δt::Float64, cube::Bool=false, bounds::Union{Nothing, Vector{Tuple{Float64, Float64}}}=nothing, filename::Union{String, Nothing}=nothing) = drawgif(drawframes(bodies, framecount, Δt), cube, bounds, filename)\n", "meta": {"hexsha": "94e4a94a9a61e0297c5148e71cb06ac7ec4cf17d", "size": 9608, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "library.jl", "max_stars_repo_name": "DoctorDalek1963/Julia-Gravity", "max_stars_repo_head_hexsha": "d877cf4cdfb1b971964f5223a1525a86c95a39fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "library.jl", "max_issues_repo_name": "DoctorDalek1963/Julia-Gravity", "max_issues_repo_head_hexsha": "d877cf4cdfb1b971964f5223a1525a86c95a39fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-08-02T19:09:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-07T19:20:27.000Z", "max_forks_repo_path": "library.jl", "max_forks_repo_name": "DoctorDalek1963/Julia-Gravity", "max_forks_repo_head_hexsha": "d877cf4cdfb1b971964f5223a1525a86c95a39fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3142857143, "max_line_length": 256, "alphanum_fraction": 0.6915070774, "num_tokens": 2959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7817599898825224}}
{"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 28042615-8f2b-41fa-9b14-28d69180debb\nusing Pkg; Pkg.develop(path=\"..\"); Pkg.activate(\"..\")\n\n# ╔═╡ 3ec6aae0-c233-11eb-355d-3dfe780e33bc\nbegin\n\tusing DataFrames\n\tusing JuMP\n\tusing Ipopt\n\tusing StatsPlots\n\tplotly()\nend\n\n# ╔═╡ a6997248-aee3-4ebb-8a1e-f791ad503aa8\nbegin\n\tn = 100\n\tμ1 = 10\n\tμ2 = 15\n\n\tdf = append!(\n\t\tDataFrame(x1=randn(n).+μ1, x2=randn(n).+μ1, y=ones(n)),\n\t\tDataFrame(x1=randn(n).+μ2, x2=randn(n).+μ2, y=-ones(n))\n\t)\n\n\tp = @df df scatter(:x1, :x2, group=:y, legend=:topleft)\nend\n\n# ╔═╡ bf7d0459-4b47-4839-800d-01bdcd500633\nmd\"\n$arg\\ min_{𝐰, b}\\ \\frac{1}{2}𝐰^T𝐰$\n\n$\\text{subject to }\\forall i, y_i(𝐰^T𝐱_i+b) \\geq 1$\n\"\n\n# ╔═╡ 27dfce4e-3ccd-4221-8eca-144ae87e2998\nmd\"\nrespect to\n\n$arg\\ min_{𝐰, b}\\ \\frac{1}{2}𝐮^T 𝐐 𝐮 + 𝐏^T 𝐮$\n\n$\\text{subject to }\\forall i, 𝐚_i^T 𝐮) \\geq c_i$\n\nTherefore,\n\n$𝐮 = \\begin{bmatrix}b \\\\ 𝐰\\end{bmatrix}$\n$𝐐 = \\begin{bmatrix}0 & 0^T_d \\\\ 0^T_d & 𝐈_d\\end{bmatrix}$\n$𝐏 = 0_{d+1}$\n$𝐚^T_i = y_i\\begin{bmatrix}1 & 𝐱^T_i\\end{bmatrix}$\n$c_i = 1$\n\"\n\n# ╔═╡ 5056cc0a-f832-47b3-a6a5-f7ee2d7bc5ba\nbegin\n\tx = Matrix(df[:, 1:2])\n\ty = Vector(df[:, 3])\n\n\tfunction solve_svm(x, y)\n\t\tsvm = Model(Ipopt.Optimizer)\n\t\t@variable(svm, w[1:2])\n\t\t@variable(svm, b)\n\t\t@objective(svm, Min, 0.5 * w' * w)\n\t\t@constraint(svm, y.*(x * w .+ b) .>= 1)\n\t\toptimize!(svm)\n\n\t\t@show objective_value(svm)\n\n\t\treturn value.(w), value(b)\n\tend\n\n\tw, b = solve_svm(x, y)\nend\n\n# ╔═╡ e5334dab-56b2-4dd0-a12c-e17f1c8e584b\nŷ(x1, x2) = sign([x1, x2]' * w + b)\n\n# ╔═╡ 16448a5a-090f-4a6a-a9a0-55192a77dfb3\nheatmap!(p, 5:0.1:20, 5:0.1:20, ŷ, color=:coolwarm)\n\n# ╔═╡ Cell order:\n# ╟─28042615-8f2b-41fa-9b14-28d69180debb\n# ╠═3ec6aae0-c233-11eb-355d-3dfe780e33bc\n# ╠═a6997248-aee3-4ebb-8a1e-f791ad503aa8\n# ╟─bf7d0459-4b47-4839-800d-01bdcd500633\n# ╟─27dfce4e-3ccd-4221-8eca-144ae87e2998\n# ╠═5056cc0a-f832-47b3-a6a5-f7ee2d7bc5ba\n# ╠═e5334dab-56b2-4dd0-a12c-e17f1c8e584b\n# ╠═16448a5a-090f-4a6a-a9a0-55192a77dfb3\n", "meta": {"hexsha": "1c01a8a9e04797519da35ac04840cda3cdb2ca42", "size": 1972, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SVM/notebook/svm.jl", "max_stars_repo_name": "foldfelis/ML101.jl", "max_stars_repo_head_hexsha": "b4b217ac4af88ba460ec26c5c8a1ce322edae64a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-02-23T05:48:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-23T11:52:24.000Z", "max_issues_repo_path": "SVM/notebook/svm.jl", "max_issues_repo_name": "foldfelis/ML101.jl", "max_issues_repo_head_hexsha": "b4b217ac4af88ba460ec26c5c8a1ce322edae64a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-02-22T21:59:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-05T07:29:55.000Z", "max_forks_repo_path": "SVM/notebook/svm.jl", "max_forks_repo_name": "foldfelis/ML101.jl", "max_forks_repo_head_hexsha": "b4b217ac4af88ba460ec26c5c8a1ce322edae64a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-28T07:04:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-28T07:04:06.000Z", "avg_line_length": 21.2043010753, "max_line_length": 58, "alphanum_fraction": 0.6495943205, "num_tokens": 1079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7817599882075628}}
{"text": "function solve_002()\n    fib_vec = [1, 2]\n    i = 3\n    # Generate fibonacci numbers\n    while fib_vec[end] < 4000000\n        push!(fib_vec, fib_vec[i-1] + fib_vec[i-2]) \n        i += 1\n    end\n    # Sum even terms\n    sum(filter(x -> x % 2 == 0, fib_vec))\nend", "meta": {"hexsha": "0bc5b3673ed6d1f2cf625ce97154f967ed4269da", "size": 260, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/002.jl", "max_stars_repo_name": "jkynaston/ProjectEuler.jl", "max_stars_repo_head_hexsha": "84dba07bc8f532ce819811ee896ca643c7bce3b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/002.jl", "max_issues_repo_name": "jkynaston/ProjectEuler.jl", "max_issues_repo_head_hexsha": "84dba07bc8f532ce819811ee896ca643c7bce3b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/002.jl", "max_forks_repo_name": "jkynaston/ProjectEuler.jl", "max_forks_repo_head_hexsha": "84dba07bc8f532ce819811ee896ca643c7bce3b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6363636364, "max_line_length": 52, "alphanum_fraction": 0.55, "num_tokens": 91, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551958, "lm_q2_score": 0.8244619350028205, "lm_q1q2_score": 0.7817173176240886}}
{"text": "module SampleProject\n\nexport sin_sum, cos_sum, geometric_series, pi_gregory_leibniz, pi_nilakantha\n\nsin_sum(n) = sum(sin, range(0, 2pi, length=n))\n\ncos_sum(n) = sum(cos, range(0, 2pi, length=n))\n\ngeometric_series(a, r, n) = sum(k -> a * r^k, 0:n)\n\npi_gregory_leibniz(n) = sum(k -> 4/(4k+1) - 4/(4k+3), 0:n)\n\npi_nilakantha(n) = 3 + sum(k -> 4/((4k-2)*(4k-1)*4k) - 4/(4k*(4k+1)*(4k+2)), 1:n)\n\nend\n", "meta": {"hexsha": "4d569ac0fb4961735735968c70d8324b5c817ab4", "size": 395, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SampleProject.jl", "max_stars_repo_name": "maxbennedich/julia-regression-analysis", "max_stars_repo_head_hexsha": "d1b6523721f779b2cc38149acd0ce00422287902", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-09-08T14:33:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T14:26:29.000Z", "max_issues_repo_path": "src/SampleProject.jl", "max_issues_repo_name": "maxbennedich/julia-regression-analysis", "max_issues_repo_head_hexsha": "d1b6523721f779b2cc38149acd0ce00422287902", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SampleProject.jl", "max_forks_repo_name": "maxbennedich/julia-regression-analysis", "max_forks_repo_head_hexsha": "d1b6523721f779b2cc38149acd0ce00422287902", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6875, "max_line_length": 81, "alphanum_fraction": 0.6303797468, "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.94815453335022, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7817173151133552}}
{"text": "module Shamir\n\nusing Polynomials\n\nfunction l(x, j, k)\n\"\"\"\n    Create a Lagrange basis polynomial\n    Reference: https://wikimedia.org/api/rest_v1/media/math/render/svg/6e2c3a2ab16a8723c0446de6a30da839198fb04b\n\"\"\" \n    polys = []\n    for m in 1:k       \n        if m != j\n            d = x[j] - x[m]\n            r = Poly([-1 * x[m], 1]) / d\n            push!(polys, r)            \n        end\n    end\n        \n    #println(polys)\n    \n    return prod(polys)\nend\n\nfunction L(x, y, k)\n\"\"\"\n    Create a linear combination of Lagrange basis polynomials\n    Reference: https://wikimedia.org/api/rest_v1/media/math/render/svg/d07f3378ff7718c345e5d3d4a57d3053190226a0\n\"\"\"\n    \n    s = []\n    \n    for j in 1:k\n        r = y[j] * l(x, j, k)\n        push!(s, r)\n    end\n    \n    #println(sum(s))\n    \n    return sum(s)\nend\n\nfunction construct_shares(n, production_poly)\n\"\"\"\n    Create shares of the secret\n    \n    Parameters:\n    n: Total number of shares\n    production_poly : The Polynomial created with the secret\n                    to produce secret shares\n\"\"\"\n    \n    share = []\n    \n    for i in 1:n\n        push!(share, [i, production_poly(i)])\n    end\n    \n    return share\nend\n\nfunction recover_secret(shares, n, k, p)\n\"\"\"\n    Recover the secret by finding the coefficient of x^0 i.e.\n    when the x=0 in the polynomial. \n    \n    Parameters:\n    shares : An array of shares of the individuals.\n    n : total number of shares\n    k: minimum number of shares required to unravel the secret\n    p: Field number (to restrict the computation space)\n\"\"\"\n    if length(shares) < k\n        throw(\"Need more parties!\")\n    end\n    \n    x = []\n    y = []\n    for i in 1:n\n        push!(x, shares[i][1])\n        push!(y, shares[i][2])\n    end\n    \n    f = L(x, y, k)\n    f = mod(f(0), p)\n    \n    return f\nend\n\nexport Shamir\n\nend\n", "meta": {"hexsha": "0b08c65cc3e2c303f4a1d513d1ee37dbe8bb10f0", "size": 1822, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Shamir.jl", "max_stars_repo_name": "r0cketr1kky/Shamir.jl", "max_stars_repo_head_hexsha": "1571804cd3518750a06ae54dd6ed2f4f49533d27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Shamir.jl", "max_issues_repo_name": "r0cketr1kky/Shamir.jl", "max_issues_repo_head_hexsha": "1571804cd3518750a06ae54dd6ed2f4f49533d27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-07T10:41:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-07T10:41:53.000Z", "max_forks_repo_path": "src/Shamir.jl", "max_forks_repo_name": "r0cketr1kky/Shamir.jl", "max_forks_repo_head_hexsha": "1571804cd3518750a06ae54dd6ed2f4f49533d27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8043478261, "max_line_length": 111, "alphanum_fraction": 0.5680570801, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502202, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7817173130686009}}
{"text": "export mean_squared_error\n\n\"\"\"\n    MeanSquaredError <: Func\n\"\"\"\n@func mutable struct MeanSquaredError end\n\nfunction forward(f::MeanSquaredError, x1, x2)\n    diff = x1 .- x2\n    y = sum(diff.^2) / length(diff)\n    return y\nend\n\nfunction backward(f::MeanSquaredError, gy)\n    x1, x2 = f.args\n    diff = x1 - x2\n    gx1 = gy .* diff .* (2.0 / length(diff))\n    gx2 = -gx1\n    return gx1, gx2\nend\n\nmean_squared_error(x1, x2) = MeanSquaredError()(x1, x2)\n", "meta": {"hexsha": "664b7bbb821140ac455400a0b781242b0a86ce3b", "size": 450, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/loss.jl", "max_stars_repo_name": "k-fog/dorayaki.jl", "max_stars_repo_head_hexsha": "ea5796e180706f2868eb1d8ebda02fede310edf9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/loss.jl", "max_issues_repo_name": "k-fog/dorayaki.jl", "max_issues_repo_head_hexsha": "ea5796e180706f2868eb1d8ebda02fede310edf9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/loss.jl", "max_forks_repo_name": "k-fog/dorayaki.jl", "max_forks_repo_head_hexsha": "ea5796e180706f2868eb1d8ebda02fede310edf9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5652173913, "max_line_length": 55, "alphanum_fraction": 0.6422222222, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.781717310652914}}
{"text": "function e006(N)\n    return difference(N)\nend\n\nfunction difference(N)\n    sum_squares = begin\n        s = 0\n        for i = 1:N\n            s += i ^ 2\n        end\n        s\n    end\n    \n    square_sum = begin\n        s = 0\n        for i = 1:N\n            s += i\n        end\n        s ^ 2\n    end\n\n    return square_sum - sum_squares\nend\n\nfunction solution006()\n    N = 100\n    answer = e006(N)\n    println(\"The answer to problem 006 is $answer\")\nend\n\n", "meta": {"hexsha": "3f2103a9efbada09911b24ab53beb8f9f23daea4", "size": 451, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/006.jl", "max_stars_repo_name": "mithodin/ttpe", "max_stars_repo_head_hexsha": "8253a0b60bb94194bf91f375cfd1a707d6a4be0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/006.jl", "max_issues_repo_name": "mithodin/ttpe", "max_issues_repo_head_hexsha": "8253a0b60bb94194bf91f375cfd1a707d6a4be0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/006.jl", "max_forks_repo_name": "mithodin/ttpe", "max_forks_repo_head_hexsha": "8253a0b60bb94194bf91f375cfd1a707d6a4be0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.5483870968, "max_line_length": 51, "alphanum_fraction": 0.4922394678, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7817031887464868}}
{"text": "N, faces = 10^6, 1:6\n\nnumSol = sum([iseven(i+j) for i in faces, j in faces]) / length(faces)^2\nmcEst  = sum([iseven(rand(faces) + rand(faces)) for i in 1:N]) / N\n\nprintln(\"Numerical solution = $numSol \\nMonte Carlo estimate = $mcEst\")\n", "meta": {"hexsha": "d0c03acafa449253ed005720c802b54ae1597e74", "size": 235, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2_chapter/diceSumEven.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "2_chapter/diceSumEven.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "2_chapter/diceSumEven.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 33.5714285714, "max_line_length": 72, "alphanum_fraction": 0.6553191489, "num_tokens": 87, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037262250325, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7817031798576831}}
{"text": "\"\"\"\n    𝑛(v::Vector{T}) where T<:Number\n\nScales a length-``n`` vector ``v``  such that the last component\nof the vector is one, provided that the last component is not zero. If the last\ncomponent is zero then the vector is left unchanged.\n\n# Details\nSuppose the length-``n`` vector ``v`` represents the homogeneous coordinates  of\na point in a projective space. The corresponding Cartesian coordinates  usually\njust the first ``n-1`` numbers of homogeneous coordinates divided by  the last\ncomponent. So if the last component is one, then the first  ``n-1`` homogeneous\ncoordinates can be interpreted as Cartesian.  The exceptional case is when the\nlast component of the homogenenous coordinates is zero. These homogeneous\ncoordinates are associated with so-called *points at infinity* and have no\nCartesian counterparts.\n\n# Example\n```julia\nh = [4, 4 , 2]\nc = 𝑛(h)\n\n3-element Array{Float64,1}:\n 2.0\n 2.0\n 1.0\n```\n\n\n\"\"\"\nfunction 𝑛(v::AbstractArray)\n    if v[end] != 0 && v[end] != 1\n        v .= v ./ v[end]\n    else\n        v\n    end\nend\n\nfunction 𝑛(v::SVector)\n    if v[end] != 0 && v[end] != 1\n        v / v[end]\n    else\n        v\n    end\nend\n\nfunction hom⁻¹(v::SVector)\n    if isapprox(v[end], 0.0; atol = 1e-14)\n        pop(v)\n    else\n        pop(v / v[end])\n    end\nend\n\nfunction hom(v::SVector)\n    push(v,1)\nend\n\nfunction ∂hom⁻¹(𝐧::SVector)\n    k = length(𝐧)\n    𝐞ₖ = push(zeros(SVector{k-1}),1.0)\n    𝐈 = SMatrix{3,3}(1.0I)\n    1/𝐧[k]*𝐈 - 1/𝐧[k]^2 * 𝐧 * 𝐞ₖ'\nend\n\nfunction ∂𝑛(𝐧::AbstractArray)\n    k = length(𝐧)\n    𝐞ₖ = fill(0.0,(k,1))\n    𝐞ₖ[k] = 1\n    1/𝐧[k]*Matrix{Float64}(I, k, k) - 1/𝐧[k]^2 * 𝐧 * 𝐞ₖ'\nend\n\n\nfunction smallest_eigenpair(A::AbstractArray)\n    F = eigen(A)\n    index = argmin(F.values)\n    (F.values[index], F.vectors[:,index])\nend\n\nfunction smallest_eigenpair(A::AbstractArray,B::AbstractArray)\n    F = eigfact(A,B)\n    index = indmin(F[:values])\n    (F[:values][index], F[:vectors][:,index])\nend\n\n\nfunction vec2antisym(v::AbstractArray)\n    if length(v) != 3\n         throw(ArgumentError(\"The operation is only defined for a length-3 vector.\"))\n    end\n    𝐒  = @SMatrix [   0  -v[3]    v[2] ;\n                    v[3]    0    -v[1] ;\n                   -v[2]  v[1]      0]\n\nend\n", "meta": {"hexsha": "4e41016297e387c9cc43bfe82ceef30bee1aface", "size": 2211, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operators/operators.jl", "max_stars_repo_name": "JuliaTagBot/MultipleViewGeometry.jl", "max_stars_repo_head_hexsha": "cafd7f61f30258f804ac31c5f9648b54edc6b347", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-29T18:45:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-29T18:45:09.000Z", "max_issues_repo_path": "src/operators/operators.jl", "max_issues_repo_name": "JuliaTagBot/MultipleViewGeometry.jl", "max_issues_repo_head_hexsha": "cafd7f61f30258f804ac31c5f9648b54edc6b347", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-17T16:03:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-18T09:13:22.000Z", "max_forks_repo_path": "src/operators/operators.jl", "max_forks_repo_name": "JuliaTagBot/MultipleViewGeometry.jl", "max_forks_repo_head_hexsha": "cafd7f61f30258f804ac31c5f9648b54edc6b347", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:18:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T20:13:09.000Z", "avg_line_length": 23.03125, "max_line_length": 85, "alphanum_fraction": 0.6146540027, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7816696543927958}}
{"text": "\"\"\"\n    fdweights(z, x, m)\n\nCalculates FD (finite difference) weights for arbitrarily spaced nodes in 1D.\n\nReturn an array of size m+1 by length(x) containing, in successive rows, the\nweights for derivatives 0, 1, ..., m. The zero (m = 0) derivative corresponds\nto interpolation.\n\n# Arguments\n- `z`: location at which to approximate the derivative (may but need to be a grid point)\n- `x`: vector of x-coordinates (grid points; distinct, otherwise arbitrary)\n- `m`: highest derivative for which weights are sought (default value is 0)\n\n# Examples\n```julia-repl\njulia> fdweights(0, -2:2, 6)\n5×5 adjoint(::Matrix{Float64}) with eltype Float64:\n -0.0         0.0        1.0   0.0       -0.0\n  0.0833333  -0.666667   0.0   0.666667  -0.0833333\n -0.0833333   1.33333   -2.5   1.33333   -0.0833333\n -0.5         1.0        0.0  -1.0        0.5\n  1.0        -4.0        6.0  -4.0        1.0\n```\n\"\"\"\nfunction fdweights(z, x, m = 0)\n    n = length(x)\n    if m >= n\n        m = n - 1 # set to highest possible derivative\n    end\n\n    c1 = 1\n    c4 = x[1] - z\n    C = zeros(n, m+1)\n    C[1, 1] = 1\n    \n    for i = 1:n-1\n        i1 = i + 1\n        mn = min(i, m)\n        c2 = 1\n        c5 = c4\n        c4 = x[i1] - z\n        for j = 0:i-1\n            j1 = j + 1\n            c3 = x[i1] - x[j1]\n            c2 = c2 * c3\n            if j == i-1\n                for s = mn:-1:1\n                    s1 = s + 1\n                    C[i1, s1] = c1 * (s * C[i1-1, s1-1] - c5 * C[i1-1, s1]) / c2\n                end\n                C[i1, 1] = -c1 * c5 * C[i1-1, 1] / c2\n            end\n        for s = mn:-1:1\n            s1 = s + 1\n            C[j1, s1] = (c4 * C[j1, s1] - s*C[j1, s1-1]) / c3\n        end\n        C[j1, 1] = c4 * C[j1,1] / c3\n        end\n        c1 = c2\n    end\n    return C'\nend\n", "meta": {"hexsha": "9153211c284165568b706b37f3172f9c801e2753", "size": 1776, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "fdweights.jl", "max_stars_repo_name": "williamhunter/fornberg", "max_stars_repo_head_hexsha": "395635e8dcbc85907df7b7beae1028d65e4d52bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fdweights.jl", "max_issues_repo_name": "williamhunter/fornberg", "max_issues_repo_head_hexsha": "395635e8dcbc85907df7b7beae1028d65e4d52bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fdweights.jl", "max_forks_repo_name": "williamhunter/fornberg", "max_forks_repo_head_hexsha": "395635e8dcbc85907df7b7beae1028d65e4d52bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.75, "max_line_length": 88, "alphanum_fraction": 0.4707207207, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642531177793, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7816696451574003}}
{"text": "module kuramoto_sivashinsky\n\nusing SparseArrays \nusing LinearAlgebra\n\n\"\"\"\n    B = calcBernoulli(n)\n\nReturn the `n`th Bernoulli number.  Follows the convention that `n=1` \nBernoulli number is equal to -1/2.\n\"\"\"\nfunction calcBernoulli(n)\n    A = Vector{Rational{BigInt}}(undef, n + 1)\n    for m = 0:n\n        A[m + 1] = 1 // (m + 1)\n        for j = m:-1:1\n            A[j] = j * (A[j] - A[j + 1])\n        end\n    end\n    if n == 1\n        return -A[1]\n    else\n        return A[1]\n    end\nend\n\n\"\"\"\n    quad = buildQuadrature(order [, T=Float64])\n\nReturn a Gregory-type quadrture rule for uniformly spaced data. \n\"\"\"\nfunction buildQuadrature(order::Int)\n    # Form the linear system to solve\n    numbnd = order - 1\n    A = zeros(Rational{BigInt}, order-1, numbnd)\n    b = zeros(Rational{BigInt}, order-1)\n    for j = 1:order-1\n        for i = 1:numbnd \n            A[j,i] = j*(numbnd - (i-1))^(j-1)\n        end\n        b[j] = numbnd^j - ((-1)^j)*calcBernoulli(j)\n    end\n    w = A\\b\n    return w\n    # if order <= 2\n    #     quad = [1//2]\n    # elseif order <= 4 \n    #     quad = [17//48; 59//48; 43//48; 49//48]\n    # elseif order <= 6 \n    #     quad = [13649//43200; 12013//8640; 2711//4320; 5359//4320; 7877//8640;\n    #             43801//43200]\n    # else\n    #     quad = [1498139//5080320; 1107307//725760; 20761//80640;\n    #             1304999//725760; 299527//725760; 103097//80640;\n    #             670091//725760; 5127739//5080320]\n    # end\n    # return convert(Array{T,1}, quad)\nend\n\n\"\"\"\nData structure for finite-difference operators on uniformly spaced points\n\"\"\"\nstruct FiniteDiff{T}\n    \"\"\"Defines the nodes in the stencil; node 0 is rel. location of operator\"\"\"\n    stencil::Array{Int,1}\n    \"\"\"Actual finite-difference coefficients\"\"\"\n    coeffs::Array{T,1}\nend\n\n\"\"\"\n    fd = buildFiniteDifference(deriv, order [, T=Float64, h=1.0])\n\nReturns a finite difference operator struct for a derivative of order `deriv` \nand order of accuracy of `order`. The optional argument `T` controls the \nprecision used, and `h` sets the (uniform) mesh spacing.\n\"\"\"\nfunction buildFiniteDifference(deriv::Int, order::Int, T::Type=Float64;\n                               h=convert(T,1) )\n    num_pts = deriv + order - 1\n    if iseven(num_pts) num_pts += 1 end \n    stencil = Array{Int}(-div(num_pts-1,2):div(num_pts-1,2))\n    V = zeros(T, num_pts, num_pts)\n    for i = 1:num_pts\n        V[i,:] = stencil.^(i-1)\n    end\n    b = zeros(T, num_pts)\n    b[deriv+1] = factorial(deriv)\n    c = V\\b\n    c /= (h^deriv)\n    return FiniteDiff{T}(stencil, c)\nend\n\n\"\"\"\n    interp = buildInterp(order [, T=Float64])\n\nReturns a centered interpolation operator of order `order` that does **not** \nuse data at the central node.\n\"\"\"\nfunction buildInterp(order::Int, T::Type=Float64)\n    num_pts = order\n    if isodd(num_pts) num_pts += 1 end\n    stencil = Array{Int}([-div(num_pts,2):-1;1:div(num_pts,2)])\n    V = zeros(T, num_pts, num_pts)\n    for i = 1:num_pts\n        V[i,:] = stencil.^(i-1)\n    end\n    b = zeros(T, num_pts)\n    b[1] = 1.0\n    c = V\\b\n    return FiniteDiff{T}(stencil, c)\nend\n\n\"\"\"\n    num_ghost, num_bndry, ghost_op = buildGhostOp(order [, T=Float64])\n\nConstructs a matrix operator `ghost_op` that, when applied to `num_bndry` nodes \nat the boundary, produces `order` accurate `num_ghost` values.  **Note**, this \noperator is designed to enforce a zero function value and zero derivative value\nat the boundary, as per the Blonigan and Wang paper.\n\nThe ghost operator is constructed by solving a linearly constrained minimum \nnorm problem for the ghost node values.\n\"\"\"\nfunction buildGhostOp(order::Int, T::Type=Float64)\n    # first, build the constraint Jacobian that enforces u=0 and du/dx = 0\n    # A*u_ghost - B*u_true = c \n    fd = buildFiniteDifference(1, order, T)\n    #interp = buildInterp(order, T)\n    num_nodes = length(fd.stencil)\n    num_ghost = div(num_nodes-1,2) + 1 # this includes node at boundary\n    num_bndry = num_nodes - num_ghost \n    A = zeros(T, 2, num_ghost)\n    A[1,end] = 1.0 # last node is the node on the boundary\n    #A[1,1:end-1] = interp.coeffs[1:num_ghost-1]\n    A[2,:] = fd.coeffs[1:num_ghost]\n    B = zeros(T, 2, num_bndry)\n    #B[1,:] = interp.coeffs[num_ghost:end]\n    B[2,:] = fd.coeffs[num_ghost+1:end]\n    return num_ghost, num_bndry, -A'*( (A*A') \\ B )\n    \n    if false\n        # This version uses a TVD-type regularization\n        # first, build the constraint Jacobian that enforces u=0 and du/dx = 0\n        # A*u_ghost = B*u_true + c \n        fd = buildFiniteDifference(1, order, T)\n        #interp = buildInterp(order, T)\n        num_nodes = length(fd.stencil)\n        num_ghost = div(num_nodes-1,2) + 1 # this includes node at boundary\n        num_bndry = num_nodes - num_ghost \n        A = zeros(T, 2, num_ghost)\n        A[1,end] = 1.0 # last node \n        #A[1,1:end-1] = interp.coeffs[1:num_ghost-1]\n        A[2,:] = fd.coeffs[1:num_ghost]\n        B = zeros(T, 2, num_bndry)\n        #B[1,:] = interp.coeffs[num_ghost:end]\n        B[2,:] = fd.coeffs[num_ghost+1:end]\n\n        D = zeros(T, num_ghost, num_ghost)\n        D += diagm(2*ones(T,num_ghost))\n        D -= diagm(ones(T, num_ghost-1), 1)\n        D -= diagm(ones(T, num_ghost-1), -1)\n        K = [D A'; A zeros(T, 2, 2)]\n        G = -inv(K)[1:num_ghost,end-1:end]*B \n        return num_ghost, num_bndry, G\n    end\nend\n\n\"\"\"\nData for KS function evaluation to avoid reallocation\n\"\"\"\nstruct KSData{T}\n    \"\"\"Number of internal nodes (nodes we are solving for)\"\"\"\n    num_nodes::Int \n    \"\"\"Number of ghost nodes at each end; include x=0 and x=L\"\"\"\n    num_ghost::Int\n    \"\"\"Number of internal nodes used to determine ghost values\"\"\"\n    num_bndry::Int\n    \"\"\"Stores the boundary first-derivative operator\"\"\"\n    bndry_op::Array{T,2}\n    \"\"\"Stores the linear operatrors\"\"\"\n    linear_op::SparseMatrixCSC{T,Int}\n    \"\"\"finite difference operator for the first-derivative\"\"\"\n    fd::FiniteDiff{T}\nend\n \n\"\"\"\n    ks = buildKSDataPeriodic(order, num_nodes [, T=Float64])\n\nReturns a KSData structure that can be used to solve the Kuramoto-Sivashinsky \nequations on _periodic domains_, while avoiding reallocation of arrays.\n\"\"\"\nfunction buildKSDataPeriodic(order::Int, num_nodes::Int, T::Type=Float64)\n    # domain length used in Blonigan and Wang paper, but here periodic \n    Lx = convert(T, 128)\n    h = Lx/num_nodes\n    # generate the matrix used for the linear operators\n    A = zeros(T, num_nodes, num_nodes)\n    # second, add the Laplacian contributions\n    fd = buildFiniteDifference(2, order, T)\n    fac = 1/(h*h)\n    for i = 1:num_nodes\n        A[i, mod.(fd.stencil .+ i .- 1, num_nodes) + 1] -= fd.coeffs*fac \n    end\n    # finally, add the BiLaplacian terms \n    fd = buildFiniteDifference(4, order, T)\n    fac *= fac\n    for i = 1:num_nodes\n        A[i, mod.(fd.stencil .+ i .- 1, num_nodes) + 1] -= fd.coeffs*fac \n    end\n    Asparse = sparse(A)\n    # finally, get the first-derivative operator for nonlinear terms \n    fd = kuramoto_sivashinsky.buildFiniteDifference(1, order, T, h=h)\n    return KSData{T}(num_nodes, 0, 0, zeros(0,0), Asparse, fd)\nend\n\n\"\"\"\n    getKSFuncPeriodic!(ks, t, u, du)\n\nA function that returns the perodic spatial discretization of the\nKuramoto-Sivashinsky PDE for use in a time marching method.\n\"\"\"\nfunction getKSFuncPeriodic!(ks::KSData{Tks}, t, u::AbstractArray{T,1},\n                            du::AbstractArray{T,1}) where {Tks, T}\n    # apply the linear operators\n    du[:] = ks.linear_op*u\n    # add the nonlinear terms; this uses a skew-symmetric split-form\n    third = convert(T, 1//3)\n    for i = 1:ks.num_nodes\n        for k = 1:size(ks.fd.stencil,1)\n            j = mod(ks.fd.stencil[k]+i-1, ks.num_nodes) + 1\n            du[i] -= third*u[i]*ks.fd.coeffs[k]*u[j]\n            du[i] -= third*ks.fd.coeffs[k]*u[j]*u[j]\n        end\n        # This version uses central differencing for the nonlinear term\n        #du[i] -= u[i]*dot(ks.fd.coeffs, \n        #                  u[mod.(ks.fd.stencil+i-1,ks.num_nodes)+1])\n    end\n    return nothing\nend\n\n\"\"\"\n    getKSJacPeriodic!(ks, t, u, Jac)\n\nA function that returns the Jacobian of the perodic spatial discretization of\nthe Kuramoto-Sivashinsky PDE for use in a time marching method.\n\"\"\"\nfunction getKSJacPeriodic!(ks::KSData{T}, t, u::AbstractArray{T,1}, \n                           Jac::SparseMatrixCSC{T,Int}) where {T}\n    Jac[:,:] = sparse(ks.linear_op)\n    third = convert(T, 1//3)\n    for i = 1:ks.num_nodes \n        for k = 1:size(ks.fd.stencil,1)\n            j = mod(ks.fd.stencil[k]+i-1, ks.num_nodes) + 1\n            #du[i] -= fac*u[i]*ks.fd.coeffs[k]*u[j]\n            Jac[i,i] -= third*ks.fd.coeffs[k]*u[j]\n            Jac[i,j] -= third*u[i]*ks.fd.coeffs[k] \n            #du[i] -= fac*ks.fd.coeffs[k]*u[j]*u[j]\n            Jac[i,j] -= 2*third*ks.fd.coeffs[k]*u[j]\n        end\n        # This version uses central differencing for the nonlinear term\n        #Jac[i,i] -= dot(ks.fd.coeffs, \n        #                u[mod.(ks.fd.stencil+i-1,ks.num_nodes)+1])\n        #Jac[i,mod.(ks.fd.stencil+i-1,ks.num_nodes)+1] -= u[i]*ks.fd.coeffs \n    end\nend\n\n\"\"\"\n    ks = buildKSData(order, num_nodes [, T=Float64])\n\nReturns a KSData structure that can be used to solve the Kuramoto-Sivashinsky \nequations while avoiding reallocation of arrays.  This version imposes\nhomogeneous Dirichlet and Neumann conditions at the ends of the spatial domain.\n\"\"\"\nfunction buildKSData(order::Int, num_nodes::Int, T::Type=Float64)\n    # domain length used in Blonigan and Wang paper\n    Lx = convert(T, 128)\n    h = Lx/(num_nodes+1)\n    # get the ghost node operator, call it Bg\n    num_ghost, num_bndry, Bg = buildGhostOp(order, T)\n    # println(\"Bg = \", Bg)\n\n    # generate the matrix used for the linear operators\n    A = zeros(T, num_nodes, num_nodes)\n    # first, add the Laplacian contributions\n    fd = buildFiniteDifference(2, order, T)\n    fac = 1/(h*h)\n    for i = 1:num_nodes\n        idx = [k for k = 1:size(fd.stencil,1) \n               if fd.stencil[k] + i >= 1 && fd.stencil[k] + i <= num_nodes]\n        A[i, fd.stencil[idx] .+ i] -= fd.coeffs[idx]*fac \n    end\n\n    # eliminate ghost node contributions for Laplacian\n    Ag = zeros(T, num_bndry, num_ghost)\n    for i = 1:num_bndry\n        idx = [k for k = 1:size(fd.stencil,1) if fd.stencil[k] + i < 1]\n        Ag[i, fd.stencil[idx] .+ num_ghost .+ i] -= fd.coeffs[idx]*fac\n    end\n    # println(\"Ag (Laplacian) = \", Ag)\n    G = Ag*Bg \n    A[1:num_bndry,1:num_bndry] += G \n    A[end:-1:end-num_bndry+1,end:-1:end-num_bndry+1] += G \n\n    # next, add the BiLaplacian terms \n    fd = buildFiniteDifference(4, order, T)\n    fac = 1/(h*h*h*h)\n    for i = 1:num_nodes\n        idx = [k for k = 1:size(fd.stencil,1) \n               if fd.stencil[k] + i >= 1 && fd.stencil[k] + i <= num_nodes]\n        A[i, fd.stencil[idx] .+ i] -= fd.coeffs[idx]*fac \n    end\n\n    # eliminate ghost node contributions for BiLaplacian\n    fill!(Ag, zero(T))\n    for i = 1:num_bndry\n        idx = [k for k = 1:size(fd.stencil,1) if fd.stencil[k] + i < 1]\n        Ag[i, fd.stencil[idx] .+ num_ghost .+ i] -= fd.coeffs[idx]*fac\n    end\n    # println(\"Ag (BiLaplacian) = \", Ag)\n    G = Ag*Bg\n    A[1:num_bndry,1:num_bndry] += G \n    A[end:-1:end-num_bndry+1,end:-1:end-num_bndry+1] += G\n\n    # println(\"A[1,1:5] = \",A[1,1:5])\n    # println(\"A[end,end-4:end] = \",A[end,end-4:end])\n\n    Asparse = sparse(A)\n\n    # finally, get the first-derivative operator for nonlinear terms \n    fd = kuramoto_sivashinsky.buildFiniteDifference(1, order, T, h=h)\n    # Get the first-derivative operator at the boundary\n    fill!(Ag, zero(T))\n    G = zeros(T, num_bndry, div(size(fd.stencil,1)+1,2) + num_bndry - 1 )\n    for i = 1:num_bndry\n        idx = [k for k = 1:size(fd.stencil,1) if fd.stencil[k] + i < 1]\n        Ag[i, fd.stencil[idx] .+ num_ghost .+ i] += fd.coeffs[idx]\n        idx = [k for k = 1:size(fd.stencil,1) if fd.stencil[k] + i >= 1]\n        G[i, fd.stencil[idx] .+ i] += fd.coeffs[idx]\n    end\n    # println(\"Ag (first-derivative) = \", Ag)\n    # println(\"G before = \",G)\n    G[:,1:num_bndry] += Ag*Bg \n    # println(\"G after = \",G)\n\n    return KSData{T}(num_nodes, num_ghost, num_bndry, G, Asparse, fd)\nend\n\n\"\"\"\n    getKSFunc!(ks, t, u, du)\n\nA function that returns the spatial discretization of the\nKuramoto-Sivashinsky PDE for use in a time marching method.  Homogeneous BCs \nfor u and dudx are used at both ends of the domain.\n\"\"\"\nfunction getKSFunc!(ks::KSData{Tks}, t, u::AbstractArray{T,1},\n                    du::AbstractArray{T,1}) where {Tks, T}\n    # apply the linear operators\n    du[:] = ks.linear_op*u\n    # add the nonlinear terms to interior nodes \n    fac = convert(T, 1//3)\n    for i = ks.num_bndry + 1:ks.num_nodes - ks.num_bndry \n        for k = 1:size(ks.fd.stencil,1)\n            j = mod(ks.fd.stencil[k]+i-1, ks.num_nodes) + 1\n            du[i] -= fac*u[i]*ks.fd.coeffs[k]*u[j]\n            du[i] -= fac*ks.fd.coeffs[k]*u[j]*u[j]\n        end\n        #du[i] -= u[i]*dot(ks.fd.coeffs, \n        #                  u[mod.(ks.fd.stencil+i-1,ks.num_nodes)+1])\n    end\n    # add the nonlinear terms to the boundary nodes \n    for i = 1:size(ks.bndry_op,1)\n        for k = 1:size(ks.bndry_op,2)\n            du[i] -= fac*u[i]*ks.bndry_op[i,k]*u[k]\n            du[i] -= fac*ks.bndry_op[i,k]*u[k]*u[k]\n            du[end-i+1] += fac*u[end-i+1]*ks.bndry_op[i,k]*u[end-k+1]\n            du[end-i+1] += fac*ks.bndry_op[i,k]*u[end-k+1]*u[end-k+1]\n        end\n    end\n    return nothing\nend\n\n\"\"\"\n    getKSJac!(ks, t, u, Jac)\n\nA function that returns the Jacobian of the spatial discretization of\nthe Kuramoto-Sivashinsky PDE for use in a time marching method. Homogeneous BCs\nfor u and dudx are used at both ends of the domain.\n\"\"\"\nfunction getKSJac!(ks::KSData{T}, t, u::AbstractArray{T,1}, \n                   Jac::SparseMatrixCSC{T,Int}) where {T}\n    # Jacobian contribution due to linear terms \n    Jac[:,:] = sparse(ks.linear_op)\n    #Jac[:,:] = deepcopy(ks.linear_op)\n    # Jacobian due to nonlinear terms on interior \n    fac = convert(T, 1//3)\n    for i = ks.num_bndry+1:ks.num_nodes - ks.num_bndry \n        for k = 1:size(ks.fd.stencil,1)\n            j = mod(ks.fd.stencil[k]+i-1, ks.num_nodes) + 1\n            # du[i] -= fac*u[i]*ks.fd.coeffs[k]*u[j]\n            Jac[i,i] -= fac*ks.fd.coeffs[k]*u[j]\n            Jac[i,j] -= fac*u[i]*ks.fd.coeffs[k] \n            # du[i] -= fac*ks.fd.coeffs[k]*u[j]*u[j]\n            Jac[i,j] -= 2*fac*ks.fd.coeffs[k]*u[j]\n        end\n        # This version uses central differencing for the nonlinear term\n        #Jac[i,i] -= dot(ks.fd.coeffs, \n        #                u[mod.(ks.fd.stencil+i-1,ks.num_nodes)+1])\n        #Jac[i,mod.(ks.fd.stencil+i-1,ks.num_nodes)+1] -= u[i]*ks.fd.coeffs \n    end\n    # Jacobian due to nonlinear terms on boundary \n    for i = 1:size(ks.bndry_op,1)\n        for k = 1:size(ks.bndry_op,2)\n            # du[i] -= fac*u[i]*ks.bndry_op[i,k]*u[k]\n            Jac[i,i] -= fac*ks.bndry_op[i,k]*u[k]\n            Jac[i,k] -= fac*u[i]*ks.bndry_op[i,k]\n            # du[i] -= fac*ks.bndry_op[i,k]*u[k]*u[k]\n            Jac[i,k] -= 2*fac*ks.bndry_op[i,k]*u[k]\n            # du[end-i+1] += fac*u[end-i+1]*ks.bndry_op[i,k]*u[end-k+1]\n            Jac[end-i+1,end-i+1] += fac*ks.bndry_op[i,k]*u[end-k+1]\n            Jac[end-i+1,end-k+1] += fac*u[end-i+1]*ks.bndry_op[i,k]\n            # du[end-i+1] += fac*ks.bndry_op[i,k]*u[end-k+1]*u[end-k+1]\n            Jac[end-i+1,end-k+1] += 2*fac*ks.bndry_op[i,k]*u[end-k+1]\n\n            # This version uses central differencing for the nonlinear term\n            #du[i] -= u[i]*ks.bndry_op[i,k]*u[k]\n            #  Jac[i,i] -= ks.bndry_op[i,k]*u[k]\n            #  Jac[i,k] -= u[i]*ks.bndry_op[i,k]\n            #du[end-i+1] -= u[end-i+1]*ks.bndry_op[i,k]*u[end-k+1]\n            #  Jac[end-i+1,end-i+1] += ks.bndry_op[i,k]*u[end-k+1]\n            #  Jac[end-i+1,end-k+1] += u[end-i+1]*ks.bndry_op[i,k]\n        end\n    end\nend\n\n\"\"\"\n    Jac = getJacobian(u, ks)\n\nThis function uses the complex-step method to get the Jacobian; used for\nverification of getKSJac!.  **Do not use** in simulations, due to cost.\n\"\"\"\nfunction getJacobian(u::AbstractArray{T,1}, ks::KSData{T}) where{T}\n    fd_c = FiniteDiff{Complex128}(ks.fd.stencil, ks.fd.coeffs)\n    ks_c = KSData{Complex128}(ks.num_nodes, ks.num_ghost, ks.num_bndry, \n                              ks.bndry_op, ks.linear_op, fd_c)\n    Jac = zeros(size(u,1),size(u,1))\n    u_c = complex.(u, 0.0)\n    du_c = zeros(u_c)\n    ceps = 1e-60\n    for i = 1:ks.num_nodes\n        u_c[i] += complex(0.0, ceps)\n        getKSFunc!(ks_c, 0.0, u_c, du_c)\n        Jac[:,i] = imag.(du_c)/ceps\n        u_c[i] -= complex(0.0, ceps)\n    end\n    return Jac \nend\n\n\"\"\"\n    sol = solveUsingMidpoint(ks, Time, num_stpes, u)\n\nSolve the KS problem on the nonperiodic domain using the midpoint rule.  The \nproblem is run from t=0 to t=`Time` using `num_steps` steps.  The initial\ncondition is `u`.  Returns `sol`, the solution over all space and temporal \nnodes; `sol[i,n]` stores the `i`th space node at time step `n`.  Note that \n`sol` stores the boundary nodes, whereas `u` does not.\n\"\"\"\nfunction solveUsingMidpoint(ks::KSData{T}, Time::T, num_steps::Int,\n                            u::Array{T,1}) where {T}\n    num_nodes = size(u,1)\n    # storage for solution over all time steps\n    dt = Time/num_steps\n    sol = zeros(num_nodes+2, num_steps+1)\n    sol[2:end-1,1] = u\n    \n    t = convert(T, 0.0)\n    Jac = similar(ks.linear_op)\n    F = lu(ks.linear_op) # initialize memory for the lu factorization\n    u_mid = zeros(size(u))\n    u_old = zeros(size(u))\n    r = zeros(size(u))\n    newt_tol = 1e-10 # We will need to ensure this is sufficiently small\n    max_newt_iter = 50\n    for n = 1:num_steps\n        #println(\"Iteration \",n,\": time \",t)\n        # Newton iterations\n        u_old = u\n        norm0 = one(T)\n        for k = 1:max_newt_iter\n            u_mid = 0.5*u + 0.5*u_old\n            kuramoto_sivashinsky.getKSFunc!(ks, t, u_mid, r)\n            r = u - u_old - dt*r\n            #println(\"\\tNewton iter \",k,\": res norm = \",norm(r))\n            if k == 1 \n                norm0 = norm(r)\n            else \n                if norm(r) < newt_tol*norm0 \n                    break\n                end\n            end \n            kuramoto_sivashinsky.getKSJac!(ks, t, u_mid, Jac)\n            Jac *= 0.5*dt \n            Jac -= I #speye(T, num_nodes)            \n            lu!(F, Jac) \n            du = F\\r \n            u += du \n        end\n        t += dt\n        sol[2:end-1,n+1] = u\n    end \n    return sol\nend\n\n\"\"\"\n    avg = calcSolutionAverage(order, sol, func)\n\nReturns the space and time average of `func(sol[:,:])` using an `order` order\naccurate diagonal norm scheme.\n\"\"\"\nfunction calcSolutionAverage(order::Int, sol::AbstractArray{T,2},\n                             func::Function) where {T}\n    avg = zero(T)\n    quad = convert(Vector{T}, buildQuadrature(order))\n    num_bndry = size(quad,1)\n    for n = 1:size(sol,2)\n        wt = one(T) \n        if n <= num_bndry\n            wt *= quad[n]\n        elseif n >= size(sol,2) - num_bndry + 1\n            wt *= quad[size(sol,2)-n+1]\n        end      \n        for i = 1:size(sol,1)\n            if i <= num_bndry\n                avg += func(sol[i,n])*wt*quad[i]\n            elseif i >= size(sol,1) - num_bndry + 1\n                avg += func(sol[i,n])*wt*quad[size(sol,1)-i+1]\n            else \n                avg += func(sol[i,n])*wt\n            end\n        end \n    end \n    avg /= (size(sol,1)-1)*(size(sol,2)-1)\n    return avg \nend\n\n\n# function factorBandedSparse(A::SparseMatrixCSC{T,Int64}) where {T} \n\n#     fac = one(T)\n#     # loop over the elementary matrix operations \n#     for k = 1:A.m-1\n#         # update column k of the lower triangular matrix\n#         # This assumes the rows are sorted, which Julia matrices should be \n#         for ptr = A.colptr[k]:A.colptr[k+1]-1\n#             if rowval[ptr] > k\n#                 continue\n#             elseif rowval[ptr] == k\n#                 fac = one(T)/A.nzval[ptr]\n#             else\n#                 A.nzval[ptr] *= fac\n#             end\n#         end\n#         # apply the elementary matrix to the lower block matrix \n#         for j = k+1:A.n \n#             if A.rowval[A.colptr[j]] > k \n#                 break # there are no further nonzeros in row k beyond col j\n#             end\n#             for ptr = A.colptr[j]:A.colptr[j+1]-1\n#                 i = A.rowval[ptr] \n#                 if i <= k continue end             \n#                 A.nzval[ptr] -= A[i,k]*A[k,j] # this is not efficient \n#             end\n#         end\n#     end\n# end \n\nend # module", "meta": {"hexsha": "f6d1d9b1a390f2fb74eb66f8b885a1ead7e7134a", "size": 20534, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "kuramoto-sivashinsky/kuramoto-sivashinsky.jl", "max_stars_repo_name": "jehicken/high-order-and-chaos", "max_stars_repo_head_hexsha": "dad3576698956f99f65fe630fe0c0c27a7ff2eac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kuramoto-sivashinsky/kuramoto-sivashinsky.jl", "max_issues_repo_name": "jehicken/high-order-and-chaos", "max_issues_repo_head_hexsha": "dad3576698956f99f65fe630fe0c0c27a7ff2eac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kuramoto-sivashinsky/kuramoto-sivashinsky.jl", "max_forks_repo_name": "jehicken/high-order-and-chaos", "max_forks_repo_head_hexsha": "dad3576698956f99f65fe630fe0c0c27a7ff2eac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6493055556, "max_line_length": 80, "alphanum_fraction": 0.5766046557, "num_tokens": 6555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.781669641911332}}
{"text": "module IRSpectrum\n\nusing FFTW\n\nexport autocorrelation,\n       read_cp2k_dipoles,\n       spectrum\n\n\n\"\"\"\nread_cp2k_dipoles(fname) -> Matrix{Float64}\n\nRead dipole trajectory file created by CP2K and return dipolemoments as\na two dimensional array.\n\"\"\"\nfunction read_cp2k_dipoles(fname::AbstractString)\n    out = Float64[]\n    open(fname,\"r\") do file\n        re = r\"X=\\ +(?<X>-?\\d+.?\\d+)\\ +Y=\\ +(?<Y>-?\\d+.?\\d+)\\ +Z=\\ +(?<Z>-?\\d+.?\\d+)\"\n        for line in eachline(file)\n            m = match(re, line)\n            if m !== nothing\n                push!(out,parse(Float64,m[:X]))\n                push!(out,parse(Float64,m[:Y]))\n                push!(out,parse(Float64,m[:Z]))\n            end\n        end\n    end\n    if length(out)%3 == 0\n        return reshape(out, (3, Int(length(out)/3)))\n    else\n        error(\"Error in reading file\")\n    end\nend\n\n\n\"\"\"\nautocorrelation(μ::AbstractMatrix) -> Vector\n\nCalculates autocorrelation function using [Wiener-Khinchin Theorem](http://mathworld.wolfram.com/Wiener-KhinchinTheorem.html).\n\"\"\"\nfunction autocorrelation(μ::AbstractMatrix)\n    tmp = [ fft(abs2.(ifft(r))) for r in eachrow(μ)]\n    return real.(reduce(+,tmp))\nend\n\n\n\"\"\"\nspectrum(μ::AbstractMatrix; tstep=0.5, maxfreq=4000) -> Dict\n\nCalculates spectrum from dipolemoment trajectory. Calculates autocorrelation function and\nits Fourier transform.\n\n# Arguments\n- `μ::AbstractMatrix` :  data where autocorrelation funtion is calculated for each row\n\n# Keywords\n- `tstep` : timestep for trajectory in fempto seconds\n- `maxfreq` : maximum frequency in wavenumbers for resulting spectrum\n\n# Returns\n- `Dict` : with fields `\"absorption\"` and `\"wavenumber\"`.\n\"\"\"\nfunction spectrum(μ::AbstractMatrix; tstep=0.5, maxfreq=4000)\n    l = size(μ)[2]\n    lh = Int(floor(l/2))\n    acor = autocorrelation(μ)\n    s = abs.(fft(acor))[1:lh]\n    # freq = n/NΔ and wavenumber = freq/100c\n    w = [ n/(l*tstep*1E-15*299792458E2) for n in 1:lh ]\n    i = w .<= maxfreq\n    return Dict(\"absorption\"=>s[i], \"wavenumber\"=>w[i])\nend\n\n\n\"\"\"\nspectrum(fname::AbstractString; tstep=0.5, maxfreq=4000) -> Dict\n\nRead dipolemoments from CP2K dipole file `fname` and calculate spectrum.\n\"\"\"\nfunction spectrum(fname::AbstractString; tstep=0.5, maxfreq=4000)\n    μ = read_cp2k_dipoles(fname)\n    return spectrum(μ; tstep=tstep, maxfreq=maxfreq)\nend\n\nend # module\n", "meta": {"hexsha": "5dbb3fc89db081934a8ad8b5b8a2f939a175b248", "size": 2322, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/IRSpectrum.jl", "max_stars_repo_name": "MatrixLabTools/IRSpectrum.jl", "max_stars_repo_head_hexsha": "3a38b7a84d68488a9f9458b3fa80a0ab19a840cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/IRSpectrum.jl", "max_issues_repo_name": "MatrixLabTools/IRSpectrum.jl", "max_issues_repo_head_hexsha": "3a38b7a84d68488a9f9458b3fa80a0ab19a840cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-01-09T13:59:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-12T13:16:56.000Z", "max_forks_repo_path": "src/IRSpectrum.jl", "max_forks_repo_name": "MatrixLabTools/IRSpectrum.jl", "max_forks_repo_head_hexsha": "3a38b7a84d68488a9f9458b3fa80a0ab19a840cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6896551724, "max_line_length": 126, "alphanum_fraction": 0.649870801, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.8499711680567799, "lm_q1q2_score": 0.7816696289319895}}
{"text": "# single qubit Cliffords\n\nexport localclifford\n\nconst pX = [0 1; 1 0]\nconst pY = [0 -im; im 0]\nconst pZ = [1 0; 0 -1]\n\nC1 = Vector{Clifford}(24)\n\n# identity\nC1[1]  = RI\n\n# pi/2 and pi rotations about X,Y,Z\nC1[2]  = expm(-im*pi/4*pX)\nC1[3]  = im * pX\nC1[4]  = expm(im*pi/4*pX)\nC1[5]  = expm(-im*pi/4*pY)\nC1[6]  = im * pY\nC1[7]  = expm(im*pi/4*pY)\nC1[8]  = expm(-im*pi/4*pZ)\nC1[9]  = im * pZ\nC1[10] = expm(im*pi/4*pZ)\n\n# Hadamard class\nC1[11] = expm(-im*pi/2/sqrt(2) * (pX+pY))\nC1[12] = expm(-im*pi/2/sqrt(2) * (pX-pY))\nC1[13] = expm(-im*pi/2/sqrt(2) * (pX+pZ)) # standard Hadamard\nC1[14] = expm(-im*pi/2/sqrt(2) * (pX-pZ))\nC1[15] = expm(-im*pi/2/sqrt(2) * (pY+pZ))\nC1[16] = expm(-im*pi/2/sqrt(2) * (pY-pZ))\n\n# Axis exchange class\nC1[17] = expm(-1im*pi/3/sqrt(3) * (pX+pY+pZ))\nC1[18] = expm(-2im*pi/3/sqrt(3) * (pX+pY+pZ))\nC1[19] = expm(-1im*pi/3/sqrt(3) * (pX-pY+pZ))\nC1[20] = expm(-2im*pi/3/sqrt(3) * (pX-pY+pZ))\nC1[21] = expm(-1im*pi/3/sqrt(3) * (pX+pY-pZ))\nC1[22] = expm(-2im*pi/3/sqrt(3) * (pX+pY-pZ))\nC1[23] = expm(-1im*pi/3/sqrt(3) * (-pX+pY+pZ))\nC1[24] = expm(-2im*pi/3/sqrt(3) * (-pX+pY+pZ))\n\nrC1 = Dict{Clifford,UInt}()\n\nfor (k,v) in enumerate(C1)\n    rC1[v] = k\nend\n\nlocalclifford(i::Int) = C1[i]\nlocalclifford(v::Vector) = kron(C1[v]...)\n\nlocalcliffordindex(c::Clifford) = rC1[c]\n", "meta": {"hexsha": "ba8697b583f2c2f75d9ce71aa5799435dc78519f", "size": 1290, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/C1.jl", "max_stars_repo_name": "JuliaPackageMirrors/Cliffords.jl", "max_stars_repo_head_hexsha": "92ca97025539c44e79a217a2b7a98586422f2bd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-10T02:56:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-10T02:56:06.000Z", "max_issues_repo_path": "src/C1.jl", "max_issues_repo_name": "JuliaPackageMirrors/Cliffords.jl", "max_issues_repo_head_hexsha": "92ca97025539c44e79a217a2b7a98586422f2bd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/C1.jl", "max_forks_repo_name": "JuliaPackageMirrors/Cliffords.jl", "max_forks_repo_head_hexsha": "92ca97025539c44e79a217a2b7a98586422f2bd7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3396226415, "max_line_length": 61, "alphanum_fraction": 0.5713178295, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813463747182, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7815859485132045}}
{"text": "function K_eular_shear(beam::Beam)::Matrix{Float64}\n    E,ν=beam.material.E,beam.material.ν\n    A,I₂,I₃,J,l=beam.section.A,beam.section.I₂,beam.section.I₃,beam.section.J,beam.l\n    As₂,As₃=beam.section.As₂,beam.section.As₃\n    G=E/2/(1+ν)\n    ϕ₂,ϕ₃=12E*I₃/(G*As₂*l^2),12E*I₂/(G*As₃*l^2)\n    K=zeros(12,12)\n    K[1,1]=E*A/l\n    K[2,2]=12E*I₃/l^3/(1+ϕ₂)\n    K[3,3]=12E*I₂/l^3/(1+ϕ₃)\n    K[4,4]=G*J/l\n    K[5,5]=(4+ϕ₃)*E*I₂/l/(1+ϕ₃)\n    K[6,6]=(4+ϕ₂)*E*I₃/l/(1+ϕ₂)\n    K[7,7]=E*A/l\n    K[8,8]=12E*I₃/l^3/(1+ϕ₂)\n    K[9,9]=12E*I₂/l^3/(1+ϕ₃)\n    K[10,10]=G*J/l\n    K[11,11]=(4+ϕ₃)*E*I₂/l/(1+ϕ₃)\n    K[12,12]=(4+ϕ₂)*E*I₃/l/(1+ϕ₂)\n\n    K[3,5]=K[5,3]=-6E*I₂/l^2/(1+ϕ₃)\n    K[6,8]=K[8,6]=-6E*I₃/l^2/(1+ϕ₂)\n    K[9,11]=K[11,9]=6E*I₂/l^2/(1+ϕ₃)\n\n    K[2,6]=K[6,2]=6E*I₃/l^2/(1+ϕ₂)\n    K[5,9]=K[9,5]=6E*I₂/l^2/(1+ϕ₃)\n    K[8,12]=K[12,8]=-6E*I₃/l^2/(1+ϕ₂)\n\n    K[7,1]=K[1,7]=-E*A/l\n    K[8,2]=K[2,8]=-12E*I₃/l^3/(1+ϕ₂)\n    K[9,3]=K[3,9]=-12E*I₂/l^3/(1+ϕ₃)\n    K[10,4]=K[4,10]=-G*J/l\n    K[11,5]=K[5,11]=(2-ϕ₃)*E*I₂/l/(1+ϕ₃)\n    K[12,6]=K[6,12]=(2-ϕ₂)*E*I₃/l/(1+ϕ₂)\n\n    K[3,11]=K[11,3]=-6E*I₂/l^2/(1+ϕ₃)\n\n    K[2,12]=K[12,2]=6E*I₃/l^2/(1+ϕ₂)\n\n    return K\nend\n\nfunction K2_eular_shear(beam::Beam)::Matrix{Float64}\n    E,ν=beam.material.E,beam.material.ν\n    A,I₂,I₃,J,l=beam.section.A,beam.section.I₂,beam.section.I₃,beam.section.J,beam.l\n    As₂,As₃=beam.section.As₂,beam.section.As₃\n    G=E/2/(1+ν)\n    T=σ*A\n    ϕ₂,ϕ₃=12E*I₃/(G*As₂*l^2),12E*I₂/(G*As₃*l^2)\n    K=zeros(12,12)\n\n    K[2,2]=(6/5+2ϕ₂+ϕ₂^2)/(1+ϕ₂)^2\n    K[3,3]=(6/5+2ϕ₃+ϕ₃^2)/(1+ϕ₃)^2\n    K[4,4]=J/A\n    K[5,5]=(2*l^2/15+l^2*ϕ₃/6+l^2*ϕ₃^2/12)/(1+ϕ₃)^2\n    K[6,6]=(2*l^2/15+l^2*ϕ₂/6+l^2*ϕ₂^2/12)/(1+ϕ₂)^2\n    K[8,8]=(6/5+2ϕ₂+ϕ₂^2)/(1+ϕ₂)^2\n    K[9,9]=(6/5+2ϕ₃+ϕ₃^2)/(1+ϕ₃)^2\n    K[10,10]=J/A\n    K[11,11]=(2*l^2/15+l^2*ϕ₃/6+l^2*ϕ₃^2/12)/(1+ϕ₃)^2\n    K[12,12]=(2*l^2/15+l^2*ϕ₂/6+l^2*ϕ₂^2/12)/(1+ϕ₂)^2\n\n    K[3,5]=K[5,3]=-(l/10)/(1+ϕ₃)^2\n    K[6,8]=K[8,6]=-(l/10)/(1+ϕ₂)^2\n    K[9,11]=K[11,9]=(l/10)/(1+ϕ₃)^2\n\n    K[2,6]=K[6,2]=(l/10)/(1+ϕ₂)^2\n    K[5,9]=K[9,5]=(l/10)/(1+ϕ₃)^2\n\n    K[2,8]=K[8,2]=-(6/5+2ϕ₂+ϕ₂^2)/(1+ϕ₂)^2\n    K[3,9]=K[9,3]=-(6/5+2ϕ₃+ϕ₃^2)/(1+ϕ₃)^2\n    K[4,10]=K[10,4]=-J/A\n    K[5,11]=K[11,5]=-(l^2/30+l^2*ϕ₃/6+l^2*ϕ₃^2/12)/(1+ϕ₃)^2\n    K[6,12]=K[12,6]=-(l^2/30+l^2*ϕ₂/6+l^2*ϕ₂^2/12)/(1+ϕ₂)^2\n\n    K[3,11]=K[11,3]=-(l/10)/(1+ϕ₃)^2\n\n    K[2,12]=K[12,2]=(l/10)/(1+ϕ₂)^2\n\n    K*=T/l\n    return K\nend\n", "meta": {"hexsha": "801eff530d1901a5788516eb7ee5a1f096fdc37a", "size": 2362, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/structure/beams/eular_shear.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Mozi.jl-938b0b66-b18d-59c3-b436-87bb841ccf42", "max_stars_repo_head_hexsha": "392c31542dc2c8cc95ea87e06c258be2f4d0de37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/structure/beams/eular_shear.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Mozi.jl-938b0b66-b18d-59c3-b436-87bb841ccf42", "max_issues_repo_head_hexsha": "392c31542dc2c8cc95ea87e06c258be2f4d0de37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/structure/beams/eular_shear.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Mozi.jl-938b0b66-b18d-59c3-b436-87bb841ccf42", "max_forks_repo_head_hexsha": "392c31542dc2c8cc95ea87e06c258be2f4d0de37", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4578313253, "max_line_length": 84, "alphanum_fraction": 0.4919559695, "num_tokens": 1607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013548, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7815838610963728}}
{"text": "function giant_component_size(g, present)\r\n    n = nv(g)\r\n    Q = Queue{Int}()\r\n\tlabel = zeros(Int,n)\r\n\tcnt = zeros(Int,n)\r\n\tmaxcnt = 0\r\n    @inbounds for u in vertices(g)\r\n\t\tif present[u]\r\n\t        label[u] != 0 && continue\r\n\t        label[u] = u\r\n\t\t\tcnt[u] += 1\r\n\t        enqueue!(Q, u)\r\n\t        while !isempty(Q)\r\n\t            src = dequeue!(Q)\r\n\t            for vertex in all_neighbors(g, src)\r\n\t\t\t\t\tif present[vertex]\r\n\t\t                if label[vertex] == 0\r\n\t\t                    enqueue!(Q, vertex)\r\n\t\t                    label[vertex] = u\r\n\t\t\t\t\t\t\tcnt[u] += 1\r\n\t\t                end\r\n\t\t\t\t\tend\r\n\t            end\r\n\t        end\r\n\t\t\tif cnt[u] > maxcnt\r\n\t\t\t\tmaxcnt = cnt[u]\r\n\t\t\tend\r\n\t\tend\r\n    end\r\n    return maxcnt\r\nend\r\n\r\nfunction recover_add_nodes(g, attack_nodes)\r\n\tn = nv(g)\r\n\tmax_comp_sizes = Int[]\r\n\tds = IntDisjointSets(n)\r\n\tpresent = fill(true, n)\r\n\tpresent[attack_nodes] .= false\r\n\tcomp_sizes = ones(Int, n)\r\n\tmax_comp_size = 1\r\n\r\n\t# add edges between present nodes and record component sizes\r\n\tfor i in vertices(g)\r\n\t\tif present[i]\r\n\t\t\tfor j in neighbors(g,i)\r\n\t\t\t\tif present[j]\r\n\t\t\t\t\tnewroot = merge_nodes!(ds, comp_sizes, i, j)\r\n\t\t\t\t\tif comp_sizes[newroot] > max_comp_size\r\n\t\t\t\t\t\tmax_comp_size = comp_sizes[newroot]\r\n\t\t\t\t\tend\r\n\t\t\t\tend\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\n\r\n\tfor i in reverse(attack_nodes)\r\n\t\tfor j in neighbors(g, i)\r\n\t\t\tif present[j]\r\n\t\t\t\tnewroot = merge_nodes!(ds, comp_sizes, i, j)\r\n\t\t\t\tif comp_sizes[newroot] > max_comp_size\r\n\t\t\t\t\tmax_comp_size = comp_sizes[newroot]\r\n\t\t\t\tend\r\n\t\t\tend\r\n\t\tend\r\n\t\tpresent[i] = true\r\n\t\tpush!(max_comp_sizes, max_comp_size)\r\n\tend\r\n\treverse(max_comp_sizes)\r\nend\r\n", "meta": {"hexsha": "1519d2103d44079b96580e5fe98b4bd862ed11c7", "size": 1614, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "afternone/-NetworkDismantling.jl", "max_stars_repo_head_hexsha": "0b2788602510a07f996a6f5c4070795c45f5bb41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-30T04:37:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T04:37:37.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "afternone/NetworkDismantle.jl", "max_issues_repo_head_hexsha": "0b2788602510a07f996a6f5c4070795c45f5bb41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "afternone/NetworkDismantle.jl", "max_forks_repo_head_hexsha": "0b2788602510a07f996a6f5c4070795c45f5bb41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0571428571, "max_line_length": 62, "alphanum_fraction": 0.56133829, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7815809002006521}}
{"text": "#---------------------------------------------------------------------#\n#This code computes the Chebyshev points & weights\n#Written by F.X. Giraldo on 7/2014\n#           Department of Applied Mathematics\n#           Naval Postgraduate School\n#           Monterey; CA 93943-5216\n#---------------------------------------------------------------------#\nfunction chebyshev_gauss(P::Integer)\n\n    #Initialize arrays\n    xgl=zeros(P)\n    wgl=zeros(P)\n\n    #Construct arrays\n    for i=1:P\n        xgl[P+1-i]=cos( (2*i-1)*pi/(2*P) );\n        wgl[P+1-i]=pi/P\n    end\n    return (xgl,wgl)\nend #function\n", "meta": {"hexsha": "4d91f4874c57148c87b53415a878fb6ec24c5a09", "size": 593, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Projects/Project_01_1D_Interpolation/For_Instructors/julia/chebyshev_gauss.jl", "max_stars_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_stars_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-12-28T06:19:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:40:33.000Z", "max_issues_repo_path": "Projects/Project_01_1D_Interpolation/For_Students/julia/chebyshev_gauss.jl", "max_issues_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_issues_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-29T19:12:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-29T21:53:41.000Z", "max_forks_repo_path": "Projects/Project_01_1D_Interpolation/For_Students/julia/chebyshev_gauss.jl", "max_forks_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_forks_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:35:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T06:53:34.000Z", "avg_line_length": 28.2380952381, "max_line_length": 71, "alphanum_fraction": 0.4637436762, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.964321448096903, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7815621904465678}}
{"text": "using Plots\n\nusing ForwardDiff\neta_d = 1.0\neta_e = 0.5\n\npot(eta, e) = 1/eta * log(exp(eta*e) + exp(-eta*e))\n\n\ne(y, y0) = abs(y0 - y)\n\n\n\n\n\nyd = 0.5\nye = 1.0\n\npotd(y) = pot(eta_d, e(y, yd))\npote(y) = pot(eta_e, e(y, ye))\n\npot2(y) = (pot(eta_d, e(y, yd)) + pot(eta_e, e(y, ye)))/2\n\n\n# plot(potd, label=\"d\")\n# plot!(pote, label=\"e\")\n# plot!(pot2, label=\"sum\")\n\n\nnabla_pot2(y) = ForwardDiff.derivative(pot2, y)\n\n\ny = -2.0:0.01:2.0\np2 = pot2.(y)\npd = potd.(y)\npe = pote.(y)\n\ndp2 = [nabla_pot2(_y) for _y in y]\n\nplot(y, p2, label=\"p2\")\nplot!(y, dp2,label=\"dp2\")\nplot!(y, pd, label=\"pd\")\nplot!(y, pe, label=\"pe\")\n", "meta": {"hexsha": "f520d08162dd04c27290b9508bd67db063d5a723", "size": 605, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "misc/potential_.jl", "max_stars_repo_name": "YoshimitsuMatsutaIe/manipulator_dynamics", "max_stars_repo_head_hexsha": "587b3cedddd07c2aa09d1195289b0c312e0fc749", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "misc/potential_.jl", "max_issues_repo_name": "YoshimitsuMatsutaIe/manipulator_dynamics", "max_issues_repo_head_hexsha": "587b3cedddd07c2aa09d1195289b0c312e0fc749", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc/potential_.jl", "max_forks_repo_name": "YoshimitsuMatsutaIe/manipulator_dynamics", "max_forks_repo_head_hexsha": "587b3cedddd07c2aa09d1195289b0c312e0fc749", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.75, "max_line_length": 57, "alphanum_fraction": 0.5636363636, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214460461698, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7815621865772941}}
{"text": "abstract type AbstractSplineLayer <: Function end\nFlux.trainable(m::AbstractSplineLayer) = (m.p,)\n\n\"\"\"\nConstructs a Spline Layer. At a high-level, it performs the following:\n1. Takes as input a one-dimensional training dataset, a time span, a time step and\nan interpolation method.\n2. During training, adjusts the values of the function at multiples of the time-step\nsuch that the curve interpolated through these points has minimum loss on the corresponding\none-dimensional dataset.\n\n```julia\nSplineLayer(time_span,time_step,spline_basis,saved_points=nothing)\n```\nArguments:\n- `time_span`: Tuple of real numbers corresponding to the time span.\n- `time_step`: Real number corresponding to the time step.\n- `spline_basis`: Interpolation method to be used yb the basis (current supported\n  interpolation methods: ConstantInterpolation, LinearInterpolation, QuadraticInterpolation,\n  QuadraticSpline, CubicSpline).\n- 'saved_points': values of the function at multiples of the time step. Initialized by default\nto a random vector sampled from the unit normal.\n\"\"\"\nstruct SplineLayer{T<:Tuple{Real, Real},R<:Real,S1<:AbstractVector,S2<:UnionAll} <: AbstractSplineLayer\n    time_span::T\n    time_step::R\n    saved_points::S1\n    spline_basis::S2\n    function SplineLayer(time_span,time_step,spline_basis,saved_points=nothing)\n        saved_points = randn(length(time_span[1]:time_step:time_span[2]))\n        new{typeof(time_span),typeof(time_step),typeof(saved_points),typeof(spline_basis)}(time_span,time_step,saved_points,spline_basis)\n    end\nend\n\nfunction (layer::SplineLayer)(t::Real,p=layer.saved_points)\n    return layer.spline_basis(p,layer.time_span[1]:layer.time_step:layer.time_span[2])(t)\nend\n", "meta": {"hexsha": "a6089176ff3335461a01f1c6a2dcbee9260fdf13", "size": 1699, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spline_layer.jl", "max_stars_repo_name": "achuchmala/DiffEqFlux.jl", "max_stars_repo_head_hexsha": "7f2a25d0f3f86161127edd5e3f36bf19c8b5c50d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 472, "max_stars_repo_stars_event_min_datetime": "2020-03-29T08:59:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T12:24:46.000Z", "max_issues_repo_path": "src/spline_layer.jl", "max_issues_repo_name": "achuchmala/DiffEqFlux.jl", "max_issues_repo_head_hexsha": "7f2a25d0f3f86161127edd5e3f36bf19c8b5c50d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 356, "max_issues_repo_issues_event_min_datetime": "2020-03-25T15:46:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:37:25.000Z", "max_forks_repo_path": "src/spline_layer.jl", "max_forks_repo_name": "achuchmala/DiffEqFlux.jl", "max_forks_repo_head_hexsha": "7f2a25d0f3f86161127edd5e3f36bf19c8b5c50d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 114, "max_forks_repo_forks_event_min_datetime": "2020-03-26T21:34:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T21:45:50.000Z", "avg_line_length": 44.7105263158, "max_line_length": 137, "alphanum_fraction": 0.7822248381, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.8418256452674009, "lm_q1q2_score": 0.7815583442696045}}
{"text": "# Tests the null of normality using the Jarque-Bera test statistic.\nfunction jbtest(x::Vector)\n    n = length(x)\n    m1 = sum(x)/n\n    m2 = sum((x - m1).^2)/n\n    m3 = sum((x - m1).^3)/n\n    m4 = sum((x - m1).^4)/n\n    b1 = (m3/m2^(3/2))^2\n    b2 = (m4/m2^2)\n    statistic = n * b1/6 + n*(b2 - 3)^2/24\n    d = Chisq(2.)\n    pvalue = 1.-cdf(d,statistic)\n    statistic, pvalue\nend\n\n", "meta": {"hexsha": "9b60c17b402e7b8d3e7a9edcf4595d39a445013b", "size": 380, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/diagnostic_tests.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/TimeModels.jl-69470c01-11c1-51f0-b04c-03fbc3a7dfa2", "max_stars_repo_head_hexsha": "655fe3cd0d689955e698491af42e7783a4cc3bbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 60, "max_stars_repo_stars_event_min_datetime": "2015-03-20T08:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T11:45:40.000Z", "max_issues_repo_path": "src/diagnostic_tests.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/TimeModels.jl-69470c01-11c1-51f0-b04c-03fbc3a7dfa2", "max_issues_repo_head_hexsha": "655fe3cd0d689955e698491af42e7783a4cc3bbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44, "max_issues_repo_issues_event_min_datetime": "2015-04-14T15:50:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-16T21:12:21.000Z", "max_forks_repo_path": "src/diagnostic_tests.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/TimeModels.jl-69470c01-11c1-51f0-b04c-03fbc3a7dfa2", "max_forks_repo_head_hexsha": "655fe3cd0d689955e698491af42e7783a4cc3bbc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2015-05-06T12:12:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T01:37:58.000Z", "avg_line_length": 23.75, "max_line_length": 67, "alphanum_fraction": 0.5289473684, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7815583442696044}}
{"text": "@doc raw\"\"\"\n    MinimumError <: AbstractImageBinarizationAlgorithm\n    MinimumError()\n\n    binarize([T,] img, f::MinimumError)\n    binarize!([out,] img, f::MinimumError)\n\nUnder the assumption that the image histogram is a mixture of two Gaussian\ndistributions the binarization threshold is chosen such that the expected\nmisclassification error rate is minimised.\n\n# Output\n\nReturn the binarized image as an `Array{Gray{T}}` of size `size(img)`. If\n`T` is not specified, it is inferred from `out` and `img`.\n\n# Details\n\nLet ``f_i`` ``(i=1 \\ldots I)`` denote the number of observations in the\n``i``th bin of the histogram. Then the probability that an observation\nbelongs to the ``i``th bin is given by  ``p_i = \\frac{f_i}{N}`` (``i = 1,\n\\ldots, I``), where ``N = \\sum_{i=1}^{I}f_i``.\n\nThe minimum error thresholding method assumes that one can find a threshold\n``T`` which partitions the data into two categories,  ``C_0`` and ``C_1``, such that\nthe data can be modelled by a mixture of two Gaussian distribution. Let\n```math\nP_0(T) = \\sum_{i = 1}^T p_i \\quad \\text{and} \\quad P_1(T) = \\sum_{i = T+1}^I p_i\n```\ndenote the cumulative probabilities,\n```math\n\\mu_0(T) = \\sum_{i = 1}^T i \\frac{p_i}{P_0(T)} \\quad \\text{and} \\quad \\mu_1(T) = \\sum_{i = T+1}^I i \\frac{p_i}{P_1(T)}\n```\ndenote the means, and\n```math\n\\sigma_0^2(T) = \\sum_{i = 1}^T (i-\\mu_0(T))^2 \\frac{p_i}{P_0(T)} \\quad \\text{and} \\quad \\sigma_1^2(T) = \\sum_{i = T+1}^I (i-\\mu_1(T))^2 \\frac{p_i}{P_1(T)}\n```\ndenote the variances of categories ``C_0`` and ``C_1``, respectively.\n\nKittler and Illingworth proposed to use the minimum error criterion function\n```math\nJ(T) = 1 + 2 \\left[ P_0(T) \\ln \\sigma_0(T) + P_1(T) \\ln \\sigma_1(T) \\right] - 2 \\left[P_0(T) \\ln P_0(T) + P_1(T) \\ln P_1(T) \\right]\n```\nto assess the discreprancy between the mixture of Gaussians implied by a particular threshold ``T``,\nand the piecewise-constant probability density function represented by the histogram.\nThe discrete value ``T`` which minimizes the function ``J(T)`` produces\nthe sought-after threshold value (i.e. the bin which determines the threshold).\n\n# Arguments\n\nThe function argument is described in more detail below.\n\n##  `img::AbstractArray`\n\nThe image that needs to be binarized. The image is automatically converted\nto `Gray` in order to construct the requisite graylevel histogram.\n\n# Example\n\nBinarize the \"cameraman\" image in the `TestImages` package.\n\n```julia\nusing TestImages, ImageBinarization\n\nimg = testimage(\"cameraman\")\nimg_binary = binarize(img, MinimumError())\n```\n\n# References\n\n1. J. Kittler and J. Illingworth, “Minimum error thresholding,” Pattern Recognition, vol. 19, no. 1, pp. 41–47, Jan. 1986. [doi:10.1016/0031-3203(86)90030-0](https://doi.org/10.1016/0031-3203%2886%2990030-0)\n2. Q.-Z. Ye and P.-E. Danielsson, “On minimum error thresholding and its implementations,” Pattern Recognition Letters, vol. 7, no. 4, pp. 201–206, Apr. 1988. [doi:10.1016/0167-8655(88)90103-1](https://doi.org/10.1016/0167-8655%2888%2990103-1)\n\"\"\"\nstruct MinimumError <: AbstractImageBinarizationAlgorithm end\n\nfunction (f::MinimumError)(out::GenericGrayImage, img::GenericGrayImage)\n    edges, counts = build_histogram(img,  256)\n    t = find_threshold(HistogramThresholding.MinimumError(), counts[1:end], edges)\n    @simd for i in CartesianIndices(img)\n        out[i] = img[i] < t ? 0 : 1\n    end\n    out\nend\n\n(f::MinimumError)(out::GenericGrayImage, img::AbstractArray{<:Color3}) =\n    f(out, of_eltype(Gray, img))\n", "meta": {"hexsha": "03ac1f536e28c04bdb6f973caae57e6a9d7836df", "size": 3474, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algorithms/minimum_error.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ImageBinarization.jl-cbc4b850-ae4b-5111-9e64-df94c024a13d", "max_stars_repo_head_hexsha": "e6b3b13279196544e815c821e45e2bef37c18376", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algorithms/minimum_error.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ImageBinarization.jl-cbc4b850-ae4b-5111-9e64-df94c024a13d", "max_issues_repo_head_hexsha": "e6b3b13279196544e815c821e45e2bef37c18376", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithms/minimum_error.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ImageBinarization.jl-cbc4b850-ae4b-5111-9e64-df94c024a13d", "max_forks_repo_head_hexsha": "e6b3b13279196544e815c821e45e2bef37c18376", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-13T20:29:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-13T20:29:41.000Z", "avg_line_length": 39.9310344828, "max_line_length": 243, "alphanum_fraction": 0.7032239493, "num_tokens": 1134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.781558343300477}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.5\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ ad96c6b4-add2-11eb-1a72-8993033e1259\nusing Plots, LaTeXStrings, QuadGK, Roots, DifferentialEquations\n\n# ╔═╡ 5168971b-2b60-494c-a8d8-cdfa8e1b8102\nmd\"# 1D Bistable Example\"\n\n# ╔═╡ 261580d9-f1a5-442c-8e7f-3479f993f9b2\nmd\"_Define separate production and degradation terms_\"\n\n# ╔═╡ 02d0fcf2-ca87-49ae-a8f3-f14310d0182a\nbegin\n\tn_max = 200.\n\tn_min = 1 # need to avoid 0 for log we'll evaluate later\n\tn = n_min:0.1:n_max\n\tγ = 1\n\tks = 1e-4\n\tν0 = 12.5\n\tν1 = 200\n\tproduction(n) = (ν0+ ν1 * ks*n^2)/(1+ks*n^2)\n\tdegradation(n) = γ*n\nend\n\n# ╔═╡ 13ddc727-e9bd-44f2-ba5e-c6c311b41723\nbegin\n\t\n\tplot(production, n, label=L\"f(n)\")\n\tp1 = plot!(degradation, n, label=L\"g(n)\", xlabel=L\"n\", title=\"Rate of Change\", scale=:log10, xlimits=(15, n_max), ylimits=(15, 200), legend=:topleft)\n# plot!(n->production(n)  - degradation(n), n, label=L\"\\frac{dn}{dt}\", \n# \t\tylims=(-20, 150), xlims=(0, 150), legend=:topleft, title=\"Time evolution\")\nend\n\n# ╔═╡ 868ba091-d0d2-42a2-bca7-f9e996b3870d\nmd\"_Compute the fixed points to split up the 2 attractors into **Basins of Attractions**_\" \n\n# ╔═╡ 348718a0-8e19-4911-8998-5de9689bce1d\nfixed_points = find_zeros(n-> production(n) - degradation(n), n_min, n_max)\n\n# ╔═╡ 51d6af76-5ed3-41f8-9351-91e683c7bb57\nmd\"_Integrate to get the quasi-potential_\"\n\n# ╔═╡ acb0adcf-fc19-45cf-bf0f-eb5532743b1a\nbegin\n\tf = production\n\tg = degradation\n\t\n\tϕ(n) = quadgk(n -> -2*(f(n) -g(n))/(f(n) + g(n)), n_min, n)[1]\nend\n\n# ╔═╡ b4c511ea-fc96-475e-a5fc-1c9e282ca0e5\nϕ_vec = ϕ.(n)\n\n# ╔═╡ 3373f26d-a6a4-4378-a8e1-c011c2e9f7a9\np2 = plot(n, ϕ_vec, ylabel=L\"\\phi(n)\", xlabel=L\"n\", label=\"\", title=\"Quasi-potential\")\n\n# ╔═╡ e147802a-2cc5-4610-821b-bf351ed62f9f\nmd\"_Show the the probability due to the quasi-potential dominates compared to the other term in the equation_\"\n\n# ╔═╡ 178564ff-da53-4dd5-ba1f-b3e5db24b2ea\nbegin\n\tplot(n->log10.(f(n) + g(n)), n, label=L\"f + g\")\n\tplot!(n, log10.(ℯ.^(-ϕ_vec)), label=L\"e^{-\\phi}\")\n\tp3 = plot!(xaxis=:log10, legend=:topleft)\nend\n\n# ╔═╡ 33cf16fa-679d-4447-aa59-b6d48e8fd15a\nmd\"_Compute the normalized probability_\"\n\n# ╔═╡ a7e9be12-a1d4-4f1a-bbfc-d2642e5a9dd5\nbegin\n\tfn = f.(n)\n\tgn = g.(n)\n\tp_unnormal(n) =  ℯ^(-ϕ(n)) / (f(n)+g(n))\n\tnorm = quadgk(p_unnormal, n_min, n_max)[1]\n\tp_normal(n) = 1/norm * p_unnormal(n)\n\tp4 = plot(p_normal,n,  title = \"Normalized Probability\", label=\"\")\nend\n\n# ╔═╡ f5b8a081-222f-4dd6-ae4c-af7060aa4223\nmd\"_Set up the jump process simulation_\"\n\n# ╔═╡ 467386e3-2ee8-46d4-9b40-831ae2778a57\nrandom_count() = floor(Int, n_min + rand() * n_max)\n\n# ╔═╡ 6ae4ed84-80c2-4c06-b69a-c81e6485b78b\nbegin\n\taffect1!(integrator) = integrator.u += 1\n\taffect2!(integrator) = integrator.u -= 1\n\tprodJump = ConstantRateJump((u, p, t) -> f(u), affect1!)\n\tdegJump = ConstantRateJump((u, p, t) -> g(u), affect2!)\n\tu0 = random_count()\n\tt = (0.0, 5000.0)\n\tdprob = DiscreteProblem(u0, t)\n\tjprob = JumpProblem(dprob, Direct(), prodJump, degJump)\nend\n\n# ╔═╡ f32b2ab8-a941-463b-bb27-968c09e24777\nbegin\n\tsim_res = solve(jprob, SSAStepper())\n\tp5 = plot(sim_res, xlabel=L\"t\", label=L\"n(t)\", title=\"Simulation trace\")\nend\n\n# ╔═╡ 50c911b1-57cf-4de4-9d65-054318c445fe\nbegin\n\tpf = plot(p1, p2, p4, p5, layout = grid(2,2), size=(750, 750))\n\t# savefig(pf, \"ch3_bistable_prob.pdf\")\n\tpf\nend\n\n# ╔═╡ 4547d20c-dab1-4df2-aa54-b8c52b1b5eeb\nmd\"_Setup functions to do a longer time simulation and compare to integrated probability distribution_\"\n\n# ╔═╡ 456090be-e1c0-452e-b0ad-98fbc9f0576f\nfunction calculate_time_fraction(sim_result, split)\n\tdts = diff(sim_result.t)\n\tdt_vals = collect(zip(dts, map(last, sim_result.u[1:end])))\n\thigh = sum(map(first, filter(dtu -> last(dtu) > split, dt_vals)))\n\tlow = sum(map(first, filter(dtu -> last(dtu) < split, dt_vals)))\n\thigh, low\nend\n\n# ╔═╡ 23494ad1-82e3-4eee-86e3-695511de502e\nfunction big_sim(num_sim = 25)\n\tfunction prob_func(prob, i, repeat)\n        remake(prob, u0=random_count())\n    end\n\tnum_steps = 0\n    ensemble_prob = EnsembleProblem(jprob, prob_func=prob_func)\n\tsim = solve(ensemble_prob, SSAStepper(), trajectories=num_sim)\n\ttotals = [0., 0.]\n\tfor j in 1:num_sim\n\t\ttotals.+= calculate_time_fraction(sim[j], fixed_points[2])\n\t\tnum_steps += length(sim[j])\n\tend\n\ttotals, num_steps\nend\n\n# ╔═╡ 0e38a5c3-d970-4844-b560-fe4ed5452d85\ntotals, num_steps = big_sim()\n\n# ╔═╡ 573a4914-b37e-4c2b-bd23-c10b58a6d4db\nbegin\n\tsim_frac = totals./sum(totals)\nend\n\n# ╔═╡ c62dd4a3-80ce-4b1f-b5a1-6142d30d0880\nmd\"Time fractions from simulations is $(sim_frac)\"\n\n# ╔═╡ 86ee8326-51e1-453d-8d83-fd7021613c76\nbegin\n\tp_low = quadgk(p_normal, n_min, fixed_points[2])[1]\n\tp_high = quadgk(p_normal, fixed_points[2], n_max)[1]\n\tcomp_frac = p_high, p_low\nend\n\n# ╔═╡ 5cabf565-b573-4446-b34d-8812986b25fe\nmd\"Time fractions from integration of probability is $(comp_frac)\"\n\n# ╔═╡ Cell order:\n# ╠═ad96c6b4-add2-11eb-1a72-8993033e1259\n# ╟─5168971b-2b60-494c-a8d8-cdfa8e1b8102\n# ╟─261580d9-f1a5-442c-8e7f-3479f993f9b2\n# ╠═02d0fcf2-ca87-49ae-a8f3-f14310d0182a\n# ╠═13ddc727-e9bd-44f2-ba5e-c6c311b41723\n# ╟─868ba091-d0d2-42a2-bca7-f9e996b3870d\n# ╠═348718a0-8e19-4911-8998-5de9689bce1d\n# ╟─51d6af76-5ed3-41f8-9351-91e683c7bb57\n# ╠═acb0adcf-fc19-45cf-bf0f-eb5532743b1a\n# ╠═b4c511ea-fc96-475e-a5fc-1c9e282ca0e5\n# ╠═3373f26d-a6a4-4378-a8e1-c011c2e9f7a9\n# ╟─e147802a-2cc5-4610-821b-bf351ed62f9f\n# ╠═178564ff-da53-4dd5-ba1f-b3e5db24b2ea\n# ╟─33cf16fa-679d-4447-aa59-b6d48e8fd15a\n# ╠═a7e9be12-a1d4-4f1a-bbfc-d2642e5a9dd5\n# ╟─f5b8a081-222f-4dd6-ae4c-af7060aa4223\n# ╠═467386e3-2ee8-46d4-9b40-831ae2778a57\n# ╠═6ae4ed84-80c2-4c06-b69a-c81e6485b78b\n# ╠═f32b2ab8-a941-463b-bb27-968c09e24777\n# ╠═50c911b1-57cf-4de4-9d65-054318c445fe\n# ╟─4547d20c-dab1-4df2-aa54-b8c52b1b5eeb\n# ╠═456090be-e1c0-452e-b0ad-98fbc9f0576f\n# ╠═23494ad1-82e3-4eee-86e3-695511de502e\n# ╠═0e38a5c3-d970-4844-b560-fe4ed5452d85\n# ╟─c62dd4a3-80ce-4b1f-b5a1-6142d30d0880\n# ╟─5cabf565-b573-4446-b34d-8812986b25fe\n# ╠═573a4914-b37e-4c2b-bd23-c10b58a6d4db\n# ╠═86ee8326-51e1-453d-8d83-fd7021613c76\n", "meta": {"hexsha": "cb13ad814fdda86f492229c83f3a9dd997eb5cd6", "size": 5946, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "pluto/1d_bistable.jl", "max_stars_repo_name": "BolaSMalek/gene_network_examples", "max_stars_repo_head_hexsha": "fde451b386584696e50fc38264cf6da40a04619a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pluto/1d_bistable.jl", "max_issues_repo_name": "BolaSMalek/gene_network_examples", "max_issues_repo_head_hexsha": "fde451b386584696e50fc38264cf6da40a04619a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pluto/1d_bistable.jl", "max_forks_repo_name": "BolaSMalek/gene_network_examples", "max_forks_repo_head_hexsha": "fde451b386584696e50fc38264cf6da40a04619a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8082901554, "max_line_length": 150, "alphanum_fraction": 0.7134207871, "num_tokens": 2828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7815583305802452}}
{"text": "\"\"\"\nThe bistable model of mutual antagonism. To perform the bistability, the parameters are defined symmetrically, contributing to a stable system with steady-states determined by the initial state.\n\nIn this section, we are going to examine wheter this package can successfully find two steady states by grid searching and predefined ranges.\n\n\nReference\n---------\n1. p.82-p.83, Figure 4.8. Ingalls, B. P. (2013). Mathematical modeling in systems biology: an introduction. MIT press.\n\"\"\"\nfunction bistable_ode!(du, u, p ,t)\n\ts1, s2 = u\n\tK1, K2, k1, k2, k3, k4, n1 , n2  = p\n\t\n\tdu[1] = k1 / (1 + (s2/K2)^n1) - k3*s1\n\tdu[2] = k2/  (1 + (s1/K1)^n2) - k4*s2 \nend\n\np_ = LVector(K1=1., K2=1., k1=20., k2=20., k3=5., k4=5., n1= 4., n2=4.)\n\nu_1 = LVector(s1=3., s2=1.)\nu_2 = LVector(s1=1., s2=3.)", "meta": {"hexsha": "7c629502f066b635f58d737a726bd11418cb9135", "size": 787, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testutils.jl", "max_stars_repo_name": "stevengogogo/FindSteadyStates.jl", "max_stars_repo_head_hexsha": "863042b248702ff7e68c20aa69128c94b346fb5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-11-25T00:04:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T06:51:41.000Z", "max_issues_repo_path": "test/testutils.jl", "max_issues_repo_name": "stevengogogo/FindSteadyStates.jl", "max_issues_repo_head_hexsha": "863042b248702ff7e68c20aa69128c94b346fb5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 40, "max_issues_repo_issues_event_min_datetime": "2020-11-06T10:04:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T08:22:56.000Z", "max_forks_repo_path": "test/testutils.jl", "max_forks_repo_name": "stevengogogo/FindSteadyStates.jl", "max_forks_repo_head_hexsha": "863042b248702ff7e68c20aa69128c94b346fb5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7727272727, "max_line_length": 194, "alphanum_fraction": 0.665819568, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.7815519167847068}}
{"text": "abstract type AbstractStochasticProcess end\nabstract type AbstractMarkovChain <: AbstractStochasticProcess end\n\n\n\"\"\"\n    MarkovChain\n\nA discrete-time, discrete-space, finite-space Markov chain.\n\n##### Fields\n- `transitionmatrix::Matrix{Float64}` : stochastic matrix in which element `[i,j]` denotes\nthe probability that the Markov chain transitions from state `i` to state `j`.\n- `initialdist::Vector{Float64}` : stochastic vector in which element `i` denotes the\nprobability that the Markov chain's initial state is `i`.\n\n##### Complexity (for the inner constructor)\n- Time complexity: `O(n^2)`, where `n` denotes the number of rows (or columns) in a square\nmatrix.\n\"\"\"\nstruct MarkovChain <: AbstractMarkovChain\n    transitionmatrix::Matrix{Float64}\n    initialdist::Vector{Float64}\n    # ensure that the transition matrix and the initial distribution are stochastic\n    function MarkovChain(transitionmatrix::AbstractMatrix{<:Real},\n                         initialdist::AbstractVector{<:Real})\n        size(transitionmatrix)[1] != length(initialdist) &&\n            ArgumentError(\"Uh-oh! The transition matrix must have the same number of rows as\n                          the initial distribution has elements.\") |> throw\n        !isstochastic(initialdist) || !isstochastic(transitionmatrix) &&\n            ArgumentError(\"Oops! The transition matrix and the initial distribution must be\n                          stochastic.\") |> throw\n        return new(transitionmatrix, initialdist)\n    end\nend\n\n\"\"\"\n    Base.show(io::IO, markovchain::MarkovChain) -> nothing\n\nShow a `MarkovChain` in a human-friendly manner.\n\"\"\"\nfunction Base.show(io::IO, markovchain::MarkovChain)\n    println(io, typeof(markovchain))\n    println(io, \" Initial distribution:\")\n    println(io, \"  \", markovchain.initialdist)\n    println(io, \" Transition matrix:\")\n    println(io, \"  \", markovchain.transitionmatrix)\n    return nothing\nend\n\n\"\"\"\n    MarkovChain(transitionmatrix::AbstractMatrix{<:Real},\n                initialdist::AbstractMatrix{<:Real}) -> MarkovChain\n\nConstruct a `MarkovChain` when the initial distribution `initialdist` is specified as either\na one-row or a one-column matrix.\n\n##### Complexity\n- Time complexity: `O(n^2)`, where `n` denotes the number of rows (or columns) in a square\nmatrix.\n\"\"\"\nfunction MarkovChain(transitionmatrix::AbstractMatrix{<:Real},\n                     initialdist::AbstractMatrix{<:Real})\n    nrows, ncols = size(initialdist)[1], size(initialdist)[2]\n    if nrows == 1\n        # make initialdist a vector\n        initialdist = initialdist[1,:]\n    elseif ncols == 1\n        # make initialdist a vector\n        initialdist = initialdist[:,1]\n    else\n        throw(ArgumentError(\"The initial distribution must be a vector.\"))\n    end\n    # multiple dispatch\n    return MarkovChain(transitionmatrix, initialdist)\nend\n\n\"\"\"\n    isstochastic(matrix::AbstractMatrix, tol::Float64 = 1e-5) -> Bool\n\nDecide if `matrix` is stochastic.\n\n`tol` is the tolerance associated with the row sums. We consider the row sums to be valid if\nand only if they are in the interval `[1-tol, 1+tol]`. This is important when the element\ntype is `Float64`, for example.\n\n##### Complexity\n- Time complexity: `O(n^2)`, where `n` denotes the number of rows (or columns) in a square\nmatrix.\n\"\"\"\nfunction isstochastic(matrix::AbstractMatrix, tol::Float64 = 1e-5)\n    nrows, ncols = size(matrix)[1], size(matrix)[2]\n    # if matrix has only one row\n    if nrows == 1\n        vec = matrix[1,:]::Vector\n        # multiple dispatch\n        return isstochastic(vec, tol)\n    # if matrix has only one column\n    elseif ncols == 1\n        vec = matrix[:,1]::Vector\n        # multiple dispatch\n        return isstochastic(vec, tol)\n    # if matrix is non-square\n    elseif nrows != ncols\n        return false\n    end\n    # check if elements are in [0,1]\n    for element in matrix\n        if element < 0 || element > 1\n            return false\n        end\n    end\n    # check row sums\n    for row in eachrow(matrix)\n        rowsum = sum(row)\n        if rowsum < 1 - tol || rowsum > 1 + tol\n            return false\n        end\n    end\n    return true  # this line is reached only if all above checks pass\nend\n\n\"\"\"\n    isstochastic(vector::AbstractVector, tol::Float64 = 1e-5) -> Bool\n\nDecide if `vector` is stochastic.\n\n`tol` is the tolerance associated with the sum over `vector`'s elements. We consider the sum\nto be valid if and only if it is in the interval `[1-tol, 1+tol]`. This is important when\nthe element type is `Float64`, for example.\n\n##### Complexity\n- Time complexity: `O(n)`.\n\"\"\"\nfunction isstochastic(vector::AbstractVector, tol::Float64 = 1e-5)\n    # check if elements are in [0,1]\n    for element in vector\n        if element < 0 || element > 1\n            return false\n        end\n    end\n    vecsum = sum(vector)\n    if vecsum < 1 - tol || vecsum > 1 + tol\n        return false\n    end\n    return true  # this line is reached only if all above checks pass\nend\n", "meta": {"hexsha": "0c8dc63f88c5e42f5d9ad666bd7ead32a2f8f31f", "size": 4963, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MarkovChains/markovchains.jl", "max_stars_repo_name": "LoganDGraham/StochasticProcesses", "max_stars_repo_head_hexsha": "c3f9947d9f93c9d8397664ed3acf93c8bf7da444", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-11-15T19:57:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T22:42:14.000Z", "max_issues_repo_path": "src/MarkovChains/markovchains.jl", "max_issues_repo_name": "LoganDGraham/StochasticProcesses", "max_issues_repo_head_hexsha": "c3f9947d9f93c9d8397664ed3acf93c8bf7da444", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-02T16:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-14T17:56:52.000Z", "max_forks_repo_path": "src/MarkovChains/markovchains.jl", "max_forks_repo_name": "LoganDGraham/StochasticProcesses", "max_forks_repo_head_hexsha": "c3f9947d9f93c9d8397664ed3acf93c8bf7da444", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7619047619, "max_line_length": 92, "alphanum_fraction": 0.6661293572, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.8652240756264638, "lm_q1q2_score": 0.7815519017715348}}
{"text": "using Oceananigans.Grids\n\nusing PyPlot\n\ninclude(\"ConvergenceTests/ConvergenceTests.jl\")\n\nusing .ConvergenceTests\nusing .ConvergenceTests.TwoDimensionalDiffusion: run_and_analyze\n\ndefaultcolors = plt.rcParams[\"axes.prop_cycle\"].by_key()[\"color\"]\nremovespine(side) = gca().spines[side].set_visible(false)\nremovespines(sides...) = [removespine(side) for side in sides]\n\nfunction convergence_test(Nx, Δt, stop_iteration, topo)\n    results = [run_and_analyze(Nx=N, Δt=Δt, stop_iteration=stop_iteration, topo=topo,\n                               output=false) for N in Nx]\n\n    L₁ = map(r -> r.L₁, results)\n    L∞ = map(r -> r.L∞, results)\n\n    return (L₁=L₁, L∞=L∞)\nend\n\n# Setup and run simulations\nNx = [8, 16, 32, 64, 128, 256]\nstop_time = 1e-4\n\n# Calculate time step based on diffusive time-step constraint for finest mesh\n        min_Δx = 2π / maximum(Nx)\n   proposal_Δt = 1e-3 * min_Δx^2 # proposal time-step\nstop_iteration = round(Int, stop_time / proposal_Δt)\n            Δt = stop_time / stop_iteration # ensure time-stepping to exact finish time.\n\ntopologies = (\n              (Periodic, Periodic, Bounded),\n              (Periodic, Bounded, Bounded),\n              (Bounded, Bounded, Bounded)\n             )\n\nerrors = [convergence_test(Nx, Δt, stop_iteration, topo) for topo in topologies]\n\nfig, axs = subplots()\n\nfor (itopo, topo) in enumerate(topologies)\n    L₁ = errors[itopo].L₁\n    L∞ = errors[itopo].L∞\n    name =\"$(topo[1]), $(topo[2])\"\n\n    loglog(Nx, L₁, \"o\", basex=2, color=defaultcolors[itopo], mfc=\"None\", label=\"\\$L_1\\$-norm, $name\")\n    loglog(Nx, L∞, \"^\", basex=2, color=defaultcolors[itopo], mfc=\"None\", label=\"\\$L_\\\\infty\\$-norm, $name\")\nend\n\nL₁ = errors[1].L₁\nL∞ = errors[1].L∞\nloglog(Nx, L₁[1] * (Nx[1]./Nx).^2, \"k-\", basex=2, alpha=0.6, linewidth=1, label=L\"\\sim N_x^{-2}\")\n\nxlabel(L\"N_x\")\nylabel(\"\\$L\\$-norms of \\$ | c_\\\\mathrm{sim} - c_\\\\mathrm{analytical} |\\$\")\ntitle(\"Two dimensional diffusion convergence test\")\nremovespines(\"top\", \"right\")\nlegend(loc=\"upper right\")\n\nfilepath = joinpath(@__DIR__, \"figs\", \"two_dimensional_diffusion_convergence.png\")\nsavefig(filepath, dpi=480)\n\nfor (itopo, topo) in enumerate(topologies)\n    L₁ = errors[itopo].L₁\n    L∞ = errors[itopo].L∞\n    test_rate_of_convergence(L₁, Nx, expected=-2.0, atol=0.01, name=\"2D diffusion $topo L₁\")\n    test_rate_of_convergence(L∞, Nx, expected=-2.0, atol=0.06, name=\"2D diffusion $topo L∞\")\nend\n", "meta": {"hexsha": "7dcd1d435e65858a54790c926ea9d4ef18bd930f", "size": 2394, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "validation/convergence_tests/two_dimensional_diffusion.jl", "max_stars_repo_name": "ascheinb/Oceananigans.jl", "max_stars_repo_head_hexsha": "52bfeb09e3562f639deb32b8807f32a88e3a1cfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-02T05:32:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-02T05:32:51.000Z", "max_issues_repo_path": "validation/convergence_tests/two_dimensional_diffusion.jl", "max_issues_repo_name": "ssghost/Oceananigans.jl", "max_issues_repo_head_hexsha": "a8ea2555c36bdc7a29161d6cb692d8bdf6290156", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "validation/convergence_tests/two_dimensional_diffusion.jl", "max_forks_repo_name": "ssghost/Oceananigans.jl", "max_forks_repo_head_hexsha": "a8ea2555c36bdc7a29161d6cb692d8bdf6290156", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.25, "max_line_length": 107, "alphanum_fraction": 0.6629072682, "num_tokens": 793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.8652240721511739, "lm_q1q2_score": 0.7815518986323255}}
{"text": "\"\"\"\r\n    v = normalized_legendre(x,n)\r\n\r\nCalculates a single value of the `n`-th order Legendre polynomial of `x`.\r\nIt calls `Jacobi.legendre`.\r\n\"\"\"\r\nfunction normalized_legendre(x,n)\r\n   a = sqrt((2*n+1)/2)\r\n   return a*legendre(x,n)\r\nend\r\n\r\n\"\"\"\r\n    M = normalized_legendre_matrix(t,n)\r\n\r\nCalculates a matrix with the `n`-th order Legendre coefficients on time points `t`, a vector or range.\r\n\r\n```juliadoctests\r\n# up to 3rd order coefficients for 5 to 12\r\njulia> M = normalized_legendre_matrix(5:12,3)\r\n\r\n# same expression\r\njulia> M = normalized_legendre_matrix([5,6,7,8,9,10,11,12],3)\r\n```\r\n\"\"\"\r\nfunction normalized_legendre_matrix(t::Union{UnitRange,Vector},n)\r\n   if !issorted(t)\r\n      throw(ArgumentError(\"time points not sorted\"))\r\n   end\r\n   tmin = minimum(t)\r\n   tmax = maximum(t)\r\n   x = -1 .+ 2*( (t .- tmin)/(tmax-tmin) )\r\n   M = [normalized_legendre(y,k) for y=x,k=0:n]\r\n   return M\r\nend\r\n\r\n\"\"\"\r\n    vare = hrv_class(ve,rangeset)\r\n\r\nGenerate a vector containing residual variances from a vector of heterogeneous residual variances `ve` and a set of ranges `rangeset`.\r\n\r\n```juliadoctests\r\njulia> vare = hrv_class([10.0,20.0],[3:5,6:9])\r\n7-element Vector{Float64}:\r\n10.0\r\n10.0\r\n10.0\r\n20.0\r\n20.0\r\n20.0\r\n20.0\r\n```\r\n\"\"\"\r\nfunction hrv_class(ve,rangeset)\r\n   if length(ve)!=length(rangeset)\r\n      throw(DimensionMismatch(\"ve and rangeset\"))\r\n   end\r\n   tmin = minimum(rangeset[1])\r\n   tmax = maximum(rangeset[end])\r\n   vare = zeros(tmax-tmin+1)\r\n   for i in 1:length(rangeset)\r\n      for t in rangeset[i]\r\n         vare[t-tmin+1] = ve[i]\r\n      end\r\n   end\r\n   return vare\r\nend\r\n", "meta": {"hexsha": "94db129df3cda92c83c39cd178d1f9a618da20ba", "size": 1589, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polynomials.jl", "max_stars_repo_name": "masuday/AnimalBreedingTools.jl", "max_stars_repo_head_hexsha": "68265523af2483a58c3e5a786515bc99385644dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polynomials.jl", "max_issues_repo_name": "masuday/AnimalBreedingTools.jl", "max_issues_repo_head_hexsha": "68265523af2483a58c3e5a786515bc99385644dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polynomials.jl", "max_forks_repo_name": "masuday/AnimalBreedingTools.jl", "max_forks_repo_head_hexsha": "68265523af2483a58c3e5a786515bc99385644dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7164179104, "max_line_length": 135, "alphanum_fraction": 0.6444304594, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.8652240721511739, "lm_q1q2_score": 0.7815518963798485}}
{"text": "# ## クロスバリデーション\n# まず線形回帰の場合のクロスバリデーションの関数を定義します。\n# ```julia\n# function cv_linear(X::AbstractArray,y::Vector,K::Int)\n#     n = length(y); m = round(Int,n/K)\n#     S = 0\n#     for j in 1:K\n#         test = j*m-m+1:j*m\n#         train = setdiff(1:n,test)\n#         β̂ = multiple_regression(X[train,:],y[train])\n#         ŷ = insert_ones(X[test,:])*β̂\n#         S += dot(y[test]-ŷ,y[test]-ŷ)\n#     end\n#     return S/n\n# end\n# ```\n# ### 例39\nusing Joe, Random, Plots\nusing Plots.PlotMeasures # hide\nPlots.reset_defaults() # hide\ndefault( # hide\n    titlefont  = font(\"JuliaMono\", default(:titlefontsize),  ), # hide\n    guidefont  = font(\"JuliaMono\",  default(:guidefontsize),  ), # hide\n    tickfont   = font(\"JuliaMono\", default(:tickfontsize),   ), # hide\n    legendfont = font(\"JuliaMono\",  default(:legendfontsize), ), # hide\n    left_margin = 30px, # hide\n    bottom_margin = 30px # hide\n) # hide\nusing Joe: cv_linear\nn = 100; p = 5\nRandom.seed!(1)\nX_39 = randn(n, p)\nβ = randn(p+1); β[2:3] .= 0\ny_39 = insert_ones(X_39)*β + randn(n)\n@show cv_linear(X_39[:,[3,4,5]],y_39,10);\n@show cv_linear(X_39,y_39,10);\n# あれ？変数選択した方が誤差でかいぞ？試行回数を増やして全変数を用いた場合のCV値と\n# 変数選択を行った場合のCV値を可視化します。\nusing Joe # hide\nU=Float64[]; V = Float64[] \nfor _ in 1:100\n    global U, V, X_39, β, n # hide\n    local y # hide\n    y = insert_ones(X_39)*β + randn(n)\n    push!(U,cv_linear(X_39[:,[3,4,5]],y,10))\n    push!(V,cv_linear(X_39,y,10))\nend\n\np39 = scatter(U,V,xlabel=\"変数4,5,6を選んだ時の二乗誤差\",\n                ylabel=\"全変数を選んだ時の二乗誤差\",\n                title=\"変数を多く選びすぎて過学習\")\nplot!(p39, x->x,xlims=(0.7,1.5),legend=false)\nsavefig(p39,joinpath(@OUTPUT,\"fig3-1.svg\")) # hide\n# \\fig{fig3-1}\n# \\lineskip\n# $y=x$ の直線の上側に大多数の点がプロットされているので、\n# 変数選択をした方が誤差が少ないことが分かりました。\n# ただ、あまり二乗誤差の違いは大きくないです。\n# ### 例40\n# kの値を変えたときのCVの予測誤差の変化\nn = 100; p = 5;\np40 = plot(ylims=(0.3,1.5),xlabel=\"k\",ylabel=\"CVの値\",\n            title=\"k-foldのkとCVの値の関係\",legend=false)\nRandom.seed!(1)\nfor _ in 1:10\n    global p40 # hide\n    local X, β, y, U, V # hide\n    X = randn(n,p)\n    β = randn(p+1)\n    y = insert_ones(X) * β + randn(n)\n    U = Int[]\n    V = Float64[]\n    for k in 2:n\n        if n%k==0 \n            push!(U,k)\n            push!(V, cv_linear(X,y,k))\n        end\n    end\n    plot!(p40,U,V)\nend\nsavefig(p40,joinpath(@OUTPUT,\"fig3-2.svg\")) # hide\n# \\fig{fig3-2}\n# ### 例41 (FInsherのあやめ)\n# あやめのデータセットでK近傍法のｋ毎に誤り率を評価します。\n\nusing ScikitLearn, StatsBase, Random, Plots\nusing Joe:knn\n@sk_import datasets: load_iris\niris = load_iris()\nX_41 = iris[\"data\"]\ny_41 = iris[\"target\"]\nn = length(y_41);\n# データセットをランダムに並べ替えておきます。\nRandom.seed!(1)\norder = StatsBase.sample(1:n,n,replace=false);\nX_41 = X_41[order,:];\ny_41 = y_41[order];\n# 10-foldクロスバリデーションなので、テストデータを15毎に交代させることになります。\nerrorRate = Vector{Float64}(undef,10) \nfor k in 1:10\n    global errorRate, X_41, y_41 # hide\n    S = 0\n    for top in 1:15:150\n        test = top:top+14\n        train = setdiff(1:150,test)\n        knn_ans = knn(X_41[train,:],y_41[train],X_41[test,:],k)\n        S += sum(y_41[test] .!= knn_ans)\n    end\n    S /= n\n    errorRate[k] = S\nend\np41 = plot(errorRate,xlabel=\"K\",ylabel=\"誤り率\",\n            legend=false, title=\"CVによる誤り率の評価\")\nsavefig(p41,joinpath(@OUTPUT,\"fig3-3.svg\")) # hide\n# \\fig{fig3-3}\n# \\lineskip\n# $K \\ge 3$で大きく誤り率が低下することが分かりました。\n# pythonでは実行に10分程度かかったとありますが、いくらなんでも遅すぎでは？(juliaは瞬殺)\n# ## 線形回帰の場合の公式(CVの公式)\n# クロスバリデーションでの誤差の分析は、訓練データ毎に重回帰分析を行う必要があるので、\n# 処理に時間がかかります。$\\hat{\\beta}_{-S}$をあらわに求めることなく、CVを\n# 楽して評価できるのがこの公式です。($S$はテストデータの集合、$-S$は訓練データの集合)\n# \\lineskip\n# $$\\sum_{S} || (I - H_S)^{-1}e_S||^2$$\n# ただし、$H_S = X_S(X^\\mathsf{T}X)^{-1}X_S^\\mathsf{T}$、\n# $e_S = y_S - X_S\\hat{\\beta}$ です。プログラムを実装して、ベンチマークをしてみます。\n# cv_fast関数は次のように実装しました。\n# ```julia\n# function cv_fast(X::AbstractArray,y::Vector,K::Int)\n#     n = length(y); m = round(Int,n/K)\n#     X = insert_ones(X)\n#     H = X*((X'X)\\X')\n#     e = (I(n) - H)*y\n#     S = 0\n#     @views for j in 1:K\n#         test = j*m-m+1:j*m;\n#         err = (I(m)-H[test,test]) \\ e[test]\n#         S += dot(err,err)\n#     end\n#     return S/n\n# end\n# ```\nusing Joe, Random, Plots\nusing Joe:cv_linear,cv_fast\n\nn = 1000; p = 5\nRandom.seed!(1)\nX = randn(n, p)\nβ = randn(p+1); β[2:3] .= 0\ny = insert_ones(X)*β + randn(n);\n# ループのネストを浅くしたいので、K-foldのkのリストを作って、ループすることにします。\nK = [i for i in 2:1000 if 1000%i ==0]\nt_linear = Vector{Float64}(undef,length(K));\nt_fast = similar(t_linear);\n# まずは関数の慣らし運転を\n@show cv_linear(X,y,10)\n@show cv_fast(X,y,10)\n# 値が一致することは確認できました。それでは、いざ本番!\nfor i in eachindex(K)\n    global X, y, t_fast, t_linear,K # hide\n    start = time_ns();cv_fast(X,y,K[i]);stop = time_ns()\n    t_fast[i] = (stop-start)/1e9\n    start = time_ns();cv_linear(X,y,K[i]);stop = time_ns()\n    t_linear[i] = (stop-start)/1e9\nend\np42 = plot(ylims=(0.0,0.5), xlabel = \"k\" ,ylabel=\"実行時間\",\n           label=\"cv_linear\",title=\"cv_fastとcv_linearの比較\",\n           legend=:topleft)\nplot!(p42,K, t_linear, label=\"cv_linear\")\nplot!(p42,K, t_fast, label=\"cv_fast\")\nsavefig(p42,joinpath(@OUTPUT,\"fig3-4.svg\")) # hide\n# \\fig{fig3-4}\n# \\lineskip\n# $n\\ge100$ではcv_fastの方が実行時間が短いことが分かります。\n# 原著と比べると、マシンの違いがあるとはいえ、juliaは速いということもよくわかります。\n# ## ブートストラップ\n# 以下のような複合型とbootstrap関数を定義しました。\n# 原著のコードよりは可読性が向上したかなぁ。\n# ```julia\n# using Parameters\n# @with_kw mutable struct bt{T<:Number}\n#     original::T = 0.0\n#     bias::T = 0.0\n#     stderr::T = 0.0\n# end\n# function bootstrap(df::AbstractArray{T}, F::Function, r::Int) where T <:Number\n#     m,_ = size(df)\n#     original = F(df,1:m)\n#     u = Vector{T}(undef, r)\n#     for i in 1:r\n#         index = sample(1:m,m,replace=true)\n#         u[i] = F(df,index)\n#     end\n#     bias = mean(u) - original; stderr = std(u)\n#     result = bt()\n#     @pack! result = original, bias, stderr \n# end\n# ```\n# ### 例43\n# データは[ここ](https://bitbucket.org/prof-joe/statistical_learning_with_python/src/master/)からダウンロードできます。\nusing DelimitedFiles, Statistics\nusing Joe:bootstrap\nfunction func_1(data,index)\n    X=data[index,1]; Y= data[index,2]\n    (var(Y) - var(X))/(var(X) + var(Y) -2cov(X,Y))\nend\nPortfolio = readdlm(joinpath(\"_assets\",\"data\",\"Portfolio.csv\"),',', skipstart=1)\nbootstrap(Portfolio,func_1,1000)\n\n# ### 例44\n# データの読み込み\nusing Joe,DelimitedFiles\ndf = readdlm(joinpath(\"_assets\",\"data\",\"crime.txt\"))\nX = df[:,3:4]; y =df[:,1]\nβ = multiple_regression(X,y)\n\n# 回帰係数のそれぞれについて、ブートストラップ法を適用します。ここでは標準偏差だけを出力します。\nstd_bt = ones(3) \nfor j in 1:3\n    function func_2(data,index)\n        X = data[index,3:4];y = data[index,1]\n        β = multiple_regression(X,y)\n        return β[j]\n    end\n    std_bt[j] = bootstrap(df,func_2,1000).stderr\nend\nstd_bt\n# GLM.jlで回帰係数を推定したときの標準偏差と比較してみます。\nusing GLM, DataFrames\ndata = DataFrame(df,:auto)\nols = lm(@formula(x1 ~ x3 + x4), data)\n# 標準偏差がほぼ一致することが分かりました。", "meta": {"hexsha": "540cb77bbc6133d849980289272bdb559e3c7ba6", "size": 6656, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/_literate/ex_chap3.jl", "max_stars_repo_name": "lethal8723/Joe.jl", "max_stars_repo_head_hexsha": "f30bf44f7e662ae58dded2ec675540b2996fe90a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/_literate/ex_chap3.jl", "max_issues_repo_name": "lethal8723/Joe.jl", "max_issues_repo_head_hexsha": "f30bf44f7e662ae58dded2ec675540b2996fe90a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/_literate/ex_chap3.jl", "max_forks_repo_name": "lethal8723/Joe.jl", "max_forks_repo_head_hexsha": "f30bf44f7e662ae58dded2ec675540b2996fe90a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6896551724, "max_line_length": 100, "alphanum_fraction": 0.6253004808, "num_tokens": 3116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.8652240791017535, "lm_q1q2_score": 0.7815518959008348}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ acd7da78-1d69-11eb-2517-e1bafdc14f4a\nusing Pkg, DrWatson\n\n# ╔═╡ acd82a8c-1d69-11eb-10c9-0902b833d79e\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Plots, LaTeXStrings, Measures\nend\n\n# ╔═╡ 2e6c02cc-1d69-11eb-283a-1bcf9e0044bf\nmd\"## Listing 1.10\"\n\n# ╔═╡ acd8c1cc-1d69-11eb-3164-5b9e66fc3664\nbegin\n\tf(x,y) = x^2 + y^2\n\tf0(x) = f(x,0)\n\tf2(x) = f(x,2)\nend\n\n# ╔═╡ ace3c478-1d69-11eb-0a4d-f191cf032e78\nbegin\n\tx, y = -5:0.1:5 , -5:0.1:5\n\tplot(x, [f0.(x), f2.(x)], \n\t\tc=[:blue :red], xlims=(-5, 5), legend=:top,\n\t\tylims=(-5, 25), ylabel=L\"f(x,⋅)\", label=[\"f(x, 0)\" \"f(x, 2)\"])\n\tp1 = annotate!(-1, -0.2, text(\"Minimum = (0,0)\", :left, :top, 10))\nend\n\n# ╔═╡ ace462fa-1d69-11eb-2b31-c1c9efe2376f\nbegin\n\tz = [ f(x,y) for y in y, x in x ]\n\tp2 = surface(x, y, z, c=cgrad([:blue, :red]), legend=:none, ylabel=\"y\", zlabel=\"f(x,y)\")\nend\n\n# ╔═╡ acf332f0-1d69-11eb-09df-43d188f0b58d\nbegin\n\tM = z[1:10,1:10]\n\tp3 = heatmap(M, c=cgrad([:blue, :red]), yflip=true, ylabel=\"y\",  \n\t\txticks=([1:10;], x), yticks=([1:10;], y))\nend\n\n# ╔═╡ ad012874-1d69-11eb-24a0-e936c7c266d5\nmd\"## End of listing 1.10\"\n\n# ╔═╡ Cell order:\n# ╟─2e6c02cc-1d69-11eb-283a-1bcf9e0044bf\n# ╠═acd7da78-1d69-11eb-2517-e1bafdc14f4a\n# ╠═acd82a8c-1d69-11eb-10c9-0902b833d79e\n# ╠═acd8c1cc-1d69-11eb-3164-5b9e66fc3664\n# ╠═ace3c478-1d69-11eb-0a4d-f191cf032e78\n# ╠═ace462fa-1d69-11eb-2b31-c1c9efe2376f\n# ╠═acf332f0-1d69-11eb-09df-43d188f0b58d\n# ╟─ad012874-1d69-11eb-24a0-e936c7c266d5\n", "meta": {"hexsha": "28bbced7a0f3d6aadb26d98ecac048fad626a984", "size": 1523, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/01/listing1.10.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/01/listing1.10.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/01/listing1.10.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.3833333333, "max_line_length": 89, "alphanum_fraction": 0.6546290217, "num_tokens": 842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8705972684083609, "lm_q1q2_score": 0.7815310644060537}}
{"text": "# # Nonlocal diffusion on $\\mathbb{S}^2$\n# This example calculates the spectrum of the nonlocal diffusion operator:\n# ```math\n# \\mathcal{L}_\\delta u = \\int_{\\mathbb{S}^2} \\rho_\\delta(|\\mathbf{x}-\\mathbf{y}|)\\left[u(\\mathbf{x}) - u(\\mathbf{y})\\right] \\,\\mathrm{d}\\Omega(\\mathbf{y}),\n# ```\n# defined in Eq. (2) of\n#\n# R. M. Slevinsky, H. Montanelli, and Q. Du, [A spectral method for nonlocal diffusion operators on the sphere](https://doi.org/10.1016/j.jcp.2018.06.024), *J. Comp. Phys.*, **372**:893--911, 2018.\n#\n# In the above, $0<\\delta<2$, $-1<\\alpha<1$, and the kernel:\n# ```math\n# \\rho_\\delta(|\\mathbf{x}-\\mathbf{y}|) = \\frac{4(1+\\alpha)}{\\pi \\delta^{2+2\\alpha}} \\frac{\\chi_{[0,\\delta]}(|\\mathbf{x}-\\mathbf{y}|)}{|\\mathbf{x}-\\mathbf{y}|^{2-2\\alpha}},\n# ```\n# where $\\chi_I(\\cdot)$ is the indicator function on the set $I$.\n#\n# This nonlocal operator is diagonalized by spherical harmonics:\n# ```math\n# \\mathcal{L}_\\delta Y_\\ell^m(\\mathbf{x}) = \\lambda_\\ell(\\alpha, \\delta) Y_\\ell^m(\\mathbf{x}),\n# ```\n# and its eigenfunctions are given by the generalized Funk--Hecke formula:\n# ```math\n# \\lambda_\\ell(\\alpha, \\delta) = \\frac{(1+\\alpha) 2^{2+\\alpha}}{\\delta^{2+2\\alpha}}\\int_{1-\\delta^2/2}^1 \\left[P_\\ell(t)-1\\right] (1-t)^{\\alpha-1} \\,\\mathrm{d} t.\n# ```\n# In the paper, the authors use Clenshaw--Curtis quadrature and asymptotic evaluation of Legendre polynomials to achieve $\\mathcal{O}(n^2\\log n)$ complexity for the evaluation of the first $n$ eigenvalues. With a change of basis, this complexity can be reduced to $\\mathcal{O}(n\\log n)$.\n#\n# First, we represent:\n# ```math\n# P_n(t) - 1 = \\sum_{j=0}^{n-1} \\left[P_{j+1}(t) - P_j(t)\\right] = -\\sum_{j=0}^{n-1} (1-t) P_j^{(1,0)}(t).\n# ```\n# Then, we represent $P_j^{(1,0)}(t)$ with Jacobi polynomials $P_i^{(\\alpha,0)}(t)$ and we integrate using [DLMF 18.9.16](https://dlmf.nist.gov/18.9.16):\n# ```math\n# \\int_x^1 P_i^{(\\alpha,0)}(t)(1-t)^\\alpha\\,\\mathrm{d}t = \\left\\{ \\begin{array}{cc} \\frac{(1-x)^{\\alpha+1}}{\\alpha+1} & \\mathrm{for~}i=0,\\\\ \\frac{1}{2i}(1-x)^{\\alpha+1}(1+x)P_{i-1}^{(\\alpha+1,1)}(x), & \\mathrm{for~}i>0.\\end{array}\\right.\n# ```\n# The code below implements this algorithm, making use of the Jacobi--Jacobi transform `plan_jac2jac`.\n# For numerical stability, the conversion from Jacobi polynomials $P_j^{(1,0)}(t)$ to $P_i^{(\\alpha,0)}(t)$ is divided into conversion from $P_j^{(1,0)}(t)$ to $P_k^{(0,0)}(t)$, before conversion from $P_k^{(0,0)}(t)$ to $P_i^{(\\alpha,0)}(t)$.\n\nusing FastTransforms, LinearAlgebra\n\nfunction oprec!(n::Integer, v::AbstractVector, alpha::Real, delta2::Real)\n    if n > 0\n        v[1] = 1\n    end\n    if n > 1\n        v[2] = (4*alpha+8-(alpha+4)*delta2)/4\n    end\n    for i = 1:n-2\n        v[i+2] = (((2*i+alpha+2)*(2*i+alpha+4)+alpha*(alpha+2))/(2*(i+1)*(2*i+alpha+2))*(2*i+alpha+3)/(i+alpha+3) - delta2/4*(2*i+alpha+3)/(i+1)*(2*i+alpha+4)/(i+alpha+3))*v[i+1] - (i+alpha+1)/(i+alpha+3)*(2*i+alpha+4)/(2*i+alpha+2)*v[i]\n    end\n    return v\nend\n\nfunction evaluate_lambda(n::Integer, alpha::T, delta::T) where T\n    delta2 = delta*delta\n    scl = (1+alpha)*(2-delta2/2)\n\n    lambda = Vector{T}(undef, n)\n\n    if n > 0\n        lambda[1] = 0\n    end\n    if n > 1\n        lambda[2] = -2\n    end\n\n    oprec!(n-2, view(lambda, 3:n), alpha, delta2)\n\n    for i = 2:n-1\n        lambda[i+1] *= -scl/(i-1)\n    end\n\n    p = plan_jac2jac(T, n-1, zero(T), zero(T), alpha, zero(T))\n\n    lambda[2:end] .= p'lambda[2:end]\n\n    for i = 2:n-1\n        lambda[i+1] = ((2i-1)*lambda[i+1] + (i-1)*lambda[i])/i\n    end\n\n    for i = 2:n-1\n        lambda[i+1] += lambda[i]\n    end\n\n    return lambda\nend\n\n# The spectrum in `Float64`:\nlambda = evaluate_lambda(10, -0.5, 1.0)\n\n# The spectrum in `BigFloat`:\nlambdabf = evaluate_lambda(10, parse(BigFloat, \"-0.5\"), parse(BigFloat, \"1.0\"))\n\n# The $\\infty$-norm relative error:\nnorm(lambda-lambdabf, Inf)/norm(lambda, Inf)\n", "meta": {"hexsha": "9598e5c2598665f84058de389c6df7845e2ae5a5", "size": 3846, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/nonlocaldiffusion.jl", "max_stars_repo_name": "eschnett/FastTransforms.jl", "max_stars_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2019-04-13T05:52:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T10:03:15.000Z", "max_issues_repo_path": "examples/nonlocaldiffusion.jl", "max_issues_repo_name": "eschnett/FastTransforms.jl", "max_issues_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113, "max_issues_repo_issues_event_min_datetime": "2019-04-12T20:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:16:28.000Z", "max_forks_repo_path": "examples/nonlocaldiffusion.jl", "max_forks_repo_name": "eschnett/FastTransforms.jl", "max_forks_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2019-04-23T08:43:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T15:35:17.000Z", "avg_line_length": 40.914893617, "max_line_length": 287, "alphanum_fraction": 0.6034841394, "num_tokens": 1510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.7815254422169872}}
{"text": "#=\n  Regression fallacy.\n\n  From Gelman et.al \"Regression and other stories\", page 88f\n  \"\"\"\n  Regression to the mean can be confusing and it has led people to mistakenly attribute causality.\n  To see how this can happen, we move from heights of parents and children to the mathematically\n  equivalent scenario of students who take two tests.\n  [...]\n  Rather than using real data, we have simulated exam scores using the following simple process\n  representing signal and noise:6\n  1. Each student is assumed to have a true ability drawn from a distribution with \n     mean 50 and standard deviation 10.\n  2. Each student’s score on the midterm exam is the sum of two components: the student’s true ability,\n     and a random component with mean 0 and standard deviation 10, reflecting that performance on\n     any given test will be unpredictable: a midterm exam is far from a perfect measuring instrument\n  3. Likewise, each student’s score on the final exam is his or her true ability, plus another, independent,\n     random component.\n  \"\"\"\n\n\n  1) We simulate with rand and Distributions.jl and then fit with lm(),\n     were we see that it's a \"regression to the mean\", i.e. slope < 1.\n\n    score_final ~ 1 + score_midterm\n\n    Coefficients:\n    ───────────────────────────────────────────────────────────────────────────\n                    Coef.  Std. Error      t  Pr(>|t|)  Lower 95%  Upper 95%\n    ───────────────────────────────────────────────────────────────────────────\n    (Intercept)    22.1621     1.44193    15.37    <1e-47  19.3326    24.9917\n    score_midterm   0.565276   0.0278395  20.30    <1e-76   0.510646   0.619907\n    ───────────────────────────────────────────────────────────────────────────\n\n\n  2) Then we try to the recover the parameters with Turing.\n      mu_ability = 50\n      sigma_ability = 10\n\n      mu_score = 0\n      sigma_score = 10\n\n    Summary Statistics\n        parameters      mean       std   naive_se      mcse        ess      rhat   ess_per_sec \n            Symbol   Float64   Float64    Float64   Float64    Float64   Float64       Float64 \n\n        mu_ability   49.7729    0.3167     0.0100    0.0090   948.7999    0.9997      129.3877\n     sigma_ability    9.7822    0.2086     0.0066    0.0063   670.0839    1.0013       91.3792\n          mu_score    0.1490    0.1154     0.0036    0.0039   625.4673    0.9999       85.2949\n       sigma_score   10.1247    0.1610     0.0051    0.0045   683.0471    0.9991       93.1470\n\n    Quantiles\n        parameters      2.5%     25.0%     50.0%     75.0%     97.5% \n            Symbol   Float64   Float64   Float64   Float64   Float64 \n\n        mu_ability   49.1503   49.5634   49.7748   49.9773   50.3799\n     sigma_ability    9.3879    9.6409    9.7798    9.9150   10.2067\n          mu_score    0.0040    0.0605    0.1272    0.2114    0.4748\n       sigma_score    9.8106   10.0148   10.1218   10.2331   10.4427\n\n\n=#\nusing Turing, StatsPlots, DataFrames, Distributions, Random\nusing GLM\ninclude(\"jl_utils.jl\")\n\n\n#\n# It's much faster to use random and Distributions to generate\n# the data (instead of using Turing for this).\n#\n# It's almost the same model, except for the ~'s. \n#\nfunction regression_fallacy_sim(n=1000)\n    \n    mu_ability = 50\n    sigma_ability = 10\n\n    mu_score = 0\n    sigma_score = 10\n\n    ability = rand(Normal(mu_ability,sigma_ability), n)\n    score_midterm = Vector{Real}(undef, n) \n    score_final = Vector{Real}(undef, n) \n    # for i in 1:n \n    #     score_midterm[i] = rand(Normal(ability[i]+mu_score,sigma_score))\n    #     score_final[i] = rand(Normal(ability[i]+mu_score,sigma_score))\n    # end\n    # Neater:\n    @. score_midterm = rand(Normal(ability+mu_score,sigma_score))\n    @. score_final = rand(Normal(ability+mu_score,sigma_score)) \n    \n    return ability, score_midterm, score_final\nend\n\n\nn = 1000\n\nability, score_midterm, score_final = regression_fallacy_sim(n)\n\n#\n# Fit the data\n#\n\ndf = DataFrame(ability=ability,score_midterm=score_midterm, score_final=score_final)\nfit = lm(@formula(score_final ~ score_midterm), df)\ndisplay(fit)\nprintln()\n\n#=\npred = predict(fit)\n# display(plot(xlabel=\"midterm\", ylabel=\"final\", legend=:bottomright))\ndisplay(plot(df.score_midterm, df.score_final, label=\"data\", seriestype=:scatter,ms=1,xlabel=\"midterm\", ylabel=\"final\", legend=:bottomright))\ndisplay(plot!(score_midterm, pred, label=\"model\", linewidth=3))\n=#\n\n#=\n# What are the mean for those students that got \n# final < / > midterm scores\nmean_midterm = mean(score_midterm)\nmean_final = mean(score_final)\n\nix_gt = score_final .> score_midterm\nix_lt = score_final .< score_midterm\n@show mean(score_final[ix_gt])\n@show mean(score_final[ix_lt])\n@show mean(score_final[ix_gt] .- score_midterm[ix_gt])\n@show mean(score_final[ix_lt] .- score_midterm[ix_lt])\n=#\n\n\n#\n# Now we try to recover the values.\n#\n# Note: Generating the data using this Turing model takes too long time.\n# Hence the dedicated simulation model above.\n# \n@model function regression_fallacy(ability, score_midterm, score_final)\n    n = length(ability)\n    # Use uninformed priors so we are not accused of cheating. :-)\n    mu_ability ~ Uniform(1,1000)\n    sigma_ability ~ Uniform(1,50)\n\n    mu_score ~ Uniform(0,100)\n    sigma_score ~ Uniform(1,50)\n\n    ability .~ Normal(mu_ability,sigma_ability)\n    @. score_midterm ~ Normal(ability+mu_score,sigma_score)\n    @. score_final   ~ Normal(ability+mu_score,sigma_score)\nend\n\n\nmodel = regression_fallacy(ability,score_midterm,score_final)\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 1_000)\n# chns = sample(model, PG(20), 1_000)\n# chns = sample(model, IS(), 1_000)\n# chns = sample(model, SMC(1000), 1_000)\n\n# chns = sample(model, NUTS(1000,0.65), 1_000)\nchns = sample(model, NUTS(), 1_000)\n# chns = sample(model, HMC(0.1,5), 1_000)\n\ndisplay(chns)\n", "meta": {"hexsha": "8e3ec7cbad7281d78870f298aad2ff06e45c08e2", "size": 5805, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/regression_fallacy.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/regression_fallacy.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/regression_fallacy.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 34.9698795181, "max_line_length": 141, "alphanum_fraction": 0.6463393626, "num_tokens": 1755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8824278618165526, "lm_q1q2_score": 0.7815058824713814}}
{"text": "\n\"\"\"\n    SqExponentialARD(lnℒ::AbstractVector) \n    <: RadialKernel{WeightedSqEuclidean}\n\nThe squared exponential kernel (aka the Gaussian kernel) with\nvector valued length scale\n``\\\\exp(2 \\\\ln\\\\mathscr{L}_i) = \\\\mathscr{L}_i^2 > 0``.\n\nFinding an optimal ``\\\\mathscr{L}`` is refered to as automatic \nrelevance detetermination. \n\nFor the matrix ``\\\\Sigma_{ii} = \\\\mathscr{L}_i^{-2}``\n\n```math\nk_{\\\\mathscr{L}}(x, y) = k_{\\\\mathscr{L}}(\\\\lVert x - y\\\\rVert_\\\\Sigma^2) = \n\\\\exp\\\\Big\\\\lbrace -\\\\frac{1}{2}\\\\lVert x - y\\\\rVert_\\\\Sigma^2\\\\Big\\\\rbrace\n```\n\n\"\"\"\nmutable struct SqExponentialARD{\n    F<:AbstractFloat,\n    V<:AbstractVector{F},\n} <: RadialKernel{WeightedSqEuclidean}\n    dist::WeightedSqEuclidean\n    lnℒ::V\n    diagΣ::V\nend\n\nfunction SqExponentialARD(lnℒ::AbstractVector)\n    diagΣ = exp.(-2 .* lnℒ)\n    SqExponentialARD(WeightedSqEuclidean(diagΣ), lnℒ, diagΣ)\nend\n\n@inline (k::SqExponentialARD)(τ::AbstractFloat) = exp(-τ / 2)\n\nGaussianARD = SqExponentialARD\n\nnumparams(k::SqExponentialARD) = (length(k.lnℒ),)\nparamtypes(k::SqExponentialARD{F}) where F = (F,) \nparams(k::SqExponentialARD) = (lnℒ = k.lnℒ,)\nfunction setparams!(k::SqExponentialARD{F}, lnℒ::AbstractVector{F}) where F\n    diagΣ = exp.(-2 .* lnℒ)\n    copyto!(k.lnℒ, lnℒ)\n    copyto!(k.diagΣ, diagΣ)\n    k.dist = WeightedSqEuclidean(diagΣ)\nend\n", "meta": {"hexsha": "964a9940ac6c44c64a03de9a92b7a71cf5860492", "size": 1315, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/radial/SqExponentialARD.jl", "max_stars_repo_name": "cameton/SKI.jl", "max_stars_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/radial/SqExponentialARD.jl", "max_issues_repo_name": "cameton/SKI.jl", "max_issues_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/radial/SqExponentialARD.jl", "max_forks_repo_name": "cameton/SKI.jl", "max_forks_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3958333333, "max_line_length": 76, "alphanum_fraction": 0.6775665399, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7814666149770003}}
{"text": "###############################################\n#FEniCS tutorial demo program: Deflection of a membrane.\n#  -Laplace(w) = p  in the unit circle\n#            w = 0  on the boundary\n#The load p is a Gaussian function centered at (0, 0.6).\n###############################################\n\nmodule ft02\n\nusing FenicsPy\n\n# Create mesh and define function space\nΩ = Circle(Point(0, 0), 1)\nmesh = generate_mesh(Ω, 64)\nV = FunctionSpace(mesh, \"P\", 2)\n\n# Define boundary condition\nw_D = Constant(0)\n\nbc = DirichletBC(V, w_D, \"on_boundary\")\n\n# Define load\nβ = 8\nR0 = 0.6\np = Expression(\"4*exp(-pow(beta, 2)*(pow(x[0], 2) + pow(x[1] - R0, 2)))\",\n               degree=1, beta=β, R0=R0)\n\n# Define variational problem\nw = TrialFunction(V)\nv = TestFunction(V)\na = dot(grad(w), grad(v))*dx\nL = p*v*dx\n\n# Compute solution\nw = FeFunction(V)\nsolve(a == L, w, bc)\n\np = interpolate(p, V)\n\n# Save solution to file in VTK format\nvtkfile_w = File(\"poisson_membrane/deflection.pvd\")\nvtkfile_w << w\nvtkfile_p = File(\"poisson_membrane/load.pvd\")\nvtkfile_p << p\n\n# Plot solution\n#plot(w, title=\"Deflection\")\n#plot(p, title=\"Load\")\n\n# Curve plot along x = 0 comparing p and w\n#import numpy as np\n#import matplotlib.pyplot as plt\n#tol = 0.001  # avoid hitting points outside the domain\n#y = np.linspace(-1 + tol, 1 - tol, 101)\n#points = [(0, y_) for y_ in y]  # 2D points\n#w_line = np.array([w(point) for point in points])\n#p_line = np.array([p(point) for point in points])\n#plt.plot(y, 50*w_line, 'k', linewidth=2)  # magnify w\n#plt.plot(y, p_line, 'b--', linewidth=2)\n#plt.grid(True)\n#plt.xlabel('$y$')\n#plt.legend(['Deflection ($\\\\times 50$)', 'Load'], loc='upper left')\n#plt.savefig('poisson_membrane/curves.pdf')\n#plt.savefig('poisson_membrane/curves.png')\n\nend # module ft02\n", "meta": {"hexsha": "d0b9006e6ac0b24858ba355b7e91f9f5e603843c", "size": 1751, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ft02_poisson_membrane.jl", "max_stars_repo_name": "chaoskey/FenicsPy.jl", "max_stars_repo_head_hexsha": "18b42f6b193a220702d544560f403a9917adda6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/ft02_poisson_membrane.jl", "max_issues_repo_name": "chaoskey/FenicsPy.jl", "max_issues_repo_head_hexsha": "18b42f6b193a220702d544560f403a9917adda6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ft02_poisson_membrane.jl", "max_forks_repo_name": "chaoskey/FenicsPy.jl", "max_forks_repo_head_hexsha": "18b42f6b193a220702d544560f403a9917adda6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1343283582, "max_line_length": 73, "alphanum_fraction": 0.6287835523, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370312, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7814666093640112}}
{"text": "using FFTW\n\nfunction FourierCoeffsOdd(f,ta,tb,M)\n  N = 2*M+1\n  h = (tb-ta)/N  \n  tt = range(ta,step=h,length=N)\n  ff = f.(tt)\n  hf = 1/N*rfft(ff)\n  return (tt,ff,hf)\nend\n\nfunction FourierEvalOdd(ta,tb,hf,N)\n    M = length(hf)-1\n    if (N<2M+1) \n        error(\"$M=length(hf)-1 should be less than (N+1)/2=$div(N+1,2)\")\n    end\n    h = (tb-ta)/N  \n    TT = range(ta,step=h,length=N)\n    MM = div(N,2)\n    hF = zeros(Complex{Float64},MM+1)\n    hF[1:(M+1)] = hf[1:(M+1)]\n    PP = N*real.(irfft(hF,N))\n    return (TT, PP)\nend\n\nfunction FourierCoeffsEven(f,ta,tb,M)\n  N = 2*M\n  h = (tb-ta)/N  \n  tt = range(ta,step=h,length=N)\n  ff = f.(tt)\n  hf = 1/N*rfft(ff)\n  return (tt,ff,hf)\nend\n\nfunction FourierEvalEven(ta,tb,hf,N)\n    M = length(hf)-1\n    if (N<2M) \n        error(\"$M=length(hf)-1 should be less than or equal to N/2=$div(N,2)\")\n    end\n    h = (tb-ta)/N  \n    TT = range(ta,step=h,length=N)\n    MM = div(N,2)\n    hF = zeros(Complex{Float64},MM+1)\n    hF[1:M] = hf[1:M]\n    hF[M+1] = hf[M+1]/2\n    PP = N*real.(irfft(hF,N))\n    return (TT, PP)\nend\n\nfunction FourierCoeffs(tt,ff)\n    N = length(ff)\n    hf = 1/N*rfft(ff)\n    return (tt,ff,hf)\nend\n\nfunction FourierEval(ta,tb,hf,N)\n    if mod(N, 2) == 0\n        return FourierEvalEven(ta,tb,hf,N)\n    else \n        return FourierEvalOdd(ta,tb,hf,N)\n    end\nend\n\nfunction DiffMatrix(N)\n    D = zeros(N,N)\n    isodd(N) ? auxfcn = csc : auxfcn = cot\n    for j in 1:N\n        for k in 1:j-1\n            D[j,k] = 0.5*(-1)^(j-k)*auxfcn((j-k)*pi/N)\n            D[k,j] = -D[j,k]\n        end\n    end\n    return D\nend", "meta": {"hexsha": "83012e429d0147dc73b9c884a8cf1538b75f15e5", "size": 1558, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TrigInt.jl", "max_stars_repo_name": "MarkelZ/3body-problem", "max_stars_repo_head_hexsha": "2bd824607f72b0bf48f769a98118943c1323adb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TrigInt.jl", "max_issues_repo_name": "MarkelZ/3body-problem", "max_issues_repo_head_hexsha": "2bd824607f72b0bf48f769a98118943c1323adb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TrigInt.jl", "max_forks_repo_name": "MarkelZ/3body-problem", "max_forks_repo_head_hexsha": "2bd824607f72b0bf48f769a98118943c1323adb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0540540541, "max_line_length": 78, "alphanum_fraction": 0.5391527599, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.7814666081339934}}
{"text": "@inline function rand_point()\n    return 2.0 .* rand(3) .- 1.0\nend\n\nfunction sample_in_sphere(R::Number, r::Number, n::Integer, max_retry_times::Integer = 100)\n    r > R && throw(ArgumentError(\"particle radius must be smaller than region radius!\"))\n\n    points = Vector{Float64}[]\n    r′ = r / R\n    for _ = 1:n\n        retry_times = 0\n        new_point = rand_point()\n        while norm(new_point) + r′ > 1.0\n            new_point = rand_point()\n        end\n        min_dist = minimum(norm(point - new_point) for point in points; init = Inf)\n        while min_dist < 2r′ && retry_times < max_retry_times\n            retry_times += 1\n            new_point = rand_point()\n            while norm(new_point) + r′ > 1.0\n                new_point = rand_point()\n            end\n            min_dist = minimum(norm(point - new_point) for point in points; init = Inf)\n        end\n        if min_dist >= 2r′\n            push!(points, new_point)\n        end\n    end\n\n    length(points) < n &&\n        @warn \"Failed to generate enough points. $(length(points))/$n generated.\"\n\n    return [point ./ r′ for point in points]\nend\n\nexport sample_in_sphere\n", "meta": {"hexsha": "0b6ac604cf8b49618aab48b41a707b73b31893b8", "size": 1141, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "JuliaRemoteSensing/STMMRunner.jl", "max_stars_repo_head_hexsha": "00028d0893bfbe5ef2b7215f3be2838beed3cf75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-24T07:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T07:30:55.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "JuliaRemoteSensing/STMMRunner.jl", "max_issues_repo_head_hexsha": "00028d0893bfbe5ef2b7215f3be2838beed3cf75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "JuliaRemoteSensing/STMMRunner.jl", "max_forks_repo_head_hexsha": "00028d0893bfbe5ef2b7215f3be2838beed3cf75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8378378378, "max_line_length": 91, "alphanum_fraction": 0.5828220859, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370312, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7814666074482567}}
{"text": "# Load Turing.\nusing Turing\n# Load other dependencies\nusing Distributions, RDatasets\n\n# Example data set - Fisher's Iris data set\ndata = dataset(\"datasets\", \"iris\")\nspecies = data[!, \"Species\"]\ndat = data[!, 1:4]\n\n@model pPCA(x, ::Type{T} = Float64) where {T} = begin\n\n  # Dimensionality of the problem.\n  N, D = size(x)\n\n  # latent variable z\n  z = Matrix{T}(undef, D, N)\n  for d in 1:D\n    z[d, :] ~ MvNormal(N, 1.)\n  end\n\n  # weights/loadings w\n  w = Matrix{T}(undef, D, D)\n  for d in 1:D\n    w[d, :] ~ MvNormal(D, 1.)\n  end\n\n  mu = w * z\n\n  for d in 1:D\n    x[:,d] ~ MvNormal(mu[d,:], 1.)\n  end\n\nend\n\nppca = pPCA(dat)\n\n# Hamiltonian Monte Carlo (HMC) sampler parameters\nn_iterations = 10000\nϵ = 0.05\nτ = 10\n\nchain = sample(ppca, HMC(ϵ, τ), n_iterations)\n\n# Extract paramter estimates for plotting.\nw = reshape(mean(group(chain, :w))[:,2], (4,4))\nz = reshape(mean(group(chain, :z))[:,2], size(dat))\n\n#  plot(z[1, :], z[2,:])\n\n\n## Extend to ARD\n## Original paper\n#\n#  #  for (d in 1:D){\n    #  w[d] ~ normal(0, sigma * alpha);\n  #  }\n  #  sigma ~ lognormal(0, 1);\n  #  alpha ~ inv_gamma(1, 1);\n\n", "meta": {"hexsha": "3f2fc666c95c9ac12e1494a8868ee1fc8d575e4d", "size": 1097, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tutorials/11-probabilistic-pca/11-probabilistic-pca.jl", "max_stars_repo_name": "leachim/TuringTutorials", "max_stars_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorials/11-probabilistic-pca/11-probabilistic-pca.jl", "max_issues_repo_name": "leachim/TuringTutorials", "max_issues_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/11-probabilistic-pca/11-probabilistic-pca.jl", "max_forks_repo_name": "leachim/TuringTutorials", "max_forks_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.9836065574, "max_line_length": 53, "alphanum_fraction": 0.5897903373, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7814666062182387}}
{"text": "function findPi(num_samples, trials_per_sample)\n  samples = Array{Float64}(undef, num_samples)\n  mean = 0.0\n\n  for sample = 1:num_samples\n    samples[sample] = integrateCircle(trials_per_sample)\n  end\n\n  mean = sum(samples) / size(samples)[1]\n\n  std_dev = getStdDev(mean, samples)\n\n  return mean, std_dev\nend\n\nfunction getStdDev(mean, samples)\n  variance = 0\n\n  for sample in samples\n    variance += (sample - mean) ^ 2\n  end\n\n  variance /= size(samples)[1]\n  return sqrt(variance)\nend\n\nfunction integrateCircle(points_placed)\n  counter = 0\n\n  for trial = 1:points_placed\n    y_pos = rand()\n    x_pos = rand()\n\n    dist = y_pos ^ 2 + x_pos ^ 2\n    if dist <= 1\n      counter += 1\n    end\n  end\n\n  return 4.0 * counter / points_placed\nend\n\nfunction monte_carlo()\n  res = [0.0, 0.0]\n  for i in 1:20\n    res1, res2 = findPi(1000, 50000)\n    res[1] += res1 / 20.0\n    res[2] += res2 / 20.0\n  end\n  print(res)\nend\n", "meta": {"hexsha": "325bb34c24a7ff4af96b6dfdb477348616e264e1", "size": 909, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "monte_carlo.jl", "max_stars_repo_name": "pnadon/monte-carlo-comparison", "max_stars_repo_head_hexsha": "ce5227ee1ffba54855d1e236c1379f2204c17a6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "monte_carlo.jl", "max_issues_repo_name": "pnadon/monte-carlo-comparison", "max_issues_repo_head_hexsha": "ce5227ee1ffba54855d1e236c1379f2204c17a6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "monte_carlo.jl", "max_forks_repo_name": "pnadon/monte-carlo-comparison", "max_forks_repo_head_hexsha": "ce5227ee1ffba54855d1e236c1379f2204c17a6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4807692308, "max_line_length": 56, "alphanum_fraction": 0.6479647965, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.958537730841905, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.78143110690649}}
{"text": "function ffd(f::Function, x=0.0, h=1e-8)\n    val = (f(x+h)-f(x))/h\n    return val\nend\n\nfunction bfd(f::Function, x=0.0, h=1e-8)\n    val = (f(x)-f(x-h))/h\n    return val\nend\n\nfunction cfd(f::Function, x=0.0, h=1e-5)\n    val = (f(x+h)-f(x-h))/2/h\n    return val\nend", "meta": {"hexsha": "ece3990ffcd5984e5499f0b746d747357b9155c7", "size": 263, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/differentiation.jl", "max_stars_repo_name": "hessianguo/NumericalMethod.jl", "max_stars_repo_head_hexsha": "bd6c00a88c8168e39b2ba1894466a6b6f6e24984", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/differentiation.jl", "max_issues_repo_name": "hessianguo/NumericalMethod.jl", "max_issues_repo_head_hexsha": "bd6c00a88c8168e39b2ba1894466a6b6f6e24984", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/differentiation.jl", "max_forks_repo_name": "hessianguo/NumericalMethod.jl", "max_forks_repo_head_hexsha": "bd6c00a88c8168e39b2ba1894466a6b6f6e24984", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7857142857, "max_line_length": 40, "alphanum_fraction": 0.5551330798, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.781431101858237}}
{"text": "### wiener.jl ---  Wiener deconvolution\n#\n# Copyright (C) 2016 Mosè Giordano.\n#\n# Maintainer: Mosè Giordano <mose AT gnu DOT org>\n# Keywords: wiener, deconvolution, signal processing\n#\n# This file is a part of Deconvolution.jl.\n#\n# License is MIT \"Expat\".\n#\n### Commentary:\n#\n# This file provides the `wiener' function to perform Wiener deconvolution.  It\n# has two modes: one for the case of presence of a known blurring, the other one\n# without blurring.\n#\n### Code:\n\nexport wiener\n\n### The implementation of the deconvolution algorithm\n\nfunction _wiener_no_blur(Y::AbstractArray, # Fourier transform of the input\n                         S::AbstractArray, # Power spectrum of the signal\n                         N::AbstractArray) # Power spectrum of the noise\n    # Without blurring, the filter is:\n    #   |S|² / (|S|² + |N|²)\n    return real(ifft(Y .* S ./ (S .+ N)))\nend\n\nfunction _wiener_with_blur(Y::AbstractArray, # Fourier transform of the input\n                           S::AbstractArray, # Power spectrum of the signal\n                           N::AbstractArray, # Power spectrum of the noise\n                           H::AbstractArray) # Fourier transform of the blurring\n    # With blurring, the filter is:\n    #   H* / (|H|² + |N/S|²)\n    return real(ifft(Y .* conj(H) ./ (abs2.(H) .+ N ./ S)))\nend\n\n### User interface\n\n## Without blurring\nfunction wiener(input::AbstractArray, signal::AbstractArray,\n                noise::AbstractArray)\n    @assert size(input) == size(signal) == size(noise)\n    input_ft = fft(input)\n    signal_power_spectrum = abs2.(fft(signal))\n    noise_power_spectrum = abs2.(fft(noise))\n    return _wiener_no_blur(input_ft, signal_power_spectrum,\n                           noise_power_spectrum)\nend\n\n# Noise as a real (it's converted to an array)\nwiener(input::AbstractArray, signal::AbstractArray, noise::Real) =\n    wiener(input, signal, fill!(similar(input), one(eltype(input)))*noise)\n\n## With blurring\nfunction wiener(input::AbstractArray, signal::AbstractArray,\n                noise::AbstractArray, blurring::AbstractArray)\n    @assert size(input) == size(signal) == size(noise) == size(blurring)\n    input_ft = fft(input)\n    signal_power_spectrum = abs2.(fft(signal))\n    noise_power_spectrum = abs2.(fft(noise))\n    blurring_ft = fft(blurring)\n    return _wiener_with_blur(input_ft, signal_power_spectrum,\n                             noise_power_spectrum, blurring_ft)\nend\n\n# Noise as a real (it's converted to an array)\nwiener(input::AbstractArray, signal::AbstractArray,\n       noise::Real, blurring::AbstractArray) =\n           wiener(input, signal, fill!(similar(input), one(eltype(input)))*noise, blurring)\n\n\"\"\"\n    wiener(input, signal, noise[, blurring])\n\nReturn the Wiener deconvolution of `input`, using the power spectrum of `signal`\nand `noise`.  If the `input` was blurred with a known blurring kernel, pass it\nas fourth argument, `blurring`.\n\nAll arguments must be arrays in the time/space domain and all of the same size,\nthey will be converted into the frequency domain internally using the `fft`\nfunction.\n\"\"\"\nwiener\n", "meta": {"hexsha": "aaacdcb2eedda23293c8a42737f891b86cbe0c50", "size": 3088, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/wiener.jl", "max_stars_repo_name": "abhishalya/Deconvolution.jl", "max_stars_repo_head_hexsha": "ad51bb095ad1455ffcbe12afbe6cae7971e23608", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/wiener.jl", "max_issues_repo_name": "abhishalya/Deconvolution.jl", "max_issues_repo_head_hexsha": "ad51bb095ad1455ffcbe12afbe6cae7971e23608", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/wiener.jl", "max_forks_repo_name": "abhishalya/Deconvolution.jl", "max_forks_repo_head_hexsha": "ad51bb095ad1455ffcbe12afbe6cae7971e23608", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4942528736, "max_line_length": 91, "alphanum_fraction": 0.6690414508, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297141, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7814175803662075}}
{"text": "using LinearAlgebra\nusing Plots\ngr()\n\n\"\"\"\nGlobal Newton Fractal for Solving Systems of Nonlinear Equations\n@author Oscar Veliz\n\"\"\"\n\n\"\"\"\n    F(X)\n\nSystem of nonlinear equations on vector X ([x;y]).\nOverwrite for your own testing, currently set to:\nx^2 - y - 1\nx - y^2 + 1\n\nFor a system version of z^3-1 use F(X) = [X[1]^3-3*X[1]*X[2]^2-1;3*X[1]^2*X[2]-X[2]^3]\n\n# Example\n```julia-repl\njulia> F([1.0; 2.0])\n2-element Array{Float64,1}:\n -2.0\n -2.0\n```\n\"\"\"\nF(X) = [X[1]^2-X[2]-1;X[1]-X[2]^2+1]\n\n\"\"\"\n    J(X)\n\nJacobian matrix for F given vector X ([x;y]).\nOverwrite for your own testing, currently set to:\n[2x -1;1 -2y]\n\nFor a system version of z^3-1 use J(X) = [3*X[1]^2-3*X[2]^2 -6*X[1]*X[2];6*X[1]*X[2] 3*X[1]^2-3*X[2]^2]\n\n# Example\n```julia-repl\njulia> J([1.0; 2.0])\n2×2 Array{Float64,2}:\n 2.0  -1.0\n 1.0  -4.0\n```\n\"\"\"\nJ(X) = [2*X[1] -1;1 -2*X[2]]\n\n\"\"\"\n    Newton(X, eps=10^-6)\n\nNewton's Method for the system of nonlinear equations in [`F`](@ref). Returns the number of iterations.\n# Example\n```julia-repl\njulia> Newton([1.0;2.0])\n5\n```\n\"\"\"\nfunction Newton(X, eps::Float64=10^-6)\n    i = 1\n    FX = F(X)\n    while norm(FX) > eps && i < 50\n        X = X - J(X) \\ FX\n        FX = F(X)\n        i = i + 1\n    end\n    i\nend\n\n\"\"\"\n    GlobalNewton(X, eps=10^-6)\n\nGlobal Newton's Method for the system of nonlinear equations in [`F`](@ref). Returns the number of iterations.\n# Example\n```julia-repl\njulia> GlobalNewton([1.0;2.0])\n\n```\n\"\"\"\nfunction GlobalNewton(X, eps::Float64=10^-6)\n    FX = F(X)\n    nF = norm(FX)\n    i = 1\n    JX = J(X)\n    delta = 1000\n    while norm(delta) > eps && nF > eps\n        a = 1.0\n        delta = JX \\ FX\n        T = X - a * delta\n        FT = F(T)\n        nFT = norm(FT)\n        while nFT > nF\n            a = a * 0.5\n            T = X - a * delta\n            FT = F(T)\n            nFT = norm(FT)\n        end\n        delta = X - T\n        X = T\n        FX = FT\n        nF = nFT\n        JX = J(X)\n        i = i + 1\n    end\n    i\nend\n\n\"\"\"\n    Fractal(useGlobal=true, eps=10^-3)\n\nFunction for creating fractals. Call with false for normal newton fractal. Uses [`F`](@ref) and [`J`](@ref).\nSaves the file to `globalnewton.svg` or `newton.svg` depending on `useGlobal`.\n# Example\n```julia-repl\njulia> Fractal()\n```\n\"\"\"\nfunction Fractal(useGlobal::Bool=true, step::Float64=.001)\n    domain = -3.6:step:3.6\n    range = -2.0:step:2.0\n    data = rand(length(range), length(domain))\n    i = 1\n    for x in domain\n        j = 1\n        for y in range\n            X = [x;y]\n            try\n                data[j,i] = if useGlobal GlobalNewton(X) else Newton(X) end\n            catch\n                data[j,i] = 50\n            end\n            j = j + 1\n        end\n        if i > length(domain)\n            i = 1\n        else\n            i = i + 1\n        end\n    end\n    heatmap(domain,\n    range, data,\n    c = cgrad([:black, :red, :yellow, :white]),\n    xlabel = \"x\", ylabel = \"y\",\n    title = if useGlobal \"Global Newton Fractal\" else \"Newton Fractal\" end,\n    fmt = :svg)\n    savefig(if useGlobal \"globalnewton.svg\" else \"newton.svg\" end)\nend\n\n\"\"\"\nMain\n\"\"\"\n\nFractal()\n", "meta": {"hexsha": "4d9a377e904d8ce1d7c26b791975e289d323b03f", "size": 3086, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/systems/GlobalNewtonFractal.jl", "max_stars_repo_name": "deboradeben/numerical-veliz", "max_stars_repo_head_hexsha": "afd208d5198315642aab3e0dab20bf27b20ed61c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-30T21:51:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:51:15.000Z", "max_issues_repo_path": "src/systems/GlobalNewtonFractal.jl", "max_issues_repo_name": "KulakovaEA/numerical-veliz", "max_issues_repo_head_hexsha": "d2f3f80c4179ddc2793a19d334526ae84d6d7480", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/systems/GlobalNewtonFractal.jl", "max_forks_repo_name": "KulakovaEA/numerical-veliz", "max_forks_repo_head_hexsha": "d2f3f80c4179ddc2793a19d334526ae84d6d7480", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.038961039, "max_line_length": 110, "alphanum_fraction": 0.5259235256, "num_tokens": 1106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109784205502, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7814175697748034}}
{"text": "# find the interval for integral for a pdf\n\nfunction zero_finding(f, kmax, tol, b0)\n    # step 0:\n    # test if b0 is a good guess\n    while f(b0) < tol\n        b0 = b0/2\n    end\n\n    b = b0\n    k = 0\n    iter = 0\n\n    \n    intvl = [b, 2*b]\n\n\n    # step 1:\n        # find an interval [a, b] such that f(a) > tol, f(b) < tol \n    while (f(intvl[1]) > tol && f(intvl[2]) < tol) == false\n        intvl[1] = intvl[2]\n        intvl[2] *= 2\n        # print(\"Current interval: [$(intvl[1]), $(intvl[2])] \\n\")\n        # print(\"Function values: [$(f(intvl[1])), $(f(intvl[2]))] \\n\")\n        iter += 1\n    end\n\n    # step 2\n        # shrink such interval using bisection\n    while k < kmax\n        midpt = (intvl[1] + intvl[2])/2\n        midvalue = f(midpt)\n        if midvalue < tol\n            intvl[2] = midpt\n            # print(\"Current interval: [$(intvl[1]), $(intvl[2])] \\n\")\n            # print(\"Function values: [$(f(intvl[1])), $(f(intvl[2]))] \\n\")\n        else\n            intvl[1] = midpt\n            # print(\"Current interval: [$(intvl[1]), $(intvl[2])] \\n\")\n            # print(\"Function values: [$(f(intvl[1])), $(f(intvl[2]))] \\n\")\n        end\n        k += 1\n    end\n    ttl_iter = iter + k\n    return intvl[2], ttl_iter\nend\n", "meta": {"hexsha": "8da2f49cd34d7dac57627d9c3ef2b652841a59a2", "size": 1232, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "individual_implementations/BTG_xinran/src/root_finding/zero_finding.jl", "max_stars_repo_name": "dbindel/btg", "max_stars_repo_head_hexsha": "83616be1d1c4d80f385fa95cef38753f39a3a4c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-09-18T04:52:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-03T18:58:55.000Z", "max_issues_repo_path": "individual_implementations/BTG_xinran/src/root_finding/zero_finding.jl", "max_issues_repo_name": "dbindel/btg", "max_issues_repo_head_hexsha": "83616be1d1c4d80f385fa95cef38753f39a3a4c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "individual_implementations/BTG_xinran/src/root_finding/zero_finding.jl", "max_forks_repo_name": "dbindel/btg", "max_forks_repo_head_hexsha": "83616be1d1c4d80f385fa95cef38753f39a3a4c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-06T06:07:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-06T06:07:50.000Z", "avg_line_length": 26.2127659574, "max_line_length": 75, "alphanum_fraction": 0.474025974, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8791467564270271, "lm_q1q2_score": 0.7813494053641599}}
{"text": "using Plots\nplotly()\n\nfunction Φ(z, λ, w0)\n    zR = pi*w0^2/λ\n    return atan(z/zR)\nend\n\nfunction w(z, λ, w0)\n    zR = pi*w0^2/λ\n    return w0*sqrt(1+(z/zR)^2)\nend\n\nfunction R(z, λ, w0)\n    zR = pi*w0^2/λ\n    return z+zR^2/z\nend\n\nfunction q(z, λ, w0)\n    zR = pi*w0^2/λ\n    return z + zR*1im\nend\n\nfunction ψ(z, p, m, λ, w0)\n    zR = pi*w0^2/λ\n    N = abs(m) + 2p\n    return (N+1)*atan(z/zR)\nend\n\nδ(k::Integer,j::Integer) = k == j ? 1 : 0\n\nfunction gLaguerre(x, p, m)\n    if p == 0\n        return 1\n    elseif p == 1\n        return 1+m-x\n    else\n        k = p-1\n        return ((2k+1+m-x)*gLaguerre(x, k, m)-(k+m)*gLaguerre(x, k-1, m))/(k+1)\n    end\nend\n\nfunction H(x,n)\n    if n==0\n        return 1\n    elseif n==1\n        return 2x\n    else\n        return 2x*H(x, n-1)-2*(n-1)*H(x, n-2)\n    end\nend\n\nfunction r_and_θ(x, y)\n    r = sqrt.(x.^2 .+ y'.^2)\n    θ = atan.(y', x)\n    return r, θ\nend\n\n\n#Laguerre-Gaussian modes\nfunction LG(r, θ, z, p, m; λ=800e-9, w0=2e-2)\n    k = 2pi/λ\n    _1 = @. sqrt(2*factorial(p)/(pi*factorial(abs(m)+p)))\n    _2 = @. w0/w(z, λ, w0)*(sqrt(2)*r/w(z, λ, w0))^abs(m)\n    _3 = @. exp(-r^2/w(z, λ, w0)^2)\n    _4 = @. gLaguerre(2r^2/w(z, λ, w0)^2,p,abs(m))\n    _5 = @. exp(-1im*k*r^2/(2*R(z, λ, w0))-1im*θ*m)\n    _6 = @. exp(1im*ψ(z, p, m, λ, w0))\n    return  @. _1*_2*_3*_4*_5*_6\n    # return _3*_4\nend\n\n#Hermite-Gaussian modes\nfunction HG(x, y, z, l, m; λ=800e-9, w0=2e-2)\n    k = 2pi/λ\n    r, θ = r_and_θ(x, y)\n    # outer product\n    _1 =  w0/w(z, λ, w0).*H.(sqrt(2)*x/w(z, λ, w0), l).*H.(sqrt(2)*y/w(z, λ, w0), m)'\n    _2 = @. exp(-(r^2)/w(z, λ, w0)^2)\n    _3 = @. exp(-1im*k*(r^2)/(2*R(z, λ, w0)))\n    _4 = @. exp(1im*ψ(z, l, m, λ, w0))\n    return @. _1*_2*_3*_4\nend\n\n\n\n# x = LinRange{Float64}(-2,10, 100)\nx = Vector(LinRange{Float64}(-5e-2,5e-2, 500))\ny = Vector(LinRange{Float64}(-5e-2,5e-2, 500))\nr, θ = r_and_θ(x, y)\n\n# heatmap(x,y,real.(LG(r,θ,0,1,3)).^2)\n# plot!(x,gLaguerre.(x, 2, 2))\n\n# x = LinRange{Float64}(-2,3, 100)\n# plot!(x, H.(x,4))\nheatmap(x,y, real.(HG(x, y, 0, 2, 2)).^2)\n\n# heatmap(r)\n", "meta": {"hexsha": "d378ccf5a8046d726b200ed313759383b14d3378", "size": 2038, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Transverse_modes.jl", "max_stars_repo_name": "SabbahMohammed/Dev", "max_stars_repo_head_hexsha": "c9639e9958d9472cbf9945a5a485a540dd10e8b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Transverse_modes.jl", "max_issues_repo_name": "SabbahMohammed/Dev", "max_issues_repo_head_hexsha": "c9639e9958d9472cbf9945a5a485a540dd10e8b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Transverse_modes.jl", "max_forks_repo_name": "SabbahMohammed/Dev", "max_forks_repo_head_hexsha": "c9639e9958d9472cbf9945a5a485a540dd10e8b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.38, "max_line_length": 85, "alphanum_fraction": 0.5019627085, "num_tokens": 1012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.781337410982766}}
{"text": "\nusing FFTW\nusing StatsBase\n\nstruct PoissonSolverFFT{DT <: Real} <: PoissonSolver{DT}\n    nx::Int\n    Δx::DT\n    xgrid::Vector{DT}\n    cells::Vector{DT}\n    L::DT\n    ρ::Vector{DT}\n    ϕ::Vector{DT}\n\n    function PoissonSolverFFT{DT}(nx::Int, L::DT) where {DT}\n        Δx = L/(nx+1)\n        xgrid = LinRange(Δx/2, L-Δx/2, nx)\n        cells = LinRange(0, L, nx+1)\n        new(nx, Δx, xgrid, cells, L, zeros(DT, nx), zeros(DT, nx))\n    end\nend\n\nPoissonSolverFFT(nx::Int, L::DT) where {DT} = PoissonSolverFFT{DT}(nx, L)\n\nBase.length(p::PoissonSolverFFT) = p.nx\n\nfunction solve!(p::PoissonSolverFFT{DT}, x::AbstractVector{DT}, w::AbstractVector{DT} = one.(x) ./ length(x)) where {DT}\n    h = fit(Histogram, mod.(x, p.L), p.cells)\n    p.ρ .= h.weights ./ length(x)\n    ρ̂ = rfft(p.ρ)\n    k² = [(i-1)^2 for i in eachindex(ρ̂)]\n    ϕ̂ = - ρ̂ ./ k²\n    ϕ̂[1] = 0\n    p.ϕ .= irfft(ϕ̂, length(p.ρ))\n    return p\nend\n\n\nfunction get_indices(p::PoissonSolverFFT, x)\n    y = mod(x, p.L)\n\n    i1 = floor(Int, y / p.Δx)\n    i2 = mod( ceil(Int, y / p.Δx) - 1, p.nx) + 1\n\n    i1 == 0 && (i1 = p.nx)\n    i2 == 0 && (i2 = p.nx)\n\n    i1 == p.nx+1 && (i1 = 1)\n    i2 == p.nx+1 && (i2 = 1)\n\n    return (i1, i2)\nend\n\nfunction get_index(p::PoissonSolverFFT, x)\n    i1, i2 = get_indices(p, x)\n    return (abs(p.xgrid[i1] - x) ≤ abs(p.xgrid[i2] - x) ? i1 : i2)\nend\n\n\nfunction eval_density(p::PoissonSolverFFT{DT}, x::DT) where {DT}\n    p.ρ[get_index(p, x)]\nend\n\nfunction eval_potential(p::PoissonSolverFFT{DT}, x::DT) where {DT}\n    p.ϕ[get_index(p, x)]\nend\n\nfunction eval_field(p::PoissonSolverFFT{DT}, x::DT) where {DT}\n    i1, i2 = get_indices(p, x)\n    return - (p.ϕ[i2] - p.ϕ[i1]) / p.Δx\nend\n", "meta": {"hexsha": "81ce617849c6725b56bc58cc9e72b28d435ffa07", "size": 1670, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/poisson_fft.jl", "max_stars_repo_name": "JuliaGNI/Particles.jl", "max_stars_repo_head_hexsha": "1c37708aa8575c41619a2a26d9f8c67ca590de7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-18T21:16:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-18T21:16:24.000Z", "max_issues_repo_path": "src/poisson_fft.jl", "max_issues_repo_name": "michakraus/Particles.jl", "max_issues_repo_head_hexsha": "c69ca0e3679c9320b12eb6ec6ec91c0e7cef7970", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-05-06T01:04:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-06T01:25:06.000Z", "max_forks_repo_path": "src/poisson_fft.jl", "max_forks_repo_name": "JuliaGNI/Particles.jl", "max_forks_repo_head_hexsha": "1c37708aa8575c41619a2a26d9f8c67ca590de7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5211267606, "max_line_length": 120, "alphanum_fraction": 0.5694610778, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.781337410982766}}
{"text": "using StatsBase\nusing StatsPlots\nusing Random\n\n\"\"\"\n    compute_running_proportion(p_heads::Float64, N::Int)\n\nComputes the running proportion of heads when 0 < p_heads < 1 is the probability of getting an head\nand N is the number of trials.\n\"\"\"\nfunction compute_running_proportion(p_heads::Float64, N::Int)\n    @assert p_heads >= 0 && p_heads <= 1\n    flip_sequence = sample(0:1,pweights([1-p_heads,p_heads]), N)\n    r = cumsum(flip_sequence)\n    n = 1:N\n    run_prop = r ./ n\n    return run_prop\nend\n\n\"\"\"\n    plot_running_proportion(p_heads::Float64, N::Int) \n\nReproduces figure 4.1 with custom probability of heads and number of flips.\n\"\"\"\nfunction plot_running_proportion(p_heads::Float64, N::Int)\n    run_prop = compute_running_proportion(p_heads, N)\n    n = 1:N\n    plot(n,run_prop,\n        title=\"Running Proportion of Heads\",\n        legend=false,\n        marker = :dot,\n        xscale = :log10)\n    plot!(ylims=(0,1))\n    # Add annotation with end proportion\n    annotation = \"End Proportion = \" * string(run_prop[end])\n    annotate!(N/4,0.7,annotation)\n    # Add reference line (true probability)\n    plot!(n, fill(p_heads, N), linestyle = :dot)\n    xlabel!(\"Flip Number\")\n    ylabel!(\"Proportion Heads\")\nend", "meta": {"hexsha": "9df1fa129ede4072bb798f672adce896e9558efa", "size": 1216, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/03_running_proportion.jl", "max_stars_repo_name": "alesasse/PuppyBook.jl", "max_stars_repo_head_hexsha": "35021e2d570c45d44ee05a8c4ceca551b63f2de1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/03_running_proportion.jl", "max_issues_repo_name": "alesasse/PuppyBook.jl", "max_issues_repo_head_hexsha": "35021e2d570c45d44ee05a8c4ceca551b63f2de1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/03_running_proportion.jl", "max_forks_repo_name": "alesasse/PuppyBook.jl", "max_forks_repo_head_hexsha": "35021e2d570c45d44ee05a8c4ceca551b63f2de1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6585365854, "max_line_length": 99, "alphanum_fraction": 0.6809210526, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7813374093634401}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots, LaTeXStrings\n\tRandom.seed!(0)\nend\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.20\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\talpha, beta = 8, 2\n\tprior(lam) = pdf(Gamma(alpha, 1/beta), lam)\n\tdata = [2,1,0,0,1,0,2,2,5,2,4,0,3,2,5,0]\n\n\tlike(lam) = *([pdf(Poisson(lam),x) for x in data]...)\n\tposteriorUpToK(lam) = like(lam)*prior(lam)\n\n\tsig = 0.5\n\tfoldedNormalPDF(x,mu) = (1/sqrt(2*pi*sig^2))*(exp(-(x-mu)^2/2sig^2)\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ exp(-(x+mu)^2/2sig^2))\n\tfoldedNormalRV(mu) = abs(rand(Normal(mu,sig)))\nend\n\n# ╔═╡ f9da18ea-3afb-11eb-1c03-eb97ca5c6918\nfunction sampler(piProb,qProp,rvProp)\n    lam = 1\n    warmN, N = 10^5, 10^6\n    samples = zeros(N-warmN)\n\n    for t in 1:N\n        while true\n            lamTry = rvProp(lam)\n            L = piProb(lamTry)/piProb(lam)\n            H = min(1,L*qProp(lam,lamTry)/qProp(lamTry,lam))\n            if rand() < H\n                lam = lamTry\n                if t > warmN\n                    samples[t-warmN] = lam\n                end\n                break\n            end\n        end\n    end\n    return samples\nend\n\n# ╔═╡ f9da4af4-3afb-11eb-3be6-c136b5d61c81\nbegin\n\tmcmcSamples = sampler(posteriorUpToK,foldedNormalPDF,foldedNormalRV)\n\tText(\"MCMC Bayes Estimate: $(mean(mcmcSamples))\")\nend\n\n# ╔═╡ f9dae8a6-3afb-11eb-3b01-15befda98071\nbegin\n\tstephist(mcmcSamples, bins=100, \n\t\tc=:black, normed=true, label=\"Histogram of MCMC samples\")\n\n\tlamRange = 0:0.01:10\n\tplot!(lamRange, prior.(lamRange), \n\t\tc=:blue, label=\"Prior distribution\")\n\n\tclosedFormPosterior(lam)=pdf(Gamma(alpha + sum(data),1/(beta+length(data))),lam)\n\tplot!(lamRange, closedFormPosterior.(lamRange), \n\t\tc=:red, label=\"Posterior distribution\", \n\t\txlims=(0, 10), ylims=(0, 1.2),\n\t\txlabel=L\"\\lambda\",ylabel=\"Density\")\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.20\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═f9da18ea-3afb-11eb-1c03-eb97ca5c6918\n# ╠═f9da4af4-3afb-11eb-3be6-c136b5d61c81\n# ╠═f9dae8a6-3afb-11eb-3b01-15befda98071\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "b204fc714bb8f4328724ea6ad9bba93ba2bb0314", "size": 2442, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/listing5.20.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/05/listing5.20.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/05/listing5.20.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 26.5434782609, "max_line_length": 81, "alphanum_fraction": 0.6543816544, "num_tokens": 1089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.781337407497489}}
{"text": "function bisect_left(A, p, r, v)\n\ti = p\n\tif p < r\n\t   q = floor(Int, (p + r) / 2)\n\t   if v <= A[q]\n\t\t   i = bisect_left(A, p, q, v)\n\t   else\n\t\t   i = bisect_left(A, q + 1, r, v)\n\t   end\n\tend\n\treturn i\nend\n\n\nfunction bisect_right(A, p, r, v)\n\ti = p\n\tif p < r\n\t   q = floor(Int, (p + r) / 2)\n\t   if v < A[q]\n\t\t   i = bisect_right(A, p, q, v)\n\t   else\n\t\t   i = bisect_right(A, q + 1, r, v)\n\t   end\n\tend\n\treturn i\nend\n\n\nfunction find_median(a, low, upp)\n\ti_low = bisect_left(a, 1, length(a) + 1, low)\n\ti_upp = bisect_right(a, 1, length(a) + 1, upp)\n\n\tmid = floor(Int, (i_upp + i_low) / 2)\n\tif (i_upp - i_low) % 2 == 0\n\t\treturn (a[mid] + a[mid - 1]) / 2\n\telse\n\t\treturn a[mid]\n\tend\nend\n", "meta": {"hexsha": "39c45f0c11a1eb03708f1485f0f942e9f9560e3b", "size": 680, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "18Host/TDT4120/AtomProjectFolder/Project1/Oving3/Ov3.jl", "max_stars_repo_name": "MarcusTL12/School", "max_stars_repo_head_hexsha": "f7302f2d390e99ad9d06004e15da032c05ec59e7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "18Host/TDT4120/AtomProjectFolder/Project1/Oving3/Ov3.jl", "max_issues_repo_name": "MarcusTL12/School", "max_issues_repo_head_hexsha": "f7302f2d390e99ad9d06004e15da032c05ec59e7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "18Host/TDT4120/AtomProjectFolder/Project1/Oving3/Ov3.jl", "max_forks_repo_name": "MarcusTL12/School", "max_forks_repo_head_hexsha": "f7302f2d390e99ad9d06004e15da032c05ec59e7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0, "max_line_length": 47, "alphanum_fraction": 0.5264705882, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7813374052453361}}
{"text": "\"\"\"\n$(SIGNATURES)\n\nCompute the area of the given `ConvexHull` using the\n[shoelace formula](https://en.wikipedia.org/wiki/Shoelace_formula).\n\"\"\"\nfunction area(hull::ConvexHull)\n    T = eltype(hull)\n    vertices = hull.vertices\n    n = length(vertices)\n    n <= 2 && return zero(arithmetic_closure(T))\n    @inbounds begin\n        ret = cross2(vertices[n], vertices[1])\n        @simd for i in Base.OneTo(n - 1)\n            ret += cross2(vertices[i], vertices[i + 1])\n        end\n        return abs(ret) / 2\n    end\nend\n", "meta": {"hexsha": "ed4af9dcab5829ea001d9c450a769bc6d22134e9", "size": 516, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/area.jl", "max_stars_repo_name": "zygmuntszpak/PlanarConvexHulls.jl", "max_stars_repo_head_hexsha": "01b8d17e45754725188c0be6744f34ed6fc9ccf7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-01-25T18:42:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-09T12:31:15.000Z", "max_issues_repo_path": "src/area.jl", "max_issues_repo_name": "zygmuntszpak/PlanarConvexHulls.jl", "max_issues_repo_head_hexsha": "01b8d17e45754725188c0be6744f34ed6fc9ccf7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2019-01-28T15:53:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-02T16:08:37.000Z", "max_forks_repo_path": "src/area.jl", "max_forks_repo_name": "zygmuntszpak/PlanarConvexHulls.jl", "max_forks_repo_head_hexsha": "01b8d17e45754725188c0be6744f34ed6fc9ccf7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-07-02T15:40:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-16T02:50:38.000Z", "avg_line_length": 25.8, "max_line_length": 67, "alphanum_fraction": 0.6201550388, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7813374049987115}}
{"text": "\r\nfunction linsolve_lu(A::Matrix{T}, b::Vector{T}) where {T}\r\n\r\n    (n_row, n_col) = size(A)\r\n    if n_row != n_col\r\n        error(\"This function only works with the same dimensions\")\r\n    end\r\n    x = zeros(eltype(b), n_row)\r\n\r\n    (L, U, p) = lu_decomp_partialpivot(A)\r\n    b_ = b[p]\r\n    y_ = triangular_solve_lower_colwise(L, b_)\r\n    x = triangular_solve_upper_colwise(U, y_)\r\n    # y_ = triangular_solve_lower_rowwise(L, b_)\r\n    # x = triangular_solve_upper_rowwise(U, y_)\r\n\r\n    return x\r\nend\r\n\r\nfunction lu_decomp_partialpivot(A::Matrix{T}) where {T}\r\n\r\n    (n_row, n_col) = size(A)\r\n\r\n    M = copy(A)\r\n    p = collect(1:n_row)\r\n\r\n    for jj = 1:(n_col-1)\r\n\r\n        @inbounds (max_elem, maxidx) = util.maximum( abs, @view( M[jj:n_row, jj] ) )\r\n        if maxidx > 1\r\n            maxidx = maxidx + jj - 1\r\n            # swap the row\r\n            @inbounds p[jj], p[maxidx] = p[maxidx], p[jj]\r\n            @simd for cc = 1:n_col\r\n                @inbounds M[jj, cc], M[maxidx, cc] = M[maxidx, cc], M[jj, cc]\r\n            end\r\n\r\n        end\r\n\r\n        # calculate the L\r\n        @fastmath @simd for rr = (jj+1):n_row\r\n            M[rr, jj] /= M[jj, jj]\r\n        end\r\n\r\n        for cc = (jj+1):n_col\r\n            @inbounds m_ = M[jj, cc]\r\n            @simd for rr = (jj+1):n_row\r\n                @fastmath @inbounds M[rr, cc] -= M[rr, jj] .* m_\r\n            end\r\n        end\r\n\r\n    end\r\n\r\n    L = UnitLowerTriangular(M);\r\n    U = UpperTriangular(M);\r\n    return (L, U, p)\r\nend", "meta": {"hexsha": "d7f23186986048777285ba2b18f7c54b78934a35", "size": 1482, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/linalg/src/lu.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "__lib__/math/linalg/src/lu.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "__lib__/math/linalg/src/lu.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0, "max_line_length": 85, "alphanum_fraction": 0.5107962213, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7813374045054621}}
{"text": "\n\"\"\"\n    RationalQuadratic(lnℓ::AbstractFloat) <: RadialKernel{SqEuclidean}\n\nThe rational quadratic kernel with parameters \n``\\\\exp(2 \\\\ln\\\\ell) = \\\\ell^2 > 0`` and ``\\\\exp(\\\\ln\\\\alpha) = \\\\alpha > 0``. \n\nThe rational quadratic kernel may be used to model functions with a \nvariable length scale.\n\n```math\nk_{\\\\ell,\\\\alpha}(x, y) = k_{\\\\ell,\\\\alpha}(\\\\lVert x - y\\\\rVert_2^2) = \n\\\\bigg(1 + \\\\frac{\\\\lVert x - y\\\\rVert_2^2}{2\\\\alpha\\\\ell^2}\\\\bigg)^{-\\\\alpha}\n```\n\nExternal links\n* [Rational quadratic covariance function on Wikipedia](https://en.wikipedia.org/wiki/Rational_quadratic_covariance_function)\n\n\"\"\"\nmutable struct RationalQuadratic{\n    F<:AbstractFloat\n} <: RadialKernel{SqEuclidean}\n    dist::SqEuclidean\n    lnℓ::F\n    lnα::F\n    \n    α::F\n    twoαℓ²::F\n    function RationalQuadratic(\n        dist::SqEuclidean,\n        lnℓ::AbstractFloat,\n        lnα::AbstractFloat\n    )\n        lnℓ, lnα = promote(lnℓ, lnα)\n        new{typeof(lnℓ)}(\n            dist,\n            lnℓ,\n            lnα,\n            exp(lnα),\n            exp(2 * lnℓ + lnα + float(logtwo)),\n        )\n    end\nend\n\nRationalQuadratic(lnℓ::AbstractFloat, lnα::AbstractFloat) =\n    RationalQuadratic(SqEuclidean(), lnℓ, lnα)\n\n@inline (k::RationalQuadratic)(τ::AbstractFloat) = (1 + τ / k.twoαℓ²)^(-k.α)\n\nnumparams(::RationalQuadratic) = (1, 1)\nparamtypes(::RationalQuadratic{F}) where F = (F, F)\nparams(k::RationalQuadratic) = (lnℓ = k.lnℓ, lnα = k.lnα)\nfunction setparams!(k::RationalQuadratic{F}, lnℓ::F, lnα::F) where F\n    k.lnℓ = lnℓ\n    k.lnα = lnα\n    k.α = exp(lnα)\n    k.twoαℓ² = exp(2 * lnℓ + lnα + float(logtwo))\nend\n", "meta": {"hexsha": "861e933a730db49d74dc4ffc7d90991f4db3a4df", "size": 1605, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/radial/RationalQuadratic.jl", "max_stars_repo_name": "cameton/SKI.jl", "max_stars_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/radial/RationalQuadratic.jl", "max_issues_repo_name": "cameton/SKI.jl", "max_issues_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/radial/RationalQuadratic.jl", "max_forks_repo_name": "cameton/SKI.jl", "max_forks_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2033898305, "max_line_length": 125, "alphanum_fraction": 0.6168224299, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582535657921, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7813374010201851}}
{"text": "module MT1D\nusing PyPlot\nconst μ = 4*pi*1e-7\n\nfunction Z_f(freqs, ρ, h, irxlayer=1)\n    n = length(ρ)\n    @assert length(h) == n - 1\n    [Z_f(f, ρ, h, n, irxlayer) for f in freqs]   \nend    \n\nfunction Z_f(f, ρ, h, n, irxlayer)\n    # from Kaufman & Keller 1981 \n    ω = 2pi*f\n    k = sqrt(im*ω*μ/ρ[end])\n    Z = ω*μ/k\n    for i = n-1:-1:irxlayer\n        k = sqrt(im*ω*μ/ρ[i])\n        ωμ_over_k = ω*μ/k\n        Z = ωμ_over_k*coth(-im*k*h[i] + acoth(Z/ωμ_over_k))\n    end\n    Z    \nend\n\nρapp(freqs, Z) = abs2.(Z)./(2pi*freqs*μ)\n\nphase(Z) = rad2deg.(angle.(Z))\n\nfunction twolayer_ex(h1, ρ1, ρ2::AbstractArray; ntimesperdecade=10)\n    X = 10 .^(-1:1/ntimesperdecade:5) # λ₁/h₁\n    T = ((h1*X/(2pi*503)).^2)/ρ1\n    Z = [twolayer_ex(h1, ρ1, rho2, T) for rho2 in ρ2]\n    fig, ax = plt.subplots(2,1, sharex=true, figsize=(6,10))\n    for ZZ in Z\n        ax[1].loglog(X, ρapp(1 ./T, ZZ)/ρ1)\n        ax[2].semilogx(X, phase(ZZ))\n    end\n    ax[1].set_ylim(1e-3, 1e4)\n    ax[2].set_ylim(-95, 10)\n    ax[1].grid()\n    ax[2].grid()\n    ax[2].set_xlabel(L\"\\lambda_1/h_1\")\n    ax[1].set_ylabel(L\"\\rho_a/\\rho_1\")\n    ax[2].set_ylabel(\"Phase \"*L\"^\\circ\")\n    fig.suptitle(\"Kaufman & Keller 1981 Fig 3.1\")\n    fig.tight_layout()  \n    nothing\nend\n\nfunction twolayer_ex(h1, ρ1, ρ2::S, T) where S<:Number\n    ρ = [ρ1, ρ2]\n    Z_f(1 ./T, ρ, [h1])\nend    \n\nfunction plotcurve(T, Z; showfreq=false, gridalpha=0.5)\n    fig, ax = plt.subplots(1, 2, sharex=true)\n    plotcurve(T, Z, fig, showfreq=showfreq, gridalpha=gridalpha)\n    fig\nend    \n\nfunction plotcurve(T, Z, fig; showfreq=false, iaxis=1, gridalpha=0.5, modelalpha=0.5, lcolor=\"nocolor\") \n    f = 1 ./T\n    ρₐ = ρapp(f, Z)\n    ϕ  = phase(Z)\n    ax = fig.axes\n    xlabel, abcissa = f_or_T(f, showfreq=showfreq)\n    if lcolor == \"nocolor\"\n        ax[iaxis].semilogx(abcissa, log10.(ρₐ))\n        ax[iaxis+1].semilogx(abcissa, ϕ)\n    else\n        ax[iaxis].semilogx(abcissa, log10.(ρₐ), alpha=modelalpha, color=lcolor)\n        ax[iaxis+1].semilogx(abcissa, ϕ, alpha=modelalpha, color=lcolor)\n    end    \n    labelaxis(xlabel, ax, iaxis, gridalpha=gridalpha)\n    fig.tight_layout()\nend    \n\nfunction f_or_T(f; showfreq=false)\n    if showfreq \n        abcissa = f\n        xlabel = \"Frequency Hz\"\n    else\n        abcissa = 1 ./f\n        xlabel = \"Time s\"\n    end\n    xlabel, abcissa\nend    \n\nfunction labelaxis(xlabel, ax, iaxis; gridalpha=0.5)\n    ax[iaxis].set_xlabel(xlabel)\n    ax[iaxis].set_ylabel(L\"\\log_{10}\\rho_{app}\"*\" (ohm-m)\")\n    ax[iaxis].grid(b=true, which=\"both\", alpha=gridalpha)\n    ax[iaxis+1].set_xlabel(xlabel)\n    ax[iaxis+1].set_ylabel(\"Phase \"*L\"^\\circ\")\n    ax[iaxis+1].grid(b=true, which=\"both\", alpha=gridalpha)\nend    \n\nfunction plotmodelcurve(T, ρ, z; showfreq=false, figsize=(10,4), gridalpha=0.5, logscaledepth=false, irxlayer=1)\n    fig = figure(figsize=(figsize))\n    s1 = subplot(131)\n    s2 = subplot(132)\n    s3 = subplot(133, sharex=s2)\n    plotmodelcurve(T, ρ, z, fig, showfreq=showfreq, gridalpha=gridalpha, logscaledepth=logscaledepth, irxlayer=irxlayer)\n    fig\nend\n\nfunction plotmodelcurve(T, ρ, z, fig; showfreq=false, gridalpha=0.5, logscaledepth=false, lcolor=\"nocolor\", modelalpha=0.5, irxlayer=1)\n    f = 1 ./T\n    h = diff(z)\n    Z = Z_f(f, ρ, h, irxlayer)\n    ax = fig.axes\n    zlast = diff(z)[end] + z[end]\n    if lcolor == \"nocolor\"\n        ax[1].step([ρ; ρ[end]], [z; zlast])\n    else\n        ax[1].step([ρ; ρ[end]], [z; zlast], color=lcolor, alpha=modelalpha)\n    end      \n    ax[1].set_xlabel(\"ρ ohm-m\")\n    ax[1].set_ylabel(\"Depth m\")\n    y1, y2 = ax[1].get_ylim()\n    y1 < y2 && ax[1].invert_yaxis()\n    if logscaledepth\n        ymax = max(y1, y2)\n        ax[1].set_ylim(ymax, 1)\n        ax[1].set_yscale(\"log\")\n    end    \n    ax[1].set_xscale(\"log\")\n    ax[1].grid(b=true, which=\"both\", alpha=gridalpha)\n    plotcurve(T, Z, fig, showfreq=showfreq, iaxis=2, gridalpha=gridalpha, modelalpha=modelalpha, lcolor=lcolor) \nend\n\nend", "meta": {"hexsha": "7092c50ed1dd7d6dfe165fc79956f58f7d119e18", "size": 3910, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MT1D.jl", "max_stars_repo_name": "GeoscienceAustralia/HiQGA", "max_stars_repo_head_hexsha": "7980ce00c504ca7fd4238a55c8d9862600cc162f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MT1D.jl", "max_issues_repo_name": "GeoscienceAustralia/HiQGA", "max_issues_repo_head_hexsha": "7980ce00c504ca7fd4238a55c8d9862600cc162f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-30T03:50:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T05:23:46.000Z", "max_forks_repo_path": "src/MT1D.jl", "max_forks_repo_name": "a2ray/transD_GP", "max_forks_repo_head_hexsha": "44238b66ba5b9adb7a93f4759e92d2bff702c9b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8473282443, "max_line_length": 135, "alphanum_fraction": 0.6020460358, "num_tokens": 1508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7813373938030062}}
{"text": "@doc raw\"\"\"\n`HODE`: Hamiltonian Ordinary Differential Equation *EXPERIMENTAL*\n\nDefines a Hamiltonian ordinary differential initial value problem, that is\na canonical Hamiltonian system of equations,\n```math\n\\begin{align*}\n\\dot{q} (t) &= v(t, q(t), p(t)) , & q(t_{0}) &= q_{0} , \\\\\n\\dot{p} (t) &= f(t, q(t), p(t)) , & p(t_{0}) &= p_{0} ,\n\\end{align*}\n```\nwith vector fields ``v`` and ``f``, given by\n```math\n\\begin{align*}\nv &=   \\frac{\\partial H}{\\partial p} , &\nf &= - \\frac{\\partial H}{\\partial q} ,\n\\end{align*}\n```\ninitial conditions ``(q_{0}, p_{0})`` and the dynamical variables ``(q,p)``\ntaking values in ``\\mathbb{R}^{d} \\times \\mathbb{R}^{d}``.\n\n### Fields\n\n* `d`: dimension of dynamical variables ``q`` and ``p`` as well as the vector fields ``v`` and ``f``\n* `n`: number of initial conditions\n* `v`: function computing the vector field ``v``\n* `f`: function computing the vector field ``f``\n* `h`: function computing the Hamiltonian ``H``\n* `t₀`: initial time\n* `q₀`: initial condition for dynamical variable ``q``\n* `p₀`: initial condition for dynamical variable ``p``\n\n\"\"\"\n", "meta": {"hexsha": "70e84fdc0fb747d88d8ce9d9ada879d375c2b9e9", "size": 1086, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/equations/hode.jl", "max_stars_repo_name": "krystophny/GeometricIntegrators.jl", "max_stars_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-04T11:52:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T11:52:47.000Z", "max_issues_repo_path": "src/equations/hode.jl", "max_issues_repo_name": "krystophny/GeometricIntegrators.jl", "max_issues_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/equations/hode.jl", "max_forks_repo_name": "krystophny/GeometricIntegrators.jl", "max_forks_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9411764706, "max_line_length": 100, "alphanum_fraction": 0.6279926335, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140206578809, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7813315094796132}}
{"text": "\"\"\"\n  Sampling from a poisson distribution\n\"\"\"\nabstract type AbstractPoissonDistribution <: AbstractSampleDistribution end\nstruct PoissonSampleDistribution{T} <: AbstractPoissonDistribution\n  lambda::T\n  function PoissonSampleDistribution(lambda::T) where {T <: AbstractFloat}\n    return new{T}(lambda)\n  end\nend\n\n\"\"\"\n  Sampling from Poisson Distribution\n\n  Reference:\n  Poisson Random Variate Generation, Appl. Statis. (1991), \n      40, No. 1, pp 143 - 158.\n  \n  # Example:\n  sample(PoissonSampleDistribution(1.0), (20,))\n\n\"\"\"\nfunction sample(distrib::PoissonSampleDistribution{T}, shape::Tuple{Vararg{Int64}}, version::Val{1}) where {T <: AbstractFloat}\n  \n  n = prod(shape)\n  p = exp(-distrib.lambda)\n  ret = zeros(T, shape)\n\n  for i in 1:n\n    s = T(1); x = T(0)\n    while true\n      u = rand(T, 1)[1]\n      s *= u\n      if s < p\n        break\n      end\n      x += 1\n    end\n    ret[i] = x\n  end\n  \n  return ret\nend\n\nfunction sample(distrib::PoissonSampleDistribution{T}, shape::Int64, version::Val{1}) where {T <: AbstractFloat}\n  return sample(distrib, (shape,))\nend\n\n\n\"\"\"\n  Function to sample from poisson from a lambda array\n\"\"\"\nfunction sample(::Type{<: AbstractPoissonDistribution}, lambda::Array{T}, version::Val{1}) where {T <: AbstractFloat}\n  \n  shape = size(lambda)\n  n = prod(shape)\n  ret = zeros(T, shape)\n\n  for i in 1:n\n    p = exp(-lambda[i])\n    s = T(1); x = T(0)\n    while true\n      u = rand(T, 1)[1]\n      s *= u\n      if s < p\n        break\n      end\n      x += 1\n    end\n    ret[i] = x\n  end\n\n  return ret\nend\n\nfunction sample(distrib::PoissonSampleDistribution{T}, shape::Tuple{Vararg{Int64}}, version::Val{2}) where {T <: AbstractFloat}\n  \n  n = prod(shape)\n  ret = zeros(T, shape)\n\n  for i in 1:n\n    p = exp(-distrib.lambda)\n    F = p; x = T(0)\n    u = rand(T, 1)[1]\n    while true\n      if u < F\n        break\n      end\n      x += 1\n      p *= (distrib.lambda/x)\n      F += p\n    end\n    ret[i] = x\n  end\n  \n  return ret\nend\n\nfunction sample(distrib::PoissonSampleDistribution{T}, shape::Int64, version::Val{2}) where {T <: AbstractFloat}\n  return sample(distrib, (shape,))\nend\n\n\"\"\"\n  Function to sample from poisson from a lambda array\n\"\"\"\nfunction sample(::Type{<: AbstractPoissonDistribution}, lambda::Array{T}, version::Val{2}) where {T <: AbstractFloat}\n  \n  shape = size(lambda)\n  n = prod(shape)\n  ret = zeros(T, shape)\n  \n  for i in 1:n\n    p = exp(-lambda[i])\n    F = p; x = T(0)\n    u = rand(T, 1)[1]\n    while true\n      if u < F\n        break\n      end\n      x += 1\n      p *= (lambda[i]/x)\n      F += p\n    end\n    ret[i] = x\n  end\n  \n  return ret\nend\n\n\n\"\"\"\n# Example simulate poisson distribution\n\n  X, eta = simulateData(Float64, 10, 1000);\n  y = linkinv(LogLink(), eta);\n  y = sample(AbstractPoissonDistribution, y, Val{2}());\n\"\"\"\n\n\n\"\"\"\n  Function to simulate data\n\n  # Example\n  using Random: seed!\n  seed!(0);\n  X, y = simulateData(Float64, PoissonDistribution(), LogLink(), 10, 1000)\n  X, y = simulateData(Float64, BinomialDistribution(), LogitLink(), 10, 1000)\n  X, y = simulateData(Float64, GammaDistribution(), LogLink(), 10, 1000)\n  X, y = simulateData(Float64, GaussianDistribution(), IdentityLink(), 10, 1000)\n\"\"\"\nfunction simulateData(::Type{T}, distrib::AbstractDistribution, \n              link::AbstractLink, p::Int64, n::Int64) where {T <: AbstractFloat}\n  \n  X = Array{T, 2}(undef, (0, 0))\n  eta = Array{T, 1}(undef, (0,))\n  \n  X, eta = simulateData(T, p, n)\n  y = linkinv(link, eta)\n\n  if (typeof(distrib) <: GammaDistribution)\n    y .+= 10\n  end\n\n  if typeof(distrib) <: PoissonDistribution\n    y = sample(AbstractPoissonDistribution, y, Val{2}())\n  end\n\n  if typeof(distrib) <: BinomialDistribution\n    y = map((x, u) -> T(1)*(x > u), y, rand(T, n))\n  end\n  \n  y = reshape(y, (size(y)[1], 1))\n  \n  return X, y\nend\n", "meta": {"hexsha": "69b7e843109beea3ddd73b50e96ca4c27f3029d8", "size": 3781, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "glmSolverjl/src/simulate.jl", "max_stars_repo_name": "dataPulverizer/glmSolver", "max_stars_repo_head_hexsha": "d82623caac1e14d29ee09fbafa7efbbd5d6ee0bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-17T15:34:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-17T15:34:44.000Z", "max_issues_repo_path": "glmSolverjl/src/simulate.jl", "max_issues_repo_name": "dataPulverizer/glmSolver", "max_issues_repo_head_hexsha": "d82623caac1e14d29ee09fbafa7efbbd5d6ee0bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "glmSolverjl/src/simulate.jl", "max_forks_repo_name": "dataPulverizer/glmSolver", "max_forks_repo_head_hexsha": "d82623caac1e14d29ee09fbafa7efbbd5d6ee0bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4829545455, "max_line_length": 127, "alphanum_fraction": 0.6088336419, "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996141, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7812804022891165}}
{"text": "using ISA #References: Sandoval, Steven, and Phillip L. De Leon. \"The Instantaneous Spectrum: A General Framework for Time-Frequency Analysis.\" IEEE Transactions on Signal Processing 66.21 (2018): 5679-5693.\r\nusing Plots\r\n\r\nsig = cos.(0.0:π/100:10pi) +  cos.( 5*(0.0:π/100:10pi))+  cos.( 20*(0.0:π/100:10pi))\r\nφ₁ = SIFT(sig)\r\nplot(sig)\r\nplot!(φ₁)\r\nφ₂ = SIFT(sig-φ₁)\r\nplot!(φ₂)\r\nplot!(sig-φ₁-φ₂)\r\n\r\n\r\n#-------------------------------------------\r\n\r\nsig = cos.(0.0:π/100:10pi) +  cos.( 5*(0.0:π/100:10pi))+  cos.( 20*(0.0:π/100:10pi))\r\nIMF = EMD(sig)\r\nplot(sig)\r\nplot!(IMF)\r\n\r\n#-------------------------------------------\r\n\r\nsig = exp.( 1im*(0.0:π/100:10pi)) +  exp.( 5im*(0.0:π/100:10pi)) +  exp.( 20im*(0.0:π/100:10pi))\r\nφ₁ = ℂSIFT(sig)\r\nplot(real(sig))\r\nplot!(real(φ₁))\r\nφ₂ = ℂSIFT(sig-φ₁)\r\nplot!(real(φ₂))\r\nplot!(real(sig-φ₁-φ₂))\r\n\r\n#-------------------------------------------\r\n\r\nsig = exp.( 1im*(0.0:π/100:10pi)) +  exp.( 5im*(0.0:π/100:10pi)) +  exp.( 20im*(0.0:π/100:10pi))\r\nIMF = ℂEMD(sig)\r\nplot(real(sig))\r\nplot!(real.(IMF))\r\n", "meta": {"hexsha": "d90a5889606e743044101a511a288a043f37c393", "size": 1034, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/EMDtests.jl", "max_stars_repo_name": "kricheso/ISA", "max_stars_repo_head_hexsha": "d6f8c60b319b7a3ea436f831a8d60995744d90b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/EMDtests.jl", "max_issues_repo_name": "kricheso/ISA", "max_issues_repo_head_hexsha": "d6f8c60b319b7a3ea436f831a8d60995744d90b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/EMDtests.jl", "max_forks_repo_name": "kricheso/ISA", "max_forks_repo_head_hexsha": "d6f8c60b319b7a3ea436f831a8d60995744d90b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7222222222, "max_line_length": 208, "alphanum_fraction": 0.5232108317, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.7812804022560845}}
{"text": "export # Convex Hull Functions\n       ch_akl_toussaint,\n       ch_bykat,\n       ch_eddy,\n       ch_graham_andrew,\n       ch_jarvis,\n       ch_melkman,\n       convex_hull_2,\n       # Convexity Checking\n       is_ccw_strongly_convex_2,\n       is_cw_strongly_convex_2,\n       # Hull Subsequence Functions\n       ch_graham_andrew_scan,\n       ch_jarvis_march,\n       lower_hull_points_2,\n       upper_hull_points_2,\n       # Extreme Point Functions\n       ch_e_point,\n       ch_n_point,\n       ch_ns_point,\n       ch_nswe_point,\n       ch_s_point,\n       ch_w_point,\n       ch_we_point\n\n@doc raw\"\"\"\n    ch_akl_toussaint(ps::AbstractVector{Point2})\n    ch_akl_toussaint(ps::Point2...)\n\nReturns the counterclockwise sequence of extreme points of points in the vector\n`ps`.\n\nIt is not specified at which point the cyclic sequence of extreme points is cut\ninto a linear sequence.\n\n!!! info \"Precondition\"\n\n    The vector `ps` does not contain the result.\n\n### Implementation\n\nThis function uses the algorithm of Akl and Toussaint [^sga78] that requires\n``O(n \\log n)`` time for ``n`` input points.\n\n[^sga78]: S. G. Akl and G. T. Toussaint. A fast convex hull algorithm. *Inform.\n          Process. Lett.*, 7(5):219--222, 1978.\n\nSee also: [`ch_bykat()`](@ref), [`ch_eddy()`](@ref),\n[`ch_graham_andrew()`](@ref), [`ch_jarvis()`](@ref), [`ch_melkman()`](@ref),\n[`convex_hull_2()`](@ref)\n\"\"\"\nch_akl_toussaint(ps::AbstractVector{Point2})\n\n@doc raw\"\"\"\n    ch_bykat(ps::AbstractVector{Point2})\n    ch_bykat(ps::Point2...)\n\nReturns the counterclockwise sequence of extreme points of points in the vector\n`ps`.\n\nIt is not specified at which point the cyclic sequence of extreme points is cut\ninto a linear sequence.\n\n!!! info \"Precondition\"\n\n    The vector `ps` does not contain the result.\n\n### Implementation\n\nThis function implements the non-recursive variation of Eddy's algorithm (see\n[`ch_eddy()`](@ref)) described in [^kra78]. This algorithm requires ``O(nh)``\ntime in the worst case for ``n`` input points with ``h`` extreme points.\n\n[^kra78]: K. R. Anderson. A reevaluation of an efficient algorithm for determining\n          the convex hull of a finite planar set. *Inform. Process. Lett.*,\n          7(1):53--55, 1978.\n\nSee also: [`ch_akl_toussaint()`](@ref), [`ch_eddy()`](@ref),\n[`ch_graham_andrew()`](@ref), [`ch_jarvis()`](@ref), [`ch_melkman()`](@ref),\n[`convex_hull_2()`](@ref)\n\"\"\"\nch_bykat(ps::AbstractVector{Point2})\n\n@doc raw\"\"\"\n    ch_eddy(ps::AbstractVector{Point2})\n    ch_eddy(ps::Point2...)\n\nReturns the counterclockwise sequence of extreme points of points in the vector\n`ps`.\n\nIt is not specified at which point the cyclic sequence of extreme points is cut\ninto a linear sequence.\n\n!!! info \"Precondition\"\n\n    The vector `ps` does not contain the result.\n\n### Implementation\n\nThe function implements Eddy's algorithm [^wfe77], which is the two-dimensional\nversion of the quickhull algorithm [^cbb77].\n\nThis algorithm requires ``O(nh)`` time in the worst case for ``n`` input points\nwith ``h`` extreme points.\n\n[^wfe77]: W. F. Eddy. A new convex hull algorithm for planar sets. *ACM Trans.\n          Math. Softw.*, 3:398--403 and 411--412, 1977.\n\n[^cbb96]: C. Bradford Barber, David P. Dobkin, and Hannu Huhdanpaa. The\n          Quickhull algorithm for convex hulls. *ACM Trans. Math. Softw.*,\n          22(4):469--483, December 1996.\n\nSee also: [`ch_akl_toussaint()`](@ref), [`ch_bykat()`](@ref),\n[`ch_graham_andrew()`](@ref), [`ch_jarvis()`](@ref), [`ch_melkman()`](@ref),\n[`convex_hull_2()`](@ref)\n\"\"\"\nch_eddy(ps::AbstractVector{Point2})\n\n@doc raw\"\"\"\n    ch_graham_andrew(ps::AbstractVector{Point2})\n    ch_graham_andrew(ps::Point2...)\n\nReturns the counterclockwise sequence of extreme points of points in the vector\n`ps`.\n\nIt is not specified at which point the cyclic sequence of extreme points is cut\ninto a linear sequence.\n\n!!! info \"Precondition\"\n\n    The vector `ps` does not contain the result.\n\n### Implementation\n\nThis function implements Andrew's variant of the Graham scan algorithm\n[^ama79] and follows the presentation of Mehlhorn [^km84]. This algorithm\nrequires ``O(n \\log n)`` time in the worst case for ``n`` input points.\n\n[^ama79]: A. M. Andrew. Another efficient algorithm for convex hulls in two\n    dimensions. *Inform. Process. Lett.*, 9(5):216--219, 1979.\n\n[^km84]: Kurt Mehlhorn. *Data Structures and Algorithms 3: Multi-dimensional\n         Searching and Computational Geometry*, volume 3 of *EATCS Monographs\n         on Theoretical Computer Science*. Springer-Verlag, Heidelberg,\n         Germany, 1984.\n\nSee also: [`ch_akl_toussaint()`](@ref), [`ch_bykat()`](@ref),\n[`ch_eddy()`](@ref), [`ch_graham_andrew_scan()`](@ref), [`ch_jarvis()`](@ref),\n[`ch_melkman()`](@ref), [`convex_hull_2()`](@ref),\n[`lower_hull_points_2`](@ref), [`upper_hull_points_2`](@ref)\n\"\"\"\nch_graham_andrew(ps::AbstractVector{Point2})\n\n@doc raw\"\"\"\n    ch_jarvis(ps::AbstractVector{Point2})\n    ch_jarvis(ps::Point2...)\n\nReturns the counterclockwise sequence of extreme points of points in the vector\n`ps`.\n\nIt is not specified at which point the cyclic sequence of extreme points is cut\ninto a linear sequence.\n\n!!! info \"Precondition\"\n\n    The vector `ps` does not contain the result.\n\n### Implementation\n\nThis functions uses the Jarvis march (gift-wrapping) algorithm [^raj73]. This\nalgorithm requires ``O(nh)`` time in the worst case for ``n`` input points with\n``h`` extreme points.\n\n[^raj73]: R. A. Jarvis. On the identification of the convex hull of a finite\n          set of points in the plane. *Inform. Process. Lett.*, 2:18--21, 1973.\n\nSee also: [`ch_akl_toussaint()`](@ref), [`ch_bykat()`](@ref),\n[`ch_eddy()`](@ref), [`ch_graham_andrew()`](@ref), [`ch_jarvis_march()`](@ref),\n[`ch_melkman()`](@ref), [`convex_hull_2()`](@ref)\n\"\"\"\nch_jarvis(ps::AbstractVector{Point2})\n\n@doc raw\"\"\"\n    ch_melkman(ps::AbstractVector{Point2})\n    ch_melkman(ps::Point2...)\n\nReturns the counterclockwise sequence of extreme points of points in the vector\n`ps`.\n\nIt is not specified at which point the cyclic sequence of extreme points is cut\ninto a linear sequence.\n\n!!! info \"Precondition\"\n\n    The vector `ps` does not contain the result.\n\n### Implementation\n\nIt uses an implementation of Melkman's algorithm [^am87]. Running time of\nthis is linear.\n\n[^am87] A. Melkman. On-line construction of the convex hull of a simple\n        polyline. *Inform. Process. Lett.*, 25:11--12, 1987.\n\nSee also: [`ch_akl_toussaint()`](@ref), [`ch_bykat()`](@ref),\n[`ch_eddy()`](@ref), [`ch_graham_andrew()`](@ref), [`ch_jarvis()`](@ref),\n[`convex_hull_2()`](@ref)\n\"\"\"\nch_melkman(ps::AbstractVector{Point2})\n\n@doc raw\"\"\"\n    convex_hull_2(ps::AbstractVector{Point2})\n    convex_hull_2(ps::Point2...)\n\nReturns the counterclockwise sequence of extreme points of points in the vector\n`ps`.\n\nIt is not specified at which point the cyclic sequence of extreme points is cut\ninto a linear sequence.\n\n!!! info \"Precondition\"\n\n    The vector `ps` does not contain the result.\n\n### Implementation\n\nThe ``O(n \\log n)`` Akl and Toussaint [^sga78] algorithm is used.\n\nSee also: [`ch_akl_toussaint()`](@ref), [`ch_bykat()`](@ref),\n[`ch_eddy()`](@ref), [`ch_graham_andrew()`](@ref), [`ch_jarvis()`](@ref),\n[`ch_melkman()`](@ref)\n\"\"\"\nconvex_hull_2(ps::AbstractVector{Point2})\n\n\"\"\"\n    is_ccw_strongly_convex_2(ps::AbstractVector{Point2})\n    is_ccw_strongly_convex_2(ps::Point2...)\n\nThe function [`is_ccw_strongly_convex_2()`](@ref) determines if a given\nsequence of points defines a counterclockwise-oriented, strongly convex polygon.\n\nIt returns `true`, iff the point elements in `ps` form a\ncounterclockwise-oriented strongly convex polygon.\n\nA set of points is said to be strongly convex if it consists of only extreme\npoints (*i.e.*, vertices of the convex hull).\n\n### Implementation\n\nThe algorithm requires ``O(n)`` time for a set of ``n`` input points.\n\nSee also: [`is_cw_strongly_convex_2()`](@ref)\n\"\"\"\nis_ccw_strongly_convex_2(ps::AbstractVector{Point2})\n\n\"\"\"\n    is_cw_strongly_convex_2(ps::AbstractVector{Point2})\n    is_cw_strongly_convex_2(ps::Point2...)\n\nThe function [`is_cw_strongly_convex_2()`](@ref) determines if a given sequence\nof points defines a clockwise-oriented, strongly convex polygon.\n\nIt returns `true`, iff the point elements in `ps` form a clockwise-oriented\nstrongly convex polygon.\n\nA set of points is said to be strongly convex if it consists of only extreme\npoints (*i.e.*, vertices of the convex hull).\n\n### Implementation\n\nThe algorithm requires ``O(n)`` time for a set of ``n`` input points.\n\nSee also: [`is_ccw_strongly_convex_2()`](@ref)\n\"\"\"\nis_cw_strongly_convex_2(ps::AbstractVector{Point2})\n\nfor F ∈ (:is_ccw_strongly_convex_2, :is_cw_strongly_convex_2)\n    @eval begin\n        $F(ps::AbstractVector) = $F(collect(CxxRef{Point2}, CxxRef.(ps)))\n        $F(ps::reference_type_union(Point2)...) = $F(collect(CxxRef.(ps)))\n    end\nend\n\n\"\"\"\n    ch_graham_andrew_scan(ps::AbstractVector{Point2})\n    ch_graham_andrew_scan(p::Point2, q::Point2, ps::Point2...)\n\nGenerates the counterclockwise sequence of extreme points from a given\nsequence of input points that are not left of the line defined by the first and\nlast points in this sequence.\n\nMore precisely, it generates the counterclockwise sequence of extreme points\nfrom a given sequence of input points that are not left of the line ``pq``\ndefined by the first (``p``) and last (``q``) points in the sequence (``p`` is\nthe value of `first(ps)` and ``q`` is the value of `last(ps)`).  The resulting\nsequence is returned starting with ``p``; point ``q`` is omitted.\n\n!!! info \"Precondition\"\n\n    `ps` contains at least two different points.  The points in `ps` are sorted\n    with respect to ``pq``, *i.e.*, the sequence of points in `ps` defines a\n    counterclockwise polygon, for which the Graham-Sklansky-procedure [^js72]\n    works.\n\n### Implementation\n\nThis algorithm requires ``O(n)`` time in the worst case for ``n`` input points.\n\n[^js72]: J. Sklansky. Measuring concavity on rectangular mosaic. *IEEE Trans.\n         Comput.*, C-21:1355--1364, 1972.\n\nSee also: [`ch_graham_andrew()`](@ref), [`lower_hull_points_2()`](@ref),\n[`upper_hull_points_2()`](@ref)\n\"\"\"\nch_graham_andrew_scan(ps::AbstractVector{Point2})\n\n@cxxdereference ch_graham_andrew_scan(ps::AbstractVector) =\n    ch_graham_andrew_scan(collect(CxxRef{Point2}, CxxRef.(ps)))\n@cxxdereference ch_graham_andrew_scan(p::Point2, q::Point2,\n                                      ps::reference_type_union(Point2)...) =\n    ch_graham_andrew_scan(CxxRef.([p, q, ps...]))\n\n\"\"\"\n    ch_jarvis_march(ps::AbstractVector{Point2}, p::Point2, q::Point2)\n    ch_jarvis_march(p::Point2, q::Point2, ps::Point2...)\n\nGenerates the counterclockwise sequence of extreme points from a given set of\ninput points that line between two input points.\n\nMore precisely, it generates the counterclockwise subsequence of extreme points\nbetween `p` and `q` of the points in `ps`.  Said sequence is returned starting\nwith point `p`.  The last point generated is the point preceding `q` in the\ncounterclockwise order of extreme points.\n\n!!! info \"Precondition\"\n\n    `p` and `q` are extreme points with respect to the points in `ps` and `q`\n    belongs to `ps`.\n\n### Implementation\n\nThe functions uses the Jarvis march (gift-wrapping) algorithm [^raj73]. This\nalgorithm requires ``O(nh)`` time in the worst case for ``n`` input points with\n``h`` extreme points.\n\nSee also: [`ch_jarvis()`](@ref), [`lower_hull_points_2()`](@ref),\n[`upper_hull_points_2()`](@ref)\n\"\"\"\nch_jarvis_march(ps::AbstractVector{Point2}, p::Point2, q::Point2)\n\n@cxxdereference ch_jarvis_march(ps::AbstractVector, p::Point2, q::Point2) =\n    ch_jarvis_march(collect(CxxRef{Point2}, CxxRef.(ps)), p, q)\n@cxxdereference ch_jarvis_march(p::Point2, q::Point2, ps::Point2...) =\n    ch_jarvis_march(collect(ps), p, q)\n\n@doc raw\"\"\"\n    lower_hull_points_2(ps::AbstractVector{Point2})\n    lower_hull_points_2(ps::Point2...)\n\nGenerates the counterclockwise sequence of extreme points on the lower hull of a\ngiven set of input points.\n\nMore precisely, it generates the counterclockwise sequence of extreme points in\nthe lower hull of the points in `ps`.  The resulting sequence is returned,\nstarting with the leftmost point; the rightmost point is not included.  If there\nis only one extreme point (*i.e.*, the leftmost and rightmost points are equal),\nthe extreme point is reported.\n\n!!! info \"Precondition\"\n\n    `ps` does not contain the result.\n\nThe different treatment by [`upper_hull_points_2()`](@ref) of the case that all\npoints are equal ensures that concatenation of lower and upper hull points gives\nthe sequence of extreme points.\n\n### Implementation\n\nThis function uses Andrew's variant of Graham's scan algorithm [^ama79],\n[^km84]. The algorithm has worst-case running time of ``O(n \\log n)`` for\n``n`` input points.\n\nSee also: [`ch_graham_andrew()`](@ref), [`ch_graham_andrew_scan()`](@ref),\n[`upper_hull_points_2()`](@ref)\n\"\"\"\nlower_hull_points_2(ps::AbstractVector{Point2})\n\n@doc raw\"\"\"\n    upper_hull_points_2(ps::AbstractVector{Point2})\n    upper_hull_points_2(ps::Point2...)\n\nGenerates the counterclockwise sequence of extreme points on the upper hull of a\ngiven set of input points.\n\nMore precisely, it generates the counterclockwise sequence of extreme points in\nthe lower hull of the points in `ps`.  The resulting sequence is returned,\nstarting with the rightmost point; the leftmost point is not included.  If there\nis only one extreme point (*i.e.*, the leftmost and rightmost points are equal),\nthe extreme point is reported.\n\n!!! info \"Precondition\"\n\n    `ps` does not contain the result.\n\nThe different treatment by [`lower_hull_points_2()`](@ref) of the case that all\npoints are equal ensures that concatenation of lower and upper hull points gives\nthe sequence of extreme points.\n\n### Implementation\n\nThis function uses Andrew's variant of Graham's scan algorithm [^ama79],\n[^km84]. The algorithm has worst-case running time of ``O(n \\log n)`` for\n``n`` input points.\n\nSee also: [`ch_graham_andrew()`](@ref), [`ch_graham_andrew_scan()`](@ref),\n[`lower_hull_points_2()`](@ref)\n\"\"\"\nupper_hull_points_2(ps::AbstractVector{Point2})\n\nfor F ∈ (:ch_akl_toussaint\n       , :ch_bykat\n       , :ch_eddy\n       , :ch_graham_andrew\n       , :ch_jarvis\n       , :ch_melkman\n       , :convex_hull_2\n       , :lower_hull_points_2\n       , :upper_hull_points_2)\n    @eval begin\n        $F(ps::AbstractVector) = $F(collect(CxxRef{Point2}, CxxRef.(ps)))\n        $F(ps::reference_type_union(Point2)...) = $F(collect(CxxRef.(ps)))\n    end\nend\n\n\n@doc raw\"\"\"\n    ch_e_point(ps::AbstractVector{Point2})\n    ch_e_point(ps::Point2...)\n\nThe function [`ch_e_point()`](@ref) finds a point of a given set of input points\nwith maximal ``x`` coordinate.\n\nIt traverses `ps`. After execution, the returned value is the first point\n``e`` such that ``∀p\\! ∈\\! ps\\; e ≥_{xy} p``.\n\nSee also: [`ch_n_point()`](@ref), [`ch_nswe_point()`](@ref),\n[`ch_ns_point()`](@ref), [`ch_s_point()`](@ref), [`ch_w_point()`](@ref),\n[`ch_we_point()`](@ref)\n\"\"\"\nch_e_point(ps::AbstractVector{Point2})\n\n@doc raw\"\"\"\n    ch_n_point(ps::AbstractVector{Point2})\n    ch_n_point(ps::Point2...)\n\nThe function [`ch_n_point()`](@ref) finds a point of a given set of input points\nwith maximal ``y`` coordinate.\n\nIt traverses `ps`. After execution, the returned value is the first point\n``n`` such that ``∀p\\! ∈\\! ps\\; n ≥_{yx} p``.\n\nSee also: [`ch_e_point()`](@ref), [`ch_nswe_point()`](@ref),\n[`ch_ns_point()`](@ref), [`ch_s_point()`](@ref), [`ch_w_point()`](@ref),\n[`ch_we_point()`](@ref)\n\"\"\"\nch_n_point(ps::AbstractVector{Point2})\n\n@doc raw\"\"\"\n    ch_ns_point(ps::AbstractVector{Point2})\n    ch_ns_point(ps::Point2...)\n\nThe function [`ch_ns_point()`](@ref) finds two points of a given set of input\npoints with minimal and maximal ``y`` coordinate.\n\nIt traverses `ps`. After execution, the returned value is a tuple where the\nfirst point ``n`` is such that ``∀p\\! ∈\\! ps\\; n ≥_{yx} p``, and the second\npoint ``s`` is such that ``∀p\\! ∈\\! ps\\; s ≤_{yx} p``.\n\nSee also: [`ch_e_point()`](@ref), [`ch_nswe_point()`](@ref),\n[`ch_n_point()`](@ref), [`ch_s_point()`](@ref), [`ch_w_point()`](@ref),\n[`ch_we_point()`](@ref)\n\"\"\"\nch_ns_point(ps::AbstractVector{Point2})\n\n@doc raw\"\"\"\n    ch_nswe_point(ps::AbstractVector{Point2})\n    ch_nswe_point(ps::Point2...)\n\nThe function [`ch_nswe_point()`](@ref) finds the four extreme points of a given\nset of input points using a linear scan of the input points.\n\nThat is, it determines the points with maximal ``y``, minimal ``y``, minimal\n``x``, and maximal ``x`` coordinates.\n\nIt traverses `ps`. After execution, the returned value is a tuple where the\nfirst point ``n`` is such that ``∀p\\! ∈\\! ps\\; n ≥_{yx} p``, the second\npoint ``s`` is such that ``∀p\\! ∈\\! ps\\; s ≤_{yx} p``, the third point ``w`` is\nsuch that ``∀p\\! ∈\\! ps\\; w ≤_{xy} p``, and the fourth point ``e`` is such that\n``∀p\\! ∈\\! ps\\; e ≥_{xy} p``.\n\nSee also: [`ch_e_point()`](@ref), [`ch_n_point()`](@ref),\n[`ch_ns_point()`](@ref), [`ch_s_point()`](@ref), [`ch_w_point()`](@ref),\n[`ch_we_point()`](@ref)\n\"\"\"\nch_nswe_point(ps::AbstractVector{Point2})\n\n@doc raw\"\"\"\n    ch_s_point(ps::AbstractVector{Point2})\n    ch_s_point(ps::Point2...)\n\nThe function [`ch_s_point()`](@ref) finds a point of a given set of input points\nwith minimal ``y`` coordinate.\n\nIt traverses `ps`. After execution, the returned value is the first point\n``s`` such that ``∀p\\! ∈\\! ps\\; s ≤_{yx} p``.\n\nSee also: [`ch_e_point()`](@ref), [`ch_nswe_point()`](@ref),\n[`ch_n_point()`](@ref), [`ch_ns_point()`](@ref), [`ch_w_point()`](@ref),\n[`ch_we_point()`](@ref)\n\"\"\"\nch_s_point(ps::AbstractVector{Point2})\n\n@doc raw\"\"\"\n    ch_w_point(ps::AbstractVector{Point2})\n    ch_w_point(ps::Point2...)\n\nThe function [`ch_w_point()`](@ref) finds a point of a given set of input points\nwith minimal ``x`` coordinate.\n\nIt traverses `ps`. After execution, the returned value is the first point\n``w`` such that ``∀p\\! ∈\\! ps\\; w ≤_{xy} p``.\n\nSee also: [`ch_e_point()`](@ref), [`ch_nswe_point()`](@ref),\n[`ch_n_point()`](@ref), [`ch_ns_point()`](@ref), [`ch_s_point()`](@ref),\n[`ch_we_point()`](@ref)\n\"\"\"\nch_w_point(ps::AbstractVector{Point2})\n\n@doc raw\"\"\"\n    ch_we_point(ps::AbstractVector{Point2})\n    ch_we_point(ps::Point2...)\n\nThe function [`ch_we_point()`](@ref) finds two points of a given set of input\npoints with minimal and maximal ``x`` coordinate.\n\nIt traverses `ps`. After execution, the returned value is a tuple where the\nfirst point ``w`` is such that ``∀p\\! ∈\\! ps\\; w ≤_{xy} p``, and the second\npoint ``e`` is such that ``∀p\\! ∈\\! ps\\; e ≥_{xy} p``.\n\nSee also: [`ch_e_point()`](@ref), [`ch_nswe_point()`](@ref),\n[`ch_n_point()`](@ref), [`ch_ns_point()`](@ref), [`ch_s_point()`](@ref),\n[`ch_w_point()`](@ref)\n\"\"\"\nch_we_point(ps::AbstractVector{Point2})\n\nfor S ∈ (:e, :n, :ns, :nswe, :s, :w, :we)\n    F = Symbol(:ch_, S, :_point)\n    @eval begin\n        $F(ps::AbstractVector) =\n            isempty(ps) ?\n                $F([CxxRef(Point2())]) :\n                $F(CxxRef.(ps))\n        $F(ps::reference_type_union(Point2)...) = $F(collect(CxxRef.(ps)))\n    end\nend\n", "meta": {"hexsha": "487d646528bc7f0ccdc0ee66bc4f74f9a900de35", "size": 19055, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/convex_hull_2.jl", "max_stars_repo_name": "rgcv/CGAL.jl", "max_stars_repo_head_hexsha": "a3d55993938f271f3243fb86cb59f2e481bac7d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-07-17T22:06:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T08:32:54.000Z", "max_issues_repo_path": "src/convex_hull_2.jl", "max_issues_repo_name": "rgcv/CGAL.jl", "max_issues_repo_head_hexsha": "a3d55993938f271f3243fb86cb59f2e481bac7d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-10-31T19:37:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T20:04:37.000Z", "max_forks_repo_path": "src/convex_hull_2.jl", "max_forks_repo_name": "rgcv/CGAL.jl", "max_forks_repo_head_hexsha": "a3d55993938f271f3243fb86cb59f2e481bac7d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-16T13:55:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T18:07:26.000Z", "avg_line_length": 33.6660777385, "max_line_length": 82, "alphanum_fraction": 0.6855943322, "num_tokens": 5620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7812455945761829}}
{"text": "#=\nN-queens problem in Julia. \n\nCf with the ConstraintSolver.jl solution: http://hakank.org/julia/constraint/nqueens.jl\n\nThis Julia program was created by Hakan Kjellerstrand, hakank@gmail.com\nSee also my Julia page: http://www.hakank.org/julia/\n\n=#\n\ninclude(\"jl_utils.jl\") # for next_permutation \n\n\n\n\n\n# Brute force version using next_permutation\n# Find all solutions\nfunction queens(n=8,num=0,printit=true) \n    println(\"n:$n\")\n    q = collect(1:n)\n    rev = reverse(q)\n    c = 0\n    while q != rev\n      check = true\n      for i in 1:n\n        for j in 1:i-1\n          if q[i] === q[j] ||\n            q[i] + i === q[j] + j ||\n            q[i] - i === q[j] - j\n            check = false\n            break\n          end\n        end\n      end\n    \n      if check === true\n        c += 1 \n        if printit\n          println(q)\n        end\n        if num > 0 && c >= num \n          return c\n        end\n      end\n      if q != rev \n        q = next_permutation(q)\n      end\n    end\n    if printit\n      println(c)\n    end\n  \n    return c\nend\n\n@time queens(8,0, true)\n\n@time queens(8,0, false)\n\nprintln(\"\\nCount all solutions:\")\nfor n in 2:10\n  @time c = queens(n,0,false)\n  println(\"n:$n count:$c\")\nend\n\nprintln(\"\\nFirst solution:\")\nfor n in 2:12\n  @time c = queens(n,1,true)\n  println(\"n:$n count:$c\")\nend\n", "meta": {"hexsha": "64a003a17ee85672937721aaded35ac19641708a", "size": 1307, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/queens.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/queens.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/queens.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 18.1527777778, "max_line_length": 87, "alphanum_fraction": 0.5401683244, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7812455942789404}}
{"text": "using EngEconomics\n\n# Given\nxInit = 80000\nxMaintenance = 30000\nxSalvage = 40000\nyInit = 97000\nyMaintenance = 27000\nySalvage = 50000\ni = 0.15\nN = 3 # years\n\n# Find: The Future Worth Analysis\n# Determine Alternatives\noption1Init = xInit * 2\noption2Init = yInit * 2\noption3Init = xInit + yInit\noption1Maintenance = xMaintenance * 2\noption2Maintenance = yMaintenance * 2\noption3Maintenance = xMaintenance + yMaintenance\noption1Salvage = 2 * xSalvage\noption2Salvage = 2 * ySalvage\noption3Salvage = xSalvage + ySalvage\n\n# Determine the FW of Option1\noption1InitFW = -option1Init * compoundAmountFactor(i, N)\noption1MaintenanceFW = -option1Maintenance * uniformSeriesCompoundAmoundFactor(i, N)\noption1SalvageFW = option1Salvage\noption1FW = option1InitFW + option1MaintenanceFW + option1SalvageFW\n\n# Determine the FW of Option2\noption2InitFW = -option2Init * compoundAmountFactor(i, N)\noption2MaintenanceFW = -option2Maintenance * uniformSeriesCompoundAmoundFactor(i, N)\noption2SalvageFW = option2Salvage\noption2FW = option2InitFW + option2MaintenanceFW + option2SalvageFW\n\n# Determine the FW of Option3\noption3InitFW = -option3Init * compoundAmountFactor(i, N)\noption3MaintenanceFW = -option3Maintenance * uniformSeriesCompoundAmoundFactor(i, N)\noption3SalvageFW = option3Salvage\noption3FW = option3InitFW + option3MaintenanceFW + option3SalvageFW\n\n# Pick the Better one\nmaxOption = max(option1FW, option2FW, option3FW)\n\nif maxOption == option1FW\n\tprintln(\"Pick XX\")\nelseif maxOption == option2FW\n\tprintln(\"Pick YY\")\nelse\n\tprintln(\"Pick XY\")\nend\n", "meta": {"hexsha": "5b31a59a2ca65eed073fda0ffe721455248bbc0b", "size": 1539, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps4/p5.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/ps4/p5.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/ps4/p5.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0377358491, "max_line_length": 84, "alphanum_fraction": 0.7992202729, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591976, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7812382716775097}}
{"text": "abstract type AbstractHeap{T} <: AbstractTree{T} end\n\nmutable struct BinaryHeap{T} <: AbstractHeap{T}\n    tree::CompleteBinaryTree{T}\n    size::Int\n    maxsize::Int\n    comparator::Function\n    function BinaryHeap{T}(data, comparator) where T\n        tree = CompleteBinaryTree{T}(data)\n        size = tree.size\n        maxsize = DEFAULT_MAX_SIZE\n        n = new(tree, size, maxsize, comparator)\n        buildheap!(n)\n    end\nend\n\nBinaryHeap(data::Vector, comparator) = BinaryHeap{eltype(data)}(data, comparator)\nMinHeap(data::Vector) = BinaryHeap(data, isless)\nMaxHeap(data::Vector) = BinaryHeap(data, (x,y)->isless(y,x))\n\nfunction _siftdown!(h::BinaryHeap, pos)\n    let i = pos\n        while !isleaf(h.tree, i)\n            j = leftchild(h.tree, i)\n            rc = rightchild(h.tree, i)\n            # check if rightchild is within bounds\n            if (rc != 0) && h.comparator(h.tree.data[rc], h.tree.data[j])\n                j = rc\n            end\n            h.comparator(h.tree.data[i], h.tree.data[j]) && break\n            swap!(h.tree, i, j)\n            i = j\n        end\n    end\nend\n\nfunction _siftup!(h::BinaryHeap, pos)\n    let i = pos\n        while (i != 1) && h.comparator(h.tree.data[i], h.tree.data[parent(h.tree, i)])\n            swap!(h.tree, i, parent(h.tree, i))\n            i = parent(h.tree, i)\n        end\n    end\nend\n\nfunction insert!(h::BinaryHeap, item)\n    (h.size < h.maxsize) || throw(ErrorException(\"heap capacity exceeded\"))\n    append!(h.tree, item)\n    h.size += 1\n    _siftup!(h, h.size)\nend\n    \n\nfunction remove!(h::BinaryHeap)\n    (h.size > 0) || throw(ArgumentError(\"no current element\"))\n    item = h.tree.data[1]\n    swap!(h.tree, 1, h.size)\n    h.size -= 1; h.tree.size -= 1\n    if h.size != 0\n        _siftdown!(h, 1)\n    end\n    return item\nend\n\nfunction remove!(h::BinaryHeap, pos)\n    (1 <= pos <= h.size) || throw(BoundsError(h, pos))\n    item = h.tree.data[pos]\n    if pos == h.size\n        h.size -= 1; h.tree.size -= 1\n    else\n        swap!(h.tree, pos, h.size)\n        h.size -= 1; h.tree.size -= 1\n        _siftup!(h, pos)\n        if h.size != 0\n            _siftdown!(h, pos)\n        end\n    end\n    return item\nend\n\nfunction buildheap!(h::BinaryHeap)\n    let i = h.size ÷ 2\n        while i>0\n            _siftdown!(h, i)\n            i -= 1\n        end\n    end\n    return h\nend\n\npeek(h::BinaryHeap) =  (h.size > 0) ? h.tree.data[1] : throw(ArgumentError(\"no current element\"))\nlength(h::BinaryHeap) = h.size\nisempty(h::BinaryHeap) = h.size == 0\n", "meta": {"hexsha": "770323865ac7d477d51f3af94f2725be2b170684", "size": 2497, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tree/heap.jl", "max_stars_repo_name": "hesseltuinhof/DataStructures.jl", "max_stars_repo_head_hexsha": "50c630bfb9b0eb43329bfd92148e1ca8b3fec9b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tree/heap.jl", "max_issues_repo_name": "hesseltuinhof/DataStructures.jl", "max_issues_repo_head_hexsha": "50c630bfb9b0eb43329bfd92148e1ca8b3fec9b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tree/heap.jl", "max_forks_repo_name": "hesseltuinhof/DataStructures.jl", "max_forks_repo_head_hexsha": "50c630bfb9b0eb43329bfd92148e1ca8b3fec9b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5638297872, "max_line_length": 97, "alphanum_fraction": 0.5642771326, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544448, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.781212517982234}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.14\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\tfaces, N = 1:6, 10^6\n\tmcEstimate = counts(rand(faces,N), faces)/N\nend\n\n# ╔═╡ b93d18b8-2161-11eb-299b-0d801d262dd3\nbegin\n\tplot(faces, mcEstimate, \n\t\tline=:stem, marker=:circle, \n\t\tc=:blue, ms=10, msw=0, lw=4, label=\"MC estimate\")\n\tplot!([i for i in faces], [1/6 for _ in faces], \n\t\tline=:stem, marker=:xcross, c=:red, \n\t\tms=6, msw=0, lw=2, label=\"PMF\", \n\t\txlabel=\"Face number\", ylabel=\"Probability\", ylims=(0,0.22))\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.14\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═b93d18b8-2161-11eb-299b-0d801d262dd3\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "2e153c2e4d19c51eec976f2e89448460423d7d66", "size": 1194, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.14.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.14.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.14.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.4042553191, "max_line_length": 61, "alphanum_fraction": 0.7102177554, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.7812125026572497}}
{"text": "# Whitening\n\n\"\"\"\n    cov_whitening(C)\n\nDerive the whitening transform coefficient matrix `W` given the covariance matrix `C`. Here, `C` can be either a square matrix, or an instance of `Cholesky`.\n\nInternally, this function solves the whitening transform using Cholesky factorization. The rationale is as follows: let ``\\\\mathbf{C} = \\\\mathbf{U}^T \\\\mathbf{U}`` and ``\\\\mathbf{W} = \\\\mathbf{U}^{-1}``, then ``\\\\mathbf{W}^T \\\\mathbf{C} \\\\mathbf{W} = \\\\mathbf{I}``.\n\n**Note:** The return matrix `W` is an upper triangular matrix.\n\"\"\"\nfunction cov_whitening(C::Cholesky{T}) where {T<:Real}\n    cf = C.UL\n    Matrix{T}(inv(istriu(cf) ? cf : cf'))\nend\n\n\"\"\"\n    cov_whitening!(C)\n\nIn-place version of `cov_whitening(C)`, in which the input matrix `C` will be overwritten during computation. This can be more efficient when `C` is no longer used.\n\"\"\"\ncov_whitening!(C::AbstractMatrix{<:Real}) = cov_whitening(cholesky!(Hermitian(C, :U)))\ncov_whitening(C::AbstractMatrix{<:Real}) = cov_whitening!(copy(C))\n\n\"\"\"\n    cov_whitening!(C, regcoef)\n\nIn-place version of `cov_whitening(C, regcoef)`, in which the input matrix `C` will be overwritten during computation. This can be more efficient when `C` is no longer used.\n\"\"\"\ncov_whitening!(C::AbstractMatrix{<:Real}, regcoef::Real) = cov_whitening!(regularize_symmat!(C, regcoef))\n\n\"\"\"\n    cov_whitening(C, regcoef)\n\nDerive a whitening transform based on a regularized covariance, as `C + (eigmax(C) * regcoef) * eye(d)`.\n\"\"\"\ncov_whitening(C::AbstractMatrix{<:Real}, regcoef::Real) = cov_whitening!(copy(C), regcoef)\n\n## Whitening type\n\n\"\"\"\nA whitening transform representation.\n\"\"\"\nstruct Whitening{T<:Real} <: AbstractDataTransform\n    mean::AbstractVector{T}\n    W::AbstractMatrix{T}\n\n    function Whitening{T}(mean::AbstractVector{T}, W::AbstractMatrix{T}) where {T<:Real}\n        d, d2 = size(W)\n        d == d2 || error(\"W must be a square matrix.\")\n        isempty(mean) || length(mean) == d ||\n        throw(DimensionMismatch(\"Sizes of mean and W are inconsistent.\"))\n        return new(mean, W)\n    end\nend\nWhitening(mean::AbstractVector{T}, W::AbstractMatrix{T}) where {T<:Real} = Whitening{T}(mean, W)\n\n\"\"\"\n    length(f)\n\nGet the dimension of the  whitening transform `f`.\n\"\"\"\nlength(f::Whitening) = size(f.W, 1)\n\n\"\"\"\n    size(f)\n\nDimensions of the coefficient matrix of the whitening transform `f`.\n\"\"\"\nsize(f::Whitening) = size(f.W)\n\n\"\"\"\n    mean(f)\n\nGet the mean vector of the whitening transformation `f`.\n\n**Note:** if mean is empty, this function returns a zero vector of `length(f)`.\n\"\"\"\nmean(f::Whitening) = fullmean(length(f), f.mean)\n\n\n\"\"\"\n    transform(f, x)\n\nApply the whitening transform `f` to a vector or a matrix `x` with samples in columns, as ``\\\\mathbf{W}^T (\\\\mathbf{x} - \\\\boldsymbol{\\\\mu})``.\n\"\"\"\nfunction transform(f::Whitening, x::AbstractVecOrMat{<:Real})\n    s = size(x)\n    Z, dims = if length(s) == 1\n        length(f.mean) == s[1] || throw(DimensionMismatch(\"Inconsistent dimensions.\"))\n        x - f.mean, 2\n    else\n        dims = (s[1] == length(f.mean)) + 1\n        length(f.mean) == s[3-dims] || throw(DimensionMismatch(\"Inconsistent dimensions.\"))\n        x .- (dims == 2 ? f.mean : transpose(f.mean)), dims\n    end\n    if dims == 2\n        transpose(f.W) * Z\n    else\n        Z * f.W\n    end\nend\n\n\"\"\"\n    fit(Whitening, X::AbstractMatrix{T}; kwargs...)\n\nEstimate a whitening transform from the data given in `X`.\n\nThis function returns an instance of [`Whitening`](@ref)\n\n**Keyword Arguments:**\n- `regcoef`: The regularization coefficient. The covariance will be regularized as follows when `regcoef` is positive `C + (eigmax(C) * regcoef) * eye(d)`. Default values is `zero(T)`.\n\n- `dims`: if `1` the transformation calculated from the row samples. fit standardization parameters in column-wise fashion;\n  if `2` the transformation calculated from the column samples. The default is `nothing`, which is equivalent to `dims=2` with a deprecation warning.\n\n- `mean`: The mean vector, which can be either of:\n    - `0`: the input data has already been centralized\n    - `nothing`: this function will compute the mean (**default**)\n    - a pre-computed mean vector\n\n**Note:** This function internally relies on [`cov_whitening`](@ref) to derive the transformation `W`.\n\"\"\"\nfunction fit(::Type{Whitening}, X::AbstractMatrix{T};\n             dims::Union{Integer,Nothing}=nothing,\n             mean=nothing, regcoef::Real=zero(T)) where {T<:Real}\n    if dims === nothing\n        Base.depwarn(\"fit(Whitening, x) is deprecated: use fit(Whitening, x, dims=2) instead\", :fit)\n        dims = 2\n    end\n    if dims == 1\n        n = size(X,1)\n        n >= 2 || error(\"X must contain at least two rows.\")\n    elseif dims == 2\n        n = size(X, 2)\n        n >= 2 || error(\"X must contain at least two columns.\")\n    else\n        throw(DomainError(dims, \"fit only accept dims to be 1 or 2.\"))\n    end\n    mv = preprocess_mean(X, mean; dims=dims)\n    Z = centralize((dims==1 ? transpose(X) : X), mv)\n    C = rmul!(Z * transpose(Z), one(T) / (n - 1))\n    return Whitening(mv, cov_whitening!(C, regcoef))\nend\n\n# invsqrtm\n\nfunction _invsqrtm!(C::AbstractMatrix{<:Real})\n    n = size(C, 1)\n    size(C, 2) == n || error(\"C must be a square matrix.\")\n    E = eigen!(Symmetric(C))\n    U = E.vectors\n    evs = E.values\n    for i = 1:n\n        @inbounds evs[i] = 1.0 / sqrt(sqrt(evs[i]))\n    end\n    rmul!(U, Diagonal(evs))\n    return U * transpose(U)\nend\n\n\"\"\"\n    invsqrtm(C)\n\nCompute `inv(sqrtm(C))` through symmetric eigenvalue decomposition.\n\"\"\"\ninvsqrtm(C::AbstractMatrix{<:Real}) = _invsqrtm!(copy(C))\n", "meta": {"hexsha": "06e8d6fdad8faf0701fb2100085db84f6a6f8215", "size": 5569, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/whiten.jl", "max_stars_repo_name": "rkube/MultivariateStats.jl", "max_stars_repo_head_hexsha": "949cd06d4c26e0e0cad005d24110e2226f2b87f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 294, "max_stars_repo_stars_event_min_datetime": "2015-01-30T17:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T23:59:27.000Z", "max_issues_repo_path": "src/whiten.jl", "max_issues_repo_name": "rkube/MultivariateStats.jl", "max_issues_repo_head_hexsha": "949cd06d4c26e0e0cad005d24110e2226f2b87f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 145, "max_issues_repo_issues_event_min_datetime": "2015-01-17T17:09:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T02:59:04.000Z", "max_forks_repo_path": "src/whiten.jl", "max_forks_repo_name": "rkube/MultivariateStats.jl", "max_forks_repo_head_hexsha": "949cd06d4c26e0e0cad005d24110e2226f2b87f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 92, "max_forks_repo_forks_event_min_datetime": "2015-02-19T09:16:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T11:45:23.000Z", "avg_line_length": 33.3473053892, "max_line_length": 265, "alphanum_fraction": 0.6491291076, "num_tokens": 1630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913354875362, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.781202454425112}}
{"text": "\"\"\"\nPaper: Bayesian inference for finite mixtures of univariate and multivariate\n       skew-normal and skew-t distributions, Biostatistics 2010.\nskew (delta): a real number in (-1, 1)\n\"\"\"\nfunction rand_skewnormal(loc, scale, skew)\n    z = rand(TruncatedNormal(0, 1, 0, Inf))\n    return loc + scale * skew * z + scale * sqrt(1 - skew ^ 2) * randn()\nend\n\nfunction rand_skewnormal(loc, scale, skew, dims...)\n    z = rand(TruncatedNormal(0, 1, 0, Inf), dims...)\n    return loc .+ scale * skew * z + scale * sqrt(1 - skew ^ 2) * randn(dims...)\nend\n", "meta": {"hexsha": "de6490644a61d2c462edc52aa73e0ab02ad0cb00", "size": 544, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "runs/sim-study/rand_skewnormal.jl", "max_stars_repo_name": "luiarthur/CytofRepFAM.jl", "max_stars_repo_head_hexsha": "1f997d1620d74861c5bde5559ebdd1e6c449b9e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "runs/sim-study/rand_skewnormal.jl", "max_issues_repo_name": "luiarthur/CytofRepFAM.jl", "max_issues_repo_head_hexsha": "1f997d1620d74861c5bde5559ebdd1e6c449b9e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-02-05T01:26:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-16T04:13:03.000Z", "max_forks_repo_path": "runs/sim-study/rand_skewnormal.jl", "max_forks_repo_name": "luiarthur/CytofRepFAM.jl", "max_forks_repo_head_hexsha": "1f997d1620d74861c5bde5559ebdd1e6c449b9e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2666666667, "max_line_length": 80, "alphanum_fraction": 0.6544117647, "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133548753619, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7812024485282101}}
{"text": "\"\"\"\n`MaternKernel([ρ=1.0,[ν=1.0]])`\nThe matern kernel is an isotropic Mercer kernel given by the formula:\n```\n    κ(x,y) = 2^{1-ν}/Γ(ν)*(√(2ν)‖x-y‖)^ν K_ν(√(2ν)‖x-y‖)\n```\nFor `ν=n+1/2, n=0,1,2,...` it can be simplified and you should instead use [`ExponentialKernel`](@ref) for `n=0`, [`Matern32Kernel`](@ref), for `n=1`, [`Matern52Kernel`](@ref) for `n=2` and [`SqExponentialKernel`](@ref) for `n=∞`.\n\"\"\"\nstruct MaternKernel{Tν<:Real} <: BaseKernel\n    ν::Vector{Tν}\n    function MaternKernel(;nu::T=1.5, ν::T=nu) where {T<:Real}\n        @check_args(MaternKernel, ν, ν > zero(T), \"ν > 0\")\n        return new{T}([ν])\n    end\nend\n\n@inline function kappa(κ::MaternKernel, d::Real)\n    ν = first(κ.ν)\n    iszero(d) ? one(d) :\n    exp(\n        (one(d) - ν) * logtwo - logabsgamma(ν)[1] +\n        ν * log(sqrt(2ν) * d) +\n        log(besselk(ν, sqrt(2ν) * d))\n    )\nend\n\nmetric(::MaternKernel) = Euclidean()\n\n\"\"\"\n`Matern32Kernel([ρ=1.0])`\nThe matern 3/2 kernel is an isotropic Mercer kernel given by the formula:\n```\n    κ(x,y) = (1+√(3)ρ‖x-y‖)exp(-√(3)ρ‖x-y‖)\n```\n\"\"\"\nstruct Matern32Kernel <: BaseKernel end\n\nkappa(κ::Matern32Kernel, d::Real) = (1 + sqrt(3) * d) * exp(-sqrt(3) * d)\n\nmetric(::Matern32Kernel) = Euclidean()\n\n\"\"\"\n`Matern52Kernel([ρ=1.0])`\nThe matern 5/2 kernel is an isotropic Mercer kernel given by the formula:\n```\n    κ(x,y) = (1+√(5)ρ‖x-y‖ + 5ρ²‖x-y‖^2/3)exp(-√(5)ρ‖x-y‖)\n```\n\"\"\"\nstruct Matern52Kernel <: BaseKernel end\n\nkappa(κ::Matern52Kernel, d::Real) = (1 + sqrt(5) * d + 5 * d^2 / 3) * exp(-sqrt(5) * d)\n\nmetric(::Matern52Kernel) = Euclidean()\n", "meta": {"hexsha": "ce9d6ac016db280ce3d8b0305a88d41745ef1e6e", "size": 1563, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/matern.jl", "max_stars_repo_name": "theogf/KernelFunctions.jl", "max_stars_repo_head_hexsha": "d4e8bcb7e66b02b11b8a9eeb2ddbd125795b4ff2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-05-24T15:12:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T07:23:25.000Z", "max_issues_repo_path": "src/kernels/matern.jl", "max_issues_repo_name": "theogf/KernelFunctions.jl", "max_issues_repo_head_hexsha": "d4e8bcb7e66b02b11b8a9eeb2ddbd125795b4ff2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2019-05-24T15:26:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-24T10:39:19.000Z", "max_forks_repo_path": "src/kernels/matern.jl", "max_forks_repo_name": "theogf/KernelFunctions.jl", "max_forks_repo_head_hexsha": "d4e8bcb7e66b02b11b8a9eeb2ddbd125795b4ff2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-05-24T15:13:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T18:33:59.000Z", "avg_line_length": 28.9444444444, "max_line_length": 230, "alphanum_fraction": 0.5847728727, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7812024474305311}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, NLsolve\n\tRandom.seed!(0)\nend;\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.08\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\ta, b, c = 3, 5, 4\n\tdist = TriangularDist(a,b,c)\n\tn = 2000\n\tsamples = rand(dist,n)\nend\n\n# ╔═╡ d91f4766-3a9b-11eb-2892-7b7925b084b2\nbegin\n\tm_k(k,data) = 1/n*sum(data.^k)\n\tmHats = [m_k(i,samples) for i in 1:3]\nend\n\n# ╔═╡ d91f7dd0-3a9b-11eb-313d-81f3bcee7e68\nfunction equations(F, x)\n    F[1] = 1/3*( x[1] + x[2] + x[3] ) - mHats[1]\n    F[2] = 1/6*( x[1]^2 + x[2]^2 + x[3]^2 + x[1]*x[2] + x[1]*x[3] +\n\t\t x[2]*x[3] ) - mHats[2]\n    F[3] = 1/10*( x[1]^3 + x[2]^3 + x[3]^3 + x[1]^2*x[2] + x[1]^2*x[3] +\n\t\t x[2]^2*x[1] + x[2]^2*x[3] + x[3]^2*x[1] + x[3]^2*x[2] +\n\t\t x[1]*x[2]*x[3] ) - mHats[3]\nend\n\n# ╔═╡ d9200de0-3a9b-11eb-2204-db202244e154\nbegin\n\tnlOutput = nlsolve(equations, [ 0.1; 0.1; 0.1])\n\tsol = sort(nlOutput.zero)\n\taHat, bHat, cHat = sol[1], sol[3], sol[2]\n\tText(\"Found estimates for (a,b,c) = $((aHat, bHat, cHat))\")\n\tnlOutput\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.08\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═d91f4766-3a9b-11eb-2892-7b7925b084b2\n# ╠═d91f7dd0-3a9b-11eb-313d-81f3bcee7e68\n# ╠═d9200de0-3a9b-11eb-2204-db202244e154\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "83c08a4dddd19a1fe3929267c8ecd06c7fda15a6", "size": 1669, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/listing5.08.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/05/listing5.08.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/05/listing5.08.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.6769230769, "max_line_length": 72, "alphanum_fraction": 0.6434991013, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7812024454648973}}
{"text": "#=\nThe Fibonacci sequence is defined by the recurrence relation:\n\nFn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.\nHence the first 12 terms will be:\n\nF1 = 1\nF2 = 1\nF3 = 2\nF4 = 3\nF5 = 5\nF6 = 8\nF7 = 13\nF8 = 21\nF9 = 34\nF10 = 55\nF11 = 89\nF12 = 144\nThe 12th term, F12, is the first term to contain three digits.\n\nWhat is the first term in the Fibonacci sequence to contain 1000 digits?\n=#\nfunction calc()\n  a = BigInt[1, 1]\n  while length(\"$(last(a))\") < 1_000\n    a1 = a[length(a)] + a[length(a)-1]\n    push!(a, a1)\n  end\n  length(a)\nend\n@time println(calc())\n", "meta": {"hexsha": "c67b34c72bdbc03c327cac98f573c62b7e12f3f5", "size": 550, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p25.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p25.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p25.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 17.1875, "max_line_length": 72, "alphanum_fraction": 0.6345454545, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9609517061554854, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7811262424885475}}
{"text": "\"\"\"\n    rand_unitary(N, dims=(N,))\n\nGenerate a Haar distributed random unitary operator for a Hilbert space of size `N`. It is possible to specify the subspace dimensions with the `dims` argument. Returns a dense matrix.\n\n# Example\n```jldoctest\njulia> U = rand_unitary(4,(2,2));\n\njulia> U'*U ≈ qeye(4,(2,2))\ntrue\n```\n\"\"\"\nfunction rand_unitary(N::Integer, dims::Dims=(N,))\n    return Operator(rand_unitary(ComplexF64,N),dims)\nend\n\nfunction rand_unitary(::Type{T},n::Integer) where {T<:Compat.LinearAlgebra.BlasComplex}\n    # Generate a Haar distributed random unitary matrix\n    # ref https://arxiv.org/pdf/math-ph/0609050.pdf\n    A = randn(T,n,n)\n    f = qr!(A)\n    U = Matrix(Compat.LinearAlgebra.QRCompactWYQ(f.factors,f.T))\n    @inbounds for i = 1:n\n        U[:,i] .*= sign(f.factors[i,i]) # U = Q*Diagonal(diag(R)./abs.(diag(R)))\n    end\n    return U\nend\n", "meta": {"hexsha": "6d3026f8b140ae66b4f42749ed7bf3a877471e2c", "size": 859, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/library/random.jl", "max_stars_repo_name": "peterse/Schrodinger.jl", "max_stars_repo_head_hexsha": "dfcc66872b801413e5e665853e665fc02321f9da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/library/random.jl", "max_issues_repo_name": "peterse/Schrodinger.jl", "max_issues_repo_head_hexsha": "dfcc66872b801413e5e665853e665fc02321f9da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/library/random.jl", "max_forks_repo_name": "peterse/Schrodinger.jl", "max_forks_repo_head_hexsha": "dfcc66872b801413e5e665853e665fc02321f9da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6206896552, "max_line_length": 184, "alphanum_fraction": 0.6705471478, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092412, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7810796104963581}}
{"text": "\"\"\"\n    evolve!(curr::Field, prev::Field, a, dt)\n\nCalculate a new temperature field curr based on the previous \nfield prev. a is the diffusion constant and dt is the largest \nstable time step.    \n\"\"\"\nfunction evolve!(curr::Field, prev::Field, a, dt)\n    for j = 2:curr.ny+1\n        for i = 2:curr.nx+1\n            xderiv = (prev.data[i-1, j] - 2.0 * prev.data[i, j] + prev.data[i+1, j]) / curr.dx^2\n            yderiv = (prev.data[i, j-1] - 2.0 * prev.data[i, j] + prev.data[i, j+1]) / curr.dy^2\n            curr.data[i, j] = prev.data[i, j] + a * dt * (xderiv + yderiv)\n        end \n    end\nend\n\n\n\n\"\"\"\n    swap_fields!(curr::Field, prev::Field)\n\nSwap the data of two fields curr and prev.    \n\"\"\"    \nfunction swap_fields!(curr::Field, prev::Field)\n    tmp = curr.data\n    curr.data = prev.data\n    prev.data = tmp\nend\n\n\"\"\" \n    average_temperature(f::Field)\n\nCalculate average temperature of a temperature field.        \n\"\"\"\naverage_temperature(f::Field) = sum(f.data[2:f.nx+1, 2:f.ny+1]) / (f.nx * f.ny)\n\n\"\"\"\n    simulate!(current, previous, nsteps)\n\nRun the heat equation solver on fields curr and prev for nsteps.\n\"\"\"\nfunction simulate!(curr::Field, prev::Field, nsteps)\n\n    println(\"Initial average temperature: $(average_temperature(curr))\")\n\n    # Diffusion constant\n    a = 0.5\n    # Largest stable time step\n    dt = curr.dx^2 * curr.dy^2 / (2.0 * a * (curr.dx^2 + curr.dy^2))\n    \n    # display a nice progress bar\n    p = Progress(nsteps)\n\n    for i = 1:nsteps\n        # calculate new state based on previous state\n        evolve!(curr, prev, a, dt)\n\n        # swap current and previous fields\n        swap_fields!(curr, prev)\n\n        # increment the progress bar\n        next!(p)\n    end \n\n    # print final average temperature\n    println(\"Final average temperature: $(average_temperature(curr))\")\nend\n", "meta": {"hexsha": "a02511a2aff37686c9a5c8818256fc241a3183c3", "size": 1819, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/core.jl", "max_stars_repo_name": "wikfeldt/Heatequation.jl", "max_stars_repo_head_hexsha": "c350a1b3dfaa7a3513f7c139a5f8e40f983f1070", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2022-01-18T08:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T07:45:27.000Z", "max_issues_repo_path": "src/core.jl", "max_issues_repo_name": "wikfeldt/Heatequation.jl", "max_issues_repo_head_hexsha": "c350a1b3dfaa7a3513f7c139a5f8e40f983f1070", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2022-01-18T08:13:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T15:14:10.000Z", "max_forks_repo_path": "src/core.jl", "max_forks_repo_name": "wikfeldt/Heatequation.jl", "max_forks_repo_head_hexsha": "c350a1b3dfaa7a3513f7c139a5f8e40f983f1070", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-02-26T14:40:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T12:37:13.000Z", "avg_line_length": 26.3623188406, "max_line_length": 96, "alphanum_fraction": 0.6118746564, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522862, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7810796088648548}}
{"text": "export Sin\n\n\"\"\"\n`Sin([domainType=Float64::Type,] dim_in::Tuple)`\n\nCreates a sinusoid non-linear operator with input dimensions `dim_in`:\n```math\n\\\\sin( \\\\mathbf{x} ).\n```\n\n\"\"\"\nstruct Sin{T,N} <: NonLinearOperator\n\tdim::NTuple{N,Int}\nend\n\nfunction Sin(DomainType::Type, DomainDim::NTuple{N,Int}) where {N} \n\tSin{DomainType,N}(DomainDim)\nend\n\nSin(DomainDim::NTuple{N,Int}) where {N} = Sin{Float64,N}(DomainDim)\nSin(DomainDim::Vararg{Int}) = Sin{Float64,length(DomainDim)}(DomainDim)\n\nfunction mul!(y::AbstractArray{T,N}, L::Sin{T,N}, x::AbstractArray{T,N}) where {T,N}\n\ty .= sin.(x)\nend\n\nfunction mul!(y::AbstractArray, \n              J::AdjointOperator{Jacobian{A,TT}}, \n              b::AbstractArray) where {T,N, A<: Sin{T,N}, TT <: AbstractArray{T,N}}\n    L = J.A\n    y .= conj.(cos.(L.x)).*b\nend\n\nfun_name(L::Sin) = \"sin\"\n\nsize(L::Sin) = (L.dim, L.dim)\n\ndomainType(L::Sin{T,N}) where {T,N} = T\ncodomainType(L::Sin{T,N}) where {T,N} = T\n", "meta": {"hexsha": "3c7962870f776eed1b788c5c653dbc450dd5b298", "size": 939, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nonlinearoperators/Sin.jl", "max_stars_repo_name": "nantonel/AbstractOperators.jl", "max_stars_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2017-08-28T17:28:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-21T18:53:01.000Z", "max_issues_repo_path": "src/nonlinearoperators/Sin.jl", "max_issues_repo_name": "nantonel/AbstractOperators.jl", "max_issues_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2017-11-17T14:43:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-23T20:02:48.000Z", "max_forks_repo_path": "src/nonlinearoperators/Sin.jl", "max_forks_repo_name": "nantonel/AbstractOperators.jl", "max_forks_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-09-02T08:56:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T18:56:33.000Z", "avg_line_length": 23.475, "max_line_length": 84, "alphanum_fraction": 0.6357827476, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666346, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7810796076399916}}
{"text": "function dJv_seriesdk(k2::T,v::Int64) where {T <: Real}\n# Use series expansion to compute J_v:\nnmax = 100\nn = 1; error = Inf; if k2 < 1; tol = eps(k2); else; tol = eps(inv(k2)); end\n# Computing leading coefficient (n=0):\n#coeff = 3pi/(2^(2+v)*factorial(v+2))\nif k2 < 1\n  coeff = .75*pi/exp(lfact(v+2))\n#  println(\"coefficient: \",coeff)\n# multiply by (2v-1)!!\n  for i=1:v\n    coeff *= (2i-1)/2\n  end\n# Add leading term to J_v:\n  Jv = one(k2)*coeff\n  dJvdk = one(k2)*coeff*(2v+1)\n# Now, compute higher order terms until desired precision is reached:\n  while n < nmax && abs(error) > tol\n    coeff *= (2n-1)*(2(n+v)-1)/(2n*(2n+2v+4))*k2\n    Jv += coeff\n    dJvdk += coeff*(2n+2v+1)\n#    error = coeff/Jv\n    error = coeff\n    n += 1\n  end\n  dJvdk *= k2^v\n  Jv *= k2^v*sqrt(k2)\n#  println(\"Jv: \",Jv,\" dJv/dk: \",dJvdk)\n  return Jv,dJvdk\nelse # k^2 >= 1\n  coeff = convert(typeof(k2),pi)\n  # Compute (2v-1)!!/(2^v v!):\n  for i=1:v\n#    coeff *= 1.-.5/i \n    coeff *= (2i-1)/(2i)\n  end\n  Jv = one(k2)*coeff\n  dJvdk = zero(k2)\n  k2inv = inv(k2); n=2\n  while n < nmax && abs(error) > tol\n#    coeff *= (1.-2.5/n)*(1.-.5/(n+v))*k2inv\n    coeff *= (n-5)*(n+2v-1)/(n*(n+2v))\n    coeff *= k2inv\n    Jv += coeff\n    dJvdk -= n*coeff\n#    error = coeff/Jv\n    error = coeff\n    n += 2\n  end\n  dJvdk /= sqrt(k2)\n  return Jv,dJvdk\nend\nend\n", "meta": {"hexsha": "4487a972d2127d7933438207d3cbed7fe0fca9ad", "size": 1321, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/deprecated/dJv_seriesdk.jl", "max_stars_repo_name": "tagordon/limbdark", "max_stars_repo_head_hexsha": "275ba17a767c585461515ea0d25dd9546032f3b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2019-05-08T09:03:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-14T20:53:23.000Z", "max_issues_repo_path": "src/deprecated/dJv_seriesdk.jl", "max_issues_repo_name": "tagordon/limbdark", "max_issues_repo_head_hexsha": "275ba17a767c585461515ea0d25dd9546032f3b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 75, "max_issues_repo_issues_event_min_datetime": "2018-04-23T20:41:25.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-02T01:50:19.000Z", "max_forks_repo_path": "src/deprecated/dJv_seriesdk.jl", "max_forks_repo_name": "tagordon/limbdark", "max_forks_repo_head_hexsha": "275ba17a767c585461515ea0d25dd9546032f3b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-05-15T08:06:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-24T19:11:47.000Z", "avg_line_length": 24.462962963, "max_line_length": 75, "alphanum_fraction": 0.558667676, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810407096791, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7810795978361423}}
{"text": "# ---\n# title: 354. Russian Doll Envelopes\n# id: problem354\n# author: Indigo\n# date: 2021-03-04\n# difficulty: Hard\n# categories: Binary Search, Dynamic Programming\n# link: <https://leetcode.com/problems/russian-doll-envelopes/description/>\n# hidden: true\n# ---\n# \n# You have a number of envelopes with widths and heights given as a pair of\n# integers `(w, h)`. One envelope can fit into another if and only if both the\n# width and height of one envelope is greater than the width and height of the\n# other envelope.\n# \n# What is the maximum number of envelopes can you Russian doll? (put one inside\n# other)\n# \n# **Note:**  \n# Rotation is not allowed.\n# \n# **Example:**\n# \n#     \n#     \n#     Input: [[5,4],[6,4],[6,7],[2,3]]\n#     Output: 3 \n#     **Explanation: T** he maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).\n#     \n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction max_envelopes(envelopes::Vector{Vector{Int}})\n    isempty(envelopes) && return 0\n    sort!(envelopes, by = x -> (x[1], -x[2]))\n    dp = [envelopes[1][2]]\n    for envo in @view(envelopes[2:end])\n        if envo[2] > dp[end]\n            push!(dp, envo[2])\n        else\n            dp[searchsortedfirst(dp, envo[2])] = envo[2]\n        end\n    end\n    length(dp)\nend\n## @lc code=end\n", "meta": {"hexsha": "aeb71aa0c2c1b00bdc23b126b254b85eca0fe000", "size": 1287, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/354.russian-doll-envelopes.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/354.russian-doll-envelopes.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/354.russian-doll-envelopes.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 25.74, "max_line_length": 108, "alphanum_fraction": 0.6169386169, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7810676908424382}}
{"text": "#=\n# 2. Potential flow with an impenetrable surface\n\nThis part introduces the treatment of rigid impenetrable surfaces in `GridPotentialFlow`. We can impose the no-penetration constraint by setting the fluid streamfunction equal to that of the surface $\\mathfrak{s}_b$, up to a uniform value $s_0$. The discrete no-penetration constraint is thus\n\n$\\mathsf{Es}=\\mathfrak{s}_{b}-\\mathsf{E} \\mathsf{s}_{\\infty}-\\mathfrak{s}_{0},$\n\nwhere $\\mathsf{E}$ is the interpolation operator that interpolates grid data to the surface points, $\\mathsf{s}_{\\infty}$ is the streamfunction of the uniform flow. For a body translating at velocity $(U,V)$ and rotating at angular velocity $\\Omega$, this streamfunction would be\n\n$\\mathfrak{s}_{b,k} = U \\mathfrak{r}_y - V \\mathfrak{r}_x - \\frac{1}{2} \\Omega (\\mathfrak{r}_x^2+\\mathfrak{r}_y^2).$\n\nFor later shorthand, we will denote the difference between the body motion streamfunction and interpolated uniform flow streamfunction by $\\mathfrak{s}'_b \\equiv \\mathfrak{s}_b - \\mathsf{E} \\mathsf{s}_{\\infty}$. The no-penetration constraint is enforced in the basic potential flow problem with the help of a vector of Lagrange multipliers, $\\mathfrak{f}$, on the surface points. The modified potential flow problem is thus\n\n$\\mathsf{Ls} + \\mathsf{R}\\mathfrak{f} = -\\mathsf{w},$\n\nwhere $\\mathsf{R}$ is the regularization operator that transfers data from surface data to nodes. $\\mathsf{E}$ can be constructed (and we will assume it has) so that it is the transpose of the interpolation operator, $\\mathsf{E} = \\mathsf{R}^{T}$.\n\nFrom the previous equation, it is clear (by simple comparison with the vorticity on the right-hand side) that the vector $\\mathfrak{f}$ represents the strength of the discrete bound vortex sheet on the surface. Suppose we consider the bound vortex sheet $\\gamma(s)$ that emerges from the analogous continuous problem on the undiscretized surface, where $s$ is the arc-length parameter along the surface. At each point $p$, the discrete solution $\\mathfrak{f}$ is approximately equal to this continuous solution, multiplied by the length $\\delta S_p$ of the small segment surrounding the point:\n\n$\\mathfrak{e}_{p}^{T} \\mathfrak{f} \\approx \\gamma(s) \\delta S_p.$\n\nThus, the potential flow problem in the presence of the impenetrable surface is\n\n$\\begin{bmatrix}\n\\mathsf{L} & \\mathsf{R} \\\\\n\\mathsf{E} &  0\n\\end{bmatrix} \\begin{pmatrix} \\mathsf{s} \\\\ \\mathfrak{f} \\end{pmatrix} =\n\\begin{pmatrix} -\\mathsf{w} \\\\ \\mathfrak{s}'_b - \\mathfrak{s}_0 \\end{pmatrix}.$\n\nThis problem has the structure of a generic saddle-point problem. `GridPotentialFlow.jl` automatically formulates the no-penetration constraint on the streamfunction and solves the saddle system when it needs to. See the next page for the role of $\\mathfrak{s}_0$ and how it will be treated internally.\n=#\n\n# We will now consider two examples. In these examples, we use the following grid.\n#md # ```@setup 2.-Potential-flow-with-an-impenetrable-surface\n#md # using GridPotentialFlow\n#md # using Plots\n#md # ```\n#!md using GridPotentialFlow\n#!md using Plots\nΔx = 0.02\nLx = 4.0\nxlim = (-Lx/2,Lx/2)\nylim = (-Lx/2,Lx/2)\ng = PhysicalGrid(xlim,ylim,Δx);\n\n#=\n## Vortex near a cylinder\n\nAs a basic example, consider now a point vortex near a circular cylinder.\n=#\n\n# A body in `GridPotentialFlow.jl` is represented by `PotentialFlowBody`. This is a wrapper around a `Body` from `RigidBodyTools.jl` and can be endowed with a linear velocity, rotational velocity, circulation, and other properties using the appropriate keywords during construction or by mutating its fields using its setter methods. For our circular cylinder, we use the `Circle` shape.\nRc = Lx/4\nΔs = 2Δx\nbody = PotentialFlowBody(Circle(Rc,Δs))\n\n# We choose an initial position $R_v$ of the vortex at $3/2 R_c$ from the origin.\nRv = 3/2*Rc\nΓv = 1.0\nv = Vortex(Rv,0.0,Γv);\n\n# And we set an equal and opposite circulation about the body\nsetΓ(body,-Γv)\n\n# We construct the `VortexModel` by using the optional `bodies` keyword. In this case, we are interested in the bound vortex sheet strength $\\mathfrak{f}$, instead of just the streamfunction field. For this reason, we use `solve`, which in this case returns a `ConstrainedIBPoissonSolution`.\nmodel = VortexModel(g,vortices=[v],bodies=[body]);\nsol = solve(model);\n\n#md # ```@setup 2.-Potential-flow-with-an-impenetrable-surface\n#md # # Analytical solution (vortex at Rv and image vortex at Rc^2/Rv)\n#md # r1 = sqrt.((body.points.x.-Rv).^2 .+ (body.points.y).^2) # distance from vortex to points on circle\n#md # r2 = sqrt.((body.points.x.-Rc^2/Rv).^2 .+ (body.points.y).^2) # distance from image vortex to points on circle\n#md # θ1 = π.+atan.((body.points.y)./(body.points.x.-Rv)) # angle from vortex to points on circle\n#md # θ2 = atan.((body.points.y),(body.points.x.-Rc^2/Rv)) # angle from image vortex to points on circle\n#md # v1x = -v.Γ./(2π*r1).*cos.(θ1.-π/2) # x velocity on circle induced by vortex\n#md # v1y = -v.Γ./(2π*r1).*sin.(θ1.-π/2) # y velocity on circle induced by vortex\n#md # v2x = v.Γ./(2π*r2).*cos.(θ2.-π/2) # x velocity on circle induced by image vortex\n#md # v2y = v.Γ./(2π*r2).*sin.(θ2.-π/2) # y velocity on circle induced by image vortex\n#md # V = sqrt.((v1x.+v2x).^2+(v1y.+v2y).^2) # velocity magnitude on circle\n#md # γ = -V; # bound vortex sheet strength on circle (velocity on circle is clockwise if positive vortex is to the right of it)\n#md # ```\n\n#!md # Analytical solution (vortex at Rv and image vortex at Rc^2/Rv)\n#!md r1 = sqrt.((body.points.x.-Rv).^2 .+ (body.points.y).^2) # distance from vortex to points on circle\n#!md r2 = sqrt.((body.points.x.-Rc^2/Rv).^2 .+ (body.points.y).^2) # distance from image vortex to points on circle\n#!md θ1 = π.+atan.((body.points.y)./(body.points.x.-Rv)) # angle from vortex to points on circle\n#!md θ2 = atan.((body.points.y),(body.points.x.-Rc^2/Rv)) # angle from image vortex to points on circle\n#!md v1x = -v.Γ./(2π*r1).*cos.(θ1.-π/2) # x velocity on circle induced by vortex\n#!md v1y = -v.Γ./(2π*r1).*sin.(θ1.-π/2) # y velocity on circle induced by vortex\n#!md v2x = v.Γ./(2π*r2).*cos.(θ2.-π/2) # x velocity on circle induced by image vortex\n#!md v2y = v.Γ./(2π*r2).*sin.(θ2.-π/2) # y velocity on circle induced by image vortex\n#!md V = sqrt.((v1x.+v2x).^2+(v1y.+v2y).^2) # velocity magnitude on circle\n#!md γ = -V; # bound vortex sheet strength on circle (velocity on circle is clockwise if positive vortex is to the right of it)\n\n# We can then easily retrieve the streamfunction and the bound vortex sheet strength from the fields of the solution variable.\nplot(sol.ψ,g)\nplot!(body,fillcolor=:black,fillrange=0,fillalpha=0.25,linecolor=:black,linewidth=2)\nscatter!([v.x],[v.y],color=:black,markersize=2,xlabel=\"x\",ylabel=\"y\")\n\n# For this example, we can easily calculate the analytical bound vortex sheet strength $\\gamma$ and compare it with our numerical solution $f$.\n#md # See the notebook in the examples folder for the analytical solution.\nplot(sol.f./Δs,label=\"f/ds\",xlabel=\"body point index\")\nplot!(γ,label=\"gamma\")\n\n# Finally, we can also check if the vortex will move around the cylinder on a circular path if we advance the system in time, as predicted by analytical potential flow theory. The period of the circular motion can be easily determined by calculating the velocity induced by the image vortex at $R_c^2/R_v$:\n\nVv = Γv/(2π*(Rv-Rc^2/Rv))\nT = 2π*Rv/Vv\n\n# For the time stepping, we again use the fourth-order Runge Kutta scheme from `OrdinaryDiffEq.jl`.\nimport OrdinaryDiffEq\nfunction rhs(X,model,t)\n    setvortexpositions!(model,X)\n    Ẋ = vortexvelocities!(model)\n    return Ẋ\nend\nX = getvortexpositions(model)\nprob = OrdinaryDiffEq.ODEProblem(rhs,X,(0.0,T),model);\nsol = OrdinaryDiffEq.solve(prob,dt=0.1,OrdinaryDiffEq.RK4(),dense=false,adaptive=false);\nplot(body,fillcolor=:black,fillrange=0,fillalpha=0.25,linecolor=:black,linewidth=2)\nplot!(map(s->s.u[1],sol.u),map(s->s.v[1],sol.u))\nscatter!([v.x],[v.y],color=:black,markersize=2,xlabel=\"x\",ylabel=\"y\")\n\n\n#jl @testset \"Vortex near cylinder\" begin\n#jl     import OrdinaryDiffEq\n#jl\n#jl     # analytical solution\n#jl     Rv = sqrt(v.x^2+v.y^2)\n#jl     Vθ = -v.Γ/(2π*(Rv-Rc^2/Rv))\n#jl     Tv = 2π*Rv/abs(Vθ)\n#jl\n#jl     # numerical solution\n#jl     tspan = (0,Tv)\n#jl     model = VortexModel(g,bodies=[body],vortices=[v])\n#jl\n#jl     function rhs(X,model,t)\n#jl         setvortexpositions!(model,X)\n#jl         Ẋ = vortexvelocities!(model)\n#jl         return Ẋ\n#jl     end\n#jl\n#jl     X = getvortexpositions(model)\n#jl     prob = OrdinaryDiffEq.ODEProblem(rhs,X,tspan,model);\n#jl     sol = OrdinaryDiffEq.solve(prob,dt=0.1,OrdinaryDiffEq.RK4(),dense=false,adaptive=false);\n#jl\n#jl     @test isapprox(sol.u[end].u[1], 1.5; atol = 1e-2)\n#jl     @test isapprox(sol.u[end].v[1], 0.0; atol = 1e-1)\n#jl end\n\n#=\n## Moving cylinder\n\nIn this example we will create a model with a moving body.\n=#\n\n# Here we use the keyword `U` to add create a body with a linear velocity.\nbody = PotentialFlowBody(Circle(Rc,Δs), U=(1.0,0.0))\nmodel = VortexModel(g,bodies=[body]);\nsol = solve(model);\n\n#md # ```@setup 2.-Potential-flow-with-an-impenetrable-surface\n#md # # Analytical solution\n#md # θ = atan.(body.points.y,body.points.x)\n#md # γ = 2*sin.(θ);\n#md # ```\n\n#!md # # Analytical solution\n#!md θ = atan.(body.points.y,body.points.x)\n#!md γ = 2*sin.(θ);\n\nplot(sol.ψ,g)\nplot!(body,fillcolor=:black,fillrange=0,fillalpha=0.25,linecolor=:black,linewidth=2,xlabel=\"x\",ylabel=\"y\")\n\n# Again, we can compare the discrete bound vortex sheet strength with the analytical vortex sheet strength.\nplot(sol.f./Δs,label=\"f/ds\",xlabel=\"body point index\")\nplot!(γ,label=\"gamma\")\n", "meta": {"hexsha": "33a83c02ee1493f18522302b94a6dde0025a2bcf", "size": 9623, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/literate/2.-Potential-flow-with-an-impenetrable-surface.jl", "max_stars_repo_name": "JuliaIBPM/GridPotentialFlow.jl", "max_stars_repo_head_hexsha": "b24127d036ed54a588a11ebedb35544acb8dea53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:10:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T22:51:52.000Z", "max_issues_repo_path": "test/literate/2.-Potential-flow-with-an-impenetrable-surface.jl", "max_issues_repo_name": "JuliaIBPM/GridPotentialFlow.jl", "max_issues_repo_head_hexsha": "b24127d036ed54a588a11ebedb35544acb8dea53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-04-01T20:39:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-15T17:46:44.000Z", "max_forks_repo_path": "test/literate/2.-Potential-flow-with-an-impenetrable-surface.jl", "max_forks_repo_name": "JuliaIBPM/GridPotentialFlow.jl", "max_forks_repo_head_hexsha": "b24127d036ed54a588a11ebedb35544acb8dea53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.0617977528, "max_line_length": 593, "alphanum_fraction": 0.7123558142, "num_tokens": 2993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.863391617003942, "lm_q1q2_score": 0.7810676905437488}}
{"text": "import RowEchelon\n\n#=\nHomework 2\nSection 1.3\nProblem 13\n=#\n\nprintln()\n\n# Create the Matrix to be evaluated\nA = [1 -4 2 3 ;\n     0 3 5 -7 ;\n    -2 8 -4 -3]\n\n# Store the number of columns\ncolumns = 4\n\n# Print the original Matrix\nprintln(\"Original Matrix:\")\nprintln(A)\nprintln()\n\n# Row reduce the Matrix\nA_rref = RowEchelon.rref(A)\n\n# Print the RREF'd matrix\nprintln(\"Row Reduced Echelon Form:\")\nprintln(A_rref)\nprintln()\n\n# Determine whether or not matrix was consistent\nindex = 0\nleadingEntryLocated = false\nconsistent = true\nfor value in A_rref\n    global index\n    global columns\n    global leadingEntryLocated\n    global consistent\n\n    # Determine first if we are in the 0 column of a Row\n    if index % columns == 0\n        # If here then:\n        # We are in the 0 columns\n        # Reset Leading Entry Locator\n        leadingEntryLocated = false\n    end\n    # Now we can save time by skipping the rest of the Row\n    # If a leading entry has already been found\n    if leadingEntryLocated == false\n        # If here then:\n        # Leading entry hasnt been found yet\n        # Evaluate the current position\n        # Determine if its a leading entry\n        if value != 0\n            # If here then:\n            # This row has a leading entry somewhere\n            if index % columns == (columns - 1)\n                # If here then:\n                # This entry is in the last column\n                # Matrix is not consistent\n                consistent = false\n            else\n                # Else:\n                # The matrix hasnt been proven inconsistent\n                leadingEntryLocated = true\n            end\n        end\n    end\n    index = index+1\nend\n\nif consistent == true\n    # If here then:\n    # Matrix is consistent\n    println(\"This matrix is consistent.\")\n    print(\"Hence the vector b is a linear combination of the \")\n    print(\"vectors made by the columns of the original matrix.\")\nelse\n    # Else:\n    # Matrix is inconsistent\n    println(\"This matrix is inconsistent.\")\n    print(\"Hence the vector b is NOT a linear combination of the \")\n    print(\"vectors made by the columns of the original matrix.\")\nend\n\n# Print two blanks lines for a better display\nprintln()\nprintln()\nexit(0)\n", "meta": {"hexsha": "117f725fb3896ed9399cd37bb456aa4d330e6b65", "size": 2214, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HW2_S1.3_P13.jl", "max_stars_repo_name": "tleecsm/J4LA", "max_stars_repo_head_hexsha": "0ff51fa1771e9b5fc0b8a684a65cb36cebb8eefb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW2_S1.3_P13.jl", "max_issues_repo_name": "tleecsm/J4LA", "max_issues_repo_head_hexsha": "0ff51fa1771e9b5fc0b8a684a65cb36cebb8eefb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW2_S1.3_P13.jl", "max_forks_repo_name": "tleecsm/J4LA", "max_forks_repo_head_hexsha": "0ff51fa1771e9b5fc0b8a684a65cb36cebb8eefb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0652173913, "max_line_length": 67, "alphanum_fraction": 0.6269196025, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129515, "lm_q2_score": 0.8633916117313211, "lm_q1q2_score": 0.7810676902128887}}
{"text": "cd(@__DIR__)\nusing Pkg; Pkg.activate(\".\"); Pkg.instantiate()\n\n#This script simulates the Fisher-KPP equation and fits\n#a neural PDE to the data with the growth (aka reaction) term replaced\n#by a feed-forward neural network and the diffusion term with a CNN\n\nusing PyPlot, Printf\nusing LinearAlgebra\nusing Flux, DiffEqFlux, Optim, DiffEqSensitivity\nusing BSON: @save, @load\nusing Flux: @epochs\nusing OrdinaryDiffEq\n\n#parameter\nD = 0.01; #diffusion\nr = 1.0; #reaction rate\n\n#domain\nX = 1.0; T = 5;\ndx = 0.04; dt = T/10;\nx = collect(0:dx:X);\nt = collect(0:dt:T);\nNx = Int64(X/dx+1);\nNt = Int64(T/dt+1);\n\n#initial conditions\nAmp = 1.0;\nDelta = 0.2\n#IC-1\nrho0 = Amp*(tanh.((x .- (0.5 - Delta/2))/(Delta/10)) - tanh.((x .- (0.5 + Delta/2))/(Delta/10)))/2\n#IC-2\n#rho0 = Amp*(1 .- tanh.((x .- 0.2)/(Delta/6)))/2.\n\nsave_folder = \"data\"\n\nif isdir(save_folder)\n    rm(save_folder, recursive=true)\nend\nmkdir(save_folder)\n\nclose(\"all\")\nfigure()\nplot(x, rho0)\ntitle(\"Initial Condition\")\ngcf()\n\n########################\n# Generate training data\n########################\nreaction(u) = r * u .* (1 .- u)\nlap = diagm(0 => -2.0 * ones(Nx), 1=> ones(Nx-1), -1 => ones(Nx-1)) ./ dx^2\n#Periodic BC\nlap[1,end] = 1.0/dx^2\nlap[end,1] = 1.0/dx^2\n#Neumann BC\n#lap[1,2] = 2.0/dx^2\n#lap[end,end-1] = 2.0/dx^2\n\nfunction rc_ode(rho, p, t)\n    #finite difference\n    D * lap * rho + reaction.(rho)\nend\n\nprob = ODEProblem(rc_ode, rho0, (0.0, T), saveat=dt)\nsol = solve(prob, Tsit5());\node_data = Array(sol);\n\nfigure(figsize=(8,3))\n\nsubplot(121)\npcolor(x,t,ode_data')\nxlabel(\"x\"); ylabel(\"t\");\ncolorbar()\n\nsubplot(122)\nfor i in 1:2:Nt\n    plot(x, ode_data[:,i], label=\"t=$(sol.t[i])\")\nend\nxlabel(\"x\"); ylabel(L\"$\\rho$\")\nlegend(frameon=false, fontsize=7, bbox_to_anchor=(1, 1), loc=\"upper left\", ncol=1)\ntight_layout()\nsavefig(@sprintf(\"%s/training_data.pdf\", save_folder))\ngcf()\n\n########################\n# Define the neural PDE\n########################\nn_weights = 10\n\n#for the reaction term\nrx_nn = Chain(Dense(1, n_weights, tanh),\n                Dense(n_weights, 2*n_weights, tanh),\n                Dense(2*n_weights, n_weights, tanh),\n                Dense(n_weights, 1),\n                x -> x[1])\n\n#conv with bias with initial values as 1/dx^2\nw_err = 0.0\ninit_w = reshape([1.1 -2.5 1.0], (3, 1, 1, 1))\ndiff_cnn_ = Conv(init_w, [0.], pad=(0,0,0,0))\n\n#initialize D0 close to D/dx^2\nD0 = [6.5]\n\np1,re1 = Flux.destructure(rx_nn)\np2,re2 = Flux.destructure(diff_cnn_)\np = [p1;p2;D0]\nfull_restructure(p) = re1(p[1:length(p1)]), re2(p[(length(p1)+1):end-1]), p[end]\n\nfunction nn_ode(u,p,t)\n    rx_nn = re1(p[1:length(p1)])\n\n    u_cnn_1   = [p[end-4] * u[end] + p[end-3] * u[1] + p[end-2] * u[2]]\n    u_cnn     = [p[end-4] * u[i-1] + p[end-3] * u[i] + p[end-2] * u[i+1] for i in 2:Nx-1]\n    u_cnn_end = [p[end-4] * u[end-1] + p[end-3] * u[end] + p[end-2] * u[1]]\n\n    # Equivalent using Flux, but slower!\n    #CNN term with periodic BC\n    #diff_cnn_ = Conv(reshape(p[(end-4):(end-2)],(3,1,1,1)), [0.0], pad=(0,0,0,0))\n    #u_cnn = reshape(diff_cnn_(reshape(u, (Nx, 1, 1, 1))), (Nx-2,))\n    #u_cnn_1 = reshape(diff_cnn_(reshape(vcat(u[end:end], u[1:1], u[2:2]), (3, 1, 1, 1))), (1,))\n    #u_cnn_end = reshape(diff_cnn_(reshape(vcat(u[end-1:end-1], u[end:end], u[1:1]), (3, 1, 1, 1))), (1,))\n\n    [rx_nn([u[i]])[1] for i in 1:Nx] + p[end] * vcat(u_cnn_1, u_cnn, u_cnn_end)\nend\n\n########################\n# Soving the neural PDE and setting up loss function\n########################\nprob_nn = ODEProblem(nn_ode, rho0, (0.0, T), p)\nsol_nn = concrete_solve(prob_nn,Tsit5(), rho0, p)\n\nfunction predict_rd(θ)\n  # No ReverseDiff if using Flux\n  Array(concrete_solve(prob_nn,Tsit5(),rho0,θ,saveat=dt,sensealg=InterpolatingAdjoint(autojacvec=ReverseDiffVJP())))\nend\n\n#match data and force the weights of the CNN to add up to zero\nfunction loss_rd(p)\n    pred = predict_rd(p)\n    sum(abs2, ode_data .- pred) + 10^2 * abs(sum(p[end-4 : end-2])), pred\nend\n\n########################\n# Training\n########################\n\n#Optimizer\nopt = ADAM(0.001)\n\nglobal count = 0\nglobal save_count = 0\nsave_freq = 50\n\ntrain_arr = Float64[]\ndiff_arr = Float64[]\nw1_arr = Float64[]\nw2_arr = Float64[]\nw3_arr = Float64[]\n\n#callback function to observe training\ncb = function (p,l,pred)\n    rx_nn, diff_cnn_, D0 = full_restructure(p)\n    push!(train_arr, l)\n    push!(diff_arr, p[end])\n\n    weight = diff_cnn_.weight[:]\n    push!(w1_arr, weight[1])\n    push!(w2_arr, weight[2])\n    push!(w3_arr, weight[3])\n\n    println(@sprintf(\"Loss: %0.4f\\tD0: %0.4f Weights:(%0.4f,\\t %0.4f, \\t%0.4f) \\t Sum: %0.4f\"\n            ,l, D0[1], weight[1], weight[2], weight[3], sum(weight)))\n\n    global count\n\n    if count==0\n        fig = figure(figsize=(8,2.5));\n        ttl = fig.suptitle(@sprintf(\"Epoch = %d\", count), y=1.05)\n        global ttl\n        subplot(131)\n        pcolormesh(x,t,ode_data')\n        xlabel(L\"$x$\"); ylabel(L\"$t$\"); title(\"Data\")\n        colorbar()\n\n        subplot(132)\n        img = pcolormesh(x,t,pred')\n        global img\n        xlabel(L\"$x$\"); ylabel(L\"$t$\"); title(\"Prediction\")\n        colorbar(); clim([0, 1]);\n\n        ax = subplot(133); global ax\n        u = collect(0:0.01:1)\n        rx_line = plot(u, rx_nn.([[elem] for elem in u]), label=\"NN\")[1];\n        global rx_line\n        plot(u, reaction.(u), label=\"True\")\n        title(\"Reaction Term\")\n        legend(loc=\"upper right\", frameon=false, fontsize=8);\n        ylim([0, r*0.25+0.2])\n\n        subplots_adjust(top=0.8)\n        tight_layout()\n    end\n\n    if count>0\n        println(\"updating figure\")\n        img.set_array(pred[1:end-1, 1:end-1][:])\n        ttl.set_text(@sprintf(\"Epoch = %d\", count))\n\n        u = collect(0:0.01:1)\n        rx_pred = rx_nn.([[elem] for elem in u])\n        rx_line.set_ydata(rx_pred)\n        u = collect(0:0.01:1)\n\n        min_lim = min(minimum(rx_pred), minimum(reaction.(u)))-0.1\n        max_lim = max(maximum(rx_pred), maximum(reaction.(u)))+0.1\n\n        ax.set_ylim([min_lim, max_lim])\n    end\n\n    global save_count\n    if count%save_freq == 0\n        println(\"saved figure\")\n        savefig(@sprintf(\"%s/pred_%05d.png\", save_folder, save_count), dpi=200, bbox_inches=\"tight\")\n        save_count += 1\n    end\n\n    display(gcf())\n    count += 1\n\n    false\nend\n\n#train\nres1 = DiffEqFlux.sciml_train(loss_rd, p, ADAM(0.001), cb=cb, maxiters = 100)\nres2 = DiffEqFlux.sciml_train(loss_rd, res1.minimizer, ADAM(0.001), cb=cb, maxiters = 300)\nres3 = DiffEqFlux.sciml_train(loss_rd, res2.minimizer, BFGS(), cb=cb, maxiters = 1000)\n\npstar = res3.minimizer\n\n## Save trained model\n@save @sprintf(\"%s/model.bson\", save_folder) pstar\n\n########################\n# Plot for paper\n########################\n@load @sprintf(\"%s/model.bson\", save_folder) pstar\n#re-defintions for newly loaded data\n\ndiff_cnn_ = Conv(reshape(pstar[(end-4):(end-2)],(3,1,1,1)), [0.0], pad=(0,0,0,0))\ndiff_cnn(x) = diff_cnn_(x) .- diff_cnn_.bias\nD0 = res3.minimizer[end]\n\nfig = figure(figsize=(4,4))\n\nrcParams = PyPlot.PyDict(PyPlot.matplotlib.\"rcParams\")\nrcParams[\"font.size\"] = 10\nrcParams[\"text.usetex\"] = true\nrcParams[\"font.family\"] = \"serif\"\nrcParams[\"font.sans-serif\"] = \"Helvetica\"\nrcParams[\"axes.titlesize\"] = 10\n\nsubplot(221)\npcolormesh(x,t,ode_data', rasterized=true)\nxlabel(L\"$x$\"); ylabel(L\"$t$\"); title(\"Data\")\nyticks([0, 1, 2, 3, 4, 5])\n\nax = subplot(222)\ncur_pred = predict_rd(pstar)[1]\nimg = pcolormesh(x,t,cur_pred', rasterized=true)\nglobal img\nxlabel(L\"$x$\"); ylabel(L\"$t$\"); title(\"Prediction\")\nyticks([0, 1, 2, 3, 4, 5])\ncax = fig.add_axes([.48,.62,.02,.29])\ncolb = fig.colorbar(img, cax=cax)\ncolb.ax.set_title(L\"$\\rho$\")\nclim([0, 1]);\ncolb.set_ticks([0, 1])\n\nsubplot(223)\nplot(Flux.data(w1_arr ./ w3_arr) .- 1, label=L\"$w_1/w_3 - 1$\")\nplot(Flux.data(w1_arr .+ w2_arr .+ w3_arr), label=L\"$w_1 + w_2 + w_3$\")\naxhline(0.0, linestyle=\"--\", color=\"k\")\nxlabel(\"Epochs\"); title(\"CNN Weights\")\nxticks([0, 1500, 3000]); yticks([-0.4, -0.3,-0.2, -0.1, 0.0, 0.1])\nlegend(loc=\"lower right\", frameon=false, fontsize=6)\n\nsubplot(224)\nu = collect(0:0.01:1)\nplot(u, rx_nn.([[elem] for elem in u]), label=\"UPDE\")[1];\nplot(u, reaction.(u), linestyle=\"--\", label=\"True\")\nxlabel(L\"$\\rho$\")\ntitle(\"Reaction Term\")\nlegend(loc=\"lower center\", frameon=false, fontsize=6);\nylim([0, 0.3])\n\ntight_layout(h_pad=1)\ngcf()\nsavefig(@sprintf(\"%s/fisher_kpp.pdf\", save_folder))\n\n#plot loss vs epochs and save\nfigure(figsize=(6,3))\nplot(log.(train_arr), \"k.\", markersize=1)\nxlabel(\"Epochs\"); ylabel(\"Log(loss)\")\ntight_layout()\nsavefig(@sprintf(\"%s/loss_vs_epoch.pdf\", save_folder))\ngcf()\n", "meta": {"hexsha": "4e789ce040ff4251e2af81908ce44853542cab16", "size": 8483, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "FisherKPP/Fisher-KPP-CNN.jl", "max_stars_repo_name": "AlCap23/universal_differential_equations-1", "max_stars_repo_head_hexsha": "b85d9217ed75e8927c015598105063f2e1eb3b0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 173, "max_stars_repo_stars_event_min_datetime": "2020-01-15T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:23:25.000Z", "max_issues_repo_path": "FisherKPP/Fisher-KPP-CNN.jl", "max_issues_repo_name": "AlCap23/universal_differential_equations-1", "max_issues_repo_head_hexsha": "b85d9217ed75e8927c015598105063f2e1eb3b0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-01-28T02:37:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T05:47:26.000Z", "max_forks_repo_path": "FisherKPP/Fisher-KPP-CNN.jl", "max_forks_repo_name": "AlCap23/universal_differential_equations-1", "max_forks_repo_head_hexsha": "b85d9217ed75e8927c015598105063f2e1eb3b0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2020-01-21T08:13:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:43:29.000Z", "avg_line_length": 27.4530744337, "max_line_length": 116, "alphanum_fraction": 0.6037958269, "num_tokens": 3017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7810676775253805}}
{"text": "\"\"\"\r\n    komptrap(f,a,b,M)\r\nadalah fungsi yang digunakan untuk menghitung nilai integral `f` secara numerik\r\npada interval `[a,b]` menggunakan komposit trapesium dengan `M` sub-interval.\r\n\r\n# Example\r\n```jl\r\njulia> a = 1; b = 6;\r\n\r\njulia> f(x) = 2+sin(2*sqrt(x));\r\n\r\njulia> y = komptrap(f,a,b,10)\r\n8.193854565172531\r\n```\r\nreturn solusi `y`\r\n\"\"\"\r\nfunction komptrap(f,a,b,M)\r\n  h = (b-a)/M;\r\n  s = 0;\r\n  for k = 1:M-1\r\n    x = a+k*h;\r\n    s = s+f(x);\r\n  end\r\n  y = h/2*(f(a)+f(b)+2*s)\r\nend\r\n", "meta": {"hexsha": "6a4fa2a5135d3c3770d1a022dec863ba4f227e53", "size": 489, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/komptrap.jl", "max_stars_repo_name": "mkhoirun-najiboi/metnum.jl", "max_stars_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/komptrap.jl", "max_issues_repo_name": "mkhoirun-najiboi/metnum.jl", "max_issues_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/komptrap.jl", "max_forks_repo_name": "mkhoirun-najiboi/metnum.jl", "max_forks_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8076923077, "max_line_length": 80, "alphanum_fraction": 0.5685071575, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.8633916047011594, "lm_q1q2_score": 0.781067672755501}}
{"text": "mutable struct PWGrid\n    Ns::Array{Int64,1}\n    LatVecs::Array{Float64,2}\n    RecVecs::Array{Float64,2}\n    Npoints::Int\n    Ω::Float64\n    R::Array{Float64,2}\n    G::Array{Float64,2}\n    G2::Array{Float64}\nend\n\nfunction PWGrid( Ns::Array{Int,1},LatVecs::Array{Float64,2} )\n    Npoints = prod(Ns)\n    RecVecs = 2*pi*inv(LatVecs')\n    Ω = det(LatVecs)\n    R,G,G2 = init_grids( Ns, LatVecs, RecVecs )\n    return PWGrid( Ns, LatVecs, RecVecs, Npoints, Ω, R, G, G2 )\nend\n\nfunction mm_to_nn(mm::Int,S::Int)\n    if mm > S/2\n        return mm - S\n    else\n        return mm\n    end\nend\n\nfunction init_grids( Ns, LatVecs, RecVecs )\n    #\n    Npoints = prod(Ns)\n    #\n    R = Array(Float64,3,Npoints)\n    ip = 0\n    for k in 0:Ns[3]-1\n    for j in 0:Ns[2]-1\n    for i in 0:Ns[1]-1\n        ip = ip + 1\n        R[1,ip] = LatVecs[1,1]*i/Ns[1] + LatVecs[1,2]*j/Ns[2] + LatVecs[1,3]*k/Ns[3]\n        R[2,ip] = LatVecs[2,1]*i/Ns[1] + LatVecs[2,2]*j/Ns[2] + LatVecs[2,3]*k/Ns[3]\n        R[3,ip] = LatVecs[3,1]*i/Ns[1] + LatVecs[3,2]*j/Ns[2] + LatVecs[3,3]*k/Ns[3]\n    end\n    end\n    end\n    #\n    G  = Array(Float64,3,Npoints)\n    G2 = Array(Float64,Npoints)\n    ip    = 0\n    for k in 0:Ns[3]-1\n    for j in 0:Ns[2]-1\n    for i in 0:Ns[1]-1\n        gi = mm_to_nn( i, Ns[1] )\n        gj = mm_to_nn( j, Ns[2] )\n        gk = mm_to_nn( k, Ns[3] )\n        ip = ip + 1\n        G[1,ip] = RecVecs[1,1]*gi + RecVecs[1,2]*gj + RecVecs[1,3]*gk\n        G[2,ip] = RecVecs[2,1]*gi + RecVecs[2,2]*gj + RecVecs[2,3]*gk\n        G[3,ip] = RecVecs[3,1]*gi + RecVecs[3,2]*gj + RecVecs[3,3]*gk\n        G2[ip] = G[1,ip]^2 + G[2,ip]^2 + G[3,ip]^2\n    end\n    end\n    end\n    return R,G,G2\nend\n", "meta": {"hexsha": "06aee4f69039428f821f62b53316dc848f39f9e9", "size": 1656, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PW/dft_01/PWGrid.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "PW/dft_02/PWGrid.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PW/dft_02/PWGrid.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 25.875, "max_line_length": 84, "alphanum_fraction": 0.5307971014, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7810445413309137}}
{"text": "using LinearAlgebra\n\nA = [\n   1 2\n   2 1\n]\n\ne = eigen(A)\nV = e.vectors\n@show Diagonal(e.values)\nV⁻¹ = inv(V)\n@show V⁻¹ * A * V\n\nF = rand(3,5)\ns = svd(F)\n\nF |> display\ns.U * Diagonal(s.S) * s.Vt |> display\n", "meta": {"hexsha": "56463a7d01cb10fceb7e2231fc7f25521ac222d4", "size": 205, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linearAlgebras/svd.jl", "max_stars_repo_name": "terasakisatoshi/juliaExer", "max_stars_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-02T01:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-04T12:03:25.000Z", "max_issues_repo_path": "linearAlgebras/svd.jl", "max_issues_repo_name": "terasakisatoshi/juliaExer", "max_issues_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linearAlgebras/svd.jl", "max_forks_repo_name": "terasakisatoshi/juliaExer", "max_forks_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 10.7894736842, "max_line_length": 37, "alphanum_fraction": 0.556097561, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191297273499, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7810445349614515}}
{"text": "using LinearAlgebra\n\n\"\"\"\nCalculates the jacobian matrix\n\"\"\"\nfunction genjacobian(fun, X, w)\n    n = size(w)[1]\n    J = zeros(size(X)[1], n)\n    h = zeros(n)\n    for i in 1:n\n        h[i] = 10^-5\n        J[:, i] = (fun(w+h, X) - fun(w-h, X)) / h[i]\n        h[i] = 0\n    end\n    return J\nend\n\n\n\"\"\"\nimplements the gauss newton method.\nfit's a non-linear model (fun) to data points X, Y.\n\n...\n# Arguments\n- `fun::function`: the model, form: fun(w, X), where w are the weights\n- `X::Array/Vector`: X data.\n- `Y::Array/Vector`: Y data.\n- `b0::Array/Vector`: initial guess.\n...\n\"\"\"\nfunction gaussnewton(fun, X, Y, w0)\n    r(w, X) = fun(w, X) - Y             # Anonymous function for the residual (error)\n    f_grad(r_jac, r) = 2 * r_jac' * r   # Anonymous function for the gradient of the residual\n\n    alpha = 1                           # Static Step width, alternatively use Arijo-Goldstein or Wolfe-Powell line search\n    r_jac = genjacobian(fun, w0, X)\n    rw = r(w0, X)                       # The actual residual \n    w = w0\n    iter = 0\n\n    # if gradient is app. 0 -> local minima reached\n    while norm(f_grad(r_jac, rw)) > 1^-8\n\n        # calculate step direction d\n        C = cholesky(r_jac' * r_jac)\n        z = C.L \\ (r_jac' * rw)\n        d = C.U \\ z\n\n        # update weights w\n        w = w - alpha * d\n        r_jac = genjacobian(fun, w, X)\n        rw = r(w, X)\n\n        iter = iter + 1\n        if iter == 10000\n            break\n        end\n    end\n    return w\nend\n\n", "meta": {"hexsha": "e5532b3eeb84dfed3308c88126b4077fecdd8617", "size": 1479, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "regression/gauss_newton_method.jl", "max_stars_repo_name": "micaebe/ai-julia", "max_stars_repo_head_hexsha": "88703d70681465704f210a6a75a8ea7bb6ed8c54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "regression/gauss_newton_method.jl", "max_issues_repo_name": "micaebe/ai-julia", "max_issues_repo_head_hexsha": "88703d70681465704f210a6a75a8ea7bb6ed8c54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "regression/gauss_newton_method.jl", "max_forks_repo_name": "micaebe/ai-julia", "max_forks_repo_head_hexsha": "88703d70681465704f210a6a75a8ea7bb6ed8c54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8548387097, "max_line_length": 122, "alphanum_fraction": 0.5314401623, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191259110588, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7810445297181953}}
{"text": "\"\"\"\n    struct PolynomialV <: AbstractVApproximator{Int}\n        weights::Vector{Float64}\n    end\n\nSee more details at Section (9.5.1) on Page 210 of the book *Sutton, Richard S., and Andrew G. Barto. Reinforcement learning: An introduction. MIT press, 2018.*\n\"\"\"\nstruct PolynomialV <: AbstractVApproximator{Int}\n    weights::Vector{Float64}\nend\n\nPolynomialV(order::Int) = PolynomialV(zeros(Float64, order+1))\n\nfunction (p::PolynomialV)(s)\n    sum(w * s^(i-1) for (i, w) in enumerate(p.weights))\nend\n\nfunction update!(p::PolynomialV, s, e)\n    for i in 1:length(p.weights)\n        p.weights[i] += e * s^(i-1)\n    end\nend", "meta": {"hexsha": "da96907aa1caf21b3b8ebc9cabf1f4d70b39e4bc", "size": 620, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/approximators/polynomial_V.jl", "max_stars_repo_name": "JuliaTagBot/Ju.jl", "max_stars_repo_head_hexsha": "f951f940de7ea007fe3e0be8c6e477bb6fadd05e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2019-01-03T02:57:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T14:09:28.000Z", "max_issues_repo_path": "src/approximators/polynomial_V.jl", "max_issues_repo_name": "JuliaTagBot/Ju.jl", "max_issues_repo_head_hexsha": "f951f940de7ea007fe3e0be8c6e477bb6fadd05e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2018-12-25T10:02:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-30T09:06:43.000Z", "max_forks_repo_path": "src/approximators/polynomial_V.jl", "max_forks_repo_name": "JuliaTagBot/Ju.jl", "max_forks_repo_head_hexsha": "f951f940de7ea007fe3e0be8c6e477bb6fadd05e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-12-25T09:51:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:06:30.000Z", "avg_line_length": 28.1818181818, "max_line_length": 160, "alphanum_fraction": 0.6758064516, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374443, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7810415136194458}}
{"text": "using LinearAlgebra\nusing Memoize\n\n\"\"\"\n    pauli_vector(x, y, z)\n\nAssemble the \"Pauli vector\" matrix.\n\"\"\"\npauli_vector(x, y, z) = ComplexF64[z x - im * y; x + im * y -z]\n\n\n\"\"\"\n    binary_digits(x::Integer, M::Integer)\n\nReturn `M` bits of the binary representation of the integer `x` as array (least significant bit at first index).\n\"\"\"\nfunction binary_digits(M::Integer, x::Integer)\n    binary_digits!(BitArray(undef, M), x)\nend\n\n\"\"\"\n    binary_digits!(m::BitArray{1}, x::Integer)\n\nFill `m` with the binary representation of the integer `x` (least significant bit at first index).\n\"\"\"\nfunction binary_digits!(m::BitArray{1}, x::Integer=0)\n    for i in 1:length(m)\n        m[i] = x & 1\n        x >>= 1\n    end\n    return m\nend\n\n\"\"\"\n    binary_to_int(m::BitArray{1}, s=0)\n\nconverts BitArray `m` into Integer\n\"\"\"\nfunction binary_to_int(m::BitArray{1}, x=0)\n    v = 1\n    for i in Base.view(m, :)\n        x += v*i\n        v <<= 1\n    end \n    x\nend\n\n\n\"\"\"\n    quaternary_digits(x::Integer, M::Integer)\n\nReturn `M` base-4 digits of the quaternary representation of the integer `x` as array (least significant digit at first index).\n\"\"\"\nfunction quaternary_digits(M::Integer, x::Integer)\n    quaternary_digits!(Vector{Int}(undef, M), x)\nend\n\n\"\"\"\n    quaternary_digits!(m::Vector{Int}, x::Integer)\n\nFill `m` with the quaternary representation of the integer `x` (least significant digit at first index).\n\"\"\"\nfunction quaternary_digits!(m::Vector{Int}, x::Integer)\n    for i in 1:length(m)\n        m[i] = x & 3\n        x >>= 2\n    end\n    return m\nend\n\n\n\"\"\"\n    intlog2(x::Integer)\n\nCompute integer base-2 logarithm. Rounds to floor if x is not a power of 2.\n\"\"\"\nfunction intlog2(x::Integer)\n    x == 0 && error(\"Logarithm of 0 is undefined\")\n    x < 0 && error(\"Logarithm of negative number is undefined\")\n    ret::Int = 0\n    while x > 1\n        x >>= 1\n        ret += 1\n    end\n    ret\nend\n\n\n\"\"\"\n    sliced_index(idx, targetwires::Tuple, N::Int)\n\nConstruct sliced index via target map (utility function).\n\"\"\"\nfunction sliced_index(idx, targetwires::Tuple, N::Int)\n    islice = Vector{Any}(fill(Colon(), N))\n    for k in 1:length(targetwires)\n        islice[targetwires[k]] = idx[k] + 1\n    end\n    return islice\nend\n\n\n\"\"\"\n    gramm_schmidt(a::Array{Float64})\n\nCompute orthogonalized real vectors.\n\"\"\"\nfunction gramm_schmidt!(a::Array{Float64})\n    num_vectors = size(a,2)\n    \n    a[:, end] = a[:, end] ./ norm(a[:, end])\n\n    for i in num_vectors-1:-1:1        \n        for j in i+1:num_vectors\n            a[:, i] = a[:, i] - (dot(a[:, i], a[:, j]) / dot(a[:, j], a[:, j])) * a[:, j]\n        end\n        a[:, i] = a[:, i] ./ norm(a[:, i])\n    end\n\n    return a\nend\n\n\"\"\"\n    gramm_schmidt(a::Array{ComplexF64})\n\nCompute orthogonalized complex vectors.\n\"\"\"\nfunction gramm_schmidt!(a::Array{ComplexF64})\n    num_vectors = size(a,2)\n\n    a[:, end] = a[:, end] ./ norm(a[:, end])\n\n    for i in num_vectors-1:-1:1        \n        for j in num_vectors:-1:i+1\n            a[:, i] = a[:, i] - conj(dot(a[:, i], a[:, j]) / dot(a[:, j], a[:, j])) * a[:, j]\n        end\n        a[:, i] = a[:, i] ./ norm(a[:, i])\n    end\n    return a\nend\n\n\"\"\"\n    rdm(N, iwire, ψ, χ, d=2)\n\nCompute the reduced density matrix ``tr_B[|ψ⟩⟨χ|]``, where the trace runs over\nthe subsystem complementary to the qubits specified by `iwire`.\n\"\"\"\n@views function rdm(N::Integer, iwire::NTuple{M,<:Integer}, ψ::Vector{T}, χ::Vector{T}, d::Int=2) where {M,T}\n    M ≥ 1 || error(\"Need at least one wire to act on.\")\n    M ≤ N || error(\"Number of gate wires cannot be larger than total number of wires.\")\n    length(unique(iwire)) == M || error(\"Wire indices must be unique.\")\n    minimum(iwire) ≥ 1 || error(\"Wire index cannot be smaller than 1.\")\n    maximum(iwire) ≤ N || error(\"Wire index cannot be larger than total number of wires.\")\n    length(ψ) == d^N || error(\"Input vector 'ψ' has wrong length.\")\n    length(χ) == d^N || error(\"Input vector 'χ' has wrong length.\")\n\n    # convert to array\n    iwire = collect(iwire)\n    # complementary wires\n    iwcompl = setdiff(1:N, iwire)\n    @assert length(iwire) + length(iwcompl) == N\n\n    ρ = zeros(eltype(ψ), d^M, d^M)\n    # # Note: following the ordering convention of `kron` here, i.e.,\n    # # last qubit corresponds to fastest varying index\n    strides = [d^(j-1) for j in 1:N]\n    wstrides = strides[iwire]\n    cstrides = strides[iwcompl]\n\n    if d == 2\n        iw = BitArray{1}(undef, M)\n        jw = BitArray{1}(undef, M)\n        kw = BitArray{1}(undef, N - M)\n        # TODO: optimize memory access pattern\n        for k in 0:2^(N-M)-1\n            binary_digits!(kw, k)\n            koffset = dot(kw, cstrides)\n            for i in 1:2^M\n                binary_digits!(iw, i - 1)\n                for j in 1:2^M\n                    binary_digits!(jw, j - 1)\n                    rowind = koffset + dot(iw, wstrides) + 1\n                    colind = koffset + dot(jw, wstrides) + 1\n                    @inbounds ρ[i, j] += ψ[rowind] * conj(χ[colind])\n                end\n            end\n        end\n    elseif d == 4\n        iw = Vector{Int}(undef, M)\n        jw = Vector{Int}(undef, M)\n        kw = Vector{Int}(undef, N - M)\n        # TODO: optimize memory access pattern\n        for k in 0:4^(N-M)-1\n            quaternary_digits!(kw, k)\n            koffset = dot(kw, cstrides)\n            for i in 1:4^M\n                quaternary_digits!(iw, i - 1)\n                for j in 1:4^M\n                    quaternary_digits!(jw, j - 1)\n                    rowind = koffset + dot(iw, wstrides) + 1\n                    colind = koffset + dot(jw, wstrides) + 1\n                    @inbounds ρ[i, j] += ψ[rowind] * conj(χ[colind])\n                end\n            end\n        end\n    else\n        error(\"d = $d not supported yet.\")\n    end\n\n    return ρ\nend", "meta": {"hexsha": "e9f2ed3fd46b215f646720b3df7ffd656fdd9807", "size": 5760, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/util.jl", "max_stars_repo_name": "isolatedinformation/Qaintessent.jl", "max_stars_repo_head_hexsha": "275df394b9b7103005fac6bac3d6ce0f955718e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/util.jl", "max_issues_repo_name": "isolatedinformation/Qaintessent.jl", "max_issues_repo_head_hexsha": "275df394b9b7103005fac6bac3d6ce0f955718e9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util.jl", "max_forks_repo_name": "isolatedinformation/Qaintessent.jl", "max_forks_repo_head_hexsha": "275df394b9b7103005fac6bac3d6ce0f955718e9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2985781991, "max_line_length": 127, "alphanum_fraction": 0.5614583333, "num_tokens": 1766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686647, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7810415069971808}}
{"text": "\"\"\"\nRiesz sense fractional derivative\n\"\"\"\nabstract type Riesz <: FracDiffAlg end\n\n\"\"\"\n# Riesz sense symmetric fractional derivative algorithm.\n\n    fracdiff(f, α, end_point, h, RieszSymmetric())\n\nCompute fractional derivative of Riesz sense using Triangular Strip Matrix algorithm.\n\n### Example\n\n```julia-repl\njulia> fracdiff(x->x, 0.5, 1, 0.01, RieszSymmetric())\n```\n\"\"\"\nstruct RieszSymmetric <: Riesz end\n\n\n\"\"\"\n# Riesz sense Ortigueira definition fractional derivative\n\n    fracdiff(f, α, end_point, h, RieszOrtigueira())\n\nOrtigueira's definition of the symmetric Riesz derivative via centred differences\n\n### Usage\n\n```julia-repl\njulia> fracdiff(x->x, 0.5, 1, 0.01, RieszOrtigueira())\n```\n\"\"\"\nstruct RieszOrtigueira <: Riesz end\n\n################################################################\n###                    Type definition done                  ###\n################################################################\n\n\nfunction fracdiff(f::FunctionAndNumber, α, end_point, h, ::RieszSymmetric)\n    N=floor(Int, end_point/h)\n\n    mat = RieszMatrix(α, N+1, h)\n    return mat*f.(collect(0:h:end_point))\nend\nfunction RieszMatrix(α, N, h)\n    caputo = B(N+1, α)\n    caputo = caputo[2:(N+1), 1:N]\n    result = 1/2*(caputo+caputo')\n    result = h^(-α)*result\n    return result\nend\n\n#FIXME: Values are changing when h become smaller?\nfunction fracdiff(f, α, point, h, ::RieszOrtigueira)\n    N = round(Int, point/h)\n    t = collect(0:h:point)\n    return ranort(α, N+1, h)*f.(t)\nend\n\nfunction ranort(alpha, N)\n    k=collect(0:N-1)\n    rc = ((-1)*ones(size(k))).^k.*gamma.(alpha+1).*(gamma.(alpha*0.5 .-k.+1).*gamma.(alpha*0.5 .+ k.+1)).^(-1)\n    rc = rc*(cos(alpha*π*0.5))\n    R = zeros(N, N)\n\n    for m=1:N\n        R[m, m:N] = rc[1:N-m+1]\n    end\n\n    for i=1:N-1\n        for j=i:N\n            R[j, i] = R[i, j]\n        end\n    end\n    return R\nend\n# Dispatch for ranort\nfunction ranort(alpha, N, h)\n    R = ranort(alpha, N)\n    R = R*h^(-alpha)\n    return R\nend", "meta": {"hexsha": "91d6847588d97f88c17aeceefab8bcf704543007", "size": 1964, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Derivative/Riesz.jl", "max_stars_repo_name": "SciFracX/FractionalCalculus.jl", "max_stars_repo_head_hexsha": "f570164fdf86314f6c8871d18659bd343046bb04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-11-05T12:53:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T20:58:27.000Z", "max_issues_repo_path": "src/Derivative/Riesz.jl", "max_issues_repo_name": "SciFracX/FractionalCalculus.jl", "max_issues_repo_head_hexsha": "f570164fdf86314f6c8871d18659bd343046bb04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-11-05T17:20:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T13:20:01.000Z", "max_forks_repo_path": "src/Derivative/Riesz.jl", "max_forks_repo_name": "SciFracX/FractionalCalculus.jl", "max_forks_repo_head_hexsha": "f570164fdf86314f6c8871d18659bd343046bb04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-10-21T08:58:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T20:40:29.000Z", "avg_line_length": 23.1058823529, "max_line_length": 110, "alphanum_fraction": 0.5773930754, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.781041506377628}}
{"text": "#\n# Maneuver calculations for orbits within the Twobody Problem\n#\n\n\"\"\"\nProvides the radius of escape.\n\"\"\"\nescape_radius(r₀, v₀, aₜ) = r₀ * v₀ / (20 * aₜ^2 * r₀^2)^(1/4)\nescape_radius(orbit::T, m::ConstantManeuver) where T <: RestrictedTwoBodySystem = escape_radius(radius(orbit), velocity(orbit), m.aₜ)\n\n\"\"\"\nProvides the velocity at escape.\n\"\"\"\nescape_velocity(r₀, v₀, aₜ, μ) = √(2 * μ / escape_radius(r₀, v₀, aₜ))\nescape_velocity(orbit::T, m::ConstantManeuver) where T <: RestrictedTwoBodySystem = escape_velocity(radius(orbit), velocity(orbit), m.aₜ, orbit.body.μ)\n\n\"\"\"\nProvides time delta from the provided initial orbit to escape.\n\"\"\"\nescape_time(r₀, v₀, aₜ) = upreferred(v₀ / aₜ) * (1 - (upreferred(20aₜ^2 * r₀^2) / upreferred(v₀^4))^(1/8))\nescape_time(orbit::T, m::ConstantManeuver) where T <: RestrictedTwoBodySystem = escape_time(radius(orbit), velocity(orbit), m.aₜ)\n\n\"\"\"\nProvides the path length from the initial condition to escape.\n\"\"\"\nescape_path_length(r₀, v₀, aₜ) = upreferred(v₀^2 / 2aₜ) * (1 - upreferred((1/v₀) * (20aₜ^2 * r₀^2)^(1/4)))\nescape_path_length(orbit::T, m::ConstantManeuver) where T <: RestrictedTwoBodySystem = escape_path_length(radius(orbit), velocity(orbit), m.aₜ)", "meta": {"hexsha": "85e4a227e63a0a769c05c2c8356f6343be2f9af1", "size": 1198, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "deprecated/GeneralAstrodynamics_v0.8/Maneuvers/twobody_maneuver_calculations.jl", "max_stars_repo_name": "pbouffard/GeneralAstrodynamics.jl", "max_stars_repo_head_hexsha": "80f175a5b3c6dac2140e645b016d39f131ecea05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deprecated/GeneralAstrodynamics_v0.8/Maneuvers/twobody_maneuver_calculations.jl", "max_issues_repo_name": "pbouffard/GeneralAstrodynamics.jl", "max_issues_repo_head_hexsha": "80f175a5b3c6dac2140e645b016d39f131ecea05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deprecated/GeneralAstrodynamics_v0.8/Maneuvers/twobody_maneuver_calculations.jl", "max_forks_repo_name": "pbouffard/GeneralAstrodynamics.jl", "max_forks_repo_head_hexsha": "80f175a5b3c6dac2140e645b016d39f131ecea05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3703703704, "max_line_length": 151, "alphanum_fraction": 0.7120200334, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.8376199552262966, "lm_q1q2_score": 0.7810415019627844}}
{"text": "\nusing Plots, OrdinaryDiffEq, DiffEqPhysics, RecursiveArrayTools\ngr()\n\nG = 2.95912208286e-4\nM = [1.00000597682, 0.000954786104043, 0.000285583733151, 0.0000437273164546, 0.0000517759138449, 1/1.3e8]\nplanets = [\"Sun\", \"Jupiter\", \"Saturn\", \"Uranus\", \"Neptune\", \"Pluto\"]\n\npos_x = [0.0,-3.5023653,9.0755314,8.3101420,11.4707666,-15.5387357]\npos_y = [0.0,-3.8169847,-3.0458353,-16.2901086,-25.7294829,-25.2225594]\npos_z = [0.0,-1.5507963,-1.6483708,-7.2521278,-10.8169456,-3.1902382]\npos = ArrayPartition(pos_x,pos_y,pos_z)\n\nvel_x = [0.0,0.00565429,0.00168318,0.00354178,0.00288930,0.00276725]\nvel_y = [0.0,-0.00412490,0.00483525,0.00137102,0.00114527,-0.00170702]\nvel_z = [0.0,-0.00190589,0.00192462,0.00055029,0.00039677,-0.00136504]\nvel = ArrayPartition(vel_x,vel_y,vel_z)\n\ntspan = (0.,200_000)\n\n\nconst ∑ = sum\nconst N = 6\npotential(p, t, x, y, z, M) = -G*∑(i->∑(j->(M[i]*M[j])/sqrt((x[i]-x[j])^2 + (y[i]-y[j])^2 + (z[i]-z[j])^2), 1:i-1), 2:N)\n\n\nnprob = NBodyProblem(potential, M, pos, vel, tspan)\nsol = solve(nprob,Yoshida6(), dt=100);\n\n\norbitplot(sol,body_names=planets)\n\n\nusing DiffEqTutorials\nDiffEqTutorials.tutorial_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])\n\n", "meta": {"hexsha": "b3ee7e84bac4ff5466e811854abc1be6ccbbcee0", "size": 1167, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/models/07-outer_solar_system.jl", "max_stars_repo_name": "isaacsas/DiffEqTutorials.jl", "max_stars_repo_head_hexsha": "46c1701ef613aacbd678bde7437a3c8de363990d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-15T14:57:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-15T14:57:40.000Z", "max_issues_repo_path": "script/models/07-outer_solar_system.jl", "max_issues_repo_name": "LoopGlitch26/SciMLTutorials.jl", "max_issues_repo_head_hexsha": "837d71ad59de12af2fa48babb9e5cd2e280dc71a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/models/07-outer_solar_system.jl", "max_forks_repo_name": "LoopGlitch26/SciMLTutorials.jl", "max_forks_repo_head_hexsha": "837d71ad59de12af2fa48babb9e5cd2e280dc71a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5405405405, "max_line_length": 120, "alphanum_fraction": 0.6958011997, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7810415013432315}}
{"text": "#! /usr/bin/julia\n\n# Rosetta Code, Arithmetic-geometric mean\n\nfunction agm{T<:FloatingPoint,U<:Integer}(x::T, y::T, e::U=5)\n    0 < y && 0 < y && 0 < e || throw(DomainError())\n    err = e*eps(x)\n    (g, a) = extrema([x, y])\n    while err < (a - g)\n        ap = a\n        a = 0.5*(a + g)\n        g = sqrt(ap*g)\n    end\n    return a\nend\n\nx = 1.0\ny = 1.0/sqrt(2.0)\n\nprintln(\"Using literal-precision float numbers:\")\nprintln(\"    agm(\", x, \",\", y, \") = \", agm(x, y))\n\nprintln()\nprintln(\"Using half-precision float numbers:\")\nx = float16(x)\ny = float16(y)\nprintln(\"    agm(\", x, \",\", y, \") = \", agm(x, y))\n\nprintln()\nprintln(\"Using \", get_bigfloat_precision(), \"-bit float numbers:\")\nx = BigFloat(1.0)\ny = x/sqrt(BigFloat(2.0))\nprintln(\"    agm(\", x, \",\", y, \") = \\n    \", agm(x, y))\n\n\n\n", "meta": {"hexsha": "2ca891fc74e4bfa306109de8ae7bc2c4db1ddaf4", "size": 782, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/completed/arithmetic_geometric_mean.jl", "max_stars_repo_name": "MichaeLeroy/rosetta-code", "max_stars_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/completed/arithmetic_geometric_mean.jl", "max_issues_repo_name": "MichaeLeroy/rosetta-code", "max_issues_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/completed/arithmetic_geometric_mean.jl", "max_forks_repo_name": "MichaeLeroy/rosetta-code", "max_forks_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1351351351, "max_line_length": 66, "alphanum_fraction": 0.5294117647, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7810414994533835}}
{"text": "## Exercise 6-7\n## A number, a, is a power of b if it is divisible by b and a/b is a power of b. Write a function called ispower that takes parameters a and b and returns true if a is a power of b.\n\n## TIP\n## You will have to think about the base case.\nprintln(\"Ans: \")\n\nfunction ispower(a, b)\n    if a == b\n        return true\n    end\n\n    if a % b == 0 && ispower(a / b, b)\n        return true\n    end \n\n    return false\nend\n\nprintln(ispower(1000, 10))\nprintln(ispower(343, 7))\nprintln(ispower(31, 2))\n\nprintln(\"End.\")\n", "meta": {"hexsha": "d67d43abfa26918487f7619b0cab97f75bd6d77e", "size": 521, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter6/ex7.jl", "max_stars_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_stars_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-13T14:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T14:11:30.000Z", "max_issues_repo_path": "Chapter6/ex7.jl", "max_issues_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_issues_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter6/ex7.jl", "max_forks_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_forks_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.84, "max_line_length": 181, "alphanum_fraction": 0.6333973129, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.8757869884059267, "lm_q1q2_score": 0.7810365097112254}}
{"text": "# This file contains the functions to compute the emissivities of bulks and multilayers\r\n\r\n# Factors\r\n\"\"\"\r\n    bose_einstein(w,T)\r\n\r\nBose-Einstein factor using the definition:\r\n```math\r\n\\\\Theta(\\\\omega,T) = \\\\frac{\\\\hbar\\\\omega}{e^{\\\\frac{\\\\hbar\\\\omega}{k_B T}}-1}\r\n```\r\n\r\n\"\"\"\r\nfunction bose_einstein(w,T)\r\n    u = w*ħ/kb/T\r\n    if T==0\r\n        return 0.0\r\n    end\r\n    if w==0.0\r\n        return kb*T\r\n    end\r\n\r\n    return u*kb*T/(exp(u)-1.0)\r\nend\r\n\r\n\"\"\"\r\n    planck(w,T)\r\n\r\nPlanck's Distribution using the definition:\r\n\r\n```math\r\nq^{\\\\text{BB}}(\\\\omega,T) =  \\\\Theta(\\\\omega,T) \\\\frac{k_0^2}{4\\\\pi^2}\r\n```\r\n\"\"\"\r\nfunction planck(w,T)\r\n    return  bose_einstein(w,T)*(w/c0)^2/(2.0*pi)^2\r\nend\r\n\r\n\"\"\"\r\n    planck_fraction(w1,w2,T)\r\n\r\nfraction of the energy between pulsations w1 and w2\r\n\r\n```math\r\nq^{\\\\text{BB}}(\\\\omega_1,\\\\omega_2,T) =  \\\\frac{1}{\\\\sigma T^4}\\\\int_{\\\\omega_1}^{\\\\omega_2}q^{\\\\text{BB}}(\\\\omega)d\\\\omega\r\n```\r\n\"\"\"\r\nfunction planck_fraction(w1,w2,T)\r\n  pl(w) = planck(w,T)\r\n  (val, err) = quadgk(pl, w1, w2 ;rtol=1e-8)\r\n  return val/sigma/T^4\r\nend\r\n\r\n\"\"\"\n    wien(T)\n\nWien frequency: return the frequency for which Planck distribution is maximum.\nT is given in Kelvin and the result is given in radHz\n\"\"\"\nfunction wien(T)\r\n    return   2.8214393721220787*kb*T/ħ\r\nend\r\n\r\n\r\n\"\"\"\r\n    invwien(w)\r\n\r\nInverse of Wien law : return the temperature (K)\r\nfor a given frequency in radHz\r\n\"\"\"\r\nfunction invwien(w)\r\n    return   w*ħ/(2.8214393721220787*kb)\r\nend\r\n\r\n\" Unit conversion from rad/s to wavelength in m\"\r\nunitconv(w) = 2.0*pi*c0/w\r\n\r\n\" Wien's wavelength obtained from wien's law in m\"\r\nlambda_wien(T) = 2.8977729e-3/T\r\n\r\n\"Monocromatic directional emissivity\"\r\nfunction emissivity_kx_w(structure, kx, w)\r\n\r\n    (Rte,Tte)=power_rt(structure, te(), kx ,w)\r\n    (Rtm,Ttm)=power_rt(structure, tm(), kx ,w)\r\n\r\n    if imag(permittivity(substrate(structure),w)) == 0.0\r\n        integr1 = 1.0 - Rte - Tte\r\n        integr2 = 1.0 - Rtm - Ttm\r\n    else\r\n        integr1 = 1.0 - Rte\r\n        integr2 = 1.0 - Rtm\r\n    end\r\n\r\n    return integr1 + integr2\r\nend\r\n\r\n\r\n\r\n\"Total directional emissivity\"\r\nfunction emissivity_kx(structure,T, kx, wi,wf; rtol=1e-8)\r\n\r\n    e(u) = emissivity_kx_w(structure, kx, u*kb*T/ħ)*u^3/(exp(u)-1.0)\r\n    val :: Float64  = 0.0\r\n    err :: Float64  = 0.0\r\n    (val,err) = quadgk(e, wi*ħ/kb/T , wf*ħ/kb/T ; rtol=rtol)\r\n\r\n    return val*kb^4/ħ^3/c0^2/(2.0*pi)^2/sigma\r\nend\r\n\r\n\" Monocromatic hemispherical emissivity\"\r\nfunction emissivity_w(structure, w; rtol = 1e-8)\r\n    e_kx(kx) = kx*emissivity_kx_w(structure ,kx, w)\r\n\r\n    val :: Float64  = 0.0\r\n    err :: Float64  = 0.0\r\n    (val,err) = quadgk(e_kx, 0.0, w/c0 ; rtol=rtol)\r\n\r\n    return val/(w/c0)^2\r\nend\r\n\r\n\" total hemispherical emissivity\"\r\nfunction emissivity(structure,T;rtol = 1e-8)\r\n    e(u) = emissivity_w(structure, u*kb*T/ħ;rtol = rtol)*u^3/(exp(u)-1.0)\r\n    e2(t) = e(t/(1.0-t))/(1.0-t)^2\r\n\r\n    val :: Float64  = 0.0\r\n    err :: Float64  = 0.0\r\n    (val,err) = quadgk(e2, 0.0, 1.0 ; rtol=rtol)\r\n\r\n    return val*kb^4/ħ^3/c0^2/(2.0*pi)^2/sigma\r\nend\r\n\r\n\" total hemispherical emissivity with integration bounds for frequency\"\r\nfunction emissivity(structure,T,wi,wf;rtol = 1e-8)\r\n    e(u) = emissivity_w(structure, u*kb*T/ħ; rtol = rtol)*u^3/(exp(u)-1.0)\r\n    val :: Float64  = 0.0\r\n    err :: Float64  = 0.0\r\n    (val,err) = quadgk(e, wi*ħ/kb/T , wf*ħ/kb/T ; rtol=rtol)\r\n\r\n    return val*kb^4/ħ^3/c0^2/(2.0*pi)^2/sigma\r\nend\r\n\r\nfunction emissivity_fraction(structure,T,wi,wf;rtol = 1e-8)\r\n    return emissivity_kx(structure,T,0.0,wi,wf;rtol = rtol)/planck_fraction(wi,wf,T)\r\nend\r\n", "meta": {"hexsha": "a881aff18fa27a2e7ac2d8397ad4b151289c6b3d", "size": 3567, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/emissivity.jl", "max_stars_repo_name": "omerchiers/MultiLayerNFRHT.jl", "max_stars_repo_head_hexsha": "cecc3efbd0303bd2cac84b36b79690c636bbdec4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/emissivity.jl", "max_issues_repo_name": "omerchiers/MultiLayerNFRHT.jl", "max_issues_repo_head_hexsha": "cecc3efbd0303bd2cac84b36b79690c636bbdec4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/emissivity.jl", "max_forks_repo_name": "omerchiers/MultiLayerNFRHT.jl", "max_forks_repo_head_hexsha": "cecc3efbd0303bd2cac84b36b79690c636bbdec4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4315068493, "max_line_length": 124, "alphanum_fraction": 0.606391926, "num_tokens": 1340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7810007995884469}}
{"text": "using Optim: optimize, Fminbox, LBFGS\nusing Zygote: gradient\n\ninclude(\"./kernels.jl\")\n\n\"\"\"\nFollowing (15.14) in MLAPP, the posterior predictive for noise free \nobservation ``\\\\mathbf{f}_*`` with new data ``\\\\mathbf{X}_*`` is\n\n``\np(\\\\mathbf{f}_* | \\\\mathbf{X}_*, \\\\mathbf{X}, \\\\mathbf{y}) =\n\\\\mathscr{N}(\\\\mathbf{f}_* | \\\\mathbf{\\\\mu}_*, \\\\mathbf{\\\\Sigma}_*)\n``\n\nTo derive posterior predictive distribution for ``\\\\mathbf{y}_*``, \nwe need to add the observation noise to ``\\\\mathbf{f}_*``.\n\"\"\"\nfunction predict(kernel, X, y, Xs; decomp=false)\n    Ky = covariancematrix(kernel, X)\n    Ks = covarianceblock(kernel, X, Xs)\n    Kss = covariancematrix(kernel, Xs)\n    invKy = inv(Ky)\n    μs = Ks'*invKy*y\n    Σs = Kss - Ks'*invKy*Ks\n    return μs, Σs\nend\n\n\"\"\"\nNegative log likelihood for the marginal distribution ``p(y|X)``.\nThe numerically stable version follows **Algorithm 15.1** in MLAPP.\n\"\"\"\nfunction negloglike(X, y, Ky; stable=false)\n    N = size(X, 1)\n    if stable\n        L = cholesky(Ky).L\n        invL = inv(L)\n        α = invL'*invL*y \n        loglike = -0.5*y'*α - sum(log.(diag(L))) - 0.5*N*log(2π)\n        return -loglike\n    else\n        logdetKy = log(det(Ky))\n        loglike = -0.5*y'*inv(Ky)*y - 0.5*logdetKy - 0.5*N*log(2π)\n        return -loglike\n    end\nend\n\n\"\"\"\nNegative log-likelihood for squared exponential kernel (log parameters).\n\"\"\"\nfunction sqexp_negloglike_log(X, y, logl, logσf, logσy; stable=false)\n    l = exp(logl) \n    σf = exp(logσf)\n    σy = exp(logσy)\n    sekernel = SquaredExponentialKernel(l, σf, σy)\n    # Ky = covariancematrix_alt(sekernel, X)\n    Ky = covariancematrix(sekernel, X)\n    return negloglike(X, y, Ky, stable=stable)\nend\n\nfunction sqexp_negloglike(X, y, l, σf, σy; stable=false)\n    sekernel = SquaredExponentialKernel(l, σf, σy)\n    Ky = covariancematrix(sekernel, X)\n    return negloglike(X, y, Ky, stable=stable)\nend\n\n\"\"\"\nAnalytic gradient of the log marginal likelihood for squared exponential kernel.\n\"\"\"\nfunction sqexp_gradient_analytic!(G, X, y, paramvals...)\n    sekernel = SquaredExponentialKernel(paramvals...)\n    grad = -logmarginalgradient(sekernel, X, y)\n    for i = 1:size(G, 1)\n        G[i] = grad[i]\n    end\n    nothing\nend\n\n\"\"\"\nAutodiff gradient of the log marginal gradient using Zygote.\n\"\"\"\nfunction sqexp_gradient_autodiff!(G, X, y, paramvals...)\n    grad = gradient(params -> sqexp_negloglike(X, y, params...), paramvals)[1]\n    for i = 1:size(G, 1)\n        G[i] = grad[i]\n    end\n    nothing\nend\n\nfunction optimize_sekernel(\n    X, y; \n    init_params=ones(3), \n    lower=[1e-6, 1e-6, 1e-6], \n    upper=[Inf, Inf, Inf],\n    stable=true,\n    optimizer=LBFGS()\n    )\n    result = optimize(\n        params -> sqexp_negloglike(X, y, params..., stable=stable),\n        lower, \n        upper, \n        init_params,\n        Fminbox(optimizer)\n    )\n    return result\nend\n\n\"\"\"\nOptimizing squared exponential kernel hyperparameters with provided gradient.\nThe second input to `optimize` is the function to calculate gradient.\nIts first argument is inserted by the `optimize` function to keep track\nof the current gradient.\n\"\"\"\nfunction optimize_sekernel(\n    X, y, g!; \n    init_params=ones(3), \n    lower=[1e-6, 1e-6, 1e-6], \n    upper=[Inf, Inf, Inf],\n    stable=true,\n    optimizer=LBFGS()\n    )\n    result = optimize(\n        params -> sqexp_negloglike(X, y, params..., stable=stable),\n        (G, params) -> g!(G, X, y, params...),\n        lower, \n        upper, \n        init_params,\n        Fminbox(optimizer)\n    )\n    return result\nend\n\nfunction mixture_negloglike(X, y, logl, logσf, logσy, θ0, θ1)\n    l = exp(logl) \n    σf = exp(logσf)\n    σy = exp(logσy)\n    mixturekernel = MixtureKernel(l, σf, σy, θ0, θ1)\n    Ky = covariancematrix(mixturekernel, X)\n    return negloglike(X, y, Ky)\nend\n\n\"\"\"\n    logmarginalpartial(kernel, X, y, ∂Ky∂θ)\n\nPartial derivative of log marginal likelihood ``\\\\log{P(y|X)}`` wrt\nparameter ``θ``.\n\n# Parameters\n- `X`: input matrix\n- `y`: labels\n- `∂Ky∂θ`: partial derivative of covariance matrix ``K_y`` wrt ``θ``.\n\n\"\"\"\nfunction logmarginalpartial(kernel, X, y, ∂Ky∂θ) \n    Ky = covariancematrix(kernel, X)\n    invKy = inv(Ky)\n    α = invKy*y\n    return 0.5*tr((α*α' - invKy)*∂Ky∂θ)\nend\n\n\"\"\"\n    logmarginalgradient(kernel, X, y)\n  \n``∇_θ \\\\log{P(y|X)}``: Analytic gradient of log marginal likelihood ``\\\\log{P(y|X)}`` \nwrt parameters. \n\nNotice because we are passing ``\\\\logθ`` into the log marginal \nlikelihood function. \n    \nWe need to apply chain rule to the gradient we need is \n``\n∇_{\\\\logθ} \\\\log{P(y|X)} = \\\\frac{∂log{P(y|X)}}{∂θ^2} \n                         \\\\frac{∂θ^2}{∂θ} \n                         \\\\frac{∂θ}{∂logθ}  \n``\n\n# Parameters\n\n- `kernel`: kernel function\n- `X`: input matrix\n- `y`: observed outcome \n\n\"\"\"\nfunction logmarginalgradient(kernel::SquaredExponentialKernel, X, y)\n    l = kernel.l\n    σf = kernel.σf\n    σy = kernel.σy\n\n    funcs = Dict{String, Function}()\n    quad(xp, xq, M) = -0.5*(xp-xq)'*M*(xp-xq)\n    funcs[\"∂p∂logl\"] = (xp, xq, δpq, M) -> \n        σf^2*(-0.5*(xp-xq)'*(xp-xq))*exp.(quad(xp, xq, M))*(-1/l^4)*2*l*l\n    funcs[\"∂p∂logσf\"] = (xp, xq, δpq, M) -> exp.(quad(xp, xq, M))*2*σf*σf\n    funcs[\"∂p∂logσy\"] = (xp, xq, δpq, M) -> δpq*2*σy*σy\n\n    N = size(X, 1)\n    numparameters = 3\n    parameternames = [\"∂p∂logl\", \"∂p∂logσf\", \"∂p∂logσy\"]\n    marginalpartialderiv = zeros(numparameters)\n    for i = 1:numparameters\n        parametername = parameternames[i]\n        func = funcs[parametername]\n        ∂Ky∂θ = zeros(N, N)\n        for p=1:N, q=1:N  \n            xp = X[p, :]\n            xq = X[q, :]\n            M = lengthscalematrix(l, length(xp))\n            ∂Ky∂θ[p, q] = func(xp, xq, p==q, M)\n        end\n        marginalpartialderiv[i] = logmarginalpartial(kernel, X, y, ∂Ky∂θ)\n    end\n\n    marginalpartialderiv\nend\n", "meta": {"hexsha": "2de0c58c75dc5c9de7bc82aa19cd3c96b8ad9058", "size": 5767, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gaussianprocess.jl", "max_stars_repo_name": "Jetafull/AlgorithmsInJulia", "max_stars_repo_head_hexsha": "6e4d8a58e063861967de9260f15d182eb7d35ada", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-21T03:27:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T03:27:23.000Z", "max_issues_repo_path": "src/gaussianprocess.jl", "max_issues_repo_name": "Jetafull/algorithms-in-julia", "max_issues_repo_head_hexsha": "6e4d8a58e063861967de9260f15d182eb7d35ada", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gaussianprocess.jl", "max_forks_repo_name": "Jetafull/algorithms-in-julia", "max_forks_repo_head_hexsha": "6e4d8a58e063861967de9260f15d182eb7d35ada", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9485981308, "max_line_length": 86, "alphanum_fraction": 0.6044737298, "num_tokens": 1966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416414, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7810007971438084}}
{"text": "using DifferentialEquations\nusing Plots\nusing Markdown\n\ndescription = md\"\"\"\n\nSolve the Pendulum System:\n``dθ/dt = ω(t),``\n``dω/dt = -(3/2)(g/l)sinθ + (3/ml²)M(t)``\nfor mass m, length l, and where t∈[0,10], u₀= [0.01, 0.0], and M(t) is an external torque\n\n\"\"\"\ndisplay(description)\n\nl = 1.0\nm = 1.0\ng = 9.81\n\nfunction pendulum!(du, u, p, t)\n    du[1] = u[2]\n    du[2] = -3g/(2l)*sin(u[1]) + 3/(m*l^2)*p(t)  # here p is a function\nend\n\nθ₀ = 0.01\nω₀ = 0.0\nu0 = [θ₀, ω₀]\n\ntspan = (0.0, 10.0)\n\n\nM = t->0.1sin(t)  # this is the external torque\n\nprob = ODEProblem(pendulum!, u0, tspan, M)\nsol = solve(prob)\n\n# visualize the result\nplot(sol, linewidth=2, xaxis=\"t\", label=[\"θ [rad]\" \"ω [rad/s]\"], layout=(2,1))\n", "meta": {"hexsha": "f899b02215f3fafc55932b91ffb20e4e379133b5", "size": 702, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "DiffEqs/ODEs/NonhomogenousEquations.jl", "max_stars_repo_name": "john-waczak/SciML-examples", "max_stars_repo_head_hexsha": "bed1fc7c7038f7676662540d5939465584978a85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DiffEqs/ODEs/NonhomogenousEquations.jl", "max_issues_repo_name": "john-waczak/SciML-examples", "max_issues_repo_head_hexsha": "bed1fc7c7038f7676662540d5939465584978a85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DiffEqs/ODEs/NonhomogenousEquations.jl", "max_forks_repo_name": "john-waczak/SciML-examples", "max_forks_repo_head_hexsha": "bed1fc7c7038f7676662540d5939465584978a85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.4736842105, "max_line_length": 89, "alphanum_fraction": 0.594017094, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104924150547, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7809246404543704}}
{"text": "# Conjugate\n\nexport Conjugate\n\n\"\"\"\n**Convex conjugate**\n\n    Conjugate(f)\n\nReturns the convex conjugate (also known as Fenchel conjugate, or Fenchel-Legendre transform) of function `f`, that is\n```math\nf^*(x) = \\\\sup_y \\\\{ \\\\langle y, x \\\\rangle - f(y) \\\\}.\n```\n\"\"\"\nstruct Conjugate{T <: ProximableFunction} <: ProximableFunction\n    f::T\n    function Conjugate{T}(f::T) where {T<: ProximableFunction}\n        if is_convex(f) == false\n            error(\"`f` must be convex\")\n        end\n        new(f)\n    end\nend\n\nis_prox_accurate(f::Conjugate) = is_prox_accurate(f.f)\nis_convex(f::Conjugate) = true\nis_cone(f::Conjugate) = is_cone(f.f) && is_convex(f.f)\nis_smooth(f::Conjugate) = is_strongly_convex(f.f)\nis_strongly_convex(f::Conjugate) = is_smooth(f.f)\nis_quadratic(f::Conjugate) = is_strongly_convex(f.f) && is_generalized_quadratic(f.f)\nis_generalized_quadratic(f::Conjugate) = is_quadratic(f.f)\nis_set(f::Conjugate) = is_convex(f.f) && is_support(f.f)\nis_positively_homogeneous(f::Conjugate) = is_convex(f.f) && is_set(f.f)\n\nfun_dom(f::Conjugate) = fun_dom(f.f)\n\nConjugate(f::T) where {T <: ProximableFunction} = Conjugate{T}(f)\n\n# only prox! is provided here, call method would require being able to compute\n# an element of the subdifferential of the conjugate\n\nfunction prox!(y::AbstractArray{R}, g::Conjugate, x::AbstractArray{R}, gamma::R=R(1)) where R <: Real\n    # Moreau identity\n    v = prox!(y, g.f, x/gamma, 1/gamma)\n    if is_set(g)\n        v = R(0)\n    else\n        v = dot(x, y) - gamma * dot(y, y) - v\n    end\n    y .= x .- gamma .* y\n    return v\nend\n\n# complex case, need to cast inner products to real\n\nfunction prox!(y::AbstractArray{Complex{T}}, g::Conjugate, x::AbstractArray{Complex{T}}, gamma::R=R(1)) where {R <: Real, T <: RealOrComplex{R}}\n    v = prox!(y, g.f, x/gamma, 1/gamma)\n    if is_set(g)\n        v = R(0)\n    else\n        v = real(dot(x, y)) - gamma * real(dot(y, y)) - v\n    end\n    y .= x .- gamma .* y\n    return v\nend\n\n# naive implementation\n\nfunction prox_naive(g::Conjugate, x::AbstractArray{T}, gamma=R(1)) where {R, T <: RealOrComplex{R}}\n    y, v = prox_naive(g.f, x/gamma, 1/gamma)\n    return x - gamma * y, if is_set(g) R(0) else real(dot(x, y)) - gamma * real(dot(y, y)) - v end\nend\n\n# TODO: hard-code conjugation rules? E.g. precompose/epicompose\n", "meta": {"hexsha": "a6947e4803b2d2478c1562dc0309a18ec90b8568", "size": 2300, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/calculus/conjugate.jl", "max_stars_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_stars_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2016-10-29T12:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:11:52.000Z", "max_issues_repo_path": "src/calculus/conjugate.jl", "max_issues_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_issues_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2016-10-26T16:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T20:38:48.000Z", "max_forks_repo_path": "src/calculus/conjugate.jl", "max_forks_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_forks_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T10:40:24.000Z", "avg_line_length": 30.6666666667, "max_line_length": 144, "alphanum_fraction": 0.6469565217, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7809095320802426}}
{"text": "# Floyd Warshall algorithm to find shortest paths between all pairs of vertices\n\n\nfunction floyd_warshall!(dists::AbstractMatrix{W}) where {W} # dists: minimum distance matrix (initialized to edge distances)\n\n    # argument checking\n\n    n = size(dists, 1)\n    if size(dists, 2) != n\n        throw(ArgumentError(\"dists should be a square matrix.\"))\n    end\n\n    # initialize\n\n    for i = 1 : n\n        dists[i,i] = 0\n    end\n\n    # main loop\n\n    for k = 1 : n, i = 1 : n, j = 1 : n\n        d = dists[i,k] + dists[k,j]\n        if d < dists[i,j]\n            dists[i,j] = d\n        end\n    end\n\n    dists\nend\n\n\nfunction floyd_warshall!(\n    dists::AbstractMatrix{W},                # minimum distance matrix (initialized to edge distances)\n    nexts::AbstractMatrix{Int})  where {W}   # nexts(i,j) = the next hop from i when traveling from i to j via shortest path\n\n    # argument checking\n\n    n = size(dists, 1)\n    if size(dists, 2) != n\n        throw(ArgumentError(\"dists should be a square matrix.\"))\n    end\n\n    if size(nexts) != (n, n)\n        throw(ArgumentError(\"nexts should be an n-by-n matrix.\"))\n    end\n\n    # initialize\n\n    for i = 1 : n\n        dists[i,i] = 0\n    end\n\n    for j = 1 : n, i = 1 : n\n        nexts[i,j] = isfinite(dists[i,j]) ? j : 0\n    end\n\n    # main loop\n\n    for k = 1 : n, i = 1 : n, j = 1 : n\n        d = dists[i,k] + dists[k,j]\n        if d < dists[i,j]\n            dists[i,j] = d\n            nexts[i,j] = nexts[i,k]\n        end\n    end\n\n    dists\nend\n\n\nfloyd_warshall(weights::AbstractMatrix) = floyd_warshall!(copy(weights))\n", "meta": {"hexsha": "9a07ca8a12217d72709692135867869e1d4197b2", "size": 1565, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/floyd_warshall.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Graphs.jl-86223c79-3864-5bf0-83f7-82e725a168b6", "max_stars_repo_head_hexsha": "b76b9914178a417085681167643af510547e8a0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2018-08-19T13:26:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-07T08:17:35.000Z", "max_issues_repo_path": "src/floyd_warshall.jl", "max_issues_repo_name": "JuliaAttic/OldGraphs.jl", "max_issues_repo_head_hexsha": "39a9c6efacc190ac79db47dd4dd951657058d2c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-02-20T22:05:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T15:20:41.000Z", "max_forks_repo_path": "src/floyd_warshall.jl", "max_forks_repo_name": "JuliaAttic/OldGraphs.jl", "max_forks_repo_head_hexsha": "39a9c6efacc190ac79db47dd4dd951657058d2c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-02-12T18:37:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-03T14:09:36.000Z", "avg_line_length": 21.7361111111, "max_line_length": 125, "alphanum_fraction": 0.5571884984, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.780909527048096}}
{"text": "\n\"\"\"\n  hexlattice(width, height, r)\n\nBuild a 2D simplex from a hexagonal grid.\n\nThe grid will cover the given width and height. Each edge in the grid\nwill be of length `r`. This returns a tuple with vertices as a Float64\narray of `(2, n)` and triangles as an Int64 array of `(3, m)`, where\ntriangle indices point into the vertices.\n\"\"\"\nfunction hexlattice(width, height, r)\n    # Us a Bravais lattice.\n    # Two vectors: r1, r2, of the same length.\n    # The angle between them is 120 degrees.\n    #\n    # a1 = (r, 0)\n    # a2 = (-r/sqrt(3), 2r/sqrt(3))\n    # x,y = i a1 + j a2\n    # x = ri - rj/2\n    # y = 2jr/√3\n    # m and n are the row count (x) and column count (y).\n    m, n = Int64.(ceil.([width / r, height * sqrt(3) / 2]))\n    # This is all about making a square region from a Bravais\n    # lattice that is tilted. We do that by coming up with a rule\n    # for which entries are saved.\n    isvertex((i, j)) = (0 <= (i-1) - (j-1) ÷ 2 < m) && (0 <= j-1 < n)\n\n    v = Dict{Tuple{Int64,Int64},Int64}()\n    vidx = 1\n    for j in 1:n\n        ioffset = (j - 1) ÷ 2\n        for i in (1 + ioffset):(m + ioffset)\n            @assert isvertex((i, j))\n            v[(i, j)] = vidx\n            vidx += 1\n        end\n    end\n    vertex = zeros(Float64, 2, length(v))\n    for ((i, j), idx) in v\n        vertex[:, idx] = [r * (i-1) - r * (j-1) / 2, 2 * r * (j-1) / 3]\n    end\n\n    # This is too many but we can trim at the end, faster than adding to array.\n    triangles_pad = zeros(Int64, 3, length(v))\n    triangle_cnt = 0\n    for (i, j) in keys(v)\n        # Each unit of the Bravais lattice is a parallelogram, so two triangles.\n        triangle = [\n                [(i, j), (i + 1, j), (i + 1, j + 1)]\n                [(i, j), (i + 1, j + 1), (i, j + 1)]\n                ]\n        for t in 1:2\n            if all(isvertex.(triangle[5]))\n                triangle_cnt += 1\n                triangles_pad[:, triangle_cnt] = [v[t] for t in triangle[t]]\n            end\n        end\n    end\n    triangles = triangles_pad[:, 1:triangle_cnt]\n    vertex, triangles\nend\n", "meta": {"hexsha": "d0791fb212da0448950a482c41b2efc466ca6716", "size": 2057, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hexlattice.jl", "max_stars_repo_name": "adolgert/simplexpop.jl", "max_stars_repo_head_hexsha": "4e403816f7b94002b8dff45db859ab45ecd8849b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hexlattice.jl", "max_issues_repo_name": "adolgert/simplexpop.jl", "max_issues_repo_head_hexsha": "4e403816f7b94002b8dff45db859ab45ecd8849b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hexlattice.jl", "max_forks_repo_name": "adolgert/simplexpop.jl", "max_forks_repo_head_hexsha": "4e403816f7b94002b8dff45db859ab45ecd8849b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-04T13:27:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-04T13:27:58.000Z", "avg_line_length": 32.6507936508, "max_line_length": 80, "alphanum_fraction": 0.5318424891, "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7808380039659775}}
{"text": "#=\nBy starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.\n\n3\n7 4\n2 4 6\n8 5 9 3\n\nThat is, 3 + 7 + 4 + 9 = 23.\n\nFind the maximum total from top to bottom of the triangle below:\n\n75\n95 64\n17 47 82\n18 35 87 10\n20 04 82 47 65\n19 01 23 75 03 34\n88 02 77 73 07 63 67\n99 65 04 28 06 16 70 92\n41 41 26 56 83 40 80 70 33\n41 48 72 33 47 32 37 16 94 29\n53 71 44 65 25 43 91 52 97 51 14\n70 11 33 28 77 73 17 78 39 68 17 57\n91 71 52 38 17 14 91 43 58 50 27 29 48\n63 66 04 68 89 53 67 30 73 16 69 87 40 31\n04 62 98 27 23 09 70 98 73 93 38 53 60 04 23\n\nNOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)\n=#\na = Array[\n[75],\n[95, 64],\n[17, 47, 82],\n[18, 35, 87, 10],\n[20, 04, 82, 47, 65],\n[19, 01, 23, 75, 03, 34],\n[88, 02, 77, 73, 07, 63, 67],\n[99, 65, 04, 28, 06, 16, 70, 92],\n[41, 41, 26, 56, 83, 40, 80, 70, 33],\n[41, 48, 72, 33, 47, 32, 37, 16, 94, 29],\n[53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],\n[70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],\n[91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],\n[63, 66, 04, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],\n[04, 62, 98, 27, 23, 09, 70, 98, 73, 93, 38, 53, 60, 04, 23]]\n\nfunction calc(arr)\n  result = Array[]\n  push!(result, arr[length(arr)])\n  for row in reverse(1:length(arr)-1)\n    nextrow = Int64[]\n    for column in 1:length(arr[row])\n      lowleft = last(result)[column]\n      lowright = last(result)[column+1]\n      center = arr[row][column]\n      push!(nextrow, max(center+lowleft, center+lowright))\n    end\n    push!(result, nextrow)\n  end\n  last(result)[1]\nend\n@time println(calc(a))\n\n", "meta": {"hexsha": "1e51455c8f7019a7c16e5bac85ee3b4a00b55976", "size": 1825, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p18.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p18.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p18.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 28.0769230769, "max_line_length": 255, "alphanum_fraction": 0.6246575342, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552536, "lm_q2_score": 0.8459424295406087, "lm_q1q2_score": 0.7808379985852538}}
{"text": "# This file calculates the third application in Y.-S. Chan, A. C. Fannjiang, and G. H. Paulino,\n# Integral equations with hypersingular kernels -- theory and applications to fracture mechanics,\n# Int. J. Eng. Sci., 41:683--720, 2003.\n\nusing ApproxFun, SingularIntegralEquations\n\n\nx = Fun(identity)\nw = 1/sqrt(1-x^2)\nd = domain(x)\nd2 = d^2\nB = [dirichlet(d);neumann(d)]\nH2 = Hilbert(d,2)\nH4 = Hilbert(d,4)\nϵ = 0.2\nL = -6ϵ^2*H4[w] + H2[w]\nf = -Fun(one)\n\nuSIE = [B;L]\\[zeros(4);f]\n@time uSIE = [B;L]\\[zeros(4);f]\nprintln(\"The length of uSIE is: \",length(uSIE))\nprintln(\"The extrema of uSIE are: \",extrema(uSIE))\n\ntest0 = uSIE/(1-x^2)^2\ntest = Fun(x->test0(x),Ultraspherical(1,d))\ntemp = 0.0\n[temp+= i*test.coefficients[i] for i=1:length(test)];\nprintln(\"The normalized generalized Stress Intensity Factors are: \",3ϵ*temp)\n", "meta": {"hexsha": "a2a25254d16b67e518bc4e6047a1b16bdd06cd9c", "size": 819, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Fracture_c.jl", "max_stars_repo_name": "JuliaPackageMirrors/SingularIntegralEquations.jl", "max_stars_repo_head_hexsha": "eb9e03d887d4450211f73df3569d27d3fa2e8942", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Fracture_c.jl", "max_issues_repo_name": "JuliaPackageMirrors/SingularIntegralEquations.jl", "max_issues_repo_head_hexsha": "eb9e03d887d4450211f73df3569d27d3fa2e8942", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Fracture_c.jl", "max_forks_repo_name": "JuliaPackageMirrors/SingularIntegralEquations.jl", "max_forks_repo_head_hexsha": "eb9e03d887d4450211f73df3569d27d3fa2e8942", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2413793103, "max_line_length": 97, "alphanum_fraction": 0.6752136752, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9496693716759489, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7808078349815754}}
{"text": "# # Algebraic networks\n#\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/generated/experimental/algebraic_nets.ipynb)\n#\n\nusing Catlab, Catlab.Doctrines, Catlab.Graphics\nusing Catlab.Experimental.AlgebraicNets\nusing Catlab.Experimental.MathFormulas\n\nimport TikzPictures\n#-\nR = Ob(AlgebraicNet, \"\\\\mathbb{R}\")\nf_sin = Hom(:sin, R, R)\nf_cos = Hom(:cos, R, R)\ndisplay(f_sin)\ndisplay(f_cos)\n#-\nf = compose(mcopy(R),otimes(f_sin,f_cos),mmerge(R))\n#-\nto_tikz(f, labels=true)\n#-\ncompile_expr(f; args=[:x])\n#-\nto_formula(f, [:x])\n#-\nf = compose(mcopy(R,3), otimes(f_sin, f_cos, f_sin))\n#-\nto_tikz(f)\n#-\ncompile_expr(f; args=[:x])\n#-\nf = compose(linear(2,R,R), f_sin, linear(2,R,R))\n#-\nto_tikz(f)\n#-\ncompile_expr(f; args=[:x])\n#-\nto_formula(f, [:x])\n#-\nf = compose(mcopy(R), otimes(id(R),Hom(:cos,R,R)), Hom(:*,otimes(R,R),R))\n#-\nto_tikz(f)\n#-\ncompile_expr(f; args=[:x])\n#-\nto_formula(f, [:x])\n", "meta": {"hexsha": "e5c3be82d6ecfa7f24f2f5248105ebbbc4f17b03", "size": 926, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/literate/experimental/algebraic_nets.jl", "max_stars_repo_name": "shivamkhare95/catlab_bayes", "max_stars_repo_head_hexsha": "35038d04735ab54c8ac17efb2caf9da87c291af5", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-03T21:31:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-03T21:31:20.000Z", "max_issues_repo_path": "experiments/CompAlgebra/docs/algebraic_nets.jl", "max_issues_repo_name": "jpfairbanks/Catlab.jl", "max_issues_repo_head_hexsha": "8a6410fd0faff8d3bcf294d89ea299c35218dee8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experiments/CompAlgebra/docs/algebraic_nets.jl", "max_forks_repo_name": "jpfairbanks/Catlab.jl", "max_forks_repo_head_hexsha": "8a6410fd0faff8d3bcf294d89ea299c35218dee8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7021276596, "max_line_length": 134, "alphanum_fraction": 0.6706263499, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7808078335368307}}
{"text": "#=\r\nCost and final layer delta functions.\r\nThese are paired to each type of output layer.\r\n=#\r\n\r\n################################################################################\r\n#\r\n# LinearOutputLayer\r\n#\r\n################################################################################\r\n\r\n########################################\r\n# Quadratic / [Sum of Squares Diff]       # ℝ\r\n########################################\r\n\r\n# J = 1/2 ∑ᵐ ∑ᵏ (h - y)²\r\n# h is a row vector and y is a column vector\r\nfunction quadratic_cost{F<:AbstractFloat}(h::Array{F}, y::Vector{F})\r\n    #length(y) == size(h, 2) || throw(DimensionMismatch(\"Inconsistent array sizes\"))\r\n    s = F(0)\r\n    @simd for i in eachindex(h)\r\n        @inbounds s += abs2(h[i] - y[i])\r\n    end\r\n    return s * F(0.5)\r\nend\r\n\r\n########################################\r\n# Linear Delta                            # ℝ^ 1 x num_obs\r\n########################################\r\n\r\n# Final layer delta function for regression\r\nfunction delta_linear!{F<:AbstractFloat}(Δ::Array{F}, h::Array{F}, y::Vector{F},\r\n                                         num_obs::F)\r\n\r\n    # Δ⁽ᴸ⁾ = 1/m (h - y)               (recall: A⁽ᴸ⁾ = h)\r\n    @simd for j in eachindex(y)\r\n        @inbounds Δ[j] = (h[j] - y[j]) / num_obs\r\n    end\r\nend\r\n\r\n\r\n################################################################################\r\n#\r\n# LogisticOutputLayer\r\n#\r\n################################################################################\r\n\r\n########################################\r\n# Cross Entropy                           # ℝ\r\n########################################\r\n\r\n# J = ∑ᵐ - y * log(h) - (1-y) log(1-h)\r\n# h is a row vector and y is a column vector\r\nfunction cross_entropy_cost{F<:AbstractFloat, T<:Integer}(h::Array{F}, y::Vector{T})\r\n    #length(y) == size(h, 2) || throw(DimensionMismatch(\"Inconsistent array sizes\"))\r\n    s = F(0)\r\n    @simd for j in eachindex(h)\r\n        @inbounds if y[j] == T(1)\r\n                      s -= log(h[j])\r\n                  else\r\n                      s -= log1p(-h[j])\r\n                  end\r\n    end\r\n    s\r\nend\r\n\r\n########################################\r\n# Logistic Delta                          # ℝ^ 1 x num_obs\r\n########################################\r\n\r\n# Final layer delta function for regression\r\nfunction delta_logistic!{F<:AbstractFloat, T<:Integer}(Δ::Array{F}, h::Array{F},\r\n                                                       y::Vector{T}, num_obs::F)\r\n\r\n    # Δ⁽ᴸ⁾ = h - y               (recall: A⁽ᴸ⁾ = h)\r\n    @simd for j in eachindex(y)\r\n        @inbounds Δ[j] = (h[j] - y[j]) / num_obs\r\n    end\r\nend\r\n\r\n\r\n################################################################################\r\n#\r\n# SoftmaxOutputLayer\r\n#\r\n################################################################################\r\n\r\n########################################\r\n# Log Loss                                # ℝ\r\n########################################\r\n\r\n# J = ∑ᵐ ∑ᵏ - 1{y=k} log(h)\r\nfunction log_loss_cost{F<:AbstractFloat, T<:Integer}(H::Array{F}, y::Vector{T})\r\n    length(y) == size(H, 2) || throw(DimensionMismatch(\"Inconsistent array sizes\"))\r\n    s = F(0)\r\n    for j in eachindex(y)\r\n        @inbounds s -= log(H[y[j], j])\r\n    end\r\n    s\r\nend\r\n\r\n########################################\r\n# Softmax Delta                          # ℝ^ num_classes x num_obs\r\n########################################\r\n\r\n# Final layer delta function for classification\r\nfunction delta_softmax!{F<:AbstractFloat, T<:Integer}(Δ::Array{F}, H::Array{F},\r\n                                                      y::Vector{T}, num_obs::F)\r\n\r\n    # Δ⁽ᴸ⁾ = 1/m (H - Y)               (recall: A⁽ᴸ⁾ = H)\r\n    copy!(Δ, H)\r\n    for j in eachindex(y)\r\n        @inbounds Δ[y[j], j] -= F(1)\r\n    end\r\n\r\n    # Divide by m\r\n    broadcast!(/, Δ, Δ, num_obs)\r\nend\r\n\r\n\r\n################################################################################\r\n#\r\n# MultiLinearOutputLayer\r\n#\r\n################################################################################\r\n\r\n########################################\r\n# Quadratic                              # ℝ\r\n########################################\r\n\r\n# J = 1/2 ∑ᵐ ∑ᵏ (h - y)²\r\nfunction quadratic_cost{F<:AbstractFloat}(H::Array{F}, Y::Array{F})\r\n    size(H) == size(Y) || throw(DimensionMismatch(\"Inconsistent array sizes\"))\r\n    s = F(0)\r\n    @simd for i in eachindex(H)\r\n        @inbounds s += abs2(H[i] - Y[i])\r\n    end\r\n    return s * F(0.5)\r\nend\r\n\r\n########################################\r\n# Multi Linear Delta                     # ℝ^ num_outputs x num_obs\r\n########################################\r\n\r\n# Final layer delta function for regression\r\nfunction delta_linear!{F<:AbstractFloat}(Δ::Array{F}, H::Array{F}, Y::Array{F},\r\n                                         num_obs::F)\r\n\r\n    # Δ⁽ᴸ⁾ = 1/m (h - y)               (recall: A⁽ᴸ⁾ = h)\r\n\r\n    @simd for j in eachindex(Y)\r\n        @inbounds Δ[j] = (H[j] - Y[j]) / num_obs\r\n    end\r\nend\r\n", "meta": {"hexsha": "ef502e6d21d3776f63a8d0da223ce321f39f2c2f", "size": 4932, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cost_and_delta.jl", "max_stars_repo_name": "Wedg/Alice.jl", "max_stars_repo_head_hexsha": "48884d8dfaca3f987e69423dfc63e1f0881c7dc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cost_and_delta.jl", "max_issues_repo_name": "Wedg/Alice.jl", "max_issues_repo_head_hexsha": "48884d8dfaca3f987e69423dfc63e1f0881c7dc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cost_and_delta.jl", "max_forks_repo_name": "Wedg/Alice.jl", "max_forks_repo_head_hexsha": "48884d8dfaca3f987e69423dfc63e1f0881c7dc7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8193548387, "max_line_length": 85, "alphanum_fraction": 0.3594890511, "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.780807831741568}}
{"text": "# https://julianlsolvers.github.io/Optim.jl/stable/#examples/generated/ipnewton_basics/\n\nusing Optim\n\nfun(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2\n\nfunction con2_c!(c, x)\n    c[1] = x[1]^2 + x[2]^2     ## First constraint\n    c[2] = x[2]*sin(x[1])-x[1] ## Second constraint\n    return c\nend\n\nx0 = [0.25, 0.25]\ndf = TwiceDifferentiable(fun, x0)\n\nlc = [-Inf, 0.0]; uc = [0.5^2, 0.0]\nlx = [-0.5, -0.5]; ux = [0.5, 0.5]\ndfc = TwiceDifferentiableConstraints(con2_c!, lx, ux, lc, uc)\n\nres = optimize(df, dfc, x0, IPNewton(), Optim.Options(show_trace=true))\ndisplay(res)\n\nprintln(res.minimum)\nprintln(res.minimizer)\n", "meta": {"hexsha": "190abb486cb7cdeba623fcf35624f75c6bafd4f2", "size": 616, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "debug/optim-mwe.jl", "max_stars_repo_name": "lanl-ansi/rosetta-opf", "max_stars_repo_head_hexsha": "09e76f505c04cc788256a4f3f479033ba6abe1f0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2022-03-25T19:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:42:04.000Z", "max_issues_repo_path": "debug/optim-mwe.jl", "max_issues_repo_name": "lanl-ansi/rosetta-opf", "max_issues_repo_head_hexsha": "09e76f505c04cc788256a4f3f479033ba6abe1f0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2022-03-28T01:10:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:44:10.000Z", "max_forks_repo_path": "debug/optim-mwe.jl", "max_forks_repo_name": "lanl-ansi/rosetta-opf", "max_forks_repo_head_hexsha": "09e76f505c04cc788256a4f3f479033ba6abe1f0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.64, "max_line_length": 87, "alphanum_fraction": 0.6201298701, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7808078291256348}}
{"text": "\"\"\"\n    Construct{T <: Number} <: Number\n\nAn abstract Cayley-Dickson construct.\n\"\"\"\nabstract type Construct{T <: Number} <: Number end\n\n\"\"\"\n    array(z::Construct) -> Array\n\nReturn an array with all the `Real` components of `z`.\n\"\"\"\nfunction array(z::Construct)\n    vcat(real(z), unreal(z))\nend\n\n\"\"\"\n    iszero(z::Construct) -> Bool\n\nReturn `true` if all `Real` components of `z` are zero.\n\"\"\"\nfunction iszero(z::Construct)\n    iszero(array(z))\nend\n\n\"\"\"\n    isreal(z::Construct) -> Bool\n\nReturn `true` if the unreal part of `z` is zero.\n\"\"\"\nfunction isreal(z::Construct)\n    iszero(unreal(z))\nend\n\n\"\"\"\n    (+)(z::Construct)\n\nThe identity operation on Cayley-Dickson constructs.\n\"\"\"\nfunction (+)(z::Construct)\n    z\nend\n\n\"\"\"\n    commutator(x::Construct, y::Construct)\n\nMeasure the failure of commutativity of the multiplication operation:\n```julia\n    (x * y) - (y * x)\n```\nIf `commutator(x, y)` is zero, then the multiplication operation is commutative.\n\"\"\"\nfunction commutator(x::Construct, y::Construct)\n    (x * y) - (y * x)\nend\n\n\"\"\"\n    anti_commutator(x::Construct, y::Construct)\n\nMeasure the failure of anti-commutativity of the multiplication operation:\n```julia\n    (x * y) + (y * x)\n```\nIf `anti_commutator(x, y)` is zero, then the multiplication operation is anti-commutative.\n\"\"\"\nfunction anti_commutator(x::Construct, y::Construct)\n    (x * y) + (y * x)\nend\n\n\"\"\"\n    associator(x::Construct, y::Construct, z::Construct)\n\nMeasure the failure of associativity of the multiplication operation:\n```julia\n    ((x * y) * z) - (x * (y * z))\n```\nIf `associator(x, y, z)` is zero, then the multiplication operation is associative.\n\"\"\"\nfunction associator(x::Construct, y::Construct, z::Construct)\n    ((x * y) * z) - (x * (y * z))\nend\n\n\"\"\"\n    anti_associator(x::Construct, y::Construct, z::Construct)\n\nMeasure the failure of anti-associativity of the multiplication operation:\n```julia\n    ((x * y) * z) + (x * (y * z))\n```\nIf `anti_associator(x, y, z)` is zero, then the multiplication operation is anti-associative.\n\"\"\"\nfunction anti_associator(x::Construct, y::Construct, z::Construct)\n    ((x * y) * z) + (x * (y * z))\nend\n\n\"\"\"\n    jacobiator(x::Construct, y::Construct, z::Construct)\n\nMeasure the failure of the multiplication operation to satisfy the Jacobi identity:\n```julia\n    ((x * y) * z) + ((z * x) * y) + ((y * z) * x)\n```\nIf `jacobiator(x, y, z)` is zero, then the multiplication operation satisfies the Jacobi\nidentity.\n\"\"\"\nfunction jacobiator(x::Construct, y::Construct, z::Construct)\n    ((x * y) * z) + ((z * x) * y) + ((y * z) * x)\nend\n\n\"\"\"\n    alternatorL(x::Construct, y::Construct)\n\nMeasure the failure of the multiplication operation to be left-alternative:\n```julia\n    ((x * x) * y) - (x * (x * y))\n```\nIf `alternatorL(x, y)` is zero, then the multiplication operation is left-alternative.\n\"\"\"\nfunction alternatorL(x::Construct, y::Construct)\n    associator(x, x, y)\nend\n\n\"\"\"\n    anti_alternatorL(x::Construct, y::Construct)\n\nMeasure the failure of the multiplication operation to be anti-left-alternative:\n```julia\n    ((x * x) * y) + (x * (x * y))\n```\nIf `anti_alternatorL(x, y)` is zero, then the multiplication operation is anti-left-alternative.\n\"\"\"\nfunction anti_alternatorL(x::Construct, y::Construct)\n    anti_associator(x, x, y)\nend\n\n\"\"\"\n    alternatorR(x::Construct, y::Construct)\n\nMeasure the failure of the multiplication operation to be right-alternative:\n```julia\n    ((x * y) * y) - (x * (y * y))\n```\nIf `alternatorR(x, y)` is zero, then the multiplication operation is right-alternative.\n\"\"\"\nfunction alternatorR(x::Construct, y::Construct)\n    associator(x, y, y)\nend\n\n\"\"\"\n    anti_alternatorR(x::Construct, y::Construct)\n\nMeasure the failure of the multiplication operation to be anti-right-alternative:\n```julia\n    ((x * y) * y) + (x * (y * y))\n```\nIf `anti_alternatorR(x, y)` is zero, then the multiplication operation is anti-right-alternative.\n\"\"\"\nfunction anti_alternatorR(x::Construct, y::Construct)\n    anti_associator(x, y, y)\nend\n\n\"\"\"\n    flexator(x::Construct, y::Construct)\n\nMeasure the failure of the multiplication operation to be flexible:\n```julia\n    ((x * y) * x) - (x * (y * x))\n```\nIf `flexator(x, y)` is zero, then the multiplication operation is flexible.\n\"\"\"\nfunction flexator(x::Construct, y::Construct)\n    associator(x, y, x)\nend\n\n\"\"\"\n    anti_flexator(x::Construct, y::Construct)\n\nMeasure the failure of the multiplication operation to be anti-flexible:\n```julia\n    ((x * y) * x) + (x * (y * x))\n```\nIf `anti_flexator(x, y)` is zero, then the multiplication operation is anti-flexible.\n\"\"\"\nfunction anti_flexator(x::Construct, y::Construct)\n    anti_associator(x, y, x)\nend\n\n\"\"\"\n    inv(z::Construct)\n\nReturn the multiplicative inverse of a Cayley-Dickson construct.\nIf `z` is a zero divisor, then an `ErrorException` is thrown.\n\"\"\"\nfunction inv(z::Construct)\n    if iszerodivisor(z)\n        error(ZeroDivisorInverse)\n    end\n\n    conj(z) / quadrance(z)\nend\n\n\"\"\"\n    (/)(x::Construct, y::Construct)\n\nNaive right quotient of two Cayley-Dickson constructs.\nEquivalent to multiplying `x` on the right by the inverse of `y`.\n\"\"\"\nfunction (/)(x::Construct, y::Construct)\n    x * inv(y)\nend\n\n\"\"\"\n    (\\\\)(y::Construct, x::Construct)\n\nNaive left quotient of two Cayley-Dickson constructs.\nEquivalent to multiplying `x` on the left by the inverse of `y`.\n\"\"\"\nfunction (\\)(y::Construct, x::Construct)\n    inv(y) * x\nend\n\n\"\"\"\n    (/)(a::Real, z::Construct)\n\nEquivalent to multiplying the inverse of `z` by `a`.\n\"\"\"\nfunction (/)(a::Real, z::Construct)\n    a * inv(z)\nend\n\n\"\"\"\n    (\\\\)(z::Construct, a::Real)\n\nEquivalent to multiplying the inverse of `z` by `a`.\n\"\"\"\nfunction (\\)(z::Construct, a::Real)\n    inv(z) * a\nend\n\n\"\"\"\n    convert(::Type{T}, z::Construct) where T <: Real\n\nConvert a Cayley-Dickson construct to a real number.\nIf `z` is not real (i.e. has non-zero unreal part), then an `InexactError` is\nthrown.\n\"\"\"\nfunction convert(::Type{T}, z::Construct) where T <: Real\n    if !isreal(z)\n        throw(InexactError())\n    end\n\n    convert(T, real(z))\nend\n\n\"\"\"\n    convert(::Type{T}, z::T) where T <: Construct\n\nThe trivial conversion. Equivalent to the identity operation.\n\"\"\"\nfunction convert(::Type{T}, z::T) where T <: Construct\n    z\nend\n\n\"\"\"\n    convert(::Type{T}, a::Real) where T <: Construct\n\nConvert a real number into a Cayley-Dickson construct.\n\"\"\"\nfunction convert(::Type{T}, a::Real) where T <: Construct\n    T(a)\nend\n", "meta": {"hexsha": "3aea9843a03afe6f73b766315f06b558b15184e7", "size": 6407, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Construct.jl", "max_stars_repo_name": "meirizarrygelpi/CayleyDickson.jl", "max_stars_repo_head_hexsha": "cf9c69907bee082fbb7b94bf956a59fc50c0fca8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-07-20T20:47:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T01:13:37.000Z", "max_issues_repo_path": "src/Construct.jl", "max_issues_repo_name": "meirizarrygelpi/CayleyDickson.jl", "max_issues_repo_head_hexsha": "cf9c69907bee082fbb7b94bf956a59fc50c0fca8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Construct.jl", "max_forks_repo_name": "meirizarrygelpi/CayleyDickson.jl", "max_forks_repo_head_hexsha": "cf9c69907bee082fbb7b94bf956a59fc50c0fca8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-17T22:58:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-17T22:58:29.000Z", "avg_line_length": 23.5551470588, "max_line_length": 97, "alphanum_fraction": 0.6542843765, "num_tokens": 1811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.8479677660619634, "lm_q1q2_score": 0.7807999663213866}}
{"text": "export AbstractInnerProduct, EuclideanIP, WeightedIP, euclidean_distance, euclidean_norm,\n       init_weight!, change_weight!, norm2, inner, distance\n\n\nabstract type AbstractInnerProduct end\n\nstruct EuclideanIP <: AbstractInnerProduct end\n\n\"\"\"\n    WeightedIP(weight)\n\nRepresents a weighted euclidean inner product.\n\"\"\"\nstruct WeightedIP{T<:Real} <: AbstractInnerProduct\n    weight::Vector{T} # The applied weights are 1 / w[i]\nend\nWeightedIP(x::AbstractVector) = WeightedIP(zeros(real(eltype(x)), length(x)))\n\n\"\"\"\n    distance(u, v, inner_product=EuclideanIP)\n\nCompute the distance ||u-v|| with the norm induced by `inner_product`.\nIf `inner_product === nothing` the euclidean scalar product is used.\n\"\"\"\nfunction distance(x::AbstractVector, y::AbstractVector, ::EuclideanIP=EuclideanIP())\n    @boundscheck length(x) == length(y)\n    n = length(x)\n    @inbounds d = abs2(x[1] - y[1])\n    @inbounds for i in 2:n\n        @fastmath d += abs2(x[i] - y[i])\n    end\n    sqrt(d)\nend\nfunction distance(x::AbstractVector, y::AbstractVector, in::WeightedIP)\n    @boundscheck length(in.weight) == length(x) == length(y)\n    w = in.weight\n    @inbounds d = abs2(x[1] - y[1]) / (w[1]^2)\n    for i in 2:length(x)\n        @inbounds d += abs2(x[i] - y[i]) / (w[i]^2)\n    end\n    sqrt(d)\nend\n\n\nfunction norm2(x::AbstractVector, ::EuclideanIP=EuclideanIP())\n    out = zero(real(eltype(x)))\n    for i in eachindex(x)\n        @inbounds out += abs2(x[i])\n    end\n    out\nend\nfunction norm2(x::AbstractVector, in::WeightedIP)\n    @boundscheck length(in.weight) == length(x)\n    out = zero(real(eltype(x)))\n    w = in.weight\n    for i in eachindex(x)\n        @inbounds out += abs2(x[i]) / (w[i]^2)\n    end\n    out\nend\nLinearAlgebra.norm(x::AbstractVector, ip::AbstractInnerProduct) = sqrt(norm2(x, ip))\n\n(ip::EuclideanIP)(x::AbstractVector) = LinearAlgebra.norm(x, ip)\n(ip::WeightedIP)(x::AbstractVector) = LinearAlgebra.norm(x, ip)\n", "meta": {"hexsha": "fd3c0e0695515034083aea9d9e9fb01642253ac1", "size": 1910, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utilities/inner.jl", "max_stars_repo_name": "KristofferC/HomotopyContinuation.jl", "max_stars_repo_head_hexsha": "66968c579db9716a41ff4011039d28ec32f2ddc3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utilities/inner.jl", "max_issues_repo_name": "KristofferC/HomotopyContinuation.jl", "max_issues_repo_head_hexsha": "66968c579db9716a41ff4011039d28ec32f2ddc3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utilities/inner.jl", "max_forks_repo_name": "KristofferC/HomotopyContinuation.jl", "max_forks_repo_head_hexsha": "66968c579db9716a41ff4011039d28ec32f2ddc3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3846153846, "max_line_length": 89, "alphanum_fraction": 0.6691099476, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7807999611634365}}
{"text": "#=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=#\n# Problem set 1 solutions\n# Written by Tyler Ransom\n# Commented by Giuseppe Grasso\n#=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=#\n\nusing DataFrames\nusing FreqTables\nusing CSV\nusing JLD\nusing Random\nusing LinearAlgebra\nusing Statistics\nusing Distributions\ncd(\"/Users/peppegrass/Documents/GitHub/fall-2020/ProblemSets/PS1-julia-intro/\") # GG: sets working directory\npwd() ## GG: prints working directory\nreaddir() # GG: equivalent to -ls- to see elements of working directory\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# Question 1\n# Initializing variables and practice with basic matrix operations\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n\n# a. Set the seed\nRandom.seed!(1234)\n#=\nGG: It seems to me that Random.seed!() only applies to the next command.\nHence the use of function q1() so that it applies to everything.\nBut I'm not sure about it.\n=#\n\n#=\nGG: The content of the function cannot be called from the .jl\nYou either copy and paste it in the REPL or call the functions (as done in the end of this script)\n=#\nfunction q1()\n    ## a. i.-iv. create matrices\n\n    # A 10×7- random numbers distributed U [−5,10]\n    A = 15*rand(10,7).-5 # GG: same result as using Distributions A=rand(Uniform(-5,10),10,7). Not sure why you have 15 instead of 10 here, but it works.\n\n    # B 10×7- random numbers distributed N (−2,15) [st dev is 15]\n    B = 15*randn(10,7).-2 # GG: same result as using Distributions B=rand(Normal(-2,15),10,7)\n\n    # C 5×7- the ﬁrst 5 rows and ﬁrst 5 columns of A and the last two columns and ﬁrst 5 rows of B\n    C = cat(A[1:5,1:5],B[1:5,end-1:end]; dims=2) # GG: notice end arguments\n\n    # D 10×7- where D i,j= A i,jif A i,j≤ 0, or 0 otherwise\n    D = A.*(A.<=0) # GG: D contains only negative elements of A; rest filled with 0s\n    # GG: very elegant subsetting; had no idea how to do it\n\n    ## b. Use a built-in Julia function to list the number of elements of A\n    println(length(A))\n\n    ## c. Use a series of built-in Julia functions to list the number of unique elements of D\n    println(length(unique(A)))\n\n    ## d. Using the reshape() function, create a new matrix called E which is the ‘vec’ operator applied to B.\n    ## Can you ﬁnd an easier way to accomplish this?\n\n    # one way:\n    E = reshape(B,length(B)) # GG: piles columns of B one above the other\n    # easy way:\n    E = B[:] ## GG: simple as that\n\n    ## e. Create a new array called F which is 3-dimensional and contains\n    ## A in the ﬁrst column of the third dimension and\n    ## B in the second column of the third dimension\n    F = cat(A,B; dims=3) # GG: making a cuboid (3-dimensional tensor) out of matrices A and B; see https://improbable-research.github.io/keanu/docs/tensors/\n\n    ## f. Use the permutedims() function to twist F so that it is now F 2×10×7 instead of F 10×7×2 . Save this new matrix as F.\n    F = permutedims(F, [3 1 2]) # GG: now F has 7 third dimensions, each containing a 2x10 matrix\n\n    ## g. Create a matrix G which is equal to B ⊗ C (the Kronecker product of B and C). What happens when you try C ⊗ F?\n    G = kron(B,C) # GG: A (5x10=50)x(7x7=49) matrix; see https://en.wikipedia.org/wiki/Kronecker_product\n    #kron(C,F) # it does work; not sure whether it is that tensor of different dimension cannot be kronecher-multiplied (don't think so) or that this Julia command isn't suited for such operation\n\n    ## h. Save the matrices A, B, C, D, E, F and G as a .jld ﬁle named matrixpractice.\n    save(\"matrixpractice.jld\",\"A\",A,\"B\",B,\"C\",C,\"D\",D,\"E\",E,\"F\",F,\"G\",G)\n        #=\n        GG: \"matrixpractice.jld\" can be read back with\n        d = load(\"matrixpractice.jld\")\n        where d is a dictionary\n        Other examples of .jld loading are provided in Exercise 4\n        =#\n\n    ## i. Save only the matrices A, B, C, and D as a .jld ﬁle called firstmatrix.\n    save(\"firstmatrix.jld\",\"A\",A,\"B\",B,\"C\",C,\"D\",D)\n\n    ## j. Export C as a .csv ﬁle called Cmatrix. You will ﬁrst need to transform C into a DataFrame.\n    CSV.write(\"Cmatrix.csv\",DataFrame(C))\n\n    ## k. Export D as a tab-delimited .dat ﬁle called Dmatrix. You will ﬁrst need to transform D into a DataFrame.\n    CSV.write(\"Dmatrix.dat\",DataFrame(D); delim=\"\\t\")\n    return A,B,C,D\nend\n#=\nl. Wrap a function deﬁnition around all of the code for question 1. Call the function q1().\nThe function should have 0 inputs and should output the arrays A, B, C and D.\nAt the very bottom of your script you should add the code A,B,C,D = q1().\n=#\n\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# Question 2\n# Practice with loops and comprehensions\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n\nfunction q2(A,B,C)\n    ## a. Write a loop or use a comprehension that computes the element-by-element product of A and B. Name the new matrix AB.\n    ## Create a matrix called AB2 that accomplishes this task without a loop or comprehension.\n\n    #=\n    GG: Using a COMPREHENSION to compute the element-by-element product of A and B; which has same dimension 10x7\n    What is a comprehension? It allows the user in 1 line of code to create an object that could be a complex formula.\n    e.g. computing a present value by PV = sum([β^t*Y[t] for t=1:T])\n    or a shift-share instrument for what matters\n    =#\n    AB = [A[i,j]*B[i,j] for i=1:size(A,1),j=1:size(A,2)] # GG: could have been size(B,1) and size(B,2); what matter are the 1 and 2 to indicate dimensions\n\n    AB2 = A.*B ## GG: doing it with the ELEMENT-BY-ELEMENT multiplication oparator .*\n\n    ## b. Write a loop that creates a column vector called Cprime which contains only the elements of C that are between -5 and 5 (inclusive).\n    ## Create a vector called Cprime2 which does this calculation without a loop.\n    Cprime = [] # GG: creating empty array\n    for j=1:size(C,2)\n        for i=1:size(C,1)\n            if C[i,j]>=-5 && C[i,j]<=5 ## GG: declaring the IF condition here; note usage of && coz boolean here\n                push!(Cprime,C[i,j]) ## GG: sounds like some sort of \"copy\"; \"pushes\" only element satisfying IF clause\n            end\n        end\n    end\n    Cprime2 = C[(C.>=-5) .& (C.<=5)]\n\n    ## c. Using loops or comprehensions, create a 3-dimensional array called X that is of dimension N × K × T where\n    ## N = 15,169, K = 6, and T = 5. For all t, the columns of X should be (in order):\n    ## - an intercept (i.e. vector of ones)\n    ## - a dummy variable that is 1 with probability .75∗(6−t)/5\n    ## - a continuous variable distributed normal with mean 15+t−1 and standard deviation 5(t−1)\n        ## GG: apparently (mean).+(sd).*randn(N,1) generates a normal rv with mean and sd\n    ## - a continuous variable distributed normal with mean π(6−t)/3 and standard deviation 1/e\n    ## - a discrete variable distributed “discrete normal” with mean 12 and standard deviation 2.19. (A discrete normal random variable is properly called a binomial random variable. The distribution described above can be implemented by choosing binomial parameters n and p where n = 20 and p = 0.6. Use the following code (after loading Julia’s Distributions package) to generate this vector of X: rand(Binomial(20,0.6),N), where N is the length of the vector\n    ## - a discrete variable distributed binomial with n = 20 and p = 0.5\n    N = 15169\n    K = 6\n    T = 5\n    #=\n    GG: cat is for CONCATENATION\n    WOW this is basically generating a dataset in one line :O\n    The dataset has N=15169 observations, K=6 variables, and T=5 time periods\n    =#\n    X = cat([cat([ones(N,1) rand(N,1).<=(0.75*(6-t)/5) (15+t-1).+(5*(t-1)).*randn(N,1) (π*(6-t)/3).+(1/exp(1)).*randn(N,1) rand(Binomial(20,0.6),N) rand(Binomial(20,0.5),N)];dims=3) for t=1:T]...;dims=3) # discrete_normal binomial\n\n    ## d. Use comprehensions to create a matrix β which is K × T and whose elements evolve across time in the following fashion:\n    ## - 1,1.25,1.5,...\n    ## - ln(t)\n    ## - −√t\n    ## - exp{t}-exp{t+1}\n    ## - t\n    ## - t/3\n    β = vcat([cat([1+0.25*(t-1) log(t) -sqrt(t) exp(t)-exp(t+1) t t/3];dims=1) for t=1:T]...)' ## GG: using vertical concatenation here; mind the transpose\n\n    ## e. Use comprehensions to create a matrix Y which is N × T deﬁned by Y_t= X_t β_t + ε_t , where ε_t ∼ iid N (0,σ=.36)\n    Y = hcat([cat(X[:,:,t]*β[:,t] + .36*randn(N,1);dims=2) for t=1:T]...) # GG: 3-dots at the end have to do with the layout given by hcat\n    return nothing\nend\n\n#=\nf. Wrap a function deﬁnition around all of the code for question 2. Call the function q2().\nThe function should have take as inputs the arrays A, B and C. It should return nothing.\nAt the very bottom of your script you should add the code q2(A,B,C). Make sure q2() gets called after q1()!\n=#\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# Question 3\n# Reading in Data and calculating summary statistics\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n\nfunction q3()\n    ## a. Clear the workspace and import the ﬁle nlsw88.csv into Julia as a DataFrame.\n    ## Make sure you appropriately convert missing values and variable names. Save the result as nlsw88.jld.\n    nlsw88 = CSV.read(\"nlsw88.csv\") # GG: kinda -import csv-\n    save(\"nlsw88.jld\",\"nlsw88\",nlsw88) # GG: kinda -save-\n\n    ## b. What percentage of the sample has never been married? What percentage are college graduates?\n    mean(nlsw88.never_married) # GG: kinda -summarize- but just returning the mean\n    mean(nlsw88.collgrad)\n\n    ## c. Use the tabulate command to report what percentage of the sample is in each race category\n    freqtable(nlsw88, :race) # GG: oneway -tabulate race-; gotta have that colon to work though\n\n    ## d. Use the describe() function to create a matrix called summarystats which lists the mean, median,\n    ## standard deviation, min, max, number of unique elements, and interquartile range (75th percentile minus\n    ## 25th percentile) of the data frame. How many grade observations are missing?\n    summarystats = describe(nlsw88)\n    #=\n    GG: to see how many grade observation are missing you gotta visualize all rows using\n    show(summarystats, allrows=true)\n    see https://juliadata.github.io/DataFrames.jl/stable/man/getting_started/\n    =#\n\n    ## e. Show the joint distribution of industry and occupation using a cross-tabulation.\n    freqtable(nlsw88, :industry, :occupation) # GG: twoway tabulate\n\n    ## f. Tabulate the mean wage over industry and occupation categories.\n    ## Hint: you should ﬁrst subset the data frame to only include the columns industry, occupation and wage.\n    ## You should then follow the “split-apply-combine” directions here.\n    wageonly = nlsw88[:,[:industry,:occupation,:wage]] # GG: [SPLIT] creating a sub-dataframe from nlsw88\n    grouper = groupby(wageonly, [:industry,:occupation]) # GG: [APPLY] created a GroupedDataFrame whereby observations are grouped, e.g. 12 observations/rows with industry=5 and occupation=6\n    combine(grouper, valuecols(grouper) .=> mean) # GG: [COMBINE] essentially \"collapsing\" to means by groups defined in previous step\n    return nothing\nend\n\n#=\ng. Wrap a function deﬁnition around all of the code for question 3. Call the function q3().\nThe function should have no inputs and no outputs. At the very bottom of your script you should add the code q3().\n=#\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# Question 4\n# Practice with functions\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n\nfunction q4()\n    ## a. Load firstmatrix.jld.\n    mats = load(\"firstmatrix.jld\") # GG: loads .jld file in dictionary \"mats\"\n    A = mats[\"A\"] # GG: creating/extracting array from \"mats\"\n    B = mats[\"B\"]\n    C = mats[\"C\"]\n    D = mats[\"D\"]\n\n    ## b. Write a function called matrixops that takes as inputs the matrices A and B from question (a) of problem 1 and has\n    ## three outputs: (i) the element-by-element product of the inputs, (ii) the product A ′ B, and (iii) the sum of all the\n    ## elements of A+B.\n    function matrixops(m1,m2) # GG: defining function matrixops to have two argumets/inputs\n        ## c. Starting on line 2 of the function, write a comment that explains what matrixops does.\n        ## this function computes the following matrix formulas: i) element-wise multiplication; ii) transpose multiplication; iii) sum of the elementwise product\n\n        ## e. Just before the ﬁrst executable line of matrixops.m (i.e. right after the ﬁrst-line comments),\n        ## write an if statement which gives an error if the two inputs are not the same size. Have the error say “inputs must have the same size.”\n        if size(m1)!=size(m2)\n            error(\"inputs must have the same size.\") # GG: creating an error which stops function if matrices aren't the same size (needed for element-wise multiplication)\n        end\n        ret1 = m1.*m2\n        ret2 = m1'*m2 # GG: '* is operator for transpose multiplication\n        ret3 = sum(m1+m2)\n        return ret1,ret2,ret3\n    end\n\n    ## d. Evaluate [GG: the returns one-ny-one in the REPL and the function itself] matrixops() using A and B from question (a) of problem 1\n    matrixops(A,B) # GG: everything goes fine\n\n    ## f. Evaluate matrixops.m using C and D from question (a) of problem 1. What happens?\n    # matrixops(C,D) # GG: since C and D aren't the same size the programmed error is raised\n\n    ## g. Now evaluate matrixops.m using ttl_exp and wage from nlsw88.jld.\n    ## Hint: before doing this, you will need to convert the data frame columns to Arrays.\n    ## e.g. convert(Array,nlsw88.ttl_exp), depending on what you called the data frame object [I called it nlsw88].\n    #= GG: Two lines below actually not working. Apparently, it has to do with the conversion that are purported to do next...\n    mat1 = load(\"nlsw88.jld\")\n    nlsw88 = mat1[\"nlsw88\"]\n    ... Instead a re-import from the CSV and create the DataFrame from scratch\n    =#\n    nlsw88 = CSV.read(\"nlsw88.csv\",DataFrame;) # GG: nlsw88 = CSV.read(\"nlsw88.csv\") would work to but appears to be deprecated in favour of the one used\n    matrixops(convert(Array,nlsw88.ttl_exp),convert(Array,nlsw88.wage)) # GG: evaluating matrixops() on the converted versions of nlsw88.ttl_exp and nlsw88.wage\n    return nothing\nend\n\n\n#=\nh. Wrap a function deﬁnition around all of the code for question 4. Call the function q4().\nThe function should have no inputs or outputs. At the very bottom of your script you should add the code q4().\n=#\n\n# Call the functions defined above\nA,B,C,D = q1()\nq2(A,B,C)\nq3()\nq4()\n", "meta": {"hexsha": "e793cd6a634b5848dea73e61b9e1922224435622", "size": 14450, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS1-julia-intro/PS1solutions_GG.jl", "max_stars_repo_name": "peppegrass/fall-2020", "max_stars_repo_head_hexsha": "03f90548ca4d800146bbeaf9dceca917a21c1195", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-01T08:58:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-01T08:58:14.000Z", "max_issues_repo_path": "ProblemSets/PS1-julia-intro/PS1solutions_GG.jl", "max_issues_repo_name": "peppegrass/fall-2020", "max_issues_repo_head_hexsha": "03f90548ca4d800146bbeaf9dceca917a21c1195", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS1-julia-intro/PS1solutions_GG.jl", "max_forks_repo_name": "peppegrass/fall-2020", "max_forks_repo_head_hexsha": "03f90548ca4d800146bbeaf9dceca917a21c1195", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-12T17:24:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-12T17:24:05.000Z", "avg_line_length": 51.7921146953, "max_line_length": 461, "alphanum_fraction": 0.6602076125, "num_tokens": 4090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.9207896720870642, "lm_q1q2_score": 0.7807999577148583}}
{"text": "\"\"\"\n# GoldenSection\n## Constructor\n```julia\n    GoldenSection(;)\n```\n\n## Description\nThe `GoldenSection` method seeks to minimize a univariate function on an interval\n`[a, b]`. At all times the algorithm maintains a tuple of three minimizer candidates\n`(c, d, e)` where ``c<d<e`` such that the ratio of the largest to the smallest interval\nis the Golden Ratio.\n\n## References\nhttps://en.wikipedia.org/wiki/Golden-section_search\n\"\"\"\nstruct GoldenSection <: UnivariateOptimizer end\n\nBase.summary(::GoldenSection) = \"Golden Section Search\"\n\nfunction optimize(f, x_lower::T, x_upper::T,\n     mo::GoldenSection;\n     rel_tol::T = sqrt(eps(T)),\n     abs_tol::T = eps(T),\n     iterations::Integer = 1_000,\n     store_trace::Bool = false,\n     show_trace::Bool = false,\n     callback = nothing,\n     show_every = 1,\n     extended_trace::Bool = false,\n     nargs...) where T <: AbstractFloat\n    if x_lower > x_upper\n        error(\"x_lower must be less than x_upper\")\n    end\n    t0 = time()\n    options = (store_trace=store_trace, show_trace=show_trace, show_every=show_every, callback=callback)\n    # Save for later\n    initial_lower = x_lower\n    initial_upper = x_upper\n\n    golden_ratio::T = 0.5 * (3.0 - sqrt(5.0))\n\n    new_minimizer = x_lower + golden_ratio*(x_upper-x_lower)\n    new_minimum = f(new_minimizer)\n    best_bound = \"initial\"\n    f_calls = 1 # Number of calls to f\n\n    iteration = 0\n    converged = false\n\n    # Trace the history of states visited\n    tr = OptimizationTrace{T, typeof(mo)}()\n    tracing = store_trace || show_trace || extended_trace || callback !== nothing\n    stopped_by_callback = false\n    if tracing\n        # update trace; callbacks can stop routine early by returning true\n        state = (new_minimizer=new_minimizer,\n                 x_lower=x_lower,\n                 x_upper=x_upper,\n                 best_bound=best_bound,\n                 new_minimum=new_minimum)\n        stopped_by_callback = trace!(tr, nothing, state, iteration, mo, options, time()-t0)\n    end\n\n    while iteration < iterations && !stopped_by_callback\n\n        x_tol = rel_tol * abs(new_minimizer) + abs_tol\n\n        x_midpoint = (x_upper+x_lower)/2\n\n        if abs(new_minimizer - x_midpoint) <= 2*x_tol - (x_upper-x_lower)/2\n            converged = true\n            break\n        end\n\n        iteration += 1\n\n        if x_upper - new_minimizer > new_minimizer - x_lower\n            new_x = new_minimizer + golden_ratio*(x_upper - new_minimizer)\n            new_f = f(new_x)\n            f_calls += 1\n            if new_f < new_minimum\n                x_lower = new_minimizer\n                best_bound = \"lower\"\n                new_minimizer = new_x\n                new_minimum = new_f\n            else\n                x_upper = new_x\n                best_bound = \"upper\"\n            end\n        else\n            new_x = new_minimizer - golden_ratio*(new_minimizer - x_lower)\n            new_f = f(new_x)\n            f_calls += 1\n            if new_f < new_minimum\n                x_upper = new_minimizer\n                best_bound = \"upper\"\n                new_minimizer = new_x\n                new_minimum = new_f\n            else\n                x_lower = new_x\n                best_bound = \"lower\"\n            end\n        end\n\n        if tracing\n            # update trace; callbacks can stop routine early by returning true\n            state = (new_minimizer=new_minimizer,\n                     x_lower=x_lower,\n                     x_upper=x_upper,\n                     best_bound=best_bound,\n                     new_minimum=new_minimum)\n            stopped_by_callback = trace!(tr, nothing, state, iteration, mo, options, time()-t0)\n        end\n    end\n\n    return UnivariateOptimizationResults(mo,\n                                         initial_lower,\n                                         initial_upper,\n                                         new_minimizer,\n                                         new_minimum,\n                                         iteration,\n                                         iteration == iterations,\n                                         converged,\n                                         rel_tol,\n                                         abs_tol,\n                                         tr,\n                                         f_calls)\nend\n\n\nfunction trace!(tr, d, state, iteration, method::GoldenSection, options, curr_time=time())\n    dt = Dict()\n    dt[\"time\"] = curr_time\n    dt[\"minimizer\"] = state.new_minimizer\n    dt[\"x_lower\"] = state.x_lower\n    dt[\"x_upper\"] = state.x_upper\n    T = eltype(state.new_minimum)\n\n    update!(tr,\n            iteration,\n            state.new_minimum,\n            T(NaN),\n            dt,\n            options.store_trace,\n            options.show_trace,\n            options.show_every,\n            options.callback)\nend\n", "meta": {"hexsha": "43ea89a3736dcec10e67a73fe10cb833e8f78ef1", "size": 4826, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/solvers/golden_section.jl", "max_stars_repo_name": "schrimpf/Optim.jl", "max_stars_repo_head_hexsha": "f6850c92c8de7bd2cc937081925bce9c7ca1b81e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-22T14:59:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-22T14:59:45.000Z", "max_issues_repo_path": "src/univariate/solvers/golden_section.jl", "max_issues_repo_name": "schrimpf/Optim.jl", "max_issues_repo_head_hexsha": "f6850c92c8de7bd2cc937081925bce9c7ca1b81e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/solvers/golden_section.jl", "max_forks_repo_name": "schrimpf/Optim.jl", "max_forks_repo_head_hexsha": "f6850c92c8de7bd2cc937081925bce9c7ca1b81e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1733333333, "max_line_length": 104, "alphanum_fraction": 0.5424782429, "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7807999520217812}}
{"text": "print(\"Last updated: $(read(`date`, String))\")\n\n# Load environment\nimport Pkg; Pkg.activate(\"../../../\")\n\n# Import Libraries\nusing Turing\nusing Turing: Variational\nusing Distributions\nusing Distances\nusing PyPlot\nusing StatsFuns\nimport Random\nusing Flux\nimport LinearAlgebra\nusing JSON3\n\n# For getting quantiles along array dimensions\nfunction quantiles(X, q; dims, drop=false)\n  Q = mapslices(x -> quantile(x, q), X, dims=dims)\n  out = drop ? dropdims(Q, dims=dims) : Q\n  return out\nend\n\n# To extract parameters from ADVI model.\nfunction make_extractor(m, q, nsamples=1000)\n    qsamples = rand(q, nsamples)\n    _, sym2range = Variational.bijector(m; sym_to_ranges = Val(true));\n    return sym -> qsamples[collect(sym2range[sym][1]), :]\nend\n;\n\n# Squared-exponential covariance function\nfunction sqexp_cov_fn(D, alpha, rho; d_is_squared=false)\n    if d_is_squared\n        return alpha ^ 2 * exp.(-0.5 * D/(rho^2))\n    else\n        return alpha ^ 2 * exp.(-0.5 * (D/rho) .^ 2)\n    end\nend\n\n@model function GP(y, X, m_alpha=0.0, s_alpha=1.0, m_rho=0.0, s_rho=1.0, m_sigma=0.0, s_sigma=1.0)\n    # Distance matrix.\n    D2 = pairwise(Distances.SqEuclidean(), X, dims=1)\n    \n    # Priors.\n    alpha ~ LogNormal(m_alpha, s_alpha)\n    rho ~ LogNormal(m_rho, s_rho)\n    sigma ~ LogNormal(m_sigma, s_sigma)\n    \n    # Realized covariance function\n    K = sqexp_cov_fn(D2, alpha, rho, d_is_squared=true)\n    \n    # Sampling Distribution.\n    y ~ MvNormal(K + LinearAlgebra.I * sigma^2)  # mean=0, covariance=K.\nend;\n\n# Read data.\n\n# Directory where all simulation data are stored.\ndata_path = joinpath(@__DIR__, \"../data/gp-data-N30.json\")\n\n# Load data in JSON format.\ndata = let\n    x = open(f -> read(f, String), data_path)\n    JSON3.read(x)\nend\n\n# Reshape data if needed.\ny = Float64.(data[:y])\nX = Float64.(reshape(data[:x], length(y), 1))\n\nf = Float64.(data[:f])\nx_grid = Float64.(data[:x_grid])\n\nN = size(X, 1);\n\n# Plot data\nplt.scatter(vec(X), y, label=\"Data\")\nplt.plot(x_grid, f, c=\"grey\", ls=\":\", label=\"True f(x)\")\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.legend();\n\n# Create model.\nm = begin\n    m_alpha = 0.0\n    s_alpha = 0.1\n    m_rho = 0.0\n    s_rho = 1.0\n    m_sigma = 0.0\n    s_sigma = 1.0\n    GP(y, X, m_alpha, s_alpha, m_rho, s_rho, m_sigma, s_sigma)\nend;\n\n# Fit via ADVI. You can also use HMC.\nRandom.seed!(0)\n\n# initialize variational distribution (optional)\nq0 = Variational.meanfield(m)\n\n# NOTE: ADVI(num_elbo_samples, max_iters)\n\n# Compile\n@time q = vi(m, ADVI(1, 1), q0, optimizer=Flux.ADAM(1e-1));\n\n# RUN\n@time q = vi(m, ADVI(1, 2000), q0, optimizer=Flux.ADAM(1e-1));\n\n# Get posterior samples\nextract_gp = make_extractor(m, q)\nalpha = vec(extract_gp(:alpha));\nrho = vec(extract_gp(:rho));\nsigma = vec(extract_gp(:sigma));\nadvi_samples = Dict(:alpha => alpha, :rho => rho, :sigma => sigma);\n\n# Fit via HMC.\nRandom.seed!(0)\nburn = 1000\nnsamples = 1000\n\n# Compile\n@time _ = sample(m, HMC(0.01, 1), 1)\n\n# Run\n@time chain = sample(m, HMC(0.01, 100), burn + nsamples)\n\n# Get posterior samples\nalpha = vec(group(chain, :alpha).value.data[end-nsamples:end, :, 1]);\nrho = vec(group(chain, :rho).value.data[end-nsamples:end, :, 1]);\nsigma = vec(group(chain, :sigma).value.data[end-nsamples:end, :, 1]);\nhmc_samples = Dict(:alpha => alpha, :rho => rho, :sigma => sigma);\n\n# Fit via NUTS.\nRandom.seed!(7)\n\n# Compile\n@time _ = sample(m, NUTS(4, 0.8), 9);\n\n# Run\n@time chain = begin\n    nsamples = 1000  # number of MCMC samples\n    nadapt = 1000  # number of iterations to adapt tuning parameters in NUTS\n    iterations = nsamples + nadapt\n    target_accept_ratio = 0.8\n    \n    sample(m, NUTS(nadapt, target_accept_ratio, max_depth=10), iterations);\nend\n\n# Get posterior samples\nalpha = vec(group(chain, :alpha).value.data[:, :, 1]);\nrho = vec(group(chain, :rho).value.data[:, :, 1]);\nsigma = vec(group(chain, :sigma).value.data[:, :, 1]);\nnuts_samples = Dict(:alpha => alpha, :rho => rho, :sigma => sigma);\n\n# This funciton returns a function for predicting at new points given parameter values.\nfunction make_gp_predict_fn(Xnew, y, X)\n    N = size(X, 1)\n    M = size(Xnew, 1)\n    Q = N + M\n    Z = [Xnew; X]\n    D2 = pairwise(SqEuclidean(), Z, dims=1)\n    \n    return (alpha, rho, sigma) -> let\n        K = sqexp_cov_fn(D2, alpha, rho, d_is_squared=true) + LinearAlgebra.I * sigma^2\n        Koo_inv = inv(K[(M+1):end, (M+1):end])\n        Knn = K[1:M, 1:M]\n        Kno = K[1:M, (M+1):end]\n        C = Kno * Koo_inv\n        m = C * y\n        S = Matrix(LinearAlgebra.Hermitian(Knn - C * Kno'))\n        mvn = MvNormal(m, S)\n        rand(mvn)\n    end\nend\n\n# Function for plotting parameter posterior.\nfunction plot_post(samples, name; bins=nothing, suffix=\"\")\n    param = samples[name]\n    plt.hist(param, density=true, bins=bins)\n    plt.xlabel(name)\n    plt.ylabel(\"density\")\n    if suffix !== \"\"\n        suffix = \"($(suffix))\"\n    end\n    plt.title(\"Histogram of $(name) $(suffix)\");\nend\n\nfunction plot_fn_posterior(samples; figsize=(12, 4), figsize_f=figsize, suffix=\"\")\n    # Get parameters\n    alpha = samples[:alpha]\n    rho = samples[:rho]\n    sigma = samples[:sigma]\n    nsamps = length(alpha)\n   \n    # Plot parameters posterior.\n    plt.figure(figsize=figsize)\n    plt.subplot(1, 3, 1)\n    plot_post(samples, :alpha, bins=30, suffix=suffix)\n    plt.subplot(1, 3, 2)\n    plot_post(samples, :rho, bins=30, suffix=suffix)\n    plt.subplot(1, 3, 3)\n    plot_post(samples, :sigma, bins=30, suffix=suffix)    \n    plt.axvline(data[:sigma], ls=\":\", label=\"truth\", color=\"red\")\n    plt.legend()\n    plt.tight_layout()\n    \n    # Make predictions at new locations.\n    X_new = reshape(collect(range(-3.5, 3.5, length=100)), 100, 1)\n    gp_predict = make_gp_predict_fn(X_new, y, X)\n    \n    ynew = [gp_predict(alpha[m], rho[m], sigma[m]) for m in 1:nsamps]\n    ynew = hcat(ynew...)\n    \n    # Summary statistics of posterior function.\n    pred_mean = mean(ynew, dims=2)\n    pred_lower = quantiles(ynew, 0.025, dims=2)\n    pred_upper = quantiles(ynew, 0.975, dims=2)\n    \n    if suffix !== \"\"\n        suffix = \"($(suffix))\"\n    end \n     \n    # Plot predictions.\n    plt.figure(figsize=figsize_f)\n    plt.plot(vec(X_new), vec(pred_mean), color=\"blue\", label=\"Posterior predictive mean\")\n    plt.plot(x_grid, f, color=\"red\", ls=\":\", label=\"True f(x)\")\n    \n    plt.scatter(vec(X), vec(y), color=\"black\", label=\"Data\")\n    plt.fill_between(vec(X_new), vec(pred_upper), vec(pred_lower), color=\"blue\",\n                     alpha=0.2, label=\"95% Credible Interval\")\n    plt.legend(loc=\"upper left\", fontsize=8)\n    plt.title(\"GP Posterior predictive with 95% credible interval $(suffix)\");\n    \n    plt.xlabel(\"x\")\n    plt.ylabel(\"y\")\n    \n    plt.ylim(-2, 2)\n    plt.tight_layout()\nend\n\nplot_fn_posterior(advi_samples, figsize=(9, 3), suffix=\"ADVI\")\n\nplot_fn_posterior(hmc_samples, figsize=(9, 3), suffix=\"HMC\");\n\nplot_fn_posterior(nuts_samples, figsize=(9, 3), suffix=\"NUTS\");\n\n\n", "meta": {"hexsha": "5c0b9c91940352f018940b3312ae28a45064d42d", "size": 6871, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gp/scripts/gp_turing_alt.jl", "max_stars_repo_name": "luiarthur/TuringBnpBenchmarks", "max_stars_repo_head_hexsha": "c2f8c537ddc4f016d70fe49a0310a6819ad3a302", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2020-05-06T16:50:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T13:06:27.000Z", "max_issues_repo_path": "src/gp/scripts/gp_turing_alt.jl", "max_issues_repo_name": "luiarthur/TuringBnpBenchmarks", "max_issues_repo_head_hexsha": "c2f8c537ddc4f016d70fe49a0310a6819ad3a302", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2020-05-07T15:53:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T20:06:41.000Z", "max_forks_repo_path": "src/gp/scripts/gp_turing_alt.jl", "max_forks_repo_name": "luiarthur/TuringBnpBenchmarks", "max_forks_repo_head_hexsha": "c2f8c537ddc4f016d70fe49a0310a6819ad3a302", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-08T15:35:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T18:51:05.000Z", "avg_line_length": 27.59437751, "max_line_length": 98, "alphanum_fraction": 0.6389171882, "num_tokens": 2138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7807970277104745}}
{"text": "# example from \n# Barraud, A.Y., \"A numerical algorithm to solve A'XA - X = Q\",\n# IEEE Trans. Auto. Contr., AC-22, pp. 883-885, 1977. \n\nA = [1.5 2.5 3.5 4.5 5.5 6.5 7.5;\n\t\t1 -1.5 2.5 3.5 4.5 5.5 6.5;\n\t\t0 0 1.5 -2.5 3.5 4.5 5.5;\n\t\t0 0 0 1.5 2.5 -3.5 4.5;\n\t\t0 0 0 1 1.5 2.5 -3.5;\n\t\t0 0 0 0 0 1.5 -2.5;\n\t\t0 0 0 0 0 1 1.5]\n\nq = [5.25 1.5 19.25 22.5 55.75 60 49.25;\n\t\t0 0 3.25 -0.25 -6 -11 11.25;\n\t\t0 0 62.75 83 183.25 222.75 129.75;\n\t\t0 0 0 56.5 208.25 232.25 250.75;\n\t\t0 0 0 0 532.25 739.5 476.75;\n\t\t0 0 0 0 0 631 745.75;\n\t\t0 0 0 0 0 0 133.75]\n\nQ = (q + q') - diagm(0 => diag(q))\n\nx = [1 1 1 1 1 1 1;\n\t\t0 1 2 3 4 5 6;\n\t\t0 0 1 3 6 10 15;\n\t\t0 0 0 1 4 10 20;\n\t\t0 0 0 0 1 5 15;\n\t\t0 0 0 0 0 1 6;\n\t\t0 0 0 0 0 0 1];\n\nX = (x + x') - diagm(0 => diag(x)) # theoretical solution\n\t\nA = Array(A') # A' gets Adjoint{Float64,Array{Float64,2}}, but sylvester needs Array\nQ = -Q\n\nX1 = dlyap(A,Q) # computed solution\n##################################################\n\nprint(\"Testing dlyap: \")\nif sum((X-X1).^2) < 1e-6\n\tprintln(\"OK\")\nend\n\n", "meta": {"hexsha": "78e99fb8b6b653ee2b12e951e35cf86f99e43abb", "size": 1018, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dlyap_test.jl", "max_stars_repo_name": "javiercara/emACQR.jl", "max_stars_repo_head_hexsha": "acd8be36d722a03e47ec8c49dc2f57bba500cfd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dlyap_test.jl", "max_issues_repo_name": "javiercara/emACQR.jl", "max_issues_repo_head_hexsha": "acd8be36d722a03e47ec8c49dc2f57bba500cfd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dlyap_test.jl", "max_forks_repo_name": "javiercara/emACQR.jl", "max_forks_repo_head_hexsha": "acd8be36d722a03e47ec8c49dc2f57bba500cfd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-05T03:32:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-05T03:32:32.000Z", "avg_line_length": 23.1363636364, "max_line_length": 84, "alphanum_fraction": 0.5088408644, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.780797027557714}}
{"text": "module kuramoto_model\n\nusing DifferentialEquations, Flux, Optim, DiffEqFlux, Plots, Random\n\nrng=MersenneTwister(123) #make the results consistent across runs\nN=10000\nω=randn(rng,N)\nnorder=2 #OA=1, versus Hannay Ansatz=2\n\n#ω0,γ,K,β\nmodel_params=[2π, 0.1,0.8,0.1]\nic=rand(rng,N)*2π;\n\ntend=20.0\ntstart=0.0\nsampling=0.05\n\n\nfunction full_model(dϕ,ϕ,p,t)\n    ω0, γ, K, β=p\n    ψ,R=OrderParameter(ϕ)\n    for i in 1:N\n        dϕ[i]=ω0+γ*ω[i]+R*K*sin(ψ-ϕ[i]+β)\n    end\nend\n\nfunction reduced_model(du,u,p,t)\n    ω0, γ, K, β=p\n    ψ,R=u\n    n=norder\n    du[1]=ω0+K/2.0*sin(β)*(1+R^(2*norder))\n    du[2]=-γ*R+K/2.0*cos(β)*R*(1-R^(2*norder))\nend\n\n\nfunction OrderParameter(ϕ;m=1.0)\n    Z=1.0/N*sum(exp.(im.*ϕ*m))\n    R=abs(Z)\n    ψ=angle(Z)\n    return ψ,R\nend\n\nfunction OrderParameterComplex(ϕ;m=1.0)\n    Z=1.0/N*sum(exp.(im.*ϕ*m))\n    return Z\nend\n\nicr=[angle(OrderParameterComplex(ic)), abs(OrderParameterComplex(ic))]\n\nfunction InitPlot()\n\n    lay = @layout [ a{0.6w} [b; c]]\n\n    t=tstart:0.01:tend\n    sol=solve(ODEProblem(full_model,ic,(tstart,tend),model_params), Tsit5(), saveat=t)\n\n    num_tps=length(t)\n    R=zeros(num_tps)\n    ψ=zeros(num_tps)\n    for tp in 1:num_tps\n        psi, rr=OrderParameter(sol[:,tp])\n        R[tp]=rr\n        ψ[tp]=psi\n    end\n\n    pl1=plot(ψ,R,lw=2, legend=false, color=:blue, proj = :polar)\n\n\n    #radius plot\n    pl2=plot(t,R,lw=2, legend=false, color=:blue)\n\n\n    #angle plot\n    pl3=plot(t,sin.(ψ), lw=2, legend=false, color=:blue)\n\n\n    pl=plot(pl1, pl2, pl3, layout=lay)\n    display(pl)\n\nend\n\n\nfunction predict_adjoint(param) # Our 1-layer neural network\n    prob=ODEProblem(reduced_model,icr,(tstart,tend), model_params)\n    Array(concrete_solve(prob,Tsit5(),icr,param,saveat=tstart:sampling:tend,abstol=1e-8,reltol=1e-6))\nend\n\nfunction generate_data(ic; param=model_params)\n    prob=ODEProblem(full_model,ic,(tstart,tend), param)\n    tps=tstart:sampling:tend\n    num_tps=length(tps)\n    d1=Array(concrete_solve(prob,Tsit5(),ic,param,saveat=tps))\n    # Get a time series of the order parameter\n    d2=mapslices(OrderParameterComplex, d1, dims=1)\n    data=Float64[angle.(d2); abs.(d2)]\n    data=reshape(data,2,num_tps)\n    return data\nend\n\n# Generate some data to fit, and add some noise to it\ndata=generate_data(ic)\n#σN=0.05\n#data+=σN*randn(size(data))\n\n\nfunction loss_adjoint(param)\n    prediction = predict_adjoint(param)\n    loss=0.0\n    for k in 1:length(prediction[1,:])\n        Rp=prediction[2,k]\n        Rd=data[2,k]\n        θp=prediction[1,k]\n        θd=data[1,k]\n        loss+=sqrt((Rp*cos(θp)-Rd*cos(θd))^2+(Rp*sin(θp)-Rd*sin(θd))^2)\n    end\n    loss,prediction\nend\n\nfunction train_model(;pguess=[6.1, 0.15,1.1,0.15])\n    println(\"The initial loss function is $(loss_adjoint(pguess)[1])\")\n    res = DiffEqFlux.sciml_train(loss_adjoint,pguess,BFGS(initial_stepnorm=0.0001), maxiters=4000)\n    println(\"The parameters are $(res.minimizer) with final loss value $(res.minimum)\")\n    return(res)\nend\n\nfunction plotFit(param; tend=20.0)\n\n    validationPlot(param,ic; tend=tend)\n\nend\n\nfunction validationPlot(param,ic; tend=10.0)\n\n    lay = @layout [ a{0.6w} [b; c]]\n\n    t=tstart:0.01:tend\n    icr=[angle(OrderParameterComplex(ic)), abs(OrderParameterComplex(ic))]\n\n    sol=solve(ODEProblem(full_model,ic,(tstart,tend),model_params), Tsit5(), saveat=t)\n    sol_fit=solve(ODEProblem(reduced_model,icr,(tstart,tend),param), Tsit5(), saveat=t)\n\n    num_tps=length(t)\n    R=zeros(num_tps)\n    ψ=zeros(num_tps)\n    for tp in 1:num_tps\n        psi, rr=OrderParameter(sol[:,tp])\n        R[tp]=rr\n        ψ[tp]=psi\n    end\n\n    pl1=plot(ψ,R,lw=2, legend=false, color=:blue, proj = :polar)\n    plot!(pl1, sol_fit, color=:green, proj=:polar, vars=(1,2))\n\n    #radius plot\n    pl2=plot(t,R,lw=2, legend=false, color=:blue)\n    plot!(pl2, sol_fit, color=:green, lw=2.0, vars=(0,2))\n\n    #angle plot\n    pl3=plot(t,sin.(ψ), lw=2, legend=false, color=:blue)\n    plot!(pl3, sol_fit.t, sin.(sol_fit[1,:]), color=:green)\n\n    pl=plot(pl1, pl2, pl3, layout=lay)\n    display(pl)\n\nend\n\nend #module\n\n#d=kuramoto_model.generate_data(randn(kuramoto_model.N))\n#kuramoto_model.predict_adjoint(kuramoto_model.model_params)\n\nkuramoto_model.InitPlot()\nresults_kuramoto=kuramoto_model.train_model()\nkuramoto_model.plotFit(results_kuramoto.minimizer)\nkuramoto_model.validationPlot(results_kuramoto.minimizer, π*rand(kuramoto_model.N))\nkuramoto_model.validationPlot(results_kuramoto.minimizer, 1.5*π*rand(kuramoto_model.N))\n", "meta": {"hexsha": "93ba08a825227e2fa91e19028a8bc1b518181905", "size": 4429, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/kuramoto_parameter_fit.jl", "max_stars_repo_name": "khannay/FittingParamsDiffEqFlux", "max_stars_repo_head_hexsha": "19cf5691b5a81d8bdea945c266515dff70fb06ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-04-24T10:23:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T14:25:55.000Z", "max_issues_repo_path": "julia/kuramoto_parameter_fit.jl", "max_issues_repo_name": "khannay/FittingParamsDiffEqFlux", "max_issues_repo_head_hexsha": "19cf5691b5a81d8bdea945c266515dff70fb06ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-16T12:49:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-16T12:49:02.000Z", "max_forks_repo_path": "julia/kuramoto_parameter_fit.jl", "max_forks_repo_name": "khannay/FittingParamsDiffEqFlux", "max_forks_repo_head_hexsha": "19cf5691b5a81d8bdea945c266515dff70fb06ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-04T00:28:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T00:28:43.000Z", "avg_line_length": 25.0225988701, "max_line_length": 101, "alphanum_fraction": 0.6721607586, "num_tokens": 1555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299529686199, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7807970260469881}}
{"text": "using Plots, LinearAlgebra, Random, Statistics\npyplot()\n\n# compute gradient\nfunction df(X::Matrix{Float64}, y::Vector{Float64}, theta::Vector{Float64})\n    return X' * (X * theta - y)\nend\n\n# gradient descent\nfunction lr_gd(X::Matrix{Float64}, y::Vector{Float64}, alpha::Float64, num_iterations::Int64)\n    (num_samples, num_features) = size(X)\n    theta = zeros(num_features)\n    for i = 1:num_iterations\n        theta += df(X, y, theta)\n    end\n    return theta\nend\n\n# stochastic gradient descent, batch size of 1\nfunction lr_sgd(X::Matrix{Float64}, y::Vector{Float64}, alpha::Float64, batch_size::Int64, num_iterations::Int64)\n    (num_samples, num_features) = size(X)\n    theta = zeros(num_features)\n    for i = 1:num_iterations\n        # use num_samples minibatches of size 1 to compute gradient to update theta\n        # using k:k in order to keep type as a matrix\n        theta += mean(df(X[k:k,:], y[k:k], theta) for k in (rand(1:num_samples) for b = 1:batch_size));\n    end\n    return theta\nend\nfunction main()\n    num_features = 1024;\n    dataset_sizes = 2 .^ [7,8,9,10,11,12,13,14,15,16];\n    num_iterations = 1024;\n    alpha = 0.001;\n    # we will do this for the vanilla sgd case, without varying minibatch size\n    batch_size = 1;\n    gd_times = Float64[];\n    sgd_times = Float64[];\n    for num_samples in dataset_sizes\n        X = randn(num_samples, num_features);\n        y = randn(num_samples);\n        gd_time = (@elapsed lr_gd(X, y, alpha, num_iterations)) / num_iterations;\n        sgd_time = (@elapsed lr_sgd(X, y, alpha, batch_size, num_iterations)) / num_iterations;\n        push!(gd_times, gd_time);\n        push!(sgd_times, sgd_time);\n        println(\"dataset size $num_samples --- GD time = $gd_time, SGD time = $sgd_time\");\n    end\n    plot(dataset_sizes, gd_times, label=\"Gradient Descent (GD)\", color=:blue,\n        markershape=:circle, xaxis=:log, yaxis=:log);\n    plot!(dataset_sizes, sgd_times, label=\"Stochastic Gradient Descent (SGD, with minibatch size=$batch_size)\",\n        markershape=:rect, color=:orange, marker=:, xaxis=:log, yaxis=:log,\n        xticks = 10 .^ [2, 3, 4, 5, 6],\n        xlabel=\"Number of data points\", ylabel=\"Time per iteration (seconds)\",\n        title=\"Comparing Runtime per Iteration for GD and SGD\");\n    savefig(\"timesgd.pdf\")\nend\nmain()\n", "meta": {"hexsha": "5bdaf4d2e812db8e232e91160ab709421d3af8ea", "size": 2301, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "figures/gd_variants.jl", "max_stars_repo_name": "pasta41/lml-2020", "max_stars_repo_head_hexsha": "0ef7226ab836a814db0817bb78bd1c9af3a1af93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "figures/gd_variants.jl", "max_issues_repo_name": "pasta41/lml-2020", "max_issues_repo_head_hexsha": "0ef7226ab836a814db0817bb78bd1c9af3a1af93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figures/gd_variants.jl", "max_forks_repo_name": "pasta41/lml-2020", "max_forks_repo_head_hexsha": "0ef7226ab836a814db0817bb78bd1c9af3a1af93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6724137931, "max_line_length": 113, "alphanum_fraction": 0.6623207301, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7806817364743686}}
{"text": "### A Pluto.jl notebook ###\n# v0.18.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 57c67334-a30d-11ec-3019-012043761a13\nbegin\n\tusing Plots\n\tusing Random\n\timport Distributions as di\n\tusing Statistics\nend\n\n# ╔═╡ 287d1794-fe2c-49ba-ad5a-71a130ee14be\nmd\"\"\"\n# Midterm BME 502 Spring 2022\nput names of your group here.  A maxiumum of three students can be in a group.  The class is allowed to discuss the problem with each other.  I expect one report per group.  Don't copy from each other.\n\"\"\"\n\n# ╔═╡ cb547e46-51fb-47ae-97ed-482d89d9c5e5\nmd\"\"\"\n# Problem 1 (30 Points)\nEstimate Pi using random numbers.  The basic idea is to play darts on a 2x2 square in which a circle of radius one is placed.  You now throw random darts at this board and you have to figure out how to calculate ``\\pi`` by counting how many darts hit the circle and how many darts miss.  You can use any Julia function that you like, but I want you to be conscious of computational and coding efficiency.  To illustrate your approach we want you to create a figure of the circle with the hits and misses indicated by different colors.  We provided a template.\nAlso, please calculate how accurately you can estimate Pi using this method given that you throw N darts (Remember what I told you about counting errors).\n\"\"\"\n\n# ╔═╡ b93fcb5e-64b3-4bda-abd4-ade9cedf56ca\nfunction makeacircle(x1,y1,r)\n    theta = LinRange(0,2*pi,500)\n    return x1.+r*cos.(theta), y1.+r*sin.(theta)\nend\n\n# ╔═╡ 61d7c512-c0a0-4341-b97c-ffaf26944b6a\nmd\"\"\"\nHere is some help with the figure.\nAll you need to do is to add the hits and misses with different colors\n\"\"\"\n\n# ╔═╡ 6aa0d42e-e778-48eb-a2a7-d923fa80daea\nbegin\n\tplot(makeacircle(1,1,1),seriestype = :shape,c = :blue,legend = false,fillalpha = 0.2,aspect_ratio = 1)\n\t# add random hits here\nend\n\n# ╔═╡ ab0da14c-2b52-44d6-a91d-795c669687fb\nmd\"\"\"\n# Problem 2 (total 70 Points)\nIn the lecture on \"least squares\", we discussed the case where we used the wrong model (linear vs. quadratic).  We showed that in this case the chi-squared distribution does not follow the theoretical prediction but showed a different distribution.  Here I want to demonstrate that if your error is bimodal (as compared to Gaussian), and even if you are using the correct model function, the statistics do not agree with a least-squares fit.  This is not unsurprising but the subject of this midterm is to attempt to develop a Bayesian model to properly fit data that come from a bimodal distribution.\n\"\"\"\n\n# ╔═╡ 68c4f411-d5a0-48f0-bbba-8e6901b0408f\nmd\"\"\"\n1) (30 points) Develop a maximum likelihood model for a bi-modal error distribution that is composed of two Gaussian distributions of width $\\sigma$ at a y-distance of $\\pm \\Delta y$ around the real data point.  For this, you need to formulate the likelihood probability distribution of finding a particular dataset $\\{y_{i}\\}$ of N datapoints with this bi-modal error distribution assuming a “true” model $f(x_{i},\\theta)$.  Here I expect an analytic expression.\n\n2) (20 points) Develop a method to fit a straight line through actual data points taken from a line with added bi-modal errors as described in the paragraph above.  Do this by maximizing the likelihood above.  Can you develop a similar procedure as for Gaussian errors (taking the log of the likelihood turns the maximization into a minimization problem)? First try an analytical approach by taking the derivative and trying to find the maximum of the function.  If analytical math is too difficult you may approach the problem using numerical or approximate methods.\n\n3) (20 points) Consider the same scenario as in (1), but instead of fitting to a single line, fit to two parallel lines using a least squares approach (fit parameters should be slope, intercept and Δy). Be very careful how you calculate chi-squared (each data point should only count once).  Please produce a similar graph (Out[7]) to confirm that the fit indeed behaves properly and fits the theoretical chi-squared distribution.\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nDistributions = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nRandom = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\nStatistics = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[compat]\nDistributions = \"~0.25.49\"\nPlots = \"~1.27.0\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"af92965fb30777147966f58acb05da51c5616b5f\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.3\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"4b859a208b2397a7a623a03449e4636bdb17bcf2\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+1\"\n\n[[Calculus]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"f641eb0a4f00c343bbc32346e1217b86f3ce9dad\"\nuuid = \"49dc2e85-a5d0-5ad3-a950-438e2897f1b9\"\nversion = \"0.5.1\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"c9a6160317d1abe9c44b3beb367fd448117679ca\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.13.0\"\n\n[[ChangesOfVariables]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"bf98fa45a0a4cee295de98d4c1462be26345b9a1\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.2\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"12fc73e5e0af68ad3137b886e3f7c1eacfca2640\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.17.1\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"96b0bc6c52df76506efc8a441c6cf1adcb1babc4\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.42.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"3daef5523dd2e769dad2365274f760ff5f282c7d\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.11\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[DensityInterface]]\ndeps = [\"InverseFunctions\", \"Test\"]\ngit-tree-sha1 = \"80c3e8639e3353e5d2912fb3a1916b8455e2494b\"\nuuid = \"b429d917-457f-4dbc-8f4c-0cc954292b1d\"\nversion = \"0.4.0\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Distributions]]\ndeps = [\"ChainRulesCore\", \"DensityInterface\", \"FillArrays\", \"LinearAlgebra\", \"PDMats\", \"Printf\", \"QuadGK\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"Test\"]\ngit-tree-sha1 = \"9d3c0c762d4666db9187f363a76b47f7346e673b\"\nuuid = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nversion = \"0.25.49\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[DualNumbers]]\ndeps = [\"Calculus\", \"NaNMath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"90b158083179a6ccbce2c7eb1446d5bf9d7ae571\"\nuuid = \"fa6b7ba4-c1ee-5f82-b5fc-ecf0adba8f74\"\nversion = \"0.6.7\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ae13fcbc7ab8f16b0856729b050ef0c446aa3492\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.4.4+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"0dbc5b9683245f905993b51d2814202d75b34f1a\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.13.1\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"51d2dfe8e590fbd74e7a842cf6d13d8a2f45dc01\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.6+0\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"RelocatableFolders\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"9f836fb62492f4b0f0d3b06f55983f2704ed0883\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.64.0\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"a6c850d77ad5118ad3be4bd188919ce97fffac47\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.64.0+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"83ea630384a13fc4f002b77690bc0afeb4255ac9\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.2\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"a32d672ac2c967f3deb8a81d828afc739c838a06\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+2\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"0fa77022fe4b511826b39c894c90daf5fce3334a\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.17\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"129acf094d168394e80ee1dc4bc06ec835e510a3\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+1\"\n\n[[HypergeometricFunctions]]\ndeps = [\"DualNumbers\", \"LinearAlgebra\", \"SpecialFunctions\", \"Test\"]\ngit-tree-sha1 = \"65e4589030ef3c44d3b90bdc5aac462b4bb05567\"\nuuid = \"34004b35-14d8-5ef3-9330-4cdb6864b03a\"\nversion = \"0.3.8\"\n\n[[IniFile]]\ngit-tree-sha1 = \"f550e6e32074c939295eb5ea6de31849ac2c9625\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.1\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"91b5dcf362c5add98049e6c29ee756910b03051d\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.3\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[IterTools]]\ngit-tree-sha1 = \"fa6287a4469f5e048d763df38279ee729fbd44e5\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.4.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"abc9885a7ca2052a736a600f7fa66209f96506e1\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.4.1\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"3c837543ddb02250ef42f4738347454f95079d4e\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.3\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b53380851c6e6664204efb2e62cd24fa5c47e4ba\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.2+0\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LERC_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"bf36f528eec6634efc60d7ec062008f171071434\"\nuuid = \"88015f11-f218-50d7-93a8-a6af411a945d\"\nversion = \"3.0.0+1\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"f2355693d6778a178ade15952b7ac47a4ff97996\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.3.0\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"4f00cc36fede3c04b8acf9b2e2763decfdcecfa6\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.13\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"0b4a5d71f3e5200a7dff793393e09dfc2d874290\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+1\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"LERC_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"c9551dd26e31ab17b86cbd00c2ede019c08758eb\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+1\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"56ad13e26b7093472eba53b418eba15ad830d6b5\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.9\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"737a5957f387b17e74d4ad2f440eb330b39a62c5\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"1.0.0\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"887579a3eb005446d514ab7aeac5d1d027658b8f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+1\"\n\n[[OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"648107615c15d4e09f7eca16307bc821c1f718d8\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.13+0\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[PDMats]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"SuiteSparse\"]\ngit-tree-sha1 = \"e8185b83b9fc56eb6456200e873ce598ebc7f262\"\nuuid = \"90014a1f-27ba-587c-ab20-58faa44d9150\"\nversion = \"0.11.7\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"85b5da0fa43588c75bb1ff986493443f821c70b7\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.2.3\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"6f1b25e8ea06279b5689263cc538f51331d7ca17\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.1.3\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"Pkg\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\", \"UnicodeFun\", \"Unzip\"]\ngit-tree-sha1 = \"9213b4c18b57b7020ee20f33a4ba49eb7bef85e0\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.27.0\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"d3538e7f8a790dc8903519090857ef8e1283eecd\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.5\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[QuadGK]]\ndeps = [\"DataStructures\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"78aadffb3efd2155af139781b8a8df1ef279ea39\"\nuuid = \"1fd47b50-473d-5c70-9696-f719f8f3bcdc\"\nversion = \"2.4.2\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.2.1\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"995a812c6f7edea7527bb570f0ac39d0fb15663c\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.5.1\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[RelocatableFolders]]\ndeps = [\"SHA\", \"Scratch\"]\ngit-tree-sha1 = \"cdbd3b1338c72ce29d9584fdbe9e9b70eeb5adca\"\nuuid = \"05181044-ff0b-4ac5-8273-598c1e38db00\"\nversion = \"0.1.3\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.3.0\"\n\n[[Rmath]]\ndeps = [\"Random\", \"Rmath_jll\"]\ngit-tree-sha1 = \"bf3188feca147ce108c76ad82c2792c57abe7b1f\"\nuuid = \"79098fc4-a85e-5d69-aa6a-4863f24498fa\"\nversion = \"0.7.0\"\n\n[[Rmath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"68db32dff12bb6127bac73c209881191bf0efbb7\"\nuuid = \"f50d1b31-88e8-58de-be2c-1cc44531875f\"\nversion = \"0.3.0+0\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"5ba658aeecaaf96923dce0da9e703bd1fe7666f9\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"2.1.4\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"74fb527333e72ada2dd9ef77d98e4991fb185f04\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.4.1\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"c3d8ba7f3fa0625b062b82853a7d5229cb728b6b\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.2.1\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"8977b17906b0a1cc74ab2e3a05faa16cf08a8291\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.16\"\n\n[[StatsFuns]]\ndeps = [\"ChainRulesCore\", \"HypergeometricFunctions\", \"InverseFunctions\", \"IrrationalConstants\", \"LogExpFunctions\", \"Reexport\", \"Rmath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"25405d7016a47cf2bd6cd91e66f4de437fd54a07\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.16\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"57617b34fa34f91d536eb265df67c2d4519b8b98\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.5\"\n\n[[SuiteSparse]]\ndeps = [\"Libdl\", \"LinearAlgebra\", \"Serialization\", \"SparseArrays\"]\nuuid = \"4607b0f0-06f3-5cda-b6b1-a6196a1729e9\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"OrderedCollections\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"5ce79ce186cc678bbb5c5681ca3379d1ddae11a1\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.7.0\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[UnicodeFun]]\ndeps = [\"REPL\"]\ngit-tree-sha1 = \"53915e50200959667e78a92a418594b428dffddf\"\nuuid = \"1cfade01-22cf-5700-b092-accc4b62d6e1\"\nversion = \"0.4.1\"\n\n[[Unzip]]\ngit-tree-sha1 = \"34db80951901073501137bdbc3d5a8e7bbd06670\"\nuuid = \"41fe7b60-77ed-43a1-b4f0-825fd5a5650d\"\nversion = \"0.1.2\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4528479aa01ee1b3b4cd0e6faef0e04cf16466da\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.25.0+0\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e45044cd873ded54b6a5bac0eb5c971392cf1927\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.2+0\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"b910cb81ef3fe6e78bf6acee440bda86fd6ae00c\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+1\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╠═57c67334-a30d-11ec-3019-012043761a13\n# ╟─287d1794-fe2c-49ba-ad5a-71a130ee14be\n# ╟─cb547e46-51fb-47ae-97ed-482d89d9c5e5\n# ╠═b93fcb5e-64b3-4bda-abd4-ade9cedf56ca\n# ╟─61d7c512-c0a0-4341-b97c-ffaf26944b6a\n# ╠═6aa0d42e-e778-48eb-a2a7-d923fa80daea\n# ╟─ab0da14c-2b52-44d6-a91d-795c669687fb\n# ╟─68c4f411-d5a0-48f0-bbba-8e6901b0408f\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "b861a1259a43ea042729bbf9f77f585a2f9bf7ff", "size": 37035, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "midterm.jl", "max_stars_repo_name": "hstrey/BME-502-2022", "max_stars_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "midterm.jl", "max_issues_repo_name": "hstrey/BME-502-2022", "max_issues_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "midterm.jl", "max_forks_repo_name": "hstrey/BME-502-2022", "max_forks_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-15T18:19:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T18:26:08.000Z", "avg_line_length": 35.7135969142, "max_line_length": 601, "alphanum_fraction": 0.740218712, "num_tokens": 16468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.9184802423517103, "lm_q1q2_score": 0.7806817314099376}}
{"text": "\"\"\"\n        vikor(decisionMat, weights, fns; v = 0.5)\n\nApply VIKOR (VlseKriterijumska Optimizcija I Kaompromisno Resenje in Serbian) method for a given matrix and weights.\n\n# Arguments:\n - `decisionMat::DataFrame`: n × m matrix of objective values for n candidate (or strategy) and m criteria \n - `weights::Array{Float64, 1}`: m-vector of weights that sum up to 1.0. If the sum of weights is not 1.0, it is automatically normalized.\n - `fns::Array{Function, 1}`: m-vector of function that are either maximum or minimum.\n - `v::Float64`: Optional algorithm parameter. Default is 0.5.\n\n# Description \nvikor() applies the VIKOR method to rank n strategies subject to m criteria which are supposed to be either maximized or minimized.\n\n# Output \n- `::VikorResult`: VikorResult object that holds multiple outputs including scores and best index.\n\n# Examples\n```julia-repl\njulia> Amat = [\n             100 92 10 2 80 70 95 80 ;\n             80  70 8  4 100 80 80 90 ;\n             90 85 5 0 75 95 70 70 ; \n             70 88 20 18 60 90 95 85\n           ];\n\njulia> dmat = makeDecisionMatrix(Amat)\n4×8 DataFrame\n Row │ Crt1     Crt2     Crt3     Crt4     Crt5     Crt6     Crt7     Crt8    \n     │ Float64  Float64  Float64  Float64  Float64  Float64  Float64  Float64 \n─────┼────────────────────────────────────────────────────────────────────────\n   1 │   100.0     92.0     10.0      2.0     80.0     70.0     95.0     80.0\n   2 │    80.0     70.0      8.0      4.0    100.0     80.0     80.0     90.0\n   3 │    90.0     85.0      5.0      0.0     75.0     95.0     70.0     70.0\n   4 │    70.0     88.0     20.0     18.0     60.0     90.0     95.0     85.0\n\njulia> fns = makeminmax([maximum, maximum, maximum, maximum, maximum, maximum, maximum, maximum]);\n\njulia> result = vikor(dmat, w, fns);\n\njulia> result.scores\n4-element Array{Float64,1}:\n  0.1975012087551764\n  0.2194064473270817\n  0.3507643203516215\n -0.16727341435277993\n\njulia> result.bestIndex\n4\n\n```\n\n# References\nCelikbilek Yakup, Cok Kriterli Karar Verme Yontemleri, Aciklamali ve Karsilastirmali\nSaglik Bilimleri Uygulamalari ile. Editor: Muhlis Ozdemir, Nobel Kitabevi, Ankara, 2018\n\"\"\"\nfunction vikor(decisionMat::DataFrame, weights::Array{Float64,1}, fns::Array{Function,1}; v::Float64=0.5)::VikorResult\n    w = unitize(weights)\n\n    nalternatives, ncriteria = size(decisionMat)\n\n    # col_max = colmaxs(decisionMat)\n    # col_min = colmins(decisionMat)\n    col_max = apply_columns(fns, decisionMat)\n    col_min = apply_columns(reverseminmax(fns), decisionMat)\n\n    A = similar(decisionMat)\n\n    for i in 1:nalternatives\n        for j in 1:ncriteria\n            if fns[j] == maximum\n                @inbounds A[i, j] = abs((col_max[j] - decisionMat[i, j]) / (col_max[j] - col_min[j]))\n            elseif fns[j] == minimum \n                @inbounds A[i, j] = abs((decisionMat[i, j] - col_min[j]) / (col_max[j] - col_min[j]))\n            else\n                @warn fns[j]\n                error(\"Function must be either maximum or minimum.\")\n            end    \n        end\n    end\n\n    weightedA = w * A\n\n    s = Array{Float64,1}(undef, nalternatives)\n    r = similar(s)\n    q = similar(s)\n\n    for i in 1:nalternatives\n        s[i] = sum(weightedA[i,:])\n        r[i] = maximum(weightedA[i,:])\n    end\n\n    smin = minimum(s)\n    smax = maximum(s)\n    rmin = minimum(r)\n    rmax = maximum(r)\n    q = v .* ((s .- smin ./ (smax .- smin))) + (1 - v) .* ((r .- rmin ./ (rmax .- rmin)))\n\n    scores = q\n\n    # select the one with minimum score\n    best_index = sortperm(q) |> first \n\n    result = VikorResult(\n        decisionMat,\n        w,\n        weightedA,\n        best_index,\n        scores\n    )\n    return result\nend", "meta": {"hexsha": "c8c9c6b1f04681730c04ec5d9c4e81d73316caa3", "size": 3681, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vikor.jl", "max_stars_repo_name": "bahadirfyildirim/JMcDM", "max_stars_repo_head_hexsha": "c1c3f11d92cd8b8c6367245794464e6643caa735", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/vikor.jl", "max_issues_repo_name": "bahadirfyildirim/JMcDM", "max_issues_repo_head_hexsha": "c1c3f11d92cd8b8c6367245794464e6643caa735", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vikor.jl", "max_forks_repo_name": "bahadirfyildirim/JMcDM", "max_forks_repo_head_hexsha": "c1c3f11d92cd8b8c6367245794464e6643caa735", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8660714286, "max_line_length": 138, "alphanum_fraction": 0.5900570497, "num_tokens": 1232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.780681730784421}}
{"text": "import Base: full, ==, copy, size, convert\nimport SparseArrays: sparse\n\n\"\"\"\n# SkylineMatrix type for symmetric matrices\n\nType to hold skyline matrices with element types Tv\n\n- sv:         Skyline vector\n- kdiag:      Diagonal elements in sv.\n- sm:         SkylineMatrix.\n\n### Constructor\n```julia\nsm = SkylineMatrix{Tv}(kdiag::Vector{Int}, sv::Vector{Tv})\n\n```\n### Arguments\n```julia\n* `kdiag`           : Vector specifying location of diagonal element in sv. \n* `sv`              : Non-zero values in upper triangular matrix.\n```\n### Additional methods\n```julia\n* `size(sm)`        : Return size of full matrix => (n, n).\n* `==(sm1, sm2)`    : Compare 2 SkylineMatrices for equality.\n* `copy(sm)`        : Create a copy.\n* `sparse(sm)`      : Convert to a SparseMatrixCSC.\n* `full(sm)`        : Convert to a full matrix.\n\n* `convert(::Type{NumericalMethodsforEngineers.SkylineMatrix}, kdiag::Vector{Int}, sv::Vector{Tv})`\n                    : Default constructor\n\n* `fromskyline(kdiag::Vector{Int}, sv::Vector{Tv})`\n                    : Convert kdiag,sv to full matrix.\n```\n\"\"\"\nmutable struct SkylineMatrix{Tv}\n    kdiag::Vector{Int}        # Diagonal elements\n    sv::Vector{Tv}         # Nonzero values\nend\n\nsize(sm::SkylineMatrix) = (length(sm.kdiag), length(sm.kdiag))\n\n==(sm1::SkylineMatrix, sm2::SkylineMatrix) = (sm1.kdiag==sm2.kdiag && sm1.sv==sm2.sv)\n    \nfunction copy(sm::SkylineMatrix)\n  Tv = eltype(sm.sv)\n  SkylineMatrix{Tv}(copy(sm.kdiag), copy(sm.sv))\nend\n\nfunction convert(::Type{NumericalMethodsforEngineers.SkylineMatrix}, kdiag::Vector{Int}, sv::Vector)\n  Tv = eltype(sv)\n  SkylineMatrix{Tv}(kdiag, sv)\nend\n\nfunction full(sm::SkylineMatrix)\n  fromskyline(sm.kdiag, sm.sv)\nend\n\nfunction sparse(sm::SkylineMatrix)\n\tsparse(fromskyline(sm.kdiag, sm.sv))\nend\n\n\"\"\"\n# Convert the pair kdiag, sv to a full matrix\n\n### Function\n```julia\nm = fromskyline{Tv}(kdiag::Vector{Int}, sv::Vector{Tv})\n```\n### Arguments\n```julia\n* `kdiag`           : Vector specifying location of diagonal element in sv. \n* `sv`              : Non-zero values in upper triangular matrix.\n```\n\"\"\"\nfunction fromskyline(kdiag::Vector{Int64}, sv::Vector)\n\tneq = size(kdiag, 1)\n\tkm = zeros(eltype(sv), neq, neq)\n\tkm[1, 1] = sv[kdiag[1]]\n\tfor i in 2:neq\n\t\tkm[i, i] = sv[kdiag[i]]\n\t\tfor j in (kdiag[i-1] + 1):kdiag[i]\n\t\t\tkm[i, i - (kdiag[i]-j)] = sv[j]\n\t\t\tkm[i - (kdiag[i]-j), i] = sv[j]\n    end\n  end\n\tkm\nend\n", "meta": {"hexsha": "b14312b931460196e995f3be612f07eb57e3491d", "size": 2392, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nmlib/SkylineMatrices.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-02T01:16:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-02T01:16:31.000Z", "max_issues_repo_path": "src/nmlib/SkylineMatrices.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nmlib/SkylineMatrices.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2857142857, "max_line_length": 100, "alphanum_fraction": 0.6350334448, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995703, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7806817235005327}}
{"text": "function F_(u::T, v::T, w::T) where T<:Real\n\tR1 = sqrt(v^2 + w^2)\n\tR2 = sqrt(u^2 + w^2)\n\tR3 = sqrt(u^2 + v^2)\n\tR  = sqrt(u^2 + v^2 + w^2)\n\treturn sign(u*v) * \n\t\t(\n\t\t\tabs(u) * log( (abs(v) + R3) * R2 / (abs(u) * (abs(v) + R))) +\n\t\t\tabs(v) * log( (abs(u) + R3) * R1 / (abs(v) * (abs(u) + R))) +\n\t\t\tw * atan(abs(u * v) / w / R)\n \t\t)\nend\n\n\"\"\"\n   gbox(x, y, z, xextent, yextent, zextent)\n\nCompute the vertical component of the gravitational attraction\nrectangular box bounded by the axis-parallel planes defined \nby `xextent`, `yextent`, and `zextent`.\nObservation point is given by the cartesian coordinates `x, y, z`.\n\nOutput is given in units of m/s^2.\n\"\"\"\nfunction gbox(x::T, y::T, z::T, x1::Array{T}, y1::Array{T}, z1::Array{T}) where T<:Real\n\tVz = zero(eltype(T))\n\tfor i in 1:2\n        for j in 1:2\n            for k in 1:2\n                f = (-1.0)^(i+j+k)\n                Vz += f * F_(x - x1[i], y - y1[j], z - z1[k])\n            end\n        end\n    end\n\treturn Vz * 6.6742e-11\nend", "meta": {"hexsha": "3f7f33d75c0503ef370f8313c349d7c9bee4eccf", "size": 985, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gbox.jl", "max_stars_repo_name": "ruboerner/GravMag", "max_stars_repo_head_hexsha": "6d3ace710b99416d827276a9b4adde4d656a323e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gbox.jl", "max_issues_repo_name": "ruboerner/GravMag", "max_issues_repo_head_hexsha": "6d3ace710b99416d827276a9b4adde4d656a323e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gbox.jl", "max_forks_repo_name": "ruboerner/GravMag", "max_forks_repo_head_hexsha": "6d3ace710b99416d827276a9b4adde4d656a323e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-20T04:49:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-20T04:49:06.000Z", "avg_line_length": 28.1428571429, "max_line_length": 87, "alphanum_fraction": 0.5258883249, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924785827002, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7806788890536217}}
{"text": "# # [Ecosystem Models](@id ecosystem_example)\n#\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/examples/Ecosystem.ipynb)\n\nusing AlgebraicDynamics\nusing AlgebraicDynamics.DWDDynam\nusing AlgebraicDynamics.UWDDynam\n\nusing Catlab.CategoricalAlgebra\nusing Catlab.WiringDiagrams\nusing Catlab.Graphics\nusing Catlab.Programs\n\nusing LabelledArrays\nusing OrdinaryDiffEq\nusing Plots, Plots.PlotMeasures\n\n\n# There will be 16 parameters in to the total ecosystem. With four distinct types:\n# - parameters $\\alpha$ represent the rate at which a species population grows\n# - parameters $\\beta$ represent the rate at which a population of prey declines in a predation interaction\n# - parameters $\\gamma$ represent the rate at which a population of predators grows in a predation interaction\n# - parameters $\\delta$ represent the rate at with a species population declines\n\nparams = LVector(αr=0.3, βrf=0.015, γrf=0.015, δf=0.7,                     \n                 βrh=0.01, γrh=0.01, δh=0.5, \n                 γfishh=0.001, βfishh=0.003, \n                 αfish=0.35, βfishF=0.015, γfishF=0.015, \n                 δF=0.7, βFs=0.017, γFs=0.017, δs=0.35)\n\n# ## Land Ecosystem\n\n# ### Rabbits and foxes\n\n# A standard Lotka Volterra predator-prey model is the composition of three primitive resource sharers:\n\n# 1. a model of rabbit growth: this resource sharer has dynamics $\\dot r(t) = \\alpha r(t)$ and one port which exposes the rabbit population.\n# 2. a model of rabbit/fox predation: this resource sharer has dynamics $$\\dot r(t) = -\\beta r(t) f(t), \\dot f(t) = \\gamma r(t)f(t)$$ and two ports which expose the rabbit and fox populations respectively.\n# 3. a model of fox population decline: this resource sharer has dynamics $\\dot f(t) = -\\delta f(t)$ and one port which exposes the fox population.\n\n# However, there are not two independent rabbit populations -- one that grows and one that gets eaten by foxes. Likewise, there are not two independent fox populations -- one that declines and one that feasts on rabbits. To capture these interactions between the trio of resource sharers, we compose them by identifying the exposed rabbit populations and identifying the exposed fox populations. \n# The syntax for this undirected composition is defined by an undirected wiring diagram.\n\n\n## Define the primitive systems\ndotr(u,p,t) = p.αr*u\ndotrf(u,p,t) = [-p.βrf*u[1]*u[2], p.γrf*u[1]*u[2]]\ndotf(u,p,t) = -p.δf*u\n\nrabbit_growth = ContinuousResourceSharer{Float64}(1, dotr)\nrabbitfox_predation = ContinuousResourceSharer{Float64}(2, dotrf)\nfox_decline = ContinuousResourceSharer{Float64}(1, dotf)\n\n## Define the composition pattern\nrabbitfox_pattern = @relation (rabbits, foxes) begin\n    rabbit_growth(rabbits)\n    rabbitfox_predation(rabbits,foxes)\n    fox_decline(foxes)\nend\n\n## Compose\nsubmodels = Dict(\n    :rabbit_growth => rabbit_growth, \n    :rabbitfox_predation => rabbitfox_predation, \n    :fox_decline => fox_decline\n)\nrabbitfox_system = oapply(rabbitfox_pattern, submodels)\n\n# Previously, when we derived the Lotka-Volterra model via [undirected composition](https://algebraicjulia.github.io/AlgebraicDynamics.jl/dev/examples/Lotka-Volterra/#Undirected-composition), we by-hand defined the undirected wiring diagram that implements the composition pattern. In contrast, here we implement the same composition pattern as before but this time using the [`@relation` macro](https://algebraicjulia.github.io/Catlab.jl/stable/apis/programs/#Catlab.Programs.RelationalPrograms.@relation-Tuple). This strategy simplifies the definition and explicitly names the boxes and variables. We  visualize the composition pattern below.\n\nto_graphviz(rabbitfox_pattern, box_labels = :name, junction_labels = :variable, edge_attrs=Dict(:len => \".75\"))\n\n# We can now construct an `ODEProblem` from the resource sharer `rabbitfox_system` and plot the solution.\nu0 = [10.0, 100.0]\ntspan = (0.0, 100.0)\n\nprob = ODEProblem(rabbitfox_system, u0, tspan, params)\nsol = solve(prob, Tsit5())\n\nplot(sol, rabbitfox_system,\n    lw=2, \n    title = \"Lotka-Volterra Predator-Prey Model\",\n    xlabel = \"time\", ylabel = \"population size\")\n\n# ### Rabbits, foxes, and hawks\n# Suppose we now have a three species ecosystem containing rabbits, foxes, and hawks. Foxes and hawks both prey upon rabbits but do not interact with each other. This ecosystem consists of five primitive systems which share variables.\n# 1. rabbit growth:  $\\dot r(t) = \\alpha r(t)$\n# 2. rabbit/fox predation:  $\\dot r(t) = -\\beta r(t) f(t), \\dot f(t) = \\delta r(t)f(t)$\n# 3. fox decline:  $\\dot f(t) = -\\gamma f(t)$\n# 4. rabbit/hawk predation: $\\dot r(t) = -\\beta' r(t)h(t), \\dot h(t) = \\delta' r(t)h(t)$\n# 5. hawk decline:  $\\dot h(t) = -\\gamma' h(t)$\n\n# This means the desired composition pattern has five boxes and many ports and wires to keep track of. Instead of implementing this composition pattern by hand, we construct it as a pushout.\n\n\n## Define the composition pattern for rabbit growth\nrabbit_pattern = @relation (rabbits,) -> rabbit_growth(rabbits)\n\n## Define the composition pattern for the rabbit/hawk Lotka Volterra model\nrabbithawk_pattern = @relation (rabbits, hawks) begin\n    rabbit_growth(rabbits)\n    rabbithawk_predation(rabbits,hawks)\n    hawk_decline(hawks)\nend\n\n## Define transformations between the composition patterns\nrabbitfox_transform  = ACSetTransformation((Box=[1], Junction=[1], Port=[1], OuterPort=[1]), rabbit_pattern, rabbitfox_pattern)\nrabbithawk_transform = ACSetTransformation((Box=[1], Junction=[1], Port=[1], OuterPort=[1]), rabbit_pattern, rabbithawk_pattern)\n\n## Take the pushout to define the composition pattern for the rabbit, fox, hawk system\nrabbitfoxhawk_pattern = ob(pushout(rabbitfox_transform, rabbithawk_transform))\n\n## Visualize the compsition pattern\nto_graphviz(rabbitfoxhawk_pattern, box_labels = :name, junction_labels = :variable, edge_attrs=Dict(:len => \".9\"))\n\n#-\n## Define the additional primitive systems\ndotrh(u, p, t) = [-p.βrh*u[1]*u[2], p.γrh*u[1]*u[2]]\ndoth(u, p, t)  = -p.δh*u\n\nrabbithawk_predation = ContinuousResourceSharer{Float64}(2, dotrh)\nhawk_decline         = ContinuousResourceSharer{Float64}(1, doth)\n\n## Compose\nmerge!(submodels, Dict(\n    :rabbithawk_predation => rabbithawk_predation,\n    :hawk_decline => hawk_decline\n))\n\nland_system = oapply(rabbitfoxhawk_pattern, submodels)\n\n## Solve and plot\nu0 = [10.0, 100.0, 50.0]\ntspan = (0.0, 100.0)\n\nprob = ODEProblem(land_system, u0, tspan, params)\nsol = solve(prob, Tsit5())\n\nplot(sol, land_system, \n    lw=2, \n    title = \"Land Ecosystem\",\n    xlabel = \"time\", ylabel = \"population size\")\n\n# Unfortunately, the hawks are going extinct in this model. We'll have to give hawks something else to eat!\n#-\n# ## Ocean Ecosystem\n\n# Consider a ocean ecosystem containing three species —- little fish, big fish, and sharks -— with two predation interactions —- sharks eat big fish and big fish eat little fish.\n\n# This ecosystem can be modeled as the composition of 3 machines:\n# 1. Evolution of the little fish population:  this machine has one exogenous variable which represents a population of predators $h(t)$ that hunt little fish. This machine has one output which emits the little fish population. The dynamics of this machine is the driven ODE $$\\dot f(t) = \\alpha f(t) - \\beta f(t)h(t)$$\n# 2. Evolution of the big fish population:  this machine has two exogenous variables which represent a population of prey $e(t)$ that are eaten by big fish and a population of predators $h(t)$ which hunt big fish. This machine has one output which emits the big fish population. The dynamics of this machine is the drive ODE $$\\dot F(t) = \\gamma F(t)e(t) - \\delta F(t) - \\beta'F(t)h(t)$$\n# 3. Evolution of the shark population:  this machine has one exogenous variable which represents a population of prey $e(t)$ that are eaten by sharks. This machine has one output which emits the shark population. The dynamics of this machine is the driven ODE $$\\dot s(t) = \\gamma's(t)e(t) - \\delta's(t)$$\n\n\n## Define the primitive systems\ndotfish(f, x, p, t) = [p.αfish*f[1] - p.βfishF*x[1]*f[1]]\ndotFISH(F, x, p, t) = [p.γfishF*x[1]*F[1] - p.δF*F[1] - p.βFs*x[2]*F[1]]\ndotsharks(s, x, p, t) = [p.γFs*s[1]*x[1]-p.δs*s[1]]\n\nfish   = ContinuousMachine{Float64}(1,1,1, dotfish,   (f,p,t)->f)\nFISH   = ContinuousMachine{Float64}(2,1,1, dotFISH,   (F,p,t)->F)\nsharks = ContinuousMachine{Float64}(1,1,1, dotsharks, (s,p,t)->s)\n\n# We compose these machines by (1) sending the output of the big fish machine as the input to both the little fish and shark machines and (2) sending the output of the little fish and shark machines as the inputs to the big fish machine.\n# The syntax for this directed composition is given by a directed wiring diagram.\n\n## Define the composition pattern\nocean_pattern = WiringDiagram([], [:fish, :Fish, :shark])\nfish_box = add_box!(ocean_pattern, Box(:fish, [:pop], [:pop]))\nFish_box = add_box!(ocean_pattern, Box(:Fish, [:pop, :pop], [:pop]))\nshark_box = add_box!(ocean_pattern, Box(:shark, [:pop], [:pop]))\n\noutput_box = output_id(ocean_pattern)\nadd_wires!(ocean_pattern, Pair[\n    (fish_box, 1)  => (Fish_box, 1),\n    (shark_box, 1) => (Fish_box, 2),\n    (Fish_box, 1)  => (fish_box, 1),\n    (Fish_box, 1)  => (shark_box, 1),\n    (fish_box, 1)  => (output_box, 1),\n    (Fish_box, 1)  => (output_box, 2),\n    (shark_box, 1) => (output_box, 3)\n])\n\n## Visualize the composition pattern\nto_graphviz(ocean_pattern, orientation=TopToBottom)\n\n#-\n\n## Compose\nocean_system = oapply(ocean_pattern, [fish, FISH, sharks])\n\n## Solve and plot\nu0 = [100.0, 10, 2.0]\ntspan = (0.0, 100.0)\n\nprob = ODEProblem(ocean_system, u0, tspan, params)\nsol = solve(prob, Tsit5())\n\nplot(sol, ocean_system,\n    lw=2, title = \"Ocean Ecosystem\",\n    xlabel = \"time\", ylabel = \"population size\"\n)\n\n# ## Total ecosystem\n# ### Another layer of composition\n\n# We will introduce a final predation interaction -- hawks eat little fish --  which will combine the land and ocean ecosystems.\n# The composition will be as resource shareres so the first thing we will do is use the dynamics of the machine `ocean_system` to define the dynamics of a resource sharer. We will also define a resource sharer that models hawk/little fish predation.\n\n\n## Define the additional primitive systems\nocean_system_rs = ContinuousResourceSharer{Float64}(3, (u,p,t) -> eval_dynamics(ocean_system, u, [], p))\n\ndothf(u,p,t) = [p.γfishh*u[1]*u[2], -p.βfishh*u[1]*u[2]]\nfishhawk_predation = ContinuousResourceSharer{Float64}(2, dothf)\n\n## Define the composition pattern\neco_pattern = @relation (rabbits, foxes, hawks, littlefish, BigFish, sharks)  begin\n    turf(rabbits,foxes,hawks)\n    air(hawks, littlefish)\n    surf(littlefish, BigFish, sharks)\nend\n\n## Visualize the composition pattern\nto_graphviz(eco_pattern, box_labels = :name, junction_labels = :variable, edge_attrs=Dict(:len => \".75\"))\n\n#-\n## Compose\n\necosystem = oapply(eco_pattern, Dict(\n    :turf => land_system,\n    :air => fishhawk_predation,\n    :surf => ocean_system_rs)\n)\n\n# We can now plot the evolution of the total ecosystem.\n\n## Solve and plot\nu0 = [100.0, 50.0, 20.0, 100, 10, 2.0]\ntspan = (0.0, 100.0)\n\nprob = ODEProblem(ecosystem, u0, tspan, params)\nsol = solve(prob, Tsit5())\nplot(sol, ecosystem,\n    lw=2, title = \"Total Ecosystem\", \n    xlabel = \"time\", ylabel = \"population size\"\n)\n\n# Let's zoom in on a narrower time-window.\ntspan = (0.0, 30.0)\n\nprob = ODEProblem(ecosystem, u0, tspan, params)\nsol = solve(prob, Tsit5())\nplot(sol, ecosystem,\n    lw=2, title = \"Total Ecosystem\", \n    xlabel = \"time\", ylabel = \"population size\"\n)\n# As a sanity check we can define the rates for the hawk/little fish predation to be 0. This decouples the land and ocean ecosystems. As expected, the plot shows the original evolution of the land ecosystem overlayed with the original evolution of the ocean ecosystem. This shows that they two ecosystems now evolve independently.\n\ntspan = (0.0, 100.0)\nparams.βfishh = 0; params.γfishh = 0\n\nprob = ODEProblem(ecosystem, u0, tspan, params)\nsol = solve(prob, Tsit5())\nplot(sol, ecosystem,\n    lw=2, title = \"Decoupled Ecosystem\", \n    xlabel = \"time\", ylabel = \"population size\"\n)", "meta": {"hexsha": "059091a68e06c7e28d4bb45c21c17db48c608352", "size": 12141, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Ecosystem.jl", "max_stars_repo_name": "stjordanis/AlgebraicDynamics.jl", "max_stars_repo_head_hexsha": "70065459dc5fe19322a0d7972fadba3d21be4458", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2021-01-15T19:06:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T17:31:38.000Z", "max_issues_repo_path": "examples/Ecosystem.jl", "max_issues_repo_name": "stjordanis/AlgebraicDynamics.jl", "max_issues_repo_head_hexsha": "70065459dc5fe19322a0d7972fadba3d21be4458", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2021-02-15T21:35:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T04:08:46.000Z", "max_forks_repo_path": "examples/Ecosystem.jl", "max_forks_repo_name": "stjordanis/AlgebraicDynamics.jl", "max_forks_repo_head_hexsha": "70065459dc5fe19322a0d7972fadba3d21be4458", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-02-08T23:29:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T04:17:54.000Z", "avg_line_length": 45.1338289963, "max_line_length": 644, "alphanum_fraction": 0.7223457705, "num_tokens": 3508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8418256432832332, "lm_q1q2_score": 0.7806781961551863}}
{"text": "## Julia program for Gamma Metropolis-Hastings\r\n## author: weiya <szcfweiya@gmail.com>\r\n## date: 2018-08-21\r\n\r\n## import function gamma_int\r\ninclude(\"../../GenRV/gamma.jl\")\r\n\r\nfunction mh_gamma(T = 100, alpha = 1.5)\r\n    a = Int(floor(alpha))\r\n    b = a/alpha\r\n    x = ones(T+1) # initial value: 1\r\n    for t = 1:T\r\n        yt = rgamma_int(a, b)\r\n        rt = (yt / x[t] * exp((x[t] - yt) / alpha))^(alpha-a)\r\n        if rt >= 1\r\n            x[t+1] = yt\r\n        else\r\n            u = rand()\r\n            if u < rt\r\n                x[t+1] = yt\r\n            else\r\n                x[t+1] = x[t]\r\n            end\r\n        end   \r\n    end\r\n    return(x)\r\nend\r\n\r\n# example\r\nmh_gamma()\r\n\r\n# comparison with accept-reject\r\nres = mh_gamma(5000, 2.43)[2:end]\r\nest = cumsum(res.^2) ./ collect(1:5000)\r\n\r\nres2 = ones(5000)\r\nfor i = 1:5000\r\n    res2[i] = rgamma(2.43, 1)\r\nend\r\nest2 = cumsum(res2.^2) ./ collect(1:5000)\r\n\r\nusing Plots\r\nplot(est, label=\"Independent MH\")\r\nplot!(est2, label=\"Accept-Reject\")\r\nhline!([8.33], label=\"True value\")", "meta": {"hexsha": "fe8d4a7e5db80d698ef436081a113b5c7a5fcde7", "size": 1028, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "MH/IMH/gamma_imh.jl", "max_stars_repo_name": "szcf-weiya/MCMC", "max_stars_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-07-19T12:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T08:06:50.000Z", "max_issues_repo_path": "MH/IMH/gamma_imh.jl", "max_issues_repo_name": "szcf-weiya/MCMC", "max_issues_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-02-03T15:08:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-05T15:41:39.000Z", "max_forks_repo_path": "MH/IMH/gamma_imh.jl", "max_forks_repo_name": "szcf-weiya/MCMC", "max_forks_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-07-19T12:50:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T08:06:52.000Z", "avg_line_length": 22.8444444444, "max_line_length": 62, "alphanum_fraction": 0.5107003891, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7806781960051096}}
{"text": "# From HyperDualNumbers\nconst DIFF_RULES = [\n    (  :sqrt,    :(1/2/sqrt(x)),                       :(-1/4/(sqrt(x) * x)))\n    (  :cbrt,    :(1/3/x^(2/3)),                       :(-2/9/x^(5/3)))\n    (  :abs2,    :(2*x),                               :(2))\n    (  :abs,     :(signbit(x) ? -one(x) : one(x)),     :(0))\n    (  :inv,     :(-1/x^2),                            :(2/x^3))\n    (  :log,     :(1/x),                               :(-1/x^2))\n    (  :log10,   :(1/(log(10)*x)),                     :(-1/(log(10)*x^2)))\n    (  :log2,    :(1/(log(2)*x)),                      :(-1/(log(2)*x^2)))\n    (  :log1p,   :(1/(x + 1)),                         :(-1/(x + 1)^2))\n    (  :exp,     :(exp(x)),                            :(exp(x)))\n    (  :exp2,    :(2^x*log(2)),                        :(2^x*log(2)^2))\n    (  :exp10,   :(10^x*log(10)),                      :(10^x*log(10)^2))\n    (  :expm1,   :(exp(x)),                            :(exp(x)))\n   #( :sin,     :(cos(x)),                             :(-sin(x)))\n   #( :cos,     :(-sin(x)),                            :(-cos(x)))\n    (  :tan,     :(tan(x)^2 + 1),                      :(2*(tan(x)^2 + 1)*tan(x)))\n    (  :sec,     :(sec(x)*tan(x)),                     :(sec(x)*tan(x)^2 + (tan(x)^2 + 1)*sec(x)))\n    (  :csc,     :(-cot(x)*csc(x)),                    :(cot(x)^2*csc(x) + (cot(x)^2 + 1)*csc(x)))\n    (  :cot,     :(-cot(x)^2 - 1),                     :(2*(cot(x)^2 + 1)*cot(x)))\n    (  :sind,    :(π*cos(π*x/180)/180),                :(-π^2*sin(π*x/180)/180^2))\n    (  :cosd,    :(-π*sin(π*x/180)/180),               :(-π^2*cos(π*x/180)/180^2))\n    (  :tand,    :(π*(tan(π*x/180)^2 + 1)/180),        :(2*π^2*(tan(π*x/180)^2 + 1)*tan(π*x/180)/180^2))\n    (  :secd,    :(π*sec(π*x/180)*tan(π*x/180)/180),   :(π^2*sec(π*x/180)*tan(π*x/180)^2/180^2 + π^2*(tan(π*x/180)^2 + 1)*sec(π*x/180)/180^2))\n    (  :cscd,    :(-π*cot(π*x/180)*csc(π*x/180)/180),  :(π^2*cot(π*x/180)^2*csc(π*x/180)/180^2 + π^2*(cot(π*x/180)^2 + 1)*csc(π*x/180)/180^2))\n    (  :cotd,    :(-π*(cot(π*x/180)^2 + 1)/180),       :(2*π^2*(cot(π*x/180)^2 + 1)*cot(π*x/180)/180^2))\n    (  :asin,    :(1/sqrt(-x^2 + 1)),                  :(x/(-x^2 + 1)^(3/2)))\n    (  :acos,    :(-1/sqrt(-x^2 + 1)),                 :(-x/(-x^2 + 1)^(3/2)))\n    (  :atan,    :(1/(x^2 + 1)),                       :(-2*x/(x^2 + 1)^2))\n    (  :asec,    :(1/(sqrt(x^2 - 1)*x)),               :(-1/(x^2 - 1)^(3/2) - 1/(sqrt(x^2 - 1)*x^2)))\n    (  :acsc,    :(-1/(sqrt(x^2 - 1)*x)),              :(1/(x^2 - 1)^(3/2) + 1/(sqrt(x^2 - 1)*x^2)))\n    (  :acot,    :(-1/(x^2 + 1)),                      :(2*x/(x^2 + 1)^2))\n    (  :asind,   :(π/(sqrt(-π^2*x^2/180^2 + 1)*180)),  :(π^3*x/((-π^2*x^2/180^2 + 1)^(3/2)*180^3)))\n    (  :acosd,   :(-π/(sqrt(-π^2*x^2/180^2 + 1)*180)), :(-π^3*x/((-π^2*x^2/180^2 + 1)^(3/2)*180^3)))\n    (  :atand,   :(π/((π^2*x^2/180^2 + 1)*180)),       :(-2*π^3*x/((π^2*x^2/180^2 + 1)^2*180^3)))\n    (  :asecd,   :(1/(sqrt(π^2*x^2/180^2 - 1)*x)),     :(-π^2/((π^2*x^2/180^2 - 1)^(3/2)*180^2) - 1/(sqrt(π^2*x^2/180^2 - 1)*x^2)))\n    (  :acscd,   :(-1/(sqrt(π^2*x^2/180^2 - 1)*x)),    :(π^2/((π^2*x^2/180^2 - 1)^(3/2)*180^2) + 1/(sqrt(π^2*x^2/180^2 - 1)*x^2)))\n    (  :acotd,   :(-π/((π^2*x^2/180^2 + 1)*180)),      :(2*π^3*x/((π^2*x^2/180^2 + 1)^2*180^3)))\n    (  :sinh,    :(cosh(x)),                           :(sinh(x)))\n    (  :cosh,    :(sinh(x)),                           :(cosh(x)))\n    (  :tanh,    :(-tanh(x)^2 + 1),                    :(2*(tanh(x)^2 - 1)*tanh(x)))\n    (  :sech,    :(-sech(x)*tanh(x)),                  :(sech(x)*tanh(x)^2 + (tanh(x)^2 - 1)*sech(x)))\n    (  :csch,    :(-coth(x)*csch(x)),                  :(coth(x)^2*csch(x) + csch(x)/sinh(x)^2))\n    (  :coth,    :(-1/sinh(x)^2),                      :(2*cosh(x)/sinh(x)^3))\n    (  :asinh,   :(1/sqrt(x^2 + 1)),                   :(-x/(x^2 + 1)^(3/2)))\n    (  :acosh,   :(1/(sqrt(x + 1)*sqrt(x - 1))),       :(-1/2/(sqrt(x + 1)*(x - 1)^(3/2)) - 1/2/((x + 1)^(3/2)*sqrt(x - 1))))\n    (  :atanh,   :(-1/(x^2 - 1)),                      :(2*x/(x^2 - 1)^2))\n    (  :asech,   :(-1/(sqrt(-x^2 + 1)*x)),             :(-1/(-x^2 + 1)^(3/2) + 1/(sqrt(-x^2 + 1)*x^2)))\n    (  :acsch,   :(-1/(sqrt(x^2 + 1)*x)),              :(1/(x^2 + 1)^(3/2) + 1/(sqrt(x^2 + 1)*x^2)))\n    (  :acoth,   :(-1/(x^2 - 1)),                      :(2*x/(x^2 - 1)^2))\n    (  :deg2rad, :(π/180),                             :(0))\n    (  :rad2deg, :(180/π),                             :(0))\n  # ( :erf,     :(2*exp(-x^2)/sqrt(π)),               :(-4*x*exp(-x^2)/sqrt(π)))\n  # ( :erfinv,  :(1/2*sqrt(π)*exp(erfinv(x)^2)),      :(1/2*π*erfinv(x)*exp(2*erfinv(x)^2)))\n  # ( :erfc,    :(-2*exp(-x^2)/sqrt(π)),              :(4*x*exp(-x^2)/sqrt(π)))\n  # ( :erfi,    :(2*exp(x^2)/sqrt(π)),                :(4*x*exp(x^2)/sqrt(π)))\n    (  :cospi,   :(-π*sinpi(x)),                       :(-π^2*cospi(x)))\n    (  :sinpi,   :(π*cospi(x)),                        :(-π^2*sinpi(x)))\n]\n\nchangeprecision(x) = x\nchangeprecision(x::Integer) = :(T($x))\nfunction changeprecision(x::Symbol)\n    x == :π  ?  :(T($x)) : x\nend\nfunction changeprecision(ex::Expr)\n    if Meta.isexpr(ex, :call, 3) && ex.args[1] == :^ && ex.args[3] isa Int\n        return Expr(:call, :^, changeprecision(ex.args[2]), ex.args[3])\n    else\n        return Expr(ex.head, changeprecision.(ex.args)...)\n    end\nend\n\nfor (i, rule) in enumerate(DIFF_RULES)\n    prec_f′ = changeprecision(rule[2])\n    prec_f′′ = changeprecision(rule[3])\n    DIFF_RULES[i] = (rule[1], prec_f′, prec_f′′)\nend", "meta": {"hexsha": "c6bfb2b55f446cfaf22d079f2b119ba6ff15d535", "size": 5504, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rules.jl", "max_stars_repo_name": "KristofferC/FastHessians.jl", "max_stars_repo_head_hexsha": "0de3c29b04177cf666962ac6251905fb89378dca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-11-29T12:59:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T07:45:38.000Z", "max_issues_repo_path": "src/rules.jl", "max_issues_repo_name": "KristofferC/HyperHessians.jl", "max_issues_repo_head_hexsha": "0de3c29b04177cf666962ac6251905fb89378dca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rules.jl", "max_forks_repo_name": "KristofferC/HyperHessians.jl", "max_forks_repo_head_hexsha": "0de3c29b04177cf666962ac6251905fb89378dca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 69.6708860759, "max_line_length": 142, "alphanum_fraction": 0.3366642442, "num_tokens": 2412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305381464927, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.7806780265360943}}
{"text": "using Interpolations\nusing Plots\nplotly()\n\n# Example\nA_x = 1.:2.:40.\nA = [log(x) for x in A_x]\nitp = interpolate(A, BSpline(Cubic(Line(OnGrid()))))\n\nsitp = scale(itp, A_x)\n\nsitp(3.0)\nsitp(3.5)\n\nx = convert(Vector{Float64}, range(1.0, 39.0, step=0.25))\nỹ = sitp.(x)\ny = log.(x)\nplot(x, ỹ)\nplot!(x, y)\n\n# parametric-splines\nt = 0:0.1:1\nx = sin.(2pi*t)\ny = cos.(2pi*t)\nA = hcat(x,y)\n\nitp = Interpolations.scale(interpolate(A, (BSpline(Cubic(Natural(OnGrid()))), NoInterp())), t, 1:2)\ntfine = 0:0.01:1\nxs, ys = [itp(t, 1) for t in tfine], [itp(t,2) for t in tfine]\n\nscatter(x, y, label=\"knots\")\nplot!(xs, ys, label=\"spline\")\n\nitp1 = Interpolations.scale(interpolate(A, (BSpline(Cubic(Natural(OnCell()))), NoInterp())), t, 1:2)\nxs1, ys1 = [itp1(t, 1) for t in tfine], [itp1(t,2) for t in tfine]\nplot!(xs1, ys1, label=\"spline2\")\n\nitp2 = Interpolations.scale(interpolate(A, (BSpline(Cubic(Periodic(OnCell()))), NoInterp())), t, 1:2)\nxs2, ys2 = [itp2(t, 1) for t in tfine], [itp2(t,2) for t in tfine]\nplot!(xs2, ys2, label=\"spline3\")\n\n# itp3 = Interpolations.scale(interpolate(A, (BSpline(Cubic(Free(OnCell()))), NoInterp())), t, 1:2)\n# xs3, ys3 = [itp3(t, 1) for t in tfine], [itp3(t,2) for t in tfine]\n# plot!(xs3, ys3, label=\"spline3\")\n#\n# itp4 = Interpolations.scale(interpolate(A, (BSpline(Cubic(Free(OnGrid()))), NoInterp())), t, 1:2)\n# xs4, ys4 = [itp4(t, 1) for t in tfine], [itp4(t,2) for t in tfine]\n# plot!(xs4, ys4, label=\"spline4\")\n#\n# itp5 = Interpolations.scale(interpolate(A, (BSpline(Cubic(Reflect(OnGrid()))), NoInterp())), t, 1:2)\n# xs5, ys5 = [itp5(t, 1) for t in tfine], [itp5(t,2) for t in tfine]\n# plot!(xs5, ys5, label=\"spline5\")\n\n# parametric-splines 2\nt = [0.0, 1/6, 1/6, 2/6, 3/6, 3/6, 4/6, 5/6, 5/6, 1.0]\nx = [0.0, -2.0, -2.0, -3.0, -4.0, -4.0, 0.25, 4.5, 4.5, 0.0]\ny = [0.0, -2.0, -2.0, 0.0, -2.0, -2.0, 0.0, -2.0, -2.0, 0.0]\nA = hcat(x,y)\n\nitp = Interpolations.scale(interpolate(A, (BSpline(Cubic(Natural(OnGrid()))), NoInterp())), t, 1:2)\ntfine = 0:0.01:1\nxs, ys = [itp(t, 1) for t in tfine], [itp(t,2) for t in tfine]\n\nscatter(x, y, label=\"knots\")\nplot!(xs, ys, label=\"spline\")\n\nitp1 = Interpolations.scale(interpolate(A, (BSpline(Cubic(Natural(OnCell()))), NoInterp())), t, 1:2)\nxs1, ys1 = [itp1(t, 1) for t in tfine], [itp1(t,2) for t in tfine]\nplot!(xs1, ys1, label=\"spline2\")\n\nitp2 = Interpolations.scale(interpolate(A, (BSpline(Cubic(Periodic(OnCell()))), NoInterp())), t, 1:2)\nxs2, ys2 = [itp2(t, 1) for t in tfine], [itp2(t,2) for t in tfine]\nplot!(xs2, ys2, label=\"spline3\")\n\nusing BSplines\n\nbasis = BSplines.BSplineBasis(4, 0:5)\nplot(basis)\nspl = BSplines.approximate(sin, basis)\nplot(1:5, spl)\nplot(spl, 1,3)\nplot(spl)\n\nf1 = Function(spl)\nf2 = Function(spl, Derivative(1))\nf3 = Function(spl, Derivative(2))\nplot([f1, f2, f3])\n\nbasis2 = BSplineBasis(3, [1, 2, 3, 4, 5, 5, 6, 7, 8])\nplot(basis2)\nBSplines.knots(basis2)\nb = bsplines(basis2, 3.5)\n\n# splines consist of b-spline basis and a coefficient vector of the same length\nt = [0, 1, 2, 3, 4, 5]\npoints = [0 0; 1 0; 1 1; 0 1; 0 2; 1 2];\nx = points[:,1]\ny = points[:,2]\nplot(t,x); scatter!(t,x)\nplot(t,y); scatter!(t,y)\nplot(x,y); scatter!(x,y)\n\nbasis = averagebasis(3, t)\nxspline = BSplines.interpolate(basis, t, x)\nplot(t, xspline); scatter!(t, x)\nyspline = BSplines.interpolate(basis, t, y)\nplot(t, yspline); scatter!(t, y)\nxapprox = xspline.(range(0, 5.0; length=100))\nyapprox = yspline.(range(0.0, 5.0; length=100))\nplot(xapprox, yapprox); scatter!(x,y)\n\n# 3-d splines\nt = [0, 1, 2, 3, 4, 5]\npoints = [0 0 0; 1 0 0; 1 1 0; 0 1 0; 0 2 0; 1 2 0];\nx = points[:,1]\ny = points[:,2]\nz = points[:,3]\nplot(t,x); scatter!(t,x)\nplot(t,y); scatter!(t,y)\nplot(t,z); scatter!(t,z)\nplot3d(x,y,z); scatter3d!(x,y,z)\n\nbasis = averagebasis(3,t)\nxspline = BSplines.interpolate(basis, t, x)\nplot(xspline); scatter!(t,x)\nyspline = BSplines.interpolate(basis, t, y)\nplot(yspline); scatter!(t,y)\nzspline = BSplines.interpolate(basis, t, z)\nplot(zspline); scatter!(t,z)\nxapprox = xspline.(range(0, 5.0; length=100))\nyapprox = yspline.(range(0.0, 5.0; length=100))\nzapprox = zspline.(range(0.0, 5.0; length=100))\nplot3d(xapprox, yapprox, zapprox)\nscatter3d!(x,y,z)\n\n# get the derivatives\nxdis = Function(xspline)\nxvel = Function(xspline, Derivative(1))\nxacc = Function(xspline, Derivative(2))\nplot([xdis, xvel, xacc], labels=[\"disp\",\"vel\", \"acc\"])\n\nydis = Function(yspline)\nyvel = Function(yspline, Derivative(1))\nyacc = Function(yspline, Derivative(2))\n# yjerk = Function(yspline, Derivative(3))\nplot([ydis, yvel, yacc], labels=[\"disp\",\"vel\", \"acc\"])\n\nzdis = Function(zspline)\nzvel = Function(zspline, Derivative(1))\nzacc = Function(zspline, Derivative(2))\nplot([zdis, zvel, zacc], labels=[\"disp\",\"vel\", \"acc\"])\n\n# try a 3-d path\nt = [0, 1, 2, 3, 4]\npoints = [0 0 0; 0 0.5 -2; 1 1 0; 2 1.5 -2; 0 0 0];\nx = points[:,1]\ny = points[:,2]\nz = points[:,3]\nplot(t,x); scatter!(t,x)\nplot(t,y); scatter!(t,y)\nplot(t,z); scatter!(t,z)\nplot3d(x,y,z); scatter3d!(x,y,z)\n\nbasis = averagebasis(3,t)\nxspline = BSplines.interpolate(basis, t, x)\nplot(xspline); scatter!(t,x)\nyspline = BSplines.interpolate(basis, t, y)\nplot(yspline); scatter!(t,y)\nzspline = BSplines.interpolate(basis, t, z)\nplot(zspline); scatter!(t,z)\nxapprox = xspline.(range(0, 5.0; length=100))\nyapprox = yspline.(range(0.0, 5.0; length=100))\nzapprox = zspline.(range(0.0, 5.0; length=100))\nplot3d(xapprox, yapprox, zapprox)\nscatter3d!(x,y,z)\n\n# try another basis with stops at -2 points\nt = [0, 1, 2, 3, 4]\npoints = [0 0 0; 0 0.5 -2; 1 1 0; 2 1.5 -2; 0 0 0];\nx = points[:,1]\ny = points[:,2]\nz = points[:,3]\nplotly()\np1 = plot(t,x, label=\"x\"); scatter!(t,x, label=:none)\np2 = plot(t,y, label=\"y\", linecolor=:green); scatter!(t,y, label=:none)\np3 = plot(t,z, label=\"z\", linecolor=:purple); scatter!(t,z, label=\"Via Points\")\nplt = plot(p1, p2, p3, layout=(3,1), legend=:outertopright)\np4 = plot3d(x,y,z, xlabel=\"x\", ylabel=\"y\", zlabel=\"z\", label=:none); scatter3d!(x,y,z, markersize=2, label=:none)\nplt2 = plot(plt, p4, layout=(1,2))\n\n\nplotly()\nbasis = averagebasis(3, t)\nbasis = BSplines.BSplineBasis(4, [0.0, 1.0, 1.0, 2.0, 3.0, 3.0, 4.0]) # BEAUTIFUL!\n# basis = averagebasis(4, t)\n# basis = BSplines.BSplineBasis(3, [0.0, 0.0, 1.0, 1.0, 1.5, 2.5, 4.0, 4.0])\n# basis = BSplines.BSplineBasis(4, [0.0, 0.0, 1.0, 1.0, 3.0, 3.0, 4.0, 4.0]) # BEAUTIFUL!\n# basis = BSplines.BSplineBasis(4, [0.0, 0.0, 1.0, 3.0, 4.0, 4.0]) # BEAUTIFUL!\nxspline = BSplines.interpolate(basis, t, x)\np1 = plot(xspline, label=\"x\"); scatter!(t,x, label=:none)\nyspline = BSplines.interpolate(basis, t, y)\np2 = plot(yspline, label=\"y\", linecolor=:green); scatter!(t,y, label=:none)\nzspline = BSplines.interpolate(basis, t, z)\np3 = plot(zspline, label=\"z\", linecolor=:purple); scatter!(t,z, label=\"Via Points\")\nplt = plot(p1, p2, p3, layout=(3,1), legend=:outertopright)\nxapprox = xspline.(range(0.0, 4.0; length=401))\nyapprox = yspline.(range(0.0, 4.0; length=401))\nzapprox = zspline.(range(0.0, 4.0; length=401))\np4 = plot3d(xapprox, yapprox, zapprox, xlabel=\"x\", ylabel=\"y\", zlabel=\"z\", label=:none); scatter3d!(x,y,z, markersize=2, label=:none)\nplt2 = plot(plt, p4, layout=(1,2))\n\nplot(basis, legend=:none, title=\"Trajectory Basis Functions\")\n\n# get the derivatives\nxdis = Function(xspline)\nxvel = Function(xspline, Derivative(1))\nxacc = Function(xspline, Derivative(2))\n\nydis = Function(yspline)\nyvel = Function(yspline, Derivative(1))\nyacc = Function(yspline, Derivative(2))\n\nzdis = Function(zspline)\nzvel = Function(zspline, Derivative(1))\nzacc = Function(zspline, Derivative(2))\n", "meta": {"hexsha": "47d6cc796fd9d80fc207b4146f9c67f8ec1e7f95", "size": 7478, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tools/jl/bspline_trajectories.jl", "max_stars_repo_name": "zborffs/Delta", "max_stars_repo_head_hexsha": "b2efa9fe1cc2138656f4d7964ccdbbbfcebba639", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-03T09:34:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T09:34:54.000Z", "max_issues_repo_path": "tools/jl/bspline_trajectories.jl", "max_issues_repo_name": "zborffs/Delta", "max_issues_repo_head_hexsha": "b2efa9fe1cc2138656f4d7964ccdbbbfcebba639", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/jl/bspline_trajectories.jl", "max_forks_repo_name": "zborffs/Delta", "max_forks_repo_head_hexsha": "b2efa9fe1cc2138656f4d7964ccdbbbfcebba639", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0884955752, "max_line_length": 133, "alphanum_fraction": 0.6446910939, "num_tokens": 3160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7806717800310907}}
{"text": "export SinusoidalFit\r\nimport LsqFit\r\n\r\n\"\"\"\r\n    SinusoidalFit(s, fs) <: Decomposition\r\nDecompose a timeseries `s` into a **sum** `x + r` (with `x` the periodic component),\r\nby fitting sinuisoidals with given\r\nfrequencies `fs` to the signal `s` using the package `LsqFit`. Specifically, fit\r\n```math\r\ns - \\\\bar{s} \\\\approx \\\\sum_i A_i \\\\sin(2\\\\pi f_i t + \\\\phi_i)\r\n```\r\nwith ``\\\\bar{s}`` the mean. The fit happens on the amplitudes\r\nand phases ``A_i, \\\\phi_i``. After the `decomposition` you can find these in the struct's\r\nfields `amps, phases`. The fit is done on `s` versus `t`, so be sure that you have\r\ntransformed `t` appropriately (e.g. if `t` is \"days\" but your frequencies are multiples of\r\nyears, then you should give `t/365.26`).\r\n\r\n    SinusoidalFit(fs, φ0s, A0s [, ub, lb])\r\n\r\nThe quality of the fit depends dramatically on the initial guesses for the phases\r\nand amplitudes, `φ0s, A0s`. This second constructor\r\ngives full control over initial phases and amplitudes, as well as\r\nupper and lower bounds on the amplitudes `ub, lb` (also vectors of `length(fs)`).\r\nIn the first constructor `φ0 = 0, A0 = abs(-(extrema(s)...))/2, ub = Inf, lb = -Inf` for\r\nall frequencies. (the bounds for the phases are always ± π)\r\n\r\n**Notice**: `LsqFit` performs poorly for fitting sinusoidals and `Fourier`\r\nshould be preferred over this method if the signal given is in\r\nmultiples of the expected periods (and of course `t` is equally spaced).\r\n\"\"\"\r\nmutable struct SinusoidalFit{T<:AbstractFloat} <: Decomposition\r\n    fs::Vector{T}\r\n    φ0s::Vector{T}\r\n    A0s::Vector{T}\r\n    ub::Vector{T}\r\n    lb::Vector{T}\r\n    amps::Vector{T}\r\n    phases::Vector{T}\r\nend\r\n\r\nfunction SinusoidalFit(s::AbstractVector{T}, fs) where {T}\r\n    φ0s = zero(fs)\r\n    A0s = fill(abs(-(extrema(s)...))/2, length(fs))\r\n    ub = fill(T(Inf), length(fs))\r\n    lb = fill(T(-Inf), length(fs))\r\n    SinusoidalFit{T}(fs, φ0s, A0s, ub, lb, zero(fs), zero(fs))\r\nend\r\n\r\nSinusoidalFit(fs, φ0s, A0s, ub=fill(Inf, length(fs)), lb=fill(-Inf, length(fs))) =\r\nSinusoidalFit{eltype(fs)}(fs, φ0s, A0s, ub, lb, zero(fs), zero(fs))\r\n\r\nfunction decompose(t, s, method::SinusoidalFit{T}) where {T}\r\n    fs = method.fs\r\n    L = length(fs)\r\n    function sinuisoidal(t, p)\r\n        r = zeros(T, length(t))\r\n        for i in 1:L\r\n            @. r += p[i]*sin(2π * (fs[i]*t + p[i+L]))\r\n        end\r\n        return r\r\n    end\r\n\r\n    p0 = vcat(method.A0s, method.φ0s)\r\n    ub = vcat(method.ub, fill( T(π), L))\r\n    lb = vcat(method.lb, fill(-T(π), L))\r\n\r\n    fit = LsqFit.curve_fit(sinuisoidal, t, s .- mean(s), p0; lower=lb, upper=ub)\r\n    method.amps .= LsqFit.coef(fit)[1:L]\r\n    method.phases .= LsqFit.coef(fit)[L+1:2L]\r\n    periodic = sinuisoidal(t, LsqFit.coef(fit)) .+ mean(s)\r\n    return periodic, s .- periodic\r\nend\r\n", "meta": {"hexsha": "a5f25ceeb5823ecac929eea98df80ff286c64915", "size": 2773, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear/lsqfit.jl", "max_stars_repo_name": "JuliaDynamics/SignalDecomposition.jl", "max_stars_repo_head_hexsha": "e865058d48a5e28e827b97ed05e99952f86e9a66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2020-04-04T14:49:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T19:36:47.000Z", "max_issues_repo_path": "src/linear/lsqfit.jl", "max_issues_repo_name": "JuliaDynamics/SignalDecomposition.jl", "max_issues_repo_head_hexsha": "e865058d48a5e28e827b97ed05e99952f86e9a66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-04-04T09:29:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T14:33:06.000Z", "max_forks_repo_path": "src/linear/lsqfit.jl", "max_forks_repo_name": "JuliaDynamics/SignalDecomposition.jl", "max_forks_repo_head_hexsha": "e865058d48a5e28e827b97ed05e99952f86e9a66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9863013699, "max_line_length": 91, "alphanum_fraction": 0.6375766318, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.780671771624425}}
{"text": "# Hessian Eigenmaps (HLLE)\n# ---------------------------\n# Hessian eigenmaps: Locally linear embedding techniques for high-dimensional data,\n# D. Donoho and C. Grimes, Proc Natl Acad Sci U S A. 2003 May 13; 100(10): 5591–5596\n\nimport Combinatorics: combinations\n\n#### HLLE type\nstruct HLLE{T <: Real} <: AbstractDimensionalityReduction\n    k::Int\n    λ::AbstractVector{T}\n    proj::Projection{T}\n\n    HLLE{T}(k::Int, λ::AbstractVector{T}, proj::Projection{T}) where T = new(k, λ, proj)\nend\n\n## properties\noutdim(R::HLLE) = size(R.proj, 1)\neigvals(R::HLLE) = R.λ\nneighbors(R::HLLE) = R.k\n\n## show\nsummary(io::IO, R::HLLE) = print(io, \"Hessian Eigenmaps(outdim = $(outdim(R)), neighbors = $(neighbors(R)))\")\n\n## interface functions\nfunction fit(::Type{HLLE}, X::AbstractMatrix{T}; maxoutdim::Int=2, k::Int=12) where {T<:Real}\n    n = size(X, 2)\n\n    # Identify neighbors\n    D, E = find_nn(X, k)\n\n    # Obtain tangent coordinates and develop Hessian estimator\n    hs = (maxoutdim*(maxoutdim+1)) >> 1\n    W = spzeros(T, hs*n, n)\n    for i=1:n\n        II = @view E[:,i]\n        # re-center points in neighborhood\n        μ = mean(X[:, II], dims=2)\n        N = X[:, II] .- μ\n        # calculate tangent coordinates\n        tc = svd(N).V[:,1:maxoutdim]\n\n        # Develop Hessian estimator\n        Yi = [ones(T, k) tc zeros(T, k, hs)]\n        for ii=1:maxoutdim\n            Yi[:,maxoutdim+ii+1] = tc[:,ii].^2\n        end\n        yi = 2*(1+maxoutdim)\n        for (ii,jj) in combinations(1:maxoutdim, 2)\n            Yi[:, yi] = tc[:, ii] .* tc[:, jj]\n            yi += 1\n        end\n        F = qr(Yi)\n        H = transpose(F.Q[:,(end-(hs-1)):end])\n        W[(1:hs).+(i-1)*hs, II] = H\n    end\n\n    # decomposition\n    λ, V = decompose(transpose(W)*W, maxoutdim)\n    return HLLE{T}(k, λ, transpose(V) .* convert(T, sqrt(n)))\nend\n\ntransform(R::HLLE) = R.proj\n", "meta": {"hexsha": "cc06aeba6adf889d15dbc8f0e4032f310a8d125a", "size": 1849, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hlle.jl", "max_stars_repo_name": "adediego/ManifoldLearning.jl", "max_stars_repo_head_hexsha": "f7969c1b05897659beafa6491d875de5497be1da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hlle.jl", "max_issues_repo_name": "adediego/ManifoldLearning.jl", "max_issues_repo_head_hexsha": "f7969c1b05897659beafa6491d875de5497be1da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hlle.jl", "max_forks_repo_name": "adediego/ManifoldLearning.jl", "max_forks_repo_head_hexsha": "f7969c1b05897659beafa6491d875de5497be1da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.890625, "max_line_length": 109, "alphanum_fraction": 0.5684153597, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.7806717708495149}}
{"text": "\n\n\"Example of a more complicated periodic contractor\"\nfunction sawtooth(X::IntervalBox)\n\n    x, y = X\n\n    x = x ∩ (-1..1)\n    y = y ∩ (-2..2)\n\n    y = y ∩ (2x)\n    x = x ∩ (y/2)\n\n    return IntervalBox(x, y)\nend\n\n\nfunction constant_contractor(X, y_val)\n    x, y = X\n    y = y ∩ Interval(y_val)\n    return IntervalBox(x, y)\nend\n\n\n\nfunction add_one(X)  # y = x + 1\n    x, y = X\n\n    y = y ∩ (x + 1)\n    x = x ∩ (y - 1)\n\n    return IntervalBox(x, y)\nend\n\n\n\nfunction cube0(X::IntervalBox)  # contractor for y=x^3, x>=0\n\n    x, y = X\n\n    x = x ∩ (0..∞)\n\n    y = y ∩ (x ^ 3)\n    x = x ∩ Interval(y.lo ^ (1/3), y.hi^(1/3))   # not rigorous!\n\n    return x × y\nend\n\n\n\"\"\"\nMake the \"odd\" version of a box\nodd(X::IntervalBox) = ( (x,y) = X; IntervalBox(-x, -y) )\n\"\"\"\n\ncube_neg = symmetrise(cube0, odd)\ncube = cube0 ∪ cube_neg\n\nff(x) = x^2 - x^3\n\nfunction ff(X::IntervalBox)\n    x, y = X\n\n    a = x^2\n    b = x^3\n\n    y = y ∩ (a - b)  # y = a - b\n\n    a = a ∩ (y + b)\n    b = b ∩ (a - y)\n\n    x, a = square(IntervalBox(x, a))\n    x, b = cube(IntervalBox(x, b))\n\n    return IntervalBox(x, y)\n\nend\n", "meta": {"hexsha": "5a512515fd498ef8d2e1c4de0540e32340c04b80", "size": 1085, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/examples.jl", "max_stars_repo_name": "kaarthiksundar/IntervalContractors.jl", "max_stars_repo_head_hexsha": "488b206aafc6e562655a0e395a0d6ca2217272ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-02-27T20:15:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T17:55:10.000Z", "max_issues_repo_path": "examples/examples.jl", "max_issues_repo_name": "kaarthiksundar/IntervalContractors.jl", "max_issues_repo_head_hexsha": "488b206aafc6e562655a0e395a0d6ca2217272ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2017-05-03T14:08:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-04T20:43:33.000Z", "max_forks_repo_path": "examples/examples.jl", "max_forks_repo_name": "kaarthiksundar/IntervalContractors.jl", "max_forks_repo_head_hexsha": "488b206aafc6e562655a0e395a0d6ca2217272ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-05-04T04:46:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T23:30:35.000Z", "avg_line_length": 14.0909090909, "max_line_length": 64, "alphanum_fraction": 0.5013824885, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7806717636052141}}
{"text": "\nn = 256\nw = exp(-2im*pi/n)\nDFT = zeros(Complex, n, n)\n\nfor i = 1:n\n    for j = 1:n\n        DFT[i,j] = w^((i-1)*(j-1))\n    end\nend\n\n", "meta": {"hexsha": "dd788569f4f722eb6e869c85bdefa0dac863391b", "size": 132, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ddsae/CODE/CH02/CH02_SEC02_1_DFT.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "ddsae/CODE/CH02/CH02_SEC02_1_DFT.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "ddsae/CODE/CH02/CH02_SEC02_1_DFT.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 11.0, "max_line_length": 34, "alphanum_fraction": 0.446969697, "num_tokens": 64, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.780646199170972}}
{"text": "\n\n\"\"\"\nFind root of h(x) in the interval [a, b] using binary search\n\"\"\"\nfunction bisection(h, a, b, tol=1e-5, nmax=10)\n    #find root in [a, b]\n    n=1\n    c=0\n    while n<nmax\n        c = (a+b)/2\n        if abs(h(c))<tol\n            return c\n        elseif (sign(h(c))==sign(h(a)))\n            a=c\n        else\n            b=c\n        end \n        n=n+1\n    end\n    return c\nend\n\n\"\"\"\nComputes the symmetric 95% confidence interval about the median of a \nprobability distribution given by its PDF using bisection\n\"\"\"\nfunction confidence(pdf, median, alpha=0.95)\n    f = h -> int1D(pdf, median-h, median+h, \"2\") - alpha\n    c = bisection(f, 0, median, 1e-3, 10)\n    if abs(c)>median*.9 #this should mean that integration scheme failed to detect spike, indicating that interval is very thin to begin with\n        c=.1\n    end\n    return c\nend", "meta": {"hexsha": "321b926d71ef31f301023f32902bf054bbc88acf", "size": 839, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "individual_implementations/btg julia/statistics.jl", "max_stars_repo_name": "dbindel/btg", "max_stars_repo_head_hexsha": "83616be1d1c4d80f385fa95cef38753f39a3a4c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-09-18T04:52:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-03T18:58:55.000Z", "max_issues_repo_path": "individual_implementations/btg julia/statistics.jl", "max_issues_repo_name": "dbindel/btg", "max_issues_repo_head_hexsha": "83616be1d1c4d80f385fa95cef38753f39a3a4c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "individual_implementations/btg julia/statistics.jl", "max_forks_repo_name": "dbindel/btg", "max_forks_repo_head_hexsha": "83616be1d1c4d80f385fa95cef38753f39a3a4c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-06T06:07:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-06T06:07:50.000Z", "avg_line_length": 23.9714285714, "max_line_length": 141, "alphanum_fraction": 0.5816448153, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.8289388083214155, "lm_q1q2_score": 0.7805736808061391}}
{"text": "###########################################\n# From last lecture\n###########################################\n\nabstract type Step end\n\nstruct GD <: Step\n    α::Real\nend\n\noptim_step(s::GD, f, g, x) = -s.α*g(x)\n\nfunction optim(f, g, x, s::Step; max_iter=100)\n    for i in 1:max_iter\n        x += optim_step(s, f, g, x)\n    end\n    return x\nend\n\n###########################################\n# Linear regression\n###########################################\n\n# EXTRA\n\nσ(z) = 1/(1+exp(-z))\nplot(-10:0.01:10, σ)\n\n# Load data\n\nusing Plots\nusing StatsPlots\nusing RDatasets\nusing LinearAlgebra\nusing Query\nusing Statistics\n\niris = dataset(\"datasets\", \"iris\")\n\niris[1:5,:]\n\n# Exercise\n\ny = iris.PetalWidth\nX = hcat(iris.PetalLength, ones(length(y)))\n\n@df iris scatter(\n    :PetalLength,\n    :PetalWidth;\n    label=\"\",\n    xlabel = \"Petal length\",\n    ylabel = \"Petal width\"\n)    \n\n# Exercise\n\nw = (X'*X)^(-1)*X'*y\nw = (X'*X)^(-1)*(X'*y)\nw = X'*X \\ X'*y\n\ng(w) = X'*(X*w-y)\nw2 = optim([], g, zeros(size(X,2)), GD(1e-4); max_iter=10000)\n\nnorm(w-w2)\n\n# EXTRA\n\nw = (X'*X)^(-1)*X'*y\nw = (X'*X)^(-1)*(X'*y)\nw = X'*X \\ X'*y\n\nA = randn(1000,1000)\nb = randn(1000)\n\n@time (A*A)*b;\n@time A*(A*b);\n\n# Exercise\n\nf_pred(x::Real, w) = ([x 1]*w)[1]\nf_pred(x::Real, w) = w[1]*x + w[2]*1\n\nx_lims = extrema(iris.PetalLength) .+ [-0.1, 0.1]\n\n@df iris scatter(\n    :PetalLength,\n    :PetalWidth;\n    xlabel = \"Petal length\",\n    ylabel = \"Petal width\",\n    label = \"\",\n    legend = :topleft,\n)\n\nplot!(x_lims, x -> f_pred(x,w); label = \"Prediction\", line = (:black,3))\n\n###########################################\n# Logistic regression\n###########################################\n\n# Exercise\n\niris_reduced = @from i in iris begin\n    @where i.Species != \"setosa\"\n    @select {\n        i.PetalLength,\n        i.PetalWidth,\n        intercept = 1,\n        i.Species,\n        label = i.Species == \"virginica\",\n    }\n    @collect DataFrame\nend\n\n# EXTRA\n\niris_reduced2 = iris[iris.Species .!= \"setosa\", :]\niris_reduced2 = iris_reduced2[:,[3;4;5]]\n\ninsertcols!(iris_reduced2, 3, :intercept => 1)\ninsertcols!(iris_reduced2, 5, :label => iris_reduced2.Species .== \"virginica\")\n\nisequal(iris_reduced, iris_reduced2)\n\n# Extract data\n\nX = Matrix(iris_reduced[:, 1:3])\ny = iris_reduced.label\n\n# Exercise\n\n@df iris_reduced scatter(\n    :PetalLength,\n    :PetalWidth;\n    group = :Species,\n    xlabel = \"Petal length\",\n    ylabel = \"Petal width\",\n    legend = :topleft,\n)\n\n# EXTRA\n\nii = iris_reduced.Species .== \"virginica\"\n\nscatter(iris_reduced.PetalLength[ii,:], iris_reduced.PetalWidth[ii,:];\n    xlabel = \"Petal length\",\n    ylabel = \"Petal width\",\n    legend = :topleft,\n    label = \"virginica\"\n)\n\nscatter!(iris_reduced.PetalLength[.!ii,:], iris_reduced.PetalWidth[.!ii,:];\n    label = \"versicolor\"\n)\n\n# Exercise\n\nfunction log_reg(X, y, w; max_iter=100, tol=1e-6)\n    X_mult = [row*row' for row in eachrow(X)]\n    for i in 1:max_iter\n        y_hat = σ.(X*w)\n        grad = X'*(y_hat.-y) / size(X,1)\n        hess = y_hat.*(1 .-y_hat).*X_mult |> mean\n        w -= hess \\ grad\n    end\n    return w\nend\n\nw = log_reg(X, y, zeros(size(X,2)))\n\n# EXTRA\n\nfunction g(w, X, y)\n    n = size(X,1)\n    y_hat = σ.(X*w)\n    return X'*(y_hat - y) / n\nend\n\noptim([], w -> g(w, X, y), [0;0;0], GD(5e-1); max_iter=1000000)\n\n# Plot the separating hyperplane\n\nsepar(x, w) = (-w[3]-w[1]*x)/w[2]\n\nxlims = extrema(iris_reduced.PetalLength) .+ [-0.1, 0.1]\nylims = extrema(iris_reduced.PetalWidth) .+ [-0.1, 0.1]\n\n@df iris_reduced scatter(\n    :PetalLength,\n    :PetalWidth;\n    group = :Species,\n    xlabel = \"Petal length\",\n    ylabel = \"Petal width\",\n    legend = :topleft,\n    xlims,\n    ylims,\n)\n\nplot!(xlims, x -> separ(x,w); label = \"Separation\", line = (:black,3))\n\n# Check optimality\n\ny_hat = σ.(X*w)\ngrad = X'*(y_hat.-y) / size(X,1)\nnorm(grad)\n\n# Exercise\n\npred = y_hat .>= 0.5\n\"Correct number of predictions: \" * string(sum(pred .== y))\n\"Wrong   number of predictions: \" * string(sum(pred .!= y))\n", "meta": {"hexsha": "83069ed2cf5c4af15ab2a9f13719ee8d3fbbc293", "size": 3933, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/lecture_08/script_sol.jl", "max_stars_repo_name": "rzehumat/JuliaCourse", "max_stars_repo_head_hexsha": "ee26c21e90ab5d3d67ad979910d750683304e83c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/lecture_08/script_sol.jl", "max_issues_repo_name": "rzehumat/JuliaCourse", "max_issues_repo_head_hexsha": "ee26c21e90ab5d3d67ad979910d750683304e83c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/lecture_08/script_sol.jl", "max_forks_repo_name": "rzehumat/JuliaCourse", "max_forks_repo_head_hexsha": "ee26c21e90ab5d3d67ad979910d750683304e83c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-09T10:36:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T10:36:10.000Z", "avg_line_length": 18.6398104265, "max_line_length": 78, "alphanum_fraction": 0.554792779, "num_tokens": 1319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7805736780915514}}
{"text": "using Random\nusing Makie\nusing BasicBSpline\nusing ExportNURBS\nRandom.seed!(2)\n\n## 1-dim B-spline manifold\np = 2 # degree of polynomial\nk = Knots(1:12) # knot vector\nP = FastBSplineSpace(p, k) # B-spline space\na = [[i-5, 3*sin(i^2)] for i in 1:dim(P)] # control points\nM = BSplineCurve([P], a) # Define B-spline manifold\nsave_png(\"docs/src/img/1dim.png\", M, unitlength = 50)\n\n## 2-dim B-spline manifold\np = 2 # degree of polynomial\nk = Knots(1:8) # knot vector\nP = BSplineSpace(p, k) # B-spline space\nrand_a = [rand(2) for i in 1:dim(P), j in 1:dim(P)]\na = [[2 * i - 6.5, 2 * j - 6.5] for i in 1:dim(P), j in 1:dim(P)] + rand_a # random generated control points\nM = BSplineManifold([P, P], a) # Define B-spline manifold\nsave_png(\"docs/src/img/2dim.png\", M, unitlength = 50)\n\n## h-Refinement\nk₊ = [Knots(3.3, 4.2), Knots(3.8, 3.2, 5.3)]\nM′ = refinement(M, k₊ = k₊)\nsave_png(\"docs/src/img/2dim_h-refinement.png\", M′, unitlength = 50)\n\n## p-Refinement\np₊ = [1,2]\nM′ = refinement(M, p₊ = p₊)\nsave_png(\"docs/src/img/2dim_p-refinement.png\", M′, unitlength = 50)\n\n## Makie\npoints = [M([u,v]) for u in range(3.0,6.0,length=50), v in range(3.0,6.0,length=50)]\nX = [point[1] for point in points]\nY = [point[2] for point in points]\nscene = Scene(resolution=(1000,1000))\nMakie.surface!(X,Y)\nMakie.xlims!(-5,5)\nMakie.ylims!(-5,5)\nsave(\"docs/src/img/2dim_makie.png\", scene)\n\n## Fitting\np1 = 2\np2 = 2\nk1 = Knots(-10:10) + p1 * Knots(-10, 10)\nk2 = Knots(-10:10) + p2 * Knots(-10, 10)\nP1 = FastBSplineSpace(p1, k1)\nP2 = FastBSplineSpace(p2, k2)\n\nf(u1,u2) = [2u1 + sin(u1) + cos(u2) + u2 / 2, 3u2 + sin(u2) + sin(u1) / 2 + u1^2 / 6] / 5\n\na = fittingcontrolpoints(f, P1, P2)\nM = BSplineManifold([P1, P2], a)\nsave_png(\"docs/src/img/fitting.png\", M, unitlength = 50, up = 10, down = -10, left = -10, right = 10)\n\n## Coarse fitting\np1 = 2\np2 = 2\nk1 = Knots(-10:5:10) + p1 * Knots(-10, 10)\nk2 = Knots(-10:5:10) + p2 * Knots(-10, 10)\nP1 = FastBSplineSpace(p1, k1)\nP2 = FastBSplineSpace(p2, k2)\n\nf(u) = [2u[1] + sin(u[1]) + cos(u[2]) + u[2] / 2, 3u[2] + sin(u[2]) + sin(u[1]) / 2 + u[1]^2 / 6] / 5\n\na = fittingcontrolpoints(f, [P1, P2])\nM = BSplineManifold([P1, P2], a)\nsave_png(\"docs/src/img/fitting_coarse.png\", M, unitlength = 50, up = 10, down = -10, left = -10, right = 10)\n\n## Sine curve\np = 3\nk = Knots(range(-2π, 2π, length = 8)) + p * Knots(-2π, 2π)\nP = FastBSplineSpace(p, k)\n\nf(u) = [u, sin(u)]\na = fittingcontrolpoints(f, P)\nM = BSplineManifold([P], a)\nsave_svg(\"docs/src/img/sine_curve.svg\", M, unitlength = 50, up = 2, down = -2, left = -8, right = 8)\n", "meta": {"hexsha": "1162f236afbe9c1fd9e7ec5cbd8718d59327e14f", "size": 2540, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/bsplineexport.jl", "max_stars_repo_name": "hyrodium/BasicBSpline.jl", "max_stars_repo_head_hexsha": "4fa0c7ba69b62c8c115cbd98c4aa3223dd2e89a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2020-04-26T03:49:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T06:34:42.000Z", "max_issues_repo_path": "docs/src/bsplineexport.jl", "max_issues_repo_name": "hyrodium/BasicBSpline.jl", "max_issues_repo_head_hexsha": "4fa0c7ba69b62c8c115cbd98c4aa3223dd2e89a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 103, "max_issues_repo_issues_event_min_datetime": "2020-07-04T15:00:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:55:41.000Z", "max_forks_repo_path": "docs/src/bsplineexport.jl", "max_forks_repo_name": "hyrodium/BasicBSpline.jl", "max_forks_repo_head_hexsha": "4fa0c7ba69b62c8c115cbd98c4aa3223dd2e89a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3580246914, "max_line_length": 108, "alphanum_fraction": 0.6216535433, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135442, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7805736760093601}}
{"text": "#saha function\nfunction fHI(T,ne)\n     χ   = 13.60\n    temp = 15.6826 - log10(ne) + log10(2) + 1.5 * log10(T) - χ * (5040 / T)\n\n    return temp\nend\n\nfunction fHeI(T,ne)\n     χ   = 24.58\n    temp = 15.6826 - log10(ne) + log10(2) + 1.5 * log10(T) - χ * (5040 / T)\n\n    return temp\nend\n\nfunction fHeII(T,ne)\n     χ   = 54.41\n    temp = 15.6826 - log10(ne) + log10(2) + 1.5 * log10(T) - χ * (5040 / T)\n\n    return temp\nend\n\nfunction saha(T,N;ionization = false)\n    Ne  = N * 0.1\n    X   = 0.9\n    Y   = 0.1\n    NH  = X * N\n    NHe = Y * N\n    δ   = 1e-5\n\n    X1  = fHI(  T, Ne)\n    X2  = fHeI( T, Ne)\n    X3  = fHeII(T, Ne)\n\n    Y1  = 10^(X1) #H0\n    Y2  = 10^(X2) #He0\n    Y3  = 10^(X3) #He+\n\n    X4  = X * N  / (1 + Y1)\n    X5  = Y * N  / (1 + Y2 * (1 + Y3))\n    Ne_last = 0\n\n    AHI    = 0\n    AHII   = 0\n    AHeI   = 0\n    AHeII  = 0\n    AHeIII = 0\n    ANe    = 0\n\n    while true\n        HI    = X4\n        HII   = X * N - HI\n        HeI   = X5\n        HeII  = Y2 * HeI\n        HeIII = Y3 * HeII\n        Ne    = HII + HeII + 2 * HeIII\n\n        if (1 - Ne / Ne_last) < δ\n\n            AHI    = HI\n            AHII   = HII\n            AHeI   = HeI\n            AHeII  = HeIII\n            AHeIII = HeIII\n            ANe    = Ne\n\n            break\n        else\n            Ne_last = (Ne_last + Ne) /2\n        end\n    end\n\n    if ionization == true\n        return [AHI,AHII,AHeI,AHeII,AHeIII,ANe]\n    else\n        return ANe, AHI, AHII, AHeI, AHeII, AHeIII\n    end\nend\n\nexport fHI, fHeI, fHeII, saha\n", "meta": {"hexsha": "3ea3d77afb71a6516e34f750dabdd6e0d7dfb4e3", "size": 1494, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/saha.jl", "max_stars_repo_name": "fratava/RadioTools.jl", "max_stars_repo_head_hexsha": "a596d88c80447304f1160790b27cddf06d94f276", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/saha.jl", "max_issues_repo_name": "fratava/RadioTools.jl", "max_issues_repo_head_hexsha": "a596d88c80447304f1160790b27cddf06d94f276", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/saha.jl", "max_forks_repo_name": "fratava/RadioTools.jl", "max_forks_repo_head_hexsha": "a596d88c80447304f1160790b27cddf06d94f276", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.4444444444, "max_line_length": 75, "alphanum_fraction": 0.4303882195, "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630935, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7805736714900834}}
{"text": "import SpecialFunctions: erfc, erfcinv\n\n\"\"\"\ninverse of cdf.\n\"\"\"\n@inline function ppf(x)\n    return -  sqrt(2) * erfcinv(2 * x)\nend\n\n@inline function pdf(x)\n    return (1. / (sqrt(2 * pi) ) *\n        exp(-(((x)) ^ 2 / 2.0)))\nend\n\n@inline function cdf(x)\n    return 0.5 * erfc(-(x) / (sqrt(2)))\nend\n", "meta": {"hexsha": "7eab64c357bfa3c523c34874d7dc55c22f523ccd", "size": 297, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distribution.jl", "max_stars_repo_name": "kose-y/TrueSkill.jl", "max_stars_repo_head_hexsha": "9c0f592b023e8d487206e8295fb85ed1a714e176", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-11T20:31:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T02:48:39.000Z", "max_issues_repo_path": "src/distribution.jl", "max_issues_repo_name": "kose-y/TrueSkill.jl", "max_issues_repo_head_hexsha": "9c0f592b023e8d487206e8295fb85ed1a714e176", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-03T02:01:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-03T15:45:38.000Z", "max_forks_repo_path": "src/distribution.jl", "max_forks_repo_name": "kose-y/TrueSkill.jl", "max_forks_repo_head_hexsha": "9c0f592b023e8d487206e8295fb85ed1a714e176", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-24T02:03:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T02:03:23.000Z", "avg_line_length": 16.5, "max_line_length": 39, "alphanum_fraction": 0.5622895623, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7805736701327896}}
{"text": "export\n    Plane3,\n    get_signed_distance\n\n\"\"\"\nPlane3\n\nA hyperplane is an affine subspace of dimension n-1 in a space of dimension n.\nFor example, a hyperplane in a plane is a line; a hyperplane in 3-space is a plane.\n\nThis class represents an hyperplane in 3D space. It is the zero set of\nn⋅x + d = 0 where n is a unit normal vector of the plane (linear part)\nand d is the distance (offset) to the origin.\n\"\"\"\nstruct Plane3\n    normal::VecE3 # should always be normalized\n    offset::Float64\n\n    Plane3() = new(VecE3(1.0,0.0,0.0), 0.0)\n\n    \"\"\"\n    Constructs a plane from its normal n and distance to the origin d\n    such that the algebraic equation of the plane is n⋅x + d = 0.\n    \"\"\"\n    Plane3(normal::VecE3, offset::Real) = new(normalize(normal), convert(Float64, offset))\n\n\n    \"\"\"\n    Construct a plane from its normal and a point on the plane.\n    \"\"\"\n    function Plane3(normal::VecE3, P::VecE3)\n        n = normalize(normal)\n        offset = -n⋅P\n        return new(n, offset)\n    end\nend\n\n\"\"\"\nConstructs a plane passing through the three points. \n\"\"\"\nfunction Plane3(p0::VecE3, p1::VecE3, p2::VecE3)\n    v0 = p2 - p0\n    v1 = p1 - p0\n\n    normal = v0×v1\n    nnorm = norm(normal)\n    if nnorm <= norm(v0)*norm(v1)*eps()\n        M = hcat(convert(Vector{Float64}, v0),\n                 convert(Vector{Float64}, v1))'\n        s = svdfact(M, thin=false)\n        normal = convert(VecE3, s[:V][:,2])\n    else\n        normal = normalize(normal)\n    end\n    \n    offset = -p0⋅normal\n    \n    return Plane3(normal, offset)\nend\n\n\"\"\"\nReturns the signed distance between the plane and a point\n\"\"\"\nget_signed_distance(plane::Plane3, A::VecE3) = plane.normal⋅A + plane.offset\n\n\"\"\"\nReturns the absolute distance between the plane and a point\n\"\"\"\nget_distance(plane::Plane3, A::VecE3) = abs(get_signed_distance(plane, A))\n\n\"\"\"\nReturns the projection of a point onto the plane\n\"\"\"\nproj(A::VecE3, plane::Plane3) = A - get_signed_distance(plane, A) * plane.normal\n\n\"\"\"\nWhat side of the plane you are on\nIs -1 if on the negative side, 1 if on the positive side, and 0 if on the plane\n\"\"\"\nfunction get_side(plane::Plane3, A::VecE3, ε::Float64=DUMMY_PRECISION)\n    signed_dist = get_signed_distance(plane, A)\n    if abs(signed_dist) < ε\n        return 0\n    else\n        return sign(signed_dist)\n    end\nend", "meta": {"hexsha": "61467c45fc7941eb0eb1176abf5f35e89681c529", "size": 2300, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geom/hyperplanes.jl", "max_stars_repo_name": "release200428/Vec.jl", "max_stars_repo_head_hexsha": "1356755f5b91169950a9932f921c2544baaeb853", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/geom/hyperplanes.jl", "max_issues_repo_name": "release200428/Vec.jl", "max_issues_repo_head_hexsha": "1356755f5b91169950a9932f921c2544baaeb853", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geom/hyperplanes.jl", "max_forks_repo_name": "release200428/Vec.jl", "max_forks_repo_head_hexsha": "1356755f5b91169950a9932f921c2544baaeb853", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4367816092, "max_line_length": 90, "alphanum_fraction": 0.6552173913, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541528387691, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.780573669315391}}
{"text": "\n# coding: utf-8\n\n# In[1]:\n\n\nfunction pascal_triangle(n)\n    \n    row=Any[]\n    \n    #base case\n    if n==1\n        \n        return Any[1]\n        \n    elseif n==2\n        \n        return Any[1,1]\n        \n    else\n        \n        #calculate the elements in each row\n        for i in 2:n-1\n            \n            #rolling sum all the values within 2 windows from the previous row\n            #but we cannot include two boundary numbers 1 in this row\n            push!(row,pascal_triangle(n-1)[i-1]+pascal_triangle(n-1)[i])\n        \n        end\n        \n        #append 1 for both front and rear of the row\n        pushfirst!(row,1)\n        push!(row,1)\n    \n    end\n    \n    return row\n    \nend\n\n\n# In[2]:\n\n\nfunction styled_row(nested)\n    \n    #the first loop is to concatenate all rows\n    for i in 1:length(nested)\n        \n        temp=nested[i]\n        \n        #this loop is to reshape the row\n        #insert '' between each element in the row\n        for j in 2:(2*i-1)\n            \n            #if index k is an even number,insert ''\n            if j%2==0\n                \n                insert!(temp,j,\"\")\n                \n            end\n            \n        end\n        \n        #need to add '' to both sides of rows\n        #length(nested)-i=((length(nested)+length(nested)-1)-(i+i-1))/2\n        #we set the n th row plus n-1 space as the total elements in a row\n        #we minus the reshaped row (i+i-1)\n        #we get the space for both sides\n        #finally we divide it by 2 and add to both sides of the row\n        #we append the styled row into rows\n        nested[i]=cat(fill(\"\",length(nested)-i),temp,fill(\"\",length(nested)-i),dims=1)\n        \n    end\n    \n    return nested\n    \nend\n\n\n# In[3]:\n\n#print out each row\nfunction printit(n)\n    \n    nested=Any[]\n    \n    for i in 1:n\n        \n        push!(nested,pascal_triangle(i))\n        \n    end\n    \n    for i in styled_row(nested)\n        \n        println(i)\n        \n    end\n    \nend\n\n\n# In[4]:\n\n\n#using memoization\n\n\n# In[5]:\n\n\nfunction mmz(n)\n        \n    row=Any[]\n    \n    if !(n in keys(memoization))\n        \n        #rolling sum all the values within 2 windows from the previous row\n        #but we cannot include two boundary numbers 1 in this row\n        for i in 2:n-1\n        \n            push!(row,mmz(n-1)[i-1]+mmz(n-1)[i])\n        \n        end\n    \n        #append 1 for both front and rear of the row\n        pushfirst!(row,1)\n        push!(row,1)\n        \n        global memoization[n]=row\n        \n    end\n        \n    return memoization[n]\n    \nend\n\n\n# In[6]:\n\n\nfunction printit_mmz(n)\n    \n    global memoization=Dict(1=>Any[1],2=>Any[1,1])\n    \n    nested=Any[]\n    \n    for i in 1:n\n        \n        push!(nested,mmz(i))\n        \n    end\n    \n    for i in styled_row(nested)\n        \n        println(i)\n        \n    end\n    \nend\n\n\n# In[7]:\n\n\n#0.021448 seconds (1.95 k allocations: 72.875 KiB)\n@time begin\n    \n    printit(5)\n    \nend\n\n\n# In[8]:\n\n\n#0.355459 seconds (344.14 k allocations: 17.351 MiB)\n@time begin\n    \n    printit_mmz(5)\n    \nend\n\n\n# In[9]:\n\n\n#3.822380 seconds (36.60 M allocations: 2.678 GiB, 8.57% gc time)\n@time begin\n    \n    printit(10)\n    \nend\n\n\n# In[10]:\n\n\n#0.232830 seconds (7.27 k allocations: 254.938 KiB)\n@time begin\n    \n    printit_mmz(10)\n    \nend\n\n#at the first glance,memoization isnt faster\n#as the number grows larger,memoization reveals its true nature", "meta": {"hexsha": "8e4a5296408f5983ba1f891bbbc98e9551ca70ad", "size": 3390, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "pascal triangle with memoization.jl", "max_stars_repo_name": "je-suis-tm/recursion-and-dynamic-programming", "max_stars_repo_head_hexsha": "55a6085cd45b73426379ff947d9a842ef7d325bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-03-22T10:31:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:30:17.000Z", "max_issues_repo_path": "pascal triangle with memoization.jl", "max_issues_repo_name": "slowbrain/recursion-and-dynamic-programming", "max_issues_repo_head_hexsha": "1cd77db1e7940fee15fc8aa2cedd3ab84e10374f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pascal triangle with memoization.jl", "max_forks_repo_name": "slowbrain/recursion-and-dynamic-programming", "max_forks_repo_head_hexsha": "1cd77db1e7940fee15fc8aa2cedd3ab84e10374f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2019-10-27T12:34:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T13:54:37.000Z", "avg_line_length": 16.3768115942, "max_line_length": 86, "alphanum_fraction": 0.515339233, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156295, "lm_q2_score": 0.8947894590884704, "lm_q1q2_score": 0.7805672414646557}}
{"text": "#Haario et al. 2001 An  adaptive  Metropolis  algorithm\r\n\r\n#proposal function\r\nfunction mcmc_proposal_func_ad(par,sig)\r\n    return par.+rand(MvNormal(sig))\r\nend\r\n\r\nfunction mcmc_update_Σ_n_μ(x,Σ,μ,ϵ,s_d,T)\r\n    \r\n    μ_new = T*μ/(T+1)+x/(T+1)\r\n    #Σ_new = Hermitian((T-1)/T*Σ+s_d/T*(T*μ*transpose(μ)-(T+1)*μ_new*transpose(μ_new)+x*transpose(x)+UniformScaling(ϵ)))\r\n    Σ_new = (T-1)/T*Σ+s_d/T*(T*(μ*transpose(μ))-(T+1)*(μ_new*transpose(μ_new))+(x*transpose(x))+UniformScaling(ϵ))   \r\n\r\n    return Σ_new,μ_new\r\nend\r\n\r\n#n runs of the Metropolis algorithm\r\nfunction mcmc_run_ad!(x_current,P_current,p,sig,n::Integer,n_chains::Integer)\r\n    n_accept = zeros(n_chains)\r\n\r\n    Threads.@threads for j = 1:n_chains\r\n    #for j = 1:n_chains\r\n        for i = 1:n        \r\n            x_new = mcmc_proposal_func_ad(x_current[j],sig[j]) #ceate new candidate\r\n            p_new = p(x_new) #Probability of candidate \r\n            A = min(1,p_new/P_current[j]) #calcualte acceptance ratio\r\n            u = rand() #Probability of accepting candidate \r\n            if u<=A\r\n                x_current[j],P_current[j]= x_new,p_new\r\n                n_accept[j] += 1\r\n            end            \r\n        end\r\n    end\r\n    return n_accept\r\nend\r\n\r\n#n runs of the Metropolis algorithm\r\nfunction mcmc_run_ad!(x_current,P_current,p,Σ,μ,ϵ,s_d,T,n::Integer,n_chains::Integer)\r\n    n_accept = zeros(n_chains)\r\n\r\n    Threads.@threads for j = 1:n_chains\r\n    #for j = 1:n_chains    \r\n        T_local = T\r\n        for i = 1:n        \r\n            x_new = mcmc_proposal_func_ad(x_current[j],Σ[j]) #ceate new candidate\r\n            p_new = p(x_new) #Probability of candidate \r\n            A = min(1,p_new/P_current[j]) #calcualte acceptance ratio\r\n            u = rand() #Probability of accepting candidate \r\n            if u<=A\r\n                x_current[j],P_current[j]= x_new,p_new\r\n                n_accept[j] += 1\r\n            end \r\n            Σ[j],μ[j] = mcmc_update_Σ_n_μ(reshape(x_current[j],(length(x_current[j]),1)),Σ[j],μ[j],ϵ,s_d,T_local)\r\n            T_local += 1           \r\n        end\r\n    end\r\n    T += n \r\n    return n_accept\r\nend\r\n\r\nfunction mcmc_create_Σ_n_μ!(x_current,P_current,p,sig,n::Integer,n_chains::Integer)\r\n    \r\n    μ = Array{Array{Float64,2},1}(undef,n_chains) #Sample mean\r\n    Σ = Array{Array{Float64,2},1}(undef,n_chains) #Sample Covariance matrix\r\n\r\n    Threads.@threads for j = 1:n_chains\r\n    #for j = 1:n_chains    \r\n\r\n        samples = Array{Float64,2}(undef,n,length(x_current[j]))\r\n\r\n        for i = 1:n        \r\n            x_new = mcmc_proposal_func_ad(x_current[j],sig[j]) #ceate new candidate\r\n            p_new = p(x_new) #Probability of candidate \r\n            A = min(1,p_new/P_current[j]) #calcualte acceptance ratio\r\n            u = rand() #Probability of accepting candidate \r\n            if u<=A\r\n                x_current[j],P_current[j]= x_new,p_new                \r\n            end\r\n            samples[i,:] = x_current[j] \r\n        end\r\n        μ[j] = transpose(mean(samples, dims=1))\r\n        Σ[j] = cov(samples)\r\n    end    \r\n    return Σ,μ\r\nend\r\n\r\nfunction metropolis_mcmc_ad!(x_current,P_current,sig,p,s_d;\r\n    n_samples::Integer=100,burn_in_init::Integer=100,burn_in::Integer=100,\r\n    sample_freq::Integer=5,init_sample::Integer=300,ϵ::Float64=1.0e-9,every_n_sample_accept_check::Integer=10)    \r\n    \r\n    n_chains = length(x_current)    \r\n\r\n    #Run initial burn-in\r\n    println(\"Start: Init Burn-in\")\r\n    mcmc_run_ad!(x_current,P_current,p,sig,burn_in,n_chains)\r\n    println(\"Done: Init Burn-in\")\r\n\r\n    #Create sample Covariance matrix matrix and mean\r\n    println(\"Start: Create sample Σ and μ\")\r\n    Σ,μ = mcmc_create_Σ_n_μ!(x_current,P_current,p,sig,init_sample,n_chains)\r\n    T = init_sample #Total number of iteration after initial burn-in\r\n    println(\"Done: Create sample Σ and μ\")\r\n\r\n    #Run burn-in\r\n    println(\"Start: Burn-in\")\r\n    mcmc_run_ad!(x_current,P_current,p,Σ,μ,ϵ,s_d,T,burn_in,n_chains)    \r\n    println(\"Done: Burn-in\")\r\n\r\n    #Create container for samples\r\n    samples = Array{typeof(x_current[1]),2}(undef,n_samples,n_chains)\r\n    accept_rate = zeros(n_chains)\r\n    accept_rate_monitor = zeros(n_chains)\r\n   \r\n    println(\"Start: Sampling\")\r\n    #Run samples\r\n    for i = 1:n_samples\r\n        println(\"---Sample: \",i,\"/\",n_samples)\r\n        #Run mcmc\r\n        n_accept = mcmc_run_ad!(x_current,P_current,p,Σ,μ,ϵ,s_d,T,sample_freq,n_chains)         \r\n        accept_rate = accept_rate.+n_accept\r\n        accept_rate_monitor = accept_rate_monitor.+n_accept\r\n        #Save sample\r\n        for j = 1:n_chains\r\n            samples[i,j] = x_current[j]\r\n        end\r\n\r\n        if mod(i,every_n_sample_accept_check)==0\r\n            println(\"Acceptance rate (short term): \",accept_rate_monitor/(every_n_sample_accept_check*sample_freq))    \r\n            println(\"Acceptance rate (long term): \",accept_rate/(i*sample_freq)) \r\n            accept_rate_monitor = zeros(n_chains)        \r\n        end\r\n    end\r\n    println(\"Done: Sampling\")\r\n    accept_rate /= n_samples*sample_freq\r\n\r\n    return samples,accept_rate\r\nend", "meta": {"hexsha": "cdac54ad3575a3cbe880d0e6858f11af966814c7", "size": 5071, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "MCMC/metropolis_ad.jl", "max_stars_repo_name": "PeterFransson/CCPH_Project", "max_stars_repo_head_hexsha": "7034b26ab0a0c494022b15e315d74bcf59a94756", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MCMC/metropolis_ad.jl", "max_issues_repo_name": "PeterFransson/CCPH_Project", "max_issues_repo_head_hexsha": "7034b26ab0a0c494022b15e315d74bcf59a94756", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MCMC/metropolis_ad.jl", "max_forks_repo_name": "PeterFransson/CCPH_Project", "max_forks_repo_head_hexsha": "7034b26ab0a0c494022b15e315d74bcf59a94756", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0145985401, "max_line_length": 121, "alphanum_fraction": 0.6067836719, "num_tokens": 1442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7805621434786666}}
{"text": "\n\"\"\"\nA `Compunding` type gives information on how to map\nan interest rate `r` and year fraction `y`\nto a discount factor or effective rate factor.\n\"\"\"\nabstract type Compounding end\n\n\"\"\"\nThe Effective Rate Factor under `Continuous` compounding\nis defined by:\n\n```math\nexp(rt)\n```\n\ngiven an annual rate `r` and year fraction `t`.\n\"\"\"\nstruct Continuous <: Compounding end\n\n\"\"\"\nThe Effective Rate Factor under `Simple` compounding\nis defined by:\n\n```math\n(1 + rt)\n```\n\ngiven an annual rate `r` and year fraction `t`.\n\"\"\"\nstruct Simple <: Compounding end\n\n\"\"\"\nThe Effective Rate Factor under `Exponential` compounding\nis defined by:\n\n```math\n(1 + r)^t\n```\n\ngiven an annual rate `r` and year fraction `t`.\n\"\"\"\nstruct Exponential <: Compounding end\n", "meta": {"hexsha": "e06fbf130a2c27c2aec092bd5ac683aa9fb9ce60", "size": 742, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/types.jl", "max_stars_repo_name": "JuliaFinance/Rates.jl", "max_stars_repo_head_hexsha": "b037880ee21ba45dd4bd155c0f7b687d8a6e025d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-06-27T03:04:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-22T10:08:59.000Z", "max_issues_repo_path": "src/types.jl", "max_issues_repo_name": "JuliaFinance/Rates.jl", "max_issues_repo_head_hexsha": "b037880ee21ba45dd4bd155c0f7b687d8a6e025d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/types.jl", "max_forks_repo_name": "JuliaFinance/Rates.jl", "max_forks_repo_head_hexsha": "b037880ee21ba45dd4bd155c0f7b687d8a6e025d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-28T01:22:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T01:22:59.000Z", "avg_line_length": 16.8636363636, "max_line_length": 57, "alphanum_fraction": 0.7035040431, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7805621415984624}}
{"text": "# ============================================================================ #\r\n# General\r\n# ============================================================================ #\r\n\r\n\r\northogonal_vector(a::AbstractArray) = [-a[2], a[1]]\r\n\r\n\r\n\r\nfunction point_projection(point::AbstractPoint, line::Line)\r\n    e12 = normalize!( vector(line) )\r\n    p = line.p1 + Point(e12 .* dot(point - line.p1, e12))\r\nend\r\n\r\n\r\n\r\n\r\nfunction cross2(a::AbstractArray, b::AbstractArray)\r\n    if !(length(a) == length(b) == 2)\r\n        throw(DimensionMismatch(\"cross2 is only defined for vectors of length 2\"))\r\n    end\r\n    unsafe_cross2(a, b)\r\nend\r\n\r\nunsafe_cross2(a::AbstractArray, b::AbstractArray) = a[1] * b[2] - a[2] * b[1]\r\n\r\nfunction cross2(a_x::T, a_y::T, b_x::T, b_y::T)::T where {T}\r\n    return a_x * b_y - a_y * b_x\r\nend\r\n\r\nfunction dot2(a_x::T, a_y::T, b_x::T, b_y::T)::T where {T}\r\n    return a_x * b_x + a_y * b_y\r\nend\r\n\r\n\r\nfunction is_left(line::Line, point::AbstractPoint)::Bool\r\n    v12 = vector(line)\r\n    v1p = point - line.p1\r\n    c = cross2(v12, v1p)\r\n    return c > 0\r\nend\r\n\r\n\r\n\r\nfunction is_left_on(line::Line, point::AbstractPoint)::Bool\r\n    v12 = vector(line)\r\n    v1p = point - line.p1\r\n    c = cross2(v12, v1p)\r\n    return c >= 0\r\nend\r\n\r\n\r\nfunction is_left_on(line_1::AbstractPoint, line_2::AbstractPoint, point::AbstractPoint)::Bool\r\n    # v12 = vector(line)\r\n    v12 = line_2 - line_1\r\n    v1p = point - line_1\r\n    c = cross2(v12, v1p)\r\n    return c >= 0\r\nend\r\n\r\nfunction is_left(line_1::AbstractPoint, line_2::AbstractPoint, point::AbstractPoint)::Bool\r\n    # v12 = vector(line)\r\n    # v12 = line_2 - line_1\r\n    # v1p = point - line_1\r\n    # c = cross2(v12, v1p)\r\n\r\n    v12_x = line_2.x - line_1.x\r\n    v12_y = line_2.y - line_1.y\r\n    v1p_x = point.x - line_1.x\r\n    v1p_y = point.y - line_1.y\r\n\r\n    c = cross2(v12_x, v12_y, v1p_x, v1p_y)\r\n\r\n    return c > 0\r\nend\r\n\r\nfunction is_left_on_inlined(line::Line, point::AbstractPoint)::Bool\r\n    v12_x = line.p2.x - line.p1.x\r\n    v12_y = line.p2.y - line.p1.y\r\n    v1p_x = point.x - line.p1.x\r\n    v1p_y = point.y - line.p1.y\r\n\r\n    c = cross2(v12_x, v12_y, v1p_x, v1p_y)\r\n    return c >= 0\r\nend\r\n\r\nfunction is_left_on_inlined(p1::AbstractPoint, p2::AbstractPoint, point::AbstractPoint)::Bool\r\n    v12_x = p2.x - p1.x\r\n    v12_y = p2.y - p1.y\r\n    v1p_x = point.x - p1.x\r\n    v1p_y = point.y - p1.y\r\n\r\n    c = cross2(v12_x, v12_y, v1p_x, v1p_y)\r\n    return c >= 0\r\nend\r\n\r\n\r\nfunction is_on_line(line::Line, point::AbstractPoint, tol = 1e-10)::Bool\r\n    d = distance(line, point)\r\n    return d <= tol\r\nend\r\n\r\n\r\nfunction is_on_line(line_p1::AbstractPoint, line_p2::AbstractPoint, point::AbstractPoint, tol = 1e-10)::Bool\r\n    d = distance(line_p1, line_p2, point)\r\n    return d <= tol\r\nend\r\n\r\n\r\n", "meta": {"hexsha": "c39c3717144940b016b6ca07ae1cc179aa05ecb7", "size": 2747, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "geom/src/general.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geom/src/general.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geom/src/general.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9727272727, "max_line_length": 109, "alphanum_fraction": 0.5755369494, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.8615382058759128, "lm_q1q2_score": 0.7805448443949788}}
{"text": "using FractionalCalculus, Plots\n\ntspan=collect(0:0.01:15)\n\nexamplederivative = []\n\nfor i in range(0.1, 0.9, step=0.1)\n    push!(examplederivative, fracdiff(sin, i, tspan, 0.001, CaputoDiethelm()))\nend\n\nplot(tspan, examplederivative, title=\"Different order of derivative\", linewidth=3, label=[\"α=0.1\" \"α=0.2\" \"α=0.3\" \"α=0.4\" \"α=0.5\" \"α=0.6\" \"α=0.7\" \"α=0.8\" \"α=0.9\" \"α=1\"], legend=:bottomright)", "meta": {"hexsha": "9a9261bd5d1d9b7f320fd0a7cae2f3fc329dfecc", "size": 392, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/derivative_of_sin.jl", "max_stars_repo_name": "SciFracX/FractionalCalculus.jl", "max_stars_repo_head_hexsha": "f570164fdf86314f6c8871d18659bd343046bb04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-11-05T12:53:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T20:58:27.000Z", "max_issues_repo_path": "example/derivative_of_sin.jl", "max_issues_repo_name": "SciFracX/FractionalCalculus.jl", "max_issues_repo_head_hexsha": "f570164fdf86314f6c8871d18659bd343046bb04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-11-05T17:20:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T13:20:01.000Z", "max_forks_repo_path": "example/derivative_of_sin.jl", "max_forks_repo_name": "SciFracX/FractionalCalculus.jl", "max_forks_repo_head_hexsha": "f570164fdf86314f6c8871d18659bd343046bb04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-10-21T08:58:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T20:40:29.000Z", "avg_line_length": 35.6363636364, "max_line_length": 190, "alphanum_fraction": 0.6658163265, "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474155747541, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7804953649814677}}
{"text": "using LinearAlgebra,Distributions,DataFrames,StatsBase,GLM,LsqFit,Optim,BlackBoxOptim,HypothesisTests,Colors,Images,StatsModels,CategoricalArrays,\nImageFiltering,SpecialFunctions,DSP,HCubature,Combinatorics,DataStructures,ANOVA,StatsFuns,Trapz,CircStats,ImageSegmentation,ProgressMeter,PyCall,\nDierckx,BandedMatrices,OffsetArrays\nimport Base: vec,range\nimport StatsBase: predict\n\ninclude(\"NeuroDataType.jl\")\ninclude(\"Stats.jl\")\ninclude(\"Spike.jl\")\ninclude(\"LFP.jl\")\ninclude(\"Image.jl\")\ninclude(\"Condition.jl\")\ninclude(\"2P.jl\")\n\nvec(x::RGBA)=[x.r,x.g,x.b,x.alpha]\nanscombe(x) = 2*sqrt(x+(3/8))\n\n\"`Gaussian` function\"\ngaussianf(x;a=1,μ=0,σ=1) = a*exp(-0.5((x-μ)/σ)^2)\nfunction gaussianf(x,y;a=1,μ₁=0,σ₁=1,μ₂=0,σ₂=1,θ=0)\n    sinv,cosv = sincos(θ)\n    x₀ = x-μ₁\n    y₀ = y-μ₂\n    x′ = cosv * x₀ + sinv * y₀\n    y′ = cosv * y₀ - sinv * x₀\n    a*exp(-0.5((x′/σ₁)^2 + (y′/σ₂)^2))\nend\n\n\"\"\"\n`von Mises` function [^1]\n\n```math\nf(α) =  βe^{κ(cos(n(α - μ)) - 1)}\n```\n\n[^1]\n\nSwindale, N.V. (1998). Orientation tuning curves: empirical description and estimation of parameters. Biol Cybern 78, 45–56.\n\n- β: amplitude at μ\n- μ: angle of peak\n- κ: width parameter\n- n: frequency parameter\n\"\"\"\nvmf(α;β=1,μ=0,κ=1,n=1) = β*exp(κ*(cos(n*(α-μ))-1))\n\"\"\"\n`Generalized von Mises` function [^1]\n\n```math\nf(α) =  βe^{κ₁(cos(α - μ₁) - 1) + κ₂(cos2(α - μ₂) - 1)}\n```\n\n[^1]\n\nGatto, R., and Jammalamadaka, S.R. (2007). The generalized von Mises distribution. Statistical Methodology 4, 341–353.\n\"\"\"\ngvmf(α;β=1,μ₁=0,κ₁=1,μ₂=0,κ₂=1) = β*exp(κ₁*cos(α-μ₁) + κ₂*cos(2(α-μ₂)))\n\n\"\"\"\n`Difference of Gaussians` function\n\"\"\"\ndogf(x;aₑ=2,μₑ=0,σₑ=1,aᵢ=1,μᵢ=0,σᵢ=2) = aₑ*exp(-0.5((x-μₑ)/σₑ)^2) - aᵢ*exp(-0.5((x-μᵢ)/σᵢ)^2)\nfunction dogf(x,y;aₑ=2,μₑ₁=0,σₑ₁=1,μₑ₂=0,σₑ₂=1,θₑ=0,aᵢ=1,μᵢ₁=0,σᵢ₁=2,μᵢ₂=0,σᵢ₂=2,θᵢ=0)\n    sinvₑ,cosvₑ = sincos(θₑ)\n    xₑ₀ = x-μₑ₁\n    yₑ₀ = y-μₑ₂\n    xₑ′ = cosvₑ * xₑ₀ + sinvₑ * yₑ₀\n    yₑ′ = cosvₑ * yₑ₀ - sinvₑ * xₑ₀\n    sinvᵢ,cosvᵢ = sincos(θᵢ)\n    xᵢ₀ = x-μᵢ₁\n    yᵢ₀ = y-μᵢ₂\n    xᵢ′ = cosvᵢ * xᵢ₀ + sinvᵢ * yᵢ₀\n    yᵢ′ = cosvᵢ * yᵢ₀ - sinvᵢ * xᵢ₀\n    aₑ*exp(-0.5((xₑ′/σₑ₁)^2 + (yₑ′/σₑ₂)^2)) - aᵢ*exp(-0.5((xᵢ′/σᵢ₁)^2 + (yᵢ′/σᵢ₂)^2))\nend\n\n\"\"\"\n`sin` grating function\n\n- μ: x offset\n- f: Frequency in cycle/unit_x\n- phase: Phase of a cycle in [0, 1] scale\n\"\"\"\ngratingf(x;μ=0, f=1, phase=0) = sin(2π * (f * (x-μ) + phase))\n\n\"\"\"\n2D `sin` grating function\n\n- μ₁: x offset\n- μ₂: y offset\n- θ: Orientation in radius, 0 is -, increase counter-clock wise\n- f: Frequency in cycle/unit_x/y\n- phase: Phase of a cycle in [0, 1] scale\n\"\"\"\nfunction gratingf(x,y;μ₁=0,μ₂=0,θ=0,f=1,phase=0)\n    sinθ,cosθ = sincos(θ)\n    y′ = cosθ * (y-μ₂) - sinθ * (x-μ₁)\n    sin(2π * (f * y′ + phase))\nend\n\n\"\"\"\n`cas` function defined as ``cas(x) = cos(x) + sin(x)``\n\n- f: Frequency in cycle/unit_x\n- phase: Phase of a cycle in [0, 1] scale\n- isnorm: scale `cas` in [-√2, √2] to [-1, 1]\n\"\"\"\nfunction cas(x;f=1, phase=0, isnorm::Bool=true)\n    r = sum(sincos(2π * (f * x + phase)))\n    if isnorm\n        r /=sqrt(2)\n    end\n    return r\nend\n\n\"\"\"\n2D `cas` function defined as ``cas(x+y) = cos(x+y) + sin(x+y)``\n\n- kx: Frequency in cycle/unit_x\n- ky: Frequency in cycle/unit_y\n- phase: Phase of a cycle in [0, 1] scale\n- isnorm: scale `cas` in [-√2, √2] to [-1, 1]\n\"\"\"\nfunction cas(x,y;kx=1,ky=1, phase=0, isnorm::Bool=true)\n    r = sum(sincos(2π * (kx * x + ky * y + phase)))\n    isnorm && (r /=sqrt(2))\n    return r\nend\n\n\"\"\"\n`cas` phase to `sin` phase, phase is in [0, 1] scale\n\n!!! note\n    ``cas(x) = √2 sin(x + π/4)``\n\"\"\"\ncas2sin(phase) = phase + 0.125\n\n\"\"\"\n2D `cas` to 2D sin `gratingf`\n\"\"\"\nfunction cas2sin(kx,ky,phase)\n    θ = atan(ky,kx) - π/2\n    f = sqrt(kx*kx + ky*ky)\n    return (θ=θ,f=f,phase=phase + 0.125)\nend\n\n\"\"\"\n`sin` phase to `cas` phase, phase is in [0, 1] scale\n\n!!! note\n    ``cas(x) = √2 sin(x + π/4)``\n\"\"\"\nsin2cas(phase) = phase - 0.125\n\n\"\"\"\n2D sin `gratingf` to 2D `cas`\n\"\"\"\nfunction sin2cas(θ,f,phase)\n    sinθ,cosθ = sincos(θ + π/2)\n    kx = cosθ*f\n    ky = sinθ*f\n    return (kx=kx,ky=ky,phase=phase - 0.125)\nend\n\n\"`Gabor` function\"\ngaborf(x;a=1,μ=0,σ=1,f=1,phase=0) = a*exp(-0.5((x-μ)/σ)^2)*sin(2π*(f*(x-μ)+phase))\nfunction gaborf(x,y;a=1,μ₁=0,σ₁=1,μ₂=0,σ₂=1,θ=0,f=1,phase=0)\n    sinv,cosv = sincos(θ)\n    x₀ = x-μ₁\n    y₀ = y-μ₂\n    x′ = cosv * x₀ + sinv * y₀\n    y′ = cosv * y₀ - sinv * x₀\n    a*exp(-0.5((x′/σ₁)^2 + (y′/σ₂)^2)) * sin(2π*(f * y′ + phase))\nend\n\n\"Binary mask for gabor envelope\"\nfunction gaborenvelopemask(x,y;fσ=2.5,μ₁=0,σ₁=1,μ₂=0,σ₂=1,θ=0)\n    sinv,cosv = sincos(θ)\n    x₀ = x-μ₁\n    y₀ = y-μ₂\n    x′ = cosv * x₀ + sinv * y₀\n    y′ = cosv * y₀ - sinv * x₀\n    (x′/fσ/σ₁)^2 + (y′/fσ/σ₂)^2 <= 1 ? true : false\nend\n\"Binary mask for concentric circular dog envelope\"\ndogenvelopemask(x,y;fσ=2.5,μ₁=0,σₑ₁=1,μ₂=0,rσᵢₑ=2) = edogenvelopemask(x,y;fσ,μ₁,σₑ₁,rσ₂₁=1,μ₂,rσᵢₑ,θ=0)\n\"Binary mask for concentric orientated elliptical dog envelope\"\nfunction edogenvelopemask(x,y;fσ=2.5,μ₁=0,σₑ₁=1,rσ₂₁=1,μ₂=0,rσᵢₑ=2,θ=0)\n    sinv,cosv = sincos(θ)\n    x₀ = x-μ₁\n    y₀ = y-μ₂\n    x′ = cosv * x₀ + sinv * y₀\n    y′ = cosv * y₀ - sinv * x₀\n    σ₁ = max(σₑ₁,rσᵢₑ*σₑ₁)\n    σ₂ = σ₁ * rσ₂₁\n    (x′/fσ/σ₁)^2 + (y′/fσ/σ₂)^2 <= 1 ? true : false\nend\n\n\"Fit 1D model to data\"\nfunction fitmodel(model,x,y)\n    lb,ub = extrema(y)\n    bm = (lb+ub)/2\n    br = (ub-lb)/2\n    alb,aub = abs.((lb,ub))\n    ab = max(alb,aub)\n\n    xlb,xub = extrema(x)\n    xbm = (xlb+xub)/2\n    xalb,xaub = abs.((xlb,xub))\n    xab = max(xalb,xaub)\n\n    rlt = fun = missing\n    if model == :vmn2\n        fun = (x,p) -> vmf.(x,β=p[1],μ=p[2],κ=p[3],n=2)\n        ofun = (p;x=x,y=y) -> sum((y.-fun(x,p)).^2)\n\n        ub=[1.8ab,   prevfloat(float(π)),   200]\n        lb=[0.2ab,            0,              0]\n        p0=[ab,               0,              1]\n    elseif model == :gvm\n        # fun = (x,p) -> gvmf.(x,β=p[1],μ₁=p[2],κ₁=p[3],μ₂=p[4],κ₂=p[5])\n        fun = gvmff\n        ofun = (p;x=x,y=y) -> sum((y.-fun(x,p)).^2)\n\n        ub=[1.8ab,   prevfloat(float(2π)),   40,    prevfloat(float(π)),     40]\n        lb=[nextfloat(0.0),   0,              0,             0,               0]\n        p0=[ab,               0,              1,             0,               1]\n    elseif model == :dog\n        fun = (x,p) -> dogf.(x,aₑ=p[1],μₑ=p[2],σₑ=p[3],aᵢ=p[4],μᵢ=p[5],σᵢ=p[6])\n        ofun = (p;x=x,y=y) -> sum((y.-fun(x,p)).^2)\n\n        ub=[1.8ab,   10xab,            10xab,    1.8ab,     10xab,              10xab]\n        lb=[0,      -10xab,   nextfloat(0.0),        0,    -10xab,     nextfloat(0.0)]\n        p0=[ab,        0,                  1,       ab,         0,                  1]\n    elseif model == :sfdog\n        # fun = (x,p) -> dogf.(x,aₑ=p[1],μₑ=p[2],σₑ=p[3],aᵢ=p[4],μᵢ=p[5],σᵢ=p[6]) .+ p[7]\n        fun = sfdogff\n        ofun = (p;x=x,y=y) -> sum((y.-fun(x,p)).^2)\n\n        ub=[1.5ab,    10,             10,          1.5ab,       10,                10,         bm+br/3]\n        lb=[0,         0,      nextfloat(0.0),       0,          0,        nextfloat(0.0),        0]\n        p0=[ab,     0.5xab,         0.5xab,          0,        0.5xab,           0.5xab,       bm-br/3]\n    elseif model == :sfgaussian\n        # fun = (x,p) -> gaussianf.(log2.(x),a=p[1],μ=p[2],σ=p[3]) .+ p[4]\n        fun = sfgaussianff\n        ofun = (p;x=x,y=y) -> sum((y.-fun(x,p)).^2)\n\n        # limit gaussian center ~[-8 10], sigma ~[1.4 8]\n        ub=[1.5ab,     3.3,          3,       bm]\n        lb=[0,          -3,        0.5,        0]\n        p0=[ab,          0,          1,        0]\n    end\n    if !ismissing(fun)\n        # ofit = optimize(ofun,lb,ub,p0,SAMIN(rt=0.92),Optim.Options(iterations=220000))\n        # param=ofit.minimizer\n        ofit = bboptimize(ofun,p0;SearchRange=collect(zip(lb,ub)),Method=:adaptive_de_rand_1_bin_radiuslimited,MaxSteps=200000)\n        param = best_candidate(ofit)\n\n        rlt = (;model,fun,param, goodnessoffit(y,fun(x,param),k=length(param))...)\n    end\n    return rlt\nend\ngvmff(x,p) = gvmf.(x,β=p[1],μ₁=p[2],κ₁=p[3],μ₂=p[4],κ₂=p[5])\nsfdogff(x,p) = dogf.(x,aₑ=p[1],μₑ=p[2],σₑ=p[3],aᵢ=p[4],μᵢ=p[5],σᵢ=p[6]) .+ p[7]\nsfgaussianff(x,p) = gaussianf.(log2.(x),a=p[1],μ=p[2],σ=p[3]) .+ p[4]\n\n\n\"Fit 2D model to image\"\nfunction fitmodel2(model,data::Matrix,ppu;w=0.5)\n    rspx = (size(data).-1)./2\n    radii = rspx./ppu\n    x = (mapreduce(i->[i[2] -i[1]],vcat,CartesianIndices(data)) .+ [-(rspx[2]+1) (rspx[1]+1)])/ppu\n    y = vec(data)\n\n    # try estimate solution\n    roi = peakroi(localcontrast(data,round(Int,w*ppu)))\n    alb,aub = abs.(extrema(data[roi.i]))\n    ab = max(alb,aub)\n    r = roi.radius/ppu\n    c = [roi.center[2] - (rspx[2]+1), -roi.center[1] + (rspx[1]+1)]/ppu\n\n    rlt = fun = missing\n    if model == :dog\n        if aub >= alb\n            ai = 5alb\n            ae = aub + ai\n        else\n            ae = 5aub\n            ai = alb + ae\n        end\n        # concentric circular dog\n        # fun = (x,y,p) -> dogf.(x,y,aₑ=p[1],μₑ₁=p[2],σₑ₁=p[3],μₑ₂=p[4],σₑ₂=p[3],θₑ=0,aᵢ=p[5],μᵢ₁=p[2],σᵢ₁=p[6]*p[3],μᵢ₂=p[4],σᵢ₂=p[6]*p[3],θᵢ=0)\n        # mfun = (x,y,p) -> dogenvelopemask.(x,y;fσ=2.5,μ₁=p[2],μ₂=p[4],σₑ₁=p[3],rσᵢₑ=p[6])\n        fun = dogff\n        mfun = dogfmf\n        ofun = (p;x=x,y=y) -> @views sum((y.-fun(x[:,1],x[:,2],p)).^2)\n        ub=[5ae,    0.5r+c[1],    0.9r,    0.5r+c[2],     5ai,    4]\n        lb=[0,     -0.5r+c[1],    0.1r,   -0.5r+c[2],     0,      0.25]\n        p0=[ae,      c[1],        0.3r,     c[2],         ai,     1]\n    elseif model == :edog\n        if aub >= alb\n            ai = 5alb\n            ae = aub + ai\n        else\n            ae = 5aub\n            ai = alb + ae\n        end\n        # concentric orientated elliptical dog\n        # fun = (x,y,p) -> dogf.(x,y,aₑ=p[1],μₑ₁=p[2],σₑ₁=p[3],μₑ₂=p[4],σₑ₂=p[5]*p[3],θₑ=p[6],aᵢ=p[7],μᵢ₁=p[2],σᵢ₁=p[8]*p[3],μᵢ₂=p[4],σᵢ₂=p[5]*p[8]*p[3],θᵢ=p[6])\n        # mfun = (x,y,p) -> edogenvelopemask.(x,y;fσ=2.5,μ₁=p[2],μ₂=p[4],σₑ₁=p[3],rσ₂₁=p[5],rσᵢₑ=p[8],θ=p[6])\n        fun = edogff\n        mfun = edogfmf\n        ofun = (p;x=x,y=y) -> @views sum((y.-fun(x[:,1],x[:,2],p)).^2)\n        ub=[5ae,    0.5r+c[1],    0.9r,    0.5r+c[2],       1,       prevfloat(float(π)),    5ai,     4]\n        lb=[0,     -0.5r+c[1],    0.1r,   -0.5r+c[2],      0.5,              0,               0,      0.25]\n        p0=[ae,      c[1],        0.3r,     c[2],           1,               0,               ai,     1]\n    elseif model == :gabor\n        # fun = (x,y,p) -> gaborf.(x,y,a=p[1],μ₁=p[2],σ₁=p[3],μ₂=p[4],σ₂=p[5]*p[3],θ=p[6],f=p[7],phase=p[8])\n        # mfun = (x,y,p) -> gaborenvelopemask.(x,y;fσ=2.5,μ₁=p[2],μ₂=p[4],σ₁=p[3],σ₂=p[5]*p[3],θ=p[6])\n        fun = gaborff\n        mfun = gaborfmf\n        ofun = (p;x=x,y=y) -> @views sum((y.-fun(x[:,1],x[:,2],p)).^2)\n\n        ori,sf = f1orisf(powerspectrum2(data,ppu)...)\n        ub=[5ab,   0.5r+c[1],   0.9r,    0.5r+c[2],    6.0,     prevfloat(float(π)),     12,            prevfloat(1.0)]\n        lb=[0,    -0.5r+c[1],   0.1r,   -0.5r+c[2],    0.2,             0,              0.05,                  0]\n        p0=[ab,    c[1],        0.3r,     c[2],          1,            ori,     clamp(sf,lb[7],ub[7]),       0.5]\n    end\n    if !ismissing(fun)\n        # ofit = optimize(ofun,lb,ub,p0,SAMIN(rt=0.92),Optim.Options(iterations=220000))\n        # param = ofit.minimizer\n        ofit = bboptimize(ofun,p0;SearchRange=collect(zip(lb,ub)),Method=:adaptive_de_rand_1_bin_radiuslimited,MaxSteps=200000)\n        param = best_candidate(ofit)\n\n        @views rlt = (;model,fun,mfun,param,radii, goodnessoffit(y,fun(x[:,1],x[:,2],param),k=length(param))...)\n    end\n    return rlt\nend\n# workaround since JLD2 can not save/load anonymous functions yet\ndogff(x,y,p) = dogf.(x,y,aₑ=p[1],μₑ₁=p[2],σₑ₁=p[3],μₑ₂=p[4],σₑ₂=p[3],θₑ=0,aᵢ=p[5],μᵢ₁=p[2],σᵢ₁=p[6]*p[3],μᵢ₂=p[4],σᵢ₂=p[6]*p[3],θᵢ=0)\nedogff(x,y,p) = dogf.(x,y,aₑ=p[1],μₑ₁=p[2],σₑ₁=p[3],μₑ₂=p[4],σₑ₂=p[5]*p[3],θₑ=p[6],aᵢ=p[7],μᵢ₁=p[2],σᵢ₁=p[8]*p[3],μᵢ₂=p[4],σᵢ₂=p[5]*p[8]*p[3],θᵢ=p[6])\ngaborff(x,y,p) = gaborf.(x,y,a=p[1],μ₁=p[2],σ₁=p[3],μ₂=p[4],σ₂=p[5]*p[3],θ=p[6],f=p[7],phase=p[8])\ndogfmf(x,y,p) = dogenvelopemask.(x,y;fσ=2.5,μ₁=p[2],μ₂=p[4],σₑ₁=p[3],rσᵢₑ=p[6])\nedogfmf(x,y,p) = edogenvelopemask.(x,y;fσ=2.5,μ₁=p[2],μ₂=p[4],σₑ₁=p[3],rσ₂₁=p[5],rσᵢₑ=p[8],θ=p[6])\ngaborfmf(x,y,p) = gaborenvelopemask.(x,y;fσ=2.5,μ₁=p[2],μ₂=p[4],σ₁=p[3],σ₂=p[5]*p[3],θ=p[6])\n\n\npredict(fit,x) = fit.fun(x,fit.param)\nfunction predict(fit,x,y;xygrid=true,yflip=false)\n    if xygrid\n        z = [fit.fun(i,j,fit.param) for j in y, i in x]\n        yflip && (z=reverse(z,dims=1))\n    else\n        z = fit.fun(x,y,fit.param)\n    end\n    z\nend\n\n\"\"\"\nGoodness of Fit Metrics:\n\n- r: Pearson Correlation Coefficient\n- mae: Mean Absolute Error\n- rmse: Root Mean Squared Error\n- rae: Relative Absolute Error\n- rse: Relative Squared Error\n- r2: R Squared\n- adjr2: Adjusted-R²\n- s: Residual Standard Error\n- aic: Akaike Information Criterion\n- bic: Bayesian Information Criterion\n\n1. y: responses\n2. ŷ: model predictions\n\n- n: sample size\n- e: errors(y - ŷ)\n- k: number of predictors\n- df: degree of freedom(n - k - 1)\n\"\"\"\nfunction goodnessoffit(y,ŷ;n = length(y),e = y .- ŷ,k=missing,df = n-k-1)\n    r = cor(y,ŷ)\n    ae = abs.(e)\n    e2 = e.^2\n    ssᵣ = sum(e2)\n    mae = mean(ae)\n    rmse = sqrt(mean(e2))\n    ydm = y .- mean(y)\n    ssₜ = sum(ydm.^2)\n    rae = sum(ae)/sum(abs.(ydm))\n    fvu = ssᵣ/ssₜ\n    rse = sqrt(fvu)\n    r2 = 1 - fvu\n    s = ssᵣ/df\n    s = s < 0 ? missing : sqrt(s)\n    adjr2 = 1 - fvu*(n-1)/df\n    aic = n*log(ssᵣ) + 2k\n    bic = n*log(ssᵣ/n) + k*log(n) # under iid normal error assumption\n    (;r,mae,rmse,rae,rse,r2,adjr2,s,aic,bic)\nend\n\nfunction searchclosest(v,vs;start::Integer=1,step::Integer=1,circ=false)\n    n=length(vs);ssign = sign(vs[start]-v)\n    i = start\n    for _ in 1:n\n        if !circ\n            i<1 && return -Inf\n            n<i && return Inf\n        end\n        sign(vs[i]-v) != ssign && return i\n        i += step\n        if circ\n            i<1 && (i+=n)\n            n<i && (i-=n)\n        end\n    end\n    Inf\nend\n\n\"\"\"\nleft and right half width of `v` relative to `y[start]`, -Inf/Inf when no `v` is found.\n\n- start: index of `y` which is the center of the width\n- v: value on which width is cutoff\n- circ: whether `y` is defined on circular domain and width can wrap around\n- x: domain of `y`, return width when `x` provided, otherwise return cutoff indices\n\"\"\"\nfunction halfwidth(y;start=argmax(y),v=y[start]/2,circ=false,x=nothing)\n    li = searchclosest(v,y;start,step=-1,circ)\n    ri = searchclosest(v,y;start,step=1,circ)\n    if isnothing(x)\n        return li,ri\n    else\n        if circ\n            lw = isinf(li) ? li : li<=start ? abs(x[start]-x[li]) : abs(x[start]-x[1])+abs(x[end]-x[li])\n            rw = isinf(ri) ? ri : ri>=start ? abs(x[ri]-x[start]) : abs(x[ri]-x[1])+abs(x[end]-x[start])\n        else\n            lw = isinf(li) ? li : abs(x[start]-x[li])\n            rw = isinf(ri) ? ri : abs(x[ri]-x[start])\n        end\n        return lw,rw\n    end\nend\n\ncirctuningfeature(mfit;od=[π,0.5π],fn=:a,x = 0:0.002:2π) = circtuningfeature(x,predict(mfit,x);od,fn) # 0.002rad ≈ 0.11deg\n\"\"\"\nProperties of Circular Tuning\n\n    - Prefered Angle with Peak Response\n    - Selectivity Index\n        - version 1: (ResponsePeak - ResponseOpposing)/ResponsePeak\n        - version 2: (ResponsePeak - ResponseOpposing)/(ResponsePeak + ResponseOpposing)\n    - Half Width at Half Peak-to-Trough\n\n1. x: angles in radius\n2. y: responses\n- od: opposing angle distance to prefered angle, e.g. π for DSI, 0.5π for OSI\n- fn: factor name\n\"\"\"\nfunction circtuningfeature(x,y;od=[π,0.5π],fn=:a)\n    maxr,maxi = findmax(y)\n    minr,mini = findmin(y)\n    maxx = x[maxi]\n    ox = maxx.+od\n    _,oi = findclosestangle(x,ox)\n    or = y[oi]\n\n    si1 = 1 .- or./maxr\n    si2 = (maxr .- or)./(maxr .+ or)\n    hw = halfwidth(y,start=maxi,v=(maxr+minr)/2,circ=true,x=x)\n\n    (;Symbol(:p,fn)=>rad2deg(mod2pi(maxx)),Symbol(fn,:hw)=>rad2deg.(hw),Symbol(fn,:si1)=>si1,Symbol(fn,:si2)=>si2,Symbol(fn,:od)=>od)\nend\n\nsftuningfeature(mfit;x = 0:0.003:10) = sftuningfeature(x,predict(mfit,x))\n\"\"\"\nProperties of Spatial Frequency Tuning\n\n    - Prefered Spatial Frequency with Peak Response\n    - Half Width at Half Peak-to-Trough\n    - Freq Passing Type {A:All Pass, H:High Pass, L:Low Pass, B:Band Pass}\n    - Bandwidth ``log2(H_cut/L_cut)``\n    - Passwidth at Half Peak-to-Trough constrained by low freq lim and high freq lim\n\n1. x: sf in cycle/degree\n2. y: responses\n\"\"\"\nfunction sftuningfeature(x,y;low=minimum(x),high=maximum(x))\n    maxr,maxi = findmax(y)\n    minr,mini = findmin(y)\n    maxx = x[maxi]\n\n    hw = halfwidth(y,start=maxi,v=(maxr+minr)/2,circ=false,x=x)\n    pt = all(isinf.(hw)) ? 'A' : isinf(hw[1]) ? 'L' : isinf(hw[2]) ? 'H' : 'B'\n    bw = log2((maxx+hw[2])/(maxx-hw[1]))\n    pw = pt == 'A' ? high-low : pt == 'L' ? maxx-low+hw[2] : pt == 'H' ? high-maxx+hw[1] : sum(hw)\n\n    (;psf=maxx,sfhw=hw,sftype=pt,sfbw=bw,sfpw=pw)\nend\n\n\"\"\"\nTuning properties of factor response\n\n1. fl: factor levels\n2. fr: factor responses for each level\n\n    Angle, Orientation and Direction follow the same convention such that 0 is -/→, then increase counter-clock wise.\n\n    For cases where Orientation and Direction are interlocked(drifting grating):\n        - when Orientation is -(0), then Direction is ↑(90)\n        - when Direction is →(0), then Orientation is |(-90)\n\"\"\"\nfunction factorresponsefeature(fl,fr;fm=mean.(fr),factor=:Ori,isfit::Bool=true)\n    i = .!ismissing.(fr)\n    fl = fl[i];fr=fr[i];fm=fm[i]\n    ls = mapreduce((l,r)->fill(l,length(r)),append!,fl,fr)\n    rs = mapreduce(deepcopy,append!,fr)\n\n    if factor in [:Ori,:Ori_Final]\n        θ = mod2pi.(deg2rad.(ls))\n        α = mod2pi.(deg2rad.(fl))\n        d = mean(diff(sort(unique(α)))) # angle spacing\n        up, = circ_otest(α,w=fm) # Omnibus test for non-uniformity\n        # for orientation\n        oα = mod.(α,π)\n        ocv, = circ_var(2oα,w=fm,d=2d)\n        ocm, = circ_mean(2oα,w=fm)\n        ocm = rad2deg(mod2pi(ocm)/2)\n        # for direction\n        dcv, = circ_var(α;w=fm,d)\n        dcm, = circ_mean(α,w=fm)\n        dcm = rad2deg(mod2pi(dcm+0.5π))\n        maxr,maxi = findmax(fm)\n        maxl = fl[maxi]\n\n        fit = ()\n        if isfit\n            try\n                mfit = fitmodel(:gvm,θ,rs) # fit Generalized von Mises\n                fit = (;circtuningfeature(mfit,od=[π,0.5π],fn=:o)...,mfit)\n            catch\n                display.(stacktrace(catch_backtrace()))\n            end\n        end\n\n        return (;up,ocv,ocm,dcv,dcm,max=maxl=>maxr,fit)\n    elseif factor == :Dir\n        θ = deg2rad.(fl)\n        d = mean(diff(sort(unique(θ)))) # angle spacing\n        # for orientation\n        oθ = mod.(θ.-0.5π,π)\n        om, = circ_mean(2oθ,w=fr)\n        oo = rad2deg(mod(angle(om),2π)/2)\n        ocv = circ_var(2oθ,w=fr,d=2d)\n        # for direction\n        dm, = circ_mean(θ,w=fr)\n        od = rad2deg(mod(angle(dm),2π))\n        dcv = circ_var(θ;w=fr,d)\n        # fit Generalized von Mises for direction\n        fit = ()\n        if isfit\n            try\n                mfit = fitmodel(:gvm,θ,fr)\n                fit = (circtuningfeature(mfit,od=π,fn=:d)...,gvm=mfit)\n            catch\n            end\n            # fit von Mises for orientation\n            try\n                mfit = fitmodel(:vmn2, θ.-0.5π,fr)\n                fit =(fit...,circtuningfeature(mfit, od=0.5π,fn=:o)...,vmn2=mfit)\n            catch\n            end\n        end\n\n        return (;dm,od,dcv,om,oo,ocv,fit)\n    elseif factor == :SpatialFreq\n        up = PyOnewayANOVA.anova_oneway(fr,use_var=\"unequal\").pvalue\n        msf = 2^(sum(rs.*log2.(ls))/sum(rs)) # weighted average\n        maxr,maxi = findmax(fm)\n        maxl = fl[maxi]\n\n        fit = ()\n        if isfit\n            try\n                # mfit = fitmodel(:sfdog,ls,rs) # fit Difference of Gaussians\n                mfit = fitmodel(:sfgaussian,ls,rs) # fit Gaussian of logarithm sf\n                fit = (;sftuningfeature(mfit)...,mfit)\n            catch\n                display.(stacktrace(catch_backtrace()))\n            end\n        end\n\n        return (;up,msf,max=maxl=>maxr,fit)\n    elseif factor == :ColorID\n        # transform colorId to hue angle\n        ucid = sort(unique(fl))\n        hstep = 2pi/length(ucid)\n        ha = map(l->hstep*(findfirst(c->c==l,ucid)-1),fl)\n        # for hue direction\n        hm, = circ_mean(ha,w=fr)\n        oh = mod(rad2deg(angle(hm)),360)\n        hcv = circ_var(ha,w=fr,d=hstep)\n        maxi = argmax(fr)\n        maxh = rad2deg(ha[maxi])\n        maxr = fr[maxi]\n\n        fit = ()\n        if isfit\n            # fit Generalized von Mises for hue\n            try\n                mfit = fitmodel(:gvm,θ,fr)\n                fit = (circtuningfeature(mfit,od=π,fn=:h)...,gvm=mfit)\n            catch\n            end\n            # fit von Mises for hue axis\n            try\n                mfit = fitmodel(:vmn2,θ,fr)\n                fit = (fit...,circtuningfeature(mfit,od=0.5π,fn=:ha)...,vmn2=mfit)\n            catch\n            end\n        end\n\n        return (;ham,oha,hacv,hm,oh,hcv,maxh,maxr,fit)\n    elseif factor in [:HueAngle,:Angle]\n        θ = mod2pi.(deg2rad.(ls))\n        α = mod2pi.(deg2rad.(fl))\n        d = mean(diff(sort(unique(α)))) # angle spacing\n        up, = circ_otest(α,w=fm) # Omnibus test for non-uniformity\n        # for axis\n        aα = mod.(α,π)\n        acv, = circ_var(2aα,w=fm,d=2d)\n        acm, = circ_mean(2aα,w=fm)\n        acm = rad2deg(mod2pi(acm)/2)\n        # for angle\n        cv, = circ_var(α;w=fm,d)\n        cm, = circ_mean(α,w=fm)\n        cm = rad2deg(mod2pi(cm))\n        maxr,maxi = findmax(fm)\n        maxl = fl[maxi]\n\n        fit = ()\n        if isfit\n            try\n                mfit = fitmodel(:gvm,θ,rs) # fit Generalized von Mises\n                fit = (;circtuningfeature(mfit,od=[π,0.5π],fn=:a)...,mfit)\n            catch\n                display.(stacktrace(catch_backtrace()))\n            end\n        end\n\n        return (;up,acv,acm,cv,cm,max=maxl=>maxr,fit)\n    else\n        return ()\n    end\nend\n\n\"\"\"\nSpike Triggered Average of Images\n\n1. x: Matrix where each row is one image\n2. y: Vector of image response\n\n- norm: normalization factor, default no normalization.\n        it could be ``sum(y)`` if y is number of spike or spike rate, then STA would be spiking probability.\n- whiten: whiten factor, default no whiten.\n        it could be ``(xᵀx)⁻¹`` or inverse of covariance matrix, that decorrelate STA.\n\"\"\"\nfunction sta(x::AbstractMatrix,y::AbstractVector;norm=nothing,whiten=nothing)\n    r = x'*y\n    isnothing(norm) || (r/=norm)\n    isnothing(whiten) || (r=whiten*r)\n\n    # r = x'*x\\r\n    # r=length(y)*inv(cov(x,dims=1))*r\n\n    return r\nend\n\n\nfunction psthsts(xs::Vector,binedges::Vector,c;israte::Bool=true,normfun=nothing)\n    m,se,x = psth(xs,binedges,israte=israte,normfun=normfun)\n    df = DataFrame(x=x,m=m,se=se,c=fill(c,length(x)))\nend\nfunction psthsts(xs::Vector,binedges::Vector,cond::DataFrame;israte::Bool=true,normfun=nothing)\n    fs = finalfactor(cond)\n    vcat([psth(xs[r[:i]],binedges,condstring(r,fs),israte=israte,normfun=normfun) for r in eachrow(cond)]...)\nend\nfunction psthsts(xs::Vector,binedges::Vector,ctc::DataFrame,factor;israte::Bool=true,normfun=nothing)\n    vf = intersect(names(ctc),factor)\n    isempty(vf) && error(\"No Valid Factor Found.\")\n    psth(xs,binedges,condin(ctc[:,vf]),israte=israte,normfun=normfun)\nend\nfunction psth(ds::DataFrame,binedges::Vector,conds::Vector;normfun=nothing,spike=:spike,isse::Bool=true)\n    is,ss = findcond(ds,conds)\n    df = psth(map(x->ds[spike][x],is),binedges,ss,normfun=normfun)\n    if isse\n        df[:ymin] = df[:y]-df[:ysd]./sqrt(df[:n])\n        df[:ymax] = df[:y]+df[:ysd]./sqrt(df[:n])\n    end\n    return df,ss\nend\nfunction psthstss(xss::Vector,binedges::Vector,conds;normfun=nothing)\n    n = length(xss)\n    n!=length(conds) && error(\"Length of xss and conds don't match.\")\n    dfs = [psth(xss[i],binedges,conds[i],normfun=normfun) for i=1:n]\n    return cat(1,dfs)\nend\nfunction unitdensity(pos;w=ones(length(pos)),spacerange=extrema(pos),bw=0.01(last(spacerange)-first(spacerange)),\n                    step=bw/2,r=nothing,wfun=sum,s=nothing)\n    hbw = bw/2\n    y = first(spacerange):step:last(spacerange)\n    n = [wfun(w[i-hbw .<=pos.< i+hbw]) for i in y]\n    if !isnothing(r)\n        n = n/(bw*π*r^2)\n    end\n    i = isnan.(n) .| isinf.(n)\n    if any(i)\n        n = Spline1D(y[.!i],n[.!i],k=3,bc=\"extrapolate\")(y)\n    end\n    if !isnothing(s)\n        g = gaussianf.(-5:5,σ=s)\n        g ./= sum(g)\n        n = imfilter(n,centered(g),ImageFiltering.Fill(0))\n    end\n    return (;n,y)\nend\nfunction spacepsth(unitpsth,unitposition;w=ones(size(unitposition,1)),spacerange=extrema(unitposition),\n                    bw=0.01(last(spacerange)-first(spacerange)),step=bw/2)\n    hbw = bw/2\n    x = unitpsth[1].x\n    y = first(spacerange):step:last(spacerange)\n\n    n = zeros(length(y))\n    psth = zeros(length(y),length(x))\n    for i in eachindex(y)\n        @views j = y[i]-hbw .<=unitposition[:,2].< y[i]+hbw\n        n[i] = sum(w[j])\n        if n[i] > 0\n            @views psth[i,:] = mapreduce(u->u.m,.+,unitpsth[j])/n[i]\n        end\n    end\n    return (;psth,x,y,n)\nend\n\n\n\"\"\"\nShift(shuffle) corrected, normalized(coincidence/spike), condition/trial-averaged Cross-Correlogram of binary spike trains.\n(Bair, W., Zohary, E., and Newsome, W.T. (2001). Correlated Firing in Macaque Visual Area MT: Time Scales and Relationship to Behavior. J. Neurosci. 21, 1676–1697.)\n\"\"\"\nfunction correlogram(bst1,bst2;lag=nothing,isnorm=true,shiftcorrection=true,condis=nothing)\n    if !isnothing(condis)\n        cccg=[];x=[]\n        for ci in condis\n            ccg,x = correlogram(bst1[:,ci],bst2[:,ci],lag=lag,isnorm=isnorm,shiftcorrection=shiftcorrection,condis=nothing)\n            push!(cccg,ccg)\n        end\n        ccg=dropdims(mean(hcat(cccg...),dims=2),dims=2)\n        return ccg,x\n    end\n    n,nepoch = size(bst1)\n    lag = floor(Int,isnothing(lag) ? min(n-1, 10*log10(n)) : lag)\n    x = -lag:lag;xn=2lag+1\n    cc = Array{Float64}(undef,xn,nepoch)\n    for k in 1:nepoch\n        cc[:,k]=crosscov(bst1[:,k],bst2[:,k],x,demean=false)*n\n    end\n    ccg = dropdims(mean(cc,dims=2),dims=2)\n    if isnorm\n        λ1 = mean(mean(bst1,dims=1))\n        λ2 = mean(mean(bst2,dims=1))\n        gmsr = sqrt(λ1*λ2)\n        Θ = n.-abs.(x)\n        normfactor = 1 ./ Θ ./ gmsr\n    end\n    if shiftcorrection\n        psth1 = dropdims(mean(bst1,dims=2),dims=2)\n        psth2 = dropdims(mean(bst2,dims=2),dims=2)\n        s = crosscov(psth1,psth2,x,demean=false)*n\n        shiftccg = (nepoch*s .- ccg)/(nepoch-1)\n        if isnorm\n            ccg .*= normfactor\n            shiftccg .*= normfactor\n        end\n        ccg .-= shiftccg\n    elseif isnorm\n        ccg .*= normfactor\n    end\n    ccg,x\nend\nfunction circuitestimate(unitbinspike;lag=nothing,maxprojlag=3,minepoch=5,minspike=10,esdfactor=5,isdfactor=3.5,unitid=[],condis=nothing)\n    nunit=length(unitbinspike)\n    n,nepoch = size(unitbinspike[1])\n    lag = floor(Int,isnothing(lag) ? min(n-1, 10*log10(n)) : lag)\n    x = -lag:lag;xn=2lag+1\n\n    isenoughspike = (i,j;minepoch=5,minspike=10) -> begin\n        vsi = sum(i,dims=1)[:] .>= minspike\n        vsj = sum(j,dims=1)[:] .>= minspike\n        count(vsi) >= minepoch && count(vsj) >= minepoch\n    end\n\n    ccgs=[];ccgis=[];projs=[];eunits=[];iunits=[];projweights=[]\n    for (i,j) in combinations(1:nunit,2)\n        if isnothing(condis)\n            !isenoughspike(unitbinspike[i],unitbinspike[j],minepoch=minepoch,minspike=minspike) && continue\n            vcondis=nothing\n        else\n            vci = map(ci->isenoughspike(unitbinspike[i][:,ci],unitbinspike[j][:,ci],minepoch=minepoch,minspike=minspike),condis)\n            all(.!vci) && continue\n            vcondis = condis[vci]\n        end\n\n        ccg,_ = correlogram(unitbinspike[i],unitbinspike[j],lag=lag,condis=vcondis)\n        ps,es,is,pws = projectionfromcorrelogram(ccg,i,j,maxprojlag=maxprojlag,esdfactor=esdfactor,isdfactor=isdfactor)\n        if !isempty(ps)\n            push!(ccgs,ccg);push!(ccgis,(i,j))\n            append!(projs,ps);append!(eunits,es);append!(iunits,is);append!(projweights,pws)\n        end\n    end\n    unique!(eunits);unique!(iunits)\n    if length(unitid)==nunit\n        map!(t->(unitid[t[1]],unitid[t[2]]),ccgis,ccgis)\n        map!(t->(unitid[t[1]],unitid[t[2]]),projs,projs)\n        map!(t->unitid[t],eunits,eunits)\n        map!(t->unitid[t],iunits,iunits)\n    end\n    return ccgs,x,ccgis,projs,eunits,iunits,projweights\nend\nfunction projectionfromcorrelogram(cc,i,j;maxprojlag=3,minbaselag=maxprojlag+1,esdfactor=5,isdfactor=5)\n    midi = Int((length(cc)+1)/2)\n    base = [cc[midi+minbaselag:end];cc[1:midi-minbaselag]]\n    bm,bsd = mean_and_std(base);hl = bm + esdfactor*bsd;ll = bm - isdfactor*bsd\n    forwardlags = midi+1:midi+maxprojlag\n    backwardlags = midi-maxprojlag:midi-1\n    fcc = cc[forwardlags]\n    bcc = cc[backwardlags]\n    ps=[];ei=[];ii=[];pws=[]\n\n    if ll <= cc[midi] <= hl\n        if any(fcc .> hl)\n            push!(ps,(i,j));push!(ei,i);push!(pws,(maximum(fcc)-bm)/bsd)\n        elseif any(fcc .< ll)\n            push!(ps,(i,j));push!(ii,i);push!(pws,(minimum(fcc)-bm)/bsd)\n        end\n        if any(bcc .> hl)\n            push!(ps,(j,i));push!(ei,j);push!(pws,(maximum(bcc)-bm)/bsd)\n        elseif any(bcc .< ll)\n            push!(ps,(j,i));push!(ii,j);push!(pws,(minimum(bcc)-bm)/bsd)\n        end\n    end\n    return ps,ei,ii,pws\nend\n\n\"Check Layer Boundaries\"\nfunction checklayer!(ls::Dict;ln=[\"1\", \"2\", \"3\", \"23\", \"4A\", \"4B\", \"4AB\", \"4Cα\", \"4Cβ\", \"4C\", \"5\", \"6\", \"56\", \"WM\"])\n    n = length(ln)\n    for i in 1:n-1\n        if haskey(ls,ln[i])\n            for j in (i+1):n\n                if haskey(ls,ln[j])\n                    ls[ln[i]][1] = ls[ln[j]][2]\n                    break\n                end\n            end\n        end\n    end\n    return ls\nend\n\n\"\"\"\nTry to locate cell layer.\n\n1. y coordinate of cell postion\n2. layer definition\n\"\"\"\nfunction assignlayer(y,layer::Dict)\n    l = missing\n    for k in keys(layer)\n        if layer[k][1] <= y < layer[k][2]\n            l=k;break\n        end\n    end\n    return l\nend\n\n\"Check circuit consistency and remove duplicates\"\nfunction checkcircuit(projs,eunits,iunits,projweights)\n    ivu = intersect(eunits,iunits)\n    veunits = setdiff(eunits,ivu)\n    viunits = setdiff(iunits,ivu)\n    ivp = map(p->p[1] in ivu,projs)\n    vprojs = projs[.!ivp]\n    vprojweights = projweights[.!ivp]\n    ui = indexin(unique(vprojs),vprojs)\n    return vprojs[ui],veunits,viunits,vprojweights[ui]\nend\n", "meta": {"hexsha": "8b287e64cb82f4c070c14b9b0c68e4d7f67ab943", "size": 30340, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Base/Base.jl", "max_stars_repo_name": "babaq/NeuroAnalysis.jl", "max_stars_repo_head_hexsha": "186a00c4b26a042d2b9e29d247183782fb38d5d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-09-24T05:33:01.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-16T13:08:44.000Z", "max_issues_repo_path": "src/Base/Base.jl", "max_issues_repo_name": "VLABSys/NeuroAnalysis.jl", "max_issues_repo_head_hexsha": "186a00c4b26a042d2b9e29d247183782fb38d5d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Base/Base.jl", "max_forks_repo_name": "VLABSys/NeuroAnalysis.jl", "max_forks_repo_head_hexsha": "186a00c4b26a042d2b9e29d247183782fb38d5d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8238573021, "max_line_length": 164, "alphanum_fraction": 0.5534937376, "num_tokens": 11894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474142844408, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7804953618048792}}
{"text": "## Here is the code from unit 1\n\n##\nusing DelimitedFiles\nusing SparseArrays\nei,ej = copy.(eachcol(Int.(readdlm(\"wiki-simple.edges\"))))\nxy = readdlm(\"wiki-simple.xy\")\npages = readlines(\"wiki-simple.nodes\")\nn = size(xy,1)\nA = sparse(ei,ej,1,n,n)\n\n##  PageRank with coordinate relaxation\n#\nfunction relaxpagerank(A,α,v)\n  @assert(0 ≤ α < 1, \"needs probably α\")\n  @assert(all(vi -> vi ≥ 0, v), \"needs non-negative v\")\n  v = v ./ sum(v) # we can normalize for them.\n  d = vec(sum(A,dims=2)) # compute the degrees\n  x = copy(v) # start of with v\n  nsteps = 2*ceil(Int,log(eps(1.0))/log(α)) # upper bound on steps\n  # we need row's of A', which are columns of A.\n  # it's also easier to iterate over Di*x, instead of x\n  d[d .== 0] .= 1 # switch 0's to 1's\n  idx = x./d\n  for i=1:nsteps\n    for j=1:size(A,1)\n      rhs = (1-α)*v[j]  + α*(A[:,j]'*idx)\n      gamma = rhs/(1 - α*A[j,j])\n      idx[j] = gamma/d[j]\n    end\n  end\n  x =  (d.*idx)\n  return x/sum(x) # renormalize to probability\nend\nx = relaxpagerank(A,0.85,ones(n)/n)\n\n##\nusing MatrixNetworks\npr = pagerank(A,0.85)\nnorm(x-pr)\n", "meta": {"hexsha": "525b853de231135d4b03ea41a8c960e0e3a9753e", "size": 1078, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5-unit-4-demos/pagerank-relax.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "5-unit-4-demos/pagerank-relax.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5-unit-4-demos/pagerank-relax.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 26.2926829268, "max_line_length": 66, "alphanum_fraction": 0.6141001855, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474168650673, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7804953596714111}}
{"text": "\"\"\"\n    gamma_rng(α, β, shape=1; seed=nothing)\n\nGenerate a `shape` element array of random variables from a Gamma(`α`, `β`) distribution. Optionally you can set a specific seed.\n\n# Notes\n\nThe Gamma distribution is given:\n\n``f(x,α,β) = \\\\frac{β^α x^{α-1} e^{-βx}}{Γ(α)} \\\\quad x ≥ 0``\n\n# Examples\n\n```julia-repl\njulia> gamma_rng(1,1)\n1-element Vector{Float64}:\n 0.5190236735858542\n\njulia> gamma_rng(1,1,4)\n4-element Vector{Float64}:\n 0.3035517926878862\n 0.5765419737109622\n 0.44121996206333797\n 0.7325887616559309\n\njulia> gamma_rng(1,1,(2,2))\n2×2 Matrix{Float64}:\n 0.228818  0.88849\n 0.665729  1.01668\n \n```\n\n# References\n\nLaw, A. Simulation modeling and analysis, 5th Ed. McGraw Hill Education, Tuscon, 2013.\n\"\"\"\nfunction gamma_rng(α::Real, β::Real=1, shape::Union{Int, Tuple{Vararg{Int}}}=1; seed::Union{Int, Nothing}=nothing)\n    seed_setter(seed)\n    X = β .* get_gamma_rv(α, shape)\n    return X\nend\n\n\nfunction get_gamma_rv(α::Real, shape::Union{Int, Tuple{Vararg{Int}}}=1; seed::Union{Int, Nothing}=nothing)\n    seed_setter(seed)\n    if α < 0\n        throw(ArgumentError(\"Not implemented for α < 0.\"))\n    elseif α == 1\n        return expon_rng(1, shape)\n    elseif α < 1\n        X = zeros(shape)\n        X .= get_gamma_ad.(α)\n        return X\n    else \n        X = zeros(shape)\n        X .= get_gamma_gb.(α)\n        return X\n    end\nend\n\n\nfunction get_gamma_ad(α::Real; max_iter=300)\n    b = (ℯ + α)/ℯ\n    i = 0\n    while i < max_iter\n        U₁ = get_std_uniform()[1]\n        P = b*U₁\n        if P > 1\n            Y = -log((b-P)/α)\n            U₂ = get_std_uniform()[1]\n            if U₂ ≤ Y^(α-1)\n                return Y\n            end\n        else\n            Y = P^(1/α)\n            U₂ = get_std_uniform()[1]\n            if U₂ ≤ ℯ^(-Y)\n                return Y\n            end\n        end\n        i +=1\n    end\nend\n\n\nfunction get_gamma_gb(α::Real; max_iter=300)\n    a = 1 / sqrt(2*α - 1)\n    b = α - log(4)\n    q = α + 1/a\n    θ = 4.5\n    d = 1 + log(θ)\n    i = 0\n    while i < max_iter\n        U₁, U₂ = get_std_uniform(2)\n        V = a * log(U₁/(1-U₁))\n        Y = α * ℯ^V\n        Z = U₁^2 * U₂\n        W = b + q * V - Y\n        if W + d - θ * Z ≥ 0\n            return Y\n        elseif W ≥ log(Z)\n            return Y\n        end\n        i += 1\n    end\nend\n", "meta": {"hexsha": "c3b2b67aa8e3fde96e2beffc07cb20da42899313", "size": 2269, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gamma.jl", "max_stars_repo_name": "chris-santiago/RandomVariates.jl", "max_stars_repo_head_hexsha": "75cf7057d06482f5208233f0f78f08e0dcfee58f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gamma.jl", "max_issues_repo_name": "chris-santiago/RandomVariates.jl", "max_issues_repo_head_hexsha": "75cf7057d06482f5208233f0f78f08e0dcfee58f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gamma.jl", "max_forks_repo_name": "chris-santiago/RandomVariates.jl", "max_forks_repo_head_hexsha": "75cf7057d06482f5208233f0f78f08e0dcfee58f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2056074766, "max_line_length": 129, "alphanum_fraction": 0.5354781842, "num_tokens": 807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474155747541, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7804953564948227}}
{"text": "# The following iterative sequence is defined for the set of positive integers:\n#\n# n → n/2 (n is even)\n# n → 3n + 1 (n is odd)\n#\n# Using the rule above and starting with 13, we generate the following sequence:\n#\n# 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1\n#\n# It can be seen that this sequence (starting at 13 and finishing at 1) contains\n# 10 terms. Although it has not been proved yet (Collatz Problem), it is thought\n# that all starting numbers finish at 1.\n#\n# Which starting number, under one million, produces the longest chain?\n#\n# NOTE: Once the chain starts the terms are allowed to go above one million.\n\nusing ProjectEulerSolutions\n\n# Memoization type solution to store intermediate results without recursion.\n# It does end up recalculating some solutions multiple times.\nfunction p014solution_memoize(num::Integer=3)::Integer\n    cache = Dict{Integer, Integer}(1 => 1)\n    for k = 2:num\n        n = k\n        i = 1\n        while !haskey(cache, n)\n            if n % 2 == 0\n                n = fld(n, 2)\n            else\n                n = 3 * n + 1\n            end\n            i += 1\n        end\n        @inbounds cache[k] = get(cache, n, 0) + i - 1\n    end\n\n    # Find max value\n    return maxdictkey(cache)\nend\n\n# Return maximum value in dictionary\nfunction maxdictkey(cache::Dict{Integer, Integer})::Integer\n    # Find max value\n    maxkey, maxvalue = 0, 0\n    for (key, value) in cache\n        if value > maxvalue\n            maxkey, maxvalue = key, value\n        end\n    end\n    return maxkey\nend\n\n# Dynamic programming type solution to store intermediate results\nfunction collatz!(cache::Dict{Integer, Integer}, n::Integer)::Integer\n    if haskey(cache, n)\n        return cache[n]\n    else\n        if n % 2 == 0\n            @inbounds cache[n] = collatz!(cache, fld(n, 2)) + 1\n        else\n            @inbounds cache[n] = collatz!(cache, 3 * n + 1) + 1\n        end\n        return cache[n]\n    end\nend\n\n# Same type of answer, but with no caching.  Sometimes the \"smartest\" solution\n# isn't always the fastest.\nfunction p014solution_nocache(num::Integer=3)::Integer\n    longest = 0\n    max_terms = 0\n    for i in 1:num\n        n = i\n        nterms = 1\n        while n != 1\n            nterms += 1\n            if nterms > max_terms\n                max_terms = nterms\n                longest = i\n            end\n            if n % 2 == 0\n                n = fld(n, 2)\n            else\n                n = 3 * n + 1\n            end\n        end\n    end\n\n    return longest\nend\n\n# Recursive type solution to store intermediate results.  Theoretically\n# recalculates no numbers, but recursion adds an overhead.\nfunction p014solution_recurse(num::Integer=3)::Integer\n    cache = Dict{Integer, Integer}(1 => 1)\n    for k = num:-1:2\n        if !haskey(cache, k)\n            collatz!(cache, k)\n        end\n    end\n\n    # Find max value\n    return maxdictkey(cache)\nend\n\np014 = Problems.Problem(Dict(\"Recurse\" => p014solution_recurse,\n                             \"Memoize\" => p014solution_memoize,\n                             \"No Cache\" => p014solution_nocache))\n\nProblems.benchmark(p014, 1_000_000)\n", "meta": {"hexsha": "501e83aed17bae09dc61abc65f0fddf81efbf7ed", "size": 3110, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/014.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/014.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/014.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7678571429, "max_line_length": 80, "alphanum_fraction": 0.5897106109, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.7804892107120176}}
{"text": "# sse(x) gives the L2 norm of x\nsse(x) = (x'*x)[1]\n\nfunction levenberg_marquardt(f::Function, g::Function, x0; tolX=1e-8, tolG=1e-12, maxIter=100, lambda=100.0, show_trace=false)\n\t# finds argmin sum(f(x).^2) using the Levenberg-Marquardt algorithm\n\t#          x\n\t# The function f should take an input vector of length n and return an output vector of length m\n\t# The function g is the Jacobian of f, and should be an m x n matrix\n\t# x0 is an initial guess for the solution\n\t# fargs is a tuple of additional arguments to pass to f\n\t# available options:\n\t#   tolX - search tolerance in x\n\t#   tolG - search tolerance in gradient\n\t#   maxIter - maximum number of iterations\n\t#   lambda - (inverse of) initial trust region radius\n\t#   show_trace - print a status summary on each iteration if true\n\t# returns: x, J\n\t#   x - least squares solution for x\n\t#   J - estimate of the Jacobian of f at x\n\n\t# other constants\n\tconst MAX_LAMBDA = 1e16 # minimum trust region radius\n\tconst MIN_LAMBDA = 1e-16 # maximum trust region radius\n\tconst MIN_STEP_QUALITY = 1e-3\n\tconst MIN_DIAGONAL = 1e-6 # lower bound on values of diagonal matrix used to regularize the trust region step\n\n\tconverged = false\n\titerCt = 0\n\tx = x0\n\tdelta_x = copy(x0)\n\tf_calls = 0\n\tg_calls = 0\n\n\tfcur = f(x)\n\tf_calls += 1\n\tresidual = sse(fcur)\n\t\n\t# Maintain a trace of the system.\n\ttr = OptimizationTrace()\n\tif show_trace\n\t\td = {\"lambda\" => lambda}\n\t\tos = OptimizationState(x, sse(fcur), iterCt, d)\n\t\tpush!(tr, os)\n\t\tprintln(os)\n\tend\n\n\twhile ( ~converged && iterCt < maxIter )\n\t\tJ = g(x)\n\t\tg_calls += 1\n\t\t# we want to solve:\n\t\t#    argmin 0.5*||J(x)*delta_x + f(x)||^2 + lambda*||diagm(J'*J)*delta_x||^2\n\t\t# Solving for the minimum gives:\n\t\t#    (J'*J + lambda*DtD) * delta_x == -J^T * f(x), where DtD = diagm(sum(J.^2,1))\n\t\t# Where we have used the equivalence: diagm(J'*J) = diagm(sum(J.^2, 1))\n\t\t# It is additionally useful to bound the elements of DtD below to help\n\t\t# prevent \"parameter evaporation\".\n\t\tDtD = diagm(Float64[max(x, MIN_DIAGONAL) for x in sum(J.^2,1)])\n\t\tdelta_x = ( J'*J + sqrt(lambda)*DtD ) \\ -J'*fcur\n\t\t# if the linear assumption is valid, our new residual should be:\n\t\tpredicted_residual = sse(J*delta_x + fcur)\n\t\t# check for numerical problems in solving for delta_x by ensuring that the predicted residual is smaller\n\t\t# than the current residual\n\t\tif predicted_residual > residual\n\t\t\terror(\"Error solving for delta_x: predicted residual increase.\")\n\t\tend\n\t\t# try the step and compute its quality\n\t\ttrial_f = f(x + delta_x)\n\t\tf_calls += 1\n\t\ttrial_residual = sse(trial_f)\n\t\t# step quality = residual change / predicted residual change\n\t\trho = (trial_residual - residual) / (predicted_residual - residual)\n\n\t\tif rho > MIN_STEP_QUALITY\n\t\t\tx += delta_x\n\t\t\tfcur = trial_f\n\t\t\tresidual = trial_residual\n\t\t\t# increase trust region radius\n\t\t\tlambda = max(0.1*lambda, MIN_LAMBDA)\n\t\telse\n\t\t\t# decrease trust region radius\n\t\t\tlambda = min(10*lambda, MAX_LAMBDA)\n\t\tend\n\t\titerCt += 1\n\n\t\t# show state\n\t\tif show_trace\n\t\t\td = {\"g(x)\" => norm(J'*fcur, Inf), \"dx\" => delta_x, \"lambda\" => lambda}\n\t\t\tos = OptimizationState(x, sse(fcur), iterCt, d)\n\t\t\tpush!(tr, os)\n\t\t\tprintln(os)\n\t\tend\n\n\t\t# check convergence criteria:\n\t\t# 1. Small gradient: norm(J^T * fcur, Inf) < tolG\n\t\t# 2. Small step size: norm(delta_x) < tolX\n\t\tif norm(J' * fcur, Inf) < tolG\n\t\t\tconverged = true\n\t\telseif norm(delta_x) < tolX*(tolX + norm(x))\n\t\t\tconverged = true\n\t\tend\n\tend\n\n\t# give the user info about the stopping condition\n\tif ~converged\n\t\tprintln(\"Exceeded maximum number of iterations\")\n\tend\n\n\tOptimizationResults(\"Levenberg-Marquardt\", x0, x, sse(fcur), iterCt, converged, tr, f_calls, g_calls)\nend", "meta": {"hexsha": "885c0d251833a76469e00c00d6c925b5f2f67c0e", "size": 3640, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/levenberg_marquardt.jl", "max_stars_repo_name": "aviks/Optim.jl", "max_stars_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-22T09:32:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-22T09:32:32.000Z", "max_issues_repo_path": "src/levenberg_marquardt.jl", "max_issues_repo_name": "aviks/Optim.jl", "max_issues_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/levenberg_marquardt.jl", "max_forks_repo_name": "aviks/Optim.jl", "max_forks_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3944954128, "max_line_length": 126, "alphanum_fraction": 0.682967033, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7804892094992466}}
{"text": "\"\"\"\n    Adam(;lr=0.001, gclip=0, beta1=0.9, beta2=0.999, eps=1e-8)\n    update!(w,g,p::Adam)\n\nContainer for parameters of the Adam optimization algorithm used by\n[`update!`](@ref).\n\nAdam is one of the methods that compute the adaptive learning rate. It\nstores accumulated gradients (first moment) and the sum of the squared\nof gradients (second).  It scales the first and second moment as a\nfunction of time. Here is the update formulas:\n\n    m = beta1 * m + (1 - beta1) * g\n    v = beta2 * v + (1 - beta2) * g .* g\n    mhat = m ./ (1 - beta1 ^ t)\n    vhat = v ./ (1 - beta2 ^ t)\n    w = w - (lr / (sqrt(vhat) + eps)) * mhat\n\nwhere `w` is the weight, `g` is the gradient of the objective function\nw.r.t `w`, `lr` is the learning rate, `m` is an array with the same\nsize and type of `w` and holds the accumulated gradients. `v` is an\narray with the same size and type of `w` and holds the sum of the\nsquares of the gradients. `eps` is a small constant to prevent a zero\ndenominator. `beta1` and `beta2` are the parameters to calculate bias\ncorrected first and second moments. `t` is the update count.\n\nIf `vecnorm(g) > gclip > 0`, `g` is scaled so that its norm is equal\nto `gclip`.  If `gclip==0` no scaling takes place.\n\nReference: [Kingma, D. P., & Ba,\nJ. L. (2015)](https://arxiv.org/abs/1412.6980). Adam: a Method for\nStochastic Optimization. International Conference on Learning\nRepresentations, 1–13.\n\n\"\"\"\ntype Adam\n    lr::AbstractFloat\n    gclip::AbstractFloat\n    beta1::AbstractFloat\n    beta2::AbstractFloat\n    eps::AbstractFloat\n    t::Int\n    fstm\n    scndm\nend\n\nAdam(; lr=0.001, gclip=0, beta1=0.9, beta2=0.999, eps=1e-8)=Adam(lr, gclip, beta1, beta2, eps, 0, nothing, nothing)\n\nfunction update!(w, g, p::Adam)\n    gclip!(g, p.gclip)\n    if p.fstm===nothing; p.fstm=zeros(w); p.scndm=zeros(w); end\n    p.t += 1\n    scale!(p.beta1, p.fstm)\n    axpy!(1-p.beta1, g, p.fstm)\n    scale!(p.beta2, p.scndm)\n    axpy!(1-p.beta2, g .* g, p.scndm)\n    fstm_corrected = p.fstm / (1 - p.beta1 ^ p.t)\n    scndm_corrected = p.scndm / (1 - p.beta2 ^ p.t)\n    axpy!(-p.lr, (fstm_corrected ./ (sqrt.(scndm_corrected) + p.eps)), w)\nend\n", "meta": {"hexsha": "65c5a3fd1eeb1b763c455f4b1da86f6a9f0db38d", "size": 2132, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Adam.jl", "max_stars_repo_name": "QuantumBFS/AbstractGradOptim.jl", "max_stars_repo_head_hexsha": "7520e0d8572364bbe323b74ad238059463ee7b64", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-25T03:34:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-25T03:34:19.000Z", "max_issues_repo_path": "src/Adam.jl", "max_issues_repo_name": "QuantumBFS/AbstractGradOptim.jl", "max_issues_repo_head_hexsha": "7520e0d8572364bbe323b74ad238059463ee7b64", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Adam.jl", "max_forks_repo_name": "QuantumBFS/AbstractGradOptim.jl", "max_forks_repo_head_hexsha": "7520e0d8572364bbe323b74ad238059463ee7b64", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-07-25T03:34:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:57:28.000Z", "avg_line_length": 34.9508196721, "max_line_length": 115, "alphanum_fraction": 0.6552532833, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7804826786765714}}
{"text": "# Linear algebra functions not in the standard library.\n\nexport orthogonal, orthogonal!, pca, explained_variance, projection_distance\n\n\"\"\"Return the angle between a and b\"\"\"\nfunction Base.angle(a::AbstractVector, b::AbstractVector)\n    length(a) == length(b) || throw(DimensionMismatch(\"a has dimension $(length(a)), but b has dimension $(length(b))\"))\n    acos(min(max(-1.0, dot(a, b) / norm(a) / norm(b)), 1.0))\nend\n\n\"\"\"return the angle between w and v, accounting for their sign\"\"\"\nminangle(w, v) = min(angle(w, v), angle(w, -v))\n\n\"\"\"\n    pca(X::AbstractMatrix, k::Integer=min(size(X)...))\n\nCompute the top `k` PCs of `X` via `LinearAlgebra.svd`. The columns of `X` correspond to samples and \nthe rows to features.\n\"\"\"\nfunction pca(X::AbstractMatrix, k::Integer=min(size(X)...))\n    F = svd(X)\n    return F.U[:, 1:k]\nend\n\n\"\"\"Orthogonalize and normalize the columns of A in-place.\"\"\"\nfunction orthogonal!(A::AbstractMatrix)\n    m, n = size(A)\n    for i in 1:n\n        for j in 1:i-1\n            l = dot(view(A, :, j), view(A, :, i))\n            for k in 1:size(A, 1)\n                A[k, i] -= l*A[k, j]\n            end\n        end\n        g = norm(view(A, :, i))\n        if g > sqrt(eps(eltype(A)) * size(A, 1))\n            view(A, :, i) ./= g\n        end\n        replace!(view(A, :, i), NaN=>zero(eltype(A)))\n    end\n    return A\nend\n\n\"\"\"Orthogonalize and normalize the columns of A.\"\"\"\northogonal(A::AbstractMatrix) = orthogonal!(copy(A))\n\n\"\"\"\n    explained_variance(X, V, den)\n\nExplained variance with pre-computed denominator.\n\"\"\"\nexplained_variance(X, V, Xnorm::Real) = min((norm(X'*V) / Xnorm)^2, 1.0-eps(Float64))\n\n\"\"\"\n    explained_variance(X, V)\n\nReturn the fraction of variance explained by the principal components\nin V, defined as tr(V'X'XV) / tr(X'X).\n\n\"\"\"\nexplained_variance(X, V) = explained_variance(X, V, norm(X))\n\n\"\"\"\n\nCompute the right-singular vectors from the left-singular vectors `U` and the data matrix `X`.\n\"\"\"\nright_from_left_singular_vectors(X, U) = orthogonal!(U'*X)\n\n\"\"\"\n\nIn-place version of the above.\n\"\"\"\nright_from_left_singular_vectors!(V, X, U) = orthogonal!(mul!(V, U', X))\n\nprojection_distance(X, V) = sqrt(norm(X .- (X*V)*V')) / reduce(*, size(X))\n\nfunction projection_distance(X::SparseMatrixCSC, V)\n    rv = 0.0\n    L = X*V\n    R = V'    \n    Is, Js, Vs = findnz(X)\n    for (i, j, v) in zip(Is, Js, Vs)\n        rv += (Float64(v) - dot(view(L, i, :), view(R, :, j)))^2\n    end\n    rv = sqrt(rv)\n    rv /= length(V)\nend\n\n\"\"\"\n    matrix_from_tensor(T)\n\nConvert a tensor (i.e., a 3D matrix) to a matrix by flattening the first two dimensions. For \nexample, if the tensor corresponds to a vector of images, each image corresponds to a row of \nthe resulting matrix.\n\"\"\"\nfunction matrix_from_tensor(T)\n    d1, d2, n = size(T)\n    d = d1*d2\n    Matrix(reshape(T, d, n)')\nend\n\nimport SparseArrays.AbstractSparseMatrixCSC\nimport SparseArrays.permute, SparseArrays.permute!\nimport SparseArrays.getcolptr\nimport SparseArrays._checkargs_sourcecompatdest_permute!, SparseArrays._checkargs_sourcecompatperms_permute!, SparseArrays._ispermutationvalid_permute!\n\nfunction perm!(X::AbstractSparseMatrixCSC{Tv,Ti}, A::AbstractSparseMatrixCSC{Tv,Ti}, q::AbstractVector{<:Integer}, f::Function=identity) where {Tv,TvA,Ti}\n    Xi = 1\n    getcolptr(X)[1] = Xi\n    for Xj in 1:size(A, 2) # column of X, add @inbounds\n        Aj = q[Xj] # corresponding column of A        \n        for Ai in nzrange(A, Aj) # row of A\n            rowvals(X)[Xi] = rowvals(A)[Ai]\n            nonzeros(X)[Xi] = f(nonzeros(A)[Ai])\n            Xi += 1\n        end\n        getcolptr(X)[Xj+1] = Xi\n    end\n    return X\nend\n\nfunction permute!(X::AbstractSparseMatrixCSC{Tv,Ti}, A::AbstractSparseMatrixCSC{Tv,Ti}, q::AbstractVector{<:Integer}) where {Tv,Ti}\n    _checkargs_sourcecompatdest_permute!(A, X)\n    _checkargs_sourcecompatperms_permute!(A, 1:size(A, 1), q)\n    if !_ispermutationvalid_permute!(q, getcolptr(X))\n        throw(ArgumentError(\"column-permutation argument `q` must be a valid permutation\"))\n    end\n    perm!(X, A, q)\nend\n\nfunction permute(A::AbstractSparseMatrixCSC{Tv,Ti}, q::AbstractVector{<:Integer}) where {Tv,Ti}\n    _checkargs_sourcecompatperms_permute!(A, 1:size(A, 1), q)    \n    X = SparseMatrixCSC(size(A, 1), size(A, 2),\n                        ones(Ti, size(A, 2) + 1),\n                        Vector{Ti}(undef, nnz(A)),\n                        Vector{Tv}(undef, nnz(A)))\n    _checkargs_sourcecompatdest_permute!(A, X)                        \n    if !_ispermutationvalid_permute!(q, getcolptr(X))\n        throw(ArgumentError(\"column-permutation argument `q` must be a valid permutation\"))\n    end\n    perm!(X, A, q)\nend\n", "meta": {"hexsha": "ec456530d3e46d7cbf2a67b2f0eb8fcc16083428", "size": 4646, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Linalg.jl", "max_stars_repo_name": "severinson/CodedComputing.jl", "max_stars_repo_head_hexsha": "c60597579faa176f57c86acd309cf904c395268f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Linalg.jl", "max_issues_repo_name": "severinson/CodedComputing.jl", "max_issues_repo_head_hexsha": "c60597579faa176f57c86acd309cf904c395268f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Linalg.jl", "max_forks_repo_name": "severinson/CodedComputing.jl", "max_forks_repo_head_hexsha": "c60597579faa176f57c86acd309cf904c395268f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4895104895, "max_line_length": 154, "alphanum_fraction": 0.6340938442, "num_tokens": 1355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7804826761446231}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Statistics, Distributions, DataFrames, CSV\n\tusing HypothesisTests\nend;\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.10\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tdata = CSV.read(datadir(\"machine1.csv\"), DataFrame; delim=\",\")[:, 1]\nend;\n\n# ╔═╡ 1aa41898-3afa-11eb-2f49-570853ce6435\nbegin\n\tn, s, alpha = length(data), std(data), 0.1\n\tci = (  (n-1)*s^2/quantile(Chisq(n-1),1-alpha/2),\n\t\t\t(n-1)*s^2/quantile(Chisq(n-1),alpha/2)  )\n\n\tText(\"Point estimate for the variance: $(s^2)\")\nend\n\n# ╔═╡ d0a56572-3b2a-11eb-383a-f94fe2f45a5b\nText(\"Confidence interval for the variance: $ci\")\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.10\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═1aa41898-3afa-11eb-2f49-570853ce6435\n# ╠═d0a56572-3b2a-11eb-383a-f94fe2f45a5b\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "c4cd9a55bbe3847c7d5bee813769586fd7f3119c", "size": 1224, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/06/listing6.10.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/06/listing6.10.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/06/listing6.10.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.5, "max_line_length": 69, "alphanum_fraction": 0.7214052288, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.780482157832026}}
{"text": "\"\"\"\nIn both digital filter design and spectral estimation, the choice of a windowing\nfunction can play an important role in determining the quality of overall results.\nThe main role of the window is to damp out the effects of the Gibbs phenomenon that\nresults from truncation of an infinite series.\n\n# Available Window Functions\n\n    | Function       | Window Type                                    |\n    | -------------- | ---------------------------------------------- |\n    | barthann       | Modified Bartlett-Hann                         |\n    | bartlett       | Bartlett                                       |\n    | blackman       | Blackman                                       |\n    | blackmanharris | Minimum four-term Blackman-Harris              |\n    | bohman         | Bohman                                         |\n    | flattop        | Flat top weighted                              |\n    | hamming        | Hamming                                        |\n    | hanning        | Hann (Hanning)                                 |\n    | nuttall        | Nuttall-defined minimum 4-term Blackman-Harris |\n    | parzen         | Parzen (de la Vallée Poussin)                  |\n    | rectangular    | Rectangular                                    |\n    | triangular     | Triangular                                     |\n    | tukey          | Tukey (tapered cosine)                         |\n\n\"\"\"\nmodule WindowFunctions\n\nexport barthann\nexport bartlett\nexport blackman\nexport blackmanharris\nexport bohman\nexport flattop\nexport hamming\nexport hanning\nexport nuttall\nexport parzen\nexport rectangular\nexport triangular\n\n\n\"\"\"\n    barthann(N::Int) -> AbstractArray\n    Sidelobe peak attenuation = 35.9dB\nbarthann window has a mainlobe at the origin and asymptotically decaying\nsidelobes on both sides. It is a linear combination of weighted Bartlett\nand Hanning windows with near sidelobes lower than both Bartlett and Hanning\nand with far sidelobes lower than both Bartlett and Hamming windows. The\nmainlobe width of the modified Bartlett-Hann window is not increased relative\nto either Bartlett or Hann window mainlobes.\n\"\"\"\nfunction barthann(N::Int)\n    n = (0:N-1)/(N-1)\n    return @. 0.62 - 0.48*abs(n-0.5) + 0.38*cos(2*pi*n-pi)\nend\n\n\n\"\"\"\n    bartlett(N::Int) -> AbstractArray\n    Sidelobe peak attenuation = 26.5dB\nBartlett window is very similar to a triangular window as returned by the triang\nfunction. However, the Bartlett window always has zeros at the first and last samples,\nwhile the triangular window is nonzero at those points.\n\"\"\"\nfunction bartlett(L::Int)\n    L==1 && return [1.0]\n    N = L - 1\n    w = zeros(L)\n    for i = 1:L\n        n = i - 1\n        w[i] = 0<=n<=N/2 ? 2n/N : 2-2n/N\n    end\n    return w\nend\n\n\n\"\"\"\n    blackman(N::Int) -> AbstractArray\n    Sidelobe peak attenuation = 58.1dB\nIt is recommended to use blackman window to detect two\nsignals with similar frequency but different amplitude.\n\"\"\"\nfunction blackman(N::Int)\n    n = 2 * pi .* (0:(N-1))/(N-1)\n\treturn @. 0.42 - 0.5 * cos(n) + 0.08 * cos(2n)\nend\n\n\n\"\"\"\n    blackmanharris(N::Int) -> AbstractArray\n    Sidelobe peak attenuation = 92dB\nMinimum four-term Blackman-Harris window.\n\"\"\"\nfunction blackmanharris(N::Int)\n    n = 2 * pi .* (0:N-1)/(N-1)\n    a₀ = 0.35875\n    a₁ = 0.48829\n    a₂ = 0.14128\n    a₃ = 0.01168\n    return @. a₀ - a₁*cos(n) + a₂*cos(2n) - a₃*cos(3n)\nend\n\n\n\"\"\"\n    bohman(N::Int) -> AbstractArray\n    Sidelobe peak attenuation = 46dB\nBohman window is the convolution of two half-duration cosine lobes.\nIn the time domain, it is the product of a triangular window and a\nsingle cycle of a cosine with a term added to set the first derivative\nto zero at the boundary. Bohman windows fall off as 1/ω⁴\n\"\"\"\nfunction bohman(N::Int)\n    n = (0:N-1)/(N-1)\n    n = abs.((2n) .- 1)\n    return @. (1-n)*cos(pi*n) + 1/pi*sin(pi*n)\nend\n\n\n\"\"\"\n    flattop(N::Int) -> AbstractArray\n    Sidelobe peak attenuation = 93.6dB\nflat-top window is summations of cosines with very small passband fluctuations.\n\"\"\"\nfunction flattop(N::Int)\n    n = 2 * pi .* (0:N-1)/(N-1)\n    a₀ = 0.215578950\n    a₁ = 0.416631580\n    a₂ = 0.277263158\n    a₃ = 0.083578947\n    a₄ = 0.006947368\n    return @. a₀ - a₁*cos(n) + a₂*cos(2n) - a₃*cos(3n) + a₄*cos(4n)\nend\n\n\n\"\"\"\n    hamming(N::Int) -> AbstractArray\n    Sidelobe peak attenuation = 43.2dB\nSimilar to hanning but has lower Sidelobe.\n\"\"\"\nfunction hamming(N::Int)\n\treturn @. 0.54 - 0.46 * cos( 2*pi * (0:(N-1))/(N-1) )\nend\n\n\n\"\"\"\n    hanning(N::Int) -> AbstractArray\n    Sidelobe peak attenuation = 31.5dB\n\nIf the signal is random or unknown, or has multiple frequency components, and\nthe test focuses on frequency points rather than energy, it is recommended to\nselect hanning window.\n\"\"\"\nfunction hanning(N::Int)\n\treturn @. 0.5 - 0.5 * cos( 2*pi * (0:(N-1))/(N-1) )\nend\n\n\n\"\"\"\n    nuttall(N::Int) -> AbstractArray\n    Sidelobe peak attenuation = 93.8dB\nThe window is minimum in the sense that its maximum sidelobes are minimized.\nThe coefficients for this window differ from the Blackman-Harris window coefficients\ncomputed with blackmanharris and produce slightly lower sidelobes.\n\"\"\"\nfunction nuttall(N::Int)\n    n = 2 * pi .* (0:N-1)/(N-1)\n    a₀ = 0.3635819\n    a₁ = 0.4891775\n    a₂ = 0.1365995\n    a₃ = 0.0106411\n    return @. a₀ - a₁*cos(n) + a₂*cos(2n) - a₃*cos(3n)\nend\n\n\n\"\"\"\n    parzen(N::Int) -> AbstractArray\n    Sidelobe peak attenuation = 53.1dB\nParzen windows are piecewise-cubic approximations of Gaussian windows.\nParzen window sidelobes fall off as 1/ω⁴\n\"\"\"\nfunction parzen(N::Int)\n    w = zeros(N)\n    for i = 1:N\n        m = i - 1\n        n = abs(m - (N-1)/2)\n        w[i] = n<(N-1)/4 ? 1 - 6(2n/N)^2 + 6(2n/N)^3 : 2(1-2n/N)^3\n    end\n    return w\nend\n\n\n\"\"\"\n    rectangular(N::Int) -> AbstractArray\n    Sidelobe peak attenuation = 13.3dB\n\"\"\"\nfunction rectangular(N::Int)\n    return ones(N)\nend\n\n\n\"\"\"\n    triangular(N::Int) -> AbstractArray\n    Sidelobe peak attenuation = 26.5dB\nCompared with a rectangular window, the mainlobe is about twice wide, but the\nsidelobes are smaller and have no negative sidelobes.\n\"\"\"\nfunction triangular(N::Int)\n    N%2==0 && return triangulareven(N)\n    N%2==1 && return triangularodd(N)\nend\n\nfunction triangularodd(N::Int)\n    w = zeros(N)\n    for n = 1:N\n        w[n] = 1<=n<=(N+1)/2 ? 2n/(N+1) : 2-2n/(N+1)\n    end\n    return w\nend\n\nfunction triangulareven(N::Int)\n    w = zeros(N)\n    for n = 1:N\n        w[n] = 1<=n<=N/2 ? (2n-1)/N : 2-(2n-1)/N\n    end\n    return w\nend\n\n\nend # WindowFunctions\n", "meta": {"hexsha": "b0b3bb7392e90e9f1f897a0df7d4cd0393a1f955", "size": 6485, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/winfuns.jl", "max_stars_repo_name": "sonosole/AcousticFeatures.jl", "max_stars_repo_head_hexsha": "e9c55175df21dbec512a52a47e2a4f6811006ec7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-13T16:25:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-13T16:25:03.000Z", "max_issues_repo_path": "src/winfuns.jl", "max_issues_repo_name": "sonosole/AcousticFeatures.jl", "max_issues_repo_head_hexsha": "e9c55175df21dbec512a52a47e2a4f6811006ec7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/winfuns.jl", "max_forks_repo_name": "sonosole/AcousticFeatures.jl", "max_forks_repo_head_hexsha": "e9c55175df21dbec512a52a47e2a4f6811006ec7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1956521739, "max_line_length": 86, "alphanum_fraction": 0.6064764842, "num_tokens": 1955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7804821517486059}}
{"text": "using Random\nusing Distributions\n\"\"\"\n    vegas(f, st, en, kwargs...)\n\nVEGAS is a Monte Carlo algorithm for \nmultidimensional integration based on \nadaptive importance sampling. It divides\neach dimension into bins and adaptively adjusts\nbin widths so the points sampled from the\nregion where the function has highest magnitude. \n\nArguments:\n----------\n- st: Array of starting values in each dimension. \nDefaults to zeros(2)\n- end: Array of ending values in each dimension. \nDefaults to ones(2)\n\nKwargs:\n------\n- nbins: Number of bins in each dimension. \nDefaults to 100. \n- ncalls: Number of function calls per iteration. \nDefaults to 1000.\n- maxiter: Maximum number of iterations. \nDefaults to 100.\n- rtol: Relative tolerance required. \nDefaults to 1e-4.\n- atol: Absolute tolerance required. \nDefaults to 1e-2.\n- debug: Prints `abs(sd/I)` every 100 iterations. \nDefaults to false.\n- batch: Whether `f` returns batches of function\nevaluations. `f` is assumed to take one argument \n`pts`, an `ncalls × `ndims` matrix. Each row\nis a unique point and returns an `ncalls` length\nvector of function evals. This argument defaults\nto false. \n\nOutput:\n------\n- Estimate for the integral \n- Standard deviation\n- χ^2 / (numiter - 1): should be less than 1 \notherwise integral estimate should not be trusted. \n\nReferences:\n-----------\n- Lepage, G. Peter. \"A new algorithm for adaptive \nmultidimensional integration.\" Journal of \nComputational Physics 27.2 (1978): 192-203.\n\"\"\"\nfunction vegas(func, \n               a = [0.,0.], \n               b = [1.,1.];\n               maxiter = 100, \n               nbins = 100, \n               ncalls = 1000,\n               rtol = 1e-4, \n               atol = 1e-4,\n               debug = false, \n               batch = false)\n\n    N = nbins\n    M = ncalls\n\n    @assert length(a) == length(b)\n\n    ndim = length(a)\n\n    # Start out with uniform grid\n    grid = zeros(N, ndim)\n    for d = 1:ndim\n        grid[:,d] .= fill((b[d] - a[d])/N, N)\n    end\n    cgrid = cumsum(grid, dims = 1)\n\n    # Initialize all cumulative variables \n    # for integral and sd estimation \n    nevals = 0\n    Itot = 0.\n    sd = 0.\n    integrals = Float64[]\n    sigma_squares = Float64[]\n    iter = 1\n\n    while iter <= maxiter\n\n\n        # Sample `M` points from this grid\n        pts, bpts = generate_pts(grid, cgrid, M, a, b)\n        \n\n        # Estimate integral\n        S, S², fevals = evaluate_at_samples(func, \n                                            pts, \n                                            bpts,\n                                            M,\n                                            N, \n                                            grid, \n                                            batch\n                                           )\n\n\n        σ² = (S² - S^2) / (M - 1) + eps() # When σ² = 0\n        nevals += M\n        push!(integrals, S)\n        push!(sigma_squares, σ²)\n\n        # Estimate sub-increments distribution\n        m = calculate_m_dist(fevals, \n                             bpts, \n                             grid, \n                             ndim\n                            )\n\n        # Update grid to reflect sub-inc dist\n        update_grid!(grid, cgrid, N, M, m)\n\n        # Update grid and generate new points\n        cumsum!(cgrid, grid, dims=1)\n\n        oldItot = Itot\n        \n        # Calculate integral and s.d upto this point\n        Itot = sum((integrals.^3) ./ sigma_squares) / \n                sum((integrals.^2) ./ sigma_squares)\n\n\n        sd = Itot * sum((integrals.^2) ./ sigma_squares)^(-0.5)\n        \n        if debug\n            iter % 100 == 0 && println(\"Iteration $iter, abs(sd/Itot) = $(abs(sd/Itot))\")\n        end\n\n        if abs(sd/Itot) < rtol && abs(sd) < atol\n            println(\"Converged in $nevals evaluations\")\n            break\n        end\n\n        iter += 1\n        # M += Minc\n\n    end\n    χ² = sum(((integrals .- Itot).^2) ./ sigma_squares)\n    @show nevals\n\n\n    Itot, sd, χ²/(iter-1)\nend\n\nfunction evaluate_at_samples(f, pts, bpts, M, N, grid, batch)\n\n    S = 0.\n    S² = 0.\n    fevals = zeros(M)\n    dim = size(pts, 2)\n\n    # Get all fevals in one shot\n    if batch\n        fevals = f(pts)\n        @assert length(fevals) == M \n    end\n\n    for i = 1:M\n\n        if !batch\n\n            # Extract point\n            p = vec(pts[i,:])\n\n            # Eval function\n            fp = f(p)\n            fevals[i] = fp\n        else\n            fp = fevals[i]\n        end\n\n        # Get probability of that particular point\n        prob = 1.\n        for d = 1:dim\n            prob *= (1/(N*grid[bpts[i,d],d]))\n        end\n\n        S += (fp / prob)\n        S² += (fp / prob)^2\n\n    end\n\n    S/M, S²/M, fevals\nend\n\n\n\"\"\"\npts, bpts = generate_pts(grid, cumgrid, M)\n\nGenerate `M` points from `grid` which probabilities \ninversely proportional to grid spacings \n\"\"\"\nfunction generate_pts(grid, cgrid, M, a, b)\n\n    # Get bins and dimension\n    dim = size(cgrid, 2)\n    N = size(cgrid, 1)\n\n    # Each dimension needs M points\n    pts = zeros(M, dim)\n    bpts = zeros(Int, M, dim)\n\n    for d = 1:dim\n\n        # Remember which bins they come from \n        b = rand(1:N, M)\n\n        bpts[:,d] .= b\n\n        idx = 1\n        for (i,bin) in enumerate(b)\n            if bin == 1\n                pts[i,d] = a[d] + rand(Uniform(0, cgrid[1,d]))\n            else\n                st = cgrid[bin-1,d]\n                en = cgrid[bin,d]\n                if st == en\n                    continue\n                end\n                pts[i,d] = a[d] + rand(Uniform(cgrid[bin-1,d], cgrid[bin,d]))\n            end\n        end\n    end\n\n   pts, bpts\nend\n\nfunction calculate_m_dist(fevals, bpts, grid, dim)\n\n \n    M = size(bpts, 1) \n    N = size(grid, 1)\n    m = zeros(N, dim)\n    probs = zeros(size(grid)...)\n    for d = 1:dim\n        probs[:,d] .= (1 ./ grid[:,d]) ./ sum(1 ./ grid[:,d])\n    end\n    \n    for d = 1:dim \n        for i = 1:M\n            f̄ = sqrt(fevals[i]^2 / \n                                (\n                                 (prod(probs[bpts[i,d],:]) / \n                                 probs[bpts[i,d],d]\n                                ) \n                                )\n                    )\n            m[bpts[i,d], d] += f̄ * grid[bpts[i,d],d]\n        end\n        m[:,d] .+= sum(m[:,d])\n        m[:,d] .= m[:,d] ./ sum(m[:,d])\n    end\n    \n    m\nend\n\nfunction update_grid!(grid, cgrid, N, M, m)\n\n    dims = size(grid, 2)\n\n    for d = 1:dims\n        gridcol = grid[:,d]\n        mdim = m[:,d]\n\n        # Count zeros in m \n        z = iszero.(mdim)\n        c = sum(z)\n        pos = findall(z)\n\n        res = zeros(size(grid, 1))  \n        for i = 1:N\n            mdim[i] == 0 && continue\n            res[i] = gridcol[i] / mdim[i]\n        end\n\n        # Calculate optm as sum / # non-zero m's\n        optm = sum(mdim)/(N - c)\n\n        for i = 1:N\n\n            # If there are no m's, grid[i] = 0 \n            if res[i] == 0 \n                gridcol[i] = 0 \n                continue\n            end\n\n            dist  = extract_from_bins!(mdim, optm, grid, res)\n            gridcol[i] = dist\n\n        end\n        grid[:,d] .= gridcol\n    end    \n    \n    grid\nend\n\nfunction extract_from_bins!(m, optm, grid, res)\n\n    N = size(m, 1)\n    dist = 0.\n    collected = 0\n    for k = 1:N\n\n        # First, calculate how many required\n        required = optm - collected\n\n        (m[k] == 0) && continue\n\n        # If bin has what's required, take everything\n        if required <= m[k]\n            #res = grid[k] / morig[k]\n            dist += (res[k] * required)\n            m[k] -= required\n            collected += required\n        end\n\n        # Update requirements\n        required = optm - collected\n\n        # If more is required, take the entire bin\n        if required >= m[k]\n            #res = grid[k] / morig[k]\n            dist += (res[k] * m[k])\n            collected += m[k]\n            m[k] = 0\n        end\n\n        # If collected everything, exit\n        if collected >= optm\n            break\n        end\n    end\n\n    dist \nend\n", "meta": {"hexsha": "30407916243a922af5163be2e778d5593fd28141", "size": 8001, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vegas.jl", "max_stars_repo_name": "ranjanan/MonteCarloIntegration.jl", "max_stars_repo_head_hexsha": "2a9a1e34609f494fb0f265ca06260d2161650c41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-06-14T17:31:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T07:49:26.000Z", "max_issues_repo_path": "src/vegas.jl", "max_issues_repo_name": "ranjanan/MonteCarloIntegration.jl", "max_issues_repo_head_hexsha": "2a9a1e34609f494fb0f265ca06260d2161650c41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-10T12:32:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-16T17:38:51.000Z", "max_forks_repo_path": "src/vegas.jl", "max_forks_repo_name": "ranjanan/MonteCarloIntegration.jl", "max_forks_repo_head_hexsha": "2a9a1e34609f494fb0f265ca06260d2161650c41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-06-14T20:07:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T17:57:00.000Z", "avg_line_length": 23.2587209302, "max_line_length": 89, "alphanum_fraction": 0.4775653043, "num_tokens": 2189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798115, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7804821507153135}}
{"text": "# # Power Network Flexibility Design\n# Here we consider a stochastic flexibility design problem that is inspired\n# from an example problem in Pulsipher JL, Zavala VM. *A scalable stochastic\n# programming approach for the design of flexible systems*. Computers & Chemical\n# Engineering. 2019 Sep 2;128:69-76. See the paper \n# [here](https://doi.org/10.1016/j.compchemeng.2019.05.033).\n\n# ## Modeling and Solution\n\nusing InfiniteOpt, Clp, Distributions\n\n## Set the covariance matrix for the uncertain parameters\nθ_nom = [0.; 60.; 10.]\ncovar = [80. 0 0; 0 80. 0; 0 0 120.]\n\n## Set the dimensions\nn_z = 3; n_θ = 3; n_d = 3\n\n## Set the problem parameters\nc = ones(n_d) / sqrt(n_d)\nc_max = 5\nU = 10000\nnum_samples = 100 # more should be used (kept small for doc generation)\n\n## Initialize the model\nm = InfiniteModel(Clp.Optimizer)\nset_silent(m)\n\n## Set the uncertainty parameters\n@infinite_parameter(m, θ[i = 1:n_θ] ~ MvNormal(θ_nom, covar), \n                    num_supports = num_samples)\n\n## Initialize the variables\n@variable(m, 0 <= y <= 1, Infinite(θ))\n@variable(m, z[1:n_z], Infinite(θ))\n@variable(m, d[1:n_d] >= 0)\n\n## Set objective function\n@objective(m, Max, expect(1 - y, θ))\n\n## Set the line capacity constraints\n@constraint(m, f1, -z[1] - 35 - d[1] <= y * U)\n@constraint(m, f2, z[1] - 35 - d[1] <= y * U)\n@constraint(m, f3, -z[2] - 50 - d[2] <= y * U)\n@constraint(m, f4, z[1] - 50 - d[2] <= y * U)\n\n## Set the generator capacity constraints\n@constraint(m, f5, -z[3] <= y * U)\n@constraint(m, f6, z[3] - 100 - d[3] <= y * U)\n\n## Set the node balance constraints\n@constraint(m, h1, z[1] - θ[1] == 0)\n@constraint(m, h2, -z[1] -z[2] + z[3] - θ[2] == 0)\n@constraint(m, h3, z[2] - θ[3] == 0)\n\n## Enforce the minimum SF\n@constraint(m, max_cost, sum(c[i] * d[i] for i = 1:n_d) <= c_max)\n\n## Solve and and obtain results\noptimize!(m)\nif has_values(m)\n    opt_y = value(y)\n    opt_d = value.(d)\n    opt_obj = objective_value(m)\nend\n\n## Estimate the value of SF\nSF = 1 - sum(opt_y .>= 1e-8) / num_samples\n\n## Print the results\nprint(\"------------------RESULTS------------------\\n\")\nprint(\"Optimal Objective:     \", opt_obj, \"\\n\")\nprint(\"Optimal Cost:          \", sum(c[i] * opt_d[i] for i = 1:n_d), \"\\n\")\nprint(\"Maximum Cost:          \", c_max, \"\\n\")\nprint(\"Predicted SF:          \", 100 * SF, \"%\\n\")\nprint(\"Optimal Design Values: \", opt_d, \"\\n\\n\")\n\n# ### Maintenance Tests\n# These are here to ensure this example stays up to date. \nusing Test\n@test termination_status(m) == MOI.OPTIMAL\n@test opt_y isa Vector{<:Real}\n", "meta": {"hexsha": "c9a4eb4d38c661533660cff25f8af9963b7f105d", "size": 2514, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/Stochastic Optimization/flexible_design.jl", "max_stars_repo_name": "bdaves12/InfiniteOpt.jl", "max_stars_repo_head_hexsha": "85e170ac1c749d9e3e21b2f9c9db32ccf99cc5ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 128, "max_stars_repo_stars_event_min_datetime": "2020-03-03T07:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T18:27:13.000Z", "max_issues_repo_path": "docs/src/examples/Stochastic Optimization/flexible_design.jl", "max_issues_repo_name": "bdaves12/InfiniteOpt.jl", "max_issues_repo_head_hexsha": "85e170ac1c749d9e3e21b2f9c9db32ccf99cc5ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 204, "max_issues_repo_issues_event_min_datetime": "2019-10-02T17:04:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T14:27:11.000Z", "max_forks_repo_path": "docs/src/examples/Stochastic Optimization/flexible_design.jl", "max_forks_repo_name": "bdaves12/InfiniteOpt.jl", "max_forks_repo_head_hexsha": "85e170ac1c749d9e3e21b2f9c9db32ccf99cc5ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-09-04T00:05:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:49:35.000Z", "avg_line_length": 30.2891566265, "max_line_length": 80, "alphanum_fraction": 0.6312649165, "num_tokens": 848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.780482148764008}}
{"text": "\"\"\"\n    FBMKernel(; h::Real=0.5)\n\nFractional Brownian motion kernel with Hurst index `h`.\n\n# Definition\n\nFor inputs ``x, x' \\\\in \\\\mathbb{R}^d``, the fractional Brownian motion kernel with\n[Hurst index](https://en.wikipedia.org/wiki/Hurst_exponent#Generalized_exponent)\n``h \\\\in [0,1]`` is defined as\n```math\nk(x, x'; h) =  \\\\frac{\\\\|x\\\\|_2^{2h} + \\\\|x'\\\\|_2^{2h} - \\\\|x - x'\\\\|^{2h}}{2}.\n```\n\"\"\"\nstruct FBMKernel{T<:Real} <: Kernel\n    h::Vector{T}\n    function FBMKernel(h::Real)\n        @check_args(FBMKernel, h, zero(h) ≤ h ≤ one(h), \"h ∈ [0, 1]\")\n        return new{typeof(h)}([h])\n    end\nend\n\nFBMKernel(; h::Real=0.5) = FBMKernel(h)\n\n@functor FBMKernel\n\nfunction (κ::FBMKernel)(x::AbstractVector{<:Real}, y::AbstractVector{<:Real})\n    modX = sum(abs2, x)\n    modY = sum(abs2, y)\n    modXY = sqeuclidean(x, y)\n    h = first(κ.h)\n    return (modX^h + modY^h - modXY^h) / 2\nend\n\nfunction (κ::FBMKernel)(x::Real, y::Real)\n    return (abs2(x)^first(κ.h) + abs2(y)^first(κ.h) - abs2(x - y)^first(κ.h)) / 2\nend\n\nfunction Base.show(io::IO, κ::FBMKernel)\n    return print(io, \"Fractional Brownian Motion Kernel (h = \", first(κ.h), \")\")\nend\n\n_fbm(modX, modY, modXY, h) = (modX^h + modY^h - modXY^h) / 2\n\n_mod(x::AbstractVector{<:Real}) = abs2.(x)\n_mod(x::ColVecs) = vec(sum(abs2, x.X; dims=1))\n_mod(x::RowVecs) = vec(sum(abs2, x.X; dims=2))\n\nfunction kernelmatrix(κ::FBMKernel, x::AbstractVector)\n    modx = _mod(x)\n    modxx = pairwise(SqEuclidean(), x)\n    return _fbm.(modx, modx', modxx, κ.h)\nend\n\nfunction kernelmatrix!(K::AbstractMatrix, κ::FBMKernel, x::AbstractVector)\n    modx = _mod(x)\n    pairwise!(K, SqEuclidean(), x)\n    K .= _fbm.(modx, modx', K, κ.h)\n    return K\nend\n\nfunction kernelmatrix(κ::FBMKernel, x::AbstractVector, y::AbstractVector)\n    modxy = pairwise(SqEuclidean(), x, y)\n    return _fbm.(_mod(x), _mod(y)', modxy, κ.h)\nend\n\nfunction kernelmatrix!(\n    K::AbstractMatrix, κ::FBMKernel, x::AbstractVector, y::AbstractVector\n)\n    pairwise!(K, SqEuclidean(), x, y)\n    K .= _fbm.(_mod(x), _mod(y)', K, κ.h)\n    return K\nend\n\nfunction kernelmatrix_diag(κ::FBMKernel, x::AbstractVector)\n    modx = _mod(x)\n    modxx = colwise(SqEuclidean(), x)\n    return _fbm.(modx, modx, modxx, κ.h)\nend\n\nfunction kernelmatrix_diag(κ::FBMKernel, x::AbstractVector, y::AbstractVector)\n    modxy = colwise(SqEuclidean(), x, y)\n    return _fbm.(_mod(x), _mod(y), modxy, κ.h)\nend\n", "meta": {"hexsha": "3f4d88ca0b12693cd77b5a348df2199dc78dc806", "size": 2384, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basekernels/fbm.jl", "max_stars_repo_name": "bmharsha/KernelFunctions.jl", "max_stars_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basekernels/fbm.jl", "max_issues_repo_name": "bmharsha/KernelFunctions.jl", "max_issues_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-20T12:51:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:51:15.000Z", "max_forks_repo_path": "src/basekernels/fbm.jl", "max_forks_repo_name": "bmharsha/KernelFunctions.jl", "max_forks_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0470588235, "max_line_length": 83, "alphanum_fraction": 0.6291946309, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542284, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7804639564090555}}
{"text": "export\n    isperfectsquare,\n    factor, eulerphi,\n    divisorcount, divisorsigma,\n    isperfect, isdeficient, isabundant,\n    primefactors, factors,\n    least_number_with_d_divisors\n\nisperfectsquare(n::Integer) = n == isqrt(n)^2\n\nNemo.factor(n::Int128) = (factor ∘ big)(n)\nNemo.factor(n::T) where {T<:Integer} = factor(n, Dict{T, Int})\nNemo.factor(n::Integer, out::Type{O}) where {OP<:Integer, OK<:Integer, O<:Associative{OP, OK}} = begin\n    factorization = (factor ∘ fmpz)(n)\n    pairs = (convert(OP, p) => convert(OK, k) for (p, k) in factorization)\n    out(pairs)\nend\nNemo.factor(n::Integer, out::Type{Nemo.Fac}) = (factor ∘ fmpz)(n)\n\n##  Euler's Phi (or: totient) function\nNemo.eulerphi(n::T) where {T<:Integer} = convert(T, (eulerphi ∘ fmpz)(n))\nNemo.eulerphi(f::Associative{T, <:Integer}) where {T<:Integer} = begin\n    phi = one(T)\n    for (p, k) in f\n        phi *= p^(k-1) * (p - 1)\n    end\n    phi\nend\n\n# https://oeis.org/wiki/Divisor_function\ndivisorcount(n::T) where {T<:Integer} = convert(T, sigma(fmpz(n), 0))\ndivisorcount(f::Associative{T, <:Integer}) where {T<:Integer} = begin\n    c = one(T)\n    for k in values(f)\n        c *= k + 1\n    end\n    c\nend\n\ndivisorsigma(n::T, s = 1) where {T<:Integer} = convert(T, sigma(fmpz(n), s))\ndivisorsigma(f::Associative{T, <:Integer}, s = 1) where {T<:Integer} = begin\n    s >= 0 || error(\"Argument 's' must be an integer greater or equal 0\")\n    s == 0 && return divisorcount(f)\n\n    σ = one(T)\n    for (p, k) in f\n        σ *= (p^((k + 1) * s) - 1) ÷ (p^s - 1)\n    end\n    σ\nend\n\nisperfect(n::Integer) = divisorsigma(n, 1) - n == n\nisdeficient(n::Integer) = divisorsigma(n, 1) - n < n\nisabundant(n::Integer) = divisorsigma(n, 1) - n > n\n\nprimefactors(n::Integer) = (sort! ∘ collect ∘ keys ∘ factor)(n)\n\n# http://rosettacode.org/wiki/Factors_of_an_integer\nfactors(n::T, negative::Bool = false) where {T<:Integer} = begin\n    n > 0 || error(\"Argument 'n' must be an integer greater 0\")\n\n    f = [one(n)]\n    for (p, k) in factor(n)\n        f = reduce(vcat, f, [f * p^j for j in 1:k])::Array{T,1}\n    end\n\n    if length(f) == 1\n        f = [one(n), n]\n    else\n        sort!(f)\n    end\n\n    negative ? flatten([f -f]') : f\nend\n\nindexfactorization2number(x::Array{T,1}) where {T<:Integer} =\n    prod(big(nthprime(i))^k for (i, k) in enumerate(x))\n\n# http://www.primepuzzles.net/problems/prob_019.htm\nleast_number_with_d_divisors(d::Integer) =\n    minimum(indexfactorization2number(e) for e in least_number_with_d_divisors_exponents(d))\n\nleast_number_with_d_divisors_exponents(d::T, i::Int = 1, prevn::T = zero(T)) where {T<:Integer} = begin\n    d <= 1 && return Vector{T}[T[]]\n\n    f = factor(d, SortedDict{T, Int})\n    pmax = last(f)[1]\n    k = sum(values(f))\n\n    p = nthprime(k+i-1)\n    p_i = nthprime(i)\n    m = floor(Integer, log(p) / log(p_i))\n\n    c = [pmax]\n    for b in 2:m\n        !(b in keys(f)) && continue\n\n        for a in b:m\n            a*b <= pmax && continue\n            d % (a*b) != 0 && continue\n            first(primefactors(a)) < b && continue\n            i > 1 && a*b > prevn && continue\n\n            push!(c, a*b)\n        end\n    end\n\n    ans = Vector{T}[]\n    for ni in c\n        for tailn in least_number_with_d_divisors_exponents(d ÷ ni, i+1, ni)\n            push!(tailn, ni-1)\n            push!(ans, tailn)\n        end\n    end\n\n    i == 1 ? [reverse(x) for x in ans] : ans\nend\n", "meta": {"hexsha": "e670e76da59edb21361b01f97271c8e514066e73", "size": 3360, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Math/NumberTheory/factor.jl", "max_stars_repo_name": "Samayel/Brainstorm.jl", "max_stars_repo_head_hexsha": "9d83bb0a104973e498ba4ca84b0a27ede6c053ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-12-22T17:56:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T21:13:36.000Z", "max_issues_repo_path": "src/Math/NumberTheory/factor.jl", "max_issues_repo_name": "Samayel/Brainstorm.jl", "max_issues_repo_head_hexsha": "9d83bb0a104973e498ba4ca84b0a27ede6c053ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/NumberTheory/factor.jl", "max_forks_repo_name": "Samayel/Brainstorm.jl", "max_forks_repo_head_hexsha": "9d83bb0a104973e498ba4ca84b0a27ede6c053ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4745762712, "max_line_length": 103, "alphanum_fraction": 0.5860119048, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7804639521542738}}
{"text": "#############################################################################\n# relative_entropy.jl\n# relative entropy (ie, sum_i( x_i log (x_i/y_i) ) of expressions x and y\n# All expressions and atoms are subtypes of AbstractExpr.\n# Please read expressions.jl first.\n#############################################################################\n\nexport relative_entropy, log_perspective\nexport sign, curvature, monotonicity, evaluate\n\n# TODO: make this work for a *list* of inputs, rather than just for scalar/vector/matrix inputs\n\nstruct RelativeEntropyAtom <: AbstractExpr\n    head::Symbol\n    id_hash::UInt64\n    children::Tuple{AbstractExpr,AbstractExpr}\n    size::Tuple{Int, Int}\n\n    function RelativeEntropyAtom(x::AbstractExpr, y::AbstractExpr)\n        if sign(x) == ComplexSign() || sign(y) == ComplexSign()\n            error(\"Both the arguments should be real but these are instead $(sign(x)) and $(sign(y))\")\n        else\n            children = (x, y)\n            return new(:entropy, hash(children), children, size(x))\n        end\n    end\nend\n\nfunction sign(x::RelativeEntropyAtom)\n    return NoSign()\nend\n\nfunction monotonicity(x::RelativeEntropyAtom)\n    return (NoMonotonicity(),NoMonotonicity())\nend\n\nfunction curvature(x::RelativeEntropyAtom)\n    return ConvexVexity()\nend\n\nfunction evaluate(e::RelativeEntropyAtom)\n    x = evaluate(e.children[1])\n    y = evaluate(e.children[2])\n    if any(isnan, y) return Inf end\n\n    out = x.*log.(x./y)\n    # fix value when x=0:\n    # out will only be NaN if x=0, in which case the correct value is 0\n    out[isnan.(out)] = 0\n    return out\nend\n\nfunction conic_form!(e::RelativeEntropyAtom, unique_conic_forms::UniqueConicForms=UniqueConicForms())\n    if !has_conic_form(unique_conic_forms, e)\n        # transform to conic form:\n        # x log x/y <= z\n        # x log y/x >= -z\n        # log y/x >= -z/x\n        # y/x >= exp(-z/x)\n        # y >= x exp(-z/x)\n        # and cf the standard form for the exponential cone {(x,y,z): y*exp(x/y) <= z}\n        z = Variable(e.size)\n        x = e.children[1]\n        y = e.children[2]\n        objective = conic_form!(z, unique_conic_forms)\n        for i=1:size(x,1)\n            for j=1:size(x,2)\n                conic_form!(ExpConstraint(-z[i,j], x[i,j], y[i,j]), unique_conic_forms)\n            end\n        end\n        # need to constrain x>=0 and y>0.\n        # x>=0 we get for free from the form of the exponential cone, so just add\n        conic_form!(y>=0, unique_conic_forms) # nb we don't know how to ask for strict inequality\n        cache_conic_form!(unique_conic_forms, e, objective)\n    end\n    return get_conic_form(unique_conic_forms, e)\nend\n\nrelative_entropy(x::AbstractExpr, y::AbstractExpr) = sum(RelativeEntropyAtom(x, y))\n# y*log(x/y)\nlog_perspective(x::AbstractExpr, y::AbstractExpr) = -relative_entropy(y, x)\n", "meta": {"hexsha": "ae2e3b20cb92ca7d914505af55feee8b309ac253", "size": 2828, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/atoms/exp_cone/relative_entropy.jl", "max_stars_repo_name": "ranocha/Convex.jl", "max_stars_repo_head_hexsha": "ee58743611756e5cbb104682686031ab8d0feec4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-10-10T16:38:59.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-13T06:35:58.000Z", "max_issues_repo_path": "src/atoms/exp_cone/relative_entropy.jl", "max_issues_repo_name": "ranocha/Convex.jl", "max_issues_repo_head_hexsha": "ee58743611756e5cbb104682686031ab8d0feec4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/atoms/exp_cone/relative_entropy.jl", "max_forks_repo_name": "ranocha/Convex.jl", "max_forks_repo_head_hexsha": "ee58743611756e5cbb104682686031ab8d0feec4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-10-19T20:58:10.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-20T01:12:01.000Z", "avg_line_length": 34.487804878, "max_line_length": 102, "alphanum_fraction": 0.6159830269, "num_tokens": 737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248208414329, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7804639457174309}}
{"text": "struct Polytope{T<:Integer}\n    points::Matrix{Rational{T}}\n    rays::Matrix{T}\n    bidrays::Matrix{T}\nend\n\nfunction find_generators(A::Matrix{T}, b::Vector{T}) where T<:Rational\n    mat = [A b]\n    imat = intmat(mat)\n    Aint, bint = imat[:,1:end-1], imat[:,end]\n    find_generators(Aint, bint)\nend\n\n\"\"\"\n# Description\nFind generators for the polytope\n  P = { x : Ax ≥ b }\nthat is, calculate the following representation\n  P = { ∑ᵢ λᵢUᵢ + ∑ⱼ μⱼVⱼ + ∑ₖ νₖWₖ : ∑ᵢλᵢ = 1, μ ≥ 0 }\n\nThis is done through the use of the generalised Chernikova\nalgorithm on the cone homogenization of the above system.\n\n# Returns\n(points, rays, bidrays):\n  `points::Matrix{Rational{T}}`: matrix whose columns correspond extremal points of polytope\n  `rays::Matrix{T}`: matrix whose columns correspond to unidirectional rays of polytope\n  `bidrays::Matrix{T}`: matrix whose columns correspond to bidirectional rays of polytopes\n\"\"\"\nfunction find_generators(A::Matrix{T}, b::Vector{T}) where T<:Integer\n    # Create homogenized system\n    m, n = size(A)\n    Ab = [[A -b]; zeros(T, 1, n+1)]\n    Ab[m+1,n+1] = one(T)\n    bid, uni = chernikova_general(Ab)\n\n    n_bid = size(bid, 2)\n    n_uni = size(uni, 2)\n    \n    # Count number of trailing zeros (rays of polytope)\n    # Note that all bidirectional rays in homogenized system\n    # must have a trailing zero\n    # (due to positivity constraint on this coordinate)\n    n_zeros_uni = 0\n    for j in 1:n_uni\n        if uni[n+1,j] == 0 n_zeros_uni += 1 end\n    end\n\n    # If no unidirectional rays intersect with {x : x[n+1] == 0}\n    # then polytope is empty\n    if n_zeros_uni == n_uni\n        return Array{Rational{T}}(undef, n, 0), Array{T}(undef, n, 0), Array{T}(undef, n, 0)\n    end\n    \n    # Allocate matrices and get points.\n    # The vertices of the polytope correspond to the unidirectional rays with non-zero trailing coordinate\n    points = Array{Rational{T}}(undef, n, (n_uni - n_zeros_uni))\n    rays = Array{T}(undef, n, n_zeros_uni)\n    p_count = 1\n    r_count = 1\n    for j in 1:n_uni\n        if uni[n+1, j] != 0\n            points[:, p_count] = uni[1:n,j]//uni[n+1,j]\n            p_count+=1\n        else\n            rays[:,r_count] = uni[1:n,j]\n            r_count+=1\n        end\n    end\n\n    bidrays = bid[1:n,:]\n    return points, rays, bidrays\nend\n\n\"\"\"\n# Description\nCalculates the minimum and maximum values of\nthe projection of the polytope onto\nspecified vectors:\n\n  min_{x ∈ P} Tᵢx \n  max_{x ∈ P} Tᵢx\n\nwhere Tᵢ are the columns of a matrix T.\n# Arguments\n* `P::Polytope{I}`: Polytope to project\n* `T::Matrix{I}`: Matrix onto whose columns we project polytope\n# Returns\n`(mins::Array{Rational{T}}, maxs::Array{Rational{T}})`\n\"\"\"\nfunction min_max_projections(P::Polytope{S}, T::Matrix{Rational{S}} = Array{Rational{S}}(I, length(P), length(P))) where S<:Integer\n    n = size(T, 2)\n    n_points, n_rays, n_bidrays = size(P.points, 2), size(P.rays, 2), size(P.bidrays, 2)\n    mins, maxs = fill(typemax(Rational{S}), n), fill(typemin(Rational{S}), n)\n    for i in 1:n\n        for j in 1:n_points\n            tp = dot(T[:,i], P.points[:,j])\n            if tp < mins[i]\n                mins[i] = tp\n            end\n            if tp > maxs[i]\n                maxs[i] = tp\n            end\n        end\n        for j in 1:n_rays\n            tr = dot(T[:,i], P.rays[:,j])\n            if tr < 0\n                mins[i] = -Inf\n                break\n            elseif tr > 0\n                maxs[i] = Inf\n                break\n            end\n        end\n        for j in 1:n_bidrays\n            if dot(T[:,i], P.bidrays[:,j]) != 0\n                maxs[i] = Inf\n                mins[i] = -Inf\n                break\n            end\n        end\n    end\n    return mins, maxs\nend\n\nlength(P::Polytope{T} where T<:Integer) = size(P.points, 1)\n", "meta": {"hexsha": "ec386902746577c9c900609cff81ab8683d32928", "size": 3769, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polytope.jl", "max_stars_repo_name": "fairbrot/Cones.jl", "max_stars_repo_head_hexsha": "653c19c6553643a15a535e82d763901c2fe90356", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-11-07T23:52:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T17:21:29.000Z", "max_issues_repo_path": "src/polytope.jl", "max_issues_repo_name": "fairbrot/Cones.jl", "max_issues_repo_head_hexsha": "653c19c6553643a15a535e82d763901c2fe90356", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polytope.jl", "max_forks_repo_name": "fairbrot/Cones.jl", "max_forks_repo_head_hexsha": "653c19c6553643a15a535e82d763901c2fe90356", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6771653543, "max_line_length": 131, "alphanum_fraction": 0.5839745291, "num_tokens": 1213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7804329220239521}}
{"text": "using EconPDEs\n\nBase.@kwdef  struct CampbellCochraneModel\n    # consumption process parameters\n    μ::Float64 = 0.0189\n    σ::Float64 = 0.015\n    # utility\n    γ::Float64 = 2.0\n    ρ::Float64 = 0.116\n    # habit\n    κs::Float64 = 0.138\n    b::Float64 = 0.0\nend\n# I choose persistence so that monthly simulation of the model matches processes in CC (1999)\n# ρ = 12 * (1 - 0.89^(1/12))\n# κs = 12 * (1 - 0.87^(1/12))\n\nfunction initialize_stategrid(m::CampbellCochraneModel; sn = 1000)\n    μ = m.μ ; σ = m.σ ; γ = m.γ ; ρ = m.ρ ; κs = m.κs ; b = m.b\n    Sbar = σ * sqrt(γ / (κs - b / γ))\n    sbar = log.(Sbar)\n    smax =  sbar + 0.5 * (1 - Sbar^2)\n    # corresponds to Grid 3 in Wachter (2005)\n    shigh = log.(range(0.0, exp(smax), length = div(sn, 10)))\n    slow = range(-300.0, shigh[2], length = sn - div(sn, 10))\n    OrderedDict(:s => vcat(slow[1:(end-1)], shigh[2:end]))\nend\n\n\t\nfunction (m::CampbellCochraneModel)(state::NamedTuple, y::NamedTuple)\n    (; μ, σ, γ, ρ, κs, b) = m\n    (; s) = state\n    (; p, ps_up, ps_down, pss) = y\n    \n    # drift and volatility of  s and p\n    Sbar = σ * sqrt(γ / (κs - b / γ))\n    sbar = log(Sbar)\n    λ = 1 / Sbar * sqrt(1 - 2 * (s - sbar)) - 1\n    μs = - κs * (s - sbar)\n    ps = (μs >= 0) ? ps_up : ps_down\n    σs = λ * σ\n    σp = ps / p * σs\n    μp = ps / p * μs + 0.5 * pss / p * σs^2\n\n    # market price of risk κ\n    κ = γ * (σ + σs)\n\n    # risk free rate  r\n    r = ρ + γ * μ - (γ * κs - b) / 2 + b * (sbar - s)\n\n    # PDE\n    pt = - p * (1 / p + μ + μp + σp * σ - r - κ * (σ + σp))\n    return (; pt)\nend\n\n\n# Campbell Cochrane (1999)\nm = CampbellCochraneModel()\nstategrid = initialize_stategrid(m)\nyend = OrderedDict(:p => ones(length(stategrid[:s])))\nresult = pdesolve(m, stategrid, yend)\n@assert result.residual_norm <= 1e-5\n\n\n# Wachter (2005) calibration\n# m = CampbellCochraneModel(μ = 0.022, σ = 0.0086, γ = 2.0, ρ = 0.073, κs = 0.116, b = 0.011)\n# stategrid = initialize_stategrid(m)\n# yend = OrderedDict(:p => ones(length(stategrid[:s])))\n# y, result, distance = pdesolve(m, stategrid, yend)\n\n", "meta": {"hexsha": "ffe6f14770f2a6e2ba7fdcb546da7fc12fc0f3e0", "size": 2046, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/AssetPricing/CampbellCochrane.jl", "max_stars_repo_name": "matthieugomez/PDEModels.jl", "max_stars_repo_head_hexsha": "ecdefd0b1e52b2ec3bcebb9498d39057c26afd74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2016-10-06T20:37:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T16:25:39.000Z", "max_issues_repo_path": "examples/AssetPricing/CampbellCochrane.jl", "max_issues_repo_name": "matthieugomez/PDEModels.jl", "max_issues_repo_head_hexsha": "ecdefd0b1e52b2ec3bcebb9498d39057c26afd74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2018-04-27T17:24:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T01:42:28.000Z", "max_forks_repo_path": "examples/AssetPricing/CampbellCochrane.jl", "max_forks_repo_name": "matthieugomez/PDEModels.jl", "max_forks_repo_head_hexsha": "ecdefd0b1e52b2ec3bcebb9498d39057c26afd74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38, "max_forks_repo_forks_event_min_datetime": "2016-11-12T15:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:57:36.000Z", "avg_line_length": 28.8169014085, "max_line_length": 93, "alphanum_fraction": 0.5581622678, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7804329162562792}}
{"text": "module StatisticTools\n\nexport weightedmean\n\n\"\"\"\nweightedmean(values::Array{Float64,1}, errors::Array{Float64,1})\n\ncomputes the weighted mean of values, using as weights w = 1/ sigma^2\n\"\"\"\nfunction weightedmean(x::Array{Float64,1}, errors::Array{Float64,1}) \n    @assert length(x) == length(errors)\n    weights = 1./ (errors.^2)\n    sigma = sqrt( 1./ sum( weights ) )\n    mean = sigma^2 * sum(x .* weights)\n\n    mean, sigma\nend\n\nend # module\n", "meta": {"hexsha": "235dc44c2b624ebe71513fde4445a75f812bc40c", "size": 441, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/StatisticTools.jl", "max_stars_repo_name": "JohannesHelmes/StatisticTools.jl", "max_stars_repo_head_hexsha": "4cd3b4a83b70b79d77f6f9e6adf7e8a32b4a68f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/StatisticTools.jl", "max_issues_repo_name": "JohannesHelmes/StatisticTools.jl", "max_issues_repo_head_hexsha": "4cd3b4a83b70b79d77f6f9e6adf7e8a32b4a68f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/StatisticTools.jl", "max_forks_repo_name": "JohannesHelmes/StatisticTools.jl", "max_forks_repo_head_hexsha": "4cd3b4a83b70b79d77f6f9e6adf7e8a32b4a68f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.05, "max_line_length": 69, "alphanum_fraction": 0.6712018141, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966641739773, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7804329010809334}}
{"text": "module Epidemiology\n\nusing AlgebraicPetri\nusing Petri\nusing Catlab\nusing Catlab.Theories\n\nexport InfectiousDiseases, FunctorGenerators, F_epi, S, E, I, R, D, transmission, exposure, illness, recovery, death\n\nob = PetriCospanOb(1)\nspontaneous_petri = PetriCospan([1], Petri.Model(1:2, [(Dict(1=>1), Dict(2=>1))]), [2])\ntransmission_petri = PetriCospan([1], Petri.Model(1:2, [(Dict(1=>1, 2=>1), Dict(2=>2))]), [2])\nexposure_petri = PetriCospan([1, 2], Petri.Model(1:3, [(Dict(1=>1, 2=>1), Dict(3=>1, 2=>1))]), [3, 2])\n\n\"\"\" InfectiousDiseases\n\"\"\"\n@present InfectiousDiseases(FreeBiproductCategory) begin\n    S::Ob\n    E::Ob\n    I::Ob\n    R::Ob\n    D::Ob\n    transmission::Hom(S⊗I, I)\n    exposure::Hom(S⊗I, E⊗I)\n    illness::Hom(E,I)\n    recovery::Hom(I,R)\n    death::Hom(I,D)\nend\n\n\"\"\" generators\n\"\"\"\nS,E,I,R,D,transmission,exposure,illness,recovery,death = generators(InfectiousDiseases);\n\n\"\"\" FunctorGenerators\n\"\"\"\nconst FunctorGenerators = Dict(S=>ob, E=>ob, I=>ob, R=>ob, D=>ob,\n        transmission=>transmission_petri, exposure=>exposure_petri,\n        illness=>spontaneous_petri, recovery=>spontaneous_petri, death=>spontaneous_petri)\n\n\"\"\" F_epi\n\"\"\"\nF_epi(ex) = functor((PetriCospanOb, PetriCospan), ex, generators=FunctorGenerators)\n\nend", "meta": {"hexsha": "a8bb7bd0ece3416b5fac950a820c30e847e697ff", "size": 1242, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Epidemiology.jl", "max_stars_repo_name": "olynch/AlgebraicPetri.jl", "max_stars_repo_head_hexsha": "26de81cdac3ee3a4274c6779665a5b56019848d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Epidemiology.jl", "max_issues_repo_name": "olynch/AlgebraicPetri.jl", "max_issues_repo_head_hexsha": "26de81cdac3ee3a4274c6779665a5b56019848d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Epidemiology.jl", "max_forks_repo_name": "olynch/AlgebraicPetri.jl", "max_forks_repo_head_hexsha": "26de81cdac3ee3a4274c6779665a5b56019848d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2272727273, "max_line_length": 116, "alphanum_fraction": 0.6811594203, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488964, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7804263170876949}}
{"text": "function tvlqr(A, B, Q, R)\n    T = length(Q)\n\n    P = [zero(A[1]) for t = 1:T]\n    K = [zero(B[1]') for t = 1:T-1]\n    P[T] = Q[T]\n\n    for t = T-1:-1:1\n        K[t] = (R[t] + B[t]' * P[t+1] *  B[t]) \\ (B[t]' * P[t+1] * A[t])\n        P[t] = (Q[t] + K[t]' * R[t] * K[t]\n                + (A[t] - B[t] * K[t])' * P[t+1] * (A[t] - B[t] * K[t]))\n    end\n\n    return K, P\nend\n\nfunction reference_gains(s::Simulation, traj::ContactTraj, obj::TrackingVelocityObjective;\n\t\tN::Int=10, κ=2e-4, U_scaling=100, V_scaling=100)\n\n\tmodel = s.model\n\tH = traj.H\n\tz = [[deepcopy(traj.z) for i = 1:N]...;]\n\tθ = [[deepcopy(traj.θ) for i = 1:N]...;]\n\n\trz = [LinearizedStep(s, z[t], θ[t], κ).rz for t = 1:N*H]\n\trθ = [LinearizedStep(s, z[t], θ[t], κ).rθ for t = 1:N*H]\n\n\tidx_z = indices_z(s)\n\tidx_θ = indices_θ(model, nf=1)\n\n\t∂z∂θ = [-rz[t] \\ rθ[t] for t = 1:N*H]\n\n\t∂q2∂q1 = [zeros(model.nq, model.nq) for t = 1:N*H]\n\t∂q2∂q2 = [I(model.nq) for t = 1:N*H]\n\t∂q3∂q1 = [∂z∂θ[t][idx_z.q, idx_θ.q1] for t = 1:N*H]\n\t∂q3∂q2 = [∂z∂θ[t][idx_z.q, idx_θ.q2] for t = 1:N*H]\n\n\t∂q2∂u = [zeros(model.nq, model.nu) for t = 1:N*H]\n\t∂q3∂u = [∂z∂θ[t][idx_z.q, idx_θ.u] for t = 1:N*H]\n\n\tA = [[∂q2∂q1[t] ∂q2∂q2[t]; ∂q3∂q1[t] ∂q3∂q2[t]] for t = 1:N*H]\n\tB = [[∂q2∂u[t]; ∂q3∂u[t]] for t = 1:N*H]\n\tQ = [\n\t\t[obj.q[1]+V_scaling*obj.v[1]    -V_scaling*obj.v[1];\n\t\t -V_scaling*obj.v[1]    obj.q[1]+V_scaling*obj.v[1]\n\t\t ] for i = 1:N*H+1]\n\tR = [U_scaling * obj.u[1] for i = 1:N*H]\n\n\tK, P = tvlqr(A, B, Q, R)\n\treturn K[1:H]\nend\n", "meta": {"hexsha": "a4fe05daaeb947063243a87d054aea471eec7561", "size": 1473, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/controller/gains.jl", "max_stars_repo_name": "thowell/ContactImplicitMPC.jl", "max_stars_repo_head_hexsha": "6226c93521362b32235a53bc22e573a27f28fda8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2021-09-28T04:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T07:56:35.000Z", "max_issues_repo_path": "src/controller/gains.jl", "max_issues_repo_name": "thowell/ContactImplicitMPC.jl", "max_issues_repo_head_hexsha": "6226c93521362b32235a53bc22e573a27f28fda8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-09-28T04:23:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-11T22:44:59.000Z", "max_forks_repo_path": "src/controller/gains.jl", "max_forks_repo_name": "thowell/ContactImplicitMPC.jl", "max_forks_repo_head_hexsha": "6226c93521362b32235a53bc22e573a27f28fda8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-09-28T22:11:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T20:48:27.000Z", "avg_line_length": 28.3269230769, "max_line_length": 90, "alphanum_fraction": 0.4915139172, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7804263085649942}}
{"text": "module Geometry\nexport volume, surfacearea, lateralarea\n\nabstract type Solid end\n\n# *******************************************\nmutable struct Cone <: Solid\n    height::Float32\n    # one element implies start from one point\n    # two elements for truncated cone volume\n    radii::Array{Float32, 1}\n    function Cone(depth, diameters)\n        if length(diameters) > 2\n            error(\"Too many diameter arguments in list\")\n        end\n        if length(diameters) == 1\n            push!(diameters,0.0)\n        end\n        new(depth, diameters / 2)\n    end\nend\nmutable struct Cylinder <: Solid\n    height::Float32\n    radius::Float32\n    function Cylinder(depth, diameter)\n        new(depth, (diameter / 2.0))\n    end\nend\nstruct Cube <: Solid\n    side::Float32\nend\nstruct RectangularPrism <: Solid\n    height::Float32\n    width::Float32\n    depth::Float32\nend\n\n\n\nfunction volume(c::Solid)\n    tc = typeof(c)\n    if tc == Cone\n        rads = (c.radii[1]^2 + c.radii[1]*c.radii[2] + c.radii[2]^2)\n        return (1/3)*(pi*rads*c.height)\n    elseif tc == Cylinder\n        return (1/1)*(pi*(c.radius^2)*c.height)\n    elseif tc == Cube\n        return (1/1)*(c.side^3)\n    elseif tc == RectangularPrism\n        return (1/1) * (c.height * c.width * c.depth)\n    end\n    return nothing\nend\n\nfunction lateralarea(c::Solid)\n    tc = typeof(c)\n    if tc == Cone\n        return pi * (c.radii[1] + c.radii[2]) * (((c.radii[1] - c.radii[2])^2 + c.height^2)^(1/2))\n    elseif tc == Cylinder\n        return 2*pi*c.radius*c.height\n    elseif tc == Cube\n        return (1/1)*4*(c.side^2)\n    elseif tc == RectangularPrism\n        return (1/1) * (2 * (c.height * c.width) + 2 * (c.height * c.depth))\n    end\n    return nothing\nend\n    \nfunction surfacearea(c::Solid)\n    tc = typeof(c)\n    if tc == Cone\n        return lateralarea(c) + pi * (c.radii[1]^2 + c.radii[2]^2)\n    elseif tc == Cylinder\n        return lateralarea(c) + 2*pi*(c.radius^2)    \n    elseif tc == Cube\n        return (1/1)*6*(c.side^2)    \n    elseif tc == RectangularPrism\n        return lateralarea(c) + (1/1) * (2 * (c.width * c.depth))    \n    end\n    return nothing\n    \nend\n\nend", "meta": {"hexsha": "dd0100f60f4a8519ef6b1488465c0668d8bb8dfa", "size": 2136, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Geometry.jl", "max_stars_repo_name": "bassoman/Geometry.jl", "max_stars_repo_head_hexsha": "524a7f68686e585b270fd9f2308a2bc74d847a82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Geometry.jl", "max_issues_repo_name": "bassoman/Geometry.jl", "max_issues_repo_head_hexsha": "524a7f68686e585b270fd9f2308a2bc74d847a82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Geometry.jl", "max_forks_repo_name": "bassoman/Geometry.jl", "max_forks_repo_head_hexsha": "524a7f68686e585b270fd9f2308a2bc74d847a82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4285714286, "max_line_length": 98, "alphanum_fraction": 0.5725655431, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778036723353, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.780403966889213}}
{"text": "using FFTW\nusing Plots\n\ninclude(\"naiveDFT.jl\")\ninclude(\"simpleDFT.jl\")\ninclude(\"benchmarkFunction.jl\")\n\nfunction main()\n    #\n    # Create test set\n    #\n    N = 2^8 # 2^8=256\n    tmax = 30.0\n    Δ = tmax / N\n\n    t = collect(range(0.0, tmax, length = N))\n    ω = collect(range(0, stop = N - 1))\n    hk = sin.(t) .+ 0.5 .* sin.(5.0 .* t .+ 1.0) .+ sin.(4.0 .* t .- 1.5)\n\n\n    #\n    # Calculations\n    #\n    resNaive = naiveDFT(hk)                 #naive approach\n    resNaiveIter = naiveDFTIterative(hk)    #naive approach iterative\n    resSimple = simpleDFT(hk)               #simple recursive dft\n    resFFTW = fft(hk)                       #fftw\n    resRealFFTW = rfft(hk)                  #real fftw\n\n    \n    println(sum(abs.(resFFTW .- resNaive))) #differences to naive<->fftw\n    println(sum(abs.(resFFTW .- resNaiveIter))) #differences to naive<->fftw\n    println(sum(abs.(resFFTW .- resSimple))) #differences to simple<->fftw\n\n    \n    #\n    # Benchmarking\n    #\n    benchmarkDFTFunction(fft, 1.0, 5, \"FFTW.csv\")\n    benchmarkDFTFunction(simpleDFT, 1.0, 5, \"simpleDFT.csv\")\n    benchmarkDFTFunction(naiveDFT, 1.0, 5, \"naiveDFT.csv\")\n    benchmarkDFTFunction(naiveDFTIterative, 1.0, 5, \"naiveDFTIter.csv\")\n\n    #\n    # plotting\n    #\n    gr()\n    p1re = plot(ω, real.(resFFTW), title = \"FFTW Real\", label = \"\");\n    p1im = plot(ω, imag.(resFFTW), title = \"FFTW Imag\", label = \"\");\n    p1abs = plot(ω, abs.(resFFTW) .^ 2 , title = \"FFTW Abs^2\", label = \"\");\n\n    p2re = plot(ω, real.(resNaive), title = \"Naive Real\", label = \"\");\n    p2im = plot(ω, imag.(resNaive), title = \"Naive Imag\", label = \"\");\n    p2abs = plot(ω, abs.(resNaive) .^ 2 , title = \"Naive Abs^2\", label = \"\");\n\n    p3re = plot(ω, real.(resSimple), title = \"Simple Real\", label = \"\");\n    p3im = plot(ω, imag.(resSimple), title = \"Simple Imag\", label = \"\");\n    p3abs = plot(ω, abs.(resSimple) .^ 2 , title = \"Simple Abs^2\", label = \"\");\n\n    p = plot(p1re, p1im, p1abs, p2re, p2im, p2abs, p3re, p3im, p3abs, layout = (3, 3), size = (1024, 800))\n    savefig(p, \"fftPlot.png\")\n\nend\n\nmain()\n", "meta": {"hexsha": "a9fdf512bef0ad68437220caaa7e837d607391d8", "size": 2064, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Excercise_01/A2/A2.jl", "max_stars_repo_name": "JulienKluge/ComputationalPhotonics", "max_stars_repo_head_hexsha": "78bfdccc49dca5b19e524814c0ca3fcff7be6765", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Excercise_01/A2/A2.jl", "max_issues_repo_name": "JulienKluge/ComputationalPhotonics", "max_issues_repo_head_hexsha": "78bfdccc49dca5b19e524814c0ca3fcff7be6765", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Excercise_01/A2/A2.jl", "max_forks_repo_name": "JulienKluge/ComputationalPhotonics", "max_forks_repo_head_hexsha": "78bfdccc49dca5b19e524814c0ca3fcff7be6765", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2727272727, "max_line_length": 106, "alphanum_fraction": 0.5687984496, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778061099871, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7804039645791707}}
{"text": "\"\"\"\n```\ntransition(m::PoolModel{T}) where {T<:AbstractFloat}\n```\n\nAssign transition equation\n\n```\nx_t = (1-ρ) μ + ρ x_{t-1} + sqrt{1 - ρ^2} σ ϵ_t\nϵ_t ∼ iid N(0,1), x_0 ∼ N(μ,σ^2)\nλ_t = Φ(x_t)\n```\nwhere Φ(⋅) is the cdf of a N(0,1) random variable, F_ϵ is the distribution of ϵ_t,\nand F_λ is the distribution of λ(x_0).\n\"\"\"\nfunction transition(m::PoolModel{T}) where {T<:AbstractFloat}\n    @inline Φ(x::Vector{Float64}, ϵ::Vector{Float64}) = abs.([0;1] .-\n                                                             (cdf.(Normal(), (1 - m[:ρ].value) .*\n                                                                   m[:μ].value .+ m[:ρ].value .*\n                                                                   quantile(Normal(),x[1]) .+\n                                                                   sqrt(1 - m[:ρ].value^2) .*\n                                                                   m[:σ].value .* ϵ)))\n    F_ϵ = Normal(0.,1.)\n    F_λ = Uniform(0.,1.)\n    return Φ, F_ϵ, F_λ\nend\n", "meta": {"hexsha": "ccb3cd0dbc12e40e645186d72ff676dc06ef1a73", "size": 1000, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/poolmodel/transition.jl", "max_stars_repo_name": "UnofficialJuliaMirror/DSGE.jl-6cf23378-2c47-544c-b0c3-6efefe57ca11", "max_stars_repo_head_hexsha": "21dab967580fc92ec18bf2d219eaeaa88bebc5d1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 822, "max_stars_repo_stars_event_min_datetime": "2015-12-03T13:42:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T16:12:55.000Z", "max_issues_repo_path": "src/models/poolmodel/transition.jl", "max_issues_repo_name": "UnofficialJuliaMirror/DSGE.jl-6cf23378-2c47-544c-b0c3-6efefe57ca11", "max_issues_repo_head_hexsha": "21dab967580fc92ec18bf2d219eaeaa88bebc5d1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2016-06-20T14:42:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T16:14:10.000Z", "max_forks_repo_path": "src/models/poolmodel/transition.jl", "max_forks_repo_name": "UnofficialJuliaMirror/DSGE.jl-6cf23378-2c47-544c-b0c3-6efefe57ca11", "max_forks_repo_head_hexsha": "21dab967580fc92ec18bf2d219eaeaa88bebc5d1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 226, "max_forks_repo_forks_event_min_datetime": "2015-12-03T16:53:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T09:52:56.000Z", "avg_line_length": 37.037037037, "max_line_length": 97, "alphanum_fraction": 0.392, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778048911612, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7804039635855442}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.5\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 0507f8ed-8b64-48af-a6c4-ff7c4211b9e9\nbegin\n\tusing Pkg\n\tPkg.activate(\".\")\nend\n\n# ╔═╡ 3310d2f7-450a-4cd1-9c3a-46d02d23a7c6\nusing Revise\n\n# ╔═╡ d27b2d72-d264-11eb-0be5-13dcacfd2adc\nusing DeconvOptim, TestImages, ImageShow, Plots, LinearAlgebra, IndexFunArrays, Noise, FourierTools, SpecialFunctions, FFTW, LaTeXStrings, PlutoUI, Images, Tullio\n\n# ╔═╡ 952b251c-207b-4412-b6e1-268fce1647d9\nbegin\n\timg = Float32.(testimage(\"fabio_gray\"));\n\timg_1D = img[:, 200]\nend;\n\n# ╔═╡ fa8cd9c9-a2fd-495c-8d22-ada7bb9c39f6\notf(x, Δx=1) = begin\n\tx = abs(x)\n\tif x <= Δx \n\t\tSpecialFunctions.jinc(x * Δx *(1-x/Δx)) .* 2 / π * (acos(x/Δx) - x/Δx * sqrt(1-(x/Δx)^2))\n\telse\n\t\tzero(x)\n\tend\nend\n\n# ╔═╡ 9a07bc88-be76-4531-bc91-df0d20c3221c\nbegin\n\tx = range(-1.5, 1.5, length=size(img, 1))\n\tfreqs = fftshift(fftfreq(size(img_1D, 1), 1))\n\tpsf = Float32.(DeconvOptim.generate_psf(size(img), 20))\n\tpsf_1D = psf[1, :]\n\tpsf_1D ./= sum(psf_1D)\n\totf_1D = abs.(ffts(psf_1D))\nend;\n\n# ╔═╡ 24fc86da-0b7c-493c-8977-2a19ef6dc133\nimg_n = Float32.(poisson(DeconvOptim.conv(img, psf), 1000));\n\n# ╔═╡ 3bda922d-552b-42ec-9055-33a141b5841a\nblur(x, otf=otf_1D) = iffts(ffts(x) .* otf)\n\n# ╔═╡ 308e2562-5a20-4082-8a6d-9fb135738c49\nmd\"\nMathematically:\n\n$(S * \\text{PSF})(\\mathbf r) = \\int_{-\\infty}^{\\infty} S(\\mathbf r - \\mathbf x) \\cdot \\text{PSF}(\\mathbf x) \\, \\mathrm d \\mathbf x$\n\"\n\n# ╔═╡ b542187a-3ae7-4430-a81d-f968d9000427\nimg_blurry = DeconvOptim.conv(img, psf);\n\n# ╔═╡ 88d83629-f1b2-4d69-928f-d4acfbc76b70\nreg_1D = TV(num_dims=1);\n\n# ╔═╡ d6d0f436-48fd-4e8a-863c-3e9d3850cc91\nbegin\n\treg_tik = Tikhonov()\n\treg_TV = TV()\n\treg_GR = DeconvOptim.GR()\nend\n\n# ╔═╡ 061faf49-662c-4508-83b4-ddcf0970ed0d\nmd\"### DeconvOptim.jl: Microscopy Image Deconvolution\n\"\n\n# ╔═╡ 23829201-9756-4ef8-90c9-3917b761fe4b\nload(\"../docs/src/assets/logo.png\")\n\n# ╔═╡ 30f21bb8-6d09-4fce-9d2a-568bfaf3ff7a\nmd\"\n* **Felix Wechsler:** Master Student at the Leibniz Institute of Photonic Technology in  Jena, Germany\n* https://github.com/roflmaostc/DeconvOptim.jl\n* `]add DeconvOptim`\n\"\n\n# ╔═╡ 7a0a44c9-fb07-44e6-9a8b-8f720b84e6f6\nmd\"\"\"### Image Convolution\n\n* Typical description of isotropic blur of an image\n* The blurring kernel describes blur\n    * In optics/microscopy a finite sized dot called Point Spread Function (**PSF**)\n    * often a Gaussian function used in image processing\n    * cigarre shaped object for motion blur\n\n\nDiscrete version:\n\n$(S * \\text{PSF})[i] = \\sum_{m} S[i-m] \\cdot \\text{PSF}[m]$\n\"\"\"\n\n# ╔═╡ 49686d9a-1683-428f-83ba-a9131c2ad432\n[Gray.(img) Gray.(DeconvOptim.conv(img, psf))]\n\n# ╔═╡ 491ec7cb-1663-4acf-b81f-9acafba2b63d\nmd\"## Convolution Theorem\n\n$(S * \\text{PSF})(\\mathbf r) = \\mathcal{F}^{-1}\\bigg[ \\mathcal{F}[S] \\cdot \\mathcal{F}[\\text{PSF}]  \\bigg]$\n\n* we can express the convolution with a Fast Fourier Transform (FFT) which only takes $\\mathcal O(N \\log(N))$ operations\n\n\n* For large kernels (especially in 3D), sliding kernels are slower\n\n\n*  $\\mathcal{F}[\\text{PSF}]$ is called the $\\text{OTF}$\n\n\"\n\n# ╔═╡ b6f9e42e-5a23-40ad-9e73-8f02da48f69c\nmd\"### Optical System act as low pass filter\n\n*  $\\text{OTF}$ shows the frequency throughput\n\n\"\n\n# ╔═╡ e31f4704-5bce-4c8d-b3a7-873a3460d9f8\nplot(x, otf.(x), xlabel=\"frequency / maximum frequency\", ylabel=\"contrast\")\n\n# ╔═╡ dc8cf4e2-a87c-47ea-8247-3ae772852241\nmd\"## Frequency spectrum of blurred sample $Y(\\mathbf r)$\n\nBlurred sample:\n$Y(\\mathbf r) = (S * \\text{PSF})(\\mathbf r)$\n\"\n\n# ╔═╡ f8033d13-faee-41f5-bdd6-ae8721e8b8a8\nbegin\n\tplot(freqs, abs.(ffts(img_blurry)[:, 128]), yaxis=:log, ylabel=\"real part of FFT output in AU\", xlabel=\"frequency in 1/px\", ylims=(1e-4, 1e2), label=\"blurred\")\n\tplot!(freqs, abs.(ffts(img)[:, 128]), ylabel=\"abs of FFT output in AU\", \n\t\t\t\txlabel=\"frequency in 1/px\", yaxis=:log,\n\t\t\t\tylims=(1e-4, 1e4), label=\"ground truth\")\n\t#plot!(freqs, abs.(ffts(DeconvOptim.conv(img_1D, psf_1D))))\nend\n\n# ╔═╡ fe7e0292-31f6-43b5-83a5-a38698a87563\nmd\"## Deconvolution Pipeline\n\n* based on:\n    * Zygote.jl\n    * Optim.jl\n    * Tullio.jl\n    * CUDA.jl\n\"\n\n# ╔═╡ e9ef5ba4-56c0-4595-bc28-e04882f44a9a\nload(\"../docs/src/assets/tex/pipeline.png\")\n\n# ╔═╡ 90e5708c-05a4-46e4-b1e4-9a61c96dae32\nTV_by_hand(x) = @tullio r = sqrt(1f-8 + abs2(x[i, j] - x[i+1, j]) + \n\t\t\t\t\t\t \t     abs2(x[i, j] - x[i, j+1]))\n\n# ╔═╡ 03139ac5-3525-4fad-abf1-84421492b763\nDeconvOptim.generate_TV(4, [1,2, 3], [1,1, 1], 1, 0)[1]\n\n# ╔═╡ 4e84e739-9c59-4939-8b04-aec7dc069d67\nmd\"\n### Deconvolve with DeconvOptim.jl\n\n\"\n\n# ╔═╡ 9d9a5da2-14df-46e6-b7e6-5a33aade1754\n@bind reg_list2 Select([\"1\" => (\"Tikhonov\"), \"2\" => (\"Total Variation TV\"), \"3\" => (\"Good's Roughness GR\")])\n\n# ╔═╡ 5ae1a6a3-4505-4123-9f1e-8a1d4ac0b4e1\nreg = [reg_tik, reg_TV, reg_GR][parse(Int, reg_list2)]\n\n# ╔═╡ 15d54e5e-64f4-4a1d-8cc8-9334b2e3784f\nmd\"\niterations = \n$(@bind iter Slider(0:50, show_value=true))\n\nλ = $(@bind λ Slider(0:0.001:0.3, show_value=true))\n\nregularizer = $(@bind reg_bool CheckBox())\"\n\n# ╔═╡ 803368e6-53fd-4413-b3f5-ffe46ee8983e\nimg_deconv, res_img = deconvolution(img_blurry, psf, regularizer=reg_bool ? reg : nothing, iterations=iter, λ=λ);\n\n# ╔═╡ e58e1f63-2c81-48fb-866a-4bb70bd428a6\nGray.(img_deconv)\n\n# ╔═╡ 438a6639-bd35-464f-a81d-d98eb65e006e\nres_1D, o = deconvolution(real(blur(img_1D)), psf_1D, iterations=iter, regularizer=reg_1D, λ=0.01);\n\n# ╔═╡ 7a16df73-95ad-47f5-907c-6fd23c6000cf\n[Gray.(img) Gray.(img_blurry) Gray.(img_deconv)]\n\n# ╔═╡ 5c8030b7-8805-4771-9329-23abb2744544\nbegin\n\tplot(freqs, abs.(ffts(img_blurry)[:, 128]), yaxis=:log, ylabel=\"abs of FFT output in AU\", xlabel=\"frequency in 1/px\", ylims=(1e-4, 1e2), label=\"blurred\")\n\tplot!(freqs, abs.(ffts(img)[:, 128]),  yaxis=:log,\n\t\t\t\tylims=(1e-4, 1e4), label=\"ground truth\")\n\tplot!(freqs, abs.(ffts(img_deconv)[:, 128]), label=\"deconvolved image\")\nend\n\n# ╔═╡ ff9af79c-f06c-42ac-9c8d-6f09d2ff4056\n[Gray.(img_1D); Gray.(res_1D)];\n\n# ╔═╡ d8aee845-e922-41da-a17e-37ffa3e692f0\nmd\"### Real Microscopy Data\"\n\n# ╔═╡ fc93fa3d-8599-463b-b9e6-8043b90e9d63\nload(\"figures/real_data_large.png\")\n\n# ╔═╡ 97c45bfd-d1ef-49ad-908d-7360c03b0170\nmd\"Image taken from [DeconvolutionLab2](http://bigwww.epfl.ch/deconvolution/deconvolutionlab2/).\"\n\n# ╔═╡ bf37664a-f726-46b6-9592-da419165af91\nmd\"## Conclusion - DeconvOptim.jl\n\"\n\n# ╔═╡ f8117250-bac8-43a1-aae4-5c8bab3a522d\n[Gray.(ones(130, 012)) load(\"../docs/src/assets/logo.png\")]\n\n# ╔═╡ b5a70276-e9b9-46e8-8c67-0cad2cfa19da\nmd\"* Flexible Image Deconvolution Software\n* N-dimensional signal deconvolution\n* Works both on CPU and GPUs\n    * GPUs usually 5-15x speed improvement\n\"\n\n# ╔═╡ Cell order:\n# ╠═3310d2f7-450a-4cd1-9c3a-46d02d23a7c6\n# ╠═0507f8ed-8b64-48af-a6c4-ff7c4211b9e9\n# ╠═d27b2d72-d264-11eb-0be5-13dcacfd2adc\n# ╠═952b251c-207b-4412-b6e1-268fce1647d9\n# ╠═24fc86da-0b7c-493c-8977-2a19ef6dc133\n# ╠═3bda922d-552b-42ec-9055-33a141b5841a\n# ╟─fa8cd9c9-a2fd-495c-8d22-ada7bb9c39f6\n# ╠═9a07bc88-be76-4531-bc91-df0d20c3221c\n# ╟─308e2562-5a20-4082-8a6d-9fb135738c49\n# ╠═b542187a-3ae7-4430-a81d-f968d9000427\n# ╠═88d83629-f1b2-4d69-928f-d4acfbc76b70\n# ╠═e58e1f63-2c81-48fb-866a-4bb70bd428a6\n# ╠═d6d0f436-48fd-4e8a-863c-3e9d3850cc91\n# ╠═803368e6-53fd-4413-b3f5-ffe46ee8983e\n# ╠═5ae1a6a3-4505-4123-9f1e-8a1d4ac0b4e1\n# ╠═438a6639-bd35-464f-a81d-d98eb65e006e\n# ╟─061faf49-662c-4508-83b4-ddcf0970ed0d\n# ╟─23829201-9756-4ef8-90c9-3917b761fe4b\n# ╟─30f21bb8-6d09-4fce-9d2a-568bfaf3ff7a\n# ╟─7a0a44c9-fb07-44e6-9a8b-8f720b84e6f6\n# ╟─49686d9a-1683-428f-83ba-a9131c2ad432\n# ╟─491ec7cb-1663-4acf-b81f-9acafba2b63d\n# ╟─b6f9e42e-5a23-40ad-9e73-8f02da48f69c\n# ╟─e31f4704-5bce-4c8d-b3a7-873a3460d9f8\n# ╟─dc8cf4e2-a87c-47ea-8247-3ae772852241\n# ╟─f8033d13-faee-41f5-bdd6-ae8721e8b8a8\n# ╟─fe7e0292-31f6-43b5-83a5-a38698a87563\n# ╟─e9ef5ba4-56c0-4595-bc28-e04882f44a9a\n# ╠═90e5708c-05a4-46e4-b1e4-9a61c96dae32\n# ╠═03139ac5-3525-4fad-abf1-84421492b763\n# ╟─4e84e739-9c59-4939-8b04-aec7dc069d67\n# ╟─9d9a5da2-14df-46e6-b7e6-5a33aade1754\n# ╟─15d54e5e-64f4-4a1d-8cc8-9334b2e3784f\n# ╟─7a16df73-95ad-47f5-907c-6fd23c6000cf\n# ╟─5c8030b7-8805-4771-9329-23abb2744544\n# ╟─ff9af79c-f06c-42ac-9c8d-6f09d2ff4056\n# ╟─d8aee845-e922-41da-a17e-37ffa3e692f0\n# ╟─fc93fa3d-8599-463b-b9e6-8043b90e9d63\n# ╟─97c45bfd-d1ef-49ad-908d-7360c03b0170\n# ╟─bf37664a-f726-46b6-9592-da419165af91\n# ╟─f8117250-bac8-43a1-aae4-5c8bab3a522d\n# ╟─b5a70276-e9b9-46e8-8c67-0cad2cfa19da\n", "meta": {"hexsha": "85749f25aeb71a5f84c3e4c68ba9ef6edbc68190", "size": 8646, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/juliacon_2021.jl", "max_stars_repo_name": "RainerHeintzmann/DeconvOptim.jl", "max_stars_repo_head_hexsha": "21f212f919d1b36d011162a6af6f933671d30f45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2020-11-03T22:04:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:31:01.000Z", "max_issues_repo_path": "examples/juliacon_2021.jl", "max_issues_repo_name": "RainerHeintzmann/DeconvOptim.jl", "max_issues_repo_head_hexsha": "21f212f919d1b36d011162a6af6f933671d30f45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2020-11-05T07:46:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T10:57:53.000Z", "max_forks_repo_path": "examples/juliacon_2021.jl", "max_forks_repo_name": "RainerHeintzmann/DeconvOptim.jl", "max_forks_repo_head_hexsha": "21f212f919d1b36d011162a6af6f933671d30f45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-01-27T10:55:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T15:53:15.000Z", "avg_line_length": 30.5512367491, "max_line_length": 195, "alphanum_fraction": 0.7066851723, "num_tokens": 4270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.8652240947405565, "lm_q1q2_score": 0.7803634963160695}}
{"text": "function simsys(sys,nt,seed)\n\t###\n\t# simulated systems\n\t###\n\t\n\t# random seed for the simulations\n\tsrand(seed)\n    \n\tif sys==1\n\t\t#\n\t\t# system 1\n\t\n\t\t# ref: \"Subspace Identification for Linear Systems\"\n\t\t# P. Van Overschee and B. De Moor, page 81\n\t\t#\n\t\tA = [0.6 0.6 0.;-0.6 0.6 0.;0. 0. 0.4]\n\t\tK = [0.1706 -0.1507 0.2772]'\n\t\tC = [0.7831 0.5351 0.9701]\n\t\tR = 6.3663\n\t\tQ = K * R * K'\n        \n\t\tet = sqrt(R)*randn(1,nt)\n\t\tw = K*et\n        \n\t\tns = 3\n \t\tx = zeros(ns,nt)\n\t\tx[:,1] = w[:,1]\n\t\tfor t in 1:nt-1\n\t\t\tx[:,t+1] = A * x[:,t] + w[:,t]\n\t\tend\n\t\ty = C * x + et\n        \n\t\tsalida = y, A, K, C, Q, R\n\t\t#\n\telseif sys==2\n\t\t###\n\t\t# ref: \"Subspace Identification for Linear Systems\"\n\t\t# P. Van Overschee and B. De Moor, page 115\n\t\t###\n\t\tA = [0.6 0.6 0.;-0.6 0.6 0.;0. 0. 0.7]\n\t\tB = [1.6161 -0.3481 2.6319]'\n\t\tK = [-1.1472 -1.5204 -3.1993]'\n\t\tC = [-0.4373 -0.5046 -0.0936]\n\t\tD = -0.7759\n\t\tR = 0.0432\n\t\tQ = K * R * K'\n        \n\t\tet = sqrt(R)*randn(1,nt)\n\t\tw = K*et\n        \n\t\t# input = AR(1)\n\t\tu = zeros(1,nt)\n\t\ta = randn(nt)\n\t\tfor t in 1:nt-1\n\t\t\tu[t+1] = 0.3*u[t] + a[t]\n\t\tend\n        \n\t\t# states\n\t\tns = size(A,1)\n\t\tx = zeros(ns,nt)\n\t\tx[:,1] = w[:,1]\n\t\tfor t in 1:nt-1\n\t\t\tx[:,t+1:t+1] = A * x[:,t:t] + B * u[t] + w[:,t:t]\n\t\tend\n\t\t# output\n\t\ty = C * x + D * u + et\n        \n\t\tsalida = y, u, A, B, K, C, D, Q, R        \n\tend\n    \n\treturn salida\n    \nend\n", "meta": {"hexsha": "321a28f0960511b757880b0d42750292f09ce807", "size": 1341, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ABCDQR/ABCDQR_bench.jl", "max_stars_repo_name": "javiercara/emSSM.jl", "max_stars_repo_head_hexsha": "1a1f18ea9b862c1de9f682dd773f7e86057f5cf3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-25T02:28:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-25T02:28:22.000Z", "max_issues_repo_path": "src/ABCDQR/ABCDQR_bench.jl", "max_issues_repo_name": "javiercara/emSSM.jl", "max_issues_repo_head_hexsha": "1a1f18ea9b862c1de9f682dd773f7e86057f5cf3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ABCDQR/ABCDQR_bench.jl", "max_forks_repo_name": "javiercara/emSSM.jl", "max_forks_repo_head_hexsha": "1a1f18ea9b862c1de9f682dd773f7e86057f5cf3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-12T00:05:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T00:05:04.000Z", "avg_line_length": 18.1216216216, "max_line_length": 53, "alphanum_fraction": 0.4601043997, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8705972784807408, "lm_q1q2_score": 0.780274011109893}}
{"text": "# See Floater and Hormann 2007 Eqn. (18) (Actually, an unnumbered equation\n# that is 3 equations later)\n# UPDATE: used formula (18) from Hormann's \"Barycentric Interpolation\"\n# part is that the interpolation seems to work OK for either. (We do know\n# that the sign of the weights must alternate)\n\"\"\" \n    floater_weights(x, d=0)  \n\nCalculate the Floater-Hormann weights for grid x and mixing degree d.  For\nmany applications d = 3 or 4 works well.\n\n    if we had a regular grid the values would be...\n    x: points at which we have function values\n    d: mixing degree        weights\n    d = 0                 1,1,...,1,1  \n    d = 1               1,2,2,...,2,2,1\n    d = 2             1,3,4,4,...,4,4,3,1\n    d = 3           1,4,7,8,8,...,8,8,7,4,1\n    d = 4     1,5,11,15,16,16,...,16,16,15,11,5,1\n\nBut note, if you do have a regularly spaced grid, it is much better to call\nthe floater_weights(n, order)\n\"\"\"\nfunction floater_weights(x::Array{T, 1}, d=0) where {T}\n    n = length(x)\n    d > n && error(\"Mixing coefficient must be less than node set size\")\n    w = zeros(eltype(x), n)\n    @inbounds for k in 1:n\n        ws = 0.0\n        for i in max(1, k-d):min(n-d, k)\n            lwp = 0.0\n            for j in i:min(n, i+d)\n                j == k && continue\n                lwp += log(abs(x[k] - x[j]))\n            end\n            ws += 1.0 / exp(lwp)\n        end\n        w[k] = k % 2 == 0 ? ws : -ws\n    end\n    return w ./ norm(w, Inf)\nend\n\n# Calculate the FH weights for a uniform grid of size n.  We don't\n# worry about the actual grid size, since these weights are intended\n# for use in the barycentric (2nd kind) interpolation formula.\n# This is from the last equation (unnumbered) in Section 4 of the FH paper\nfunction floater_weights(n::Int, d=0)\n    w = Vector{Float64}(undef, n)\n    @inbounds for k in 1:n\n        s = 0.0\n        for i in max(1, k-d):min(n-d, k)\n            s += binomial(d, k-i)\n        end\n        w[k] = (k-d) % 2 == 0 ? s : -s\n    end\n    return w\nend\n\n# Recognize a step range and handle it efficiently\nfunction floater_weights(x::T, d=0) where {T <:StepRangeLen}\n    return floater_weights(length(x), d)\nend\n\n\n\"\"\"Return the n + 1 chebychev points on the [-1, 1] interval\n\n  A shifted sin is used to make sure the points are symmetric\n\"\"\"\nfunction chebpts(n)\n    m = n - 1\n    x = sinpi.([-m:2:m;] ./ 2m)\n    return x\nend\n\nfunction chebwts(n)\n    w = ones(n)\n    w[2:2:end] .= -1.0\n    w[1] *= 0.5\n    w[end] *= 0.5\n    return w\nend\n\n\n# This is faster.  The exp(sum(log.(abs.(...))) version is ~30X slower do n = 10000\n\"\"\"The weights for Barycentric Lagrange interpolation given the x grid of evaluations\"\"\"\nfunction lagrange_weights(x::Vector{T}) where {T}\n    n = length(x)\n    w = ones(T, n)\n    t = copy(w)\n    @inbounds for i ∈ 1:n\n        t .= x[i] .- x\n        t[i] = one(eltype(x))\n        w[i] = one(eltype(x)) / prod(t)\n        # Here is the \"safe\" version\n        # w[i] = one(eltype(x)) / exp(sum(log.(abs.(t))))\n        # neg = count(t .< zero(eltype(x))) % 2 == 1\n        # w[i] = neg ? -w[i] : w[i]\n    end\n    # Normalize weights\n    return  w ./ norm(w, Inf)\nend\n\n", "meta": {"hexsha": "08bcacefe354936dbb96718e41b1109d35fb7364", "size": 3118, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/weights.jl", "max_stars_repo_name": "macd/BaryRational.jl", "max_stars_repo_head_hexsha": "6e5bb75e6fa3146bea855d2412fb45fecf9a8103", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-01-28T20:12:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T03:34:03.000Z", "max_issues_repo_path": "src/weights.jl", "max_issues_repo_name": "macd/BaryRational.jl", "max_issues_repo_head_hexsha": "6e5bb75e6fa3146bea855d2412fb45fecf9a8103", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-22T09:05:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-22T09:05:02.000Z", "max_forks_repo_path": "src/weights.jl", "max_forks_repo_name": "macd/BaryRational.jl", "max_forks_repo_head_hexsha": "6e5bb75e6fa3146bea855d2412fb45fecf9a8103", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2718446602, "max_line_length": 88, "alphanum_fraction": 0.5673508659, "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850021922959, "lm_q2_score": 0.8333245994514082, "lm_q1q2_score": 0.7802293244242559}}
{"text": "\"\"\"\n    Uniform(a,b)\n\nThe *continuous uniform distribution* over an interval ``[a, b]`` has probability density function\n\n```math\nf(x; a, b) = \\\\frac{1}{b - a}, \\\\quad a \\\\le x \\\\le b\n```\n\n```julia\nUniform()        # Uniform distribution over [0, 1]\nUniform(a, b)    # Uniform distribution over [a, b]\n\nparams(d)        # Get the parameters, i.e. (a, b)\nminimum(d)       # Get the lower bound, i.e. a\nmaximum(d)       # Get the upper bound, i.e. b\nlocation(d)      # Get the location parameter, i.e. a\nscale(d)         # Get the scale parameter, i.e. b - a\n```\n\nExternal links\n\n* [Uniform distribution (continuous) on Wikipedia](http://en.wikipedia.org/wiki/Uniform_distribution_(continuous))\n\n\"\"\"\nstruct Uniform{T<:Real} <: ContinuousUnivariateDistribution\n    a::T\n    b::T\n    Uniform{T}(a::T, b::T) where {T <: Real} = new{T}(a, b)\nend\n\nfunction Uniform(a::T, b::T; check_args=true) where {T <: Real}\n    check_args && @check_args(Uniform, a < b)\n    return Uniform{T}(a, b)\nend\n\nUniform(a::Real, b::Real) = Uniform(promote(a, b)...)\nUniform(a::Integer, b::Integer) = Uniform(float(a), float(b))\nUniform() = Uniform(0.0, 1.0, check_args=false)\n\nfunction Uniform(::Type{T}, a, b) where {T <: Real}\n    return Uniform(T(a), T(b))\nend\n\n@distr_support Uniform d.a d.b\n\n#### Conversions\nconvert(::Type{Uniform{T}}, a::Real, b::Real) where {T<:Real} = Uniform(T(a), T(b))\nconvert(::Type{Uniform{T}}, d::Uniform{S}) where {T<:Real, S<:Real} = Uniform(T(d.a), T(d.b), check_args=false)\n\n#### Parameters\n\nparams(d::Uniform) = (d.a, d.b)\npartype(::Uniform{T}) where {T<:Real} = T\n\nlocation(d::Uniform) = d.a\nscale(d::Uniform) = d.b - d.a\n\n\n#### Statistics\n\nmean(d::Uniform) = middle(d.a, d.b)\nmedian(d::Uniform) = mean(d)\nmode(d::Uniform) = mean(d)\nmodes(d::Uniform) = Float64[]\n\nvar(d::Uniform) = (w = d.b - d.a; w^2 / 12)\n\nskewness(d::Uniform{T}) where {T<:Real} = zero(T)\nkurtosis(d::Uniform{T}) where {T<:Real} = -6/5*one(T)\n\nentropy(d::Uniform) = log(d.b - d.a)\n\n\n#### Evaluation\n\npdf(d::Uniform{T}, x::Real) where {T<:Real} = insupport(d, x) ? 1 / (d.b - d.a) : zero(T)\nlogpdf(d::Uniform{T}, x::Real) where {T<:Real} = insupport(d, x) ? -log(d.b - d.a) : -T(Inf)\n\nfunction cdf(d::Uniform{T}, x::Real) where T<:Real\n    (a, b) = params(d)\n    x <= a ? zero(T) :\n    x >= d.b ? one(T) : (x - a) / (b - a)\nend\n\nfunction ccdf(d::Uniform{T}, x::Real) where T<:Real\n    (a, b) = params(d)\n    x <= a ? one(T) :\n    x >= d.b ? zero(T) : (b - x) / (b - a)\nend\n\nquantile(d::Uniform, p::Real) = d.a + p * (d.b - d.a)\ncquantile(d::Uniform, p::Real) = d.b + p * (d.a - d.b)\n\n\nfunction mgf(d::Uniform, t::Real)\n    (a, b) = params(d)\n    u = (b - a) * t / 2\n    u == zero(u) && return one(u)\n    v = (a + b) * t / 2\n    exp(v) * (sinh(u) / u)\nend\n\nfunction cf(d::Uniform, t::Real)\n    (a, b) = params(d)\n    u = (b - a) * t / 2\n    u == zero(u) && return complex(one(u))\n    v = (a + b) * t / 2\n    cis(v) * (sin(u) / u)\nend\n\n\n#### Sampling\n\nrand(rng::AbstractRNG, d::Uniform) = d.a + (d.b - d.a) * rand(rng)\n\n\n#### Fitting\n\nfunction fit_mle(::Type{<:Uniform}, x::AbstractArray{T}) where T<:Real\n    if isempty(x)\n        throw(ArgumentError(\"x cannot be empty.\"))\n    end\n\n    xmin = xmax = x[1]\n    for i = 2:length(x)\n        xi = x[i]\n        if xi < xmin\n            xmin = xi\n        elseif xi > xmax\n            xmax = xi\n        end\n    end\n\n    Uniform(xmin, xmax)\nend\n", "meta": {"hexsha": "7b794abddc3117953df16b2f8172e598f38d32b3", "size": 3365, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/uniform.jl", "max_stars_repo_name": "aminya/Distributions.jl", "max_stars_repo_head_hexsha": "e599d188f6839d67e26d9b647b69132f6f254fca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/uniform.jl", "max_issues_repo_name": "aminya/Distributions.jl", "max_issues_repo_head_hexsha": "e599d188f6839d67e26d9b647b69132f6f254fca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-10-30T02:14:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-31T00:46:58.000Z", "max_forks_repo_path": "src/univariate/continuous/uniform.jl", "max_forks_repo_name": "aminya/Distributions.jl", "max_forks_repo_head_hexsha": "e599d188f6839d67e26d9b647b69132f6f254fca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5620437956, "max_line_length": 114, "alphanum_fraction": 0.5616641902, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654263, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7802115931149156}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots\n\tRandom.seed!(0)\nend\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.06\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nn, N = 30, 10^6\n\n# ╔═╡ d599e1d4-3a99-11eb-1ab2-637caef1df0d\nbegin\n\tdist1 = Uniform(1-sqrt(3),1+sqrt(3))\n\tdist2 = Exponential(1)\n\tdist3 = Normal(1,1)\n\n\tdata1 = [mean(rand(dist1,n)) for _ in 1:N]\n\tdata2 = [mean(rand(dist2,n)) for _ in 1:N]\n\tdata3 = [mean(rand(dist3,n)) for _ in 1:N]\nend\n\n# ╔═╡ d59a153c-3a99-11eb-1cfe-f54834ffbc5c\nbegin\n\tstephist([data1 data2 data3], bins=100, \n\t\tc=[:blue :red :green], xlabel = \"x\", ylabel = \"Density\",\n\t\tlabel=[\"Average of Uniforms\" \"Average of Exponentials\" \"Average of Normals\"], \n\t\tnormed=true, xlims=(0,2), ylims=(0,2.5))\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.06\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═d599e1d4-3a99-11eb-1ab2-637caef1df0d\n# ╠═d59a153c-3a99-11eb-1cfe-f54834ffbc5c\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "baec61cfb6b9d758c3857c0c4759730bfef484e4", "size": 1349, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/listing5.06.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/05/listing5.06.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/05/listing5.06.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.4528301887, "max_line_length": 80, "alphanum_fraction": 0.709414381, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765257642906, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7802000340259466}}
{"text": "\"\"\"\n    +   +---+---+\n    | 1   2   3 |\n    +---+   +   +\n    | 4   5 | 6\n    +---+---+---+\n\n    julia> const graph = [\n            0 1 0 0 0 0;\n            1 0 1 0 1 0;\n            0 1 0 0 0 1;\n            0 0 0 0 1 0;\n            0 1 0 1 0 0;\n            0 0 1 0 0 0]\n\n    julia> dist, path = dijkstra(graph, 1)\n    (Dict(4=>3,2=>1,3=>2,5=>2,6=>3,1=>0), Dict(4=>5,2=>1,3=>2,5=>2,6=>3,1=>0))\n\n    julia> printpath(path, 6) # Display solution of the maze\n    1 -> 2 -> 3 -> 6\n\n\"\"\"\nfunction dijkstra(graph, source::Int=1)\n    # ensure that the adjacency matrix is squared\n    @assert size(graph, 1) == size(graph, 2)\n    inf = typemax(Int64)\n    n   = size(graph, 1)\n\n    Q    = IntSet(1:n)                  # Set of unvisited nodes\n    dist = Dict(n => inf for n in Q)    # Unknown distance function from source to v\n    prev = Dict(n => 0   for n in Q)    # Previous node in optimal path from source\n    dist[source] = 0                    # Distance from source to source\n\n    function _minimumdist(nodes) # Find the less distant node among nodes\n        kmin, vmin = nothing, inf\n        for (k, v) in dist\n            if k ∈ nodes && v ≤ vmin\n                kmin, vmin = k, v\n            end\n        end\n        return kmin\n    end\n    # Until all nodes are visited...\n    while !isempty(Q)\n        u = _minimumdist(Q)         # Vertex in Q with smallest dist[]\n        pop!(Q, u)\n        if dist[u] == inf break end # All remaining vertices are inaccessible from source\n        for v in 1:n                # Each neighbor v of u\n            if graph[u, v] != 0 && v ∈ Q # where v has not yet been visited\n                alt = dist[u] + graph[u, v]\n                if alt < dist[v]    # Relax (u, v, a)\n                    dist[v] = alt\n                    prev[v] = u\n                end\n            end\n        end\n    end\n\n    return dist, prev\nend\n\nfunction printpath(prev::Dict, target::Int)\n    path = \"$target\"\n    while prev[target] != 0\n        target = prev[target]\n        path = \"$target -> \" * path\n    end\n    println(path)\nend\n\nconst graph = [\n    0 1 0 0 0 0;\n    1 0 1 0 1 0;\n    0 1 0 0 0 1;\n    0 0 0 0 1 0;\n    0 1 0 1 0 0;\n    0 0 1 0 0 0]\n\ndist, path = dijkstra(graph)\nprintpath(path, 6)\n", "meta": {"hexsha": "a098c203aadb6041325b096bf39334d8d049f18e", "size": 2216, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/maze-solving.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/maze-solving.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/maze-solving.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3580246914, "max_line_length": 89, "alphanum_fraction": 0.4747292419, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7802000303203789}}
{"text": "struct Polynomial{R}\n    coeffs::Vector{R}\nend\n\nfunction (p::Polynomial)(x)\n    v = p.coeffs[end]\n    for i = (length(p.coeffs)-1):-1:1\n        v = v*x + p.coeffs[i]\n    end\n    return v\nend\n\n(p::Polynomial)() = p(9)\n\np = Polynomial([1,9,250])\n\nprintln(p(3))\n\nprintln(p())\n", "meta": {"hexsha": "5f113de6bfe57498d01c4e94fd0f51302da44427", "size": 273, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "manual/methods.jl", "max_stars_repo_name": "JulialangOrgCN/howtojulia", "max_stars_repo_head_hexsha": "c84d32046621e5191dd87bfa359666e507620d11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "manual/methods.jl", "max_issues_repo_name": "JulialangOrgCN/howtojulia", "max_issues_repo_head_hexsha": "c84d32046621e5191dd87bfa359666e507620d11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manual/methods.jl", "max_forks_repo_name": "JulialangOrgCN/howtojulia", "max_forks_repo_head_hexsha": "c84d32046621e5191dd87bfa359666e507620d11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-12T17:31:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-12T17:31:03.000Z", "avg_line_length": 13.65, "max_line_length": 37, "alphanum_fraction": 0.5641025641, "num_tokens": 96, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7802000286219851}}
{"text": "\"\"\"\n    crandnToep(t)\n\nGenerate `x ~ N_C(0,T)` with Toeplitz cov. `T` that has `t` as\nits first row.\n\"\"\"\nfunction crandnToep(t)\n    C = toeplitzHe(t)\n    y = sqrtm(C)*crandn(length(t))\nend\n\n\"\"\"\n    toeplitz(t::Vector)\n\nGenerate an `n` x `n` Toeplitz matrix `C` with generating vector `t` of length `2n-1`.\n`C[1,1] = t[n]`\n`C[1,n] = t[2n-1]`\n`C[n,1] = t[1]`\n\"\"\"\nfunction toeplitz(t::Vector)\n    n = Int(floor(length(t)/2)+1)\n\n    C = [t[j-i+n] for i=1:n,j=1:n]\nend\n\nfunction applyToep(t,x)\n    x2 = [x;zeros(x)]\n    t2 = [conj(t);0;t[end:-1:2]]\n    y = ifft(fft(t2,1).*fft(x2,1))\n    y = y[1:length(x)]\nend\n\n\"\"\"\n    toeplitzHe(t::Vector)\n\nGenerate an `n` x `n` Hermitian Toeplitz matrix `C` with generating vector `t` of length `n`.\nThe vector `t` defines the first row of `C` and `t[1]` must be real.\n\"\"\"\nfunction toeplitzHe(t::Vector)\n    t_full = [ conj(t[end:-1:2]); t[1:end] ]\n    C = toeplitz(t_full)\nend\n\n\"\"\"\n    best_circulant_approximation(t::Vector)\n\nIf `t` is the length `n` generating vector of a Hermitian Toeplitz matrix `T`, then\n`c` is the length `n` generating vector of a Hermitian circulant matrix `C`, which\nis the best approximation of `T`.\n\"\"\"\nfunction best_circulant_approximation(t::Vector)\n    n = length(t);\n    lins = ((n:-2:-n+2)./n);\n    t1 = t;\n    t2 = cat(1,[0], conj(reverse(t[2:end])));\n    c = 0.5*n*real(ifft(lins .*(t1-t2) + t1 + t2));\nend\n\n\n\"\"\"\n    best_circulant_approximation(t::Matrix)\n\nIf each `t[:,m]` is the length `n` generating vector of a Hermitian Toeplitz matrix `T_m`, then\neach `c[:,m]` is the length `n` generating vector of a Hermitian circulant matrix `C_m`, which\nis the best approximation of `T_m`.\n\"\"\"\nfunction best_circulant_approximation(t::Matrix)\n    n = size(t,1);\n    m = size(t,2);\n    lins = ((n:-2:-n+2)./n);\n    t1 = t;\n    t2 = cat(1,zeros(1,m), conj(flipdim(t[2:end,:],1)));\n    c = 0.5*n*real(ifft(lins .*(t1-t2) + t1 + t2,1));\nend\n", "meta": {"hexsha": "6280172d2233ad3d8a4f801df33a0b120f4743f9", "size": 1901, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SCM3GPP/src/toeplitz_helpers.jl", "max_stars_repo_name": "tum-msv/learning-mmse-est", "max_stars_repo_head_hexsha": "804336e314a4d81accf49404a564d1809399e947", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2018-04-18T15:49:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T20:16:43.000Z", "max_issues_repo_path": "SCM3GPP/src/toeplitz_helpers.jl", "max_issues_repo_name": "onism222/learning-mmse-est", "max_issues_repo_head_hexsha": "804336e314a4d81accf49404a564d1809399e947", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SCM3GPP/src/toeplitz_helpers.jl", "max_forks_repo_name": "onism222/learning-mmse-est", "max_forks_repo_head_hexsha": "804336e314a4d81accf49404a564d1809399e947", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2018-05-02T07:03:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T10:40:42.000Z", "avg_line_length": 25.3466666667, "max_line_length": 95, "alphanum_fraction": 0.6081009995, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767974, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.780189469203337}}
{"text": "using Pkg\nPkg.status()\nusing Plots\nusing DifferentialEquations\n\n#----------------------------------------------\n# Set Parameters:\n# Membrane capacitance and potential\nC_m = 1.0\nV_m = -65.0\n\n# Max sodium conductance and membrane potential\ng_Na = 120.0\nV_Na = 56.0\n\n# Max potassium conductance and membrane potential\ng_K = 36.0\nV_K = -77.0\n\n# Max leak conductance and membrane potential\ng_l = 0.3 \nV_l = -60.0\n\n# Time to integrate over\ntime = 0.0:0.1:1000\n\n# ion variables\nm = 0.05\nh = 0.6\nn = 0.32\n\n#----------------------------------------------\n# Potassium Rate Functoins\na_n(V_m) =  0.01 * (V_m + 55) / (1 - exp(-(V_m + 55.0) / 10))\n\nB_n(V_m) = 0.125 * exp(-(V_m + 65.0) / 80)\n\n\n#----------------------------------------------\n# Sodium Rate Functions\na_m(V_m) = 0.1 * (40 + V_m) / (1.0 - exp(-(V_m + 40.0) / 10.0))\n\na_h(V_m) = 0.07 * exp(-(V_m + 65.0) / 20.0)\n\nB_m(V_m) = 4 * exp(-(V_m + 65.0) / 18.0)\n\nB_h(V_m) = 1 / (exp(-(35 + V_m) / 10) + 1)\n\n\n#----------------------------------------------\n# Ion Currents\nIK(g_K, n, V_m, V_K) = g_K * n^(4) * (V_m - V_K)\n\nINa(g_Na, m, h, V_m, V_Na) =  g_Na * m^(3) * h * (V_m - V_Na)\n\nLI(g_l, V_m, V_l) = g_l * (V_m - V_l)\n\n#----------------------------------------------\n# Input current\nI_Inj = 20\n\ninput(t::AbstractFloat) = ifelse(0 < t < 200, zero(t), ifelse(200<t<300, one(t)*I_Inj, zero(t)))\n\n#----------------------------------------------\n# Hodking Huxley model\nfunction hodgkin_huxley!(du, u, p, t)\n    # dVdt, dndt, dmdt, dhdt = u\n    #\n    #\n    V_m, n, m, h = u\n    g_K, V_K, g_Na, V_Na, g_l, C_m = p\n    \n    # Total current through the membrane\n    du[1] = input(t) - IK(g_K,n,V_m,V_K) - INa(g_Na, m, h, V_m, V_Na) - LI(g_l, V_m, V_l) / C_m\n\n    # Derivative of n, potassium channel activation, w.r.t. time\n    du[2] = a_n(V_m) * (1 - n) - B_n(V_m) * n\n\n    # Derivative of m, sodium channel activion, w.r.t. time\n    du[3] = a_m(V_m) * (1 - m) - B_m(V_m) * m\n\n    # Derivative of h, leaky channel in-activion, w.r.t. time\n\n    du[4] = a_h(V_m) * (1 - h) - B_h(V_m) * h\n\nend\n\n#----------------------------------------------\n# Define and solve ODE problem\np = [g_K, V_K, g_Na, V_Na, g_l, C_m]\nu0 = [V_m, n, m, h]\ntspan = (0.0,500.0)\n\nprob = ODEProblem(hodgkin_huxley!,u0,tspan,p)\nsol = solve(prob)\n\n#----------------------------------------------\n# Plotting Solutions\nplot(sol, vars=1)\n#animate(sol, vars=(1), every=20)\n\nplot(sol, vars=(2,3))\n\nplot(sol, vars=(2,3,4))\n", "meta": {"hexsha": "618b810dc40d630f34a36712b128dd6dbae30b00", "size": 2421, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia_models/Hodkin_Huxley.jl", "max_stars_repo_name": "PavanChaggar/neuronal_models", "max_stars_repo_head_hexsha": "89ffc6773838a5e5b8e6d0fd577af8b4135764cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia_models/Hodkin_Huxley.jl", "max_issues_repo_name": "PavanChaggar/neuronal_models", "max_issues_repo_head_hexsha": "89ffc6773838a5e5b8e6d0fd577af8b4135764cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia_models/Hodkin_Huxley.jl", "max_forks_repo_name": "PavanChaggar/neuronal_models", "max_forks_repo_head_hexsha": "89ffc6773838a5e5b8e6d0fd577af8b4135764cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0571428571, "max_line_length": 96, "alphanum_fraction": 0.4981412639, "num_tokens": 925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7801894611974155}}
{"text": "function lin_inter(grid,vals)\n    function func(x::Real)\n        if x <= grid[1]\n            return (vals[2] - vals[1])/(grid[2] - grid[1])*(x - grid[1]) + vals[1]\n        elseif x >= grid[end]\n            return (vals[end] - vals[end-1])/(grid[end] - grid[end-1])*(x - grid[end]) + vals[end]\n        else\n            index = searchsortedlast(grid,x)\n            return (vals[index+1] - vals[index])/(grid[index+1] - grid[index])*(x - grid[index]) + vals[index]\n        end\n    end\n\n    function func{T<:Real}(x::AbstractVector{T})\n        m = length(x)\n        out = Array(Any,m)\n        for i in 1:m\n            out[i] = func(x[i])\n        end\n        return out\n    end\n    return func\n\nend\n", "meta": {"hexsha": "2de5c4b2e7331961aa07954b6b3e4e388cb01a7f", "size": 694, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lin_int2.jl", "max_stars_repo_name": "R-Tsushima/MyInterpolation.jl", "max_stars_repo_head_hexsha": "b13ff178cce5beba4083f27c66f2f0f3bafd61c7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lin_int2.jl", "max_issues_repo_name": "R-Tsushima/MyInterpolation.jl", "max_issues_repo_head_hexsha": "b13ff178cce5beba4083f27c66f2f0f3bafd61c7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-05-22T01:35:19.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-07T10:04:34.000Z", "max_forks_repo_path": "lin_int2.jl", "max_forks_repo_name": "R-Tsushima/MyInterpolation.jl", "max_forks_repo_head_hexsha": "b13ff178cce5beba4083f27c66f2f0f3bafd61c7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9166666667, "max_line_length": 110, "alphanum_fraction": 0.5043227666, "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172630429474, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7801894553041879}}
{"text": "\"\"\"\nObtain coefficients (A, B) of the function Se = B(x - A)^2 for\nSe(1.2) = B(1.2 - A)^2 and Se(1.0) = B(1.0 - A)^2 as:\nSe(1.0) = Se(1.2)/(1.2 - A)^2 * (1.0 - A)^2 that yields\n(1.2 - A)^2 Se(1.0) = Se(1.2) * (1.0 - A)^2 or expanding:\n(Se(1.2) - Se(1.0)) A^2 + (2.4 Se(1.0) - 2 Se(1.2)) A + (Se(1.2) - 1.44 Se(1.0)) = 0\nand uses the negative solution of the quadratic equation\n\"\"\"\nfunction get_quadratic_saturation(Se::Tuple{Float64, Float64})\n    if Se[1] == 0.0 || Se[2] == 0.0\n        @warn \"$(Se[1]) or $(Se[2]) equals to zero. Ignoring saturation.\"\n        return (0.0, 0.0)\n    end\n    if Se[2] <= Se[1]\n        throw(IS.ConflictingInputsError(\"Se(1.2) <= Se(1.0). Saturation data is inconsistent.\"))\n    end\n    E1 = 1.0\n    E12 = 1.2\n    Sat_Se1 = Se[1]\n    Sat_Se12 = Se[2]\n    Sat_a = sqrt(E1 * Sat_Se1 / (E12 * Sat_Se12)) * ((Sat_Se12 > 0) + (Sat_Se12 < 0))\n    Sat_A = E12 - (E1 - E12) / (Sat_a - 1)\n    Sat_B = E12 * Sat_Se12 * (Sat_a - 1)^2 * ((Sat_a > 0) + (Sat_a < 0)) / (E1 - E12)^2\n\n    return (Sat_A, Sat_B)\nend\n\n\"\"\"\nObtain coefficients (A, B) of the function Se = Bx^A for\nSe(1.2) = B(1.2)^A and Se(1.0) = B(1.0)^A as:\nB = Se(1.0) and hence\n(1.2)^A = Se(1.2)/B -> A = log(Se(1.2)/B) / log(1.2)\n\"\"\"\nfunction get_exponential_saturation(Se::Tuple{Float64, Float64})\n    if Se[1] == 0.0 || Se[2] == 0.0\n        @warn \"$(Se[1]) or $(Se[2]) equals to zero. Ignoring saturation.\"\n        return (0.0, 0.0)\n    end\n    if Se[2] <= Se[1]\n        throw(IS.ConflictingInputsError(\"Se(1.2) <= Se(1.0). Saturation data is inconsistent.\"))\n    end\n    B = Se[1]\n    A = log(Se[2] / B) / log(1.2)\n\n    return (A, B)\nend\n", "meta": {"hexsha": "4f8e37556013179fac65e7b7778ffa016e2e508e", "size": 1625, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/dynamic_machines.jl", "max_stars_repo_name": "andrewrosemberg/PowerSystems.jl", "max_stars_repo_head_hexsha": "b47e0c03cc80627615585014a2f42cb5b814d5c5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/models/dynamic_machines.jl", "max_issues_repo_name": "andrewrosemberg/PowerSystems.jl", "max_issues_repo_head_hexsha": "b47e0c03cc80627615585014a2f42cb5b814d5c5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/dynamic_machines.jl", "max_forks_repo_name": "andrewrosemberg/PowerSystems.jl", "max_forks_repo_head_hexsha": "b47e0c03cc80627615585014a2f42cb5b814d5c5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5744680851, "max_line_length": 96, "alphanum_fraction": 0.5384615385, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762057376384, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7801592093418125}}
{"text": "\"\"\"\n    borehole(param_values::AbstractArray{<:Number, N})\n\nReturn an `N` by 1 array of results of the Borehole function (http://www.sfu.ca/~ssurjano/borehole.html)\nusing the `N` by 8 array of `param_values`.\n\"\"\"\nfunction borehole(param_values::AbstractArray{<:Number, N}) where N\n\n    numruns = size(param_values, 1)\n    Y = zeros(numruns, 1)\n\n    for i in 1:numruns\n\n        # parameters\n        rw =    param_values[i, 1] # radius of borehole (m)\n        r =     param_values[i, 2] # radius of influence (m)\n        Tu =    param_values[i, 3] # transmissivity of upper aquifer (m2/yr)\n        Hu =    param_values[i, 4] # potentiometric head of upper aquifer (m)\n        Tl =    param_values[i, 5] # transmissivity of lower aquifer (m2/yr)\n        Hl =    param_values[i, 6] # potentiometric head of lower aquifer (m)\n        L =     param_values[i, 7] # length of borehole (m)\n        Kw =    param_values[i, 8] # hydraulic conductivity of borehole (m/yr)\n\n        # calculation\n        l = log(r/rw)\n        num = 2 * pi * Tu * (Hu - Hl)\n        denom = l * (1 + ((2 * L * Tu) / (l * rw^2 * Kw)) + (Tu/Tl))\n        Y[i] = num / denom\n    end\n    return Y\nend\n", "meta": {"hexsha": "5e12534a92438362d70a51c5ddb667f6c36ccba8", "size": 1164, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/test_functions/borehole.jl", "max_stars_repo_name": "lrennels/SAJulia", "max_stars_repo_head_hexsha": "6e9fe1eb81b07e5232de8ae95302995363b1e113", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2019-02-25T00:07:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-15T00:26:04.000Z", "max_issues_repo_path": "src/test_functions/borehole.jl", "max_issues_repo_name": "lrennels/SAJulia", "max_issues_repo_head_hexsha": "6e9fe1eb81b07e5232de8ae95302995363b1e113", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2019-02-22T06:14:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-04T06:55:02.000Z", "max_forks_repo_path": "src/test_functions/borehole.jl", "max_forks_repo_name": "lrennels/SALib.jl", "max_forks_repo_head_hexsha": "6e9fe1eb81b07e5232de8ae95302995363b1e113", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-12-06T01:22:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-28T13:02:25.000Z", "avg_line_length": 36.375, "max_line_length": 104, "alphanum_fraction": 0.5859106529, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762055074521, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7801592031197643}}
{"text": "using CSV\nusing LsqFit\nusing Dates\n\n\nfunction calc(dates::Array{Date}, data::Array{Float64}, n::Int64)\n\n    function j_m_exp(t,p)\n        J = Array{Float64}(undef, length(t), length(p))\n        J[:,1] = exp.(p[2] .* t)       #df/dp[1]\n        J[:,2] = t .* p[1] .* J[:,1]   #df/dp[2]\n        J\n    end\n\n    function j_m_pow2(t,p)\n        J = Array{Float64}(undef, length(t), length(p))\n        J[:,1] = 2.0 .^ (t ./ p[2])       #df/dp[1]\n\n        c = -log(2.0)*p[1]/(p[2] * p[2])\n        J[:,2] =  t .* c .* J[:,1]        #df/dp[2]\n        J\n    end\n\n    datesWindow = dates[end-n+1 : end]\n    date1 = dates[end-n+1]\n\n    x = map(d -> (d-date1).value, datesWindow)\n    y = data[end-n+1 : end] .- data[end-n+1];\n\n    m_exp(t, p) = p[1] * exp.(p[2] * t)\n    p0_exp = [x[1], 0.5]\n    fit_exp = curve_fit(m_exp, j_m_exp, x, y, p0_exp)\n\n    m_pow2(t, p) = p[1] * 2.0 .^ (t/p[2])\n    p0_pow2 = [x[1], 0.5]\n    fit_pow2 = curve_fit(m_pow2, j_m_pow2, x, y, p0_pow2)\n\n    confidence_intervals = confidence_interval(fit_pow2, 0.1)\n\n    p = fit_pow2.param\n    \n    # y_fitted = m_pow2(x,p)\n    # diff = 100.0*(abs.(y.-y_fitted))./y\n    # println(diff)\n\n    print(p)\n    print(\"\\t\")\n    println(confidence_intervals)\n    println(\"---\")\n\nend\n\ndf = CSV.File(\"CoronaData2.csv\")\n\ndates = df.Date\n\ndataDE = convert(Array{Float64}, df.Germany)\ndataCH = convert(Array{Float64}, df.Switzerland)\n\nprint(\"Germany: \")\n# calc(dates[1:end], dataDE, 15)\ncalc(dates[1:end], dataDE, 10)\n# calc(dates[1:end], dataDE, 5)\n\nprint(\"Switzerland: \")\n# calc(dates[1:end], dataCH, 15)\ncalc(dates[1:end], dataCH, 10)\n# calc(dates[1:end], dataCH, 5)", "meta": {"hexsha": "c5cc80e29f8c7dfd4aa6a4639fc158a8c7206daf", "size": 1610, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CoronaSim.jl", "max_stars_repo_name": "qrider71/CoronaSim", "max_stars_repo_head_hexsha": "6a1ba9e6b9a093f576a9e9fae5423427cec1b248", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CoronaSim.jl", "max_issues_repo_name": "qrider71/CoronaSim", "max_issues_repo_head_hexsha": "6a1ba9e6b9a093f576a9e9fae5423427cec1b248", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoronaSim.jl", "max_forks_repo_name": "qrider71/CoronaSim", "max_forks_repo_head_hexsha": "6a1ba9e6b9a093f576a9e9fae5423427cec1b248", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6764705882, "max_line_length": 65, "alphanum_fraction": 0.5447204969, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762052772658, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7801591990731856}}
{"text": "function RTBPEnergy(u, mu)\n\"\"\"\n     RTBP-Nbody problem\n\"\"\"\n\n\n @inbounds begin\n    x = u[1]   # x\n    y = u[2]   # y\n    px = u[3]  # px\n    py = u[4]  # py\n\n    umu=1-mu\n\n    r1 = ((x+mu)^2 + y^2)^(1/2)\n    r2 = ((x-umu)^2 + y^2)^(1/2)\n\n    Energy=(px*px+py*py)/2+px*y-py*x-umu/r1-mu/r2-mu*umu/2\n\n    return(Energy)\n    end\n\nend\n\n\nf = (du,u,p,t) -> begin\n\n  μ=p[1]\n  uμ=1-μ\n  @inbounds begin\n  # 1 = y₁\n  # 2 = y₂\n  # 3 = y₁'\n  # 4 = y₂'\n  D₁ = ((u[1]+μ)^2 + u[2]^2)^(3/2)\n  D₂ = ((u[1]-uμ)^2 + u[2]^2)^(3/2)\n  du[1] = u[3]+u[2]\n  du[2] = u[4]-u[1]\n  du[3] = u[4] - uμ*(u[1]+μ)/D₁ - μ*(u[1]-uμ)/D₂\n  du[4] = -u[3] - uμ*u[2]/D₁ - μ*u[2]/D₂\n  end\nend\n", "meta": {"hexsha": "a40808df28f2ee605021f115f1f1a949571a5d83", "size": 649, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ODEProblems/RTBP.jl", "max_stars_repo_name": "mikelehu/IRKGL16.jl", "max_stars_repo_head_hexsha": "2cf769cebef40d5a1587d77330c3088c28c1f8af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-10-20T22:06:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:57:29.000Z", "max_issues_repo_path": "ODEProblems/RTBP.jl", "max_issues_repo_name": "mikelehu/IRKGL16.jl", "max_issues_repo_head_hexsha": "2cf769cebef40d5a1587d77330c3088c28c1f8af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-10-14T12:55:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-02T10:48:57.000Z", "max_forks_repo_path": "ODEProblems/RTBP.jl", "max_forks_repo_name": "mikelehu/IRKGL16.jl", "max_forks_repo_head_hexsha": "2cf769cebef40d5a1587d77330c3088c28c1f8af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-01-26T23:53:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T18:20:15.000Z", "avg_line_length": 15.0930232558, "max_line_length": 58, "alphanum_fraction": 0.4191063174, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9683812345563902, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7801590892448761}}
{"text": "# WARNING:\n# ========\n# This blog post https://julialang.org/blog/2019/01/fluxdiffeq/ gives a high level\n# description of this file.\n\n# Many function calls are fully qualified. This is not necessary. The package name is\n# included to get a better sense of the role of the different packages.\n\n# The Lotka-Volterra differential equations model populations of predators\n# and preys over time.\n\n# This example starts with an ODE setup with a given set of parameters.\n# Then, using the same equations, optimises starting with a different set of parameters\n\n## Import the required packages\nusing DifferentialEquations, DiffEqSensitivity\nusing Flux, DiffEqFlux\nusing Plots\n\n\n##\n## Setup ODE to optimize\n##\n\n# The populations are representated as a vector of 2 numbers:\n#    U = [numbers of rabbits, number of wolves]\n#\n# ODE problems expect the equations to be presented with standard parameters:\n#   dU: the derivatives of U. This vector is modified in place for speed purposes\n#    U: the functions\n#    p: a vector of paramters\n#    t: the functions' variable (here time)\nfunction lotka_volterra!(du, u, p, t)\n  x, y = u\n  α, β, δ, γ = p\n  du[1] = dx = α * x - β * x * y\n  du[2] = dy = -δ * y + γ * x * y\nend\n\n# Initial conditions\nu0 = [1.0, 1.0]\n\n# Time over which to simulate\nt_span = (0.0, 10.0)\n\n# Initial parameters\np0 = [1.5, 1.0, 3.0, 1.0]\n\n# Setup the ODE\nprob0 = DiffEqBase.ODEProblem(lotka_volterra!, u0, t_span, p0)\n\n# Solve the ODE\nsol0 = DiffEqBase.solve(prob0, Tsit5())\n\n# Plot it\nplot(sol0)\n\n##\n## Generate data that will be used to train the network\n## The data is the number of rabbits/wolves at set times\n##\n\n# Solve the ODE (again) and collect solutions at fixed intervals\ntarget_data = DiffEqBase.solve(prob0, Tsit5(), saveat = 0.1)\nrabbits = target_data[1, :]                     # vector of 101 data points\nwolves  = target_data[2, :]                    # vector of 101 data points\n\n# Plot the data on top of the full solution\nt_steps = 0:0.1:10.0\nscatter!(t_steps, rabbits, color = [1], label = \"rabbits\")\nscatter!(t_steps, wolves,  color = [2], label = \"wolves\")\n\n\n##\n## Parameter optimisation\n##\n\n# Loss function is the total squared error\n# (the number of points is constant - mean is not necessary)\nloss_function = function()\n    prediction = DiffEqBase.concrete_solve(prob0, Tsit5(), u0, p;\n    sensealg = TrackerAdjoint(), saveat = 0.0:0.1:10.0)\n\n    # Calculate squared error\n  return sum(abs2, prediction - target_data)\nend\n\n\n# Callback function to observe training\niter = 0\ncallback = function ()\n  global iter += 1\n  if iter % 10 == 1\n    # Plot the training data\n    scatter(t_steps,  rabbits, color = [1], label = \"rabbit data\")\n    scatter!(t_steps, wolves,  color = [2], label = \"wolves data\")\n\n    # Use `remake` to re-create the original `prob0` with different current parameters `p`\n    remade_sol = DiffEqBase.solve(remake(prob0, p = p), Tsit5(), saveat = 0.1)\n    remade_rabbits = remade_sol[1, :]\n    remade_wolves  = remade_sol[2, :]\n    plot!(t_steps, remade_rabbits, ylim = (0, 6), labels = \"rabbit model\", color = 1)\n    display(plot!(t_steps, remade_wolves, ylim = (0, 6), labels = \"wolf model\", color = 2))\n  end\nend\n\n\n# Vector of new parameters different from p0\np = [4.0, 1.0, 2.0, 0.4]\nODEparams = Flux.params(p)\n\n# Display the ODE with the initial parameter values.\ncallback()\n\n\n# The parameter `loss_data` in `train!` (below) contains a list of data that are provided\n# to the loss function. `train!`` works by iterating over that list. In our case, the\n# calculation of the loss function does not require any additional data.\n# Therefore `loss_data` is filled with a whole bunch of nothing.\nloss_data = Iterators.repeated((), 1000)\n\n# ADAM is a great default optimiser\noptimiser = Flux.ADAM(0.1)\n\n# train! is a function that hides some of the complexity of the library\nFlux.train!(loss_function, ODEparams, loss_data, optimiser; cb = callback)\n", "meta": {"hexsha": "4ede118bc2ff002102a85f032b73f1f22e78eba6", "size": 3896, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "contrib/diffeq/lotka-volterra.jl", "max_stars_repo_name": "AdarshKumar712/model-zoo", "max_stars_repo_head_hexsha": "b52421d74341b3f33927d22cacbea08bf74ce459", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "contrib/diffeq/lotka-volterra.jl", "max_issues_repo_name": "AdarshKumar712/model-zoo", "max_issues_repo_head_hexsha": "b52421d74341b3f33927d22cacbea08bf74ce459", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contrib/diffeq/lotka-volterra.jl", "max_forks_repo_name": "AdarshKumar712/model-zoo", "max_forks_repo_head_hexsha": "b52421d74341b3f33927d22cacbea08bf74ce459", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6771653543, "max_line_length": 91, "alphanum_fraction": 0.6953285421, "num_tokens": 1139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7799834341461557}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.21\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 166bbbb2-8f7a-11eb-19c6-19dfe8ee5123\nusing ChainRules\n\n# ╔═╡ a8439cf0-8eab-11eb-3d6b-a3d65e46a635\nmd\"\"\"\n# Automatic Differentiation (AD)\n\nAutomatic differentiation is a method to evaluate the derivatives of a given program, you may heard this in context of deep learning as back-propagation. However, in more general scientific machine learning, the situation can be more complicated, thus it'd be necessary to understand better about the mechanism of automatic differentiation.\n\nIn this section, we will introduce the automatic differentiation technique in a more systematic aspect\n\"\"\"\n\n# ╔═╡ 12cb96f8-8f48-11eb-212d-956d24e7a892\nmd\"\"\"\n# Dual Numbers\n\nDual number is the simplest way of implementing AD. And thanks to Julia's powerful generic programming features, we can easily implement one ourselves!\n\n**definition** define ``ϵ`` to satisfy ``ϵ^2 = 0``, then similar to a complex number we define dual number as ``x = a + b ⋅ ϵ``\n\nthen we can intermediately get the rule of multiplication\n\n```math\n(a + b⋅ϵ)(c + d⋅ϵ) = ac + (ad + bc)ϵ\n```\n\nthus we can implement our own dual number as following\n\"\"\"\n\n# ╔═╡ af43976a-8f48-11eb-1485-0b76c7ee1e79\nbegin\n\tstruct Dual{T<:Real} <: Real\n\t\ta::T\n\t\tb::T\n\tend\n\t\n\tDual(a) = Dual(a, one(a))\nend\n\n# ╔═╡ d1522092-8f48-11eb-30f2-f9c3183ae364\nBase.show(io::IO, x::Dual) = print(io, x.a, \"+\", x.b, \"ϵ\")\n\n# ╔═╡ e0a6fe78-8f48-11eb-152f-5b448f08fc49\nDual(2)\n\n# ╔═╡ e4fbb1f8-8f48-11eb-220e-f33784f6e617\nBase.:(*)(x::Dual, y::Dual) = Dual(x.a * y.a, x.a * y.b + x.b * y.a)\n\n# ╔═╡ 25669170-8f4b-11eb-1cae-a78fc79be709\nBase.:(+)(x::Dual, y::Dual) = Dual(x.a + y.a, x.b + y.b)\n\n# ╔═╡ 0c7cdab8-8f49-11eb-3bac-2de9b80bb7d0\nDual(3, 1) * Dual(3, 1)\n\n# ╔═╡ 82b578de-8f49-11eb-13dd-aba04a2c196d\nmd\"now let's define a simply function see what happens if we instead of feeding a normal real number, we feed in a dual number\"\n\n# ╔═╡ 28b6ea34-8f49-11eb-2625-d58fbfba667f\nf(x) = x^3\n\n# ╔═╡ 9f7849bc-8f49-11eb-0f59-1bdf987ecdfe\nf(Dual(2))\n\n# ╔═╡ a7d73bb6-8f49-11eb-2c45-99fbd3a2c248\nmd\"\"\"\nthe prefactor of ϵ gives the derivative! let's see why\n\ngiven a real polynomail\n\n```math\nP(x) = p_0 + p_1 x + p_2 x^2 + ⋯ + p_n x^n\n```\n\nif we put a dual number ``x = a + b ϵ``, we have\n\n```math\n\\begin{aligned}\nP(a+bϵ) \n&= p_0 + p_1 a + p_2 a^2 + ⋯ + p_n a^n + p_1 bϵ + 2p_2 abϵ + ⋯ + n p_n a^{n-1}b ϵ\\\\\n&= P(a) + b P'(a)ϵ\n\\end{aligned}\n```\n\nmore generally, using Taylor series, this is also true for any real analytical functions. \n\nHowever, if we plugin our dual number into functions like `sin`, it doesn't work\n\"\"\"\n\n# ╔═╡ 8a4b5ec8-8f4a-11eb-1155-f358a173daa2\nsin(Dual(2))\n\n# ╔═╡ 94bc3b16-8f4a-11eb-0871-59f5469f4c0e\nmd\"\"\"\nthis is because in practical numerical program, for efficiency, a lot mathematical functions are implemented specifically for floating point type, thus we don't have a generic function for these functions to make things \"just work\"\n\nthus we will need to define the derivative of `sin` manually here\n\"\"\"\n\n# ╔═╡ cfdb25b6-8f4a-11eb-2248-3f7783956f35\nBase.sin(x::Dual) = Dual(sin(x.a), cos(x.a) * x.b)\n\n# ╔═╡ de6df808-8f4a-11eb-0f70-43400519fd6f\nsin(Dual(2))\n\n# ╔═╡ f2b1a960-8f4a-11eb-1276-b333b086605c\nmd\"however if we happen to have a function definition on generic types, e.g the matrix multiplication, this will just work\"\n\n# ╔═╡ 0906c78e-8f4b-11eb-1d3b-dd8d6d891175\nA = [Dual(1.0) Dual(2.0); Dual(1.0) Dual(2.0)]\n\n# ╔═╡ 149734d0-8f4b-11eb-0af4-6368d8bb34c0\nB = [Dual(1.0) Dual(2.0); Dual(1.0) Dual(3.0)]\n\n# ╔═╡ 1a483212-8f4b-11eb-0fa5-5994548ea6b9\nA * B\n\n# ╔═╡ f4228cb2-8eab-11eb-1b98-fbb30f8eeac3\nmd\"\"\"\n# Forward Mode AD\n\nThe forward mode AD is the simplest way of implementing an AD system. The above dual number is one way to implement forward mode AD with a generic type system.\n\nMore formally, we say forward mode AD is to apply the chain rule on primal derivatives\nwhen we evaluate the value of an expression, e.g if we are going to evaluate the following function\n\"\"\"\n\n# ╔═╡ c6d79168-8f4f-11eb-1c4f-4bf4abbb2c72\nfunction foo(x)\n\tx1 = sin(x)\n\tx2 = sin(x1)\n\tx3 = cos(x2) + x2\nend\n\n# ╔═╡ d2f7c68e-8f4f-11eb-0d90-4f2f22bd87b6\nmd\"\"\"\nwhen we put in a dual number we actually do the following things:\n\n1. evaluate `sin(x)` and its derivative, store them in `x1`\n2. evaluate `sin(x1)` and its derivative, multiply the derivative of `sin(x1)` to previous derivative since we have ``P'(x)b ϵ`` term in the dual number\n3. evaluate the derivative of `cos(x2)` and do the same thing as above, but let's call the intermediate value of `cos(x2)` to be `y`\n4. evaluate the value of `y+x2` and derivative then multiply and store them in `x3`\n\nthus we see every time we evaluate the derivative, we can throw away the variables we calculated before, but for every single scalar number we need to calculate the entire function, as a result, this gives us the time complexity $O(mn)$ where $n$ is the number of parameters and $m$ is the complexity of the original code.\n\nthe memory complexity is $O(m+n)$ where $m$ is the memory complexity of the original code\n\"\"\"\n\n# ╔═╡ f75c7e22-8f52-11eb-0b32-f9ed6267fb18\nmd\"\"\"\nto formalize the above process in terms of chain rule, the forward mode means we evaluate the derivatives in the following accumulation:\n\n```math\n\\begin{aligned}\n\\frac{\\partial y_n}{\\partial x}\n&= \\frac{\\partial y_n}{\\partial y_{n-1}} \\frac{\\partial y_{n-1}}{\\partial x}\\\\\n&= \\frac{\\partial y_n}{\\partial y_{n-1}} (\\frac{\\partial y_{n-1}}{\\partial y_{n-2}} \\frac{\\partial y_{n-2}}{\\partial x})\\\\\n&= \\cdots\\\\\n&= \\frac{\\partial y_n}{\\partial y_{n-1}} (\\frac{\\partial y_{n-1}}{\\partial y_{n-2}} \\cdots (\\frac{\\partial y_2}{\\partial y_1} \\frac{\\partial y_1}{\\partial x}))\n\\end{aligned}\n```\n\n\"\"\"\n\n# ╔═╡ 9ef95826-8f53-11eb-11ed-a35e16d20083\nmd\"\"\"\nwe can further generalize this to multi-variable case using Jacobians\n\n```math\n\\begin{aligned}\n\\frac{\\partial \\vec{y}_n}{\\partial x}\n&= \\frac{\\partial \\vec{y}_n}{\\partial \\vec{y}_{n-1}} \\frac{\\partial \\vec{y}_{n-1}}{\\partial x}\\\\\n&= \\frac{\\partial \\vec{y}_n}{\\partial \\vec{y}_{n-1}} (\\frac{\\partial \\vec{y}_{n-1}}{\\partial \\vec{y}_{n-2}} \\frac{\\partial \\vec{y}_{n-2}}{\\partial x})\\\\\n&= \\cdots\\\\\n&= \\frac{\\partial \\vec{y}_n}{\\partial \\vec{y}_{n-1}} (\\frac{\\partial \\vec{y}_{n-1}}{\\partial \\vec{y}_{n-2}} \\cdots (\\frac{\\partial \\vec{y}_2}{\\partial \\vec{y}_1} \\frac{\\partial \\vec{y}_1}{\\partial x}))\n\\end{aligned}\n```\n\"\"\"\n\n# ╔═╡ 0e07a38e-8f55-11eb-0c46-ef5d11df07de\nmd\"\"\"\nnow we see to calculate the derivative of ``\\frac{\\partial \\vec{y}_n}{\\partial x}`` it is actually about calculatnig a chain of **Jacobian-vector product**\n\"\"\"\n\n# ╔═╡ 13c539e8-8eac-11eb-35b0-61108d5f3c5f\nmd\"\"\"\n# Reverse Mode AD\n\nFor large number of parameters, reverse mode is more efficient. This method has been re-discovered many times in history in different fields, you may hear it called back-propagation in context of deep learning.\n\"\"\"\n\n# ╔═╡ 45826916-8f55-11eb-3f3c-95d6b601191b\nmd\"\"\"\nsimilar to forward mode AD, the reverse mode AD is actually about calculating the chain rule in the following accumulation:\n\n```math\n\\begin{aligned}\n\\frac{\\partial \\vec{y}_n}{\\partial x}\n&= (\\frac{\\partial \\vec{y}_n}{\\partial \\vec{y}_{n-1}}) \\frac{\\partial \\vec{y}_{n-1}}{\\partial x}\\\\\n&= ((\\frac{\\partial \\vec{y}_n}{\\partial \\vec{y}_{n-1}}) \\frac{\\partial \\vec{y}_{n-1}}{\\partial \\vec{y}_{n-2}}) \\frac{\\partial \\vec{y}_{n-2}}{\\partial x}\\\\\n&= ⋯\\\\\n&= (\\cdots ((\\frac{\\partial \\vec{y}_n}{\\partial \\vec{y}_{n-1}}) \\frac{\\partial \\vec{y}_{n-1}}{\\partial \\vec{y}_{n-2}}\\cdots \\frac{\\partial \\vec{y}_2}{\\partial \\vec{y}_1}) \\frac{\\partial \\vec{y}_1}{\\partial x}\\\\\n(\\frac{\\partial \\vec{y}_n}{\\partial x})^T &= (\\frac{\\partial \\vec{y}_1}{\\partial x})^T (\\frac{\\partial \\vec{y}_2}{\\partial \\vec{y}_1})^{T} \\cdots (\\frac{\\partial \\vec{y}_{n-1}}{\\partial \\vec{y}_{n-2}})^T (\\frac{\\partial \\vec{y}_n}{\\partial \\vec{y}_{n-1}})^T\n\\end{aligned}\n```\n\nthus the reverse mode automatic differentiation is acutally about **Jacobian-transpose-vector product**. \n\nWe can see an intermediate advantage of this accumulation is that if ``x`` is a vector, we can directly calculate the derivative of this vector by a chain of matrix multiplication.\n\"\"\"\n\n# ╔═╡ e026ffa6-8f5f-11eb-0651-dfb9e28fcc4f\nmd\"\"\"\nthis process will be easier to understand if we use a graphical language to describe it, this the **computational graph**, to demonstrate this better, I'll use a more complicated function\n\n```math\ny = \\mathbf{x}^T\\mathbf{A}\\mathbf{x} + \\mathbf{b}\\cdot\\mathbf{x} + c\n```\n\"\"\"\n\n# ╔═╡ 10ba0d9c-8f5f-11eb-0744-6be46cfacebe\nmd\"\"\"\nWe will need to call several functions in Julia to get the result $y$, which is\n\n1. ``\\mathbf{z_1} = \\mathbf{x}^T``: `transpose` function.\n2. ``\\mathbf{z_2} = \\mathbf{z_1} A`` matrix-vector multiplication, which can be `gemv` in `LinearAlgebra.BLAS`, or just `*`.\n3. ``y_1 = \\mathbf{z_2} \\mathbf{x}`` vector dot operation, which is `LinearAlgebra.dot` or the UTF-8 operator `x ⋅ y`\n4. ``y_2 = \\mathbf{b} \\cdot \\mathbf{x}`` another vector dot\n5. ``y_1 + y_2 + c`` a scalar add function, one can calculate it by simply calling `+` operator in Julia.\n\nIn fact, we can draw a graph of this expression, which illustrates the relationship between each variable in this expression.\nEach node in the graph with an output arrow represents a variable and each node with an input arrow represents a function/operator.\n\n![](https://blog.rogerluo.me/images/comput-graph-forward.gif)\n\nThe evaluation of the math equation above can then be expressed as a process called **forward evaluation**, it starts from the leaf nodes, which represents the inputs of the whole expression, e.g they are $\\mathbf{x}, \\mathbf{A}, \\mathbf{b}, c$ in our expression. Each time, we receive the value of a node in the graph, we mark the node with **green**.\n\"\"\"\n\n# ╔═╡ 4921f4f8-8f60-11eb-0e45-3f3034dbea83\nmd\"\"\"\nthe derivative calculation can be then visualized as following\n\n![](https://blog.rogerluo.me/images/comput-graph-backward.gif)\n\"\"\"\n\n# ╔═╡ 29fa38b6-8f61-11eb-118a-616fc647715a\nmd\"\"\"\nas we demonstrate above, although the reverse mode can calculate the derivatives for all the parameters in single evaluation. it will need to store the intermediate values.\n\nthus we need a specific data structure to store these values， this data structure is often called the computational graph, tape or Wengert list.\n\nNow the problem of implementing reverse mode AD becomes how to create the tape.\n\"\"\"\n\n# ╔═╡ 0580566c-8ff4-11eb-35a3-bf0505fe5a1c\nmd\"\"\"\n# Relation with Differential Geometry\n\nSince we have represented our AD algorithm as Jacobian or Jacobian transpose product, it is natural to have a geometric interpretation of them.\n\n## Definitions\n\nLet ``p`` be a point in the space ``\\mathbf{M}`` defined by ``(x_1, x_2, ⋯, x_m)``, and we have a function ``f: \\mathbf{M} → \\mathbf{K}`` that is a smooth map (differentiable everywhere), then we can define the **tangent space** ``\\mathbf{T}_p \\mathbf{M}`` at point ``p`` as the space span by the derivatives ``\\frac{d}{dx}``, the tangent space acts linearly on the space of functions. \n\nNow we define **the collection of the tangent spaces** ``\\mathbf{T}_p\\mathbf{M}`` for ``p ∈ \\mathbf{M}`` as the **tangent bundle** of ``\\mathbf{M}``\n\n![tangent space](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Tangentialvektor.svg/200px-Tangentialvektor.svg.png)\n\nlet ``df`` denotes the first order information of ``f`` at each point, which is called the **differential** of ``f``. If the derivative of ``f`` and ``g`` agree at ``p``, we say that ``df`` and ``dg`` represents the same cotangent at ``p``. The covectors ``dx_1, dx_2, ⋯, dx_m`` form the basis of the cotangent space ``\\mathbf{T}^*_p \\mathbf{M}`` for ``p∈\\mathbf{M}``\n\n**push-forward**\n\n![](https://upload.wikimedia.org/wikipedia/commons/thumb/3/37/Pushforward.svg/330px-Pushforward.svg.png)\n\n**pullback**\n\n![](https://www.mathphysicsbook.com/wp-content/uploads/2013/10/39.pullback-v2.png)\n\"\"\"\n\n# ╔═╡ eb4df5e4-8f79-11eb-2429-a31bd0009c4b\nmd\"\"\"\n## the manual AD\n\nso we can do reverse mode \"automatic\" differentiation manually first, to have a feeling about it. \n\nWe will use the package `ChainRules` here.\n\"\"\"\n\n# ╔═╡ 72b98a42-8ff8-11eb-17f3-6d14da3964be\nx = 3.0\n\n# ╔═╡ 1a78b2be-8f7a-11eb-0470-e7febaac6272\ny, sin_pullback = rrule(sin, x)\n\n# ╔═╡ 627f170a-8ff8-11eb-21eb-47796905e10b\nsin_pullback(1)\n\n# ╔═╡ 67c7f3d0-8ff8-11eb-04dc-4f796cfb940e\ncos(x)\n\n# ╔═╡ 7cffb62a-8ff8-11eb-0288-f55b0d333571\nmd\"\"\"\nnow we can manually generate the pullback function for a given function defined on some primal functions, in AD, we usually call these functions **adjoint**s.\n\nlet's use the previous example `foo` here\n\"\"\"\n\n# ╔═╡ 98d147c4-8ff8-11eb-3ab8-21e26217e02a\nfunction adjoint_foo(x)\n\tx1, x1_pullback = rrule(sin, x)\n\tx2, x2_pullback = rrule(sin, x1)\n\ty, y_pullback = rrule(cos, x2)\n\tx3, x3_pullback = rrule(+, y, x2)\n\t\n\treturn x3, function pullback(Δ)\n\t\t_, ∂y, ∂x2_1 = x3_pullback(Δ)\n\t\t_, ∂x2_2 = y_pullback(∂y)\n\t\t_, ∂x1 = x2_pullback(∂x2_1 + ∂x2_2)\n\t\t_, ∂x = x1_pullback(∂x1)\n\t\treturn Zero(), ∂x\n\tend\nend\n\n# ╔═╡ 8e593406-8ff9-11eb-101a-695b2b026a20\n_, foo_pullback = adjoint_foo(x)\n\n# ╔═╡ 9e31a492-8ff9-11eb-108d-1b7bbd152170\nfoo_pullback(1)\n\n# ╔═╡ a21aa0c2-8ff9-11eb-1cc8-7b63a20d0791\n(foo(x+1e-10)-foo(x-1e-10))/2e-10\n\n# ╔═╡ c5f14d48-8ff9-11eb-1350-790162aa8b34\nmd\"\"\"\nthus the simplest reverse mode AD is about how to create this tiny `pullback` function automatically, and to know how to create this `pullback` function we need to know what primal functions are called by the given function, so that we can simply reverse the order of calls and replace them with the `pullback` functions.\n\"\"\"\n\n# ╔═╡ 3fc036f8-8eac-11eb-15dc-017c0d5237bc\nmd\"\"\"\n## Operator Overloading AD\n\nThe easiest way of creating a tape is using operator overloading. By operator overloading, it means the exactly same way we implemented our toy symbolic program in the previous section.\n\nfor example, we can define our own type to dispatch the functions to a `track` function so that we can store the function call into a tape.\n\n```julia\nmutable struct Variable{T} <: ADExpr\n    value::T\n    grad::T\n\n    Variable(val::T) where T = new{T}(val)\n    Variable(val::T, grad::T) where T = new{T}(val)\nend\n\nstruct Node{FT <: Function, ArgsT <: Tuple, KwargsT <: NamedTuple} <: ADExpr\n    f::FT\n    args::ArgsT\n    kwargs::KwargsT\nend\n```\n\nthen overload some primal functions to track the call into tape\n\n```\nBase.sin(x::ADExpr) = register(Base.sin, x)\n```\n\"\"\"\n\n# ╔═╡ 35cfef70-8ffa-11eb-1a48-e906596eebe6\nmd\"\"\"\nI will not demonstrate the details of implementing such AD engine, but once you understand the mechanism, you should be able to write one yourself in mins!\n\nFor the curious, checkout my blog post **Implementing Your Own Automatic Differentiation Engine in ONE day**: [https://blog.rogerluo.me/2018/10/23/write-an-ad-in-one-day/](https://blog.rogerluo.me/2018/10/23/write-an-ad-in-one-day/)\n\"\"\"\n\n# ╔═╡ 73ffb3fe-8ffd-11eb-2b71-038543ea5093\nmd\"\"\"\n\n## What packages/software uses this method?\n\n#### Python\n\n- PyTorch\n- autograd\n- ...\n\n#### Julia\n\n- Tracker\n- YAAD\n- Nabla\n- ...\n\n\"\"\"\n\n\n# ╔═╡ bd69872c-8f78-11eb-2197-2f760c33b197\nmd\"\"\"\n\n## Limitations\n\nhowever, the above method **won't work for general programs that contains control flows**. This is because in the representation of Wengert list, or the tape, we don't have the semantic of control flows, and we don't have a way to record control flows using operator overloading, such as `for` loop or `if else` statements.\n\nThis is because control flows are not functions in most of the programming languages, we cannot change the control flow behaviour by overloading them on different types, and it may not make sense to do so.\n\nOn the other hand, it **won't work for generic programming**, since we have used a specific type to dispatch functions, which kinda \"abused\" the type system.\n\"\"\"\n\n# ╔═╡ 46ad0fa2-8eac-11eb-28df-4f2c23f8d3ff\nmd\"\"\"\n## Source Code Transformation AD\n\nAs you may noticed, in both forward and reverse mode AD, in order to represent intermediate derivatives, we were forced to use a new temperory variable for every function call.\n\nThis leads to a special intermediate representation for general programs called the **Static Single Assignment** intermediate representation (SSA IR), by **Static Single Assignment** we mean:\n\n> every variable in the program is only assigned once statically\n\nthe control flows in a SSA IR are usually canonicalized to `goto` or `goto ifnot` if it has conditions, since every variable is only assigned once we use `%<name>` or `%<int>` to represent a variable.\n\"\"\"\n\n# ╔═╡ cbe1949e-8ffc-11eb-0747-e576545133b4\nmd\"\"\"\nthe SSA IR is a widely used representation in your daily used compilers, for example, your C/C++ compiler clang, or some of your new fancy langauges like Julia, rust and more. This is because SSA IR is a very convenient representation to optimize and analysis.\n\n![](https://slideplayer.com/slide/13900843/85/images/7/C-like+IR+In+SSA+form+x1+%3D+f%28x0%29%3B+x+%3D+f%28x%29%3B+if+%28x1+%3E+y0%29.jpg)\n\"\"\"\n\n# ╔═╡ 6616ee24-8ffd-11eb-0d13-7f7ea01d3f73\nmd\"\"\"\nthis is a natural extension of the Wengert list (the tape) with control flows. Thus instead of doing operator overloading, we can directly write a compiler extension to transform the source encoded in SSA IR to the corresponding differential function in SSA IR.\n\nAnd in Julia, this is extremely easy (in terms of implementing it), because Julia is a dynamic compiled language\n\n![](https://blog.rogerluo.me/images/julia-compile-diagram.png)\n\"\"\"\n\n# ╔═╡ df1d9e58-90de-11eb-341a-bb942e20e713\nmd\"\"\"\nFor the curious, checkout my blog post **Build your own source to source automatic differentiation in ONE day!** :[https://blog.rogerluo.me/2019/07/27/yassad/](https://blog.rogerluo.me/2019/07/27/yassad/)\n\"\"\"\n\n# ╔═╡ c5f18fe2-8ffe-11eb-0a96-1f3ce397e943\nmd\"\"\"\n# Software/Package uses this method\n\n- **Julia**: Zygote, Enzyme, Yota, Diffractor (work-in-progress), ...\n- **Python**: JAX, ...\n\"\"\"\n\n# ╔═╡ 420d72f4-8ffe-11eb-1b0f-43bdc9edf955\nmd\"\"\"\n## Limitations\n\nNo limitations in theory.\n\nWe have the information about control flows, which means it **will work for control flows**.\n\nWe don't need to reply on type system to track the function calls anymore which means it works for **generic programming**\n\nBut covering the entire general purpose programming language with most of the corner cases may take years to accomplish.\n\"\"\"\n\n# ╔═╡ 84e5fe6e-8eac-11eb-04f8-cf7499b2c218\nmd\"\"\"\n## Other type of AD engines\n\nThere are other type of AD engines that works under some context, such as polynomials, reversible programs, etc.\n\nYou can find a full list of AD engines in Julia at [https://juliadiff.org/](https://juliadiff.org/)\n\"\"\"\n\n# ╔═╡ 2e3fc494-90de-11eb-1c90-f9cc1357aab3\nmd\"\"\"\n\n### Is there an algebra gives us reverse mode AD?\n\n- reversible programming\n\n![](https://giggleliu.github.io/NiLang.jl/dev/asset/revcomp.jpg)\n\n\"\"\"\n\n# ╔═╡ 8d13dbe0-90de-11eb-1bcf-dfbd8118e59d\nmd\"\"\"\n## NiLang: reversible domain-specific programming language in Julia\n\n![](https://github.com/GiggleLiu/NiLang.jl/raw/master/docs/src/asset/logo3.png)\n\"\"\"\n\n# ╔═╡ 4c23d3bc-8eac-11eb-2870-a37dfc123bc5\nmd\"\"\"\n## Differentiable Programming in Condensed Matter Physics: Tensor Network\n\nOne of the most poplular method in numerical condensed matter physics is the tensor network methods.\n\nTensor network is also way to approximate the solution, in previous lectures, you have learned how to use neural network states to solve ground state problem using variational Monte Carlo. \n\nMore traditionally physicists have been using tensor network as the physical ansatz. However calculating the gradient of tensor networks can be complicated. Thus, by making use of automatic differentiation, one will be able to do gradient based optimization on tensor network easily.\n\n![](https://github.com/Roger-luo/PIML/blob/master/notebooks/assets/tensor-network.png?raw=true)\n\n[https://arxiv.org/pdf/1903.09650.pdf](https://arxiv.org/pdf/1903.09650.pdf)\n\"\"\"\n\n# ╔═╡ 619d6b8e-90d4-11eb-17fa-dd41790aa420\nmd\"\"\"\n## Further Readings\n\n- the ChainRules package documentation: [https://juliadiff.org/ChainRulesCore.jl/stable/](https://juliadiff.org/ChainRulesCore.jl/stable/)\n- NiLang tutorial for reversible programming: [https://giggleliu.github.io/NiLang.jl/dev/why/](https://giggleliu.github.io/NiLang.jl/dev/why/)\n- the differential and pullback: [https://www.mathphysicsbook.com/mathematics/manifolds/mapping-manifolds/the-differential-and-pullback/](https://www.mathphysicsbook.com/mathematics/manifolds/mapping-manifolds/the-differential-and-pullback/)\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─a8439cf0-8eab-11eb-3d6b-a3d65e46a635\n# ╟─12cb96f8-8f48-11eb-212d-956d24e7a892\n# ╠═af43976a-8f48-11eb-1485-0b76c7ee1e79\n# ╠═d1522092-8f48-11eb-30f2-f9c3183ae364\n# ╠═e0a6fe78-8f48-11eb-152f-5b448f08fc49\n# ╠═e4fbb1f8-8f48-11eb-220e-f33784f6e617\n# ╠═25669170-8f4b-11eb-1cae-a78fc79be709\n# ╠═0c7cdab8-8f49-11eb-3bac-2de9b80bb7d0\n# ╟─82b578de-8f49-11eb-13dd-aba04a2c196d\n# ╠═28b6ea34-8f49-11eb-2625-d58fbfba667f\n# ╠═9f7849bc-8f49-11eb-0f59-1bdf987ecdfe\n# ╟─a7d73bb6-8f49-11eb-2c45-99fbd3a2c248\n# ╠═8a4b5ec8-8f4a-11eb-1155-f358a173daa2\n# ╟─94bc3b16-8f4a-11eb-0871-59f5469f4c0e\n# ╠═cfdb25b6-8f4a-11eb-2248-3f7783956f35\n# ╠═de6df808-8f4a-11eb-0f70-43400519fd6f\n# ╟─f2b1a960-8f4a-11eb-1276-b333b086605c\n# ╠═0906c78e-8f4b-11eb-1d3b-dd8d6d891175\n# ╠═149734d0-8f4b-11eb-0af4-6368d8bb34c0\n# ╠═1a483212-8f4b-11eb-0fa5-5994548ea6b9\n# ╟─f4228cb2-8eab-11eb-1b98-fbb30f8eeac3\n# ╠═c6d79168-8f4f-11eb-1c4f-4bf4abbb2c72\n# ╟─d2f7c68e-8f4f-11eb-0d90-4f2f22bd87b6\n# ╟─f75c7e22-8f52-11eb-0b32-f9ed6267fb18\n# ╟─9ef95826-8f53-11eb-11ed-a35e16d20083\n# ╟─0e07a38e-8f55-11eb-0c46-ef5d11df07de\n# ╟─13c539e8-8eac-11eb-35b0-61108d5f3c5f\n# ╟─45826916-8f55-11eb-3f3c-95d6b601191b\n# ╟─e026ffa6-8f5f-11eb-0651-dfb9e28fcc4f\n# ╟─10ba0d9c-8f5f-11eb-0744-6be46cfacebe\n# ╟─4921f4f8-8f60-11eb-0e45-3f3034dbea83\n# ╟─29fa38b6-8f61-11eb-118a-616fc647715a\n# ╟─0580566c-8ff4-11eb-35a3-bf0505fe5a1c\n# ╟─eb4df5e4-8f79-11eb-2429-a31bd0009c4b\n# ╠═166bbbb2-8f7a-11eb-19c6-19dfe8ee5123\n# ╠═72b98a42-8ff8-11eb-17f3-6d14da3964be\n# ╠═1a78b2be-8f7a-11eb-0470-e7febaac6272\n# ╠═627f170a-8ff8-11eb-21eb-47796905e10b\n# ╠═67c7f3d0-8ff8-11eb-04dc-4f796cfb940e\n# ╟─7cffb62a-8ff8-11eb-0288-f55b0d333571\n# ╠═98d147c4-8ff8-11eb-3ab8-21e26217e02a\n# ╠═8e593406-8ff9-11eb-101a-695b2b026a20\n# ╠═9e31a492-8ff9-11eb-108d-1b7bbd152170\n# ╠═a21aa0c2-8ff9-11eb-1cc8-7b63a20d0791\n# ╟─c5f14d48-8ff9-11eb-1350-790162aa8b34\n# ╟─3fc036f8-8eac-11eb-15dc-017c0d5237bc\n# ╟─35cfef70-8ffa-11eb-1a48-e906596eebe6\n# ╟─73ffb3fe-8ffd-11eb-2b71-038543ea5093\n# ╟─bd69872c-8f78-11eb-2197-2f760c33b197\n# ╟─46ad0fa2-8eac-11eb-28df-4f2c23f8d3ff\n# ╟─cbe1949e-8ffc-11eb-0747-e576545133b4\n# ╟─6616ee24-8ffd-11eb-0d13-7f7ea01d3f73\n# ╟─df1d9e58-90de-11eb-341a-bb942e20e713\n# ╟─c5f18fe2-8ffe-11eb-0a96-1f3ce397e943\n# ╟─420d72f4-8ffe-11eb-1b0f-43bdc9edf955\n# ╟─84e5fe6e-8eac-11eb-04f8-cf7499b2c218\n# ╟─2e3fc494-90de-11eb-1c90-f9cc1357aab3\n# ╟─8d13dbe0-90de-11eb-1bcf-dfbd8118e59d\n# ╟─4c23d3bc-8eac-11eb-2870-a37dfc123bc5\n# ╟─619d6b8e-90d4-11eb-17fa-dd41790aa420\n", "meta": {"hexsha": "43abadd16ca47da402adcbad7ba62b33f73fe89e", "size": 23022, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/2.automatic-differentiation.jl", "max_stars_repo_name": "Roger-luo/PIML", "max_stars_repo_head_hexsha": "48672658b6c5175d47ce0966588e9e7f362dd43b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2021-03-28T21:21:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T05:10:46.000Z", "max_issues_repo_path": "notebooks/2.automatic-differentiation.jl", "max_issues_repo_name": "Roger-luo/PIML", "max_issues_repo_head_hexsha": "48672658b6c5175d47ce0966588e9e7f362dd43b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/2.automatic-differentiation.jl", "max_forks_repo_name": "Roger-luo/PIML", "max_forks_repo_head_hexsha": "48672658b6c5175d47ce0966588e9e7f362dd43b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-01T07:27:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-01T07:27:51.000Z", "avg_line_length": 39.6247848537, "max_line_length": 386, "alphanum_fraction": 0.7272608809, "num_tokens": 8623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8872045922259089, "lm_q1q2_score": 0.7799830549935586}}
{"text": "# In this tutorial, we are exploring the application of Ridge and Lasso\n# regression to the Hitters R dataset.\n#\n# ## Getting started\n\nusing MLJ\nimport RDatasets: dataset\nusing PrettyPrinting\nMLJ.color_off() # hide\nimport Distributions\nconst D = Distributions\n\n@load LinearRegressor pkg=MLJLinearModels\n@load RidgeRegressor pkg=MLJLinearModels\n@load LassoRegressor pkg=MLJLinearModels\n\n# We load the dataset using the `dataset` function, which takes the Package and\n# dataset names as arguments.\n\nhitters = dataset(\"ISLR\", \"Hitters\")\n@show size(hitters)\nnames(hitters) |> pprint\n\n# Let's unpack the dataset with the `unpack` function.\n# In this case, the target is `Salary` (`==(:Salary)`) and all other columns are features (`col->true`).\n\ny, X = unpack(hitters, ==(:Salary), col->true);\n\n# The target has missing values which we will just ignore.\n# We extract the row indices corresponding to non-missing values of the target.\n# Note the use of the element-wise operator `.`.\nno_miss = .!ismissing.(y);\n\n# We collect the non missing values of the target in an Array.\n# And keep only the corresponding features values.\ny = collect(skipmissing(y))\nX = X[no_miss, :]\n\n# Let's now split our dataset into a train and test sets.\ntrain, test = partition(eachindex(y), 0.5, shuffle=true, rng=424);\n\n# Let's have a look at the target.\n\nusing PyPlot\nioff() # hide\n\nfigure(figsize=(8,6))\nplot(y, ls=\"none\", marker=\"o\")\n\nxticks(fontsize=12); yticks(fontsize=12)\nxlabel(\"Index\", fontsize=14), ylabel(\"Salary\", fontsize=14)\n\nsavefig(joinpath(@OUTPUT, \"ISL-lab-6-g1.svg\")) # hide\n\n# \\figalt{Salary}{ISL-lab-6-g1.svg}\n\n# That looks quite skewed, let's have a look at a histogram:\n\nfigure(figsize=(8,6))\nhist(y, bins=50, density=true)\n\nxticks(fontsize=12); yticks(fontsize=12)\nxlabel(\"Salary\", fontsize=14); ylabel(\"Density\", fontsize=14)\n\nedfit = D.fit_mle(D.Exponential, y)\nxx = range(minimum(y), 2500, length=100)\nyy = pdf.(edfit, xx)\nplot(xx, yy, lw=3, label=\"Exponential distribution fit\")\n\nlegend(fontsize=12)\n\nsavefig(joinpath(@OUTPUT, \"ISL-lab-6-g2.svg\")) # hide\n\n# \\figalt{Distribution of salary}{ISL-lab-6-g2.svg}\n#\n# ### Data preparation\n#\n# Most features are currently encoded as integers but we will consider them as continuous.\n# To coerce `int` features to `Float`, we nest the `autotype` function in the `coerce` function.\n# The `autotype` function returns a dictionary containing scientific types, which is then passed to the `coerce` function.\n# For more details on the use of `autotype`, see the [Scientific Types](https://alan-turing-institute.github.io/DataScienceTutorials.jl/data/scitype/index.html#autotype)\n\nXc = coerce(X, autotype(X, rules=(:discrete_to_continuous,)))\nscitype(Xc)\n\n# There're a few features that are categorical which we'll one-hot-encode.\n\n# ## Ridge pipeline\n# ### Baseline\n#\n# Let's first fit a simple pipeline with a standardizer, a one-hot-encoder and a basic linear regression:\n\nmodel = @pipeline(Standardizer(),\n                     OneHotEncoder(),\n                     LinearRegressor())\n\npipe  = machine(model, Xc, y)\nfit!(pipe, rows=train)\nŷ = predict(pipe, rows=test)\nround(rms(ŷ, y[test])^2, sigdigits=4)\n\n# Let's get a feel for how we're doing\n\nfigure(figsize=(8,6))\n\nres = ŷ .- y[test]\nstem(res)\n\nxticks(fontsize=12); yticks(fontsize=12)\nxlabel(\"Index\", fontsize=14); ylabel(\"Residual (ŷ - y)\", fontsize=14)\n\nylim([-1300, 1000])\n\nsavefig(joinpath(@OUTPUT, \"ISL-lab-6-g3.svg\")) # hide\n\n# \\figalt{Residuals}{ISL-lab-6-g3.svg}\n\nfigure(figsize=(8,6))\nhist(res, bins=30, density=true, color=\"green\")\n\nxx = range(-1100, 1100, length=100)\nndfit = D.fit_mle(D.Normal, res)\nlfit  = D.fit_mle(D.Laplace, res)\n\nplot(xx, pdf.(ndfit, xx), lw=3, color=\"orange\", label=\"Normal fit\")\nplot(xx, pdf.(lfit, xx), lw=3, color=\"magenta\", label=\"Laplace fit\")\n\nlegend(fontsize=12)\n\nxticks(fontsize=12); yticks(fontsize=12)\nxlabel(\"Residual (ŷ - y)\", fontsize=14); ylabel(\"Density\", fontsize=14)\nxlim([-1100, 1100])\n\nsavefig(joinpath(@OUTPUT, \"ISL-lab-6-g4.svg\")) # hide\n\n# \\figalt{Distribution of residuals}{ISL-lab-6-g4.svg}\n\n# ### Basic Ridge\n#\n# Let's now swap the linear regressor for a Ridge one without specifying the penalty (`1` by default):\n# We modify the supervised model in the pipeline directly.\n\npipe.model.linear_regressor = RidgeRegressor()\nfit!(pipe, rows=train)\nŷ = predict(pipe, rows=test)\nround(rms(ŷ, y[test])^2, sigdigits=4)\n\n# Ok that's a bit better but surely we can do better with an appropriate selection of the hyperparameter.\n\n# ### Cross validating\n\n# What penalty should you use? Let's do a simple CV to try to find out:\n\nr  = range(model, :(linear_regressor.lambda), lower=1e-2, upper=100_000, scale=:log10)\ntm = TunedModel(model=model, ranges=r, tuning=Grid(resolution=50),\n                resampling=CV(nfolds=3, rng=4141), measure=rms)\nmtm = machine(tm, Xc, y)\nfit!(mtm, rows=train)\n\nbest_mdl = fitted_params(mtm).best_model\nround(best_mdl.linear_regressor.lambda, sigdigits=4)\n\n# right, and  with that we get:\n\nŷ = predict(mtm, rows=test)\nround(rms(ŷ, y[test])^2, sigdigits=4)\n\n# Let's see:\n\nfigure(figsize=(8,6))\n\nres = ŷ .- y[test]\nstem(res)\n\nxticks(fontsize=12); yticks(fontsize=12)\nxlabel(\"Index\", fontsize=14);\nylabel(\"Residual (ŷ - y)\", fontsize=14)\nxlim(1, length(res))\n\nylim([-1300, 1000])\n\nsavefig(joinpath(@OUTPUT, \"ISL-lab-6-g5.svg\")) # hide\n\n# \\figalt{Ridge residuals}{ISL-lab-6-g5.svg}\n#\n# You can compare that with the residuals obtained earlier.\n\n# ## Lasso pipeline\n#\n# Let's do the same as above but using a Lasso model and adjusting the range a bit:\n\nmtm.model.model.linear_regressor = LassoRegressor()\nmtm.model.range = range(model, :(linear_regressor.lambda), lower=500, upper=100_000, scale=:log10)\nfit!(mtm, rows=train)\n\nbest_mdl = fitted_params(mtm).best_model\nround(best_mdl.linear_regressor.lambda, sigdigits=4)\n\n# Ok and let's see how that does:\n\nŷ = predict(mtm, rows=test)\nround(rms(ŷ, y[test])^2, sigdigits=4)\n\n# Pretty good! and the parameters are reasonably sparse as expected:\n\ncoefs, intercept = fitted_params(mtm.fitresult).linear_regressor\n@show coefs\n@show intercept\n\n# with around 50% sparsity:\n\ncoef_vals = [c[2] for c in coefs]\nsum(coef_vals .≈ 0) / length(coefs)\n\n# Let's visualise this:\n\nfigure(figsize=(8,6))\nstem(coef_vals)\n\n## name of the features including one-hot-encoded ones\nall_names = [:AtBat, :Hits, :HmRun, :Runs, :RBI, :Walks, :Years,\n             :CAtBat, :CHits, :CHmRun, :CRuns, :CRBI, :CWalks,\n             :League__A, :League__N, :Div_E, :Div_W,\n             :PutOuts, :Assists, :Errors, :NewLeague_A, :NewLeague_N]\n\nidxshow = collect(1:length(coef_vals))[abs.(coef_vals) .> 10]\nxticks(idxshow .- 1, all_names[idxshow], rotation=45, fontsize=12)\nyticks(fontsize=12)\nylabel(\"Amplitude\", fontsize=14)\n\nsavefig(joinpath(@OUTPUT, \"ISL-lab-6-g6.svg\")) # hide\n\n# \\figalt{Lasso coefficients}{ISL-lab-6-g6.svg}\n\n# ## Elastic net pipeline\n\n@load ElasticNetRegressor pkg=MLJLinearModels\n\nmtm.model.model.linear_regressor = ElasticNetRegressor()\nmtm.model.range = [range(model, :(linear_regressor.lambda), lower=0.1, upper=100, scale=:log10),\n                    range(model, :(linear_regressor.gamma),  lower=500, upper=10_000, scale=:log10)]\nmtm.model.tuning = Grid(resolution=10)\nfit!(mtm, rows=train)\n\nbest_mdl = fitted_params(mtm).best_model\n@show round(best_mdl.linear_regressor.lambda, sigdigits=4)\n@show round(best_mdl.linear_regressor.gamma, sigdigits=4)\n\n# And it's not too bad in terms of accuracy either\n\nŷ = predict(mtm, rows=test)\nround(rms(ŷ, y[test])^2, sigdigits=4)\n\n# But the simple ridge regression seems to work best here.\nPyPlot.close_figs() # hide\n", "meta": {"hexsha": "69e809c8c388c95c5706447fea23773bdd50e35b", "size": 7585, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "_literate/ISL-lab-6b.jl", "max_stars_repo_name": "giordano/DataScienceTutorials.jl", "max_stars_repo_head_hexsha": "8284298842e0d77061cf8ee767d0899fb7d051ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_literate/ISL-lab-6b.jl", "max_issues_repo_name": "giordano/DataScienceTutorials.jl", "max_issues_repo_head_hexsha": "8284298842e0d77061cf8ee767d0899fb7d051ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_literate/ISL-lab-6b.jl", "max_forks_repo_name": "giordano/DataScienceTutorials.jl", "max_forks_repo_head_hexsha": "8284298842e0d77061cf8ee767d0899fb7d051ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.62890625, "max_line_length": 169, "alphanum_fraction": 0.7123269611, "num_tokens": 2245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8791467643431001, "lm_q1q2_score": 0.7799830452547654}}
{"text": "# %% Demonstration of delay embeddings\nusing DrWatson\n@quickactivate \"NonlinearDynamicsTextbook\"\ninclude(srcdir(\"style.jl\"))\nusing DynamicalSystems, PyPlot, Random\n\nlo = Systems.lorenz([0, 10, 0.0])\ntr = trajectory(lo, 1000; Ttr=10, reltol = 1e-12, abstol = 1e-12)\nx, y, z = columns(tr)\nw = x\nτ = estimate_delay(w, \"mi_min\")\nR = embed(w, 3, τ)\n\nclose(\"all\")\nN = 5000\nfig = figure()\nax1 = subplot(131, projection = \"3d\")\nax1.plot3D(x[1:N], y[1:N], z[1:N], lw = 1.0, color = \"C0\")\nax1.set_title(\"original set \\$A\\$\", pad = 0)\nax = ax1\nfor a in (ax.xaxis, ax.yaxis, ax.zaxis); a.set_ticklabels([]); end\n# ax1.text(-20, -20, 0, \"\\$D_0(A)\\$ = $(round(D_A;digits=3))\", color = \"C1\")\n\nax2 = subplot(132)\nwx = 2400:3200\nax2.plot(wx, w[wx])\nmidpoint = (wx[1] + wx[end])/2\ntau = midpoint:(midpoint+τ)\nax2.plot(tau, fill(10, length(tau)), color = \"C3\")\nax2.text(midpoint, 7.5, \"\\$\\\\tau\\$\", color = \"C3\", size = 32)\nax2.set_title(\"measurement \\$w=x\\$\")\n# make fancy axis\nax2.spines[\"bottom\"].set_position(\"center\")\nax2.spines[\"right\"].set_color(\"none\")\nax2.spines[\"top\"].set_color(\"none\")\nax2.set_xticks([])\nax2.set_yticks([])\nax2.set_xlabel(\"\\$t\\$\")\nax2.set_ylabel(\"\\$w\\$\", rotation = 0)\nax2.xaxis.set_label_coords(1.0, 0.5)\nax2.yaxis.set_label_coords(-0.05, 0.9)\n\nax3 = subplot(133, projection = \"3d\")\nax3.plot(R[1:N, 1], R[1:N, 2], R[1:N, 3], color = \"C1\", lw = 1.0)\nax = ax3\nfor a in (ax.xaxis, ax.yaxis, ax.zaxis); a.set_ticklabels([]); end\nax3.set_title(\"reconstruction \\$R\\$\", pad = 0)\n# ax3.set_title(\"reconstruction \\$R\\$\\n\\$(\\\\gamma=$(γ),\\\\tau=$(τ))\\$\")\n# ax3.text(-5,-25,-10, \"\\$D_0(R)\\$ = $(round(D_R;digits=3))\", color = \"C2\")\nax1.dist = 9\nax3.dist = 9\n\nfig.tight_layout(pad = 0.3)\nwsave(plotsdir(\"6\", \"delayembedding\"), fig)", "meta": {"hexsha": "cfde935f56477232c5087055457126637706e42f", "size": 1726, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "figure_generation/6/6.1.jl", "max_stars_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_stars_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 88, "max_stars_repo_stars_event_min_datetime": "2021-07-18T20:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T09:23:53.000Z", "max_issues_repo_path": "figure_generation/6/6.1.jl", "max_issues_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_issues_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figure_generation/6/6.1.jl", "max_forks_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_forks_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-07-28T18:49:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:45:11.000Z", "avg_line_length": 31.962962963, "max_line_length": 76, "alphanum_fraction": 0.6332560834, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.868826777936422, "lm_q1q2_score": 0.779941717722234}}
{"text": "#!/usr/bin/env julia\n#\n# Jerzy Wroczyński (nr. indeksu 250075)\n# Obliczenia Naukowe, Laboratorium\n# Lista 2, Zadanie 1.\n#\n\n# assert ARGS\nerr_mess = \"provide two arguments: [64, 32] [up, down, max_to_min, min_to_max]\"\nif length(ARGS) != 2\n    println(err_mess)\n    exit(1)\nend\n\n# name the arguments\nfl_str = ARGS[1]\nmode = ARGS[2]\n\n# parse the arguments\nif !in(fl_str, [\"64\", \"32\"]) || !in(mode, [\"up\", \"down\", \"max_to_min\", \"min_to_max\"])\n    println(err_mess)\n    exit(1)\nend\n\nfl = Float64\n\n# apply the first argument\nif fl_str== \"32\"\n    global fl = Float32\nend\n# end assert\n\n# x₄ and x₅ were altered\nx = [2.718281828, -3.141592654, 1.414213562, 0.577215664, 0.301029995]\ny = [1486.2497, 878366.9879, -22.37492, 4773714.647, 0.000185049]\n\nfunction calc_scalar_product(x, y)\n    S = fl(0)\n    # (a), (b)\n    if in(mode, [\"up\", \"down\"])\n        # change the direction of the range depending on the provided program argument\n        for i in (mode == \"down\" ? (5:-1:1) : (1:5))\n            S = fl(S + fl(x[i] * y[i]))\n        end\n    # (c), (d)\n    elseif in(mode, [\"max_to_min\", \"min_to_max\"])\n        # save partial products\n        mid_positive::Array{fl} = []\n        mid_negative::Array{fl} = []\n        # iterate over the vectors\n        for i in (1:5)\n            out = fl(x[i] * y[i])\n            if out < fl(0)\n                push!(mid_negative, out)\n            else\n                push!(mid_positive, out)\n            end\n        end\n\n        # sort the partial products\n        sort!(mid_negative, rev=(mode == \"max_to_min\"))\n        sort!(mid_positive, rev=(mode == \"max_to_min\"))\n\n        # add the partial products\n        S_positive = fl(0)\n        S_negative = fl(0)\n        for i in (1:length(mid_negative))\n            S_negative = fl(S_negative + mid_negative[i])\n        end\n        for i in (1:length(mid_positive))\n            S_positive = fl(S_positive + mid_positive[i])\n        end\n        # finally, add the partial sums\n        S = fl(S_positive + S_negative)\n    end\n    return S\nend\n\n# print out the results\nprintln(calc_scalar_product(x,y))\n", "meta": {"hexsha": "bed4a4480524a760600f98be6ecedacdb0cfa03c", "size": 2073, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5th-semester/on/lab/lista-2/ex-1.jl", "max_stars_repo_name": "jerry-sky/academic-notebook", "max_stars_repo_head_hexsha": "be2d350289441b99168ea40412891bc65b9cb431", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-28T21:53:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T19:24:47.000Z", "max_issues_repo_path": "5th-semester/on/lab/lista-2/ex-1.jl", "max_issues_repo_name": "jerry-sky/academic-notebook", "max_issues_repo_head_hexsha": "be2d350289441b99168ea40412891bc65b9cb431", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-02-13T18:07:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T18:16:07.000Z", "max_forks_repo_path": "5th-semester/on/lab/lista-2/ex-1.jl", "max_forks_repo_name": "jerry-sky/academic-notebook", "max_forks_repo_head_hexsha": "be2d350289441b99168ea40412891bc65b9cb431", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-28T16:05:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T16:20:00.000Z", "avg_line_length": 25.5925925926, "max_line_length": 86, "alphanum_fraction": 0.5750120598, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.7799417126013649}}
{"text": "using Optim\n\nf(x) = -sin(x[1]^2/2 - x[2]^2/4 + 3) * cos(2x[1] + 1 - exp(x[2])) # Same as last section\nres = optimize(f, [0, 0.5])\n\nfunction df(x) \n    # Same as last section\n    a1 = x[1]^2/2 - x[2]^2/4 + 3\n    a2 = 2x[1] + 1 - exp(x[2])\n    b1 = cos(a1)*cos(a2)\n    b2 = sin(a1)*sin(a2)\n    return -[x[1]*b1 - 2b2, -x[2]/2*b1 + exp(x[2])*b2]\nend\nres = optimize(f, df, [0, 0.5]; inplace=false)\n\nres = optimize(f, df, [0, 0.5], GradientDescent(); inplace=false)\n\nres = optimize(f, [0, 0.5], GradientDescent(); autodiff=:forward)\n\nres = optimize(f, [0, 0.5], Newton(); autodiff=:forward)\n\nres = optimize(f, [0, 0.5], BFGS(); autodiff=:forward)\n", "meta": {"hexsha": "f1ed8c6bb209392edee51f79a56883eb2319579a", "size": 642, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Optimization/Optim_Package.jl", "max_stars_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_stars_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "textbook/_build/jupyter_execute/content/Optimization/Optim_Package.jl", "max_issues_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_issues_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "textbook/_build/jupyter_execute/content/Optimization/Optim_Package.jl", "max_forks_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_forks_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9130434783, "max_line_length": 88, "alphanum_fraction": 0.5576323988, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660936744719, "lm_q2_score": 0.8175744717487329, "lm_q1q2_score": 0.7799383251021086}}
{"text": "module XiCor\n\nusing Random\n\nexport xicor\n\n\"\"\"\n    xicor(X, Y[, break_ties_randomly=false[, rng=nothing]])\n\nComputes the correlation ξ between X and Y.\n\nUnlike most coefficients of correlation, ξ ranges from -0.5 to 1.\n\nIf there are duplicate values in X, then ties are\nbroken based on the order in which they are observed.\nIf the order of X is not random, then you should\nset `break_ties_randomly` to `true` to avoid a biased\nestimate. You can use the `rng` parameter to\ndeterministically break ties.\n\nSee _A new coefficient of correlation_ by Chatterjee.\n\n[arXiv:1909.10140 [math.ST]](https://arxiv.org/abs/1909.10140)\n\n# Examples\n```julia-repl\njulia> ξ = xicor(1:100, 1:100)\n0.9702970297029703\njulia> x = trunc.((1:100) ./ 10);  # create x with lots of duplicates\njulia> y = rand(MersenneTwister(0), 100);\njulia> ξ = xicor(x, y, true, MersenneTwister(0))\n-0.01830183018301823\njulia> ξ = xicor(x, y, true, MersenneTwister(42))\n0.004500450045004545\n```\n\"\"\"\nfunction xicor(X, Y, break_ties_randomly=false, rng=nothing)\n    if break_ties_randomly\n        if !isnothing(rng)\n            index = randperm(rng, length(X))\n        else\n            index = randperm(length(X))\n        end\n        X = X[index]\n        Y = Y[index]\n    end\n    n = length(X)\n    Y = Y[sortperm(X)]  # how should offset arrays be handled?\n    sorter = sortperm(Y)\n    R = zeros(Int, n)  # R[i] is the number of j such that Y[j] ≤ Y[i]\n    L = zeros(Int, n)  # L[i] is the number of j such that Y[j] ≥ Y[i]\n\n    i = 1\n    while i <= n\n        curr = Y[sorter[i]]\n        counter = 1\n        i += 1  # look ahead for repeated Y values\n        while i <= n && Y[sorter[i]] == curr\n            counter += 1\n            i += 1\n        end\n        i -= 1\n        for j = i-counter+1:i  # fill in R and L values wherever Y == curr\n            R[sorter[j]] = i\n            L[sorter[j]] = (n-i) + counter\n        end\n        i += 1\n    end\n\n    1 - n * sum(abs.(diff(R))) / (2 * sum(L .* (n .- L)))\nend\n\nend # module\n", "meta": {"hexsha": "bcc089c0d9d0360cada7ed6a334e1fb511bbace9", "size": 1982, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/XiCor.jl", "max_stars_repo_name": "kbrose/XiCor.jl", "max_stars_repo_head_hexsha": "27c8da01bf03dd6880774a7176934ace32305610", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/XiCor.jl", "max_issues_repo_name": "kbrose/XiCor.jl", "max_issues_repo_head_hexsha": "27c8da01bf03dd6880774a7176934ace32305610", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/XiCor.jl", "max_forks_repo_name": "kbrose/XiCor.jl", "max_forks_repo_head_hexsha": "27c8da01bf03dd6880774a7176934ace32305610", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7837837838, "max_line_length": 74, "alphanum_fraction": 0.6024217962, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.8633916222765627, "lm_q1q2_score": 0.7798966550144958}}
{"text": "######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n@doc \"\"\"\n    \n    kalmanFilter(data, ssmodel)\n\nDescription: \nApply Kalman filter to observed data. \nMeasurement Equation:   \n    y_{t} = H_{t} β_{t} + A z_{t} + e_{t} .\nTransition Equation:    \n    β_{t} = μ + F β_{t-1} + v_{t};\n    e_{t} ~ i.i.d.N(0,R);\n    v_{t} ~ i.i.d.N(0,Q);\n    z_{t} ~ i.i.d.N(0,Z);\n    E(e_t v_s') = 0.\n\nInputs: \n- data      = observed data \n- H         = measurement eq. state coef. matrix\n- A         = measurement eq. exogenous coef. matrix\n- F         = state eq. companion matrix\n- μ         = state eq. intercept term\n- R         = covariance matrix on measurement disturbance\n- Q         = covariance matrix on state disturbance\n- Z         = covariance matrix on predetermined var vector \n\"\"\"\nfunction kalmanFilter(data_y, ssmodel)\n\n    @unpack H, A, F, μ, R, Q, Z = ssmodel\n\n    # Save number of observations \n    num_obs = size(data_y)[1]\n\n    # Empty filtered data matrices \n    data_filtered_y = similar(data_y)\n    data_filtered_β = zeros(num_obs, size(Q)[1])\n\n    # Create empty lists for P_{t}, P_{t|t-1}\n    Ptt = Any[]\n    Pttlag = Any[]\n\n    # Initialize β_pred and P_pred \n    β_pred_laglag = inv(I - F) * μ\n    P_pred_laglag = ones(size(Q)[1], size(Q)[1])\n\n    for t = 1:num_obs\n        # Save current obs of y\n        y = data_y[t, :]\n\n        # Prediction \n        β_pred_lag = μ + F * β_pred_laglag\n        P_pred_lag = F * P_pred_laglag * transpose(F) + Q\n        y_pred_lag = H * β_pred_lag\n        η_pred_lag = y - y_pred_lag\n        f_pred_lag = H * P_pred_lag * transpose(H) + R\n\n        # Save P_{t|t-1}\n        push!(Pttlag, P_pred_lag)\n\n        # Updating \n        K = P_pred_lag * transpose(H) * pinv(f_pred_lag)\n        β_pred = β_pred_lag + K * η_pred_lag\n        P_pred = P_pred_lag - K * H * P_pred_lag\n\n        # Save P_{t|t}\n        push!(Ptt, P_pred)\n\n        # Save data \n        data_filtered_y[t, :] = y_pred_lag\n        data_filtered_β[t, :] = β_pred\n\n        # Lag the predictions \n        β_pred_laglag = β_pred\n        P_pred_laglag = P_pred\n    end\n\n    # Returned filtered series \n    # for obs variable and state \n    return data_filtered_y, data_filtered_β, Pttlag, Ptt\nend;\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n@doc \"\"\"\n    \n    kalmanSmoother(data, ssmodel)\n\nDescription: \nApply Kalman smoother to observed data. \nMeasurement Equation:   \n    y_{t} = H_{t} β_{t} + A z_{t} + e_{t}.\nTransition Equation:    \n    β_{t} = μ + F β_{t-1} + v_{t};\n    e_{t} ~ i.i.d.N(0,R);\n    v_{t} ~ i.i.d.N(0,Q);\n    z_{t} ~ i.i.d.N(0,Z);\n    E(e_t v_s') = 0.\n\nInputs: \n- data      = observed data \n- H         = measurement eq. state coef. matrix\n- A         = measurement eq. exogenous coef. matrix\n- F         = state eq. companion matrix\n- μ         = state eq. intercept term\n- R         = covariance matrix on measurement disturbance\n- Q         = covariance matrix on state disturbance\n- Z         = covariance matrix on predetermined var vector \n\"\"\"\nfunction kalmanSmoother(data_y, ssmodel)\n\n    @unpack H, A, F, μ, R, Q, Z = ssmodel\n\n    # Save number of observations \n    num_obs = size(data_y)[1]\n\n    # Empty filtered data matrices \n    data_smoothed_y = similar(data_y)\n    data_smoothed_β = zeros(num_obs, size(Q)[1])\n\n    # Create empty list for P_{t|T}\n    PtT = Any[]\n\n    # Run Kalman filter \n    data_filtered_y, data_filtered_β, Pttlag, Ptt = kalmanFilter(data_y, ssmodel)\n\n    # Initialize β_{t+1|T} (β_{T|T})\n    βtflagT = data_filtered_β[end]\n    data_smoothed_β[end] = βtflagT\n\n    # Initialize P_{t+1|T} (P_{T|T})\n    Ptflag_T = Ptt[end]\n    push!(PtT, Ptflag_T)\n\n    # Initialize y_{t|T} (y_{T|T})\n    data_smoothed_y[end] = data_filtered_y[end]\n\n    # Run Kalman smoother \n    for i = 1:(num_obs-1)\n\n        # Retrieve β_{t|t}\n        βtt = data_filtered_β[end-i]\n\n        # Compute β_{t|T} using β_{t+1|T}, β_{t|t}, P_{t|t}, and P_{t+1|t}\n        βtT = βtt +\n              Ptt[end-i] * transpose(F) * inv(Pttlag[end-i+1]) *\n              (βtflagT - F * βtt - μ)\n\n        # Store β_{t+1|T} in smoothed data \n        data_smoothed_β[end-i] = βtT\n\n        # Set β_{t|T} as new β_{t+1|T} for next iteration \n        βtflagT = βtT\n\n        # Compute P_{t|T} using P_{t|t}, P_{t+1|t}, and P_{t+1|T}\n        Pt_T = Ptt[end-i] +\n               Ptt[end-i] * transpose(F) * inv(Pttlag[end-i+1]) *\n               (Ptflag_T - Pttlag[end-i+1]) *\n               transpose(Ptt[end-i] * transpose(F) * inv(Pttlag[end-i+1]))\n\n        # Store P_{t|T}\n        push!(PtT, Pt_T)\n\n        # Set P_{t|T} as new P_{t+1|T} for next iteration \n        Ptflag_T = Pt_T\n\n        # Generate y_{t|T} (smoothed obs.)\n        ytT = H * βtT\n\n        # Store smoothed obs.\n        data_smoothed_y[end-i] = ytT\n    end\n\n    # Flip P_{t|T} list \n    PtT = reverse(PtT)\n\n    # Returned filtered series \n    # for obs variable and state \n    return data_smoothed_y, data_smoothed_β, PtT\nend;\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n@doc \"\"\"\n    \n    KNFactorSampler(data_y, ssmodel)\n\nDescription: \nDraw a sample series of dynamic factor from conditional distribution in Ch 8, Kim & Nelson (1999).\nMeasurement Equation:   \n    y_{t} = H_{t} β_{t} + A z_{t} + e_{t}.\nTransition Equation:    \n    β_{t} = μ + F β_{t-1} + v_{t};\n    e_{t} ~ i.i.d.N(0,R);\n    v_{t} ~ i.i.d.N(0,Q);\n    z_{t} ~ i.i.d.N(0,Z);\n    E(e_t v_s') = 0.\n\nInputs: \n- data      = observed data \n- H         = measurement eq. state coef. matrix\n- A         = measurement eq. exogenous coef. matrix\n- F         = state eq. companion matrix\n- μ         = state eq. intercept term\n- R         = covariance matrix on measurement disturbance\n- Q         = covariance matrix on state disturbance\n- Z         = covariance matrix on predetermined var vector \n\"\"\"\nfunction KNFactorSampler(data_y, ssmodel)\n\n    @unpack H, A, F, μ, R, Q, Z = ssmodel\n\n    # Run Kalman filter \n    data_filtered_y, data_filtered_β, Pttlag, Ptt = kalmanFilter(data_y, ssmodel)\n\n    # Create placeholders for factor distr. \n    # mean vector and covariance matrix for all t \n    β_t_mean = Any[]\n    β_t_var = Any[]\n\n    # Record number of time periods \n    T = size(data_y)[1]\n\n    # Create empty vector for factor realizations\n    β_realized = similar(data_filtered_β)\n\n    # Initialize β_realized \n    push!(β_t_mean, data_filtered_β[T, :])\n    push!(β_t_var, Ptt[T])\n    β_realized[T, :] = sim_MvNormal_alt(β_t_mean[1], β_t_var[1])\n\n    # Generate `β_t_mean` and `β_t_var`\n    # for all time periods \n    if isposdef(Q) == false\n        ## IF Q IS SINGULAR \n\n        # Determine number of rows\n        # of state factor used \n        num_use_rows = 0\n        for i = 1:size(Q)[1]\n            if Q[i, i] != 0\n                num_use_rows += 1\n            end\n        end\n\n        # Create modified F and Q matrices \n        F_star = F[1:num_use_rows, :]\n        Q_star = Q[1:num_use_rows, 1:num_use_rows]\n\n        # Iteratively generate conditional draws \n        # of state vector \n        for j = 1:(T-1)\n\n            # β_{t|t,β*_{t+1}}\n            β_t_mean_temp = data_filtered_β[T-j, :]\n            +Ptt[T-j] * transpose(F_star) * inv(F_star * Ptt[T-j] * transpose(F_star) + Q_star) * (β_realized[T+1-j, :][1:num_use_rows] - μ[1:num_use_rows] - F_star * data_filtered_β[T-j, :])\n            push!(β_t_mean, β_t_mean_temp)\n\n            # P_{t|t,β*_{t+1}}\n            β_t_var_temp = Ptt[T-j] - Ptt[T-j] * transpose(F_star) * inv(F_star * Ptt[T-j] * transpose(F_star) + Q_star) * F_star * Ptt[T-j]\n            push!(β_t_var, β_t_var_temp)\n\n            # Draw new β_t \n            β_realized[T-j, :] = sim_MvNormal_alt(β_t_mean[1+j], β_t_var[1+j])\n        end\n    else\n        ## IF Q IS NOT SINGULAR (redundant, but potentially faster) \n        for j = 1:(T-1)\n\n            # β_{t|t,β_{t+1}}\n            β_t_mean_temp = data_filtered_β[T-j, :]\n            +Ptt[T-j] * transpose(F) * inv(F * Ptt[T-j] * transpose(F) + Q) * (β_realized[T+1-j, :] - μ - F * data_filtered_β[T-j, :])\n            push!(β_t_mean, β_t_mean_temp)\n\n            # P_{t|t,β_{t+1}}\n            β_t_var_temp = Ptt[T-j] - Ptt[T-j] * transpose(F) * inv(F * Ptt[T-j] * transpose(F) + Q) * F * Ptt[T-j]\n            push!(β_t_var, β_t_var_temp)\n\n            # Draw new β_t \n            β_realized[T-j, :] = sim_MvNormal_alt(β_t_mean[1+j], β_t_var[1+j])\n        end\n    end\n\n    # Return sampled factor series \n    # fot t = 1,...,T \n    return β_realized\nend;\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n@doc \"\"\"\n    \n    linearRegressionSampler(Y,X)\n\nDescription: \nEstimate β and σ^2 in Y = Xβ + e, e ~ N(0,σ^2 I_T).\nGenerate samples of β and σ^2. \n\nInputs: \n- Y     = Dependent data matrix\n- X     = Independent data matrix \n\"\"\"\nfunction linearRegressionSampler(Y, X)\n\n    # Save number of obs \n    T = size(X)[1]\n\n    # Initialize σ2 \n    σ2 = 1.0\n\n    ##################################\n    ##################################\n    # Generate new β\n\n    ## Prior parameters in N(β0,Σ0)\n    β0 = zeros(size(X)[2])\n    Σ0 = Matrix(I, size(β0)[1], size(β0)[1]) .* 1000.0\n\n    ## Posterior parameters in N(β1,Σ1) \n    β1 = inv(inv(Σ0) + inv(σ2) * transpose(X) * X) * (inv(Σ0) * β0 + inv(σ2) * transpose(X) * Y)\n    β1 = vec(β1)\n    Σ1 = inv(inv(Σ0) + inv(σ2) * transpose(X) * X)\n    Σ1 = Hermitian(Σ1)\n\n    ## Generate new β\n    β = sim_MvNormal(β1, Σ1)\n\n    ##################################\n    ##################################\n    # Update σ2\n\n    ## Prior parameters in IG(ν0/2, δ0/2) \n    ν0 = 0.002\n    δ0 = 0.002\n\n    ## Posterior parameters in IG(ν1/2, δ1/2)\n    ν1 = ν0 + T\n    δ1 = δ0 + norm(Y - X * β)^2\n\n    ## Generate new σ2\n    σ2 = rand(InverseGamma(ν1 / 2, δ1 / 2))\n\n    ##################################\n    ##################################\n    # Return parameters \n    return β, σ2\nend;\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n@doc \"\"\"\n    \n    linearRegressionSamplerRestrictedVariance(Y, X, σ2)\n\nDescription: \nEstimate β and σ^2 in Y = Xβ + e, e ~ N(0,σ^2 I_T),\nwhere σ^2 is restricted to some chosen value. \nGenerate samples of β and σ^2. \n\nInputs: \n- Y     = Dependent data matrix\n- X     = Independent data matrix \n- σ2    = Restricted error variance \n\"\"\"\nfunction linearRegressionSamplerRestrictedVariance(Y, X, σ2)\n\n    # Save number of obs \n    T = size(X)[1]\n\n    ##################################\n    ##################################\n    # Generate new β\n\n    ## Prior parameters in N(β0,Σ0)\n    β0 = zeros(size(X)[2])\n    Σ0 = Matrix(I, size(β0)[1], size(β0)[1]) .* 1000.0\n\n    ## Posterior parameters in N(β1,Σ1) \n    β1 = inv(inv(Σ0) + inv(σ2) * transpose(X) * X) * (inv(Σ0) * β0 + inv(σ2) * transpose(X) * Y)\n    β1 = vec(β1)\n    Σ1 = inv(inv(Σ0) + inv(σ2) * transpose(X) * X)\n    Σ1 = Hermitian(Σ1)\n\n    ## Generate new β\n    β = sim_MvNormal(β1, Σ1)\n\n    ##################################\n    ##################################\n    # Return parameters \n    return β\nend;\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n@doc \"\"\"\n    \n    autocorrErrorLinearRegressionSampler(Y, X, error_lag_num)\n\nDescription: \nEstimate β, σ^2, and ϕ in Y = Xβ + e, e = Eϕ + ν, ν_t ~ i.i.d.N(0,σ^2).  \nGenerate samples of β, σ^2, and ϕ.  \nProcedure descried in Section 7.4.2 in Kim & Nelson.\n\nInputs: \n- Y             = Dependent data matrix\n- X             = Independent data matrix \n- error_lag_num = Number of lags in the disturbance DGP \n\"\"\"\n\nfunction autocorrErrorLinearRegressionSampler(Y, X, ϕold, σ2old, error_lag_num)\n\n    # Save number of obs \n    T = size(X)[1]\n\n    # Initialize σ2 \n    ϕ = ϕold\n    σ2 = σ2old\n\n    ##################################\n    ##################################\n    # Generate β\n\n    ## Prior parameters in N(b0,A0)\n    b0 = zeros(size(X)[2])\n    A0 = Matrix(I, size(b0)[1], size(b0)[1]) .* 1000.0\n\n    ## Generate X^⋆ \n    X_star = similar(X[(1+length(ϕ)):end, :])\n    for i = 1:size(X)[2] # iterate over variables in X\n        x_temp = X[:, i]\n        for p = 1:length(ϕ) # iterate over lag params in ϕ\n            x_temp[(1+length(ϕ)):end, :] = x_temp[(1+length(ϕ)):end, :] - ϕ[p] .* lag(x_temp, p)[(1+length(ϕ)):end, :]\n        end\n        x_temp = x_temp[(1+length(ϕ)):end, :]\n        X_star[:, i] = x_temp\n    end\n\n    ## Generate Y^⋆\n    Y_star = similar(Y[(1+length(ϕ)):end, :])\n    y_temp = Y\n    for p = 1:length(ϕ)\n        y_temp = Y\n        y_temp = y_temp[(1+length(ϕ)):end, :] - ϕ[p] .* lag(y_temp, p)[(1+length(ϕ)):end, :]\n    end\n    Y_star = y_temp\n\n    ## Posterior parameters in N(b1,A1) \n    b1 = inv(inv(A0) + inv(σ2) * transpose(X_star) * X_star) * (inv(A0) * b0 + inv(σ2) * transpose(X_star) * Y_star)\n    b1 = vec(b1)\n    A1 = inv(inv(A0) + inv(σ2) * transpose(X_star) * X_star)\n    A1 = Hermitian(A1)\n\n    ## Draw new β\n    β = sim_MvNormal(b1, A1)\n\n    ##################################\n    ##################################\n    # Generate ϕ\n\n    ## Prior parameters in N(c0,B0)\n    c0 = zeros(size(ϕ)[1])\n    B0 = Matrix(I, size(c0)[1], size(c0)[1]) .* 1000.0\n\n    ## Generate e^⋆ \n    e_star = Y - X * β\n\n    ## Generate E^⋆\n    E_star = zeros(T, length(ϕ))\n    E_star = E_star[(1+length(ϕ)):end, :]\n    for i = 1:(size(E_star)[2]) # iterate over variables in X\n        e_temp = lag(e_star, i)\n        E_star[:, i] = e_temp[(1+length(ϕ)):end]\n    end\n    e_star = e_star[(1+length(ϕ)):end]\n\n    ## Posterior parameters in N(c1,B1)\n    c1 = inv(inv(B0) + inv(σ2) * transpose(E_star) * E_star) * (inv(B0) * c0 + inv(σ2) * transpose(E_star) * e_star)\n    c1 = vec(c1)\n    B1 = inv(inv(B0) + inv(σ2) * transpose(E_star) * E_star)\n    B1 = Hermitian(B1)\n\n    ## Generate new ϕ\n    ###=\n    ind = 0\n    accept = 0\n    ϕ = similar(ϕold)\n    while accept == 0\n\n        ind += 1\n\n        ## Draw ψ\n        ϕ = sim_MvNormal(c1, B1)\n\n        ## Check for stationarity \n        coef = [-reverse(vec(ϕ), dims = 1); 1]                      # check stationarity \n        root = roots(Polynomial(reverse(coef)))\n        rootmod = abs.(root)\n        accept = min(rootmod...) >= 1.01\n\n        ## If while loop goes on for too long \n        if ind > 100\n            ϕ = ϕold\n            coef = [-reverse(vec(ϕ), dims = 1); 1]                      # check stationarity \n            root = roots(Polynomial(reverse(coef)))\n            rootmod = abs.(root)\n            accept = min(rootmod...) >= 1.01\n        end\n    end\n    ##=#\n\n    #ϕ = sim_MvNormal(c1, B1)\n\n\n    ##################################\n    ##################################\n    # Generate σ2\n\n    ## Prior parameters in IG(ν0/2, δ0/2) \n    ν0 = 0.002\n    δ0 = 0.002\n\n    ## Posterior parameters in IG(ν1/2, δ1/2)\n    ν1 = ν0 + T\n    δ1 = δ0 .+ norm(Y_star - X_star * β)^2\n    δ1 = δ1[1, 1]\n\n    ## Generate new σ2\n    σ2 = rand(InverseGamma(ν1 / 2, δ1 / 2))\n\n    ##################################\n    ##################################\n    # Return parameters \n    return β, σ2, ϕ\nend;\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################", "meta": {"hexsha": "e16a693e088e38e95497e7a3ca84275a856f2c6e", "size": 16404, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kim_nelson/kn_tools.jl", "max_stars_repo_name": "gionikola/DynamicFactorModeling.jl", "max_stars_repo_head_hexsha": "e52471e4b16b6a9ead53996d571d49ba8c0e9e91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kim_nelson/kn_tools.jl", "max_issues_repo_name": "gionikola/DynamicFactorModeling.jl", "max_issues_repo_head_hexsha": "e52471e4b16b6a9ead53996d571d49ba8c0e9e91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2021-12-14T00:30:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T21:33:09.000Z", "max_forks_repo_path": "src/kim_nelson/kn_tools.jl", "max_forks_repo_name": "gionikola/DynamicFactorModeling.jl", "max_forks_repo_head_hexsha": "e52471e4b16b6a9ead53996d571d49ba8c0e9e91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2945091514, "max_line_length": 191, "alphanum_fraction": 0.4690929042, "num_tokens": 4912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7798928022680385}}
{"text": "include(\"FractalDimensions.jl\")\n\n#S_0 = [[0.0,0.0], [1.0,0.0], [0.5,1.0]]\nS_0 = [[0.0,0.0], [1.0,0.0], [0.5,2.0]]\n#S_0 = [[0.0,0.0], [1.0,0.0], [0.0,1.0]]\n\nf1(x) = (S_0[1]+x)/2\nf2(x) = (S_0[2]+x)/2\nf3(x) = (S_0[3]+x)/2\n\n# WARNING This will use up your memory and slow down your computer for k>10\nfunction sierpinsky_endpoints(k)\n        s::Vector{Vector{Float64}} = []\n        s1 = S_0\n        for i in 1:k\n            s2 = setdiff([f1.(s1); f2.(s1); f3.(s1)], s1)\n            append!(s, s1)\n            s1 = s2\n        end\n    return s\nend\n\ns = sierpinsky_endpoints(10)\n\nusing Plots\nx = [u[1] for u in s]\ny = [u[2] for u in s]\n\nplotlyjs()\nscatter(x,y, markersize=1, markerstrokealpha=0.0, legend=false)\nsavefig(\"sierpinsky.eps\")\n\nd, N, ε = box_counting_dimension(s, 9, 0.0)\n\nloglog_regression(N,ε)\n\nlog(3)/log(2)\n\nplot(-log.(ε), log.(N), xlabel=\"-ln ε\", ylabel=\"ln N\", marker=:d, legend=false)\nsavefig(\"boxdim_sierpinsky.eps\")\n\nC, r = correlation_dimension(s)\n\nloglog_regression(C,r)\n\nplot(log.(r), log.(C), xlabel=\"ln r\", ylabel=\"ln C\", marker=:d, legend=false)\nsavefig(\"cordim_sierpinsky.eps\")\n", "meta": {"hexsha": "925aa4596eadc890e31131f26360ddaf7ffe0b65", "size": 1097, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "sierpinsky.jl", "max_stars_repo_name": "csimal/chaos-and-fractals", "max_stars_repo_head_hexsha": "4b189b0fde62d480f1f2e750b976de54bd9d2297", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sierpinsky.jl", "max_issues_repo_name": "csimal/chaos-and-fractals", "max_issues_repo_head_hexsha": "4b189b0fde62d480f1f2e750b976de54bd9d2297", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sierpinsky.jl", "max_forks_repo_name": "csimal/chaos-and-fractals", "max_forks_repo_head_hexsha": "4b189b0fde62d480f1f2e750b976de54bd9d2297", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8541666667, "max_line_length": 79, "alphanum_fraction": 0.5907019143, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.779892802121696}}
{"text": "function acqr_ksmoother(a,xtt,Ptt,xtt1,Ptt1)\n\t#\n\t# Kalman smoother for model\n\t#\n\t# x_{t+1} = ax_{t} + w_{t}\n\t# y_{t}   = cx_{t} + v_{t}\n\t#\n\t# cov(w_{t},v_{t}) = [q 0;0 r]\n\t#\n\t# javier.cara@upm.es, 2020-05\n\t#\n\n\tnt = length(xtt)\n\n\t# allocation\n\txtN = zeros(nt+1)\n\tPtN = zeros(nt+1)\n\tPt1tN = zeros(nt)\n\n\t# values for t = nt+1\n\txtN[nt+1] = xtt1[nt+1]\n\tPtN[nt+1] = Ptt1[nt+1]\n\n\t# values for t=nt\n\txtN[nt] = xtt[nt]\n\tPtN[nt] = Ptt[nt]\n\tPt1tN[nt] = a*Ptt[nt]\n\n\t# smother\n\tfor t = nt-1:-1:1\n\t\t# Kalman Smoother matrix J\n\t\tJt = (Ptt[t]*a) / Ptt1[t+1]\n\n\t\txtN[t] = xtt[t] + Jt*( xtN[t+1] - xtt1[t+1] )\n\t\tPtN[t] = Ptt[t] + Jt^2*( PtN[t+1] - Ptt1[t+1] )\n\n\t\tPt1tN[t] = PtN[t+1]*Jt\n\tend\n\n\treturn xtN,PtN,Pt1tN\n\nend\n", "meta": {"hexsha": "c15c5f09d73ae1ea4bd653cdf7aeaa2b942627d9", "size": 700, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/acqr/acqr_ksmoother.jl", "max_stars_repo_name": "javiercara/StateSpaceModelsEM.jl", "max_stars_repo_head_hexsha": "989d538b01274885e4579df130f9b38bbb99cc7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/acqr/acqr_ksmoother.jl", "max_issues_repo_name": "javiercara/StateSpaceModelsEM.jl", "max_issues_repo_head_hexsha": "989d538b01274885e4579df130f9b38bbb99cc7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/acqr/acqr_ksmoother.jl", "max_forks_repo_name": "javiercara/StateSpaceModelsEM.jl", "max_forks_repo_head_hexsha": "989d538b01274885e4579df130f9b38bbb99cc7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.2790697674, "max_line_length": 49, "alphanum_fraction": 0.5457142857, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7798928003557363}}
{"text": "#####################\n# Utility Functions #\n#####################\n\n\"\"\"\nKronecker Delta Function.\n\nReturns 1 if inputs are equal returns 0 otherwise.\n\nArguments:\n- `a::Real`: First input argument\n- `b::Real`: Second input argument \n\nReturns:\n- `delta:Integer`: Kronecker delta result.\n\"\"\"\nfunction kron(a::Real, b::Real)\n    return a == b ? 1 : 0\nend\n\n\"\"\"\nInternal helper function to aid in denormalization of gravity field coefficients.\n\nProvides method co compute the factorial ratio: (n-m)!/(n+m)!\n\nArguments:\n- `n::Real`: Gravity model degree, n.\n- `m::Real`: Gravity model order, m.\n\nReturns:\n- `p::Real`: Factorial product\n\"\"\"\nfunction facprod(n::Int, m::Int)\n    p = 1.0\n\n    for i in (n-m+1):(n+m+1) # Is this correct? Should it be (n-m+1):(n+m)\n        p = p/i\n    end\n\n    return p\nend\n\n###########\n# Gravity #\n###########\n\nexport accel_point_mass\n\"\"\"\nComputes the acceleration of a satellite caused by a point-mass approximation \nof the central body. Returns the acceleration vector of the satellite.\n\nAssumes the satellite is much, much less massive than the central body.\n\nArguments:\n- `r_sat::Array{<:Real, 1}`: satellite position in a commonn inertial frame [m]\n- `r_body::Array{<:Real, 1}`: position of body in a commonn inertial frame [m]\n- `GM::Array{<:Real, 1}`: gravitational coeffient of attracting body [m^3/s^2] Default: SatelliteDynamics.GM_EARTH)\n(Default: SatelliteDynamics.GM_EARTH\n\nReturn:\n- `a::Array{<:Real, 1}`: Acceleration in X, Y, and Z inertial directions [m/s^2]\n\"\"\"\nfunction accel_point_mass(r_sat::Array{<:Real, 1}, r_body::Array{<:Real, 1}, gm_body::Real=GM_EARTH)\n    # Restrict inputs to position only\n    r_sat  = r_sat[1:3]\n    r_body = r_body[1:3]\n\n    # Relative position vector of satellite w.r.t. the attraching body\n    d = r_sat - r_body\n\n    # Acceleration\n    a = -gm_body * (d/norm(d)^3 + r_body/norm(r_body)^3)\n\n    return a\nend\n\n\"\"\"\nComputes the acceleration on a satellite caused by a point-mass approximation \nof a massive body. Returns the acceleration vector of the satellite.\n\nArguments:\n- `r_sat::Array{<:Real, 1}`: satellite position in the inertial frame [m]\n- `GM::Array{<:Real, 1}`: gravitational coeffient of attracting body [m^3/s^2] Default: SatelliteDynamics.GM_EARTH)\n(Default: SatelliteDynamics.GM_EARTH\n\nReturn:\n- `a::Array{<:Real, 1}`: Acceleration in X, Y, and Z inertial directions [m/s^2]\n\"\"\"\nfunction accel_point_mass(x::Array{<:Real, 1}, gm_body::Real=GM_EARTH)\n    # Restrict inputs to position only. Considered in body frame\n    r  = x[1:3]\n\n    # Acceleration\n    a = -gm_body * r/norm(r)^3\n\n    return a\nend\n\n\"\"\"\nCompute the gravitational acceleration at a model given a spherical harmonic\ngravity field model.\n\nArguments:\n- `r::Array{<:Real, 1}`: Position of the point in the body (field) fixed frame. [m]\n- `coef::Array{<:Real, 2}`: Gravity coefficients stored in dense matrix form. C_nm terns are stored along rows indexed from C_00 in coef[1, 1] to C_nm in coef[n+1, m+1]. S_nm terms are stored along matrix columns with S_n0 stored in coef[0, n+1]\n- `n_max::Integer`: Maximum degree coefficient to use in expansion\n- `m_max::Integer`: Maximum order coefficient to use in the expansion. Must be less than the degree.\n- `r_ref::Real`: Reference distance of the gravity field.\n- `GM::Real`: Gravitational constant of central body\n- `normralized::Bool`: Whether the input gravity field coefficients are normalized coefficients (Default: true)\n\nReturns:\n- `a::Array{<:Real, 1}`: Acceleration in X, Y, and Z inertial directions [m/s^2]\n\"\"\"\nfunction spherical_harmonic_gravity(r::Array{<:Real, 1}, coef::Array{<:Real, 2}, n_max::Integer, m_max::Integer, r_ref::Real, GM::Real; normalized::Bool=true)\n    # Intermediate computations\n    r_sqr = dot(r, r)\n    rho   = r_ref^2/r_sqr\n    x0    = r_ref * r[1] / r_sqr\n    y0    = r_ref * r[2] / r_sqr\n    z0    = r_ref * r[3] / r_sqr\n\n    # Initialize Intermediary Matrices\n    V = zeros(eltype(r), n_max+2, n_max+2)\n    W = zeros(eltype(r), n_max+2, n_max+2)\n\n    # Calculate zonal terms V(n, 0). Set W(n,0)=0.0\n    V[0+1, 0+1] = r_ref /sqrt(r_sqr)\n    W[0+1, 0+1] = 0.0\n\n    V[1+1, 0+1] = z0 * V[0+1, 0+1]\n    W[1+1, 0+1] = 0.0\n\n    for n in 2:(n_max+1)\n        V[n+1, 0+1] = ((2*n-1)*z0*V[n+1-1, 0+1] - (n-1)*rho*V[n+1-2,0+1])/n\n        W[n+1, 0+1] = 0.0\n    end\n\n    # Calculate tesseral and sectoral terms\n    for m in 1:m_max+1\n        # Calculate V(m,m) to V(n_max+1,m)\n        V[m+1, m+1] = (2*m-1)*(x0*V[m+1-1, m+1-1] - y0*W[m+1-1, m+1-1])\n        W[m+1, m+1] = (2*m-1)*(x0*W[m+1-1, m+1-1] + y0*V[m+1-1, m+1-1])\n\n        if m <= m_max\n            V[m+1+1, m+1] = (2*m+1)*z0*V[m+1,m+1]\n            W[m+1+1, m+1] = (2*m+1)*z0*W[m+1,m+1]\n        end\n\n        for n in (m+2):(n_max+1)\n            V[n+1,m+1] = ((2*n-1)*z0*V[n+1-1,m+1]-(n+m-1)*rho*V[n+1-2,m+1])/(n-m)\n            W[n+1,m+1] = ((2*n-1)*z0*W[n+1-1,m+1]-(n+m-1)*rho*W[n+1-2,m+1])/(n-m)\n        end\n    end\n\n    # Calculate accelerations\n    ax = 0.0\n    ay = 0.0\n    az = 0.0\n\n    for m in 0:m_max\n        for n in m:n_max\n            C = 0.0\n            S = 0.0\n            if m == 0\n                # Denormalize Coeeficients\n                if normalized\n                    N = sqrt(2*n+1)\n                    C = N*coef[n+1, 0+1]\n                else\n                    C = coef[n+1, 0+1]\n                end\n\n                ax -= C*V[n+1+1, 1+1]\n                ay -= C*W[n+1+1, 1+1]\n                az -= (n+1)*C*V[n+1+1, 0+1]\n\n            else\n                if normalized\n                    N = sqrt((2 - kron(0,m))*(2*n+1)*facprod(n,m))\n                    C = N*coef[n+1,   m+1]\n                    S = N*coef[m+1-1, n+1]\n                else\n                    C = coef[n+1,   m+1]\n                    S = coef[m+1-1, n+1]\n                end\n\n                fac =  0.5 * (n-m+1)*(n-m+2)\n                ax += +0.5 * (-C * V[n+1+1, m+1+1] - S * W[n+1+1, m+1+1])\n                      +fac * (+C * V[n+1+1, m+1-1] + S * W[n+1+1, m+1-1])\n                ay += +0.5 * (-C * W[n+1+1, m+1+1] + S * V[n+1+1, m+1+1])\n                      +fac * (-C * W[n+1+1, m+1-1] + S * V[n+1+1, m+1-1])\n                az += (n-m+1)*(-C*V[n+1+1, m+1] - S*W[n+1+1, m+1])\n            end\n        end\n    end\n\n    a = (GM / (r_ref^2)) * [ax, ay, az]\n\n    return a\nend\n\nexport accel_gravity\n\"\"\"\nComputes the accleration caused by Earth gravity as modeled by a spherical \nharmonic gravity field.\n\nArguments:\n- `r_sat::Array{<:Real, 1}`: Satellite position in the inertial frame [m]\n- `R_eci_ecef::Array{<:Real, 2}`: Rotation matrix transforming a vector from the inertial to body-fixed reference frames. \n- `n_max::Integer`: Maximum degree coefficient to use in expansion\n- `m_max::Integer`: Maximum order coefficient to use in the expansion. Must be less than the degree.\n    \nReturn:\n- `a::Array{<:Real, 1}`: Gravitational acceleration in X, Y, and Z inertial directions [m/s^2]\n\nReferences:\n1. O. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and Applications_, 2012, p.56-68.\n\"\"\"\nfunction accel_gravity(x::Array{<:Real, 1}, R_eci_ecef::Array{<:Real, 2}, n_max::Int=20, m_max::Int=20)\n    \n    # Check Limits of Gravity Field\n    if n_max > GRAVITY_MODEL.n_max\n        error(\"Requested gravity model order $n_max is larger than the maximum order of the model maximum: \", GRAVITY_MODEL.n_max)\n    end\n\n    if m_max > GRAVITY_MODEL.m_max\n        error(\"Requested gravity model degree $m_max is larger than the maximum degree of the model maximum: \", GRAVITY_MODEL.m_max)\n    end\n\n    # Gravitational parameters of primary body\n    GM    = GRAVITY_MODEL.GM\n    R_ref = GRAVITY_MODEL.R\n\n    # Body-fixed position\n    r_bf = R_eci_ecef * x[1:3]\n\n    # Compute spherical harmonic acceleration\n    a_ecef = spherical_harmonic_gravity(r_bf, GRAVITY_MODEL.data, n_max, m_max, R_ref, GM, normalized=GRAVITY_MODEL.normalized)\n\n    # Inertial acceleration\n    a_eci = R_eci_ecef' * a_ecef\n\n    # Finished\n    return a_eci\nend\n\n#########################\n# Planetary Ephemerides #\n#########################\n\nexport sun_position\n\"\"\"\nCompute the Sun's position in the EME2000 inertial frame through the use\nof low-precision analytical functions.\n\nArgument:\n- `epc::Epoch`: Epoch\n\nReturns:\n- `r_sun::Array{<:Real, 1}`: Position vector of the Sun in the Earth-centered inertial fame.\n\nNotes:\n1. The EME2000 inertial frame is for most purposes equivalent to the GCRF frame.\n\nReferences:\n1. O. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and Applications_, 2012, p.70-73.\n\"\"\"\nfunction sun_position(epc::Epoch)\n    # Constants\n    mjd_tt  = mjd(epc, tsys=\"TT\")      # MJD of epoch in TT\n    epsilon = 23.43929111*pi/180.0     # Obliquity of J2000 ecliptic\n    T       = (mjd_tt-MJD2000)/36525.0 # Julian cent. since J2000\n\n    # Variables\n\n    # Mean anomaly, ecliptic longitude and radius\n    M = 2.0*pi * modf(0.9931267 + 99.9973583*T)[1]                 # [rad]\n    L = 2.0*pi * modf(0.7859444 + M/(2.0*pi) + (6892.0*sin(M)+72.0*sin(2.0*M)) / 1296.0e3)[1] # [rad]\n    r = 149.619e9 - 2.499e9*cos(M) - 0.021e9*cos(2*M)           # [m]\n\n    # Equatorial position vector\n    p_sun = Rx(-epsilon) * [r*cos(L), r*sin(L), 0.0]\n\n    return p_sun\nend\n\nexport moon_position\n\"\"\"\nCompute the Moon's position in the EME2000 inertial frame through the use\nof low-precision analytical functions.\n\nArgument:\n- `epc::Epoch`: Epoch\n\nReturns:\n- `r_moon::Array{<:Real, 1}`: Position vector of the Moon in the Earth-centered inertial fame.\n\nNotes:\n1. The EME2000 inertial frame is for most purposes equivalent to the GCRF frame.\n\nReferences:\n1. O. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and Applications_, 2012, p.70-73.\n\"\"\"\nfunction moon_position(epc::Epoch)\n    # Constants\n    mjd_tt  = mjd(epc, tsys=\"TT\")      # MJD of epoch in TT\n    epsilon = 23.43929111*pi/180.0     # Obliquity of J2000 ecliptic\n    T       = (mjd_tt-MJD2000)/36525.0 # Julian cent. since J2000\n\n    # Mean elements of lunar orbit\n    L_0 =     modf(0.606433 + 1336.851344*T)[1] # Mean longitude [rev] w.r.t. J2000 equinox\n    l   = 2.0*pi*modf(0.374897 + 1325.552410*T)[1] # Moon's mean anomaly [rad]\n    lp  = 2.0*pi*modf(0.993133 +   99.997361*T)[1] # Sun's mean anomaly [rad]\n    D   = 2.0*pi*modf(0.827361 + 1236.853086*T)[1] # Diff. long. Moon-Sun [rad]\n    F   = 2.0*pi*modf(0.259086 + 1342.227825*T)[1] # Argument of latitude \n\n\n    # Ecliptic longitude (w.r.t. equinox of J2000)\n    dL = + 22640*sin(l) - 4586*sin(l-2*D) + 2370*sin(2*D) +  769*sin(2*l)\n         - 668*sin(lp) - 412*sin(2*F) - 212*sin(2*l-2*D) - 206*sin(l+lp-2*D)\n         + 192*sin(l+2*D) - 165*sin(lp-2*D) - 125*sin(D) - 110*sin(l+lp)\n         + 148*sin(l-lp) - 55*sin(2*F-2*D)\n\n    L = 2.0*pi * modf(L_0 + dL/1296.0e3)[1]  # [rad]\n\n    # Ecliptic latitude\n    S  = F + (dL+412*sin(2*F)+541*sin(lp)) * AS2RAD \n    h  = F-2*D\n    N  = - 526*sin(h) + 44*sin(l+h) - 31*sin(-l+h) - 23*sin(lp+h)\n         + 11*sin(-lp+h) - 25*sin(-2*l+F) + 21*sin(-l+F)\n    B  = (18520.0*sin(S) + N) * AS2RAD   # [rad]\n\n    # Distance [m]\n    r = + 385000e3 - 20905e3*cos(l) - 3699e3*cos(2*D-l) - 2956e3*cos(2*D)\n        - 570e3*cos(2*l) + 246e3*cos(2*l-2*D) - 205e3*cos(lp-2*D)\n        - 171e3*cos(l+2*D) - 152e3*cos(l+lp-2*D)   \n\n    # Equatorial coordinates\n    p_moon = Rx(-epsilon) * [r*cos(L)*cos(B), r*sin(L)*cos(B), r*sin(B)]\n\n    return p_moon\nend\n\n######################\n# Third-Body Gravity #\n######################\n\nexport accel_thirdbody_sun\n\"\"\"\nComputes the acceleration of a satellite in the inertial frame due to the\ngravitational attraction of the Sun.\n\nArguments:\n- `x::Array{<:Real, 1}`: Satellite Cartesean state in the inertial reference frame [m; m/s]\n- `r_sun::Array{<:Real, 1}`: Position of sun in inertial frame.\n\nReturn:\n- `a::Array{<:Real, 1}`: Acceleration due to the Sun's gravity in the inertial frame [m/s^2]\n\nReferences:\n1. O. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and Applications_, 2012, p.69-70.\n\"\"\"\nfunction accel_thirdbody_sun(x::Array{<:Real, 1}, r_sun::Array{<:Real, 1})\n    # Acceleration due to sun point mass\n    a_sun = accel_point_mass(x[1:3], r_sun, GM_SUN)\n\n    return a_sun\nend\n\nfunction accel_thirdbody_sun(epc::Epoch, x::Array{<:Real, 1})\n    # Compute solar position\n    r_sun = sun_position(epc)\n\n    # Acceleration due to sun point mass\n    a_sun = accel_point_mass(x[1:3], r_sun, GM_SUN)\n\n    return a_sun\nend\n\nexport accel_thirdbody_moon\n\"\"\"\nComputes the acceleration of a satellite in the inertial frame due to the\ngravitational attraction of the Moon.\n\nArguments:\n- `x::Array{<:Real, 1}`: Satellite Cartesean state in the inertial reference frame [m; m/s]\n- `r_moon::Array{<:Real, 1}`: Position of moon in inertial frame.\n\nReturns:\n- `a::Array{<:Real, 1}`: Acceleration due to the Moon's gravity in the inertial frame [m/s^2]\n\nReferences:\n1. O. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and Applications_, 2012, p.69-70.\n\"\"\"\nfunction accel_thirdbody_moon(x::Array{<:Real, 1}, r_moon::Array{<:Real, 1})\n    # Acceleration due to moon point mass\n    a_moon = accel_point_mass(x[1:3], r_moon, GM_MOON)\n\n    return a_moon\nend\n\nfunction accel_thirdbody_moon(epc::Epoch, x::Array{<:Real, 1})\n    # Compute solar position\n    r_moon = moon_position(epc)\n\n    # Acceleration due to moon point mass\n    a_moon = accel_point_mass(x[1:3], r_moon, GM_MOON)\n\n    return a_moon\nend\n\n####################\n# Atmospheric Drag #\n####################\n\nexport density_harris_priester\n\"\"\"\nComputes the local density using the Harris-Priester density model.\n\nArguments:\n- `x::Array{<:Real, 1}`: Satellite Cartesean state in the inertial reference frame [m; m/s]\n- `r_sun::Array{<:Real, 1}`: Position of sun in inertial frame.\n\nReturns:\n- `rho:Float64`: Local atmospheric density [kg/m^3]\n\nReferences:\n1. O. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and Applications_, 2012, p.89-91.\n\"\"\"\nfunction density_harris_priester(x::Array{<:Real, 1}, r_sun::Array{<:Real, 1})\n    # Harris-Priester Constants\n    hp_upper_limit =   1000.0          # Upper height limit [km]\n    hp_lower_limit =    100.0          # Lower height limit [km]\n    hp_ra_lag      = 0.523599          # Right ascension lag [rad]\n    hp_n_prm       =        3          # Harris-Priester parameter \n                                        # 2(6) low(high) inclination\n    hp_N           = 50                # Number of coefficients\n\n    # Height [km]\n    hp_h = [100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,     \n            210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,     \n            320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,     \n            520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,     \n            720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0,1000.0]\n\n    # Minimum density [g/km^3]\n    hp_c_min = [4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,         \n                8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,         \n                9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,         \n                2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,         \n                2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,         \n                2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,         \n                4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,         \n                1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,         \n                1.560e-03, 1.150e-03]\n\n    # Maximum density [g/km^3]\n    hp_c_max = [4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,         \n                8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,         \n                1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,         \n                4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,         \n                7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,         \n                1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,         \n                4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,         \n                1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,         \n                2.360e-02, 1.810e-02]\n\n    # Satellite height\n    geod   = sECEFtoGEOD(x[1:3], use_degrees=true)\n    height = geod[3]/1.0e3 # height in [km]\n\n    # Exit with zero density outside height model limits\n    if height > hp_upper_limit || height < hp_lower_limit\n        return 0.0\n    end\n\n\n    # Sun right ascension, declination\n    ra_sun  = atan( r_sun[2], r_sun[1] )\n    dec_sun = atan( r_sun[3], sqrt( r_sun[1]^2 + r_sun[2]^2 ) )\n\n\n    # Unit vector u towards the apex of the diurnal bulge\n    # in inertial geocentric coordinates\n    c_dec = cos(dec_sun)\n    u     = [c_dec * cos(ra_sun + hp_ra_lag),\n             c_dec * sin(ra_sun + hp_ra_lag),\n             sin(dec_sun)]\n\n\n    # Cosine of half angle between satellite position vector and\n    # apex of diurnal bulge\n    c_psi2 = 0.5 + 0.5 * dot(x[1:3], u)/norm(x[1:3])\n\n    # Height index search and exponential density interpolation\n    ih = 0                            # section index reset\n    for i in 1:hp_N                   # loop over N_Coef height regimes\n        if height >= hp_h[i] && height < hp_h[i+1] \n            ih = i                    # ih identifies height section\n            break\n        end\n    end\n\n    h_min = ( hp_h[ih] - hp_h[ih+1] )/log( hp_c_min[ih+1]/hp_c_min[ih] )\n    h_max = ( hp_h[ih] - hp_h[ih+1] )/log( hp_c_max[ih+1]/hp_c_max[ih] )\n\n    d_min = hp_c_min[ih] * exp( (hp_h[ih]-height)/h_min )\n    d_max = hp_c_max[ih] * exp( (hp_h[ih]-height)/h_max )\n\n    # Density computation\n    density = d_min + (d_max-d_min) * c_psi2^hp_n_prm\n\n    # Convert from g/km^3 to kg/m^3\n    density *= 1.0e-12\n\n    # Finished\n    return density\nend\n\nfunction density_harris_priester(epc::Epoch, x::Array{<:Real, 1})\n    r_sun = sun_position(epc)\n    return density_harris_priester(x, r_sun)\nend\n\nexport accel_drag\n\"\"\"\nComputes the perturbing, non-conservative acceleration caused by atmospheric\ndrag assuming that the ballistic properties of the spacecraft are captured by\nthe coefficient of drag.\n\nArguments:\n- `x::Array{<:Real, 1}`: Satellite Cartesean state in the inertial reference frame [m; m/s]\n- `rho::Real`: atmospheric density [kg/m^3]\n- `mass::Real`: Spacecraft mass [kg]\n- `area::Real`: Wind-facing cross-sectional area [m^2]\n- `Cd::Real`: coefficient of drag [dimensionless]\n- `T::Array{<:Real, 2}`: Rotation matrix from the inertial to the true-of-date frame\n\nReturn:\n- `a::Array{<:Real, 1}`: Acceleration due to drag in the X, Y, and Z inertial directions. [m/s^2]\n\nReferences:\n1. O. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and Applications_, 2012, p.83-86.\n\"\"\"\nfunction accel_drag(x::Array{<:Real, 1}, rho::Real, mass::Real, area::Real, Cd::Real, T::Array{<:Real, 2})\n\n    # Constants\n    omega = [0, 0, OMEGA_EARTH]\n\n    # Position and velocity in true-of-date system\n    r_tod = T * x[1:3]\n    v_tod = T * x[4:6]\n\n    # Velocity relative to the Earth's atmosphere\n    v_rel = v_tod - cross(omega, r_tod)\n    v_abs = norm(v_rel)\n\n    # Acceleration \n    a_tod  = -0.5*Cd*(area/mass)*rho*v_abs*v_rel\n    a_drag = T' * a_tod \n\n    return a_drag\nend\n\n############################\n# Solar Radiation Pressure #\n############################\n\nexport eclipse_cylindrical\n\"\"\"\nComputes the illumination fraction of a satellite in Earth orbit using a\ncylindrical Earth shadow model.\n\nArguments:\n- `x::Array{<:Real, 1}`: Satellite Cartesean state in the inertial reference frame [m; m/s]\n- `r_sun::Array{<:Real, 1}`: Position of sun in inertial frame.\n\nReturn:\n- `nu::Float64`: Illumination fraction (0 <= nu <= 1). nu = 0 means spacecraft in complete shadow, nu = 1 mean spacecraft fully illuminated by sun.\n\nReferences:\n1. O. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and Applications_, 2012, p.80-83.\n\"\"\"\nfunction eclipse_cylindrical(x::Array{<:Real, 1}, r_sun::Array{<:Real, 1})\n    # Satellite inertial position\n    r = x[1:3]\n    \n    # Sun-direction unit-vector\n    e_sun = r_sun / norm(r_sun)\n    \n    # Projection of spacecraft position\n    s = dot(r, e_sun)\n\n    # Compute illumination\n    nu = 0.0\n    if s/norm(s) >= 1.0 || norm(r - s*e_sun) > R_EARTH \n        nu = 1.0\n    end\n\n    return nu\nend\n\nfunction eclipse_cylindrical(epc::Epoch, x::Array{<:Real, 1})\n    r_sun = sun_position(epc)\n    return eclipse_cylindrical(x, r_sun)\nend\n\nexport eclipse_conical\n\"\"\"\nComputes the illumination fraction of a satellite in Earth orbit using a\nconical Earth shadow model.\n\nArguments:\n- `x::Array{<:Real, 1}`: Satellite Cartesean state in the inertial reference frame [m; m/s]\n- `r_sun::Array{<:Real, 1}`: Position of sun in inertial frame.\n\nReturn:\n- `nu::Float64`: Illumination fraction (0 <= nu <= 1). nu = 0 means spacecraft in complete shadow, nu = 1 mean spacecraft fully illuminated by sun.\n\nReferences:\n1. O. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and Applications_, 2012, p.80-83.\n\"\"\"\nfunction eclipse_conical(x::Array{<:Real, 1}, r_sun::Array{<:Real, 1})\n    # Satellite inertial position\n    r = x[1:3]\n\n    # Occultation Geometry\n    a = asin(R_SUN/norm(r_sun - r))\n    b = asin(R_EARTH/norm(r))\n    c = acos(dot(r, r_sun-r)/(norm(r)*norm(r_sun-r)) )\n\n    e_sun = r_sun / norm(r_sun)\n\n    # Test Occulation Conditions\n    nu = 0.0\n    if abs(a - b) < c && c < (a + b)\n        # Partial occultation\n    \n        xx = (c^2 + a^2 - b^2)/(2*c)\n        yy = sqrt(a^2 - xx^2)\n        A  = a^2 * acos(xx/a) + b^2 * acos((c-xx)/b) - c * yy\n\n        nu = 1 - A/(pi*a^2)\n    elseif (a + b) <= c\n        # No occultation\n        nu = 1.0\n    else\n        # Full occultation\n        nu = 0.0\n    end\n\n    return nu\nend\n\n\nfunction eclipse_conical(epc::Epoch, x::Array{<:Real, 1})\n    r_sun = sun_position(epc)\n    return eclipse_conical(x, r_sun)\nend\n\nexport accel_srp\n\"\"\"Computes the perturbing acceleration due to direct solar radiation \npressure assuming the reflecting surface is a flat plate pointed directly at\nthe Sun.\n\nArguments:\n- `x::Array{<:Real, 1}`: Satellite Cartesean state in the inertial reference frame [m; m/s]\n\nReturns:\n- `a::Array{<:Real, 1}`: Satellite acceleration due to solar radiation pressure [m/s^2]\n\nReferences:\n1. O. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and Applications_, 2012, p.77-79.\n\"\"\"\nfunction accel_srp(x::Array{<:Real, 1}, r_sun::Array{<:Real, 1}, mass::Real=0, area::Real=0, CR::Real=1.8, p0::Real=P_SUN, au::Real=AU)\n    # Spacecraft position vector\n    r = x[1:3]\n\n    # Relative position vector of spacecraft w.r.t. Sun\n    d = r - r_sun\n\n    # Acceleration due to moon point mass\n    a_srp = d * (CR*(area/mass)*p0*AU^2 / norm(d)^3)\n\n    # Return\n    return a_srp\nend\n\n##############\n# Relativity #\n##############\n\nexport accel_relativity\n\"\"\"Computes perturbation accleration of a satellite in the Inertial frame\ndue to the combined effects of special and general relativity.\n\nArguments:\n- `x::Array{<:Real, 1}`: Satellite Cartesean state in the inertial reference frame [m; m/s]\n\nReturns:\n- `a::Array{<:Real, 1}`: Satellite acceleration due to relativity. [m/s^2]\n\nReferences:\n1. O. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and Applications_, 2012, p.110-112.\n\"\"\"\nfunction accel_relativity(x::Array{<:Real, 1})\n    # Extract state variables\n    r = x[1:3]\n    v = x[4:6]\n\n    # Intermediate computations\n    norm_r = norm(r)\n    r2     = norm_r^2\n\n    norm_v = norm(v)\n    v2     = norm_v^2\n\n    c  = C_LIGHT\n    c2 = c^2\n\n    # Compute unit vectors\n    er = r/norm_r\n    ev = v/norm_v\n\n    # Compute perturbation and return\n    a_rel = GM_EARTH/r2 * ( (4*GM_EARTH/(c2*norm_r) - v2/c2)*er + 4*v2/c2*dot(er, ev)*ev)\n\n    return a_rel\nend\n", "meta": {"hexsha": "ae5d988ec0443bb45671e0e4cf47c5a3cfdebb12", "size": 23918, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/orbit_dynamics.jl", "max_stars_repo_name": "sisl/SatelliteDynamics", "max_stars_repo_head_hexsha": "f1eede2faffd2d6a6864d7ac0989a075c7d7a04f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-01-02T17:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:40:54.000Z", "max_issues_repo_path": "src/orbit_dynamics.jl", "max_issues_repo_name": "sisl/SatelliteDynamics", "max_issues_repo_head_hexsha": "f1eede2faffd2d6a6864d7ac0989a075c7d7a04f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-01-14T10:38:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-10T16:07:56.000Z", "max_forks_repo_path": "src/orbit_dynamics.jl", "max_forks_repo_name": "sisl/SatelliteDynamics", "max_forks_repo_head_hexsha": "f1eede2faffd2d6a6864d7ac0989a075c7d7a04f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-02-08T08:12:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-29T20:48:52.000Z", "avg_line_length": 32.7195622435, "max_line_length": 245, "alphanum_fraction": 0.6063215988, "num_tokens": 8452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787566, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7798787577600249}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 37b018c4-34b0-11eb-234d-4fbeaa683873\nusing LinearAlgebra, SparseArrays, Plots, DifferentialEquations\n\n# ╔═╡ baed3ace-34ad-11eb-0cf6-19357238b1de\nmd\"## Heat equation with Dirichlet boundary conditions\n\nThe domain is given by the one-dimensional rod $\\Omega = (0,L)$ and the time by $t \\in (0,T).$ The rod has the physical properties\n- thermal conductivity $\\lambda$,\n- specific heat capacity $c$,\n- mass density $\\rho$.\n\n### Heat Equation\n\nThe diffusivity constant is given by $\\alpha = \\frac{\\lambda}{c \\rho}$. The heat equation is noted as\n\n$\\dot{\\vartheta}(t,x) = \\alpha \\frac{\\partial^2}{\\partial x^2} \\vartheta(t,x)$\n\nfor $(t,x) \\in (0,T) \\times \\Omega$ with initial condition\n\n$\\vartheta(0,x) = \\vartheta_{0}(x)$ \n\nfor $x \\in \\overline{\\Omega}$ and boundary conditions  $\\qquad \\vartheta(\\cdot,0) = \\vartheta(\\cdot,L) = 0$.\n\"\n\n# ╔═╡ 8f5d25dc-34ae-11eb-2aa7-39e601f648a1\nmd\"#### Code: implementing physical constants\"\n\n# ╔═╡ 8f493cca-34ae-11eb-3e60-31ab68674568\n# Length of rod\nL = 0.5\n\n# ╔═╡ 8f149f6a-34ae-11eb-01f2-5983e256a7de\n# Thermal conductivity\nλ = 45.0 \n\n# ╔═╡ 8efa0286-34ae-11eb-1952-e790d141e19b\n# Specific heat capacity\nc = 480.0\n\n# ╔═╡ 8ecb6bba-34ae-11eb-2c16-819675412725\n# Mass density\nρ = 7800.0\n\n# ╔═╡ e6433430-34af-11eb-318d-2199461e5ec9\n# Thermal diffusivity\nα = λ/(c*ρ)\n\n# ╔═╡ 37c91fae-34b0-11eb-0f82-639173602ac0\nmd\"### Spatial approximation\n\nThe one-dimensional rod is discretized as a one-dimensional grid with N points and the finite discretization is noted by\n\n$\\Delta x = \\frac{L}{N-1}.$\n\nThe resulting grid points have the position $x^{0} = 0$, $x^{n} = n~\\Delta x$ and $x^{N-1} = L$. The second order derivative is approximated using the [Taylor series](https://en.wikipedia.org/wiki/Taylor_series) as \n\n$\\left. \\frac{\\partial^2 f(x)}{\\partial x^2} \\right\\rvert_{x = \\tilde{x}} \\approx \\frac{1}{\\Delta x^2} \\left[ f(\\tilde{x} - \\Delta x) - 2 f(\\tilde{x}) + f(\\tilde{x} + \\Delta x)  \\right].$\n\nThis [Finite Difference](https://en.wikipedia.org/wiki/Finite_difference_method) scheme is written in matrix-vector form as \n\n$\\frac{\\partial^2 \\vartheta(t,x)}{\\partial x^2} \\approx \\frac{1}{\\Delta x^2}\n\\begin{pmatrix}\n-2 & 1 & 0 & \\cdots &  & 0 \\\\\n1 & -2 & 1 & 0  & \\cdots & \\vdots \\\\\n0 & 1 & -2 & 1 & \\ddots &  \\\\\n & & \\ddots & \\ddots & \\ddots &  & \\\\\n& & & 1 & -2 & 1 \\\\\n& & &  & 1 & -2 \\\\\n\\end{pmatrix}\n~\n\\begin{pmatrix}\n\\vartheta(t, x^{0}) \\\\\n\\vartheta(t, x^{1}) \\\\\n\\vdots \\\\\n\\vartheta(t, x^{N-1}) \\\\\n\\end{pmatrix}.$\n\"\n\n# ╔═╡ 65049b1a-3549-11eb-33ee-9dfae609164d\n# Number of grid elements\nN = 101\n\n# ╔═╡ a36fd440-3549-11eb-0e93-0d36244400ef\n# Finite discretization\nΔx = L/(N-1)   \n\n# ╔═╡ c18a976a-3549-11eb-2991-799f558e4493\n# 1-dimensional grid\nxspan = 0 : Δx : L\n\n# ╔═╡ d7d5be46-3549-11eb-3a12-afab5ab4bce5\n# Diffusion matrix\nM = spdiagm(-1 => ones(N-1), 0 => -2*ones(N), 1 => ones(N-1));\n\n# ╔═╡ 045066e2-354a-11eb-164b-09fc7095de47\nMatrix(M)[1:5,1:5]\n\n# ╔═╡ 37822ec8-34b0-11eb-175d-7745382c2955\nmd\"### Boundary conditions\n\nThe Dirichlet boundary condition states that the value at both sides is fixed as \n\n$\\qquad \\vartheta(\\cdot,0) = \\vartheta(\\cdot, x^{0}) = 0$\n\non the left boundary and \n\n$\\vartheta(\\cdot,L) = \\vartheta(\\cdot, x^{N-1})  = 0$\n\non the right boundary. This means, there is no dynamical (e.g. diffusive) behaviour at both boundaries and thus the first and the last row of the diffusion matrix M is set to 0. \"\n\n# ╔═╡ 3768b7e0-34b0-11eb-0772-f5f4c95cf8f5\n# First row\nM[1,1] = M[1,2] = 0;\n\n# ╔═╡ 37529500-34b0-11eb-1ee4-b5837bea23c9\n# Last row\nM[end,end] = M[end,end-1] = 0;\n\n# ╔═╡ 373652f0-34b0-11eb-2fea-4f14b3ee9140\nmd\"### Heat equation as ODE\n\nAfter the spatial approximation the heat equation has a form of \n\n$\\dot{\\theta}(t) = \\frac{\\alpha}{\\Delta x^2} ~ M ~ \\theta(t)$\n\nwith M as diffusion matrix and $\\quad \\theta(t) = \\left( \\vartheta(t, x^{0}), \\cdots, \\vartheta(t, x^{N-1}) \\right)^{\\top}$. This is an ordinary differential equation (ODE) that can be solved with common solvers like forward Euler method or Runge-Kutta scheme.\"\n\n# ╔═╡ 371c6d52-34b0-11eb-12ab-a51e10fe33c5\n# Heat Equation as ODE\nfunction heat_eq(dθ, θ, p, t)\n    return dθ .= (1/Δx^2) * α * M * θ\nend\n\n# ╔═╡ 37013e12-34b0-11eb-3d23-9d43ca3f06a3\nmd\"### Initial Conditions\n\nThe initial data of the original heat equation is assumed as $\\quad \\vartheta_{0}(x) := m \\left[ L~x - x^2 \\right]~$ with  $m > 0$. This function is approximated to gain the initial conditions of the ODE \n\n$\\theta(0) = \\left( \\vartheta_{0}(x^{0}), \\cdots , \\vartheta_{0}(x^{N-1}) \\right)^{\\top}.$\n\"\n\n# ╔═╡ 78b7fa20-354c-11eb-3754-d5d515d0a2d5\n#Initial conditions: θ(0) = m * (L * x - x^2)\nfunction initial_data(x, params)\n    # α = params[1] # unused here \n    L = params[2]\n    m = params[3]\n\n    return m*( L * x - x^2)\nend\n\n# ╔═╡ 77906a42-354c-11eb-397e-9dca847ab964\n# Initial heat distribution\nθ₀ = zeros(N);\n\n# ╔═╡ 93696cf4-354d-11eb-0af3-9b27a8186fbd\n# Amplification of initial data\n@bind amp html\"<input type='range' min='0' max='100' step='1'>\"\n\n# ╔═╡ a91c8b80-354d-11eb-03ec-8f4386a69708\nm = amp\n\n# ╔═╡ 86f0f21c-354d-11eb-2a32-299183f9118b\n# Parameters\nparam = [α, L, amp]\n\n# ╔═╡ 666a8878-354d-11eb-22dc-e94a72ede22d\nlet\n\n\tfor i = 1 : length(xspan)\n\t\tθ₀[i] = initial_data(xspan[i], param)\n\tend\n\t\n\tplot(xspan, θ₀, xlabel=\"Position x\", ylabel=\"Temperature\", legend=false)\nend\n\n# ╔═╡ cfc0e592-354d-11eb-2b06-458d198c38e5\nmd\"### Numerical stability\n\nBefore the approximated heat equation can be simulated, the [numerical stability](https://en.wikipedia.org/wiki/Numerical_stability) has to be proven with the [von Neumann stability analysis](https://en.wikipedia.org/wiki/Von_Neumann_stability_analysis). \n\nIn case of the forward Euler method one finds the approach\n\n$\\vartheta(t^{k+1}, x^{n}) = \\vartheta(t^{k}, x^{n}) + \\alpha \\frac{\\Delta t}{\\Delta x^2} \\left( \\vartheta(t^{k}, x^{n-1}) - 2 ~ \\vartheta(t^{k}, x^{n}) + \\vartheta(t^{k}, x^{n+1}) \\right)$\n\nor equivalent\n\n$\\vartheta(t^{k+1}, x^{n}) = \\left(1 - 2 \\alpha \\frac{\\Delta t}{\\Delta x^2} \\right) \\vartheta(t^{k}, x^{n}) + \\alpha \\frac{\\Delta t}{\\Delta x^2}  \\left( \\vartheta(t^{k}, x^{n-1}) + \\vartheta(t^{k}, x^{n+1}) \\right).$\n\nThe sampling time $\\Delta t$ has to be chosen to guarantee \n\n$\\left(1 - 2 \\alpha \\frac{\\Delta t}{\\Delta x^2} \\right) > 0.$\n\nTherefore, the upper limit of the sampling time is given by \n\n$\\Delta t < \\frac{1}{2} \\frac{\\Delta x^2}{\\alpha}.$\n\"\n\n# ╔═╡ 25789968-3552-11eb-1e25-35c0d1b1c461\n# Upper limit of sampling time\nul = 0.5 * Δx^2 / α\n\n# ╔═╡ 56daee6e-3554-11eb-37cd-49ad4ac56805\n# Sampling time\nΔt = 0.8\n\n# ╔═╡ 56bb225a-3554-11eb-0062-6d03b8ea772f\n# time discretization\ntspan = (0.0, 1000.0)\n\n# ╔═╡ 569a20f0-3554-11eb-0479-f1e583620682\nmd\"### Code: Solving the ODE\"\n\n# ╔═╡ 56790ed8-3554-11eb-3c51-b9b31a4c340e\n# Solving the ODE\nlet\n\tprob = ODEProblem( heat_eq, θ₀, tspan ) # ODE Problem\n\t\n\tsol = solve(prob,Euler(),dt=Δt,progress=true, save_everystep=false, \n\t\t\t\tsave_start=true) # Solving the ODE\n\t\n\tplot(xspan, sol.u[2], xlabel = \"Position x\", ylabel=\"Temperature\", legend=false)\nend\n\n# ╔═╡ Cell order:\n# ╟─baed3ace-34ad-11eb-0cf6-19357238b1de\n# ╟─8f5d25dc-34ae-11eb-2aa7-39e601f648a1\n# ╠═8f493cca-34ae-11eb-3e60-31ab68674568\n# ╠═8f149f6a-34ae-11eb-01f2-5983e256a7de\n# ╠═8efa0286-34ae-11eb-1952-e790d141e19b\n# ╠═8ecb6bba-34ae-11eb-2c16-819675412725\n# ╠═e6433430-34af-11eb-318d-2199461e5ec9\n# ╟─37c91fae-34b0-11eb-0f82-639173602ac0\n# ╠═37b018c4-34b0-11eb-234d-4fbeaa683873\n# ╠═65049b1a-3549-11eb-33ee-9dfae609164d\n# ╠═a36fd440-3549-11eb-0e93-0d36244400ef\n# ╠═c18a976a-3549-11eb-2991-799f558e4493\n# ╠═d7d5be46-3549-11eb-3a12-afab5ab4bce5\n# ╠═045066e2-354a-11eb-164b-09fc7095de47\n# ╟─37822ec8-34b0-11eb-175d-7745382c2955\n# ╠═3768b7e0-34b0-11eb-0772-f5f4c95cf8f5\n# ╠═37529500-34b0-11eb-1ee4-b5837bea23c9\n# ╟─373652f0-34b0-11eb-2fea-4f14b3ee9140\n# ╠═371c6d52-34b0-11eb-12ab-a51e10fe33c5\n# ╟─37013e12-34b0-11eb-3d23-9d43ca3f06a3\n# ╠═78b7fa20-354c-11eb-3754-d5d515d0a2d5\n# ╠═77906a42-354c-11eb-397e-9dca847ab964\n# ╠═93696cf4-354d-11eb-0af3-9b27a8186fbd\n# ╠═a91c8b80-354d-11eb-03ec-8f4386a69708\n# ╠═86f0f21c-354d-11eb-2a32-299183f9118b\n# ╠═666a8878-354d-11eb-22dc-e94a72ede22d\n# ╟─cfc0e592-354d-11eb-2b06-458d198c38e5\n# ╠═25789968-3552-11eb-1e25-35c0d1b1c461\n# ╠═56daee6e-3554-11eb-37cd-49ad4ac56805\n# ╠═56bb225a-3554-11eb-0062-6d03b8ea772f\n# ╟─569a20f0-3554-11eb-0479-f1e583620682\n# ╠═56790ed8-3554-11eb-3c51-b9b31a4c340e\n", "meta": {"hexsha": "37d3b24704898ffc8c841896dd0210647aa0daa9", "size": 8768, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/modeling/dirichlet_numerical.jl", "max_stars_repo_name": "stephans3/IntroHeatEquation.jl", "max_stars_repo_head_hexsha": "37e9c9ededeb7cdfc2ffb0c11ac1661d157a0288", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/modeling/dirichlet_numerical.jl", "max_issues_repo_name": "stephans3/IntroHeatEquation.jl", "max_issues_repo_head_hexsha": "37e9c9ededeb7cdfc2ffb0c11ac1661d157a0288", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/modeling/dirichlet_numerical.jl", "max_forks_repo_name": "stephans3/IntroHeatEquation.jl", "max_forks_repo_head_hexsha": "37e9c9ededeb7cdfc2ffb0c11ac1661d157a0288", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1172161172, "max_line_length": 261, "alphanum_fraction": 0.6846487226, "num_tokens": 3859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7798787557929151}}
{"text": "\"\"\"\nDetermine the null and alternate hypotheses under t-tests given:\n\n* `ns`: Per-group sample size(s)\n* `δ`: Deviation from the null\n* `σs`: Per-group standard deviations\n\"\"\"\nfunction hypotheses(::Type{OneSampleTTest}, n::Real, δ::Real, σ::Real)\n    df = n - 1\n    ncp = sqrt(n) * δ / σ\n    null = TDist(df)\n    alt = NoncentralT(df, ncp)\n    return null, alt\nend\n\n\"\"\"\nDetermine the null and alternate hypotheses under t-tests given:\n\n* `ns`: Per-group sample size(s)\n* `δ`: Deviation from the null\n* `σs`: Per-group standard deviations\n\"\"\"\nfunction hypotheses(::Type{EqualVarianceTTest}, n::Real, δ::Real, σ::Real)\n    df = 2 * n - 2\n    ncp = sqrt(n / 2) * δ / σ\n    null = TDist(df)\n    alt = NoncentralT(df, ncp)\n    return null, alt\nend\n\n\"\"\"\nDetermine the null and alternate hypotheses under t-tests given:\n\n* `ns`: Per-group sample size(s)\n* `δ`: Deviation from the null\n* `σs`: Per-group standard deviations\n\"\"\"\nfunction hypotheses(::Type{EqualVarianceTTest}, ns::Tuple, δ::Real, σ::Real)\n    n1, n2 = ns[1], ns[2]\n    df = n1 + n2 - 2\n    ncp = (1 / sqrt(1 / n1 + 1 / n2)) * δ / σ\n    null = TDist(df)\n    alt = NoncentralT(df, ncp)\n    return null, alt\nend\n\n# @doc \"\"\"\n# Determine the values of t that lead to overestimates of the magnitude of δ.\n# \"\"\" ->\nthresholds(alt::NoncentralT) = -alt.λ, alt.λ\n", "meta": {"hexsha": "308e823d266b9b02e7e5c876d2fa0eafe4de10c8", "size": 1311, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/t_test.jl", "max_stars_repo_name": "johnmyleswhite/PowerAnalysis.jl", "max_stars_repo_head_hexsha": "df7c7d3875289b55e4a23680e3064f2f88754eb5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:46:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-23T01:20:46.000Z", "max_issues_repo_path": "src/t_test.jl", "max_issues_repo_name": "johnmyleswhite/PowerAnalysis.jl", "max_issues_repo_head_hexsha": "df7c7d3875289b55e4a23680e3064f2f88754eb5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-08-06T21:15:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T19:48:49.000Z", "max_forks_repo_path": "src/t_test.jl", "max_forks_repo_name": "johnmyleswhite/PowerAnalysis.jl", "max_forks_repo_head_hexsha": "df7c7d3875289b55e4a23680e3064f2f88754eb5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-01-12T14:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T22:45:40.000Z", "avg_line_length": 25.7058823529, "max_line_length": 77, "alphanum_fraction": 0.6346300534, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217417, "lm_q2_score": 0.8438951084436076, "lm_q1q2_score": 0.7798787543358017}}
{"text": "\"\"\"\n    floatmod(x, y)\n\nThis is the equivalent of `x // y` for floating point.\n\"\"\"\nfloatmod(x, y) = x - y * floor(x / y)\n\n\"\"\"\n    fibonacci_points(n)\n\nConstructs lat-long points on a sphere from a Fibonacci sequence.\n\nThere are 2n + 1 points on the sphere. It returns a `(2,2n+1)` grid of lat-long.\n\nThese points are a good start on an evenly-spaced set of points on the\nsurface of a sphere. This algorithm is from González [^1]. The usual way\nto use these points is to make them a little more even by adjustment\nwith a successive over-relaxation algorithm. That algorithm moves them\na little at each step due to a repulsive force among neighbors.\nThen you make a Voronoi on the sphere and create triangles from this.\nThe Voronoi will be almost all hexagons, but there will be a few polygons\nwith 5 and 7 sides.\n\n[^1]: González, Á. (2010). Measurement of areas on a sphere using Fibonacci\nand latitude–longitude lattices. Mathematical Geosciences, 42(1), 49.\n\"\"\"\nfunction fibonacci_points(n)\n    ϕ = (1 + sqrt(5)) / 2\n    points = zeros(Float64, 2, 2n + 1)\n    for i in -n:n\n        points[1, i + n + 1] = asin(2i / (2n + 1)) * 180 / π\n        lon = floatmod(i, ϕ) * 360 / ϕ\n        if lon < -180\n            points[2, i + n + 1] = lon + 360\n        elseif lon >= 180\n            points[2, i + n + 1] = lon - 360\n        else\n            points[2, i + n + 1] = lon\n        end\n    end\n    points\nend\n", "meta": {"hexsha": "c7fa91baac87f066f70dc6d2e7af92bdd4b49c44", "size": 1400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fibgrid.jl", "max_stars_repo_name": "adolgert/simplexpop.jl", "max_stars_repo_head_hexsha": "4e403816f7b94002b8dff45db859ab45ecd8849b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fibgrid.jl", "max_issues_repo_name": "adolgert/simplexpop.jl", "max_issues_repo_head_hexsha": "4e403816f7b94002b8dff45db859ab45ecd8849b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fibgrid.jl", "max_forks_repo_name": "adolgert/simplexpop.jl", "max_forks_repo_head_hexsha": "4e403816f7b94002b8dff45db859ab45ecd8849b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-04T13:27:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-04T13:27:58.000Z", "avg_line_length": 32.5581395349, "max_line_length": 80, "alphanum_fraction": 0.6414285714, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7798787523176933}}
{"text": "export bisect, cross_edges\n\n\"\"\"\n`bisect(G::SimpleGraph)` partitions the vertex set of `G` using the\neigenvector associated with the second smallest eigenvalue of the\ngraph's Laplacian matrix (called `x` below).\n\nThis can be invoked as follows:\n\n+ `bisect(G,\"user\",pivot)` splits the vertices `v` depending on\n  `x[v] >= pivot` vs. `x[v] < pivot`.\n\n+ `bisect(G,\"zero\")` is the same as `bisect(G,\"user\", 0.0)`.\n\n+ `bisect(G,\"median\")` is equivalent to `bisect(G,\"user\",m)` where `m`\n  is the median value of `x`.\n\n+ `bisect(G,\"equal\")` creates a partition in which the two parts have sizes\n  the differ by at most 1.\n\nA plain call to `bisect(G)` is equivalent to `bisect(G,\"zero\")` (which\nis the same as `bisect(G,\"user\", 0.0)`).\n\"\"\"\nfunction bisect(G::SimpleGraph,\n                where::AbstractString=\"zero\",\n                pivot::Real=0.0\n               )\n\n    verbose = false\n\n    if verbose\n        println(\"G = $G\")\n        println(\"where = $where\")\n        println(\"pivot = $pivot\")\n    end\n\n    T = vertex_type(G)\n    VV = vlist(G)\n    n  = NV(G)\n    L  = laplace(G)\n    # x  = collect( eig(L)[2][:,2] )\n    x = collect( eigen(L).vectors[:,2])\n\n    if verbose\n        println(sort(x))\n    end\n\n    piv = 0.0\n\n\n    if where==\"equal\"\n        pairs = sort(collect(zip(x,VV)))\n        vtcs  = [ p[2] for p in pairs ]\n\n        if verbose\n            println(pairs)\n            println(vtcs)\n        end\n\n        mid = floor(Int, n/2)\n        if verbose\n            println(\"Equal partition of the vertex set: $mid and $(n-mid)\")\n        end\n        A = Set{T}(vtcs[1:mid])\n        B = Set{T}(vtcs[mid+1:end])\n        return A,B\n    end\n\n\n    if where==\"median\"\n        piv = median(x)\n    elseif where==\"user\"\n        piv = pivot\n    elseif where==\"zero\"\n        piv = 0.0\n    else\n        error(\"Unknown \\\"where\\\" specifier: $where\")\n    end\n\n    if verbose\n        println(\"pivot set to $piv\")\n    end\n\n    A = Set{T}()\n    B = Set{T}()\n\n    for k=1:n\n        v = VV[k]\n        if x[k] >= piv\n            push!(A,v)\n        else\n            push!(B,v)\n        end\n    end\n\n    return A,B\nend\n\n# import IterTools.product\n\n\"\"\"\n`cross_edges(G::SimpleGraph,A,B)` returns the set of edges of `G` with\none end in `A` and one end in `B`. Here `A` and `B` are collections\nof vertices of `G`.\n\"\"\"\nfunction cross_edges(G::SimpleGraph, A, B)\n\n    AB = Base.Iterators.product(A,B)\n\n    result = Set(filter(e -> has(G,e[1],e[2]), collect(AB)))\n    return result\nend\n", "meta": {"hexsha": "23f38741c10730efb72ea02c8976557eac3fdce9", "size": 2458, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bisect.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_stars_repo_head_hexsha": "a22fbfc7f37c5b4debf209a11f5b059a688d8676", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bisect.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_issues_repo_head_hexsha": "a22fbfc7f37c5b4debf209a11f5b059a688d8676", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bisect.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_forks_repo_head_hexsha": "a22fbfc7f37c5b4debf209a11f5b059a688d8676", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7522123894, "max_line_length": 75, "alphanum_fraction": 0.5492270138, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7798787452652496}}
{"text": "#=##############################################################################\n# DESCRIPTION\n    Linear algebra tools\n\n# AUTHORSHIP\n  * Author    : Eduardo J Alvarez\n  * Email     : Edo.AlvarezR@gmail.com\n  * Created   : Oct 2021\n  * License   : MIT License\n=###############################################################################\n\ndot(A, B) = sum(a*b for (a,b) in zip(A, B))\nnorm(A) = sqrt(mapreduce(x->x^2, +, A))\n\ncross1(A, B) = A[2]*B[3] - A[3]*B[2]\ncross2(A, B) = A[3]*B[1] - A[1]*B[3]\ncross3(A, B) = A[1]*B[2] - A[2]*B[1]\n\nfunction cross!(out, A, B)\n    out[1] = cross1(A, B)\n    out[2] = cross2(A, B)\n    out[3] = cross3(A, B)\nend\n\nfunction cross(A, B)\n    out = zero(A)\n    cross!(out, A, B)\n    return out\nend\n", "meta": {"hexsha": "af0e74b479e19da5b4b84123738a1c505956dcc4", "size": 729, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GeometricTools_linearalgebra.jl", "max_stars_repo_name": "byuflowlab/VTKtools.jl", "max_stars_repo_head_hexsha": "ac4ac07ad0b141a3ed2dfc30e46c837cfae2b7b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-01-13T16:39:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T12:25:40.000Z", "max_issues_repo_path": "src/GeometricTools_linearalgebra.jl", "max_issues_repo_name": "byuflowlab/VTKtools.jl", "max_issues_repo_head_hexsha": "ac4ac07ad0b141a3ed2dfc30e46c837cfae2b7b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-17T16:23:04.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-17T16:32:49.000Z", "max_forks_repo_path": "src/GeometricTools_linearalgebra.jl", "max_forks_repo_name": "byuflowlab/VTKtools.jl", "max_forks_repo_head_hexsha": "ac4ac07ad0b141a3ed2dfc30e46c837cfae2b7b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-06T03:24:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T12:25:40.000Z", "avg_line_length": 24.3, "max_line_length": 80, "alphanum_fraction": 0.4238683128, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475778774729, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7798765725668975}}
{"text": "import Distributions: Uniform\nimport StaticArrays: SVector\nimport DynamicalSystems: DiscreteDynamicalSystem\n\n\"\"\"\n    eom_ikeda(u, p, t)\n\nEquations of motion for a discrete two-dimensional Ikeda map system, adapted from [1]\nby adding a noise term and allowing the influences from ``x \\\\to y`` (``c_{xy}``) and \nfrom ``y \\\\to x`` (``c_{yx}``) to be adjusted. The difference equations are\n\n```math\n\\\\begin{aligned}\nx(t+1) = 1 + \\\\mu(x(t) \\\\cos{(\\\\theta)} - c_{yx} y(t) \\\\sin{(\\\\theta)}) - min(\\\\dfrac{\\\\sigma \\\\xi_{t}^{(1)})}{(1-x)}, \\\\xi_{t}^{(2)} \\\\\\\\\ny(t+1) = \\\\mu(y(t) \\\\cos{(\\\\theta)} - c_{xy} x(t) \\\\sin{(\\\\theta)}) - min(\\\\dfrac{\\\\sigma \\\\zeta_{t}^{(1)})}{(1-y)}, \\\\zeta_{t}^{(2)}\n\\\\end{aligned}\n```\n\n## References\n\n1. Cao, Liangyue, Alistair Mees, and Kevin Judd. \"Modeling and predicting \n    non-stationary time series.\" International Journal of Bifurcation and \n    Chaos 7.08 (1997): 1823-1831.\n\"\"\"\nfunction eom_ikeda(u, p, t)\n    x, y = u[1], u[2]\n    c_xy, c_yx, a, b, c, r₁, r₂, σ = p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8]\n    \n    θ = a - b/(c + x^2 + y^2)\n    μ = r₁*sin(t) - r₂\n    d = Uniform(0.1, 0.4)\n    \n    dx = 1 + μ*(x*cos(θ) - c_yx*y*sin(θ)) - min(σ*rand(d)/(1-x), rand(d))\n    dy = μ*(y*cos(θ) + c_xy*x*sin(θ)) -  min(σ*rand(d)/(1-y), rand(d))\n    \n    SVector{2}(dx, dy)\nend\n\n\"\"\"\n    ikeda(; u₀ = rand(2), c_xy = 1.0, c_yx = 1.0, a = 0.8, b = 12, c = 0.9,\n        r₁ = rand(Uniform(0.01, 0.3)), r₂ = rand(Uniform(0.01, 0.3)), σ = 0.05)\n\nInitialise a discrete two-dimensional Ikeda map system, adapted from [1]\nby adding a noise term and allowing the influences from ``x \\\\to y`` (``c_{xy}``) and \nfrom ``y \\\\to x`` (``c_{yx}``) to be adjusted.\n\nAs a rule-of-thumb, if parameters `a`, `b`, and `c` are drawn from uniform \ndistributions on `[0.8, 1.5]`, `[10, 14]` and `[0.1, 0.9]`.\n\nThe difference equations are\n\n```math\n\\\\begin{aligned}\nx(t+1) = 1 + \\\\mu(x \\\\cos{(\\\\theta)} - c_{yx} y \\\\sin{(\\\\theta)}) - min(\\\\dfrac{\\\\sigma \\\\xi_{t}^{(1)})}{(1-x)}, \\\\xi_{t}^{(2)} \\\\\\\\\ny(t+1) = \\\\mu(y \\\\cos{(\\\\theta)} - c_{xy} x \\\\sin{(\\\\theta)}) - min(\\\\dfrac{\\\\sigma \\\\zeta_{t}^{(1)})}{(1-y)}, \\\\zeta_{t}^{(2)}\n\\\\end{aligned}\n```\n\n## References\n\n1. Cao, Liangyue, Alistair Mees, and Kevin Judd. \"Modeling and predicting \n    non-stationary time series.\" International Journal of Bifurcation and \n    Chaos 7.08 (1997): 1823-1831.\n\"\"\"\nfunction ikeda(u₀, c_xy, c_yx, a, b, c, r₁, r₂, σ)\n    p = [c_xy, c_yx, a, b, c, r₁, r₂, σ]\n    DiscreteDynamicalSystem(eom_ikeda, u₀, p)\nend\n\nfunction ikeda(; u₀ = rand(2), c_xy = 1.0, c_yx = 1.0, a = 0.8, b = 12, c = 0.9,\n        r₁ = rand(Uniform(0.01, 0.3)), r₂ = rand(Uniform(0.01, 0.3)), σ = 0.05)\n    ikeda(u₀, c_xy, c_yx, a, b, c, r₁, r₂, σ)\nend\n\nexport eom_ikeda, ikeda", "meta": {"hexsha": "8b944b00d556a693ecf2ad36323638b35c3e9607", "size": 2732, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/systems/discretemaps/ikeda.jl", "max_stars_repo_name": "bhannis/CausalityTools.jl", "max_stars_repo_head_hexsha": "7a1d048e287b413e5588d0e8aefb54e65f6de400", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2020-06-11T01:51:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T18:39:43.000Z", "max_issues_repo_path": "src/systems/discretemaps/ikeda.jl", "max_issues_repo_name": "bhannis/CausalityTools.jl", "max_issues_repo_head_hexsha": "7a1d048e287b413e5588d0e8aefb54e65f6de400", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2020-12-21T02:52:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T10:40:08.000Z", "max_forks_repo_path": "src/systems/discretemaps/ikeda.jl", "max_forks_repo_name": "bhannis/CausalityTools.jl", "max_forks_repo_head_hexsha": "7a1d048e287b413e5588d0e8aefb54e65f6de400", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-09-27T08:56:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T15:05:51.000Z", "avg_line_length": 36.4266666667, "max_line_length": 138, "alphanum_fraction": 0.5673499268, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7798765659058635}}
{"text": "import Pkg;Pkg.add(\"DifferentialEquations\")\nimport Pkg;Pkg.add(\"Plots\")\nusing DifferentialEquations\nusing Plots;gr()\n\n# definition ode\nf(y, t) = 3.0 * y + 2.0\n\n# setting initial condiction\ny0 = 1.0\n\n# setting time step\ntspan = (0.0, 1.0)\n\n# solve of ODEProblem\nprob = ODEProblem(f , y0 , tspan)\nsol = solve(prob)\n\n# plot\nplot(\n    sol,\n    linewidth=5,\n    title=\"Solution to the linear ODE with a thick line\",\n    xaxis=\"Time (t)\",\n    yaxis=\"y(t) (in micro.m)\",\n    label=\"My Thick Line!\"\n)\n\n# exact solution\ng(t) = 5//3 * exp.(3 * t) - 2//3\n\n# comparison plot\nplot!(g, lw=3, ls=:dash, label=\"True Solution!\")", "meta": {"hexsha": "a03b293cd5ddd846c79aec407edb266ffed4b538", "size": 611, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "sample_ode.jl", "max_stars_repo_name": "muripoLife/collection_de", "max_stars_repo_head_hexsha": "bd7021db9c459ac099225ca7f62b22026ba19b1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sample_ode.jl", "max_issues_repo_name": "muripoLife/collection_de", "max_issues_repo_head_hexsha": "bd7021db9c459ac099225ca7f62b22026ba19b1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sample_ode.jl", "max_forks_repo_name": "muripoLife/collection_de", "max_forks_repo_head_hexsha": "bd7021db9c459ac099225ca7f62b22026ba19b1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5151515152, "max_line_length": 57, "alphanum_fraction": 0.6382978723, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368928, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7798660760935179}}
{"text": "###################################\n## Simple Variational Inference\n## for 2D Gaussian\n\nusing PyPlot\n\nfunction calc_KL(mu1, lambda1, mu2, lambda2)\n    D = size(mu1, 1)\n    px_lnqx = 0.5 * logdet(lambda2) - 0.5 * ((mu1 - mu2)' * lambda2 * (mu1 - mu2) + trace(lambda2 * inv(lambda1)))\n    px_lnpx = 0.5 * logdet(lambda1) - 0.5 * D\n    KL = - (px_lnqx - px_lnpx)\n    return KL[1]\nend\n\nfunction plot_results(result, truth)\n    N = size(result, 1)\n    H = Int(ceil(sqrt(N)))\n    W = Int(ceil(N / H))\n    f, ax = subplots(H, W)\n    for i in 1 : H\n        for j in 1 : W\n            n = (i - 1) * W + j\n            if n <= N\n                p = ax[i, j]\n                p[:set_title](@sprintf(\"%d of %d\", n, N))\n                plot_gaussian(p, result[n][1], result[n][2], \"b\", \"p(z)\")\n                plot_gaussian(p, truth[1], truth[2], \"r\", \"q(z)\")\n                p[:set_xlim]([-1.5, 1.0])\n                p[:set_ylim]([-0.6, 0.8])\n            end\n        end\n    end\nend\n\nfunction plot_gaussian(p, Mu, Sigma, col, label)\n    res = 100\n    p[:plot](Mu[1], Mu[2], \"x\", color=col)\n    \n    F = eigfact(Sigma)\n    vec = F[:vectors]\n    val = F[:values]\n    dw = 2*pi/res\n    w = dw * (0 : res)\n    \n    c = 1.0\n    a = sqrt(c * val[1])\n    b = sqrt(c * val[2])\n    P1 = a*cos(w)\n    P2 = b*sin(w)\n    P = Mu .+ vec'*vcat(P1', P2')\n    p[:plot](P[1, :]', P[2, :]', \"-\", color=col, label=label)\nend\n        \nfunction main()\n    ## creat truth distribution\n    D = 2 # dimension\n    theta = 2.0*pi/12 # tilt\n    A = reshape([cos(theta), -sin(theta),\n                 sin(theta), cos(theta)],\n                2, 2)\n    mu = [0.0, 0.0]\n    lambda = inv(A * inv(reshape([1,0,0,10], 2, 2)) * A')\n    \n    ## initialize\n    mu_h = randn(D)\n    lambda_h = zeros(D,D)\n    \n    ## main iteration\n    max_iter = 10\n    KL = Vector{Float64}()\n    result = Vector()\n    for i in 1 : max_iter\n        ## update\n        mu_h[1] = mu[1] - inv(lambda[1,1])*lambda[1,2] * (mu_h[2] - mu[2])\n        lambda_h[1,1] = lambda[1,1]\n        mu_h[2] = mu[2] - inv(lambda[2,2])*lambda[2,1] * (mu_h[1] - mu[1])\n        lambda_h[2,2] = lambda[2,2]\n        \n        ## calculate KL divergeince\n        push!(KL, calc_KL(mu_h, lambda_h, mu, lambda))\n        #println(mu_h)\n        #println(lambda_h)\n\n        ## store the results\n        push!(result, (deepcopy(mu_h), deepcopy(inv(lambda_h))))\n    end\n\n    ## visualize results\n    plot_results(result, (mu, inv(lambda)))\n\n    f, ax = subplots(1, 1)\n    plot_gaussian(ax, mu, inv(lambda), \"b\", latexstring(\"\\$p(z)\\$\"))\n    plot_gaussian(ax, result[end][1], result[end][2], \"r\", latexstring(\"\\$q(z)\\$\"))\n    ax[:set_xlabel](latexstring(\"\\$z_1\\$\"), fontsize=16)\n    ax[:set_ylabel](latexstring(\"\\$z_2\\$\"), fontsize=16)\n    ax[:legend](fontsize=16)\n    \n    ## KL divergence\n    f, ax = subplots(1)\n    ax[:plot](1:max_iter, KL)\n    ax[:set_ylabel](\"KL divergence\")\n    ax[:set_xlabel](\"iteration\")\n    show()\nend\n\nmain()\n", "meta": {"hexsha": "b003b5109f8e449ac2aae3f06e45711cb2e19280", "size": 2932, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/demo_simpleVI.jl", "max_stars_repo_name": "sammy-suyama/mlblog", "max_stars_repo_head_hexsha": "da56962ef85693e5219fe3c11d9dee5df27930b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2016-08-25T11:34:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T01:40:54.000Z", "max_issues_repo_path": "src/demo_simpleVI.jl", "max_issues_repo_name": "sammy-suyama/mlblog", "max_issues_repo_head_hexsha": "da56962ef85693e5219fe3c11d9dee5df27930b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/demo_simpleVI.jl", "max_forks_repo_name": "sammy-suyama/mlblog", "max_forks_repo_head_hexsha": "da56962ef85693e5219fe3c11d9dee5df27930b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-01-13T22:51:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-19T12:35:16.000Z", "avg_line_length": 27.4018691589, "max_line_length": 114, "alphanum_fraction": 0.4976125512, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.779866071451951}}
{"text": "# Bregman divergence\n\n\"\"\"\nImplements the Bregman divergence, a friendly introduction to which can be found\n[here](http://mark.reid.name/blog/meet-the-bregman-divergences.html).\nBregman divergences are a minimal implementation of the \"mean-minimizer\" property.\n\nIt is assumed that the (convex differentiable) function F maps vectors (of any type or size) to real numbers.\nThe inner product used is `Base.dot`, but one can be passed in either by defining `inner` or by\npassing in a keyword argument. If an analytic gradient isn't available, Julia offers a suite\nof good automatic differentiation packages.\n\nfunction evaluate(dist::Bregman, p::AbstractVector, q::AbstractVector)\n\"\"\"\nstruct Bregman{T1 <: Function, T2 <: Function, T3 <: Function} <: PreMetric\n    F::T1\n    ∇::T2\n    inner::T3\nend\n\n# Default costructor.\nBregman(F, ∇) =  Bregman(F, ∇, LinearAlgebra.dot)\n\n# Evaluation fuction\nfunction (dist::Bregman)(p, q)\n    # Create cache vals.\n    FP_val = dist.F(p)\n    FQ_val = dist.F(q)\n    DQ_val = dist.∇(q)\n    p_size = length(p)\n    # Check F codomain.\n    if !(isa(FP_val, Real) && isa(FQ_val, Real))\n        throw(ArgumentError(\"F Codomain Error: F doesn't map the vectors to real numbers\"))\n    end\n    # Check vector size.\n    if p_size != length(q)\n        throw(DimensionMismatch(\"The vector p ($(size(p))) and q ($(size(q))) are different sizes.\"))\n    end\n    # Check gradient size.\n    if length(DQ_val) != p_size\n        throw(DimensionMismatch(\"The gradient result is not the same size as p and q\"))\n    end\n    # Return the Bregman divergence.\n    return FP_val - FQ_val - dist.inner(DQ_val, p .- q)\nend\n\n# Convenience function.\nbregman(F, ∇, x, y; inner = LinearAlgebra.dot) = Bregman(F, ∇, inner)(x, y)\n", "meta": {"hexsha": "81066d0525a0bc2c254e6cc64a71eb2bcd75b011", "size": 1725, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bregman.jl", "max_stars_repo_name": "jlapeyre/Distances.jl", "max_stars_repo_head_hexsha": "8d6e093e44dbd5bb5b39d703e6d01558736cd478", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bregman.jl", "max_issues_repo_name": "jlapeyre/Distances.jl", "max_issues_repo_head_hexsha": "8d6e093e44dbd5bb5b39d703e6d01558736cd478", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bregman.jl", "max_forks_repo_name": "jlapeyre/Distances.jl", "max_forks_repo_head_hexsha": "8d6e093e44dbd5bb5b39d703e6d01558736cd478", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2040816327, "max_line_length": 109, "alphanum_fraction": 0.6892753623, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7798660706340457}}
{"text": "# ---\n# title: 780. Reaching Points\n# id: problem780\n# author: Indigo\n# date: 2021-01-28\n# difficulty: Hard\n# categories: Math\n# link: <https://leetcode.com/problems/reaching-points/description/>\n# hidden: true\n# ---\n# \n# A move consists of taking a point `(x, y)` and transforming it to either `(x,\n# x+y)` or `(x+y, y)`.\n# \n# Given a starting point `(sx, sy)` and a target point `(tx, ty)`, return `True`\n# if and only if a sequence of moves exists to transform the point `(sx, sy)` to\n# `(tx, ty)`. Otherwise, return `False`.\n# \n#     \n#     \n#     **Examples:**\n#     Input: sx = 1, sy = 1, tx = 3, ty = 5\n#     Output: True\n#     Explanation:\n#     One series of moves that transforms the starting point to the target is:\n#     (1, 1) -> (1, 2)\n#     (1, 2) -> (3, 2)\n#     (3, 2) -> (3, 5)\n#     \n#     Input: sx = 1, sy = 1, tx = 2, ty = 2\n#     Output: False\n#     \n#     Input: sx = 1, sy = 1, tx = 1, ty = 1\n#     Output: True\n#     \n#     \n# \n# **Note:**\n# \n#   * `sx, sy, tx, ty` will all be integers in the range `[1, 10^9]`.\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction reaching_points(sx, sy, tx, ty)\n    while tx >= sx && ty >= sy\n        if tx == ty\n            break\n        end\n        if tx > ty\n            if ty > sy \n                tx %= ty;\n            else \n                return (tx - sx) % ty == 0;\n            end\n        else\n            if tx > sx \n                ty %= tx;\n            else \n                return (ty - sy) % tx == 0;\n            end\n        end\n    end\n    tx == sx && ty == sy\nend\n## @lc code=end\n", "meta": {"hexsha": "6dedd6dc989300f347165b6b07aa5a64c995e347", "size": 1554, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/780.reaching-points.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/780.reaching-points.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/780.reaching-points.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 22.8529411765, "max_line_length": 80, "alphanum_fraction": 0.4749034749, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7798571321026965}}
{"text": "\"\"\"\n    cilc_weights(cij, a, b)\n\nThis function returns weights (a vector of the number of frequency channels) of the constrained ILC (CILC) method.\n\n*Reference*: Equation (20) of Remazeilles, Delabrouille, Cardoso, MNRAS, 410, 2481 (2011)\n\n# Arguments\n- `cij::Array{<:AbstractFloat,2}`: symmetric covariance matrix with the dimention of `(nν, nν)` where `nν` is the number of frequency bands.\n- `a::Array{<:AbstractFloat,1}`: vector of the frequency response, for the component to be extracted. E.g., `a = [1,...,1]` for CMB.\n- `b::Array{<:AbstractFloat,1}`: vector of the frequency response, for the component to be nulled.\n\"\"\"\nfunction cilc_weights(\n    cij::Array{T,2},\n    a::Array{T,1},\n    b::Array{T,1},\n) where {T<:AbstractFloat}\n    if size(cij)[1] ≠ size(cij)[2]\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    elseif size(cij)[1] ≠ length(a) || size(cij)[1] ≠ length(b)\n        throw(DimensionMismatch(\"dimensions of the covariance matrix and the frequency response vector do not match\"))\n    elseif a ≈ b\n        throw(ErrorException(\"vectors of the frequency response are too similar\"))\n    else\n        M = Symmetric(cij)\n    end\n    x = M \\ a # R^-1 a\n    y = M \\ b # R^-1 b\n    w = (b'y * x - a'y * y) / (a'x * b'y - (a'y)^2) # ILC weights\nend\n\n\"\"\"\n    cilc_weights(cijℓ, a, b[, ℓid=3])\n\nThis function returns weights (a `nν`-by-`nℓ` matrix) of the constrained ILC (CILC) method.\n\nHere, `nν` is the number of frequency channels and `nℓ` is the number of elements in the relevant domain, e.g., multipoles, band-power bins, pixels, etc.\n\n*Reference*: Equation (20) of Remazeilles, Delabrouille, Cardoso, MNRAS, 410, 2481 (2011)\n\n# Arguments\n- `cijℓ::Array{<:AbstractFloat,3}`: symmetric covariance matrix with the dimention of `(nℓ, nν, nν)`, `(nν, nℓ, nν)` or `(nν, nν, nℓ)` (default).\n- `a::Array{<:AbstractFloat,1}`: vector of the frequency response, for the component to be extracted. E.g., `a = [1,...,1]` for CMB.\n- `b::Array{<:AbstractFloat,1}`: vector of the frequency response, for the component to be nulled.\n\n# Optional Arguments\n- `ℓid::Integer=3`: location of the index for the `nℓ` domain. `ℓid=1` if `cijℓ[nℓ,nν,nν]`, `ℓid=2` if `cijℓ[nν,nℓ,nν]`, and `ℓid=3` (the default value) if `cijℓ[nν,nν,nℓ]`.\n\"\"\"\nfunction cilc_weights(\n    cijℓ::Array{T,3},\n    a::Array{T,1},\n    b::Array{T,1},\n    ℓid::Integer = 3,\n) where {T<:AbstractFloat}\n    if ℓid > 3 || ℓid < 1\n        throw(DomainError(ℓid, \"ℓid must be 1, 2, or 3\"))\n    end\n    if (ℓid == 3 && size(cijℓ)[1] ≠ size(cijℓ)[2]) ||\n       (ℓid == 2 && size(cijℓ)[1] ≠ size(cijℓ)[3]) ||\n       (ℓid == 1 && size(cijℓ)[2] ≠ size(cijℓ)[3])\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    end\n    nℓ = size(cijℓ)[ℓid]\n    nν = ifelse(ℓid == 3, size(cijℓ)[1], size(cijℓ)[3])\n    if length(a) ≠ nν || length(b) ≠ nν\n        throw(DimensionMismatch(\"dimensions of the covariance matrix and the frequency response vector do not match\"))\n    elseif a ≈ b\n        throw(ErrorException(\"vectors of the frequency response are too similar\"))\n    else\n    end\n    wℓ = zeros(nν, nℓ) # ILC weights\n    for iℓ = 1:nℓ\n        if ℓid == 3\n            M = Symmetric(cijℓ[:, :, iℓ])\n        elseif ℓid == 2\n            M = Symmetric(cijℓ[:, iℓ, :])\n        else\n            M = Symmetric(cijℓ[iℓ, :, :])\n        end\n        x = M \\ a # R^-1 a\n        y = M \\ b # R^-1 b\n        wℓ[:, iℓ] = (b'y * x - a'y * y) / (a'x * b'y - (a'y)^2)\n    end\n    return wℓ\nend\n", "meta": {"hexsha": "09ff4d33675c96c1a89a91a3469bd9f4b1d19a37", "size": 3487, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cilc.jl", "max_stars_repo_name": "komatsu5147/CleanCMB.jl", "max_stars_repo_head_hexsha": "d44d5731f01047b6d02293cfb1b96d97b9c3e003", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-06-22T14:41:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-23T20:05:14.000Z", "max_issues_repo_path": "src/cilc.jl", "max_issues_repo_name": "komatsu5147/CleanCMB.jl", "max_issues_repo_head_hexsha": "d44d5731f01047b6d02293cfb1b96d97b9c3e003", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cilc.jl", "max_forks_repo_name": "komatsu5147/CleanCMB.jl", "max_forks_repo_head_hexsha": "d44d5731f01047b6d02293cfb1b96d97b9c3e003", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-03T15:17:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T15:17:51.000Z", "avg_line_length": 40.5465116279, "max_line_length": 173, "alphanum_fraction": 0.6105534844, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7798571304202063}}
{"text": "# Matern 1/2 isotropic covariance Function\n\n\"\"\"\n    Mat12Iso <: MaternISO\n\nIsotropic Matern 1/2 kernel (covariance)\n```math\nk(x,x') = σ^2 \\\\exp(-|x-y|/ℓ)\n```\nwith length scale ``ℓ`` and signal standard deviation ``σ``.\n\"\"\"\nmutable struct Mat12Iso{T} <: MaternIso where {T<:Real}\n    \"Length scale\"\n    ℓ::T\n    \"Signal variance\"\n    σ2::T\n    \"Priors for kernel parameters\"\n    priors::Array\nend\n\n\"\"\"\nMatern 1/2 isotropic covariance Function\n\n    Mat12Iso(ll::T, lσ::T)\n\n# Arguments\n  - `ll::Real`: length scale (given on log scale)\n  - `lσ::Real`: signal standard deviation (given on log scale)  \n\"\"\"\nMat12Iso(ll::T, lσ::T) where T = Mat12Iso{T}(exp(ll), exp(2 * lσ), [])\n\nfunction set_params!(mat::Mat12Iso, hyp::AbstractVector)\n    length(hyp) == 2 || throw(ArgumentError(\"Matern 1/2 covariance function has two parameters, received $(length(hyp)).\"))\n    mat.ℓ, mat.σ2 = exp(hyp[1]), exp(2 * hyp[2])\nend\n\nget_params(mat::Mat12Iso{T}) where T = T[log(mat.ℓ), log(mat.σ2) / 2]\nget_param_names(mat::Mat12Iso) = [:ll, :lσ]\nnum_params(mat::Mat12Iso) = 2\n\ncov(mat::Mat12Iso, r::Number) = mat.σ2 * exp(-r / mat.ℓ)\n\n@inline dk_dll(mat::Mat12Iso, r::Real) = r / mat.ℓ * cov(mat, r)\n", "meta": {"hexsha": "f74bf4a4b0261e9a548340cb17ab053bbbf2ded0", "size": 1177, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/mat12_iso.jl", "max_stars_repo_name": "mcusi/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 284, "max_stars_repo_stars_event_min_datetime": "2015-07-31T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T07:08:58.000Z", "max_issues_repo_path": "src/kernels/mat12_iso.jl", "max_issues_repo_name": "mcusi/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 171, "max_issues_repo_issues_event_min_datetime": "2015-05-28T12:04:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T06:48:23.000Z", "max_forks_repo_path": "src/kernels/mat12_iso.jl", "max_forks_repo_name": "mcusi/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-05-31T12:44:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:21:38.000Z", "avg_line_length": 26.75, "max_line_length": 123, "alphanum_fraction": 0.6440101954, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7798342002961005}}
{"text": "# indicator of the L2 norm sphere with given radius\n\n\"\"\"\n  IndSphereL2(r::Real=1.0)\n\nReturns the function `g = ind{x : ||x|| = r}`, for a real parameter `r > 0`.\n\"\"\"\n\nimmutable IndSphereL2{R <: Real} <: IndicatorNonconvex\n  r::R\n  function IndSphereL2(r::R)\n    if r <= 0\n      error(\"parameter r must be positive\")\n    else\n      new(r)\n    end\n  end\nend\n\nIndSphereL2{R <: Real}(r::R=1.0) = IndSphereL2{R}(r)\n\nfunction (f::IndSphereL2){T <: RealOrComplex}(x::AbstractArray{T})\n  if abs(vecnorm(x) - f.r)/f.r > 1e-14\n    return +Inf\n  end\n  return 0.0\nend\n\nfunction prox!{T <: RealOrComplex}(f::IndSphereL2, x::AbstractArray{T}, y::AbstractArray{T}, gamma::Real=1.0)\n  normx = vecnorm(x)\n  if normx > 0 # zero-zero?\n    scal = f.r/normx\n    for k in eachindex(x)\n      y[k] = scal*x[k]\n    end\n  else\n    normy = 0.0\n    for k in eachindex(x)\n      y[k] = randn()\n      normy += y[k]*y[k]\n    end\n    normy = sqrt(normy)\n    y[:] *= f.r/normy\n  end\n  return 0.0\nend\n\nfun_name(f::IndSphereL2) = \"indicator of an L2 norm sphere\"\nfun_dom(f::IndSphereL2) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::IndSphereL2) = \"x ↦ 0 if ||x|| = r, +∞ otherwise\"\nfun_params(f::IndSphereL2) = \"r = $(f.r)\"\n\nfunction prox_naive{T <: RealOrComplex}(f::IndSphereL2, x::AbstractArray{T}, gamma::Real=1.0)\n  normx = vecnorm(x)\n  if normx > 0\n    y = x*f.r/normx\n  else\n    y = randn(size(x))\n    y *= f.r/vecnorm(y)\n  end\n  return y, 0.0\nend\n", "meta": {"hexsha": "85a103f1063204e9ccb216b51b741b8fa4e84c1b", "size": 1434, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indSphereL2.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/indSphereL2.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/indSphereL2.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7619047619, "max_line_length": 109, "alphanum_fraction": 0.610181311, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7798341982318397}}
{"text": "#Linear Kalman filter example\n#This example closely follows that given on \"Greg Czerniak's Website\". Namely\n#the voltage example on this page: http://greg.czerniak.info/guides/kalman1/\n\n#Let's import the modules required to execute the Kalman Filter\nusing StateSpace\nusing Distributions\nusing DataFrames\nusing Gadfly\nusing Colors\n\n#To use the Kalman Filter we need three things:\n#1) Some observations\n#2) The parameters of the Kalman Filter model describing the system process and\n#the observation model.\n#3) An initial guess of the state.\n#\n#The following code is split into those three sections to begin with. We finish\n#by performing the Kalman Filter algorithm and finally displaying the results.\n\n################################################################################\n#Section: Generate noisy Observations\n#-------------------------------------------------------------------------------\n#Let's assume that the true voltage value does not change throughout the\n#experiment. So we can give the true voltage a value\ntrue_voltage = 1.25\n\n#However our measurements of the true voltage are noisy. Here we assume that the\n#noise is normally distributed with zero mean but non-zero variance:\nmeasurement_noise_variance = 0.1\n\n#Given this information we can generate some noisy data (observations). We'll\n#also choose the number of observations\nnumber_of_observations = 60\nobservations = randn(number_of_observations) * sqrt(measurement_noise_variance) + true_voltage\n\n#Note that the observation list has to be transposed because each column of the\n#matrix is considered as a new observation.\nobservations = observations'\n#End Section: Generate noisy Observations\n################################################################################\n\n################################################################################\n#Section: Describe Kalman Filter parameters\n#-------------------------------------------------------------------------------\n#Now that we have some observations we need to describe the Kalman Filter\n#parameters:\n#Process matrix - Note that since this is a one-dimensional system I've given\n#a floating point value rather than explicitly declaring a matrix with one\n#element, although you can do it that way. The value of 1.0 here means that the\n#process model suggests that the previous state is the same as the next state.\n#i.e. the voltage doesn't change.\nprocess_matrix = 1.0\n\n#Process Covariance - Since it's a single value, the covariance is the same as\n#variance. We've made it small here because we are fairly sure of our process\n#model that the state doesn't change. If we were less sure that the model was\n#correct then we would increase this value.\nprocess_covariance = 0.00001\n\n#Observation matrix - Since we measure the voltage directly (we don't measure\n#some quantity related by a function - i.e. we don't measure twice the voltage)\n#the observation matrix is equal to 1.0\nobservation_matrix = 1.0\n\n#Observation Covariance - we set the variance of the measurement noise earlier\n#so we'll give it the same value.\nobservation_covariance = measurement_noise_variance\n\n#Now we can create our Linear State Space Model\nlinSSM = LinearGaussianSSM(process_matrix, process_covariance, observation_matrix, observation_covariance)\n#End Section: Describe Kalman Filter parameters\n################################################################################\n\n################################################################################\n#Section: Set initial guess of the state\n#-------------------------------------------------------------------------------\n#We'll begin with a guess that's quite off. We'll assume an initial mean state\n#of 3 (i.e. we think we have 3 volts) and give the variance as 1\ninitial_guess = MvNormal([3.0], [1.0])\n#End Section: Set initial guess of the state\n################################################################################\n\n################################################################################\n#Section: Execute Kalman Filter\n#-------------------------------------------------------------------------------\n#Now that we have some noisy observations, the Kalman filter parameters and an\n#intial guess for the state of the system, we can run the Kalman Filter\nfiltered_state = filter(linSSM, observations, initial_guess)\n#End Section: Execute Kalman Filter\n################################################################################\n\n################################################################################\n#Section: Plot Filtered results\n#-------------------------------------------------------------------------------\n#Here we are plotting the filtered results with Gadfly. See the Gadfly\n#documentation for information about how plotting works if you are unfamiliar.\n#Website: http://gadflyjl.org/\n\nx_data = 1:number_of_observations\nstate_array = Vector{Float64}(number_of_observations+1)\nconfidence_array = Vector{Float64}(number_of_observations+1)\nstate_array[1] = initial_guess.μ[1]\nconfidence_array[1] = 2*sqrt(initial_guess.Σ.diag[1])\nfor i in x_data\n    current_state = filtered_state.state[i]\n    state_array[i+1] = current_state.μ[1]\n    confidence_array[i+1] = 2*sqrt(current_state.Σ.mat[1])\nend\ndf_fs = DataFrame(\n    x = [0;x_data],\n    y = state_array,\n    ymin = state_array - confidence_array,\n    ymax = state_array + confidence_array,\n    f = \"Filtered values\"\n    )\n\nn = 3\ngetColors = distinguishable_colors(n, Color[LCHab(70, 60, 240)],\n                                   transform=c -> deuteranopic(c, 0.5),\n                                   lchoices=Float64[65, 70, 75, 80],\n                                   cchoices=Float64[0, 50, 60, 70],\n                                   hchoices=linspace(0, 330, 24))\nfiltered_state_plot = plot(\n    layer(x=x_data, y=filtered_state.observations, Geom.point, Theme(default_color=getColors[2])),\n    layer(x=[0;x_data], y=ones(number_of_observations+1)*true_voltage, Geom.line, Theme(default_color=getColors[3])),\n    layer(df_fs, x=:x, y=:y, ymin=:ymin, ymax=:ymax, Geom.line, Geom.ribbon),\n    Guide.xlabel(\"Measurement Number\"), Guide.ylabel(\"Voltage (Volts)\"),\n    Guide.manual_color_key(\"Colour Key\",[\"Filtered Estimate\", \"Measurements\",\"True Value \"],[getColors[1],getColors[2],getColors[3]]),\n    Guide.title(\"Linear Kalman Filter Example\")\n    )\ndisplay(filtered_state_plot)\n#End Section: Plot Filtered results\n################################################################################\n\n################################################################################\n#Section: Execute Kalman Smoother\n#-------------------------------------------------------------------------------\n#Everything can be performed much better in hindsight and that's essentially\n#where the Kalman smoother comes in. Given all of the observations and the\n#filtered state (including the Kalman filter parameters, the smoother attempts\n#to give better estimates of the system's state. Here we perform smoothing on\n#the filtered data.\nsmoothed_state = smooth(linSSM, filtered_state)\n#End Section: Execute Kalman Filter\n################################################################################\n\n################################################################################\n#Section: Plot Smoothed Results\n#-------------------------------------------------------------------------------\n#Here we are plotting the smoothed results with Gadfly. See the Gadfly\n#documentation for information about how plotting works if you are unfamiliar.\n#Website: http://gadflyjl.org/\nstate_array = Vector{Float64}(number_of_observations)\nconfidence_array = Vector{Float64}(number_of_observations)\nfor i in x_data\n    current_state = smoothed_state.state[i]\n    state_array[i] = current_state.μ[1]\n    confidence_array[i] = 2*sqrt(current_state.Σ.mat[1])\nend\ndf_ss = DataFrame(\n    x = x_data,\n    y = state_array,\n    ymin = state_array - confidence_array,\n    ymax = state_array + confidence_array,\n    f = \"Filtered values\"\n    )\n\nsmoothed_state_plot = plot(\n    layer(x=x_data, y=smoothed_state.observations, Geom.point, Theme(default_color=getColors[2])),\n    layer(x=x_data, y=ones(number_of_observations)*true_voltage, Geom.line, Theme(default_color=getColors[3])),\n    layer(df_ss, x=:x, y=:y, ymin=:ymin, ymax=:ymax, Geom.line, Geom.ribbon),\n    Guide.xlabel(\"Measurement Number\"), Guide.ylabel(\"Voltage (Volts)\"),\n    Guide.manual_color_key(\"Colour Key\",[\"Smoothed Estimate\", \"Measurements\",\"True Value \"],[getColors[1],getColors[2],getColors[3]]),\n    Guide.title(\"Linear Kalman Smoother Example\")\n    )\ndisplay(smoothed_state_plot)\n#End Section: Plot Filtered results\n################################################################################\n", "meta": {"hexsha": "178e332585ba924fd0aabcf19abcb668cdef7a64", "size": 8715, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/LinearKalmanFilter_VoltageExample.jl", "max_stars_repo_name": "npsmc/StateSpace.jl", "max_stars_repo_head_hexsha": "2175c85b23dfbf3178d508a5c749627594e719e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2015-04-30T13:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T12:04:59.000Z", "max_issues_repo_path": "examples/LinearKalmanFilter_VoltageExample.jl", "max_issues_repo_name": "npsmc/StateSpace.jl", "max_issues_repo_head_hexsha": "2175c85b23dfbf3178d508a5c749627594e719e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2015-08-12T04:04:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-01T02:35:35.000Z", "max_forks_repo_path": "examples/LinearKalmanFilter_VoltageExample.jl", "max_forks_repo_name": "npsmc/StateSpace.jl", "max_forks_repo_head_hexsha": "2175c85b23dfbf3178d508a5c749627594e719e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-02-24T23:33:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T18:55:35.000Z", "avg_line_length": 48.4166666667, "max_line_length": 134, "alphanum_fraction": 0.6081468732, "num_tokens": 1769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7798341886889123}}
{"text": "\"\"\"\n    norm_data(A; dims=1, use_MAD::Bool=false, corrected::Bool=false)\n\nComputes ``\\\\frac{A - \\\\bar A}{\\\\sigma}``, where `dims` is 1 (the default) if `A` is\ncolumn-oriented and 2 if it is row-oriented. If `use_MAD` is `true`, ``\\\\bar A`` is\n`median(A, dims=dims)` and ``\\\\sigma`` is the MAD version of the standard deviation. If\n`use_MAD` is `false`, ``\\\\bar A`` is `mean(A, dims=dims)` and ``\\\\sigma`` is the standard\ndeviation. If `corrected` is `true` then the sum is scaled with `n-1`, whereas the sum is\nscaled with `n` if `corrected` is `false`, where `n = size(A, dims)`.\n\"\"\"\nfunction norm_data(A; dims=1, use_MAD=false, corrected=false)\n    A = Matrix{Float64}(A)\n    if use_MAD\n        return (A .- median(A, dims=dims)) ./ mapslices(mad, A, dims=dims)\n    else\n        return (A .- mean(A, dims=dims)) ./ std(A, dims=dims, corrected=corrected)\n    end\nend\n\n\"\"\"\n    classic_PCA(A; dims=1, standardize::Bool=true, corrected::Bool=false)\n\nPerforms PCA on a copy of the ``m × n`` matrix `A`. `dims` is 1 (the default) if `A` is\ncolumn-oriented and 2 if it is row-oriented. If `standardize` is `true` (the default), the\ncopy will be transformed using the MAD version of the standard deviation. If `corrected`\nis `true` then the sum is scaled with `n-1`, whereas the sum is scaled with `n` if\n`corrected` is `false`, where `n = size(A, dims)`.\n\nReturns `(V, S, prod)`, where ``A = U Σ V^*``, with ``Σ = \\\\text{diagm}(S)`` being the\ndiagonal matrix of singular values sorted in descending order and `prod` is the matrix\nmultiplication of `V` and `A`, with `A` being standardized by default.\n\"\"\"\nfunction classic_PCA(A; dims=1, standardize=true, corrected=false)\n    data = copy(A)\n    data = standardize ? norm_data(data, dims=dims, use_MAD=true, corrected=corrected) : data\n    U, S, V = svd(cov(data, dims=dims, corrected=corrected))\n    prod = dims == 1 ? data * V : V' * data\n    return V, S, prod\nend\n", "meta": {"hexsha": "a25f61e60a1ed7684dac62929d92187cb3a1e7bc", "size": 1911, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/detrending.jl", "max_stars_repo_name": "icweaver/ACCESS.jl", "max_stars_repo_head_hexsha": "5e3e064f5b6df70b532d68f7c9b285b58288f34e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/detrending.jl", "max_issues_repo_name": "icweaver/ACCESS.jl", "max_issues_repo_head_hexsha": "5e3e064f5b6df70b532d68f7c9b285b58288f34e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/detrending.jl", "max_forks_repo_name": "icweaver/ACCESS.jl", "max_forks_repo_head_hexsha": "5e3e064f5b6df70b532d68f7c9b285b58288f34e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.775, "max_line_length": 93, "alphanum_fraction": 0.6614338043, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8479677660619634, "lm_q1q2_score": 0.7798272264735242}}
{"text": "@doc raw\"\"\"\n    usinc(θ::Real)\n\nUnnormalized version of `sinc` function, i.e. $\\operatorname{usinc}(θ) = \\frac{\\sin(θ)}{θ}$.\nThis is equivalent to `sinc(θ/π)`.\n\"\"\"\n@inline usinc(θ::Real) = θ == 0 ? one(θ) : isinf(θ) ? zero(θ) : sin(θ) / θ\n\n@doc raw\"\"\"\n    usinc_from_cos(x::Real)\n\nUnnormalized version of `sinc` function, i.e. $\\operatorname{usinc}(θ) = \\frac{\\sin(θ)}{θ}$,\ncomputed from $x = cos(θ)$.\n\"\"\"\n@inline function usinc_from_cos(x::Real)\n    return if x >= 1\n        one(x)\n    elseif x <= -1\n        zero(x)\n    else\n        sqrt(1 - x^2) / acos(x)\n    end\nend\n\n@doc raw\"\"\"\n    nzsign(z[, absz])\n\nCompute a modified `sign(z)` that is always nonzero, i.e. where\n````math\n\\operatorname(nzsign)(z) = \\begin{cases}\n    1 & \\text{if } z = 0\\\\\n    \\frac{z}{|z|} & \\text{otherwise}\n\\end{cases}\n````\n\"\"\"\n@inline function nzsign(z, absz=abs(z))\n    psignz = z / absz\n    return ifelse(iszero(absz), one(psignz), psignz)\nend\n\nallocate(p, s::Size{S}) where {S} = similar(p, S...)\nallocate(p::StaticArray, s::Size{S}) where {S} = similar(p, maybesize(s))\nallocate(p, ::Type{T}, s::Size{S}) where {S,T} = similar(p, T, S...)\nallocate(p::StaticArray, ::Type{T}, s::Size{S}) where {S,T} = similar(p, T, maybesize(s))\n\n\"\"\"\n    eigen_safe(x)\n\nCompute the eigendecomposition of `x`. If `x` is a `StaticMatrix`, it is\nconverted to a `Matrix` before the decomposition.\n\"\"\"\n@inline eigen_safe(x; kwargs...) = eigen(x; kwargs...)\n@inline function eigen_safe(x::StaticMatrix; kwargs...)\n    s = size(x)\n    E = eigen!(Matrix(parent(x)); kwargs...)\n    return Eigen(SizedVector{s[1]}(E.values), SizedMatrix{s...}(E.vectors))\nend\n\n\"\"\"\n    log_safe(x)\n\nCompute the matrix logarithm of `x`. If `x` is a `StaticMatrix`, it is\nconverted to a `Matrix` before computing the log.\n\"\"\"\n@inline log_safe(x) = log(x)\n@inline function log_safe(x::StaticMatrix)\n    s = Size(x)\n    return SizedMatrix{s[1],s[2]}(log(Matrix(parent(x))))\nend\n\n# NOTE: workaround until https://github.com/JuliaLang/julia/pull/39973 or similar is merged\n\"\"\"\n    log_safe!(y, x)\n\nCompute the matrix logarithm of `x`. If the eltype of `y` is real, then the imaginary part\nof `x` is ignored, and a `DomainError` is raised if `real(x)` has no real logarithm.\n\"\"\"\nfunction log_safe!(Y, A)\n    if eltype(Y) <: Real\n        if ishermitian(A)\n            eigenF = eigen(Symmetric(real(A)))\n            i = findfirst(≤(0), eigenF.values)\n            if i !== nothing\n                throw(\n                    DomainError(\n                        eigenF.values[i],\n                        \"All eigenvalues must be positive to compute a real logarithm.\",\n                    ),\n                )\n            end\n            mul!(Y, eigenF.vectors .* log.(eigenF.values'), eigenF.vectors')\n        elseif istriu(A)\n            i = findfirst(≤(0), @view(A[diagind(A)]))\n            if i !== nothing\n                throw(\n                    DomainError(\n                        A[i, i],\n                        \"All eigenvalues must be positive to compute a real logarithm.\",\n                    ),\n                )\n            end\n            copyto!(Y, real(log(UpperTriangular(A))))\n        else\n            schurF = schur(convert(Matrix, real(A)))\n            i = findfirst(x -> isreal(x) && real(x) ≤ 0, schurF.values)\n            if i !== nothing\n                throw(\n                    DomainError(\n                        schurF.values[i],\n                        \"All eigenvalues must be positive to compute a real logarithm.\",\n                    ),\n                )\n            end\n            if istriu(schurF.T)\n                mul!(Y, schurF.Z, real(log(UpperTriangular(schurF.T))) * schurF.Z')\n            else\n                schurS = schur(complex(schurF.T))\n                Y .= real.(schurS.Z * log(UpperTriangular(schurS.T)) * schurS.Z')\n                mul!(Y, schurF.Z * Y, schurF.Z')\n            end\n        end\n    else\n        copyto!(Y, log_safe(A))\n    end\n    return Y\nend\n\n\"\"\"\n    mul!_safe(Y, A, B) -> Y\n\nCall `mul!` safely, that is, `A` and/or `B` are permitted to alias with `Y`.\n\"\"\"\nmul!_safe(Y, A, B) = (Y === A || Y === B) ? copyto!(Y, A * B) : mul!(Y, A, B)\n\n@doc raw\"\"\"\n    realify(X::AbstractMatrix{T𝔽}, 𝔽::AbstractNumbers) -> Y::AbstractMatrix{<:Real}\n\nGiven a matrix $X ∈ 𝔽^{n × n}$, compute $Y ∈ ℝ^{m × m}$, where $m = n \\operatorname{dim}_𝔽$,\nand $\\operatorname{dim}_𝔽$ is the [`real_dimension`](@ref) of the number field $𝔽$, using\nthe map $ϕ \\colon X ↦ Y$, that preserves the matrix product, so that for all\n$C,D ∈ 𝔽^{n × n}$,\n````math\nϕ(C) ϕ(D) = ϕ(CD).\n````\nSee [`realify!`](@ref) for an in-place version, and [`unrealify!`](@ref) to compute the\ninverse of $ϕ$.\n\"\"\"\nfunction realify(X, 𝔽)\n    n = LinearAlgebra.checksquare(X)\n    nℝ = real_dimension(𝔽) * n\n    Y = allocate(X, real(eltype(X)), nℝ, nℝ)\n    return realify!(Y, X, 𝔽, n)\nend\nrealify(X, ::typeof(ℝ)) = X\n\n\"\"\"\n    realify!(Y::AbstractMatrix{<:Real}, X::AbstractMatrix{T𝔽}, 𝔽::AbstractNumbers)\n\nIn-place version of [`realify`](@ref).\n\"\"\"\nrealify!(Y, X, 𝔽)\n\n@doc raw\"\"\"\n    realify!(Y::AbstractMatrix{<:Real}, X::AbstractMatrix{<:Complex}, ::typeof(ℂ))\n\nGiven a complex matrix $X = A + iB ∈ ℂ^{n × n}$, compute its realified matrix\n$Y ∈ ℝ^{2n × 2n}$, written\nwhere\n````math\nY = \\begin{pmatrix}A & -B \\\\ B & A \\end{pmatrix}.\n````\n\"\"\"\nfunction realify!(Y, X, ::typeof(ℂ), n=LinearAlgebra.checksquare(X))\n    for i in 1:n, j in 1:n\n        Xr, Xi = reim(X[i, j])\n        Y[i, j] = Y[n + i, n + j] = Xr\n        Y[n + i, j] = Xi\n        Y[i, n + j] = -Xi\n    end\n    return Y\nend\n\n@doc raw\"\"\"\n    unrealify!(X::AbstractMatrix{T𝔽}, Y::AbstractMatrix{<:Real}, 𝔽::AbstractNumbers[, n])\n\nGiven a real matrix $Y ∈ ℝ^{m × m}$, where $m = n \\operatorname{dim}_𝔽$, and\n$\\operatorname{dim}_𝔽$ is the [`real_dimension`](@ref) of the number field $𝔽$, compute\nin-place its equivalent matrix $X ∈ 𝔽^{n × n}$. Note that this function does not check that\n$Y$ has a valid structure to be un-realified.\n\nSee [`realify!`](@ref) for the inverse of this function.\n\"\"\"\nunrealify!(X, Y, 𝔽)\n\nfunction unrealify!(X, Y, ::typeof(ℂ), n=LinearAlgebra.checksquare(X))\n    for i in 1:n, j in 1:n\n        X[i, j] = complex((Y[i, j] + Y[n + i, n + j]) / 2, (Y[n + i, j] - Y[i, n + j]) / 2)\n    end\n    return X\nend\nunrealify!(Y, X, ::typeof(ℝ), args...) = copyto!(Y, X)\n\n@generated maybesize(s::Size{S}) where {S} = prod(S) > 100 ? S : :(s)\n\n\"\"\"\n    select_from_tuple(t::NTuple{N, Any}, positions::Val{P})\n\nSelects elements of tuple `t` at positions specified by the second argument.\nFor example `select_from_tuple((\"a\", \"b\", \"c\"), Val((3, 1, 1)))` returns\n`(\"c\", \"a\", \"a\")`.\n\"\"\"\n@generated function select_from_tuple(t::NTuple{N,Any}, positions::Val{P}) where {N,P}\n    for k in P\n        (k < 0 || k > N) && error(\"positions must be between 1 and $N\")\n    end\n    return Expr(:tuple, [Expr(:ref, :t, k) for k in P]...)\nend\n\n@doc raw\"\"\"\n    vec2skew!(X, v, k)\n\ncreate a skew symmetric matrix inplace in `X` of size $k\\times k$ from a vector `v`,\nfor example for `v=[1,2,3]` and `k=3` this\nyields\n````julia\n[  0  1  2;\n  -1  0  3;\n  -2 -3  0\n]\n````\n\"\"\"\nfunction vec2skew!(X, v)\n    k = size(X)[1]\n    size(X)[2] != k && error(\"X is of wrong size, expected ($k,$k) got $(size(X)).\")\n    n = div(k * (k - 1), 2)\n    length(v) < n && error(\"The vector $(v) is too short, expected $(n) got $(length(v)).\")\n    m = 0\n    X .= [i < j ? (m += 1; v[m]) : zero(eltype(v)) for i in 1:k, j in 1:k]\n    X .= X - X'\n    return X\nend\nfunction vec2skew(v, k)\n    X = similar(v, k, k)\n    vec2skew!(X, v)\n    return X\nend\n\n@doc raw\"\"\"\n    isnormal(x; kwargs...) -> Bool\n\nCheck if the matrix or number `x` is normal, that is, if it commutes with its adjoint:\n````math\nx x^\\mathrm{H} = x^\\mathrm{H} x.\n````\nBy default, this is an equality check. Provide `kwargs` for `isapprox` to perform an\napproximate check.\n\"\"\"\nfunction isnormal(x; kwargs...)\n    (isdiag(x) || ishermitian(x)) && return true\n    isempty(kwargs) && return x * x' == x' * x\n    return isapprox(x * x', x' * x; kwargs...)\nend\nisnormal(::LinearAlgebra.RealHermSymComplexHerm; kwargs...) = true\n\n\"\"\"\n    ziptuples(a, b[, c[, d[, e]]])\n\nZips tuples `a`, `b`, and remaining in a fast, type-stable way. If they have different\nlengths, the result is trimmed to the length of the shorter tuple.\n\"\"\"\n@generated function ziptuples(a::NTuple{N,Any}, b::NTuple{M,Any}) where {N,M}\n    ex = Expr(:tuple)\n    for i in 1:min(N, M)\n        push!(ex.args, :((a[$i], b[$i])))\n    end\n    return ex\nend\n@generated function ziptuples(\n    a::NTuple{N,Any},\n    b::NTuple{M,Any},\n    c::NTuple{L,Any},\n) where {N,M,L}\n    ex = Expr(:tuple)\n    for i in 1:min(N, M, L)\n        push!(ex.args, :((a[$i], b[$i], c[$i])))\n    end\n    return ex\nend\n@generated function ziptuples(\n    a::NTuple{N,Any},\n    b::NTuple{M,Any},\n    c::NTuple{L,Any},\n    d::NTuple{K,Any},\n) where {N,M,L,K}\n    ex = Expr(:tuple)\n    for i in 1:min(N, M, L, K)\n        push!(ex.args, :((a[$i], b[$i], c[$i], d[$i])))\n    end\n    return ex\nend\n@generated function ziptuples(\n    a::NTuple{N,Any},\n    b::NTuple{M,Any},\n    c::NTuple{L,Any},\n    d::NTuple{K,Any},\n    e::NTuple{J,Any},\n) where {N,M,L,K,J}\n    ex = Expr(:tuple)\n    for i in 1:min(N, M, L, K, J)\n        push!(ex.args, :((a[$i], b[$i], c[$i], d[$i], e[$i])))\n    end\n    return ex\nend\n", "meta": {"hexsha": "dc8f2d638b2c85f0b4db652d41a76c0442ef3c46", "size": 9266, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "Nikdwal/Manifolds.jl", "max_stars_repo_head_hexsha": "10d264d146159015fdebab94b7394b9f74728381", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "Nikdwal/Manifolds.jl", "max_issues_repo_head_hexsha": "10d264d146159015fdebab94b7394b9f74728381", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "Nikdwal/Manifolds.jl", "max_forks_repo_head_hexsha": "10d264d146159015fdebab94b7394b9f74728381", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5095541401, "max_line_length": 92, "alphanum_fraction": 0.557306281, "num_tokens": 3126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7798272249086506}}
{"text": "### A Pluto.jl notebook ###\n# v0.19.4\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local iv = try Base.loaded_modules[Base.PkgId(Base.UUID(\"6e696c72-6542-2067-7265-42206c756150\"), \"AbstractPlutoDingetjes\")].Bonds.initial_value catch; b -> missing; end\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)\n        el\n    end\nend\n\n# ╔═╡ 7c860884-5afd-4b4a-b358-4f2bce8bd395\nusing Pkg; Pkg.activate(\"../..\")\n\n# ╔═╡ 38c4e220-d708-11ec-3968-fbbd41c26155\nusing PlutoUI, Plots, DifferentialEquations, NonLinearDynamicsCourse\n\n# ╔═╡ 2ac364c2-cbdd-49b4-9f26-9fe89382be5e\nTableOfContents(title=\"📚 Table of Contents\", indent=true, depth=4, aside=true)\n\n# ╔═╡ 6b6a5e19-5298-4969-b1c9-699aa1cb2996\nhtml\"\"\"\n<style>\ninput[type*=\"range\"] {\n\twidth: 50%;\n}\n</style>\n\"\"\"\n\n# ╔═╡ 62cba86d-4406-4d16-8715-b29bee7d3178\nmd\"\"\"\n# Logistic Equation\n\n$\\dot{x}=Rx\\left(1-\\frac{x}{K}\\right)$\n\"\"\"\n\n# ╔═╡ 6d64cc27-1059-4dd7-8f17-1c6fd9a2eca0\nhtml\"\"\"\n<div style=\"position: relative; right: 0; top: 0; z-index: 300;\"><iframe src=\"https://www.youtube.com/embed/JwYhhnuuINk\" width=500 height=250  frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe></div>\n\"\"\"\n\n# ╔═╡ 4dc32b5a-5794-4d2d-844e-cdb80bec2e7b\nlogistic(x,p,t)=p[1]*x*(1.0-x/p[2])\n\n# ╔═╡ 77766c99-4142-4acb-a855-ab133e67aa66\n@bind pars2 (\n\tPlutoUI.combine() do bind\n\t\tmd\"\"\"\n\t\tR: $(bind(Slider(0:0.02:2.0,default=0.1;show_value=true))) \\\n\t\tK: $(bind(Slider(0.01:0.02:2.0,default=0.1;show_value=true))) \\\n\t\tx0: $(bind(Slider(0:0.02:2.0,default=0.1;show_value=true)))\n\t\t\"\"\"\n\tend\n)\n\n# ╔═╡ 16a156b5-92ab-4e1c-ab70-c3b348186c57\nflux1D(logistic,pars2[3],100.0,pars2;xlims=[-0.1,2.0],title=\"Logistic\")\n\n# ╔═╡ ce4da9bf-316b-45d2-8504-f2a63cdda247\nmd\"\"\"\n# Logistic Equation with Harvest\n\n$\\dot{x}=Rx\\left(1-\\frac{x}{K}\\right)-H$\n\"\"\"\n\n# ╔═╡ 29474ca0-839b-45de-a7bf-7d91c5ea59aa\nlogharvest1(x,p,t)=p[1]*x*(1.0-x/p[2])-p[3]\n\n# ╔═╡ 8fc407f4-a242-4cdc-b7e0-062c8f5782d1\n@bind pars_harvest (\n\tPlutoUI.combine() do bind\n\t\tmd\"\"\"\n\t\tR: $(bind(Slider(0:0.02:2.0,default=0.1;show_value=true))) \\\n\t\tK: $(bind(Slider(0.01:0.02:2.0,default=0.1;show_value=true))) \\\n\t\tH: $(bind(Slider(0.01:0.02:2.0,default=0.1;show_value=true))) \\\n\t\tx0: $(bind(Slider(0:0.02:2.0,default=0.1;show_value=true)))\n\t\t\"\"\"\n\tend\n)\n\n# ╔═╡ 794936ae-d9ae-4319-994f-4282c99c4238\nflux1D(logharvest1,pars_harvest[4],300.0,pars_harvest,(u)->(u<0);xlims=[0.0,2.0],title=\"Logistic with Harvest\")\n\n# ╔═╡ b13d261e-1c1b-41b0-ae86-e20cd2304727\nmd\"\"\"\n## Critical Slowing Down\n\"\"\"\n\n# ╔═╡ c3757398-060c-412c-997b-58331b2dee04\n@bind pars_csd (\n\tPlutoUI.combine() do bind\n\t\tmd\"\"\"\n\t\tH: $(bind(Slider(0.2:0.002:0.25,default=0.1;show_value=true))) \\\n\t\tS: $(bind(Slider(0:0.001:0.1,default=0.0;show_value=true)))\n\t\t\"\"\"\n\tend\n)\n\n# ╔═╡ f1f04dd4-0447-4e48-9bab-f34058a6a0f1\nflux1D(logharvest1,0.5+sqrt(0.25-pars_csd[1]),200.0,[1.0,1.0,pars_csd[1]],10.0,pars_csd[2],(u)->(u<0);xlims=[0.0,1.0],title=\"Log whith Harvest perturbed\")\n\n# ╔═╡ c803ed90-958c-4d0e-84d5-3e8cc9c8fbfe\nmd\"\"\"\n# Consumer Equation\n\n$\\dot{x} = Rx\\left(1-\\frac{x}{K}\\right) - Px$ \n\"\"\"\n\n# ╔═╡ b4ea8364-a582-443c-bdb1-46e75a5c4d4e\n# Consumer Equation\nconsumer(x,p,t)=p[1]*x*(1.0-x/p[2])-p[3]*x\n\n# ╔═╡ 5afa3aff-af15-429b-a0fb-9a0dfcad740d\n@bind pars_consumer (\n\tPlutoUI.combine() do bind\n\t\tmd\"\"\"\n\t\tR: $(bind(Slider(0:0.02:1.0,default=0.1;show_value=true))) \\\n\t\tK: $(bind(Slider(0.01:0.02:2.0,default=0.1;show_value=true))) \\\n\t\tP: $(bind(Slider(0.0:0.01:0.5,default=0.1;show_value=true))) \\\n\t\tx0: $(bind(Slider(0:0.02:2.0,default=0.1;show_value=true)))\n\t\t\"\"\"\n\tend\n)\n\n# ╔═╡ 5018d342-0a51-4275-8c0f-1b5d253c2ec0\nflux1D(consumer,pars_consumer[4],300.0,pars_consumer,xlims=[0.0,2.0],title=\"Consumer Equation\")\n\n# ╔═╡ 84a596c1-3a0a-4edd-a7ea-f3fcd8839c2a\nmd\"\"\"\n# Logistic Equation with Outbreak\n\n$\\dot{x} = Rx\\left(1-\\displaystyle\\frac{x}{K}\\right)-P\\displaystyle\\frac{x^2}{1+x^2}$\n\"\"\"\n\n# ╔═╡ 91b2718a-a921-4bae-99c0-91ec9c7e6479\nhtml\"\"\"\n<div style=\"position: relative; right: 0; top: 0; z-index: 300;\"><iframe src=\"https://www.youtube.com/embed/1CSKTCS6st8\" width=500 height=250  frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe></div>\n\"\"\"\n\n# ╔═╡ 5a0b156e-b0b2-43b8-b15e-bcdb65c154bf\nlogoutbreak(x,p,t)=p[1]*x*(1.0-x/p[2])-p[3]*x*x/(1+x*x)\n\n# ╔═╡ 6528501f-3bb2-48a7-b24e-d32400033538\n@bind pars_outbreak (\n\tPlutoUI.combine() do bind\n\t\tmd\"\"\"\n\t\tR: $(bind(Slider(0:0.02:2.0,default=0.1;show_value=true))) \\\n\t\tK: $(bind(Slider(0.01:0.02:10.0,default=0.1;show_value=true))) \\\n\t\tP: $(bind(Slider(0.0:0.01:1.0,default=0.1;show_value=true))) \\\n\t\tx0: $(bind(Slider(0:0.02:8.0,default=0.1;show_value=true)))\n\t\t\"\"\"\n\tend\n)\n\n# ╔═╡ a3270d8b-f167-4fb9-bcc5-c62c91b39649\nflux1D(logoutbreak,pars_outbreak[4],300.0,pars_outbreak;xlims=[-0.2,8.0],title=\"Log with Outbreak\")\n\n# ╔═╡ 0d0d6d2f-56b2-4e01-b9a4-6e469eac90ad\nhtml\"\"\"\n<div style=\"position: relative; right: 0; top: 0; z-index: 300;\"><iframe src=\"https://www.youtube.com/embed/MlwAI3BlDsU\" width=500 height=250  frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe></div>\n\"\"\"\n\n# ╔═╡ 76cfd5c8-6298-4ae2-9d2d-9e60deb12f49\nhtml\"\"\"\n<div style=\"position: relative; right: 0; top: 0; z-index: 300;\"><iframe src=\"https://www.youtube.com/embed/yUEXpUyi404\" width=500 height=250  frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe></div>\n\"\"\"\n\n# ╔═╡ 0bf40552-b627-4fa7-b3ba-1d8c7ed4a568\nhtml\"\"\"\n<div style=\"position: relative; right: 0; top: 0; z-index: 250;\"><iframe src=\"https://www.youtube.com/embed/Vu9oNWXv4Uk\" width=500 height=250  frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe></div>\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─7c860884-5afd-4b4a-b358-4f2bce8bd395\n# ╠═38c4e220-d708-11ec-3968-fbbd41c26155\n# ╟─2ac364c2-cbdd-49b4-9f26-9fe89382be5e\n# ╟─6b6a5e19-5298-4969-b1c9-699aa1cb2996\n# ╟─62cba86d-4406-4d16-8715-b29bee7d3178\n# ╟─6d64cc27-1059-4dd7-8f17-1c6fd9a2eca0\n# ╠═4dc32b5a-5794-4d2d-844e-cdb80bec2e7b\n# ╟─16a156b5-92ab-4e1c-ab70-c3b348186c57\n# ╟─77766c99-4142-4acb-a855-ab133e67aa66\n# ╟─ce4da9bf-316b-45d2-8504-f2a63cdda247\n# ╠═29474ca0-839b-45de-a7bf-7d91c5ea59aa\n# ╟─794936ae-d9ae-4319-994f-4282c99c4238\n# ╟─8fc407f4-a242-4cdc-b7e0-062c8f5782d1\n# ╟─b13d261e-1c1b-41b0-ae86-e20cd2304727\n# ╟─f1f04dd4-0447-4e48-9bab-f34058a6a0f1\n# ╟─c3757398-060c-412c-997b-58331b2dee04\n# ╟─c803ed90-958c-4d0e-84d5-3e8cc9c8fbfe\n# ╠═b4ea8364-a582-443c-bdb1-46e75a5c4d4e\n# ╟─5018d342-0a51-4275-8c0f-1b5d253c2ec0\n# ╟─5afa3aff-af15-429b-a0fb-9a0dfcad740d\n# ╟─84a596c1-3a0a-4edd-a7ea-f3fcd8839c2a\n# ╟─91b2718a-a921-4bae-99c0-91ec9c7e6479\n# ╠═5a0b156e-b0b2-43b8-b15e-bcdb65c154bf\n# ╟─a3270d8b-f167-4fb9-bcc5-c62c91b39649\n# ╟─6528501f-3bb2-48a7-b24e-d32400033538\n# ╟─0d0d6d2f-56b2-4e01-b9a4-6e469eac90ad\n# ╟─76cfd5c8-6298-4ae2-9d2d-9e60deb12f49\n# ╟─0bf40552-b627-4fa7-b3ba-1d8c7ed4a568\n", "meta": {"hexsha": "a87191878755a5081f448fa939003592522d4960", "size": 7248, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Lectures/Pluto/NLD_Flux1D_Population_Models.jl", "max_stars_repo_name": "meguia/NonLinearDynamicsCourse.jl", "max_stars_repo_head_hexsha": "3dec755694718cb2917999293294fd2cedb9f2ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lectures/Pluto/NLD_Flux1D_Population_Models.jl", "max_issues_repo_name": "meguia/NonLinearDynamicsCourse.jl", "max_issues_repo_head_hexsha": "3dec755694718cb2917999293294fd2cedb9f2ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lectures/Pluto/NLD_Flux1D_Population_Models.jl", "max_forks_repo_name": "meguia/NonLinearDynamicsCourse.jl", "max_forks_repo_head_hexsha": "3dec755694718cb2917999293294fd2cedb9f2ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0144927536, "max_line_length": 270, "alphanum_fraction": 0.7028145695, "num_tokens": 3388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.77982722304109}}
{"text": "#=\nCreated on Wednesday 18 March 2020\nLast update: Tuesday 23 March 2020\n\n@author: Michiel Stock\nmichielfmstock@gmail.com\n\nThis is an illustration of solving the Krontrovich formulation of the optimal\ntransport problem. It also demonstrates the use of Convex.jl, a package for\nconvex optimization problems.\n=#\n\nusing Convex, SCS\n\n# first give the problem parameters, we use the dessert problem\n\n# portions per person\na = [3.0, 3, 3, 4, 2, 2, 2, 1]\n# quantities of each dessert\nb = [4.0, 2, 6, 4, 4]\n\n# should both have the same sum\n@assert sum(a) ≈ sum(b)\n\npreferences = [2 2 1 0 0;\n              0 -2 -2 -2 2;\n              1 2 2 2 -1;\n              2 1 0 1 -1;\n              0.5 2 2 1 0;\n              0 1 1 1 -1;\n             -2 2 2 1 1;\n              2 1 2 1 -1]\n\nC = -preferences\n\nn, m = size(C)\n\nP = Variable(n, m)\n\nproblem = minimize(sum(P .* C),  # objective\n                    P >= 0,  # non-neg constraints\n                    P * ones(m) == a,  # row marginals\n                    P' * ones(n) == b)  # column marginals\n\nsolve!(problem, () -> SCS.Optimizer(verbose=false))\n\npstar = problem.optval  # best objective\nPstar = P.value  # distribution\n\nusing StatsPlots\n\ngroupedbar(Pstar, bar_position = :stack, title=\"Optimal distribution desserts\\nobjective = $pstar\")\n\nsavefig(\"figures/kantovorisc.png\")\n", "meta": {"hexsha": "385561400e2bf0ba74d0f940861c20bb3b00637d", "size": 1314, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/kantorovich.jl", "max_stars_repo_name": "f6v/STMO", "max_stars_repo_head_hexsha": "cbbb8083caeaef361fbcaa7e60c687ff6f0db17e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2020-01-28T15:43:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T07:35:52.000Z", "max_issues_repo_path": "scripts/kantorovich.jl", "max_issues_repo_name": "f6v/STMO", "max_issues_repo_head_hexsha": "cbbb8083caeaef361fbcaa7e60c687ff6f0db17e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-02-04T16:30:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-30T11:24:57.000Z", "max_forks_repo_path": "scripts/kantorovich.jl", "max_forks_repo_name": "f6v/STMO", "max_forks_repo_head_hexsha": "cbbb8083caeaef361fbcaa7e60c687ff6f0db17e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2020-02-09T15:13:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T18:32:40.000Z", "avg_line_length": 23.8909090909, "max_line_length": 99, "alphanum_fraction": 0.603500761, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7798272192050726}}
{"text": "#=##############################################################################\n# DESCRIPTION\n    Methods for generation of conic sections\n# AUTHORSHIP\n  * Author    : Eduardo J Alvarez\n  * Email     : Edo.AlvarezR@gmail.com\n  * Created   : Sep 2019\n  * License   : MIT License\n=###############################################################################\n\n\n\"\"\"\n    `line_intersect(x1, y1, x2, y2, x3, y3, x4, y4)`\n\n    Returns the intersect between two lines, with the first line\npassing through the points `(x1, y1), (x2, y2)`, and the second line passing\nthrough the points `(x3, y3), (x4, y4)`.\n\"\"\"\nfunction line_intersect(x1, y1, x2, y2, x3, y3, x4, y4)\n    Px = (\n            (x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4 - y3*x4)\n         ) / (\n            (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)\n         )\n    Py = (\n            (x1*y2-y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4)\n         ) / (\n            (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)\n         )\n\n    return Px, Py\nend\n\n\"\"\"\n    `generate_conic_fun(Ax::Real, Ay::Real, Bx::Real, By::Real, Cx::Real, Cy::Real, Sx::Real, Sy::Real)`\n\n     Returns a conic curve function with control point A, B, and C, and shoulder point S. \n        See Raymer's Aircraft Design, lofting chapter (p. 128).\n\"\"\"\nfunction generate_conic_fun(Ax::Real, Ay::Real, Bx::Real, By::Real,\n                            Cx::Real, Cy::Real, Sx::Real, Sy::Real)\n\n    \"\"\"\n        Receives a value between 0 and 1, and returns the\n    corresponding point along the conic curve, with 0 being A\n    and 1 B.\n    \"\"\"\n    function conic_fun(s)\n        if s<0 || s>1\n            error(\"Invalid conic parameter $s. Value between 0 and 1 expected.\")\n        end\n\n        # D: Point in between A and B\n        Dx = Ax + s*(Bx-Ax)\n        Dy = Ay + s*(By-Ay)\n\n        # E: Intersect between AS and CD\n        Ex, Ey = line_intersect(Ax, Ay, Sx, Sy, Cx, Cy, Dx, Dy)\n\n        # F: Intersect between BS and CD\n        Fx, Fy = line_intersect(Bx, By, Sx, Sy, Cx, Cy, Dx, Dy)\n\n        # P: Intersect between AF and BE\n        Px, Py = line_intersect(Ax, Ay, Fx, Fy, Bx, By, Ex, Ey)\n\n        return Px, Py\n    end\n\n    return conic_fun\nend\n\n\n\"\"\"\n    `generate_conic_fun(Ax::Real, Ay::Real, Bx::Real, By::Real, Cx::Real, Cy::Real, rho::Real)`\n\n    Returns a conic curve function with control point A, B, and C, and shape parameter rho. \n        See Raymer's Aircraft Design, lofting chapter (p. 132).\n\n    Hyperbola: rho > 0.5\n    Parabola:  rho = 0.5\n    Ellipse:   rho < 0.5\n    Circle:    rho = 0.4142 and AC = BC\n\"\"\"\nfunction generate_conic_fun(Ax::Real, Ay::Real, Bx::Real, By::Real,\n                            Cx::Real, Cy::Real, rho::Real)\n\n    # D: Midpoint between A and B\n    Dx = Ax + 0.5*(Bx-Ax)\n    Dy = Ay + 0.5*(By-Ay)\n\n    # S: Shoulder point in between D and C\n    Sx = Dx + rho*(Cx-Dx)\n    Sy = Dy + rho*(Cy-Dy)\n\n    return generate_conic_fun(Ax, Ay, Bx, By, Cx, Cy, Sx, Sy)\nend\n\n\n\"\"\"\n    `conic_cross_section(Ps::Array{Array{T1, 1},1}, CPs::Array{Array{T2, 1},1},\nrhos::Array{T3, 1}, ss::Array{Array{T4, 1},1})`\n\n    Receives a collection of points `Ps` along an open contour, and\nstretching control points `CPs`, shape parameters `rhos`, and probing\nparameters `ss` associated to every section of the contour, and it returns\na compound-conic cross section (it is a closed loop, so the number of\nsections is equal to the number of points)\n\"\"\"\nfunction conic_cross_section(Ps::Array{Array{T1, 1},1},\n                             CPs::Array{Array{T2, 1},1},\n                             rhos::Array{T3, 1},\n                             ss::Array{Array{T4, 1},1}\n                            ) where {T1<:Real, T2<:Real, T3<:Real, T4<:Real}\n    nPs = size(Ps, 1)\n\n    if size(CPs, 1)!=nPs\n        error(\"Invalid CPs. Expected $nPs, got $(size(CPs, 1)).\")\n    elseif size(rhos, 1)!=nPs\n        error(\"Invalid rhos. Expected $nPs, got $(size(rhos, 1)).\")\n    elseif size(ss, 1)!=nPs\n        error(\"Invalid ss. Expected $nPs, got $(size(ss, 1)).\")\n    end\n\n    points = []\n\n    for i in 1:nPs\n        A = Ps[i]\n        B = Ps[i%nPs + 1]\n\n        conic_fun = generate_conic_fun(Ps[i]..., Ps[i%nPs + 1]...,\n                                                CPs[i]..., rhos[i])\n        for s in ss[i]\n            push!(points, [conic_fun(s)...])\n        end\n    end\n\n    return points\nend\n", "meta": {"hexsha": "fc4658c59246d48f9689cc300397e17b2f200485", "size": 4293, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GeometricTools_conics.jl", "max_stars_repo_name": "AKGitHub2/GEO", "max_stars_repo_head_hexsha": "ad53dfd19e854a230b51d0a6faa83909b3a73bc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-01-13T16:39:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T12:25:40.000Z", "max_issues_repo_path": "src/GeometricTools_conics.jl", "max_issues_repo_name": "AKGitHub2/GEO", "max_issues_repo_head_hexsha": "ad53dfd19e854a230b51d0a6faa83909b3a73bc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-17T16:23:04.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-17T16:32:49.000Z", "max_forks_repo_path": "src/GeometricTools_conics.jl", "max_forks_repo_name": "AKGitHub2/GEO", "max_forks_repo_head_hexsha": "ad53dfd19e854a230b51d0a6faa83909b3a73bc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-06T03:24:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T12:25:40.000Z", "avg_line_length": 30.8848920863, "max_line_length": 104, "alphanum_fraction": 0.5273701374, "num_tokens": 1397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7798272174384078}}
{"text": "function cart_to_cyl(x,y)\n    return [sqrt(x*x + y*y), (atan(y, x) + 2π)%(2π)]\nend\nfunction cyl_to_cart(r,t)\n    return [r*cos(t), r*sin(t)] \nend\nfunction dcart_to_cyl(x,y)\n    r2 = x*x + y*y \n    r = sqrt(r2)\n    return [x/r y/r; -y/r2 x/r2]\nend\nfunction dcyl_to_cart(r,t)\n    ct, st = cos(t), sin(t)\n    return [ct -r*st;st r*ct]    \nend\nfunction step(x, s, n)\n    x_trj = zeros(3, n+1)\n    x_trj[:,1] = x\n    s0, s1, s2 = s[1], s[2], s[3]\n    for i = 2:n+1\n           x_trj[:,i] = next(x_trj[:,i-1],s)    \n    end\n    return x_trj\nend\nfunction next(u, s)\n    x, y, z = u\n    s0, s1, s2 = s\n    r, t = cart_to_cyl(x, y)\n    r1 = s0 + (r - s0)/s1 + cos(t)/2\n    t1 = (2*t + s2/4*sin(4*t)) % (2π)\n    z1 = z/s1 + sin(t)/2\n    x1, y1 = cyl_to_cart(r1,t1)\n    return [x1, y1, z1]\nend\nfunction dstep(u::Array{Float64,1},s::Array{Float64,1})\n    du = zeros(2,2)\n    s0, s1, s2 = s\n    x, y, z = u\n    r, t = cart_to_cyl(x,y)\n    r1 = s0 + (r - s0)/s1 + cos(t)/2\n    t1 = (2*t + s2/4*sin(4*t)) % (2π)\n    z1 = z/s1 + sin(t)/2\n\n    drt1drt = [1/s1 -sin(t)/2;0 2 + s2*cos(4*t)]\n    dz1dt = cos(t)/2 \n    dz1dz = 1/s1\n\n    drtdxy = dcart_to_cyl(x,y)\n    dtdx, dtdy = drtdxy[2,1], drtdxy[2,2]\n    dxy1dxy = dcyl_to_cart(r1,t1)*drt1drt*drtdxy\n    dz1 = [dz1dt*dtdx dz1dt*dtdy dz1dz]\n    \n    du = [dxy1dxy [0;0]]\n    du = [du;dz1]\n    return du\nend\nfunction pert(u::Array{Float64,1}, s::Array{Float64,1},\n              p::Int64)\n    x, y, z = u\n    s0, s1, s2 = s\n    r, t = cart_to_cyl(x,y)     \n    r1 = s0 + (r - s0)/s1 + cos(t)/2\n    t1 = 2*t + s2/4*sin(4*t)\n    z1 = z/s1 + sin(t)/2\n    x1, y1 = cyl_to_cart(r1,t1)\n    dxyz1drtz1 = [dcyl_to_cart(r1,t1) [0;0]]\n    dxyz1drtz1 = [dxyz1drtz1; [0 0 1]] \n\n    if p==1\n        drtz1ds = [1-1/s1; 0; 0]\n    elseif p==2\n        drtz1ds = [-(r - s0)/s1^2; 0; -z/s1^2]\n    elseif p==3\n        drtz1ds = [0; (1/4)*sin(4*t); 0]  \n    else\n        println(\"parameter perturbation is only defined \n                for indices 1 through 3\")\n        return 0\n    end\n    return dxyz1drtz1*drtz1ds\nend\n", "meta": {"hexsha": "50d72ac669071fa4f68aa00adf8fac2db9cc7daf", "size": 2030, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/solenoid.jl", "max_stars_repo_name": "nishaChandramoorthy/linearResponse", "max_stars_repo_head_hexsha": "41f95790019950b5484300ea2c60a6bc9a250958", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/solenoid.jl", "max_issues_repo_name": "nishaChandramoorthy/linearResponse", "max_issues_repo_head_hexsha": "41f95790019950b5484300ea2c60a6bc9a250958", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-23T19:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-27T19:18:12.000Z", "max_forks_repo_path": "examples/solenoid.jl", "max_forks_repo_name": "nishaChandramoorthy/linearResponse", "max_forks_repo_head_hexsha": "41f95790019950b5484300ea2c60a6bc9a250958", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.756097561, "max_line_length": 56, "alphanum_fraction": 0.5083743842, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.8479677545357569, "lm_q1q2_score": 0.7798272121384128}}
{"text": "\"\"\"\n    Gamma\n\n* Parametrization\nparametrized in \\\\alpha and \\\\theta\n\n* Score\n\n* Fisher Information\n\n* `time_varying_params` map.\n\n* Default link\n\"\"\"\nGamma\n\nfunction score!(score_til::Matrix{T}, y::T, ::Type{Gamma}, param::Matrix{T}, t::Int) where T\n    score_til[t, 1] = log(y) - digamma(param[t, 1]) - log(param[t, 2])\n    score_til[t, 2] = y/param[t, 2]^2 - param[t, 1]/param[t, 2]\n    return \nend\n\nfunction fisher_information!(aux::AuxiliaryLinAlg{T}, ::Type{Gamma}, param::Matrix{T}, t::Int) where T\n    aux.fisher[1, 1] = trigamma(param[t, 1])\n    aux.fisher[2, 2] = param[t, 1] / param[t, 2]^2\n    aux.fisher[2, 1] = 1/param[t, 2]\n    aux.fisher[1, 2] = 1/param[t, 2]\n    return\nend\n\nfunction log_likelihood(::Type{Gamma}, y::Vector{T}, param::Matrix{T}, n::Int) where T\n    loglik = 0.0\n    for t in 1:n\n        loglik += (param[t, 1] - 1)*log(y[t]) - y[t]/param[t, 2] - loggamma(param[t, 1]) - param[t, 1]*log(param[t, 2])\n    end\n    return -loglik\nend\n\n# Links\nfunction link!(param_tilde::Matrix{T}, ::Type{Gamma}, param::Matrix{T}, t::Int) where T \n    param_tilde[t, 1] = link(LogLink, param[t, 1], zero(T))\n    param_tilde[t, 2] = link(LogLink, param[t, 2], zero(T))\n    return\nend\nfunction unlink!(param::Matrix{T}, ::Type{Gamma}, param_tilde::Matrix{T}, t::Int) where T \n    param[t, 1] = unlink(LogLink, param_tilde[t, 1], zero(T))\n    param[t, 2] = unlink(LogLink, param_tilde[t, 2], zero(T))\n    return\nend\nfunction jacobian_link!(aux::AuxiliaryLinAlg{T}, ::Type{Gamma}, param::Matrix{T}, t::Int) where T \n    aux.jac[1] = jacobian_link(LogLink, param[t, 1], zero(T))\n    aux.jac[2] = jacobian_link(LogLink, param[t, 2], zero(T))\n    return\nend\n\n# utils \nfunction update_dist(::Type{Gamma}, param::Matrix{T}, t::Int) where T\n    small_threshold!(param, SMALL_NUM, t)\n    return Gamma(param[t, 1], param[t, 2])\nend \n\nfunction params_sdm(d::Gamma)\n    return Distributions.params(d)\nend\n\nfunction num_params(::Type{Gamma})\n    return 2\nend\n", "meta": {"hexsha": "7fdae6fc2b90082ddb2a50fcb9f8510c5261b300", "size": 1957, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distributions/gamma.jl", "max_stars_repo_name": "marinadietze/ScoreDrivenModels.jl", "max_stars_repo_head_hexsha": "4ee85b8d606892535a7b0bf2aec1d976f44d796e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2020-02-05T04:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T18:46:03.000Z", "max_issues_repo_path": "src/distributions/gamma.jl", "max_issues_repo_name": "marinadietze/ScoreDrivenModels.jl", "max_issues_repo_head_hexsha": "4ee85b8d606892535a7b0bf2aec1d976f44d796e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 109, "max_issues_repo_issues_event_min_datetime": "2019-11-26T12:34:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-27T20:16:55.000Z", "max_forks_repo_path": "src/distributions/gamma.jl", "max_forks_repo_name": "marinadietze/ScoreDrivenModels.jl", "max_forks_repo_head_hexsha": "4ee85b8d606892535a7b0bf2aec1d976f44d796e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:11:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-04T20:05:21.000Z", "avg_line_length": 28.3623188406, "max_line_length": 119, "alphanum_fraction": 0.6320899336, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7798272121384127}}
{"text": "\n\n\"\"\"\n    Circle(c,r)\n\nCircle in the complex plane. \\$|c-z|=r\\$.\n\n#### Arguments\n- `c::N`: Center.\n- `r::R`: Radius.\n\"\"\"\nstruct Circle{N <: Number, R <: Real} <: AbstractCircle\n  center::N\n  radius::R\n\n  function Circle{N,R}(c0::N, r0::R)  where {N <: Number, R <: Real}\n    #if r0 < 0\n    #  error(\"Circle can not have negative radius.\")\n    #end\n    new(c0,r0)\n  end\nend\n\nCircle(c0::N, r0::R) where {N <: Number, R <: Real} = Circle{N,R}(c0,r0)\n\ncenter(c::Circle) = c.center\ncenterC(c::Circle) = c.center\ncenterR2(c::Circle) = real(c.center), imag(c.center)\ncenterx(c::Circle) = real(c.center)\ncentery(c::Circle) = imag(c.center)\nradius(c::Circle) = c.radius\nradius2(c::Circle) = c.radius*c.radius\n\nBase.show(io::IO, c::Circle{N,R}) where {N,R} =\nprint(io, \"Circle{$N,$R}: |z - (\", c.center, \")| = \", c.radius)\n\n\n\"\"\"\n    CircleR2(x,y,r)\n\nCircle in the plane \\$\\\\mathbb{R}^2\\$. \\$|(x0,y0)-(x,y)|=r\\$.\n\"\"\"\nstruct CircleR2{R <: Real} <: AbstractCircle\n  centerx::R\n  centery::R\n  radius::R\n\n  function CircleR2{R}(x0::R, y0::R, r0::R)  where {R <: Real}\n    #if r0 < 0\n    #  error(\"Circle can not have negative radius.\")\n    #end\n    new(x0,y0,r0)\n  end\nend\n\nCircleR2(x0::R, y0::R, r0::R) where {R <: Real} = CircleR2{R}(x0,y0,r0)\nCircleR2(x0::Real, y0::Real, r0::Real) = CircleR2(promote(x0,y0,r0)...)\n\ncenter(c::CircleR2) = c.centerx, c.centery\ncenterC(c::CircleR2) = complex(c.centerx, c.centery)\ncenterR2(c::CircleR2) = c.centerx, c.centery\ncenterx(c::CircleR2) = c.centerx\ncentery(c::CircleR2) = c.centery\nradius(c::CircleR2) = c.radius\nradius2(c::CircleR2) = c.radius*c.radius\n\nBase.show(io::IO, c::CircleR2{R}) where {R} =\nprint(io, \"CircleR2{$R}: |(x,y) - (\", c.centerx, \",\", c.centery, \" )| = \", c.radius)\n\n\n\"\"\"\n    Arc(c,p1,p2)\n\nCircular arc the complex plane.\n\n#### Arguments:\n- `c::N`: center.\n- `p1::N`: Initial point.\n- `p2::N`: Final point.\n\"\"\"\nstruct Arc{N} <: AbstractArc\n  center::N\n  p1::N\n  p2::N\n\n  function Arc{N}(c0::N, p10::N, p20::N)  where {N <: Number}\n    #if r0 < 0\n    #  error(\"Circle can not have negative radius.\")\n    #end\n    new(c0,p10,p20)\n  end\nend\n\n\nArc(c0::N, p10::N, p20::N) where {N <: Number} = Arc{N}(c0,p10,p20)\nArc(c0::Number, p10::Number, p20::Number) = Arc(promote(c0,p10,p20)...)\nArc(c0::Number, r::Real, θ1::Real, θ2::Real) =\nArc(c0, r*(cos(θ1)+sin(θ1)*im), r*(cos(θ2)+sin(θ2)*im))\n\ncenter(ca::Arc) = ca.center\ncenterC(ca::Arc) = ca.center\ncenterR2(ca::Arc) = real(ca.center), imag(ca.center)\nradius(ca::Arc) = abs(ca.center - ca.p1)\nradius2(ca::Arc) = abs2(ca.center - ca.p1)\ninitialpoint(ca::Arc) = ca.p1\nfinalpoint(ca::Arc) = ca.p2\ninitialpointC(ca::Arc) = ca.p1\nfinalpointC(ca::Arc) = ca.p2\ninitialpointR2(ca::Arc) = real(ca.p1), imag(ca.p1)\nfinalpointR2(ca::Arc) = real(ca.p2), imag(ca.p2)\n\nBase.show(io::IO, ca::Arc{N}) where {N} =\nprint(io, \"Arc{$N}: center=\", ca.center, \", extremes \", ca.p1, \", \", ca.p2)\n\n\n\"\"\"\n    BiArc(c,p1,p2,p3,p4)\n\nTwo arcs in the same circunference.\n\"\"\"\nstruct BiArc{N <: Number} <: AbstractCircularCurve\n  center::N\n  p1::N\n  p2::N\n  p3::N\n  p4::N\n\n  function BiArc{N}(c0::N, p10::N, p20::N, p30::N, p40::N)  where {N <: Number}\n    new(c0,p10,p20,p30,p40)\n  end\nend\n\nBiArc(c0::N, p10::N, p20::N, p30::N, p40::N) where {N <: Number} = BiArc{N}(c0,p10,p20,p30,p40)\nBiArc(c0::Number, p10::Number, p20::Number, p30::Number, p40::Number) = BiArc(promote(c0,p10,p20,p30,p40)...)\n\ntoarcs(ba::BiArc) = Arc(ba.center,ba.p1,ba.p2), Arc(ba.center,ba.p3,ba.p4)\n\n\n#=\nToDo!\nArcR2\nBiArcR2\n=#\n\n\n\n\"\"\"\nChecks if `z` is inside the circle `c` with \\$|center-z|^2 < radius^2\\$.\n\"\"\"\nisinside(z::Number, c::Circle) = abs2(c.center - z) < (c.radius * c.radius)\n\n\"\"\"\nChecks if `z` is outside the circle `c` with \\$|center-z|^2 > radius^2\\$.\n\"\"\"\nisoutside(z::Number, c::Circle) = abs2(c.center - z) > (c.radius * c.radius)\n\n\n\"\"\"\n    circlepoints(c, [θ0, θ1; numpts]) -> Array{Tuple{Float64,Float64}}\n\nCreate an array of points (`Tuple{Float64,Float64}`) in a given circle\n\n#### Arguments\n- `c::Circle`: A circle.\n- `θ0::Real`: Initial angle.\n- `θ1::Real`: Final angle.\n- `numpts::Integer`: Number of points to create.\n\"\"\"\ncirclepoints(c::AbstractCircle, θ0::Real=0, θ1::Real=2π; numpts::Integer=100) =\n[ (centerx(c) + radius(c)*cos(θ), centery(c) + radius(c)*sin(θ)) for θ ∈ θ0:((θ1 - θ0)/numpts):θ1 ]\n\ncirclepoints(x::Real, y::Real, r::Real, θ0::Real=0, θ1::Real=2π; numpts::Integer=100) =\n[ (x + r*cos(θ), y + r*sin(θ)) for θ ∈ θ0:((θ1 - θ0)/numpts):θ1 ]\n\n\"\"\"\n    circlepoints(c, [θ0, θ1; numpts]) -> Array{Complex{Float64}}\n\nCreate an array of complex number in a given circle.\n\n#### Arguments\n- `c::Circle`: A circle.\n- `θ0::Real`: Initial angle.\n- `θ1::Real`: Final angle.\n- `numpts::Integer`: Number of points to create.\n\"\"\"\ncirclecomplexes(c::AbstractCircle, θ0::Real=0, θ1::Real=2π; numpts::Integer=100) =\n[ centerC(c) + radius(c)*exp(θ*im) for θ ∈ θ0:((θ1 - θ0)/numpts):θ1 ]\n\ncirclecomplexes(z::Number, r::Real, θ0::Real=0, θ1::Real=2π; numpts::Integer=100) =\n[ z + r*cos(θ) + r*sin(θ)*im for θ ∈ θ0:((θ1 - θ0)/numpts):θ1 ]\n", "meta": {"hexsha": "db7672df4d4292256970daddbb3fe7d2ed006846", "size": 4991, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/circles.jl", "max_stars_repo_name": "Colectivo-SDD/SDDGeometry.jl", "max_stars_repo_head_hexsha": "f3fe97b8b9f846ea7955f88877e2c4715984987a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/circles.jl", "max_issues_repo_name": "Colectivo-SDD/SDDGeometry.jl", "max_issues_repo_head_hexsha": "f3fe97b8b9f846ea7955f88877e2c4715984987a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/circles.jl", "max_forks_repo_name": "Colectivo-SDD/SDDGeometry.jl", "max_forks_repo_head_hexsha": "f3fe97b8b9f846ea7955f88877e2c4715984987a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1308900524, "max_line_length": 109, "alphanum_fraction": 0.6106992587, "num_tokens": 1949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642533380189, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7798272104726436}}
{"text": "\"\"\"\nconstructDormandPrince()\n\nConstructs the tableau object for the Dormand-Prince Order 4/5 method.\n\"\"\"\nfunction constructDormandPrince(T::Type = Float64)\n  A = [0 0 0 0 0 0 0\n      1//5 0 0 0 0 0 0\n      3//40 9//40 0 0 0 0 0\n      44//45 -56//15 32//9 0 0 0 0\n      19372//6561 -25360//2187 64448//6561 -212//729 0 0 0\n      9017//3168 -355//33 46732//5247 49//176 -5103//18656 0 0\n      35//384 0 500//1113 125//192 -2187//6784 11//84 0]\n  c = [0;1//5;3//10;4//5;8//9;1;1]\n  α = [35//384;0;500//1113;125//192;-2187//6784;11//84;0]\n  αEEst = [5179//57600;0;7571//16695;393//640;-92097//339200;187//2100;1//40]\n  A = map(T,A)\n  α = map(T,α)\n  αEEst = map(T,αEEst)\n  c = map(T,c)\n  return(ExplicitRKTableau(A,c,α,5,αEEst=αEEst,adaptiveorder=4,fsal=true))\nend\n\n\"\"\"\nODE_DEFAULT_TABLEAU\n\nSets the default tableau for the ODE solver. Currently Dormand-Prince 4/5.\n\"\"\"\nconst ODE_DEFAULT_TABLEAU = constructDormandPrince()\n\n@inline ODE_DEFAULT_NORM(u) = sqrt(sum(abs2,u) / length(u))\n@inline ODE_DEFAULT_NORM(u::Number) = abs(u)\n@inline ODE_DEFAULT_ISOUTOFDOMAIN(t,u) = false\n@inline ODE_DEFAULT_PROG_MESSAGE(dt,t,u) = \"dt=\"*string(dt)*\"\\nt=\"*string(t)*\"\\nmax u=\"*string(maximum(abs.(u)))\n@inline ODE_DEFAULT_UNSTABLE_CHECK(dt,t,u) = any(isnan,u)\n", "meta": {"hexsha": "e98f807caa8e79cb99df5ccbf0bab129592f8202", "size": 1242, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/constants.jl", "max_stars_repo_name": "ranocha/OrdinaryDiffEq.jl", "max_stars_repo_head_hexsha": "48a0f6886fda7da1051105544889e72a6222da60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/constants.jl", "max_issues_repo_name": "ranocha/OrdinaryDiffEq.jl", "max_issues_repo_head_hexsha": "48a0f6886fda7da1051105544889e72a6222da60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/constants.jl", "max_forks_repo_name": "ranocha/OrdinaryDiffEq.jl", "max_forks_repo_head_hexsha": "48a0f6886fda7da1051105544889e72a6222da60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5, "max_line_length": 112, "alphanum_fraction": 0.6594202899, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7797862340062091}}
{"text": "import FractionalCalculus.FracDiffAlg\n\n\"\"\"\nRiesz sense fractional derivative\n\"\"\"\nabstract type Riesz <: FracDiffAlg end\n\n\"\"\"\n# Riesz sense symmetric fractional derivative algorithm.\n\n    fracdiff(f, α, end_point, h, Riesz_Symmetric())\n\nCompute fractional derivative of Riesz sense using Triangular Strip Matrix algorithm.\n\n### Example\n\n```julia-repl\njulia> fracdiff(x->x, 0.5, 1, 0.01, Riesz_Symmetric())\n```\n\"\"\"\nstruct Riesz_Symmetric <: Riesz end\n\n\n################################################################\n###                    Type defination done                  ###\n################################################################\n\n\nfunction fracdiff(f, α, end_point, h, ::Riesz_Symmetric)\n    N=Int(floor(end_point/h))\n\n    mat = RieszMatrix(α, N+1, h)\n    return mat*f.(collect(0:h:end_point))\nend\nfunction RieszMatrix(α, N, h)\n    caputo = B(N+1, α)\n    caputo = caputo[2:(N+1), 1:N]\n    result = 1/2*(caputo+caputo')\n    result = h^(-α)*result\n\n    return result\nend\n\nfunction B(N, p)\n    result=zeros(N, N)\n    temp=omega(N, p)\n\n    @inbounds @simd for i ∈ 1:N\n        @views result[i, 1:i]=reverse(temp[1:i])\n    end\n\n    return result\nend\n\nfunction omega(n, p)\n    omega = zeros(n+1)\n\n    omega[1]=1\n    @fastmath @inbounds @simd for i ∈ 1:n\n        omega[i+1]=(1-(p+1)/i)*omega[i]\n    end\n    \n    return omega\nend", "meta": {"hexsha": "77d3ba7b8253f3a7ca135c45d2c59d1a4296c06c", "size": 1337, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Derivative/Riesz.jl", "max_stars_repo_name": "mohammed198246/FractionalCalculus.jl", "max_stars_repo_head_hexsha": "d9d4d21fe4710823c0fb045d61b09306030a9e47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-09-25T03:46:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T11:42:37.000Z", "max_issues_repo_path": "src/Derivative/Riesz.jl", "max_issues_repo_name": "ErikQQY/FractionalCalculus.jl", "max_issues_repo_head_hexsha": "f84306de4c3b44f66f21c88629b5a690179663c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-13T17:15:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T17:15:14.000Z", "max_forks_repo_path": "src/Derivative/Riesz.jl", "max_forks_repo_name": "ErikQQY/FractionalCalculus.jl", "max_forks_repo_head_hexsha": "f84306de4c3b44f66f21c88629b5a690179663c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.890625, "max_line_length": 85, "alphanum_fraction": 0.5632011967, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7797771384389173}}
{"text": "export arithmetic_mean, geometric_mean, harmonic_mean, generalized_means\nexport pref_attach3, common3, jaccard3, adamic_adar3\nexport common_nbr_set\n\n\"\"\"\narithmetic_mean\n---------------\n\nReturns the arithmetic mean of the weights of the edges of a list of triangles.\n\narithmetic_mean(triangles::Vector{NTuple{3,Int64}}, B::SpIntMat)\n\nInput parameters:\n- triangles::Vector{NTuple{3,Int64}}: The vector of triangles upon which to compute scores.\n- B::SpIntMat: Projected graph as a Sparse integer matrix, where B[i, j] is the number of times that i and j co-appear in a simplex.\n\"\"\"\nfunction arithmetic_mean(triangles::Vector{NTuple{3,Int64}}, B::SpIntMat)\n    scores = zeros(Float64, length(triangles))\n    Threads.@threads for ind = 1:length(triangles)\n        i, j, k = triangles[ind]\n        scores[ind] = (B[i, j] + B[j, k] + B[i, k]) / 3\n    end\n    return scores\nend\n\n\"\"\"\ngeometric_mean\n---------------\n\nReturns the geometric mean of the weights of the edges of a list of triangles.\n\ngeometric_mean(triangles::Vector{NTuple{3,Int64}}, B::SpIntMat)\n\nInput parameters:\n- triangles::Vector{NTuple{3,Int64}}: The vector of triangles upon which to compute scores.\n- B::SpIntMat: Projected graph as a Sparse integer matrix, where B[i, j] is the number of times that i and j co-appear in a simplex.\n\"\"\"\nfunction geometric_mean(triangles::Vector{NTuple{3,Int64}}, B::SpIntMat)\n    scores = zeros(Float64, length(triangles))\n    Threads.@threads for ind = 1:length(triangles)\n        i, j, k = triangles[ind]\n        scores[ind] = (B[i, j] * B[j, k] * B[i, k])^(1 / 3)\n    end\n    return scores    \nend\n\n\"\"\"\nharmonic_mean\n---------------\n\nReturns the harmonic mean of the weights of the edges of a list of triangles.\n\nharmonic_mean(triangles::Vector{NTuple{3,Int64}}, B::SpIntMat)\n\nInput parameters:\n- triangles::Vector{NTuple{3,Int64}}: The vector of triangles upon which to compute scores.\n- B::SpIntMat: Projected graph as a Sparse integer matrix, where B[i, j] is the number of times that i and j co-appear in a simplex.\n\"\"\"\nfunction harmonic_mean(triangles::Vector{NTuple{3,Int64}}, B::SpIntMat)\n    scores = zeros(Float64, length(triangles))\n    Threads.@threads for ind = 1:length(triangles)\n        i, j, k = triangles[ind]\n        scores[ind] = 3.0 / (1.0 / B[i, j] + 1.0 / B[j, k] + 1.0 / B[i, k])\n    end\n    return scores\nend\n\n\"\"\"\ngeneralized_means\n----------------\n\nComputes the generalized p-means of the weights of the edges of a list of triangles.\nThe generalized mean of 3 values is\n\n```math\nM_p(x, y, z) = ((x^p + y^p + z^p) / 3)^{1/p}\n```\n\ngeneralized_means(triangles::Vector{NTuple{3,Int64}}, B::SpIntMat, ps::Float64=[-Inf; collect(-4:0.25:4); Inf])\n\nInput parameters:\n- triangles::Vector{NTuple{3,Int64}}: The vector of triangles upon which to compute scores.\n- B::SpIntMat: Projected graph as a Sparse integer matrix, where B[i, j] is the number of times that i and j co-appear in a simplex.\n- ps::Vector{Float64}=[-Inf; collect(-4:0.25:4); Inf]: the values of p for which to compute the means\n\nReturns a matrix of size length(triangles) x length(ps) of the scores for the various generalized means.\n\"\"\"\nfunction generalized_means(triangles::Vector{NTuple{3,Int64}}, B::SpIntMat, ps::Vector{Float64}=[-Inf; collect(-4:0.25:4); Inf])\n    scores = zeros(Float64, length(triangles), length(ps))\n    Threads.@threads for ind = 1:length(triangles)\n        i, j, k = triangles[ind]\n        Bij, Bjk, Bik = B[i, j], B[j, k], B[i, k]\n        for (r, p) in enumerate(ps)\n            if     p == -Inf; scores[ind, r] = min(Bij, Bjk, Bik)\n            elseif p == Inf;  scores[ind, r] = max(Bij, Bjk, Bik)\n            elseif p == 0;    scores[ind, r] = (Bij * Bjk * Bik)^(1.0 / 3)\n            else              scores[ind, r] = ((Bij^p + Bjk^p + Bik^p) / 3)^(1.0 / p)\n            end\n        end\n    end\n    return scores\nend\n\n\"\"\"\npref_attach3\n------------\n\nReturns the preferential attachment score for a degree vector\n\npref_attach3(triangles::Vector{NTuple{3,Int64}}, degrees::Vector{Int64})\n\nThe score of triangle (i, j, k) is degrees[i] * degrees[j] * degrees[k]\n\nInput parameters:\n- triangles::Vector{NTuple{3,Int64}}: The vector of triangles upon which to compute scores.\n- degrees::Vector{Int64}: the degree vector\n\"\"\"\nfunction pref_attach3(triangles::Vector{NTuple{3,Int64}}, degrees::Vector{Int64})\n    scores = zeros(Float64, length(triangles))\n    Threads.@threads for ind = 1:length(triangles)\n        i, j, k = triangles[ind]\n        scores[ind] = 1.0 * degrees[i] * degrees[j] * degrees[k]\n    end\n    return scores    \nend\n\n\"\"\" Return common neighbors of two nodes u and v. \"\"\"\nfunction common_nbr_set(common_nbrs::NbrSetMap, u::Int64, v::Int64)\n    min_node, max_node = min(u, v), max(u, v)\n    if !haskey(common_nbrs, (min_node, max_node))\n        return Set{Int64}()\n    end\n    return common_nbrs[(min_node, max_node)]\nend\n\n\"\"\"\ncommon3\n------------\n\nReturns the number of common 4th neighbors of a list of triangles.\n\ncommon3(triangles::Vector{NTuple{3,Int64}}, common_nbrs::NbrSetMap)\n\nInput parameters:\n- triangles::Vector{NTuple{3,Int64}}: The vector of triangles upon which to compute scores.\n- common_nbrs::NbrSetMap: the common neighbors map attained from common_neighbors_map()\n\"\"\"\nfunction common3(triangles::Vector{NTuple{3,Int64}}, common_nbrs::NbrSetMap)\n    scores = zeros(Float64, length(triangles))\n    Threads.@threads for ind = 1:length(triangles)\n        i, j, k = triangles[ind]\n        common_ij = common_nbr_set(common_nbrs, i, j)\n        common_ik = common_nbr_set(common_nbrs, i, k)\n        common_jk = common_nbr_set(common_nbrs, j, k)\n        common_ijk = intersect(common_ij, common_ik, common_jk)\n        scores[ind] = length(common_ijk)\n    end\n    return scores\nend\n\n\"\"\"\njaccard3\n------------\n\nReturns the 3-way Jaccard index of the neighbor lists of nodes in triangle.\n\njaccard3(triangles::Vector{NTuple{3,Int64}}, common_nbrs::NbrSetMap, degrees::Vector{Int64})\n\nInput parameters:\n- triangles::Vector{NTuple{3,Int64}}: The vector of triangles upon which to compute scores.\n- common_nbrs::NbrSetMap: the common neighbors map attained from common_neighbors_map()\n- degrees::Vector{Int64}: degree of each node in the projected graph\n\"\"\"\nfunction jaccard3(triangles::Vector{NTuple{3,Int64}}, common_nbrs::NbrSetMap,\n                  degrees::Vector{Int64})\n    scores = zeros(Float64, length(triangles))\n    Threads.@threads for ind = 1:length(triangles)\n        i, j, k = triangles[ind]\n        common_ij = common_nbr_set(common_nbrs, i, j)\n        common_ik = common_nbr_set(common_nbrs, i, k)\n        common_jk = common_nbr_set(common_nbrs, j, k)\n        common_ijk = intersect(common_ij, common_ik, common_jk)\n        nij, nik, njk = length(common_ij), length(common_ik), length(common_jk)\n        nijk = length(common_ijk)\n        di, dj, dk = degrees[[i, j, k]]\n        scores[ind] = nijk / (di + dj + dk - nij - nik - njk + nijk)\n    end\n    return scores\nend\n\n\"\"\"\nadamic_adar3\n------------\n\nReturns the 3-way Adamic-Adar score for a list of triangles.\n\nadamic_adar3(triangles::Vector{NTuple{3,Int64}}, common_nbrs::NbrSetMap, degrees::Vector{Int64})\n\nInput parameters:\n- triangles::Vector{NTuple{3,Int64}}: The vector of triangles upon which to compute scores.\n- common_nbrs::NbrSetMap: the common neighbors map attained from common_neighbors_map()\n- degrees::Vector{Int64}: degree of each node in the projected graph\n\"\"\"\nfunction adamic_adar3(triangles::Vector{NTuple{3,Int64}}, common_nbrs::NbrSetMap,\n                      degrees::Vector{Int64})\n    scores = zeros(Float64, length(triangles))\n    Threads.@threads for ind = 1:length(triangles)\n        i, j, k = triangles[ind]\n        common_ij = common_nbr_set(common_nbrs, i, j)\n        common_ik = common_nbr_set(common_nbrs, i, k)\n        common_jk = common_nbr_set(common_nbrs, j, k)\n        common_ijk = intersect(common_ij, common_ik, common_jk)\n        scores[ind] = sum([1.0 / log(degrees[z]) for z in common_ijk])\n    end\n    return scores\nend\n", "meta": {"hexsha": "6d16b8959a5f810d6cae944710af93101878ccb9", "size": 7968, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/local_scores.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/ScHoLP.jl-c786d6c3-4fbc-59fc-968c-e848efb65d2d", "max_stars_repo_head_hexsha": "c69088aab50376c539937a5dc1e647ffba7ae41b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-07T13:04:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-03T06:09:38.000Z", "max_issues_repo_path": "src/local_scores.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/ScHoLP.jl-c786d6c3-4fbc-59fc-968c-e848efb65d2d", "max_issues_repo_head_hexsha": "c69088aab50376c539937a5dc1e647ffba7ae41b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/local_scores.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/ScHoLP.jl-c786d6c3-4fbc-59fc-968c-e848efb65d2d", "max_forks_repo_head_hexsha": "c69088aab50376c539937a5dc1e647ffba7ae41b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:21:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-26T18:21:34.000Z", "avg_line_length": 36.7188940092, "max_line_length": 132, "alphanum_fraction": 0.6752008032, "num_tokens": 2322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7797771359198503}}
{"text": "abstract type AbstractPoint end\n\nfunction iselliptic(𝑥::Number,𝑦::Number,𝑎::Number,𝑏::Number)\n    𝑦^2 == 𝑥^3 + 𝑎*𝑥 + 𝑏\nend\n\nPOINTTYPES = Union{Integer,PrimeField}\n\n\"\"\"\nRepresents a point with coordinates (𝑥,𝑦) on an elliptic curve where 𝑦² = 𝑥³ + 𝑎𝑥 + 𝑏\nOptional parameter 𝑝 represents finite field 𝐹ₚ and will convert all other parameter to PrimeField\nPoint(∞,∞,𝑎,𝑏) represents point at infinity\nReturns an error if elliptic curve equation isn't satisfied\n\"\"\"\nstruct Point{T<:Number,S<:Number} <: AbstractPoint\n    𝑥::T\n    𝑦::T\n    𝑎::S\n    𝑏::S\n    Point{T,S}(𝑥,𝑦,𝑎,𝑏) where {T<:Number,S<:Number} = new(𝑥,𝑦,𝑎,𝑏)\nend\n\nPoint(𝑥::Infinity,𝑦::Infinity,𝑎::T,𝑏::T) where {T<:POINTTYPES} = Point{Infinity,T}(𝑥,𝑦,𝑎,𝑏)\nPoint(𝑥::T,𝑦::T,𝑎::T,𝑏::T) where {T<:POINTTYPES} = !iselliptic(𝑥,𝑦,𝑎,𝑏) ? throw(DomainError(\"Point is not on curve\")) : Point{T,T}(𝑥,𝑦,𝑎,𝑏)\nPoint(𝑥::Infinity,𝑦::Infinity,𝑎::T,𝑏::T,𝑝::T) where {T<:Integer} = Point(𝑥,𝑦,FieldElement(𝑎,𝑝),FieldElement(𝑏,𝑝))\nPoint(𝑥::T,𝑦::T,𝑎::T,𝑏::T,𝑝::T) where {T<:Integer} = Point(FieldElement(𝑥,𝑝),FieldElement(𝑦,𝑝),FieldElement(𝑎,𝑝),FieldElement(𝑏,𝑝))\n\n\"Formats AbstractPoint as (𝑥, 𝑦) on 𝑦² = 𝑥³ + 𝑎𝑥 + 𝑏 (: 𝐹ₚ)\"\nfunction show(io::IO, z::AbstractPoint)\n    if typeof(z.𝑥) <: PrimeField\n        x, y = z.𝑥.𝑛, z.𝑦.𝑛\n    else\n        x, y = z.𝑥, z.𝑦\n    end\n\n    if typeof(z.𝑎) <: PrimeField\n        a, b = z.𝑎.𝑛, z.𝑏.𝑛\n        field = string(\" : 𝐹\", z.𝑎.𝑝)\n    else\n        a, b = z.𝑎, z.𝑏\n        field = \"\"\n    end\n    print(io, \"(\", x, \", \", y, \") on 𝑦² = 𝑥³ + \", a, \"𝑥 + \", b, field)\nend\n\n\"\"\"\nReturns the point resulting from the intersection of the curve and the\nstraight line defined by the points P and Q\n\"\"\"\nfunction +(𝑃::AbstractPoint,𝑄::AbstractPoint)\n    T = typeof(𝑃)\n    S = typeof(𝑃.𝑎)\n    if 𝑃.𝑎 != 𝑄.𝑎 || 𝑃.𝑏 != 𝑄.𝑏\n        throw(DomainError(\"Points are not on the same curve\"))\n\n    # Case 0\n    elseif 𝑃.𝑥 == ∞\n        return 𝑄\n    elseif 𝑄.𝑥 == ∞\n        return 𝑃\n    elseif 𝑃.𝑥 == 𝑄.𝑥 && 𝑃.𝑦 != 𝑄.𝑦\n        # something more elegant should exist to return correct point type\n        if T <: Point\n            return Point{Infinity,S}(∞, ∞, 𝑃.𝑎, 𝑃.𝑏)\n        elseif T <: S256Point\n            return S256Point{Infinity}(∞, ∞, 𝑃.𝑎, 𝑃.𝑏)\n        end\n\n    # Case 1\n    elseif 𝑃.𝑥 != 𝑄.𝑥\n        λ = (𝑄.𝑦 - 𝑃.𝑦) ÷ (𝑄.𝑥 - 𝑃.𝑥)\n        𝑥 = λ^2 - 𝑃.𝑥 - 𝑄.𝑥\n    # Case 2\n    else\n        λ = (3 * 𝑃.𝑥^2 + 𝑃.𝑎) ÷ (2 * 𝑃.𝑦)\n        𝑥 = λ^2 - 2 * 𝑃.𝑥\n    end\n    𝑦 = λ * (𝑃.𝑥 - 𝑥) - 𝑃.𝑦\n    return T(S(𝑥), S(𝑦), 𝑃.𝑎, 𝑃.𝑏)\nend\n\n\"Scalar multiplication of a Point\"\nfunction *(λ::Integer,𝑃::Point)\n    𝑅 = Point(∞, ∞, 𝑃.𝑎, 𝑃.𝑏)\n    while λ > 0\n        𝑅 += 𝑃\n        λ -= 1\n    end\n    return 𝑅\nend\n", "meta": {"hexsha": "7ba268f8d61c4115915d73851d34b5d65d6142f3", "size": 2647, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/point.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ECC.jl-a99b485a-c5c8-540e-ab00-7a7265134077", "max_stars_repo_head_hexsha": "2ea9cdfea2f773317c432e5eb2771f2c4990f6b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/point.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ECC.jl-a99b485a-c5c8-540e-ab00-7a7265134077", "max_issues_repo_head_hexsha": "2ea9cdfea2f773317c432e5eb2771f2c4990f6b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-11-30T17:15:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T17:22:14.000Z", "max_forks_repo_path": "src/point.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ECC.jl-a99b485a-c5c8-540e-ab00-7a7265134077", "max_forks_repo_head_hexsha": "2ea9cdfea2f773317c432e5eb2771f2c4990f6b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-07-11T18:59:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:52:38.000Z", "avg_line_length": 29.0879120879, "max_line_length": 139, "alphanum_fraction": 0.5613902531, "num_tokens": 1388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992932829917, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7797708263609867}}
{"text": "function algebry(rel::Parallelism, coords)\n    A = coords[rel.l.l]\n    B = coords[rel.l.r]\n    C = coords[rel.r.l]\n    D = coords[rel.r.r]\n    return ((B.x - A.x)*(D.y - C.y) - (B.y - A.y)*(D.x - C.x),)\nend\n\nfunction algebry(rel::Perpendicularity, coords)\n    A = coords[rel.l.l]\n    B = coords[rel.l.r]\n    C = coords[rel.r.l]\n    D = coords[rel.r.r]\n    return ((B.x - A.x)*(D.x - C.x) + (B.y - A.y)*(D.y - C.y),)\nend\n\nfunction algebry(rel::Congruence{Segment}, coords)\n    A = coords[rel.l.l]\n    B = coords[rel.l.r]\n    C = coords[rel.r.l]\n    D = coords[rel.r.r]\n    return ((B.x-A.x)^2 + (B.y-A.y)^2 - (D.x-C.x)^2 - (D.y-C.y)^2,)\nend\n\nfunction algebry(rel::Parallelogram, coords)\n    A = coords[rel.A]\n    B = coords[rel.B]\n    C = coords[rel.C]\n    D = coords[rel.D]\n    return (B.x + D.x - A.x - C.x, B.y + D.y - A.y - C.y)\nend\n\nfunction algebry(rel::Midpoint, coords)\n    M = coords[rel.M]\n    A = coords[rel.seg.l]\n    B = coords[rel.seg.r]\n    return (2*M.x-A.x-B.x, 2*M.y-A.y-B.y)\nend\n\nfunction algebry(rel::Appartenence{Segment}, coords)\n    P = coords[rel.l]\n    A = coords[rel.r.l]\n    B = coords[rel.r.r]\n    return ((B.x - A.x)*(P.y - A.y) - (B.y - A.y)*(P.x - A.x),)\nend\n\nfunction algebry(rel::Intersection{Segment, Segment}, coords)\n    return (algebry(Appartenence(rel.P, rel.l), coords)[1], algebry(Appartenence(rel.P, rel.r), coords)[1])\nend\n\nfunction algebry(rel::Projection, coords)\n    return (algebry(Appartenence(rel.H, rel.seg), coords)[1], algebry(Perpendicularity(Segment(rel.P, rel.H), rel.seg), coords)[1])\nend\n\nfunction algebry(rel::Appartenence{Circle}, coords)\n    OP = Segment(rel.r.O, rel.l)\n    OA = Segment(rel.r.O, rel.r.A)\n    return algebry(Congruence(OA, OP), coords)\nend\n\nfunction algebry(rel::CircleThreePoints, coords)\n    OA = Segment(rel.O, rel.A)\n    OB = Segment(rel.O, rel.B)\n    OC = Segment(rel.O, rel.C)\n    return (algebry(Congruence(OA, OB), coords)[1], algebry(Congruence(OA, OC), coords)[1])\nend\n", "meta": {"hexsha": "ced5bbd0a7c5c38c81617bd10e3b9f2d6039e0dd", "size": 1954, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rittwu/algebry.jl", "max_stars_repo_name": "lucaferranti/GeometricTheoremProver.jl", "max_stars_repo_head_hexsha": "970ed8fffe5011b22a757277cc8ac529efe50850", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2022-01-16T19:09:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:15:30.000Z", "max_issues_repo_path": "src/rittwu/algebry.jl", "max_issues_repo_name": "lucaferranti/GeometricTheoremProver.jl", "max_issues_repo_head_hexsha": "970ed8fffe5011b22a757277cc8ac529efe50850", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-01-17T09:00:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T19:13:36.000Z", "max_forks_repo_path": "src/rittwu/algebry.jl", "max_forks_repo_name": "lucaferranti/GeometricTheoremProver.jl", "max_forks_repo_head_hexsha": "970ed8fffe5011b22a757277cc8ac529efe50850", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1641791045, "max_line_length": 131, "alphanum_fraction": 0.599283521, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075711974104, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.779767896529662}}
{"text": "\nusing DifferentialEquations\nusing Plots\n\n\nfunction sir_ode!(du,u,p,t)\n    (S,I,R) = u\n    (β,c,γ) = p\n    N = S+I+R\n    @inbounds begin\n        du[1] = -β*c*I/N*S\n        du[2] = β*c*I/N*S - γ*I\n        du[3] = γ*I\n    end\n    nothing\nend;\n\n\nδt = 0.1\ntmax = 80.0\ntspan = (0.0,tmax)\nt = 0.0:δt:tmax;\n\n\nu0 = [990.0,10.0,0.0]; # S,I.R\n\n\np = [0.05,10.0,0.25]; # β,c,γ\n\n\nlockdown_times = [10.0, 20.0]\ncondition(u,t,integrator) = t ∈ lockdown_times\nfunction affect!(integrator)\n    if integrator.t < lockdown_times[2]\n        integrator.p[1] = 0.01\n    else\n        integrator.p[1] = 0.05\n    end\nend\ncb = PresetTimeCallback(lockdown_times, affect!);\n\n\nprob_ode = ODEProblem(sir_ode!,u0,tspan,p)\n\n\nsol_ode = solve(prob_ode, callback = cb);\n\n\nplot(sol_ode, label = [\"S\" \"I\" \"R\"], title = \"Lockdown in a SIR model\")\nvline!(lockdown_times, c = :red, w = 2, label = \"\")\n\n", "meta": {"hexsha": "4bc81e4c96d64edb0e0e4cae78ee1c4098df2e1f", "size": 862, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_lockdown/ode_lockdown.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 126, "max_stars_repo_stars_event_min_datetime": "2020-04-29T08:41:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:42:53.000Z", "max_issues_repo_path": "script/ode_lockdown/ode_lockdown.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2020-04-29T11:44:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:45:15.000Z", "max_forks_repo_path": "script/ode_lockdown/ode_lockdown.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2020-04-29T08:01:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T16:55:08.000Z", "avg_line_length": 16.5769230769, "max_line_length": 71, "alphanum_fraction": 0.5788863109, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075701109193, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7797678912448234}}
{"text": "# # [Basic Epidemiology Models](@id epidemiology_example)\n#\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/examples/covid/epidemiology.ipynb)\n\nusing AlgebraicPetri\nusing AlgebraicPetri.Epidemiology\n\nusing LabelledArrays\nusing OrdinaryDiffEq\nusing Plots\n\nusing Catlab\nusing Catlab.Graphics\nusing Catlab.WiringDiagrams\nusing Catlab.CategoricalAlgebra\nusing Catlab.Programs.RelationalPrograms\n\ndisplay_uwd(ex) = to_graphviz(ex, box_labels=:name, junction_labels=:variable, edge_attrs=Dict(:len=>\".75\"));\n\n# #### SIR Model:\n\n# define model\nsir = @relation (s,i,r) begin\n    infection(s,i)\n    recovery(i,r)\nend\ndisplay_uwd(sir)\n#-\np_sir = apex(oapply_epi(sir))\nGraph(p_sir)\n\n# define initial states and transition rates, then\n# create, solve, and visualize ODE problem\n\nu0 = LVector(S=10, I=1, R=0);\np = LVector(inf=0.4, rec=0.4);\n\n# The C-Set representation has direct support for generating a DiffEq vector field\n\nprob = ODEProblem(vectorfield(p_sir),u0,(0.0,7.5),p);\nsol = solve(prob,Tsit5())\n\nplot(sol)\n\n# #### SEIR Model:\n\n# define model\nseir = @relation (s,e,i,r) begin\n    exposure(s,i,e)\n    illness(e,i)\n    recovery(i,r)\nend\ndisplay_uwd(seir)\n#-\np_seir = apex(oapply_epi(seir))\nGraph(p_seir)\n\n# define initial states and transition rates, then\n# create, solve, and visualize ODE problem\n\nu0 = LVector(S=10, E=1, I=0, R=0);\np = LVector(exp=.9, ill=.2, rec=.5);\n\nprob = ODEProblem(vectorfield(p_seir),u0,(0.0,15.0),p);\nsol = solve(prob,Tsit5())\n\nplot(sol)\n\n# #### SEIRD Model:\n\n# define model\nseird = @relation (s,e,i,r,d) begin\n    exposure(s,i,e)\n    illness(e,i)\n    recovery(i,r)\n    death(i,d)\nend\ndisplay_uwd(seird)\n#-\np_seird = apex(oapply_epi(seird))\nGraph(p_seird)\n\n# define initial states and transition rates, then\n# create, solve, and visualize ODE problem\n\nu0 = LVector(S=10, E=1, I=0, R=0, D=0);\np = LVector(exp=0.9, ill=0.2, rec=0.5, death=0.1);\n\nprob = ODEProblem(vectorfield(p_seird),u0,(0.0,15.0),p);\nsol = solve(prob,Tsit5())\n\nplot(sol)", "meta": {"hexsha": "00e398219b181e5698b9223472d902d640d62662", "size": 2002, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/covid/epidemiology.jl", "max_stars_repo_name": "AlgebraicJulia/AlgebraicPetri", "max_stars_repo_head_hexsha": "43318f0eec62c93aa29a7c07f9534030cad98a4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 44, "max_stars_repo_stars_event_min_datetime": "2020-07-03T20:45:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T19:33:22.000Z", "max_issues_repo_path": "examples/covid/epidemiology.jl", "max_issues_repo_name": "AlgebraicJulia/AlgebraicPetri", "max_issues_repo_head_hexsha": "43318f0eec62c93aa29a7c07f9534030cad98a4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2020-07-01T02:02:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-14T18:58:49.000Z", "max_forks_repo_path": "examples/covid/epidemiology.jl", "max_forks_repo_name": "AlgebraicJulia/AlgebraicPetri", "max_forks_repo_head_hexsha": "43318f0eec62c93aa29a7c07f9534030cad98a4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-07-16T19:14:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T17:37:26.000Z", "avg_line_length": 21.7608695652, "max_line_length": 124, "alphanum_fraction": 0.7052947053, "num_tokens": 657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661944, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7797152607320117}}
{"text": "using Plots, Measures; pyplot()\n\npDiscrete = [0.25, 0.25, 0.5]\nxGridD = 0:2\n\npContinuous(x) = 3/4*(1 - x^2)\nxGridC = -1:0.01:1\n\npContinuous2(x) = x < 0 ? x+1 : 1-x\n\np1 = plot(xGridD, line=:stem, pDiscrete, marker=:circle, c=:blue, ms=6, msw=0)\np2 = plot(xGridC, pContinuous.(xGridC), c=:blue)\np3 = plot(xGridC, pContinuous2.(xGridC), c=:blue)\n\nplot(p1, p2, p3, layout=(1,3), legend=false, ylims=(0,1.1), xlabel=\"x\",\n\tylabel=[\"Probability\" \"Density\" \"Density\"], size=(1200, 400), margin=5mm)\n", "meta": {"hexsha": "65802cc6c2c2a36c791a776b87da83052f550a68", "size": 491, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/discreteContinuous.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "3_chapter/discreteContinuous.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "3_chapter/discreteContinuous.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 28.8823529412, "max_line_length": 78, "alphanum_fraction": 0.6374745418, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.77971525824606}}
{"text": "using Turing, Random, MCMCChains\nusing CSV, DataFrames, StatsBase\nusing ParetoSmooth\nusing StatisticalRethinking\n\n#Random.seed!(129111)\n\ndf = CSV.read(sr_datadir(\"WaffleDivorce.csv\"), DataFrame)\ndf.D = zscore(df.Divorce)\ndf.M = zscore(df.Marriage)\ndf.A = zscore(df.MedianAgeMarriage)\ndata = (D=df.D, A=df.A)\n\nfunction lin(a, b, c, x...)\n    result = @. a + b * c\n    for i in 1:2:length(x)\n        @. result += x[i] * x[i+1]\n    end\n    return result\nend\n\n\n@model function m5_1t(A, D)\n    a ~ Normal(0, 0.2)\n    bA ~ Normal(0, 0.5)\n    σ ~ Exponential(1)\n    for i in eachindex(D)\n        μ = lin(a, A[i], bA)\n        D[i] ~ Normal(μ, σ)\n    end\nend\n\nchn5_1t = sample(m5_1t(df.A, df.D), NUTS(1000, .9), MCMCThreads(), 1000, 4)\n\n@model function m5_2t(M, D)\n    a ~ Normal(0, 0.2)\n    bM ~ Normal(0, 0.5)\n    σ ~ Exponential(1)\n    for i in eachindex(D)\n        μ = lin(a, M[i], bM)\n        D[i] ~ Normal(μ, σ)\n    end\nend\n\nchn5_2t = sample(m5_2t(df.M, df.D), NUTS(1000, .9), MCMCThreads(), 1000, 4)\n\n@model function m5_3t(A, M, D)\n    a ~ Normal(0, 0.2)\n    bA ~ Normal(0, 0.5)\n    bM ~ Normal(0, 0.5)\n    σ ~ Exponential(1)\n    for i in eachindex(D)\n        μ = a + M[i] * bM + A[i] * bA\n        D[i] ~ Normal(μ, σ)\n    end\nend\n\nchn5_3t = sample(m5_3t(df.A, df.M, df.D), NUTS(1000, .9), MCMCThreads(), 1000, 4)\n\npw_lls5_1t = pointwise_log_likelihoods(m5_1t(df.A, df.D), chn5_1t)\npw_lls5_2t = pointwise_log_likelihoods(m5_2t(df.M, df.D), chn5_2t)\npw_lls5_3t = pointwise_log_likelihoods(m5_3t(df.A, df.M, df.D), chn5_3t)\n\nloo_comparison = ParetoSmooth.loo_compare([pw_lls5_1t, pw_lls5_2t, pw_lls5_3t];\n    model_names=[:m5_1t, :m5_2t, :m5_3t])\n\nfor (i, psis) in enumerate(loo_comparison.psis)\n    psis |> display\n    pk_plot(psis.pointwise(:pareto_k))\n    savefig(joinpath(@__DIR__, \"m5.$(i)t.png\"))\nend\nprintln()\nParticles(chn5_1t[:,[:a, :bA, :σ],:]) |> display\nParticles(chn5_2t[:,[:a, :bM, :σ],:]) |> display\nParticles(chn5_3t[:,[:a, :bA, :bM, :σ],:]) |> display\nloo_comparison |> display\n\n", "meta": {"hexsha": "9b8398d7818f327095e4720a13a69a0763bc8812", "size": 1991, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "research/loo_compare/waffle_divorce_turing.jl", "max_stars_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_stars_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2020-10-01T23:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T11:48:45.000Z", "max_issues_repo_path": "research/loo_compare/waffle_divorce_turing.jl", "max_issues_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_issues_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-11-24T21:59:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T12:34:49.000Z", "max_forks_repo_path": "research/loo_compare/waffle_divorce_turing.jl", "max_forks_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_forks_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-11-30T18:25:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T06:59:27.000Z", "avg_line_length": 25.5256410256, "max_line_length": 81, "alphanum_fraction": 0.614766449, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7796808198233721}}
{"text": "export ortho_latin, check_ortho\n\n\"\"\"\n`A,B = ortho_latin(n)` returns a pair of orthogonal `n`-by-`n`\nLatin squares.\n\n`A,B = ortho_latin(n,true)` returns a pair of orthogonal Latin squares\nthat are transposes of each other.\n\n`A,B = ortho_latin(n,r,s)` builds the Latin squares `latin(n,r)`\nand `latin(n,s)` and, if they are orthogonal, returns them as the\nanswer. (Otherwise, throws an error.) See: `find_ortho_parameters`.\n\"\"\"\nfunction ortho_latin(n::Int, self::Bool=false)\n    if !self\n        try\n            r,s = find_ortho_parameters(n)\n            return ortho_latin(n,r,s)\n        catch\n        end\n    end\n    println(\"No quick solution. Using integer programming.\")\n\n    return ortho_latin_IP(n,self)\nend\n\n\nfunction ortho_latin_IP(n::Int,self::Bool=false)\n    MOD = Model(get_solver())\n    # Z[i,j,k,l] is an indicator that there is a k in A[i,j] and\n    # an l in B[i,j]\n    @variable(MOD,Z[1:n,1:n,1:n,1:n], Bin)\n\n    # one entry per cell constraint\n    for i=1:n\n        for j=1:n\n            @constraint(MOD, sum(Z[i,j,k,l] for k=1:n for l=1:n) == 1)\n        end\n    end\n\n    # Top row 11 22 33 ... nn\n    if !self\n        for i=1:n\n            @constraint(MOD, Z[1,i,i,i]==1)  # A[1,i] = B[1,i] = i\n        end\n    end\n\n    # orthogonality constraint\n    for k=1:n\n        for l=1:n\n            @constraint(MOD, sum(Z[i,j,k,l] for i=1:n for j=1:n) == 1)\n        end\n    end\n\n    # Row constraints\n\n    for i=1:n\n        for k=1:n\n            @constraint(MOD, sum(Z[i,j,k,l] for j=1:n for l=1:n) == 1)\n        end\n    end\n\n    for i=1:n\n        for l=1:n\n            @constraint(MOD, sum(Z[i,j,k,l] for j=1:n for k=1:n) == 1)\n        end\n    end\n\n    # Col constraints\n    for j=1:n\n        for k=1:n\n            @constraint(MOD, sum(Z[i,j,k,l] for i=1:n for l=1:n) == 1)\n        end\n    end\n\n    for j=1:n\n        for l=1:n\n            @constraint(MOD, sum(Z[i,j,k,l] for i=1:n for k=1:n) == 1)\n        end\n    end\n\n    if self   # force A^T==B\n        for i=1:n\n            for j=1:n\n                for k=1:n\n                    for l=1:n\n                        @constraint(MOD, Z[i,j,k,l] == Z[j,i,l,k])\n                    end\n                end\n            end\n        end\n    end\n\n\n    optimize!(MOD)\n    status = Int(termination_status(MOD))\n\n    if status != 1\n        error(\"No pair of orthogonal Latin squares of order $n can be found.\")\n    end\n\n    ZZ = value.(Z)\n    A = zeros(Int,n,n)\n    B = zeros(Int,n,n)\n\n    for i=1:n\n        for j=1:n\n            for k=1:n\n                for l=1:n\n                    if ZZ[i,j,k,l]>0\n                        A[i,j] = k\n                        B[i,j] = l\n                    end\n                end\n            end\n        end\n    end\n\n    return A,B\nend\n\n\n\n\n\nfunction ortho_latin(n::Int, r::Int, s::Int)\n    A = latin(n,r)\n    B = latin(n,s)\n    @assert check_ortho(A,B) \"Parameters n=$n, r=$r, and s=$s do not generate a pair of orthogonal Latin squares\"\n    return A,B\nend\n\n\"\"\"\n`find_ortho_parameters(n)` tries to find parameters `r` and `s`\nso that `ortho_latin(n,r,s)` will succeed. Returns `(r,s)` if\nsuccessful or throws an error if not.\n\"\"\"\nfunction find_ortho_parameters(n::Int)\n    for r=1:n-1\n        for s=1:n-1\n            if gcd(n,r)==1 && gcd(n,s)==1 && gcd(n,r-s)==1\n                return r,s\n            end\n        end\n    end\n    error(\"No parameters for n=$n found\")\nend\n\n\n\"\"\"\n`check_ortho(A,B)` checks that matrices `A` and `B` are a pair of\northogonal Latin squares.\n\"\"\"\nfunction check_ortho(A::Matrix{Int},B::Matrix{Int})::Bool\n    if size(A) != size(B)\n        return false\n    end\n    if !check_latin(A) || !check_latin(B)\n        return false\n    end\n    n,r = size(A)\n\n    vals = unique((n+1)*A + B)\n    return length(vals) == n*n\nend\n", "meta": {"hexsha": "d133fda4fcfb5891b318bd2482bc34c2a66b3a47", "size": 3733, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ortho_latin.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/LatinSquares.jl-c3c424ec-ae8f-5049-b7bf-f9296ef684c8", "max_stars_repo_head_hexsha": "0ed5548a237340dea8a8856679685e3fe753d3fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ortho_latin.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/LatinSquares.jl-c3c424ec-ae8f-5049-b7bf-f9296ef684c8", "max_issues_repo_head_hexsha": "0ed5548a237340dea8a8856679685e3fe753d3fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ortho_latin.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/LatinSquares.jl-c3c424ec-ae8f-5049-b7bf-f9296ef684c8", "max_forks_repo_head_hexsha": "0ed5548a237340dea8a8856679685e3fe753d3fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4879518072, "max_line_length": 113, "alphanum_fraction": 0.5156710421, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7796808180803149}}
{"text": "# These functions compute the sizes of combinations of parameters.\n\nusing Combinatorics: combinations\n\n\"\"\"\n    total_combinations(arity, n_way)\n\nGiven an array of the number of values for each parameter and the\nlevel of coverage, return the number of n-tuples required for complete\ncoverage.\n\"\"\"\nfunction total_combinations(arity, n_way)\n  param_cnt = length(arity)\n  sum(prod(arity[key_set]) for key_set in combinations(1:param_cnt, n_way))\nend\n\n\n\"\"\"\n    next_multiplicative!(values, arity)\n\nGiven a set of values for parameters, this returns the next possible\nvalue. When it reaches the end, it cycles back to the start. The first\nvalue is all ones. The last value equals the arity.\n\"\"\"\nfunction next_multiplicative!(values, arity)\n    carry = 1\n    for slot_idx in length(values):-1:1\n        values[slot_idx] += carry\n        if arity[slot_idx] < values[slot_idx]\n            values[slot_idx] = 1\n            carry = 1\n        else\n            carry = 0\n        end\n    end\nend\n\n\n\"\"\"\n    all_combinations(arity, n_way)\n\nThis represents possible coverage as a matrix, one row per parameter,\nzero if not used. `arity` is a list of the number of values for each parameter,\nand `n_way` is the order of the combinations, most commonly 2-way.\n\"\"\"\nfunction all_combinations(arity, n_way)\n    v_cnt = length(arity)\n    # This returns a list of lists, so it has length, not size.\n    indices = collect(combinations(1:v_cnt, n_way))\n    combinations_cnt = total_combinations(arity, n_way)\n\n    coverage = zeros(eltype(arity), v_cnt, combinations_cnt)\n    idx = 1\n    for indices_idx in 1:length(indices)\n        offset = indices[indices_idx]\n        sub_arity = arity[offset]\n        sub_cnt = prod(sub_arity)\n        values = copy(sub_arity)\n        for sub_idx in 1:sub_cnt\n            next_multiplicative!(values, sub_arity)\n            coverage[offset, idx] = values\n            idx += 1\n        end\n    end\n    coverage\nend\n\n\n\"\"\"\n    one_parameter_combinations(arity, n_way)\n\nGenerates all combinations that are nonzero for the last parameter.\nThis is for in-parameter-order generation, where we need\nonly those tuples that end with this column being nonzero.\n\nThe construction method is to leave out the given parameter\nand construct all `n_way` - 1 tuples. Then copy and paste that\nonce for each possible value of the given parameter.\n\"\"\"\nfunction one_parameter_combinations(arity, n_way)\n    param_cnt = length(arity)\n    if n_way > 1\n        partial = all_combinations(arity[1:(param_cnt-1)], n_way - 1)\n        one_set = size(partial, 2)\n        comb = zeros(eltype(arity), param_cnt, one_set * arity[param_cnt])\n        for vidx in 1:(arity[param_cnt])\n            col_begin = (vidx - 1) * one_set + 1\n            col_end = vidx * one_set\n            comb[1:size(partial, 1), col_begin:col_end] .= partial\n            comb[param_cnt, col_begin:col_end] .= vidx\n        end\n    else  # n_way == 1\n        comb = zeros(eltype(arity), param_cnt, arity[param_cnt])\n        comb[param_cnt, :] .= 1:(arity[param_cnt])\n    end\n    comb\nend\n\n\ncombination_number(n, m) = prod(n:-1:(n-m+1)) ÷ factorial(m)\n\n\nfunction pairs_in_entry(entry, n_way)\n    n = length(entry)\n    ans = zeros(Int, combination_number(n, n_way), n)\n    col_set_idx = 1\n    for param_idx in combinations(1:length(entry), n_way)\n        for row_idx in 1:n_way\n            ans[param_idx[row_idx], col_set_idx] = entry[param_idx[row_idx]]\n        end\n        col_set_idx += 1\n    end\n    ans\nend\n", "meta": {"hexsha": "926b8286c5050709f71045e89904bb434f31fa3c", "size": 3460, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/combinations.jl", "max_stars_repo_name": "oxinabox/UnitTestDesign.jl", "max_stars_repo_head_hexsha": "2c51b85f3d0de8bb7106b42981d3555f8d21983f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-12-15T04:15:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-04T21:18:56.000Z", "max_issues_repo_path": "src/combinations.jl", "max_issues_repo_name": "oxinabox/UnitTestDesign.jl", "max_issues_repo_head_hexsha": "2c51b85f3d0de8bb7106b42981d3555f8d21983f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2020-11-30T05:03:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T14:45:44.000Z", "max_forks_repo_path": "src/combinations.jl", "max_forks_repo_name": "adolgert/UnitTestDesign.jl", "max_forks_repo_head_hexsha": "b6813153caa8668df829aea3cd5ffc3599eebfd4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0869565217, "max_line_length": 79, "alphanum_fraction": 0.6725433526, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7796808103939936}}
{"text": "# Example from \"Bounds on the reachable sets of nonlinear control systems\" Constant Temperature Profile\r\nid = :ScottB2013a\r\n\r\npL = [420.0]\r\npU = [480.0]\r\nScottB2013a_x0(p::Vector{T}) where T = [1.5*one(T); 0.5*one(T); zero(T)]\r\nfunction ScottB2013a_f!(du::Vector{T}, u::Vector{T}, p::Vector{T}, t) where T\r\n\r\n    R = 8.134\r\n    A1 = 2400\r\n    A2 = 8800\r\n    E1 = 6.9*10^3\r\n    E2 = 1.69*10^4\r\n\r\n    du[1] = -A1*exp(E1/(R*p[1]))*u[1]\r\n    du[2] = A1*exp(E1/(R*p[1]))*u[1] - A2*exp(E2/(R*p[1]))*u[2]\r\n    du[3] = A2*exp(E2/(R*p[1]))*u[2]\r\n    return\r\nend\r\ntspan = (0.0, 0.08)\r\n\r\nprob = ODERelaxProb(ScottB2013a_f!, tspan, ScottB2013a_x0, pL, pU)\r\nurl = \"https://www.sciencedirect.com/science/article/pii/S0005109812004839\"\r\nsource = \"ScottB2013\"\r\ndesc = \"3 Series Rxn Network\"\r\n", "meta": {"hexsha": "2b345972d42a17845b4806025040fc00bef2ccb1", "size": 776, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/library/pODEs/ScottB2013a.jl", "max_stars_repo_name": "PSORLab/DynamicBounds.jl", "max_stars_repo_head_hexsha": "a7c258e3e4297442ad425c398705f3163e953331", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-15T17:57:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-15T17:57:30.000Z", "max_issues_repo_path": "src/library/pODEs/ScottB2013a.jl", "max_issues_repo_name": "PSORLab/DynamicBounds.jl", "max_issues_repo_head_hexsha": "a7c258e3e4297442ad425c398705f3163e953331", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-09-15T14:31:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T03:48:15.000Z", "max_forks_repo_path": "src/library/pODEs/ScottB2013a.jl", "max_forks_repo_name": "PSORLab/DynamicBounds.jl", "max_forks_repo_head_hexsha": "a7c258e3e4297442ad425c398705f3163e953331", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-15T17:57:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T17:57:36.000Z", "avg_line_length": 29.8461538462, "max_line_length": 104, "alphanum_fraction": 0.6018041237, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819236, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7796808069078789}}
{"text": "using StanModels, CSV\n\ndf = CSV.read(joinpath(@__DIR__, \"..\", \"..\", \"data\", \"milk.csv\"), delim=';')\ndcc = filter(row -> !(row[:neocortex_perc] == \"NA\"), df)\ndcc[!, :kcal_per_g] = convert(Vector{Float64}, dcc[!, :kcal_per_g])\ndcc[!, :neocortex_perc] = parse.(Float64, dcc[!, :neocortex_perc])\n\n# Show first 5 rows\n\nfirst(dcc, 5)\n\n# Define the Stan language model\n\nm5_5s = \"\ndata{\n    int N;\n    vector[N] kcal_per_g;\n    vector[N] neocortex_perc;\n}\nparameters{\n    real a;\n    real bn;\n    real sigma;\n}\nmodel{\n    vector[N] mu = a + bn * neocortex_perc;\n    sigma ~ uniform( 0 , 1 );\n    bn ~ normal( 0 , 1 );\n    a ~ normal( 0 , 100 );\n    kcal_per_g ~ normal( mu , sigma );\n}\n\";\n\n# Define the Stanmodel and set the output format to :mcmcchains.\n\nsm = SampleModel(\"m5.5s\", m5_5s);\n\n# Input data for cmdstan\n\nm5_5_data = Dict(\"N\" => size(dcc, 1), \n  \"kcal_per_g\" => dcc[!, :kcal_per_g],\n  \"neocortex_perc\" => dcc[!, :neocortex_perc]);\n\n# Sample using cmdstan\n\n(sample_file, log_file) = stan_sample(sm, data=m5_5_data);\n\n# Rethinking results\n\nrethinking_results = \"\n       mean   sd  5.5% 94.5%\n a     0.04 0.15 -0.21  0.29\n bN    0.13 0.22 -0.22  0.49\n sigma 1.00 0.16  0.74  1.26\n\"\n\n# Describe the draws\nif !(sample_file == nothing)\n  chn = read_samples(sm)\n  describe(chn)\nend\n\n", "meta": {"hexsha": "42dcd25474d115dc573f494b82a9faed9ca3ea33", "size": 1280, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/05/m5.5s.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StanModels.jl-fb740163-aa3c-59c1-9c12-c3f890714cde", "max_stars_repo_head_hexsha": "16dd5f82cc418e8444ef6ac8490b4bbda3783283", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/05/m5.5s.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StanModels.jl-fb740163-aa3c-59c1-9c12-c3f890714cde", "max_issues_repo_head_hexsha": "16dd5f82cc418e8444ef6ac8490b4bbda3783283", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/05/m5.5s.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StanModels.jl-fb740163-aa3c-59c1-9c12-c3f890714cde", "max_forks_repo_head_hexsha": "16dd5f82cc418e8444ef6ac8490b4bbda3783283", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3174603175, "max_line_length": 76, "alphanum_fraction": 0.6171875, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7796164179512814}}
{"text": "\n\"A basis of Chebyshev polynomials of the second kind on the interval `[-1,1]`.\"\nstruct ChebyshevU{T} <: OPS{T}\n    n\t\t\t::\tInt\nend\n\nChebyshevU(n::Int) = ChebyshevU{Float64}(n)\n\nsimilar(b::ChebyshevU, ::Type{T}, n::Int) where {T} = ChebyshevU{T}(n)\n\nshow(io::IO, d::ChebyshevU{Float64}) = print(io, \"ChebyshevU($(length(d)))\")\nshow(io::IO, d::ChebyshevU{T}) where T = print(io, \"ChebyshevU{$(T)}($(length(d)))\")\n\nfunction unsafe_eval_element(b::ChebyshevU, idx::PolynomialDegree, x::Real)\n    # Don't use the formula when |x|=1, because it will generate NaN's\n    d = degree(idx)\n    abs(x) < 1 ? sin((d+1)*acos(x))/sqrt(1-x^2) : recurrence_eval(b, idx, x)\nend\n\nfirst_moment(b::ChebyshevU{T}) where {T} = convert(T, pi)/2\n\ninterpolation_grid(b::ChebyshevU{T}) where {T} = ChebyshevUNodes{T}(b.n)\n\niscompatible(dict::ChebyshevU, grid::ChebyshevUNodes) = length(dict) == length(grid)\nissymmetric(::ChebyshevU) = true\nmeasure(dict::ChebyshevU{T}) where {T} = ChebyshevUWeight{T}()\nhasmeasure(::ChebyshevU) = true\n\nfunction innerproduct_native(b1::ChebyshevU, i::PolynomialDegree, b2::ChebyshevU, j::PolynomialDegree, m::ChebyshevUWeight;\n\t\t\tT = coefficienttype(b1), options...)\n\tif i == j\n\t\tconvert(T, pi)/2\n\telse\n\t\tzero(T)\n\tend\nend\n\n\n# Parameters alpha and beta of the corresponding Jacobi polynomial\njacobi_α(b::ChebyshevU{T}) where {T} = one(T)/2\njacobi_β(b::ChebyshevU{T}) where {T} = one(T)/2\n\n\n# See DLMF, Table 18.9.1\n# http://dlmf.nist.gov/18.9#i\nrec_An(b::ChebyshevU{T}, n::Int) where {T} = convert(T, 2)\n\nrec_Bn(b::ChebyshevU{T}, n::Int) where {T} = zero(T)\n\nrec_Cn(b::ChebyshevU{T}, n::Int) where {T} = one(T)\n\nsupport(b::ChebyshevU{T}) where {T} = ChebyshevInterval{T}()\n\n\n\"A Chebyshev polynomial of the second kind\"\nstruct ChebyshevUPolynomial{T} <: OrthogonalPolynomial{T}\n    degree  ::  Int\nend\n\nChebyshevUPolynomial{T}(p::ChebyshevUPolynomial) where {T} = ChebyshevUPolynomial{T}(p.degree)\n\nshow(io::IO, p::ChebyshevUPolynomial) = print(io, \"U_$(degree(p))(x) (Chebyshev polynomial of the second kind)\")\n\nconvert(::Type{TypedFunction{T,T}}, p::ChebyshevUPolynomial) where {T} = ChebyshevUPolynomial{T}(p.degree)\n\nsupport(::ChebyshevUPolynomial{T}) where {T} = ChebyshevInterval{T}()\n\n(p::ChebyshevUPolynomial{T})(x) where {T} = eval_element(ChebyshevU{T}(degree(p)+1), degree(p)+1, x)\n\nbasisfunction(dict::ChebyshevU, idx) = basisfunction(dict, native_index(dict, idx))\nbasisfunction(dict::ChebyshevU{T}, idx::PolynomialDegree) where {T} = ChebyshevUPolynomial{T}(degree(idx))\n\ndictionary(p::ChebyshevUPolynomial{T}) where {T} = ChebyshevU{T}(degree(p)+1)\nindex(p::ChebyshevUPolynomial) = degree(p)+1\n", "meta": {"hexsha": "9c5459002fd0fc0268e83c2162550d318874625a", "size": 2614, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bases/poly/chebyshev/ChebyshevU.jl", "max_stars_repo_name": "JuliaApproximation/BasisFunctions.jl", "max_stars_repo_head_hexsha": "9f2ab9cae1394cbaede565db1036fbf0fbd1da9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-06-21T03:12:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:03:32.000Z", "max_issues_repo_path": "src/bases/poly/chebyshev/ChebyshevU.jl", "max_issues_repo_name": "JuliaApproximation/BasisFunctions.jl", "max_issues_repo_head_hexsha": "9f2ab9cae1394cbaede565db1036fbf0fbd1da9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2020-01-07T17:23:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T17:50:16.000Z", "max_forks_repo_path": "src/bases/poly/chebyshev/ChebyshevU.jl", "max_forks_repo_name": "daanhb/BasisFunctions.jl", "max_forks_repo_head_hexsha": "93ef8f01b828b17d896acf11713a714fc7b6cb9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-21T17:01:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-03T08:12:27.000Z", "avg_line_length": 34.8533333333, "max_line_length": 123, "alphanum_fraction": 0.7004590666, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7796164038504098}}
{"text": "# indicator of the L2 norm ball with given radius\n\n\"\"\"\n  IndBallL2(r::Real=1.0)\n\nReturns the function `g = ind{x : ||x|| ⩽ r}`, for a real parameter `r > 0`.\n\"\"\"\n\nimmutable IndBallL2{R <: Real} <: IndicatorConvex\n  r::R\n  function IndBallL2(r::R)\n    if r <= 0\n      error(\"parameter r must be positive\")\n    else\n      new(r)\n    end\n  end\nend\n\nIndBallL2{R <: Real}(r::R=1.0) = IndBallL2{R}(r)\n\nfunction (f::IndBallL2){T <: RealOrComplex}(x::AbstractArray{T})\n  if vecnorm(x) - f.r > 1e-14\n    return +Inf\n  end\n  return 0.0\nend\n\nfunction prox!{T <: RealOrComplex}(f::IndBallL2, x::AbstractArray{T}, y::AbstractArray{T}, gamma::Real=1.0)\n  scal = f.r/vecnorm(x)\n  if scal > 1\n    y[:] = x\n    return 0.0\n  end\n  for k in eachindex(x)\n    y[k] = scal*x[k]\n  end\n  return 0.0\nend\n\nfun_name(f::IndBallL2) = \"indicator of an L2 norm ball\"\nfun_dom(f::IndBallL2) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::IndBallL2) = \"x ↦ 0 if ||x|| ⩽ r, +∞ otherwise\"\nfun_params(f::IndBallL2) = \"r = $(f.r)\"\n\nfunction prox_naive{T <: RealOrComplex}(f::IndBallL2, x::AbstractArray{T}, gamma::Real=1.0)\n  normx = vecnorm(x)\n  if normx > f.r\n    y = (f.r/normx)*x\n  else\n    y = x\n  end\n  return y, 0.0\nend\n", "meta": {"hexsha": "64ecb7c11f620eeac0e8e61d316198e4ccf5f2e6", "size": 1202, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indBallL2.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/indBallL2.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/indBallL2.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8545454545, "max_line_length": 107, "alphanum_fraction": 0.6181364393, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121366457407, "lm_q2_score": 0.867035771827307, "lm_q1q2_score": 0.7795703879328209}}
{"text": "using GeometryTypes\nusing SurfaceTopology\nusing LinearAlgebra\n\nfunction quadraticform(vects,vnormal)\n    \n    Lx = [0 0 0; 0 0 -1; 0 1 0]\n    Ly = [0 0 1; 0 0 0; -1 0 0]\n    Lz = [0 -1 0; 1 0 0; 0 0 0]\n\n    d = [0,0,1] + vnormal\n    d /= norm(d)\n        \n    Ln = d[1]*Lx + d[2]*Ly + d[3]*Lz\n    R = exp(pi*Ln)\n\n    vects = copy(vects)\n    for vj in 1:length(vects)\n        vects[vj] = R*vects[vj]\n    end\n\n    ### Construction of the system\n    A = Array{Float64}(undef,3,3)\n    B = Array{Float64}(undef,3)\n\n    vects_norm2 = Array{Float64}(undef,length(vects))\n    for vj in 1:length(vects)\n       vects_norm2[vj] = norm(vects[vj])^2\n    end\n\n    A[1,1] = sum((v[1]^4 for v in vects) ./ vects_norm2)\n    A[1,2] = sum((v[1]^3*v[2] for v in vects) ./ vects_norm2)\n    A[1,3] = sum((v[1]^2*v[2]^2 for v in vects) ./ vects_norm2)\n    A[2,1] = A[1,2]\n    A[2,2] = A[1,3]\n    A[2,3] = sum( (v[2]^3*v[1] for v in vects) ./vects_norm2)\n    A[3,1] = A[1,3]\n    A[3,2] = A[2,3]\n    A[3,3] = sum((v[2]^4 for v in vects) ./vects_norm2)\n\n    \n    B[1] = sum((v[3]*v[1]^2 for v in vects) ./vects_norm2)\n    B[2] = sum((v[1]*v[2]*v[3] for v in vects) ./vects_norm2)\n    B[3] = sum((v[2]^2*v[3] for v in vects) ./vects_norm2)\n\n    C,D,E = A\\B\n    return C,D,E\nend\n\nfunction meancurvature(points,topology)\n    curvatures = Array{Float64}(undef,length(points))\n    for v in 1:length(points)\n\n        s = Point(0,0,0)\n        for (v1,v2) in EdgeRing(v,topology)\n            s += cross(points[v2],points[v1])\n        end\n        normal = s ./ norm(s)\n\n        vring = collect(VertexRing(v,topology))\n        vects = [points[vi] - points[v] for vi in vring]\n\n        C,D,E = quadraticform(vects,normal)\n\n        A = [C D/2;D/2 E]\n        k1,k2 = eigvals(-A)\n        H = (k1 + k2)/2\n\n        ### Multiplier by is 2 an empirical fix\n        curvatures[v] = 2*H \n    end\n    return curvatures\nend\n\nfunction normals(vertices,topology)\n    n = Point{3,Float64}[]\n    for v in 1:length(vertices)\n        s = Point(0,0,0)\n        for (v1,v2) in EdgeRing(v,topology)\n            s += cross(vertices[v2],vertices[v1])\n        end\n        normal = s ./ norm(s)\n        push!(n,normal)\n    end\n    return n\nend\n\nfunction vertexareas(points,topology)\n    vareas = zeros(Float64,length(points))\n    for face in Faces(topology)\n        v1,v2,v3 = face\n        area = norm(cross(points[v2]-points[v1],points[v3]-points[v1])) /2\n        vareas[v1] += area/3\n        vareas[v2] += area/3\n        vareas[v3] += area/3\n    end\n    return vareas\nend\n\nfunction surfacevolume(points,topology)\n    # Calculate face normal\n    # Calculate projected area\n    # Calculate ordinary volume \n    # Calculate volume between projected and real area\n    # (+) if normal is outwards\n    \n    normal0 = [0,0,1]\n    s = 0\n    for face in Faces(topology)\n        y1 = points[face[1]]\n        y2 = points[face[2]]\n        y3 = points[face[3]]\n\n        normaly = cross(y2-y1,y3-y1)\n        normaly /= norm(normaly)\n\n        area = norm(cross(y2-y1,y3-y1))/2\n        areaproj = dot(normaly,normal0)*area\n        volume = dot(y1 + y2 + y3,normal0)/3*areaproj\n\n        s += volume\n    end\n\n    return s\nend\n\n\n\n", "meta": {"hexsha": "1724f80d17cba801c1d011686cdf3742cf6356ba", "size": 3150, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/properties.jl", "max_stars_repo_name": "JuliaTagBot/SoftSurfaceDynamics.jl", "max_stars_repo_head_hexsha": "02e6a0e46d5fa44fa5fab244d1a92a4fc7222b94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-27T11:48:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T11:48:32.000Z", "max_issues_repo_path": "src/properties.jl", "max_issues_repo_name": "JuliaTagBot/SoftSurfaceDynamics.jl", "max_issues_repo_head_hexsha": "02e6a0e46d5fa44fa5fab244d1a92a4fc7222b94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/properties.jl", "max_forks_repo_name": "JuliaTagBot/SoftSurfaceDynamics.jl", "max_forks_repo_head_hexsha": "02e6a0e46d5fa44fa5fab244d1a92a4fc7222b94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:02:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:02:46.000Z", "avg_line_length": 24.4186046512, "max_line_length": 74, "alphanum_fraction": 0.5523809524, "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692352660529, "lm_q2_score": 0.798186784940666, "lm_q1q2_score": 0.7795644768474697}}
{"text": "\"\"\"\n\trandom_density(n)\n\nReturns a random ``N × N`` density matrix, distributed according to the\nHilbert-Schmidt measure.\n\nNOTE: No guarantee about the quality of the algorithm\nFor more details see [V Al Osipov et al 2010 J. Phys. A: Math. Theor. 43 055302]\n(https://doi.org/10.1088/1751-8113/43/5/055302)\n\"\"\"\nfunction random_density_matrix(n)\n    A = randn(n,n) + 1im * randn(n,n)\n    rho = A * A'\n    return rho / tr(rho)\nend\n\n\"\"\"\n\tunitary_op(H, t)\n\nReturns the unitary evolution operator ``U = \\\\exp[-i H t]``.\n\"\"\"\nfunction unitary_op(H, t)\n   return exp(-1im * Matrix(H) * t)\nend\n\n\"\"\"\n    commutator(A, B)\n\nReturns the commutator [A,B] = A * B - B * A between two matrices\n\"\"\"\nfunction commutator(a, b)\n\ta * b - b * a\nend\n\n\"\"\"\n\tlocalized_state(N, i)\n\nReturns the density operator for a state ``|i⟩`` in an ``N``-dimensional Hilbert\nspace\n\"\"\"\nfunction localized_state(n, i)\n   sparse([i,n],[i,n],[1,0])\nend\n", "meta": {"hexsha": "ca501f9d64fc5ebbc8b668ffc06cb25efd6c447c", "size": 909, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Utilities.jl", "max_stars_repo_name": "matteoacrossi/QuasiHamiltonianRTN.jl", "max_stars_repo_head_hexsha": "8005be028134838eda520fe0a8fd7131171f8db7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-22T23:36:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T00:39:43.000Z", "max_issues_repo_path": "src/Utilities.jl", "max_issues_repo_name": "matteoacrossi/QuasiHamiltonianRTN.jl", "max_issues_repo_head_hexsha": "8005be028134838eda520fe0a8fd7131171f8db7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utilities.jl", "max_forks_repo_name": "matteoacrossi/QuasiHamiltonianRTN.jl", "max_forks_repo_head_hexsha": "8005be028134838eda520fe0a8fd7131171f8db7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-10T00:39:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T00:39:48.000Z", "avg_line_length": 20.6590909091, "max_line_length": 80, "alphanum_fraction": 0.6534653465, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802364, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.7795623455226129}}
{"text": "# # Chebyshev transform\n# This demonstrates the Chebyshev transform and inverse transform,\n# explaining precisely the normalization and points\n\nusing FastTransforms\nn = 20\n\n# First kind points $\\to$ first kind polynomials\np_1 = chebyshevpoints(Float64, n, Val(1))\nf = exp.(p_1)\nf̌ = chebyshevtransform(f, Val(1))\nf̃ = x -> [cos(k*acos(x)) for k=0:n-1]' * f̌\nf̃(0.1) ≈ exp(0.1)\n\n# First kind polynomials $\\to$ first kind points\nichebyshevtransform(f̌, Val(1)) ≈ exp.(p_1)\n\n# Second kind points $\\to$ first kind polynomials\np_2 = chebyshevpoints(Float64, n, Val(2))\nf = exp.(p_2)\nf̌ = chebyshevtransform(f, Val(2))\nf̃ = x -> [cos(k*acos(x)) for k=0:n-1]' * f̌\nf̃(0.1) ≈ exp(0.1)\n\n# First kind polynomials $\\to$ second kind points\nichebyshevtransform(f̌, Val(2)) ≈ exp.(p_2)\n\n# First kind points $\\to$ second kind polynomials\np_1 = chebyshevpoints(Float64, n, Val(1))\nf = exp.(p_1)\nf̌ = chebyshevutransform(f, Val(1))\nf̃ = x -> [sin((k+1)*acos(x))/sin(acos(x)) for k=0:n-1]' * f̌\nf̃(0.1) ≈ exp(0.1)\n\n# Second kind polynomials $\\to$ first kind points\nichebyshevutransform(f̌, Val(1)) ≈ exp.(p_1)\n\n# Second kind points $\\to$ second kind polynomials\np_2 = chebyshevpoints(Float64, n, Val(2))[2:n-1]\nf = exp.(p_2)\nf̌ = chebyshevutransform(f, Val(2))\nf̃ = x -> [sin((k+1)*acos(x))/sin(acos(x)) for k=0:n-3]' * f̌\nf̃(0.1) ≈ exp(0.1)\n\n# Second kind polynomials $\\to$ second kind points\nichebyshevutransform(f̌, Val(2)) ≈ exp.(p_2)\n", "meta": {"hexsha": "5f553b09b43e7e7b8aefecd1ab35fe691448b0fa", "size": 1421, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/chebyshev.jl", "max_stars_repo_name": "eschnett/FastTransforms.jl", "max_stars_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2019-04-13T05:52:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T10:03:15.000Z", "max_issues_repo_path": "examples/chebyshev.jl", "max_issues_repo_name": "eschnett/FastTransforms.jl", "max_issues_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113, "max_issues_repo_issues_event_min_datetime": "2019-04-12T20:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:16:28.000Z", "max_forks_repo_path": "examples/chebyshev.jl", "max_forks_repo_name": "eschnett/FastTransforms.jl", "max_forks_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2019-04-23T08:43:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T15:35:17.000Z", "avg_line_length": 30.2340425532, "max_line_length": 66, "alphanum_fraction": 0.6622097115, "num_tokens": 580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545274901875, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7795623444920885}}
{"text": "# # Robust approximate fitting\n# Section 6.4.2\n# Boyd & Vandenberghe \"Convex Optimization\"\n# Original by Lieven Vandenberghe\n# Adapted for Convex by Joelle Skaf - 10/03/05\n#\n# Adapted for Convex.jl by Karanveer Mohan and David Zeng - 26/05/14\n# Original cvx code and plots here:\n# <http://web.cvxr.com/cvx/examples/cvxbook/Ch06_approx_fitting/html/fig6_15.html>\n#\n# Consider the least-squares problem:\n#       minimize $\\|(A + tB)x - b\\|_2$\n# where $t$ is an uncertain parameter in [-1,1]\n# Three approximate solutions are found:\n#\n#   1. nominal optimal (i.e. letting t=0)\n#   2. stochastic robust approximation:\n#           minimize $\\mathbb{E}\\|(A+tB)x - b\\|_2$\n#      assuming $u$ is uniformly distributed on [-1,1].\n#      (reduces to minimizing $\\mathbb{E} \\|(A+tB)x-b\\|^2 = \\|A*x-b\\|^2  + x^TPx$\n#        where $P = \\mathbb{E}(t^2) B^TB = (1/3) B^TB$ )\n#   3. worst-case robust approximation:\n#           minimize $\\mathrm{sup}_{-1\\leq u\\leq 1} \\|(A+tB)x - b\\|_2$\n#      (reduces to minimizing $\\max\\{\\|(A-B)x - b\\|_2, \\|(A+B)x - b\\|_2\\}$ ).\n#\nusing Convex, LinearAlgebra, SCS\n\n# Input Data\nm = 20;\nn = 10;\nA = randn(m, n);\n(U, S, V) = svd(A);\nS = diagm(exp10.(range(-1, stop = 1, length = n)));\nA = U[:, 1:n] * S * V';\n\nB = randn(m, n);\nB = B / norm(B);\n\nb = randn(m, 1);\nx = Variable(n)\n\n# Case 1: Nominal optimal solution\np = minimize(norm(A * x - b, 2))\nsolve!(p, SCS.Optimizer; silent_solver = true)\nx_nom = evaluate(x)\n\n# Case 2: Stochastic robust approximation\nP = 1 / 3 * B' * B;\np = minimize(square(pos(norm(A * x - b))) + quadform(x, Symmetric(P)))\nsolve!(p, SCS.Optimizer; silent_solver = true)\nx_stoch = evaluate(x)\n\n# Case 3: Worst-case robust approximation\np = minimize(max(norm((A - B) * x - b), norm((A + B) * x - b)))\nsolve!(p, SCS.Optimizer; silent_solver = true)\nx_wc = evaluate(x)\n\n# Plot residuals:\nparvals = range(-2, stop = 2, length = 100);\n\nerrvals(x) = [norm((A + parvals[k] * B) * x - b) for k in eachindex(parvals)]\nerrvals_ls = errvals(x_nom)\nerrvals_stoch = errvals(x_stoch)\nerrvals_wc = errvals(x_wc)\n\nusing Plots\nplot(parvals, errvals_ls, label = \"Nominal problem\")\nplot!(parvals, errvals_stoch, label = \"Stochastic Robust Approximation\")\nplot!(parvals, errvals_wc, label = \"Worst-Case Robust Approximation\")\nplot!(\n    title = \"Residual r(u) vs a parameter u for three approximate solutions\",\n    xlabel = \"u\",\n    ylabel = \"r(u) = ||A(u)x-b||_2\",\n)\n", "meta": {"hexsha": "4005d9e88ca9b8ebc2550ecbbcc7994678db905c", "size": 2390, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/general_examples/robust_approx_fitting.jl", "max_stars_repo_name": "baggepinnen/Convex.jl", "max_stars_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 327, "max_stars_repo_stars_event_min_datetime": "2015-01-22T01:00:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T16:42:11.000Z", "max_issues_repo_path": "docs/examples_literate/general_examples/robust_approx_fitting.jl", "max_issues_repo_name": "baggepinnen/Convex.jl", "max_issues_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 275, "max_issues_repo_issues_event_min_datetime": "2015-01-12T19:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-05T19:05:45.000Z", "max_forks_repo_path": "docs/examples_literate/general_examples/robust_approx_fitting.jl", "max_forks_repo_name": "baggepinnen/Convex.jl", "max_forks_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 121, "max_forks_repo_forks_event_min_datetime": "2015-01-23T21:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T13:58:39.000Z", "avg_line_length": 31.8666666667, "max_line_length": 82, "alphanum_fraction": 0.6351464435, "num_tokens": 838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7794524323870292}}
{"text": "import Pkg; Pkg.activate(joinpath(@__DIR__, \"../../../../../\"))\nusing Distributions\nusing PyPlot\n\n\"\"\"\nPaper: Bayesian inference for finite mixtures of univariate and multivariate\n       skew-normal and skew-t distributions, Biostatistics 2010.\nskew (delta): a real number in (-1, 1)\n\"\"\"\nfunction rand_skewnormal(loc, scale, skew)\n    z = rand(TruncatedNormal(0, 1, 0, Inf))\n    return loc + scale * skew * z + scale * sqrt(1 - skew ^ 2) * randn()\nend\n\nfunction rand_skewnormal(loc, scale, skew, dims...)\n    z = rand(TruncatedNormal(0, 1, 0, Inf), dims...)\n    return loc .+ scale * skew * z + scale * sqrt(1 - skew ^ 2) * randn(dims...)\nend\n\nx = rand_skewnormal(1, .5, -.97, 100000)\nplt.hist(x, bins=100);\n\nmean(x .< 0)\n\nmean(x), std(x)\n\n\n", "meta": {"hexsha": "d57867463fd6192147031c96695cf7aca8c38ee7", "size": 740, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "runs/sim-study/configs/test-sim-6-7-19/notebook/scripts/sketch-data-gen.jl", "max_stars_repo_name": "luiarthur/CytofRepFAM.jl", "max_stars_repo_head_hexsha": "1f997d1620d74861c5bde5559ebdd1e6c449b9e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "runs/sim-study/configs/test-sim-6-7-19/notebook/scripts/sketch-data-gen.jl", "max_issues_repo_name": "luiarthur/CytofRepFAM.jl", "max_issues_repo_head_hexsha": "1f997d1620d74861c5bde5559ebdd1e6c449b9e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-02-05T01:26:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-16T04:13:03.000Z", "max_forks_repo_path": "runs/sim-study/configs/test-sim-6-7-19/notebook/scripts/sketch-data-gen.jl", "max_forks_repo_name": "luiarthur/CytofRepFAM.jl", "max_forks_repo_head_hexsha": "1f997d1620d74861c5bde5559ebdd1e6c449b9e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4285714286, "max_line_length": 80, "alphanum_fraction": 0.6432432432, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465188527685, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7794472670430118}}
{"text": "module MDL\n\nsetprecision(BigFloat, 64)\n\n\"\"\"\nscalable binomial coefficient\n\"\"\"\nfunction choose(n::Int64, k::Int64)\n    if 0 < k <= n\n        p = BigInt(1)\n        for t=0:(min(k,n-k)-1)\n            p = floor((p * (n - t)) / (t + 1))\n        end\n        return p\n    else\n        return 0.\n    end\nend\n\n\"\"\"\nbinary logarithm\n\"\"\"\nfunction log2(n::Real)\n    return log(2, n)\nend\n\n\"\"\"\nbinary logarithm returning 0. at zero\n\"\"\"\nfunction log2_zero(n::Real)\n    if n == 0\n        return 0.\n    else\n        return log2(n)\n    end\nend\n\n\"\"\"\nbinary logarithm of binomial coefficient\n\"\"\"\nfunction log2_choose(n::Int64, k::Int64)\n    if n == 0 || k == 0\n        return 0.\n    else\n        return log2_zero(choose(n,k))\n    end\nend\n\n\"\"\"\niterated logarithm (log-star)\n\"\"\"\nfunction log2_star(n::Union{Int64,Float64,BigInt,BigFloat})\n    if n <= 1\n        return 0.\n    else\n        return 1. + log2_star(log2(n))\n    end\nend\n\n\"\"\"\n:param z: an int >= 1\n:return: the encoded size of the int according to Rissanen 1983's universal code for integers\n\"\"\"\nfunction universal_integer(z::Int64)\n    NORMALIZATION_CONSTANT = 2.865064\n    if z <= 0\n        return 0.\n    end\n    c = log2(NORMALIZATION_CONSTANT)\n    logstar_z = log2_star(z)\n    return logstar_z + c\nend\n\nend", "meta": {"hexsha": "e0712c9cd767039de1157cbd9d2053cc9f268f97", "size": 1247, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code/mdl.jl", "max_stars_repo_name": "dataspider/momo", "max_stars_repo_head_hexsha": "c3c16839dfed0fa3ba5deabc7ecf1431280df74c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-07-21T01:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T12:41:28.000Z", "max_issues_repo_path": "code/mdl.jl", "max_issues_repo_name": "dataspider/momo", "max_issues_repo_head_hexsha": "c3c16839dfed0fa3ba5deabc7ecf1431280df74c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/mdl.jl", "max_forks_repo_name": "dataspider/momo", "max_forks_repo_head_hexsha": "c3c16839dfed0fa3ba5deabc7ecf1431280df74c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.8513513514, "max_line_length": 93, "alphanum_fraction": 0.5902165196, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465188527685, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.779447253491854}}
{"text": "\"\"\"\n    treynor_ratio(asset_returns, benchmark_returns; multiplier=1.0, risk_free=0.0)\n\nCalculates the Treynor ratio as the ratio of excess return divided by the CAPM beta. This ratio is similar to the Sharpe Ratio, but instead of dividing by the volatility, we devide by the CAPM beta as risk proxy.\n\n# Formula\n\n    TR = E[asset_returns - risk_free] / beta * multiplier\n\n# Arguments\n- `asset_returns`:      Vector of asset returns.\n- `benchmark_returns`:  Vector of benchmark returns (e.g. market portfolio returns).\n- `multiplier`:         Optional scalar multiplier, i.e. use `12` to annualize monthly returns, and use `252` to annualize daily returns.\n- `risk_free`:          Optional vector or scalar value denoting the risk-free return (must have same frequency as the provided returns, e.g. daily).\n\"\"\"\nfunction treynor_ratio(asset_returns, benchmark_returns; multiplier=1.0, risk_free=0.0)\n    α, β = capm(asset_returns, benchmark_returns; risk_free=risk_free)\n    mean(asset_returns .- risk_free) / β * multiplier\nend\n", "meta": {"hexsha": "63aaa37ff6a534eb94ed2e21dcd5906e8c72c5df", "size": 1027, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/treynor_ratio.jl", "max_stars_repo_name": "rbeeli/RiskPerf.jl", "max_stars_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-07T19:19:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T19:19:09.000Z", "max_issues_repo_path": "src/treynor_ratio.jl", "max_issues_repo_name": "rbeeli/RiskPerf.jl", "max_issues_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/treynor_ratio.jl", "max_forks_repo_name": "rbeeli/RiskPerf.jl", "max_forks_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.35, "max_line_length": 212, "alphanum_fraction": 0.7439143135, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7794472524240185}}
{"text": "\nusing DifferentialEquations\nusing SimpleDiffEq\nusing Random\nusing Distributions\nusing GpABC\nusing Distances\nusing ApproxBayes\nusing Plots\n\n\nfunction sir_ode!(du,u,p,t)\n    (S,I,R,C) = u\n    (β,c,γ) = p\n    N = S+I+R\n    infection = β*c*I/N*S\n    recovery = γ*I\n    @inbounds begin\n        du[1] = -infection\n        du[2] = infection - recovery\n        du[3] = recovery\n        du[4] = infection\n    end\n    nothing\nend;\n\n\ntmax = 40.0\nδt = 1.0\ntspan = (0.0,tmax)\nobstimes = 1.0:δt:tmax;\nu0 = [990.0,10.0,0.0,0.0]; # S,I.R,C\np = [0.05,10.0,0.25]; # β,c,γ\n\n\nprob_ode = ODEProblem(sir_ode!,u0,tspan,p)\nsol_ode = solve(prob_ode,saveat=δt)\nout_ode = Array(sol_ode)\nC = out_ode[4,:]\nX = C[2:end] .- C[1:(end-1)];\n\n\nRandom.seed!(1234)\nY = rand.(Poisson.(X));\n\n\nbar(obstimes,Y)\nplot!(obstimes,X)\n\n\nfunction simdata(x)\n    (i0,β) = x\n    I = i0*1000.0\n    prob = remake(prob_ode,u0=[1000-I,I,0.0,0.0],p=[β,10.0,0.25])\n    sol = solve(prob,Tsit5(),saveat=δt)\n    out = Array(sol)\n    C = out[4,:]\n    X = C[2:end] .- C[1:(end-1)]\n    transpose(X)\nend;\n\n\npriors = [Uniform(0.0,0.1),Uniform(0.0,0.1)];\n\n\nYt = transpose(float.(Y));\n\n\nn_particles = 2000\nthreshold = 80.0\nsim_rej_result = SimulatedABCRejection(\n    Yt, # data\n    simdata, # simulator\n    priors, # priors\n    threshold, # threshold distance\n    n_particles; # particles required\n    max_iter=convert(Int, 1e7),\n    distance_function = Distances.euclidean,\n    write_progress=false);\n\n\nplot(sim_rej_result)\n\n\nn_design_points = 500\nemu_rej_result = EmulatedABCRejection(Yt,\n    simdata,\n    priors,\n    threshold,\n    n_particles,\n    n_design_points;\n    max_iter=convert(Int, 1e7),\n    distance_function = Distances.euclidean,\n    write_progress=false);\n\n\nplot(emu_rej_result)\n\n\nthreshold_schedule = [110.0,100.0,90.0,80.0];\n\n\nsim_smc_result = SimulatedABCSMC(Yt,\n    simdata,\n    priors,\n    threshold_schedule,\n    n_particles;\n    max_iter=convert(Int, 1e7),\n    distance_function = Distances.euclidean,\n    write_progress=false);\n\n\npopulation_colors=[\"#FF2F4E\", \"#D0001F\", \"#A20018\", \"#990017\"]\nplot(sim_smc_result, population_colors=population_colors)\n\n\nemu_smc_result = EmulatedABCSMC(Yt,\n    simdata,\n    priors,\n    threshold_schedule,\n    n_particles,\n    n_design_points;\n    distance_metric = Distances.euclidean,\n    batch_size=1000,\n    write_progress=false,\n    emulator_retraining = PreviousPopulationThresholdRetraining(n_design_points, 100, 10),\n    emulated_particle_selection = MeanVarEmulatedParticleSelection());\n\n\nplot(emu_smc_result, population_colors=population_colors)\n\n\nfunction simdist(x, constants, y)\n  s = transpose(simdata(x))\n  Distances.euclidean(s, y), 1\nend;\n\n\nab_rej_setup = ABCRejection(simdist, #simulation function\n  2, # number of parameters\n  threshold, #target ϵ\n  Prior(priors); # Prior for each of the parameters\n  maxiterations = 10^7, #Maximum number of iterations before the algorithm terminates\n  nparticles = n_particles\n  );\n\n\nab_rej = runabc(ab_rej_setup,\n            Y,\n            verbose = true,\n            progress = true,\n            parallel = true);\n\n\nplot(ab_rej)\n\n\nab_smc_setup = ABCSMC(simdist, #simulation function\n  2, # number of parameters\n  threshold, #target ϵ\n  Prior(priors), #Prior for each of the parameters\n  maxiterations=convert(Int,1e7),\n  nparticles=n_particles,\n  α = 0.3,\n  convergence = 0.05,\n  kernel = uniformkernel\n  );\n\n\nab_smc = runabc(ab_smc_setup,\n            Y,\n            verbose = true,\n            progress = true,\n            parallel = true);\n\n\nplot(ab_smc)\n\n", "meta": {"hexsha": "dba23238e5fb1719528164711808b6c6f9c9ef45", "size": 3507, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_abc/ode_abc.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 126, "max_stars_repo_stars_event_min_datetime": "2020-04-29T08:41:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:42:53.000Z", "max_issues_repo_path": "script/ode_abc/ode_abc.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2020-04-29T11:44:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:45:15.000Z", "max_forks_repo_path": "script/ode_abc/ode_abc.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2020-04-29T08:01:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T16:55:08.000Z", "avg_line_length": 19.5921787709, "max_line_length": 90, "alphanum_fraction": 0.6638152267, "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.779447249854325}}
{"text": "\"\"\"\n    angularspectrum(Uin, d, λ, lx, ly)\n\ncalculate the propagation light field based on the angular spectrum.\n\n## Arguments\n\n- `Uin::AbstractArray{<:Number,2}`: Complex array of input complex amplitude.\n- `d::Real`: Distance to propagate in metres.\n- `λ::Real`: Wavelength of light to propagate.\n- `lx::Real`: The physical size of the input data along the x-axis.\n- `ly::Real`: The physical size of the input data along the y-axis.\n\n## Returns\n\n- `::Array{<:Number,2}`: Complex amplitude data after propagation.\n\"\"\"\nfunction angularspectrum(Uin::AbstractArray{<:Number,2}, d::Real, λ::Real, lx::Real, ly::Real)\n    (n, m) = size(Uin)\n    ua = (-n/2:n/2-1)/lx*λ\n    va = (-m/2:m/2-1)/ly*λ\n    ifft(fft(Uin).*ifftshift([1.0-u^2-v^2>=0.0 ? exp(2im*pi*d/λ*sqrt(1.0-u^2-v^2)) : 0.0+0.0im for u in ua, v in va]))\nend\n\n\n\"\"\"\n    angularspectrum(Uin::MonoLightField2D, d::Unitful.Length) -> MonoLightField2D\n\ncalculate the propagation light field for [`MonoLightField2D`](@ref) based on the angular spectrum.\n\"\"\"\nfunction angularspectrum(Uin::MonoLightField2D, d::Unitful.Length)\n    Uout = angularspectrum(Uin.data, auval(d), auval(Uin.wavelength), auval(Uin.size[1]), auval(Uin.size[2]))\n    MonoLightField2D(Uin, data=Uout)\nend\n\n\"\"\"\n    angularspectrum(d)\n\nrepresent an [`angularspectrum`](@ref) propagation functor with the specified distance.\n\"\"\"\nangularspectrum(d) = x->angularspectrum(x, d)\n", "meta": {"hexsha": "287fe3fb19dbfea926ac83c93f558cdbced5cffa", "size": 1392, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/angularspectrum.jl", "max_stars_repo_name": "HIT-UOI-SR/LightPropagation.jl", "max_stars_repo_head_hexsha": "35d57f5e3698ff3498ae041b634a58b27f800725", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-11-21T14:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T15:49:38.000Z", "max_issues_repo_path": "src/angularspectrum.jl", "max_issues_repo_name": "HIT-UOI-SR/LightPropagation.jl", "max_issues_repo_head_hexsha": "35d57f5e3698ff3498ae041b634a58b27f800725", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-11-18T12:11:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-28T12:36:39.000Z", "max_forks_repo_path": "src/angularspectrum.jl", "max_forks_repo_name": "HIT-UOI-SR/LightPropagation.jl", "max_forks_repo_head_hexsha": "35d57f5e3698ff3498ae041b634a58b27f800725", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1428571429, "max_line_length": 118, "alphanum_fraction": 0.6882183908, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7794472494203031}}
{"text": "module InclusionsGenerator\n\nexport generate_inclusions\n\n# sphere volume\nvol(r) = 4/3*π*r^3\n\n# random inclusoin center\nnew_center(lx, ly, lz) = (rand()*lx, rand()*ly, rand()*lz)\n\n# 3D euclidean distance\ndistance(p1, p2) = sqrt((p1[1]-p2[1])^2 + (p1[2]-p2[2])^2 + (p1[3]-p2[3])^2)\n\n# check if the new inclusion collides with any pre-existent inclusion\nfunction sphere_collision(coords, new_coord, r; buffer = 0.2)\n    for c in coords\n        if distance(c, new_coord) ≤ 2*r*(1 + buffer)\n            return true\n        end\n    end\n\n    return false\nend\n\nfunction wall_collision(new_coord, r, lx, ly, lz; buffer = 0.2)\n    x, y, z = new_coord\n    buffer += 1\n    if (x ≤ r*buffer) || (x ≥ (lx - r*buffer))\n        return true\n\n    elseif (y ≤ r*buffer) || (y ≥ (ly - r*buffer))\n        return true\n    \n    elseif (z ≤ r*buffer) || (z ≥ (lz - r*buffer))\n        return true\n    end\n\n    return false\nend\n\nfunction generate_inclusions(lx, ly, lz, ϕ, r;  buffer_ball = 0.2, buffer_wall = 0.2)\n    # first sphere coordinate\n    coords = [new_center(lx, ly, lz)]\n\n    tot_vol = vol(r)\n    vol_fraction = tot_vol/(lx*ly*lz)\n\n    iter = 0\n    while vol_fraction ≤ ϕ\n        iter += 1\n        # temptative coordinate\n        new_coord = new_center(lx, ly, lz) \n        collision1 = sphere_collision(coords, new_coord, r; buffer=buffer_ball)\n        collision2 = wall_collision(new_coord, r, lx, ly, lz; buffer=buffer_wall)\n        if !collision1 && !collision2\n            push!(coords, new_coord)\n            tot_vol += vol(r)\n            vol_fraction = tot_vol/(lx*ly*lz)\n            iter = 0\n        end\n        if iter > 500\n            println(\"Forcing exit. Generator stalling\")\n            break\n        end\n    end\n\n    println(\"Done with $(length(coords)) inclusions and $(vol_fraction*100) % volume fraction.\")\n\n    return coords, vol_fraction\nend\n\nend # module\n", "meta": {"hexsha": "87b9afda43bc8fe333c75676ad7206b98a0cc947", "size": 1862, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/InclusionsGenerator.jl", "max_stars_repo_name": "albert-de-montserrat/BallsGen", "max_stars_repo_head_hexsha": "0a0f9fcf8103b8718de63a1e04f5007da18d7975", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/InclusionsGenerator.jl", "max_issues_repo_name": "albert-de-montserrat/BallsGen", "max_issues_repo_head_hexsha": "0a0f9fcf8103b8718de63a1e04f5007da18d7975", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/InclusionsGenerator.jl", "max_forks_repo_name": "albert-de-montserrat/BallsGen", "max_forks_repo_head_hexsha": "0a0f9fcf8103b8718de63a1e04f5007da18d7975", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5068493151, "max_line_length": 96, "alphanum_fraction": 0.597207304, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7794472489862809}}
{"text": "using Nemo \r\n\r\n# _Fast_ composed sums and composed products of polynomials,\r\n# using the algorithm described in: \r\n# \"Fast computation of special resultants\"\r\n# by Bostan, Flajolet, Salvy, and Schost\r\n\r\n# derivative of polynomial\r\nderivative(c::Vector) = c[2:end] .* (1:length(c)-1)\r\n\r\nfunction polyinv(coeffs::Vector, n)\r\n\tR, x = Nemo.PowerSeriesRing(Nemo.FlintQQ, n, \"x\")\r\n\ta = R(map(Nemo.FlintQQ, coeffs), length(coeffs), n, 0)\r\n\tai = inv(a)\r\n\treturn Nemo.fmpq[coeff(ai,i) for i=0:n-1]\r\nend\r\n\r\n# compute newton power series of polynomial given with coefficients coeff,\r\n# in base field R,x.\r\n# See fig.1 in reference\r\nfunction to_newton(coeffs::Vector{BigInt},n,R,x)\r\n\t# first, make monic.\r\n\tcoeffs = coeffs//coeffs[end]\r\n\r\n\td = length(coeffs)-1\r\n\ta_cfs = reverse(derivative(coeffs))\r\n\tb_cfs = reverse(coeffs)\r\n\t\r\n\t# initialize power series polynomials\r\n\ta = R(map(Nemo.FlintQQ, a_cfs))\r\n\tb = R(map(Nemo.FlintQQ, b_cfs))\r\n\tb0 = R(polyinv(b_cfs, n))\r\n\r\n\tc  = truncate(a*b0, d)\r\n\r\n\tr = R()\r\n\tx_power = R(1)\r\n\tx_d = x^d\r\n\r\n\tl = round(Int64,floor(n/d))\r\n\tfor j = 0 : l\r\n\t\tr += c*x_power\r\n\t\tx_power *= x_d\r\n\t\tc = -mullow(shift_right(b*c,d),b0,d)\r\n\tend\r\n\treturn r\r\nend\r\n\r\nto_array(p) = Rational{BigInt}[Rational(coeff(p,i)) for i=0:Nemo.degree(p)]\r\n\r\n# tr: traces i.e. newton series\r\n# This algorithm is based on the Leverrier-Faddeev algorithm\r\n# see: http://math.stackexchange.com/questions/405822/what-is-the-fastest-way-to-find-the-characteristic-polynomial-of-a-matrix\r\nfunction from_newton(tr::Vector{T}) where {T<:Number}\r\n\t# special case\r\n\tif tr==[1]\r\n\t\treturn [0,1]\r\n\tend\r\n\tn = length(tr)\r\n\tc = Array{T}(UndefInitializer(),n)\r\n\tc[end] = one(T)\r\n\tfor k = 1 : n-1\r\n\t\tnext_c = -sum(tr[2:(k+1)].*c[end-k+1:end])/k\r\n\t\tc[end-k] = next_c\r\n\tend\r\n\treturn c\r\nend \r\n\r\n# Hadamard (element-wise) product of two polynomials\r\nfunction hadm(p,q,R)\r\n\tn = max(Nemo.degree(p),Nemo.degree(q))\r\n\tR([Nemo.coeff(p,i)*Nemo.coeff(q,i) for i=0:n])\r\nend \r\n\r\n# composed product of two polynomials, given as coeffs p and q\r\nfunction composed_product(p::Vector{BigInt},q::Vector{BigInt})\r\n\t# compute newton series\r\n\tn = (length(p)-1)*(length(q)-1)+1\r\n\tR, x = Nemo.PolynomialRing(Nemo.FlintQQ, \"x\")\r\n\ta = to_newton(p,n,R,x)\r\n\tb = to_newton(q,n,R,x)\r\n\r\n\t# multiply newton series and invert\r\n\tpq = from_newton(to_array(hadm(a,b,R)))\r\n\r\n\t# convert to integer and return\r\n\treturn map(numerator, pq*lcm(map(denominator, pq)))\r\nend\r\n\r\n# composed sum of two polynomials, given as coeffs p and q\r\nfunction composed_sum(p::Vector{BigInt},q::Vector{BigInt})\r\n\t# compute newton series\r\n\tn = (length(p)-1)*(length(q)-1)+1\r\n\tR, x = Nemo.PolynomialRing(Nemo.FlintQQ, \"x\")\r\n\ta = to_newton(p,n,R,x)\r\n\tb = to_newton(q,n,R,x)\r\n\r\n\t# exp series \r\n\tee  = R([Nemo.FlintQQ(1//factorial(BigInt(i))) for i=0:(n-1)])\r\n\teei = R([Nemo.FlintQQ(   factorial(BigInt(i))) for i=0:(n-1)])\r\n\r\n\t# multiply newton series and invert\r\n\tm = truncate(hadm(a,ee,R)*hadm(b,ee,R),n)\r\n\tpq = from_newton(to_array(hadm(m,eei,R)))\r\n\r\n\t# convert to integer and return\r\n\treturn map(numerator, pq*lcm(map(denominator, pq)))\r\nend", "meta": {"hexsha": "e2d465d9356e29fca972d2e5a26e98cf634ceb68", "size": 3053, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/newton.jl", "max_stars_repo_name": "zenon/AlgebraicNumbers.jl", "max_stars_repo_head_hexsha": "09ff96705fb4c299b8a00780c96a1dec65387618", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/newton.jl", "max_issues_repo_name": "zenon/AlgebraicNumbers.jl", "max_issues_repo_head_hexsha": "09ff96705fb4c299b8a00780c96a1dec65387618", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/newton.jl", "max_forks_repo_name": "zenon/AlgebraicNumbers.jl", "max_forks_repo_head_hexsha": "09ff96705fb4c299b8a00780c96a1dec65387618", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2685185185, "max_line_length": 128, "alphanum_fraction": 0.6606616443, "num_tokens": 980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748209, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7793028620600206}}
{"text": "\"\"\"Julia program to implement Minimum XOR value.\nGiven an array of integers, we have to find the minimum XOR value, a pair in the array makes.\"\"\"\n\n\nfunction minimumXOR(arr, n)\n    # Sort the array, so that elements with minimum bit difference are present consecutive.\n    sort(arr)\n    minXOR = typemax(Int64)\n    val = 0\n\n    # Compute the XOR values of the consecutive elements of the array.\n    for i in 1:(n-1)\n        val = arr[i] ⊻ arr[i+1]\n        minXOR = min(minXOR, val)\n    end\n\n    return minXOR\nend\n\n\n\nprint(\"How many numbers are present in the array? \")\nn = readline()\nn = parse(Int, n)\nif (n <= 0)\n    println(\"No numbers are present in the array!!!\")\n    exit()\nend\narr = Int[]\nprint(\"Enter the numbers: \")\narr = [parse(Int, num) for num in split(readline())]\nres = minimumXOR(arr, n)\nprint(\"The minimum XOR value present in the given array is $res\")\n\n\n\"\"\"\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE I\n\nHow many numbers are present in the array? 8\nEnter the numbers: 25 45 36 458 651 89 52 95 \nThe minimum XOR value present in the given array is 9\n\nSAMPLE II\n\nHow many numbers are present in the array? 5\nEnter the numbers: 5 4 3 2 1\nThe minimum XOR value present in the given array is 1\n\n\"\"\"\n", "meta": {"hexsha": "3a7b285ac31028c85e1c3d13afde86d6e3d9d9f1", "size": 1198, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/Bit--Manipulation/minimum_xor_value.jl", "max_stars_repo_name": "Khushboo85277/NeoAlgo", "max_stars_repo_head_hexsha": "784d7b06c385336425ed951918d1ab37b854d29f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 897, "max_stars_repo_stars_event_min_datetime": "2020-06-25T00:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:49:31.000Z", "max_issues_repo_path": "Julia/Bit--Manipulation/minimum_xor_value.jl", "max_issues_repo_name": "adarshnjena/NeoAlgo", "max_issues_repo_head_hexsha": "77a92858d2bf970054ef31c2f55a6d79917a786a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5707, "max_issues_repo_issues_event_min_datetime": "2020-06-24T17:53:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T05:03:15.000Z", "max_forks_repo_path": "Julia/Bit--Manipulation/minimum_xor_value.jl", "max_forks_repo_name": "adarshnjena/NeoAlgo", "max_forks_repo_head_hexsha": "77a92858d2bf970054ef31c2f55a6d79917a786a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1817, "max_forks_repo_forks_event_min_datetime": "2020-06-25T03:51:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:14:07.000Z", "avg_line_length": 23.0384615385, "max_line_length": 96, "alphanum_fraction": 0.683639399, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8723473763375644, "lm_q1q2_score": 0.7792761215847945}}
{"text": "# ------------------------------------------------------------------- #\n# CES Producer\n# ------------------------------------------------------------------- #\nimmutable CESProducer <: AbstractProducer\n    η::Float64\n    ν::Float64\nend\n\n# call(p::CESProducer, k, l) = (p.η*k.^p.ν + (1-p.η)*l.^(p.ν)).^(1./p.ν)\nBase.produce(p::CESProducer, k, l) = (p.η*k.^p.ν + (1-p.η)*l.^(p.ν)).^(1./p.ν)\nf_k(p::CESProducer, k, l) = p.η * (produce(p, k, l) ./ k).^(1.-p.ν)\n\n# ------------------------------------------------------------------- #\n# Cobb-Douglas Producer\n# ------------------------------------------------------------------- #\nimmutable CobbDouglassProducer <: AbstractProducer\n    α_k::Float64\n    α_l::Float64\nend\n\nis_crs(i::CobbDouglassProducer) = i.α_k == 1. - i.α_l\n", "meta": {"hexsha": "80235894b1b6904cba5b67b09b96fe5bdf1980dc", "size": 769, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Models/MA_Producers.jl", "max_stars_repo_name": "NYUEcon/GrowthModels", "max_stars_repo_head_hexsha": "463ceafc5749475340e367074f3eaf6248668eaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-08-19T23:28:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-25T11:07:10.000Z", "max_issues_repo_path": "Models/MA_Producers.jl", "max_issues_repo_name": "NYUEcon/GrowthModels", "max_issues_repo_head_hexsha": "463ceafc5749475340e367074f3eaf6248668eaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-08-18T20:18:34.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-20T17:21:15.000Z", "max_forks_repo_path": "Models/MA_Producers.jl", "max_forks_repo_name": "NYUEcon/GrowthModels", "max_forks_repo_head_hexsha": "463ceafc5749475340e367074f3eaf6248668eaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-11-09T18:43:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:49:32.000Z", "avg_line_length": 34.9545454545, "max_line_length": 78, "alphanum_fraction": 0.3810143043, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399051935107, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7792712748878974}}
{"text": "struct ShamirSecretSharing\n    prime::BigInt\nend\n\nShamirSecretSharing() = ShamirSecretSharing(BigInt(2)^127 - 1)\n\n\"\"\"\nn is the number of shares.\nk is the threshold.\n\n\"\"\"\nfunction Base.split(scheme::ShamirSecretSharing, secret::BigInt, n::Int64, k::Int64)\n    prime = scheme.prime\n    polynomial = [secret]\n    for i in 2:k\n        push!(polynomial, rand(RandomDevice(), 0:(prime-1)))\n    end\n\n    points = []\n    for i in 1:n\n        push!(points, (i, eval_poly(polynomial, i, prime)))\n    end\n    return points\nend\n\nfunction Base.join(scheme::ShamirSecretSharing, points)\n    prime = scheme.prime\n    xs, ys = zip(points...)\n    return lagrange_interpolate(0, [xs...], [ys...], prime)\nend\n", "meta": {"hexsha": "c53bc75840dc0bfebc16eba02ab2195bfeb5d831", "size": 690, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SecretSharing.jl", "max_stars_repo_name": "Maelstrom6/CryptoTools.jl", "max_stars_repo_head_hexsha": "2a13daddd2342e16cfd65ad4bab83156e0ef0ceb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SecretSharing.jl", "max_issues_repo_name": "Maelstrom6/CryptoTools.jl", "max_issues_repo_head_hexsha": "2a13daddd2342e16cfd65ad4bab83156e0ef0ceb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SecretSharing.jl", "max_forks_repo_name": "Maelstrom6/CryptoTools.jl", "max_forks_repo_head_hexsha": "2a13daddd2342e16cfd65ad4bab83156e0ef0ceb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2580645161, "max_line_length": 84, "alphanum_fraction": 0.6550724638, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214521983691, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7792365510757234}}
{"text": "# https://juliasmoothoptimizers.github.io/ADNLPModels.jl/stable/tutorial/\n\nusing ADNLPModels\nusing NLPModelsIpopt\n\nf(x) = (x[1] - 1)^2 + 100*(x[2] - x[1]^2)^2\n\nx0 = [-1.2; 1.0]\nuvar = [10.0; 10.0]\nlvar = [-10.0; -10.0]\n\nc(x) = [x[1]^2 + x[2]^2; x[1]*x[2]]\nucon = [0.75; 0.3]\nlcon = [0.0; 0.0]\n\nnlp = ADNLPModel(f, x0, lvar, uvar, c, lcon, ucon)\n\n#output = ipopt(nlp, print_level=0)\noutput = ipopt(nlp)\n\nprintln(output.objective)\nprintln(output.solution)\n", "meta": {"hexsha": "49644a68b920f02ff70de8b1a67153394f66b3b2", "size": 454, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "debug/nlpmodels-mwe.jl", "max_stars_repo_name": "lanl-ansi/rosetta-opf", "max_stars_repo_head_hexsha": "09e76f505c04cc788256a4f3f479033ba6abe1f0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2022-03-25T19:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:42:04.000Z", "max_issues_repo_path": "debug/nlpmodels-mwe.jl", "max_issues_repo_name": "lanl-ansi/rosetta-opf", "max_issues_repo_head_hexsha": "09e76f505c04cc788256a4f3f479033ba6abe1f0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2022-03-28T01:10:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:44:10.000Z", "max_forks_repo_path": "debug/nlpmodels-mwe.jl", "max_forks_repo_name": "lanl-ansi/rosetta-opf", "max_forks_repo_head_hexsha": "09e76f505c04cc788256a4f3f479033ba6abe1f0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7391304348, "max_line_length": 73, "alphanum_fraction": 0.6211453744, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.964321450147636, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7792365449613269}}
{"text": "function Green(xr,xz,yr,yz; derivative=0)\n    #= \n    Fundamental solution (Green function) and derivatives of the Grad-Shafranov Delta^* operator\n    -Delta_x^* G(x,y)=delta(x-y)\n    y=(yr,yz) is the source point (a filament with unit current)\n    x=(xr,xz) is the evaluation point\n    Derivatives from Itagaki, Engineering Analysis with Boundary Elements, 33 (2009) 845-857\n    \n    derivative=0 only Green function value\n    derivative=1 + gradient wrt to x and y\n    derivative=2 + second order cross derivatives (see return outputs below)\n    =#\n    \n    mu0=4*pi*10^-7\n    #modulus at points x and y\n    k_xy=sqrt(4*xr*yr/((xr+yr)^2+(xz-yz)^2))\n    \n    #Complete elliptic integrals of first and second kind\n    K_xy,E_xy=Elliptic.ellipke(k_xy^2)\n    \n    #Green function\n    G_xy = (mu0/pi*((xr*yr)^(1/2))/k_xy)*((1-0.5*k_xy^2)*K_xy - E_xy)\n    \n    \n    #println(\"derivative=\",derivative)\n    \n    if(derivative==0)\n        return (G_xy=G_xy,)\n        #return G_xy\n    end\n       \n    if(derivative>0)\n        # gradient with respect to y\n        dyrG_xy = (mu0/(2*pi))*((yr   )/(sqrt( (xr+yr)^2 + (xz-yz)^2 )))*(K_xy - ((yr^2-xr^2+(xz-yz)^2 )/( (xr-yr)^2 + (xz-yz)^2))*E_xy)\n        dyzG_xy = (mu0/(2*pi))*((yz-xz)/(sqrt( (xr+yr)^2 + (xz-yz)^2 )))*(K_xy - ((yr^2+xr^2+(xz-yz)^2 )/( (xr-yr)^2 + (xz-yz)^2))*E_xy)\n    \n        # gradient with respect to x\n        dxrG_xy = (mu0/(2*pi))*((xr   )/(sqrt( (xr+yr)^2 + (xz-yz)^2 )))*(K_xy - ((xr^2-yr^2+(xz-yz)^2 )/( (xr-yr)^2 + (xz-yz)^2))*E_xy)\n        dxzG_xy = (mu0/(2*pi))*((xz-yz)/(sqrt( (xr+yr)^2 + (xz-yz)^2 )))*(K_xy - ((xr^2+yr^2+(xz-yz)^2 )/( (xr-yr)^2 + (xz-yz)^2))*E_xy)\n        \n        if(derivative==1)\n            #return G_xy, dyrG_xy, dyzG_xy, dxrG_xy, dxzG_xy\n            return (G_xy=G_xy, dyrG_xy=dyrG_xy, dyzG_xy=dyzG_xy, dxrG_xy=dxrG_xy, dxzG_xy=dxzG_xy)\n        end\n        \n    end\n    \n    if(derivative==2)\n    \n        # second order cross derivatives\n        dxrdyrG_xy = -((xr+yr)/((xr+yr)^2+(xz-yz)^2))*dxrG_xy + \n            (mu0/2*pi)*xr*(1/((xr+yr)^2+(xz-yz)^2)^(1/2))*(1/((xr-yr)^2+(xz-yz)^2))*\n            ( ((xr^2-yr^2+(xz-yz)^2)/((xr+yr)^2+(xz-yz)^2))*((xr-yr)*K_xy+(xr+yr)*E_xy) -2*xr*E_xy + ((4*yr*(xz-yz)^2)/((xr-yr)^2+(xz-yz)^2))*E_xy )\n    \n        dxzdyrG_xy = -((xr+yr)/((xr+yr)^2+(xz-yz)^2))*dxzG_xy + \n            (mu0/2*pi)*xr*(xz-yz)*(1/((xr-yr)^2+(xz-yz)^2)^(1/2))*(1/((xr-yr)^2+(xz-yz)^2))*\n            ( ((xr^2-yr^2+(xz-yz)^2)/((xr+yr)^2+(xz-yz)^2))*(K_xy+E_xy) -2*E_xy - ((4*yr*(xr-yr))/((xr-yr)^2+(xz-yz)^2))*E_xy )\n    \n        dxrdyzG_xy = ((xz-yz)/((xr+yr)^2+(xz-yz)^2))*dxrG_xy +\n            (mu0/pi)*yr*xr*(xz-yz)*\n            (1/((xr+yr)^2+(xz-yz)^2)^(1/2))*(1/((xr-yr)^2+(xz-yz)^2))*\n            ( (1/((xr+yr)^2+(xz-yz)^2))*((xr-yr)*K_xy+(xr+yr)*E_xy) +\n            ((-2*(xr-yr))/((xr-yr)^2+(xz-yz)^2))*E_xy )\n    \n        dxzdyzG_xy = (((-1)/(xz-yz))+((xz-yz)/((xr+yr)^2+(xz-yz)^2)))*dxzG_xy +\n            (mu0/pi)*yr*xr*(xz-yz)^2 *\n            (1/((xr+yr)^2+(xz-yz)^2)^(1/2))*(1/((xr-yr)^2+(xz-yz)^2))*\n            ( (1/((xr+yr)^2+(xz-yz)^2))*(K_xy+E_xy) +\n            (-2/((xr-yr)^2+(xz-yz)^2))*E_xy )\n    \n        #return G_xy, dyrG_xy, dyzG_xy, dxrG_xy, dxzG_xy, dxrdyrG_xy, dxzdyrG_xy, dxrdyzG_xy, dxzdyzG_xy\n        return (G_xy=G_xy, dyrG_xy=dyrG_xy, dyzG_xy=dyzG_xy, dxrG_xy=dxrG_xy, dxzG_xy=dxzG_xy, dxrdyrG_xy=dxrdyrG_xy, dxzdyrG_xy=dxzdyrG_xy, dxrdyzG_xy=dxrdyzG_xy, dxzdyzG_xy=dxzdyzG_xy)\n    end\n\nend\n", "meta": {"hexsha": "a6a4b2e177fd905a3e2aebda55959a22eaffc9e9", "size": 3430, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/green.jl", "max_stars_repo_name": "blaise-faugeras/VacBEM.jl", "max_stars_repo_head_hexsha": "afa3c3e26b482a2749806a756f62e17a52f520dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/green.jl", "max_issues_repo_name": "blaise-faugeras/VacBEM.jl", "max_issues_repo_head_hexsha": "afa3c3e26b482a2749806a756f62e17a52f520dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/green.jl", "max_forks_repo_name": "blaise-faugeras/VacBEM.jl", "max_forks_repo_head_hexsha": "afa3c3e26b482a2749806a756f62e17a52f520dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.1315789474, "max_line_length": 186, "alphanum_fraction": 0.5239067055, "num_tokens": 1474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214470715363, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7792365447042648}}
{"text": "# This function implements Kalman Filter on a state-space model of the form:\n# α_{t} = T * α_{t-1} + η_{t}\n# y_{t} = Z * α_{t} + ϵ_{t}\n# E[η_{t}η'_{t}] = Q, E[ϵ_{t}ϵ'_{t}] = H\n\nfunction KalmanFilter(T::Matrix, Z::Matrix, Q::Matrix, H::Matrix, n::Integer, α0, y)\n    \n    # Initialize state variables\n    αhat = repeat([zeros(size(α0))], n);\n    αhat[1] = T*α0;\n\n    yhat = repeat([zeros(size(y[1]))], n);\n    v = copy(yhat);\n\n    P0 = Q * Q;\n    d = 10;\n    tol = 10^(-8);\n    maxiter = 1000;\n    iter = 1;\n    while d > tol && iter <= maxiter\n        P1 = T * P0 * T' + Q;\n        d = maximum(abs.(P0 - P1));\n        P0 = P1;\n        iter = iter + 1;\n    end\n    \n    P = repeat([zeros(size(Q))], n);\n    P[1] = T * P0 * T' + Q;\n\n    F = repeat([zeros(size(H))], n)\n    G = repeat([zeros(size(Z * Q))], n)\n    K = repeat([zeros(size(T * G[1]' * ones(size(H))))], n)\n\n    for i in 1:n-1\n        yhat[i] = Z * αhat[i];\n        v[i] = y[i] - yhat[i];\n\n        F[i] = Z * P[i] * Z' + H;\n        G[i] = Z * P[i];\n        K[i] = T * G[i]' * inv(F[i]);\n\n        αhat[i + 1] = T * αhat[i] + K[i] * v[i];\n        P[i + 1] = T * (P[i] - G[i]' * inv(F[i]) * G[i]) * T' + Q;\n    end\n\n    yhat[n] = Z * αhat[n];\n    v[n] = y[n] - yhat[n];\n    \n    F[n] = Z * P[n] * Z' + H;\n    G[n] = Z * P[n];\n    K[n] = T * G[n]' * inv(F[n]);\n\n    return αhat, v, yhat, P, F, G, K\nend\n\n\n\n", "meta": {"hexsha": "6263184cfaff4db19f711f33d2c319291e181fa4", "size": 1362, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Ellen/HW3/KalmanFilter.jl", "max_stars_repo_name": "wongr003/ECON8185", "max_stars_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ellen/HW3/KalmanFilter.jl", "max_issues_repo_name": "wongr003/ECON8185", "max_issues_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ellen/HW3/KalmanFilter.jl", "max_forks_repo_name": "wongr003/ECON8185", "max_forks_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4827586207, "max_line_length": 84, "alphanum_fraction": 0.419236417, "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068041, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7792356262225616}}
{"text": "# A tolerance graph is a graph whose vertices are represented by pairs\n# (J,t) where J is a closed interval and t is a real number. Vertices\n# are adjacent if and only if length(J * JJ) >= min(t,tt).\n\nexport ToleranceGraph\n\n\"\"\"\n`ToleranceGraph(Jlist, tlist)` creates a tolerance graph where `Jlist`\nis a list of intervals and `tlist` is a list of tolerances.\n\"\"\"\nfunction ToleranceGraph(\n    Jlist::Vector{ClosedInterval{S}},\n    tlist::Vector{T},\n) where {S<:Real,T<:Real}\n    n = length(Jlist)\n    G = IntGraph(n)\n\n    for i = 1:n-1\n        J = Jlist[i]\n        t = tlist[i]\n        for j = i+1:n\n            JJ = Jlist[j]\n            tt = tlist[j]\n\n            K = J * JJ\n            if !isempty(K) && length(K) >= min(t, tt)\n                add!(G, i, j)\n            end\n        end\n    end\n    return G\nend\n\n\"\"\"\n`ToleranceGraph(f)` creates a tolerance graph where `f` is a `Dict`\nmapping vertices to pairs `(J,t)` where `J` is a `ClosedInterval` and\n`t` is a `Real` tolerance.\n\"\"\"\nfunction ToleranceGraph(f::Dict{X,Tuple{ClosedInterval{S},T}}) where {S<:Real,T<:Real,X}\n    vtcs = collect(keys(f))\n    G = SimpleGraph{X}()\n    for v in vtcs\n        add!(G, v)\n    end\n\n    n = length(vtcs)\n    for i = 1:n-1\n        v = vtcs[i]\n        J, t = f[v]\n        for j = i+1:n\n            w = vtcs[j]\n            JJ, tt = f[w]\n\n            K = J * JJ\n            if !isempty(K) && length(K) >= min(t, tt)\n                add!(G, v, w)\n            end\n        end\n    end\n    return G\nend\n", "meta": {"hexsha": "39d297762c4b4efbb72d8d4a0537d11d62fc787a", "size": 1486, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ToleranceGraphs.jl", "max_stars_repo_name": "scheinerman/SimpleGraphRepresentations.jl", "max_stars_repo_head_hexsha": "815367c0a545ef60e49f8b26944770f50b42a407", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ToleranceGraphs.jl", "max_issues_repo_name": "scheinerman/SimpleGraphRepresentations.jl", "max_issues_repo_head_hexsha": "815367c0a545ef60e49f8b26944770f50b42a407", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ToleranceGraphs.jl", "max_forks_repo_name": "scheinerman/SimpleGraphRepresentations.jl", "max_forks_repo_head_hexsha": "815367c0a545ef60e49f8b26944770f50b42a407", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:13:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T01:13:04.000Z", "avg_line_length": 23.9677419355, "max_line_length": 88, "alphanum_fraction": 0.5289367429, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7791814311127477}}
{"text": "# calculate varianve of sensor data\n\nmodule CalcVariance\n    using DataFrames, CSV, Statistics\n\n    function main()\n        data_path = joinpath(split(@__FILE__, \"src\")[1], \"data/sensor_data_200.txt\")\n        df_200_mm = CSV.read(data_path, DataFrame, \n                             header=[\"date\", \"time\", \"ir\", \"lidar\"],\n                             delim=' ')\n        \n        # calculate from definition\n        zs = df_200_mm.lidar # observation\n        mean_def = sum(zs) / length(zs) # mean\n        diff_square = [(z - mean_def)^2 for z in zs]\n        \n        sampling_var = sum(diff_square) / length(zs) # sampling variance\n        unbiased_var = sum(diff_square) / (length(zs) - 1) # unbiased variance\n\n        println(\"Sampling Variance = $sampling_var\")\n        println(\"Unbiased Variance = $unbiased_var\")\n\n        # calculate by Statistics\n        stats_sampling_var = Statistics.var(zs, corrected=false)\n        stats_unbiased_var = Statistics.var(zs, corrected=true)\n\n        println(\"Sampling Variance by Statistics = $stats_sampling_var\")\n        println(\"Unbiased Variance by Statistics = $stats_unbiased_var\")\n    end\nend", "meta": {"hexsha": "e8f32a7532039cc6aa234b81cf9f417a93d05023", "size": 1140, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/prob_stats/freq_dist/variance/calc_variance.jl", "max_stars_repo_name": "ShisatoYano/JuliaAutonomy", "max_stars_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2021-03-10T12:43:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T16:40:19.000Z", "max_issues_repo_path": "src/prob_stats/freq_dist/variance/calc_variance.jl", "max_issues_repo_name": "ShisatoYano/JuliaAutonomy", "max_issues_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/prob_stats/freq_dist/variance/calc_variance.jl", "max_forks_repo_name": "ShisatoYano/JuliaAutonomy", "max_forks_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-14T02:46:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T09:19:40.000Z", "avg_line_length": 38.0, "max_line_length": 84, "alphanum_fraction": 0.6175438596, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996141, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7791814304545958}}
{"text": "# Linear Isotropic Covariance Function\n\n@doc \"\"\"\n# Description\nConstructor for the isotropic linear kernel (covariance)\n\nk(x,x') = xᵀx'/ℓ²\n# Arguments:\n* `ll::Float64`: Log of the length scale ℓ\n\"\"\" ->\ntype LinIso <: Kernel\n    ll::Float64      # Log of Length scale \n    LinIso(ll::Float64) = new(ll)\nend\n\nfunction cov(lin::LinIso, x::Vector{Float64}, y::Vector{Float64})\n    ell = exp(lin.ll)\n    K = dot(x,y)/ell^2\n    return K\nend\n\nfunction cov(lin::LinIso, X::Matrix{Float64}, data::EmptyData)\n    ell = exp(lin.ll)\n    return ((1/ell^2).*X') * X\nend\n\nget_params(lin::LinIso) = Float64[lin.ll]\nget_param_names(lin::LinIso) = [:ll]\nnum_params(lin::LinIso) = 1\n\nfunction set_params!(lin::LinIso, hyp::Vector{Float64})\n    length(hyp) == 1 || throw(ArgumentError(\"Linear isotropic kernel only has one parameter\"))\n    lin.ll = hyp[1]\nend\n\nfunction grad_kern(lin::LinIso, x::Vector{Float64}, y::Vector{Float64})\n    ell = exp(lin.ll)\n    \n    dK_ell = -2.0*dot(x,y)/ell^2\n    dK_theta = [dK_ell]\n    return dK_theta\nend\n\nfunction grad_stack!(stack::AbstractArray, lin::LinIso, X::Matrix{Float64}, data::EmptyData)\n    ell = exp(lin.ll)\n    stack[:,:,1] = ((-2.0/ell^2).*X') * X\nend\n", "meta": {"hexsha": "1485f0dde2e2545effd1e7007f56794d13149d6e", "size": 1183, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/lin_iso.jl", "max_stars_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/lin_iso.jl", "max_issues_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/lin_iso.jl", "max_forks_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6458333333, "max_line_length": 94, "alphanum_fraction": 0.6517328825, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506726044381, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7791814284238257}}
{"text": "function CholeskyL(A::Array)\r\n\r\n  #A = the matrix of coefficients 'A' must be squared\r\n\r\n    m,n =size(A)\r\n\r\n    if m != n\r\n        error(\"Matrix must be squared\")\r\n    end\r\n\r\n    # System of equations\r\n    L=zeros(m,m)\r\n\r\n    L[1,1]=A[1,1]^0.5\r\n\r\n    for k=2:m\r\n\r\n    for i=1:k-1\r\n       L[k,i]=(A[k,i]-(L[i,1:i-1]'*L[k,1:i-1]))/(L[i,i])\r\n\r\n    end\r\n          L[k,k]=(A[k,k]-(L[k,1:k-1]'*L[k,1:k-1]))^0.5\r\n    end\r\n\r\n\r\n\r\n    return L\r\n\r\nend\r\n", "meta": {"hexsha": "fdc8b3bc07df36085aec3ea089bda7b0e52bbb91", "size": 443, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Cholesky.jl", "max_stars_repo_name": "scuervo91/LinearSolvers.jl", "max_stars_repo_head_hexsha": "471102b870dde6cb4c3b80c976381db31198faaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Cholesky.jl", "max_issues_repo_name": "scuervo91/LinearSolvers.jl", "max_issues_repo_head_hexsha": "471102b870dde6cb4c3b80c976381db31198faaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Cholesky.jl", "max_forks_repo_name": "scuervo91/LinearSolvers.jl", "max_forks_repo_head_hexsha": "471102b870dde6cb4c3b80c976381db31198faaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.7666666667, "max_line_length": 57, "alphanum_fraction": 0.4469525959, "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697694, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7791814217484491}}
{"text": "module FeynmanKleinert\n\n# Bring out the major leagues... https://www.youtube.com/watch?v=_E6DDktoPhg\nusing Optim\n\nusing QuadGK # For numerical integration\n\nexport K,Va2,Wtilde,verboseWtilde,W # export all the things.\n\n\"Integrand of (4) in Feynman and Kleinert\"\nK(xp,x,a2,V)=1/sqrt(2*π*a2)*exp(-(x-xp)^2/(2*a2))*V(xp)\n\"(4) in Feynman and Kleinert\"\nVa2(x,a2,V)=quadgk(xp->K(xp,x,a2,V), -Inf, +Inf) #, reltol=0, abstol=1e-5)\n\n# (5) naively as written, in Feynman and Kleinert\n#Wtilde(x0,a2,Ω,g,β)=(1/β) * log( sinh(β*Ω/2)/(β*Ω/2) ) - (Ω^2/2) * a2 + Va2(x0,a2,g)[1]\n# Large β limit; by taking sinh(x)=e^x-e^-x , and then dropping e^-x\n#Wtilde(x0,a2,Ω,g,β)=(1/β) * (β*Ω/2 - log(β*Ω/2)) - (Ω^2/2) * a2 + Va2(x0,a2,g)[1]\n\n# Branch depending on β; for accuracy + lack of infinities\n\"\"\"\n    Wtilde(x0,a2,Ω,V,β)\n\n(5) in Feynman and Kleinert. Switches depending on D=β*Ω/2 to use either an\nexponential approximation for sinh(x) (D>7.5) or an explicit evaluation and\nthen take logarithms. Without doing this you get collapse to infinity for large\nβ.  \n\"\"\"\nfunction Wtilde(x0,a2,Ω,V,β)\n    D=β*Ω/2\n    if D>7.5\n        F=(1/β) * (D - log(2*D)) # Large limit;  by taking sinh(x)=e^x-e^-x , and then dropping e^-x\n    else\n        F=(1/β)*( log(sinh(D)/D) ) # explicit evaluation, naively as written in (5)\n    end\n    V0=Va2(x0,a2,V)[1]\n    mid=(Ω^2/2) * a2\n    return F-mid+V0\nend\n\n\"\"\"\n   verboseWtilde(x0,a2,Ω,g,β)\n\nExpanded version of Wtilde, reporting the decomposition - this was used to explain what was going wrong\n\"\"\"\nfunction verboseWtilde(x0,a2,Ω,g,β)\n    D=β*Ω/2\n    println(\"D=β*Ω/2 = $D\")\n    F= (1/β)*( log(sinh(D)) - log(D) )\n    #F= (1/β)*( (log(2D)+D^2/6+D^4/180) - log(D) ) # generalised Puiseux series\n    # Large D limit, through sinh(D) --> e^D [through away e^-D part]\n    F = (1/β) * (D - log(2*D))\n    V=Va2(x0,a2,g)[1]\n    mid=(Ω^2/2) * a2\n    println(\"Wtilde(x0=$x0,a2=$a2,Ω=$Ω,g=$g,β=$β) \\n\\t= F - mid + V\")\n    println(\"\\t= $F - $mid + $V = \",F-mid+V)\n    return F-mid+V\nend\n\n\"\"\"\n    W(x0,g,β)\n\n    Implementing optimisation / minimisation described in Feynman-Kleinert (6)\n    Calculates optimal W for x0, with given g and Beta\n    Use's (7) (a2 in terms of omega) to fix numerical noise from trying to do\n    it directly...  \n\"\"\"\nfunction W(x0,g,β)\n    #println(\"W(x0=$x0,g=$g,β=$β)\")\n    \n    a2(Ω)=1/(β*Ω^2)*( (β*Ω)/2 * coth(β*Ω/2)-1 ) #(7)\n    myf(x)=Wtilde(x0,a2(x[1]),x[1],g,β)\n\n    # Define bounds on solution\n    lower=[0.0]\n    upper=[5.0]\n    initial=[1.0]\n    \n    res=optimize(OnceDifferentiable(myf, initial; autodiff = :forward), initial, lower, upper, Fminbox(); \n    optimizer=GradientDescent)\n\n    minimum=Optim.minimum(res)\n    Ω=Optim.minimizer(res)[1]\n    mya2=a2(Ω)[1]\n    #println(\"Optimised for W(x0=$x0,g=$g,β=$β). \\n\\tΩ=$Ω, a2=$mya2, minimum=$minimum.\")\n    #show(res)\n    return minimum\nend\n\n\nend # module\n\n", "meta": {"hexsha": "367fa76525654c7ed98d58eb676966c0cd0f456c", "size": 2848, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FeynmanKleinert.jl", "max_stars_repo_name": "jarvist/Feynman-Kleinert-1986-PRA", "max_stars_repo_head_hexsha": "b07c9343ab3fa62423d54083cd7bd8c07178d816", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-07-02T18:36:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-22T18:23:45.000Z", "max_issues_repo_path": "src/FeynmanKleinert.jl", "max_issues_repo_name": "jarvist/Feynman-Kleinert-1986-PRA", "max_issues_repo_head_hexsha": "b07c9343ab3fa62423d54083cd7bd8c07178d816", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FeynmanKleinert.jl", "max_forks_repo_name": "jarvist/Feynman-Kleinert-1986-PRA", "max_forks_repo_head_hexsha": "b07c9343ab3fa62423d54083cd7bd8c07178d816", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.623655914, "max_line_length": 106, "alphanum_fraction": 0.6099016854, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145365, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7791814217296776}}
{"text": "# A comparison between ℓ_0 and ℓ_1 trend filtering\n\nusing Plots\nusing Convex\nusing Mosek\nusing EllZeroTrendFiltering\n\ng = snp500_data()[1:300]\n\n\nN = length(g)\n\n\n## ℓ_1 trend filtering, see \"ℓ_1 Trend Filtering\", Kim et al. (2009)\nH =  spdiagm(0=>ones(N-2), 1=>-2*ones(N-2), 2=>ones(N-2))\n\nx = Variable(N)\n\nλ = 2.0\nproblem = minimize(sumsquares(x - g) + λ * norm(H*x, 1))\n\nsolve!(problem, Mosek.Optimizer)\n#solve!(problem, SCS.Optimizer)\nprintln(problem.status)\n\nx_l1 = evaluate(x)[:]\nf_l1 = sum((x_l1 - g).^2)\n\n\n## ℓ_0 trend filtering\nζ = 0.02\nI_l0, Y_l0, f_l0 = fit_pwl_regularized(g, ζ)\n\n\n\nplot(g, label=\"SP500\", size=(1000,550));\nplot!(x_l1, lw=2.5, label=\"l1 reg. lambda = $λ\");\nplot!(I_l0, Y_l0, lw=2.5, label=\"l0 reg. zeta = $ζ\")\n\n# plot(H*x.value);\n# plot!(I_l0[2:end], 0.1*diff(Y_l0) ./ diff(I_l0), m=:o, lw=0)\n#\n", "meta": {"hexsha": "31402537d52043158c4a6118f8a16425883e4672", "size": 821, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example4.jl", "max_stars_repo_name": "mfalt/EllZeroTrendFiltering.jl", "max_stars_repo_head_hexsha": "1b4d100df8404d342ec682ba4f796de1cdd267c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2018-03-07T09:16:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T02:29:00.000Z", "max_issues_repo_path": "examples/example4.jl", "max_issues_repo_name": "mfalt/EllZeroTrendFiltering.jl", "max_issues_repo_head_hexsha": "1b4d100df8404d342ec682ba4f796de1cdd267c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-06-05T16:39:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-23T10:08:46.000Z", "max_forks_repo_path": "examples/example4.jl", "max_forks_repo_name": "mfalt/EllZeroTrendFiltering.jl", "max_forks_repo_head_hexsha": "1b4d100df8404d342ec682ba4f796de1cdd267c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-23T00:17:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T00:17:46.000Z", "avg_line_length": 19.0930232558, "max_line_length": 68, "alphanum_fraction": 0.6455542022, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7791814203946023}}
{"text": "# Generate random unitaries and density matrices for testing\n\nexport random_unitary, random_densitymatrix\n\n\"\"\" `U = random_unitary(dim, real=true/false, complex=true/false)`\n\nGenerate a random unitary of dimension *dim*. Depending on *real* and *complex* the matrix has real and complex parts.\n\n\"\"\"\n\nfunction random_unitary(dim::Integer; real::Bool = true, complex::Bool = false)\n\n  \t@assert dim > 1 \"Dimension must be at least 2.\"\n\n  \tgenerated = randn(dim, dim)\n\n  \tif complex || !real\n    \t\tgenerated += im * randn(dim, dim)\n  \tend\n\n\t# Compute the QR decomposition\n  \t(Q, R) = qr(generated)\n\n\t# Get the upper diagonal part of R\n  \tF = diagm(diag(R))\n\n  \tR = sign(diagm(diag(R)))\n  \tR[find((x)->  x == 0, R)] = 1\n  \tF = diagm(diag(R))\n\n  \treturn Q*F\nend\n\n\"\"\" `rho = random_densitymatrix(dim)`\n\nGenerate a random density matrix in dimension *dim*.\n\n\"\"\"\n\nfunction random_densitymatrix(dim::Integer)\n \n\t@assert dim > 1 \"Dimension must be at least 2.\"\n\n        # Draw random numbers\n\trList = rand(dim);\n\n\t# Normalize to form a distribution\n\ts = sum(rList);\n\tnList = rList/s;\n\t\n\t# Construct a matrix with the numbers on the diagonal\n\tM = diagm(nList);\n\n\t# Draw a random unitary\n   \tU = random_unitary(dim, real = true, complex = true)\n\n\t# Roate the diagonal matrix\n\treturn(U*M*U');\nend\n", "meta": {"hexsha": "82ce037eb1764e8039efd4b36e04be7a552a0b61", "size": 1283, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "build/random.jl", "max_stars_repo_name": "StephanieWehner/EntanglementDist.jl", "max_stars_repo_head_hexsha": "38918843ac6866d072185e1ee9bf411c406aed48", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-07T15:10:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T15:10:32.000Z", "max_issues_repo_path": "build/random.jl", "max_issues_repo_name": "StephanieWehner/EntanglementDist.jl", "max_issues_repo_head_hexsha": "38918843ac6866d072185e1ee9bf411c406aed48", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/random.jl", "max_forks_repo_name": "StephanieWehner/EntanglementDist.jl", "max_forks_repo_head_hexsha": "38918843ac6866d072185e1ee9bf411c406aed48", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-06-12T13:33:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T18:42:48.000Z", "avg_line_length": 21.3833333333, "max_line_length": 118, "alphanum_fraction": 0.6718628215, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506726044381, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7791814183638317}}
{"text": "# All matrices are DxN, where N is the number of positions and D is the dimensionality\n\n# Here, P is the probe (to be rotated) and Q is the refereence\n# https://en.wikipedia.org/wiki/Kabsch_algorithm\n# This has been generalized to support weighted points:\n# https://igl.ethz.ch/projects/ARAP/svd_rot.pdf\n\n# assuming P and Q are already centered at the origin\n# returns the rotation for alignment\nfunction kabsch_centered(P,Q,w)\n    @assert size(P) == size(Q)\n    W = diagm(w/sum(w)) # here, the weights are assumed to sum to 1\n    H = P*W*Q'\n    D = Matrix{Float64}(I,size(H,1), size(H,2))\n    U,Σ,V = svd(H)\n    D[end] = sign(det(V*U'))\n    return LinearMap(V * D * U')\nend\n\n# transform DxN matrices\nfunction (tform::Translation)(A::AbstractMatrix)\n    return hcat([tform(A[:,i]) for i=1:size(A,2)]...)\nend\n\n# P and Q are not necessarily centered\n# returns the transformation for alignment\nfunction kabsch(P, Q, w::AbstractVector=ones(size(P,2)))\n    @assert !any(w.<0) && sum(w)>0\n    wn = w/sum(w) # weights should sum to 1 for computing the centroid\n    centerP, centerQ = center_translation(P,wn), center_translation(Q,wn)\n    R = kabsch_centered(centerP(P), centerQ(Q), wn)\n    return inv(centerQ) ∘ R ∘ centerP\nend\n\nfunction kabsch(P,Q,matches::AbstractVector{<:Tuple{Int,Int}},wp=ones(size(P,2)),wq=ones(size(Q,2)))\n    matchedP, matchedQ = matched_points(P,Q,matches)\n    w = [wp[i]*wq[j] for (i,j) in matches]\n    return kabsch(matchedP, matchedQ, w)\nend\n\n# centroid of positions in A, weighted by weights in w (assumed to sum to 1)\ncentroid(A, w=fill(1/size(A,2), size(A,2))) = A*w\n\n# translation moving centroid to origin\ncenter_translation(A, w=fill(1/size(A,2), size(A,2))) = Translation(-centroid(A,w))", "meta": {"hexsha": "f2ad113336b66d1cb7eb0edf3f23c595baa9ee28", "size": 1717, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kabsch.jl", "max_stars_repo_name": "tmcgrath325/IterativeClosestPointl.jl", "max_stars_repo_head_hexsha": "7a7684caa890b3ccd902e9cd298e8f4502819e11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kabsch.jl", "max_issues_repo_name": "tmcgrath325/IterativeClosestPointl.jl", "max_issues_repo_head_hexsha": "7a7684caa890b3ccd902e9cd298e8f4502819e11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kabsch.jl", "max_forks_repo_name": "tmcgrath325/IterativeClosestPointl.jl", "max_forks_repo_head_hexsha": "7a7684caa890b3ccd902e9cd298e8f4502819e11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1555555556, "max_line_length": 100, "alphanum_fraction": 0.6884100175, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.7791408865696516}}
{"text": "function rosenbrock(x, g=nothing)\n    n = length(x)\n    f = 0.0\n    for i=1:(n-1)\n        f += (1-x[i])^2 + 100*(x[i+1]-x[i]^2)^2\n    end\n    if g != nothing\n        for i=1:n\n            g[i] = ((i==n ? 0 : -2*(1-x[i]) - 400*(x[i+1]-x[i]^2)*x[i]) +\n                    (i==1 ? 0 : 200*(x[i]-x[i-1]^2)))\n        end\n    end\n    return f\nend\n\nfunction gtest(x=randn(10);eps=1e-5)\n    g = similar(x)\n    @show f0 = rosenbrock(x,g)\n    for i=1:length(x)\n        xi = x[i]\n        x[i] = xi+eps; f1 = rosenbrock(x)\n        x[i] = xi-eps; f2 = rosenbrock(x)\n        x[i] = xi; df = (f1-f2)/(2*eps)\n        @show (i,g[i],df)\n    end\nend\n\nusing Base.LinAlg\n\nfunction eq10(f, x0; gtol=0.95, gamma=1e-8)\n    g0, x1, rb, rr, r = [ zeros(x0) for i=1:5 ]\n    f0 = f(x0, g0)\n    n0 = vecnorm(g0)\n    nf = cosa = 0\n    while cosa < gtol\n        f1 = f(axpy!(gamma, randn!(r), copy!(x1,x0)))\n        nf += 1\n        b = f1 - f0\n        axpy!(b, r, rb)\n        axpy!(1, r.*r, rr)\n        g1 = rb ./ (gamma * rr)\n        n1 = vecnorm(g1)\n        cosa = dot(g0,g1)/(n0*n1)\n    end\n    return nf\nend\n", "meta": {"hexsha": "48e6bbbbc34fa5cfc5d41bf1d40cacc66e47d740", "size": 1081, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "patelli.jl", "max_stars_repo_name": "JuliaTagBot/dhc4rnn", "max_stars_repo_head_hexsha": "41be62515d540d8992d5d85b274ba70b9329e522", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "patelli.jl", "max_issues_repo_name": "JuliaTagBot/dhc4rnn", "max_issues_repo_head_hexsha": "41be62515d540d8992d5d85b274ba70b9329e522", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "patelli.jl", "max_forks_repo_name": "JuliaTagBot/dhc4rnn", "max_forks_repo_head_hexsha": "41be62515d540d8992d5d85b274ba70b9329e522", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:20:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:20:01.000Z", "avg_line_length": 23.0, "max_line_length": 73, "alphanum_fraction": 0.4375578168, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7791408828403132}}
{"text": "# Bogumił Kamiński, 2021\n\n# Codes for chapter 5\n\n# Code for section 5.1.1\n\nx = [1 2 3]\ny = [1, 2, 3]\nx * y\n\na = [1, 2, 3]\nb = [4, 5, 6]\na * b\n\na .* b\n\nmap(*, a, b)\n[a[i] * b[i] for i in eachindex(a, b)]\n\neachindex(a, b)\n\neachindex([1, 2, 3], [4, 5])\n\nmap(*, [1, 2, 3], [4, 5])\n\n[1, 2, 3] .* [4, 5]\n\n# Code for section 5.1.2\n\n[1, 2, 3] .^ [2]\n\n[1, 2, 3] .^ 2\n\n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] .* [1 2 3 4 5 6 7 8 9 10]\n\n[\"x\", \"y\", \"z\"] .=> [sum minimum maximum]\n\nabs.([1, -2, 3, -4])\n\nabs([1, 2, 3])\n\nstring(1, 2, 3)\n\nstring.(\"x\", 1:10)\n\nf(i::Int) = string(\"got integer \", i)\nf(s::String) = string(\"got string \", s)\nf.([1, \"1\"])\n\n# Code for section 5.1.3\n\nin(1, [1, 2, 3])\nin(4, [1, 2, 3])\n\n1 in [1, 2, 3]\n4 in [1, 2, 3]\n\nin([1, 3, 5, 7, 9], [1, 2, 3, 4])\n\nin([1, 3, 5, 7, 9], [1, 2, 3, 4, [1, 3, 5, 7, 9]])\n\nin.([1, 3, 5, 7, 9], [1, 2, 3, 4])\n\nin.([1, 3, 5, 7, 9], Ref([1, 2, 3, 4]))\n\nisodd.([1, 2, 3, 4, 5, 6, 7, 8, 9, 10] .+ [1 2 3 4 5 6 7 8 9 10])\n\nMatrix{Any}(isodd.([1, 2, 3, 4, 5, 6, 7, 8, 9, 10] .* [1 2 3 4 5 6 7 8 9 10]))\n\n# Code for section 5.1.4\n\naq = [10.0   8.04  10.0  9.14  10.0   7.46   8.0   6.58\n       8.0   6.95   8.0  8.14   8.0   6.77   8.0   5.76\n      13.0   7.58  13.0  8.74  13.0  12.74   8.0   7.71\n       9.0   8.81   9.0  8.77   9.0   7.11   8.0   8.84\n      11.0   8.33  11.0  9.26  11.0   7.81   8.0   8.47\n      14.0   9.96  14.0  8.1   14.0   8.84   8.0   7.04\n       6.0   7.24   6.0  6.13   6.0   6.08   8.0   5.25\n       4.0   4.26   4.0  3.1    4.0   5.39  19.0  12.50\n      12.0  10.84  12.0  9.13  12.0   8.15   8.0   5.56\n       7.0   4.82   7.0  7.26   7.0   6.42   8.0   7.91\n       5.0   5.68   5.0  4.74   5.0   5.73   8.0   6.89]\nusing Statistics\n\nmean.(eachcol(aq))\n\nmean(eachcol(aq))\n\nfunction R²(x, y)\n    X = [ones(11) x]\n    model = X \\ y\n    prediction = X * model\n    error = y - prediction\n    SS_res = sum(v -> v ^ 2, error)\n    mean_y = mean(y)\n    SS_tot = sum(v -> (v - mean_y) ^ 2, y)\n    return 1 - SS_res / SS_tot\nend\n\nfunction R²(x, y)\n    X = [ones(11) x]\n    model = X \\ y\n    prediction = X * model\n    SS_res = sum((y .- prediction) .^ 2)\n    SS_tot = sum((y .- mean(y)) .^ 2)\n    return 1 - SS_res / SS_tot\nend\n\n# Code for section 5.2\n\n[]\nDict()\n\nFloat64[1, 2, 3]\n\nDict{UInt8, Float64}(0 => 0, 1 => 1)\n\nUInt32(200)\n\nReal[1, 1.0, 0x3]\n\nv1 = Any[1, 2, 3]\neltype(v1)\nv2 = Float64[1, 2, 3]\neltype(v2)\nv3 = [1, 2, 3]\neltype(v3)\nd1 = Dict()\neltype(d1)\nd2 = Dict(1 => 2, 3 => 4)\neltype(d2)\n\np = 1 => 2\ntypeof(p)\n\n# Code for section 5.2.1\n\n[1, 2, 3] isa AbstractVector{Int}\n[1, 2, 3] isa AbstractVector{Real}\n\nAbstractVector{<:Real} == AbstractVector{T} where T<:Real\n\n# Code for section 5.2.2\n\nusing Statistics\nfunction ourcov(x::AbstractVector{<:Real},\n                y::AbstractVector{<:Real})\n    len = length(x)\n    @assert len == length(y) > 0\n    return sum((x .- mean(x)) .* (y .- mean(y))) / (len - 1)\nend\n\nourcov(1:4, [1.0, 3.0, 2.0, 4.0])\ncov(1:4, [1.0, 3.0, 2.0, 4.0])\n\nourcov(1:4, Any[1.0, 3.0, 2.0, 4.0])\n\nx = Any[1, 2, 3]\nidentity.(x)\ny = Any[1, 2.0]\nidentity.(y)\n\n# Code for section 5.3\n\nusing Random\nRandom.seed!(1234);\ncluster1 = randn(100, 5) .- 1\ncluster2 = randn(100, 5) .+ 1\n\ndata5 = vcat(cluster1, cluster2)\n\nusing PyCall\nmanifold = pyimport(\"sklearn.manifold\")\n\n# Optional code to run if the pyimport(\"sklearn.manifold\") fails\n# There is no need to run it if the above operation worked\nusing Conda\nConda.add(\"scikit-learn\")\n\ntsne = manifold.TSNE(n_components=2, init=\"random\",\n                     learning_rate=\"auto\", random_state=1234)\ndata2 = tsne.fit_transform(data5)\n\nusing Plots\nscatter(data2[:, 1], data2[:, 2];\n        color=[fill(\"black\", 100); fill(\"gold\", 100)],\n        legend=false)\n", "meta": {"hexsha": "88a2152374c71903e5221334c84bb10d0a4e99a3", "size": 3679, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ch05.jl", "max_stars_repo_name": "Mo-Gul/JuliaForDataAnalysis", "max_stars_repo_head_hexsha": "28af42c8fb30bb56569281c9d2978ad76069e3b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch05.jl", "max_issues_repo_name": "Mo-Gul/JuliaForDataAnalysis", "max_issues_repo_head_hexsha": "28af42c8fb30bb56569281c9d2978ad76069e3b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch05.jl", "max_forks_repo_name": "Mo-Gul/JuliaForDataAnalysis", "max_forks_repo_head_hexsha": "28af42c8fb30bb56569281c9d2978ad76069e3b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5691489362, "max_line_length": 78, "alphanum_fraction": 0.5137265561, "num_tokens": 1905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7791408757187985}}
{"text": "module BernsteinEllipses\n\nexport jouk, ijouk\n\n\"\"\"\n    rsmo(x)\n\nEvaluate `√(x^2-1)` with branch cut along `[-1,1]`.\n\nThe function name is the abbreviation of \"root of square minus one\".\n\"\"\"\nrsmo(x) = rsmo(float(x))\nrsmo(x::Union{T,Complex{T}}) where {T<:AbstractFloat} = ifelse(!signbit(real(x)),1,-1)*sqrt(x^2-1)\n\n\"\"\"\n    jouk(z)\n\nJoukowsky map `(z+z^-1)/2`.\n\"\"\"\njouk(z) = (z+inv(z))/2\n\n\"\"\"\n    ijouk(x; halfplane=Val(false), branch=Val(true)) -> z\n\nInverse Joukowsky map `z = x ± √(x^2-1)`. The branch to evaluate is seleced as\nfollows.\n\n+-----------+---------------+----------------+\n|           | `!halfplane`  |  `halfplane`   |\n+-----------+---------------+----------------+\n| ` branch` | `abs(z) >= 1` | `imag(z) >= 0` |\n| `!branch` | `abs(z) <= 1` | `imag(z) <= 0` |\n+-----------+---------------+----------------+\n\n\"\"\"\nijouk(x; halfplane=Val(false), branch=Val(true)) = ijouk(x,halfplane,branch)\nijouk(x,::Val{false},::Val{true} ) = x + rsmo(x)\nijouk(x,::Val{false},::Val{false}) = x - rsmo(x)\nijouk(x,::Val{true} ,::Val{true} ) = x + im*sqrt(1-x^2)\nijouk(x,::Val{true} ,::Val{false}) = x - im*sqrt(1-x^2)\n\n\n\"\"\"\n   radius(x; kwargs...) = abs(ijouk(x; kwargs...))\n\"\"\"\nradius(x; kwargs...) = abs(ijouk(x; kwargs...))\n\n\"\"\"\n   semimajor(x; kwargs...)\n\nSemi-major axis of the Bernstein ellipse through `x`.\n\nSee [`ijouk`](@ref) regardings `kwargs`.\n\"\"\"\nsemimajor(x; kwargs...) = (w = abs(ijouk(x; kwargs...)); (w+inv(w))/2)\n\n\"\"\"\n   semiminor(x; kwargs...)\n\nSemi-minor axis of the Bernstein ellipse through `x`.\n\nSee [`ijouk`](@ref) regardings `kwargs`.\n\"\"\"\nsemiminor(x; kwargs...) = (w = abs(ijouk(x; kwargs...)); (w-inv(w))/2)\n\n\"\"\"\n    semiminor(x,xr)\n\nImaginary component of the point in the upper half-plane\nwhere the line `{ x̃ | real(x̃) = xr }` intersects the Bernstein\nellipse through `x`.\n\"\"\"\nfunction semiminor(x::Number,xr::Real; kwargs...)\n    a = semimajor(x; kwargs...)\n    b = semiminor(x; kwargs...)\n    return b*sqrt(1 - (xr/a)^2)\nend\n\nend # module\n", "meta": {"hexsha": "b85d69089a513d59ff8abc7414fbd0b176fbfbb2", "size": 1967, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BernsteinEllipses.jl", "max_stars_repo_name": "ettersi/BernsteinEllipses.jl", "max_stars_repo_head_hexsha": "944c28d99885a7470b90a7bfcd2a4e9bd4db02b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BernsteinEllipses.jl", "max_issues_repo_name": "ettersi/BernsteinEllipses.jl", "max_issues_repo_head_hexsha": "944c28d99885a7470b90a7bfcd2a4e9bd4db02b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BernsteinEllipses.jl", "max_forks_repo_name": "ettersi/BernsteinEllipses.jl", "max_forks_repo_head_hexsha": "944c28d99885a7470b90a7bfcd2a4e9bd4db02b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5875, "max_line_length": 98, "alphanum_fraction": 0.548551093, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.779140874697035}}
{"text": "using StatsModelComparisons, StanSample\nusing CSV, Printf, StatsPlots\n\nProjDir = @__DIR__\n\ndf = CSV.read(joinpath(ProjDir, \"roachdata.csv\"), DataFrame)\ndf.roach1 = df.roach1 / 100\n\nroaches1_stan = \"\ndata {\n  int<lower=0> N; \n  int<lower=0> K; \n  vector[N] exposure2;\n  vector[N] roach1;\n  vector[N] senior;\n  vector[N] treatment;\n  int y[N];\n}\ntransformed data {\n  vector[N] log_expo;\n  log_expo = log(exposure2);\n}\nparameters {\n  vector[K] beta;\n}\ntransformed parameters {\n   vector[N] eta;\n   eta = log_expo + beta[1] + beta[2] * roach1 + beta[3] * treatment\n                + beta[4] * senior;\n}\nmodel {\n  y ~ poisson_log(eta);\n}\ngenerated quantities {\n  vector[N] log_lik;\n  for (i in 1:N)\n    log_lik[i] = poisson_log_lpmf(y[i] | eta[i]);\n}\n\";\n\ndata = (N = size(df, 1), K = 4, y = Int.(df.y), roach1=df.roach1,\n  exposure2=df.exposure2, senior=df.senior, treatment=df.treatment)\nn = size(df, 1)\n\ntmpdir = mktempdir()\nsm1 = SampleModel(\"roaches1\", roaches1_stan; tmpdir)\nrc1 = stan_sample(sm1; data)\n\nif success(rc1)\n  stan_summary(sm1, true)\n  nt1 = read_samples(sm1)\n\n  # Compute LOO and standard error\n  log_lik1 = nt1.log_lik'\n  loo1, loos1, pk1 = psisloo(log_lik1)\n  elpd_loo1 = sum(loos1)\n  se_elpd_loo1 = std(loos1) * sqrt(n)\n  @printf(\">> elpd_loo = %.1f, SE(elpd_loo) = %.1f\\n\", elpd_loo1, se_elpd_loo1)\n\n  # Check the shape parameter k of the generalized Pareto distribution\n  if all(pk1 .< 0.5)\n      println(\"All Pareto k estimates OK (k < 0.5).\")\n  else\n    pk_good = sum(pk1 .<= 0.5)\n    pk_ok = length(pk1[pk1 .<= 0.7]) - pk_good\n    pk_bad = length(pk1[pk1 .<= 1]) - pk_good - pk_ok\n    println((good=pk_good, ok=pk_ok, bad=pk_bad, very_bad=sum(pk1 .> 1)))\n  end\nend\n\nbegin\n  scatter(pk1, xlab=\"Datapoint\", ylab=\"Pareto shape k\",\n    marker=2.5, lab=\"Pk points\")\n  hline!([0.5], lab=\"pk = 0.5\");hline!([0.7], lab=\"pk = 0.7\")\n  hline!([1], lab=\"pk = 1.0\")\n  title!(\"PSIS diagnostic plot for poisson-log model.\")\n  savefig(joinpath(ProjDir, \"diag_plot_1.png\"))\nend\n\n\n#=\n*Simple negative binomial regression example\n*using the 2nd parametrization of the negative\n*binomial distribution, see section 40.1-3 in the Stan\n*reference guide\n=#\n\nroaches2_stan = \"\ndata {\n  int<lower=0> N; \n  int<lower=0> K;\n  vector[N] exposure2;\n  vector[N] roach1;\n  vector[N] senior;\n  vector[N] treatment;\n  int y[N];\n}\ntransformed data {\n  vector[N] log_expo;\n  log_expo = log(exposure2);\n}\nparameters {\n  real phi;\n  vector[K] beta;\n}\ntransformed parameters {\n   vector[N] eta;\n   eta = log_expo + beta[1] + beta[2] * roach1 + beta[3] * treatment\n                + beta[4] * senior;\n}\nmodel {  \n  phi ~ normal(0, 10);\n  beta[1] ~ cauchy(0,10);   //prior for the intercept following Gelman 2008\n  for(i in 2:K)\n   beta[i] ~ cauchy(0,2.5); //prior for the slopes following Gelman 2008\n  y ~ neg_binomial_2_log(eta, phi);\n}\ngenerated quantities {\n vector[N] log_lik;\n for(i in 1:N){\n  log_lik[i] <- neg_binomial_2_log_lpmf(y[i] | eta[i], phi);\n }\n}\n\";\n\ntmpdir=joinpath(ProjDir, \"tmp\")\nsm2 = SampleModel(\"roaches2\", roaches2_stan; tmpdir)\nrc2 = stan_sample(sm2; data)\n\nif success(rc2)\n  read_summary(sm2, true)\n  nt2 = read_samples(sm2)\n\n  # Compute LOO and standard error\n  log_lik2 = nt2.log_lik'\n  loo2, loos2, pk2 = psisloo(log_lik2)\n  elpd_loo2 = sum(loos2)\n  se_elpd_loo2 = std(loos2) * sqrt(n)\n  @printf(\">> elpd_loo = %.1f, SE(elpd_loo) = %.1f\\n\", elpd_loo2, se_elpd_loo2)\n\n  # Check the shape parameter k of the generalized Pareto distribution\n  pk_qualify(pk2) |> display\n  \nend\n\nbegin\n  scatter(pk2, xlab=\"Datapoint\", ylab=\"Pareto shape k\",\n    marker=2.5, lab=\"Pk points\")\n  hline!([0.5], lab=\"pk = 0.5\");hline!([0.7], lab=\"pk = 0.7\")\n  hline!([1], lab=\"pk = 1.0\")\n  title!(\"PSIS diagnostic plot for neg-binomial model.\")\n  savefig(joinpath(ProjDir, \"diag_plot_2.png\"))\nend\n\n", "meta": {"hexsha": "2fc39abd8a1fe9ef453d268deba4a11e5d3a63fd", "size": 3783, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/roaches/roaches.jl", "max_stars_repo_name": "devmotion/StatsModelComparisons.jl", "max_stars_repo_head_hexsha": "07896872c4140710b9ab91631a08aabb15106077", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/roaches/roaches.jl", "max_issues_repo_name": "devmotion/StatsModelComparisons.jl", "max_issues_repo_head_hexsha": "07896872c4140710b9ab91631a08aabb15106077", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/roaches/roaches.jl", "max_forks_repo_name": "devmotion/StatsModelComparisons.jl", "max_forks_repo_head_hexsha": "07896872c4140710b9ab91631a08aabb15106077", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4064516129, "max_line_length": 79, "alphanum_fraction": 0.6542426646, "num_tokens": 1373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091157, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.779130651539342}}
{"text": "\"\"\"\n    isclockwise(polygon::Polygon)\n\nThe shoelace formula, also known as Gauss's area formula, is used to determine\nwhether polygon traversal is clockwise or counter-clockwise. If the sum over the\nedges is greater than 0, the curve is clockwise. If the sum over the edges is\nlesser than 0, the curve is counter-clockwise. When the sum over the edges\nequals 0, the polygon traverses like a figure eight.\n\nNote: The right-handed coordinate system is used.\n\"\"\"\nfunction isclockwise(polygon::Polygon)\n    sum([(b[1] - a[1]) * (b[2] + a[2]) for (a, b) in edges(polygon)]) > 0\nend\n", "meta": {"hexsha": "d7b2252eaf3bcb93d9e16f002f51981f1621e839", "size": 577, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/shoelace.jl", "max_stars_repo_name": "aaronang/Slicer.jl", "max_stars_repo_head_hexsha": "cbe7b825e4bc6a81a87ab4c47a157e0e6792697b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-10-12T16:34:06.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-12T16:34:06.000Z", "max_issues_repo_path": "src/shoelace.jl", "max_issues_repo_name": "aaronang/Slicer.jl", "max_issues_repo_head_hexsha": "cbe7b825e4bc6a81a87ab4c47a157e0e6792697b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-10-15T00:08:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-15T15:37:22.000Z", "max_forks_repo_path": "src/shoelace.jl", "max_forks_repo_name": "aaronang/Slicer.jl", "max_forks_repo_head_hexsha": "cbe7b825e4bc6a81a87ab4c47a157e0e6792697b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4666666667, "max_line_length": 80, "alphanum_fraction": 0.733102253, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.939913343093499, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7791306485353352}}
{"text": "#############\n# In this example, we explore integration of a harmonic function:\n#\n#   f(x,y) = (x^2-y^2+1)/[(x^2-y^2+1)^2+(2xy+1)^2],\n#\n# over the unit disk. In this case, we know from complex analysis that the\n# integral of a holomorphic function is equal to π × f(0,0).\n# We analyze the function on an N×M tensor product grid defined by:\n#\n#   rₙ = cos[(n+1/2)π/2N], for 0 ≤ n < N, and\n#\n#   θₘ = 2π m/M, for 0 ≤ m < M;\n#\n# we convert the function samples to Chebyshev×Fourier coefficients using\n# `plan_disk_analysis`; and finally, we transform the Chebyshev×Fourier\n# coefficients to disk harmonic coefficients using `plan_disk2cxf`.\n#\n# For the storage pattern of the arrays, please consult the documentation.\n#############\n\nusing FastTransforms, LinearAlgebra\n\nf = (x,y) -> (x^2-y^2+1)/((x^2-y^2+1)^2+(2x*y+1)^2)\n\nN = 5\nM = 4N-3\n\nr = [sinpi((N-n-0.5)/(2N)) for n in 0:N-1]\nθ = (0:M-1)*2/M # mod π.\n\n# On the mapped tensor product grid, our function samples are:\nF = [f(r*cospi(θ), r*sinpi(θ)) for r in r, θ in θ]\n\nP = plan_disk2cxf(F)\nPA = plan_disk_analysis(F)\n\n# Its Zernike coefficients are:\nU = P\\(PA*F)\n\n# The Zernike coefficients are useful for integration. The integral of f(x,y)\n# over the disk should be π/2 by harmonicity. The coefficient of Z_0^0\n# multiplied by √π is:\nU[1, 1]*sqrt(π)\n\n# Using an orthonormal basis, the integral of [f(x,y)]^2 over the disk is\n# approximately the square of the 2-norm of the coefficients:\nnorm(U)^2\n", "meta": {"hexsha": "4a4b6c4dac0136e68b506a53a47796095b108016", "size": 1450, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/disk.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/FastTransforms.jl-057dd010-8810-581a-b7be-e3fc3b93f78c", "max_stars_repo_head_hexsha": "766d3076b4e3b32206169a4310d4211c2e0a1902", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-15T03:23:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T03:23:28.000Z", "max_issues_repo_path": "examples/disk.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/FastTransforms.jl-057dd010-8810-581a-b7be-e3fc3b93f78c", "max_issues_repo_head_hexsha": "766d3076b4e3b32206169a4310d4211c2e0a1902", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/disk.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/FastTransforms.jl-057dd010-8810-581a-b7be-e3fc3b93f78c", "max_forks_repo_head_hexsha": "766d3076b4e3b32206169a4310d4211c2e0a1902", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2083333333, "max_line_length": 77, "alphanum_fraction": 0.6668965517, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7791306439725049}}
{"text": "function chebyshev_extrema(n::S,domain = [1.0,-1.0]) where S <: Integer\n\n  if n <= 0\n    error(\"The number of nodes must be positive.\")\n  end\n  \n  nodes = zeros(n)\n  \n  if isodd(n)\n    nodes[Int((n-1)/2)+1] = (domain[1]+domain[2])/2.0\n  end\n  \n  for i = 1:div(n,2)\n    x = -cos((i-1)*pi/(n-1))*(domain[1]-domain[2])/2.0\n    nodes[i]       = (domain[1]+domain[2])/2.0  + x\n    nodes[end-i+1] = (domain[1]+domain[2])/2.0  - x\n  end\n  \n  return nodes\n  \nend", "meta": {"hexsha": "71b8c75cfda0370e86523cbf783c5eecb77508b4", "size": 454, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chebyshev_extrema.jl", "max_stars_repo_name": "RJDennis/ChebyshevApprox", "max_stars_repo_head_hexsha": "9b43654b3b7d00210ca2191b1173c79c7333dad3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-05-15T13:28:38.000Z", "max_stars_repo_stars_event_max_datetime": "2015-05-15T13:28:38.000Z", "max_issues_repo_path": "src/chebyshev_extrema.jl", "max_issues_repo_name": "RJDennis/ChebyshevApprox", "max_issues_repo_head_hexsha": "9b43654b3b7d00210ca2191b1173c79c7333dad3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chebyshev_extrema.jl", "max_forks_repo_name": "RJDennis/ChebyshevApprox", "max_forks_repo_head_hexsha": "9b43654b3b7d00210ca2191b1173c79c7333dad3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.619047619, "max_line_length": 71, "alphanum_fraction": 0.5396475771, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7791121563533704}}
{"text": "export resampleα, randomindex\n\n\"\"\"\n\tresampleα(α::Float64, N::Int, K::Int)\n\nResample α given the approach by Escobar and West. (page 585)\n\"\"\"\nfunction resampleα(α::Float64, N::Int, K::Int; k = 1.0, Θ = 1.0, maxiter = 1)\n\n    w = zeros(2)\n    w[2] = N\n\n    f0 = k + K\n    f1 = Θ + K - 1\n\n    newα = α\n\n    for i in 1:maxiter\n\n        η = rand(Beta(newα + 1, N))\n        f3 = Θ - log(η)\n\n        w[1] = f1 / f3\n\n        z = randomindex(w)\n\n        if z == 1\n            newα = rand(Gamma(f0, 1/f3))\n        else\n            newα = rand(Gamma(f1, 1/f3))\n        end\n    end\n\n    return newα\nend\n\nfunction resampleα(α::Float64, N::Array{Int}, K::Array{Int}; k = 1.0, Θ = 1.0, maxiter = 1)\n    # implementation according to escobar - west page\n    totalK = sum(K)\n    num = length(N)\n\n    η = zeros(num)\n\n\t\tnewα = α\n    for i in 1:maxiter\n\n        for j in 1:num\n            η[j] = rand(Beta(newα + 1, N[j]))\n        end\n\n        z = rand(num) .* (newα + N) .< N\n\n        g_a = k + totalK - sum(z)\n        g_b = Θ - sum(log(η))\n\n        newα = rand(Gamma(g_a, 1/g_b))\n    end\n\n    newα\nend\n\n\"\"\"\n\trandomindex(p::Vector{Float64})\n\nRandomly select an index propotional to its probability.\n\"\"\"\nfunction randomindex(p::Vector{Float64})\n\n    max = sum(p)\n    csum = 0.0\n    thres = rand()\n\n    @inbounds for i in 1:length(p)\n        csum += p[i]\n        if csum >= thres * max\n            return convert(Int, i)\n        end\n    end\n\n    return length(p)\nend\n\nfunction randnumtable(weights::Array{Float64}, table::Array{Int})\n\n    numtable = zeros(Int, size(table))\n\n    B = unique( table )\n    w = log( weights )\n\n    for i in 1:length(B)\n\n        max = B[i]\n        if max > 0\n\n            m = 1:max\n\n            stirnums = map( x -> abs(stirlings1(max, x)), m)\n            stirnums /= maximum(stirnums)\n\n            for (idx, j) in enumerate(findall(table .== max))\n\n                clike = m .* w[idx]\n                clike = cumsum(stirnums .* exp(clike - maximum(clike)))\n\n                numtable[j] = 1+sum(rand() * clike[max] .> clike)\n            end\n\n\n        end\n\n    end\n\n    return numtable\nend\n", "meta": {"hexsha": "da2d8964eb1fcfd5ce0d6d22763f83adfa481f62", "size": 2096, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "UnofficialJuliaMirror/BayesianNonparametrics.jl-7e49bc5d-d907-5fdd-93a4-11f1b4f8bb51", "max_stars_repo_head_hexsha": "12d790361ffefeeadc97810e1ebb06f6a237fde1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2016-12-10T01:58:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T04:10:57.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "UnofficialJuliaMirror/BayesianNonparametrics.jl-7e49bc5d-d907-5fdd-93a4-11f1b4f8bb51", "max_issues_repo_head_hexsha": "12d790361ffefeeadc97810e1ebb06f6a237fde1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-01-05T23:29:50.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-13T10:36:48.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "UnofficialJuliaMirror/BayesianNonparametrics.jl-7e49bc5d-d907-5fdd-93a4-11f1b4f8bb51", "max_forks_repo_head_hexsha": "12d790361ffefeeadc97810e1ebb06f6a237fde1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2017-04-05T13:29:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T01:06:47.000Z", "avg_line_length": 18.2260869565, "max_line_length": 91, "alphanum_fraction": 0.5066793893, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374443, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7790493959682168}}
{"text": "\n\n# interpolate point at (x, y) from 4 nearby pixel values\nfunction interp_bilinear{T <: Union(Real, Integer)}(dat::Array{T, 2},\n                                                    x::Float64, y::Float64,\n                                                    x1, x2, y1, y2)\n    q11 = dat[y1, x1]         \n    q12 = dat[y2, x1]\n    q21 = dat[y1, x2]\n    q22 = dat[y2, x2]\n    if x1 != x2\n        r1 = (x2 - x) / (x2 - x1) * q11 + (x - x1) / (x2 - x1) * q21\n        r2 = (x2 - x) / (x2 - x1) * q12 + (x - x1) / (x2 - x1) * q22\n    else\n        # special case of x1 == x2, no interpolation needed\n        r1 = q11\n        r2 = q12\n    end\n    if y1 != y2\n        r = (y - y1) / (y2 - y1) * r1 + (y2 - y) / (y2 - y1) * r2\n    else\n        # special case of y1 == y2, no interpolation needed\n        r = r1\n    end\n    if typeof(r) <: Real\n        r = round(r)\n    end\n    r = convert(T, r)\n    return r\nend\n\n\nfunction imresize{T <: Union(Real, Integer)}(dat::Array{T, 2},\n                                             new_size::(Int, Int))\n    new_dat = similar(dat, new_size)\n    h, w = size(dat)\n    new_h, new_w = new_size\n    for new_j=1:new_w, new_i=1:new_h\n        # coordinates in original image\n        x = new_j * w / new_w\n        y = new_i * h / new_h\n        # coordinates of 4 points to interpolate from\n        x1, x2 = max(1, floor(x)), min(w, ceil(x))\n        y1, y2 = max(1, floor(y)), min(h, ceil(y))\n        new_dat[new_i, new_j] = interp_bilinear(dat, x, y, x1, x2, y1, y2)\n    end\n    return new_dat\nend\n\n\nfunction imresize{T <: Union(Real, Integer)}(dat::Array{T, 2},\n                                             new_size...)\n    return imresize(dat, new_size)\nend\n\n\n## if isinteractive()\n##     using Images\n##     using ImageView\n##     im = imread(\"../../data/CK/faces_aligned/S999_003_00000054.png\")\n##     dat = convert(Array, im)\n## end\n\n\n\nusing Images, Cairo\n\nfunction imresize_julia!(resized, original)\n    scale1 = (size(original,1)-1)/(size(resized,1)-0.999f0)\n    scale2 = (size(original,2)-1)/(size(resized,2)-0.999f0)\n    for jr = 0:size(resized,2)-1\n        jo = scale2*jr\n        ijo = itrunc(jo)\n        fjo = jo - oftype(jo, ijo)\n        @inbounds for ir = 0:size(resized,1)-1\n            io = scale1*ir\n            iio = itrunc(io)\n            fio = io - oftype(io, iio)\n            tmp = (1-fio)*((1-fjo)*original[iio+1,ijo+1] +\n                           fjo*original[iio+1,ijo+2])\n            + fio*((1-fjo)*original[iio+2,ijo+1] +\n                   fjo*original[iio+2,ijo+2])\n            resized[ir+1,jr+1] = convertsafely(eltype(resized), tmp)\n        end\n    end\n    resized\nend\nimresize_julia(original, new_size) =\n    imresize_julia!(similar(original,\n                            new_size), original)\n                            \nconvertsafely{T<:FloatingPoint}(::Type{T}, val) = convert(T, val)\nconvertsafely{T<:Integer}(::Type{T}, val::Integer) = convert(T, val)\nconvertsafely{T<:Integer}(::Type{T}, val::FloatingPoint) =\n    itrunc(T,\n           val+oftype(val, 0.5))\n           \n           \nfunction imresize_cairo(dat::Array{Uint32, 2}, new_size::(Int, Int))\n    cs = CairoImageSurface(dat, 0)\n    new_dat = zeros(Uint32, new_size)\n    new_cs = CairoImageSurface(new_dat, 0)\n    pat = CairoPattern(cs)\n    pattern_set_filter(pat, Cairo.FILTER_BILINEAR)\n    c = CairoContext(new_cs)\n    h, w = size(dat)\n    new_h, new_w = new_size\n    scale(c, new_h / h, new_w / w)\n    set_source(c, pat)\n    paint(c)\n    return new_cs.data\nend\n\n## img = rand(0x00:0xff, 774, 512)\n## new_size = (3096, 2048)\n## imresize_cairo(convert(Array{Uint32}, img), new_size)\n## println(\"Cairo:\")\n## @time imresize_cairo(convert(Array{Uint32}, img), new_size)\n## imresize_julia(img, new_size)\n## println(\"Julia:\")\n## @time imresize_julia(img, new_size)\n", "meta": {"hexsha": "28dfc6ac42e6ad7871464562f4a736bea5f00883", "size": 3774, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "masque/playground/interp.jl", "max_stars_repo_name": "dfdx/masque", "max_stars_repo_head_hexsha": "d779bd3a4001436148cf6668638d9a1bf64254bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-11-29T06:25:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T20:12:37.000Z", "max_issues_repo_path": "masque/playground/interp.jl", "max_issues_repo_name": "dfdx/masque", "max_issues_repo_head_hexsha": "d779bd3a4001436148cf6668638d9a1bf64254bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "masque/playground/interp.jl", "max_forks_repo_name": "dfdx/masque", "max_forks_repo_head_hexsha": "d779bd3a4001436148cf6668638d9a1bf64254bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-19T17:29:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-19T17:29:43.000Z", "avg_line_length": 30.9344262295, "max_line_length": 75, "alphanum_fraction": 0.5344462109, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7790493892140349}}
{"text": "# p20.m - 2nd-order wave eq. in 2D via FFT (compare p19.m)\n\n# Grid and initial data:\nN = 24; x = y = cheb(N)[2];\ndt = 6/N^2;\nxx = yy = x[end:-1:1];\nplotgap = round(Int,(1/3)/dt); dt = (1/3)/plotgap;\nvv = @. exp(-40*((x'-.4)^2 + y^2));\nvvold = vv;  clf();\n\n# Time-stepping by leap frog formula:\nfor n = 0:3*plotgap\n    t = n*dt;\n    if rem(n+.5,plotgap)<1     # plots at multiples of t=1/3\n          i = n/plotgap+1;\n          subplot(2,2,i,projection=\"3d\");\n          xxx = yyy = -1:1/16:1;\n          s = Spline2D(xx,yy,reduce(flipdim,vv,1:2));\n          vvv = evalgrid(s,xxx,yyy);\n          surf(xxx,yyy,vvv); xlim(-1,1); ylim(-1,1); zlim(-0.15,1);\n          view(-37.5,30); title(\"t = $(signif(t,5))\");\n    end\n    uxx = zeros(N+1,N+1); uyy = zeros(N+1,N+1);\n    ii = 2:N;\n    for i = 2:N                # 2nd derivs wrt x in each row\n          v = vv[i,:]; V = [v;flipdim(v[ii],1)];\n          U = real(fft(V));\n          W1 = real(ifft(1im*[0:N-1;0;1-N:-1].*U)); # diff wrt theta\n          W2 = real(ifft(-[0:N;1-N:-1].^2.*U));     # diff^2 wrt theta\n          uxx[i,ii] = W2[ii]./(1-x[ii].^2) - x[ii].*W1[ii]./(1-x[ii].^2).^(3/2);\n    end\n    for j = 2:N                # 2nd derivs wrt y in each column\n          v = vv[:,j]; V = [v; flipdim(v[ii],1)];\n          U = real(fft(V));\n          W1 = real(ifft(1im*[0:N-1;0;1-N:-1].*U));# diff wrt theta\n          W2 = real(ifft(-[0:N;1-N:-1].^2.*U));    # diff^2 wrt theta\n          uyy[ii,j] = W2[ii]./(1-y[ii].^2) - y[ii].*W1[ii]./(1-y[ii].^2).^(3/2);\n    end\n    vvnew = 2*vv - vvold + dt^2*(uxx+uyy);\n    vvold = vv; vv = vvnew;\nend\n", "meta": {"hexsha": "b898c4fd00556956601bfaf936853373578c583e", "size": 1588, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p20.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p20.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p20.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8095238095, "max_line_length": 80, "alphanum_fraction": 0.4628463476, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7790493851923731}}
{"text": "module FunctionsCollection\n\n    function function1(x)\n        return 2 * exp.(-2 * (x .- 1).^2) .- exp.(-(x .- 1).^2)\n    end\n\n    function function2(x)\n        return x.^(1/2)\n    end\n\n    function function3(x)\n        return exp.(-x) .* sin.(2 * x)\n    end\n\n    function function4(x)\n        return log.(log.(x))\n    end\n\n    function function5(x)\n        return 6 * exp.(-2 * x) + 2 * sin.(x) - cos.(x)\n    end\n    \nend # FunctionsCollection\n", "meta": {"hexsha": "e01adce78d6a73723968e3c85e1b491be5e93389", "size": 445, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "functions_collection.jl", "max_stars_repo_name": "pabloduque0/regression_genetic_algorithm", "max_stars_repo_head_hexsha": "807d6b7a2cae812fe8dfac126d8803d06c024d16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-02-21T10:11:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-24T11:24:27.000Z", "max_issues_repo_path": "functions_collection.jl", "max_issues_repo_name": "pabloduque0/regression_genetic_algorithm", "max_issues_repo_head_hexsha": "807d6b7a2cae812fe8dfac126d8803d06c024d16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions_collection.jl", "max_forks_repo_name": "pabloduque0/regression_genetic_algorithm", "max_forks_repo_head_hexsha": "807d6b7a2cae812fe8dfac126d8803d06c024d16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5416666667, "max_line_length": 63, "alphanum_fraction": 0.5168539326, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533032291502, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7790493839656739}}
{"text": "abstract type InnerProduct end\n\ndot_arg(f,p::InnerProduct) = evaluate(f,p)\ndot_arg(f::AbstractArray,p::InnerProduct) = [f(x) for x in evalpoints(p), f in f]\ndot_arg(f::AbstractBasis,p::InnerProduct) = Matrix(f,evalpoints(p))\n\nLinearAlgebra.norm(f, p::InnerProduct) = norm(dot_arg(f,p), p)\nLinearAlgebra.dot(f,g,p::InnerProduct) = dot(dot_arg.((f,g),Ref(p))...,p)\n\n\"\"\"\n    WeightedL2(x,w) <: InnerProduct\n\n# Example\n```\np = WeightedL2([0,1],[2,3])\nnorm(identity,p) -> sqrt(0^2*2 + 1^2*3)\n```\n\"\"\"\nstruct WeightedL2{X,W} <: InnerProduct\n    points::X\n    weights::W\nend\n\nevalpoints(p::WeightedL2) = p.points\nevaluate(f,p::WeightedL2) = f.(evalpoints(p))\ndot_arg(f::AbstractArray{<:Number},p::WeightedL2) = f\n\nLinearAlgebra.norm(f::AbstractVecOrMat{<:Number}, p::WeightedL2) = sqrt(dot(f,f,p))\n\nfunction LinearAlgebra.dot(\n    f::AbstractVecOrMat{<:Number},\n    g::AbstractVecOrMat{<:Number},\n    p::WeightedL2\n)\n    w = p.weights\n    # Workaround for https://github.com/JuliaLang/julia/issues/35424\n    length(w) == 0 && return zero(eltype(f))*zero(eltype(w))*zero(eltype(g))\n    return f'*Diagonal(w)*g\nend\n\n\nusing FastGaussQuadrature\n\nLegendreInnerProduct(n) = WeightedL2(gausslegendre(n)...)\nJacobiInnerProduct(n,a,b) = WeightedL2(gaussjacobi(n,a,b)...)\n", "meta": {"hexsha": "600facd35e4aa40db2ae1b780a520a81ed9b0f61", "size": 1254, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/inner_products.jl", "max_stars_repo_name": "ettersi/ApproxTools.jl", "max_stars_repo_head_hexsha": "5a14019a3ed7a545c3446a7dd03b4584adf6ff46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/inner_products.jl", "max_issues_repo_name": "ettersi/ApproxTools.jl", "max_issues_repo_head_hexsha": "5a14019a3ed7a545c3446a7dd03b4584adf6ff46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-03-16T15:54:22.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-09T16:37:30.000Z", "max_forks_repo_path": "src/inner_products.jl", "max_forks_repo_name": "ettersi/ApproxTools.jl", "max_forks_repo_head_hexsha": "5a14019a3ed7a545c3446a7dd03b4584adf6ff46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2608695652, "max_line_length": 83, "alphanum_fraction": 0.6858054226, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.7790012602871343}}
{"text": "using GR\nusing LaTeXStrings\n\n𝒩(μ, σ) = 1 / (σ * √(2π)) * exp.(-0.5 * ((x .- μ) / σ) .^ 2)\n\nx = LinRange(-5, 5, 500);\ny = hcat(𝒩(0, √0.2), 𝒩(0, √1), 𝒩(0, √5), 𝒩(-2, √0.5));\n\nplot(x, y, xlabel=L\"\\mathcal{X}\", ylabel=L\"\\mathcal{N}(\\mu,\\,\\sigma^{2})\", title=L\"\\frac{1}{\\sigma\\sqrt{2\\pi}} e^{-\\frac{1}{2} \\left({\\frac{x-\\mu}{\\sigma}}\\right)^2}\", labels=(L\"\\mu=0, \\sigma^2=0.2\", L\"\\mu=0, \\sigma^2=1\", L\"\\mu=0, \\sigma^2=5\", L\"\\mu={-2}, \\sigma^2=0.5\"), xlim=(-5.2, 5.2), ylim=(-0.05, 1.05), linewidth=3)\n", "meta": {"hexsha": "149a068c5d1961d3861b7e4e26c9a5890c52d0c7", "size": 496, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/gauss_ex.jl", "max_stars_repo_name": "ven-k/GR.jl", "max_stars_repo_head_hexsha": "1e0d1f0a7590aa1e86e7afd80125ff1ea7af0a8a", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 339, "max_stars_repo_stars_event_min_datetime": "2015-01-26T01:14:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T12:40:07.000Z", "max_issues_repo_path": "examples/gauss_ex.jl", "max_issues_repo_name": "ven-k/GR.jl", "max_issues_repo_head_hexsha": "1e0d1f0a7590aa1e86e7afd80125ff1ea7af0a8a", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": 413, "max_issues_repo_issues_event_min_datetime": "2015-01-15T11:00:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T08:16:48.000Z", "max_forks_repo_path": "examples/gauss_ex.jl", "max_forks_repo_name": "ven-k/GR.jl", "max_forks_repo_head_hexsha": "1e0d1f0a7590aa1e86e7afd80125ff1ea7af0a8a", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 88, "max_forks_repo_forks_event_min_datetime": "2015-01-15T10:44:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T01:06:07.000Z", "avg_line_length": 49.6, "max_line_length": 322, "alphanum_fraction": 0.502016129, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914020657881, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7789770612754314}}
{"text": "\"\"\"\n    uniform_bsplines_eval_basis( spline_degree, normalized_offset, bspl )\n  \n# UNIFORM B-SPLINE FUNCTIONS\n\n## Evaluate all non vanishing uniform B-Splines in unit cell. \n\nReturns an array with the values of the b-splines of the \nrequested degree, evaluated at a given cell offset. The cell size is\nnormalized between 0 and 1, thus the offset given must be a number\nbetween 0 and 1.\n\nOutput: \n\n```math\nbspl(1:d+1)= B_d(-(d+1)/2+d+x),...,B_d(-(d+1)/2+x)\n```\n \nwith ``d``=`spline_degree` and ``x``=`normalized_offset`\nwhere ``B_d=B_{d-1}*B_0`` and ``B_0=1_[-1/2,1/2]`` and `*` is convolution\nthe following FORTRAN code can be used for comparison with \n[deboor](http://pages.cs.wisc.edu/~deboor/)\n\n```fortran\ndo i=-d,d+1\n    t(i+d+1)=real(i,8)\nend do\ncall bsplvb(t,d+1,1,normalized_offset,d+1,out)\n```\n\nWe also have the property (from the symmetry of the B-spline)\n```math\nout[1:d+1]= B_d(-(d+1)/2+xx),...,B_d(-(d+1)/2+d+xx),..., \n```\nwhere ``xx=1-`` `normalized_offset`\n\n\"\"\"\nfunction uniform_bsplines_eval_basis(spline_degree::Int, normalized_offset::Float64)\n    @assert spline_degree >= 0\n    @assert normalized_offset >= 0.0\n    @assert normalized_offset <= 1.0\n\n    bspl = zeros(Float64, spline_degree + 1)\n\n    bspl[1] = 1.0\n    @inbounds for j in 1:spline_degree\n        xx = -normalized_offset\n        j_real = Float64(j)\n        inv_j = 1.0 / j_real\n        saved = 0.0\n        for r in 0:(j - 1)\n            xx = xx + 1.0\n            temp = bspl[r + 1] * inv_j\n            bspl[r + 1] = saved + xx * temp\n            saved = (j_real - xx) * temp\n        end\n        bspl[j + 1] = saved\n    end\n\n    return bspl\nend\n\nfunction uniform_bsplines_eval_basis!(\n    bspl::Vector{Float64}, spline_degree::Int, normalized_offset::Float64\n)\n    bspl[1] = 1.0\n    @inbounds for j in 1:spline_degree\n        xx = -normalized_offset\n        j_real = Float64(j)\n        inv_j = 1.0 / j_real\n        saved = 0.0\n        for r in 0:(j - 1)\n            xx = xx + 1.0\n            temp = bspl[r + 1] * inv_j\n            bspl[r + 1] = saved + xx * temp\n            saved = (j_real - xx) * temp\n        end\n        bspl[j + 1] = saved\n    end\nend\n\nfunction uniform_bsplines_eval_basis!(\n    bspl::Array{Float64,2},\n    spline_degree::Int,\n    normalized_offset_x::Float64,\n    normalized_offset_y::Float64,\n)\n    bspl[1, 1] = 1.0\n    bspl[1, 2] = 1.0\n    @inbounds for j in 1:spline_degree\n        xx = -normalized_offset_x\n        yy = -normalized_offset_y\n        j_real = Float64(j)\n        inv_j = 1.0 / j_real\n        saved_x = 0.0\n        saved_y = 0.0\n        for r in 0:(j - 1)\n            xx = xx + 1\n            yy = yy + 1\n            temp_x = bspl[r + 1, 1] * inv_j\n            temp_y = bspl[r + 1, 2] * inv_j\n            bspl[r + 1, 1] = saved_x + xx * temp_x\n            bspl[r + 1, 2] = saved_y + yy * temp_y\n            saved_x = (j_real - xx) * temp_x\n            saved_y = (j_real - yy) * temp_y\n        end\n        bspl[j + 1, 1] = saved_x\n        bspl[j + 1, 2] = saved_y\n    end\nend\n\nexport eval_uniform_periodic_spline_curve\n\n\"\"\"\n    eval_uniform_periodic_spline_curve( degree, scoef )\n\nEvaluate uniform periodic spline curve defined by coefficients scoef at \nknots (which are the grid points) \n\n\"\"\"\nfunction eval_uniform_periodic_spline_curve(degree::Int, scoef::Vector{Float64})\n\n    # get bspline values at knots\n    bspl = uniform_bsplines_eval_basis(degree, 0.0)\n    n = length(scoef)\n    sval = similar(scoef)\n    for i in 1:n\n        val = 0.0\n        for j in 1:degree\n            imj = mod1(i - j + n, n)\n            val = val + bspl[j] * scoef[imj]\n        end\n        sval[i] = val\n    end\n\n    return sval\nend\n", "meta": {"hexsha": "319b19983dca4062ad85ac687e1ab2997cabea41", "size": 3633, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/low_level_bsplines.jl", "max_stars_repo_name": "JuliaVlasov/GEMPIC.jl", "max_stars_repo_head_hexsha": "bc7f0a5524ef6f7c4fa50a1450e24865c2a0abad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-08-23T08:56:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T00:13:38.000Z", "max_issues_repo_path": "src/low_level_bsplines.jl", "max_issues_repo_name": "JuliaVlasov/GEMPIC.jl", "max_issues_repo_head_hexsha": "bc7f0a5524ef6f7c4fa50a1450e24865c2a0abad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2019-04-01T12:47:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T11:08:28.000Z", "max_forks_repo_path": "src/low_level_bsplines.jl", "max_forks_repo_name": "JuliaVlasov/GEMPIC.jl", "max_forks_repo_head_hexsha": "bc7f0a5524ef6f7c4fa50a1450e24865c2a0abad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-12-12T10:18:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T11:58:18.000Z", "avg_line_length": 26.3260869565, "max_line_length": 84, "alphanum_fraction": 0.5832645197, "num_tokens": 1213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7789562424475641}}
{"text": "@doc \"\"\"\n      Heun's Method (with iteration)\n      Supported by:\n      -PhD Kelvyn B. Sánchez kelvyn.baruc@gmail.com\n \"\"\" ->\nfunction heun(f, tspan, y0; h = 1, AbsTol = 0.00001)\n\nt = tspan[1]:h:tspan[end]\nn = length(t)\n\n      if t[n] < tspan[end]\n            t = [t, tspan[end]]\n            n += 1\n      end\n\ny1 = f(t[1],y0)\neq = length(y1) # Test the number of equations in f\ny = zeros(Int(n),eq)\ny[1,:] = y0\ny1 = zeros(Int(n),eq)\ny2 = zeros(Int(n),eq)\ny3 = zeros(Int(n),eq)\n\n\tfor i=1:n-1 # Solve for each x\n            for j=1:eq # Solve for each equation in f\n                  s1 = f(t[i],y[i,:])\n                  y1[i,j] = y[i,j] + s1[j] * (t[i+1] - t[i])\n\n                  s2 = f(t[i+1],y1[i,:])\n                  y2[i,j] = y[i,j] + ((s1[j] + s2[j])/2) * (t[i+1] - t[i])\n\n                  err = 100\n                  while err >= AbsTol\n                        s1 = f(t[i],y[i,:])\n                        s2 = f(t[i+1],y2[i,:])\n                        y3[i,j] = y[i,j] + ((s1[j] + s2[j]) / 2) * (t[i+1] - t[i])\n                        err = abs((y3[i,j] - y2[i,j])/y3[i,j]) * 100\n                        y2[i,j] = y3[i,j]\n                        y[i+1,j] = y3[i,j]\n                  end\n            end\n\tend\n\treturn t, y\nend\n", "meta": {"hexsha": "9bbf30dbd49a441d1a9ec6d81b1352af8bb3dea0", "size": 1235, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/heun.jl", "max_stars_repo_name": "Kelvyn88/ODEs.jl", "max_stars_repo_head_hexsha": "15c096f9f4cc6cf3e2f01a9917d3e3c737fe2c1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/heun.jl", "max_issues_repo_name": "Kelvyn88/ODEs.jl", "max_issues_repo_head_hexsha": "15c096f9f4cc6cf3e2f01a9917d3e3c737fe2c1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/heun.jl", "max_forks_repo_name": "Kelvyn88/ODEs.jl", "max_forks_repo_head_hexsha": "15c096f9f4cc6cf3e2f01a9917d3e3c737fe2c1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4444444444, "max_line_length": 82, "alphanum_fraction": 0.3805668016, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7789562390299491}}
{"text": "using Distributions\nusing LightBayes\n\nfunction simulate(r::Float64, n::Int)\n    # Simulate Δb for H0 & H1\n    #\n    # generate two clusters of samples, respectively centered\n    # at (r, 0) and (-r, 0), where each cluster contains n\n    # samples.\n    #\n    # This function computes the values of Δb, respectively\n    # for the following two hypotheses:\n    #\n    # - H0: all samples are generated by a single component\n    # - H1: each cluster of samples are generated by a different\n    #       component\n    #\n    # Prior model: θ ~ N(0, σ0^2) with σ0 = 10.0\n    # Likelihood:  x ~ N(θ, σ^2) with σ = 1.0\n    #\n\n    # data\n    n = 1000\n    X1 = [r, 0.0] .+ rand(2, 1000)\n    X2 = [-r, 0.0] .+ rand(2, 1000)\n\n    X = hcat(X1, X2)\n    @assert size(X) == (2, 2n)\n\n    # prior\n    β0 = zeros(2)\n    σ0 = 10.0\n    κ0 = inv(σ0^2)\n    pri = MvNormalCanon(β0, κ0)\n\n    # likelihood model\n    σ = 1.0\n    g = IsoGaussModel(σ)\n\n    # H0: single component\n    pp0 = posterior(pri, suffstats(g, X))\n    Δb0 = logpar(pp0) - logpar(pri)\n\n    # H1: two components:\n    pp1 = posterior(pri, suffstats(g, X1))\n    pp2 = posterior(pri, suffstats(g, X2))\n    Δb1 = (logpar(pp1) - logpar(pri)) + (logpar(pp2) - logpar(pri))\n\n    return (Δb0, Δb1)\nend\n\n\n# main script\n\nn = 1000\n\nfor r in [0.0, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0]\n    Δb0, Δb1 = simulate(r, n)\n    @printf(\"With r = %5.1f:  H0.Δb = %8.2f,  H1.Δb = %8.2f\\n\", r, Δb0, Δb1)\nend\n", "meta": {"hexsha": "f710b63d16bc2cb37fdde046767d3b7e5a2b2b87", "size": 1417, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ex_gauss.jl", "max_stars_repo_name": "lindahua/BayesModels.jl", "max_stars_repo_head_hexsha": "a27a06f846d16914c812c00d9cfb8f2d48e4c439", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-01-25T19:07:30.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-20T07:21:30.000Z", "max_issues_repo_path": "examples/ex_gauss.jl", "max_issues_repo_name": "lindahua/LightBayes.jl", "max_issues_repo_head_hexsha": "a27a06f846d16914c812c00d9cfb8f2d48e4c439", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ex_gauss.jl", "max_forks_repo_name": "lindahua/LightBayes.jl", "max_forks_repo_head_hexsha": "a27a06f846d16914c812c00d9cfb8f2d48e4c439", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2295081967, "max_line_length": 76, "alphanum_fraction": 0.5645730416, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.8311430478583169, "lm_q1q2_score": 0.7789562292794531}}
{"text": "\"\"\"Compute the entropy of the specified dataset.\"\"\"\nfunction entropy(dataset::AbstractArray{T, 2}, target::Integer,\n                c::Integer=2) where {T}\n    class = dataset[:, target]\n    n = length(class)\n    uniques = unique(class)\n\n    return -mapreduce(u -> begin\n        subset = dataset[class .== u, :]\n        p = size(subset, 1) / n\n        return p * log2(p)\n    end, +, uniques) / log2(c)\nend\n\nentropy(dataset::AbstractArray{T, 2}, target::String,\n        header::AbstractArray{String}, c::Integer=2) where {T} =\n    entropy(dataset, something(findfirst(isequal(target), header), 0), c)\n\n\"\"\"Compute the information gain of the specified attribute.\"\"\"\nfunction information_gain(dataset::AbstractArray{T, 2}, attribute::Integer,\n                        target::Integer, c::Integer=2) where {T}\n    n = size(dataset, 1)\n    attr = dataset[:, attribute]\n    uniques = unique(attr)\n\n    attr_sub_entropy = mapreduce(u -> begin\n        subset = dataset[attr .== u, :]\n        return size(subset, 1) / n * entropy(subset, target, c)\n    end, +, uniques)\n\n    return entropy(dataset, target, c) - attr_sub_entropy\nend\n\ninformation_gain(dataset::AbstractArray{T, 2}, attribute::String,\n                target::String, header::AbstractArray{String},\n                c::Integer=2) where {T} =\n    information_gain(dataset,\n            something(findfirst(isequal(attribute), header), 0),\n            something(findfirst(isequal(target), header), 0), c)\n\ninformation_gain(dataset::AbstractArray{T, 2}, attribute::String,\n                target::Integer, header::AbstractArray{String},\n                c::Integer=2) where {T} =\n    information_gain(dataset,\n            something(findfirst(isequal(attribute), header), 0), target, c)\n\ninformation_gain(dataset::AbstractArray{T, 2}, attribute::Integer,\n                target::String, header::AbstractArray{String},\n                c::Integer=2) where {T} =\n    information_gain(dataset, attribute,\n            something(findfirst(isequal(target), header), 0), c)\n", "meta": {"hexsha": "9a76da346cc6c948e5dabdd1168960f14a379547", "size": 2013, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/measures.jl", "max_stars_repo_name": "laschuet/DecisionTrees.jl", "max_stars_repo_head_hexsha": "8b60255bba14d5e7fdf905dfe55bdd99781eec9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/measures.jl", "max_issues_repo_name": "laschuet/DecisionTrees.jl", "max_issues_repo_head_hexsha": "8b60255bba14d5e7fdf905dfe55bdd99781eec9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/measures.jl", "max_forks_repo_name": "laschuet/DecisionTrees.jl", "max_forks_repo_head_hexsha": "8b60255bba14d5e7fdf905dfe55bdd99781eec9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7115384615, "max_line_length": 75, "alphanum_fraction": 0.6264282166, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7789562273194708}}
{"text": "immutable Binomial <: DiscreteUnivariateDistribution\n    size::Int\n    prob::Float64\n    function Binomial(n::Real, p::Real)\n    \tif n <= 0\n\t    \terror(\"size must be positive\")\n\t    else\n\t    \tif 0.0 <= p <= 1.0\n\t    \t\tnew(int(n), float64(p))\n\t    \telse\n\t    \t\terror(\"prob must be in [0, 1]\")\n\t\t\tend\n\t    end\n\tend\nend\n\nBinomial(size::Integer) = Binomial(size, 0.5)\nBinomial() = Binomial(1, 0.5)\n\n@_jl_dist_2p Binomial binom\n\nentropy(d::Binomial) = d.size * (-xlogx(1.0 - d.prob) - xlogx(d.prob))\n\ninsupport(d::Binomial, x::Number) = isinteger(x) && 0 <= x <= d.size\n\nkurtosis(d::Binomial) = (1.0 - 2.0 * d.prob * (1.0 - d.prob)) / var(d)\n\nmean(d::Binomial) = d.size * d.prob\n\nmedian(d::Binomial) = iround(d.size * d.prob)\n\n# TODO: May need to subtract 1 sometimes\nmodes(d::Binomial) = iround((d.size + 1.0) * d.prob)\n\nfunction mgf(d::Binomial, t::Real)\n\tn, p = d.size, d.prob\n\treturn (1.0 - p + p * exp(t))^n\nend\n\nfunction cf(d::Binomial, t::Real)\n\tn, p = d.size, d.prob\n\treturn (1.0 - p + p * exp(im * t))^n\nend\n\nmodes(d::Binomial) = iround([d.size * d.prob])\n\n# TODO: rand() is totally screwed up\n\nskewness(d::Binomial) = (1.0 - 2.0 * d.prob) / std(d)\n\nvar(d::Binomial) = d.size * d.prob * (1.0 - d.prob)\n", "meta": {"hexsha": "669903ddfebd178baea453c2643ac0d73a86dc1c", "size": 1207, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/binomial.jl", "max_stars_repo_name": "mewo2/Distributions.jl", "max_stars_repo_head_hexsha": "00dd06fb13632b9f0259f036bb861e47b7170a76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-16T01:43:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-16T01:43:20.000Z", "max_issues_repo_path": "src/univariate/binomial.jl", "max_issues_repo_name": "mewo2/Distributions.jl", "max_issues_repo_head_hexsha": "00dd06fb13632b9f0259f036bb861e47b7170a76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/binomial.jl", "max_forks_repo_name": "mewo2/Distributions.jl", "max_forks_repo_head_hexsha": "00dd06fb13632b9f0259f036bb861e47b7170a76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2115384615, "max_line_length": 70, "alphanum_fraction": 0.5965202983, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7789482320341073}}
{"text": "using Plots\nusing Distributions\nusing Random\ngr(size=(300,300))\n\nfunction ellipse!(μ,Σ;kw...)\n    for i=1:3\n        plot!([tuple((i*sqrt(Σ)*[cos(t),sin(t)]+μ)...) for t in range(0,stop=2π,length=100)];\n              seriestype=:shape,linealpha=0.5,linecolor=:gray,fillalpha=[0.4,0.2,0.1][i],kw...)\n    end\n    current()\nend\n\nfunction mixtureplot(X₁,X₂,μ₀,Σ₀,μ₁,Σ₁,Π)\n    scatter(X₁,X₂;fillalpha=0.5,markerstrokewidth=0.5,\n        marker_z=Π,mc=ColorGradient([:lightblue,:orange]),\n        colorbar=:false)\n    ellipse!(μ₀,Σ₀,fillcolor=:lightblue)\n    ellipse!(μ₁,Σ₁,fillcolor=:orange)\n    plot!(;bg=:transparent,xlims=(-4.5,8.5),ylims=(-3.5,10.5),\n        leg=false,ticks=:none,ratio=:equal)\nend\n\nfunction scalein(x)\n    (x-1/2)^101/(0.5^101)\nend\n\nRandom.seed!(123);\nn = 100\nα = 0.4\n𝒩₀ = MvNormal([1,1],[2.0 1.0; 1.0 2.0])\n𝒩₁ = MvNormal([3.0,7.0],[1.5 0; 0 0.5])\nX₁ = zeros(n)\nX₂ = zeros(n)\nZ = zeros(Bool,n)\nfor i=1:n\n    Z[i] = rand(Bernoulli(α))\n    X₁[i],X₂[i] = Z[i] ? rand(𝒩₁) : rand(𝒩₀)\nend\n\nα = 0.6\nμ₀ = [3.0,3.0]\nμ₁ = [1.0,6.0]\nΣ₀ = 1.0*Matrix(I, 2, 2)\nΣ₁ = 1.0*Matrix(I, 2, 2)\nmixtureplot(X₁,X₂,μ₀,Σ₀,μ₁,Σ₁)\n\nΠ = [α*pdf(MvNormal(μ₁,Σ₁),[x₁,x₂]) /\n       ((1-α)*pdf(MvNormal(μ₀,Σ₀),[x₁,x₂]) +\n        α*pdf(MvNormal(μ₁,Σ₁),[x₁,x₂])) for (x₁,x₂) in zip(X₁,X₂)];\n\nα = sum(Π)/n\nμ₀ = [(1 .- Π) ⋅ X₁, (1 .- Π) ⋅ X₂] / sum(1 .- Π)\nμ₁ = [Π ⋅ X₁, Π ⋅ X₂] / sum(Π)\nΣ₀ = Matrix(Hermitian(sum((1-π)*([x₁,x₂] - μ₀) * ([x₁,x₂] - μ₀)' for (x₁,x₂,π) in zip(X₁,X₂,Π))/sum(1 .- Π)))\nΣ₁ = Matrix(Hermitian(sum(π*([x₁,x₂] - μ₁) * ([x₁,x₂] - μ₁)' for (x₁,x₂,π) in zip(X₁,X₂,Π))/sum(Π)))\nΠ = [α*pdf(MvNormal(μ₁,Σ₁),[x₁,x₂]) /\n       ((1-α)*pdf(MvNormal(μ₀,Σ₀),[x₁,x₂]) +\n        α*pdf(MvNormal(μ₁,Σ₁),[x₁,x₂])) for (x₁,x₂) in zip(X₁,X₂)];\n\nmixtureplot(X₁,X₂,μ₀,Σ₀,μ₁,Σ₁,Π)\n", "meta": {"hexsha": "d8cbb23a78476609d2278e4cc339ac47240cd175", "size": 1761, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/bayesian-inference-and-graphical-models/code/test.jl", "max_stars_repo_name": "seanrattana/courses", "max_stars_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-08-21T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T15:46:58.000Z", "max_issues_repo_path": "content/bayesian-inference-and-graphical-models/code/test.jl", "max_issues_repo_name": "seanrattana/courses", "max_issues_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-08-23T06:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-26T12:47:12.000Z", "max_forks_repo_path": "content/bayesian-inference-and-graphical-models/code/test.jl", "max_forks_repo_name": "seanrattana/courses", "max_forks_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-08-18T21:23:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T19:14:33.000Z", "avg_line_length": 28.4032258065, "max_line_length": 109, "alphanum_fraction": 0.5644520159, "num_tokens": 913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868805, "lm_q2_score": 0.8438951045175642, "lm_q1q2_score": 0.7789482302475025}}
{"text": "using OrdinaryDiffEq\nusing StaticArrays\nusing Plots\n\n\"\"\"\n    Duffing\n\nA Duffing equation with periodic forcing of the form\n\n```math\nmx″ + cx′ + kx + μx³ = F₀cos(ωt)\n```\n\"\"\"\nBase.@kwdef mutable struct Duffing\n    m::Float64 = 1.0\n    c::Float64 = 0.01\n    k::Float64 = 2.0\n    μ::Float64 = 1\n    F₀::Float64 = 0.05\n    ω::Float64 = 1.0\nend\n\n\"\"\"\n    rhs_dt(u, p::Duffing, t)\n\nReturn the right-hand side of the Duffing.\n\"\"\"\nfunction rhs_dt(u, p::Duffing, t)\n    x = u[1]\n    x′ = u[2]\n    f = p.F₀ * cos(p.ω * t)\n    # Use a static vector (SVector) for speed; it's not necessary for any other reason\n    return SVector(x′, (f - p.c * x′ - p.k * x - p.μ * x^3) / p.m)\nend\n\n\"\"\"\n    integrate(u, p::Duffing, t)\n\nReturn a solution of the Duffing equation over the time interval `t` starting at the initial\ncondition `u` with the parameters of the Duffing equation taken from `p`.\n\"\"\"\nfunction integrate(u, p::Duffing, t)\n    # Explicitly convert everything to Float64 in case integer values are used\n    # Use SVectors for speed (not necessary)\n    prob = ODEProblem(rhs_dt, SVector{2, Float64}(u), Float64.(t), p)\n    return solve(prob, Tsit5())\nend\n\n\"\"\"\n    example()\n\nRun an example Duffing equation simulation and plot the results.\n\"\"\"\nfunction example()\n    p = Duffing()\n    sol = integrate([0, 0], p, (0, 100))\n    plot(sol.t, sol[1,:])\nend\n\n# Code to benchmark the timings\n\n# using BenchmarkTools\n# p = Duffing()\n# @benchmark integrate($([0, 0]), $p, (0, 100))\n\n# Output on my laptop\n\n# BenchmarkTools.Trial:\n#   memory estimate:  60.34 KiB\n#   allocs estimate:  462\n#   --------------\n#   minimum time:     73.100 μs (0.00% GC)\n#   median time:      75.700 μs (0.00% GC)\n#   mean time:        90.955 μs (3.73% GC)\n#   maximum time:     3.807 ms (96.36% GC)\n#   --------------\n#   samples:          10000\n#   evals/sample:     1\n", "meta": {"hexsha": "334eb84af24ebe3335c92ef50ccfac8a86774b3e", "size": 1830, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ode_duffing.jl", "max_stars_repo_name": "dawbarton/julia-de-examples", "max_stars_repo_head_hexsha": "1e641c91c7edae87b52e03190ce31fc41eb5e764", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ode_duffing.jl", "max_issues_repo_name": "dawbarton/julia-de-examples", "max_issues_repo_head_hexsha": "1e641c91c7edae87b52e03190ce31fc41eb5e764", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ode_duffing.jl", "max_forks_repo_name": "dawbarton/julia-de-examples", "max_forks_repo_head_hexsha": "1e641c91c7edae87b52e03190ce31fc41eb5e764", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.164556962, "max_line_length": 92, "alphanum_fraction": 0.6081967213, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7789350699256212}}
{"text": "function BondNSxPs(m,b0,b1,b2,tau,b3=0.0,tau2=1.0)\n#BondNSxPs    Extended Nelson and Siegel (1987) spot rate, forward rate, and discount function\n#\n#\n#\n#\n#  Usage:    (s,f,d) = BondNSxPs(m,b0,b1,b2,tau[,b3[,tau2]])\n#\n#  Input:    m         NxK matrix  times to maturity in years (don't use less than 1e-8 or so)\n#            b0        scalar, beta0 parameter in NS\n#            b1        scalar, beta1 parameter in NS\n#            b2        scalar, beta2 parameter in NS\n#            tau       scalar, tau   parameter in NS\n#            b3        (optional) scalar, beta2 parameter in extended NS [0]\n#            tau2      (optional) scalar, tau2  parameter in extended NS [1]\n#\n#  Output:   s         NxK matrix,  spot rate (continously compounded)\n#            f         NxK matrix,  forward rate (continously compounded)\n#            d         NxK matrix,  discount function\n#\n#\n#\n#  Note:     For more details, see\n#            (a) Svensson (1995), \"Estimating Forward Interest Rates with\n#                the Extended Nelson & Siegel Method,\" Quarterly Review,\n#                Sveriges Riksbank, 1995:3, 13-26.\n#            (b) Soderlind and Svensson (1997), \"New Techniques to Extract\n#                Market Expectations from Financial Instruments,\"\n#                Journal of Monetary Economics 40, 383-429.\n#\n#\n#\n#  Paul.Soderlind@unisg.ch, April 2002, to Julia 2015\n#----------------------------------------------------------------------------*/\n\n                                                 #forward rate\n  f =  b0 .+ b1*exp.(-m/tau) + b2*(m/tau).*exp.(-m/tau) + b3*(m/tau2).*exp.(-m/tau2)\n\n  s =  b0 .+ b1* (1 .- exp.(-m/tau)) ./(m/tau) +\n             b2*((1 .- exp.(-m/tau)) ./(m/tau)  - exp.(-m/tau)) +\n             b3*((1 .- exp.(-m/tau2))./(m/tau2) - exp.(-m/tau2))        #spot rate\n\n  d = exp.(-s.*m)             #discount function\n\n  return s,f,d\n\nend\n#------------------------------------------------------------------------------\n\n\n#------------------------------------------------------------------------------\nfunction BondNSxEstPs(par0,Q,tm,c,s0,ytmLoss=0,weight=1.0)\n#BondNSxEstPs  Estimates parameters in (extended) Nelson-Siegel yield curve model by\n#              non-linear least squares (minimizing squared differences between\n#              actual and fitted bond prices or yield to maturities).\n#\n#\n#\n#  Usage:    NSb = BondNSxEstPs(par0,Q,tm,c,s0[,ytmLoss[,weight]])\n#\n#\n#  Input:    par0       4x1 or 6x1 vector, initial guess of paremeters\n#                         if 4x1: standard NS with par0 = [b0,b1,b2,tau]\n#                         if 6x1: extended NS with par0 = [b0,b1,b2,tau,b3,tau2]\n#            Q          nx1 vector, data on bond prices, eg. 1.01\n#            tm         nx1 vector, data on time to maturity (in years), eg. 2.54\n#            c          nx1 vector, data on bond coupons, eg. 0.06\n#            s0         scalar, restricted value of short rate:\n#                       if [] no restriction, else b0 + b1 = s0 is imposed\n#            ytmLoss    scalar, scalar, 0: mimimize squared price errors;\n#                                       1: minimize squared ytm errors (default 0)\n#            weight     scalar or nx1 vector, weights in the loss function\n#\n#  Output:   NSb        4x1 or 6x1 vector, estimated parameters\n#\n#\n#\n#  Note:     For more details, see\n#            (a) Svensson (1995), \"Estimating Forward Interest Rates with\n#                the Extended Neolson & Siegel Method,\" Quarterly Review,\n#                Sveriges Riksbank, 1995:3, 13-26.\n#            (b) Soderlind and Svensson (1997), \"New Techniques to Extract\n#                Market Expectations from Financial Instruments,\"\n#                Journal of Monetary Economics 40, 383-429.\n#\n#\n#  Uses:  Optim\n#\n#\n#\n#  Paul.Soderlind@unisg.ch, April 2002, to Julia Nov 2015\n#------------------------------------------------------------------------------\n\n  Qtc = [Q tm c]\n\n  if in(length(par0),[4,6]) && !isempty(s0)\n      par0 = deleteat!(par0,2)   #b1 = s0 - b0 is imposed by BondNSxLossPs\n  end\n\n  Sol = optimize(b->BondNSxLossPs(b,Qtc,s0,ytmLoss,weight),par0)\n  NSb = Optim.minimizer(Sol)\n  if !Optim.converged(Sol)\n    println(\"no convergence\")\n    return\n  end\n\n  if length(NSb) == 3\n    NSb[[1,3]] = abs.(NSb[[1,3]])\n    NSb        = [NSb[1]; s0-NSb[1]; NSb[2:3]]\n  elseif length(NSb) == 4\n    NSb[[1,4]] = abs.(NSb[[1,4]])\n  elseif length(NSb) == 5\n    NSb[[1,3,5]] = abs.(NSb[[1,3,5]])\n    NSb = [NSb[1]; s0-NSb[1]; NSb[2:5]]\n  elseif length(NSb) == 6\n    NSb[[1,4,6]] = abs.(NSb[[1,4,6]])\n  end\n\n  return NSb\n\nend\n#----------------------------------------------------------------------------\n\n\n#------------------------------------------------------------------------------\nfunction BondNSxLossPs(b,Qtc,s0,ytmLoss=0,weight=1.0)\n#BondNSxLossPs    Defines loss function for bond prices in extended Nelson-Siegel model.\n#                 Used for estimation of the parameters in the model by minimizing\n#                 Loss (squared price deviations, possibly with weights).\n#\n#\n#  Usage:    Loss = BondNSxLossPs(b,Qtc,s0,ytmLoss,weight)    or\n#                 = BondNSxLossPs(b,Qtc,s0,ytmLoss)           or\n#                 = BondNSxLossPs(b,Qtc,s0)\n#\n#  Input:    b         3x1, 4x1, 5x1, or 6x1 vector with parameters in Nelson-Siegel model\n#                        if 3x1: [b0,b2,tau], NS with restriction that b1 = g_s0 - b0\n#                        if 4x1: [b0,b1,b2,tau], NS without restrictions\n#                        if 5x1: [b0,b2,tau,b3,tau2], extended NS with restriction that b1 = g_s0 - b0\n#                        if 6x1: [b0,b1,b2,tau,b3,tau2], extended NS without restrictions\n#            Qtc       nx3 matrix, data on [bond prices,time to maturity,coupons]. Use ytm instead\n#                      of bond prices if ytmLoss==1\n#            s0        scalar, restricted value of short rate\n#            ytmLoss   scalar, 0: mimimize squared price errors;\n#                      1: minimize squared ytm errors (default 0)\n#            weight    scalar or nx1 vector, weights in the loss function\n#\n#  Output:   Loss    scalar, sum of squared differences between implied and actual bond\n#                    prices (or yields)\n#\n#  Calls on: BondNSxPs, BondYieldToMatPs (if ytmLoss==1)\n#\n#------------------------------------------------------------------------------\n\n  (Q,tm,c) = [Qtc[:,i] for i=1:3]       #data on bond prices, time to maturity, coupons\n  n        = length(c)           #number of bonds\n\n  if length(b) == 3             #standard Nelson-Siegel with restriction b1 = s0-b0\n    (b0,b1,b2,tau,b3,tau2) = (abs(b[1]),s0-abs(b[1]),b[2],abs(b[3]),0.0,1.0)\n  elseif length(b) == 4         #standard Nelson-Siegel\n   (b0,b1,b2,tau,b3,tau2)  = (abs(b[1]),b[2],b[3],abs(b[4]),0.0,1.0)\n  elseif length(b) == 5         #extended Nelson-Siegel with restriction b1 = s0 - b0\n    (b0,b1,b2,tau,b3,tau2) = (abs(b[1]),s0-abs(b[1]),b[2],abs(b[3]),b[4],abs(b[5]))\n  elseif length(b) == 6         #extended Nelson-Siegel\n   (b0,b1,b2,tau,b3,tau2)  = (abs(b[1]),b[2],b[3],abs(b[4]),b[5],abs(b[6]))\n  end\n\n  QNS = fill(NaN,n)\n  for i = 1:n                            #loop over bonds\n    ti     = filter(z->z>0,mod(tm[i],1):tm[i])      #time to coupon payments, >0 only\n    d      = BondNSxPs(ti,b0,b1,b2,tau,b3,tau2)[3]  #NSx: spot, forward, discount fn\n    QNS[i] = sum(d.*c[i]) + d[end]                  #fitted bond price\n    if ytmLoss == 1\n      QNS[i] = BondYieldToMatPs(QNS[i],c[i],ti,1,1,0.05,1e-7)  #fitted ytm\n    end\n  end\n  Loss = 1.0 + 100*sum( weight.*(QNS - Q).^2 )  #weighted sum of squared deviations of fitted from actual\n\n  return Loss\n\nend\n#------------------------------------------------------------------------------\n", "meta": {"hexsha": "32a1b5274a070560c8be67ad3d32e2864d045eab", "size": 7705, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "NelsonSiegel/jlFiles/BondNSxPs.jl", "max_stars_repo_name": "PaulSoderlind/PaulSoderlindCode", "max_stars_repo_head_hexsha": "849ab977e410ece42d24ec86a4e043180200c551", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2016-01-15T21:13:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T21:21:18.000Z", "max_issues_repo_path": "NelsonSiegel/jlFiles/BondNSxPs.jl", "max_issues_repo_name": "PaulSoderlind/PaulSoderlindCode", "max_issues_repo_head_hexsha": "849ab977e410ece42d24ec86a4e043180200c551", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-03-05T13:07:59.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-07T11:11:21.000Z", "max_forks_repo_path": "NelsonSiegel/jlFiles/BondNSxPs.jl", "max_forks_repo_name": "PaulSoderlind/PaulSoderlindCode", "max_forks_repo_head_hexsha": "849ab977e410ece42d24ec86a4e043180200c551", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2016-03-05T13:01:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T19:44:57.000Z", "avg_line_length": 42.1038251366, "max_line_length": 105, "alphanum_fraction": 0.5138221934, "num_tokens": 2352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7789350663493176}}
{"text": "\"\"\"\n    natural_eigdist(𝚽, 𝛌, Q; α = 1.0, T = :Inf,\n                    input_format = :zero_measures, distance = :DAG,\n                    edge_weight = 1, edge_length = 1)\n\ncompute natural distances between graph Laplacian eigenvectors.\n\n# Input Arguments\n- `𝚽::Matrix{Float64}`: matrix of (weighted) graph Laplacian eigenvectors.\n- `𝛌::Vector{Float64}`: vector of eigenvalues.\n- `Q::Matrix{Float64}`: unweighted incidence matrix of the graph.\n- `α::Float64`: ROT parameter. (default: `1.0`)\n- `T::Any`: TSD parameter, i.e., the stopping time T in K_functional (default: `:Inf`)\n- `input_format::Symbol`: options: `:zero_measures`, `:pmf1` and `:pmf2` (default: `:zero_measures`)\n- `distance::Symbol`: options: `:ROT`, `:HAD`, `:DAG` and `:TSD` (default: `:DAG`)\n- `edg_length::Any`: vector of edge lengths (default: 1 represents unweighted graphs)\n- `edge_weight::Any`: the weights vector, which stores the affinity weight of\n    each edge (default: `1` represents unweighted graphs).\n\n# Output Argument\n- `dis::Matrix{Float64}`: the distance matrix, dis[i,j] = d(𝜙ᵢ₋₁, 𝜙ⱼ₋₁).\n\n\"\"\"\nfunction natural_eigdist(𝚽, 𝛌, Q; α = 1.0, T = :Inf,\n                         input_format = :zero_measures, distance = :DAG,\n                         edge_weight = 1, edge_length = 1)\n    N = size(Q, 1)\n    P = deepcopy(𝚽)\n    if input_format == :zero_measures\n        P[:, 1] .= 0\n    elseif input_format == :pmf1\n        P = P.^2\n    elseif input_format == :pmf2\n        P = exp.(P) ./ sum(exp.(P), dims = 1)\n    else\n        @error(\"input_format does not support $(input_format)!\")\n        return\n    end\n\n    if distance == :ROT\n        D = eigROT_Distance(P, Q; edge_length = edge_length, α = α)\n    elseif distance == :HAD\n        D = eigHAD_Distance(𝚽, 𝛌)\n    elseif distance == :DAG\n        D = eigDAG_Distance(𝚽, Q, N; edge_weight = edge_weight)\n    elseif distance == :TSD\n        tL = Q * Q'\n        t𝛌, t𝚽 = eigen(Matrix(tL))\n        D = eigTSD_Distance(P, t𝚽, t𝛌, Q; length = edge_length, T = T)\n    else\n        error(\"distance does not support $(distance)!\")\n        return\n    end\n\n    return D\nend\n", "meta": {"hexsha": "633690ce426672dafbd6841f723346af7e32b7e6", "size": 2101, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/natural_distances.jl", "max_stars_repo_name": "BoundaryValueProblems/MTSG.jl", "max_stars_repo_head_hexsha": "8cf8e2b3035876b5ceda45109b0847a60b581a7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-02T18:39:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-19T15:45:17.000Z", "max_issues_repo_path": "src/natural_distances.jl", "max_issues_repo_name": "haotian127/MultiscaleGraphSignalTransforms.jl", "max_issues_repo_head_hexsha": "85ba99e505283491ac69e979737bbb712b698a6e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2021-04-27T23:00:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-03T11:03:17.000Z", "max_forks_repo_path": "src/natural_distances.jl", "max_forks_repo_name": "haotian127/MultiscaleGraphSignalTransforms.jl", "max_forks_repo_head_hexsha": "85ba99e505283491ac69e979737bbb712b698a6e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-04-24T21:46:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T04:32:31.000Z", "avg_line_length": 36.8596491228, "max_line_length": 100, "alphanum_fraction": 0.6030461685, "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7789350643585958}}
{"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    euclidsq(x, y)\n\nReturn the Euclidean distance between two indexable objects.\n\"\"\"\neuclidsq(x, y) = sum((x[i] - y[i])^2 for i in eachindex(x))\n\n# Support matrix data in a GPU and AD compatible way\n\n\"\"\"\n    euclidsq(X::T, Y::T) where {T<:AbstractMatrix}\n\nReturn the Euclidean distance between columns in two matrices.\n\"\"\"\nfunction euclidsq(X::T, Y::T) where {T<:AbstractMatrix}\n    XiXj = transpose(X) * Y\n    x² = sum(X .^ 2; dims=1)\n    y² = sum(Y .^ 2; dims=1)\n    transpose(x²) .+ y² - 2XiXj\nend\n\n\"\"\"\n    euclidsq(X::T) where {T<:AbstractMatrix}\n\nEffective version of `euclidsq(X, X)`.\n\"\"\"\nfunction euclidsq(X::T) where {T<:AbstractMatrix}\n    XiXj = transpose(X) * X\n    x² = sum(X .^ 2; dims=1)\n    transpose(x²) .+ x² - 2XiXj\nend\n\n\"\"\"\n    gaussian_gramian(xs, ys, σ=1)\n\nGramian matrix for samples `xs` and `ys` using a Gaussian kernel\nkernel with bandwidth `σ`.\n\"\"\"\ngaussian_gramian(xs; kwargs...) = gaussian_gramian(xs, xs; kwargs...)\ngaussian_gramian(xs, ys; σ=1) =\n  [exp(-euclidsq(x, y) / 2σ^2) for x in xs, y in ys]\n\nfunction gaussian_gramian(X::T, Y::T; σ=1) where {T<:AbstractMatrix}\n    gaussian_gramian(euclidsq(X, Y), σ)\nend\n\ngaussian_gramian(esq, σ::AbstractFloat) = exp.(-esq ./ 2σ^2)\n\n\"\"\"\n    safe_diagm(mat, a)\n\nGenerate a squared matrix whose diagonal is `a` that is \ncompatible to perform addition on `mat`. It hebaves \ndifferently based on `mat` is on CPU or GPU.\n\nIt is compatible with\n- CuArrays.jl (see lib/cuarrays.jl)\n- Zygote.jl (see lib/zygote.jl)\n\"\"\"\nsafe_diagm(mat, a) = a * I\n", "meta": {"hexsha": "82e80c8d2abf21968c70e895cd245342306c02e4", "size": 1721, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "JuliaEarth/DensityRatioEstimation.jl", "max_stars_repo_head_hexsha": "f8b14d4d28d5aaafb7d2b95a04b55e69cbc3f9ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-02-08T04:03:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T13:22:41.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "xukai92/DensityRatioEstimation.jl", "max_issues_repo_head_hexsha": "6bafd1354026b887c6721fce60df85a28d4a436f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2019-09-19T22:48:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-22T18:52:24.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "xukai92/DensityRatioEstimation.jl", "max_forks_repo_head_hexsha": "6bafd1354026b887c6721fce60df85a28d4a436f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-28T21:53:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T21:53:19.000Z", "avg_line_length": 26.4769230769, "max_line_length": 69, "alphanum_fraction": 0.6083672284, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896737173119, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7789350554684792}}
{"text": "# These methods are used solely to help the auto-arima algorithm\n# Kwiatkowski, D.; \n# Phillips, P. C. B.; \n# Schmidt, P.; \n# Shin, Y. (1992)\n# \"Testing the null hypothesis \n#  of stationarity against the \n#  alternative of a unit root\"\n\nfunction calc_lag_kpss(lags::Bool, n::Int)\n    return lags ? trunc(Int, 4*(n/100)^0.25) : trunc(Int, 12*(n/100)^0.25)\nend\n\nfunction σ²_estimator(l::Int, n::Int, ϵ::Vector{Fl}) where Fl\n    return ((1/n)*sum(ϵ[t]^2 for t in 1:n)) + ((2/n)*sum((1-(s/(l + 1))) * (sum(ϵ[t]*ϵ[t - s] for t in s + 1:n)) for s in 1:l))\nend\n\nfunction p_value_weighted_average(η::Fl, p1::Fl, cv1::Fl, \n                                  p2::Fl, cv2::Fl) where Fl\n    return ((p1*(cv1 - cv2)) - ((cv1 - η)*(p1 - p2)))/(cv1 - cv2)\nend\n\nfunction p_value_from_η(η::Fl, crit_vals::Vector{Fl}) where Fl\n    if η >= crit_vals[1]\n        p_value = 0.01\n    elseif η < crit_vals[1] && η >= crit_vals[2]\n        p_value = p_value_weighted_average(η, 0.01, crit_vals[1], 0.025, crit_vals[2])\n    elseif η < crit_vals[2] && η >= crit_vals[3]\n        p_value = p_value_weighted_average(η, 0.025, crit_vals[2], 0.05, crit_vals[3])\n    elseif η < crit_vals[3] && η <= crit_vals[4]\n        p_value = p_value_weighted_average(η, 0.05, crit_vals[3], 0.1, crit_vals[4])\n    else\n        p_value = 0.1\n    end\n    return p_value\nend\n\nfunction calc_η_level(y::Vector{Fl}, lags::Bool) where Fl\n    n = length(y)\n    ϵ = y .- (mean(y))\n    l = calc_lag_kpss(lags, n)\n    η = (1/n^2)*sum(sum((((sum(ϵ[i] for i in 1:t))^2)/σ²_estimator(l, n, ϵ)) for t in 1:n))\n    return η\nend\n\nfunction kpss_test(y::Vector{Fl}; lags::Bool = true) where Fl\n    η = calc_η_level(y, lags)\n    crit_vals = [0.739, 0.574, 0.463, 0.347]\n    p_value = p_value_from_η(η, crit_vals)\n    return p_value\nend", "meta": {"hexsha": "6c78cd09f22c346336567653932a28a69c5d855d", "size": 1768, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/statistical_tests/kpss.jl", "max_stars_repo_name": "gionikola/StateSpaceModels.jl", "max_stars_repo_head_hexsha": "477426b6b1a40809b793bdc46574bfa3909e6182", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 189, "max_stars_repo_stars_event_min_datetime": "2018-03-08T18:13:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:55:22.000Z", "max_issues_repo_path": "src/statistical_tests/kpss.jl", "max_issues_repo_name": "PaulMainwood/StateSpaceModels.jl", "max_issues_repo_head_hexsha": "b1723e74f3c6243020a9909d49639a3ca8325985", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 270, "max_issues_repo_issues_event_min_datetime": "2018-04-02T15:48:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:35:16.000Z", "max_forks_repo_path": "src/statistical_tests/kpss.jl", "max_forks_repo_name": "PaulMainwood/StateSpaceModels.jl", "max_forks_repo_head_hexsha": "b1723e74f3c6243020a9909d49639a3ca8325985", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2019-07-24T14:56:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T17:13:07.000Z", "avg_line_length": 34.6666666667, "max_line_length": 127, "alphanum_fraction": 0.6040723982, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699844, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7789350535790422}}
{"text": "module Mandelbrot\nexport mandelbrot_image, mandelbrot\n\nusing Base.Threads\n\nfunction mandelbrot(c::Complex, max_iter::Int)\n    z = 0.0 + 0.0im\n    for i in 1:max_iter\n        z = z^2 + c\n        if abs(z) > 2\n            return max_iter - i\n        end\n    end\n    return 0\nend\n\nfunction mandelbrot_image(width, height, max_iter = 1000; rmin = -2, rmax = 1, imin = -1, imax = 1)\n    A = [\n        Complex((j/width * (rmax - rmin) + rmin), (i/height * (imax - imin) + imin))\n        for i in 1:height, j in 1:width\n    ]\n\n    set = Array{Int}(undef, height, width)\n\n    @time @inbounds @threads for i in 1:height\n        for j in 1:width\n            set[i, j] = mandelbrot(A[i, j], max_iter)\n        end\n    end\n\n    return set\nend\n\nend\n", "meta": {"hexsha": "1217e001c17c3b58445c3309c1c343d9862e231a", "size": 735, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Mandelbrot.jl", "max_stars_repo_name": "VasanthManiVasi/Mandelbrot.jl", "max_stars_repo_head_hexsha": "a2e2507810bb0831694635968ae3389f55bc8c11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-05T04:19:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T04:19:26.000Z", "max_issues_repo_path": "src/Mandelbrot.jl", "max_issues_repo_name": "VasanthManiVasi/Mandelbrot.jl", "max_issues_repo_head_hexsha": "a2e2507810bb0831694635968ae3389f55bc8c11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Mandelbrot.jl", "max_forks_repo_name": "VasanthManiVasi/Mandelbrot.jl", "max_forks_repo_head_hexsha": "a2e2507810bb0831694635968ae3389f55bc8c11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0, "max_line_length": 99, "alphanum_fraction": 0.5673469388, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810525948927, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.778926403905965}}
{"text": "firstPayment = 3000\ni = 0.12\nm = 12\n\n# (A/P, i, N)\nfunction capitalRecoveryFactor(i, N)\n\t(i * (1 + i)^N) / ((i+1)^N - 1)\nend\n\n# Find: How much the guy paid the student\nP = firstPayment / (1 + i/m)^(m * 1/12)\nA = P * capitalRecoveryFactor(i/m, 12)\nC = A * 1 / capitalRecoveryFactor(i/m, 5) + A + 1000\n\nprintln(\"Guy paid: \", C)\n", "meta": {"hexsha": "761ebb35c494237462c224cf94fa95d2c30c4c75", "size": 326, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps2/p6.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/ps2/p6.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/ps2/p6.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.375, "max_line_length": 52, "alphanum_fraction": 0.5950920245, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7789264014629919}}
{"text": "function hermite_polynomial_coefficient_matrix(left,right)\r\n    [1.0   left   left^2   left^3\r\n     0.0   1.0   2.0*left  3.0*(left^2)\r\n     1.0   right  right^2  right^3\r\n     0.0   1.0   2.0*right 3.0*right^2]\r\nend\r\n\r\n\r\n\r\nfunction hermite_polynomial_coefficients(left,right)\r\n    M = hermite_polynomial_coefficient_matrix(left,right)\r\n    coeffs = M\\I\r\nend\r\n\r\nfunction hermite_polynomials(x,left,right)\r\n    coeffs = hermite_polynomial_coefficients(left,right)\r\n    order,numbasis = size(coeffs)\r\n    return [polynomial_from_coefficients(x,coeffs[:,i]) for i = 1:numbasis]\r\nend\r\n", "meta": {"hexsha": "d01b57b5d98950672ba5ebd42060972ddf805d57", "size": 581, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hermite_polynomials.jl", "max_stars_repo_name": "ArjunNarayanan/PolynomialBasis.jl", "max_stars_repo_head_hexsha": "09a3479154639c45a285d559508aa0092dfedad6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hermite_polynomials.jl", "max_issues_repo_name": "ArjunNarayanan/PolynomialBasis.jl", "max_issues_repo_head_hexsha": "09a3479154639c45a285d559508aa0092dfedad6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hermite_polynomials.jl", "max_forks_repo_name": "ArjunNarayanan/PolynomialBasis.jl", "max_forks_repo_head_hexsha": "09a3479154639c45a285d559508aa0092dfedad6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.05, "max_line_length": 76, "alphanum_fraction": 0.6850258176, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7788823058501578}}
{"text": "\"\"\"\nFLOYDWARSHALL\n-------------\n    compute all shortest paths using the Floyd-Warshall algorithm.\n    \n    (D,P) = floydwarshall(A) returns the shortest distance matrix between all pairs\n    of nodes in the graph A in matrix D.  If A has a negative weight cycle, then this\n    algorithm will throw an error. P is the matrix of predecessors.\n\nFunctions\n---------\n- (D,P) = floydwarshall(A::MatrixNetwork)\n- (D,P) = floydwarshall{T}(A::SparseMatrixCSC{T,Int64})\n\nExample\n-------\n~~~\nA = load_matrix_network(\"all_shortest_paths_example\")\n(D,P) = floydwarshall(A)\n~~~\n\"\"\"\n:floydwarshall\n\n## setup functions:\n\nfunction floydwarshall_phase1(A::MatrixNetwork)\n    (nzi,nzj,nzv) = csr_to_sparse(A.rp,A.ci,A.vals,A.n)\n    return (nzi,nzj,nzv,A.n)\nend\n\nfunction floydwarshall_phase1{T}(A::SparseMatrixCSC{T,Int64})\n    (ri,ci,ai) = findnz(A)\n    return (ri,ci,ai,A.n)\nend\n\nfunction floydwarshall_phase2{T}(ri::Vector{Int64},ci::Vector{Int64},ai::Vector{T},n::Int64)\n\n    nz = length(ai)\n    D = Inf*ones(Int64,n,n)\n    \n    #TODO: check: always compute P or give the option of just computing D?\n    \n    P = zeros(Int64,n,n)\n    # initialize the distance and predecessor matrix\n    for ei = 1:nz\n        i = ri[ei]\n        j = ci[ei]\n        v = ai[ei]\n        if v < D[i,j]\n            D[i,j] = v\n            P[i,j] = i\n        end\n    end\n    \n    ids = sub2ind((n,n),1:n,1:n)\n    D[ids] = 0 # set diagonal to 0\n    \n    for k=1:n\n        for i=1:n\n            for j=1:n\n                if D[i,k]+D[k,j] < D[i,j]\n                    D[i,j] = D[i,k]+D[k,j]\n                    P[i,j] = P[k,j]\n                end\n            end\n        end\n    end\n    \n    if any(diag(D).<0)\n        warn(\"floydwarshall:negativeCycle\",\"negative weight cycle detected\")\n    end\n    \n    return (D,P)\nend\n\n\n## floyd warshall\nfunction floydwarshall(A::MatrixNetwork)\n    (nzi,nzj,nzv,n) = floydwarshall_phase1(A)\n    (D,P) = floydwarshall_phase2(nzi,nzj,nzv,n)\n    return (D,P)\nend\n\nfunction floydwarshall{T}(A::SparseMatrixCSC{T,Int64})\n    (nzi,nzj,nzv,n) = floydwarshall_phase1(A)\n    (D,P) = floydwarshall_phase2(nzi,nzj,nzv,n)\n    return (D,P)\nend\n", "meta": {"hexsha": "3f456ac375878dbac46ec67b49d14e1b2b2d4681", "size": 2127, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/floydwarshall.jl", "max_stars_repo_name": "MeherChaitanya04/Julia", "max_stars_repo_head_hexsha": "644e96c3109f7210c6a71898fc61a777ba20d49b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/floydwarshall.jl", "max_issues_repo_name": "MeherChaitanya04/Julia", "max_issues_repo_head_hexsha": "644e96c3109f7210c6a71898fc61a777ba20d49b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/floydwarshall.jl", "max_forks_repo_name": "MeherChaitanya04/Julia", "max_forks_repo_head_hexsha": "644e96c3109f7210c6a71898fc61a777ba20d49b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8988764045, "max_line_length": 92, "alphanum_fraction": 0.5876821815, "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7788466102035513}}
{"text": "\nusing Turing, Distributions, DifferentialEquations\n\n# Import MCMCChain, Plots, and StatsPlots for visualizations and diagnostics.\nusing MCMCChains, Plots, StatsPlots\n\n# Set a seed for reproducibility.\nusing Random\nRandom.seed!(14);\n\n\nfunction lotka_volterra(du,u,p,t)\n  x, y = u\n  α, β, γ, δ  = p\n  du[1] = (α - β*y)x # dx =\n  du[2] = (δ*x - γ)y # dy =\nend\np = [1.5, 1.0, 3.0, 1.0]\nu0 = [1.0,1.0]\nprob1 = ODEProblem(lotka_volterra,u0,(0.0,10.0),p)\nsol = solve(prob1,Tsit5())\nplot(sol)\n\n\nsol1 = solve(prob1,Tsit5(),saveat=0.1)\nodedata = Array(sol1) + 0.8 * randn(size(Array(sol1)))\nplot(sol1, alpha = 0.3, legend = false); scatter!(sol1.t, odedata')\n\n\nTuring.setadbackend(:forwarddiff)\n\n@model function fitlv(data, prob1)\n    σ ~ InverseGamma(2, 3) # ~ is the tilde character\n    α ~ truncated(Normal(1.5,0.5),0.5,2.5)\n    β ~ truncated(Normal(1.2,0.5),0,2)\n    γ ~ truncated(Normal(3.0,0.5),1,4)\n    δ ~ truncated(Normal(1.0,0.5),0,2)\n\n    p = [α,β,γ,δ]\n    prob = remake(prob1, p=p)\n    predicted = solve(prob,Tsit5(),saveat=0.1)\n\n    for i = 1:length(predicted)\n        data[:,i] ~ MvNormal(predicted[i], σ)\n    end\nend\n\nmodel = fitlv(odedata, prob1)\n\n# This next command runs 3 independent chains without using multithreading.\nchain = mapreduce(c -> sample(model, NUTS(.65),1000), chainscat, 1:3)\n\n\nplot(chain)\n\n\npl = scatter(sol1.t, odedata');\n\n\nchain_array = Array(chain)\nfor k in 1:300\n    resol = solve(remake(prob1,p=chain_array[rand(1:1500), 1:4]),Tsit5(),saveat=0.1)\n    plot!(resol, alpha=0.1, color = \"#BBBBBB\", legend = false)\nend\n# display(pl)\nplot!(sol1, w=1, legend = false)\n\n\n@model function fitlv2(data, prob1) # data should be a Vector\n    σ ~ InverseGamma(2, 3) # ~ is the tilde character\n    α ~ truncated(Normal(1.5,0.5),0.5,2.5)\n    β ~ truncated(Normal(1.2,0.5),0,2)\n    γ ~ truncated(Normal(3.0,0.5),1,4)\n    δ ~ truncated(Normal(1.0,0.5),0,2)\n\n    p = [α,β,γ,δ]\n    prob = remake(prob1, p=p)\n    predicted = solve(prob,Tsit5(),saveat=0.1)\n\n    for i = 1:length(predicted)\n        data[i] ~ Normal(predicted[i][2], σ) # predicted[i][2] is the data for y - a scalar, so we use Normal instead of MvNormal\n    end\nend\n\nmodel2 = fitlv2(odedata[2,:], prob1)\n\n\nThreads.nthreads()\n\n\n# This next command runs 3 independent chains with multithreading.\nchain2 = sample(model2, NUTS(.45), MCMCThreads(), 5000, 3, progress=false)\n\n\npl = scatter(sol1.t, odedata');\nchain_array2 = Array(chain2)\nfor k in 1:300\n    resol = solve(remake(prob1,p=chain_array2[rand(1:12000), 1:4]),Tsit5(),saveat=0.1)\n    # Note that due to a bug in AxisArray, the variables from the chain will be returned always in\n    # the order it is stored in the array, not by the specified order in the call - :α, :β, :γ, :δ\n    plot!(resol, alpha=0.1, color = \"#BBBBBB\", legend = false)\nend\n#display(pl)\nplot!(sol1, w=1, legend = false)\n\n\nfunction delay_lotka_volterra(du, u, h, p, t)\n   x, y = u\n   α, β, γ, δ = p\n   du[1] = α * h(p, t-1; idxs=1) - β * x * y\n   du[2] = -γ * y + δ * x * y\n   return\nend\n\np = (1.5,1.0,3.0,1.0)\nu0 = [1.0; 1.0]\ntspan = (0.0,10.0)\nh(p, t; idxs::Int) = 1.0\nprob1 = DDEProblem(delay_lotka_volterra,u0,h,tspan,p)\n\n\nsol = solve(prob1,saveat=0.1)\nddedata = Array(sol)\nddedata = ddedata + 0.5 * randn(size(ddedata))\n\n\nscatter(sol.t, ddedata'); plot!(sol)\n\n\nTuring.setadbackend(:forwarddiff)\n@model function fitlv(data, prob1)\n\n    σ ~ InverseGamma(2, 3)\n    α ~ Truncated(Normal(1.5,0.5),0.5,2.5)\n    β ~ Truncated(Normal(1.2,0.5),0,2)\n    γ ~ Truncated(Normal(3.0,0.5),1,4)\n    δ ~ Truncated(Normal(1.0,0.5),0,2)\n\n    p = [α,β,γ,δ]\n\n    #prob = DDEProblem(delay_lotka_volterra,u0,_h,tspan,p)\n    prob = remake(prob1, p=p)\n    predicted = solve(prob,saveat=0.1)\n    for i = 1:length(predicted)\n        data[:,i] ~ MvNormal(predicted[i], σ)\n    end\nend;\nmodel = fitlv(ddedata, prob1)\n\n\nchain = sample(model, NUTS(.65), MCMCThreads(), 300, 3, progress=true)\nplot(chain)\n\n\nchain\n\n\npl = scatter(sol.t, ddedata')\nchain_array = Array(chain)\nfor k in 1:100\n    resol = solve(remake(prob1,p=chain_array[rand(1:450),1:4]),Tsit5(),saveat=0.1)\n    # Note that due to a bug in AxisArray, the variables from the chain will be returned always in\n    # the order it is stored in the array, not by the specified order in the call - :α, :β, :γ, :δ\n\n    plot!(resol, alpha=0.1, color = \"#BBBBBB\", legend = false)\nend\n#display(pl)\nplot!(sol)\n\n\nusing Zygote, DiffEqSensitivity\nTuring.setadbackend(:zygote)\nprob1 = ODEProblem(lotka_volterra,u0,(0.0,10.0),p)\n\n\n@model function fitlv(data, prob)\n    σ ~ InverseGamma(2, 3)\n    α ~ truncated(Normal(1.5,0.5),0.5,2.5)\n    β ~ truncated(Normal(1.2,0.5),0,2)\n    γ ~ truncated(Normal(3.0,0.5),1,4)\n    δ ~ truncated(Normal(1.0,0.5),0,2)\n    p = [α,β,γ,δ]\n    prob = remake(prob, p=p)\n\n    predicted = solve(prob,saveat=0.1)\n    for i = 1:length(predicted)\n        data[:,i] ~ MvNormal(predicted[i], σ)\n    end\nend;\nmodel = fitlv(odedata, prob1)\nchain = sample(model, NUTS(.65),1000)\n\n\n@model function fitlv(data, prob)\n    σ ~ InverseGamma(2, 3)\n    α ~ truncated(Normal(1.5,0.5),0.5,2.5)\n    β ~ truncated(Normal(1.2,0.5),0,2)\n    γ ~ truncated(Normal(3.0,0.5),1,4)\n    δ ~ truncated(Normal(1.0,0.5),0,2)\n    p = [α,β,γ,δ]\n    prob = remake(prob, p=p)\n    predicted = solve(prob,saveat=0.1,sensealg=InterpolatingAdjoint(autojacvec=ReverseDiffVJP(true)))\n    for i = 1:length(predicted)\n        data[:,i] ~ MvNormal(predicted[i], σ)\n    end\nend;\nmodel = fitlv(odedata, prob1)\n@time chain = sample(model, NUTS(.65),1000)\n\n\nu0 = [1.0,1.0]\ntspan = (0.0,10.0)\nfunction multiplicative_noise!(du,u,p,t)\n  x,y = u\n  du[1] = p[5]*x\n  du[2] = p[6]*y\nend\np = [1.5,1.0,3.0,1.0,0.1,0.1]\n\nfunction lotka_volterra!(du,u,p,t)\n  x,y = u\n  α,β,γ,δ = p\n  du[1] = dx = α*x - β*x*y\n  du[2] = dy = δ*x*y - γ*y\nend\n\n\nprob_sde = SDEProblem(lotka_volterra!,multiplicative_noise!,u0,tspan,p)\n\nensembleprob = EnsembleProblem(prob_sde)\n@time data = solve(ensembleprob,SOSRI(),saveat=0.1,trajectories=1000)\nplot(EnsembleSummary(data))\n\n\nTuring.setadbackend(:forwarddiff)\n@model function fitlv(data, prob)\n    σ ~ InverseGamma(2,3)\n    α ~ truncated(Normal(1.3,0.5),0.5,2.5)\n    β ~ truncated(Normal(1.2,0.25),0.5,2)\n    γ ~ truncated(Normal(3.2,0.25),2.2,4.0)\n    δ ~ truncated(Normal(1.2,0.25),0.5,2.0)\n    ϕ1 ~ truncated(Normal(0.12,0.3),0.05,0.25)\n    ϕ2 ~ truncated(Normal(0.12,0.3),0.05,0.25)\n    p = [α,β,γ,δ,ϕ1,ϕ2]\n    prob = remake(prob, p=p)\n    predicted = solve(prob,SOSRI(),saveat=0.1)\n\n    if predicted.retcode != :Success\n        Turing.acclogp!(_varinfo, -Inf)\n    end\n    for j in 1:length(data)\n        for i = 1:length(predicted)\n            data[j][i] ~ MvNormal(predicted[i],σ)\n        end\n    end\nend;\n\n\nmodel = fitlv(data, prob_sde)\nchain = sample(model, NUTS(0.25), 5000, init_theta = [1.5,1.3,1.2,2.7,1.2,0.12,0.12])\nplot(chain)\n\n\nif isdefined(Main, :TuringTutorials)\n    Main.TuringTutorials.tutorial_footer(WEAVE_ARGS[:folder], WEAVE_ARGS[:file])\nend\n\n", "meta": {"hexsha": "6d3e400926e38eca8118c2bb89d29aad37178ecc", "size": 6881, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/10-bayesian-differential-equations/10_bayesian-differential-equations.jl", "max_stars_repo_name": "leachim/TuringTutorials", "max_stars_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 154, "max_stars_repo_stars_event_min_datetime": "2018-08-13T17:04:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T06:28:19.000Z", "max_issues_repo_path": "script/10-bayesian-differential-equations/10_bayesian-differential-equations.jl", "max_issues_repo_name": "leachim/TuringTutorials", "max_issues_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 137, "max_issues_repo_issues_event_min_datetime": "2018-09-06T21:56:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T07:36:07.000Z", "max_forks_repo_path": "script/10-bayesian-differential-equations/10_bayesian-differential-equations.jl", "max_forks_repo_name": "leachim/TuringTutorials", "max_forks_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 82, "max_forks_repo_forks_event_min_datetime": "2018-09-17T15:57:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T04:54:57.000Z", "avg_line_length": 25.6753731343, "max_line_length": 129, "alphanum_fraction": 0.6349367824, "num_tokens": 2671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7788466085748481}}
{"text": "# rmsd100\n# root mean-squared difference between two arrays in %\n\nexport rmsd100\n\nusing LinearAlgebra: norm\n\n\n\"\"\"\n    rmsd = rmsd100(x, y ; mask)\n\nCompute 100 * RMSD (root mean squared difference) between `x` and `y` within domain mask.\n\nin\n- `x` : array\n- `y` : another array of same size\n\noption:\n- `mask::Array{Bool}` : domain over which to compute the RMSE; default `trues(size(x))`\n\nout\n- rmsd : rmsd of `x` vs `y` within `mask` in %\n\"\"\"\nfunction rmsd100(x::AbstractArray{<:Number}, y::AbstractArray{<:Number}\n        ; mask::AbstractArray{Bool} = trues(size(x)))\n    return 100 * norm(x[mask] - y[mask]) / sqrt(sum(mask))\nend\n", "meta": {"hexsha": "02a83c4724cbd4f25bafebb4472aff039a9e1194", "size": 632, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utility/rmsd100.jl", "max_stars_repo_name": "jamesthesnake/MIRT.jl", "max_stars_repo_head_hexsha": "3a4b1e33a35e2ab062f532a22866bfb11f6e5cd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utility/rmsd100.jl", "max_issues_repo_name": "jamesthesnake/MIRT.jl", "max_issues_repo_head_hexsha": "3a4b1e33a35e2ab062f532a22866bfb11f6e5cd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utility/rmsd100.jl", "max_forks_repo_name": "jamesthesnake/MIRT.jl", "max_forks_repo_head_hexsha": "3a4b1e33a35e2ab062f532a22866bfb11f6e5cd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5714285714, "max_line_length": 89, "alphanum_fraction": 0.6629746835, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.7788416444825218}}
{"text": "# This file is part of the IntervalArithmetic.jl package; MIT licensed\n\n\"\"\"\n    setdiff(x::Interval, y::Interval)\n\nCalculate the set difference `x ∖ y`, i.e. the set of values\nthat are inside the interval `x` but not inside `y`.\n\nReturns an array of intervals.\nThe array may:\n\n- be empty if `x ⊆ y`;\n- contain a single interval, if `y` overlaps `x`\n- contain two intervals, if `y` is strictly contained within `x`.\n\"\"\"\nfunction setdiff(x::Interval{T}, y::Interval{T}) where T\n    intersection = x ∩ y\n\n    isempty(intersection) && return [x]\n    intersection == x && return [emptyinterval(T)]\n\n    if x.lo == intersection.lo\n        if isfinite(intersection.hi)\n            return [unsafe_interval(intersection.hi, x.hi)]\n        else\n            return [emptyinterval(T)]\n        end\n    end\n    if x.hi == intersection.hi\n        if isfinite(intersection.lo)\n            return [unsafe_interval(x.lo, intersection.lo)]\n        else\n            return [emptyinterval(T)]\n        end\n    end\n\n    return [unsafe_interval(x.lo, y.lo),\n            unsafe_interval(y.hi, x.hi)]\nend\nsetdiff(x::ValidInterval, ::ValidInterval) = [x]\n\n\n\"\"\"\n    distance(a::Interval, b::Interval)\n\nHausdorff distance between two intervals.\n\"\"\"\ndistance(a::Interval, b::Interval) = max(abs(a.lo-b.lo), abs(a.hi-b.hi))\n\nconst where_bisect = 0.49609375\n\n\"\"\"\n    bisect(X::Interval, α=0.49609375)\n\nSplit the interval `X` at position α; α=0.5 corresponds to the midpoint.\nReturns a tuple of the new intervals.\n\"\"\"\nfunction bisect(X::Interval, α=where_bisect)\n    @assert 0 ≤ α ≤ 1\n\n    m = mid(X, α)\n\n    return (unsafe_interval(X.lo, m), unsafe_interval(m, X.hi))\nend\n\n\"\"\"\n    mid(a::Interval, α=0.5)\n\nFind an intermediate point at a relative position `α`` in the interval `a`.\nThe default is the true midpoint at `α = 0.5`.\n\nAssumes 0 ≤ α ≤ 1.\n\nWarning: if the parameter `α = 0.5` is explicitly set, the behavior differs\nfrom the default case if the provided `Interval` is not finite, since when\n`α` is provided `mid` simply replaces `+Inf` (respectively `-Inf`) by `prevfloat(+Inf)`\n(respecively `nextfloat(-Inf)`) for the computation of the intermediate point.\n\"\"\"\nfunction mid(a::Interval{T}, α) where T\n\n    lo = (a.lo == -Inf ? nextfloat(T(-Inf)) : a.lo)\n    hi = (a.hi == +Inf ? prevfloat(T(+Inf)) : a.hi)\n\n    β = T(α)\n\n    midpoint = β * (hi - lo) + lo\n    isfinite(midpoint) && return midpoint\n    #= Fallback in case of overflow: hi - lo == +Inf.\n       This case can not be the default one as it does not pass several\n       IEEE1788-2015 tests for small floats.\n    =#\n    return (1 - β) * lo + β * hi\nend\n\nmid(::EmptyInterval{T}, α) where T = T(NaN)\n", "meta": {"hexsha": "8eb8b3f73f5c01ba4fbeee5fce83c622f58a22b3", "size": 2636, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/complementary/sets.jl", "max_stars_repo_name": "gwater/IntervalArithmetic.jl", "max_stars_repo_head_hexsha": "0967cbbbaf455af5043bc197139dd0e4c2b40204", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/complementary/sets.jl", "max_issues_repo_name": "gwater/IntervalArithmetic.jl", "max_issues_repo_head_hexsha": "0967cbbbaf455af5043bc197139dd0e4c2b40204", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/complementary/sets.jl", "max_forks_repo_name": "gwater/IntervalArithmetic.jl", "max_forks_repo_head_hexsha": "0967cbbbaf455af5043bc197139dd0e4c2b40204", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4583333333, "max_line_length": 87, "alphanum_fraction": 0.6411229135, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252812, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.778841633640436}}
{"text": "function piecewise(x)\n\tIfElse.ifelse(x[1] < 0.5, 0.0,\n\t\tIfElse.ifelse(x[1] < 2.0, m_ss * x[1] - 0.5 * m_ss,\n\t\t\t-0.250 * m_ss * (x[1] - 2.0) + 1.5 * m_ss))\nend\n\nfunction d_piecewise(x)\n\tIfElse.ifelse(x[1] < 0.5, 0.0,\n\t\tIfElse.ifelse(x[1] < 2.0, m_ss,\n\t\t\t-0.250 * m_ss))\nend\n\nfunction mirror_and_repeat(x; l::T = 5.0) where {T}\n\t# l = length of the pattern  ---^_/^-\n\t# we repeat it this way ---^_/^--^\\_^------^_/^--^\\_^---\n\t# section ≡ even -> normal pattern\n\t# section ≡ odd -> mirrored pattern\n\tsection = floor(x / l)\n\tx_rel = x % l\n\tmir = (section % 2) == 1\n\tif !mir\n\t\tx_mir = x_rel\n\telseif mir # mirroring\n\t\tx_mir = l - x_rel\n\tend\n\tmult = mir == 1 ? -1 : 1\n\treturn x_mir, mult\nend\n\n# smooth kinks w/ cubic polynomial\npoly(a, z) = a[4] + a[3] * z + a[2] * z^2.0 + a[1] * z^3.0\nd_poly(a, z) = a[3] + 2.0 * a[2] * z + 3.0 * a[1] * z^2.0\n\nfunction generate_piecewise_terrain(mss; repeat::Bool = false)\n\t# piece 1\n\tm1 = 0.0\n\tx1 = 0.4\n\ty1 = m1 * x1\n\n\tm2 = m_ss\n\tx2 = 0.6\n\ty2 = m2 * 0.1\n\n\tA1 = [x1^3.0 x1^2.0 x1 1.0;\n\t      x2^3.0 x2^2.0 x2 1.0;\n\t\t  3.0 * x1^2.0 2.0 * x1 1.0 0.0;\n\t\t  3.0 * x2^2.0 2.0 * x2 1.0 0.0]\n\tb1 = [y1; y2; m1; m2]\n\n\ta1 = A1 \\ b1\n\n\t@assert isapprox(poly(a1, x1) - y1, 0.0, atol = 1.0e-8)\n\t@assert isapprox(poly(a1, x2) - y2, 0.0, atol = 1.0e-8)\n\n\t# piece 2\n\tm1 = m_ss\n\tx1 = 1.4\n\ty1 = m_ss * x1\n\n\tm2 = -0.250 * m_ss\n\tx2 = 1.6\n\ty2 = m_ss * 1.5 + m2 * 0.1\n\n\tA2 = [x1^3.0 x1^2.0 x1 1.0;\n\t      x2^3.0 x2^2.0 x2 1.0;\n\t\t  3.0 * x1^2.0 2.0 * x1 1.0 0.0;\n\t\t  3.0 * x2^2.0 2.0 * x2 1.0 0.0]\n\tb2 = [y1; y2; m1; m2]\n\n\ta2 = A2 \\ b2\n\n\t@assert isapprox(poly(a2, x1) - y1, 0.0, atol = 1.0e-8)\n\t@assert isapprox(poly(a2, x2) - y2, 0.0, atol = 1.0e-8)\n\n\tif !repeat\n\t\tfunction piecewise_smoothed(x)\n\t\t\tIfElse.ifelse(x[1] < 0.4, 0.0,\n\t\t\t\tIfElse.ifelse(x[1] < 0.6, poly(a1, x[1]),\n\t\t\t\t\tIfElse.ifelse(x[1] < 1.9, m_ss * x[1] - 0.5 * m_ss,\n\t\t\t\t\t\tIfElse.ifelse(x[1] < 2.1, poly(a2, x[1] - 0.5),\n\t\t\t\t\t\t-0.250 * m_ss * (x[1] - 2.0) + 1.5 * m_ss))))\n\t\tend\n\n\t\tfunction d_piecewise_smoothed(x)\n\t\t\tIfElse.ifelse(x[1] < 0.4, 0.0,\n\t\t\t\tIfElse.ifelse(x[1] < 0.6, d_poly(a1, x[1]),\n\t\t\t\t\tIfElse.ifelse(x[1] < 1.9, m_ss,\n\t\t\t\t\t\tIfElse.ifelse(x[1] < 2.1, d_poly(a2, x[1] - 0.5),\n\t\t\t\t\t\t-0.250 * m_ss))))\n\t\tend\n\t\treturn piecewise_smoothed, d_piecewise_smoothed\n\telseif repeat\n\t\t@show \"repp\"\n\t\tfunction piecewise_repeat_smoothed(x)\n\t\t\tx_mir, mult = mirror_and_repeat(x[1]; l = 5.0)\n\t\t\tIfElse.ifelse(x_mir < 0.4, mult * 0.0,\n\t\t\t\tIfElse.ifelse(x_mir < 0.6, mult * poly(a1, x_mir),\n\t\t\t\t\tIfElse.ifelse(x_mir < 1.9, mult * (m_ss * x_mir - 0.5 * m_ss),\n\t\t\t\t\t\tIfElse.ifelse(x_mir < 2.1, mult * poly(a2, x_mir - 0.5),\n\t\t\t\t\t\tmult * (-0.250 * m_ss * (x_mir - 2.0) + 1.5 * m_ss)))))\n\t\tend\n\n\t\tfunction d_piecewise_repeat_smoothed(x)\n\t\t\tx_mir, mult = mirror_and_repeat(x[1]; l = 5.0)\n\t\t\tIfElse.ifelse(x_mir < 0.4, 0.0,\n\t\t\t\tIfElse.ifelse(x_mir < 0.6, d_poly(a1, x_mir),\n\t\t\t\t\tIfElse.ifelse(x_mir < 1.9, m_ss,\n\t\t\t\t\t\tIfElse.ifelse(x_mir < 2.1, d_poly(a2, x_mir - 0.5),\n\t\t\t\t\t\t-0.250 * m_ss))))\n\t\tend\n\t\treturn piecewise_repeat_smoothed, d_piecewise_repeat_smoothed\n\tend\nend\n\n# x = range(-1.0, stop = 4.0, length = 1000)\n# plot(x, piecewise.(x))#, aspect_ratio = :equal)\n# plot!(x, piecewise_smoothed.(x))#, aspect_ratio = :equal)\n#\n# plot(x, d_piecewise.(x), aspect_ratio = :equal)\n# plot!(x, d_piecewise_smoothed.(x), aspect_ratio = :equal)\n\nm_ss = tan(deg2rad(10.0)) # 10 degree slope\np1, dp1 = generate_piecewise_terrain(m_ss, repeat = false)\npiecewise1_2D_lc = Environment{R2, LinearizedCone}(p1, dp1)\nplot(-1:0.01:15, piecewise1_2D_lc.surf.(-1:0.01:15))\nplot!(-1:0.01:15, piecewise1_2D_lc.surf_grad.(-1:0.01:15))\n\nm_ss = tan(deg2rad(-15.0)) # 10 degree slope\np2, dp2 = generate_piecewise_terrain(m_ss)\npiecewise2_2D_lc = Environment{R2, LinearizedCone}(p2, dp2)\n# plot(-1:0.01:15, piecewise2_2D_lc.surf.(-1:0.01:15))\n# plot!(-1:0.01:15, piecewise2_2D_lc.surf_grad.(-1:0.01:15))\n\n\n# vis = Visualizer()\n# open(vis)\n# plot_surface!(vis, piecewise1_2D_lc, n = 100)\n# plot_surface!(vis, piecewise2_2D_lc, n = 100)\n", "meta": {"hexsha": "386d84931b45be72f8fcf733c9ba72e9ef12a693", "size": 3975, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simulation/environments/piecewise.jl", "max_stars_repo_name": "rejuvyesh/ContactImplicitMPC.jl", "max_stars_repo_head_hexsha": "6614b2b319bea63f00fbe3d83041e9be3b8c949b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulation/environments/piecewise.jl", "max_issues_repo_name": "rejuvyesh/ContactImplicitMPC.jl", "max_issues_repo_head_hexsha": "6614b2b319bea63f00fbe3d83041e9be3b8c949b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulation/environments/piecewise.jl", "max_forks_repo_name": "rejuvyesh/ContactImplicitMPC.jl", "max_forks_repo_head_hexsha": "6614b2b319bea63f00fbe3d83041e9be3b8c949b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5971223022, "max_line_length": 67, "alphanum_fraction": 0.5919496855, "num_tokens": 1881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7788416316205107}}
{"text": "\n# borrowed from KernelDensity.jl\n# https://github.com/JuliaStats/KernelDensity.jl/blob/master/src/univariate.jl\n\n\"\"\"\noptimize(f, x_lower, x_upper; iterations=1000, rel_tol=nothing, abs_tol=nothing)\n\nMinimize the function `f` in the interval `x_lower..x_upper`, using the\n[golden-section search](https://en.wikipedia.org/wiki/Golden-section_search).\nReturn an approximate minimum `x̃` or error if such approximate minimum cannot be found.\n\nThis algorithm assumes that `-f` is unimodal on the interval `x_lower..x_upper`,\nthat is to say, there exists a unique `x` in `x_lower..x_upper` such that `f` is\ndecreasing on `x_lower..x` and increasing on `x..x_upper`.\n\n`rel_tol` and `abs_tol` determine the relative and absolute tolerance, that is\nto say, the returned value `x̃` should differ from the actual minimum `x` at most\n`abs_tol + rel_tol * abs(x̃)`.\nIf not manually specified, `rel_tol` and `abs_tol` default to `sqrt(eps(T))` and\n`eps(T)` respectively, where `T` is the floating point type of `x_lower` and `x_upper`.\n\n`iterations` determines the maximum number of iterations allowed before convergence.\n\nThis is a private, unexported function, used internally to select the optimal bandwidth\nautomatically.\n\"\"\"\nfunction optimize(f, x_lower, x_upper; iterations=1000, rel_tol=nothing, abs_tol=nothing)\n\nif x_lower > x_upper\n    error(\"x_lower must be less than x_upper\")\nend\n\nT = promote_type(typeof(x_lower/1), typeof(x_upper/1))\nrtol = something(rel_tol, sqrt(eps(T)))\natol = something(abs_tol, eps(T))\n\nfunction midpoint_and_convergence(lower, upper)\n    midpoint = (lower + upper) / 2\n    tol = atol + rtol * midpoint\n    midpoint, (upper - lower) <= 2tol\nend\n\ninvphi::T = 0.5 * (sqrt(5) - 1)\ninvphisq::T = 0.5 * (3 - sqrt(5))\n\na::T, b::T = x_lower, x_upper\nh = b - a\nc = a + invphisq * h\nd = a + invphi * h\n\nfc, fd = f(c), f(d)\n\nfor _ in 1:iterations\n    h *= invphi\n    if fc < fd\n        m, converged = midpoint_and_convergence(a, d)\n        converged && return m\n        b = d\n        d, fd = c, fc\n        c = a + invphisq * h\n        fc = f(c)\n    else\n        m, converged = midpoint_and_convergence(c, b)\n        converged && return m\n        a = c\n        c, fc = d, fd\n        d = a + invphi * h\n        fd = f(d)\n    end\nend\n\nerror(\"Reached maximum number of iterations without convergence.\")\nend", "meta": {"hexsha": "fbfcf4e5ae9f6b3cb37351a0254dbc97d8a6a94b", "size": 2316, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariateopt.jl", "max_stars_repo_name": "tbeason/NonparametricRegression.jl", "max_stars_repo_head_hexsha": "ff9b306d623ea4f38da44f6446bfb1b58418cb26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-12-26T18:00:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T09:57:45.000Z", "max_issues_repo_path": "src/univariateopt.jl", "max_issues_repo_name": "tbeason/NonparametricRegression.jl", "max_issues_repo_head_hexsha": "ff9b306d623ea4f38da44f6446bfb1b58418cb26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-26T00:47:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T20:48:31.000Z", "max_forks_repo_path": "src/univariateopt.jl", "max_forks_repo_name": "tbeason/NonparametricRegression.jl", "max_forks_repo_head_hexsha": "ff9b306d623ea4f38da44f6446bfb1b58418cb26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7260273973, "max_line_length": 89, "alphanum_fraction": 0.6813471503, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.778841630239318}}
{"text": "# 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.\n#\n# Find the sum of all numbers which are equal to the sum of the factorial of\n# their digits.\n#\n# Note: as 1! = 1 and 2! = 2 are not sums they are not included.\n\nusing ProjectEulerSolutions\n\n# Precompute one digit factorials, use mapreduce to quickly calculate sums of\n# factorials of digits.\nfunction p034solution()::Integer\n    facs = map(factorial, 0:9) # precompute digit factorials\n    sums = 0\n    for i in 11:99999 # Arbitrary upper bound?\n        if mapreduce(x -> facs[x + 1], +, digits(i)) == i\n            sums += i\n        end\n    end\n    return sums\nend\n\np034 = Problems.Problem(p034solution)\n\nProblems.benchmark(p034)", "meta": {"hexsha": "52a6cb8baeff5d848bd1482be56de93821340490", "size": 697, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/034.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/034.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/034.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.88, "max_line_length": 77, "alphanum_fraction": 0.6614060258, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191271831558, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.7788071987561089}}
{"text": "using LinearAlgebra\n\"\"\"\n    Compute Lyapunov Exponents and Covariant \n    Lyapunov vectors.\n    Reference: Ginelli 2013\n\tInputs:\n\t\tDTu: dxdxm m-length timeseries of jacobian matrices\n\t\tdu: tangent subspace dimension that the computed CLVs must span.\n\tOutputs:\n\t\tlyap_exps: the first du Lyapunov exponents\n\t\tQ: dxduxm m-length timeseries of the first du CLVs\n\n\"\"\"\nfunction clvs(DTu::Array{Float64,3},du::Int64)\n    d = size(DTu)[1]\n    m = size(DTu)[3]\n    lyap_exps = zeros(du)\n    R = zeros(du,du,m)\n    Q = zeros(d,du,m)\n    A = qr!(rand(d,du))\n\tQ[:,:,1] = Array(A.Q)\n\tR[:,:,1] = A.R\n    for i=2:m\n        Q[:,:,i] = DTu[:,:,i-1]*Q[:,:,i-1]\n        A = qr!(Q[:,:,i])\n\t\tQ[:,:,i] = Array(A.Q)\n\t\tR[:,:,i] = A.R\n        lyap_exps .+= log.(abs.(diag(R[:,:,i])))./m\n    end\n    C = zeros(du,du,m)\n    C[:,:,end] = diagm(ones(du))\n    for i=reverse(1:m-1)\n        C[:,:,i] = R[:,:,i+1]\\C[:,:,i+1]\n        [normalize!(view(C,:,j,i)) for j = 1:du]\n        Q[:,:,i] = Q[:,:,i]*C[:,:,i]\n    end\n    return lyap_exps, Q\nend\n\n", "meta": {"hexsha": "d70e08ffff4887efa0e1ba363fcdd44b79e956d9", "size": 1015, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/clvs.jl", "max_stars_repo_name": "nishaChandramoorthy/energies", "max_stars_repo_head_hexsha": "17ffd87a976b9a6d23089fc182e16102bf4607c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-24T22:32:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-24T22:32:31.000Z", "max_issues_repo_path": "src/clvs.jl", "max_issues_repo_name": "nishaChandramoorthy/energies", "max_issues_repo_head_hexsha": "17ffd87a976b9a6d23089fc182e16102bf4607c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/clvs.jl", "max_forks_repo_name": "nishaChandramoorthy/energies", "max_forks_repo_head_hexsha": "17ffd87a976b9a6d23089fc182e16102bf4607c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.375, "max_line_length": 66, "alphanum_fraction": 0.5369458128, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296944, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7788002884539004}}
{"text": "\n\"\"\"\n    FourierDerivativeOperator{T}\n\nA derivative operator on a periodic grid with real scalar type `T` computing the\nfirst derivative using a spectral Fourier expansion via real discrete Fourier\ntransforms.\n\"\"\"\nstruct FourierDerivativeOperator{T<:Real, Grid, RFFT, BRFFT} <: AbstractPeriodicDerivativeOperator{T}\n    jac::T\n    Δx::T\n    grid_compute::Grid   # N-1 nodes, including the left and excluding the right boundary\n    grid_evaluate::Grid #  N  nodes, including both boundaries\n    tmp::Vector{Complex{T}}\n    rfft_plan::RFFT\n    brfft_plan::BRFFT\n\n    function FourierDerivativeOperator(jac::T, Δx::T, grid_compute::Grid, grid_evaluate::Grid,\n                                        tmp::Vector{Complex{T}}, rfft_plan::RFFT, brfft_plan::BRFFT) where {T<:Real, Grid, RFFT, BRFFT}\n        @argcheck length(brfft_plan) == length(tmp) DimensionMismatch\n        @argcheck length(brfft_plan) == (length(rfft_plan)÷2)+1 DimensionMismatch\n        @argcheck length(grid_compute) == length(rfft_plan) DimensionMismatch\n        @argcheck length(grid_compute) == length(grid_evaluate)-1 DimensionMismatch\n        @argcheck first(grid_compute) == first(grid_evaluate)\n        @argcheck step(grid_compute) ≈ step(grid_evaluate)\n        @argcheck last(grid_compute) < last(grid_evaluate)\n\n        new{T, Grid, RFFT, BRFFT}(jac, Δx, grid_compute, grid_evaluate, tmp, rfft_plan, brfft_plan)\n    end\nend\n\n\"\"\"\n    FourierDerivativeOperator(xmin::T, xmax::T, N::Integer) where {T<:Real}\n\nConstruct the `FourierDerivativeOperator` on a uniform grid between `xmin` and\n`xmax` using `N` nodes and `N÷2+1` complex Fourier modes.\n\"\"\"\nfunction FourierDerivativeOperator(xmin::T, xmax::T, N::Integer) where {T<:Real}\n    @argcheck N >= 1\n\n    jac = 2*T(π) / (xmax - xmin) / N # / N because of brfft instead of BRFFT\n    Δx = (xmax - xmin) / N\n    grid_evaluate = range(xmin, stop=xmax, length=N+1) # two boundary nodes\n    grid_compute = range(xmin, stop=grid_evaluate[end-1], length=N)\n    u = zero.(grid_compute)\n    rfft_plan = plan_rfft(u)\n    uhat = rfft_plan*u\n    brfft_plan = plan_brfft(uhat, N)\n\n    FourierDerivativeOperator(jac, Δx, grid_compute, grid_evaluate, uhat, rfft_plan, brfft_plan)\nend\n\n\"\"\"\n    fourier_derivative_operator(xmin::Real, xmax::Real, N::Integer)\n    fourier_derivative_operator(; xmin::Real, xmax::Real, N::Integer)\n\nConstruct the `FourierDerivativeOperator` on a uniform grid between `xmin` and\n`xmax` using `N` nodes and `N÷2+1` complex Fourier modes.\n\"\"\"\nfunction fourier_derivative_operator(xmin::Real, xmax::Real, N::Integer)\n    FourierDerivativeOperator(promote(xmin, xmax)..., N)\nend\n\nfunction fourier_derivative_operator(; xmin::Real, xmax::Real, N::Integer)\n    FourierDerivativeOperator(promote(xmin, xmax)..., N)\nend\n\nderivative_order(D::FourierDerivativeOperator) = 1\nLinearAlgebra.issymmetric(D::FourierDerivativeOperator) = false\n\nfunction Base.show(io::IO, D::FourierDerivativeOperator)\n    if get(io, :compact, false)\n        print(io, \"Periodic 1st derivative Fourier operator\")\n    else\n        grid = D.grid_evaluate\n        print(io, \"Periodic 1st derivative Fourier operator {T=\", eltype(D), \"} \\n\")\n        print(io, \"on a grid in [\", first(grid), \", \", last(grid),\n                    \"] using \", length(D.rfft_plan), \" nodes and \",\n                    length(D.brfft_plan), \" modes\")\n    end\nend\n\n\nfunction mul!(dest::AbstractVector{T}, D::FourierDerivativeOperator, u::AbstractVector{T}) where {T}\n    @unpack jac, tmp, rfft_plan, brfft_plan = D\n    N, _ = size(D)\n    @boundscheck begin\n        @argcheck N == length(u)\n        @argcheck N == length(dest)\n    end\n\n    mul!(tmp, rfft_plan, u)\n    @inbounds @simd for j in Base.OneTo(length(tmp)-1)\n        tmp[j] *= (j-1)*im * jac\n    end\n    # see e.g. Steven G. Johnson (2011) Notes on FFT based differentiation\n    if iseven(N)\n        @inbounds tmp[end] = zero(eltype(tmp))\n    else\n        @inbounds tmp[end] *= (length(tmp)-1)*im * jac\n    end\n    mul!(dest, brfft_plan, tmp)\nend\n\n# TODO there is no 5 argument mul! in FFTW.jl...\n# function mul!(dest::AbstractVector{T}, D::FourierDerivativeOperator, u::AbstractVector{T}, α, β) where {T}\n#     @unpack jac, tmp, rfft_plan, brfft_plan = D\n#     N, _ = size(D)\n#     @boundscheck begin\n#         @argcheck N == length(u)\n#         @argcheck N == length(dest)\n#     end\n\n#     mul!(tmp, rfft_plan, u)\n#     @inbounds @simd for j in Base.OneTo(length(tmp)-1)\n#         tmp[j] *= (j-1)*im * jac\n#     end\n#     if iseven(N)\n#         @inbounds tmp[end] = zero(eltype(tmp))\n#     else\n#         @inbounds tmp[end] *= (length(tmp)-1)*im * jac\n#     end\n#     mul!(dest, brfft_plan, tmp, α, β)\n# end\n\n\n\nfunction integrate(func, u::AbstractVector, D::FourierDerivativeOperator)\n    @boundscheck begin\n        length(u) == length(grid(D))\n    end\n    @unpack Δx = D\n\n    @inbounds res = sum(func, u)\n\n    Δx * res\nend\n\nfunction mass_matrix(D::FourierDerivativeOperator)\n    @unpack Δx = D\n\n    Δx * I\nend\n\n\n\n\"\"\"\n    fourier_derivative_matrix(N, xmin::Real=0.0, xmax::Real=2π)\n\nCompute the Fourier derivative matrix with respect to the corresponding nodal\nbasis using `N` nodes, see\nKopriva (2009) Implementing Spectral Methods for PDEs, Algorithm 18.\n\"\"\"\nfunction fourier_derivative_matrix(N, xmin::Real=0.0, xmax::Real=2π)\n    T = promote_type(typeof(xmin), typeof(xmax))\n    jac_2 = T(π) / (xmax - xmin)\n    D = Array{T}(undef, N, N)\n    @inbounds for j in 1:N, i in 1:N\n        j == i && continue\n        D[i,j] = (-1)^(i+j) * cot((i-j)*T(π)/N) * jac_2\n        D[i,i] -= D[i,j]\n    end\n    D\nend\n\n\nfunction _coef_end(coef, D1::FourierDerivativeOperator{T}) where {T}\n    if isodd(size(D1, 1))\n        return coef\n    else\n        return ntuple(i -> isodd(i) ? coef[i] : zero(T), length(coef))\n    end\nend\n# fallback for periodic FD operators etc.\n_coef_end(coef, D1) = coef\n\nstruct FourierPolynomialDerivativeOperator{T<:Real, Grid, RFFT, BRFFT, N} <: AbstractPeriodicDerivativeOperator{T}\n    D1::FourierDerivativeOperator{T,Grid,RFFT,BRFFT}\n    coef::NTuple{N,T}\n    coef_end::NTuple{N,T}\n\n    function FourierPolynomialDerivativeOperator(D1::FourierDerivativeOperator{T,Grid,RFFT,BRFFT}, coef::NTuple{N,T}) where {T<:Real, Grid, RFFT, BRFFT, N}\n        coef_end = _coef_end(coef, D1)\n        new{T,Grid,RFFT,BRFFT,N}(D1, coef, coef_end)\n    end\nend\n\nfunction FourierPolynomialDerivativeOperator(D1::FourierDerivativeOperator)\n    T = eltype(D1)\n    FourierPolynomialDerivativeOperator(D1, (zero(T), one(T)))\nend\n\nBase.size(poly::FourierPolynomialDerivativeOperator) = size(poly.D1)\nfunction LinearAlgebra.issymmetric(poly::FourierPolynomialDerivativeOperator)\n    @unpack coef = poly\n    all(iszero, coef[idx] for idx in eachindex(coef) if iseven(idx))\nend\ngrid(poly::FourierPolynomialDerivativeOperator) = grid(poly.D1)\n\nfunction Base.show(io::IO, poly::FourierPolynomialDerivativeOperator)\n    if get(io, :compact, false)\n        print(io, \"Fourier polynomial\")\n    else\n        print(io, \"Fourier polynomial with coefficients\\n\")\n        print(io, poly.coef)\n        print(io, \"\\nof the operator:\\n\")\n        print(io, poly.D1)\n    end\nend\n\n\nfunction Base.:*(D1::FourierDerivativeOperator, D2::FourierDerivativeOperator)\n    T = eltype(D1)\n    @argcheck T == eltype(D2) ArgumentError\n    @argcheck D1.jac == D2.jac ArgumentError\n    @argcheck D1.Δx == D2.Δx ArgumentError\n    @argcheck D1.grid_compute == D2.grid_compute DimensionMismatch\n    @argcheck D1.grid_evaluate == D2.grid_evaluate DimensionMismatch\n\n    FourierPolynomialDerivativeOperator(D1, (zero(T), zero(T), one(T)))\nend\n\nfunction Base.literal_pow(::typeof(^), D1::FourierDerivativeOperator, ::Val{P}) where {P}\n    T = eltype(D1)\n    coef = Base.setindex( ntuple(_->zero(T), Val{P+1}()), one(T), P+1)\n    FourierPolynomialDerivativeOperator(D1, coef)\nend\n\nfunction Base.:*(factor::Union{Real,Integer}, poly::FourierPolynomialDerivativeOperator)\n    @unpack coef = poly\n    for idx in 1:length(coef)\n        coef = Base.setindex(coef, factor*coef[idx], idx)\n    end\n\n    FourierPolynomialDerivativeOperator(poly.D1, coef)\nend\n\nfunction Base.:*(poly::FourierPolynomialDerivativeOperator, factor::Union{Real,Integer})\n    factor * poly\nend\n\nfunction Base.:*(D::FourierDerivativeOperator, factor::Union{Real,Integer})\n    FourierPolynomialDerivativeOperator(D) * factor\nend\n\nfunction Base.:*(factor::Union{Real,Integer}, D::FourierDerivativeOperator)\n    D * factor\nend\n\nfunction Base.:*(poly::FourierPolynomialDerivativeOperator, scaling::UniformScaling)\n    scaling.λ * poly\nend\n\nfunction Base.:*(scaling::UniformScaling, poly::FourierPolynomialDerivativeOperator)\n    poly * scaling\nend\n\nfunction Base.:*(D::FourierDerivativeOperator, scaling::UniformScaling)\n    scaling * FourierPolynomialDerivativeOperator(D)\nend\n\nfunction Base.:*(scaling::UniformScaling, D::FourierDerivativeOperator)\n    FourierPolynomialDerivativeOperator(D) * scaling\nend\n\nfunction Base.:*(poly1::FourierPolynomialDerivativeOperator, poly2::FourierPolynomialDerivativeOperator)\n    T = eltype(poly1.D1)\n    @argcheck T == eltype(poly2.D1) ArgumentError\n    @argcheck poly1.D1.jac == poly2.D1.jac ArgumentError\n    @argcheck poly1.D1.Δx == poly2.D1.Δx ArgumentError\n    @argcheck poly1.D1.grid_compute == poly2.D1.grid_compute DimensionMismatch\n    @argcheck poly1.D1.grid_evaluate == poly2.D1.grid_evaluate DimensionMismatch\n\n    coef = mul_poly(poly1.coef, poly2.coef)\n    FourierPolynomialDerivativeOperator(poly1.D1, coef)\nend\n\nfunction Base.:*(poly1::FourierPolynomialDerivativeOperator, D2::FourierDerivativeOperator)\n    poly1 * FourierPolynomialDerivativeOperator(D2)\nend\n\nfunction Base.:*(D1::FourierDerivativeOperator, poly2::FourierPolynomialDerivativeOperator)\n    FourierPolynomialDerivativeOperator(D1) * poly2\nend\n\n\nfunction Base.:+(poly1::FourierPolynomialDerivativeOperator, poly2::FourierPolynomialDerivativeOperator)\n    T = eltype(poly1.D1)\n    @argcheck T == eltype(poly2.D1) ArgumentError\n    @argcheck poly1.D1.jac == poly2.D1.jac ArgumentError\n    @argcheck poly1.D1.Δx == poly2.D1.Δx ArgumentError\n    @argcheck poly1.D1.grid_compute == poly2.D1.grid_compute DimensionMismatch\n    @argcheck poly1.D1.grid_evaluate == poly2.D1.grid_evaluate DimensionMismatch\n\n    coef = add_poly(poly1.coef, poly2.coef)\n    FourierPolynomialDerivativeOperator(poly1.D1, coef)\nend\n\nfunction Base.:+(D1::FourierDerivativeOperator, poly2::FourierPolynomialDerivativeOperator)\n    FourierPolynomialDerivativeOperator(D1) + poly2\nend\n\nfunction Base.:+(poly1::FourierPolynomialDerivativeOperator, D2::FourierDerivativeOperator)\n    poly1 + FourierPolynomialDerivativeOperator(D2)\nend\n\nfunction Base.:+(poly::FourierPolynomialDerivativeOperator, scaling::UniformScaling)\n    @unpack coef = poly\n    coef = Base.setindex(coef, coef[1] + scaling.λ, 1)\n\n    FourierPolynomialDerivativeOperator(poly.D1, coef)\nend\n\nfunction Base.:+(scaling::UniformScaling, poly::FourierPolynomialDerivativeOperator)\n    poly + scaling\nend\n\nfunction Base.:+(D::FourierDerivativeOperator, scaling::UniformScaling)\n    FourierPolynomialDerivativeOperator(D) + scaling\nend\n\nfunction Base.:+(scaling::UniformScaling, D::FourierDerivativeOperator)\n    D + scaling\nend\n\n\nfunction Base.:-(poly1::FourierPolynomialDerivativeOperator, poly2::FourierPolynomialDerivativeOperator)\n    T = eltype(poly1.D1)\n    @argcheck T == eltype(poly2.D1) ArgumentError\n    @argcheck poly1.D1.jac == poly2.D1.jac ArgumentError\n    @argcheck poly1.D1.Δx == poly2.D1.Δx ArgumentError\n    @argcheck poly1.D1.grid_compute == poly2.D1.grid_compute DimensionMismatch\n    @argcheck poly1.D1.grid_evaluate == poly2.D1.grid_evaluate DimensionMismatch\n\n    coef = subtract_poly(poly1.coef, poly2.coef)\n    FourierPolynomialDerivativeOperator(poly1.D1, coef)\nend\n\nfunction Base.:-(D1::FourierDerivativeOperator, poly2::FourierPolynomialDerivativeOperator)\n    FourierPolynomialDerivativeOperator(D1) - poly2\nend\n\nfunction Base.:-(poly1::FourierPolynomialDerivativeOperator, D2::FourierDerivativeOperator)\n    poly1 - FourierPolynomialDerivativeOperator(D2)\nend\n\nfunction Base.:-(poly::FourierPolynomialDerivativeOperator, scaling::UniformScaling)\n    @unpack coef = poly\n    coef = Base.setindex(coef, coef[1] - scaling.λ, 1)\n\n    FourierPolynomialDerivativeOperator(poly.D1, coef)\nend\n\nfunction Base.:-(scaling::UniformScaling, poly::FourierPolynomialDerivativeOperator)\n    @unpack coef = poly\n    coef = Base.setindex(coef, scaling.λ - coef[1], 1)\n    for idx in 2:length(coef)\n        coef = Base.setindex(coef, -coef[idx], idx)\n    end\n\n    FourierPolynomialDerivativeOperator(poly.D1, coef)\nend\n\nfunction Base.:-(D::FourierDerivativeOperator, scaling::UniformScaling)\n    FourierPolynomialDerivativeOperator(D) - scaling\nend\n\nfunction Base.:-(scaling::UniformScaling, D::FourierDerivativeOperator)\n    scaling - D\nend\n\n\nfunction mul!(dest::AbstractVector{T}, poly::FourierPolynomialDerivativeOperator, u::AbstractVector{T}) where {T}\n    @unpack D1, coef, coef_end = poly\n    @unpack jac, tmp, rfft_plan, brfft_plan = D1\n    N, _ = size(D1)\n    @boundscheck begin\n        @argcheck N == length(u)\n        @argcheck N == length(dest)\n    end\n\n    mul!(tmp, rfft_plan, u)\n    @inbounds @simd for j in Base.OneTo(length(tmp)-1)\n        # *N ) / N: brfft instead of irfft\n        tmp[j] *= evalpoly((j-1)*im * jac*N, coef) / N\n    end\n    # see e.g. Steven G. Johnson (2011) Notes on FFT based differentiation\n    @inbounds tmp[end] *= evalpoly((length(tmp)-1)*im * jac*N, coef_end) / N\n    mul!(dest, brfft_plan, tmp)\nend\n\nfunction LinearAlgebra.ldiv!(dest::AbstractVector{T}, rat::FourierPolynomialDerivativeOperator, u::AbstractVector{T}) where {T}\n    @unpack D1, coef, coef_end = rat\n    @unpack jac, tmp, rfft_plan, brfft_plan = D1\n    N, _ = size(D1)\n    @boundscheck begin\n        @argcheck N == length(u)\n        @argcheck N == length(dest)\n    end\n\n    mul!(tmp, rfft_plan, u)\n    @inbounds @simd for j in Base.OneTo(length(tmp)-1)\n        # *N ) / N: brfft instead of irfft\n        tmp[j] /= (evalpoly((j-1)*im * jac*N, coef) * N)\n    end\n    # see e.g. Steven G. Johnson (2011) Notes on FFT based differentiation\n    @inbounds tmp[end] /= (evalpoly((length(tmp)-1)*im * jac*N, coef_end) * N)\n    mul!(dest, brfft_plan, tmp)\nend\n\n\n\nstruct FourierRationalDerivativeOperator{T<:Real, Grid, RFFT, BRFFT, Nnum, Nden} <: AbstractPeriodicDerivativeOperator{T}\n    D1::FourierDerivativeOperator{T,Grid,RFFT,BRFFT}\n    num_coef::NTuple{Nnum,T}\n    num_coef_end::NTuple{Nnum,T}\n    den_coef::NTuple{Nden,T}\n    den_coef_end::NTuple{Nden,T}\n\n    function FourierRationalDerivativeOperator(D1::FourierDerivativeOperator{T,Grid,RFFT,BRFFT}, num_coef::NTuple{Nnum,T}, den_coef::NTuple{Nden,T}) where {T<:Real, Grid, RFFT, BRFFT, Nnum, Nden}\n        num_coef_end = _coef_end(num_coef, D1)\n        den_coef_end = _coef_end(den_coef, D1)\n        new{T,Grid,RFFT,BRFFT,Nnum,Nden}(D1, num_coef, num_coef_end, den_coef, den_coef_end)\n    end\nend\n\nBase.size(rat::FourierRationalDerivativeOperator) = size(rat.D1)\ngrid(rat::FourierRationalDerivativeOperator) = grid(rat.D1)\n\nfunction Base.show(io::IO, rat::FourierRationalDerivativeOperator)\n    if get(io, :compact, false)\n        print(io, \"Rational Fourier operator\")\n    else\n        print(io, \"Rational Fourier operator with coefficients\\n\")\n        print(io, rat.num_coef)\n        print(io, \"\\nand\\n\")\n        print(io, rat.den_coef)\n        print(io, \"\\nof the operator:\\n\")\n        print(io, rat.D1)\n    end\nend\n\nfunction LinearAlgebra.issymmetric(rat::FourierRationalDerivativeOperator)\n    @unpack num_coef, den_coef = rat\n    num_is_even = all(iszero, num_coef[idx] for idx in eachindex(num_coef) if iseven(idx))\n    den_is_even = all(iszero, den_coef[idx] for idx in eachindex(den_coef) if iseven(idx))\n\n    num_is_even == den_is_even\nend\n\n\nfunction FourierRationalDerivativeOperator(num::FourierPolynomialDerivativeOperator)\n    T = eltype(num)\n    FourierRationalDerivativeOperator(num.D1, num.coef, (one(T),))\nend\n\nfunction FourierRationalDerivativeOperator(D::FourierDerivativeOperator)\n    FourierRationalDerivativeOperator(FourierPolynomialDerivativeOperator(D))\nend\n\nfunction Base.:/(num::FourierPolynomialDerivativeOperator, den::FourierPolynomialDerivativeOperator)\n    @argcheck num.D1.jac == den.D1.jac ArgumentError\n    @argcheck num.D1.Δx == den.D1.Δx ArgumentError\n    @argcheck num.D1.grid_compute == den.D1.grid_compute DimensionMismatch\n    @argcheck num.D1.grid_evaluate == den.D1.grid_evaluate DimensionMismatch\n\n    FourierRationalDerivativeOperator(num.D1, num.coef, den.coef)\nend\n\nfunction Base.:/(num::FourierDerivativeOperator, den::FourierPolynomialDerivativeOperator)\n    FourierPolynomialDerivativeOperator(num) / den\nend\n\nfunction Base.:/(num::FourierPolynomialDerivativeOperator, den::FourierDerivativeOperator)\n    num / FourierPolynomialDerivativeOperator(den)\nend\n\nfunction Base.inv(rat::FourierRationalDerivativeOperator)\n    FourierRationalDerivativeOperator(rat.D1, rat.den_coef, rat.num_coef)\nend\n\nfunction Base.inv(den::Union{FourierDerivativeOperator,FourierPolynomialDerivativeOperator})\n    inv(FourierRationalDerivativeOperator(den))\nend\n\n\nfunction Base.:+(rat1::FourierRationalDerivativeOperator, rat2::FourierRationalDerivativeOperator)\n    T = eltype(rat1)\n    @argcheck T == eltype(rat2) ArgumentError\n    @argcheck rat1.D1.jac == rat2.D1.jac ArgumentError\n    @argcheck rat1.D1.Δx == rat2.D1.Δx ArgumentError\n    @argcheck rat1.D1.grid_compute == rat2.D1.grid_compute DimensionMismatch\n    @argcheck rat1.D1.grid_evaluate == rat2.D1.grid_evaluate DimensionMismatch\n\n    num_coef = add_poly(mul_poly(rat1.num_coef, rat2.den_coef), mul_poly(rat1.den_coef, rat2.num_coef))\n    den_coef = mul_poly(rat1.den_coef, rat2.den_coef)\n    FourierRationalDerivativeOperator(rat1.D1, num_coef, den_coef)\nend\n\nfunction Base.:+(rat1::FourierRationalDerivativeOperator, rat2::Union{FourierDerivativeOperator,FourierPolynomialDerivativeOperator})\n    rat1 + FourierRationalDerivativeOperator(rat2)\nend\n\nfunction Base.:+(rat1::Union{FourierDerivativeOperator,FourierPolynomialDerivativeOperator}, rat2::FourierRationalDerivativeOperator)\n    FourierRationalDerivativeOperator(rat1) + rat2\nend\n\nfunction Base.:-(rat1::FourierRationalDerivativeOperator, rat2::FourierRationalDerivativeOperator)\n    T = eltype(rat1)\n    @argcheck T == eltype(rat2) ArgumentError\n    @argcheck rat1.D1.jac == rat2.D1.jac ArgumentError\n    @argcheck rat1.D1.Δx == rat2.D1.Δx ArgumentError\n    @argcheck rat1.D1.grid_compute == rat2.D1.grid_compute DimensionMismatch\n    @argcheck rat1.D1.grid_evaluate == rat2.D1.grid_evaluate DimensionMismatch\n\n    num_coef = subtract_poly(mul_poly(rat1.num_coef, rat2.den_coef), mul_poly(rat1.den_coef, rat2.num_coef))\n    den_coef = mul_poly(rat1.den_coef, rat2.den_coef)\n    FourierRationalDerivativeOperator(rat1.D1, num_coef, den_coef)\nend\n\nfunction Base.:-(rat1::FourierRationalDerivativeOperator, rat2::Union{FourierDerivativeOperator,FourierPolynomialDerivativeOperator})\n    rat1 - FourierRationalDerivativeOperator(rat2)\nend\n\nfunction Base.:-(rat1::Union{FourierDerivativeOperator,FourierPolynomialDerivativeOperator}, rat2::FourierRationalDerivativeOperator)\n    FourierRationalDerivativeOperator(rat1) - rat2\nend\n\nfunction Base.:*(rat1::FourierRationalDerivativeOperator, rat2::FourierRationalDerivativeOperator)\n    T = eltype(rat1)\n    @argcheck T == eltype(rat2) ArgumentError\n    @argcheck rat1.D1.jac == rat2.D1.jac ArgumentError\n    @argcheck rat1.D1.Δx == rat2.D1.Δx ArgumentError\n    @argcheck rat1.D1.grid_compute == rat2.D1.grid_compute DimensionMismatch\n    @argcheck rat1.D1.grid_evaluate == rat2.D1.grid_evaluate DimensionMismatch\n\n    num_coef = mul_poly(rat1.num_coef, rat2.num_coef)\n    den_coef = mul_poly(rat1.den_coef, rat2.den_coef)\n    FourierRationalDerivativeOperator(rat1.D1, num_coef, den_coef)\nend\n\nfunction Base.:*(rat1::FourierRationalDerivativeOperator, rat2::Union{FourierDerivativeOperator,FourierPolynomialDerivativeOperator})\n    rat1 * FourierRationalDerivativeOperator(rat2)\nend\n\nfunction Base.:*(rat1::Union{FourierDerivativeOperator,FourierPolynomialDerivativeOperator}, rat2::FourierRationalDerivativeOperator)\n    FourierRationalDerivativeOperator(rat1) * rat2\nend\n\nfunction Base.:/(rat1::FourierRationalDerivativeOperator, rat2::FourierRationalDerivativeOperator)\n    T = eltype(rat1)\n    @argcheck T == eltype(rat2) ArgumentError\n    @argcheck rat1.D1.jac == rat2.D1.jac ArgumentError\n    @argcheck rat1.D1.Δx == rat2.D1.Δx ArgumentError\n    @argcheck rat1.D1.grid_compute == rat2.D1.grid_compute DimensionMismatch\n    @argcheck rat1.D1.grid_evaluate == rat2.D1.grid_evaluate DimensionMismatch\n\n    num_coef = mul_poly(rat1.num_coef, rat2.den_coef)\n    den_coef = mul_poly(rat1.den_coef, rat2.num_coef)\n    FourierRationalDerivativeOperator(rat1.D1, num_coef, den_coef)\nend\n\nfunction Base.:/(rat1::FourierRationalDerivativeOperator, rat2::Union{FourierDerivativeOperator,FourierPolynomialDerivativeOperator})\n    rat1 / FourierRationalDerivativeOperator(rat2)\nend\n\nfunction Base.:/(rat1::Union{FourierDerivativeOperator,FourierPolynomialDerivativeOperator}, rat2::FourierRationalDerivativeOperator)\n    FourierRationalDerivativeOperator(rat1) / rat2\nend\n\n\nfunction mul!(dest::AbstractVector{T}, rat::FourierRationalDerivativeOperator, u::AbstractVector{T}) where {T}\n    @unpack D1, num_coef, num_coef_end, den_coef, den_coef_end = rat\n    @unpack jac, tmp, rfft_plan, brfft_plan = D1\n    N, _ = size(D1)\n    @boundscheck begin\n        @argcheck N == length(u)\n        @argcheck N == length(dest)\n    end\n\n    mul!(tmp, rfft_plan, u)\n    @inbounds @simd for j in Base.OneTo(length(tmp)-1)\n        # *N ) / N: brfft instead of irfft\n        tmp[j] *= evalpoly((j-1)*im * jac*N, num_coef) / (N * evalpoly((j-1)*im * jac*N, den_coef))\n    end\n    # see e.g. Steven G. Johnson (2011) Notes on FFT based differentiation\n    @inbounds tmp[end] *= evalpoly((length(tmp)-1)*im * jac*N, num_coef_end) / (N * evalpoly((length(tmp)-1)*im * jac*N, den_coef_end))\n    mul!(dest, brfft_plan, tmp)\nend\n\nfunction LinearAlgebra.ldiv!(dest::AbstractVector{T}, rat::FourierRationalDerivativeOperator, u::AbstractVector{T}) where {T}\n    @unpack D1, num_coef, num_coef_end, den_coef, den_coef_end = rat\n    @unpack jac, tmp, rfft_plan, brfft_plan = D1\n    N, _ = size(D1)\n    @boundscheck begin\n        @argcheck N == length(u)\n        @argcheck N == length(dest)\n    end\n\n    mul!(tmp, rfft_plan, u)\n    @inbounds @simd for j in Base.OneTo(length(tmp)-1)\n        # *N ) / N: brfft instead of irfft\n        tmp[j] *= evalpoly((j-1)*im * jac*N, den_coef) / (N * evalpoly((j-1)*im * jac*N, num_coef))\n    end\n    # see e.g. Steven G. Johnson (2011) Notes on FFT based differentiation\n    @inbounds tmp[end] *= evalpoly((N-1)*im * jac*N, den_coef_end) / (N * evalpoly((N-1)*im * jac*N, num_coef_end))\n    mul!(dest, brfft_plan, tmp)\nend\n\nfunction Base.:\\(rat::Union{FourierRationalDerivativeOperator,FourierPolynomialDerivativeOperator}, u::AbstractVector{T}) where {T}\n    dest = similar(u)\n    ldiv!(dest, rat, u)\nend\n\n\n\n\nstruct PeriodicDerivativeOperatorQuotient{T<:Real, numDtype<:Union{PeriodicDerivativeOperator{T},FourierDerivativeOperator{T}}, denDtype<:Union{PeriodicDerivativeOperator{T},FourierDerivativeOperator{T}}, Nnum, Nden, RFFT, IRFFT} <: AbstractPeriodicDerivativeOperator{T}\n    num_D::numDtype\n    den_D::denDtype\n    num_coef::NTuple{Nnum,T}\n    den_coef::NTuple{Nden,T}\n    num_coef_end::NTuple{Nnum,T}\n    den_coef_end::NTuple{Nden,T}\n    tmp::Vector{Complex{T}}\n    num_eigval::Vector{Complex{T}}\n    den_eigval::Vector{Complex{T}}\n    rfft_plan::RFFT\n    irfft_plan::IRFFT\n\n    function PeriodicDerivativeOperatorQuotient(num_D::numDtype, den_D::denDtype, num_coef::NTuple{Nnum,T}, den_coef::NTuple{Nden,T}, tmp::Vector{Complex{T}}, num_eigval::Vector{Complex{T}}, den_eigval::Vector{Complex{T}}, rfft_plan::RFFT, irfft_plan::IRFFT) where {T<:Real, numDtype<:Union{PeriodicDerivativeOperator{T},FourierDerivativeOperator{T}}, denDtype<:Union{PeriodicDerivativeOperator{T},FourierDerivativeOperator{T}}, Nnum, Nden, RFFT, IRFFT}\n        @argcheck length(irfft_plan) == length(tmp) DimensionMismatch\n        @argcheck length(irfft_plan) == length(num_eigval) DimensionMismatch\n        @argcheck length(irfft_plan) == length(den_eigval) DimensionMismatch\n        @argcheck length(irfft_plan) == (length(rfft_plan)÷2)+1 DimensionMismatch\n        @argcheck length(grid(num_D)) == length(rfft_plan) DimensionMismatch\n        @argcheck length(grid(den_D)) == length(rfft_plan) DimensionMismatch\n\n        num_coef_end = _coef_end(num_coef, num_D)\n        den_coef_end = _coef_end(den_coef, den_D)\n\n        new{T,numDtype,denDtype,Nnum,Nden,RFFT,IRFFT}(num_D, den_D, num_coef, den_coef, num_coef_end, den_coef_end, tmp, num_eigval, den_eigval, rfft_plan, irfft_plan)\n    end\nend\n\nBase.size(quot::PeriodicDerivativeOperatorQuotient) = size(quot.num_D)\ngrid(quot::PeriodicDerivativeOperatorQuotient) = grid(quot.num_D)\n\nfunction Base.show(io::IO, quot::PeriodicDerivativeOperatorQuotient)\n    if get(io, :compact, false)\n        print(io, \"Rational operator (\", quot.num_D, \", \", quot.den_D, \")\")\n    else\n        print(io, \"Quotient of the polynomial with coefficients\\n\")\n        print(io, quot.num_coef)\n        print(io, \"\\nof the operator:\\n\")\n        print(io, quot.num_D)\n        print(io, \"and the polynomial with coefficients\\n\")\n        print(io, quot.den_coef)\n        print(io, \"\\nof the operator:\\n\")\n        print(io, quot.den_D)\n    end\nend\n\n\nfunction _eigvals!(eigval::Vector{Complex{T}}, D::FourierDerivativeOperator{T}) where {T<:Real}\n    N = length(grid(D))\n    jac = D.jac * N\n    @inbounds for idx in 1:(length(eigval))\n        eigval[idx] = (idx-1)*im * jac\n    end\n\n    eigval\nend\n\nfunction Base.://(num::FourierDerivativeOperator, den::PeriodicRationalDerivativeOperator)\n    T = eltype(num)\n    @argcheck T == eltype(den) ArgumentError\n    @argcheck grid(num) == grid(den) ArgumentError\n    @argcheck den.den_coef == (one(T),) ArgumentError\n\n    @unpack tmp, rfft_plan = num\n    irfft_plan = plan_irfft(tmp, length(grid(num)))\n\n    num_eigval = similar(tmp)\n    _eigvals!(num_eigval, num)\n\n    den_eigval = similar(tmp)\n    _eigvals!(den_eigval, den.D)\n\n    PeriodicDerivativeOperatorQuotient(num, den.D, (zero(T), one(T)), den.num_coef, tmp, num_eigval, den_eigval, rfft_plan, irfft_plan)\nend\n\nfunction Base.://(num::FourierPolynomialDerivativeOperator, den::PeriodicRationalDerivativeOperator)\n    T = eltype(num)\n    @argcheck T == eltype(den) ArgumentError\n    @argcheck grid(num) == grid(den) ArgumentError\n    @argcheck den.den_coef == (one(T),) ArgumentError\n\n    @unpack tmp, rfft_plan = num.D1\n    irfft_plan = plan_irfft(tmp, length(grid(num)))\n\n    num_eigval = similar(tmp)\n    _eigvals!(num_eigval, num.D1)\n\n    den_eigval = similar(tmp)\n    _eigvals!(den_eigval, den.D)\n\n    PeriodicDerivativeOperatorQuotient(num.D1, den.D, num.coef, den.num_coef, tmp, num_eigval, den_eigval, rfft_plan, irfft_plan)\nend\n\nfunction Base.://(num::PeriodicDerivativeOperator, den::PeriodicRationalDerivativeOperator)\n    T = eltype(num)\n    @argcheck T == eltype(den) ArgumentError\n    @argcheck grid(num) == grid(den) ArgumentError\n    @argcheck den.den_coef == (one(T),) ArgumentError\n\n    x = grid(num)\n    u = zero.(x)\n    rfft_plan = plan_rfft(u)\n    tmp = rfft_plan * u\n    irfft_plan = plan_irfft(tmp, length(grid(num)))\n\n    num_eigval = similar(tmp)\n    _eigvals!(num_eigval, num)\n\n    den_eigval = similar(tmp)\n    _eigvals!(den_eigval, den.D)\n\n    PeriodicDerivativeOperatorQuotient(num, den.D, (zero(T), one(T)), den.num_coef, tmp, num_eigval, den_eigval, rfft_plan, irfft_plan)\nend\n\nfunction Base.://(num::PeriodicRationalDerivativeOperator, den::PeriodicRationalDerivativeOperator)\n    T = eltype(num)\n    @argcheck T == eltype(den) ArgumentError\n    @argcheck grid(num) == grid(den) ArgumentError\n    @argcheck num.den_coef == (one(T),) ArgumentError\n    @argcheck den.den_coef == (one(T),) ArgumentError\n\n    x = grid(num)\n    u = zero.(x)\n    rfft_plan = plan_rfft(u)\n    tmp = rfft_plan * u\n    irfft_plan = plan_irfft(tmp, length(grid(num)))\n\n    num_eigval = similar(tmp)\n    _eigvals!(num_eigval, num.D)\n\n    den_eigval = similar(tmp)\n    _eigvals!(den_eigval, den.D)\n\n    PeriodicDerivativeOperatorQuotient(num.D, den.D, num.num_coef, den.num_coef, tmp, num_eigval, den_eigval, rfft_plan, irfft_plan)\nend\n\nfunction Base.://(num::FourierDerivativeOperator, den::FourierPolynomialDerivativeOperator)\n    T = eltype(num)\n    @argcheck T == eltype(den) ArgumentError\n    @argcheck grid(num) == grid(den) ArgumentError\n\n    @unpack tmp, rfft_plan = den.D1\n    irfft_plan = plan_irfft(tmp, length(grid(num)))\n\n    num_eigval = similar(tmp)\n    _eigvals!(num_eigval, num)\n\n    den_eigval = similar(tmp)\n    _eigvals!(den_eigval, den.D1)\n\n    PeriodicDerivativeOperatorQuotient(num, den.D1, (zero(T), one(T)), den.coef, tmp, num_eigval, den_eigval, rfft_plan, irfft_plan)\nend\n\nfunction Base.://(num::FourierPolynomialDerivativeOperator, den::FourierPolynomialDerivativeOperator)\n    T = eltype(num)\n    @argcheck T == eltype(den) ArgumentError\n    @argcheck grid(num) == grid(den) ArgumentError\n\n    @unpack tmp, rfft_plan = den.D1\n    irfft_plan = plan_irfft(tmp, length(grid(num)))\n\n    num_eigval = similar(tmp)\n    _eigvals!(num_eigval, num.D1)\n\n    den_eigval = similar(tmp)\n    _eigvals!(den_eigval, den.D1)\n\n    PeriodicDerivativeOperatorQuotient(num.D1, den.D1, num.coef, den.coef, tmp, num_eigval, den_eigval, rfft_plan, irfft_plan)\nend\n\nfunction Base.://(num::PeriodicDerivativeOperator, den::FourierPolynomialDerivativeOperator)\n    T = eltype(num)\n    @argcheck T == eltype(den) ArgumentError\n    @argcheck grid(num) == grid(den) ArgumentError\n\n    @unpack tmp, rfft_plan = den.D1\n    irfft_plan = plan_irfft(tmp, length(grid(num)))\n\n    num_eigval = similar(tmp)\n    _eigvals!(num_eigval, num)\n\n    den_eigval = similar(tmp)\n    _eigvals!(den_eigval, den.D1)\n\n    PeriodicDerivativeOperatorQuotient(num, den.D1, (zero(T), one(T)), den.coef, tmp, num_eigval, den_eigval, rfft_plan, irfft_plan)\nend\n\nfunction Base.://(num::PeriodicRationalDerivativeOperator, den::FourierPolynomialDerivativeOperator)\n    T = eltype(num)\n    @argcheck T == eltype(den) ArgumentError\n    @argcheck grid(num) == grid(den) ArgumentError\n    @argcheck num.den_coef == (one(T),) ArgumentError\n\n    @unpack tmp, rfft_plan = den.D1\n    irfft_plan = plan_irfft(tmp, length(grid(num)))\n\n    num_eigval = similar(tmp)\n    _eigvals!(num_eigval, num.D)\n\n    den_eigval = similar(tmp)\n    _eigvals!(den_eigval, den.D1)\n\n    PeriodicDerivativeOperatorQuotient(num.D, den.D1, num.num_coef, den.coef, tmp, num_eigval, den_eigval, rfft_plan, irfft_plan)\nend\n\n\nfunction mul!(dest::AbstractVector{T}, quot::PeriodicDerivativeOperatorQuotient, u::AbstractVector{T}) where {T}\n    @unpack num_D, num_coef, den_coef, num_coef_end, den_coef_end, tmp, num_eigval, den_eigval, rfft_plan, irfft_plan = quot\n    N, _ = size(num_D)\n    @boundscheck begin\n        @argcheck N == length(u)\n        @argcheck N == length(dest)\n    end\n\n    mul!(tmp, rfft_plan, u)\n    @inbounds @simd for j in Base.OneTo(length(tmp)-1)\n        tmp[j] *= evalpoly(num_eigval[j], num_coef) / evalpoly(den_eigval[j], den_coef)\n    end\n    tmp[end] *= evalpoly(num_eigval[end], num_coef_end) / evalpoly(den_eigval[end], den_coef_end)\n    mul!(dest, irfft_plan, tmp)\nend\n\n\n\n\n\"\"\"\n    ConstantFilter(D::FourierDerivativeOperator, filter)\n\nCreate a modal filter with constant parameters adapted to the Fourier\nderivative operator `D` with parameters given by the filter function `filter`.\n\"\"\"\nfunction ConstantFilter(D::FourierDerivativeOperator{T}, filter) where {T}\n    Np1 = length(D.brfft_plan)\n    coefficients = Array{T}(undef, Np1)\n    set_filter_coefficients!(coefficients, filter)\n    tmp = copy(D.tmp)\n    modal2nodal = plan_irfft(D.tmp, length(D.rfft_plan))\n    nodal2modal = D.rfft_plan\n    ConstantFilter(coefficients, nodal2modal, modal2nodal, tmp, filter)\nend\n\n\n\nabstract type AbstractFourierViscosity{T} <: AbstractPeriodicDerivativeOperator{T} end\n\n@inline source_of_coefficients(Di::AbstractFourierViscosity) = (Di.source_of_coefficients)\n\nLinearAlgebra.issymmetric(Di::AbstractFourierViscosity) = true\ngrid(Di::AbstractFourierViscosity) = grid(Di.D)\n\nfunction mul!(dest::AbstractVector{T}, Di::AbstractFourierViscosity{T}, u::AbstractVector{T}) where {T}\n    @unpack coefficients, D = Di\n    @unpack tmp, rfft_plan, brfft_plan = D\n    N = size(D, 1)\n    @boundscheck begin\n        @argcheck N == length(u)\n        @argcheck N == length(dest)\n        @argcheck length(tmp) == length(coefficients)\n    end\n\n    mul!(tmp, rfft_plan, u)\n    @inbounds @simd for j in Base.OneTo(length(tmp))\n        tmp[j] *= coefficients[j]\n    end\n    mul!(dest, brfft_plan, tmp)\n\n    nothing\nend\n\n\n\"\"\"\n    FourierConstantViscosity\n\nFourier viscosity operator with constant coefficients for the periodic 1st\nderivative Fourier operator.\n\"\"\"\nstruct FourierConstantViscosity{T<:Real, Grid, RFFT, BRFFT} <: AbstractFourierViscosity{T}\n    coefficients::Vector{T}\n    D::FourierDerivativeOperator{T,Grid,RFFT,BRFFT}\n    parameters\n    source_of_coefficients\n\n    function FourierConstantViscosity(D::FourierDerivativeOperator{T,Grid,RFFT,BRFFT}, parameters, source_of_coefficients) where {T<:Real, Grid, RFFT, BRFFT}\n        # precompute coefficients\n        N = size(D,1)\n        jac = N * D.jac # *N: brfft instead of irfft\n        coefficients = Vector{T}(undef, length(D.brfft_plan))\n        set_filter_coefficients!(coefficients, jac, N, parameters, source_of_coefficients)\n        new{T,Grid,RFFT,BRFFT}(coefficients, D, parameters, source_of_coefficients)\n    end\nend\n\nfunction Base.show(io::IO, Di::FourierConstantViscosity)\n    if get(io, :compact, false)\n        print(io, \"Fourier viscosity operator with constant coefficients of \")\n    else\n        grid = Di.D.grid_evaluate\n        print(io, \"Fourier viscosity operator with constant coefficients for the periodic 1st\\n\")\n        print(io, \"derivative Fourier operator {T=\", eltype(Di), \"} on a grid in [\",\n                first(grid), \", \", last(grid), \"]\\n\")\n        print(io, \"using \", length(Di.D.rfft_plan), \" nodes and \",\n                length(Di.D.brfft_plan), \" modes with coefficients of \")\n    end\n    print(io, Di.source_of_coefficients)\nend\n\n\nfunction dissipation_operator(source_of_coefficients, D::FourierDerivativeOperator; kwargs...)\n    parameters = get_parameters(source_of_coefficients, D; kwargs...)\n    FourierConstantViscosity(D, parameters, source_of_coefficients)\nend\n\n\n\"\"\"\n    Tadmor1989()\n\nCoefficients of the Fourier spectral viscosity given in\n- Tadmor (1989)\n  Convergence of Spectral Methods for Nonlinear Conservation Laws.\n  SIAM Journal on Numerical Analysis 26.1, pp. 30-44.\n\"\"\"\nstruct Tadmor1989 <: SourceOfCoefficients end\n\nfunction Base.show(io::IO, source::Tadmor1989)\n    if get(io, :compact, false)\n        summary(io, source)\n    else\n        print(io,\n            \"Tadmor (1989) \\n\",\n            \"  Convergence of Spectral Methods for Nonlinear Conservation Laws. \\n\",\n            \"  SIAM Journal on Numerical Analysis 26.1, pp. 30-44. \\n\")\n    end\nend\n\nfunction set_filter_coefficients!(coefficients::AbstractVector{T},\n                                  jac::T, N::Int,\n                                  parameters, source::Tadmor1989) where {T<:Real}\n    @unpack strength, cutoff = parameters\n    @argcheck cutoff >= 1\n    fill!(coefficients, zero(T))\n    jac = jac^2 / N # ^2: 2nd derivative; /N: brfft instead of irfft\n    @simd for j in cutoff:length(coefficients)\n        @inbounds coefficients[j] = -strength * (j-1)^2 * jac\n    end\nend\n\n\n\"\"\"\n    MadayTadmor1989()\n\nCoefficients of the Fourier spectral viscosity given in\n- Maday, Tadmor (1989)\n  Analysis of the Spectral Vanishing Viscosity Method for Periodic Conservation\n    Laws.\n  SIAM Journal on Numerical Analysis 26.4, pp. 854-870.\n\"\"\"\nstruct MadayTadmor1989 <: SourceOfCoefficients end\n\nfunction Base.show(io::IO, source::MadayTadmor1989)\n    if get(io, :compact, false)\n        summary(io, source)\n    else\n        print(io,\n            \"Maday, Tadmor (1989) \\n\",\n            \"  Analysis of the Spectral Vanishing Viscosity Method for Periodic Conservation\\n\",\n            \"    Laws. \\n\",\n            \"  SIAM Journal on Numerical Analysis 26.4, pp. 854-870.\")\n    end\nend\n\nfunction set_filter_coefficients!(coefficients::AbstractVector{T},\n                                  jac::T, N::Int,\n                                  parameters, source::MadayTadmor1989) where {T<:Real}\n    @unpack strength, cutoff = parameters\n    @argcheck cutoff >= 1\n    fill!(coefficients, zero(T))\n    jac = jac^2 / N # ^2: 2nd derivative; /N: brfft instead of irfft\n    @inbounds @simd for j in cutoff:min(2cutoff,length(coefficients))\n        coefficients[j] = -strength * (j-1)^2 * jac * (j-cutoff)/cutoff\n    end\n    @inbounds @simd for j in 2cutoff:length(coefficients)\n        coefficients[j] = -strength * (j-1)^2 * jac\n    end\nend\n\n\n\"\"\"\n    TadmorWaagan2012Standard()\n\nCoefficients of the Fourier spectral viscosity given in\n- Tadmor, Waagan (2012)\n  Adaptive Spectral Viscosity for Hyperbolic Conservation Laws.\n  SIAM Journal on Scientific Computing 34.2, pp. A993-A1009.\n\"\"\"\nstruct TadmorWaagan2012Standard <: SourceOfCoefficients end\n\nfunction Base.show(io::IO, source::TadmorWaagan2012Standard)\n    if get(io, :compact, false)\n        summary(io, source)\n    else\n        print(io,\n            \"Tadmor, Waagan (2012) \\n\",\n            \"  Adaptive Spectral Viscosity for Hyperbolic Conservation Laws. \\n\",\n            \"  SIAM Journal on Scientific Computing 34.2, pp. A993-A1009.\")\n    end\nend\n\nfunction set_filter_coefficients!(coefficients::AbstractVector{T},\n                                  jac::T, N::Int,\n                                  parameters, source::TadmorWaagan2012Standard) where {T<:Real}\n    @unpack strength, cutoff = parameters\n    @argcheck cutoff >= 1\n    fill!(coefficients, zero(T))\n    jac = jac^2 / N # ^2: 2nd derivative; /N: brfft instead of irfft\n    @inbounds @simd for j in cutoff+1:length(coefficients)\n        coefficients[j] = -strength * (j-1)^2 * jac * exp(-((length(coefficients)-j)/(j-cutoff))^2)\n    end\nend\n\n\n\"\"\"\n    TadmorWaagan2012Convergent()\n\nCoefficients of the Fourier spectral viscosity given in\n- Tadmor, Waagan (2012)\n  Adaptive Spectral Viscosity for Hyperbolic Conservation Laws.\n  SIAM Journal on Scientific Computing 34.2, pp. A993-A1009.\n\nSee also\n- Schochet (1990)\n  The Rate of Convergence of Spectral-Viscosity Methods for Periodic Scalar\n    Conservation Laws.\n  SIAM Journal on Numerical Analysis 27.5, pp. 1142-1159.\n\"\"\"\nstruct TadmorWaagan2012Convergent <: SourceOfCoefficients end\n\nfunction Base.show(io::IO, source::TadmorWaagan2012Convergent)\n    if get(io, :compact, false)\n        summary(io, source)\n    else\n        print(io,\n            \"Tadmor, Waagan (2012) \\n\",\n            \"  Adaptive Spectral Viscosity for Hyperbolic Conservation Laws. \\n\",\n            \"  SIAM Journal on Scientific Computing 34.2, pp. A993-A1009.\")\n    end\nend\n\nfunction set_filter_coefficients!(coefficients::AbstractVector{T},\n                                  jac::T, N::Int,\n                                  parameters, source::TadmorWaagan2012Convergent) where {T<:Real}\n    @unpack strength, cutoff = parameters\n    @argcheck cutoff >= 1\n    fill!(coefficients, zero(T))\n    jac = jac^2 / N # ^2: 2nd derivative; /N: brfft instead of irfft\n    @inbounds @simd for j in cutoff:min(2cutoff,length(coefficients))\n        coefficients[j] = -strength * (j-1)^2 * jac * exp(-((2cutoff-j)/(j-cutoff))^2)\n    end\n    @inbounds @simd for j in 2cutoff:length(coefficients)\n        coefficients[j] = -strength * (j-1)^2 * jac\n    end\nend\n\n\nconst FourierSpectralViscosityCoefficients = Union{Tadmor1989,MadayTadmor1989,TadmorWaagan2012Standard,TadmorWaagan2012Convergent}\n\nfunction get_parameters(source_of_coefficients::FourierSpectralViscosityCoefficients,\n                        D::FourierDerivativeOperator;\n                        strength::Real=eltype(D)(1)/size(D,2),\n                        cutoff::Int=1+round(Int, sqrt(size(D,2))), #+1: 1 based indexing\n                        kwargs...)\n    @argcheck cutoff >= 1\n\n    Dict(:strength=>strength, :cutoff=>cutoff)\nend\n\n\n\"\"\"\n    Tadmor1993()\n\nCoefficients of the Fourier super spectral viscosity given in\n- Tadmor (1993)\n  Super Viscosity and Spectral Approximations of Nonlinear Conservation Laws.\n  Numerical Methods for Fluid Dynamics IV, pp. 69-82.\n\"\"\"\nstruct Tadmor1993 <: SourceOfCoefficients end\n\nfunction Base.show(io::IO, source::Tadmor1993)\n    if get(io, :compact, false)\n        summary(io, source)\n    else\n        print(io,\n            \"Tadmor (1993) \\n\",\n            \"  Super Viscosity and Spectral Approximations of Nonlinear Conservation Laws. \\n\",\n            \"  Numerical Methods for Fluid Dynamics IV, pp. 69-82.\")\n    end\nend\n\nfunction set_filter_coefficients!(coefficients::AbstractVector{T},\n                                  jac::T, N::Int,\n                                  parameters, source::Tadmor1993) where {T<:Real}\n    @unpack order, strength, cutoff = parameters\n    @argcheck order >= 1\n    @argcheck cutoff >= 1\n    fill!(coefficients, zero(T))\n    jac = jac^2order / N # ^2order: order-th derivative; /N: brfft instead of irfft\n    @inbounds @simd for j in cutoff:length(coefficients)\n        coefficients[j] = -strength * (j-1)^2order * jac * (1 - (cutoff/j)^2order)\n    end\nend\n\n\nconst FourierSuperSpectralViscosityCoefficients = Tadmor1993\n\nfunction get_parameters(source::FourierSuperSpectralViscosityCoefficients,\n                        D::FourierDerivativeOperator;\n                        order::Int=1,\n                        strength=eltype(D)(1)/size(D,2)^(2order-1),\n                        cutoff::Int=1+round(Int, size(D,2)^(1-1/2order)), #+1: 1 based indexing\n                        kwargs...)\n    @argcheck order >= 1\n    @argcheck cutoff >= 1\n\n    Dict(:order=>order, :strength=>strength, :cutoff=>cutoff)\nend\n", "meta": {"hexsha": "5900d7ae54f5b5a7c3486071f7473c7a6bab1cdf", "size": 41971, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fourier_operators.jl", "max_stars_repo_name": "ranocha/SummationByPartsOperators.jl", "max_stars_repo_head_hexsha": "2f6ec738e7387553024cd82f4abff9a38fcefc96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2018-12-06T19:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T19:17:47.000Z", "max_issues_repo_path": "src/fourier_operators.jl", "max_issues_repo_name": "ranocha/SummationByPartsOperators.jl", "max_issues_repo_head_hexsha": "2f6ec738e7387553024cd82f4abff9a38fcefc96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2017-12-17T12:07:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T14:10:41.000Z", "max_forks_repo_path": "src/fourier_operators.jl", "max_forks_repo_name": "ranocha/SummationByPartsOperators.jl", "max_forks_repo_head_hexsha": "2f6ec738e7387553024cd82f4abff9a38fcefc96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:01:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:01:43.000Z", "avg_line_length": 36.7521891419, "max_line_length": 453, "alphanum_fraction": 0.7033189583, "num_tokens": 12134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103779, "lm_q2_score": 0.8558511469672595, "lm_q1q2_score": 0.7787449631148683}}
{"text": "function derivative{T<:FloatingPoint}(f::Function,x::Array{T,1})\n\n    n = length(f(x))\n    m = length(x)\n\n\te  = eps(T)^(1/3)*Base.maxabs([x,one(T)])\n    dh = eye(m)*e\n\tderiv = Array(T,n,m)\n\n    for i = 1:m\n\t    f1 = f(x+2*dh[:,i])\n\t    f2 = f(x+dh[:,i])\n\t    f3 = f(x-dh[:,i])\n\t    f4 = f(x-2*dh[:,i])\n        deriv[:,i] = (-f1+8*f2-8*f3+f4)/(12*e)\n    end\n\n    return deriv\n\nend", "meta": {"hexsha": "d5a7127945396656fd484707c3a8adcaa187d26d", "size": 379, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/derivative.jl", "max_stars_repo_name": "dingliumath/SolveDSGE", "max_stars_repo_head_hexsha": "994be79b200de9230dac39fc6721aeb5c8ef0a14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-07T02:37:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-21T08:26:23.000Z", "max_issues_repo_path": "src/derivative.jl", "max_issues_repo_name": "dingliumath/SolveDSGE", "max_issues_repo_head_hexsha": "994be79b200de9230dac39fc6721aeb5c8ef0a14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/derivative.jl", "max_forks_repo_name": "dingliumath/SolveDSGE", "max_forks_repo_head_hexsha": "994be79b200de9230dac39fc6721aeb5c8ef0a14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-04-29T15:03:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-07T02:37:23.000Z", "avg_line_length": 18.95, "max_line_length": 64, "alphanum_fraction": 0.4749340369, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7787449610239533}}
{"text": "\"\"\"\nFBeam!(FV, U, bdata)\nFunction evaluation for PTC example.\nF(u) = -u'' - lambda sin(u)\n\"\"\"\nfunction FBeam!(FV, U, bdata)\n    D2 = bdata.D2\n    lambda = bdata.lambda\n    su = lambda * sin.(U)\n    FV .= (D2 * U - su)\nend\n\n\"\"\"\nBeamJ!(FP,FV,U,bdata)\n\nJacobian for the beam problem\nF(u) = -u'' - lambda sin(u)\nso\nF'(u) w  = D2 w - lambda cos(u) w\n\"\"\"\nfunction BeamJ!(FP, FV, U, bdata)\n    D2 = bdata.D2\n    lambda = bdata.lambda\n    cu = lambda * cos.(U)\n    n = length(U)\n    zr = zeros(n - 1)\n    FP .= D2 - Tridiagonal(zr, cu, zr)\nend\n\n\"\"\"\nBeamtdJ!(FP, FV, U, bdata)\n\nJacobian evaluation for the time-dependent beam problem.\nIf F^n(w) = w - u_n + dt F(w) = 0 then\nF^n(w)' = I + dt F'(w)\n\"\"\"\nfunction BeamtdJ!(FP, FV, U, bdata)\n    FP .= BeamJ!(FP, FV, U, bdata)\n    dt = bdata.dt\n    FP .= I + dt * FP\nend\n\n\"\"\"\nFBeamtd!(FV, U, bdata)\n\nFunction evaluation for the time-dependent beam problem.\nThe implicit Euler step for u_t = - F(u) is\nu_{n+1} = u_n - dt F(u_{n+1})\nso the nonlinear equation is\nF^n(w) = w - u_n + dt F(w) = 0\n\"\"\"\nfunction FBeamtd!(FV, U, bdata)\n    un = bdata.UN\n    dt = bdata.dt\n    FV .= FBeam!(FV, U, bdata)\n    dU = U - un\n    FV .= dU + dt * FV\n    #axpby!(1.0,dU,dt,FV)\nend\n\n\"\"\"\nbeaminit(n,dt,lambda=20.0)\n\nSet up the beam problem with n interior grid points.\n\ndt is only needed for the temporal integration examples\n\"\"\"\n\nfunction beaminit(n, dt, lambda = 20.0)\n    #\n    # deltaval is a place to store the current pseudo-time step. I need this\n    # for preconditioning. You MUST have this in your pdata because ptcsoli\n    # writes to it:  pdata.deltaval[1]=delta\n    # So it has to be there in exactly this way.\n    #\n    deltaval = zeros(1)\n    D2 = Lap1d(n)\n    dx = 1.0 / (n + 1)\n    x = collect(dx:dx:1.0-dx)\n    UN = zeros(size(x))\n    bdata = (D2 = D2, x = x, dx = dx, dt = dt, lambda = lambda, UN = UN, deltaval = deltaval)\nend\n\n\"\"\"\nLap1d(n)\n\nreturns -d^2/dx^2 on [0,1] zero BC\n\"\"\"\nfunction Lap1d(n)\n    dx = 1 / (n + 1)\n    d = 2.0 * ones(n)\n    sup = -ones(n - 1)\n    slo = -ones(n - 1)\n    D2 = Tridiagonal(slo, d, sup)\n    D2 = D2 / (dx * dx)\n    return D2\nend\n", "meta": {"hexsha": "f3f61731900e16c3c142c402ea65002a8291e25b", "size": 2100, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TestProblems/Systems/FBeam!.jl", "max_stars_repo_name": "aliddell/SIAMFANLEquations.jl", "max_stars_repo_head_hexsha": "4a9bad23d726993764c5790d56b9d68cb27dffe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2020-04-16T19:59:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T12:18:53.000Z", "max_issues_repo_path": "src/TestProblems/Systems/FBeam!.jl", "max_issues_repo_name": "aliddell/SIAMFANLEquations.jl", "max_issues_repo_head_hexsha": "4a9bad23d726993764c5790d56b9d68cb27dffe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-07-22T20:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T01:14:10.000Z", "max_forks_repo_path": "src/TestProblems/Systems/FBeam!.jl", "max_forks_repo_name": "aliddell/SIAMFANLEquations.jl", "max_forks_repo_head_hexsha": "4a9bad23d726993764c5790d56b9d68cb27dffe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-03T10:47:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-03T10:47:05.000Z", "avg_line_length": 21.4285714286, "max_line_length": 93, "alphanum_fraction": 0.5780952381, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7787449593512206}}
{"text": "#!/usr/bin/env julia\n\nmodule PE11\n\nusing DelimitedFiles\n\nconst buffer=IOBuffer(\n\"08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08\n49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00\n81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65\n52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91\n22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80\n24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50\n32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70\n67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21\n24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72\n21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95\n78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92\n16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57\n86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58\n19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40\n04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66\n88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69\n04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36\n20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16\n20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54\n01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48\"\n);\nconst data=readdlm(buffer,' ',Int);\n\nend\n\nexport pe11\n\nfunction pe11(data::Matrix{<:Integer}=PE11.data)\n    n=4\n    productline(dx::Int,dy::Int)=[prod(data[y+i*dy,x+i*dx] for i in 0:n-1) for y in 1:size(data,1), x in 1:size(data,2) if checkbounds(Bool,data,y+(n-1)*dy,x+(n-1)*dx)]\n    cat(productline(1,0),productline(0,1),productline(1,1),productline(1,-1),dims=1)|>maximum\nend\n\nif !haskey(ENV,\"PROJECT_EULER_WITHOUT_RESULT\")\n    pe11()|>print\nend\n", "meta": {"hexsha": "883053f61f09f579a760ab9e6c3a636cf7db8d27", "size": 1734, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "11. Largest product in a grid/11.jl", "max_stars_repo_name": "miRoox/ProjectEuler", "max_stars_repo_head_hexsha": "020e8efddbf0dde33f2b2561e7b636fa199be75c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-11-13T16:11:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T23:20:05.000Z", "max_issues_repo_path": "11. Largest product in a grid/11.jl", "max_issues_repo_name": "miRoox/ProjectEuler", "max_issues_repo_head_hexsha": "020e8efddbf0dde33f2b2561e7b636fa199be75c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-12-27T15:12:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-27T15:12:05.000Z", "max_forks_repo_path": "11. Largest product in a grid/11.jl", "max_forks_repo_name": "miRoox/ProjectEuler", "max_forks_repo_head_hexsha": "020e8efddbf0dde33f2b2561e7b636fa199be75c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4090909091, "max_line_length": 168, "alphanum_fraction": 0.6724336794, "num_tokens": 994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088004, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7787449534966615}}
{"text": "using StatisticalRethinking, Optim\n#gr(size=(600,600));\n\np_grid = range(0, step=0.001, stop=1);\n\nprior = ones(length(p_grid));\n\nlikelihood = [pdf(Binomial(9, p), 6) for p in p_grid];\n\nposterior = likelihood .* prior;\n\nposterior = posterior / sum(posterior);\n\nN = 10000\nsamples = sample(p_grid, Weights(posterior), N);\n\nchn = MCMCChains.Chains(reshape(samples, N, 1, 1), [\"toss\"]);\n\nMCMCChains.describe(chn)\n\nplot(chn)\n\nx0 = [0.5]\nlower = [0.0]\nupper = [1.0]\n\nfunction loglik(x)\n  ll = 0.0\n  ll += log.(pdf.(Beta(1, 1), x[1]))\n  ll += sum(log.(pdf.(Binomial(9, x[1]), repeat([6], 1))))\n  -ll\nend\n\n(qmap, opt) = quap(loglik, x0, lower, upper)\n\nopt\n\nquapfit = [qmap[1], std(samples, mean=qmap[1])]\n\np = Vector{Plots.Plot{Plots.GRBackend}}(undef, 4)\np[1] = scatter(1:length(p_grid), samples, markersize = 2, ylim=(0.0, 1.3), lab=\"Draws\")\n\nw = 6\nn = 9\nx = 0:0.01:1\np[2] = plot( x, pdf.(Beta( w+1 , n-w+1 ) , x ), lab=\"Conjugate solution\")\ndensity!(p[2], samples, lab=\"Sample density\")\n\np[3] = plot( x, pdf.(Beta( w+1 , n-w+1 ) , x ), lab=\"Conjugate solution\")\nplot!( p[3], x, pdf.(Normal( quapfit[1], quapfit[2] ) , x ), lab=\"Quap approximation\")\n\nw = 6; n = 9; x = 0:0.01:1\np[4] = plot( x, pdf.(Beta( w+1 , n-w+1 ) , x ), lab=\"Conjugate solution\")\nplot!(p[4], x, pdf.(Normal( 0.67 , 0.16 ) , x ), lab=\"Normal approximation\")\nplot(p..., layout=(2, 2))\n\n# This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl\n\n", "meta": {"hexsha": "f4290a8e5d23663b775e80442fbc0dcadfb701ce", "size": 1437, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapters/02/clip-06-07.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_stars_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/02/clip-06-07.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_issues_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/02/clip-06-07.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_forks_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3559322034, "max_line_length": 87, "alphanum_fraction": 0.6158663883, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7787449530784758}}
{"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 67477abe-0b56-49a6-818d-3fccc669c6ce\nbegin\n\t# using Pkg; Pkg.add(\"Primes\")\n\tusing Primes\nend\n\n# ╔═╡ 727bf063-5fef-4126-a615-8a483aab9c99\nbegin\n\t# using Pkg; Pkg.add(\"Plots\") \n\tusing Plots\nend\n\n# ╔═╡ 80fc74b2-e038-11eb-39c8-fbd84caf7338\nmd\"\n# Fun with Arithmetic Derivatives\n\nIn this notebook I use Julia and Pluto to entertain the concept of the [Arithmetic Derivative](https://en.wikipedia.org/wiki/Arithmetic_derivative), also known as **number derivative**. It is named due to its axiomatic definition, which shares some of the properties of [real derivatives](https://en.wikipedia.org/wiki/Derivative), except it is a function acting on numbers.\n\n**Definition (Arithmetic Derivative).** _Let $n\\in \\mathbb{N}$. Then $D:\\mathbb{N}\\rightarrow\\mathbb{N}$ is a function with the following properties:_\n\n* _$D(p)=1$ for any prime $p$, and_\n\n* _$D(pq)=D(p)q+D(q)p$ for any $p,q\\in\\mathbb{N}$._\n\nThus we can generalize the arithmetic derivative to the set of natural numbers, ie. if we take $p=q=0$, we obtain that $D(0)=0$, and if we take $p=q=1$ we also obtain that $D(1)=0$. Thus we can calculate the arithmetic derivative for any non-prime natural by means of prime factorization, using the \\\"power rule\\\"\n\n$$D(p^n)=np^{n-1}D(p)$$\n\nfor $p,n\\in\\mathbb{N}$.\n\n**Proof (Power rule).** _The \\\"power rule\\\" can be proven in a straight-forward manner by means of mathematical induction. We take $n=0$ and see easily that the equation holds, for $D(1)=0$. Next we assume that the equation holds for a given $n$ and apply the induction step $n\\rightarrow n+1$:_\n\n$\\begin{align}\nD(p^{n+1})&=D(p^np)\\\\\n&=D(p^n)p+p^nD(p)\\\\\n&=np^{n-1}D(p)p + p^nD(p)\\\\\n&=np^{n}D(p) + p^nD(p)\\\\\n&=(n+1)p^{n}D(p)\n\\end{align}$\n\n_Thus the proof is concluded._\n\nTherefore we conclude that the arithmetic derivatie of any natural number $q$ greater than $1$ can be determined using its prime factorization, as in\n\n$$D(q)=D\\left(\\prod_{j=1}^Np_j^{m_j}\\right),$$\n\nwhere $p_1,...,p_N$ are the prime factors of $q$ and $m_1,...,m_N$ their multiplicities.\n\nNow we have all the building blocks to implement the arithmetic derivative in Julia. To this end, we make use of the Julia package `Primes.jl`, which provides optimized routines to calculate prime numbers and perform prime factorization of `Integer` values.\n\"\n\n# ╔═╡ 8b83eccb-c629-45ff-b8cb-4b4879664ace\nmd\"\nNext we implement $D(p)$ as the Julia function `arithmetic_derivative(::Integer)`. We also implement the generalization upon the set of whole numbers $\\mathbb{Z}$, which will be useful later. This generalization rests upon the fact that we consider $D(-q)=-D(q)$. This statement can be proven, but we will simply pretend that the proof is trivial, as in the prime factorization of a negative integer simply yields a factor of $-1$ multiplied with the other (positive) prime factors.\n\"\n\n# ╔═╡ c0d8d582-364c-4b06-8b08-cf902a359897\nfunction arithmetic_derivative(n::Integer)\n\tif (n < 0)\n\t\treturn -arithmetic_derivative(-n)\n\tend\n\t\n\tif (n < 2)\n\t\treturn 0\n\telseif (isprime(n))\n\t\treturn 1\n\tend\n\t\n\tfac = factor(n)\n\tsum = 0\n\t\n\tmap(collect(fac)) do pair\n\t\tm = pair.second\n\t\tp = pair.first\n\t\tsum += m * p^(m-1) * (n ÷ p^m)\n\tend\n\tsum\nend\n\n# ╔═╡ fa3e00d3-7f8e-4158-98ee-4e22285952d7\nmd\"\nThus we have implemented the basic algorithm that determines the arithmetic derivative of an integer number. Indeed, the arithmetic derivative is sometimes generalized to the set of rational numbers $\\mathbb{Q}$, and in this generalization the special case of a negative integer is indeed treated that way (see later).\n\nTo test our implementation, we let Julia compute `arithmetic_derivative(n)` for $0\\le n \\le 25$. We make sure that the values calculated are correct by calculating them by hand ([see this handwritten document](https://cdn.calza.xyz/pics/notebooks/maths/arithmetic_derivatives/Primes_Test.pdf) to check the results). While the standard output is not shown in Pluto, the reader is welcome to download the notebook and run it locally to double-check the test output with the results calculated by hand.\n\"\n\n# ╔═╡ 49eea834-b3bf-426b-993b-d2ea01da742d\nmd\"\nAt this point it would be interesting to show the values in a `scatter` plot. Indeed, the arithmetic derivative is a very interesting construction from a number theory standpoint since it is a reasonably simble and yet fun axiomatic construction, however it is difficult to visualize. A plot will hopefully shed more light on the nature of the function $D(p)$.\n\nTo this end, we plot the first $80$ values for $D(p)$ against their corresponding values $p$:\n\"\n\n# ╔═╡ 5fbd5946-9e1e-444b-9ab6-03bfed725620\nmd\"\nThis is perhaps less useful than we had hoped. We can try to connect the dots to visualize the path of the function $D(n)$:\n\"\n\n# ╔═╡ 5166fe7d-50fc-4e0e-b839-c0db8bf73b01\nmd\"\nThis makes a moderate amount of sense because we expect some kind of oscillation as the derivative is bound to rise as $n$ grows, but will keep falling to $1$ as primes are encountered every now and again in order to rise again. The \\\"amplitude\\\" of the oscillation (as in, the maximum) is also expected to rise as larger natural numbers are likelier to have a longer array of prime factors and higher multiplicities, which means that the sum due to the power rule can reach higher values.\n\nJulia is more than capable of doing better, though, such that we can venture into higher bounds. Let's try larger values of $N$ (note that the code cells containing the calls to `plot_derivatives(n, connect_dots = true)` have been hidden for aesthetic purposes):\n\"\n\n# ╔═╡ a3a14843-7b62-4f6f-8e81-ed772e4a27f3\nmd\"\nThese plots share in the character described earlier, but fail to provide further insights. Interestingly enough, [a generalization over the rational numbers $\\mathbb{Q}$ is given](https://en.wikipedia.org/wiki/Arithmetic_derivative#Extensions_beyond_natural_numbers) by the well-known quotient rule\n\n$$D\\left(\\frac pq\\right)=\\frac{D(p)q-D(q)p}{q^2}$$\n\nfor any rational number expressed as the fraction $\\frac pq$. We implement the function `arithmetic_derivative(::Rational)` which calls `arithmetic_derivative(::Integer)`:\n\"\n\n# ╔═╡ 8af8ac5e-616d-407b-8001-6fa7529c5729\nbegin\n\tfunction arithmetic_derivative(r::Rational)\n\t\tp = numerator(r)\n\t\tq = denominator(r)\n\t\t(arithmetic_derivative(p) * q - arithmetic_derivative(q) * p) / q^2\n\tend\nend\n\n# ╔═╡ 3c9f9459-9828-47ec-bdfc-8bd8a0187553\nfor n in 0:25\n\tprintln(\"n=$n\\tD(n)=$(arithmetic_derivative(n))\")\nend\n\n# ╔═╡ 1f2295eb-188f-4498-9d8c-1c0f303b2396\nfunction plot_derivatives(N; connect_dots = false, plot_label = nothing, new_plot = true, dots_color = :lightblue)\n\tmode_func = nothing\n\tif (connect_dots)\n\t\tmode_func = new_plot ? plot : plot!\n\telse\n\t\tmode_func = new_plot ? scatter : scatter!\n\tend\n\t\n\tif (plot_label === nothing)\n\t\tmode_func(0:N, arithmetic_derivative.(0:N), legend=false, color = dots_color)\n\telse\n\t\tmode_func(0:N, arithmetic_derivative.(0:N), label=plot_label, legend=:topleft, color = dots_color)\n\tend\n\t\n\txlabel!(\"Natural number n\")\n\tylabel!(\"Number derivative D(n)\")\n\ttitle!(\"Plot of the first $N derivatives\")\nend\n\n# ╔═╡ 9ebc2997-8db4-4aeb-a2e1-4614302d4f56\nplot_derivatives(80)\n\n# ╔═╡ f9b2636f-231c-44f4-95a3-013ba47df516\nplot_derivatives(80, connect_dots = true)\n\n# ╔═╡ 652bf146-8059-4c52-8f9a-63c3b5a22487\nplot_derivatives(100, connect_dots = true)\n\n# ╔═╡ 9cbc71f0-d902-4276-8a3d-b025355dddef\nplot_derivatives(200, connect_dots = true)\n\n# ╔═╡ 9c06d571-24e9-4678-9c0f-a7ac01f7d8f6\nplot_derivatives(500, connect_dots = true)\n\n# ╔═╡ 0374c7ce-c485-4712-a95b-55e2f3c30a67\nplot_derivatives(3000, connect_dots = true)\n\n# ╔═╡ c3248ade-6106-47df-8e6f-38847aee52ce\nmd\"\nWe can plot this function and overlay it with the scatter plot for $N=100$:\n\"\n\n# ╔═╡ 2ae73301-1458-4d49-80f4-249706d2eb09\nbegin\n\t# Calculate array of rationals to use:\n\t\n\tN_max = 101\n\trationals = zeros(Rational, N_max^2 + 1)\n\tfor i in 0:N_max, j in 1:N_max\n\t\trationals[i * (N_max-1) + j] = i//j\n\tend\n\tsort!(rationals)\n\t\n\t# Plot the rational derivatives:\n\t\n\tplot(rationals, arithmetic_derivative.(rationals), label = \"Rational generalization\", color = :lightblue)\n\t\n\t# ----------------------------\n\t# Overlay integer derivatives:\n\t\n\tplot_derivatives(100, connect_dots = false, plot_label = \"Integer derivatives\", new_plot = false, dots_color = :lightgreen)\nend\n\n# ╔═╡ 7f491dc8-d921-4637-acc9-09ccc3d2b9d6\nmd\"\nWith this interesting plot we conclude our small exploration.\n\nAbout this very last plot a few questions could be asked, for example why does the line belonging to the rational generalization become less dense after $n=50$? Could it be due to the way the `rationals` array is generated? If so, are the rationals in the array all equidistant from one another? Or does it depend on the nature of the generalized function $D(p/q)$?\n\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPrimes = \"27ebfcd6-29c5-5fa9-bf4b-fb8fc14df3ae\"\n\n[compat]\nPlots = \"~1.18.1\"\nPrimes = \"~0.5.0\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c3598e525718abcc440f69cc6d5f60dda0a1b61e\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.6+5\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"e2f47f6d8337369411569fd45ae5753ca10394c6\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.0+6\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\", \"StaticArrays\"]\ngit-tree-sha1 = \"ed268efe58512df8c7e224d2e170afd76dd6a417\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.13.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"dc7dedc2c2aa9faf59a55c622760a25cbefbe941\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.31.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"ee400abb2298bd13bfc3df1c412ed228061a2385\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.7.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"4437b64df1e0adccc3e5d1adbc3ac741095e4677\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.9\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"92d8f9f208637e8d2d28c664051a00569c01493d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.1.5+1\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"LibVPX_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"3cc57ad0a213808473eafef4845a74766242e05f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.3.1+4\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"35895cf184ceaab11fd778b4590144034a167a2f\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.1+14\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"cbd58c9deb1d304f5a245a0b7eb841a2560cfec6\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.1+5\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"dba1e8614e98949abfa60480b13653813d8f0157\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+0\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"b83e3125048a9c3158cbb7ca423790c7b1b57bea\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.57.5\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"e14907859a1d3aee73a019e7b3c98e9e7b8b5b3e\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.57.3+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"15ff9a14b9e1218958d3530cc288cf31465d9ae2\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.3.13\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"47ce50b742921377301e15005c96e979574e130b\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.1+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"c6a1fff2fd4b1da29d3dccaffb1e1001244d844e\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.12\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"81690084b6198a2e1da36fcfda16eeca9f9f24e4\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.1\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a4b12a1bd2ebade87891ab7e36fdbce582301a92\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.6\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[LibVPX_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"12ee7e23fa4d18361e7c2cde8f8337d4c3101bc7\"\nuuid = \"dd192d2f-8180-539f-9fb4-cc70b1dcf69a\"\nversion = \"1.10.0+0\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"761a393aeccd6aa92ec3515e428c26bf99575b3b\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+0\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"6a8a2a625ab0dea913aba95c11370589e0239ff0\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.6\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"4ea90bd5d3985ae1f9a908bd4500ae88921c5ce7\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.0\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+0\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"c8abc88faa3f7a3950832ac5d6e690881590d6dc\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"1.1.0\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"501c20a63a34ac1d015d5304da0e645f42d91c9f\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.0.11\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\"]\ngit-tree-sha1 = \"b93181645c1209d912d5632ba2d0094bc00703ad\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.18.1\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Primes]]\ngit-tree-sha1 = \"afccf037da52fa596223e5a0e331ff752e0e845c\"\nuuid = \"27ebfcd6-29c5-5fa9-bf4b-fb8fc14df3ae\"\nversion = \"0.5.0\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"b3fb709f3c97bfc6e948be68beeecb55a0b340ae\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.1\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"2a7a2469ed5d94a98dea0e85c46fa653d76be0cd\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.3.4\"\n\n[[Reexport]]\ngit-tree-sha1 = \"5f6c21241f0f655da3952fd60aa18477cf96c220\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.1.0\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"a43a7b58a6e7dc933b2fa2e0ca653ccf8bb8fd0e\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.6\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"1958272568dc176a1d881acb797beb909c785510\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.0.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"2f6792d523d7448bbe2fec99eca9218f06cc746d\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.8\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"000e168f5cc9aded17b6999a560b7c11dda69095\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.0\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"8ed4a3ea724dac32670b062be3ef1c1de6773ae8\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.4.4\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\"]\ngit-tree-sha1 = \"2839f1c1296940218e35df0bbb220f2a79686670\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.18.0+4\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"acc685bcf777b2202a904cdcb49ad34c2fa1880c\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.14.0+4\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7a5780a0d9c6864184b3a2eeeb833a0c871f00ab\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"0.1.6+4\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d713c1ce4deac133e3334ee12f4adff07f81778f\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2020.7.14+2\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"487da2f8f2f0c8ee0e83f39d13037d6bbf0a45ab\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.0.0+3\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─80fc74b2-e038-11eb-39c8-fbd84caf7338\n# ╠═67477abe-0b56-49a6-818d-3fccc669c6ce\n# ╟─8b83eccb-c629-45ff-b8cb-4b4879664ace\n# ╠═c0d8d582-364c-4b06-8b08-cf902a359897\n# ╟─fa3e00d3-7f8e-4158-98ee-4e22285952d7\n# ╠═3c9f9459-9828-47ec-bdfc-8bd8a0187553\n# ╟─49eea834-b3bf-426b-993b-d2ea01da742d\n# ╠═727bf063-5fef-4126-a615-8a483aab9c99\n# ╠═1f2295eb-188f-4498-9d8c-1c0f303b2396\n# ╠═9ebc2997-8db4-4aeb-a2e1-4614302d4f56\n# ╟─5fbd5946-9e1e-444b-9ab6-03bfed725620\n# ╠═f9b2636f-231c-44f4-95a3-013ba47df516\n# ╟─5166fe7d-50fc-4e0e-b839-c0db8bf73b01\n# ╟─652bf146-8059-4c52-8f9a-63c3b5a22487\n# ╟─9cbc71f0-d902-4276-8a3d-b025355dddef\n# ╟─9c06d571-24e9-4678-9c0f-a7ac01f7d8f6\n# ╟─0374c7ce-c485-4712-a95b-55e2f3c30a67\n# ╟─a3a14843-7b62-4f6f-8e81-ed772e4a27f3\n# ╠═8af8ac5e-616d-407b-8001-6fa7529c5729\n# ╟─c3248ade-6106-47df-8e6f-38847aee52ce\n# ╠═2ae73301-1458-4d49-80f4-249706d2eb09\n# ╟─7f491dc8-d921-4637-acc9-09ccc3d2b9d6\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "e3a2ca07c9f8129ff985db034d4c47b934395f6a", "size": 37235, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "maths/arithmetic_derivatives/Arithmetic_Derivatives.jl", "max_stars_repo_name": "ess3sq/pluto_notebooks", "max_stars_repo_head_hexsha": "9301d2150da2ba7aa5003963daa5947260a1c9be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "maths/arithmetic_derivatives/Arithmetic_Derivatives.jl", "max_issues_repo_name": "ess3sq/pluto_notebooks", "max_issues_repo_head_hexsha": "9301d2150da2ba7aa5003963daa5947260a1c9be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maths/arithmetic_derivatives/Arithmetic_Derivatives.jl", "max_forks_repo_name": "ess3sq/pluto_notebooks", "max_forks_repo_head_hexsha": "9301d2150da2ba7aa5003963daa5947260a1c9be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4957102002, "max_line_length": 499, "alphanum_fraction": 0.7365919162, "num_tokens": 16286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.778744950151196}}
{"text": "# ---\n# title: 446. Arithmetic Slices II - Subsequence\n# id: problem446\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Hard\n# categories: Dynamic Programming\n# link: <https://leetcode.com/problems/arithmetic-slices-ii-subsequence/description/>\n# hidden: true\n# ---\n# \n# A sequence of numbers is called arithmetic if it consists of at least three\n# elements and if the difference between any two consecutive elements is the\n# same.\n# \n# For example, these are arithmetic sequences:\n# \n#     \n#     \n#     1, 3, 5, 7, 9\n#     7, 7, 7, 7\n#     3, -1, -5, -9\n# \n# The following sequence is not arithmetic.\n# \n#     \n#     \n#     1, 1, 2, 5, 7\n# \n# \n# \n# A zero-indexed array A consisting of N numbers is given. A **subsequence**\n# slice of that array is any sequence of integers (P0, P1, ..., Pk) such that 0\n# ≤ P0 < P1 < ... < Pk < N.\n# \n# A **subsequence** slice (P0, P1, ..., Pk) of array A is called arithmetic if\n# the sequence A[P0], A[P1], ..., A[Pk-1], A[Pk] is arithmetic. In particular,\n# this means that k ≥ 2.\n# \n# The function should return the number of arithmetic subsequence slices in the\n# array A.\n# \n# The input contains N integers. Every integer is in the range of -231 and 231-1\n# and 0 ≤ N ≤ 1000\\. The output is guaranteed to be less than 231-1.\n# \n# \n# \n# **Example:**\n# \n#     \n#     \n#     Input: [2, 4, 6, 8, 10]\n#     \n#     Output: 7\n#     \n#     Explanation:\n#     All arithmetic subsequence slices are:\n#     [2,4,6]\n#     [4,6,8]\n#     [6,8,10]\n#     [2,4,6,8]\n#     [4,6,8,10]\n#     [2,4,6,8,10]\n#     [2,6,10]\n#     \n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "84f6372d8b7755a8e04935be1903220ac85aa96e", "size": 1632, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/446.arithmetic-slices-ii-subsequence.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/unresolved/446.arithmetic-slices-ii-subsequence.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/unresolved/446.arithmetic-slices-ii-subsequence.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 22.3561643836, "max_line_length": 85, "alphanum_fraction": 0.5943627451, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.778744945132998}}
{"text": "include(\"fisher_yates!.jl\")\n\n\"\"\"\n    simplexpt(unif)\n\nTakes a vector of length `d-1` of numbers between `0` and `1` and converts it a point on the standard `d-1` dimensional simplex.\n\"\"\"\nfunction simplexpt(unif)\n    d = length(unif) + 1\n    T = eltype(unif)\n    w = zeros(T, d + 1)\n    w[2:d] .= sort(unif)\n    w[d+1] = one(T)\n    diff(w)\nend\n\n\"\"\"\n    randprobvec([rng], d::Int)\n\nGenerates a random probability vector of length `d` using an algorithm by [Smith and Tromble](http://www.cs.cmu.edu/~nasmith/papers/smith+tromble.tr04.pdf).\n\"\"\"\nrandprobvec(rng::AbstractRNG, ::Type{N}, d::Int) where {N<:Number} =\n    simplexpt(rand(rng, N, d - 1))\n\nrandprobvec(rng::AbstractRNG, d::Int) = simplexpt(rand(rng, Float64, d - 1))\n\nrandprobvec(::Type{N}, d::Int) where {N<:Number} = randprobvec(Random.GLOBAL_RNG, N, d)\n\nrandprobvec(d::Int) = randprobvec(Random.GLOBAL_RNG, Float64, d)\n\n\n\"\"\"\n    randprobvec([rng], d::Int, N::T) where {T <: Integer}\n\nGenerates a random probability vector of length `d` whose entries are rational numbers with denominator at most `N` using an algorithm by [Smith and Tromble](http://www.cs.cmu.edu/~nasmith/papers/smith+tromble.tr04.pdf).\n\"\"\"\nfunction randprobvec(rng::AbstractRNG, d::Int, N::T) where {T<:Integer}\n    unif = zeros(T, d - 1)\n    fisher_yates_sample!(rng, 1:N, unif)\n    unif = unif .// N\n    simplexpt(unif)\nend\n\nrandprobvec(d::Int, N::T) where {T<:Integer} = randprobvec(Random.GLOBAL_RNG, d, N)\n\n\n\"\"\"\n    randunitary([rng], d::Int)\n\nGenerates a unitary matrix of dimension `d` at random according to the Haar measure, using an algorithm described by Maris Ozols in [\"How to generate a random unitary matrix\"](http://home.lu.lv/~sd20008/papers/essays/Random%20unitary%20%5Bpaper%5D.pdf).\n\"\"\"\nfunction randunitary(rng::AbstractRNG, d::Int)\n    RG = randn(rng, d, d) + im * randn(rng, d, d)\n    Q, R = qr!(RG)\n    r = diag(R)\n    L = Diagonal(r ./ abs.(r))\n    return Q * L\nend\n\nrandunitary(d::Int) = randunitary(Random.GLOBAL_RNG, d)\n\n\n\"\"\"\n    randdm([rng], d::Int)\n\nGenerates a density matrix of dimension `d` at random.\n\"\"\"\nfunction randdm(rng, d::Int)\n    eigs = Diagonal(randprobvec(rng, d))\n    U = randunitary(rng, d)\n    ρ = U * eigs * (U')\n    return Hermitian((ρ + ρ') / 2)\nend\n\nranddm(d::Int) = randdm(Random.GLOBAL_RNG, d)\n\n\"\"\"\n    randmajpair([rng], [T], d::Int, [N])\n\nGenerates a pair of probability vectors `p`, `q` of length `d`\nsuch that `p ≺ q` by rejection sampling. Supply a type `T` to\nchoose the numeric type of the elements of the vectors, and an\ninteger `N` to use rational numbers with maximum denominator `N`.\n\"\"\"\nfunction randmajpair(args...)\n    while true\n        p = randprobvec(args...)\n        q = randprobvec(args...)\n        p ≺ q && return p, q\n        p ≻ q && return q, p\n    end\nend\n\n\"\"\"\n    randincomppair([rng], [T], d::Int, [N]; sortby = entropy)\n\nGenerates a pair of probability vectors `p`, `q` of length `d`\nsuch that `!(p ≺ q)` and `!(q ≺ p)` by rejection sampling. Supply\na type `T` to choose the numeric type of the elements of the vectors,\nand an integer `N` to use rational numbers with maximum denominator `N`.\n\nOptionally, pass a function (from probability vectors to an\nordered set) to the keyword argument `sortby` to sort the results.\n\"\"\"\nfunction randincomppair(args...; sortby = entropy)\n    while true\n        p = randprobvec(args...)\n        q = randprobvec(args...)\n        p ≺ q && continue\n        p ≻ q && continue\n        if sortby(p) >= sortby(q)\n            return p, q\n        else\n            return q, p\n        end\n    end\nend\n", "meta": {"hexsha": "2b59533dda484bc94e5bc3f26630aa87a341de90", "size": 3537, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/random_utilities.jl", "max_stars_repo_name": "ericphanson/MajorizationExtrema.jl", "max_stars_repo_head_hexsha": "b90d342fe6f891d1be44f8b2079b3bd8eda3cec9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-30T21:15:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T04:01:01.000Z", "max_issues_repo_path": "src/random_utilities.jl", "max_issues_repo_name": "ericphanson/MajorizationExtrema.jl", "max_issues_repo_head_hexsha": "b90d342fe6f891d1be44f8b2079b3bd8eda3cec9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/random_utilities.jl", "max_forks_repo_name": "ericphanson/MajorizationExtrema.jl", "max_forks_repo_head_hexsha": "b90d342fe6f891d1be44f8b2079b3bd8eda3cec9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9745762712, "max_line_length": 253, "alphanum_fraction": 0.6434831778, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7787384580412523}}
{"text": "using Plots\nusing LinearAlgebra\n\nfunction plot_plane(center, spanning_vector_a, spanning_vector_b, color=:grey, ε = 1/2, frame=false, frame_color=:blue)\n\tx = [center[1] + ε * spanning_vector_a[1] + ε * spanning_vector_b[1],\n\t     center[1] - ε * spanning_vector_a[1] + ε * spanning_vector_b[1],\n\t     center[1] + ε * spanning_vector_a[1] - ε * spanning_vector_b[1],\n\t     center[1] - ε * spanning_vector_a[1] - ε * spanning_vector_b[1]]\n\t\n\ty = [center[2] + ε * spanning_vector_a[2] + ε * spanning_vector_b[2],\n\t     center[2] - ε * spanning_vector_a[2] + ε * spanning_vector_b[2],\n\t     center[2] + ε * spanning_vector_a[2] - ε * spanning_vector_b[2],\n\t     center[2] - ε * spanning_vector_a[2] - ε * spanning_vector_b[2]]\n\n\tz = [center[3] + ε * spanning_vector_a[3] + ε * spanning_vector_b[3],\n\t     center[3] - ε * spanning_vector_a[3] + ε * spanning_vector_b[3],\n\t     center[3] + ε * spanning_vector_a[3] - ε * spanning_vector_b[3],\n\t     center[3] - ε * spanning_vector_a[3] - ε * spanning_vector_b[3]]\n\t\n\tif frame\n\t\tpath3d!(x,y,z;color=frame_color)\n\tend\n\tmesh3d!(x,y,z;color,connections=([0,3],[1,2],[3,0]))\nend\n\n", "meta": {"hexsha": "90bccdb942f08891129ab5ec27711e4238aebf2b", "size": 1119, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/plot_plane.jl", "max_stars_repo_name": "dwd31415/ContactStructures.jl", "max_stars_repo_head_hexsha": "86a8caeaa4f4896b79904358cec2fb45401e230b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/plot_plane.jl", "max_issues_repo_name": "dwd31415/ContactStructures.jl", "max_issues_repo_head_hexsha": "86a8caeaa4f4896b79904358cec2fb45401e230b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-08T11:52:18.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-03T22:44:55.000Z", "max_forks_repo_path": "src/plot_plane.jl", "max_forks_repo_name": "dwd31415/ContactStructures.jl", "max_forks_repo_head_hexsha": "86a8caeaa4f4896b79904358cec2fb45401e230b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.0384615385, "max_line_length": 119, "alphanum_fraction": 0.6568364611, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7787384558335559}}
{"text": "using QuadGK, HCubature\n\n\"\"\"\nCreate a new directory `dirname` in the current path.\nAppend a number to the name if the directory already exists.\n\"\"\"\nfunction make_new_dir(dirname::String)\n    if ispath(dirname)\n        k=1\n        while ispath(dirname*\"_$k\")\n            k+=1\n        end\n        return mkdir(dirname*\"_$k\")\n    else\n        return mkdir(dirname)\n    end\nend\n\n\"\"\"\n    nice_number(x,K::Int)\n\nReturn a string which is the rounded value of `x` with `K` (decimal) digits and\nif necessary, pad `\"0\"` to the right so that there are exactly `K` decimal places.\n\"\"\"\nfunction nice_float2string(x,K::Int)\n    integer_part = trunc(Int,x)\n    y = x - integer_part\n    decimal_part = rpad(round(Int,y*10^K),K,\"0\")\n    return \"$(integer_part).$decimal_part\"\nend\n\n\"\"\"\nReturn the coefficients `c1,c2,λ` of the SOH model computed for the `model` `\"Fokker-Planck\"` (default)\nor `\"BGK\"` with the concentration parameters `κ`.\nThese coefficients are given by\n\nc₁ = ∫\\\\_[0,π] cos(θ)exp(κcos(θ))dθ / ∫\\\\_[0,π] exp(κcos(θ))dθ\n\nc₂ = ∫\\\\_[0,π] cos(θ)sin(θ)g(θ)exp(κcos(θ))dθ / ∫\\\\_[0,π] sin(θ)g(θ)exp(κcos(θ))dθ\n\nλ = 1/κ\n\nwhere\n\ng(θ) = θ/κ - π/κ * ∫\\\\_[0,θ] exp(-κcos(ψ))dψ / ∫\\\\_[0,π] exp(-κcos(ψ))dψ in the Fokker-Planck case\n\nand\n\ng(θ) = 1 in the BGK case.\n\"\"\"\nfunction coefficients_Vicsek(κ;model=\"Fokker-Planck\")\n    λ = 1/κ\n    I1 = quadgk(θ->cos(θ)*exp(κ*cos(θ)),0,pi,rtol=1e-5)[1]\n    Z1 = quadgk(θ->exp(κ*cos(θ)),0,pi,rtol=1e-5)[1]\n    c1 = I1/Z1\n    if model==\"BGK\"\n        I2 = quadgk(θ->cos(θ)*sin(θ)^2*exp(κ*cos(θ)),0,pi,rtol=1e-5)[1]\n        Z2 = quadgk(θ->sin(θ)^2*exp(κ*cos(θ)),0,pi,rtol=1e-5)[1]\n        c2 = I2/Z2\n        return c1,c2,λ\n    elseif model==\"Fokker-Planck\"\n        Zinv = quadgk(θ->exp(-κ*cos(θ)),0,pi,rtol=1e-5)[1]\n        I21 = quadgk(θ->θ*cos(θ)*sin(θ)*exp(κ*cos(θ)),0,pi,rtol=1e-5)[1]/κ\n        I22 = pi/(κ*Zinv) * hcubature(x->cos(x[1])*sin(x[1])*exp(κ*cos(x[1]))*exp(-κ*cos(x[2]))*(x[2]<x[1]),(0,0),(pi,pi),rtol=1e-3)[1]\n        I2 = I21 - I22\n        Z21 = quadgk(θ->θ*sin(θ)*exp(κ*cos(θ)),0,pi,rtol=1e-5)[1]/κ\n        Z22 = pi/(κ*Zinv) * hcubature(x->sin(x[1])*exp(κ*cos(x[1]))*exp(-κ*cos(x[2]))*(x[2]<x[1]),(0,0),(pi,pi),rtol=1e-3)[1]\n        Z2 = Z21 - Z22\n        c2 = I2/Z2\n        return c1,c2,λ\n    else\n        ArgumentError(\"Model not defined!\")\n    end\nend\n", "meta": {"hexsha": "3613e3240a15874934de6389acc629a450918234", "size": 2296, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/toolbox.jl", "max_stars_repo_name": "antoinediez/SOH.jl", "max_stars_repo_head_hexsha": "54b6a13bf5b364d5678f59e1c399fe9b8e8b5d11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-14T13:22:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T17:10:36.000Z", "max_issues_repo_path": "src/toolbox.jl", "max_issues_repo_name": "antoinediez/SOH.jl", "max_issues_repo_head_hexsha": "54b6a13bf5b364d5678f59e1c399fe9b8e8b5d11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-16T19:23:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T11:33:15.000Z", "max_forks_repo_path": "src/toolbox.jl", "max_forks_repo_name": "antoinediez/SOH.jl", "max_forks_repo_head_hexsha": "54b6a13bf5b364d5678f59e1c399fe9b8e8b5d11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-16T18:01:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T18:01:47.000Z", "avg_line_length": 30.6133333333, "max_line_length": 135, "alphanum_fraction": 0.5783972125, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7787384543217638}}
{"text": "# calculate eigen values/vectors\n# plot eigen vectors on the contour\n\nmodule CalcPlotEigen\n    using Plots, Base.Iterators, LinearAlgebra\n    pyplot()\n\n    function pdf(x, mu, cov_mat)\n        # determinant\n        det_mat = det(cov_mat)\n\n        diff_x = x - mu\n        return exp(-((diff_x'/cov_mat)*diff_x)/2)/(2*pi*sqrt(det_mat))\n    end\n\n    function main(is_test=false)\n        # x-y grid\n        vx = 0:200\n        vy = 0:100\n\n        # mu, covariance matrix\n        mu = [150; 50]\n        cov = [100 -25*sqrt(3); -25*sqrt(3) 50]\n\n        # calculate eigen values/vectors\n        eig_vals, eig_vecs = eigen(cov)\n        println(\"Eigen Values: $(eig_vals)\")\n        println(\"Eigen Vectors: $(eig_vecs)\")\n        println(\"Eigen Vector1: $(eig_vecs[:, 1])\")\n        println(\"Eigen Vector2: $(eig_vecs[:, 2])\")\n\n        # long or short\n        if eig_vals[1] > eig_vals[2]\n            long_val = eig_vals[1]\n            long_vec = eig_vecs[:, 1]\n            short_val = eig_vals[2]\n            short_vec = eig_vecs[:, 2]\n        else\n            long_val = eig_vals[2]\n            long_vec = eig_vecs[:, 2]\n            short_val = eig_vals[1]\n            short_vec = eig_vecs[:, 1]\n        end\n        println(\"Long Value: $(long_val)\")\n        println(\"Long Vector: $(long_vec)\")\n        println(\"Short Value: $(short_val)\")\n        println(\"Short Vector: $(short_vec)\")\n\n        # plot\n        z = [pdf([x; y], mu, cov) for x in vx, y in vy]\n        contour(vx, vy, z', c=:haline, aspect_ratio=:equal)\n        long = 2 * sqrt(long_val) * long_vec\n        short = 2 * sqrt(short_val) * short_vec\n        quiver!([mu[1]], [mu[2]], quiver=([long[1]], [long[2]]), \n                c=:red, aspect_ratio=:equal)\n        quiver!([mu[1]], [mu[2]], quiver=([short[1]], [short[2]]), \n                c=:blue, aspect_ratio=:equal)\n        \n        if is_test == false\n            save_path = joinpath(split(@__FILE__, \"src\")[1], \"src/prob_stats/multi_dim_gauss_dist/eigen/contour_eigen.png\")\n            savefig(save_path)\n        end\n    end\nend", "meta": {"hexsha": "eab2725c4308028610f77ab649eaf8f9a072b3e5", "size": 2040, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/prob_stats/multi_dim_gauss_dist/eigen/calc_plot_eigen.jl", "max_stars_repo_name": "ShisatoYano/JuliaAutonomy", "max_stars_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2021-03-10T12:43:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T16:40:19.000Z", "max_issues_repo_path": "src/prob_stats/multi_dim_gauss_dist/eigen/calc_plot_eigen.jl", "max_issues_repo_name": "ShisatoYano/JuliaAutonomy", "max_issues_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/prob_stats/multi_dim_gauss_dist/eigen/calc_plot_eigen.jl", "max_forks_repo_name": "ShisatoYano/JuliaAutonomy", "max_forks_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-14T02:46:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T09:19:40.000Z", "avg_line_length": 31.875, "max_line_length": 123, "alphanum_fraction": 0.5362745098, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7787384524620194}}
{"text": "@registerN Hahn AbstractCDOP3 α β 𝐍\nexport Hahn\n\n\"\"\"\n    Hahn{α,β,𝐍}\n\nReferences: [Koekoek and Swarttouw §1.5](https://arxiv.org/pdf/math/9602214.pdf)\n\n!!! note\n    In  [Koekoek and Swarttouw](https://arxiv.org/pdf/math/9602214.pdf) sections 1.3, 1.4, and 1.6  are other  Hahn-type polynomials,  not  implemented here.\n\n\"\"\"\nHahn\n\nabcde(::Type{<:Hahn{α,β,𝐍}})  where {α,β,𝐍} = NamedTuple{(:a,:b,:c,:d,:e)}((1, -(β+𝐍+1), 0,  α+β+2, -𝐍*(α+1)))\n\nbasis_symbol(::Type{<:Hahn{α,β,𝐍}}) where {α,β,𝐍} = \"Q⁽ᵅᵝ⁾\"\nPolynomials.domain(::Type{<:Hahn{α, β, 𝐍}}) where {α, β,  𝐍} = Polynomials.Interval(0, 𝐍)\nweight_function(::Type{<:Hahn{α,β,𝐍}}) where {α,β,𝐍} = x -> generalized_binomial(α+x,x) * generalized_binomial(𝐍+β-x,𝐍-x)\n\n# use   recurrence relation  1.5.3 of Koekoek and Swarttouw\n# -xQᵢ = AQᵢ₊₁ -  (A+C)Qᵢ + CQᵢ₋₁\n#  or Qᵢ₊₁ = (1/A ⋅ x - (1 + C/A)) Qᵢ + C/A ⋅ Qᵢ₋₁\n# Using kᵢ = A⁻¹ᵢ₋₁ ⋅ A⁻¹ᵢ₋₂ ⋯ A⁻¹₀; so kᵢ₊₁/kᵢ = A⁻¹ᵢ, kᵢ₊₁/kᵢ₋ᵢ = A⁻¹ᵢA⁻¹ᵢ₋₁\n#\n# function Aᵢ⁻¹(n,α,β,𝐍)\n#     num = (2n+α+β + 1) * (2n+α+β+2)\n#     den = (n+α + β + 1)*(n + α + 1) *(𝐍-n)\n#     num/den\n# end\n\n# define kn, k1k_1 through defaults\nfunction k1k0(P::Type{<:Hahn{α,β, 𝐍}}, n::Int) where {α,β,𝐍}\n\n    num  = (2*n + α + β + 1)*(2*n + α + β + 2)\n    den = (-n + 𝐍)*(n + α + 1)*(n + α + β + 1)\n\n    -(one(eltype(P))*num)/den\n    \nend\n\n# end\n\nfunction classical_hypergeometric(::Type{<:Hahn{α,β,𝐍}}, n::Int, x)  where {α,β,𝐍}\n    pFq((-n, -x, n+1+α+β),  (α+1, -𝐍),  1)\nend\n\n", "meta": {"hexsha": "803ddcd82adab607b6ba0746e01aba83d1298d66", "size": 1441, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Orthogonal/Discrete/Hahn.jl", "max_stars_repo_name": "rurz/SpecialPolynomials.jl", "max_stars_repo_head_hexsha": "91196ab12232c4d45a4681e871803fbd6bb3a417", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-06-18T14:37:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T22:25:01.000Z", "max_issues_repo_path": "src/Orthogonal/Discrete/Hahn.jl", "max_issues_repo_name": "rurz/SpecialPolynomials.jl", "max_issues_repo_head_hexsha": "91196ab12232c4d45a4681e871803fbd6bb3a417", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2020-06-05T19:42:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T16:46:17.000Z", "max_forks_repo_path": "src/Orthogonal/Discrete/Hahn.jl", "max_forks_repo_name": "rurz/SpecialPolynomials.jl", "max_forks_repo_head_hexsha": "91196ab12232c4d45a4681e871803fbd6bb3a417", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-02-11T04:04:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T07:19:21.000Z", "avg_line_length": 30.0208333333, "max_line_length": 157, "alphanum_fraction": 0.5572519084, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384593, "lm_q2_score": 0.8633916187614823, "lm_q1q2_score": 0.7787107597317854}}
{"text": "\nusing Tables\nusing DataFrames\nusing StatsPlots\nusing BenchmarkTools\n\n\nfunction sir_ode!(du,u,p,t)\n    (S,I,R) = u\n    (β,c,γ) = p\n    N = S+I+R\n    @inbounds begin\n        du[1] = -β*c*I/N*S\n        du[2] = β*c*I/N*S - γ*I\n        du[3] = γ*I\n    end\n    nothing\nend;\n\n\nt0 = 0.0\nδt = 0.1\ntmax = 40.0\nu0 = [990.0,10.0,0.0] # S,I,R\np = [0.05,10.0,0.25]; # β,c,γ\n\n\nfunction euler(f, u0, p, δt, t0, tmax)\n    t = t0 # Initialize time\n    u = copy(u0) # Initialize struct parametric inherited\n    du = zeros(length(u0)) # Initialize derivatives\n    f(du,u,p,t)\n    sol = [] # Store output\n    times = [] # Store times\n    push!(sol,copy(u))\n    push!(times,t)\n    # Main loop\n    while t < tmax\n        t = t + δt # Update time\n        u .= u .+ du.*δt # Update state\n        sir_ode!(du,u,p,t) # Update derivative\n        push!(sol,copy(u)) # Store output\n        push!(times,t) # Store time\n    end\n    sol = hcat(sol...) # Convert to matrix\n    return times, sol\nend;\n\n\ntimes, sol = euler(sir_ode!, u0, p, δt, t0, tmax);\n\n\ndf = DataFrame(Tables.table(sol'))\nrename!(df,[\"S\",\"I\",\"R\"])\ndf[!,:t] = times;\n\n\n@df df plot(:t,\n    [:S :I :R],\n    label=[\"S\" \"I\" \"R\"],\n    xlabel=\"Time\",\n    ylabel=\"Number\")\n\n\n@benchmark euler(sir_ode!, u0, p, δt, t0, tmax)\n\n", "meta": {"hexsha": "3df5435585f9055e7486a48d8df76d3c40b7f0e8", "size": 1251, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_euler/ode_euler.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/ode_euler/ode_euler.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/ode_euler/ode_euler.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.671641791, "max_line_length": 57, "alphanum_fraction": 0.5379696243, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7786667614002722}}
{"text": "# Nonlinear curve fitting.\n\n\"\"\"\n# Nonlinear multi-variable least squares\n\nUses a Newton like algorithm to compute the least squares fit \nof a model\n\n## Parameters:\n\n * `x` an array where each colum is a variable\n * `fun` The function that should be fitted (more later on)\n * `a0` An initial guess for each fitting parameter\n * `eps` Convergence criterion\n * `maxiter` Maximum number of iterations\n\n## Specifying the model\n\nThe model is specified in argument `fun` that should be callable according\nto the following signature:\n\n`r = fun(x, a)`\n\nwhere both `x` and `a` are vectors\n\nThe way the algorithm is implemented allows for the function to be implicit. This means\nthat we are trying to fit the relationship `fun(x, a) = 0`. \n\n## Initial guess\n\nThe initial guess is important and should be as close as possible to the expeted values. It should, at least, give an order of magnitude of each parameter. Zero values are not recommended since in this \ncase no order of magnitude is available and it is assumed. The initial step is assumed to be `a0/10`.\n\n## Convergence criterion\n\nThe initial guess `a0` will probably not fit the data very well. The largest value\nof `maxerr = maxabs(fun(x, a0))` (maximum error) is used as a reference and \nevery time a new approximation is computed, if the change in paramaters is compared to this\nreference error. If it is small, `maxabs(da) < eps*maxerr`, the algorithm converged.\n\n## Return values\n\nA tuple containing:\n\n * The estimated coefficients\n * A `Bool` stating whether the algorithm converged\n * Number of iterations it took to converge.\n\n\"\"\"\nfunction nonlinear_fit(x, fun, a0, eps=1e-8, maxiter=200)\n\n    na = length(a0)\n    np = size(x, 1)\n    nv = size(x, 2)\n    for i in 1:na\n        if a0[i] == 0\n            a0[i] = 0.01\n        end\n    end\n\n    da = a0 / 10\n    a1 = zeros(na)\n    a = zeros(na)\n    for k = 1:na\n        a1[k] = a0[k] - da[k]\n    end\n    xp = zeros(nv)\n    A = zeros(np, na)\n    r0 = zeros(np)\n    r1 = zeros(np)\n    for p = 1:np\n        for k = 1:nv\n            xp[k] = x[p,k]\n        end\n        r0[p] = fun(xp, a0)\n        r1[p] = fun(xp, a1)\n    end\n    maxerr = maximum(abs, [maximum(abs, r0), maximum(abs, r1)])\n    iter = 1\n    convergence = false\n    for i = 1:maxiter\n        iter = i\n        for p = 1:np\n            for k = 1:nv\n                xp[k] = x[p,k]\n            end\n            for k = 1:na\n                aa = a1[k]\n                a1[k] = a1[k] + da[k]\n                r = fun(xp, a1)\n                a1[k] = aa\n                  \n                A[p,k] = -(r1[p] - r) / da[k]\n            end\n        end\n        da = A \\ r1\n        for k = 1:na\n            a1[k] = a1[k] - da[k]\n        end\n        for p = 1:np\n            r0[p] = r1[p]\n            for k = 1:nv\n                xp[k] = x[p,k]\n            end\n            r1[p] = fun(xp, a1)\n        end\n        if maximum(abs, r1) < eps * maxerr\n            convergence = true\n            break\n        end\n    end\n\n    return a1, convergence, iter\nend\n\n\n\"\"\"\n   a = gauss_newton_fit(x, y, fun, ∇fun!, a0[[, eps,] maxiter])\n\nGauss-Newton nonlinear least squares. Given vectors `x` and `y`, the tries to fit parameters `a` to \na function `f` using least squares approximation:\n\n ``y = f(x, a₁, ..., aₙ)``\n\nFor more general approximations, see [`gauss_newton_fit`](@ref).\n\n### Arguments:\n\n * `x` Vector with x values\n * `y` Vector with y values\n * `fun` a function that is called as `fun(x, a)` where `a` is a vector of parameters.\n * `∇fun!` A function that calculares the derivatives with respect to parameters `a`\n * `a0` Vector with the initial guesses of the parameters\n * `eps` Maximum residual for convergence\n * `maxiter` Maximum number of iterations for convergence\n\n## Return value\n\nA vector with the convrged array. If no convergence is achieved, the function throws an error.\n\n## Specification of the fitting function\n\nThe function that should be fitted shoud be specified by Julia funcion with the following signature:\n\n```julia\nfun(x::T, a::AbstractVector{T}) where {T<:Number}\n```\n\nThe derivatives with respect to each fitting parameter `a[i]` should have the following signature:\n\n```julia\n∇fun!(x::T, a::AbstractVector{T}, df::AbstractVector{T}) where {T<:Number}\n```\n\nNo return value is expected and the derivatives are returned in argument `df`.\n\n## Initial approximation (guess)\n\nIf the initial approximation is not good enough, divergence is possible. \n\n**Careful** with parameters close to 0. The initial guess should never be 0.0 because the initial\nvalue of the parameter is used as reference value for computing resiuduals.\n\n## Convergence criteria\n\nThe argumento `maxiter` specifies the maximum number of iterations that should be carried out. \nAt each iteration, \n\n``aₖⁿ⁺¹ = aₖⁿ + δₖ``\n\nConvergence is achieved when\n\n``|δᵏ / aₖ⁰| < ε``\n\n## Example\n```julia\nx = 1.0:10.0\na = [3.0, 2.0, 1.0]\ny = a[1] + a[2]*x + a[3]*x^2\nfun(x, a) = a[1] + a[2]*x + a[3]*x^2\n\nfunction ∇fun!(x, a, df) \n    df[1] = 1.0\n    df[2] = x\n    df[3] = x^2\nend\n\na = gauss_newton_fit(x, y, fun, ∇fun!, [0.5, 0.5, 0.5], 1e-8, 30)\n```\n\"\"\"\nfunction gauss_newton_fit(x::AbstractVector{T}, y::AbstractVector{T}, fun, ∇fun!, a0::AbstractVector{T},\n                          eps=1e-8, maxiter=200) where {T<:Number}\n    P = length(x) # Number of points\n    N = length(a0) # Number of parameters\n    \n    xi = zero(T)\n    df = zeros(T, N)\n    a = zeros(T, N)\n    for i in 1:N\n        a[i] = a0[i]\n        if a[i] == 0\n            a[i] = 0.01\n        end\n    end\n\n    A = zeros(T, N, N)\n    b = zeros(T, N)\n\n    δref = abs.(a)\n    maxerr = zero(T)\n    for iter = 1:maxiter\n        A .= zero(T)\n        b .= zero(T)\n        for i in 1:P\n            xi = x[i]\n            yi = y[i]\n            f = fun(xi, a) - yi\n            ∇fun!(xi, a, df)\n\n            # Assemble LHS\n            for k in 1:N\n                for j in 1:N\n                    A[j,k] += df[j] * df[k]\n                end\n            end\n            # Assemble RHS\n            for j in 1:N\n                b[j] -= f * df[j]\n            end\n        end\n\n        δ = A\\b\n        a .+= δ\n\n        # Verify convergence:\n        maxerr = maximum(abs, δ./δref)\n        if maxerr < eps\n            return(a)\n        end\n        \n    end\n\n    error(\"gauss_newton_fit failed to converge in $maxiter iterations with relative residual of $maxerr !\")\n    \n    return(a)\nend\n\n\"\"\"\n   a = gauss_newton_generic_fit(x, y, fun, ∇fun!, a0[[, eps,] maxiter])\n\nGauss-Newton nonlinear least squares. Given matrix `x` the function tries to fit parameters `a` to \nan implicit function `f` using least squares approximation:\n\n``f(x₁,..., xₘ, a₁, ..., aₙ) = 0``\n\nThis function is very similar to [`gauss_newton_fit`](@ref) but more generic. It doesn't limit the number of \nindependent variables and doesn't require a `y` LHS.\n\n\n### Arguments:\n\n * `x` Matrix where each column is a variable\n * `\n * `fun` a function that is called as `fun(x, a)` where `a` is a vector of parameters.\n * `∇fun!` A function that calculares the derivatives with respect to parameters `a`\n * `a0` Vector with the initial guesses of the parameters\n * `eps` Maximum residual for convergence\n * `maxiter` Maximum number of iterations for convergence\n\n## Return value\n\nA vector with the convrged array. If no convergence is achieved, the function throws an error.\n\n## Specification of the fitting function\n\nThe function that should be fitted shoud be specified by Julia funcion with the following signature:\n\n```julia\nfun(x::T, a::AbstractVector{T}) where {T<:Number}\n```\n\nThe derivatives with respect to each fitting parameter `a[i]` should have the following signature:\n\n```julia\n∇fun!(x::T, a::AbstractVector{T}, df::AbstractVector{T}) where {T<:Number}\n```\n\nNo return value is expected and the derivatives are returned in argument `df`.\n\n## Initial approximation (guess)\n\nIf the initial approximation is not good enough, divergence is possible. \n\n**Careful** with parameters close to 0. The initial guess should never be 0.0 because the initial\nvalue of the parameter is used as reference value for computing resiuduals.\n\n## Convergence criteria\n\nThe argumento `maxiter` specifies the maximum number of iterations that should be carried out. \nAt each iteration, \n\n``aₖⁿ⁺¹ = aₖⁿ + δₖ``\n\nConvergence is achieved when\n\n``|δᵏ / aₖ⁰| < ε``\n\n## Example\n```julia\nx = 1.0:10.0\na = [3.0, 2.0, 1.0]\ny = a[1] + a[2]*x + a[3]*x^2\nfun(x, a) = a[1] + a[2]*x + a[3]*x^2\n\nfunction ∇fun!(x, a, df) \n    df[1] = 1.0\n    df[2] = x\n    df[3] = x^2\nend\n\na = gauss_newton_fit(x, y, fun, ∇fun!, [0.5, 0.5, 0.5], 1e-8, 30)\n```\n\n\"\"\"\nfunction gauss_newton_generic_fit(x::AbstractMatrix{T}, fun, ∇fun!, a0::AbstractVector{T},\n                          eps=1e-8, maxiter=200) where {T<:Number}\n    P = size(x, 1) # Number of points\n    M = size(x, 2) # Number of columns (variables)\n    N = length(a0) # Number of parameters\n    \n    xi = zeros(T, M)\n    df = zeros(T, N)\n    a = zeros(T, N)\n    for i in 1:N\n        a[i] = a0[i]\n        if a[i] == 0\n            a[i] = 0.01\n        end\n    end\n\n    A = zeros(T, N, N)\n    b = zeros(T, N)\n\n    δref = abs.(a)\n    maxerr = zero(T)\n    for iter = 1:maxiter\n        A .= zero(T)\n        b .= zero(T)\n        for i in 1:P\n            for k in 1:M\n                xi[k] = x[i,k]\n            end\n            f = fun(xi, a)\n            \n            ∇fun!(xi, a, df)\n            # Assemble LHS\n            for k in 1:N\n                for j in 1:N\n                    A[j,k] += df[j] * df[k]\n                end\n            end\n            # Assemble RHS\n            for j in 1:N\n                b[j] -= f * df[j]\n            end\n        end\n\n        δ = A\\b\n        a .+= δ\n\n        # Verify convergence:\n        maxerr = maximum(abs, δ./δref)\n        if maxerr < eps\n            return(a)\n        end\n        \n    end\n\n    error(\"gauss_newton_fit failed to converge in $maxiter iterations with relative residual of $maxerr !\")\n    \n    return(a)\nend\n\n\n\n        \n        \n    \n\"\"\"\n   a = secant_nls_fit(x, y, fun, ∇fun!, a0[[, eps,] maxiter])\n\nSecant/Gauss-Newton nonlinear least squares. DOESN'T NEED A DERIVATIVE FUNCTION. Given vectors `x` and `y`, the tries to fit parameters `a` to \na function `f` using least squares approximation:\n\n ``y = f(x, a₁, ..., aₙ)``\n\nFor more general approximations, see [`gauss_newton_fit`](@ref).\n\n### Arguments:\n\n * `x` Vector with x values\n * `y` Vector with y values\n * `fun` a function that is called as `fun(x, a)` where `a` is a vector of parameters.\n * `∇fun!` A function that calculares the derivatives with respect to parameters `a`\n * `a0` Vector with the initial guesses of the parameters\n * `eps` Maximum residual for convergence\n * `maxiter` Maximum number of iterations for convergence\n\n## Return value\n\nA vector with the convrged array. If no convergence is achieved, the function throws an error.\n\n## Specification of the fitting function\n\nThe function that should be fitted shoud be specified by Julia funcion with the following signature:\n\n```julia\nfun(x::T, a::AbstractVector{T}) where {T<:Number}\n```\n\nThe derivatives with respect to each fitting parameter `a[i]` should have the following signature:\n\n```julia\n∇fun!(x::T, a::AbstractVector{T}, df::AbstractVector{T}) where {T<:Number}\n```\n\nNo return value is expected and the derivatives are returned in argument `df`.\n\n## Initial approximation (guess)\n\nIf the initial approximation is not good enough, divergence is possible. \n\n**Careful** with parameters close to 0. The initial guess should never be 0.0 because the initial\nvalue of the parameter is used as reference value for computing resiuduals.\n\n## Convergence criteria\n\nThe argumento `maxiter` specifies the maximum number of iterations that should be carried out. \nAt each iteration, \n\n``aₖⁿ⁺¹ = aₖⁿ + δₖ``\n\nConvergence is achieved when\n\n``|δᵏ / aₖ⁰| < ε``\n\n## Example\n```julia\nx = 1.0:10.0\na = [3.0, 2.0, 1.0]\ny = a[1] + a[2]*x + a[3]*x^2\nfun(x, a) = a[1] + a[2]*x + a[3]*x^2\n\na = secant_nls_fit(x, y, fun, ∇fun!, [0.5, 0.5, 0.5], 1e-8, 30)\n```\n\"\"\"\n\nfunction secant_nls_fit(x::AbstractVector{T}, y::AbstractVector{T}, fun, aguess::AbstractVector{T},\n                          eps=1e-8, maxiter=200) where {T<:Number}\n    P = length(x) # Number of points\n    N = length(aguess) # Number of parameters\n    \n    xi = zero(T)\n    df = zeros(T, N)\n    a = zeros(T, N)\n    for i in 1:N\n        a[i] = aguess[i]\n        if a[i] == 0\n            a[i] = 0.01\n        end\n    end\n\n    δ = a .* (one(T)/20)\n    f1 = zeros(T, P)\n    a .+= δ\n    A = zeros(T, N, N)\n    b = zeros(T, N)\n\n    δref = abs.(a)\n    maxerr = zero(T)\n    for iter = 1:maxiter\n\n        A .= zero(T)\n        b .= zero(T)\n        f1 .= fun.(x, Ref(a))\n        for i in 1:P\n            xi = x[i]\n            yi = y[i]\n            f = f1[i] - yi\n            for k in 1:N\n                a[k] -= δ[k]\n                df[k] = (f1[i] - fun(xi, a)) / δ[k]\n                a[k] += δ[k]\n            end\n            # Assemble LHS\n            for k in 1:N\n                for j in 1:N\n                    A[j,k] += df[j] * df[k]\n                end\n            end\n            # Assemble RHS\n            for j in 1:N\n                b[j] -= f * df[j]\n            end\n        end\n        δ = A\\b\n        a .+= δ\n        # Verify convergence:\n        maxerr = maximum(abs, δ./δref)\n        if maxerr < eps\n            return(a)\n        end\n        \n    end\n\n    error(\"gauss_newton_fit failed to converge in $maxiter iterations with relative residual of $maxerr !\")\n    \n    return(a)\nend\n\n\n        \n", "meta": {"hexsha": "96fea05db1e8ecb72a13f11503ac2b8d835470c2", "size": 13478, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nonlinfit.jl", "max_stars_repo_name": "AndreChinazzo/CurveFit.jl", "max_stars_repo_head_hexsha": "9c89c266964ccc4b367192a970f1e07a95dd2550", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67, "max_stars_repo_stars_event_min_datetime": "2015-02-06T15:21:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T17:15:00.000Z", "max_issues_repo_path": "src/nonlinfit.jl", "max_issues_repo_name": "AndreChinazzo/CurveFit.jl", "max_issues_repo_head_hexsha": "9c89c266964ccc4b367192a970f1e07a95dd2550", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2016-01-18T17:04:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T18:59:00.000Z", "max_forks_repo_path": "src/nonlinfit.jl", "max_forks_repo_name": "AndreChinazzo/CurveFit.jl", "max_forks_repo_head_hexsha": "9c89c266964ccc4b367192a970f1e07a95dd2550", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2015-04-25T18:57:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T17:34:59.000Z", "avg_line_length": 25.7705544933, "max_line_length": 202, "alphanum_fraction": 0.5786466835, "num_tokens": 4047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7786667614002721}}
{"text": "\n# Generate a random graph with n vertices where each edge is included with probability p.\nfunction erdos_renyi_graph(g::GT, n::Integer, p::Real; has_self_loops=false) where {GT<:AbstractGraph}\n    for i=1:n\n        start_ind = is_directed(g) ? 1 : i\n        for j=start_ind:n\n            if(rand() <= p && (i != j || has_self_loops))\n                add_edge!(g, i, j)\n            end\n        end\n    end\n    return g\nend\n\n# Convenience function with a default graph type.\nfunction erdos_renyi_graph(n::Integer, p::Real; is_directed=true, has_self_loops=false)\n    g = simple_inclist(n, is_directed=is_directed)\n    erdos_renyi_graph(g, n, p, has_self_loops=has_self_loops)\nend\n\n# Generate a 'small world' random graph based on the Watts-Strogatz model.\n# Written with much reference to the implementation from GraphStream <http://graphstream-project.org>.\n# The resulting graph has n vertices,\n#   Each vertex has a base degree of k  (n > k, k >= 2, k must be even.)\n#   There is a beta chance of each edge being 'rewired'\nfunction watts_strogatz_graph(g::GT, n::Integer, k::Integer, beta::Real) where {GT<:AbstractGraph}\n    # When attributes are restored, we can enable placing the vertices around a circle.\n    # This is nice for explicit visualization of the model.\n    #space = linspace(0,2*pi,n+1)\n    #for v in vertices(g)\n    #    attrs = attributes(v)\n    #    x = round((cos(space[i]) + 1)*100,2)\n    #    y = round((sin(space[i]) + 1)*100,2)\n    #    attrs[\"pos\"] = \"$(x),$(y)\"\n    #end\n\n    # Link each node to the k/2 nodes next to it in each direction.\n    # For each vertex in the graph:\n    for i in 1:n\n        # For the next k/2 higher indexed nodes:\n        for j in 1:div(k,2)\n            # Either make an edge to the neighbor or a long edge across the graph.\n            if rand() > beta\n                add_edge!(g, i, ((i+j - 1) % n) + 1 )\n            else\n                # Add a random link across the graph and delete the link to the neighbor.\n                while true\n                    target = rand(1:(n-1))\n                    if (target >= i)\n                        target += 1\n                    end\n                    if !(target in out_neighbors(i,g))\n                        add_edge!(g,i, target)\n                        break\n                    end\n                end\n            end\n        end\n    end\n    g\nend\n\n# Convenience function with a default graph type.\nfunction watts_strogatz_graph(n::Integer, k::Integer, beta::Real)\n    g = simple_inclist(n, is_directed=false)\n    watts_strogatz_graph(g,n,k,beta)\nend\n", "meta": {"hexsha": "63007afbe21dec7f4064860ad335b5a6516e7edc", "size": 2564, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/random.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Graphs.jl-86223c79-3864-5bf0-83f7-82e725a168b6", "max_stars_repo_head_hexsha": "b76b9914178a417085681167643af510547e8a0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2018-08-19T13:26:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-07T08:17:35.000Z", "max_issues_repo_path": "src/random.jl", "max_issues_repo_name": "JuliaAttic/OldGraphs.jl", "max_issues_repo_head_hexsha": "39a9c6efacc190ac79db47dd4dd951657058d2c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-02-20T22:05:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T15:20:41.000Z", "max_forks_repo_path": "src/random.jl", "max_forks_repo_name": "JuliaAttic/OldGraphs.jl", "max_forks_repo_head_hexsha": "39a9c6efacc190ac79db47dd4dd951657058d2c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-02-12T18:37:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-03T14:09:36.000Z", "avg_line_length": 37.7058823529, "max_line_length": 102, "alphanum_fraction": 0.5889235569, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.8807970654616711, "lm_q1q2_score": 0.7786592158786185}}
{"text": "#All these examples of path are in 4 stages\n\nusing Distributions, Random\nrng = MersenneTwister(01012019);\n\n\"\"\"\n\tgaussian_path1D()\n\nReturns a '4x1' dimensional array of Gaussian random walk\n\"\"\"\nfunction gaussian_path1D()\n    return vcat(0.0, cumsum(randn(rng, 3, 1), dims = 1)) #4 stages\nend\n\n\"\"\"\n\tgaussian_path2D()\n\nReturns a '4x2' dimensional array of Gaussian random walk\n\"\"\"\nfunction gaussian_path2D()\n    gsmatrix = randn(rng, 4, 2) * [1.0 0.0 ; 0.9 0.3] #will create an (dimension x nstages) matrix\n    gsmatrix[1,:] .= 0.0\n    return cumsum(gsmatrix .+ [1.0 0.0], dims = 1)\nend\n\n\"\"\"\n\trunning_maximum1D()\n\nReturns a '4x1' dimensional array of Running Maximum process.\n\"\"\"\nfunction running_maximum1D()\n    rmatrix = vcat(0.0, cumsum(randn(rng, 3, 1), dims = 1))\n    for i = 2 : 4\n        rmatrix[i] = max.(rmatrix[i-1], rmatrix[i])\n    end\n    return rmatrix\nend\n\n\"\"\"\n\trunning_maximum2D()\n\nReturns a '4x2' dimensional array of Running Maximum process.\n\"\"\"\nfunction running_maximum2D()\n    rmatrix = vcat(0.0, cumsum(randn(rng, 3, 1), dims = 1))\n    rmatrix2D = zeros(4, 2)\n    rmatrix2D[:,1] .= vec(rmatrix)\n    for j = 2 : 2\n        for i = 2 : 4\n            rmatrix2D[i,j] = max.(rmatrix[i-1], rmatrix[i])\n        end\n    end\n    return rmatrix2D * [1.0 0.0; 0.9 0.3]\nend\n\n\"\"\"\n\tpath()\n\nReturns a sample of stock prices following the a simple random random process.\n\"\"\"\nfunction path()\n    return  100 .+ 50 * vcat(0.0, cumsum(randn(rng, 3, 1), dims = 1))\nend\n", "meta": {"hexsha": "39f9955f201bbc8c797edbd4440688ffa2e76353", "size": 1465, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/StochPaths.jl", "max_stars_repo_name": "kirui93/ScenTrees.jl", "max_stars_repo_head_hexsha": "7a0637c6717a3256429b959eee209cdeaafd4e02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-08-29T07:38:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T01:25:43.000Z", "max_issues_repo_path": "src/StochPaths.jl", "max_issues_repo_name": "rubsc/ScenTrees.jl", "max_issues_repo_head_hexsha": "e13e7b06f29a387e1f2afcd0f3575b77ef6132bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2019-09-06T13:18:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-31T22:20:03.000Z", "max_forks_repo_path": "src/StochPaths.jl", "max_forks_repo_name": "rubsc/ScenTrees.jl", "max_forks_repo_head_hexsha": "e13e7b06f29a387e1f2afcd0f3575b77ef6132bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-11-22T18:25:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T00:23:17.000Z", "avg_line_length": 22.890625, "max_line_length": 98, "alphanum_fraction": 0.6409556314, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7786544733192432}}
{"text": "export color, chromatic_number\n\n\"\"\"\n`color(G,k)`: Return a `k`-coloring of `G` (or error if none exists).\n\"\"\"\nfunction color(G::SimpleGraph, k::Int)\n    VV = vlist(G)\n    EE = elist(G)\n    n = NV(G)\n    m = NE(G)\n\n    if k<1\n        error(\"Number of colors must be positive\")\n    end\n\n    err_msg = \"This graph is not \" * string(k) * \" colorable\"\n\n    # Special cases that don't require integer programming\n\n    # see if we know the chromatic number already\n    if cache_check(G,:chromatic_number)\n        chi = cache_recall(G,:chromatic_number)\n        if k<chi\n            error(err_msg)\n        end\n    end\n\n    result = Dict{vertex_type(G),Int}()\n\n    if k==1\n        if NE(G) > 0\n            error(err_msg)\n        end\n        for v in VV\n            result[v] = 1\n        end\n        return result\n    end\n\n    if k==2\n        return two_color(G)\n    end\n\n    MOD = Model(get_solver())\n\n    @variable(MOD, x[VV,1:k], Bin)\n\n    for v in VV\n        @constraint(MOD, sum(x[v,i] for i=1:k) == 1)\n    end\n\n    for e in EE\n        u = e[1]\n        v = e[2]\n        for i=1:k\n            @constraint(MOD, x[u,i] + x[v,i] <= 1)\n        end\n    end\n\n    optimize!(MOD)\n    status = Int(termination_status(MOD))\n\n    if status != 1\n        error(err_msg)\n    end\n\n\n    X = value.(x)\n\n    for v in VV\n        for c = 1:k\n            if X[v,c] > 0\n                result[v] = c\n            end\n        end\n    end\n\n    return result\nend\n\n\n\n\nfunction chromatic_number(G::SimpleGraph, verb::Bool=false)::Int\n    if cache_check(G,:chromatic_number)\n        return cache_recall(G,:chromatic_number)\n    end\n\n    if NV(G) == 0\n        return 0\n    end\n    if NE(G) == 0\n        return 1\n    end\n\n    # lower bound: larger of clique size or n/alpha\n    n = NV(G)\n    alf = length(max_indep_set(G))\n    lb1 = Int(floor(n/alf))\n    lb2 = length(max_clique(G))\n    lb = max(lb1,lb2)\n\n    # upper bound: try a random greedy coloring\n    f = greedy_color(G)\n    ub = maximum(values(f))\n\n    k =  chromatic_number_work(G,lb,ub,verb)\n    cache_save(G,:chromatic_number,k)\n    return k\nend\n\n\n\nfunction chromatic_number_work(G::SimpleGraph, lb::Int, ub::Int, verb::Bool)::Int\n    if verb\n        print(\"$lb <= chi(G) <= $ub\")\n    end\n    if lb == ub\n        if verb\n            println(\"\\tand we're done\")\n        end\n        return lb\n    end\n\n    mid = Int(floor((ub+lb)/2))\n\n    if verb\n        print(\"\\tlooking for a $mid coloring\")\n    end\n\n    try\n        f = color(G,mid)  # success\n        if verb\n            println(\"\\tfound\")\n        end\n        return chromatic_number_work(G,lb,mid,verb)\n    catch\n    end\n    if verb\n        println(\"\\tno such coloring\")\n    end\n    return chromatic_number_work(G,mid+1,ub,verb)\nend\n", "meta": {"hexsha": "335a07e9ab6628e16b53ec106ab41fb670ad4f9a", "size": 2710, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kcolor.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SimpleGraphAlgorithms.jl-41400c72-0c58-5c16-8579-4ecbce768449", "max_stars_repo_head_hexsha": "e310e66612bd9c7def9b167ac424da03b8b3b224", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kcolor.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SimpleGraphAlgorithms.jl-41400c72-0c58-5c16-8579-4ecbce768449", "max_issues_repo_head_hexsha": "e310e66612bd9c7def9b167ac424da03b8b3b224", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kcolor.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SimpleGraphAlgorithms.jl-41400c72-0c58-5c16-8579-4ecbce768449", "max_forks_repo_head_hexsha": "e310e66612bd9c7def9b167ac424da03b8b3b224", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8194444444, "max_line_length": 81, "alphanum_fraction": 0.536900369, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951570602081, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7786544641848018}}
{"text": "@model function gmm_tarray(x, K)\n    N = length(x)\n    \n    # Cluster centers.\n    μ ~ filldist(Normal(), K)\n\n    # Cluster association prior.\n    w ~ Dirichlet(K, 1.0)\n\n    # Cluster assignments.\n    z = tzeros(Int, N)\n    for n = 1:N\n        z[n] ~ DiscreteNonParametric(1:K, w)\n    end\n    \n    # Observations.\n    for n = 1:N\n        x[n] ~ Normal(μ[z[n]], 1.0)\n    end\nend\n\ngmm_tarray_example(x = [0.1, -0.05, 1.0], K = 2) = gmm_tarray(x, K)\n\n\n# K clusters, each one around i for i = 1:K with variance 0.5\n@model function hmm_tarray(x, K, ::Type{T}=Float64) where {T<:Real}\n    N = length(x)\n\n    # State sequence.\n    s = tzeros(Int, N)\n\n    # Emission matrix.\n    m = Vector{T}(undef, K)\n\n    # Transition matrix.\n    T = Vector{Vector{T}}(undef, K)\n\n    # Assign distributions to each element\n    # of the transition matrix and the\n    # emission matrix.\n    for i = 1:K\n        T[i] ~ Dirichlet(K, 1.0)\n        m[i] ~ Normal(i, 0.5)\n    end\n    \n    # Observe each point of the input.\n    s[1] ~ Categorical(K)\n    x[1] ~ Normal(m[s[1]], 0.1)\n\n    for i = 2:N\n        s[i] ~ Categorical(T[s[i-1]])\n        x[i] ~ Normal(m[s[i]], 0.1)\n    end\nend\n\nhmm_tarray_example(x = [0.1, -0.05, 1.0], K = 2) = hmm_tarray(x, K)\n\n\nfunction stickbreak(v)\n    K = length(v) + 1\n    cumprod_one_minus_v = cumprod(1 .- v)\n\n    return map(1:K) do k\n        if k == 1\n            v[1]\n        elseif k == K\n            cumprod_one_minus_v[K - 1]\n        else\n            v[k] * cumprod_one_minus_v[k - 1]\n        end\n    end\nend\n\n@model function imm_stick_tarray(y, α, K)\n    N = length(y)\n    crm = DirichletProcess(α)\n\n    v ~ filldist(StickBreakingProcess(crm), K - 1)\n    w = stickbreak(v)\n    \n    # Cluster assignments\n    z = tzeros(Int, N)\n    for n = 1:N\n        z[n] ~ Categorical(w)\n    end\n\n    # Cluster centers\n    L = identity(K)\n    μ ~ filldist(Normal(), L)\n\n    # Observations\n    for n = 1:N\n        y[n] ~ Normal(μ[z[n]], 1.0)\n    end\nend\n\nimm_stick_tarray_example(y = data_neal, α = α_neal, K = 10) = imm_stick_tarray()\n", "meta": {"hexsha": "ad9c233d57274709084484f60a127733f7508ce7", "size": 2030, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/models_comparison.jl", "max_stars_repo_name": "trappmartin/AutoGibbs.jl", "max_stars_repo_head_hexsha": "eb4bfb37b4bd298dbccc143518852da3223ce80b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/models_comparison.jl", "max_issues_repo_name": "trappmartin/AutoGibbs.jl", "max_issues_repo_head_hexsha": "eb4bfb37b4bd298dbccc143518852da3223ce80b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/models_comparison.jl", "max_forks_repo_name": "trappmartin/AutoGibbs.jl", "max_forks_repo_head_hexsha": "eb4bfb37b4bd298dbccc143518852da3223ce80b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7142857143, "max_line_length": 80, "alphanum_fraction": 0.5438423645, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693617046216, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7786275893415984}}
{"text": "using LinearAlgebra\nusing SpecialFunctions\nusing OffsetArrays\n\nconst Γ = gamma\n\n# Coefficients in the Jacobi polynomial recurrence relations.\na(α, β, n) = 2/(2n+α+β) * √(n * (n+α+β) * (n+α) * (n+β) / (2n+α+β-1) / (2n+α+β+1))\nb(α, β, n) = -(α^2 - β^2) / (2n+α+β) / (2n+α+β+2)\n\n\" Evaluates the Jacobi polynomial Pₙᵅᵝ(x). \"\nfunction jacobi(x, α, β, n::Int)\n    Pᵅᵝ = n <= 1 ? OffsetArray(zeros(2), 0:1) : OffsetArray(zeros(n+1), 0:n)\n    Pᵅᵝ[0] = √(2.0^-(α+β+1) * Γ(α+β+2) / Γ(α+1) / Γ(β+1))\n    Pᵅᵝ[1] = Pᵅᵝ[0]/2 * √((α+β+3) / (α+1) / (β+1)) * ((α+β+2)*x + α - β)\n    for n′ in 1:n-1\n        Pᵅᵝ[n′+1] = ((x - b(α,β,n′)) * Pᵅᵝ[n′] - a(α,β,n′) * Pᵅᵝ[n′-1]) / a(α, β, n′+1)\n    end\n    return Pᵅᵝ[n]\nend\n\n\" Evaluates the derivative of the Jacobi polynomial Pₙᵅᵝ(x). \"\n∂jacobi(x, α, β, n::Int) = n == 0 ? 0 : √(n * (n+α+β+1)) * jacobi(x, α+1, β+1, n-1)\n\n\" Guassian quadrature points and weights for the Jacobi polynomial Pₙᵅᵝ. \"\nfunction jacobi_gauss_quadrature(α, β, N)\n    N == 0 && return [(α-β) / (α+β+2)], [2]\n\n    # Form symmetric matrix from recurrence.\n    dv = OffsetArray(zeros(N+1), 0:N)  # diagonal vector\n    ev = OffsetArray(zeros(N+1), 0:N)  # sub/super-diagonal vector\n\n    for n in 0:N\n        dv[n] = b(α, β, n)\n        ev[n] = a(α, β, n)\n    end\n\n    # Create full matrix combining the two.\n    # Need to pass arrays that are not offset.\n    J = SymTridiagonal(dv[0:N], ev[1:N])\n    (α + β) ≈ 0 && (J[1, 1] = 0)\n\n    # Compute quadrature points and weights by eigenvalue solve.\n    x, V = eigen(J)\n    w = @. V[1, :]^2 * 2^(α+β+1) / (α+β+1)\n    @. w *= factorial(α) * factorial(β) / factorial(α+β)\n\n    return x, w\nend\n\n\" Guass-Labatto quadrature points for the Jacobi Polynomial Pₙᵅᵝ. \"\nfunction jacobi_gauss_lobatto(α, β, N)\n    N == 0 && error(\"What are you doing? Gauss-Lobatto points only make sense if N >= 1.\")\n    N == 1 && return [-1, 1]\n\n    x = zeros(N+1)\n    x[1], x[N+1] = -1, 1\n\n    x_GQ, _ = jacobi_gauss_quadrature(α+1, β+1, N-2)\n    x[2:N] .= x_GQ\n\n    return x\nend\n", "meta": {"hexsha": "4b215d10c3b84040026517ca2996a96fe33cfb79", "size": 1997, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/jacobi.jl", "max_stars_repo_name": "ali-ramadhan/DiscontinuousGherkins.jl", "max_stars_repo_head_hexsha": "8cef921b3b6491d41134f3b8eb6b1568f408a25b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-29T22:59:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-29T22:59:28.000Z", "max_issues_repo_path": "src/jacobi.jl", "max_issues_repo_name": "ali-ramadhan/nodal-discontinuous-galerkin-julia", "max_issues_repo_head_hexsha": "8cef921b3b6491d41134f3b8eb6b1568f408a25b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-02-13T14:39:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-20T13:14:13.000Z", "max_forks_repo_path": "src/jacobi.jl", "max_forks_repo_name": "ali-ramadhan/nodal-discontinuous-galerkin-julia", "max_forks_repo_head_hexsha": "8cef921b3b6491d41134f3b8eb6b1568f408a25b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.203125, "max_line_length": 90, "alphanum_fraction": 0.5538307461, "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693659780479, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7786275823969548}}
{"text": "function bs(O::Option)\n    d1 = (log(O.s / O.k) + (O.r + O.σ * O.σ / 2) * O.t) / (O.σ * √O.t)\n    d2 = d1 - O.σ * √O.t\n\n    if O.call_or_put == \"Put\"\n        return CND(-d2) * O.k * exp(-O.r * O.t) - CND(-d1) * O.s\n    else\n        return O.s * CND(d1) - exp(-O.r * O.t) * O.k * CND(d2)\n    end\nend\n\nfunction CND(x::Float64)\n    a1 = 0.31938153\n    a2 = -0.356563782\n    a3 = 1.781477937\n    a4 = -1.821255978\n    a5 = 1.330274429\n    l = abs(x)\n    k = 1 / (1 + 0.2316419 * l)\n    \n    CND = 1 - 1 / sqrt(2 * π) * exp(-l^2 / 2) * (a1 * k + a2 * k^2 + a3 * k^3 + a4 * k^4 + a5 * k^5)\n\n    if x < 0\n        return 1 - CND\n    end\n    \n    return CND\nend\n", "meta": {"hexsha": "bde9dbec963a0eb88210c763143d1ffc4d142153", "size": 653, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bs.jl", "max_stars_repo_name": "brilhana/OptionsPricing.jl", "max_stars_repo_head_hexsha": "eccb54341ad41e6260ed24e5dd0f1c1d6698b749", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-10-24T21:21:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-07T16:28:45.000Z", "max_issues_repo_path": "src/bs.jl", "max_issues_repo_name": "brilhana/OptionsPricing.jl", "max_issues_repo_head_hexsha": "eccb54341ad41e6260ed24e5dd0f1c1d6698b749", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bs.jl", "max_forks_repo_name": "brilhana/OptionsPricing.jl", "max_forks_repo_head_hexsha": "eccb54341ad41e6260ed24e5dd0f1c1d6698b749", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-23T02:06:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T02:06:35.000Z", "avg_line_length": 22.5172413793, "max_line_length": 100, "alphanum_fraction": 0.4410413476, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147201714922, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7786046868492952}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6a41e9d0-c58c-11eb-078e-c36bf22a38d2\nmd\"\"\"\n# Support Vector Machines\n\n[Reference 1](https://scikit-learn.org/stable/modules/svm.html)\\\n[Reference 2](https://en.wikipedia.org/wiki/Support_vector_machine)\\\n[Reference 3](http://www.robots.ox.ac.uk/~az/lectures/ml/lect3.pdf)\n\"\"\"\n\n# ╔═╡ 9cfc2328-0e4f-4a86-944c-31c0c133fe9a\nmd\"\"\"\nThe SVM classification problem (directly taken from sklearn website):\\\n\n\nGiven training vectors $x_i\\in \\mathbb{R}^P$, $i=1,...,n$, and a vector $y\\in\\{1,-1\\}^n$\\\nThe goal is to find $w\\in \\mathbb{R}^P$ and $b\\in \\mathbb{R}$ such that prediction given by $\\text{sign}(w^T\\phi(x)+b)$ is accurate for most samples\\\n\n\nSolve the following __primal problem__:\\\n$$\\begin{align}\n\\min_{w,b,\\zeta}\\frac{1}{2}w^Tw+C\\sum^n_{i=1}\\zeta_i\\\\\n\\text{subject to }y_i(w^T\\phi(x_i)+b)\\geq1-\\zeta_i,\\\\\n\\zeta_i\\geq0,i=1,...,n\n\\end{align}$$\\\n\n\nIntuition is we are maximizing the margin (by minimizing $\\|w\\|^2=w^Tw$), while penalize when a sample is misclassified\\\n\n\nThe __dual problem__ to primal is:\\\n$$\\begin{align}\n\\min_\\alpha\\frac{1}{2}\\alpha^TQ\\alpha-e^T\\alpha\\\\\n\\text{subject to }y^T\\alpha=0,\\\\\n0\\leq\\alpha_i\\leq C,i=1,...,n\n\\end{align}$$\\\n\n\n $e$ is vector of all ones, $Q$ is nxn positive semidefinite matrix, $Q_{ij}\\equiv y_iy_jK(x_i,x_j)$, and $K(x_i,x_j)=\\phi(x_i)^T\\phi(x_j)$ is the kernel  \n$\\alpha_i$ are dual coefficients, upper-bounded by $C$\\\nHighlighting the fact that training vectors are implicitly mapped to a higher (or infinite) dimensional space by function $\\phi$\\\n\n\nAfter optimization problem solved, the __output__ for a given sample $x$ is:\n$$\\sum_{i\\in SV}y_i\\alpha_iK(x_i,x)+b$$\\\n\n\nThe problem solved by `liblinear` for `LinearSVC` is a equivant form of primal problem:\\\n$$\\min_{w,b}\\frac{1}{2}w^Tw+C\\sum_{i=1}\\max(0,y_i(w^T\\phi(x_i)+b))$$\\\nwhich does not involve inner products between samples, and therefore cannot apply kernel tricks\\\n\n\n$$C=\\frac{1}{\\text{alpha}}$$\n\"\"\"\n\n# ╔═╡ 30975066-eb17-4682-bda1-fd77f9d44734\nfunction ingredients(path::String)\n\t# this is from the Julia source code (evalfile in base/loading.jl)\n\t# but with the modification that it returns the module instead of the last object\n\tname = Symbol(basename(path))\n\tm = Module(name)\n\tCore.eval(m,\n        Expr(:toplevel,\n             :(eval(x) = $(Expr(:core, :eval))($name, x)),\n             :(include(x) = $(Expr(:top, :include))($name, x)),\n             :(include(mapexpr::Function, x) = $(Expr(:top, :include))(mapexpr, $name, x)),\n             :(include($path))))\n\tm\nend\n\n# ╔═╡ 9088c5d0-f07c-404f-8e08-2c8585f86a2f\nimport Random\n\n# ╔═╡ fc9d6f80-70c1-4518-b9db-29c6e3e2d280\nimport Statistics\n\n# ╔═╡ 6a0019bf-ab70-4095-ac52-7606e401d9a5\nimport LinearAlgebra\n\n# ╔═╡ b8447232-6b1d-4b3a-8d11-a9a2da1cf31b\nJuTools = ingredients(\"../tools.jl\").JuTools\n\n# ╔═╡ e4380307-4abe-4a20-9127-e608d1a5fa6e\nmd\"\"\"\n### Linear SVM Implementation (Hinge Loss)\n\n[Reference](https://stackoverflow.com/questions/48804198/soft-margin-in-linear-support-vector-machine-using-python)\\\n\n\nCost function is:\\\n$$J=\\frac{1}{2}w^Tw+\\frac{C}{N}\\sum^N_{i=1}\\max\\Big(0,1-y_i(w^T\\phi(x_i)+b)\\Big)$$\n\n\nGradient function for $w$ is:\\\n$$\\frac{\\partial J}{\\partial w}=w + \\frac{C}{N}\\sum^N_{i=1}\\begin{cases}\n0 & y_i(w^T\\phi(x_i)+b) \\geq 1\\\\\n-y_i\\phi(x_i) & \\text{otherwise}\n\\end{cases}$$\n\n\nGradient function for $b$ is:\\\n$$\\frac{\\partial J}{\\partial b}=\\frac{C}{N}\\sum^N_{i=1}\\begin{cases}\n0 & y_i(w^T\\phi(x_i)+b) \\geq 1\\\\\n-y_i & \\text{otherwise}\n\\end{cases}$$\n\"\"\"\n\n# ╔═╡ 6841f5fe-45ad-4f71-84d5-368d196a40ab\n# define a struct to store weights\n# this should be returned by a training function\n# alpha should be treated as constant\nmutable struct WeightsLinearSVM\n    C::AbstractFloat\n    w::Array{T} where T<:AbstractFloat\n    b::AbstractFloat\nend\n\n# ╔═╡ a093820c-20a0-4af1-98b3-ea92ad37bc77\n# define cost function for linear SVM\n# assum Y_data is {-1, 1}\nfunction cost(X_data::Array{T} where T<:Number, Y_data::Array{T} where T<:Number, weights::WeightsLinearSVM)::AbstractFloat\n    @assert ndims(Y_data) == ndims(weights.w) == 1\n    @assert size(X_data) == (size(Y_data)[1], size(weights.w)[1])\n    loss_w = 0.5 * (weights.w' * weights.w)\n    loss_inner = 1.0 .- Y_data .* vec(X_data * weights.w .+ weights.b)\n    loss_inner .= map(m->max(0.0,m), loss_inner)\n    loss = loss_w + weights.C * sum(loss_inner) / size(X_data)[1]\n    return loss\nend\n\n# ╔═╡ 8c3fa961-d88d-4e28-98e9-18b8804c568e\nX_data, Y_data = JuTools.data_generate_linear_2d()\n\n# ╔═╡ 6341ae48-9cda-4019-bfe6-443caf8788aa\nY_data .= Y_data .* 2.0 .- 1.0 # convert from {0,1} to {-1,1}\n\n# ╔═╡ 500703d2-e315-44c7-8d6c-c36f40b815df\nX_train, X_test, Y_train, Y_test = JuTools.split_data(X_data, Y_data)\n\n# ╔═╡ 7531e45c-95fd-4664-8c37-3364aae7020b\n@show size(X_train)\n\n# ╔═╡ 747fabf5-fd7b-40cc-b5da-b15f6925cff0\n@show size(X_test)\n\n# ╔═╡ 9504574b-2281-4f8a-83d5-3eea38acec53\n@show size(Y_train)\n\n# ╔═╡ c496efb2-5a50-4131-bd65-e9025a3273a4\n@show size(Y_test)\n\n# ╔═╡ 46e9b187-d445-4efe-b4f2-ad824e5ec832\nweight_test = WeightsLinearSVM(1.0, Random.randn(size(X_data)[2]), Random.randn())\n\n# ╔═╡ 8adbc614-9440-42d3-9672-f3b816e114a4\n# define the learning function (gradient descent)\nfunction learn!(X_data::Array{T} where T<:Number, Y_data::Array{T} where T<:Number, weights::WeightsLinearSVM, alpha::AbstractFloat)\n    @assert ndims(Y_data) == ndims(weights.w) == 1\n    @assert size(X_data) == (size(Y_data)[1], size(weights.w)[1])\n    # compute deciding feature\n    decide = (Y_data .* (X_data * weights.w .+ weights.b)) .< 1 # (? < 1) will be 1, otherwise 0\n    # update w\n    gradient_w = weights.w .+ (weights.C / size(X_data)[1]) .* vec(-(Y_data .* decide)' * X_data)\n    gradient_w .= gradient_w .* alpha\n    weights.w .= weights.w .- gradient_w\n    # update b\n    gradient_b = (weights.C / size(X_data)[1]) * sum(-(Y_data .* decide))\n    gradient_b *= alpha\n    weights.b = weights.b - gradient_b\n    return nothing\nend\n\n# ╔═╡ 633040d0-651b-427f-a5a8-83124bbea43b\n# define prediction function\nfunction predict_proba(X_predict::Array{T} where T<:Number, weights::WeightsLinearSVM)::Array\n    @assert ndims(X_predict) == 2\n    @assert size(X_predict)[2] == size(weights.w)[1]\n    prediction = vec(X_predict * weights.w .+ weights.b)\n    return prediction\nend\n\n# ╔═╡ ea07e163-d2a0-4447-9239-64d1aee8b3a0\n# output prediction is in {-1, 1}\nfunction predict(X_predict::Array{T} where T<:Number, weights::WeightsLinearSVM)::Array\n    @assert ndims(X_predict) == 2\n    @assert size(X_predict)[2] == size(weights.w)[1]\n    prediction = vec(X_predict * weights.w .+ weights.b)\n    prediction .= map(m -> m >= 0 ? 1.0 : -1.0, prediction)\n    return prediction\nend\n\n# ╔═╡ 77bd6c88-335f-46a9-a46b-3d3596d54bf9\nmd\"\"\"\n### SVM (with various kernels)\n\n[Reference](https://en.wikipedia.org/wiki/Quadratic_programming)\\\n\n\nFor solving SVM minimization problem:\\\n$$\\begin{align}\n\\min_\\alpha\\frac{1}{2}\\alpha^TQ\\alpha-e^T\\alpha\\\\\n\\text{subject to }y^T\\alpha=0,\\\\\n0\\leq\\alpha_i\\leq C,i=1,...,n\n\\end{align}$$\\\n\n\nwhere $e$ is vector of all ones, $Q$ is nxn positive semidefinite matrix, $Q_{ij}\\equiv y_iy_jK(x_i,x_j)$, and $K(x_i,x_j)=\\phi(x_i)^T\\phi(x_j)$ is the kernel  \n$\\alpha_i$ are dual coefficients, upper-bounded by $C$\\\n\n\nWe'll be using a Quatratic Programming technique: [Sequential Minimal Optimization](https://en.wikipedia.org/wiki/Sequential_minimal_optimization)(SMO)\\\n\n\nMy implementation is inspired from [this blog](https://jonchar.net/notebooks/SVM/), whose code is originally from [this paper](https://www.researchgate.net/publication/234786663_Fast_Training_of_Support_Vector_Machines_Using_Sequential_Minimal_Optimization)\\\n\n\nThe problem can also be written into (objective function):\\\n$$\\begin{align}\n\\max_\\alpha e^T\\alpha-\\frac{1}{2}\\alpha^TQ\\alpha\\\\\n\\text{subject to }y^T\\alpha=0,\\\\\n0\\leq\\alpha_i\\leq C,i=1,...,n\n\\end{align}$$\\\n\n\nThe kernel functions that I'm going to implement are (using sklearn names):\n* Linear Kernel: $\\langle x_i,x_j \\rangle$  \n* Polynomial Kernel: $(\\gamma\\langle x_i,x_j \\rangle + r)^d$ ($d$ is degree, and $r$ is coeficient, $\\gamma$ is a parameter)  \n* Rbf Kernel: $\\exp(-\\gamma\\|x_i-x_j\\|^2)$, where $\\gamma$ is a parameter  \n* Sigmoid Kernel: $\\tanh(\\gamma\\langle x_i,x_j \\rangle + r)$, where $r$ and $\\gamma$ are parameters  \n\"\"\"\n\n# ╔═╡ 111304b2-bfbb-4875-838a-93c153d452be\n# define a struct to store information\nmutable struct WeightsSVM\n    C::AbstractFloat                # constraint\n    b::AbstractFloat                # threshold\n    gamma::AbstractFloat            # parameter used for polynomial, rbf, and sigmoid kernels\n    r::AbstractFloat                # parameter used for polynomial, and sigmoid kernels\n    d::AbstractFloat                # parameter used for polynomial kernel\n    tol_alpha::AbstractFloat        # tolerance for alpha\n    tol_error::AbstractFloat        # tolerance for error\n    alpha::Array{T} where T<:Number # alpha array\n    error::Array{T} where T<:Number # array for error cache\n    kernel::String                  # kernel function name\nend\n\n# ╔═╡ 3f6728b3-fb75-4783-ab6e-96ae6301f7cb\n# linear kernel\nfunction kernel_linear(X1::Array{T} where T<:Number, X2::Array{T} where T<:Number)::Array\n    @assert ndims(X1) == ndims(X2) == 2\n    @assert size(X1)[2] == size(X2)[2]\n    result = X1 * X2'\n    return result\nend\n\n# ╔═╡ e3b0cd51-75bc-41aa-96eb-251b376a183d\n# polynomial kernel\nfunction kernel_polynomial(X1::Array{T} where T<:Number, X2::Array{T} where T<:Number;\n        d::AbstractFloat=1.0, r::AbstractFloat=0.0, gamma::AbstractFloat=1.0)::Array\n    @assert ndims(X1) == ndims(X2) == 2\n    @assert size(X1)[2] == size(X2)[2]\n    result = (gamma .* (X1 * X2') .+ r) .^ d\n    return result\nend\n\n# ╔═╡ 4a0ee69a-6151-423b-9227-65fa4e9f2b5e\n# rbf kernel\nfunction kernel_rbf(X1::Array{T} where T<:Number, X2::Array{T} where T<:Number; gamma::AbstractFloat=1.0)::Array\n    @assert ndims(X1) == ndims(X2) == 2\n    @assert size(X1)[2] == size(X2)[2]\n    result = (sum(X1 .^ 2, dims=2) * ones(size(X2)[1])') .+ (ones(size(X1)[1]) * sum(X2 .^ 2, dims=2)') .- 2.0 .* (X1 * X2')\n    result .= broadcast(m->max(0.0, m), result) # ignore very small negative outputs, due to precision\n    result .= sqrt.(result)\n    result .= (-gamma) .* result\n    result .= exp.(result)\n    return result\nend\n\n# ╔═╡ 85939fbf-de18-46d8-9708-dec8a85f49dd\n# sigmoid kernel\nfunction kernel_sigmoid(X1::Array{T} where T<:Number, X2::Array{T} where T<:Number; gamma::AbstractFloat=1.0, r::AbstractFloat=0.0)::Array\n    @assert ndims(X1) == ndims(X2) == 2\n    @assert size(X1)[2] == size(X2)[2]\n    result = gamma .* (X1 * X2') .+ r\n    result .= tanh.(gamma)\n    return result\nend\n\n# ╔═╡ 99d0a23e-e06b-4c13-89a7-62aeebf7c559\n# because we call it cost function, we will use the original formula\nfunction cost(X_data::Array{T} where T<:Number, weights::WeightsSVM)::AbstractFloat\n    @assert ndims(X_data) == ndims(weights.alpha) + 1 == 2\n    @assert size(X_data)[1] == size(weights.alpha)[1]\n    result = nothing\n    if weights.kernel == \"linear\"\n        result = kernel_linear(X_data, X_data)\n    elseif weights.kernel == \"polynomial\"\n        result = kernel_polynomial(X_data, X_data, d=weights.d, r=weights.r, gamma=weights.gamma)\n    elseif weights.kernel == \"rbf\"\n        result = kernel_rbf(X_data, X_data, gamma=weights.gamma)\n    elseif weights.kernel == \"sigmoid\"\n        result = kernel_sigmoid(X_data, X_data, gamma=weights.gamma, r=weights.r)\n    else\n        throw(ArgumentError(\"Error: kernel function $weights.kernel is not recognized\"))\n    end\n    result = 0.5 * (weights.alpha' * result * weights.alpha) - sum(weights.alpha)\n    return result\nend\n\n# ╔═╡ 50e8d679-d4fc-4ed8-9868-b59cc4151d2c\ncost(X_data, Y_data, weight_test)\n\n# ╔═╡ ece26477-6e53-4536-a6a8-61947cb2815e\n# define learning each step function\n# update weights in place, and return num steps\nfunction learn_step!(X_data::Array{T} where T<:Number, Y_data::Array{T} where T<:Number,\n        weights::WeightsSVM, id1::Integer, id2::Integer)::Integer\n    @assert ndims(X_data) == ndims(Y_data) + 1 == 2\n    @assert size(X_data)[1] == size(Y_data)[1]\n    @assert size(X_data)[1] == size(weights.alpha)[1]\n    @assert size(weights.error) == size(weights.alpha)\n    @assert id1 >= 1\n    @assert id2 >= 1\n    # if choosing same alpha, skip\n    if id1 == id2\n        return 0\n    end\n    # prepare data\n    alpha1 = weights.alpha[id1]\n    alpha2 = weights.alpha[id2]\n    Y1 = Y_data[id1]\n    Y2 = Y_data[id2]\n    error1 = weights.error[id1]\n    error2 = weights.error[id2]\n    # compute L & H\n    L = nothing\n    H = nothing\n    if Y1 != Y2\n        L = max(0.0, alpha2 - alpha1)\n        H = min(weights.C, weights.C + alpha2 - alpha1)\n    else\n        L = max(0.0, alpha1 + alpha2 - weights.C)\n        H = min(weights.C, alpha1 + alpha2)\n    end\n    if L == H\n        return 0\n    end\n    # compute kernel results and 2nd derivative eta\n    k11 = nothing\n    k12 = nothing\n    k22 = nothing\n    n_features = size(X_data)[2]\n    X_id1 = reshape(X_data[id1, :], (1, n_features))\n    X_id2 = reshape(X_data[id2, :], (1, n_features))\n    if weights.kernel == \"linear\"\n        k11 = kernel_linear(X_id1, X_id1)[1]\n        k12 = kernel_linear(X_id1, X_id2)[1]\n        k22 = kernel_linear(X_id2, X_id2)[1]\n    elseif weights.kernel == \"polynomial\"\n        k11 = kernel_polynomial(X_id1, X_id1, d=weights.d, r=weights.r, gamma=weights.gamma)[1]\n        k12 = kernel_polynomial(X_id1, X_id2, d=weights.d, r=weights.r, gamma=weights.gamma)[1]\n        k22 = kernel_polynomial(X_id2, X_id2, d=weights.d, r=weights.r, gamma=weights.gamma)[1]\n    elseif weights.kernel == \"rbf\"\n        k11 = kernel_rbf(X_id1, X_id1, gamma=weights.gamma)[1]\n        k12 = kernel_rbf(X_id1, X_id2, gamma=weights.gamma)[1]\n        k22 = kernel_rbf(X_id2, X_id2, gamma=weights.gamma)[1]\n    elseif weights.kernel == \"sigmoid\"\n        k11 = kernel_sigmoid(X_id1, X_id1, gamma=weights.gamma, r=weights.r)[1]\n        k12 = kernel_sigmoid(X_id1, X_id2, gamma=weights.gamma, r=weights.r)[1]\n        k22 = kernel_sigmoid(X_id2, X_id2, gamma=weights.gamma, r=weights.r)[1]\n    else\n        throw(ArgumentError(\"Error: kernel function $weights.kernel is not recognized\"))\n    end\n    eta = 2 * k12 - k11 - k22\n    # compute new alpha2 (a2)\n    a2 = nothing\n    if eta < 0.0\n        a2 = alpha2 - Y2 * (error1 - error2) / eta\n        a2 = min(a2, H)\n        a2 = max(a2, L)\n    else\n        weights.alpha[id2] = L\n        Lobj = -cost(X_data, weights)\n        weights.alpha[id2] = H\n        Hobj = -cost(X_data, weights)\n        weights.alpha[id2] = alpha2\n        if Lobj > (Hobj + weights.tol_alpha)\n            a2 = L\n        elseif Lobj < (Hobj - weights.tol_alpha)\n            a2 = H\n        else\n            a2 = alpha2\n        end\n    end\n    # push to 0 or C\n    if a2 < 1e-8\n        a2 = 0.0\n    elseif a2 > (weights.C - 1e-8)\n        a2 = weights.C\n    end\n    # skip if cannot be optimized\n    if abs(a2 - alpha2) < weights.tol_alpha * (a2 + alpha2 + weights.tol_alpha)\n        return 0\n    end\n    # compute new alpha1 (a1)\n    a1 = alpha1 + (Y1 * Y2) * (alpha2 - a2)\n    if a1 < 0.0\n        a2 += (Y1 * Y2) * a1\n        a1 = 0.0\n    elseif a1 > weights.C\n        a2 += (Y1 * Y2) * (a1 - weights.C)\n        a1 = weights.C\n    end\n    # update threshold\n    b1 = error1 + Y1 * (a1 - alpha1) * k11 + Y2 * (a2 - alpha2) * k12 + weights.b\n    b2 = error2 + Y1 * (a1 - alpha1) * k12 + Y2 * (a2 - alpha2) * k22 + weights.b\n    b_new = nothing\n    if 0 < a1 < weights.C\n        b_new = b1\n    elseif 0 < a2 < weights.C\n        b_new = b2\n    else\n        b_new = (b1 + b2) * 0.5\n    end\n    # update error cache\n    non_optimized_ids = [i for i in 1:size(X_data)[1] if (i != id1 && i != id2 && (0 < weights.alpha[i] < weights.C))]\n    kerr1 = nothing\n    kerr2 = nothing\n    if weights.kernel == \"linear\"\n        kerr1 = vec(kernel_linear(X_id1, X_data[non_optimized_ids, :]))\n        kerr2 = vec(kernel_linear(X_id2, X_data[non_optimized_ids, :]))\n    elseif weights.kernel == \"polynomial\"\n        kerr1 = vec(kernel_polynomial(X_id1, X_data[non_optimized_ids, :], d=weights.d, r=weights.r, gamma=weights.gamma))\n        kerr2 = vec(kernel_polynomial(X_id2, X_data[non_optimized_ids, :], d=weights.d, r=weights.r, gamma=weights.gamma))\n    elseif weights.kernel == \"rbf\"\n        kerr1 = vec(kernel_rbf(X_id1, X_data[non_optimized_ids, :], gamma=weights.gamma))\n        kerr2 = vec(kernel_rbf(X_id2, X_data[non_optimized_ids, :], gamma=weights.gamma))\n    elseif weights.kernel == \"sigmoid\"\n        kerr1 = vec(kernel_sigmoid(X_id1, X_data[non_optimized_ids, :], gamma=weights.gamma, r=weights.r))\n        kerr2 = vec(kernel_sigmoid(X_id2, X_data[non_optimized_ids, :], gamma=weights.gamma, r=weights.r))\n    end\n    weights.error[non_optimized_ids] .= weights.error[non_optimized_ids] .+\n        ((Y1*(a1-alpha1)) .* kerr1) .+ ((Y2*(a2-alpha2)) .* kerr2) .+ (b_new - weights.b)\n    weights.error[id1] = 0.0\n    weights.error[id2] = 0.0\n    # update alpha and b\n    weights.b = b_new\n    weights.alpha[id1] = a1\n    weights.alpha[id2] = a2\n    return 1\nend\n\n# ╔═╡ 59c861e3-8c4d-450d-b727-c59cdf17a84f\n# now define the learning function\nfunction learn!(X_data::Array{T} where T<:Number, Y_data::Array{T} where T<:Number,\n        weights::WeightsSVM, id::Integer; verbose::Bool=false)::Integer\n    @assert ndims(X_data) == ndims(Y_data) + 1 == 2\n    @assert size(X_data)[1] == size(Y_data)[1]\n    @assert size(X_data)[1] == size(weights.alpha)[1]\n    @assert size(weights.error) == size(weights.alpha)\n    @assert id >= 1\n    Y = Y_data[id]\n    alpha = weights.alpha[id]\n    error = weights.error[id]\n    r = error * Y\n    if ((r < -weights.tol_error) && (alpha < weights.C)) || ((r > weights.tol_error) && (alpha > 0))\n        alpha_target = [i for (i, m) in enumerate(weights.alpha) if (0.0 < m < weights.C)]\n        # try argmax E1 - E2\n        new_id = -1\n        tmax = 0\n        if verbose\n            println(\"Trying argmax(abs(E1 - E2))\")\n        end\n        for i in alpha_target\n            tmp = abs(error - weights.error[i])\n            if(tmp > tmax)\n                tmax = tmp\n                new_id = i\n            end\n        end\n        if new_id >= 1\n            step = learn_step!(X_data, Y_data, weights, id, new_id)\n            if step > 0\n                return step\n            end\n        end\n        # loop non-bound alphas, randomly\n        if verbose\n            println(\"Trying random non-bound alphas\")\n        end\n        for new_id in alpha_target[Random.randperm(length(alpha_target))]\n            step = learn_step!(X_data, Y_data, weights, id, new_id)\n            if step > 0\n                return step\n            end\n        end\n        # else loop all alphas, randomly\n        if verbose\n            println(\"Trying random remaining alphas\")\n        end\n        for new_id in Random.randperm(length(weights.alpha))\n            if new_id in alpha_target\n                continue # skip the alpha ids that already looked at\n            end\n            step = learn_step!(X_data, Y_data, weights, id, new_id)\n            if step > 0\n                return step\n            end\n        end\n    end\n    return 0\nend\n\n# ╔═╡ 882b95f5-6261-42d4-91b2-16a7ce9c1aa4\n# implement predict functions\nfunction predict_proba(X_predict::Array{T} where T<:Number, X_data::Array{T} where T<:Number,\n        Y_data::Array{T} where T<:Number, weights::WeightsSVM)::Array\n    @assert ndims(X_predict) == ndims(X_data) == ndims(Y_data) + 1 == 2\n    @assert size(X_predict)[2] == size(X_data)[2]\n    result = nothing\n    if weights.kernel == \"linear\"\n        result = kernel_linear(X_data, X_predict)\n    elseif weights.kernel == \"polynomial\"\n        result = kernel_polynomial(X_data, X_predict, d=weights.d, r=weights.r, gamma=weights.gamma)\n    elseif weights.kernel == \"rbf\"\n        result = kernel_rbf(X_data, X_predict, gamma=weights.gamma)\n    elseif weights.kernel == \"sigmoid\"\n        result = kernel_sigmoid(X_data, X_predict, gamma=weights.gamma, r=weights.r)\n    else\n        throw(ArgumentError(\"Error: kernel function $weights.kernel is not recognized\"))\n    end\n    prediction = vec((weights.alpha .* Y_data)' * result)\n    return prediction\nend\n\n# ╔═╡ dde248cd-6fac-4c59-877d-58e5b8f06685\nfunction predict(X_predict::Array{T} where T<:Number, X_data::Array{T} where T<:Number,\n        Y_data::Array{T} where T<:Number, weights::WeightsSVM)::Array\n    @assert ndims(X_predict) == ndims(X_data) == ndims(Y_data) + 1 == 2\n    @assert size(X_predict)[2] == size(X_data)[2]\n    result = nothing\n    if weights.kernel == \"linear\"\n        result = kernel_linear(X_data, X_predict)\n    elseif weights.kernel == \"polynomial\"\n        result = kernel_polynomial(X_data, X_predict, d=weights.d, r=weights.r, gamma=weights.gamma)\n    elseif weights.kernel == \"rbf\"\n        result = kernel_rbf(X_data, X_predict, gamma=weights.gamma)\n    elseif weights.kernel == \"sigmoid\"\n        result = kernel_sigmoid(X_data, X_predict, gamma=weights.gamma, r=weights.r)\n    else\n        throw(ArgumentError(\"Error: kernel function $weights.kernel is not recognized\"))\n    end\n    prediction = vec((weights.alpha .* Y_data)' * result)\n    prediction .= map(m -> m >= 0 ? 1.0 : -1.0, prediction)\n    return prediction\nend\n\n# ╔═╡ aafac217-757c-442a-88b1-17e8895f703a\n# training function for linear SVM\n# assume Y_data is in {-1, 1}\n# this function is similar to the training function for Logistic Regression (Both are gradient descent)\nfunction train_linear(X_data::Array{T} where T<:Number, Y_data::Array{T} where T<:Number, C::AbstractFloat;\n        learning_rate::AbstractFloat=0.1, max_iter::Integer=1000, n_iter_no_change::Integer=5, tol::AbstractFloat=0.001,\n        verbose::Bool=false, shuffle::Bool=true, early_stop::Bool=true)::WeightsLinearSVM\n    @assert ndims(X_data) == ndims(Y_data) + 1 == 2\n    @assert size(X_data)[1] == size(Y_data)[1]\n    @assert max_iter >= 0\n    @assert n_iter_no_change >= 0\n    @assert tol >= 0\n    X_data = Float64.(X_data)\n    Y_data = Float64.(Y_data)\n    if shuffle\n        JuTools.shuffle_data!(X_data, Y_data)\n    end\n    # is it better to use zero weights than normal weights ?\n    weights = WeightsLinearSVM(C, Random.randn(size(X_data)[2]), Random.randn())\n    best_cost = nothing\n    n_cost_no_change = n_iter_no_change\n    for i in 1:max_iter\n        if n_cost_no_change <= 0 && early_stop\n            break\n        end\n        learn!(X_data, Y_data, weights, learning_rate)\n        new_cost = cost(X_data, Y_data, weights)\n        if verbose\n            acc = JuTools.compute_accuracy(predict(X_data, weights), Y_data)\n            println(\"Iter: $i\")\n            println(\"Cost = $new_cost\")\n            println(\"Accuracy = $acc\")\n            println()\n        end\n        if early_stop\n            if best_cost === nothing || isnan(best_cost)\n                best_cost = new_cost\n            else\n                if new_cost > best_cost - tol\n                    n_cost_no_change -= 1\n                else\n                    best_cost = min(new_cost, best_cost)\n                    n_cost_no_change = n_iter_no_change\n                end\n            end\n        end\n    end\n    return weights\nend\n\n# ╔═╡ ec256a57-ea44-4f73-af5b-f5e09ba2fec1\nweights = train_linear(X_train, Y_train, 1.0, learning_rate=0.005, max_iter=20, tol=0.001, verbose=true)\n\n# ╔═╡ fb710b22-79b0-477c-b2a6-f85fe8b4271a\nJuTools.compute_accuracy(predict(X_test, weights), Y_test)\n\n# ╔═╡ 47846484-1824-41b3-b26d-e4e3953fd079\n# finally implement the training function\nfunction train(X_data::Array{T} where T<:Number, Y_data::Array{T} where T<:Number, C::AbstractFloat;\n        tol_alpha::AbstractFloat=0.001, tol_error::AbstractFloat=0.001, kernel::String=\"rbf\", gamma::String=\"scale\",\n        degree::AbstractFloat=1.0, coef::AbstractFloat=0.0, verbose::Bool=false)::WeightsSVM\n    @assert ndims(X_data) == ndims(Y_data) + 1 == 2\n    @assert size(X_data)[1] == size(Y_data)[1]\n    X_data = Float64.(X_data)\n    Y_data = Float64.(Y_data)\n    # gamma is computed the same way sklearn does\n    gamma_num = nothing\n    if gamma == \"scale\"\n        gamma_num = 1.0 / (size(X_data)[2] * Statistics.var(X_data))\n    elseif gamma == \"auto\"\n        gamma_num = 1.0 / size(X_data)[2]\n    else\n        throw(ArgumentError(\"Error: gamma $gamma is not recognized, possible values are 'scale' and 'auto'\"))\n    end\n    weights = WeightsSVM(C, 0.0, gamma_num, coef, degree, tol_alpha, tol_error, Float64.(zeros(size(X_data)[1])), -copy(Y_data), kernel)\n    num_changed = 0\n    examine_all = true\n    total_steps = 0\n    while (num_changed > 0) || examine_all\n        num_changed = 0\n        if examine_all\n            if verbose\n                println(\"Scanning all training data\")\n            end\n            for i in 1:size(X_data)[1]\n                step = learn!(X_data, Y_data, weights, i, verbose=verbose)\n                num_changed += step\n                if step > 0 && verbose\n                    obj = -cost(X_data, weights)\n                    println(\"1 step further, objective = $obj\")\n                end\n            end\n        else\n            if verbose\n                println(\"Scanning data whose alpha is not at limit\")\n            end\n            alpha_target = [i for (i, m) in enumerate(weights.alpha) if (m != 0.0 && m != weights.C)]\n            for i in alpha_target\n                step = learn!(X_data, Y_data, weights, i, verbose=verbose)\n                num_changed += step\n                if step > 0 && verbose\n                    obj = -cost(X_data, weights)\n                    println(\"1 step further, objective = $obj\")\n                end\n            end\n        end\n        if examine_all\n            examine_all = false\n        elseif num_changed <= 0\n            examine_all = true\n        end\n        total_steps += num_changed\n    end\n    if verbose\n        println(\"Training Complete\\nTotal steps: $total_steps\")\n    end\n    return weights\nend\n\n# ╔═╡ fdd56685-18d1-47b5-9b9c-27090422f250\nweights_svm = train(X_train, Y_train, 10.0, kernel=\"rbf\", verbose=false, gamma=\"auto\", coef=0.0, degree=2.0)\n\n# ╔═╡ 1b11d952-a35f-4778-8a7f-779eb72f0436\nJuTools.compute_accuracy(predict(X_test, X_train, Y_train, weights_svm), Y_test)\n\n# ╔═╡ Cell order:\n# ╟─6a41e9d0-c58c-11eb-078e-c36bf22a38d2\n# ╟─9cfc2328-0e4f-4a86-944c-31c0c133fe9a\n# ╟─30975066-eb17-4682-bda1-fd77f9d44734\n# ╠═9088c5d0-f07c-404f-8e08-2c8585f86a2f\n# ╠═fc9d6f80-70c1-4518-b9db-29c6e3e2d280\n# ╠═6a0019bf-ab70-4095-ac52-7606e401d9a5\n# ╠═b8447232-6b1d-4b3a-8d11-a9a2da1cf31b\n# ╟─e4380307-4abe-4a20-9127-e608d1a5fa6e\n# ╠═6841f5fe-45ad-4f71-84d5-368d196a40ab\n# ╠═a093820c-20a0-4af1-98b3-ea92ad37bc77\n# ╠═8c3fa961-d88d-4e28-98e9-18b8804c568e\n# ╠═6341ae48-9cda-4019-bfe6-443caf8788aa\n# ╠═500703d2-e315-44c7-8d6c-c36f40b815df\n# ╠═7531e45c-95fd-4664-8c37-3364aae7020b\n# ╠═747fabf5-fd7b-40cc-b5da-b15f6925cff0\n# ╠═9504574b-2281-4f8a-83d5-3eea38acec53\n# ╠═c496efb2-5a50-4131-bd65-e9025a3273a4\n# ╠═46e9b187-d445-4efe-b4f2-ad824e5ec832\n# ╠═50e8d679-d4fc-4ed8-9868-b59cc4151d2c\n# ╠═8adbc614-9440-42d3-9672-f3b816e114a4\n# ╠═633040d0-651b-427f-a5a8-83124bbea43b\n# ╠═ea07e163-d2a0-4447-9239-64d1aee8b3a0\n# ╠═aafac217-757c-442a-88b1-17e8895f703a\n# ╠═ec256a57-ea44-4f73-af5b-f5e09ba2fec1\n# ╠═fb710b22-79b0-477c-b2a6-f85fe8b4271a\n# ╟─77bd6c88-335f-46a9-a46b-3d3596d54bf9\n# ╠═111304b2-bfbb-4875-838a-93c153d452be\n# ╠═3f6728b3-fb75-4783-ab6e-96ae6301f7cb\n# ╠═e3b0cd51-75bc-41aa-96eb-251b376a183d\n# ╠═4a0ee69a-6151-423b-9227-65fa4e9f2b5e\n# ╠═85939fbf-de18-46d8-9708-dec8a85f49dd\n# ╠═99d0a23e-e06b-4c13-89a7-62aeebf7c559\n# ╠═ece26477-6e53-4536-a6a8-61947cb2815e\n# ╠═59c861e3-8c4d-450d-b727-c59cdf17a84f\n# ╠═882b95f5-6261-42d4-91b2-16a7ce9c1aa4\n# ╠═dde248cd-6fac-4c59-877d-58e5b8f06685\n# ╠═47846484-1824-41b3-b26d-e4e3953fd079\n# ╠═fdd56685-18d1-47b5-9b9c-27090422f250\n# ╠═1b11d952-a35f-4778-8a7f-779eb72f0436\n", "meta": {"hexsha": "0669d07b9e1a91d1ee605352d112359640850b00", "size": 27771, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Support_Vector_Machines/notebook.jl", "max_stars_repo_name": "teamclouday/JuliaLearn", "max_stars_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Support_Vector_Machines/notebook.jl", "max_issues_repo_name": "teamclouday/JuliaLearn", "max_issues_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Support_Vector_Machines/notebook.jl", "max_forks_repo_name": "teamclouday/JuliaLearn", "max_forks_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.146978022, "max_line_length": 258, "alphanum_fraction": 0.6456015268, "num_tokens": 9572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.8791467770088162, "lm_q1q2_score": 0.7786000531710098}}
{"text": "########################\n###### Data Types ######\n########################\n\n# (1 + 2)::Int\n# 3\n\nfunction f(y::Int)\n    x::Int8 = 100\n    x + y\nend\n\nx = f(20) # 120\n\ntypeof(x) # Int8\n\n############################\n###### Abstract Types ######\n############################\n\n# abstract type «name» end\n# abstract type «name» <: «supertype» end\n\nabstract type Number end\nabstract type Real     <: Number end\nabstract type AbstractFloat <: Real end\nabstract type Integer  <: Real end\nabstract type Signed   <: Integer end\nabstract type Unsigned <: Integer end\n\n# The Number type is a direct child type of Any, and Real is its child. \n\n#############################\n###### Primitive Types ######\n#############################\n\n# primitive type «name» «bits» end\n# primitive type «name» <: «supertype» «bits» end\n\n# primitive type Float16 <: AbstractFloat 16 end\n# primitive type Float32 <: AbstractFloat 32 end\n# primitive type Float64 <: AbstractFloat 64 end\n\n# primitive type Bool <: Integer 8 end\n# primitive type Char <: AbstractChar 32 end\n\n# primitive type Int8    <: Signed   8 end\n# primitive type UInt8   <: Unsigned 8 end\n# primitive type Int16   <: Signed   16 end\n# primitive type UInt16  <: Unsigned 16 end\n# primitive type Int32   <: Signed   32 end\n# primitive type UInt32  <: Unsigned 32 end\n# primitive type Int64   <: Signed   64 end\n# primitive type UInt64  <: Unsigned 64 end\n# primitive type Int128  <: Signed   128 end\n# primitive type UInt128 <: Unsigned 128 end\n\n####################\n###### Struct ######\n####################\n\nstruct Foo \n    bar  # Any\n    baz::Int\n    qux::Float64\nend\n\nfoo = Foo(\"Hello\", 23, 1.5)\n\ntypeof(foo) # Foo\n\nfieldnames(Foo) # (:bar, :baz, :qux)\n\nfoo.bar # \"Hello\"\n\n# Composite objects declared with struct are immutable; they cannot be modified after construction.\n\nmutable struct Bar\n    baz\n    qux::Float64\nend\n\nbar = Bar(\"Hello\", 1.5)\n\nbar.qux = 2.0\n\nbar.baz = 1//2\n\n#########################\n###### Type Unions ######\n#########################\n\nIntOrString = Union{Int,AbstractString}\n\n1 :: IntOrString\n\n\"Hello\" :: IntOrString\n\n# 1.0 :: IntOrString - ERROR\n\n##############################\n###### Parametric Types ######\n##############################\n\n# An important and powerful feature of Julia's type system is that it is parametric: types can \n# take parameters, so that type declarations actually introduce a whole family of new types – one  \n# for each possible combination of parameter values. \n\nstruct Point{T}\n    x::T\n    y::T\nend\n\n# Point{Float64}\n# Point{AbstractString}\n\n# Point{Float64} <: Point \n# true\n\n# Point{AbstractString} <: Point\n# true\n\n# Point{Float64} <: Point{Real}\n# false\n\n# !!!! Even though Float64 <: Real we DO NOT have Point{Float64} <: Point{Real}. !!!!\n\n# Define a method that accepts all arguments of type Point{T} where T is a subtype of Real\nfunction norm(p::Point{<:Real})\n    sqrt(p.x^2 + p.y^2)\nend\n\np = Point{Float64}(1.0, 2.0)\n\ntypeof(p) # Point{Float64}(1.0, 2.0)\n\np1 = Point(1,2)\n\ntypeof(p1) # Point{Int64}(1, 2)\n\n# p3 = Point(1, 2.5) !!!! Error !!!!\n\n#######################################\n###### Parametric Abstract Types ######\n#######################################\n\nabstract type Pointy{T} end\n\nstruct Point{T} <: Pointy{T}\n    x::T\n    y::T\nend\n\n# Point{Float64} <: Pointy{Float64}\n# true\n\n# Point{Float64} <: Pointy{Real}\n# false\n\n# Point{Float64} <: Pointy{<:Real}\n# true\n\nstruct DiagPoint{T} <: Pointy{T}\n    x::T\nend\n\n# Now both Point{Float64} and DiagPoint{Float64} are implementations of the Pointy{Float64} abstraction, \n# and similarly for every other possible choice of type T. This allows programming to a common interface \n# shared by all Pointy objects, implemented for both Point and DiagPoint\n\nstruct Point{T<:Real} <: Pointy{T}\n    x::T\n    y::T\nend\n\n# Real-world example of how all this parametric type machinery can be useful\n\nstruct Rational{T<:Integer} <: Real\n    num::T\n    den::T\nend\n\n# It only makes sense to take ratios of integer values, so the parameter type T is restricted to \n# being a subtype of Integer, and a ratio of integers represents a value on the real number line, \n# so any Rational is an instance of the Real abstraction.\n\n#########################\n###### Tuple Types ######\n#########################\n\nstruct Tuple2{A,B}\n    a::A\n    b::B\nend\n\ntypeof((1,\"foo\",2.5)) # Tuple{Int64, String, Float64}\n\n# Vararg Tuple types\n\nmytupletype = Tuple{AbstractString,Vararg{Int}}\n# Tuple{AbstractString, Vararg{Int64, N} where N}\n\nisa((\"1\",), mytupletype)\n# true\n\n# Named Tuple Types\n\ntypeof((a=1,b=\"hello\"))\n# NamedTuple{(:a, :b), Tuple{Int64, String}}\n\n# The @NamedTuple macro provides a more convenient struct-like syntax for declaring NamedTuple types \n# via key::Type declarations, where an omitted ::Type corresponds to ::Any.\n\n@NamedTuple{a::Int, b::String}\n# NamedTuple{(:a, :b), Tuple{Int64, String}}\n\n@NamedTuple begin\n    a::Int\n    b::String\nend\n\n# NamedTuple{(:a, :b), Tuple{Int64, String}}\n\n############################\n###### UnionAll Types ######\n############################\n\nconst T1 = Array{Array{T,1} where T, 1}\n# Vector{Vector{T} where T} (alias for Array{Array{T, 1} where T, 1})\n\nconst T2 = Array{Array{T, 1}, 1} where T\n# Array{Vector{T}, 1} where T\n\n# Type T1 defines a 1-dimensional array of 1-dimensional arrays; each of the inner arrays consists \n# of objects of the same type, but this type may vary from one inner array to the next. On the other hand, \n# type T2 defines a 1-dimensional array of 1-dimensional arrays all of whose inner arrays must have the \n# same type. Note that T2 is an abstract type, e.g., Array{Array{Int,1},1} <: T2, whereas T1 is a \n# concrete type. As a consequence, T1 can be constructed with a zero-argument constructor a=T1() but \n# T2 cannot.\n\nVector{T} = Array{T, 1}\n\n# This is equivalent to const Vector = Array{T,1} where T. \n# Writing Vector{Float64} is equivalent to writing Array{Float64,1}\n\n####################################\n###### Type{T} type selectors ######\n####################################\n\n# For each type T, Type{T} is an abstract parametric type whose only instance is the object T.\n\nisa(Float64, Type{Float64})\n# true\n\nisa(Real, Type{Float64})\n# false\n\nisa(Real, Type{Real})\n# true\n\n# In other words, isa(A, Type{B}) is true if and only if A and B are the same object and that object is a type.\n\nstruct WrapType{T}\n    value::T\nend\n\nWrapType(Float64) # default constructor, note DataType\n# WrapType{DataType}(Float64)\n\nWrapType(::Type{T}) where T = WrapType{Type{T}}(T)\n# WrapType\n\nWrapType(Float64) # sharpened constructor, note more precise Type{Float64}\n# WrapType{Type{Float64}}(Float64)\n\n####################################\n###### Custom pretty-printing ######\n####################################\n\nstruct Polar{T<:Real} <: Number\n    r::T\n    Θ::T\nend\n\nPolar(r::Real,Θ::Real) = Polar(promote(r,Θ)...)\n# Polar\n", "meta": {"hexsha": "9302d29e857fbc48e0d7d61278753ee394482b39", "size": 6831, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "basics/data_types.jl", "max_stars_repo_name": "mauricioriva/learn-julia", "max_stars_repo_head_hexsha": "f4ff81ff412ba4f1243a8cee1123ebc8b3335f01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "basics/data_types.jl", "max_issues_repo_name": "mauricioriva/learn-julia", "max_issues_repo_head_hexsha": "f4ff81ff412ba4f1243a8cee1123ebc8b3335f01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "basics/data_types.jl", "max_forks_repo_name": "mauricioriva/learn-julia", "max_forks_repo_head_hexsha": "f4ff81ff412ba4f1243a8cee1123ebc8b3335f01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8013937282, "max_line_length": 111, "alphanum_fraction": 0.6126482213, "num_tokens": 1863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.8856314753275017, "lm_q1q2_score": 0.7786000403260006}}
{"text": "# calculate the volume of a sphere with radius r\n# Arguments:  r = radius of the sphere\n# Returns:    Volume\n\nfunction sphereVolume(r)\n  return 4/3 * pi * r^3\nend\n", "meta": {"hexsha": "748bd5390b6b701282435a1b7f37e208019cdcb4", "size": 163, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jl/sphereVolume.jl", "max_stars_repo_name": "thomasjdelaney/FluorescenceModel.jl", "max_stars_repo_head_hexsha": "9d2bd32e27dddf46c0a1d61d3013fa4b033a04fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jl/sphereVolume.jl", "max_issues_repo_name": "thomasjdelaney/FluorescenceModel.jl", "max_issues_repo_head_hexsha": "9d2bd32e27dddf46c0a1d61d3013fa4b033a04fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jl/sphereVolume.jl", "max_forks_repo_name": "thomasjdelaney/FluorescenceModel.jl", "max_forks_repo_head_hexsha": "9d2bd32e27dddf46c0a1d61d3013fa4b033a04fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.375, "max_line_length": 48, "alphanum_fraction": 0.6993865031, "num_tokens": 48, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9664104924150547, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7785714027137745}}
{"text": "\n# Computes the logarithmic mean: (aR-aL)/(LOG(aR)-LOG(aL)) = (aR-aL)/LOG(aR/aL)\n# Problem: if aL~= aR, then 0/0, but should tend to --> 0.5*(aR+aL)\n#\n# introduce xi=aR/aL and f=(aR-aL)/(aR+aL) = (xi-1)/(xi+1)\n# => xi=(1+f)/(1-f)\n# => Log(xi) = log(1+f)-log(1-f), and for small f (f^2<1.0E-02) :\n#\n#    Log(xi) ~=     (f - 1/2 f^2 + 1/3 f^3 - 1/4 f^4 + 1/5 f^5 - 1/6 f^6 + 1/7 f^7)\n#                  +(f + 1/2 f^2 + 1/3 f^3 + 1/4 f^4 + 1/5 f^5 + 1/6 f^6 + 1/7 f^7)\n#             = 2*f*(1           + 1/3 f^2           + 1/5 f^4           + 1/7 f^6)\n#  (aR-aL)/Log(xi) = (aR+aL)*f/(2*f*(1 + 1/3 f^2 + 1/5 f^4 + 1/7 f^6)) = (aR+aL)/(2 + 2/3 f^2 + 2/5 f^4 + 2/7 f^6)\n#  (aR-aL)/Log(xi) = 0.5*(aR+aL)*(105/ (105+35 f^2+ 21 f^4 + 15 f^6)\nfunction ln_mean(value1, value2)\n  epsilon_f2 = 1.0e-4\n  ratio = value2 / value1\n  # f2 = f^2\n  f2 = (ratio * (ratio - 2) + 1) / (ratio * (ratio + 2) + 1)\n  if f2 < epsilon_f2\n    return (value1 + value2) * 52.5 / (105 + f2 * (35 + f2 * (21 + f2 * 15)))\n  else\n    return (value2 - value1) / log(ratio)\n  end\nend\n", "meta": {"hexsha": "88ce6d3779c154d3c88439e24a8bf823c0852a94", "size": 1047, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/auxiliary/math.jl", "max_stars_repo_name": "jbreue16/Trixi.jl", "max_stars_repo_head_hexsha": "f6de21b834ceb9b9a5295cbf6b221ab297c279f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-13T11:10:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-13T11:10:41.000Z", "max_issues_repo_path": "src/auxiliary/math.jl", "max_issues_repo_name": "jbreue16/Trixi.jl", "max_issues_repo_head_hexsha": "f6de21b834ceb9b9a5295cbf6b221ab297c279f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-13T13:22:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-04T16:29:31.000Z", "max_forks_repo_path": "src/auxiliary/math.jl", "max_forks_repo_name": "jbreue16/Trixi.jl", "max_forks_repo_head_hexsha": "f6de21b834ceb9b9a5295cbf6b221ab297c279f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-23T09:45:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-23T09:46:17.000Z", "avg_line_length": 41.88, "max_line_length": 114, "alphanum_fraction": 0.4651384909, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104933824753, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7785713967282164}}
{"text": "\nusing OrdinaryDiffEq\nusing ForwardDiff\nusing DataFrames\nusing LinearAlgebra\nusing StatsPlots\n\n\nfunction sir_rates(u,p)\n  (S,I,R) = u\n  (β,c,γ) = p\n  N = S+I+R\n  infection = β*c*I/N*S\n  recovery = γ*I\n  [infection,recovery]\nend;\n\n\nsir_transitions = float.([[-1  1  0];\n                          [ 0 -1  1]])\n\n\nδt = 0.1\ntmax = 40.0\ntspan = (0.0,tmax)\nt = 0.0:δt:tmax;\n\n\nu0 = [990.0,10.0,0.0]; # S,I.R\nc0 = zeros(3,3) # covariance matrix\nuc0 = vcat(diagm(0=>u0), c0)\n\n\np = [0.05,10.0,0.25]; # β,c,γ\n\n\nrates = sir_rates\ntransitions = sir_transitions\nnrates, nstates = size(transitions);\n\n\nfunction ode(du, u, p, t)\n    du[1:3] = transitions' * rates(u, p)\nend;\n\n\nprob_ode = ODEProblem(ode, u0 ,tspan, p);\n\n\nsol_ode = solve(prob_ode, Tsit5(), saveat=t);\n\n\ndf_ode = DataFrame(sol_ode(t)')\ndf_ode[!,:t] = t;\n\n\n@df df_ode plot(:t,\n    [:x1 :x2 :x3],\n    label=[\"S\" \"I\" \"R\"],\n    xlabel=\"Time\",\n    ylabel=\"Number\",\n    c=[:blue :red :green])\n\n\nfunction lna(du, u, p, t)\n        mean_vec = diag(u)\n        covar_mx = u[nstates+1:nstates*2,:]\n        reaction_rates = rates(mean_vec, p)\n        reaction_rates_jac = ForwardDiff.jacobian(\n            y -> rates(y, p),\n            mean_vec)\n        A = transitions' * reaction_rates_jac\n        du[1:nstates, :] .= diagm(0 => transitions'*reaction_rates)\n        du[nstates + 1:end, :] .= A*covar_mx + covar_mx*A' + transitions' * diagm(0 => reaction_rates) * transitions\nend;\n\n\nprob_lna = ODEProblem(lna, uc0, tspan, p);\n\n\nsol_lna = solve(prob_lna, Tsit5(),saveat=t);\n\n\nmean_traj = Array{Float64,2}(undef, nstates, length(t))\ncovar_traj = Array{Array{Float64,2},1}(undef, length(t))\nfor j in 1:length(t)\n    mean_traj[:,j] = diag(sol_lna[j][1:nstates,1:nstates])\n    covar_traj[j] = sol_lna[j][nstates+1:end, 1:nstates]\nend;\n\n\nvar_traj = zeros(nstates, length(t))\nfor (idx, elt) in enumerate(covar_traj)\n    var_traj[:, idx] = diag(elt)\nend\nsd_traj = 1.96 .* sqrt.(var_traj);\n\n\nplot(t, mean_traj',\n     ribbon=sd_traj',\n     label = [\"S\" \"I\" \"R\"],\n     xlabel = \"Time\",\n     ylabel = \"Number\")\n\n", "meta": {"hexsha": "fff2e204c59e6b9dad69f5378e800e4ddca2041b", "size": 2036, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/lna/lna.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 126, "max_stars_repo_stars_event_min_datetime": "2020-04-29T08:41:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:42:53.000Z", "max_issues_repo_path": "script/lna/lna.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2020-04-29T11:44:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:45:15.000Z", "max_forks_repo_path": "script/lna/lna.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2020-04-29T08:01:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T16:55:08.000Z", "avg_line_length": 19.3904761905, "max_line_length": 116, "alphanum_fraction": 0.6006876228, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7785178426133016}}
{"text": "#=\n\n  Gaussian mixture model.\n\n  cf ~/blog/gaussian_mixture_model.blog\n     ~/psi/gaussian_mixture_model.psi\n     ~/webppl/gaussian_mixture_model.wppl\n\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n@model function gaussian_mixture_model()\n    x = [0.2,1.0,0.5,0.6]\n    n = length(x)\n\n    p ~ Beta(0.5, 1)\n    a ~ Uniform(-1, 1)\n    b ~ Uniform(-1, 1)\n\n    z = tzeros(n)\n    x = tzeros(n)\n    for i in 1:n\n        z[i] ~ Bernoulli(p)\n        if z[i] == 1\n            x[i] ~ Normal(a, 1.0)\n        else\n            x[i] ~ Normal(b, 1.0)\n        end\n    end\n\n    return a > b\n\nend\n\nmodel = gaussian_mixture_model()\n\nnum_chains = 4\n\n# chains = sample(model, Prior(), 10_000)\n# chains = sample(model, MH(), MCMCThreads(), 100_000, num_chains)\n# chains = sample(model, MH(), MCMCThreads(), 10_000, num_chains)\n# chains = sample(model, MH(), 10_000)\n\n# chains = sample(model, PG(15), MCMCThreads(), 1_000, num_chains)\n\nchains = sample(model, SMC(1000), MCMCThreads(), 10_000, num_chains)\n# chains = sample(model, SMC(1000), 10_000)\n# chains = sample(model, IS(), 10_000)\n#\n#chains = sample(model, Gibbs(HMC(0.1,5,:a,:b),PG(15,:p)), 10_000)\n# chains = sample(model, Gibbs(NUTS(1000,0.65,:a,:b),PG(15,:p)), 10_000)\n# chains = sample(model, Gibbs(HMC(0.1,5,:a,:b),SMC(1000,:p)), 10_000) # Nope\n\ndisplay(chains)\n# display(plot(chains))\n\n# show_var_dist_pct(chains,:a,20)\n# show_var_dist_pct(chains,:b,20)\n# show_var_dist_pct(chains,:p,20)\n\ngenq = generated_quantities(model, chains)\nshow_var_dist_pct(genq,20)\n", "meta": {"hexsha": "a53b6c425eae7de7465fae248eda2398d5510164", "size": 1518, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/gaussian_mixture_model.jl", "max_stars_repo_name": "Wikunia/hakank", "max_stars_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/turing/gaussian_mixture_model.jl", "max_issues_repo_name": "Wikunia/hakank", "max_issues_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/turing/gaussian_mixture_model.jl", "max_forks_repo_name": "Wikunia/hakank", "max_forks_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3538461538, "max_line_length": 77, "alphanum_fraction": 0.6337285903, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037782, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7785178412228463}}
{"text": "\"\"\"\n\ntrueG2_test() は，分割表のマス目のうちに 0 があるような場合でも，正確に lambda=0.0 にした場合の，正しい答えを返す。\n\n\"\"\"\n\nusing Distributions\nfunction trueG2_test(x; correct=false)\n    # セルに 0 があっても正しい答えを出す\n    # correct=true で，連続性の補正も行うことができる\n    ln(n) = sum(n .== 0 ? 0 : n .* log(n) for n in vcat(n...))\n    nrows, ncols = size(x)\n    n = sum(x) # 全サンプルサイズ\n    n1 = sum(x, dims=2) # 行和\n    n2 = sum(x, dims=1) # 列和\n    G2 = 2*(ln(x) - ln(n1) - ln(n2) + ln(n)) # G 統計量\n    correct && (G2 /= 1 + (n * sum(1 ./ n1) - 1) * (n * sum(1 ./ n2) - 1) / (6n * nrows * ncols)) # 連続性の補正\n    df = (nrows - 1) * (ncols - 1) # G の自由度\n    p = ccdf(Chisq(df), G2)\n    name = correct ? \"corrected G-sq.\" : \"G-sq.\"\n    println(\"$name = $G2,  df = $df,  p value = $p\")\nend\n\n\"\"\"\n使用法\n\njulia> z = [4 5 2 0\n            0 7 6 1\n            1 0 3 1]\n3×4 Matrix{Int64}:\n 4  5  2  0\n 0  7  6  1\n 1  0  3  1\n\njulia> trueG2_test(z)\nG-sq. = 15.364591286599591,  df = 6,  p value = 0.017602886503051453\n\nまた，ピアソンの χ2\n検定では 2×2 分割表の場合にしか連続性の補正は行えないが，G2 検定は分割表の大きさに関わらず，連続性の補正を行うことができる。\n\n上に示した関数 trueG2_test() で correct=true を指定すればよい。\n\njulia> trueG2_test(z, correct=true) # 連続性の補正\ncorrected G-sq. = 13.776490649307341,  df = 6,  p value = 0.032235015595581236\n\n\"\"\"\n", "meta": {"hexsha": "639c984ce56aebb6c6a9be6ecf6af12c1ce91b58", "size": 1194, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "trueG2_test.jl", "max_stars_repo_name": "r-de-r/stats", "max_stars_repo_head_hexsha": "69ae834ecb55f737106900a1f14674e55cc1f972", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trueG2_test.jl", "max_issues_repo_name": "r-de-r/stats", "max_issues_repo_head_hexsha": "69ae834ecb55f737106900a1f14674e55cc1f972", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trueG2_test.jl", "max_forks_repo_name": "r-de-r/stats", "max_forks_repo_head_hexsha": "69ae834ecb55f737106900a1f14674e55cc1f972", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4042553191, "max_line_length": 106, "alphanum_fraction": 0.5787269682, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.778517832050782}}
{"text": "# Define a \"model\" type, that just needs a predict function\r\ntype GenericModel\r\n\tpredict # Function that makes predictions\r\nend\r\n\r\ntype LinearModel\r\n\tpredict # Funcntion that makes predictions\r\n\tw # Weight vector\r\nend\r\n\r\ntype CompressModel\r\n\tcompress # Function that compresses\r\n\texpand # Function that de-compresses\r\n\tW # weight matrix\r\nend\r\n\r\n# Function to compute the mode of a vector\r\nfunction mode(x)\r\n\t# Returns mode of x\r\n\t# if there are multiple modes, returns the smallest\r\n\tx = sort(x[:]);\r\n\r\n\tcommonVal = [];\r\n\tcommonFreq = 0;\r\n\tx_prev = NaN;\r\n\tfreq = 0;\r\n\tfor i in 1:length(x)\r\n\t\tif(x[i] == x_prev)\r\n\t\t\tfreq += 1;\r\n\t\telse\r\n\t\t\tfreq = 1;\r\n\t\tend\r\n\t\tif(freq > commonFreq)\r\n\t\t\tcommonFreq = freq;\r\n\t\t\tcommonVal = x[i];\r\n\t\tend\r\n\t\tx_prev = x[i];\r\n\tend\r\n\treturn commonVal\r\nend\r\n\r\n# Return element-wise log, but set log(0)=0\r\nfunction log0(x)\r\n\ty = copy(x)\r\n\ty[y.==0] = 1\r\n\treturn log.(y)\r\nend\r\n\r\n\r\n# Return squared Euclidean distance all pairs of rows in X1 and X2\r\nfunction distancesSquared(X1,X2)\r\n\t(n,d) = size(X1)\r\n\t(t,d2) = size(X2)\r\n\tassert(d==d2)\r\n\treturn X1.^2*ones(d,t) + ones(n,d)*(X2').^2 - 2X1*X2'\r\nend\r\n\r\n\r\n# Subtract mean of each column and divide by standard deviation\r\n# (or call it with mu and sigma to use these specific mean/std)\r\nfunction standardizeCols(X;mu=[],sigma=[])\r\n\t(n,d) = size(X)\r\n\r\n\tif isempty(mu)\r\n\t\tmu_j = mean(X,1)\r\n\telse\r\n\t\tmu_j = mu\r\n\tend\r\n\r\n\tXstd = zeros(n,d)\r\n\tfor j in 1:d\r\n\t\tXstd[:,j] = X[:,j] - mu_j[j]\r\n\tend\r\n\r\n\tif isempty(sigma)\r\n\t\tsigma_j = std(Xstd,1)\r\n\telse\r\n\t\tsigma_j = sigma\r\n\tend\r\n\r\n\tfor j in 1:d\r\n\t\tXstd[:,j] /= sigma_j[j]\r\n\tend\r\n\r\n\tif isempty(mu) & isempty(sigma)\r\n\t\treturn (Xstd,mu_j,sigma_j)\r\n\telse\r\n\t\treturn Xstd\r\n\tend\r\nend\r\n\r\n\r\n### A function to compute the gradient numerically\r\nfunction numGrad(func,x)\r\n\tn = length(x);\r\n\tdelta = 2*sqrt(1e-12)*(1+norm(x));\r\n\tg = zeros(n);\r\n\te_i = zeros(n)\r\n\tfor i = 1:n\r\n\t\te_i[i] = 1;\r\n\t\t(fxp,) = func(x + delta*e_i)\r\n\t\t(fxm,) = func(x - delta*e_i)\r\n\t\tg[i] = (fxp - fxm)/2delta;\r\n\t\te_i[i] = 0\r\n\tend\r\n\treturn g\r\nend\r\n\r\n### Check if number is a real-finite number\r\nfunction isfinitereal(x)\r\n\treturn (imag(x) == 0) & (!isnan(x)) & (!isinf(x))\r\nend\r\n\r\nfunction dijkstra(D,s,t)\r\n\t# Finds shortest path from 's' to 't' with non-negative edge weights D\r\n  # - set the edge weight D[i,j] to Inf if there is no edge between nodes 'i' and 'j' in the graph\r\n\t# (not really a fast implementation)\r\n\r\n\tn = size(D,1)\r\n\r\n\tdistances = fill(Inf,n)\r\n\tdistances[s] = 0\r\n\r\n\tvisited = fill(false,n)\r\n\r\n\twhile true\r\n\r\n\t\t# Choose next node to visit\r\n\t\tminDist = Inf\r\n\t\ti = []\r\n\t\tfor j in 1:n\r\n\t\t\tif !visited[j] & (distances[j] < minDist)\r\n\t\t\t\ti = j\r\n\t\t\t\tminDist = distances[j]\r\n\t\t\tend\r\n\t\tend\r\n\r\n\t\tif isinf(minDist)\r\n\t\t\t# We have nowhere left to visit, there is no path\r\n\t\t\tbreak\r\n\t\tend\r\n\r\n\t\t# \"Visit\" the node: update neighbour distances\r\n\t\tfor j in 1:n\r\n\t\t\tif distances[i] + D[i,j] < distances[j]\r\n\t\t\t\tdistances[j] = distances[i] + D[i,j]\r\n\t\t\tend\r\n\t\tend\r\n\t\tvisited[i] = true\r\n\r\n\t\t# If we just visited the solution\r\n\t\tif i == t\r\n\t\t\tbreak\r\n\t\tend\r\n\tend\r\n\treturn distances[t]\r\nend\r\n", "meta": {"hexsha": "e632b76193205e833286ceccfd42381c1959c506", "size": 3051, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "a1sol/misc.jl", "max_stars_repo_name": "d4l3k/cs540", "max_stars_repo_head_hexsha": "049617af46048b5471877b9bdfb0bd8a65f3cf0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "a1sol/misc.jl", "max_issues_repo_name": "d4l3k/cs540", "max_issues_repo_head_hexsha": "049617af46048b5471877b9bdfb0bd8a65f3cf0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "a1sol/misc.jl", "max_forks_repo_name": "d4l3k/cs540", "max_forks_repo_head_hexsha": "049617af46048b5471877b9bdfb0bd8a65f3cf0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3101265823, "max_line_length": 99, "alphanum_fraction": 0.6119305146, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8774767922879693, "lm_q1q2_score": 0.7785014357640713}}
{"text": "function area(r)\n    return (r^2 * asin(sqrt(r^2 - 1)/r)/2) - sqrt(r^2 - 1) - (r^2 * asin(1/r)/2) + 1\nend\n\nfunction prob(k)\n    if k == 1\n        return area(k + 1/2)/k^2\n    else\n        return (area(k + 1/2) - area(k - 1/2))/k^2\n    end\nend\n\nfunction main(limit)\n    expectation = sum(k * prob(k) for k in 1:limit)\n    println(expectation)\nend\n\nmain(100000)\n", "meta": {"hexsha": "fceff85ab5dc5610d8b8070c484ac89743ffd335", "size": 360, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/problem_285.jl", "max_stars_repo_name": "HarrisonGreen/Project-Euler-Solutions", "max_stars_repo_head_hexsha": "e2599e406c8a1c997bf620e1c35045303b12091e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Julia/problem_285.jl", "max_issues_repo_name": "HarrisonGreen/Project-Euler-Solutions", "max_issues_repo_head_hexsha": "e2599e406c8a1c997bf620e1c35045303b12091e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/problem_285.jl", "max_forks_repo_name": "HarrisonGreen/Project-Euler-Solutions", "max_forks_repo_head_hexsha": "e2599e406c8a1c997bf620e1c35045303b12091e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9473684211, "max_line_length": 84, "alphanum_fraction": 0.55, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541659378681, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7784766069267972}}
{"text": "using Contour, Gadfly, DataFrames\n\nusing OneDimensional: goldenSectionSearch, fibSearch\n\nf(x, y) = x^4 + y^4 - 5 * (x * y - x^2 * y^2)\nfdx(x, y) = 4x^3 - 5y + 10 * x * y^2\nfdy(x, y) = 4y^3 - 5x + 10 * y * x^2\n▽(x, y) = [fdx(x, y), fdy(x, y)]\nL(x, y, λ) = [x, y] .- (λ .* ▽(x, y))\n\nfunction simpleGradientDescent(f, ▽, x0, y0, ɛ) # down gradient with exponentital slow step\n  callCnt, gradCallCnt, xs, ys = 1, 0, [x0], [y0]\n\n  λ = 0.05\n  fprev = f(x0, y0)\n  while true\n    xk, yk = xs[end], ys[end]\n    xnew, ynew = L(xk, yk, λ)\n    gradCallCnt += 1\n    if xnew < 0 || 1 < xnew || ynew < 0 || 1 < ynew\n      λ *= 0.75\n      continue\n    end\n    fnew = f(xnew, ynew)\n    callCnt += 1\n    if fnew > fprev\n      λ *= 0.75\n      continue\n    end\n    fprev = fnew\n    push!(xs, xnew)\n    push!(ys, ynew)\n    if norm([xs[end] - xs[end - 1], ys[end] - ys[end - 1]]) < ɛ\n      break\n    end\n  end\n  xs, ys, callCnt, gradCallCnt\nend\n\nfunction fastGradienDescent(f, ▽, x0, y0, ɛ) # fastest descent gradient\n  callCnt, gradCallCnt, xl, yl = 1, 0, [x0], [y0]\n\n  left, right = 0, 1\n  while true\n    x_left, y_left = xl[end], yl[end]\n    g = ▽(x_left, y_left)\n    gradCallCnt += 1\n    ax = [(left - x_left) / -g[1], (right - x_left) / -g[1]]\n    ay = [(left - y_left) / -g[2], (right - y_left) / -g[2]]\n    sort!(ax)\n    sort!(ay)\n    a = [max(ax[1], ay[1]), min(ax[2], ay[2])]\n    λ, cnt, _, _, _ = fibSearch(arg -> f(x_left - arg * g[1], y_left - arg * g[2]), a[1], a[2], ɛ)\n    callCnt += cnt\n    xnew, ynew = x_left - λ * g[1], y_left - λ * g[2]\n    push!(xl, xnew)\n    push!(yl, ynew)\n    if norm([xl[end] - xl[end - 1], yl[end] - yl[end - 1]]) < ɛ\n      break\n    end\n  end\n  xl, yl, callCnt, gradCallCnt\nend\n\nɛ = 0.0001\nx0, y0 = 0.2, 0.8\nsgx, sgy, cnt1, gcnt1 = simpleGradientDescent(f, ▽, x0, y0, ɛ)\nfgx, fgy, cnt2, gcnt2 = fastGradienDescent(f, ▽, x0, y0, ɛ)\n\n@printf(\"Обычный градиентный спуск: %d вычислений функции, %d вычислений градиента\\n\", cnt1, gcnt1)\n@printf(\"Наискорейший спуск: %d вычислений функции, %d вычислений градиента\\n\", cnt2, gcnt2)\n\nGadfly.set_default_plot_size(18cm, 18cm)\nplot(layer(x=[0:0.01:1], y=[0:0.01:1], z=f, Geom.contour(levels=15)),\n     layer(x=sgx, y=sgy, Theme(default_color=color(\"orange\")), Geom.point, Geom.line),\n     layer(x=fgx, y=fgy, Theme(default_color=color(\"red\")), Geom.point, Geom.line(preserve_order=true)),\n     Guide.xticks(ticks=[0:0.2:1.0]), Guide.yticks(ticks=[0:0.2:1.0]),\n     Guide.title(\"Линии уровня функции x^4 + y^4 - 5(xy - x^2 * y^2)\"))\n", "meta": {"hexsha": "12637bb4e25ddaa0ce6f74bd21482de29230d3c7", "size": 2494, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "optimization-course/grad.jl", "max_stars_repo_name": "ChShersh/university-courses", "max_stars_repo_head_hexsha": "b78ab71d9b62e31de34efa4a93ac6fbe684c4ac0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "optimization-course/grad.jl", "max_issues_repo_name": "ChShersh/university-courses", "max_issues_repo_head_hexsha": "b78ab71d9b62e31de34efa4a93ac6fbe684c4ac0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimization-course/grad.jl", "max_forks_repo_name": "ChShersh/university-courses", "max_forks_repo_head_hexsha": "b78ab71d9b62e31de34efa4a93ac6fbe684c4ac0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5696202532, "max_line_length": 104, "alphanum_fraction": 0.5677626303, "num_tokens": 1108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257062, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7784766008556764}}
{"text": "#==============================================================================\n\n          Solving the HJB with a state constraint using\n                the explicit method\n\n\n\n               Translated from matlab code on Ben Moll's website:\n                              http://www.princeton.edu/~moll/HACTproject.htm\n\n==============================================================================#\n\nusing LinearAlgebra, SparseArrays, Plots\n\nγ = 2 # parameter from CRRA utility\nr = 0.03 # the interest rate\nρ = 0.05 # the discount rate\n\nz1=.1\nz2 =.2\nz= [z1 z2]\n\nλ1 = 0.02\nλ2 = 0.03\n\nλ = [λ1 λ2]\n\nH = 500 # number of points in the grid space\namin=-0.02\namax=2\n\na = LinRange(amin,amax,H)\nda = (amax-amin)/(H-1)\n\naa = [a a]\nzz = ones(H,1)*z\n\nmaxit = 20000 # the maximum number of iterations we allow the finite differencing algorithm\ncrit = 10^(-6) # our critical value\n\ndVf=zeros(H,2)\ndVb = zeros(H,2)\nc= zeros(H,2)\n\n# Inital Guess\nv0=zeros(H,2)\nv0[:,1] = (z[1] .+ r.*a).^(1-γ)/(1-γ)/ρ\nv0[:,2] = (z[2] .+ r.*a).^(1-γ)/(1-γ)/ρ\nglobal v=v0\n\ndist=[]\n\n# The finite differeing loop\n\nfor n in 1:maxit\n    global V=v\n    # Forward differencing\n    dVf[1:H-1,:]=(V[2:H,:]-V[1:H-1,:])/da\n    dVf[H,:] = zeros(1,2) # will never be used\n    # Backward differencing\n    dVb[2:H,:]=(V[2:H,:]-V[1:H-1,:])/da\n    dVb[1,:]= (z .+r.*amin).^(-γ)\n\n    # Find consumption and savings with the forward difference\n    cf = dVf.^(-1/γ)\n    sf = zz +r.*aa -cf\n\n    # Find consumption and savings with the backward difference\n    cb= dVb.^(-1/γ)\n    sb = zz +r.*aa -cb\n\n    # Find consumption and savings at steady state\n    c0 = zz + r.*aa\n    dV0 = c0.^(-γ)\n\n    # Now implement the upwind scheme in order to select the best differencing method\n    If = sf .> 0\n    Ib = sb .< 0\n    I0 = (1 .- If - Ib)\n\n    # Make sure the backward difference is using at the grid max\n    Ib[H,:] = ones(1,2)\n    If[H,:] = zeros(1,2)\n\n    # State constraint at amin is automatically implemented\n\n    global dV_Upwind = dVf.*If + dVb.*Ib + dV0.*I0\n\n    global c = dV_Upwind.^(-1/γ)\n    global V_switch = [V[:,2] V[:,1]]\n\n    V_change = c.^(1-γ)/(1-γ) + dV_Upwind.*(zz + r.*aa -c) + ones(H,1)*λ.*(V_switch-V)-ρ.*V\n\n    Δ = .9*da/(findmax(z2 .+r.*a)[1])\n    global v = v  + Δ*V_change\n\n    push!(dist, findmax(abs.(V_change))[1])\n\n    if dist[n] < crit\n        println(\"Value Function converged, Iteration=\")\n        println(n)\n        break\n    end\nend\n\n# Graphs\nV_err = c.^(1-γ)/(1-γ) + dV_Upwind.*(zz +r.*aa -c) + ones(H,1)*λ.*(V_switch-V)-ρ.*V\nadot = zz + r.*aa -c\n\nplot(dist[:], xlabel=\"Iteration\", ylabel=\"\\$\\\\lvert V^{n+1}-V^{n}\\\\rvert\\$\")\n\nplot(a,V_err, xlabel=\"k\",ylabel=\"Error in HJB Equation\", xlims=(amin,amax), legend=false)\n\nplot(a,V, xlabel=\"a\", ylabel=\"\\$V_{i}(a)\\$\", xlims=(amin,amax),legend=false)\n\nplot(a,c,xlabel=\"a\", ylabel=\"\\$c_{i}(a)\\$\", xlims=(amin,amax), legend=false)\n\nplot(a, adot, xlabel=\"a\", ylabel=\"\\$s_{i}(a)\\$\", xlims=(amin,amax))\n\n# Approximation at the borrowing constraint\nu1=(z1+r*amin)^(-γ)\nu2 = c[1,2]^(-γ)\nu11 = -γ*(z1+r*amin)^(-γ-1)\nν = sqrt(-2*((ρ-r)*u1 + λ1*(u1-u2))/u11)\ns_approx = -ν*(a.-amin).^(1/2)\n\nplot(a, adot[:,1], xlabel=\"a\", ylabel=\"\\$s_{i}(a)\\$\", xlims=(amin,amax), label=\"\\$s_{1}(a)\\$\")\nplot!(a, adot[:,2], label=\"\\$s_{2}(a)\\$\")\nplot!(a, zeros(H,1), line=:dash, label=\"\", color=:black)\nplot!(a, s_approx, label=\"Approximatation\")\n", "meta": {"hexsha": "4cc2e8499c273f99c79f25204b6d1ab446d76f35", "size": 3341, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Moll_Code/Section01-Hugget-Achdou_etal_2017/HJB_stateconstraint_explicit/HJB_state_constraint_explicit.jl", "max_stars_repo_name": "chandlerlester/Radio_Free_Julia", "max_stars_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-02-26T11:52:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T12:41:38.000Z", "max_issues_repo_path": "Moll_Code/Section01-Hugget-Achdou_etal_2017/HJB_stateconstraint_explicit/HJB_state_constraint_explicit.jl", "max_issues_repo_name": "chandlerlester/Radio_Free_Julia", "max_issues_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Moll_Code/Section01-Hugget-Achdou_etal_2017/HJB_stateconstraint_explicit/HJB_state_constraint_explicit.jl", "max_forks_repo_name": "chandlerlester/Radio_Free_Julia", "max_forks_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-11T08:09:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-30T18:54:12.000Z", "avg_line_length": 25.5038167939, "max_line_length": 94, "alphanum_fraction": 0.5489374439, "num_tokens": 1199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7784765981889663}}
{"text": "#=\n\n@authors : Spencer Lyon <spencer.lyon@nyu.edu>, John Stachurski\n\n=#\n\nusing QuantEcon\nusing Distributions\n\n\"\"\"\nThe Lucas asset pricing model --- parameters and grid data\n\"\"\"\nstruct LucasTree{TF<:AbstractFloat}\n    γ::TF                 # coefficient of risk aversion\n    β::TF                 # Discount factor in (0, 1)\n    α::TF                 # Correlation coefficient in the shock process\n    σ::TF                 # Volatility of shock process\n    ϕ::Distribution       # Distribution for shock process\n    grid::Vector{TF}      # Grid of points on which to evaluate prices\n    shocks::Vector{TF}    # Draws of the shock\n    h::Vector{TF}         # The h function represented as a vector\nend\n\n\"\"\"\nConstructor for the Lucas asset pricing model\n\"\"\"\nfunction LucasTree(;γ::AbstractFloat=2.0,\n                β::AbstractFloat=0.95,\n                α::AbstractFloat=0.9,\n                σ::AbstractFloat=0.1,\n                grid_size::Integer=100)\n\n    ϕ = LogNormal(0.0, σ)\n    shocks = rand(ϕ, 500)\n\n    # == build a grid with mass around stationary distribution == #\n    ssd = σ / sqrt(1 - α^2)\n    grid_min, grid_max = exp(-4 * ssd), exp(4 * ssd)\n    grid = collect(linspace(grid_min, grid_max, grid_size))\n\n    # == set h(y) = β * int u'(G(y,z)) G(y,z) ϕ(dz) == #\n    h = similar(grid)\n    for (i, y) in enumerate(grid)\n        h[i] = β * mean((y^α .* shocks).^(1 - γ))\n    end\n\n    return LucasTree(γ,\n                     β,\n                     α,\n                     σ,\n                     ϕ,\n                     grid,\n                     shocks,\n                     h)\nend\n\n\n\"\"\"\nThe approximate Lucas operator, which computes and returns updated function\nTf on the grid points.\n\"\"\"\nfunction lucas_operator(lt::LucasTree, f::Vector)\n\n    # == unpack names == #\n    grid, α, β, h = lt.grid, lt.α, lt.β, lt.h\n    z = lt.shocks\n\n    Af = LinInterp(grid, f)\n\n    Tf = [h[i] + β * mean(Af.(grid[i]^α.*z)) for i in 1:length(grid)]\n    return Tf\nend\n\n\n\"\"\"\nCompute the equilibrium price function associated with Lucas tree `lt`\n\"\"\"\nfunction solve_lucas_model(lt::LucasTree;\n                           tol::AbstractFloat=1e-6, \n                           max_iter::Integer=500)\n    \n    # == simplify notation == #\n    grid, γ = lt.grid, lt.γ\n    \n    i = 0\n    f = zeros(grid)  # Initial guess of f\n    error = tol + 1\n    \n    while (error > tol) && (i < max_iter)\n        f_new = lucas_operator(lt, f)\n        error = maximum(abs, f_new - f)\n        f = f_new\n        i += 1\n    end\n    \n    # p(y) = f(y) * y ^ γ\n    price = f .* grid.^γ\n    \n    return price\nend\n", "meta": {"hexsha": "19302cd650ca39d4777a0445cf2541c2b3a6cc30", "size": 2578, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lucas_model/lucastree.jl", "max_stars_repo_name": "chenwang/QuantEcon.lectures.code", "max_stars_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2017-05-09T10:45:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:33:27.000Z", "max_issues_repo_path": "lucas_model/lucastree.jl", "max_issues_repo_name": "chenwang/QuantEcon.lectures.code", "max_issues_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2017-06-30T01:52:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-01T20:09:47.000Z", "max_forks_repo_path": "lucas_model/lucastree.jl", "max_forks_repo_name": "QuantEcon/QuantEcon.lectures.code", "max_forks_repo_head_hexsha": "d61ac7bc54529dd5c77470c17539eb2418b047c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 117, "max_forks_repo_forks_event_min_datetime": "2017-04-25T16:09:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T02:30:29.000Z", "avg_line_length": 25.5247524752, "max_line_length": 75, "alphanum_fraction": 0.5310318076, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7784378746776327}}
{"text": "import Base.intersect\n\ncomplex_empty = Set{Complex{Float64}}()\nidentical_warn = \"Intersection of identical clines returns the empty set\"\n\n\"\"\"\n    intersect(C::Cline,D::Cline)\n    C ∩ D \n\nFind the points common to the clines `C` and `D` as a set of complex numbers.\n\nNote that if `C==D` a warning is issued and the emptyset is returned.\n\"\"\"\nfunction intersect(C::Circle, D::Circle)::Set{Complex{Float64}}\n    if C == D\n        @warn identical_warn\n        return complex_empty\n    end\n\n    z = center(C)\n    r = radius(C)\n\n    w = center(D)\n    s = radius(D)\n\n    d = abs(z - w)\n\n    if d > r + s || d + s < r || d + r < s\n        return Set{Complex{Float64}}()\n    end\n\n    θ = acos((r^2 + d^2 - s^2) / (2 * r * d))\n    u = (w - z) / abs(w - z)\n    uu = u * exp(θ * im)\n    a = z + uu * r\n    uu = u * exp(-θ * im)\n    b = z + uu * r\n    return Set([a, b])\nend\n\n\nfunction intersect(L::Line, M::Line)::Set{Complex{Float64}}\n    if L == M\n        @warn identical_warn\n        return complex_empty\n    end\n\n    # check if parallel\n    m1 = slope(L)\n    m2 = slope(M)\n    if (isinf(m1) && isinf(m2)) || (abs(m1 - m2) < get_tolerance())\n        return complex_empty\n    end\n\n    a = L.a\n    b = L.b\n\n    ax, ay = reim(a)\n    bx, by = reim(b)\n\n    aa = M.a\n    bb = M.b\n\n    aax, aay = reim(aa)\n    bbx, bby = reim(bb)\n\n\n    MAT = zeros(2, 2)\n    MAT[1, 1] = ax - bx\n    MAT[1, 2] = bbx - aax\n    MAT[2, 1] = ay - by\n    MAT[2, 2] = bby - aay\n\n    RHS = [bbx - bx, bby - by]\n    st = MAT \\ RHS\n\n    s = st[1]\n    z = s * L.a + (1 - s) * L.b\n    return Set(z)\nend\n\n\n\nfunction intersect(C::Cline, D::Cline)::Set{Complex{Float64}}\n    if C == D\n        @warn identical_warn\n        return complex_empty\n    end\n\n    F = LFT(C)  # map C to x-axis\n    G = inv(F)\n    DD = F(D)  # apply that to D and find where DD crosses the x-axis \n\n    # if the images of D is a circle\n    if isa(DD, Circle)\n        x, y = reim(center(DD))\n        r = radius(DD) + get_tolerance()\n\n        if r < abs(y)\n            return complex_empty = Set{Complex{Float64}}()\n        end\n\n        δ = sqrt(r^2 - y^2)\n        a = G(x + δ)\n        b = G(x - δ)\n        if abs(a - b) < get_tolerance()  # if the points are too close, we say they're the same\n            ab = (a + b) / 2\n            return Set{Complex{Float64}}(ab)\n        else\n            return Set{Complex{Float64}}([a, b])\n        end\n    end\n\n    # otherwise, DD, the image of D, is a line\n\n    X = Line(0, 1)  # x-axis \n    S = X ∩ DD\n    return G.(S)\n\n    # x, y = reim(DD.a)\n    # xx, yy = reim(DD.b)\n\n    # if abs(y - yy) < get_tolerance()  # DD is a horizontal line \n    #     return complex_empty()\n    # end\n\n    # if abs(x - xx) < get_tolerance()  # DD is a vertical line \n    #     z = G((x + xx) / 2)\n    #     return Set{Complex{Float64}}(z)\n    # end\n\n    # slope = (y - yy) / (x - xx)\n    # δ = y / slope\n    # z = G(x - δ)\n    # return Set{Complex{Float64}}(z)\nend\n", "meta": {"hexsha": "0d97671751c696cd0f1a883c411e09c957a2009a", "size": 2911, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/intersection.jl", "max_stars_repo_name": "scheinerman/Clines.jl", "max_stars_repo_head_hexsha": "8d32bef6d6cd3485bf418a4c1969a8bb0c566d3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/intersection.jl", "max_issues_repo_name": "scheinerman/Clines.jl", "max_issues_repo_head_hexsha": "8d32bef6d6cd3485bf418a4c1969a8bb0c566d3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/intersection.jl", "max_forks_repo_name": "scheinerman/Clines.jl", "max_forks_repo_head_hexsha": "8d32bef6d6cd3485bf418a4c1969a8bb0c566d3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2481751825, "max_line_length": 95, "alphanum_fraction": 0.5060116798, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7784378733825772}}
{"text": "test = (5764801, 17807724)\npuzzle = (8987316, 14681524)\nmodulus = 20201227\nseed = 7\n\nmods = let mods = Vector(undef, modulus - 1)\n    mods[1] = seed\n    for i in 2:modulus - 1\n        mods[i] = (7 * mods[i - 1]) % modulus\n    end\n    mods\nend\n@assert mods[end] == 1\n\nfunction q1(card, door)::Int\n    loops = (findfirst(==(card), mods), findfirst(==(door), mods))\n    return mods[(*(loops...) - 1) % (modulus - 1) + 1]\nend\n\n@assert q1(test...) == 14897079\n\nprintln(\"Q1: \", q1(puzzle...))\n", "meta": {"hexsha": "8a6324433dc70f1817a7f4168825376e535901dc", "size": 487, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "aoc2020/day25.jl", "max_stars_repo_name": "dhanak/competitive-coding", "max_stars_repo_head_hexsha": "9e28298f8c646f169b7389d0ef20f99c5ef68f00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aoc2020/day25.jl", "max_issues_repo_name": "dhanak/competitive-coding", "max_issues_repo_head_hexsha": "9e28298f8c646f169b7389d0ef20f99c5ef68f00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aoc2020/day25.jl", "max_forks_repo_name": "dhanak/competitive-coding", "max_forks_repo_head_hexsha": "9e28298f8c646f169b7389d0ef20f99c5ef68f00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1739130435, "max_line_length": 66, "alphanum_fraction": 0.5790554415, "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7784378726414563}}
{"text": "function penstock(Hn, Vdotn, H, theta; method=\"Bier\",eta_nominal=0.9,pipe_roughness=0.05)\r\n    g,rho,mu=parameters()\r\n    P = eta_nominal*rho*g*Vdotn*Hn/1000;\r\n    D = nominal_diameter(method,P,Hn,Vdotn)\r\n    A = pi*D^2/4\r\n    v = Vdotn/A\r\n    NRe = renoldsnum(rho,v,D,mu)\r\n    f = f_Darcy(NRe, pipe_roughness,D)\r\n    L = H/sind(theta)\r\n    hL = f*L*v^2/(2*g*D)\r\n    hGrad = hL/sqrt(L^2-H^2)\r\n    gradAngle = atan(hGrad)\r\n    return sort((Dict(\"a. Nominal head\"=>Hn,\r\n                \"b. Nominal dischare\"=>Vdotn,\r\n                \"c. Nominal hydraulic efficiency\"=>eta_nominal,\r\n                \"d. Nominal power output\"=>P,\r\n                \"e. Design based on\"=>method,\r\n                \"f. Economical diameter\"=>D,\r\n                \"g. Cross-section\"=>A,\r\n                \"h. Height\"=>H,\r\n                \"i. Length\"=>L,\r\n                \"j. Hydraulic crosssection\"=>A,\r\n                \"k. Angle of inclination\"=>theta,\r\n                \"l. Average velocity\"=>v,\r\n                \"m. Nominal Reynolds number\"=>NRe,\r\n                \"n. Darcy's friction factor\"=>f,\r\n                \"o. Nominal allowed head loss\"=>hL,\r\n                \"p. Hydraulic gradient\"=>hGrad,\r\n                \"q. Pipe roughness\"=>pipe_roughness,\r\n                \"r. Gradient angle\"=>gradAngle)))\r\nend\r\n\r\nfunction headraceNsurgetank(Hn, Vdotn, H, theta, Hns; method=\"Bier\",eta_nominal=0.9,pipe_roughness=0.05)\r\n    g,rho,mu=parameters()\r\n    headrace_dict = penstock(Hn, Vdotn, H, theta,method=method,eta_nominal=eta_nominal,pipe_roughness=pipe_roughness)\r\n    # surge tank depends on headrace tunnel so\r\n    n = 1.6 # safety factor for Thoma criteria\r\n    # Acessing data of headrace tunnel from dictionary\r\n    Dt,Lt,At,ft,vt = headrace_dict[\"f. Economical diameter\"],headrace_dict[\"i. Length\"],headrace_dict[\"g. Cross-section\"],headrace_dict[\"n. Darcy's friction factor\"],headrace_dict[\"l. Average velocity\"]\r\n    # calculating headrace tunnel friction factor\r\n    beta = ft*Lt/(2*g*Dt)\r\n    As = n*(Lt*At)/(2*g*beta*(Hn-beta*vt^2))\r\n    Ds = sqrt(4*As/pi)\r\n    Ymax = vt*sqrt((Lt*At)/(g*As))\r\n    Hs = 1.2*(Hns+Ymax)\r\n    vs = Vdotn/As\r\n    surgetank_dict = sort((Dict(\"s. Diameter of surge tank\"=>Ds,\r\n                    \"t. Cross-section of surge tank\"=>As,\r\n                    \"u. Maximum height of water oscillation\"=>Hns+Ymax,\r\n                    \"v. Height of surge tank\"=>Hs,\r\n                    \"w. Allowed velocity of water inside surge tank\"=>vs)))\r\n    return sort(merge(headrace_dict,surgetank_dict))\r\nend\r\nfunction f2x1y(x,y)\r\n    return 2*x+1*y\r\nend\r\n", "meta": {"hexsha": "3cdbab6b9818d0b5f79892f5c96faa9717eff577", "size": 2553, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unitdesign.jl", "max_stars_repo_name": "pandeysudan27/OpenHPLJulia.jl", "max_stars_repo_head_hexsha": "feaec57dc1c9b609bc3f3533cf55929643f5298a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/unitdesign.jl", "max_issues_repo_name": "pandeysudan27/OpenHPLJulia.jl", "max_issues_repo_head_hexsha": "feaec57dc1c9b609bc3f3533cf55929643f5298a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/unitdesign.jl", "max_forks_repo_name": "pandeysudan27/OpenHPLJulia.jl", "max_forks_repo_head_hexsha": "feaec57dc1c9b609bc3f3533cf55929643f5298a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.7894736842, "max_line_length": 203, "alphanum_fraction": 0.5718762241, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7784378719003353}}
{"text": "# # Trade-off curves\nusing Random\nRandom.seed!(1)\nm = 25;\nn = 10;\nA = randn(m, n);\nb = randn(m, 1);\n\n#-\n\nusing Convex, SCS, LinearAlgebra\n\ngammas = exp10.(range(-4, stop = 2, length = 100));\n\nx_values = zeros(n, length(gammas));\nx = Variable(n);\nfor i in 1:length(gammas)\n    cost = sumsquares(A * x - b) + gammas[i] * norm(x, 1)\n    problem = minimize(cost, [norm(x, Inf) <= 1])\n    solve!(problem, SCS.Optimizer; silent_solver = true)\n    x_values[:, i] = evaluate(x)\nend\n\n#-\n\n# Plot the regularization path.\n\nusing Plots\nplot(\n    title = \"Entries of x vs lambda\",\n    xaxis = :log,\n    xlabel = \"lambda\",\n    ylabel = \"x\",\n)\nfor i in 1:n\n    plot!(gammas, x_values[i, :], label = \"x$i\")\nend\nplot!()\n", "meta": {"hexsha": "518416f799f5dd04024a27814a413bfa2d157ad2", "size": 703, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/general_examples/trade_off_curves.jl", "max_stars_repo_name": "baggepinnen/Convex.jl", "max_stars_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 327, "max_stars_repo_stars_event_min_datetime": "2015-01-22T01:00:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T16:42:11.000Z", "max_issues_repo_path": "docs/examples_literate/general_examples/trade_off_curves.jl", "max_issues_repo_name": "baggepinnen/Convex.jl", "max_issues_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 275, "max_issues_repo_issues_event_min_datetime": "2015-01-12T19:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-05T19:05:45.000Z", "max_forks_repo_path": "docs/examples_literate/general_examples/trade_off_curves.jl", "max_forks_repo_name": "baggepinnen/Convex.jl", "max_forks_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 121, "max_forks_repo_forks_event_min_datetime": "2015-01-23T21:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T13:58:39.000Z", "avg_line_length": 18.0256410256, "max_line_length": 57, "alphanum_fraction": 0.5988620199, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.778437868015169}}
{"text": "\"\"\"\n    PeriodicKernel(; r::AbstractVector=ones(Float64, 1))\n\nPeriodic kernel with parameter `r`.\n\n# Definition\n\nFor inputs ``x, x' \\\\in \\\\mathbb{R}^d``, the periodic kernel with parameter ``r_i > 0`` is\ndefined[^DM] as\n```math\nk(x, x'; r) = \\\\exp\\\\bigg(- \\\\frac{1}{2} \\\\sum_{i=1}^d \\\\bigg(\\\\frac{\\\\sin\\\\big(\\\\pi(x_i - x'_i)\\\\big)}{r_i}\\\\bigg)^2\\\\bigg).\n```\n\n[^DM]: D. J. C. MacKay (1998). Introduction to Gaussian Processes.\n\"\"\"\nstruct PeriodicKernel{T} <: SimpleKernel\n    r::Vector{T}\n    function PeriodicKernel(; r::AbstractVector{<:Real}=ones(Float64, 1))\n        @check_args(PeriodicKernel, r, all(ri > zero(ri) for ri in r), \"r > 0\")\n        return new{eltype(r)}(r)\n    end\nend\n\nPeriodicKernel(dims::Int) = PeriodicKernel(Float64, dims)\n\n\"\"\"\n    PeriodicKernel([T=Float64, dims::Int=1])\n\nCreate a [`PeriodicKernel`](@ref) with parameter `r=ones(T, dims)`.\n\"\"\"\nPeriodicKernel(T::DataType, dims::Int=1) = PeriodicKernel(; r=ones(T, dims))\n\n@functor PeriodicKernel\n\nmetric(κ::PeriodicKernel) = Sinus(κ.r)\n\nkappa(::PeriodicKernel, d::Real) = exp(-0.5d)\n\nfunction Base.show(io::IO, κ::PeriodicKernel)\n    return print(io, \"Periodic Kernel, length(r) = $(length(κ.r))\")\nend\n", "meta": {"hexsha": "2758d7f94f5533d77546704fa9baf0a1fbb8755c", "size": 1177, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basekernels/periodic.jl", "max_stars_repo_name": "bmharsha/KernelFunctions.jl", "max_stars_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 200, "max_stars_repo_stars_event_min_datetime": "2020-04-07T11:28:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:14:13.000Z", "max_issues_repo_path": "src/basekernels/periodic.jl", "max_issues_repo_name": "bmharsha/KernelFunctions.jl", "max_issues_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 324, "max_issues_repo_issues_event_min_datetime": "2020-03-24T16:26:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T07:34:54.000Z", "max_forks_repo_path": "src/basekernels/periodic.jl", "max_forks_repo_name": "bmharsha/KernelFunctions.jl", "max_forks_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2020-03-25T10:25:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T21:19:06.000Z", "avg_line_length": 28.0238095238, "max_line_length": 125, "alphanum_fraction": 0.6440101954, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631688, "lm_q2_score": 0.8519528019683105, "lm_q1q2_score": 0.7784092722124246}}
{"text": "using ComponentArrays\nusing DifferentialEquations\nusing Parameters: @unpack\n\n\ntspan = (0.0, 20.0)\n\n\n## Lorenz system\nfunction lorenz!(D, u, p, t; f=0.0)\n    @unpack σ, ρ, β = p\n    @unpack x, y, z = u\n    \n    D.x = σ*(y - x)\n    D.y = x*(ρ - z) - y - f\n    D.z = x*y - β*z\n    return nothing\nend\n\nlorenz_p = (σ=10.0, ρ=28.0, β=8/3)\nlorenz_ic = ComponentArray(x=0.0, y=0.0, z=0.0)\nlorenz_prob = ODEProblem(lorenz!, lorenz_ic, tspan, lorenz_p)\n\n\n## Lotka-Volterra system\nfunction lotka!(D, u, p, t; f=0.0)\n    @unpack α, β, γ, δ = p\n    @unpack x, y = u\n    \n    D.x =  α*x - β*x*y + f\n    D.y = -γ*y + δ*x*y\n    return nothing\nend\n\nlotka_p = (α=2/3, β=4/3, γ=1.0, δ=1.0)\nlotka_ic = ComponentArray(x=1.0, y=1.0)\nlotka_prob = ODEProblem(lotka!, lotka_ic, tspan, lotka_p)\n\n\n## Composed Lorenz and Lotka-Volterra system\nfunction composed!(D, u, p, t)\n    c = p.c #coupling parameter\n    @unpack lorenz, lotka = u\n    \n    lorenz!(D.lorenz, lorenz, p.lorenz, t, f=c*lotka.x)\n    lotka!(D.lotka, lotka, p.lotka, t, f=c*lorenz.x)\n    return nothing\nend\n\ncomp_p = (lorenz=lorenz_p, lotka=lotka_p, c=0.01)\ncomp_ic = ComponentArray(lorenz=lorenz_ic, lotka=lotka_ic)\ncomp_prob = ODEProblem(composed!, comp_ic, tspan, comp_p)\n\n\n## Solve problem\n# We can solve the composed system...\ncomp_sol = solve(comp_prob)\n\n# ...or we can unit test one of the component systems\nlotka_sol = solve(lotka_prob)", "meta": {"hexsha": "3950faacf61db2875b4c40c092712fc7d62b3a9a", "size": 1383, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ODE_example.jl", "max_stars_repo_name": "scheidan/ComponentArrays.jl", "max_stars_repo_head_hexsha": "4a4eb3271c1efb8e724f108ec5cb4a3b9769c329", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/ODE_example.jl", "max_issues_repo_name": "scheidan/ComponentArrays.jl", "max_issues_repo_head_hexsha": "4a4eb3271c1efb8e724f108ec5cb4a3b9769c329", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-13T08:18:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-13T08:18:34.000Z", "max_forks_repo_path": "examples/ODE_example.jl", "max_forks_repo_name": "scheidan/ComponentArrays.jl", "max_forks_repo_head_hexsha": "4a4eb3271c1efb8e724f108ec5cb4a3b9769c329", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.05, "max_line_length": 61, "alphanum_fraction": 0.6341287057, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.7784092633409403}}
{"text": "function dbscan(arr::Array{Float64,2} , ϵ::Number, minPoints::Int)\n\t\n\tnPoints = size(arr,1)\n\tdists = fill(0.0, nPoints, nPoints)\n\tconnectedPaths = fill(0, nPoints, nPoints)\n\t\n\tseeds = Int[]\n\tcounts = Int[]\n\tclusters = zeros(Int, nPoints)\n\tvisited = zeros(Bool, nPoints)\n\n\t# Make superpixel distance matrix and connectivity matrix\n\tfor i in  1:nPoints\n\t\tfor j in 1:nPoints\n\t\t\tdists[i,j] = euclidean(arr[i,:],arr[j,:])\n\t\tend\n\tend\n\t\n\treachable = findall(x->x <= ϵ, dists)\n\tconnectedPaths[reachable] .= 1\n\t\n\tfunction regionQuery(idx)\n\t\tneighbors = findall(x -> x == 1, connectedPaths[:,idx])\n\t\treturn neighbors\n\tend\n\t\n\tk = 0\n\t\n\tfor pt in 1:nPoints\n\t\tif clusters[pt] == 0 && !visited[pt]\n\t\t\tvisited[pt] == true\n\t\t\tneighbors = regionQuery(pt)\n\t\t\tif length(neighbors) >= minPoints\n\t\t\t\tk += 1\n\t\t\t\tclusters[pt] = k\n\t\t\t\tcnt = 1\n\t\t\t\twhile !isempty(neighbors)\n\t\t\t\t\tq = popfirst!(neighbors)\n\t\t\t\t\tif !visited[q]\n\t\t\t\t\t\tvisited[q] = true\n\t\t\t\t\t\tqNeighbors = regionQuery(q)\n\t\t\t\t\t\tfor x in qNeighbors\n\t\t\t\t\t\t\tif clusters[x] == 0\n\t\t\t\t\t\t\t\tpush!(neighbors, x)\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\tif clusters[q] == 0\n\t\t\t\t\t\tclusters[q] = k\n\t\t\t\t\t\tcnt += 1\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tpush!(seeds, pt)\n\t\t\t\tpush!(counts, cnt)\n\t\t\t\t\t\t\n\t\t\tend\n\t\tend\n\tend\n\t\n\treturn clusters\nend", "meta": {"hexsha": "7dd6534aa6a534c128e0d2c32e81789df0ecbb07", "size": 1237, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dbscan.jl", "max_stars_repo_name": "neuro-myoung/CellSegmenter", "max_stars_repo_head_hexsha": "a6fcaf0e929080685d29bac2315cc9488882c8fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-24T22:42:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T22:42:09.000Z", "max_issues_repo_path": "src/dbscan.jl", "max_issues_repo_name": "neuro-myoung/CellSegmenter", "max_issues_repo_head_hexsha": "a6fcaf0e929080685d29bac2315cc9488882c8fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dbscan.jl", "max_forks_repo_name": "neuro-myoung/CellSegmenter", "max_forks_repo_head_hexsha": "a6fcaf0e929080685d29bac2315cc9488882c8fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-24T22:42:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T22:42:13.000Z", "avg_line_length": 20.2786885246, "max_line_length": 66, "alphanum_fraction": 0.6054971706, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7783941156972994}}
{"text": "# Canonical Correlation Analysis\n\n#### CCA Type\n\nstruct CCA{T<:Real}\n    xmean::Vector{T}  # sample mean of X: of length dx (can be empty)\n    ymean::Vector{T}  # sample mean of Y: of length dy (can be empty)\n    xproj::Matrix{T}  # projection matrix for X, of size (dx, p)\n    yproj::Matrix{T}  # projection matrix for Y, of size (dy, p)\n    corrs::Vector{T}  # correlations, of length p\n\n    function CCA(xm::Vector{T},\n                 ym::Vector{T},\n                 xp::Matrix{T},\n                 yp::Matrix{T},\n                 crs::Vector{T}) where T<:Real\n\n        dx, px = size(xp)\n        dy, py = size(yp)\n\n        isempty(xm) || length(xm) == dx ||\n            throw(DimensionMismatch(\"Incorrect length of xmean.\"))\n\n        isempty(ym) || length(ym) == dy ||\n            throw(DimensionMismatch(\"Incorrect length of ymean.\"))\n\n        px == py ||\n            throw(DimensionMismatch(\"xproj and yproj should have the same number of columns.\"))\n\n        length(crs) == px ||\n            throw(DimensionMismatch(\"Incorrect length of corrs.\"))\n\n        new{T}(xm, ym, xp, yp, crs)\n    end\nend\n\n## properties\n\nxindim(M::CCA) = size(M.xproj, 1)\nyindim(M::CCA) = size(M.yproj, 1)\noutdim(M::CCA) = size(M.xproj, 2)\n\nxmean(M::CCA) = fullmean(xindim(M), M.xmean)\nymean(M::CCA) = fullmean(yindim(M), M.ymean)\n\nxprojection(M::CCA) = M.xproj\nyprojection(M::CCA) = M.yproj\n\ncorrelations(M::CCA) = M.corrs\n\n## use\n\nxtransform(M::CCA, X::AbstractVecOrMat{<:Real}) = transpose(M.xproj) * centralize(X, M.xmean)\nytransform(M::CCA, Y::AbstractVecOrMat{<:Real}) = transpose(M.yproj) * centralize(Y, M.ymean)\n\n## show & dump\n\nfunction show(io::IO, M::CCA)\n    print(io, \"CCA (xindim = $(xindim(M)), yindim = $(yindim(M)), outdim = $(outdim(M)))\")\nend\n\nfunction dump(io::IO, M::CCA)\n    show(io, M)\n    println(io)\n    println(io, \"correlations: \")\n    printvecln(io, correlations(M))\n    println(io, \"xmean:\")\n    printvecln(io, xmean(M))\n    println(io, \"ymean:\")\n    printvecln(io, ymean(M))\n    println(io, \"xprojection:\")\n    printarrln(io, xprojection(M))\n    println(io, \"yprojection:\")\n    printarrln(io, yprojection(M))\nend\n\n\n#### Perform CCA on data\n\n## ccacov\n\nfunction ccacov(Cxx::DenseMatrix{T},\n                Cyy::DenseMatrix{T},\n                Cxy::DenseMatrix{T},\n                xmean::Vector{T},\n                ymean::Vector{T},\n                p::Int) where T<:Real\n\n    # argument checking\n    dx, dx2 = size(Cxx)\n    dy, dy2 = size(Cyy)\n    dx == dx2 || error(\"Cxx must be a square matrix.\")\n    dy == dy2 || error(\"Cyy must be a square matrix.\")\n    size(Cxy) == (dx, dy) ||\n        throw(DimensionMismatch(\"size(Cxy) should be equal to (dx, dy)\"))\n\n    isempty(xmean) || length(xmean) == dx ||\n        throw(DimensionMismatch(\"Incorrect length of xmean.\"))\n\n    isempty(ymean) || length(ymean) == dy ||\n        throw(DimensionMismatch(\"Incorrect length of ymean.\"))\n\n    1 <= p <= min(dx, dy) ||\n        throw(DimensionMismatch(\"\"))\n\n    _ccacov(Cxx, Cyy, Cxy, xmean, ymean, p)\nend\n\nfunction _ccacov(Cxx, Cyy, Cxy, xmean, ymean, p::Int)\n    dx = size(Cxx, 1)\n    dy = size(Cyy, 1)\n\n    # solve Px and Py\n\n    if dx <= dy\n        # solve Px: (Cxy * inv(Cyy) * Cyx) Px = λ Cxx * Px\n        # compute Py: inv(Cyy) * Cyx * Px\n\n        G = cholesky(Cyy) \\ Cxy'\n        Ex = eigen(Symmetric(Cxy * G), Symmetric(Cxx))\n        ord = sortperm(Ex.values; rev=true)\n        vx, Px = extract_kv(Ex, ord, p)\n        Py = qnormalize!(G * Px, Cyy)\n    else\n        # solve Py: (Cyx * inv(Cxx) * Cxy) Py = λ Cyy Py\n        # compute Px: inv(Cx) * Cxy * Py\n\n        H = cholesky(Cxx) \\ Cxy\n        Ey = eigen(Symmetric(Cxy'H), Symmetric(Cyy))\n        ord = sortperm(Ey.values; rev=true)\n        vy, Py = extract_kv(Ey, ord, p)\n        Px = qnormalize!(H * Py, Cxx)\n    end\n\n    # compute correlations\n    # Note: Px' * Cxx * Px == I\n    #       Py' * Cyy * Py == I\n    crs = coldot(Px, Cxy * Py)\n\n    # construct CCA model\n    CCA(xmean, ymean, Px, Py, crs)\nend\n\n## ccasvd\n\nfunction ccasvd(Zx::DenseMatrix{T},\n                Zy::DenseMatrix{T},\n                xmean::Vector{T},\n                ymean::Vector{T},\n                p::Int) where T<:Real\n\n    dx, n = size(Zx)\n    dy, n2 = size(Zy)\n    n == n2 ||\n        throw(DimensionMismatch(\"Zx and Zy must have the same number of columns.\"))\n\n    isempty(xmean) || length(xmean) == dx ||\n        throw(DimensionMismatch(\"Incorrect length of xmean.\"))\n\n    isempty(ymean) || length(ymean) == dy ||\n        throw(DimensionMismatch(\"Incorrect length of ymean.\"))\n\n    1 <= p <= min(dx, dy) ||\n        throw(DimensionMismatch(\"\"))\n\n    _ccasvd(Zx, Zy, xmean, ymean, p)\nend\n\n# The implementation is partly based on:\n#\n#   David Weenink.\n#   Canonical Correlation Analysis.\n#   Institute of Phonetic Sciences, Univ. of Amsterdam,\n#   Proceedings 25 (2003), 81-99.\n#\n#   Note: in this paper, each row is considered as an observation.\n#   The algorithm is adpated to the column-major format here.\n#\nfunction _ccasvd(Zx::DenseMatrix{T}, Zy::DenseMatrix{T}, xmean::Vector{T}, ymean::Vector{T}, p::Int) where T<:Real\n    # svd factorization of Z\n\n    n = size(Zx, 2)\n\n    # svd decomposition\n    Sx = svd(Zx)\n    Sy = svd(Zy)\n    S = svd!(Sx.Vt * transpose(Sy.Vt)) # svd of Vx * Vy'\n\n    # compute Px and Py\n    ord = sortperm(S.S; rev=true)\n    si = ord[1:p]\n    Px = rmul!(Sx.U, Diagonal(1.0 ./ Sx.S)) * S.U[:, si]\n    Py = rmul!(Sy.U, Diagonal(1.0 ./ Sy.S)) * S.V[:, si]\n\n    # scale so that Px' * Cxx * Py == I\n    #           and Py' * Cyy * Py == I,\n    #\n    # with Cxx = Zx * Zx' / (n - 1)\n    #      Cyy = Zy * Zy' / (n - 1)\n    #\n    rmul!(Px, sqrt(n-1))\n    rmul!(Py, sqrt(n-1))\n\n    # compute correlations\n    crs = rmul!(coldot(Zx'Px, Zy'Py), one(T)/(n-1))\n\n    # construct CCA model\n    CCA(xmean, ymean, Px, Py, crs)\nend\n\n## interface functions\n\nfunction fit(::Type{CCA}, X::AbstractMatrix{T}, Y::AbstractMatrix{T};\n             outdim::Int=min(min(size(X)...), min(size(Y)...)),\n             method::Symbol=:svd,\n             xmean=nothing,\n             ymean=nothing) where T<:Real\n\n    dx, n = size(X)\n    dy, n2 = size(Y)\n\n    n2 == n ||\n        throw(DimensionMismatch(\"X and Y should have the same number of columns.\"))\n\n    (n >= dx && n >= dy) ||\n        @warn(\"CCA would be numerically instable when n < dx or n < dy.\")\n\n    xmv = preprocess_mean(X, xmean)\n    ymv = preprocess_mean(Y, ymean)\n\n    Zx = centralize(X, xmv)\n    Zy = centralize(Y, ymv)\n\n    if method == :cov\n        Cxx = rmul!(Zx*transpose(Zx), inv(n - 1))\n        Cyy = rmul!(Zy*transpose(Zy), inv(n - 1))\n        Cxy = rmul!(Zx*transpose(Zy), inv(n - 1))\n        M = ccacov(Cxx, Cyy, Cxy, xmv, ymv, outdim)\n    elseif method == :svd\n        M = ccasvd(Zx, Zy, xmv, ymv, outdim)\n    else\n        error(\"Invalid method name $(method)\")\n    end\n\n    return M::CCA\nend\n", "meta": {"hexsha": "7c3faa97fd42c5b99b0bfcf0fde3855cdfbe7fb6", "size": 6801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cca.jl", "max_stars_repo_name": "rkube/MultivariateStats.jl", "max_stars_repo_head_hexsha": "949cd06d4c26e0e0cad005d24110e2226f2b87f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 294, "max_stars_repo_stars_event_min_datetime": "2015-01-30T17:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T23:59:27.000Z", "max_issues_repo_path": "src/cca.jl", "max_issues_repo_name": "rkube/MultivariateStats.jl", "max_issues_repo_head_hexsha": "949cd06d4c26e0e0cad005d24110e2226f2b87f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 145, "max_issues_repo_issues_event_min_datetime": "2015-01-17T17:09:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T02:59:04.000Z", "max_forks_repo_path": "src/cca.jl", "max_forks_repo_name": "rkube/MultivariateStats.jl", "max_forks_repo_head_hexsha": "949cd06d4c26e0e0cad005d24110e2226f2b87f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 92, "max_forks_repo_forks_event_min_datetime": "2015-02-19T09:16:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T11:45:23.000Z", "avg_line_length": 27.5344129555, "max_line_length": 114, "alphanum_fraction": 0.5600646964, "num_tokens": 2181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7783941137131648}}
{"text": "\"\"\"\n    Base.rand(randomwalk::RandomWalk{<:AbstractArray{<:DataType}, <:AbstractArray{<:Real},\n                                     <:Sampleable}, ntimesteps::Integer) -> Matrix{Int}\n\nSimulate `randomwalk` for `ntimesteps` time-steps over an integer lattice, returning one\nsample path (i.e. trajectory) of length `ntimesteps`.\n\nThe time steps represented in the sample path are `0, 1, ..., ntimesteps-1`, for we start\nwith an initial state.\n\n##### Complexity\n- Time complexity: `O(n)`.\n\"\"\"\nfunction Base.rand(randomwalk::RandomWalk{<:AbstractArray{<:DataType},\n                                          <:AbstractArray{<:Real},\n                                          <:Sampleable}, ntimesteps::Integer)\n    # allocate memory\n    realizationmatrix = Matrix{Int}(undef, ntimesteps,\n                                                   length(randomwalk.initialstate))\n    realizationmatrix[1,:] = randomwalk.initialstate\n    # draw a random step\n    change = rand(randomwalk.stepsampler)\n    for step in 2:ntimesteps\n        realizationmatrix[step,:] = realizationmatrix[step-1,:] + change\n        change = rand(randomwalk.stepsampler)\n    end\n    return realizationmatrix\nend\n\n\"\"\"\n    Base.rand(randomwalk::RandomWalk{<:DataType, <:Real, <:Sampleable,\n              ntimesteps::Integer) -> Vector{Int}\n\nSimulate a one-dimensional `randomwalk` for `ntimesteps` time-steps, returning one sample\npath (i.e. trajectory) of length `ntimesteps`.\n\nThe time steps represented in the sample path are `0, 1, ..., ntimesteps-1`, for we start\nwith an initial state.\n\n##### Complexity\n- Time complexity: `O(n)`.\n\"\"\"\nfunction Base.rand(randomwalk::RandomWalk{<:DataType, <:Real, <:Sampleable},\n                   ntimesteps::Integer)\n    # allocate memory\n    realizationvec = Vector{eltype(randomwalk)}(undef, ntimesteps)\n    realizationvec[1] = randomwalk.initialstate\n    # draw a random step\n    change = rand(randomwalk.stepsampler)[1]\n    for step in 2:ntimesteps\n        realizationvec[step] = realizationvec[step-1] + change\n        change = rand(randomwalk.stepsampler)[1]\n    end\n    return realizationvec\nend\n\n\"\"\"\n    Base.rand(randomwalk::RandomWalk{<:AbstractGraph, <:Integer, <:Sampleable},\n              ntimesteps::Integer) -> Vector{Int}\n\nSimulate `randomwalk` for `ntimesteps` time-steps over a graph, returning one sample path\n(i.e. trajectory) of length `ntimesteps`.\n\nThe time steps represented in the sample path are `0, 1, ..., ntimesteps-1`, for we start\nwith an initial state.\n\n##### Complexity\n- Time complexity: `O(n)`.\n\"\"\"\nfunction Base.rand(randomwalk::RandomWalk{<:AbstractGraph, <:Integer, <:Sampleable},\n                   ntimesteps::Integer)\n    # allocate memory\n    realizationvec = Vector{eltype(randomwalk)}(undef, ntimesteps)\n    realizationvec[1] = randomwalk.initialstate\n    for step in 2:ntimesteps\n        # draw a neighbor at random\n        realizationvec[step] = NeighborSampler(randomwalk.statespace,\n                                               realizationvec[step-1]) |> rand\n    end\n    return realizationvec\nend\n", "meta": {"hexsha": "69b6b3dda9b973b90729adae474bdf6987a80e02", "size": 3051, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/RandomWalks/simulaterandomwalks.jl", "max_stars_repo_name": "LoganDGraham/StochasticProcesses", "max_stars_repo_head_hexsha": "c3f9947d9f93c9d8397664ed3acf93c8bf7da444", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-11-15T19:57:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T22:42:14.000Z", "max_issues_repo_path": "src/RandomWalks/simulaterandomwalks.jl", "max_issues_repo_name": "LoganDGraham/StochasticProcesses", "max_issues_repo_head_hexsha": "c3f9947d9f93c9d8397664ed3acf93c8bf7da444", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-02T16:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-14T17:56:52.000Z", "max_forks_repo_path": "src/RandomWalks/simulaterandomwalks.jl", "max_forks_repo_name": "LoganDGraham/StochasticProcesses", "max_forks_repo_head_hexsha": "c3f9947d9f93c9d8397664ed3acf93c8bf7da444", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2073170732, "max_line_length": 90, "alphanum_fraction": 0.6486397902, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8670357477770336, "lm_q1q2_score": 0.7783339088682162}}
{"text": "#!jl # # EFTfitter.jl - BLUE Example\n#jl # EFTfitter.jl - BLUE Example\n\n#~When using multiple measurements of a single observable and a uniform prior for\n#~the parameter representing the combined value, the combination of measurements performed with EFTfitter.jl\n#~yields the same results as the Best Linear Unbiased Estimator (BLUE) method.\n\n#~Here, we demonstrate this by using the examples of the paper\n#~\"How to combine correlated estimates of a single physical quantity\"\n#~by L. Lyons, D. Gibaut and P. Clifford (https://www.sciencedirect.com/science/article/pii/0168900288900186).\n#~All numbers are taken from the example on charm particle lifetime experiments in section 5.\n#~A factor of 10^13 is applied for convenience.\n\nusing EFTfitter\nusing BAT\nusing IntervalSets\nusing Statistics\nusing StatsBase\nusing LinearAlgebra\nusing Plots\n\n#~We need one parameter for the best estimator and choose\n#~a uniform distribution in the range 8 to 14 as prior:\nparameters = BAT.NamedTupleDist(\n    τ = 8..14,\n)\n\n#~When combining multiple measurements of the same observable,\n#~only a function returning the combination parameter is needed:\nestimator(params) = params.τ\n\n#~In Eq. (17') of the reference paper the following covariance matrix is given:\ncovariance = [2.74 1.15 0.86 1.31;\n              1.15 1.67 0.82 1.32;\n              0.86 0.82 2.12 1.05;\n              1.31 1.32 1.05 2.93]\n\n#~For using this in EFTfitter.jl, we first need to convert the covariance matrix \n#~into a correlation matrix and the corresponding uncertainty values:\ncorr, unc = EFTfitter.cov_to_cor(covariance)\n\nmeasurements = (\n    τ1 = Measurement(estimator,  9.5, uncertainties = (stat=unc[1],) ),\n    τ2 = Measurement(estimator, 11.9, uncertainties = (stat=unc[2],) ),\n    τ3 = Measurement(estimator, 11.1, uncertainties = (stat=unc[3],) ),\n    τ4 = Measurement(estimator,  8.9, uncertainties = (stat=unc[4],) ),\n)\n\ncorrelations = (\n    stat = Correlation(corr),\n)\n\n#~construct an `EFTfitterModel`:\nmodel = EFTfitterModel(parameters, measurements, correlations)\nposterior = PosteriorDensity(model);\n\n#~sample the posterior with BAT.jl:\nalgorithm = MCMCSampling(mcalg =MetropolisHastings(), nsteps = 10^6, nchains = 4)\nsamples = bat_sample(posterior, algorithm).result\n\n#~plot the posterior distribution for the combination parameter τ:\nplot(samples, :τ, mean=true)\n#md # ![blue plots](plots/plot_blue.png)\n\n#~print numerical results of combination:\nprintln(\"Mode: $(mode(samples).τ)\")\nprintln(\"Mean: $(mean(samples).τ) ± $(std(samples).τ)\")\n#md ```\n#md Mode: 11.15985\n#md Mean: 11.15471 ± 0.80180\n#md ```\n\n#!jl # ### Comparison with BLUE method\n#jl # comparison with BLUE method:\nblue = BLUE(model)\nprintln(\"BLUE: $(blue.value) ± $(blue.unc)\") \nprintln(\"BLUE weights: $(blue.weights)\") \n#md ```\n#md BLUE: 11.15983 ± 1.28604  \n#md BLUE weights: [0.145, 0.470, 0.347, 0.038]\n#md ```\n", "meta": {"hexsha": "b9df97e452884c4db29629efb6265a6f0059ba7e", "size": 2856, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/literate/BLUE_lit/lit_runBLUE.jl", "max_stars_repo_name": "oschulz/EFTfitter.jl", "max_stars_repo_head_hexsha": "38a3d05e9db1e905661580e47a245c5e5e04870f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-27T15:31:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T13:34:25.000Z", "max_issues_repo_path": "docs/src/literate/BLUE_lit/lit_runBLUE.jl", "max_issues_repo_name": "oschulz/EFTfitter.jl", "max_issues_repo_head_hexsha": "38a3d05e9db1e905661580e47a245c5e5e04870f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-01-28T08:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-10T00:39:51.000Z", "max_forks_repo_path": "docs/src/literate/BLUE_lit/lit_runBLUE.jl", "max_forks_repo_name": "oschulz/EFTfitter.jl", "max_forks_repo_head_hexsha": "38a3d05e9db1e905661580e47a245c5e5e04870f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-27T22:42:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T14:21:15.000Z", "avg_line_length": 34.8292682927, "max_line_length": 110, "alphanum_fraction": 0.718837535, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703476, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.7783339080372699}}
{"text": "export birdcageSensitivity\n\n\"\"\"\n    birdcageSensitivity(N::Int64, ncoils::Int64, relative_radius::Float64)\n\nComputes the sensitivity maps for each coils that are arranged\nin a birdcage manner.\n\"\"\"\nfunction birdcageSensitivity(N::Int64,\n                             ncoils::Int64,\n                             relative_radius::Float64)\n\n  out = zeros(ComplexF64, N, N, 1, ncoils)\n  for c=0:ncoils-1\n    coilx = relative_radius*cos(c*(2*pi/ncoils))\n    coily = relative_radius*sin(c*(2*pi/ncoils))\n    coil_phase = -c*(2*pi/ncoils)\n\n    for y=0:N-1\n      y_co = (y - (N/2))/(N/2) - coily\n      for x=0:N-1\n        x_co = (x - (N/2))/(N/2) - coilx\n        rr = sqrt(x_co^2+y_co^2)\n        phi = atan(x_co, -y_co) + coil_phase\n        out[x+1,y+1, 1, c+1] = 1/(rr) * exp(1im*phi)\n      end\n    end\n  end\n return out\nend\n", "meta": {"hexsha": "c89d98a438125e61c3f3d59828907abd7afbf3d8", "size": 816, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Simulation/CoilSensitivity.jl", "max_stars_repo_name": "UnofficialJuliaMirror/MRIReco.jl-bdf86e05-2d2b-5731-a332-f3fe1f9e047f", "max_stars_repo_head_hexsha": "f8ce9fcd09d81c166bae1359884489e7b0da0954", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2019-04-22T20:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T10:49:45.000Z", "max_issues_repo_path": "src/Simulation/CoilSensitivity.jl", "max_issues_repo_name": "UnofficialJuliaMirror/MRIReco.jl-bdf86e05-2d2b-5731-a332-f3fe1f9e047f", "max_issues_repo_head_hexsha": "f8ce9fcd09d81c166bae1359884489e7b0da0954", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 49, "max_issues_repo_issues_event_min_datetime": "2018-11-03T09:34:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T15:13:07.000Z", "max_forks_repo_path": "src/Simulation/CoilSensitivity.jl", "max_forks_repo_name": "UnofficialJuliaMirror/MRIReco.jl-bdf86e05-2d2b-5731-a332-f3fe1f9e047f", "max_forks_repo_head_hexsha": "f8ce9fcd09d81c166bae1359884489e7b0da0954", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2019-04-23T21:34:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T08:34:17.000Z", "avg_line_length": 26.3225806452, "max_line_length": 74, "alphanum_fraction": 0.5759803922, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966762263737, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7782815002436559}}
{"text": "function generate_synthetic_data(n, param_frac, sigma; signal_to_noise=10,\n    fixed_rank_sparse=false, fixed_rank=1, fixed_sparse=0)\n    \"\"\"\n    This function samples synthetic data by adding noise to the sum of a\n    random low rank matrix and a random sparse matrix.\n\n    :param n: The row and column dimension of the data to be sampled (Int64).\n    :param param_frac: Parameter that controls the rank and sparsity of the\n                       sampled low rank and sparse matrix when\n                       fixed_rank_sparse=false (Float64).\n    :param sigma: Parameter that controls the absolute magnitude of the noise\n                  (Float64).\n    :param signal_to_noise: Parameter that controls the signal to noise ratio of\n                            the sampled data (Float64).\n    :param fixed_rank_sparse: If true, use fixed_rank and fixed_sparse as the\n                              rank and sparsity respectively of the low rank\n                              matrix and the sparse matrix to be sampled (Bool).\n    :param fixed_rank: Rank of the low rank matrix to be sampled when\n                       fixed_rank_sparse=true.\n    :param fixed_sparse: Sparsity of the sparse matrix to be sampled when\n                         fixed_rank_sparse=true\n\n    :return: This function returns 5 values:\n             1) The sampled n x n data matrix.\n             2) The sampled n x n low rank matrix.\n             3) The sampled n x n sparse matrix.\n             4) The sparsity level of the sparse matrix.\n             5) The rank of the low rank matrix.\n    \"\"\"\n\n    if fixed_rank_sparse\n        k_sparse = fixed_sparse\n        k_rank = fixed_rank\n    else\n        k_sparse = Int64(floor(param_frac * n^2))\n        k_rank = Int64(floor(param_frac * n))\n    end\n\n    # Sample a rank k_rank matrix\n    d = Normal(0, signal_to_noise * sigma / n^0.5)\n    X = rand(d, (n, k_rank))\n    Y = rand(d, (n, k_rank))\n    L_0 = X * Y'\n\n    # Sample a sparsity k_sparse matrix\n    d = Uniform(-5, 5)\n    E = rand(d, (n, n))\n    S_0 = zeros(n, n)\n\n    indexes = []\n    for i = 1:n\n        for j = 1:n\n            append!(indexes, [(i, j)])\n        end\n    end\n\n    select_indexes = sample(indexes, k_sparse, replace=false)\n    for index in select_indexes\n        S_0[index[1], index[2]] = E[index[1], index[2]]\n    end\n\n    data = L_0 + S_0\n\n    # Add noise to the sum of the sampled low rank and sparse matrices\n    d = Normal(0, sigma^2)\n    noise = rand(d, (n, n))\n    data = data + noise\n\n    return data, L_0, S_0, k_sparse, k_rank\n\nend;\n\nfunction generate_synthetic_data_symmetric(n, param_frac, sigma;\n    signal_to_noise=10, fixed_rank_sparse=false, fixed_rank=1, fixed_sparse=0)\n    \"\"\"\n    This function samples symmetric synthetic data by adding symmetric noise to\n    the sum of a random symmetric low rank matrix and a random symmetric sparse\n    matrix.\n\n    :param n: The row and column dimension of the data to be sampled (Int64).\n    :param param_frac: Parameter that controls the rank and sparsity of the\n                       sampled low rank and sparse matrix when\n                       fixed_rank_sparse=false (Float64).\n    :param sigma: Parameter that controls the absolute magnitude of the noise\n                  (Float64).\n    :param signal_to_noise: Parameter that controls the signal to noise ratio of\n                            the sampled data (Float64).\n    :param fixed_rank_sparse: If true, use fixed_rank and fixed_sparse as the\n                              rank and sparsity respectively of the low rank\n                              matrix and the sparse matrix to be sampled (Bool).\n    :param fixed_rank: Rank of the low rank matrix to be sampled when\n                       fixed_rank_sparse=true.\n    :param fixed_sparse: Sparsity of the sparse matrix to be sampled when\n                         fixed_rank_sparse=true\n\n    :return: This function returns 5 values:\n             1) The sampled n-by-n data matrix.\n             2) The sampled n-by-n low rank matrix.\n             3) The sampled n-by-n sparse matrix.\n             4) The sparsity level of the sparse matrix.\n             5) The rank of the low rank matrix.\n    \"\"\"\n\n    if fixed_rank_sparse\n        k_sparse = fixed_sparse\n        k_rank = fixed_rank\n    else\n        k_sparse = Int64(floor(param_frac * n^2))\n        k_rank = Int64(floor(param_frac * n))\n    end\n\n    # Sample a rank k_rank symmetric matrix\n    d = Normal(0, signal_to_noise * sigma / n^0.5)\n    X = rand(d, (n, k_rank))\n    L_0 = X * X'\n\n    # Sample a sparsity k_sparse symmetric matrix\n    d = Uniform(-5, 5)\n    E = rand(d, (n, n))\n    S_0 = zeros(n, n)\n\n    indexes = []\n    for i = 1:(n-1)\n        for j = (i+1):n\n            append!(indexes, [(i, j)])\n        end\n    end\n\n    select_indexes = sample(indexes, Int64(floor(k_sparse/2)), replace=false)\n    for index in select_indexes\n        S_0[index[1], index[2]] = E[index[1], index[2]]\n        S_0[index[2], index[1]] = S_0[index[1], index[2]]\n    end\n\n    if k_sparse % 2 == 1\n        index = sample(1:n, 1)\n        S_0[index, index] = E[index, index]\n    end\n\n    data = L_0 + S_0\n\n    # Add symmetric noise to the sum of the sampled low rank and sparse matrices\n    d = Normal(0, sigma^2)\n    noise = rand(d, (n, n))\n    for i = 1:(n-1)\n        for j = (i+1):n\n            noise[j, i] = noise[i, j]\n        end\n    end\n    data = data + noise\n\n    return data, L_0, S_0, k_sparse, k_rank\n\nend;\n", "meta": {"hexsha": "e82c994583384a441d8d77695de42914d4e98c61", "size": 5428, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/generateSyntheticData.jl", "max_stars_repo_name": "NicholasJohnson2020/SparseLowRankSoftware", "max_stars_repo_head_hexsha": "824c9db34b3f3299ae1ffe195b29bf72f603a80c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-03T15:42:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T15:42:59.000Z", "max_issues_repo_path": "src/generateSyntheticData.jl", "max_issues_repo_name": "NicholasJohnson2020/SparseLowRankSoftware", "max_issues_repo_head_hexsha": "824c9db34b3f3299ae1ffe195b29bf72f603a80c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/generateSyntheticData.jl", "max_forks_repo_name": "NicholasJohnson2020/SparseLowRankSoftware", "max_forks_repo_head_hexsha": "824c9db34b3f3299ae1ffe195b29bf72f603a80c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0193548387, "max_line_length": 80, "alphanum_fraction": 0.600036846, "num_tokens": 1387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7782814994132329}}
{"text": "# In this tutorial, we will learn\n#  - How to solve nonlinear multi-field PDEs in Gridap\n#  - How to build FE spaces whose functions have zero mean value\n#\n# ## Problem statement\n#\n# The goal of this last tutorial is to solve a nonlinear multi-field PDE. As a model problem, we consider a well known benchmark in computational fluid dynamics, the lid-driven cavity for the incompressible Navier-Stokes equations. Formally, the PDE we want to solve is: find the velocity vector $u$ and the pressure $p$ such that\n#\n# ```math\n# \\left\\lbrace\n# \\begin{aligned}\n# -\\Delta u + \\mathit{Re}\\ (u\\cdot \\nabla)\\ u + \\nabla p = 0 &\\text{ in }\\Omega,\\\\\n# \\nabla\\cdot u = 0 &\\text{ in } \\Omega,\\\\\n# u = g &\\text{ on } \\partial\\Omega,\n# \\end{aligned}\n# \\right.\n# ```\n#\n# where the computational domain is the unit square $\\Omega \\doteq (0,1)^d$, $d=2$, $\\mathit{Re}$ is the Reynolds number (here, we take $\\mathit{Re}=10$), and $(w \\cdot \\nabla)\\ u = (\\nabla u)^t w$  is the well known convection operator. In this example, the driving force is the Dirichlet boundary velocity $g$, which is a non-zero horizontal velocity with a value of $g = (1,0)^t$ on the top side of the cavity, namely the boundary $(0,1)\\times\\{1\\}$, and $g=0$ elsewhere on $\\partial\\Omega$. Since we impose Dirichlet boundary conditions on the entire boundary $\\partial\\Omega$, the mean value of the pressure is constrained to zero in order have a well posed problem,\n#\n# ```math\n# \\int_\\Omega q \\ {\\rm d}\\Omega = 0.\n# ```\n#\n# ## Numerical Scheme\n#\n# In order to approximate this problem we chose a formulation based on inf-sub stable $Q_k/P_{k-1}$ elements with continuous velocities and discontinuous pressures (see, e.g., [1] for specific details). The interpolation spaces are defined as follows.  The velocity interpolation space is\n#\n# ```math\n# V \\doteq \\{ v \\in [C^0(\\Omega)]^d:\\ v|_T\\in [Q_k(T)]^d \\text{ for all } T\\in\\mathcal{T} \\},\n# ```\n# where $T$ denotes an arbitrary cell of the FE mesh $\\mathcal{T}$, and $Q_k(T)$ is the local polynomial space in cell $T$ defined as the multi-variate polynomials in $T$ of order less or equal to $k$ in each spatial coordinate. Note that, this is the usual continuous vector-valued Lagrangian FE space of order $k$ defined on a mesh of quadrilaterals or hexahedra.  On the other hand, the space for the pressure is\n#\n# ```math\n# \\begin{aligned}\n# Q_0 &\\doteq \\{ q \\in Q: \\  \\int_\\Omega q \\ {\\rm d}\\Omega = 0\\}, \\text{ with}\\\\\n# Q &\\doteq \\{ q \\in L^2(\\Omega):\\ q|_T\\in P_{k-1}(T) \\text{ for all } T\\in\\mathcal{T}\\},\n# \\end{aligned}\n# ```\n# where $P_{k-1}(T)$ is the polynomial space of multi-variate polynomials in $T$ of degree less or equal to $k-1$. Note that functions in $Q_0$ are strongly constrained to have zero mean value. This is achieved in the code by removing one degree of freedom from the (unconstrained) interpolation space $Q$ and  adding a constant to the computed pressure so that the resulting function has zero mean value.\n#\n# The weak form associated to these interpolation spaces reads: find $(u,p)\\in U_g \\times Q_0$ such that $[r(u,p)](v,q)=0$ for all $(v,q)\\in V_0 \\times Q_0$\n# where $U_g$ and $V_0$ are the set of functions in $V$ fulfilling the Dirichlet boundary condition $g$ and $0$  on $\\partial\\Omega$ respectively. The weak residual $r$ evaluated at a given pair $(u,p)$ is the linear form defined as\n#\n# ```math\n# [r(u,p)](v,q) \\doteq a((u,p),(v,q))+ [c(u)](v),\n# ```\n# with\n# ```math\n# \\begin{aligned}\n# a((u,p),(v,q)) &\\doteq \\int_{\\Omega} \\nabla v \\cdot \\nabla u \\ {\\rm d}\\Omega - \\int_{\\Omega} (\\nabla\\cdot v) \\ p \\ {\\rm d}\\Omega + \\int_{\\Omega} q \\ (\\nabla \\cdot u) \\ {\\rm d}\\Omega,\\\\\n# [c(u)](v) &\\doteq \\int_{\\Omega} v \t\\cdot \\left( (u\\cdot\\nabla)\\ u \\right)\\ {\\rm d}\\Omega.\\\\\n# \\end{aligned}\n# ```\n# Note that the bilinear form $a$ is associated with the linear part of the PDE, whereas $c$ is the contribution to the residual resulting from the convective term.\n#\n# In order to solve this nonlinear weak equation with a Newton-Raphson method, one needs to compute the Jacobian associated with the residual $r$. In this case, the Jacobian $j$ evaluated at a pair $(u,p)$ is the bilinear form defined as\n#\n# ```math\n# [j(u,p)]((\\delta u, \\delta p),(v,q)) \\doteq a((\\delta u,\\delta p),(v,q))  + [{\\rm d}c(u)](\\delta u,v),\n# ```\n# where ${\\rm d}c$ results from the linearization of the convective term, namely\n# ```math\n# [{\\rm d}c(u)](\\delta u,v) \\doteq \\int_{\\Omega} v \\cdot \\left( (u\\cdot\\nabla)\\ \\delta u \\right) \\ {\\rm d}\\Omega + \\int_{\\Omega} v \\cdot \\left( (\\delta u\\cdot\\nabla)\\ u \\right)  \\ {\\rm d}\\Omega.\n# ```\n# The implementation of this numerical scheme is done in Gridap by combining the concepts previously seen for single-field nonlinear PDEs  and linear multi-field problems.\n#\n# ## Discrete model\n#\n# We start with the discretization of the computational domain. We consider a $100\\times100$ Cartesian mesh of the unit square.\n\nusing Gridap\nn = 100\ndomain = (0,1,0,1)\npartition = (n,n)\nmodel = CartesianDiscreteModel(domain,partition)\n\n# For convenience, we create two new boundary tags,  namely `\"diri1\"` and `\"diri0\"`, one for the top side of the square (where the velocity is non-zero), and another for the rest of the boundary (where the velocity is zero).\n\nlabels = get_face_labeling(model)\nadd_tag_from_tags!(labels,\"diri1\",[6,])\nadd_tag_from_tags!(labels,\"diri0\",[1,2,3,4,5,7,8])\n\n# ## FE spaces\n#\n# For the velocities, we need to create a conventional vector-valued continuous Lagrangian FE space. In this example, we select a second order interpolation.\n\nD = 2\norder = 2\nreffeᵤ = ReferenceFE(lagrangian,VectorValue{2,Float64},order)\nV = TestFESpace(model,reffeᵤ,conformity=:H1,labels=labels,dirichlet_tags=[\"diri0\",\"diri1\"])\n\n# The interpolation space for the pressure is built as follows\n\nreffeₚ = ReferenceFE(lagrangian,Float64,order-1;space=:P)\nQ = TestFESpace(model,reffeₚ,conformity=:L2,constraint=:zeromean)\n\n# With the options `:Lagrangian`, `space=:P`, `valuetype=Float64`, and `order=order-1`, we select the local polynomial space $P_{k-1}(T)$ on the cells $T\\in\\mathcal{T}$. With the symbol `space=:P` we specifically chose a local Lagrangian interpolation of type \"P\". Without using `space=:P`, would lead to a local Lagrangian of type \"Q\" since this is the default for quadrilateral or hexahedral elements. On the other hand, `constraint=:zeromean` leads to a FE space, whose functions are constrained to have mean value equal to zero, which is just what we need for the pressure space. With these objects, we build the trial multi-field FE spaces\n\nuD0 = VectorValue(0,0)\nuD1 = VectorValue(1,0)\nU = TrialFESpace(V,[uD0,uD1])\nP = TrialFESpace(Q)\n\nY = MultiFieldFESpace([V, Q])\nX = MultiFieldFESpace([U, P])\n\n# ## Triangulation and integration quadrature\n#\n# From the discrete model we can define the triangulation and integration measure\n\ndegree = order\nΩₕ = Triangulation(model)\ndΩ = Measure(Ωₕ,degree)\n\n\n# ## Nonlinear weak form\n#\n# The different terms of the nonlinear weak form for this example are defined following an approach similar to the one discussed for the $p$-Laplacian equation, but this time using the notation for multi-field problems.\n\nconst Re = 10.0\nconv(u,∇u) = Re*(∇u')⋅u\ndconv(du,∇du,u,∇u) = conv(u,∇du)+conv(du,∇u)\n\n# The bilinear form reads\na((u,p),(v,q)) = ∫( ∇(v)⊙∇(u) - (∇⋅v)*p + q*(∇⋅u) )dΩ\n\n# The nonlinear term and its Jacobian are given by\nc(u,v) = ∫( v⊙(conv∘(u,∇(u))) )dΩ\ndc(u,du,v) = ∫( v⊙(dconv∘(du,∇(du),u,∇(u))) )dΩ\n\n# Finally, the Navier-Stokes weak form residual and Jacobian can be defined as\nres((u,p),(v,q)) = a((u,p),(v,q)) + c(u,v)\njac((u,p),(du,dp),(v,q)) = a((du,dp),(v,q)) + dc(u,du,v)\n\n# With the functions `res`, and `jac` representing the weak residual and the Jacobian, we build the nonlinear FE problem:\nop = FEOperator(res,jac,X,Y)\n\n# ## Nonlinear solver phase\n#\n# To finally solve the problem, we consider the same nonlinear solver as previously considered for the  $p$-Laplacian equation.\n\nusing LineSearches: BackTracking\nnls = NLSolver(\n  show_trace=true, method=:newton, linesearch=BackTracking())\nsolver = FESolver(nls)\n\n# In this example, we solve the problem without providing an initial guess (a default one equal to zero will be generated internally)\n\nuh, ph = solve(solver,op)\n\n# Finally, we write the results for visualization (see next figure).\n\nwritevtk(Ωₕ,\"ins-results\",cellfields=[\"uh\"=>uh,\"ph\"=>ph])\n\n# ![](../assets/inc_navier_stokes/ins_solution.png)\n#\n#  ## References\n#\n#  [1] H. C. Elman, D. J. Silvester, and A. J. Wathen. *Finite elements and fast iterative solvers: with applications in incompressible fluid dynamics*. Oxford University Press, 2005.\n", "meta": {"hexsha": "11117b10a5c935b809bb131bf8706ba5b38f1e42", "size": 8617, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/inc_navier_stokes.jl", "max_stars_repo_name": "Alba-Intelligence/Gridap_Tutorials", "max_stars_repo_head_hexsha": "d13de6b3db93fb3b225d5f4cfed564fc7bcca4de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67, "max_stars_repo_stars_event_min_datetime": "2019-08-08T20:10:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:00:31.000Z", "max_issues_repo_path": "src/inc_navier_stokes.jl", "max_issues_repo_name": "Alba-Intelligence/Gridap_Tutorials", "max_issues_repo_head_hexsha": "d13de6b3db93fb3b225d5f4cfed564fc7bcca4de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-08-27T18:03:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T05:50:57.000Z", "max_forks_repo_path": "src/inc_navier_stokes.jl", "max_forks_repo_name": "Alba-Intelligence/Gridap_Tutorials", "max_forks_repo_head_hexsha": "d13de6b3db93fb3b225d5f4cfed564fc7bcca4de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 32, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:14:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:55:28.000Z", "avg_line_length": 53.5217391304, "max_line_length": 671, "alphanum_fraction": 0.6997795056, "num_tokens": 2699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7782814948807361}}
{"text": "# Simulate a Poisson point process on a triangle\n# Author: H. Paul Keeler, 2019.\n# Website: hpaulkeeler.com\n# Repository: github.com/hpaulkeeler/posts\n# For more details, see the post:\n# hpaulkeeler.com/testing-the-julia-language-with-point-process-simulations/\n\n#Note: Need the .+ for adding a scalar to an array\n#Also need . for sqrt, exp, cos, sin etc and assinging scalars to arrays\n#Don't confuse 1.-V with 1 .-V for array V\n#Best to use vectors instead of 1-D matrices eg x=rand(n),  NOT x=rand(n,1).\n\nusing Distributions #for random simulations\nusing Plots #for plotting\n\n#Simulation window parameters -- points A,B,C of a triangle\nxA=0;xB=1;xC=1; #x values of three points\nyA=0;yB=0;yC=1; #y values of three points;\n\n#Point process parameters\nlambda=100; #ntensity (ie mean density) of the Poisson process\n\n#calculate sides of trinagle\na=sqrt((xA-xB)^2+(yA-yB)^2);\nb=sqrt((xB-xC)^2+(yB-yC)^2);\nc=sqrt((xC-xA)^2+(yC-yA)^2);\ns=(a+b+c)/2; #calculate semi-perimeter\n\n#Use Herron's forumula to calculate area\nareaTotal=sqrt(s*(s-a)*(s-b)*(s-c)); #area of triangle\n\n#Simulate a Poisson point process\nnumbPoints=rand(Poisson(areaTotal*lambda)); #Poisson number of points\nU=rand(numbPoints);#uniform random variables\nV=rand(numbPoints);#uniform random variables\n\nxx=sqrt.(U).*xA .+sqrt.(U).*(1 .-V).*xB .+sqrt.(U).*V.*xC;#x coordinates of points\nyy=sqrt.(U).*yA .+sqrt.(U).*(1 .-V).*yB .+sqrt.(U).*V.*yC;#y coordinates of points\n\n#Plotting\nplot1=scatter(xx,yy,xlabel =\"x\",ylabel =\"y\", leg=false);\ndisplay(plot1);\n", "meta": {"hexsha": "eb3907504e18814a43bce5ce61f9b32dc7f9f84a", "size": 1513, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "TestingJulia/PoissonTriangle.jl", "max_stars_repo_name": "hpkeeler/posts", "max_stars_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2020-05-14T12:14:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:22:09.000Z", "max_issues_repo_path": "TestingJulia/PoissonTriangle.jl", "max_issues_repo_name": "hpkeeler/posts", "max_issues_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TestingJulia/PoissonTriangle.jl", "max_forks_repo_name": "hpkeeler/posts", "max_forks_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-10-26T01:22:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T17:33:40.000Z", "avg_line_length": 35.1860465116, "max_line_length": 82, "alphanum_fraction": 0.7144745539, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7782814911647303}}
{"text": "function compute(coins::Vector{Int}, n::Int)::Int\n    combinations = vcat([1], repeat([0], n))\n    for i ∈ 1:length(coins)\n        for j ∈ coins[i] + 1:n + 1\n            combinations[j] += combinations[j - coins[i]]\n        end\n    end\n    return combinations[end]\nend\n", "meta": {"hexsha": "2991e33eb2bafc69817dc1cfcf6646a458d682f9", "size": 269, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/0031/compute.jl", "max_stars_repo_name": "Dynortice/Project-Euler", "max_stars_repo_head_hexsha": "99a0201b5d5f147eab77fc52d9db8995045cded0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/0031/compute.jl", "max_issues_repo_name": "Dynortice/Project-Euler", "max_issues_repo_head_hexsha": "99a0201b5d5f147eab77fc52d9db8995045cded0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/0031/compute.jl", "max_forks_repo_name": "Dynortice/Project-Euler", "max_forks_repo_head_hexsha": "99a0201b5d5f147eab77fc52d9db8995045cded0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9, "max_line_length": 57, "alphanum_fraction": 0.5650557621, "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7782814858018103}}
{"text": "\n\n\n\"\"\"\n\n- `⁺pᵢ` : Particle i at next step\n- `pᵢ`  : Particle i\n- `pⱼ`  : Particle j\n- `ϵ`   : Softening parameter\n\"\"\"\nfunction evaluate_Euler!(⁺aᵢ, pᵢ, pⱼ, ϵ)\n    r = pⱼ.r .- pᵢ.r\n    r⁻³ = (norm(r)^2 + ϵ^2)^(-3/2)\n    \n    @. ⁺aᵢ += G * pⱼ.m * r⁻³ * r\nend\n\n\nfunction evaluate_Euler!(ps, ϵ)\n    for pᵢ in ps\n        pᵢ.a .= 0.\n        for pⱼ in ps\n            pᵢ != pⱼ && evaluate_Euler!(pᵢ.a, pᵢ, pⱼ, ϵ)\n        end\n    end\nend\n\n\nfunction update!(p::AbstractParticle, Δt)\n    @. p.v += p.a * Δt\n    @. p.r += p.v * Δt\nend\n\n\nfunction update!(ps, Δt)\n    for p in ps\n        update!(p, Δt)\n    end\nend\n\n\nfunction run_Euler(ps, params_sim)\n    @unpack ϵ, Δt, t_end = params_sim\n    \n    times = (0:Δt:t_end)\n    ts, rs, vs, as = prep_snapshot(ps, params_sim)\n    \n    for (i, t) in enumerate(times)\n        evaluate_Euler!(ps, ϵ)\n        save_snapshot!(ts, rs, vs, as, i, t, ps, params_sim)\n        update!(ps, Δt)\n    end\n    ts, rs, vs, as\nend\n\n", "meta": {"hexsha": "35f095b5aa033ef3d406b8cccf24df1139515e5c", "size": 945, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/.ipynb_checkpoints/Euler-checkpoint.jl", "max_stars_repo_name": "MasanoriKanamaru/Astroshaper", "max_stars_repo_head_hexsha": "0040c4c9260252859d4ce3225b3e8616258d0a36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2021-05-25T07:22:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T15:42:50.000Z", "max_issues_repo_path": "src/Euler.jl", "max_issues_repo_name": "MasanoriKanamaru/Astroshaper", "max_issues_repo_head_hexsha": "0040c4c9260252859d4ce3225b3e8616258d0a36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Euler.jl", "max_forks_repo_name": "MasanoriKanamaru/Astroshaper", "max_forks_repo_head_hexsha": "0040c4c9260252859d4ce3225b3e8616258d0a36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.875, "max_line_length": 60, "alphanum_fraction": 0.5174603175, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474207360067, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7782595996883115}}
{"text": "## Exercise 2-3\n## Practice using the Julia REPL as a calculator:\n\n## 1. The volume of a sphere with radius r is (4/3)πr^3. What is the volume of a sphere with radius 5?\nprintln(\"Ans 1:\")\nprintln(\"the volume of sphere with radius 5 is: \" * string((4/3) * π * 5 ^ 3))\n\n## 2. Suppose the cover price of a book is $ 24.95, but bookstores get a 40 % discount. Shipping costs $ 3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?\nprintln(\"Ans 2:\")\ncover_price = 24.95\nn_copies = 60\nshipping_cost = 3 + (n_copies - 1) * 0.75\nbooks_price = n_copies * cover_price * 0.6 \ntotal = shipping_cost + books_price\nprintln(total)\n\n## 3. If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?\nprintln(\"Ans 3:\")\neasy_pace_time = 8*60 + 15\ntempo_pace_time = 7*60 + 12\n\ntotal_time = 2 * easy_pace_time + 3 * tempo_pace_time\n\nseconds = total_time % 60\nminutes = total_time ÷ 60\n\n\nprintln(\"you will reach home at 6:52 + \", minutes, \" minutes and \", seconds, \" seconds\")\nprintln(\"End.\")\n", "meta": {"hexsha": "9f1cae84a25db716a155952ef265f0117f5a0ec8", "size": 1152, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter2/ex3.jl", "max_stars_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_stars_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-13T14:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T14:11:30.000Z", "max_issues_repo_path": "Chapter2/ex3.jl", "max_issues_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_issues_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter2/ex3.jl", "max_forks_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_forks_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4, "max_line_length": 212, "alphanum_fraction": 0.7005208333, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474142844408, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7782595944287852}}
{"text": "\"\"\"`care(A, B, Q, R)`\n\nCompute 'X', the solution to the continuous-time algebraic Riccati equation,\ndefined as A'X + XA - (XB)R^-1(B'X) + Q = 0, where R is non-singular.\n\nAlgorithm taken from:\nLaub, \"A Schur Method for Solving Algebraic Riccati Equations.\"\nhttp://dspace.mit.edu/bitstream/handle/1721.1/1301/R-0859-05666488.pdf\n\"\"\"\nfunction care(A, B, Q, R)\n    G = try\n        B*inv(R)*B'\n    catch y\n        if y isa SingularException\n            error(\"R must be non-singular in care.\")\n        else\n            throw(y)\n        end\n    end\n\n    Z = [A  -G;\n        -Q  -A']\n\n    S = schur(Z)\n    S = ordschur(S, real(S.values).<0)\n    U = S.Z\n\n    (m, n) = size(U)\n    U11 = U[1:div(m, 2), 1:div(n,2)]\n    U21 = U[div(m,2)+1:m, 1:div(n,2)]\n    return U21/U11\nend\n\n\"\"\"`dare(A, B, Q, R)`\n\nCompute `X`, the solution to the discrete-time algebraic Riccati equation,\ndefined as A'XA - X - (A'XB)(B'XB + R)^-1(B'XA) + Q = 0, where Q>=0 and R>0\n\nAlgorithm taken from:\nLaub, \"A Schur Method for Solving Algebraic Riccati Equations.\"\nhttp://dspace.mit.edu/bitstream/handle/1721.1/1301/R-0859-05666488.pdf\n\"\"\"\nfunction dare(A, B, Q, R)\n    if (!ishermitian(Q) || minimum(eigvals(real(Q))) < 0)\n        error(\"Q must be positive-semidefinite.\");\n    end\n    if (!isposdef(R))\n        error(\"R must be positive definite.\");\n    end\n    \n    n = size(A, 1);\n    \n    E = [\n        Matrix{Float64}(I, n, n) B/R*B';\n        zeros(size(A)) A'\n    ];\n    F = [\n        A zeros(size(A));\n        -Q Matrix{Float64}(I, n, n)\n    ];\n    \n    QZ = schur(F, E);\n    QZ = ordschur(QZ, abs.(QZ.alpha./QZ.beta) .< 1);\n    \n    return QZ.Z[(n+1):end, 1:n]/QZ.Z[1:n, 1:n];\nend\n\n\"\"\"`dlyap(A, Q)`\n\nCompute the solution `X` to the discrete Lyapunov equation\n`AXA' - X + Q = 0`.\n\"\"\"\nfunction dlyap(A::AbstractMatrix, Q)\n    lhs = kron(A, conj(A))\n    lhs = I - lhs\n    x = lhs\\reshape(Q, prod(size(Q)), 1)\n    return reshape(x, size(Q))\nend\n\n\"\"\"`gram(sys, opt)`\n\nCompute the grammian of system `sys`. If `opt` is `:c`, computes the\ncontrollability grammian. If `opt` is `:o`, computes the observability\ngrammian.\"\"\"\nfunction gram(sys::AbstractStateSpace, opt::Symbol)\n    if !isstable(sys)\n        error(\"gram only valid for stable A\")\n    end\n    func = iscontinuous(sys) ? lyap : dlyap\n    if opt == :c\n        # TODO probably remove type check in julia 0.7.0\n        return func(sys.A, sys.B*sys.B')#::Array{numeric_type(sys),2} # lyap is type-unstable\n    elseif opt == :o\n        return func(Matrix(sys.A'), sys.C'*sys.C)#::Array{numeric_type(sys),2} # lyap is type-unstable\n    else\n        error(\"opt must be either :c for controllability grammian, or :o for\n                observability grammian\")\n    end\nend\n\n\"\"\"`obsv(A, C)` or `obsv(sys)`\n\nCompute the observability matrix for the system described by `(A, C)` or `sys`.\n\nNote that checking for observability by computing the rank from `obsv` is\nnot the most numerically accurate way, a better method is checking if\n`gram(sys, :o)` is positive definite.\"\"\"\nfunction obsv(A::AbstractMatrix, C::AbstractMatrix)\n    T = promote_type(eltype(A), eltype(C))\n    n = size(A, 1)\n    ny = size(C, 1)\n    if n != size(C, 2)\n        throw(ArgumentError(\"C must have the same number of columns as A\"))\n    end\n    res = fill(zero(T), n*ny, n)\n    res[1:ny, :] = C\n    for i=1:n-1\n        res[(1 + i*ny):(1 + i)*ny, :] = res[((i - 1)*ny + 1):i*ny, :] * A\n    end\n    return res\nend\nobsv(sys::StateSpace) = obsv(sys.A, sys.C)\n\n\"\"\"`ctrb(A, B)` or `ctrb(sys)`\n\nCompute the controllability matrix for the system described by `(A, B)` or\n`sys`.\n\nNote that checking for controllability by computing the rank from\n`ctrb` is not the most numerically accurate way, a better method is\nchecking if `gram(sys, :c)` is positive definite.\"\"\"\nfunction ctrb(A::AbstractMatrix, B::AbstractMatrix)\n    T = promote_type(eltype(A), eltype(B))\n    n = size(A, 1)\n    nu = size(B, 2)\n    if n != size(B, 1)\n        throw(ArgumentError(\"B must have the same number of rows as A\"))\n    end\n    res = fill(zero(T), n, n*nu)\n    res[:, 1:nu] = B\n    for i=1:n-1\n        res[:, (1 + i*nu):(1 + i)*nu] = A * res[:, ((i - 1)*nu + 1):i*nu]\n    end\n    return res\nend\nctrb(sys::StateSpace) = ctrb(sys.A, sys.B)\n\n\"\"\"`P = covar(sys, W)`\n\nCalculate the stationary covariance `P = E[y(t)y(t)']` of an lti-model `sys`, driven by gaussian\nwhite noise 'w' of covariance `E[w(t)w(τ)]=W*δ(t-τ)` where δ is the dirac delta.\n\nThe ouput is if Inf if the system is unstable. Passing white noise directly to\nthe output will result in infinite covariance in the corresponding outputs\n(D*W*D' .!= 0) for contunuous systems.\"\"\"\nfunction covar(sys::AbstractStateSpace, W)\n    (A, B, C, D) = (sys.A, sys.B, sys.C, sys.D)\n    if !isa(W, UniformScaling) && (size(B,2) != size(W, 1) || size(W, 1) != size(W, 2))\n        error(\"W must be a square matrix the same size as `sys.B` columns\")\n    end\n    if !isstable(sys)\n        return fill(Inf,(size(C,1),size(C,1)))\n    end\n    func = iscontinuous(sys) ? lyap : dlyap\n    Q = try\n        func(A, B*W*B')\n    catch\n        error(\"No solution to the Lyapunov equation was found in covar\")\n    end\n    P = C*Q*C'\n    if iscontinuous(sys)\n        #Variance and covariance infinite for direct terms\n        directNoise = D*W*D'\n        for i in 1:size(C,1)\n            if directNoise[i,i] != 0\n                P[i,:] .= Inf\n                P[:,i] .= Inf\n            end\n        end\n    else\n        P += D*W*D'\n    end\n    return P\nend\n\ncovar(sys::TransferFunction, W) = covar(ss(sys), W)\n\n\"\"\"\n    covar(C,W)\nIf `C` is a matrix, return CWC'\n\"\"\"\ncovar(C::Union{AbstractMatrix,UniformScaling}, R) = C*R*C'\n\n\n# Note: the H∞ norm computation is probably not as accurate as with SLICOT,\n# but this seems to be still reasonably ok as a first step\n\"\"\"\n`..  norm(sys, p=2; tol=1e-6)`\n\n`norm(sys)` or `norm(sys,2)` computes the H2 norm of the LTI system `sys`.\n\n`norm(sys, Inf)` computes the L∞ norm of the LTI system `sys`.\nThe H∞ norm is the same as the L∞ for stable systems, and Inf for unstable systems.\nIf the peak gain frequency is required as well, use the function `norminf` instead.\n\n`tol` is an optional keyword argument, used only for the computation of L∞ norms.\nIt represents the desired relative accuracy for the computed L∞ norm\n(this is not an absolute certificate however).\n\nsys is first converted to a state space model if needed.\n\nThe L∞ norm computation implements the 'two-step algorithm' in:\nN.A. Bruinsma and M. Steinbuch, 'A fast algorithm to compute the H∞-norm\nof a transfer function matrix', Systems and Control Letters 14 (1990), pp. 287-293.\nFor the discrete-time version, see, e.g.,: P. Bongers, O. Bosgra, M. Steinbuch, 'L∞-norm\ncalculation for generalized state space systems in continuous and discrete time',\nAmerican Control Conference, 1991.\n\"\"\"\nfunction LinearAlgebra.norm(sys::AbstractStateSpace, p::Real=2; tol=1e-6)\n    if p == 2\n        return sqrt(tr(covar(sys, I)))\n    elseif p == Inf\n        if sys.Ts == 0\n            return normLinf_twoSteps_ct(sys,tol)[1]\n        else\n            return normLinf_twoSteps_dt(sys,tol)[1]\n        end\n    else\n        error(\"`p` must be either `2` or `Inf`\")\n    end\nend\n\nfunction LinearAlgebra.norm(sys::TransferFunction, p::Real=2; tol=1e-6)\n    return norm(ss(sys), p, tol=tol)\nend\n\n\"\"\"\n`.. (peakgain, peakgainfrequency) = norminf(sys; tol=1e-6)`\n\nCompute the L∞ norm of the LTI system `sys`, together with the frequency\n`peakgainfrequency` (in rad/TimeUnit) at which the gain achieves its peak value `peakgain`.\nThe H∞ norm is the same as the L∞ for stable systems, and Inf for unstable systems.\n\n`tol` is an optional keyword argument representing the desired relative accuracy for\nthe computed L∞ norm (this is not an absolute certificate however).\n\nsys is first converted to a state space model if needed.\n\nThe L∞ norm computation implements the 'two-step algorithm' in:\nN.A. Bruinsma and M. Steinbuch, 'A fast algorithm to compute the H∞-norm\nof a transfer function matrix', Systems and Control Letters 14 (1990), pp. 287-293.\nFor the discrete-time version, see, e.g.,: P. Bongers, O. Bosgra, M. Steinbuch, 'L∞-norm\ncalculation for generalized state space systems in continuous and discrete time',\nAmerican Control Conference, 1991.\n\"\"\"\nfunction norminf(sys::AbstractStateSpace; tol=1e-6)\n    if sys.Ts == 0\n        return normLinf_twoSteps_ct(sys,tol)\n    else\n        return normLinf_twoSteps_dt(sys,tol)\n    end\nend\n\nfunction norminf(sys::TransferFunction, ; tol=1e-6)\n    return norminf(ss(sys), tol=tol)\nend\n\nfunction normLinf_twoSteps_ct(sys::AbstractStateSpace, tol=1e-6, maxIters=1000, approximag=1e-10)\n    # `maxIters`: the maximum  number of iterations allowed in the algorithm (default 1000)\n    # approximag is a tuning parameter: what does it mean for a number to be on the imaginary axis\n    # Because of this tuning for example, the relative precision that we provide on the norm computation\n    # is not a true guarantee, more an order of magnitude\n    # outputs: pair of Float64, namely L∞ norm approximation and frequency fpeak at which it is achieved\n    T = promote_type(numeric_type(sys), Float64)\n    if sys.nx == 0  # static gain\n        return (svdvals(sys.D)[1], T(0))\n    end\n    p = pole(sys)\n    # Check if there is a pole on the imaginary axis\n    pidx = findfirst(map(x->isapprox(x,0.0),real(p)))\n    if !(pidx isa Nothing)\n        return (T(Inf), imag(p[pidx]))\n        # note: in case of cancellation, for s/s for example, we return Inf, whereas Matlab returns 1\n    else\n        # Initialization: computation of a lower bound from 3 terms\n        lb = maximum(svdvals(sys.D))\n        fpeak = T(Inf)\n        (lb, idx) = findmax([lb, T(maximum((svdvals(evalfr(sys,0)))))]) #TODO remove T() in julia 0.7.0\n        if idx == 2\n            fpeak = T(0)\n        end\n        if isreal(p)  # only real poles\n            omegap = minimum(abs.(p))\n        else  # at least one pair of complex poles\n            tmp = maximum(abs.(imag.(p)./(real.(p).*abs.(p))))\n            omegap = abs(p[argmax(tmp)])    # TODO This is highly suspicious\n        end\n        (lb, idx) = findmax([lb, T(maximum(svdvals(evalfr(sys, omegap*1im))))]) #TODO remove T() in julia 0.7.0\n        if idx == 2\n            fpeak = omegap\n        end\n\n        # Iterations\n        iter = 1;\n        while iter <= maxIters\n            res = (1+2*T(tol))*lb\n            R = sys.D'*sys.D - res^2*I\n            S = sys.D*sys.D' - res^2*I\n            M = sys.A-sys.B*(R\\sys.D')*sys.C\n            H = [         M              -res*sys.B*(R\\sys.B') ;\n                   res*sys.C'*(S\\sys.C)            -M'            ]\n            omegas = eigvals(H) .+ 0im # To make type stable\n            omegaps = imag.(omegas[ (abs.(real.(omegas)).<=approximag) .& (imag.(omegas).>=0) ])\n            sort!(omegaps)\n            if isempty(omegaps)\n                return (1+T(tol))*lb, fpeak\n            else  # if not empty, omegaps contains at least two values\n                ms = [(x+y)/2 for x=omegaps[1:end-1], y=omegaps[2:end]]\n                for mval in ms\n                    (lb, idx) = findmax([lb, T(maximum(svdvals(evalfr(sys,mval*1im))))]) #TODO remove T() in julia 0.7.0\n                    if idx == 2\n                        fpeak = mval\n                    end\n                end\n            end\n            iter += 1\n        end\n        error(\"In norminf: The computation of the H-infinity norm did not converge in $maxIters iterations\")\n    end\nend\n\n# discrete-time version of normHinf_twoSteps_ct above\n# The value fpeak returned by the function is in the range [0,pi)/sys.Ts (in rad/s)\nfunction normLinf_twoSteps_dt(sys::AbstractStateSpace,tol=1e-6, maxIters=1000, approxcirc=1e-8)\n    T = promote_type(numeric_type(sys), Float64)\n    if sys.nx == 0  # static gain\n        return (svdvals(sys.D)[1], T(0))\n    end\n    p = pole(sys)\n    # Check first if there is a pole on the unit circle\n    pidx = findfirst(map(x->isapprox(x,1.0),abs.(p)))\n    if !(pidx isa Nothing)\n        return (T(Inf), angle(p[pidx])/abs(T(sys.Ts)))\n    else\n        # Initialization: computation of a lower bound from 3 terms\n        lb = T(maximum(svdvals(evalfr(sys,1))))  #TODO remove T() in julia 0.7.0\n        fpeak = T(0)\n        (lb, idx) = findmax([lb, T(maximum(svdvals(evalfr(sys,-1))))]) #TODO remove T() in julia 0.7.0\n        if idx == 2\n            fpeak = T(pi)\n        end\n\n        p = p[imag(p).>0]\n        if ~isempty(p)  # not just real poles\n            # find frequency of pôle closest to unit circle\n            omegap = angle(p[findmin(abs.(abs.(p).-1))[2]])\n        else\n            omegap = T(pi)/2\n        end\n        (lb, idx) = findmax([lb, T(maximum(svdvals(evalfr(sys, exp(omegap*1im)))))]) #TODO remove T() in julia 0.7.0\n        if idx == 2\n            fpeak = omegap\n        end\n\n        # Iterations\n        iter = 1;\n        while iter <= maxIters\n            res = (1+2*T(tol))*lb\n            R = res^2*I - sys.D'*sys.D\n            RinvDt = R\\sys.D'\n            L = [ sys.A+sys.B*RinvDt*sys.C  sys.B*(R\\sys.B');\n                  zeros(T, sys.nx,sys.nx)      I]\n            M = [ I                                 zeros(T, sys.nx,sys.nx);\n                  sys.C'*(I+sys.D*RinvDt)*sys.C     L[1:sys.nx,1:sys.nx]']\n            # +0im to make type stable\n            zs = eigvals(L,M) .+ 0im # generalized eigenvalues\n            # are there eigenvalues on the unit circle?\n            omegaps = angle.(zs[ (abs.(abs.(zs).-1) .<= approxcirc) .& (imag(zs).>=0)])\n            sort!(omegaps)\n            if isempty(omegaps)\n                return (1+T(tol))*lb, fpeak/T(sys.Ts)\n            else  # if not empty, omegaps contains at least two values\n                ms = [(x+y)/2 for x=omegaps[1:end-1], y=omegaps[2:end]]\n                for mval in ms\n                    (lb, idx) = findmax([lb, T(maximum(svdvals(evalfr(sys,exp(mval*1im)))))]) #TODO remove T() in julia 0.7.0\n                    if idx == 2\n                        fpeak = mval\n                    end\n                end\n            end\n            iter += 1\n        end\n        error(\"In norminf: The computation of the H-infinity norm did not converge in $maxIters iterations\")\n    end\nend\n\n\n\"\"\"`S, P, B = balance(A[, perm=true])`\n\nCompute a similarity transform `T` resulting in `B = T\\\\A*T` such that the row\nand column norms of `B` are approximately equivalent. If `perm=false`, the\ntransformation will only scale `A` using diagonal `S`, and not permute `A` (i.e., set `P=I`).\"\"\"\nfunction balance(A, perm::Bool=true)\n    n = LinearAlgebra.checksquare(A)\n    B = copy(A)\n    job = perm ? 'B' : 'S'\n    ilo, ihi, scaling = LAPACK.gebal!(job, B)\n\n    S = diagm(0 => scaling)\n    for j = 1:(ilo-1)   S[j,j] = 1 end\n    for j = (ihi+1):n   S[j,j] = 1 end\n\n    P = Matrix{Int}(I,n,n)\n    if perm\n        if ilo > 1\n            for j = (ilo-1):-1:1 cswap!(j, round(Int, scaling[j]), P) end\n        end\n        if ihi < n\n            for j = (ihi+1):n    cswap!(j, round(Int, scaling[j]), P) end\n        end\n    end\n    return S, P, B\nend\n\nfunction cswap!(i::Integer, j::Integer, X::StridedMatrix)\n    for k = 1:size(X,1)\n        X[i, k], X[j, k] = X[j, k], X[i, k]\n    end\nend\n\n\n\n\"\"\"\n`sysr, G = balreal(sys::StateSpace)`\n\nCalculates a balanced realization of the system sys, such that the observability and reachability gramians of the balanced system are equal and diagonal `G`\n\nSee also `gram`, `baltrunc`\n\nGlad, Ljung, Reglerteori: Flervariabla och Olinjära metoder\n\"\"\"\nfunction balreal(sys::ST) where ST <: AbstractStateSpace\n    P = gram(sys, :c)\n    Q = gram(sys, :o)\n\n    Q1 = try\n        cholesky(Hermitian(Q)).U\n    catch\n        throw(ArgumentError(\"Balanced realization failed: Observability grammian not positive definite, system needs to be observable\"))\n    end\n    U,Σ,V = svd(Q1*P*Q1')\n    Σ .= sqrt.(Σ)\n    Σ1 = diagm(0 => sqrt.(Σ))\n    T = Σ1\\(U'Q1)\n\n    Pz = T*P*T'\n    Qz = inv(T')*Q*inv(T)\n    if norm(Pz-Qz) > sqrt(eps())\n        @warn(\"balreal: Result may be inaccurate\")\n        println(\"Controllability gramian before transform\")\n        display(P)\n        println(\"Controllability gramian after transform\")\n        display(Pz)\n        println(\"Observability gramian before transform\")\n        display(Q)\n        println(\"Observability gramian after transform\")\n        display(Qz)\n        println(\"Singular values of PQ\")\n        display(Σ)\n    end\n\n    sysr = ST(T*sys.A/T, T*sys.B, sys.C/T, sys.D, sys.Ts), diagm(0 => Σ)\nend\n\n\n\"\"\"\n`sysr, G = baltrunc(sys::StateSpace, atol = √ϵ, rtol=1e-3, unitgain=true)`\n\nReduces the state dimension by calculating a balanced realization of the system sys, such that the observability and reachability gramians of the balanced system are equal and diagonal `G`, and truncating it such that all states corresponding to singular values less than `atol` and less that `rtol σmax` are removed. If `unitgain=true`, the matrix `D` is chosen such that unit static gain is achieved.\n\nSee also `gram`, `balreal`\n\nGlad, Ljung, Reglerteori: Flervariabla och Olinjära metoder\n\"\"\"\nfunction baltrunc(sys::ST; atol = sqrt(eps()), rtol = 1e-3, unitgain = true) where ST <: AbstractStateSpace\n    sysbal, S = balreal(sys)\n    S = diag(S)\n    S = S[S .>= atol]\n    S = S[S .>= S[1]*rtol]\n    n = length(S)\n    A = sysbal.A[1:n,1:n]\n    B = sysbal.B[1:n,:]\n    C = sysbal.C[:,1:n]\n    D = sysbal.D\n    if unitgain\n        D = D/(C*inv(-A)*B)\n    end\n\n    return ST(A,B,C,D,sys.Ts), diagm(0 => S)\nend\n\n\"\"\"\n    syst = similarity_transform(sys, T)\nPerform a similarity transform `T : Tx̃ = x` on `sys` such that\n```\nÃ = T⁻¹AT\nB̃ = T⁻¹ B\nC̃ = CT\nD̃ = D\n```\n\"\"\"\nfunction similarity_transform(sys::ST, T) where ST <: AbstractStateSpace\n    Tf = factorize(T)\n    A = Tf\\sys.A*T\n    B = Tf\\sys.B\n    C = sys.C*T\n    D = sys.D\n    ST(A,B,C,D,sys.Ts)\nend\n\n\"\"\"\nsysi = innovation_form(sys, R1, R2)\nsysi = innovation_form(sys; sysw=I, syse=I, R1=I, R2=I)\n\nTakes a system\n```\nx' = Ax + Bu + w ~ R1\ny  = Cx + e ~ R2\n```\nand returns the system\n```\nx' = Ax + Kv\ny  = Cx + v\n```\nwhere `v` is the innovation sequence.\n\nIf `sysw` (`syse`) is given, the covariance resulting in filtering noise with `R1` (`R2`) through `sysw` (`syse`) is used as covariance.\n\nSee Stochastic Control, Chapter 4, Åström\n\"\"\"\nfunction innovation_form(sys::ST, R1, R2) where ST <: AbstractStateSpace\n    K = kalman(sys, R1, R2)\n    ST(sys.A, K, sys.C, Matrix{eltype(sys.A)}(I, sys.ny, sys.ny), sys.Ts)\nend\n# Set D = I to get transfer function H = I + C(sI-A)\\ K\nfunction innovation_form(sys::ST; sysw=I, syse=I, R1=I, R2=I) where ST <: AbstractStateSpace\n\tK = kalman(sys, covar(sysw,R1), covar(syse, R2))\n\tST(sys.A, K, sys.C, Matrix{eltype(sys.A)}(I, sys.ny, sys.ny), sys.Ts)\nend\n", "meta": {"hexsha": "b41ae152c138eb45dc7a48cbcfb6e8d43b25a57c", "size": 18646, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix_comps.jl", "max_stars_repo_name": "phelipe/ControlSystems.jl", "max_stars_repo_head_hexsha": "1e113caaa1a1253875bb5563e49a2889d9034d9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matrix_comps.jl", "max_issues_repo_name": "phelipe/ControlSystems.jl", "max_issues_repo_head_hexsha": "1e113caaa1a1253875bb5563e49a2889d9034d9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix_comps.jl", "max_forks_repo_name": "phelipe/ControlSystems.jl", "max_forks_repo_head_hexsha": "1e113caaa1a1253875bb5563e49a2889d9034d9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9018181818, "max_line_length": 402, "alphanum_fraction": 0.5980907433, "num_tokens": 5872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474194456935, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7782595943509192}}
{"text": "using DifferentialEquations\nusing Plots\n\n\nfunction seir_ode(dY,Y,p,t)\n dY[1] = p[4]-p[1]*Y[1]*Y[3]-p[4]*Y[1]\n dY[2] = p[1]*Y[1]*Y[3]-(p[2]+p[4])*Y[2]\n dY[3] = p[2]*Y[2] - (p[3]+p[4])*Y[3]\nend\n\npar=[520/365,1/60,1/30,774835/(65640000*365)]\ninit=[0.8,0.1,0.1]\ntspan=(0.0,365.0)\n\nseir_prob = ODEProblem(seir_ode,init,tspan,par)\n\nsol=solve(seir_prob);\n\n# Plot\nR=ones(1,size(sol,2))-sum(sol,1);\n\nplot(sol.t,[sol',R'],xlabel=\"Time\",ylabel=\"Proportion\")\n", "meta": {"hexsha": "3140fae74eb94d1bdf4afcac3a29a13ed40d9b75", "size": 447, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/simple_deterministic_models/seir/seir.jl", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/simple_deterministic_models/seir/seir.jl", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/simple_deterministic_models/seir/seir.jl", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 19.4347826087, "max_line_length": 55, "alphanum_fraction": 0.615212528, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474155747541, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.778259593337947}}
{"text": "# Represent as a permtuation matrix.\n\"\"\"\n    Matrix(p::Permutation)\n\nReturn the permutation matrix for `p`.\n\"\"\"\nfunction Matrix{T}(p::Permutation) where {T}\n    n = length(p)\n    A = Matrix{T}(I, n, n)     # A = eye(T,n)   #  int(eye(n))\n    return A[:, p.data]\nend\n\nMatrix(p::Permutation) = Matrix{Int}(p)\nArray(p::Permutation) = Matrix(p)\nAbstractMatrix(p::Permutation) = Matrix(p)\nAbstractArray(p::Permutation) = Matrix(p)\n\nArray{T}(p::Permutation) where {T} = Matrix{T}(p)\nAbstractMatrix{T}(p::Permutation) where {T} = Matrix{T}(p)\nAbstractArray{T}(p::Permutation) where {T} = Matrix{T}(p)\n\n\nfunction Permutation(M::Matrix)\n    n, c = size(M)\n    @assert n == c \"Matrix must be square\"\n    v = [findfirst(Bool.(M[:, k])) for k = 1:n]\n    return Permutation(v)\nend\n", "meta": {"hexsha": "c3d6c319243cf0c3380d51f945b1970b7b5ce5b5", "size": 768, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix.jl", "max_stars_repo_name": "scheinerman/Permutations.jl", "max_stars_repo_head_hexsha": "1a1accf58669ae84e00b6491748c8e1c2db4e477", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2015-06-19T16:01:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T15:12:24.000Z", "max_issues_repo_path": "src/matrix.jl", "max_issues_repo_name": "scheinerman/Permutations.jl", "max_issues_repo_head_hexsha": "1a1accf58669ae84e00b6491748c8e1c2db4e477", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2015-11-20T17:57:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T19:40:41.000Z", "max_forks_repo_path": "src/matrix.jl", "max_forks_repo_name": "scheinerman/Permutations.jl", "max_forks_repo_head_hexsha": "1a1accf58669ae84e00b6491748c8e1c2db4e477", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2015-04-27T21:16:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T12:14:12.000Z", "avg_line_length": 26.4827586207, "max_line_length": 62, "alphanum_fraction": 0.63671875, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7782215928633341}}
{"text": "\"\"\"\n    owens_t(x, a)\n\nOwen's T function\n\nPorted from Matlab implementation of John Burkardt, which is distributed under the GNU LGPL license.\n\nReference:\n    MA Porter, DJ Winstanley, Remark AS R30: A Remark on Algorithm AS76: An Integral Useful in \n    Calculating Noncentral T and Bivariate Normal Probabilities, Applied Statistics, Volume 28, \n    Number 1, 1979, page 113.\n\n    JC Young, Christoph Minder, Algorithm AS 76: An Algorithm Useful in Calculating Non-Central T and\n    Bivariate Normal Distributions, Applied Statistics, Volume 23, Number 3, 1974, pages 455-457.\n\"\"\"\nfunction owens_t(x::Real, a::Real)\n    ng = 5\n    r = [0.1477621, 0.1346334, 0.1095432, 0.0747257, 0.0333357]\n    tp = 0.159155\n    tv1 = 1.0E-35\n    tv2 = 15.0\n    tv3 = 15.0\n    tv4 = 1.0E-05\n    u = [0.0744372, 0.2166977, 0.3397048, 0.4325317, 0.4869533]\n    # Test for X near zero.\n    if abs(x) < tv1\n        return tp * atan(a)\n    end\n    # Test for large values of abs(X).\n    if tv2 < abs(x)\n        return 0.\n    end\n    # Test for `a` near zero.\n    if abs(a) < tv1\n        return 0.\n    end\n    # Test whether abs(`a`) is so large that it must be truncated.\n    xs = -0.5 * x * x\n    x2 = a\n    fxs = a * a\n    #  Computation of truncation point by Newton iteration.  \n    if tv3 <= log(1.0 + fxs) - xs * fxs\n        x1 = 0.5 * a\n        fxs = 0.25 * fxs\n        while true\n            rt = fxs + 1.\n            x2 = x1 + (xs * fxs + tv3 - log(rt)) / (2. * x1 * ( 1. / rt - xs))\n            fxs = x2 * x2\n            if abs(x2 - x1) < tv4\n                break\n            end\n            x1 = x2\n        end\n    end\n    # Gaussian quadrature.\n    rt = 0.0\n    for i in 1:ng\n        r1 = 1.0 + fxs * (0.5 + u[i])^2\n        r2 = 1.0 + fxs * (0.5 - u[i])^2\n        rt = rt + r[i] * (exp(xs * r1) / r1 + exp(xs * r2) / r2)\n    end\n    return rt * x2 * tp\nend\n", "meta": {"hexsha": "fb99ffc8f8c032a8e20a0bec2e04ae45e3234ba3", "size": 1851, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/owens_t.jl", "max_stars_repo_name": "ohmsweetohm1/SpecialFunctions.jl", "max_stars_repo_head_hexsha": "225521a95a65f1c5a395e0f39fa4613ca5eb55d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/owens_t.jl", "max_issues_repo_name": "ohmsweetohm1/SpecialFunctions.jl", "max_issues_repo_head_hexsha": "225521a95a65f1c5a395e0f39fa4613ca5eb55d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/owens_t.jl", "max_forks_repo_name": "ohmsweetohm1/SpecialFunctions.jl", "max_forks_repo_head_hexsha": "225521a95a65f1c5a395e0f39fa4613ca5eb55d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.921875, "max_line_length": 101, "alphanum_fraction": 0.547271745, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7782215909555346}}
{"text": "# functions to create regular polygons\n\nexport equilateral, equiangular\n\n\n\n\"\"\"\n`_solver(f,goal,lo,hi)` assumes `f` is increasing on the interval `[lo,hi]`\n\"\"\"\nfunction _solver(f::Function, goal::Real, lo::Real, hi::Real)\n    mid = (hi+lo)/2\n    y = f(mid)\n\n    if abs(y-goal) <= THRESHOLD*eps(1.0)\n        return mid\n    end\n    if y > goal\n        return _solver(f,goal,lo,mid)\n    end\n    return _solver(f,goal,mid,hi)\nend\n\n\"\"\"\n`_solver(f,goal)` assumes that `f` is increasing and there is a nonnegative `x`\nso that `f(x)==goal`.\n\"\"\"\nfunction _solver(f::Function, goal::Real)\n    x::Float64 = 1.0\n    while f(x) < goal\n        x *= 2.0\n    end\n    _solver(f,goal,0,x)\nend\n\n\n\n\"\"\"\n`equilateral(n,s)` creates a regular `n`-gon with side lengths `s`\ncentered at the origin. First point is on the positive x-axis.\n\"\"\"\nfunction equilateral(n::Int, s::Real)\n    @assert n>2 \"Number of sides must be at least 3\"\n    @assert s>0 \"Side length must be positive\"\n\n    tlist = [ k*2*pi/n for k=0:n-1 ]   # list of angles\n    t = tlist[2]\n\n    f(x)  = dist(HPoint(x,0), HPoint(x,t))\n    r = _solver(f,s)\n\n\n    pts = [ HPoint(r,theta) for theta in tlist]\n\n    return HPolygon(pts)\nend\n\n\"\"\"\n`equiangular(n,theta)` creates a regular `n`-gon where the vertex\nangles equal `theta`\n\"\"\"\nfunction equiangular(n::Int, theta::Real)\n    @assert n>2 \"Number of sides must be at least 3\"\n    if theta < 0\n        theta = -theta\n    end\n    @assert theta!=0 \"Angle cannot be zero\"\n\n    tmax = (n-2)*pi/n\n    @assert theta<tmax \"Angle must be less than $(n-2)*pi/$n = $tmax\"\n\n    tlist = [ k*2*pi/n for k=0:n-1 ]   # list of angles\n    t = tlist[2]\n\n    f(x) = -angle(HPoint(x,0), HPoint(x,t), HPoint(x,2t))\n    r = _solver(f,-theta)\n\n    pts = [ HPoint(r,theta) for theta in tlist]\n\n    return HPolygon(pts)\n\nend\n", "meta": {"hexsha": "7bf5d7828dc7d9787e174b6c58fee6dd43899771", "size": 1787, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/regular.jl", "max_stars_repo_name": "switzel/HyperbolicPlane.jl", "max_stars_repo_head_hexsha": "89ba26e080b520b4f200e985f2b431b1d61ecb21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-01-19T06:12:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T22:18:48.000Z", "max_issues_repo_path": "src/regular.jl", "max_issues_repo_name": "switzel/HyperbolicPlane.jl", "max_issues_repo_head_hexsha": "89ba26e080b520b4f200e985f2b431b1d61ecb21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-01-31T08:33:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T19:44:39.000Z", "max_forks_repo_path": "src/regular.jl", "max_forks_repo_name": "switzel/HyperbolicPlane.jl", "max_forks_repo_head_hexsha": "89ba26e080b520b4f200e985f2b431b1d61ecb21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-31T21:10:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T18:49:43.000Z", "avg_line_length": 21.7926829268, "max_line_length": 79, "alphanum_fraction": 0.6094012311, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7782215903190899}}
{"text": "\"\"\"\n    ifft_times(fs)\n\n    Returns an array of DFT time points associated with the set of\n    frequency-domain points.\n\n    Assumes unit of argument `x` is Hz (not rad/sec). Output unit is in s.\n\"\"\"\nfunction ifft_times(fs)\n    deltaf = fs[2]-fs[1]\n    N = Int(length(fs))\n    if N%2 == 0\n        delta_t = 1/(-2*fs[1])\n    else\n        delta_t = 1/(2*fs[end]+deltaf)\n    end\n    ts = (0:N-1)*delta_t\n    return ts\nend\n", "meta": {"hexsha": "b93d24f0cf43827215c28672b441e52e9be0c629", "size": 419, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ifft_times.jl", "max_stars_repo_name": "fuzzybear3965/CircuitSimulation.jl", "max_stars_repo_head_hexsha": "48a09cc6b22973b3a2ed7fe49467ce67bcbca5cb", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-27T02:40:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-27T02:40:07.000Z", "max_issues_repo_path": "src/ifft_times.jl", "max_issues_repo_name": "fuzzybear3965/CircuitSimulation.jl", "max_issues_repo_head_hexsha": "48a09cc6b22973b3a2ed7fe49467ce67bcbca5cb", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ifft_times.jl", "max_forks_repo_name": "fuzzybear3965/CircuitSimulation.jl", "max_forks_repo_head_hexsha": "48a09cc6b22973b3a2ed7fe49467ce67bcbca5cb", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.95, "max_line_length": 74, "alphanum_fraction": 0.584725537, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7782215887295129}}
{"text": "export calc_k, calc_λ, calc_κ\nexport calc_NA\nexport fresnel_number\n\n\"\"\"\n    calc_NA(focal_length, diameter[, n])\n\nCalculate the numerical aperture of a system with `focal_length` \nand `diameter` of the lens. Per default `n=1` is the refractive index.\n\n # Examples\n```julia-repl\njulia> calc_NA(100e-3, 200e-3)\n1.0\n\njulia> calc_NA(100e-3, 200e-3, 1.33)\n1.33\n```\n\"\"\"\nfunction calc_NA(focal_length, diameter, n=1)\n    return n * diameter / 2 / focal_length\nend\n\n\n\"\"\"\n    calc_k(λ, n=1)\n\nCalculate the value of the (angular) wave number with vacuum wavelength `λ` in\nmedium with refractive index `n`.\nIt holds: \\$ k = \\\\kappa \\\\cdot 2 \\\\pi \\$\n\"\"\"\nfunction calc_k(λ, n=1)\n    return 2 * oftype(λ, π) * n / λ\nend\n\n\"\"\"\n    calc_κ(λ, n=1)\n\nCalculate the value of the (non angular) wave number with vacuum wavelength `λ` in\nmedium with refractive index `n`.\nIt holds: \\$ \\\\kappa = \\\\frac{k}{2 \\\\pi} \\$\n\"\"\"\nfunction calc_κ(λ, n=1)\n    return calc_k(λ, n) / 2 / oftype(λ, π)\nend\n\n\n\"\"\"\n    calc_λ(k, n=1)\n\nCalculate the vacuum wavelength `λ` from the angular wave number `k` in \nmedium with refractive index `n`.\nIt holds: \\$ \\\\lambda = \\\\frac{n \\\\cdot 2 \\\\pi}{k} \\$\n\"\"\" \nfunction calc_λ(k, n=1)\n    return 2 * oftype(k, π) * n / k\nend\n\n\n\"\"\"\n    fresnel_number(a, L, λ=λ0)\n\nCalculate the Fresnel number where `a` is the characteristic size,\n`L` the distance from screen to aperture and `λ` the wavelength.\n\"\"\"\nfunction fresnel_number(a, L, λ=λ0)\n    return a^2 / L / λ\nend\n", "meta": {"hexsha": "1c29a05321e4b7daea739e2941ac03f40270b591", "size": 1460, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/physical_conversions.jl", "max_stars_repo_name": "JuliaPhysics/PhysicalOptics", "max_stars_repo_head_hexsha": "47efb1d816756fe7ea57b01061776cad8dbe47c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2020-11-04T11:52:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T10:13:22.000Z", "max_issues_repo_path": "src/physical_conversions.jl", "max_issues_repo_name": "JuliaPhysics/PhysicalOptics", "max_issues_repo_head_hexsha": "47efb1d816756fe7ea57b01061776cad8dbe47c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-01-06T12:58:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T13:48:37.000Z", "max_forks_repo_path": "src/physical_conversions.jl", "max_forks_repo_name": "JuliaPhysics/PhysicalOptics", "max_forks_repo_head_hexsha": "47efb1d816756fe7ea57b01061776cad8dbe47c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-05T09:40:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T23:19:30.000Z", "avg_line_length": 21.1594202899, "max_line_length": 82, "alphanum_fraction": 0.6582191781, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.7782215814165366}}
{"text": "function higibbs(Y, T, mu0 = 50.0, gamma20 = 25.0, nu0 = 1.0, sigma2 = 100.0, eta0 = 1.0, tau20 = 100.0)\r\n    m = size(unique(Y[:,1]), 1)\r\n    # starting value\r\n    ybar = ones(m)\r\n    sv = ones(m)\r\n    n = ones(m)\r\n    for j = 1:m\r\n        yj = Y[ [Y[i,1] == j for i = 1:end], 2]\r\n        ybar[j] = mean(yj)\r\n        sv[j] = var(yj)\r\n        n[j] = size(yj, 1)\r\n    end\r\n    theta = ybar\r\n    sigma2 = mean(sv)\r\n    mu = mean(theta)\r\n    tau2 = var(theta)\r\n\r\n    THETA = ones(T, m)\r\n    # sigma2 mu tau2 \r\n    SMT = ones(T, 3)\r\n\r\n    for t = 1:T        \r\n        # sample theta\r\n        for j = 1:m\r\n            vartheta = 1 / (n[j] / sigma2 + 1 / tau2)\r\n            meantheta = vartheta * ( n[j] * ybar[j]) / sigma2 + mu / tau2) \r\n            rnorm = Normal(meantheta, sqrt(vartheta))\r\n            theta[j] = rand(rnorm, 1)[1]\r\n        end\r\n        THETA[t, :] .= theta\r\n        \r\n        # sample new sigma2\r\n        nun = nu0 + sum(n)\r\n        ss = nu0 * s20\r\n        for j = 1:m\r\n            ss += sum((Y[ [Y[i, 1] == j for i = 1:end], 2] .- theta[j]).^2)\r\n        end  \r\n        rgamma = Gamma(nun/2, 2/ss)\r\n        sigma2 = 1 / rand(rgamma, 1)[1]\r\n\r\n        # sample mu\r\n        varmu = 1 / (m / tau2 + 1 / gamma20)\r\n        meanmu = varmu * (m * mean(theta) / tau2 + mu0 / gamma20)\r\n        rnorm = Normal(meanmu, sqrt(varmu))\r\n        mu = rand(rnorm, 1)[1]\r\n\r\n        # sample 1/tau2\r\n        shapetau = (eta0 + m) / 2\r\n        ratetau = ( eta0 * tau20 + sum((theta .- mu).^2) ) / 2\r\n        rgamma = Gamma(shapetau, 1/ratetau)\r\n        tau2 = 1 / rand(rgamma, 1)[1]\r\n                \r\n        # store results\r\n        SMT[t, :] .= [sigma2, mu, tau2]\r\n    end\r\n    return THETA, SMT\r\nend\r\n\r\n# run\r\nY = readdlm(\"math-score-Y.csv\")\r\nTHETA, SMT = higibbs(Y, 5000)\r\n", "meta": {"hexsha": "d464ed8bfebd04586a0f6940346fac0d55e286bd", "size": 1772, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Gibbs/group-comparison.jl", "max_stars_repo_name": "szcf-weiya/MCMC", "max_stars_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-07-19T12:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T08:06:50.000Z", "max_issues_repo_path": "Gibbs/group-comparison.jl", "max_issues_repo_name": "szcf-weiya/MCMC", "max_issues_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-02-03T15:08:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-05T15:41:39.000Z", "max_forks_repo_path": "Gibbs/group-comparison.jl", "max_forks_repo_name": "szcf-weiya/MCMC", "max_forks_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-07-19T12:50:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T08:06:52.000Z", "avg_line_length": 28.5806451613, "max_line_length": 105, "alphanum_fraction": 0.4401805869, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7782190869913546}}
{"text": "function FPU(omega)\n\n# returns functions for the fast potential, the slow potential, kineticTerm, Lagragian, Hamiltonian and Oscillatory Energy\n# of the FPUT problem, when provided with the stiffness parameter omega\n\n# FPUT problem: see I.5.1 A Fermi–Pasta–Ulam Problem in Geometric Numerical Integration by Hairer, Lubich, Wanner (2006)\n    \n    function fastPotential(qf)\n    omega^2/2*sum(qf.^2)\n    end\n\n    function slowPotential(qs,qf)\n        qd= qs-qf\n        1/4*(qd[1]^4 + sum((qd[2:end]-qs[1:end-1]-qf[1:end-1]).^4) + qd[end]^4)\n    end\n\n    function kineticTerm(qsdot,qfdot)\n        1/2*(sum(qsdot.^2)+sum(qfdot.^2))\n    end\n\n    function L(qs,qf,qsdot,qfdot)\n        kineticTerm(qsdot,qfdot)-slowPotential(qs,qf)-fastPotential(qf)\n    end\n\n    function Hamiltonian(qs,qf,qsdot,qfdot)\n        kineticTerm(qsdot,qfdot)+slowPotential(qs,qf)+fastPotential(qf)\n    end\n    \n    function OscillatoryEnergy(qf,pf)\n    # adiabatic invariant\n        return sum(1/2*(pf.^2 .+omega^2*qf.^2),dims=1)\n    end\n    \n    \n    return fastPotential, slowPotential, kineticTerm, L, Hamiltonian, OscillatoryEnergy\n    \nend\n\n", "meta": {"hexsha": "89c76dcc72923b2b028cf6911cef0d03a0f16c4f", "size": 1117, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "FPU_setup.jl", "max_stars_repo_name": "Christian-Offen/MultiRate", "max_stars_repo_head_hexsha": "2cb2fd57d50acbed10bdeda7ce8e72a0769d5c98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FPU_setup.jl", "max_issues_repo_name": "Christian-Offen/MultiRate", "max_issues_repo_head_hexsha": "2cb2fd57d50acbed10bdeda7ce8e72a0769d5c98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FPU_setup.jl", "max_forks_repo_name": "Christian-Offen/MultiRate", "max_forks_repo_head_hexsha": "2cb2fd57d50acbed10bdeda7ce8e72a0769d5c98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.641025641, "max_line_length": 122, "alphanum_fraction": 0.6732318711, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632234212402, "lm_q2_score": 0.8175744850834649, "lm_q1q2_score": 0.7782190847585075}}
{"text": "\nusing ModelingToolkit\nusing DiffEqJump\nusing Random\nusing DataFrames\nusing Tables\nusing StatsPlots\nusing BenchmarkTools\n\n\n@parameters β c γ\n@variables t S(t) I(t) R(t)\nN = S+I+R\nrate₁   = β*c*S*I/N\naffect₁ = [S ~ S - 1, I ~ I + 1]\nrate₂   = γ*I\naffect₂ = [I ~ I - 1, R ~ R + 1]\nj₁      = ConstantRateJump(rate₁,affect₁)\nj₂      = ConstantRateJump(rate₂,affect₂)\n@named sir_js = JumpSystem([j₁,j₂], t, [S,I,R], [β,c,γ])\n\n\ntmax = 40.0\ntspan = (0.0,tmax)\nδt = 1.0;\n\n\nu0 = [S => 990, I => 10, R => 0];\n\n\np = [β => 0.05, c => 10.0, γ => 0.25];\n\n\nRandom.seed!(1234);\n\n\nsir_dprob = DiscreteProblem(sir_js, u0, tspan,p);\n\n\nsir_jprob = JumpProblem(sir_js, sir_dprob,Direct());\n\n\nsol_jump = solve(sir_jprob,SSAStepper());\n\n\nout_jump = sol_jump(0:δt:tmax);\n\n\ndf_jump = DataFrame(Tables.table(out_jump'))\nrename!(df_jump,[\"S\",\"I\",\"R\"])\ndf_jump[!,:t] = out_jump.t;\n\n\n@df df_jump plot(:t,\n    [:S :I :R],\n    xlabel=\"Time\",\n    ylabel=\"Number\")\n\n\n@benchmark solve(sir_jprob,SSAStepper())\n\n", "meta": {"hexsha": "15654c17fab24c764646c4e2233c48f16e0e6466", "size": 976, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/jump_process_mtk/jump_process_mtk.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/jump_process_mtk/jump_process_mtk.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/jump_process_mtk/jump_process_mtk.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.7419354839, "max_line_length": 56, "alphanum_fraction": 0.6229508197, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037732, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7781867821709287}}
{"text": "using CompEcon\nusing Dierckx\nusing Statistics\n\n# Create functions to test against\nf1(x) = sin.(x)\nfp1(x) = cos.(x)\nf2(x) = exp.(x)\nfp2(x) = exp.(x)\nf3(x) = 1.5 .+ log.(x)\nfp3(x) = 1.0 ./ x\nfs = [f1, f2, f3]\nfps = [fp1, fp2, fp3]\nnf = length(fs)\n\nx = collect(range(.5; stop=2, length=35))\nfinex = collect(range(1e-2; stop=2*pi - 1e-2, length=150))\nys = map(f->f(x), fs)\nfiney = map(f->f(finex), fs)\n\nfunction compare_D_CE_levels(f::Function, x::Array{Float64, 1}, order::Int)\n\n    # Create Dierckx Spline (and data)\n    n = length(x)\n    y = f(x)\n    dspl = Spline1D(x, y; s=0., k=order)\n\n    # Create CompEcon Spline (and data)\n    cebasis = Basis(SplineParams(x, 0, order))\n    xx = nodes(cebasis)[1]\n    yy = f(xx)\n    c, bs = funfitxy(cebasis, xx, yy)\n\n    # Evaluate Splines on finer grid\n    xfine = collect(range(x[1]; stop=x[end], length=2*n + 1))\n    yfine = f(xfine)\n\n    deval = Dierckx.evaluate(dspl, xfine)\n    derr = abs.(yfine - deval)\n\n    ceeval = CompEcon.funeval(c, cebasis, xfine)\n    ceerr = abs.(yfine - ceeval)\n\n    # # Evaluate Derivative\n    # dderiv1 = Dierckx.derivative(dspl1, finex)\n    # cederiv1 = CompEcon.evaluate(ceinterp1, finex, order=1)\n\n    return derr, ceerr\nend\n\nfunction compare_D_CE_deriv(f::Function, fp::Function, x::Array{Float64, 1}, order::Int)\n\n    # Create Dierckx Spline (and data)\n    n = length(x)\n    y = f(x)\n    dspl = Spline1D(x, y; s=0., k=order)\n\n    # Create CompEcon Spline (and data)\n    cebasis = Basis(SplineParams(x, 0, order))\n    xx = nodes(cebasis)[1]\n    yy = f(xx)\n    c, bs = funfitxy(cebasis, xx, yy)\n\n    # Evaluate Splines on finer grid\n    xfine = collect(range(x[1]; stop=x[end], length=2*n + 1))\n    ypfine = fp(xfine)\n\n    devalderiv = Dierckx.derivative(dspl, xfine)\n    derr = abs.(ypfine - devalderiv)\n\n    ceevalderiv = funeval(c, cebasis, xfine, ones(Int64, 1,1))\n    ceerr = abs.(ypfine .- ceevalderiv)\n\n    return derr, ceerr\nend\n\n\nfor i=1:nf\n\n    curr_f, curr_fp = fs[i], fps[i]\n\n    derr1_levels, ceerr1_levels = compare_D_CE_levels(curr_f, x, 1)\n    derr2_levels, ceerr2_levels = compare_D_CE_levels(curr_f, x, 2)\n    derr3_levels, ceerr3_levels = compare_D_CE_levels(curr_f, x, 3)\n\n    # derr1_deriv, ceerr1_deriv = compare_D_CE_deriv(curr_f, curr_fp, x, 1)\n    derr2_deriv, ceerr2_deriv = compare_D_CE_deriv(curr_f, curr_fp, x, 2)\n    derr3_deriv, ceerr3_deriv = compare_D_CE_deriv(curr_f, curr_fp, x, 3)\n\n    println(\"\\nLinear Approximation to Function\\n\")\n    println(\"Dierckx Level Errors \\n\\t Max: $(maximum(derr1_levels)) \\n\\t Min: $(minimum(derr1_levels)) \\n\\t Mean: $(mean(derr1_levels))\")\n    # println(\"Dierckx Deriv Errors \\n\\t Max: $(maximum(derr1_deriv)) \\n\\t Min: $(minimum(derr1_deriv)) \\n\\t Mean: $(mean(derr1_deriv))\")\n    println(\"CompEcon Level Errors \\n\\t Max: $(maximum(ceerr1_levels)) \\n\\t Min: $(minimum(ceerr1_levels)) \\n\\t Mean: $(mean(ceerr1_levels))\")\n    # println(\"CompEcon Deriv Errors \\n\\t Max: $(maximum(ceerr1_deriv)) \\n\\t Min: $(minimum(ceerr1_deriv)) \\n\\t Mean: $(mean(ceerr1_deriv))\")\n\n    println(\"\\n\\nQuadratic Approximation to Function\\n\")\n    println(\"Dierckx Level Errors \\n\\t Max: $(maximum(derr2_levels)) \\n\\t Min: $(minimum(derr2_levels)) \\n\\t Mean: $(mean(derr2_levels))\")\n    println(\"Dierckx Deriv Errors \\n\\t Max: $(maximum(derr2_deriv)) \\n\\t Min: $(minimum(derr2_deriv)) \\n\\t Mean: $(mean(derr2_deriv))\")\n    println(\"CompEcon Level Errors \\n\\t Max: $(maximum(ceerr2_levels)) \\n\\t Min: $(minimum(ceerr2_levels)) \\n\\t Mean: $(mean(ceerr2_levels))\")\n    println(\"CompEcon Deriv Errors \\n\\t Max: $(maximum(ceerr2_deriv)) \\n\\t Min: $(minimum(ceerr2_deriv)) \\n\\t Mean: $(mean(ceerr2_deriv))\")\n\n    println(\"\\n\\nCubic Approximation to Function\\n\")\n    println(\"Dierckx Level Errors \\n\\t Max: $(maximum(derr3_levels)) \\n\\t Min: $(minimum(derr3_levels)) \\n\\t Mean: $(mean(derr3_levels))\")\n    println(\"Dierckx Deriv Errors \\n\\t Max: $(maximum(derr3_deriv)) \\n\\t Min: $(minimum(derr3_deriv)) \\n\\t Mean: $(mean(derr3_deriv))\")\n    println(\"CompEcon Level Errors \\n\\t Max: $(maximum(ceerr3_levels)) \\n\\t Min: $(minimum(ceerr3_levels)) \\n\\t Mean: $(mean(ceerr3_levels))\")\n    println(\"CompEcon Deriv Errors \\n\\t Max: $(maximum(ceerr3_deriv)) \\n\\t Min: $(minimum(ceerr3_deriv)) \\n\\t Mean: $(mean(ceerr3_deriv))\")\n\n\nend\n", "meta": {"hexsha": "9eb8be243e5108e204bd9adc1f66a7e1d55cce13", "size": 4242, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demo/dierckxcompare_1d.jl", "max_stars_repo_name": "magerton/BasisMatrices.jl", "max_stars_repo_head_hexsha": "093925e67c2452a1f2da872571aff84d93cfac2d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2016-10-26T02:36:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-22T22:05:15.000Z", "max_issues_repo_path": "demo/dierckxcompare_1d.jl", "max_issues_repo_name": "magerton/BasisMatrices.jl", "max_issues_repo_head_hexsha": "093925e67c2452a1f2da872571aff84d93cfac2d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 58, "max_issues_repo_issues_event_min_datetime": "2016-10-25T21:55:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T10:14:37.000Z", "max_forks_repo_path": "demo/dierckxcompare_1d.jl", "max_forks_repo_name": "magerton/BasisMatrices.jl", "max_forks_repo_head_hexsha": "093925e67c2452a1f2da872571aff84d93cfac2d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:47:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T23:07:07.000Z", "avg_line_length": 38.5636363636, "max_line_length": 142, "alphanum_fraction": 0.6607732202, "num_tokens": 1494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7781867758164082}}
{"text": "function linear_interpolation(x1, xT, T)\n    n = length(x1)\n    X = [copy(Array(x1)) for t = 1:T]\n    for t = 1:T\n        for i = 1:n\n            X[t][i] = (xT[i] - x1[i]) / (T - 1) * (t - 1) + x1[i]\n        end\n    end\n    return X\nend\n", "meta": {"hexsha": "a2d8feaa7e40ffeba480c07d6f5dfc34a1110937", "size": 237, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "rejuvyesh/DirectTrajectoryOptimization.jl", "max_stars_repo_head_hexsha": "62d75797697a5b8250c1b052eb541086ed68f0ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "rejuvyesh/DirectTrajectoryOptimization.jl", "max_issues_repo_head_hexsha": "62d75797697a5b8250c1b052eb541086ed68f0ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "rejuvyesh/DirectTrajectoryOptimization.jl", "max_forks_repo_head_hexsha": "62d75797697a5b8250c1b052eb541086ed68f0ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5454545455, "max_line_length": 65, "alphanum_fraction": 0.4388185654, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7781867704226522}}
{"text": "# Each new term in the Fibonacci sequence is generated by adding the previous\n# two terms. By starting with 1 and 2, the first 10 terms will be:\n#\n# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\n#\n# By considering the terms in the Fibonacci sequence whose values do not exceed\n# four million, find the sum of the even-valued terms.\n\nusing ProjectEulerSolutions\n\n# Brute force solution, cycle through Fibonacci numbers up to 4 mil and sum the\n# even ones.\nfunction p002solution_running_sum(n::Integer=3)::Integer\n    fibs = fibonacci_bound(BigInt(n))\n    running_sum = 0\n    @simd for val in fibs\n        if val % 2 == 0\n            running_sum += val\n        end\n    end\n    return running_sum\nend\n\n# With a little thought, we see that it is only the 3*k+2 Fibonacci numbers that\n# are even, so just sum them.\nfunction p002solution_sum(n::Integer=3)::Integer\n    fibs = fibonacci_bound(BigInt(n))\n    return sum(fibs[2:3:length(fibs)])\nend\n\np002 = Problems.Problem(Dict(\"Running sum\" => p002solution_running_sum, \"Sum\" => p002solution_sum))\n\nProblems.benchmark(p002, 4_000_000 - 1)", "meta": {"hexsha": "c86724ca9f8bab56d3b4d45a66e7581ad972795f", "size": 1074, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/002.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/002.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/002.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5454545455, "max_line_length": 99, "alphanum_fraction": 0.7076350093, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701655, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7781867659896614}}
{"text": "# Worked with Kasra and Waleed #\r\n\r\ncd(\"D:\\\\Semester 3_Fall 2020\\\\ECON 6453 - Econometrics III\\\\ProblemSets\\\\PS4-mixture\")\r\nusing Random, Distributions, JLD2, DataFrames, CSV, LinearAlgebra, Statistics, FreqTables, TexTables, Optim, HTTP, GLM, ForwardDiff\r\n\r\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n# Question 1: Multinomial logit with Alternate Specific Covariates\r\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n\r\nurl = \"https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2020/master/ProblemSets/PS4-mixture/nlsw88t.csv\"\r\ndf = CSV.read(HTTP.get(url).body)\r\n\r\nX = [df.age df.white df.collgrad]\r\nZ = hcat(df.elnwage1, df.elnwage2, df.elnwage3, df.elnwage4, df.elnwage5, df.elnwage6, df.elnwage7, df.elnwage8)\r\ny = df.occ_code\r\n# Using PS3's code for Multinomial Logit #\r\nfunction mlogit(alpha, X, Z, y)\r\n    beta = alpha[1:end-1] # Indexing the parameter so coefficient on X is the first element\r\n    gamma = alpha[end] # Indexing the parameter so coefficient on Z is the last element\r\n    K = size(X,2) # K is the no. of covariates in X, which in this case are 3\r\n    J = length(unique(y)) # J is the no. of coefficients, which are 8 in this case (So J-1 = 7)\r\n    N = length(y) # N is a vector with the same length as y (not sure why we are defining N)\r\n    bigY = zeros(N,J) # Simply defining the matrix of dependent variables Y, which are going to be dummies in case of Multinomial Logit\r\n\r\n    for j=1:J # Simply defining j to be something, next step, j represents column\r\n        bigY[:,j] = y.==j # Making a dummies for each of the corresponding occupation in y\r\n    end\r\n    bigBeta = [reshape(beta,K,J-1) zeros(K)] # Reshaping into a matrix with K rows and J-1 columns\r\n    # Adding a column of zeros in the end to make it conform with bigY and also to normalize the parameters of the last occupation to be zero\r\n\r\n    T = promote_type(eltype(X),eltype(alpha)) # To get the standard errors we promote the type\r\n    num   = zeros(T,N,J) # Define numerator T-type , N-rows, J-columns\r\n    dem   = zeros(T,N) # Define denominator T-type , N-rows\r\n    for j=1:J\r\n        num[:,j] = exp.(X*bigBeta[:,j] .+ (Z[:,j] .- Z[:,J])*gamma) # Numerator Likelihood function\r\n        dem .+= num[:,j] # Denominator Likelihood function: Simply the Sum of all the numerators\r\n    end\r\n\r\n    P = num./repeat(dem,1,J) # Putting together numerator and denominator\r\n\r\n    loglike = -sum( bigY.*log.(P) ) # Since Optim minimizes the function, we take its negative to maximize\r\n\r\n    return loglike # This is used for storing the function parameters\r\nend\r\n\r\nstartvals = [2*rand(7*size(X,2)).-1; .1]\r\ntd = TwiceDifferentiable(alpha -> mlogit(alpha, X, Z, y), startvals; autodiff = :forward)\r\n\r\n# Use Optim #\r\nα_hat_multinomial = optimize(td, startvals, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\r\nα_hat_multinomial_ad = α_hat_multinomial.minimizer\r\n\r\n# Find Hessian #\r\nH  = Optim.hessian!(td, α_hat_multinomial_ad) # Finding the Hessian Matrix\r\nα_hat_multinomial_ad_se = sqrt.(diag(inv(H))) # Standard Errors of alpha_hat\r\n\r\nprintln([α_hat_multinomial_ad α_hat_multinomial_ad_se])\r\n\r\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n# Question 2: Interpretation of gamma_hat\r\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n# gamma_hat make more sense as compared to PS3 because it's sign is positive #\r\n\r\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n# Question 3:\r\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n\r\n### Part (A) ###\r\nusing Distributions\r\ninclude(\"lgwt.jl\") # make sure the function gets read in\r\n\r\n# define distribution\r\nd = Normal(0,1) # mean=0, standard deviation=1\r\n\r\n# get quadrature nodes and weights for 7 grid points, with +_ 4SD\r\nnodes, weights = lgwt(7,-4,4)\r\n\r\n# now compute the integral over the density and verify it's 1\r\nsum(weights.*pdf.(d,nodes)) # d here is normal dist. as defined earlier #\r\n\r\n# now compute the expectation and verify it's 0\r\nsum(weights.*nodes.*pdf.(d,nodes)) # it seems as if the nodes here is x in: intergral x phi(x) dx #\r\n\r\n### Part (B) ###\r\n\r\n#Practice 1#\r\nd = Normal(0,2)\r\nnodes, weights = lgwt(7,-5,5)\r\nsum(weights.*(nodes.^2).*pdf.(d,nodes))\r\n\r\n#Practice 2#\r\nnodes, weights = lgwt(10,-5,5)\r\nsum(weights.*(nodes.^2).*pdf.(d,nodes))\r\n\r\n# Comment: Increasing the quadrature points gives us better estimates (of variace of f(x)) #\r\n\r\n### Part (C) ###\r\n\r\n#Practice 1#\r\nRandom.seed!(1234)\r\nd = Normal(0,2)\r\nN = 1000000\r\nnodes, weights = lgwt(10,-5,5)\r\nx = rand(Uniform(-10,10), N)\r\nA = (10-(-10))*(1/N)*sum((x.^2).*pdf(d,x)) # A is approximately equal to 4 #\r\n\r\n#Practice 2#\r\nA1 = (10-(-10))*(1/N)*sum((x).*pdf(d,x)) # A1 is approx. equal to 0 #\r\n#Practice 3#\r\nA2 = (10-(-10))*(1/N)*sum(pdf(d,x)) # A2 is approx. equal to 1 #\r\n\r\n#Practice 4#\r\nD = 1000\r\nx = rand(Uniform(-10,10), D)\r\n\r\nA = (10-(-10))*(1/D)*sum((x.^2).*pdf(d,x))\r\n\r\nA1 = (10-(-10))*(1/D)*sum((x).*pdf(d,x))\r\n\r\nA2 = (10-(-10))*(1/D)*sum(pdf(d,x))\r\n# Reducing D to 1000 more likely less precise estimates #\r\n\r\n### Part (D) ###\r\n\r\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n# Question 4: With Gauss-Lagendre Quadrature\r\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\r\nfunction mixedlogit_quadrature(theta, X, Z, y, rn)\r\n\r\n        alpha = theta[1:end-1]\r\n        gamma = theta[end]\r\n        K = size(X,2)\r\n        J = length(unique(y))\r\n        N = length(y)\r\n        bigY = zeros(N,J)\r\n        for j=1:J\r\n            bigY[:,j] = y.==j\r\n        end\r\n        bigAlpha = [reshape(alpha,K,J-1) zeros(K)]\r\n\r\n        nodes, weights = lgwt(rn,-4,4);\r\n        d=Normal(0,1)\r\n\r\n\r\n        T = promote_type(eltype(X),eltype(theta))\r\n        num   = zeros(T,N,J)\r\n        dem   = zeros(T,N)\r\n        for j=1:J\r\n            num[:,j] = sum(exp.(X*bigAlpha[:,j] .+ (Z[:,j] .- Z[:,J])*gamma).*weights.*pdf.(d,nodes))\r\n            dem .+= num[:,j]\r\n        end\r\n\r\n        P = num./repeat(dem,1,J)\r\n\r\n\r\n        loglike = -sum( log.(P.^bigY) )\r\n\r\n        return loglike\r\n    end\r\n\r\n\r\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n# Question 5: With Monte Carlo Simulations\r\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\r\nfunction mixedlogit_simulation(theta, X, Z, y,rn)\r\n\r\n        alpha = theta[1:end-1]\r\n        gamma = theta[end]\r\n        K = size(X,2)\r\n        J = length(unique(y))\r\n        N = length(y)\r\n        bigY = zeros(N,J)\r\n        for j=1:J\r\n            bigY[:,j] = y.==j\r\n        end\r\n        bigAlpha = [reshape(alpha,K,J-1) zeros(K)]\r\n\r\n\r\n        d=Normal(0,1)\r\n        rx=rand(Uniform(0,1 ),rn)\r\n\r\n        T = promote_type(eltype(X),eltype(theta))\r\n        num   = zeros(T,N,J)\r\n        dem   = zeros(T,N)\r\n        for j=1:J\r\n            num[:,j] = sum(exp.(X*bigAlpha[:,j] .+ (Z[:,j] .- Z[:,J])*gamma).*(pdf.(d,x)))\r\n            dem .+= num[:,j]\r\n        end\r\n\r\n        P = num./repeat(dem,1,J)\r\n\r\n\r\n        loglike = -sum( log.(P.^bigY) )\r\n\r\n        return loglike\r\n    end\r\n\r\n                                ### End ###\r\n", "meta": {"hexsha": "9406f05c023b2167345bbf6a597c89eec45913f2", "size": 6958, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS4-mixture/PS4_Ahmed Chaudhry.jl", "max_stars_repo_name": "ahmedch92/fall-2020", "max_stars_repo_head_hexsha": "ef1c9f859f4cbb81e1006454d79b3600157cabfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSets/PS4-mixture/PS4_Ahmed Chaudhry.jl", "max_issues_repo_name": "ahmedch92/fall-2020", "max_issues_repo_head_hexsha": "ef1c9f859f4cbb81e1006454d79b3600157cabfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS4-mixture/PS4_Ahmed Chaudhry.jl", "max_forks_repo_name": "ahmedch92/fall-2020", "max_forks_repo_head_hexsha": "ef1c9f859f4cbb81e1006454d79b3600157cabfd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9648241206, "max_line_length": 142, "alphanum_fraction": 0.560649612, "num_tokens": 2060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055544, "lm_q2_score": 0.8902942348544447, "lm_q1q2_score": 0.778185932045901}}
{"text": "# # Thermal Generation Dispatch Example\n\n#md # [![](https://img.shields.io/badge/GitHub-100000?style=for-the-badge&logo=github&logoColor=white)](@__REPO_ROOT_URL__/examples/Thermal_Generation_Dispatch_Example.jl)\n\n# This example illustrates the sensitivity analysis of thermal generation dispatch problem.\n\n# This problem can be described as the choice of thermal generation `g` given a demand `d`, a price for thermal generation `c` and a penalty price `c_{ϕ}` for any demand not attended ϕ.\n\n# ```math\n# \\begin{split}\n# \\begin{array} {ll}\n# \\mbox{minimize} & \\sum_{i=1}^{N} c_{i} g_{i} + c_{\\phi} \\phi \\\\\n# \\mbox{s.t.} & g_{i} \\ge 0 \\quad i=1..N  \\\\\n#             & g_{i} \\le G_{i} \\quad i=1..N  \\\\\n#             & \\sum_{i=1}^{N} g_{i} + \\phi = d\\\\\n# \\end{array}\n# \\end{split}\n# ```\n# where\n# - `G_{i}` is the maximum possible generation for a thermal generator `i`\n\n# ## Define and solve the Thermal Dispatch Problem\n\n# First, import the libraries.\n\nusing Test\nusing JuMP\nimport DiffOpt\nimport LinearAlgebra: dot\nimport HiGHS\nimport MathOptInterface\nimport Plots\nconst MOI = MathOptInterface\n\n# Define the model that will be construct given a set of parameters.\n\nfunction generate_model(d::Float64; g_sup::Vector{Float64}, c_g::Vector{Float64}, c_ϕ::Float64)\n    ## Creation of the Model and Parameters\n    model = Model(() -> DiffOpt.diff_optimizer(HiGHS.Optimizer))\n    set_silent(model)\n    I = length(g_sup)\n\n    ## Variables\n    @variable(model, g[i in  1:I] >= 0.0)\n    @variable(model, ϕ >= 0.0)\n\n    ## Constraints\n    @constraint(model, limit_constraints_sup[i in 1:I], g[i] <= g_sup[i])\n    @constraint(model, demand_constraint, sum(g) + ϕ == d)\n\n    ## Objectives\n    @objective(model, Min, dot(c_g, g) + c_ϕ * ϕ)\n\n    ## Solve the model\n    optimize!(model)\n\n    ## Return the solved model\n    return model\nend\n\n# Define the functions that will get the primal values `g` and `\\phi` and sensitivity analysis of the demand `dg/dd` and `d\\phi/dd` from a optimized model.\n\nfunction diff_forward(model::Model, ϵ::Float64 = 1.0)\n    ## Initialization of parameters and references to simplify the notation\n    vect_ref = [model[:g]; model[:ϕ]]\n    I = length(model[:g])\n\n    ## Get the primal solution of the model\n    vect = MOI.get.(model, MOI.VariablePrimal(), vect_ref)\n     \n    ## Pass the perturbation to the DiffOpt Framework and set the context to Forward\n    constraint_equation = convert(MOI.ScalarAffineFunction{Float64}, ϵ)\n    MOI.set(model, DiffOpt.ForwardConstraintFunction(), model[:demand_constraint], constraint_equation)\n    DiffOpt.forward_differentiate!(model)\n    \n    ## Get the derivative of the model\n    dvect = MOI.get.(model, DiffOpt.ForwardVariablePrimal(), vect_ref)\n    \n    ## Return the values as a vector\n    return [vect; dvect]\nend\n\nfunction diff_reverse(model::Model, ϵ::Float64 = 1.0)\n    ## Initialization of parameters and references to simplify the notation\n    vect_ref = [model[:g]; model[:ϕ]]\n    I = length(model[:g])\n\n    ## Get the primal solution of the model\n    vect = MOI.get.(model, MOI.VariablePrimal(), vect_ref)\n\n    ## Set variables needed for the DiffOpt Backward Framework\n    dvect = Array{Float64, 1}(undef, I + 1)\n    perturbation = zeros(I + 1)\n\n    ## Loop for each primal variable\n    for i in 1:I+1\n        ## Set the perturbation in the Primal Variables and set the context to Backward\n        perturbation[i] = ϵ\n        MOI.set.(model, DiffOpt.ReverseVariablePrimal(), vect_ref, perturbation)\n        DiffOpt.reverse_differentiate!(model)\n\n        ## Get the value of the derivative of the model\n        dvect[i] = JuMP.constant(MOI.get(model, DiffOpt.ReverseConstraintFunction(), model[:demand_constraint]))\n        perturbation[i] = 0.0\n    end\n\n    ## Return the values as a vector\n    return [vect;dvect]\nend\n\n# Initialize of Parameters\n\ng_sup = [10.0, 20.0, 30.0]\nI = length(g_sup)\nd = 0.0:0.1:80\nd_size = length(d)\nc_g = [1.0, 3.0, 5.0]\nc_ϕ = 10.0\n;\n\n# Generate models for each demand `d`\nmodels = generate_model.(d; g_sup = g_sup, c_g = c_g, c_ϕ = c_ϕ);\n\n# Get the results of models with the DiffOpt Forward and Backward context\n\nresult_forward = diff_forward.(models)\noptimize!.(models)\nresult_reverse = diff_reverse.(models);\n\n# Organization of results to plot\n# Initialize data_results that will contain every result\ndata_results = Array{Float64,3}(undef, 2, d_size, 2*(I+1));\n\n# Populate the data_results array\nfor k in 1:d_size\n    data_results[1,k,:] = result_forward[k]\n    data_results[2,k,:] = result_reverse[k]\nend\n\n# ## Results with Plot graphs\n# ### Results for the forward context\n# Result Primal Values:\nPlots.plot(d,data_results[1,:,1:I+1],\n    title=\"Generation by Demand\",label=[\"Thermal Generation 1\" \"Thermal Generation 2\" \"Thermal Generation 3\" \"Generation Deficit\"],\n    xlabel=\"Demand [unit]\",ylabel= \"Generation [unit]\"\n)\n\n# Result Sensitivity Analysis:\nPlots.plot(d,data_results[1,:,I+2:2*(I+1)],\n    title=\"Sensitivity of Generation by Demand\",label=[\"T. Gen. 1 Sensitivity\" \"T. Gen. 2 Sensitivity\" \"T. Gen. 3 Sensitivity\" \"Gen. Deficit Sensitivity\"],\n    xlabel=\"Demand [unit]\",ylabel= \"Sensitivity [-]\"\n)\n\n# ### Results for the reverse context\n# Result Primal Values:\nPlots.plot(d,data_results[2,:,1:I+1],\n    title=\"Generation by Demand\",label=[\"Thermal Generation 1\" \"Thermal Generation 2\" \"Thermal Generation 3\" \"Generation Deficit\"],\n    xlabel=\"Demand [unit]\",ylabel= \"Generation [unit]\"\n)\n\n# Result Sensitivity Analysis:\nPlots.plot(d,data_results[2,:,I+2:2*(I+1)],\n    title=\"Sensitivity of Generation by Demand\",label=[\"T. Gen. 1 Sensitivity\" \"T. Gen. 2 Sensitivity\" \"T. Gen. 3 Sensitivity\" \"Gen. Deficit Sensitivity\"],\n    xlabel=\"Demand [unit]\",ylabel= \"Sensitivity [-]\"\n)\n", "meta": {"hexsha": "1ab14c11ace4da85707dbe9b070b2386c44e485d", "size": 5693, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/Thermal_Generation_Dispatch_Example.jl", "max_stars_repo_name": "AKS1996/DiffOpt.jl", "max_stars_repo_head_hexsha": "8dfa684c49ad51a0e6801c4b7f1ea3d167c84812", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-05-22T11:38:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T12:18:47.000Z", "max_issues_repo_path": "docs/src/examples/Thermal_Generation_Dispatch_Example.jl", "max_issues_repo_name": "AKS1996/DiffOpt.jl", "max_issues_repo_head_hexsha": "8dfa684c49ad51a0e6801c4b7f1ea3d167c84812", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-05-21T20:29:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-27T06:57:03.000Z", "max_forks_repo_path": "docs/src/examples/Thermal_Generation_Dispatch_Example.jl", "max_forks_repo_name": "AKS1996/DiffOpt.jl", "max_forks_repo_head_hexsha": "8dfa684c49ad51a0e6801c4b7f1ea3d167c84812", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2951807229, "max_line_length": 185, "alphanum_fraction": 0.6876866327, "num_tokens": 1640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.8740772335247532, "lm_q1q2_score": 0.7781859167360728}}
{"text": "# function to calcule the force between a pair of particles\n# Exercise 39_40\nusing simulationQP934\n\n\n\n#inputs\ndata = Data();\nbox  = initial_point(data);\nparticle1 = box[1];\nparticle2 = box[2];\n\nfunction fpair(x,y,r,data)\n\n  # r values for F calculation \n  r6  = r^6\n  r7  = r6 * r\n  r12 = r6^2\n  r13 = r12 * r\n\n  # x and y components\n  # Fz = -( dU(r) / dz) = - (dr/dz) * (dU(r)/dr), r = sqrt(dx^2,dy^2)     \n  # calculation for -(dr/dr) \n\n  drdx1 = -(x[1]-y[1])/r\n  drdx2 = -(x[2]-y[2])/r\n\n  dudr1 = -12*(data.sig12/r13)\n  dudr2 = -6*(data.sig6/r7)\n\n  dfacdr =  data.eps4*(dudr1 - dudr2)\n\n  upair = data.eps4*(data.sig12/r12 - data.sig6/r6)  \n  f = ( -dfacdr*drdx1, -dfacdr*drdx2 ) \n\n  return upair, f\n\nend\n\n\nr = pbcseparation(particle1,particle2,data.side)\n  \nf12 = fpair(particle1,particle2,r,data)\n\nf21 = fpair(particle2,particle1,r,data)\n\n\n\n\n\n", "meta": {"hexsha": "f5e7a06de7fac81fee52ba685bdf78a7af0efa02", "size": 848, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ativ_39_40.jl", "max_stars_repo_name": "viniciuspiccoli/simulationQP934", "max_stars_repo_head_hexsha": "1187384bddb098dba854d01db66d82891f6d6dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ativ_39_40.jl", "max_issues_repo_name": "viniciuspiccoli/simulationQP934", "max_issues_repo_head_hexsha": "1187384bddb098dba854d01db66d82891f6d6dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ativ_39_40.jl", "max_forks_repo_name": "viniciuspiccoli/simulationQP934", "max_forks_repo_head_hexsha": "1187384bddb098dba854d01db66d82891f6d6dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.6274509804, "max_line_length": 74, "alphanum_fraction": 0.6120283019, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995703612219, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.778159789713743}}
{"text": "\"\"\"\n    newton(x0, f, j; maxiter, tol)\n\nSolution to f(x) = 0 where f'(x) = j(x) using Newton's method.\n\"\"\"\nfunction newton(x0, f, j; maxiter = 1000, tol = 1e-14)\n    x = x0\n    for _ in 1:maxiter\n        fx = f(x)\n        if abs(fx) < tol\n            return x\n        else\n            x = x - (fx / j(x))\n        end\n    end\n    return x\nend\n\n", "meta": {"hexsha": "2fb5e32b69213d52b52f6be988f439ce04e2c875", "size": 343, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/optimization.jl", "max_stars_repo_name": "ruairidhs/RSUtils.jl", "max_stars_repo_head_hexsha": "485567ac2f9604249d5e121936733219438e251e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/optimization.jl", "max_issues_repo_name": "ruairidhs/RSUtils.jl", "max_issues_repo_head_hexsha": "485567ac2f9604249d5e121936733219438e251e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimization.jl", "max_forks_repo_name": "ruairidhs/RSUtils.jl", "max_forks_repo_head_hexsha": "485567ac2f9604249d5e121936733219438e251e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0526315789, "max_line_length": 62, "alphanum_fraction": 0.4664723032, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9572778000158576, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7781398398941816}}
{"text": "# # One-Dimensional Cases\n#\n# The 1D case in Optimal Transport is a special case where one can\n# easily obtain closed form solutions efficiently\n# when the cost function is convex. In this situation,\n# one does no need to use Linear Programming solvers\n# to obtain the exact solution to the problem.\n\n# ## Packages\n#\n# We load the following packages into our environment:\n\nusing OptimalTransport\nusing Distances\nusing Distributions\nusing StatsPlots\n\nusing LinearAlgebra\nusing Random\n\nRandom.seed!(1234);\n\n# ## Continuous Distribution\n#\n# In the 1D case, when the source measure $\\mu$ is continuous and the cost function\n# has the form ``c(x, y) = h(|x - y|)`` where ``h`` is a convex function,\n# the optimal transport plan is the Monge map\n# ```math\n# T = F_\\nu^{-1} \\circ F_\\mu\n# ```\n# where ``F_\\mu`` is the cumulative distribution function of `μ` and ``F_\\nu^{-1}`` is the\n# quantile function of `ν`.\n# In this setting, the optimal transport cost can be computed as\n# ```math\n# \\int_0^1 c(F_\\mu^{-1}(x), F_\\nu^{-1}(x)) \\mathrm{d}x\n# ```\n# where ``F_\\mu^{-1}`` and ``F_\\nu^{-1}`` are the quantile functions of `μ` and `ν`,\n# respectively.\n# \n# We start by defining the distributions.\n\nμ = Normal(0, 1)\n\nN = 10\nν = Poisson(N);\n\n# Nest, we define a cost function.\nc(x, y) = (abs(x - y))^2 # could have used `sqeuclidean` from `Distances.jl`\n\nT = ot_plan(c, μ, ν);\n\n# `T` is the Monge Map. Let's visualize it.\np1 = plot(μ; label='μ')\np1 = plot!(ν; marker=:circle, label='ν')\np2 = plot(-2:0.1:2, T(-2:0.1:2); label=\"Monge map\", color=:green, legend=:topleft)\nplot(p1, p2)\n\n# The optimal transport cost can be computed with\not_cost(c, μ, ν)\n\n# If instead you want the 2-Wasserstein distance (which is the square root\n# of the optimal transport with the Square Euclidean distatce, then use\nwasserstein(μ, ν; p=2)\n\n# ## Finite Discrete Distributions\n#\n# If the source and target measures are 1D finite discrete distributions\n# (sometimes referred as empirical distributions, or as sample distributions),\n# and if the cost function is convex, then the optimal\n# transport plan can be written as a sorting algorithm,\n# where the utmost left probability mass of the source is transported\n# to the closest probability mass of the target, until everything is transported.\n# \n# Define your measures as DiscreteNonParametric, which is a type in Distributions.jl.\n# Also, let's assume both point masses with equal weights and let's\n# use the `sqeuclidean` function instead of creating our own cost function.\n\nM = 15\nμ = DiscreteNonParametric(1.5rand(M), fill(1 / M, M))\n\nN = 10\nν = DiscreteNonParametric(1.5rand(N) .+ 2, fill(1 / N, N))\n\nγ = ot_plan(sqeuclidean, μ, ν);\n\n# This time γ is a sparse matrix containing the transport plan. Let's visualize the results.\n# We create a function `curve` just as a helper to draw the transport plan.\n\nfunction curve(x1, x2, y1, y2)\n    a = min(y1, y2)\n    b = (y1 - y2 + a * (x1^2 - x2^2)) / (x1 - x2)\n    c = y1 + a * x1^2 - b * x1\n    f(x) = -a * x^2 + b * x + c\n    return f\nend\n\np = plot(μ; marker=:circle, label='μ')\np = plot!(ν; marker=:circle, label='ν', ylims=(0, 0.2))\nfor i in 1:M, j in 1:N\n    if γ[i, j] > 0\n        transport = curve(μ.support[i], ν.support[j], 1 / M, 1 / N)\n        x = range(μ.support[i], ν.support[j]; length=100)\n        p = plot!(x, transport.(x); color=:green, label=nothing, alpha=0.5)\n    end\nend\np\n\n# Again, the optimal transport cost can be calculated with\n\not_cost(sqeuclidean, μ, ν)\n", "meta": {"hexsha": "43af0b027e76e433676cc6ee8b83337c45e8a9de", "size": 3451, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/OneDimension/script.jl", "max_stars_repo_name": "zsteve/ot.jl", "max_stars_repo_head_hexsha": "a82e3fb19b00839ba809225e76a4ea43b49a315d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2021-05-28T14:16:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:38:40.000Z", "max_issues_repo_path": "examples/OneDimension/script.jl", "max_issues_repo_name": "zsteve/ot.jl", "max_issues_repo_head_hexsha": "a82e3fb19b00839ba809225e76a4ea43b49a315d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 109, "max_issues_repo_issues_event_min_datetime": "2021-05-18T18:45:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T12:30:01.000Z", "max_forks_repo_path": "examples/OneDimension/script.jl", "max_forks_repo_name": "zsteve/ot.jl", "max_forks_repo_head_hexsha": "a82e3fb19b00839ba809225e76a4ea43b49a315d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-30T12:11:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T19:11:56.000Z", "avg_line_length": 31.0900900901, "max_line_length": 92, "alphanum_fraction": 0.6806722689, "num_tokens": 1062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7780679790949339}}
{"text": "# Period doubling bifurcation + cobweb for logistic map\nusing DrWatson\n@quickactivate \"NonlinearDynamicsTextbook\"\ninclude(srcdir(\"style.jl\"))\nusing DynamicalSystems, PyPlot, Random\n\nlo = Systems.logistic(0.4)\nrs = (2.8, 3.3)\n\nfig, axs = subplots(1, 2, figsize = (0.66figx, figy))\n\nT = 1000\nxs = 0:0.0001:1\n\nfunction cobweb(t) # transform timeseries t into cobweb (point2D)\n    cx = Float64[]; cy = Float64[]\n    for i ∈ 1:length(t)-1\n        push!(cx, t[i]); push!(cy, t[i])\n\t\tpush!(cx, t[i]); push!(cy, t[i+1])\n    end\n    # add line to x axis\n    pushfirst!(cx, cx[1])\n    pushfirst!(cy, 0)\n    return cx, cy\nend\n\nfor (i, r) in enumerate(rs)\n    ax = axs[i]\n    ax.set_xlim(0,1)\n    ax.set_ylim(0,1)\n    ax.set_xticks([0, 1])\n    ax.set_xlabel(\"\\$x\\$\"; labelpad=-30)\n\tset_parameter!(lo, 1, r)\n\tf  = lo.f.(xs, Ref([r]), 0)\n    f² = lo.f.(f, Ref([r]), 0)\n\tax.plot(xs, f, color = \"C0\")\n\tax.plot([0, 1], [0,1]; lw = 2, color = \"C3\", ls = \"--\")\n\tx = trajectory(lo, T)\n    cx, cy = cobweb(x)\n    if i>1\n        ax.plot(xs, f², color = \"C1\")\n        ax.text(0.15, 0.875, \"\\$f^{(2)}\\$\"; color = \"C1\", transform = ax.transAxes, size = 32)\n    end\n    ax.plot(cx, cy; lw = 1.0, color = \"C2\")\n    ax.text(0.05, 0.875, \"\\$f\\$\"; color = \"C0\", transform = ax.transAxes, size = 32)\nend\naxs[2].set_yticklabels([])\n\nfig.tight_layout(pad = 0.37)\nadd_identifiers!(fig)\n\nwsave(plotsdir(\"4\", \"period_doubling_bifurcation\"), fig)", "meta": {"hexsha": "d530e95de3fc7c9c82ba99cd2fb3c888ccf1baa3", "size": 1409, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "figure_generation/4/4.3.jl", "max_stars_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_stars_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 88, "max_stars_repo_stars_event_min_datetime": "2021-07-18T20:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T09:23:53.000Z", "max_issues_repo_path": "figure_generation/4/4.3.jl", "max_issues_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_issues_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figure_generation/4/4.3.jl", "max_forks_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_forks_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-07-28T18:49:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:45:11.000Z", "avg_line_length": 27.0961538462, "max_line_length": 94, "alphanum_fraction": 0.5862313698, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7780679671032538}}
{"text": "using LinearAlgebra\nusing Plots\n\ninclude(\"cheb.jl\")\ninclude(\"parameters.jl\")\ninclude(\"geometry.jl\")\ninclude(\"profile.jl\")\ninclude(\"build_A.jl\")\ninclude(\"compute_spectrum.jl\")\ninclude(\"mesh.jl\")\ninclude(\"plot_fields.jl\")\n \nparams=parameters(\n     H = 1, \n    Lϕ = π/100,\n  ϕmin = π/4,\n   TwoΩ = 1, \n      g = 10,\n      a = 1,\n    Lj = π/2000, \n    Uj = 1.0,\n    Nϕ = 100,\n    dk = 1e-2,\n    kₘ = 3\n    ); \n    \nparams.Fr = (params.TwoΩ * params.Lj)^2/(params.g * params.H);\nparams.Ro =  params.Uj/(params.TwoΩ * params.Lj)\n\nprint(\"\\n\")\nprint(\"Linear-Stability-Caluculator\\n\")\nprint(\"============================\\n\\n\")\nprint(\"Repo:      Linear-Stability-Calculators\\n\")\nprint(\"Code:      ShallowWater/Julia/Spherical/linear_stability_shallow_water.jl\\n\")\nprint(\"Model:     Rotating Shallow Water\\n\")\nprint(\"Geometry:  Spherical\\n\")\nprint(\"Structure: Bickley Jet\\n\")\nprint(\"\\n\")\nprint(\"Nondimensional Parameters\\n\")\nprint(\"=========================\\n\")\nprint(\"Fr = \", params.Fr, \"\\n\")\nprint(\"Ro = \", params.Ro, \"\\n\")\n\n# Wavenumbers \nks = collect(params.dk:params.dk:params.kₘ) / params.Lj;\nNk = length(ks);\n\n# Grid and basic state\nDϕ, Dϕ2, ϕ = geometry(params);\n      U,  E = profile(  ϕ, params);\n\nplot_basic_state(ϕ, U, E, \"basic_state.png\")\n\n# initialize fields to store\nNmodes = 2\n     σ = zeros(Nmodes, Nk);\n     ω = zeros(Nmodes, Nk);   \nσmodes = zeros(ComplexF64, 3*params.Nϕ+1, Nmodes, Nk);\n\n# Compute growth rates\nfor cnt in 1:Nk\n    local k = ks[cnt]\n    local A = build_A(k, U, E, Dϕ, Dϕ2, ϕ, params);\n    local σ[:,cnt], ω[:,cnt], σmodes[:,:,cnt] = compute_spectrum(A, k, params, Nmodes);\nend\n\nplot_growth_rates(ks, σ, Nmodes, \"growth_rates_spherical_Bickley_jet.png\")\n\n#print(\"σ = \", σ[1,:],\"\\n\")\n\nmode_number = 1;\n      σ_max = maximum(σ[mode_number,:]);\n    k_index = sortperm(σ[mode_number,:],rev=true)[1];\n          k = ks[k_index]; # pick wavenumber\n\nplot_1D_streamfunction(k_index, k, ϕ, σmodes, mode_number, \"modes_1D_streamfunction.png\")\nplot_2D_streamfunction(k_index, k, ϕ, σmodes, mode_number, \"modes_2D_streamfunction.png\")\nplot_2D_vorticity(Dϕ,  k_index, k, ϕ, σmodes, mode_number, \"modes_2D_vorticity.png\")\n", "meta": {"hexsha": "ffd85f2bb32defac7ccb232880fe3bc23b907218", "size": 2131, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ShallowWater/Julia/Spherical/linear_stability_shallow_water.jl", "max_stars_repo_name": "francispoulin/Linear-Stability-Calculators", "max_stars_repo_head_hexsha": "2e1cf66b0bed95f24ddfeea09ec7d66956cdce64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-22T20:00:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T17:19:18.000Z", "max_issues_repo_path": "ShallowWater/Julia/Spherical/linear_stability_shallow_water.jl", "max_issues_repo_name": "francispoulin/Linear-Stability-Calculators", "max_issues_repo_head_hexsha": "2e1cf66b0bed95f24ddfeea09ec7d66956cdce64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-27T16:14:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-27T16:14:05.000Z", "max_forks_repo_path": "ShallowWater/Julia/Spherical/linear_stability_shallow_water.jl", "max_forks_repo_name": "francispoulin/Linear-Stability-Calculators", "max_forks_repo_head_hexsha": "2e1cf66b0bed95f24ddfeea09ec7d66956cdce64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-05-18T11:05:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T18:57:19.000Z", "avg_line_length": 26.9746835443, "max_line_length": 89, "alphanum_fraction": 0.6367902393, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172688214138, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7780109450399506}}
{"text": "module CartesianSphericalHarmonics\n\n# Write your package code here.\nusing LinearAlgebra\nusing Reexport\n\n@reexport using MultivariatePolynomials\n@reexport using TypedPolynomials\n\nexport YLMNorm, Schmidt, Laplace, Nonorm, Full\nexport rlm, ylm\n#normalization factor\nabstract type YLMNorm{T} end\n\nstruct Schmidt{T} <: YLMNorm{T}; end\nstruct Laplace{T} <: YLMNorm{T}; end\nstruct Nonorm{T} <: YLMNorm{T}; end\nstruct Full{T} <: YLMNorm{T}; end\n\nfunction ylmcoeff(N::Schmidt{T},l::Integer, m::Integer) where T\n\n\tk = one(T)\n\tfor i in (l-m+1):(l+m)\n\t  k *= i\n\tend\n\tfac = sqrt(1/k)\n\tif m!=0\n\t\tfac*=sqrt(2*one(T))\n\tend\n\treturn fac\nend\n\nfunction ylmcoeff(N::Laplace{T}, l::Integer, m::Integer) where T\n\n  k = one(T)\n  for i in (l-m+1):(l+m)\n    k *= i\n  end\n\n  return sqrt((2*l+1) / (4*T(pi)*k))\nend\n\nfunction ylmcoeff(N::Full{T}, l::Integer, m::Integer) where T\n\tfac = m==0 ? one(T) : sqrt(2*one(T))\n\treturn ylmcoeff(Laplace{T}(),l,m)*sqrt(4T(pi))*fac\nend\n\nfunction ylmcoeff(N::Nonorm{T}, l::Integer, m::Integer) where T\n return one(T)\nend\n\n\n\nfunction cossinpoly(m::Integer, x::Variable, y::Variable)\n\n  sum = zero(x*y)\n  for j in 0:div(m,2)\n\t  k = 2j\n    sum += ((-1)^j)*binomial(m, k)*y^Int(k)*x^Int(m-k)\n  end\n  return sum\nend\n\nfunction sinsinpoly(m::Integer, x::Variable, y::Variable)\n\n  sum = zero(x*y)\n  for j in 0:div((m-1),2)\n\t  k = 2j+1\n    sum += ((-1)^j)*binomial(m, k)*y^Int(k)*x^Int(m-k)\n  end\n  return sum\nend\n\n#\nfunction legendre_assoc(::Type{T},z,l,m) where T\n\tp = (z^2 - 1)^l\n\n\tfor i = 1:l+abs(m)\n\tc = i <= l ? 1/(2one(T)*i) : one(T)\n\tp = c*differentiate(p, z)\n\tend\n\n\tp *= (-1)^m\n\treturn p\nend\n# #legendre polynomial:\n# P(l::BigInt,x) = differentiate((x^2 - 1)^l,x,l)\n#\n# #associated legendre polynomial (without sin(θ)^m)\n# P(l::BigInt,m::BigInt,x) = 1//(big(2)^l*factorial(l))*differentiate(P(l,x),x,m)\n\n\"\"\"\n    ylm(l::Integer, m::Integer, x::Variable, y::Variable, z::Variable)\n*Description:*  Calculation of the spherical harmonic for a given order (l,m) in Cartesian coordinates\\\\\n\n*Input:*  `l`       - Degree of the spherical harmonic\\\\\n          `m`       - Order of the spherical harmonic\\\\\n          `x, y, z` - Cartesian coordinates\\\\\n\n*Output:*  Spherical harmonic polynomial\n\"\"\"\nfunction ylm(l::Integer, m::Integer, x::Variable, y::Variable, z::Variable;\n\t\t\t norm::YLMNorm{T}=Nonorm{Rational{Int}}(),real::Bool=true) where T\n\n\tif abs(m) > l\n\t\tthrow(DomainError(m,\"-l <= m <= l expected, but m = $m and l = $l.\"))\n\tend\n\n\tp = legendre_assoc(T,z,l,m)\n\t# p = (z^2 - 1)^l\n\n\t# for i = 1:l+abs(m)\n\t#   c = i <= l ? 1/(2one(T)*i) : one(T)\n\t#   p = c*differentiate(p, z)\n\t# end\n\n\t# p *= (-1)^m\n\n\tif real\n\t\tif m > 0\n\t\t\treturn ylmcoeff(norm, l, m)*cossinpoly(m,x,y)*p\n\t\telseif m < 0\n\t\t\treturn ylmcoeff(norm, l, abs(m))*sinsinpoly(abs(m),x,y)*p\n\t\telse\n\t\t\treturn ylmcoeff(norm, l, 0)*p\n\t\tend\n\telse\n\t\treturn ylmcoeff(norm, l, m)*(cossinpoly(m,x,y)+im*sinsinpoly(m,x,y))*p\n\tend\nend\n\n# multiplying r^l*ylm(x,y,z)\nfunction rlm(l::Integer, m::Integer, x::Variable, y::Variable, z::Variable;\n\t\t\t   norm::YLMNorm{T}=Nonorm{Rational{Int}}(),real::Bool=true) where T\n\tp = ylm(l,m,x,y,z;norm=norm,real=real)\n\ttout = []\n\n\tfor t in terms(p)\n\t\tdeg = degree(monomial(t)) # degree of monomial\n\t\tdegR = l-deg # degree of r: l-deg\n\t\tpush!(tout,(x^2+y^2+z^2)^div(degR,2)*t) # r² replaced by x²+y²+z²\n\tend\n\n\treturn polynomial(tout)\nend\n\nend\n", "meta": {"hexsha": "00d8fcf4322c831f7da3b15b0aa18b5d1a789dda", "size": 3327, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CartesianSphericalHarmonics.jl", "max_stars_repo_name": "fgerick/CartesianSphericalHarmonics.jl", "max_stars_repo_head_hexsha": "7eb8fa83fcc17f5b1e51439b2a87bb3eb5c12efd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-12T10:44:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T10:45:04.000Z", "max_issues_repo_path": "src/CartesianSphericalHarmonics.jl", "max_issues_repo_name": "fgerick/CartesianSphericalHarmonics.jl", "max_issues_repo_head_hexsha": "7eb8fa83fcc17f5b1e51439b2a87bb3eb5c12efd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CartesianSphericalHarmonics.jl", "max_forks_repo_name": "fgerick/CartesianSphericalHarmonics.jl", "max_forks_repo_head_hexsha": "7eb8fa83fcc17f5b1e51439b2a87bb3eb5c12efd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4797297297, "max_line_length": 104, "alphanum_fraction": 0.625488428, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172615983309, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7780109432938421}}
{"text": "\"\"\"\n    poisson_rng(p, n, shape=1; seed=nothing)\n\nGenerate a `shape` element array of random variables from a Poisson(`λ`) distribution. Optionally you can set a specific seed.\n\n# Notes\n\nThe Poisson distribution is given by:\n\n``f(x, λ) = \\\\frac{λ^x}{x!} e^λ \\\\quad x = 0,1,2,…``\n\n# Examples\n\n```julia-repl\njulia> poisson_rng(3)\n1×1 Matrix{Int64}:\n 7\n\njulia> poisson_rng(10, 5)\n5×1 Matrix{Int64}:\n 13\n 11\n 10\n  8\n 15\n\njulia> poisson_rng(10, (5,5))\n5×5×1 Array{Int64, 3}:\n[:, :, 1] =\n 11  15   9  11   9\n  8  15  13  10   9\n 11  12   4  10   6\n  7   9  13  11   7\n 13   7  10  10  14\n \n```\n\n# References\n\nR. Larson, A. Odoni. Urban operations research. Prentice-Hall, New Jersey, 1981.\n\nG. Last, M. Penrose. Lectures on the poisson process. Cambridge University Press, 2017.\n\"\"\"\nfunction poisson_rng(λ::Real, shape::Union{Int, Tuple{Vararg{Int}}}=1; seed::Union{Int, Nothing}=nothing)\n    n = ceil(Int, λ*5)  # ensure n is integer\n    U = expon_rng(λ, (shape..., n), seed=seed)\n    X = sum(cumsum(U, dims=ndims(U)) .< 1, dims=ndims(U))\n    return X\nend\n", "meta": {"hexsha": "ffc187930677f31a70eaddb6fe657de886e229e2", "size": 1051, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/poisson.jl", "max_stars_repo_name": "chris-santiago/RandomVariates.jl", "max_stars_repo_head_hexsha": "75cf7057d06482f5208233f0f78f08e0dcfee58f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/poisson.jl", "max_issues_repo_name": "chris-santiago/RandomVariates.jl", "max_issues_repo_head_hexsha": "75cf7057d06482f5208233f0f78f08e0dcfee58f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/poisson.jl", "max_forks_repo_name": "chris-santiago/RandomVariates.jl", "max_forks_repo_head_hexsha": "75cf7057d06482f5208233f0f78f08e0dcfee58f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.02, "max_line_length": 126, "alphanum_fraction": 0.6279733587, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7779662927910075}}
{"text": "immutable Beta <: ContinuousUnivariateDistribution\n    α::Float64\n    β::Float64\n\n    function Beta(a::Real, b::Real)\n        (a > zero(a) && b > zero(b)) || error(\"α and β must be positive\")\n        new(float64(a), float64(b))\n    end\n\n    Beta(α::Real) = Beta(α, α)\n    Beta() = new(1.0, 1.0)\nend\n\n@_jl_dist_2p Beta beta\n\n@distr_support Beta 0.0 1.0\n\n\n#### Parameters\n\nparams(d::Beta) = (d.α, d.β)\n\n\n#### Statistics\n\nmean(d::Beta) = ((α, β) = params(d); α / (α + β)) \n\nfunction mode(d::Beta)\n    (α, β) = params(d)\n    (α > 1.0 && β > 1.0) || error(\"mode is defined only when α > 1 and β > 1.\")\n    return (α - 1.0) / (α + β - 2.0)\nend\n\nmodes(d::Beta) = [mode(d)]\n\nfunction var(d::Beta)\n    (α, β) = params(d)\n    s = α + β\n    return (α * β) / (abs2(s) * (s + 1.0))\nend\n\nmeanlogx(d::Beta) = ((α, β) = params(d); digamma(α) - digamma(α + β))\n\nvarlogx(d::Beta) = ((α, β) = params(d); trigamma(α) - trigamma(α + β))\n\nfunction skewness(d::Beta)\n    (α, β) = params(d)\n    if α == β\n        return 0.0\n    else\n        s = α + β\n        (2.0 * (β - α) * sqrt(s + 1.0)) / ((s + 2.0) * sqrt(α * β))\n    end\nend\n\nfunction kurtosis(d::Beta)\n    α, β = params(d)\n    s = α + β\n    p = α * β\n    6.0 * (abs2(α - β) * (s + 1.0) - p * (s + 2.0)) / (p * (s + 2.0) * (s + 3.0))\nend\n\nfunction entropy(d::Beta)\n    α, β = params(d)\n    s = α + β\n    lbeta(α, β) - (α - 1.0) * digamma(α) - (β - 1.0) * digamma(β) + \n        (s - 2.0) * digamma(s)\nend\n\n\n#### Evaluation\n\ngradlogpdf(d::Beta, x::Float64) = \n    ((α, β) = params(d); 0.0 <= x <= 1.0 ? (α - 1.0) / x - (β - 1.0) / (1 - x) : 0.0)\n\n\n## Fit model\n\n# TODO: add MLE method (should be similar to Dirichlet)\n\n# This is a moment-matching method (not MLE)\n#\nfunction fit(::Type{Beta}, x::AbstractArray)\n    x_bar = mean(x)\n    v_bar = varm(x, x_bar)\n    α = x_bar * (((x_bar * (1.0 - x_bar)) / v_bar) - 1.0)\n    β = (1.0 - x_bar) * (((x_bar * (1.0 - x_bar)) / v_bar) - 1.0)\n    Beta(α, β)\nend\n\n\n", "meta": {"hexsha": "039fb61c4e59cbfdc110d4e12a054e3725ce5846", "size": 1933, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/beta.jl", "max_stars_repo_name": "davidanthoff/Distributions.jl", "max_stars_repo_head_hexsha": "75a04ebc12f3643392d33240a4029d458f86e7f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-11T18:43:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T18:43:39.000Z", "max_issues_repo_path": "src/univariate/continuous/beta.jl", "max_issues_repo_name": "davidanthoff/Distributions.jl", "max_issues_repo_head_hexsha": "75a04ebc12f3643392d33240a4029d458f86e7f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/beta.jl", "max_forks_repo_name": "davidanthoff/Distributions.jl", "max_forks_repo_head_hexsha": "75a04ebc12f3643392d33240a4029d458f86e7f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0108695652, "max_line_length": 85, "alphanum_fraction": 0.4961200207, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7779662839222068}}
{"text": "import Healpix\nexport std2fwhm, fwhm2std, gaussian_beam\n\n@doc raw\"\"\"\n    std2fwhm(stddev)\n\nConvert a standard deviation into a Full Width Half Maximum (FWHM) value. The\nmeasure unit for `stddev` can be arbitrary, as the transformation is linear.\nSee also `fwhm2std`.\n\"\"\"\nstd2fwhm(stddev) = 2 * sqrt(2 * log(2)) * stddev\n\n@doc raw\"\"\"\n    std2fwhm(stddev)\n\nConvert a standard deviation into a Full Width Half Maximum (FWHM) value. The\nmeasure unit for `stddev` can be arbitrary, as the transformation is linear.\nSee also `std2fwhm`.\n\"\"\"\nfwhm2std(fwhm) = fwhm / (2 * sqrt(2 * log(2)))\n\n@doc raw\"\"\"\n    gaussian_beam!(beam_map::Healpix.Map{T,O}, angle_std_rad; normalization = 1.0) where {T,O <: Healpix.Order}\n\nSave a map of a circual Gaussian beam in `beam_map`. The width of the beam is\nprovided through the parameter `angle_std_rad`, which is expressed in radians.\nIf you want to specify the FWHM instead, use `fwhm2std` like in the following\nexample:\n\n````julia\nimport Healpix\nnside = 1024\nbeam_map = Healpix.Map{Float64, RingOrder}(nside)\n\n# Assume 2.5° of FWHM\ngaussian_beam!(beam_map, 2.5 |> fwhm2std)\n````\n\nSee also `gaussian_beam`.\n\"\"\"\nfunction gaussian_beam!(beam_map::Healpix.Map{T,O}, angle_std_rad; normalization = 1.0) where {T,O <: Healpix.Order}\n    for pixidx in 1:beam_map.resolution.numOfPixels\n        theta, _ = Healpix.pix2ang(beam_map, pixidx)\n        beam_map[pixidx] = normalization * exp(-theta^2 / (2 * angle_std_rad))\n    end\nend\n\nfunction gaussian_beam(nside::Integer, angle_std_rad; normalization = 1.0)\n    beam_map = Healpix.Map{Float64,Healpix.RingOrder}(nside)\n    gaussian_beam!(beam_map, angle_std_rad, normalization = normalization)\n\n    beam_map\nend\n\nfunction gaussian_beam(res::Healpix.Resolution, angle_std_rad; normalization = 1.0)\n    gaussian_beam(res.nside, angle_std_rad, normalization = normalization)\nend\n\n@doc raw\"\"\"\n    gaussian_beam(res::Healpix.Resolution, angle_std_rad; normalization = 1.0) where {T,O <: Healpix.Order}\n    gaussian_beam(nside::Integer, angle_std_rad; normalization = 1.0) where {T,O <: Healpix.Order}\n\nSave a map of a circual Gaussian beam in `beam_map`. The width of the beam is\nprovided through the parameter `angle_std_rad`, which is expressed in radians.\nIf you want to specify the FWHM instead, use `fwhm2std` like in the following\nexample:\n\n````julia\n# Assume 2.5° of FWHM\nbeam_map = gaussian_beam(1024, 2.5 |> fwhm2std)\n````\n\nSee also `gaussian_beam!`.\n\"\"\"\ngaussian_beam\n\nstruct BeamMoments\n    S::Array{Float32,1}\n    M::Array{Float32,2}\nend\n\n@doc raw\"\"\"\n\n    beam_m(beam_map, l, m, n)\n\nCalculate the moment `(l, m, n)` of the beam in the Healpix map `beam_map`. Beam\nmoments are defined in Appendix A of the paper \"Planck 2013 results. LFI\ncalibration\" (Planck collaboration, A&A, 2013),\nhttps://dx.doi.org/10.1051/0004-6361/201321527.\n\nThis function does not take into account the factor `N` (normalization of the beam).\nYou can compute it using `beam_m(beam_map, 0, 0, 0)`.\n\n\"\"\"\nfunction beam_m(beam_map, l::Integer, m::Integer, n::Integer)\n    result = 0.0\n    for idx in 1:length(beam_map)\n        θ, ϕ = Healpix.pix2ang(beam_map, idx)\n\n        # We could have used `Healpix.ang2vec`, but we need the value\n        # of sinθ in order to calculate dΩ = sinθ⋅dθ⋅dϕ\n        sinθ, cosθ = sincos(θ)\n        sinϕ, cosϕ = sincos(ϕ)\n        \n        x = sinθ * cosϕ\n        y = sinθ * sinϕ\n        z = cosθ\n        \n        result += x^l * y^m * z^n * sinθ * beam_map[idx]\n    end\n    result\nend\n\nfunction beam_moments(beam_map)\n    N = beam_m(beam_map, 0, 0, 0)\n\n    S = [\n        beam_m(beam_map, 1, 0, 0) / N,\n        beam_m(beam_map, 0, 1, 0) / N,\n        beam_m(beam_map, 0, 0, 1) / N,\n    ]\n\n    M = [\n        [(beam_m(beam_map, 2, 0, 0) / N)  (beam_m(beam_map, 1, 1, 0) / N)  (beam_m(beam_map, 1, 0, 1) / N)];\n        [(beam_m(beam_map, 1, 1, 0) / N)  (beam_m(beam_map, 0, 2, 0) / N)  (beam_m(beam_map, 0, 1, 1) / N)];\n        [(beam_m(beam_map, 1, 0, 1) / N)  (beam_m(beam_map, 0, 1, 1) / N)  (beam_m(beam_map, 0, 0, 2) / N)];\n    ]\n\n    BeamMoments(S, M)\nend", "meta": {"hexsha": "c46f4919adc9626d085e3f701af80c4155fe4a15", "size": 4040, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/beams.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Harlequin.jl-af1cbc52-b994-11e9-036a-87a15c7b4bde", "max_stars_repo_head_hexsha": "e9b94de197c69e904723c63559ff81ac9bb95c85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/beams.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Harlequin.jl-af1cbc52-b994-11e9-036a-87a15c7b4bde", "max_issues_repo_head_hexsha": "e9b94de197c69e904723c63559ff81ac9bb95c85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-08-08T16:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T15:41:44.000Z", "max_forks_repo_path": "src/beams.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Harlequin.jl-af1cbc52-b994-11e9-036a-87a15c7b4bde", "max_forks_repo_head_hexsha": "e9b94de197c69e904723c63559ff81ac9bb95c85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:21:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:21:46.000Z", "avg_line_length": 31.0769230769, "max_line_length": 116, "alphanum_fraction": 0.6712871287, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7779662820136897}}
{"text": "# indicator of the L2 norm sphere with given radius\n\nexport IndSphereL2\n\n\"\"\"\n**Indicator of a Euclidean sphere**\n\n    IndSphereL2(r=1.0)\n\nReturns the indicator function of the set\n```math\nS = \\\\{ x : \\\\|x\\\\| = r \\\\},\n```\nwhere ``\\\\|\\\\cdot\\\\|`` is the ``L_2`` (Euclidean) norm. Parameter `r` must be positive.\n\"\"\"\nstruct IndSphereL2{R <: Real} <: ProximableFunction\n    r::R\n    function IndSphereL2{R}(r::R) where {R <: Real}\n        if r <= 0\n            error(\"parameter r must be positive\")\n        else\n            new(r)\n        end\n    end\nend\n\nis_set(f::IndSphereL2) = true\n\nIndSphereL2(r::R=1.0) where {R <: Real} = IndSphereL2{R}(r)\n\nfunction (f::IndSphereL2)(x::AbstractArray{T}) where {R <: Real, T <: RealOrComplex{R}}\n    if isapprox(norm(x), f.r, atol=eps(R), rtol=sqrt(eps(R)))\n        return R(0)\n    end\n    return R(Inf)\nend\n\nfunction prox!(y::AbstractArray{T}, f::IndSphereL2, x::AbstractArray{T}, gamma::R=R(1)) where {R <: Real, T <: RealOrComplex{R}}\n    normx = norm(x)\n    if normx > 0 # zero-zero?\n        scal = f.r/normx\n        for k in eachindex(x)\n            y[k] = scal*x[k]\n        end\n    else\n        normy = R(0)\n        for k in eachindex(x)\n            y[k] = randn()\n            normy += y[k]*y[k]\n        end\n        normy = sqrt(normy)\n        y .*= f.r/normy\n    end\n    return R(0)\nend\n\nfun_name(f::IndSphereL2) = \"indicator of an L2 norm sphere\"\nfun_dom(f::IndSphereL2) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::IndSphereL2) = \"x ↦ 0 if ||x|| = r, +∞ otherwise\"\nfun_params(f::IndSphereL2) = \"r = $(f.r)\"\n\nfunction prox_naive(f::IndSphereL2, x::AbstractArray{T}, gamma::R=R(1)) where {R <: Real, T <: RealOrComplex{R}}\n    normx = norm(x)\n    if normx > 0\n        y = x*f.r/normx\n    else\n        y = randn(size(x))\n        y *= f.r/norm(y)\n    end\n    return y, R(0)\nend\n", "meta": {"hexsha": "200d4d30cf0be2f6fec1e3e6fbccd4d920d4f7e3", "size": 1833, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indSphereL2.jl", "max_stars_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_stars_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2016-10-29T12:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:11:52.000Z", "max_issues_repo_path": "src/functions/indSphereL2.jl", "max_issues_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_issues_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2016-10-26T16:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T20:38:48.000Z", "max_forks_repo_path": "src/functions/indSphereL2.jl", "max_forks_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_forks_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T10:40:24.000Z", "avg_line_length": 25.4583333333, "max_line_length": 128, "alphanum_fraction": 0.5662847791, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7779646441227613}}
{"text": "export MoreauEnvelope\n\n\"\"\"\n**Moreau envelope**\n\n    MoreauEnvelope(f, γ=1.0)\n\nReturns the Moreau envelope (also known as Moreau-Yosida regularization) of function `f` with parameter `γ` (positive), that is\n```math\nf^γ(x) = \\\\min_z \\\\left\\\\{ f(z) + \\\\tfrac{1}{2γ}\\\\|z-x\\\\|^2 \\\\right\\\\}.\n```\nIf ``f`` is convex, then ``f^γ`` is a smooth, convex, lower approximation to ``f``, having the same minima as the original function.\n\"\"\"\nmutable struct MoreauEnvelope{R <: Real, T <: ProximableFunction} <: ProximableFunction\n    g::T\n    lambda::R\n    function MoreauEnvelope{R, T}(g::T, lambda::R) where {R, T}\n        if lambda <= 0 error(\"parameter lambda must be positive\") end\n        new(g, lambda)\n    end\nend\n\nMoreauEnvelope(g::T, lambda::R=1.0) where {R <: Real, T <: ProximableFunction} = MoreauEnvelope{R, T}(g, lambda)\n\nis_convex(f::MoreauEnvelope) = is_convex(f.g)\nis_smooth(f::MoreauEnvelope) = is_convex(f.g)\nis_quadratic(f::MoreauEnvelope) = is_generalized_quadratic(f.g)\nis_strongly_convex(f::MoreauEnvelope) = is_strongly_convex(f.g)\n\nfunction (f::MoreauEnvelope)(x::AbstractArray)\n    buf = similar(x)\n    g_prox = prox!(buf, f.g, x, f.lambda)\n    return g_prox + 1/(2*f.lambda)*norm(buf .- x)^2\nend\n\nfunction gradient!(grad::AbstractArray, f::MoreauEnvelope, x::AbstractArray)\n    g_prox = prox!(grad, f.g, x, f.lambda)\n    grad .= (x .- grad)./f.lambda\n    fx = g_prox + (f.lambda/2)*norm(grad)^2\n    return fx\nend\n\nfun_name(f::MoreauEnvelope,i::Int64) =\n\"f$(i)(prox{λ$(i),f$(i)}(A$(i)x))+ 1/2 ‖x - prox{λ$(i),f$(i)}(A$(i)x)‖²\"\n\nfun_par( f::MoreauEnvelope,i::Int64)  = \"λ$i = $(round(f.lambda, digits=3))\"\n", "meta": {"hexsha": "567b5efa17d071096a63d30f60df0cdc712bec58", "size": 1617, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/calculus/moreauEnvelope.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_stars_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/calculus/moreauEnvelope.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_issues_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/calculus/moreauEnvelope.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_forks_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4042553191, "max_line_length": 132, "alphanum_fraction": 0.6555349412, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7779646422596609}}
{"text": "# This script provides implementations of\n# multi-step methods of different orders\n# for solving a system of differential equations\n# and compares them to the exact solutions and\n# other methods while solving a 1-body problem\n\nprintln('\\n', \" \"^4, \"> Loading the packages...\")\n\nusing LinearAlgebra\nusing Printf\n\n# Define the value of ϰ\nconst ϰ = -1\n\n# Integrate equations of motion using the\n# Euler's method, return the values of position\n# and velocity on the last step\nfunction euler(\n    r₀₁::Vector{F},\n    r₀₂::Vector{F},\n    r₀₃::Vector{F},\n    v₀₁::Vector{F},\n    v₀₂::Vector{F},\n    v₀₃::Vector{F},\n    h::F,\n    n::I,\n)::Tuple{Vector{F},Vector{F},Vector{F},Vector{F},Vector{F},Vector{F}} where\n{F <: AbstractFloat,I <: Unsigned}\n    # Determine the length of the input vectors\n    N = length(r₀₁)\n    # Prepare the output vectors\n    r₁ = copy(r₀₁)\n    r₂ = copy(r₀₂)\n    r₃ = copy(r₀₃)\n    v₁ = copy(v₀₁)\n    v₂ = copy(v₀₂)\n    v₃ = copy(v₀₃)\n    # Compute the solutions (in-place)\n    for _ in 1:n\n        ρ₁₂ = norm(r₁ - r₂)^3\n        ρ₁₃ = norm(r₁ - r₃)^3\n        ρ₂₃ = norm(r₂ - r₃)^3\n        for k in 1:N\n            a₁₂ = ϰ * (r₁[k] - r₂[k]) / ρ₁₂\n            a₁₃ = ϰ * (r₁[k] - r₃[k]) / ρ₁₃\n            a₂₃ = ϰ * (r₂[k] - r₃[k]) / ρ₂₃\n            a₂₁ = -a₁₂\n            a₃₁ = -a₁₃\n            a₃₂ = -a₂₃\n            r₁[k] += h * v₁[k]\n            r₂[k] += h * v₂[k]\n            r₃[k] += h * v₃[k]\n            v₁[k] += h * (a₁₂ + a₁₃)\n            v₂[k] += h * (a₂₁ + a₂₃)\n            v₃[k] += h * (a₃₁ + a₃₂)\n        end\n    end\n    return r₁, r₂, r₃, v₁, v₂, v₃\nend\n\n# Integrate the three-body problem using the\n# two-step Adams–Bashforth's method, return the\n# values of position and velocity on the last step\nfunction ab2(\n    r₀₁::Vector{F},\n    r₀₂::Vector{F},\n    r₀₃::Vector{F},\n    v₀₁::Vector{F},\n    v₀₂::Vector{F},\n    v₀₃::Vector{F},\n    h::F,\n    n::I,\n)::Tuple{Vector{F},Vector{F},Vector{F},Vector{F},Vector{F},Vector{F}} where\n{F <: AbstractFloat,I <: Unsigned}\n    # Determine the length of the input vectors\n    N = length(r₀₁)\n    # Prepare the output vectors\n    r₁ = copy(r₀₁)\n    r₂ = copy(r₀₂)\n    r₃ = copy(r₀₃)\n    v₁ = copy(v₀₁)\n    v₂ = copy(v₀₂)\n    v₃ = copy(v₀₃)\n    # Prepare buffers for previous values\n    r₁_ₖ₋₁ = copy(r₀₁)\n    r₂_ₖ₋₁ = copy(r₀₂)\n    r₃_ₖ₋₁ = copy(r₀₃)\n    v₁_ₖ₋₁ = copy(v₀₁)\n    v₂_ₖ₋₁ = copy(v₀₂)\n    v₃_ₖ₋₁ = copy(v₀₃)\n    # Compute the second value of the solution\n    # by using the one-step Euler's method\n    r₁, r₂, r₃, v₁, v₂, v₃ = euler(r₀₁, r₀₂, r₀₃, v₀₁, v₀₂, v₀₃, h, UInt(1))\n    # Define a couple of independent coefficients\n    k₁ = 3 / 2 * h\n    k₂ = -1 / 2 * h\n    # Compute the rest in two steps\n    for _ in 2:n\n        ρ₁₂_ₖ = norm(r₁ - r₂)^3\n        ρ₁₃_ₖ = norm(r₁ - r₃)^3\n        ρ₂₃_ₖ = norm(r₂ - r₃)^3\n        ρ₁₂_ₖ₋₁ = norm(r₁_ₖ₋₁ - r₂_ₖ₋₁)^3\n        ρ₁₃_ₖ₋₁ = norm(r₁_ₖ₋₁ - r₃_ₖ₋₁)^3\n        ρ₂₃_ₖ₋₁ = norm(r₂_ₖ₋₁ - r₃_ₖ₋₁)^3\n        for k in 1:N\n            a₁₂_ₖ = k₁ * ϰ * (r₁[k] - r₂[k]) / ρ₁₂_ₖ\n            a₁₃_ₖ = k₁ * ϰ * (r₁[k] - r₃[k]) / ρ₁₃_ₖ\n            a₂₃_ₖ = k₁ * ϰ * (r₂[k] - r₃[k]) / ρ₂₃_ₖ\n            a₁₂_ₖ₋₁ = k₂ * ϰ * (r₁_ₖ₋₁[k] - r₂_ₖ₋₁[k]) / ρ₁₂_ₖ₋₁\n            a₁₃_ₖ₋₁ = k₂ * ϰ * (r₁_ₖ₋₁[k] - r₃_ₖ₋₁[k]) / ρ₁₃_ₖ₋₁\n            a₂₃_ₖ₋₁ = k₂ * ϰ * (r₂_ₖ₋₁[k] - r₃_ₖ₋₁[k]) / ρ₂₃_ₖ₋₁\n\n            a₂₁_ₖ = -a₁₂_ₖ\n            a₃₁_ₖ = -a₁₃_ₖ\n            a₃₂_ₖ = -a₂₃_ₖ\n            a₂₁_ₖ₋₁ = -a₁₂_ₖ₋₁\n            a₃₁_ₖ₋₁ = -a₁₃_ₖ₋₁\n            a₃₂_ₖ₋₁ = -a₂₃_ₖ₋₁\n\n            r₁_ₖ₋₁[k] = r₁[k]\n            r₂_ₖ₋₁[k] = r₂[k]\n            r₃_ₖ₋₁[k] = r₃[k]\n\n            r₁[k] += k₁ * v₁[k] + k₂ * v₁_ₖ₋₁[k]\n            r₂[k] += k₁ * v₂[k] + k₂ * v₂_ₖ₋₁[k]\n            r₃[k] += k₁ * v₃[k] + k₂ * v₃_ₖ₋₁[k]\n\n            v₁_ₖ₋₁[k] = v₁[k]\n            v₂_ₖ₋₁[k] = v₂[k]\n            v₃_ₖ₋₁[k] = v₃[k]\n\n            v₁[k] += a₁₂_ₖ + a₁₃_ₖ + a₁₂_ₖ₋₁ + a₁₃_ₖ₋₁\n            v₂[k] += a₂₁_ₖ + a₂₃_ₖ + a₂₁_ₖ₋₁ + a₂₃_ₖ₋₁\n            v₃[k] += a₃₁_ₖ + a₃₂_ₖ + a₃₁_ₖ₋₁ + a₃₂_ₖ₋₁\n        end\n    end\n    return r₁, r₂, r₃, v₁, v₂, v₃\nend\n\n# Integrate the three-body problem using the\n# three-step Adams–Bashforth's method, return the\n# values of position and velocity on the last step\nfunction ab3(\n    r₀₁::Vector{F},\n    r₀₂::Vector{F},\n    r₀₃::Vector{F},\n    v₀₁::Vector{F},\n    v₀₂::Vector{F},\n    v₀₃::Vector{F},\n    h::F,\n    n::I,\n)::Tuple{Vector{F},Vector{F},Vector{F},Vector{F},Vector{F},Vector{F}} where\n{F <: AbstractFloat,I <: Unsigned}\n    # Determine the length of the input vectors\n    N = length(r₀₁)\n    # Prepare the output vectors\n    r₁ = copy(r₀₁)\n    r₂ = copy(r₀₂)\n    r₃ = copy(r₀₃)\n    v₁ = copy(v₀₁)\n    v₂ = copy(v₀₂)\n    v₃ = copy(v₀₃)\n    # Prepare buffers for previous values\n    r₁_ₖ₋₁ = copy(r₀₁)\n    r₂_ₖ₋₁ = copy(r₀₂)\n    r₃_ₖ₋₁ = copy(r₀₃)\n    v₁_ₖ₋₁ = copy(v₀₁)\n    v₂_ₖ₋₁ = copy(v₀₂)\n    v₃_ₖ₋₁ = copy(v₀₃)\n    r₁_ₖ₋₂ = copy(r₀₁)\n    r₂_ₖ₋₂ = copy(r₀₂)\n    r₃_ₖ₋₂ = copy(r₀₃)\n    v₁_ₖ₋₂ = copy(v₀₁)\n    v₂_ₖ₋₂ = copy(v₀₂)\n    v₃_ₖ₋₂ = copy(v₀₃)\n    # Compute the second value of the solution\n    # by using the one-step Euler's method\n    r₁, r₂, r₃, v₁, v₂, v₃ = euler(r₀₁, r₀₂, r₀₃, v₀₁, v₀₂, v₀₃, h, UInt(1))\n    # Compute the third value of the solution\n    # by using the two-step Adams–Bashforth's method\n    r₁_ₖ₋₁, r₂_ₖ₋₁, r₃_ₖ₋₁, v₁_ₖ₋₁, v₂_ₖ₋₁, v₃_ₖ₋₁ = r₁, r₂, r₃, v₁, v₂, v₃\n    r₁, r₂, r₃, v₁, v₂, v₃ = ab2(r₀₁, r₀₂, r₀₃, v₀₁, v₀₂, v₀₃, h, UInt(2))\n    # Define a couple of independent coefficients\n    k₁ = 23 / 12 * h\n    k₂ = -4 / 3 * h\n    k₃ = 5 / 12 * h\n    # Compute the rest in two steps\n    for _ in 3:n\n        ρ₁₂_ₖ = norm(r₁ - r₂)^3\n        ρ₁₃_ₖ = norm(r₁ - r₃)^3\n        ρ₂₃_ₖ = norm(r₂ - r₃)^3\n        ρ₁₂_ₖ₋₁ = norm(r₁_ₖ₋₁ - r₂_ₖ₋₁)^3\n        ρ₁₃_ₖ₋₁ = norm(r₁_ₖ₋₁ - r₃_ₖ₋₁)^3\n        ρ₂₃_ₖ₋₁ = norm(r₂_ₖ₋₁ - r₃_ₖ₋₁)^3\n        ρ₁₂_ₖ₋₂ = norm(r₁_ₖ₋₂ - r₂_ₖ₋₂)^3\n        ρ₁₃_ₖ₋₂ = norm(r₁_ₖ₋₂ - r₃_ₖ₋₂)^3\n        ρ₂₃_ₖ₋₂ = norm(r₂_ₖ₋₂ - r₃_ₖ₋₂)^3\n        for k in 1:N\n            a₁₂_ₖ = k₁ * ϰ * (r₁[k] - r₂[k]) / ρ₁₂_ₖ\n            a₁₃_ₖ = k₁ * ϰ * (r₁[k] - r₃[k]) / ρ₁₃_ₖ\n            a₂₃_ₖ = k₁ * ϰ * (r₂[k] - r₃[k]) / ρ₂₃_ₖ\n            a₁₂_ₖ₋₁ = k₂ * ϰ * (r₁_ₖ₋₁[k] - r₂_ₖ₋₁[k]) / ρ₁₂_ₖ₋₁\n            a₁₃_ₖ₋₁ = k₂ * ϰ * (r₁_ₖ₋₁[k] - r₃_ₖ₋₁[k]) / ρ₁₃_ₖ₋₁\n            a₂₃_ₖ₋₁ = k₂ * ϰ * (r₂_ₖ₋₁[k] - r₃_ₖ₋₁[k]) / ρ₂₃_ₖ₋₁\n            a₁₂_ₖ₋₂ = k₃ * ϰ * (r₁_ₖ₋₂[k] - r₂_ₖ₋₂[k]) / ρ₁₂_ₖ₋₂\n            a₁₃_ₖ₋₂ = k₃ * ϰ * (r₁_ₖ₋₂[k] - r₃_ₖ₋₂[k]) / ρ₁₃_ₖ₋₂\n            a₂₃_ₖ₋₂ = k₃ * ϰ * (r₂_ₖ₋₂[k] - r₃_ₖ₋₂[k]) / ρ₂₃_ₖ₋₂\n\n            a₂₁_ₖ = -a₁₂_ₖ\n            a₃₁_ₖ = -a₁₃_ₖ\n            a₃₂_ₖ = -a₂₃_ₖ\n            a₂₁_ₖ₋₁ = -a₁₂_ₖ₋₁\n            a₃₁_ₖ₋₁ = -a₁₃_ₖ₋₁\n            a₃₂_ₖ₋₁ = -a₂₃_ₖ₋₁\n            a₂₁_ₖ₋₂ = -a₁₂_ₖ₋₂\n            a₃₁_ₖ₋₂ = -a₁₃_ₖ₋₂\n            a₃₂_ₖ₋₂ = -a₂₃_ₖ₋₂\n\n            r₁_ₖ₋₂[k] = r₁_ₖ₋₁[k]\n            r₂_ₖ₋₂[k] = r₂_ₖ₋₁[k]\n            r₃_ₖ₋₂[k] = r₃_ₖ₋₁[k]\n            r₁_ₖ₋₁[k] = r₁[k]\n            r₂_ₖ₋₁[k] = r₂[k]\n            r₃_ₖ₋₁[k] = r₃[k]\n\n            r₁[k] += k₁ * v₁[k] + k₂ * v₁_ₖ₋₁[k] + k₃ * v₁_ₖ₋₂[k]\n            r₂[k] += k₁ * v₂[k] + k₂ * v₂_ₖ₋₁[k] + k₃ * v₂_ₖ₋₂[k]\n            r₃[k] += k₁ * v₃[k] + k₂ * v₃_ₖ₋₁[k] + k₃ * v₃_ₖ₋₂[k]\n\n            v₁_ₖ₋₂[k] = v₁_ₖ₋₁[k]\n            v₂_ₖ₋₂[k] = v₂_ₖ₋₁[k]\n            v₃_ₖ₋₂[k] = v₃_ₖ₋₁[k]\n            v₁_ₖ₋₁[k] = v₁[k]\n            v₂_ₖ₋₁[k] = v₂[k]\n            v₃_ₖ₋₁[k] = v₃[k]\n\n            v₁[k] += a₁₂_ₖ + a₁₃_ₖ + a₁₂_ₖ₋₁ + a₁₃_ₖ₋₁ + a₁₂_ₖ₋₂ + a₁₃_ₖ₋₂\n            v₂[k] += a₂₁_ₖ + a₂₃_ₖ + a₂₁_ₖ₋₁ + a₂₃_ₖ₋₁ + a₂₁_ₖ₋₂ + a₂₃_ₖ₋₂\n            v₃[k] += a₃₁_ₖ + a₃₂_ₖ + a₃₁_ₖ₋₁ + a₃₂_ₖ₋₁ + a₃₁_ₖ₋₂ + a₃₂_ₖ₋₂\n        end\n    end\n    return r₁, r₂, r₃, v₁, v₂, v₃\nend\n\nprintln(\" \"^4, \"> Integrating the 3-body problem...\")\n\n# Define the initial values of the position and velocity\nr₀₁ = [0.97, -0.2431]\nr₀₂ = [-0.97, 0.2431]\nr₀₃ = [0.0, 0.0]\nv₀₁ = [0.4662, 0.4324]\nv₀₂ = [0.4662, 0.4324]\nv₀₃ = [-0.9324, -0.8647]\n\n# Calculate total energy\nE₀ = 1 / 2 * (norm(v₀₁)^2 + norm(v₀₂)^2 + norm(v₀₃)^2) - ϰ^2 *\n    (1 / norm(r₀₁ - r₀₂) + 1 / norm(r₀₃ - r₀₂) + 1 / norm(r₀₃ - r₀₁))\n\n# Print the initial values\nprintln(\n    '\\n',\n    \" \"^6, \"r₀₁: \", r₀₁[1], \" \", r₀₁[2], '\\n',\n    \" \"^6, \"r₀₂: \", r₀₂[1], \" \", r₀₂[2], '\\n',\n    \" \"^6, \"r₀₃: \", r₀₃[1], \" \", r₀₃[2], '\\n',\n    \" \"^6, \"v₀₁: \", v₀₁[1], \" \", v₀₁[2], '\\n',\n    \" \"^6, \"v₀₂: \", v₀₂[1], \" \", v₀₂[2], '\\n',\n    \" \"^6, \"v₀₃: \", v₀₃[1], \" \", v₀₃[2], '\\n',\n    \" \"^6, \"E₀: \", E₀,\n)\n\n# Define the output directories\nconst data_dir = \"$(@__DIR__)/../data/3-body\"\nconst files = joinpath.(\n    data_dir,\n    [\n        \"euler.dat\",\n        \"ab2.dat\",\n        \"ab3.dat\",\n    ]\n)\n\n# Prepare a list of methods\nconst methods = (euler, ab2, ab3)\n\n# Integrate equations of motion using all available\n# methods and write the values of position and velocity\n# on the last step\nfunction integrate(h::Vector{F}, n::Vector{I}) where {F <: AbstractFloat,I <: Unsigned}\n    # Open the data files\n    io = open.(files, \"a\")\n\n    # Prepare results vectors\n\n    r₁ = [ Vector{Vector{F}}() for _ in 1:length(io) ]\n    r₂ = [ Vector{Vector{F}}() for _ in 1:length(io) ]\n    r₃ = [ Vector{Vector{F}}() for _ in 1:length(io) ]\n    v₁ = [ Vector{Vector{F}}() for _ in 1:length(io) ]\n    v₂ = [ Vector{Vector{F}}() for _ in 1:length(io) ]\n    v₃ = [ Vector{Vector{F}}() for _ in 1:length(io) ]\n\n    E = [ Vector{F}() for _ in 1:length(io) ]\n    ΔE = [ Vector{F}() for _ in 1:length(io) ]\n\n    # For each pair of parameters\n    for i in eachindex(h)\n        # Integrate and get the results of the last steps\n        for j in eachindex(io)\n            rᵢ₁, rᵢ₂, rᵢ₃, vᵢ₁, vᵢ₂, vᵢ₃ = methods[j](r₀₁, r₀₂, r₀₃, v₀₁, v₀₂, v₀₃, h[i], n[i])\n\n            push!(r₁[j], rᵢ₁)\n            push!(r₂[j], rᵢ₂)\n            push!(r₃[j], rᵢ₃)\n            push!(v₁[j], vᵢ₁)\n            push!(v₂[j], vᵢ₂)\n            push!(v₃[j], vᵢ₃)\n\n            Eᵢ = 1 / 2 * (norm(vᵢ₁)^2 + norm(vᵢ₂)^2 + norm(vᵢ₃)^2) - ϰ^2 *\n                (1 / norm(rᵢ₁ - rᵢ₂) + 1 / norm(rᵢ₃ - rᵢ₂) + 1 / norm(rᵢ₃ - rᵢ₁))\n            ΔEᵢ = abs(E₀ - Eᵢ)\n\n            push!(E[j], Eᵢ)\n            push!(ΔE[j], ΔEᵢ)\n        end\n    end\n\n    # Get the format string based on the index of the iteration\n    function get_format(i)\n        Printf.Format(\n            \"\\$ 10^{-$(length(\"$(n[i])\") - 1)} \\$ \" *\n            \"& \\$ $(n[i] % 10 == 0 ? \"10^$(length(\"$(n[i])\") - 1)\" : n[i]) \\$ \" *\n            \"& \\$ %.14f \\$ \" *\n            \"& \\$ %.14f \\$ \" *\n            \"\\\\\\\\\\n\"\n        )\n    end\n\n    # Print the data in the files in the LaTeX format\n\n    for j in eachindex(io)\n        println(io[j], \"# Positions #1\")\n        for i in eachindex(h)\n            Printf.format(io[j], get_format(i), r₁[j][i][1], r₁[j][i][2])\n        end\n    end\n\n    for j in eachindex(io)\n        println(io[j], \"\\n# Positions #2\")\n        for i in eachindex(h)\n            Printf.format(io[j], get_format(i), r₂[j][i][1], r₂[j][i][2])\n        end\n    end\n\n    for j in eachindex(io)\n        println(io[j], \"\\n# Positions #3\")\n        for i in eachindex(h)\n            Printf.format(io[j], get_format(i), r₃[j][i][1], r₃[j][i][2])\n        end\n    end\n\n    for j in eachindex(io)\n        println(io[j], \"\\n# Velocities #1\")\n        for i in eachindex(h)\n            Printf.format(io[j], get_format(i),  v₁[j][i][1], v₁[j][i][2])\n        end\n    end\n\n    for j in eachindex(io)\n        println(io[j], \"\\n# Velocities #2\")\n        for i in eachindex(h)\n            Printf.format(io[j], get_format(i),  v₂[j][i][1], v₂[j][i][2])\n        end\n    end\n\n    for j in eachindex(io)\n        println(io[j], \"\\n# Velocities #3\")\n        for i in eachindex(h)\n            Printf.format(io[j], get_format(i),  v₃[j][i][1], v₃[j][i][2])\n        end\n    end\n\n    for j in eachindex(io)\n        println(io[j], \"\\n# Total energy\")\n        for i in eachindex(h)\n            Printf.format(io[j], get_format(i), E[j][i], ΔE[j][i])\n        end\n        println(io[j])\n        close(io[j])\n    end\nend\n\n# Truncate the previous results\nopen.(files; truncate=true)\n\n# Integrate n = 2^m iterations\nintegrate(\n    [1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7],\n    UInt.([ 10^i for i in 2:7 ]),\n)\n\nprintln()\n", "meta": {"hexsha": "a9f69265db0673f9c824875f5c188f397db326d5", "size": 12047, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Adam's/scripts/3-body.jl", "max_stars_repo_name": "paveloom-university/Computer-Methods-of-Celestial-Mechanics-S09-2021", "max_stars_repo_head_hexsha": "a650c76d6f299c20bbe82e98dd0708ef97a35f65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Adam's/scripts/3-body.jl", "max_issues_repo_name": "paveloom-university/Computer-Methods-of-Celestial-Mechanics-S09-2021", "max_issues_repo_head_hexsha": "a650c76d6f299c20bbe82e98dd0708ef97a35f65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Adam's/scripts/3-body.jl", "max_forks_repo_name": "paveloom-university/Computer-Methods-of-Celestial-Mechanics-S09-2021", "max_forks_repo_head_hexsha": "a650c76d6f299c20bbe82e98dd0708ef97a35f65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.042394015, "max_line_length": 95, "alphanum_fraction": 0.4953930439, "num_tokens": 5856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7779646407052655}}
{"text": "# Chapter 1.1\n\n# Visualizing a geometric series\n\n## Julia code to generate a geometric series\nusing Plots:bar\np = 0.5\nn = 1:10\nX = p .^ n\nbar(n, X, legend=false)\n\n## compute N choose K\n# Julia code to (N choose K) and K!\nn = 10\nk = 2\nbinomial(n, k)\nfactorial(k)\n\n# Chapter 1.4\n\n# Inner product of two vectors\n\n## Julia code to perform and inner product\nx = [1, 0, -1]\ny = [3, 2, 0]\nx'y\n\n## Norm of a vector\n# Julia code to compute the norm\nusing LinearAlgebra:norm\nx = [1, 0, -1]\nnorm(x)\n\n## Weighted norm of a vector\n# Julia code to compute the weighted norm\nW = [1. 2. 3.; 4. 5. 6.; 7. 8. 9.]\nx = [2, -1, 1]\nz = x'W*x\n\n## System of linear equations\n# Julia code to solve Xβ = y\nX = [1. 3.; -2. 7.; 0. 1.]\ny = [2., 1., 0.]\nβ = X\\y\n", "meta": {"hexsha": "55427c7850cc7aafa4b4404c662932ff08a77471", "size": 732, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Ch1.jl", "max_stars_repo_name": "r2cp/IntProbDS.jl", "max_stars_repo_head_hexsha": "ec9424eac1eb1055b4430340146f7f6db49c0e2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ch1.jl", "max_issues_repo_name": "r2cp/IntProbDS.jl", "max_issues_repo_head_hexsha": "ec9424eac1eb1055b4430340146f7f6db49c0e2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ch1.jl", "max_forks_repo_name": "r2cp/IntProbDS.jl", "max_forks_repo_head_hexsha": "ec9424eac1eb1055b4430340146f7f6db49c0e2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.2666666667, "max_line_length": 44, "alphanum_fraction": 0.6092896175, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731158685837, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7779045867517302}}
{"text": "# Estimates the Klein consumption equation by GMM\nusing Econometrics, DelimitedFiles, Statistics\nfunction KleinMoments(θ, y, x, z)\n\te = y - x*θ\n\tm = e.*z\nend\n\t\nfunction main()\ndata = readdlm(\"klein.data\")\n# construct missing lags, and drop first row that has missing data\nprofits = data[:,3]\noutput = data[:,7]\ndata = [data lag(profits,1) lag(output,1)]\ndata = data[2:end,:]\nn = size(data,1)\n# define instruments\nexogs = [1, 6, 8, 9, 10, 11, 12]\nexogs = data[:,exogs]\nexogs = [ones(n,1) exogs]\n# CONSUMPTION\nprintln(\"CONSUMPTION EQUATION\")\n# define variables in consumption equation\ny = data[:,2]\nprofits = data[:,3]\nlagprofits = data[:,11]\nwp = data[:,4]\nwg = data[:,8]\nwages = wp + wg\n# regressors in consumption equation\nx = [profits lagprofits wages]\nx = [ones(n,1) x]\n# GMM estimation using CUE\nθstart = x\\y # ols start values\nnames = [\"Constant\", \"Profits\", \"Profits-1\", \"Wages\"]\nmoments = θ -> KleinMoments(θ, y, x, exogs)\n# estimation results using CUE\ngmmtitle = \"Klein model 1 GMM example CUE\"\ngmmresults(moments, θstart, \"\",  gmmtitle, names)\nnothing\nend\nmain()\n", "meta": {"hexsha": "74a271e5572f143f171d56fbf6e9473e74fcd0ba", "size": 1073, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/Simeq/KleinCUE.jl", "max_stars_repo_name": "Hiroakiyusheng/Econometrics", "max_stars_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "Examples/Simeq/KleinCUE.jl", "max_issues_repo_name": "Hiroakiyusheng/Econometrics", "max_issues_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "Examples/Simeq/KleinCUE.jl", "max_forks_repo_name": "Hiroakiyusheng/Econometrics", "max_forks_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 25.5476190476, "max_line_length": 66, "alphanum_fraction": 0.6896551724, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620608291781, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7778669098407737}}
{"text": "suml2loss(yhat, y) = sum((yhat .- y).^2)\nsumabsloss(yhat, y) = sum(abs.(yhat .- y))\nl2loss(yhat, y) = mean((yhat .- y).^2)\nabsloss(yhat, y) = mean(abs.(yhat .- y))\nmape(yhat, y, eps = 1.0) =\n    100.0 * mean(abs.(yhat .- (y .+ eps)) ./ abs.(y .+ eps))\n", "meta": {"hexsha": "cfc9a0ccb27c2ff95e5b61d3636d2ab9f888d312", "size": 252, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/loss_functions.jl", "max_stars_repo_name": "robertfeldt/InterpretableModels.jl", "max_stars_repo_head_hexsha": "7585609ca88b477294bbcc58fa6dfad75f9dfef1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-18T13:23:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-18T13:23:32.000Z", "max_issues_repo_path": "src/loss_functions.jl", "max_issues_repo_name": "smsinks/InterpretableModels.jl", "max_issues_repo_head_hexsha": "405d70045233c105ed38f528fd8add2a63b6be96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/loss_functions.jl", "max_forks_repo_name": "smsinks/InterpretableModels.jl", "max_forks_repo_head_hexsha": "405d70045233c105ed38f528fd8add2a63b6be96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-28T20:24:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-28T20:24:01.000Z", "avg_line_length": 36.0, "max_line_length": 60, "alphanum_fraction": 0.5317460317, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9597620596782469, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7778669045144447}}
{"text": "\nusing OrdinaryDiffEq\nusing DiffEqUncertainty\nusing DiffEqCallbacks\nusing Statistics\nusing Random\nusing Plots\nusing BenchmarkTools\n\n\nfunction sir_ode!(du,u,p,t)\n    (S,I,R) = u\n    (β,c,γ) = p\n    N = S+I+R\n    @inbounds begin\n        du[1] = -β*c*I/N*S\n        du[2] = β*c*I/N*S - γ*I\n        du[3] = γ*I\n    end\n    nothing\nend;\n\n\nfunction condition(u,t,integrator) # Event when event_f(u,t) == 0\n  u[2]\nend;\n\n\nfunction affect!(integrator)\n  integrator.u[2] = 0.0\nend;\n\n\npositive_cb = ContinuousCallback(condition,affect!);\n\n\ntmax = 40.0\ntspan = (0.0,tmax);\n\n\nu0 = [990.0,10.0,0.0]; # S,I,R\n\n\np = [0.05,10.0,0.25]; # β,c,γ\n\n\nRandom.seed!(1234);\n\n\nprob_ode = ODEProblem(sir_ode!, u0, tspan, p);\n\n\nprobint_cb_4th = AdaptiveProbIntsUncertainty(4);\n\n\nnum_samples = 100\nensemble_prob_ode = EnsembleProblem(prob_ode)\n\n\nsamples_ode = solve(ensemble_prob_ode,\n                             ROS34PW3(),\n                             trajectories=num_samples,\n                             callback=CallbackSet(positive_cb,probint_cb_4th));\n\n\ns20 = [s(20.0) for s in samples_ode]\n[[mean([s[i] for s in s20]) for i in 1:3] [std([s[i] for s in s20]) for i in 1:3]]\n\n\np = plot(samples_ode[1],\n     label=[\"S\" \"I\" \"R\"],\n     color=[:blue :red :green],\n     xlabel=\"Time\",\n     ylabel=\"Number\")\nfor i in 2:num_samples\n    plot!(p,\n          samples_ode[i],\n          label=\"\",\n          color=[:blue :red :green])\nend;\n\n\nplot(p,yaxis=:log10,xlim=(15,20),ylim=(100,1000))\n\n\nplot(p,yaxis=:log10,xlim=(35,40),ylim=(10,1000))\n\n\n@benchmark solve(ensemble_prob_ode,\n                 ROS34PW3(),\n                 trajectories=100,\n                 callback=CallbackSet(positive_cb,probint_cb_4th))\n\n", "meta": {"hexsha": "0c7d06596f32202c990aa6c0a058ed0d2d18436a", "size": 1676, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_probint_diffequncertainty/ode_probint_diffequncertainty.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/ode_probint_diffequncertainty/ode_probint_diffequncertainty.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/ode_probint_diffequncertainty/ode_probint_diffequncertainty.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.829787234, "max_line_length": 82, "alphanum_fraction": 0.5900954654, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368929, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7778508648214387}}
{"text": "using Optim\n\nstruct HW\n\tm::Int64\n    α::Float64\n    β::Float64\n    γ::Float64\n    l0::Float64\n    b0::Float64\n    s0::Array{Float64, 1}\n\n    HW(m::Int64) = new(m, 0, 0, 0, 0, 0, repeat([0], m))\n\tHW(m::Int64, α::Number, β::Number, γ::Number, l0::Number, b0::Number, s0::Array{Float64, 1}) = \n\t\tm == length(s0) ? new(m, Float64(α), Float64(β), Float64(γ), Float64(l0), Float64(b0), \n\t\tFloat64.(s0)) : error(\"length(s0) must be equal to m\")\nend\n\nfunction loss(model::HW, time_series)\n\tα = model.α\n\tβ = model.β\n\tγ = model.γ\n\tl0 = model.l0\n\tb0 = model.b0\n\tm = model.m\n\ts = model.s0\n\n\tN = length(time_series)\n\tl_t = 0\n\tb_t = 0\n\tl_t_ = 0 #Variable to save l(t-1)\n\tb_t_ = 0 #Variable to save b(t-1)\n\ts_ = 0\n\t\n\tloss = 0\n\t\n\tfor i in 0:(N - 1)\n\t\tif i == 0\n\t\t\tl_t = l0\n\t\t\tb_t = b0\n\t\telse\n\t\t\tl_t = (time_series[i] - s_) * α + (l_t_ + b_t_) * (1 - α) \n\t\t\tb_t = β * (l_t - l_t_) + (1 - β) * b_t_\n\t\tend\n\t\tl_t_ = l_t\n\t\tb_t_ = b_t\n\t\ts_ = s[i%m + 1]\n\t\t\n\t\ty_pred = l_t + b_t + s[i%m + 1]\n\t\t\n\t\ts[i%m + 1] = γ * (time_series[i + 1] - l_t_ - b_t_) + (1 - γ) * s[i%m + 1]\n\t\t\n\t\tloss += (time_series[i + 1] - y_pred)^2\t\n\tend\n\n\treturn loss\nend\n\nfunction forecast(model::HW, time_serie, n_pred)\n\tα = model.α\n\tβ = model.β\n\tγ = model.γ\n\tl0 = model.l0\n\tb0 = model.b0\n\tm = model.m\n\ts = model.s0\n\t\n\tN = length(time_serie)\n\tl_t = 0\n\tb_t = 0\n\tl_t_ = 0 #Variable to save l(t-1)\n\tb_t_ = 0 #Variable to save b(t-1)\n\ts_ = 0\n\t\n\tpred = []\n\n\tfor i in 0:(N - 1)\n\t\tif i == 0\n\t\t\tl_t = l0\n\t\t\tb_t = b0\n\t\telse\n\t\t\tl_t = (time_serie[i] - s_) * α + (l_t_ + b_t_) * (1 - α) \n\t\t\tb_t = β * (l_t - l_t_) + (1 - β) * b_t_\n\t\tend\n\t\tl_t_ = l_t\n\t\tb_t_ = b_t\n\t\ts_ = s[i%m + 1]\n\t\t\n\t\ts[i%m + 1] = γ * (time_serie[i + 1] - l_t_ - b_t_) + (1 - γ) * s[i%m + 1]\t\n\tend\n\t\n\tl_t = (time_serie[end] - s_) * α + (l_t + b_t) * (1 - α)\n\tb_t = β * (l_t - l_t_) + (1 - β) * b_t_\n\t\n\tfor i in N:(N+n_pred - 1) \n\t\ty_pred = l_t + b_t*(i-N+1) + s[i%m + 1] \n\t\t#The trend has to be added as many times as periods we want to forecast.\n\t\tpush!(pred, y_pred)\n\tend\t\n\t\n\treturn pred\nend\n", "meta": {"hexsha": "b6bd391f00bec1e6695083863f09e60ec80e4464", "size": 1997, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "TSeriesForecast/src/seasonality_exponential_smoothing.jl", "max_stars_repo_name": "lambdaclass/julia_time_series_library", "max_stars_repo_head_hexsha": "4e02a71b485f16aff60ce741b0ad3ce2481fed91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TSeriesForecast/src/seasonality_exponential_smoothing.jl", "max_issues_repo_name": "lambdaclass/julia_time_series_library", "max_issues_repo_head_hexsha": "4e02a71b485f16aff60ce741b0ad3ce2481fed91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TSeriesForecast/src/seasonality_exponential_smoothing.jl", "max_forks_repo_name": "lambdaclass/julia_time_series_library", "max_forks_repo_head_hexsha": "4e02a71b485f16aff60ce741b0ad3ce2481fed91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5784313725, "max_line_length": 96, "alphanum_fraction": 0.5338007011, "num_tokens": 913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.8333246035907932, "lm_q1q2_score": 0.7778508621237803}}
{"text": "using StaticArrays\nusing SymPy\n\n\"\"\"\nWENO reconstruction schemes following the lecture notes by Shu (1998) and\nthe review article by Shu (2009). WENO smoothness indicators are due to\nJiang & Shu (1996). \n\nShu (1998), \"Essentially Non-Oscillatory and Weighted Essentially Non-Oscillatory\n    Schemes for Hyperbolic Conservation Laws\", In: Advanced Numerical Approximation\n    of Nonlinear Hyperbolic Equations, edited by Cockburn et al., pp. 325–432.\n    DOI: https://doi.org/10.1007/BFb0096355\n\nShu (2009) \"High Order Weighted Essentially Nonoscillatory Schemes for Convection\n    Dominated Problems\", SIAM Review 51(1), pp. 82–126.\n    DOI: https://doi.org/10.1137/070679065\n\nJiang & Shu (1996) \"Efficient Implementation of Weighted ENO Schemes\", Journal of\n    Computational Physics 126, pp. 202–228.\n    DOI: https://doi.org/10.1006/jcph.1996.0130\n\"\"\"\n\n#####\n##### ENO reconstruction coefficients and WENO weights on a uniform grid\n##### Equation (2.21) from the Shu (1998) lecture notes.\n#####\n\n\"\"\"\n    UΠ(k, r, m, l)\n\nReturn the product in the numerator of equation (2.21) of Shu (1998) for the `l`th\nterm of the `m`th Lagrange basis polynomial of an ENO reconstruction scheme with\norder `k` and left shift `r`.\n\"\"\"\nUΠ(k, r, l, m) = prod([r-q+1 for q in 0:k if q ∉ (m, l)])\n\n\"\"\"\n    U(k, r, m)\n\nReturn the numerator in equation (2.21) of Shu (1998) for the `m`th Lagrange basis\npolynomial of an ENO reconstruction scheme with order `k` and left shift `r`.\n\"\"\"\nU(k, r, m) = sum([UΠ(k, r, m, l) for l in 0:k if l != m])\n\n\"\"\"\n    D(k, m)\n\nReturn the denominator in equation (2.21) of Shu (1998) for the `m`th Lagrange basis\npolynomial of an ENO reconstruction scheme with order `k`.\n\"\"\"\nD(k, m) = prod([m - l for l in 0:k if l != m])\n\n\"\"\"\n    eno_coefficient(k, r)\n\nReturn the `j`th ENO coefficient used to reconstruct a value at the point x(i+½) with\norder of accuracy `k` (stencil size) and left shift `r`.\n\"\"\"\neno_coefficient(k, r, j) = sum([U(k, r, m)//D(k, m) for m in j+1:k])\n\n\"\"\"\n    eno_coefficients(k, r)\n\nReturn an array of ENO coefficients to reconstruct a value at the point x(i+½) with\norder of accuracy `k` (stencil size) and left shift `r`.\n\"\"\"\neno_coefficients(k, r) = [eno_coefficient(k, r, j) for j in 0:k-1]\n\n\"\"\"\n    eno_coefficients_matrix([FT=Rational], k)\n\nReturn a k×k static array containing ENO coefficients to reconstruct a value at the\npoint x(i+½) with order of accuracy `k` (stencil size) with element type `FT`. Note\nthat when combined these ENO interpolants produce a WENO scheme of order 2k-1.\n\"\"\"\neno_coefficients_matrix(FT, k) =\n    cat([eno_coefficients(k, r) for r in 0:k-1]..., dims=1) |> SMatrix{k,k,FT}\n\neno_coefficients_matrix(k) = eno_coefficients_matrix(Rational, k) \n\n\"\"\"\n    optimal_weno_weights([FT=Rational], k)\n\nReturn a static vector containing the optimal weights that can be used to weigh ENO\nreconstruction schemes of order `k` to produce a WENO scheme of order 2k-1.\n\"\"\"\nfunction optimal_weno_weights(FT, k)\n    C = zeros(Rational, 2k-1, k)\n    b = eno_coefficients(2k-1, k-1)\n\n    for n in 0:k-1\n        C[n+1:n+k, n+1] .= eno_coefficients(k, k-1-n)\n    end\n\n    γ = C \\ b\n    γ = rationalize.(γ, tol=√eps(Float64)) |> reverse\n    return SVector{k,FT}(γ)\nend\n\noptimal_weno_weights(k) = optimal_weno_weights(Rational, k)\n\n#####\n##### Jiang & Shu (1996) WENO smoothness indicators β\n##### See equation (2.61) of Shu (1998).\n#####\n\nx(j) = j  # Assume uniform grid for now.\n\n\"\"\"\n    ℓ(ξ, k, r, j)\n\nReturn a symbolic expression for the `j`th Lagrange basis polynomial ℓ(ξ) for an\nENO reconstruction scheme of order k and left shift `r` with field values `ϕ`.\n\"\"\"\nℓ(ξ, k, r, j) = prod((ξ - x(m-r)) / (x(j-r) - x(m-r)) for m in 0:k-1 if m != j)\n\n\"\"\"\n    L(ξ, k, r, ϕ)\n\nReturn a symbolic expression for the interpolating Lagrange polynomial p(ξ) for an\nENO reconstruction scheme of order k and left shift `r` with field values `ϕ`.\n\"\"\"\np(ξ, k, r, ϕ) = sum(ℓ(ξ, k, r, j) * ϕ[j+1] for j in 0:k-1)\n\n\"\"\"\n    β(k, r, ϕ)\n\nReturn a symbolic expression for the smoothness indicator β for a WENO reconstruction\nscheme with stencils of size `k` and left shift `r` (WENO scheme of order 2k-1). The\nfield values are represented by the symbols in `ϕ` which should have length k.\n\"\"\"\nfunction β(k, r, ϕ)\n    @vars ξ\n    return sum(integrate(diff(p(ξ, k, r, ϕ), ξ, l)^2, (ξ, Sym(-1//2), Sym(1//2))) for l in 1:k-1)\nend\n\n\"\"\"\n    subscript(n)\n\nConvert the integer `n` to a subscript in the form of a unicode string. Note\nthat `0x2080` is the unicode encoding for the subscript 0.\n\"\"\"\nsubscript(n) = join(Char(0x2080 + parse(Int, d)) for d in string(n))\n\nsubscript_sign(n) = n > 0 ? \"₊\" : n < 0 ? \"₋\" : \"\"\n\nsubscript_index(n) = n == 0 ? \"\" : subscript_sign(n) * subscript(abs(n))\n\n\"\"\"\n    β_coefficients([FT=Rational], k)\n\nReturn a k×k×k static array containing the WENO smoothness indicator coefficients\ndescribed by Jiang & Shu (1998) for a WENO reconstruction with stencils of size `k`\n(WENO scheme of order 2k-1) with element type `FT`.\n\nThe `B[m, n, r]` coefficient corresponds to the coefficient of the\n`ϕ[r-k+m+1] * ϕ[r-k+n+1]` term where r-k+1 <= m, n <= r and `r` is the left shift of\nthe ENO interpolants.\n\"\"\"\nfunction β_coefficients(FT, k)\n    B = zeros(Float64, k, k, k)\n    \n    for r in 0:k-1\n        ϕ = [Sym(\"ϕᵢ\" * subscript_index(n)) for n in r:-1:r-k+1]\n        β_symbolic = β(k, r, ϕ) |> expand\n\n        for m in 1:k, n in 1:k\n            B[m, n, r+1] = β_symbolic.coeff(ϕ[m] * ϕ[n])\n        end\n    end\n    \n    B = rationalize.(B, tol=√eps(Float64))\n    return SArray{Tuple{k,k,k},FT}(B)\nend\n\nβ_coefficients(k) = β_coefficients(Rational, k)", "meta": {"hexsha": "523505b12725e0ce16b5ef4f59751dc08e14a519", "size": 5589, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Advection/weno_reconstruction.jl", "max_stars_repo_name": "nolanrei99/Oceananigans.jl", "max_stars_repo_head_hexsha": "e808a821d78949b0482b8372533e992cabb5d65f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Advection/weno_reconstruction.jl", "max_issues_repo_name": "nolanrei99/Oceananigans.jl", "max_issues_repo_head_hexsha": "e808a821d78949b0482b8372533e992cabb5d65f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Advection/weno_reconstruction.jl", "max_forks_repo_name": "nolanrei99/Oceananigans.jl", "max_forks_repo_head_hexsha": "e808a821d78949b0482b8372533e992cabb5d65f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7556818182, "max_line_length": 97, "alphanum_fraction": 0.663088209, "num_tokens": 1852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7778508598031421}}
{"text": "# this uses catalyst reaction networks -- probably not optimised for performance\n# function calculate_steady_state_of_ode(repression_threshold,\n#                                        hill_coefficient,\n#                                        mRNA_degradation_rate,\n#                                        protein_degradation_rate,\n#                                        basal_transcription_rate,\n#                                        translation_rate)\n#    # define Hes5 reaction network\n#    hes5_network = @reaction_network begin\n#       hillr(protein,basal_transcription_rate,repression_threshold,hill_coefficient), ∅ --> mRNA\n#       mRNA_degradation_rate, mRNA → ∅\n#       protein_degradation_rate, protein → ∅\n#       translation_rate, mRNA → mRNA + protein\n#    end repression_threshold hill_coefficient mRNA_degradation_rate protein_degradation_rate basal_transcription_rate translation_rate\n#\n#    # parameters [α,K,n,δ,γ,β,μ]\n#    parameters = (repression_threshold,\n#                  hill_coefficient,\n#                  mRNA_degradation_rate,\n#                  protein_degradation_rate,\n#                  basal_transcription_rate,\n#                  translation_rate)\n#    # initial condition [m,p]\n#    u₀ = [40.,50000.]\n#    tspan = (0.0,100.0)\n#    # create the ODEProblem we want to solve\n#    prob = ODEProblem(hes5_network, u₀,tspan,parameters)\n#    sol = solve(prob)\n#\n# end #function\n\n\"\"\"\nCalculate the steady state of the Hes5 ODE system, for a specific set of parameters.\n\n# Arguments\n\n- `repression_threshold::Float64`\n\n- `hill_coefficient::Float64`\n\n- `mRNA_degradation_rate::Float64`\n\n- `protein_degradation_rate::Float64`\n\n- `basal_transcription_rate::Float64`\n\n- `translation_rate::Float64`\n\n# Returns\n\n- `steady_state_solution::Array{Float64,1}`: A 2-element array, giving the steady state for the mRNA and protein respectively.\n\"\"\"\nfunction calculate_steady_state_of_ode(repression_threshold,\n                                       hill_coefficient,\n                                       mRNA_degradation_rate,\n                                       protein_degradation_rate,\n                                       basal_transcription_rate,\n                                       translation_rate)\n\n   hill_function(protein,repression_threshold,hill_coefficient) = 1/(1 + (protein/repression_threshold)^hill_coefficient)\n\n   function hes_ode!(du,u,p,t)\n      du[1] = p[5]*hill_function(u[2],p[1],p[2]) - p[3]*u[1]\n      du[2] = p[6]*u[1] - p[4]*u[2]\n   end #function\n\n   parameters = (repression_threshold,\n                 hill_coefficient,\n                 mRNA_degradation_rate,\n                 protein_degradation_rate,\n                 basal_transcription_rate,\n                 translation_rate)\n\n   # initial condition [m,p]\n   initial_guess = [40.,50000.]\n   # create the SteadyStateProblem we want to solve\n   prob = SteadyStateProblem(hes_ode!, initial_guess, parameters)\n   # solve the problem\n   steady_state_solution = solve(prob,SSRootfind())\nend #function\n", "meta": {"hexsha": "d21a2e1335ccbf8f4a852e9c593745758c44081d", "size": 3013, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hes5_ode_steady_state.jl", "max_stars_repo_name": "burtonjosh/DelayedKalmanFilter.jl", "max_stars_repo_head_hexsha": "659d3f3e23659741c761567ad772da269ed0e640", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-03-31T15:19:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:38:57.000Z", "max_issues_repo_path": "src/hes5_ode_steady_state.jl", "max_issues_repo_name": "burtonjosh/DelayedKalmanFilter.jl", "max_issues_repo_head_hexsha": "659d3f3e23659741c761567ad772da269ed0e640", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-05-21T01:01:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-03T02:10:23.000Z", "max_forks_repo_path": "src/hes5_ode_steady_state.jl", "max_forks_repo_name": "burtonjosh/DelayedKalmanFilter.jl", "max_forks_repo_head_hexsha": "659d3f3e23659741c761567ad772da269ed0e640", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-31T15:10:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:10:17.000Z", "avg_line_length": 37.1975308642, "max_line_length": 135, "alphanum_fraction": 0.6159973448, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.8333245994514082, "lm_q1q2_score": 0.7778508582599509}}
{"text": "#=\r\nHidden layer activation functions and gradients.\r\nOptions are:\r\n:logistic, :tanh, :rectifier\r\n=#\r\n\r\n################################################################################\r\n#\r\n# Activation Functions and Derivatives\r\n#\r\n################################################################################\r\n\r\n########################################\r\n# Logistic\r\n########################################\r\n\r\n# logistic function of element z\r\n# f(z) = 1 / (1 + exp(-z))\r\nfunction logistic{F<:AbstractFloat}(z::F)\r\n    one(z) / (one(z) + exp(-z))\r\nend\r\n\r\n# logistic function of array Z\r\n# replacing array A in-place\r\n# A[i] = f(Z[i]) = 1 / (1 + exp(-Z[i])) ∀ i\r\nfunction logistic!{F<:AbstractFloat}(A::Array{F}, Z::Array{F})\r\n    size(A) == size(Z) || throw(DimensionMismatch(\"Inconsistent array sizes\"))\r\n    @threads for i in eachindex(Z)\r\n        @inbounds A[i] = logistic(Z[i])\r\n    end\r\nend\r\n\r\n# logistic function derivative of element z\r\n# df/dz = f(z) (1 - f(z))\r\nfunction logistic_deriv{F<:AbstractFloat}(z::F)\r\n    s = logistic(z)\r\n    s * (F(1) - s)\r\nend\r\n\r\n# logistic function derivative of array Z\r\n# ∂f/∂Z[i] = f(Z[i]) (1 - f(Z[i]))\r\n# replacing dest in-place with Hademaard product of dest and derivative i.e.\r\n# dest[i] = dest[i] * ∂f/∂Z[i]\r\nfunction logistic_deriv!{F<:AbstractFloat}(dest::Array{F}, Z::Array{F})\r\n    size(dest) == size(Z) || throw(DimensionMismatch(\"Inconsistent array sizes\"))\r\n    @threads for i in eachindex(Z)\r\n        @inbounds dest[i] *= logistic_deriv(Z[i])\r\n    end\r\nend\r\n\r\n########################################\r\n# Tanh\r\n########################################\r\n\r\n# Elementwise tanh function of array Z\r\n# replacing array A in-place\r\nfunction tanh!{F<:AbstractFloat}(A::Array{F}, Z::Array{F})\r\n    size(A) == size(Z) || throw(DimensionMismatch(\"Inconsistent array sizes\"))\r\n    @threads for i in eachindex(Z)\r\n        @inbounds A[i] = tanh(Z[i])\r\n    end\r\nend\r\n\r\n# Elementwise tanh function derivative of array Z\r\n# ∂f/∂Z[i] = 1 - f(Z[i])^2\r\n# replacing dest in-place with Hademaard product of dest and derivative i.e.\r\n# dest[i] = dest[i] * ∂f/∂Z[i]\r\nfunction tanh_deriv!{F<:AbstractFloat}(dest::Array{F}, Z::Array{F})\r\n    size(dest) == size(Z) || throw(DimensionMismatch(\"Inconsistent array sizes\"))\r\n    @threads for i in eachindex(Z)\r\n        @inbounds dest[i] *= (F(1) - tanh(Z[i])^2)\r\n    end\r\nend\r\n\r\n########################################\r\n# Rectified linear units\r\n########################################\r\n\r\n# Elementwise rectifier function of array Z\r\n# replacing array A in-place\r\nfunction relu!{F<:AbstractFloat}(A::Array{F}, Z::Array{F})\r\n    size(A) == size(Z) || throw(DimensionMismatch(\"Inconsistent array sizes\"))\r\n    @threads for i in eachindex(Z)\r\n        @inbounds A[i] = max(F(0), Z[i])\r\n    end\r\nend\r\n\r\n# Elementwise rectifier function derivative of array Z\r\n# ∂f/∂Z[i] = 0 (if Z[i] <= 0) or 1 (if Z[i] > 0)\r\n# replacing dest in-place with Hademaard product of dest and derivative i.e.\r\n# dest[i] = dest[i] * ∂f/∂Z[i]\r\nfunction relu_deriv!{F<:AbstractFloat}(dest::Array{F}, Z::Array{F})\r\n    size(dest) == size(Z) || throw(DimensionMismatch(\"Inconsistent array sizes\"))\r\n    for i in eachindex(Z)\r\n        @inbounds (Z[i] <= F(0)) && (dest[i] = F(0))\r\n        #@inbounds dest[i] *= ifelse(Z[i] > F(0), F(1), F(0))\r\n    end\r\nend\r\n\r\n########################################\r\n# Softmax\r\n########################################\r\n\r\n# Softmax function of matrix Z replacing matrix A in-place\r\n# Applies function to each column of Z i.e. each column will sum to 1\r\nfunction softmax!{F<:AbstractFloat}(A::Matrix{F}, Z::Matrix{F}, u::Matrix{F})\r\n    #size(A) == size(Z) || throw(DimensionMismatch(\"Inconsistent array sizes\"))\r\n    maximum!(u, Z)\r\n    for j in indices(Z, 2)\r\n        s = F(0)\r\n        for i in indices(Z, 1)\r\n            @inbounds s += (A[i, j] = exp(Z[i, j] - u[j]))\r\n        end\r\n        for i in indices(Z, 1)\r\n            @inbounds A[i, j] /= s\r\n        end\r\n    end\r\nend\r\n\r\n################################################################################\r\n#\r\n# Activation Dictionaries\r\n#\r\n################################################################################\r\n\r\nactivation_dict = Dict{Symbol, Function}(:logistic => logistic!,\r\n                                         :tanh => tanh!,\r\n                                         :relu => relu!)\r\n\r\nactivation_deriv_dict = Dict{Symbol, Function}(:logistic => logistic_deriv!,\r\n                                               :tanh => tanh_deriv!,\r\n                                               :relu => relu_deriv!)\r\n", "meta": {"hexsha": "d7bd78dd157a194004aa03d082cd4920065a64e5", "size": 4564, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/activations.jl", "max_stars_repo_name": "Wedg/Alice.jl", "max_stars_repo_head_hexsha": "48884d8dfaca3f987e69423dfc63e1f0881c7dc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/activations.jl", "max_issues_repo_name": "Wedg/Alice.jl", "max_issues_repo_head_hexsha": "48884d8dfaca3f987e69423dfc63e1f0881c7dc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/activations.jl", "max_forks_repo_name": "Wedg/Alice.jl", "max_forks_repo_head_hexsha": "48884d8dfaca3f987e69423dfc63e1f0881c7dc7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3157894737, "max_line_length": 82, "alphanum_fraction": 0.5, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7778508524642066}}
{"text": "matern12(x1, x2; ρ=ρ, σ²=σ²) = MaternCovariance_12(abs(x1-x2); ρ=ρ, σ²=σ²)\n\nfunction MaternCovariance_12(d; ρ=ρ, σ²=σ²)\n\n    @assert(d >= 0)\n\n    σ² * exp(-d/ρ)\n\nend\n\n\nmatern32(x1, x2; ρ=ρ, σ²=σ²) = MaternCovariance_32(abs(x1-x2); ρ=ρ, σ²=σ²)\n\nfunction MaternCovariance_32(d; ρ=ρ, σ²=σ²)\n\n    @assert(d >= 0)\n\n    σ² * (1 + sqrt(3)*d/ρ) * exp(- sqrt(3)*d/ρ)\n\nend\n\n\nmatern52(x1, x2; ρ=ρ, σ²=σ²) = MaternCovariance_52(abs(x1-x2); ρ=ρ, σ²=σ²)\n\nfunction MaternCovariance_52(d; ρ=ρ, σ²=σ²)\n\n    @assert(d >= 0)\n\n    σ² * (1 + sqrt(5)*d/ρ + 5*d^2/(3*ρ^2)) * exp(- sqrt(5)*d/ρ)\n\nend\n\n\nrbf(x1, x2; ρ=ρ, σ²=σ²) = RBFCovariance(abs(x1-x2); ρ=ρ, σ²=σ²)\n\nfunction RBFCovariance(d; ρ=ρ, σ²=σ²)\n\n    @assert(d >= 0)\n\n    σ² * exp(-d^2 / (2ρ))\n\nend\n\n\nlinear(x1, x2; c=c, σ²=σ²) = σ² * (x1 - c) * (x2 - c)\n\nfunction calculatekernelmatrix(k, ρ, σ², x)\n\n    calculatekernelmatrix(k, ρ, σ², x, x)\n\nend\n\nfunction calculatekernelmatrix(k, ρ, σ², x1, x2)\n\n    [k(a, b; ρ = ρ, σ² = σ²) for a in x1, b in x2]\n\nend\n", "meta": {"hexsha": "d35495bab90691d216707e74d1ba5225798ed7b1", "size": 990, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels.jl", "max_stars_repo_name": "ngiann/SimpleRegressionGP.jl", "max_stars_repo_head_hexsha": "0a24158b4bb462e4ad4f43f2e6fd1eaeed59b603", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels.jl", "max_issues_repo_name": "ngiann/SimpleRegressionGP.jl", "max_issues_repo_head_hexsha": "0a24158b4bb462e4ad4f43f2e6fd1eaeed59b603", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels.jl", "max_forks_repo_name": "ngiann/SimpleRegressionGP.jl", "max_forks_repo_head_hexsha": "0a24158b4bb462e4ad4f43f2e6fd1eaeed59b603", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0689655172, "max_line_length": 74, "alphanum_fraction": 0.5808080808, "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776496, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7778508513097393}}
{"text": "\"\"\"\n    mm(X,v,K) = v*X / (X + K)\n\nA Michaelis-Menten rate function.\n\"\"\"\nmm(X,v,K) = v*X / (X + K)\n@register mm(X,v,K);\nSymbolics.derivative(::typeof(mm), args::NTuple{3,Any}, ::Val{1}) = (args[2]*args[3]) / (args[1]+args[3])^2\nSymbolics.derivative(::typeof(mm), args::NTuple{3,Any}, ::Val{2}) = args[1]/(args[1]+args[3])\nSymbolics.derivative(::typeof(mm), args::NTuple{3,Any}, ::Val{3}) = - args[2]*args[1]/(args[1]+args[3])^2\n\n# Registers the repressing Michaelis-Menten function.\n\"\"\"\n    mmr(X,v,K) = v*K / (X + K)\n\nA repressive Michaelis-Menten rate function.\n\"\"\"\nmmr(X,v,K) = v*K / (X + K)\n@register mmr(X,v,K); \nSymbolics.derivative(::typeof(mmr), args::NTuple{3,Any}, ::Val{1}) = - (args[2]*args[3]) / (args[1]+args[3])^2\nSymbolics.derivative(::typeof(mmr), args::NTuple{3,Any}, ::Val{2}) = args[3]/(args[1]+args[3])\nSymbolics.derivative(::typeof(mmr), args::NTuple{3,Any}, ::Val{3}) = args[2]*args[1]/(args[1]+args[3])^2\n\n\n\"\"\"\n    hill(X,v,K,n) = v*(X^n) / (X^n + K^n)\n\nA Hill rate function.\n\"\"\"\nhill(X,v,K,n) = v*(X^n) / (X^n + K^n)\n@register hill(X,v,K,n);\nSymbolics.derivative(::typeof(hill), args::NTuple{4,Any}, ::Val{1}) = args[2] * args[4] * (args[3]^args[4]) * (args[1]^(args[4]-1))  /  (args[1]^args[4] + args[3]^args[4])^2\nSymbolics.derivative(::typeof(hill), args::NTuple{4,Any}, ::Val{2}) = (args[1]^args[4])  /  (args[1]^args[4] + args[3]^args[4])\nSymbolics.derivative(::typeof(hill), args::NTuple{4,Any}, ::Val{3}) = - args[2] * args[4] * (args[1]^args[4]) * (args[3]^(args[4]-1))  /  (args[1]^args[4] + args[3]^args[4])^2\nSymbolics.derivative(::typeof(hill), args::NTuple{4,Any}, ::Val{4}) = args[2] * (args[1]^args[4]) * (args[3]^args[4]) * (log(args[1])-log(args[3]))  /  (args[1]^args[4] + args[3]^args[4])^2\n\n\"\"\"\n    hillr(X,v,K,n) = v*(K^n) / (X^n + K^n)\n\nA repressive Hill rate function.\n\"\"\"\nhillr(X,v,K,n) = v*(K^n) / (X^n + K^n)\n@register hillr(X,v,K,n);\nSymbolics.derivative(::typeof(hillr), args::NTuple{4,Any}, ::Val{1}) = - args[2] * args[4] * (args[3]^args[4]) * (args[1]^(args[4]-1))  /  (args[1]^args[4] + args[3]^args[4])^2\nSymbolics.derivative(::typeof(hillr), args::NTuple{4,Any}, ::Val{2}) = (args[3]^args[4])  /  (args[1]^args[4] + args[3]^args[4])\nSymbolics.derivative(::typeof(hillr), args::NTuple{4,Any}, ::Val{3}) = args[2] * args[4] * (args[1]^args[4]) * (args[3]^(args[4]-1))  /  (args[1]^args[4] + args[3]^args[4])^2\nSymbolics.derivative(::typeof(hillr), args::NTuple{4,Any}, ::Val{4}) = args[2] * (args[1]^args[4]) * (args[3]^args[4]) * (log(args[3])-log(args[1]))  /  (args[1]^args[4] + args[3]^args[4])^2\n\n\"\"\"\n    hillar(X,Y,v,K,n) = v*(X^n) / (X^n + Y^n + K^n)\n\nAn activation/repressing Hill rate function.\n\"\"\"\nhillar(X,Y,v,K,n) = v*(X^n) / (X^n + Y^n + K^n)\n@register hillar(X,Y,v,K,n);\nSymbolics.derivative(::typeof(hillar), args::NTuple{5,Any}, ::Val{1}) = args[3] * args[5] * (args[1]^(args[5]-1)) * (args[2]^args[5]+args[4]^args[5])  /  (args[1]^args[5] + args[2]^args[5] + args[4]^args[5])^2\nSymbolics.derivative(::typeof(hillar), args::NTuple{5,Any}, ::Val{2}) = - args[3] * args[5] * (args[2]^(args[5]-1)) * (args[1]^args[5])  /  (args[1]^args[5] + args[2]^args[5] + args[4]^args[5])^2\nSymbolics.derivative(::typeof(hillar), args::NTuple{5,Any}, ::Val{3}) = (args[1]^args[5])   /  (args[1]^args[5] + args[2]^args[5] + args[4]^args[5])\nSymbolics.derivative(::typeof(hillar), args::NTuple{5,Any}, ::Val{4}) = - args[3] * args[5] * (args[3]^(args[5]-1)) * (args[1]^args[5])  /  (args[1]^args[5] + args[2]^args[5] + args[4]^args[5])^2\nSymbolics.derivative(::typeof(hillar), args::NTuple{5,Any}, ::Val{5}) = args[3] * (args[1]^args[5])  *  (log(args[1])*(args[2]^args[5] + args[4]^args[5]) - (args[2]^args[5])*log(args[2]) - (args[4]^args[5])*log(args[4]))   /   (args[1]^args[5] + args[2]^args[5] + args[4]^args[5])^2\n", "meta": {"hexsha": "27ae01be0ff21b83677108220b037c4aaad6c3b0", "size": 3776, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/registered_functions.jl", "max_stars_repo_name": "JuliaDiffEq/BiologicalModels.jl", "max_stars_repo_head_hexsha": "405fe978dacc9417f6c0cde802ca7b4680aeeceb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 177, "max_stars_repo_stars_event_min_datetime": "2020-07-20T21:27:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T14:08:31.000Z", "max_issues_repo_path": "src/registered_functions.jl", "max_issues_repo_name": "JuliaDiffEq/BiologicalModels.jl", "max_issues_repo_head_hexsha": "405fe978dacc9417f6c0cde802ca7b4680aeeceb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 201, "max_issues_repo_issues_event_min_datetime": "2020-07-17T06:56:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:49:53.000Z", "max_forks_repo_path": "src/registered_functions.jl", "max_forks_repo_name": "JuliaDiffEq/BiologicalModels.jl", "max_forks_repo_head_hexsha": "405fe978dacc9417f6c0cde802ca7b4680aeeceb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2020-08-02T09:41:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T13:16:59.000Z", "avg_line_length": 61.9016393443, "max_line_length": 282, "alphanum_fraction": 0.5725635593, "num_tokens": 1625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7778487139905984}}
{"text": "using Turing, BridgeSampling\n\n## Test on bivariate standard Normal distribution\nsamples = rand(MvNormal(ones(2)), 10_000)\n\nlog_posterior(x) = -0.5 * x' * x\n\nBridge = bridgesampling(samples, log_posterior, [-Inf, -Inf], [Inf, Inf])\nAnalytical = log(2*pi)\n\nisapprox(value(Bridge), Analytical, atol = 1e-3)\n\n## Hierarchical Normal example\n\n# Generate data\ntrue_μ = 0.0\ntrue_τ² = 0.5\ntrue_σ² = 1.0\nn = 20\ntrue_θ = rand(Normal(true_μ, sqrt(true_τ²)), n)\n#y = rand.(Normal.(true_θ, sqrt(true_σ²)))\n# Same values as in : https://cran.r-project.org/web/packages/bridgesampling/vignettes/bridgesampling_example_jags.html\ny = vec([1.19365332  1.95745331 -0.72161754 -1.87380833 -1.16928239  0.51960853 -0.03610041  0.42508815  0.41119221 -0.81236980  0.72967357  3.48186722  2.31126381  2.00029422 -0.27643507  1.06882370 -0.95083599 -1.89651101  2.56019737  0.23703060])\n\n# DynamicPPL models\n@model H0(Y) = begin\n    τ² ~ InverseGamma(1,1)\n    θ ~ filldist(Normal(0.0, sqrt(τ²)), length(Y))\n    Y ~ arraydist(Normal.(θ, 1.0))\nend\n\n@model H1(Y) = begin\n    μ ~ Normal()\n    τ² ~ InverseGamma(1,1)\n    θ ~ filldist(Normal(μ, sqrt(τ²)), length(Y))\n    Y ~ arraydist(Normal.(θ, 1.0))\nend\n\nM0 = H0(y)\nM1 = H1(y)\n\n# Sampling\nchn0 = sample(M0, NUTS(), MCMCThreads(), 50_000, 3, burnin=2000)\nchn1 = sample(M1, NUTS(), MCMCThreads(), 50_000, 3, burnin=2000)\n\n# Estimate log marginal likelihood : directly with the DynamicPPL model (lower precision)\nL0 = bridgesampling(chn0, M0)\nL1 = bridgesampling(chn1, M1)\n\n# Or with specified log posterior functions and boundaries\nlog_posterior_H0(x) = sum([logpdf(Normal(x.θ[i], 1.0), y[i]) for i = 1:n]) + \n                sum([logpdf(Normal(0.0, sqrt(x.τ²)), x.θ[i]) for i = 1:n]) + \n                logpdf(InverseGamma(1,1), x.τ²)\n\nlog_posterior_H1(x) = sum([logpdf(Normal(x.θ[i], 1.0), y[i]) for i = 1:n]) + \n                sum([logpdf(Normal(x.μ, sqrt(x.τ²)), x.θ[i]) for i = 1:n]) + \n                logpdf(InverseGamma(1,1), x.τ²) + \n                logpdf(Normal(), x.μ)\n\nsamplesH0, names = BridgeSampling.extract_samples(chn0, M0)\nL0 = bridgesampling(samplesH0, log_posterior_H0, [0.0, -Inf], [Inf, Inf]; names=names)\n\n\nsamplesH1, names = BridgeSampling.extract_samples(chn1, M1)\nL1 = bridgesampling(samplesH1, log_posterior_H1, [-Inf, 0.0, -Inf], [Inf, Inf, Inf]; names=names)\n\n# Bayes factor\nbayes_factor(L0, L1)\n\n# Posterior model probabilities\nposterior_probabilities([L0, L1])", "meta": {"hexsha": "e7ead6edbff52509e71e01728f325b037c93b723", "size": 2412, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example.jl", "max_stars_repo_name": "sqwayer/BridgeSampling.jl", "max_stars_repo_head_hexsha": "e3efa5a6d0598c90e6e99cf687b3ccd07ee84178", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-11-23T08:11:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T16:30:43.000Z", "max_issues_repo_path": "example.jl", "max_issues_repo_name": "sqwayer/BridgeSampling.jl", "max_issues_repo_head_hexsha": "e3efa5a6d0598c90e6e99cf687b3ccd07ee84178", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-11-03T00:20:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T00:33:38.000Z", "max_forks_repo_path": "example.jl", "max_forks_repo_name": "sqwayer/BridgeSampling.jl", "max_forks_repo_head_hexsha": "e3efa5a6d0598c90e6e99cf687b3ccd07ee84178", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9718309859, "max_line_length": 249, "alphanum_fraction": 0.6674958541, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7778487136921689}}
{"text": "# === Misc Utility Functions === #\nconst LOG_2_PI = log(2 * pi)\n\n\"\"\"Log-gamma function.\"\"\"\nlgamma(x) = logabsgamma(x)[1]\n\n\n\"\"\"\nSample from a list of log probabilities. Overwrites\nvector so that no new memory is allocated.\n\"\"\"\nsample_logprobs!(log_probs) = sample(pweights(softmax!(log_probs)))\n\n\n\"\"\"\nLog normalizer of 1D normal distribution in information form.\ngiven potential `m` and precision `v`. \n\nN(x | m, v) = exp{ m⋅x - .5v⋅x² - log Z(m, v) }\n\"\"\"\ngauss_info_logZ(m, v) = 0.5 * (LOG_2_PI - log(v) + m * m / v)\n", "meta": {"hexsha": "5495cf915c90ed70ebfd5c71f8af9f3c91d89115", "size": 517, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/misc.jl", "max_stars_repo_name": "WilburDoz/PPSeq.jl", "max_stars_repo_head_hexsha": "fd16af0e6aa4ce6e380d22c4a4ee05cf80b188a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 42, "max_stars_repo_stars_event_min_datetime": "2020-10-12T20:45:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T09:55:07.000Z", "max_issues_repo_path": "src/utils/misc.jl", "max_issues_repo_name": "WilburDoz/PPSeq.jl", "max_issues_repo_head_hexsha": "fd16af0e6aa4ce6e380d22c4a4ee05cf80b188a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-03T00:34:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-12T02:35:12.000Z", "max_forks_repo_path": "src/utils/misc.jl", "max_forks_repo_name": "WilburDoz/PPSeq.jl", "max_forks_repo_head_hexsha": "fd16af0e6aa4ce6e380d22c4a4ee05cf80b188a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-10-27T22:01:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T16:58:59.000Z", "avg_line_length": 23.5, "max_line_length": 67, "alphanum_fraction": 0.6557059961, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7778487101261451}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.10\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 9f18ccd0-8e25-11eb-20e6-ab941f663550\nbegin\n\timport Pkg\n    Pkg.activate(\".\")\n    Pkg.add(\"PlutoUI\")\n\tPkg.add(\"Plots\")\n\tPkg.add(\"Distributions\")\n\t\n\tusing PlutoUI\n\tusing Plots\n\tusing Distributions\nend\n\n# ╔═╡ 10a9374c-8e1a-11eb-10b4-fb8272dd46d1\nmd\"\"\"\n## Random SIRD Model with two Populations\n\n#### Intro\n\nThe **SIRD Model** has been developed to simulate an epidemic over time. The model consists of a system of 4 differential equations that express the rates of change of 4 variables over time. The 4 variables are:\n\n${ \\begin{align*}\n\tS & - \\text{the susceptibles of getting the infection} \\\\\n\tI & - \\text{the infected} \\\\\n\tR & - \\text{the recovered from the infection} \\\\\n\tD & - \\text{the number of dead}\n\\end{align*} }$\n\n#### The Model\nDefine the parameters of the dynamics as follows:\n\n${ \\begin{align*}\n\t\\beta & \\to \\text{ rate of infection} \\\\\n\t\\gamma & \\to \\text{ rate of recovery} \\\\\n\t\\delta & \\to \\text{ rate of immunity loss} \\\\\n\t\\rho & \\to \\text{ mortality}\n\\end{align*} }$\n\nThen the following 4 equations govern the dynamis of the model:\n\n${ \\begin{align*}\n\\frac{\\mathrm{d}S}{\\mathrm{d}t} & = -\\beta \\cdot \\frac{S \\cdot I}{N} + \\delta \\cdot R \\\\\n\\frac{\\mathrm{d}I}{\\mathrm{d}t} & = \\beta \\cdot \\frac{S \\cdot I}{N} - (\\gamma+\\rho) \\cdot I \\\\\n\\frac{\\mathrm{d}R}{\\mathrm{d}t} & = \\gamma \\cdot I - \\delta \\cdot R \\\\\n\\frac{\\mathrm{d}D}{\\mathrm{d}t} & = \\rho \\cdot I \n\\end{align*} }$\n\nTo model two mixing populations with independent parameters double the system and add resp. substract the mixing term \n\n${ \\pm \\beta_{ij} \\frac{S_j\\cdot I_i}{N_i + N_j} }$\n\nto the number of infected resp. susceptible individuals. This term models the infection from Population \\\\( i \\\\) to Population \\\\( j \\\\), for \\\\( i,j = 1,2\\\\).\n\nFinally to randomize the dynamics of the system in every step, all quantities that move between within the system get drawn from a Poisson distribution with the respective rate as mean.\n\n#### Model simulation\nThe following is a simulation of the model described above. First choose the model parameters\n\"\"\"\n\n# ╔═╡ 43970fa0-8e1b-11eb-3052-1701966a4478\nbegin\n\tT = 300 \t#period of 300 daysplot\n\tΔt = 1/4 \t#time interval of 6 hours (1/4 of a day)\nend;\n\n# ╔═╡ 742d1fd0-907d-11eb-27d1-59ca2af59f97\nparameter = Dict(\n\t\"rate of infection\" => 0.14,\n\t\"rate of recovery\" => 0.07,\n\t\"rate of immuity loss\" => 0.1,\n\t\"rate of death of infected\" => 0.001,\n\t\"total population\" => 1*10^4,\n\t\"initial number of infected\" => 10\n);\n\n# ╔═╡ d59335ac-913b-11eb-228f-273be8d7a86a\nmd\"\"\"\n---\n**Additional parameter and functions for simulations with two subgroups**\n\"\"\"\n\n# ╔═╡ 56b9df4c-913b-11eb-180a-eb784c2b5181\nbegin\n\tparameter_subpopulation = Dict(\n\t\t\"rate of infection\" => 0.14,\n\t\t\"rate of recovery\" => 0.035,\n\t\t\"rate of immuity loss\" => 0.2,\n\t\t\"rate of death of infected\" => 0.01,\n\t\t\"total population\" => 1*10^2,\n\t\t\"initial number of infected\" => 0.0\n\t\t)\n\t\n\tmixing_parameter = Dict(\n\t\t\"rate of infection 1 -> 2\" => 0.14,\n\t\t\"rate of infection 2 -> 1\" => 0.14\n\t)\nend;\n\n# ╔═╡ f8e23e02-9142-11eb-1700-6974da1a09c0\nmd\"\"\"\n---\n#### Worksheet \nHere all the calculations start. Set the initial state, choose the set of parameters and if needed the parameter changing function.\n\"\"\"\n\n# ╔═╡ da008842-9142-11eb-388c-d7e1f662d9db\nmd\"\"\"\n---\n#### Plots\n\"\"\"\n\n# ╔═╡ 93b1fcc4-9145-11eb-3d5e-4b9bd577a545\nmd\"\"\"\n---\n#### Model Functions\n\n**Euler Algorithm to solve system. With constant or changing parameters** \n\"\"\"\n\n# ╔═╡ 2680b820-8e32-11eb-28de-6f039360524b\nbegin\n\tfunction euler(f::Function,change_par!::Function,t0,tn,Δt,x₀,par)\n\t\tT = t0:Δt:tn\n\t\tF = Matrix{eltype(x₀)}(undef,(length(T),length(x₀)))\n\t\tF[1,:] = x₀\n\t\tfor (n,t) ∈ enumerate(T[2:end])\n\t\t\tchange_par!(par,t,F,n)\n\t\t\tF[n+1,:] = max.(F[n,:] + f(t,F,n,par) .* Δt,0)\n\t\tend\n\t\treturn F\n\tend\n\t\n\tfunction no_change!(par,t,F,n) end\n\t\n\teuler(f::Function,t0,tn,Δt,x₀,par) = euler(f,no_change!,t0,tn,Δt,x₀,par)\nend;\n\n# ╔═╡ 58f42866-9146-11eb-29ea-87830bc8db66\nmd\"\"\"\n**Defines the infinitesimal change of system**\n\"\"\"\n\n# ╔═╡ 3ab68bec-8e2f-11eb-203e-f9530bc39073\nbegin\n\tfunction SIR_step(t,x,β,δ,γ,ρ,N)\n\t\tS, I, R, D = x[1], x[2], x[3], x[4]\n\t\tnI = rand(Poisson(β*I*S/N))\n\t\tnIL = rand(Poisson(δ*R))\n\t\tnR = rand(Poisson(γ*I))\n\t\tnD = rand(Poisson(ρ*I))\n\t\treturn [\n\t\t\t-nI + nIL,\n\t\t\tnI - nR - nD,\n\t\t\tnR - nIL,\n\t\t\tnD\n\t\t\t]\n\tend\n\t\n\tSIR_step(t,x,par::Dict) = SIR_step(t,x,\n\t\t\t\tpar[\"rate of infection\"],par[\"rate of immuity loss\"],\n\t\t\t\tpar[\"rate of recovery\"],par[\"rate of death of infected\"],\n\t\t\t\tpar[\"total population\"]\n\t\t\t)\n\t\n\tSIR_step(t,H,n,par::Dict) = SIR_step(t,H[n,:],par)\nend;\n\n# ╔═╡ a7ac774a-913b-11eb-267b-8f9841c44cb4\nbegin\n\tfunction SIR_step_2D(t,H,n,par₁::Dict,par₂::Dict,par_mix::Dict)\n\t\tx₁,x₂ = view(H,n,1:4), view(H,n,5:8)\t\n\t\tx = vcat(SIR_step(t,x₁,par₁),SIR_step(t,x₂,par₂))\n\t\treturn x + SIR_interaction(t,x₁,x₂,\n\t\t\t\t\tpar_mix[\"rate of infection 1 -> 2\"],\n\t\t\t\t\tpar_mix[\"rate of infection 2 -> 1\"],\n\t\t\t\t\tpar₁[\"total population\"]+par₂[\"total population\"])\n\tend\n\t\n\tSIR_step_2D(t,H,n,par) = SIR_step_2D(t,H,n,par[1],par[2],par[3])\n\t\n\tfunction SIR_interaction(t,x₁,x₂,β₃,β₄,N)\n\t\tS₁, I₁, S₂, I₂ = x₁[1], x₁[2], x₂[1], x₂[2]\n\t\tnI₁ = rand(Poisson(β₄*S₁*I₂/N))\n\t\tnI₂ = rand(Poisson(β₃*S₂*I₁/N))\n\t\treturn [\n\t\t\t-nI₁, nI₁, 0, 0,\n\t\t\t-nI₂, nI₂, 0, 0\n\t\t]\n\tend\nend;\n\n# ╔═╡ c6bbb678-9080-11eb-2047-a3dcd34e8c77\nbegin\n\tN₁,N₂ = parameter[\"total population\"], parameter_subpopulation[\"total population\"]\n\tI₁,I₂ = parameter[\"initial number of infected\"], parameter_subpopulation[\"initial number of infected\"]\n\t\n\tx₀ = [\n\t\tN₁-I₁,\n\t\tI₁,\n\t\t0.0,\n\t\t0.0,\n\t\tN₂-I₂,\n\t\tI₂,\n\t\t0.0,\n\t\t0.0\n\t]\n\t\n\tresult = euler(\n\t\tSIR_step_2D,\n\t\t0.0,T,Δt,\n\t\tx₀,\n\t\t(parameter,parameter_subpopulation,mixing_parameter)\n\t\t)\nend;\n\n# ╔═╡ 3d9185a6-908c-11eb-301c-358ed4a3eb37\nlet\n\tp1 = plot(framestlye=:zerolines,title=\"Main Population\")\n\n\tplot!(p1, 0.0:Δt:T,result[:,1:4],\n\t\tlabel = [\"S\" \"I\" \"R\" \"D\"],\n\t\tcolor = [:blue :red :green :yellow],\n\t\txlabel = \"Days\",\n\t\tylabel = \"Number of Individuals\"\n\t)\n\t\n\tp2 = plot(framestlye=:zerolines,title=\"Subpopulation\")\n\n\tplot!(p2, 0.0:Δt:T,result[:,5:8],\n\t\tlabel = [\"S\" \"I\" \"R\" \"D\"],\n\t\tcolor = [:blue :red :green :yellow],\n\t\txlabel = \"Days\",\n\t\tylabel = \"Number of Individuals\"\n\t)\n\t\n\tplot(p1,p2,layout=(2,1),size=(680,680))\nend\n\n# ╔═╡ de101aba-9145-11eb-2457-7b1831145eeb\nmd\"\"\"\n\n**Supporting function for calculating the Incidence**\n\"\"\"\n\n# ╔═╡ 16a50518-906d-11eb-1e2b-3faa1765f30c\nbegin\n\t#Calculates at one time within the simulation\n\tfunction incidence(nI,t,pop_size;ndays=7,scale=100_000)\n\t\t#set starting time in range\n\t\tt₀ = max(t-round(Int,ndays/Δt),1)\n\t\t#return Incidence\n\t\treturn (nI[t] - nI[t₀]) .* (scale/pop_size)\n\tend\n\n\t\n\t#Calculates for all times after simulation\n\tfunction incidence(nI,pop_size;ndays=7,scale=100_000)\n\t\t#rescale days\n\t\tndays = round(Int,ndays/Δt)\n\t\t#sum new cases in first days\n\t\tI = nI[1:ndays]\n\t\t#iterate and add incidence\n\t\tfor t₀ ∈ 1:length(nI)-ndays\n\t\t\tappend!(I,nI[t₀+ndays] - nI[t₀])\n\t\tend\n\t\t#scale and return\n\t\treturn I .* scale/pop_size\n\tend\nend;\n\n# ╔═╡ ceedca8e-9148-11eb-189c-a3a088520c2c\nmd\"\"\"\n---\nPackage Management\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─10a9374c-8e1a-11eb-10b4-fb8272dd46d1\n# ╠═43970fa0-8e1b-11eb-3052-1701966a4478\n# ╠═742d1fd0-907d-11eb-27d1-59ca2af59f97\n# ╟─d59335ac-913b-11eb-228f-273be8d7a86a\n# ╠═56b9df4c-913b-11eb-180a-eb784c2b5181\n# ╟─f8e23e02-9142-11eb-1700-6974da1a09c0\n# ╠═c6bbb678-9080-11eb-2047-a3dcd34e8c77\n# ╟─da008842-9142-11eb-388c-d7e1f662d9db\n# ╟─3d9185a6-908c-11eb-301c-358ed4a3eb37\n# ╟─93b1fcc4-9145-11eb-3d5e-4b9bd577a545\n# ╠═2680b820-8e32-11eb-28de-6f039360524b\n# ╟─58f42866-9146-11eb-29ea-87830bc8db66\n# ╠═3ab68bec-8e2f-11eb-203e-f9530bc39073\n# ╠═a7ac774a-913b-11eb-267b-8f9841c44cb4\n# ╟─de101aba-9145-11eb-2457-7b1831145eeb\n# ╠═16a50518-906d-11eb-1e2b-3faa1765f30c\n# ╟─ceedca8e-9148-11eb-189c-a3a088520c2c\n# ╠═9f18ccd0-8e25-11eb-20e6-ab941f663550\n", "meta": {"hexsha": "e2c3b5fbb30c551786cbf54f1e51c0c91b0a8622", "size": 7824, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SIRD_2D_random.jl", "max_stars_repo_name": "roccminton/PlutoNotebooks", "max_stars_repo_head_hexsha": "c32dd451fb19e99ef184c463cb49bb1385fe4ffa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SIRD_2D_random.jl", "max_issues_repo_name": "roccminton/PlutoNotebooks", "max_issues_repo_head_hexsha": "c32dd451fb19e99ef184c463cb49bb1385fe4ffa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SIRD_2D_random.jl", "max_forks_repo_name": "roccminton/PlutoNotebooks", "max_forks_repo_head_hexsha": "c32dd451fb19e99ef184c463cb49bb1385fe4ffa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9072847682, "max_line_length": 211, "alphanum_fraction": 0.6687116564, "num_tokens": 3245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7778487070077651}}
{"text": "function absolute_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(abs.(y_true .- y_pred))\nend\n\nfunction percent_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return((y_true .- y_pred) ./ y_true)\nend\n\nfunction log_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(log(y_true - y_pred))\nend\n\nfunction squared_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return((y_true - y_pred) .^ 2)\nend\n\nfunction squared_log_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(log_error(y_true, y_pred) .^ 2)\nend\n\nfunction absolute_percent_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(abs.(percent_error(y_true, y_pred)))\nend\n\nfunction mean_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(mean(y_true - y_pred))\nend\n\nfunction mean_absolute_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(mean(absolute_error(y_true, y_pred)))\nend\n\nfunction median_absolute_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(median(absolute_error(y_true, y_pred)))\nend\n\nfunction mean_percent_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(mean(percent_error(y_true, y_pred)))\nend\n\nfunction median_percent_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(median(percent_error(y_true, y_pred)))\nend\n\nfunction mean_squared_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(mean(squared_error(y_true, y_pred)))\nend\n\nfunction median_squared_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(median(squared_error(y_true, y_pred)))\nend\n\nfunction sum_squared_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(sum(squared_error(y_true, y_pred)))\nend\n\nfunction mean_squared_log_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(mean(squared_log_error(y_true, y_pred)))\nend\n\nfunction mean_absolute_percent_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(mean(absolute_percent_error(y_true, y_pred)))\nend\n\nfunction median_absolute_percent_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(median(absolute_percent_error(y_true, y_pred)))\nend\n\nfunction symmetric_mean_absolute_percent_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(mean(abs.(y_pred .- y_true) ./ ((abs.(y_true) .+ abs.(y_pred)) ./ 3)))\nend\n\nfunction symmetric_median_absolute_percent_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(median(abs.(y_pred - y_true) ./ ((abs.(y_true) .+ abs.(y_pred)) ./ 2)))\nend\n\nfunction mean_absolute_scaled_error(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    n = max(length(y_true), length(y_pred))\n    numerator = sum(abs.(y_true .- y_pred))\n    denominator = (n / (n - 1)) * sum(abs.(y_true[2:n] .- y_pred[1:(n-1)]))\n    return(numerator / denominator)\nend\n\nfunction total_variance_score(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(sum((y_true .- mean(y_true)) .^ 2))\nend\n\nfunction explained_variance_score(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(sum((y_pred .- mean(y_true)) .^ 2))\nend\n\nfunction unexplained_variance_score(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(sum((y_true .- y_pred) .^ 2))\nend\n\nfunction r2_score(y_true, y_pred)\n    @_dimcheck length(y_true) == length(y_pred)\n    return(explained_variance_score(y_true, y_pred) / total_variance_score(y_true, y_pred))\nend\n", "meta": {"hexsha": "a1e1c83d0074bea60e237a46f1c5c8e186b38882", "size": 3756, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/regression.jl", "max_stars_repo_name": "JuliaTagBot/MLMetrics.jl", "max_stars_repo_head_hexsha": "73a776f77b43be614fe18c12128333cfebdaadfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2016-04-20T18:01:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T01:41:39.000Z", "max_issues_repo_path": "src/regression.jl", "max_issues_repo_name": "JuliaTagBot/MLMetrics.jl", "max_issues_repo_head_hexsha": "73a776f77b43be614fe18c12128333cfebdaadfb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2016-04-11T15:23:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-30T18:07:43.000Z", "max_forks_repo_path": "src/regression.jl", "max_forks_repo_name": "JuliaTagBot/MLMetrics.jl", "max_forks_repo_head_hexsha": "73a776f77b43be614fe18c12128333cfebdaadfb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2016-04-11T15:37:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-31T13:11:29.000Z", "avg_line_length": 30.5365853659, "max_line_length": 91, "alphanum_fraction": 0.7292332268, "num_tokens": 1012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7778487011364775}}
{"text": "using SparseArrays\nusing LinearAlgebraicRepresentation\nLar = LinearAlgebraicRepresentation\nusing ViewerGL\nGL = ViewerGL\n\nV, (VV,EV,FV,CV) = Lar.simplex(3, true)\ntetra = V, EV,FV,CV\ntwotetra = Lar.Struct([ tetra, Lar.t(0.25,0.25,0.25), tetra ])\nV,EV,FV,CV = Lar.struct2lar(twotetra)\nGL.VIEW([ GL.GLGrid(V,FV, GL.Point4d(1,1,1,0.2)) ]);\n\n\n\ncop_EV = Lar.coboundary_0(EV::Lar.Cells);\ncop_EW = convert(Lar.ChainOp, cop_EV);\ncop_FE = Lar.coboundary_1(V, FV::Lar.Cells, EV::Lar.Cells);\nW = convert(Lar.Points, V');\n\nV, copEV, copFE, copCF = Lar.Arrangement.spatial_arrangement( W::Lar.Points, cop_EW::Lar.ChainOp, cop_FE::Lar.ChainOp)\n\nEV = Lar.cop2lar(copEV)\nFE = [findnz(copFE[k,:])[1] for k=1:size(copFE,1)]\nFV = [collect(Set(cat(EV[e] for e in FE[f]))) for f=1:length(FE)]\nFV = convert(Lar.Cells, FV)\nW = convert(Lar.Points, V')\nWW = [[k] for k=1:size(W,2)]\n\nGL.VIEW(GL.numbering(.5)((W,[WW,EV]) ));\n\ntriangulated_faces = Lar.triangulate(V, [copEV, copFE])\nFVs = convert(Array{Lar.Cells}, triangulated_faces)\nV = convert(Lar.Points, V')\nGL.VIEW(GL.GLExplode(V,FVs,1.5,1.5,1.5,99));\n\nEVs = Lar.FV2EVs(copEV, copFE) # polygonal face fragments\nGL.VIEW(GL.GLExplode(V,EVs,1.5,1.5,1.5,99,1));\n", "meta": {"hexsha": "57ccf6edd0d8966633eea2384812e12f07b2fb45", "size": 1185, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/3d/two_tetrahedrons.jl", "max_stars_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_stars_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-25T16:45:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-25T16:45:01.000Z", "max_issues_repo_path": "examples/3d/two_tetrahedrons.jl", "max_issues_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_issues_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/3d/two_tetrahedrons.jl", "max_forks_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_forks_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1842105263, "max_line_length": 118, "alphanum_fraction": 0.6902953586, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.77784308161021}}
{"text": "function hammingsequence(N::Int)\n    if N < 1\n        throw(\"Hamming sequence index must be a positive integer\")\n    end\n    ham = Vector{BigInt}([1])\n    base2, base3, base5 = 1, 1, 1\n    next2, next3, next5 = BigInt(2), BigInt(3), BigInt(5)\n    for _ in 1:N-1\n        x = min(next2, next3, next5)\n        push!(ham, x)\n        next2 <= x && (base2 += 1; next2 = 2ham[base2])\n        next3 <= x && (base3 += 1; next3 = 3ham[base3])\n        next5 <= x && (base5 += 1; next5 = 5ham[base5])\n    end\n    ham\nend\n", "meta": {"hexsha": "0db80d7b5531cf616c82ab5b6231ffe7f4510902", "size": 509, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/hamming-numbers-2.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/hamming-numbers-2.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/hamming-numbers-2.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9411764706, "max_line_length": 66, "alphanum_fraction": 0.5383104126, "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7777619922311865}}
{"text": "# Diffusion maps\n# --------------\n# Diffusion maps,\n# Coifman, R. & Lafon, S., Applied and Computational Harmonic Analysis, Elsevier, 2006, 21, 5-30\n\n\"\"\"\n\n    DiffMap{T <: Real} <: AbstractDimensionalityReduction\n\nThe `DiffMap` type represents diffusion maps model constructed for `T` type data.\n\"\"\"\nstruct DiffMap{T <: Real} <: AbstractDimensionalityReduction\n    t::Int\n    α::Real\n    ɛ::Real\n    λ::AbstractVector{T}\n    K::AbstractMatrix{T}\n    proj::Projection{T}\nend\n\n## properties\noutdim(R::DiffMap) = size(R.proj, 1)\neigvals(R::DiffMap) = R.λ\n\n## custom\n\"\"\"Returns the kernel matrix of the diffusion maps model `R`\"\"\"\nkernel(R::DiffMap) = R.K\n\n## show\nsummary(io::IO, R::DiffMap) = print(io, \"Diffusion Maps(outdim = $(outdim(R)), t = $(R.t), α = $(R.α), ɛ = $(R.ɛ))\")\nfunction show(io::IO, R::DiffMap)\n    summary(io, R)\n    io = IOContext(io, :limit=>true)\n    println(io)\n    println(io, \"Kernel: \")\n    Base.print_matrix(io, R.K, \"[\", \",\",\"]\")\n    println(io)\n    println(io, \"Embedding:\")\n    Base.print_matrix(io, transform(R), \"[\", \",\",\"]\")\nend\n\n## interface functions\n\"\"\"\n    fit(DiffMap, data; maxoutdim=2, t=1, α=1.0, ɛ=1.0)\n\nFit a isometric mapping model to `data`.\n\n# Arguments\n* `data`: a matrix of observations. Each column of `data` is an observation.\n\n# Keyword arguments\n* `maxoutdim`: a dimension of the reduced space.\n* `t`: a number of transitions\n* `α`: a normalization parameter\n* `ɛ`: a Gaussian kernel variance (the scale parameter)\n\n# Examples\n```julia\nM = fit(DiffMap, rand(3,100)) # construct diffusion map model\nR = transform(M)              # perform dimensionality reduction\n```\n\"\"\"\nfunction fit(::Type{DiffMap}, X::AbstractMatrix{T}; maxoutdim::Int=2, t::Int=1, α::Real=0.0, ɛ::Real=1.0) where {T<:Real}\n    # compute kernel matrix\n    sumX = sum(X.^ 2, dims=1)\n    L = exp.(-( transpose(sumX) .+ sumX .- 2*transpose(X) * X ) ./ convert(T, ɛ))\n    # L = pairwise((x,y)-> exp(-norm(x-y,2)^2/ε), Xtr)\n\n    # Calculate Laplacian & normalize it\n    if α > 0\n        D = transpose(sum(L, dims=1))\n        L ./= (D * transpose(D)) .^ convert(T, α)\n    end\n    D = Diagonal(vec(sum(L, dims=1)))\n    M = inv(D)*L\n\n    # D = Diagonal(vec(sum(L, dims=1)))\n    # D⁻ᵅ = inv(D^α)\n    # Lᵅ = D⁻ᵅ*L*D⁻ᵅ\n    # Dᵅ = Diagonal(vec(sum(Lᵅ, dims=1)))\n    # M = inv(Dᵅ)*Lᵅ\n\n    # Eigendecomposition & reduction\n    F = eigen(M, permute=false, scale=false)\n    λ = real.(F.values)\n    idx = sortperm(λ, rev=true)[2:maxoutdim+1]\n    λ = λ[idx]\n    V = real.(F.vectors[:,idx])\n    Y = (λ.^t) .* V'\n\n    return DiffMap{T}(t, α, ɛ, λ, L, Y)\nend\n\n\"\"\"\n    transform(R::DiffMap)\n\nTransforms the data fitted to the diffusion map model `R` into a reduced space representation.\n\"\"\"\ntransform(R::DiffMap) = R.proj\n", "meta": {"hexsha": "95882491702cdd79f6bea66df52c1218a5dc4482", "size": 2720, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/diffmaps.jl", "max_stars_repo_name": "yha/ManifoldLearning.jl", "max_stars_repo_head_hexsha": "29a97cce829f0ab8fb172ac27ddfcfff446596a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71, "max_stars_repo_stars_event_min_datetime": "2015-03-15T17:34:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T19:17:06.000Z", "max_issues_repo_path": "src/diffmaps.jl", "max_issues_repo_name": "yha/ManifoldLearning.jl", "max_issues_repo_head_hexsha": "29a97cce829f0ab8fb172ac27ddfcfff446596a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2015-02-13T17:18:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T21:36:26.000Z", "max_forks_repo_path": "src/diffmaps.jl", "max_forks_repo_name": "yha/ManifoldLearning.jl", "max_forks_repo_head_hexsha": "29a97cce829f0ab8fb172ac27ddfcfff446596a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2015-06-17T17:56:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T21:45:13.000Z", "avg_line_length": 27.2, "max_line_length": 121, "alphanum_fraction": 0.6080882353, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897558991952, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7777619789094005}}
{"text": "abstract HopfieldNet\n\nfunction energy(net::HopfieldNet)\n    e = 0.0\n    n = length(net.s)\n    for i in 1:n\n        for j in 1:n\n            e += net.W[i, j] * net.s[i] * net.s[j]\n        end\n    end\n    e *= -0.5\n    for i in 1:n\n        e += net.W[i] * net.s[i]\n    end\n    return e\nend\n\nfunction settle!(net::HopfieldNet,\n                 iterations::Integer = 1_000,\n                 trace::Bool = false)\n    for i in 1:iterations\n        update!(net)\n        if trace\n            @printf \"%5.0d: %.4f\\n\" i energy(net)\n        end\n    end\n    return\nend\n\nfunction associate!{T <: Real}(net::HopfieldNet,\n                               pattern::Vector{T};\n                               iterations::Integer = 1_000,\n                               trace::Bool = false)\n    copy!(net.s, pattern)\n    settle!(net, iterations, trace)\n    # TODO: Decide if this should really be a copy\n    return copy(net.s)\nend\n\n# Hebbian learning steps w/ columns as patterns\nfunction train!{T <: Real}(net::HopfieldNet, patterns::Matrix{T})\n    n = length(net.s)\n    p = size(patterns, 2)\n    # Could use outer products here\n    # (1 / p) * (patterns[:, mu] * patterns[:, mu]')\n    for i in 1:n\n        for j in (i + 1):n\n            s = 0.0\n            for mu in 1:p\n                s += patterns[i, mu] * patterns[j, mu]\n            end\n            s = s / p # May need to be careful here\n            net.W[i, j] += s\n            net.W[j, i] += s\n        end\n    end\n    return\nend\n\nfunction h{T <: Real}(i::Integer, j::Integer, mu::Integer, n::Integer,\n                      W::Matrix{Float64}, patterns::Matrix{T})\n    res = 0.0\n    for k in 1:n\n        if k != i && k != j\n            res += W[i, k] * patterns[k, mu]\n        end\n    end\n    return res\nend\n\n# Storkey learning steps w/ columns as patterns\nfunction storkeytrain!{T <: Real}(net::HopfieldNet, patterns::Matrix{T})\n    n = length(net.s)\n    p = size(patterns, 2)\n    for i in 1:n\n        for j in (i + 1):n\n            for mu in 1:p\n                s = patterns[i, mu] * patterns[j, mu]\n                s -= patterns[i, mu] * h(j, i, mu, n, net.W, patterns)\n                s -= h(i, j, mu, n, net.W, patterns) * patterns[j, mu]\n                s *= 1 / n\n                net.W[i, j] += s\n                net.W[j, i] += s\n            end\n        end\n    end\n    return\nend\n", "meta": {"hexsha": "576b1be490da8af68eea2e243bd68962a42b3042", "size": 2326, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/generic.jl", "max_stars_repo_name": "JuliaPackageMirrors/HopfieldNets.jl", "max_stars_repo_head_hexsha": "77cbb439b832daaa60c1ec9809d606087aff8fb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-10-09T08:31:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-19T00:47:40.000Z", "max_issues_repo_path": "src/generic.jl", "max_issues_repo_name": "JuliaPackageMirrors/HopfieldNets.jl", "max_issues_repo_head_hexsha": "77cbb439b832daaa60c1ec9809d606087aff8fb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-04-04T15:45:05.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-05T17:20:32.000Z", "max_forks_repo_path": "src/generic.jl", "max_forks_repo_name": "JuliaPackageMirrors/HopfieldNets.jl", "max_forks_repo_head_hexsha": "77cbb439b832daaa60c1ec9809d606087aff8fb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-03-15T02:25:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T15:44:58.000Z", "avg_line_length": 26.1348314607, "max_line_length": 72, "alphanum_fraction": 0.4742046432, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7777619713106465}}
{"text": "using IDRsSolver\n\nprintln(\"FDM discretisation of a 3D convection-diffusion-reaction problem on a unit cube\")\nprintln(\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n\n# Define system\n\n# Defaults:\nh = 0.025\neps1 = 1.\nbeta = [0/sqrt(5), 250/sqrt(5), 500/sqrt(5)]\nr = 400\n\n\n# Generate matrix\nm = round(Int, 1/h)-1\nn = m*m*m\nSx = sparse(Tridiagonal((-eps1/h^2-beta[1]/(2*h))*ones(m-1),2*eps1/h^2*ones(m),(-eps1/h^2+beta[1]/(2*h))*ones(m-1)))\nSy = sparse(Tridiagonal((-eps1/h^2-beta[2]/(2*h))*ones(m-1),2*eps1/h^2*ones(m),-eps1/h^2+beta[2]/(2*h)*ones(m-1)))\nSz = sparse(Tridiagonal((-eps1/h^2-beta[3]/(2*h))*ones(m-1),2*eps1/h^2*ones(m),-eps1/h^2+beta[3]/(2*h)*ones(m-1)))\nIs = speye(m)       \nA = kron(kron(Is,Is),Sx) + kron(kron(Is,Sy),Is)+ kron(kron(Sz,Is),Is) -r*speye(n)\n\nx = linspace(h,1-h,m)\nsol = kron(kron(x.*(1-x),x.*(1-x)),x.*(1-x))\nb = A*sol\n\nprintln(\" \");\nprintln(\"The parameters of the problem are :\")\nprintln(\"Gridsize h = \", (h),\";\")\nprintln(\"Number of equations = \", (n),\";\")\nprintln(\"Diffusion parameter = \", (eps1),\";\")\nprintln(\"Convection parameters = (\",(beta[1]),\",\",(beta[2]),\",\",(beta[3]),\");\")\nprintln(\"Reaction parameter = \",(r),\" (Note: positive reaction parameter gives negative shift to matrix);\")\nprintln(\" \")\n\n\n\n# Defaults for the iterative solvers:\n\ntol = 1e-8\nmaxiter = 1000\n      \ns = 4\nprintln(\"IDR(4) iteration...\")\ntime = @elapsed x, _ = idrs( A, b; s=s, tol=tol, maxiter=maxiter)\n\nprintln(\"Final accuracy: \", norm(b-A*x)/norm(b))\nprintln(\"CPU time: \", time, \"s.\")\n      \n", "meta": {"hexsha": "b13a48bcdc24cddb4ef334e2bdcf6b82f126eaa2", "size": 1538, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example.jl", "max_stars_repo_name": "mschauer/IDRs.jl", "max_stars_repo_head_hexsha": "c5be1fdcd7b3f479837a7ba5faaa799c7b0f7e6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-08-24T11:18:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-13T14:14:17.000Z", "max_issues_repo_path": "examples/example.jl", "max_issues_repo_name": "mschauer/IDRs.jl", "max_issues_repo_head_hexsha": "c5be1fdcd7b3f479837a7ba5faaa799c7b0f7e6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-07-19T11:48:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:34:31.000Z", "max_forks_repo_path": "examples/example.jl", "max_forks_repo_name": "mschauer/IDRs.jl", "max_forks_repo_head_hexsha": "c5be1fdcd7b3f479837a7ba5faaa799c7b0f7e6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-01-12T09:52:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:19:00.000Z", "avg_line_length": 30.1568627451, "max_line_length": 116, "alphanum_fraction": 0.5799739922, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774729, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7777541674026972}}
{"text": "\"\"\"\n# Usage\n\n    solve(FDDE::FDDEProblem, h, DelayPECE())\n\nUsing the delayed predictor-corrector method to solve the delayed fractional differential equation problem.\n\n### References\n\n```tex\n@article{Wang2013ANM,\n  title={A Numerical Method for Delayed Fractional-Order Differential Equations},\n  author={Zhen Wang},\n  journal={J. Appl. Math.},\n  year={2013},\n  volume={2013},\n  pages={256071:1-256071:7}\n}\n```\n\"\"\"\nstruct DelayPECE <: FractionalDiffEqAlgorithm end\n\nfunction solve(FDDE::FDDEProblem, h, ::DelayPECE)\n    @unpack f, ϕ, α, τ, tspan = FDDE\n    T = tspan\n    t = collect(0:h:T)\n    maxn = size(t, 1)\n    yp = collect(0:h:T+h)\n    y = copy(t)\n    y[1] = ϕ(0)\n\n    @fastmath @inbounds @simd for n in 1:maxn-1\n        yp[n+1] = 0\n        @fastmath @inbounds @simd for j = 1:n\n            yp[n+1] = yp[n+1]+b(j-1, n-1, α, h)*f(t[j], y[j], v(ϕ, j, τ, h, y, yp))\n        end\n        yp[n+1] = yp[n+1]/gamma(α)+ϕ(0)\n\n        y[n+1] = 0\n\n        @fastmath @inbounds @simd for j=1:n\n            y[n+1] = y[n+1]+a(j-1, n-1, α, h)*f(t[j], y[j], v(ϕ, j, τ, h, y, yp))\n        end\n\n        y[n+1] = y[n+1]/gamma(α)+h^α*f(t[n+1], yp[n+1], v(ϕ, n+1, τ, h, y, yp))/gamma(α+2)+ϕ(0)\n    end\n\n    delayedterm = copy(t)\n    @fastmath @inbounds @simd for n = 1:maxn-1\n        delayedterm[n] = v(ϕ, n, τ, h, y, yp)\n    end\n    return delayedterm, y\nend\n\nfunction a(j, n, α, h)\n    if j == n+1\n        result = 1\n    elseif j == 0\n        result = n^(α+1)-(n-α)*(n+1)^α\n    else\n        result = (n-j+2)^(α+1) + (n-j)^(α+1) - 2*(n-j+1)^(α+1)\n    end\n    return result*h^α / (α * (α + 1))\nend\n\nfunction b(j, n, α, h)\n    return h^α/α*((n-j+1)^α - (n-j)^α)\nend\n\nfunction v(ϕ, n, τ, h, y, yp)\n    if τ >= n*h\n        return ϕ((n-1)*h-τ)\n    else\n        m = floor(Int, τ/h)\n        δ = m-τ/h\n\n        if m>1\n            return δ*y[n-m+2] + (1-δ)*y[n-m+1]\n        elseif m == 1\n            return δ*yp[n+1] + (1-δ)*y[n]\n        end\n    end\nend", "meta": {"hexsha": "1e4a0ccedd61d5308d7fe84064de3d4ee2b0b6f8", "size": 1928, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FDDE/DelayPECE.jl", "max_stars_repo_name": "SciFracX/FractionalDiffEq.jl", "max_stars_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-11-05T12:49:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:57:20.000Z", "max_issues_repo_path": "src/FDDE/DelayPECE.jl", "max_issues_repo_name": "SciFracX/FractionalDiffEq.jl", "max_issues_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-11-01T22:05:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:57:19.000Z", "max_forks_repo_path": "src/FDDE/DelayPECE.jl", "max_forks_repo_name": "SciFracX/FractionalDiffEq.jl", "max_forks_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2289156627, "max_line_length": 107, "alphanum_fraction": 0.5062240664, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993028, "lm_q2_score": 0.8244619350028205, "lm_q1q2_score": 0.7777541654976659}}
{"text": "@doc raw\"\"\"\n    Plane3\n\nAn object `h` of the data type [`Plane3`](@ref) is an oriented plane in the\nthree-dimensional Euclidean space ``Ε^3``.\n\nIt is defined by the set of points with Cartesian coordinates ``(x,y,z)`` that\nsatisfy the plane equation\n\n```math\n    h:\\; a\\, x + b\\, y + c\\, z + d = 0.\n```\n\nThe plane splits ``Ε^3`` in a *positive* and a *negative side*. A point `p` with\nCartesian coordinates ``(px, py, pz)`` is on the positive side of `h`, iff\n``a\\, px + b\\, py + c\\, pz + d > 0``. It is on the negative side, iff\n``a\\, px + b\\, py + c\\, pz + d < 0``.\n\"\"\"\nPlane3\n\n@doc raw\"\"\"\n    Plane3(a::Real, b::Real, c::Real, d::Real)\n\nCreate a plane `h` defined by the equation ``a\\, px + b\\, py + c\\, pz + d = 0``.\n\nNotice that `h` is degenerate if ``a = b = c = 0``.\n\"\"\"\nPlane3(a::Real, b::Real, c::Real, d::Real) =\n    Plane3(convert(FT, a), convert(FT, b),\n           convert(FT, c), convert(FT, d))\n\n\"\"\"\n    Plane3(p::Point3, q::Point3, r::Point3)\n\nCreate a plane `h` passing through the points `p`, `q`, and `r`.\n\nThe plane is oriented such that `p`, `q` and `r` are oriented in a positive\nsense (that is counterclockwise) when seen form the positive side of `h`. Notice\nthat `h` is degenerate if the points are collinear.\n\"\"\"\nPlane3(p::Point3, q::Point3, r::Point3)\n\n\"\"\"\n    Plane3(p::Point3, v::Vector3)\n\nIntroduces a plane `h` that passes through point `p` and that is orthogonal to\n`v`.\n\"\"\"\nPlane3(p::Point3, v::Vector3)\n\n\"\"\"\n    Plane3(p::Point3, d::Direction3)\n\nIntroduces a plane `h` that passes through point `p` and that has an orthogonal\ndirection equal to `d`.\n\"\"\"\nPlane3(p::Point3, d::Direction3)\n\n\"\"\"\n    Plane3(l::Line3, p::Point3)\n\nIntroduces a plane `h` that is defined through the three points `point(l, 0)`,\n`point(l, 1)` and `p`.\n\"\"\"\nPlane3(l::Line3, p::Point3)\n\n\"\"\"\n    Plane3(r::Ray3, p::Point3)\n\nIntroduces a plane `h` that is defined through the three points `point(r, 0)`,\n`point(r, 1)` and `p`.\n\"\"\"\nPlane3(r::Ray3, p::Point3)\n\n\"\"\"\n    Plane3(s::Segment3, p::Point3)\n\nIntroduces a plane `h` that is defined through the three points `source(s)`,\n`target(s)` and `p`.\n\"\"\"\nPlane3(s::Segment3, p::Point3)\n\n\"\"\"\n    Plane3(c::Circle3)\n\nIntroduces a plane `h` that is defined as the plane containing the circle `c`.\n\"\"\"\nPlane3(c::Circle3)\n\n\"\"\"\n    ==(h₁::Plane3, h₂::Plane3)\n\nTest for equality: two planes are equal, iff they have a non empty intersection\nand the same orientation.\n\"\"\"\n==(h₁::Plane3, h₂::Plane3)\n\n\"\"\"\n    a(h::Plane3)\n\nReturns the first coefficient of `h`.\n\"\"\"\na(h::Plane3)\n\n\"\"\"\n    b(h::Plane3)\n\nReturns the second coefficient of `h`.\n\"\"\"\nb(h::Plane3)\n\n\"\"\"\n    c(h::Plane3)\n\nReturns the third coefficient of `h`.\n\"\"\"\nc(h::Plane3)\n\n\"\"\"\n    d(h::Plane3)\n\nReturns the fourth coefficient of `h`.\n\"\"\"\nd(h::Plane3)\n\n\"\"\"\n    perpendicular_line(h::Plane3, p::Point3)\n\nReturns the line that is perpendicular to `h` and that passes through point `p`.\n\nThe line is oriented from the negative to the positive side of `h`.\n\"\"\"\nperpendicular_line(h::Plane3, p::Point3)\n\n\"\"\"\n    projection(h::Plane3, p::Point3)\n\nReturns the orthogonal projection of `p` on `h`.\n\"\"\"\nprojection(h::Plane3, p::Point3)\n\n\"\"\"\n    opposite(h::Plane3)\n\nReturns the plane with opposite orientation.\n\"\"\"\nopposite(h::Plane3)\n\n\"\"\"\n    point(h::Plane3)\n\nReturns an arbitrary point on `h`.\n\"\"\"\npoint(h::Plane3)\n\n\"\"\"\n    orthogonal_vector(h::Plane3)\n\nReturns a vector that is orthogonal to `h` and that is directed to the positive\nside of `h`.\n\"\"\"\northogonal_vector(h::Plane3)\n\n\"\"\"\n    orthogonal_direction(h::Plane3)\n\nReturns a direction that is orthogonal to `h` and that is directed to the positive\nside of `h`.\n\"\"\"\northogonal_direction(h::Plane3)\n\n\"\"\"\n    base1(h::Plane3)\n\nReturns a vector orthogonal to [`orthogonal_vector()`](@ref).\n\"\"\"\nbase1(h::Plane3)\n\n\"\"\"\n    base2(h::Plane3)\n\nReturns a vector that is both orthogonal to [`base1()`](@ref), and to\n[`orthogonal_vector()`](@ref), and such that the result of `orientation(\npoint(h), point(h) + base1(h), point(h) +\nbase2(h), point(h) + orthogonal_vector(h) )` is positive.\n\"\"\"\nbase2(h::Plane3)\n\n\"\"\"\n    to_2d(h::Plane3, p::Point3)\n\nReturns the image point of the projection of `p` under an affine transformation,\nwhich maps `h` onto the ``xy``-plane, with the ``z``-coordinate removed.\n\"\"\"\nto_2d(h::Plane3, p::Point3)\n\n\"\"\"\n    to_3d(h::Plane3, p::Point2)\n\nReturns a point `q`, such that `to_2d(h, to_3d(h, p))` is equal to `p`.\n\"\"\"\nto_3d(h::Plane3, p::Point2)\n\n\"\"\"\n    oriented_side(h::Plane3, p::Point3)\n\nReturns either [`ON_ORIENTED_BOUNDARY`](@ref), or the constant\n[`ON_POSITIVE_SIDE`](@ref), or the constant [`ON_NEGATIVE_SIDE`](@ref),\ndetermined by the position of `p` relative to the oriented plane `h`.\n\"\"\"\noriented_side(h::Plane3, p::Point3)\n\n\"\"\"\n    has_on(h::Plane3, p::Point3)\n\nReturns `true`, iff `p` properly lies on `h`.\n\"\"\"\nhas_on(h::Plane3, p::Point3)\n\n\"\"\"\n    has_on_positive_side(h::Plane3, p::Point3)\n\nReturns `true`, iff `p` lies on the positive side of `h`.\n\"\"\"\nhas_on_positive_side(h::Plane3, p::Point3)\n\n\"\"\"\n    has_on_negative_side(h::Plane3, p::Point3)\n\nReturns `true`, iff `p` lies on the negative side of `h`.\n\"\"\"\nhas_on_negative_side(h::Plane3, p::Point3)\n\n\"\"\"\n    has_on(h::Plane3, l::Line3)\n\nReturns `true`, iff `l` properly lies on `h`.\n\"\"\"\nhas_on(h::Plane3, l::Line3)\n\n\"\"\"\n    has_on(h::Plane3, c::Circle3)\n\nReturns `true`, iff `c` properly lies on `h`.\n\"\"\"\nhas_on(h::Plane3, c::Circle3)\n\n\"\"\"\n    is_degenerate(h::Plane3)\n\nPlane `h` is degenerate, if the coefficients `a`, `b`, and `c` of the plane\nequation are zero.\n\"\"\"\nis_degenerate(h::Plane3)\n\n\"\"\"\n    transform(h::Plane3, t::AffTransformation3)\n\nReturns the plane obtained by applying `t` on a point of `h` and the\northogonal direction of `h`.\n\"\"\"\ntransform(h::Plane3, t::AffTransformation3)\n", "meta": {"hexsha": "a9950e1ff87a8cff7b6df83cc4f49466391ec028", "size": 5738, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernel/plane_3.jl", "max_stars_repo_name": "rgcv/CGAL.jl", "max_stars_repo_head_hexsha": "a3d55993938f271f3243fb86cb59f2e481bac7d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-07-17T22:06:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T08:32:54.000Z", "max_issues_repo_path": "src/kernel/plane_3.jl", "max_issues_repo_name": "rgcv/CGAL.jl", "max_issues_repo_head_hexsha": "a3d55993938f271f3243fb86cb59f2e481bac7d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-10-31T19:37:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T20:04:37.000Z", "max_forks_repo_path": "src/kernel/plane_3.jl", "max_forks_repo_name": "rgcv/CGAL.jl", "max_forks_repo_head_hexsha": "a3d55993938f271f3243fb86cb59f2e481bac7d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-16T13:55:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T18:07:26.000Z", "avg_line_length": 21.8174904943, "max_line_length": 82, "alphanum_fraction": 0.6484837923, "num_tokens": 1779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7777541633339212}}
{"text": "function laplace_filter(x::Matrix{Tv}) where {Tv<:AbstractFloat}\n\n    (n1, n2) = size(x)\n    x1 = zeros(Tv, n1, n2)\n    for i2 = 2 : n2-1\n        for i1 = 2 : n1-1\n            x1[i1,i2] = (8.0 * x[i1,i2] - x[i1-1,i2-1] - x[i1,i2-1] - x[i1+1,i2-1]\n                                        - x[i1-1,i2  ]              - x[i1+1,i2  ]\n                                        - x[i1-1,i2+1] - x[i1,i2+1] - x[i1+1,i2+1])\n        end\n    end\n    return x1\nend\n\n# function laplace_filter(img::Matrix{Tv}, iflag::Int64) where {Tv<:AbstractFloat}\n#     (m, n) = size(img)\n#     # d = zeros(eltype(img), m, n)\n#     # for ix = 2 : n-1\n#     #     for iz = 2 : m-1\n#     #         d[iz, ix] = 4*img[iz,ix]-img[iz-1,ix]-img[iz+1,ix]-img[iz,ix-1]-img[iz,ix+1]\n#     #     end\n#     # end\n#     a = -1.0 * ones(m-1); a[end] = 0.0\n#     b =    2 * ones(m  ); b[1]   = 1.0; b[end] = 1.0\n#     c = -1.0 * ones(m-1); c[1]   = 0.0;\n#     V = spdiagm((a,b,c), (-1,0,1), m, m)\n#\n#     a = -1.0 * ones(n-1); a[end] = 0.0\n#     b =    2 * ones(n  ); b[1]   = 1.0; b[end] = 1.0\n#     c = -1.0 * ones(n-1); c[1]   = 0.0;\n#     H = spdiagm((a,b,c), (-1,0,1), n, n)\n#\n#     if iflag == 1\n#        r = V * img + img * H'\n#     elseif iflag == 2\n#        r = V'* img + img * H\n#     end\n#\n#     return r\n# end\n", "meta": {"hexsha": "42f9204457b5ddc7e14c56f33f5f6795b33884af", "size": 1279, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/imaging/filter.jl", "max_stars_repo_name": "joaquin-17/SeisAcoustic.jl", "max_stars_repo_head_hexsha": "98d25280bcf88c471152b2ade977dec754494271", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2019-07-01T15:02:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T12:48:43.000Z", "max_issues_repo_path": "src/imaging/filter.jl", "max_issues_repo_name": "joaquin-17/SeisAcoustic.jl", "max_issues_repo_head_hexsha": "98d25280bcf88c471152b2ade977dec754494271", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2022-01-26T22:31:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-05T20:15:21.000Z", "max_forks_repo_path": "src/imaging/filter.jl", "max_forks_repo_name": "joaquin-17/SeisAcoustic.jl", "max_forks_repo_head_hexsha": "98d25280bcf88c471152b2ade977dec754494271", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-04-25T02:21:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T00:27:24.000Z", "avg_line_length": 31.1951219512, "max_line_length": 92, "alphanum_fraction": 0.392494136, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7777541633339212}}
{"text": "#=\nThese functions are taken from http://pordlabs.ucsd.edu/matlab/stream.htm\nKirill K. Pankratov, March 7, 1994.\n=#\n\nfunction cumsimp(vec::Vector{T}) where T\n    c1 = 3//8\n    c2 = 6//8\n    c3 = -1//8\n\n    # Interpolate values of Y to all midpoints\n    f = fill(zero(T),length(vec))\n    for i in 2:length(f)-1\n        f[i] = c1*vec[i-1]+c2*vec[i]+c3*vec[i+1]\n    end\n    for i in 3:length(f)\n        f[i] += c3*vec[i-2]+c2*vec[i-1]+c1*vec[i]\n    end\n    f[2] *= 2\n    f[end] *= 2\n    # Now Simpson (1,4,1) rule\n    for i in 2:length(f)\n        f[i] = 2f[i]+vec[i-1]+vec[i]\n    end\n    f[1:end] .= cumsum(f)/6  # Cumulative sum, 6 - denom. from the Simpson rule\nend\n\nfunction cumsimp(U::AbstractMatrix{T}) where T\n    ret = similar(U)\n    for i in 1:size(U)[2]\n        ret[:,i] .= cumsimp(U[:,i])\n    end\n    ret\nend\n\nfunction flowfun(u,v)\n    lx = size(u,2)  # Size of the velocity matrices\n    ly = size(u,1)\n    # Integrate velocity fields to get potential and streamfunction\n    # Use Simpson rule summation\n    cx = cumsimp(v[1,:])  # Compute x-integration constant\n    cy = cumsimp(u[:,1])  # Compute y-integration constant\n    ψ = -cumsimp(u)+repeat(cx',ly,1)\n    ψ = (ψ+cumsimp(v')'-repeat(cy,1,lx))/2\nend\n\n# function cumsimp_naive(vec::Vector{T})::Vector{T} where T\n#     c1 = 3//8\n#     c2 = 6//8\n#     c3 = -1//8\n#\n#     lv = length(vec)\n#     num = 1:lv-2\n#     vec_itp = fill(zero(T),length(vec))\n#     # Interpolate values of Y to all midpoints\n#     @. vec_itp[num+1] = c1*vec[num]+c2*vec[num+1]+c3*vec[num+2]\n#     @. vec_itp[num+2] = vec_itp[num+2]+c3*vec[num]+c2*vec[num+1]+c1*vec[num+2]\n#     vec_itp[2] *= 2\n#     vec_itp[lv] *= 2\n#     # Now Simpson (1,4,1) rule\n#     @. vec_itp[num+1] = 2vec_itp[num+1]+vec[num]+vec[num+1]\n#     vec_itp[:] .= cumsum(vec_itp)/6\n# end\n", "meta": {"hexsha": "8e3fe4469286ab2d025d735f208f4c9bbae4587b", "size": 1789, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/data/stream/stream.jl", "max_stars_repo_name": "JackDevine/BrownianDynamics.jl", "max_stars_repo_head_hexsha": "93892b09466b89dea47f8a5c65da2a544712dd31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-06T17:48:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T17:48:13.000Z", "max_issues_repo_path": "examples/data/stream/stream.jl", "max_issues_repo_name": "JackDevine/BrownianDynamics.jl", "max_issues_repo_head_hexsha": "93892b09466b89dea47f8a5c65da2a544712dd31", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/data/stream/stream.jl", "max_forks_repo_name": "JackDevine/BrownianDynamics.jl", "max_forks_repo_head_hexsha": "93892b09466b89dea47f8a5c65da2a544712dd31", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.953125, "max_line_length": 80, "alphanum_fraction": 0.5718278368, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7777541546044777}}
{"text": "function companion(p::Pol{T}) where {T<:Number}\n    p /= lc(p)\n    C = zeros(T, deg(p), deg(p))\n    C[2:end, 1:end-1] .= Matrix(I, deg(p)-1, deg(p)-1)\n    C[:, end] = -p.coeffs[1:end-1]\n    return C\nend\n\nfunction roots(p::Pol{T}) where {T<:Number}\n    C = companion(p)\n    return eigvals(C)\nend\n", "meta": {"hexsha": "10c7de37df2af2b6104fe2a7db728fb366c4c546", "size": 295, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polynomials/roots.jl", "max_stars_repo_name": "lucaferranti/MatrixPolynomials.jl", "max_stars_repo_head_hexsha": "909ce44f5dc339157ac563769f7ebf089084646f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polynomials/roots.jl", "max_issues_repo_name": "lucaferranti/MatrixPolynomials.jl", "max_issues_repo_head_hexsha": "909ce44f5dc339157ac563769f7ebf089084646f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polynomials/roots.jl", "max_forks_repo_name": "lucaferranti/MatrixPolynomials.jl", "max_forks_repo_head_hexsha": "909ce44f5dc339157ac563769f7ebf089084646f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-31T23:31:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T23:31:12.000Z", "avg_line_length": 22.6923076923, "max_line_length": 54, "alphanum_fraction": 0.5559322034, "num_tokens": 108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9653811581728097, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7777421311548615}}
{"text": "# Parts of this code were taken / derived from NetworkX. See LICENSE for\n# licensing details.\n\n\"\"\"Calculates the [PageRank](https://en.wikipedia.org/wiki/PageRank) of the graph\n`g`. Can optionally specify a different damping factor (`α`), number of\niterations (`n`), and convergence threshold (`ϵ`). If convergence is not\nreached within `n` iterations, an error will be returned.\n\"\"\"\nfunction pagerank(g::DiGraph, α=0.85, n=100, ϵ = 1.0e-6)\n    A = adjacency_matrix(g,:out,Float64)\n    S = vec(sum(A,1))\n    S = 1./S\n    S[find(S .== Inf)]=0.0\n    M = A' # need a separate line due to bug #17456 in julia\n    M = (Diagonal(S) * M)'\n    N = nv(g)\n    x = repmat([1.0/N], N)\n    p = repmat([1.0/N], N)\n    dangling_weights = p\n    is_dangling = find(S .== 0)\n\n    for _ in 1:n\n        xlast = x\n        x = α * (M * x + sum(x[is_dangling]) * dangling_weights) + (1 - α) * p\n        err = sum(abs(x - xlast))\n        if (err < N * ϵ)\n            return x\n        end\n    end\n    error(\"Pagerank did not converge after $n iterations.\")\nend\n", "meta": {"hexsha": "34256b1bc991f8fd8b277fba9c4afb24f7b1c454", "size": 1036, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/centrality/pagerank.jl", "max_stars_repo_name": "JuliaPackageMirrors/LightGraphs.jl", "max_stars_repo_head_hexsha": "b13472899cba49999567bb88f9d32d5d87cf4a19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/centrality/pagerank.jl", "max_issues_repo_name": "JuliaPackageMirrors/LightGraphs.jl", "max_issues_repo_head_hexsha": "b13472899cba49999567bb88f9d32d5d87cf4a19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/centrality/pagerank.jl", "max_forks_repo_name": "JuliaPackageMirrors/LightGraphs.jl", "max_forks_repo_head_hexsha": "b13472899cba49999567bb88f9d32d5d87cf4a19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.375, "max_line_length": 81, "alphanum_fraction": 0.5945945946, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.953966101527047, "lm_q2_score": 0.8152324871074607, "lm_q1q2_score": 0.7777041575641028}}
{"text": "### A Pluto.jl notebook ###\n# v0.11.14\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 2cf61e2a-ff3f-11ea-2d5b-77a2b52fd6e7\nusing CSV, DataFrames\n\n# ╔═╡ 78701408-ff37-11ea-04a8-07805ef3cc1c\nmd\"\"\"\n## Outline\n\nIn this project, we will implement a sowing plan for a mixed culture of three types of crops. At our disposal, we have fifteen plots of land, to be planted using a limited supply of seeds. The different lots have varying soil compositions, influencing plant growth. Furthermore, some combinations of the crops grow well together; other combinations show competition. These aspects make for a challenging optimization problem!\n\"\"\"\n\n# ╔═╡ bea5f54e-ff37-11ea-2c37-8707c75a9b5c\nn = 15\n\n# ╔═╡ 9b5ec9c8-ff37-11ea-1816-0365aa76c976\nmd\"\"\"\n## A model for plant growth\n\nWe have $n=15$ plots of land. The three types of plants are denoted with x, y, and z, respectively. Indices are used to indicate the amount of seed distributed to a particular plot, e.g., $x_i$ is the amount of seed assigned to the $i$-th plot. So this optimization problem can be solved in a $15\\times 3=45$-dimensional space.\n\nSmall-capped variables indicate the amount of seed assigned to a field. Large-cap variables represent the corresponding yield of that field, i.e., $X_i$ is the yield (in kg) for field $i$. The yield for each type of seed can be computed using the following equations:\n\n$$X_i = \\frac{A_i^x x_i^2}{120 + x_i^2 + 2y_i - 0.8x_iz_i + z_i^2}\\,,$$\n\n$$Y_i = \\frac{A_i^y y_i^2}{30 + 4x_i + y_i^2 + 7z_i}\\,,$$\n\n$$Z_i = \\frac{A_i^z z_i^2}{80 + 0.4x_i^2 + 0.2x_iz_i +0.6y_i + z_i^2}\\,.$$\n\"\"\"\n\n# ╔═╡ d327e0c2-ff37-11ea-3006-53be838b7dc8\nmd\"\"\"\nHere, $A_i^x$, $A_i^y$, $A_i^z$ represent the maximum in yields in field $i$ for the different seed types. It depends on the amount of nitrogen $u_i$ and the water status $v_i$ of the soil. The following equation can be used to compute these coefficients:\n\n$$\\begin{bmatrix}\nA_i^x \\\\\nA_i^y\\\\\nA_i^z\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n4 & 2  \\\\\n1 & 0.3 \\\\\n-0.5 & 4\n\\end{bmatrix}\n\\begin{bmatrix}\nu_i \\\\\nv_j\\\\\n\\end{bmatrix}\n+\n\\begin{bmatrix}\n100 \\\\\n300 \\\\\n210\n\\end{bmatrix}\\,.$$\n\"\"\"\n\n# ╔═╡ c9897d6a-ff47-11ea-1212-9d5eb14cd0d7\nS, b = [4 2; 1 0.3; -0.5 4], [100, 300, 210]  # soil effects\n\n# ╔═╡ e4a29d80-ff37-11ea-0d0b-59545bce9bd2\nmd\"\"\"\nThe growth model has several interesting facets:\n- sowing more seed results in a larger yield, however, the effect saturates, increasing quantities have diminishing returns;\n- the plants show competition;\n- z positively influences x, while x negatively influences z (z produces nitrogen while x requires much nitrogen);\n- y is a good producer but very sensitive to adverse conditions.\n\"\"\"\n\n# ╔═╡ ea977544-ff37-11ea-310b-79307ef120d3\nmd\"Below are the concentrations of nitrogen ($u$) and water status ($v$) for every field.\"\n\n# ╔═╡ eba6a9dc-ff37-11ea-233d-1b9aca686ea4\nu = [36.6776, 36.9967, 83.033, 50.3725, 43.4616, 55.5842, 44.8919, 99.6519, 20.158, 102.325, 96.8896, 33.7957, 26.6129, 38.7194, 60.1461]\n\n# ╔═╡ 0e9a6d52-ff38-11ea-2472-810a521cb8f8\nv = [34.5773,  24.3003,  24.3952,  28.462,  37.2912,  38.196,  36.4821,  30.1988,  20.9124,  35.207,  38.0924,  24.438,  28.3169,  20.3022,  24.8884]\n\n# ╔═╡ 100a63f4-ff38-11ea-1fbf-05c136011e28\nmd\"The total amount of seed for every type is fixed by $c_x$, $c_y$, $c_z$:\"\n\n# ╔═╡ 17088b36-ff38-11ea-3519-85055dd00929\ncx, cy, cz = 250, 175, 325\n\n# ╔═╡ 25b72854-ff38-11ea-0817-0f44e6420882\nmd\"Finally, the yield for each crop can be sold at different prices (EUR/kg) $w_x$, $w_y$, $w_z$:\"\n\n# ╔═╡ 223cec90-ff38-11ea-040f-47c9ee1c9036\nwx, wy, wz = 0.7, 0.85, 0.6\n\n# ╔═╡ 3282d3c6-ff38-11ea-0458-af74eb6b42dc\nmd\"\"\"\nSo the objective is\n\n$$f(\\mathbf{x}, \\mathbf{y}, \\mathbf{z}) = \\sum_{i=1}^{15}w_xX_i(x_i,y_i,z_i) + w_yY_i(x_i,y_i,z_i)+w_zZ_i(x_i,y_i,z_i)\\,,$$\n\nbut the constraints are\n\n$$\\sum_{i=1}^{15} x_i \\le c_x \\quad\\text{and}\\quad x_i\\geq 0\\text{ for }i=1,\\ldots,15\\,,$$\n\n$$\\sum_{i=1}^{15} y_i \\le c_y \\quad\\text{and}\\quad y_i\\geq 0\\text{ for }i=1,\\ldots,15\\,,$$\n\n$$\\sum_{i=1}^{15} z_i \\le c_z \\quad\\text{and}\\quad z_i\\geq 0\\text{ for }i=1,\\ldots,15\\,.$$\n\nNote: the sum constraints are inequalities because you don't need to use all the seed. However, the optimal solution will likely use all the available seed.\n\"\"\"\n\n# ╔═╡ 625ffadc-ff48-11ea-1849-39df2c3ddb85\nmd\"\"\"\n## An example\n\nLet us compute the yield for plot 1 when we sow $x_1=10,y_1=6, z_1=8$. First, we compute the maximum yields, then the resulting concrete yields and, finally the value.\n\"\"\"\n\n# ╔═╡ 57dc25e6-ff38-11ea-342c-f19e90a2c732\nx1, y1, z1 = 10, 6, 8  # amount of seed per plot\n\n# ╔═╡ 6137fea8-ff38-11ea-34b7-631de98c3ad4\n(Ax1, Ay1, Az1) = S * [u[1], v[1]] .+ b\n\n# ╔═╡ 7e33d806-ff38-11ea-2297-512188693a6a\nX1 = (Ax1 * x1^2) / (120 + x1^2 + 2y1 - 0.8x1 * z1 + z1^2)\n\n# ╔═╡ 84e7171e-ff38-11ea-07fd-5fb12ff4f039\nY1 = (Ay1 * y1^2) / (30 + 4x1 + y1^2 + 7z1)\n\n# ╔═╡ 85d3cd6e-ff38-11ea-2d7d-539601eec8aa\nZ1 = (Az1 * z1^2) / (80 + 0.4x1 + 0.2x1*z1 +0.6y1 + z1^2)\n\n# ╔═╡ 8a574622-ff38-11ea-15dc-1b4bb63497df\nrevenue_plot1 = wx * X1 + wy * Y1 + wz * Z1  # in EUR\n\n# ╔═╡ 92a481f4-ff39-11ea-1cc0-855d93b3967b\nmd\"\"\"\n# Assignments\n\n1. Give the formal optimization problem. Also provide the Lagrangian formulation.\n2. Is the optimization problem of the optimal sowing plan concave? (since it is a maximization problem, I mean is minimizing the negative total revenue of a plan convex). You don't have to prove this formally, but you can make visual arguments. For a given field, make a the contour plots for (x,y), (x,z) and (y,z), always setting the third variable to 0.\n3. Give a good/optimal sowing plan. You may solve this either using custom code or using a Julia package [Optim.jl](https://github.com/JuliaNLSolvers/Optim.jl), [Convex.jl](https://github.com/jump-dev/Convex.jl), or [JuMP.jl](https://github.com/jump-dev/JuMP.jl). Make plots of your solution and discuss it.\n4. Given an optimal sowing plan found in the previous assignment, what is the price per kg for every seed you would be willing to buy, as to be break-even? How would you use this additional marginal quantity of seed. (HINT: you can obtain this from the Lagrangian).\n5. Provide three alternative solutions, each in which you only use one of the types of seed, e.g. $\\max_\\mathbf{x}f(\\mathbf{x}, 0, 0)$. Show and discuss the difference.\n\"\"\"\n\n# ╔═╡ ea2c0d3e-ff43-11ea-14f4-932602b2fecd\nmd\"\"\"\n## Submission\n\nHand in the solved Jupyter notebook by **14 November 2020**. Send your notebook to [me](michiel.stock@ugent.be) both as Pluto notebook file (.jl) and as **PDF or HTML file**. Hand in a CSV file with your best **valid** solution for question 3. In this file, every row is a plot of land and the three columns represent x, y, z, respectively.\n\"\"\"\n\n# ╔═╡ 64049c58-ff37-11ea-1ae8-f907d5e33509\nstudent_name = missing  # fill in your name(s)\n\n# ╔═╡ 2568b67a-ff37-11ea-37fd-87a3d569fc31\nmd\"\"\"\n# Project: Sowing plan\n\n**STMO**\n\n2020-2021\n\nProject by: $student_name\n\"\"\"\n\n# ╔═╡ ddab3252-07bc-11eb-390a-750512ee8c90\nif ismissing(student_name)\n\tmd\"fill in your name(s) below\"\nend\n\n# ╔═╡ 562bc43a-ff43-11ea-0451-d9e7005c56a1\nmd\"\"\"\n### 1. Formal description of the problem\n\nCOMPLETE\n\"\"\"\n\n# ╔═╡ 5232b83c-ff43-11ea-36e4-7d08693203dc\nmd\"\"\"\n### 2. Concavity\n\nCOMPLETE\n\"\"\"\n\n# ╔═╡ 8cb9cf68-ff43-11ea-399d-df193400c077\nmd\"\"\"\n### 3. Making a sowing plan\n\nHere, you have the space to solve the problem. Save your final solution in the variable `solution` and save it in a csv file using `save_solution`. This is done automatically when your name is filled in.\n\"\"\"\n\n# ╔═╡ 9d2eabae-ff43-11ea-3103-0f22b5c59e6b\n\n\n# ╔═╡ 9cd521d8-ff43-11ea-174e-71556bcdebac\n\n\n# ╔═╡ 67882c04-ff3f-11ea-19b5-890bd3bd15a9\nsolution = fill(1.0, 15, 3)  # valid, but can be improved...\n\n# ╔═╡ 0a220a2a-ff45-11ea-2b35-c70cdb18c0a8\nmd\"Check if the solution is valid.\"\n\n# ╔═╡ 1411424e-ff45-11ea-2b3e-c75c7d39917a\nmd\"Save the solution.\"\n\n# ╔═╡ 07575a02-ff45-11ea-2794-63681f41a7bf\nmd\"\"\"\n### 4. Price of seed\n\nCompute how much you would pay for each additional unit of seed in your solution.\n\"\"\"\n\n# ╔═╡ 79df7272-ff44-11ea-01bb-716d0bf52464\n\n\n# ╔═╡ 79a661b0-ff44-11ea-10ef-fbc61315162b\nmd\"\"\"\n### 5. One type of seed\n\nMake three solutions in which you only use one type of seed. Analyse your solutions!\n\"\"\"\n\n# ╔═╡ 79897d9a-ff44-11ea-269c-bba522b74d66\n\n\n# ╔═╡ 796e75c2-ff44-11ea-2a85-0b3fbdc675b5\n\n\n# ╔═╡ 0ba3f5f6-ff46-11ea-0449-29b505430cf9\n\n\n# ╔═╡ 7ade6b7e-ff44-11ea-130a-bdd36b48b8af\nmd\"## Functions\"\n\n# ╔═╡ b96c0828-ff3b-11ea-3ee3-b979608fe705\n\"\"\"Check if a solution is valid.\"\"\"\nfunction isvalidsolution(solution::Matrix)\n\treturn size(solution) == (15, 3) && all(solution .≥ 0.0) && all(sum(solution, dims=1) .≤ [cx cy cz])\nend\n\n# ╔═╡ 6f98672e-ff3f-11ea-0198-5fbef05027da\nisvalidsolution(solution)\n\n# ╔═╡ a9ca6492-ff44-11ea-3b51-3905bf9280cf\n\"\"\"Save the solution to a file for submission.\"\"\"\nfunction save_solution(fname, solution::Matrix)\n\t@assert isvalidsolution(solution) \"Oh no, your solution is invalid!\"\n\tCSV.write(fname, DataFrame(solution))\nend\n\n# ╔═╡ 928fd032-ff3f-11ea-13a0-07140325ab9f\n!ismissing(student_name) && save_solution(\"solution_$(student_name).csv\", solution);\n\n# ╔═╡ Cell order:\n# ╟─2568b67a-ff37-11ea-37fd-87a3d569fc31\n# ╟─ddab3252-07bc-11eb-390a-750512ee8c90\n# ╟─78701408-ff37-11ea-04a8-07805ef3cc1c\n# ╠═bea5f54e-ff37-11ea-2c37-8707c75a9b5c\n# ╟─9b5ec9c8-ff37-11ea-1816-0365aa76c976\n# ╟─d327e0c2-ff37-11ea-3006-53be838b7dc8\n# ╠═c9897d6a-ff47-11ea-1212-9d5eb14cd0d7\n# ╟─e4a29d80-ff37-11ea-0d0b-59545bce9bd2\n# ╟─ea977544-ff37-11ea-310b-79307ef120d3\n# ╠═eba6a9dc-ff37-11ea-233d-1b9aca686ea4\n# ╠═0e9a6d52-ff38-11ea-2472-810a521cb8f8\n# ╟─100a63f4-ff38-11ea-1fbf-05c136011e28\n# ╠═17088b36-ff38-11ea-3519-85055dd00929\n# ╟─25b72854-ff38-11ea-0817-0f44e6420882\n# ╠═223cec90-ff38-11ea-040f-47c9ee1c9036\n# ╟─3282d3c6-ff38-11ea-0458-af74eb6b42dc\n# ╟─625ffadc-ff48-11ea-1849-39df2c3ddb85\n# ╠═57dc25e6-ff38-11ea-342c-f19e90a2c732\n# ╠═6137fea8-ff38-11ea-34b7-631de98c3ad4\n# ╠═7e33d806-ff38-11ea-2297-512188693a6a\n# ╠═84e7171e-ff38-11ea-07fd-5fb12ff4f039\n# ╠═85d3cd6e-ff38-11ea-2d7d-539601eec8aa\n# ╠═8a574622-ff38-11ea-15dc-1b4bb63497df\n# ╟─92a481f4-ff39-11ea-1cc0-855d93b3967b\n# ╟─ea2c0d3e-ff43-11ea-14f4-932602b2fecd\n# ╠═64049c58-ff37-11ea-1ae8-f907d5e33509\n# ╠═562bc43a-ff43-11ea-0451-d9e7005c56a1\n# ╠═5232b83c-ff43-11ea-36e4-7d08693203dc\n# ╟─8cb9cf68-ff43-11ea-399d-df193400c077\n# ╠═9d2eabae-ff43-11ea-3103-0f22b5c59e6b\n# ╠═9cd521d8-ff43-11ea-174e-71556bcdebac\n# ╠═67882c04-ff3f-11ea-19b5-890bd3bd15a9\n# ╟─0a220a2a-ff45-11ea-2b35-c70cdb18c0a8\n# ╠═6f98672e-ff3f-11ea-0198-5fbef05027da\n# ╟─1411424e-ff45-11ea-2b3e-c75c7d39917a\n# ╠═928fd032-ff3f-11ea-13a0-07140325ab9f\n# ╟─07575a02-ff45-11ea-2794-63681f41a7bf\n# ╠═79df7272-ff44-11ea-01bb-716d0bf52464\n# ╟─79a661b0-ff44-11ea-10ef-fbc61315162b\n# ╠═79897d9a-ff44-11ea-269c-bba522b74d66\n# ╠═796e75c2-ff44-11ea-2a85-0b3fbdc675b5\n# ╠═0ba3f5f6-ff46-11ea-0449-29b505430cf9\n# ╟─7ade6b7e-ff44-11ea-130a-bdd36b48b8af\n# ╠═2cf61e2a-ff3f-11ea-2d5b-77a2b52fd6e7\n# ╠═b96c0828-ff3b-11ea-3ee3-b979608fe705\n# ╠═a9ca6492-ff44-11ea-3b51-3905bf9280cf\n", "meta": {"hexsha": "a834f126a458eace24cb2c6a267dff4092041d5b", "size": 10976, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "project/project_sowing_plan.jl", "max_stars_repo_name": "tjvneste/STMO", "max_stars_repo_head_hexsha": "e442dbb130505300a4e81e8abf61ed64a1795e6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project/project_sowing_plan.jl", "max_issues_repo_name": "tjvneste/STMO", "max_issues_repo_head_hexsha": "e442dbb130505300a4e81e8abf61ed64a1795e6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project/project_sowing_plan.jl", "max_forks_repo_name": "tjvneste/STMO", "max_forks_repo_head_hexsha": "e442dbb130505300a4e81e8abf61ed64a1795e6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9868852459, "max_line_length": 425, "alphanum_fraction": 0.7189322157, "num_tokens": 4925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7776952664431173}}
{"text": "# this shows effects of het. on the OLS estimator\nusing Plots, Distributions, Econometrics, LinearAlgebra, Statistics\nfunction main()\nhet = true  # set this to true or false\nn = 50 # sample size\n\n# the function we simulate\nfunction wrapper(het, n)\n  x = randn(n)\n  e = randn(n)\n  if het\n    e = x .* e # note the heteroscedasticity here\n  end\n  y = x + e # true coefs are zero for const, and 1 for slope\n  x = [ones(n) x]\n  b, varb, junk, junk, junk = ols(y, x, vc=\"standard\",silent=true)\n  H0 = [0; 1] # coefficient values under true null hypothesis\n  t = (b - H0) ./ sqrt.(diag(varb))\nend\n\n# simulation loop\nreps = 1000\nts = zeros(reps,2)\nfor rep = 1:reps\n    ts[rep,:] = wrapper(het, n)\nend    \nts = abs.(ts)\ncrit_val = quantile(TDist(n-2),0.95) # 5# of prob. is to the R of this value\ntest = ts .> crit_val # now it\"s a 10# signif. level test, because of the abs value\nif het\n  println(\"data is heteroscedastic\")\nelse\n  println(\"data is homoscedastic\")\nend\nprintln(\"rejection frequency of nominal 10 percent test\")\nprintln(\"intercept: \", sum(test[:,1]/reps))\nprintln(\"slope: \", sum(test[:,2]/reps))\n\nplot([0.0; 1.0],sum(test,dims=1)'/1000, linetype=:bar, label=\"0 is intercept, 1 is slope\")\n#savefig(\"EffectsOLS.svg\")\ngui()\nreturn\nend\nmain()\n", "meta": {"hexsha": "71c5e74cecdccea731ffcdfdf4caef886a5fefab", "size": 1246, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/GLS/EffectsOLS.jl", "max_stars_repo_name": "nilshg/Econometrics", "max_stars_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-17T06:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T06:32:18.000Z", "max_issues_repo_path": "Examples/GLS/EffectsOLS.jl", "max_issues_repo_name": "nilshg/Econometrics", "max_issues_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/GLS/EffectsOLS.jl", "max_forks_repo_name": "nilshg/Econometrics", "max_forks_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-02T08:27:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-02T08:27:17.000Z", "avg_line_length": 27.6888888889, "max_line_length": 90, "alphanum_fraction": 0.6701444623, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7776537577612671}}
{"text": "using Combinatorics\n\n# Checks if val is sum of n values in arr\nfunction is_sum(val, arr; n=2)\n    s = with_replacement_combinations(arr, n)\n    sums = []\n    for i in s\n        push!(sums, sum(i))\n    end\n\n    if val in sums\n        return true\n    else\n        return false\n    end\nend\n\n# Check all vals in a window of size preamble\nfunction check_vals(file; preamble = 25)\n    i = 1\n    while i <= (length(file) - preamble)\n        j = i + preamble - 1\n        arr = file[i:j]\n        val = file[j+1]\n\n        if is_sum(val, arr)\n            i += 1\n        else\n            return val\n        end\n    end\nend\n\n# Function to find the weakness\n# Defined as the sum of the min and max\n# values of a continuous section of code\n# that sum to the invalid value\nfunction find_weakness(file, val)\n    i = 1\n    di = 1\n    \n    # Do forever!\n    while true\n        j = i + di\n        arr = file[i:j]\n        s = sum(arr)\n\n        if s == val\n            return minimum(arr) + maximum(arr)\n        elseif s > val\n            i += 1\n            di = 1\n        else\n            di += 1\n        end\n    end\n     \nend\n\n# Test values\ntest_vals = [35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576,]\n\ndata =  parse.(Int, readlines(\"./XMAS_data.txt\"))\nprintln(\"Test: \", check_vals(test_vals, preamble=5))\ninval = check_vals(data)\nprintln(\"Real: \", inval)\nprintln(\"Encryption weakness: \", find_weakness(data, inval))\n", "meta": {"hexsha": "30c447bb853161bd405654ae596ee2850ee50ca5", "size": 1440, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "09/09.jl", "max_stars_repo_name": "lsterzinger/advent_of_code_2020", "max_stars_repo_head_hexsha": "735f118ce057ad793fbe73663cb7ceed6f99ecf4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "09/09.jl", "max_issues_repo_name": "lsterzinger/advent_of_code_2020", "max_issues_repo_head_hexsha": "735f118ce057ad793fbe73663cb7ceed6f99ecf4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "09/09.jl", "max_forks_repo_name": "lsterzinger/advent_of_code_2020", "max_forks_repo_head_hexsha": "735f118ce057ad793fbe73663cb7ceed6f99ecf4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1764705882, "max_line_length": 103, "alphanum_fraction": 0.5548611111, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7776537454795569}}
{"text": "@doc raw\"\"\"\n    Oblique{N,M} <: AbstractPowerManifold\n\nThe oblique manifold $\\mathcal{OB}(n,m)$ is the set of real-valued matrices with unit norm\ncolumn endowed with the metric from the embedding. This yields exactly the same metric as\nconsidering the product metric of the unit norm vectors, i.e. [`PowerManifold`](@ref) of the\n$(n-1)$-dimensional [`Sphere`](@ref).\n\nThe [`Sphere`](@ref) is stored internally within `M.manifold`, such that all functions of\n[`AbstractPowerManifold`](@ref) can be used directly.\n\n# Constructor\n\n    Oblique(n,m)\n\nGenerate the manifold of matrices $\\mathbb R^{n × m}$ such that the $m$ columns are unit\nvectors, i.e. from the [`Sphere`](@ref)`(n-1)`.\n\"\"\"\nstruct Oblique{N,M} <: AbstractPowerManifold{Sphere{N},ArrayPowerRepresentation}\n    manifold::Sphere{N}\nend\n\nOblique(n::Int, m::Int) = Oblique{n - 1,m}(Sphere(n - 1))\n\n^(M::Sphere{N}, m::Int) where {N} = Oblique{N,m}(M)\n\n@doc raw\"\"\"\n    check_manifold_point(M::Oblique{n,m},p)\n\nChecks whether `p` is a valid point on the [`Oblique`](@ref)`{m,n}` `M`, i.e. is a matrix\nof `m` unit columns from $\\mathbb R^{n+1}$, i.e. each column is a point from\n[`Sphere`](@ref)`(n)`.\n\"\"\"\ncheck_manifold_point(::Oblique, ::Any)\nfunction check_manifold_point(M::Oblique{Ns,Ms}, p; kwargs...) where {Ns,Ms}\n    if size(p) != (Ns + 1, Ms)\n        return DomainError(\n            length(p),\n            \"The matrix in `p` ($(size(p))) does not match the dimension of Oblique $((Ns,Ms)).\",\n        )\n    end\n    return check_manifold_point(PowerManifold(M.manifold, Ms), p; kwargs...)\nend\n@doc raw\"\"\"\n    check_tangent_vector(M::Oblique p, X; check_base_point = true, kwargs...)\n\nChecks whether `X` is a valid tangent vector to `p` on the [`Oblique`](@ref) `M`.\nThis means, that `p` is valid, that `X` is of correct dimension and columnswise\na tangent vector to the columns of `p` on the [`Sphere`](@ref).\nThe optional parameter `check_base_point` indicates, whether to call [`check_manifold_point`](@ref)  for `p`.\n\"\"\"\nfunction check_tangent_vector(\n    M::Oblique{Ns,Ms},\n    p,\n    X;\n    check_base_point = true,\n    kwargs...,\n) where {Ns,Ms}\n    if check_base_point && size(p) != (Ns + 1, Ms)\n        return DomainError(\n            length(p),\n            \"The matrix `p` ($(size(p))) does not match the dimension of Oblique $((Ns,Ms)).\",\n        )\n    end\n    if size(X) != (Ns + 1, Ms)\n        return DomainError(\n            length(X),\n            \"The matrix `X` ($(size(X))) does not match the dimension of Oblique $((Ns,Ms)).\",\n        )\n    end\n    return check_tangent_vector(\n        PowerManifold(M.manifold, Ms),\n        p,\n        X;\n        check_base_point = check_base_point,\n        kwargs...,\n    )\nend\n\nget_iterator(M::Oblique{Ns,Ms}) where {Ns,Ms} = 1:Ms\n\n@generated manifold_dimension(::Oblique{N,M}) where {N,M} = (N) * M\n\n@generated representation_size(::Oblique{N,M}) where {N,M} = (N + 1, M)\n\nshow(io::IO, ::Oblique{N,M}) where {N,M} = print(io, \"Oblique($(N+1),$(M))\")\n", "meta": {"hexsha": "98d1d48968931a866d7374073fa300322857a798", "size": 2966, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/manifolds/Oblique.jl", "max_stars_repo_name": "dahong67/Manifolds.jl", "max_stars_repo_head_hexsha": "f070e54148695cfde09cc7110b9df7105dd96851", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/manifolds/Oblique.jl", "max_issues_repo_name": "dahong67/Manifolds.jl", "max_issues_repo_head_hexsha": "f070e54148695cfde09cc7110b9df7105dd96851", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/manifolds/Oblique.jl", "max_forks_repo_name": "dahong67/Manifolds.jl", "max_forks_repo_head_hexsha": "f070e54148695cfde09cc7110b9df7105dd96851", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.091954023, "max_line_length": 109, "alphanum_fraction": 0.6304787593, "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7776537450346345}}
{"text": "using EngEconomics, Roots, Plots, ColorSchemes\nplotly()\n\nuwEngColorScheme = ColorScheme([parse(Colorant, \"#D0B4E7\"), parse(Colorant, \"#57058B\"), parse(Colorant, \"#8100B4\"), parse(Colorant, \"#000000\")])\n\n# Given\nn = 5\ntimeDelay = 3\nA = 10\nG = 1\nMARR = 0.15\nsensitivity = [0.85, 0.925, 1.0, 1.075, 1.15]\n\n# Find\n# Construct a sensitivity graph for the interest rate:\nNPW_interest = (A .+ G * sinkingFundPaymentArithmetic.(MARR * sensitivity, n + 1)) .* uniformSeriesCompoundAmoundFactor.(MARR * sensitivity, (n + 1)) .* presentWorthFactor.(MARR * sensitivity, n + timeDelay)\nplot(sensitivity, NPW_interest, label=\"Interest\", legend=:outerbottomright,\n\txlabel=\"Sensitivity (+/- 7.5%, 15%)\",\n\tylabel=\"Net Present Worth (\\$1000)\",\n\ttitle=\"Sensitivity of Interest Rate, Base Savings,<br> and Saving Gradient\",\n\tpalette=cgrad(uwEngColorScheme))\n\n# Construct a sensitivity graph for the base savings\nNPW_baseSavings = (A * sensitivity .+ G * sinkingFundPaymentArithmetic.(MARR, n + 1)) .* uniformSeriesCompoundAmoundFactor.(MARR, n + 1) .* presentWorthFactor.(MARR, n + timeDelay)\nplot!(sensitivity, NPW_baseSavings, label=\"Base Savings\")\n\n# Construct a sensitivity graph for the savings gradient\nNPW_gradientSavings = (A .+ G * sensitivity * sinkingFundPaymentArithmetic.(MARR, n + 1)) .* uniformSeriesCompoundAmoundFactor.(MARR, n + 1) .* presentWorthFactor.(MARR, n + timeDelay)\nplot!(sensitivity, NPW_gradientSavings, label=\"Gradient Savings\")\n", "meta": {"hexsha": "c801b088acd577df9fdb362229f780de434aa6ea", "size": 1440, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps8/p3.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/ps8/p3.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/ps8/p3.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.0, "max_line_length": 207, "alphanum_fraction": 0.7361111111, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.8376199613065411, "lm_q1q2_score": 0.7776537419387166}}
{"text": "# Divergence calculation\n\n\"\"\"\n\tdivergence_ndgrid!(hx, hy, hz, vec, div)\n\nGeneric divergence `div` of vector `vec` with step lengths `hx`, `hy`, `hz`.\n\"\"\"\nfunction divergence_ndgrid!(hx, hy, hz, vec, div)\n\n   siz = size(vec)::NTuple{4,Int64}\n\n   px = zeros(Float64, Base.front(siz))\n   qy = zeros(Float64, Base.front(siz))\n   rz = zeros(Float64, Base.front(siz))\n\n   n = size(hx, 1)\n   # Right now do nothing for the ghost cells maybe needed later!\n   # Take central differences on interior points\n   if n > 2\n      compute_px(siz, px, n, hx, vec)\n   end\n\n   n = size(hy, 1)\n   if n > 2\n      compute_qy(siz, qy, n, hx, vec)\n   end\n\n   n = size(hz, 1)\n   if n > 2\n      compute_rz(siz, rz, n, hx, vec)\n   end\n\n   @. div = px + qy + rz\n   return\nend\n\nfunction divergence_ndgrid(hx, hy, hz, vec)\n\n   siz = size(vec)\n\n   div = zeros(Float64, Base.front(siz))\n\n   divergence_ndgrid!(hx, hy, hz, vec, div)\n\n   return div\nend\n\nfunction compute_px(siz, px, n, hx, vec)\n   @inbounds for i = 1:n-2, j = 1:siz[2], k = 1:siz[3]\n      px[i+1,j,k] = (vec[i+2,j,k,1] - vec[i,j,k,1])/(hx[i+2] - hx[i])\n   end\nend\n\nfunction compute_qy(siz, qy, n, hy, vec)\n   @inbounds for i = 1:siz[1], j = 1:n-2, k = 1:siz[3]\n      qy[i,j+1,k] = (vec[i,j+2,k,2] - vec[i,j,k,2])/(hy[i+2] - hy[i])\n   end\nend\n\nfunction compute_rz(siz, rz, n, hz, vec)\n   @inbounds for i = 1:siz[1], j = 1:siz[2], k = 1:n-2\n      rz[i,j,k+1] = (vec[i,j,k+2,3] - vec[i,j,k,3])/(hz[i+2] - hz[i])\n   end\nend\n\n\"\"\"\n   divergence!(param, vec, div)\n\nCalculate the divergence of vectors specialized to my grid size.\nAlways assume starting with i -> j -> k for 1/2/3D!\nRight now do nothing for the ghost cells. Maybe needed later!\nTake central differences on interior points.\n\"\"\"\n@inline function divergence!(param, vec, div)\n\n   x, y, z = param.x, param.y, param.z\n   nI, nJ, nK, nG = param.nI, param.nJ, param.nK, param.nG\n   iMin, iMax, jMin, jMax, kMin, kMax =\n   param.iMin, param.iMax, param.jMin, param.jMax, param.kMin, param.kMax\n   \n   div .= 0.0\n\n   @inbounds for k = kMin:kMax, j = jMin:jMax, i = iMin:iMax\n      div[i-nG,j-nG,k-nG] = (vec[i+1,j,k,1] - vec[i-1,j,k,1]) / (x[i+1] - x[i-1])\n   end\n\n   if nJ > 1\n      @inbounds for k = kMin:kMax, j = jMin:jMax, i = iMin:iMax\n         div[i-nG,j-nG,k-nG] += (vec[i,j+1,k,2] - vec[i,j-1,k,2]) / (y[i+1] - y[i-1])\n      end\n   end\n\n   if nK > 1\n      @inbounds for k = kMin:kMax, j = jMin:jMax, i = iMin:iMax\n         div[i-nG,j-nG,k-nG] += (vec[i,j,k+1,3] - vec[i,j,k-1,3]) / (z[i+1] - z[i-1])\n      end\n   end\n\n   return\nend", "meta": {"hexsha": "d89339ceb9cd16dfeab4987efbb606b05ced919b", "size": 2523, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/divergence.jl", "max_stars_repo_name": "henry2004y/Dante", "max_stars_repo_head_hexsha": "e8399f927b1d0e7a4907229960462dbb1096b738", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-19T06:05:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-31T21:24:16.000Z", "max_issues_repo_path": "src/divergence.jl", "max_issues_repo_name": "henry2004y/Dante", "max_issues_repo_head_hexsha": "e8399f927b1d0e7a4907229960462dbb1096b738", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-12-20T16:21:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-14T13:11:29.000Z", "max_forks_repo_path": "src/divergence.jl", "max_forks_repo_name": "henry2004y/DanteJulia", "max_forks_repo_head_hexsha": "ec339e0f2bfdf6414d193a0c142efaa8404ada2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.23, "max_line_length": 85, "alphanum_fraction": 0.5766944114, "num_tokens": 999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7776537381754149}}
{"text": "\"\"\"\n    tensordecomp(k::Int, d::Int)\n\nDecomposition of the integers  0:(k^p - 1) in powers of k.\n\n\n\"\"\"\nfunction tensordecomp(k::Int, d::Int)\n\n    sequences = zeros(Int, k^d, d)\n\n    for n = 0:k^d-1\n        i = d\n        m = n\n\n        while i > 0\n            i = i - 1\n            j = i\n            f = floor(Int, m / k^i)\n\n            while j > 0 && f == 0\n                j = j - 1\n                f = floor(Integer, m / k^j)\n            end\n\n            if f > 0\n                sequences[n + 1, j + 1, ] = f\n                i = j\n            elseif f == 0\n                sequences[n + 1, 1] = m\n                i = 0\n            end\n            m = m - f * k^i\n        end\n    end\n\n    return sequences\nend\n\n\n\"\"\"\n    even_sampling_rules(dim::Int, split_factor::Int) -> Array{Float64, 2}\n\nGenerate rules for evenly distributed points within a simplex. To do this,\nwe perform a shape-preserving splitting of the simplex, given a splitting\nfactor.\n\nReturns the convex expansion coefficients of the points of the resulting\nsubsimplices in terms of the vertices of the original simplex.\n\"\"\"\nfunction even_sampling_rules(dim::Int, split_factor::Int)\n\n    sequences::Array{Int, 2} = tensordecomp(split_factor, dim)\n    n_seq = size(sequences, 1)\n\n    χ1 = sequences .* (dim + 1)\n    χ2 = repeat(transpose(collect(1:dim)), n_seq, 1)\n    χ::Array{Int, 2} = χ1 .+ χ2\n    χ = sort(χ, dims=2)\n\n    # Define multiplicity matrix M\n    M = zeros(Float64, size(χ, 1), size(χ, 2) + 1)\n    M[:, 1] = χ[:, 1]\n    M[:, 2:(end - 1)] = χ[:, 2:end] - χ[:, 1:(end - 1)]\n    M[:, end] = (dim+1)*split_factor * ones(size(χ, 1)) - χ[:, end]\n\n    M = M ./ (split_factor * (dim + 1))\n\n    return copy(transpose(M))\nend\n\nexport even_sampling_rules\n\n\"\"\"\nEvenly sample points within a simplex by performing a shape-preserving\nsubdivision of the simplex with a given `split_factor`. If the simplex\nlives in a space of dimension `dim`, the resulting number of points is\n`split_factor`^(dim).\n\"\"\"\nfunction evenly_sample(simplex::AbstractArray{Float64, 2}, split_factor::Int)\n    dim = size(simplex, 2)\n    centroids_exp_coeffs = copy(transpose(even_sampling_rules(dim, split_factor)))\n    centroids_exp_coeffs * simplex\nend\n\n\n\"\"\"\nReturns a matrix of convex coefficients to construct points contained within\na `dim`-dimensional simplex. Coefficients can either be random (generated\naccording to a uniform distribution) or be constructed such that the resulting\npoints are uniformly distributed within the simplex (generated by shape-preserving\nsplitting a generic simplex). The `sample_randomly` argument controls this\nbehaviour.\n\nThe default is to not sample randomly (`sample_randomly = false`). In this case,\nyou won't get the exact number of convex coefficient sets you want, but the\nsmallest number of set of coefficients such that you have *at least* `n_pts`\nconvex coefficient sets.\n\nIf `sample_randomly = true`, you get as many convex coefficient combinations as\n`n_pts`.\n\"\"\"\nfunction subsample_coeffs(dim::Int, n_randpts::Int, sample_randomly::Bool)\n    # Create a set of convex coefficients to be used for all simplices\n    if sample_randomly\n        convex_coeffs = rand(Uniform(0, 1), dim + 1, n_randpts)\n        convex_coeffs .= convex_coeffs ./ sum(convex_coeffs, dims=1) #convex_coeffs ./ sum(convex_coeffs, dims=2)\n    else\n        minimum_split_factor = ceil(Int, n_randpts^(1 / dim))[1]\n        convex_coeffs = even_sampling_rules(dim, minimum_split_factor)\n    end\n    return convex_coeffs\nend\n\nexport subsample_coeffs\n\n", "meta": {"hexsha": "50e7a05edd2e2561c681d5898a41afb71a91b7da", "size": 3508, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Discretization/TriangulationPartitions/Simplices/simplex_subsampling.jl", "max_stars_repo_name": "JuliaDynamics/StateSpaceReconstruction.jl", "max_stars_repo_head_hexsha": "d53dff4be52a319d435631768ac0560333629996", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-15T14:27:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T00:08:07.000Z", "max_issues_repo_path": "src/Discretization/TriangulationPartitions/Simplices/simplex_subsampling.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StateSpaceReconstruction.jl-1441a9f6-6a74-5418-a591-cdf1d78a07f0", "max_issues_repo_head_hexsha": "acb3f9705c6786c8db08a9841cfbe9ec8be0aec9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2018-04-23T20:14:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-01T13:36:05.000Z", "max_forks_repo_path": "src/Discretization/TriangulationPartitions/Simplices/simplex_subsampling.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StateSpaceReconstruction.jl-1441a9f6-6a74-5418-a591-cdf1d78a07f0", "max_forks_repo_head_hexsha": "acb3f9705c6786c8db08a9841cfbe9ec8be0aec9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:03:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:03:06.000Z", "avg_line_length": 29.9829059829, "max_line_length": 113, "alphanum_fraction": 0.6470923603, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087926320944, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7776537350794968}}
{"text": "\n\"\"\"\n    angle_of_incidence(lat,lon,jd,time)\n\nCalculate the cosine of the sun incident angle for a given location (lat,lon),\njulian day (jd) and time in hours and fraction of hours.\n\"\"\"\nfunction angle_of_incidence(lat, lon, jd, time)\n    # inclination angle\n    delta = (asin(-sin(23.45 / 180 * pi) .* cos(360 / 365.25 * (jd + 10) / 180 * pi)))\n    # lat to radians\n    lamda = lat / 180 * pi\n    # time to radians\n    omega = time / 24 * 2 * pi + lon / 360 * 2 * pi + pi\n\n    return cos(delta) * cos(lamda) * cos(omega) + sin(delta) * sin(lamda)\nend\n\n\"\"\"\n    delta(jd)\n\nCalculates the Sun's declination angle as a function of Julian day (jd)\n\"\"\"\ndelta(n) = (asin(-sin(23.45 / 180 * pi) .* cos(360 / 365.25 * (n + 10) / 180 * pi)))\n\n\n\"\"\"\n    heaviside(x)\n\nHeaviside function : 0 when x<0 and 1 when x>=0\n\"\"\"\nfunction heaviside(x)\n    y = zeros(size(x))\n    y[x.>=0] .= 1\n    return y\nend\n", "meta": {"hexsha": "b82a84a19da2a3edef7fcea878dddf705c23d629", "size": 888, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/AOGCM1D_helpers.jl", "max_stars_repo_name": "zhenwu0728/AirSeaFluxes.jl", "max_stars_repo_head_hexsha": "0988c88fd4205df5dd41e1de749760a77c9ebcf6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-07T02:44:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-07T02:44:20.000Z", "max_issues_repo_path": "src/AOGCM1D_helpers.jl", "max_issues_repo_name": "zhenwu0728/AirSeaFluxes.jl", "max_issues_repo_head_hexsha": "0988c88fd4205df5dd41e1de749760a77c9ebcf6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-02-16T17:33:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-13T17:57:23.000Z", "max_forks_repo_path": "src/AOGCM1D_helpers.jl", "max_forks_repo_name": "zhenwu0728/AirSeaFluxes.jl", "max_forks_repo_head_hexsha": "0988c88fd4205df5dd41e1de749760a77c9ebcf6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-08T19:07:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-08T19:07:31.000Z", "avg_line_length": 24.0, "max_line_length": 86, "alphanum_fraction": 0.6013513514, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7776474083986401}}
{"text": "\"\"\"\nCalculates the average of the elements in a vector ``x``.\n\"\"\"\nfunction sample_mean(x::Vector)\n    n = length(x)\n    x̅ = 1 / n * sum(x)\n    return x̅\nend\n\n\n\"\"\"\nCalculates the sample variance of the elements in a vector ``x``.\n\"\"\"\nfunction sample_variance(x::Vector)\n    n = length(x)\n    s² = 1 / (n - 1) * (sum(x.^2) - 1 / n * sum(x)^2)\n    return s² \nend\n\n\n\"\"\"\nCalculates the covariance of vector ``x``.\n\"\"\"\nfunction sample_covariance(x::Vector)\n    n = length(x)\n    cᵪᵪ = sum_of_squares(x) / (n - 1)\n    return cᵪᵪ \n    \nend\n\n\n\"\"\"\nCalculates the covariance of two vectors ``x`` and ``y``. \n\"\"\"\nfunction two_sample_covariance(x::Vector, y::Vector)\n    n = length(x)\n    cᵪᵧ = 1 / (n -1) * (sum(x .* y) - 1 / n * sum(x) * sum(y))\n    return cᵪᵧ\nend\n\n\n\"\"\"\nCalculates the correlation coefficient of two vectors ``x`` and ``y``.\nSee also: [`sample_variance`](@ref), [`two_sample_covariance`](@ref). \n\"\"\"\nfunction two_sample_correlation_coefficient(x::Vector, y::Vector)\n    sᵪ = √(sample_variance(x))\n    sᵧ = √(sample_variance(y))\n    cᵪᵧ = two_sample_covariance(x, y)\n    rᵪᵧ = cᵪᵧ / (sᵪ * sᵧ)\n    return rᵪᵧ\nend\n\n\n\"\"\"\nCalculates the sample variance of two vectors ``x`` and ``y``.\nUsed mainly for calculating reference variables for significance tests when the variance is unknown.\nSee also: [`sample_variance`](@ref). \n\"\"\"\nfunction two_sample_variance(x::Vector, y::Vector)\n    nᵪ = length(x)\n    nᵧ = length(y)\n    s²ᵪ = sample_variance(x)\n    s²ᵧ = sample_variance(y)\n    s²ᵪᵧ = ((nᵪ - 1) * s²ᵪ + (nᵧ - 1) * s²ᵧ) / (nᵪ + nᵧ - 2)\n    return s²ᵪᵧ    \nend\n\n\n\"\"\"\nThis function calculates the sum of squares. \nThis is used mainly for estimating the parameters in simple linear regression.\nSee also: [`not_implemented`](@ref).\n\"\"\"\nfunction sum_of_squares(x::Vector, y=x::Vector)\n    n = length(x)\n    Sᵪᵧ = (sum(x .* y) - 1 / n * sum(x) * sum(y))\n    return Sᵪᵧ \nend\n", "meta": {"hexsha": "62c6a4c1ca17bd6ccfdb5152e50dc681e5680250", "size": 1870, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DescriptiveStatistics.jl", "max_stars_repo_name": "persson-io/Stochastics.jl", "max_stars_repo_head_hexsha": "548c82646d786d9153015bd4a95fd2ea5e4861cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-02T19:01:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-02T19:01:17.000Z", "max_issues_repo_path": "src/DescriptiveStatistics.jl", "max_issues_repo_name": "persson-io/Stochastics", "max_issues_repo_head_hexsha": "548c82646d786d9153015bd4a95fd2ea5e4861cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DescriptiveStatistics.jl", "max_forks_repo_name": "persson-io/Stochastics", "max_forks_repo_head_hexsha": "548c82646d786d9153015bd4a95fd2ea5e4861cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.375, "max_line_length": 100, "alphanum_fraction": 0.6245989305, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7776474027895411}}
{"text": "function derivative(fn)\n    return function(x)\n        # pick a small value for h\n        h = x == 0 ? sqrt(eps(Float64)) : sqrt(eps(Float64)) * x\n        # floating point arithmetic gymnastics\n        xph = x + h\n        dx = xph - x\n        # evaluate f at x + h\n        f1 = fn(xph)\n        # evaluate f at x\n        f0 = fn(x)\n        # divide the difference by h\n        # return (fn(xph) - fn(x)) / dx\n        return (f1 - f0) / dx\n    end\n\n# 1st approximation:\n#    return function(x)\n#        h = 0.00001\n#        f1 = fn(x + h)\n#        f0 = fn(x)\n#        return (f1 - f0)/h\n#    end\nend\n", "meta": {"hexsha": "28b478c28b8e638c51c92c38a80308d198bd05d1", "size": 598, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Module 1/Chapter03/Old/quadratic/derivative.jl", "max_stars_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_stars_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2017-02-12T15:36:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T03:30:39.000Z", "max_issues_repo_path": "Module 1/Chapter03/Old/quadratic/derivative.jl", "max_issues_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_issues_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Module 1/Chapter03/Old/quadratic/derivative.jl", "max_forks_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_forks_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-02-10T16:19:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T11:46:44.000Z", "avg_line_length": 23.92, "max_line_length": 64, "alphanum_fraction": 0.4782608696, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7776474024519463}}
{"text": "\"\"\"\n*ProspectTheory*\n\n`ProspectTheory` constructs a model object for cummulative prospect theory. \nBy default, parameters for utility curvature and probability weigting are equal gains and losses.\n\n- `α`: utility curvature for gains\n- `β`: utility curvature for losses\n- `γg`: probability weighting parameter for gains \n- `γl`: probability weighting parameter for losses\n- `λ`: loss aversion parameter\n\nConstructor\n````julia\nProspectTheory(;α=.80, β=α, γg=.70, γl=γg, λ=2.25)\n````\n*References*\n\nFennema, H., & Wakker, P. (1997). Original and cumulative prospect theory: A discussion of empirical differences. Journal of Behavioral Decision Making, 10(1), 53-64.\n\nTversky, A., & Kahneman, D. (1992). Advances in prospect theory: Cumulative representation of uncertainty. Journal of Risk and uncertainty, 5(4), 297-323.\n\"\"\"\nmutable struct ProspectTheory{T1,T2,T3,T4,T5} <:UtilityModel\n    α::T1\n    β::T2\n    γg::T3\n    γl::T4\n    λ::T5\nend\n\nfunction ProspectTheory(;α=.80, β=α, γg=.70, γl=γg, λ=2.25)\n    return ProspectTheory(α, β, γg, γl, λ)\nend\n\n\"\"\"\n*compute_utility*\n\n`compute_utility` computes utility of gamble outcomes according to prospect theory\n\n- `model`: a model object for prospect theory\n- `gamble`: a gamble object\n\nFunction Signature\n````julia\ncompute_utility(model::ProspectTheory, gamble::Gamble)\n````\n\"\"\"\nfunction compute_utility(model::ProspectTheory, gamble)\n    @unpack α,β,λ = model\n    vl,vg = split_values(gamble)\n    utilg = vg.^α\n    utill = @. -λ*abs(vl)^β \n    return [utill; utilg]\nend\n\n\"\"\"\n*compute_weights*\n\n`compute_weights` computes decision weights based on cummulative outcomes\n\n- `model`: a model object for prospect theory\n- `gamble`: a gamble object\n\nFunction Signature\n````julia\ncompute_weights(model::ProspectTheory, gamble::Gamble)\n````\n\"\"\"\nfunction compute_weights(model::ProspectTheory, gamble::Gamble)\n    pl,pg = split_probs(gamble)\n    @unpack γg,γl = model\n    ω = [_compute_weights(pl, γl); _compute_weights(pg, γg)]\n    return ω\nend\n\n\"\"\"\n*_compute_weights*\n\n`_compute_weights` computes decision weights based on cummulative outcomes\n\n- `p`: a probability vector\n- `γ`: parameter that controls weighting of low and high probabilities\n\nFunction Signature\n````julia\n_compute_weights(p, γ)\n````\n\"\"\"\nfunction _compute_weights(p, γ)\n    n = length(p)\n    f(i) = weight(sum(p[i:n]), γ) - weight(sum(p[(i+1):n]), γ)\n    ω = [f(i) for i in 1:n-1]\n    isempty(p) ? nothing : push!(ω, weight(p[n], γ))\n    return ω\nend\n\nweight(p, γ) = (p^γ)/(p^γ + (1-p)^γ)^(1/γ)\n\nfunction sort!(model::ProspectTheory, gamble)\n    @unpack p,v = gamble\n    i = sortperm(v)\n    p .= p[i]; v .= v[i]\n    gains = v .>= 0\n    pl = @view p[.!gains]\n    vl = @view v[.!gains]\n    reverse!(vl); reverse!(pl)\n    return nothing\nend\n\nfunction split_values(gamble)\n    @unpack v = gamble\n    gains = v .>= 0\n    vg = @view v[gains] \n    vl = @view v[.!gains]\n    return vl,vg\nend\n\nfunction split_probs(gamble)\n    @unpack v,p = gamble\n    gains = v .>= 0\n    pg = @view p[gains] \n    pl = @view p[.!gains]\n    return pl,pg\nend", "meta": {"hexsha": "45dadcf3ac7f023a24149ec7898f05c93f780e80", "size": 3036, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ProspectTheory.jl", "max_stars_repo_name": "itsdfish/UtilityModels.jl", "max_stars_repo_head_hexsha": "3207aa7b1499cc0d471f5b7260e3ea7a26b3334f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-02-11T13:02:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T13:31:56.000Z", "max_issues_repo_path": "src/ProspectTheory.jl", "max_issues_repo_name": "itsdfish/UtilityModels.jl", "max_issues_repo_head_hexsha": "3207aa7b1499cc0d471f5b7260e3ea7a26b3334f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-02-07T12:27:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T13:40:42.000Z", "max_forks_repo_path": "src/ProspectTheory.jl", "max_forks_repo_name": "itsdfish/UtilityModels.jl", "max_forks_repo_head_hexsha": "3207aa7b1499cc0d471f5b7260e3ea7a26b3334f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-11T16:21:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-11T16:21:06.000Z", "avg_line_length": 24.4838709677, "max_line_length": 166, "alphanum_fraction": 0.6742424242, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7776474022413287}}
{"text": "module TestUtils\n\nexport random_complex_matrix, random_real_matrix, random_hermitian_matrix\nexport random_complex_sparse_matrix, random_real_sparse_matrix\nexport random_hermitian_sparse_matrix, random_state_vector\n\n\nusing Random\nusing Distributions\nusing LinearAlgebra\nusing SparseArrays\n\n\n\"\"\"Construct a random complex matrix of size N×N with spectral radius ρ.\n\n```julia\nrandom_complex_matrix(N, ρ)\n```\n\"\"\"\nfunction random_complex_matrix(N, ρ)\n    σ = 1/√N\n    d = Normal(0.0, σ)\n    H = ρ * (rand(d, (N, N)) + rand(d, (N, N)) * 1im) / √2\nend\n\n\n\"\"\"Construct a random real-valued matrix of size N×N with spectral radius ρ.\n\n```julia\nrandom_real_matrix(N, ρ)\n```\n\"\"\"\nfunction random_real_matrix(N, ρ)\n    σ = 1/√N\n    d = Normal(0.0, σ)\n    H = ρ * rand(d, (N, N))\nend\n\n\n\"\"\"Construct a random Hermitian matrix of size N×N with spectral radius ρ.\n\n```julia\nrandom_hermitian_matrix(N, ρ)\n```\n\"\"\"\nfunction random_hermitian_matrix(N, ρ)\n    σ = 1/√N\n    d = Normal(0.0, σ)\n    X = rand(d, (N, N))\n    H = ρ * (X + X') / (2*√2)\nend\n\n\n\"\"\"Construct a random sparse complex matrix.\n\n```julia\nrandom_complex_sparse_matrix(N, ρ, sparsity)\n```\n\nreturns a matrix of size N×N with spectral radius ρ and the given sparsity\n(number between zero and one that is the approximate fraction of non-zero\nelements).\n\"\"\"\nfunction random_complex_sparse_matrix(N, ρ, sparsity)\n    σ = 1/√(sparsity * N)\n    d = Normal(0.0, σ)\n    Hre = sprand(N, N, sparsity, (dims...) -> rand(d, dims...))\n    Him = sprand(N, N, sparsity, (dims...) -> rand(d, dims...))\n    H = ρ * (Hre + Him * 1im) / √2\nend\n\n\n\"\"\"Construct a random sparse real-valued matrix.\n\n```julia\nrandom_real_sparse_matrix(N, ρ, sparsity)\n```\n\nreturns a matrix of size N×N with spectral radius ρ and the given sparsity\n(number between zero and one that is the approximate fraction of non-zero\nelements).\n\"\"\"\nfunction random_real_sparse_matrix(N, ρ, sparsity)\n    σ = 1/√(sparsity * N)\n    d = Normal(0.0, σ)\n    H = ρ * sprand(N, N, sparsity, (dims...) -> rand(d, dims...))\nend\n\n\n\"\"\"Construct a random sparse Hermitian matrix.\n\n```julia\nrandom_hermitian_sparse_matrix(N, ρ, sparsity)\n```\n\nreturns a matrix of size N×N with spectral radius ρ and the given sparsity\n(number between zero and one that is the approximate fraction of non-zero\nelements).\n\"\"\"\nfunction random_hermitian_sparse_matrix(N, ρ, sparsity)\n    σ = 1/√(sparsity * N)\n    d = Normal(0.0, σ)\n    H = sprand(N, N, sparsity, (dims...) -> rand(d, dims...))\n    return 0.5ρ * (H + H') / √2\nend\n\n\n\"\"\"Return a random, normalized Hilbert space state vector of dimension `N`.\n\n```julia\nrandom_state_vector(N)\n```\n\"\"\"\nfunction random_state_vector(N)\n    Ψ = rand(N) .* exp.((2π * im) .* rand(N))\n    Ψ ./= norm(Ψ)\n    return Ψ\nend\n\nend\n", "meta": {"hexsha": "578f686e6dfd6ebf4d8c45b34b88e92c8a062c01", "size": 2725, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/testutils.jl", "max_stars_repo_name": "QuantumControl-jl/QuantumControlBase.jl", "max_stars_repo_head_hexsha": "c0cac7b7a81a32a7fab5a85a39d142c8cfd6f779", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-11T13:06:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-13T09:04:47.000Z", "max_issues_repo_path": "src/testutils.jl", "max_issues_repo_name": "QuantumControl-jl/QuantumControlBase.jl", "max_issues_repo_head_hexsha": "c0cac7b7a81a32a7fab5a85a39d142c8cfd6f779", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-13T02:43:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-13T02:43:33.000Z", "max_forks_repo_path": "src/testutils.jl", "max_forks_repo_name": "QuantumControl-jl/QuantumControlBase.jl", "max_forks_repo_head_hexsha": "c0cac7b7a81a32a7fab5a85a39d142c8cfd6f779", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.520661157, "max_line_length": 76, "alphanum_fraction": 0.6708256881, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164657, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7776474015661392}}
{"text": "\"\"\"\nQuite crude way of checking that a number is a probability\n\nThe two steps are\n\n1. The number should be of the `Float64` type\n2. The number should belong to [0.0,1.0]\n\"\"\"\nfunction _value_is_a_probability(p::T) where {T<:AbstractFloat}\n\t(0.0 <= p <= 1.0) || throw(ArgumentError(\"The value p=$(p) is not a probability\"))\n\treturn nothing\nend\n\n\n\"\"\"\nExpected value of a single Bernoulli event\n\nSimply f(p): p\n\"\"\"\nfunction _single_bernoulli_expectation(p::Float64)\n    _value_is_a_probability(p)\n\treturn p\nend\n\n\"\"\"\nVariance of a single Bernoulli event\n\nf(p): p(1-p)\n\"\"\"\nfunction _single_bernoulli_variance(p::Float64)\n    _value_is_a_probability(p)\n\treturn p*(1.0-p)\nend\n\n\"\"\"\nVariance of a series of additive Bernoulli events\n\nf(p): ∑(p(1-p))\n\"\"\"\nfunction _additive_bernoulli_variance(p::Array{Float64})\n\treturn sum(_single_bernoulli_variance.(p))\nend\n\n\"\"\"\nVariance of a series of multiplicative Bernoulli events\n\"\"\"\nfunction _multiplicative_bernoulli_variance(p::Array{Float64})\n\tv = _single_bernoulli_variance.(p)\n\te = _single_bernoulli_expectation.(p)\n\treturn prod(v.+e.^2.0)-prod(e.^2.0)\nend\n", "meta": {"hexsha": "1f545d9823a80dbeff23ed6537d44ba41767974b", "size": 1093, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/misc/probabilities.jl", "max_stars_repo_name": "Inazuma110/EcologicalNetworks.jl", "max_stars_repo_head_hexsha": "a0b01e0a17269d56cd61d5b7b9ecc63b84f49d2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-09-01T16:31:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T13:20:23.000Z", "max_issues_repo_path": "src/misc/probabilities.jl", "max_issues_repo_name": "Inazuma110/EcologicalNetworks.jl", "max_issues_repo_head_hexsha": "a0b01e0a17269d56cd61d5b7b9ecc63b84f49d2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2020-10-13T00:24:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T02:03:30.000Z", "max_forks_repo_path": "src/misc/probabilities.jl", "max_forks_repo_name": "Inazuma110/EcologicalNetworks.jl", "max_forks_repo_head_hexsha": "a0b01e0a17269d56cd61d5b7b9ecc63b84f49d2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-08-15T22:14:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T01:29:39.000Z", "avg_line_length": 21.0192307692, "max_line_length": 83, "alphanum_fraction": 0.7337602928, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661944, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.7776474008073098}}
{"text": "#!/usr/bin/env julia\n\nusing ArgParse\nusing Distributed\n\nfunction compute_pi(a::Float64, b::Float64, n::Int64)::Float64\n    result::Float64 = 0.0\n    delta = (b - a)/n\n    x::Float64 = a\n    i::Int64 = 1\n    while x < 1.0 && i <= n\n        result += sqrt(1.0 - x^2)\n        x += delta\n        i += 1\n    end\n    result *= 2.0*delta\n    println(\"($a, $b) -> $result, $n\")\n    return result\nend\n\nfunction main()\n    arg_parser = ArgParseSettings()\n    arg_parser.description = \"Compute pi using a quadrature on multiple processes\"\n    @add_arg_table arg_parser begin\n        \"--nr_points\", \"-p\"\n            arg_type = Int64\n            help = \"number of points for the quadrature method\"\n            required = true\n        \"--nr_workers\", \"-w\"\n            arg_type = Int\n            help = \"number of workers to use\"\n            default = 0\n    end\n    options = parse_args(ARGS, arg_parser)\n    nr_points = options[\"nr_points\"]\n    nr_workers = options[\"nr_workers\"]\n    println(\"running with $nr_workers workers\")\n    if nr_workers == 0\n        @time result = compute_pi(-1.0, 1.0, nr_points)\n        println(result)\n    else\n        addprocs(nr_workers)\n        @everywhere function compute_pi(a::Float64, b::Float64, n::Int64)::Float64\n            result::Float64 = 0.0\n            delta = (b - a)/n\n            x::Float64 = a\n            i::Int64 = 1\n            while x < 1.0 && i <= n\n                result += sqrt(1.0 - x^2)\n                x += delta\n                i += 1\n            end\n            result *= 2.0*delta\n            println(\"($a, $b) -> $result, $n\")\n            return result\n        end\n\n        delta = 2.0/nr_workers\n        result = @distributed (+) for i in 1:nr_workers\n            @time compute_pi(-1.0 + (i - 1)*delta, -1.0 + i*delta, div(nr_points, nr_workers))\n        end\n        println(result)            \n    end\nend\n\nmain()\n", "meta": {"hexsha": "0b830e8861acf929484af46b3ba09037a6a506e5", "size": 1866, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "source-code/parallel/pi_distributed.jl", "max_stars_repo_name": "gjbex/Julia_good_bad_ugly", "max_stars_repo_head_hexsha": "0d5d25bb6cc80aa36eae6758d2c86d3106e9bcee", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-12T14:32:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T08:04:35.000Z", "max_issues_repo_path": "source-code/parallel/pi_distributed.jl", "max_issues_repo_name": "gjbex/Julia_good_bad_ugly", "max_issues_repo_head_hexsha": "0d5d25bb6cc80aa36eae6758d2c86d3106e9bcee", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source-code/parallel/pi_distributed.jl", "max_forks_repo_name": "gjbex/Julia_good_bad_ugly", "max_forks_repo_head_hexsha": "0d5d25bb6cc80aa36eae6758d2c86d3106e9bcee", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-18T08:03:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T08:03:54.000Z", "avg_line_length": 27.8507462687, "max_line_length": 94, "alphanum_fraction": 0.5225080386, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009573133051, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.777639449251805}}
{"text": "\"\"\"\r\n    fihess(A, E; fast = true, finite_infinite = false, atol1 = 0, atol2 = 0, rtol, withQ = true, withZ = true) -> (At, Et, Q, Z, ν, blkdims)\r\n\r\nReduce the regular matrix pencil `A - λE` to an equivalent form `At - λEt = Q'*(A - λE)*Z` using \r\northogonal or unitary transformation matrices `Q` and `Z` such that the transformed matrices `At` and `Et` are in one of the\r\nfollowing block upper-triangular forms:\r\n\r\n(1) if `finite_infinite = false`, then\r\n \r\n                   | Ai-λEi |   *     |\r\n        At - λEt = |--------|---------|, \r\n                   |    O   | Af-λEf  |\r\n \r\nwhere the `ni x ni` subpencil `Ai-λEi` contains the infinite elementary divisors and \r\nthe `nf x nf` subpencil `Af-λEf` contains the finite eigenvalues of the pencil `A-λE`.\r\n\r\nThe subpencil `Ai-λEi` is in a staircase form, with `Ai` nonsingular and upper triangular and `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vector `ν` contains the dimensions of the diagonal blocks\r\nof the staircase form  `Ai-λEi` such that `i`-th block has dimensions `ν[i] x ν[i]`. \r\nThe difference `ν[i]-ν[i+1]` for `i = 1, 2, ..., nb` is the number of infinite elementary divisors of degree `i` \r\n(with `ν[nb+1] = 0`).\r\n\r\nThe subpencil `Af-λEf` is with `Af` in an upper Hessenberg form and `Ef` nonsingular and upper triangular. \r\n\r\nThe dimensions of the diagonal blocks are returned in `blkdims = (ni, nf)`.   \r\n\r\n(2) if `finite_infinite = true`, then\r\n \r\n                   | Af-λEf |   *    |\r\n        At - λEt = |--------|--------|, \r\n                   |   O    | Ai-λEi |\r\n \r\nwhere the `nf x nf` subpencil `Af-λEf`, with `Ef` nonsingular and upper triangular, \r\ncontains the finite eigenvalues of the pencil `A-λE` and the `ni x ni` subpencil `Ai-λEi` \r\ncontains the infinite elementary divisors.\r\n\r\nThe subpencil `Af-λEf` is with `Af` in an upper Hessenberg form and `Ef` nonsingular and upper triangular.  \r\n\r\nThe subpencil `Ai-λEi` is in a staircase form, with `Ai` nonsingular and upper triangular  and `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vectors `ν` contains the dimensions of the diagonal blocks\r\nof the staircase form `Ai-λEi` such that `i`-th block has dimensions `ν[i] x ν[i]`. \r\nThe difference `ν[nb-j+1]-ν[nb-j]` for `j = 1, 2, ..., nb` is the number of infinite elementary \r\ndivisors of degree `j` (with `ν[0] = 0`).\r\n\r\nThe dimensions of the diagonal blocks are returned in `blkdims = (nf, ni)`.   \r\n\r\nThe keyword arguments `atol1`, `atol2`, and `rtol`, specify, respectively, the absolute tolerance for the \r\nnonzero elements of `A`, the absolute tolerance for the nonzero elements of `E`,  and the relative tolerance \r\nfor the nonzero elements of `A` and `E`. \r\n\r\nThe reduction is performed using rank decisions based on rank revealing QR-decompositions with column pivoting \r\nif `fast = true` or the more reliable SVD-decompositions if `fast = false`.\r\n\r\nThe performed left orthogonal or unitary transformations are accumulated in the matrix `Q` if `withQ = true`. \r\nOtherwise, `Q` is set to `nothing`.   \r\nThe performed right orthogonal or unitary transformations are accumulated in the matrix `Z` if `withZ = true`. \r\nOtherwise, `Z` is set to `nothing`.  \r\n\"\"\"\r\nfunction fihess(A::AbstractMatrix, E::AbstractMatrix; \r\n                   fast::Bool = true, finite_infinite::Bool = false, \r\n                   atol1::Real = zero(real(eltype(A))), atol2::Real = zero(real(eltype(E))), \r\n                   rtol::Real = (size(A,1)*eps(real(float(one(eltype(A))))))*iszero(min(atol1,atol2)), \r\n                   withQ::Bool = true, withZ::Bool = true)\r\n\r\n    n = LinearAlgebra.checksquare(A)\r\n    n == LinearAlgebra.checksquare(E) || throw(DimensionMismatch(\"A and E must have the same dimensions\"))          \r\n    T = promote_type(eltype(A), eltype(E))\r\n    T <: BlasFloat || (T = promote_type(Float64,T))\r\n\r\n    A1 = copy_oftype(A,T)   \r\n    E1 = copy_oftype(E,T)\r\n\r\n    withQ ? (Q = Matrix{T}(I,n,n)) : (Q = nothing)\r\n    withZ ? (Z = Matrix{T}(I,n,n)) : (Z = nothing)\r\n\r\n    ν, blkdims = fisplit!(A1, E1, Q, Z, missing, missing; \r\n                         fast  = fast, finite_infinite = finite_infinite, \r\n                         atol1 = atol1, atol2 = atol2, rtol = rtol, withQ = withQ, withZ = withZ)\r\n    (ilo, ihi) = finite_infinite ? (1, blkdims[1]) : (blkdims[1]+1, n)\r\n    ilo > ihi || gghrd!(withQ ? 'V' : 'N', withZ ? 'V' : 'N', ilo, ihi, A1, E1, Q, Z)\r\n   \r\n    return A1, E1, Q, Z, ν, blkdims                                             \r\nend\r\n\"\"\"\r\n    fischur(A, E; fast = true, finite_infinite = false, atol1 = 0, atol2 = 0, rtol, withQ = true, withZ = true) -> (At, Et, Q, Z, ν, blkdims)\r\n\r\nReduce the regular matrix pencil `A - λE` to an equivalent form `At - λEt = Q'*(A - λE)*Z` using \r\northogonal or unitary transformation matrices `Q` and `Z` such that the transformed matrices `At` and `Et` are in one of the\r\nfollowing block upper-triangular forms:\r\n\r\n(1) if `finite_infinite = false`, then\r\n \r\n                   | Ai-λEi |   *     |\r\n        At - λEt = |--------|---------|, \r\n                   |    O   | Af-λEf  |\r\n \r\nwhere the `ni x ni` subpencil `Ai-λEi` contains the infinite elementary divisors and \r\nthe `nf x nf` subpencil `Af-λEf` contains the finite eigenvalues of the pencil `A-λE`.\r\n\r\nThe subpencil `Ai-λEi` is in a staircase form, with `Ai` nonsingular and upper triangular and `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vector `ν` contains the dimensions of the diagonal blocks\r\nof the staircase form  `Ai-λEi` such that `i`-th block has dimensions `ν[i] x ν[i]`. \r\nThe difference `ν[i]-ν[i+1]` for `i = 1, 2, ..., nb` is the number of infinite elementary divisors of degree `i` \r\n(with `ν[nb+1] = 0`).\r\n\r\nThe subpencil `Af-λEf` is with the pair `(Af,Ef)` in a generalized Schur form, with `Af` (quasi) upper triangular and \r\n`Ef` nonsingular and upper triangular.  \r\n\r\nThe dimensions of the diagonal blocks are returned in `blkdims = (ni, nf)`.   \r\n\r\n(2) if `finite_infinite = true`, then\r\n \r\n                   | Af-λEf |   *    |\r\n        At - λEt = |--------|--------|, \r\n                   |   O    | Ai-λEi |\r\n \r\nwhere the `nf x nf` subpencil `Af-λEf`, with `Ef` nonsingular and upper triangular, \r\ncontains the finite eigenvalues of the pencil `A-λE` and the `ni x ni` subpencil `Ai-λEi` \r\ncontains the infinite elementary divisors.\r\n\r\nThe subpencil `Af-λEf` is with the pair `(Af,Ef)` in a generalized Schur form, with `Af` (quasi) upper triangular and \r\n`Ef` nonsingular and upper triangular.  \r\n\r\nThe subpencil `Ai-λEi` is in a staircase form, with `Ai` nonsingular and upper triangular \r\nand `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vectors `ν` contains the dimensions of the diagonal blocks\r\nof the staircase form `Ai-λEi` such that `i`-th block has dimensions `ν[i] x ν[i]`. \r\nThe difference `ν[nb-j+1]-ν[nb-j]` for `j = 1, 2, ..., nb` is the number of infinite elementary \r\ndivisors of degree `j` (with `ν[0] = 0`).\r\n\r\nThe dimensions of the diagonal blocks are returned in `blkdims = (nf, ni)`.   \r\n\r\nThe keyword arguments `atol1`, `atol2`, and `rtol`, specify, respectively, the absolute tolerance for the \r\nnonzero elements of `A`, the absolute tolerance for the nonzero elements of `E`,  and the relative tolerance \r\nfor the nonzero elements of `A` and `E`. \r\n\r\nThe reduction is performed using rank decisions based on rank revealing QR-decompositions with column pivoting \r\nif `fast = true` or the more reliable SVD-decompositions if `fast = false`.\r\n\r\nThe performed left orthogonal or unitary transformations are accumulated in the matrix `Q` if `withQ = true`. \r\nOtherwise, `Q` is set to `nothing`.   \r\nThe performed right orthogonal or unitary transformations are accumulated in the matrix `Z` if `withZ = true`. \r\nOtherwise, `Z` is set to `nothing`.  \r\n\"\"\"\r\nfunction fischur(A::AbstractMatrix, E::AbstractMatrix; \r\n                      fast::Bool = true, finite_infinite::Bool = false, \r\n                      atol1::Real = zero(real(eltype(A))), atol2::Real = zero(real(eltype(E))), \r\n                      rtol::Real = (size(A,1)*eps(real(float(one(eltype(A))))))*iszero(min(atol1,atol2)), \r\n                      withQ::Bool = true, withZ::Bool = true)\r\n\r\n    n = LinearAlgebra.checksquare(A)\r\n    n == LinearAlgebra.checksquare(E) || throw(DimensionMismatch(\"A and E must have the same dimensions\"))          \r\n    T = promote_type(eltype(A), eltype(E))\r\n    T <: BlasFloat || (T = promote_type(Float64,T))\r\n\r\n    A1 = copy_oftype(A,T)   \r\n    E1 = copy_oftype(E,T)\r\n\r\n    withQ ? (Q = Matrix{T}(I,n,n)) : (Q = nothing)\r\n    withZ ? (Z = Matrix{T}(I,n,n)) : (Z = nothing)\r\n\r\n    ν, blkdims = fisplit!(A1, E1, Q, Z, missing, missing; \r\n                         fast  = fast, finite_infinite = finite_infinite, \r\n                         atol1 = atol1, atol2 = atol2, rtol = rtol, withQ = withQ, withZ = withZ)\r\n    (ilo, ihi) = finite_infinite ? (1, blkdims[1]) : (blkdims[1]+1, n)\r\n    if ilo < ihi \r\n        compq = withQ ? 'V' : 'N'                    \r\n        compz = withZ ? 'V' : 'N'                    \r\n        gghrd!(compq, compz, ilo, ihi, A1, E1, Q, Z)\r\n        hgeqz!(compq, compz, ilo, ihi, A1, E1, Q, Z)\r\n    end\r\n   \r\n    return A1, E1, Q, Z, ν, blkdims                                             \r\nend\r\n\"\"\"\r\n    fischursep(A, E; smarg, disc = false, fast = true, finite_infinite = false, stable_unstable = false, atol1 = 0, atol2 = 0, rtol, withQ = true, withZ = true) -> (At, Et, Q, Z, ν, blkdims)\r\n\r\nReduce the regular matrix pencil `A - λE` to an equivalent block upper triangular form `At - λEt = Q'*(A - λE)*Z` \r\nusing orthogonal or unitary transformation matrices `Q` and `Z` such that the transformed matrices `At` and `Et` \r\nhave separated infinite, stable and unstable eigenvalues with respect to a stability domain `Cs` defined by the stability margin parameter `smarg` and \r\nthe stability type parameter `disc`. If `disc = false`, `Cs` is the set of complex numbers with real parts less than `smarg`, \r\nwhile if `disc = true`, `Cs` is the set of complex numbers with moduli less than `smarg` (i.e., the interior of a disc \r\nof radius `smarg` centered in the origin). If `smarg = missing`, the default value used is `smarg = 0`, if  `disc = false`,\r\nand `smarg = 1`, if `disc = true`.\r\n\r\nThe pencil `At - λEt` results in one of the following block upper-triangular forms:\r\n\r\n(1) if `finite_infinite = false`, then\r\n \r\n                   | Ai-λEi   *      *    |\r\n        At - λEt = |    O   A1-λE1   *    |\r\n                   |    0     0    A2-λE2 |\r\n \r\nwhere the `ni x ni` subpencil `Ai-λEi` contains the infinite elementary divisors, \r\nthe `n1 x n1` subpencil `A1-λE1` is with the pair `(A1,E1)` in a generalized Schur form, and the \r\n`n2 x n2` subpencil `A2-λE2` is with the pair `(A2,E2)` in a generalized Schur form. \r\nThe pencil `A1-λE1` has unstable finite eigenvalues and `A2-λE2` has stable finite eigenvalues if `stable_unstable = false`,\r\nwhile `A1-λE1` has stable finite eigenvalues and `A2-λE2` has unstable finite eigenvalues if `stable_unstable = true`.\r\n\r\nThe subpencil `Ai-λEi` is in a staircase form, with `Ai` nonsingular and upper triangular and `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vector `ν` contains the dimensions of the diagonal blocks\r\nof the staircase form  `Ai-λEi` such that `i`-th block has dimensions `ν[i] x ν[i]`. \r\nThe difference `ν[i]-ν[i+1]` for `i = 1, 2, ..., nb` is the number of infinite elementary divisors of degree `i` \r\n(with `ν[nb+1] = 0`).\r\n\r\nThe dimensions of the diagonal blocks are returned in `blkdims = (ni, n1, n2)`.   \r\n\r\n(2) if `finite_infinite = true`, then\r\n \r\n                   | A1-λE1   *      *    |\r\n        At - λEt = |    O   A2-λE2   *    |\r\n                   |    0     0    Ai-λEi |\r\n \r\nwhere the `ni x ni` subpencil `Ai-λEi` contains the infinite elementary divisors, \r\nthe `n1 x n1` subpencil `A1-λE1` is with the pair `(A1,E1)` in a generalized Schur form, and the \r\n`n2 x n2` subpencil `A2-λE2` is with the pair `(A2,E2)` in a generalized Schur form. \r\nThe pencil `A1-λE1` has unstable finite eigenvalues and `A2-λE2` has stable finite eigenvalues if `stable_unstable = false`,\r\nwhile `A1-λE1` has stable finite eigenvalues and `A2-λE2` has unstable finite eigenvalues if `stable_unstable = true`.\r\n\r\nThe subpencil `Ai-λEi` is in a staircase form, with `Ai` nonsingular and upper triangular \r\nand `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vectors `ν` contains the dimensions of the diagonal blocks\r\nof the staircase form `Ai-λEi` such that `i`-th block has dimensions `ν[i] x ν[i]`. \r\nThe difference `ν[nb-j+1]-ν[nb-j]` for `j = 1, 2, ..., nb` is the number of infinite elementary \r\ndivisors of degree `j` (with `ν[0] = 0`).\r\n\r\nThe dimensions of the diagonal blocks are returned in `blkdims = (n1, n2, ni)`.   \r\n\r\nThe keyword arguments `atol1`, `atol2`, and `rtol`, specify, respectively, the absolute tolerance for the \r\nnonzero elements of `A`, the absolute tolerance for the nonzero elements of `E`,  and the relative tolerance \r\nfor the nonzero elements of `A` and `E`. \r\n\r\nThe reduction is performed using rank decisions based on rank revealing QR-decompositions with column pivoting \r\nif `fast = true` or the more reliable SVD-decompositions if `fast = false`.\r\n\r\nThe performed left orthogonal or unitary transformations are accumulated in the matrix `Q` if `withQ = true`. \r\nOtherwise, `Q` is set to `nothing`.   \r\nThe performed right orthogonal or unitary transformations are accumulated in the matrix `Z` if `withZ = true`. \r\nOtherwise, `Z` is set to `nothing`.  \r\n\"\"\"\r\nfunction fischursep(A::AbstractMatrix, E::AbstractMatrix; \r\n                    smarg::Union{Real,Missing} = missing, disc::Bool = false, \r\n                    fast::Bool = true, finite_infinite::Bool = false, stable_unstable::Bool = false, \r\n                    atol1::Real = zero(real(eltype(A))), atol2::Real = zero(real(eltype(E))), \r\n                    rtol::Real = (size(A,1)*eps(real(float(one(eltype(A))))))*iszero(min(atol1,atol2)), \r\n                    withQ::Bool = true, withZ::Bool = true)\r\n\r\n    n = LinearAlgebra.checksquare(A)\r\n    n == LinearAlgebra.checksquare(E) || throw(DimensionMismatch(\"A and E must have the same dimensions\"))    \r\n    disc && (!ismissing(smarg) && smarg < 0 && error(\"sdeg must be non-negative if disc = true\"))\r\n      \r\n    T = promote_type(eltype(A), eltype(E))\r\n    T <: BlasFloat || (T = promote_type(Float64,T))\r\n\r\n    A1 = copy_oftype(A,T)   \r\n    E1 = copy_oftype(E,T)\r\n\r\n    withQ ? (Q = Matrix{T}(I,n,n)) : (Q = nothing)\r\n    withZ ? (Z = Matrix{T}(I,n,n)) : (Z = nothing)\r\n\r\n    ν, blkdims = fisplit!(A1, E1, Q, Z, missing, missing; \r\n                         fast  = fast, finite_infinite = finite_infinite, \r\n                         atol1 = atol1, atol2 = atol2, rtol = rtol, withQ = withQ, withZ = withZ)\r\n    (ilo, ihi) = finite_infinite ? (1, blkdims[1]) : (blkdims[1]+1, n)\r\n    if ilo <= ihi \r\n        compq = withQ ? 'V' : 'N'                    \r\n        compz = withZ ? 'V' : 'N'                    \r\n        gghrd!(compq, compz, ilo, ihi, A1, E1, Q, Z)\r\n        _, _, α, β, _, _ = hgeqz!(compq, compz, ilo, ihi, A1, E1, Q, Z)\r\n        i2 = ilo:ihi\r\n        ismissing(smarg) && (smarg = disc ? one(real(T)) : zero(real(T)))\r\n        select2 = disc ? abs.(α[i2]) .< smarg*abs.(β[i2]) : real.(α[i2] ./ β[i2]) .< smarg\r\n        stable_unstable || (select2 = .!select2)\r\n\r\n        if finite_infinite\r\n           n3 = blkdims[2]\r\n           n1 = length(select2[select2 .== true])\r\n           n2 = n-n3-n1\r\n           select = [Int.(select2); zeros(Int,n3)] \r\n        else\r\n           n1 = blkdims[1]\r\n           n2 = length(select2[select2 .== true])\r\n           n3 = n-n2-n1\r\n           select = [ones(Int,n1);Int.(select2)]\r\n        end\r\n        tgsen!(withQ, withZ, select, A1, E1, Q, Z) \r\n    else\r\n        (n1,n2,n3) = finite_infinite ? (0,0,blkdims[2]) : (blkdims[1],0,0)\r\n    end\r\n \r\n    return A1, E1, Q, Z, ν, (n1,n2,n3)                                             \r\nend\r\n\"\"\"\r\n    sfischursep(A, E; smarg, disc = false, fast = true, finite_infinite = false, stable_unstable = false, atol1 = 0, atol2 = 0, rtol, withQ = true, withZ = true) -> (At, Et, Q, Z, ν, blkdims)\r\n\r\nReduce the regular matrix pencil `A - λE` to an equivalent block upper triangular form `At - λEt = Q'*(A - λE)*Z` \r\nusing orthogonal or unitary transformation matrices `Q` and `Z` such that the transformed matrices `At` and `Et` \r\nhave separated infinite, stable and unstable eigenvalues with respect to a stability domain `Cs` defined by the stability margin parameter `smarg` and \r\nthe stability type parameter `disc`. If `disc = false`, `Cs` is the set of complex numbers with real parts less than `smarg`, \r\nwhile if `disc = true`, `Cs` is the set of complex numbers with moduli less than `smarg` (i.e., the interior of a disc \r\nof radius `smarg` centered in the origin). If `smarg = missing`, the default value used is `smarg = 0`, if  `disc = false`,\r\nand `smarg = 1`, if `disc = true`.\r\n\r\nThe pencil `At - λEt` results in one of the following block upper-triangular forms:\r\n\r\n(1) if `finite_infinite = true`, then\r\n \r\n                   | Ai1   *      *       *     |\r\n        At - λEt = |  0  A1-λE1   *       *     |\r\n                   |  0    0    A2-λE2    *     |\r\n                   |  0    0      0    Ai2-λEi2 |\r\n \r\nwhere the `ni1 x ni1` matrix `Ai1` and the  `ni2 x ni2` subpencil `Ai2-λEi2` contain the infinite elementary divisors, \r\nthe `n1 x n1` subpencil `A1-λE1` is with the pair `(A1,E1)` in a generalized Schur form, and the \r\n`n2 x n2` subpencil `A2-λE2` is with the pair `(A2,E2)` in a generalized Schur form. \r\nThe pencil `A1-λE1` has unstable finite eigenvalues and `A2-λE2` has stable finite eigenvalues if `stable_unstable = false`,\r\nwhile `A1-λE1` has stable finite eigenvalues and `A2-λE2` has unstable finite eigenvalues if `stable_unstable = true`.\r\n\r\nThe subpencil `Ai2-λEi2` is in a staircase form, with `Ai2` nonsingular and upper triangular and `Ei2` nilpotent and upper triangular. \r\nThe `nb`-dimensional vector `ν` contains the dimensions of the diagonal blocks\r\nof the staircase form  `Ai2-λEi2` such that `i`-th block has dimensions `ν[i] x ν[i]`. \r\nThe difference `ν[nb-j+2]-ν[nb-j+1]` for `j = 1, 2, ..., nb+1` is the number of infinite elementary \r\ndivisors of degree `j` (with `ν[0] := 0` and `ν[nb+1] := ni1`).\r\n\r\nThe dimensions of the diagonal blocks are returned in `blkdims = (ni1, n1, n2, ni2)`.   \r\n\r\n(2) if `finite_infinite = false`, then\r\n \r\n                   | Ai1-λEi1   *      *     *  |\r\n                   |    0     A1-λE1   *     *  |\r\n        At - λEt = |    0       0    A2-λE2  *  |\r\n                   |    0       0      0    Ai2 |\r\n \r\nwhere the `ni1 x ni1` subpencil `Ai1-λEi1` and the `ni2 x ni2` upper triangular and nonsingular matrix `Ai2` contain\r\nthe infinite elementary divisors of `A-λE`, \r\nthe `n1 x n1` subpencil `A1-λE1` is with the pair `(A1,E1)` in a generalized Schur form, and the \r\n`n2 x n2` subpencil `A2-λE2` is with the pair `(A2,E2)` in a generalized Schur form. \r\nThe pencil `A1-λE1` has unstable finite eigenvalues and `A2-λE2` has stable finite eigenvalues if `stable_unstable = false`,\r\nwhile `A1-λE1` has stable finite eigenvalues and `A2-λE2` has unstable finite eigenvalues if `stable_unstable = true`.\r\n\r\nThe subpencil `Ai1-λEi1` is in a staircase form, with `Ai1` nonsingular and upper triangular \r\nand `Ei1` nilpotent and upper triangular. \r\nThe `nb`-dimensional vectors `ν` contains the dimensions of the diagonal blocks\r\nof the staircase form `Ai1-λEi1` such that `i`-th block has dimensions `ν[i] x ν[i]`. \r\nThe difference `ν[i]-ν[i+1]` for `i = 0, 1, 2, ..., nb` is the number of infinite elementary divisors of degree `i` \r\n(with `ν[nb+1] = 0` and `ν[0] = ni2`).\r\n\r\nThe dimensions of the diagonal blocks are returned in `blkdims = (ni1, n1, n2, ni2)`.   \r\n\r\nThe keyword arguments `atol1`, `atol2`, and `rtol`, specify, respectively, the absolute tolerance for the \r\nnonzero elements of `A`, the absolute tolerance for the nonzero elements of `E`,  and the relative tolerance \r\nfor the nonzero elements of `A` and `E`. \r\n\r\nThe reduction is performed using rank decisions based on rank revealing QR-decompositions with column pivoting \r\nif `fast = true` or the more reliable SVD-decompositions if `fast = false`.\r\n\r\nThe performed left orthogonal or unitary transformations are accumulated in the matrix `Q` if `withQ = true`. \r\nOtherwise, `Q` is set to `nothing`.   \r\nThe performed right orthogonal or unitary transformations are accumulated in the matrix `Z` if `withZ = true`. \r\nOtherwise, `Z` is set to `nothing`.  \r\n\"\"\"\r\nfunction sfischursep(A::AbstractMatrix, E::AbstractMatrix; \r\n                    smarg::Union{Real,Missing} = missing, disc::Bool = false, \r\n                    fast::Bool = true, finite_infinite::Bool = false, stable_unstable::Bool = false, \r\n                    atol1::Real = zero(real(eltype(A))), atol2::Real = zero(real(eltype(E))), \r\n                    rtol::Real = (size(A,1)*eps(real(float(one(eltype(A))))))*iszero(min(atol1,atol2)), \r\n                    withQ::Bool = true, withZ::Bool = true)\r\n\r\n    n = LinearAlgebra.checksquare(A)\r\n    n == LinearAlgebra.checksquare(E) || throw(DimensionMismatch(\"A and E must have the same dimensions\"))    \r\n    disc && (!ismissing(smarg) && smarg < 0 && error(\"sdeg must be non-negative if disc = true\"))\r\n      \r\n    T = promote_type(eltype(A), eltype(E))\r\n    T <: BlasFloat || (T = promote_type(Float64,T))\r\n\r\n    A1 = copy_oftype(A,T)   \r\n    E1 = copy_oftype(E,T)\r\n\r\n    withQ ? (Q = Matrix{T}(I,n,n)) : (Q = nothing)\r\n    withZ ? (Z = Matrix{T}(I,n,n)) : (Z = nothing)\r\n\r\n    ν, blkdims1 = sfisplit!(A1, E1, Q, Z, missing, missing; \r\n                         fast  = fast, finite_infinite = finite_infinite, \r\n                         atol1 = atol1, atol2 = atol2, rtol = rtol, withQ = withQ, withZ = withZ)\r\n    ni1 = blkdims1[1]\r\n    nf  = blkdims1[2]\r\n    ni2 = blkdims1[3]\r\n    (ilo, ihi) = (ni1+1, ni1+nf)\r\n    if ilo <= ihi \r\n        compq = withQ ? 'V' : 'N'                    \r\n        compz = withZ ? 'V' : 'N'                    \r\n        gghrd!(compq, compz, ilo, ihi, A1, E1, Q, Z)\r\n        _, _, α, β, _, _ = hgeqz!(compq, compz, ilo, ihi, A1, E1, Q, Z)\r\n        i2 = ilo:ihi\r\n        ismissing(smarg) && (smarg = disc ? one(real(T)) : zero(real(T)))\r\n        select2 = disc ? abs.(α[i2]) .< smarg*abs.(β[i2]) : real.(α[i2] ./ β[i2]) .< smarg\r\n        stable_unstable || (select2 = .!select2)\r\n\r\n        select = [ones(Int,ni1); Int.(select2); zeros(Int,ni2) ]\r\n        n1 = length(select2[select2 .== true])\r\n        n2 = nf-n1\r\n        blkdims = (ni1, n1, n2, ni2)\r\n        tgsen!(withQ, withZ, select, A1, E1, Q, Z) \r\n    else\r\n        blkdims = (ni1, 0, 0, ni2)\r\n    end\r\n \r\n    return A1, E1, Q, Z, ν, blkdims                                             \r\nend\r\n\"\"\"\r\n    fiblkdiag(A, E, B, C; fast = true, finite_infinite = false, trinv = false, atol1 = 0, atol2 = 0, rtol, withQ = true, withZ = true) -> (At, Et, Bt, Ct, Q, Z, ν, blkdims, sep)\r\n\r\nReduce the regular matrix pencil `A - λE` to an equivalent form `At - λEt = Q*(A - λE)*Z` using \r\nthe transformation matrices `Q` and `Z` such that the transformed matrices `At` and `Et` are in one of the\r\nfollowing block diagonal forms:\r\n\r\n(1) if `finite_infinite = false`, then\r\n \r\n                   | Ai-λEi |   0     |\r\n        At - λEt = |--------|---------|, \r\n                   |    O   | Af-λEf  |\r\n \r\nwhere the `ni x ni` subpencil `Ai-λEi` contains the infinite elementary \r\ndivisors and the `nf x nf` subpencil `Af-λEf`, with `Ef` nonsingular and upper triangular, contains the finite eigenvalues of the pencil `A-λE`.\r\n\r\nThe subpencil `Ai-λEi` is in a staircase form, with `Ai` nonsingular and upper triangular and `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vector `ν` contains the dimensions of the diagonal blocks\r\nof the staircase form  `Ai-λEi` such that `i`-th block has dimensions `ν[i] x ν[i]`. \r\nThe difference `ν[i]-ν[i+1]` for `i = 1, 2, ..., nb` is the number of infinite elementary divisors of degree `i` \r\n(with `ν[nb+1] = 0`).\r\n\r\nThe dimensions of the diagonal blocks are returned in `blkdims = (ni, nf)`.   \r\n\r\n(2) if `finite_infinite = true`, then\r\n \r\n                   | Af-λEf |   0    |\r\n        At - λEt = |--------|--------|, \r\n                   |   O    | Ai-λEi |\r\n \r\nwhere the `nf x nf` subpencil `Af-λEf`, with `Ef` nonsingular and upper triangular, \r\ncontains the finite eigenvalues of the pencil `A-λE` and the `ni x ni` subpencil `Ai-λEi` \r\ncontains the infinite elementary divisors.\r\n\r\nThe subpencil `Ai-λEi` is in a staircase form, with `Ai` nonsingular and upper triangular  and `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vectors `ν` contains the dimensions of the diagonal blocks\r\nof the staircase form `Ai-λEi` such that `i`-th block has dimensions `ν[i] x ν[i]`. \r\nThe difference `ν[nb-j+1]-ν[nb-j]` for `j = 1, 2, ..., nb` is the number of infinite elementary \r\ndivisors of degree `j` (with `ν[0] = 0`).\r\n\r\nThe dimensions of the diagonal blocks are returned in `blkdims = (nf, ni)`.   \r\n\r\nThe keyword arguments `atol1`, `atol2`, and `rtol`, specify, respectively, the absolute tolerance for the \r\nnonzero elements of `A`, the absolute tolerance for the nonzero elements of `E`,  and the relative tolerance \r\nfor the nonzero elements of `A` and `E`. \r\n\r\nThe reduction is performed using rank decisions based on rank revealing QR-decomdiagpositions with column pivoting \r\nif `fast = true` or the more reliable SVD-decompositions if `fast = false`.\r\n\r\nIf `withQ = true`, `Q` contains the left transformation matrix, if `trinv = false`, or its inverse, if `trinv = true`. \r\nIf `withQ = false`, `Q` is set to `nothing`.   \r\nIf `withZ = true`, `Z` contains the right transformation matrix, if `trinv = false`, or its inverse, if `trinv = true`. \r\nIf `withZ = false`, `Z` is set to `nothing`.   \r\n\r\n`Bt = Q*B`, unless `B = missing`, in which case `Bt = missing` is returned, and `Ct = C*Z`, \r\nunless `C = missing`, in which case `Ct = missing` is returned .              \r\n\r\nAn estimation of the separation of the spectra of `Ai-λEi` and `Af-λEf` is returned in `sep`, where  `0 < sep ≤ 1`.\r\n\"\"\"\r\nfunction fiblkdiag(A::AbstractMatrix, E::AbstractMatrix, B::Union{AbstractMatrix,Missing}, C::Union{AbstractMatrix,Missing}; \r\n                   fast::Bool = true, finite_infinite::Bool = false, trinv::Bool = false, \r\n                   atol1::Real = zero(real(eltype(A))), atol2::Real = zero(real(eltype(E))), \r\n                   rtol::Real = (size(A,1)*eps(real(float(one(eltype(A))))))*iszero(min(atol1,atol2)), \r\n                   withQ::Bool = true, withZ::Bool = true)\r\n\r\n    compq = withQ || !ismissing(B) \r\n    compz = withZ || !ismissing(C) \r\n    A1, E1, Q, Z, ν, blkdims = fischur(A, E; fast = fast, finite_infinite = finite_infinite, atol1 = atol1, atol2 = atol2,\r\n                                      rtol = rtol, withQ = compq, withZ = compz) \r\n    T = eltype(A1)\r\n    ONER = one(real(T))\r\n    ismissing(B) ? B1 = missing : B1 = Q'*copy_oftype(B,T)\r\n    ismissing(C) ? C1 = missing : C1 = copy_oftype(C,T)*Z\r\n    \r\n    minimum(blkdims) == 0 && (return A1, E1, B1, C1, withQ ? (trinv ? Q : adjis!(Q)) : nothing, \r\n                              withZ ? (trinv ? adjis!(Z) : Z) : nothing, ν, blkdims, ONER)   \r\n\r\n    trinv ? (withZ && adjis!(Z)) : (withQ && adjis!(Q))  \r\n\r\n    n1 = blkdims[1]\r\n    i1 = 1:n1\r\n    i2 = n1+1:size(A,1)\r\n    X = view(E1,i1,i2)\r\n    Y = view(A1,i1,i2)\r\n    _, _, scale = tgsyl!(view(A1,i1,i1), view(A1,i2,i2), Y, view(E1,i1,i1), view(E1,i2,i2), X) \r\n    \r\n    ONE = one(T)\r\n    ZERO = zero(T)\r\n    scale != 0 && (scale = ONE/scale)\r\n\r\n    ismissing(B) || mul!(view(B1,i1,:),X,view(B1,i2,:),scale,ONE)\r\n    ismissing(C) || mul!(view(C1,:,i2),view(C1,:,i1),Y,-scale,ONE)\r\n\r\n    if trinv\r\n       withQ && mul!(view(Q,:,i2),view(Q,:,i1),X,-scale,ONE) \r\n       withZ && mul!(view(Z,i1,:),Y,view(Z,i2,:),scale,ONE)\r\n    else\r\n       withQ && mul!(view(Q,i1,:),X,view(Q,i2,:),scale,ONE) \r\n       withZ && mul!(view(Z,:,i2),view(Z,:,i1),Y,-scale,ONE) \r\n    end  \r\n\r\n    scale == 0 ? sep = ONER : sep = ONER/max(1+norm(X)*abs(scale),1+norm(Y)*abs(scale))\r\n   \r\n    fill!(X,ZERO)\r\n    fill!(Y,ZERO)\r\n \r\n    return A1, E1, B1, C1, Q, Z, ν, blkdims, sep                                             \r\n                       \r\nend\r\n\"\"\"\r\n    gsblkdiag(A, E, B, C; smarg, disc = false, fast = true, finite_infinite = false, stable_unstable = false, trinv = false, \r\n              atol1 = 0, atol2 = 0, rtol, withQ = true, withZ = true) -> (At, Et, Bt, Ct, Q, Z, ν, blkdims, sep)\r\n\r\nReduce the regular matrix pencil `A - λE` to an equivalent block diagonal triangular form `At - λEt = Q*(A - λE)*Z` \r\nusing the transformation matrices `Q` and `Z` such that the transformed matrices `At` and `Et` \r\nhave separated infinite, stable and unstable eigenvalues with respect to a stability domain `Cs` \r\ndefined by the stability margin parameter `smarg` and the stability type parameter `disc`. \r\nIf `disc = false`, `Cs` is the set of complex numbers with real parts less than `smarg`, \r\nwhile if `disc = true`, `Cs` is the set of complex numbers with moduli less than `smarg` (i.e., the interior of a disc \r\nof radius `smarg` centered in the origin). If `smarg = missing`, the default value used is `smarg = 0`, if  `disc = false`,\r\nand `smarg = 1`, if `disc = true`.\r\n\r\nThe pencil `At - λEt` results in one of the following block upper-triangular forms:\r\n\r\n(1) if `finite_infinite = false`, then\r\n \r\n                   | Ai-λEi   *      0    |\r\n        At - λEt = |    O   A1-λE1   0    |\r\n                   |    0     0    A2-λE2 |\r\n \r\nwhere the `ni x ni` subpencil `Ai-λEi` contains the infinite elementary divisors, \r\nthe `n1 x n1` subpencil `A1-λE1` is with the pair `(A1,E1)` in a generalized Schur form, and the \r\n`n2 x n2` subpencil `A2-λE2` is with the pair `(A2,E2)` in a generalized Schur form. \r\nThe pencil `A1-λE1` has unstable finite eigenvalues and `A2-λE2` has stable finite eigenvalues if `stable_unstable = false`,\r\nwhile `A1-λE1` has stable finite eigenvalues and `A2-λE2` has unstable finite eigenvalues if `stable_unstable = true`.\r\n\r\nThe subpencil `Ai-λEi` is in a staircase form, with `Ai` nonsingular and upper triangular and `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vector `ν` contains the dimensions of the diagonal blocks\r\nof the staircase form  `Ai-λEi` such that `i`-th block has dimensions `ν[i] x ν[i]`. \r\nThe difference `ν[i]-ν[i+1]` for `i = 1, 2, ..., nb` is the number of infinite elementary divisors of degree `i` \r\n(with `ν[nb+1] = 0`).\r\n\r\nThe dimensions of the diagonal blocks are returned in `blkdims = (ni, n1, n2)`.   \r\n\r\n(2) if `finite_infinite = true`, then\r\n \r\n                   | A1-λE1   0      0    |\r\n        At - λEt = |    O   A2-λE2   *    |\r\n                   |    0     0    Ai-λEi |\r\n \r\nwhere the `ni x ni` subpencil `Ai-λEi` contains the infinite elementary divisors, \r\nthe `n1 x n1` subpencil `A1-λE1` is with the pair `(A1,E1)` in a generalized Schur form, and the \r\n`n2 x n2` subpencil `A2-λE2` is with the pair `(A2,E2)` in a generalized Schur form. \r\nThe pencil `A1-λE1` has unstable finite eigenvalues and `A2-λE2` has stable finite eigenvalues if `stable_unstable = false`,\r\nwhile `A1-λE1` has stable finite eigenvalues and `A2-λE2` has unstable finite eigenvalues if `stable_unstable = true`.\r\n\r\nThe subpencil `Ai-λEi` is in a staircase form, with `Ai` nonsingular and upper triangular \r\nand `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vectors `ν` contains the dimensions of the diagonal blocks\r\nof the staircase form `Ai-λEi` such that `i`-th block has dimensions `ν[i] x ν[i]`. \r\nThe difference `ν[nb-j+1]-ν[nb-j]` for `j = 1, 2, ..., nb` is the number of infinite elementary \r\ndivisors of degree `j` (with `ν[0] = 0`).\r\n\r\nThe dimensions of the diagonal blocks are returned in `blkdims = (n1, n2, ni)`.   \r\n\r\nThe keyword arguments `atol1`, `atol2`, and `rtol`, specify, respectively, the absolute tolerance for the \r\nnonzero elements of `A`, the absolute tolerance for the nonzero elements of `E`,  and the relative tolerance \r\nfor the nonzero elements of `A` and `E`. \r\n\r\nThe reduction is performed using rank decisions based on rank revealing QR-decompositions with column pivoting \r\nif `fast = true` or the more reliable SVD-decompositions if `fast = false`.\r\n\r\nIf `withQ = true`, `Q` contains the left transformation matrix, if `trinv = false`, or its inverse, if `trinv = true`. \r\nIf `withQ = false`, `Q` is set to `nothing`.   \r\nIf `withZ = true`, `Z` contains the left transformation matrix, if `trinv = false`, or its inverse, if `trinv = true`. \r\nIf `withZ = false`, `Z` is set to `nothing`.   \r\n\r\n`Bt = Q*B`, unless `B = missing`, in which case `Bt = missing` is returned, and `Ct = C*Z`, \r\nunless `C = missing`, in which case `Ct = missing` is returned .              \r\n\r\nAn estimation of the separation of the spectra of the two underlying diagonal blocks is returned in `sep`, \r\nwhere  `0 ≤ sep ≤ 1`. A value `sep ≈ 0` indicates that `A1-λE1` and `A2-λE2` have some almost equal eigenvalues. \r\n\"\"\"\r\nfunction gsblkdiag(A::AbstractMatrix, E::AbstractMatrix, B::Union{AbstractMatrix,Missing}, C::Union{AbstractMatrix,Missing}; \r\n                   smarg::Union{Real,Missing} = missing, disc::Bool = false, trinv::Bool = false, \r\n                   fast::Bool = true, finite_infinite::Bool = false, stable_unstable::Bool = false, \r\n                   atol1::Real = zero(real(eltype(A))), atol2::Real = zero(real(eltype(E))), \r\n                   rtol::Real = (size(A,1)*eps(real(float(one(eltype(A))))))*iszero(min(atol1,atol2)), \r\n                   withQ::Bool = true, withZ::Bool = true)\r\n\r\n    compq = withQ || !ismissing(B)  \r\n    compz = withZ || !ismissing(C) \r\n    A1, E1, Q, Z, ν, blkdims = fischursep(A, E; smarg = smarg, disc = disc, \r\n                                      fast = fast, finite_infinite = finite_infinite, stable_unstable = stable_unstable,\r\n                                      atol1 = atol1, atol2 = atol2, rtol = rtol, withQ = compq, withZ = compz) \r\n    T = eltype(A1)\r\n    ONER = one(real(T))\r\n    ismissing(B) ? B1 = missing : B1 = Q'*copy_oftype(B,T)\r\n    ismissing(C) ? C1 = missing : C1 = copy_oftype(C,T)*Z\r\n\r\n    finite_infinite ? n1 = blkdims[1] : n1 = blkdims[1] + blkdims[2]                     \r\n    (n1 == 0 || size(A1,1) == n1) && (return A1, E1, B1, C1, withQ ? (trinv ? Q : adjis!(Q)) : nothing, \r\n               withZ ? (trinv ? adjis!(Z) : Z) : nothing, ν, blkdims,ONER)   \r\n\r\n    trinv ? (withZ && adjis!(Z)) : (withQ && adjis!(Q))  \r\n\r\n    i1 = 1:n1\r\n    i2 = n1+1:size(A,1)\r\n    X = view(E1,i1,i2)\r\n    Y = view(A1,i1,i2)\r\n    _, _, scale = tgsyl!(view(A1,i1,i1), view(A1,i2,i2), Y, view(E1,i1,i1), view(E1,i2,i2), X) \r\n    \r\n    ONE = one(T)\r\n    ZERO = zero(T)\r\n    scale != 0 && (scale = ONE/scale)\r\n\r\n    ismissing(B) || mul!(view(B1,i1,:),X,view(B1,i2,:),scale,ONE)\r\n    ismissing(C) || mul!(view(C1,:,i2),view(C1,:,i1),Y,-scale,ONE)\r\n\r\n    if trinv\r\n       withQ && mul!(view(Q,:,i2),view(Q,:,i1),X,-scale,ONE) \r\n       withZ && mul!(view(Z,i1,:),Y,view(Z,i2,:),scale,ONE)\r\n    else\r\n       withQ && mul!(view(Q,i1,:),X,view(Q,i2,:),scale,ONE) \r\n       withZ && mul!(view(Z,:,i2),view(Z,:,i1),Y,-scale,ONE) \r\n    end  \r\n\r\n    scale == 0 ? sep = ONER : sep = ONER/max(1+norm(X)*abs(scale),1+norm(Y)*abs(scale))\r\n   \r\n    fill!(X,ZERO)\r\n    fill!(Y,ZERO)\r\n\r\n    return A1, E1, B1, C1, Q, Z, ν, blkdims, sep                                             \r\n        \r\nend\r\n@inline function adjis!(A::AbstractMatrix) \r\n    # in-situ adjoint of a square matrix\r\n    n = LinearAlgebra.checksquare(A)\r\n    for i = 1:n\r\n        for j = i:n\r\n            t = A[i,j]'\r\n            A[i,j] = A[j,i]'\r\n            A[j,i] = t\r\n        end\r\n    end\r\n    return A \r\nend\r\n\"\"\"\r\n    ssblkdiag(A, B, C; smarg, disc = false, stable_unstable = false, withQ = true, withZ = true) -> (At, Bt, Ct, Q, Z, blkdims, sep)\r\n\r\nReduce the regular matrix pencil `A - λI` to an equivalent block diagonal triangular form `At - λI = Q*(A - λI)*Z` \r\nusing the transformation matrices `Q` and `Z`, where `Q = inv(Z)`, such that the transformed matrix `At` have \r\nseparated stable and unstable eigenvalues with respect to a stability domain `Cs` defined by the \r\nstability margin parameter `smarg` and the stability type parameter `disc`. \r\nIf `disc = false`, `Cs` is the set of complex numbers with real parts less than `smarg`, \r\nwhile if `disc = true`, `Cs` is the set of complex numbers with moduli less than `smarg` (i.e., the interior of a disc \r\nof radius `smarg` centered in the origin). If `smarg = missing`, the default value used is `smarg = 0`, if  `disc = false`,\r\nand `smarg = 1`, if `disc = true`.\r\nThe matrix `At` results in the following block diagonal form\r\n \r\n        At = | A1  0  |\r\n             | 0   A2 |\r\n \r\nwhere the `n1 x n1` matrix `A1` and the `n2 x n2` matrix `A2` are in Schur form. \r\nThe matrix `A1` has unstable eigenvalues and `A2` has stable eigenvalues if `stable_unstable = false`,\r\nwhile `A1` has stable eigenvalues and `A2` has unstable eigenvalues if `stable_unstable = true`.\r\nThe dimensions of the diagonal blocks are returned in `blkdims = (n1, n2)`.   \r\nIf `withQ = true`, `Q` contains the left transformation matrix. If `withQ = false`, `Q` is set to `nothing`.   \r\nIf `withZ = true`, `Z` contains the right transformation matrix. If `withZ = false`, `Z` is set to `nothing`.   \r\n`Bt = Q*B`, unless `B = missing`, in which case `Bt = missing` is returned, and `Ct = C*Z`, \r\nunless `C = missing`, in which case `Ct = missing` is returned .              \r\nAn estimation of the separation of the spectra of the two underlying diagonal blocks is returned in `sep`, \r\nwhere  `0 ≤ sep ≤ 1`. A value `sep ≈ 0` indicates that `A1` and `A2` have some almost equal eigenvalues. \r\n\"\"\"\r\nfunction ssblkdiag(A::AbstractMatrix{T}, B::Union{AbstractMatrix{T},Missing}, C::Union{AbstractMatrix{T},Missing}; \r\n                   smarg::Union{Real,Missing} = missing, disc::Bool = false, stable_unstable::Bool = false, \r\n                   withQ::Bool = true, withZ::Bool = true ) where T <: BlasFloat\r\n    \r\n    n = LinearAlgebra.checksquare(A)\r\n    S = schur(A)\r\n    ONER = real(float(one(T)))\r\n    if disc\r\n       ismissing(smarg) && (smarg = ONER)\r\n       stable_unstable ? select = abs.(S.values) .< smarg : select = abs.(S.values) .> smarg \r\n    else\r\n       ismissing(smarg) && (smarg = real(float(zero(T))))\r\n       stable_unstable ? select = real(S.values) .< smarg : select = real(S.values) .> smarg \r\n    end\r\n    n1 = length(filter(y-> y == true,select)) \r\n\r\n    (n1 == 0 || n1 == n) && (return A, B, C, withQ ? copy(S.Z') : nothing, withZ ? S.Z : nothing, (n1,n-n1), ONER)   \r\n\r\n    ordschur!(S, select)\r\n\r\n    i1 = 1:n1\r\n    i2 = n1+1:size(A,1)\r\n    Y = view(S.T,i1,i2)  # Y will contain the negative of solution -Y\r\n    _, scale = LAPACK.trsyl!('N', 'N', view(S.T,i1,i1), view(S.T,i2,i2), Y, -1) \r\n \r\n    ONE = one(T)\r\n    ZERO = zero(T)\r\n    scale != 0 && (scale = ONE/scale)\r\n\r\n    ismissing(B) ? B1 = missing : (B1 = S.Z'*B; mul!(view(B1,i1,:),Y,view(B1,i2,:),scale,ONE))\r\n    ismissing(C) ? C1 = missing : (C1 = C*S.Z; mul!(view(C1,:,i2),view(C1,:,i1),Y,-scale,ONE))\r\n\r\n    withQ ? Q = copy(S.Z') : Q = nothing \r\n    withQ && mul!(view(Q,i1,:),Y,view(Q,i2,:),scale,ONE) \r\n    withZ && mul!(view(S.Z,:,i2),view(S.Z,:,i1),Y,-scale,ONE)\r\n\r\n    scale == 0 ? sep = zero(real(T)) : sep = ONER/(1+norm(Y)*abs(scale))\r\n   \r\n    fill!(Y,ZERO)\r\n    return S.T, B1, C1, Q, withZ ? S.Z : nothing, (n1, n-n1), sep                                                    \r\nend\r\n# fallback for versions prior 1.3\r\nVERSION > v\"1.3.0\" || (mul!(C::StridedMatrix{T}, A::StridedMatrix{T}, B::StridedMatrix{T}, α::T, β::T) where {T<:BlasFloat} = \r\n                           BLAS.gemm!('N', 'N', α, A, B, β, C))\r\n\r\n", "meta": {"hexsha": "6c974b023e9d41bdcb8aebd459be177439aeb76c", "size": 39900, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gsep.jl", "max_stars_repo_name": "andreasvarga/MatrixPencils.jl", "max_stars_repo_head_hexsha": "25b9505a799a812129d4df8daca1aa5227927469", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-05-22T11:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T07:42:08.000Z", "max_issues_repo_path": "src/gsep.jl", "max_issues_repo_name": "andreasvarga/MatrixPencils.jl", "max_issues_repo_head_hexsha": "25b9505a799a812129d4df8daca1aa5227927469", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-02-08T16:05:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:24:47.000Z", "max_forks_repo_path": "src/gsep.jl", "max_forks_repo_name": "andreasvarga/MatrixPencils.jl", "max_forks_repo_head_hexsha": "25b9505a799a812129d4df8daca1aa5227927469", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:51:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T12:35:52.000Z", "avg_line_length": 54.7325102881, "max_line_length": 192, "alphanum_fraction": 0.6068170426, "num_tokens": 12445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.7776394433351759}}
{"text": "\n\"\"\"\nA basis of the classical Jacobi polynomials on the interval `[-1,1]`.\nThese polynomials are orthogonal with respect to the weight function\n```\nw(x) = (1-x)^α (1+x)^β.\n```\n\"\"\"\nstruct Jacobi{T} <: OPS{T}\n    n       ::  Int\n    α       ::  T\n    β       ::  T\n\n    Jacobi{T}(n, α = 0, β = 0) where {T} = new{T}(n, α, β)\nend\n\nJacobi(n::Int; α = 0, β = 0) = Jacobi(n, α, β)\nJacobi(n::Int, α, β) = Jacobi(n, promote(α, β)...)\nJacobi(n::Int, α::T, β::T) where {T <: AbstractFloat} = Jacobi{T}(n, α, β)\nJacobi(n::Int, α::S, β::S) where {S} = Jacobi(n, float(α), float(β))\n\nsimilar(b::Jacobi, ::Type{T}, n::Int) where {T} = Jacobi{T}(n, b.α, b.β)\n\nsupport(b::Jacobi{T}) where {T} = ChebyshevInterval{T}()\n\nfirst_moment(b::Jacobi{T}) where {T} = (b.α+b.β+1≈0) ?\n    T(2).^(b.α+b.β+1)*gamma(b.α+1)*gamma(b.β+1) :\n    T(2).^(b.α+b.β+1)*gamma(b.α+1)*gamma(b.β+1)/(b.α+b.β+1)/gamma(b.α+b.β+1)\n    # 2^(b.α+b.β) / (b.α+b.β+1) * gamma(b.α+1) * gamma(b.β+1) / gamma(b.α+b.β+1)\n\njacobi_α(b::Jacobi) = b.α\njacobi_β(b::Jacobi) = b.β\n\nmeasure(b::Jacobi) = JacobiWeight(b.α, b.β)\n\niscompatible(d1::Jacobi, d2::Jacobi) = d1.α == d2.α && d1.β == d2.β\n\nisorthogonal(dict::Jacobi, measure::JacobiWeight) =\n\tdict.α == measure.α && dict.β == measure.β\n\ngauss_rule(dict::Jacobi) = GaussJacobi(length(dict), dict.α, dict.β)\n\ninterpolation_grid(dict::Jacobi) = JacobiNodes(length(dict), dict.α, dict.β)\niscompatible(dict::Jacobi, grid::JacobiNodes) =  length(dict) == length(grid) && dict.α ≈ grid.α && dict.β ≈ grid.β\nisorthogonal(dict::Jacobi, measure::GaussJacobi) = jacobi_α(dict) ≈ jacobi_α(measure) && jacobi_β(dict) ≈ jacobi_β(measure) && opsorthogonal(dict, measure)\n\nissymmetric(dict::Jacobi) = jacobi_α(dict)≈jacobi_β(dict)\n\n# See DLMF (18.9.2)\n# http://dlmf.nist.gov/18.9#i\nfunction rec_An(b::Jacobi{T}, n::Int) where {T}\n    if (n == 0) && (b.α + b.β+1 == 0)\n        one(T)/2*(b.α+b.β)+1\n    else\n        T(2*n + b.α + b.β + 1) * (2*n + b.α + b.β + 2) / T(2 * (n+1) * (n + b.α + b.β + 1))\n    end\nend\n\nfunction rec_Bn(b::Jacobi{T}, n::Int) where {T}\n    if (n == 0) && ((b.α + b.β + 1 == 0) || (b.α+b.β == 0))\n        one(T)/2*(b.α-b.β)\n    else\n        T(b.α^2 - b.β^2) * (2*n + b.α + b.β + 1) / T(2 * (n+1) * (n + b.α + b.β + 1) * (2*n + b.α + b.β))\n    end\nend\n\nrec_Cn(b::Jacobi{T}, n::Int) where {T} =\n    T(n + b.α) * (n + b.β) * (2*n + b.α + b.β + 2) / T((n+1) * (n + b.α + b.β + 1) * (2*n + b.α + b.β))\n\nfunction innerproduct_native(d1::Jacobi, i::PolynomialDegree, d2::Jacobi, j::PolynomialDegree, measure::JacobiWeight; options...)\n\tT = coefficienttype(d1)\n\tif iscompatible(d1, d2) && isorthogonal(d1, measure)\n\t\tif i == j\n\t\t\ta = d1.α\n\t\t\tb = d1.β\n\t\t\tn = convert(T, value(i))\n\t\t\t2^(a+b+1)/(2n+a+b+1) * gamma(n+a+1)*gamma(n+b+1)/factorial(n)/gamma(n+a+b+1)\n\t\telse\n\t\t\tzero(T)\n\t\tend\n\telse\n\t\tinnerproduct1(d1, i, d2, j, measure; options...)\n\tend\nend\n\n## Printing\nfunction show(io::IO, b::Jacobi{Float64})\n\tif jacobi_α(b) == 0 && jacobi_β(b) == 0\n\t\tprint(io, \"Jacobi($(length(b)))\")\n\telse\n\t\tprint(io, \"Jacobi($(length(b)); α = $(jacobi_α(b)), β = $(jacobi_β(b)))\")\n\tend\nend\n\nfunction show(io::IO, b::Jacobi{T}) where T\n\tif jacobi_α(b) == 0 && jacobi_β(b) == 0\n\t\tprint(io, \"Jacobi{$(T)}($(length(b)))\")\n\telse\n\t\tprint(io, \"Jacobi{$(T)}($(length(b)); α = $(jacobi_α(b)), β = $(jacobi_β(b)))\")\n\tend\nend\n\n# TODO: move to its own file and make more complete\n# Or better yet: implement in terms of Jacobi polynomials\nstruct UltrasphericalBasis{T} <: OPS{T}\n\tn\t\t::\tInt\n\talpha\t::\tT\nend\n\njacobi_α(b::UltrasphericalBasis) = b.α\njacobi_β(b::UltrasphericalBasis) = b.α\n\nweightfun(b::UltrasphericalBasis, x) = (1-x)^(b.α) * (1+x)^(b.α)\n", "meta": {"hexsha": "e0b56b20f34f4c9adf8f579652f777db44821f0b", "size": 3612, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bases/poly/jacobi.jl", "max_stars_repo_name": "JuliaApproximation/BasisFunctions.jl", "max_stars_repo_head_hexsha": "9f2ab9cae1394cbaede565db1036fbf0fbd1da9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-06-21T03:12:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:03:32.000Z", "max_issues_repo_path": "src/bases/poly/jacobi.jl", "max_issues_repo_name": "JuliaApproximation/BasisFunctions.jl", "max_issues_repo_head_hexsha": "9f2ab9cae1394cbaede565db1036fbf0fbd1da9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2020-01-07T17:23:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T17:50:16.000Z", "max_forks_repo_path": "src/bases/poly/jacobi.jl", "max_forks_repo_name": "daanhb/BasisFunctions.jl", "max_forks_repo_head_hexsha": "93ef8f01b828b17d896acf11713a714fc7b6cb9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-21T17:01:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-03T08:12:27.000Z", "avg_line_length": 31.6842105263, "max_line_length": 155, "alphanum_fraction": 0.5722591362, "num_tokens": 1551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7776394415966825}}
{"text": "# === PRIVATE FUNCTIONS THAT ARE NOT EXPORTED =============================================================== #\n# =========================================================================================================== #\n\n# === PUBLIC FUNCTIONS THAT ARE EXPORTED ==================================================================== #\n\"\"\"\n    z_score_transform_data_set(dataFrame::DataFrame,colNameArray::Array{String,1})::VLResult\n\"\"\"\nfunction z_score_transform_data_set(dataFrame::DataFrame,colNameArray::Array{String,1})::VLResult\n\n    # initialize -\n    (number_of_rows, number_of_cols) = size(dataFrame)\n    z_score_array = Array{Float64,2}(undef,number_of_rows,length(colNameArray))\n\n    try\n\n        # ok:  for each col, lets z-center the data -\n        for (col_index,col_name) in enumerate(colNameArray)\n            \n            # grab the data -\n            data_col = dataFrame[!,col_name]\n\n            # transform -\n            tmp = parse.(Float64,data_col)\n            \n            # compute the mean, std -\n            µ = mean(tmp)\n            σ = std(tmp)\n\n            # compute the z-score -\n            z_score_col = (tmp .- μ)./σ\n\n            # add -\n            for (row_index,value) in enumerate(z_score_col)\n                z_score_array[row_index,col_index] = value\n            end\n        end\n\n        # return -\n        return VLResult(z_score_array)\n    catch error\n        return VLResult(error)\n    end\nend\n\n\"\"\"\n    z_score_transform_array(dataArray::Array{Float64,2})::VLResult\n\"\"\"\nfunction z_score_transform_array(dataArray::Array{Float64,2})::VLResult\n\n    # initialize -\n    (number_of_rows, number_of_cols) = size(dataArray)\n    z_score_array = Array{Float64,2}(undef, number_of_rows, number_of_cols)\n\n    try\n\n        for col_index = 1:number_of_cols\n            \n            # grab the data col -\n            data_col = dataArray[:,col_index]\n\n            # zscale this col -\n            zscale_vector_result = z_score_transform_vector(data_col)\n            if (isa(zscale_vector_result.value, Exception) == true)\n                throw(zscale_vector_result.value)\n            end\n            scaled_col_data = zscale_vector_result.value\n\n            # package, and go around again ...\n            for (row_index, scaled_value) in enumerate(scaled_col_data)\n                z_score_array[row_index,col_index] = scaled_value\n            end\n        end\n\n        # return -\n        return VLResult(z_score_array)\n    catch error\n        return VLResult(error)\n    end\nend\n\n\"\"\"\n    z_score_transform_vector(dataVector::Array{Float64,1})::VLResult\n\"\"\"\nfunction z_score_transform_vector(dataVector::Array{Float64,1})::VLResult\n\n    # initalize -\n    number_of_elements = length(dataVector)\n    z_score_array = Array{Float64,1}(undef, number_of_elements)\n\n    try \n\n        # compute the mean, std -\n        µ = mean(dataVector)\n        σ = std(dataVector)\n\n        # scale -\n        for index = 1:number_of_elements\n            \n            # get the raw value -\n            raw_value = dataVector[index]\n            \n            # scale -\n            z_score_array[index] =  (raw_value - µ)/σ\n        end\n\n        # rerurn -\n        return VLResult(z_score_array)\n\n    catch error\n        return VLResult(error)\n    end\nend\n# =========================================================================================================== #", "meta": {"hexsha": "81ff59d638637e25e5e88c5278683880822a5ac6", "size": 3368, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/analysis/Pretreatment.jl", "max_stars_repo_name": "varnerlab/PregnancyCoagDataAnalysisKit", "max_stars_repo_head_hexsha": "2ccdd3c364b11987f0ed8e5ffc0639435c852ac7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/analysis/Pretreatment.jl", "max_issues_repo_name": "varnerlab/PregnancyCoagDataAnalysisKit", "max_issues_repo_head_hexsha": "2ccdd3c364b11987f0ed8e5ffc0639435c852ac7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/analysis/Pretreatment.jl", "max_forks_repo_name": "varnerlab/PregnancyCoagDataAnalysisKit", "max_forks_repo_head_hexsha": "2ccdd3c364b11987f0ed8e5ffc0639435c852ac7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8053097345, "max_line_length": 111, "alphanum_fraction": 0.5335510689, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7776394415966824}}
{"text": "using Pkg\nPkg.activate(\".\")\nPkg.instantiate()\n\nusing DifferentialEquations\nusing LinearAlgebra\nusing Plots\n\nf(u,p,t) = 0.98*u\n\nu0 = 1.0\ntspan = (0.0, 1.0)\n\nprob = ODEProblem(f, u0, tspan)\n\nsol = solve(prob)\n\nplot(sol; label=\"\")\n\nsol(0.8)\n\nfunction lorenz(u, p, t)\n    σ, ρ, β = p\n    x_t = σ*(u[2]-u[1])\n    y_t = u[1]*(ρ-u[3]) - u[2]\n    z_t = u[1]*u[2] - β*u[3]\n    return [x_t; y_t; z_t]\nend\n\nu0 = [1.0; 0.0; 0.0]\np = [10; 28; 8/3] \n\ntspan = (0.0, 100.0)\nprob = ODEProblem(lorenz, u0, tspan, p)", "meta": {"hexsha": "767ba0b8712dd06413e11aec15587e966773331b", "size": 497, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/lecture_12/script_init.jl", "max_stars_repo_name": "petrmvala/JuliaCourse", "max_stars_repo_head_hexsha": "8169ec94eb06d0c6fe098a06ea5d061b16ab6556", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/lecture_12/script_init.jl", "max_issues_repo_name": "petrmvala/JuliaCourse", "max_issues_repo_head_hexsha": "8169ec94eb06d0c6fe098a06ea5d061b16ab6556", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/lecture_12/script_init.jl", "max_forks_repo_name": "petrmvala/JuliaCourse", "max_forks_repo_head_hexsha": "8169ec94eb06d0c6fe098a06ea5d061b16ab6556", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-09T10:36:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T10:36:10.000Z", "avg_line_length": 14.6176470588, "max_line_length": 39, "alphanum_fraction": 0.5633802817, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7776394368486338}}
{"text": "\n# Write functions as pure math\ncartesian(r, θ, ϕ) = r*cos(θ)*sin(ϕ), r*sin(θ)*sin(ϕ), r*cos(ϕ)\n\nf(x) = 2x^2+5x-10\n∇f(x) = 4x+5\n∇²f(x) = 4\n\n# Set notation are defined operators\n10 ∈ [12,13,14,15] # returns false\n\n", "meta": {"hexsha": "c5b82f6f3f33df9e3c347233da8d56e6548c7883", "size": 213, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "interesting_examples.jl", "max_stars_repo_name": "JamieMair/intro-to-julia-talk", "max_stars_repo_head_hexsha": "3c9ff26541934ca9b37fc4579caa361a9328fa38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "interesting_examples.jl", "max_issues_repo_name": "JamieMair/intro-to-julia-talk", "max_issues_repo_head_hexsha": "3c9ff26541934ca9b37fc4579caa361a9328fa38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "interesting_examples.jl", "max_forks_repo_name": "JamieMair/intro-to-julia-talk", "max_forks_repo_head_hexsha": "3c9ff26541934ca9b37fc4579caa361a9328fa38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.75, "max_line_length": 63, "alphanum_fraction": 0.6056338028, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9511422186079558, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7776296053918016}}
{"text": "# Holds the possible QP-like objective structs\n\n#############################################################\n###  Structs for Quadratic and Linear Objective Functions ###\n#############################################################\n\nabstract type objectiveFunc end\nabstract type objectiveQP_abstract <: objectiveFunc end\n\nusing SparseArrays\n\n\n\n@doc raw\"\"\"\n    objectiveQP(Q, p)\n\nQuadratic (and Linear) Objective/Cost Function\n----\n\n```math\n\\frac{1}{2} x^{⊤} Q x + p^{⊤} x\n```\n\n`Q` is an nxn Symmetric Matrix (that is positive definite for convex)\n\n`p` is an nx1 vector\n\nSee also: [`objectiveQP`](@ref), [`fObjQP`](@ref), [`dfdxQP`](@ref)\n\"\"\"\nstruct objectiveQP <: objectiveQP_abstract\n    \"Positive Definite Symmetric Matrix\"\n    Q\n    p\nend\n\n@doc raw\"\"\"\n    objectiveQ(Q)\n\nQuadratic (only) Objective/Cost Function\n----\n\n```math\n\\frac{1}{2} x^{⊤} Q x\n```\n\n`Q` is an nxn Symmetric Matrix (that is positive definite for convex)\n\nSee also: [`objectiveQP`](@ref) [`fObjQP`](@ref), [`dfdxQP`](@ref)\n\"\"\"\nstruct objectiveQ <: objectiveQP_abstract\n    \"Positive Definite Symmetric Matrix\"\n    Q\nend\n\n@doc raw\"\"\"\n    objectiveP(P)\n\nLinear (only) Objective/Cost Function\n----\n\n```math\np^{⊤} x\n```\n\n`p` is an nx1 vector\n\nSee also: [`objectiveQP`](@ref), [`fObjQ`](@ref), [`dfdxQ`](@ref)\n\"\"\"\nstruct objectiveP <: objectiveQP_abstract\n    \"Positive Definite Symmetric Matrix\"\n    p\nend\n\n#############################################################\n###       Evaluate Quadratic and Linear Objectives        ###\n#############################################################\n\n\n\"\"\"\n    fObjQP(qp::objectiveQP, x)\n\nEvaluates a quadratic function at the input `x`. The input `x` should be a\n*column* vector (i.e. `x = [4; 3]`)\n\"\"\"\nfunction fObjQP(qp::objectiveQP, x)\n    return (1/2) * x' * (qp.Q) * x + (qp.p)' * x\nend\n\n\"\"\"\n    fObjQP(q::objectiveQ, x)\n\nEvaluates a quadratic (only) function at the input `x`. The input `x` should\nbe a *column* vector (i.e. `x = [4; 3]`)\n\"\"\"\nfunction fObjQP(q::objectiveQ, x)\n    return (1/2) * x' * (q.Q) * x\nend\n\n\"\"\"\n    fObjQP(p::objectiveP, x)\n\nEvaluates a linear function at the input `x`. The input `x` should be a\n*column* vector (i.e. `x = [4; 3]`)\n\"\"\"\nfunction fObjQP(p::objectiveP, x)\n    return (p.p)' * x\nend\n\n#############################################################\n###     Gradients for Quadratic and Linear Objectives     ###\n#############################################################\n\n\n@doc raw\"\"\"\n    dfdxQP(qp::objectiveQP, x)\n\nEvaluates the derivative of a quadratic function at input `x`. The input `x`\nshould be a *column* vector (i.e. `x = [4; 3]`)\n\n```math\n\\frac{d}{dx} (\\frac{1}{2} x^{⊤} Q x + p^{⊤} x) = Qx + p\n```\n\"\"\"\nfunction dfdxQP(qp::objectiveQP, x)\n    return (qp.Q) * x + qp.p\nend\n\n@doc raw\"\"\"\n    dfdxQ(q::objectiveQ, x)\n\nEvaluates the derivative of a quadratic (only) function at input `x`. The\ninput `x` should be a *column* vector (i.e. `x = [4; 3]`)\n\n```math\n\\frac{d}{dx} (\\frac{1}{2} x^{⊤} Q x) = Qx\n```\n\"\"\"\nfunction dfdxQP(q::objectiveQ, x)\n    return (q.Q) * x\nend\n\n@doc raw\"\"\"\n    dfdxQP(p::objectiveP, x = 0)\n\nEvaluates the derivative of a linear function. The `x` is unused, but is kept\nto maintain the same function header.\n\n```math\n\\frac{d}{dx} (p^{⊤} x) = p\n```\n\"\"\"\nfunction dfdxQP(p::objectiveP, x = 0)\n    return p.p\nend\n\n\n#############################################################\n###      Hessians for Quadratic and Linear Objectives     ###\n#############################################################\n\n\n@doc raw\"\"\"\n    hessQP(qp::objectiveQP)\n\nEvaluates the hessian of a quadratic function.\n\n```math\nH(\\frac{1}{2} x^{⊤} Q x + p^{⊤} x) = Q\n```\n\nNote that Q is already square, symmetric, and (generally) positive definite.\n\"\"\"\nfunction hessQP(qp::objectiveQP)\n    return qp.Q\nend\n\n@doc raw\"\"\"\n    hessQP(q::objectiveQ)\n\nEvaluates the hessian of a quadratic (only) function.\n\n```math\nH(\\frac{1}{2} x^{⊤} Q x) = Q\n```\n\nNote that Q is already square, symmetric, and (generally) positive definite.\n\"\"\"\nfunction hessQP(q::objectiveQ)\n    return q.Q\nend\n\n@doc raw\"\"\"\n    hessQP(q::objectiveQ)\n\nEvaluates the hessian of a linear (only) function. (which is zero)\n\n```math\nH(p^{⊤} x) = 0\n```\n\"\"\"\nfunction hessQP(p::objectiveP)\n    n = size(p.p, 1)\n    return spzeros(n, n)\nend\n\n#############################################################\n", "meta": {"hexsha": "55f6c796f26bd291708631466d6ba38e39d33c83", "size": 4312, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/objective/QP_Linear_objectives.jl", "max_stars_repo_name": "danineamati/TrajOptSOCPs", "max_stars_repo_head_hexsha": "3ff6f89e875d4e9d0b3ec918ceb90bb1295989af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-06T13:14:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T13:14:18.000Z", "max_issues_repo_path": "src/objective/QP_Linear_objectives.jl", "max_issues_repo_name": "danineamati/TrajectoryOptimizationWithSOCPs", "max_issues_repo_head_hexsha": "3ff6f89e875d4e9d0b3ec918ceb90bb1295989af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-08-11T05:31:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-11T05:34:53.000Z", "max_forks_repo_path": "src/objective/QP_Linear_objectives.jl", "max_forks_repo_name": "danineamati/TrajectoryOptimizationWithSOCPs", "max_forks_repo_head_hexsha": "3ff6f89e875d4e9d0b3ec918ceb90bb1295989af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8309178744, "max_line_length": 77, "alphanum_fraction": 0.5482374768, "num_tokens": 1273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7776296013147629}}
{"text": "struct PolynomialBasis\n    polynomial::AbstractVector{T} where T <: AbstractPolynomialLike\n    x::AbstractVector{T} where T <: AbstractPolynomialLike\nend\n\n\n\"\"\"\n# Notes\n`with_bias=true` provides polynomials with the degree of from 0 to `d`.\n`with_bias=false` provides polynomials with the degree of `d`.\n# Variables\nn ∈ N: length of array, i.e., x ∈ Rⁿ\nd ∈ N: degree\n\"\"\"\nfunction PolynomialBasis(n::Int, d::Int; with_bias=true)\n    @assert n >= 1 && d >= 0\n    _n = with_bias ? n+1 : n\n    exponents = multiexponents(_n, d)\n    @polyvar x[1:n]\n    _x = with_bias ? [x..., 1] : x\n    polynomial = exponents |> Map(exponent -> prod(_x.^exponent)) |> collect\n    PolynomialBasis(polynomial, x)\nend\n\nfunction (a::PolynomialBasis)(x::AbstractArray)\n    a.polynomial |> Map(poly -> poly(a.x => x)) |> collect\nend\n", "meta": {"hexsha": "e869c63f87524d3f4396a8cebd5d9b376bcd2b1a", "size": 806, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/approximators/PolynomialBasis.jl", "max_stars_repo_name": "hnlee77/ApproximateDPs.jl", "max_stars_repo_head_hexsha": "e19ce0de84c96a557d2c78c43fdf016d7f04c5ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-15T03:49:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T11:39:10.000Z", "max_issues_repo_path": "src/utils/approximators/PolynomialBasis.jl", "max_issues_repo_name": "hnlee77/ApproximateDPs.jl", "max_issues_repo_head_hexsha": "e19ce0de84c96a557d2c78c43fdf016d7f04c5ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-09-27T05:28:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T01:19:41.000Z", "max_forks_repo_path": "src/utils/approximators/PolynomialBasis.jl", "max_forks_repo_name": "hnlee77/ApproximateDPs.jl", "max_forks_repo_head_hexsha": "e19ce0de84c96a557d2c78c43fdf016d7f04c5ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7857142857, "max_line_length": 76, "alphanum_fraction": 0.6674937965, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7776275231688997}}
{"text": "\"\"\"\n    generate_image(size, porosity, distribution)\n\nGenerate an image of overlapping `n`-dimensional balls with radii\nsampled from `distribution`. The image is generated with specified\n`size` and `porosity`.\n\"\"\"\nfunction generate_image(size,\n                        porosity     :: AbstractFloat,\n                        distribution :: Distribution)\n    image     = zeros(Bool, size) |> BitArray\n    cur_pores = prod(size)\n    pores     = porosity * cur_pores\n\n    indices    = CartesianIndices(image)\n    fidx, lidx = first(indices), last(indices)\n    uidx       = oneunit(fidx)\n\n    while true\n        radius  = rand(distribution)\n        iradius = radius |> ceil |> Int\n        center  = rand(indices)\n\n        from = max(center - iradius*uidx, fidx)\n        to   = min(center + iradius*uidx, lidx)\n\n        old_pores = count(iszero, image[from:to])\n\n        for idx in from:to\n            r = sqrt(sum(x^2 for x in Tuple(idx - center)))\n            if r <= radius\n                image[idx] = 1\n            end\n        end\n\n        new_pores = count(iszero, image[from:to])\n        cur_pores += new_pores - old_pores\n\n        if cur_pores < pores\n            return image\n        end\n    end\nend\n", "meta": {"hexsha": "61c9ab902f2d656c24cec286faa63148e6247897", "size": 1203, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/generate.jl", "max_stars_repo_name": "shamazmazum/Sandcorn.jl", "max_stars_repo_head_hexsha": "4256577eb51b7b1949aba259f875dd5c25abcca9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/generate.jl", "max_issues_repo_name": "shamazmazum/Sandcorn.jl", "max_issues_repo_head_hexsha": "4256577eb51b7b1949aba259f875dd5c25abcca9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/generate.jl", "max_forks_repo_name": "shamazmazum/Sandcorn.jl", "max_forks_repo_head_hexsha": "4256577eb51b7b1949aba259f875dd5c25abcca9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3409090909, "max_line_length": 66, "alphanum_fraction": 0.5710723192, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.77762752271717}}
{"text": "\"\"\"\n```\nModel(y, H, A, Q, R, x, P)\n```\n\nThe type Model contains the measurements matrix as well as the kalman setup:\nMeasurement:  y(t)     = H * x(t) + e(t) ~ N(0, R)\nState:        x(t + 1) = A * x(t) + n(t) ~ N(0, Q)\n\nwhere both y(t) and x(t+1) are vectors of length p and m, respectively.\nThe state transition matrix, A, is (m x m) while the measurement model matrix, H, is (p x m).\n\nTime-varying H and A are not currently implemented. Similarly, the covariances\nR and Q are constant across time.\n\"\"\"\n\nmutable struct Model\n    y::Matrix{<:Real}\n    H::Matrix{<:Real}\n    A::Matrix{<:Real}\n    Q::Matrix{<:Real}\n    R::Matrix{<:Real}\n    x::Vector{<:Real}\n    P::Matrix{<:Real}\n    predicted::Predicted\n    filtered::Filtered\n    smoothed::Smoothed\n    function Model(y, H, A, Q, R, x, P)\n        str = \"y is $(size(y, 1))x$(size(y, 2)), \" *\n              \"H is $(size(H, 1))x$(size(H, 2)), \" *\n              \"A is $(size(A, 1))x$(size(A, 2)), \" *\n              \"Q is $(size(Q, 1))x$(size(Q, 2)), \" *\n              \"R is $(size(R, 1))x$(size(R, 2)), \" *\n              \"x is $(length(x)), \" *\n              \"P is $(size(P, 1))x$(size(P, 2))\"\n        !(size(H, 2) == size(A, 1) == size(A, 2) == size(Q, 1) == size(Q, 2) == length(x) == size(P, 1) == size(P, 2)) && throw(DimensionMismatch(str))\n        !(size(y, 2) == size(H, 1) == size(R, 1) == size(R, 2)) && throw(DimensionMismatch(str))\n\n        @assert all(diag(R) .> 0) \"All diagonal elements of R must be strictly positive.\"\n        @assert all(diag(Q) .> 0) \"All diagonal elements of Q must be strictly positive.\"\n        @assert all(diag(P) .> 0) \"All diagonal elements of P must be strictly positive.\"\n\n        predicted = Predicted(size(y, 1), size(y, 2), length(x))\n        filtered  = Filtered( size(y, 1), size(y, 2), length(x))\n        smoothed  = Smoothed( size(y, 1), size(y, 2), length(x))\n\n        return new(y, H, A, Q, R, x, P, predicted, filtered, smoothed)\n    end\nend\n\n# Outer constructors for univariate measurement\nModel(y::Vector{<:Real}, H::Vector{<:Real}, A::Matrix{<:Real}, Q::Matrix{<:Real}, R::Real, x::Vector{<:Real}, P::Matrix{<:Real}) = Model(repeat(y, 1, 1), reshape(H, 1, length(H)), A, Q, fill(R, 1, 1), x, P)\nModel(y::Vector{<:Real}, H::Real, A::Real, Q::Real, R::Real, x::Real, P::Real) = Model(repeat(y, 1, 1), fill(H, 1, 1), fill(A, 1, 1), fill(Q, 1, 1), fill(R, 1, 1), [x], fill(P, 1, 1))\n\n# Univariate state\nModel(y::Matrix{<:Real}, H::Matrix{<:Real}, A::Real, Q::Real, R::Matrix{<:Real}, x::Real, P::Real) = Model(y, H, fill(A, 1, 1), fill(Q, 1, 1), R, [x], fill(P, 1, 1))\n\n# Special constructors\nLocalLevel(y::Vector{<:Real}, Q::Real, R::Real, x::Real, P::Real) = Model(repeat(y, 1, 1), ones(1, 1), ones(1, 1), fill(Q, 1, 1), fill(R, 1, 1), [x], fill(P, 1, 1))\nLocalLevel(y::Matrix{<:Real}, Q::Real, R::Matrix, x::Real, P::Real) = Model(y, ones(size(y, 2), 1), ones(1, 1), fill(Q, 1, 1), R, [x], fill(P, 1, 1))\n\nLocalLevel(y::Vector{<:Real}, Q::Real, R::Real) = Model(repeat(y, 1, 1), ones(1, 1), ones(1, 1), fill(Q, 1, 1), fill(R, 1, 1), [y[1]], fill(1000.0, 1, 1))\nLocalLevel(y::Matrix{<:Real}, Q::Real, R::Matrix) = Model(repeat(y, 1, 1), ones(1, 1), ones(1, 1), fill(Q, 1, 1), R, [0.0], fill(1000.0, 1, 1))\n\n\"\"\"\n```\nOutput\n```\n\nThe type Output contains the means and covariances for the measurements\nand states, respectively, at each time step, t = 1,...,T:\nx is a (T x m) matrix of state means\nP is a (T x m x m) array of state covariances\nμ is a (T x p) matrix of measurement means\nΣ is a (T x p x p) matrix of measurement covariances\n\"\"\"\n\nabstract type Output end\n\nmutable struct Predicted <: Output\n    x::Matrix{AbstractFloat}\n    P::Array{AbstractFloat, 3}\n    μ::Matrix{AbstractFloat}\n    Σ::Array{AbstractFloat, 3}\nend\n\nmutable struct Filtered <: Output\n    x::Matrix{AbstractFloat}\n    P::Array{AbstractFloat, 3}\n    μ::Matrix{AbstractFloat}\n    Σ::Array{AbstractFloat, 3}\nend\n\nmutable struct Smoothed <: Output\n    x::Matrix{AbstractFloat}\n    P::Array{AbstractFloat, 3}\n    μ::Matrix{AbstractFloat}\n    Σ::Array{AbstractFloat, 3}\nend\n\nPredicted(T::Int, p::Int, m::Int) = Predicted(zeros(T, m), zeros(T, m, m), zeros(T, p), zeros(T, p, p))\nFiltered(T::Int, p::Int, m::Int)  = Filtered(zeros(T, m), zeros(T, m, m), zeros(T, p), zeros(T, p, p))\nSmoothed(T::Int, p::Int, m::Int)  = Smoothed(zeros(T, m), zeros(T, m, m), zeros(T, p), zeros(T, p, p))", "meta": {"hexsha": "1962fcd4da2b62737c5cf1342d37d44175c8e650", "size": 4356, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/types.jl", "max_stars_repo_name": "madskoefoed/KalmanFilter.jl", "max_stars_repo_head_hexsha": "057347af3ddc2cceb3791e9474b3b2d6bc6a61c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/types.jl", "max_issues_repo_name": "madskoefoed/KalmanFilter.jl", "max_issues_repo_head_hexsha": "057347af3ddc2cceb3791e9474b3b2d6bc6a61c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/types.jl", "max_forks_repo_name": "madskoefoed/KalmanFilter.jl", "max_forks_repo_head_hexsha": "057347af3ddc2cceb3791e9474b3b2d6bc6a61c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2912621359, "max_line_length": 206, "alphanum_fraction": 0.5785123967, "num_tokens": 1621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7776275152799299}}
{"text": "\nusing JuMP\nusing GLPK\n\nmodel = Model(GLPK.Optimizer)\n@variable(model, x >= 0)\n@variable(model, y >= 0)\n@constraint(model, 6x + 8y >= 100)\n@constraint(model, 7x + 12y >= 120)\n@objective(model, Min, 12x + 20y)\n\noptimize!(model)\n\n@show value(x);\n@show value(y);\n@show objective_value(model);\n\n\nusing JuMP\n\n\nusing GLPK\n\n\nmodel = Model(GLPK.Optimizer);\n\n\n@variable(model, x >= 0)\n@variable(model, y >= 0);\n\n\n@constraint(model, 6x + 8y >= 100)\n@constraint(model, 7x + 12y >= 120);\n\n\n@objective(model, Min, 12x + 20y);\n\n\noptimize!(model)\n\n\n@show value(x);\n@show value(y);\n@show objective_value(model);\n\n", "meta": {"hexsha": "ddd080d73fc2e78cdc20cf02f5b79bbc5076792a", "size": 597, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/introduction/getting_started_with_JuMP.jl", "max_stars_repo_name": "mtanneau/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 75, "max_stars_repo_stars_event_min_datetime": "2020-06-15T13:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T12:58:48.000Z", "max_issues_repo_path": "test/introduction/getting_started_with_JuMP.jl", "max_issues_repo_name": "mtanneau/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-05-27T05:36:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T09:52:29.000Z", "max_forks_repo_path": "test/introduction/getting_started_with_JuMP.jl", "max_forks_repo_name": "mtanneau/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-10-09T09:32:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T17:41:21.000Z", "avg_line_length": 12.9782608696, "max_line_length": 36, "alphanum_fraction": 0.6566164154, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290922181331, "lm_q2_score": 0.8006920068519378, "lm_q1q2_score": 0.7775753017604375}}
{"text": "# Using the BBP formula\n#\n# The Bailey–Borwein–Plouffe formula (BBP formula) is a formula for π\n\n\n#=\nComputing Bailey–Borwein–Plouffe formula for Pi\nto ascertain the performance of FastRational{BigInt}\nrelative to Rational{BigInt} by BPP iterations\n\nFastRational{BigInt}s perform better below n=328\nRational{BigInt}s     perform better above n=330\n\nAs BPP iterations increase, numerator and denominator grow.\nAfter some digit count in numerator aor denominator, ~10_000,\nThe extra time spent in divgcd reductions becomes less than\nthe time spent performing arithmetic on very large integers;\nso reducing the numerator and denominator begins to win.\n=#\n\nusing FastRationals\nusing BenchmarkTools\n\nconst BT=BenchmarkTools.DEFAULT_PARAMETERS;\nBT.overhead=BenchmarkTools.estimate_overhead();\nBT.evals=1; ; BT.time_tolerance = 5.0e-7; BT.samples = 100;\n\nconst big1 = BigInt(1)\nconst big2 = BigInt(2)\nconst big4 = BigInt(4)\nconst big5 = BigInt(5)\nconst big6 = BigInt(6)\nconst big8 = BigInt(8)\nconst big16 = BigInt(16)\n\nfunction bpp(::Type{T}, n) where {T}\n    result = zero(T)\n    for k = 0:n\n       eightk = big8 * k\n       cur = T(big4,eightk+1) -\n             T(big2,eightk+4) -\n             T(big1,eightk+5) -\n             T(big1,eightk+6)\n       cur = T(big1, big16^k) * cur\n       result = result + cur\n    end\n    return result\nend\n\n\nsystemqtime = @belapsed bpp(Rational{BigInt},   15);\nfastqtime = @belapsed bpp(FastRational{BigInt}, 15);\nbpp15 = round(systemqtime/fastqtime, digits=1)\n\nsystemqtime = @belapsed bpp(Rational{BigInt},   125);\nfastqtime = @belapsed bpp(FastRational{BigInt}, 125);\nbpp125 = round(systemqtime/fastqtime, digits=1)\n\nsystemqtime = @belapsed bpp(Rational{BigInt},   250);\nfastqtime = @belapsed bpp(FastRational{BigInt}, 250);\nbpp250 = round(systemqtime/fastqtime, digits=1)\n\n# relspeeds meet at n=328\n\nsystemqtime = @belapsed bpp(Rational{BigInt},   500);\nfastqtime = @belapsed bpp(FastRational{BigInt}, 500);\nbpp500 = round(systemqtime/fastqtime, digits=1)\n\nsystemqtime = @belapsed bpp(Rational{BigInt},   1000);\nfastqtime = @belapsed bpp(FastRational{BigInt}, 1000);\nbpp1000 = round(systemqtime/fastqtime, digits=1)\n\nsystemqtime = @belapsed bpp(Rational{BigInt},   2000);\nfastqtime = @belapsed bpp(FastRational{BigInt}, 2000);\nbpp2000 = round(systemqtime/fastqtime, digits=1)\n\nsystemqtime = @belapsed bpp(Rational{BigInt},   3000);\nfastqtime = @belapsed bpp(FastRational{BigInt}, 3000);\nbpp3000 = round(systemqtime/fastqtime, digits=1)\n\n\n\nrelspeeds = (bpp15=bpp15, bpp125=bpp125, bpp250=bpp250, \n             bpp500=bpp500, bpp1000=bpp1000, bpp2000=bpp2000,\n             bpp3000=bpp3000)\n\nrelspeeds = (bpp15 = 0.3, bpp125 = 0.3, bpp250 = 0.7, bpp500 = 2.4, bpp1000 = 8.1, bpp2000 = 20.9, bpp3000 = 36.0)\n\nxs = [15,125,250,500,1000,2000,3000];\nys = [relspeeds...,];\n\nusing GR\nplot(xs, ys, size=(500,500))\n", "meta": {"hexsha": "19dc1d24a2b28b0ee3641ddb42e6a17d7622b2aa", "size": 2833, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmarks/BBP_for_pi.jl", "max_stars_repo_name": "JuliaTagBot/FastRationals.jl", "max_stars_repo_head_hexsha": "0027cc1c998dc3a98f1464d6f4544bc84286f698", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-06-16T02:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T00:49:06.000Z", "max_issues_repo_path": "benchmarks/BBP_for_pi.jl", "max_issues_repo_name": "JuliaTagBot/FastRationals.jl", "max_issues_repo_head_hexsha": "0027cc1c998dc3a98f1464d6f4544bc84286f698", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2019-06-17T09:17:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-14T09:59:34.000Z", "max_forks_repo_path": "benchmarks/BBP_for_pi.jl", "max_forks_repo_name": "JuliaTagBot/FastRationals.jl", "max_forks_repo_head_hexsha": "0027cc1c998dc3a98f1464d6f4544bc84286f698", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-06-17T11:04:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-12T18:08:32.000Z", "avg_line_length": 30.1382978723, "max_line_length": 114, "alphanum_fraction": 0.7144369926, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8633916187614822, "lm_q1q2_score": 0.7775098743890267}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     text_representation:\n#       extension: .jl\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.5.0\n#   kernelspec:\n#     display_name: Julia 1.4.2\n#     language: julia\n#     name: julia-1.4\n# ---\n\n# # Gradient descent (勾配法)\n#\n# 勾配法の練習として下記の簡単な設定のもとで勾配法を逐次適用することで目的関数の極値問題を解く際の点の動きを可視化する.\n#\n# $A$ を 2x2 の実対称行列とし, $f=f(x,y)$ を次で定める二変数関数とする.\n#\n# $$\n# f(x,y) =  \\begin{bmatrix}x & y\\end{bmatrix} A \\begin{bmatrix} x \\\\ y \\end{bmatrix}\n# $$\n#\n# このとき $f$ の勾配ベクトルは $\\nabla f$ は \n#\n# $$\n# \\nabla f= \\begin{bmatrix} \\frac{\\partial f}{\\partial x} \\\\ \\frac{\\partial f}{\\partial y} \\end{bmatrix} = A \\begin{bmatrix} x \\\\ y \\end{bmatrix}\n# $$\n#\n# と書ける. 初期位置を $v_0\\in\\mathbb{R}^2$, 学習率を $\\eta$ とすれば $i$ 番目のステップで得られる点は次のようになる.\n#\n# $$\n# v_{i} = v_{i-1} - \\eta \\nabla f|_{(x,y)=v_{i-1}} \\quad (i=1,2,\\dots)\n# $$\n\nusing Colors\nusing LinearAlgebra\nusing Plots\n\n# +\nA = [\n    2.0  0.2\n    0.2  1.0\n]\n\nf(v) =  dot(v,A,v)\nf(x, y) = f([x, y])\n∇f(v) = A * v\nη = 0.05 # learning rate\n# -\n\n# ## 等高線の描画\n\nx = range(-10,stop=10,length=50)\ny = range(-10,stop=10,length=50)\np = contour(x, y, f)\n\n# ## 勾配法を試す\n\n# +\nx = range(-5, stop=5, length=50)\ny = range(-5, stop=5, length=50)\np = contour(x, y, f, levels=range(0, stop=100, step=3))\n\nv = [-5., -5.] # initial point\nfor i in 1:100\n    v .-= η .* ∇f(v)\n    scatter!(\n        p, [v[1]], [v[2]], \n        label=:none, color=:blue, msize=3,\n    )\nend\n\nplot(p)\n# -\n\n# ## ランダムに点を配置しそれを初期値とする勾配法\n\n# +\nx = range(-5, stop=5, length=50)\ny = range(-5, stop=5, length=50)\np = contour(x, y, f, levels=range(0,stop=100,step=3))\nfor _ in 1:10\n    v = rand(range(-5,stop=5,step=0.01), 2)\n    c =　RGB(rand(3)...)\n    for _ in 1:30 # num steps\n        v .-= η .* ∇f(v)\n        scatter!(\n            p, [v[1]], [v[2]], \n            label=:none, color=c, msize=3,\n        )\n    end\nend\n\nplot(p)\n", "meta": {"hexsha": "98259d8865fc713da62b70ac682f6ef038c0951f", "size": 1891, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiments/notebook/gradient_descent.jl", "max_stars_repo_name": "hsugawa8651/MyWorkflow.jl", "max_stars_repo_head_hexsha": "48edcbcc3fd9e425895ef91bea833ef1e5d4c3fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments/notebook/gradient_descent.jl", "max_issues_repo_name": "hsugawa8651/MyWorkflow.jl", "max_issues_repo_head_hexsha": "48edcbcc3fd9e425895ef91bea833ef1e5d4c3fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-06T12:34:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-06T12:39:46.000Z", "max_forks_repo_path": "experiments/notebook/gradient_descent.jl", "max_forks_repo_name": "hsugawa8651/MyWorkflow.jl", "max_forks_repo_head_hexsha": "48edcbcc3fd9e425895ef91bea833ef1e5d4c3fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2959183673, "max_line_length": 145, "alphanum_fraction": 0.5404547858, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912849, "lm_q2_score": 0.8688267643505193, "lm_q1q2_score": 0.7774170317335899}}
{"text": "\"\"\"\n    Ricker(; <keyword arguments>)\n\nCreate a Ricker wavelet.\n\n# Keyword arguments\n* `dt::Real=0.002`: sampling interval in secs.\n* `f0::Real=20.0`: central frequency in Hz.\n\n# Examples\n```julia\njulia> w = Ricker(); plot(w);\njulia> w = Ricker(dt=0.004, f0=20); plot(w);\n```\n\n# Reference\nSheriff, Robert, 2002, Encyclopedic Dictionary of Applied Geophysics, fourth\ned.: Society of Exploration Geophysicists. Geophysical Reference Series No. 13.\n\"\"\"\n\nfunction Ricker(; dt::Real=0.002, f0::Real=20.0)\n\n    nw = 2.0/(f0*dt)\n    nc = floor(Int, nw/2)\n    t = dt*collect(-nc:1:nc)\n    b = (pi*f0*t).^2\n    w = (1.-2.*b).*exp(-b)\n    \nend\n", "meta": {"hexsha": "814138f1c730e99448a9e2e7052a331ca0edf4e5", "size": 634, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Wavelets/Ricker.jl", "max_stars_repo_name": "JuliaPackageMirrors/Seismic.jl", "max_stars_repo_head_hexsha": "7fb94347c2486f8de3185edf92bbf023f9e68cc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Wavelets/Ricker.jl", "max_issues_repo_name": "JuliaPackageMirrors/Seismic.jl", "max_issues_repo_head_hexsha": "7fb94347c2486f8de3185edf92bbf023f9e68cc5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Wavelets/Ricker.jl", "max_forks_repo_name": "JuliaPackageMirrors/Seismic.jl", "max_forks_repo_head_hexsha": "7fb94347c2486f8de3185edf92bbf023f9e68cc5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-07T17:48:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-07T17:48:25.000Z", "avg_line_length": 21.1333333333, "max_line_length": 79, "alphanum_fraction": 0.6324921136, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7774067608532809}}
{"text": "# This program computes Feigenbaum's alpha constant using\n# Feigenbaum's functional equation derived via renormalization\n# group methods.\n# Oct 2017 -- Stuart Brorson, sdb@cloud9.net\n\nusing ForwardDiff\n\n# I define the helper fcns first.\n\n#-------------------------------------------------------\n# Define universal fcn g(z, a).  It is expressed as a power\n# series, coefficients a.  Only even powers are needed since\n# g(z) is even.\nfunction g(z, a::Vector)\n  #println(\"---> Entered g\\n\")\n  s = 0;\n  for i=length(a):-1:1\n    # println(\"i = $i, s = $s\\n\")\n    s = z*z*(s + a[i]);\n  end\n  #println(\"<--- Leaving g\\n\")\n  return (1+s)\nend\n\n#---------------------------------------------------------\n# Define relation obeyed by g(z).  Name it f(z, a)  \nfunction f(z, a::Vector)\n  #println(\"---> Entered f\\n\")\n  const one = big(1.0)\n  alpha = one/g(one, a);\n  r = g(z, a) - alpha*g(g(z/alpha, a), a);\n  #println(\"<--- Leaving g\\n\")\n  return r\nend\n\n\n#--------------------------------------------------------\n# Define fcn which takes gradient of f w.r.t. a.\n# Returns row vector which is gradient of f w.r.t. a,\n# evaluated at z, a.\nfunction gradf(z, a::Vector)\n  #println(\"---> Entered gradf\\n\")\n  # Specialize to position z.  Result is fcn of coeffs a only.\n  fbeta(a) = f(z, a);\n\n  # Compute gradient w.r.t. beta and return it\n  gf1 = ForwardDiff.gradient(fbeta, a)\n  #println(\"<--- Leaving gradf\\n\")\n  return gf1'\nend\n\n\n# ------------------------------------------------------------\n# The main event -- a computation of alpha using Newton's method.\nfunction compute_alpha(Numdigs, N, betain)\n\n  # First set up variables, including BigFloat settings\n  # Setting precision to 5x Numdigs seems to keep Newton's method\n  # from wandering away.  Smaller values don't.  More fidding might\n  # improve things here.\n  setprecision(5*Numdigs);\n  \n  # Set stopping tol for Newton's method so I get the number of digits\n  # I want.\n  const tol = BigFloat(10.0)^-(Numdigs);\n\n  const zi = big.(linspace(1/N, 1, N));   # Grid of sample points zi\n  fn = zeros(BigFloat, N);             # Function f vector\n  Jn = zeros(BigFloat, N, N);        # Jacobian\n \n  # Need expansion coeffs beta.  Start with the one passed in, betain.  \n  # N should always be larger than length(betain), so we are adding to the \n  # betas we computed last time.\n  betan = zeros(BigFloat, N);\n  for i = 1:length(betain)\n    betan[i] = betain[i];\n  end\n\n  # println(\"-----------------------------\\n\")\n  sttim = now();  # Keep track of loop timing.\n  # Now enter Newton loop.  \n  for cnt = 1:50\n    nowtim = now();  # Keep track of loop timing\n    println(\"Newton iteration = $cnt, time elapsed = $(nowtim-sttim)\\n\")\n\n    # Compute new f and Jacobian upon each iteration\n    for i = 1:N\n      fn[i] = f(zi[i], betan);\n      Jn[i,:] = gradf(zi[i], betan);\n    end\n\n    # Now compute step to take, then take it.\n    sn = Jn\\fn;\n    betanp1 = betan - sn;\n\n    # Check for convergence\n    if (norm(sn) < tol)\n      println(\"\\nDone!  Converged after $cnt iterations.\\n\")\n      # compute alpha\n      myalpha = 1/g(1, betanp1);\n      return myalpha, betanp1;\n    end\n\n    # Move values back\n    betan = betanp1\n\n  end\n  println(\"!!!!!!!  Didn't converge!  !!!!!!!!\\n\")\n\nend\n\n\n#--------------------------------------------------\nfunction iterate_alpha()\n  # This is a runner -- call this fcn.  This fcn calls\n  # compute_alpha asking for different number of digits \n  # at different precision/tolerance levels.\n  # It calls with the beta coefficients computed in the \n  # last iteration as the starting point to help Newton's \n  # method from wandering away.\n\n  # Seed betan with 3 values.\n  betan = zeros(BigFloat, 3);\n  betan[1] = big(-1.52763883147);\n  betan[2] = big(1.048327004372e-1);\n  betan[3] = big(2.669121419134012e-2);\n\n  # Step up number of pts to compute on.  Change this to get\n  # more digits\n  for N = 10:20:1700\n    println(\"=================================\\n\")\n    println(\"N = $N\\n\")\n    Numdigs = Int(floor(2*N));\n\n    # Call the function which computes alpha at this level\n    # of precision.\n    myalpha, betan = compute_alpha(Numdigs, N, betan)\n    \n    # Print out myalpha to N digits of precision.  Must add 3\n    # to account for negative sign and \"2.\"\n    a = string(myalpha);\n    println(\"myalpha = $(a[1:N+3])\\n\")\n\n    f = open(\"alpha.dat\", \"a\");\n    write(f, \"==========\\nN = $N\\n$(a[1:N+3])\\n\")\n    close(f)\n\n    # Compare against the version from \n    # http://www.plouffe.fr/simon/constants/feigenbaum.txt\n    oeisalpha = oeis_alpha(3*Numdigs);\n    diff = Float64(abs(myalpha) - abs(oeisalpha));\n    println(\"diff = $diff\\n\")\n  end\n\n\nend\n\n\n#------------------------------------------------\nfunction oeis_alpha(Numdigs)\n  # Return up to 1018 digits of alpha from\n  # http://www.plouffe.fr/simon/constants/feigenbaum.txt\n\n  if (Numdigs <= 1018)\n    setprecision(Numdigs);\n  else\n    setprecision(1018);\n  end\n\n  str = \"-2.\"\n  str = str*\"5029078750958928222839028732182157863812713767271499773361920567\"\n  str = str*\"7923546317959020670329964974643383412959523186999585472394218237\"\n  str = str*\"7785445179272863314993372578112163594879503744781260997380598671\"\n  str = str*\"2397117373289276654044010306698313834600094139322364490657889951\"\n  str = str*\"2205843172507873377463087853424285351988587500042358246918740820\"\n  str = str*\"4281700901714823051821621619413199856066129382742649709844084470\"\n  str = str*\"1008054549677936760888126446406885181552709324007542506497157047\"\n  str = str*\"0475419932831783645332562415378693957125097066387979492654623137\"\n  str = str*\"6745918909813116752434221110130913127837160951158341230841503716\"\n  str = str*\"4997020224681219644081216686527458043026245782561067150138521821\"\n  str = str*\"6449532543349873487413352795815351016583605455763513276501810781\"\n  str = str*\"1948369459574850237398235452625632779475397269902012891516645793\"\n  str = str*\"9420198920248803394051699686551494477396533876979741232354061781\"\n  str = str*\"9896112494095990353128997733611849847377946108428833293833903950\"\n  str = str*\"9008914086351525626803381414669279913310743349705143545201344643\"\n  str = str*\"4264752001621384610729922641994332772918977769053802596851\"\n\n  alpha = parse(BigFloat, str)\n\nend", "meta": {"hexsha": "355f9a6b57fcf20b1887fd12a40ad4f86eba0d08", "size": 6196, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "compute_alpha.jl", "max_stars_repo_name": "brorson/FeigenbaumConstants", "max_stars_repo_head_hexsha": "d3a37be33d81c6d54e11d1f25d208637406092eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2017-11-28T17:10:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T14:05:25.000Z", "max_issues_repo_path": "compute_alpha.jl", "max_issues_repo_name": "brorson/FeigenbaumConstants", "max_issues_repo_head_hexsha": "d3a37be33d81c6d54e11d1f25d208637406092eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compute_alpha.jl", "max_forks_repo_name": "brorson/FeigenbaumConstants", "max_forks_repo_head_hexsha": "d3a37be33d81c6d54e11d1f25d208637406092eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-01-30T17:22:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T21:34:37.000Z", "avg_line_length": 32.6105263158, "max_line_length": 78, "alphanum_fraction": 0.645900581, "num_tokens": 1889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.777406758315586}}
{"text": "using LinearAlgebra\nusing DataFrames\nusing CSV\n\n#This file contains various renditions of  which perform numerical\n#quadrature given integration endpoints and a function handle\n#More importantly, it provides a composite type which stores nodes and weight. \n\n\"\"\"\nData-type which stores quadrature nodes and weights\n\"\"\"\n \n\nmutable struct nodesWeights{T1<:Array{Float64}, T2<:Array{Float64}}\n    nodes::T1\n    weights::T2  \nend\n\n\"\"\"\nApply affine transformation to nodes to integration over range r (linear change of variables)\n\"\"\"\nfunction affineTransformNodes(nw::nodesWeights{O}, r::Array{<:Real}) where O<:Union{Array{Float64, 2}, Array{Float64, 1}}\n    b = r[2]; a = r[1]\n    nw.nodes = (b-a)/2 .* nw.nodes .+ (b + a)/2\nend\n\n\n\"\"\"\nUses the Golub-Welsch eigenvalue method to compute\nGauss-Legendre quadrature nodes and weights for the domain [-1, 1]\n\nINPUTS: n, the number of desired nodes\nOUTPUTS: x and w, the nodes and weights\n\"\"\"\nfunction gausslegpts(n)\n    x = zeros(n-1) \n    for i = 1:n-1\n        x[i] = i/sqrt(4*i^2-1)\n    end\n    x = SymTridiagonal(zeros(n), x) #Jacobi matrix\n    d, V = eigen(x)\n    w = 2*V[1,:].^2 #factor of 2 comes from the fact that integral of measure is 2\n    return d, w\nend\n\n#precomute various integration nodes/weights\ndm0, wm0 = gausslegpts(24) \ndm, wm = gausslegpts(12) \ndm2, wm2 = gausslegpts(50)\ndm3, wm3 = gausslegpts(100)\n\nfunction getGaussQuadraturedata()\n    nodesWeights(dm, wm)\nend\n\n\"\"\"\nINPUTS:\nf is a function handle, a and b are integration endpoints (a<b), and n \nis the number of quadrature nodes (defaults to 10). Note that f can be\nmulti-output, in which case int1D integrates each entry individually. This way,\nthe function lends itself to being composed with Gauss-Turan integration.  \n\"\"\"\nfunction int1D(f, arr, num=\"1\")\n    if num==\"1\"\n        x, w= dm, wm\n    elseif num==\"2\"\n        x, w= dm2, wm2\n    elseif num==\"0\"\n        x, w = dm0, wm0\n    else \n        x, w = dm3, wm3\n    end\n    sample = f(arr[1])\n    res = zeros(size(sample))\n    for i = 1:length(x)\n        expr = (arr[2]-arr[1])/2 * x[i] .+ (arr[1]+arr[2])/2\n        #println(res)\n        #println(f(expr) .* w[i])\n        res = res .+ f(expr) .* w[i]\n    end\n    res = (arr[2]-arr[1])/2 .* res\nend\n\nfunction int1D_print(f, arr, num=\"0\")\n    if num==\"1\"\n        x, w= dm, wm\n    elseif num==\"2\"\n        x, w= dm2, wm2\n    elseif num==\"0\"\n        x, w = dm0, wm0\n    else \n        x, w = dm3, wm3\n    end\n    sample = f(arr[1])\n    res = zeros(size(sample))\n    for i = 1:length(x)\n        expr = (arr[2]-arr[1])/2 * x[i] .+ (arr[1]+arr[2])/2\n        println(res)\n        println(f(expr) .* w[i])\n        res = res .+ f(expr) .* w[i]\n    end\n    res = (arr[2]-arr[1])/2 .* res\nend\n\n\"\"\"\nIntegrates function over 2D domain using Gauss-Legendre Quadrature\narr[:, 1] are lower bounds, while arr[:, 2] are upper bounds     \n\"\"\"\nfunction int2D(f, arr)\n    d = size(arr, 1) #number of dimensions\n    int = 0.0\n    x, w = dm, wm\n    avg1 = (arr[1, 2] - arr[1, 1])/2\n    avg2 = (arr[2, 2] - arr[2, 1])/2\n    for i = 1:length(x)\n        for j = 1:length(x)\n           expr1 = avg1*x[i] + (arr[1, 2]+arr[1, 1])/2\n           expr2 = avg2*x[j] + (arr[2, 2]+arr[2, 1])/2\n           int = int + w[i]*w[j]*f(expr1, expr2)\n        end\n    end\n    int = int*avg1*avg2\nend\n\ndata50 = DataFrame(CSV.File(\"nodes_weights_50.csv\", header=0))\nnodes50 = convert(Array, data50[:,1]) #integration nodes for Gauss-Turan Quadrature\nweights50 = convert(Matrix, data50[:, 2:end]) #integration weights \n\ndata20 = DataFrame(CSV.File(\"nodes_weights_20.csv\", header=0))\nnodes20  = convert(Array, data20[:,1])\nweights20 = convert(Array, data20[:,2:end])\n\ndata12 = DataFrame(CSV.File(\"nodes_weights_12.csv\", header=0))\nnodes12  = convert(Array, data12[:,1])\nweights12 = convert(Array, data12[:,2:end])\n\nfunction getTuranQuadratureData()\n    return nodesWeights(nodes12, weights12)\nend\n\n\"\"\"\nGauss-Turan integration with 2 derivatives\nINPUTS:\narr contains enpoints of integration interval\n\"\"\"\nfunction Gauss_Turan(F, arr, nodes = nodes12, weights=weights12)\n    a = arr[1]\n    b = arr[2]\n    nodes = (b-a)/2 .* nodes .+ (b+a)/2\n    T = zeros(length(nodes), 3)\n    time = @elapsed begin\n    for i = 1:length(nodes)\n        (T[i, 1], T[i, 2], T[i, 3]) = F(nodes[i])\n    end\n    end\n    println(time)\n    fn = T[:, 1]\n    dfn = T[:, 2]\n    d2fn = T[:, 3]\n    return (fn'*weights[:, 1] + dfn'*weights[:, 2] + d2fn'*weights[:, 3])*(b-a)/2\nend\n\n\"\"\"\nn-dimensional Gauss-Legendre integration\n\"\"\"\nfunction intnD(f, arr, n)\n\nend\n", "meta": {"hexsha": "e3415c2ab498fb0cc33af3c1a7e10ba3970ba4b2", "size": 4498, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "individual_implementations/btg julia/quadrature.jl", "max_stars_repo_name": "dbindel/btg", "max_stars_repo_head_hexsha": "83616be1d1c4d80f385fa95cef38753f39a3a4c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-09-18T04:52:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-03T18:58:55.000Z", "max_issues_repo_path": "individual_implementations/btg julia/quadrature.jl", "max_issues_repo_name": "dbindel/btg", "max_issues_repo_head_hexsha": "83616be1d1c4d80f385fa95cef38753f39a3a4c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "individual_implementations/btg julia/quadrature.jl", "max_forks_repo_name": "dbindel/btg", "max_forks_repo_head_hexsha": "83616be1d1c4d80f385fa95cef38753f39a3a4c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-06T06:07:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-06T06:07:50.000Z", "avg_line_length": 26.6153846154, "max_line_length": 121, "alphanum_fraction": 0.612716763, "num_tokens": 1485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8311430478583169, "lm_q1q2_score": 0.7774067504912529}}
{"text": "function chobac!(kb::Matrix{Float64}, loads::Vector{Float64})\n  #local l, m\n  n = size(kb, 1)\n  iw = size(kb, 2) - 1\n  loads[1] = loads[1] / kb[1, iw+1]\n  for i in 2:n\n    x = 0.0\n    k = 1\n    if i <= (iw + 1)\n      k = iw - i + 2\n    end\n    for j in k:iw\n      x += kb[i, j]*loads[i+j-iw-1]\n    end\n    loads[i] = (loads[i] - x) / kb[i, iw+1]\n  end\n  loads[n] = loads[n] / kb[n, iw+1]\n  for i in n-1:-1:1\n    x = 0.0\n    l = i + iw\n    m = l - 1\n    if i > (n - iw)\n      l = n\n      m = i + 1\n    end\n    for j in m:l\n      x += kb[j, iw+i-j+1] * loads[j]\n    end\n    loads[i] = (loads[i] - x) / kb[i, iw+1]\n  end\nend\n  ", "meta": {"hexsha": "1613b17337f474c6011504718c1e6286e7b447d8", "size": 624, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nmlib/chobac.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "src/nmlib/chobac.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "src/nmlib/chobac.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 19.5, "max_line_length": 61, "alphanum_fraction": 0.4310897436, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7774067499096411}}
{"text": "# [18](https://projecteuler.net/problem=18) / [67](https://projecteuler.net/problem=67)\n\n#In a triangle like this:\n#\n#      a\n#     b c\n#    d e f\n#    \n#the best way to find the anwser is not to get the maximum from the summaries of\n#all possible branches from top to bottom.\n#\n#There is such a recursive pattern\n#\n#a + max( b+max(b,c), c+max(e,f)\n#\n# tri.txt\n#75\n#95 64\n#17 47 82\n#18 35 87 10\n#20 04 82 47 65\n#19 01 23 75 03 34\n#88 02 77 73 07 63 67\n#99 65 04 28 06 16 70 92\n#41 41 26 56 83 40 80 70 33\n#41 48 72 33 47 32 37 16 94 29\n#53 71 44 65 25 43 91 52 97 51 14\n#70 11 33 28 77 73 17 78 39 68 17 57\n#91 71 52 38 17 14 91 43 58 50 27 29 48\n#63 66 04 68 89 53 67 30 73 16 69 87 40 31\n#04 62 98 27 23 09 70 98 73 93 38 53 60 04 23\n\nimport Base.zero\nzero(::SubString{String}) = 0 # Julia 0.5\n\nZeroString(::SubString{String}) = 0\nZeroString(x::Int64) = x\n\nA = readdlm(\"tri.txt\")\nA = ZeroString.(A)\n\nfunction myreduction(m)\n\tif size(m)[1] == 1\n\t\treturn m[1,1]\n\telse\n\t\tmprime = m[1:(end-1), :]\n\t\tfor k in 1:(size(m, 1)-1)\n\t\t\tmprime[size(mprime, 1), k] += max(\n\t\t\t\t\t\t\t\t\t m[size(m, 1),k], m[size(m, 1),k+1])\n\t\tend\n\t\treturn myreduction(mprime)\n\tend\nend\n\nprintln(myreduction(A))\n", "meta": {"hexsha": "5302170efb9c4900244765a49942a0107092e457", "size": 1176, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "algo/su.18.jl", "max_stars_repo_name": "cdluminate/MyNotes", "max_stars_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algo/su.18.jl", "max_issues_repo_name": "cdluminate/MyNotes", "max_issues_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algo/su.18.jl", "max_forks_repo_name": "cdluminate/MyNotes", "max_forks_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0, "max_line_length": 87, "alphanum_fraction": 0.6301020408, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7774067470372432}}
{"text": "## This function computes the Generalized Laguerre polynomials using the Tridiagonal matrix\ninclude(\"orthopoly_evaluate.jl\")\nfunction compute_laguerre(n, a, x, all=true)\n    # Evaluate Orthonormalized Laguerre polynomials at x\n    #  Laguerre:\n    #     w(x)=x^a exp(-x) with integral gamma(a+1)  (a>-1)\n    #     Equivalent Mathematica:LaguerreL[n,a,x]/Sqrt[Gamma[n+a+1]/Gamma[n+1]] \n    ## Laguerre Bidiagonal matrix\n    B = diagm(sqrt((a + 1 +(0:n)))) # diagonal\n    B = B - diagm(sqrt((1:n)), 1)   # superdiagonal\n    T = B'*B\n    c = gamma(a+1) #Integral of weight function\n    ## Default to 0 through n computation\n    if all\n        phi = orthopoly_evaluate_all(T, x)\n    else\n        phi = orthopoly_evaluate_n(T, x)\n    end\n    phi/sqrt(c)\nend\n", "meta": {"hexsha": "dfc9d0d8a0d5dca3cea48236236b29247e00ab60", "size": 753, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demos/book/5/compute_laguerre.jl", "max_stars_repo_name": "shashi/RandomMatrices.jl", "max_stars_repo_head_hexsha": "603b9e9acd95133839e804d6ef068cdfee4cbbfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2017-09-29T08:46:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T10:05:30.000Z", "max_issues_repo_path": "demos/book/5/compute_laguerre.jl", "max_issues_repo_name": "shashi/RandomMatrices.jl", "max_issues_repo_head_hexsha": "603b9e9acd95133839e804d6ef068cdfee4cbbfb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2017-08-18T19:50:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-15T08:08:44.000Z", "max_forks_repo_path": "demos/book/5/compute_laguerre.jl", "max_forks_repo_name": "shashi/RandomMatrices.jl", "max_forks_repo_head_hexsha": "603b9e9acd95133839e804d6ef068cdfee4cbbfb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2018-01-05T22:05:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T20:25:41.000Z", "avg_line_length": 35.8571428571, "max_line_length": 91, "alphanum_fraction": 0.6440903054, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551957, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.777385581792949}}
{"text": "function sieve2(n :: Int)\n    ni = (n - 1) ÷ 2\n    isprime = trues(ni)\n    for i in 1:ni\n        if isprime[i]\n            j = 2i * (i + 1)\n            if j > ni\n                m = findall(isprime)\n                map!((i::Int) -> 2i + 1, m, m)\n                return pushfirst!(m, 2)\n            else\n                p = 2i + 1\n                while j <= ni\n                  isprime[j] = false\n                  j += p\n                end\n            end\n        end\n    end\nend\n", "meta": {"hexsha": "37d0d54a3aea6bae3a7358217b397bd45a35c235", "size": 482, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/sieve-of-eratosthenes-3.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/sieve-of-eratosthenes-3.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/sieve-of-eratosthenes-3.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9523809524, "max_line_length": 46, "alphanum_fraction": 0.3236514523, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202038, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7773855725623682}}
{"text": "module Day05\n\nusing OffsetArrays\n\nexport day05\n\nfunction parseLine(line)\n    raw = split.(split(line, \" -> \"), \",\")\n    return complex(parse.(Int64, raw[1])...), complex(parse.(Int64, raw[2])...)\nend\n\nfunction readInput(inputfile=\"inputs/input05.txt\")\n    return [parseLine(line) for line in eachline(inputfile)]\nend\n\n\nfunction day05(ventdata = readInput(\"inputs/input05.txt\"))\n    minx = minimum((a) -> min(real(a[1]), real(a[2])), ventdata)\n    miny = minimum((a) -> min(imag(a[1]), imag(a[2])), ventdata)\n    maxx = maximum((a) -> max(real(a[1]), real(a[2])), ventdata)\n    maxy = maximum((a) -> max(imag(a[1]), imag(a[2])), ventdata)\n\n    ## previous version used a Dict here\n    ## that's ~25x slower\n    grid = OffsetArray(zeros(UInt8, maxx-minx+1, maxy-miny+1), minx:maxx, miny:maxy)\n\n    mask = ishorizontal.(ventdata)\n    mapvents!(grid, ventdata[mask])\n    part1 = count(>=(2), grid)\n\n    mapvents!(grid, ventdata[.!(mask)])\n    part2 = count(>=(2), grid)\n    return part1, part2\nend\n\nfunction mapvents!(grid, data)\n    for (start, stop) in data\n        Δ = stop-start\n        dist = distance(Δ)\n        δ = intdiv(Δ, dist)\n        for l in 0:dist\n            pos = start+δ*l\n            grid[real(pos), imag(pos)] += 1\n        end\n    end\n    return grid\nend\n\nishorizontal((from, to)) = real(from) == real(to) || imag(from) == imag(to)\ndistance(x::Complex) = let r = abs(real(x)); r == 0 ? abs(imag(x)) : r end\nintdiv(x::Complex, by::Int) = complex(div(real(x), by), div(imag(x), by))\n\ncount_crossings(grid) = count(>=(2), values(grid))\n\nend #module\n", "meta": {"hexsha": "fe9011e80cea30c9e0ee3f6d9142e05cca64f23f", "size": 1561, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/day05.jl", "max_stars_repo_name": "abraemer/AoC2021.jl", "max_stars_repo_head_hexsha": "f445367d5a6059bdba32608df122f53ab0aba929", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/day05.jl", "max_issues_repo_name": "abraemer/AoC2021.jl", "max_issues_repo_head_hexsha": "f445367d5a6059bdba32608df122f53ab0aba929", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/day05.jl", "max_forks_repo_name": "abraemer/AoC2021.jl", "max_forks_repo_head_hexsha": "f445367d5a6059bdba32608df122f53ab0aba929", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-12T18:36:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-12T18:36:56.000Z", "avg_line_length": 27.875, "max_line_length": 84, "alphanum_fraction": 0.602178091, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7773825649779808}}
{"text": "push!(LOAD_PATH,joinpath(@__DIR__, \"../src/\"))\nusing LinearAlgebra\nusing StableApproxEPW\n\n# ## Target of the approximation problem\n\n# We consider the Helmholtz solution in the unit disk, with wavenumber\nk = 5;\n# We need to define the maximum Fourier mode number `P` in the approximation\n# target:\nP = 25;\n# The target approximation will be of the form\n# ```math\n# u = \\mathbf{x} ↦ \\sum_{|p| \\leq P} u_p b_{p}(\\mathbf{x}).\n# ```\n# Next we construct the vector of coefficients in the basis `b_p`\n# for `p` in `[-P,P]`:\nU = zeros(ComplexF64, 2P+1);\nU[P+1]     = 0.5;  # This is the constant mode (`p=0`)\nU[P+1 + P] = 1im;  # This is mode `p = P`\n# Here the only non-zero coefficients are ``u_0 = \\frac{1}{2}`` and\n# ``u_P = \\imath`` so that\n# ```math\n# u = \\frac{1}{2} b_{0} + \\imath b_{P}.\n# ```\n# The target of the approximation problem can then be constructed as:\nu = solution_surrogate(U; k=k);\n# ``u`` can be evaluated at any `(r,θ)` point.\n# Alternatively, the target ``u`` could have been a single mode.\n# For instance, to get the circular wave with mode number `p=15`, simply set\n# ``u = bp(15; k=k)``.\n# Of course, any other function (defined in polar coordinates) can be defined\n# by the user as target of the approximation problem.\n\n# ## Reconstruction method\n\n# The approximation will be reconstructed by sampling the target on the\n# boundary of the unit disk.\n# To do so, we need to know now the dimension `N` of the approximation sets\n# that we are going to use:\nN = 100;\n# We can determine the number of sampling nodes necessary for a successful\n# reconstruction, based on `N`, `P` (to avoid aliasing) and the oversampling\n# ratio `η`:\nS = number_of_boundary_sampling_nodes(N; η=2, P=P);\n# The (equispaced) boundary nodes are then constructed as:\nX = boundary_sampling_nodes(S);\n# The right-hand-side of the linear system can then be readily constructed:\nb = samples_from_nodes(u, X);\n\n\n# ## Approximation with **propagative** plane waves\n\n# We construct the approximation set of PPW:\nΦppw = approximation_set(N; k=k);\n# The matrix and its (SVD) factorization\nAppw = samples_from_nodes(Φppw, X);\niAppw = RegularizedSVDPseudoInverse(Appw; ϵ=1e-14);\n# The coefficients of the approximation are computed:\nξppw = solve_via_regularizedSVD(iAppw, b);\nũppw = (r,θ) -> sum([ξi * ϕi(r,θ) for (ξi, ϕi) in zip(ξppw, Φppw)]);\n# Absolute error function\neppw = (r,θ) -> ũppw(r,θ) - u(r,θ); eppw(1,π/2)\n# Let's compute the relative residual:\nresppw = norm(Appw * ξppw - b) / norm(b)\n# We did not obtained any accuracy whatsoever!\n# The reason is that the coefficients are too large:\nnrmppw = norm(ξppw) / norm(U)\n\n\n# ## Approximation with **evanescent** plane waves\n\n# We construct the approximation set of EPW:\nΦepw = approximation_set(N, P, sobol_sampling; k=k);\n# It is possible to choose other types of sampling methods, instead of\n# `sobol_sampling`, for instance `uniform_sampling` and `random_sampling`.\n# The matrix and its (SVD) factorization\nAepw = samples_from_nodes(Φepw, X);\niAepw = RegularizedSVDPseudoInverse(Aepw; ϵ=1e-14);\n# The coefficients of the approximation are computed:\nξepw = solve_via_regularizedSVD(iAepw, b);\nũepw = (r,θ) -> sum([ξi * ϕi(r,θ) for (ξi, ϕi) in zip(ξepw, Φepw)]);\n# Absolute error function\neepw = (r,θ) -> ũepw(r,θ) - u(r,θ); eepw(1,π/2)\n# Let's compute the relative residual:\nresepw = norm(Aepw * ξepw - b) / norm(b)\n# We get almost 8 digits of accuracy!\n# The size of the coefficients remains quite high:\nnrmepw = norm(ξepw) / norm(U)\n\n# ### Down to machine precision\n\n# Let's double the number of EPW\nN = 200\n# The above approximation process can be obtained much more rapidly with the\n# following convenience function\n_, ξepw, ũepw, resepw, nrmepw, eepw = Dirichlet_sampling(k, U, N; smpl_type=sobol_sampling);\n# One can check that we obtain now a relative residual very close to machine\n# precision (13 digits of accuracy):\nresepw\n# The size of the coefficients is also greatly reduced:\nnrmepw", "meta": {"hexsha": "b8b90fd5edfcdc90d74e697dd7f50bf711dace41", "size": 3942, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/example.jl", "max_stars_repo_name": "EmileParolin/STrAW", "max_stars_repo_head_hexsha": "beea3b830a66d1fad257e455fba06bb8614b1abb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/example.jl", "max_issues_repo_name": "EmileParolin/STrAW", "max_issues_repo_head_hexsha": "beea3b830a66d1fad257e455fba06bb8614b1abb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/example.jl", "max_forks_repo_name": "EmileParolin/STrAW", "max_forks_repo_head_hexsha": "beea3b830a66d1fad257e455fba06bb8614b1abb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6470588235, "max_line_length": 93, "alphanum_fraction": 0.7092846271, "num_tokens": 1249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7773825649779808}}
{"text": "_clamp(u, u_min, u_max) = max(min(u, u_max), u_min)\n_dead_zone(u, u_min, u_max) = ifelse(u > u_max, u - u_max, ifelse(u < u_min, u - u_min, 0))\n\n\"\"\"\nLimit the range of a signal.\n\n# Parameters:\n- `y_max`: Maximum of output signal\n- `y_min`: Minimum of output signal\n\"\"\"\nfunction Limiter(;name, y_max, y_min=y_max > 0 ? -y_max : -Inf)\n    y_max ≥ y_min || throw(ArgumentError(\"`y_min` must be smaller than `y_max`\"))\n    @named siso = SISO()\n    @unpack u, y = siso\n    pars = @parameters y_max=y_max y_min=y_min\n    eqs = [\n        y ~ _clamp(u, y_min, y_max)\n    ]\n    extend(ODESystem(eqs, t, [], pars; name=name), siso)\nend\n\n\"\"\"\n    DeadZone(; u_max, u_min=-u_max, name)\n\nThe DeadZone block defines a region of zero output.\nIf the input is within uMin ... uMax, the output is zero. Outside of this zone, the output is a linear function of the input with a slope of 1.\n```\n       y▲\n        │     /\n        │    /\n  u_min │   /\n─────|──┼──|───────► u\n    /   │   u_max\n   /    │\n  /     │\n```\n\"\"\"\nfunction DeadZone(; name, u_max, u_min=-u_max)\n    if !ModelingToolkit.isvariable(u_max)\n        u_max ≥ u_min || throw(ArgumentError(\"`u_min` must be smaller than `u_max`\"))\n    end\n    @named siso = SISO()\n    @unpack u, y = siso\n    pars = @parameters u_max=u_max u_min=u_min\n    eqs = [\n        y ~ _dead_zone(u, u_min, u_max)\n    ]\n    extend(ODESystem(eqs, t, [], pars; name=name), siso)\nend\n\n\"\"\"\n    SlewRateLimiter(;name, rising=1, falling=-rising, Td=0.001, y_start=0.0)\n    \nLimits the slew rate of a signal.\n\n# Parameters:\n- `Rising`: Maximum rising slew rate\n- `falling`: Maximum falling slew rate\n- `Td`: Derivative time constant\n\"\"\"\nfunction SlewRateLimiter(;name, rising=1, falling=-rising, Td=0.001, y_start=0.0)\n    rising ≥ falling || throw(ArgumentError(\"`rising` must be smaller than `falling`\"))\n    Td > 0 || throw(ArgumentError(\"Time constant `Td` must be strictly positive\"))\n    @named siso = SISO(y_start=y_start)\n    @unpack u, y = siso\n    pars = @parameters rising=rising falling=falling\n    eqs = [\n        D(y) ~ max(min((u-y) / Td, rising), falling)\n    ]\n    extend(ODESystem(eqs, t, [], pars; name=name), siso)\nend\n", "meta": {"hexsha": "2a9ac5c0ee2144b83864d6aae8c2f64361b48004", "size": 2147, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Blocks/nonlinear.jl", "max_stars_repo_name": "AayushSabharwal/ModelingToolkitStandardLibrary.jl", "max_stars_repo_head_hexsha": "4b081e638e26db5d67e0de258e40815242687132", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Blocks/nonlinear.jl", "max_issues_repo_name": "AayushSabharwal/ModelingToolkitStandardLibrary.jl", "max_issues_repo_head_hexsha": "4b081e638e26db5d67e0de258e40815242687132", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Blocks/nonlinear.jl", "max_forks_repo_name": "AayushSabharwal/ModelingToolkitStandardLibrary.jl", "max_forks_repo_head_hexsha": "4b081e638e26db5d67e0de258e40815242687132", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8194444444, "max_line_length": 143, "alphanum_fraction": 0.6157428971, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7773825614611086}}
{"text": "Text provided under a Creative Commons Attribution license, CC-BY.  All code is made available under the FSF-approved BSD-3 license.  (c) Lorena A. Barba, Gilbert F. Forsyth 2017. Thanks to NSF for support via CAREER award #1149784.\n[@LorenaABarba](https://twitter.com/LorenaABarba)\n\n12 steps to Navier–Stokes\n=====\n***\n\nFor a moment, recall the Navier–Stokes equations for an incompressible fluid, where $\\vec{v}$ represents the velocity field:\n\n$$\n\\begin{eqnarray*}\n\\nabla \\cdot\\vec{v} &=& 0 \\\\\n\\frac{\\partial \\vec{v}}{\\partial t}+(\\vec{v}\\cdot\\nabla)\\vec{v} &=& -\\frac{1}{\\rho}\\nabla p + \\nu \\nabla^2\\vec{v}\n\\end{eqnarray*}\n$$\n\nThe first equation represents mass conservation at constant density. The second equation is the conservation of momentum. But a problem appears: the continuity equation for incompressble flow does not have a dominant variable and there is no obvious way to couple the velocity and the pressure. In the case of compressible flow, in contrast, mass continuity would provide an evolution equation for the density $\\rho$, which is coupled with an equation of state relating $\\rho$ and $p$.\n\nIn incompressible flow, the continuity equation $\\nabla \\cdot\\vec{v}=0$ provides a *kinematic constraint* that requires the pressure field to evolve so that the rate of expansion $\\nabla \\cdot\\vec{v}$ should vanish everywhere. A way out of this difficulty is to *construct* a pressure field that guarantees continuity is satisfied; such a relation can be obtained by taking the divergence of the momentum equation. In that process, a Poisson equation for the pressure shows up!\n\nStep 10: 2D Poisson Equation\n----\n***\n\nPoisson's equation is obtained from adding a source term to the right-hand-side of Laplace's equation:\n\n$$\\frac{\\partial ^2 p}{\\partial x^2} + \\frac{\\partial ^2 p}{\\partial y^2} = b$$\n\nSo, unlinke the Laplace equation, there is some finite value inside the field that affects the solution. Poisson's equation acts to \"relax\" the initial sources in the field.\n\nIn discretized form, this looks almost the same as [Step 9](./12_Step_9.ipynb), except for the source term:\n\n$$\\frac{p_{i+1,j}^{n}-2p_{i,j}^{n}+p_{i-1,j}^{n}}{\\Delta x^2}+\\frac{p_{i,j+1}^{n}-2 p_{i,j}^{n}+p_{i,j-1}^{n}}{\\Delta y^2}=b_{i,j}^{n}$$\n\nAs before, we rearrange this so that we obtain an equation for $p$ at point $i,j$. Thus, we obtain:\n\n$$p_{i,j}^{n}=\\frac{(p_{i+1,j}^{n}+p_{i-1,j}^{n})\\Delta y^2+(p_{i,j+1}^{n}+p_{i,j-1}^{n})\\Delta x^2-b_{i,j}^{n}\\Delta x^2\\Delta y^2}{2(\\Delta x^2+\\Delta y^2)}$$\n\n\nWe will solve this equation by assuming an initial state of $p=0$ everywhere, and applying boundary conditions as follows:\n\n$p=0$ at $x=0, \\ 2$ and $y=0, \\ 1$\n\nand the source term consists of two initial spikes inside the domain, as follows:\n\n$b_{i,j}=100$ at $i=\\frac{1}{4}nx, j=\\frac{1}{4}ny$\n\n$b_{i,j}=-100$ at $i=\\frac{3}{4}nx, j=\\frac{3}{4}ny$\n\n$b_{i,j}=0$ everywhere else.\n\nThe iterations will advance in pseudo-time to relax the initial spikes. The relaxation under Poisson's equation gets slower and slower as they progress. *Why?*\n\nLet's look at one possible way to write the code for Poisson's equation. As always, we load our favorite Python libraries. We also want to make some lovely plots in 3D. Let's get our parameters defined and the initialization out of the way. What do you notice of the approach below?\n\n\n```python\nimport numpy\nfrom matplotlib import pyplot, cm\nfrom mpl_toolkits.mplot3d import Axes3D\n%matplotlib inline\n```\n\n\n```python\n# Parameters\nnx = 50\nny = 50\nnt  = 100\nxmin = 0\nxmax = 2\nymin = 0\nymax = 1\n\ndx = (xmax - xmin) / (nx - 1)\ndy = (ymax - ymin) / (ny - 1)\n\n# Initialization\np  = numpy.zeros((ny, nx))\npd = numpy.zeros((ny, nx))\nb  = numpy.zeros((ny, nx))\nx  = numpy.linspace(xmin, xmax, nx)\ny  = numpy.linspace(xmin, xmax, ny)\n\n# Source\nb[int(ny / 4), int(nx / 4)]  = 100\nb[int(3 * ny / 4), int(3 * nx / 4)] = -100\n```\n\nWith that, we are ready to advance the initial guess in pseudo-time. How is the code below different from the function used in [Step 9](./12_Step_9.ipynb) to solve Laplace's equation?\n\n\n```python\nfor it in range(nt):\n\n    pd = p.copy()\n\n    p[1:-1,1:-1] = (((pd[1:-1, 2:] + pd[1:-1, :-2]) * dy**2 +\n                    (pd[2:, 1:-1] + pd[:-2, 1:-1]) * dx**2 -\n                    b[1:-1, 1:-1] * dx**2 * dy**2) / \n                    (2 * (dx**2 + dy**2)))\n\n    p[0, :] = 0\n    p[ny-1, :] = 0\n    p[:, 0] = 0\n    p[:, nx-1] = 0\n```\n\nMaybe we could reuse our plotting function from [Step 9](./12_Step_9.ipynb), don't you think?\n\n\n```python\ndef plot2D(x, y, p):\n    fig = pyplot.figure(figsize=(11, 7), dpi=100)\n    ax = fig.gca(projection='3d')\n    X, Y = numpy.meshgrid(x, y)\n    surf = ax.plot_surface(X, Y, p[:], rstride=1, cstride=1, cmap=cm.viridis,\n            linewidth=0, antialiased=False)\n    ax.view_init(30, 225)\n    ax.set_xlabel('$x$')\n    ax.set_ylabel('$y$')\n\n```\n\n\n```python\nplot2D(x, y, p)\n```\n\n\n![png](output_14_0.png)\n\n\nAh! The wonders of code reuse! Now, you probably think: \"Well, if I've written this neat little function that does something so useful, I want to use it over and over again. How can I do this without copying and pasting it each time? —If you are very curious about this, you'll have to learn about *packaging*. But this goes beyond the scope of our CFD lessons. You'll just have to Google it if you really want to know.\n\n***\n\n## Learn More\n\nTo learn more about the role of the Poisson equation in CFD, watch **Video Lesson 11** on You Tube:\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('ZjfxA3qq2Lg')\n```\n\n\n\n\n\n<iframe\n    width=\"400\"\n    height=\"300\"\n    src=\"https://www.youtube.com/embed/ZjfxA3qq2Lg\"\n    frameborder=\"0\"\n    allowfullscreen\n></iframe>\n\n\n\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n    styles = open(\"../styles/custom.css\", \"r\").read()\n    return HTML(styles)\ncss_styling()\n```\n\n\n\n\n<link href='http://fonts.googleapis.com/css?family=Fenix' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Source+Code+Pro:300,400' rel='stylesheet' type='text/css'>\n<style>\n    @font-face {\n        font-family: \"Computer Modern\";\n        src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');\n    }\n    div.cell{\n        width:800px;\n        margin-left:16% !important;\n        margin-right:auto;\n    }\n    h1 {\n        font-family: 'Alegreya Sans', sans-serif;\n    }\n    h2 {\n        font-family: 'Fenix', serif;\n    }\n    h3{\n\t\tfont-family: 'Fenix', serif;\n        margin-top:12px;\n        margin-bottom: 3px;\n       }\n\th4{\n\t\tfont-family: 'Fenix', serif;\n       }\n    h5 {\n        font-family: 'Alegreya Sans', sans-serif;\n    }\t   \n    div.text_cell_render{\n        font-family: 'Alegreya Sans',Computer Modern, \"Helvetica Neue\", Arial, Helvetica, Geneva, sans-serif;\n        line-height: 135%;\n        font-size: 120%;\n        width:600px;\n        margin-left:auto;\n        margin-right:auto;\n    }\n    .CodeMirror{\n            font-family: \"Source Code Pro\";\n\t\t\tfont-size: 90%;\n    }\n/*    .prompt{\n        display: None;\n    }*/\n    .text_cell_render h1 {\n        font-weight: 200;\n        font-size: 50pt;\n\t\tline-height: 100%;\n        color:#CD2305;\n        margin-bottom: 0.5em;\n        margin-top: 0.5em;\n        display: block;\n    }\t\n    .text_cell_render h5 {\n        font-weight: 300;\n        font-size: 16pt;\n        color: #CD2305;\n        font-style: italic;\n        margin-bottom: .5em;\n        margin-top: 0.5em;\n        display: block;\n    }\n\n    .warning{\n        color: rgb( 240, 20, 20 )\n        }  \n</style>\n<script>\n    MathJax.Hub.Config({\n                        TeX: {\n                           extensions: [\"AMSmath.js\"]\n                           },\n                tex2jax: {\n                    inlineMath: [ ['$','$'], [\"\\\\(\",\"\\\\)\"] ],\n                    displayMath: [ ['$$','$$'], [\"\\\\[\",\"\\\\]\"] ]\n                },\n                displayAlign: 'center', // Change this to 'center' to center equations.\n                \"HTML-CSS\": {\n                    styles: {'.MathJax_Display': {\"margin\": 4}}\n                }\n        });\n</script>\n\n\n\n\n> (The cell above executes the style for this notebook.)\n", "meta": {"hexsha": "22759e9cba75c81a983bc79a6d04809d17e3c3be", "size": 8341, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lessons/13_Step_10.jl", "max_stars_repo_name": "mkitti/CFDJulia", "max_stars_repo_head_hexsha": "47c9df5c6cd4b7695ce0929b96f1c29a92850118", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lessons/13_Step_10.jl", "max_issues_repo_name": "mkitti/CFDJulia", "max_issues_repo_head_hexsha": "47c9df5c6cd4b7695ce0929b96f1c29a92850118", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lessons/13_Step_10.jl", "max_forks_repo_name": "mkitti/CFDJulia", "max_forks_repo_head_hexsha": "47c9df5c6cd4b7695ce0929b96f1c29a92850118", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7148288973, "max_line_length": 485, "alphanum_fraction": 0.6270231387, "num_tokens": 2491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7773825582388494}}
{"text": "#-----------------------------#\n# see page 136 in Sarkka book #\n#-----------------------------#\n\nfunction smoothingrecursion(y; A = A, H = H, Q = Q, R = R, m = m, P = P)\n\n    N = length(y); @assert(N == length(m) == length(P))\n\n    # Store here state distribution\n\n    μstate, Σstate = Array{Vector{Float64}}(undef, N), Array{Matrix{Float64}}(undef, N)\n\n    # Start recursion with prior mean and prior covariance\n\n    mˢₖ₊₁, Pˢₖ₊₁ = m[end], P[end]\n\n    μstate[N], Σstate[N] = mˢₖ₊₁, Pˢₖ₊₁\n\n    for k in N-1:-1:1\n\n        m⁻ₖ₊₁ = A * m[k]\n\n        P⁻ₖ₊₁ = A * P[k] * A' + Q\n\n        Gₖ = (P[k] * A') / P⁻ₖ₊₁\n\n        mˢₖ = m[k] + Gₖ * (mˢₖ₊₁ - m⁻ₖ₊₁)\n\n        Pˢₖ = P[k] + Gₖ * (Pˢₖ₊₁ - P⁻ₖ₊₁) * (Gₖ)'\n\n        # store mean and covariance of Gaussian distribution N(xₖ|mˢₖ, Pˢₖ)\n        Pˢₖ = (Pˢₖ + (Pˢₖ)') / 2\n\n        μstate[k], Σstate[k] = mˢₖ, Pˢₖ\n\n        # previous state\n\n        mˢₖ₊₁, Pˢₖ₊₁ = mˢₖ, Pˢₖ\n\n    end\n\n    return μstate, Σstate\n\nend\n\n\n\nfunction testsmoothing(seed=1)\n\n    yclean, y, x, A, H, Q, R, m₀, P₀ = simulatedata(seed=seed)\n\n    μfilter, Σfilter = filteringrecursion(y; A = A, H = H, Q = Q, R = R, m₀ = m₀, P₀ = P₀)\n\n    μsmooth, Σsmooth = smoothingrecursion(y; A = A, H = H, Q = Q, R = R, m = μfilter, P = Σfilter)\n\n\n    figure()\n    subplot(211)\n    plot([yᵢ[1]        for yᵢ in yclean], label = \"simulated 1\")\n    plot([(H*xᵢ)[1]    for xᵢ in x], label = \"simulated 1\")\n    legend()\n\n    subplot(212)\n    plot([xᵢ[1]    for xᵢ in x], label = \"simulated 1\")\n    plot([xᵢ[1]    for xᵢ in μfilter], label = \"filtered 1\")\n    plot([xᵢ[1]    for xᵢ in μsmooth], \"--\", label = \"smoothed 1\")\n    legend()\n\n    acc = accfilter = accsmooth = 0.0\n\n    for i in 1:length(y)\n\n        acc += sum((yclean[i] - H*x[i]).^2) / length(y)\n\n        accfilter += sum((yclean[i] - H*μfilter[i]).^2)/ length(y)\n\n        accsmooth += sum((yclean[i] - H*μsmooth[i]).^2)/ length(y)\n\n    end\n\n    @show acc, accfilter, accsmooth\n\n    accx = accfilterx = accsmoothx = 0.0\n\n    for i in 1:length(y)\n\n        accx += sum((x[i] - x[i]).^2)\n\n        accfilterx += sum((x[i] - μfilter[i]).^2)\n\n        accsmoothx += sum((x[i] - μsmooth[i]).^2)\n\n    end\n\n    @show accx, accfilterx, accsmoothx\n\n\n    x, μfilter, μsmooth\n\nend\n", "meta": {"hexsha": "6d4b0cd320921bf485251ea51c2afa0bfed3e93b", "size": 2220, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/smoothingrecursion.jl", "max_stars_repo_name": "ngiann/StateSpaceStudy.jl", "max_stars_repo_head_hexsha": "249206cca241b672dbe44d0b24fdafe7d6624001", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/smoothingrecursion.jl", "max_issues_repo_name": "ngiann/StateSpaceStudy.jl", "max_issues_repo_head_hexsha": "249206cca241b672dbe44d0b24fdafe7d6624001", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/smoothingrecursion.jl", "max_forks_repo_name": "ngiann/StateSpaceStudy.jl", "max_forks_repo_head_hexsha": "249206cca241b672dbe44d0b24fdafe7d6624001", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9801980198, "max_line_length": 98, "alphanum_fraction": 0.5121621622, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582535657921, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7773825566277199}}
{"text": "\"\"\"\n    twoD(X)\n\nProject `X` to two dmensions using PCA\n\"\"\"\nfunction twoD(X)\n    X = X .- mean(X,dims=1)\n    X = X ./ std(X,dims=1)\n    s = svd(X)\n    Y = s.U[:,1:2]#.*s.S[1:2]'\n    Y[:,1], Y[:,2]\nend\n\n\"\"\"\n    threeD(X)\n\nProject `X` to three dimensions using PCA\n\"\"\"\nfunction threeD(X)\n    X = X .- mean(X,dims=1)\n    X = X ./ std(X,dims=1)\n    s = svd(X)\n    Y = s.U[:,1:3]#.*s.S[1:2]'\n    Y[:,1], Y[:,2], Y[:,3]\nend\n\n\"\"\"\n    s1(x, dims=:)\n\nnormalize x sums to 1\n\"\"\"\nfunction s1(x, dims=:)\n    if isderiving()\n        m = minimum(real(x), dims=dims)\n        if any(<(0), m)\n            x = x .- m\n        end\n        return x ./ sum(x, dims=dims)\n    else\n        m = minimum(x, dims=dims)\n        x = float.(x)\n        if any(<(0), m)\n            x .-= m\n        end\n        x ./= sum(x, dims=dims)\n    end\nend\n\n\"\"\"\n    n1(x)\n\nnormalize x norm 1\n\"\"\"\nn1(x) = x./norm(x)\nn1(x::AbstractMatrix, dims) = mapslices(n1, x, dims=dims)\n\"\"\"\n    v1(x, dims=:)\n\nnormalize x var 1\n\"\"\"\nfunction v1(x, dims=:)\n    x = x .- mean(x, dims=dims)\n    x .= x./std(x, dims=dims)\nend\n\nfunction v1!(x, dims=:)\n    x .-= mean(x, dims=dims)\n    x .= x./std(x, dims=dims)\nend\n\n\"\"\"\n    median1(x, dims=:)\n\nnormalize x median 0, median absolute deviation = 1\n\"\"\"\nfunction m1(x, dims=:)\n    x = x .- median(x, dims=dims)\n    # x .= x./mapslices(mad, x, dims=dims)\nend\nfunction m1(x::AbstractVector)\n    x = x .- median(x)\n    x .= x./mad(x, normalize=true)\nend\n\n\n\"\"\"\n    bp_filter(x, passband)\n\nBand-pass filter, passband is tuple, `fs` assumed = 1\n\"\"\"\nfunction bp_filter(x, passband)\n    responsetype = Bandpass(passband..., fs=1)\n    designmethod = Butterworth(2)\n    filt(digitalfilter(responsetype, designmethod), x)\nend\n\n\"\"\"\n    lp_filter(x, cutoff)\n\nLow-pass filter, `fs` assumed = 1\n\"\"\"\nfunction lp_filter(x, cutoff)\n    responsetype = Lowpass(cutoff, fs=1)\n    designmethod = Butterworth(2)\n    filt(digitalfilter(responsetype, designmethod), x)\nend\n", "meta": {"hexsha": "774d7444313fc5e2dfdccc6167df1623342ec4fd", "size": 1930, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "baggepinnen/SpectralDistances.jl", "max_stars_repo_head_hexsha": "7a97ac1652c7a5d39c9a50cff2fbb31bb92ad6ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2019-10-26T14:54:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T23:14:35.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "baggepinnen/SpectralDistances.jl", "max_issues_repo_head_hexsha": "7a97ac1652c7a5d39c9a50cff2fbb31bb92ad6ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2019-11-13T11:23:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T06:40:37.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "baggepinnen/SpectralDistances.jl", "max_forks_repo_head_hexsha": "7a97ac1652c7a5d39c9a50cff2fbb31bb92ad6ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:58:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T17:13:53.000Z", "avg_line_length": 18.0373831776, "max_line_length": 57, "alphanum_fraction": 0.5430051813, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7773825566277198}}
{"text": "\"\"\"\n## Convex hull\n\nCalculation f convex hull of a sequence of points represented through an Float64\nArray of N rows and 2 columns\n\"\"\"\nfunction convexhull{T <: Real}(points::Array{T,2})\n    n = size(points,1)\n    # Sort the points by x-coordinate, resulting in a sequence p 1 , . . . , p n\n    p = sortrows(points)\n    # Put the points p_1 and p_2 in a list L_upper , with p_1 as the first point\n    upper = [p[1,:], p[2,:]]\n\n    for i in 3:n\n        while size(upper,1) >= 2 && direction(upper[end-1], upper[end], p[i,:]) <= 0\n            pop!(upper)\n        end\n\n        push!(upper,p[i,:])\n    end\n\n    lower = [p[end,:], p[end-1,:]]\n\n    for i in n-2:-1:1\n        while size(lower,1) >= 2 && direction(lower[end-1], lower[end], p[i,:]) <= 0\n            pop!(lower)\n        end\n\n        push!(lower,p[i,:])\n    end\n\n    append!(upper, lower[2:end-1])\nend\n\nfunction convexhull{T <: Real}(points::Array{Point2D{T}, 1})\n    n = size(points,1)\n    # Sort the points by x-coordinate, resulting in a sequence p 1 , . . . , p n\n    p = sort(points)\n    # Put the points p_1 and p_2 in a list L_upper , with p_1 as the first point\n    upper = [p[1], p[2]]\n\n    for i in 3:n\n        while size(upper,1) >= 2 && direction(upper[end-1], upper[end], p[i]) <= 0\n            pop!(upper)\n        end\n\n        push!(upper,p[i])\n    end\n\n    lower = [p[end], p[end-1]]\n\n    for i in n-2:-1:1\n        while size(lower,1) >= 2 && direction(lower[end-1], lower[end], p[i]) <= 0\n            pop!(lower)\n        end\n\n        push!(lower,p[i])\n    end\n\n    append!(upper, lower[2:end-1])\nend\n", "meta": {"hexsha": "3ba4ac3c6d912754896a89e5968cd90f342dc6aa", "size": 1572, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/convexhull.jl", "max_stars_repo_name": "helgith/GeometricStructures", "max_stars_repo_head_hexsha": "45abab04c6eba046098f19d4c4b760d411f6366d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/convexhull.jl", "max_issues_repo_name": "helgith/GeometricStructures", "max_issues_repo_head_hexsha": "45abab04c6eba046098f19d4c4b760d411f6366d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/convexhull.jl", "max_forks_repo_name": "helgith/GeometricStructures", "max_forks_repo_head_hexsha": "45abab04c6eba046098f19d4c4b760d411f6366d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3548387097, "max_line_length": 84, "alphanum_fraction": 0.5432569975, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.777382554427364}}
{"text": "##################################################\n## Classical derivative-based, iterative, root-finding algorithms: Newton and Halley\n## Historic, we have derivative free versions of similar order\n\n\n## Newton\n\"\"\"\n\n    Roots.Newton()\n\nImplements Newton's [method](http://tinyurl.com/b4d7vls): `x_n1 = xn -\nf(xn)/f'(xn)`.  This is a quadratically converging method requiring\none derivative. Two function calls per step.\n\"\"\"\nstruct Newton <: AbstractUnivariateZeroMethod\nend\n\nfunction update_state(method::Newton, fs, o, options) \n    xn = o.xn1\n    fxn = o.fxn1\n    fpxn = fs(xn,1)\n\n    if isissue(fpxn)\n        o.stopped=true\n        return\n    end\n    \n    xn1 = xn - fxn / fpxn\n    fxn1 = fs(xn1)\n    incfn(o)\n    \n    o.xn0, o.xn1 = xn, xn1\n    o.fxn0, o.fxn1 = fxn, fxn1\n\n\n\n\nend\n\n\"\"\"\n    newton(f, fp, x0; kwargs...)\n    \nImplementation of Newton's method: `x_n1 = x_n - f(x_n)/ f'(x_n)`\n\nArguments:\n\n* `f::Function` -- function to find zero of\n\n* `fp::Function` -- the derivative of `f`. \n\n* `x0::Number` -- initial guess. For Newton's method this may be complex.\n\nWith the `FowardDiff` package derivatives may be computed automatically. For example,  defining\n`D(f) = x -> ForwardDiff.derivative(f, float(x))` allows `D(f)` to be used for the first derivative.\n\nKeyword arguments are passed to `find_zero` using the `Roots.Newton()` method.\n\n\"\"\"\nnewton(f, fp, x0; kwargs...) = find_zero((f, fp), x0, Newton(); kwargs...)\n@deprecate newton(f, x0; kwargs...)  newton(f, fp, x0; kwargs...)\n\n\n## Halley\n\n\n\"\"\"\n    Roots.Halley()\n\nImplements Halley's [method](http://tinyurl.com/yd83eytb),\n`x_n1 = xn - (2 f(xn)*f'(xn)) / (2 f'(xn)^2 - f(xn) * f''(xn))`.\nThis method is cubically converging, but requires more function calls per step (3) than\nother methods.\n\"\"\"    \nstruct Halley <: AbstractUnivariateZeroMethod\nend\n\n\nfunction update_state(method::Halley, fs, o::UnivariateZeroState{T,S}, options::UnivariateZeroOptions) where {T,S}\n    xn = o.xn1\n    fxn = o.fxn1\n    fpxn = fs(xn,1); incfn(o)\n    fppxn = fs(xn,2); incfn(o)\n    \n    xn1 = xn - 2fxn*fpxn / (2*fpxn*fpxn - fxn * fppxn)\n    fxn1 = fs(xn1); incfn(o)\n\n    o.xn0, o.xn1 = xn, xn1\n    o.fxn0, o.fxn1 = fxn, fxn1\nend\n\n\"\"\"\n    halley(f, fp, fpp, x0; kwargs...)\n    \nImplementation of Halley's method. `xn1 = xn - 2f(xn)*f'(xn) / (2*f'(xn)^2 - f(xn) * f''(xn))`\n    \nArguments:\n\n* `f::Function` -- function to find zero of\n\n* `fp::Function` -- derivative of `f`.\n\n* `fpp:Function` -- second derivative of `f`.\n\n* `x0::Number` -- initial guess\n\nWith the `FowardDiff` package derivatives may be computed automatically. For example,  defining\n`D(f) = x -> ForwardDiff.derivative(f, float(x))` allows `D(f)` and `D(D(f))` to be used for the first and second\nderivatives, respectively.\n\nKeyword arguments are passed to `find_zero` using the `Roots.Halley()` method.\n\n\n\"\"\"\nhalley(f, fp, fpp, x0; kwargs...) = find_zero((f, fp, fpp), x0, Halley(); kwargs...)\n#halley(f,  x0; kwargs...) = find_zero(f, x0, Halley(); kwargs...) # deprecated\n#halley(f, fp, x0; kwargs...) = find_zero((f, fp), x0, Halley(); kwargs...) # deprecated\n@deprecate halley(f,  x0; kwargs...)    halley(f, fp, fpp, x0; kwargs...)\n@deprecate halley(f, fp, x0; kwargs...) halley(f, fp, fpp, x0; kwargs...)\n", "meta": {"hexsha": "6cf11d4e88cd04fdf1968d34a68e627127af6603", "size": 3229, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/newton.jl", "max_stars_repo_name": "ksmcreynolds/Roots.jl", "max_stars_repo_head_hexsha": "022de5dcc477c17ceeb28e4db400f35cf58859bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/newton.jl", "max_issues_repo_name": "ksmcreynolds/Roots.jl", "max_issues_repo_head_hexsha": "022de5dcc477c17ceeb28e4db400f35cf58859bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/newton.jl", "max_forks_repo_name": "ksmcreynolds/Roots.jl", "max_forks_repo_head_hexsha": "022de5dcc477c17ceeb28e4db400f35cf58859bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1344537815, "max_line_length": 114, "alphanum_fraction": 0.6286776092, "num_tokens": 1050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582477806521, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7773825460771026}}
{"text": "\n\nfunction plot_country_posterior(chains, grouped_dat, country; tspan = [0.0, 365.0], subsample_size=100)\n\n    country_pop = grouped_dat[country].pop[1]\n    country_name = grouped_dat[country].Country_Region[1]\n\n    post_dat = DataFrame(chains);\n\n    init = [(country_pop - 100.0) / country_pop, 100.0 / country_pop, 0.0]\n    country_param_cols = [Symbol(\"β[\" * string(country) * \"]\"), Symbol(\"γ[\" * string(country) * \"]\")]\n\n    posterior_mean_params = mean.(eachcol(post_dat[:, country_param_cols]))\n    posterior_mean_prob = ODEProblem(sir_ode, init, tspan, posterior_mean_params)\n    posterior_mean_sol = solve(posterior_mean_prob);\n\n    # plt = plot(posterior_mean_sol;\n    #     title = country_name * \"\\n\",\n    #     title_location = :left,\n    #     top_margin = 5mm,\n    #     vars = [1],\n    #     xguidefontsize = 10, yguidefontsize = 10,\n    #     xlabel = \"Days since 100 confirmed cases\",\n    #     ylabel = \"Proportion of population\",\n    #     label = \"S\",\n    #     color = \"blue\",\n    #     linewidth = 2,\n    #     legend = :outerright)\n    plt = plot(posterior_mean_sol;\n        title = country_name * \"\\n\",\n        title_location = :left,\n        top_margin = 5mm,\n        vars = [2],\n        xguidefontsize = 10, yguidefontsize = 10,\n        xlabel = \"Days since 100 confirmed cases\",\n        ylabel = \"Proportion of population\",\n        label = \"I\",\n        color = \"red\",\n        linewidth = 2,\n        legend = :outerright)\n    # plot!(posterior_mean_sol; label=\"I\", vars = [2], color = \"red\", linewidth = 2)\n    plot!(posterior_mean_sol; label=\"R\", vars = [3], color = \"green\", linewidth = 2)\n\n    # scatter!(grouped_dat[country].susc_prop, color = \"blue\", label = \"Obs. S\", markerstrokewidth = 0)\n    scatter!(grouped_dat[country].case_prop, color = \"red\", label = \"Obs. I\", markerstrokewidth = 0)\n    scatter!(grouped_dat[country].recov_prop, color = \"green\", label = \"Obs. R\", markerstrokewidth = 0)\n\n    # subsample to avoid a crowded plot\n    sub_idx = sample(axes(post_dat, 1), subsample_size; replace = false);\n    for i in sub_idx\n        prob = ODEProblem(sir_ode, init, tspan, post_dat[i, country_param_cols])\n        sol = solve(prob);\n        # plot!(sol; vars = [1], label=\"\", color = \"blue\", alpha = 0.1, xlabel = \"Days since 100 confirmed cases\")\n        plot!(sol; vars = [2], label=\"\", color = \"red\", alpha = 0.1, xlabel = \"Days since 100 confirmed cases\")\n        plot!(sol; vars = [3], label=\"\", color = \"green\", alpha = 0.1, xlabel = \"Days since 100 confirmed cases\")\n    end\n\n    return plt\nend", "meta": {"hexsha": "26e184dda5f0b7a0c5cf91daa8fae20fd4e52926", "size": 2540, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "bayesian_nlde/src/criticism.jl", "max_stars_repo_name": "v-a-s-a/bayesian_sir", "max_stars_repo_head_hexsha": "1d4a0e2e37b3daeea025b847e28301204cdf306d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-05-29T19:23:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-18T19:39:27.000Z", "max_issues_repo_path": "bayesian_nlde/src/criticism.jl", "max_issues_repo_name": "v-a-s-a/bayesian_sir", "max_issues_repo_head_hexsha": "1d4a0e2e37b3daeea025b847e28301204cdf306d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bayesian_nlde/src/criticism.jl", "max_forks_repo_name": "v-a-s-a/bayesian_sir", "max_forks_repo_head_hexsha": "1d4a0e2e37b3daeea025b847e28301204cdf306d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-11T19:16:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-11T19:16:01.000Z", "avg_line_length": 43.0508474576, "max_line_length": 114, "alphanum_fraction": 0.6157480315, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7773525449367498}}
{"text": "# The normal fit api in Distributions.jl is:\n#   fit(Distr, values)\n# so we want to do a more general\n#   fitall(values)\n# that will try all distributions that can be fitted and return back the \"best\" one\n# for relevant criteria of \"best\", typically BIC or AIC.\n\nusing Distributions\n\nAllContinuousDistributions = [\n    Arcsine, Beta, BetaPrime, Cauchy, Chi, Chisq, Erlang, Exponential,\n    FDist, Frechet, Gamma, GeneralizedExtremeValue, GeneralizedPareto,\n    Gumbel, InverseGamma, InverseGaussian, Laplace, Levy, LogNormal,\n    Logistic, Normal, NormalInverseGaussian, Pareto, Rayleigh, \n    SymTriangularDist, TDist, TriangularDist, Uniform, VonMises, Weibull\n]\n\nsamples1 = rand(Normal(3.4, 1.2), 100)\n\nContinuousDistributionsThatCanFit = filter(AllContinuousDistributions) do D\n    try\n        fit_mle(D, samples1)\n        true\n    catch _err\n        false\n    end\nend\n\n# Start for continuous distributions\nfunction fitalldistr{T<:Real}(x::AbstractArray{T}, sortby = :BIC)\n    n = length(x)\n    allfits = map(ContinuousDistributionsThatCanFit) do D\n        d = fit_mle(D, x)\n        loglik = loglikelihood(d, x)\n        k = length(params(d))\n        if sortby == :BIC\n            criteria = -2 * loglik + k * log(n)\n        elseif sortby == :AIC\n            criteria = -2 * loglik + 2 * k\n        elseif sortby == :AICc\n            criteria = -2 * loglik + 2 * k + ((2*k*(k+1))/(n-k-1))\n        elseif sortby == :NLogL\n            criteria = -loglik\n        end\n        (d, criteria)\n    end\n    sort(allfits, by = t -> t[2])\nend\n\nfunction fitall{T<:Real}(x::AbstractArray{T}, sortby = :BIC)\n    fitalldistr(x, sortby)[1][1]\nend\n\nsamples1 = rand(Normal(3.4, 1.2), 100)\nd1 = fitall(samples1)\n\nsamples2 = rand(Exponential(0.3), 100)\nd2 = fitall(samples2)\n\nsamples3 = rand(LogNormal(-5.0, 2.0), 100)\nd3s = fitalldistr(samples3)\nd3 = fitall(samples3)\n\nsamples4 = rand(Gamma(6.20, 1.3), 200)\nd4s = fitalldistr(samples4)\nd4 = fitall(samples4)\n\n# Should we maybe use a non-parametric test to select between them?", "meta": {"hexsha": "cfb2e123b50140fcb905a31ee172a16f38987edd", "size": 2009, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "spikes/fitalldistr/fitalldistr.jl", "max_stars_repo_name": "robertfeldt/FeldtLib.jl", "max_stars_repo_head_hexsha": "8b7fd87097a77a0a1f4a2f2b4d89938572ed7243", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spikes/fitalldistr/fitalldistr.jl", "max_issues_repo_name": "robertfeldt/FeldtLib.jl", "max_issues_repo_head_hexsha": "8b7fd87097a77a0a1f4a2f2b4d89938572ed7243", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spikes/fitalldistr/fitalldistr.jl", "max_forks_repo_name": "robertfeldt/FeldtLib.jl", "max_forks_repo_head_hexsha": "8b7fd87097a77a0a1f4a2f2b4d89938572ed7243", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-04-18T18:30:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:14:25.000Z", "avg_line_length": 29.5441176471, "max_line_length": 83, "alphanum_fraction": 0.656047785, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7773525446230641}}
{"text": "function mirror(A,d::Int=3)\n    w = div(d-1,2) #width of window, d is an ODD integer\n    mA = [A[(w+1):-1:2];A;A[lastindex(A)-1:-1:(length(A)-w)]]\nend\n\nfunction find_extrema(A::Array,d::Int=3)\n    mA = mirror(A)\n    count = 0\n    maxs = Int[]\n    mins = Int[]\n    exts = Int[]\n    for i in 1:lastindex(mA)-d+1\n        win = view(mA,i:i+d-1)\n        if (win[2] > win[1] && win[2] > win[3])\n                count+=1\n                push!(maxs,i)\n                push!(exts,i)\n        elseif (win[2] < win[1] && win[2] < win[3])\n                count+=1\n                push!(mins,i)\n                push!(exts,i)\n        end\n    end\n    maxs, mins,exts\nend\n\nfunction find_extrema_count(A::Array,d::Int=3)\n    dd = diff(sign.(diff(A)))\n    return length(dd[dd .!= 0]) + 2\nend\n\nfunction find_extrema_minmax(A::Array,d::Int=3)\n    dd = diff(sign.(diff(A)))\n    return findall(dd .< 0), findall(dd .> 0)\nend\n\nfunction stream_minmax(env1, env2, A, d::Int)\n    a = mirror(A, d)\n    N = length(a)\n    upper = UInt32[] #buffer for indices\n    lower = UInt32[]\n    push!(upper,1)\n    push!(lower,1)\n    w = d\n    for i in 2:lastindex(a)\n        if i >= w\n            env1[i-w+1] = a[upper[1]]\n            env2[i-w+1] = a[lower[1]]\n        end\n\n        if a[i] > a[i-1]\n            pop!(upper)\n            # remove maxima from buffer that are less than our new one\n            while isempty(upper) != true\n                if a[i] <= a[upper[end]]\n                    break\n                end\n                pop!(upper)\n            end\n        else\n            pop!(lower)\n            # remove minima from buffer that are greater than our new one\n            while isempty(lower) != true\n                if a[i] >= a[lower[end]]\n                    break\n                end\n                pop!(lower)\n            end\n        end\n        push!(upper,i)\n        push!(lower,i)\n        if i == w + upper[1]\n            popfirst!(upper)\n        elseif i == w + lower[1]\n            popfirst!(lower)\n        end\n        env1[end-w] = a[upper[1]]\n        env2[end-w] = a[lower[1]]\n    end\n    return nothing\nend\n\nfunction moving_average(A, d::Int=3)\n    A = mirror(A,d)\n    T = typeof(one(eltype(A))/1)\n    ret = Vector{T}(undef, length(A) - d + 1)\n    id = 1 / d\n    s = sum(view(A, 1:d))\n    ret[1] = s * id\n    @inbounds for n = 1:length(ret)-1\n        s += A[n+d] - A[n]\n        ret[n+1] = s * id\n    end\n    return ret\nend\n", "meta": {"hexsha": "76666753dd4ff29fad140d4b545d1e1ae4bb2fe7", "size": 2413, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "jarrison/EMD.jl", "max_stars_repo_head_hexsha": "b6c6e07602f84f010fd0745ab1a4ada62fe28fd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-02-27T04:04:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-04T09:20:58.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "jarrison/sEMD.jl", "max_issues_repo_head_hexsha": "b6c6e07602f84f010fd0745ab1a4ada62fe28fd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "jarrison/sEMD.jl", "max_forks_repo_head_hexsha": "b6c6e07602f84f010fd0745ab1a4ada62fe28fd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1354166667, "max_line_length": 73, "alphanum_fraction": 0.4641525073, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7773525429081659}}
{"text": "function ^(a::STaylor1{N,T}, n::Integer) where {N,T<:Real}\r\n    n == 0 && return one(a)\r\n    n == 1 && return a\r\n    n == 2 && return square(a)\r\n    n < 0 && return a^float(n)\r\n    return power_by_squaring(a, n)\r\nend\r\n\r\n^(a::STaylor1{N,T}, b::STaylor1{N,T}) where {N,T<:Number} = exp(b*log(a))\r\n\r\nfunction power_by_squaring(x::STaylor1{N,T}, p::Integer) where {N,T<:Number}\r\n    p == 1 && return x\r\n    p == 0 && return one(x)\r\n    p == 2 && return square(x)\r\n    t = trailing_zeros(p) + 1\r\n    p >>= t\r\n\r\n    while (t -= 1) > 0\r\n        x = square(x)\r\n    end\r\n\r\n    y = x\r\n    while p > 0\r\n        t = trailing_zeros(p) + 1\r\n        p >>= t\r\n        while (t -= 1) ≥ 0\r\n            x = square(x)\r\n        end\r\n        y *= x\r\n    end\r\n\r\n    return y\r\nend\r\n\r\n@generated function ^(a::STaylor1{N,T}, r::S) where {N, T<:Number, S<:Real}\r\n\r\n    ex_calc = quote end\r\n    append!(ex_calc.args, Any[nothing for i in 1:N])\r\n    syms = Symbol[Symbol(\"c$i\") for i in 1:N]\r\n    ctuple = Expr(:tuple)\r\n    for i = 1:N\r\n        push!(ctuple.args, syms[i])\r\n    end\r\n\r\n    for i = 1:N\r\n        push!(ex_calc.args, :($(syms[i]) = zero(T)))\r\n    end\r\n\r\n    expr_quote = quote\r\n        iszero(r) && return one(a)\r\n        r == 1 && return a\r\n        r == 2 && return square(a)\r\n        r == 1/2 && return sqrt(a)\r\n        $ex_calc\r\n    end\r\n\r\n    c = STaylor1(zero(T), Val{N}())\r\n    for k = 0:(N - 1)\r\n        symk = syms[k + 1]\r\n        temp_quote = quote\r\n            # First non-zero coefficient\r\n            l0 = findfirst(a)\r\n            if l0 < 0\r\n                $symk = zero(T)\r\n            else\r\n                # The first non-zero coefficient of the result; must be integer\r\n                !isinteger(r*l0) && throw(ArgumentError(\r\n                    \"\"\"The 0th order Taylor1 coefficient must be non-zero\r\n                    to raise the Taylor1 polynomial to a non-integer exponent.\"\"\"))\r\n                lnull = trunc(Int, r*l0)\r\n                kprime = $k - lnull\r\n                if (kprime < 0) || (lnull > N-1)\r\n                    $symk = zero(T)\r\n                else\r\n                    # Relevant for positive integer r, to avoid round-off errors\r\n                    if isinteger(r) && ($k > r*findlast(a))\r\n                        $symk = zero(T)\r\n                    else\r\n                        if $k == lnull\r\n                            $symk = a[l0]^r\r\n                        else\r\n                            # The recursion formula\r\n                            if l0 + kprime ≤ (N - 1)\r\n                                tup_in = $ctuple\r\n                                $symk = r*kprime*tup_sel(lnull, tup_in)*a[l0 + kprime]\r\n                            else\r\n                                $symk = zero(T)\r\n                            end\r\n                            for i = 1:($k - lnull - 1)\r\n                                if !((i + lnull) > (N - 1) || (l0 + kprime - i > (N - 1)))\r\n                                    aux = r*(kprime - i) - i\r\n                                    tup_in = $ctuple\r\n                                    $symk += aux*tup_sel(i + lnull, tup_in)*a[l0 + kprime - i]\r\n                                end\r\n                            end\r\n                            $symk /= kprime*a[l0]\r\n                        end\r\n                    end\r\n                end\r\n            end\r\n        end\r\n        one_tup = ntuple(i -> i == 1 ? one(T) : zero(T), Val{N}())\r\n        expr_quote = quote\r\n            $expr_quote\r\n            if r == 0\r\n                $ctuple = $one_tup\r\n            elseif r == 1 # DO NOTHING\r\n            elseif r == 2\r\n                temp_st1 = square(STaylor1{N,T}($ctuple))\r\n            elseif r == 0.5\r\n                temp_st2 = sqrt(STaylor1{N,T}($ctuple))\r\n            else\r\n                $temp_quote\r\n            end\r\n        end\r\n    end\r\n\r\n    exout = :(($(syms[1]),))\r\n    for i = 2:N\r\n        push!(exout.args, syms[i])\r\n    end\r\n\r\n    return quote\r\n               Base.@_inline_meta\r\n               $expr_quote\r\n               return STaylor1{N,T}($exout)\r\n            end\r\nend\r\n\r\n@generated function square(a::STaylor1{N,T}) where {N, T<:Number}\r\n    ex_calc = quote end\r\n    append!(ex_calc.args, Any[nothing for i in 1:N])\r\n    syms = Symbol[Symbol(\"c$i\") for i in 1:N]\r\n\r\n    sym = syms[1]\r\n    ex_line = :($(syms[1]) = a[0]^2)\r\n    ex_calc.args[1] = ex_line\r\n\r\n    for k in 1:(N-1)\r\n        kodd = k%2\r\n        kend = div(k - 2 + kodd, 2)\r\n        ex_line = :(a[0] * a[$k])\r\n        @inbounds for i = 1:kend\r\n            ex_line = :($ex_line + a[$i] * a[$(k-i)])\r\n        end\r\n        ex_line = :(2.0*($ex_line)) # float(2)* TODO: ADD BACK IN\r\n        if kodd !== 1\r\n            ex_line = :($ex_line +a[$(div(k,2))]^2)\r\n        end\r\n        ex_line = :($(syms[k+1]) = $ex_line)\r\n        ex_calc.args[k+1] = ex_line\r\n    end\r\n\r\n    exout = :(($(syms[1]),))\r\n    for i = 2:N\r\n        push!(exout.args, syms[i])\r\n    end\r\n    return quote\r\n               Base.@_inline_meta\r\n               $ex_calc\r\n               return STaylor1{N,T}($exout)\r\n            end\r\nend\r\n\r\n@generated function inverse(a::STaylor1{N,T}) where {N,T<:Real}\r\n    ex_calc = quote end\r\n    append!(ex_calc.args, Any[nothing for i in 1:(2*N)])\r\n    syms = Symbol[Symbol(\"c$i\") for i in 1:N]\r\n\r\n    exout = :(($(syms[1]),))\r\n    for i = 2:N\r\n        push!(exout.args, syms[i])\r\n    end\r\n\r\n    count = 1\r\n    for n = 1:(N - 1)\r\n        ex_calc.args[2*count - 1] = :(syms[n + 1] = zdivfpown[n - 1]/n)\r\n        ex_calc.args[2*count] = :(zdivfpown *= zdivf)\r\n        count += 1\r\n    end\r\n\r\n    return quote\r\n               Base.@_inline_meta\r\n               if a[0] != zero(T)\r\n                   throw(ArgumentError(\r\n                   \"\"\"\r\n                   Evaluation of Taylor1 series at 0 is non-zero. For high accuracy, revert\r\n                   a Taylor1 series with first coefficient 0 and re-expand about f(0).\r\n                   \"\"\"))\r\n               end\r\n               z = copy(a)\r\n               zdivf = z/a\r\n               zdivfpown = zdivf\r\n               S = eltype(zdivf)\r\n               $ex_calc\r\n               return STaylor1{N,T}($exout)\r\n            end\r\nend\r\n\r\nfunction tup_sel(i, vargs)\r\n    return vargs[i+1]\r\nend\r\n\r\n@generated function sqrt(a::STaylor1{N,T}) where {N,T<:Number}\r\n\r\n    ex_calc = quote end\r\n    append!(ex_calc.args, Any[nothing for i in 1:N])\r\n    syms = Symbol[Symbol(\"c$i\") for i in 1:N]\r\n    ctuple = Expr(:tuple)\r\n    for i = 1:N\r\n        push!(ctuple.args, syms[i])\r\n    end\r\n\r\n    # First non-zero coefficient\r\n    expr_quote = quote\r\n        l0nz = findfirst(a)\r\n        aux = zero(T)\r\n        if l0nz < 0\r\n            return zero(STaylor1{N,T})\r\n        elseif l0nz%2 == 1 # l0nz must be pair\r\n            throw(ArgumentError(\r\n            \"\"\"First non-vanishing Taylor1 coefficient must correspond\r\n            to an **even power** in order to expand `sqrt` around 0.\"\"\"))\r\n        end\r\n\r\n        # The last l0nz coefficients are set to zero.\r\n        lnull = div(l0nz, 2)\r\n    end\r\n\r\n    for i = 1:N\r\n        push!(ex_calc.args, :($(syms[i]) = zero(T)))\r\n    end\r\n\r\n\r\n    for i = 1:N\r\n        switch_expr = :((lnull == $(i-1)) && ($(syms[i]) = sqrt(a[l0nz])))\r\n        expr_quote = quote\r\n            $expr_quote\r\n            $switch_expr\r\n        end\r\n    end\r\n\r\n    for k = 0:(N - 1)\r\n        symk = syms[k + 1]\r\n        temp_expr = quote\r\n            if $k >= lnull + 1\r\n                if $k == lnull\r\n                    $symk = sqrt(a[2*lnull])\r\n                else\r\n                    kodd = ($k - lnull)%2\r\n                    kend = div($k - lnull - 2 + kodd, 2)\r\n                    imax = min(lnull + kend, N - 1)\r\n                    imin = max(lnull + 1, $k + lnull - (N - 1))\r\n                    if imin ≤ imax\r\n                        tup_in = $ctuple\r\n                        $symk = tup_sel(imin, tup_in)*tup_sel($k + lnull - imin, tup_in)\r\n                    end\r\n                    for i = (imin + 1):imax\r\n                        tup_in = $ctuple\r\n                        $symk += tup_sel(i, tup_in)*tup_sel($k + lnull - i, tup_in)\r\n                    end\r\n                    if $k + lnull ≤ (N - 1)\r\n                        aux = a[$k + lnull] - 2*$symk\r\n                    else\r\n                        aux = -2*$symk\r\n                    end\r\n                    tup_in = $ctuple\r\n                    if kodd == 0\r\n                        aux -= tup_sel(kend + lnull + 1, tup_in)^2\r\n                    end\r\n                    $symk = aux/(2*tup_sel(lnull, tup_in))\r\n                end\r\n            end\r\n        end\r\n        expr_quote = quote\r\n            $expr_quote\r\n            $temp_expr\r\n        end\r\n    end\r\n\r\n    exout = :(($(syms[1]),))\r\n    for i = 2:N\r\n        push!(exout.args, syms[i])\r\n    end\r\n    return quote\r\n               Base.@_inline_meta\r\n               $ex_calc\r\n               $expr_quote\r\n               return STaylor1{N,T}($exout)\r\n            end\r\nend\r\n", "meta": {"hexsha": "9add5f4f06ca7eb8f6eae43cf647440fe9274f9c", "size": 8935, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/power.jl", "max_stars_repo_name": "mewilhel/StaticTaylorSeries.jl", "max_stars_repo_head_hexsha": "962b75010152ce076e8f5831279edc783a5a8361", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-16T17:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-16T17:24:12.000Z", "max_issues_repo_path": "src/power.jl", "max_issues_repo_name": "mewilhel/StaticTaylorSeries.jl", "max_issues_repo_head_hexsha": "962b75010152ce076e8f5831279edc783a5a8361", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-10-09T18:35:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T23:09:28.000Z", "max_forks_repo_path": "src/power.jl", "max_forks_repo_name": "mewilhel/StaticTaylorSeries.jl", "max_forks_repo_head_hexsha": "962b75010152ce076e8f5831279edc783a5a8361", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-29T06:24:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-29T06:24:55.000Z", "avg_line_length": 30.5993150685, "max_line_length": 95, "alphanum_fraction": 0.4086177952, "num_tokens": 2507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7773525377634715}}
{"text": "# This file includes IFS tools.\nusing LinearAlgebra\nusing StatsBase\n\nexport IFS, attractor, DetAlg, RandAlg, dimension, contfactor, Sierpinski, Fern, Square, Tree\n\nexport w, Transformation, randalg_sequential_for_generator, randalg_sequential_generator\n\n\"\"\" \n    $(TYPEDEF) \nAffine transformation \n\n# Fields \n    $(TYPEDFIELDS)\n\"\"\"\nstruct Transformation{T1<:AbstractMatrix{<:Real}, T2<:AbstractVector{<:Real}}\n    \"Transformation matrix\"\n    A::T1 \n    \"Transformation vector\"\n    b::T2 \nend \n\n(w::Transformation)(x) = w.A * x + w.b\n\n\"\"\"\n    $SIGNATURES \n\nReturns dimension of `w`.\n\"\"\"\ndimension(w::Transformation) = size(w.A,1)\n\n\"\"\"\n    $SIGNATURES \n\nReturns contraction factor of `w`. Contraction factor is computed as the norm of `w.A`.\n\"\"\"\ncontfactor(w::Transformation) = norm(w.A)\n\n\n\"\"\" \n    $(TYPEDEF) \n\nIterated fucntion sytem (IFS) \n\n# Fields \n\n    $(TYPEDFIELDS)\n\"\"\"\nstruct IFS{T1<:AbstractVector{<:Transformation}, T2<:AbstractVector{<:Real},T3}\n    \"Vector of transformations of IFS\"\n    ws::T1 \n    \"Vector of probabilities of IFS\"\n    probs::T2\n    \"generator of the ifs\"\n    generator::T3\nend\n\nfunction IFS(ws::T1, probs::T2, args...) where {T1, T2} \n    # Note: For the floating point numbers, aproximation(≈), instead of exact equal (==), should be considered\n    sum(probs) ≈ 1 || throw(ArgumentError(\"Sum of probabilities must be 1.\"))\n    generator = randalg_sequential_generator(ws, probs, args...)\n    IFS{T1, T2, typeof(generator)}(ws, probs, generator)\nend\nIFS(ws,args...) = (n = length(ws); IFS(ws, 1  / n * ones(n), args...))\n\n\"\"\" \n    $SIGNATURES\n\nConctructs an IFS for Sierpinski triangle.\n\"\"\"\nSierpinski() = IFS([\n    Transformation([0.5 0.0; 0. 0.5], [0; 0]),\n    Transformation([0.5 0.0; 0. 0.5], [0; 1/2.]),\n    Transformation([0.5 0.0; 0. 0.5], [1/2.; 1/2.])\n    ], [1/3., 1/3., 1/3.])\n\n\"\"\"\n    $SIGNATURES\n\nConstructs and IFS for a sqaure.\n\"\"\"\nSquare() = IFS([\n    Transformation([0.5 0.0; 0. 0.5], [1.; 1.]),\n    Transformation([0.5 0.0; 0. 0.5], [50.; 1.]),\n    Transformation([0.5 0.0; 0. 0.5], [1.; 50.]),\n    Transformation([0.5 0.0; 0. 0.5], [50.; 50.])\n    ], [0.25, 0.25, 0.25, 0.25])\n\n\"\"\"\n    $SIGNATURES\n\nConstructs and IFS for a fern.\n\"\"\"\nFern() = IFS([\n    Transformation([0 0; 0 0.16], [0.; 0.]),\n    Transformation([0.85 0.04; -0.04 0.85],[0.; 1.6]),\n    Transformation([0.2 -0.26; 0.23 0.22], [0.; 1.6]),\n    Transformation([-0.15 0.28; 0.26 0.24], [0.; 0.44])\n    ], [0.01, 0.85, 0.07, 0.07])\n\n\"\"\"\n    $SIGNATURES\n\nConstructs and IFS for a fractal tree.\n\"\"\"\nTree() = IFS([\n    Transformation([0 0; 0 0.5], [0.; 0.]),\n    Transformation([0.42 -0.42; 0.42 0.42], [0.; 0.2]),\n    Transformation([0.42 0.42; -0.42 0.42], [0.; 0.2]),\n    Transformation([0.1 0; 0 0.1], [0.; 0.2])\n    ], [0.05, 0.40, 0.40, 0.15])\n\n\"\"\"\n    $SIGNATURES\n\nReturns dimension of `ifs`.\n\"\"\"\ndimension(ifs::IFS) = dimension(ifs.ws[1])\n\n\"\"\"\n    $SIGNATURES\n\nReturns the contraction factor of `IFS`.\n\"\"\"\ncontfactor(ifs::IFS) = maximum(contfactor.(ifs.ws))\n\n\"\"\"\n    $TYPEDEF\n\nA type signifying that deterministic algorithm is used when calculating the attractor of and IFS.\n\"\"\"\nstruct DetAlg end\n\n\"\"\"\n    $TYPEDEF\n\nA type signifying that random algorithm is used when calculating the attractor of and IFS.\n\"\"\"\nstruct RandAlg end\n\n\"\"\"\n    $TYPEDEF\n\nAttractor of `IFS` type \n\n# Fields\n\n    $TYPEDFIELDS\n\"\"\"\nstruct Attractor{T, S, R1, R2}\n    \"IFS of Attractor\"\n    ifs::T\n    \"Type of algorithm to be used to compute attractor(Options are DetAlg and RandAlg\"\n    alg::S\n    \"Initial set of attractor\"\n    initset::R1\n    \"Set of the attractor\"\n    set::R2\n    \"Number of iterations\"\n    numiter::Int\n    \"Sequential or parallel\"\n    parallel::Bool\nend\n\n\"\"\"\n    $SIGNATURES\n\nComputes the attractor of `ifs`. If `alg` is of type `DetAlg`, the deterministic algorithm is used. If `alg` is of type\n`RandAlg`, random algorithm is used. `kwargs` may include\n\n* `numiter::Int` : Number of iterations to used to calcuate the attractor (defaults to 10)\n\n* `numtransient::Int` : Number of transient iterations to used to calcuate a transient set. When the transient set is\n  constructed, the computation of attractor is continued with distributed computation if `alg` is `RandAlg` and `parallel` is\n  `true`. (defaults to 10)\n\n* `parallel::Bool`: If  `true`, the attractor is computed using distrbuted computation. (defaults to false)\n\n* `placedependent::Bool` : If `true`, place dependent attractor is computed if α and β is given accordingly. (default to\n  false)\n\n* `α::AbstractVector` : Place-dependent probility coefficient(defaults to nothing)\n\n* `β::AbstractVector` : Place-dependent probility coefficient. (default to nothing)\n\"\"\"\nattractor(ifs, initset; alg=DetAlg(), kwargs...) = typeof(alg) == DetAlg ? \n                                                   detalg(ifs,initset; kwargs...) : \n                                                   randalg(ifs,initset; kwargs...)\n\n\"\"\"\n    $SIGNATURES\n\nComputes the attractor of `ifs` with deterministic algorithm.`numiter` is number of iterations. (Defaults to 10). If\n`parallel` is true, attractor is computed via parallel computation.\n\"\"\"\nfunction detalg(ifs, initset; numiter=10, parallel=false)\n    copiedset = copy(initset)\n    set = parallel ? \n          detalg_parallel(ifs.ws, copiedset, numiter) : \n          detalg_sequential(ifs.ws, copiedset, numiter)\n    Attractor(ifs, DetAlg(), initset, set, numiter, parallel)\nend\n\n# Computes the attractor of an ifs via deterministic algorithm sequentially. \nfunction detalg_sequential(ws, set, numiter)\n    for i in 1 : numiter\n        set = vcat(map(w -> w.(set), ws)...)\n    end\n    set\nend\n\n# Computes the attractor of an ifs via deterministic algorithm in parallel. \nfunction detalg_parallel(ws, set, numiter)\n    loadprocs()\n    for i in 1 : numiter\n        set = vcat(map(w -> pmap(w, set), ws)...)\n    end\n    set\nend\n\n\"\"\"\n    $SIGNATURES\n\nComputes the attractor of `ifs` with random algorithm.`numiter` is number of iterations. (Defaults to 100). `numtransient` is\nthe number of transient iterations. If `parallel` is true, attractor is computed via parallel computation. If\n`placedependent` is true, the probabilties of the ifs are dependent on the coordinates `x`. This dependency `p(x)` is given\nvia the parameters `α` and `β` where p(x) = α x + β.\n\"\"\"\nfunction randalg(ifs, initset; numiter=100, numtransient=10, parallel=false, placedependent=false, α=nothing, β=nothing, allocated::Bool=false)\n    ws = ifs.ws\n    probs = ifs.probs\n    if parallel\n        if placedependent\n            transient = randalg_sequential_pd(ws, copy(initset), numtransient, probs, α, β, allocated)\n            set = randalg_parallel_pd(ws, transient, numiter, probs, α, β, allocated)\n        else\n            transient = randalg_sequential(ws, copy(initset), numtransient, probs, allocated)\n            set = randalg_parallel(ws, transient, numiter, probs, allocated)\n        end\n    else\n        if placedependent\n            set = randalg_sequential_pd(ws, copy(initset), numiter, probs, α, β, allocated)\n        else\n            set = randalg_sequential(ws, copy(initset), numiter, probs, allocated)\n        end\n    end\n    Attractor(ifs, RandAlg(), initset, set, numiter, parallel)\nend\n\n\n\nfunction _randalg_sequential(set::AbstractVector, ws, numiter, probs)\n    weights = Weights(probs)\n    xi = set[end]\n    for i = 1 : numiter\n        trfmi = sample(ws, weights)\n        xi = trfmi(xi)\n        push!(set, xi)\n    end\n    return set\nend\n\n\n\n# Computes the attractor of an ifs via random algorithm sequentially. \nfunction _randalg_sequential(ch::AbstractChannel, xinit, ws, numiter, probs)\n    weights = Weights(probs)\n    #TODO: Cancel the numiter, determine the post-error, K(contraction)\n    for i = 1 : numiter\n        trfmi = sample(ws, weights)\n        xnew = trfmi(xinit)\n        put!(ch, xnew)\n        xinit = xnew\n    end\n    ch\nend\n\nfunction randalg_sequential(ws, set, numiter, probs, allocated::Bool=false)\n    if allocated\n        _randalg_sequential(set, ws, numiter, probs)\n    else \n        # NOTE: The set is assumed to have just a single initial point. If the set consists of more element, then we need a fix.\n        ch = Channel(0)\n        task = @async _randalg_sequential(ch, only(set), ws, numiter, probs)\n        # task = @async _randalg_sequential(ch, ws, probs)\n        bind(ch, task)\n        ch\n    end \nend\n\nfunction _randalg_sequential_generator(ch::AbstractChannel, ws, probs, xinit=nothing; num_iter=nothing, chunk_size=10, ϵ = 1e-8)\n    # Compute initial set with a single point.\n    if xinit === nothing\n        n = size(ws[1].b)[1]\n        xinit = rand(n)       \n    else\n        n = size(xinit)[1]\n    end\n\n    # Compute number of iterations\n    σ, index = findmax(contfactor.(ws))\n    if num_iter === nothing\n        # Compute num_iter with respect to ϵ\n        x1 = ws[index](xinit)\n        _k = (log(ϵ) - log(norm(x1 - xinit))) / log(σ) + 1\n        k = Int(ceil(_k))\n    else\n        # Assign num_iter directly\n        k = num_iter\n    end\n\n    # Compute transients\n    weights = Weights(probs)\n    xnew = xinit\n    for i = 1 : k\n        trfmi = sample(ws, weights)\n        xnew = trfmi(xnew)\n    end\n\n    # Compute attractor\n    chunk = zeros(n, chunk_size) \n    while true\n        for i = 1 : chunk_size\n            trfmi = sample(ws, weights)\n            xnew = trfmi(xnew)\n            chunk[:,i] = xnew\n        end\n        put!(ch, chunk)\n    end\nend\n\nfunction randalg_sequential_generator(ws, probs, args...)\n    ch = Channel(0)\n    task = @async _randalg_sequential_generator(ch, ws, probs, args...)\n    bind(ch, task)\n    ch\nend\n\n#TODO: Cancel the numiter, determine the post-error, K(contraction), choose num_iter from consraction factor\n\n# function estimate_contraction_factor(ws)\n#     σ = zeros(lenght(ws))\n#     for i, transformation in ws\n#         σ[i] = norm(transformation.A, inf)\n#     end\n#     # TODO : Returns nothing\n#     σ\n# end\n\n\n# Computes the attractor of an ifs via random algorithm sequentially with placedependent probabilties.\nfunction randalg_sequential_pd(ws, set, numiter, probs, α, β, allocated::Bool=false)\n    # TODO: Impletement no allocation method \n    xi = set[end]\n    for i = 1 : numiter\n        trfmi = sample(ws, Weights(probs))\n        xi = trfmi(xi)\n        probs = α * xi + β\n    end\n    set\nend\n\n# Computes the attractor of an ifs via random algorithm in parallel. \nfunction randalg_parallel(ws, set, numiter, probs, allocated::Bool=false)\n    # TODO: Impletement no allocation method \n    weights = Weights(probs)\n    loadprocs()\n    vcat(pmap(process_chunk, [(ws, set, floor(Int, numiter / nworkers()), weights) for i =  1 : nworkers()])...)\nend\n\n# Computes the attractor of an ifs via random algorithm in parallel with placedependent probabilties.\nfunction randalg_parallel_pd(ws, set, numiter, probs, α, β)\n    loadprocs()\n    vcat(pmap(process_chunk_pd, [(ws, set, floor(Int, numiter / nworkers()), probs, α, β) for i =  1 : nworkers()])...)\nend\n\n# `process_chunk` is the worker function that is used in all processes(both in master and worker process). when calculating\n# the attractor if alg is `RandAlg` and `parallel` is true.\nfunction process_chunk(ws_set_niter_weights)\n    ws, set, niter, weights = ws_set_niter_weights\n    xi = set[end]\n    for i = 1 : niter\n        wi = sample(ws, weights)\n        xi = wi(xi)\n        push!(set, xi)\n    end\n    set\nend\n\n# `process_chunk` is the worker function that is used in all processes(both in master and worker process). when calculating\n# the attractor if alg is `RandAlg` and `parallel` is true with placedependent probabilties.\nfunction process_chunk_pd(ws_set_niter_probs_alpha_beta)\n    ws, set, niter, probs, α, β = ws_set_niter_probs_alpha_beta\n    xi = set[end]\n    for i = 1 : niter\n        wi = sample(ws, Weights(probs))\n        xi = wi(xi)\n        probs = α * xi + β\n        push!(set, xi)\n    end\n    set\nend\n\n# Load worker processes and load FractalTools to those worker processes.\nfunction loadprocs(numprocs=Base.Sys.CPU_THREADS - 1 - nprocs())\n    addprocs(numprocs)\n    @everywhere @eval using FractalTools\nend\n\n", "meta": {"hexsha": "31d4db5d4581ca25483db3df08f94a8676ccb799", "size": 12076, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ifs.jl", "max_stars_repo_name": "zekeriyasari/FractalTools.jl", "max_stars_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-08T12:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T12:50:16.000Z", "max_issues_repo_path": "src/ifs.jl", "max_issues_repo_name": "zekeriyasari/FractalTools.jl", "max_issues_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-09-05T18:22:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T10:09:46.000Z", "max_forks_repo_path": "src/ifs.jl", "max_forks_repo_name": "zekeriyasari/FractalTools.jl", "max_forks_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4536585366, "max_line_length": 143, "alphanum_fraction": 0.6470685658, "num_tokens": 3576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8824278618165526, "lm_q1q2_score": 0.7772398822142902}}
{"text": "#========================================================================================#\n#\tLaboratory 11\n#\n# Deterministic CHAOS and the course project.\n#\n# Author: Niall Palfreyman, 23/03/2022\n#========================================================================================#\n[\n\tActivity(\n\t\t\"\"\"\n\t\tThis is the last laboratory in this course, and it presents the assessed project for\n\t\tthe course. In this laboratory, you will implement a program to demonstrate chaos in a\n\t\tgravitational system containing three bodies of equal mass in two dimensions. You will use\n\t\tJulia to analyse the execution of a complex simulation program, and adapt this program to\n\t\tuse Runge-Kutta integration to (a) simulate 3-body motion and (b) evaluate its chaoticity.\n\t\tYou will present your methods and results in ONE deliverable: A complete Julia module with\n\t\tassociated demonstration code that presents a pedagogically pleasing description of the\n\t\tn-body problem, its solution using Runge-Kutta-2 integration and an analysis of the\n\t\tdynamics of your chosen system. This deliverable will also contain a title, information on\n\t\tauthors and references, and diagrams.\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> true\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tIn your project, you will investigate DETERMINISTIC CHAOS. Chaos is important for biology\n\t\tbecause it is the source of the spontaneity that we observe in living organisms. To see\n\t\thow chaos works, first define a Julia version of the Mathematica function nestlist():\n\n\t\t\tfunction nestlist( f::Function, x0, n::Integer)\n\t\t\t\t(n ≤ 0) ? [x0] : begin\n\t\t\t\t\tlist = Vector{typeof(x0)}(undef, n+1)\n\t\t\t\t\tlist[1] = x0\n\t\t\t\t\tfor i in 1:n\n\t\t\t\t\t\tlist[i+1] = f(list[i])\n\t\t\t\t\tend\n\t\t\t\t\tlist\n\t\t\t\tend\n\t\t\tend\n\t\t\n\t\tExperiment with nestlist(). For example, what is the result of the following invocation?\n\n\t\t\tnestlist(x->2x,3,5)\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x == [3,6,12,24,48,96]\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tnestlist() applies the function f repeatedly to the initial value x0, creating a list of\n\t\tthe values that it generates in this way. You can see how this might be useful if we want\n\t\tto create a simulation of timesteps that repeat themselves over time. We'll do that now ...\n\n\t\tImagine a population of wasps living on an island with renewable but limited resources.\n\t\tThey can fill the island's carrying capacity (population x = 1), they can die out (x = 0),\n\t\tor else their population can have any value in the range 0 ≤ x ≤ 1. Also, they all die each\n\t\twinter, so their population takes on a new value each year: [x0,x1,x2,...,xn].\n\t\t\n\t\tFor specific birthrate r, the wasp population's growth is governed by this logistic equation:\n\n\t\t\tx[i+1] = Λ(r)(x[i]), where\n\t\t\tΛ(r) is the function: (x -> r x (1-x))\n\n\t\tImplement this model now and experiment with it, then tell me the population two years\n\t\tafter an initial population of x0 = 0.3, if r = 0.5\n\t\t\"\"\",\n\t\t\"Λ(r) = (x -> r .* x .* (1 .- x))\",\n\t\tx -> (0.04698 < x < 0.04699)\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tUse nestlist() to create a list of 5 simulation steps of the wasp population, starting from\n\t\tan initial value of 0.3 and using specific growth rate r = 0.5. You will see that the\n\t\tpopulation x is tending towards a particular limiting value - what is that limit value?\n\t\t\"\"\",\n\t\t\"nestlist(Λ(1),0.3,5)\",\n\t\tx -> x==0\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tYou should now be able to do the following: Use nestlist() to create a list of 20\n\t\tsimulation steps of the wasp population with x0=0.3, r=0.9, then plot them in a graph.\n\t\tWhat is the limit point of this sequence?\n\t\t\"\"\",\n\t\t\"lines(nestlist(Λ(0.9),0.3,20))\",\n\t\tx -> x==0\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tOK, now we have the equipment, we can investigate the onset of chaos. We will slowly\n\t\tincrease the value of the specific birthrate r to discover how this affects the\n\t\tdevelopmental motion of the wasp population. Use the initial value x0=0.3 for all of the\n\t\tfolloiwng excercises until I tell you otherwise.\n\t\t\n\t\tJust to make our language clear: a LIMIT POINT of the wasp population's motion is any\n\t\tvalue of the population that stays the same from one generation to the next: Λ(r)(x) == x.\n\t\t\n\t\tWhat was the limit point of the motion Λ(0.9)?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==0\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWhat is the approximate value of the limit point of the motion Λ(1.1)?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> 0.07<x<0.1\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWhat is the EXACT value of the limit point of the motion Λ(1.5)?\n\t\t\"\"\",\n\t\t\"You can work it out for yourself by solving the equation Λ(r)(x) == x, or: r x (1-x) = x\",\n\t\tx -> x == 1//3\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tUse the technique from the hint in the previous activity to calculate the limit point of\n\t\tthe motion Λ(2), then check this value using your simulator:\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==0.5\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tNow investigate the motion Λ(2.1). In which direction does the population change from x[6]\n\t\tto x[7]: positive (+) or negative (-)?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> (x == -)\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tThis is interesting 00! Up to now, the development of the wasps has been monotone: the\n\t\tpopulation has only either shrunk or grown. But now it grows above the value, then drops\n\t\tback down again. Let's investigate this further: find the limit point of the motion\n\t\tΛ(2.5) both by calculating and by simulating:\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==0.6\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tNotice that now we have an oscillating motion that dies away as x comes to rest at the\n\t\tlimit point. Try out various values of r between 2.5 and 2.95. Does the oscillation\n\t\tstill die away?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> occursin(\"y\",lowercase(x))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tNow find the limiting motion of the population for Λ(3). Does the oscillation die away?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> occursin(\"n\",lowercase(x))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tIt now no longer makes sense to speak of a limit VALUE, since the motion oscillates\n\t\tforever around the value 2/3. Instead, we speak of a limit CYCLE: the motion Λ(3) displays\n\t\ta limit cycle around the value 2/3. \"cycle\" means the value oscillates forever, and\n\t\t\"limit\" means that it will converge to this cycle, no matter where we start the motion.\n\t\tCheck this for yourself by changing the value of x0. Does the motion always converge on\n\t\ta cycle around 2/3?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> occursin(\"y\",lowercase(x))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tHow many oscillatory periods are contained within one complete limit cycle of the motion\n\t\tΛ(3)? That is, how many times does the population wobble up and down within ONE cycle? If\n\t\tyou have difficulty understanding exactly what I am asking, try looking at the hint for\n\t\tthis activity.\n\t\t\"\"\",\n\t\t\"We call this limit cycle a \\\"period-1 limit-cycle\\\"!\",\n\t\tx -> x==1\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tLet's investigate further. Look at the limit-cycle of the motion Λ(3.2) (You may want\n\t\tto extend the simulation's duration to 50). How many periods are in this limit cycle?\n\t\t\"\"\",\n\t\t\"The number of periods should not (yet) have changed\",\n\t\tx -> x==1\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tHow many periods are in the limit-cycle of the motion Λ(3.45)? That is, how many complete\n\t\toscillations does the population make before the motion repeats itself?\n\t\t\"\"\",\n\t\t\"Count very carefully: This should be a period-2 limit-cycle!\",\n\t\tx -> x==2\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tHow many periods are in the limit-cycle of the motion Λ(3.55)? By now, things will move\n\t\tquite quickly and the wasp population will need a while to stabilise towards the limit-\n\t\tcycle. You may like to save time by using a line like this:\n\n\t\t\tlines(nestlist(Λ(3.55),0.5,5000)[end-40:end])\n\t\t\"\"\",\n\t\t\"Look very carefully!\",\n\t\tx -> x==4\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tHow many periods are in the limit-cycle of the motion Λ(3.567)?\n\t\t\"\"\",\n\t\t\"Count ve-ery carefully - remembering to inspect the smaller oscillations as well!\",\n\t\tx -> x==8\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tHow many periods are in the limit-cycle of the motion Λ(3.5695)? You will find this\n\t\tone difficult to count, but it is actually a period-16 limit-cycle. If you can't\n\t\tdistinguish the oscillations, don't worry - just go on to the next activity.\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==16\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWe have seen that as r increases, period-doubling occurs, so the motion takes longer\n\t\tand longer before it repeats. Now check out the motion Λ(3.7). How long does it take\n\t\tbefore this motion repeats itself? Or in other words: What is the period-length of\n\t\tthis limit-cycle?\n\t\t\"\"\",\n\t\t\"Find out how to write \\\"Infinity\\\" in Julia :)\",\n\t\tx -> x==Inf\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWe have come a long way, and what we have learned is that some naturally occurring systems\n\t\tcan enter a type of motion in which they require an infinite amount of time to repeat, and\n\t\tso we call them CHAOTIC. Notice that this phenomenon has nothing to do with randomness. The\n\t\tpopulation of Vespula Island is perfectly deterministic - we can always predict what will\n\t\thappen in the next step, but ONLY by actually simulating it! We cannot calculate in advance\n\t\twhat will happen after 1000 iterations without actually performing ALL of the 1000 steps\n\t\tthat lead up to it.\n\n\t\tActually, the situation is even worse than this. Use the following command to inspect the\n\t\tbehaviour of Λ(3.7) for the different starting conditions x0 ∈ [0.5,0.50001,4.99999]\n\n\t\t\tlines(nestlist(Λ(3.7),0.5,5000)[end-40:end])\n\n\t\tAre these three graphs at all similar to each other?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> occursin(\"n\",lowercase(x))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tSo you see, chaotic motion meanns that even tinsey-tiny changes in the initial conditions\n\t\tof a chaotic system lead to completely different behaviour. So even if we measured the\n\t\tcurrent wasp population, we could never be sure that we had done it sufficiently accurately\n\t\tto be ABSOLUTELY sure that we are accurately predicting the development of the system!\n\n\t\tSo. What has all this to do with your course project? Henri Poincaré was the first to\n\t\tnotice deterministic chaos. In 1908, he showed that the gravitational motion of three\n\t\torbiting bodies cannot be solved exactly. Weather, dripping taps and driven pendula have a\n\t\tsimilar problem. We cannot predict the story of their future motion without simulation,\n\t\twhich as you know is never precise! As an introduction to chaos in the three-body problem,\n\t\tplease view the following video-clip now, and then proceed to the next activity:\n\n\t\thttps://www.youtube.com/watch?v=LwkvO3t1b30&t=113s\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> true\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tThe demo() function of the module NBodies creates an instance of the type NBody to simulate\n\t\tthe motion of TWO bodies in ONE spatial dimension. Run it now: do the blue and red bodies\n\t\torbit each other? Investigate this further by increasing the resolution of the simulation\n\t\tand of the figure. Try focussing your graphic on the time-snapshots around where the two\n\t\tbodies meet, and magnify the image. Do they orbit now? What exactly is happening here?\n\t\tThis is the origin of chaotic motion!\n\n\t\tCheck that the vector x returned by the method NBodies.simulate() has three levels: the\n\t\telements of x span the individual time snapshots of the simulation; each snapshot contains\n\t\ta list of the bodies participating in the motion; and each body contains a list of that\n\t\tbody's coordinates. What do the contents of p represent?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> occursin(\"time\",lowercase(x))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tSoftware development is always driven by the needs of its CLIENT program - in our case,\n\t\tthis is the function NBodies.demo(). As you work with demo(), think about what kinds of\n\t\tbehaviour you as a user demand of the type NBody, and include that functionality in your\n\t\tNBodies module design. Your use-cases and newly developed design will form an important\n\t\tpart of your deliverables for this project.\n\n\t\tNotice that the two bodies (blue and red) do not orbit around each other. Why not? It may\n\t\thelp your thinking to consider the following question: Is energy conserved in this system?\n\t\t\"\"\",\n\t\t\"Think about the bodies' positions and momenta during the simulation\",\n\t\tx -> occursin(\"no\",lowercase(x))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tBe aware that I have not given much attention to the naming of variables - you will need to\n\t\tcomment, reformat and document the module much better than I have! Doing this will help you\n\t\tto understand the matrix programming techniques I have used, but they are not easy! You\n\t\twill need to thoroughly analyse the code and use Help and internet search to look up\n\t\tEVERYTHING you do not yet understand. Here is how to do this ...\n\n\t\tFirst remember: Matrices work very naturally in Julia, so if a=[1 2;3 5] and b=[2 3;4 5],\n\t\tthen a*b and a.*b will deliver very different results. First test this idea at the Julia\n\t\tprompt, and then tell me the value of a*b-a.*b :\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x == [8 7;14 9]\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tThe secret of matrix programming is this: Whenever you think you need a for-loop to\n\t\tmanipulate some values, build them together instead into a matrix that does the job for you.\n\t\tFor example define and test an anonymous version of the factorial function that requires no\n\t\trecursion or iteration, but uses the prod() function.\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> occursin(\"->prod(1:\",replace(x,\" \"=>\"\"))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tAnalyse the internal helper function relpos(), which calculates the relative positions\n\t\tx[i]-x[j] between all pairs of particles. Instead of looping over the particles, I compute\n\t\tthe relative positions more efficiently in a matrix operation. Find where relpos() is\n\t\tcalled, and notice that its argument is a Vector - for example [1,2].\n\t\t\n\t\tAt the Julia prompt, define relpos() and then call relpos([1,2]). What does the result look\n\t\tlike? What does relpos() do? At the Julia prompt, analyse the calls\n\n\t\t\tlocations = [1,2]\n\t\t\tlocPerBody = repeat(locations,1,length(locations))\n\t\t\tpermutedims(locPerBody)\n\n\t\tDiscuss your findings with others: How, exactly, does relPos() work?\n\n\t\tNow tell me the result of repeat([1,2],2,3)?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==[1 1 1;2 2 2;1 1 1;2 2 2]\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tSet a breakpoint and use the Debugger to investigate how simulate() uses relpos() to\n\t\tcalculate the gravitational forces acting between the different bodies in the system.\n\t\tWhich variable is used to calculate Newton's inverse-square law that falls with\n\t\tincreased distance between the sources?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==\"invSq\"\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tOK, now we can start on your actual project. First, extend my simulator to 2 bodies in\n\t\t2 dimensions and get the two bodies to orbit each other. This is your first major\n\t\tsuccess - well done!\n\n\t\tRemember to keep your solution very neat, so that others can understand what you have\n\t\tdone by reading your code.\n\t\t\"\"\",\n\t\t\"Just move on when you have completed this activity\",\n\t\tx -> true\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tNotice that your two bodies spiral outwards on their orbits because of my inaccurate\n\t\tsimulator. Improve my integration method to achieve (practically) closed orbits.\n\n\t\tWhat is the name of the integration technique you are using?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> occursin(\"runge-kutta\",lowercase(x))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tNow introduce a third body into your system (use the same mass for all three bodies). Try\n\t\tto create a situation in which the three bodies circle around each other without any of\n\t\tthem getting thrown out of the system to infinity. Ensure that your system is conserving\n\t\tenergy; that is, the three bodies taken together should neither gain nor lose energy!\n\t\t\"\"\",\n\t\t\"Just move on when you have completed this activity\",\n\t\tx -> true\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tYou will need to find a way of testing your simulation for chaotic motion. There are\n\t\tseveral ways to do this - some are easy, some more difficult; some are approximate, some\n\t\tare very accurate. Here is a paper containing an accurate method of detecting chaos:\n\t\t\n\t\thttps://www.nature.com/articles/s42003-019-0715-9.pdf\n\t\t\n\t\tAlternatively, in chaotic dynamics, small differences in initial conditions grow\n\t\texponentially over time in the short term. The easiest way to test for exponential growth\n\t\tis by plotting a logarithm graph over time to see if it is linear. Decide how you want to\n\t\tmeasure chaoticity in your system.\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> true\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tYour project deliverable is a Julia module that must fulfil the following constraints:\n\t\t\t- the demonstration program MUST execute correctly within its own folder;\n\t\t\t- simulates the motion of three or more gravitational bodies;\n\t\t\t- executes an aesthetically pleasing chaotic trajectory;\n\t\t\t- demonstrates that the motion conserves energy;\n\t\t\t- demonstrates that the motion is indeed chaotic;\n\t\t\t- displays explanatory text so that anyone can understand it WITHOUT studying the code!\n\t\t\t- the code must be neat, well documented and easily readable and comprehensible.\n\t\t\"\"\",\n\t\t\"Good luck!!!\",\n\t\tx -> true\n\t),\n]", "meta": {"hexsha": "d2265b7f821022625f29eacf5fdd14766a0c6db1", "size": 16661, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Labs/INLab011.jl", "max_stars_repo_name": "NiallPalfreyman/Ingolstadt.jl", "max_stars_repo_head_hexsha": "c8b92b4b2bd8659d2584f153efe70dd7e99c5e9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-25T09:00:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:00:42.000Z", "max_issues_repo_path": "Labs/INLab011.jl", "max_issues_repo_name": "NiallPalfreyman/Ingolstadt.jl", "max_issues_repo_head_hexsha": "c8b92b4b2bd8659d2584f153efe70dd7e99c5e9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/INLab011.jl", "max_forks_repo_name": "NiallPalfreyman/Ingolstadt.jl", "max_forks_repo_head_hexsha": "c8b92b4b2bd8659d2584f153efe70dd7e99c5e9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-03-18T14:20:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T09:00:45.000Z", "avg_line_length": 39.3877068558, "max_line_length": 95, "alphanum_fraction": 0.7024188224, "num_tokens": 4506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.8807970701552505, "lm_q1q2_score": 0.7772398793964646}}
{"text": "\"\"\"\nfunction logmean(aL,aR)\n\"\"\"\n\nfunction logmean(aL,aR)\n    return logmean(aL,aR,log(aL),log(aR))\nend\n\n\"\"\"\nfunction logmean(aL,aR,logL,logR)\n    Compute logarithmic mean using pre-computed log values\n\"\"\"\n\nfunction logmean(aL,aR,logL,logR)\n\n    \"from: Entropy stable num. approx. for the isothermal and polytropic Euler\"\n    # assumes the specific value γ = 1.4\n    da = aR-aL;\n    aavg = .5*(aR+aL);\n    f = da/aavg;\n    v = f^2;\n    if abs(f)<1e-4\n        return aavg*(1 + v*(-.2-v*(.0512 - v*0.026038857142857)))\n    else\n        return -da/(logL-logR)\n    end\nend\n", "meta": {"hexsha": "53937674c1bdfa99545e68f126fa1b152e22497b", "size": 568, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/EntropyStableEuler/logmean.jl", "max_stars_repo_name": "yiminllin/ESDG-Fourier", "max_stars_repo_head_hexsha": "0cbd36add7b06e0fa43335daf7188ccaea461e6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/EntropyStableEuler/logmean.jl", "max_issues_repo_name": "yiminllin/ESDG-Fourier", "max_issues_repo_head_hexsha": "0cbd36add7b06e0fa43335daf7188ccaea461e6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/EntropyStableEuler/logmean.jl", "max_forks_repo_name": "yiminllin/ESDG-Fourier", "max_forks_repo_head_hexsha": "0cbd36add7b06e0fa43335daf7188ccaea461e6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2857142857, "max_line_length": 79, "alphanum_fraction": 0.6161971831, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9736446486833799, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7771502894701849}}
{"text": "using Plots\nusing ForwardDiff\nusing LinearAlgebra\n\na = 1.0\nb = 100.0\n\nf(x) = (a - x[1])^2.0 + b * (x[2] - x[1]^2.0)^2.0\nf(x, y) = f([x; y])\n∇f(x) = ForwardDiff.gradient(f, x)\n∇²f(x) = ForwardDiff.hessian(f, x)\n\nn = 1000\nx_limits = range(-1.0, stop = 1.0, length = n)\ny_limits = range(-1.0, stop = 1.0, length = n)\n\nx = zeros(2)\n\nfunction solve(x;\n        max_iter = 100,\n        visualize = true)\n    visualize && (plt = Plots.contour(x_limits, y_limits, f))\n    visualize && (plt = plot!((x[1], x[2]), markershape = :circle, color = :cyan, outline = :cyan))\n\n    for i = 1:max_iter\n        grad = ∇f(x)\n        println(\"x:  $x\")\n        println(\"grad norm: $(norm(grad))\")\n        norm(grad) < 1.0e-3 && break\n\n        hess = ∇²f(x)\n        # Δ = hess \\ grad\n        Δ = grad\n\n        α = 1.0\n        iter = 1\n        while norm(∇f(x - α * Δ)) > norm(grad) && iter < 100\n            α *= 0.5\n            iter += 1\n        end\n\n        x .-= α * Δ\n\n        if i % 10 == 0 && visualize\n            plt = plot!((x[1], x[2]),\n                markershape = :circle, color = :cyan, outline = :cyan,\n                legend = false)\n            display(plt)\n        end\n    end\n    print(\"iters: $i\")\n    return x\nend\n\nsolve([0.0, -1.0], max_iter = 1000)\n", "meta": {"hexsha": "11220da781ee06611a785006b07f64f1db7b376d", "size": 1248, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/development/derivative_free/rosenbrock.jl", "max_stars_repo_name": "thowell/motion_planning", "max_stars_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2021-02-07T10:46:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:30:20.000Z", "max_issues_repo_path": "examples/development/derivative_free/rosenbrock.jl", "max_issues_repo_name": "thowell/DirectMotionPlanning", "max_issues_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-10-07T05:36:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-11T17:16:28.000Z", "max_forks_repo_path": "examples/development/derivative_free/rosenbrock.jl", "max_forks_repo_name": "thowell/motion_planning", "max_forks_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-01-25T19:23:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T06:43:01.000Z", "avg_line_length": 22.2857142857, "max_line_length": 99, "alphanum_fraction": 0.4767628205, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750360641186, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7771407871066585}}
{"text": "#normalization factor\nabstract type YLMNorm{T} end\n\nstruct Schmidt{T} <: YLMNorm{T}; end\nstruct Laplace{T} <: YLMNorm{T}; end\nstruct Nonorm{T} <: YLMNorm{T}; end\nstruct Full{T} <: YLMNorm{T}; end\n\nfunction ylmcoeff(N::Schmidt{T},l::Int64, m::Int64) where T\n\n\tk = one(T)\n\tfor i in (l-m+1):(l+m)\n\t  k *= i\n\tend\n\treturn sqrt(1/k)\nend\n\nfunction ylmcoeff(N::Laplace{T}, l::Int64, m::Int64) where T\n\n  k = one(T)\n  for i in (l-m+1):(l+m)\n    k *= i\n  end\n\n  return sqrt((2*l+1) / (4*T(pi)*k))\nend\n\nfunction ylmcoeff(N::Full{T}, l::Int64, m::Int64) where T\n\tfac = m==0 ? one(T) : sqrt(2*one(T))\n\treturn ylmcoeff(Laplace{T}(),l,m)*sqrt(4T(pi))*fac\nend\n\nfunction ylmcoeff(N::Nonorm{T}, l::Int64, m::Int64) where T\n return one(T)\nend\n\n\n\nfunction cossinpoly(m::Int64, x::Variable, y::Variable)\n\n  sum = zero(x*y)\n  for j in 0:div(m,2)\n\t  k = 2j\n    sum += ((-1)^j)*binomial(m, k)*y^k*x^(m-k)\n  end\n  return sum\nend\n\nfunction sinsinpoly(m::Int64, x::Variable, y::Variable)\n\n  sum = zero(x*y)\n  for j in 0:div((m-1),2)\n\t  k = 2j+1\n    sum += ((-1)^j)*binomial(m, k)*y^k*x^(m-k)\n  end\n  return sum\nend\n\n# #legendre polynomial:\n# P(l::BigInt,x) = differentiate((x^2 - 1)^l,x,l)\n#\n# #associated legendre polynomial (without sin(θ)^m)\n# P(l::BigInt,m::BigInt,x) = 1//(big(2)^l*factorial(l))*differentiate(P(l,x),x,m)\n\n\"\"\"\n    ylm(l::Int64, m::Int64, x::Variable, y::Variable, z::Variable)\n*Description:*  Calculation of the spherical harmonic for a given order (l,m) in Cartesian coordinates\\\\\n\n*Input:*  `l`       - Degree of the spherical harmonic\\\\\n          `m`       - Order of the spherical harmonic\\\\\n          `x, y, z` - Cartesian coordinates\\\\\n\n*Output:*  Spherical harmonic polynomial\n\"\"\"\nfunction ylm(l::Int64, m::Int64, x::Variable, y::Variable, z::Variable;\n\t\t\t norm::YLMNorm{T}=Laplace{Float64}(),real=true) where T\n\n\tif abs(m) > l\n\tthrow(DomainError(m,\"-l <= m <= l expected, but m = $m and l = $l.\"))\n\tend\n\n\tp = (z^2 - 1)^l\n\n\tfor i = 1:l+abs(m)\n\t  c = i <= l ? 1/(2one(T)*i) : one(T)\n\t  p = c*differentiate(p, z)\n\tend\n\n\tp *= (-1)^m\n\n\tif real\n\t\tif m > 0\n\t\t\tout = ylmcoeff(norm, l, m)*cossinpoly(m,x,y)*p\n\t\t\tif norm != Nonorm{T}()\n\t\t\t\tout *= sqrt(2one(T))\n\t\t\tend\n\t\t\treturn out\n\t\telseif m < 0\n\t\t\tout = ylmcoeff(norm, l, abs(m))*sinsinpoly(abs(m),x,y)*p\n\t\t\tif norm != Nonorm{T}()\n\t\t\t\tout *= sqrt(2one(T))\n\t\t\tend\n\t\t\treturn out\n\t\telse\n\t\t\treturn ylmcoeff(norm, l, 0)*p\n\t\tend\n\telse\n\t\treturn ylmcoeff(norm, l, m)*(cossinpoly(m,x,y)+sign(m)*im*sinsinpoly(m,x,y))*p\n\tend\nend\n\n# multiplying r^l*ylm(x,y,z)\nfunction rlylm(l::Int64, m::Int, x::Variable, y::Variable, z::Variable;\n\t\t\t   norm::YLMNorm{T}=Laplace{Float64}(),real=true) where T\n\tp = ylm(l,m,x,y,z;norm=norm,real=real)\n\ttout = []\n\t# Zerlegung des Polynoms in Terme:\n\tfor t in terms(p)\n\t\tdeg = degree(monomial(t)) # Gibt den gesamten Grad des Monoms an\n\t\tdegR = l-deg # durch das Kürzen ergibt sich ein Grad von l-deg fuer r\n\t\tpush!(tout,(x^2+y^2+z^2)^div(degR,2)*t) # r² wird durch x²+y²+z² ersetzt\n\tend\n\n\treturn polynomial(tout)\nend\n\n# solid harmonics\nfunction rlm(l::Int64, m::Int64, x::Variable, y::Variable, z::Variable;\n\t\t\t norm::YLMNorm{T}=Laplace{Float64}(),real=true) where T\n\trlm = rlylm(l,m,x,y,z; norm=norm,real=real)\n\tif norm != Nonorm{T}()\n\t\trlm = sqrt(4one(T)*T(pi)/(2*l+1))*rlm\n\tend\n\treturn rlm\nend\n", "meta": {"hexsha": "9080edc88cbbbf33d2d3d587fcf335e63cbbe2df", "size": 3262, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sphericalHarmonic.jl", "max_stars_repo_name": "fgerick/SphericalHarmonics.jl", "max_stars_repo_head_hexsha": "d55bc0fda24ee6c38cc8ddb82831d37fb190b874", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sphericalHarmonic.jl", "max_issues_repo_name": "fgerick/SphericalHarmonics.jl", "max_issues_repo_head_hexsha": "d55bc0fda24ee6c38cc8ddb82831d37fb190b874", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sphericalHarmonic.jl", "max_forks_repo_name": "fgerick/SphericalHarmonics.jl", "max_forks_repo_head_hexsha": "d55bc0fda24ee6c38cc8ddb82831d37fb190b874", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9852941176, "max_line_length": 104, "alphanum_fraction": 0.6155732679, "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750360641186, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7771407806876689}}
{"text": "#  Copyright 2017, Oscar Dowson\n\nexport binexpand, bincontract, bitsrequired\n\n# Cache these for speed\nconst log2inv = 1 / log(2)\n# dereferencing an array is faster than a 2^x call\nconst _2i_ = Int[2^(i-1) for i in 1:floor(Int, log(typemax(Int)) * log2inv)+1]\nconst _2i_L = length(_2i_)\n\nfunction binexpand!(y::Vector{Int}, x::Int)\n    if x < 0\n        error(\"Values to be expanded must be nonnegative. Currently x = $x.\")\n    end\n    @inbounds for i in length(y):-1:1\n        k = _2i_[i]\n        if x >= k\n            y[i] = 1\n            x -= k\n        end\n    end\n    if x > 0\n        error(\"Unable to expand binary. Overflow of $x.\")\n    end\nend\n\nfunction bitsrequired(x::Int)\n    floor(Int, log(x) * log2inv) + 1\nend\nfunction bitsrequired(x::Float64, eps::Float64=0.1)\n    xx = round(Int, x / eps)\n    floor(Int, log(xx) * log2inv) + 1\nend\n\n\"\"\"\n    binexpand(x::Int; length::Int=-1, maximum::Real=-1)\n\nReturns an array of 0/1 coefficients for the binary expansion of `x`.\nIf trailing zeroes are needed, use `length` to specify the length of the output.\n\"\"\"\nfunction binexpand(x::Int; length::Int=-1, maximum::Real=-1)\n    x < 0 && error(\"Cannot perform binary expansion on a negative number.\")\n    if maximum != -1\n        if length != -1\n            warn(\"Length is being ignored.\")\n        end\n        length = bitsrequired(floor(Int, maximum))\n    end\n    if length == -1\n        y = zeros(Int, bitsrequired(x))\n    else\n        y = zeros(Int, length)\n    end\n    binexpand!(y, x)\n    y\nend\n\n\"\"\"\n    binexpand(x::Float64, eps::Float64=0.1; length::Int=-1, maximum::Real=-1)\n\nReturns an array of 0/1 coefficients for the binary expansion of `x`.\nIf trailing zeroes are needed, use `length` to specify the length of the output.\n\"\"\"\nfunction binexpand(x::Float64, eps::Float64=0.1; length::Int=-1, maximum::Real=-1)\n    x < 0 && error(\"Cannot perform binary expansion on a negative number.\")\n    if eps <= 0.0\n        error(\"Epsilon tolerance for Float binary expansion must be strictly greater than 0.\")\n    end\n    xx = round(Int, x / eps)\n    if maximum != -1\n        if length != -1\n            warn(\"Length is being ignored.\")\n        end\n        length = bitsrequired(floor(Int, maximum / eps))\n    end\n    binexpand(xx, length=length)\nend\n\nfunction bincontract_2i_(y::Vector{T}) where T\n    x = zero(T)\n    @inbounds for i in 1:length(y)\n        x += _2i_[i] * y[i]\n    end\n    x\nend\nfunction bincontract_pow(y::Vector{T}) where T\n    x = zero(T)\n    @inbounds for i in 1:length(y)\n        x += 2^(i-1) * y[i]\n    end\n    x\nend\n\n\"\"\"\n    bincontract{T}(y::Vector{T})\n\nFor vector `y`, evaluates ∑ᵢ 2ⁱ⁻¹yᵢ.\n\"\"\"\nfunction bincontract(y::Vector{T}) where T\n    if length(y) < _2i_L\n        bincontract_2i_(y)\n    else\n        bincontract_pow(y)\n    end\nend\n\nfunction bincontract(::Type{Float64}, y::Vector{T}, eps::Float64=0.1) where T\n    if eps <= 0\n        error(\"Epsilon tolerance for Float binary contraction must be strictly greater than 0.\")\n    end\n    xx = bincontract(y)\n    xx * eps\nend\n", "meta": {"hexsha": "2dc10982a4ba283db86b5b8362ebbeb6dfd3055f", "size": 3003, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/binary_expansion.jl", "max_stars_repo_name": "lkapelevich/SDDiP.jl", "max_stars_repo_head_hexsha": "8e6cc59897ed5afd603ec840a4019788459be460", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2017-07-12T21:51:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-02T00:03:27.000Z", "max_issues_repo_path": "src/binary_expansion.jl", "max_issues_repo_name": "lkapelevich/SDDiP.jl", "max_issues_repo_head_hexsha": "8e6cc59897ed5afd603ec840a4019788459be460", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2017-07-12T21:51:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-07T15:25:25.000Z", "max_forks_repo_path": "src/binary_expansion.jl", "max_forks_repo_name": "lkapelevich/SDDiP.jl", "max_forks_repo_head_hexsha": "8e6cc59897ed5afd603ec840a4019788459be460", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-01-05T20:38:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-28T11:57:37.000Z", "avg_line_length": 26.3421052632, "max_line_length": 96, "alphanum_fraction": 0.6137196137, "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7771291779025159}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,jl:hydrogen\n#     text_representation:\n#       extension: .jl\n#       format_name: hydrogen\n#       format_version: '1.3'\n#       jupytext_version: 1.10.3\n#   kernelspec:\n#     display_name: Julia 1.7.0\n#     language: julia\n#     name: julia-1.7\n# ---\n\n# %%\nusing Distributions\n\ntstat(μ, X) = (mean(X) - μ)/√(var(X) / length(X))\npvalue(μ, X) = 2ccdf(TDist(length(X) - 1), abs(tstat(μ, X)))\n\nfunction ci(X, α)\n    X̄ = mean(X)\n    c = quantile(TDist(length(X) - 1), 1 - α/2)\n    d = √(var(X) / length(X))\n    X̄ - c*d, X̄ + c*d\nend\n\nisininterval(x, int) = first(int) ≤ x ≤ last(int)\nisinci(μ, X, α) = isininterval(μ, ci(X, α))\n\nprob_trueisinci(dist, n, α; L=10^6) = mean(isinci(mean(dist), rand(dist, n), α) for _ in 1:L)\n\n# %%\nprob_trueisinci(Normal(), 20, 0.05)\n\n# %%\nprob_trueisinci(Uniform(), 20, 0.05)\n\n# %%\nprob_trueisinci(Exponential(), 20, 0.05)\n\n# %%\nprob_trueisinci(MixtureModel([Normal(), Normal(10, 1)], [0.95, 0.05]), 20, 0.05)\n\n# %%\nusing Plots\n\n# %%\nnormal = Normal(mean(Uniform()), std(Uniform()))\nP = plot(x -> pdf(Uniform(), x), -1, 2; label=\"Uniform()\")\nplot!(x -> pdf(normal, x), -1, 2; label=\"normal approx.\", ls=:dash)\ntitle!(\"pdfs\")\nQ = plot(x -> cdf(Uniform(), x), -1, 2; label=\"Uniform()\")\nplot!(x -> cdf(normal, x), -1, 2; label=\"normal approx.\", ls=:dash)\ntitle!(\"cdfs\"; legend=:bottomright)\nplot(P, Q; size=(720, 300))\n\n# %%\nnormal = Normal(mean(Exponential()), std(Exponential()))\nP = plot(x -> pdf(Exponential(), x), -3, 6; label=\"Exponential()\")\nplot!(x -> pdf(normal, x), -3, 6; label=\"normal approx.\", ls=:dash)\ntitle!(\"pdfs\")\nQ = plot(x -> cdf(Exponential(), x), -3, 6; label=\"Exponential()\")\nplot!(x -> cdf(normal, x), -3, 6; label=\"normal approx.\", ls=:dash)\ntitle!(\"cdfs\"; legend=:bottomright)\nplot(P, Q; size=(720, 300))\n\n# %%\nmixnormal = MixtureModel([Normal(), Normal(10, 1)], [0.95, 0.05])\nP = plot(x -> pdf(mixnormal, x), -5, 15; label=\"mixnormal\")\nplot!(x -> pdf(Normal(), x), -5, 15; label=\"Normal()\", ls=:dash)\ntitle!(\"pdfs\")\nQ = plot(x -> cdf(mixnormal, x), -5, 15; label=\"mixnormal\")\nplot!(x -> cdf(Normal(), x), -5, 15; label=\"Normal()\", ls=:dash)\ntitle!(\"cdfs\"; legend=:bottomright)\nplot(P, Q; size=(720, 300))\n\n# %%\nmixnormal = MixtureModel([Normal(), Normal(10, 1)], [0.95, 0.05])\nnormal = Normal(mean(mixnormal), std(mixnormal))\nP = plot(x -> pdf(mixnormal, x), -5, 15; label=\"mixnormal\")\nplot!(x -> pdf(normal, x), -5, 15; label=\"normal approx.\", ls=:dash)\ntitle!(\"pdfs\")\nQ = plot(x -> cdf(mixnormal, x), -5, 15; label=\"mixnormal\")\nplot!(x -> cdf(normal, x), -5, 15; label=\"normal approx.\", ls=:dash)\ntitle!(\"cdfs\"; legend=:bottomright)\nplot(P, Q; size=(720, 300))\n\n# %%\nmodel = Normal()\n@show model\nμ, σ² = mean(model), var(model)\nPP = []\nfor n in (5, 10, 20, 100)\n    Z = [(mean(rand(model, n)) - μ)/√(σ²/n) for _ in 1:10^5]\n    P = histogram(Z; norm=true, alpha=0.3, bin = -3.5:0.1:6, label=\"\")\n    plot!(x -> pdf(Normal(), x); label=\"\", ls=:dash, lw=1.5)\n    title!(\"sample size n = $n\")\n    push!(PP, P)\nend\nplot(PP...; size=(800, 600), layout=(2, 2), titlefontsize=11)\n\n# %%\nmodel = Uniform()\n@show model\nμ, σ² = mean(model), var(model)\nPP = []\nfor n in (5, 10, 20, 100)\n    Z = [(mean(rand(model, n)) - μ)/√(σ²/n) for _ in 1:10^5]\n    P = histogram(Z; norm=true, alpha=0.3, bin = -3.5:0.1:6, label=\"\")\n    plot!(x -> pdf(Normal(), x); label=\"\", ls=:dash, lw=1.5)\n    title!(\"sample size n = $n\")\n    push!(PP, P)\nend\nplot(PP...; size=(800, 600), layout=(2, 2), titlefontsize=11)\n\n# %%\nmodel = Exponential()\n@show model\nμ, σ² = mean(model), var(model)\nPP = []\nfor n in (5, 10, 20, 100)\n    Z = [(mean(rand(model, n)) - μ)/√(σ²/n) for _ in 1:10^5]\n    P = histogram(Z; norm=true, alpha=0.3, bin = -3.5:0.1:6, label=\"\")\n    plot!(x -> pdf(Normal(), x); label=\"\", ls=:dash, lw=1.5)\n    title!(\"sample size n = $n\")\n    push!(PP, P)\nend\nplot(PP...; size=(800, 600), layout=(2, 2), titlefontsize=11)\n\n# %%\nmodel = MixtureModel([Normal(), Normal(10, 1)], [0.95, 0.05])\n@show model\nμ, σ² = mean(model), var(model)\nPP = []\nfor n in (5, 10, 20, 100)\n    Z = [(mean(rand(model, n)) - μ)/√(σ²/n) for _ in 1:10^5]\n    P = histogram(Z; norm=true, alpha=0.3, bin = -3.5:0.1:6, label=\"\")\n    plot!(x -> pdf(Normal(), x); label=\"\", ls=:dash, lw=1.5)\n    title!(\"sample size n = $n\")\n    push!(PP, P)\nend\nplot(PP...; size=(800, 600), layout=(2, 2), titlefontsize=11)\n\n# %%\n", "meta": {"hexsha": "47f1153083075df953d189712adddbd2f0933386", "size": 4391, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0012/probability of true value being in CI.jl", "max_stars_repo_name": "genkuroki/public", "max_stars_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-06-06T00:33:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T06:56:08.000Z", "max_issues_repo_path": "0012/probability of true value being in CI.jl", "max_issues_repo_name": "genkuroki/public", "max_issues_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0012/probability of true value being in CI.jl", "max_forks_repo_name": "genkuroki/public", "max_forks_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-02T11:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T11:46:05.000Z", "avg_line_length": 29.6689189189, "max_line_length": 93, "alphanum_fraction": 0.5698018675, "num_tokens": 1674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7771291740781531}}
{"text": "###############################################################\n#                Combined Mean and Variance\n###############################################################\n\"\"\"\n    combined_mean_and_var(xs...) -> meanc, varc\nCalculates the combined mean and variance of the concatenated sample `vcat(xs...)`.\n\"\"\"\nfunction combined_mean_and_var(xstuple::AbstractVector{T}...) where T\n    xs = collect(xstuple)\n    ns = length.(xs)\n    μs = mean.(xs)\n    vs = var.(xs)\n    return combined_mean_and_var(ns, μs, vs)\nend\n\nexport combined_mean_and_var\n\n\n\n\n\"\"\"\n    combined_mean_and_var(ns, μs, vs) -> meanc, varc\nGiven N samples characterized by their lengths `ns`,\ntheir means `μs`, and their variances `vs`,\ncalculates the combined (or pooled) mean and variance of the\noverall (concatenated) sample.\n\"\"\"\nfunction combined_mean_and_var(ns::AbstractVector{<:Integer},\n                               μs::AbstractVector{<:Number},\n                               vs::AbstractVector{<:Number})\n    nsum = sum(ns)\n    meanc = dot(ns, μs) / nsum\n    varc = sum((ns .- 1) .* vs + ns .* abs2.(μs .- meanc)) / (nsum - 1)\n    return meanc, varc\nend\n\n\nfunction combined_mean_and_var(ns::AbstractVector{<:Integer},\n                               μs::AbstractVector{<:AbstractArray{<:Number}},\n                               vs::AbstractVector{<:AbstractArray{<:Number}})\n    meanc = zero(μs[1])\n    varc = zero(vs[1])\n\n    nsum = sum(ns)\n    N = length(μs) # number of samples\n    for i in eachindex(meanc)\n\n        for k in 1:N\n            meanc[i] += ns[k] * μs[k][i]\n        end\n        meanc[i] = meanc[i] / nsum\n\n\n        for k in 1:N\n            varc[i] += (ns[k] - 1) * vs[k][i] + ns[k] * abs2(μs[k][i] - meanc[i])\n        end\n        varc[i] = varc[i] / (nsum - 1)\n    end\n\n    return meanc, varc\nend\n\n\n\n\n###############################################################\n#       Combined Mean and Variance (\"Hand-written\")\n###############################################################\n\"\"\"\n    combined_mean_and_var(x1, x2) -> meanc, varc\nGiven two samples `x1`,`x2` calculates the mean and variance of the\nconcatenated sample.\n\"\"\"\nfunction combined_mean_and_var(x1::AbstractVector{<:Number}, x2::AbstractVector{<:Number})\n    n1, n2 = length(x1), length(x2)\n    μ1, μ2 = mean(x1), mean(x2)\n    v1, v2 = var(x1), var(x2)\n    return combined_mean_and_var(n1, μ1, v1, n2, μ2, v2)\nend\n\n\n\"\"\"\n    combined_mean_and_var(n1, μ1, v1, n2, μ2, v2) -> meanc, varc\nGiven two samples characterized by their lengths `n1`, `n2`, \ntheir means `μ1`, `μ2`, and their variances `v1`, `v2`,\ncalculates the combined (or pooled) mean and variance of the\nconcatenated sample.\n\"\"\"\nfunction combined_mean_and_var(n1::Integer, μ1::Number, v1::Number,\n                               n2::Integer, μ2::Number, v2::Number)\n    meanc = (n1 * μ1 + n2 * μ2) / (n1 + n2)\n\n    # Based on https://www.emathzone.com/tutorials/basic-statistics/combined-variance.html,\n    # including Robert Matheson's comment and adding abs for complex number support.\n    varc = ((n1-1)*v1 + (n2-1)*v2 + n1*abs2(μ1 - meanc) + n2*abs2(μ2 - meanc)) /\n                                (n1 + n2 - 1)\n    return meanc, varc\nend\n\n\n# Explicit version for three samples (only for testing)\nfunction combined_mean_and_var_three(x1, x2, x3)\n    n1, n2, n3 = length(x1), length(x2), length(x3)\n    μ1, μ2, μ3 = mean(x1), mean(x2), mean(x3)\n    v1, v2, v3 = var(x1), var(x2), var(x3)\n\n    meanc12, varc12 = combined_mean_and_var(n1, μ1, v1, n2, μ2, v2)\n    n12 = n1 + n2\n    return combined_mean_and_var(n12, meanc12, varc12, n3, μ3, v3)\nend\n\n\n\n\n\n\n\n\n\n\n\"\"\"\n    combined_mean_and_var(ors::Vector{<:ObservableResult}) -> meanc, stderrc\nCalculates the combined mean and standard error of the concatenated observable results.\n\"\"\"\nfunction combined_mean_and_error(ors::Vector{<:ObservableResult})\n    @assert length(ors) > 0 \"Provided vector of ObservableResults must not be empty.\"\n\n    ns = [r.count for r in ors]\n    μs = [r.mean for r in ors]\n    vs = [r.error^2 for r in ors]\n\n    meanc, varc = combined_mean_and_var(ns, μs, vs)\n    return meanc, sqrt.(varc)\nend", "meta": {"hexsha": "b23142b4998b9eb8820157a0703bbfa1fa4f492c", "size": 4082, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/statistics.jl", "max_stars_repo_name": "crstnbr/dqmc", "max_stars_repo_head_hexsha": "0797999881ca21013da0a6c44ff852017ac2127f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2020-03-17T01:15:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-06T16:21:16.000Z", "max_issues_repo_path": "src/statistics.jl", "max_issues_repo_name": "crstnbr/dqmc", "max_issues_repo_head_hexsha": "0797999881ca21013da0a6c44ff852017ac2127f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-08T19:02:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T19:02:16.000Z", "max_forks_repo_path": "src/statistics.jl", "max_forks_repo_name": "crstnbr/dqmc", "max_forks_repo_head_hexsha": "0797999881ca21013da0a6c44ff852017ac2127f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-15T22:21:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-15T22:21:45.000Z", "avg_line_length": 30.4626865672, "max_line_length": 91, "alphanum_fraction": 0.5788829005, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.8577680977182186, "lm_q1q2_score": 0.7771291734915614}}
{"text": "# Struct to hold an x, y position. A tuple would also be fine.\nstruct Pos\n    x::Float64\n    y::Float64\nend\n\n# This returns a measure of how far \"left\" the vector is with a cross product\nfunction cross(point1::Pos, point2::Pos, point3::Pos)\n    vec1 = Pos(point2.x - point1.x, point2.y - point1.y)\n    vec2 = Pos(point3.x - point2.x, point3.y - point2.y)\n    ret_angle = vec1.x*vec2.y - vec1.y*vec2.x\n    return ret_angle*ret_angle\nend\n\nfunction jarvis_march(points::Vector{Pos})\n    hull = Vector{Pos}()\n\n    # sorting array based on leftmost point\n    sort!(points, by = item -> item.x)\n    push!(hull, points[1])\n\n    i = 1\n    curr_point = points[2]\n\n    # Find angle between points\n    curr_product = cross(Pos(0,0), hull[1], curr_point)\n\n    # We will hold a temp variable with the highest cross product as we iterate\n    # through all the points and move our hull vector forward.\n    while (curr_point != hull[1])\n        for point in points\n            product = 0.0\n\n            # Special case for the first element when there is no hull[i-1]\n            if (i == 1)\n                if (hull[i] != point)\n                    product = cross(Pos(0,0), hull[i], point)\n                end\n            else\n                if (hull[i] != point && hull[i-1] != point)\n                    product = cross(hull[i-1], hull[i], point)\n                end\n            end\n            if (product > curr_product)\n                curr_point = point\n                curr_product = product\n            end\n        end\n\n        # Pushing to hull, moving simulation forward and resetting the product\n        push!(hull, curr_point)\n        curr_product = 0\n        i += 1\n    end\n\n    return hull\nend\n\nfunction main()\n\n    # These points are chosen such that there is a clearly defined hull with\n    # several interior points. As a note, these will be generated either \n    # randomly or via some mesh in practice.\n    points = [Pos(2,1.5), Pos(1, 1), Pos(2, 4), Pos(3, 1), Pos(2,2), Pos(2,0.5)]\n    hull = jarvis_march(points)\n    println(hull)\nend\n\nmain()\n", "meta": {"hexsha": "3710d835d21432f20c4aa6b9d343447e4bbf8bbb", "size": 2052, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapters/computational_geometry/gift_wrapping/jarvis_march/code/jarvis.jl", "max_stars_repo_name": "chrisb2244/algorithm-archive", "max_stars_repo_head_hexsha": "a30a088dc57f73c24724e9adcf45131c34ec2829", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 197, "max_stars_repo_stars_event_min_datetime": "2015-07-26T02:04:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T11:53:33.000Z", "max_issues_repo_path": "gift_wrapping/jarvis.jl", "max_issues_repo_name": "shiffman/simuleios", "max_issues_repo_head_hexsha": "57239350d2cbed10893483bda65fa323e5e3a06d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2015-08-04T22:55:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-06T02:33:48.000Z", "max_forks_repo_path": "gift_wrapping/jarvis.jl", "max_forks_repo_name": "shiffman/simuleios", "max_forks_repo_head_hexsha": "57239350d2cbed10893483bda65fa323e5e3a06d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 55, "max_forks_repo_forks_event_min_datetime": "2015-08-02T21:43:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T18:25:08.000Z", "avg_line_length": 29.3142857143, "max_line_length": 80, "alphanum_fraction": 0.5843079922, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8577681068080748, "lm_q1q2_score": 0.7771291686630811}}
{"text": "# See https://jp.mathworks.com/help/matlab/ref/peaks.html\nfunction peaks(N=49::Int)\n    function formula(x::T, y::T) where T<:Float64\n        z = 3(1-x)^2*exp(-(x^2)-(y+1)^2)-10(x/5 - x^3 - y^5)*exp(-x^2-y^2)-(1/3)exp(-(x+1)^2-y^2)\n    end\n    vec = collect(Float64, LinRange(-3.,3.,N))\n    x = repeat(vec', outer=(N,1))\n    y = repeat(vec, outer=(1,N))\n    z = formula.(x,y)\n    return (x,y,z)\nend\n", "meta": {"hexsha": "72e70be62c6c6f38dbb28dae9e76f1b876f51ab4", "size": 399, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "peaks.jl", "max_stars_repo_name": "hydrocoast/julia_training", "max_stars_repo_head_hexsha": "d8d103b5254f1f1b3c3c5435bf23a30772d85ecb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-03-16T12:02:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-11T01:20:59.000Z", "max_issues_repo_path": "peaks.jl", "max_issues_repo_name": "hydrocoast/julia_training", "max_issues_repo_head_hexsha": "d8d103b5254f1f1b3c3c5435bf23a30772d85ecb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "peaks.jl", "max_forks_repo_name": "hydrocoast/julia_training", "max_forks_repo_head_hexsha": "d8d103b5254f1f1b3c3c5435bf23a30772d85ecb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-11T01:21:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-11T01:21:10.000Z", "avg_line_length": 33.25, "max_line_length": 97, "alphanum_fraction": 0.5513784461, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813488829418, "lm_q2_score": 0.8128673155708976, "lm_q1q2_score": 0.7770859928023227}}
{"text": "# =============================================================================\n# CALCULATRICE SCIENTIFIQUE\n# =============================================================================\n\n# opérateurs  classiques : +-*/\\\n\n1 + 3\n3 / 7\n3 \\ 7 # ≈ 7 / 3\n1e2\nim # nombre complexe i\nim^2\n# Les fonctions usuelles : exp, log, log10, abs, sqrt, cbrt, sign\n\nlog10(100_000)\nlog(exp(2))\n1 / (1 + exp(1))\n# Les fonctions trigonométriques usuelles : sin, cos, tan, cot, sec, csc, sinh, cosh, tanh, coth, sech, csch, asin, acos, atan...\n\n\nsin(π+√2) # Code Is Math !!  tapez \"\\pi<tab>\" et \"\\sqrt<tab>2\"\n\n\n# =============================================================================\n# VALEURS (tout ce qui est manipulable en Julia) & TYPES (Int32, Int64, Int128, Float32, Float64, Complex32, Complex64, Complex128...)\n# =============================================================================\n\n# types et collections\n\n3 + 5 # nombre entier stockée en 32/64 bits en fonction de l'architecture machine\ntypeof(3 + 5) \n3. * 4. # nombre en virgule flottante stockée en 32/64 bits en fonction de l'architecture machine\ntypeof(3. * 4.)\ntypeof(3. * 4)\ntypeof(Float64)\nπ # tapez \"\\pi<tab>\"\ntypeof(π)\nFloat64(π)\nFloat32(π)\ntypeof(1 + 2im)\n[1,2,3]\ntypeof([1,2,3])\n1:5 # itérateur\ntypeof(1:5)\ncollect(1:5)\n0:0.1:1\ntypeof(0:0.1:1)\ncollect(0:0.1:1)\n[4. 5. 6.;7. 8. 9.]\n(1, 2.0, \"test\") # tuple\ntypeof((1, 2.0, \"test\"))\n\n# Caractères et chaînes de caractères\n\n'A'\ntypeof('A')\n\"hello\" \n\ntypeof(\"hello\")\n\n\"racine carrée de 2 : $(sqrt(2))\"\n\n\" √3 : $(√3)\" \n\n\"Hello\" * \" John Doe\"\n\n# Boléens et opérateurs de comparaison | \"==\" | \"!=\" | > | \">=\" | \"<\" | \"<=\" | et de conjonction | \"&\" | \"|\" | \"!\"|\n\n1 > 2\ntypeof(1 > 2)\n\n# supertype et sous-types\n\nsupertype(Int64)\nsubtypes(Integer)\n\n# type utilisateur\n\nstruct MyComplex\n    _real::Float64\n    _imag::Float64\nend\ntypeof(MyComplex)\nMyComplex(1,2)\ntypeof(MyComplex(1, 2))\n\n\n# =============================================================================\n# REGLE DE NOMMAGE(variables, fonctions/méthodes, modules, types, macros)\n# =============================================================================\n#= \n- noms des variables  en minuscule, la séparation des mots dans une variable se fait à l'aide d'un underscore ('_') (\"snake case\")\n- noms de type et de modules commencent par une lettre majuscule, les majuscules séparant les différents mots du nom (exemple \"MonModule\") (\"camel case\")\n- noms des fonctions et macros en minuscule sans underscores.\n- une fonction qui modifie ses arguments s'écrit avec ! à la fin. =#\n\n\n# =============================================================================\n# VARIABLES (étiquettes associées aux valeurs)\n# =============================================================================\n\n# Les variables contenant des nombres scalaires\n\nα = 6 # variable latex-unicode  names — tapez \"\\alpha<tab>\"\ntypeof(α)\nβ = 2α + 1.5\ntypeof(β)\nγ = α + β * im\ntypeof(γ)\nδ = Float64(10)\nδ = MyComplex(1, 2)\nδ._real\n\n# Les vecteurs (tableau de nombres scalaires ou non de dim=1)\n\nv = [1, 17, 32, 15] \n@show v\nsize(v)\nn = length(v)\neltype(v)\nv[2] # accès à l'élément d'index n°2 (indice de départ = 1)\nfor i in 1:n\n\tprintln(\"v[$i] = $(v[i])\")\nend\nfor elt in v\n\tprintln(elt)\nend\nv[2:3] # slicing\nv' # transposée de x\nv2 = Float64[1, 2, 3, 4]\nv + v2\nv' * v2\nsin.(v) # opérateur . de broadcast ( sin de chaque terme)\nv .* v2 # opérateur . de broadcast (ici multiplication terme à terme)\nv3 = ones(Int64, 3)\nv4 = []\ntypeof(v4)\npush!(v4,1)     # => [1]\npush!(v4,2.)     # => [1,2.]\npush!(v4,\"test\")     # => [1,2, \"test\"]\nappend!(v4,v4)\n\n# Les matrices (tableau de nombres scalaires ou non dim=2 )\n\nA = [1. 2 3\n     4 5 6\n     7 8 10]\nni, nj = size(A)\nlength(A)\neltype(A)\nA[2,3]\nA[end,end]\nA[2,:]\nA[:,2]\nA[2:3,2:3]\nA[1:end]\nfor j in 1:nj\n    for i in 1:ni\n        println(\"A[$i,$j] = $(A[i,j])\")\n    end\nend\nfor elt in A\n\tprintln(elt)\nend\nAs = similar(A)\nB = fill(2.0, (3, 3))\nC = A + B\nC = A * B\nsin.(A)\nAA = [A  A] # concaténation horizontale par bloc (hcat)\nAAAA = [AA;AA] # concaténation verticale par bloc (vcat)\nC = [ 1 2 3; 4 5 6; 7 8 9]\nC = [ u * v for u = 0:0.1:1, v = 0:0.1:1]\n\n\n# =============================================================================\n# Programmation \n# =============================================================================\n\nfor i = 1:5\n    println(\"i = $i\")\nend\nfor i = 1:1000\n    println(i)\n    if i >= 5\n       break\n    end\nend\ni = 1\nif i == 1\n    println(\"i = 1\")\nend\ni = 2\nif i != 1\n    println(\"i ≠ 1\")\nelse\n    println(\"i = 1\")\nend\ni = 0\nif i == 1\n    println(\"i = 1\")\nelseif i > 1\n    println(\"i > 1\")\nelse \n    println(\"i < 1\")\nend\ni=0\nwhile i<5\n    global i+=1  # i =i+1\n    println(\"i = $i\")\nend\ni=0 \nwhile i<10\n    global i+=1\n    if i <= 5\n    println(\"i = $i\")\n    else\n        break\n    end\nend\n\n\n# =============================================================================\n# Algèbre linéaire\n# Déterminant, valeurs et vecteurs propres...\n# =============================================================================\n\nusing LinearAlgebra\n\nA = [1. 2. 3.; 4. 5. 6.; 7. 8. 10.]\ndiag(A)\ntr(A)\nsum(A)\ndet(A)\nF = eigen(A)\nF.values \nF.vectors\nb = [3, 2, 1] # a vector\nx = A \\ b # résolution du système linéaire Ax=b\nxx = inv(A) * b # résolution du système linéaire Ax=b\nx - xx\n\n\n# =============================================================================\n# Fonctions, Méthodes, Compilation, Spécialisation, Multiple Dispatch\n# =============================================================================\n\n# Version longue\n\nfunction fun_name(arg1, arg2)\n    tmp = arg1 + arg2\n    return tmp * arg1          # <- le mot-clé return est optionnel, la dernière valeur calculée est retournée\nend    \n\n# Appel\n\nfun_name(2, 3)\n\n# Version courte\n\nfun_name(arg1, arg2) = arg1 * (arg1 + arg2)\n\n# Appel\n\nfun_name(2, 3)\n\n\n# Multiple Dispatch\n# différentes implémentations (méthodes) de la fonction f\n\nfunction f end\nf(x)          = println(\"Generic method with 1 argument : $x\")\nf(x::Integer) = println(\"Specific method with 1 argument (Integer) : $x\")\nf(x, y)       = println(\"Generic method with 2 arguments: $x, $y\")\nf(x::Real, y) = println(\"Specific method with 2 arguments (Real, Any): $x, $y\")\n\nmethods(f)\n\nf(π)\nf(1)\nf(im, 2)\nf(π, [1, 2, 3])\n\n@which f(im, im)\n\nusing BenchmarkTools\n\nfunction my_sum(X)\n    acc = zero(eltype(X)) # zero du type de l'élément de l'argument\n    for x in X\n        acc += x\n    end\n    acc\nend\n\nV = rand(1_000_000)\n@time my_sum(V) # Compilation + Exécution de la fonction  my_sum avec argument de type vecteur (spécialisation)\n@time my_sum(V) # Exécution de la fonction  my_sum\n@time my_sum(V)\n\n@code_native debuginfo = :none my_sum(V)\n\nUR = (1:1_000_000)\n@time my_sum(UR) # # Compilation + Exécution de la fonction  my_sum avec argument de type UnitRange (spécialisation)\n@time my_sum(UR)\n@time my_sum(UR)\n\n@code_native debuginfo = :none my_sum(UR) # code natif différent du précédent  avec même implémnetation => spécialisation\n\n@btime my_sum(UR)\n@btime Base.sum(UR) # pas de magie dans Julia !!\n\nfunction my_sum(X::Array{Float64,2})\n    acc = zero(eltype(X))\n    ni, nj = size(X)\n    for j in 1:nj\n        for i in 1:ni\n            acc += X[i,j]\n        end\n    end\n    acc\nend\nA = rand(Float64, 1_000, 1_000)\nmethods(my_sum)\n@time my_sum(A) # type est connu, donc pas de perte de temps pour le branchement\n@time my_sum(A)\n@time my_sum(A)\n@btime my_sum(A)\n@which my_sum(A)\n\n@code_native debuginfo = :none my_sum(A)\n\n\n# =============================================================================\n# Graphique avec Plots\n#  =============================================================================\n\nusing Plots\nx=0:2π/100:2π\ny=sin.(x)\ntheme(:dark)\nplot(x,y,title=\"Mon premier graphique avec Plots\")\ny=cos.(x)\nplot!(x,y)\n\n\n# =============================================================================\n# Sciences des données \n# https://en.wikibooks.org/wiki/Introducing_Julia/DataFrames\n# =============================================================================\n\n# using Pkg; Pkg.add(\"CSV\"); Pkg.add(\"HTTP\");Pkg.add(\"DataFrames\")\nusing CSV\nusing HTTP\nusing DataFrames\n\ndf = CSV.File(HTTP.get(\"https://raw.githubusercontent.com/nassarhuda/easy_data/master/programming_languages.csv\").body) |> DataFrame\n@show df\n\n\n# =============================================================================\n# Calcul parallèle sur GPU NVidia\n# =============================================================================\n\nusing BenchmarkTools\n\nmcpu = rand(2^12, 2^12)\n@btime mcpu*mcpu\n\n# using Pkg; Pkg.add(\"CUDA\")\nusing CUDA\n\nmgpu = cu(mcpu)\n@btime  mgpu*mgpu\n\n# =============================================================================\n# Calcul symbolique\n# =============================================================================\n\n# using Pkg; Pkg.add(\"SymPy\")\nusing SymPy\n\nE, S, L, θ = symbols(\"E S L θ\",real=true)\nke = E * S / L * Sym[1 0 -1 0;0 0 0 0;-1 0 1 0;0 0 0 0 ]\nRe=Sym[cos(θ) sin(θ) 0 0; -sin(θ) cos(θ) 0 0; 0 0 cos(θ) sin(θ); 0 0 -sin(θ) cos(θ)]\nKe=Re'*ke*Re\n\n# using Pkg; Pkg.add(\"Symbolics\");Pkg.add(\"SymbolicUtils\")\nusing Symbolics\n\n@variables Eₑ Sₑ Lₑ θₑ\nkₑ = Eₑ * Sₑ / Lₑ * [1 0 -1 0;0 0 0 0;-1 0 1 0;0 0 0 0 ]\nRₑ = [cos(θₑ) sin(θₑ) 0 0; -sin(θₑ) cos(θₑ) 0 0; 0 0 cos(θₑ) sin(θₑ); 0 0 -sin(θₑ) cos(θₑ)]\nKₑ = Rₑ' * kₑ * Rₑ", "meta": {"hexsha": "eaf93d0f4163ea8cbcdf1f91c133fb87abd204d8", "size": 9276, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia4FEM.jl", "max_stars_repo_name": "amdeld/FEM.jl", "max_stars_repo_head_hexsha": "4da9eb20bcf66cc1510b1a70ad8ae6579d2c561b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Julia4FEM.jl", "max_issues_repo_name": "amdeld/FEM.jl", "max_issues_repo_head_hexsha": "4da9eb20bcf66cc1510b1a70ad8ae6579d2c561b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia4FEM.jl", "max_forks_repo_name": "amdeld/FEM.jl", "max_forks_repo_head_hexsha": "4da9eb20bcf66cc1510b1a70ad8ae6579d2c561b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5431472081, "max_line_length": 153, "alphanum_fraction": 0.5147692971, "num_tokens": 2989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8962513814471134, "lm_q1q2_score": 0.7770819974867431}}
{"text": "\n\"\"\"\nalpha,beta,vk,vkm1 = LanczosStep!(A::Function,vk,vkm1,beta;sigma=0.0,tol=1e-10)\n\nPerforms a Lanczos step\n\nImplementation is based on Table 2.1 in\n\nChoi, S.-C. T. (2006). \nIterative Methods for Singular Linear Equations and Least-squares Problems. \nPhd thesis, Stanford University.\n\"\"\"\nfunction LanczosStep!(A::Function,vk,vkm1,beta;sigma=0.0,tol=1e-10)\n    n     = length(vk)\n    \n    pk    = A(vk)\n    if sigma!=0.0\n        BLAS.axpy!(n,-sigma,vk,1,pk,1) #pk   -= sigma*vk\n    end\n    \n    alpha = BLAS.dot(n,vk,1,pk,1)  # alpha = dot(vk,pk)\n    BLAS.axpy!(n,-alpha,vk,1,pk,1) # pk   -= alpha*vk\n    BLAS.axpy!(n,-beta,vkm1,1,pk,1)# pk   -= beta*vkm1\n    vkm1  = BLAS.blascopy!(n,vk,1,vkm1,1) # vkm1 = copy(vk)\n    vk    = pk \n    beta  = BLAS.nrm2(n,vk,1)\n    if beta>tol\n         vk /= beta\n    end\n    return alpha, beta,vk,vkm1\nend\n\n\n\"\"\"\nc,s,r = SymOrtho(a,b)\n\nComputes a Givens rotation\n\nImplementation is based on Table 2.9 in\n\nChoi, S.-C. T. (2006). \nIterative Methods for Singular Linear Equations and Least-squares Problems. \nPhd thesis, Stanford University.\n\"\"\"\nfunction symOrtho(a,b)\n    c = 0.0; s = 0.0; r = 0.0\n\tif b==0\n\t\ts = 0.0\n\t\tr = abs(a)\n\t\tc = (a==0) ? c=1.0 : c = sign(a)\n\telseif a == 0\n\t\tc = 0.0\n\t\ts = sign(b)\n\t\tr = abs(b)\n\telseif abs(b) > abs(a)\n\t\ttau = a/b\n\t\ts   = sign(b)/sqrt(1+tau^2)\n\t\tc   = s*tau\n\t\tr   = b/s\n\telseif abs(a) > abs(b)\n\t\ttau = b/a\n\t\tc   = sign(a)/sqrt(1+tau^2)\n\t\ts   = c*tau\n\t\tr   = a/c\n\tend\n\treturn c,s,r\nend", "meta": {"hexsha": "0e89295cfc9532bc50a94636a3f4f2238be79315", "size": 1456, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lanczos.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/KrylovMethods.jl-9a2cd570-f05c-5dc1-9209-93ad6f5727f7", "max_stars_repo_head_hexsha": "10eab6b7804df804257c457648c67e926fa144aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-02-11T21:49:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T07:08:10.000Z", "max_issues_repo_path": "src/lanczos.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/KrylovMethods.jl-9a2cd570-f05c-5dc1-9209-93ad6f5727f7", "max_issues_repo_head_hexsha": "10eab6b7804df804257c457648c67e926fa144aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-06-14T22:48:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:06:49.000Z", "max_forks_repo_path": "src/lanczos.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/KrylovMethods.jl-9a2cd570-f05c-5dc1-9209-93ad6f5727f7", "max_forks_repo_head_hexsha": "10eab6b7804df804257c457648c67e926fa144aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-08-01T09:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T12:17:33.000Z", "avg_line_length": 21.7313432836, "max_line_length": 79, "alphanum_fraction": 0.5851648352, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.7770819897884962}}
{"text": "\nstruct PoissonSolver{DT <: Real}\n    nx::Int\n    Δx::DT\n    xgrid::Vector{DT}\n    ρ::Vector{DT}\n    ϕ::Vector{DT}\n\n    function PoissonSolver{DT}(nx::Int) where {DT}\n        Δx = 1/nx\n        xgrid = collect(0:Δx:1)\n        new(nx, Δx, xgrid, zeros(DT, nx), zeros(DT, nx))\n    end\nend\n\n\nfunction solve!(p::PoissonSolver{DT}, x::AbstractVector{DT}) where {DT}\n    h = fit(Histogram, mod.(x, 1), p.xgrid)\n    p.ρ .= h.weights ./ length(x)\n    ρ̂ = rfft(p.ρ)\n    k² = [(i-1)^2 for i in eachindex(ρ̂)]\n    ϕ̂ = - ρ̂ ./ k²\n    ϕ̂[1] = 0\n    p.ϕ .= irfft(ϕ̂, length(p.ρ))\n    return p\nend\n\n\nfunction eval_field(p::PoissonSolver{DT}, x::DT) where {DT}\n    y = mod(x, one(x))\n    i1 = floor(Int, y / p.Δx) + 1\n    i2 = mod( ceil(Int, y / p.Δx), p.nx) + 1\n    i1 == i2 && (i1 = i1-1)\n    i1 == 0 && (i1 = lastindex(p.ϕ))\n    return - (p.ϕ[i2] - p.ϕ[i1]) / p.Δx\nend\n", "meta": {"hexsha": "98b255d92cfe1843e64af75c55962a4fa7779a08", "size": 857, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5-closures-traits-2-closures/Particles/src/poisson.jl", "max_stars_repo_name": "michakraus/JuliaAtHomeAssignments", "max_stars_repo_head_hexsha": "0ff1563002cdfe477d7a5ab11dbdac62fff92b47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-03T07:40:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-16T23:02:51.000Z", "max_issues_repo_path": "5-closures-traits-6-callbacks/Particles/src/poisson.jl", "max_issues_repo_name": "michakraus/JuliaAtHomeAssignments", "max_issues_repo_head_hexsha": "0ff1563002cdfe477d7a5ab11dbdac62fff92b47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5-closures-traits-6-callbacks/Particles/src/poisson.jl", "max_forks_repo_name": "michakraus/JuliaAtHomeAssignments", "max_forks_repo_head_hexsha": "0ff1563002cdfe477d7a5ab11dbdac62fff92b47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1621621622, "max_line_length": 71, "alphanum_fraction": 0.5192532089, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506726044381, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.777060917075149}}
{"text": "##---begin-Plot-functions---------------------------------------------------------------------------\n\"\"\"\n    chromatogram(t, tR, τR)\n\nCalculate the chromatogram as a sum of gaussian peaks over the time `t` for peaks centered at retention times `tR` and with peak width `τR`.    \n\"\"\"\nfunction chromatogram(t::Array{Float64,1}, tR::Array{Float64,1}, τR::Array{Float64,1})\n\tg(t,tR,τR) = 1/sqrt(2*π*τR^2)*exp(-(t-tR)^2/(2*τR^2))\n\tchromatograms = Array{Array{Float64,1}}(undef, length(tR))\n\tfor j=1:length(tR)\n\t\tchromatograms[j] = g.(t, tR[j], τR[j])\n\tend\n\treturn sum(chromatograms)\nend\n\n\"\"\"\n    plot_chromatogram(peaklist, tlims; annotation=true, number=true, mirror=false, offset=0.0)\n\nPlot the chromatogram of the peaks listed in `peaklist` over the time tupel `tlims = (t_start, t_end`). \n\n# Arguments\n* `peaklist`: DataFrame with the names, retention times and peak widths of the simulated substances.\n* `tlims`: Tuple defining the start and end time of the plotted chromatogram.\n* `annotation`: Boolean, switching the annotation of the peaks on/off; default = true.\n* `number`: Boolean, switching the type of the annotation between _number_ of the substance in the peaklist (`number = true`) or _name_ of the substance (`number = false`); default = true.\n* `mirror`: Boolean, if `mirror = true` the chromatogram is multiplied by `-1`; default = false.\n* `offset`: Float64, this value is added to the chromatogram; default = 0.0.\n\n# Output\nTupel `(p_chrom, t, chrom)`\n* `p_chrom`: the plot of the chromatogram `chrom` over time `t`\n* `t`: Array of time of the chromatogram\n* `chrom`: Array of the abundance values of the chromatogram\n\"\"\"\nfunction plot_chromatogram(peaklist, tlims; annotation=true, number=true, mirror=false, offset=0.0)\n\tt₀ = tlims[1]\n\ttMax = tlims[2]\n\tt = t₀:tMax/10000:tMax\n\tif mirror==true\n\t\tsgn = -1.0\n\telse\n\t\tsgn = 1.0\n\tend\n\tchrom = sgn.*chromatogram(collect(t), peaklist.tR, peaklist.τR) .+ offset\n\tchrom_tR = sgn.*chromatogram(peaklist.tR, peaklist.tR, peaklist.τR) .+ offset\n\tp_chrom = plot(t, chrom, xlabel=\"time in s\", ylabel=\"abundance\", legend=false)\n\tif annotation==true && number==true\n\t\tplot!(p_chrom, annotations = [(peaklist.tR[i], chrom_tR[i], text(i, 10, rotation=0, :center)) for i in 1:length(peaklist.tR)])\n\telseif annotation==true && number==false\n\t\tplot!(p_chrom, annotations = [(peaklist.tR[i], chrom_tR[i], text(peaklist.Name[i], 10, rotation=90, :center)) for i in 1:length(peaklist.tR)])\n\tend\n\treturn p_chrom, t, chrom\nend\n\n\"\"\"\n    plot_chromatogram!(p_chrom, peaklist, tlims; annotation=true, number=true, mirror=false, offset=0.0)\n\nAdd the chromatogram of the peaks listed in `peaklist` over the time tupel `tlims = (t_start, t_end`) to the plot `p_chrom`. \n\n# Arguments\n* `p_chrom`: Plot of an existing chromatogram.\n* `peaklist`: DataFrame with the names, retention times and peak widths of the simulated substances.\n* `tlims`: Tuple defining the start and end time of the plotted chromatogram.\n* `annotation`: Boolean, switching the annotation of the peaks on/off; default = true.\n* `number`: Boolean, switching the type of the annotation between _number_ of the substance in the peaklist (`number = true`) or _name_ of the substance (`number = false`); default = true.\n* `mirror`: Boolean, if `mirror = true` the chromatogram is multiplied by `-1`; default = false.\n* `offset`: Float64, this value is added to the chromatogram; default = 0.0.\n\n# Output\nTupel `(t, chrom)`\n* `t`: Array of time of the chromatogram\n* `chrom`: Array of the abundance values of the chromatogram\n\"\"\"\nfunction plot_chromatogram!(p_chrom, peaklist, tlims; t₀=0.0, annotation=true, number=true, mirror=false, offset=0.0)\n\tt₀ = tlims[1]\n\ttMax = tlims[2]\n\tt = t₀:tMax/10000:tMax\n\tif mirror==true\n\t\tsgn = -1.0\n\telse\n\t\tsgn = 1.0\n\tend\n\tchrom = sgn.*chromatogram(collect(t), peaklist.tR, peaklist.τR) .+ offset\n\tchrom_tR = sgn.*chromatogram(peaklist.tR, peaklist.tR, peaklist.τR) .+ offset\n\tplot!(p_chrom, t, chrom)\n\tif annotation==true && number==true\n\t\tplot!(p_chrom, annotations = [(peaklist.tR[i], chrom_tR[i], text(i, 10, rotation=0, :center)) for i in 1:length(peaklist.tR)])\n\telseif annotation==true && number==false\n\t\tplot!(p_chrom, annotations = [(peaklist.tR[i], chrom_tR[i], text(peaklist.Name[i], 10, rotation=90, :center)) for i in 1:length(peaklist.tR)])\n\tend\n\treturn t, chrom\nend\n\n\"\"\"\n\tplot_flow(par)\n\nCalculate and plot the flow (in mL/min, normalized) of the carrier gas in a GC Column with a program defined in the parameters `par::GasChromatography.Parameters`.\n\"\"\"\nfunction plot_flow(par)\n\tt = 0.0:sum(par.prog.time_steps)/1000.0:sum(par.prog.time_steps)\n\tF = Array{Float64}(undef, length(t))\n\tfor i=1:length(t)\n\t\tF[i] = flow(t[i], par.prog.T_itp, par.prog.Fpin_itp, par.prog.pout_itp, par.col.L, par.col.d, par.col.gas; ng=par.opt.ng, vis=par.opt.vis, control=par.opt.control)\n\tend\n\tp_flow = plot(t, F.*60e6, xlabel=\"time in s\", ylabel=\"column flow in mL/min\", legend=false)\n\treturn p_flow\nend\n\n\"\"\"\n\tplot_pressure(prog)\n\nPlot the inlet and outlet pressure over time of the program `prog::GasChromatographySimulator.Program`.\n\"\"\"\nfunction plot_pressure(par)\n\tt = 0.0:sum(par.prog.time_steps)/1000.0:sum(par.prog.time_steps)\n\tpin = Array{Float64}(undef, length(t))\n\tpout = Array{Float64}(undef, length(t))\n\tfor i=1:length(t)\n\t\tpin[i] = inlet_pressure(t[i], par.prog.T_itp, par.prog.Fpin_itp, par.prog.pout_itp, par.col.L, par.col.d, par.col.gas; ng=par.opt.ng, vis=par.opt.vis, control=par.opt.control)\n\t\tpout[i] = par.prog.pout_itp(t[i])\n\tend\n\tp_press = plot(t, pin, xlabel=\"time in s\", ylabel=\"pressure in Pa\", label=\"inlet\", legend=:right)\n\tplot!(p_press, t, pout, label=\"outlet\")\n\treturn p_press\nend\n\n\"\"\"\n\tplot_temperature(par; selector=\"T(t)\")\n\nPlot the temperature program of the GC Column. \n\n# Arguments\n* `par::GasChromatographySimulator.Parameters`: parameters of the GC system\n* `selector::String`: selection of the plot as:\n\t* `selector = \"T(t)\"`: 2D-plot of temperature `T` over time `t` at inlet (`x=0`) and outlet (`x=L`)\n\t* `selector = \"T(x)\"`: 2D-plot of temperature `T` over column position `x` at the `time_steps` of the program\n\t* `selector = \"T(x,t)\"`: 3D-plot of temperature `T` over column position `x` and `t`\n\"\"\"\nfunction plot_temperature(par::GasChromatographySimulator.Parameters; selector=\"T(t)\")\n\tif selector==\"T(x)\"\n\t\tnx = 0.0:par.col.L/1000:par.col.L\n\t\tp_temp = plot(xlabel=\"x in m\", ylabel=\"T in °C\", legend=:top)\n\t\tfor i=1:length(par.prog.time_steps)\n\t\t\tT = par.prog.T_itp.(nx, cumsum(par.prog.time_steps)[i]).-273.15\n\t\t\tplot!(p_temp, nx, T, label=\"t=$(cumsum(par.prog.time_steps)[i])s\")\n\t\tend\n\telseif selector==\"T(t)\"\n\t\tnt = 0.0:sum(par.prog.time_steps)/1000:sum(par.prog.time_steps)\n\t\tT0 = par.prog.T_itp.(0.0, nt).-273.15\n\t\tp_temp = plot(nt, T0, xlabel=\"t in s\", ylabel=\"T in °C\", legend=:top, label=\"inlet\", c=:red)\n\t\tTL = par.prog.T_itp.(par.col.L, nt).-273.15\n\t\tplot!(p_temp, nt, TL, label=\"outlet\", c=:blue)\n\telseif selector==\"T(x,t)\"\n\t\tnx = 0.0:par.col.L/1000:par.col.L\n\t\tnt = 0.0:sum(par.prog.time_steps)/1000:sum(par.prog.time_steps)\n\t\tT = Array{Float64}(undef, length(nx), length(nt))\n\t\tfor j=1:length(nt)\n\t\t\tfor i=1:length(nx)\n\t\t\t\tT[i,j] = par.prog.T_itp(nx[i], nt[j])-273.15\n\t\t\tend\n\t\tend\n\t\tp_temp = plot(nx, nt, T', st=:surface, xlabel=\"x in m\", ylabel=\"t in s\", zlabel=\"T in °C\")\n\tend\n\treturn p_temp\nend\n\n# functions from GasChromatographyTools.jl:\n\"\"\"\n\tlocal_plots(xx, yy, sol, par)\n\nShow additional 'local' plots of selected `yy` quantities over selected `xx`\nquantities.\n\n# Arguments\n* `xx`: Selected quantity shown on the x-axis. Possible values: \"z\", \"t\", \"T\",\n  \"τ\", \"σ\" and \"u\".\n* `yy`: Selected quantity shown on the y-axis. Possible values: \"z\", \"t\", \"T\",\n  \"τ\", \"σ\" and \"u\".\n* `sol`: The solution of the simulation.\n* `par`: The parameters of the simulated GC-system.\n\"\"\"   \nfunction local_plots(xx, yy, sol, par)\n\tn = size(sol)[1]\n\n\tdf_sol = GasChromatographySimulator.sol_extraction(sol, par)\n\txvalues = Array{Array{Float64,1}}(undef, n)\n\tyvalues = Array{Array{Float64,1}}(undef, n)\n\t\n\tp_add = plot(legend=false)\n\tfor i=1:n\n\t\tif xx==\"z\"\n\t\t\txvalues[i] = df_sol.z[i]\n\t\t\txlabel = \"position z in m\"\n\t\telseif xx==\"t\"\n\t\t\txvalues[i] = df_sol.t[i]\n\t\t\txlabel = \"time t in s\"\n\t\telseif xx==\"T\"\n\t\t\txvalues[i] = par.prog.T_itp.(df_sol.z[i], df_sol.t[i]).-273.15\n\t\t\txlabel = \"temperature T in °C\"\n\t\telseif xx==\"τ\"\n\t\t\txvalues[i] = sqrt.(df_sol.τ²[i])\n\t\t\txlabel = \"peak width τ in s\"\n\t\telseif xx==\"σ\"\n\t\t\txvalues[i] = velocity(df_sol, i, par).*sqrt.(df_sol.τ²[i])\n\t\t\txlabel = \"band width in m\"\n\t\telseif xx==\"u\"\n\t\t\txvalues[i] = velocity(df_sol, i, par)\n\t\t\txlabel = \"solute velocity in m/s\"\n\t\tend\n\t\tif yy==\"z\"\n\t\t\tyvalues[i] = df_sol.z[i]\n\t\t\tylabel = \"position z in m\"\n\t\telseif yy==\"t\"\n\t\t\tyvalues[i] = df_sol.t[i]\n\t\t\tylabel = \"time t in s\"\n\t\telseif yy==\"T\"\n\t\t\tyvalues[i] = par.prog.T_itp.(df_sol.z[i], df_sol.t[i]).-273.15\n\t\t\tylabel = \"temperature T in °C\"\n\t\telseif yy==\"τ\"\n\t\t\tyvalues[i] = sqrt.(df_sol.τ²[i])\n\t\t\tylabel = \"peak width in s\"\n\t\telseif yy==\"σ\"\n\t\t\tyvalues[i] = velocity(df_sol, i, par).*sqrt.(df_sol.τ²[i])\n\t\t\tylabel = \"band width in m\"\n\t\telseif yy==\"u\"\n\t\t\tyvalues[i] = velocity(df_sol, i, par)\n\t\t\tylabel = \"solute velocity in m/s\"\n\t\tend\n\t\tplot!(p_add, xvalues[i], yvalues[i], xlabel=xlabel, ylabel=ylabel, label=par.sub[i].name, m=:o)\n\tend\n\treturn p_add\nend\n\n\"\"\"\n\tvelocity(df_sol, i, par)\n\nCalculate the velocity (in m/s) coressponding to solution of the `i-th` sunstance of a\nGC-system defined by `par`.\n\"\"\" \nfunction velocity(df_sol, i, par)\n\tx = df_sol.z[i]\n\tt = df_sol.t[i]\n\tT_itp = par.prog.T_itp\n\tpin_itp = par.prog.Fpin_itp\n\tpout_itp = par.prog.pout_itp\n\tL = par.col.L\n\td = par.col.d\n\tdf = par.col.df\n\tgas = par.col.gas\n\tΔCp = par.sub[i].ΔCp\n\tTchar = par.sub[i].Tchar\n\tθchar = par.sub[i].θchar\n\tφ₀ = par.sub[i].φ₀\n\tu = Array{Float64}(undef, length(x))\n\tfor j=1:length(x)\n\t\tu[j] = 1/GasChromatographySimulator.residency(x[j], t[j], T_itp, pin_itp, pout_itp, L, d, df, gas, ΔCp, Tchar, θchar, φ₀; ng=par.opt.ng, vis=par.opt.vis, control=par.opt.control)\n\tend\n\treturn u\nend", "meta": {"hexsha": "323c6e71a129bfa7af66a6a0e2833dc2da50f643", "size": 9968, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Plot.jl", "max_stars_repo_name": "JanLeppert/GasChromatographySimulator.jl", "max_stars_repo_head_hexsha": "b9bd4917b687d74ad288e2130e07e78e8c8ee4a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-03-18T20:39:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T00:13:21.000Z", "max_issues_repo_path": "src/Plot.jl", "max_issues_repo_name": "JanLeppert/GasChromatographySimulator.jl", "max_issues_repo_head_hexsha": "b9bd4917b687d74ad288e2130e07e78e8c8ee4a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2022-01-27T14:57:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T11:08:27.000Z", "max_forks_repo_path": "src/Plot.jl", "max_forks_repo_name": "JanLeppert/GasChromatographySimulator.jl", "max_forks_repo_head_hexsha": "b9bd4917b687d74ad288e2130e07e78e8c8ee4a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4864864865, "max_line_length": 188, "alphanum_fraction": 0.6779695024, "num_tokens": 3293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145364, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7770609062819666}}
{"text": "## these are differently named than SymPy or missing or ...\n\n\nBase.abs(x::SymbolicObject) = sympy.Abs(x)\nBase.abs2(x::SymbolicObject) = x * conj(x)\nBase.max(x::Sym, a) = sympy.Max(x, a)\nBase.min(x::Sym, a) = sympy.Min(x, a)\n\n\nBase.cbrt(x::Sym) = x^(1//3)\nBase.ceil(x::Sym) = sympy.ceiling(x)\n\n## Trig\nBase.asech(z::Sym) = log(sqrt(1/z-1)*sqrt(1/z+1) + 1/z)\nBase.acsch(z::Sym) = log(sqrt(1+1/z^2) + 1/z) ## http://mathworld.wolfram.com/InverseHyperbolicCosecant.html\nBase.atan(y::Sym, x) = sympy.atan2(y,x)\n\n\nBase.sinc(x::Sym) = iszero(x) ? one(x) : sin(PI*x)/(PI*x)\ncosc(x::Sym) = diff(sinc(x))\n\nBase.sincos(x::Sym) = (sin(x), cos(x))\nBase.sinpi(x::Sym) = sympy.sin(x*PI)\nBase.cospi(x::Sym) = sympy.cos(x*PI)\ndegree_variants = (:sind, :cosd, :tand, :cotd, :secd, :cscd,\n                   :asind, :acosd, :atand, :acotd, :asecd, :acscd)\n\nfor  methvar in degree_variants\n    meth = Symbol(String(methvar)[1:end-1])\n    @eval begin\n        (Base.$methvar)(ex::SymbolicObject) = ($meth)((PI/180)*ex)\n    end\nend\n\nBase.rad2deg(x::Sym) = (x * 180) / PI\nBase.deg2rad(x::Sym) = (x * PI) / 180\n\nBase.hypot(x::Sym, y::Number) = hypot(promote(x,y)...)\nBase.hypot(xs::Sym...) = sqrt(sum(abs(xᵢ)^2 for xᵢ ∈ xs))\n\n## exponential\nBase.log1p(x::Sym) = sympy.log(1 + x)\nBase.log(x::Sym) = sympy.log(x)\nBase.log(b::Number, x::Sym) = sympy.log(x, b)\nBase.log2(x::SymbolicObject) = log(2,x)\nBase.log10(x::SymbolicObject) = log(10,x)\n\n\n\n\n## calculus.\n## use a pair for limit x=>0\nlimit(x::SymbolicObject, xc::Pair, args...;kwargs...) = limit(x, xc[1], xc[2], args...;kwargs...)\n## allow a function\nlimit(f::Function, x::Sym, c;kwargs...) = limit(Sym(f(x)), x, c; kwargs...)\nfunction  limit(f::Function, c;kwargs...)\n    @vars  x\n    limit(f, x, c; kwargs...)\nend\n\n## This is  type piracy  and a bad   idea\nfunction Base.diff(f::Function, n::Integer=1)\n    @vars x\n    sympy.diff(f(x), x, n)\nend\n\n## integrate(ex,a,b)\nfunction integrate(ex::SymbolicObject, a::Number, b::Number)\n    fs = free_symbols(ex)\n    if length(fs) !== 1\n        @warn \"Need exactly on free symbol. Use `integrate(ex, (x, a, b))` instead\"\n        return\n    end\n    integrate(ex, (fs[1], a, b))\nend\nfunction integrate(f::Function, a::Number, b::Number)\n    @vars x\n    sympy.integrate(f(x), (x, a, b))\nend\nfunction integrate(f::Function)\n    @syms  x\n    sympy.integrate(f(x), x)\nend\n\n\n## Add interfaces for solve, nonlinsolve when vector of equations passed in\n\n## An alternative to Eq(lhs, rhs) following Symbolics.jl\n\"\"\"\n    lhs ~ rhs\n\nSpecify an equation.\n\nAlternative syntax to `Eq(lhs, rhs)` or `lhs ⩵ rhs` (`\\\\Equal[tab]`) following `Symbolics.jl`.\n\"\"\"\nBase.:~(lhs::Number, rhs::SymbolicObject) = Eq(lhs, rhs)\nBase.:~(lhs::SymbolicObject, rhs::Number) = Eq(lhs, rhs)\nBase.:~(lhs::SymbolicObject, rhs::SymbolicObject) = Eq(lhs, rhs)\n\n\n\"\"\"\n    solve\n\nUse `solve` to solve algebraic equations.\n\nExamples:\n\n```julia\njulia> using SymPy\n\njulia> @syms x y a b c d\n(x, y, a, b, c, d)\n\njulia> solve(x^2 + 2x + 1, x) # [-1]\n1-element Vector{Sym}:\n -1\n\njulia> solve(x^2 + 2a*x + a^2, x) # [-a]\n1-element Vector{Sym}:\n -a\n\njulia> solve([a*x + b*y-3, c*x + b*y - 1], [x,y]) # Dict(y => (a - 3*c)/(b*(a - c)),x => 2/(a - c))\nDict{Any, Any} with 2 entries:\n  y => (a - 3*c)/(a*b - b*c)\n  x => 2/(a - c)\n\n```\n\n!!! note\n    A very nice example using `solve` is a [blog](https://newptcai.github.io/euclidean-plane-geometry-with-julia.html) entry on [Napolean's theorem](https://en.wikipedia.org/wiki/Napoleon%27s_theorem) by Xing Shi Cai.\n\"\"\"\nsolve() = ()\nsolve(V::Vector{T}, args...; kwargs...) where {T <: SymbolicObject} =\n    sympy.solve(V, args...; kwargs...)\n\n\"\"\"\n    nonlinsolve\n\nNote: if passing variables in use a tuple (e.g., `(x,y)`) and *not* a vector (e.g., `[x,y]`).\n\"\"\"\nnonlinsolve(V::AbstractArray{T,N}, args...; kwargs...) where {T <: SymbolicObject, N} =\n    sympy.nonlinsolve(V, args...; kwargs...)\n\nlinsolve(V::AbstractArray{T,N}, args...; kwargs...) where {T <: SymbolicObject, N} =\n    sympy.linsolve(V, args...; kwargs...)\nlinsolve(Ts::Tuple, args...; kwargs...) where {T <: SymbolicObject} =\n    sympy.linsolve(Ts, args...; kwargs...)\n\n\n## dsolve allowing initial condiation to be specified\n\n\"\"\"\n   dsolve(eqn, var, args..,; ics=nothing, kwargs...)\n\nCall `sympy.dsolve`.\n\nThe initial conditions are specified with a dictionary.\n\nExample:\n\n```jldoctest dsolve\njulia> using SymPy\n\njulia> @syms α, x, f(), g()\n(α, x, f, g)\n\njulia> ∂ = Differential(x)\nDifferential(x)\n\njulia> eqn = ∂(f(x)) ~ α * x\nd\n──(f(x)) = x⋅α\ndx\n```\n\n```julia\njulia> dsolve(eqn)\n             2\n            x ⋅α\nf(x) = C₁ + ────\n             2\n```\n\n```jldoctest dsolve\njulia> dsolve(eqn(α=>2); ics=Dict(f(0)=>1)) |> print # fill in parameter, initial condition\nEq(f(x), x^2 + 1)\n\njulia> eqn = ∂(∂(f(x))) ~ -f(x); print(eqn)\nEq(Derivative(f(x), (x, 2)), -f(x))\n\njulia> dsolve(eqn)\nf(x) = C₁⋅sin(x) + C₂⋅cos(x)\n\njulia> dsolve(eqn; ics = Dict(f(0)=>1, ∂(f)(0) => -1))\nf(x) = -sin(x) + cos(x)\n\njulia> eqn = ∂(∂(f(x))) - f(x) - exp(x);\n\njulia> dsolve(eqn, ics=Dict(f(0) => 1, f(1) => Sym(1//2))) |> print # not just 1//2\nEq(f(x), (x/2 + (-exp(2) - 2 + E)/(-2 + 2*exp(2)))*exp(x) + (-E + 3*exp(2))*exp(-x)/(-2 + 2*exp(2)))\n```\n\nSystems\n\n```jldoctest dsolve\njulia> @syms x() y() t g\n(x, y, t, g)\n\njulia> ∂ = Differential(t)\nDifferential(t)\n\njulia> eqns = [∂(x(t)) ~ y(t), ∂(y(t)) ~ x(t)]\n2-element Vector{Sym}:\n Eq(Derivative(x(t), t), y(t))\n Eq(Derivative(y(t), t), x(t))\n\njulia> dsolve(eqns)\n2-element Vector{Sym}:\n Eq(x(t), -C1*exp(-t) + C2*exp(t))\n  Eq(y(t), C1*exp(-t) + C2*exp(t))\n\njulia> dsolve(eqns, ics = Dict(x(0) => 1, y(0) => 2))\n2-element Vector{Sym}:\n Eq(x(t), 3*exp(t)/2 - exp(-t)/2)\n Eq(y(t), 3*exp(t)/2 + exp(-t)/2)\n\njulia> eqns = [∂(∂(x(t))) ~ 0, ∂(∂(y(t))) ~ -g]\n2-element Vector{Sym}:\n  Eq(Derivative(x(t), (t, 2)), 0)\n Eq(Derivative(y(t), (t, 2)), -g)\n\njulia> dsolve(eqns)  # can't solve for initial conditions though! (NotAlgebraic)\n2-element Vector{Sym}:\n           x(t) = C₁ + C₂⋅t\n Eq(y(t), C3 + C4*t - g*t^2/2)\n\njulia> @syms t x() y()\n(t, x, y)\n\njulia> eq = (∂(x)(t) ~ x(t)*y(t)*sin(t), ∂(y)(t) ~ y(t)^2 * sin(t))\n(Eq(Derivative(x(t), t), x(t)*y(t)*sin(t)), Eq(Derivative(y(t), t), y(t)^2*sin(t)))\n```\n\n```julia\njulia> dsolve(eq)  # returns a set to be `collect`ed:\nPyObject {Eq(x(t), -exp(C1)/(C2*exp(C1) - cos(t))), Eq(y(t), -1/(C1 - cos(t)))}\n```\n\n```julia\njulia> dsolve(eq) |> collect\n2-element Vector{Any}:\n Eq(x(t), -exp(C1)/(C2*exp(C1) - cos(t)))\n               Eq(y(t), -1/(C1 - cos(t)))\n```\n\n\"\"\"\nfunction dsolve(eqn, args...;\n                ics::Union{Nothing, AbstractDict, Tuple}=nothing,\n                kwargs...)\n    if isa(ics, Tuple) # legacy\n        _dsolve(eqn, args...; ics=ics, kwargs...)\n    else\n        sympy.dsolve(eqn, args...; ics=ics, kwargs...)\n    end\nend\n\nrhs(x::SymbolicObject) = pycall_hasproperty(x, :rhs) ? x.rhs : x\nlhs(x::SymbolicObject) = pycall_hasproperty(x, :lhs) ? x.lhs : x\n\n\nexport dsolve, rhs, lhs\n\n## ---- deprecate ----\n## used with ics=(u,0,1) style\nfunction _dsolve(eqn::Sym, args...; ics=nothing, kwargs...)\n\n    Base.depwarn(\"Use of tuple(s), `(u, x₀, u₀)`, to specify initial conditions is deprecated. Use a dictionary: `ics=Dict(u(x₀) => u₀)`.\", :_dsolve)\n\n    if isempty(args)\n        var = first(free_symbols(eqn))\n    else\n        var = first(args)\n    end\n    # var might be f(x) or x, we want `x`\n    if Introspection.classname(var) != \"Symbol\"\n        var = first(var.args)\n    end\n    ## if we have one initial condition, can be passed in a (u,x0,y0) *or* ((u,x0,y0),)\n    ## if more than oneq a tuple of tuples\n    if eltype(ics) <: Tuple\n        __dsolve(eqn, var, ics; kwargs...)\n    else\n        __dsolve(eqn, var, (ics,); kwargs...)\n        end\nend\n\nfunction __dsolve(eqn::Sym, var::Sym, ics; kwargs...)\n    if length(ics) == 0\n        throw(ArgumentError(\"\"\"Some initial value specification is needed.\nSpecifying the function, as in `dsolve(ex, f(x))`, is deprecated.\nUse `sympy.dsolve(ex, f(x); kwargs...)` directly for that underlying interface.\n\"\"\"))\n    end\n\n    out = sympy.dsolve(eqn; kwargs...)\n    ord = sympy.ode_order(eqn, var)\n\n    ## `out` may be an array of solutions. If so we do each one.\n    ## we want to use an array for output only if needed\n    if !isa(out, Array)\n        return _solve_ivp(out, var, ics,ord)\n    else\n        output = Sym[]\n        for o in out\n            a = _solve_ivp(o, var, ics,ord)\n            a != nothing && push!(output, a)\n        end\n        return length(output) == 1 ? output[1] : output\n    end\nend\n\n## Helper.\n## out is an equation in var with constants. Args are intial conditions\n## Return `nothing` if initial condition is not satisfied (found by `solve`)\nfunction _solve_ivp(out, var, args, o)\n\n    eqns = Sym[(diff(out.rhs(), var, f.n))(var=>x0) - y0 for (f, x0, y0) in args]\n    sols = solve(eqns, Sym[\"C$i\" for i in 1:o], dict=true)\n    if length(sols) == 0\n       return nothing\n    end\n\n    ## massage output\n    ## Might have more than one solution, though unlikely. But if we substitute a variable\n    ## for y0 we will get an array back from solve which may have length 1.\n    if isa(sols, Array)\n        if length(sols) == 1\n            sols = sols[1]\n        else\n            return [out([Pair(k,v) for (k,v) in sol]...) for sol in sols]\n        end\n    end\n\n    out([Pair(k,v) for (k,v) in sols]...)\nend\n\n## For System Of Ordinary Differential Equations\n## may need to collect return values\n# dsolve(eqs::Union{Array, Tuple}, args...; kwargs...) = sympy.dsolve(eqs, args...; kwargs...)\n", "meta": {"hexsha": "37757266dd39dbcdcba60d4b06b966c113b062dd", "size": 9473, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mathfuns.jl", "max_stars_repo_name": "fatteneder/SymPy.jl", "max_stars_repo_head_hexsha": "8b25bb9d0941443404de1b3a79205fee32080f6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mathfuns.jl", "max_issues_repo_name": "fatteneder/SymPy.jl", "max_issues_repo_head_hexsha": "8b25bb9d0941443404de1b3a79205fee32080f6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mathfuns.jl", "max_forks_repo_name": "fatteneder/SymPy.jl", "max_forks_repo_head_hexsha": "8b25bb9d0941443404de1b3a79205fee32080f6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0657142857, "max_line_length": 217, "alphanum_fraction": 0.5866145888, "num_tokens": 3403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909757, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7770499015822392}}
{"text": "# # Hypercube Examples (Bravais Lattice)\n\n# ## Preamble\nusing LatticeTools\nusing Plots\n\nmkpath(\"example_hypercube\")\n\nfunction draw_hypercube(hypercube::Hypercube, coordinates::AbstractMatrix{<:Integer})\n    xlim = (minimum(coordinates[1,:]) - 3.5, maximum(coordinates[1,:]) + 3.5)\n    ylim = (minimum(coordinates[2,:]) - 3.5, maximum(coordinates[2,:]) + 3.5)\n    boundary = let\n        r0 = [0,0]\n        r1 = hypercube.shape_matrix[:,1]\n        r2 = hypercube.shape_matrix[:,2]\n        hcat(r0, r1, r1 .+ r2, r2, r0)\n    end\n    fig = plot(boundary[1,:], boundary[2,:], label=\"\", size=(400, 400))\n    for Ri in Iterators.product(-1:1, -1:1)\n        alpha = (Ri == (0,0)) ? 1.0 : 0.1\n        Rr = hypercube.shape_matrix * [Ri...]\n        scatter!(coordinates[1,:] .+ Rr[1], coordinates[2,:] .+ Rr[2], aspect_ratio=1, markersize=12, xlim=xlim, ylim=ylim, markeralpha=alpha, label=\"\")\n        annotation = []\n        for i in 1:size(coordinates, 2)\n            x = coordinates[1,i] + Rr[1]\n            y = coordinates[2,i] + Rr[2]\n            if xlim[1] < x < xlim[2] && ylim[1] < y < ylim[2]\n                push!(annotation, (x, y, text(\"$i\", 8, :black, :center)))\n            end\n        end\n        if !isempty(annotation)\n            annotation = [annotation...]\n            annotate!(annotation)\n        end\n    end\n    fig\nend\n\n\n# ## (4,-4) x (4,4)\nsize_matrix = [ 4 4; -4 4]\nhypercube = Hypercube(size_matrix)\ngenerator_translations = find_generators(hypercube)\ncoordinates = generate_coordinates(hypercube, generator_translations)\ncoordmat = hcat(coordinates...)\nprintln(\"All elements\")\nfor (i, c) in enumerate(coordinates)\n    println(\"$i : $c\")\nend\nprintln(\"Generator translations\")\nfor (it, t) in enumerate(eachcol(generator_translations))\n    println(\"t($it) = $t\")\nend\ndraw_hypercube(hypercube, coordmat)\nsavefig(\"example_hypercube/bravais_(4,-4)x(4,4).svg\")\n\n\n# ![](example_hypercube//bravais_(4,-4)x(4,4).svg)\n\n\n# ## (2,-2) x (2,4)\nsize_matrix = [ 2 2; -2 4]\nhypercube = Hypercube(size_matrix)\ngenerator_translations = find_generators(hypercube)\ncoordinates = generate_coordinates(hypercube, generator_translations)\ncoordmat = hcat(coordinates...)\ndraw_hypercube(hypercube, coordmat)\nprintln(\"All elements\")\nfor (i, c) in enumerate(coordinates)\n    println(\"$i : $c\")\nend\nprintln(\"Generator translations\")\nfor (it, t) in enumerate(eachcol(generator_translations))\n    println(\"t($it) = $t\")\nend\ndraw_hypercube(hypercube, coordmat)\nsavefig(\"example_hypercube/bravais_(2,-2)x(2,4).svg\")\n\n\n# ![](example_hypercube//bravais_(2,-2)x(2,4).svg)\n", "meta": {"hexsha": "fc5aa2a0ac5d8f38b0c6cd1d9fd7de36574e4c40", "size": 2552, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example_hypercube.jl", "max_stars_repo_name": "kyungminlee/LatticeTools.jl", "max_stars_repo_head_hexsha": "9880b9b2eb55f853ee667bdde70e911487eb724f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-01T01:01:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T22:33:37.000Z", "max_issues_repo_path": "examples/example_hypercube.jl", "max_issues_repo_name": "kyungminlee/LatticeTools.jl", "max_issues_repo_head_hexsha": "9880b9b2eb55f853ee667bdde70e911487eb724f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-28T05:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T05:04:26.000Z", "max_forks_repo_path": "examples/example_hypercube.jl", "max_forks_repo_name": "kyungminlee/LatticeTools.jl", "max_forks_repo_head_hexsha": "9880b9b2eb55f853ee667bdde70e911487eb724f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5061728395, "max_line_length": 152, "alphanum_fraction": 0.637539185, "num_tokens": 788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.777039138600861}}
{"text": "using ProgressBars, Plots, StatsBase, Statistics, LaTeXStrings, JLD\n\n\nfunction RandomWalker(P,TimeSteps)\n    X = 0\n    for i in 1:TimeSteps\n        X += sample([1,-1], Weights([P,1-P]))\n    end\n    return X\nend\n\nfunction Linear_fit(X, Y)\n    A = [hcat(X) reshape(ones(length(X)), length(X), 1)]\n    b = reshape(hcat(Y), length(Y), 1)\n    line = (A \\ b)\n    return line\nend\n\nPList = [0.1,0.3,0.5,0.7,0.9]\nN = 100000\nTimeSteps = 10000\nRES = [[] for i = 1:5]\n\nfor n in 1:5\n    P = PList[n]\n    for i in ProgressBar(1:N)\n        push!(RES[n],RandomWalker(P,TimeSteps))\n    end\n    push!(Avg,mean(RES[n]))\nend\n\nsave(\"../../Data/Q4/Q4-RW.jld\", \"Data\", RES)\n\nLine = round.(Linear_fit(PList,Avg))\n\np1 = histogram(RES[1],bins = 50, label = L\"P = %$(PList[1]), \\ l = \\tau = 1\", xlabel=L\"\\langle X_{final} \\rangle_{(P)}\", ylabel = L\"Number\", c = :steelblue)\np2 = histogram(RES[2],bins = 50, label = L\"P = %$(PList[2]), \\ l = \\tau = 1\", xlabel=L\"\\langle X_{final} \\rangle_{(P)}\", ylabel = L\"Number\", c = :purple)\np3 = histogram(RES[3],bins = 50, label = L\"P = %$(PList[3]), \\ l = \\tau = 1\", xlabel=L\"\\langle X_{final} \\rangle_{(P)}\", ylabel = L\"Number\", c = :red)\np4 = histogram(RES[4],bins = 50, label = L\"P = %$(PList[4]), \\ l = \\tau = 1\", xlabel=L\"\\langle X_{final} \\rangle_{(P)}\", ylabel = L\"Number\", c = :gold)\np5 = histogram(RES[5],bins = 50, label = L\"P = %$(PList[5]), \\ l = \\tau = 1\", xlabel=L\"\\langle X_{final} \\rangle_{(P)}\", ylabel = L\"Number\", c = :green)\np6 = begin\n    plot(PList,Avg,label = L\"Y = %$(round(Line[1],digits=3)) X %$(round(Line[2],digits=3))\", c = :black)\n    scatter!(PList,Avg,label = L\"Data\\ Points\",legend = 140,xlabel = L\"P\",ylabel = L\"\\langle \\overline{X_{final}} \\rangle_{(P)}\",c = :steelblue)\nend\n\nPmain1 = begin\n    plot(plot(plot(p1,p2,layout=(1,2)),plot(p3,p4,layout=(1,2)),plot(p5,p6,layout=(1,2)),layout=(3,1)))\n    plot!(plot_title = L\"Distribution\\ of\\ X_{final}\\ (N = %$N\\ , Time\\ Steps=%$TimeSteps)\",size = (1000,1000))\nend\nsavefig(Pmain1,\"../../Figs/Q4/Q4-tot.pdf\")\n", "meta": {"hexsha": "e117d9b0bf73cb107fbc183b2ac8cf715baf9408", "size": 2001, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSet4/Codes/Q4/Q4-RW.jl", "max_stars_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_stars_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSet4/Codes/Q4/Q4-RW.jl", "max_issues_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_issues_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSet4/Codes/Q4/Q4-RW.jl", "max_forks_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_forks_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-21T11:07:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-21T11:07:08.000Z", "avg_line_length": 39.2352941176, "max_line_length": 156, "alphanum_fraction": 0.5887056472, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7770380491068741}}
{"text": "function readfile(filename, row::Int64)\n    return readdlm(filename)[:,row]\nend\n\nfunction pn(x::Y, xvalues::T, yvalues::T , n::Int64) where {T, Y}\n    @assert length(xvalues)==length(yvalues)\n    l = length(xvalues)\n    denom = 1.0\n    numer = 1.0\n    for i in 1:l\n        if i != n\n            denom = denom*(xvalues[n]-xvalues[i])\n        end\n    end\n    for i in 1:l\n        if i != n\n            numer = numer*(x-xvalues[i])\n        end\n    end\n    return yvalues[n]*numer/denom\nend\n\nfunction lagrangeinterpolation(x::Y, xvalues::T,yvalues::T) where {T,Y}\n    @assert length(xvalues)==length(yvalues)\n    l = length(xvalues)\n    sumpn = 0.0\n    for i in 1:l\n        sumpn = sumpn + pn(x, xvalues, yvalues, i)\n    end\n    return sumpn\nend\n\n", "meta": {"hexsha": "0881f0e501d0edab998515d75e58b3dc9b40b3a0", "size": 743, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "hjk971/lpinterpolate", "max_stars_repo_head_hexsha": "6aa2afa4e649fa62d63ef5e879b9abcb772dac56", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions.jl", "max_issues_repo_name": "hjk971/lpinterpolate", "max_issues_repo_head_hexsha": "6aa2afa4e649fa62d63ef5e879b9abcb772dac56", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions.jl", "max_forks_repo_name": "hjk971/lpinterpolate", "max_forks_repo_head_hexsha": "6aa2afa4e649fa62d63ef5e879b9abcb772dac56", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-09T01:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T01:47:19.000Z", "avg_line_length": 22.5151515152, "max_line_length": 71, "alphanum_fraction": 0.5760430686, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7770380453947044}}
{"text": "#' # Optimizing water networks with Knitro\n#'\n#' This notebook explains how to solve effectively NLP and MINLP\n#' problem with the Knitro solver.\n#'\n#' The problem studied hereafter was originally designed by\n#' Pierre Carpentier, for educational purposes.\n#' The original code is available [here](http://perso.ensta-paristech.fr/~pcarpent/TP_Reseau/ENSMP/).\n#' The author credits him for the following tutorial.\n#'\n#' # Description of the problem\n#'\n#' The tutorial studies the optimization of water flows in a water\n#' distribution network (at steady state). The optimizer aims at\n#' minimizing the network's energy while statisfying some linear constraints\n#' corresponding to Kirchhoff's first law.\n#'\n#' Let $G = (N, E)$ be an oriented graph. We note $n = |E|$ the number of\n#' arcs and $m = |N|$ the number of nodes in this graph.\n#'\n#' We suppose that the network has $r$ tanks storing some waters to fulfill\n#' the demands in $d$ nodes (distinct from the tanks).\n#' We split the set of nodes $N$ accordingly:\n#' $$\n#' N = N_r \\cup N_d.\n#' $$\n#'\n#' We suppose further that the graph is *connected*, implying\n#' $$\n#' n \\geq m - 1 .\n#' $$\n#' We note $A \\in R^{m \\times n}$ the incidence matrix of the graph.\n#'\n#' Lets introduce physical variables to describe further the water network.\n#' - the vector of resulting flows at nodes, denoted $f = (f_d, f_r)$. $f_d$ is given for demands' nodes.\n#' - the vector of pressures at nodes, denoted $p = (p_d, p_r)$. Pressures $p_r$ are given for the reservoirs.\n#' - the vector of resistances in all arcs, denoted $r$ (parameters of the problem)\n#' - the vector of flows across arcs, denoted $q$.\n#'\n#' The decision variable is the vector of flows $q$.\n#'\n#' ### Constraints\n#'\n#' The first Kirchhoff law states that:\n#' $$\n#' A q -f = 0,\n#' $$\n#' as we suppose that no accumulation occurs in the nodes.\n#' The second Kirchhoff law takes into account the losses in the pipes,\n#' which is given on each arc by a function $\\phi_{alpha}$ (corresponding\n#' to the Colebrooks law):\n#' $$\n#' \\phi_{\\alpha}(q_\\alpha) = r_\\alpha q_\\alpha | q_\\alpha |\n#' $$\n#' The second Kirchhoff law writes, in a vectorial manner,\n#' $$\n#' A^\\top p + r \\circ q \\circ | q | = 0\n#' $$\n#'\n#' ### Objective\n#' On each arc $\\alpha$, we define the energy function $\\Phi_\\alpha$\n#' as\n#' $$\n#' \\Phi_\\alpha(q_\\alpha) = \\dfrac{1}{3} r_\\alpha q_\\alpha^2 | q_\\alpha |\n#' $$\n#' On the graph, the overall energy equates\n#' $$\n#' J(q, f_r) = \\dfrac{1}{3} q^\\top (r \\circ q \\circ | q |) + p_r^\\top f_r\n#' $$\n#'\n#' The global problem writes\n#' $$\n#' \\min_{q} \\dfrac{1}{3} q^\\top (r \\circ q \\circ | q |) + p_r^\\top f_r \\qquad\n#' s.t. \\quad Aq  - f = 0\n#' $$\n#'\n#' ### Reformulation\n#' By applying some mathematical tricks, we are able to reformulate\n#' the problem in the following manner.\n#'\n#' By considering some properties of the overall graph, we split the vector\n#' of flows in two $q = (q_T, q_C)$, where $q_T$ depends linearly on $q_C$.\n#' Then, we are able to prove the existence of a matrix $B$ and a fixed\n#' vector $q_0$ such that the vector of flows on arcs writes\n#' $$\n#' q = q_0 + B \\; q_C\n#' $$\n#' By using this formulation, we can reduce the dimension of the search\n#' space by selecting as decision variable the subvector $q_C$ instead of $q$.\n#'\n#' Note that the problem becomes also constraint-free, as the vector $q$\n#' statisfying the previous equation sastifies also the first Kirchhoff law.\n#'\n#' We reformulate the optimization problem as\n#' $$\n#' \\min_{q_c} \\dfrac{1}{3} q^\\top (r \\circ q \\circ | q |) + p_r^\\top f_r \\qquad\n#' s.t. \\quad q = q_0 + B q_C\n#' $$\n\n\n\n#' ---\n#' # Numerical resolution\n#' We start by importing JuMP and Knitro.\n\nusing JuMP, KNITRO\n\n#' Import data.\ninclude(\"data.jl\");\n\n#' Plotting utilities\nusing Pkg\n\n# Turned off by default.\nPLOT_GRAPH = false\nif haskey(Pkg.installed(), \"PyPlot\")\n    PLOT_GRAPH = true\n    include(\"utils.jl\");\nend\n\n\n#' ---\n#' ## First case study: the non-linear problem\n#'\n#' Define Knitro Optimizer with JuMP.\nmodel = Model(with_optimizer(KNITRO.Optimizer, outlev=3))\n\n#' Write non-linear optimization problem first.\n# Parameters.\nα1 = Ar' * pr\n# Dimension of the problem.\nnx = n - md\n@variable(model, qc[1:nx])\n# Add dummy variable in the model...\n@variable(model, q[1:n])\n# ... as we restrict the problem inside a 9-dimensional manifold:\n@constraint(model, q .== q0 + B*qc)\n@NLobjective(model, Min,\n             sum(r[i] * abs(q[i]) * q[i]^2 / 3 + α1[i] * q[i] for i in 1:n))\noptimize!(model)\n\n#' Display results\nif PLOT_GRAPH\n    optimal_flow = JuMP.value.(q)\n    fig = figure()\n    plot_network(flow=optimal_flow)\n    display(fig)\nend\n\n#' Observe that some arcs seem almost useless here...\n\n\n#' ---\n#' ## Extension to Mixed-integer non-linear programming\n\n#' We were able to quickly formule the NLP problem with JuMP, and Knitro\n#' finds a solution in few iterations.\n#' We now modify slightly the problem. Consider the $n$ arcs inside the graph.\n#' The questions are:\n# - *how many arcs in $E$ can we remove before the problem becomes infeasible?*\n# - *how much is the cost impacted by arc removals?*\n\n#' We define hereafter the MINLP version of the problem.\n# Add a maximum flows through the pipes\nconst QMAX = 10.\n\nfunction load_mip_model!(model::JuMP.Model; nremovals=3)\n    # Reconsider the NLP problem introduced previously.\n    @variable(model, qc[1:nx])\n    @variable(model, q[1:n])\n    @constraint(model, q .== q0 + B*qc)\n\n    # Introduce switch: $z$ is set to 0 if the corresponding arc is removed\n    # from the graph.\n    @variable(model, z[1:n], Bin)\n\n    # Bounds the abs flows through the arcs by QMAX\n    # The constraints write:\n    # | q | <= q_{max} * z\n    # Note that z_a = 0 implies that q_a = 0.\n    @constraint(model,  q .<= QMAX * z)\n    @constraint(model, -q .<= QMAX * z)\n    # Ensure that we remove exactly nremovals arcs.\n    @constraint(model, sum(z) == n - nremovals)\n\n    # Same cost as previously.\n    @NLobjective(model, Min,\n                 sum(r[i] * abs(q[i]) * q[i]^2 / 3 + α1[i] * q[i] for i in 1:n))\n    return\nend\n\n#' **Optimization related remark:** Note that the constraint\n#' $$\n#' | q | \\leq q_{max} \\; z\n#' $$\n#' could be reformulated as a complementarity constraint (also supported by Knitro\n#' but not natively by JuMP).\n\n#' **Physics related remark:** We are a bit loosy with the physics of the\n#' problem if we remove the arcs in the previous manner. Imagine that for\n#' a given arc $a \\in E$, $z_a =0$ thus implying $q_a =0$. Then, if we\n#' note $i$ and $j$ the two adjacent nodes, the physics tells us that\n#' $$\n#' p_i = 0 \\, \\quad p_j = 0 ,\n#' $$\n#' which is not the case if we solve the previous optimization problem.\n#' However, the goal of this tutorial is purely pedagogical and as a\n#' consequence we allow us to play a bit with the physics.\n\n\n#' ### Default Knitro\n\n#' Solve with default Knitro.\n# Build non-linear solver.\nmodel = Model(with_optimizer(KNITRO.Optimizer, outlev=3))\nload_mip_model!(model)\n@time JuMP.optimize!(model)\n\n#' We plot the solution by displaying in red the arcs removed from the graph.\n# Plot!\nif PLOT_GRAPH\n    optimal_flow = JuMP.value.(model[:q])\n    fig = figure()\n    plot_network(flow=optimal_flow)\n    display(fig)\nend\n\n#' In the resolving, Knitro uses the Branch & Bound algorithm to find\n#' the optimal solution corresponding to the (convex) MINLP problem.\n#' We refer to the [documentation](https://www.artelys.com/docs/knitro/2_userGuide/minlp.html)\n#' for further details.\n#' The approach used here is different than in BONMIN (outer approximation).\n\n#' Observe that Knitro with default options computes 165 nodes before\n#' finding the solution.\n#' Is it possible to find a better tuning for Knitro?\n\n#' ### MIP-Tuner\n\n#' Since Knitro 12.0, a MINLP tuner was added to compute the optimal\n#' parameterization to solve a given MINLP problem with Knitro. The MINLP\n#' tuner uses an exhaustive search to find the optimal setting.\n#'\n#' By default, the tuner tests 36 combinations.\nmodel = Model(with_optimizer(KNITRO.Optimizer, outlev=3, tuner=1))\nload_mip_model!(model)\n@time JuMP.optimize!(model)\n\n\n#' Setting `mip_branchrule=2` and `mip_selectrule=3` seems to give\n#' better results, according to the tuner.\n#' Note that setting `outlev` to 0 switch off Knitro's output.\nmip_solver = with_optimizer(KNITRO.Optimizer, mip_knapsack=0, mip_branchrule=2,\n                            mip_selectrule=3, outlev=0)\nmodel = Model(mip_solver)\nload_mip_model!(model)\n@time JuMP.optimize!(model)\n\n\n#' ### Quantify impact of arcs' removals\n\n#' The fewer arcs, the harder the problem.\n#' If `nremovals >= 10`, Knitro takes too long to solve the problem.\n#' However, the problem remains feasible till n_removals = 13.\n#' Compute for instance the solution of the following problem:\nfeas_model = Model(with_optimizer(KNITRO.Optimizer))\n@variable(feas_model, qc[1:nx])\n@variable(feas_model, q[1:n])\n@constraint(feas_model, q .== q0 + B*qc)\n@variable(feas_model, z[1:n], Bin)\n@constraint(feas_model,  q .<= QMAX * z)\n@constraint(feas_model, -q .<= QMAX * z)\n@objective(feas_model, Min, sum(z))\n\n\n#' We know study the evolution of the objective cost w.r.t. the\n#' number of removals.\nmax_removals = 9\n\n# Save results in some arrays.\ncost_values = Float64[]\n\nfor nremove in 1:max_removals\n    println(\"Remove \", nremove, \" arcs from graph.\")\n    model = Model(mip_solver)\n    load_mip_model!(model, nremovals=nremove)\n    @time JuMP.optimize!(model)\n\n    push!(cost_values, JuMP.objective_value(model))\n\n    # Plot!\n    if PLOT_GRAPH\n        optimal_flow = JuMP.value.(model[:q])\n        fig = figure()\n        plot_network(flow=optimal_flow)\n        title(\"Optimal solution with $nremove removals\")\n        display(fig)\n    end\nend\n\n#' Plot evolution of costs w.r.t. number of removals.\nif PLOT_GRAPH\n    fig = figure()\n    plot(1:max_removals, cost_values, lw=3, c=\"k\")\n    xlabel(\"#removals\")\n    ylabel(\"Objective value\")\n    display(fig)\nend\n\n#' We observe that removing up to 6 arcs does not impact significantly\n#' the cost.\n", "meta": {"hexsha": "53aa50218d68ee75f4adf8b357199c6ebe32acf5", "size": 9995, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "minlp/water-network/network.jl", "max_stars_repo_name": "frapac/Knitro-Zoo", "max_stars_repo_head_hexsha": "1d79731a7e9bf1d3f5915430770e1c6b274535bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "minlp/water-network/network.jl", "max_issues_repo_name": "frapac/Knitro-Zoo", "max_issues_repo_head_hexsha": "1d79731a7e9bf1d3f5915430770e1c6b274535bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "minlp/water-network/network.jl", "max_forks_repo_name": "frapac/Knitro-Zoo", "max_forks_repo_head_hexsha": "1d79731a7e9bf1d3f5915430770e1c6b274535bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0352564103, "max_line_length": 110, "alphanum_fraction": 0.68014007, "num_tokens": 2874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7770380384627736}}
{"text": "using StatsBase, Distributions, Plots; pyplot()\n\nlambda, N = 1, 10^6\nxGrid = 0:6\n\nexpDist = Exponential(1/lambda)\nfloorData = counts(convert.(Int,floor.(rand(expDist,N))), xGrid)/N\ngeomDist = Geometric(1-MathConstants.e^-lambda)\n\nplot( xGrid, floorData, \n\tline=:stem, marker=:circle, \n\tc=:blue, ms=10, msw=0, lw=4, \n\tlabel=\"Floor of Exponential\")\nplot!( xGrid, pdf.(geomDist,xGrid), \n\tline=:stem, marker=:xcross, \n\tc=:red, ms=6, msw=0, lw=2, \n\tlabel=\"Geometric\", ylims=(0,1), \n\txlabel=\"x\", ylabel=\"Probability\")", "meta": {"hexsha": "a4706453d6ba90b164bfdde956035232f573bc90", "size": 511, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/expGeom.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "3_chapter/expGeom.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "3_chapter/expGeom.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 28.3888888889, "max_line_length": 66, "alphanum_fraction": 0.6810176125, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913356558485, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7770374632908414}}
{"text": "\"\"\"Calculates the 2nd order centred gradient in x-direction on any grid (u,v,T or q).\nThe size of dudx must be m-1,n compared to m,n = size(u)\"\"\"\nfunction ∂x!(dudx::AbstractMatrix,u::AbstractMatrix)\n    m,n = size(dudx)\n    @boundscheck (m+1,n) == size(u) || throw(BoundsError())\n\n    @inbounds for j ∈ 1:n\n        for i ∈ 1:m\n            dudx[i,j] = u[i+1,j] - u[i,j]\n        end\n    end\nend\n\n\"\"\"Calculates the 2nd order centred gradient in y-direction on any grid (u,v,T or q).\nThe size of dudy must be m,n-1 compared to m,n = size(u).\"\"\"\nfunction ∂y!(dudy::AbstractMatrix,u::AbstractMatrix)\n    m,n = size(dudy)\n    @boundscheck (m,n+1) == size(u) || throw(BoundsError())\n\n    @inbounds for j ∈ 1:n\n        for i ∈ 1:m\n            dudy[i,j] = u[i,j+1] - u[i,j]\n        end\n    end\nend\n\n\"\"\" ∇² is the 2nd order centred Laplace-operator ∂/∂x^2 + ∂/∂y^2.\nThe 1/Δ²-factor is omitted and moved into the viscosity coefficient.\"\"\"\nfunction ∇²!(du::AbstractMatrix,u::AbstractMatrix)\n    m, n = size(du)\n    @boundscheck (m+2,n+2) == size(u) || throw(BoundsError())\n\n    @inbounds for i ∈ 1:n\n        for j ∈ 1:m\n            du[j,i] = minus_4*u[j+1,i+1] + u[j,i+1] + u[j+2,i+1] + u[j+1,i] + u[j+1,i+2]\n        end\n    end\nend\n", "meta": {"hexsha": "dff65c1d3da4d56cdc2ef9621ed0fe439038d798", "size": 1220, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gradients.jl", "max_stars_repo_name": "eschnett/juls", "max_stars_repo_head_hexsha": "2921372578c880c52c07f5449afc234c69433148", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gradients.jl", "max_issues_repo_name": "eschnett/juls", "max_issues_repo_head_hexsha": "2921372578c880c52c07f5449afc234c69433148", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gradients.jl", "max_forks_repo_name": "eschnett/juls", "max_forks_repo_head_hexsha": "2921372578c880c52c07f5449afc234c69433148", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2820512821, "max_line_length": 88, "alphanum_fraction": 0.5778688525, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913354875362, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7770374578864587}}
{"text": "\"\"\"\n    GaussianLikelihood(σ²)\n\nGaussian likelihood with `σ²` variance. This is to be used if we assume that the\nuncertainity associated with the data follows a Gaussian distribution.\n\n```math\n    p(y|f) = Normal(y | f, σ²)\n```\nOn calling, this would return a normal distribution with mean `f` and variance σ².\n\"\"\"\nstruct GaussianLikelihood{T<:Real}\n    σ²::Vector{T}\nend\n\nGaussianLikelihood() = GaussianLikelihood(1e-6)\n\nGaussianLikelihood(σ²::Real) = GaussianLikelihood([σ²])\n\n@functor GaussianLikelihood\n\n(l::GaussianLikelihood)(f::Real) = Normal(f, sqrt(first(l.σ²)))\n\n(l::GaussianLikelihood)(fs::AbstractVector{<:Real}) = MvNormal(fs, first(l.σ²) * I)\n\n\"\"\"\n    HeteroscedasticGaussianLikelihood(l::AbstractLink=ExpLink())\n\nHeteroscedastic Gaussian likelihood. \nThis is a Gaussian likelihood whose mean and variance are functions of\nlatent processes.\n\n```math\n    p(y|[f, g]) = Normal(y | f, sqrt(l(g)))\n```\nOn calling, this would return a normal distribution with mean `f` and variance `l(g)`.\nWhere `l` is link going from R to R^+\n\"\"\"\nstruct HeteroscedasticGaussianLikelihood{Tl<:AbstractLink}\n    invlink::Tl\nend\n\nHeteroscedasticGaussianLikelihood() = HeteroscedasticGaussianLikelihood(ExpLink())\n\nfunction (l::HeteroscedasticGaussianLikelihood)(f::AbstractVector{<:Real})\n    return Normal(f[1], sqrt(l.invlink(f[2])))\nend\n\nfunction (l::HeteroscedasticGaussianLikelihood)(fs::AbstractVector)\n    return MvNormal(first.(fs), Diagonal(l.invlink.(last.(fs))))\nend\n", "meta": {"hexsha": "8a3c93d802546a46b4a0e19dbf378e12e3a078ff", "size": 1469, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/likelihoods/gaussian.jl", "max_stars_repo_name": "hendersontrent/GPLikelihoods.jl", "max_stars_repo_head_hexsha": "da25a4dccd3d0ea3cb381d3b4703ae940059873e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/likelihoods/gaussian.jl", "max_issues_repo_name": "hendersontrent/GPLikelihoods.jl", "max_issues_repo_head_hexsha": "da25a4dccd3d0ea3cb381d3b4703ae940059873e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/likelihoods/gaussian.jl", "max_forks_repo_name": "hendersontrent/GPLikelihoods.jl", "max_forks_repo_head_hexsha": "da25a4dccd3d0ea3cb381d3b4703ae940059873e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.25, "max_line_length": 86, "alphanum_fraction": 0.7365554799, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7770374537120853}}
{"text": "using LinearAlgebra\r\n\r\nfunction so3ToVec(so3mat)\r\n    if( size(so3mat)!=(3,3) )\r\n        println(\"!Warning! : Input matrix should be 3x3.\")\r\n        return\r\n    end\r\n    if( !((so3mat[1,1]==so3mat[2,2]==so3mat[3,3]==0)) )\r\n        println(\"!Warning! : Diagonals should be zero.\")\r\n        return\r\n    end\r\n    if( so3mat[2,1]!=-so3mat[1,2] ||\r\n        so3mat[3,1]!=-so3mat[1,3] ||\r\n        so3mat[3,2]!=-so3mat[2,3] )\r\n        println(\"!Warning! : Entered matrix isn't a skew symmetric matrix.\")\r\n        return\r\n    end\r\n    ret_vec = [so3mat[3,2];\r\n               so3mat[1,3];\r\n               so3mat[2,1] ]\r\n        return ret_vec\r\nend\r\n\r\nfunction vecToSo3(omg)\r\n    if( size(omg)!=(3,) )\r\n        println(\"!Warning! : Input matrix should be 3x1.\")\r\n        return\r\n    end\r\n\r\n    ret_ss_matrix = [0      -omg[3]   omg[2];\r\n                     omg[3]    0     -omg[1];\r\n                    -omg[2]  omg[1]      0];\r\n    return ret_ss_matrix\r\nend\r\n\r\nusing LinearAlgebra\r\n\r\nfunction so3ToVec(so3mat)\r\n    if( size(so3mat)!=(3,3) )\r\n        println(\"!Warning! : Input matrix should be 3x3.\")\r\n        return\r\n    end\r\n    if( !((so3mat[1,1]==so3mat[2,2]==so3mat[3,3]==0)) )\r\n        println(\"!Warning! : Diagonals should be zero.\")\r\n        return\r\n    end\r\n    if( so3mat[2,1]!=-so3mat[1,2] ||\r\n        so3mat[3,1]!=-so3mat[1,3] ||\r\n        so3mat[3,2]!=-so3mat[2,3] )\r\n        println(\"!Warning! : Entered matrix isn't a skew symmetric matrix.\")\r\n        return\r\n    end\r\n    ret_vec = [so3mat[3,2];\r\n               so3mat[1,3];\r\n               so3mat[2,1] ]\r\n        return ret_vec\r\nend\r\n\r\nfunction VecToso3(omg)\r\n    if( size(omg)!=(3,) )\r\n        println(\"!Warning! : Input matrix should be 3x1.\")\r\n        return\r\n    end\r\n\r\n    ret_ss_matrix = [0      -omg[3]   omg[2];\r\n                     omg[3]    0     -omg[1];\r\n                    -omg[2]  omg[1]      0];\r\n    return ret_ss_matrix\r\nend\r\n#****************************************************************#\r\n# VeysiADN 17 Apr 2021\r\n# Advanced Robotics Homework 4 Codes\r\n#****************************************************************#\r\nusing LinearAlgebra\r\nconst lAlgebra = LinearAlgebra\r\n#****************************************************************#\r\n# Returns normalized version of given matrix/array\r\nfunction Normalize(N)\r\n    return N/lAlgebra.norm(N)\r\nend\r\n#****************************************************************#\r\n# Returns 4x4 twist matrix ‘se3mat’ (an element of Lie Algebra se3)\r\n# from given twist vector (= 6x1 vector) ‘xi\r\nfunction VecTose3( xi )\r\n    w_skew = [ 0   -xi[3]   xi[2];\r\n              xi[3]   0    -xi[1];\r\n             -xi[2]  xi[1]    0 ]\r\n    return vcat(hcat(w_skew,xi[4:6]), zeros(1, 4))\r\nend\r\n#****************************************************************#\r\n# Returns twist vector ‘xi’ from given twist matrix ‘se3mat’\r\nfunction se3ToVec( se3mat )\r\n    omg = [se3mat[3, 2], se3mat[1, 3],se3mat[2, 1]]\r\n    v = se3mat[1:3, 4]\r\n    return vcat(omg,v)\r\nend\r\n#****************************************************************#\r\n# Calculates and return rotation matrix ‘R’ by\r\n# evaluating matrix exponential of 3x3 skew symmetric matrix ‘so3mat’\r\n\r\nfunction MatrixExp3(so3mat)\r\n        omg = [so3mat[3, 2], so3mat[1, 3],so3mat[2, 1]]\r\n        theta = lAlgebra.norm(omg)\r\n        omg_n = so3mat / theta\r\n        return lAlgebra.I + sin(theta) * omg_n + (1 - cos(theta)) * omg_n * omg_n\r\nend\r\n\r\n#****************************************************************#\r\n# Calculates and return transformation matrix ‘g’ by\r\n# evaluating matrix exponential of 4x4 twist matrix ‘se3mat’\r\nfunction MatrixExp6( se3mat )\r\n    omg = [se3mat[3, 2], se3mat[1, 3],se3mat[2, 1]]\r\n    theta = lAlgebra.norm(omg)\r\n    omg_n = se3mat[1:3, 1:3] / theta\r\n    temp  = hcat(MatrixExp3(se3mat[1:3, 1:3]),\r\n                         (lAlgebra.I * theta +\r\n                          (1 - cos(theta)) * omg_n +\r\n                          (theta - sin(theta)) * omg_n * omg_n) *\r\n                         se3mat[1:3, 4] / theta)\r\n    return    vcat(temp,[0 0 0 1])\r\nend\r\n\r\n#****************************************************************#\r\n# VeysiADN 12 May 2021\r\n# Advanced Robotics Homework 5 Codes\r\n#****************************************************************#\r\nusing LinearAlgebra\r\nconst lAlgebra = LinearAlgebra\r\n#****************************************************************#\r\n# Computes exponential coordinate ‘so3mat’\r\n# (skew symmetric matrix) of the rotation matrix R\r\n\r\nfunction MatrixLog3(R)\r\n    acosinput = (lAlgebra.tr(R) - 1) / 2\r\n    if acosinput >= 1\r\n        return zeros(3, 3)\r\n    else\r\n        theta = acos(acosinput)\r\n        return theta / 2 / sin(theta) * (R - R')\r\n    end\r\nend\r\n#****************************************************************#\r\n# Computes exponential coordinate ‘se3mat’\r\n# (twist matrix) of the rigid body transformation matrix T\r\nfunction MatrixLog6(T)\r\n    if( size(T)!=(4,4) )\r\n        println(\"!Warning! : Transformation matrix should be 4x4.\")\r\n        return\r\n    end\r\n    R = T[1:3,1:3]\r\n    t = T[1:3,4]\r\n    omg_h = MatrixLog3(R)\r\n    w = [omg_h[3,2];omg_h[1,3];omg_h[2,1]]\r\n    if omg_h == zeros(3, 3)\r\n        return vcat(hcat(zeros(3, 3), T[1:3, 4]), [0 0 0 0])\r\n    else\r\n        theta = acos((lAlgebra.tr(R) - 1) / 2)\r\n        return vcat(hcat(omg_h,\r\n                         (I - omg_h / 2 +\r\n                          (1 / theta - 1 / tan(theta / 2) / 2) *\r\n                          omg_h * omg_h / theta) * T[1:3, 4]),\r\n                    [0 0 0 0])\r\n    end\r\nend\r\n#****************************************************************#\r\n\r\n#****************************************************************#\r\n# VeysiADN 12 May 2021\r\n# Advanced Robotics Homework 5 Codes\r\n#****************************************************************#\r\nusing LinearAlgebra\r\n#****************************************************************#\r\n# Returns Adjoint matrix with given rigid body\r\n# transformation matrix g\r\nfunction Adjoint(g)\r\n\r\n    R=g[1:3,1:3];\r\n    p=g[1:3,4];\r\n    p_hat = [ 0       -p[3]     p[2];\r\n             p[3]       0      -p[1];\r\n            -p[2]      p[1]       0 ]\r\n\r\n    return [R zeros(3,3);p_hat*R R]\r\nend\r\n#****************************************************************#\r\n# VeysiADN 4 Apr 2021\r\n# Advanced Robotics Homework 3 Codes\r\n#****************************************************************#\r\nusing LinearAlgebra\r\n#****************************************************************#\r\n# Returns 3 x 3 rotation matrix representing\r\n# rotation about unit vector w by angle theta.\r\n# theta should be in radian\r\nfunction Rodrigues(w,theta)\r\n    if( length(w) != 3)\r\n        println(\"!Warning! : W matrix should have 3 elements.\")\r\n        return\r\n    end\r\n    if(size(w)==(1,3))\r\n        w=w';\r\n    end\r\n    w_hat = [0      -w[3]    w[2];\r\n             w[3]     0     -w[1];\r\n            -w[2]    w[1]      0];\r\n    rotation_matrix = cos(theta)*Matrix(1I,3,3) + sin(theta)*w_hat+(1-cos(theta))*w*w';\r\n    return rotation_matrix;\r\nend\r\n#****************************************************************#\r\n# Builds rigid transformation matrix T from given\r\n#rotation matrix R and translation t\r\nfunction RpToTrans(R,t)\r\n    if( size(R)!=(3,3) )\r\n        println(\"!Warning! : Rotation matrix should be 3x3.\")\r\n        return\r\n    end\r\n    if( length(t) != 3 )\r\n        println(\"!Warning! : Translation matrix should have 3 elements.\")\r\n        return\r\n    end\r\n    if(size(t)==(1,3))\r\n        t=t';\r\n    end\r\n    R_B_T = hcat(R,t) ;\r\n    R_B_T = vcat(R_B_T,[0 0 0 1]) ;\r\n    return R_B_T\r\nend\r\n#****************************************************************#\r\n#Extracts rotation matrix R and translation t from given /\r\n# rigid transformation matrix T\r\nfunction TransToRp(T)\r\n    if( size(T)!=(4,4) )\r\n        println(\"!Warning! : Transformation matrix should be 4x4.\")\r\n        return\r\n    end\r\n    R = T[1:3,1:3]\r\n    t = T[1:3,4]\r\n    return R,t;\r\nend\r\n#****************************************************************#\r\n# Inverts rigid transformation matrix T\r\nfunction TransInv(T)\r\n    if( size(T)!=(4,4) )\r\n        println(\"!Warning! : W matrix should be 4x4.\")\r\n        return\r\n    end\r\n    if( det(T)==0 )\r\n        println(\"!Warning! : Inverse doesn't exist (Determinant is equal to zero).\")\r\n        return\r\n    end\r\n    R,t = TransToRp(T);\r\n    r_inv =hcat(R',-(R'*t))\r\n    r_inv = vcat(r_inv,[0 0 0 1]);\r\n    return r_inv;\r\nend\r\n#****************************************************************#\r\n", "meta": {"hexsha": "77dc4860b5fd22dfb43fa5aaf62ffdd342f1011a", "size": 8472, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Combined.jl", "max_stars_repo_name": "veysiadn/AdvancedRoboticsJulia", "max_stars_repo_head_hexsha": "0484999de1908b73fd19c7c78f5c8471a62610ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Combined.jl", "max_issues_repo_name": "veysiadn/AdvancedRoboticsJulia", "max_issues_repo_head_hexsha": "0484999de1908b73fd19c7c78f5c8471a62610ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Combined.jl", "max_forks_repo_name": "veysiadn/AdvancedRoboticsJulia", "max_forks_repo_head_hexsha": "0484999de1908b73fd19c7c78f5c8471a62610ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.09375, "max_line_length": 88, "alphanum_fraction": 0.4448772427, "num_tokens": 2372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913343093499, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.777037446139791}}
{"text": "# nuclear Norm (times a constant)\n\n\"\"\"\n  NuclearNorm(λ::Real=1.0)\n\nReturns the function `λ∑σ_i(X)`, where `σ_i(X)` is i-th singular value of matrix X.\n\"\"\"\n\nimmutable NuclearNorm{R <: Real} <: ProximableConvex\n  lambda::R\n  function NuclearNorm(lambda::R)\n    if lambda < 0\n      error(\"parameter λ must be nonnegative\")\n    else\n      new(lambda)\n    end\n  end\nend\n\nNuclearNorm{R <: Real}(lambda::R=1.0) = NuclearNorm{R}(lambda)\n\nfunction (f::NuclearNorm){T <: RealOrComplex}(X::AbstractArray{T,2})\n  U, S, V = svd(X);\n  return f.lambda * sum(S);\nend\n\nfunction prox!{T <: RealOrComplex}(f::NuclearNorm, X::AbstractArray{T,2}, Y::AbstractArray{T,2}, gamma::Real=1.0)\n  U, S, V = svd(X)\n\n  for i in eachindex(S)\n    S[i] = max(0, S[i] - f.lambda*gamma);\n  end\n\n  Y[:] = U * diagm(S) * V'\n  return f.lambda * sum(S);\nend\n\nfun_name(f::NuclearNorm) = \"nuclear norm\"\nfun_dom(f::NuclearNorm) = \"AbstractArray{Real,2}, AbstractArray{Complex,2}\"\nfun_expr(f::NuclearNorm) = \"X ↦ λ∑σ_i(X)\"\nfun_params(f::NuclearNorm) = \"λ = $(f.lambda)\"\n\nfunction prox_naive{T <: RealOrComplex}(f::NuclearNorm, X::AbstractArray{T,2}, gamma::Real=1.0)\n  U,S,V = svd(X)\n  ftemp = NormL1(1.0)\n  S_γ, fS_γ =  prox(ftemp,S,f.lambda*gamma)\n  Y = U * diagm(S_γ) * V'\n  return Y, f.lambda * sum(S_γ)\nend\n", "meta": {"hexsha": "1b29ae136168ef177513aae55b77840534f44b7f", "size": 1268, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/nuclearNorm.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/nuclearNorm.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/nuclearNorm.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.36, "max_line_length": 113, "alphanum_fraction": 0.641955836, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7770362882999463}}
{"text": "\nusing DifferentialEquations\nusing DiffEqCallbacks\nusing Distributions\nusing StatsBase\nusing Random\nusing DataFrames\nusing StatsPlots\nusing BenchmarkTools\n\n\nfunction rate_to_proportion(r::Float64,t::Float64)\n    1-exp(-r*t)\nend;\n\n\n@enum InfectionStatus Susceptible Infected Recovered\n\n\nBase.zero(::Type{InfectionStatus}) = Infected\n\n\nfunction sir_abm!(du,u,p,t)\n    (β,c,γ,δt) = p\n    N = length(u)\n    # Initialize du to u\n    for i in 1:N\n        du[i] = u[i]\n    end\n    for i in 1:N # loop through agents\n        # If recovered\n        if u[i]==Recovered\n            continue\n        # If susceptible\n        elseif u[i]==Susceptible\n            ncontacts = rand(Poisson(c*δt))\n            while ncontacts > 0\n                j = sample(1:N)\n                if j==i\n                    continue\n                end\n                a = u[j]\n                if a==Infected && rand() < β\n                    du[i] = Infected\n                    break\n                end\n                ncontacts -= 1\n            end\n        # If infected\n        else u[i]==Infected\n            if rand() < γ\n                du[i] = Recovered\n            end\n        end\n    end\n    nothing\nend;\n\n\nδt = 0.1\ntf = 40.0\ntspan = (0.0,tf);\n\n\nβ = 0.05\nc = 10.0\nγ = rate_to_proportion(0.25,δt)\np = [β,c,γ,δt];\n\n\nN = 1000\nI0 = 10\nu0 = Array{InfectionStatus}(undef,N)\nfor i in 1:N\n    if i <= I0\n        s = Infected\n    else\n        s = Susceptible\n    end\n    u0[i] = s\nend\n\n\nRandom.seed!(1234);\n\n\nsusceptible(u) = count(i == Susceptible for i in u)\ninfected(u) = count(i == Infected for i in u)\nrecovered(u) = count(i == Recovered for i in u);\n\n\nsaved_values = SavedValues(Float64, Tuple{Int64,Int64,Int64})\ncb = SavingCallback((u,t,integrator)->(susceptible(u),infected(u),recovered(u)),\n    saved_values,\n    saveat=0:δt:tf);\n\n\nprob_abm = DiscreteProblem(sir_abm!,u0,tspan,p);\n\n\nsol_abm = solve(prob_abm,\n    solver = FunctionMap(),\n    dt = δt,\n    callback = cb,\n    dense = false,\n    save_on = false);\n\n\ndf_abm = DataFrame(saved_values.saveval)\nrename!(df_abm,[:S,:I,:R])\ndf_abm[!,:t] = saved_values.t;\n\n\n@df df_abm plot(:t,\n    [:S :I :R],\n    label=[\"S\" \"I\" \"R\"],\n    xlabel=\"Time\",\n    ylabel=\"Number\")\n\n\n@benchmark solve(prob_abm,\n    solver=FunctionMap,\n    dt=δt,\n    callback=cb,\n    dense=false,\n    save_on=false)\n\n", "meta": {"hexsha": "9d0d56913221b9be6434068be5d1e90eba8391a5", "size": 2310, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/abm_vector_diffeq/abm_vector_diffeq.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 126, "max_stars_repo_stars_event_min_datetime": "2020-04-29T08:41:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:42:53.000Z", "max_issues_repo_path": "script/abm_vector_diffeq/abm_vector_diffeq.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2020-04-29T11:44:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:45:15.000Z", "max_forks_repo_path": "script/abm_vector_diffeq/abm_vector_diffeq.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2020-04-29T08:01:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T16:55:08.000Z", "avg_line_length": 18.046875, "max_line_length": 80, "alphanum_fraction": 0.5567099567, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915912, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.77703628094606}}
{"text": "# Example 2.5 from A. Law (2013): Simulation Modeling and Analysis, 5ed\n\nusing EventSimulation\nusing Distributions   # Exponential distribution\nusing StatsBase       # weighted mean\nusing DataFrames      # nicer ouptut of results\n\nmutable struct Job\n    tin::Float64  # time when job entered the system\n    tout::Float64 # time when job left the system\n    ttrue::Float64 # time needed without cycling\n    remaining::Float64 # time remaining to finish the job\nend\n\nmutable struct SharedComputer <: AbstractState\n    a::Exponential{Float64}    # arrival time distribution\n    p::Exponential{Float64}    # processing time distribution\n    τ::Float64                 # switching time\n    q::Float64                 # processing quantum time\n    n::Int                     # number of terminals\n    reps::Int                  # number of finished jobs to collect\n    job_queue::Vector{Job}     # queue of jobs waiting for processing\n    finished_jobs::Vector{Job} # list of finished jobs\n    job::Union{Job, Nothing}  # current job on computer\n    # this structure holds information for reporting\n    # for each perior between events it holds the length of queue,\n    # if the computer were busy and the length of time period\n    state_chunks::Vector{Tuple{Int, Bool, Float64}}\n    SharedComputer(a, p, τ, q, n, reps) =\n        new(Exponential(a), Exponential(p), τ, q, n, reps,\n            Job[], Job[], nothing, Tuple{Int, Bool, Float64}[])\nend\n\nfunction arrival(s)\n    ttrue = rand(s.state.p)\n    j = Job(s.now, NaN, ttrue, ttrue)\n    isnothing(s.state.job) && register!(s, start_compute, 0.0)\n    push!(s.state.job_queue, j)\nend\n\nfunction start_compute(s)\n    j = popfirst!(s.state.job_queue)\n    s.state.job = j\n    processed = j.remaining < s.state.q ? j.remaining : s.state.q\n    j.remaining -= processed\n    register!(s, stop_compute, processed + s.state.τ)\nend\n\nfunction stop_compute(s)\n    j = s.state.job\n    s.state.job = nothing\n    if j.remaining == 0\n        j.tout = s.now\n        push!(s.state.finished_jobs, j)\n        register!(s, arrival, rand(s.state.a))\n    else\n        push!(s.state.job_queue, j)\n    end\n    isempty(s.state.job_queue) || register!(s, start_compute, 0.0)\n    length(s.state.finished_jobs) == s.state.reps && terminate!(s)\nend\n\nmonitor(s, Δ) =\n    push!(s.state.state_chunks,\n          (length(s.state.job_queue), !isnothing(s.state.job), Δ))\n\nfunction run(a, p, τ, q, n, reps)\n    sc = SharedComputer(a, p, τ, q, n, reps)\n    s = Scheduler(sc, Float64, monitor)\n    for _ in 1:n\n        register!(s, arrival, rand(sc.a))\n    end\n    go!(s)\n    chunks = s.state.state_chunks\n    (n=n,\n     response=mean(j.tout - j.tin for j in s.state.finished_jobs),\n     queue=mean(getindex.(chunks, 1), Weights(getindex.(chunks, 3))),\n     CPU=mean(getindex.(chunks, 2), Weights(getindex.(chunks, 3))))\nend\n\nDataFrame([run(25.0, 0.8, 0.015, 0.1, n, 1000) for n in 10:10:80])\n", "meta": {"hexsha": "1e17c80301ecd9043faa72f9269efcc7b01cae3e", "size": 2898, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/computer.jl", "max_stars_repo_name": "UnofficialJuliaMirror/EventSimulation.jl-bf752c2e-6b1c-53e3-a22f-e5bb209bd3f1", "max_stars_repo_head_hexsha": "32b1ca2dab786a0c256f88a70ecf324928f07b0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2018-01-13T19:51:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T12:00:25.000Z", "max_issues_repo_path": "examples/computer.jl", "max_issues_repo_name": "UnofficialJuliaMirror/EventSimulation.jl-bf752c2e-6b1c-53e3-a22f-e5bb209bd3f1", "max_issues_repo_head_hexsha": "32b1ca2dab786a0c256f88a70ecf324928f07b0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2018-04-27T11:46:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-18T21:55:08.000Z", "max_forks_repo_path": "examples/computer.jl", "max_forks_repo_name": "UnofficialJuliaMirror/EventSimulation.jl-bf752c2e-6b1c-53e3-a22f-e5bb209bd3f1", "max_forks_repo_head_hexsha": "32b1ca2dab786a0c256f88a70ecf324928f07b0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:18:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:49:38.000Z", "avg_line_length": 35.3414634146, "max_line_length": 71, "alphanum_fraction": 0.6456176674, "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520764, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7770362642069042}}
{"text": "\"\"\"\n    logtp_equal_rates_equal_time(i, j)\n\nEvaluate the logarithm of a transition probability of a simple birth and death\nprocess when the death rate `μ` is equal to the birth rate `λ` and the time `t`\nis equal to `1 / λ`. It is a very unlikely event (let's say impossible) but it\nsimplifies into a special case.\n\"\"\"\n@inline function logtp_equal_rates_equal_time(\n  i::I,\n  j::I\n) where {\n  I <: Integer\n}\n  lgamma(i + j) - lgamma(i) - lgamma(j + 1) - (i + j) * log(2)\nend\n\n\"\"\"\n    logtp_equal_rates(i, j, t, λ)\n\nEvaluate the logarithm of a transition probability of a simple birth and death\nprocess.\n\"\"\"\n@inline function logtp_equal_rates(\n  i::I,\n  j::I,\n  t::F,\n  λ::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  a::F, b::F = (j <= i) ? (i, j) : (j, i)\n\n  θ = λ * t\n\n  lgamma(i + j) - lgamma(i) - lgamma(j + 1) + (i + j) * log(θ / (1 + θ)) +\n  log_hypergeometric(a, b, logexpm1(-2 * log(θ)))\nend\n\n\"\"\"\n    logtp_equal_rates_alternating(i, j, t, λ)\n\nEvaluate the logarithm of a transition probability of a simple birth and death\nprocess when terms are alternating in sign.\n\"\"\"\n@inline function logtp_equal_rates_alternating(\n  i::I,\n  j::I,\n  t::F,\n  λ::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  a::F, b::F = (j <= i) ? (i, j) : (j, i)\n\n  θ = λ * t\n\n  lgamma(i + j) - lgamma(i) - lgamma(j + 1) + (i + j) * log(θ / (1 + θ)) +\n  log_meixner_ortho_poly(a, b, 2 * log(θ))\nend\n\n\"\"\"\n    logtp_equal_rates_equal_time_extinction(i)\n\nEvaluate the logarithm of a transition probability of a simple birth and death\nprocess when the death rate `μ` is equal to the birth rate `λ`, time `t` is\nequal to `1 / λ`, and 'j' is equal to zero. It is a very unlikely event\n(let's say impossible) but it simplifies into a special case.\n\"\"\"\n@inline function logtp_equal_rates_equal_time_extinction(\n  i::I\n) where {\n  I <: Integer\n}\n  - i * log(2)\nend\n\n\"\"\"\n    logtp_equal_rates_extinction(i, t, λ)\n\nEvaluate the logarithm of the probability of extinction for a simple birth and\ndeath process when the death rate `μ` is equal to the birth rate `λ`.\n\"\"\"\n@inline function logtp_equal_rates_extinction(\n  i::I,\n  t::F,\n  λ::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  i * log((λ * t) / (1 + λ * t))\nend\n\n\"\"\"\n    logtp_pure_birth(i, j, t, λ)\n\nEvaluate the logarithm of the transition probability of a pure-birth process.\n\"\"\"\n@inline function logtp_pure_birth(\n  i::I,\n  j::I,\n  t::F,\n  λ::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  lgamma(j) + (j - i) * logexpm1(λ * t) -\n  (lgamma(i) + lgamma(j - i + 1) + j * λ * t)\nend\n\n\"\"\"\n    logtp_pure_death(i, j, t, μ)\n\nEvaluate the logarithm of the transition probability of a pure-death process.\n\"\"\"\n@inline function logtp_pure_death(\n  i::I,\n  j::I,\n  t::F,\n  μ::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  lgamma(i + 1) + (i - j) * logexpm1(μ * t) -\n  (lgamma(j + 1) + lgamma(i - j + 1) + i * μ * t)\nend\n\n\"\"\"\n    logtp_equal_time(i, j, λ, μ)\n\nEvaluate the logarithm of a transition probability of a simple birth and death\nprocess when the time `t` is equal to `log(λ / μ) / (λ - μ)`. It is a very\nunlikely event (let's say impossible) but it simplifies into a special case.\n\"\"\"\n@inline function logtp_equal_time(\n  i::I,\n  j::I,\n  λ::F,\n  μ::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  lgamma(i + j) + i * log(μ) + j * log(λ) -\n  (lgamma(i) + lgamma(j + 1) + (i + j) * log(λ + μ))\nend\n\n\"\"\"\n    logtp_sum(i, j, t, λ, μ)\n\nEvaluate the logarithm of a transition probability of a simple birth and death\nprocess.\n\"\"\"\n@inline function logtp_sum(\n  i::I,\n  j::I,\n  t::F,\n  λ::F,\n  μ::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  a::F, b::F = (j <= i) ? (i, j) : (j, i)\n\n  θ = (λ - μ) * t\n  ω = log(λ / μ)\n\n  x = if λ < μ\n    logexpm1(θ - ω) + log1mexp(θ + ω) - 2 * log1mexp(θ)\n  else\n    logexpm1(θ + ω) + log1mexp(θ - ω) - 2 * logexpm1(θ)\n  end\n\n  lgamma(i + j) - lgamma(i) - lgamma(j + 1) + j * ω +\n  (i + j) * log(expm1(θ) / expm1(θ + ω)) +\n  log_hypergeometric(a, b, x)\nend\n\n\"\"\"\n    logtp_sum_alternating(i, j, t, λ, μ)\n\nEvaluate the logarithm of a transition probability of a simple birth and death\nprocess when terms are alternating in sign.\n\"\"\"\n@inline function logtp_sum_alternating(\n  i::I,\n  j::I,\n  t::F,\n  λ::F,\n  μ::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  a::F, b::F = (j <= i) ? (i, j) : (j, i)\n\n  θ = (λ - μ) * t\n  ω = log(λ / μ)\n\n  x = log(2 * λ * μ) +\n      logexpm1(log1pexp(2 * θ) - (θ + log(F(2)))) -\n      log((λ - μ)^2)\n\n  lgamma(i + j) - lgamma(i) - lgamma(j + 1) + j * ω +\n  (i + j) * log(expm1(θ) / expm1(θ + ω)) +\n  log_meixner_ortho_poly(a, b, x)\nend\n\n\"\"\"\n    logtp_equal_time_extinction(i, t, λ, μ)\n\nEvaluate the logarithm of the probability of extinction for a simple birth and\ndeath process when `t = log(λ / μ) / (λ - μ)`.\n\"\"\"\n@inline function logtp_equal_time_extinction(\n  i::I,\n  λ::F,\n  μ::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  i * log(μ / (λ + μ))\nend\n\n\"\"\"\n    logtp_extinction(i, t, λ, μ)\n\nEvaluate the logarithm of the probability of extinction for a simple birth and\ndeath process.\n\"\"\"\n@inline function logtp_extinction(\n  i::I,\n  t::F,\n  λ::F,\n  μ::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  i * log(expm1((λ - μ) * t) / expm1(log(λ / μ) + (λ - μ) * t))\nend\n\n\"\"\"\n    trans_prob(i, j, t, λ, μ; log_value)\n\nEvaluate the transition probability of a simple birth and death process, i.e.\nthe probability of moving from `i` to `j` in `t` time when the birth rate is\nequal to `λ` and the death rate is equal to `μ`.\n\nThe minimum amount of units `i` allowed at time 0 is 1 but `j` is allowed to be\n0. Time `t`, birth rate `λ`, and death rate `μ` cannot be negative.\n\nLet ``α = (μ e^{(λ - μ) t} - μ) / (λ e^{(λ - μ) t} - μ)`` and\n``β = (λ e^{(λ - μ) t} - λ) / (λ e^{(λ - μ) t} - μ)``. Transition probability\nis equal to (Bailey, 1964):\n``\\\\sum_{h = 0}^{\\\\min(i, j)} \\\\binom{i}{h} \\\\binom{i + j - h - 1}{i - 1}\nα^{i - h} β^{j - h} (1 - α - β)^{h}``.\n\n# References:\n\nBailey, N. T. J. (1964). The elements of stochastic processes with applications\nto the natural sciences. Wiley, New York, NY, USA. ISBN 0-471-04165-3.\n\"\"\"\nfunction trans_prob(\n  i::I,\n  j::I,\n  t::Real,\n  η::Vector{R};\n  log_value::Bool=true\n) where {\n  I <: Integer,\n  R <: Real\n}\n  if i < 1\n    msg = \"Initial population size 'i' must be greater than zero.\"\n    throw(DomainError(i, msg))\n  end\n\n  if j < 0\n    msg = \"Final population size 'j' must be greater than or equal to zero.\"\n    throw(DomainError(j, msg))\n  end\n\n  if t < 0\n    msg = \"Time 't' must be greater than or equal to zero.\"\n    throw(DomainError(t, msg))\n  end\n\n  if η[1] < 0\n    msg = \"Birth rate 'η[1]' must be greater than or equal to zero.\"\n    throw(DomainError(η[1], msg))\n  end\n\n  if η[2] < 0\n    msg = \"Death rate 'η[2]' must be greater than or equal to zero.\"\n    throw(DomainError(η[2], msg))\n  end\n\n  # promote values to the appropriate float\n  F = float(R)\n  t, λ, μ = F(t), F(η[1]), F(η[2])\n  ϵ = floatmin(F)\n\n  log_trans_prob::F = if (t < ϵ) || ((λ < ϵ) && (μ < ϵ))\n    if i == j\n      0\n    else\n      -Inf\n    end\n  elseif λ ≈ μ\n    ξ = 1 / λ\n\n    if j > 0\n      if t ≈ ξ\n        logtp_equal_rates_equal_time(i, j)\n      elseif t < ξ\n        logtp_equal_rates(i, j, t, λ)\n      else\n        logtp_equal_rates_alternating(i, j, t, λ)\n      end\n    else\n      if t ≈ ξ\n        logtp_equal_rates_equal_time_extinction(i)\n      else\n        logtp_equal_rates_extinction(i, t, λ)\n      end\n    end\n  elseif μ < ϵ\n    if j >= i\n      logtp_pure_birth(i, j, t, λ)\n    else\n      -Inf\n    end\n  elseif λ < ϵ\n    if j <= i\n      logtp_pure_death(i, j, t, μ)\n    else\n      -Inf\n    end\n  else\n    ξ = log(λ / μ) / (λ - μ)\n\n    if j > 0\n      if t ≈ ξ\n        logtp_equal_time(i, j, λ, μ)\n      elseif t < ξ\n        logtp_sum(i, j, t, λ, μ)\n      else\n        logtp_sum_alternating(i, j, t, λ, μ)\n      end\n    else\n      if t ≈ ξ\n        logtp_equal_time_extinction(i, λ, μ)\n      else\n        logtp_extinction(i, t, λ, μ)\n      end\n    end\n  end\n\n  if log_value\n    log_trans_prob\n  else\n    exp(log_trans_prob)\n  end\nend\n", "meta": {"hexsha": "6020b5adb7b6709ab3c8fa85608527d05326ac25", "size": 8041, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simple/transition_probabilities.jl", "max_stars_repo_name": "albertopessia/SimpleBirthDeathProcess.jl", "max_stars_repo_head_hexsha": "bafe6c3c5a42396d575efb7dd99bab50d46fc358", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simple/transition_probabilities.jl", "max_issues_repo_name": "albertopessia/SimpleBirthDeathProcess.jl", "max_issues_repo_head_hexsha": "bafe6c3c5a42396d575efb7dd99bab50d46fc358", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simple/transition_probabilities.jl", "max_forks_repo_name": "albertopessia/SimpleBirthDeathProcess.jl", "max_forks_repo_head_hexsha": "bafe6c3c5a42396d575efb7dd99bab50d46fc358", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-11T15:30:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T15:30:13.000Z", "avg_line_length": 21.5576407507, "max_line_length": 79, "alphanum_fraction": 0.5841313269, "num_tokens": 2910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159683, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7770317588147654}}
{"text": "export NormalNormalTransformer\n\n@doc raw\"\"\"\n    NormalNormalTransformer(normal_sampler, new_params, old_params=(0.0, 1.0))\n\nGenerate normal random variables from another normal sampler.\n\nTransform samples from a normal distribution sampler into samples from a normal\ndistribution with different parameters. This uses the result that if ``Z`` is a\nstandard normal random variable (``Z \\sim \\text{Normal}(0, 1)``) then\n``X =  \\sigma Z + \\mu`` has distribution ``\\text{Normal}(\\mu, \\sigma^2)``.\n\n# Arguments\n* `normal_sampler::sampler`: a sampler producing normally distributed samples.\n* `new_params::Tuple{Real, Real}`: a tuple (mu, sigma2) giving the mean and\n    variance of the target distribution\n* `old_params::Tuple{Real, Real}=(0.0, 1.0)`: a tuple (mu, sigma2) giving the\n    mean and variance of the normal sampler. Defaults to a standard normal\n    distribution.\n\n# Examples\n```julia\n# Transforming ten standard normal random variables into N(1, 2)\ns = BoxMullerTransformSampler()\nt = NormalNormalTransformer(s, (1, 2))\ntransformed_samples = sample(t, 10)\n```\n\"\"\"\nstruct NormalNormalTransformer <: Sampler\n    normal_sampler::Sampler\n    new_params::NamedTuple{(:mu, :sigma2), Tuple{Real, Real}}\n    old_params::NamedTuple{(:mu, :sigma2), Tuple{Real, Real}}\n    function NormalNormalTransformer(\n        normal_sampler::Sampler,\n        new_params::Tuple{Real, Real},\n        old_params::Tuple{Real, Real}=(0.0, 1.0)\n    )\n        # Name parameter tuples\n        new_params = (mu = new_params[1], sigma2 = new_params[2])\n        old_params = (mu = old_params[1], sigma2 = old_params[2])\n        # Validation\n        if !(old_params[:sigma2] > 0 && new_params[:sigma2] > 0)\n            error(\"variance must be positive\")\n        end\n        new(normal_sampler, new_params, old_params)\n    end\nend\n\n@doc raw\"\"\"\n    sample(s::NormalNormalTransformer, N)\n\nTransform normal samples into normal samples with new parameters.\n\n# Arguments\n* `s::NormalNormalTransformer`: a normal-normal transformer.\n* `N::Integer`: the number of samples to generate.\n\n# Returns\n* `samples::Array{Float64}`: a 2-D array in which each column is a sample.\n\"\"\"\nfunction sample(s::NormalNormalTransformer, N::Integer)\n    old_samples = sample(s.normal_sampler, N)\n    std_samples = (old_samples .- s.old_params[:mu]) ./\n        sqrt(s.old_params[:sigma2])\n    new_samples = sqrt(s.new_params[:sigma2]) .* std_samples .+\n        s.new_params[:mu]\n\n    return new_samples\nend\n", "meta": {"hexsha": "2e1ebfa9be4909c4cb94d6c48be3dc2cec82a9c9", "size": 2453, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Transformation.jl", "max_stars_repo_name": "jacobusmmsmit/MonteCarloZoo.jl", "max_stars_repo_head_hexsha": "39b70fc8b3449a091cadd4c7b804b58b51f2d1b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-05-05T12:50:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T13:44:18.000Z", "max_issues_repo_path": "src/Transformation.jl", "max_issues_repo_name": "jacobusmmsmit/MonteCarloZoo.jl", "max_issues_repo_head_hexsha": "39b70fc8b3449a091cadd4c7b804b58b51f2d1b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-05-03T07:32:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-28T22:12:32.000Z", "max_forks_repo_path": "src/Transformation.jl", "max_forks_repo_name": "jacobusmmsmit/MonteCarloZoo.jl", "max_forks_repo_head_hexsha": "39b70fc8b3449a091cadd4c7b804b58b51f2d1b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-14T16:41:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T22:10:07.000Z", "avg_line_length": 35.0428571429, "max_line_length": 79, "alphanum_fraction": 0.6958825927, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410982634296, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7770317570714288}}
{"text": "using Primes\n\n# These primes are good example primes, as they have p = ±4 (mod 9), so taking cube roots is easy in F_p^2\nplist = [5, 13, 23, 31, 41, 59, 67]\nbigplist = [big(2)^107 - 1, big(2)^521 - 1]\n\n# The prime used in the OG SIDH paper. Does not have above property^\nOGp = big(2)^63*big(3)^41*11-1\n\n# If p = 2 (mod 3) we have an easy supersingular curve\n# E = Affine_EC_TwiHes(F, inv(4*one(F)), zero(F))\n# Or twisted to\n# E = Affine_EC_TwiHes(F, sqrt(F(b))*inv(4*one(F)), zero(F))\n# This is isomorphic to the Weierstrass curve y^2 = x^3 + 1\n\n# Similarly (slightly worse though) If p = 3 (mod 4) we have an easy supersingular curve\n# y^2 = x^3 - x\n# Translating this to twisted Hessian form will be future work\n\n# If p = 1 (mod 12), just run away, dont look back.\n\n\n#Scratch all this, much easier than that...\n#If p = 2 (mod 3), then 0 is a supersingular j-invariant\n#If p = 3 (mod 4), then 1728 is a supersingular j-invariant\n\n\n#Example:\nOGp = big(2)^63*big(3)^41*11-1\nF = Fpsquare(OGp)\nE = TwiHesEC(F, inv(4*one(F)), zero(F))\n#w = F([1850222081870264162797200520152908562431, 2673953603825912900316077551548884232036])\n#MAYBE: all points of order two are of the form (X : 1 : 1)\n#Want to find roots of x^3-a = 0, where a = 3700444163740528325594401040305817124855\n#One lies in F_p, the other two are the roots of x^2 + 3700444163740528325594401040305817124861*x + 4\n#Roots are r1 = 3700444163740528325594401040305817124862 + 1647463043911297475037754062791951339209*i\n#and r2 = 3700444163740528325594401040305817124862 + 2052981119829230850556646977513865785654*i\n#r1 = F([3700444163740528325594401040305817124862, 1647463043911297475037754062791951339209])\n#P = E(-r1, one(F), one(F))\n#E0 = Isogeny(E,P).codomain\n#c = F([3398654792751657841130893587213062545659])*w\n#Q = E0(zero(F), -w, one(F))\n#E1 = Isogeny(E0, Q).codomain\n\n#Simple example with isogeny over F_p\nF = Zmod(31)\nE = TwiHesEC(F, F(1), F(7))\nlistP = allPointsNaive(E)\nphi = Isogeny(E, E(F(13), F(1), F(1)))\n\n\n#Simple example with isogeny over F_p^2\nF = Fpsquare(31)\nE = TwiHesEC(F, F([4, 5]), F([1,2]))\nlistP = allPointsNaive(E)\nphi = Isogeny(E, E(F([9,19]), F([1]), F([1])))\n", "meta": {"hexsha": "3d4083606ba083040e176bbd5a0e58c2475d4933", "size": 2145, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "otherTools/parameters.jl", "max_stars_repo_name": "Jonathke/SIDH-with-twisted-hessian-curves", "max_stars_repo_head_hexsha": "c8599d60fa62a789c40c6d844d0f0db3f94bd093", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "otherTools/parameters.jl", "max_issues_repo_name": "Jonathke/SIDH-with-twisted-hessian-curves", "max_issues_repo_head_hexsha": "c8599d60fa62a789c40c6d844d0f0db3f94bd093", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "otherTools/parameters.jl", "max_forks_repo_name": "Jonathke/SIDH-with-twisted-hessian-curves", "max_forks_repo_head_hexsha": "c8599d60fa62a789c40c6d844d0f0db3f94bd093", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6315789474, "max_line_length": 106, "alphanum_fraction": 0.703962704, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297141, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7770317538108324}}
{"text": "\"\"\"\n    Module Basis1D\nGeneral math tools for 1D bases used by DG\n\"\"\"\n\nmodule Basis1D\n\nexport gauss_lobatto_quad, gauss_quad\nexport jacobiP, grad_jacobiP\nexport vandermonde1D, grad_vandermonde1D\nexport chebyshev\nexport dPhi1D\n\nusing LinearAlgebra\nusing SpecialFunctions\n\n\"\"\"\n    gauss_lobatto_quad(degree, α=0, β=0)\nInitialize Gauss-Legendre-Lobatto (GLL) quadrature nodes and weights (x,w)\nto be able to exactly integrate (α,β) Jacobi polynomial of given degree\n\"\"\"\nfunction gauss_lobatto_quad(degree, α=0, β=0)\n    # Need n points to integrate polynomials of degree 2n-3\n    n = ceil(Int, (degree+3)/2)\n    p = n-1\n    if (α!=0) && (β!=0)\n        error(\"currently only allows alpha == beta == 0\")\n    end\n    x = zeros(p+1)\n    w = zeros(p+1)\n    if p == 0\n        x[1] = 0\n        w[1] = 2\n    elseif p == 1\n        x[1] = -1.0\n        x[2] = 1.0\n        w[1] = 1.0\n        w[2] = 1.0\n    else\n        xint, w = gauss_quad(2*p-3, α+1, β+1)\n        x = [-1 transpose(xint) 1]\n\n        V = vandermonde1D(p,x)\n        w = vec(sum(inv(V*V'),dims=2))\n    end\n    return x[:],w[:]\nend\n\n\"\"\"\n    gauss_quad(degree, α, β)\nInitialize Gaussian quadrature nodes and weights (x,w) to be able to exactly\nintegrate Jacobi Polynomial (α,β) of given degree\n\"\"\"\nfunction gauss_quad(degree, α=0, β=0)\n    # Need n points to integrate polynomials of degree 2n-1\n    n = ceil(Int, (degree+1)/2)\n    p = n-1\n    if p == 0\n        x = [-(α-β)/(α+β+2)]\n        w = [2]\n        return x, w\n    end\n\n    J = zeros(p+1, p+1)\n    h₁ = @. 2*(0:p)+α+β\n    J = diagm(0 => (@. -1/2*(α^2-β^2)/(h₁+2)/h₁), 1 => (@. 2/(h₁[1:p]+2)*sqrt((1:p)*((1:p)+α+β)*((1:p)+α)*((1:p)+β)/(h₁[1:p]+1)/(h₁[1:p]+3))))\n    if α+β<10*eps()\n        J[1,1] = 0.0\n    end\n    J = J + transpose(J) # Finalize symmetric tridiagonal Jacobi matrix\n\n    x, V = eigen(J)\n    w = @. transpose(V[1,:])^2*2^(α+β+1)/(α+β+1)*gamma(α+1)*gamma(β+1)/gamma(α+β+1)\n    return x[:], w[:]\nend\n\n\"\"\"\n    grad_jacobiP(p, r, α, β)\nEvaluate the derivative of Jacobi Polynomial (α, β) of order p at nodes r\n\"\"\"\nfunction grad_jacobiP(p, r, α, β)\n    dP = zeros(length(r))\n    if p != 0\n        dP = sqrt(p*(p+α+β+1))*jacobiP(p-1,r,α+1,β+1)\n    end\n    return dP\nend\n\n\"\"\"\n    jacobiP(p, x, α, β)\nEvaluate Jacobi Polynomial (α, β) of order p at points x\n\"\"\"\nfunction jacobiP(p, x, α, β)\n    xp = x\n    if size(xp, 2) == 1\n        xp = transpose(xp)\n    end\n\n    PL = zeros(p+1,length(xp))\n    γ₀ = 2^(α+β+1)/(α+β+1)*gamma(α+1)*gamma(β+1)/gamma(α+β+1)\n    PL[1,:] .= 1.0/sqrt(γ₀)\n    if p == 0\n        P = transpose(PL)\n        return P\n    end\n    γ₁ = (α+1)*(β+1)/(α+β+3)*γ₀\n    PL[2,:] = ((α+β+2).*xp/2 .+ (α-β)/2)/sqrt(γ₁)\n    if p == 1\n        P = PL[p+1,:]\n        return P\n    end\n\n    aold = 2/(2+α+β)*sqrt((α+1)*(β+1)/(α+β+3))\n\n    for i = 1:p-1\n        h₁ = 2i+α+β\n        anew = 2/(h₁+2)*sqrt((i+1)*(i+1+α+β)*(i+1+α)*(i+1+β)/(h₁+1)/(h₁+3))\n        bnew = -(α^2-β^2)/h₁/(h₁+2)\n        PL[i+2,:] = 1/anew*(-aold*transpose(PL[i,:]).+(xp.-bnew).*transpose(PL[i+1,:]))\n        aold = anew\n    end\n\n    P = PL[p+1,:]\n    return P;\nend\n\n\"\"\"\n    vandermonde1D(p, r)\nInitialize the 1D Vandermonde matrix of order p Legendre polynomials at nodes r\n\"\"\"\nfunction vandermonde1D(p, r)\n    V1D = zeros(length(r), p+1)\n    for j = 1:p+1\n        V1D[:,j] = jacobiP(j-1, r[:], 0, 0)\n    end\n    return V1D\nend\n\n\"\"\"\n    grad_vandermonde1D(p, r)\nInitialize the 1D gradient Vandermonde matrix of order p Legendre polynomials at nodes r\n\"\"\"\nfunction grad_vandermonde1D(p, r)\n    V1D = zeros(length(r), p+1)\n    for j = 1:p+1\n        V1D[:,j] = grad_jacobiP(j-1, r[:], 0, 0)\n    end\n    return V1D\nend\n\n\"\"\"\n    chebyshev(p)\nReturn the 1D Chebyshev nodes of order p on [-1,1]\n\"\"\"\nfunction chebyshev(p)\n    cheby = cos.((p:-1:0)*π/p)\nend\n\n\"\"\"\n    interpolation_matrix1D(x_from, x_to)\nCompute an interpolation matrix from a set of 1D points to another set of 1D points.\nAssumes that points interpolating from provide enough accuracy (aka - they are\nwell spaced out and of high enough order), and define an interval. Points\ninterpolating onto can be of any size, but must be defined on this same interval.\nInterpolation matrix ∈ ℜ^(size of x_to x size of x_from)\n\"\"\"\nfunction interpolation_matrix1D(x_from, x_to)\n    # Create nodal representation of reference bases\n    order = size(x_from,1) - 1 # Assumes order = (size of x_from) - 1\n    n_from = size(x_from,1)\n    l_from = vandermonde1D(order, x_from)\n\n    eye = diagm(0=>ones(n_from))\n    V = reshape(l_from, n_from,n_from)\n    coeffs_phi = V \\ eye\n\n    # Compute reference bases on the output points\n    l_to = vandermonde1D(order, x_to)\n    n_to = size(l_to,1)\n    V_to = reshape(l_to, n_to,n_from)\n\n    # Construct interpolation matrix\n    Interp1D = V_to*coeffs_phi\nend\n\n\"\"\"\n    dPhi1D(x_from, x_to)\nCompute the gradient of the basis functions defined by 1D points on another\nset of 1D points.\n\nAssumes that points interpolating from provide enough accuracy (aka - they are\nwell spaced out and of high enough order), and define an interval. Points\ninterpolating onto can be of any size, but must be defined on this same interval.\ndPhi ∈ ℜ^(size of x_to × size of x_from × 1)\n\"\"\"\nfunction dPhi1D(x_from, x_to)\n    dim = 1\n    # Create nodal representation of reference bases\n    order = size(x_from,1) - 1 # Assumes order = (size of x_from) - 1\n    n_from = size(x_from,1)\n    l_from = vandermonde1D(order, x_from)\n\n    eye = diagm(0=>ones(n_from))\n    V = reshape(l_from, n_from,n_from)\n    coeffs_phi = V \\ eye\n\n    # Compute derivative of reference bases on the output points\n    dl_to = grad_vandermonde1D(order, x_to)\n    n_to = size(dl_to,1)\n    dV = reshape(dl_to, n_to,n_from,dim)\n    # Construct gradient of phi = dV*coeffs_phi\n    dPhi_to = Array{Float64,3}(undef, n_to,n_from,dim)\n    for l = 1:dim\n        dPhi_to[:,:,l] = dV[:,:,l]*coeffs_phi\n    end\n    return dPhi_to\nend\n\nend\n", "meta": {"hexsha": "8cf053b419df13c250261e47ce98bfcc9f2e48e9", "size": 5851, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Basis1D.jl", "max_stars_repo_name": "NoseKnowsAll/DGToolkit", "max_stars_repo_head_hexsha": "e029ed96f337b187876a52a3f63b7636336374c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-22T03:23:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T03:23:48.000Z", "max_issues_repo_path": "src/Basis1D.jl", "max_issues_repo_name": "NoseKnowsAll/DGToolkit", "max_issues_repo_head_hexsha": "e029ed96f337b187876a52a3f63b7636336374c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Basis1D.jl", "max_forks_repo_name": "NoseKnowsAll/DGToolkit", "max_forks_repo_head_hexsha": "e029ed96f337b187876a52a3f63b7636336374c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-22T03:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-22T03:23:50.000Z", "avg_line_length": 26.5954545455, "max_line_length": 142, "alphanum_fraction": 0.6022902068, "num_tokens": 2141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068041, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7770317480690806}}
{"text": "function integrate(f, a, b, n)\n\th = (b - a) / n\n\tx = zeros(1, 3)\n\tx[1] = f(a) + f(b)\n\tfor i ∈ 1:(n - 1)\n\t\tX = a + i*h\n\t\tif iseven(i)\n\t\t\tx[3] += f(X)\n\t\telse\n\t\t\tx[2] += f(X)\n\t\tend\n\tend\n\treturn h*(x[1] + 2*x[3] + 4*x[2])/3\nend\n\nf(x) = x\nprintln(integrate(f, 0, 3, 100))\n", "meta": {"hexsha": "c094f9e7bba519ba816947a0f807139713860d5a", "size": 267, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter4/composite_simpson.jl", "max_stars_repo_name": "Matt8898/julia-numerical", "max_stars_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-05T01:36:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-26T04:07:41.000Z", "max_issues_repo_path": "chapter4/composite_simpson.jl", "max_issues_repo_name": "Matt8898/julia-numerical", "max_issues_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter4/composite_simpson.jl", "max_forks_repo_name": "Matt8898/julia-numerical", "max_forks_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.8333333333, "max_line_length": 36, "alphanum_fraction": 0.4531835206, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95041097139764, "lm_q2_score": 0.8175744717487329, "lm_q1q2_score": 0.7770317478846256}}
{"text": "module SymRCM\n\n# (C) 2020, Petr Krysl\n\nexport symrcm\n\nusing SparseArrays\n\n\"\"\"\n    adjgraph(A)\n\nCompute the adjacency graph from a sparse matrix. \n\nThe sparse matrix `A` is assumed to be symmetric.\nThe results will be wrong if it isn't.\n\n- `sortbydeg`: Should the neighbor lists be sorted by column degree? The default is\n  `true`, but often results of very similar quality are obtained when this is\n  set to `false` and the lists are not sorted. The second option is much\n  faster, as the sorting is expensive.\n\"\"\"\nfunction adjgraph(A::SparseMatrixCSC; sortbydeg = true)\n    colptr = A.colptr\n    rowval = A.rowval\n    ncols = length(colptr)-1\n    neighbors = Vector{Vector{eltype(colptr)}}(undef, ncols)\n    cdeg = diff(colptr) # the degree is colptr[j+1]-colptr[j]\n    for j in 1:ncols\n        cstart = colptr[j]\n        jdeg = cdeg[j]\n        neighbors[j] = [rowval[cstart+m-1] for m in 1:jdeg]\n    end\n    # All of these sorts can be done in parallel,  they are totally independent.\n    # The question is when to switch over to parallel execution so as to\n    # amortize the cost of starting up threads.\n    if sortbydeg\n        for j in 1:ncols\n            sort!(neighbors[j], by = j -> cdeg[j])\n        end\n    end\n    return neighbors\nend\n\n\"\"\"\n    nodedegrees(adjgr::Vector{Vector{Int}})\n\nCompute the degrees of the nodes in the adjacency graph.\n\nconn = [9 1 8 4;\n       1 3 2 8;\n       8 2 7 5;\n       2 6 7 7];\nnfens = 9;\nadjgr = adjgraph(conn, nfens)\nnodedegrees(adjgr)\n\njulia> degrees = node_degrees(adjgr)\n9-element Array{Int64,1}:\n 5\n 6\n 3\n 3\n 3\n 2\n 4\n 7\n 3\n\"\"\"\nfunction nodedegrees(adjgr::Vector{Vector{T}}) where {T}\n    degrees = fill(0, length(adjgr))\n    for k = 1:length(adjgr)\n        degrees[k] = length(adjgr[k])\n    end\n    return degrees\nend\n\n\"\"\"\n    symrcm(adjgr::Vector{Vector{T}}, degrees::Vector{T}) where {T}\n\nReverse Cuthill-McKee node-renumbering algorithm.\n\"\"\"\nfunction symrcm(adjgr::Vector{Vector{T}}, degrees::Vector{T}) where {T}\n    @assert length(adjgr) == length(degrees)\n    # Initialization\n    n = length(adjgr)\n    ndegperm = sortperm(degrees) # sorted nodal degrees\n    inR = fill(false, n) # Is a node in the result list?\n    inQ = fill(false, n) # Is a node in the queue?\n    R = T[]\n    sizehint!(R, n)\n    Q = T[] # Node queue\n    sizehint!(Q, n)\n    while true\n        P = zero(T) # Find the next node to start from\n        while !isempty(ndegperm)\n            i = popfirst!(ndegperm)\n            if !inR[i]\n                P = i\n                break\n            end\n        end\n        if P == zero(T)\n            break # That was the last node\n        end\n        # Now we have a node to start from: put it into the result list\n        push!(R, P); inR[P] = true\n        empty!(Q) # empty the queue\n        append!(Q, adjgr[P]); inQ[adjgr[P]] .= true # put adjacent nodes in queue\n        while length(Q) >= 1\n            C = popfirst!(Q) # child to put into the result list\n            inQ[C] = false # make note: it is not in the queue anymore\n            if !inR[C]\n                push!(R, C); inR[C] = true\n            end\n            for i in adjgr[C] # add all adjacent nodes into the queue\n                if (!inR[i]) && (!inQ[i]) # contingent on not being in result/queue\n                    push!(Q, i); inQ[i] = true\n                end\n            end\n        end\n    end\n    return reverse(R) # reverse the result list\nend\n\n\"\"\"\n    symrcm(A::SparseMatrixCSC; sortbydeg = true) \n\nReverse Cuthill-McKee node-renumbering algorithm.\n\nCompute the adjacency graph from a sparse matrix. The sparse matrix `A` is\nassumed to be symmetric. The results will be wrong if it isn't.\n\n- `sortbydeg`: Should the neighbor lists be sorted by column degree? The default is\n  `true`, but often results of very similar quality are obtained when this is\n  set to `false` and the lists are not sorted. The second option can be much\n  faster, as the sorting is expensive when the neighbor lists are long.\n\"\"\"\nfunction symrcm(A::SparseMatrixCSC; sortbydeg = true) \n    ag = adjgraph(A; sortbydeg = sortbydeg)\n    nd = nodedegrees(ag)\n    return symrcm(ag, nd)\nend\n\nend # module\n", "meta": {"hexsha": "99828efc999d05e9637d6be407236e9ecc46dbea", "size": 4118, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SymRCM.jl", "max_stars_repo_name": "dehann/SymRCM.jl", "max_stars_repo_head_hexsha": "a3ed870b942b1ce18eb5619bb5188d6cf5790486", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SymRCM.jl", "max_issues_repo_name": "dehann/SymRCM.jl", "max_issues_repo_head_hexsha": "a3ed870b942b1ce18eb5619bb5188d6cf5790486", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SymRCM.jl", "max_forks_repo_name": "dehann/SymRCM.jl", "max_forks_repo_head_hexsha": "a3ed870b942b1ce18eb5619bb5188d6cf5790486", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4, "max_line_length": 83, "alphanum_fraction": 0.6204468188, "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995028, "lm_q2_score": 0.8757869851639066, "lm_q1q2_score": 0.7770022389670173}}
{"text": "using JuMP\nusing Clp\n\n\nm = Model(Clp.Optimizer)\n\n@variable(m, x₁ ≥ 0)\n@variable(m, x₂ ≥ 0)\n@variable(m, x₃ ≥ 0)\n\n@objective(m, Max, 2x₁  + 4x₂ + 3x₃)\n@constraint(m, 3x₁  + 4x₂ + 2x₃ ≤ 60)\n@constraint(m, 2x₁  + x₂ + 2x₃ ≤ 40)\n@constraint(m, x₁  + 3x₂ + 2x₃ ≤ 80)\n\nprint(m)\n\noptimize!(m)\n\nstatus = termination_status(m)\n\nprintln(\"Solution status: \", status)\n\nprintln(\"Objective value: \", objective_value(m))\nprintln(\"x₁ = \", value(x₁))\nprintln(\"x₂ = \", value(x₂))\nprintln(\"x₃ = \", value(x₃))\n", "meta": {"hexsha": "9eb793d6d2ad0643fe5b72428a4fa00322c70a36", "size": 490, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week2/from_tutorials/problem_2.jl", "max_stars_repo_name": "InzamamRahaman/COMP6925-2021", "max_stars_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-23T23:33:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T01:47:28.000Z", "max_issues_repo_path": "week2/from_tutorials/problem_2.jl", "max_issues_repo_name": "InzamamRahaman/COMP6925-2021", "max_issues_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week2/from_tutorials/problem_2.jl", "max_forks_repo_name": "InzamamRahaman/COMP6925-2021", "max_forks_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5, "max_line_length": 48, "alphanum_fraction": 0.6306122449, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102514755853, "lm_q2_score": 0.8031737892899221, "lm_q1q2_score": 0.7769985574755623}}
{"text": "using Distributions, LaTeXStrings, Random, Plots\nRandom.seed!(1234)\n\n# Simulate n coin flips with a bias of 0.6\nn = 1000\nflips = rand(n) .< 0.6\np = sum(flips)\nq = n - p\n\n# Create plot of Beta(α,β) density\nα = 10\nβ = 5\n\nx_values = 0:0.001:1\n\n# Get prior and posterior values\nprior = [pdf(Beta(α,β),x) for x in x_values]\nposterior = [pdf(Beta(α+p,β+q),x) for x in x_values]\n\n\n# Create plots\nplot(x_values, posterior, seriestype = :line, label = \"posterior\",\n yaxis = L\"f(\\theta|y)\", xaxis = L\"\\theta\", grid = false)\n\nplot!(x_values, prior, seriestype = :line, label = \"prior\", grid = false)\n\n\nposterior_quantile = cdf(Beta(α+p,β+q),0.65) - cdf(Beta(α+p,β+q),0.55)\nconfidence_interval = [quantile(Beta(α+p,β+q),0.025), quantile(Beta(α+p,β+q),0.975)]\nbayes_mean = mean(Beta(α+p,β+q))\n\n\nplot(x_values, normal_values)\nsavefig(\"beta_prior_coin_ex_2.svg\")\n", "meta": {"hexsha": "729660819f61197bb9a6ef194fa5c61b1a5d5286", "size": 848, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/bayesian-inference-and-graphical-models/code/bayes_posterior_ex.jl", "max_stars_repo_name": "seanrattana/courses", "max_stars_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-08-21T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T15:46:58.000Z", "max_issues_repo_path": "content/bayesian-inference-and-graphical-models/code/bayes_posterior_ex.jl", "max_issues_repo_name": "seanrattana/courses", "max_issues_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-08-23T06:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-26T12:47:12.000Z", "max_forks_repo_path": "content/bayesian-inference-and-graphical-models/code/bayes_posterior_ex.jl", "max_forks_repo_name": "seanrattana/courses", "max_forks_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-08-18T21:23:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T19:14:33.000Z", "avg_line_length": 24.2285714286, "max_line_length": 84, "alphanum_fraction": 0.6768867925, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338035725358, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.776983948056221}}
{"text": "using StatsBase\nusing Plots\n\nParameters = [[[0 0 ; 0 0.16], [0 ; 0]],\n        [[0.85 0.04 ; -0.04 0.85], [0 ; 1.6]],\n        [[0.20 -0.26 ; 0.23 0.22], [0 ; 1.6]],\n        [[-0.15 0.28 ; 0.26 0.24], [0 ; 0.44]]]\n\nf1(vector, Pars) = Pars[1][1] * vector + Pars[1][2]\nf2(vector, Pars) = Pars[2][1] * vector + Pars[2][2]\nf3(vector, Pars) = Pars[3][1] * vector + Pars[3][2]\nf4(vector, Pars) = Pars[4][1] * vector + Pars[4][2]\n\nfunction RandomBarnsleyFern(P, PointNums)\n    Functions = [f1, f2, f3, f4]\n    X = [0.0 for i = 1:PointNums]\n    Y = [0.0 for i = 1:PointNums]\n    for i in 1:PointNums\n        point = [rand() ; rand()]\n        for j in 1:P\n            s = sample([1,2,3,4], Weights([0.01,0.85,0.07,0.07]))\n            point = Functions[s](point, Parameters)\n        end\n        X[i]= point[1]\n        Y[i]= point[2]\n    end\n    return X, Y\nend\n\nfor i in [10, 100]\n    for j in [10000,1000000]\n        x,y = RandomBarnsleyFern(i, j)\n\n        scatter(x,y,markersize = 10^4/j, legend = false, border=:none, color =:green,dpi=200, label = \"Points number = $j Operations number = $i\")\n        savefig(\"C:\\\\Users\\\\Yaghoub\\\\Documents\\\\GitHub\\\\ComputationalPhysics-Fall2021\\\\ProblemSet1\\\\Figs\\\\Q6\\\\RandomBarnsleyFern-p$(i)num$(j).png\")\n    end\nend\n", "meta": {"hexsha": "3ffb0ef8493567293553d809b68268317a155666", "size": 1245, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSet1/Codes/Q6.jl", "max_stars_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_stars_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSet1/Codes/Q6.jl", "max_issues_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_issues_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSet1/Codes/Q6.jl", "max_forks_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_forks_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-21T11:07:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-21T11:07:08.000Z", "avg_line_length": 32.7631578947, "max_line_length": 147, "alphanum_fraction": 0.5493975904, "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195635, "lm_q2_score": 0.8459424353665382, "lm_q1q2_score": 0.7769814201297762}}
{"text": "# ## Quiver plots\n\n#md # ![FILE_NAME.png](images/FILE_NAME.png)\n\nn = 7\nf(x,y) = 1 / hypot(x, y)\nx = repeat(-3:(2*3)/n:3, 1, n) |> vec\ny = repeat(-3:(2*3)/n:3, 1, n)' |> vec\nvx = f.(x,y) .* cos.(atan.(y,x)) |> vec\nvy = f.(x,y) .* sin.(atan.(y,x)) |> vec\n\nquiver(x, y, quiver=(vx, vy), aspect_ratio=:equal)\n", "meta": {"hexsha": "d35e878035198311123dccfb522443659f3043ca", "size": 305, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "site_generator/quiver.jl", "max_stars_repo_name": "goropikari/PlotsGallery.jl", "max_stars_repo_head_hexsha": "9a3c901adfef097f86baa029af4b529b8b6cc302", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2018-12-20T12:33:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:46:34.000Z", "max_issues_repo_path": "site_generator/quiver.jl", "max_issues_repo_name": "goropikari/JuliaPlotsGallery.jl", "max_issues_repo_head_hexsha": "367fca5dbca42a90d1f28e3b5aae1652e3ce4f3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-08T15:39:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T11:01:09.000Z", "max_forks_repo_path": "site_generator/quiver.jl", "max_forks_repo_name": "goropikari/JuliaPlotsGallery.jl", "max_forks_repo_head_hexsha": "367fca5dbca42a90d1f28e3b5aae1652e3ce4f3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-03-19T22:21:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T11:42:32.000Z", "avg_line_length": 23.4615384615, "max_line_length": 50, "alphanum_fraction": 0.5213114754, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7769814198177993}}
{"text": "\"\"\"\nReturn the rotation angle around the \nreference axis for the first vector to be \naligned to the second vector.\n\nArguments\n----------\n:Type{ProjectedRotationAngle}\n    must be type ``ProjectedRotationAngle``\n\ninput:AbstractArray\n    the vector to be rotated\n\ntarget:AbstractArray \n    the target vector to be aligned to\n\nref_axis:AbstractArray\n    the reference axis around which input vector will be rotated\n\ntol_near_zero=1e-15:AbstractFloat\n    (optional) tolerance for the length of the input vectors to be close to zero\n\"\"\"\nfunction gage(::Type{ProjectedRotationAngle}, input::AbstractArray, target::AbstractArray,\n    ref_axis::AbstractArray, tol_near_zero::AbstractFloat=1e-15)\n\n    @debug @assert length(input) == length(target)\n\n    ref_axis_magnitude = norm(ref_axis, 2)\n    input_magnitude = norm(input, 2)   \n    target_magnitude = norm(target, 2)\n\n    if ref_axis_magnitude < tol_near_zero # this means the input vector is the origin\n        return 0. # no need to rotate \n    else \n        unit_ref_axis = ref_axis / ref_axis_magnitude\n    end \n\n    if input_magnitude < tol_near_zero # this means the input vector is the origin\n        return 0. # no need to rotate\n    else \n        unit_input = input / input_magnitude \n    end \n\n    if target_magnitude < tol_near_zero # this means the target vector is the origin\n        return 0. # no need to rotate \n    else \n        unit_target = target / target_magnitude\n    end \n\n    # get the projection along a direction normal to the ref_axis\n    function normal_projection(input::AbstractArray, unit_ref_axis::AbstractArray)\n        return input - dot(input, unit_ref_axis) * unit_ref_axis\n    end\n\n    return gage(RotationAngle, normal_projection(unit_input, unit_ref_axis), \n        normal_projection(unit_target, unit_ref_axis))\nend", "meta": {"hexsha": "39442276aadd2ad16eae8c91e3b8111099a2e4be", "size": 1801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/function/angle/gage_ProjectedRotationAngle.jl", "max_stars_repo_name": "UMOL/MolecularGeometry.jl", "max_stars_repo_head_hexsha": "9923212a2316413fd86cdf92d7a390d4014c4883", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/function/angle/gage_ProjectedRotationAngle.jl", "max_issues_repo_name": "UMOL/MolecularGeometry.jl", "max_issues_repo_head_hexsha": "9923212a2316413fd86cdf92d7a390d4014c4883", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/function/angle/gage_ProjectedRotationAngle.jl", "max_forks_repo_name": "UMOL/MolecularGeometry.jl", "max_forks_repo_head_hexsha": "9923212a2316413fd86cdf92d7a390d4014c4883", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5964912281, "max_line_length": 90, "alphanum_fraction": 0.7240421988, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7769814162504655}}
{"text": "module DiffSolve\n\nexport eulersolve, eulercromer, eulermid, verlet, velverlet, rk4\n\n\"\"\"\nSolve a system of first order ODEs dx/dt = f(t, x(t)) using the Euler method.\nx(t) is a vector.\n\n# Arguments\n- `init`: initial x vector\n- `func`: the function dx/dt = f(t, x(t))\n- `start`: initial t\n- `stop`: final t\n\n# Returns\nvector of all t and matrix containing x at all t (the (i, j) element in the matrix\nrepresents the jth variable in the x vector x[j] at the ith time step t[i]).\n\"\"\"\nfunction eulersolve(func::Function, init::Vector{Float64}, start::Float64, stop::Float64;\n        step::Float64 = 0.01)\n    ts = collect(range(start, stop, step=step)) # exclucive range\n    xs = Matrix{Float64}(undef, length(ts), length(init))\n    xs[1, :] = init\n\n    x = init\n    for (i, t) in enumerate(@view ts[1:end-1])\n        x += step * func(t, x)\n        xs[i + 1, :] = x\n    end\n\n    return ts, xs\nend\n\n\"\"\"\nSolve a system of first order ODEs dx/dt = f(t, x(t)) using the 4th order Runge–Kutta\nmethod (a.k.a. RK4, or Classic Runge–Kutta). x(t) is a vector.\n\n# Arguments\n- `init`: initial x vector\n- `func`: the function dx/dt = f(t, x(t))\n- `start`: initial t\n- `stop`: final t\n\n# Returns\nvector of all t and matrix containing x at all t (the (i, j) element in the matrix\nrepresents the jth variable in the x vector x[j] at the ith time step t[i]).\n\"\"\"\nfunction rk4(func::Function, init::Vector{Float64}, start::Float64, stop::Float64;\n        step::Float64 = 0.01)\n    ts = collect(range(start, stop, step=step)) # exclucive range\n    xs = Matrix{Float64}(undef, length(ts), length(init))\n    xs[1, :] = init\n\n    x = init\n    for (i, t) in enumerate(@view ts[1:end-1])\n        k1 = func(t, x)\n        k2 = func(t + step / 2, x .+ step / 2 * k1)\n        k3 = func(t + step / 2, x .+ step / 2 * k2)\n        k4 = func(t + step, x .+ step * k3)\n\n        x += step / 6 * (k1 + 2k2 + 2k3 + k4)\n        xs[i + 1, :] = x\n    end\n\n    return ts, xs\nend\n\n\"\"\"\nSolve a second order ODE d²x/dt² = a(t, x(t)) using the Euler–Cromer method\n(a.k.a. the semi-implicit euler method, or the Newton–Størmer–Verlet).\n\n# Arguments\n- `initx`, `initv`: initial x (displacement) and dx/dt (velocity v)\n- `acceleration`: the function d²x/dt² = a(t, x(t))\n- `start`: initial t\n- `stop`: final t\n\n# Returns\nt, x, and v (dx/dt) vectors.\n\"\"\"\nfunction eulercromer(acceleration::Function, initx::Float64, initv::Float64,\n        start::Float64, stop::Float64; step::Float64 = 0.01)\n    ts = collect(range(start, stop, step=step)) # exclucive range\n    xs = Vector{Float64}(undef, length(ts))\n    vs = Vector{Float64}(undef, length(ts))\n    xs[1] = initx\n    vs[1] = initv\n\n    x = initx\n    v = initv\n    for (i, t) in enumerate(@view ts[1:end-1])\n        v += step * acceleration(t, x)\n        x += step * v\n\n        xs[i + 1] = x\n        vs[i + 1] = v\n    end\n\n    return ts, xs, vs\nend\n\n\"\"\"\nSolve a second order ODE d²x/dt² = a(t, x(t)) using the Midpoint method\n(a modified euler method).\n\n# Arguments\n- `initx`, `initv`: initial x (displacement) and dx/dt (velocity v)\n- `acceleration`: the function d²x/dt² = a(t, x(t))\n- `start`: initial t\n- `stop`: final t\n\n# Returns\nt, x, and v (dx/dt) vectors. Due to the way this method works, the v vector is the\nvelocity at midpoints between the time steps.\n\"\"\"\nfunction eulermid(acceleration::Function, initx::Float64, initv::Float64,\n        start::Float64, stop::Float64; step::Float64 = 0.01)\n    ts = collect(range(start, stop, step=step)) # exclucive range\n    xs = Vector{Float64}(undef, length(ts))\n    vs = Vector{Float64}(undef, length(ts))\n    xs[1] = initx\n    vs[1] = initv - acceleration(start, initx) * step / 2\n\n    x = initx\n    v = vs[1]\n    for (i, t) in enumerate(@view ts[1:end-1])\n        v += step * acceleration(t, x)\n        x += step * v\n\n        xs[i + 1] = x\n        vs[i + 1] = v\n    end\n\n    return ts, xs, vs\nend\n\n\"\"\"\nSolve a second order ODE d²x/dt² = a(t, x(t)) using Verlet integration\n(a.k.a. the Störmer–Verlet method).\n\n# Arguments\n- `initx`, `initv`: initial x (displacement) and dx/dt (velocity v)\n- `acceleration`: the function d²x/dt² = a(t, x(t))\n- `start`: initial t\n- `stop`: final t\n\n# Returns\nt, x, and v (dx/dt) vectors.\n\"\"\"\nfunction verlet(acceleration::Function, initx::Float64, initv::Float64,\n        start::Float64, stop::Float64; step::Float64 = 0.01)\n    ts = collect(range(start, stop, step=step)) # exclucive range\n    xs = Vector{Float64}(undef, length(ts))\n    vs = Vector{Float64}(undef, length(ts))\n\n    xs[1] = initx\n    vs[1] = initv\n    xs[2] = initx + initv * step + acceleration(start, initx) * step * step / 2\n\n    for i in 2:length(xs)-1\n        xs[i + 1] = 2 * xs[i] - xs[i - 1] + acceleration(ts[i], xs[i]) * step * step\n        vs[i + 1] = (xs[i + 1] - xs[i]) / step\n    end\n\n    return ts, xs, vs\nend\n\n\"\"\"\nSolve a second order ODE d²x/dt² = a(t, x(t)) using the velocity Verlet method\n\n# Arguments\n- `initx`, `initv`: initial x (displacement) and dx/dt (velocity v)\n- `acceleration`: the function d²x/dt² = a(t, x(t))\n- `start`: initial t\n- `stop`: final t\n\n# Returns\nt, x, and v (dx/dt) vectors.\n\"\"\"\nfunction velverlet(acceleration::Function, initx::Float64, initv::Float64,\n        start::Float64, stop::Float64; step::Float64 = 0.01)\n    ts = collect(range(start, stop, step=step)) # exclucive range\n    xs = Vector{Float64}(undef, length(ts))\n    vs = Vector{Float64}(undef, length(ts))\n\n    xs[1] = initx\n    vs[1] = initv\n\n    for i in 1:length(ts)-1\n        accbefore = acceleration(ts[i], xs[i])\n        xs[i + 1] = xs[i] + vs[i] * step + accbefore * step * step / 2\n        accafter = acceleration(ts[i + 1], xs[i + 1])\n        vs[i + 1] = vs[i] + (accbefore + accafter) * step / 2\n    end\n\n    return ts, xs, vs\nend\n\nend\n", "meta": {"hexsha": "cef184a0c5704b9259a65620b6d7301a57398db3", "size": 5708, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ps9-ode-solvers-logistic-map/DiffSolve.jl", "max_stars_repo_name": "slhshamloo/comp-phys", "max_stars_repo_head_hexsha": "04d6759e0eb9d7e16e2781417d389bc15e22b01b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ps9-ode-solvers-logistic-map/DiffSolve.jl", "max_issues_repo_name": "slhshamloo/comp-phys", "max_issues_repo_head_hexsha": "04d6759e0eb9d7e16e2781417d389bc15e22b01b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ps9-ode-solvers-logistic-map/DiffSolve.jl", "max_forks_repo_name": "slhshamloo/comp-phys", "max_forks_repo_head_hexsha": "04d6759e0eb9d7e16e2781417d389bc15e22b01b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.54, "max_line_length": 89, "alphanum_fraction": 0.6063419762, "num_tokens": 1951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7769814126831316}}
{"text": "using SpecialFunctions\nusing Base.MathConstants\nusing DataFrames, CSV\nusing Printf\n\n\"\"\"\n    gamma_derivatives()\n\nDerive a table of derivatives of the Gamma function at 1, i.e., Gamma^{(m)}(a)\n\nThis code is used to create the results, which are included in the main code via a lookup table.\n\n\"\"\"\nfunction gamma_derivatives(k::Integer, x::Float64)\n    #    general form from: http://erikerlandson.github.io/blog/2016/06/15/computing-derivatives-of-the-gamma-function/\n    return SpecialFunctions.gamma(x) * D(k,0,x)\nend\n\nfunction D(k::Integer, n::Integer, x::Float64)\n    # general form from: http://erikerlandson.github.io/blog/2016/06/15/computing-derivatives-of-the-gamma-function/\n    if n<0\n        throw(DomainError(n))\n    elseif k<0\n        throw(DomainError(k))\n    end\n    if k==0\n        return 1\n    elseif k==1\n        return SpecialFunctions.polygamma(n,x)\n    else\n        total = D(k-1,n+1,x)\n        for j=0:n\n            total += binomial(n,j) * D(1,j,x) * D(k-1,n-j,x)\n        end\n        return total\n    end\nend\n\nfunction g1(t::Int) # Crandall,2012, p.17\n    # t derivate of Gamma function at 1\n    PG21 = -2.4041138063191902 # SpecialFunctions.polygamma(2,1)\n    PG41 = -24.8862661234409   # SpecialFunctions.polygamma(4,1)\n    if t==0\n        return 1.0\n    elseif t==1\n        return -γ\n    elseif t==2\n        # return γ^2 - γ + pi^2/6, Crandall seems to be wrong on this\n        return γ^2 + pi^2/6  # from Mathematica\n    elseif t==3\n        # return -2*γ^3 + 9*γ^2 - (π^2+6)*γ + 3*π^2/2 - 4*SpecialFunctions.zeta(3), Crandall seems to be wrong on this\n        return -γ^3  - π^2*γ/2 + PG21 # from Mathematica\n    elseif t==4\n        return γ^4 + γ^2*π^2 + 3*π^4/20 - 4*γ*PG21 # from Mathematica\n    elseif t==5\n        return -γ^5 - (20/12)*γ^3*π^2 - (9/12)*γ*π^4 + (10*γ^2 + (20/12)*π^2)*PG21 + PG41 # from Mathematica\n    else\n        return NaN\n    end\nend\n\nfunction g2(t::Int) # http://erikerlandson.github.io/blog/2016/06/15/computing-derivatives-of-the-gamma-function/\n    # t derivate of Gamma function at 1\n    return gamma_derivatives(t,1.0) \nend\n\n\n# #### output a table\n# K = 14\n# k = collect(0:K)\n# G1 = zeros(Float64, K+1)\n# G2 = zeros(Float64, K+1)\n# for i=1:K+1\n#     G1[i] = g1(i-1)\n#     G2[i] = g2(i-1)\n#     @printf(\"G1[i] = %.20f, G2[i] = %.20f\\n\", G1[i], G2[i])\n# end\n\n# df = DataFrame( k=k, G1=G1, G2=G2 )\n# CSV.write(\"../data/gamma_derivatives.csv\", df)\n\n", "meta": {"hexsha": "8f2332b05349aa918203cf230666bb4da0e1c930", "size": 2403, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gamma_derivatives.jl", "max_stars_repo_name": "AshtonSBradley/Polylogarithms.jl", "max_stars_repo_head_hexsha": "f52e3075cd1d87b0d67d26c72cd1a79a365eddcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-08-24T09:17:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T10:54:45.000Z", "max_issues_repo_path": "src/gamma_derivatives.jl", "max_issues_repo_name": "AshtonSBradley/Polylogarithms.jl", "max_issues_repo_head_hexsha": "f52e3075cd1d87b0d67d26c72cd1a79a365eddcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-11-18T00:06:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-18T10:35:43.000Z", "max_forks_repo_path": "src/gamma_derivatives.jl", "max_forks_repo_name": "AshtonSBradley/Polylogarithms.jl", "max_forks_repo_head_hexsha": "f52e3075cd1d87b0d67d26c72cd1a79a365eddcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-17T16:20:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T09:32:06.000Z", "avg_line_length": 29.3048780488, "max_line_length": 119, "alphanum_fraction": 0.6125676238, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7769811981473795}}
{"text": "# collatz conjenture\n\n\n#Jl Plots\n\nfunction collatz_next(n)\n    if n % 2 == 0\n        return n ÷ 2\n    else\n        return 3n+1\n    end\nend\n\nfunction collatz_path(n)\n    steps = Vector{Int}()\n    while n != 1\n        push!(steps, n)\n        n = collatz_next(n)\n    end\n    push!(steps, 1)\n    return steps\nend\n\nusing Plots\n\nx = 1:10000\ny = length.(collatz_path.(x))\nPlots.scatter(x, y, label=\"Stopping time\", legend=:topleft, size=(800,600))\n\nx = 2 .^ (0:13)\ny = length.(collatz_path.(x))\nPlots.scatter!(x, y, color=:red, label=\"for powers of two\")\n", "meta": {"hexsha": "0c0b8af74619afe99a81df03bbb01501ad980253", "size": 548, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/collatz-conjenture/collatz.jl", "max_stars_repo_name": "Ellon-M/visualizations", "max_stars_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/collatz-conjenture/collatz.jl", "max_issues_repo_name": "Ellon-M/visualizations", "max_issues_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/collatz-conjenture/collatz.jl", "max_forks_repo_name": "Ellon-M/visualizations", "max_forks_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.6060606061, "max_line_length": 75, "alphanum_fraction": 0.5967153285, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672954, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7769811959489832}}
{"text": "module DTWDTfunctions\nexport test, computeErrorFunction, accumulateErrorFunction, backtrackDistanceFunction, computeDTWerror\n\n\"\"\"\n USAGE: err = computeErrorFunction( u1, u0, nSample, lag )\n\n INPUT:\n\n   u1      = trace that we want to warp; size = (nsamp,1)\n\n   u0      = reference trace to compare with: size = (nsamp,1)\n\n   nSample = numer of points to compare in the traces\n\n   lag     = maximum lag in sample number to search\n\n   norm    = 'L2' or 'L1' (default is 'L2')\n\n OUTPUT:\n\n    err = the 2D error function; size = (nsamp,2*lag+1)\n\n The error function is equation 1 in Hale, 2013.\n\n You could umcomment the L1 norm and comment the L2 norm if you want on Line 29\n\n Original by Di Yang\n Last modified by Dylan Mikesell (25 Feb. 2015)\n\"\"\"\nfunction computeErrorFunction(u1::Union{Array{Float32,1},Array{Float64,1}}, u0::Union{Array{Float32,1},Array{Float64,1}}, nSample::Int, lag::Int; norm::String=\"L2\")\n\n    if lag >= nSample\n        error(\"computeErrorFunction:lagProblem \",\"lag must be smaller than nSample\");\n    end\n\n    #using JLD2\n    #@load \"../exampledata/sineShiftData.jld2\"\n    #nSample = length(u0)\n    #lag = 80\n    #norm = \"L2\"\n\n    # Allocate error function variable\n    err = zeros(Float64, nSample, 2 * lag + 1 );\n\n    #--------------------------------------------------------------------------\n    # initial error calculation\n    for ll = -lag:lag # loop over lags\n\n        thisLag = ll + lag + 1;\n\n        for ii = 1:nSample # loop over samples\n\n            if ( ii + ll >= 1 && ii + ll <= nSample ) # skip corners for now, we will come back to these\n\n                diff = u1[ii] - u0[ii + ll]; # sample difference\n\n                if norm == \"L2\"\n                        err[ii, thisLag] = diff^2; # difference squared error\n                elseif norm == \"L1\"\n                        err[ii, thisLag] = abs(diff); # absolute value errors\n                else\n                    error(\"norm type is not defined.\")\n                end\n\n            end\n\n        end\n\n    end\n\n    #--------------------------------------------------------------------------\n    # Now fix corners with constant extrapolation\n    for ll = -lag:lag # loop over lags\n\n        thisLag = ll + lag + 1;\n\n        for ii = 1:nSample # loop over samples\n\n            if ( ii + ll < 1 ) # lower left corner (negative lag, early time)\n\n                err[ii, thisLag] = err[-ll + 1, thisLag];\n\n            elseif ( ii + ll > nSample ) # upper right corner (positive lag, late time)\n\n                err[ii, thisLag] = err[nSample - ll, thisLag];\n\n            end\n\n        end\n\n    end\n\n    return err\nend\n\n\n\"\"\"\n\n USAGE: d = accumulation_diw_mod( dir, err, nSample, lag, b )\n\n INPUT:\n\n   dir = accumulation direction ( dir > 0 = forward in time, dir <= 0 = backward in time)\n\n   err = the 2D error function; size = (nsamp,2*lag+1)\n\n   nSample = numer of points to compare in the traces\n\n   lag = maximum lag in sample number to search\n\n   b = strain limit (integer value >= 1)\n\n OUTPUT:\n\n    d = the 2D distance function; size = (nsamp,2*lag+1)\n\n The function is equation 6 in Hale, 2013.\n\n Original by Di Yang Last modified by Dylan Mikesell (25 Feb. 2015)\n\"\"\"\nfunction accumulateErrorFunction(dir::Int, err::Array{Float64,2}, nSample::Int, lag::Int, b::Int)\n\n    #nSample = length(u0)\n    #lag = 80\n    #dir = -1\n\n    nLag = (2 * lag ) + 1; # number of lags from [ -lag : +lag ]\n\n    # allocate distance matrix\n    d = zeros(Float64, nSample, nLag);\n\n    #--------------------------------------------------------------------------\n    # Setup indices based on forward or backward accumulation direction\n    #--------------------------------------------------------------------------\n    if dir > 0            # FORWARD\n        iBegin = 1;       # start index\n        iEnd   = nSample; # end index\n        iInc   = 1;       # increment\n    else                  # BACKWARD\n        iBegin = nSample; # start index\n        iEnd   = 1;       # stop index\n        iInc   = -1;      # increment\n    end\n    #--------------------------------------------------------------------------\n    # Loop through all times ii in forward or backward direction\n\n    for ii = iBegin:iInc:iEnd\n\n        # min/max to account for the edges/boundaries\n        ji = max(1, min(nSample, ii - iInc ));     # i-1 index\n        jb = max(1, min(nSample, ii - iInc * b )); # i-b index\n\n        # loop through all lags l\n        for ll = 1:nLag\n\n            # -----------------------------------------------------------------\n            # check limits on lag indices\n            lMinus1 = ll - 1; # lag at l-1\n\n            if lMinus1 < 1  # check lag index is greater than 1\n                lMinus1 = 1; # make lag = first lag\n            end\n\n            lPlus1 = ll + 1; # lag at l+1\n\n            if lPlus1 > nLag # check lag index less than max lag\n    #             lPlus1 = nLag - 1; # D.Y. version\n                lPlus1 = nLag; # D.M. version\n            end\n            # -----------------------------------------------------------------\n\n            # get distance at lags (ll-1, ll, ll+1)\n            distLminus1 = d[jb, lMinus1]; # minus:  d( i-b, j-1 )\n            distL       = d[ji, ll];      # actual: d( i-1, j   )\n            distLplus1  = d[jb, lPlus1];  # plus:   d( i-b, j+1 )\n\n            if ji != jb # equation 10 in Hale (2013)\n                for kb = ji:-iInc:jb+iInc # sum errors over i-1:i-b+1\n                    distLminus1 = distLminus1 + err[kb, lMinus1];\n                    distLplus1  = distLplus1  + err[kb, lPlus1];\n                end\n            end\n\n            # equation 6 (if b=1) or 10 (if b>1) in Hale (2013) after treating boundaries\n            d[ii, ll] = err[ii, ll] + min(distLminus1, distL, distLplus1);\n        end\n    end\n    return d\nend\n\n\n\"\"\"\n\n USAGE: stbar = backtrackDistanceFunction( dir, d, err, lmin, b )\n\n INPUT:\n\n   dir   = side to start minimization ( dir > 0 = front, dir <= 0 =  back)\n\n   d     = the 2D distance function; size = (nsamp,2*lag+1)\n\n   err   = the 2D error function; size = (nsamp,2*lag+1)\n\n   lmin  = minimum lag to search over\n\n   b     = strain limit (integer value >= 1)\n\n OUTPUT:\n\n   stbar = vector of integer shifts subject to |u(i)-u(i-1)| <= 1/b\n\n The function is equation 2 in Hale, 2013.\n\n Original by Di Yang Last modified by Dylan Mikesell (19 Dec. 2014)\n\n\"\"\"\nfunction backtrackDistanceFunction(dir::Int, d::Array{Float64,2}, err::Array{Float64,2}, lmin::Int, b::Int)\n\n    #d = dist\n    #dir = -1\n    #lmin = -maxLag\n    #b = 1\n\n    nSample = size(d,1); # number of samples\n    nLag    = size(d,2); # number of lags\n    stbar   = zeros(Int64, nSample); # allocate\n\n    #--------------------------------------------------------------------------\n    # Setup indices based on forward or backward accumulation direction\n    #--------------------------------------------------------------------------\n    if dir > 0            # FORWARD\n        iBegin = 1;       # start index\n        iEnd   = nSample; # end index\n        iInc   = 1;       # increment\n    else                  # BACKWARD\n        iBegin = nSample; # start index\n        iEnd   = 1;       # stop index\n        iInc   = -1;      # increment\n    end\n    #--------------------------------------------------------------------------\n    # start from the end (front or back)\n    ll0 = argmin(d[iBegin,:]); # find minimum accumulated distance at front or back depending on 'dir'\n    stbar[iBegin] = ll0 + lmin - 1; # absolute value of integer shift\n    #--------------------------------------------------------------------------\n    # move through all time samples in forward or backward direction\n    ii = iBegin;\n\n    while ii != iEnd\n        if ii == iBegin\n            ll = ll0;\n        else\n            ll = ll_next\n        end\n\n        # min/max for edges/boundaries\n        ji = max( 1, min(nSample, ii + iInc) );\n        jb = max( 1, min(nSample, ii + iInc * b) );\n\n        # -----------------------------------------------------------------\n        # check limits on lag indices\n\n        lMinus1 = ll - 1; # lag at l-1\n\n        if lMinus1 < 1 # check lag index is greater than 1\n            lMinus1 = 1; # make lag = first lag\n        end\n\n        lPlus1 = ll + 1; # lag at l+1\n\n        if lPlus1 > nLag # check lag index less than max lag\n            lPlus1 = nLag; # D.M. and D.Y. version\n        end\n        # -----------------------------------------------------------------\n        # get distance at lags (ll-1, ll, ll+1)\n        distLminus1 = d[jb, lMinus1]; # minus:  d( i-b, j-1 )\n        distL       = d[ji, ll];      # actual: d( i-1, j   )\n        distLplus1  = d[jb, lPlus1];  # plus:   d( i-b, j+1 )\n\n        if ji != jb # equation 10 in Hale (2013)\n            for kb = ji:iInc:jb-iInc # sum errors over i-1:i-b+1\n                distLminus1 = distLminus1 + err[kb, lMinus1];\n                distLplus1  = distLplus1  + err[kb, lPlus1];\n            end\n        end\n\n        dl = min(distLminus1, distL, distLplus1); # update minimum distance to previous sample\n\n        if ( dl != distL ) # then ll != ll and we check forward and backward\n            if ( dl == distLminus1 )\n                global ll_next = lMinus1;\n            else # ( dl == lPlus1 )\n                global ll_next = lPlus1;\n            end\n        else\n            ll_next = ll\n        end\n\n        # assume ii = ii - 1\n        ii += iInc; # previous time sample\n\n        stbar[ii] = ll_next + lmin - 1; # absolute integer of lag\n        # now move to correct time index, if smoothing difference over many\n        # time samples using 'b'\n\n        if ( ll_next == lMinus1 || ll_next == lPlus1 ) # check edges to see about b values\n            if ( ji != jb ) # if b>1 then need to move more steps\n                for kb = ji:iInc:jb - iInc\n                    ii = ii + iInc; # move from i-1:i-b-1\n                    stbar[ii] = ll_next + lmin - 1; # constant lag over that time\n                end\n            end\n        end\n    end\n\n    return stbar\n\n    #------------------------#\n    # while loop is tricky with Julia\n    # we modified ll to ll_next\n    # this is the original source from dylanmikesell\n    #------------------------#\n    # ii = iBegin;\n    # while (ii ~= iEnd)\n    #\n    #     % min/max for edges/boundaries\n    #     ji = max( 1, min( [ nSample, ii + iInc ] ) );\n    #     jb = max( 1, min( [ nSample, ii + iInc * b ] ) );\n    #\n    #     % -----------------------------------------------------------------\n    #     % check limits on lag indices\n    #     lMinus1 = ll - 1; % lag at l-1\n    #\n    #     if lMinus1 < 1 % check lag index is greater than 1\n    #         lMinus1 = 1; % make lag = first lag\n    #     end\n    #\n    #     lPlus1 = ll + 1; % lag at l+1\n    #\n    #     if lPlus1 > nLag % check lag index less than max lag\n    #         lPlus1 = nLag; % D.M. and D.Y. version\n    #     end\n    #     % -----------------------------------------------------------------\n    #\n    #     % get distance at lags (ll-1, ll, ll+1)\n    #     distLminus1 = d( jb, lMinus1 ); % minus:  d( i-b, j-1 )\n    #     distL       = d( ji, ll );      % actual: d( i-1, j   )\n    #     distLplus1  = d( jb, lPlus1 );  % plus:   d( i-b, j+1 )\n    #\n    #     if (ji ~= jb) % equation 10 in Hale (2013)\n    #         for kb = ji : iInc : jb - iInc % sum errors over i-1:i-b+1\n    #             distLminus1 = distLminus1 + err( kb, lMinus1 );\n    #             distLplus1  = distLplus1  + err( kb, lPlus1  );\n    #         end\n    #     end\n    #\n    #     dl = min( [ distLminus1, distL, distLplus1 ] ); % update minimum distance to previous sample\n    #\n    #     if ( dl ~= distL ) % then ll ~= ll and we check forward and backward\n    #         if ( dl == distLminus1 )\n    #             ll = lMinus1;\n    #         else % ( dl == lPlus1 )\n    #             ll = lPlus1;\n    #         end\n    #     end\n    #\n    #     % assume ii = ii - 1\n    #     ii = ii + iInc; % previous time sample\n    #\n    #     stbar(ii) = ll + lmin - 1; % absolute integer of lag\n    #\n    #     % now move to correct time index, if smoothing difference over many\n    #     % time samples using 'b'\n    #     if ( ll == lMinus1 || ll == lPlus1 ) % check edges to see about b values\n    #         if ( ji ~= jb ) % if b>1 then need to move more steps\n    #             for kb = ji : iInc : jb - iInc\n    #                 ii = ii + iInc; % move from i-1:i-b-1\n    #                 stbar(ii) = ll + lmin - 1; % constant lag over that time\n    #             end\n    #         end\n    #     end\n    # end\n\nend\n\n\n\"\"\"\n\n Compute the accumulated error along the warping path for Dynamic\n Time Warping.\n\n USAGE: function error = computeDTWerror( Aerr, u, lag0 )\n\n INPUT:\n\n   Aerr = error MATRIX (equation 13 in Hale, 2013)\n\n   u    = warping function (samples) VECTOR\n\n   lag0 = value of maximum lag (samples) SCALAR\n\n Written by Dylan Mikesell Last modified: 25 February 2015\n\"\"\"\nfunction computeDTWerror(Aerr::Array{Float64,2}, u::Array{Int64,1}, lag0::Int)\n\n    npts = length(u);\n\n    if size(Aerr,1) != npts\n        #println(\"Funny things with dimensions of error matrix: check inputs.\");\n        #Aerr = transpose(Aerr);\n        error(\"Funny things with dimensions of error matrix: check inputs.\")\n    end\n\n    error = 0; # initialize\n\n    # accumulate error\n    for ii = 1:npts\n        idx = lag0 + 1 + u[ii]; # index of lag\n        error += Aerr[ii,idx]; # sum error\n    end\n\n    return error\n\nend\n\n\nend\n", "meta": {"hexsha": "65980c8a9a9881ce32ce7b19efa87a48fe1213e2", "size": 13406, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "jaredbryan881/DTWDT.jl", "max_stars_repo_head_hexsha": "38e1e4ca90b42d44929aa8f76fd9ae8dac0721bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-07-03T19:03:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-05T18:35:14.000Z", "max_issues_repo_path": "src/functions.jl", "max_issues_repo_name": "jaredbryan881/DTWDT.jl", "max_issues_repo_head_hexsha": "38e1e4ca90b42d44929aa8f76fd9ae8dac0721bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions.jl", "max_forks_repo_name": "jaredbryan881/DTWDT.jl", "max_forks_repo_head_hexsha": "38e1e4ca90b42d44929aa8f76fd9ae8dac0721bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-09T21:40:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-09T21:40:08.000Z", "avg_line_length": 31.3957845433, "max_line_length": 164, "alphanum_fraction": 0.4870953304, "num_tokens": 3764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.776981195554191}}
{"text": "# indicator of the zero cone\n\n\"\"\"\n  IndZero()\n\nReturns the indicator function of the zero point, or \"zero cone\", i.e.,\n  `g(x) = 0 if x = 0, +∞ otherwise`\n\"\"\"\n\nimmutable IndZero <: IndicatorConvexCone end\n\nfunction (f::IndZero){T <: RealOrComplex}(x::AbstractArray{T})\n  for k in eachindex(x)\n    if x[k] != zero(T)\n      return Inf\n    end\n  end\n  return 0.0\nend\n\nfunction prox!{T <: RealOrComplex}(f::IndZero, x::AbstractArray{T}, y::AbstractArray{T}, gamma::Real=1.0)\n  for k in eachindex(x)\n    y[k] = zero(T)\n  end\n  return 0.0\nend\n\nfun_name(f::IndZero) = \"indicator of the zero cone\"\nfun_dom(f::IndZero) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::IndZero) = \"x ↦ 0 if all(x = 0), +∞ otherwise\"\nfun_params(f::IndZero) = \"none\"\n\nfunction prox_naive(f::IndZero, x::AbstractArray, gamma::Real=1.0)\n  return zero(x), 0.0\nend\n", "meta": {"hexsha": "590e4b0fc63528be3fd341b3ca4cdd73253c7a9e", "size": 843, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indZero.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/indZero.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/indZero.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4166666667, "max_line_length": 105, "alphanum_fraction": 0.6607354686, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7769811913818324}}
{"text": "using Distributed\n\n## Function to get the number of points inside a circle\nfunction in_circle_points(n)\n    points_in = 0 ## Points inside the circle\n    for i = 1:n\n        x, y = rand(), rand() ## Randomly generate x,y btwn 0 & 1\n        ## Count if generated value is within radius of the circle\n        ## int the unit square\n        points_in += (x*x + y*y) <= 1\n    end\n    ## Return the number of points in\n    return points_in\nend\n\n## Run code in parallel across n cores\nfunction parallel_pi(n)\n    ## Create the number of workers specified by the\n    p = nworkers()\n    ## Combine results via addition (+)\n    n_in = @distributed (+) for i=1:p\n        in_circle_points(n / p)\n    end\n    return 4 * n_in / n ## Approximation of pi\nend\n\n## Run code serially on 1 worker\nfunction serial_pi(n)\n    n_in = in_circle_points(n)\n    return 4 * n_in / n\nend\n", "meta": {"hexsha": "6c28b2ff245f03f19abf1496df20e734f1e52582", "size": 859, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "pi_approximation.jl", "max_stars_repo_name": "Ochibobo/pi_approximation_julia", "max_stars_repo_head_hexsha": "21ae3efc833f042ae54502cf388260dc4b6210f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-18T11:53:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T11:53:32.000Z", "max_issues_repo_path": "pi_approximation.jl", "max_issues_repo_name": "Ochibobo/pi_approximation_julia", "max_issues_repo_head_hexsha": "21ae3efc833f042ae54502cf388260dc4b6210f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pi_approximation.jl", "max_forks_repo_name": "Ochibobo/pi_approximation_julia", "max_forks_repo_head_hexsha": "21ae3efc833f042ae54502cf388260dc4b6210f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.84375, "max_line_length": 66, "alphanum_fraction": 0.6402793946, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7769643839944208}}
{"text": "#= Fornberg algorithm\nThis implements the Fornberg (1988) algorithm (https://doi.org/10.1090/S0025-5718-1988-0935077-0)\nand hermite-based finite difference Fornberg(2020) algorithm (https://doi.org/10.1093/imanum/draa006)\nto obtain Finite Difference weights over arbitrary points to arbitrary order.\nInputs:\n        order: The derivative order for which we need the coefficients\n        x0   : The point in the array 'x' for which we need the coefficients\n        x    : A dummy array with relative coordinates, e.g., central differences\n               need coordinates centred at 0 while those at boundaries need\n               coordinates starting from 0 to the end point\n        dfdx : optional argument to consider weights of the first-derivative of function or not\n                if    dfdx == false (default kwarg), implies Fornberg(1988)\n                      dfdx == true,                  implies Fornberg(2020)\n    Outputs:\n        if dfdx == false (default kwarg),   _C : weights to approximate derivative of required order using function values only.\n                                 else,   _D,_E : weights to approximate derivative of required order using function and its first- \n                                                 derivative values respectively.                                             \n=#\n\nfunction calculate_weights(order::Int, x0::T, x::AbstractVector; dfdx::Bool = false) where T<:Real\n    N = length(x)\n    @assert order < N \"Not enough points for the requested order.\"\n    M = order\n    c1 = one(T)\n    c4 = x[1] - x0\n    C = zeros(T, N, M+1)\n    C[1,1] = 1\n    @inbounds for i in 1 : N-1\n        i1 = i + 1\n        mn = min(i, M)\n        c2 = one(T)\n        c5 = c4\n        c4 = x[i1] - x0\n        for j in 0 : i-1\n            j1 = j + 1\n            c3 = x[i1] - x[j1]\n            c2 *= c3\n            if j == i-1\n                for s in mn : -1 : 1\n                    s1 = s + 1\n                    C[i1,s1] = c1*(s*C[i,s] - c5*C[i,s1]) / c2\n                end\n                C[i1,1] = -c1*c5*C[i,1] / c2\n           end\n            for s in mn : -1 : 1\n                s1 = s + 1\n                C[j1,s1] = (c4*C[j1,s1] - s*C[j1,s]) / c3\n            end\n            C[j1,1] = c4 * C[j1,1] / c3\n        end\n        c1 = c2\n    end\n    #=\n        This is to fix the problem of numerical instability which occurs when the sum of the stencil_coefficients is not\n        exactly 0.\n        https://scicomp.stackexchange.com/questions/11249/numerical-derivative-and-finite-difference-coefficients-any-update-of-the-fornb\n        Stack Overflow answer on this issue.\n        http://epubs.siam.org/doi/pdf/10.1137/S0036144596322507 - Modified Fornberg Algorithm\n    =#\n    _C = C[:,end]\n    if order != 0\n        _C[div(N,2)+1] -= sum(_C)\n    end\n    if dfdx == false\n        return _C\n    else\n        A = x .- x';\n        s = sum(1 ./ (A + I(N)), dims = 1) .- 1;\n        cp = factorial.(0:M);\n        cc = C./cp'\n        c̃ = zeros(N, M+2);\n        for k in 1:M+1\n           c̃[:,k+1] = sum(cc[:,1:k].*cc[:,k:-1:1], dims = 2);\n        end\n        E = c̃[:,1:M+1] - (x .- x0).*c̃[:,2:M+2];\n        D = c̃[:,2:M+2] + 2*E.*s';\n        D = D.*cp';\n        E = E.*cp';\n\n        _D = D[:,end];   _E = E[:,end]\n        return _D, _E\n    end\nend\n", "meta": {"hexsha": "3aac12116b38a3c27ed9ed06e1029962d6a18bc5", "size": 3279, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/discretization/fornberg.jl", "max_stars_repo_name": "pfcrowe/MethodOfLines.jl", "max_stars_repo_head_hexsha": "ab2a6e1c3e5214821770a67ad604e8d326f7c152", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2021-12-15T23:57:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:07:05.000Z", "max_issues_repo_path": "src/discretization/fornberg.jl", "max_issues_repo_name": "pfcrowe/MethodOfLines.jl", "max_issues_repo_head_hexsha": "ab2a6e1c3e5214821770a67ad604e8d326f7c152", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47, "max_issues_repo_issues_event_min_datetime": "2021-12-21T01:12:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:48:01.000Z", "max_forks_repo_path": "src/discretization/fornberg.jl", "max_forks_repo_name": "pfcrowe/MethodOfLines.jl", "max_forks_repo_head_hexsha": "ab2a6e1c3e5214821770a67ad604e8d326f7c152", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-12-16T13:48:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T13:46:41.000Z", "avg_line_length": 39.0357142857, "max_line_length": 137, "alphanum_fraction": 0.5129612687, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388754, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7769470298032622}}
{"text": "\n\"\"\"\nStationary vector with iterative methods\n\"\"\"\n\n\"\"\"\nstguess(Q::MatT, ::Type{Tv} = Float64)::Vector{Tv}\n\nGet a vector which is guessed as the stationary vector of CTMC.\nThis is used as the initial vector for the iterative methods.\n\"\"\"\n\nfunction stguess(Q::MatT, ::Type{Tv} = Float64)::Vector{Tv} where {Tv,MatT}\n    m, n = size(Q)\n    @assert m == n\n    result = Vector{Tv}(undef, n)\n    for (i,x) in enumerate(spdiag(Q))\n        result[i] = 1/x\n    end\n    result ./= sum(result)\nend\n\n\"\"\"\nstgs(Q::SparseCSC{Tv,Ti}, x0::Vector{Tv}=stguess(Q,Tv); maxiter=5000, steps=20, rtol::Tv=Tv(1.0e-6))\n\nGet a stationary vector of CTMC.\n\nParameters:\n- Q: CTMC Kernal\n- x0: Initial vector for iteration\n- maxiter: The maximum number of iteration. The algorithm stops when the number of iteration becomes maxiter.\n- steps: The number of steps to check the convergence\n- rtol: the tolerance error. When the relative errors of two successive vectors with steps attains rtol, the algorithm stops.\nReturn value:\nA tuple of\n- x: stationary vector\n- conv: A boolean whether the algorithm converges or not\n- iter: The number of iterations\n- rerror: The relative error when the algorithm stops\n\"\"\"\n\nfunction stgs(Q::SparseMatrixCSC{Tv,Ti}; x0::Vector{Tv}=stguess(Q,Tv),\n        maxiter=5000, steps=20, rtol::Tv=Tv(1.0e-6)) where {Tv,Ti}\n    stgs(SparseCSC(Q), x0=x0, maxiter=maxiter, steps=steps, rtol=rtol)\nend\n\nfunction stgs(Q::SparseCSC{Tv,Ti}; x0::Vector{Tv}=stguess(Q,Tv),\n        maxiter=5000, steps=20, rtol::Tv=Tv(1.0e-6)) where {Tv,Ti}\n    m, n = size(Q)\n    @assert m == n\n    b = zeros(Tv, n)\n    x = copy(x0)\n    iter = 0\n    conv = false\n    rerror::Tv = 0\n    prevx = similar(x)\n    while true\n        prevx .= x\n        for i in 1:steps\n            gsstep!(x, Q, b)\n            x ./= sum(x)\n        end\n        # rerror = maximum(abs.((x - prevx) ./ x))\n        rerror = maximum(abs.(x - prevx)) / maximum(x)\n        iter += steps\n        if rerror < rtol\n            conv = true\n            break\n        end\n        if iter >= maxiter\n            break\n        end\n    end\n    return x, conv, iter, rerror\nend\n\n\"\"\"\nstpower(P::AbstractMatrix{Tv}, x0::Vector{Tv}=stguess(Q,Tv); maxiter=5000, steps=20, rtol::Tv=Tv(1.0e-6))\n\nGet a stationary vector of DTMC with power method.\n\nParameters:\n- P: The transition probability matrix for DTMC\n- x0: Initial vector for iteration\n- maxiter: The maximum number of iteration. The algorithm stops when the number of iteration becomes maxiter.\n- steps: The number of steps to check the convergence\n- rtol: the tolerance error. When the relative errors of two successive vectors with steps attains rtol, the algorithm stops.\nReturn value:\nA tuple of\n- x: stationary vector\n- conv: A boolean whether the algorithm converges or not\n- iter: The number of iterations\n- rerror: The relative error when the algorithm stops\n\"\"\"\n\nfunction stpower(P::AbstractMatrix{Tv}; x0::Vector{Tv}=stguess(P,Tv),\n    maxiter=5000, steps=20, rtol::Tv=Tv(1.0e-6)) where {Tv}\n    m, n = size(P)\n    @assert m == n\n    Pdash = P'\n    x = copy(x0)\n    iter = 0\n    conv = false\n    rerror::Tv = 0\n    prevx = similar(x)\n    while true\n        prevx .= x\n        for i in 1:steps\n            x = Pdash * x\n            x ./= sum(x)\n        end\n        # rerror = maximum(abs.((x - prevx) ./ x))\n        rerror = maximum(abs.(x - prevx)) / maximum(x)\n        iter += steps\n        if rerror < rtol\n            conv = true\n            break\n        end\n        if iter >= maxiter\n            break\n        end\n    end\n    return x, conv, iter, rerror\nend\n", "meta": {"hexsha": "08f45d58914163e44b2fb2896b7b42db5560aeb1", "size": 3556, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/_stationary_iterative.jl", "max_stars_repo_name": "JuliaReliab/NMarkov.jl", "max_stars_repo_head_hexsha": "cdaacdfe9801af84ea5f6a9cbb4108d77e2a8a0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/_stationary_iterative.jl", "max_issues_repo_name": "JuliaReliab/NMarkov.jl", "max_issues_repo_head_hexsha": "cdaacdfe9801af84ea5f6a9cbb4108d77e2a8a0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-07T06:12:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-07T06:13:58.000Z", "max_forks_repo_path": "src/_stationary_iterative.jl", "max_forks_repo_name": "JuliaReliab/NMarkov.jl", "max_forks_repo_head_hexsha": "cdaacdfe9801af84ea5f6a9cbb4108d77e2a8a0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.448, "max_line_length": 125, "alphanum_fraction": 0.6228908886, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388752, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7769470242368639}}
{"text": "# project x onto matrix A's column space, given A is full column rank\nfunction Proj(x,A)\n    y = try\n        pinv(A' * A) * (A' * x)\n    catch err\n        if err != Nothing\n            A' * x\n        end\n    end\n    return A * y\nend\n\nfunction wavelet_perp_Matrix(w,A)\n    N, k = size(A)\n    B = zeros(N, k - 1)\n    if k == 1\n        return\n    end\n    tmp = A'*w\n    if tmp[1] > 1e-6\n        M = Matrix{Float64}(I, k-1, k-1)\n        return A*vcat((-tmp[2:end] ./ tmp[1])', M)\n    end\n    if tmp[end] > 1e-6\n        M = Matrix{Float64}(I, k-1, k-1)\n        return A*vcat(M,(-tmp[1:end-1] ./ tmp[end])')\n    end\n    ind = findall(tmp .== maximum(tmp))[1]\n    rest_ind = setdiff([i for i in 1:k], ind)\n    M = Matrix{Float64}(I, k-1, k-1)\n    B = A * vcat(vcat(M[1:ind-1,:], (-tmp[rest_ind] ./ tmp[ind])'), M[ind:end,:])\n    return B\nend\n\n\n# Gram-Schmidt Process Orthogonalization\nfunction gram_schmidt(A; tol = 1e-12)\n    # Input: matirx A\n    # Output: orthogonalization matrix of A's column vectors\n\n    # Convert the matrix to a list of column vectors\n    a = [A[:,i] for i in 1:size(A,2)]\n\n    # Start Gram-Schmidt process\n    q = []\n    complement_dim = 0\n    for i = 1:length(a)\n        qtilde = a[i]\n        for j = 1:(i - 1)\n            qtilde -= (q[j]' * a[i]) * q[j]\n        end\n        if norm(qtilde) < tol\n            complement_dim = size(A,2) - i + 1\n            break\n        end\n        push!(q, qtilde / norm(qtilde))\n    end\n    Q = zeros(size(A,1), length(q))\n    for i = 1:length(q)\n        Q[:,i] .= q[i]\n    end\n    return Q, complement_dim\nend\n\n#\n\"\"\"\n    mgslp(A::Matrix{Float64}; tol::Float64 = 1e-12, p::Float64 = 1.0)\n\nModified Gram-Schmidt Process Orthogonalization with ℓᵖ pivoting algorithm (MGSLp)\n\n# Input Arguments\n- `A::Matrix{Float64}`: whose column vectors are to be orthogonalized.\n\n# Output Argument\n- `A::Matrix{Float64}`: orthogonalization matrix of A's column vectors based on ℓᵖ pivoting.\n\"\"\"\nfunction mgslp(A::Matrix{Float64}; tol::Float64 = 1e-12, p::Float64 = 1.0)\n    n = size(A, 2)\n    # Convert the matrix to a list of column vectors\n    a = [A[:, i] for i in 1:n]\n\n    # Start modified Gram-Schmidt process\n    q = []\n    v = copy(a)\n    vec_lp_norm = [norm(v[i], p) for i in 1:n]\n    complement_dim = 0\n    for i = 1:n\n        # Pivoting based on minimum ℓᵖ-norm\n        idx = findmin(vec_lp_norm)[2]\n        v[i], v[idx + i - 1] = v[idx + i - 1], v[i]\n        # Check the linear dependency\n        if norm(v[i]) < tol\n            complement_dim = n - i + 1\n            break\n        end\n        qtilde = v[i] / norm(v[i], 2)\n        vec_lp_norm = []\n        for j = (i + 1):n\n            v[j] .-= (qtilde' * v[j]) * qtilde\n            push!(vec_lp_norm, norm(v[j], p))\n        end\n        push!(q, qtilde)\n    end\n    Q = zeros(size(A,1), length(q))\n    for i = 1:length(q)\n        Q[:,i] .= q[i]\n    end\n    return Q, complement_dim\nend\n", "meta": {"hexsha": "5aa9bec8d1e08a636be7663abc5e55a38aa4f46f", "size": 2887, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "haotian127/NGWP.jl", "max_stars_repo_head_hexsha": "a46ed733182f1a6ef04dab8e6ab1540d814e4048", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-29T17:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-29T17:18:57.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "haotian127/NGWP.jl", "max_issues_repo_head_hexsha": "a46ed733182f1a6ef04dab8e6ab1540d814e4048", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-29T06:53:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-29T06:53:23.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "haotian127/NGWP.jl", "max_forks_repo_head_hexsha": "a46ed733182f1a6ef04dab8e6ab1540d814e4048", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2454545455, "max_line_length": 92, "alphanum_fraction": 0.5316937998, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7769470207742897}}
{"text": "export hindmarsh_rose\n\n\"\"\"\nEquations of motion for the Hindmarsh-Rose system.\n\"\"\"\nfunction eom_hindmarsh_rose(u, p, t)\n    a, b, c, d, r, s, xᵣ, I = (p...,)\n    x, y, z = (u...,)\n\n\tϕ = -a*x^3 + b*x^2\n\tψ = c - d*x^2\n    dx = y + ϕ - z + I\n\tdy = ψ - y\n\tdz = r*(s*(x - xᵣ) - z)\n    return SVector{3}(dx, dy, dz)\nend\n\n\"\"\"\n\thindmarsh_rose(u₀, p)\n\nInitialise a Hindmarsh-Rose system, which is a model of neuronal\nspiking.\n\n```math\n\\\\begin{aligned}\n\\\\dfrac{dx}{dt} &= y + \\\\phi(x) - z + I\n\\\\dfrac{dy}{dt} &= \\\\psi(x) - y\n\\\\dfrac{dz}{dt} &= r[s(x - x_R) - z],\n\\\\end{aligned}\n```\nwhere\n\n```math\n\\\\begin{aligned}\n\\\\phi(x) &= -ax^3+bx^2\n\\\\psi(x) &= c - dx^2\n\\\\end{aligned}\n```\n\nIf parameters other than the defaults are to be used, they must be\nprovided as a vector `[a, b, c, d, r, s, xᵣ, I]`.\n\"\"\"\nfunction hindmarsh_rose(u₀, p)\n    ContinuousDynamicalSystem(eom_hindmarsh_rose, u₀, p)\nend\nhindmarsh_rose(;u₀ = rand(3), a = 1, b = 3, c = 1, d = 5, r = 1e-3, s = 4, xᵣ = - 8/5, I = -8) =\n    hindmarsh_rose(u₀, [a, b, c, d, r, s, xᵣ, I])\n", "meta": {"hexsha": "218ebeabae708d4aa34257012bde60ebf76877d1", "size": 1027, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/example_systems/continuous_systems/hindmarsh_rose.jl", "max_stars_repo_name": "kahaaga/CausalityTools.jl", "max_stars_repo_head_hexsha": "e1de3943a2ccb3c9997ca38e7a4fac025f1f8475", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2018-11-07T11:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-05T06:26:37.000Z", "max_issues_repo_path": "src/example_systems/continuous_systems/hindmarsh_rose.jl", "max_issues_repo_name": "kahaaga/CausalityTools.jl", "max_issues_repo_head_hexsha": "e1de3943a2ccb3c9997ca38e7a4fac025f1f8475", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2018-09-04T08:02:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-04T11:59:38.000Z", "max_forks_repo_path": "src/example_systems/continuous_systems/hindmarsh_rose.jl", "max_forks_repo_name": "kahaaga/CausalityTools.jl", "max_forks_repo_head_hexsha": "e1de3943a2ccb3c9997ca38e7a4fac025f1f8475", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-12-03T10:59:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:02:55.000Z", "avg_line_length": 21.3958333333, "max_line_length": 96, "alphanum_fraction": 0.5598831548, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303292, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7769470192913599}}
{"text": "#=\nproximal.jl\n\n    Evaluate the proximal operator for a variety of commonly used functions in\n    optimization, data science, machine learning, and econometrics\n\n@author: Quint Wiersma <q.wiersma@vu.nl>\n\n@date: 2022/01/13\n=#\n\n\"\"\"\n\tsoft_thresh(x, λ)\n\t\nCompute soft thresholding operator with scaling parameter `λ` at `x`, proximal\noperator of ``ℓ₁``-norm.\n\n#### Arguments\n  - `x::Real`\t: input\n  - `λ::Real`\t: scaling parameter\n\n#### Returns\n  - `y::Real`\t: soft thresholded value\n\"\"\"\nfunction soft_thresh(x::Real, λ::Real)\n\t# Soft thresholding\n\ty= sign(x)*max(abs(x) - λ, zero(λ))\n\n\treturn y\nend\n\n\"\"\"\n\tblock_soft_thresh(x, λ)\n\t\nCompute block soft thresholding operator with scaling parameter `λ` at `x`,\nproximal operator of the ``ℓ₂``-norm.\n\n#### Arguments\n  - `x::AbstractVector`\t: input (n x 1)\n  - `λ::Real`\t\t\t: scaling parameter\n\n#### Returns\n  - `y::AbstractVector`\t: block soft thresholded value (n x 1)\n\"\"\"\nfunction block_soft_thresh(x::AbstractVector, λ::Real)\n    y= similar(x)\n\tblock_soft_thresh!(y, x, λ)\n\n\treturn y\nend\n\n\"\"\"\n\tblock_soft_thresh!(y, x, λ)\n\t\nCompute block soft thresholding operator with scaling parameter `λ` at `x`,\nproximal operator of the ``ℓ₂``-norm, storing the results in `y`. See also\n`block_soft_thresh`.\n\"\"\"\nfunction block_soft_thresh!(y::AbstractVector, x::AbstractVector, λ::Real)\n\tT= eltype(x)\n\t# Scaling\n\tτ= max(one(λ) - λ*inv(norm(x) + eps(T)), zero(λ))\n\n\t# Block soft thresholding\n\t@. y= τ*x\n\n\treturn nothing\nend\n\n\"\"\"\n\tblock_soft_thresh!(x, λ)\n\t\nCompute block soft thresholding operator with scaling parameter `λ` at `x`,\nproximal operator of the ``ℓ₂``-norm, overwriting `x`. See also\n`block_soft_thresh`.\n\"\"\"\nfunction block_soft_thresh!(x::AbstractVector, λ::Real)\n\tT= eltype(x)\n\t# Scaling\n\tτ= max(one(λ) - λ*inv(norm(x) + eps(T)), zero(λ))\n\n\t# Block soft thresholding\n\t@. x= τ*x\n\n\treturn nothing\nend\n\n\"\"\"\n\tshrinkage(x, λ)\n\t\nCompute shrinkage operator with scaling parameter `λ` at `x`, proximal operator\nof the squared ℓ₂-norm (ridge).\n\n#### Arguments\n  - `x::Real`\t: input\n  - `λ::Real`\t: scaling parameter\n\n#### Returns\n  - `y::Real`\t: shrunken value\n\"\"\"\nfunction shrinkage(x::Real, λ::Real)\n\t# Scaling\n\tτ= one(λ)*inv(one(λ) + λ)\n\n\t# Shrinkage\n\ty= τ*x\n\n\treturn y\nend\n\n\"\"\"\n    shrinkage!(x, λ, fac, b)\n\nCompute the generalized shrinkage operator with scaling parameter `λ` at `x`,\nproximal operator of a quadratic function with quadratic parameters `A` and\nlinear parameters `b` using a factorization `fac` of ``I + λA``, overwriting\n`x`. See also `shrinkage`.\n\"\"\"\nfunction shrinkage!(x::AbstractVector, λ::Real, fac::Factorization, b::AbstractVector)\n    # x - λb\n    x.-= λ .* b \n    # (I + λA)⁻¹(x - λb)\n    ldiv!(fac, x)\n\n    return nothing\nend\n\n\"\"\"\n    shrinkage(x, λ, fac, b)\n\nCompute the generalized shrinkage operator with scaling parameter `λ` at `x`,\nproximal operator of a quadratic function with quadratic parameters `A` and\nlinear parameters `b` using a factorization `fac` of ``I + λA``.\n\n#### Arguments\n  - `x::AbstractVector` : input\n  - `λ::Real`           : scaling parameter\n  - `fac::Factorization`: factorization of ``I + λA`` \n  - `b::AbstractVector` : linear coefficients\n\n#### Returns\n  - `y::AbstractVector` : shrunken values\n\"\"\"\nfunction shrinkage(x::AbstractVector, λ::Real, fac::Factorization, b::AbstractVector)\n    y= similar(x)\n    shrinkage!(y, λ, fac, b)\n\n    return y\nend\n\n\"\"\"\n    shrinkage!(x, λ, A, b)\n\nCompute the generalized shrinkage operator with scaling parameter `λ` at `x`,\nproximal operator of a quadratic function with quadratic parameters `A` and\nlinear parameters `b`, overwriting `x`. See also `shrinkage`.\n\"\"\"\nfunction shrinkage!(x::AbstractVector, λ::Real, A::AbstractMatrix, b::AbstractVector)\n    # scaling I + λA\n    S= λ .* A\n    @inbounds @fastmath for i in axes(A,1)\n        S[i,i]+= one(eltype(A))\n    end\n\n    # factorization\n    C= cholesky!(Hermitian(S))\n\n    shrinkage!(x, λ, C, b)\n\n    return nothing\nend\n\n\"\"\"\n    shrinkage(x, λ, A, b)\n\nCompute the generalized shrinkage operator with scaling parameter `λ` at `x`,\nproximal operator of a quadratic function with quadratic parameters `A` and\nlinear parameters `b`.\n\n#### Arguments\n  - `x::AbstractVector` : input\n  - `λ::Real`           : scaling parameter\n  - `A::AbstractMatrix` : quadratic coefficients\n  - `b::AbstractVector` : linear coefficients\n\n#### Returns\n  - `y::AbstractVector` : shrunken values\n\"\"\"\nfunction shrinkage(x::AbstractVector, λ::Real, A::AbstractMatrix, b::AbstractVector)\n    y= similar(x)\n    shrinkage!(y, λ, A, b)\n\n    return y\nend\n\nfunction smooth!(x::AbstractVector, λ::Real, f::Function, ∇f!::Function, x0::AbstractVector)\n    # adjust objective function and gradient\n    # f(y) + (1/2λ)‖y - x‖₂² \n    g(y::AbstractVector)= f(y) + inv(λ + λ) * ( sum(abs2, y) + sum(abs2, x) - 2 * dot(y, x) )\n    # ∇f(y) + (1/λ)(y - x)\n    ∇g!(∇g::AbstractVector, y::AbstractVector)= begin\n                                                    # gradient    \n                                                    ∇f!(∇g, y)\n                                                    # quadratic term\n                                                    ∇g.+= inv(λ) .* (y .- x)\n                                                end\n    \n    # solve using L-BFGS\n    res= optimize(g, ∇g!, x0, LBFGS(), Optim.Options(g_tol = 1e-4))\n    x.= Optim.minimizer(res)\n    # store current estimate to warm start next iteration\n    x0.= x\n\n    return nothing\nend", "meta": {"hexsha": "a05b039446f2021f4ecf1c98a4927c3de5bbebff", "size": 5409, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/proximal.jl", "max_stars_repo_name": "qntwrsm/ProximalMethods.jl", "max_stars_repo_head_hexsha": "091d24b531144c0e575777f24fd2fa90e86be096", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/proximal.jl", "max_issues_repo_name": "qntwrsm/ProximalMethods.jl", "max_issues_repo_head_hexsha": "091d24b531144c0e575777f24fd2fa90e86be096", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/proximal.jl", "max_forks_repo_name": "qntwrsm/ProximalMethods.jl", "max_forks_repo_head_hexsha": "091d24b531144c0e575777f24fd2fa90e86be096", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1581395349, "max_line_length": 93, "alphanum_fraction": 0.6271029765, "num_tokens": 1586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7769470173117151}}
{"text": "# This file calculates the UL Decomposition of a Toeplitz operator,\n# via the Wiener–Hopf factorization.  If the symbol of\n# the Toeplitz operator is G(z), we find a Wiener–Hopf factorization\n#\n# \tG(z) = φ_+(z)*φ_-(z)\n#\n# where φ_± are analytic in the interior/exterior of the unit\n# circle.  Then we have the UL decomposition\n#\n#   T[G]=T[φ_+]*T[φ_-]\n#\n# The Wiener–Hopf factorization is found by rephrasing as a\n# Riemann–Hilbert problem:\n#\n#   φ_+(z)=φ_-(z)^(-1)*G(z)\n#\n# and writing\n#\n#   φ_-(z)^(-1) = 1 + C_-V(z) and φ_+(z)=1+C_+V(z)=1+V+C_-V(z)\n#\n# where C_± are the left/right limits of the Cauchy operator.\n# This leads to a singular integral equation\n#\n#   V + C_-V*(1-G) = G - 1\n#\n# This approach also extends to the matrix case.\n\n\n\nusing ApproxFun, SingularIntegralEquations\n\n\n# Scalar case\n\nG=Fun(z->2+cos(z+1/z),Circle()) # the symbol of the Toeplitz operator\nT=ToeplitzOperator(G)\n\nC  = Cauchy(-1)\nV  = (I+(1-G)*C)\\(G-1)\n\nΦmi = 1+C*V\nΦp = V+Φmi\n\nL  = ToeplitzOperator(1/Φmi)\nU  = ToeplitzOperator(Φp)\n\nnorm((T-U*L)[1:10,1:10])  # check the accuracy\n\n\n# Matrix case\n\nG=Fun(z->[-1 -3; -3 -1]/z +\n         [ 2  2;  1 -3] +\n         [ 2 -1;  1  2]*z,Circle())\nT=ToeplitzOperator(G)\n\nC  = Cauchy(-1)\nV  = V=(I+(I-G)*C)\\(G-I)\n\nΦmi = I+C*V\nΦp = V+Φmi\n\nL  = ToeplitzOperator(inv(Φmi))\nU  = ToeplitzOperator(Φp)\n\n\nnorm((T-U*L)[1:10,1:10])  # check the accuracy\n", "meta": {"hexsha": "51eea79fafd0f7a98c01a36f5006f272e1bf9f21", "size": 1367, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Wiener-Hopf.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SingularIntegralEquations.jl-e094c991-5a90-5477-8896-c1e4c9552a1a", "max_stars_repo_head_hexsha": "8a0ca7376ecad020ef8f8beca90686311fbb9f84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2016-12-02T13:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T18:31:48.000Z", "max_issues_repo_path": "examples/Wiener-Hopf.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SingularIntegralEquations.jl-e094c991-5a90-5477-8896-c1e4c9552a1a", "max_issues_repo_head_hexsha": "8a0ca7376ecad020ef8f8beca90686311fbb9f84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2016-12-19T06:02:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:33:33.000Z", "max_forks_repo_path": "examples/Wiener-Hopf.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SingularIntegralEquations.jl-e094c991-5a90-5477-8896-c1e4c9552a1a", "max_forks_repo_head_hexsha": "8a0ca7376ecad020ef8f8beca90686311fbb9f84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-05-16T06:08:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:20:46.000Z", "avg_line_length": 20.1029411765, "max_line_length": 69, "alphanum_fraction": 0.6247256767, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069105, "lm_q2_score": 0.8397339636614178, "lm_q1q2_score": 0.776947013973319}}
{"text": "# Three-state Bioreactor\r\nid = :PerezGalvan2017e\r\n\r\npL = [6.45; 0.46; 1.05]\r\npU = [6.55; 0.47; 1.1]\r\nPerezGalvan2017e_x0(p::Vector{T}) where T = T[p[1]; 5.0*one(T); 15.0*one(T)]\r\nfunction PerezGalvan2017e_f!(du::Vector{T}, u::Vector{T}, p::Vector{T}, t) where T\r\n    x3m = 50.0; x2f = 20.0; D = 0.202; Y = 0.4; β = 0.2; α = 0.5\r\n    μ = p[2]*(1.0 - u[3]/x3m)*u[2]/(p[3] + u[2])\r\n    du[1] = (μ - D)*u[1]\r\n    du[2] = D*(x2f - u[2]) - μ*u[1]/Y\r\n    du[3] = D*u[3] + (α*μ + β)*u[1]\r\n    return\r\nend\r\ntspan = (0.0, 7.7)\r\n\r\nprob = ODERelaxProb(PerezGalvan2017e_f!, tspan, PerezGalvan2017e_x0, pL, pU)\r\nurl = \"https://www.sciencedirect.com/science/article/abs/pii/S0098135417300923\"\r\nsource = \"PerezGalvan2017\"\r\ndesc = \"Three-state Bioreactor\"\r\n", "meta": {"hexsha": "a56e17369748ffa276577c97851acc1b027b93a6", "size": 740, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/library/pODEs/PerezGalvan2017e.jl", "max_stars_repo_name": "PSORLab/DynamicBounds.jl", "max_stars_repo_head_hexsha": "a7c258e3e4297442ad425c398705f3163e953331", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-15T17:57:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-15T17:57:30.000Z", "max_issues_repo_path": "src/library/pODEs/PerezGalvan2017e.jl", "max_issues_repo_name": "PSORLab/DynamicBounds.jl", "max_issues_repo_head_hexsha": "a7c258e3e4297442ad425c398705f3163e953331", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-09-15T14:31:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T03:48:15.000Z", "max_forks_repo_path": "src/library/pODEs/PerezGalvan2017e.jl", "max_forks_repo_name": "PSORLab/DynamicBounds.jl", "max_forks_repo_head_hexsha": "a7c258e3e4297442ad425c398705f3163e953331", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-15T17:57:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T17:57:36.000Z", "avg_line_length": 35.2380952381, "max_line_length": 83, "alphanum_fraction": 0.5783783784, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229948845201, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7769470122420317}}
{"text": "\"\"\"\n    eom_chuacircuit_nscroll_sine(u, p, t) -> SVector{3}\n\nEquations of motion for n-scroll chaotic attractors from an adjusted Chua\nsystem [1].\n\n# References\n1. Tang, Wallace KS, et al. \"Generation of n-scroll attractors via\nsine function.\" IEEE Transactions on Circuits and Systems I:\nFundamental Theory and Applications 48.11 (2001): 1369-1372.\n\n\"\"\"\nfunction eom_chuacircuit_nscroll_sine(u, p, t)\n    α, β, γ, a, b, c, σx, σy, σz = (p...,)\n    x, y, z = (u...,)\n\n    n::Int = c + 1\n    if x >= 2*a*c\n        fx = (b*pi/2*a)*(x - 2*a*c)\n    elseif -2*a*c < x < 2*a*c\n        d = ifelse(isodd(n), pi, 0)\n        fx = -b*sin((pi*x/2*a) + d)\n    elseif x <= -2*a*c\n        fx = (b*pi/2*a)*(x + 2*a*c)\n    end\n\n    ηx = σx == 0 ? 0 : rand(Normal(0, σx))\n    ηy = σy == 0 ? 0 : rand(Normal(0, σy))\n    ηz = σz == 0 ? 0 : rand(Normal(0, σz))\n\n    dx = α*(y - fx) + ηx\n    dy = x - y + z + ηy\n    dz = -β*y - γ*z + ηz\n    return SVector{3}(dx, dy, dz)\nend\n\n\"\"\"\n    chua_nscroll_sinefunc(u₀, α, β, γ, a, b, c::Int)\n\nGenerate n-scroll chaotic attractors from an adjusted Chua system [1].\n\n# References\n1. Tang, Wallace KS, et al. \"Generation of n-scroll attractors via\nsine function.\" IEEE Transactions on Circuits and Systems I:\nFundamental Theory and Applications 48.11 (2001): 1369-1372.\n\"\"\"\nfunction chuacircuit_nscroll_sine(u₀, α, β, γ, a, b, c::Int, σx, σy, σz)\n    p = [α, β, γ, a, b, c, σx, σy, σz]\n    ContinuousDynamicalSystem(eom_chuacircuit_nscroll_sine, u₀, p)\nend\nchuacircuit_nscroll_sine(;u₀ = [0.0, 0.0, 0.28695],\n        α = 10.814, β = 14, γ = 0, a = 1.3, b = 0.11, c = 2,\n        σx = 0.0, σy = 0.0, σz = 0.0) =\n    chuacircuit_nscroll_sine(u₀, α, β, γ, a, b, c, σx, σy, σz)\n", "meta": {"hexsha": "0ec114e6c1bbff2cf2f7098ee634afdfbef10c3d", "size": 1689, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/systems/continuous_systems/chuacircuit_nscroll_sine.jl", "max_stars_repo_name": "tormolle/CausalityTools.jl", "max_stars_repo_head_hexsha": "b8c1014349358d8cdb5eddc1bcac9303f475d90b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/systems/continuous_systems/chuacircuit_nscroll_sine.jl", "max_issues_repo_name": "tormolle/CausalityTools.jl", "max_issues_repo_head_hexsha": "b8c1014349358d8cdb5eddc1bcac9303f475d90b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/systems/continuous_systems/chuacircuit_nscroll_sine.jl", "max_forks_repo_name": "tormolle/CausalityTools.jl", "max_forks_repo_head_hexsha": "b8c1014349358d8cdb5eddc1bcac9303f475d90b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7090909091, "max_line_length": 73, "alphanum_fraction": 0.5831853168, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029487, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.7768904044927377}}
{"text": "using Flux, DiffEqFlux, DifferentialEquations, Plots, StatsBase, RecursiveArrayTools\r\n\r\nconst u0 = Float32[2.; 0.]\r\nconst datasize = 1000\r\nconst batchsize = 30\r\nconst batchtime = 10\r\nconst tspan = (0.0f0,25f0)\r\n\r\nfunction trueODEfunc(du,u,p,t)\r\n    true_A = [-0.1 2.0; -2.0 -0.1]\r\n    du .= ((u.^3)'true_A)'\r\nend\r\nt = range(tspan[1],tspan[2],length=datasize)\r\nprob = ODEProblem(trueODEfunc,u0,tspan)\r\ntrue_sol = solve(prob,Tsit5(),saveat=t)\r\node_data = Array(true_sol)\r\n\r\nfunction get_batch()\r\n    batch_0s = sample(1:datasize-batchtime, batchsize, replace=false,ordered=false)\r\n    batch_idxs = range.(batch_0s,batch_0s.+(batchtime-1))\r\n    batch_ts = [t[i] for i in batch_idxs]\r\n    batch_u0 = [true_sol[u0] for u0 in batch_0s]\r\n    batch_u = [true_sol[:,idxs] for idxs in batch_idxs]\r\n    return batch_u0, batch_u, batch_ts\r\nend\r\nbatch_u0, batch_u, batch_ts = get_batch();\r\n\r\n\r\ndudt = Chain(x -> x.^3,\r\n             Dense(2,50,tanh),\r\n             Dense(50,2))\r\nps = Flux.params(dudt)\r\nfunction n_ode(batch_u0, batch_t)\r\n    neural_ode(dudt,batch_u0,tspan,Tsit5(),\r\n               saveat=batch_t, reltol=1e-7,abstol=1e-9)\r\nend\r\n#= n_ode = x->neural_ode(dudt,x,tspan,Tsit5(), =#\r\n                      #= saveat=t,reltol=1e-7,abstol=1e-9) =#\r\n\r\nn_ode(batch_u0, batch_ts)\r\n\r\npred = n_ode(u0,t) # Get the prediction using the correct initial condition\r\nscatter(t,ode_data[1,:],label=\"data\")\r\nscatter!(t,Flux.data(pred[1,:]),label=\"prediction\")\r\n\r\nfunction predict_n_ode(batch_u0,batch_t)\r\n  n_ode(batch_u0, batch_t)\r\nend\r\nloss_n_ode(batch_u0, batch_u,batch_t) = sum(abs2,batch_u .- predict_n_ode(batch_u0,batch_t))\r\n\r\ndata = Iterators.repeated(get_batch(), 1000)\r\nopt = ADAM(0.1)\r\ncb = function () #callback function to observe training\r\n    bu0,bu,bt = get_batch()\r\n    display(loss_n_ode(bu0,bu,bt))\r\n  # plot current prediction against data\r\n  #= cur_pred = Flux.data(predict_n_ode(bu0,bt)) =#\r\n  #= pl = scatter(bt,ode_data[1,:],label=\"data\") =#\r\n  #= scatter!(pl,bt,cur_pred[1,:],label=\"prediction\") =#\r\n  #= display(plot(pl)) =#\r\nend\r\n\r\n# Display the ODE with the initial parameter values.\r\ncb()\r\n\r\nFlux.train!(loss_n_ode, ps, data, opt, cb = cb)\r\n", "meta": {"hexsha": "3856e4a5bd0eb87ab519a83562737040a0c0aac6", "size": 2154, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "other/diffeq/neural_ode.jl", "max_stars_repo_name": "jessebett/model-zoo", "max_stars_repo_head_hexsha": "081792a07571c1e31f3e2db5274b6952ffe8c721", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-15T21:29:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-15T21:29:15.000Z", "max_issues_repo_path": "other/diffeq/neural_ode.jl", "max_issues_repo_name": "jessebett/model-zoo", "max_issues_repo_head_hexsha": "081792a07571c1e31f3e2db5274b6952ffe8c721", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "other/diffeq/neural_ode.jl", "max_forks_repo_name": "jessebett/model-zoo", "max_forks_repo_head_hexsha": "081792a07571c1e31f3e2db5274b6952ffe8c721", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-08T09:07:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-08T09:07:25.000Z", "avg_line_length": 32.1492537313, "max_line_length": 93, "alphanum_fraction": 0.6620241411, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491797, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7768903951177639}}
{"text": "# coding: utf-8\n\n\n# In[1]: \n\n\n#a simple day trading game\n#day trader is only allowed to make at maximum two trades\n#the strategy is long only\n#lets find out the maximum profit\n\n#more details can be found in the following link\n# https://www.geeksforgeeks.org/maximum-profit-by-buying-and-selling-a-share-at-most-twice/\n\n#an alternative version in recursion exists\n#its done by using a different approach\n#strongly recommend you to take a look\n# https://github.com/je-suis-tm/recursion-and-dynamic-programming/blob/master/stock%20trading%20recursion.jl\n\n\n# In[2]:\n\n\n#there are two scenarios to maximize the profit\n#one trade or two trades\n#first we run a reverse iteration\n#to obtain the maximum profit from one trade\n#then we run a normal iteration\n#to obtain the maximum profit\n#from one trade plus the result from reverse iteration\nfunction stock_trading(prices)\n    \n    #initialize the profit at zero\n    profit=[0 for _ in 1:length(prices)]\n    \n    #initialize maximum price with the close price\n    max_price=prices[end]\n    \n    #reverse order iteration\n    for i in length(prices)-1:-1:1\n        \n        #update the maximum price to compute the maximum profit\n        if prices[i]>max_price\n            \n            max_price=prices[i]\n            \n        end\n        \n        #two scenarios to get the maximum profit\n        #either the previous iteration is larger\n        #or this round of iteration\n        profit[i]=max(profit[i+1],max_price-prices[i])\n        \n    end\n    \n    #initialize minimum price with the open price\n    min_price=prices[1]\n    \n    #second round of iteration\n    for i in 2:length(prices)\n        \n        #update the minimum price to compute the maximum profit\n        if prices[i]<min_price\n            \n            min_price=prices[i]\n            \n        end\n        \n        #two scenarios to get the maximum profit\n        #either the previous iteration is larger\n        #or this round of iteration plus the result from single transaction\n        profit[i]=max(profit[i-1],profit[i]+prices[i]-min_price)   \n                \n    end\n    \n    return profit[end]\n    \nend\n\n\n# In[3]:\n\n\nstock_trading([10,22,5,75,65,80])\n\n\n# In[4]:\n\n\nstock_trading([2,30,15,10,8,25,80])\n\n\n# In[5]:\n\n\nstock_trading([100,30,15,10,8,25,80])\n\n\n# In[6]:\n\n\nstock_trading([90,70,35,11,5])\n", "meta": {"hexsha": "72f83eaaf7c73a5ee191030a947fc640acdfc905", "size": 2308, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "stock trading dynamic programming.jl", "max_stars_repo_name": "je-suis-tm/recursion-and-dynamic-programming", "max_stars_repo_head_hexsha": "55a6085cd45b73426379ff947d9a842ef7d325bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-03-22T10:31:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:30:17.000Z", "max_issues_repo_path": "stock trading dynamic programming.jl", "max_issues_repo_name": "slowbrain/recursion-and-dynamic-programming", "max_issues_repo_head_hexsha": "1cd77db1e7940fee15fc8aa2cedd3ab84e10374f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stock trading dynamic programming.jl", "max_forks_repo_name": "slowbrain/recursion-and-dynamic-programming", "max_forks_repo_head_hexsha": "1cd77db1e7940fee15fc8aa2cedd3ab84e10374f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2019-10-27T12:34:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T13:54:37.000Z", "avg_line_length": 22.4077669903, "max_line_length": 108, "alphanum_fraction": 0.6520797227, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.87407724336544, "lm_q1q2_score": 0.7768438310818236}}
{"text": "# # Two Parabolas\n# \n# The “two parabolas” problem in two dimensions reads as\n# ```math\n#     \\min_{𝐱 ∈ X } \n#     \\begin{bmatrix} f₁(\\mathbf{x}) \\\\ f₂(\\mathbf{x}) \\end{bmatrix} = \n#     \\min_{\\mathbf{x} ∈ X}\n#     \\begin{bmatrix}\n#     (x₁ - 1)² + (x₂ - 1)² \\\\\n#     (x₁ + 1)² + (x₂ + 1)²\n#     \\end{bmatrix}.\n# ```\n# It is unconstrained if the feasible set is ``X = ℝ^2``.\n# The individual minima ``[1,1]`` and ``[-1,-1]`` are such that (in the unconstrained case)\n# the global Pareto Set is \n# ```math\n# \\mathcal{P}_{S} = \\{ \\mathbf{x} ∈ ℝ^2 : x₁ = x₂, \\, -1 \\le x₁, x₂ \\le 1  \\}.\n# ```\n# \n# ## Solve using Exact Functions\n# \n# The gradients are easily calculated as \n# ```math\n# \\nabla f_1 (\\mathbf x) = 2 \\begin{bmatrix}\n# x_1 -1 \\\\ x_2 - 1 \\end{bmatrix}, \\;\n# \\nabla f_2 (\\mathbf x) = 2 \\begin{bmatrix}\n# x_1 +1 \\\\ x_2 + 1 \\end{bmatrix}, \\;\n# ```\n# \n# We can provide them to the solver to find a critical point:\n\nusing Pkg #src\nPkg.activate(@__DIR__) #src\nusing Test #src\n\nusing Morbit\nMorbit.print_all_logs() #src\n\nf₁ = x -> sum( (x .- 1).^2 )\nf₂ = x -> sum( (x .+ 1).^2 )\n∇f₁ = x -> 2 .* ( x .- 1 )\n∇f₂ = x -> 2 .* ( x .+ 1 )\n\nmop = MixedMOP(2);  # problem with 2 variables\nadd_objective!(mop, f₁, ∇f₁ )\nadd_objective!(mop, f₂, ∇f₂ )\n\n#~ starting point\nx₀ = [ -π ;  2.71828 ]\n\n#~ set maximum number of iterations \nac = AlgoConfig( max_iter = 20)\n#~ `optimize` will return parameter and result vectors as well \n#~ as an return code and the evaluation database:\nx, fx, ret_code, db = optimize( mop, x₀; algo_config = ac );\nx\n\n# Hopefully, `x` is critical, i.e., `x[1] ≈ x[2]`.\n@test x[1] ≈ x[2] atol = .1 #src\n\n# !!! note\n#     To print more information on what the solver is doing, you can use the `Logging` module: \n#     ```julia \n#     import Logging: global_logger, ConsoleLogger\n#     global_logger( ConsoleLogger( stderr, Morbit.loglevel4; \n#         meta_formatter = Morbit.morbit_formatter ) )\n#     ```\n#     `loglevel4` is the most detailed and `loglevel1` is least detailed. \n#     `Morbit.print_all_logs()` is a convenient shorthand.\n \n#%% #src\n# ### Plotting Iteration Sites \n# Let's retrieve the iteration sites.\n# We convert to Tuples for easier plotting.\niteration_indices = [ iter_.x_index for iter_ in db.iter_info]\nit_sites = Tuple.(Morbit.get_site.(db, iteration_indices))\n\n# For Plotting we use CairoMakie\nusing Makie, CairoMakie\n\n#~ Pareto Set ≙ line from (-1,-1) to (1,1)\nfig, ax, _ = lines( [(-1,-1),(1,1)]; color = :blue, linewidth = 2,\n    figure = (resolution = (600, 600),) )\n\n#~ Plot the iteration sites:\nlines!(it_sites)\nscatter!(it_sites; \n    color = LinRange(0, 1, length(it_sites)), \n    colormap = :winter\n)\n\n#~ Plot function contours \nY = X = LinRange(-4, 4, 100)\nZ₁ = [ f₁([x;y]) for x ∈ X, y ∈ X ]\nZ₂ = [ f₂([x;y]) for x ∈ X, y ∈ X ]\nlevels = [ i.^2 for i = LinRange(.1, 6, 6) ]\ncontour!(X,Y,Z₁; colormap = :greens, levels = levels, linewidth = .5 )\ncontour!(X,Y,Z₂; colormap = :heat, levels = levels, linewidth = .5 )\n\n#~ Show the plot:\nax.title[] = \"Pareto Set and Iterates.\"\nax.xgridvisible[] = false \nax.ygridvisible[] = false\n\nfig\n\n#%% #src\n\n# ## Solving using RBF Surrogates\n# \n# Suppose now that we do not have access to the objective gradients and that the objectives \n# also take some time to evaluate.\n# In this situation, we could try to model them using surrogate models.\n# To use radial basis function models, pass an `RbfConfig` when specifying the objective:\n# \nmop_rbf = MixedMOP()\n\n#~ Define the RBF surrogates\nrbf_cfg = RbfConfig( \n    kernel = :inv_multiquadric \n)\n#~ Add objective functions to `mop_rbf`\nadd_objective!(mop_rbf, f₁, rbf_cfg )\nadd_objective!(mop_rbf, f₂, rbf_cfg )\n\n#~ only perform 10 iterations\nac = AlgoConfig( max_iter = 10 )\nx, fx, _, db = optimize( mop_rbf, x₀; algo_config = ac ) \nx\n\n#src Setup and save plot for docs.\niteration_indices_rbf = [ iter_.x_index for iter_ in db.iter_info]\nit_sites_rbf = Tuple.(Morbit.get_site.(db, iteration_indices_rbf))\nlines!(it_sites_rbf) #hide\nscatter!(it_sites_rbf; color = :orange) #hide\nnothing #hide \n\n# The iteration sites are the orange circles:\nfig #hide\n\n#%% #src\n\n# ## Different Starting Points and Recycling Data \n# \n# The method could converge to different points depending on the starting point. \n# We can pass the evaluation data from previous runs to facilitate the construction of surrogate models:\n \n#src Setup the problem anew, to ensure fresh start\nac = AlgoConfig( #hide\n    max_iter = 10 #hide\n    ); #hide\nmop_rbf = MixedMOP(); #hide\n#~ define the RBF surogates #hide\nrbf_cfg = RbfConfig(  #hide\n    kernel = :inv_multiquadric, #hide\n); #hide\n#~ add objective functions to `mop_rbf` #hide\nadd_objective!(mop_rbf, f₁, rbf_cfg ); #hide\nadd_objective!(mop_rbf, f₂, rbf_cfg ); #hide\n\n#~ an array of well spread points in [-4,4]² #hide\nX =[ #hide\n [-4.0, -4.0], #hide\n [3.727327839472812, 3.8615291196035457], #hide\n [3.804712690019901, -3.9610212058521235], #hide\n [-0.14512898384374573, -0.005775390168885508], #hide\n [-3.775315499879552, 3.8150054323309064], #hide\n [1.714228746087743, 1.8435786475209621], #hide\n [-1.9603720505875337, -2.0123206708499275], #hide\n [3.9953803225349187, -0.47734576293976794], #hide\n [-3.9944468955728745, 0.49857343385493635], #hide\n [-1.0455585089057458, 2.735699160002545] #hide\n]; #hide\n\n# Suppose, `X` is a list of different points in ℝ².\n\n#src This is the code block visible in the docs:\n\n#~ A dict to associate starting and end points:\nstart_fin_points = Dict();\n\n#~ perform several runs:\ndb₀ = nothing # initial database can be `nothing`\nfor x₀ ∈ X\n    global db₀, start_fin_points\n    x_fin, fx_fin, _, db₀ = optimize( mop_rbf, x₀; algo_config = ac, populated_db = db₀ )\n    #~ add points to dict\n    start_fin_points[x₀] = x_fin\nend\n\n# Plotting: \n\nfig, ax, _ = lines( [(-1,-1),(1,1)]; color = :blue, linewidth = 2,\n    figure = (resolution = (600, 600), ),\n    axis = (title=\"Different Starting Points\",), \n)\n\nfor (k,v) in start_fin_points\n    lines!( [ Tuple(k), Tuple(v) ]; color = :lightgray )\nend\n\nscatter!( Tuple.(keys(start_fin_points)); \n    color = :green\n)\nscatter!( Tuple.(values(start_fin_points)); \n    color = :lightblue\n)\n\nfig #hide\n\n# In the plot, the green points show the starting points and the lightblue circles show the final iterates:", "meta": {"hexsha": "305f9fa34418062d0914c9b571549102bcccbaac", "size": 6238, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example_two_parabolas.jl", "max_stars_repo_name": "manuelbb-upb/Morbit.jl", "max_stars_repo_head_hexsha": "bfc6b1a7982d2c0003042ec9af75e64ad7ef5cf1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-07-21T14:38:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T13:14:14.000Z", "max_issues_repo_path": "examples/example_two_parabolas.jl", "max_issues_repo_name": "manuelbb-upb/Morbit.jl", "max_issues_repo_head_hexsha": "bfc6b1a7982d2c0003042ec9af75e64ad7ef5cf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2021-04-14T09:40:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-09T10:43:40.000Z", "max_forks_repo_path": "examples/example_two_parabolas.jl", "max_forks_repo_name": "manuelbb-upb/Morbit.jl", "max_forks_repo_head_hexsha": "bfc6b1a7982d2c0003042ec9af75e64ad7ef5cf1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-01T02:51:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T02:51:21.000Z", "avg_line_length": 29.5639810427, "max_line_length": 107, "alphanum_fraction": 0.6625521, "num_tokens": 2118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.8887587846530938, "lm_q1q2_score": 0.7768438270487289}}
{"text": "# Rational Quadratic Isotropic Covariance Function\n\n\"\"\"\n    RQIso <: Isotropic{SqEuclidean}\n\nIsotropic Rational Quadratic kernel (covariance)\n```math\nk(x,x') = σ²(1 + (x - x')ᵀ(x - x')/(2αℓ²))^{-α}\n```\nwith length scale ``ℓ``, signal standard deviation ``σ``, and shape parameter ``α``.\n\"\"\"\nmutable struct RQIso <: Isotropic{SqEuclidean}\n    \"Squared length scale\"\n    ℓ2::Float64\n    \"Signal variance\"\n    σ2::Float64\n    \"Shape parameter\"\n    α::Float64\n    \"Priors for kernel parameters\"\n    priors::Array\n\n    \"\"\"\n        RQIso(ll:Float64, lσ::Float64, lα::Float64)\n\n    Create `RQIso` with length scale `exp(ll)`, signal standard deviation `exp(lσ)`, and\n    shape parameter `exp(lα)`.\n    \"\"\"\n    RQIso(ll::Float64, lσ::Float64, lα::Float64) =\n        new(exp(2 * ll), exp(2 * lσ), exp(lα), [])\nend\n\nfunction set_params!(rq::RQIso, hyp::VecF64)\n    length(hyp) == 3 || throw(ArgumentError(\"Rational Quadratic function has three parameters\"))\n    rq.ℓ2, rq.σ2, rq.α = exp(2 * hyp[1]), exp(2 * hyp[2]), exp(hyp[3])\nend\n\nget_params(rq::RQIso) = Float64[log(rq.ℓ2) / 2, log(rq.σ2) / 2, log(rq.α)]\nget_param_names(rq::RQIso) = [:ll, :lσ, :lα]\nnum_params(rq::RQIso) = 3\n\nStatistics.cov(rq::RQIso, r::Float64) = rq.σ2 * (1 + r / (2 * rq.α * rq.ℓ2))^(-rq.α)\n\n@inline dk_dll(rq::RQIso, r::Float64) =\n    (s = r / rq.ℓ2; rq.σ2 * s * (1 + s / (2 * rq.α))^(-rq.α - 1)) # dK_d(log ℓ)dK_dℓ\n@inline function dk_dlα(rq::RQIso, r::Float64)\n    s = r / rq.ℓ2\n    part = 1 + s / (2 * rq.α)\n    rq.σ2 * part^(-rq.α) * (s / (2 * part) - rq.α * log(part))  # dK_d(log α)\nend\n@inline function dk_dθp(rq::RQIso, r::Float64, p::Int)\n    if p==1\n        return dk_dll(rq, r)\n    elseif p==2\n        return dk_dlσ(rq, r)\n    elseif p==3\n        return dk_dlα(rq, r)\n    else\n        return NaN\n    end\nend\n", "meta": {"hexsha": "4cc7f7373f255a590e1e5063f096a71d2434cc72", "size": 1785, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/rq_iso.jl", "max_stars_repo_name": "jbrea/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/rq_iso.jl", "max_issues_repo_name": "jbrea/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/rq_iso.jl", "max_forks_repo_name": "jbrea/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.262295082, "max_line_length": 96, "alphanum_fraction": 0.5910364146, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7768314209257311}}
{"text": "# # Transmission line circuit\n#\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/models/TransmissionLine.ipynb)\n#\n#md # !!! note \"Overview\"\n#md #     System type: linear continuous system\\\n#md #     State dimension: parametric, typically between 4 to 40\\\n#md #     Application domain: Power Systems Stability\n#\n# We consider the transmission line model used in [AKS11].\n# The RLC circuit of the transmission line is shown below.\n# In the circuit, ``U_{in}`` is the voltage at the sending end,\n# and ``U_{out}`` is the voltage at the receiving end.\n\n# ![](https://raw.githubusercontent.com/JuliaReach/ReachabilityAnalysis.jl/master/examples/TransmissionLine/tline.png)\n\n# ## Model description\n\n# For reference to understand this model we refer to any standard textbook on electrical circuits.\n# The electrical elements law for resistors (R), inductors (L) and capacitors (C) are studied,\n# for instance, in Chapter 3 of [^K15].\n\n# Let's assume that the network consists of ``η > 2`` nodes.\n# There are ``η`` dynamic equations for the capacitor voltages and ``\\eta`` dynamic\n# equations for the circuit currents. Therefore, the state vector can be represented as\n\n# ```math\n# x = [U_1, U_2, …, U_η, I_1, I_2, …, I_η]^T,\n# ```\n# and the state dimension is ``2η``.\n\n# **Analysis of the first node.** When writing the equations for the voltages and currents,\n# we should pay attention to the sign choices in given circuit, which do not exactly match\n# the convention in text-books (in the sense that ``U_1``s positive terminal is at the bottom,\n# as indicated by the arrows). Let ``R_d`` denote the driver resistance's current.\n# By Kirchhoff's voltage law,\n\n# ```math\n# U_{in} = R_d I_1 + LI_1' - U_1,\n# ```\n# therefore\n# ```math\n# \\boxed{I_1' = \\dfrac{U_{in} + U_1}{L} - \\dfrac{R_d}{L}I_1}.\n# ```\n#\n# By Kirchhoff's current law, and if ``I_{1, C}`` denotes the current through the\n# capacitor ``C``, connected to the first node,\n#\n# ```math\n#    I_1 = I_2 + I_{C, 1},\n# ```\n# and\n# ```math\n# I_{C, 1} = -CU_1',\n# ```\n# then\n# ```math\n#    \\boxed{U_1' = \\frac{I_2 - I_1}{C}}.\n# ```\n\n# **Analysis of the intermediate nodes.** Other node's equations are obtained\n# in a similar fashion. For instance, for the second loop one has\n\n# ```math\n# -U_1 = RI_2 + LI_2' - U_2 \\Rightarrow I_2' = \\dfrac{U_2-U_1}{L} - \\frac{R}{L}I_2\n# ```\n# for the current's equation, and\n#\n# ```math\n#    I_{2, C} = I_2 - I_3,\\Rightarrow U_2' = \\frac{I_3 - I_2}{C}.\n# ```\n# for the voltage's equation.\n#\n# Generalizing for arbitrary ``l = 2, \\ldots, \\eta - 1`` is trivial and gives:\n#\n# ```math\n#     \\boxed{I'_l = \\dfrac{U_l - U_{l-1}}{L} - \\frac{R}{L}I_l} \\\\\n#     \\boxed{U'_l = \\dfrac{I_{l+1} - I_l}{C}}.\n# ```\n\n# **Analysis of the last node.** The last node corresponds to the case ``l = \\eta``\n#\n# ```math\n# \\boxed{I'_\\eta = \\dfrac{U_\\eta - U_{\\eta-1}}{L} - \\frac{R}{L}I_\\eta}, \\\\\n# \\boxed{U'_{out} = U'_{out} = - \\frac{I_{\\eta}}{C}}.\n# ```\n\n# **System of linear ODEs.** Recall that that the stateset is ``\\mathbb{R}^{2\\eta}``,\n# where the state variables are\n# ``x = [U_1, U_2, \\ldots, U_\\eta, I_1, I_2, \\ldots, I_\\eta]^T``.\n# The system can be written as a block-diagonal system of linear ODEs,\n# ```math\n# x'(t) = Ax(t) + BU_{in}(t),\n# ```\n# using the results in the previous section.\n\n# The coefficients matrix ``A`` can be written as a block-diagonal matrix.\n# There exist useful constructors in the base package `LinearAlgebra` that greatly simplify\n# building matrices with special shape, as in our case, such as diagonal and band matrices,\n# using the types `Diagonal` and `Bidiagonal` in our case.\n\nusing ReachabilityAnalysis, LinearAlgebra, SparseArrays\n\nfunction tline(;η=3, R=1.00, Rd=10.0, L=1e-10, C=1e-13 * 4.00)\n    A₁₁ = zeros(η, η)\n    A₁₂ = Bidiagonal(fill(-1/C, η), fill(1/C, η-1), :U)\n    A₂₁ = Bidiagonal(fill(1/L, η), fill(-1/L, η-1), :L)\n    A₂₂ = Diagonal(vcat(-Rd/L, fill(-R/L, η-1)))\n    A  = [A₁₁ A₁₂; A₂₁ A₂₂]\n    B = sparse([η+1], [1], 1/L, 2η, 1)\n    return A, B\nend\n\n# We can visualize the structure of the cofficients matrix ``A`` for the case\n# $\\eta = 20$ with `spy` plot:\n\nusing Plots\n\nA, _ = tline(η=20)\nspy(A, legend=nothing, markersize=2.0, title=\"Sparsity pattern of A\", xlab=\"columns\", ylab=\"rows\")\n\n# Notice that the matrix coefficients are rather big, hence it is convenient to rescale the system\n# for numerical stability.\n# Let ``α > 0`` be a scaling factor, and let ``\\tilde{x}(t) = x(\\alpha t)``.\n# By the chain rule,\n# ```math\n# \\tilde{x}'(t) = \\alpha x'(\\alpha t) = \\alpha A x(\\alpha t) + \\alpha B U_{in}(\\alpha t) = \\tilde{A} \\tilde{x}(t) + \\tilde{B} \\tilde{U}_{in}(t),\n# ```\n# where ``\\tilde{A} := \\alpha A`` and ``\\tilde{B} := \\alpha B``.\n\nfunction scale!(s, α=1.0)\n    s.A .*= α\n    s.B .*= α\n    return s\nend\n\n# Note that under this transformation, the time horizon has to be transformed as well,\n# through ``\\tilde{T} = \\alpha T``.\n\n# ## Reachability settings\n\n# The transmission line parameters used in this model are displayed in the following table.\n\n# |resistance in [Ω] | driver resistance in [Ω] | Inductance in [H] | Capacitance in [F] |\n# |------------------|--------------------------|------------------|-------------------|\n# |R = 1.00| Rdriver = 10.0| L = 1e−10 | C = 4e−13|\n\n# The steady state is obtained by zeroing the left-hand side of the ODE, which gives\n#\n# ```math\n#    0 = x' = Ax_\\infty + Bu_0 \\Rightarrow x_\\infty = -A^{-1}B u_0\n# ```\n# The initial set under consideration corresponds to the steady state for input voltages\n# ``U_{in, ss} := [-0.2, 0.2]``.\n# Moreover, an uncertainty is added so that the initial currents are also uncertain.\n# The set of initial states is then\n# ```math\n#    x(0) \\in \\mathcal{X}_0 := -A^{-1} B  U_{in, ss} \\oplus □(0.001),\n# ```\n# where ``□(ϵ)`` is the infinity-norm ball of center zero and radius ``ϵ``.\n\n# The time horizon is chosen as ``T = 0.7`` seconds. We consider a\n# scaling factor ``\\alpha = 1e-9``.\n\n# We are interested in the step response to an input voltage ``U_{in}(t)``, constant\n# for ``t \\in [0, T]`` over the domain ``U_{in} = [0.99, 1.01]``.\n\n# We consider the case of ``\\eta = 20`` nodes as in [AKS11], such that the system\n# has ``n = 40`` state variables.\n\nη = 20 # order\nn = 2η # state-space dimension\nA, B = tline(η=η);\n\nUin_ss = Interval(-0.2, 0.2)\n□(ϵ) = BallInf(zeros(n), ϵ)\nX0 = -inv(Matrix(A)) * B * Uin_ss ⊕ □(0.001);\n\nUin = Interval(0.99, 1.01)\ns = @system(x'= A*x + B*u, x ∈ Universe(n), u ∈ Uin)\nα = 1e-9 # scaling factor\nscale!(s, α);\n\nT = 0.7 * 1e-11 # time horizon\nP = InitialValueProblem(s, X0);\n\n# ## Results\n\n# We solve system using a step size of `δ=1e-3` and the box algorithm.\n\nsol = solve(P, T=0.7, alg=BOX(δ=1e-3));\n\n# To get the variable ``U_{out}`` we have to project onto the ``η``-th coordinate\n# and invert the sign of the flowpipe.\n\nUout_vs_t = @. (-1.0) * project(sol, η);\n\n#-\n\nplot(Uout_vs_t, vars=(0, η), color=:blue, xlab=\"t\", ylab=\"Uout\", alpha=.5, lw=0.5)\n\n#md # !!! tip \"Technical note\"\n#md #     Since we are only interested in the behavior of ``U_{out}``, we can use\n#md #     algorithm `BFFPSV18` with the options `alg=BFFPSV18(δ=1e-3, dim=statedim(P), vars=[η]))`,\n#md #     which will use an interval (1D) decomposition of the state space and only compute\n#md #     the flowpipe associated with variable ``\\eta``.\n\n# ## References\n\n# [^AKS11]: Althoff, Matthias, Bruce H. Krogh, and Olaf Stursberg. [Analyzing reachability of linear dynamic systems with parametric uncertainties.](http://www.i6.in.tum.de/Main/Publications/Althoff2011b.pdf). Modeling, Design, and Simulation of Systems with Uncertainties. Springer, Berlin, Heidelberg, 2011. 69-94.\n\n# [^K15]: Kluever, Craig A. [Dynamic systems: modeling, simulation, and control.](https://www.wiley.com/en-us/Dynamic+Systems%3A+Modeling%2C+Simulation%2C+and+Control-p-9781118289457). John Wiley & Sons, 2015.\n\n# [^GLG08]: Girard, Antoine, and Colas Le Guernic. [Efficient reachability analysis for linear systems using support functions.]() IFAC Proceedings Volumes 41.2 (2008): 8966-8971.\n", "meta": {"hexsha": "f9d8ed304b662a37171699198d34e2390143d904", "size": 8030, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/TransmissionLine/TransmissionLine.jl", "max_stars_repo_name": "pitmonticone/ReachabilityAnalysis.jl", "max_stars_repo_head_hexsha": "cf7271353bbf20780d1996e824df1859d380daa2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-26T10:48:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T10:48:30.000Z", "max_issues_repo_path": "examples/TransmissionLine/TransmissionLine.jl", "max_issues_repo_name": "pitmonticone/ReachabilityAnalysis.jl", "max_issues_repo_head_hexsha": "cf7271353bbf20780d1996e824df1859d380daa2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/TransmissionLine/TransmissionLine.jl", "max_forks_repo_name": "pitmonticone/ReachabilityAnalysis.jl", "max_forks_repo_head_hexsha": "cf7271353bbf20780d1996e824df1859d380daa2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3488372093, "max_line_length": 316, "alphanum_fraction": 0.6457036115, "num_tokens": 2736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.7768314147345956}}
{"text": "# Matern 5/2 isotropic covariance function\n\n@doc \"\"\"\n# Description\nConstructor for the isotropic Matern 5/2 kernel (covariance)\n\nk(x,x') = σ²(1+√5*d/ℓ + 5d²/3ℓ²)exp(-√5*d/ℓ), where d = |x-x'|\n# Arguments:\n* `ll::Float64`: Log of the length scale ℓ\n* `lσ::Float64`: Log of the signal standard deviation σ\n\"\"\" ->\ntype Mat52Iso <: Isotropic\n    ℓ::Float64      # Length scale \n    σ2::Float64     # Signal std\n    Mat52Iso(ll::Float64, lσ::Float64) = new(exp(ll), exp(2*lσ))\nend\n\nfunction set_params!(mat::Mat52Iso, hyp::Vector{Float64})\n    length(hyp) == 2 || throw(ArgumentError(\"Matern 5/2 only has two parameters\"))\n    mat.ℓ, mat.σ2 = exp(hyp[1]), exp(2.0*hyp[2])\nend\nget_params(mat::Mat52Iso) = Float64[log(mat.ℓ), log(mat.σ2)/2.0]\nget_param_names(mat::Mat52Iso) = [:ll, :lσ]\nnum_params(mat::Mat52Iso) = 2\n\nmetric(mat::Mat52Iso) = Euclidean()\ncov(mat::Mat52Iso, r::Float64) = mat.σ2*(1+sqrt(5)*r/mat.ℓ+5*r^2/(3*mat.ℓ^2))*exp(-sqrt(5)*r/mat.ℓ)\n\nfunction grad_kern(mat::Mat52Iso, x::Vector{Float64}, y::Vector{Float64})\n    r = distance(mat,x,y)\n    exp_r = exp(-sqrt(5)*r/mat.ℓ)\n\n    g1 = mat.σ2*(5*r^2/mat.ℓ^2)*((1+sqrt(5)*r/mat.ℓ)/3)*exp_r   #dK_d(log ℓ)\n    g2 = 2.0*mat.σ2*(1+sqrt(5)*r/mat.ℓ+5*r^2/(3*mat.ℓ^2))*exp_r #dK_d(log σ)\n    return [g1,g2]\nend\n\nfunction grad_stack!(stack::AbstractArray, mat::Mat52Iso, X::Matrix{Float64}, data::IsotropicData)\n    nobsv = size(X,2)\n    R = distance(mat, X, data)\n    exp_R = exp(-sqrt(5)*R/mat.ℓ)\n\n    for i in 1:nobsv, j in 1:i\n        @inbounds stack[i,j,1] = mat.σ2*(5*R[i,j]^2/mat.ℓ^2)*((1+sqrt(5)*R[i,j]/mat.ℓ)/3)*exp_R[i,j]      # dK_dℓ\n        @inbounds stack[j,i,1] = stack[i,j,1] \n        @inbounds stack[i,j,2] = 2.0*mat.σ2*(1+sqrt(5)*R[i,j]/mat.ℓ+5*R[i,j]^2/(3*mat.ℓ^2))*exp_R[i,j]   # dK_dσ\n        @inbounds stack[j,i,2] = stack[i,j,2] \n    end\n    \n    return stack\nend\n", "meta": {"hexsha": "21cebbaa24c8b3377d4b55e96ed5be148bd848b7", "size": 1834, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/mat52_iso.jl", "max_stars_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/mat52_iso.jl", "max_issues_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/mat52_iso.jl", "max_forks_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2692307692, "max_line_length": 113, "alphanum_fraction": 0.6134133043, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7767780205774159}}
{"text": "using Statistics\nfunction median2(n)\n\ts = sort(n)\n\tlen = length(n)\n\tif len % 2 == 0\n\t\treturn (s[floor(Int, len / 2) + 1] + s[floor(Int, len / 2)]) / 2\n\telse\n\t\treturn  s[floor(Int, len / 2) + 1]\n\tend\nend\n\na = [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]\nb = [4.1, 7.2, 1.7, 9.3, 4.4, 3.2]\n\n@show a b median2(a) median(a) median2(b) median(b)\n", "meta": {"hexsha": "2a6c70d94fc2fe45b0cbeab11af34ee517b31977", "size": 332, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/averages-median.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/averages-median.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/averages-median.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.75, "max_line_length": 66, "alphanum_fraction": 0.5481927711, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7767780166203448}}
{"text": "\n\nfunction lag_matrix(x::T, lag::Int) where {T<:AbstractMatrix}\n    nobs, nx = size(x)\n    xlag = zeros(nobs - lag, nx * lag)\n    for i = 1:lag\n        xlag[1:(nobs-lag), (nx*(i-1)+1):(nx*i)] = x[(lag+1-i):(nobs-i), 1:nx]\n    end\n    return xlag\nend\n\nfunction lag_matrix(x::T, lag::Int) where {T<:AbstractVector}\n    x2 = reshape(x, length(x), 1)\n    return lag_matrix(x2, lag)\nend\n\n\"\"\"\n    companion(A, p) -> Matrix\n\nConstruct the companion matrix for VAR coefficient matrix `A`, where `A` has\n    dimensions (Kp × K). K is the number of endogenous variables, p is the\n    number of lags.\n\"\"\"\nfunction companion(A, p)\n    K = size(A, 2)\n    subI = [Matrix(1.0I, K * (p - 1), K * (p - 1)) zeros(K * (p - 1), K)]\n    Acomp = vcat(A', subI)\n    return Acomp\nend\n\nfunction rhs_matrix(y, ylag, constant, trend, x)\n    rhs = lag_matrix(y, ylag)\n    if !isa(x, Nothing)\n        rhs = hcat(x[ylag+1:end, :], rhs)\n    end\n    if trend\n        ltrend = collect(1.0:size(rhs, 1))\n        rhs = hcat(ltrend, rhs)\n    end\n    if constant\n        rhs = hcat(ones(Float64, size(rhs, 1)), rhs)\n    end\n    return rhs\nend\n", "meta": {"hexsha": "fbc55a58026542ecdf92f198b3d2e5c073ab058b", "size": 1106, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix_utilities.jl", "max_stars_repo_name": "stephenbnicar/VectorAutoregressions.jl", "max_stars_repo_head_hexsha": "f5575b39b589745ca9d1ac1dda0e8f7707349188", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-05-16T16:36:33.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-19T06:17:16.000Z", "max_issues_repo_path": "src/matrix_utilities.jl", "max_issues_repo_name": "stephenbnicar/VectorAutoregressions.jl", "max_issues_repo_head_hexsha": "f5575b39b589745ca9d1ac1dda0e8f7707349188", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-05-14T15:09:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-03T13:58:55.000Z", "max_forks_repo_path": "src/matrix_utilities.jl", "max_forks_repo_name": "stephenbnicar/VectorAutoregressions.jl", "max_forks_repo_head_hexsha": "f5575b39b589745ca9d1ac1dda0e8f7707349188", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-05-16T16:36:34.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-16T16:36:34.000Z", "avg_line_length": 24.5777777778, "max_line_length": 77, "alphanum_fraction": 0.5786618445, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7767780132572962}}
{"text": "using Parameters\nusing DifferentialEquations\nusing ForwardDiff\nusing LinearAlgebra\n\ninclude(\"cr_model.jl\")\n\n## CR exp resource, type I consumer\nfunction expI_inteq(p)\n    @unpack r, a, m, e = p\n    C = r / a\n    R = m / ( a * e ) \n    return [R , C]\nend\n\nexpI_inteq_jac = jac(expI_inteq(CRPar()), cr_expI_model, CRPar())\n\neigvals(expI_inteq_jac)\n\nλ_stability(expI_inteq_jac)\n\nexpI_00_jac = jac([0.0,0.0], cr_expI_model, CRPar())\n\nλ_stability(expI_00_jac)\n\neigvals(expI_00_jac)\n\nexpI_k_jac = jac([3.0,0.0], cr_expI_model, CRPar())\n\nλ_stability(expI_k_jac)\n\neigvals(expI_k_jac)\n\n\n## CR log resource, type I consumer\nfunction logI_inteq(p)\n    @unpack r, a, k, m, e = p\n    R =  m / (a * e)\n    C = r * (- R + k) / (a * k)\n    return [R , C]\nend\n\nlogI_inteq_jac = jac(logI_inteq(CRPar()), cr_logI_model, CRPar())\n\neigvals(logI_inteq_jac)\n\nλ_stability(logI_inteq_jac)\n\nlogI_00_jac = jac([0.0,0.0], cr_logI_model, CRPar())\n\nλ_stability(logI_00_jac)\n\neigvals(logI_00_jac)\n\nlogI_k_jac = jac([3.0,0.0], cr_logI_model, CRPar())\n\nλ_stability(logI_k_jac)\n\neigvals(logI_k_jac)\n\n## CR log resource, type II consumer\n\nlogII_inteq_jac = jac(logII_eq(CRPar()), cr_logII_model, CRPar())\n\neigvals(logII_inteq_jac)\n\nλ_stability(logII_inteq_jac)\n\nlogII_00_jac = jac([0.0,0.0], cr_logII_model, CRPar())\n\nλ_stability(logII_00_jac)\n\neigvals(logII_00_jac)\n\nlogII_k_jac = jac([3.0,0.0], cr_logII_model, CRPar())\n\nλ_stability(logII_k_jac)\n\neigvals(logII_k_jac)\n\n## CR exp resource, type II consumer\n\n# Calculate the interior equilibrium\nfunction expII_inteq(p)\n    @unpack r, a, h, m, e = p\n    R = m / (a * (e - h * m))\n    C = R * h * r + r / a\n    return [R , C]\nend\n\nexpII_inteq_jac = jac(expII_inteq(CRPar(r = 0.5, a = 1.0)), cr_expII_model, CRPar(r = 0.5, a = 1.0))\n\neigvals(expII_inteq_jac)\n\nλ_stability(expII_inteq_jac)\n\nexpII_00_jac = jac([0.0,0.0], cr_expII_model, CRPar(r = 0.5, a = 1.0))\n\nλ_stability(expII_00_jac)\n\neigvals(expII_00_jac)", "meta": {"hexsha": "25478e30aaecf5155ae56482b99833a33936aa0d", "size": 1923, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/julia/CR/cr_eigenvalues.jl", "max_stars_repo_name": "McCannLab/TheoryClub", "max_stars_repo_head_hexsha": "bc11de9951d727dc071c99ea6283a5a7d83af2ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/julia/CR/cr_eigenvalues.jl", "max_issues_repo_name": "McCannLab/TheoryClub", "max_issues_repo_head_hexsha": "bc11de9951d727dc071c99ea6283a5a7d83af2ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-30T22:48:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-30T22:48:02.000Z", "max_forks_repo_path": "src/julia/CR/cr_eigenvalues.jl", "max_forks_repo_name": "McCannLab/TheoryClub", "max_forks_repo_head_hexsha": "bc11de9951d727dc071c99ea6283a5a7d83af2ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-25T13:01:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-25T13:01:31.000Z", "avg_line_length": 19.0396039604, "max_line_length": 100, "alphanum_fraction": 0.6905876235, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692236, "lm_q2_score": 0.8376199613065411, "lm_q1q2_score": 0.7767780128612813}}
{"text": "using Symbolics, SymbolicUtils\nusing ModelingToolkit, DifferentialEquations\nusing Plots\n\n############ The Helper Functions ############################################\n\ndef_taylor(x, ps) = sum([a*x^i for (i,a) in enumerate(ps)])\ndef_taylor(x, ps, p₀) = p₀ + def_taylor(x, ps)\n\nexpand_sin(x, n) = sum([(isodd(k) ? -1 : 1)*(-x)^(2k-1)/factorial(2k-1) for k=1:n])\n\nfunction collect_powers(eq, x, ns; max_power=100)\n    eq = substitute(expand(eq), Dict(x^j => 0 for j=last(ns)+1:max_power))\n\n    eqs = []\n    for i in ns\n        powers = Dict(x^j => (i==j ? 1 : 0) for j=1:last(ns))\n        push!(eqs, substitute(eq, powers))\n    end\n    eqs\nend\n\nfunction solve_coef(eqs, ps)\n    vals = Dict()\n\n    for i = 1:length(ps)\n        eq = substitute(eqs[i], vals)\n        vals[ps[i]] = Symbolics.solve_for(eq ~ 0, ps[i])\n    end\n    vals\nend\n\nfunction solve_newton(f, x, x₀; abstol=1e-8, maxiter=50)\n    xₙ = Float64(x₀)\n    fₙ₊₁ = x - f / Symbolics.derivative(f, x)\n\n    for i = 1:maxiter\n        xₙ₊₁ = substitute(fₙ₊₁, Dict(x => xₙ))\n        if abs(xₙ₊₁ - xₙ) < abstol\n            return xₙ₊₁\n        else\n            xₙ = xₙ₊₁\n        end\n    end\n    return xₙ₊₁\nend\n\nfunction calc_u0(sys, d; def_val=0.0)\n    S = states(sys)\n    u0 = Dict{typeof(S[1]), Float64}()\n\n    for s in S\n        name_withˍt = string(s)\n        name_withoutˍt = replace(name_withˍt, r\"\\(.*\\)\" => \"\")\n\n        if haskey(d, name_withˍt)\n            u0[s] = d[name_withˍt]\n        elseif haskey(d, name_withoutˍt)\n            u0[s] = d[name_withoutˍt]\n        else\n            u0[s] = def_val\n        end\n    end\n\n    return u0\nend\n\n#################### The examples ############################################\n\n\"\"\"\n    x^5 + x = 1\n\"\"\"\nfunction test_quintic(n=4)\n    @variables ϵ z a[1:n]\n    x = def_taylor(ϵ, a, 1)\n    eq = x^5 + ϵ*x - 1\n    eqs = collect_powers(eq, ϵ, 1:n)\n    vals = solve_coef(eqs, a)\n\n    x′ = substitute(x, vals)\n    X = 𝜀 -> substitute(x′, Dict(ϵ => 𝜀))\n\n    xₚ = X(1.0)\n    xₙ = solve_newton(z^5 + z - 1, z, 1.0)\n\n    return xₚ, xₙ\nend\n\n\"\"\"\n    E - e * sin(E) = M\n\"\"\"\nfunction test_kepler(n=4)\n    @variables ϵ z M a[1:n]\n    x = def_taylor(ϵ, a, M)\n    eq = x - ϵ * expand_sin(x, n) - M\n    eqs = collect_powers(eq, ϵ, 1:n)\n    vals = solve_coef(eqs, a)\n\n    x′ = substitute(x, vals)\n    X = (𝜀, 𝑀) -> substitute(x′, Dict(ϵ => 𝜀, M => 𝑀))\n\n    𝑒 = 0.01671    # The Earth eccentricity\n    M₀ = π/2\n\n    xₚ = X(𝑒, M₀)\n    xₙ = solve_newton(z - 𝑒*sin(z) - M₀, z, M₀)\n\n    return xₚ, xₙ\nend\n\nfunction test_rocket(n=3)\n    sys, y = calc_rocket_sys(n)\n    u0 = calc_u0(sys, Dict(\"y₁ˍt\" => 1.0))\n    prob = ODEProblem(sys, u0, (0, 3.0))\n    sol = solve(prob; dtmax=0.01)\n    X = 𝜀 -> sum([𝜀^(i-1) * sol[y[i]] for i in eachindex(y)])\n    plot(sol.t, hcat([X(ϵ) for ϵ = 0.0:0.1:0.5]...))\nend\n\nfunction calc_rocket_sys(n)\n    @variables ϵ t y[1:n](t) ∂∂y[1:n]\n    x = def_taylor(ϵ, y[2:end], y[1])\n    ∂∂x = def_taylor(ϵ, ∂∂y[2:end], ∂∂y[1])\n    eq = ∂∂x * (1 + ϵ*x)^2 + 1\n    eqs = collect_powers(eq, ϵ, 0:n)\n    vals = solve_coef(eqs, ∂∂y)\n\n    D = Differential(t)\n    subs = Dict(∂∂y[i] => D(D(y[i])) for i in eachindex(y))\n    eqs = [substitute(first(v), subs) ~ substitute(last(v), subs) for v in vals]\n\n    sys = ODESystem(eqs, t)\n    sys = ode_order_lowering(sys)\n\n    sys, y\nend\n\nfunction test_oscillator(n=3)\n    sys, y = calc_oscillator_sys(n)\n    u0 = calc_u0(sys, Dict(\"y₁ˍt\" => 1.0))\n    prob = ODEProblem(sys, u0, (0, 50.0))\n    sol = solve(prob; dtmax=0.01)\n\n    X = 𝜀 -> sum([𝜀^(i-1) * sol[y[i]] for i in eachindex(y)])\n    T = sol.t\n    Y = 𝜀 -> exp.(-𝜀*T) .* sin.(sqrt(1 - 𝜀^2)*T) / sqrt(1 - 𝜀^2)    # exact solution\n\n    plot(sol.t, [Y(0.1), X(0.1)])\nend\n\nfunction calc_oscillator_sys(n)\n    @variables ϵ t y[1:n](t) ∂y[1:n] ∂∂y[1:n]\n    x = def_taylor(ϵ, y[2:end], y[1])\n    ∂x = def_taylor(ϵ, ∂y[2:end], ∂y[1])\n    ∂∂x = def_taylor(ϵ, ∂∂y[2:end], ∂∂y[1])\n\n    eq = ∂∂x + 2*ϵ*∂x + x\n    eqs = collect_powers(eq, ϵ, 0:n)\n    vals = solve_coef(eqs, ∂∂y)\n\n    D = Differential(t)\n    subs1 = Dict(∂y[i] => D(y[i]) for i in eachindex(y))\n    subs2 = Dict(∂∂y[i] => D(D(y[i])) for i in eachindex(y))\n    subs = subs1 ∪ subs2\n    eqs = [substitute(first(v), subs) ~ substitute(last(v), subs) for v in vals]\n\n    sys = ODESystem(eqs, t)\n    sys = ode_order_lowering(sys)\n\n    sys, y\nend\n", "meta": {"hexsha": "c026c8133f34554bdfba9fefe80de960e1bcf99f", "size": 4285, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/perturb.jl", "max_stars_repo_name": "siravan/SymPertExamples.jl", "max_stars_repo_head_hexsha": "9f074eaf6e2df013622ac31cb555411202acec9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2021-05-19T15:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:12:04.000Z", "max_issues_repo_path": "src/perturb.jl", "max_issues_repo_name": "siravan/SymPertExamples.jl", "max_issues_repo_head_hexsha": "9f074eaf6e2df013622ac31cb555411202acec9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/perturb.jl", "max_forks_repo_name": "siravan/SymPertExamples.jl", "max_forks_repo_head_hexsha": "9f074eaf6e2df013622ac31cb555411202acec9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9127906977, "max_line_length": 84, "alphanum_fraction": 0.5260210035, "num_tokens": 1745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7767780113777646}}
{"text": "\"\"\"\n# module kernels\n\n- Julia version: 1.4\n- Author: niallcullinane\n- Date: 2020-06-07\n\n# Examples\n\n```jldoctest\njulia>\n```\n\"\"\"\n\n\nmodule LaminartKernels\n\nexport kern_d, kern_b\n\n# lgn to l6/l4\nusing NNlib, ImageFiltering, Images, OffsetArrays\n\nfunction kern_d_ph(σ::Real, θ::Real, l = 4 * ceil(Int,σ) + 1)\n    isodd(l) || throw(ArgumentError(\"length must be odd\"))\n    w = l>>1\n    g = σ == 0 ? [1f0] : [exp(-x*cos(θ) / (2f0 * σ)) for x=-w:w]\n    centered(g/sum(g))\nend\n\nfunction kern_d_pv(σ::Real, θ::Real, l = 4*ceil(Int,σ)+1)\n    isodd(l) || throw(ArgumentError(\"length must be odd\"))\n    w = l>>1\n    g = σ == 0 ? [1f0] : [exp(-x*sin(θ)/(2f0*σ)) for x=-w:w]\n    centered(g/sum(g))\nend\n\nfunction kern_d_mh(σ::Real, θ::Real, l = 4*ceil(Int,σ)+1)\n    isodd(l) || throw(ArgumentError(\"length must be odd\"))\n    w = l>>1\n    g = σ == 0 ? [1f0] : [exp(x*cos(θ)/(2f0*σ)) for x=-w:w]\n    centered(g/sum(g))\nend\n\nfunction kern_d_mv(σ::Real, θ::Real, l = 4*ceil(Int,σ)+1)\n    isodd(l) || throw(ArgumentError(\"length must be odd\"))\n    w = l>>1\n    g = σ == 0 ? [1f0] : [exp(x*sin(θ)/(2f0*σ)) for x=-w:w]\n    centered(g/sum(g))\nend\n\nfunction kern_d_p(σ::Real, θ::Real, l = 4*ceil(Int,σ)+1)\n    kern_d_pv(σ, θ, l) .* transpose(kern_d_ph(σ, θ, l))\nend\n\nfunction kern_d_m(σ::Real, θ::Real, l = 4*ceil(Int,σ)+1)\n    kern_d_mv(σ, θ, l) .* transpose(kern_d_mh(σ, θ, l))\nend\n\nfunction kern_d(σ::Real, θ::Real, l = 4*ceil(Int,σ)+1)\n    kern_d_p(σ, θ, l).-kern_d_m(σ, θ, l)\nend\n\n\n# function kern_d(σ::Real, θ::Real, l = 4*ceil(Int,σ)+1)\n#     relu.(kern_d(σ, θ, l)) .- relu.(-1 .*(kern_d(σ, θ, l)))\n# end\n\nfunction kern_b(σ::Real, θ::Real, l = 4*ceil(Int,σ)+1)\n    relu.(kern_d(σ, θ, l)) .+ relu.(-1f0 .*(kern_d(σ, θ, l)))\nend\n\n\n\n\nfunction gaussian_rot(σ_x::Real, σ_y::Real, θ::Real, l = 4*ceil(Int, max(σ_a,σ_b))+1)\n    isodd(l) || throw(ArgumentError(\"length must be odd\"))\n    w = l>>1\n    g = OffsetArray(fill(0.0f0, l, l), -w:w, -w:w)\n    #todo add when σ_x or/and σ_y == 0\n    for x ∈ -w:w, y ∈ -w:w\n        g[x,y] = exp(-1f0/2f0*((((x*cos(θ)-y*sin(θ))/σ_x)^2f0)+(((x*sin(θ)+y*cos(θ))/σ_y)^2f0)))\n    end\n    centered(g/sum(g))\nend\n\n\n\n# Rotating function\nfunction fun_R(x,y,θ)\n    x*cos(θ)-y*sin(θ), x*sin(θ)+y*cos(θ)\nend\n\n\n\nend", "meta": {"hexsha": "4fd9c588c8d417bb3c40c7791c35ed4674fede6a", "size": 2217, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/.ipynb_checkpoints/LaminartKernels-checkpoint.jl", "max_stars_repo_name": "nialltc/MEngProject.jl", "max_stars_repo_head_hexsha": "d3304c76ca2b377795627bd47fbd2156328d55e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/.ipynb_checkpoints/LaminartKernels-checkpoint.jl", "max_issues_repo_name": "nialltc/MEngProject.jl", "max_issues_repo_head_hexsha": "d3304c76ca2b377795627bd47fbd2156328d55e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/.ipynb_checkpoints/LaminartKernels-checkpoint.jl", "max_forks_repo_name": "nialltc/MEngProject.jl", "max_forks_repo_head_hexsha": "d3304c76ca2b377795627bd47fbd2156328d55e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3368421053, "max_line_length": 96, "alphanum_fraction": 0.5719440686, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7767780057391691}}
{"text": "#=\nThe number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.\n\nThere are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.\n\nHow many circular primes are there below one million?\n=#\ninclude(\"projecteulerutils.jl\")\nusing Primes\n\nfunction iscircularprime(x)\n  i = reverse(digits(x))\n  a = copy(i)\n  circularprime = true\n  for j in i\n    if !isprime(nd(a))\n      return false\n    end\n    a = prepend!(a, [pop!(a)])\n  end\n  true\nend\n\nfunction calc()\n  count = 0\n  for x in primes(2_000_000)\n    if iscircularprime(x)\n      count += 1\n    end\n  end\n  count\nend\n@time println(calc())\n", "meta": {"hexsha": "aa7965d03f8c6d63dae969cceb143ef4ae8f1c6f", "size": 674, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p35.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p35.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p35.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 19.8235294118, "max_line_length": 121, "alphanum_fraction": 0.6587537092, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810511092412, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7767514041212953}}
{"text": "\"\"\"\n    gegenbauer(x, p::Integer)\n\nEvaluate the Gegenbauer polynomial with parameter `α` of degree `p` at `x` using\nthe three term recursion.\n\"\"\"\nfunction gegenbauer(x, p::Integer, α)\n    T = typeof( 2α*x )\n    p₀ = one(T)\n    p₁ = 2α*x\n\n    if p <= 0\n        return p₀\n    elseif p == 1\n        return p₁\n    end\n\n    for n in 2:p\n        p₀, p₁ = p₁, ( 2x*(n+α-1)*p₁ - (2α+n-2)*p₀ ) / n\n    end\n\n    p₁\nend\n", "meta": {"hexsha": "d9c79145c6f7a8aea6ae875a48af6ec4cd545e79", "size": 409, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gegenbauer.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_stars_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-09-11T18:12:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T21:08:56.000Z", "max_issues_repo_path": "src/gegenbauer.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_issues_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2018-02-15T06:32:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T15:59:07.000Z", "max_forks_repo_path": "src/gegenbauer.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_forks_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:34:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:01:42.000Z", "avg_line_length": 17.0416666667, "max_line_length": 80, "alphanum_fraction": 0.533007335, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7766160478536006}}
{"text": "# Implicitly solving the heat equation\n# at cell centers and cell faces\n# Equation: ∂_t T = α * ∇²(T) + S, S = [β*sin(γ*z), β]\n# Boundary conditions: ∇T(z=a) = ∇T_bottom, T(z=b) = T_top\nimport Plots\nusing LinearAlgebra\n\n# Note that we can stably take huge timesteps even when α is large\n# warning, analytic solution only valid for a=0, b=1\na,b, n = 0, 1, 10               # zmin, zmax, number of cells\nn̂_min, n̂_max = -1, 1            # Outward facing unit vectors\nα = 100;                        # thermal diffusivity, larger means more stiff\nβ, γ = 10000, π;                # source term coefficients\nΔt = 1000;                      # timestep\nN_t = 10;                       # number of timesteps\nFT = Float64;                   # float type\nΔz = FT(b-a)/FT(n)\nΔz² = Δz^2;\n∇²_op = [1/Δz², -2/Δz², 1/Δz²]; # row or Laplacian operator\nT_init = 1;                     # Initial temperature, shouldn't matter for steady solution\n∇T_bottom = 10;                  # Temperature gradient at the top\nT_top = 1;                      # Temperature at the bottom\nuse_sin_forcing = true\nS(z) = use_sin_forcing ? β*sin(γ*z) : β # source term, (sin for easy integration)\nzf = range(a, b, length=n+1);\nzc = map(i-> zf[i]+Δz/2, 1:n);\n\n# Analytic steady state solution:\n# ∂∂T∂∂z = -S(z)/α = -β*sin(γ*z)/α\n# ∂T∂z = β*cos(γ*z)/(γ*α)+c1\n# T(z) = β*sin(γ*z)/(γ^2*α)+c1*z+c2 # generic solution\n# Apply bc: ∂T∂z(a) = β*cos(γ*a)/(γ*α)+c1 = ∇T_bottom => c1 = ∇T_bottom-β*cos(γ*a)/(γ*α)\n# Apply bc: T(b) =    β*sin(γ*b)/(γ^2*α)+c1*b+c2 = T_top =>\n#         c2 = T_top-(β*sin(γ*b)/(γ^2*α)+c1*b)\nfunction T_analytic_sin(z)\n    c1 = ∇T_bottom-β*cos(γ*a)/(γ*α)\n    c2 = T_top-(β*sin(γ*b)/(γ^2*α)+c1*b)\n    return β*sin(γ*z)/(γ^2*α)+c1*z+c2\nend\n\n# Analytic steady state solution:\n# ∂∂T∂∂z = -S(z)/α = -β/α\n# ∂T∂z = -z*β/α+c1\n# T(z) = -β*z^2/(2*α)+c1*z+c2 # generic solution\n# Apply bc: ∂T∂z(a) = -a*β/α+c1 = ∇T_bottom => c1 = ∇T_bottom+a*β/α\n# Apply bc: T(b) =    -β*b^2/(2*α)+c1*b+c2 = T_top =>\n#         c2 = T_top-(-β*b^2/(2*α)+c1*b)\nfunction T_analytic_uniform(z)\n    c1 = ∇T_bottom+a*β/α\n    c2 = T_top-(-β*b^2/(2*α)+c1*b)\n    return -β*z^2/(2*α)+c1*z+c2\nend\n\nT_analytic(z) =\n    use_sin_forcing ? T_analytic_sin(z) : T_analytic_uniform(z)\n\n#####\n##### T ∈ cell centers, ∇T ∈ cell faces\n#####\nprintln(\"Solve for T ∈ cell centers\")\nT = zeros(FT, n);\n\n# Equations: derivation to matrix form\n# ∂_t T = α * ∇²(T) + S\n# (T^{n+1}-T^n) = Δt (α * ∇²(T^{n+1}) + S)\n# (T^{n+1} - Δt α * ∇²(T^{n+1})) = T^n + Δt*S\n# (I - Δt α * ∇²) T^{n+1} = T^n + Δt*S\n\n# Derive Dirichlet boundary stencil & source:\n# ∂_t T = α * (T[i-1]+T[g]-2*T[i])/Δz² + S\n# ∂_t T = α * (T[i-1]+(2 T[b] - T[i])-2*T[i])/Δz² + S\n# ∂_t T = α * (T[i-1]-3*T[i])/Δz² + S + α * (2 T[b])/Δz²\n\n# Derive Neumann boundary stencil & source:\n# ∇T_bottom*n̂ = (T[g] - T[i])/Δz,     n̂ = [-1,1] ∈ [zmin,zmax]\n# ∇T_bottom*n̂ = -(T[i] - T[g])/Δz,    n̂ = [-1,1] ∈ [zmin,zmax]\n# ∂_t T = α * ((T[ii] - T[i])/Δz - (T[i] - T[g])/Δz)/Δz + S\n# ∂_t T = α * ((T[ii] - T[i])/Δz + ∇T_bottom*n̂)/Δz + S\n# ∂_t T = α * (T[ii] - T[i])/Δz² + S + α*∇T_bottom*n̂/Δz\n\n# Note that size(A) = (n,n) due to 1 Dirichlet and 1 Neumann.\n∇² = Tridiagonal(\n    ones(FT, n-1) .* ∇²_op[1],\n    ones(FT, n)   .* ∇²_op[2],\n    ones(FT, n-1) .* ∇²_op[3]\n);\n# Modify boundary stencil to account for BC\n∇².d[1] = -1/Δz²\n∇².d[end] = -3/Δz²\n\nA = LinearAlgebra.I - Δt.* α .* ∇²\n\n# Compute boundary sources: α * (2 T[b])/Δz², α * ∇T_bottom*n̂/Δz\nAT_b = zeros(FT, n);\nAT_b[1] = α*∇T_bottom*n̂_min/Δz;\nAT_b[end] = α*2*T_top/Δz²;\n\n# Set initial condition:\nT .= T_init;\n@inbounds for i_t in 1:N_t\n    # change in temperature per iter:\n    b_rhs = T .+ Δt .* (S.(zc) .+ AT_b)\n    T_new = A \\ b_rhs\n    ΔT_norm = sum(T .- T_new)/length(T)\n    @show ΔT_norm # watch ΔT norm\n    T .= T_new\nend\n\n# Interpolate to, and plot on, cell faces\nzf = range(a, b, length=n+1);\nTf = zeros(FT, n+1);\nTf[2:end-1] = [(T[i]+T[i+1])/2 for i in 1:length(T)-1]\n# ∇T_bottom*n̂ = (T[g] - T[i])/Δz, T[g] = 2*T[b] - T[i]\n# ∇T_bottom*n̂ = ((2*T[b] - T[i]) - T[i])/Δz\n# Δz*∇T_bottom*n̂ = 2*T[b] - 2*T[i]\n# (Δz*∇T_bottom*n̂ + 2*T[i])/2 = T[b]\nTf[1] = (Δz*∇T_bottom*n̂_min + 2*T[1])/2\nTf[end] = T_top\np1 = Plots.plot(zf, T_analytic.(zf), label=\"analytic\", markershape=:circle, markersize=6)\np1 = Plots.plot!(p1, zf, Tf, label=\"numerical\", markershape=:diamond)\np1 = Plots.plot!(p1, title=\"T ∈ cell centers\")\n\np3 = Plots.plot(zf, abs.(Tf .- T_analytic.(zf)), label=\"error\", markershape=:circle, markersize=6)\np3 = Plots.plot!(p3, title=\"T ∈ cell centers\")\n\n#####\n##### T ∈ cell faces, ∇T ∈ cell centers\n#####\n\nprintln(\"Solve for T ∈ cell faces\")\nT = zeros(FT, n+1);\n\n# Equations: derivation to matrix form\n# ∂_t T = α * ∇²(T) + S\n# (T^{n+1}-T^n) = Δt (α * ∇²(T^{n+1}) + S)\n# (T^{n+1} - Δt α * ∇²(T^{n+1})) = T^n + Δt*S\n# (I - Δt α * ∇²) T^{n+1} = T^n + Δt*S\n\n# Derive Dirichlet boundary stencil & source:\n# ∂_t T = α * (T[i-1]+T[b]-2*T[i])/Δz² + S\n# ∂_t T = α * (T[i-1]-2*T[i])/Δz² + S + α * T[b] / Δz²\n\n# Derive Neumann boundary stencil & source:\n# ∇T_bottom*n̂= (T[g] - T[i])/(2Δz),     n̂ = [-1,1] ∈ [zmin,zmax]\n# T[i] + 2*Δz*∇T_bottom*n̂ = T[g]\n# ∂_t T = α * (((T[i] + 2*Δz*∇T_bottom*n̂) - T[b])/Δz - (T[b] - T[i])/Δz)/Δz + S\n# ∂_t T = α * (((T[i]) - T[b])/Δz - (T[b] - T[i])/Δz)/Δz + S + α/Δz²*2*Δz*∇T_bottom*n̂\n# ∂_t T = α * (2*T[i] - 2*T[b])/Δz² + S + 2α/Δz*∇T_bottom*n̂\n\n# Note that size(A) = (n,n) due to 1 Dirichlet and 1 Neumann.\n∇² = Tridiagonal(\n    ones(FT, n) .* ∇²_op[1],\n    ones(FT, n+1)   .* ∇²_op[2],\n    ones(FT, n) .* ∇²_op[3]\n);\n\n# Modify boundary stencil to account for BCs\n∇².d[1] = -2/Δz²\n∇².du[1] = +2/Δz²\n\n# Modify boundary stencil to account for BCs\n∇².du[n] = 0  # modified stencil\n∇².d[n+1] = 0 # to ensure `∂_t T = 0` at `z=zmax`\n∇².dl[n] = 0  # to ensure `∂_t T = 0` at `z=zmax`\n\nA = LinearAlgebra.I - Δt.* α .* ∇²\n\n# Compute boundary source: α * T[b] / Δz²\nAT_b = zeros(FT, n+1);\nAT_b[1] = α*2/Δz*∇T_bottom*n̂_min;\nAT_b[end-1] = α*T_top/Δz²;\n\n# Set initial condition:\nT .= T_init;\nT[n+1] = T_top\n@inbounds for i_t in 1:N_t\n    interior = 1:n\n    b_rhs = T .+ Δt .* (S.(zf) .+ AT_b)\n    T_new = A \\ b_rhs\n    ΔT_norm = sum(T .- T_new)/length(T)\n    @show ΔT_norm # watch ΔT norm\n    T .= T_new\nend\n\np2 = Plots.plot(zf, T_analytic.(zf), label=\"analytic\", markershape=:circle, markersize=6)\np2 = Plots.plot!(p2, zf, T, label=\"numerical\", markershape=:diamond)\np2 = Plots.plot!(p2, title=\"T ∈ cell faces\")\n\np4 = Plots.plot(zf, abs.(T .- T_analytic.(zf)), label=\"error\", markershape=:circle, markersize=6)\np4 = Plots.plot!(p4, title=\"T ∈ cell faces\")\n\nPlots.plot(p1, p3, p2, p4)\n", "meta": {"hexsha": "63c7d5b6a6c2e1ac8a8b2c3e4dd1644e81acf122", "size": 6554, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "heat_implicit.jl", "max_stars_repo_name": "CliMA/MinimumWorkingExamples.jl", "max_stars_repo_head_hexsha": "ff359bcec17c4158379a94d9fee71087888027dc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-05T07:11:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T07:11:08.000Z", "max_issues_repo_path": "heat_implicit.jl", "max_issues_repo_name": "CliMA/MinimumWorkingExamples.jl", "max_issues_repo_head_hexsha": "ff359bcec17c4158379a94d9fee71087888027dc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "heat_implicit.jl", "max_forks_repo_name": "CliMA/MinimumWorkingExamples.jl", "max_forks_repo_head_hexsha": "ff359bcec17c4158379a94d9fee71087888027dc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-08T22:58:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T22:58:43.000Z", "avg_line_length": 33.9585492228, "max_line_length": 98, "alphanum_fraction": 0.5466890449, "num_tokens": 2992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7766160463351793}}
{"text": "# This file calculates scattering from the Helmholtz equation via the adaptive spectral method.\n# Δu + k^2u = 0,\n# u|Γ = 0,\n# u^i = e^{im k x⋅d},\n# u = u^i + u^s.\n# The normal derivative ∂u/∂n of the entire wave is calculated on the sound-soft boundaries.\n# The scattered wave is calculated by convolving [∂u/∂n] with the fundamental solution.\n# Then, the total wave is obtained by summing the incident and the scattered waves.\n\nusing ApproxFun, SingularIntegralEquations\ninclude(\"Scatteraux.jl\")\n\nk = 50.\nω = 2π\nd = (1,-1)\nd = d[1]/hypot(d[1],d[2]),d[2]/hypot(d[1],d[2])\nui = (x,y) -> exp(im*k*(d[1]*x+d[2]*y))\n\n# The Helmholtz Green's function, split into singular and nonsingular pieces.\ng1 = (x,y) -> -besselj0(k*abs(y-x))/2\ng2 = (x,y) -> x == y ? -(log(k/2)+γ)/2/π + im/4 : im/4*hankelh1(0,k*abs(y-x)) - g1(x,y).*logabs(y-x)/π\n\n\n# A variety of domains.\n\n#dom = Circle(0.0,1/π)∪Segment(-1.0im,1.0)\n#dom = ∪(Segment.([-2.5-.5im,-1.5+.5im,-.5-.5im,.5+.5im,1.5-.5im],[-1.5-.5im,-.5+.5im,.5-.5im,1.5+.5im,2.5-.5im]))\n#dom = ∪(Segment.([-1.0-0.4im,0.1+0.4im,-0.9-0.5im],[-0.1+0.4im,1.0-0.4im,0.9-0.5im]))\n#dom = ∪(Segment.([-1.0-0.4im,-0.5-0.4im,0.1+0.4im,0.2+0.0im,-1.4-0.75im],[-0.1+0.4im,-0.2+0.0im,1.0-0.4im,0.5-0.4im,1.4-0.75im]))\n#dom = ∪(Circle.([0.,-1.0im],[0.5,0.25]))∪(Segment.([-1.5,0.5-1.0im,-0.5+1.0im],[-0.5-1.0im,1.5,0.5+1.0im]))\ndom = ChebyshevInterval()\n\nsp = Space(dom)\ncwsp = CauchyWeight(sp⊗sp,0)\nuiΓ,⨍ = Fun(t->ui(real(t),imag(t)),sp),DefiniteLineIntegral(dom)\n\n@time G = GreensFun(g1,cwsp;method=:Cholesky) + GreensFun(g2,sp⊗sp;method=:Cholesky)\n\n@time ∂u∂n = ⨍[G]\\uiΓ\nprintln(\"The length of ∂u∂n is: \",ncoefficients(∂u∂n))\nus = (x,y) -> -logkernel(g1,∂u∂n,complex(x,y))-linesum(g2,∂u∂n,complex(x,y))\n", "meta": {"hexsha": "a3a0df6a43f8d60a5f12a1cdbb811db7427f6210", "size": 1722, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/HelmholtzDirichlet.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SingularIntegralEquations.jl-e094c991-5a90-5477-8896-c1e4c9552a1a", "max_stars_repo_head_hexsha": "8a0ca7376ecad020ef8f8beca90686311fbb9f84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2016-12-02T13:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T18:31:48.000Z", "max_issues_repo_path": "examples/HelmholtzDirichlet.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SingularIntegralEquations.jl-e094c991-5a90-5477-8896-c1e4c9552a1a", "max_issues_repo_head_hexsha": "8a0ca7376ecad020ef8f8beca90686311fbb9f84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2016-12-19T06:02:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:33:33.000Z", "max_forks_repo_path": "examples/HelmholtzDirichlet.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SingularIntegralEquations.jl-e094c991-5a90-5477-8896-c1e4c9552a1a", "max_forks_repo_head_hexsha": "8a0ca7376ecad020ef8f8beca90686311fbb9f84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-05-16T06:08:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:20:46.000Z", "avg_line_length": 41.0, "max_line_length": 130, "alphanum_fraction": 0.619047619, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.776616046123775}}
{"text": "\"\"\"\n    Berlage(; <keyword arguments>)\n\nCreate a Berlage wavelet.\n\n# Arguments\n\n**Keyword arguments**\n\n* `dt::Real=0.002`: sampling interval in secs.\n* `f0::Real=20.0`: central frequency in Hz.\n* `m::Real=2`: exponential parameter of Berlage wavelet.\n* `alpha::Real=180.0`: alpha parameter of Berlage wavelet in rad/secs.\n* `phi0::Real`: phase rotation in radians.\n\n# Example\n```julia\njulia> w = Berlage(); plot(w);\n```\n\n**Reference**\n\n* Aldridge, David F., 1990, The berlage wavelet: GEOPHYSICS, 55, 1508--1511.\n\"\"\"\n\nfunction Berlage(; dt::Real=0.002, f0::Real=20.0, m::Real=2, alpha::Real=180.0,\n                 phi0::Real=0.0)\n\n    nw = floor(Int, 2.2/(f0*dt))\n    t = dt*collect(0:1:nw-1)\n    w = (t.^m).*exp(-alpha*t).*cos(2*pi*f0*t + phi0);\n    w = w/maximum(w)\n    \nend\n", "meta": {"hexsha": "5957947f79fe8d97f662f9fac807a6734acc90b4", "size": 778, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Wavelets/Berlage.jl", "max_stars_repo_name": "JuliaPackageMirrors/Seismic.jl", "max_stars_repo_head_hexsha": "7fb94347c2486f8de3185edf92bbf023f9e68cc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Wavelets/Berlage.jl", "max_issues_repo_name": "JuliaPackageMirrors/Seismic.jl", "max_issues_repo_head_hexsha": "7fb94347c2486f8de3185edf92bbf023f9e68cc5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Wavelets/Berlage.jl", "max_forks_repo_name": "JuliaPackageMirrors/Seismic.jl", "max_forks_repo_head_hexsha": "7fb94347c2486f8de3185edf92bbf023f9e68cc5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-07T17:48:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-07T17:48:25.000Z", "avg_line_length": 22.2285714286, "max_line_length": 79, "alphanum_fraction": 0.616966581, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7766160452524303}}
{"text": "export size_criterion, sqrt_criterion, change_criterion, log_criterion, epsilon_criterion\n\n\n\"\"\"\nStops when the distance between far items achieves the given `e`\n\"\"\"\nfunction epsilon_criterion(e)\n   (dmaxlist, database) -> dmaxlist[end] < e\nend\n\n\"\"\"\nStops when the number of far items are equal or larger than the given `maxsize`\n\"\"\"\nfunction size_criterion(maxsize)\n   (dmaxlist, database) -> length(dmaxlist) >= maxsize\nend\n\n\"\"\"\nStops when the number of far items are equal or larger than the square root of the size of the database\n\"\"\"\nfunction sqrt_criterion()\n   (dmaxlist, database) -> length(dmaxlist) >= Int(length(database) |> sqrt |> round)\nend\n\n\"\"\"\nStops when the number of far items are equal or larger than logarithm-2 of the size of the database\n\"\"\"\nfunction log_criterion()\n   (dmaxlist, database) -> length(dmaxlist) >= Int(length(database) |> log2 |> round)\nend\n\n\"\"\"\nStops the process whenever the maximum distance converges, i.e., after `window` far items the maximum distance\nchange is below or equal to the allowed tolerance `tol`\n\"\"\"\nfunction change_criterion(tol=0.001, window=3)\n    mlist = Float64[]\n    count = 0.0\n    function stop(dmaxlist, database)\n        count += dmaxlist[end]\n        \n        if length(dmaxlist) % window != 1\n            return false\n        end\n        push!(mlist, count)\n        count = 0.0\n        if length(dmaxlist) < 2\n            return false\n        end\n        \n        s = abs(mlist[end] - mlist[end-1])\n        return s <= tol\n    end\n    \n    return stop\nend\n\n\"\"\"\nIt nevers stops by side, it explores the entire dataset making a full farthest first traversal\n\"\"\"\nfunction salesman_criterion()\n    function stop(dmaxlist, dataset)\n        return false\n    end\nend", "meta": {"hexsha": "7326ac02b5289a399b1c8ee9a5cc0757be56dd19", "size": 1725, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kmap/criterions.jl", "max_stars_repo_name": "UnofficialJuliaMirror/KernelMethods.jl-d79e8f30-5872-11e9-0dab-2d1842b87615", "max_stars_repo_head_hexsha": "f74f497debd1caac641e359225f958fa2902127f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-10-16T23:24:03.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-16T23:24:03.000Z", "max_issues_repo_path": "src/kmap/criterions.jl", "max_issues_repo_name": "UnofficialJuliaMirror/KernelMethods.jl-d79e8f30-5872-11e9-0dab-2d1842b87615", "max_issues_repo_head_hexsha": "f74f497debd1caac641e359225f958fa2902127f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kmap/criterions.jl", "max_forks_repo_name": "UnofficialJuliaMirror/KernelMethods.jl-d79e8f30-5872-11e9-0dab-2d1842b87615", "max_forks_repo_head_hexsha": "f74f497debd1caac641e359225f958fa2902127f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-10-16T21:20:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:31:47.000Z", "avg_line_length": 26.5384615385, "max_line_length": 110, "alphanum_fraction": 0.6742028986, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951698485603, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7766160435097403}}
{"text": "\"\"\"\n**Distance to a primary producer**\n\nThis function measures, for every species, its shortest path to a primary\nproducer using matrix exponentiation. A primary producer has a value of 1,\na primary consumer a value of 2, and so forth.\n\n\"\"\"\nfunction distance_to_producer(L::Array{Int64, 2})\n\n    # We identify producers\n    is_producer = vec(sum(L, dims = 2) .== 0)\n\n    # Producers have a distance of 1\n    d = zeros(Int64, length(is_producer))\n    d[is_producer] .= 1\n\n    # We work on a copy of the matrix with no self-loops\n    K = copy(L)\n    for i in eachindex(d)\n        K[i ,i] = 0\n    end\n\n    # We loop as long as there are species with unknown distance\n    i = 1\n    while (i < length(d))|(sum(d) == 0)\n        connected_at_length = (K^i * is_producer) .> 0\n        d[(d .== 0) .* (connected_at_length)] .= i+1\n        i = i+1\n    end\n    return d\nend\n\n\"\"\"\n**Trophic rank**\n\nBased on the average distance of preys to primary producers. Specifically, the\nrank is defined as the average of the distance of preys to primary producers\n(recursively). Primary producers always have a trophic rank of 1.\n\n\"\"\"\nfunction trophic_rank(L::Array{Int64, 2})\n    # Average of positve elements, 0 otherwise\n    nonzeromean = (x) -> maximum(x) == 0 ? 0 : mean(x[x.>0])\n    d = distance_to_producer(L)\n    dL = L .* d'\n    TL = zeros(length(d))\n    for i in eachindex(d)\n        TL[i] = nonzeromean(dL[i,:]) + 1\n    end\n    return TL\nend\n", "meta": {"hexsha": "edbaeed8f253b570fac7ac516d1a57e2781674c1", "size": 1431, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/trophic_rank.jl", "max_stars_repo_name": "SimmonsBI/BioEnergeticFoodWebs", "max_stars_repo_head_hexsha": "72847a9c8cce408d3bc5bc08a70f92115aeca00c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2016-10-11T20:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T10:47:43.000Z", "max_issues_repo_path": "src/trophic_rank.jl", "max_issues_repo_name": "SimmonsBI/BioEnergeticFoodWebs", "max_issues_repo_head_hexsha": "72847a9c8cce408d3bc5bc08a70f92115aeca00c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 101, "max_issues_repo_issues_event_min_datetime": "2016-10-11T14:26:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T17:41:59.000Z", "max_forks_repo_path": "src/trophic_rank.jl", "max_forks_repo_name": "SimmonsBI/BioEnergeticFoodWebs", "max_forks_repo_head_hexsha": "72847a9c8cce408d3bc5bc08a70f92115aeca00c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2016-10-12T07:31:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T11:02:23.000Z", "avg_line_length": 27.0, "max_line_length": 78, "alphanum_fraction": 0.6387141859, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409308, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7766160374360549}}
{"text": "# FeynmanTheory.jl\n\n\"\"\"\nfrohlichalpha(ε_Inf,ε_S,freq,m_eff)\n\n    Calculates the Frohlich alpha parameter, for a given dielectric constant,\n    frequency (f) of phonon in Hertz, and effective mass (in units of the\n    bare electron mass).\n\n    See Feynman 1955:\n    http://dx.doi.org/10.1103/PhysRev.97.660\n\n\"\"\"\nfunction frohlichalpha(ε_optic,ε_static,freq,m_eff)\n    ω=freq*2*pi #frequency to angular velocity\n    # Note: we need to add a 4*pi factor to the permitivity of freespace.\n    # This gives numeric agreement with literature values.  This is required as\n    # the contemporary 1950s and 1960s literature implicitly used atomic units,\n    # where the electric constant ^-1 has this factor baked in, k_e=1/(4πϵ_0).\n    α= 0.5/(4*π*ε_0) *              # Units: m/F\n       (1/ε_optic - 1/ε_static) *   # Units: none\n       (q^2/(hbar*ω)) *             # Units: F\n       sqrt(2*me*m_eff*ω/ħ)         # Units: 1/m\n    return (α)\nend\n\n#####\n# Athermal (Feynman 1955) model\n# Set up equations for the polaron free energy, which we will variationally improve upon\n\n# Integrand of (31) in Feynman I (Feynman 1955, Physical Review, \"Slow electrons...\")\nfF(τ,v,w)=(w^2 * τ + (v^2-w^2)/v*(1-exp(-v*τ)))^-0.5 * exp(-τ)\n# (31) in Feynman I\nAF(v,w,α)=π^(-0.5) * α*v * quadgk(τ->fF(τ,v,w),0,Inf)[1]\n# (33) in Feynman I\nF(v,w,α)=(3/(4*v))*(v-w)^2-AF(v,w,α)\n\n# Let's wrap the Feynman athermal variation approximation in a simple function\n\"\"\"\n    feynmanvw(α; v=7.0, w=6.0)\n\n    Calculate v and w variational polaron parameters,\n    for the supplied α Frohlich coupling.\n    This version uses the original athermal action (Feynman 1955).\n\tReturns v,w.\n\"\"\"\nfunction feynmanvw(α; v=7.0, w=6.0) # v,w defaults\n    initial=[v,w]\n    # Main use of these bounds is stopping v or w going negative, at which you get a NaN error as you are evaluating log(-ve Real)\n    lower=[0.1,0.1]\n    upper=[1000.0,1000.0]\n\n    myf(x) = F(x[1],x[2],α) # Wraps the function so just the two variational params are exposed\n\n    # Now updated to use Optim.jl > 0.15.0 call signature (Julia >0.6 only)\n    res=optimize(OnceDifferentiable(myf, initial; autodiff = :forward), \n                 lower, upper, initial, Fminbox( BFGS() ) )\n    # specify Optim.jl optimizer. This is doing all the work.\n\n    v,w=Optim.minimizer(res)\n\n    return v,w\nend\n\n\n\n# Hellwarth et al. 1999 PRB - Part IV; T-dep of the Feynman variation parameter\n\n# Originally a Friday afternoon of hacking to try and implement the T-dep electron-phonon coupling from the above PRB\n# Which was unusually successful! And more or less reproduced Table III\n\n# In Julia we have 'Multiple dispatch', so let's just construct the free\n# energies (temperature-dependent) with the same name as before, but withthe\n# thermodynamic beta where required\n\n# Define Osaka's free-energies (Hellwarth1999 version) as Julia functions\n# Equation numbers follow above Hellwarth et al. 1999 PRB\n# 62b\nA(v,w,β)=3/β*( log(v/w) - 1/2*log(2*π*β) - log(sinh(v*β/2)/sinh(w*β/2)))\n# 62d\nY(x,v,β)=1/(1-exp(-v*β))*(1+exp(-v*β)-exp(-v*x)-exp(v*(x-β)))\n# 62c integrand\nf(x,v,w,β)=(exp(β-x)+exp(x))/(w^2*x*(1-x/β)+Y(x,v,β)*(v^2-w^2)/v)^(1/2)\n# 62c\nB(v,w,β,α) = α*v/(sqrt(π)*(exp(β)-1)) * quadgk(x->f(x,v,w,β),0,β/2)[1]\n# 62e\nC(v,w,β)=3/4*(v^2-w^2)/v * (coth(v*β/2)-2/(v*β))\n# 62a\nF(v,w,β,α)=-(A(v,w,β)+B(v,w,β,α)+C(v,w,β))\n\n# Can now evaluate, e.g.\n# F(v,w,β,α)=F(7.2,6.5,1.0,1.0)\n# BUT - this is just the objective function! (The temperature-dependent free-energy.) Not the optimised parameters.\n# Also there's a scary numeric integration (quadgk) buried within...\n\n# Unbundled version of the finite temperature one\n\"\"\"\n    feynmanvw(α, βred; v=7.1, w=6.5, verbose::Bool=false)\n\n    Calculate v and w variational polaron parameters,\n    for the supplied α Frohlich coupling and βred reduced thermodynamic temperature.\n    This uses the Osaka finite temperature action.\n    Returns v,w.\n\"\"\"\nfunction feynmanvw(α, βred; v=7.1, w=6.5, verbose::Bool=false) # v,w defaults\n    # Initial v,w to use\n    initial=[v,w]\n    # Main use of these bounds is stopping v or w going negative, at which you get a NaN error as you are evaluating log(-ve Real)\n    lower=[0.1,0.1]\n    upper=[100.0,100.0]\n\n    myf(x) = F(x[1],x[2],βred,α) # Wraps the function so just the two variational params are exposed\n    \n    # Now updated to use Optim > 0.15.0 call signature (Julia >0.6 only)\n    res=optimize(OnceDifferentiable(myf, initial; autodiff = :forward), \n                 lower, upper, initial, Fminbox( BFGS() ) )\n    # specify Optim.jl optimizer. This is doing all the work.\n\n    if Optim.converged(res) == false\n        print(\"\\tWARNING: Failed to converge to v,w soln? : \",Optim.converged(res) )\n    end\n\n    if verbose\n        println()\n        show(res)\n    end\n\n    v,w=Optim.minimizer(res)\n    return v,w\nend\n\n", "meta": {"hexsha": "1fe6898fa2378a5504293c51d9d0e463a6ac4153", "size": 4801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FeynmanTheory.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PolaronMobility.jl-a1b829d7-2a44-59aa-80d3-9ddd83901c9b", "max_stars_repo_head_hexsha": "51aa09add590bd6b68406bbf16eb872d2e502a69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FeynmanTheory.jl", "max_issues_repo_name": "UnofficialJuliaMirror/PolaronMobility.jl-a1b829d7-2a44-59aa-80d3-9ddd83901c9b", "max_issues_repo_head_hexsha": "51aa09add590bd6b68406bbf16eb872d2e502a69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FeynmanTheory.jl", "max_forks_repo_name": "UnofficialJuliaMirror/PolaronMobility.jl-a1b829d7-2a44-59aa-80d3-9ddd83901c9b", "max_forks_repo_head_hexsha": "51aa09add590bd6b68406bbf16eb872d2e502a69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3712121212, "max_line_length": 130, "alphanum_fraction": 0.6569464695, "num_tokens": 1630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.776616034399212}}
{"text": "#\r\n# This is an example of estimation of a portfolio model\r\n# as in Hansen and Singleton, 1982. The data comes from\r\n# Tauchen, JBES, 1986 (available by ftp).\r\n# The notation follows my lecture notes. In particular\r\n# gamma is the coefficient of RRA. Try out different sets\r\n# of intruments and different lag lengths. You will see\r\n# that beta is stable across  models, but that gamma is not.\r\n#\r\n# Michael Creel, Oct. 24, 2000\r\n# revised 7 Nov. 2002\r\n# translated to Octave 9/9/2003\r\n# translated to Julia 07 Aug. 2017\r\n# michael.creel@uab.es\r\n\r\n\r\n# The main thing you have to to is define the moments for estimation,\r\n# as in the function that follows immediately, and ensure that the\r\n# efficient weight matrix is estimated appropriately. The rest\r\n# is already programmed.\r\n\r\n\r\n# the following function defines the moment conditions, given the parameter\r\n# vector and the instruments. It returns the individual contributions\r\n# to allow estimation of the covariance matrix of the moments.\r\nusing DelimitedFiles, Statistics, Econometrics\r\nfunction portfolio_moments(theta, data)\r\n\t# parameters\r\n\tbeta = theta[1]\r\n\tgam = theta[2]\r\n\t# data items\r\n\tc = data[:,1]\r\n\tr = data[:,2]\r\n    inst = data[:,3:end]\r\n\t#  form error function\r\n\t# note that c = c_t / c_t-1 (for stationarity) was done in data preparation\r\n\te = 1.0 .- beta*(1.0 .+ r) .* (c .^ (-gam))\r\n\t# cross with instruments\r\n\tm = e.*inst\r\nend\r\n\r\nfunction main()\r\ndata = readdlm(\"tauchen.data\")\r\nc = data[:,1]\r\np = data[:,2]\r\nd = data[:,3]\r\n# form net return and stationary consumption\r\nr = (p + d) ./ lag(p,1) .- 1.0\r\nc = c ./ lag(c,1); # ensure stationarity\r\n# choose maximal lag of instruments.\r\nmax_lag = 1\r\ninst = [c r d p]\r\ninst = lags(inst, max_lag)\r\ninst, junk, junk = stnorm(inst)\r\ninst = [ones(size(inst,1),1) inst]\r\n# drop rows with missing values\r\ndata = [c r inst]\r\ndata = data[max_lag+1:end,:]\r\n# do estimation\r\nmoments = θ -> portfolio_moments(θ, data)\r\nweight = 1.0\r\nnames = [\"beta\",\"gamma\"]\r\n# initial consistent estimate\r\ntheta = [0.9, 1]\r\nthetahat, obj_value, D, ms, convergence = gmm(moments, theta, weight)\r\n# second step with efficient weight matrix\r\nomega = 50.0*cov(ms)\r\nweight = inv(omega)\r\ntitle = \"Two step GMM estimation of portfolio model\"\r\nresults = gmmresults(moments, thetahat, weight, title, names)\r\n# CUE GMM\r\ntitle = \"CUE GMM estimation of portfolio model\"\r\ngmmresults(moments, results[1], \"\", title, names)\r\nreturn\r\nend\r\nmain()\r\n", "meta": {"hexsha": "faa993a3c5654b0ae9e49ab98e220645e953aebb", "size": 2421, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/GMM/portfolio.jl", "max_stars_repo_name": "nilshg/Econometrics", "max_stars_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-28T01:07:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T01:07:58.000Z", "max_issues_repo_path": "Examples/GMM/portfolio.jl", "max_issues_repo_name": "nilshg/Econometrics", "max_issues_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/GMM/portfolio.jl", "max_forks_repo_name": "nilshg/Econometrics", "max_forks_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-03T13:06:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-03T13:06:42.000Z", "avg_line_length": 31.4415584416, "max_line_length": 77, "alphanum_fraction": 0.6914498141, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7765987070405267}}
{"text": "\"\"\"\nCreated on Wed Sep 23 2020\n\n@author: Yoann Pradat\n\nMultiplicative update algorithms for α divergence.\n\"\"\"\n\n\"\"\"\n    _update_nmf_mu_α!(V, WH, W, H, α, ϵ)\n    \n\"\"\"\nfunction _update_nmf_mu_α!(V::Matrix{T}, WH::Matrix{T}, W::Matrix{T}, H::Matrix{T}, α::Real, ϵ::Real) where T <: Real\n    if α == 0\n        #### dual Kullback-Leibler\n\n        #### update H\n        #### NOTE: if W has columns normalized to sum to 1, the normalization matrix\n        #### (transpose(W) * ones(size(V))) .^ (-1) is just ones(K, N)\n        H .= H .* exp.((transpose(W) * ones(size(V))) .^ (-1)  .* (transpose(W) * log.(V ./ (WH .+ ϵ)))) \n        WH .= W * H\n\n        #### update W\n        #### NOTE: if H has columns normalized to sum to 1, the normalization matrix\n        #### (transpose(H) * ones(size(V))) .^ (-1) is just ones(K, N)\n        W .= W .* exp.((ones(size(V)) * transpose(H)) .^ (-1) .* (log.(V ./ (WH .+ ϵ)) * transpose(H)))\n        WH .= W * H\n\n    else\n        #### general α divergence updates for α != 0\n        \n        #### A.Cichocki, S.Amari, R.Zdunek, R.Kompass, G.Hori, and Z.He,\n        #### \"Extended SMART algorithms for non-negative matrix factorization,\"\n        #### Artificial Intelligence and Soft Computing, 2006.\n        #### Equation (44)\n        \n        #### note: it is not clear in eqs (45) and (46) how the normalization\n        #### made the denominators disappear in (44).\n        \n        # #### case of eqs (45), (46)\n        # \n        # # update W\n        # W .= W .* (((V .+ ϵ) ./ (WH .+ ϵ)) .^ α * transpose(H)) .^ (1/α)\n\n        # #### normalize to unit sums the columns of W if specified\n        # #### note: order not as in (45-46)\n        # cs_W = sum(W, dims=1)\n        # W .= W .* repeat(cs_W .^ -1, size(W, 1), 1)\n\n        # WH .= W * H\n\n        # # update H\n        # H .= H .* ((transpose(W) * ((V .+ ϵ)./(WH .+ ϵ)) .^ α)) .^ (1/α)\n        # WH .= W * H\n\n        #### eqs (44)\n        \n        # update W\n        W .= W .* ((((V .+ ϵ) ./ (WH .+ ϵ)) .^ α * transpose(H)) ./ (ones(size(V)) * transpose(H)) .+ ϵ) .^ (1/α) \n        WH .= W * H\n\n        # update H\n        H .= H .* (((transpose(W) * ((V .+ ϵ) ./ (WH .+ ϵ)) .^ α)) ./ (transpose(W) * ones(size(V))) .+ ϵ) .^ (1/α)\n        WH .= W * H\n\n    end\nend\n", "meta": {"hexsha": "775591b48ebfacd0e71dc04c6f8b9b38c4ab4acf", "size": 2247, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solver/base/nmf_MU_alpha.jl", "max_stars_repo_name": "Durzot/MT_NMF", "max_stars_repo_head_hexsha": "a3e3c2fb4a23cc09e78e1ad1e324787c6017a4fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/solver/base/nmf_MU_alpha.jl", "max_issues_repo_name": "Durzot/MT_NMF", "max_issues_repo_head_hexsha": "a3e3c2fb4a23cc09e78e1ad1e324787c6017a4fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solver/base/nmf_MU_alpha.jl", "max_forks_repo_name": "Durzot/MT_NMF", "max_forks_repo_head_hexsha": "a3e3c2fb4a23cc09e78e1ad1e324787c6017a4fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0441176471, "max_line_length": 117, "alphanum_fraction": 0.4606141522, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191348157373, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.776547709292776}}
{"text": "module SkillRating\n\n    const q = log(10)/400\n\n    g(rd) = 1/sqrt(1 + 3q^2 * (rd^2)/π^2)\n    Es(r, r2, rd2) = 1/(1+10^(-g(rd2) * (r - r2) / 400))\n    d2(r, rjs, RDjs) = 1/((q^2) * sum(g.(RDjs).^2 .* Es.(r, rjs, RDjs).* (1 .- Es.(r, rjs, RDjs))))\n\n    \"\"\"\n        glicko_rating(r, RD, rjs::Vector, RDjs::Vector, sjs::Vector)\n        glicko_rating(r, RD, rj::T, RDj::T, sj::T) where T <: Real\n    \n    # Arguments:\n    * `r`: Rating of player\n    * `RD`: Rating deviation of player\n    * `rjs`: Ratings of oppenents within rating period.\n    * `RDjs`: Rating devations of oppenents within rating period.\n    * `sjs`: Game outcomes from the perspective of the \"player\": 1 - won, 0.5 - draw, 0 - lost.\n    \n    Calculate a new glicko rating for games within a rating period or for a single game.\n    \n    See: http://www.glicko.net/glicko/glicko.pdf and Glickman, Mark E., \"Parameter estimation \n    in large dynamic paired comparison experiments\" (1999) Applied Statistics, 48, 377-394\n    (http://www.glicko.net/research/glicko.pdf)\n    \"\"\"\n    glicko_rating(r, RD, rjs::Vector, RDjs::Vector, sjs::Vector) = r + q/(1/RD^2 + 1/d2(r, rjs, RDjs)) * sum(g.(RDjs) .* (sjs .- Es.(r, rjs, RDjs)))\n\n    \"\"\"\n        glicko_RD(r, RD, rjs::Vector, RDjs::Vector, sjs::Vector)\n        glicko_RD(r, RD, rj::T, RDj::T, sj::T) where T <: Real\n\n    # Arguments:\n    * `r`: Rating of player\n    * `RD`: Rating deviation of player\n    * `rjs`: Ratings of oppenents within rating period.\n    * `RDjs`: Rating devations of oppenents within rating period.\n    * `sjs`: Game outcomes from the perspective of the \"player\": 1 - won, 0.5 - draw, 0 - lost.\n\n    Calculate a new glicko rating deviation for games within a rating period  or for a single game.\n    \n    See: http://www.glicko.net/glicko/glicko.pdf and \n    Glickman, Mark E., \"Parameter estimation in large dynamic paired comparison experiments\" (1999) Applied Statistics, 48, 377-394\n    (http://www.glicko.net/research/glicko.pdf)\n    \"\"\"\n    glicko_RD(r, RD, rjs::Vector, RDjs::Vector, sjs::Vector) = sqrt(1/(1/RD^2 + 1/d2(r, rjs, RDjs)))\n    \n    glicko_rating(r, RD, rj::T, RDj::T, sj::T) where T <: Real = glicko_rating(r, RD, [rj], [RDj], [sj])\n    glicko_RD(r, RD, rj::T, RDj::T, sj::T) where T <: Real = glicko_RD(r, RD, [rj], [RDj], [sj])\n    \n    \"\"\"\n        glicko_RD_increase(rd; c = 63.2, maxrd=350)\n\n    # Arguments:\n    * `RD`: Rating deviation at end of rating period.\n    * `c`: Increase in uncertainty between rating periods.\n    * `maxRD`: Rating deviation of a player who does not play.\n\n    Calculate rating deviation after the end of a rating period.\n    \n    See: http://www.glicko.net/glicko/glicko.pdf and \n    Glickman, Mark E., \"Parameter estimation in large dynamic paired comparison experiments\" (1999) Applied Statistics, 48, 377-394\n    (http://www.glicko.net/research/glicko.pdf)\n    \"\"\"\n    glicko_RD_increase(RD; c = 63.2, maxRD=350) = min(sqrt(RD^2+c^2), maxRD)\n\n    \"\"\"\n        glicko_c(rating_perods_to_max, maxrd, medianrd)\n\n    Calculate c, the increase in uncertainty between rating periods.\n    \n    See: http://www.glicko.net/glicko/glicko.pdf and \n    Glickman, Mark E., \"Parameter estimation in large dynamic paired comparison experiments\" (1999) Applied Statistics, 48, 377-394\n    (http://www.glicko.net/research/glicko.pdf)\n    \"\"\"\n    glicko_c(rating_perods_to_max, maxrd, medianrd) = sqrt((maxrd^2 - medianrd^2)/rating_perods_to_max)\n\n    \"\"\"\n    elo_expected(RA, RB)\n\n    # Arguments:\n    * `RA`: Rating of player A\n    * `RB`: Rating of player B\n\n    Calculate the expected outcome using glicko.\n    \n    See: http://www.glicko.net/glicko/glicko.pdf and \n    Glickman, Mark E., \"Parameter estimation in large dynamic paired comparison experiments\" (1999) Applied Statistics, 48, 377-394\n    (http://www.glicko.net/research/glicko.pdf)\n    \"\"\"\n    glicko_expected(r1, RD1, r2, RD2) = 1 / (1 + 10^(-g(sqrt(RD1^2 + RD2^2)) * (r1 - r2)/400))\n\n    \"\"\"\n        elo_rating(r, rjs::Vector, sjs::Vector; k = 32)\n\n    # Arguments:\n    * `r`: Rating of player\n    * `rjs`: Ratings of oppenents within rating period.\n    * `sjs`: Game outcomes from the perspective of the \"player\": 1 - won, 0.5 - draw, 0 - lost.\n\n    Calculate the elo rating change.\n    See: https://en.wikipedia.org/wiki/Elo_rating_system#Mathematical_details\n    \"\"\"\n    elo_rating(r, rjs::Vector, sjs::Vector; k = 32) = r + k * (sum(sjs) - sum(elo_expected.(r, rjs)))\n\n    \"\"\"\n    elo_expected(RA, RB)\n\n    # Arguments:\n    * `RA`: Rating of player A\n    * `RB`: Rating of player B\n\n    Calculate the expected outcome using elo.\n    See: https://en.wikipedia.org/wiki/Elo_rating_system#Mathematical_details\n    \"\"\"\n    elo_expected(RA, RB) = 1 / (1 + 10 ^ ((RB - RA) / 400))\n\n    Eg2(μ, μj, ϕj) = 1/(1+exp(-gg2(ϕj)*(μ - μj)))\n    gg2(ϕ) = 1/sqrt(1 + 3*(ϕ^2)/π^2)\n    compute_v(μ, μjs, ϕjs) = 1/sum(gg2.(ϕjs).^2 .* Eg2.(μ, μjs, ϕjs) .* (1 .- Eg2.(μ, μjs, ϕjs)))\n    compute_Δ(μ, μjs, ϕjs, sjs, v) = v * sum(gg2.(ϕjs) .* (sjs .- Eg2.(μ, μjs, ϕjs)))\n    ϕincrease(ϕ, σ) = sqrt(ϕ^2 + σ^2)\n\n    \"\"\"\n        glicko2(μ::Real, ϕ::Real, σ::Real, μjs::Vector{Real}, ϕjs::Vector{Real}, sjs::Vector{Real}; τ=0.05, ϵ=10^-6)\n    \n    # Arguments:\n    * `μ`: Rating of player\n    * `ϕ`: Rating deviation of player\n    * `σ`: Rating volatility\n    * `μjs`: Ratings of oppenents within rating period\n    * `μjs`: Rating deviations within rating period\n    * `sjs`: Game outcomes from the perspective of the \"player\": 1 - won, 0.5 - draw, 0 - lost.\n    * `τ=0.5`: smaller values constrain the change in volatility over time, reasonable range between 0.3 and 1.2\n    * `ϵ=10^-6`: Convergence bound\n\n    Returns tuple `(μ, ϕ, σ)`: glicko2 rating, rating deviation and rating volatility for games in one rating period.\n\n    See: http://www.glicko.net/glicko/glicko2.pdf and \n    Glickman, Mark E., \"Dynamic paired comparison models with stochastic variances\" (2001), \n    Journal of Applied Statistics, 28, 673-689. \n    (http://www.glicko.net/research/dpcmsv.pdf)\n    \"\"\"\n    function glicko2(μ::Real, ϕ::Real, σ::Real, μjs::Vector{R}, ϕjs::Vector{R}, sjs::Vector{S}; τ=0.5, ϵ=10^-6) where {R <: Real, S <: Real}\n        v = compute_v(μ, μjs, ϕjs)\n        Δ = compute_Δ(μ, μjs, ϕjs, sjs, v) \n        a = log(σ^2)\n        f(x) = exp(x)*(Δ^2 - ϕ^2  - v - exp(x)) / (2 * (ϕ^2 + v + exp(x))^2) - (x - a)/τ^2\n        A = a\n        if Δ^2 > ϕ^2 + v \n            B = log(Δ^2 - ϕ^2  - v)\n        else\n            k = 1\n            while (f(a - k*τ) < 0)\n                k += 1\n            end\n            B = a - k*τ\n        end\n        fA = f(A)\n        fB = f(B)\n        while abs(B - A) > ϵ\n            C = A + (A-B) * fA/ (fB-fA)\n            fC = f(C)\n            if fC * fB < 0\n                A = B\n                fA = fB\n            else\n                fA /= 2\n            end\n            B = C\n            fB = fC\n        end\n        σnew = exp(A/2)\n        ϕincreased = sqrt(ϕ^2 + σnew^2)\n        ϕnew = 1/sqrt(1/ϕincreased^2 + 1/v)\n        μnew = μ + ϕnew^2 * sum(gg2.(ϕjs) .* (sjs .- Eg2.(μ, μjs, ϕjs)))\n        μnew, ϕnew, σnew\n    end\n\n    \"\"\"\n        glicko1_to_glicko2(r::real, RD::Real)\n\n    Convert ratings `r` and rating deviations `RD` from glicko1 (Elo-like) scale to glicko 2 scale (μ and ϕ).\n    \"\"\"\n    glicko1_to_glicko2(r::Real, RD::Real) = ((r-1500)/173.7178, RD/173.7178)\n\n    export glicko_rating, glicko_RD, glicko_RD_increase, glicko_c, glicko_expected, elo_rating, elo_expected, glicko2\nend\n", "meta": {"hexsha": "31d476f30fcadb81fe8428db08bfe1d90050bd04", "size": 7442, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SkillRating.jl", "max_stars_repo_name": "altre/SkillRating", "max_stars_repo_head_hexsha": "a22692dbfdafa87dca1878fbe565bc50f216d2bc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SkillRating.jl", "max_issues_repo_name": "altre/SkillRating", "max_issues_repo_head_hexsha": "a22692dbfdafa87dca1878fbe565bc50f216d2bc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SkillRating.jl", "max_forks_repo_name": "altre/SkillRating", "max_forks_repo_head_hexsha": "a22692dbfdafa87dca1878fbe565bc50f216d2bc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.585106383, "max_line_length": 148, "alphanum_fraction": 0.5889545821, "num_tokens": 2618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191259110588, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7765476933928587}}
{"text": "mutable struct Edge\n    rev::Int\n    from::Int\n    to::Int\n    cap::Int\nend\n\nfunction push!(G::Vector{Vector{Edge}}, from, to, cap)\n    fromrev = length(G[from]) + 1\n    torev = length(G[to]) + 1\n    Base.push!(G[from], Edge(torev, from, to, cap))\n    Base.push!(G[to], Edge(fromrev, to, from, 0))\nend\n\nfunction run_flow!(G::Vector{Vector{Edge}}, e::Edge, f)\n    e.cap -= f\n    G[e.to][e.rev].cap += f\n    return G\nend\n\nfunction fodfs(G, v, t, f, seens)\n    v == t && return f\n\n    seens[v] = true\n    for e ∈ G[v]\n        if seens[e.to] || e.cap == 0\n            # Skip\n        else\n            flow = fodfs(G, e.to, t, min(f, e.cap), seens)\n            if flow == 0\n                # Skip\n            else\n                run_flow!(G, e, flow)\n                return flow\n            end\n        end\n    end\n\n    return 0\nend\n\nfunction FordFulkerson(G, s, t)\n    INF = 10^9\n    res = 0\n\n    while true\n        flow = fodfs(G, s, t, INF, falses(length(G)))\n        if flow == 0\n            return res\n        else\n            res += flow\n        end\n    end\n\n    return 0\nend\n\n\nfunction main()\n    N = parse(Int, readline())\n    as = parse.(Int, split(readline()))\n    INF = 10^9\n\n    offset = 0\n    G = [Vector{Edge}() for _ = 1:N+2]\n    for (i, a) = enumerate(as)\n        if a ≥ 0\n            push!(G, N+1, i, 0)\n            push!(G, i, N+2, a)\n            offset += a\n        else\n            push!(G, N+1, i, -a)\n            push!(G, i, N+2, 0)\n        end\n    end\n\n    for i = 1:N\n        for j = i+1:N\n            if j % i == 0\n                push!(G, i, j, INF)\n            end\n        end\n    end\n\n    res = FordFulkerson(G, N+1, N+2)\n    println(offset - res)\nend\n\nmain()", "meta": {"hexsha": "dfe2055de6d4adba4d40d750bc126791619367d5", "size": 1682, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/chapter16/nicetak/arc085_c.jl", "max_stars_repo_name": "tokuma09/algorithm_problems", "max_stars_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-07T15:46:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T15:46:58.000Z", "max_issues_repo_path": "problems/chapter16/nicetak/arc085_c.jl", "max_issues_repo_name": "tokuma09/algorithm_problems", "max_issues_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-06-05T14:16:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-10T07:08:28.000Z", "max_forks_repo_path": "problems/chapter16/nicetak/arc085_c.jl", "max_forks_repo_name": "tokuma09/algorithm_problems", "max_forks_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8988764045, "max_line_length": 58, "alphanum_fraction": 0.4464922711, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305638, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7765321645396357}}
{"text": "doc\"\"\"\n    Beta(α,β)\n\nThe *Beta distribution* has probability density function\n\n$f(x; \\alpha, \\beta) = \\frac{1}{B(\\alpha, \\beta)}\n x^{\\alpha - 1} (1 - x)^{\\beta - 1}, \\quad x \\in [0, 1]$\n\nThe Beta distribution is related to the [`Gamma`](:func:`Gamma`) distribution via the\nproperty that if $X \\sim \\operatorname{Gamma}(\\alpha)$ and $Y \\sim \\operatorname{Gamma}\n(\\beta)$ independently, then $X / (X + Y) \\sim \\operatorname{Beta}(\\alpha, \\beta)$.\n\n\n```julia\nBeta()        # equivalent to Beta(1, 1)\nBeta(a)       # equivalent to Beta(a, a)\nBeta(a, b)    # Beta distribution with shape parameters a and b\n\nparams(d)     # Get the parameters, i.e. (a, b)\n```\n\nExternal links\n\n* [Beta distribution on Wikipedia](http://en.wikipedia.org/wiki/Beta_distribution)\n\n\"\"\"\n\nimmutable Beta{T<:Real} <: ContinuousUnivariateDistribution\n    α::T\n    β::T\n\n    function Beta(α::T, β::T)\n        @check_args(Beta, α > zero(α) && β > zero(β))\n        new(α, β)\n    end\nend\n\nBeta{T<:Real}(α::T, β::T) = Beta{T}(α, β)\nBeta(α::Real, β::Real) = Beta(promote(α, β)...)\nBeta(α::Integer, β::Integer) = Beta(Float64(α), Float64(β))\nBeta(α::Real) = Beta(α, α)\nBeta() = Beta(1, 1)\n\n@distr_support Beta 0.0 1.0\n\n#### Conversions\nfunction convert{T<:Real}(::Type{Beta{T}}, α::Real, β::Real)\n    Beta(T(α), T(β))\nend\nfunction convert{T <: Real, S <: Real}(::Type{Beta{T}}, d::Beta{S})\n    Beta(T(d.α), T(d.β))\nend\n\n#### Parameters\n\nparams(d::Beta) = (d.α, d.β)\n@inline partype{T<:Real}(d::Beta{T}) = T\n\n\n#### Statistics\n\nmean(d::Beta) = ((α, β) = params(d); α / (α + β))\n\nfunction mode(d::Beta)\n    (α, β) = params(d)\n    (α > 1 && β > 1) || error(\"mode is defined only when α > 1 and β > 1.\")\n    return (α - 1) / (α + β - 2)\nend\n\nmodes(d::Beta) = [mode(d)]\n\nfunction var(d::Beta)\n    (α, β) = params(d)\n    s = α + β\n    return (α * β) / (abs2(s) * (s + 1))\nend\n\nmeanlogx(d::Beta) = ((α, β) = params(d); digamma(α) - digamma(α + β))\n\nvarlogx(d::Beta) = ((α, β) = params(d); trigamma(α) - trigamma(α + β))\nstdlogx(d::Beta) = sqrt(varlogx(d))\n\nfunction skewness(d::Beta)\n    (α, β) = params(d)\n    if α == β\n        return zero(α)\n    else\n        s = α + β\n        (2(β - α) * sqrt(s + 1)) / ((s + 2) * sqrt(α * β))\n    end\nend\n\nfunction kurtosis(d::Beta)\n    α, β = params(d)\n    s = α + β\n    p = α * β\n    6(abs2(α - β) * (s + 1) - p * (s + 2)) / (p * (s + 2) * (s + 3))\nend\n\nfunction entropy(d::Beta)\n    α, β = params(d)\n    s = α + β\n    lbeta(α, β) - (α - 1) * digamma(α) - (β - 1) * digamma(β) +\n        (s - 2) * digamma(s)\nend\n\n\n#### Evaluation\n\n@_delegate_statsfuns Beta beta α β\n\ngradlogpdf{T<:Real}(d::Beta{T}, x::Real) =\n    ((α, β) = params(d); 0 <= x <= 1 ? (α - 1) / x - (β - 1) / (1 - x) : zero(T))\n\n\n#### Sampling\n\nrand(d::Beta) = StatsFuns.RFunctions.betarand(d.α, d.β)\n\n\n#### Fit model\n\n# TODO: add MLE method (should be similar to Dirichlet)\n\n# This is a moment-matching method (not MLE)\n#\nfunction fit{T<:Real}(::Type{Beta}, x::AbstractArray{T})\n    x_bar = mean(x)\n    v_bar = varm(x, x_bar)\n    α = x_bar * (((x_bar * (1 - x_bar)) / v_bar) - 1)\n    β = (1 - x_bar) * (((x_bar * (1 - x_bar)) / v_bar) - 1)\n    Beta(α, β)\nend\n", "meta": {"hexsha": "dcb1ba10800a388dfdf10acd3f3183ef5680bd13", "size": 3119, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/beta.jl", "max_stars_repo_name": "JuliaPackageMirrors/Distributions.jl", "max_stars_repo_head_hexsha": "091cad865281c92746dc455cc50f4b2a311d3dd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/beta.jl", "max_issues_repo_name": "JuliaPackageMirrors/Distributions.jl", "max_issues_repo_head_hexsha": "091cad865281c92746dc455cc50f4b2a311d3dd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/beta.jl", "max_forks_repo_name": "JuliaPackageMirrors/Distributions.jl", "max_forks_repo_head_hexsha": "091cad865281c92746dc455cc50f4b2a311d3dd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.276119403, "max_line_length": 87, "alphanum_fraction": 0.5476114139, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037782, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7765321471274675}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.10\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 8491344a-7c39-11eb-327e-df48b337d147\nbegin\n\timport Pkg\n\t\n\tPkg.add(\"Plots\")\n\tPkg.add(\"PlutoUI\")\n\tPkg.add(\"Measures\")\n\t\n\tusing Plots\n\tusing PlutoUI\n\tusing Measures\nend\n\n# ╔═╡ 0904e59a-7c3b-11eb-307d-6fd2049ea8bc\nmd\"To use Eulers Method on an ODE with parameters you can either define global variables and use them within the function or to increase runtime pass all the parameters in a variable P to the vector field.\"\n\n# ╔═╡ 8f2743fe-7c39-11eb-27d6-d527b21f46b8\nbegin\n\tfunction euler(f,t₀,tₑ,Δt,x₀,P)\n\t\tT = t₀:Δt:tₑ\n\t\tF = Vector{typeof(x₀)}(undef,length(T))\n\n\t\tF[1] = x₀\n\t\t\n\t\tfor (n,tₙ) ∈ enumerate(@view T[2:end])\n\t\t\tF[n+1] = F[n] .+ f(tₙ,F[n],P) .* Δt\n\t\tend\n\t\treturn F\n\tend\n\t\n\t#reshape result for plotting\n\treshape_result(F) = [[f[i] for f ∈ F] for i ∈ 1:length(F[1])]\nend;\n\n# ╔═╡ 925558e8-7cc7-11eb-37a8-c98fb8a33355\nmd\"\"\"\n---\n### One Locus, Two Alleles\n\nWe describe a population where every individual is characterized by one locus only. There are two possible alleles 0 and 1, where 0 is the wildtype and 1 the mutated allele. Individuals who carry the mutated allel on both copies of the allele are thought to have a severe diseas, causing them to be excluded from the birth process. Individuals give birth and die at constant rates $b, d$. The carrying capacity $K_{t}$ is time dependent and jumps at a certain point in time. The competition preassure between individuals is uniform $(b-d)/K_{t}$. Mutations appear at every birth at a constant rate $\\mu$ from 0 to 1 only. The deterministic system can be described by the following system of non linear first order ODEs:\n\n${\n\\frac{dX_{00}}{dt} = b \n\t\\left(\n\t\t(1-\\mu) \\frac{(X_{00}+\\frac{1}{2}X_{01})^2}{X_{00}+X_{01}} \n\t\\right)\n\t- (d + c\\Sigma)X_{00}\n\t\t\\phantom{\n\t\t\t+ \\mu  \\frac{(X_{00}+\\frac{1}{2}X_{01})X_{01}}{X_{00}+X_{01}} \n\t\t\t+ \\mu^2  \\frac{(X_{00}+\\frac{1}{2}X_{01})^2}{X_{00}+X_{01}} \n\t\t\t}\n\t\\phantom{\\Bigg(}\n\n}$ \n\n${\n\\frac{dX_{01}}{dt} = b \n\t\\left(\n\t\t(1-\\mu) \\frac{(X_{00}+\\frac{1}{2}X_{01})X_{01}}{X_{00}+X_{01}} \n\t\t+ \\mu  \\frac{(X_{00}+\\frac{1}{2}X_{01})^2}{X_{00}+X_{01}} \n\t\\right)\n\t- (d + c\\Sigma)X_{01} \n\t\\phantom{\n\t\t\t+ \\mu^2  \\frac{(X_{00}+\\frac{1}{2}X_{01})^2}{X_{00}+X_{01}} \n\t\t}\n}$ \n\n${\n\\frac{dX_{11}}{dt} = b \n\t\\left(\n\t\t(1-\\mu) \\frac{\\frac{1}{4}X_{01}^2}{X_{00}+X_{01}} \n\t\t+ \\mu  \\frac{(X_{00}+\\frac{1}{2}X_{01})X_{01}}{X_{00}+X_{01}} \n\t\t+ \\mu^2  \\frac{(X_{00}+\\frac{1}{2}X_{01})^2}{X_{00}+X_{01}} \n\t\\right)\n\t- (d + c\\Sigma)X_{11} \n}$ \n\nwhere $\\Sigma = X_{00} + X_{01} + X_{11}$ is the total population size.\n\"\"\"\n\n# ╔═╡ 62311b66-7c3b-11eb-335c-c53b566fcb9f\nbegin\t\n\tfunction OneLocus(t,X,P)\n\t\tX₀₀, X₀₁, X₁₁ = (x for x ∈ X)\n\t\tb, d, K, μ = (p for p ∈ P)\n\t\t\n\t\tΣ = sum(X)\n\t\tM = Σ - X₁₁\n\t\tD = d+((b-d)/K(t))*Σ\n\t\t\n\t\treturn [\n\t\t\t\t(b * (1-μ)*(X₀₀+0.5*X₀₁)^2/M - D*X₀₀),\n\t\t\t\t(b * ((1-μ)*(X₀₀+0.5*X₀₁)*X₀₁/M + μ*(X₀₀+0.5*X₀₁)^2/M) - D*X₀₁),\n\t\t\t\t(b * ((1-μ)*0.25*(X₀₁)^2/M + μ*(X₀₀+0.5*X₀₁)*X₀₁/M + μ^2*(X₀₀+0.5*X₀₁)^2/M) - D*X₁₁)\n\t\t\t\t]\n\t\tend\nend\n\n# ╔═╡ 348cb7ba-7c40-11eb-1a80-4768b0c6b4d4\nmd\"\"\"\nbirth rate: $(@bind b Slider(0.0:0.1:1.0, show_value=true, default=1.0)) |\ndeath rate: $(@bind d Slider(0.0:0.1:1.0, show_value=true, default=0.9)) |\n\ninitial population: $(@bind Kstart NumberField(1:10^7, default=500.0)) |\ncarrying capacity: $(@bind Kend NumberField(1:10^7, default=10_000.0)) |\nburn in time: $(@bind tburn Slider(0:300,show_value=true,default=100))\n\nmutation rate: $(@bind μ NumberField(0.0:0.0001:0.2, default=0.001))\n\"\"\"\n\n# ╔═╡ a19430e8-7c3d-11eb-0790-4b883ac9cd39\nbegin\n\tt_start = 0\n\tt_end = 500\n\tstep = 0.01\n\n\tOL_0 = [Kstart,0.0,0.0]\n\t\n\tT = t_start:step:t_end\n\tK(t) = t <= tburn ? Kstart : Kend ;\n\t\n\tF = euler(OneLocus,t_start,t_end,step,OL_0,[b,d,K,μ])\n\trF = reshape_result(F)\nend;\n\n# ╔═╡ d728c114-7c40-11eb-1fcb-a1ecbb31ae54\nlet\n\tp = plot(framestyle=:zerolines)\n\t\n\tplot!(T,rF,label=[\"(0,0)\" \"(0,1)\" \"(1,1)\"])\n\t\n\tp\nend\t\n\n# ╔═╡ 20a4f4dc-7c41-11eb-26a8-21e34fcfd8e4\nbegin\n\tmutation_load(X) = (X[2] + 2*X[3])/sum(X)\n\till_individual(X) = X[3]/sum(X)\nend;\n\n# ╔═╡ 619eab70-7c41-11eb-1fc0-fb3ec4e64220\nlet\n\tp_left = plot(framestyle=:zerolines,legend=:bottomleft,rightmargin=12mm,size=(680,400))\n\t\n\tplot!(p_left,T,mutation_load.(F),label=\"mutation load\",color=:red)\n\t\n\tp_right = twinx()\n\tplot!(p_right,framestyle=:zerolines,legend=:bottomright,grid=false)\n\tplot!(p_right,T,ill_individual.(F),label=\"ill_individual\",color=:orange)\n\t\n\tvline!(p_right,[T[end]],color=:black,label=\"\")\n\t\nend\n\n# ╔═╡ Cell order:\n# ╟─8491344a-7c39-11eb-327e-df48b337d147\n# ╟─0904e59a-7c3b-11eb-307d-6fd2049ea8bc\n# ╠═8f2743fe-7c39-11eb-27d6-d527b21f46b8\n# ╟─925558e8-7cc7-11eb-37a8-c98fb8a33355\n# ╠═62311b66-7c3b-11eb-335c-c53b566fcb9f\n# ╟─348cb7ba-7c40-11eb-1a80-4768b0c6b4d4\n# ╟─d728c114-7c40-11eb-1fcb-a1ecbb31ae54\n# ╟─619eab70-7c41-11eb-1fc0-fb3ec4e64220\n# ╠═a19430e8-7c3d-11eb-0790-4b883ac9cd39\n# ╟─20a4f4dc-7c41-11eb-26a8-21e34fcfd8e4\n", "meta": {"hexsha": "526461f48c3db04a504d7dd525620efa12537293", "size": 5249, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "OneLocusTwoAlleles.jl", "max_stars_repo_name": "roccminton/PlutoNotebooks", "max_stars_repo_head_hexsha": "c32dd451fb19e99ef184c463cb49bb1385fe4ffa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "OneLocusTwoAlleles.jl", "max_issues_repo_name": "roccminton/PlutoNotebooks", "max_issues_repo_head_hexsha": "c32dd451fb19e99ef184c463cb49bb1385fe4ffa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OneLocusTwoAlleles.jl", "max_forks_repo_name": "roccminton/PlutoNotebooks", "max_forks_repo_head_hexsha": "c32dd451fb19e99ef184c463cb49bb1385fe4ffa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0, "max_line_length": 719, "alphanum_fraction": 0.6502190894, "num_tokens": 2315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7765292916487968}}
{"text": "\"\"\"\n    block(i, j)\n\nReturn the linear index of the `[i,j]` position (\"block\") in the row-major packed lower triangle.\n\nUse the row-major ordering in this case because the result depends only on `i`\nand `j`, not on the overall size of the array.\n\nWhen `i == j` the value is the same as `kp1choose2(i)`.\n\"\"\"\nfunction block(i::Integer, j::Integer)\n    0 < j ≤ i || throw(ArgumentError(\"[i,j] = [$i,$j] must be in the lower triangle\"))\n    return kchoose2(i) + j\nend\n\n\"\"\"\n    kchoose2(k)\n\nThe binomial coefficient `k` choose `2` which is the number of elements\nin the packed form of the strict lower triangle of a matrix.\n\"\"\"\nfunction kchoose2(k)      # will be inlined\n    return (k * (k - 1)) >> 1\nend\n\n\"\"\"\n    kp1choose2(k)\n\nThe binomial coefficient `k+1` choose `2` which is the number of elements\nin the packed form of the lower triangle of a matrix.\n\"\"\"\nfunction kp1choose2(k)\n    return (k * (k + 1)) >> 1\nend\n\n\"\"\"\n    ltriindprs\n\nA row-major order `Vector{NTuple{2,Int}}` of indices in the strict lower triangle.\n\"\"\"\nconst ltriindprs = NTuple{2,Int}[]\n\nfunction checkindprsk(k::Integer)\n    kc2 = kchoose2(k)\n    if length(ltriindprs) < kc2\n        sizehint!(empty!(ltriindprs), kc2)\n        for i in 1:k, j in 1:(i - 1)\n            push!(ltriindprs, (i, j))\n        end\n    end\n    return ltriindprs\nend\n", "meta": {"hexsha": "f5cca625677bfc38cd70884ca21fa2cc279684f3", "size": 1310, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/blocks.jl", "max_stars_repo_name": "joscani/MixedModels.jl", "max_stars_repo_head_hexsha": "fd79f396a729bf22f237008430a92e7f4aaf0431", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 158, "max_stars_repo_stars_event_min_datetime": "2019-11-21T21:46:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T04:54:32.000Z", "max_issues_repo_path": "src/blocks.jl", "max_issues_repo_name": "joscani/MixedModels.jl", "max_issues_repo_head_hexsha": "fd79f396a729bf22f237008430a92e7f4aaf0431", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 365, "max_issues_repo_issues_event_min_datetime": "2019-11-22T05:40:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:14:53.000Z", "max_forks_repo_path": "src/blocks.jl", "max_forks_repo_name": "joscani/MixedModels.jl", "max_forks_repo_head_hexsha": "fd79f396a729bf22f237008430a92e7f4aaf0431", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2015-04-22T12:57:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-16T16:40:13.000Z", "avg_line_length": 24.7169811321, "max_line_length": 97, "alphanum_fraction": 0.6450381679, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.7765242129348299}}
{"text": "# http://mathworld.wolfram.com/SphericalSpiral.html\n\n```julia\nusing CatmullRom, Plots\n\nx(t) = cos(t) / sqrt(1 + t*t)\ny(t) = sin(t) / sqrt(1 + t*t)\nz(t) = - t/sqrt(1+t*t)\n                        \nts = collect(range(-4pi,4pi, length=24));\nxs = x.(ts); ys = y.(ts); zs = z.(ts);\n\nczs, cys, cxs = catmullrom(collect(zip(zs,ys,xs)), 36);\n\nplot(zs, ys, xs, linecolor=:darkred, linewidth=2, legend=nothing, size=(600,600))\nplot!(czs, cys, cxs, linecolor=:navy, linewidth=2, legend=nothing, size=(600,600))\n\n```\n", "meta": {"hexsha": "845bf19bc0cf9698e8b4eac20a4b3d73f3ae8c15", "size": 504, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/sphericalspiral.jl", "max_stars_repo_name": "JeffreySarnoff/-CentripetalCatmullRom.jl", "max_stars_repo_head_hexsha": "49e6536c184dfc4200b980f89aa55bc5cf357b82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-07-14T17:13:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T20:43:13.000Z", "max_issues_repo_path": "examples/sphericalspiral.jl", "max_issues_repo_name": "JeffreySarnoff/-CentripetalCatmullRom.jl", "max_issues_repo_head_hexsha": "49e6536c184dfc4200b980f89aa55bc5cf357b82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-08-09T20:29:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T14:45:14.000Z", "max_forks_repo_path": "examples/sphericalspiral.jl", "max_forks_repo_name": "JeffreySarnoff/-CentripetalCatmullRom.jl", "max_forks_repo_head_hexsha": "49e6536c184dfc4200b980f89aa55bc5cf357b82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:26:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-25T12:17:47.000Z", "avg_line_length": 26.5263157895, "max_line_length": 82, "alphanum_fraction": 0.5972222222, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799420543365, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7764521354180901}}
{"text": "\"\"\"\r\n    regpower(X,Y,m)\r\n\r\nadalah fungsi untuk mencari persamaan pangkat `y=Ax^m` dari variabel dependen `Y` dan\r\nindependen `X` dengan pangkat `m`.\r\n\r\n# Example\r\n```jldoctest\r\njulia> tk = [0.2,0.4,0.6,0.8,1.0];\r\n\r\njulia> dk = [0.1960,0.7850,1.7665,3.1405,4.9075];\r\n\r\njulia> A = regpower(tk,dk,2)\r\n4.907303370786516\r\n```\r\nreturn nilai koefisien `A`.\r\n\"\"\"\r\nfunction regpower(X,Y,m)\r\n  sumxy = (X.^m)'*Y\r\n  sumx2 = (X.^m)'*(X.^m)\r\n  A = sumxy/sumx2\r\nend\r\n", "meta": {"hexsha": "a567a1763a2d8a14af797ce4dd004975721a9b61", "size": 454, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/regpower.jl", "max_stars_repo_name": "mkhoirun-najiboi/metnum.jl", "max_stars_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/regpower.jl", "max_issues_repo_name": "mkhoirun-najiboi/metnum.jl", "max_issues_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/regpower.jl", "max_forks_repo_name": "mkhoirun-najiboi/metnum.jl", "max_forks_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7391304348, "max_line_length": 86, "alphanum_fraction": 0.6057268722, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7764254421616915}}
{"text": "using Qaintessent\nusing LinearAlgebra: I\nusing SparseArrays: sparse\nusing Memoize\n\n# Pauli X and Y matrices\nX = [0 1; 1 0]\nY = [0 -im; im 0]\n\n# Utility function for a XY mixer\n# Implements X_a X_{a+1} + Y_a Y_{a+1}, or more generally (⊗_{i ∈ xy_indices} X_i) + (⊗_{i ∈ xy_indices} Y_i)\nfunction XY_sum(xy_indices::Vector{Int64}, d::Int64)::Matrix{ComplexF64}\n    # passing generator into kron via varargs syntax\n    return kron((i ∈ xy_indices ? X : I(2) for i ∈ 1:d)...\n        ) + kron((i ∈ xy_indices ? Y : I(2) for i ∈ 1:d)...)\nend\n\n\"\"\"\n    r-nearby values single-qudit mixer gate, which acts on a single qudit (but implemented \n    here not for qudits, but the one-hot encoding)\n\n``U_{r\\\\text{-NV}}(\\\\beta) = e^{-i \\\\beta H_{r\\\\text{-NV}}}``\n``H_{r\\\\text{-NV}} = \\\\sum_{i=1}^r \\\\left(\\\\breve{X}^i + \\\\left(\\\\breve{X}^\\\\dagger\\\\right)^i\\\\right)``\n\nReference:\\n\n    Stuart Hadfield, Zhihui Wang, Bryan O'Gorman, Eleanor G. Rieffel,Davide Venturelli and Rupak Biswas\\n\n    From the Quantum Approximate Optimization Algorithm to a Quantum Alternating Operator Ansatz\\n\n    Algorithms 12.2 (2019), p.34\n\"\"\"\nstruct RNearbyValuesMixerGate <: AbstractGate\n    # use a reference type (array with 1 entry) for compatibility with Flux\n    β::Vector{Float64}\n    r::Integer # this is the r in r-Nearby-values\n    d::Integer # d (= κ) = number of colors\n\n    function RNearbyValuesMixerGate(β::Float64, r::Integer, d::Integer)\n        (r > 0 && d > 0) || throw(ArgumentError(\"Parameters r and d must be positive integers.\"))\n        (r <= d-1) || throw(ArgumentError(\"Parameter d must be between 1 and d-1.\"))\n        new([β], r, d)\n    end\nend\n\n# Compute the r-NV mixer Hamiltonian\n@memoize function r_nearby_values_hamiltonian_onehot(g::RNearbyValuesMixerGate)\n    H_rNV = sum(XY_sum([a, ((a + j - 1) % g.d) + 1], g.d) \n        for a in 1:g.d for j in 1:g.r)\n\n    return H_rNV\nend\n\n# Compute the r-NV mixer gate matrix: Implementation of Eq. (6)\nfunction Qaintessent.matrix(g::RNearbyValuesMixerGate)\n    H_rNV = r_nearby_values_hamiltonian_onehot(g)\n    U_rNV = exp(-im * g.β[] * H_rNV)\n\n    return U_rNV\nend\n\n# Adjoint of r-NV = r-NV gate with negated β parameter\nQaintessent.adjoint(g::RNearbyValuesMixerGate) = RNearbyValuesMixerGate(-g.β[], g.r, g.d)\n\nQaintessent.sparse_matrix(g::RNearbyValuesMixerGate) = sparse(matrix(g))\n\n# Number of wires (= g.d since we use the one-hot encoding canonically)\nQaintessent.num_wires(g::RNearbyValuesMixerGate)::Int = g.d\n\n\"\"\"\n    Parity single-qudit ring mixer gate, which acts on a single qudit (but implemented \n    here not for qudits, but the one-hot encoding)\n\n``U_{\\\\text{parity}}(\\\\beta) = U_{\\\\text{last}}(\\\\beta) U_{\\\\text{even}}(\\\\beta) U_{\\\\text{odd}}(\\\\beta)``\n``U_{\\\\text{odd}}(\\\\beta) = \\\\prod_{a~\\\\text{odd}, a \\\\neq d} e^{-i \\\\beta (X_a X_{a+1} + Y_a Y_{a+1})}``\n``U_{\\\\text{even}}(\\\\beta) = \\\\prod_{a~\\\\text{even}} e^{-i \\\\beta (X_a X_{a+1} + Y_a Y_{a+1})}``\n``U_{\\\\text{last}}(\\\\beta) = e^{-i \\\\beta (X_d X_1 + Y_d Y_1)} ~\\\\text{if}~ d ~\\\\text{is odd,}~ I ~\\\\text{otherwise.}``\n\nThe formulas require some interpretation. Assumptions for this implementation are:\n- the indices a start at 1 (not at zero like elsewhere in the paper)\n- X_{a+1} and Y_{a+1} actually means X_1 and Y_1 if a = d\n\nReference:\\n\n    Stuart Hadfield, Zhihui Wang, Bryan O'Gorman, Eleanor G. Rieffel, Davide Venturelli and Rupak Biswas\\n\n    From the Quantum Approximate Optimization Algorithm to a Quantum Alternating Operator Ansatz\\n\n    Algorithms 12.2 (2019), equations (7) - (10), p. 11\n\"\"\"\nstruct ParityRingMixerGate <: AbstractGate\n    β::Vector{Float64}\n    d::Integer # d (= κ) = number of colors\n    is_adjoint::Bool # if yes, the order in the product is reversed\n\n    function ParityRingMixerGate(β::Float64, d::Integer; is_adjoint::Bool = false)\n        d > 0 || throw(ArgumentError(\"Parameter d must be a positive integer.\"))\n        new([β], d, is_adjoint)\n    end\nend\n\n# Compute the parity ring mixer gate matrix: Implements Eq. (8)\nfunction Qaintessent.matrix(g::ParityRingMixerGate)\n    # assumption: by a ≠ n, the paper actually means a ≠ d.\n    # assumption: by X_a for a = d+1, the paper means X_1.\n    U_odd = prod([exp(-im * g.β[] * XY_sum([a, a+1], g.d)) for a ∈ 1:2:(g.d - 1)], init=I)\n    U_even = prod([exp(-im * g.β[] * XY_sum([a, a < g.d ? (a+1) : 1], g.d)) for a ∈ 2:2:g.d], init=I)\n\n    # Implements Eq. (9)\n    U_last =  isodd(g.d) ? exp(-im * g.β[] * XY_sum([g.d, 1], g.d)) : I\n\n    # Implements Eq. (7) (U_parity)\n    if !g.is_adjoint\n        return U_last * U_even * U_odd\n    else\n        return U_odd * U_even * U_last\n    end\nend\n\n# Adjoint of parity ring mixer -> negated β parameter, reversed order in the product\nQaintessent.adjoint(g::ParityRingMixerGate) = ParityRingMixerGate(-g.β[], g.d, is_adjoint = !g.is_adjoint)\n\nQaintessent.sparse_matrix(g::ParityRingMixerGate) = sparse(matrix(g))\n\n# Number of wires (= g.d since we use the one-hot encoding canonically)\nQaintessent.num_wires(g::ParityRingMixerGate)::Int = g.d\n\n\"\"\"\n    Partition single-qudit mixer gate (implemented not for qudits, but the one-hot encoding)\n\n``U_{\\\\mathcal{P}-r-\\\\text{NV}}(\\\\beta) = U_{P_p-\\\\text{XY}}(\\\\beta) \\\\dots U_{P_1-\\\\text{XY}}(\\\\beta)``\n``U_{P-\\\\text{XY}}(\\\\beta) = \\\\prod_{\\\\{a, b\\\\} \\\\in P} e^{-i \\\\beta (\\\\ket{a}\\\\bra{b} + \\\\ket{b}\\\\bra{a})}``\n\nNote: the time evolution term is effectively implemented with an additional factor of two in the exponent:\n``e^{-i \\\\beta 2 (\\\\ket{a}\\\\bra{b} + \\\\ket{b}\\\\bra{a})}``\nto be consistent with the XY gates used for the other mixers.\n\nReference:\\n\n    Stuart Hadfield, Zhihui Wang, Bryan O'Gorman, Eleanor G. Rieffel, Davide Venturelli and Rupak Biswas\\n\n    From the Quantum Approximate Optimization Algorithm to a Quantum Alternating Operator Ansatz\\n\n    Algorithms 12.2 (2019), equations (11) - (12), p. 12\n\"\"\"\nstruct PartitionMixerGate <: AbstractGate\n    β::Vector{Float64}\n    d::Int64\n    partition::Vector{Vector{Tuple{Int, Int}}} # the Tuple stops Flux.@functor from misinterpreting these as params\n\n    function PartitionMixerGate(β::Float64, d::Int64, partition::Vector{Vector{Tuple{Int, Int}}})\n        d > 0 || throw(ArgumentError(\"Parameter d must be a positive integer.\"))\n\n        # check that no duplicate indices occur in a part (s.t. the XY mixers within one part commute)\n        for partition_part ∈ partition\n            part_indices = union(reduce(vcat, collect.(partition_part)))\n            part_indices ⊆ 1:d || throw(\"Indices in partition must be between 1 and d.\")\n            length(part_indices) == 2 * length(partition_part) ||\n                throw(\"No index must occur more than once within each partition part in `partition`.\")\n        end\n\n        new([β], d, partition)\n    end\nend\n\n# Compute the partition mixer Hamiltonians\n@memoize function partition_mixer_hamiltonians(g::PartitionMixerGate)::Vector{Matrix{ComplexF64}}\n    hamiltonians = Matrix{ComplexF64}[]\n\n    # Implements parts of Eqs. (11), (12)\n    # iterate through partition\n    for partition_part ∈ g.partition\n        # we can represent each part by one Hamiltonian, because the individual XY gates commute\n        # and therefore exp(-iβ ∑H_{a,b}) = ∏exp(-iβ H_{a,b})\n        H_part = sum(XY_sum([a, b], g.d) for (a, b) ∈ partition_part)\n        push!(hamiltonians, H_part)\n    end\n\n    return hamiltonians\nend\n\n# Compute the partition mixer gate matrix, but allowing to pass a different β\n# than is stored in the gate struct (useful for backward pass)\nfunction partition_mixer_gate_matrix(g::PartitionMixerGate, β::Float64)\n    hamiltonians = partition_mixer_hamiltonians(g)\n\n    # Implements parts of Eqs. (11), (12)\n    # reverse terms in product to have matrix application from right to left\n    Us = exp.(-im * β * hamiltonians)\n    return prod(reverse(Us))\nend\n\nQaintessent.matrix(g::PartitionMixerGate) = partition_mixer_gate_matrix(g, g.β[])\n\n# Adjoint of partition ring mixer -> negated β parameter, reversed order in the product\nQaintessent.adjoint(g::PartitionMixerGate) = PartitionMixerGate(-g.β[], g.d, reverse(g.partition))\n\nQaintessent.sparse_matrix(g::PartitionMixerGate) = sparse(matrix(g))\n\n# Number of wires (= g.d since we use the one-hot encoding canonically)\nQaintessent.num_wires(g::PartitionMixerGate)::Int = g.d\n", "meta": {"hexsha": "77d32409d61180b31e19aea5723c329f8191651d", "size": 8237, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/qaoa/mixer_gates.jl", "max_stars_repo_name": "oguzcankirmemis/Qaintessent.jl", "max_stars_repo_head_hexsha": "6261dc5d8a9a7ea7d406ea39cac950747583f414", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-05-25T11:43:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:34:12.000Z", "max_issues_repo_path": "src/qaoa/mixer_gates.jl", "max_issues_repo_name": "oguzcankirmemis/Qaintessent.jl", "max_issues_repo_head_hexsha": "6261dc5d8a9a7ea7d406ea39cac950747583f414", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 54, "max_issues_repo_issues_event_min_datetime": "2020-04-09T17:15:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T12:46:52.000Z", "max_forks_repo_path": "src/qaoa/mixer_gates.jl", "max_forks_repo_name": "oguzcankirmemis/Qaintessent.jl", "max_forks_repo_head_hexsha": "6261dc5d8a9a7ea7d406ea39cac950747583f414", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-12-16T13:25:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T15:49:00.000Z", "avg_line_length": 42.6787564767, "max_line_length": 119, "alphanum_fraction": 0.673546194, "num_tokens": 2608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7764254396138305}}
{"text": "#===============================================================================\n\nLet p_n be the nth prime: 2, 3, 5, 7, 11, ..., and let r_n be the remainder when\n(p_n−1)^n + (p_n+1)^n is divided by p_n^2.\n\nFor example, when n = 3, p3 = 5, and 43 + 63 = 280 ≡ 5 mod 25.\n\nThe least value of n for which the remainder first exceeds 10^9 is 7037.\n\nFind the least value of n for which the remainder first exceeds 10^10.\n\n--------------------------------------------------------------------------------\n\nIt comes:\n    r_n = 2 for n even\n    r_n = 2 n p_n % p_n^2 = 2 n p_n as p_n > n\n\n===============================================================================#\n\ninclude(\"Euler.jl\")\n\nit = Euler.Primes.iter(Int)\n\nst=start(it)\nn=0\n\nlimit1 = true\n\nwhile true\n    (p, st) = next(it, st)\n    n += 1\n    # n is odd\n\n    if limit1 && 2*n*p > 1_000_000_000\n        limit1 = false\n        println(\"10^9: n=$(n), p=$(p), r=$(2*p*n)\")\n    end\n\n    if 2*n*p > 10_000_000_000\n        println(\"10^10: n=$(n), p=$(p), r=$(2*p*n)\")\n        return\n    end\n\n    # skep n even\n    (_, st) = next(it, st)\n    n += 1\nend\n", "meta": {"hexsha": "fb2d57169ad566936a1eaad8ca6d911f6695cc67", "size": 1100, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0123.jl", "max_stars_repo_name": "dpieroux/euler", "max_stars_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "0123.jl", "max_issues_repo_name": "dpieroux/euler", "max_issues_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0123.jl", "max_forks_repo_name": "dpieroux/euler", "max_forks_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9166666667, "max_line_length": 80, "alphanum_fraction": 0.4345454545, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693688269985, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7764254367758815}}
{"text": "@doc raw\"\"\"\n    BasicStructural(y::Vector{Fl}, s::Int) where Fl\n\nThe basic structural state-space model consists of a trend (level + slope) and a seasonal\ncomponent. It is defined by:\n```math\n\\begin{gather*}\n    \\begin{aligned}\n        y_{t} &=  \\mu_{t} + \\gamma_{t} + \\varepsilon_{t} \\quad &\\varepsilon_{t} \\sim \\mathcal{N}(0, \\sigma^2_{\\varepsilon})\\\\\n        \\mu_{t+1} &= \\mu_{t} + \\nu_{t} + \\xi_{t} \\quad &\\xi_{t} \\sim \\mathcal{N}(0, \\sigma^2_{\\xi})\\\\\n        \\nu_{t+1} &= \\nu_{t} + \\zeta_{t} \\quad &\\zeta_{t} \\sim \\mathcal{N}(0, \\sigma^2_{\\zeta})\\\\\n        \\gamma_{t+1} &= -\\sum_{j=1}^{s-1} \\gamma_{t+1-j} + \\omega_{t} \\quad & \\omega_{t} \\sim \\mathcal{N}(0, \\sigma^2_{\\omega})\\\\\n    \\end{aligned}\n\\end{gather*}\n```\n\n# Example\n```jldoctest\njulia> model = BasicStructural(rand(100), 12)\nBasicStructural\n```\n\n# References\n * Durbin, James, & Siem Jan Koopman. (2012). \"Time Series Analysis by State Space Methods: Second Edition.\" Oxford University Press.\n\"\"\"\nmutable struct BasicStructural <: StateSpaceModel\n    hyperparameters::HyperParameters\n    system::LinearUnivariateTimeInvariant\n    seasonality::Int\n    results::Results\n\n    function BasicStructural(y::Vector{Fl}, s::Int) where Fl\n        Z = [1; 0; 1; zeros(Fl, s - 2)]\n        T = [\n            1 1 zeros(Fl, 1, s - 1)\n            0 1 zeros(Fl, 1, s - 1)\n            0 0 -ones(Fl, 1, s - 1)\n            zeros(Fl, s - 2, 2) Matrix{Fl}(I, s - 2, s - 2) zeros(Fl, s - 2)\n        ]\n        R = [\n            Matrix{Fl}(I, 3, 3)\n            zeros(Fl, s - 2, 3)\n        ]\n        d = zero(Fl)\n        c = zeros(Fl, s + 1)\n        H = one(Fl)\n        Q = zeros(Fl, 3, 3)\n\n        system = LinearUnivariateTimeInvariant{Fl}(y, Z, T, R, d, c, H, Q)\n\n        names = [\"sigma2_ε\", \"sigma2_ξ\", \"sigma2_ζ\", \"sigma2_ω\"]\n        hyperparameters = HyperParameters{Fl}(names)\n\n        return new(hyperparameters, system, s, Results{Fl}())\n    end\nend\n\nfunction default_filter(model::BasicStructural)\n    Fl = typeof_model_elements(model)\n    steadystate_tol = Fl(1e-5)\n    a1 = zeros(Fl, num_states(model))\n    P1 = Fl(1e6) .* Matrix{Fl}(I, num_states(model), num_states(model))\n    return UnivariateKalmanFilter(a1, P1, num_states(model), steadystate_tol)\nend\n\nfunction initial_hyperparameters!(model::BasicStructural)\n    Fl = typeof_model_elements(model)\n    initial_hyperparameters = Dict{String,Fl}(\n        \"sigma2_ε\" => one(Fl),\n        \"sigma2_ξ\" => one(Fl),\n        \"sigma2_ζ\" => one(Fl),\n        \"sigma2_ω\" => one(Fl),\n    )\n    set_initial_hyperparameters!(model, initial_hyperparameters)\n    return model\nend\n\nfunction constrain_hyperparameters!(model::BasicStructural)\n    constrain_variance!(model, \"sigma2_ε\")\n    constrain_variance!(model, \"sigma2_ξ\")\n    constrain_variance!(model, \"sigma2_ζ\")\n    constrain_variance!(model, \"sigma2_ω\")\n    return model\nend\n\nfunction unconstrain_hyperparameters!(model::BasicStructural)\n    unconstrain_variance!(model, \"sigma2_ε\")\n    unconstrain_variance!(model, \"sigma2_ξ\")\n    unconstrain_variance!(model, \"sigma2_ζ\")\n    unconstrain_variance!(model, \"sigma2_ω\")\n    return model\nend\n\nfunction fill_model_system!(model::BasicStructural)\n    model.system.H = get_constrained_value(model, \"sigma2_ε\")\n    model.system.Q[1] = get_constrained_value(model, \"sigma2_ξ\")\n    model.system.Q[5] = get_constrained_value(model, \"sigma2_ζ\")\n    model.system.Q[end] = get_constrained_value(model, \"sigma2_ω\")\n    return model\nend\n\nfunction reinstantiate(model::BasicStructural, y::Vector{Fl}) where Fl\n    return BasicStructural(y, model.seasonality)\nend\n\nhas_exogenous(::BasicStructural) = false\n", "meta": {"hexsha": "7f56ded3eea063a2d3c7c069847c247f40c9ef36", "size": 3588, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/basicstructural.jl", "max_stars_repo_name": "gionikola/StateSpaceModels.jl", "max_stars_repo_head_hexsha": "477426b6b1a40809b793bdc46574bfa3909e6182", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 189, "max_stars_repo_stars_event_min_datetime": "2018-03-08T18:13:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:55:22.000Z", "max_issues_repo_path": "src/models/basicstructural.jl", "max_issues_repo_name": "PaulMainwood/StateSpaceModels.jl", "max_issues_repo_head_hexsha": "b1723e74f3c6243020a9909d49639a3ca8325985", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 270, "max_issues_repo_issues_event_min_datetime": "2018-04-02T15:48:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:35:16.000Z", "max_forks_repo_path": "src/models/basicstructural.jl", "max_forks_repo_name": "PaulMainwood/StateSpaceModels.jl", "max_forks_repo_head_hexsha": "b1723e74f3c6243020a9909d49639a3ca8325985", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2019-07-24T14:56:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T17:13:07.000Z", "avg_line_length": 33.5327102804, "max_line_length": 133, "alphanum_fraction": 0.6404682274, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693631290971, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7764254278962273}}
{"text": "#=\nA unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:\n\n1/2\t= \t0.5\n1/3\t= \t0.(3)\n1/4\t= \t0.25\n1/5\t= \t0.2\n1/6\t= \t0.1(6)\n1/7\t= \t0.(142857)\n1/8\t= \t0.125\n1/9\t= \t0.(1)\n1/10\t= \t0.1\nWhere 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.\n\nFind the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.\n=#\n\n# Multiplicative order\n# http://mathworld.wolfram.com/MultiplicativeOrder.html\nfunction multiplicative_order(a, n)\n  if gcd(a,n) > 1\n    return 0\n  else\n    order = 1\n    mod_exp = a\n    while mod_exp != 1\n      order +=1\n      mod_exp = (mod_exp * a) % n\n    end\n    return order\n  end\nend\n\nfunction calc()\n  largest = 0\n  max_i = 0\n  for i in 2:1000\n    a = multiplicative_order(10, i)\n    if a > largest\n      largest = a\n      max_i = i\n    end\n  end\n  max_i\nend\n@time println(calc())\n", "meta": {"hexsha": "a9908b73619731ee13555b895ff2e32e5a2b7980", "size": 976, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p26.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p26.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p26.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 20.7659574468, "max_line_length": 130, "alphanum_fraction": 0.6383196721, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7763580076412394}}
{"text": "using FractionalCalculus\nusing Plots, LaTeXStrings\n\ntarget = gamma(6)/gamma(2.4)*tspan.^1.4\n\n\ns=\"\\$D^{3.6}x^5\\$\"\n\ntspan=collect(0:0.01:6)\n\nresult=fracdiff(x->x^5, 3.6, 6, 0.01, RLDiffMatrix())\n\nplot(tspan, result, title=s, legend=:bottomright, label=\"Numerical\")\nplot!(tspan, target, lw=3, ls=:dash, label=\"Analytical\")\nsavefig(\"./arbitrary_order_derivative.png\")", "meta": {"hexsha": "013a6f78f5354fd1bb39a11202935e55dbe0bf62", "size": 363, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/arbitrary_order_derivative.jl", "max_stars_repo_name": "SciFracX/FractionalCalculus.jl", "max_stars_repo_head_hexsha": "f570164fdf86314f6c8871d18659bd343046bb04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-11-05T12:53:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T20:58:27.000Z", "max_issues_repo_path": "example/arbitrary_order_derivative.jl", "max_issues_repo_name": "SciFracX/FractionalCalculus.jl", "max_issues_repo_head_hexsha": "f570164fdf86314f6c8871d18659bd343046bb04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-11-05T17:20:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T13:20:01.000Z", "max_forks_repo_path": "example/arbitrary_order_derivative.jl", "max_forks_repo_name": "SciFracX/FractionalCalculus.jl", "max_forks_repo_head_hexsha": "f570164fdf86314f6c8871d18659bd343046bb04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-10-21T08:58:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T20:40:29.000Z", "avg_line_length": 24.2, "max_line_length": 68, "alphanum_fraction": 0.7052341598, "num_tokens": 135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7763580049413121}}
{"text": "import Statistics\n\n\"\"\"\n    simple_linear_regression(x::AbstractVector, y::AbstractVector)\n\nSimple linear regression - given a set of two-dimensional points (x, y), use\nthe ordinary least squares method to find the best fit line of the form\ny = a + b*x (where a and b are real numbers) and return the tuple (a, b).\n\"\"\"\nfunction simple_linear_regression(\n        x::AbstractVector,\n        y::AbstractVector,\n        )::Tuple\n    if length(x) != length(y)\n        error(\"length(x) != length(y)\")\n    end\n    if length(x) == 0\n        error(\"length(x) == 0\")\n    end\n\n    x_bar = Statistics.mean(x)\n    y_bar = Statistics.mean(y)\n    var_x = Statistics.var(x)\n    cov_x_y = Statistics.cov(x,y)\n\n    @assert(isfinite(x_bar))\n    @assert(isfinite(y_bar))\n    @assert(isfinite(var_x))\n    @assert(isfinite(cov_x_y))\n\n    coefficient = cov_x_y/var_x\n\n    if isfinite(coefficient)\n        intercept = y_bar - coefficient*x_bar\n        @debug(\n            string(\"Found best fit line: \"),\n            intercept,\n            coefficient,\n            )\n    else\n        @warn(\n            string(\n                \"The best fit line does not have a finite slope. \",\n                \"I will ignore this result and will instead return \",\n                \"intercept = 0 and coefficient = 0\",\n                )\n            )\n        intercept = 0\n        coefficient = 0\n    end\n\n    return intercept, coefficient\nend\n", "meta": {"hexsha": "8b80fc08047784fe3778a06c0839c8dfaf9663fc", "size": 1402, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/toplevel/always-loaded/linearmodel/ordinary_least_squares_regression.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PredictMD.jl-3e7d7328-36f8-4388-bd01-4613c92c7370", "max_stars_repo_head_hexsha": "7987993b5900e658c3aa9c568a9ed7fe38e82f11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2018-05-24T14:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T08:17:39.000Z", "max_issues_repo_path": "src/toplevel/always-loaded/linearmodel/ordinary_least_squares_regression.jl", "max_issues_repo_name": "UnofficialJuliaMirror/PredictMD.jl-3e7d7328-36f8-4388-bd01-4613c92c7370", "max_issues_repo_head_hexsha": "7987993b5900e658c3aa9c568a9ed7fe38e82f11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 383, "max_issues_repo_issues_event_min_datetime": "2018-04-12T21:53:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-24T15:53:37.000Z", "max_forks_repo_path": "src/toplevel/always-loaded/linearmodel/ordinary_least_squares_regression.jl", "max_forks_repo_name": "UnofficialJuliaMirror/PredictMD.jl-3e7d7328-36f8-4388-bd01-4613c92c7370", "max_forks_repo_head_hexsha": "7987993b5900e658c3aa9c568a9ed7fe38e82f11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-05-06T23:16:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T15:49:49.000Z", "avg_line_length": 25.962962963, "max_line_length": 76, "alphanum_fraction": 0.5813124108, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7763580042721209}}
{"text": "using LinearAlgebra\nfunction Sparse_matrix_SINDYPI(Theta, dx, lambda, nvars, maxiter)\n\nnormLib = zeros(1, size(Theta,2))\n\nThetan = deepcopy(Theta)\n\n    for norm_k=1:size(Theta,2)\n            normLib[norm_k] = norm(Thetan[:,norm_k]);\n            Thetan[:,norm_k] = Thetan[:,norm_k]/normLib[norm_k];\n    end\n\n\n   #Epsilon = Thetan\\dx\n\n#Below:Only to be used for ill conditioned matrices, like in the glycolysis example. Check on this\nEpsilon = zeros(size(Thetan,2),1)\nldiv!(Epsilon, qr(Thetan), dx)\n\n\n#=\n   Epsilon_c = similar(Epsilon)\n   Epsilon_c .= Epsilon\n=#\n\n    for i in 1:maxiter\n        index_remove = abs.(Epsilon) .<= lambda\n        Epsilon[index_remove] .= zero(eltype(Epsilon))\n\n        for j in 1:nvars\n            index_retain = @. !index_remove[:,j]\n            Epsilon[index_retain, j] = Thetan[:, index_retain] \\ dx[:,j]\n        end\n   #=\n    if norm(Epsilon_c - Epsilon, 2) < eps()\n        break\n    else\n        Epsilon_c .= Epsilon\n    end\n=#\n    end\n\n        for norm_k=1:length(Epsilon)\n            Epsilon[norm_k,:] = Epsilon[norm_k,:]/normLib[norm_k];\n        end\n\n    return Epsilon\nend\n\n#=\nA. Q factor\n\nqrf.R\n\nAns = inv(qrf.R)*(qrf.Q)'*dx\n=#\n", "meta": {"hexsha": "47bce4dc241d947c76da33483f4db73c780798a3", "size": 1166, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SparsityAlgorithm.jl", "max_stars_repo_name": "RajDandekar/SINDYPI_Julia.jl", "max_stars_repo_head_hexsha": "3963dbab0a1bc77515fc13b3486fd10f1dd77503", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-01T14:03:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T14:03:40.000Z", "max_issues_repo_path": "src/SparsityAlgorithm.jl", "max_issues_repo_name": "RajDandekar/SINDYPI_Julia", "max_issues_repo_head_hexsha": "3963dbab0a1bc77515fc13b3486fd10f1dd77503", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SparsityAlgorithm.jl", "max_forks_repo_name": "RajDandekar/SINDYPI_Julia", "max_forks_repo_head_hexsha": "3963dbab0a1bc77515fc13b3486fd10f1dd77503", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4561403509, "max_line_length": 98, "alphanum_fraction": 0.6054888508, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7763580042489582}}
{"text": "abstract type CovKer end\n\n\"\"\"\n    SqExp(σ)\n\nStores the bandwidth parameter `σ` of the squared exponential covariance kernel.\n\nSee also: [`(s_e::SqExp)(x, y)`](@ref)\n\"\"\"\nstruct SqExp{F <: Real} <: CovKer\n    neg_inv_double_σ_sq::F\n    \n    SqExp(σ::F = 1.0) where F <: Real = new{F}(-F(0.5)/(σ^2))\nend\n\n\"\"\"\n    (s_e::SqExp)(x, y)\n\nEvaluates the squared exponential covariance kernel at `(x, y)`.\n\"\"\"\n(s_e::SqExp)(x::V1, y::V2) where {V1 <: AbstractVector, V2 <: AbstractVector} = \n    exp(dot((x - y),(x - y))*s_e.neg_inv_double_σ_sq)\n\n\"\"\"\n    (s_e::SqExp)(X)\n\nEvaluates the s_e for all `(X_i, X_j)`.\n\"\"\"\n\nfunction (s_e::SqExp)(x_samples::AbstractMatrix{F}) where {F<:Real} \n    num_samples = size(x_samples, 2)\n    K = Array{F, 2}(undef, num_samples, num_samples)\n    for i in 1:num_samples\n        for j in i:num_samples\n            K[i, j] = s_e(x_samples[:,i], x_samples[:,j])\n        end\n    end\n    K\nend", "meta": {"hexsha": "4ff1bd0f7bb956a2e82a367719c27d1c2af0a878", "size": 909, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CovKer.jl", "max_stars_repo_name": "tpielok/SSGE.JL", "max_stars_repo_head_hexsha": "39f0852ea3cfd3161199188bb052a636062d4ed1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-30T15:22:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T00:25:20.000Z", "max_issues_repo_path": "src/CovKer.jl", "max_issues_repo_name": "tpielok/SSGE.JL", "max_issues_repo_head_hexsha": "39f0852ea3cfd3161199188bb052a636062d4ed1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CovKer.jl", "max_forks_repo_name": "tpielok/SSGE.JL", "max_forks_repo_head_hexsha": "39f0852ea3cfd3161199188bb052a636062d4ed1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3076923077, "max_line_length": 80, "alphanum_fraction": 0.602860286, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654164300481, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7763580022182222}}
{"text": "Metric(mat::T) where {N, T<:SMatrix{N, N, Float64}} = Metric{N, T}(Symmetric(mat))\n\nfunction Metric(mat::AbstractMatrix{<:Real})\n    N, M = size(mat)\n    @assert N == M\n    return Metric(SMatrix{N, N, Float64}(mat))\nend\n\n\"\"\"\n    Metric(N::Int)\n\nThe Euclidean metric in `N` dimensions.\n\"\"\"\nMetric(N::Int) = Metric(SMatrix{N,N}(1.0I))\n\nfunction Wedge(vectors::Vector{SVector{N, Float64}}) where N\n    K = length(vectors)\n    Wedge{N, K}(SVector{K, SVector{N, Float64}}(vectors))\nend\n\n\"\"\"\n    Wedge(s::Simplex{N, K}) where {N, K}\n\nThe wedge product of all vectors emanating from the first vertex of a simplex.\n\"\"\"\nfunction Wedge(s::Simplex{N, K}) where {N, K}\n    vectors = SVector{N, Float64}[p.coords - s.points[1].coords for p in s.points[2:end]]\n    return Wedge(vectors)\nend\n\nexport inner_product\n\"\"\"\n    inner_product(m::Metric{N}, v1::SVector{N, Float64}, v2::SVector{N, Float64}) where N\n    inner_product(m::Metric{N}, w1::Wedge{N, K}, w2::Wedge{N, K}) where {N, K}\n\nCompute the inner product of two vectors with respect to the given metric.\n\"\"\"\ninner_product(m::Metric{N}, v1::SVector{N, Float64}, v2::SVector{N, Float64}) where N =\n    transpose(v1) * m.mat * v2\n\nfunction inner_product(m::Metric{N}, w1::Wedge{N, K}, w2::Wedge{N, K}) where {N, K}\n    if K == 0\n        return 1.0\n    else\n        inner_products = hcat([[inner_product(m, v1, v2) for v1 in w1.vectors]\n            for v2 in w2.vectors]...)\n        return det(inner_products)\n    end\nend\n\nexport norm_square\n\"\"\"\n    norm_square(m::Metric{N}, v::SVector{N, Float64}) where N\n    norm_square(m::Metric{N}, w::Wedge{N}) where N\n\nCompute the inner product of a vector with itself with respect to the given metric. Note\nthat this value can be negative if the metric is not positive semi-definite.\n\"\"\"\nnorm_square(m::Metric{N}, v::SVector{N, Float64}) where N = inner_product(m, v, v)\n\nnorm_square(m::Metric{N}, w::Wedge{N}) where N = inner_product(m, w, w)\n\nimport LinearAlgebra: norm\n\"\"\"\n    norm(m::Metric{N}, v::SVector{N, Float64}) where N\n    norm(m::Metric{N}, w::Wedge{N}) where N\n\nCompute the square root of the magnitude of the inner product of a vector with itself with\nrespect to the metric `m`.\n\"\"\"\nnorm(m::Metric{N}, v::SVector{N, Float64}) where N = sqrt(abs(norm_square(m, v)))\n\nnorm(m::Metric{N}, w::Wedge{N}) where N = sqrt(abs(norm_square(m, w)))\n\nexport volume_square\n\"\"\"\n    volume_square(m::Metric{N}, s::Simplex{N, K}) where {N, K}\n\nCompute the squared volume of a simplex with respect to the given metric. Note that this\nvalue can be negative if the metric is not positive semi-definite.\n\"\"\"\nvolume_square(m::Metric{N}, s::Simplex{N, K}) where {N, K} =\n    norm_square(m, Wedge(s))/factorial(K-1)^2\n\nexport volume\n\"\"\"\n    volume(m::Metric{N}, s::Simplex{N, K}) where {N, K}\n\nCompute the volume of a simplex with respect to the given metric.\n\"\"\"\nvolume(m::Metric{N}, s::Simplex{N, K}) where {N, K} =\n    sqrt(abs(norm_square(m, Wedge(s))))/factorial(K-1)\n", "meta": {"hexsha": "fdc87dd26949bc689062f211f85ec7b835d4a9a6", "size": 2946, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/metrics.jl", "max_stars_repo_name": "mgscheer/DiscreteExteriorCalculus.jl", "max_stars_repo_head_hexsha": "6e95c222921fed6119824c2771740f030101ac59", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2019-06-26T08:25:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T01:21:16.000Z", "max_issues_repo_path": "src/metrics.jl", "max_issues_repo_name": "mgscheer/DiscreteExteriorCalculus.jl", "max_issues_repo_head_hexsha": "6e95c222921fed6119824c2771740f030101ac59", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-10-24T22:27:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-09T00:06:56.000Z", "max_forks_repo_path": "src/metrics.jl", "max_forks_repo_name": "mgscheer/DiscreteExteriorCalculus.jl", "max_forks_repo_head_hexsha": "6e95c222921fed6119824c2771740f030101ac59", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2019-06-26T04:21:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T01:21:28.000Z", "avg_line_length": 31.6774193548, "max_line_length": 90, "alphanum_fraction": 0.6636116768, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7763580015490312}}
{"text": "\"\"\"\nJarque–Bera Statistic as a normality measure for optimization\n\"\"\"\nfunction normality(x::AbstractVector{T}) where T<:Real\n\n    P = Base.promote_op(/, T, T)\n\n    # moments at origin\n    n = P(length(x))\n    m1 = mo2 = mo3 = mo4 = P(0)\n    \n    @inbounds for xi in x\n        m1 += x1 = xi / n\n        mo2 += x2 = x1 * x1 * n\n        mo3 += x3 = x1 * x2 * n\n        mo4 += x4 = x1 * x3 * n\n    end\n    \n    # moments\n    m2 = mo2 - m1^2\n    m3 = mo3 - P(3)*m1*mo2 + P(2)*m1^3\n    m4 = mo4 - P(4)*m1*mo3 + P(6)*m1^2*mo2 - P(3)*m1^2*m1^2\n\n    S = m3 / (m2 * sqrt(m2))\n    K = m4 / m2^2\n\n    n/P(6) * (S^2 + P(1/4) * (K-P(3))^2)\n    \nend\n", "meta": {"hexsha": "cda811c24b880b08f82701b0e056174249d68565", "size": 635, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/normality.jl", "max_stars_repo_name": "viraltux/DataWrangler.jl", "max_stars_repo_head_hexsha": "df89dddc13f68b5b74a76bdeaeaa519e6db873b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-10-10T09:44:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T20:31:48.000Z", "max_issues_repo_path": "src/normality.jl", "max_issues_repo_name": "viraltux/DataWrangler.jl", "max_issues_repo_head_hexsha": "df89dddc13f68b5b74a76bdeaeaa519e6db873b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-09T12:13:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-09T12:13:45.000Z", "max_forks_repo_path": "src/normality.jl", "max_forks_repo_name": "viraltux/DataWrangler.jl", "max_forks_repo_head_hexsha": "df89dddc13f68b5b74a76bdeaeaa519e6db873b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1666666667, "max_line_length": 61, "alphanum_fraction": 0.4692913386, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541528387691, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7763579968299492}}
{"text": "\"\"\"\n    volatility(returns; multiplier=1.0)\n\nCalculates the volatility based on the standard deviation of the returns. The optional `multiplier` parameter allows for scaling the resulting volatility metric, i.e. for annualization.\n\n# Formula\n\n    Vol = std(returns) * sqrt(multiplier)\n\n# Arguments\n- `returns`:    Vector of asset returns (usually log-returns).\n- `multiplier`: Optional scalar multiplier, i.e. use `12` to annualize monthly returns, and use `252` to annualize daily returns.\n\"\"\"\nfunction volatility(returns; multiplier=1.0)\n    std(returns) * sqrt(multiplier)\nend\n", "meta": {"hexsha": "14ca7099b2c72a49173aab2b2146eb1bb6abceb8", "size": 580, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/volatility.jl", "max_stars_repo_name": "rbeeli/RiskPerf.jl", "max_stars_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-07T19:19:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T19:19:09.000Z", "max_issues_repo_path": "src/volatility.jl", "max_issues_repo_name": "rbeeli/RiskPerf.jl", "max_issues_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/volatility.jl", "max_forks_repo_name": "rbeeli/RiskPerf.jl", "max_forks_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1176470588, "max_line_length": 185, "alphanum_fraction": 0.7448275862, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541610257064, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.776357995456823}}
{"text": "module gauss_model\n\n# Provide the functionality to model Gaussians as test cases\nusing DiskJockey.constants\n\nexport imageGauss, FTGauss\n\n# Because of the flipped nature of the sky (but not flipped nature of the UV plane)\n# there are some tricky conventions about how to pack the array.\n\n# Given two arrays of l and m coordinates, fill an array of the Gaussian image\n# following the MATLAB convention.\n# p0 is a vector of [mu_RA, mu_DEC, sigma_x, sigma_y] in units of arcseconds\n# mu_RA and mu_DEC are the locations of the centroid emission relative to the\n# image origin (RA=0, DEC=0).\nfunction imageGauss(ll::Vector{Float64}, mm::Vector{Float64}, p::Vector{Float64}, k::Int)\n\n    # Both ll and mm increase with array index\n    nx = length(ll)\n    ny = length(mm)\n\n    img = Array(Float64, ny, nx)\n    mu = p[1:2] * arcsec #ll and mm shifts\n    Sigma = Diagonal((p[3:4] * arcsec).^2) #Convert from arcsec to radians\n    pre = 1. / (2pi * sqrt(det(Sigma))) * k\n    for j=1:ny\n        for i=1:nx\n            R = Float64[ll[i] , mm[j]] - mu\n            img[j, i] = pre * exp(-0.5 * (R' * (Sigma\\R))[1])\n        end\n    end\n    return img\nend\n\n# Given u and v coordinates in [kλ], evaluate the analytic FT of the\n# aforementioned Gaussian\n# N.B. Here Sigma refers to the (same) covariance matrix in the *image* domain\n# always return a complex value\nfunction FTGauss(uu::Float64, vv::Float64, p::Vector{Float64}, k::Int)\n    uu = uu .* 1e3 #[λ]\n    vv = vv .* 1e3 #[λ]\n    mu_RA, mu_DEC = p[1:2]\n    mu = Float64[mu_RA, mu_DEC] * arcsec #ll and mm shifts\n    R = Float64[uu, vv]\n    Sigma = Diagonal((p[3:4] * arcsec).^2) #Convert from arcsec to radians\n    phase_shift = exp(-2pi * 1.0im * (R' * mu)[1]) # Not actually in polar phase form\n    return k * exp(-2 * (pi^2) * (R' * Sigma * R)[1]) * phase_shift\n    # in this case, Sigma serves as the inverse\nend\n\n# Given two arrays of u and v coordinates in [kλ], fill an array with the\n# analytic FT of aforementioned Gaussian evaluated at every pairwise (u,v) pair\nfunction FTGauss(uu::Vector{Float64}, vv::Vector{Float64}, p::Vector{Float64}, k::Int)\n    nu = length(uu)\n    nv = length(vv)\n    # Both uu and vv increase with array index\n    img = Array(Complex128, nv, nu)\n    for j=1:nv\n        for i=1:nu\n            img[j, i] = FTGauss(uu[i], vv[j], p, k)\n        end\n    end\n    return img\nend\n\n\nend # Module\n", "meta": {"hexsha": "2ba8202f9df9090c0a536ed8055013e4c845e624", "size": 2361, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tests/gauss_model.jl", "max_stars_repo_name": "elnjensen/DiskJockey", "max_stars_repo_head_hexsha": "ef618d27c2aff9b0540b0e00035b9a4dbfea1968", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/gauss_model.jl", "max_issues_repo_name": "elnjensen/DiskJockey", "max_issues_repo_head_hexsha": "ef618d27c2aff9b0540b0e00035b9a4dbfea1968", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/gauss_model.jl", "max_forks_repo_name": "elnjensen/DiskJockey", "max_forks_repo_head_hexsha": "ef618d27c2aff9b0540b0e00035b9a4dbfea1968", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7205882353, "max_line_length": 89, "alphanum_fraction": 0.6484540449, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761565, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7763579920877047}}
{"text": "\n\nimport Base.cross, Base.dot, Base.-, Base.+, Base.*, Base./\n\ntype Vector\n\tx::Real\n\ty::Real\n\tz::Real\nend\n\n# Outer Constructors\n\nVector() = Vector(0, 0, 0)\n\n# Methods on Vector\n\nfunction toList(a::Vector)\n\treturn [a.x, a.y, a.z]\nend\n\nfunction toVec(a::Array)\n\treturn Vector(a[1], a[2], a[3])\nend\n\nfunction +(a::Vector, b::Vector)\n\treturn toVec(toList(a) .+ toList(b))\nend\n\nfunction -(a::Vector, b::Vector)\n\treturn toVec(toList(a) .- toList(b))\nend\n\nfunction *(a::Vector, b::Real)\n\treturn toVec(toList(a) .* b)\nend\n\nfunction magnitude(a::Vector)\n\treturn sqrt(a.x ^ 2 + a.y ^ 2 + a.z ^ 2)\nend\n\nfunction normal(a::Vector)\n\tmag = magnitude(a)\n\treturn toVec(toList(a) ./ mag)\nend\n\nfunction dot(a::Vector, b::Vector)\n\treturn dot(toList(a), toList(b))\nend\n\nfunction cross(a::Vector, b::Vector)\n\treturn toVec(cross(toList(a), toList(b)))\nend\n", "meta": {"hexsha": "d9f71ea986e68b6d48cf3bfc58a1b89750189149", "size": 834, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/html/Julia/vector.jl", "max_stars_repo_name": "TravisA9/Niquita", "max_stars_repo_head_hexsha": "7e1c6766f2be9e15246ef81af4b9553f37008dfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/html/Julia/vector.jl", "max_issues_repo_name": "TravisA9/Niquita", "max_issues_repo_head_hexsha": "7e1c6766f2be9e15246ef81af4b9553f37008dfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/html/Julia/vector.jl", "max_forks_repo_name": "TravisA9/Niquita", "max_forks_repo_head_hexsha": "7e1c6766f2be9e15246ef81af4b9553f37008dfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.7358490566, "max_line_length": 59, "alphanum_fraction": 0.654676259, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7763028997345445}}
{"text": "export expMod, boundMod, fMod,identityMod\n\n\n\"\"\"\n\tsigma,dsigma = expMod(model)\n\n\tmaps model parameter to conductivity via\n\n\tsigma(m) = exp(m)\n\n\"\"\"\nfunction expMod(m)\n\treturn exp.(m), sdiag(exp.(m))\nend\n\n\"\"\"\n\tsigma,dsigma = fMod(model;f::Function=identity,df::Function=m->sparse(1.0I,length(m),length(m)))\n\n\tmaps model parameter to conductivity via\n\n\tsigma(m) = f(m) and dsigma(m) = sdiag(df(m))\n\n\"\"\"\nfunction fMod(m;f::Function=identity,df::Function=m->ones(eltype(m),length(m)))\n\treturn f(m),sdiag(df(m))\nend\n\nfunction identityMod(m)\n\treturn m, UniformScaling(one(eltype(m)))\nend\n\n\nexport boundMod\n\"\"\"\n\tsigma,dsigma = boundMod(m;boundLow=0.0,boundHigh=1.0)\n\n\tmaps model parameter to conductivity via\n\n\t\tsigma = 0.5*(boundHigh-boundLow) * (tanh(m)+1.0 ) + boundLow\n\n\"\"\"\nfunction boundMod(m; boundLow = 0.0, boundHigh = 1.0)\n\tu        = tanh.(m)\n\td        = 0.5 * (boundHigh - boundLow)\n\tsigma    = d * (u .+ 1.0) .+ boundLow\n\tdsigmadm = sdiag(d * (1.0 .- u .* u))\n\treturn sigma, dsigmadm\nend\n", "meta": {"hexsha": "af1f492e44514e013036f6d91c23841e30031899", "size": 991, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/InverseSolve/models.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/jInv.jl-3dacf901-f8cd-5544-86ed-7a705f85c244", "max_stars_repo_head_hexsha": "2e7305f231a29bd8e1e803b82cc2bc8e9b7a205a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2016-04-11T22:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T21:58:53.000Z", "max_issues_repo_path": "src/InverseSolve/models.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/jInv.jl-3dacf901-f8cd-5544-86ed-7a705f85c244", "max_issues_repo_head_hexsha": "2e7305f231a29bd8e1e803b82cc2bc8e9b7a205a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2016-03-23T18:24:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T15:52:47.000Z", "max_forks_repo_path": "src/InverseSolve/models.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/jInv.jl-3dacf901-f8cd-5544-86ed-7a705f85c244", "max_forks_repo_head_hexsha": "2e7305f231a29bd8e1e803b82cc2bc8e9b7a205a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-03-23T16:52:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T17:04:41.000Z", "avg_line_length": 20.2244897959, "max_line_length": 97, "alphanum_fraction": 0.6589303734, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542284, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7763028991406778}}
{"text": "using Measurements\ninclude(\"/home/jefter66/Projects/Lablib/src/Stats.jl\")\n\nprintstyled(\"Experimento 1 \\n \", color =:green);\n# densidade ρ da corda\n\n## densidade pela geometria\n\nm1 = 0.00552 ± 0.00001 # kg\nl = 22.97 ± 0.01 # m\n\nρ1 = m1.val/l.val ± (m1.val*l.err + m1.err*l.val)/l.val^2\nprintstyled(\"Densidade linear calculada pela geometria \\n\"; color=:red);\nprintln(\"ρ ± Δρ = (\",ρ1, \") kg/m\");\n\n\n## densidade pela tração\nm2 = 0.06067 ± 0.00001 #kg\nv = [48.9, 49.5, 49.8, 49.7, 49.3]\nvm = Statistics.mean(v);\nv = round(vm,digits=3) ± round(standartDeviation(v),digits=2);\nprintstyled(\"Velocidade média e erro calculado pelo desvio padrão\\n\"; color=:red);\nprintln(\"v_medio ± Δv = (\",v, \") m/s\")\n\n\n# tração\ng = 9.81\nt = m2.val*g ± m2.err*g# Newtons\nprintstyled(\"Tração:\\n\"; color=:red);\nprintln(\"T ± ΔT = (\", t, \") N\");\n\n# densidade linear calculada a partir da tração\nρ2 = t.val/v.val^2 ± (2*t.val*v.val*v.err + t.err*v.val^2)/(v.val^4)\nprintstyled(\"Densidade linear \\n \"; color =:red);\nprintln(\"ρ2 ± Δρ2= (\", ρ2 , \") kg/m\");\n\n\n\n# equivalência\n\nv1 = abs(ρ2.val - ρ1.val);\nv2 = 2*(ρ1.err + ρ2.err);\n\nprintstyled(\"Checando equivalência\", color=:red);\nprintln(\"| x1 - x2 | < 2*(σ1 + σ2)\");\nprintln(\"| \",round(ρ1.val,digits=10) , \" - \", round(ρ2.val,digits=10) , \" | < 2*(\", round(ρ1.err,digits=10), \" + \", round(ρ2.err,digits=10), \")\");\nprintln(v1<v2);\n\n\n\n\n# Ondas sonoras\nprintstyled(\"Experimento 2\\n\", color =:green);\n\n## comprimento constante\nprintstyled(\"Comprimento constante \\n \", color =:red);\nL = (0.1100 ± 0.0001);\nf = []\nn = 5\n\n\n## frequência constante\nprintstyled(\"Experimento 3\\n\", color =:green);\n\nf = (2000±0.1);\nL = [0.087,0.088,0.086,0.087];\nΔL = 0.1;\n\nλ(L) = 2*L;\n\nλs = Statistics.mean([λ(L[1]),λ(L[2]),λ(L[3]),λ(L[4])]) ± standartDeviation(L);\n\n\nprintstyled(\"Frequência constante \\n \", color =:red);\n\nprintln(\"Comprimento de onda médio: λ ± Δλ = \", λs);\n\nv =  λs*f;\nprintln(\"Velocidade média: v ± Δv = \",v);\n\n\n\n\n\n## gás desconhecido\nprintstyled(\"Experimento 4 - Gás desconhecido 1° harmônico \\n \", color =:red);\nf = (2000±0.1);\nn = 1\nl = (0.23 ±0.0001);\n\nv = 2*l*f;\nprintln(\"Velocidade média: v ± Δv = \",v);\n", "meta": {"hexsha": "76ee53248be9d250e0918c2dac27578ce5a409df", "size": 2121, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Fisica experimental/02/04/src/calcs.jl", "max_stars_repo_name": "jefter66/notes", "max_stars_repo_head_hexsha": "adf8753b166162dcb898470932db2235c5d5966b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Fisica experimental/02/04/src/calcs.jl", "max_issues_repo_name": "jefter66/notes", "max_issues_repo_head_hexsha": "adf8753b166162dcb898470932db2235c5d5966b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Fisica experimental/02/04/src/calcs.jl", "max_forks_repo_name": "jefter66/notes", "max_forks_repo_head_hexsha": "adf8753b166162dcb898470932db2235c5d5966b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8064516129, "max_line_length": 146, "alphanum_fraction": 0.6214049976, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7763028969131462}}
{"text": "export orthog!,\n       svd_recursive\n\nfunction orthog!(M::AbstractMatrix{T};\n                 npass::Int=2) where {T}\n  nkeep = min(size(M)...)\n  dots = zeros(T,nkeep)\n  for i=1:nkeep\n    coli = view(M,:,i)\n    nrm = norm(coli)\n    if nrm < 1E-10\n      rand!(coli)\n      nrm = norm(coli)\n    end\n    coli ./= nrm\n    (i==1) && continue\n\n    Mcols = view(M,:,1:i-1)\n    dotsref = view(dots,1:i-1)\n    for pass=1:npass\n      mul!(dotsref,Mcols',coli)\n      #BLAS.gemv!('N',1.0,Mcols,dotsref,-1.0,coli)\n      coli .-= Mcols*dotsref\n      nrm = norm(coli)\n      if nrm < 1E-3 #orthog is suspect\n        pass = pass-1\n      end\n      if nrm < 1E-10\n        rand!(coli)\n        nrm = norm(coli)\n      end\n      coli ./= nrm\n    end\n  end\nend\n\nfunction pos_sqrt(x::Float64)::Float64\n  (x < 0.0) && return 0.0\n  return sqrt(x)\nend\n\nfunction checkSVDDone(S::Vector,\n                      thresh::Float64)\n  N = length(S)\n  (N <= 1 || thresh < 0.0) && return (true,1)\n  S1t = S[1]*thresh\n  start = 2\n  while start <= N\n    (S[start] < S1t) && break\n    start += 1\n  end\n  if start >= N\n    return (true,N)\n  end\n  return (false,start)\nend\n\nfunction svd_recursive(M::AbstractMatrix;\n                      thresh::Float64=1E-3,\n                      north_pass::Int=2)\n  Mr,Mc = size(M)\n\n  if Mr > Mc\n    V,S,U = svd_recursive(transpose(M))\n    conj!(U)\n    conj!(V)\n    return U,S,V\n  end\n\n  #rho = BLAS.gemm('N','T',-1.0,M,M) #negative to sort eigenvalues greatest to smallest\n  rho = -M*M' #negative to sort eigenvalues in decreasing order\n  D,U = eigen(Hermitian(rho),1:size(rho,1))\n\n  Nd = length(D)\n  for n=1:Nd\n    D[n] = pos_sqrt(-D[n])\n  end\n\n  V = M'*U\n  orthog!(V,npass=north_pass)\n\n  (done,start) = checkSVDDone(D,thresh)\n\n  done && return U,D,V\n\n  u = view(U,:,start:Nd)\n  v = view(V,:,start:Nd)\n\n  b = u'*(M*v)\n  bu,bd,bv = svd_recursive(b,\n                          thresh=thresh,\n                          north_pass=north_pass)\n\n  u .= u*bu\n  v .= v*bv\n  view(D,start:Nd) .= bd\n  \n  return U,D,V\nend\n\n# TODO: maybe move to another location?\nfunction polar(M::AbstractMatrix)\n  U,S,V = svd(M) # calls LinearAlgebra.svd()\n  return U*V',V*Diagonal(S)*V'\nend\n\n", "meta": {"hexsha": "ff1aa6f42f9cb52adfe8f710d69d8ce1055241b7", "size": 2161, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tensor/svd.jl", "max_stars_repo_name": "christopherdavidwhite/ITensors.jl", "max_stars_repo_head_hexsha": "91f5c436b78c66ae54e07e44da37b5286834be1d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tensor/svd.jl", "max_issues_repo_name": "christopherdavidwhite/ITensors.jl", "max_issues_repo_head_hexsha": "91f5c436b78c66ae54e07e44da37b5286834be1d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tensor/svd.jl", "max_forks_repo_name": "christopherdavidwhite/ITensors.jl", "max_forks_repo_head_hexsha": "91f5c436b78c66ae54e07e44da37b5286834be1d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1962616822, "max_line_length": 87, "alphanum_fraction": 0.5460434984, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248208414329, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7763028963192795}}
{"text": "# Dirichlet\nstruct Dirichlet{P<:Tuple{Vararg{Real}}} <: Distribution{Tuple{Vararg{Real}},P}\n    params :: P\n    Dirichlet(; α) = new{typeof(α)}(α)\nend\n\n# Dirichlet(α::Real...) = Dirichlet(α)\n# Dirichlet(α::Integer...) = Dirichlet(Float64.(α))\n# Dirichlet(n::Integer, α::Real)= Dirichlet(ntuple(_->α, n))\n\n\nfunction randDirichlet(α::Tuple{Vararg{T}}) where T<:Real\n    p = Tuple(randGamma(αi, one(T)) for αi in α)\n    p ./ sum(p)\nend\nrandDirichlet(α::Tuple{Vararg{Integer}}) = randDirichlet(Float64.(α))\nrandDirichlet(n::Integer, α::Real) = randDirichlet(Tuple(α for _ in 1:n))\nrandDirichlet(n::Integer, α::Integer) = randDirichlet(n, Float64(α))\n\n@cufunc function logpdfDirichlet(x::NTuple{N,Real}, α::NTuple{N,Real}) where N\n    # a, b = sum(u -> SVector(u,lgamma(u)), α)\n    # s = sum(((u,v) -> (u-one(u))log(v)).(α, x))\n    # s - b + lgamma(a)\n    T = promote_type(typeof.(x)..., typeof.(α)...)\n    a = b = s = zero(T)\n    for (xi, αi) in zip(x, α)\n        a += T(αi)\n        b += lgamma(T(αi))\n        s += (T(αi) - one(T))log(T(xi))\n    end\n    s - b + lgamma(a)\nend\n", "meta": {"hexsha": "3fa4ca2d98dfe9810401047dbe1dc26f82fee609", "size": 1072, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/arrays.jl", "max_stars_repo_name": "vargonis/LightDistributions.jl", "max_stars_repo_head_hexsha": "b711b705e53c49f2a263604a00ae5fcc12c082c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-17T09:35:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T09:35:26.000Z", "max_issues_repo_path": "src/arrays.jl", "max_issues_repo_name": "vargonis/LightDistributions.jl", "max_issues_repo_head_hexsha": "b711b705e53c49f2a263604a00ae5fcc12c082c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/arrays.jl", "max_forks_repo_name": "vargonis/LightDistributions.jl", "max_forks_repo_head_hexsha": "b711b705e53c49f2a263604a00ae5fcc12c082c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4848484848, "max_line_length": 79, "alphanum_fraction": 0.5914179104, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7763028949085803}}
{"text": "using CompScienceMeshes\nusing BEAST\nusing LinearAlgebra\n\ntrias = CompScienceMeshes.meshrectangle(1.0,1.0,0.05)\ntrias = CompScienceMeshes.meshcircle(1.0,0.5)\ntetrs = CompScienceMeshes.tetmeshcuboid(1,1,1,0.2)\n\nf = BEAST.ScalarTrace(x -> sin(pi*x[1]*x[2])*sin(pi*x[2]))\nf2 = BEAST.ScalarTrace(x -> (-x[2]*sin(2*pi*(x[1]^2+x[2]^2))*sin(atan(x[2],x[1])), x[1]*sin(2*pi*(x[1]^2+x[2]^2))*sin(atan(x[2],x[1])), 0) )\ng = BEAST.ScalarTrace(x -> (sin(pi*x[1])*cos(pi*x[2]), -cos(pi*x[1])*sin(pi*x[2]), 0 ))\ng = BEAST.ScalarTrace(x -> (sin(pi*x[1])*cos(pi*x[2]), sin(pi*x[2])*cos(pi*x[2]), sin(pi*x[3])*cos(pi*x[2])))\ng2 = BEAST.ScalarTrace(x -> ( sin(pi*x[1])*cos(pi*x[3]),  0, -cos(pi*x[1])*sin(pi*x[3])))\n\n\nN = 4\n\nh = Vector(undef, N)\nerrorL = Vector(undef, N)\nerrorBDM = Vector(undef, N)\nerrorRT = Vector(undef, N)\n\nfor n in 1:N\n\n    h[n] = 0.5^(n)\n\n    trias2 = CompScienceMeshes.meshrectangle(1.0,1.0, h[n])\n    \n    trias = CompScienceMeshes.meshcircle(1.0, h[n], 3)\n\n    Z = BEAST.lagrangec0d1(trias, dirichlet=false)\n    Y = BEAST.brezzidouglasmarini(trias)\n    X = BEAST.raviartthomas(trias)\n\n    u_exact = DofInterpolate(Z,f)\n    b_exact = DofInterpolate(Y,f2)\n    r_exact = DofInterpolate(X,f2)\n\n    identity = BEAST.Identity()\n    \n    M = assemble(identity, Z, Z)\n    b = assemble(f,Z)\n    u_n = M \\ b\n\n    errorL[n] = sqrt((u_n-u_exact)'*M*(u_n-u_exact))\n\n \n    M = assemble(identity, Y, Y)\n    b = assemble(f2,Y)\n    b_n = M \\ b\n\n    errorBDM[n] = sqrt((b_n-b_exact)'*M*(b_n-b_exact))\n\n\n    M = assemble(identity, X, X)\n    b = assemble(f2,X)\n    r_n = M \\ b\n\n    errorRT[n] = sqrt((r_n-r_exact)'*M*(r_n-r_exact))\n\nend\n\nN = 15\n\ndelta = Vector(undef, N)\nerror = Vector(undef, N)\n\n\nfor i in 1:N\n\n    delta[i] = 0.5-0.025*i\n\n    tetrs =  tetmeshcuboid(1.0,1.0,1.0, delta[i])\n\n    bndry = boundary(tetrs)\n    faces = skeleton(tetrs, 2)\n\n    bndry_faces = [sort(c) for c in cells(skeleton(bndry, 2))]\n    function is_interior(faces)\n        !(sort(faces) in bndry_faces)\n    end\n\n    interior_faces = submesh(is_interior, faces)\n\n    W = BEAST.brezzidouglasmarini3d(tetrs, interior_faces)\n\n    u_exact = DofInterpolate(W,g2)\n\n    identity = BEAST.Identity()\n\n    M = assemble(identity, W, W)\n\n    b = assemble(g2,W)\n    u_n = M \\ b\n\n    error[i] = real(sqrt((u_n-u_exact)'*M*(u_n-u_exact)))\nend\n\n\nN=15\n\ndelta2 = Vector(undef, N)\nerror2 = Vector(undef, N)\n\nfor i in 1:N\n\n    delta2[i] =0.5-0.025*i\n\n    tetrs =  tetmeshcuboid(1.0,1.0,1.0, delta2[i])\n\n    bndry = boundary(tetrs)\n    faces = skeleton(tetrs, 2)\n\n    bndry_faces = [sort(c) for c in cells(skeleton(bndry, 2))]\n    function is_interior(faces)\n        !(sort(faces) in bndry_faces)\n    end\n\n    interior_faces = submesh(is_interior, faces)\n\n    V = BEAST.nedelecd3d(tetrs, interior_faces)\n    \n\n  \n    q_exact = DofInterpolate(V,g)\n\n    identity = BEAST.Identity()\n\n    M2 = assemble(identity, V, V)\n\n   \n    b2 = assemble(g,V)\n \n    q_n = M2 \\ b2\n\n   \n    error2[i] = real(sqrt((q_n-q_exact)'*M2*(q_n-q_exact)))\nend\n\nusing Plots\n\np2 = plot(delta,error, label=\"BDM3D\", title=\"L2-Error on [0,1]^3\",xlabel=\"h\", ylabel=\"Error\", legend=:bottomright, xaxis=:log, yaxis=:log)\nplot!(p2, delta2, error2, label=\"Nedelec Div\", xlims=[0.075,0.55])\n\np1 = plot(h,real(errorL), label=\"Lagrange\", title=\"L2-Error on [0,1]^2\",xlabel=\"h\", ylabel=\"Error\", legend=:bottomright, xaxis=:log, yaxis=:log, xlims=[0.025,0.5])\nplot!(p1,h,real(errorBDM),label=\"BDM\")\nplot!(p1,h,real(errorRT),label=\"Raviart-Thomas\")\n\nplot(p1,p2, layout=2)\n\n", "meta": {"hexsha": "815bbb97cd54d36876504b3f98b48ad9a80eda7f", "size": 3475, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ex_interpolation.jl", "max_stars_repo_name": "paresula/BEAST.jl", "max_stars_repo_head_hexsha": "44be41a27c6ab2cb6b9ecf43a6a90a4ff8f3488a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/ex_interpolation.jl", "max_issues_repo_name": "paresula/BEAST.jl", "max_issues_repo_head_hexsha": "44be41a27c6ab2cb6b9ecf43a6a90a4ff8f3488a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ex_interpolation.jl", "max_forks_repo_name": "paresula/BEAST.jl", "max_forks_repo_head_hexsha": "44be41a27c6ab2cb6b9ecf43a6a90a4ff8f3488a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0132450331, "max_line_length": 163, "alphanum_fraction": 0.618705036, "num_tokens": 1323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286373, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7763028934978812}}
{"text": "# ---\n# title: 892. Surface Area of 3D Shapes\n# id: problem892\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Easy\n# categories: Math, Geometry\n# link: <https://leetcode.com/problems/surface-area-of-3d-shapes/description/>\n# hidden: true\n# ---\n# \n# On a `N * N` grid, we place some `1 * 1 * 1 `cubes.\n# \n# Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of\n# grid cell `(i, j)`.\n# \n# Return the total surface area of the resulting shapes.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: [[2]]\n#     Output: 10\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: [[1,2],[3,4]]\n#     Output: 34\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: [[1,0],[0,2]]\n#     Output: 16\n#     \n# \n# **Example 4:**\n# \n#     \n#     \n#     Input: [[1,1,1],[1,0,1],[1,1,1]]\n#     Output: 32\n#     \n# \n# **Example 5:**\n# \n#     \n#     \n#     Input: [[2,2,2],[2,1,2],[2,2,2]]\n#     Output: 46\n#     \n# \n# \n# \n# **Note:**\n# \n#   * `1 <= N <= 50`\n#   * `0 <= grid[i][j] <= 50`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "f40f962021e821c2fe27379dc5cc3a523f84f80e", "size": 1086, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/892.surface-area-of-3d-shapes.jl", "max_stars_repo_name": "noob-data-analaysis/LeetCode.jl", "max_stars_repo_head_hexsha": "94d91b295e988948e77e737c10d2f0e3ecb7c2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/unresolved/892.surface-area-of-3d-shapes.jl", "max_issues_repo_name": "noob-data-analaysis/LeetCode.jl", "max_issues_repo_head_hexsha": "94d91b295e988948e77e737c10d2f0e3ecb7c2b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/unresolved/892.surface-area-of-3d-shapes.jl", "max_forks_repo_name": "noob-data-analaysis/LeetCode.jl", "max_forks_repo_head_hexsha": "94d91b295e988948e77e737c10d2f0e3ecb7c2b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.6756756757, "max_line_length": 78, "alphanum_fraction": 0.4650092081, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.7762938565704237}}
{"text": "# f.jl\n# F-tests\n#\n# Copyright (C) 2019   Raphael Saavedra\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nexport VarianceFTest\n\nstruct VarianceFTest <: HypothesisTest\n    n_x::Int   # size of sample 1\n    n_y::Int   # size of sample 2\n    df_x::Int  # degrees of freedom 1\n    df_y::Int  # degrees of freedom 2\n    F::Real    # test statistic\nend\n\n\"\"\"\n    VarianceFTest(x::AbstractVector{<:Real}, y::AbstractVector{<:Real})\n\nPerform an F-test of the null hypothesis that two real-valued vectors `x` and `y` have equal variances.\n\nImplements: [`pvalue`](@ref)\n\n# References\n\n  * George E. P. Box, \"Non-Normality and Tests on Variances\", Biometrika 40 (3/4): 318–335, 1953.\n\n# External links\n\n  * [F-test of equality of variances on Wikipedia](https://en.wikipedia.org/wiki/F-test_of_equality_of_variances)\n\"\"\"\nfunction VarianceFTest(x::AbstractVector{<:Real}, y::AbstractVector{<:Real})\n    n1, n2 = length(x), length(y)\n    F = var(x) / var(y)\n    return VarianceFTest(n1, n2, n1-1, n2-1, F)\nend\n\ntestname(::VarianceFTest) = \"Variance F-test\"\npopulation_param_of_interest(x::VarianceFTest) = (\"variance ratio\", 1.0, x.F)\ndefault_tail(test::VarianceFTest) = :both\n\nfunction show_params(io::IO, x::VarianceFTest, ident)\n    println(io, ident, \"number of observations: [$(x.n_x), $(x.n_y)]\")\n    println(io, ident, \"F statistic:            $(x.F)\")\n    println(io, ident, \"degrees of freedom:     [$(x.df_x), $(x.df_y)]\")\nend\n\nfunction pvalue(x::VarianceFTest; tail=:both)\n    dist = FDist(x.df_x, x.df_y)\n    if tail == :both\n        return 1 - 2*abs(cdf(dist, x.F) - 0.5)\n    elseif tail == :right\n        return 1 - cdf(dist, x.F)\n    elseif tail == :left\n        return cdf(dist, x.F)\n    else\n        throw(ArgumentError(\"tail=$(tail) is invalid\"))\n    end\nend\n", "meta": {"hexsha": "d4f4e367f30a18bf3230310adc1799530e272427", "size": 2776, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/f.jl", "max_stars_repo_name": "KronosTheLate/HypothesisTests.jl", "max_stars_repo_head_hexsha": "992fe205c9dcff24869d4b24cf6df847a7983329", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 221, "max_stars_repo_stars_event_min_datetime": "2015-03-09T19:11:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:12:15.000Z", "max_issues_repo_path": "src/f.jl", "max_issues_repo_name": "KronosTheLate/HypothesisTests.jl", "max_issues_repo_head_hexsha": "992fe205c9dcff24869d4b24cf6df847a7983329", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 202, "max_issues_repo_issues_event_min_datetime": "2015-02-06T20:46:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T13:29:42.000Z", "max_forks_repo_path": "src/f.jl", "max_forks_repo_name": "KronosTheLate/HypothesisTests.jl", "max_forks_repo_head_hexsha": "992fe205c9dcff24869d4b24cf6df847a7983329", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 99, "max_forks_repo_forks_event_min_datetime": "2015-02-13T13:58:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T21:48:28.000Z", "avg_line_length": 35.5897435897, "max_line_length": 113, "alphanum_fraction": 0.6995677233, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8633916082162402, "lm_q1q2_score": 0.7762938519026973}}
{"text": "\"\"\"\n    capm(asset_returns, benchmark_returns; risk_free=0.0)\n\nCalculates the CAPM α and β coefficients based on sample covariance statistics and a simple linear regression model.\n\nThe linear regression model looks as follows:\n\n        r_a - r_f = α + β(r_b - r_f) + ϵ\n\nThe α coefficient in this model is also known as Jensen's alpha. β is the slope coefficient, and ϵ is an error term.\n\n# Arguments\n- `asset_returns`:      Vector of asset returns.\n- `benchmark_returns`:  Vector of benchmark returns (e.g. market portfolio returns for CAPM beta).\n- `risk_free`:          Optional vector or scalar value denoting the risk-free return (must have same frequency as the provided returns, e.g. daily).\n\n# Returns\nTuple (α, β) with the estimated α and β coefficients of the CAPM model.\n\"\"\"\nfunction capm(asset_returns, benchmark_returns; risk_free=0.0)\n    asset_returns_ex = asset_returns .- risk_free\n    benchmark_returns_ex = benchmark_returns .- risk_free\n    μ1 = mean(asset_returns_ex)\n    μ2 = mean(benchmark_returns_ex)\n    β = sum((asset_returns_ex .- μ1).*(benchmark_returns_ex .- μ2)) / sum((benchmark_returns_ex .- μ2).^2)\n    α = μ1 - β*μ2\n    (α, β)\nend\n", "meta": {"hexsha": "479ea8828631b33fe4655bcd4791930679117082", "size": 1164, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/capm.jl", "max_stars_repo_name": "rbeeli/RiskPerf.jl", "max_stars_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-07T19:19:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T19:19:09.000Z", "max_issues_repo_path": "src/capm.jl", "max_issues_repo_name": "rbeeli/RiskPerf.jl", "max_issues_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/capm.jl", "max_forks_repo_name": "rbeeli/RiskPerf.jl", "max_forks_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1379310345, "max_line_length": 149, "alphanum_fraction": 0.7216494845, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7762919534717007}}
{"text": "function scalsq(A::AbstractArray{T,2}, b::AbstractVector{T}, w = nothing) where {T<:Number}\n#\n#  Solving the scaled least squares problem \n#          W(Ax - b) = 0\n#      with iterative refinement. \n#\n#  input  A --- the matrix\n#         b --- the right-hand side vector\n#         w --- the scaling vector (diagonal entries of W)\n#\n#      \n    m, n = size(A)\n\tE = real(one(T))\n   \n    if w == nothing\n        w = ones(T, m)\n        for j = 1:m\n            abj = abs(b[j])\n            if abj > E\n                w[j] = E / abj\n            end\n        end\n    end\n   \n    for j = 1:m\n        A[j,1:end] = A[j,1:end] * w[j]\n    end\n\n    b = b .* w\n   \n    Q, S = qr(A)\n\n    d = Q' * b\n    x = backsub(S, d)\n   \n    # one step refinement\n    bb = [b; zeros(T, n)]\n\tB = [I A; A' zeros(T, n, n)]\n    r = b - A * x\n   \n    #for j = 1:3\n    rr = bb - B * [r; x]; #disp(norm(rr));\n   \n    s = Q' * rr[1:m]\n    c = forsub(S', rr[m+1:m+n])\n\tc2 = backsub(S, s[1:n] - c)\n    #c1 = Q * [c; s[n+1:m]]\n    #r = r + c1\n    x = x + c2\n    #%end;\n    x\nend\n", "meta": {"hexsha": "c2eec7a7be927beb1c92eb58dd886f230bc1c297", "size": 1038, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scalsq.jl", "max_stars_repo_name": "KlausC/Multroot.jl", "max_stars_repo_head_hexsha": "df3978ad1af9829f644155d834a1305b73623b7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/scalsq.jl", "max_issues_repo_name": "KlausC/Multroot.jl", "max_issues_repo_head_hexsha": "df3978ad1af9829f644155d834a1305b73623b7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scalsq.jl", "max_forks_repo_name": "KlausC/Multroot.jl", "max_forks_repo_head_hexsha": "df3978ad1af9829f644155d834a1305b73623b7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5849056604, "max_line_length": 91, "alphanum_fraction": 0.4210019268, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768525822309, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7762919495972445}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.5\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ d9cff120-aba1-11eb-0f83-db8e49ac6bab\nmd\"# Chapter 03 from NNFS book\"\n\n# ╔═╡ 4a34dd2f-cbf5-4ac0-8f97-fd4050354547\nmd\"### 2 Layers of Neurons (4 inputs, 3 hidden layers)\"\n\n# ╔═╡ ab14105e-a405-4d87-80d7-940ce87ef19a\nmd\"\"\"\n**One observation:**\n\"\"\"\n\n# ╔═╡ fed9705c-b748-4cf9-827a-f10fd8073967\nbegin\t\n\t# first layer\n\tinput1 = [1, 2, 3, 2.5]\n\n\tweight1 = [\n\t\t 0.2   0.8  -0.5   1.0\n\t\t 0.5  -0.91  0.26 -0.5\n\t\t-0.26 -0.27  0.17  0.87\n\t]\n\n\tbias1 = [2, 3, 0.5]\n\n\t# second layer\n\tweight2 = [\n\t\t 0.1   -0.14   0.5\n\t\t-0.5    0.12  -0.33\n\t\t-0.44   0.73  -0.13\n\t]\n\n\tbias2 = [-1, 2, -0.5]\n\n\t# calculating layers\n\tlayer1 = weight1 * input1 + bias1\n\tlayer2 = weight2 * layer1 + bias2\nend\n\n# ╔═╡ 7ec38404-9380-411d-8b0d-f073ba5c6cbc\nmd\"\"\"\n**Multiple observations:**\n\"\"\"\n\n# ╔═╡ 773a22f6-99c3-4bf5-936b-0b22759038ed\nbegin\t\n\t# first layer\n\tinp01 = [\n\t\t[1, 2, 3, 2.5] [2, 5, -1, 2] [-1.5, 2.7, 3.3, -0.8]\n\t]\n\n\tw01 = [\n\t\t 0.2   0.8  -0.5   1.0\n\t\t 0.5  -0.91  0.26 -0.5\n\t\t-0.26 -0.27  0.17  0.87\n\t]\n\n\tb01 = [2, 3, 0.5]\n\n\t# second layer\n\tw02 = [\n\t\t 0.1   -0.14   0.5\n\t\t-0.5    0.12  -0.33\n\t\t-0.44   0.73  -0.13\n\t]\n\n\tb02 = [-1, 2, -0.5]\n\n\t# calculating layers\n\tlayer01 = w01 * inp01 .+ b01\n\tlayer02 = w02 * layer01 .+ b02\nend\n\n# ╔═╡ 6aabd18d-d0a1-4f7e-9019-92d7671e7265\nmd\"### Creating the LayerDense Struct\"\n\n# ╔═╡ 50edc678-40c3-483c-8556-666f01553802\nbegin\n\tstruct LayerDense\n\t\tw::Matrix{Float64}\n\t\tb::Vector{Float64}\n\t\tfunction LayerDense(n_in::Int, n_out::Int)\n\t\t\tw = 0.01 * randn(n_out, n_in)\n\t\t\tb = zeros(n_out)\n\t\t\treturn new(w, b)\n\t\tend\n\tend\n\t\n\t(layer::LayerDense)(input) = layer.w * input .+ layer.b\nend\n\n# ╔═╡ da9d7fdb-8b5a-466c-9370-654c133e10a3\nD = LayerDense(2, 3)\n\n# ╔═╡ 173fe819-779e-4d8e-a2b3-e00fb9363cb2\nimp01 = [3.5, 4.3]\n\n# ╔═╡ c14fce98-4470-4153-ba62-75521c3e5ed8\nimp02 = [[3.5, 4.3] [2.4, -2.8]]\n\n# ╔═╡ f8915121-453b-49bc-83ed-07ea13541160\nD(imp01)\n\n# ╔═╡ ffe4c9ac-bbbf-49e0-b882-b6a8ed096622\nD(imp02)\n\n# ╔═╡ ae0e3918-c07e-40a5-880d-15cec3afce71\nD(randn(2))\n\n# ╔═╡ Cell order:\n# ╟─d9cff120-aba1-11eb-0f83-db8e49ac6bab\n# ╟─4a34dd2f-cbf5-4ac0-8f97-fd4050354547\n# ╟─ab14105e-a405-4d87-80d7-940ce87ef19a\n# ╠═fed9705c-b748-4cf9-827a-f10fd8073967\n# ╟─7ec38404-9380-411d-8b0d-f073ba5c6cbc\n# ╠═773a22f6-99c3-4bf5-936b-0b22759038ed\n# ╟─6aabd18d-d0a1-4f7e-9019-92d7671e7265\n# ╠═50edc678-40c3-483c-8556-666f01553802\n# ╠═da9d7fdb-8b5a-466c-9370-654c133e10a3\n# ╠═173fe819-779e-4d8e-a2b3-e00fb9363cb2\n# ╠═c14fce98-4470-4153-ba62-75521c3e5ed8\n# ╠═f8915121-453b-49bc-83ed-07ea13541160\n# ╠═ffe4c9ac-bbbf-49e0-b882-b6a8ed096622\n# ╠═ae0e3918-c07e-40a5-880d-15cec3afce71\n", "meta": {"hexsha": "1a7004b26bb6610545a12d41f6c9ec406a06c03e", "size": 2628, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapters/Chapter03.jl", "max_stars_repo_name": "AugustoCL/Neural_Network_From_Scratch_in_Julia", "max_stars_repo_head_hexsha": "33f0f479c2e935b179306418e860dfa4e7cec07b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-20T16:40:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T16:40:27.000Z", "max_issues_repo_path": "Chapters/Chapter03.jl", "max_issues_repo_name": "AugustoCL/Neural_Network_From_Scratch_in_Julia", "max_issues_repo_head_hexsha": "33f0f479c2e935b179306418e860dfa4e7cec07b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapters/Chapter03.jl", "max_forks_repo_name": "AugustoCL/Neural_Network_From_Scratch_in_Julia", "max_forks_repo_head_hexsha": "33f0f479c2e935b179306418e860dfa4e7cec07b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2153846154, "max_line_length": 56, "alphanum_fraction": 0.6396499239, "num_tokens": 1493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7762821114932816}}
{"text": "# This file is pat of RLinearAlgebra.jl\n# 1. Specifies type\n# 2. Implements rsubsolve function\n# 3. Exports Type\n\n#using LinearAlgebra\n\n\"\"\"\n    LinSysVecColProjPO <: LinSysVecColProjection\n\nA mutable structure that represents the standard column projection method\n    with orthogonalization of the current projection against a set of `m` previous\n    projection directions, where `m` is specified by the user.\n\nSee Patel, Vivak, Mohammad Jahangoshahi, and Daniel Adrian Maldonado. \"An Implicit\n    Representation and Iterative Solution of Randomly Sketched Linear Systems.\"\n    SIAM Journal on Matrix Analysis and Applications (2021) 42:2, 800-831.\n    https://doi.org/10.1137/19M1259481\n\n# Fields\n\n- `α::Float64`, the relaxation parameter (usually between `0.0` and `2.0`)\n- `m::Int64`, the number of previous directions against which to orthogonalize\n- `Z::Union{Vector{Vector{Float64}}, Nothing}`, stores the `m` vectors against which the\n    current projection is orthogonalized against\n\nCalling `LinSysVecColProjPO()` defaults the relaxation parameter to `1.0`, the memory\n    parameter `m` to `5`, and `Z` to `nothing`.\n\"\"\"\nmutable struct LinSysVecColProjPO <: LinSysVecColProjection\n    α::Float64\n    m::Int64\n    Z::Union{Vector{Vector{Float64}}, Nothing}\nend\nLinSysVecColProjPO() = LinSysVecColProjPO(1.0, 5, nothing)\n\n# Common rsubsolve interface for linear systems\nfunction rsubsolve!(\n    type::LinSysVecColProjPO,\n    x::AbstractVector,\n    samp::Tuple{U,V,W} where {U<:AbstractVector,V<:AbstractArray,W<:Real},\n    iter::Int64,\n)\n    # samp[1] is the search direction\n    # samp[2] is the coefficient matrix, A\n    # samp[3] is a projection of the residual of normal system, samp[1]' * A' * (A * x - b)\n\n    # Allocate space for orthogonalization set Z\n    if iter == 1\n        d = length(x)\n        type.Z = Vector{Float64}[zeros(Float64, d) for i in 1:type.m]\n    end\n\n    # Compute orthogonal complement of A' * A * samp[1] using modified Gram-Schmidt\n    u = samp[2]' * (samp[2] * samp[1])\n    for z in type.Z\n        u = u - dot(z, u) * z\n    end\n\n    # Check whether vector u is nearly zero\n    nrmUsq = dot(u, u)\n    if nrmUsq < eps() * length(x); return nothing; end\n\n    # Otherwise, update iterate\n    x .= x - u * (type.α * samp[3] / nrmUsq )\n\n    # Update orthonormal set\n    z = u / sqrt(nrmUsq)\n    type.Z .= push!(type.Z[2:end], z)\n\n    return nothing\nend\n", "meta": {"hexsha": "9e79e2ace9472f4e14a2253094fd370916376aff", "size": 2386, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear_solver_routines/vec_col_projection_portho.jl", "max_stars_repo_name": "numlinalg/RLinearAlgebra.jl", "max_stars_repo_head_hexsha": "757cc7e581303c4fb6db228618f4be5caa02d3b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-05-28T17:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T05:23:14.000Z", "max_issues_repo_path": "src/linear_solver_routines/vec_col_projection_portho.jl", "max_issues_repo_name": "numlinalg/RLinearAlgebra.jl", "max_issues_repo_head_hexsha": "757cc7e581303c4fb6db228618f4be5caa02d3b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-06-16T16:01:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-16T12:28:20.000Z", "max_forks_repo_path": "src/linear_solver_routines/vec_col_projection_portho.jl", "max_forks_repo_name": "numlinalg/RLinearAlgebra.jl", "max_forks_repo_head_hexsha": "757cc7e581303c4fb6db228618f4be5caa02d3b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6849315068, "max_line_length": 91, "alphanum_fraction": 0.6865046102, "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7762821005343471}}
{"text": "function bounded_log_grid(xMin::Float64, xMax::Float64, steps::Int)\n  result = zeros(steps + 1)\n  gridLogSpacing = (log(xMax) - log(xMin)) / steps\n  edx = exp(gridLogSpacing)\n  result[1] = xMin\n  for j = 2:steps+1\n    result[j] = result[j-1] * edx\n  end\n\n  return result\nend\n", "meta": {"hexsha": "7d266958646cb969dac87ef76d8cf07ff3ff4cbb", "size": 275, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/grid.jl", "max_stars_repo_name": "JuliaQuant/QuantLib.jl", "max_stars_repo_head_hexsha": "b1a806daa3b15b1f3705e36f716e66cc24c1dd5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2016-03-07T07:29:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T09:43:02.000Z", "max_issues_repo_path": "src/math/grid.jl", "max_issues_repo_name": "JuliaQuant/QuantLib.jl", "max_issues_repo_head_hexsha": "b1a806daa3b15b1f3705e36f716e66cc24c1dd5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/grid.jl", "max_forks_repo_name": "JuliaQuant/QuantLib.jl", "max_forks_repo_head_hexsha": "b1a806daa3b15b1f3705e36f716e66cc24c1dd5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-03-09T08:33:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T18:21:38.000Z", "avg_line_length": 22.9166666667, "max_line_length": 67, "alphanum_fraction": 0.6618181818, "num_tokens": 97, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7762106236940604}}
{"text": "# This script provides an example of simulating changepoint data,\n# using PELT to find these changepoints, and plotting the results\n#\n# Requires Plots package\n\nusing Distributions, Plots\nusing Changepoints\n\n#########################\n# Simulate changepoints #\n#########################\n\nn = 1000        # Length of sample\nλ = 100         # Frequencey of changes\n\n# Mu parameter sampled from a N(0,10) distribution for each changepoint\nμ = Normal(0,5) \nσ = 1.0 # Sigma parameter fixed\n\n# Construct sample with changepoints where\n# at each changepoint a new value is sample for μ\nsample, cps = @changepoint_sampler n λ Normal(μ, σ)\n\n########################\n# Finding changepoints #\n########################\n\n# Find changepoints via PELT\n# assuming Normal likelihood with changing mean\n# parameter and fixed standard deviation of σ\npelt_cps, pelt_cost = @PELT sample Normal(:?, σ)\n\n# Find changepoints via Binary Segmentation\nbs_cps, bs_cost = @BS sample Normal(:?, σ)\n\n# If plotting multiple sets of changepoints which need to labelled\n# separately, it is best not to use `changepoint_plot` function\n# but to instead first plot data\n# and then add changepoints with `vline!` function\np = plot(sample, label=\"Simulated data\")\nvline!(p, cps, label=\"True changepoints\")\nvline!(p, pelt_cps, label=\"PELT changepoints\")\nvline!(p, bs_cps, label=\"BS changepoints\")\ndisplay(p)\n", "meta": {"hexsha": "f3261e5b9d79e94631b0742fa39b09baf46d532f", "size": 1366, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/example_1.jl", "max_stars_repo_name": "STOR-i/Changepoints.jl", "max_stars_repo_head_hexsha": "b5f939b6adabce227d4069e154a912c5f30c7432", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2016-02-16T02:11:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T20:06:08.000Z", "max_issues_repo_path": "docs/example_1.jl", "max_issues_repo_name": "STOR-i/Changepoints.jl", "max_issues_repo_head_hexsha": "b5f939b6adabce227d4069e154a912c5f30c7432", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2015-03-06T14:58:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-11T14:15:04.000Z", "max_forks_repo_path": "docs/example_1.jl", "max_forks_repo_name": "STOR-i/Changepoints.jl", "max_forks_repo_head_hexsha": "b5f939b6adabce227d4069e154a912c5f30c7432", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2016-02-16T15:51:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T12:25:17.000Z", "avg_line_length": 30.3555555556, "max_line_length": 71, "alphanum_fraction": 0.6947291362, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654263, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.7762106208654928}}
{"text": "export  calculateMultiIndices,\n        findUnivariateIndices\n\nfunction calculateMultiIndices(d::Int, n::Int)\n    # d denotes dimension of random variables/number of sources of uncertainty,\n    # n the maximum degree of multivariate basis\n    # function to calculate indices of multivariate basis following the algorithm\n    # from \"Spectral Methods for Uncertainty Quantiﬁcation; Le Maitre, Knio;2014\" p.516-517\n    # No::BigInt = factorial(BigInt(d+n))/(factorial(Bigint(d))*factorial(BigInt(n)));  #number of polynomials of multivariate basis\n  n < 0 && throw(DomainError(n, \"maximum degree must be non-negative\"))\n  d <= 0 && throw(DomainError(d, \"number of uncertainties must be positive\"))\n  # catch case n == 0 --> No-d==0\n  n == 0 && return zeros(Int64,1,d)\n  # non-pathological cases begin here\n  No = numberPolynomials(d,n)\n  inds = vcat(zeros(Int64,1,d),Matrix(1I,d,d),zeros(Int64, No-d-1, d));  #initiate index matrix for basis\n  pi=ones(Int64,No,d);\n\n  for k in 2:No\n    g = 0;\n    for l in 1:d\n      pi[k,l]=sum(pi[k-1,:])-g;\n      g=g+pi[k-1,l];\n    end\n  end\n\n  P = d + 1;\n  for k in 2:n\n    L = P;\n    for j in 1:d, m in L-pi[k,j]+1:L\n        P += 1;\n        inds[P,:] = inds[m,:];\n        inds[P,j] = inds[P,j]+1;\n    end\n  end\n\n  return inds\nend\n\n\"\"\"\n    computes the number of polynomials with a multivariate basis\n    `(d+n)!/(d!+n!)`\n\"\"\"\n\nfunction numberPolynomials(d::Int64, n::Int64)\n    x, y = max(d,n), min(d,n)\n    return UInt128(prod(UInt128(x+1):UInt128(d+n)) ÷ factorial(UInt128(y)))\nend\n\n\"\"\"\n    findUnivariateIndices(i::Int,ind::AbstractMatrix{Int64,2})\nGiven the multi-index `ind` this function returns all entries of the multivariate basis\nthat correspond to the `i`th univariate basis.\n\"\"\"\nfunction findUnivariateIndices(i::Int,ind::AbstractMatrix{Int})\n  l,p = size(ind)\n  i > p && throw(DomainError((i,p), \"basis is $p-variate, you requested $i-variate\"))\n  deg = ind[end,end]\n  deg < 0 && throw(DomainError(deg, \"invalid degree\"))\n  col = ind[:,i]\n  myind = zeros(Int64,deg)\n  for deg_ in 1:deg\n      myind[deg_] = findfirst(x->x==deg_,col)\n  end\n  pushfirst!(myind,1)\nend\n", "meta": {"hexsha": "18f5eedb90363878ed9ffe8058c21eb3bdcc8264", "size": 2110, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/multi_indices.jl", "max_stars_repo_name": "adriangrupp/PolyChaos.jl", "max_stars_repo_head_hexsha": "d0091cc575456721b5f4c20dd219ce3789d889bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71, "max_stars_repo_stars_event_min_datetime": "2019-02-08T15:13:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T09:48:18.000Z", "max_issues_repo_path": "src/multi_indices.jl", "max_issues_repo_name": "adriangrupp/PolyChaos.jl", "max_issues_repo_head_hexsha": "d0091cc575456721b5f4c20dd219ce3789d889bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 55, "max_issues_repo_issues_event_min_datetime": "2019-02-08T12:21:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T20:21:46.000Z", "max_forks_repo_path": "src/multi_indices.jl", "max_forks_repo_name": "adriangrupp/PolyChaos.jl", "max_forks_repo_head_hexsha": "d0091cc575456721b5f4c20dd219ce3789d889bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-03-20T08:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T14:25:42.000Z", "avg_line_length": 31.4925373134, "max_line_length": 132, "alphanum_fraction": 0.6511848341, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7762106208654928}}
{"text": "# Implicitly solve heat equation: ∂_t T = α * ∇²(T) + β*sin(γ*z)\n# Boundary conditions: ∇T(z=a) = ∇T_bottom, T(z=b) = T_top\nimport Plots\nusing LinearAlgebra\nusing DiffEqBase\nusing OrdinaryDiffEq: SplitODEProblem, solve, IMEXEuler\nimport SciMLBase\n\na,b, n = 0, 1, 10               # zmin, zmax, number of cells\nn̂_min, n̂_max = -1, 1            # Outward facing unit vectors\nα = 100;                        # thermal diffusivity, larger means more stiff\nβ, γ = 10000, π;                # source term coefficients\nΔt = 1000;                      # timestep\nN_t = 10;                       # number of timesteps\nFT = Float64;                   # float type\nΔz = FT(b-a)/FT(n)\nΔz² = Δz^2;\n∇²_op = [1/Δz², -2/Δz², 1/Δz²]; # row or Laplacian operator\n∇T_bottom = 10;                 # Temperature gradient at the top\nT_top = 1;                      # Temperature at the bottom\nS(z) = β*sin(γ*z)               # source term, (sin for easy integration)\nzf = range(a, b, length=n+1);\nzc = map(i-> zf[i]+Δz/2, 1:n);\n\nfunction T_analytic(z) # Analytic steady state solution\n    c1 = ∇T_bottom-β*cos(γ*a)/(γ*α)\n    c2 = T_top-(β*sin(γ*b)/(γ^2*α)+c1*b)\n    return β*sin(γ*z)/(γ^2*α)+c1*z+c2\nend\n\nT = zeros(FT, n+1);\n\n# Equations: derivation to matrix form\n# ∂_t T = α * ∇²(T) + S\n# (T^{n+1}-T^n) = Δt (α * ∇²(T^{n+1}) + S)\n# (T^{n+1} - Δt α * ∇²(T^{n+1})) = T^n + Δt*S\n# (I - Δt α * ∇²) T^{n+1} = T^n + Δt*S\n\n# Derive Dirichlet boundary stencil & source:\n# ∂_t T = α * (T[i-1]+T[b]-2*T[i])/Δz² + S\n# ∂_t T = α * (T[i-1]-2*T[i])/Δz² + S + α * T[b] / Δz²\n\n# Derive Neumann boundary stencil & source:\n# ∇T_bottom*n̂= (T[g] - T[i])/(2Δz),     n̂ = [-1,1] ∈ [zmin,zmax]\n# T[i] + 2*Δz*∇T_bottom*n̂ = T[g]\n# ∂_t T = α * (((T[i] + 2*Δz*∇T_bottom*n̂) - T[b])/Δz - (T[b] - T[i])/Δz)/Δz + S\n# ∂_t T = α * (((T[i]) - T[b])/Δz - (T[b] - T[i])/Δz)/Δz + S + α/Δz²*2*Δz*∇T_bottom*n̂\n# ∂_t T = α * (2*T[i] - 2*T[b])/Δz² + S + 2α/Δz*∇T_bottom*n̂\n∇² = Tridiagonal(\n    ones(FT, n) .* ∇²_op[1],\n    ones(FT, n+1)   .* ∇²_op[2],\n    ones(FT, n) .* ∇²_op[3]\n);\n\n# Modify boundary stencil to account for BCs\n∇².d[1] = -2/Δz²\n∇².du[1] = +2/Δz²\n\n# Modify boundary stencil to account for BCs\n∇².du[n] = 0  # modified stencil\n∇².d[n+1] = 0 # to ensure `∂_t T = 0` at `z=zmax`\n∇².dl[n] = 0  # to ensure `∂_t T = 0` at `z=zmax`\n\n# Compute boundary source: α * T[b] / Δz²\nAT_b = zeros(FT, n+1);\nAT_b[1] = α*2/Δz*∇T_bottom*n̂_min;\nAT_b[end-1] = α*T_top/Δz²;\n\n# Set initial condition:\nT .= 1;\nT[n+1] = T_top # set top BC\n\nfunction rhs!(dT, T, params, t)\n    n = params.n\n    i = 1:n # interior domain\n    dT[i] .= S.(zf[i]) .+ AT_b[i]\n    return dT\nend\n\nD = α .* ∇²\n\nparams = (;n)\n\ntspan = (FT(0), N_t*FT(Δt))\n\nprob = SplitODEProblem(\n    SciMLBase.DiffEqArrayOperator(\n        D,\n    ),\n    rhs!,\n    T,\n    tspan,\n    params\n)\n\nprintln(\"Solving...\")\n\nalg = IMEXEuler(linsolve=LinSolveFactorize(lu!))\n\nsol = solve(\n    prob,\n    alg,\n    dt = Δt,\n    saveat = range(FT(0), N_t*FT(Δt), length=5),\n    progress = true,\n    progress_message = (dt, u, p, t) -> t,\n);\n\nT_end = sol.u[end]\n\np1 = Plots.plot(zf, T_analytic.(zf), label=\"analytic\", markershape=:circle, markersize=6)\np1 = Plots.plot!(p1, zf, T_end, label=\"numerical\", markershape=:diamond)\np1 = Plots.plot!(p1, title=\"T ∈ cell faces\")\n\np2 = Plots.plot(zf, abs.(T_end .- T_analytic.(zf)), label=\"error\", markershape=:circle, markersize=6)\np2 = Plots.plot!(p2, title=\"T ∈ cell faces\")\n\nPlots.plot(p1, p2)\n", "meta": {"hexsha": "ff06c0f52d21130f45c0b77a49df2b1df5512c1d", "size": 3416, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "heat_implicit_diffeq.jl", "max_stars_repo_name": "CliMA/MinimumWorkingExamples.jl", "max_stars_repo_head_hexsha": "ff359bcec17c4158379a94d9fee71087888027dc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-05T07:11:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T07:11:08.000Z", "max_issues_repo_path": "heat_implicit_diffeq.jl", "max_issues_repo_name": "CliMA/MinimumWorkingExamples.jl", "max_issues_repo_head_hexsha": "ff359bcec17c4158379a94d9fee71087888027dc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "heat_implicit_diffeq.jl", "max_forks_repo_name": "CliMA/MinimumWorkingExamples.jl", "max_forks_repo_head_hexsha": "ff359bcec17c4158379a94d9fee71087888027dc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-08T22:58:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T22:58:43.000Z", "avg_line_length": 28.7058823529, "max_line_length": 101, "alphanum_fraction": 0.550058548, "num_tokens": 1465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7762106208654928}}
{"text": "function pythagorean_triplets(N::Int)::Array{Tuple{Int,Int,Int},1}\n    # Return all (a,b,c) such that:\n    # a + b + c = N\n    # a^2 + b^2 = c^2\n    # a < b < c\n\n    # Pythagorean triplets: Euclid did this a while ago\n    # a = m^2 - n^2, b = 2mn, c = m^2 + n^2\n    # so a + b + c = 2m^2 + 2mn = N\n    # m(m + n) = N/2: not nice for generation, so let's give up and filter by it instead\n    #\n    # Need to take care of int multiples so also k.*(a,b,c) => km(m+n) = N/2 too\n    # => N/2 / m(m+n) is an integer: divrem(N/2,m(m+n))\n    \n    # TODO / exercise for the reader: ensure bounds on N/2 are as tight as they can be\n    sort!(triple.(Iterators.filter(x->conditions(x[1],x[2],N),Iterators.product(1:N/2,1:N/2)),N) |> unique; by=x->x[1])\nend\n\nfunction conditions(m,n,N)\n    m > n > 0 &&\n    rem(N/2,m*(m+n)) == 0\nend\n\ntriple(t,N) = triple(t[1],t[2],N)\n\n# We only make the triple of answers that we know will work so there's no point optimising this\ntriple(m,n,N) = div(N/2,m*(m+n)).*sort!((m^2 - n^2, 2m*n, m^2 + n^2) |> collect) |> Tuple{Int,Int,Int}\n\n# This is vastly faster than mine, it's not fair\n# https://exercism.io/tracks/julia/exercises/pythagorean-triplet/solutions/369f511a364d4ce0b9c054c55b49d8d8\nfunction pythagorean_triplets(x::Int)\n\n\ttriplets = Array{Tuple{Int64,Int64,Int64}}(undef, 0)\n\tfor a in 1:(x ÷ 3)\n\t\tfor b in (a+1):(x ÷ 2 + 1)\n\n\t\t\tc = x - a - b\n\t\t\tif (a*a + b*b == c*c)\n\t\t\t\tpush!(triplets, (a, b, c))\n\t\t\tend\n\t\tend\n\tend\n\treturn triplets\nend\n", "meta": {"hexsha": "7808416467d3bb5c43868e18838d06fac66ebce5", "size": 1469, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "pythagorean-triplet/pythagorean-triplet.jl", "max_stars_repo_name": "bovine3dom/exercism-julia", "max_stars_repo_head_hexsha": "9794db44d862fefb21c178d7c28e6af615185685", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pythagorean-triplet/pythagorean-triplet.jl", "max_issues_repo_name": "bovine3dom/exercism-julia", "max_issues_repo_head_hexsha": "9794db44d862fefb21c178d7c28e6af615185685", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pythagorean-triplet/pythagorean-triplet.jl", "max_forks_repo_name": "bovine3dom/exercism-julia", "max_forks_repo_head_hexsha": "9794db44d862fefb21c178d7c28e6af615185685", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6444444444, "max_line_length": 119, "alphanum_fraction": 0.5983662355, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7762106141812429}}
{"text": "# This file investigates integration error with respect to free variables in 1D integration \n\nusing FractalTools \nusing Makie \n\n# Construct interpolation data \nf(x) = sin(2π * x) + 1            \ndx   = 0.1                              \nxi   = 0.                               \nxf   = 1.                               \nx    = collect(xi : dx : xf)            \ny    = f.(x)                            \npts  = collect.(zip(x, y))     \n\n# Compute errors \nfval = (cos(2π * xi) - cos(2π * xf)) / (2π) + (xf - xi)\nfreevars = 0.001 : 0.01 : 0.999\nmse = map(freevars) do freevar \n    ival = integrate(pts, Interp1D(freevar))\n    abs(fval - ival)\nend \n\n# Plot mse \nfig = Figure() \nax = fig[1, 1] = Axis(fig, xlabel=\"Free Variable\", ylabel=\"Integration Error\", title=\"1D Integration Error\") \nstem!(ax, freevars, mse, color=:black)\nsave(joinpath(@__DIR__, \"integ1d_error.png\"), fig)\ndisplay(fig)\n\n", "meta": {"hexsha": "25a23e2c3676a5b380e8196bbc0157fd454ad45a", "size": 885, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiment_1/integration_error_vs_freevars/integ1d/integ1d.jl", "max_stars_repo_name": "zekeriyasari/FractalTools.jl", "max_stars_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-08T12:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T12:50:16.000Z", "max_issues_repo_path": "experiment_2/integration_error_vs_freevars/integ1d/integ1d.jl", "max_issues_repo_name": "zekeriyasari/FractalTools.jl", "max_issues_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-09-05T18:22:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T10:09:46.000Z", "max_forks_repo_path": "experiment_2/integration_error_vs_freevars/integ1d/integ1d.jl", "max_forks_repo_name": "zekeriyasari/FractalTools.jl", "max_forks_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5, "max_line_length": 109, "alphanum_fraction": 0.5344632768, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850128595114, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7761229887440012}}
{"text": "using Revise\nusing AdFem\nusing LinearAlgebra\nusing PyPlot\n\nm = 50\nn = 50\nh = 1/n\n\nbdedge = bcedge(\"top\", m, n, h)\nbdnode = bcnode(\"left|right|bottom\", m, n, h)\n\nF1 = eval_f_on_gauss_pts((x,y)->3.0, m, n, h)\nF2 = eval_f_on_gauss_pts((x,y)->-1.0, m, n, h)\nF = compute_fem_source_term(F1, F2, m, n, h)\n\nt1 = eval_f_on_boundary_edge((x,y)->-x-y, bdedge, m, n, h)\nt2 = eval_f_on_boundary_edge((x,y)->2y, bdedge, m, n, h)\nT = compute_fem_traction_term([t1 t2], bdedge, m, n, h)\n\nD = constant(diagm(0=>[1,1,0.5]))\nK = compute_fem_stiffness_matrix(D, m, n, h)\nrhs = T - F \nbdval = [eval_f_on_boundary_node((x,y)->x^2+y^2, bdnode, m, n, h);\n        eval_f_on_boundary_node((x,y)->x^2-y^2, bdnode, m, n, h)]\nDOF = [bdnode;bdnode .+ (m+1)*(n+1)]\nK, rhs = impose_Dirichlet_boundary_conditions(K, rhs, DOF, bdval)\nu = K\\rhs\nsess = Session(); init(sess)\nS = run(sess, u)\n\n\nfigure(figsize=[10,4])\nsubplot(121)\nvisualize_scalar_on_fem_points(S[1:(m+1)*(n+1)], m, n, h)\nsubplot(122)\nvisualize_scalar_on_fem_points(S[(m+1)*(n+1)+1:2(m+1)*(n+1)], m, n, h)\nsavefig(\"numerical.png\")\n\nfigure(figsize=[10,4])\nx = LinRange(0, 1, 50)\nX = zeros(50, 50)\nY = zeros(50, 50)\nfor i = 1:50\n    for j = 1:50\n        X[i,j] = x[i]\n        Y[i,j] = x[j]\n    end\nend\nsubplot(121)\nXY = fem_nodes(m, n, h)\nX = XY[:,1]\nY = XY[:,2]\nU = (@. X^2+Y^2)\nV = (@. X^2-Y^2)\nsubplot(121)\nvisualize_scalar_on_fem_points(U, m, n, h)\nsubplot(122)\nvisualize_scalar_on_fem_points(V, m, n, h)\nsavefig(\"exact.png\")\n\n\n\nfigure(figsize=[10,4])\nsubplot(121)\nvisualize_scalar_on_fem_points(U-S[1:(m+1)*(n+1)], m, n, h)\nsubplot(122)\nvisualize_scalar_on_fem_points(V-S[(m+1)*(n+1)+1:2(m+1)*(n+1)], m, n, h)\nsavefig(\"difference.png\")", "meta": {"hexsha": "0753934fd70bff437dc74781c59c5076b95ba7e7", "size": 1669, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/codes/LinearElasticity/structured_forward.jl", "max_stars_repo_name": "kailaix/AdFem.jl", "max_stars_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2020-10-18T01:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:13:24.000Z", "max_issues_repo_path": "docs/src/codes/LinearElasticity/structured_forward.jl", "max_issues_repo_name": "kailaix/AdFem.jl", "max_issues_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-10-19T03:51:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:38:46.000Z", "max_forks_repo_path": "docs/src/codes/LinearElasticity/structured_forward.jl", "max_forks_repo_name": "kailaix/AdFem.jl", "max_forks_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-11-05T11:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T19:30:09.000Z", "avg_line_length": 24.1884057971, "max_line_length": 72, "alphanum_fraction": 0.6315158778, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7761229774185863}}
{"text": "_tri(t, period) = (2 / π) * abs(asin(sin(π * (t - 1) / period)))\n_sin(t, period) = abs(sin(π * (t - 1) / period))\n_cycle(λ0, λ1, g) = abs(λ0 - λ1) * g + min(λ0, λ1)\n\n\"\"\"\n    Triangle{T, S<:Integer}(range0, range1, period)\n    Triangle(;λ0, λ1, period)\n\nA [triangle wave](https://en.wikipedia.org/wiki/Triangle_wave) schedule\nwith `period`.\nThe output conforms to\n```text\nabs(λ0 - λ1) * (2 / π) * abs(asin(sin(π * (t - 1) / period))) + min(λ0, λ1)\n```\n\n# Arguments\n- `range0`/`λ0`: the first range endpoint\n- `range1`/`λ1`: the second range endpoint\n- `period::Integer`: the period\n\"\"\"\nstruct Triangle{T, S<:Integer}\n    range0::T\n    range1::T\n    period::S\nend\nTriangle(;λ0, λ1, period) = Triangle(λ0, λ1, period)\n\n(schedule::Triangle)(t) = _cycle(schedule.range0, schedule.range1, _tri(t, schedule.period))\n\nBase.eltype(::Type{<:Triangle{T}}) where T = T\nBase.IteratorSize(::Type{<:Triangle}) = Base.IsInfinite()\n\nBase.iterate(schedule::Triangle, t = 1) = schedule(t), t + 1\n\nBase.axes(::Triangle) = (OneToInf(),)\n\n\"\"\"\n    TriangleDecay2{T, S<:Integer}(range0, range1, period)\n    TriangleDecay2(;λ0, λ1, period)\n\nA [triangle wave](https://en.wikipedia.org/wiki/Triangle_wave) schedule\nwith `period` and half the amplitude each cycle.\nThe output conforms to\n```text\nabs(λ0 - λ1) * Triangle(t) / (2^floor((t - 1) / period)) + min(λ0, λ1)\n```\nwhere `Triangle(t)` is `(2 / π) * abs(asin(sin(π * (t - 1) / schedule.period)))` (see [`Triangle`](#)).\n\n# Arguments\n- `range0`/`λ0`: the first range endpoint\n- `range1`/`λ1`: the second range endpoint\n- `period::Integer`: the period\n\"\"\"\nstruct TriangleDecay2{T, S<:Integer}\n    range0::T\n    range1::T\n    period::S\nend\nTriangleDecay2(;λ0, λ1, period) = TriangleDecay2(λ0, λ1, period)\n\n(schedule::TriangleDecay2)(t) = _cycle(schedule.range0, schedule.range1,\n                                       _tri(t, schedule.period) / (2^fld(t - 1, schedule.period)))\n\nBase.eltype(::Type{<:TriangleDecay2{T}}) where T = T\nBase.IteratorSize(::Type{<:TriangleDecay2}) = Base.IsInfinite()\n\nBase.iterate(schedule::TriangleDecay2, t = 1) = schedule(t), t + 1\n\nBase.axes(::TriangleDecay2) = (OneToInf(),)\n\n\"\"\"\n    TriangleExp{T, S<:Integer}(range0, range1, period, decay)\n    TriangleExp(λ0, λ1, period, γ)\n    TriangleExp(;λ0, λ1, period, γ)\n\nA [triangle wave](https://en.wikipedia.org/wiki/Triangle_wave) schedule\nwith `period` and an exponentially decaying amplitude.\nThe output conforms to\n```text\nabs(λ0 - λ1) * Triangle(t) * γ^(t - 1) + min(λ0, λ1)\n```\nwhere `Triangle(t)` is `(2 / π) * abs(asin(sin(π * (t - 1) / schedule.period)))` (see [`Triangle`](#)).\n\n# Arguments\n- `range0`/`λ0`: the first range endpoint\n- `range1`/`λ1`: the second range endpoint\n- `period::Integer`: the period\n- `decay`/`γ`: the decay rate\n\"\"\"\nstruct TriangleExp{T, S<:Integer}\n    range0::T\n    range1::T\n    period::S\n    decay::T\nend\nTriangleExp(;λ0, λ1, period, γ) = TriangleExp(λ0, λ1, period, γ)\n\nstartvalue(schedule::TriangleExp) = schedule.tri.λ0\nendvalue(schedule::TriangleExp) = schedule.tri.λ1\n(schedule::TriangleExp)(t) = _cycle(schedule.range0, schedule.range1,\n                                    _tri(t, schedule.period) * schedule.decay^(t - 1))\n\nBase.eltype(::Type{<:TriangleExp{T}}) where T = T\nBase.IteratorSize(::Type{<:TriangleExp}) = Base.IsInfinite()\n\nBase.iterate(schedule::TriangleExp, t = 1) = schedule(t), t + 1\n\nBase.axes(::TriangleExp) = (OneToInf(),)\n\n\"\"\"\n    Sin{T, S<:Integer}(range0, range1, period)\n    Sin(;λ0, λ1, period)\n\nA sine wave schedule with `period`.\nThe output conforms to\n```text\nabs(λ0 - λ1) * abs(sin(π * (t - 1) / period)) + min(λ0, λ1)\n```\n\n# Arguments\n- `range0`/`λ0`: the first range endpoint\n- `range1`/`λ1`: the second range endpoint\n- `period::Integer`: the period\n\"\"\"\nstruct Sin{T, S<:Integer}\n    range0::T\n    range1::T\n    period::S\nend\nSin(;λ0, λ1, period) = Sin(λ0, λ1, period)\n\n(schedule::Sin)(t) = _cycle(schedule.range0, schedule.range1, _sin(t, schedule.period))\n\nBase.eltype(::Type{<:Sin{T}}) where T = T\nBase.IteratorSize(::Type{<:Sin}) = Base.IsInfinite()\n\nBase.iterate(schedule::Sin, t = 1) = schedule(t), t + 1\n\nBase.axes(::Sin) = (OneToInf(),)\n\n\"\"\"\n    SinDecay2{T, S<:Integer}(range0, range1, period)\n    SinDecay2(;λ0, λ1, period)\n\nA sine wave schedule with `period` and half the amplitude each cycle.\nThe output conforms to\n```text\nabs(λ0 - λ1) * Sin(t) / (2^floor((t - 1) / period)) + min(λ0, λ1)\n```\nwhere `Sin(t)` is `abs(sin(π * (t - 1) / period))` (see [`Sin`](#)).\n\n# Arguments\n- `range0`/`λ0`: the first range endpoint\n- `range1`/`λ1`: the second range endpoint\n- `period::Integer`: the period\n\"\"\"\nstruct SinDecay2{T, S<:Integer}\n    range0::T\n    range1::T\n    period::S\nend\nSinDecay2(;λ0, λ1, period) = SinDecay2(λ0, λ1, period)\n\n(schedule::SinDecay2)(t) = _cycle(schedule.range0, schedule.range1,\n                                  _sin(t, schedule.period) / (2^fld(t - 1, schedule.period)))\n\nBase.eltype(::Type{<:SinDecay2{T}}) where T = T\nBase.IteratorSize(::Type{<:SinDecay2}) = Base.IsInfinite()\n\nBase.iterate(schedule::SinDecay2, t = 1) = schedule(t), t + 1\n\nBase.axes(::SinDecay2) = (OneToInf(),)\n\n\"\"\"\n    SinExp{T, S<:Integer}(range0, range1, period, decay)\n    SinDecay2(;λ0, λ1, period, γ)\n\nA sine wave schedule with `period` and an exponentially decaying amplitude.\nThe output conforms to\n```text\nabs(λ0 - λ1) * Sin(t) * γ^(t - 1) + min(λ0, λ1)\n```\nwhere `Sin(t)` is `abs(sin(π * (t - 1) / period))` (see [`Sin`](#)).\n\n# Arguments\n- `range0`/`λ0`: the first range endpoint\n- `range1`/`λ1`: the second range endpoint\n- `period::Integer`: the period\n- `decay`/`γ`: the decay rate\n\"\"\"\nstruct SinExp{T, S<:Integer}\n    range0::T\n    range1::T\n    period::S\n    decay::T\nend\nSinExp(;λ0, λ1, period, γ) = SinExp(λ0, λ1, period, γ)\n\n(schedule::SinExp)(t) = _cycle(schedule.range0, schedule.range1,\n                               _sin(t, schedule.period) * schedule.decay^(t - 1))\n\nBase.eltype(::Type{<:SinExp{T}}) where T = T\nBase.IteratorSize(::Type{<:SinExp}) = Base.IsInfinite()\n\nBase.iterate(schedule::SinExp, t = 1) = schedule(t), t + 1\n\nBase.axes(::SinExp) = (OneToInf(),)\n\n\"\"\"\n    Cos{T, S<:Integer}(range0, range1, period)\n    Cos(;λ0, λ1, period)\n\nA cosine annealing schedule\n(see [\"SGDR: Stochastic Gradient Descent with Warm Restarts\"](https://arxiv.org/abs/1608.03983v5))\nThe output conforms to\n```text\nabs(λ0 - λ1) * (1 + cos(π * mod(t - 1, period) / period)) / 2 + min(λ0, λ1)\n```\nThis schedule is also referred to as \"cosine annealing with warm restarts\"\nin machine learning literature.\n\n# Arguments\n- `range0`/`λ0`: the first range endpoint\n- `range1`/`λ1`: the second range endpoint\n- `period::Integer`: the period\n\"\"\"\nstruct Cos{T, S<:Integer}\n    range0::T\n    range1::T\n    period::S\nend\nCos(;λ0, λ1, period) = Cos(λ0, λ1, period)\n\n(schedule::Cos)(t) = _cycle(schedule.range0, schedule.range1,\n                            (1 + cos(π * mod(t - 1, schedule.period) / schedule.period)) / 2)\n\nBase.eltype(::Type{<:Cos{T}}) where T = T\nBase.IteratorSize(::Type{<:Cos}) = Base.IsInfinite()\n\nBase.iterate(schedule::Cos, t = 1) = schedule(t), t + 1\n\nBase.axes(::Cos) = (OneToInf(),)", "meta": {"hexsha": "fa1295424a8375ae7afee8bdffbb640f4669f016", "size": 7091, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cyclic.jl", "max_stars_repo_name": "darsnack/ParameterSchedulers.jl", "max_stars_repo_head_hexsha": "83cb8f794b0926eb50c91f07db9391d321d4189f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2020-12-30T08:08:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T05:08:52.000Z", "max_issues_repo_path": "src/cyclic.jl", "max_issues_repo_name": "darsnack/ParameterSchedulers.jl", "max_issues_repo_head_hexsha": "83cb8f794b0926eb50c91f07db9391d321d4189f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-12-28T17:37:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T03:47:46.000Z", "max_forks_repo_path": "src/cyclic.jl", "max_forks_repo_name": "darsnack/ParameterSchedulers.jl", "max_forks_repo_head_hexsha": "83cb8f794b0926eb50c91f07db9391d321d4189f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-12-28T15:35:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-13T13:13:04.000Z", "avg_line_length": 29.3016528926, "max_line_length": 103, "alphanum_fraction": 0.634325201, "num_tokens": 2419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7761083067086121}}
{"text": "export dnorm, dgumbel, dgamma, dlognorm\n\n\"\"\"\n    dnorm(x::Real, μ::Real, σ::Real)\n\nNormal distribution density function\n\"\"\"\ndnorm(x::Real, μ::Real, σ::Real) = exp(-0.5 * ((x - μ)/σ)^2)/(σ*sqrt2π)\n\n\"\"\"\n    dgumbel(x::Real, μ::Real, σ::Real)\n\nGumbel density, parameterized by mean (μ) and SD (σ) of x.\n\"\"\"\nfunction dgumbel(x::Real, μ::Real, σ::Real)\n    β = (√6 * σ) / π\n    α = μ - (β*γ)\n    z = (x - α) / β\n    exp(-(z + exp(-z)))\nend\n\n\"\"\"\n    dgamma(x::Real, μ::Real, σ::Real)\n\nGamma density, parameterized by mean (μ) and sigma(σ) of x.\n\"\"\"\nfunction dgamma(x::Real, μ::Real, σ::Real)\n    α = μ^2 / σ^2\n    β = μ / σ^2\n    (x^(α - 1) * exp(-β * x))  * (β^α / Γ(α))\nend\n\n\"\"\"\n    dlognorm(x::Real, μ::Real, σ::Real)\n\nLognormal density, parameterized by mean (μ) and SD (σ) of x, NOT of log(x).\n\"\"\"\nfunction dlognorm(x::Real, μ::Real, σ::Real)\n    lμ = log(μ^2 / sqrt(1 + σ^2 / μ^2))\n    lσ = √(log(1 + σ^2 / μ^2))\n    dnorm(log(x), lμ, lσ) / x\nend\n", "meta": {"hexsha": "f008a16367f9bb9041ee9d21ef6865f3a160bfba", "size": 947, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distributions.jl", "max_stars_repo_name": "the-sushi/MixFit.jl", "max_stars_repo_head_hexsha": "a609efb60fcf7059ff8048c23ee2187153796726", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-24T00:12:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-22T18:01:05.000Z", "max_issues_repo_path": "src/distributions.jl", "max_issues_repo_name": "the-sushi/MixFit.jl", "max_issues_repo_head_hexsha": "a609efb60fcf7059ff8048c23ee2187153796726", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distributions.jl", "max_forks_repo_name": "the-sushi/MixFit.jl", "max_forks_repo_head_hexsha": "a609efb60fcf7059ff8048c23ee2187153796726", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.023255814, "max_line_length": 76, "alphanum_fraction": 0.535374868, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.776108305473402}}
{"text": "###################################\n## Simple VI & GS for 2D Gaussian\n\nusing PyPlot\nusing Distributions\n\nfunction calc_KL(mu1, lambda1, mu2, lambda2)\n    D = size(mu1, 1)\n    px_lnqx = 0.5 * logdet(lambda2) - 0.5 * ((mu1 - mu2)' * lambda2 * (mu1 - mu2) + trace(lambda2 * inv(lambda1)))\n    px_lnpx = 0.5 * logdet(lambda1) - 0.5 * D\n    KL = - (px_lnqx - px_lnpx)\n    return KL[1]\nend\n\nfunction plot_results(result, truth)\n    N = size(result, 1)\n    H = Int(ceil(sqrt(N)))\n    W = Int(ceil(N / H))\n    for i in 1 : H\n        for j in 1 : W\n            n = (i - 1) * W + j\n            if n <= N\n                subplot(H, W, n)\n                title(\"$n of $N\")\n                plot_gaussian(truth[1], truth[2], \"b\", \"\\$p(z)\\$\")\n                plot_gaussian(result[n][1], result[n][2], \"r\", \"\\$p(z)\\$\")\n            end\n        end\n    end\nend\n\nfunction plot_lines(X)\n    D, N = size(X)\n    X_d = zeros(D, 2*N + 1)\n    X_d[:,1] = X[:,1]\n    for i in 1 : N\n        X_d[1, 2*i - 1] = X[1, i]\n        X_d[1, 2*i] = X[1, i]\n        X_d[2, 2*i] = X[2, i]\n        X_d[2, 2*i + 1] = X[2, i]\n    end\n    plot(X[1,:], X[2,:], \"oy\")\n    plot(X_d[1,1:2*N], X_d[2,1:2*N], \"--y\")\nend\n\nfunction plot_gaussian(Mu, Sigma, col, label)\n    res = 100\n    plot(Mu[1], Mu[2], \"x\", color=col)\n    \n    F = eigfact(Sigma)\n    vec = F.vectors\n    val = F.values\n    dw = 2*pi/res\n    w = dw * (0 : res)\n    \n    c = 1.0\n    a = sqrt(c*val[1])\n    b = sqrt(c*val[2])\n    P1 = a*cos.(w)\n    P2 = b*sin.(w)\n    P = Mu .+ vec'*vcat(P1', P2')\n    plot(P[1, :], P[2, :], \"-\", color=col, label=label)\nend\n\n\"\"\"\nVariational inference for 2D Gauss.\n\"\"\"\nfunction main_VI()\n    ## creat truth distribution\n    D = 2 # dimension\n    theta = 2.0*pi/12 # tilt\n    A = reshape([cos.(theta), -sin.(theta),\n                 sin.(theta), cos.(theta)],\n                2, 2)\n    mu = [0.0, 0.0]\n    lambda = inv(A * inv(reshape([1,0,0,10], 2, 2)) * A')\n    \n    ## initialize\n    #mu_h = randn(D)\n    mu_h = [-0.5, 0.3]\n    lambda_h = zeros(D,D)\n    \n    ## main iteration\n    max_iter = 10\n    KL = NaN * Array{Float64, 1}(max_iter)\n    result = Array{Any, 1}(max_iter)\n    for i in 1 : max_iter\n        ## update\n        mu_h[1] = mu[1] - inv(lambda[1,1])*lambda[1,2] * (mu_h[2] - mu[2])\n        \n        lambda_h[1,1] = lambda[1,1]\n        mu_h[2] = mu[2] - inv(lambda[2,2])*lambda[2,1] * (mu_h[1] - mu[1])\n        lambda_h[2,2] = lambda[2,2]\n        \n        ## calculate KL divergeince\n        KL[i] = calc_KL(mu_h, lambda_h, mu, lambda)\n\n        ## store the results\n        result[i] = [deepcopy(mu_h), deepcopy(inv(lambda_h))]\n    end\n\n    ## visualize results\n    figure(\"result per iteration (VI)\")\n    clf()\n    plot_results(result, (mu, inv(lambda)))\n\n    figure(\"result (VI)\")\n    clf()\n    plot_gaussian(mu, inv(lambda), \"b\", \"\\$p(\\\\bf{z})\\$\")\n    plot_gaussian(result[end][1], result[end][2], \"r\", \"\\$q(\\\\bf{z})\\$\")\n    xlabel(\"\\$z_1\\$\", fontsize=20)\n    ylabel(\"\\$z_2\\$\", fontsize=20)\n    legend(fontsize=16)\n    \n    figure(\"KL divergence (VI)\")\n    clf()\n    plot(1:max_iter, KL)\n    ylabel(\"KL divergence\", fontsize=16)\n    xlabel(\"iteration\", fontsize=16)\n    show()\nend\n\n\"\"\"\nGibbs sampling for 2D Gauss.\n\"\"\"\nfunction main_GS()\n    ## creat truth distribution\n    D = 2 # dimension\n    theta = 2.0*pi/12 # tilt\n    A = reshape([cos.(theta), -sin.(theta),\n                 sin.(theta), cos.(theta)],\n                2, 2)\n    mu = [0.0, 0.0]\n    #lambda = inv(A * inv(reshape([1,0,0,10], 2, 2)) * A')\n    lambda = inv(A * inv(reshape([1,0,0,100], 2, 2)) * A')\n\n    ## initialize\n    #max_iter = 1000\n    max_iter = 50\n    X = randn(D, max_iter)\n    mu_h = randn(D)\n    \n    ## main iteration\n    KL = NaN * Array{Float64, 1}(max_iter)\n    for i in 2 : max_iter\n        ## update\n        mu_h[1] = mu[1] - inv(lambda[1,1])*lambda[1,2] * (X[2,i-1] - mu[2])\n        X[1, i] = rand(Normal(mu_h[1], sqrt(inv(lambda[1,1]))))\n        \n        mu_h[2] = mu[2] - inv(lambda[2,2])*lambda[2,1] * (X[1,i] - mu[1])\n        X[2, i] = rand(Normal(mu_h[2], sqrt(inv(lambda[2,2]))))        \n        \n        if i > D\n            KL[i] = calc_KL(mean(X[:,1:i], 2), inv(cov(X[:,1:i], 2)), mu, lambda)\n        end\n    end\n    \n    ## visualize results\n    expt_mu = mean(X, 2)\n    expt_Sigma = cov(X, 2)\n\n    figure(\"samples (GS)\")\n    clf()\n    plot_lines(X)\n    plot_gaussian(mu, inv(lambda), \"b\", \"\\$p(\\\\bf{z})\\$\")\n    plot_gaussian(expt_mu, expt_Sigma, \"r\", \"\\$q(\\\\bf{z})\\$\")\n    xlabel(\"\\$z_1\\$\", fontsize=20)\n    ylabel(\"\\$z_2\\$\", fontsize=20)\n    legend(fontsize=16)\n    \n    figure(\"KL divergence (GS)\")\n    clf()\n    plot(1:max_iter, KL)\n    ylabel(\"KL divergence\", fontsize=16)\n    xlabel(\"sample size\", fontsize=16)\n    show()\nend\n\nmain_VI()\nmain_GS()\n", "meta": {"hexsha": "39ab3eacd66a91d11f21560bc9c70f4086ba7e11", "size": 4717, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/demo_Simple2DGauss.jl", "max_stars_repo_name": "sammy-suyama/BayesBook", "max_stars_repo_head_hexsha": "61cb7ee0f1df348ef502aa183f23c7bc9753d02a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 158, "max_stars_repo_stars_event_min_datetime": "2017-10-19T13:33:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:59:21.000Z", "max_issues_repo_path": "src/demo_Simple2DGauss.jl", "max_issues_repo_name": "sammy-suyama/BayesBook", "max_issues_repo_head_hexsha": "61cb7ee0f1df348ef502aa183f23c7bc9753d02a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2018-01-29T08:36:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-01T14:32:34.000Z", "max_forks_repo_path": "src/demo_Simple2DGauss.jl", "max_forks_repo_name": "sammy-suyama/BayesBook", "max_forks_repo_head_hexsha": "61cb7ee0f1df348ef502aa183f23c7bc9753d02a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2017-10-20T00:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T20:34:22.000Z", "avg_line_length": 26.0607734807, "max_line_length": 114, "alphanum_fraction": 0.4941700233, "num_tokens": 1709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067252, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7761082987644408}}
{"text": "using DEMC\nusing Random\nusing LinearAlgebra\nusing Distributions\nRandom.seed!(31953150)\n\n# generate data\nnobs = 100\nnpar = 3\nΣ = ones(npar, npar)\nfor i = 1:npar\n    for iprime = 1:i\n        if i != iprime\n            Σ[i, iprime] = 0.25\n            Σ[iprime, i] = 0.25\n        end\n    end\nend\n\nDataDistribution = MvNormal(zeros(npar), Σ)\nX = zeros(nobs, npar+1)\nX[:,1] .= 1.\nfor iobs = 1:nobs\n    X[iobs, 2:end] .= rand(DataDistribution)\nend\n\nβ = rand(npar+1)\ny = X*β + randn(nobs)\n\n# log objective function - for correct std errors need to use optimal weights\nlog_obj(b) = -0.5 * sum((y.-X*b).^2)\n\n# set up of DEMCz chain\nNpar = length(β)\nndim = Npar\nblockindex = [1:Npar] # parameter blocks: here choose all parameters to be updated simultaenously\nNblocks = length(blockindex)\neps_scale = 1e-5*ones(Npar) # scale of random error around DE update\nγ = 2.38 # scale of DE update, 2.38 is the \"optimal\" number for a normal distribution\nN = 3\nK = 10\nZ = randn((10*ndim, ndim))\n\n# Number of iterations in Chain\nNgen = 2500\nmc, Z = DEMC.demcz_sample(log_obj, Z, N, K, Ngen, Nblocks, blockindex, eps_scale, γ; verbose =false)\n\n# drop first half of chain\nkeep = Int(round(Ngen/2))+1:Ngen\nNgen_burned = length(keep)\nchain_burned = mc.chain[:,:,keep]\nchainflat = DEMC.flatten_chain(chain_burned, N, Ngen_burned, Npar)'\nbhat = mean(chainflat,dims=1)[:]\nprintln(\"\\n estimates: \", bhat, \"\\n dist to true: \", bhat - β)\n# covariance of estimates\nb, Σb = DEMC.mean_cov_chain(chain_burned, N, Ngen_burned, Npar)\n# correct std errors for incorrect weighting matrix\n\n# OLS\nbols = (X'*X)\\(X'*y)\nui = y .- X*bols\ns2hat = (1/(nobs-npar)) * sum(ui.^2)\nΣols = inv(X'X)*s2hat\n", "meta": {"hexsha": "2fb11c84524d986a61a14fec3630e614ce28e3bb", "size": 1651, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/example_linreg.jl", "max_stars_repo_name": "universal/DEMC.jl", "max_stars_repo_head_hexsha": "fc5e671f8c2d3af60fde24a660e4d76cd00ba76d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/example_linreg.jl", "max_issues_repo_name": "universal/DEMC.jl", "max_issues_repo_head_hexsha": "fc5e671f8c2d3af60fde24a660e4d76cd00ba76d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/example_linreg.jl", "max_forks_repo_name": "universal/DEMC.jl", "max_forks_repo_head_hexsha": "fc5e671f8c2d3af60fde24a660e4d76cd00ba76d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.796875, "max_line_length": 100, "alphanum_fraction": 0.6723198062, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359676, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7760974525658424}}
{"text": "# Firms' parameters\nconst A = 1\nconst N = 1\nconst α = 0.33\nconst β = 0.96\nconst δ = 0.05\n\n\"\"\"\nCompute wage rate given an interest rate, r\n\"\"\"\nfunction r_to_w(r::Real)\n    return A * (1 - α) * (A * α / (r + δ)) ^ (α / (1 - α))\nend\n\n\"\"\"\nInverse demand curve for capital. The interest rate\nassociated with a given demand for capital K.\n\"\"\"\nfunction rd(K::Real)\n    return A * α * (N / K) ^ (1 - α) - δ\nend\n\n\"\"\"\nMap prices to the induced level of capital stock.\n\n##### Arguments\n- `am::Household` : Household instance for problem we want to solve\n- `r::Real` : interest rate\n\n##### Returns\n- The implied level of aggregate capital\n\"\"\"\nfunction prices_to_capital_stock(am::Household, r::Real)\n\n    # Set up problem\n    w = r_to_w(r)\n    setup_R!(am, r, w)\n    aiyagari_ddp = DiscreteDP(am.R, am.Q, am.β)\n\n    # Compute the optimal policy\n    results = solve(aiyagari_ddp, PFI)\n\n    # Compute the stationary distribution\n    stationary_probs = stationary_distributions(results.mc)[:, 1][1]\n\n    # Return K\n    return dot(am.s_vals[:, 1], stationary_probs)\nend\n\n# Create an instance of Household\nam = Household(β=β, a_max=20.0)\n\n# Create a grid of r values at which to compute demand and supply of capital\nnum_points = 20\nr_vals = linspace(0.005, 0.04, num_points)\n\n# Compute supply of capital\nk_vals = prices_to_capital_stock.(am, r_vals)\n\n# Plot against demand for capital by firms\ndemand = rd.(k_vals)\nlabels =  [\"demand for capital\" \"supply of capital\"]\nplot(k_vals, [demand r_vals], label=labels, lw=2, alpha=0.6)\nplot!(xlabel=\"capital\", ylabel=\"interest rate\", xlim=(2, 14), ylim=(0.0, 0.1))\n", "meta": {"hexsha": "1b2d6a625ccd4612ee5597a3081590b4781ff1ef", "size": 1591, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "aiyagari/aiyagari_compute_equilibrium.jl", "max_stars_repo_name": "chenwang/QuantEcon.lectures.code", "max_stars_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2017-05-09T10:45:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:33:27.000Z", "max_issues_repo_path": "aiyagari/aiyagari_compute_equilibrium.jl", "max_issues_repo_name": "chenwang/QuantEcon.lectures.code", "max_issues_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2017-06-30T01:52:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-01T20:09:47.000Z", "max_forks_repo_path": "aiyagari/aiyagari_compute_equilibrium.jl", "max_forks_repo_name": "QuantEcon/QuantEcon.lectures.code", "max_forks_repo_head_hexsha": "d61ac7bc54529dd5c77470c17539eb2418b047c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 117, "max_forks_repo_forks_event_min_datetime": "2017-04-25T16:09:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T02:30:29.000Z", "avg_line_length": 24.4769230769, "max_line_length": 78, "alphanum_fraction": 0.6731615336, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7760974454355563}}
{"text": "import Statistics:mean\n\nfunction ParetoSub(X, perm)\n    Z= X.-X[:,1]\n    nondominated=reshape(any(Z.<0,dims=1),:)\n    ispareto = all(any(Z[:,nondominated].>0, dims=1))\n    X=X[:, nondominated]\n    nondominated = perm[nondominated]\n    return ispareto, nondominated, X\nend\n\n\"\"\"\n    index = ParetoSet(X[, sense])\nGet the Pareto set from a given set of oberservations `X`. \n# Argument\n- `X::AbstractMatrix{Real}` size(X)=(n_objectives, n_samples)\n- `sense::AbstractVector{Union{Symbol, EGOSense}}=repeat(:Min, n_objectives)` sense of each objective, size(S)=(n_objectives,)\n\"\"\"\nfunction ParetoSet(X::AbstractMatrix)\n    n,m = size(X)\n    Xmin = minimum(X, dims=2)\n    Xt = X.-Xmin\n    Xm = mean(Xt, dims=2)\n    Xn = maximum(Xt ./ (Xm.+maximum(Xm)), dims=1)\n    perm = sortperm(reshape(Xn,:))\n    Y = X[:, perm]\n    membership = falses(m)\n    while length(perm)>1\n        k = perm[1]\n        membership[k], perm, Y = ParetoSub(Y, perm)\n    end\n    membership[perm] .= true\n    membership\nend\n\nParetoSet(X, sense::AbstractVector{EGOSense}) = ParetoSet(X.*Int.(sense))\n\nParetoSet(X, sense::AbstractVector{Symbol}) = ParetoSet(X, sym2sense.(sense))\n", "meta": {"hexsha": "e04a35b106811a8a65fd05c3acb72038e9f7c1e2", "size": 1142, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/paretoset.jl", "max_stars_repo_name": "xue-cheng/EfficientGlobalOptimiztion.jl", "max_stars_repo_head_hexsha": "1b3a4bb4a23da81ed74f4b4686181b9322024049", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-06T02:41:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-06T02:41:28.000Z", "max_issues_repo_path": "src/paretoset.jl", "max_issues_repo_name": "xue-cheng/EfficientGlobalOptimiztion.jl", "max_issues_repo_head_hexsha": "1b3a4bb4a23da81ed74f4b4686181b9322024049", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-27T12:52:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:52:42.000Z", "max_forks_repo_path": "src/paretoset.jl", "max_forks_repo_name": "xue-cheng/EfficientGlobalOptimiztion.jl", "max_forks_repo_head_hexsha": "1b3a4bb4a23da81ed74f4b4686181b9322024049", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:43:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:43:48.000Z", "avg_line_length": 29.2820512821, "max_line_length": 126, "alphanum_fraction": 0.6488616462, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7760974452955292}}
{"text": "using LinearAlgebra\nusing Distributions\nusing Plots\n\ninclude(\"./gen_data.jl\")\ninclude(\"./kalman_filters.jl\")\n\n\"\"\"Experimental parameters\"\"\"\n\n# Number of sigma points\nN = 10\n\n# Time horizon\nT = 100\n\n# Experimental parameters\ntransition_coeffs = 1.0\nemission_coeffs = 1.0\n\n# Noises\nprocess_noise = 0.5\nmeasurement_noise = 0.1\n\n# Prior state\nstate0 = ([0.], reshape([1e-12], 1,1))\n\n\"Generate data\"\n\n# Generate signal\nobservations, states = LGDS(transition_coeffs,\n                            emission_coeffs,\n                            process_noise,\n                            measurement_noise,\n                            state0;\n                            time_horizon=T)\n\n# Check signal visually\nscatter(1:T, observations, color=\"blue\", label=\"observations\")\nplot!(1:T, states[2:end], color=\"red\", label=\"states\")\n\n\"\"\"Basic Kalman filter\"\"\"\n\n# Call filter\ninclude(\"./kalman_filters.jl\")\nmx, Px = kalman_filter(observations,\n                       transition_coeffs,\n                       emission_coeffs,\n                       process_noise,\n                       measurement_noise,\n                       state0)\n\n# Visualize estimates\nscatter(1:T, observations[1,:], color=\"black\", label=\"observations\")\nplot!(1:T, states[1,2:end], color=\"red\", label=\"latent states\")\nplot!(1:T, mx[:], color=\"purple\", label=\"inferred\")\nplot!(1:T, mx[:],\n      ribbon=[sqrt.(Px[1,1,:]), sqrt.(Px[1,1,:])],\n      color=\"purple\", alpha=0.1, label=\"\")\nxlabel!(\"time (t)\")\nylabel!(\"signal\")\nsavefig(\"./viz/LGDS_kf.png\")\n\n\"Generate data\"\n\n# Nonlinearities\ntransition_function(x) = .1*x.^3 + 0.5*x\nemission_function(x) = x\n\n# Noises\nprocess_noise = reshape([0.1], 1,1)\nmeasurement_noise = reshape([0.2], 1,1)\n\n# Generate signal\nobservations, states = NLGDS(transition_function,\n                             emission_function,\n                             process_noise,\n                             measurement_noise,\n                             state0;\n                             time_horizon=T)\n\n# Check signal visually\nscatter(1:T, observations, color=\"black\", label=\"observations\")\nplot!(1:T, states[2:end], color=\"red\", label=\"states\")\n\n\"\"\"Nonlinear Kalman filter\"\"\"\n\n# Call basic filter\nmx1, Px1 = kalman_filter(observations,\n                         transition_coeffs,\n                         emission_coeffs,\n                         process_noise,\n                         measurement_noise,\n                         state0)\n\n# Visualize estimates\np1 = scatter(1:T, observations[1,:], color=\"black\", label=\"observations\", size=(1200,500))\nplot!(1:T, states[1,2:end], color=\"red\", label=\"latent states\")\nplot!(1:T, mx1[:], color=\"purple\", label=\"linear\")\nplot!(1:T, mx1[:],\n      ribbon=[sqrt.(Px1[1,1,:]), sqrt.(Px1[1,1,:])],\n      color=\"purple\", alpha=0.1, label=\"\")\nxlabel!(\"time (t)\")\nylabel!(\"signal\")\nsavefig(p1, \"./viz/NLGDS_KF.png\")\n\n# Call extended filter with first-order Taylor\nmx2, Px2 = extended_kalman_filter(observations,\n                                  transition_function,\n                                  emission_function,\n                                  process_noise,\n                                  measurement_noise,\n                                  state0)\n\np2 = scatter(1:T, observations[1,:], color=\"black\", label=\"observations\", size=(1200,500))\nplot!(1:T, states[1,2:end], color=\"red\", label=\"latent states\")\nplot!(1:T, mx2[:], color=\"blue\", label=\"extended\")\nplot!(1:T, mx2[:],\n      ribbon=[sqrt.(Px2[1,1,:]), sqrt.(Px2[1,1,:])],\n      color=\"blue\", alpha=0.1, label=\"\")\nxlabel!(\"time (t)\")\nylabel!(\"signal\")\nsavefig(p2, \"./viz/NLGDS_E1KF.png\")\n\n# Call extended filter with second-order Taylor\nmx3, Px3 = extended_kalman_filter(observations,\n                                  transition_function,\n                                  emission_function,\n                                  process_noise,\n                                  measurement_noise,\n                                  state0,\n                                  second_order=true)\n\np3 = scatter(1:T, observations[1,:], color=\"black\", label=\"observations\", size=(1200,500))\nplot!(1:T, states[1,2:end], color=\"red\", label=\"latent states\")\nplot!(1:T, mx3[:], color=\"cyan\", label=\"extended\")\nplot!(1:T, mx3[:],\n    ribbon=[sqrt.(Px3[1,1,:]), sqrt.(Px3[1,1,:])],\n    color=\"cyan\", alpha=0.1, label=\"\")\nxlabel!(\"time (t)\")\nylabel!(\"signal\")\nsavefig(p3, \"./viz/NLGDS_E2KF.png\")\n\n# Call unscented filter\nmx4, Px4 = unscented_kalman_filter(observations,\n                                   transition_function,\n                                   emission_function,\n                                   process_noise,\n                                   measurement_noise,\n                                   state0,\n                                   α=1., κ=0., β=2.)\n\np4 = scatter(1:T, observations[1,:], color=\"black\", label=\"observations\", size=(1200,500))\nplot!(1:T, states[1,2:end], color=\"red\", label=\"latent states\")\nplot!(1:T, mx4[:], color=\"green\", label=\"unscented\")\nplot!(1:T, mx4[:],\n      ribbon=[sqrt.(Px4[1,1,:]), sqrt.(Px4[1,1,:])],\n      color=\"green\", alpha=0.1, label=\"\")\nxlabel!(\"time (t)\")\nylabel!(\"signal\")\nsavefig(p4, \"./viz/NLGDS_UKF.png\")\n\nplot(p1, p2, p3, p4, layout=(4,1), size=(2000,1600))\nsavefig(\"./viz/NLGDS_filters.png\")\n", "meta": {"hexsha": "1952842da4d54831f2703d2657650633f2070a24", "size": 5244, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_kf.jl", "max_stars_repo_name": "wmkouw/kalman-filters", "max_stars_repo_head_hexsha": "0f10bc523170d2b3d33242ecdb0ca46f7159ab8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-08-01T03:27:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T22:05:24.000Z", "max_issues_repo_path": "test/test_kf.jl", "max_issues_repo_name": "wmkouw/kalman-filters", "max_issues_repo_head_hexsha": "0f10bc523170d2b3d33242ecdb0ca46f7159ab8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_kf.jl", "max_forks_repo_name": "wmkouw/kalman-filters", "max_forks_repo_head_hexsha": "0f10bc523170d2b3d33242ecdb0ca46f7159ab8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-01T03:27:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T03:27:19.000Z", "avg_line_length": 31.9756097561, "max_line_length": 90, "alphanum_fraction": 0.5446224256, "num_tokens": 1289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7760974417537241}}
{"text": "#!/usr/bin/julia\n\n# Trizen\n# 17 January 2017\n# https://github.com/trizen\n\n# Generates the Mandelbrot set.\n\n# See also:\n#   https://en.wikipedia.org/wiki/Mandelbrot_set\n#   https://trizenx.blogspot.ro/2017/01/mandelbrot-set.html\n\nusing Images\n\n@inline function hsv2rgb(h, s, v)\n    c = v * s\n    x = c * (1 - abs(((h/60) % 2) - 1))\n    m = v - c\n\n    if h < 60\n        r,g,b = (c, x, 0)\n    elseif h < 120\n        r,g,b = (x, c, 0)\n    elseif h < 180\n        r,g,b = (0, c, x)\n    elseif h < 240\n        r,g,b = (0, x, c)\n    elseif h < 300\n        r,g,b = (x, 0, c)\n    else\n        r,g,b = (c, 0, x)\n    end\n\n    (r + m), (b + m), (g + m)\nend\n\nfunction mandelbrot()\n\n    w, h = 1000, 1000\n\n    zoom  = 0.5\n    moveX = 0\n    moveY = 0\n\n    maxIter = 100\n    img = zeros(RGB{Float64}, h, w)\n\n    for x in 1:w, y in 1:h\n        i = maxIter\n        c = Complex(\n            (2*x - w) / (w * zoom) + moveX,\n            (2*y - h) / (h * zoom) + moveY\n        )\n        z = c\n        while abs(z) < 2 && (i -= 1) > 0\n            z = z^2 + c\n        end\n        r,g,b = hsv2rgb(i / maxIter * 360, 1, i / maxIter)\n        img[y,x] = RGB{Float64}(r, g, b)\n    end\n\n    println(\"Generating image...\")\n    save(\"mandelbrot_set.png\", img)\nend\n\nmandelbrot()\n", "meta": {"hexsha": "635cf0e17990b35337c0f7cd5d0e6de31bebe4dd", "size": 1245, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Image/mandelbrot_set.jl", "max_stars_repo_name": "trizen/julia-scripts", "max_stars_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-03-22T09:38:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T21:38:31.000Z", "max_issues_repo_path": "Image/mandelbrot_set.jl", "max_issues_repo_name": "trizen/julia-scripts", "max_issues_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Image/mandelbrot_set.jl", "max_forks_repo_name": "trizen/julia-scripts", "max_forks_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5820895522, "max_line_length": 59, "alphanum_fraction": 0.4626506024, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7760818374014453}}
{"text": "export mutualinfo, Kraskov1, Kraskov2\n\nabstract type MutualInformationEstimator <: EntropyEstimator end\n\n\"\"\"\n    mutualinfo(x, y, est; base = 2, q = 1)\n\nEstimate mutual information between `x` and `y`, ``I^{q}(x; y)``, using the provided \nentropy/probability estimator `est` from Entropies.jl, and Rényi entropy of order `q`\n(defaults to `q = 1`, which is the Shannon entropy), with logarithms to the given `base`.\n\nBoth `x` and `y` can be vectors or (potentially multivariate) [`Dataset`](@ref)s.\n\nWorth highlighting here are the estimators that compute entropies _directly_, e.g.\nnearest-neighbor based methhods. The choice is between naive \nestimation using the [`KozachenkoLeonenko`](@ref) or [`Kraskov`](@ref) entropy estimators, \nor the improved [`Kraskov1`](@ref) and [`Kraskov2`](@ref) dedicated ``I`` estimators. The \nlatter estimators reduce bias compared to the naive estimators.\n\n**Note**: only Shannon entropy is possible to use for nearest neighbor estimators, so the \nkeyword `q` cannot be provided; it is hardcoded as `q = 1`. \n\n## Description\n\nMutual information ``I`` between ``X`` and ``Y`` \nis defined as \n\n```math\nI(X; Y) = \\\\sum_{y \\\\in Y} \\\\sum_{x \\\\in X} p(x, y) \\\\log \\\\left( \\\\dfrac{p(x, y)}{p(x)p(y)} \\\\right)\n```\n\nHere, we rewrite this expression as the sum of the marginal entropies, and extend the \ndefinition of ``I`` to use generalized Rényi entropies\n\n```math\nI^{q}(X; Y) = H^{q}(X) + H^{q}(Y) - H^{q}(X, Y),\n```\n\nwhere ``H^{q}(\\\\cdot)`` is the generalized Renyi entropy of order ``q``, i.e., the\n`genentropy` function from Entropies.jl.\n\"\"\"\nfunction mutualinfo end \n\nmutualinfo(x::Vector_or_Dataset, y::Vector_or_Dataset) = \n    error(\"Estimator missing. Please provide a valid estimator as the third argument.\")\n\nfunction mutualinfo(x::Vector_or_Dataset, y::Vector_or_Dataset, est; base = 2, q = 1)\n    X = genentropy(Dataset(x), est; base = base, q = q)\n    Y = genentropy(Dataset(y), est; base = base, q = q)\n    XY = genentropy(Dataset(x, y), est; base = base, q = q)\n    MI = X + Y - XY \nend \n\ninclude(\"nearestneighbor.jl\")", "meta": {"hexsha": "dcdece1d958ace214047664e7ae1af22742166c9", "size": 2062, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mutualinfo/interface.jl", "max_stars_repo_name": "untoreh/TransferEntropy.jl", "max_stars_repo_head_hexsha": "4b472b9c686fd7ca0d79da3e5ee8f97075a76160", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-12-10T16:26:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T08:50:18.000Z", "max_issues_repo_path": "src/mutualinfo/interface.jl", "max_issues_repo_name": "untoreh/TransferEntropy.jl", "max_issues_repo_head_hexsha": "4b472b9c686fd7ca0d79da3e5ee8f97075a76160", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2020-06-23T21:02:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-14T16:06:04.000Z", "max_forks_repo_path": "src/mutualinfo/interface.jl", "max_forks_repo_name": "untoreh/TransferEntropy.jl", "max_forks_repo_head_hexsha": "4b472b9c686fd7ca0d79da3e5ee8f97075a76160", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-07-13T04:20:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T09:49:32.000Z", "avg_line_length": 38.1851851852, "max_line_length": 101, "alphanum_fraction": 0.6871968962, "num_tokens": 627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7760818318789849}}
{"text": "using LinearAlgebra: norm, inv, eigvals\nimport ForwardDiff\nusing StaticArrays: setindex\nusing DynamicalSystems\n\n# This code is written for `SVector`s, or out-of-place dynamical systems.\n# Notation z is used for the vector (x..., p), i.e. mixed space\n\"\"\"\n    bifurcation_rule_form(ds) → f, J\nProduce dynamic rule `f` and Jacobian function `J` in a two-argument form.\n\"\"\"\nfunction bifurcation_rule_form(ds::ContinuousDynamicalSystem)\n    f = (x, p) -> ds.f(x, p, 0.0)\n    J = (x, p) -> ds.jacobian(x, p, 0.0)\n    return f, J\nend\n\nfunction bifurcation_rule_form(ds::DiscreteDynamicalSystem)\n    error(\"TODO: Convert `f` to `f - x`.\")\n    f = (x, p) -> ds.f(x, p, 0.0)\n    J = (x, p) -> ds.jacobian(x, p, 0.0)\n    return f, J\nend\n\n\n# Corrector: Newton's method in mixed-space with extra fixed condition\n\"\"\"\n    corrector(zpred, zprev, f, J; max_steps = 200, δ = 0.9, ε = 1e-3) → (z*, success)\nImplement the Newton algorithm to converge to the fixed point for given predicted\nmixed state `zpred`, previously found state `zprev`, function `f`, Jacobian `J` \nand stepping factor `δ`.\n\nIf iteration occurs for more than `max_steps` without convergence better than `ε`,\nthen iteration stops and `success` will be `false`.\n\"\"\"\nfunction corrector(zpred, zprev, f, J; δ = 0.9, max_steps = 200, ε = 1e-6)\n    Δz = zpred .- zprev\n    # index of variable that changed the most\n    # The `iszero` clause is just to keep the first iteration at given `p0`\n    i = all(iszero, Δz) ? length(Δz) : argmax(Δz .^ 2)\n    c = 0\n    zⱼ = zpred\n    zⱼ₊₁ = newton_step!(zⱼ, zpred, i, f, J, δ)\n    while norm(zⱼ₊₁ - zⱼ) > ε\n        zⱼ = zⱼ₊₁\n        zⱼ₊₁ = newton_step!(zⱼ, zpred, i, f, J, δ)\n        c += 1\n        if c > max_steps \n            @warn(\"Newton did not converge.\")\n            return (zⱼ₊₁, false)\n        end\n    end\n    return zⱼ₊₁, true\nend\n\nfunction newton_step!(zⱼ, zpred, i, f, J, δ)\n    Jfinal = mixed_jacobian(zⱼ, i, f, J)\n    xⱼ = zⱼ[1:end-1]; pⱼ = zⱼ[end]\n    g = f(xⱼ, pⱼ)\n    gz = vcat(g, zⱼ[i] - zpred[i])\n    zⱼ₊₁ = zⱼ - δ*(inv(Jfinal))*gz\n    return zⱼ₊₁\nend\n\nfunction mixed_jacobian(z, i, f, J)\n    x = z[1:end-1]; p = z[end]\n    # start creating the mixed space jacobian\n    j = J(x, p)\n    # to the state space jacobian add one more column, derivative towards p\n    pder = ForwardDiff.derivative(p -> f(x, p), p)\n    Jmixed = hcat(j, pder)\n    # add the last row, which is 1 for the `i` entry, 0 everywhere else\n    last_row = setindex((@SVector zeros(length(z))), 1.0, i)\n    Jfinal = vcat(Jmixed, last_row')\n    return Jfinal\nend\n\n# Predictor: Secant (linear extrapolation of already found bifurcation curve)\nfunction predictor(zs, dz0)\n    if length(zs) == 1\n        return zs[end]\n    elseif length(zs) == 2 # 1 entry is z0, 2nd entry is 1st found fixed point\n        return zs[end] .+ dz0\n    else\n        return 2zs[end] .- zs[end-1]\n    end\nend\n\n# Continuation function: perform a step of predictor-corrector and save values\nfunction continuation!(zs, f, J; dz0, pmin, pmax)\n    zpred = predictor(zs, dz0)\n    (pmin ≤ zpred[end] ≤ pmax) || return false\n    zˣ, success = corrector(zpred, zs[end], f, J)\n    push!(zs, zˣ)\n    return success\nend\n\n# Continuation loop: do continuation for a given amount of steps\nfunction continuation(f, J, x0, p0;\n        pmin, pmax, dp0, dx0, N = 1000\n    )\n\n    z0 = vcat(x0, p0); zs = [z0]; dz0 = vcat(dx0, dp0)\n\n    ps = [p0]\n    xs = Dataset([x0])\n    stability = Bool[]\n    for i in 1:N\n        success = continuation!(zs, f, J; dz0, pmin, pmax)\n        # Stop iteration if we exceed given parameter margins\n        success || break\n        # Detect stability of found fixed point (needs `Array` coz of StaticArrays.jl)\n        eigenvalues = eigvals(Array(J(zs[end][1:end-1], zs[end][end])))\n        μ = maximum(real(v) for v ∈ eigenvalues)\n        isstable = μ < 0\n        push!(stability, isstable)\n    end\n    xs = Dataset([z[1:end-1] for z in zs])\n    ps = [z[end] for z in zs]\n    popfirst!(xs.data); popfirst!(ps) # remove initial guess\n    return xs, ps, stability\nend\n\n", "meta": {"hexsha": "f082c5a856e762ee4c453b381c9f0e339d9fd454", "size": 4026, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simple_continuation.jl", "max_stars_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_stars_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 88, "max_stars_repo_stars_event_min_datetime": "2021-07-18T20:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T09:23:53.000Z", "max_issues_repo_path": "src/simple_continuation.jl", "max_issues_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_issues_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simple_continuation.jl", "max_forks_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_forks_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-07-28T18:49:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:45:11.000Z", "avg_line_length": 32.4677419355, "max_line_length": 86, "alphanum_fraction": 0.6229508197, "num_tokens": 1396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7760818317723591}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots\n\tRandom.seed!(0)\nend\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.05\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tn1, n2 = 10, 15\n\tN = 10^6\n\tmu, sigma = 10, 4\n\tnormDist = Normal(mu,sigma)\nend;\n\n# ╔═╡ 67a42f40-3a99-11eb-2199-cb72cdee58fa\nbegin\n\tfValues = Array{Float64}(undef, N)\n\n\tfor i in 1:N\n\t\tdata1 = rand(normDist,n1)\n\t\tdata2 = rand(normDist,n2)\n\t\tfValues[i] = var(data1)/var(data2)\n\tend\nend\n\n# ╔═╡ 67a46e56-3a99-11eb-1254-3d0d490364f5\nbegin\n\tfRange = 0:0.1:5\n\tstephist(fValues, bins=400, c=:blue, label=\"Simulated\", normed=true)\n\tplot!(fRange, pdf.(FDist(n1-1, n2-1), fRange), \n\t\tc=:red, label=\"Analytic\", xlims=(0,5), ylims=(0,0.8),\n\t\t\txlabel = \"F\", ylabel = \"Density\")\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.05\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═67a42f40-3a99-11eb-2199-cb72cdee58fa\n# ╠═67a46e56-3a99-11eb-1254-3d0d490364f5\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "aa83c3aa488d758eabd191f60d45c738121527f1", "size": 1357, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/listing5.05.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/05/listing5.05.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/05/listing5.05.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 23.0, "max_line_length": 69, "alphanum_fraction": 0.7074428887, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.924141826246517, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7760332861524246}}
{"text": "function simpson_integrate(u, stepsize)\r\n    numpts = length(u)\r\n    @assert iseven(numpts - 1)\r\n    mid = div(numpts,2)\r\n    integral = 0.0\r\n    for i = 1:mid\r\n        integral += stepsize / 3.0 * (u[2i-1] + 4.0 * u[2i] + u[2i+1])\r\n    end\r\n    return integral\r\nend\r\n", "meta": {"hexsha": "40cd5a1170d406a11a34cc01726d67316e5df1c0", "size": 268, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "simpson_integrate.jl", "max_stars_repo_name": "ArjunNarayanan/ExploreJacobi", "max_stars_repo_head_hexsha": "cbeeba2a165ecc61ea294c8974929a28edea6481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simpson_integrate.jl", "max_issues_repo_name": "ArjunNarayanan/ExploreJacobi", "max_issues_repo_head_hexsha": "cbeeba2a165ecc61ea294c8974929a28edea6481", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simpson_integrate.jl", "max_forks_repo_name": "ArjunNarayanan/ExploreJacobi", "max_forks_repo_head_hexsha": "cbeeba2a165ecc61ea294c8974929a28edea6481", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3636363636, "max_line_length": 71, "alphanum_fraction": 0.552238806, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7760332843980075}}
{"text": "using SchumakerSpline\nusing Dates\ntol = 10*eps()\n\nStartDate = Date(2018, 7, 21)\nx = Array{Date}(undef,1000)\nfor i in 1:1000\n    x[i] = StartDate +Dates.Day(2* (i-1))\nend\n\nfunction f(x::Date)\n    days_between = Dates.days(x - StartDate)\n    return log(days_between+1) + sqrt(days_between)\nend\ny = f.(x)\n\nspline = Schumaker(x,y)\nfor i in 1:length(x)\n    abs(evaluate(spline, x[i]) - y[2]) < tol\nend\n# Evaluation with a Float64.\nevaluate(spline, 11.5)\n\n# Testing second derivatives\nsecond_derivatives = evaluate.(spline, x,2)\nmaximum(second_derivatives) < tol\n\n# Testing Integrals\nfunction analytic_integral(lhs,rhs)\n    lhs_in_days = Dates.days(lhs - StartDate)\n    rhs_in_days = Dates.days(rhs - StartDate)\n    return (rhs_in_days+1)*log(rhs_in_days+1)-rhs_in_days + (2/3)*rhs_in_days^(3/2) - ((lhs_in_days+1)*log(lhs_in_days+1) - lhs_in_days + (2/3)*lhs_in_days^(3/2))\nend\n\nlhs = StartDate\nrhs = StartDate + Dates.Month(16)\nnumerical_integral = evaluate_integral(spline, lhs,rhs)\nanalytical = analytic_integral(lhs,rhs)\nabs(  analytical - numerical_integral  ) < 1\n\n## Testing with only one date provided.\nx = Array{Date}(undef, 1)\nx[1] = Date(2018, 7, 21)\ny = Array{Float64}(undef, 1)\ny[1] = 0.0\nspline = Schumaker(x,y)\nabs(evaluate(spline,  Date(2018, 7, 21))) < tol\nabs(evaluate(spline,  Date(2019, 7, 21))) < tol\nabs(evaluate(spline,  Date(2000, 7, 21))) < tol\n\n## Testing with two dates provided.\nx = Array{Date}(undef,2)\nx[1] = Date(2018, 7, 21)\nx[2] = Date(2018, 8, 21)\ny = Array{Float64}(undef,2)\ny[1] = 0.0\ny[2] = 1.0\nspline = Schumaker(x,y)\nabs(evaluate(spline,  Date(2018, 7, 21))) < tol\nabs(evaluate(spline,  Date(2018, 7, 30))) > tol\nabs(evaluate(spline,  Date(2018, 8, 21)) - y[2]) < tol\nabs(evaluate(spline,  Date(2019, 8, 21)) - y[2]) > tol\n\nspline = Schumaker(x, y , extrapolation =  (Constant,Constant))\nabs(evaluate(spline,  Date(2018, 8, 21)) - y[2]) < tol\nabs(evaluate(spline,  Date(2019, 8, 21)) - y[2]) < tol\n\n## Testing with three dates provided.\nx = Array{Date}(undef,3)\nx[1] = Date(2018, 7, 21)\nx[2] = Date(2018, 8, 21)\nx[3] = Date(2018, 9, 21)\ny = Array{Float64}(undef,3)\ny[1] = 0.0\ny[2] = 1.0\ny[3] = 1.3\nspline = Schumaker(x,y)\nabs(evaluate(spline,  x[2]) - y[2]) < tol\n", "meta": {"hexsha": "93a866c518279cf7b5a76c83c3564e4a637a12dd", "size": 2198, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Test_with_Dates.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SchumakerSpline.jl-65e68595-3a03-5ff5-a6a2-f05fa774f32e", "max_stars_repo_head_hexsha": "d9ec5723ab4896e96c83ad4cf47e16b7c82731c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-04-12T00:50:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T18:31:02.000Z", "max_issues_repo_path": "test/Test_with_Dates.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SchumakerSpline.jl-65e68595-3a03-5ff5-a6a2-f05fa774f32e", "max_issues_repo_head_hexsha": "d9ec5723ab4896e96c83ad4cf47e16b7c82731c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-10-14T12:39:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T23:53:29.000Z", "max_forks_repo_path": "test/Test_with_Dates.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SchumakerSpline.jl-65e68595-3a03-5ff5-a6a2-f05fa774f32e", "max_forks_repo_head_hexsha": "d9ec5723ab4896e96c83ad4cf47e16b7c82731c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-08-10T06:39:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:21:27.000Z", "avg_line_length": 27.8227848101, "max_line_length": 162, "alphanum_fraction": 0.6642402184, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.924141826246517, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7760332824458569}}
{"text": "export Sech\n\n\"\"\"\n`Sech([domainType=Float64::Type,] dim_in::Tuple)`\n\nCreates an hyperbolic secant non-linear operator with input dimensions `dim_in`:\n```math\n\\\\text{sech} ( \\\\mathbf{x} ).\n```\n\n\"\"\"\nstruct Sech{T,N} <: NonLinearOperator\n\tdim::NTuple{N,Int}\nend\n\nfunction Sech(DomainType::Type, DomainDim::NTuple{N,Int}) where {N} \n\tSech{DomainType,N}(DomainDim)\nend\n\nSech(DomainDim::NTuple{N,Int}) where {N} = Sech{Float64,N}(DomainDim)\nSech(DomainDim::Vararg{Int}) = Sech{Float64,length(DomainDim)}(DomainDim)\n\nfunction mul!(y::AbstractArray{T,N}, L::Sech{T,N}, x::AbstractArray{T,N}) where {T,N}\n\ty .= sech.(x)\nend\n\nfunction mul!(y::AbstractArray, \n              J::AdjointOperator{Jacobian{A,TT}}, \n              b::AbstractArray) where {T,N, A<: Sech{T,N}, TT <: AbstractArray{T,N}}\n    L = J.A\n    y .= -conj.( tanh.(L.x) .* sech.(L.x) ).*b\nend\n\nfun_name(L::Sech) = \"sech\"\n\nsize(L::Sech) = (L.dim, L.dim)\n\ndomainType(L::Sech{T,N}) where {T,N} = T\ncodomainType(L::Sech{T,N}) where {T,N} = T\n", "meta": {"hexsha": "2556ece1b0239e763af5859a5509eb3a6414407f", "size": 992, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nonlinearoperators/Sech.jl", "max_stars_repo_name": "nantonel/AbstractOperators.jl", "max_stars_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2017-08-28T17:28:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-21T18:53:01.000Z", "max_issues_repo_path": "src/nonlinearoperators/Sech.jl", "max_issues_repo_name": "nantonel/AbstractOperators.jl", "max_issues_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2017-11-17T14:43:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-23T20:02:48.000Z", "max_forks_repo_path": "src/nonlinearoperators/Sech.jl", "max_forks_repo_name": "nantonel/AbstractOperators.jl", "max_forks_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-09-02T08:56:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T18:56:33.000Z", "avg_line_length": 24.8, "max_line_length": 85, "alphanum_fraction": 0.6401209677, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7760332772814722}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.6\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e77948a6-1ecc-11eb-3285-7f06dcdb7cf5\nusing Pkg, DrWatson\n\n# ╔═╡ e7799b9e-1ecc-11eb-311f-035de72c3603\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing StatsBase, Combinatorics, Plots\nend\n\n# ╔═╡ 6c38d2ce-1ecc-11eb-281d-0d13a832adea\nmd\"## Listing 2.3\"\n\n# ╔═╡ fe1ee6a6-1ecc-11eb-1930-0301940bc5f7\n\tN = 10^3\n\n# ╔═╡ e77a2a28-1ecc-11eb-0acb-5167936362f5\nbegin\n\tmatchExists1(n) = 1 - prod([k/365 for k in 365:-1:365-n+1])\n\tmatchExists2(n) = 1- factorial(365,365-big(n))/365^big(n)\n\n\tfunction bdEvent(n)\n\t\tbirthdays = rand(1:365,n)\n\t\tdayCounts = counts(birthdays, 1:365)\n\t\treturn maximum(dayCounts) > 1\n\tend\n\n\tprobEst(n) = sum([bdEvent(n) for _ in 1:N])/N\nend\n\n# ╔═╡ e7885e54-1ecc-11eb-03d1-2580aad82a3d\nbegin\n\txGrid = 1:50\n\tanalyticSolution1 = [matchExists1(n) for n in xGrid]\n\tanalyticSolution2 = [matchExists2(n) for n in xGrid]\n\t(\"Maximum error: $(round(maximum(abs.(analyticSolution1 - analyticSolution2)), digits=25))\")\nend\n\n# ╔═╡ e788edce-1ecc-11eb-3682-b1bfc98646a0\nbegin\n\tmcEstimates = [probEst(n) for n in xGrid]\n\n\tplot(xGrid, analyticSolution1, c=:blue, label=\"Analytic solution\")\n\tscatter!(xGrid, mcEstimates, c=:red, ms=6, msw=0, shape=:xcross, \n\t\tlabel=\"MC estimate\", xlims=(0,50), ylims=(0, 1), \n\t\txlabel=\"Number of people in room\", \n\t\tylabel=\"Probability of birthday match\", \n\t\tlegend=:topleft)\nend\n\n# ╔═╡ e7965b58-1ecc-11eb-2308-093c9f5a167e\nmd\"## End of listing 2.3\"\n\n# ╔═╡ Cell order:\n# ╟─6c38d2ce-1ecc-11eb-281d-0d13a832adea\n# ╠═e77948a6-1ecc-11eb-3285-7f06dcdb7cf5\n# ╠═e7799b9e-1ecc-11eb-311f-035de72c3603\n# ╠═fe1ee6a6-1ecc-11eb-1930-0301940bc5f7\n# ╠═e77a2a28-1ecc-11eb-0acb-5167936362f5\n# ╠═e7885e54-1ecc-11eb-03d1-2580aad82a3d\n# ╠═e788edce-1ecc-11eb-3682-b1bfc98646a0\n# ╟─e7965b58-1ecc-11eb-2308-093c9f5a167e\n", "meta": {"hexsha": "83ffeef19d99f21182fa3e9f1b7d6b756ade783e", "size": 1823, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/02/listing2.03.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/02/listing2.03.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/02/listing2.03.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 26.8088235294, "max_line_length": 93, "alphanum_fraction": 0.7202413604, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7760332753293216}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.6\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 7ef4b0b3-9d0a-4356-bd16-14487f14e0ab\nbegin\n\tusing PlutoUI\n\tPlutoUI.TableOfContents(aside=true)\nend\n\n# ╔═╡ 0cd92d78-1da6-435b-ad8e-60af29502e1d\nbegin\n\t# Necessary packages\n\t# If a package is missing, follow the instructions.\n\tusing LightGraphs\n\tusing GraphPlot\n\tusing SparseArrays\n\tusing LinearAlgebra\n\tusing Plots\n\tusing Distances\n\tusing Arpack\n\tusing Images\n\tusing Random\nend\n\n# ╔═╡ cb61f761-b2ee-4818-9149-f85d95b76a1e\nmd\"\"\"\n# Spectral Graph Bipartitioning\n\nMany data clustering problems can be interpreted as clustering of vertices of graphs. __Graph bipartitioning problem__ is to partition vertices into subsets such that the connections within subsets are stronger than the connections between different subsets.\n\nPartition of the vertices into two subsetts is done according to signs of the eigenvectors of the second smallest eigenvalue of the Laplacian matrix. \n\n__Prerequisites__\n\nThe reader should be familiar with the basic graph theory, linear algebra and, in particular,  eigenvalues and eigenvectors.\n \n__Competences__\n\nThe reader should be able to apply graph spectral bipartitioning and recursive bipartitioning to data clustering problems.\n\n__Credits.__ The notebook was initially derived from M.Sc. Thesis of Ivančica Mirošević.\n\"\"\"\n\n# ╔═╡ 5926c79a-6038-4dbc-b49a-5b05d02250a0\nmd\"\"\"\n# Graphs\n\nFor more details, see [W. H. Haemers, Matrices and Graphs, in L. Hogben, Ed., 'Handbook of Linear Algebra', pp. 39.1-39.14, CRC Press, Boca Raton, 2014.](https://www.routledge.com/Handbook-of-Linear-Algebra/Hogben/p/book/9781138199897) and [S. Butler and F. Chung, Spectral Graph Theory, ibid., pp. 47.1-47.6](https://www.routledge.com/Handbook-of-Linear-Algebra/Hogben/p/book/9781138199897) and the references therein.\n\n## Definitions\n\nA __weighted graph__ is an ordered triplet $G=(V,E,\\omega)$, where $V=\\{1,2,3,...,n\\}$ is the set of __vertices__ , $E=\\{(i,j)\\}$ is a set of __edges__ connecting vertices, and $\\omega$ is a set of __weights__ of edges. We assume $G$ is undirected.\n\"\"\"\n\n# ╔═╡ a66a6e80-1f80-11eb-15f8-71ffaa5050e7\nmd\"\n__Adjacency matrix__ of graph $G$ is the matrix $A$ defined as\n\n$$A_{ij}=\\begin{cases} 1 \\quad \\textrm{if}\\ (i,j)\\in E, \\\\\n0\\quad  \\textrm{otherwise} \\end{cases}.$$\n\n__Weight matrix__ of graph $G$ is the matrix $W$ defined as\n\n$W_{ij}=\\begin{cases} \\omega(e) \\quad \\textrm{if}\\ e=(i,j)\\in E, \\\\\n0\\quad  \\textrm{otherwise} \\end{cases}.$\n\n__Laplacian matrix__ of graph $G$ is the matrix \n\n$L=D-W,$ \n\nwhere \n$D=\\mathop{\\mathrm{diag}}(d_1,d_2,\\ldots,d_n)$ with $d_i=\\sum_{k=1}^n W_{ik}$ for $i=1,\\ldots,n$.\n\n__Normalized Laplacian matrix__ is the matrix\n\n$L_n=D^{-1/2} L D^{-1/2}\\equiv D^{-1/2} (D-W) D^{-1/2}$ \n\n(__diagonally scaled $L$__).\n\n__Incidence matrix__ of graph $G$ is the $|V|\\times |E|$ matrix $I_G$. Each row of $I_G$ corresponds to a vertex of $G$ and each column corresponds to an edge of $G$.\nIn the column corresponding to en edge $e=(i,j)$, all elements are zero except the ones in the $i$-th and $j$-th row, which are equal to $\\sqrt{\\omega(e)}$ and $-\\sqrt{\\omega(e)}$, respectively.\n\"\n\n# ╔═╡ d4cf12ce-12fb-4562-bbea-e9b85cba94c2\nmd\"\"\"\n### Examples\n\nGraph types and algorithms are implemented in the package [LightGraphs.jl](https://github.com/JuliaGraphs/LightGraphs.jl). \n\nPlotting graphs is done by the packages\n[GraphPlot.jl](https://github.com/JuliaGraphs/GraphPlot.jl).\n\nAs a small inconvenience, we can only plot unweighted graphs and plot weights as edge labels.\n\"\"\"\n\n# ╔═╡ 87cca1d3-b944-4d74-bf4c-1562f34cf91a\nbegin\n\t# Sources, targets and weights\n\tn=7\n\tsn=[1,1,1,2,2,3,3,3,5,5,6]\n\ttn=[2,3,4,4,5,4,6,7,6,7,7]\n\twn=[2,3,4,7,1,3,2,1,7,3,5]\n\t[sn tn wn]\nend\n\n# ╔═╡ 3d7b4a01-9a7d-4111-a45d-1d31f1ef6278\nbegin\n\t# Create the graph\n\tG=Graph(n)\n\tfor i=1:length(sn)\n\t    add_edge!(G,sn[i],tn[i])\n\tend\n\tG\nend\n\n# ╔═╡ 3b5ed1fa-75b0-43fb-a918-4c2e8f52d039\n# What is the optimal bipartition?\ngplot(G, nodelabel=1:n, edgelabel=wn)\n\n# ╔═╡ 8f7d1f6c-ee4c-407f-80d9-d2abc2af949e\nbegin\n\t# We define some functions\n\tfunction WeightMatrix(src::Array,dst::Array,weights::Array)\n\t    n=nv(G)\n\t    sparse([src;dst],[dst;src],[weights;weights],n,n)\n\tend\n\t\n\tLaplacian(W::AbstractMatrix)=spdiagm(0=>vec(sum(W,dims=2)))-W\n\t\n\tfunction NormalizedLaplacian(L::AbstractMatrix)\n\t    D=1.0./sqrt.(diag(L))\n\t\tDiagonal(D)*L*Diagonal(D)\n\tend\nend\n\n# ╔═╡ b7f127d8-e8cd-4771-8091-c88f9ffe6b08\nW=WeightMatrix(sn,tn,wn)\n\n# ╔═╡ 3f5447bb-95cd-4520-b0b9-e85f33b323bd\nMatrix(W)\n\n# ╔═╡ ecb2a46e-f9dc-4e57-812f-0a2788afb202\nbegin\n\tL=Laplacian(W)\n\tMatrix(L)\nend\n\n# ╔═╡ 86e5f00f-13ee-4867-b0cd-187f2c782a46\nLₙ=NormalizedLaplacian(L)\n\n# ╔═╡ cf26dbe9-3c4f-4c95-88ef-f197f360d759\nMatrix(Lₙ)\n\n# ╔═╡ 8fcd2440-4013-4b37-a747-2c0c7f6d4aeb\nissymmetric(Lₙ)\n\n# ╔═╡ 0c8d3572-3436-446f-952a-b19d0370ab38\n# Let us compute the incidence matrix\nfunction IncidenceMatrix(G::Graph, weights::Array)\n    A=zeros(nv(G),ne(G))\n    k=1\n    for a in edges(G)\n        A[a.dst,k]=sqrt.(weights[k])\n        A[a.src,k]=-sqrt(weights[k])\n        k+=1\n    end\n    A\nend\n\n# ╔═╡ 1437aadc-1c26-4eff-bb22-9cf9c15e1f5f\nIᵧ=IncidenceMatrix(G,wn)\n\n# ╔═╡ 6529324b-49f7-4f01-b5cd-33668979b56b\nmd\"\"\"\n## Facts\n\n1.  $L=I_{G}I_{G}^{T}$.\n\n2.  $L$ is symmetric PSD matrix.\n\n3.  $L\\mathbf{1}=0$ for $\\mathbf{1}=[1,...,1]^{T}$, thus $0$ is an eigenvalue of $L$  and $\\mathbf{1}$ is the corresponding eigenvector.\n\n4. If $G$ has $c$ connected components, then $L$ has $c$ eigenvalues equal to $0$.\n\n5. For every $x\\in \\mathbb{R}^{n}$, it holds\n$x^{T}L x=\\sum\\limits_{i<j}W_{ij}(x_{i}-x_{j})^{2}$.\n\n6. For every $x\\in\\mathbb{R}^{n}$ and $\\alpha,\\beta\\in\\mathbb{R}$, it holds\n$(\\alpha x+\\beta \\mathbf{1})^{T} L (\\alpha x+\\beta \\mathbf{1}) \n=\\alpha^{2} x^{T}L x$.\n\n7. Assume that the eigenvalues of $L$ are increasingly ordered. Then,\n\n$$\n0=\\lambda_1(L)\\leq \\lambda_2(L)\\leq \\cdots \\leq\\lambda_{n}(L)\\leq \n2\\max\\limits_{i=1,\\cdots ,n}d_{i}.$$\n\n8.  $\\sigma(L_n) \\subseteq [0,2]$.\n\"\"\"\n\n# ╔═╡ a9ba64a6-bd17-4b86-acb4-e7c7d8f87dc1\nmd\"\"\"\n### Examples\n\"\"\"\n\n# ╔═╡ 6a6f5db5-7dd4-4a26-ac1a-ef3ca3a5d6be\n# Fact 1\nnorm(L-Iᵧ*Iᵧ')\n\n# ╔═╡ e11bc23d-03e2-4780-9488-93f0adfc2fcb\n# Facts 2 and 7\nissymmetric(L), eigs(L)[1], 2*maximum(diag(L))\n\n# ╔═╡ 7192f7d0-28b9-11eb-28dd-8db0019504ca\neigen(Matrix(L))\n\n# ╔═╡ e5890dca-368f-437e-bc45-6a395714dae2\n# Fact 3\nL*ones(n)\n\n# ╔═╡ 61a978a7-b2d2-43e7-b3f7-95bf4c4f54b9\nbegin\n\t# Fact 5\n\tx=rand(n)\n\tx'*L*x, sum([W[i,j]*(x[i]-x[j])^2 for i=1:n, j=1:n])/2\nend\n\n# ╔═╡ da7f85ed-73b0-44b9-a97f-4a8ed5e9a1d1\nbegin\n\t# Fact 6\n\tα,β=rand(),rand()\n\t(α*x+β*ones(n))'*L*(α*x+β*ones(n)), α^2*x'*L*x\nend\n\n# ╔═╡ fed7f592-be03-4baf-8ace-ff9ee78fee71\n# Fact 8\neigvals(Matrix(Lₙ))\n\n# ╔═╡ 9f31928e-c933-43bb-9a5c-bf55f29737cd\nmd\"\"\"\n# Bipartitioning\n\n## Definitions\n\nLet $\\pi=\\{V_{1},V_{2}\\}$ be a partition of $V$ with $V_1,V_2\\neq \\emptyset$.\n\n__Cut__ of partition $\\pi$ is the sum of weights of all \nedges between $V_1$ and $V_2$, \n\n$$\\mathop{\\mathrm{cut}}(\\pi)\\equiv \\mathop{\\mathrm{cut}}(V_1,V_2)=\\sum\\limits_{{\\displaystyle i\\in V_{1} \\atop \\displaystyle j\\in V_{2}}}W_{ij}.$$\n\n__Weight__ of vertex $i\\in V$ is the sum of the weights of all egdges emanating from $i$,\n$\\omega(i)=\\sum\\limits_{j=1}^{n}W_{ij}$.\n\n__Weight__ of a subset $\\bar V\\subset V$ is the sum of the weights of all vertices in $\\bar V$, \n\n$\\omega(\\bar V)=\\sum\\limits_{\\displaystyle i\\in\\bar V} \\omega(i)$.\n\n__Proportional cut__ of partition $\\pi$ is\n\n$$\n\\mathop{\\mathrm{pcut}}(\\pi)=\\displaystyle\\frac{\\mathop{\\mathrm{cut}}(\\pi)}{|V_{1}|}+\\frac{\\mathop{\\mathrm{cut}}(\\pi)}{|V_{2}|}.$$\n\n__Normalized cut__ of partition $\\pi$ is\n\n$$\n\\mathop{\\mathrm{ncut}}(\\pi)=\\displaystyle\\frac{\\mathop{\\mathrm{cut}}(\\pi)}{\\omega(V_{1})}+\\frac{\\mathop{\\mathrm{cut}}(\\pi)}{\\omega(V_{2})}.$$\n\"\"\"\n\n# ╔═╡ 1e6d4c72-f25d-4bf5-99d6-ae0446be25dd\nmd\"\"\"\n### Example\n\nConsider the following partitions (all edges have unit weights):\n\n $(load(\\\"./files/cut2.png\\\"))\n\nLeft partition is $\\pi$, right partition is $\\pi'$.\n\n|     Cut \\ Partition  | $\\pi$            |  $\\pi'$     |\n| ------- | ---------------- | ------------|\n| $\\mathop{\\mathrm{cut}}$  |  $2$        |     $3$        |\n| $\\mathop{\\mathrm{pcut}}$ | $\\frac{2}{1}+\\frac{2}{11}=2.18$|    $\\frac{3}{6}+\\frac{3}{6}=1$      |\n| $\\mathop{\\mathrm{ncut}}$ | $\\frac{2}{2}+\\frac{2}{50}=1.04$ |  $\\frac{3}{27}+\\frac{3}{25}=0.23$|\n\"\"\"\n\n# ╔═╡ 02035eed-6d49-4253-a755-68a999e7e90e\nmd\"\"\"\n## Facts\n\n1. The informal description of the bipartitioning problem can be formulated as two problems,\n\n$$\n\\mathop{\\textrm{arg min}}\\limits_{\\pi} \\mathop{\\mathrm{pcut}}(\\pi) \\quad \\textrm{or} \\quad \n\\mathop{\\textrm{arg min}}\\limits_{\\pi} \\mathop{\\mathrm{ncut}}(\\pi).$$\n\nThe first problem favors partitions into subsets with similar numbers of vertices, while the second problem favors partitions into subsets with similar weights.\n\n2. Both problems are NP-hard.\n\n3. __Approximate solutions can be computed by suitable relaxations in $O(n^2)$ operations.__\n\n4. The partition $\\pi$ is defined by the vector $y$ such that\n\n$$\ny_{i}=\n\\begin{cases}\n\\frac{1}{2} & \\text{for } i\\in V_1 \\\\\n-\\frac{1}{2} & \\text{for } i\\in V_2\n\\end{cases}$$\n\nThe proportional cut problem can be formulated as the  __discrete proportional cut__ problem\n\n$$\n\\underset{\\displaystyle \\big|\\mathbf{y}^{T}\\mathbf{1} \\big|\\leq \\beta}\n{\\min\\limits_{\\displaystyle y_{i}\\in \\{-\\frac{1}{2},\\frac{1}{2}\\}}}\n\\frac{1}{2}\\sum_{i,j}(y_{i}-y_{j})^{2}W_{ij}.$$\n\nParameter $\\beta$ controls the number of vertices in each subset.\n\n5. The normalized cut problem can be formulated as the __discrete normalized cut__ problem\n\n$$\n\\underset{\\displaystyle \\big|y^{T}D\\mathbf{1} \\big|\\leq \\beta}\n{\\min\\limits_{\\displaystyle y_{i}\\in \\{-\\frac{1}{2},\\frac{1}{2}\\}}}\n\\frac{1}{2}\\sum_{i,j}(y_{i}-y_{j})^{2}W_{ij}.$$\n\nParameter $\\beta$ controls the weights of each subset.\n\n6. Using the Fact 5 above, the discrete proportional cut problem can be formulated as the __relaxed proportional cut__ problem\n\n$$\n\\underset{\\displaystyle y^{T}y=1}{\\underset{\\displaystyle \\big| y^{T}\\mathbf{1} \\big|\n\\leq 2\\frac{\\beta}{\\sqrt{n}}}\n{\\min\\limits_{\\displaystyle y\\in \\mathbb{R}^{n}}}} y^{T}L y.$$\n\nSimilarly, the discrete normalized cut problem can be formulated as the __relaxed normalized cut__ problem\n\n$$\n\\underset{\\displaystyle y^{T}Dy=1}{\\underset{\\displaystyle \\big| y^{T}D\\mathbf{1}\\big|\n\\leq \\displaystyle \\frac{\\beta}{\\sqrt{\\theta n}}}{\\min\\limits_{\\displaystyle y\\in\n\\mathbb{R}^{n}}}}y^{T}L_n y.$$\n\n7. __The Main Theorem.__ Let $A\\in \\mathbb{R}^{n\\times n}$ be a symmetric matrix with eigenvalues $\\lambda _{1}<\\lambda _{2}<\\lambda_{3}\\leq \\cdots \\leq \\lambda _{n}$ and let $v^{[1]},v^{[2]},\\ldots,v^{[n]}$ be the corresponding eigenvectors. For the fixed $0\\leq \\alpha <1$, the solution of the problem\n\n$$\n\\underset{\\displaystyle y^{T}y=1}{\\underset{\\displaystyle \\left|y^{T}v^{[1]}\\right|\\leq \\alpha}\n{\\min\\limits_{\\displaystyle y\\in \\mathbb{R}^{n}}}} y^{T}Ay$$\n\nis $y=\\pm \\alpha v^{[1]}\\pm \\sqrt{1-\\alpha^{2}}v^{[2]}$. \n\nFor the proof see [D. J. Higham and M. Kibble, A Unified View of Spectral Clustering, Theorem 3.1, p. 7](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.115.1591&rep=rep1&type=pdf).\n\n8. For $0\\leq \\beta <\\frac{n}{2}$, the solution of the relaxed proportional cut problem is\n\n$$\ny=\\pm \\frac{2\\beta}{n\\sqrt{n}}\\mathbf{1}\\pm\n\\sqrt{1-4\\frac{\\beta ^{2}}{n^{2}}}v^{[2]},$$\n\nwhere $v^{[2]}$ is an eigenvector corresponding to $\\lambda_2(L)$. $v^{[2]}$ the __Fiedler vector__. Since the first summand carries no information, $V$ is partitioned according to the signs of the components of $v^{[2]}$:\n\n$$\nV_{1}=\\{i:v^{[2]}_i <0\\}, \\quad V_{2}=\\{i:v^{[2]}_i \\geq 0\\}.$$\n\n_Notice that the value of $\\beta$ is irrelevant for the solution._\n\n9. For $0\\leq \\beta <\\sqrt{\\theta n}\\left\\Vert D^{\\frac{1}{2}}\\mathbf{1} \\right\\Vert _{2},$ the solution of the relaxed normalized cut problem is\n\n$$\ny=\\pm \\frac{\\beta }{\\sqrt{\\theta n}\\left\\Vert\nD^{\\frac{1}{2}} \\mathbf{1}\\right\\Vert _{2}^{2}}\\mathbf{1}\\pm\n\\sqrt{1-\\frac{\\beta ^{2}}{ \\theta n\\left\\Vert\nD^{\\frac{1}{2}}\\mathbf{1}\\right\\Vert _{2}^{2}}}D^{-\\frac{1\n}{2}} v_n^{[2]},$$\n\nwhere $v_n^{[2]}$ is an eigenvector corresponding to $\\lambda_2(L_n)$. $V_n$ is partitioned according to the signs of the components of $v_n^{[2]}$, as above.\n\n10. Neither of the relaxed algorithms is guaranteed to solve exactly the true proportional / normalized cut problem. However, the computed solutions are in the right direction. Whether to use proportional or normalized cut formulation, depends upon the specific problem.  \n\"\"\"\n\n# ╔═╡ c188b7cf-03e7-40b3-bf90-773978c7b410\n# Voila!\neigs(L,nev=2,which=:SM, v0=ones(n))\n\n# ╔═╡ f60b51b6-79c3-4a3f-8bfb-8f198cdb92a8\n# For the normalized cut\neigs(Lₙ,nev=2,which=:SM, v0=ones(n))\n\n# ╔═╡ bfac7a55-0d82-4549-b999-7db3272eaa20\nmd\"\"\"\n### Concentric rings\n\nA __complete graph__ has edges connecting each pair of vertices.\n\nTo a set of points $X=\\{x_{1},x_{2},\\cdots ,x_{m}\\}$ , where $x_{i}\\in\\mathbb{R}^{n}$, we assign a weighted complete graph $G=(V,E)$ with $m$ vertices, where the vertex $j\\in V$ corresponds to the point $x_j\\in X$.\n\nThe main idea is to assign weight of an edge $e=(i,j)$ which reflects the distance between $x_i$ and $x_j$, something like $\\omega(e)=\\displaystyle\\frac{1}{\\mathop{\\mathrm{dist}}(x_i,x_j)}$.\n\nHowever, this has to be implemented with care. For example, using simple Euclidean distance yield the same results as the function `kmeans()`. In this example we use Gaussian kernel, that is\n\n$$\n\\omega(e)=e^{\\displaystyle -\\|x_i-x_j\\|_2^2/\\sigma^2},$$\n\nwhere the choice of $\\sigma$ is based on experience.\n\nThe computation of various distances is implemented in the package [Distances.jl](https://github.com/JuliaStats/Distances.jl).\n\nWe will construct the Laplace matrix directly.\n\"\"\"\n\n# ╔═╡ 80ed91ad-6f9a-4f12-a1ee-bc8dc6b58168\nbegin\n\t# Two concentric circles\n\tk=2\n\t# Center\n\tRandom.seed!(541)\n\t# center=[rand(-5:5),rand(-5:5)]\n\tcenter=[0,0]\n\t# Radii\n\tradii=randperm(10)[1:k]\n\t# Number of points in circles\n\tsizes=rand(1000:2000,k)\n\tcenter,radii,sizes\nend\n\n# ╔═╡ 2d8689c9-1b9e-4360-865c-23c2c8c5dcb9\nbegin\n\t# Generate points\n\tX=Array{Float64}(undef,2,sum(sizes))\n\tcsizes=cumsum(sizes)\n\t# Random angles\n\tϕ=2*π*rand(sum(sizes))\n\tfor i=1:csizes[1]\n\t\tX[:,i]=center+radii[1]*[cos(ϕ[i]);sin(ϕ[i])] + (rand(2).-0.5)/50\n\tend\n\tfor j=2:k\n\t\tfor i=csizes[j-1]+1:csizes[j]\n\t\t\tX[:,i]=center+radii[j]*[cos(ϕ[i]);sin(ϕ[i])] + (rand(2).-0.5)/50\n\t\tend\n\tend\n\tscatter(X[1,:],X[2,:],title=\"Concentric rings\", aspect_ratio=1,label=\"Points\")\nend\n\n# ╔═╡ fa4ae713-a0b2-46ce-b5f7-558b26d82019\n# Weight matrix\nW₁=1 ./pairwise(SqEuclidean(),X)\n\n# ╔═╡ 760e8ca2-596f-435f-befb-140b3d204f7f\nbegin\n\t# Laplacian matrix\n\tm=csizes[end]\n\tfor i=1:m\n\t    W₁[i,i]=0\n\tend\n\tL₁=Diagonal(vec(sum(W₁,dims=2)))-W₁\n\t# Check Fact 3\n\tnorm(L₁*ones(m))\nend\n\n# ╔═╡ 75956488-76ab-4262-a32f-0c53e1b3dc17\n# Notice λ₁=0\nE=eigs(L₁,nev=2,which=:SM, v0=ones(m))\n\n# ╔═╡ a55260dd-f05d-4a65-9fdf-cb3fd4638857\nbegin\n\t# Define clusters\n\tC=ones(Int64,m)\n\tC[findall(E[2][:,2].>0)].=2\n\tC\nend\n\n# ╔═╡ ba164ff3-5ef4-4480-8af2-9dd9a99b1e8d\n# Yet another plotting function\nfunction plotKpartresult(C::Vector,X::Array)\n\tscatter(aspect_ratio=1)\n    k=maximum(C)\n    for j=1:k\n        scatter!(X[1,findall(C.==j)],X[2,findall(C.==j)],label=\"Cluster $j\")\n    end\n\tscatter!(aspect_ratio=1)\nend\n\n# ╔═╡ 46de28bc-73ed-495c-a2e0-f565c1ce5651\nplotKpartresult(C,X)\n\n# ╔═╡ e004e4bf-ca04-4b41-947b-9f1ecd058abb\nmd\"\"\"\nThis is the same partitioning as obtained by `kmeans()`. Let us try Gaussian kernel. A rule of thumb is: if rings are close, use $\\sigma<1$, if rings are apart, use $\\sigma>1$.\n\"\"\"\n\n# ╔═╡ bb9d4d98-3aff-439e-b8a3-8347cf345839\nbegin\n\tσ=0.7 # 0.1\n\tW₂=exp.(-pairwise(SqEuclidean(),X)/σ^2)-I\n\tL₂=Diagonal(vec(sum(W₂,dims=2)))-W₂\n\tE₂=eigs(L₂,nev=2,which=:SM, v0=ones(m))\n\tC₂=ones(Int64,m)\n\tC₂[findall(E₂[2][:,2].>0)].=2\n\tplotKpartresult(C₂,X)\nend\n\n# ╔═╡ 012fa54a-5171-4980-a0ba-474a22c25981\nmd\"\"\"\n# Recursive bipartitioning\n\n## Definitions\n\nLet $G=(V,E)$ be a weighted graph with weights $\\omega$.\n\nLet $\\pi_k =\\{V_{1},V_{2},...,V_{k}\\}$ be a $k$-partition of $V$, with $V_i\\neq \\emptyset$ for $i=1,\\ldots,k$.\n\nThe previous definition of $cut(\\pi)\\equiv cut(\\pi_2)$ extends naturally to $k$-partition.\n\nA __cut__ of a partition $\\pi_k$ is \n\n$$\n\\mathop{\\mathrm{cut}}(\\pi_k)=\\sum\\limits_{\\displaystyle i<j} \\mathop{\\mathrm{cut}}(V_{i},V_{j}),$$\n\nwhere $\\mathop{\\mathrm{cut}}(V_{i},V_{j})$ is interpreted as a cut of the bipartition of the subgraph of $G$ with vertices $V_1\\cup V_2$.\n\n__Proportional cut__ of a partition $\\pi_k$ is\n\n$$\n\\mathop{\\mathrm{pcut}}(\\pi_k)=\\underset{i<j}{\\sum\\limits_{i,j=1}^{k}} \\left(\n\\frac{\\mathop{\\mathrm{cut}}(V_{i},V_{j})}{|V_{i}|}+\\frac{\\mathop{\\mathrm{cut}}(V_{i},V_{j})}{|V_{j}|}\\right) =\n\\sum_{i=1}^{k}\\frac{\\mathop{\\mathrm{cut}}(V_{i},V\\backslash V_{i})}{|V_{i}|}.$$\n\n__Normalized cut__ of a partition $\\pi_k$ is\n\n$$\n\\mathop{\\mathrm{ncut}}(\\pi_k)=\\underset{i<j}{\\sum\\limits_{i,j=1}^{k}} \\left(\n\\frac{\\mathop{\\mathrm{cut}}(V_{i},V_{j})}{\\omega(V_{i})}+\\frac{\\mathop{\\mathrm{cut}}(V_{i},V_{j})}{\\omega(V_{j})}\\right) =\n\\sum_{i=1}^{k}\\frac{\\mathop{\\mathrm{cut}}(V_{i},V\\backslash V_{i})}{ \\omega(V_{i})}.$$\n\n## Facts\n\nIf we want to cluster vertices of graph $G=(V,E)$ into $k$ clusters, we can apply the following recursive algorithm:\n\n1. __Initialization.__ Compute the bipartition $\\pi=\\{V_{1},V_{2}\\}$ of $V$. Set the counter $c=2$.\n\n2. __Recursion.__ While $c<k$ repeat:\n\n    1. Compute the bipartition of each subset of $V$.\n    \n    2. Among all $(c+1)$-partitions, choose the one with the smallest $\\mathop{\\mathrm{pcut}}(\\pi_{c+1})$ or $\\mathop{\\mathrm{ncut}}(\\pi_{c+1})$, respectively.\n    \n    3. Set $c=c+1$.\n\n3. __Stop.__\n\nThere is no guarantee for optimality of this algorithm. Clearly, the optimal $k$-partiton may be a subpartition of one of the discarded partitions.\n\"\"\"\n\n# ╔═╡ f3eb8ad4-55a8-4e76-a581-07f9a7cc75f7\n\n\n# ╔═╡ Cell order:\n# ╟─7ef4b0b3-9d0a-4356-bd16-14487f14e0ab\n# ╟─cb61f761-b2ee-4818-9149-f85d95b76a1e\n# ╟─5926c79a-6038-4dbc-b49a-5b05d02250a0\n# ╟─a66a6e80-1f80-11eb-15f8-71ffaa5050e7\n# ╟─d4cf12ce-12fb-4562-bbea-e9b85cba94c2\n# ╠═0cd92d78-1da6-435b-ad8e-60af29502e1d\n# ╠═87cca1d3-b944-4d74-bf4c-1562f34cf91a\n# ╠═3d7b4a01-9a7d-4111-a45d-1d31f1ef6278\n# ╠═3b5ed1fa-75b0-43fb-a918-4c2e8f52d039\n# ╠═8f7d1f6c-ee4c-407f-80d9-d2abc2af949e\n# ╠═b7f127d8-e8cd-4771-8091-c88f9ffe6b08\n# ╠═3f5447bb-95cd-4520-b0b9-e85f33b323bd\n# ╠═ecb2a46e-f9dc-4e57-812f-0a2788afb202\n# ╠═86e5f00f-13ee-4867-b0cd-187f2c782a46\n# ╠═cf26dbe9-3c4f-4c95-88ef-f197f360d759\n# ╠═8fcd2440-4013-4b37-a747-2c0c7f6d4aeb\n# ╠═0c8d3572-3436-446f-952a-b19d0370ab38\n# ╠═1437aadc-1c26-4eff-bb22-9cf9c15e1f5f\n# ╟─6529324b-49f7-4f01-b5cd-33668979b56b\n# ╟─a9ba64a6-bd17-4b86-acb4-e7c7d8f87dc1\n# ╠═6a6f5db5-7dd4-4a26-ac1a-ef3ca3a5d6be\n# ╠═e11bc23d-03e2-4780-9488-93f0adfc2fcb\n# ╠═7192f7d0-28b9-11eb-28dd-8db0019504ca\n# ╠═e5890dca-368f-437e-bc45-6a395714dae2\n# ╠═61a978a7-b2d2-43e7-b3f7-95bf4c4f54b9\n# ╠═da7f85ed-73b0-44b9-a97f-4a8ed5e9a1d1\n# ╠═fed7f592-be03-4baf-8ace-ff9ee78fee71\n# ╟─9f31928e-c933-43bb-9a5c-bf55f29737cd\n# ╟─1e6d4c72-f25d-4bf5-99d6-ae0446be25dd\n# ╟─02035eed-6d49-4253-a755-68a999e7e90e\n# ╠═c188b7cf-03e7-40b3-bf90-773978c7b410\n# ╠═f60b51b6-79c3-4a3f-8bfb-8f198cdb92a8\n# ╟─bfac7a55-0d82-4549-b999-7db3272eaa20\n# ╠═80ed91ad-6f9a-4f12-a1ee-bc8dc6b58168\n# ╠═2d8689c9-1b9e-4360-865c-23c2c8c5dcb9\n# ╠═fa4ae713-a0b2-46ce-b5f7-558b26d82019\n# ╠═760e8ca2-596f-435f-befb-140b3d204f7f\n# ╠═75956488-76ab-4262-a32f-0c53e1b3dc17\n# ╠═a55260dd-f05d-4a65-9fdf-cb3fd4638857\n# ╠═ba164ff3-5ef4-4480-8af2-9dd9a99b1e8d\n# ╠═46de28bc-73ed-495c-a2e0-f565c1ce5651\n# ╟─e004e4bf-ca04-4b41-947b-9f1ecd058abb\n# ╠═bb9d4d98-3aff-439e-b8a3-8347cf345839\n# ╟─012fa54a-5171-4980-a0ba-474a22c25981\n# ╠═f3eb8ad4-55a8-4e76-a581-07f9a7cc75f7\n", "meta": {"hexsha": "74b2a27167009d1c9007077eedcd8a80a2bd588a", "size": 19655, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Module C - Applications/L10 Spectral Graph Bipartitioning.jl", "max_stars_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_stars_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2016-06-10T09:40:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:00:08.000Z", "max_issues_repo_path": "src/Module C - Applications/L10 Spectral Graph Bipartitioning.jl", "max_issues_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_issues_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Module C - Applications/L10 Spectral Graph Bipartitioning.jl", "max_forks_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_forks_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2016-06-21T14:20:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T17:03:59.000Z", "avg_line_length": 32.4339933993, "max_line_length": 419, "alphanum_fraction": 0.686034088, "num_tokens": 8347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787566, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7760332753293216}}
{"text": "# News Boy Problem solved by L-Shaped Benders Decomposition\n# Author: Edward J. Xu, edxu96@outlook.com\n# Date: April 5th, 2019\n# 0. Set working path, install packages and use module -----------------------------------------------------------------\npush!(LOAD_PATH, \"$(homedir())/Desktop/News Boy Problem, Stochastic Programming\")\ncd(\"$(homedir())/Desktop/News Boy Problem, Stochastic Programming\")\nusing BendersLshapedStochasMilp_EDXU\nusing JuMP\nusing GLPKMathProgInterface\n# 1. Date Input --------------------------------------------------------------------------------------------------------\ndemand = [12, 14, 16, 18, 20, 22, 24, 26, 28, 30] # Demand of newspapers in each scenario\nlengthS = length(demand)\nvec_prob = [0.05, 0.10, 0.10, 0.10, 0.15, 0.15, 0.10, 0.10, 0.10, 0.05 ] # probability of scenario\nc = 20 # purchase price\np = 70 # selling price\nh = 10 # scrap value\ny = 20\n# 2. Data Transfer -----------------------------------------------------------------------------------------------------\nn_x = 10  # Number of all the x\nn_y = 1\nvec_min_y = hcat([0])\nvec_max_y = hcat([30])\nvec_f = hcat(c - 10)\nvec_pi = hcat(vec_prob)\nmat_c = zeros(10, 1, 1)\nfor i = 1:10\n    mat_c[i, :, :] = hcat([- 70 + 10])\nend\nmat_h = zeros(10, 2, 1)\nfor i = 1: 10\n    mat_h[i, 1, :] = hcat(- demand[i])\n    mat_h[i, 2, :] = hcat(0)\nend\nmat3_t = zeros(10, 2, 1)\nfor i = 1:10\n    mat3_t[i, 1, :] = hcat(0)\n    mat3_t[i, 2, :] = hcat(1)\nend\nmat3_w = - ones(10, 2, 1)\nepsilon = 0.001\ntimesIterationMax = 500\n# 3. Begin Optimization ------------------------------------------------------------------------------------------------\nBendersLshaped(; n_x = n_x, n_y = n_y, vec_min_y = vec_min_y, vec_max_y = vec_max_y, vec_f = vec_f,\n    vec_pi = vec_pi, mat_c = mat_c, mat_h = mat_h, mat3_t = mat3_t, mat3_w = mat3_w,\n    epsilon = epsilon, timesIterationMax = timesIterationMax)\n# answer: obj = - 976\n", "meta": {"hexsha": "af911de6d8be350fe96f18ef2c73f84fd48ee683", "size": 1883, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/benders/news-boy/NewsBoyData.jl", "max_stars_repo_name": "edxu96/MatrixOptim", "max_stars_repo_head_hexsha": "97ef8b1311351291427f8f650b0215c7ff00bddc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/benders/news-boy/NewsBoyData.jl", "max_issues_repo_name": "edxu96/MatrixOptim", "max_issues_repo_head_hexsha": "97ef8b1311351291427f8f650b0215c7ff00bddc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/benders/news-boy/NewsBoyData.jl", "max_forks_repo_name": "edxu96/MatrixOptim", "max_forks_repo_head_hexsha": "97ef8b1311351291427f8f650b0215c7ff00bddc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-04T09:41:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-04T09:41:13.000Z", "avg_line_length": 40.0638297872, "max_line_length": 120, "alphanum_fraction": 0.5331917153, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217417, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7760332720182201}}
{"text": "using Unitful, UnitfulAstro\nusing PhysicalConstants.CODATA2018: h, c_0, k_B\n\nexport blackbody\n\n\"\"\"\n    blackbody(wave::Vector{<:Quantity}, T::Quantity)\n    blackbody(wave::Vector{<:Real}, T::Real)\n\nCreate a blackbody spectrum using Planck's law. The curve follows the mathematical form \n\n``B_\\\\lambda(T) = \\\\frac{2hc^2}{\\\\lambda^5}\\\\frac{1}{e^{hc/\\\\lambda k_B T} - 1}``\n\nIf `wave` and `T` are not `Unitful.Quantity`, they are assumed to be in angstrom and Kelvin, and the returned flux will be in units `W m^-2 Å^-1`. \n\nThe physical constants are calculated using [PhysicalConstants.jl](https://github.com/juliaphysics/physicalconstants.jl), specifically the CODATA2018 measurement set. \n\n# References\n[Planck's Law](https://en.wikipedia.org/wiki/Planck%27s_law)\n\n# Examples\n```jldoctest\njulia> using Spectra, Unitful, UnitfulAstro\n\njulia> wave = range(1, 3, length=100)u\"μm\"\n(1.0:0.020202020202020204:3.0) μm\n\njulia> bb = blackbody(wave, 2000u\"K\")\nUnitfulSpectrum (100,)\n  λ (μm) f (W μm^-1 m^-2)\n  T: 2000 K\n  name: Blackbody\n\njulia> blackbody(ustrip.(u\"angstrom\", wave), 6000)\nSpectrum (100,)\n  T: 6000\n  name: Blackbody\n\njulia> bb.wave[argmax(bb)]\n1.4444444444444444 μm\n\njulia> 2898u\"μm*K\" / bb.T # See if it matches up with Wien's law\n1.449 μm\n```\n\"\"\"\nfunction blackbody(wave::AbstractVector{<:Quantity}, T::Quantity)\n    out_unit = u\"W/m^2\" / unit(eltype(wave))\n    flux = _blackbody(wave, T) .|> out_unit\n    return spectrum(wave, flux, name = \"Blackbody\", T = T)\nend\n\nfunction blackbody(wave::AbstractVector{<:Real}, T::Real)\n    flux = ustrip.(u\"W/m^2/angstrom\", _blackbody(wave * u\"angstrom\", T * u\"K\"))\n    return spectrum(wave, flux, name = \"Blackbody\", T = T)\nend\n\n_blackbody(wave::AbstractVector{<:Quantity}, T::Quantity) = blackbody(T).(wave)\n\n\"\"\"\n  blackbody(T::Quantity)\n\nReturns a function for calculating blackbody curves. \n\"\"\"\nblackbody(T::Quantity) = w->2h * c_0^2 / w^5 / (exp(h * c_0 / (w * k_B * T)) - 1)\n", "meta": {"hexsha": "e0d0e9175752d491ef17749d1660417e7c3c42e4", "size": 1929, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "JuliaTagBot/Spectra.jl-1", "max_stars_repo_head_hexsha": "25b987b9b368881df69bffb0d3fb17e6ec027fb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-08-21T00:42:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-07T13:17:51.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "JuliaTagBot/Spectra.jl-1", "max_issues_repo_head_hexsha": "25b987b9b368881df69bffb0d3fb17e6ec027fb6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-07-30T22:54:42.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-30T23:06:16.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "JuliaTagBot/Spectra.jl-1", "max_forks_repo_head_hexsha": "25b987b9b368881df69bffb0d3fb17e6ec027fb6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:57:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:57:13.000Z", "avg_line_length": 29.6769230769, "max_line_length": 167, "alphanum_fraction": 0.689994816, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9546474207360067, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7760016797187301}}
{"text": "## PART 2\n\n# Define the error functions\n\nfunction σf1(v̄̂,σ̂)\n    ddvs = zeros(5);\n    ddvs[1] = 1 / v̄̂[2]^2;\n    ddvs[2] = v̄̂[1]^2 / v̄̂[2]^4;\n    return sqrt( dot( ddvs, σ̂.^2) );\nend\n\nfunction σf2(v̄̂,σ̂)\n    ddvs = zeros(5);\n    ddvs[3] = exp(v̄̂[3] - v̄̂[4])^2;\n    ddvs[4] = exp(v̄̂[3] - v̄̂[4])^2;\n    return sqrt( dot( ddvs, σ̂.^2) );\nend\n\nfunction σf3(v̄̂,σ̂)\n    lv5s = log(v̄̂[5])^2;\n    ddvs = zeros(5);\n    ddvs[1] = lv5s / v̄̂[2]^2;\n    ddvs[2] = lv5s * v̄̂[1]^2 / v̄̂[2]^4;\n    ddvs[3] = lv5s / v̄̂[4]^2;\n    ddvs[4] = lv5s * v̄̂[3]^2 / v̄̂[4]^4;\n    ddvs[5] = ( ( v̄̂[1]/v̄̂[2] + v̄̂[3]/v̄̂[4] ) / v̄̂[5] )^2;\n    return sqrt( dot( ddvs, σ̂.^2) );\nend\n\nprintln(\"Calculating σ̂f1, σ̂f2, σ̂f3 for sample sizes N1, N2\");\nσ̂f1N1 = σf1(v̄̂,σ̂1); \nσ̂f2N1 = σf2(v̄̂,σ̂1);\nσ̂f3N1 = σf3(v̄̂,σ̂1);\n\nσ̂f1N2 = σf1(v̄̂,σ̂2); \nσ̂f2N2 = σf2(v̄̂,σ̂2);\nσ̂f3N2 = σf3(v̄̂,σ̂2);\n\nprintln(\"\\n\\tNaive standard deviations for sample size 1,000\");\nprintln(\"\\tσ̂f1N1 = $σ̂f1N1\"); \nprintln(\"\\tσ̂f2N1 = $σ̂f2N1\");\nprintln(\"\\tσ̂f3N1 = $σ̂f3N1\");\n\nprintln(\"\\n\\tNaive standard deviations for sample size 10,000\");\nprintln(\"\\tσ̂f1N2 = $σ̂f1N2\"); \nprintln(\"\\tσ̂f2N2 = $σ̂f2N2\");\nprintln(\"\\tσ̂f3N2 = $σ̂f3N2\");\n\nprintln(\"\\n\\tTrue standard deviations for sample size 1,000\");\nprintln(\"\\tσ̂truef1N1 = $σ̂truef1N1\"); \nprintln(\"\\tσ̂truef2N1 = $σ̂truef2N1\");\nprintln(\"\\tσ̂truef3N1 = $σ̂truef3N1\");\n\nprintln(\"\\n\\tTrue standard deviations for sample size 10,000\");\nprintln(\"\\tσ̂truef1N2 = $σ̂truef1N2\"); \nprintln(\"\\tσ̂truef2N2 = $σ̂truef2N2\");\nprintln(\"\\tσ̂truef3N2 = $σ̂truef3N2\");\n\n", "meta": {"hexsha": "8851cb971a266d7782c8ab3bf2e547eb47e4d6d5", "size": 1562, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "set03/q2/p2.jl", "max_stars_repo_name": "stefco/g6080", "max_stars_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "set03/q2/p2.jl", "max_issues_repo_name": "stefco/g6080", "max_issues_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "set03/q2/p2.jl", "max_forks_repo_name": "stefco/g6080", "max_forks_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4745762712, "max_line_length": 64, "alphanum_fraction": 0.5505761844, "num_tokens": 893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7759898337882505}}
{"text": "\"\"\"\n\tcracks2moduli(E₀, nu₀, α1, α3, β11, β13, β33)\n\nCompute 6×6 stiffness matrix (in Voight notation) for a cracked material characterised by normalised crack density parameters α1, α3, β11, β13 and β33, with solid matrix moduli E₀ and nu₀. Crack density parameters are normalised by h = 3E₀(2-nu₀)/(32(1-nu₀²)). From Sayers and Kachanov 1995.\n\"\"\"\nfunction cracks2moduli(E₀, nu₀, α1, α3, β11, β13, β33)\n    S011 = 1/E₀\n    S012 = -nu₀/E₀\n    h = cracknormfactor(E₀, nu₀)\n\n    D = (S011 + α3/h + β33/h)*(S011 + S012 + α1/h + 4β11/h/3) -\n        2*(S012 + β13/h)^2\n\n    c11 = (1/2)*((S011+α3/h+β33/h)/D + 1/(S011-S012+α1/h+2β11/h/3))\n    c33 = (S011 + S012 + α1/h + 4β11/h/3)/D\n    c44 = 1/(2S011 - 2S012 + α1/h + α3/h + 4β13/h)\n    c13 = -(S012 + β13/h)/D\n    c66 = 1/(S011-S012+α1/h+2β11/h/3)/2\n\n    return stiffmatrixTI(c11, c13, c33, c44, c66)\nend\n\n\"\"\"\n\tcracknormfactor(E₀, ν₀)\n\nCompute normalisation factor h=3E₀*(2-nu₀)/(32(1-nu₀²)).\n\"\"\"\nfunction cracknormfactor(E₀, ν₀)\n    return 3E₀*(2-ν₀)/(32(1-ν₀^2))\nend\n\n\"\"\"\n\tfindcracks(p::Vector{VMeasure},\n                    sv::Vector{VMeasure},\n                    sh::Vector{VMeasure},\n                    ρ::Real,\n                    E₀::Real,\n                    nu₀::Real,\n                    α₁₀::Tuple{Real,Real},\n                    α₃₀::Tuple{Real,Real},\n                    β₁₁₀::Tuple{Real,Real},\n                    β₁₃₀::Tuple{Real,Real},\n                    β₃₃₀::Tuple{Real,Real})\n\nEstimate normalised crack density parameters and phase angles from measurements of group P, SV ans SH wave velocities, using quasinewton method. A priori values ()₀ are tuples with value and standard deviation (a priori gaussian).\n\nReturn α₁₁, α₃₃, β₁₁₁₁, β₁₁₃₃, β₃₃₃₃, θp, θsv, θsh, CMpost.\n\"\"\"\nfunction findcracks(p::Vector{VMeasure},\n                    sv::Vector{VMeasure},\n                    sh::Vector{VMeasure},\n                    ρ::Real,\n                    E₀::Real,\n                    nu₀::Real,\n                    α₁₀::Tuple{Real,Real},\n                    α₃₀::Tuple{Real,Real},\n                    β₁₁₀::Tuple{Real,Real},\n                    β₁₃₀::Tuple{Real,Real},\n                    β₃₃₀::Tuple{Real,Real})\n\n    dobs, CDi, np, nsv, nsh = inputdobs(p,sv,sh)\n    \n    #make vector of model parameters (first guess)\n    m₀ = [α₁₀[1],α₃₀[1],β₁₁₀[1],β₁₃₀[1],β₃₃₀[1]]\n    σm = [α₁₀[2],α₃₀[2],β₁₁₀[2],β₁₃₀[2],β₃₃₀[2]]\n\n    C₀ = cracks2moduli(E₀, nu₀, m₀...)\n    ϵ₀, δ₀, γ₀ = moduli2thomsen(C₀)\n    vp,vs = velocities0(C₀,ρ) # here density does not matter\n    \n    for x in p\n        push!(m₀, phaseangleP(x.angle, vp/vs, ϵ₀, δ₀))\n        push!(σm, 100)\n    end\n    for x in sv\n        push!(m₀, phaseangleSV(x.angle, vp/vs, ϵ₀, δ₀))\n        push!(σm, 100)\n    end\n    for x in sh\n        push!(m₀, phaseangleSH(x.angle, γ₀))\n        push!(σm, 100)\n    end\n    \n    CM = Diagonal(σm.^2)\n    CMi = inv(CM)\n\n    m, CMpost = quasinewton(dobs, _gf, m₀, CMi, CDi, (E₀, nu₀, ρ,np,nsv,nsh)) \n\n    \n    return m[1:5], m[6:5+np], m[6+np:5+np+nsv], m[6+np+nsv:5+np+nsv+nsh], CMpost\n    \nend\n\nfunction _gf(m,E₀,nu₀,ρ,np,nsv,nsh)\n    C₀ = cracks2moduli(E₀, nu₀, m[1:5]...)\n    ϵ, δ, γ = moduli2thomsen(C₀)\n    vp0,vs0 = velocities0(C₀,ρ)\n    mt = vcat([vp0,vs0,ϵ,δ,γ], m[6:end])\n    return _gt(mt, np, nsv, nsh)\nend\n", "meta": {"hexsha": "676f4da0ba44b3de84822eec965e18841dd66efe", "size": 3263, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cracks.jl", "max_stars_repo_name": "BMElsigood/VTIModuli.jl", "max_stars_repo_head_hexsha": "61b98ae930a0e129c145ad2062979736d523122b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-26T00:39:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T14:46:01.000Z", "max_issues_repo_path": "src/cracks.jl", "max_issues_repo_name": "BMElsigood/VTIModuli.jl", "max_issues_repo_head_hexsha": "61b98ae930a0e129c145ad2062979736d523122b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cracks.jl", "max_forks_repo_name": "BMElsigood/VTIModuli.jl", "max_forks_repo_head_hexsha": "61b98ae930a0e129c145ad2062979736d523122b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-19T16:10:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T10:46:52.000Z", "avg_line_length": 32.3069306931, "max_line_length": 291, "alphanum_fraction": 0.5467361324, "num_tokens": 1271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632234212403, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7759898294253054}}
{"text": "include(\"setting.jl\")\n\n# jacobian of lorenz96\nfunction jac_lorenz(x::Vector{Float64})::Matrix{Float64}\n    # jac[i, j] = -1 when j = i\n    # jac[i, j] = x[i-1] when j = i+1\n    # jac[i, j] = x[i+1] - x[i-2] when j = i-1\n    # jac[i, j] = -x[i-1] when j = i-2\n    len = length(x)\n    lenm = len - 1;\n    jac = zeros(len, len)\n\n    for i = 1:len\n        ip1 = (i+1+lenm)%len+1\n        im1 = (i-1+lenm)%len+1\n        im2 = (i-2+lenm)%len+1\n        @inbounds jac[i, i] = -1\n        @inbounds jac[i, ip1] = x[im1]\n        @inbounds jac[i, im1] = x[ip1] - x[im2]\n        @inbounds jac[i, im2] = -x[im1]\n    end\n    jac\nend\n\na = repeat([1., 3, 6, 4, 5], 3)\nda = repeat([.2, .2, .2, .2, .2], 3)\nb = a + da\nfa = lorenz96(a, Missing, Missing)\nfb = lorenz96(b, Missing, Missing)\njfa = jac_lorenz(a) * da\ndisplay(jac_lorenz(a))\nprintln()\n@show fa + jfa - fb\n@assert all(abs.(fa+jfa-fb) .< 1e-6)\n", "meta": {"hexsha": "c119984c16d90dd5cd5a808c152d4b4e9fa35d38", "size": 883, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/jac_test.jl", "max_stars_repo_name": "Typas/Data-Assimilation-Project", "max_stars_repo_head_hexsha": "4b880c7faadf778d891ffab77ebfbde1db5c5baf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/jac_test.jl", "max_issues_repo_name": "Typas/Data-Assimilation-Project", "max_issues_repo_head_hexsha": "4b880c7faadf778d891ffab77ebfbde1db5c5baf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/jac_test.jl", "max_forks_repo_name": "Typas/Data-Assimilation-Project", "max_forks_repo_head_hexsha": "4b880c7faadf778d891ffab77ebfbde1db5c5baf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2285714286, "max_line_length": 56, "alphanum_fraction": 0.5175537939, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7759852604624635}}
{"text": "# Converts infix expression into reverse Polish notation\n# (Only 1-digit numbers are allowed.)\n\noperators = {\n    # opname => (operator, precedence)\n    '+' => (+, 6),\n    '-' => (-, 6),\n    '*' => (*, 7),\n    '/' => (/, 7),\n}\n\nis_operator(op) = haskey(operators, op)\nget_operator(ch) = operators[ch][1];\nget_precedence(ch) = operators[ch][2];\nPREC_OFFSET = 100\n\nfunction in2post(expr::ASCIIString)\n    opstack = Char[]\n    precedence_stack = Int[]\n    output = Char[]\n    prec_offset = 0\n\n    for ch in expr\n        if ch == '('\n            prec_offset += PREC_OFFSET\n        elseif ch == ')'\n            prec_offset -= PREC_OFFSET\n        elseif is_operator(ch)\n            precedence = get_precedence(ch) + prec_offset\n            while !isempty(opstack) && \n                precedence <= precedence_stack[end]\n                push!(output, pop!(opstack))\n                pop!(precedence_stack)\n            end\n            push!(opstack, ch)\n            push!(precedence_stack, precedence)\n        else\n            push!(output, ch)\n        end\n    end\n\n    if prec_offset != 0\n        warn(\"Unbalanced parentheses!\")\n    end\n    [output, reverse(opstack)]\nend\n\nfunction eval_post(postexp)\n    numstack = Int[]\n    for ch in postexp\n        if is_operator(ch)\n            b = pop!(numstack);\n            a = pop!(numstack);\n            push!(numstack, get_operator(ch)(a, b))\n        else\n            push!(numstack, ch - '0');\n        end\n    end\n    assert(length(numstack) == 1)\n    numstack[end]\nend\n\nexpr = strip(readline())\npostexp = in2post(expr)\n@printf(\"The converted RPN is: %s,\\nwhich = %d\", \n    join(postexp), eval_post(postexp))\n\n# Conclusion: Julia is far from mature enough to use in production.\n", "meta": {"hexsha": "9d7fc31f296e1d66c4ba102b5c6a3d9c9fd41030", "size": 1715, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Infix2Postfix/in2post.jl", "max_stars_repo_name": "gyk/TrivialSolutions", "max_stars_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T05:51:37.000Z", "max_issues_repo_path": "Infix2Postfix/in2post.jl", "max_issues_repo_name": "gyk/TrivialSolutions", "max_issues_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Infix2Postfix/in2post.jl", "max_forks_repo_name": "gyk/TrivialSolutions", "max_forks_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8550724638, "max_line_length": 67, "alphanum_fraction": 0.5580174927, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7759852530747593}}
{"text": "@doc raw\"\"\"\r\n```\r\nbinarize(Balanced(), img)\r\n```\r\nBinarizes the image using the balanced histogram thresholding method.\r\n\r\n# Output\r\n\r\nReturns the binarized image as an `Array{Gray{Bool},2}`.\r\n\r\n# Details\r\nIn balanced histogram thresholding, one interprets a  bin as a  physical weight\r\nwith a mass equal to its occupancy count. The balanced histogram method involves\r\niterating the following three steps: (1) choose the midpoint bin index as a\r\n\"pivot\",  (2) compute the combined weight to the left and right of the pivot bin\r\nand (3) remove the leftmost bin if the left side is the heaviest, and the\r\nrightmost bin otherwise. The algorithm stops when only a single bin remains. The\r\nlast bin determines the sought-after threshold with which the image is\r\nbinarized.\r\n\r\nLet ``f_n`` (``n = 1 \\ldots N``) denote the number of observations in the ``n``th\r\nbin of the image histogram. The balanced histogram method constructs a sequence\r\nof nested intervals\r\n\r\n```math\r\n[1,N] \\cap \\mathbb{Z} \\supset I_2 \\supset I_3 \\supset \\ldots \\supset I_{N-1},\r\n```\r\nwhere for ``k = 2 \\ldots N-1``\r\n```math\r\nI_k = \\begin{cases}\r\n   I_{k-1} \\setminus \\{\\min \\left( I_{k-1} \\right) \\} &\\text{if } \\sum_{n = \\min \\left( I_{k-1} \\right)}^{I_m}f_n \\gt   \\sum_{n =  I_m + 1}^{ \\max \\left( I_{k-1} \\right)} f_n, \\\\\r\n   I_{k-1} \\setminus \\{\\max \\left( I_{k-1} \\right) \\} &\\text{otherwise},\r\n\\end{cases}\r\n```\r\nand ``I_m = \\lfloor \\frac{1}{2}\\left(  \\min \\left( I_{k-1} \\right) +  \\max \\left( I_{k-1} \\right) \\right) \\rfloor ``.\r\nThe final interval ``I_{N-1}`` consists of a single element which is the bin index\r\ncorresponding to the desired threshold.\r\n\r\nIf one interprets a bin as a physical weight with a mass equal to its occupancy\r\ncount, then each step of the algorithm can be conceptualised as removing the\r\nleftmost or rightmost bin to \"balance\" the resulting histogram on a pivot. The\r\npivot is defined to be the midpoint between the start and end points of the\r\ninterval under consideration.\r\n\r\nIf it turns out that the single element in ``I_{N-1}`` equals ``1`` or ``N`` then\r\nthe original histogram must have a single peak and the algorithm has failed to\r\nfind a suitable threshold. In this case the algorithm will fall back to using\r\nthe `UnimodalRosin` method to select the threshold.\r\n\r\n\r\n# Arguments\r\n\r\nThe function argument is described in more detail below.\r\n\r\n##  `img`\r\n\r\nAn `AbstractArray` representing an image. The image is automatically converted\r\nto `Gray` in order to construct the requisite graylevel histogram.\r\n\r\n\r\n# Example\r\n\r\nBinarize the \"cameraman\" image in the `TestImages` package.\r\n\r\n```julia\r\nusing TestImages, ImageBinarization\r\n\r\nimg = testimage(\"cameraman\")\r\nimg_binary = binarize(Balanced(), img)\r\n```\r\n\r\n# Reference\r\n\r\n1. “BI-LEVEL IMAGE THRESHOLDING - A Fast Method”, Proceedings of the First International Conference on Bio-inspired Systems and Signal Processing, 2008. Available: [10.5220/0001064300700076](https://doi.org/10.5220/0001064300700076)\r\n\"\"\"\r\nfunction binarize(algorithm::Balanced,  img::AbstractArray{T,2}) where T <: Colorant\r\n  img₀₁ = zeros(Gray{Bool}, axes(img))\r\n  edges, counts = build_histogram(img,  256)\r\n  t = find_threshold(HistogramThresholding.Balanced(), counts[1:end], edges)\r\n  for i in CartesianIndices(img)\r\n    img₀₁[i] = img[i] < t ? 0 : 1\r\n  end\r\n  img₀₁\r\nend\r\n", "meta": {"hexsha": "c02e4d93688d5ee0c85d610c9040e77f025b4aab", "size": 3315, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/balanced.jl", "max_stars_repo_name": "bellascalzi1/ImageBinarization.jl", "max_stars_repo_head_hexsha": "43011cd85eff0fefcaadb14f517eb75160c7d5e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/balanced.jl", "max_issues_repo_name": "bellascalzi1/ImageBinarization.jl", "max_issues_repo_head_hexsha": "43011cd85eff0fefcaadb14f517eb75160c7d5e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/balanced.jl", "max_forks_repo_name": "bellascalzi1/ImageBinarization.jl", "max_forks_repo_head_hexsha": "43011cd85eff0fefcaadb14f517eb75160c7d5e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0, "max_line_length": 233, "alphanum_fraction": 0.7095022624, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7759852437745827}}
{"text": "function boxcox(z, λ)\n    reduce(&, z .> 0) || throw(DomainError(\"boxcox requires strictly positive data\"))\n\tif λ == 0\n\t\treturn log.(z) \n\telse\n\t\treturn (z.^λ .- 1) ./ λ\n\tend\nend\n\nfunction inv_boxcox(z, λ)\n    if λ == 0\n        return exp.(z)\n    else \n        return (λ .* z .+ 1).^(1/λ)\n    end\nend\n\nfunction guerrero(z; lower=-1, upper=2, s=2)\n    s >= 2 || throw(ArgumentError(\"guerrero requires seasonality to be higher or equal to 2\"))\n    N = length(z)\n    rz = reshape(view(z, (N % s + 1):N), N ÷ s, s)\n    m = mean(rz, dims=1)\n    sd = std(rz, mean=m, dims=1)\n    function cv(λ)\n        w = sd ./ (m.^(1 - λ))\n        mw = mean(w)\n        return std(w, mean=mw) / mw\n    end\n    return optimize(cv, lower, upper).minimizer\nend\n\nfunction difference(z::AbstractVector{T}; d::Integer=1,s::Integer=1) where T\n    N = length(z)\n    differenced = Vector{T}(undef, N)\n    @inbounds @simd for i in 1:N\n        differenced[i] = z[i]\n    end\n    @inbounds for j in 1:d\n        for i in 1:N - j * s\n            differenced[N - i + 1] -= differenced[N - i + 1 - s]\n        end\n    end\n    return differenced[1 + d * s:N]\nend\n\nfunction integrate(z::AbstractVector{T}, z0::AbstractVector; d::Integer=1,s::Integer=1) where T\n    N = length(z)\n    integrated = Vector{T}(undef, N + d * s)\n    N0 = length(z0)\n    for i in 1:N + d * s\n        integrated[i] = i > d * s ? z[i - d * s] : i > N0 ? zero(T) : z0[i]\n    end\n    for j in 1:d\n        for i in (1 + s):N + d * s\n            integrated[i] += integrated[i - s]\n        end    \n    end\n    return integrated\nend\n\nintegrate(z::AbstractVector{T}; d::Integer=1,s::Integer=1) where T = integrate(z, T[], d=d, s=s)", "meta": {"hexsha": "1097c03400d46e8d02d701f76bcf9aeb346c4fbd", "size": 1656, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transforms.jl", "max_stars_repo_name": "pierrenodet/AutoARIMA.jl", "max_stars_repo_head_hexsha": "3bcfbda02b94fc249f60a431820df74081ee3c45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-06-06T22:29:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T03:00:23.000Z", "max_issues_repo_path": "src/transforms.jl", "max_issues_repo_name": "pierrenodet/AutoARIMA.jl", "max_issues_repo_head_hexsha": "3bcfbda02b94fc249f60a431820df74081ee3c45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-05-03T11:21:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-07T15:21:55.000Z", "max_forks_repo_path": "src/transforms.jl", "max_forks_repo_name": "pierrenodet/AutoARIMA.jl", "max_forks_repo_head_hexsha": "3bcfbda02b94fc249f60a431820df74081ee3c45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1475409836, "max_line_length": 96, "alphanum_fraction": 0.5452898551, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7759803768164028}}
{"text": "using Plots,ApproxFun;pyplot()\n\nx = Fun(identity,[0.,10.])\nf = sin(x^2)\ng = cos(x)\n\nh = f + g^2\nr = roots(h)\nrp = roots(differentiate(h))\nplot(h;legend=false,grid=false)\nscatter!(r,h(r))\nscatter!(rp,h(rp))\nxlabel!(\"\\$x\\$\")\nylabel!(\"\\$h(x)\\$\")\nxlims!(0,10)\nPyPlot.savefig(\"extrema.png\",dpi=300)\nprintln(\"First image done\")\n\n\nx = Fun(identity,[-1000.,200.])\nd = domain(x)\nD = Derivative(d)\nB = dirichlet(d)\nL = D^2 - x\nu = [B;L] \\ [airyai(d.a),airyai(d.b)]\nplot(u;legend=false,grid=false)\t\t\t\t\t\t    # Requires Gadfly or PyPlot\nxlabel!(\"\\$x\\$\");ylabel!(\"\\${\\\\rm Ai}(x)\\$\")\nPyPlot.savefig(\"airy.png\",dpi=300)\n\nprintln(\"Second image done\")\n\n\nd = Interval(-π,π)\na = Fun(t-> 1+sin(cos(2t)),d)\nD = Derivative(d)\nL = D + a\nf = Fun(t->exp(sin(10t)),d)\nB = periodic(d,0)\nuChebyshev = [B;L]\\[0.,f]\n\nd = PeriodicSegment([-π,π])\na = Fun(t-> 1+sin(cos(2t)),d)\nD = Derivative(d)\nL = D + a\nf = Fun(t->exp(sin(10t)),d)\nuFourier = L\\f\n\nlength(uFourier)/length(uChebyshev),2/π\nplot(real(uFourier);legend=false,grid=false)\t\t\t\t\t\t    # Requires Gadfly or PyPlot\nxlims!(d.a,d.b);xlabel!(\"\\$t\\$\");ylabel!(\"\\$u(t)\\$\")\nPyPlot.savefig(\"periodic.png\",dpi=300)\n\nprintln(\"Third image done\")\n\n\nf = abs(Fun(sin,[-5.,5.]))\nd = domain(f)\nx = ApproxFun.sample(f,10000)\nplot(f/sum(f);legend=false,grid=false)                           # Requires Gadfly or PyPlot\nhistogram!(x;normed=true,nbins=100)\nxlims!(leftendpoint(d),rightendpoint(d));ylims!(0.0,0.18);xlabel!(\"\\$x\\$\");ylabel!(\"Density\")\nPyPlot.savefig(\"Sample.png\",dpi=300)\n\nprintln(\"Fourth image done\")\n\n\n\n## Nonlinear BVP\n\nx=Fun()\nu0=0x\n\nN=u->[u(-1.)-1.,u(1.)+0.5,0.001u''+6*(1-x^2)*u'+u^2-1.]\nu=newton(N,u0)\nplot(u;legend=false,grid=false)\nPyPlot.savefig(\"nbvp.png\",dpi=300)\n\nprintln(\"Fifth image done\")\n\n\n## Multivariate\n\n\nd = ChebyshevInterval()^2                            # Defines a rectangle\n\nu = [dirichlet(d);lap(d)+100I]\\[[1.0,1.0,1.0,1.0]]      # First four entries of rhs are\n                                            # boundary conditions\nsurface(u,grid=false)                                     # contour plot\n\nPyPlot.savefig(\"helmholtz.png\",dpi=300)\n", "meta": {"hexsha": "dc63fb69d59936d897b3aedab173ff24061c8d6f", "size": 2089, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "images/images.jl", "max_stars_repo_name": "simonbyrne/ApproxFun.jl", "max_stars_repo_head_hexsha": "de05c449ad5054e964a12a593592d23c848d98e4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 372, "max_stars_repo_stars_event_min_datetime": "2016-12-02T13:14:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:13:18.000Z", "max_issues_repo_path": "images/images.jl", "max_issues_repo_name": "RickeyEstes/ApproxFun.jl", "max_issues_repo_head_hexsha": "34a40214e348782e7903a465eb49aef3fb4dc675", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 317, "max_issues_repo_issues_event_min_datetime": "2016-11-29T22:32:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T09:24:07.000Z", "max_forks_repo_path": "images/images.jl", "max_forks_repo_name": "RickeyEstes/ApproxFun.jl", "max_forks_repo_head_hexsha": "34a40214e348782e7903a465eb49aef3fb4dc675", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 73, "max_forks_repo_forks_event_min_datetime": "2016-12-08T05:10:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T10:34:22.000Z", "avg_line_length": 22.956043956, "max_line_length": 93, "alphanum_fraction": 0.5940641455, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7759803658277813}}
{"text": "__precompile__()\n\nmodule Vandermonde\n\nexport pvand\n\nfunction pvand(alpha, b)\n    # x = pvand(alpha, b)\n    #\n    # Solves system A*x = b\n    # A is Vandermonde matrix, with nonstandard definition\n    # A(i,j) = alpha(j)^i\n    #\n    # Algorithm by Bjorck & Pereyra\n    # Mathematics of Computation, Vol. 24, No. 112 (1970), pp. 893-903\n    # https://doi.org/10.2307/2004623    \n    #\n    n = length(alpha);\n    x = copy(b);\n    for k=1:n\n        for j=n:-1:k+1\n            x[j] = x[j]-alpha[k]*x[j-1];\n        end\n    end\n    for k=n-1:-1:1\n        for j=k+1:n\n            x[j] = x[j]/(alpha[j]-alpha[j-k]);\n        end\n        for j=k:n-1\n            x[j] = x[j]-x[j+1];\n        end\n    end\n    return x\nend\n\nend\n", "meta": {"hexsha": "5189d2bcafd5f47348493e48eeca1347adff2010", "size": 713, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/src/Vandermonde.jl", "max_stars_repo_name": "askhamwhat/inse-fiem-2d", "max_stars_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-08-20T12:53:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:15:10.000Z", "max_issues_repo_path": "julia/src/Vandermonde.jl", "max_issues_repo_name": "askhamwhat/inse-fiem-2d", "max_issues_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/src/Vandermonde.jl", "max_forks_repo_name": "askhamwhat/inse-fiem-2d", "max_forks_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-28T18:44:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T04:17:59.000Z", "avg_line_length": 19.2702702703, "max_line_length": 70, "alphanum_fraction": 0.4992987377, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973294, "lm_q2_score": 0.8376199572530449, "lm_q1q2_score": 0.7758904960844669}}
{"text": "\n\nusing SpecialFunctions\n\ninclude(\"spindown_besselzeros.jl\")\n\nfunction u_spindown(r, t, Re)\n    # Assuming unit radius, speed and viscosity\n    Omega, a = 1.0, 1.0\n    nu = 1.0/Re\n    S = 0.0\n    ds = 0.0\n    relerr = 0.0\n    for n=1:length(lambda)\n        ds = besselj(1, lambda[n]*r/a) / (lambda[n]*besselj(0, lambda[n]))*exp(-lambda[n]^2*nu*t/a)\n        S += ds\n        relerr = abs(ds/S) # If convergence is nice enough            \n        if relerr < eps()\n            break\n        end\n    end\n    if relerr > eps()\n        warn(\"Spindown solution not converged, relerr=\", relerr)\n    end\n    u = -2*Omega*a*S\nend\n\n\nfunction Lu_spindown(r, t, Re)\n    # Laplacian of the above\n    Omega, a = 1.0, 1.0\n    nu = 1.0/Re    \n    S = 0.0\n    ds = 0.0\n    relerr = 0.0\n    for n=1:length(lambda)\n        b = lambda[n]/a\n        ds = -b^2*besselj(1, b*r) / (lambda[n]*besselj(0, lambda[n]))*exp(-lambda[n]^2*nu*t/a)\n        S += ds\n        relerr = abs(ds/S) # If convergence is nice enough            \n        if relerr < eps()\n            break\n        end\n    end\n    if relerr > eps()\n        warn(\"Spindown solution not converged, relerr=\", relerr)\n    end\n    u = -2*Omega*a*S\nend\n\nfunction Du_spindown(r, t, Re)\n    # r derivative\n    Omega, a = 1.0, 1.0\n    nu = 1.0/Re    \n    S = 0.0\n    ds = 0.0\n    relerr = 0.0\n    for n=1:length(lambda)\n        b = lambda[n]/a\n        ds = b/2*(besselj(0, b*r)-besselj(2, b*r)) / (lambda[n]*besselj(0, lambda[n]))*exp(-lambda[n]^2*nu*t/a)\n        S += ds\n        relerr = abs(ds/S) # If convergence is nice enough            \n        if relerr < eps()\n            break\n        end\n    end\n    if relerr > eps()\n        warn(\"Spindown solution not converged, relerr=\", relerr)\n    end\n    u = -2*Omega*a*S\nend\n\n\nfunction plot_spindown(t, Re)\n    r = linspace(0,1,200)\n    u = map(x -> u_spindown(x, t, Re), r)\n    plot(r, u, label=\"Reference\")\nend\n", "meta": {"hexsha": "8da5f82718ff7c9799f7e39a3f3ed5c0bc967b8f", "size": 1894, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/output_scripts/spindown_solution.jl", "max_stars_repo_name": "askhamwhat/inse-fiem-2d", "max_stars_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-08-20T12:53:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:15:10.000Z", "max_issues_repo_path": "julia/output_scripts/spindown_solution.jl", "max_issues_repo_name": "askhamwhat/inse-fiem-2d", "max_issues_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/output_scripts/spindown_solution.jl", "max_forks_repo_name": "askhamwhat/inse-fiem-2d", "max_forks_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-28T18:44:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T04:17:59.000Z", "avg_line_length": 23.9746835443, "max_line_length": 111, "alphanum_fraction": 0.5227032735, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7758803983450323}}
{"text": "# Part of submodule Utils of BetaML _ the Beta Machine Learning Toolkit\n# Various measures of pairs (x,y) (including vectors or matrix pairs)\n\n# ------------------------------------------------------------------------------\n# Some common distance measures\n\n\"\"\"L1 norm distance (aka _Manhattan Distance_)\"\"\"\nl1_distance(x,y)     = sum(abs.(x-y))\n\"\"\"Euclidean (L2) distance\"\"\"\nl2_distance(x,y)     = norm(x-y)\n\"\"\"Squared Euclidean (L2) distance\"\"\"\nl2²_distance(x,y)    = norm(x-y)^2\n\"\"\"Cosine distance\"\"\"\ncosine_distance(x,y) = dot(x,y)/(norm(x)*norm(y))\n\n\n################################################################################\n### VARIOUS ERROR / LOSS / ACCURACY MEASURES\n################################################################################\n\n# ------------------------------------------------------------------------------\n# Classification tasks...\n\n# Used as neural network loss function\n\"\"\"\n   crossEntropy(ŷ, y; weight)\n\nCompute the (weighted) cross-entropy between the predicted and the sampled probability distributions.\n\nTo be used in classification problems.\n\n\"\"\"\ncrossEntropy(ŷ, y; weight = ones(eltype(y),length(y)))  = -sum(y .* log.(ŷ .+ 1e-15) .* weight)\ndCrossEntropy(ŷ, y; weight = ones(eltype(y),length(y))) = - y .* weight ./ (ŷ .+ 1e-15)\n\n\n\"\"\" accuracy(ŷ,y;ignoreLabels=false) - Categorical accuracy between two vectors (T vs T). \"\"\"\nfunction accuracy(ŷ::AbstractArray{T,1},y::AbstractArray{T,1}; ignoreLabels=false)  where {T}\n    # See here for better performances: https://discourse.julialang.org/t/permutations-of-a-vector-that-retain-the-vector-structure/56790/7\n    if(!ignoreLabels)\n        return sum(ŷ .== y)/length(ŷ)\n    else\n        classes  = unique(y)\n        nCl      = length(classes)\n        N        = size(y,1)\n        pSet     =  collect(permutations(1:nCl))\n        bestAcc  = -Inf\n        yOrigIdx = [findfirst(x -> x == y[i] , classes) for i in 1:N]\n        ŷOrigIdx = [findfirst(x -> x == ŷ[i] , classes) for i in 1:N]\n        for perm in pSet\n            py = perm[yOrigIdx] # permuted specific version\n            acc = sum(ŷOrigIdx .== py)/N\n            if acc > bestAcc\n                bestAcc = acc\n            end\n        end\n        return bestAcc\n    end\nend\n\n\"\"\" error(ŷ,y;ignoreLabels=false) - Categorical error (T vs T)\"\"\"\nerror(ŷ::AbstractArray{T,1},y::AbstractArray{T,1}; ignoreLabels=false) where {T} = (1 - accuracy(ŷ,y;ignoreLabels=ignoreLabels) )\n\n\n\"\"\"\n    accuracy(ŷ,y;tol)\nCategorical accuracy with probabilistic prediction of a single datapoint (PMF vs Int).\n\nUse the parameter tol [def: `1`] to determine the tollerance of the prediction, i.e. if considering \"correct\" only a prediction where the value with highest probability is the true value (`tol` = 1), or consider instead the set of `tol` maximum values.\n\"\"\"\nfunction accuracy(ŷ::Array{T,1},y_pos::Int64;tol=1,rng=Random.GLOBAL_RNG) where {T <: Number}\n    #if  length(Set(ŷ) == 1                         # all classes the same prob\n    #    return rand(rng) < (1 / length(y)) ? 1 : 0 # If all values have the same prob, it returns 1 with prob 1/nClasses\n    #end\n    tol > 1 || return mode(ŷ;rng=rng) == y_pos ? 1 : 0 # if tol is one we delegate the choice of a single prediction to mode, that handles multimodal pmfs\n    sIdx = sortperm(ŷ)[end:-1:1]\n    if ŷ[y_pos] in ŷ[sIdx[1:min(tol,length(sIdx))]]\n        return 1\n    else\n        return 0\n    end\nend\n\n\"\"\"\n    accuracy(ŷ,y;tol)\n\nCategorical accuracy with probabilistic prediction of a single datapoint given in terms of a dictionary of probabilities (Dict{T,Float64} vs T).\n\n# Parameters:\n- `ŷ`: The returned probability mass function in terms of a Dictionary(Item1 => Prob1, Item2 => Prob2, ...)\n- `tol`: The tollerance to the prediction, i.e. if considering \"correct\" only a prediction where the value with highest probability is the true value (`tol` = 1), or consider instead the set of `tol` maximum values [def: `1`].\n\"\"\"\nfunction accuracy(ŷ::Dict{T,Float64},y::T;tol=1,rng=Random.GLOBAL_RNG) where {T}\n    if !(y in keys(ŷ)) return 0 end\n    tol > 1 || return (mode(ŷ;rng=rng) == y) ? 1 : 0 # if tol is one we delegate the choice of a single prediction to mode, that handles multimodal pmfs\n    sIdx  = sortperm(collect(values(ŷ)))[end:-1:1]            # sort by decreasing values of the dictionary values\n    sKeys = collect(keys(ŷ))[sIdx][1:min(tol,length(sIdx))]  # retrieve the corresponding keys\n    return (y in sKeys) ? 1 : 0\nend\n\n@doc raw\"\"\"\n   accuracy(ŷ,y;tol,ignoreLabels)\n\nCategorical accuracy with probabilistic predictions of a dataset (PMF vs Int).\n\n# Parameters:\n- `ŷ`: An (N,K) matrix of probabilities that each ``\\hat y_n`` record with ``n \\in 1,....,N``  being of category ``k`` with $k \\in 1,...,K$.\n- `y`: The N array with the correct category for each point $n$.\n- `tol`: The tollerance to the prediction, i.e. if considering \"correct\" only a prediction where the value with highest probability is the true value (`tol` = 1), or consider instead the set of `tol` maximum values [def: `1`].\n- `ignoreLabels`: Whether to ignore the specific label order in y. Useful for unsupervised learning algorithms where the specific label order don't make sense [def: false]\n\n\"\"\"\nfunction accuracy(ŷ::Array{T,2},y::Array{Int64,1};tol=1,ignoreLabels=false,rng=Random.GLOBAL_RNG) where {T <: Number}\n    (N,D) = size(ŷ)\n    pSet = ignoreLabels ? collect(permutations(1:D)) : [collect(1:D)]\n    bestAcc = -Inf\n    for perm in pSet\n        pŷ = hcat([ŷ[:,c] for c in perm]...)\n        acc = sum([accuracy(pŷ[i,:],y[i];tol=tol,rng=rng) for i in 1:N])/N\n        if acc > bestAcc\n            bestAcc = acc\n        end\n    end\n    return bestAcc\nend\n\n@doc raw\"\"\"\n   accuracy(ŷ,y;tol)\n\nCategorical accuracy with probabilistic predictions of a dataset given in terms of a dictionary of probabilities (Dict{T,Float64} vs T).\n\n# Parameters:\n- `ŷ`: An array where each item is the estimated probability mass function in terms of a Dictionary(Item1 => Prob1, Item2 => Prob2, ...)\n- `y`: The N array with the correct category for each point $n$.\n- `tol`: The tollerance to the prediction, i.e. if considering \"correct\" only a prediction where the value with highest probability is the true value (`tol` = 1), or consider instead the set of `tol` maximum values [def: `1`].\n\n\"\"\"\nfunction accuracy(ŷ::Array{Dict{T,Float64},1},y::Array{T,1};tol=1,rng=Random.GLOBAL_RNG) where {T}\n    N = size(ŷ,1)\n    acc = sum([accuracy(ŷ[i],y[i];tol=tol,rng=rng) for i in 1:N])/N\n    return acc\nend\n\n\n\"\"\" error(ŷ,y) - Categorical error with probabilistic prediction of a single datapoint (PMF vs Int). \"\"\"\nerror(ŷ::Array{T,1},y::Int64;tol=1) where {T <: Number} = 1 - accuracy(ŷ,y;tol=tol)\n\"\"\" error(ŷ,y) - Categorical error with probabilistic predictions of a dataset (PMF vs Int). \"\"\"\nerror(ŷ::Array{T,2},y::Array{Int64,1};tol=1) where {T <: Number} = 1 - accuracy(ŷ,y;tol=tol)\n\"\"\" error(ŷ,y) - Categorical error with with probabilistic predictions of a dataset given in terms of a dictionary of probabilities (Dict{T,Float64} vs T). \"\"\"\nerror(ŷ::Array{Dict{T,Float64},1},y::Array{T,1};tol=1) where {T} = 1 - accuracy(ŷ,y;tol=tol)\n\n\"\"\"\n    ConfusionMatrix\n\n\nScores and measures resulting from a comparation between true and predicted categorical variables\n\nUse the function `ConfusionMatrix(ŷ,y;classes,labels,rng)` to build it and `report(cm::ConfusionMatrix;what)` to visualise it, or use the individual parts of interest, e.g. `display(cm.scores)`.\n\n# Fields:\n- `labels`: Array of categorical labels\n- `accuracy`: Overall accuracy rate\n- `misclassification`: Overall misclassification rate\n- `actualCount`: Array of counts per lebel in the actual data\n- `predictedCount`: Array of counts per label in the predicted data\n- `scores`: Matrix actual (rows) vs predicted (columns)\n- `normalisedScores`: Normalised scores\n- `tp`: True positive (by class)\n- `tn`: True negative (by class)\n- `fp`: False positive (by class), aka \"type I error\" or \"false allarm\"\n- `fn`: False negative (by class), aka \"type II error\" or \"miss\"\n- `precision`: True class i over predicted class i (by class)\n- `recall`: Predicted class i over true class i (by class), aka \"True Positive Rate (TPR)\", \"Sensitivity\" or \"Probability of detection\"\n- `specificity`: Predicted not class i over true not class i (by class), aka \"True Negative Rate (TNR)\"\n- `f1Score`: Harmonic mean of precision and recall\n- `meanPrecision`: Mean by class, respectively unweighted and weighted by actualCount\n- `meanRecall`: Mean by class, respectively unweighted and weighted by actualCount\n- `meanSpecificity`: Mean by class, respectively unweighted and weighted by actualCount\n- `meanF1Score`: Mean by class, respectively unweighted and weighted by actualCount\n\n\n\"\"\"\nstruct ConfusionMatrix{T}\n    classes::Vector{T}                      # Array of categorical labels\n    labels::Vector{String}                  # String representation of the categories\n    accuracy::Float64                       # Overall accuracy rate\n    misclassification::Float64              # Overall misclassification rate\n    actualCount::Vector{Int64}              # Array of counts per lebel in the actual data\n    predictedCount::Vector{Int64}           # Array of counts per label in the predicted data\n    scores::Array{Int64,2}                  # Matrix actual (rows) vs predicted (columns)\n    normalisedScores::Array{Float64,2}      # Normalised scores\n    tp::Vector{Int64}                       # True positive (by class)\n    tn::Vector{Int64}                       # True negative (by class)\n    fp::Vector{Int64}                       # False positive (by class)\n    fn::Vector{Int64}                       # False negative (by class)\n    precision::Vector{Float64}              # True class i over predicted class i (by class)\n    recall::Vector{Float64}                 # Predicted class i over true class i (by class)\n    specificity::Vector{Float64}            # Predicted not class i over true not class i (by class)\n    f1Score::Vector{Float64}                # Harmonic mean of precision and recall\n    meanPrecision::Tuple{Float64,Float64}   # Mean by class, respectively unweighted and weighted by actualCount\n    meanRecall::Tuple{Float64,Float64}      # Mean by class, respectively unweighted and weighted by actualCount\n    meanSpecificity::Tuple{Float64,Float64} # Mean by class, respectively unweighted and weighted by actualCount\n    meanF1Score::Tuple{Float64,Float64}     # Mean by class, respectively unweighted and weighted by actualCount\nend\n\n# Resources concerning Confusion Matrices:\n# https://towardsdatascience.com/confusion-matrix-for-your-multi-class-machine-learning-model-ff9aa3bf7826\n# https://en.wikipedia.org/wiki/Confusion_matrix\n# https://scikit-learn.org/stable/modules/model_evaluation.html#classification-metrics\n# https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html\n\n\"\"\"\n    ConfusionMatrix(ŷ,y;classes,labels,rng)\n\nBuild a \"confusion matrix\" between predicted (columns) vs actual (rows) categorical values\n\n# Parameters:\n- `ŷ`: Vector of predicted categorical data\n- `y`: Vector of actual categorical data\n- `classes`: The full set of possible classes (useful to give a specicif order or if not al lclasses are represented in `y`) [def: `unique(y)` ]\n- `labels`: String representation of the classes [def: `string.(classes)`]\n- `rng`: Random number generator. Used only if `ŷ` is given in terms of a PMF and there are multi-modal values, as these are assigned randomply [def: `Random.GLOBAL_RNG`]\n\n# Return:\n- a `ConfusionMatrix` object\n\"\"\"\nfunction ConfusionMatrix(ŷ,y::AbstractArray{T};classes=unique(y),labels=string.(classes),rng=Random.GLOBAL_RNG) where {T}\n    nCl              = length(labels)\n    ŷ                = typeof(ŷ) <: AbstractVector{T} ? ŷ : mode(ŷ,rng=rng) # get the mode if needed\n    N                = length(y)\n    length(ŷ) == N || @error \"ŷ and y must have the same length in ConfusionMatrix\"\n    actualCount      = [get(classCountsWithLabels(y),i,0) for i in classes]   # TODO just use classCount\n    predictedCount   = [get( classCountsWithLabels(ŷ),i,0) for i in classes]  # TODO just use classCount\n    scores           = zeros(Int64,(nCl,nCl))\n    normalisedScores = zeros(Float64,(nCl,nCl))\n    [scores[findfirst(x -> x == y[i],classes),findfirst(x -> x == ŷ[i],classes)] += 1 for i in 1:N]\n    [normalisedScores[r,:] = scores[r,:] ./ actualCount[r] for r in 1:nCl]\n    tp = [scores[i,i] for i in 1:nCl]\n    tn = [sum(scores[r,c] for r in 1:nCl, c in 1:nCl if r != i && c != i)  for i in 1:nCl]\n    fp = [sum(scores[r,c] for r in 1:nCl, c in 1:nCl if r != i && c == i)  for i in 1:nCl]\n    fn = [sum(scores[r,c] for r in 1:nCl, c in 1:nCl if r == i && c != i)  for i in 1:nCl]\n    precision         = tp ./ (tp .+ fp)\n    recall            = tp ./ (tp .+ fn)\n    specificity       = tn ./ (tn .+ fp)\n    #f1Score           = 2 .* (precision .* recall) ./ (precision .+ recall)\n    f1Score           = (2 .* tp) ./ (2 .* tp  .+ fp .+ fn )\n    meanPrecision     = (mean(precision), sum(precision .* actualCount) / sum(actualCount) )\n    meanRecall        = (mean(recall), sum(recall .* actualCount) / sum(actualCount) )\n    meanSpecificity   = (mean(specificity), sum(specificity .* actualCount) / sum(actualCount) )\n    meanF1Score       = (mean(f1Score), sum(f1Score .* actualCount) / sum(actualCount) )\n    accuracy          = sum(tp)/N\n    misclassification = 1-accuracy\n    return  ConfusionMatrix(classes,labels,accuracy,misclassification,actualCount,predictedCount,scores,normalisedScores,tp,tn,fp,fn,precision,recall,specificity,f1Score,meanPrecision,meanRecall,meanSpecificity,meanF1Score)\nend\n\n\nimport Base.print, Base.println\n\"\"\"\n    print(cm,what)\n\nPrint a `ConfusionMatrix` object\n\nThe `what` parameter is a string vector that can include \"all\", \"scores\", \"normalisedScores\" or \"report\" [def: `[\"all\"]`]\n\"\"\"\nfunction print(io::IO,cm::ConfusionMatrix{T},what=\"all\") where T\n   if what == \"all\" || what == [\"all\"]\n       what = [\"scores\", \"normalisedScores\", \"report\" ]\n   end\n   nCl = length(cm.labels)\n\n   println(\"\\n-----------------------------------------------------------------\\n\")\n   if( \"scores\" in what || \"normalisedScores\" in what)\n     println(\"*** CONFUSION MATRIX ***\")\n   end\n   if \"scores\" in what\n       println(\"\")\n       println(\"Scores actual (rows) vs predicted (columns):\\n\")\n       displayScores = vcat(permutedims(cm.labels),cm.scores)\n       displayScores = hcat(vcat(\"Labels\",cm.labels),displayScores)\n       show(stdout, \"text/plain\", displayScores)\n   end\n   if \"normalisedScores\" in what\n       println(io,\"\")\n       println(io,\"Normalised scores actual (rows) vs predicted (columns):\\n\")\n       displayScores = vcat(permutedims(cm.labels),cm.normalisedScores)\n       displayScores = hcat(vcat(\"Labels\",cm.labels),displayScores)\n       show(stdout, \"text/plain\", displayScores)\n   end\n   if \"report\" in what\n     println(\"\\n *** CONFUSION REPORT ***\\n\")\n     labelWidth =  max(8,   maximum(length.(string.(cm.labels)))+1  )\n     println(\"- Accuracy:               $(cm.accuracy)\")\n     println(\"- Misclassification rate: $(cm.misclassification)\")\n     println(\"- Number of classes:      $(nCl)\")\n     println(\"\")\n     println(\"  N \",rpad(\"Class\",labelWidth),\"precision   recall  specificity  f1Score  actualCount  predictedCount\")\n     println(\"    \",rpad(\" \",labelWidth), \"              TPR       TNR                 support                  \")\n     println(\"\")\n     # https://discourse.julialang.org/t/printf-with-variable-format-string/3805/4\n     print_formatted(fmt, args...) = @eval @printf($fmt, $(args...))\n     for i in 1:nCl\n        print_formatted(\"%3d %-$(labelWidth)s %8.3f %8.3f %12.3f %8.3f %12i %15i\\n\", i, string(cm.labels[i]),  cm.precision[i], cm.recall[i], cm.specificity[i], cm.f1Score[i], cm.actualCount[i], cm.predictedCount[i])\n     end\n     println(\"\")\n     print_formatted(\"- %-$(labelWidth+2)s %8.3f %8.3f %12.3f %8.3f\\n\", \"Simple   avg.\",  cm.meanPrecision[1], cm.meanRecall[1], cm.meanSpecificity[1], cm.meanF1Score[1])\n     print_formatted(\"- %-$(labelWidth+2)s %8.3f %8.3f %12.3f %8.3f\\n\", \"Weigthed avg.\",  cm.meanPrecision[2], cm.meanRecall[2], cm.meanSpecificity[2], cm.meanF1Score[2])\n   end\n   println(\"\\n-----------------------------------------------------------------\")\n   return nothing\nend\nprintln(io::IO, cm::ConfusionMatrix{T}, what=\"all\") where T = begin  print(cm,what);print(\"\\n\"); return nothing end\n\n# ------------------------------------------------------------------------------\n# Regression tasks...\n\n# Used as neural network loss function\n\"\"\"\n   squaredCost(ŷ,y)\n\nCompute the squared costs between a vector of prediction and one of observations as (1/2)*norm(y - ŷ)^2.\n\nAside the 1/2 term, it correspond to the squared l-2 norm distance and when it is averaged on multiple datapoints corresponds to the Mean Squared Error ([MSE](https://en.wikipedia.org/wiki/Mean_squared_error)).\nIt is mostly used for regression problems.\n\"\"\"\nsquaredCost(ŷ,y)   = (1/2)*norm(y - ŷ)^2\ndSquaredCost(ŷ,y)  = ( ŷ - y)\n\"\"\"\n    mse(ŷ,y)\n\nCompute the mean squared error (MSE) (aka mean squared deviation - MSD) between two vectors ŷ and y.\nNote that while the deviation is averaged by the length of `y` is is not scaled to give it a relative meaning.\n\"\"\"\nmse(ŷ,y) = (sum((y-ŷ).^(2))/length(y))\n\n\"\"\"\n  meanRelError(ŷ,y;normDim=true,normRec=true,p=1)\n\nCompute the mean relative error (l-1 based by default) between ŷ and y.\n\nThere are many ways to compute a mean relative error. In particular, if normRec (normDim) is set to true, the records (dimensions) are normalised, in the sense that it doesn't matter if a record (dimension) is bigger or smaller than the others, the relative error is first computed for each record (dimension) and then it is averaged.\nWith both `normDim` and `normRec` set to `false` the function returns the relative mean error; with both set to `true` (default) it returns the mean relative error (i.e. with p=1 the \"[mean absolute percentage error (MAPE)](https://en.wikipedia.org/wiki/Mean_absolute_percentage_error)\")\nThe parameter `p` [def: `1`] controls the p-norm used to define the error.\n\nThe _mean relative error_ enfatises the relativeness of the error, i.e. all observations and dimensions weigth the same, wether large or small. Conversly, in the _relative mean error_ the same relative error on larger observations (or dimensions) weights more.\n\nFor example, given `y = [1,44,3]` and `ŷ = [2,45,2]`, the _mean relative error_ `meanRelError(ŷ,y)` is `0.452`, while the _relative mean error_ `meanRelError(ŷ,y, normRec=false)` is \"only\" `0.0625`.\n\n\"\"\"\nfunction meanRelError(ŷ,y;normDim=true,normRec=true,p=1)\n    ŷ = makeMatrix(ŷ)\n    y = makeMatrix(y)\n    (n,d) = size(y)\n    #ϵ = abs.(ŷ-y) .^ p\n    if (!normDim && !normRec) # relative mean error\n        avgϵRel = (sum(abs.(ŷ-y).^p)^(1/p) / (n*d)) / (sum( abs.(y) .^p)^(1/p) / (n*d)) # (avg error) / (avg y)\n        # avgϵRel = (norm((ŷ-y),p)/(n*d)) / (norm(y,p) / (n*d))\n    elseif (!normDim && normRec) # normalised by record (i.e. all records play the same weigth)\n        avgϵRel_byRec = (sum(abs.(ŷ-y) .^ (1/p),dims=2).^(1/p) ./ d) ./   (sum(abs.(y) .^ (1/p) ,dims=2) ./d)\n        avgϵRel = mean(avgϵRel_byRec)\n    elseif (normDim && !normRec) # normalised by dimensions (i.e.  all dimensions play the same weigth)\n        avgϵRel_byDim = (sum(abs.(ŷ-y) .^ (1/p),dims=1).^(1/p) ./ n) ./   (sum(abs.(y) .^ (1/p) ,dims=1) ./n)\n        avgϵRel = mean(avgϵRel_byDim)\n    else # mean relative error\n        avgϵRel = sum(abs.((ŷ-y)./ y).^p)^(1/p)/(n*d) # avg(error/y)\n        # avgϵRel = (norm((ŷ-y)./ y,p)/(n*d))\n    end\n    return avgϵRel\nend\n", "meta": {"hexsha": "20e5441a65e250388404fd4e220eb57cf719dc23", "size": 19725, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Utils/Measures.jl", "max_stars_repo_name": "sylvaticus/bmlt.jl", "max_stars_repo_head_hexsha": "767f69779913dd8a12412be0259e6718c9b61e6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-05-19T17:13:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-06T20:49:27.000Z", "max_issues_repo_path": "src/Utils/Measures.jl", "max_issues_repo_name": "sylvaticus/bmlt.jl", "max_issues_repo_head_hexsha": "767f69779913dd8a12412be0259e6718c9b61e6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-03T12:08:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-03T12:09:04.000Z", "max_forks_repo_path": "src/Utils/Measures.jl", "max_forks_repo_name": "sylvaticus/bmlt.jl", "max_forks_repo_head_hexsha": "767f69779913dd8a12412be0259e6718c9b61e6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-20T11:37:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-22T14:07:32.000Z", "avg_line_length": 53.4552845528, "max_line_length": 334, "alphanum_fraction": 0.6422813688, "num_tokens": 5603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778012346834, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7758534698300877}}
{"text": "using Plots\n\n\nfunction wheeler(x, a=1.5)\n    return exp(-(x[1]*x[2] - a)^2 - (x[2] - a)^2);\nend\n\n# plot\n\nheatmap(-10:0.01:25, -3:0.01:6, (x, y)->wheeler([x, y]))\n", "meta": {"hexsha": "629c514e7c6dcd5313452f045b2f87bcbc9c3719", "size": 162, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test_function/wheelers_ridge.jl", "max_stars_repo_name": "tor4z/convex_optimization", "max_stars_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test_function/wheelers_ridge.jl", "max_issues_repo_name": "tor4z/convex_optimization", "max_issues_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_function/wheelers_ridge.jl", "max_forks_repo_name": "tor4z/convex_optimization", "max_forks_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.7272727273, "max_line_length": 56, "alphanum_fraction": 0.524691358, "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9572777975782055, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.7758534559112112}}
{"text": "\"\"\"\n    circumcenter_radius2(pts)\n\nCalculate circumcenter and circumradius squared from points.\n\nBased on https://github.com/hirani/pydec/blob/master/pydec/math/circumcenter.py and\nhttp://www.ics.uci.edu/~eppstein/junkyard/circumcenter.html\n\"\"\"\n# TODO: try this with SMatrix?\nfunction circumcenter_radius2(pts)\n    if length(pts) == 1\n        return pts[1], 0.0\n    elseif length(pts) == 2\n        return 0.5 * sum(pts), 0.25 * sum(abs2, pts[1] - pts[2])\n    else\n        P = to_matrix(pts)\n        n = length(pts)\n\n        A = ones(n + 1, n + 1)\n        A[end, end] = 0.0\n        A[1:(end - 1), 1:(end - 1)] .= 2 * P' * P\n\n        b = vec(sum(abs2, P; dims=1))\n        push!(b, 1.0)\n\n        fact = lu(A; check=false)\n        if issuccess(fact)\n            x = fact \\ b\n            bary_coords = x[1:(end - 1)]\n\n            center = P * bary_coords\n            radius = P[:, 1] - center\n            return center, sum(abs2, radius)\n        else\n            return fill(NaN, length(pts[1])), Inf\n        end\n    end\nend\n\n# TODO: could be faster, takes a long time to compile\nfunction _build_dims!(dicts, triangulation, points, ::Val{D}, verbose) where {D}\n    if verbose\n        progbar = Progress(size(triangulation, 2); desc=\"Collecting $D-simplcies... \")\n    end\n    for face in eachcol(triangulation)\n        for σ in IterTools.subsets(face, Val(D + 1))\n            @assert issorted(σ; rev=true)\n            σ_idx = index(σ)\n            if !haskey(dicts[D + 1], σ_idx)\n                _, σ_r2 = circumcenter_radius2(points[SVector(σ)])\n                if isfinite(σ_r2)\n                    dicts[D + 1][σ_idx] = σ_r2\n                else\n                    continue\n                end\n            end\n            # Propagate birth time to facets.\n            σ_r2 = dicts[D + 1][σ_idx]\n            for i in 1:(D + 1)\n                τ = TupleTools.deleteat(σ, i)\n                τ_idx = index(τ)\n                if haskey(dicts[D], τ_idx)\n                    dicts[D][τ_idx] = min(σ_r2, dicts[D][τ_idx])\n                elseif length(τ) > 1\n                    τ_c, τ_r2 = circumcenter_radius2(points[SVector(τ)])\n                    if sum(abs2, τ_c - points[σ[i]]) < τ_r2\n                        dicts[D][τ_idx] = σ_r2\n                    end\n                end\n            end\n        end\n        verbose && next!(progbar)\n    end\nend\n\nfunction _fix_dim!(dicts, threshold, ::Val{D}, verbose) where {D}\n    for (idx, birth) in dicts[D + 1]\n        σ = Tuple(_vertices(idx, Val(D + 1)))\n        σ_idx = index(σ)\n        if D > 1\n            for i in 1:(D + 1)\n                τ = TupleTools.deleteat(σ, i)\n                τ_idx = index(τ)\n                dicts[D][τ_idx] = min(dicts[D][τ_idx], birth)\n            end\n        end\n        corrected_birth = 2 * √dicts[D + 1][σ_idx]\n        dicts[D + 1][σ_idx] = corrected_birth\n    end\nend\n\n\"\"\"\n    alpha_simplices(points[, verbose])\n\nCollect all simplices and their birth times in alpha filtration.\n\nBased on https://github.com/scikit-tda/cechmate/blob/master/cechmate/filtrations/alpha.py\n\"\"\"\nfunction alpha_simplices(points, threshold, verbose, ::Type{I}) where {I}\n    @prog_print verbose \"Building triangulation... \"\n    triangulation = I.(delaunay(to_matrix(points)))\n    sort!.(eachcol(triangulation), rev=true, alg=InsertionSort)\n    @prog_println verbose \"done.\"\n\n    largest_face = tuple(maximum(eachcol(triangulation))...)\n    index_overflow_check(largest_face)\n\n    dim = length(points[1])\n    dicts = [Dict{I,Float64}() for _ in 0:dim]\n\n    # Build the filtration\n    for d in dim:-1:1\n        _build_dims!(dicts, triangulation, points, Val(d), verbose)\n    end\n    for i in 1:length(points)\n        dicts[1][i] = 0.0\n    end\n    if verbose\n        progbar = Progress(dim; desc=\"Fixing birth times...     \")\n    end\n    # Make sure all simplices are born after their facets and sqrt the birth times.\n    for d in dim:-1:1\n        _fix_dim!(dicts, threshold, Val(d), verbose)\n        verbose && next!(progbar)\n    end\n\n    return dicts\nend\n\n\"\"\"\n    Alpha{I, P<:SVector} <: AbstractFiltration{I, Float64}\n\n`Alpha` filtrations are filtrations of the Delaunay complex.\n\nThey have much fewer simplices than `Rips`, so they are efficient even with large datasets,\nas long as their dimensionality is low.  What \"low\" means depends on the data, but this is\ndefinitely a good choice for 3D or lower. For high dimensional data, filtration construction\nmay take a long time.\n\n!!! note\n    Unlike most implementations, this one uses circumdiameters instead of\n    circumradii. This makes the scale of the results comparable to `Rips`. If you need\n    radius based values, divide your data or the resulting interval endpoints by 2.\n\n!!! warning\n    This filtration uses [MiniQhull.jl](https://github.com/gridap/MiniQhull.jl). Please see\n    the installation instructions if constructions cause errors. MiniQhull currently has\n    problems running on Windows. See [this\n    issue](https://github.com/gridap/MiniQhull.jl/issues/5) for more info.\n\n# Constructors\n\n* `Alpha(points; threshold, verbose)`: `points` should be a vector of `Tuple`s, `SVector`s\n  or similar.\n* `Alpha{I}(args...)`: `I` sets the size of integer used to represent simplices. Try using\n  `I=Int128` if construction complains about overflow.\n\n# Reference\n\nEdelsbrunner, H. (1993, July). The union of balls and its dual shape. [In Proceedings of the\nninth annual symposium on Computational geometry\n(pp. 218-231)](https://dl.acm.org/doi/abs/10.1145/160985.161139).\n\n# Example\n\n```jldoctest\njulia> data = [(sin(t), cos(t), (t - π)^2) for t in range(0, 2π, length=101)[1:end-1]];\n\njulia> alpha = Alpha(data)\nAlpha{Int64, Float64}(nv=100)\n\njulia> rips = Rips(data)\nRips{Int64, Float64}(nv=100, sparse=false)\n\njulia> length(Ripserer.edges(alpha))\n197\n\njulia> length(Ripserer.edges(rips))\n3613\n\njulia> sort(ripserer(alpha)[2], by=persistence)[end]\n[0.375, 2.01) with:\n birth_simplex: Simplex{1, Float64, Int64}\n death_simplex: Simplex{2, Float64, Int64}\n\njulia> sort(ripserer(rips)[2], by=persistence)[end]\n[0.375, 2.01) with:\n birth_simplex: Simplex{1, Float64, Int64}\n death_simplex: Simplex{2, Float64, Int64}\n```\n\"\"\"\nstruct Alpha{I,P<:SVector} <: AbstractCustomFiltration{I,Float64}\n    dicts::Vector{Dict{I,Float64}}\n    adj::SparseMatrixCSC{Bool,Int}\n    threshold::Float64\n    points::Vector{P}\nend\nfunction Alpha{I}(points; threshold=nothing, verbose=false) where {I}\n    pts = SVector.(points)\n    threshold = isnothing(threshold) ? 2radius(pts) : threshold\n    dicts = alpha_simplices(pts, threshold, verbose, I)\n    adj = _adjacency_matrix(dicts)\n    return Alpha{I,eltype(pts)}(dicts, adj, threshold, pts)\nend\nfunction Alpha(points; kwargs...)\n    return Alpha{Int}(points; kwargs...)\nend\n\nadjacency_matrix(alpha::Alpha) = alpha.adj\nsimplex_dicts(alpha::Alpha) = alpha.dicts\nthreshold(alpha::Alpha) = alpha.threshold\n\nstruct AlphaDist{A} <: AbstractMatrix{Float64}\n    alpha::A\nend\n\nBase.size(ad::AlphaDist) = (nv(ad.alpha), nv(ad.alpha))\nfunction Base.getindex(ad::AlphaDist, i::Integer, j::Integer)\n    return Euclidean()(ad.alpha.points[i], ad.alpha.points[j])\nend\n\ndistance_matrix(alpha::Alpha) = AlphaDist(alpha)\n", "meta": {"hexsha": "bd7a27c1d1b6380cd0b317cda01f3409b05bec97", "size": 7150, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/filtrations/alpha.jl", "max_stars_repo_name": "davidhien/Ripserer.jl", "max_stars_repo_head_hexsha": "95391396bea1b2b922967f7da21de05d6b3b67bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2020-06-03T11:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T21:37:46.000Z", "max_issues_repo_path": "src/filtrations/alpha.jl", "max_issues_repo_name": "davidhien/Ripserer.jl", "max_issues_repo_head_hexsha": "95391396bea1b2b922967f7da21de05d6b3b67bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 149, "max_issues_repo_issues_event_min_datetime": "2020-04-09T07:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T10:20:46.000Z", "max_forks_repo_path": "src/filtrations/alpha.jl", "max_forks_repo_name": "davidhien/Ripserer.jl", "max_forks_repo_head_hexsha": "95391396bea1b2b922967f7da21de05d6b3b67bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-08-06T22:56:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T14:55:51.000Z", "avg_line_length": 32.0627802691, "max_line_length": 92, "alphanum_fraction": 0.6275524476, "num_tokens": 2068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8615382094310355, "lm_q1q2_score": 0.7758408148714504}}
{"text": "\nusing OrdinaryDiffEq\nusing Distributions\nusing DiffEqFlux, Flux\nusing Random\nusing Plots;\n\n\nRandom.seed!(123);\n\n\nfunction sir_ode(u,p,t)\n    (S,I,C) = u\n    (β,γ) = p\n    dS = -β*S*I\n    dI = β*S*I - γ*I\n    dC = β*S*I\n    [dS,dI,dC]\nend;\n\n\nsolver = RadauIIA3();\n\n\nN = 1000.0\np = [0.5,0.25]\nu0 = [0.99, 0.01, 0.0]\ntspan = (0., 40.)\nδt = 1;\n\n\nsir_prob = ODEProblem(sir_ode, u0, tspan, p)\nsir_sol = solve(sir_prob, solver, saveat = δt);\n\n\nplot(sir_sol,\n     xlabel = \"Time\",\n     ylabel = \"Proportion\",\n     labels = [\"S\" \"I\" \"R\"])\n\n\ntrain_time = 30.0\ntsdata = Array(sir_sol(0:δt:train_time))\ncdata = diff(tsdata[3,:])\nnoisy_data = rand.(Poisson.(N .* cdata));\n\n\nplot(1:δt:train_time, N .* cdata,\n     xlabel = \"Time\",\n     ylabel = \"New cases per day\",\n     label = \"True value\")\nscatter!(1:δt:train_time, noisy_data, label=\"Data\")\n\n\nfoi1 = FastDense(1, 1, relu, bias=false)\np1_ = Float64.(initial_params(foi1))\nlength(p1_)\n\n\nfunction sir_ude(u,p_,t,foi)\n    S,I,C = u\n    β,γ = p\n    λ = foi([I],p_)[1]\n    dS = -λ*S\n    dI = λ*S - γ*I\n    dC = λ*S\n    [dS, dI, dC]\nend;\n\n\ntspan_train = (0,train_time)\nsir_ude1 = (u,p_,t) -> sir_ude(u,p_,t,foi1)\nprob_ude1 = ODEProblem(sir_ude1,\n                      u0,\n                      tspan_train,\n                      p1_);\n\n\nfunction predict(θ, prob)\n    Array(solve(prob,\n                solver;\n                u0 = u0,\n                p = θ,\n                saveat = δt,\n                sensealg = InterpolatingAdjoint(autojacvec=ReverseDiffVJP())))\nend;\n\n\nfunction loss(θ, prob)\n    pred = predict(θ, prob)\n    cpred = abs.(N*diff(pred[3,:]))\n    Flux.poisson_loss(cpred, float.(noisy_data)), cpred\nend;\n\n\nloss(prob_ude1.p, prob_ude1);\n\n\nconst losses1 = []\ncallback1 = function (p, l, pred)\n    push!(losses1, l)\n    numloss = length(losses1)\n    if numloss % 10 == 0\n        display(\"Epoch: \" * string(numloss) * \" Loss: \" * string(l))\n    end\n    return false\nend;\n\n\nres_ude1 = DiffEqFlux.sciml_train((θ)->loss(θ,prob_ude1),\n                                  p1_,\n                                  cb=callback1);\n\n\nres_ude1.minimizer, losses1[end]\n\n\nplot(losses1, xaxis = :log, xlabel = \"Iterations\", ylabel = \"Loss\", legend=false)\n\n\nprob_ude1_fit = ODEProblem(sir_ude1, u0, tspan, res_ude1.minimizer)\nsol_ude1_fit = solve(prob_ude1_fit, solver, saveat = δt)\nscatter(sir_sol, label=[\"True Susceptible\" \"True Infected\" \"True Recovered\"],title=\"Fitted true model\")\nplot!(sol_ude1_fit, label=[\"Estimated Susceptible\" \"Estimated Infected\" \"Estimated Recovered\"])\n\n\nImax = maximum(tsdata[2,:])\nIgrid = 0:0.01:0.5\nλ = [foi1([I],res_ude1.minimizer)[1] for I in Igrid]\nscatter(Igrid,λ,xlabel=\"Proportion of population infected, I\",ylab=\"Force of infection, λ\",label=\"Neural network prediction\")\nPlots.abline!(p[1],0,label=\"True value\")\nPlots.vline!([Imax],label=\"Upper bound of training data\")\n\n\nRandom.seed!(1234)\nnhidden = 4\nfoi2 = FastChain(FastDense(1, nhidden, relu),\n                     FastDense(nhidden, nhidden, relu),\n                     FastDense(nhidden, 1, relu))\np2_ = Float64.(initial_params(foi2))\nlength(p2_)\n\n\nsir_ude2 = (u,p_,t) -> sir_ude(u,p_,t,foi2)\nprob_ude2 = ODEProblem(sir_ude2,\n                      u0,\n                      tspan_train,\n                      p2_);\n\n\nconst losses2 = []\ncallback2 = function (p, l, pred)\n    push!(losses2, l)\n    numloss = length(losses2)\n    if numloss % 10 == 0\n        display(\"Epoch: \" * string(numloss) * \" Loss: \" * string(l))\n    end\n    return false\nend;\n\n\nres_ude2 = DiffEqFlux.sciml_train((θ)->loss(θ,prob_ude2),\n                                  p2_,\n                                  cb = callback2);\n\n\nlosses1[end],losses2[end]\n\n\nprob_ude2_fit = ODEProblem(sir_ude2, u0, tspan, res_ude2.minimizer)\nsol_ude2_fit = solve(prob_ude2_fit, solver, saveat = δt)\nscatter(sir_sol, label=[\"True Susceptible\" \"True Infected\" \"True Recovered\"],title=\"Fitted UDE model\")\nplot!(sol_ude2_fit, label=[\"Estimated Susceptible\" \"Estimated Infected\" \"Estimated Recovered\"])\n\n\nλ = [foi2([I],res_ude2.minimizer)[1] for I in Igrid]\nscatter(Igrid, λ, xlabel=\"Proportion of population infected, i\", ylab=\"Force of infection, λ\", label=\"Neural network prediction\")\nPlots.abline!(p[1], 0,label=\"True value\")\nPlots.vline!([Imax], label=\"Upper bound of training data\")\n\n", "meta": {"hexsha": "4b72977101f35c1a90fa482119a1b8469cc1a977", "size": 4262, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ude/ude.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/ude/ude.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/ude/ude.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.546961326, "max_line_length": 129, "alphanum_fraction": 0.6051149695, "num_tokens": 1420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7758145366393002}}
{"text": "#' # Modeling data 2\r\n\r\n#' ## Building a model\r\n#' Recall that in notebook 3, we saw that we could use a mathematical function\r\n#' to classify an image as an apple or a banana, based on the average amount of\r\n#' green in an image:\r\n#'\r\n#' ![data_flow](data/data_flow.png)\r\n#'\r\n#' ![what_is_model](data/what_is_model.png)\r\n\r\n#' A common function for performing this kind of **classification** is the\r\n#' sigmoid that we saw in the last notebook, and that we will now extend by\r\n#' adding two **parameters**, $w$ and $b$:\r\n#'\r\n#' $$\\sigma(x; w, b) := \\frac{1}{1 + e^{(-wx + b)}}$$\r\n#'\r\n#' $$x = \\mathrm{data}$$\r\n#'\r\n#'\r\n#' $$\\begin{align}\r\n#' \\sigma(x;w,b) &\\approx 0 \\implies \\mathrm{apple} \\\\\r\n#' \\sigma(x;w,b) &\\approx 1 \\implies \\mathrm{banana}\r\n#' \\end{align}$$\r\n#'\r\n#' In our mathematical notation above, the `;` in the function differentiates\r\n#' between the **data** and the **parameters**. `x` is the data and is\r\n#' determined from the image. The parameters, `w` and `b`, are numbers which we\r\n#' choose to make our function match the results it should be modeling.\r\n\r\n#' Note that in the code below, we don't distinguish between data and\r\n#' parameters - both are just inputs to our function, σ!\r\n\r\nusing Images, Statistics\r\n\r\n# apple = load(\"C:\\\\Users\\\\Yi-Kun.Yang\\\\work\\\\org.allnix.julia\\\\JuliaAcademy\\\\FundMachLearn/data/10_100.jpg\")\r\n# banana = load(\"C:\\\\Users\\\\Yi-Kun.Yang\\\\work\\\\org.allnix.julia\\\\JuliaAcademy\\\\FundMachLearn/data/104_100.jpg\")\r\napple = load(\"data/10_100.jpg\")\r\n#'\r\nbanana = load(\"data/104_100.jpg\")\r\n#'\r\n\r\napple_green_amount = mean(Float64.(green.(apple)))\r\nbanana_green_amount = mean(Float64.(green.(banana)))\r\n\r\nprintln(\"Average green for apple = $apple_green_amount\")\r\nprintln(\"Average green for banana = $banana_green_amount\")\r\n\r\n#+ results=\"hidden\"\r\nσ(x, w, b) = 1 / (1 + exp(-w * x + b))\r\n#+\r\n\r\n#' What we want is that when we give σ as input the average green for the apple,\r\n#' roughly `x = 0.3385`, it should return as output something close to 0,\r\n#' meaning \"apple\". And when we give σ the input `x = 0.8808`, it should output\r\n#' something close to 1, meaning \"banana\".\r\n\r\n#' By changing the parameters of the function, we can change the shape of the\r\n#' function, and hence make it represent, or **fit**, the data better!\r\n\r\n#' ## Data fitting by varying parameters\r\n\r\n# We can understand how our choice of `w` and `b` affects our model by seeing how our values for `w` and `b` change the plot of the $\\sigma$ function.\r\n\r\nusing Plots\r\ngr()   # GR works better for interactive manipulations\r\n#plotly()\r\n#pyplot()\r\n\r\n#' Run the code in the next cell. You should see two \"sliders\" appear, one for\r\n#' `w` and one for `b`.\r\n\r\n#' **Game**:\r\n#' Change w and b around until the blue curve, labeled \"model\", which is the\r\n#' graph of the `\\sigma` function, passes through *both* of the data points at\r\n#' the same time.\r\n\r\nw = 10.0 # try manipulating w between -10 and 30\r\nb = 10.0 # try manipulating b between 0 and 20\r\n\r\nusing Interact\r\n\r\n# Function for Interact\r\nfunction myplot(w,b)\r\n      pt = plot()\r\n      plot!(pt, x -> σ(x, w, b), xlim=(-0,1), ylim=(-0.1,1.1), label=\"model\", legend=(0.1,0.9), lw=3)\r\n      scatter!(pt, [apple_green_amount],  [0.0], label=\"apple\", ms=5)   # marker size = 5\r\n      scatter!(pt, [banana_green_amount], [1.0], label=\"banana\", ms=5)\r\n\r\n      return pt\r\nend\r\n\r\n#' Notice that the two parameters do two very different things. The **weight**,\r\n#' `w`, determines *how fast* the transition between 0 and 1 occurs. It encodes\r\n#' how trustworthy we think our data  actually is, and in what range we should\r\n#' be putting points between 0 and 1 and thus calling them \"unsure\". The\r\n#' **bias**, `b`, encodes *where* on the $x$-axis the switch should take place.\r\n#' It can be seen as shifting the function left-right. We'll come to understand\r\n#' these *parameters* more in notebook 6.\r\n\r\n#' Here are some parameter choices that work well:\r\n\r\nw = 25.58 #20.8\r\nb = 15.6 #12.4\r\npt = myplot(w,b)\r\n\r\n#+ results=\"hidden\"\r\n# Run this in Juno or Jupyter to get interative plot\r\n# @manipulate for w=-10:0.2:30,b = 0:0.2:20\r\n#      vbox(hbox(w,b),myplot(w,b))\r\n# end\r\n#+\r\n\r\n#' (Note that in this problem there are many combinations of `w` and `b` that\r\n#' fit the data well.)\r\napple2 = load(\"data/107_100.jpg\")\r\n#'\r\ngreen_amount = mean(Float64.(green.(apple2)))\r\n@show green_amount\r\nscatter!(pt, [green_amount], [0.0], label=\"new apple\")\r\n\r\n#' Our model successfully says that our new image is an apple! Pat yourself on\r\n#' the back: you've actually just trained your first neural network!\r\n\r\n#' #### Exercise 1\r\n\r\n#' Load the image of a banana in `data/8_100.jpg` as `mybanana`. Edit the code\r\n#' below to calculate the amount of green in `mybanana` and to overlay data for\r\n#' this image with the existing model and data points.\r\nmybanana = load(\"data/8_100.jpg\")\r\ngreen_amount = mean(Float64.(green.(mybanana)))\r\n@show green_amount\r\nscatter!(pt, [green_amount], [1.0], label=\"new banana\")\r\n#' ## Closing remarks: bigger models, more data, more accuracy\r\n\r\n#' That last apple should start making you think: not all apples are red; some\r\n#' are yellow. \"Redness\" is one attribute of being an apple, but isn't the\r\n#' whole thing. What we need to do is incorporate more ideas into our model by\r\n#' allowing more inputs. However, more inputs would mean more parameters to\r\n#' play with. Also, we would like to have the computer start \"learning\" on its\r\n#' own, instead of modifying the parameters ourselves until we think it \"looks\r\n#' right\". How do we take the next step?\r\n\r\n#' The first thing to think about is, if you wanted to incorporate more data\r\n#' into the model, how would you change the sigmoid function? Play around with\r\n#' some ideas. But also, start thinking about how you chose parameters. What\r\n#' process did you do to finally end up at good parameters? These two problems\r\n#' (working with models with more data and automatically choosing parameters)\r\n#' are the last remaining step to understanding deep learning.\r\n", "meta": {"hexsha": "1729b07bd760a0a9b18594737cf959aa10a7dd75", "size": 5997, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JuliaAcademy/FundMachLearn/ch0500.jl", "max_stars_repo_name": "ykyang/org.allnix.julia", "max_stars_repo_head_hexsha": "58933a5848dec81c53d591b4163e9a70df62ddd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JuliaAcademy/FundMachLearn/ch0500.jl", "max_issues_repo_name": "ykyang/org.allnix.julia", "max_issues_repo_head_hexsha": "58933a5848dec81c53d591b4163e9a70df62ddd8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JuliaAcademy/FundMachLearn/ch0500.jl", "max_forks_repo_name": "ykyang/org.allnix.julia", "max_forks_repo_head_hexsha": "58933a5848dec81c53d591b4163e9a70df62ddd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.98, "max_line_length": 151, "alphanum_fraction": 0.6808404202, "num_tokens": 1641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.775814531195995}}
{"text": "\nusing DifferentialEquations\nusing StochasticDiffEq\nusing Random\nusing SparseArrays\nusing DataFrames\nusing StatsPlots\n\n\nfunction sir_ode!(du,u,p,t)\n    (S,I,R) = u\n    (β,c,γ) = p\n    N = S+I+R\n    @inbounds begin\n        du[1] = -β*c*I/N*S\n        du[2] = β*c*I/N*S - γ*I\n        du[3] = γ*I\n    end\n    nothing\nend;\n\n\n# Define a sparse matrix by making a dense matrix and setting some values as not zero\nA = zeros(3,2)\nA[1,1] = 1\nA[2,1] = 1\nA[2,2] = 1\nA[3,2] = 1\nA = SparseArrays.sparse(A);\n\n\n# Make `g` write the sparse matrix values\nfunction sir_noise!(du,u,p,t)\n    (S,I,R) = u\n    (β,c,γ) = p\n    N = S+I+R\n    ifrac = β*I/N*S\n    rfrac = γ*I\n    du[1,1] = -sqrt(ifrac)\n    du[2,1] = sqrt(ifrac)\n    du[2,2] = -sqrt(rfrac)\n    du[3,2] = sqrt(rfrac)\nend;\n\n\nδt = 0.1\ntmax = 40.0\ntspan = (0.0,tmax)\nt = 0.0:δt:tmax;\n\n\nu0 = [990.0,10.0,0.0]; # S,I,R\n\n\np = [0.05,10.0,0.25]; # β,c,γ\n\n\nRandom.seed!(1234);\n\n\nprob_sde = SDEProblem(sir_ode!,sir_noise!,u0,tspan,p,noise_rate_prototype=A)\n\n\nsol_sde = solve(prob_sde,SRA1());\n\n\ndf_sde = DataFrame(sol_sde(t)')\ndf_sde[!,:t] = t;\n\n\n@df df_sde plot(:t,\n    [:x1 :x2 :x3],\n    label=[\"S\" \"I\" \"R\"],\n    xlabel=\"Time\",\n    ylabel=\"Number\")\n\n\ninclude(joinpath(@__DIR__,\"tutorials\",\"appendix.jl\"))\nappendix()\n\n", "meta": {"hexsha": "e51931484de64db83486ebae699687bdc353d44f", "size": 1247, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/sde_stochasticdiffeq/sde_stochasticdiffeq.jl", "max_stars_repo_name": "FSUcilab/sir-julia", "max_stars_repo_head_hexsha": "e40b5c83b2f6056c85f5bccefa993a0a65a1ee7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/sde_stochasticdiffeq/sde_stochasticdiffeq.jl", "max_issues_repo_name": "FSUcilab/sir-julia", "max_issues_repo_head_hexsha": "e40b5c83b2f6056c85f5bccefa993a0a65a1ee7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/sde_stochasticdiffeq/sde_stochasticdiffeq.jl", "max_forks_repo_name": "FSUcilab/sir-julia", "max_forks_repo_head_hexsha": "e40b5c83b2f6056c85f5bccefa993a0a65a1ee7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.3950617284, "max_line_length": 85, "alphanum_fraction": 0.578989575, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7758145264659888}}
{"text": "\"\"\"`newton1d` performs the interval Newton method on the given function `f`\nwith its derivative `f′` and initial interval `x`.\nOptional keyword arguments give the tolerances `reltol` and `abstol`.\n`reltol` is the tolerance on the relative error whereas `abstol` is the tolerance on |f(X)|,\nand a `debug` boolean argument that prints out diagnostic information.\"\"\"\n\nfunction newton1d{T}(f::Function, f′::Function, x::Interval{T};\n                    reltol=eps(T), abstol=eps(T), debug=false)\n\n    L = Interval{T}[]\n\n    R = Root{Interval{T}}[]\n\n    push!(L, x)\n\n    while !isempty(L)\n        X = pop!(L)\n        m = mid(X)\n        if (isempty(X))\n            continue\n        end\n\n        if 0 ∉ f′(X)\n            while true\n                m = mid(X)\n                N = m - (f(Interval(m)) / f′(X))\n                X = X ∩ N\n\n                if isempty(X)\n                    break\n\n                elseif 0 ∈ f(Interval(prevfloat(m), nextfloat(m)))\n                    push!(R, Root(X, :unique))\n                    break\n                end\n            end\n\n        else\n            # 0 ∈ f'(X)\n            expansion_pt = Inf\n            # expansion point for the newton step might be m, X.lo or X.hi according to some conditions\n\n            if 0 ∈ f(Interval(mid(X)))\n                # 0 ∈ fⁱ(x)\n                # Step 7\n\n                if 0 ∉ f(Interval(X.lo))\n                    expansion_pt = X.lo\n\n                elseif 0 ∉ f(Interval(X.hi))\n                    expansion_pt = X.hi\n\n                else\n                    x1 = mid(Interval(X.lo, mid(X)))\n                    x2 = mid(Interval(mid(X), X.hi))\n                    if 0 ∉ f(Interval(x1)) || 0 ∉ f(Interval(x2))\n                        push!(L, Interval(X.lo, m))\n                        push!(L, Interval(m, X.hi))\n                        continue\n\n                    else\n                        push!(R, Root(X, :unique))\n                        continue\n                    end\n                end\n\n            else\n                # 0 ∉ fⁱ(x)\n\n                if (diam(X)/mag(X)) < reltol && diam(f(X)) < abstol\n                    push!(R, Root(X, :unknown))\n                    continue\n                end\n            end\n            # Step 8\n\n            if isinf(expansion_pt)\n                expansion_pt = mid(X)\n            end\n\n            initial_width = diam(X)\n\n            a = f(Interval(expansion_pt))\n            b = f′(X)\n\n            if 0 < b.hi && 0 > b.lo && 0 ∉ a\n                if a.hi < 0\n                    push!(L, X ∩ (expansion_pt - Interval(-Inf, a.hi / b.hi)))\n                    push!(L, X ∩ (expansion_pt - Interval(a.hi / b.lo, Inf)))\n\n                elseif a.lo > 0\n                    push!(L, X ∩ (expansion_pt - Interval(-Inf, a.lo / b.lo)))\n                    push!(L, X ∩ (expansion_pt - Interval(a.lo / b.hi, Inf)))\n\n                end\n\n                continue\n\n            else\n                N = expansion_pt - (f(Interval(expansion_pt))/f′(X))\n                X = X ∩ N\n                m = mid(X)\n\n                if isempty(X)\n                    continue\n                end\n            end\n\n            if diam(X) > initial_width/2\n                push!(L, Interval(m, X.hi))\n                X = Interval(X.lo, m)\n            end\n\n            push!(L, X)\n        end\n    end\n\n    return R\nend\n\n\n\"\"\"`newton1d` performs the interval Newton method on the given function `f` and initial interval `x`.\nOptional keyword arguments give the tolerances `reltol` and `abstol`.\n`reltol` is the tolerance on the relative error whereas `abstol` is the tolerance on |f(X)|,\nand a `debug` boolean argument that prints out diagnostic information.\"\"\"\n\nnewton1d{T}(f::Function, x::Interval{T};  args...) =\n    newton1d(f, x->D(f,x), x; args...)\n", "meta": {"hexsha": "cac4be47878c94cedf6a6e33133da6dfef7d89dc", "size": 3762, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/newton1d.jl", "max_stars_repo_name": "Kolaru/IntervalRootFinding.jl", "max_stars_repo_head_hexsha": "e235900cc4624c63cc4ba6e7071f460d4607dc8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-23T08:39:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T08:39:39.000Z", "max_issues_repo_path": "src/newton1d.jl", "max_issues_repo_name": "Kolaru/IntervalRootFinding.jl", "max_issues_repo_head_hexsha": "e235900cc4624c63cc4ba6e7071f460d4607dc8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/newton1d.jl", "max_forks_repo_name": "Kolaru/IntervalRootFinding.jl", "max_forks_repo_head_hexsha": "e235900cc4624c63cc4ba6e7071f460d4607dc8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1627906977, "max_line_length": 103, "alphanum_fraction": 0.4412546518, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308054739519, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7758145187702326}}
{"text": "using LinearAlgebra\n\nfunction err_estimation(xfull, xhalf, order::Integer)\n    return (1<<order)/(1<<order-1)*norm(xhalf .- xfull)\nend\n\nfunction richardson_extrapolation(xfull, xhalf, order::Integer)\n    return ((1<<order)*xhalf .- xfull)/(1<<order-1)\nend\n\nfunction mixed_step_ode_solver(\n    f,\n    t0::Number,\n    x0,\n    stop_cond;\n    method = mod_euler_step,\n    min_step::AbstractFloat = 1e-3,\n    max_step::AbstractFloat = 10,\n    target_err::AbstractFloat = 0.1,\n    step0::AbstractFloat = 1.0,\n    maxit::Integer = 10000,\n    debug_dict = nothing\n)\n    t = Array{typeof(t0 + step0), 1}()\n    x = Array{typeof(x0 + step0*f(t0, x0)), 1}()\n    step = step0\n    push!(t, t0)\n    push!(x, x0)\n    i = 1\n    for j = 1:maxit\n        aux = last(x) .+ method(f, last(t), last(x), [step, step/2])\n        xfull = aux[:,1]\n        xhalf = aux[:,2] + method(f, last(t)+step/2, aux[:,2], step/2)\n\n        err_full = err_estimation(xfull, xhalf, method(:order))\n        if err_full < target_err\n            push!(t, last(t)+step)\n            push!(x, richardson_extrapolation(xfull, xhalf, method(:order)))\n            if stop_cond(t, x)\n                if debug_dict != nothing\n                    debug_dict[:numit] = j\n                end\n                break\n            end\n        end\n\n        q = (target_err*step/err_full) ^ (1/(method(:order)))\n        q = min(4, max(0.1, q))\n        step = min(q*step, max_step)\n        if step < min_step\n            throw(ErrorException(\"step went below the min_step($(min_step)) value\"))\n        end\n    end\n    return t, x\nend\n\nstruct ExtButcherTableau\n    a\n    c\n    b1\n    b2\n    order\n\n    ExtButcherTableau(; a, c, b1, b2, order::Integer) = new(a, c, b1, b2, order)\nend\n\nDORPRI5_tableau = ExtButcherTableau(\n    a = [          0  1/5        3/40    44/45     19372/6561   9017/3168     35/384;\n                   0    0        9/40   -56/15    -25360/2187     -355/33          0;\n                   0    0           0     32/9     64448/6561  46732/5247   500/1113;\n                   0    0           0        0       -212/729      49/176    125/192;\n                   0    0           0        0              0 -5103/18656 -2187/6784;\n                   0    0           0        0              0           0      11/84;\n                   0    0           0        0              0           0          0],\n    c = [          0, 1/5,       3/10,     4/5,           8/9,          1,         1],\n\n    b1 = [    35/384,   0,   500/1113, 125/192,    -2187/6784,      11/84,         0],\n    b2 = [5179/57600,   0, 7571/16695, 393/640, -92097/339200,   187/2100,      1/40],\n    order = 5\n)\n\nRKFehlberg_tableau = ExtButcherTableau(\n    a = [       0  1/4        3/32    1932/2197   439/216      -8/27;\n                0    0        9/32   -7200/2197        -8          2;\n                0    0           0    7296/2197  3680/513 -3544/2565;\n                0    0           0            0 -845/4104  1859/4104;\n                0    0           0            0         0     -11/40;\n                0    0           0            0         0          0],\n    c = [       0, 1/4,        3/8,       12/13,        1,       1/2],\n\n    b1 = [ 16/135,   0, 6656/12825, 28561/56430,    -9/50,      2/55],\n    b2 = [ 25/216,   0,  1408/2565,   2197/4104,     -1/5,         0],\n    order = 4\n)\n\nfunction double_step(tab::ExtButcherTableau, f, t, x, step)\n    k = Array{typeof(x + step*f(t, x)), 1}(undef, length(tab.c))\n    k[1] = step*f(t + step*tab.c[1], x)\n    for j = 2:length(k)\n        k[j] = step*f(t + step*tab.c[j], x + tab.a[1:(j-1), j]' * k[1:(j-1)])\n    end\n    return (x + tab.b1' * k, x + tab.b2' * k)\nend\n\n# function double_step(\n\nfunction adaptative_rk_ode_solver(\n    f,\n    t0::Number,\n    x0,\n    stop_cond;\n    tableau::ExtButcherTableau = RKFehlberg_tableau,\n    min_step::AbstractFloat = 1e-3,\n    max_step::AbstractFloat = 10,\n    target_err::AbstractFloat = 0.1,\n    step0::AbstractFloat = 1.0,\n    maxit::Integer = 10000,\n    debug_dict = nothing\n)\n    t = Array{typeof(t0 + step0), 1}()\n    x = Array{typeof(x0 + step0*f(t0, x0)), 1}()\n    step = step0\n    push!(t, t0)\n    push!(x, x0)\n    i = 1\n    for j = 1:maxit\n        x1, x2 = double_step(tableau, f, last(t), last(x), step)\n\n        err = norm(x1 .- x2)\n        if err < target_err\n            push!(t, last(t)+step)\n            push!(x, x1)\n            if stop_cond(t, x)\n                if debug_dict != nothing\n                    debug_dict[:numit] = j\n                end\n                break\n            end\n        end\n\n        q = (target_err*step/err) ^ (1/(tableau.order))\n        q = min(4, max(0.1, q))\n        step = min(q*step, max_step)\n        if step < min_step\n            throw(ErrorException(\"step went below the min_step($(min_step)) value\"))\n        end\n    end\n    return t, x\nend\n\n", "meta": {"hexsha": "516e4528e839716ac7fb4b94c87a58724eef1200", "size": 4826, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MixedStepMethods.jl", "max_stars_repo_name": "useredsa/numeric-differential-equations", "max_stars_repo_head_hexsha": "7647a20120ce0a05ee5223b0ce81ad63d8aee115", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MixedStepMethods.jl", "max_issues_repo_name": "useredsa/numeric-differential-equations", "max_issues_repo_head_hexsha": "7647a20120ce0a05ee5223b0ce81ad63d8aee115", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MixedStepMethods.jl", "max_forks_repo_name": "useredsa/numeric-differential-equations", "max_forks_repo_head_hexsha": "7647a20120ce0a05ee5223b0ce81ad63d8aee115", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9602649007, "max_line_length": 86, "alphanum_fraction": 0.4643597182, "num_tokens": 1697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789452074398, "lm_q2_score": 0.8670357580842941, "lm_q1q2_score": 0.7758144509051558}}
{"text": "# Program to find GCD using Euclidean Algorithm\n\nfunction gcd(x,y)\n\tif x==0\n\t\treturn y\n\telse\n\t\treturn gcd(y%x,x)\n\tend\nend\n\nprintln(\"x = \")\nx = parse(Int64,readline())\nprintln(\"\\ny = \")\ny = parse(Int64,readline())\n\nprintln(\"gcd of ($x , $y) = \",gcd(x,y))\n", "meta": {"hexsha": "f67aa554ac1fa113efef3a6cbc917d2b219da7b1", "size": 254, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Basic-Julia-Codes/gcd.jl", "max_stars_repo_name": "cashewcodes/Basic-Julia-Projects", "max_stars_repo_head_hexsha": "a50a3b771faf453556aa1a60e4ed46019388c679", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-19T14:08:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-19T14:08:52.000Z", "max_issues_repo_path": "Basic-Julia-Codes/gcd.jl", "max_issues_repo_name": "cashewcodes/Basic-Julia-Projects", "max_issues_repo_head_hexsha": "a50a3b771faf453556aa1a60e4ed46019388c679", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Basic-Julia-Codes/gcd.jl", "max_forks_repo_name": "cashewcodes/Basic-Julia-Projects", "max_forks_repo_head_hexsha": "a50a3b771faf453556aa1a60e4ed46019388c679", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.9411764706, "max_line_length": 47, "alphanum_fraction": 0.625984252, "num_tokens": 82, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172630429474, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7758105406102223}}
{"text": "export\n    sigmoid,\n    relu,\n    softmax,\n    onehot,\n    crossentropyerror\n\nfunction sigmoid(x::T) where T <: Real\n    return 1.0 / (1.0 + exp(-x))\nend\n\nfunction relu(x::T) where T <: Real\n    return max(zero(x), x)\nend\n\nfunction softmax(x::AbstractVector{T}) where T <: Real\n    c = maximum(x)\n    exp_a = exp.(x .- c)\n    return exp_a ./ sum(exp_a)\nend\n\nfunction softmax(x::AbstractMatrix{T}) where T <: Real\n    return mapslices(softmax, x, 1)\nend\n\nfunction onehot(::Type{T}, t::AbstractVector, l::AbstractVector) where T\n    r = zeros(T, length(l), length(t))\n    for i in 1:length(t)\n        r[findfirst(l, t[i]), i] = 1\n    end\n    return r\nend\n\nonehot(t::AbstractVector, l::AbstractVector) = onehot(Int, t, l)\n\nfunction crossentropyerror(y::Vector, t::Vector)\n    δ = 1.0e-7\n    # -sum(t .* log.(y .+ δ))\n    return -(t ⋅ log.(y .+ δ))\nend\n\nfunction crossentropyerror(y::Matrix, t::Matrix)\n    batch_size = size(y, 2)\n    δ = 1.0e-7\n    # -sum(t .* log.(y .+ δ)) ./ batch_size\n    return -vecdot(t, log.(y .+ δ)) ./ batch_size\nend\n", "meta": {"hexsha": "64540f1d202e918377f4ae7414b34b57ab7ac900", "size": 1040, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "KanchiShimono/JML.jl", "max_stars_repo_head_hexsha": "c64d9cf12fc47a230660cc3719ac4bc1b7cb0a54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions.jl", "max_issues_repo_name": "KanchiShimono/JML.jl", "max_issues_repo_head_hexsha": "c64d9cf12fc47a230660cc3719ac4bc1b7cb0a54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions.jl", "max_forks_repo_name": "KanchiShimono/JML.jl", "max_forks_repo_head_hexsha": "c64d9cf12fc47a230660cc3719ac4bc1b7cb0a54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6666666667, "max_line_length": 72, "alphanum_fraction": 0.6019230769, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7758105382480589}}
{"text": "module problem111\n\ndescription = \"\"\"\nPrimes with runs\n\nConsidering 4-digit primes containing repeated digits it is clear that they cannot all be the same: 1111 is divisible by 11, 2222 is divisible by 22, and so on. But there are nine 4-digit primes containing three ones:\n1117, 1151, 1171, 1181, 1511, 1811, 2111, 4111, 8111\n\nWe shall say that M(n, d) represents the maximum number of repeated digits for an n-digit prime where d is the repeated digit, N(n, d) represents the number of such primes, and S(n, d) represents the sum of these primes.\nSo M(4, 1) = 3 is the maximum number of repeated digits for a 4-digit prime where one is the repeated digit, there are N(4, 1) = 9 such primes, and the sum of these primes is S(4, 1) = 22275. It turns out that for d = 0, it is only possible to have M(4, 0) = 2 repeated digits, but there are N(4, 0) = 13 such cases.\n\nIn the same way we obtain the following results for 4-digit primes.\nDigit, d \tM(4, d) \tN(4, d) \tS(4, d)\n0 \t2 \t13 \t67061\n1 \t3 \t9 \t22275\n2 \t3 \t1 \t2221\n3 \t3 \t12 \t46214\n4 \t3 \t2 \t8888\n5 \t3 \t1 \t5557\n6 \t3 \t1 \t6661\n7 \t3 \t9 \t57863\n8 \t3 \t1 \t8887\n9 \t3 \t7 \t48073\n\nFor d = 0 to 9, the sum of all S(4, d) is 273700.\n\nFind the sum of all S(10, d).\n\"\"\"\n\nfunction solve(n :: Integer)\n  return sum([S(n, d) for d = 0:9])\nend\n\n# search for the first r from (n-1) to 2 producing some primes having the digit d repeat r times in n-digit numbers.\nfunction S(n :: Integer, d :: Integer)\n  for r = n-1 : -1 : 2\n    result = S(n, d, r)\n    if result > 0\n      return result\n    end\n  end\nend\n\n# Find the sum of primes with n digits, having digit d repeat r times.\nfunction S(n :: Integer, d :: Integer, r :: Integer)\n  total = 0\n  repeatCombinations = collect(combinations([1 : (d == 0 ? n-1 : n)], r)) # no leading zeros\n  for repeated in repeatCombinations\n    digits = zeros(n)\n    digits[repeated] = d\n    changing = setdiff([1:n], repeated)\n    total += SPrimes(digits, changing, 1)\n  end\n  return total\nend\n\nfunction SPrimes(digits :: Vector, changing :: Vector, i :: Integer)\n\n  # Base case: all digits are set, check if result is prime\n  if i > length(changing)\n    n = sum([int(10^(x-1) * digits[x]) for x in 1:length(digits)])\n    return isprime(n) ? n : 0\n  end\n\n  # recursive case, set digit at index changing[i], and call with i+1\n  total = 0\n  for d = (changing[i] == length(digits) ? 1 : 0) : 9\n    digits[changing[i]] = d\n    total += SPrimes(digits, changing, i+1)\n  end\n  return total\nend\n\nusing Base.Test\n\n@test solve(4) == 273700\n\nend", "meta": {"hexsha": "8a118a21fa1dc862c25a7944d6a81a92aa5f7bf7", "size": 2495, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem111.jl", "max_stars_repo_name": "mbuhot/mbuhot-euler-solutions", "max_stars_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-12-18T13:25:41.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-18T13:25:41.000Z", "max_issues_repo_path": "julia/problem111.jl", "max_issues_repo_name": "mbuhot/mbuhot-euler-solutions", "max_issues_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/problem111.jl", "max_forks_repo_name": "mbuhot/mbuhot-euler-solutions", "max_forks_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9871794872, "max_line_length": 316, "alphanum_fraction": 0.6629258517, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172615983309, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7758105246666571}}
{"text": "function correlation(sample, k)\n    # Stabilized correlation function χ(k) = χ(|i-j|) = ⟨xᵢxⱼ⟩ - ⟨xᵢ⟩⟨xⱼ⟩\n    # Following Welford derivation from https://changyaochen.github.io/welford/\n\n    M = length(sample)\n    corr = sumx = sumy = 0.0\n    for i in 1:M-k\n        # ̅xᵢ₊₁ = ̅xᵢ + (xᵢ₊₁ - ̅xᵢ) / (N+1)\n        # ̅yᵢ₊₁ = ̅yᵢ + (yᵢ₊₁ - ̅yᵢ) / (N+1)\n        # χᵢ₊₁ = χᵢ + [(xᵢ₊₁ - ̅xᵢ)(yᵢ₊₁ - ̅yᵢ₊₁) - χᵢ] / (i + 1)\n\n        invN = 1.0 / i\n        sumy += invN * (sample[i + k] - sumy)\n        sumx_delta = invN * (sample[i] - sumx)\n        corr += sumx_delta * (sample[i + k] - sumy) - invN * corr\n        sumx += sumx_delta\n    end\n    return corr\nend\n\n# QMCM eq 3.15\n\"\"\"\n    unbinned_tau(sample[; truncate = true, max_rel_err = 0.0, min_sample_size = 32])\n\nEstimates the autocorrelation time `τ = ∑ₖ (1 - k/N) χₖ/χ₀` from a sample using the \ncorrelation function `χₖ = ⟨xᵢ xᵢ₊ₖ⟩ - ⟨xᵢ⟩⟨xᵢ₊ₖ⟩` where x are values in the sample.\n\nNote that by default this function truncated the sum over k if \n`v / τ < max_rel_err / (N - k)` or if the `k > N - min_sample_size`. The former \ncuts of fluctuations around 0 and can be turned of with `truncate = false`.\n\"\"\"\nfunction unbinned_tau(sample; truncate = true, max_rel_err = 0.0, min_sample_size = 32)\n    tau = 0.0\n\n    for k in 1:length(sample) - max(1, min_sample_size)\n        v = (1 - k/length(sample)) * correlation(sample, k)\n        tau += v\n\n        # We assume the worst case is a constant correlation for the tail.\n        # There are (length(sample) - k) values left\n        # The average prefactor is 0.5 * (1 - k/length(sample))\n        # If the sum of the tail is smaller than max_rel_err * tau, i.e. if tau\n        # can at most increase by a factor of max_rel_error, we stop the loop\n        if truncate && 0.5 * v * (length(sample) - k) < max_rel_err * tau\n            @debug \"Cancelled unbinned_tau summation after $k iterations.\"\n            break\n        end\n    end\n\n    return tau / correlation(sample, 0)\nend", "meta": {"hexsha": "a55b9cc4bb277d485e0457473797d040a1ef74de", "size": 1972, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/direct_tau.jl", "max_stars_repo_name": "crstnbr/BinningAnalysis", "max_stars_repo_head_hexsha": "000edcaa2cc0f8069dd6bf88ba802c245d70c60c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/direct_tau.jl", "max_issues_repo_name": "crstnbr/BinningAnalysis", "max_issues_repo_head_hexsha": "000edcaa2cc0f8069dd6bf88ba802c245d70c60c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/direct_tau.jl", "max_forks_repo_name": "crstnbr/BinningAnalysis", "max_forks_repo_head_hexsha": "000edcaa2cc0f8069dd6bf88ba802c245d70c60c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6666666667, "max_line_length": 87, "alphanum_fraction": 0.5948275862, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.7758065141206948}}
{"text": "export batchnorm\nusing Statistics\nusing AutoGrad: value\nimport Knet\n\n\"\"\"\n    batchnorm(x, mean_estimate, var_estimate, bias, scale; \n              epsilon = 1e-5, \n              update = Knet.training() ? 0.1 : 0\n              use_estimates = !Knet.training())\n\nReturn batch normalization applied to `x`:\n\n    ((x .- mean(x; dims)) ./ sqrt.(epsilon .+ var(x; dims))) .* scale .+ bias  # use_estimates=false\n    ((x .- mean_estimate) ./ sqrt.(epsilon .+ var_estimate)) .* scale .+ bias  # use_estimates=true\n\nIf `use_estimates=true`, the mean_estimate/var_estimate arguments are used in the\nnormalization calculation, otherwise the actual mean/var of the batch are used. To be\nconsistent with the CUDNN implementation `var` is called with `corrected=false`.  If `update\n> 0`, the mean_estimate/var_estimate arguments will be updated using batch statistics:\n\n    mean_estimate .= mean(x; dims) * update + mean_estimate * (1-update)\n    var_estimate  .= var(x; dims)  * update + var_estimate  * (1-update)\n\nBy default `use_estimates=false, update > 0` during training and `use_estimates=true,\nupdate=0` during inference.\n\nBias and scale are trainable parameters, corresponding to beta and gamma in the original\npaper.\n\nThe relation between the common size of bias/scale/mean/var and the dims value in the\nformula can be:\n\n    (1,1,C,1) if size(x)==(W,H,C,N) and dims==(1,2,4) (default, NCHW, per-channel)\n    (C,1,1,1) if size(x)==(C,W,H,N) and dims==(2,3,4) (NHWC tensor format)\n    (W,H,C,1) if size(x)==(W,H,C,N) and dims==4       (per-activation mode)\n\nReference: Batch Normalization: Accelerating Deep Network Training by Reducing Internal\nCovariate Shift, S. Ioffe, C. Szegedy, 2015.\n\"\"\"\nfunction batchnorm(\n    x, mean_estimate, var_estimate, bias, scale;\n    epsilon = 1e-5,\n    update = Knet.training() ? 0.1 : 0.0,\n    use_estimates = !Knet.training(),\n    o...\n)\n    update,epsilon = eltype(x).((update,epsilon))\n    if update > 0 || !use_estimates\n        dims = findall(size(mean_estimate) .== 1)\n        xmean = mean(x; dims)\n        xvar  = var(x; dims, mean=xmean, corrected=false)\n    end\n    if update > 0\n        (m, v, xm, xv) = value.((mean_estimate, var_estimate, xmean, xvar))\n        m .= xm * update + m * (1-update)\n        v .= xv * update + v * (1-update)\n    end        \n    if use_estimates\n        y = ((x .- mean_estimate) ./ sqrt.(epsilon .+ var_estimate)) .* scale .+ bias\n    else\n        y = ((x .- xmean) ./ sqrt.(epsilon .+ xvar)) .* scale .+ bias\n    end\n    return y\nend\n", "meta": {"hexsha": "e0e38aed08fbac29b8ee10ae3d3453c818abb7e4", "size": 2508, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ops21/batchnorm.jl", "max_stars_repo_name": "AndrewSerra/Knet.jl", "max_stars_repo_head_hexsha": "cbbcb670667b1707ad1b1d7c637784e36a98b81e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1492, "max_stars_repo_stars_event_min_datetime": "2015-09-30T07:05:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T14:48:46.000Z", "max_issues_repo_path": "src/ops21/batchnorm.jl", "max_issues_repo_name": "AndrewSerra/Knet.jl", "max_issues_repo_head_hexsha": "cbbcb670667b1707ad1b1d7c637784e36a98b81e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 604, "max_issues_repo_issues_event_min_datetime": "2016-02-05T06:32:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T20:09:19.000Z", "max_forks_repo_path": "src/ops21/batchnorm.jl", "max_forks_repo_name": "AndrewSerra/Knet.jl", "max_forks_repo_head_hexsha": "cbbcb670667b1707ad1b1d7c637784e36a98b81e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 340, "max_forks_repo_forks_event_min_datetime": "2015-10-28T07:47:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:51:11.000Z", "avg_line_length": 38.0, "max_line_length": 100, "alphanum_fraction": 0.6451355662, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7758065134906805}}
{"text": "# This function returns the expected score betweena  player and their opponent\n#     rating_1: rating of player\n#     rating_2: rating of opponent\n#     elo_scale: How many points above the other one player needs to be\n#        to have a 10x chance of winning the game\nfunction expected_score(rating_1, rating_2; elo_scale = 400)\n    return 1/(1+10^((rating_2 - rating_1)/elo_scale))\nend\n\n# This function rates a single player and returns the new rating\n#     rating_1: rating of player\n#     rating_2: rating of opponent\n#     outcome: the actual outcome of a given match\n#     elo_scale: How many points above the other one player needs to be\n#        to have a 10x chance of winning the game\n#     outcome_scale: the amount by which each game affects the player's rating\nfunction rate(rating_1, rating_2, outcome; elo_scale=400,\n              outcome_scale=15)\n\n    return rating_1 + outcome_scale*(outcome - expected_score(rating_1,\n                                                              rating_2;\n                                                              elo_scale))\n\nend\n\n", "meta": {"hexsha": "cb4a391aeca41f91ed22d0ef924b30525ac7092e", "size": 1089, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "elo/elo.jl", "max_stars_repo_name": "leios/simuleios", "max_stars_repo_head_hexsha": "fb96960b7f5481904ccc6ac30f94844c8a0e5900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 197, "max_stars_repo_stars_event_min_datetime": "2015-07-26T02:04:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T11:53:33.000Z", "max_issues_repo_path": "elo/elo.jl", "max_issues_repo_name": "leios/simuleios", "max_issues_repo_head_hexsha": "fb96960b7f5481904ccc6ac30f94844c8a0e5900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2015-08-04T22:55:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-06T02:33:48.000Z", "max_forks_repo_path": "elo/elo.jl", "max_forks_repo_name": "leios/simuleios", "max_forks_repo_head_hexsha": "fb96960b7f5481904ccc6ac30f94844c8a0e5900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 55, "max_forks_repo_forks_event_min_datetime": "2015-08-02T21:43:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T18:25:08.000Z", "avg_line_length": 41.8846153846, "max_line_length": 78, "alphanum_fraction": 0.6437098255, "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995742876885, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7757852211541655}}
{"text": "function naiveLU( a:: Array{Float64,1}, b :: Array{Float64,1}, c :: Array{Float64,1})\n  #= @assert (size(a) == size(b)) =#\n  #= @assert (size(a) == size(c)) =#\n  l = zeros(a)\n  d = zeros(a)\n  u = zeros(a)\n  d[1] = a[1]\n  u[1:end-1] = c[1:end-1]\n  \n  for ii = 2:(length(l))\n    l[ii] = b[ii]/d[ii-1]\n    d[ii] = a[ii] - l[ii]u[ii-1]\n  end\n  return (l,d,u)\nend\nexport naiveLU\n\nfunction ForwardThomas( l :: Array{Float64,1}, dataR :: Array{Float64,1})\n  y = zeros(dataR)\n  y[1] = dataR[1]\n  for ii = 2:length(dataR)\n    y[ii] = dataR[ii] - l[ii]*y[ii-1]\n  end\n  return y\nend\n\nfunction BackwardThomas( d :: Array{Float64, 1}, u :: Array{Float64,1}, dataR :: Array{Float64,1})\n  x = zeros(dataR)\n  x[end] = dataR[end]/d[end]\n  for ii = (length(x)-1):-1:1\n    x[ii] = (dataR[ii] - u[ii]*x[ii+1])/d[ii]\n  end\n  return x\nend\n", "meta": {"hexsha": "7710691ccc6a454ce3220e3a08be8ed929e68114", "size": 817, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/partialDifferentiate/implicit/naiveLU.jl", "max_stars_repo_name": "zhujinxuan/NaivePDE.jl", "max_stars_repo_head_hexsha": "bc079ae79e0ecc1a9cbc44fbf1dc0b4032964c75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/partialDifferentiate/implicit/naiveLU.jl", "max_issues_repo_name": "zhujinxuan/NaivePDE.jl", "max_issues_repo_head_hexsha": "bc079ae79e0ecc1a9cbc44fbf1dc0b4032964c75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/partialDifferentiate/implicit/naiveLU.jl", "max_forks_repo_name": "zhujinxuan/NaivePDE.jl", "max_forks_repo_head_hexsha": "bc079ae79e0ecc1a9cbc44fbf1dc0b4032964c75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3428571429, "max_line_length": 98, "alphanum_fraction": 0.5532435741, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7756702742706597}}
{"text": "using QuantEcon\nusing PyPlot\n\nfunction get_simultaneous_P(epsilon, N, p)\n    P = Array(Float64, (N+1, N+1))\n    for i in 1:(N+1)\n        if i - 1 < p * N\n            P[i, 1:end] = [binomial(N, j)*(epsilon)^j*(1-epsilon)^(N-j) for j in 0:N]\n            P[i, end] = 1-sum(P[i, 1:end-1])\n        elseif i - 1 == p * N\n            P[i, 1:end] = [binomial(N, j)*(1/2)^N for j in 0:N]\n            P[i, end] = 1-sum(P[i, 1:end-1])\n        else\n            P[i, 1:end] = [binomial(N, j)*(epsilon)^(N-j)*(1-epsilon)^j for j in 0:N]\n            P[i, end] = 1-sum(P[i, 1:end-1])\n        end\n    end\n    return P\nend\n\nfunction get_sequential_P(epsilon, N, p)\n    P = zeros(Float64, (N+1, N+1))\n    for i in 1:N+1\n        if i == 1\n            P[i, i + 1] = (N - (i-1))/N*epsilon/2\n            if (i-1) > p * (N-1)\n                P[i, i + 1] += 1 - epsilon\n            elseif (i-1) == p * (N-1)\n                P[i, i + 1] += 1/2\n            end\n            P[i, i] = 1 - P[i, i + 1]\n        elseif i == N+1\n            P[i, i-1] = (i-1)/N*epsilon/2\n            if i - 2 == p * (N - 1)\n                P[i, i-1] = 1/2\n            elseif i - 2 < p * (N - 1)\n                P[i, i-1] = 1 - epsilon\n            end\n            P[i, i] = 1 - P[i, i-1]\n        else\n            P[i, i+1] = (N - (i-1))/N*epsilon/2\n            if 1 > p * (N - (i-1))\n                P[i, i+1] += 1 - epsilon\n            elseif 1 == p * (N - (i-1))\n                P[i, i+1] += 1/2\n            end\n            P[i, i-1] = (i-1)/N*epsilon/2\n            if i - 2 == p * (N - 1)\n                P[i, i-1] = 1/2\n            elseif i - 2 < p * (N - 1)\n                P[i, i-1] = 1 - epsilon\n            end\n            P[i, i] = 1 - P[i, i-1] - P[i, i + 1]\n        end\n    end\n    return P\nend\n\ntype KMR\n    mc\n    N\n    epsilon\n    Xs\nend\n\nget_p_2x2(M) = (M[1, 1, 1] - M[2, 1, 1])/(M[1, 1, 1] - M[1, 2, 1] - M[2, 1, 1] + M[2, 2, 1])\nKMR(M, N::Int, epsilon::Float64; simul=true) = KMR(simul ? MarkovChain(get_simultaneous_P(epsilon, N, get_p_2x2(M))) : MarkovChain(get_sequential_P(epsilon, N, get_p_2x2(M))), N, epsilon, None)\n\nfunction simulate!(kmr::KMR, T; init=0)\n    kmr.Xs = simulate(kmr.mc, T, init+1) .- 1\nend\n\nplot_sample_path(kmr::KMR) = plot(kmr.Xs)#, label=\"epsilon = $kmr.epsion\")\n\nfunction plot_stationary_dist(kmr::KMR)\n    fig, ax = subplots()\n    #ax[:hist](mc_compute_stationary(kmr.mc))\n    ax[:bar](collect(0:kmr.N), mc_compute_stationary(kmr.mc))\nend\n\nfunction plot_empirical_dist(kmr::KMR)\n    fig, ax = subplots()\n    ax[:hist](kmr.Xs, normed=true)\nend\n\nfunction plot_sample_path(kmr::KMR)\n    plot(kmr.Xs)\nend\n\n\"\"\"\nM = Array(Int, (2, 2, 2))\nM[1, 1, :] = [4, 4]\nM[1, 2, :] = [0, 3]\nM[2, 1, :] = [3, 0]\nM[2, 2, :] = [2, 2]\n\nN = 20\nT = 100\nepsilon = 1/5\n\nkmr = KMR(M, N, epsilon)\nsimulate!(kmr, T)\n#plot_stationary_dist(kmr)\nplot_empirical_dist(kmr)\n#plot_sample_path(kmr)\n\nfor e in linspace(1/2, 0, 7)\n    kmr = KMR(M, N, e)\n    simulate!(kmr, T)\n    #plot_sample_path(kmr)\n    #plot_empirical_dist(kmr)\n    plot_stationary_dist(kmr)\nend\n#println(Xs)\n#plot(Xs)\n#println(P)\n#println(mean(X .== 2))\n\"\"\"\n", "meta": {"hexsha": "c2ab5dbf01c58970238ac65f52a0ae8fb6ef1c8a", "size": 3085, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "KMR2.jl", "max_stars_repo_name": "nswa17/KMR", "max_stars_repo_head_hexsha": "592822b0a0c25b5408e7437696666c4d64b65ec5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "KMR2.jl", "max_issues_repo_name": "nswa17/KMR", "max_issues_repo_head_hexsha": "592822b0a0c25b5408e7437696666c4d64b65ec5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KMR2.jl", "max_forks_repo_name": "nswa17/KMR", "max_forks_repo_head_hexsha": "592822b0a0c25b5408e7437696666c4d64b65ec5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9243697479, "max_line_length": 193, "alphanum_fraction": 0.4680713128, "num_tokens": 1260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7756702737774849}}
{"text": "module econ628ps7\n\nusing ForwaDiff, LinearAlgebra\n\nfunction newton(f, f_prime, x_0; tolerance = 1E-7, maxiter = 1000)\n    #Setup the algorithm\n    x_old = x_0\n    error = Inf\n    iter = 1\n    while error > tolerance && iter <= maxiter\n        x_new = x_old - (f(x_old)/f_prime(x_old))\n        error = sqrt((x_new - x_old)^2)\n        x_old = x_new\n        iter = iter + 1\n    end\n    if iter == maxiter + 1\n        return nothing\n    else\n        return x_old\nend\nend\n\nf(x) = (x-1)^3\nf_prime(x) = 3*(x-1)^2\n\nfunction newton(f, x_0; tolerance = 1E-7, maxiter = 1000)\nf_prime = x -> ForwardDiff.derivative(f, x)\nreturn newton(f,f_prime,x_0;tolerance = tolerance, maxiter = maxiter)\nend\n\nexport newton, f, f_prime\nend\n", "meta": {"hexsha": "7e78437c30b6056e2a3b6d6f51174e30db8ae4bb", "size": 714, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/econ628ps7.jl", "max_stars_repo_name": "sgyetvay/econ628ps7.jl", "max_stars_repo_head_hexsha": "a6b5f7977f17360f56afb41e204acfb9a781f766", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/econ628ps7.jl", "max_issues_repo_name": "sgyetvay/econ628ps7.jl", "max_issues_repo_head_hexsha": "a6b5f7977f17360f56afb41e204acfb9a781f766", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/econ628ps7.jl", "max_forks_repo_name": "sgyetvay/econ628ps7.jl", "max_forks_repo_head_hexsha": "a6b5f7977f17360f56afb41e204acfb9a781f766", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6363636364, "max_line_length": 69, "alphanum_fraction": 0.6260504202, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7756702685660245}}
{"text": "# Import Turing and Distributions.\nusing Turing, Distributions\n# GLM for comparison\nusing GLM\n# Import RDatasets.\nusing RDatasets\n# Import MCMCChains, Plots, and StatPlots for visualizations and diagnostics.\nusing MCMCChains, Plots, StatsPlots\n# Functionality for splitting and normalizing the data.\nusing MLDataUtils: shuffleobs, splitobs, rescale!\n# Functionality for evaluating the model predictions.\nusing Distances\n# set random seeds\nusing Random\nRandom.seed!(12212020)\n\n# import RDatasets\ndf = RDatasets.dataset(\"datasets\",\"ToothGrowth\");\n# Dummy code the Supp column\ndf.Supp_num = convert.(Float64, df.Supp .== \"VC\")\n\n# split train-test\ntrain, test = splitobs(shuffleobs(df), at=.7)\n\n# put DV and IV into separate vars\nfunction split_iv_dv(df)\n    y = Array(df.Len)\n    X = Array(df[:,[\"Supp_num\",\"Dose\"]])\n    return y, X\nend\ny_train, X_train = split_iv_dv(train)\ny_test, X_test = split_iv_dv(test)\n\n# OLS for comparison\nols = lm(@formula(Len ~ Supp * Dose), train)\n\n# define the generative function\n@model function linear_regression(y, X)\n    # construct interaction term\n    X = [X X[:,1] .* X[:,2]]\n    # prior for intercept\n    b0 ~ Normal(0,3)\n    # prior for betas, mvnormal with 0 means\n    bs ~ MvNormal(size(X,2), 3)\n    # error variance prior\n    e ~ InverseGamma(2,3)\n\n    ## condition on obs\n    mu = b0 .+ X * bs\n    y ~ MvNormal(mu, e)\nend\n\n# prior check, plot sample from prior\nprior_sample = sample(\n    linear_regression(y_train, X_train),\n    Prior(),\n    1000\n)\nplot(prior_sample)\ndescribe(prior_sample)\n\n# NUTS sampling posterior\nch = sample(\n    linear_regression(y_train, X_train),\n    NUTS(.65),\n    1000\n)\n\n# visualize the samples\nplot(ch)\n# summarize the samples\ndescribe(ch)\n\n## check against hold-out data\n", "meta": {"hexsha": "ae987ab360b039f1ace0c6c3043f36f482eac4de", "size": 1741, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "bayesian_regression.jl", "max_stars_repo_name": "zidongzhao/julia-learning", "max_stars_repo_head_hexsha": "f35aa17748243b8303e5c9e01dffcf19d80e1c64", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bayesian_regression.jl", "max_issues_repo_name": "zidongzhao/julia-learning", "max_issues_repo_head_hexsha": "f35aa17748243b8303e5c9e01dffcf19d80e1c64", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bayesian_regression.jl", "max_forks_repo_name": "zidongzhao/julia-learning", "max_forks_repo_head_hexsha": "f35aa17748243b8303e5c9e01dffcf19d80e1c64", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2133333333, "max_line_length": 77, "alphanum_fraction": 0.7082136703, "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7756702652561092}}
{"text": "## Pendulum\n# https://github.com/HarvardAgileRoboticsLab/unscented-dynamic-programming/blob/master/pendulum_dynamics.m\nfunction pendulum_dynamics!(xdot,x,u)\n    m = 1.\n    l = 0.5\n    b = 0.1\n    lc = 0.5\n    I = 0.25\n    g = 9.81\n    xdot[1] = x[2]\n    xdot[2] = (u[1] - m*g*lc*sin(x[1]) - b*x[2])/I\nend\nn,m = 2,1\n\n#create some empty functions (haven't updated for new model definition)\nfunction blank_error()\n\nend\n\nfunction blank_expansion()\n\nend\n\nmodel = Model(pendulum_dynamics!,n,m,blank_error,blank_expansion) # inplace model\n\n# initial conditions\nx0 = [0; 0.]\n\n# goal\nxf = [pi; 0] # (ie, swing up)\n\n# costs\nQ = 1e-3*Matrix(I,n,n)\nQf = 100.0*Matrix(I,n,n)\nR = 1e-2*Matrix(I,m,m)\n\n# simulation\ntf = 5.\n\nobj_uncon = LQRObjective(Q, R, Qf, tf, x0, xf)\n\n# Constraints\nu_bound = 2\nu_min = [-u_bound]\nu_max = [u_bound]\nobj_con = ConstrainedObjective(obj_uncon, u_min=u_min, u_max=u_max) # constrained objective\n\n# Set up problem\npendulum = [model,obj_uncon]\npendulum_constrained = [model, obj_con]\n", "meta": {"hexsha": "125869a8b345cdfdbabf1d348a4d781f9675af4c", "size": 998, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dynamics/pendulum.jl", "max_stars_repo_name": "GathererA/TrajectoryOptimization.jl", "max_stars_repo_head_hexsha": "c036b790555553b3477c7bebeaea118e17e43142", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-01T16:16:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-01T16:16:08.000Z", "max_issues_repo_path": "dynamics/pendulum.jl", "max_issues_repo_name": "GathererA/TrajectoryOptimization.jl", "max_issues_repo_head_hexsha": "c036b790555553b3477c7bebeaea118e17e43142", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dynamics/pendulum.jl", "max_forks_repo_name": "GathererA/TrajectoryOptimization.jl", "max_forks_repo_head_hexsha": "c036b790555553b3477c7bebeaea118e17e43142", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.568627451, "max_line_length": 106, "alphanum_fraction": 0.6733466934, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7756702647629344}}
{"text": "#=\nYou are given the following information, but you may prefer to do some research for yourself.\n\n- 1 Jan 1900 was a Monday.\n- Thirty days has September,\n  April, June and November.\n  All the rest have thirty-one,\n  Saving February alone,\n  Which has twenty-eight, rain or shine.\n  And on leap years, twenty-nine.\n- A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.\n\nHow many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?\n=#\n\nmonths = Dict(\n  1 => 31,\n  2 => 28,\n  3 => 31,\n  4 => 30,\n  5 => 31,\n  6 => 30,\n  7 => 31,\n  8 => 31,\n  9 => 30,\n  10 => 31,\n  11 => 30,\n  12 => 31\n)\n\nfunction isleapyear(year)\n  if year%100==0\n    return year%400==0 ? true : false\n  elseif year%4==0\n    return true\n  end\n  false\nend\n\nfunction calc()\n  currentyear = 1900\n  currentmonth = 1\n  totaldays = 1\n  totalsundays = 0\n  for year in 1901:2000\n    months[2] = isleapyear(year) ? 29 : 28 # set feb\n    for month in 1:length(months)\n      totaldays += months[month]\n      if (totaldays+1) % 7 == 0\n        totalsundays += 1\n      end\n    end\n  end\n  totalsundays\nend\n@time println(calc())\n", "meta": {"hexsha": "5f5affe21da83ce4aaf5cb80ae1b044a46f0b3aa", "size": 1178, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p19.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p19.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p19.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 20.6666666667, "max_line_length": 107, "alphanum_fraction": 0.6392190153, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7756702597980613}}
{"text": "using SuiteSparseGraphBLAS\nfunction pagerank(\n    A,\n    d = reduce(Monoids.PLUS_MONOID, A; dims=2),\n    α = 0.85,\n    maxiters = 100,\n    ϵ = 1.0e-4\n)\n    n = size(A, 1)\n    r = GBVector{Float32}(n)\n    t = GBVector{Float32}(n)\n    d[:, accum=BinaryOps.DIV] = α\n    r[:] = 1.0 / n\n    teleport = (1 - α) / n\n    rdiff = 1.0\n    i = 0\n    for outer i ∈ 1:maxiters\n        temp = t; t = r; r = temp\n        w = t ./ d\n        r[:] = teleport\n        mul!(r, A', w, Semirings.PLUS_SECOND, accum=BinaryOps.PLUS)\n        t .-= r\n        map!(UnaryOps.ABS, t)\n        rdiff = reduce(Monoids.PLUS_MONOID, t)\n        if rdiff <= ϵ\n            break\n        end\n    end\n    return r, i\nend\n", "meta": {"hexsha": "6a036078a7f89fa33683b0d960d56c96b702011c", "size": 682, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/pagerank.jl", "max_stars_repo_name": "samuel-esp/SuiteSparseGraphBLAS.jl", "max_stars_repo_head_hexsha": "90ab8e7bf05bde81d4d09a0abe8a08b8767a2552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/pagerank.jl", "max_issues_repo_name": "samuel-esp/SuiteSparseGraphBLAS.jl", "max_issues_repo_head_hexsha": "90ab8e7bf05bde81d4d09a0abe8a08b8767a2552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/pagerank.jl", "max_forks_repo_name": "samuel-esp/SuiteSparseGraphBLAS.jl", "max_forks_repo_head_hexsha": "90ab8e7bf05bde81d4d09a0abe8a08b8767a2552", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0, "max_line_length": 67, "alphanum_fraction": 0.4985337243, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7756453215338486}}
{"text": "function integral(x::CellVar, grid::TreeGrid; filter::Function = active)\n    int = zero(eltype(x.data))\n    for cell ∈ cells(grid, filter = filter)\n        @inbounds int += volume(cell) * x[cell]\n    end\n    return int\nend\n\nfunction inner_product(x::CellVar, y::CellVar, grid::TreeGrid; filter::Function = active)\n    int = zero(eltype(x.data))\n    for cell ∈ cells(grid, filter = filter)\n        @inbounds int += volume(cell) * x[cell] * y[cell]\n    end\n    return int\nend\n\n@inline norm(x::CellVar, grid::TreeGrid; filter::Function = active) = sqrt(inner_product(x, x, grid, filter))\n", "meta": {"hexsha": "5807ef31dfdfee1d2b1e39adafbca812c188855c", "size": 585, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functionals.jl", "max_stars_repo_name": "Ronn3y/FiniteVolumeMethod.jl", "max_stars_repo_head_hexsha": "3f7c4a790c38d667207b73b948ae3979a878c9ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functionals.jl", "max_issues_repo_name": "Ronn3y/FiniteVolumeMethod.jl", "max_issues_repo_head_hexsha": "3f7c4a790c38d667207b73b948ae3979a878c9ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functionals.jl", "max_forks_repo_name": "Ronn3y/FiniteVolumeMethod.jl", "max_forks_repo_head_hexsha": "3f7c4a790c38d667207b73b948ae3979a878c9ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5, "max_line_length": 109, "alphanum_fraction": 0.6547008547, "num_tokens": 161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7756453214854739}}
{"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\n\n\"This routine generates a gif movie showing how the heat equation rapidly dissipates\nhigh frequencies.\"\n\n# m = number of grid points\nfunction build_FD(m,f,α,β)\n    x = LinRange(-1,1,m+2)\n    xint = x[2:end-1]\n    h = x[2]-x[1]\n    A = (1/h^2) * spdiagm(0=>2*ones(m),-1=>-ones(m-1),1=>-ones(m-1))\n\n    function F(t)\n        b = f.(xint,t)\n        b[1] += α(t)/h^2\n        b[m] += β(t)/h^2\n        return b\n    end\n    return A,x,xint,h,F\nend\n\nm = 200\nT = .025\n\ndt = .005/m\n\nA,x,xint,h,F = build_FD(m,(x,t)->0,t->0,t->0)\n\nu0(x) = sin(pi*x) + .1*sin(2*pi*x) - .33*sin(3*pi*x) + 10*sin(8*pi*x)\nu = u0.(xint)\nNsteps = ceil(Int,T/dt)\ndt = T/Nsteps\n@gif for i = 1:Nsteps\n    tprev = (i-1)*dt\n    t = i*dt\n    u .= (I + .5*dt*A)\\((I - .5*dt*A)*u + .5*dt*(F(t)+F(tprev)))\n    if i%10==0\n        plot(xint,u,mark=:dot,leg=false)\n        println(\"on timestep $i out of $Nsteps\")\n    end\nend every 10\n", "meta": {"hexsha": "99499322e73421efd6c3c26c9b775cdcd6495309", "size": 941, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week3/heat_movie.jl", "max_stars_repo_name": "jlchan/caam452_s21", "max_stars_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:38:43.000Z", "max_issues_repo_path": "week3/heat_movie.jl", "max_issues_repo_name": "jlchan/caam452_s21", "max_issues_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week3/heat_movie.jl", "max_forks_repo_name": "jlchan/caam452_s21", "max_forks_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3863636364, "max_line_length": 84, "alphanum_fraction": 0.5451647184, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7756101195969879}}
{"text": "# This file illustrates the recovery of a real signal from its frequency domain. \n\nusing Plots \nusing FFTW\n\n# Define Fourier transform \nfs = 100 \nts = 1 / 100 \nl = 2^10\nfv = 0 : fs / (l - 1) : fs\nxv = sinc.(fv)\nff = 0 : fs / (2l - 1) : fs\nxf = [xv; reverse(xv)]  \n\n# Define inverse Fourier transform \nx = ifft(xf) * fs\nt = (0 : 2l - 1) * ts \n \n# Plot the results\nplt = plot(layout=2) \nplot!(ff, abs.(xf), subplot=1)\nxlabel!(\"f [Hz]\", subplot=1)\nylabel!(\"|X(f)|\", subplot=1)\nplot!(t, abs.(x), subplot=2)\nxlabel!(\"t [s]\", subplot=2)\nylabel!(\"x(t)\", subplot=2)\ndisplay(plt) \n", "meta": {"hexsha": "ce7cbd0685af4005c54f3f9c2d112e5b4eff3b6d", "size": 572, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/dsp/inversefft.jl", "max_stars_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_stars_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-03T20:02:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T06:43:38.000Z", "max_issues_repo_path": "example/dsp/inversefft.jl", "max_issues_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_issues_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-11-26T21:56:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-03T19:54:59.000Z", "max_forks_repo_path": "example/dsp/inversefft.jl", "max_forks_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_forks_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-20T12:53:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T12:53:43.000Z", "avg_line_length": 20.4285714286, "max_line_length": 81, "alphanum_fraction": 0.6031468531, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976795, "lm_q2_score": 0.8056321819811829, "lm_q1q2_score": 0.7755604420090763}}
{"text": "##############################################################\nfunction softparzen(X, S_centre, r, γ = 1e-6)\n##############################################################\n\n  N, D = size(X)\n  M = length(S_centre)\n\n  # Usually kernel has also some normalisation constant\n  # but in the following calculations it cancels out anyway\n  K = zeros(M,N)\n  for j in 1:M\n    for n in 1:N\n      @inbounds K[j,n] = exp(-0.5*norm(X[S_centre[j],:] - X[n,:])^2 / (r*r))\n    end\n  end\n\n  # Soft version for coefficients\n  Q = zeros(M)\n  sumK = sum(K)\n  for j in 1:M\n    @inbounds Q[j] = sum(K[j,:]) / sumK\n  end\n\n\n  # responsibilities - note different to standard mixture models\n  # See equation (6)\n  resp = zeros(M,N)\n  for j in 1:M\n    sum_Kj_over_n = sum(K[j,:])\n    for n in 1:N\n      @inbounds resp[j,n] = K[j,n] / sum_Kj_over_n\n    end\n  end\n\n\n  # Soft version for means\n  # See equation (7)\n  mu = zeros(M, D)\n  for j=1:M\n    for n=1:N\n      for i=1:D\n        @inbounds mu[j,i] += resp[j,n] * X[n,i]\n      end\n    end\n  end\n\n\n  # Soft version for covariances\n  C = [zeros(D, D) for j in 1:M]\n\n  for j in 1:M\n    for i in 1:D\n      for d in 1:D\n        for n in 1:N\n          @inbounds C[j][i,d] += resp[j,n] * ((X[n,i] - mu[j,i]) * (X[n,d] - mu[j,d]))\n        end\n      end\n    end\n\n    C[j] = (C[j] + C[j]')*0.5 + γ*I\n\n  end\n\n  return Q, mu, C\n\nend\n", "meta": {"hexsha": "48fd5402ed7da449a7b5f7296691b0f5452f70d8", "size": 1343, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/softparzen.jl", "max_stars_repo_name": "ngiann/FastParzenWindows.jl", "max_stars_repo_head_hexsha": "090ae01bb4089ce50ecfe8a8ba176da4b8ce6810", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-23T13:00:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:47:00.000Z", "max_issues_repo_path": "src/softparzen.jl", "max_issues_repo_name": "HITS-AIN/FastParzenWindows.jl", "max_issues_repo_head_hexsha": "d036bc3b704a931a4e2ab5ce39b4e65de8488775", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-20T10:38:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T15:47:36.000Z", "max_forks_repo_path": "src/softparzen.jl", "max_forks_repo_name": "HITS-AIN/FastParzenWindows.jl", "max_forks_repo_head_hexsha": "d036bc3b704a931a4e2ab5ce39b4e65de8488775", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-20T08:17:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T08:17:31.000Z", "avg_line_length": 20.0447761194, "max_line_length": 86, "alphanum_fraction": 0.487714073, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7755581917661654}}
{"text": "\"\"\"\n    discretize(domain, N)\n\nDiscretize domain with `N` points.\n\"\"\"\nfunction discretize end\n\ndiscretize(domain::ClosedIntervalDomain, N) = LinRange(domain.left, domain.right, N + 1)\n\nfunction discretize(domain::PeriodicIntervalDomain, N)\n    LinRange(domain.left + (domain.right - domain.left) / N, domain.right, N)\nend\n", "meta": {"hexsha": "e948ce30e8d5027321c0c305e5909a027d0c6fba", "size": 322, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/domain/discretize.jl", "max_stars_repo_name": "agdestein/DiscreteFiltering.jl", "max_stars_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-23T12:51:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T12:51:11.000Z", "max_issues_repo_path": "src/domain/discretize.jl", "max_issues_repo_name": "agdestein/DiscreteFiltering.jl", "max_issues_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/domain/discretize.jl", "max_forks_repo_name": "agdestein/DiscreteFiltering.jl", "max_forks_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7692307692, "max_line_length": 88, "alphanum_fraction": 0.7298136646, "num_tokens": 84, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7755581891910461}}
{"text": "module PCA\n\n    using LinearAlgebra\n\n    function findPCAs(\n        X    :: AbstractArray{T, 2};\n        num  :: Integer = 1\n    ) where T <: AbstractFloat\n\n\n        dim, N = size(X)\n\n\n        Σ = Symmetric(X * X')\n        \n        println(\"Dimension of Σ : \", size(Σ))\n        println(\"Any missing data? \", any(isnan.(Σ))) \n\n        if any(isnan.(Σ))\n            throw(ErrorException(\"Data contains NaN!\"))\n        end        \n\n        @time F = eigen(Σ)\n\n        #println(F.values)\n        #println(length(F.values))\n\n        order = collect(1:dim)\n        sort!(order; by = i -> F.values[i], rev=true)\n\n        evs = zeros(T, dim, num)\n        for i = 1:num\n            evs[:, i] = normalize(F.vectors[:, order[i]])\n        end\n\n\n        return evs\n\n    end\n\nend\n", "meta": {"hexsha": "d01b088f52f1baabe1aa83b094a0efda1d6632a4", "size": 766, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/old/diagnose_scripts/analysis/PCA.jl", "max_stars_repo_name": "meteorologytoday/CESM-diagnostic", "max_stars_repo_head_hexsha": "ed9cbc3ffeb2ebebe7d7a2453a52111a51b1660f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/old/diagnose_scripts/analysis/PCA.jl", "max_issues_repo_name": "meteorologytoday/CESM-diagnostic", "max_issues_repo_head_hexsha": "ed9cbc3ffeb2ebebe7d7a2453a52111a51b1660f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/old/diagnose_scripts/analysis/PCA.jl", "max_forks_repo_name": "meteorologytoday/CESM-diagnostic", "max_forks_repo_head_hexsha": "ed9cbc3ffeb2ebebe7d7a2453a52111a51b1660f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.2380952381, "max_line_length": 57, "alphanum_fraction": 0.4804177546, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9597620619801095, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7755522484436334}}
{"text": "#=\n\n    This is a port of the R2 model CoinBias.cs \n\n    Output from the R2 model:\n    ```\n    Mean: 0.421294\n    Variance: 0.0162177\n    Number of accepted samples = 692\n    ```\n\n    This model:\n  parameters      mean       std   naive_se      mcse         ess      rhat   ess_per_sec \n      Symbol   Float64   Float64    Float64   Float64     Float64   Float64       Float64 \n\n        bias    0.4166    0.1360     0.0014    0.0020   5021.6561    1.0000     2276.3627\n   \n=#\n\nusing Turing, StatsPlots, Distributions, StatsBase\nusing CSV\ninclude(\"jl_utils.jl\")\n\n@model function coin_bias(x) \n    n = length(x)\n    # Beta(2,5) has mean about 0.2855\n    bias ~ Beta(2,5)\n    x ~ filldist(Bernoulli(bias),n)\nend \n\n\nx = parse.(Int,split(readline(\"coin_bias.txt\"),\",\"))\nprintln(\"x:$x\")\nmodel = coin_bias(x)\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 1_000)\nchns = sample(model, PG(5), 10_000)\n# chns = sample(model, SMC(), 1_000)\n# chns = sample(model, IS(), 10_000)\n\n# chns = sample(model, HMC(0.1,6), 1_000)\n# chns = sample(model, NUTS(), 1_000)\n\ndisplay(chns)\n\nshow_var_dist_pct(chns,:bias,20)", "meta": {"hexsha": "1b879c37dc2051d316baddd54e433d3a1db31643", "size": 1118, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/coin_bias.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/coin_bias.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/coin_bias.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 23.7872340426, "max_line_length": 90, "alphanum_fraction": 0.6118067979, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.775544442104665}}
{"text": "# ---\n# title: 1652. Defuse the Bomb\n# id: problem1652\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Easy\n# categories: Array\n# link: <https://leetcode.com/problems/defuse-the-bomb/description/>\n# hidden: true\n# ---\n# \n# You have a bomb to defuse, and your time is running out! Your informer will\n# provide you with a **circular** array `code` of length of `n` and a key `k`.\n# \n# To decrypt the code, you must replace every number. All the numbers are\n# replaced **simultaneously**.\n# \n#   * If `k > 0`, replace the `ith` number with the sum of the **next** `k` numbers.\n#   * If `k < 0`, replace the `ith` number with the sum of the **previous** `k` numbers.\n#   * If `k == 0`, replace the `ith` number with `0`.\n# \n# As `code` is circular, the next element of `code[n-1]` is `code[0]`, and the\n# previous element of `code[0]` is `code[n-1]`.\n# \n# Given the **circular** array `code` and an integer key `k`, return _the\n# decrypted code to defuse the bomb_!\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: code = [5,7,1,4], k = 3\n#     Output: [12,10,16,13]\n#     Explanation: Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around.\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: code = [1,2,3,4], k = 0\n#     Output: [0,0,0,0]\n#     Explanation: When k is zero, the numbers are replaced by 0. \n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: code = [2,4,9,3], k = -2\n#     Output: [12,5,6,13]\n#     Explanation: The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of the **previous** numbers.\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `n == code.length`\n#   * `1 <= n <= 100`\n#   * `1 <= code[i] <= 100`\n#   * `-(n - 1) <= k <= n - 1`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "b7c76350406266c994896731d8aab3e5550afefa", "size": 1907, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1652.defuse-the-bomb.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/unresolved/1652.defuse-the-bomb.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/unresolved/1652.defuse-the-bomb.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 26.4861111111, "max_line_length": 165, "alphanum_fraction": 0.5778710016, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.8740772253241802, "lm_q1q2_score": 0.7754853295711153}}
{"text": "using Plots, JLD, ProgressBars, Statistics\nDirections=[[0,1],[0,-1],[1,0],[-1,0]]\nfunction f(N, Network_,Pos)\n    if N==0\n        return 1\n    end\n    Network_[Pos...]=true\n    c=0\n    for path in Directions\n        NextPos=Pos .+ path\n        if !Network_[NextPos...]\n            c+=f(N-1, Network_, NextPos)\n        end\n    end\n    Network_[Pos...]=false\n    return c\nend\nTotdata=[]\nN=16\nfor n in ProgressBar(0:N)\n    L=2n+1\n    Network_=falses(L,L)\n    FirstPos=[n+1, n+1]\n    push!(Totdata, f(n, Network_,FirstPos))\nend\nplot(0:N,Totdata, legend=false, dpi=400)\nscatter!(0:N,Totdata, legend=false, xlabel=\"N\",ylabel=\"Number of Paths\",\n    title=\"Number of Paths versus N for Self-Avoiding Walker\", titlefontsize=10, dpi=400)\nsave(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter5\\\\4.7\\\\SAW.jld\", \"Data\", Totdata)\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter5\\\\4.7\\\\Figs\\\\NumberOfPaths_N.png\")\nplot(0:N, Totdata./ 4 .^(0:N), legend=false, dpi=400)\nscatter!(0:N, Totdata./ 4 .^(0:N), legend=false, xlabel=\"N\",ylabel=\"Ratio of Number of Paths\",\n    title=\"Ratio of Number of Paths of SAW and RW \", dpi=400)\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter5\\\\4.7\\\\Figs\\\\Ratio_N.png\")\n", "meta": {"hexsha": "f175c890ca6231cad9a6715066491327a89128c9", "size": 1266, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter5/4.7/4.7.jl", "max_stars_repo_name": "narges8k/computational_physics", "max_stars_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter5/4.7/4.7.jl", "max_issues_repo_name": "narges8k/computational_physics", "max_issues_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter5/4.7/4.7.jl", "max_forks_repo_name": "narges8k/computational_physics", "max_forks_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T09:55:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T09:55:00.000Z", "avg_line_length": 36.1714285714, "max_line_length": 112, "alphanum_fraction": 0.6563981043, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.7754582656019715}}
{"text": "# ---\n# title: 883. Projection Area of 3D Shapes\n# id: problem883\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Easy\n# categories: Math\n# link: <https://leetcode.com/problems/projection-area-of-3d-shapes/description/>\n# hidden: true\n# ---\n# \n# On a `N * N` grid, we place some `1 * 1 * 1 `cubes that are axis-aligned with\n# the x, y, and z axes.\n# \n# Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of\n# grid cell `(i, j)`.\n# \n# Now we view the  _projection_  of these cubes onto the xy, yz, and zx planes.\n# \n# A projection is like a shadow, that maps our 3 dimensional figure to a 2\n# dimensional plane.\n# \n# Here, we are viewing the \"shadow\" when looking at the cubes from the top, the\n# front, and the side.\n# \n# Return the total area of all three projections.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: [[2]]\n#     Output: 5\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: [[1,2],[3,4]]\n#     Output: 17\n#     Explanation:\n#     Here are the three projections (\"shadows\") of the shape made with each axis-aligned plane.\n#     ![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/02/shadow.png)\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: [[1,0],[0,2]]\n#     Output: 8\n#     \n# \n# **Example 4:**\n# \n#     \n#     \n#     Input: [[1,1,1],[1,0,1],[1,1,1]]\n#     Output: 14\n#     \n# \n# **Example 5:**\n# \n#     \n#     \n#     Input: [[2,2,2],[2,1,2],[2,2,2]]\n#     Output: 21\n#     \n# \n# \n# \n# **Note:**\n# \n#   * `1 <= grid.length = grid[0].length <= 50`\n#   * `0 <= grid[i][j] <= 50`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "9ab376c8c26d31da2d7c8d67527ffbb667d82977", "size": 1633, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/883.projection-area-of-3d-shapes.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/unresolved/883.projection-area-of-3d-shapes.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/unresolved/883.projection-area-of-3d-shapes.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 18.988372093, "max_line_length": 96, "alphanum_fraction": 0.5450091855, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624557, "lm_q2_score": 0.8652240773641087, "lm_q1q2_score": 0.7754582650081738}}
{"text": "# Compact Hilbert Indices by Chris Hamilton. Technical Report CS-2006-07.\n# 6059 University Ave., Halifax, Nova Scotia, B3H 1W5, Canada.\n#\n# In this document, the notation is:\n# ∧ = & for and\n# ∨ = | for or\n# ⊻ = for xor\n# ▷ = >> for shift right\n# ◁ = << for shift left\n# ⌈x⌉ = ceil(x)\n# ⌊x⌋ = floor(x)\n\n\n# hi_g(i) is the direction in which brgc changes.\n# It is also tells us the axis along which the exit of one\n# subcube meets the entrance of the next subcube.\nhi_g(i) = trailing_set_bits(i)\n# This is the definition of g, to compare against for testing.\nhi_g_orig(i) = floor(typeof(i), log2(brgc(i) ⊻ brgc(i + 1)))\n\n\n# e is the entry vertex of the ith sub-hypercube in a Gray code\n# ordering of sub-hypercubes. If e is 0b011, then this is z-y-x\n# within the subcube of 0 in the z, 1 in the y, 1 in the x.\n# e = gc(2⌊(i-1)/2⌋) = gc(2*floor((i-1)/2)).\n# domain is i=0 to i=2^n - 1.\nfunction hi_e(i::Integer)\n    i == zero(i) && return zero(i)\n    brgc((i - one(i)) & ~one(i))\nend\n\n# This is verbatim from the article, for comparison.\nfunction hi_e_orig(i::Base.BitInteger)\n    i == zero(i) && return zero(i)\n    brgc(2 * floor(typeof(i), (i - 1) / 2))\nend\n\n\n\"\"\"\nf is the exit vertex of the ith sub-hypercube in a Gray code\nordering of the sub-hypercubes.\nCorllary 2.7 on pg. 12 says:\n    hi_f(i, n) = hi_e(i) ⊻ hi_d(i, n)\n\"\"\"\nhi_f(i, n) = hi_e(one(i)<<n - one(i) - i) ⊻ (one(i)<<(n-1))\n# hi_f(i, n) = hi_e(i) ⊻ hi_d(i, n)\n#hi_f(i, n) = hi_e(i) ⊻ (one(i)<<hi_d(i, n))\n\n\n\"\"\"\npage 12. directions\nd(i) = 0 if i=0\n    = g(i-1) mod n if i=0 mod 2\n    = g(i) mod n if i=1 mod 2.\nDomain is 0 <= i <= 2^n - 1.\n\"\"\"\nfunction hi_d(i, n)\n    i == zero(i) && return zero(i)\n    ((i & 1) == 0) && return hi_g(i - one(i)) % n\n    hi_g(i) % n\nend\n\n\n# bitrotate is a left shift, so negate d+1.\n# T_{(e,d)}(b), so read right-to-left.\n# The paper means to bit rotate over the n bits that are in use,\n# not all n bits. This is not the usual bitrotate!\n# This had a +1 in the paper.\nhi_T(b, d, e, n) = rotateright(b ⊻ e, d, n)\n\n# The author's code differs with his paper. It doesn't add one.\n# https://github.com/pdebuyl/libhilbert/blob/master/include/Hilbert/Algorithm.hpp\nhi_T_inv(b, d, e, n) = rotateleft(b, d, n) ⊻ e\n\n# Lemma 2.12, page 15.\n# Is it -2 or -1?\n# function hi_T_inv(b, d, e, n)\n#     hi_T(b, n - d - one(b) - one(b), bitrotate(e, -(d + one(b)), n), n)\n# end\n\n\n\"\"\"\n    ith_bit_of_indices(n, p, i)\n\nGiven `n` indices in `p`, take the `i`-th bit of each one\nand place it so that the first vector's value is at the\n0-th place, the second vector's value at the 1st place, and so-on.\n`i` is zero-indexed.\n\"\"\"\nfunction ith_bit_of_indices(n, p, i)\n    l = zero(eltype(p))\n    for j = 0:(n - 1)\n        b = (p[j + 1] & (one(eltype(p))<<i)) >>i\n        l |= b << j\n    end\n    l\nend\n\n\n# hamilton version of getting the ith bit, zero-indexed i.\nfunction get_location(p::Vector{T}, i) where {T}\n    l = zero(T)\n    for j = eachindex(p)\n        if (p[j] & (one(T) << i)) != 0\n            l |= (one(T) << (j - 1))\n        end\n    end\n    l\nend\n\n\n\"\"\"\n    set_indices_bits(p, l, m, i)\n\nGiven bits in `l`, set each index in the array `p` according\nto the bit in `l`. Set the i-th bit of each index in `p`.\n\"\"\"\nfunction set_indices_bits!(p, l, m, i)\n    for j in 0:(m - 1)\n        v = (l & (1<<j)) >>j\n        p[j + 1] = p[j + 1] | (v<<i)\n    end\nend\n\n\n\"\"\"\nReturn `m` bits from the `i`-th set of `m` bits\nin the integer `h`. `i` is zero-based.\n\"\"\"\nfunction bitrange(h, n, i)\n    v = zero(h)\n    for j in 0:(n - 1)\n        v = v | (h & (1<<(i*n + j)))\n    end\n    v\nend\n\n\nfunction update1(l, t, w, n, e, d)\n    e = l ⊻ (one(l) << d)\n    d += one(d) + first_set_bit(t)\n    while d >= n\n        d -= n\n    end\n    if (w & one(w)) == zero(w)\n        if d == zero(d)\n            e ⊻= one(e) << (n - 1)\n        else\n            e ⊻= one(e) << (d - 1)\n        end\n    end\n    e, d\nend\n\n\nfunction update2(l, t, w, n, e, d)\n    e = l\n    e ⊻= (one(e) << d)\n    d += one(d) + first_set_bit(t)\n    while d >= n\n        d -= n\n    end\n    e, d\nend\n\n\n\"\"\"\nAlgorithm.hpp: _coordsToIndex\n\"\"\"\nfunction hilbert_index_paper!(::Type{T}, n, m, p, ds) where {T <: Integer}\n    h = zero(T)  # hilbert index\n    e = zero(T)  # entry point\n    d = one(T)  # direction\n    nmask = fbvn1s(T, n)\n    for i = (m - 1):-1:0  # i is an index. Can be any type.\n        ds[i + 1] = d\n        l = T(ith_bit_of_indices(n, p, i))\n        t = hi_T(l, d, e, n)\n        w = t\n        if i < m - 1\n            w ⊻= (one(w) << (n - 1))\n        end\n        # Concatenate to the index\n        h |= (w & nmask) << (i * n)\n        e, d = update2(l, t, w, n, e, d)\n    end\n    brgc_inv(h)\nend\n\n\n\"\"\"\n    hilbert_index(n, m, p)\n\nHilbert index for an `n`-dimensional vector `p`, with each\ncomponent of extent less than 2^m. Algorithm 1 of Hamilton and\nRau-Chaplin.\n\"\"\"\nfunction hilbert_index_paper(::Type{T}, n, m, p) where {T <: Integer}\n    ds = zeros(Int, m)\n    hilbert_index_paper!(T, n, m, p, ds)\nend\n\n\nfunction hilbert_index_inv_paper!(::Type{T}, n, m, h, p) where {T <: Integer}\n    e = zero(T)\n    d = one(T)\n    l = zero(T)\n    p .= zero(eltype(p))\n    nmask = fbvn1s(T, n)\n    for i = (m - 1):-1:0\n        w = (h >> (i * n)) & nmask\n        t = brgc(w)\n        l = hi_T_inv(t, d, e, n)\n        set_indices_bits!(p, l, n, i)\n        e, d = update1(l, t, w, n, e, d)\n    end\nend\n\n\n# Make d an argument because it determines the initial direction and maybe\n# it isn't initialized correctly. Maybe d and e need different initial values.\nfunction hilbert_index(n, m, p, d = zero(eltype(p)))\n    h = zero(eltype(p))  # hilbert index\n    e = zero(eltype(p))  # entry point\n    for i = (m - 1):-1:0  # i is an index. Can be any type.\n        l = ith_bit_of_indices(n, p, i)\n        # @show l\n        l = hi_T(l, d, e, n)  # n or m?\n        w = brgc_inv(l)\n        h = (h << n) | w\n        e = e ⊻ rotateleft(hi_e(w), d + one(d), n)\n        d = (d + hi_d(w, n) + one(d)) % n  # n or m for hi_d?\n    end\n    h\nend\n\n\nfunction hilbert_index_inv(n, m, h)\n    e = zero(h)  # entry point\n    d = zero(h)  # direction\n    p = zeros(typeof(h), m)\n    for i = (m - 1):-1:0  # i is an index. Can be any type.\n        w = bitrange(h, n, i)\n        l = brgc(w)\n        l = hi_T_inv(l, d, e, n)\n        set_indices_bits!(p, l, m, i)\n        e = e ⊻ rotateleft(hi_e(w), d + one(d), n)\n        d = (d + hi_d(w, n) + one(d)) % n  # n or m for hi_d?\n    end\n    p\nend\n\n\n\"\"\"\nCalculates a bit-mask for excluding Gray code values when the level\nis below the resolution of the dimension.\n\nBits free at iteration `i`. Vector of resolutions, in powers of two,\n`m`. Dimensions `n` so that `length(m)==n`. `i` is the level down\nin the Hilbert curve. `d` is the direction, called `hi_d` above.\n\nReturns both the mask and the number of bits set in the mask.\n\"\"\"\nfunction extract_mask(m::Vector, n, d, i)\n    T = UInt64\n    mask = zero(T)\n    b = 0\n    jm = one(T)\n    j = d\n    while true\n        if m[j + 1] > i\n            mask |= jm\n            b += 1\n        end\n        jm <<= one(T)\n        if jm == zero(T)\n            jm = one(T)\n        end\n        j += 1\n        if j == n\n            j = 0\n        end\n        if j == d\n            break\n        end\n    end\n    mask, b\nend\n\n\nfunction extract_mask_paper(m::Vector, n, d, i)\n    T = UInt64\n    mask = zero(T)\n    b = 0\n    for j = (n-1):-1:0\n        mask <<= one(T)\n        jn = (j + d) % n\n        if m[jn + 1] > i\n            mask |= one(T)\n            b += 1\n        end\n    end\n    mask, b\nend\n\n\n\"\"\"\nFrom GrayCodeRank.hpp: compactIndex.\n\"\"\"\nfunction compact_index(ms::Vector, ds::Vector, n, m, h::T) where {T}\n    hc = zero(T)\n    hr = 0\n    hcr = 0\n    hm = one(T)\n    hcm = one(T)\n    for i = 0:(m-1)\n        j = ds[i + 1]\n        while true\n            if ms[j + 1] > i\n                if hr > 0\n                    error(\"hr on next rack\")\n                end\n                if ((h & hm) != 0)\n                    if hcr == 0\n                        hc |= hcm\n                    else\n                        error(\"should only be one rack\")\n                    end\n                end\n                hcm <<= 1\n                if hcm == 0\n                    hcm = one(T)\n                    hcr += 1\n                end\n            end\n            j += 1\n            if j == n\n                j = 0\n            end\n            hm <<= 1\n            if hm == zero(T)\n                hm = one(T)\n                hr += 1\n            end\n            if j == ds[i + 1]\n                break\n            end\n        end\n    end\n    hc\nend\n\n\nfunction coords_to_compact_index(::Type{T}, p::Vector{A}, ms::Vector, n) where {A,T}\n    m = maximum(ms)\n    M = sum(ms)\n    mn = m * n\n    ds = zeros(Int, m)\n    h = hilbert_index_paper!(T, n, m, p, ds)\n    compact_index(ms, ds, n, m, h)\nend\n\n\nfunction compact_index_to_coords!(p::Vector{A}, ms, n, hc::T) where {A, T}\n    m = maximum(ms)\n    M = sum(ms)\n    bit_cnt = 8 * sizeof(T)\n\n    e = zero(T)\n    d = one(T)\n    l = zero(T)\n    p .= zero(A)\n    # work from most significant bit to least significant bit\n    for i = (m - 1):-1:0\n        mask, b = extract_mask(ms, n, d, i)\n        # rotateright(val, shift_cnt, total_bits)\n        ptrn = rotateright(e, d, n)\n\n        # Get the Hilbert index bits.\n        M -= b\n        # b bits from hc at index M, into r\n        r = get_bits(hc, b, M)\n        \n        t, w = brgc_rank_inv(mask, ptrn, r, n, b)\n\n        l = hi_T_inv(t, d, e, n)\n        set_indices_bits!(p, l, n, i)\n        e, d = update1(l, t, w, n, e, d)\n    end\nend\n\n\n\"\"\"\n    SpaceGray(b, n)\n    SpaceGray(::Type{T}, b, n)\n\nThis is an n-dimensional Hilbert curve where all `n` dimensions\nmust have `b` bits in size. It was described in the same paper\nand examples as the `Compact` algorithm.\n\"\"\"\nstruct SpaceGray{T} <: HilbertAlgorithm{T}\n    b::Int\n    n::Int\nend\n\n\naxis_type(gg::SpaceGray) = large_enough_unsigned(gg.b)\n\n\nfunction SpaceGray(b, n)\n    ttype = large_enough_unsigned(b * n)\n    SpaceGray{ttype}(b, n)\nend\n\n\nfunction SpaceGray(::Type{T}, b, n) where {T}\n    SpaceGray{T}(b, n)\nend\n\n\nfunction encode_hilbert_zero(g::SpaceGray{T}, X::Vector)::T where {T}\n    hilbert_index_paper(T, g.n, g.b, X)\nend\n\n\nfunction decode_hilbert_zero!(g::SpaceGray{T}, X::Vector, h::T) where {T}\n    hilbert_index_inv_paper!(T, g.n, g.b, h, X)\nend\n\n\n\"\"\"\n    Compact(ms::Vector{Int})\n    Compact(::Type{T}, ms::Vector{Int})\n\nThis algorithm is n-dimensional and permits dimensions to use different\nnumbers of bits, specified in the `ms` vector. The type `T` is an\noptional data type for the Hilbert index. It should be greater than or\nequal to the sum of the bits.\n\nThis algorithm comes from three sources:\n\n* A technical report, \"Compact Hilbert Indices\" by Chris Hamilton.\n  Technical Report CS-2006-07. 6059 University Ave., Halifax, Nova\n  Scotia, B3H 1W5, Canada. This report is informative but has many\n  errors.\n\n* A paper by Hamilton and Rau-Chaplin, \"Compact Hilbert Indices for\n  Multi-Dimensional Data,\" 2007. Nice paper. Also wrong.\n\n* The [libhilbert source code](https://github.com/pdebuyl/libhilbert)\n  is a copy of Hamilton's work and has many corrections. This, ultimately,\n  lead to the working code.\n\"\"\"\nstruct Compact{T} <: HilbertAlgorithm{T}\n    ms::Vector{Int}\n    n::Int\nend\n\n\naxis_type(gg::Compact) = large_enough_unsigned(maximum(gg.ms))\n\n\nfunction Compact(ms::Vector{Int})\n    n = length(ms)\n    b = maximum(ms)\n    ttype = large_enough_unsigned(b * n)\n    Compact{ttype}(ms, n)\nend\n\n\nfunction Compact(::Type{T}, ms::Vector{Int}) where {T}\n    Compact{T}(ms, length(ms))\nend\n\n\nfunction encode_hilbert_zero(g::Compact{T}, X::Vector)::T where {T}\n    coords_to_compact_index(index_type(g), X, g.ms, g.n)\nend\n\n\nfunction decode_hilbert_zero!(g::Compact{T}, X::Vector, h::T) where {T}\n    compact_index_to_coords!(X, g.ms, g.n, h)\nend\n", "meta": {"hexsha": "b40e5fff69360848e9a9874e578c5efb28bf07e1", "size": 11769, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hamilton.jl", "max_stars_repo_name": "adolgert/BijectiveHilbert.jl", "max_stars_repo_head_hexsha": "06a7883802295fa7e50d4ab5f2e69baba9b2b9e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-12-22T02:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T13:03:39.000Z", "max_issues_repo_path": "src/hamilton.jl", "max_issues_repo_name": "adolgert/BijectiveHilbert.jl", "max_issues_repo_head_hexsha": "06a7883802295fa7e50d4ab5f2e69baba9b2b9e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-12-18T02:32:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-02T03:06:56.000Z", "max_forks_repo_path": "src/hamilton.jl", "max_forks_repo_name": "adolgert/BijectiveHilbert.jl", "max_forks_repo_head_hexsha": "06a7883802295fa7e50d4ab5f2e69baba9b2b9e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-12T04:52:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-12T04:52:34.000Z", "avg_line_length": 24.3161157025, "max_line_length": 84, "alphanum_fraction": 0.5425269777, "num_tokens": 3956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.865224072151174, "lm_q1q2_score": 0.7754582579383957}}
{"text": "using DifferentialEquations\nusing Plots\n\n# Parameters\nconst ib = 2e-5; # g⋅m⁻²⋅day⁻¹ immigration rate of bream\nconst ip = 2e-5; # g⋅m⁻²⋅day⁻¹ immigration rate of pike\nconst r = 7.5e-3; # day⁻¹ maximum growth rate of bream\nconst H₁ = 0.5; # half saturation constant\nconst H₂ = 10; # % half saturation constant\nconst H₃ = 20; # g⋅m⁻² half saturation constant\nconst H₄ = 15; # g⋅m⁻² half saturation constant\nconst cb = 7.5e-5; # m⁻²⋅g⁻¹⋅day⁻¹ intraspecific competition constant for bream\nconst cp = 2.75e-4; # m⁻²⋅g⁻¹⋅day⁻¹ intraspecific competition constant for pike\nconst prmax = 5e-2; # day⁻¹ maximum predation rate of pike\nconst ce = 0.1; # pike food conversion efficiency to growth\nconst mp = 2.25e-3; # day⁻¹ mortality rate of pike\nconst K = 100; # % maximum vetetation coverage\n\nfunction scheffer!(du,u,p,t)\n    B, P = u # g⋅m⁻² bream/pike density\n    ib, r, nutr, H₁, H₂, H₃, H₄, cb, prmax, ip, ce, mp, cp, K = p\n\n    V = K*(H₃^2/(H₃^2 + B^2)); # % of lake covered vetetation\n    FR = B^2/(B^2 + H₄^2); # fuctional response of pike\n\n    du[1] = dB = ib + r*(nutr/(nutr + H₁))*B - cb*B^2 - prmax*FR*P\n    du[2] = dP = ip + ce*prmax*FR*P*(V/(V + H₂)) - mp*P - cp*P^2\nend\n\nfunction run_ss_solver(;\n             nutr = 0.5, #nutrient level\n             u0 = [40.0, 2.6], #Initial populations\n             p = [ib, r, nutr, H₁, H₂, H₃, H₄, cb, prmax, ip, ce, mp, cp, K])\n    prob = SteadyStateProblem(scheffer!,u0,p);\n    solve(prob)\nend\n\nequilibria = Set();\nfor i in range(0.0, stop=100.0, length=10)\n    for j in range(0.0, stop=10.0, length=10)\n        for k in [0.5, 1.5, 2.5];\n            eq = run_ss_solver(u0=[i,j], nutr=k);\n            push!(equilibria, (eq[1], eq[2]));\n        end\n    end\nend\n\nfunction dB(B, P)\n    FR = B^2/(B^2 + H₄^2); # fuctional response of pike\n\n    ib + r*(nutr/(nutr + H₁))*B - cb*B^2 - prmax*FR*P\nend\n\nfunction dP(B, P)\n    V = K*(H₃^2/(H₃^2 + B^2)); # % of lake covered vetetation\n    FR = B^2/(B^2 + H₄^2); # fuctional response of pike\n\n    ip + ce*prmax*FR*P*(V/(V + H₂)) - mp*P - cp*P^2\nend\n\nbream = range(0.0, stop=100.0, length=100)\npike = range(0.0, stop=10.0, length=100)\n\nnutr = 2.5;\ncontour(bream, pike, dB, levels=[0], color=:blue, cbar=false, legend=true, label=\"bream'=0, nutr=2.5\");\nnutr = 1.5;\ncontour!(bream, pike, dB, levels=[0], color=:red, cbar=false, label=\"bream'=0, nutr=1.5\");\nnutr = 0.5;\ncontour!(bream, pike, dB, levels=[0], color=:green, cbar=false, label=\"bream'=0, nutr=0.5\");\ncontour!(bream, pike, dP, levels=[0], color=:black, cbar=false, label=\"pike'=0\");\n\neq = collect(equilibria);\nscatter!(first.(eq), last.(eq), label=\"equilibria\");\n\ngui()\n\n", "meta": {"hexsha": "26bd340cb2dd720219792465f7fa320fec598f44", "size": 2611, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scheffer.jl", "max_stars_repo_name": "Libbum/Scheffer1989.jl", "max_stars_repo_head_hexsha": "fd55427847a8aa44e488a0cd00611bafd0f8dfe9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/scheffer.jl", "max_issues_repo_name": "Libbum/Scheffer1989.jl", "max_issues_repo_head_hexsha": "fd55427847a8aa44e488a0cd00611bafd0f8dfe9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scheffer.jl", "max_forks_repo_name": "Libbum/Scheffer1989.jl", "max_forks_repo_head_hexsha": "fd55427847a8aa44e488a0cd00611bafd0f8dfe9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9090909091, "max_line_length": 103, "alphanum_fraction": 0.6112600536, "num_tokens": 1110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7754561668411999}}
{"text": "# Script that executes the Kabsch algorithm to align two paired sets of points\n# by minimising the RMSD between them.\n# Takes 2 .xyz files as input\n# Program executed as\n# 'julia kabsch_optimiser.jl geomP.xyz geomQ.xyz'\n# Darya Shchepanovska\n# 15th July 2019\n\nusing DelimitedFiles\n\nusing LinearAlgebra\nusing Statistics\n\nfunction xyz2matrix(input_xyz)\n    # Imports .xyz file format as data frame, and converts it to an N x 3 Matrix\n    raw_xyz=readdlm(input_xyz)\n    natoms=size(raw_xyz)[1]\n    just_coords=Array{Float64}(raw_xyz[2:natoms,2:4])\n    return just_coords\nend\n\nfunction translate_to_centroid(coord_matrix)\n    # Normalises the molecular coordinates by centering them.\n    center = [mean(coord_matrix[:,1]);mean(coord_matrix[:,2]);mean(coord_matrix[:,3])]\n    centroid = transpose(center)\n    translated_geom = broadcast(-,coord_matrix,centroid)\n    return translated_geom\nend\n\nfunction cross_covariance_matrix(Pmatrix,Qmatrix)\n    # Cross covariance matrix gives measure of variability between two matrices\n    CCmatrix = transpose(Pmatrix) * Qmatrix\n    return CCmatrix\nend\n\nfunction optimal_rotation_matrix(CCmatrix)\n    # Returns 3x3 matrix that can be applied to P to get Q\n    ORmatrix = sqrt(transpose(CCmatrix)*CCmatrix)*inv(CCmatrix)\n    return ORmatrix\nend\n\nPgeom = xyz2matrix(ARGS[1])\nQgeom = xyz2matrix(ARGS[2])\n\nnormalisedP = (translate_to_centroid(Pgeom))\nnormalisedQ = (translate_to_centroid(Qgeom))\n\nxcov = cross_covariance_matrix(normalisedP,normalisedQ)\norot = optimal_rotation_matrix(xcov)\n\nnum_atoms = size(normalisedP)[1]\nrotated = zeros(Float64,num_atoms,3)\n\nfor i=1:num_atoms\n    rotated[i,:] = orot*normalisedP[i,:]\nend\n\n# display(rotated)\n\nRMSD_value = norm(rotated-normalisedQ)\n\nprintln(\"RMSD between these two structures is \",RMSD_value)\n\n\n", "meta": {"hexsha": "d1a4c55164b262d0da1da5f37ab0e23c4ad6ce88", "size": 1778, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "kabsch.jl", "max_stars_repo_name": "dasha-shchep/kabsch", "max_stars_repo_head_hexsha": "9f2b0c15b73440641b62dcb0975056bdb10f7288", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-27T16:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T16:16:43.000Z", "max_issues_repo_path": "kabsch.jl", "max_issues_repo_name": "dasha-shchep/kabsch", "max_issues_repo_head_hexsha": "9f2b0c15b73440641b62dcb0975056bdb10f7288", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kabsch.jl", "max_forks_repo_name": "dasha-shchep/kabsch", "max_forks_repo_head_hexsha": "9f2b0c15b73440641b62dcb0975056bdb10f7288", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3538461538, "max_line_length": 86, "alphanum_fraction": 0.7643419573, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.775456166436526}}
{"text": "\"\"\"\n    eig2length(λ, D)\n\nConvert Laplace eigenvalue to length scale.\n\"\"\"\neig2length(λ, D) = λ > 0 ? π * √(D / λ) : Inf\n\n\"\"\"\n    length2eig(length, D)\n\nConvert length scale to Laplace eigenvalue.\n\"\"\"\nlength2eig(length, D) = D * (π / length)^2\n", "meta": {"hexsha": "bd1ff04aec63bb01f2d408a9c058de6e13af3a48", "size": 243, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix_formalism/eig2length.jl", "max_stars_repo_name": "fachra/SpinDoctor.jl", "max_stars_repo_head_hexsha": "25c633fb8020843728c1004c492a7c33b2fe2e4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2022-03-19T12:53:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:39:38.000Z", "max_issues_repo_path": "src/matrix_formalism/eig2length.jl", "max_issues_repo_name": "fachra/SpinDoctor.jl", "max_issues_repo_head_hexsha": "25c633fb8020843728c1004c492a7c33b2fe2e4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2022-03-13T19:49:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T14:58:15.000Z", "max_forks_repo_path": "src/matrix_formalism/eig2length.jl", "max_forks_repo_name": "fachra/SpinDoctor.jl", "max_forks_repo_head_hexsha": "25c633fb8020843728c1004c492a7c33b2fe2e4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-11T09:54:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T11:10:57.000Z", "avg_line_length": 17.3571428571, "max_line_length": 45, "alphanum_fraction": 0.6131687243, "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7754561639314179}}
{"text": "function isHappy(s)::Bool\n    a::Int = s isa Number ? s : (try\n                                 parse(Int64, s)\n                                 catch e\n                                 throw(error(\"Wrong type $e\"))\n                                 end)\n    innerHappy(a, Set([]))\nend\n\nfunction eachBit(n::Int)\n    result = []\n    while n != 0\n        let left = n % 10\n            push!(result, left)\n            n = Int((n-left)/10)\n        end\n    end\n    result\nend\n\nfunction innerHappy(n,se)\n    n in se && return false\n    next = sum(eachBit(n) .^ 2)\n    next == 1 ? (return true) : (se = union(se, n))\n    innerHappy(next,se)\nend\n", "meta": {"hexsha": "e5fa6b30e71d1b7c7ac4af1c03564843c34468a7", "size": 637, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Happy-Number/HN.jl", "max_stars_repo_name": "ccqpein/Arithmetic-Exercises", "max_stars_repo_head_hexsha": "748d7ac1313892d47eb0a66a0b7705e6d33b43ad", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-07-11T03:07:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T06:46:10.000Z", "max_issues_repo_path": "Happy-Number/HN.jl", "max_issues_repo_name": "ccqpein/Arithmetic-Exercises", "max_issues_repo_head_hexsha": "748d7ac1313892d47eb0a66a0b7705e6d33b43ad", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Happy-Number/HN.jl", "max_forks_repo_name": "ccqpein/Arithmetic-Exercises", "max_forks_repo_head_hexsha": "748d7ac1313892d47eb0a66a0b7705e6d33b43ad", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-12-06T22:19:33.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T22:19:33.000Z", "avg_line_length": 23.5925925926, "max_line_length": 62, "alphanum_fraction": 0.4301412873, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7754561635074778}}
{"text": "module BayesianRegression\n\n#=\n\n### Model and prior\n\nAssume a linear model\n$$\nf(\\mathbf{x}) = \\sum_{i=1}^M c_i \\phi_i(\\mathbf{x}) = \\mathbf{c}^T \\boldsymbol{\\phi}(\\mathbf{x} )\n$$\nwhere the elements of the $M$-dimensional coefficient vector have independent priors $p(c_i)=\\mathcal{N}(c_i | 0,\\sigma_i^2)$. Suppose $N$ noisy input-target pairs are available, $\\{\\mathbf{x}_i, y_i\\}_{i=1}^N$, such that\n$$\ny_i = f(\\mathbf{x}_i) + \\epsilon_i, \n$$\nwith noise prior $p(\\epsilon_i) = \\mathcal{N}(\\epsilon_i | 0,\\sigma_\\epsilon^2)$.\n\n### Posterior\n\nFor fixed values of $\\{\\sigma_i^2\\}_{i=1}^M$ and $\\sigma_\\epsilon^2$, the posterior mean used for predictions is\n$$\n\\boldsymbol{\\mu}_c = \\sigma_\\epsilon^{-2} \\boldsymbol{\\Sigma}_c \\boldsymbol{\\Phi}^T \\mathbf{y}\n$$\nwith associated covariance\n$$\n\\begin{aligned}\n\\boldsymbol{\\Sigma}_c\n&= \\left[ \\sigma_\\epsilon^{-2} \\boldsymbol{\\Phi}^T \\boldsymbol{\\Phi} + \\boldsymbol{\\Sigma}_0^{-1} \\right]^{-1} \\\\\n&= \\boldsymbol{\\Sigma}_0 - \\boldsymbol{\\Sigma}_0 \\boldsymbol{\\Phi}^T \\boldsymbol{\\Sigma}_y^{-1} \\boldsymbol{\\Phi} \\boldsymbol{\\Sigma}_0\n\\end{aligned} ,\n$$\nwhere $\\boldsymbol{\\Phi}$ is the design matrix \n$$\n\\boldsymbol{\\Phi} = \\left[\n\\begin{matrix}\n\\text{---} \\boldsymbol{\\phi}(\\mathbf{x}_1) \\text{---} \\\\\n\\text{---} \\boldsymbol{\\phi}(\\mathbf{x}_2) \\text{---} \\\\\n\\vdots \\\\\n\\text{---} \\boldsymbol{\\phi}(\\mathbf{x}_3) \\text{---}\n\\end{matrix}\n\\right] ,\n$$\n$\\boldsymbol{\\Sigma}_0$ is diagonal with $[\\boldsymbol{\\Sigma}_0]_{ii} = \\sigma_i^2$, and $\\boldsymbol{\\Sigma}_y$ is defined below.\n\n### Likelihood and log likelihood\n\nWith flat hyperpriors, the marginal likelihood---the \"evidence\" for the model---is\n$$\np(\\mathbf{y} | \\boldsymbol{\\Sigma}_0, \\sigma_\\epsilon^2) = \\mathcal{N}(\\mathbf{y} | \\mathbf{0}, \\boldsymbol{\\Sigma}_y)\n$$\nwith\n$$\n\\begin{aligned}\n\\boldsymbol{\\Sigma}_y\n&= \\boldsymbol{\\Phi} \\boldsymbol{\\Sigma}_0 \\boldsymbol{\\Phi}^T + \\sigma_\\epsilon^2 \\mathbf{I} \\\\\n&= \\left[ \\sigma_\\epsilon^{-2} \\mathbf{I} - \\sigma_\\epsilon^{-2} \\boldsymbol{\\Phi} \\boldsymbol{\\Sigma}_c \\boldsymbol{\\Phi}^T \\sigma_\\epsilon^{-2}  \\right]^{-1}\n\\end{aligned}\n$$\nWhen maximizing this quantity, one typically works with its log,\n$$\n\\begin{aligned}\n\\mathrm{\\mathcal{L}}\n&= \\ln p(\\mathbf{y} | \\boldsymbol{\\Sigma}_0, \\sigma_\\epsilon^2) \\\\\n&= -\\frac{1}{2} \\mathbf{y}^T \\boldsymbol{\\Sigma}_y^{-1} \\mathbf{y}\n    - \\frac{1}{2} \\ln \\left| \\boldsymbol{\\Sigma}_y \\right| \n    - \\frac{N}{2} \\ln (2\\pi) \\\\\n&= -\\frac{1}{2} \\sigma_\\epsilon^{-2} \\mathbf{y}^T \\left[  \\mathbf{y} - \\boldsymbol{\\Phi} \\boldsymbol{\\mu}_c \\right]\n    + \\frac{1}{2} \\ln \\left| \\boldsymbol{\\Sigma}_c \\right|\n    - \\frac{1}{2} \\ln \\left| \\boldsymbol{\\Sigma}_0 \\right|\n    - \\frac{N}{2} \\ln (\\sigma_\\epsilon^2)\n    - \\frac{N}{2} \\ln (2\\pi) \\\\\n\\end{aligned} .\n$$\nThe relevant derivatives with respect to the hyperparameters are\n$$\n\\begin{aligned}\n\\frac{\\partial \\mathcal{L}}{\\partial \\sigma_i^2}\n&= \\frac{1}{2} [\\boldsymbol{\\Phi}^T \\boldsymbol{\\Sigma}_y^{-1} \\mathbf{y}]_i^2\n    - \\frac{1}{2} [\\boldsymbol{\\Phi}^T \\boldsymbol{\\Sigma}_y^{-1} \\boldsymbol{\\Phi}]_{ii} \\\\\n&= \\frac{1}{2} \\sigma_i^{-4} \\left[ \\mu_i^2 + [\\boldsymbol{\\Sigma}_c]_{ii} - \\sigma_i^2 \\right]\n\\end{aligned}\n$$\nand\n$$\n\\begin{aligned}\n\\frac{\\partial \\mathcal{L}}{\\partial \\sigma_\\epsilon^2}\n& = \\frac{1}{2} \\left\\| \\boldsymbol{\\Sigma}_y^{-1} \\mathbf{y} \\right\\|^2 - \\frac{1}{2} \\mathrm{tr}\\left(\\boldsymbol{\\Sigma}_y^{-1}\\right) \\\\\n&= \\frac{1}{2} \\sigma_\\epsilon^{-4} \\left[ \n    \\left\\| \\mathbf{y} - \\boldsymbol{\\Phi} \\boldsymbol{\\mu}_c \\right\\|^2\n    + \\mathrm{tr}\\left( \\boldsymbol{\\Phi} \\boldsymbol{\\Sigma}_c \\boldsymbol{\\Phi}^T \\right) \n    - N \\sigma_\\epsilon^2\n\\right]\n\\end{aligned} .\n$$\n\n### References\n\n* M. E. Tipping, \"Sparse Bayesian learning and the relevance vector machine,\" Journal of Machine Learning Research 1, 211 (2001)\n* C. K. Williams and C. E. Rasmussen, _Gaussian Processes for Machine Learning_, MIT Press (2006)\n\n=#\n\nusing LinearAlgebra\nusing Optim\n\nfunction solve(\n    y::Vector{<:AbstractFloat},\n    X::Matrix{<:AbstractFloat},\n    var_c::AbstractFloat,\n    var_e::AbstractFloat,\n)\n    return solve(y, X, var_c*ones(size(X,2)), var_e)\nend\n\nfunction solve(\n    y::Vector{<:AbstractFloat},\n    X::Matrix{<:AbstractFloat},\n    var_c::Vector{<:AbstractFloat},\n    var_e::AbstractFloat,\n)\n    M = size(X,2)\n    XTX = X'*X\n    Σ_c = Array{Float64}(undef,M,M)\n    BLAS.blascopy!(length(Σ_c), XTX, stride(XTX,1), Σ_c, stride(Σ_c,1))\n    BLAS.scal!(1.0/var_e, Σ_c)\n    for i in 1:M; Σ_c[i,i] += 1.0/var_c[i]; end\n    C = cholesky!(Symmetric(Σ_c))\n    return 1.0/var_e*(C \\ (X'*y))\nend\n\nfunction log_marginal_likelihood_overdetermined!(\n    lml::AbstractFloat,\n    grad::Vector{<:AbstractFloat},\n    X::Matrix{<:AbstractFloat},\n    y::Vector{<:AbstractFloat},\n    var_c::AbstractFloat,\n    var_e::AbstractFloat,\n    XTX::Matrix{<:AbstractFloat},\n)\n    var_c_vec = var_c*ones(size(X,2))\n    grad_vec = zeros(size(X,2)+1)\n    lml = log_marginal_likelihood_overdetermined!(lml, grad_vec, X, y, var_c_vec, var_e, XTX)\n    grad[1] = sum(grad_vec[1:end-1])\n    grad[2] = grad_vec[end]\n    return lml\nend\n\nfunction log_marginal_likelihood_overdetermined!(\n    lml::AbstractFloat,\n    grad::Vector{<:AbstractFloat},\n    X::Matrix{<:AbstractFloat},\n    y::Vector{<:AbstractFloat},\n    var_c::Vector{<:AbstractFloat},\n    var_e::AbstractFloat,\n    XTX::Matrix{<:AbstractFloat},\n)\n    N = size(X,1)\n    M = size(X,2)\n    Σ_c = Array{Float64}(undef,M,M)\n    BLAS.blascopy!(length(Σ_c), XTX, stride(XTX,1), Σ_c, stride(Σ_c,1))\n    BLAS.scal!(1.0/var_e, Σ_c)\n    for i in 1:M; Σ_c[i,i] += 1.0/var_c[i]; end\n    C = cholesky!(Symmetric(Σ_c))\n    Σ_c = C \\ I(M)\n    μ_c = 1.0/var_e*(C \\ (X'*y))\n    lml = - 0.5*logdet(C) - 0.5*sum(log.(var_c)) - 0.5*N*log(var_e) - 0.5*N*log(2*π)\n    lml -= 0.5/var_e*y'*(y-X*μ_c)\n    grad[1:M] .= 0.5*(μ_c.^2 .+ diag(Σ_c) .- var_c)./var_c.^2\n    grad[M+1] = 0.5/var_e^2*(sum((y-X*μ_c).^2) + dot(XTX,Σ_c) - N*var_e)\n    return lml\nend\n\nfunction log_marginal_likelihood_underdetermined!(\n    lml::AbstractFloat,\n    grad::Vector{<:AbstractFloat},\n    X::Matrix{<:AbstractFloat},\n    y::Vector{<:AbstractFloat},\n    var_c::AbstractFloat,\n    var_e::AbstractFloat,\n)\n    var_c_vec = var_c*ones(size(X,2))\n    grad_vec = zeros(size(X,2)+1)\n    lml = log_marginal_likelihood_underdetermined!(lml, grad_vec, X, y, var_c_vec, var_e)\n    grad[1] = sum(grad_vec[1:end-1])\n    grad[2] = grad_vec[end]\n    return lml\nend\n\nfunction log_marginal_likelihood_underdetermined!(\n    lml::AbstractFloat,\n    grad::Vector{<:AbstractFloat},\n    X::Matrix{<:AbstractFloat},\n    y::Vector{<:AbstractFloat},\n    var_c::Vector{<:AbstractFloat},\n    var_e::AbstractFloat,\n)\n    N = size(X,1)\n    M = size(X,2)\n    Σ_y = X*Diagonal(var_c)*X'\n    for i=1:N; Σ_y[i,i] += var_e; end\n    C = cholesky!(Symmetric(Σ_y))\n    invΣy_y = C \\ y\n    lml = -0.5*y'*invΣy_y - 0.5*logdet(C) - 0.5*N*log(2*π)\n    grad[1:M] .= 0.5*(X'*invΣy_y).^2\n    W = C \\ X\n    @views for i=1:M; grad[i] -= 0.5*dot(X[:,i], W[:,i]); end\n    grad[M+1] = 0.5*dot(invΣy_y,invΣy_y) - 0.5*tr(C\\I(N))\n    return lml\nend\n\nfunction bayesian_fit(\n    y::Vector{<:AbstractFloat},\n    X::Matrix{<:AbstractFloat};\n    variance_floor::AbstractFloat=1e-8,\n    verbose::Bool=false,\n)\n    if size(X,1) > size(X,2)\n        XTX = X'*X  # advantageous to precompute for overdetermined case\n    end\n\n    function fg!(f, g, x)\n        var_c = variance_floor + x[1]*x[1]\n        var_e = variance_floor + x[2]*x[2]\n        if size(X,1) >= size(X,2)\n            f = log_marginal_likelihood_overdetermined!(f, g, X, y, var_c, var_e, XTX)\n        else\n            f = log_marginal_likelihood_underdetermined!(f, g, X, y, var_c, var_e)\n        end\n        if f != nothing\n            f = -f\n        end\n        if g != nothing\n            g .*= -2*x\n        end\n        return f\n    end\n\n    res = optimize(Optim.only_fg!(fg!),\n                   ones(2),\n                   Optim.LBFGS(),\n                   Optim.Options(x_tol=1e-4, g_tol=0.0, show_trace=verbose))\n    verbose && println(res)\n\n    lml = -Optim.minimum(res)\n    var_c, var_e = Optim.minimizer(res)\n    var_c = variance_floor + var_c*var_c\n    var_e = variance_floor + var_e*var_e\n\n    return solve(y, X, var_c, var_e), var_c, var_e, lml\nend\n\nfunction ard_fit(\n    y::Vector{<:AbstractFloat},\n    X::Matrix{<:AbstractFloat},\n    variance_floor::AbstractFloat=1e-8;\n    verbose::Bool=false,\n)\n    if size(X,1) >= size(X,2)\n        XTX = X'*X  # advantageous to precompute for overdetermined case\n    end\n\n    function fg!(f, g, x)\n        var_c = variance_floor .+ x[1:end-1].*x[1:end-1]\n        var_e = variance_floor + x[end]*x[end]\n        if size(X,1) >= size(X,2)\n            f = log_marginal_likelihood_overdetermined!(f, g, X, y, var_c, var_e, XTX)\n        else\n            f = log_marginal_likelihood_underdetermined!(f, g, X, y, var_c, var_e)\n        end\n        if f != nothing\n            f = -f\n        end\n        if g != nothing\n            g .*= -2*x\n        end\n        return f\n    end\n\n    res = optimize(Optim.only_fg!(fg!),\n                   ones(size(X,2)+1),\n                   Optim.LBFGS(),\n                   Optim.Options(x_tol=1e-4, g_tol=0.0, show_trace=verbose))\n    verbose && println(res)\n\n    lml = -Optim.minimum(res)\n    x = Optim.minimizer(res)\n    var_c = variance_floor .+ x[1:end-1].*x[1:end-1]\n    var_e = variance_floor + x[end]*x[end]\n\n    mask = var_c .> 10*variance_floor\n    var_c[.~mask] .= 0\n    c_mask = solve(y, X[:,mask], var_c[mask], var_e)\n    c = zeros(length(var_c))\n    c[mask] .= c_mask\n\n    return c, var_c, var_e, lml, mask\nend\n\nend\n", "meta": {"hexsha": "4dc1a0cfc634cd887cd5ca36b22e33b8f7e505a3", "size": 9558, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bayesianlinear.jl", "max_stars_repo_name": "ACEsuit/ACEfit.jl", "max_stars_repo_head_hexsha": "cb546aacc4d0c96cbcb14d06b46ff708069c3440", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-15T10:24:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T10:24:40.000Z", "max_issues_repo_path": "src/bayesianlinear.jl", "max_issues_repo_name": "ACEsuit/ACEfit.jl", "max_issues_repo_head_hexsha": "cb546aacc4d0c96cbcb14d06b46ff708069c3440", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2022-01-01T16:49:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:00:47.000Z", "max_forks_repo_path": "src/bayesianlinear.jl", "max_forks_repo_name": "ACEsuit/ACEfit.jl", "max_forks_repo_head_hexsha": "cb546aacc4d0c96cbcb14d06b46ff708069c3440", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-25T17:24:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T17:24:28.000Z", "avg_line_length": 31.9665551839, "max_line_length": 221, "alphanum_fraction": 0.6113203599, "num_tokens": 3443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7754561601930219}}
{"text": "#############################################################################\n#############################################################################\n#\n# This file implements polynomial division \n#                                                                               \n#############################################################################\n#############################################################################\n\n\"\"\"  Modular algorithm.\nf divide by g\n\nf = q*g + r\n\np is a prime\n\"\"\"\nfunction divide(num::PolynomialModP, den::PolynomialModP)\n    @assert num.prime == den.prime \"Both polynomials must share the same prime divisor\"\n    f, g = mod(num.terms,num.prime), mod(den.terms,den.prime)\n    degree(f) < degree(num.terms) && return nothing \n    iszero(g) && throw(DivideError())\n    q = Polynomial()\n    prev_degree = degree(f)\n    while degree(f) ≥ degree(g) \n        h = Polynomial( (leading(f) ÷ leading(g))(num.prime) )  #syzergy \n        f = mod((f - h*g), num.prime)\n        q = mod((q + h), num.prime)  \n        prev_degree == degree(f) && break\n        prev_degree = degree(f)\n    end\n    @assert iszero( mod((num.terms  - (q*g + f)),num.prime))\n    return q, f\nend\n\n\"\"\"\nThe quotient from polynomial division. Returns a function of an integer.\n\"\"\"\n\n÷(num::PolynomialModP, den::PolynomialModP)  = first(divide(num,den))\n\n\"\"\"\nThe remainder from polynomial division. Returns a function of an integer.\n\"\"\"\n\nrem(num::PolynomialModP, den::PolynomialModP)  = last(divide(num,den))", "meta": {"hexsha": "95283ee189363074b27d64268d29d35ac9a54f91", "size": 1510, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basic_polynomial_operations/polynomial_division.jl", "max_stars_repo_name": "ILikeTheCodespace/William-Idoine-2504-2021-PROJECT1", "max_stars_repo_head_hexsha": "2c1cf923b17dd97c91e80baab58890bfd33fc987", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basic_polynomial_operations/polynomial_division.jl", "max_issues_repo_name": "ILikeTheCodespace/William-Idoine-2504-2021-PROJECT1", "max_issues_repo_head_hexsha": "2c1cf923b17dd97c91e80baab58890bfd33fc987", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basic_polynomial_operations/polynomial_division.jl", "max_forks_repo_name": "ILikeTheCodespace/William-Idoine-2504-2021-PROJECT1", "max_forks_repo_head_hexsha": "2c1cf923b17dd97c91e80baab58890bfd33fc987", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-23T22:26:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T22:26:51.000Z", "avg_line_length": 34.3181818182, "max_line_length": 87, "alphanum_fraction": 0.4754966887, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012640659995, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7754561597498154}}
{"text": "#' ---\r\n#' title: Finance\r\n#' ---\r\n\r\n#' **Originally Contributed by**: Arpit Bhatia\r\n\r\n#' Optimization models play an increasingly important role in financial decisions.\r\n#' Many computational finance problems can be solved efficiently using modern optimization techniques.\r\n#' In this tutorial we will discuss 3 such examples.\r\n#' The first two are taken from the book Optimization Methods in Finance[[1]](#c1),\r\n#' while the third is the famous Markowitz Portfolio Optimization problem with data from\r\n#' lecture notes from a course taught at Georgia Tech[[2]](#c2).\r\n\r\nusing JuMP\r\nusing GLPK\r\n\r\n#' ## Short Term Financing\r\n\r\n#' Corporations routinely face the problem of financing short term cash commitments such as the following:\r\n\r\n#' **Month**        |Jan    |Feb    |Mar    |Apr    |May    |Jun\r\n#' :-----:          |:-----:|:-----:|:-----:|:-----:|:-----:|:-----:\r\n#' **Net Cash Flow**|-150   |-100   |200    |-200   |50     |300\r\n\r\n#' Net cash flow requirements are given in thousands of dollars. The company has the following sources of funds:\r\n\r\n#' - A line of credit of up to $100K at an interest rate of 1% per month,\r\n#' - In any one of the first three months, it can issue 90-day commercial paper bearing a total interest of 2% for the 3-month period,\r\n#' - Excess funds can be invested at an interest rate of 0.3% per month.\r\n\r\n#' Our task is to find out the most economical way to use these 3 sources such that\r\n#' we end up with the most amount of money at the end of June.\r\n#' We model this problem in the following manner:\r\n\r\n#' We will use the following decision variables:\r\n#' - the amount $u_{i}$ drawn from the line of credit in month $i$\r\n#' - the amount $v_{i}$ of commercial paper issued in month $i$\r\n#' - the excess funds $w_{i}$ in month $i$\r\n\r\n#' Here we have three types of constraints:\r\n#' 1. for every month, cash inflow = cash outflow for each month\r\n#' 2. upper bounds on $u_{i}$\r\n#' 3. nonnegativity of the decision variables $u_{i}$, $v_{i}$ and $w_{i}$.\r\n\r\n#' Our objective will be to simply maximimse the company's wealth in June, which say we represent with the variable $m$.\r\n\r\nfinancing = Model(GLPK.Optimizer)\r\n\r\n@variables(financing, begin\r\n    0 <= u[1:5] <= 100\r\n    0 <= v[1:3]\r\n    0 <= w[1:5]\r\n    m\r\nend)\r\n\r\n@objective(financing, Max, m) # Money at the end of June\r\n\r\n@constraints(financing, begin\r\n    u[1] + v[1] - w[1] == 150 # January\r\n    u[2] + v[2] - w[2] - 1.01u[1] + 1.003w[1] == 100 # February\r\n    u[3] + v[3] - w[3] - 1.01u[2] + 1.003w[2] == -200 # March\r\n    u[4] - w[4] - 1.02v[1] - 1.01u[3] + 1.003w[3] == 200 # April\r\n    u[5] - w[5] - 1.02v[2] - 1.01u[4] + 1.003w[4] == -50 # May\r\n    -m - 1.02v[3] - 1.01u[5] + 1.003w[5] == -300 # June\r\nend)\r\n\r\noptimize!(financing)\r\n@show objective_value(financing);\r\n\r\n#' ## Combinatorial Auctions\r\n#' In many auctions, the value that a bidder has for a set of items may not be\r\n#' the sum of the values that he has for individual items.\r\n#' It may be more or it may be less.\r\n#' Examples are equity trading, electricity markets, pollution right auctions and auctions for airport landing slots.\r\n#' To take this into account, combinatorial auctions allow the bidders to submit bids on combinations of items.\r\n\r\n#' Let $M=\\{1,2, \\ldots, m\\}$ be the set of items that the auctioneer has to sell.\r\n#' A bid is a pair $B_{j}=\\left(S_{j}, p_{j}\\right)$ where $S_{j} \\subseteq M$ is a nonempty set of items and\r\n#' $p_{j}$ is the price offer for this set.\r\n#' Suppose that the auctioneer has received $n$ bids $B_{1}, B_{2}, \\ldots, B_{n} .$\r\n#' The goal of this problem is to help an auctioneer determine the winners in order to maximize his revenue.\r\n\r\n#' We model this problem by taking a decision variable $y_{j}$ for every bid.\r\n#' We add a constraint that each item $i$ is sold at most once. This gives us the following model:\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' \\max && \\sum_{i=1}^{n} p_{j} y_{j} \\\\\r\n#' \\text { s.t. }  && \\sum_{j : i \\in S_{j}} y_{j} \\leq 1 && \\forall i=\\{1,2 \\ldots m\\} \\\\\r\n#' && y_{j} \\in\\{0,1\\} && \\forall j \\in\\{1,2 \\ldots n\\}\r\n#' \\end{align*}\r\n#' $$\r\n\r\nbid_values = [6 3 12 12 8 16]\r\nbid_items = [[1], [2], [3 4], [1 3], [2 4], [1 3 4]]\r\n\r\nauction = Model(GLPK.Optimizer)\r\n@variable(auction, y[1:6], Bin)\r\n@objective(auction, Max, sum(y' .* bid_values))\r\nfor i in 1:6\r\n    @constraint(auction, sum(y[j] for j in 1:6 if i in bid_items[j]) <= 1)\r\nend\r\n\r\noptimize!(auction)\r\n\r\n@show objective_value(auction);\r\n@show value.(y);\r\n\r\n#' ## Portfolio Optimization\r\n#' Suppose we are considering investing 1000 dollars in three non-dividend paying stocks,\r\n#' IBM (IBM), Walmart (WMT), and Southern Electric (SEHI), for a onemonth period.\r\n#' This means we will use the money to buy shares of the three stocks at the current market prices,\r\n#' hold these for one month, and sell the shares off at the prevailing market prices at the end of the month.\r\n#' As a rational investor, we hope to make some profit out of this endeavor, i.e.,\r\n#' the return on our investment should be positive.\r\n#' Suppose we bought a stock at $p$ dollars per share in the beginning of the month,\r\n#' and sold it off at $s$ dollars per share at the end of the month.\r\n#' Then the one-month return on a share of the stock is $ \\frac{s-p}{p} $.\r\n\r\n#' Since the stock prices are quite uncertain, so is the end-of-month return on our investment.\r\n#' Our goal is to invest in such a way that the expected end-of-month return is at least $50.00 or 5%.\r\n#' Furthermore, we want to make sure that the “risk” of not achieving our desired return is minimum.\r\n\r\n#' Note that we are solving the problem under the following assumptions:\r\n#' 1. We can trade any continuum of shares.\r\n#' 2. No short-selling is allowed.\r\n#' 3. There are no transaction costs.\r\n\r\n#' We model this problem by taking decision variables $x_{i}, i=1,2,3,$ denoting the dollars invested in each of the 3 stocks.\r\n#' Let us denote by $\\tilde{r}_{i}$ the random variable corresponding to the monthly return\r\n#' (increase in the stock price) per dollar for stock $i .$\r\n\r\n#' Then, the return (or profit) on $x_{i}$ dollars invested in stock $i$ is $\\tilde{r}_{i} x_{i},$ and\r\n#' the total (random) return on our investment is $\\sum_{i=1}^{3} \\tilde{r}_{i} x_{i} .$\r\n#' The expected return on our investment is then\r\n#' $\\mathbb{E}\\left[\\sum_{i=1}^{3} \\tilde{r}_{i} x_{i}\\right]=\\sum_{i=1}^{3} \\overline{r}_{i} x_{i},$\r\n#' where $\\overline{r}_{i}$ is the expected value of the $\\tilde{r}_{i} .$\r\n\r\n#' Now we need to quantify the notion of “risk” in our investment.\r\n#' Markowitz, in his Nobel prize winning work, showed that a rational investor’s notion of minimizing risk\r\n#' can be closely approximated by minimizing the variance of the return of the investment portfolio.\r\n#' This variance is given by:\r\n\r\n#' $$\r\n#' \\operatorname{Var}\\left[\\sum_{i=1}^{3} \\tilde{r}_{i} x_{i}\\right] = \\sum_{i=1}^{3} \\sum_{j=1}^{3} x_{i} x_{j} \\sigma_{i j}\r\n#' $$\r\n\r\n#' where $\\sigma_{i j}$ is the covariance of the return of stock $i$ with stock $j$.\r\n\r\n#' Note that the right hand side of the equation is the most reduced form of the expression and\r\n#' we have not shown the intermediate steps involved in getting to this form.\r\n#' We can also write this equation as:\r\n\r\n#' $$\r\n#' \\operatorname{Var}\\left[\\sum_{i=1}^{3} \\tilde{r}_{i} x_{i}\\right] =x^{T} Q x\r\n#' $$\r\n\r\n#' Where $Q$ is the covariance matrix for the random vector $\\tilde{r}$.\r\n\r\n#' Finally, we can write the model as:\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' \\min x^{T} Q x \\\\\r\n#' \\text { s.t. } \\sum_{i=1}^{3} x_{i} \\leq 1000.00 \\\\\r\n#' \\overline{r}^{T} x \\geq 50.00 \\\\\r\n#' x \\geq 0\r\n#' \\end{align*}\r\n#' $$\r\n\r\n#' After that long discussion, lets now use JuMP to solve the portfolio optimization problem for the data given below.\r\n\r\n#' | Month        |  IBM     |  WMT    |  SEHI  |\r\n#' |--------------|----------|---------|--------|\r\n#' | November-00  |  93.043  |  51.826 |  1.063 |\r\n#' | December-00  |  84.585  |  52.823 |  0.938 |\r\n#' | January-01   |  111.453 |  56.477 |  1.000 |\r\n#' | February-01  |  99.525  |  49.805 |  0.938 |\r\n#' | March-01     |  95.819  |  50.287 |  1.438 |\r\n#' | April-01     |  114.708 |  51.521 |  1.700 |\r\n#' | May-01       |  111.515 |  51.531 |  2.540 |\r\n#' | June-01      |  113.211 |  48.664 |  2.390 |\r\n#' | July-01      |  104.942 |  55.744 |  3.120 |\r\n#' | August-01    |  99.827  |  47.916 |  2.980 |\r\n#' | September-01 |  91.607  |  49.438 |  1.900 |\r\n#' | October-01   |  107.937 |  51.336 |  1.750 |\r\n#' | November-01  |  115.590 |  55.081 |  1.800 |\r\n\r\n\r\nusing Statistics # Useful for calculations\r\nusing Ipopt      # Ipopt since our objective is quadratic\r\n\r\nstock_data = [\r\n93.043 51.826 1.063;\r\n84.585 52.823 0.938;\r\n111.453 56.477 1.000;\r\n99.525 49.805 0.938;\r\n95.819 50.287 1.438;\r\n114.708 51.521 1.700;\r\n111.515 51.531 2.540;\r\n113.211 48.664 2.390;\r\n104.942 55.744 3.120;\r\n99.827 47.916 2.980;\r\n91.607 49.438 1.900;\r\n107.937 51.336 1.750;\r\n115.590 55.081 1.800;\r\n]\r\n\r\n# Calculating stock returns\r\n\r\nstock_returns = Array{Float64}(undef, 12, 3)\r\n\r\nfor i in 1:12\r\n    stock_returns[i, :] = (stock_data[i + 1, :] .- stock_data[i, :]) ./ stock_data[i, :]\r\nend\r\n\r\n# Calculating the expected value of monthly return\r\n\r\nr = [Statistics.mean(stock_returns[:,1]) Statistics.mean(stock_returns[:,2]) Statistics.mean(stock_returns[:,3])]'\r\n\r\n# Calculating the covariance matrix Q\r\n\r\nQ = Statistics.cov(stock_returns)\r\n\r\n#+\r\n\r\n# JuMP Model\r\n\r\nportfolio = Model(optimizer_with_attributes(Ipopt.Optimizer, \"print_level\" => 0))\r\n@variable(portfolio, x[1:3] >= 0)\r\n@objective(portfolio, Min, x' * Q * x)\r\n@constraint(portfolio, sum(x) <= 1000)\r\n@constraint(portfolio, sum(r .* x) >= 50)\r\n\r\noptimize!(portfolio)\r\n\r\n@show objective_value(portfolio);\r\n@show value.(x);\r\n\r\n#' ### References\r\n#' <a id='c1'></a>\r\n#' 1. Cornuéjols, G., Peña, J., & Tütüncü, R. (2018). <i>Optimization Methods in Finance</i>. Cambridge: Cambridge University Press. doi:10.1017/9781107297340\r\n#' <a id='c2'></a>\r\n#' 2. Ahmed, S. ISyE6669: Deterministic Optimization. Available at: https://www2.isye.gatech.edu/~sahmed/isye6669/\r\n", "meta": {"hexsha": "b99f9a7b5edbf70ad7c2311682312a89226c6e92", "size": 10034, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/modelling/finance.jl", "max_stars_repo_name": "mtanneau/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 75, "max_stars_repo_stars_event_min_datetime": "2020-06-15T13:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T12:58:48.000Z", "max_issues_repo_path": "script/modelling/finance.jl", "max_issues_repo_name": "mtanneau/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-05-27T05:36:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T09:52:29.000Z", "max_forks_repo_path": "script/modelling/finance.jl", "max_forks_repo_name": "mtanneau/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-10-09T09:32:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T17:41:21.000Z", "avg_line_length": 40.9551020408, "max_line_length": 159, "alphanum_fraction": 0.6370340841, "num_tokens": 3194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7754561556067459}}
{"text": "#=\nThe number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property.\n\nLet d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following:\n\nd2d3d4=406 is divisible by 2\nd3d4d5=063 is divisible by 3\nd4d5d6=635 is divisible by 5\nd5d6d7=357 is divisible by 7\nd6d7d8=572 is divisible by 11\nd7d8d9=728 is divisible by 13\nd8d9d10=289 is divisible by 17\nFind the sum of all 0 to 9 pandigital numbers with this property.\n=#\ninclude(\"projecteulerutils.jl\")\nusing Combinatorics\n\nfunction calc()\n  sum = 0\n  for n in permutations(collect(0:9))\n    if n[1] != 0\n      isvalid = true\n      y = [2,3,5,7,11,13,17]\n      for x in collect(2:8)\n        if nd(n[x:x+2]) % y[x-1] != 0\n          isvalid = false\n          break\n        end\n      end\n      sum += isvalid ? nd(n) : 0\n    end\n  end\n  sum\nend\n@time println(calc())\n", "meta": {"hexsha": "18dc6915858c56efd464ed3f0bffc67a5f38d711", "size": 958, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p43.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p43.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p43.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 26.6111111111, "max_line_length": 190, "alphanum_fraction": 0.6670146138, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012640659996, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7754561555874796}}
{"text": "#=\n    Simple MCMC:\n    Utilizes a Metropolis-Hastings Algorithm with a \n    standard Gibbs sampler.\n=#\n\n#=\n    Basic linear equation function\n=#\n\nfunction lnfnc(x::Array{Float64}, a::Float64, b::Float64)\n    y0 = Float64[]\n    for xi in x\n        y0i = (a * xi) + b\n\tpush!(y0, y0i)\n    end\n    return y0\nend\n\n#=\n    Basic chi squared function\n    Note: data set error is variance not stddev\n=#\n\nfunction chisqr(yo::Array{Float64}, ye::Array{Float64}, syo::Array{Float64})\n    csq = Float64[]\n    for (yoi, yei, syoi) in zip(yo, ye, syo)\n        csqi = (yoi - yei)^2 / syoi\n        push!(csq, csqi)\n    end\n    return sum(csq)\nend\n\n#=\n    Basic Metropolis-Hastings Algorithm with a \n    standard Gibbs sampler.\n=#\n\nfunction mcmc(a0, sa, b0, sb, x, y, dy)\n    y0 = lnfnc(x, a0, b0)\n    chi0 = chisqr(y0, y, dy)\n    atrace = Float64[]\n    btrace = Float64[]\n    i = 0\n    j = 0\n    mcn = 500000\n    brn = 1000\n    while i < mcn\n        at = (randn() * sa) + a0\n        bt = (randn() * sb) + b0\n        yt = lnfnc(x, at, bt)\n        chit = chisqr(yt, y, dy)\n        acal = e^((chi0 - chit) / 2.0)\n        aexp = min(1.0, acal)\n        u = rand()\n        if u <= aexp\n            a0 = at\n            b0 = bt\n            y0 = yt\n            chi0 = chit\n            push!(atrace, at)\n            push!(btrace, bt)\n            i += 1\n        end\n        j += 1\n    end\n    return i, j, sum(atrace[brn:end]) / length(atrace[brn:end]), sum(btrace[brn:end]) / length(btrace[brn:end])\nend\n\n#=\n    Main\n=#\n\nx = Float64[203, 58, 210, 202,\n\t    198, 158, 165, 201,\n\t    157, 131, 166, 160,\n\t    186, 125, 218, 146]\n\ny = Float64[495, 173, 479, 504,\n\t    510, 416, 393, 442,\n\t    317, 311, 400, 337,\n\t    423, 334, 533, 344]\n\ndy = Float64[21, 15, 27, 14,\n\t     30, 16, 14, 25,\n\t     52, 16, 34, 31,\n\t     42, 26, 16, 22]\n\na0 = 2.5\nsa = 0.025\nb0 = 28.82\nsb = 2.5\n\n# timing start\n@time mcmc_out = mcmc(a0, sa, b0, sb, x, y, dy)\n# timing end\nprintln(mcmc_out)\n", "meta": {"hexsha": "6f54019d15f9223b58c77c0b39981ac3f705bb87", "size": 1941, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "mcmc.jl", "max_stars_repo_name": "astronomerdamo/mcmc_speed", "max_stars_repo_head_hexsha": "dc86dac8a838c22b5ce2c2796fcada74934b5462", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-04-01T22:49:19.000Z", "max_stars_repo_stars_event_max_datetime": "2015-05-29T04:34:55.000Z", "max_issues_repo_path": "mcmc.jl", "max_issues_repo_name": "astronomerdamo/mcmc_speed", "max_issues_repo_head_hexsha": "dc86dac8a838c22b5ce2c2796fcada74934b5462", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mcmc.jl", "max_forks_repo_name": "astronomerdamo/mcmc_speed", "max_forks_repo_head_hexsha": "dc86dac8a838c22b5ce2c2796fcada74934b5462", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.806122449, "max_line_length": 111, "alphanum_fraction": 0.5167439464, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7754561551828059}}
{"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENCE in the project root.\n# ------------------------------------------------------------------\n\n# -------------\n# COMPOSITIONS\n# -------------\n\n\"\"\"\n    ilr(c)\n\nIsometric log-ratio transformation of composition `c`.\n\"\"\"\nfunction ilr(c::Composition{D}) where {D}\n  w = components(c) .+ eps()\n  l = log.(w)\n  T = eltype(w)\n  x = MVector(ntuple(i->zero(T), D-1))\n  for i in 1:D-1\n    s = zero(T)\n    sqrtinv = 1/sqrt(i*(i+1))\n    for j in 1:i+1\n      if j < i+1\n        s += - sqrtinv * l[j]\n      elseif j==i+1\n        s += i * sqrtinv * l[j]\n      end\n    end\n    x[i] = s\n  end\n  SVector(x)\nend\n\n\"\"\"\n    ilrinv(x)\n\nInverse ilr transformation of coordinates `x`.\n\"\"\"\nfunction ilrinv(x::SVector{D}) where {D}\n  z = MVector(ntuple(i->0.0, D+1))\n  for i in 1:D+1\n    s = 0.0\n    for j in 1:D\n      sqrtinv = 1/sqrt(j*(j+1))\n      if i < j+1\n        s += - sqrtinv * x[j]\n      elseif i == j+1\n        s += j * sqrtinv * x[j]\n      end\n    end\n    z[i] = exp(s)\n  end\n  Composition(𝒞(z))\nend\n\nilrinv(x::AbstractVector) = ilrinv(SVector{length(x)}(x))\n\n# -------\n# TABLES\n# -------\n\n\"\"\"\n    ILR([refvar])\n\nIsometric log-ratio transform following the\n[TableTransforms.jl](https://github.com/JuliaML/TableTransforms.jl)\ninterface.\n\nOptionally, specify the reference variable `refvar` for the ratios.\nDefault to the last column of the input table.\n\"\"\"\nstruct ILR <: LogRatio\n  refvar::Union{Symbol,Nothing}\nend\n\nILR() = ILR(nothing)\n\nrefvar(transform::ILR, vars) =\n  isnothing(transform.refvar) ? last(vars) : transform.refvar\n\nnewvars(::ILR, n) = collect(n)[begin:end-1]\n\noldvars(::ILR, vars, rvar) = [collect(vars); rvar]\n\napplymatrix(::ILR, X) = mapslices(ilr ∘ Composition, X, dims=2)\n\nfunction revertmatrix(::ILR, Y)\n  D = size(Y, 2)\n  f = components ∘ ilrinv ∘ SVector{D}\n  mapslices(f, Y, dims=2)\nend", "meta": {"hexsha": "f7ebe6d34d5b1137846207013a80f256cd6f7254", "size": 1907, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transforms/ilr.jl", "max_stars_repo_name": "OkonSamuel/CoDa.jl", "max_stars_repo_head_hexsha": "cae693f6662085280c09a2b4b9a05e7093851e8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-12-21T01:16:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-08T13:42:09.000Z", "max_issues_repo_path": "src/transforms/ilr.jl", "max_issues_repo_name": "OkonSamuel/CoDa.jl", "max_issues_repo_head_hexsha": "cae693f6662085280c09a2b4b9a05e7093851e8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/transforms/ilr.jl", "max_forks_repo_name": "OkonSamuel/CoDa.jl", "max_forks_repo_head_hexsha": "cae693f6662085280c09a2b4b9a05e7093851e8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:31:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-08T21:48:36.000Z", "avg_line_length": 20.956043956, "max_line_length": 68, "alphanum_fraction": 0.5458835868, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7754561539302518}}
{"text": "\n\nfunction bracket_minimum(f, x=0; s=1e-2, k=2.0)\n    a, ya = x, f(x)\n    b, yb = a + s, f(a + s)\n    if yb > ya\n        a, b = b, a\n        ya, yb = yb, ya\n        s = -s\n    end\n    while true\n        c, yc = b + s, f(b + s)\n        if yc > yb\n            return a < c ? (a, c) : (c, a)\n        end\n        a, ya, b, yb = b, yb, c, yc\n        s *= k\n    end\nend\n\nf = x->sin(10x)+cos(3x)\nx0 = 3.4\n#busca do intervalo\na,c = bracket_minimum(f,x0)\n\nusing Plots\n\nplot(f,0.,4.,lw=2,draw_arrow=\"true\")\nscatter!([a,c],[f(a),f(c)])", "meta": {"hexsha": "8be75456143fce05d4172ed76e2bc76e43ce9953", "size": 524, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Bracket_Minimum.jl", "max_stars_repo_name": "GilbertoLucas/Structural_Optimization", "max_stars_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Bracket_Minimum.jl", "max_issues_repo_name": "GilbertoLucas/Structural_Optimization", "max_issues_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Bracket_Minimum.jl", "max_forks_repo_name": "GilbertoLucas/Structural_Optimization", "max_forks_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0689655172, "max_line_length": 47, "alphanum_fraction": 0.4351145038, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182845, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7754478716794024}}
{"text": "# Generate a random orthogonal matrix\nfunction random_orthogonal!{T}(O::Matrix{T}, n::Int)\n    F = qrfact!(randn(n, n))\n    Q = full(F[:Q])\n    R = F[:R]\n    for i in 1:size(R, 1)\n        d = sign(R[i, i])\n        for j in 1:size(Q, 2)\n            Q[i, j] *= d\n        end\n    end\n\n    return copy!(O, Q)\nend\n\nrandom_orthogonal(n::Int) = random_orthogonal!(Matrix{Float64}(n, n), n)\n\n# Generate a random 3D rotation matrix\nfunction random_rotation()\n    Q = random_orthogonal(3)\n    det(Q) * Q\nend\n\n# Generate a random permutation matrix\nrandom_permutation(n::Int) = eye(n)[:, randperm(n)]\n", "meta": {"hexsha": "0e8146efceba861af847cbe942403ae2b36feef5", "size": 590, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/random_matrices.jl", "max_stars_repo_name": "NickMcNutt/MoreMatrices.jl", "max_stars_repo_head_hexsha": "bcd0650251384691a7e7520854328f3f7051118c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/random_matrices.jl", "max_issues_repo_name": "NickMcNutt/MoreMatrices.jl", "max_issues_repo_head_hexsha": "bcd0650251384691a7e7520854328f3f7051118c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/random_matrices.jl", "max_forks_repo_name": "NickMcNutt/MoreMatrices.jl", "max_forks_repo_head_hexsha": "bcd0650251384691a7e7520854328f3f7051118c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6923076923, "max_line_length": 72, "alphanum_fraction": 0.6, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660923657094, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7754478523223093}}
{"text": "\n\nfunction max_independent_set(g::Graph)\n\n    m = Model(solver=CbcSolver())   \n\n    @variable(m, b[v in vertices(g)], Bin)\n   \n    @constraint(m , nonadjacency[e in edges(g)], b[src(e)] + b[dst(e)] <= 1)\n\n    @objective(m, Max, sum{b[v] , v in vertices(g)})\n\n    solve(m)\n    println(\"The max indepedent set has $(getobjectivevalue(m)) elements\")      \n    getvalue(b)\nend\n\nfunction min_dominating_set(g::Graph)\n\n    m = Model(solver=CbcSolver())   \n\n    @variable(m, b[v in vertices(g)], Bin)\n   \n    @constraint(m , dominance[u in vertices(g)], b[u] + sum{b[v], v in out_neighbors(g,u)} >= 1)\n\n    @objective(m, Min, sum{b[v] , v in vertices(g)})\n\n    solve(m)   \n    println(\"The min dominating set has $(getobjectivevalue(m)) elements\")\n    getvalue(b)   \nend\n\n\nfunction min_vertex_cover(g::Graph)\n\n    m = Model(solver=CbcSolver())   \n\n    @variable(m, b[v in vertices(g)], Bin)\n   \n    @constraint(m , cover[e in edges(g)], b[src(e)] + b[dst(e)] >= 1)\n\n    @objective(m, Min, sum{b[v] , v in vertices(g)})\n\n    solve(m)   \n    println(\"The min vertex cover has $(getobjectivevalue(m)) elements\")\n    getvalue(b)\nend\n\nfunction bipartite_set(g::Graph)\n\n    m = Model(solver=CbcSolver())   \n\n    @variable(m, b[v in vertices(g)], Bin)\n   \n    @constraint(m , cover[e in edges(g)], b[src(e)] + b[dst(e)] == 1)\n\n    solve(m)   \n    \n    print(\"These vertices are independent : \")\n    for(v in vertices(g))\n        getvalue(b[v]) == 1 && print(\"$v, \") \n    end\n    println()\n    \n    getvalue(b)   \nend\n\n\nfunction distances(g::Graph, root::Int)\n\n    m = Model(solver=CbcSolver())   \n\n    @variable(m, d[v in vertices(g)], Int)\n   \n    @constraint(m , d[root] == 0)\n    @constraint(m , hop[e in edges(g)], -1 <= d[src(e)] - d[dst(e)] <= 1)\n\n    @objective(m, Max, sum{d[v] , v in vertices(g)})\n\n    solve(m)\n    getvalue(d)\nend\n", "meta": {"hexsha": "04b88d823a5d827a45a4a6131ffdf864348817bc", "size": 1827, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/graphs/structural.jl", "max_stars_repo_name": "IssamT/MathPrograms.jl", "max_stars_repo_head_hexsha": "ec634ee37c0dbc9bcd223efceff2cd7e6e7e7c36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-11-14T04:05:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-26T04:30:54.000Z", "max_issues_repo_path": "src/graphs/structural.jl", "max_issues_repo_name": "IssamT/MathPrograms.jl", "max_issues_repo_head_hexsha": "ec634ee37c0dbc9bcd223efceff2cd7e6e7e7c36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/graphs/structural.jl", "max_forks_repo_name": "IssamT/MathPrograms.jl", "max_forks_repo_head_hexsha": "ec634ee37c0dbc9bcd223efceff2cd7e6e7e7c36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-14T04:06:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-14T04:06:03.000Z", "avg_line_length": 22.0120481928, "max_line_length": 96, "alphanum_fraction": 0.5769020252, "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142225532629, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7754020399790145}}
{"text": "module JuliaConSamplePackage\nusing ForwardDiff\n\nexport newton\n\n\"\"\"\n    newton(f, f′, x₀; maxiter = 100, tol = 1e-8)\nFind `f`s root via Newton's method.\n\"\"\"\nfunction newton(f, f′, x₀; maxiter = 100, tol = 1e-8)\n    xₙ₊₁ = x₀\n    xₙ = NaN\n    iter = 0\n    while true\n        fₓ₊₁ = f(xₙ₊₁)\n        fₓ = f(xₙ)\n        if abs(fₓ₊₁ - fₓ) < tol\n            return xₙ₊₁\n        end\n        if iter > maxiter\n            error(\"Did not converge!\")\n        end\n\n        f′ₙ₊₁ = f′(xₙ₊₁)\n        if f′ₙ₊₁ == 0.0\n            error(\"Derivative is zero!\")\n        end\n        xₙ₊₁, xₙ = xₙ₊₁ - fₓ₊₁/f′ₙ₊₁, xₙ₊₁\n        iter += 1\n    end\nend\n\nnewton(f, x₀; maxiter = 100, tol = 1e-8) =\n    newton(f, x -> ForwardDiff.derivative(f, x), x₀; maxiter = maxiter, tol = tol)\n\nend", "meta": {"hexsha": "7a2c0c3f8a42d28d208ae1e3d40c7e76bee98070", "size": 759, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/JuliaConSamplePackage.jl", "max_stars_repo_name": "SudiptaSen29/JuliaConSamplePackage.jl", "max_stars_repo_head_hexsha": "26b96d7655214c11b908e749d074b1534d7b3b26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/JuliaConSamplePackage.jl", "max_issues_repo_name": "SudiptaSen29/JuliaConSamplePackage.jl", "max_issues_repo_head_hexsha": "26b96d7655214c11b908e749d074b1534d7b3b26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/JuliaConSamplePackage.jl", "max_forks_repo_name": "SudiptaSen29/JuliaConSamplePackage.jl", "max_forks_repo_head_hexsha": "26b96d7655214c11b908e749d074b1534d7b3b26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0833333333, "max_line_length": 82, "alphanum_fraction": 0.5059288538, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7754020386035478}}
{"text": "#==\nThis example shows multiobjective Paretofronts with 3 objectives.\nThe front is convex. The NBI method does not catch the full Pareto front,\ne.g. as seen by the missing arcs between f1 and f2, whilst f3 is 0.\nTo capture this area, we need some of the elements in β to be negative.\n\nTaken from\nIl Yong Kim and OL De Weck.\nAdaptive weighted sum method for multiobjective optimization:\na new method for pareto front generation.\nStructural and Multidisciplinary Optimization, 31(2):105–116, 2006.\n==#\n\nusing MultiJuMP, JuMP\nusing Ipopt\n\nm = MultiModel(solver = IpoptSolver())\n\n@variable(m, x[i=1:3] >= 0)\n@NLexpression(m, f1, x[1])\n@NLexpression(m, f2, x[2])\n@NLexpression(m, f3, x[3])\n@NLconstraint(m, x[1]^4+2x[2]^3+5x[3]^2<=1)\n\nobj1 = SingleObjective(f1, sense = :Max)#,\n                       #iv = Dict{Symbol, Any}(:x => [0, 0., 1.2]))\n\nobj2 = SingleObjective(f2, sense = :Max)#,\n                       #iv = Dict{Symbol, Any}(:x => [0, 0., 1.2]))\n\nobj3 = SingleObjective(f3, sense = :Max)#,\n                       #iv = Dict{Symbol, Any}(:x => [0, 0., 2.]))\n\n\nmd = getMultiData(m)\nmd.objectives = [obj1, obj2, obj3]\n#md.objectives = [obj1, obj2]\nmd.pointsperdim = 10\nsolve(m, method = :NBI)\n\nusing Plots\npyplot()\nplot(md)\n", "meta": {"hexsha": "e7f5c45c004a13debeda8b09de07507cb096402b", "size": 1228, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/kim_3d_convex.jl", "max_stars_repo_name": "matbesancon/MultiJuMP.jl", "max_stars_repo_head_hexsha": "c74c59b3df66ef94df6d4cafeb31395725f54e6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/kim_3d_convex.jl", "max_issues_repo_name": "matbesancon/MultiJuMP.jl", "max_issues_repo_head_hexsha": "c74c59b3df66ef94df6d4cafeb31395725f54e6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/kim_3d_convex.jl", "max_forks_repo_name": "matbesancon/MultiJuMP.jl", "max_forks_repo_head_hexsha": "c74c59b3df66ef94df6d4cafeb31395725f54e6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9090909091, "max_line_length": 73, "alphanum_fraction": 0.6473941368, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458263207691, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.7753737614195647}}
{"text": "using PyPlot\nip = (x, y) -> sum([x_i * y_i for (x_i, y_i) in zip(x, y)])\nct = length(filter(x -> x % 2 == 0, [0:99;]))\npairs = [(2, 5), (4, 2), (9, 8), (12, 10)]\nct2 = length(filter(x -> x[1] % 2 == 0 && x[2] % 2 == 0, pairs))\nct3 = sum([(x % 2 == 0) & (y % 2 == 0) for (x, y) in pairs])\np = (x, coeff) -> sum([a_i * x^(i-1) for (i, a_i) in enumerate(coeff)])\nct4 = str -> sum([a == A for (a, A) in zip(str, uppercase(str))])\nisin = (seq_a, seq_b) -> length(seq_a) == sum([in(a, seq_b) for a in seq_a])\n\nfunction linapprox(f, a, b, n, x)\n  delta = (b-a)/n\n  points = [a + delta*i for i in 0:n]\n  fs = map(f, points)\n  m = round(Int, div((x-a), delta))\n\n  plot(points, fs)\n\n  return fs[m] + (fs[m+1]-fs[m])/delta * (x - delta*m)\nend\n\nprintln(ip([1,2], [2,1]))\nprintln(ct)\nprintln(ct2)\nprintln(ct3)\nprintln(p(1, [1, 1, 0]))\nprintln(ct4(\"Hello\"))\nprintln(isin([2:10;], [0:10;]))\nprintln(linapprox(x -> x^2, 0, 1, 5, 0.39))\n", "meta": {"hexsha": "e989b23b612c97e640edbb3ab8edd745c905388a", "size": 920, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/jl0502/test11.jl", "max_stars_repo_name": "nswa17/Mn", "max_stars_repo_head_hexsha": "8dee1a35f798dc05ec50076ed7c43d0253993019", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Julia/jl0502/test11.jl", "max_issues_repo_name": "nswa17/Mn", "max_issues_repo_head_hexsha": "8dee1a35f798dc05ec50076ed7c43d0253993019", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/jl0502/test11.jl", "max_forks_repo_name": "nswa17/Mn", "max_forks_repo_head_hexsha": "8dee1a35f798dc05ec50076ed7c43d0253993019", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6666666667, "max_line_length": 76, "alphanum_fraction": 0.5293478261, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.775373753384733}}
{"text": "function asin!(X::IntervalBox)\n    x, y = X\n\n    h = half_pi.lo\n    y_new = y ∩ Interval(-h, h)  # range of asin\n    x_new = sin(y_new)\n\n    return IntervalBox(x_new, y_new)\nend\n\n\"\"\"\nReverse `asin`.\n\"\"\"\nfunction asin_rev(y::Interval, x::Interval)  # y = asin(x)\n\n    h = half_pi.lo\n    y_new = y ∩ Interval(-h, h)  # range of asin\n\n    x_new = sin(y_new)\n\n    return y_new, x_new  # return in order y, x\nend\n\n\"\"\"\nReverse `acos`.\n\"\"\"\nfunction acos_rev(y::Interval, x::Interval)\n        y_new = y ∩ Interval(0.0,two_pi.hi)\n        x_new = x ∩ cos(y_new)\n\n        return y_new, x_new\nend\n\n\"\"\"\n    atan_rev(y::Interval, x::Interval)\n\nInverse of `y = atan(x)`.\nReturns the new `y` and `x`.\n\"\"\"\nfunction atan_rev(y::Interval, x::Interval)\n        y_new = y ∩ Interval(-half_pi.hi, half_pi.hi)\n        x_new = x ∩ tan(y_new)\n\n        return y_new, x_new\nend\n", "meta": {"hexsha": "b8bddab4cb9b6961eda65920aad0447ea06c3c3b", "size": 851, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/inverse_trig.jl", "max_stars_repo_name": "UnofficialJuliaMirror/IntervalContractors.jl-15111844-de3b-5229-b4ba-526f2f385dc9", "max_stars_repo_head_hexsha": "e95b5d21425d6c757088d284f5a62adda4c7baa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-02-27T20:15:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T17:55:10.000Z", "max_issues_repo_path": "src/inverse_trig.jl", "max_issues_repo_name": "UnofficialJuliaMirror/IntervalContractors.jl-15111844-de3b-5229-b4ba-526f2f385dc9", "max_issues_repo_head_hexsha": "e95b5d21425d6c757088d284f5a62adda4c7baa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2017-05-03T14:08:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-04T20:43:33.000Z", "max_forks_repo_path": "src/inverse_trig.jl", "max_forks_repo_name": "UnofficialJuliaMirror/IntervalContractors.jl-15111844-de3b-5229-b4ba-526f2f385dc9", "max_forks_repo_head_hexsha": "e95b5d21425d6c757088d284f5a62adda4c7baa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-05-04T04:46:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T23:30:35.000Z", "avg_line_length": 18.5, "max_line_length": 58, "alphanum_fraction": 0.5898942421, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7753737521095483}}
{"text": "abstract type AbstractSingleValuedUtility end\nabstract type AbstractIsoElastic <: AbstractSingleValuedUtility end\n\ndutil(c, ps::AbstractIsoElastic)=c^(-rra(ps))\ninvdutil(m, ps::AbstractIsoElastic)=m^(-1/rra(ps))\n\n\"\n   IsoElastic\n\nIsoElastic specification for a utility with one good.\n\nThe parametrization is either\n```math\nU(c) = \\frac{c^{1-\\alpha}-1}{1-\\alpha}\n```\n\nor\n\n```math\nU(c) = \\frac{c^{1-\\alpha}}{1-\\alpha}\n```\n\n(depending on whether IsoElasticVar2 is passed to `util`.)\n\nThe field `elast` corresponds to α.\n\"\nstruct IsoElastic <: AbstractIsoElastic\n    elast::Float64\n    function IsoElastic(elast)\n        elast == 1 && error(\"Please use log utility specification\")\n        new(elast)\n    end\nend\nstruct LogUtility <: AbstractIsoElastic end\nfunction IsoElastic(;a::Float64)\n    a == 1 && return LogUtility()\n    return(IsoElastic(a))\nend\n\n\n# Methods for iso-elastic types\nstruct IsoElasticVar2 end\n\nutil(c, ps::IsoElastic, ::Type{IsoElasticVar2})=c^(1-ps.elast)/(1-ps.elast)\nutil(c, ps::IsoElastic)=util(c,ps,IsoElasticVar2)-1/(1-ps.elast)\ninvutil(u, ps::IsoElastic)=(u*(1-ps.elast)+1)^(1/(1-ps.elast))\n\nutil(c, ::LogUtility)=log(c)\ninvutil(u, ::LogUtility)=exp(u)\n\nrra(ps::IsoElastic)=ps.elast\nrra(::LogUtility)=1.\n\n\" Constant absolute risk aversion specification \"\nstruct CARA <: AbstractSingleValuedUtility\n    a::Float64\nend\n\nutil(c, ps::CARA)=(1 - exp(-ps.a * c))/ps.a\ninvutil(u, ps::CARA)=(-1/ps.a)*log(1 - ps.a*u)\ndutil(c, ps::CARA)=exp(-ps.a * c)\ninvdutil(m, ps::CARA)=-log(m)/ps.a\n\n\n\n\" Risk neutral specification \"\nstruct RiskNeutral <: AbstractIsoElastic end\n\nutil(c, ps::RiskNeutral)=c\ninvutil(u, ps::RiskNeutral)=u\ndutil(c, ps::RiskNeutral)=one(c)\ninvdutil(c, ps::RiskNeutral)=error(\"Tried to invert constant marginal utility from risk neutral agent\")\n", "meta": {"hexsha": "1734d516d77380c7bd1719d3c45264d83854b6a5", "size": 1775, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utility.jl", "max_stars_repo_name": "pereiragc/Econlite.jl", "max_stars_repo_head_hexsha": "4ee2664231bac4ba62b38bb85abcd7129da6bf09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utility.jl", "max_issues_repo_name": "pereiragc/Econlite.jl", "max_issues_repo_head_hexsha": "4ee2664231bac4ba62b38bb85abcd7129da6bf09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utility.jl", "max_forks_repo_name": "pereiragc/Econlite.jl", "max_forks_repo_head_hexsha": "4ee2664231bac4ba62b38bb85abcd7129da6bf09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3150684932, "max_line_length": 103, "alphanum_fraction": 0.7042253521, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7753737447252945}}
{"text": "#=\nCreated on 09/01/2021 13:08:20\nLast update: -\n\n@author: Michiel Stock\nmichielfmstock@gmail.com\n\nIntegrating for dummies. Compute the Riemann sum **without** making use of a for loop.\n\nCompute the area of a circle.\n=#\n\nfunction riemannsum(f, a, b; n=100)\n    dx = (b - a) / n\n    return sum(f.(a:dx:b)) * dx\nend\n\nriemannsum(sin, 0, 2pi)\n\nriemannsum(x->x*sin(x), 0, 2pi)\n\n4riemannsum(x->(sqrt(1-x^2)), 0, 1, n=1000)\n", "meta": {"hexsha": "8968e01752845cb62980862cc677493decfd66a0", "size": 417, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/riemann.jl", "max_stars_repo_name": "jpgmolina/DS-Julia2925", "max_stars_repo_head_hexsha": "4d96351afb72f4107fa12561a6a460dcd3c617e3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-02-03T14:07:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T13:27:08.000Z", "max_issues_repo_path": "examples/riemann.jl", "max_issues_repo_name": "jpgmolina/DS-Julia2925", "max_issues_repo_head_hexsha": "4d96351afb72f4107fa12561a6a460dcd3c617e3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 74, "max_issues_repo_issues_event_min_datetime": "2020-11-23T22:50:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:49:00.000Z", "max_forks_repo_path": "examples/riemann.jl", "max_forks_repo_name": "jpgmolina/DS-Julia2925", "max_forks_repo_head_hexsha": "4d96351afb72f4107fa12561a6a460dcd3c617e3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-01-31T14:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-19T07:11:30.000Z", "avg_line_length": 18.1304347826, "max_line_length": 86, "alphanum_fraction": 0.6594724221, "num_tokens": 161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7753737421489543}}
{"text": "\n\nraw_data = readlines(\"../inputs/day03.txt\")\nnum_bits = length(raw_data[1])\n\nfunction line2ints(line)\n    return map(x -> parse(Int, x), collect(line))\nend\n\nfunction get_power_consumption(data)\n\n\n    function get_gamma(average_vals)\n        output_string = \"\"\n        for val in average_vals\n            if val < 0.5\n                output_string = output_string * \"0\"\n            else\n                output_string = output_string * \"1\"\n            end\n        end\n        return parse(Int, output_string, base = 2)\n    end\n\n    function get_epsilon(average_vals)\n        output_string = \"\"\n        for val in average_vals\n            if val < 0.5\n                output_string = output_string * \"1\"\n            else\n                output_string = output_string * \"0\"\n            end\n        end\n        return parse(Int, output_string, base = 2)\n    end\n\n    column_sums = sum(data)\n    average_value = column_sums / length(data)\n\n    gamma = get_gamma(average_value)\n    epsilon = get_epsilon(average_value)\n\n    return gamma * epsilon\n\nend\n\nint_data = map(x -> line2ints(x), raw_data)\n\npower_consumption = get_power_consumption(int_data)\nprintln(\"Day 03 Part 1 Solution: \", power_consumption)\n\nfunction get_most_common_in_col(data, index)\n    average_val = sum(data) / length(data)\n    if average_val[index] >= 0.5\n        return 1\n    else\n        return 0\n    end\nend\n\nfunction get_least_common_in_col(data, index)\n    average_val = sum(data) / length(data)\n    if average_val[index] >= 0.5\n        return 0\n    else\n        return 1\n    end\nend\n\nfunction filter_by_most_common_index(data, index)\n    filter_val = get_most_common_in_col(data, index)\n    return data[map(x -> x[index] == filter_val, data)]\nend\n\nfunction filter_by_least_common_index(data, index)\n    filter_val = get_least_common_in_col(data, index)\n    return data[map(x -> x[index] == filter_val, data)]\nend\n\nfunction get_oxygen_rating(data)\n    output_data = data\n    for ii in range(1, num_bits)\n        if length(output_data) == 1\n            break\n        else\n            output_data = filter_by_most_common_index(output_data, ii)\n        end\n    end\n\n    output_string = \"\"\n    for bit in output_data[1]\n        output_string = output_string * string(bit)\n    end\n    return parse(Int, output_string, base = 2)\nend\n\nfunction get_co2_rating(data)\n    output_data = data\n    for ii in range(1, num_bits)\n        _backup_data = output_data\n        if length(output_data) == 1\n            break\n        else\n            output_data = filter_by_least_common_index(output_data, ii)\n        end\n\n        if length(output_data) == 0\n            output_data = _backup_data\n        end\n    end\n\n    output_string = \"\"\n    for bit in output_data[1]\n        output_string = output_string * string(bit)\n    end\n    return parse(Int, output_string, base = 2)\nend\n\noxygen_rating = get_oxygen_rating(int_data)\nco2_rating = get_co2_rating(int_data)\nlife_support = oxygen_rating * co2_rating\n\n\nprintln(\"Day 03 Part 2 Solution: \", life_support)", "meta": {"hexsha": "9dc6d2545a49ff2ca3c033ec6359a71a1100d036", "size": 3007, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "solutions/day03.jl", "max_stars_repo_name": "davidallen353/adventofcode2021", "max_stars_repo_head_hexsha": "4ecb0254dd46bddf1e1c7798e88f8b3ba5f435ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-19T16:38:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T16:38:41.000Z", "max_issues_repo_path": "solutions/day03.jl", "max_issues_repo_name": "davidallen353/adventofcode2021", "max_issues_repo_head_hexsha": "4ecb0254dd46bddf1e1c7798e88f8b3ba5f435ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solutions/day03.jl", "max_forks_repo_name": "davidallen353/adventofcode2021", "max_forks_repo_head_hexsha": "4ecb0254dd46bddf1e1c7798e88f8b3ba5f435ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.25, "max_line_length": 71, "alphanum_fraction": 0.638510143, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090322, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7753737386162254}}
{"text": "\nfunction standardize(x::AbstractVector)\n    std_x = std(x)\n    if std_x == zero(std_x)\n        return zero(x)\n    else\n        return (x .- mean(x)) ./ std_x\n    end\nend\n\nfunction standardize(x::AbstractMatrix;dims = 1 )\n    standardized_x = similar(x)\n    if dims == 1\n        for i in 1:size(x,2)\n            standardized_x[:,i] .= standardize(x[:,i])\n        end\n    elseif dims == 2\n        for i in 1:size(x,1)\n            standardized_x[i,:] .= standardize(x[i,:])\n        end\n    end\n    return standardized_x\nend\nfunction reverse_standardization(standardized_x::T, x::T) where T<: AbstractVector\n    std_x =std(x)\n    if std_x == zero(std_x)\n        temp = x[1]\n        return fill(temp,size(standardized_x))\n    else\n        return (standardized_x .* std(x)) .+ mean(x)\n    end\nend\n\nfunction reverse_standardization(standardized_x::T, x::T; dims=1) where T<: AbstractMatrix\n    new_x =similar(standardized_x)\n    if dims == 1\n        for i in 1:size(x,2)\n            new_x[:,i] .= reverse_standardization(standardized_x[:,i],x[:,i])\n        end\n    elseif dims == 2\n        for i in 1:size(x,1)\n            new_x[i,:] .= reverse_standardization(standardized_x[i,:],x[i,:])\n        end\n    end\n    return new_x\nend\n\nfunction gradient(x::Vector{T}) where {T<:Number}\n    res = similar(x)\n    for i = 1:length(x)\n        if i == 1\n            res[i] = x[i+1] - x[i]\n        elseif i == size(x, 1)\n            res[i] = x[i] - x[i-1]\n        else\n            res[i] = (x[i+1] - x[i-1]) / 2\n        end\n    end\n    return res\nend\n\nfunction gradient(m::Matrix{T}) where {T<:Number}\n    res = similar(m)\n    for i = 1:size(m, 1)\n        if i == 1\n            res[i, :] = m[i+1, :] - m[i, :]\n        elseif i == size(m, 1)\n            res[i, :] = m[i, :] - m[i-1, :]\n        else\n            res[i, :] = (m[i+1, :] - m[i-1, :]) / 2\n        end\n    end\n    return res\nend\n\n\n# function TNB_reorientation(verts::AbstractVector, T, N, B)\n#     new_verts = similar(verts)\n#     for i in eachindex(new_verts)\n#         new_verts[i] = [T N B] \\ verts[i]\n#     end\n#     return new_verts\n# end\n", "meta": {"hexsha": "fe1bd856025c6727e9c24816e7321db2b8bf216e", "size": 2087, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils_movement.jl", "max_stars_repo_name": "yusri-dh/MovingFrame.jl", "max_stars_repo_head_hexsha": "1be0d7e4ec1f20d898dfbaf9f85e5b9ac86c7b6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-28T07:25:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T11:59:15.000Z", "max_issues_repo_path": "src/utils_movement.jl", "max_issues_repo_name": "yusri-dh/MovingFrame.jl", "max_issues_repo_head_hexsha": "1be0d7e4ec1f20d898dfbaf9f85e5b9ac86c7b6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils_movement.jl", "max_forks_repo_name": "yusri-dh/MovingFrame.jl", "max_forks_repo_head_hexsha": "1be0d7e4ec1f20d898dfbaf9f85e5b9ac86c7b6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8452380952, "max_line_length": 90, "alphanum_fraction": 0.5285098227, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8596637487122112, "lm_q1q2_score": 0.7753485120927751}}
{"text": "# Implement code block 2.8 in McElreath's Statistical Rethinking, 2nd edition.\n\nusing Random\nusing Distributions\nusing Plots\n\nRandom.seed!(17)\n\nnum_samples = 2000\n\nprobas = [0.5]\n\nsuccesses = 6\ntrials = 9\n\nfor i = 2:num_samples\n    \n    proba_new = rand(Normal(probas[end], 0.1))\n    \n    if proba_new < 0; proba_new = abs(proba_new); end\n    if proba_new > 1; proba_new = 2 - proba_new; end\n    \n    q0 = pdf(Binomial(trials, probas[end]), successes)\n    q1 = pdf(Binomial(trials, proba_new), successes)\n    \n    push!(probas, rand(Uniform(0, 1)) < q1 / q0 ? proba_new : probas[end])\nend\n\n# println(probas)\n\ndisplay(histogram(probas, bins=:40))\n", "meta": {"hexsha": "d2c826dc4deef83b7e2dac9707728b6954b36ce0", "size": 646, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2-8_monte_carlo_globe_tossing.jl", "max_stars_repo_name": "CrosstabKite/stat_rethinking_julia", "max_stars_repo_head_hexsha": "5dd23fc7d2a438db59e4b45ae08d93503c1a4ef3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2-8_monte_carlo_globe_tossing.jl", "max_issues_repo_name": "CrosstabKite/stat_rethinking_julia", "max_issues_repo_head_hexsha": "5dd23fc7d2a438db59e4b45ae08d93503c1a4ef3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2-8_monte_carlo_globe_tossing.jl", "max_forks_repo_name": "CrosstabKite/stat_rethinking_julia", "max_forks_repo_head_hexsha": "5dd23fc7d2a438db59e4b45ae08d93503c1a4ef3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1875, "max_line_length": 78, "alphanum_fraction": 0.6702786378, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505204, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.775345035116895}}
{"text": "function g_ij(i::Int64,j::Int64,t)\n    ##OverFlowError if i>20\n    \n    s=0 ##The sum of each term\n    for k in j:i\n        e=exp(-k*(k-1)*t/2)\n        numerator=((2*k)-1)*((-1)^(k-j))\n        denominator=factorial(j)*factorial(k-j)*(j+k-1)\n    \n        mult_term=1\n        for y in 0:(k-1)\n            mult_term*=(((j+y)*(i-y))/(i+y))\n        end\n        val=e*(numerator/denominator)*mult_term\n        s+=val\n    end\n    return(s)\nend\n\nfunction nHistories(i::Int64,j::Int64)\n    ##the number of histories where i lineages coalesce into j lineages \n    \n    mult_term=1\n    (j==1) && (j=2) ## coalescing into 1 or 2 lineages have the same number of histories but binomial(k,2) returns 0 when k=1\n    for k in (j+1):i\n        mult_term*=binomial(k,2)\n    end\n    return(mult_term)\nend\n\n\n\nfunction nTops(n::Int64,labeled=true::Bool,rooted=true::Bool)\n    if labeled ##Number of labeled tree topologies\n        n==1 && return(1)\n        return(Int(factorial(2*n-3)/((2^(n-2)*factorial(n-2)))))\n    \n    else ##number of unlabeled topologies i.e. tree shapes\n        n==1 && return(1) ##base case for recursion\n        odd=true\n        (mod(n,2)==0) && (odd=false)\n\n        if odd ## n is odd\n            val=0\n            for p in 1:((n-1)/2)\n                val+=nTops(p,false)*nTops(n-p,false)\n            end\n        else ## n is even\n            t2=nTops(n/2,false)\n            term=t2*(t2+1)/2\n\n            s=0\n            for p in 1:((n/2)-1)\n                s+=nTops(p,false)*nTops(n-p,false)\n            end\n            val=term+s\n        end\n        return(Int(val))\n    end\nend\n\nfunction nLabeledShape(n::Int64,s::Int64)\n    ##Compute the number of labeled topologies of a given tree shapes\n    ##Where:\n        #n= # of taxa\n        #s= # of symetric nodes i.e. nodes where its two subtrees have the same shape\n    return(factorial(n)/(2^s))\nend\n\nfunction nHistoriesTop(desc_nodes::Array{Int64,1})\n    return(factorial(length(desc_nodes))*prod((x->(1/(x+1)).(desc_nodes))))\nend\n\nfunction unlabeledGenerate(n)\n    ##we will create dictionaries to store the bits we want for unlabeled tree shapes\n    ##Each key in the dictionary will point to a vector of the bits for each tree shape \n        ##e.g. sym_tops[5] will give us a vector of how many points of symmetry each tree shape with 5 taxa has \n    vect_tops=Dict{Int64, Array{Array{Int64,1},} }() ##this bit is the node vector representation of the tree shape. Each element in the vector represents an internal node and it denotes how many internal nodes it has as descendents\n    sym_tops=Dict{Int64,Array{Int64,1}}() ##this bit stores the number of reflection points for a given tree shape\n    prod_tops=Dict{Int64,Array{Float64,1}}() ##if x is the node vector representation of the tree shape, this bit stores the product of 1/(1+x)\n\n    ##Initialize the first two sets\n    vect_tops[1]=[[]]\n    sym_tops[1]=[0]\n    prod_tops[1]=[1]\n\n    vect_tops[2]=[[0]]\n    sym_tops[2]=[1]\n    prod_tops[2]=[1]\n\n    for i in 3:n\n        vect_tops[i]=[]\n        sym_tops[i]=[]\n        prod_tops[i]=[]\n\n        for j in 1:(floor(i/2))\n            ##make new shapes by combining all the the j_th and (n-j)_th arrays\n\n            bottom=j\n            top=i-j\n\n            for k in 1:(length(vect_tops[bottom]))\n                for l in 1:(length(vect_tops[top]))\n                   first=vect_tops[bottom][k] \n                   second=vect_tops[top][l]\n\n                   c=Int64[]\n                   append!(c,first)\n                   append!(c,second)\n                   push!(c,length(c))\n                   push!(vect_tops[i],c)\n\n                   sym_new=(sym_tops[bottom][k]+sym_tops[top][l]) ##The number of symmetry points is the sum of the symmetry points of the two subtrees\n                   (first==second) && (sym_new+=1) ## If the two shapes are the same then this makes another point of symmetry\n                   push!(sym_tops[i],sym_new)\n\n                   push!( prod_tops[i],prod( (x->(1/(x+1))).(c) ) ) ##TODO could make this more efficient by instead computing a new w from the c vector, just multiply the to previous products together\n                end\n            end\n        end\n    end\n    return ((vect_tops,sym_tops,prod_tops));\nend\n\nfunction splitsHistories(splits::Array{Int64,1}, tops_mat)\n    total=[0]\n\n    spltsHisRec(splits,1,1,tops_mat,total)\n   \n    return total[1];\n\nend\n\nfunction spltsHisRec(splits::Array{Int64,1},ind_splits,running_val,tops_mat,total::Array{Int64,1} )\n    split=splits[ind_splits]\n    ##Get all the symmetries and products for the split we're interested in  \n    syms=tops_mat[2][splits[ind_splits]]\n    prods=tops_mat[3][splits[ind_splits]]\n\n    nshapes=length(syms) ##the number of treeshapes for a given number of taxa in the split\n\n    for shape in 1:nshapes ##Do calculation for each shape\n        val=running_val ##reset the value for each shape\n\n        val*=factorial(split)/(2^(syms[shape]))\n        val*=prods[shape]\n\n        if ind_splits==length(splits) ##Base Case: we went thru each split and did the calculation\n            val*=factorial(sum((x->x-1).(splits)))\n            total[1]+=val \n        else ##we still have more splits to do calculations\n            spltsHisRec(splits,ind_splits+1,val,tops_mat,total)\n        end\n    end\nend\n\nfunction findLowNode(net::HybridNetwork) ##TODO. Make this generate a list of all the nodes to do in order instead of one at a time. Also, since net.node never changes until the end, we could have it store the node indices instead of pointers to the nodes themselves. \n    numbers=(x->x.number).(net.node) ##store old numbers '\n    nd_changed= net.nodes_changed ##store node ordering\n    rankNodes!(net)\n    \n    ##get all hybrid nodes\n    hybs=net.hybrid\n\n    nds=Set() ##This will have all the nodes we need to decompose\n    for hyb in hybs\n        union!(nds,Set(preorder(net,hyb))) ##add the hyb node and all its descendents to the list\n    end\n    nds=collect(nds) ##turn the nodes into an array\n    nds= nds[(x->(!x.leaf)).(nds)] ##get rid of tips\n     \n    nds=nds[sortperm((x->x.number).(nds))]\n    ((x,y)->x.number=y).(net.node,numbers) ##reset node numbers to their old values\n    net.nodes_changed=nd_changed ##reset node ordering\n\n\n    return nds\nend\n\nfunction decompILS(network::HybridNetwork,decomp_node::Node,prb::Float64,tm,hyb_sorting::Dict{Int64, Dict{Int64,Set{String}}})\n\n    ## Make a copy of the network that we can muck around with.\n    nd_ind=findfirst(x->x==decomp_node,network.node)\n    net=deepcopy(network)\n    nd=net.node[nd_ind]\n\n    par=getParents(nd)[1] \n    nmes=(x->x.name).(getChildren(nd))\n\n    c_edge=getChildrenEdges(nd)[1].length   ##get the edge length of the first child, ignore other child edge lengths, assuming ultrametricy they should all be the same anyways\n    p_edge=getChildrenEdges(par)[1].length  ##get the edge length of the parent\n    elen=c_edge+p_edge ##This will be the edge length we assign to our coalesced edges\n\n    removeClade!(net,nd,false)\n    par_ind=findfirst(x->x==par,net.node)\n\n    subsets=collect(partitions(nmes)) ##we need the power set (excluding the empty set) of all names for decomposition \n\n    ##We ultimately want ot report the decomposed trees and their respective probabilities after everything is all said and done\n    decomposed_trees=HybridNetwork[]\n    probs=Float64[]\n\n    for subset in subsets\n        ##start with a fresh tree for adding things back\n        decomp_net=deepcopy(net)\n        decomp_par=decomp_net.node[par_ind]\n\n        new_node_num=maximum((x-> x.number).(net.node))\n        new_edge_num=maximum((x-> x.number).(net.edge))\n\n        nms_coal=String[] ##These are the names of the coalesced tips we're adding to the tree \n        for nameset  in subset ##We need the individual sets within subset to concatenate the names \n            if length(nameset)==1\n                nm=nameset[1]\n            else\n                nm=join(nameset,\"|\")\n            end\n            push!(nms_coal,nm)\n        end\n\n        for nm in nms_coal #Sequentially add each coalesced tip back to the tree\n            ##create a new node and edge for the tip\n            ntip=Node(new_node_num,true)\n            ntip.name=nm\n            nedge=Edge(new_edge_num,elen)\n            new_edge_num+=1\n            new_node_num+=1\n\n           \n            ##make appropriate connections\n            push!(decomp_par.edge,nedge)\n            push!(nedge.node,ntip)\n            push!(nedge.node,decomp_par)\n            push!(ntip.edge,nedge)\n\n            ##add the new nodes and edges to the network\n            push!(decomp_net.node,ntip)\n            push!(decomp_net.edge,nedge)\n            push!(decomp_net.leaf,ntip)\n        end \n        \n        ##update the attributes of the network\n        num_added=length(nms_coal)\n        decomp_net.numTaxa+=num_added\n        decomp_net.numNodes+=num_added\n        decomp_net.numEdges+=num_added\n        preorder!(decomp_net) ##preorder things for good measure \n\n        ##Compute the probability of the tree\n        gij=g_ij(length(nmes),length(nms_coal),p_edge) ## the probability of i lineages coalescing into j lineages by time t\n        hp=splitsHistories(length.(subset),tm) ##The number of coalescent histories that lead to these partitions\n        ch=nHistories(length(nmes),length(nms_coal)) ##The total number of coalescent histories for i coalescing into j lineages\n\n        treeprob=gij*(hp/ch)*prb ##TODO I'm concerned with underflow so make this deal with small numbers. perhaps switch to log probs\n        treeprob==0 && error(\"Likely underflow of the probability\")\n        \n        push!(decomposed_trees,decomp_net)\n        push!(probs,treeprob)\n    end\n    ##Make copies of hyb_sorting for each decomposed tree\n    hybsort= Dict{Int64, Dict{Int64,Set{String}}}[]\n    for i in 1:length(probs)\n        push!(hybsort,deepcopy(hyb_sorting))\n    end\n    return collect(zip(decomposed_trees,probs,hybsort))\nend\n\nfunction emptyHybSorting(net::HybridNetwork;type=\"name\")\n    if type == \"name\"\n        hybsort= Dict{Int64, Dict{Int64,Set{String}}}()\n        hybs=net.hybrid\n        for hyb in hybs\n            hybsort[hyb.number]=Dict{Int64,Set{String}}()\n            for nd in getParents(hyb)\n            hybsort[hyb.number][nd.number]=Set{String}() \n            end\n        end\n    elseif type == \"node\"\n        hybsort= Dict{Int64, Dict{Int64,Set{Node}}}()\n        hybs=net.hybrid\n        for hyb in hybs\n            hybsort[hyb.number]=Dict{Int64,Set{Node}}()\n            for nd in getParents(hyb)\n            hybsort[hyb.number][nd.number]=Set{Node}() \n            end\n        end\n    else\n        error(\"we didn't get a valid type. Either 'node' or 'name' is accepted\")\n    end\n    return hybsort\nend\n\nfunction decompHyb(network::HybridNetwork,nd::Node,prb::Float64,hyb_sorting::Dict{Int64, Dict{Int64,Set{String}}} )\n    ## Make a copy of the network that we can muck around with.\n    nd_ind=findfirst(x->x==nd,network.node)\n    net=deepcopy(network)\n    nd=net.node[nd_ind]\n    \n    hyb_num= nd.number\n\n    lpar=getMajorParent(nd) ##left parent\n    rpar=getMinorParent(nd) ##right parent\n    lnum=lpar.number \n    rnum=rpar.number\n    lp_e=getMajorParentEdge(nd) \n    rp_e=getMinorParentEdge(nd)  \n\n    c_elen=getChildrenEdges(nd)[1].length   ##get the edge length of the first child, ignore other child edge lengths, they should be the same anyway\n    lp_elen=lp_e.length\n    rp_elen=rp_e.length\n\n    l_gamma=lp_e.gamma\n    r_gamma=rp_e.gamma\n\n    removeClade!(net,nd,false)\n\n    lpar_ind=findfirst(x->x==lpar,net.node) ##The index of the left parent in net.node\n    rpar_ind=findfirst(x->x==rpar,net.node) ##The index of the right parent in net.node\n\n    ##create all combinations for how the lineages could sort between the two hybrid getParents\n    nmes=(x->x.name).(getChildren(nd)) ##get each lineage\n    lsort=collect(combinations(nmes)) ##Generate all possible ways that things could sort to the left\n    push!(lsort,[]) ## the function above doesn't account for the fact that no species could sort left\n    rsort=(x->setdiff(nmes,x)).(lsort) ## everything that doesn't sort left must go right. NOTE: we assume that no lineages have the same name here\n    combs=collect(zip(lsort,rsort)) ##associate the proper sortings together to generate all ways that lineages can sort\n\n    ##These will store the decomposed trees and their probabilities \n    decomposed_trees=HybridNetwork[]\n    probs=Float64[]\n    hybsorts=Dict{Int64, Dict{Int64,Set{String}}}[]\n\n    for i in combs\n        ##start with a fresh slate for adding things\n        hybsort=deepcopy(hyb_sorting)\n        decomp_net=deepcopy(net)\n        ldecomp_par=decomp_net.node[lpar_ind]\n        rdecomp_par=decomp_net.node[rpar_ind]\n        \n        leftgoing=first(i)\n        rightgoing=last(i)\n\n\n        ####################\n        ###Deal with left###\n        ####################\n        if length(leftgoing)>1 ##if more than 1 tip, we need to make a node for the mrca of all tips going left\n            nedge=Edge(-1,lp_elen)\n            ##Make appropriate connections\n            push!(ldecomp_par.edge,nedge)\n            push!(nedge.node,ldecomp_par)\n            ldecomp_par=Node(-1,false,false)\n            push!(ldecomp_par.edge,nedge)\n            pushfirst!(nedge.node,ldecomp_par)\n            ##add the new nodes and tips to the network\n            push!(decomp_net.node,ldecomp_par)\n            push!(decomp_net.edge,nedge)\n            ##update attributes of the network\n            decomp_net.numNodes+=1\n            decomp_net.numEdges+=1\n            r_elen=c_elen\n        elseif  length(leftgoing)==0 ##if there is nothing going to the left we need to resolve the parent node \n            deleteleaf!(decomp_net,findfirst(x->x===ldecomp_par,decomp_net.node);index=true,simplify=false)\n        else ##only 1 tip going left\n            r_elen=c_elen+rp_elen\n        end\n        for nm in leftgoing ##add tips going left to the network\n            ntip=Node(-1,true)\n            ntip.name=nm\n            nedge=Edge(-1,lp_elen+c_elen)\n\n             ##make appropriate connections\n             push!(ldecomp_par.edge,nedge)\n             push!(ntip.edge,nedge)\n             push!(nedge.node,ntip)\n             push!(nedge.node,ldecomp_par)\n\n            ##add the new nodes and tips to the network\n            push!(decomp_net.node,ntip)\n            push!(decomp_net.edge,nedge)\n            push!(decomp_net.leaf,ntip)\n        end\n\n        ####################\n        ###Deal with right##\n        ####################\n        if length(rightgoing)>1 ##if more than 1 tip, we need to make a node for the mrca of all tips going right\n            nedge=Edge(-1,rp_elen)\n            ##Make appropriate connections\n            push!(rdecomp_par.edge,nedge)\n            push!(nedge.node,rdecomp_par)\n            rdecomp_par=Node(-1,false,false)\n            push!(rdecomp_par.edge,nedge)\n            pushfirst!(nedge.node,rdecomp_par)\n            ##add the new nodes and tips to the network\n            push!(decomp_net.node,rdecomp_par)\n            push!(decomp_net.edge,nedge)\n            ##update attributes of the network\n            decomp_net.numNodes+=1\n            decomp_net.numEdges+=1\n            r_elen=c_elen\n        elseif  length(rightgoing)==0 ##if there is nothing going to the right we need to resolve the parent node \n            deleteleaf!(decomp_net,findfirst(x->x===rdecomp_par,decomp_net.node);index=true,simplify=false)\n        else #only 1 tip going right\n            r_elen=c_elen+rp_elen\n        end\n        for nm in rightgoing ##add tips to the right parent\n            ntip=Node(-1,true)\n            ntip.name=nm\n            nedge=Edge(-1,r_elen)\n\n             ##make appropriate connections\n             push!(rdecomp_par.edge,nedge)\n             push!(ntip.edge,nedge)\n             push!(nedge.node,ntip)\n             push!(nedge.node,rdecomp_par)\n\n            ##add the new nodes and tips to the network\n            push!(decomp_net.node,ntip)\n            push!(decomp_net.edge,nedge)\n            push!(decomp_net.leaf,ntip)\n        end\n        ##the tree should now be deocmposed \n        \n        ##Update the attributes of the network\n        num_added=length(rightgoing)+length(leftgoing)\n        decomp_net.numNodes+=num_added\n        decomp_net.numEdges+=num_added\n        decomp_net.numTaxa+=num_added\n        preorder!(decomp_net) ##preorder things for good measure\n\n\n        ##record which lineages went left and right along the reticulation\n        left_names=String[]\n        right_names=String[]\n        lnms= (x->split(x,\"|\")).(leftgoing)\n        rnms= (x->split(x,\"|\")).(rightgoing)\n        println(lnms)\n        println(rnms)\n        for nms in lnms\n            append!(left_names,String.(nms))\n        end\n        for nms in rnms\n            append!(right_names,String.(nms))\n        end\n        hybsort[hyb_num][lnum]=Set(left_names)\n        hybsort[hyb_num][rnum]=Set(right_names)\n\n        ##Compute the probability of the tree\n        treeprob=(r_gamma^length(rightgoing))*(l_gamma^length(leftgoing))*prb ##TODO I'm concerned with underflow so make this deal with small numbers. perhaps switch to log probs\n        treeprob==0 && error(\"Likely underflow of the probability\")\n\n        push!(decomposed_trees,decomp_net)\n        push!(probs,treeprob)\n        push!(hybsorts,hybsort)\n    end\n    return collect(zip(decomposed_trees,probs,hybsorts))\nend\n\n\nfunction networkDecomposition(net::HybridNetwork)\n\n    hybsorting=emptyHybSorting(net)\n    prob=1.0\n    q= Array{Tuple{HybridNetwork,Array{Dict{Int64,Dict{Int64,Set{String}}},1},Float64}}() ##Queue of partially decomposed trees along with their hyb_sorting profiles and probabilities\n    fully_decomposed =  Array{Tuple{HybridNetwork,Array{Dict{Int64,Dict{Int64,Set{String}}},1},Float64}}() ##Where we store fully decompposed trees \n    push!(q,(net,hybsorting,1.0))\n\n    ##determine how big of an unlabeledGenerate we need to run. it should be the size of max(numberLeaves(hyb_node) for all hyb_node in hyb_nodes)\n    nleaves=Int64[]\n    for hyb in net.hybrid\n        e=getChildrenEdges(hyb)[1]\n        length(descendants(e))\n    end\n\n    while (!isempty(q)) ##while there are still things in the Queue...\n\n        current=popfirst!(q)\n\n        curr_net=current[1]\n        curr_hybsort=current[2]\n        curr_prob=current[3]\n\n        decomp_nds=findLowNode\n\n    end\n\n    \n    nd=findLowNode(net)\n\nend\n\n", "meta": {"hexsha": "6a718dcb7c3d40800d1c04d020b959b19fb625d6", "size": 18373, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/coalescent.jl", "max_stars_repo_name": "jjustison/PhyloNetworks.jl", "max_stars_repo_head_hexsha": "dced0084cf6dd56df00afff25c876b822412aa52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/coalescent.jl", "max_issues_repo_name": "jjustison/PhyloNetworks.jl", "max_issues_repo_head_hexsha": "dced0084cf6dd56df00afff25c876b822412aa52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/coalescent.jl", "max_forks_repo_name": "jjustison/PhyloNetworks.jl", "max_forks_repo_head_hexsha": "dced0084cf6dd56df00afff25c876b822412aa52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.343495935, "max_line_length": 268, "alphanum_fraction": 0.6270070212, "num_tokens": 4969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.7753450306350347}}
{"text": "# Scale from/to [0,1]. \nscalefrom(a,b,t) = @. (t-a)/(b-a)\nscaleto(a,b,t) = @. a + t*(b-a)\n\n# Unique real roots of a quadratic.\nfunction realroots(a,b,c)\n\ta==0 && return [-c/b]\n\tbh = -b/2\n\td = bh^2 - a*c \n\tif d < 0\n\t\t[]\n\telseif d==0\n\t\t[bh/a]\n\telse\n\t\tr = (bh + sign(bh)*sqrt(d)) / a \n\t\t[r,c/(r*a)]\n\tend\nend  \n\n# Are three given points arranged in counterclockwise order? \nfunction isccw(a::Number,b::Number,c::Number)\n\tv(z) = SVector(1,real(z),imag(z))\n\tdet([v(a) v(b) v(c)]) > 0\nend\n\n# Use 2nd order finite differences to approximate a tangent.\nfunction fdtangent(z,t::Real) \n\tϵ = eps(typeof(float(t)))\n\tϵ3 = 0.5*ϵ^(1/3)\n\tif t < ϵ3\n\t\tτ = (-1.5*z(t) + 2*z(t+ϵ3) - 0.5*z(t+2ϵ3)) / ϵ3\n\telseif t > 1-ϵ3\n\t\tτ = (1.5*z(t) - 2*z(t-ϵ3) + 0.5*z(t-2ϵ3)) / ϵ3\n\telse\n\t\tτ = (z(t+ϵ3) - z(t-ϵ3)) / (2ϵ3)\n\tend\n\treturn τ\nend\n\n# Select points adaptively to make a smooth-appearing curve. \nfunction adaptpoints(point,utangent,a,b;depth=6,curvemax=0.05)\n\tfunction refine(tl,tr,zl,zr,τl,τr,maxdz,d=depth)\t\t\n\t\tdzkap = dist(τr,τl)  # approximately, the stepsize over radius of curvature\n\t\ttm = (tl+tr)/2\n\t\tzm = point(tm)\n\t\tτm = utangent(tm) \n\t\tif d > 0 && (dzkap > curvemax || dist(zr,zl) > maxdz )\n\t\t\tzl = refine(tl,tm,zl,zm,τl,τm,maxdz,d-1)\n\t\t\tzr = refine(tm,tr,zm,zr,τm,τr,maxdz,d-1)\n\t\t\treturn [zl;zm;zr]\n\t\telse\n\t\t\treturn zm\n\t\tend\n\tend\n\n\td = (b-a)/4\n\ttt = d*[0,0.196,0.41,0.592,0.806]   # avoid common symmetry points\n\tt = [a .+ tt; a + d .+ tt; a + 2d .+ tt; a + 3d .+ tt; b]\n\tz = point.(t)\n\tτ = utangent.(t)\n\n\t# on the Riemann sphere, use distance in R^3\n\tif z[1] isa Spherical\n\t\tdist = (u,v) -> norm(S2coord(u)-S2coord(v))\n\telse\n\t\tdist = (u,v) -> abs(u-v)\n\tend\n\tm = length(t) \n\tscale = maximum(dist(z[i],z[j]) for i=2:m-1, j=2:m-1 if j > i)\n\tzfinal = z[[1]]\n\tfor j = 1:length(t)-1\n\t\tznew = refine(t[j],t[j+1],z[j],z[j+1],τ[j],τ[j+1],scale/25)\n\t\tappend!(zfinal,znew)\n\t\tpush!(zfinal,z[j+1])\n\tend\n\treturn zfinal\nend\n\n# Do adaptive integration to estimate the integral of `f` over [`a`,`b`] to desired\n# error tolerance `tol`.\nfunction intadapt(f,a,b,tol)\n    # Use error estimation and recursive bisection.\n    function do_integral(a,fa,b,fb,m,fm,tol,depth)\n        # These are the two new nodes and their f-values.\n        xl = (a+m)/2;  fl = f(xl);\n        xr = (m+b)/2;  fr = f(xr);\n        t = [a,xl,m,xr,b]              # all 5 nodes at this level\n\n        # Compute the trapezoid values iteratively.\n        h = (b-a)\n        T = [0.,0.,0.]\n        T[1] = h*(fa+fb)/2\n        T[2] = T[1]/2 + (h/2)*fm\n        T[3] = T[2]/2 + (h/4)*(fl+fr)\n\n        S = (4*T[2:3]-T[1:2]) / 3      # Simpson values\n        E = (S[2]-S[1]) / 15           # error estimate\n\n        if abs(E) < tol*(1+abs(S[2]))  # acceptable error?\n            Q = S[2]                   # yes--done\n\t\telse\n\t\t\tif depth==0\n\t\t\t\t@warn \"Too many recursions to determine integral\"\n\t\t\t\tQ = S[2] \n\t\t\telse\n    \t        # Error is too large--bisect and recurse.\n        \t    QL = do_integral(a,fa,m,fm,xl,fl,tol,depth-1)\n            \tQR = do_integral(m,fm,b,fb,xr,fr,tol,depth-1)\n\t\t\t\tQ = QL + QR\n\t\t\tend\n        end\n        return Q\n    end\n\n    m = (b+a)/2\n    Q = do_integral(a,f(a),b,f(b),m,f(m),tol,50)\n    return Q\nend\n\nfunction enclosing_circle(z::AbstractVector,expansion=2)\n\txa,xb = extrema(real(z))\n\tya,yb = extrema(imag(z))\n\tzc = complex((xa+xb)/2,(ya+yb)/2)\n\tR = length(z) > 1 ? maximum(@. abs(z - zc)) : max(1,abs(zc))\n\treturn zc,expansion*R\nend\n\nfunction enclosing_box(z::AbstractVector,expansion=2)\n\tzc = sum(z)/length(z)\n\tdz = z .- zc\n\trx = length(z) > 1 ? maximum(@. abs(real(dz))) : max(1,abs(real(zc)))\n\try = length(z) > 1 ? maximum(@. abs(imag(dz))) : max(1,abs(imag(zc)))\n\treturn real(zc).+expansion*[-rx,rx],imag(zc).+expansion*[-ry,ry] \nend\n\n# indices of the closest pair of points from two lists\nfunction argclosest(z1,z2)\n\ti1 = [argmin(abs.(z1.-z)) for z in z2]\n\ti2 = argmin(abs.(z2.-z1[i1]))\n\treturn i1[i2],i2\nend", "meta": {"hexsha": "935deedf45932d874608a624961d998f64e55771", "size": 3875, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utilities.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/ComplexRegions.jl-c64915e2-6c82-11e9-38e9-1f159a780463", "max_stars_repo_head_hexsha": "5c441763b637200b4067305e74ef8378c9ca9e99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-08-29T16:17:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T08:39:21.000Z", "max_issues_repo_path": "src/utilities.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/ComplexRegions.jl-c64915e2-6c82-11e9-38e9-1f159a780463", "max_issues_repo_head_hexsha": "5c441763b637200b4067305e74ef8378c9ca9e99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-10-15T19:54:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-01T21:15:19.000Z", "max_forks_repo_path": "src/utilities.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/ComplexRegions.jl-c64915e2-6c82-11e9-38e9-1f159a780463", "max_forks_repo_head_hexsha": "5c441763b637200b4067305e74ef8378c9ca9e99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-11-21T20:50:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T09:20:50.000Z", "avg_line_length": 27.4822695035, "max_line_length": 83, "alphanum_fraction": 0.5656774194, "num_tokens": 1554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.77530640979028}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.6\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec\nusing Pkg, DrWatson\n\n# ╔═╡ e4eeb13a-1ee4-11eb-0113-91f9a9c3b659\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, StatsBase, DataFrames\n\tRandom.seed!(1)\nend\n\n# ╔═╡ ac3ceabe-1ee4-11eb-3935-313e96aafd62\nmd\"## Listing 2.7\"\n\n# ╔═╡ c4bef1a4-1ee9-11eb-0b58-8be033f6fbad\nbegin\n\tA = Set(['a','e','i','o','u'])\n\tB = Set(['x','y','z'])\n\tomega = 'a':'z'\n\tN = 10^6\nend\n\n# ╔═╡ 23c4c304-1eea-11eb-2a57-d9b2e99a3253\nbegin\n\tdf = DataFrame()\n\tfor _ in 1:5\n    \tmcEst1 = sum([in(sample(omega),A) || in(sample(omega),B) for _ in 1:N])/N\n    \tmcEst2 = sum([in(sample(omega),union(A,B)) for _ in 1:N])/N\n    \tappend!(df, DataFrame(:mcEst1 => mcEst1, :mcEst2 => mcEst2))\n\tend\n\tdf\nend\n\n# ╔═╡ 6285dea2-1ee5-11eb-2b6a-f9906c0d3351\nmd\"## End of listing 2.7\"\n\n# ╔═╡ Cell order:\n# ╟─ac3ceabe-1ee4-11eb-3935-313e96aafd62\n# ╠═de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec\n# ╠═e4eeb13a-1ee4-11eb-0113-91f9a9c3b659\n# ╠═c4bef1a4-1ee9-11eb-0b58-8be033f6fbad\n# ╠═23c4c304-1eea-11eb-2a57-d9b2e99a3253\n# ╟─6285dea2-1ee5-11eb-2b6a-f9906c0d3351\n", "meta": {"hexsha": "f6847b7032bedcf74f6b506c61bf9e8602165e8c", "size": 1141, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/02/listing2.07.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/02/listing2.07.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/02/listing2.07.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 23.2857142857, "max_line_length": 78, "alphanum_fraction": 0.6818580193, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8887587890727755, "lm_q1q2_score": 0.7753064022688855}}
{"text": "module RadioPropagation\n\t# using Plots\n\tusing Printf\n\n\tc = 299792458; # m/s\n\ti = im;\n\n\t\"\"\"\n\tCalculate the two-way two-ray propagation between two points above a flat plane.\n\tReturns the propagation factor F. The one-way power propagation factor is |F|².\n\n\t- Radar Systems Engineering Lecture 5 Propagation through the Atmosphere, IEEE New Hampshire Section IEEE AES Society, 2010\n\t\n\t```julia\n\t# Example code plotting signal strength as function of range, compared to free space power spread\n\tusing Plots\n\n\tc = 3e8;\n\n\ttransmit_height_m\t= 2;\n\treceive_height_m\t= 10;\n\ttarget_range_m\t\t= LinRange(20, 100, 10000);\n\ttransmit_frequency_hz =3e9;\n\tλ = c/transmit_frequency_hz;\n\tΓ1 = -1;\n\tΓ2 = -0.6;\n\n\tF²( Γ ) = RadioPropagation.two_ray_propagation.( target_range_m, transmit_height_m, receive_height_m, transmit_frequency_hz, Γ );\n\n\tF²1 = F²( Γ1 );\n\tF²2 = F²( Γ2 );\n\n\tf⁴_db( F² ) = 10*log10.( abs2.( F² ));\n\n\tfreespace_loss_db = 10 .*log10.(λ^2 ./( (4*π)^3 .*target_range_m .^4 ));\n\tbias = freespace_loss_db[1]\n\n\n\tplot1 = plot( \ttarget_range_m, f⁴_db.(F²1)+freespace_loss_db .-bias,\n\t\t\t \t \txlabel \t= \"Range (one-way) [m]\",\n\t\t\t\t\tylabel \t= \"Two-way loss [dB]\",\n\t\t\t\t\ttitle  \t= \"Free-space versus two-ray propagation.\",\n\t\t\t\t\tylims \t= (-30, 6),\n\t\t\t\t\tlabel \t= \"|F|⁴+L, Γ=-1\",\n\t\t\t\t\tlegend\t= true,\n\t\t\t\t\txaxis\t=:log,\n\t\t\t\t\tdpi=300)\n\tplot!( \ttarget_range_m, f⁴_db.(F²2)+freespace_loss_db .-bias,\n\t \t\tlabel = \"|F|⁴+L, Γ=-0.6\",\n\t \t\txaxis\t=:log )\n\tplot!( \ttarget_range_m, freespace_loss_db .-bias,\n\t \t\tlabel = \"L\",\n\t \t\txaxis\t=:log )\n\tsavefig(\"figures/example_figure\")\n\n\t```\n\n\t# Arguments\n\t- 'distance'            The distance parallel to the plane earth.\n\t- 'transmit_height'     The height of the transmitter above the plane earth.\n\t- 'receive_height'      The height of the receiver/target above the plane earth.\n\t- 'Γ'                           The reflection coefficient of the medium of the plane earth.\n\t\"\"\"\n\tfunction two_ray_propagation( distance, transmit_height, receive_height, frequency_hz, Γ )\n\t\tλ = c/frequency_hz;\n\t\tΔϕ=  4*π*transmit_height*receive_height/(λ*distance);\n\t\tF = 1+abs(Γ)*exp(i*Δϕ);\n\t\treturn F;\n\tend\n\n\t\"\"\"\n\tEmpirical model for RF rain attenuation for frequencies between 1 and 400 GHz, linear polarization.\n\tModel uses the closest frequency in the underlying data.\n\t\n\t- M. A. Richards and J. A. Scheer and W. A. Holm, Principles of Modern Radar, SciTech Publishing, 2010.\n\n\t```julia\n\train_attenuation_db_per_km_circular_pol( 'v' , 30, 20 )\n\t3.3400000000000003\n\t```\n\n\t# Arguments\n\t- 'polarization'        The polarization, 'v', 'h'.\n\t- 'frequency_ghz'     \tThe frequency of the propagating waves.\n\t- 'fall_rate_mm_hour'\tThe rain intensity [mm/h]. \n\t\"\"\"\n\tfunction rain_attenuation_db_per_km( polarization::Char, frequency_ghz, fall_rate_mm_hour )\n\t\tr = fall_rate_mm_hour;\n\t\t\n\t\t# Empirical data:\n\t\tfrequency_table_ghz = [1, 2, 3 ,6, 7, 8, 10, 12, 15, 20, 25, 30, 35, 40, 45, 50, 60, 70, 80, 90, 100, 120, 150, 200, 300, 400 ];\n\t\tah = [ 3.87e-5, 1.54e-4, 6.5e-4, 1.75e-3, 3.01e-3, 4.54e-3, 1.01e-2, 1.88e-2, 3.67e-2, 7.51e-2, .124, .187, .263, .350, .442, .536, .707, .851, .975, 1.06, 1.12, 1.18, 1.31, 1.45, 1.36, 1.32 ];\n\t\tav = [ 3.52e-5, 1.38e-4, 5.91e-4, 1.55e-3, 2.65e-3, 3.95e-3, 8.87e-3, 1.68e-2, 3.47e-2, 6.91e-2, .113, .167, .233, .310, .393, .479, .642, .784, .906, .999, 1.06, 1.13, 1.27, 1.42, 1.35, 1.31 ];\n\t\tbh = [ .912, .963, 1.121, 1.308, 1.332, 1.327, 1.276, 1.217, 1.154, 1.099, 1.061, 1.021, .979, .939, .903, .873, .826, .793, .769, .753, .743, .731, .710, .689, .688, .683 ];\n\t\tbv = [ .88, .923, 1.075, 1.265, 1.312, 1.310, 1.264, 1.2, 1.128, 1.065, 1.030, 1.0, .963, .929, .897, .868, .824, .793, .769, .754, .744, .732, .711, .69, .689, .683 ];\n\n\t\t# TODO implement interpolation vor arbitrary frequency selection.\n\t\tindex = argmin( abs.(  frequency_ghz.-frequency_table_ghz ) );\n\t\tif polarization == 'v'\n\t\t\ta = av[index];\n\t\t\tb = bv[index];\n\t\telse\n\t\t\ta = ah[index];\n\t\t\tb = bh[index];\n\t\tend\n\n\t\tα = a*r^b;\n\t\treturn α;\n   end\n\n   \"\"\"\n\tEmpirical model for rain attenuation for frequencies between 1 and 400 GHz, circular polarization.\n\tModel uses closest frequency in the underlying data.\n\tOne-way attenuation in dB/km.\n\t\n\t- M. A. Richards and J. A. Scheer and W. A. Holm, Principles of Modern Radar, SciTech Publishing, 2010.\n\n\t```julia\n\train_attenuation_db_per_km_circular_pol( 30, 20 )\n\t3.6755027981960815\n\t```\n\n\t# Arguments\n\t- 'frequency_ghz'     \tThe frequency of the propagating waves.\n\t- 'fall_rate_mm_hour'\tThe rain intensity [mm/h]. \n\t\"\"\"\n\tfunction rain_attenuation_db_per_km_circular_pol( frequency_ghz, fall_rate_mm_hour )\n\t\tα_lin( pol ) = rain_attenuation_db_per_km( pol, frequency_ghz, fall_rate_mm_hour );\n\t\tαv = α_lin('v');\n\t\tαh = α_lin('h');\n\t\t\n\t\tα = 1/sqrt(2) * sqrt(αv^2+αh^2);\n\n\t\treturn α;\n\tend\n\n\t\"\"\"\n\tEmpirical model for rain attenuation for frequencies above 5 GHz.\n\tOne-way attenuation in dB/km.\n\t\t\n\t- M. A. Richards and J. A. Scheer and W. A. Holm, Principles of Modern Radar, SciTech Publishing, 2010.\n\n\t```julia\n\tfog_attenuation_db_per_km_circular_pol( 10, 0.8, 23 );\n\t4.68976\n\t```\n\n\t# Arguments\u0013\n\t- 'frequency_ghz'\tThe frequency of the propagating waves.\n\t- 'M'\t\t\t\tThe watewater concentration in g/m³.\n\t- 'T_deg'\t\t\tThe air temperature in degree Celsius.\n\t\"\"\"\n\tfunction fog_attenuation_db_per_km( frequency_ghz, M, T_deg )\n\t\tT = T_deg;\n\t\tf = frequency_ghz\n\n\t\tα= M*( -1.347 + 0.66*f+(11.152/f) - 0.022*T )\n\t\treturn α;\n\tend\n\n\t\"\"\"\n\tEmpirical model for amospheric gaseous attenuation for frequencies in the range 1 - 1000 GHz.\n\tOne-way attenuation in dB/km.\n\t\t\n\t- Rec. ITU-R P.676-12, Attenuation by atmospheric gases and related effects, ITU-R 2020.\n\t\n\t```julia\n\tusing Plots\n\n\tfrequency_ghz = collect(1:1000);\n\n\tattenuation_db_km = RadioPropagation.atmospheric_attenuation_db_per_km.( frequency_ghz );\n\n\tplot1 = plot(\tfrequency_ghz, attenuation_db_km,\n\t\t\t\t\txlabel \t= \"Frequency [GHz]\",\n\t\t\t\t\tylabel \t= \"One-way loss [dB/km]\",\n\t\t\t\t\ttitle  \t= \"Atmostpheric Attenuation.\",\n\t\t\t\t\t#ylims \t= (),\n\t\t\t\t\tlabel \t= \"Standard\",\n\t\t\t\t\tyaxis=:log);\n\t```\n\n\t# Arguments\u0013\n\t- 'frequency_ghz'\t\t\t\tThe frequency of the propagating waves.\n\t- 'T_kelvin'\t\t\t\t\tThe absolute temperature in kelvin.\n\t- 'water_vapour_density_g_m³' \tThe water vapur density in g/m³.\n\t- 'dry_air_pressure_h_pa' \t\tThe dry air pressure in hpa.\n\t\"\"\"\n\tfunction atmospheric_attenuation_db_per_km( frequency_ghz, T_kelvin=288.15, water_vapour_density_g_m³=7.5, dry_air_pressure_h_pa=1013.25 )\n\t\tf = frequency_ghz;\n\t\tT = T_kelvin;\n\t\tρ = water_vapour_density_g_m³;\n\t\tp = dry_air_pressure_h_pa;\t# Dry air pressure [hPa].\n\t\te = ρ*T/216.7;\t\t\t\t# Water vapour partial pressure [hPa].\n\t\tθ = 300/T;\n\n\t\t# Spectroscopic data for oxygen attenuation.\n\t\t# \t\t  f0 \t\t\ta1\t\t\ta2\t\ta3\t\ta4 \t\ta5 \t\ta6\n\t\ttab1 = \t[ 50.474214\t\t0.975 \t\t9.651\t6.690 \t0.0\t\t2.566 \t6.850\n\t\t\t\t  50.987745\t\t2.529 \t\t8.653\t7.170 \t0.0\t\t2.246 \t6.800\n\t\t\t\t  51.503360\t\t6.193 \t\t7.709\t7.640 \t0.0\t\t1.947 \t6.729\n\t\t\t\t  52.021429\t\t14.320 \t\t6.819\t8.110 \t0.0\t\t1.667 \t6.640\n\t\t\t\t  52.542418\t\t31.240 \t\t5.983\t8.580 \t0.0\t\t1.388 \t6.526\n\t\t\t\t  53.066934\t\t64.290 \t\t5.201\t9.060 \t0.0\t\t1.349 \t6.206\n\t\t\t\t  53.595775\t\t124.600 \t4.474\t9.550 \t0.0\t\t2.227 \t5.085\n\t\t\t\t  54.130025\t\t227.300 \t3.800\t9.960 \t0.0\t\t3.170 \t3.750\n\t\t\t\t  54.671180\t\t389.700 \t3.182\t10.370 \t0.0\t\t3.558 \t2.654\n\t\t\t\t  55.221384\t\t627.100 \t2.618\t10.890\t0.0\t\t2.560 \t2.952\n\t\t\t\t  55.783815\t\t945.300 \t2.109\t11.340\t0.0\t\t-1.172 \t6.135\n\t\t\t\t  56.264774\t\t543.400 \t0.014\t17.030\t0.0\t\t3.525 \t-0.978\n\t\t\t\t  56.363399\t\t1331.800 \t1.654\t11.890\t0.0\t\t-2.378\t6.547\n\t\t\t\t  56.968211\t\t1746.600 \t1.255\t12.230\t0.0\t\t-3.545\t6.451\n\t\t\t\t  57.612486\t\t2120.100 \t0.910\t12.620\t0.0\t\t-5.416\t6.056\n\t\t\t\t  58.323877\t\t2363.700 \t0.621\t12.950\t0.0\t\t-1.932\t0.436\n\t\t\t\t  58.446588\t\t1442.100\t0.083\t14.910\t0.0\t\t6.768 \t-1.273\n\t\t\t\t  59.164204\t\t2379.900 \t0.387\t13.530\t0.0\t\t-6.561 \t2.309\n\t\t\t\t  59.590983\t\t2090.700 \t0.207\t14.080\t0.0\t\t6.957 \t-0.776\n\t\t\t\t  60.306056\t\t2103.400 \t0.207\t14.150\t0.0\t\t-6.395 \t0.699\n\t\t\t\t  60.434778\t\t2438.000 \t0.386\t13.390\t0.0\t\t6.342 \t-2.825\n\t\t\t\t  61.150562\t\t2479.500 \t0.621\t12.920\t0.0\t\t1.014 \t-0.584\n\t\t\t\t  61.800158\t\t2275.900 \t0.910\t12.630\t0.0\t\t5.014 \t-6.619\n\t\t\t\t  62.411220\t\t1915.400 \t1.255\t12.170\t0.0\t\t3.029 \t-6.759\n\t\t\t\t  62.486253\t\t1503.000 \t0.083\t15.130\t0.0\t\t-4.499 \t0.844\n\t\t\t\t  62.997984\t\t1490.200 \t1.654\t11.740\t0.0\t\t1.856 \t-6.675\n\t\t\t\t  63.568526\t\t1078.000 \t2.108\t11.340\t0.0\t\t0.658 \t-6.139\n\t\t\t\t  64.127775\t\t728.700 \t2.617\t10.880\t0.0\t\t-3.036 \t-2.895\n\t\t\t\t  64.678910\t\t461.300 \t3.181\t10.380\t0.0\t\t-3.968 \t-2.590\n\t\t\t\t  65.224078\t\t274.000 \t3.800\t9.960   0.0\t\t-3.528 \t-3.680\n\t\t\t\t  65.764779\t\t153.000 \t4.473\t9.550   0.0\t\t-2.548 \t-5.002\n\t\t\t\t  66.302096\t\t80.400 \t\t5.200\t9.060   0.0\t\t-1.660 \t-6.091\n\t\t\t\t  66.836834\t\t39.800 \t\t5.982\t8.580   0.0\t\t-1.680\t-6.393\n\t\t\t\t  67.369601\t\t18.560 \t\t6.818\t8.110   0.0\t\t-1.956 \t-6.475\n\t\t\t\t  67.900868\t\t8.172 \t\t7.708\t7.640   0.0\t\t-2.216 \t-6.545\n\t\t\t\t  68.431006\t\t3.397 \t\t8.652\t7.170   0.0\t\t-2.492\t-6.600\n\t\t\t\t  68.960312\t\t1.334 \t\t9.650\t6.690   0.0\t\t-2.773 \t-6.650\n\t\t\t\t  118.750334 \t940.300\t\t0.010\t16.640\t0.0\t\t-0.439\t0.079\n\t\t\t\t  368.498246\t67.400\t\t0.048\t16.400\t0.0\t\t0.0\t\t0.0\n\t\t\t\t  424.763020\t637.700\t\t0.044\t16.400\t0.0\t\t0.0\t\t0.0\n\t\t\t\t  487.249273\t237.400\t\t0.049\t16.000\t0.0\t\t0.0\t\t0.0\n\t\t\t\t  715.392902\t98.100\t\t0.145\t16.000\t0.0\t\t0.0\t\t0.0\n\t\t\t\t  773.839490\t572.300\t\t0.141\t16.200\t0.0\t\t0.0\t\t0.0\n\t\t\t\t  834.145546\t183.100\t\t0.145\t14.700\t0.0\t\t0.0\t\t0.0]\n\n\t\tf0a = @view tab1[:,1];\n\t\ta1  = @view tab1[:,2];\n\t\ta2  = @view tab1[:,3];\n\t\ta3  = @view tab1[:,4];\n\t\ta4  = @view tab1[:,5];\n\t\ta5  = @view tab1[:,6];\n\t\ta6  = @view tab1[:,7];\n\t\n\t\t# Spectroscopic data for water vapour attenuation.\n\t\t# \t\t f0 \t\tb1\t\tb2\t\tb3\t\tb4 \t\tb5 \t\tb6\n\t\ttab2 = [ 22.235080 \t.1079\t2.144\t26.38\t.76\t\t5.087\t1.00\n\t\t\t\t 67.803960 \t.0011\t8.732\t28.58\t.69\t\t4.930\t.82\n\t\t\t\t 119.995940 .0007\t8.353\t29.48\t.70\t\t4.780\t.79\n\t\t\t\t 183.310087 2.273\t.668 \t29.06\t.77\t\t5.022\t.85\n\t\t\t\t 321.225630 .0470\t6.179\t24.04\t.67\t\t4.398\t.54\n\t\t\t\t 325.152888 1.514\t1.541\t28.23\t.64\t\t4.893\t.74\n\t\t\t\t 336.227764 .0010\t9.825\t26.93\t.69\t\t4.740\t.61\n\t\t\t\t 380.197353 11.67\t1.048\t28.11\t.54\t\t5.063\t.89\n\t\t\t\t 390.134508 .0045\t7.347\t21.52\t.63\t\t4.810\t.55\n\t\t\t\t 437.346667 .0632\t5.048\t18.45\t.60\t\t4.230\t.48\n\t\t\t\t 439.150807 .9098\t3.595\t20.07\t.63\t\t4.483\t.52\n\t\t\t\t 443.018343 .1920\t5.048\t15.55\t.60\t\t5.083\t.50\n\t\t\t\t 448.001085 10.41\t1.405\t25.64\t.66\t\t5.028\t.67\n\t\t\t\t 470.888999 .3254\t3.597\t21.34\t.66\t\t4.506\t.65\n\t\t\t\t 474.689092 1.260\t2.379\t23.20\t.65\t\t4.804\t.64\n\t\t\t\t 488.490108 .2529\t2.852\t25.86\t.69\t\t5.201\t.72\n\t\t\t\t 503.568532 .0372\t6.731\t16.12\t.61\t\t3.980\t.43\n\t\t\t\t 504.482692 .0124\t6.731\t16.12\t.61\t\t4.010\t.45\n\t\t\t\t 547.676440 .9785\t.158\t26.00\t.70\t\t4.500\t1.00\n\t\t\t\t 552.020960 .1840\t.158\t26.00\t.70\t\t4.500\t1.00\n\t\t\t\t 556.935985 497.0\t.159\t30.86\t.69\t\t4.552\t1.00\n\t\t\t\t 620.700807 5.015\t2.391\t24.38\t.71\t\t4.856\t.68\n\t\t\t\t 645.766085 .0067\t8.633\t18.00\t.60\t\t4.000\t.50\n\t\t\t\t 658.005280 .2732\t7.816\t32.10\t.69\t\t4.140\t1.00\n\t\t\t\t 752.033113 243.4\t.396 \t30.86\t.68\t\t4.352\t.84\n\t\t\t\t 841.051732 .0134\t8.177\t15.90\t.33\t\t5.760\t.45\n\t\t\t\t 859.965698 .1325\t8.055\t30.60\t.68\t\t4.090\t.84\n\t\t\t\t 899.303175 .0547\t7.914\t29.85\t.68\t\t4.530\t.90\n\t\t\t\t 902.611085 .0386\t8.429\t28.65\t.70\t\t5.100\t.95\n\t\t\t\t 906.205957 .1836\t5.110\t24.08\t.70\t\t4.700\t.53\n\t\t\t\t 916.171582 8.400\t1.441\t26.73\t.70\t\t5.150\t.78\n\t\t\t\t 923.112692 .0079\t10.293 \t29.00\t.70\t\t5.000\t.80\n\t\t\t\t 970.315022 9.009\t1.919 \t25.50\t.64\t\t4.940\t.67\n\t\t\t\t 987.926764 134.6\t.257 \t29.85\t.68\t\t4.550\t.90\n\t\t\t\t 1780.000000 17506. .952 \t196.3\t2.00 \t24.15\t5.00]\n\n\t\tf0b = @view tab2[:,1];\n\t\tb1  = @view tab2[:,2];\n\t\tb2  = @view tab2[:,3];\n\t\tb3  = @view tab2[:,4];\n\t\tb4  = @view tab2[:,5];\n\t\tb5  = @view tab2[:,6];\n\t\tb6  = @view tab2[:,7];\n\n\n\t\tS_o\t\t= @. a1*10^(-7)*p*θ^3*exp( a2*(1-θ));\n\t\tS_w\t\t= @. b1*10^(-1)*e*θ^3.5*exp(b2*(1-θ));\n\t\t\n\t\tΔf_o_\t= @. a3*10^(-4) *(p*θ^(0.8-a4) + 1.1*e*θ);\n\t\tΔf_o\t= @. sqrt( Δf_o_^2 + 2.25*10^(-6) );\n\n\t\tΔf_w_\t= @. b3*10^(-4) *(p*θ^b4 + b5*e*θ^b6);\n\t\tΔf_w\t= @. 0.535*Δf_w_ + sqrt( 0.217*Δf_w_^2 + (2.1316*10^-12*f0b^2)/ θ );\n\n\t\tδ_o\t\t= @. (a5+a6*θ)*10^(-4) *(p+e)*θ^(0.8);\n\t\tδ_w\t\t= 0;\n\n\t\tF_o\t\t= @. f/f0a *( (Δf_o-δ_o*(f0a-f))/((f0a-f)^2 + Δf_o^2 ) + (Δf_o-δ_o*(f0a+f))/((f0a+f)^2 + Δf_o^2) );\n\t\tF_w\t\t= @. f/f0b *( (Δf_w-δ_w*(f0b-f))/((f0b-f)^2 + Δf_w^2 ) + (Δf_w-δ_w*(f0b+f))/((f0b+f)^2 + Δf_w^2) );\n\t\t\n\t\td\t\t= 5.6*10^(-4) * (p+e)*θ^0.8;\n\t\t\n\t\tN_D_prime = f*p*θ^2 * ( (6.14*10^(-5) / ( d*(1+(f/d)^2) )) +  (1.4*10^(-12) *p*θ^1.5) / ( 1+1.9*10^(-5) *f^1.5 ) );\n\n\t\tN_d_prime_oxygen\t\t= sum( S_o.*F_o) + N_D_prime;\n\t\tN_d_prime_water_vapour\t= sum( S_w.*F_w );\n\t\t\n\t\tγ = 0.1820*f*(N_d_prime_oxygen+N_d_prime_water_vapour);\n\t\treturn γ;\n\tend\nend\n", "meta": {"hexsha": "2570a59ad485f85e5f13b455f9c44417e95b4f4c", "size": 12299, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "RadioPropagation.jl", "max_stars_repo_name": "ErikBuer/RadioPropagation", "max_stars_repo_head_hexsha": "08730c3244e478cbb38ceb21068596a55ca294db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RadioPropagation.jl", "max_issues_repo_name": "ErikBuer/RadioPropagation", "max_issues_repo_head_hexsha": "08730c3244e478cbb38ceb21068596a55ca294db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RadioPropagation.jl", "max_forks_repo_name": "ErikBuer/RadioPropagation", "max_forks_repo_head_hexsha": "08730c3244e478cbb38ceb21068596a55ca294db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8430769231, "max_line_length": 196, "alphanum_fraction": 0.6105374421, "num_tokens": 5885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907010924213, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7751978326179274}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.0\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 7224ff21-b911-417d-b42c-b2aac200d930\nbegin\n\tusing PlutoUI\nend\n\n# ╔═╡ 66ee80df-26f5-4d6b-8d2b-deba85ef5a2e\nmd\"\"\"\n\n# Selecting and Filtering Patients Based on Data Values\n\nIn this notebook we will be exploring tools we will be using during the next two weeks to split patients into different groups based on properties that the patients do or do not share. We will start with the conceptual basis for this using __sets__. We will then look at how we can achieve these sets using __Boolean logic__.\n\n\"\"\"\n\n# ╔═╡ 025f1c63-7f8e-4b8c-b470-b35f86f19901\nmd\"\"\"\n# The Beautiful (and Famous) Julia Set\n\n![Julia Set](https://upload.wikimedia.org/wikipedia/commons/thumb/b/bd/Julia_set_(indigo).png/640px-Julia_set_(indigo).png)\n\"\"\"\n\n# ╔═╡ 1da07d3d-3dd5-48e8-a679-fbeef8128091\nmd\"\"\"\n\n## The Key Idea of Sets: Commonality\n\nTo define a set we first need to select the property or properties that __all__ members (elements) of the set have in __common__. The properties need to be such that we can ask quesitons about that property that result in a __YES__ (__True__) or __NO__ (__False__) answer.\n\n### Examples using Numbers:\n\n- The set of all even integers (\"Is 3 even? No (False)\", \"Is 6 even? Yes (True)\")\n- The set of all odd integers (\"Is 3 odd?\", \"Is 6 odd?\")\n- The set of all integers greater than 6. (\"Is 5 greatr than 6?\", \"Is 10 greater than six?\")\n\n#### Exercise\n\nCan you think of at least two more questions you could ask about numbers to create sets of numbers that create a set? (Remember, all members of sets have at least one property in common.)\n\n$(@bind numex1 TextField((80,7)))\n\n\"\"\"\n\n# ╔═╡ 51c6ff9c-dc99-422d-83d4-fece9bb0068d\nmd\"\"\"\n\n\n### Example: Game of Set\n\nThe game Set consists of cards that have four properties\n\n1. Shape\n1. Fill Pattern\n1. Color\n1. Number\n\n![game of Set](https://upload.wikimedia.org/wikipedia/commons/8/8f/Set-game-cards.png)\n\n\nA set consists of three cards which satisfy ALL of these conditions:\n\n* They all have the same number, __OR__ they have three different numbers.\n\n__AND__\n\n* They all have the same symbol, __OR__ they have three different symbols.\n\n__AND__\n\n* They all have the same shading, __OR__ they have three different shadings.\n\n__AND__\n\n* They all have the same color, __OR__ they have three different colors. ([From wikipedia](https://en.wikipedia.org/wiki/Set_(game)))\n\nThis game explicitly several of the concepts that we will use to group patients.\n\nFirst, notice that every condition for the cards can be stated as a __YES__ or __NO__ question? For example, \n\n- \"Do the three cards all have the same shading?\"\n- \"Do the three cards have three different symbols?\"\n\n\n\nFurther, the conditions introduce two of the key words and the corresponding set concepts that we will use to group patients:\n\n- __AND__: This corresponds to the set concept of __INTERSECTION__ (frequently denoted with the symbol __$\\cap$__)\n- __OR__: This corresponds to the set concept of __UNION__ (frequently denoted with the symbol __$\\cup$__)\n\n### One Last Word\n\nIn order to construct our sets we need one last word that is \n\n__NOT__ (frequently denoted with the symbol __!__ or __$\\neg$__)\n\nTo help understand these concepts we will use [Venn diagrams](https://en.wikipedia.org/wiki/Venn_diagram). (Venn diagrams have limited utility for more then three sets.)\n\"\"\"\n\n# ╔═╡ 6d1b3eb5-6f2b-48c6-b8dd-73fbf6c38130\nhtml\"\"\"\n\n<h4>If you have forgotten your childhood Venn diagram lessons, watch this short video.</h4>\n\n<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/lnalI7eVQsQ\" title=\"YouTube video player\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>\n\"\"\"\n\n# ╔═╡ 9917ccf9-1503-4dd9-9bd7-c9a28e9ef7a6\nmd\"\"\"\n\n### Intersection (AND) of Two sets\n\n#### Example\n\n- Let set __F__ be the set of all patients who are Female\n- Let set __O__ be the set of all patients with a BMI > 30.\n\nConsider the question \n\n- \"Who are the female patients with BMI greater than 30?\n\nWe can rewrite this as\n\n- \"Who are the patients who are female (members of set F) __AND__ have a BMI greater than 30 (members of set O)?\"\n\nThis would be written mathematically as\n\n- $\\bf{F} \\cap \\bf{O}?$\n\nand represented in the yellow region in the Venn diagram below.\n\n![Intersection of two sets](https://github.com/chapmanbe/raw-stuff/blob/main/EulerVenn/venn_intersect_fo.png?raw=true)\n\n### Union (OR) of Two Sets\n\n#### Example\n\n- Let set __N__ be the set of all patients who have [disorder of kidney due to diabetes mellitus (nephropathy)](http://purl.bioontology.org/ontology/SNOMEDCT/127013003).\n- Let set __R__ be the set of all patients with a retinopathy.\n\nConsider the question \n\n- \"Who are the patients with nephropathy __OR__ [retinopathy due to diabetes mellitus (retinopathy)](http://purl.bioontology.org/ontology/SNOMEDCT/4855003)?\n\nThis would be written mathematically as\n\n- $\\bf{N} \\cup \\bf{R}?$\n\nand represented in the green region in the Venn diagram below.\n\n![Union of two sets](https://github.com/chapmanbe/raw-stuff/blob/main/EulerVenn/venn_union_nr.png?raw=true)\n\n#### Example\n\n- Let set __F__ be the set of all patients who are Female\n- Let set __O__ be the set of all patients with a BMI > 30.\n\nConsider the question\n\n- \"Who are the female patients who are not obese?\"\n\nThis could be rewritten as\n\n- \"Who are the patients who are female __AND NOT__ obese?\"\n\nThis can be written mathematically as\n\n- $\\bf{F} \\cap \\neg \\bf{O}?$\n\n![Difference of two sets](https://github.com/chapmanbe/raw-stuff/blob/main/EulerVenn/venn_diff_fo.png?raw=true)\n\"\"\"\n\n# ╔═╡ 95d7109f-314d-4851-ac59-4bf059626d24\nmd\"\"\"\n\n## Exploration with the [MIMIC II](https://archive.physionet.org/mimic2/) Demo Data Set\n\nMIMIC (Medical Information Mart for Intensive Care) is a fully de-identified data set consisting of hospital-generated data collected on patients with an ICU admission. The current release of MIMIC is [MIMIC-IV](https://mimic.mit.edu/docs/iv/)\n\n### MIMIC-II\n\nMIMIC-II is an earlier relesae of MIMIC\n\n>The MIMIC II...Databases contain physiologic signals and vital signs time series captured from patient monitors, and comprehensive clinical data obtained from hospital medical information systems, for tens of thousands of Intensive Care Unit (ICU) patients*. Data were collected between 2001 and 2008 from a variety of ICUs (medical, surgical, coronary care, and neonatal) in a single tertiary teaching hospital. \n\nAccess to the full MIMIC data sets requires ethics training and a data use agreement. However, the MIMIC-II data set includes a demo data set that consists of the data for 4000 deceased inviduals and is available without any restrictions. Even as a small data set there is a nearly overwhelming amount of data.\n\n- 5074 admissions\n- 5844 ICU stays\n- 3740682 lab orders\n- 1048968 medication orders\n- 90000 microbiology orders\n- 34240621 chart events\n- 2471191 io events\n- 171927 notes\n\n\n#### Diabetes in MIMIC-II Demo\n\nFor illustrative purposes I extracted some of the data that might be similar to data in our diabetes project. It is also illustrative of how standards can help work with data and how we create sets with YES/NO questions\n\n- __Diagnoses:__ Diagnoses were determined using the ICD9 codes assigned to the patient at discharge.\n  - Does the patient have a type I diabetes diagnosis?\n  - Does the patient have a type II diabetes diagnosis?\n  - Number of non-diabetes diagnoses\n- A1C Values\n- Glucose Blood \n- marital_status\n- ethnicty\n- payor\n- religion\n- admission\n- sex\n- age at death\n- hospitaldeath\n- DaysInHospital\n- height\n- weight\n- bmi\n\n\"\"\"\n\n# ╔═╡ 646ceac0-b72c-4b87-a3a1-0888d9bd4a83\nmd\"\"\"\n### Exercise:\n\nIn this and the following examples the sets are represented using Euler-Venn diagrams, which try to represent not just the intersection of sets but the relative sizes of the sets by the areas of the circles.\n\nGiven the two set _TypeI_ and _TypeII_, what combinations of __AND__, __OR__, and or __NOT__ would yield the set represented by the crosshatched area?\n\n![all diabetics](https://github.com/chapmanbe/raw-stuff/blob/main/EulerVenn/Alldiabetics.png?raw=true)\n\"\"\"\n\n# ╔═╡ a3ed9688-4459-4270-856d-bfb9bcd9a562\n\t\nHTML(\"<details><summary><strong>My Answer</strong></summary><p>TypeI <b>OR</b> Type II</p></details>\")\n\n\n# ╔═╡ 9ec579ae-059a-46e3-b73c-089271a4b83f\nmd\"\"\"\n\n### Exercise:\n\nGiven the two set _TypeI_ and _TypeII_, what combinations of __AND__, __OR__, and or __NOT__ would yield the set represented by the crosshatched area?\n\n![all diabetics](https://github.com/chapmanbe/raw-stuff/blob/main/EulerVenn/DiabeticAndObese.png?raw=true)\n\"\"\"\n\n# ╔═╡ 4ed2f1f8-1249-4679-b93b-a54684163729\n\t\nHTML(\"<details><summary><strong>My Answers</strong></summary><p>Obese <b>AND</b> (TypeI <b>OR</b> Type II)</p></details>\")\n\n\n# ╔═╡ 5aef28d5-8ffd-45f9-a547-6bb41e359bc0\nmd\"\"\"\n\n### Exercise:\n\nGiven the two set _TypeI_ and _TypeII_, what combinations of __AND__, __OR__, and or __NOT__ would yield the set represented by the crosshatched area?\n\n![all diabetics](https://github.com/chapmanbe/raw-stuff/blob/main/EulerVenn/Diedobesediabetic.png?raw=true)\n\"\"\"\n\n# ╔═╡ 392c63d4-75aa-4df1-b0fc-40702c8745b8\n\t\nHTML(\"<details><summary><strong>My Answers</strong></summary><p>Obese <b>AND</b> Type II <b>AND</b> DiedAtHospital</p></details>\")\n\n# ╔═╡ 47c88a48-5392-4b2f-abe6-8593657587bf\nmd\"\"\"## Selecting based on Numeric Values\n\nAll of our examples so far with the MIMIC data set have been asking questions of categorical data (e.g. sex, died at the hospital). But as we showed with the numbers earlier we can still form YES/NO questions with numeric values. Here is an example.\n\n#### Example\n\nA1c above 7 (HighA1c) is viewed as problematic and is a basis for diagnosing diabetes. The biological significance of low A1c (below 4) is not well known. However, a [recent study](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4734630/), found that low A1c was associated with increased mortality. So we might consider A1c vaues < 4 or greater than 7 as problematic:\n\n- \"What patients have TypeII diabetes __AND__ have A1c values less than 4.0 __OR__ have A1c values greater than 7?\"\n\n- $\\text{TypeII} \\cup ((\\text{A1C} < 4) \\cup (\\text{A1C} > 7))$\n\n![a1c problems](https://github.com/chapmanbe/raw-stuff/blob/main/EulerVenn/diabetes4.png?raw=true)\n\n\"\"\"\n\n# ╔═╡ c51953b1-d267-4206-879d-63a139d12afa\nmd\"\"\"\n# Additional set information\n\nIf you are interested in more complete (yet still brief) review of set concepts and notation, check out [this page](https://plato.stanford.edu/entries/set-theory/basic-set-theory.html).\n\"\"\"\n\n# ╔═╡ b481618c-13b7-4fd3-bf21-e736b6902fb9\nmd\"\"\"\n### Answers in set notation\n\n- $\\text{TypeI} \\cup \\text{TypeII}$\n- $\\text{Obese} \\cap (\\text{TypeI} \\cup \\text{TypeII})$\n- $\\text{DiedInHospital} \\cap \\text{Obese} \\cap \\text{TypeII}$\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\n\n[compat]\nPlutoUI = \"~0.7.9\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"438d35d2d95ae2c5e8780b330592b6de8494e779\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.3\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"Suppressor\"]\ngit-tree-sha1 = \"44e225d5837e2a2345e69a1d1e01ac2443ff9fcb\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.9\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[Suppressor]]\ngit-tree-sha1 = \"a819d77f31f83e5792a76081eee1ea6342ab8787\"\nuuid = \"fd094767-a336-5f1f-9728-57cf17d0bbfb\"\nversion = \"0.2.0\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─66ee80df-26f5-4d6b-8d2b-deba85ef5a2e\n# ╟─025f1c63-7f8e-4b8c-b470-b35f86f19901\n# ╟─1da07d3d-3dd5-48e8-a679-fbeef8128091\n# ╟─51c6ff9c-dc99-422d-83d4-fece9bb0068d\n# ╟─6d1b3eb5-6f2b-48c6-b8dd-73fbf6c38130\n# ╟─9917ccf9-1503-4dd9-9bd7-c9a28e9ef7a6\n# ╟─95d7109f-314d-4851-ac59-4bf059626d24\n# ╟─646ceac0-b72c-4b87-a3a1-0888d9bd4a83\n# ╟─a3ed9688-4459-4270-856d-bfb9bcd9a562\n# ╟─9ec579ae-059a-46e3-b73c-089271a4b83f\n# ╟─4ed2f1f8-1249-4679-b93b-a54684163729\n# ╟─5aef28d5-8ffd-45f9-a547-6bb41e359bc0\n# ╟─392c63d4-75aa-4df1-b0fc-40702c8745b8\n# ╠═47c88a48-5392-4b2f-abe6-8593657587bf\n# ╟─7224ff21-b911-417d-b42c-b2aac200d930\n# ╟─c51953b1-d267-4206-879d-63a139d12afa\n# ╟─b481618c-13b7-4fd3-bf21-e736b6902fb9\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "d80724336ab3834f04d0b5525eec07240d217b27", "size": 13911, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "sets.jl", "max_stars_repo_name": "chapmanbe/alhs_julia", "max_stars_repo_head_hexsha": "e1f40047b06468afbf177013dc62750573006fe1", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sets.jl", "max_issues_repo_name": "chapmanbe/alhs_julia", "max_issues_repo_head_hexsha": "e1f40047b06468afbf177013dc62750573006fe1", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sets.jl", "max_forks_repo_name": "chapmanbe/alhs_julia", "max_forks_repo_head_hexsha": "e1f40047b06468afbf177013dc62750573006fe1", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8467153285, "max_line_length": 414, "alphanum_fraction": 0.7473941485, "num_tokens": 4641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7751978284551455}}
{"text": "export entropy,spectrum\n\"\"\"\n    Calculate the von-Neumann entanglement entropy of an MPS at bond_id\n\"\"\"\nfunction entropy(mps::AbstractMPS,bond_id::Int)\n    S = spectrum(mps,bond_id)\n    S = S./sqrt(sum(S.*S))  #normalize MPS\n    S = S .+ 1E-100\n    return sum(- S.*S .* log.(S.*S))\nend\n\n\"\"\"\n    Calculate von-Neumann entanglement entropy of every bonds\n\"\"\"\nfunction entropy(mps::AbstractMPS,epsilon=1E-13)\n    function spectrum2entropy(S::AbstractVector)\n        t = S./sqrt(sum(S.*S))  #normalize MPS\n        t = t .+ 1E-100\n        return sum(- t.*t .* log.(t.*t))\n    end\n    # Calculate the von-Neumann entanglement entropy of an MPS\n    #from left to right, qr\n    v_entropy = zeros(Float64,mps.L-1)\n    sweep!(mps,mps.L-1,LeftNormalization())\n    #print (mps.bdim)\n    #from right to left, svd\n    for site = mps.L:-1:2 \n        S = single_tensor_spectrum!(mps,site)\n        v_entropy[site-1] = spectrum2entropy(S)\n    end\n    return v_entropy\nend\n\n\"\"\"\nCalculate Spectrum in MPS: from site-bond_id to site-bond_id+1\n\"\"\"\nfunction spectrum(mps::AbstractMPS,bond_id::Int)\n    res = 0.0\n    @assert bond_id>0 && bond_id <= mps.L\n    normalization!(mps,bond_id,MixNormalization())\n    U,S,V = svd(reshape(mps[bond_id],mps.bdim[bond_id-1]*mps.S,mps.bdim[bond_id]))\n    return S\nend ", "meta": {"hexsha": "a3543c39c7504cb62d033ccecb5e96888136eadd", "size": 1282, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/measure.jl", "max_stars_repo_name": "qiyang-ustc/JMPS", "max_stars_repo_head_hexsha": "2f0f376b54c0572991ecac32f5c7f5ed910531d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/measure.jl", "max_issues_repo_name": "qiyang-ustc/JMPS", "max_issues_repo_head_hexsha": "2f0f376b54c0572991ecac32f5c7f5ed910531d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-02T01:19:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-02T01:19:25.000Z", "max_forks_repo_path": "src/measure.jl", "max_forks_repo_name": "qiyang-ustc/JMPS", "max_forks_repo_head_hexsha": "2f0f376b54c0572991ecac32f5c7f5ed910531d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8139534884, "max_line_length": 82, "alphanum_fraction": 0.651326053, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7751443740330215}}
{"text": "# Cost functions\n\"\"\"\n    mse(ŷ, y)\n\nReturn the mean squared error `sum((ŷ .- y).^2) / length(y)`. \n\"\"\"\nmse(ŷ, y) = sum((ŷ .- y).^2) * 1 // length(y)\n\n\nfunction _crossentropy(ŷ::AbstractVecOrMat, y::AbstractVecOrMat, weight::Nothing)\n  return -sum(y .* log.(ŷ)) * 1 // size(y, 2)\nend\n\nfunction _crossentropy(ŷ::AbstractVecOrMat, y::AbstractVecOrMat, weight::Number)\n  return -sum(y .* log.(ŷ)) .* weight * 1 // size(y, 2)\nend\n\nfunction _crossentropy(ŷ::AbstractVecOrMat, y::AbstractVecOrMat, weight::AbstractVector)\n  return -sum(y .* log.(ŷ) .* weight) * 1 // size(y, 2)\nend\n\n\"\"\"\n    crossentropy(ŷ, y; weight=1)\n\nReturn the crossentropy computed as `-sum(y .* log.(ŷ) .* weight) / size(y, 2)`. \n\nSee also [`logitcrossentropy`](@ref), [`binarycrossentropy`](@ref).\n\"\"\"\ncrossentropy(ŷ::AbstractVecOrMat, y::AbstractVecOrMat; weight=nothing) = _crossentropy(ŷ, y, weight)\n\n\"\"\"\n    logitcrossentropy(ŷ, y; weight=1)\n\nReturn the crossentropy computed after a [softmax](@ref) operation: \n\n  -sum(y .* logsoftmax(ŷ) .* weight) / size(y, 2)\n\nSee also [`crossentropy`](@ref), [`binarycrossentropy`](@ref).\n\"\"\"\nfunction logitcrossentropy(ŷ::AbstractVecOrMat, y::AbstractVecOrMat; weight = 1)\n  return -sum(y .* logsoftmax(ŷ) .* weight) * 1 // size(y, 2)\nend\n\n\"\"\"\n    binarycrossentropy(ŷ, y; ϵ=eps(ŷ))\n\nReturn `-y*log(ŷ + ϵ) - (1-y)*log(1-ŷ + ϵ)`. The ϵ term provides numerical stability.\n\nTypically, the prediction `ŷ` is given by the output of a [`sigmoid`](@ref) activation.\n\"\"\"\nbinarycrossentropy(ŷ, y; ϵ=eps(ŷ)) = -y*log(ŷ + ϵ) - (1 - y)*log(1 - ŷ + ϵ)\n\n# Re-definition to fix interaction with CuArrays.\nCuArrays.@cufunc binarycrossentropy(ŷ, y; ϵ=eps(ŷ)) = -y*log(ŷ + ϵ) - (1 - y)*log(1 - ŷ + ϵ)\n\n\"\"\"\n    logitbinarycrossentropy(ŷ, y)\n\n`logitbinarycrossentropy(ŷ, y)` is mathematically equivalent to `binarycrossentropy(σ(ŷ), y)`\nbut it is more numerically stable.\n\nSee also [`binarycrossentropy`](@ref), [`sigmoid`](@ref), [`logsigmoid`](@ref).  \n\"\"\"\nlogitbinarycrossentropy(ŷ, y) = (1 - y)*ŷ - logσ(ŷ)\n\n# Re-definition to fix interaction with CuArrays.\nCuArrays.@cufunc logitbinarycrossentropy(ŷ, y) = (1 - y)*ŷ - logσ(ŷ)\n\n\"\"\"\n    normalise(x; dims=1)\n\nNormalises `x` to mean 0 and standard deviation 1, across the dimensions given by `dims`. Defaults to normalising over columns.\n\n```julia-repl\njulia> a = reshape(collect(1:9), 3, 3)\n3×3 Array{Int64,2}:\n  1  4  7\n  2  5  8\n  3  6  9\n\njulia> normalise(a)\n3×3 Array{Float64,2}:\n  -1.22474  -1.22474  -1.22474\n  0.0       0.0       0.0\n  1.22474   1.22474   1.22474\n\njulia> normalise(a, dims=2)\n3×3 Array{Float64,2}:\n  -1.22474  0.0  1.22474\n  -1.22474  0.0  1.22474\n  -1.22474  0.0  1.22474\n```\n\"\"\"\nfunction normalise(x::AbstractArray; dims=1)\n  μ′ = mean(x, dims = dims)\n  σ′ = std(x, dims = dims, mean = μ′, corrected=false)\n  return (x .- μ′) ./ σ′\nend\n\n\"\"\"\n    kldivergence(ŷ, y)\n\nKLDivergence is a measure of how much one probability distribution is different from the other.\nIt is always non-negative and zero only when both the distributions are equal everywhere.\n[KL Divergence](https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence).\n\"\"\"\nfunction kldivergence(ŷ, y)\n  entropy = sum(y .* log.(y)) *1 //size(y,2)\n  cross_entropy = crossentropy(ŷ, y)\n  return entropy + cross_entropy\nend\n\n\"\"\"\n    poisson(ŷ, y)\n\nPoisson loss function is a measure of how the predicted distribution diverges from the expected distribution.\n[Poisson Loss](https://peltarion.com/knowledge-center/documentation/modeling-view/build-an-ai-model/loss-functions/poisson).\n\"\"\"\npoisson(ŷ, y) = sum(ŷ .- y .* log.(ŷ)) *1 // size(y,2)\n\n\"\"\"\n    hinge(ŷ, y)\n\nMeasures the loss given the prediction `ŷ` and true labels `y` (containing 1 or -1). \n[Hinge Loss](https://en.wikipedia.org/wiki/Hinge_loss).\n\"\"\"\nhinge(ŷ, y) = sum(max.(0, 1 .-  ŷ .* y)) *1 // size(y,2)\n", "meta": {"hexsha": "5de5842b2a2507d0f4fd2104ea8b8cdeb16b1963", "size": 3842, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/layers/stateless.jl", "max_stars_repo_name": "visr/Flux.jl", "max_stars_repo_head_hexsha": "77a7606dad3a1bd7789fa301ad9df94cf921d31a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/layers/stateless.jl", "max_issues_repo_name": "visr/Flux.jl", "max_issues_repo_head_hexsha": "77a7606dad3a1bd7789fa301ad9df94cf921d31a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/layers/stateless.jl", "max_forks_repo_name": "visr/Flux.jl", "max_forks_repo_head_hexsha": "77a7606dad3a1bd7789fa301ad9df94cf921d31a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.015625, "max_line_length": 127, "alphanum_fraction": 0.6527850078, "num_tokens": 1381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856297, "lm_q2_score": 0.8418256432832332, "lm_q1q2_score": 0.7751443685548631}}
{"text": "__precompile__()\n\nmodule EgyptianFractions\n\nusing Base.Iterators: repeated\n\nexport efgreedy, efoddgreedy, efharmonic, engelexpand, efengel\n\nfunction _prep(r::Rational)\n  @assert(denominator(r) != 0, \"denominator must be > 0\")\n  rem = abs(big(r))\n  ef = BigInt[]\n  if rem ≥ 1\n    f = floor(rem)\n    rem -= f\n    append!(ef, collect(repeated(1, Int(f))))\n  end\n  return (rem, ef)\nend\n\nfunction _greedyloop!(ef::Vector{BigInt}, r::Rational{BigInt})\n  c = ceil(1//r)\n  push!(ef, c)\n  return r - 1//c\nend\n\n\"\"\"\nPerforms a greedy (Fibonacci–Sylvester) expansion of the given rational number into a sum of fractions of the form `1/a_1 + 1/a_2 + ...`\n\nThis function returns only the denominators of the expansion (i.e., only `[a_1, a_2, ...]`).  If the given rational number `r` satisfies `r ≥ 1`, the first `n` elements of the expansion will be 1, where `n = floor(r)`.  If the given rational number `r` satisfies `r < 0`, all returned denominators will be less than 0, so that the relationship\n\n    r == sum(1 .// efgreedy(r))\n\nis always true.\n\"\"\"\nfunction efgreedy(r::Rational; nmax::Int = typemax(Int))\n  (rem, ef) = _prep(r)\n  i = nmax\n  while rem != 0 && i > 0\n    rem = _greedyloop!(ef, rem)\n    i -= 1\n  end\n  if r < 0\n    ef .*= -1\n  end\n  return ef\nend\n\nefgreedy(r::Real; nmax::Int = typemax(Int)) = efgreedy(Rational(big(r)), nmax=nmax)\n\nfunction _oddgreedyloop!(ef::Vector{BigInt}, r::Rational{BigInt})\n  c = ceil(1//r)\n  if iseven(numerator(c))\n    c += 1\n  end\n  push!(ef, c)\n  return r - 1//c\nend\n\n\"\"\"\nPerforms a greedy (Fibonacci–Sylvester) expansion of the given rational number into a sum of fractions of the form `1/a_1 + 1/a_2 + ...`, but only using odd denominators.\n\nIt can be shown that, for any rational number `x/y` where `y` is odd, you can write this as a finite sum of fractions where all denominators are odd.  This method sometimes produces an expansion with fewer elements than the traditional greedy algorithm.\n\nThis function will throw an exception if the denominator of the rational number supplied is even.\n\nThis function returns only the denominators of the expansion (i.e., only `[a_1, a_2, ...]`).  If the given rational number `r` satisfies `r ≥ 1`, the first `n` elements of the expansion will be 1, where `n = floor(r)`.  If the given rational number `r` satisfies `r < 0`, all returned denominators will be less than 0, so that the relationship\n\n    r == sum(1 .// efoddgreedy(r))\n\nis always true.\n\"\"\"\nfunction efoddgreedy(r::Rational; nmax::Int = typemax(Int))\n  @assert isodd(denominator(r)) \"denominator of rational ($(denominator(r))) must be odd\"\n  (rem, ef) = _prep(r)\n  i = nmax\n  while rem != 0 && i > 0\n    rem = _oddgreedyloop!(ef, rem)\n    i -= 1\n  end\n  if r < 0\n    ef .*= -1\n  end\n  return ef\nend\n\nefoddgreedy(r::Real; nmax::Int = typemax(Int)) = efoddgreedy(Rational(big(r)), nmax=nmax)\n\n\"\"\"\nPerforms a harmonic expansion of the given rational number into a sum of fractions of the form `1/2 + 1/3 + ...`, and concludes the remainder of the expansion using `efgreedy` if the given rational number cannot be represented as a sum in the harmonic sequence.\n\nIf the second argument is specified, the expansion will begin using that value as the first denominator.  In other words, while `efharmonic(r)` will return an array beginning `[2, 3, ...]`, `efharmonic(r, 3)` will return an array beginning `[3, 4, ...]`, and so on.\n\nThis function will throw an exception if the second argument `f ≤ 1`.\n\nThis function returns only the denominators of the expansion (i.e., only `[a_1, a_2, ...]`).  If the given rational number `r` satisfies `r ≥ 1`, the first `n` elements of the expansion will be 1, where `n = floor(r)`.  If the given rational number `r` satisfies `r < 0`, all returned denominators will be less than 0, so that the relationship\n\n    r == sum(1 .// efharmonic(r))\n\nis always true.\n\"\"\"\nfunction efharmonic(r::Rational, first::Int = 2; nmax::Int = typemax(Int))\n  @assert(first ≥ 2, \"harmonic series must start at 2 or greater ($first given)\")\n  (rem, ef) = _prep(r)\n  s = Rational{BigInt}(0)\n  i = big(first)\n  j = nmax\n  while s ≤ rem && j > 0\n    hh = 1//i\n    if s + hh > rem\n      break\n    end\n    push!(ef, i)\n    s += hh\n    i += 1\n    j -= 1\n  end\n  rem -= s\n  while rem != 0 && j > 0\n    rem = _greedyloop!(ef, rem)\n    j -= 1\n  end\n  if r < 0\n    ef .*= -1\n  end\n  return ef\nend\n\nefharmonic(r::Real, first::Int = 2; nmax::Int = typemax(Int)) = efharmonic(Rational(big(r)), first, nmax=nmax)\n\nfunction _engelloop!(ef::Vector{BigInt}, r::Rational{BigInt})\n  c = ceil(1//r)\n  push!(ef, c)\n  return r * c - 1\nend\n\n\"\"\"\nPerforms an Engel expansion of the given rational number into a sum of fractions of the form `1/a + 1/(a*b) + 1/(a*b*c)...`.\n\nThis function returns only the unique denominators of the expansion (i.e., only `[a, b, ...]`).  If the given rational number `r` satisfies `r ≥ 1`, the first `n` elements of the expansion will be 1, where `n = floor(r)`.\n\"\"\"\nfunction engelexpand(r::Rational; nmax::Int = typemax(Int))\n  (rem, ef) = _prep(r)\n  i = nmax\n  while rem != 0 && i > 0\n    rem = _engelloop!(ef, rem)\n    i -= 1\n  end\n  # Convention:  the Engle expansion of a negative number will have ef[1] < 0.\n  # This way, all elements of cumprod(ef) will be negative.\n  if !isempty(ef) && r < 0\n    ef[1] *= -1\n  end\n  return ef\nend\n\nengelexpand(r::Real; nmax::Int = typemax(Int)) = engelexpand(Rational(big(r)), nmax=nmax)\n\n\"\"\"\nPerforms an Engel expansion of the given rational number into a sum of fractions of the form `1/a + 1/(a*b) + 1/(a*b*c)...`.\n\nThis function returns only the denominators of the expansion (i.e., only `[a, a*b, ...]`).  If the given rational number `r` satisfies `r ≥ 1`, the first `n` elements of the expansion will be 1, where `n = floor(r)`.  If the given rational number `r` satisfies `r < 0`, all returned denominators will be less than 0, so that the relationship\n\n    r == sum(1 .// efengel(r))\n\nis always true.\n\"\"\"\nfunction efengel(r::Rational; nmax::Int = typemax(Int))\n  ef = engelexpand(r, nmax=nmax)\n  cumprod!(ef, ef)\n  return ef\nend\n\nefengel(r::Real; nmax::Int = typemax(Int)) = efengel(Rational(big(r)), nmax=nmax)\n\nend # module\n", "meta": {"hexsha": "82279eda0f053dbe3cd5495ceb5911bdfa026069", "size": 6141, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/EgyptianFractions.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/EgyptianFractions.jl-0f160d28-7819-5803-9275-299e9913be39", "max_stars_repo_head_hexsha": "d0992bfc86c2ef42b8d2a5dbb9057942fdbf66d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/EgyptianFractions.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/EgyptianFractions.jl-0f160d28-7819-5803-9275-299e9913be39", "max_issues_repo_head_hexsha": "d0992bfc86c2ef42b8d2a5dbb9057942fdbf66d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/EgyptianFractions.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/EgyptianFractions.jl-0f160d28-7819-5803-9275-299e9913be39", "max_forks_repo_head_hexsha": "d0992bfc86c2ef42b8d2a5dbb9057942fdbf66d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6949152542, "max_line_length": 343, "alphanum_fraction": 0.6617814688, "num_tokens": 1958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8418256492357359, "lm_q1q2_score": 0.7751443667164833}}
{"text": "function qrsolve!(A::AbstractMatrix{T},b::AbstractVector{T}) where {T}\r\n    # Fast least-squares solver for full column rank Hessenberg-like matrices\r\n    m, n = size(A) \r\n    m < n && error(\"Column dimension exceeds row dimension\") \r\n    _, τ = LinearAlgebra.LAPACK.geqrf!(A)\r\n    T <: Complex ? tran = 'C' : tran = 'T'\r\n    LinearAlgebra.LAPACK.ormqr!('L',tran,A,τ,view(b,:,1:1))\r\n    return UpperTriangular(triu(A[1:n,:]))\\b[1:n]\r\nend\r\n\r\nfunction poldeg1(v::Vector{T}) where {T <: Number}\r\n    # Degree of a polynomial plus one.\r\n    n1 = findlast(!iszero,v) # degree(v) + 1\r\n    n1 === nothing && (n1 = 0)\r\n    return n1\r\nend\r\npoldeg(v::Vector{T}) where {T <: Number} = poldeg1(v)-1  # Degree of a polynomial\r\nfunction poldiv(a::Vector{T}, b::Vector{S}) where {T <: Number, S <: Number }\r\n    # Quotient of the exact division of two polynomials a and b.\r\n    # q = poldiv(a,b) returns the quotient q = a/b, which is computed by solving the \r\n    # linear least-square problem ||C(b)*q - a|| = min, where C(b) is the convolution \r\n    # matrix of appropriate size.  \r\n\r\n    na1 = poldeg1(a) # degree(a) + 1\r\n    nb1 = poldeg1(b) # degree(b) + 1\r\n    nb1 == 0 && throw(DivideError())\r\n    na1 < nb1 && error(\"Degree of second polynomial exceeds the degree of first polynomial\")\r\n    a1, b1  = promote(float(a[1:na1]), float(b[1:nb1]))\r\n    #return Matrix(Toeplitz([den;zeros(n1-length(den))],[den[1];zeros(n1-m1)]))\\num[1:n1] \r\n    #return convmtx(b[1:nb1],na1-nb1+1)\\a[1:na1] \r\n    return qrsolve!(convmtx(b1,na1-nb1+1),a1) \r\nend\r\nfunction convmtx(v::Vector{T}, n::Int) where {T <: Number}\r\n\r\n    #   Convolution matrix.\r\n    #   C = convmtx(v,n) returns the convolution matrix C for a vector v. \r\n    #   If q is a column vector of length n, then C*q is the same as conv(v,q). \r\n    \r\n    #   Form C as the Toeplitz matrix \r\n    #   C = Toeplitz([v; zeros(n-1)],[v[1]; zeros(n-1));  put Toeplitz code inline\r\n    \r\n    nv = length(v)-1\r\n    C = zeros(T, n+nv, n)\r\n    @inbounds for j = 1:n\r\n        C[j:j+nv,j] = v  \r\n    end\r\n    return C\r\nend\r\nfunction poldivrem(a::Vector{T}, b::Vector{S}) where {T <: Number, S <: Number }\r\n    # Quotient and remainder of the division of two polynomials a and b.\r\n    # q, r = poldivrem(a,b) returns the quotient q and remainder r such that a = q*b + r.\r\n    na1 = poldeg1(a) # degree(a) + 1\r\n    nb1 = poldeg1(b) # degree(b) + 1\r\n    nb1 == 0 && throw(DivideError())\r\n    \r\n    R = eltype(one(T)/one(S))\r\n\r\n    if na1 < nb1\r\n       return zeros(R, 1), a\r\n    end\r\n    m = nb1-1\r\n    q = zeros(R, na1-m)\r\n    r = R[ a[i] for i in 1:na1 ]\r\n    #r = copy_oftype(num[1:n1],R)\r\n\r\n    @inbounds for i in na1:-1:nb1\r\n        s = r[i] / b[nb1]\r\n        q[i-m] = s\r\n        @inbounds for j in 1:m\r\n            r[i-nb1+j] -= b[j] * s\r\n        end\r\n    end\r\n\r\n    return q, m == 0 ? zeros(R,1) : r[1:m]   \r\nend\r\nfunction polgcdvw(a::Vector{T}, b::Vector{S}; atol::Real = 0, rtol::Real = Base.rtoldefault(float(real(T))), maxnit::Int = 0) where {T <: Number, S <: Number }\r\n    # Greatest common divisor of two polynomials.\r\n    #     polgcdvw(a, b; atol = 0, rtol, maxnit = 0) -> (d, v, w, δ)\r\n    # Compute the greatest common divisor `d` of two polynomials `a` and `b`, and \r\n    # the polynomials v and w such that a = d * v * ka and b = d * w *kb, where ka and kb\r\n    # are scalar scaling factors (ka and kb are not explicitly provided). \r\n    # The accuracy estimate δ is computed as δ = norm([a/ka-d*v; b/kb-d*w]). \r\n    # A SVD-based method adapted from [1] is employed and an iterative accuracy refinement\r\n    # of δ, with a maximum number of maxnit iterations, is additionally performed.\r\n    #  [1] Z. Zeng, The numerical greatest common divisor of univariate polynomials, \r\n    #      in: L. Gurvits, P. Pébay, J.M. Rojas, D. Thompson (Eds.), \r\n    #      Randomization, Relaxation,and Complexity in Polynomial Equation Solving, \r\n    #      Contemporary Mathematics,vol.556,AMS,2011,pp.187–217.\r\n    \r\n    na1 = poldeg1(a) # degree(a) + 1\r\n    nb1 = poldeg1(b) # degree(b) + 1\r\n\r\n    R = eltype(one(T)/one(S))\r\n\r\n    a1, b1  = promote(float(a[1:na1]), float(b[1:nb1]))\r\n\r\n    na1 <= 0 && (return ones(R,1), zeros(R,1), b1, zero(R))\r\n    nb1 <= 0 && (return ones(R,1), a1, zeros(R,1), zero(R))\r\n    a1 = a1/norm(a1)\r\n    b1 = b1/norm(b1)\r\n    switch = (na1 < nb1)\r\n    switch && ((a1, b1, na1, nb1) = (b1, a1, nb1, na1))\r\n\r\n    atol == 0 ? tol = rtol : tol = atol\r\n    # determine the degree of GCD as the nullity of the Sylvester matrix \r\n    nd = na1 + nb1 - 2 - rank([convmtx(a1,nb1-1) convmtx(b1,na1-1)], atol = tol)\r\n    nd == 0 && (switch ? (return [one(R)], b1, a1, zero(R)) : (return [one(R)], a1, b1, zero(R))) \r\n    # determine [w; -v] from an orthogonal/unitary nullspace basis of dimension 1 \r\n    # of a reduced Sylvester matrix using the last row of Vt from its (partial) SVD \r\n    _, sv, Vt = LAPACK.gesvd!('N', 'A', [convmtx(a1,nb1-nd) convmtx(b1,na1-nd)])\r\n    k = na1 + nb1 -2*nd - count(x -> x > tol, sv) # expected nullity k = 1\r\n    k == 1 || error(\"GCD computation failure\")\r\n    wv = Vt[end,:] \r\n    # wv = LAPACK.gesvd!('N', 'A', [convmtx(a1,nb1-nd) convmtx(b1,na1-nd)])[3][end,:] \r\n    eltype(wv) <: Complex && (wv = conj(wv))  \r\n    v = -wv[nb1-nd+1:end]\r\n    w = wv[1:nb1-nd]\r\n    # determine the GCD d with high accuracy as the solution of a well-conditioned \r\n    # linear least-squares problem\r\n    # d = convmtx(w,nd+1)\\b1 \r\n    # d = [convmtx(v,nd+1) ; convmtx(w,nd+1)] \\ [a1; b1]\r\n    d = qrsolve!([convmtx(v,nd+1) ; convmtx(w,nd+1)],[a1; b1])\r\n    if maxnit > 0\r\n       d, v, w, δ = gcdvwupd(a1, b1, d, v, w, maxnit = maxnit)\r\n    else\r\n       δ = norm( [a1; b1] - [ conv(v,d); conv(w,d) ])\r\n    end\r\n\r\n    switch ? (return d, w, v, δ) : (return d, v, w, δ)\r\nend \r\nfunction gcdvwupd(a::Vector{T}, b::Vector{T}, d::Vector{T}, v::Vector{T}, w::Vector{T}; maxnit::Int = 10) where {T <: Number}\r\n    # Iterative refinement of the accuracy of the greatest common divisor of two polynomials.\r\n    #     gcdvwupd(a, b, d, v, w; maxnit = 0) -> (dupd, vupd, wupd, δ)\r\n    # Given the polynomials a and b, and a triple of polynomials (d, v, w) such that \r\n    # `d` is an approximation of a greatest common divisor of `a` and `b`, and \r\n    # v and w are approximate quotients of a/d and b/d, respectively, compute the updated triple \r\n    # (dupd, vupd, wupd) which minimizes the accuracy estimate δ = norm([a-dupd*vupd; b-dupd*wupd]).\r\n    # A maximum number of maxnit iterations are performed using the Gauss-Newton iteration method, \r\n    # in the form proposed in [1].\r\n    #\r\n    #  [1] Z. Zeng, The numerical greatest common divisor of univariate polynomials, \r\n    #      in: L. Gurvits, P. Pébay, J.M. Rojas, D. Thompson (Eds.), \r\n    #      Randomization, Relaxation,and Complexity in Polynomial Equation Solving, \r\n    #      Contemporary Mathematics,vol.556,AMS,2011,pp.187–217.\r\n\r\n    na1 = length(a) \r\n    nb1 = length(b) \r\n    nd1 = length(d)\r\n    nv1 = length(v)\r\n    nw1 = length(w)\r\n    na1 == nd1+nv1-1 || error(\"Incompatible dimensions between a, d and v\")\r\n    nb1 == nd1+nw1-1 || error(\"Incompatible dimensions between b, d and w\")\r\n\r\n    h = d/norm(d)^2\r\n    f = [a;b;fill(one(T),1)]\r\n    fh = [conv(v,d); conv(w,d); fill(dot(h,d),1)]\r\n    Δf = f-fh;\r\n    δ = norm(Δf)\r\n    d0 = copy(d); v0 = copy(v); w0 = copy(w);\r\n    nvw1 = nv1+nw1\r\n    ndvw1 = nd1+nvw1 \r\n    nab1 = na1+nb1\r\n    Jh = [zeros(nab1,ndvw1); zeros(1,nvw1) h' ]\r\n\r\n    j1 = 1:nv1\r\n    j2 = nv1+1:nvw1\r\n    j3 = nvw1+1:ndvw1\r\n    i1 = 1:nv1+nd1-1\r\n    i2 = nv1+nd1:nvw1+2*nd1-2\r\n    Jh11 = view(Jh,i1,j1)\r\n    Jh22 = view(Jh,i2,j2)\r\n    Jh13 = view(Jh,i1,j3)\r\n    Jh23 = view(Jh,i2,j3)\r\n\r\n    \r\n    for it = 1:maxnit\r\n        # Jh = [ convmtx(d0,nv1)          0     convmtx(v0,nd1) ] \r\n        #      [  0             convmtx(u0,nw1) convmtx(w0,nd1) ]\r\n        #      [  0                       0            h'       ] \r\n        Jh11[:,:] = convmtx(d0,nv1)\r\n        Jh22[:,:] = convmtx(d0,nw1)\r\n        Jh13[:,:] = convmtx(v0,nd1) \r\n        Jh23[:,:] = convmtx(w0,nd1) \r\n        # Δz = Jh\\Δf;   # this does not exploit the zero structure\r\n        Δz = qrsolve!(copy(Jh),copy(Δf));  # this is probably the fastest\r\n        # Δz = qr(Jh)\\Δf;  # this is usually slower, but faster for full matrices\r\n        v1 = v0 + Δz[j1];\r\n        w1 = w0 + Δz[j2];\r\n        d1 = d0 + Δz[j3];\r\n        fh1 = [conv(v1,d1); conv(w1,d1); fill(dot(h,d1),1)];\r\n        Δf1 = f-fh1;\r\n        δ1 = norm(Δf1)\r\n        if δ1 < δ\r\n           d0 = copy(d1); v0 = copy(v1); w0 = copy(w1); δ = copy(δ1); Δf = copy(Δf1);\r\n        else\r\n           break\r\n        end\r\n    end\r\n    return d0, v0, w0, δ \r\nend\r\nfunction pollcm(a::Vector{T}, b::Vector{S}; atol::Real = 0, rtol::Real = Base.rtoldefault(float(real(T))), maxnit::Int = 10) where {T <: Number, S <: Number }\r\n    # Least common multiple of two polynomials.\r\n    #     m = pollcm(a,b; atol = 0, rtol, maxnit = 0) \r\n    # Compute the least common multiple `m` of two polynomials `a` and `b`. Employ iterative refinement of\r\n    # the accuracy of GCD(a,b) if maxnit > 0. \r\n      \r\n    na1 = poldeg1(a) # degree(a) + 1\r\n    nb1 = poldeg1(b) # degree(b) + 1\r\n    \r\n    na1 == 0 && (return zeros(T,1))\r\n    nb1 == 0 && (return zeros(S,1))\r\n    na1 == 1 && (return b)\r\n    nb1 == 1 && (return a)\r\n     \r\n    return conv(a, polgcdvw(a, b, atol = atol, rtol = rtol, maxnit = maxnit)[3])\r\nend    \r\nfunction conv(a::Vector{T}, b::Vector{S}) where {T <: Number, S <: Number }\r\n    # Convolution of two vectors (or product of two polynomials).\r\n    # c = conv(a,b) returns the convolution of vectors a and b.\r\n\r\n    na1 = length(a) \r\n    nb1 = length(b) \r\n\r\n    R = promote_type(T, S)\r\n    c = zeros(R, na1 + nb1 - 1)\r\n    for i in 1:na1, j in 1:nb1\r\n        @inbounds c[i + j - 1] += a[i] * b[j]\r\n    end\r\n    return c\r\nend   \r\nfunction polcoeffval(r::AbstractVector{T},val::Number) where {T}\r\n    # Compute the coefficients of a polynomial from its roots and evaluate the polynomial\r\n    # for a given value of its argument. Both are equal to one for an empty vector r.\r\n    T1 = promote_type(T,eltype(val))\r\n    n = length(r)\r\n    c = zeros(T1, n+1)\r\n    ONE = one(T1)\r\n    c[1] = ONE\r\n    pval = ONE\r\n    for j = 1:n\r\n        pval = pval*(val-r[j])\r\n        for i = j:-1:1\r\n            c[i+1] = c[i+1]-r[j]*c[i]\r\n        end\r\n    end\r\n    return reverse(c), pval\r\n end\r\n", "meta": {"hexsha": "526e12f3edd59ce86e318d472e5a1bfdb94feb14", "size": 10347, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/poltools.jl", "max_stars_repo_name": "baggepinnen/MatrixPencils.jl", "max_stars_repo_head_hexsha": "c16b7415bd2765b452f29b6977bcc4f0566003a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/poltools.jl", "max_issues_repo_name": "baggepinnen/MatrixPencils.jl", "max_issues_repo_head_hexsha": "c16b7415bd2765b452f29b6977bcc4f0566003a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/poltools.jl", "max_forks_repo_name": "baggepinnen/MatrixPencils.jl", "max_forks_repo_head_hexsha": "c16b7415bd2765b452f29b6977bcc4f0566003a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7217741935, "max_line_length": 160, "alphanum_fraction": 0.5608388905, "num_tokens": 3615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7751443630624814}}
{"text": "export sinc_interpolate, sinc_interpolate_sum, downsample\nexport resample\n\n\n\"\"\"\n    resample(arr, new_size [, normalize]; take_real=true, boundary_handling=true)\n\nCalculates the `sinc` interpolation of an `arr` on a new array size\n`new_size`.\nIt is a re-evaluation of the Fourier series at new grid points.\n`new_size` can be arbitrary. Each dimension is then independently either up or downsampled.\n\nThis method is based on FFTs and therefore implicitly assumes periodic\nboundaries and a finite frequency support.\n`normalize=true` by default multiplies by an appropriate factor so that \nthe average intensity stays the same.\nIf `size(new_size)[i] > size(arr)[i]`, we apply zero padding in Fourier space.\nIf `size(new_size)[i] < size(arr)[i]`, we cut out a centered part of the\nFourier spectrum.\n\nWe apply some tricks at the boundary to increase accuracy of highest frequencies. \nIf you set the keyword argument `boundary_handling=false` you turn this boundary handling off.\nThis can increase inaccuracies for the highest frequency (not a big problem in real images/signals).\nHowever, `resample` is then faster on CPUs and especially on CUDA GPUs.\n\n# Examples\n```jldoctest\njulia> resample([1.0, 2.0, 3.0, 4.0], 8)\n8-element Array{Float64,1}:\n 1.0\n 1.085786437626905\n 2.0\n 2.5\n 3.0\n 3.914213562373095\n 4.0\n 2.5\n\njulia> resample([1.0  2.0; 3.0 4.0], (4,4))\n4×4 Array{Float64,2}:\n 1.0  1.5  2.0  1.5\n 2.0  2.5  3.0  2.5\n 3.0  3.5  4.0  3.5\n 2.0  2.5  3.0  2.5\n\njulia> resample([1.0, 0.0, 1.0, 0.0, 1.0, 0.0], (3))\n3-element Array{Float64,1}:\n 0.5\n 0.5\n 0.5\n\njulia> resample([1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0], (6))\n6-element Array{Float64,1}:\n  1.0\n -0.3333333333333333\n  1.0\n -0.3333333333333333\n  1.0\n -0.3333333333333333\n\njulia> resample([1 2 3; 4 5 6], (3, 2))\n3×2 Array{Float64,2}:\n 1.0   3.0\n 3.25  5.25\n 3.25  5.25\n```\n\"\"\"\nfunction resample(arr::AbstractArray{T, N}, new_size, normalize=true; take_real=true, boundary_handling=true) where {T<:Real, N}\n\n    if typeof(new_size) <: Number\n        new_size = Tuple(new_size)\n    end\n\n    # go to fourier space\n    arr_f = fftshift(fft(arr))\n    # create fourier space new array\n    \n    # the idea is the following\n    # 1) first we handle all the upsampling dimensions. By doing so, we leave the size\n    # or increase it. downsampling is done afterwards. Hence we use max to create \n    # a new array which is a least as large as the initial one or larger\n    # 2) we then handle all the downsampling dimensions\n    new_size_interp = Tuple(max(x[1], x[2]) for x in zip(size(arr), new_size))\n    out_f = similar(arr_f, new_size_interp)\n    fill!(out_f, zero(eltype(arr_f)))\n\n    # change arr_f to be a hermitian array because we want a purely real result\n    # after iffting\n   \n    # in that case, make_hermitian is useless since we only cut out\n    if boundary_handling && ~(all(new_size < size(arr)))\n        arr_f = make_hermitian(arr_f)\n    end\n\n    # it can happen, that arr_f was now padded with an extra row\n    # but there is no extra column in out_f\n    # therefore, cut it\n    inds = []\n    for (a, o) in zip(size(arr_f), size(out_f))\n        push!(inds, 1:min(a, o))\n    end\n    arr_f = arr_f[inds...]\n    \n    # set the old array into the new 0-padded array\n    center_set!(out_f, arr_f)\n    arr_f = out_f\n\n    # part 2). We handle now the downsampling\n    # if the new_size[d] is even, we need to add the highest positive frequency\n    # of the initial spectrum\n    # to the highest negative one. In that way, we get a purely real result\n    if boundary_handling\n        arr_f = add_high_frequencies(size(arr_f), arr_f, new_size, N)\n    end\n    # return arr_out_f\n\n    # do the cutting in Fourier space\n    arr_f_n = center_extract(arr_f, new_size)\n    # back to real space \n    arr_out = ifft(ifftshift(arr_f_n))\n    \n\n    if normalize\n        arr_out .*= length(arr_out) ./ length(arr)\n    end\n    if take_real\n        return real(arr_out)\n    else\n        return arr_out\n    end\nend\n\n # for a complex signal: split into real and imaginary part and solve for each \n # part individually\nfunction resample(arr::AbstractArray{T}, new_size, normalize=true) where T<:Complex\n    # array of same shape but with Complex element type\n    arr_r = resample(real(arr), new_size, normalize)\n    arr_i = 1im .* resample(imag(arr), new_size, normalize)\n    return arr_r .+ arr_i\nend\n\n\n\"\"\"\n    sinc_interpolate_sum(arr, new_length)\n\nCalculates the `sinc` interpolation of an 1D `arr` on a new array size\n`new_size`. \nThis method is slow, because of an explicit sum evalulation and\nnot a FFT based evaluation.\n\n# Examples\n```jldoctest\njulia> sinc_interpolate_sum([1.0, 2.0, 3.0, 4.0], 8)\n8-element Array{Float64,1}:\n 1.0\n 1.7825353626292277\n 2.0\n 2.1220659078919377\n 3.0\n 4.1592491794681985\n 4.0\n 2.0735615442829793\n```\n\"\"\"\nfunction sinc_interpolate_sum(arr, new_size)\n    out = zeros(eltype(arr), new_size)\n    T = 1 / size(arr)[1]\n    t_arr = range(0, 1.0, length=size(out)[1]+1)[1:size(out)[1]]\n    for (j, t) in enumerate(t_arr)\n        v = zero(eltype(arr))\n        for n = 1:size(arr)[1] \n            v += arr[n] * sinc((t - (n-1) * T) / T)\n        end\n        out[j] = v \n    end\n    return out\nend\n", "meta": {"hexsha": "eb813312a8703de10d58ebd0d3a7538e1c77b537", "size": 5168, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sinc_interpolation.jl", "max_stars_repo_name": "roflmaostc/FFTInterpolations.jl", "max_stars_repo_head_hexsha": "aa71cf741f0123ca4ec51460096eb895db39b13e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-01-04T12:26:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-14T22:15:10.000Z", "max_issues_repo_path": "src/sinc_interpolation.jl", "max_issues_repo_name": "roflmaostc/FFTInterpolations.jl", "max_issues_repo_head_hexsha": "aa71cf741f0123ca4ec51460096eb895db39b13e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-01-07T10:56:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-11T20:49:33.000Z", "max_forks_repo_path": "src/sinc_interpolation.jl", "max_forks_repo_name": "roflmaostc/FFTResampling.jl", "max_forks_repo_head_hexsha": "aa71cf741f0123ca4ec51460096eb895db39b13e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-07T10:44:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-07T10:44:31.000Z", "avg_line_length": 29.0337078652, "max_line_length": 128, "alphanum_fraction": 0.6745356037, "num_tokens": 1698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7751443630567916}}
{"text": "\"\"\"\nsolve the 1D linear advection equation\n```math\n∂q/∂t=−u∂q/∂x\n```\nin a periodic domain, where ``q`` is the quantity being advected,\n``t`` is time, ``x`` is the spatial coordinate and ``u`` is the velocity,\nwhich is constant with ``x``. \n\"\"\"\nfunction lax_wendroff!(nt::Int, c, q_init::AbstractVector{T}, q::AbstractVector{T}) where T\n    nx = length(q)\n    flux = zeros(T, nx-1)   # Fluxes between boxes\n    @inbounds for i=1:nx\n        q[i] = q_init[i] # Initialize q\n    end\n    @inbounds for j=1:nt  # Main loop in time\n        for i=1:nx-1\n            flux[i] = 0.5*c*(q[i]+q[i+1]+c*(q[i]-q[i+1]))\n        end\n        for i=2:nx-1\n            q[i] += flux[i-1]-flux[i]\n        end\n        q[1] = q[nx-1]; q[nx] = q[2] # Treat boundary conditions\n    end\n    return q\nend\n\nusing Random\nRandom.seed!(2)\nq_init = randn(100)\nq = zeros(100)\n@show lax_wendroff!(2000, 1.0, q_init, zero(q_init))\nusing BenchmarkTools\n@benchmark lax_wendroff!(2000, 1.0, $q_init, x) setup=(x=zero(q_init))\n@time lax_wendroff!(2000, 1.0, q_init, q)\n\nusing NiLang\n@i function i_lax_wendroff!(nt::Int, c, q_init::AbstractVector{T}, q::AbstractVector{T},\n        cache::AbstractMatrix{T}) where T\n    nx ← length(q)\n    @inbounds for i=1:nx\n        q[i] += q_init[i] # Initialize q\n    end\n    @inbounds for j=1:nt  # Main loop in time\n        for i=1:nx-1\n            @routine begin\n                @zeros T anc1 anc2 anc3\n                anc1 += 0.5 * c\n                anc2 += q[i] - q[i+1]\n                anc3 += q[i] + q[i+1]\n                anc3 += c * anc2\n            end\n            cache[i,j] += anc1 * anc3\n            ~@routine\n        end\n        for i=2:nx-1\n            q[i] += cache[i-1,j]-cache[i,j]\n        end\n        # Treat boundary conditions\n        cache[nx,j] += q[nx-1]\n        SWAP(q[1], cache[nx,j])\n        cache[nx+1,j] += q[2]\n        SWAP(q[nx], cache[nx+1,j])\n    end\nend\nnt = 2000\ni_lax_wendroff!(nt, 1.0, q_init, zero(q_init), zeros(length(q_init)+1,nt))\n", "meta": {"hexsha": "77fb8549f9e81ac43d23a7a345e1106ff7d25790", "size": 1968, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/lax_wendroff.jl", "max_stars_repo_name": "johnnychen94/NiLang.jl", "max_stars_repo_head_hexsha": "81fbe77d1f499003153857be8367de2024c797a5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/lax_wendroff.jl", "max_issues_repo_name": "johnnychen94/NiLang.jl", "max_issues_repo_head_hexsha": "81fbe77d1f499003153857be8367de2024c797a5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/lax_wendroff.jl", "max_forks_repo_name": "johnnychen94/NiLang.jl", "max_forks_repo_head_hexsha": "81fbe77d1f499003153857be8367de2024c797a5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9411764706, "max_line_length": 91, "alphanum_fraction": 0.5411585366, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7751073416821938}}
{"text": "function fit(m::MultinomialNB, X::Matrix{Int64}, y::Vector{C}) where C\n    ensure_data_size(X, y)\n    for j=1:size(X, 2)\n        c = y[j]\n        m.c_counts[c] += 1\n        m.x_counts[c] .+= X[:, j]\n        m.x_totals += X[:, j]\n        m.n_obs += 1\n    end\n    return m\nend\n\n\"\"\"Calculate log P(x|C)\"\"\"\nfunction logprob_x_given_c(m::MultinomialNB, x::Vector{Int64}, c::C) where C\n    x_priors_for_c = m.x_counts[c] ./ sum(m.x_counts[c])\n    x_probs_given_c = x_priors_for_c .^ x\n    logprob = sum(log(x_probs_given_c))\n    return logprob\nend\n\n\"\"\"Calculate log P(x|C)\"\"\"\nfunction logprob_x_given_c(m::MultinomialNB, X::Matrix{Int64}, c::C) where C\n    x_priors_for_c = m.x_counts[c] ./ sum(m.x_counts[c])\n    x_probs_given_c = x_priors_for_c .^ X\n    logprob = sum(log.(x_probs_given_c), dims=1)\n    return dropdims(logprob, dims=1)\nend\n", "meta": {"hexsha": "6d8a7e165cd87b059a93c0aa0a6cae39f149f8c3", "size": 836, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/multinomial.jl", "max_stars_repo_name": "pazzo83/NaiveBayes.jl", "max_stars_repo_head_hexsha": "3bd26082e09e3c940743b2c51f67635ed4081e6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2015-09-24T05:13:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T14:36:08.000Z", "max_issues_repo_path": "src/multinomial.jl", "max_issues_repo_name": "pazzo83/NaiveBayes.jl", "max_issues_repo_head_hexsha": "3bd26082e09e3c940743b2c51f67635ed4081e6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 50, "max_issues_repo_issues_event_min_datetime": "2016-01-21T10:42:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T19:45:38.000Z", "max_forks_repo_path": "src/multinomial.jl", "max_forks_repo_name": "pazzo83/NaiveBayes.jl", "max_forks_repo_head_hexsha": "3bd26082e09e3c940743b2c51f67635ed4081e6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2015-07-01T02:04:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T13:21:13.000Z", "avg_line_length": 29.8571428571, "max_line_length": 76, "alphanum_fraction": 0.6279904306, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391600697869, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.775107338053326}}
{"text": "using DifferentialEquations\nusing Plots\n\n\n# BM model for beta(t): d beta(t) = beta(t) d W(t)\n# Function to compute rates of change \nspsir_bm = function(du, u, p, t)\n    S = u[1]\n    I = u[2]\n    R = u[3]\n    beta = max(0., u[4])\n    \n    N = S + I + R\n    gamma = p[1] \n    \n    du[1] = -beta * S * I / N\n    du[2] = beta * S * I / N - gamma * I\n    du[3] = gamma * I\n    du[4] = 0.\nend\n\n# Function to add noise\nsigma_spsir = function(du, u, p, t )\n    sigma = p[2]\n    \n    du[1] = 0.\n    du[2] = 0.\n    du[3] = 0.\n    du[4] = sigma \nend\n\n# BM for logbeta(t), with drift \nspsir_logbm_drift = function(du, u, p, t)\n    S = u[1]\n    I = u[2]\n    R = u[3]\n    beta = exp( u[4] )\n    \n    N = S + I + R\n    gamma = p[1] \n    alpha = p[3]\n    \n    du[1] = -beta * S * I / N\n    du[2] = beta * S * I / N - gamma * I\n    du[3] = gamma * I\n    du[4] = -alpha * I\nend\n\n# set random seed\nsrand( 1111 )\n\n## Simulation of BM model \n# starting conditions\nu0 = [50.;1.0;0.0;2.0]\ntspan = (0.0,10.0)\n# parameters gamma sigma \np = [1.; 1.]\nspsir_bm_prob = SDEProblem(spsir_bm, sigma_spsir, u0, tspan, p)\nspsir_bm_sol = solve(spsir_bm_prob)\n\n## Simulation of log-BM with drift model \n\n# starting condtions \nu0 = [50.;1.0;0.0;log(3.) ]\ntspan = (0.0,10.0)\n# parameters gamma sigma alpha\np = [1.; 1.; 0.1]\nspsir_logbm_drift_prob = SDEProblem(spsir_logbm_drift, sigma_spsir, u0, tspan, p)\nspsir_logbm_drift_sol = solve(spsir_logbm_drift_prob)\n\n## Plotting for BM model \n# Plot evolution of number infected\nplot( spsir_bm_sol , vars = 2 )\n\n# Plot evolution of transmission rate \nplot( spsir_bm_sol , vars = 4 )\n\n## Plotting for BM with drift model \n# Plot evolution of number infected\nplot( spsir_logbm_drift_sol , vars = 2 )\n\n# Plot evolution of transmission rate \nplot( spsir_logbm_drift_sol , vars = 4 )\n", "meta": {"hexsha": "6e34be8f047cd1876f56907c41a3661907a44ba8", "size": 1785, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/time_varying_parameters/semiparametric_sir.jl", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/time_varying_parameters/semiparametric_sir.jl", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/time_varying_parameters/semiparametric_sir.jl", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 21.25, "max_line_length": 81, "alphanum_fraction": 0.593837535, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7751073342046261}}
{"text": "\"\"\"\n    euler_method(f, x0, span, h=1.0e-2)\n\nCalculate the solution to a differential equation using forward euler method.\n\"\"\"\nfunction euler_method(f, x0, span, h=1.0e-2)\n    s, e = span\n    steps = floor((e - s) / h) |> Int\n    x = Vector{Float64}(undef, steps)\n\tt = Vector{Float64}(undef, steps)\n    x[1] = x0\n\tt[1] = 0\n    for i in 1:(steps - 1)\n        x[i + 1] = x[i] + h * f(x[i], t[i])\n\t\tt[i + 1] = t[i] + h\n    end\n    return x, t\nend\n", "meta": {"hexsha": "5344f13c8b725f870800cd18935edd5ac69fd940", "size": 444, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/euler_method.jl", "max_stars_repo_name": "KohRongSoon/Julia", "max_stars_repo_head_hexsha": "e0276ab9224e191452f7932343f8b24ea8625eea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 190, "max_stars_repo_stars_event_min_datetime": "2021-06-06T10:00:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:00:33.000Z", "max_issues_repo_path": "src/math/euler_method.jl", "max_issues_repo_name": "KohRongSoon/Julia", "max_issues_repo_head_hexsha": "e0276ab9224e191452f7932343f8b24ea8625eea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 82, "max_issues_repo_issues_event_min_datetime": "2021-06-09T14:08:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:31:04.000Z", "max_forks_repo_path": "src/math/euler_method.jl", "max_forks_repo_name": "KohRongSoon/Julia", "max_forks_repo_head_hexsha": "e0276ab9224e191452f7932343f8b24ea8625eea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 70, "max_forks_repo_forks_event_min_datetime": "2021-06-06T15:14:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T09:19:17.000Z", "avg_line_length": 23.3684210526, "max_line_length": 77, "alphanum_fraction": 0.5472972973, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526934, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7751073325733855}}
{"text": "include(\"utils.jl\")\n\n\"\"\"\nComputes the jacobian of a layer `l` with respect to `wrt`, evaluated at the\npoint `x`, using 2nd order finite differences of precision `h`. The resulting\nmatrix contains the entries of `wrt` along the column and the entries of `l`'s\noutput along the rows, e.g.:\n\n    J_{i,j} = ∂_i f_j (x)\n\nThe flattening of `wrt` and `l`'s output happens in column-major order.\nExample:\n\n    x = FloatX[0 1 2]\n    l = xavier!(Linear{FloatX}(1,1))\n    Jw = jacobian_fwd(l, x, l.w, 1e-5)\n    Jx = jacobian_fwd(l, x, x, 1e-5)\n\"\"\"\nfunction jacobian_fwd(l, x, wrt, h=0)\n    out = fprop!(l, x)\n    jacobian = Array(eltype(out), (length(out), length(wrt)))\n\n    # Slightly perturb (\"wiggle\") each parameter individually.\n    for (i,idx) in enumerate(eachindex(wrt))\n        orig = wrt[idx]\n\n        # See https://codewords.recurse.com/issues/four/hack-the-derivative\n        # and the link to lecture notes therein.\n        eff_h = h == 0 ? √eps(typeof(orig)) * max(abs(orig), one(orig)) : h\n\n        wrt[idx] = orig + eff_h\n        right = vec(fprop!(l, x))\n\n        wrt[idx] = orig - eff_h\n        left = vec(fprop!(l, x))\n\n        wrt[idx] = orig\n        jacobian[:,i] = (right - left)/2eff_h\n    end\n\n    jacobian\nend\n\n\njacobian_fwd(l, x) = jacobian_fwd(l, x, x)\n\n\"\"\"\nUses backprop to compute the jacobian of a layer `l` with respect to `wrt`,\nevaluated at the point `x`. The resulting matrix contains the entries of `wrt`\nalong the column and the entries of `l`'s output along the rows, e.g.:\n\n    J_{i,j} = ∂_i f_j (x)\n\nThe flattening of `wrt` and `l`'s output happens in column-major order.\nThe last parameter, `dwrt` is the buffer of the layer containing the\nderivative. This should be automated somehow in the future.\n\nExample:\n\n    x = FloatX[0 1 2]\n    l = xavier!(Linear{FloatX}(1,1))\n    Jw = jacobian_backward(l, x, l.w, l.dw)\n    Jx = jacobian_backward(l, x, x, nothing)\n\"\"\"\nfunction jacobian_bwd(l, x, wrt, dwrt)\n    out = fprop!(l, x)\n    jacobian = Array(eltype(out), (length(out), length(wrt)))\n\n    # Set each output to 1, individually, and backprop from it.\n    for (i,idx) in enumerate(eachindex(out))\n        dout = zeros(out)\n        dout[idx] = 1\n\n        zero_grads!(l)\n\n        din = bprop!(l, dout)\n        if is(wrt, x)\n            jacobian[i,:] = vec(din)\n        else\n            jacobian[i,:] = vec(dwrt)\n        end\n    end\n\n    jacobian\nend\n\njacobian_bwd(l, x) = jacobian_bwd(l, x, x, nothing)\n", "meta": {"hexsha": "57bfa6091ad512d9f73755c3dc433c049df346a4", "size": 2431, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jacobian.jl", "max_stars_repo_name": "lucasb-eyer/Backprop.jl", "max_stars_repo_head_hexsha": "410aceee72445ebef3e91453050a000d6a25ed28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-02-17T14:32:54.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-17T14:32:54.000Z", "max_issues_repo_path": "jacobian.jl", "max_issues_repo_name": "lucasb-eyer/Backprop.jl", "max_issues_repo_head_hexsha": "410aceee72445ebef3e91453050a000d6a25ed28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jacobian.jl", "max_forks_repo_name": "lucasb-eyer/Backprop.jl", "max_forks_repo_head_hexsha": "410aceee72445ebef3e91453050a000d6a25ed28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.625, "max_line_length": 78, "alphanum_fraction": 0.6170300288, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7751073307955901}}
{"text": "\"Computes Gregory-type quadrature rules.\"\nmodule Gregory\n\nexport integrate \n\n\"\"\"\n    B = calcBernoulli(n)\n\nReturn the `n`th Bernoulli number.  Follows the convention that `n=1` \nBernoulli number is equal to -1/2.\n\"\"\"\nfunction calcBernoulli(n)\n    A = Vector{Rational{BigInt}}(undef, n + 1)\n    for m = 0:n\n        A[m + 1] = 1 // (m + 1)\n        for j = m:-1:1\n            A[j] = j * (A[j] - A[j + 1])\n        end\n    end\n    if n == 1\n        return -A[1]\n    else\n        return A[1]\n    end\nend\n\n\"\"\"\n    w = calcBoundaryWeights(numbnd, order)\n\nCompute the boundary weights for a Gregory rule of order `order` that using \n`numbnd` boundary points.\n\"\"\"\nfunction calcBoundaryWeights(numbnd::Int, order::Int)\n    @assert( numbnd >= order-1,\n             \"number of boundary nodes must be larger than order-1\")\n    # Form the linear system to solve\n    A = zeros(Rational{BigInt}, order-1, numbnd)\n    b = zeros(Rational{BigInt}, order-1)\n    for j = 1:order-1\n        for i = 1:numbnd \n            A[j,i] = j*(numbnd - (i-1))^(j-1)\n        end\n        b[j] = numbnd^j - ((-1)^j)*calcBernoulli(j)\n    end\n    w = A\\b \n    return w\nend\n\n\"\"\"\n    val = integrate(data, numbnd, order[, h=1.0])\n\nIntegrate uniformly spaced `data` using a Gregory quadrature rule of order \n`order` with `numbnd` boundary points.  The mesh spacing is defined by `h`.\n\"\"\"\nfunction integrate(data::Array{T,1}, numbnd::Int, order::Int;\n                   h::T=one(T)) where {T<:Number}\n    @assert( size(data,1) >= 2*numbnd,\n             \"number of data points must be larger than 2*numbnd\")\n    w = calcBoundaryWeights(numbnd, order)\n    integral = zero(T)\n    for i = 1:numbnd \n        integral += w[i]*(data[i] + data[end-i+1])\n    end\n    for i = numbnd+1:size(data,1)-numbnd\n        integral += data[i]\n    end \n    return integral*h\nend\n\nend # module Gregory", "meta": {"hexsha": "5c663d67d9354df188aec7421cd3430e599b4671", "size": 1835, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lorenz/gregory.jl", "max_stars_repo_name": "jehicken/high-order-and-chaos", "max_stars_repo_head_hexsha": "dad3576698956f99f65fe630fe0c0c27a7ff2eac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lorenz/gregory.jl", "max_issues_repo_name": "jehicken/high-order-and-chaos", "max_issues_repo_head_hexsha": "dad3576698956f99f65fe630fe0c0c27a7ff2eac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lorenz/gregory.jl", "max_forks_repo_name": "jehicken/high-order-and-chaos", "max_forks_repo_head_hexsha": "dad3576698956f99f65fe630fe0c0c27a7ff2eac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2142857143, "max_line_length": 76, "alphanum_fraction": 0.5891008174, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526934, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7751073307223129}}
{"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 9daa72fd-1145-4733-a21e-bd209367380a\nusing Pkg; Pkg.develop(path=\"..\"); Pkg.activate(\"..\")\n\n# ╔═╡ 947fbdc9-3c48-44f3-b4d3-183f70e2194e\nusing LinearAlgebra\n\n# ╔═╡ a465636e-bc12-4e8f-9db2-1a20ea771504\nbegin\n\t𝐱 = rand(100, 3)\n\t𝐱 = hcat(ones(size(𝐱, 1)), 𝐱)\n\ty = 𝐱 * [1, 2, 3, 4] + 1e-3randn(size(𝐱, 1))\nend;\n\n# ╔═╡ 833c56c2-d2ab-4f94-968b-b5771c9fa945\nfunction irls(𝐱, y; p=2, n_iter=100)\n\tw = ones(size(𝐱, 1))\n\t𝐰 = diagm(w)\n\tβ = inv(𝐱' * 𝐰 * 𝐱) * 𝐱' * 𝐰 * y\n\t\n\tif p == 2\n\t\treturn β\n\tend\n\t\n\tfor _ in 1:n_iter\n\t\tw = abs.(y - 𝐱 * β).^(p-2)\n\t\t𝐰 = diagm(w)\n\t\tβ = inv(𝐱' * 𝐰 * 𝐱) * 𝐱' * 𝐰 * y\n\tend\n\t\n\treturn β\nend\n\n# ╔═╡ 2c663777-b6e3-42b2-a279-d7b42dd27d70\nirls(𝐱, y, p=4, n_iter=10)\n\n# ╔═╡ Cell order:\n# ╟─9daa72fd-1145-4733-a21e-bd209367380a\n# ╠═947fbdc9-3c48-44f3-b4d3-183f70e2194e\n# ╠═a465636e-bc12-4e8f-9db2-1a20ea771504\n# ╠═833c56c2-d2ab-4f94-968b-b5771c9fa945\n# ╠═2c663777-b6e3-42b2-a279-d7b42dd27d70\n", "meta": {"hexsha": "04018ba6cc62f0dfe9f661ad7904e12f702d5fb8", "size": 985, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "IterativeReweightedLeastSquares/notebook/irls.jl", "max_stars_repo_name": "foldfelis/ML101.jl", "max_stars_repo_head_hexsha": "b4b217ac4af88ba460ec26c5c8a1ce322edae64a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-02-23T05:48:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-23T11:52:24.000Z", "max_issues_repo_path": "IterativeReweightedLeastSquares/notebook/irls.jl", "max_issues_repo_name": "foldfelis/ML101.jl", "max_issues_repo_head_hexsha": "b4b217ac4af88ba460ec26c5c8a1ce322edae64a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-02-22T21:59:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-05T07:29:55.000Z", "max_forks_repo_path": "IterativeReweightedLeastSquares/notebook/irls.jl", "max_forks_repo_name": "foldfelis/ML101.jl", "max_forks_repo_head_hexsha": "b4b217ac4af88ba460ec26c5c8a1ce322edae64a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-28T07:04:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-28T07:04:06.000Z", "avg_line_length": 20.5208333333, "max_line_length": 53, "alphanum_fraction": 0.6324873096, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7751009944703854}}
{"text": "# This script solves an elliptic partial differential equation\n\nusing Printf\nusing LinearAlgebra\n\n# Define the paths\nCURRENT_DIR = @__DIR__\nROOT_DIR = basename(CURRENT_DIR) == \"scripts\" ? dirname(CURRENT_DIR) : CURRENT_DIR\nTABLES = joinpath(ROOT_DIR, \"tables\")\n\n# Prepare the output directories\nmkpath(TABLES)\n\n# Define the problem\nl_x = 1\nl_y = 1\np(x, y) = 1\nq(x, y) = 1\nu(x, y) = x^3 * y + y^2 * x\nf(x, y) = -(6 * x * y + 2 * x)\n\n# Define the grids\nN = [5, 10, 20]\nM = copy(N)\n\n# Set the expected precision of the results\nε = 1e-4\ndigits = 4\n\n\"Compute the value of the differential operator L\"\nfunction L(U, x, y, h_x, h_y, i, j)::Float64\n    return Λ₁(U, x, y, h_x, i, j) + Λ₂(U, x, y, h_y, i, j)\nend\n\n\"Compute the value of the differential operator Λ₁\"\nfunction Λ₁(U, x, y, h_x, i, j)::Float64\n    return p(x[i] + h_x / 2, y[j]) * (U[i+1, j] - U[i, j]) / h_x^2 -\n           p(x[i] - h_x / 2, y[j]) * (U[i, j] - U[i-1, j]) / h_x^2\nend\n\n\"Compute the value of the differential operator Λ₂\"\nfunction Λ₂(U, x, y, h_y, i, j)::Float64\n    return q(x[i], y[j] + h_y / 2) * (U[i, j+1] - U[i, j]) / h_y^2 -\n           q(x[i], y[j] - h_y / 2) * (U[i, j] - U[i, j-1]) / h_y^2\nend\n\n\"Compute ξ, which is needed to compute an optimal number of iterations\"\nfunction compute_xi(l_x, l_y, h_x, h_y)::Float64\n    rx = 0:0.001:l_x\n    ry = 0:0.001:l_y\n    pairs = [(x, y) for x in rx, y in ry]\n    c₁ = minimum(args -> p(args...), pairs)\n    c₂ = maximum(args -> p(args...), pairs)\n    d₁ = minimum(args -> q(args...), pairs)\n    d₂ = maximum(args -> q(args...), pairs)\n    k₁ = 4 / h_x^2\n    k₂ = 4 / h_y^2\n    arg₁ = (π * h_x) / (2 * l_x)\n    arg₂ = (π * h_y) / (2 * l_y)\n    δ = c₁ * k₁ * sin(arg₁)^2 +\n        d₁ * k₂ * sin(arg₂)^2\n    Δ = c₂ * k₁ * cos(arg₁)^2 +\n        d₂ * k₂ * cos(arg₂)^2\n    return δ / Δ\nend\n\n\"Initialize a new matrix and compute the boundary values\"\nfunction boundary_values(N, M, x, y)::Matrix{Float64}\n    # Prepare a matrix for the solution\n    U = zeros(N + 1, M + 1)\n    # Compute the boundary values\n    U[:, 1] .= u.(x, 0)\n    U[:, M+1] .= u.(x, l_y)\n    U[1, 2:M] .= u.(0, y[2:M])\n    U[N+1, 2:M] .= u.(l_x, y[2:M])\n    return U\nend\n\n\"Iterate using the simple iteration method\"\nfunction simple_iteration(Uₖ₋₁, ξ, ε, N, M, h_x, h_y, x, y)::Tuple{Matrix{Float64},Int}\n    # Prepare a new matrix\n    Uₖ = copy(Uₖ₋₁)\n    # Compute the optimal number of iterations\n    m = ceil(Int, log(1 / ε) / (2ξ))\n    # Iterate enough times to achieve desired precision\n    for _ in 1:m\n        # Compute values at the inner nodes\n        for i = 2:N, j = 2:M\n            k₁ = p(x[i] - h_x / 2, y[j]) / h_x^2\n            k₂ = p(x[i] + h_x / 2, y[j]) / h_x^2\n            k₃ = q(x[i], y[j] - h_y / 2) / h_y^2\n            k₄ = q(x[i], y[j] + h_y / 2) / h_y^2\n            Uₖ[i, j] = (k₁ * Uₖ₋₁[i-1, j] +\n                        k₂ * Uₖ₋₁[i+1, j] +\n                        k₃ * Uₖ₋₁[i, j-1] +\n                        k₄ * Uₖ₋₁[i, j+1] +\n                        f(x[i], y[j])) /\n                       (k₁ + k₂ + k₃ + k₄)\n        end\n        # Reassign the current iteration as the previous one\n        Uₖ₋₁ = Uₖ\n    end\n    return Uₖ, m\nend\n\n\"Iterate using the Seidel's method\"\nfunction seidel(Uₖ₋₁, ξ, ε, N, M, h_x, h_y, x, y)::Tuple{Matrix{Float64},Int}\n    # Prepare a new matrix\n    Uₖ = copy(Uₖ₋₁)\n    # Compute the optimal number of iterations\n    m = ceil(Int, log(1 / ε) / (4ξ))\n    # Iterate enough times to achieve desired precision\n    for _ in 1:m\n        # Compute values at the inner nodes\n        for i = N:-1:2, j = M:-1:2\n            k₁ = p(x[i] - h_x / 2, y[j]) / h_x^2\n            k₂ = p(x[i] + h_x / 2, y[j]) / h_x^2\n            k₃ = q(x[i], y[j] - h_y / 2) / h_y^2\n            k₄ = q(x[i], y[j] + h_y / 2) / h_y^2\n            Uₖ[i, j] = (k₁ * Uₖ[i-1, j] +\n                        k₂ * Uₖ₋₁[i+1, j] +\n                        k₃ * Uₖ[i, j-1] +\n                        k₄ * Uₖ₋₁[i, j+1] +\n                        f(x[i], y[j])) /\n                       (k₁ + k₂ + k₃ + k₄)\n        end\n        # Reassign the current iteration as the previous one\n        Uₖ₋₁ = Uₖ\n    end\n    return Uₖ, m\nend\n\n\"Iterate using the upper relaxation method\"\nfunction upper_relaxation(Uₖ₋₁, ξ, ε, N, M, h_x, h_y, x, y)::Tuple{Matrix{Float64},Int}\n    # Prepare a new matrix\n    Uₖ = copy(Uₖ₋₁)\n    # Compute the optimal number of iterations\n    m = ceil(Int, log(1 / ε) / sqrt(ξ))\n    # Define ω in (0,2), which affects the speed of convergence\n    ω = 1.0\n    # Iterate enough times to achieve desired precision\n    for _ in 1:m\n        # Compute values at the inner nodes\n        for i = N:-1:2, j = M:-1:2\n            k₁ = p(x[i] + h_x / 2, y[j]) / h_x^2\n            k₂ = p(x[i] - h_x / 2, y[j]) / h_x^2\n            k₃ = q(x[i], y[j] + h_y / 2) / h_y^2\n            k₄ = q(x[i], y[j] - h_y / 2) / h_y^2\n            Uₖ[i, j] = Uₖ₋₁[i, j] +\n                       ω * (k₁ * (Uₖ₋₁[i+1, j] - Uₖ₋₁[i, j]) -\n                            k₂ * (Uₖ₋₁[i, j] - Uₖ[i-1, j]) +\n                            k₃ * (Uₖ₋₁[i, j+1] - Uₖ₋₁[i, j]) -\n                            k₄ * (Uₖ₋₁[i, j] - Uₖ[i, j-1]) +\n                            f(x[i], y[j])) /\n                       (k₁ + k₂ + k₃ + k₄)\n        end\n        # Reassign the current iteration as the previous one\n        Uₖ₋₁ = Uₖ\n    end\n    return Uₖ, m\nend\n\n\"Iterate, using the alternately triangular iterative method\"\nfunction triangular(Uₖ₋₁, ε, N, M, h_x, h_y, x, y)::Tuple{Matrix{Float64},Int}\n    # Prepare a new matrix\n    Uₖ = copy(Uₖ₋₁)\n    # Compute the coefficients\n    pairs = [(x, y) for x in 0:0.001:l_x, y in 0:0.001:l_y]\n    c₁ = minimum(args -> p(args...), pairs)\n    c₂ = maximum(args -> p(args...), pairs)\n    d₁ = minimum(args -> q(args...), pairs)\n    d₂ = maximum(args -> q(args...), pairs)\n    k₁ = 4 / h_x^2\n    k₂ = 4 / h_y^2\n    δ = c₁ * k₁ * sin((π * h_x) / (2 * l_x))^2 +\n        d₁ * k₂ * sin((π * h_y) / (2 * l_y))^2\n    Δ = c₂ * k₁ + d₂ * k₂\n    ω = 2 / sqrt(δ * Δ)\n    η = δ / Δ\n    γ₁ = δ / (2 + 2 * sqrt(η))\n    γ₂ = δ / (4 * sqrt(η))\n    ξ = γ₁ / γ₂\n    κ₁ = ω / h_x^2\n    κ₂ = ω / h_y^2\n    τ = 2 / (γ₁ + γ₂)\n    # Compute the optimal number of iterations\n    m = ceil(Int, log(1 / ε) / log((1 + ξ) / (1 - ξ)))\n    # Iterate enough times to achieve desired precision\n    for _ in 1:m\n        # Prepare intermediate matrices\n        Ũ = zeros(size(Uₖ₋₁)...)\n        U̅ = zeros(size(Uₖ₋₁)...)\n        # Compute values at the inner nodes of the first intermediate matrix\n        for i = 2:N, j = 2:M\n            k₁ = κ₁ * p(x[i] - h_x / 2, y[j])\n            k₂ = κ₂ * q(x[i], y[j] - h_y / 2)\n            Ũ[i, j] = (k₁ * Ũ[i-1, j] + k₂ * Ũ[i, j-1] +\n                        L(Uₖ₋₁, x, y, h_x, h_y, i, j) + f(x[i], y[j])) /\n                       (1 + k₁ + k₂)\n        end\n        # Compute values at the inner nodes of the second intermediate matrix\n        for i = N:-1:2, j = M:-1:2\n            k₁ = κ₁ * p(x[i] + h_x / 2, y[j])\n            k₂ = κ₂ * q(x[i], y[j] + h_y / 2)\n            U̅[i, j] = (k₁ * U̅[i+1, j] + k₂ * U̅[i, j+1] + Ũ[i, j]) /\n                       (1 + k₁ + k₂)\n        end\n        # Add up the matrices\n        Uₖ[2:N, 2:M] .= Uₖ₋₁[2:N, 2:M] .+ τ .* U̅[2:N, 2:M]\n        # Reassign the current iteration as the previous one\n        Uₖ₋₁ = Uₖ\n    end\n    return Uₖ, m\nend\n\n\"Iterate using the variable directions method\"\nfunction variable_directions(Uₖ₋₁, ε, N, M, h_x, h_y, x, y)::Tuple{Matrix{Float64},Int}\n    # Prepare a new matrix and an intermediate matrix\n    Uₖ = copy(Uₖ₋₁)\n    U̅ = copy(Uₖ₋₁)\n    # Compute the optimal number of iterations\n    m = ceil(Int, N / (2 * π) * log(1 / ε))\n    # Compute the coefficients\n    pairs = [(x, y) for x in 0:0.001:l_x, y in 0:0.001:l_y]\n    c₁ = minimum(args -> p(args...), pairs)\n    c₂ = maximum(args -> p(args...), pairs)\n    d₁ = minimum(args -> q(args...), pairs)\n    d₂ = maximum(args -> q(args...), pairs)\n    k₁ = 4 / h_x^2\n    k₂ = 4 / h_y^2\n    arg₁ = (π * h_x) / (2 * l_x)\n    arg₂ = (π * h_y) / (2 * l_y)\n    δ₁ = c₁ * k₁ * sin(arg₁)^2\n    δ₂ = d₁ * k₂ * sin(arg₂)^2\n    Δ₁ = c₂ * k₁ * cos(arg₁)^2\n    Δ₂ = d₂ * k₁ * cos(arg₂)^2\n    δ = min(δ₁, δ₂)\n    Δ = max(Δ₁, Δ₂)\n    τ = 2 / sqrt(δ * Δ)\n    # Iterate enough times to achieve desired precision\n    for _ in 1:m\n        # Compute values at the inner nodes of the intermediate matrix\n        for j = 2:M\n            # Compute the linear system's matrix\n            Ũ = Tridiagonal(\n                # A's\n                [repeat([τ / (2 * h_x^2)], N - 1); 0],\n                # B's\n                [1; repeat([-τ / h_x^2 + 1], N - 1); 1],\n                # C's\n                [0; repeat([τ / (2 * h_x^2)], N - 1)],\n            )\n            # Compute the linear system's right-hand side vector\n            g = [\n                Uₖ₋₁[1, j]\n                [-Uₖ₋₁[i, j] -\n                 τ / 2 * (Λ₂(Uₖ₋₁, x, y, h_y, i, j) +\n                          f(x[i], y[j]))\n                 for i in 2:N\n                ]\n                Uₖ₋₁[N+1, j]]\n            # Compute the solution of the linear system\n            U̅[:, j] .= Ũ \\ g\n        end\n        # Compute values at the inner nodes of the input matrix\n        for i = 2:N\n            # Compute the linear system's matrix\n            Ũ = Tridiagonal(\n                # A's\n                [repeat([τ / (2 * h_y^2)], N - 1); 0],\n                # B's\n                [1; repeat([-τ / h_y^2 + 1], N - 1); 1],\n                # C's\n                [0; repeat([τ / (2 * h_y^2)], N - 1)],\n            )\n            # Compute the linear system's right-hand side vector\n            g = [\n                Uₖ₋₁[i, 1]\n                [-U̅[i, j] -\n                 τ / 2 * (Λ₁(U̅, x, y, h_x, i, j) +\n                          f(x[i], y[j]))\n                 for j in 2:M\n                ]\n                Uₖ₋₁[i, M+1]]\n            # Compute the solution of the linear system\n            Uₖ[i, :] .= Ũ \\ g\n        end\n        # Reassign the current iteration as the previous one\n        Uₖ₋₁ = Uₖ\n    end\n    return Uₖ, m\nend\n\n\"Create the TeX tables and write them to disk\"\nfunction tables(dir, U, N, M; digits = 8)\n    # Prepare the output directory\n    OUTPUT_DIR = joinpath(TABLES, dir)\n    mkpath(OUTPUT_DIR)\n    # Prepare the ranges\n    ri = Int.([1:N/5:N+1]...)\n    rj = Int.([1:M/5:M+1]...)\n    # Create and write the table with the solution grid\n    open(joinpath(OUTPUT_DIR, \"$N, $M.tex\"), \"w\") do io\n        for i in ri\n            s = \"\"\n            for j in rj\n                number = round(U[i, j]; digits)\n                s = \"$(s)& \\$ $(Printf.format(Printf.Format(\"%.0$(digits)f\"), number == 0 ? 0 : number)) \\$ \"\n            end\n            s = \"$(s)\\\\\\\\\"\n            println(io, s)\n        end\n    end\nend\n\n\"\"\"\nCompare the approximate solution to the exact one,\nfind the biggest absolute difference between the nodes\n\"\"\"\nfunction max_difference(U, x, y)::Float64\n    M1, N1 = size(U)\n    # Find the maximum\n    Δu = 0\n    for i = 1:N1, j = 1:M1\n        _Δu = abs(u(x[i], y[j]) - U[i, j])\n        if _Δu > Δu\n            Δu = _Δu\n        end\n    end\n    return Δu\nend\n\n# For each grid\nfor l in eachindex(N)\n    # Compute the steps\n    h_x = l_x / N[l]\n    h_y = l_y / M[l]\n    # Print the numbers of nodes\n    println(\n        '\\n',\n        \" \"^5, \"N: \", N[l], '\\n',\n        \" \"^5, \"M: \", M[l]\n    )\n    # Compute the nodes\n    x = collect(0:h_x:1.0)\n    y = collect(0:h_y:1.0)\n    # Compute ξ\n    ξ = compute_xi(l_x, l_y, h_x, h_y)\n    # Create a new matrix and compute the boundary values\n    U = boundary_values(N[l], M[l], x, y)\n    # Iterate, using the simple iteration method\n    U, m = simple_iteration(U, ξ, ε, N[l], M[l], h_x, h_y, x, y)\n    # Create and write the TeX tables\n    tables(\"simple_iteration\", U, N[l], M[l]; digits)\n    # Print the info\n    println(\n        '\\n',\n        \" \"^5, \"> Simple iteration:\", '\\n',\n        \" \"^5, \"  m = \", m, '\\n',\n        \" \"^5, \"  Δu = \", max_difference(U, x, y)\n    )\n    # Iterate, using the Seidel's method\n    U, m = seidel(U, ξ, ε, N[l], M[l], h_x, h_y, x, y)\n    # Create and write the TeX tables\n    tables(\"seidel\", U, N[l], M[l]; digits)\n    # Print the info\n    println(\n        '\\n',\n        \" \"^5, \"> Seidel:\", '\\n',\n        \" \"^5, \"  m = \", m, '\\n',\n        \" \"^5, \"  Δu = \", max_difference(U, x, y)\n    )\n    # Iterate, using the upper relaxation method\n    U, m = upper_relaxation(U, ξ, ε, N[l], M[l], h_x, h_y, x, y)\n    # Create and write the TeX tables\n    tables(\"upper_relaxation\", U, N[l], M[l]; digits)\n    # Print the info\n    println(\n        '\\n',\n        \" \"^5, \"> Upper relaxation:\", '\\n',\n        \" \"^5, \"  m = \", m, '\\n',\n        \" \"^5, \"  Δu = \", max_difference(U, x, y)\n    )\n    # Iterate, using the alternately triangular iterative method\n    U, m = triangular(U, ε, N[l], M[l], h_x, h_y, x, y)\n    # Create and write the TeX tables\n    tables(\"triangular\", U, N[l], M[l]; digits)\n    # Print the info\n    println(\n        '\\n',\n        \" \"^5, \"> Alternately triangular iterative method:\", '\\n',\n        \" \"^5, \"  m = \", m, '\\n',\n        \" \"^5, \"  Δu = \", max_difference(U, x, y)\n    )\n    # Iterate, using the variable directions method\n    U, m = variable_directions(U, ε, N[l], M[l], h_x, h_y, x, y)\n    # Create and write the TeX tables\n    tables(\"variable_directions\", U, N[l], M[l]; digits)\n    # Print the info\n    println(\n        '\\n',\n        \" \"^5, \"> Variable directions method:\", '\\n',\n        \" \"^5, \"  m = \", m, '\\n',\n        \" \"^5, \"  Δu = \", max_difference(U, x, y)\n    )\nend\n\nprintln()\n", "meta": {"hexsha": "4657a5a8d755356a07bee9735dda740a4fe03193", "size": 13458, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "A3/scripts/script.jl", "max_stars_repo_name": "paveloom-university/Computational-Workshop-S09-2021", "max_stars_repo_head_hexsha": "d8efe691d9af333f00b45c50ad2ffb69e5fc4aef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A3/scripts/script.jl", "max_issues_repo_name": "paveloom-university/Computational-Workshop-S09-2021", "max_issues_repo_head_hexsha": "d8efe691d9af333f00b45c50ad2ffb69e5fc4aef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A3/scripts/script.jl", "max_forks_repo_name": "paveloom-university/Computational-Workshop-S09-2021", "max_forks_repo_head_hexsha": "d8efe691d9af333f00b45c50ad2ffb69e5fc4aef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9046454768, "max_line_length": 109, "alphanum_fraction": 0.4717640065, "num_tokens": 4926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7751009869380224}}
{"text": "# This is an exact model of a velocity controlled differential drive\n# under the following assumptions:\n# - the control was applied at the beginning of the time slot\n# - the control took effect immediately\n# - the wheels don't slip\n\nL = 0.13    # m : distance between the wheels\nr = 0.033   # m : wheel radius\n\n# Creates a new state based upon the previous one assuming that the\n# specified control that was executed for the specified time.\nfunction new_state(state, control, elapsed_time)\n    x, y, θ = state\n    ω_left, ω_right = control\n\n    θ⁺ = θ + Δθ(ω_left, ω_right, elapsed_time)\n    x⁺ = x + Δx(ω_left, ω_right, θ, θ⁺, elapsed_time)\n    y⁺ = y + Δy(ω_left, ω_right, θ, θ⁺, elapsed_time)\n\n    return [x⁺ y⁺ θ⁺]\nend\n\n# Change in the x position after the elapsed time.\nfunction Δx(ω_left, ω_right, θ_init, θ_new, elapsed_time)\n    if ω_left != ω_right\n        L/2.0 * (ω_left + ω_right)/(ω_right - ω_left) * (sin(θ_new) - sin(θ_init))\n    else\n        r/2.0 * (ω_left + ω_right) * cos(θ_init) * elapsed_time\n    end\nend\n\n# Change in the y position after the elapsed time.\nfunction Δy(ω_left, ω_right, θ_init, θ_new, elapsed_time)\n    if ω_left != ω_right\n        L/2.0 * (ω_left + ω_right)/(ω_right - ω_left) * (cos(θ_init) - cos(θ_new))\n    else\n        r/2.0 * (ω_left + ω_right) * sin(θ_init) * elapsed_time\n    end\nend\n\n# Change in the orientation after the elapsed time.\nΔθ(ω_left, ω_right, elapsed_time) = r/L * (ω_right - ω_left) * elapsed_time\n\n# Creates a new state given with the specified x, y and orientation\n# components. The components should be in identical coordinate systems,\n# e.g. world.\ninitial_state(x_world, y_world, θ_world) = [x_world y_world θ_world]\n", "meta": {"hexsha": "131792862e65eca4c4c5180aa1eda1767cf9e7e6", "size": 1682, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "model/VelocityControlledDifferentialDrive.jl", "max_stars_repo_name": "grgomrton/robot-model", "max_stars_repo_head_hexsha": "e3c4fb37919a6cadc091a434d692e8f77bd809c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model/VelocityControlledDifferentialDrive.jl", "max_issues_repo_name": "grgomrton/robot-model", "max_issues_repo_head_hexsha": "e3c4fb37919a6cadc091a434d692e8f77bd809c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model/VelocityControlledDifferentialDrive.jl", "max_forks_repo_name": "grgomrton/robot-model", "max_forks_repo_head_hexsha": "e3c4fb37919a6cadc091a434d692e8f77bd809c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0416666667, "max_line_length": 82, "alphanum_fraction": 0.6872770511, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7751009834922175}}
{"text": "# This file is a part of SimilaritySearch.jl\n\nexport CosineDistance, AngleDistance, NormalizedCosineDistance, NormalizedAngleDistance\nusing LinearAlgebra\nimport Distances: evaluate\n\n\"\"\"\n   CosineDistance()\n   \nThe cosine is defined as:\n```math\n\\\\cos(u, v) = \\\\frac{\\\\sum_i u_i v_i}{\\\\sqrt{\\\\sum_i u_i^2} \\\\sqrt{\\\\sum_i v_i^2}}\n```\n\nThe cosine distance is defined as ``1 - \\\\cos(u,v)``\n\"\"\"\nstruct CosineDistance <: PreMetric end\n\n\"\"\"\n   AngleDistance()\n   \nThe angle distance is defined as:\n```math\n∠(u, v)= \\\\arccos(\\\\cos(u, v))\n```\n\n\"\"\"\nstruct AngleDistance <: PreMetric end\n\"\"\"\n    NormalizedCosineDistance()\n\nSimilar to [`CosineDistance`](@ref) but suppose that input vectors are already normalized\n\n```math\n1 - \\\\sum_i {u_i v_i}\n```\n\n\"\"\"\nstruct NormalizedCosineDistance <: PreMetric end\n\n\"\"\"\n    NormalizedAngleDistance()\n\nSimilar to [`AngleDistance`](@ref) but suppose that input vectors are already normalized\n\n```math\n\\\\arccos \\\\sum_i {u_i v_i}\n```\n\n\"\"\"\nstruct NormalizedAngleDistance <: PreMetric end\n\nconst π_2 = π / 2\n\nfunction fastacos(d)\n    if d <= -1.0\n        π\n    elseif d >= 1.0\n        0.0\n    elseif d == 0  # turn around for zero vectors, in particular for denominator=0\n        π_2\n    else\n        acos(d)\n    end\nend\n\n\"\"\"\n    evaluate(::NormalizedCosineDistance, a, b)\n\nComputes the cosine distance between two vectors, it expects normalized vectors (see [normalize!](@ref) method).\nPlease use NormalizedAngleDistance if you are expecting a metric function (cosine_distance is a faster\nalternative whenever the triangle inequality is not needed)\n\"\"\"\nevaluate(::NormalizedCosineDistance, a, b) = one(eltype(a)) - dot(a, b)\n\n\"\"\"\n    evaluate(::AngleDistance, a, b)\n\nComputes the angle  between twovectors. It supposes that all vectors are normalized (see `normalize!` function)\n\n\"\"\"\nevaluate(::NormalizedAngleDistance, a, b) = fastacos(dot(a, b))\n\n\"\"\"\n    evaluate(::CosineDistance, a, b)\n\nComputes the cosine distance between two vectors.\nPlease use AngleDistance if you are expecting a metric function (cosine_distance is a faster\nalternative whenever the triangle inequality is not needed)\n\"\"\"\nevaluate(::CosineDistance, a, b) = one(eltype(a)) - dot(a, b) / (norm(a) * norm(b))\n\n\"\"\"\n    evaluate(::AngleDistance, a, b)\n\nComputes the angle  between twovectors.\n\n\"\"\"\nfunction evaluate(::AngleDistance, a, b)\n    d = dot(a, b) / (norm(a) * norm(b))\n    fastacos(d)\nend\n", "meta": {"hexsha": "3762609b7526d7a3a88bf1687ec618afb2c875c2", "size": 2391, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances/cos.jl", "max_stars_repo_name": "sadit/SimilaritySearch.jl", "max_stars_repo_head_hexsha": "c540baff09e1b2e55af6489826e62436f0d7cf44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-12-03T01:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:43:56.000Z", "max_issues_repo_path": "src/distances/cos.jl", "max_issues_repo_name": "sadit/SimilaritySearch.jl", "max_issues_repo_head_hexsha": "c540baff09e1b2e55af6489826e62436f0d7cf44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2017-05-26T01:14:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T16:26:21.000Z", "max_forks_repo_path": "src/distances/cos.jl", "max_forks_repo_name": "sadit/SimilaritySearch.jl", "max_forks_repo_head_hexsha": "c540baff09e1b2e55af6489826e62436f0d7cf44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-05-26T09:51:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T09:13:48.000Z", "avg_line_length": 23.213592233, "max_line_length": 112, "alphanum_fraction": 0.6917607696, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7751009796459417}}
{"text": "module CircleFit\nimport StatsBase\nimport StatsBase: RegressionModel, residuals, coef, coefnames, dof\nimport Statistics: var, cov, stdm\n\nexport circfit, Circle, algorithm\n\n\"\"\"\nCircle fit model \n\nCurrently only in 2D\n\n* position: center position of the fitted circle\n* radius: radius of the fitted circle\n* points: the data to fit to. Points are stored as a matrix (number of points, number of dimensions)\n* alg: algorithm to use. Possible options are :kasa, :pratt, :graf and :taubin\n\nTo get the coefficients one can use StatsBase.coef\nThe coeffient names are provived by StatsBase.coefnames\n\"\"\"\nstruct Circle <: RegressionModel\n    position::AbstractArray\n    radius\n    points::AbstractArray\n    alg::Symbol\nend\n\n\"\"\"\nGet the algorithm used in the fit\n\"\"\"\nalgorithm(model::Circle) = model.alg\n\n# StatsBase methods\n\nStatsBase.coef(fit::Circle) = (fit.position..., fit.radius)\nStatsBase.coefnames(fit::Circle) = ((\"center position x\".*string.(1:length(fit.position)))..., \"radius\")\nStatsBase.dof(fit::Circle) = size(fit.points,1) - length(coef(fit))\nfunction StatsBase.residuals(fit::Circle)\n    rs = @. hypot(fit.points[:,1] - fit.position[1], fit.points[:,2] - fit.position[2])\n    rs .- fit.radius\nend\nStatsBase.rss(fit::Circle) = sum(abs2.(residuals(fit)))\n\nfunction StatsBase.fit(::Type{Circle},x::AbstractArray,y::AbstractArray;alg=:kasa) \n    x0,y0,r = if alg == :taubin\n        taubin(x,y)\n    elseif alg == :pratt\n        pratt(x,y)\n    elseif alg == :graf\n        p0 = collect(kasa(x,y))\n        GRAF(x,y,p0)\n    else\n        kasa(x,y)\n    end\n    Circle([x0,y0],r,[x y],alg)\nend\n\n# Old method interface\n\n\"\"\"\nFit a circle to points provided as arrays of x and y coordinates\n\nExample\n```\nx = [-1.0,0,0,1]\ny = [0.0,1,-1,0]\nx0,y0,radius = circfit(x,y)\n```\n\"\"\"\ncircfit(x,y) = kasa(x,y)\n\n@deprecate circfit(x,y) StatsBase.fit(Circle,x,y) false\n\n\"\"\"\nFit a circle to the points provided as arrays of x and y coordinates\n\nThis method uses [Kåsa's method](https://doi.org/10.1109/TIM.1976.6312298)\nThe result is a GeometryBasics::Circle\n\"\"\"\nfunction kasa(x::AbstractArray, y::AbstractArray)\n    x² = x.^2\n    y² = y.^2\n    \n    A = var(x) \n    B = cov(x, y) \n    C = var(y) \n    D = cov(x, y²) + cov(x, x²)\n    E = cov(y, x²) + cov(y, y²) \n\n    ACB2 = 2 * (A * C - B^2)\n    am = (D * C - B * E) / ACB2 \n    bm = (A * E - B * D) / ACB2\n    rk = hypot(stdm(x, am, corrected=false), stdm(y, bm, corrected=false))\n\n    (am, bm, rk)\nend\n\nusing LinearAlgebra\n\n\"\"\"\nFit a circle by using Taubin's method\nhttps://doi.org/10.1007/s10851-005-0482-8\nWarning: not optimized\n\"\"\"\nfunction taubin(x,y)\n\n    z = x.^2 .+ y.^2\n    Mx = sum(x)\n    My = sum(y)\n    Mz = sum(z)\n    Mxx = sum(x.^2)\n    Myx = Mxy = sum(x.*y)\n    Mzx = Mxz = sum(x.*z)\n    Myy = sum(y.^2)\n    Mzy = Myz = sum(y.*z)\n    Mzz = sum(z.^2)\n    n = length(x)\n\n    C = [4Mz 2Mx 2My 0\n         2Mx n   0   0\n         2My 0   n   0\n         0   0   0   0]\n        \n    M = [Mzz Mxz Myz Mz\n         Mxz Mxx Mxy Mx\n         Myz Mxy Myy My\n         Mz  Mx  My  n]\n\n    F = eigen(M,C)\n\n    values = F.values\n    values[values .< 0] .= Inf\n    i = argmin(values)\n\n    A,B,C,D = F.vectors[:,i]\n\n    a = -B/(2*A)\n    b = -C/(2*A)\n    r = sqrt((B^2+C^2-4*A*D)/(4*A^2))\n\n    (a, b, r)\nend\n\n\"\"\"\nFit a circle by using the method of Pratt\nhttps://doi.org/10.1007/s10851-005-0482-8\nWarning: not optimized\n\"\"\"\nfunction pratt(x,y)\n    z = x.^2 .+ y.^2\n    Mx = sum(x)\n    My = sum(y)\n    Mz = sum(z)\n    Mxx = sum(x.^2)\n    Myx = Mxy = sum(x.*y)\n    Mzx = Mxz = sum(x.*z)\n    Myy = sum(y.^2)\n    Mzy = Myz = sum(y.*z)\n    Mzz = sum(z.^2)\n    n = length(x)\n\n    B = [0  0  0 -2\n         0  1  0  0\n         0  0  1  0\n        -2  0  0  0]\n        \n    M = [Mzz Mxz Myz Mz\n         Mxz Mxx Mxy Mx\n         Myz Mxy Myy My\n         Mz  Mx  My  n]\n\n    F = eigen(M,B)\n\n    values = F.values\n    values[values .< 0] .= Inf\n    i = argmin(values)\n\n    A,B,C,D = F.vectors[:,i]\n\n    a = -B/(2*A)\n    b = -C/(2*A)\n    r = sqrt((B^2+C^2-4*A*D)/(4*A^2))\n\n    (a, b, r)\nend\n\nimport LsqFit: levenberg_marquardt, OnceDifferentiable, minimizer\n\n\"\"\"\nGradient weighted algebraic fit\n* x: vector of x coordinates\n* y: vector of y coordiantes\n* p0: starting values for the fit parameters(position x, position y , radius)\n* kwargs are passed to `LsqFit.levenberg_marquardt`\n\nreturn (position x, position y , radius)\n\"\"\"\nfunction GRAF(x,y,p0;kwargs...)\n    x1 = x\n    x2 = y\n    z = @. x1^2 + x2^2\n\n    model_inplace = (F, p) -> begin\n        B,C,D = p\n        A = 1\n        @. F = (A*z + B*x1 + C*x2 + D) / (4*A*(A*z+B*x1+C*x2+D)+B^2+C^2-4*A*D)\n    end\n    jacobian_inplace = (F::Array{Float64,2},p) -> begin\n        A = 1\n        B,C,D = p\n        \n        # dA\n        #@. F[:,1] = z / (4*A*(A*z+B*x1+C*x2+D)+B^2+C^2-4*A*D) - (A*z + B*x1 + C*x2 + D) / (4*A*(A*z+B*x1+C*x2+D)+B^2+C^2-4*A*D)^2 * (8*A*z-4*D)\n        # dB\n        @. F[:,1] = x1 / (4*A*(A*z+B*x1+C*x2+D)+B^2+C^2-4*A*D) - (A*z + B*x1 + C*x2 + D) / (4*A*(A*z+B*x1+C*x2+D)+B^2+C^2-4*A*D)^2 * (4*A*x1+2*B)\n        # dC\n        @. F[:,2] = x2 / (4*A*(A*z+B*x1+C*x2+D)+B^2+C^2-4*A*D) - (A*z + B*x1 + C*x2 + D) / (4*A*(A*z+B*x1+C*x2+D)+B^2+C^2-4*A*D)^2 * (4*A*x2+2*C)\n        # dD\n        @. F[:,3] = 1 / (4*A*(A*z+B*x1+C*x2+D)+B^2+C^2-4*A*D) \n    end\n    p0_ext = [abr_to_BCD(p0...)...]\n    R = OnceDifferentiable(model_inplace, jacobian_inplace, p0_ext, similar(x); inplace = true)\n    results = levenberg_marquardt(R, p0_ext; kwargs...)\n    coef = minimizer(results)\n    BCD_to_abr(coef[1:end]...)\nend\n\n\"\"\"\nconvert the parametric form of \nz+B*x+C*y+D -> (x-a)²+(y-b)²-r²\n\"\"\"\nfunction BCD_to_abr(B,C,D)\n    [-B/2,-C/2,sqrt(B^2/4+C^2/4-D)]\nend\n\n\"\"\"\nconvert the parametric form of \nz+B*x+C*y+D <- (x-a)²+(y-b)²-r²\n\"\"\"\nfunction abr_to_BCD(a,b,r)\n    [-2a,-2b,a^2+b^2-r^2]\nend\n\nend # module\n", "meta": {"hexsha": "940cc3d4c8280f0ddfc45ef07dc7895b483a5fb1", "size": 5761, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CircleFit.jl", "max_stars_repo_name": "feanor12/CircleFit.jl", "max_stars_repo_head_hexsha": "7156f82e4832eff58838cb1196a94019e5d1a5c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-08-30T01:27:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T21:01:29.000Z", "max_issues_repo_path": "src/CircleFit.jl", "max_issues_repo_name": "feanor12/CircleFit.jl", "max_issues_repo_head_hexsha": "7156f82e4832eff58838cb1196a94019e5d1a5c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-08-25T20:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-26T14:15:57.000Z", "max_forks_repo_path": "src/CircleFit.jl", "max_forks_repo_name": "feanor12/CircFit.jl", "max_forks_repo_head_hexsha": "7156f82e4832eff58838cb1196a94019e5d1a5c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-05-11T01:18:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T21:34:31.000Z", "avg_line_length": 23.5142857143, "max_line_length": 145, "alphanum_fraction": 0.5563270266, "num_tokens": 2226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.7750020897916792}}
{"text": "### A Pluto.jl notebook ###\n# v0.11.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 5a0472c2-f40b-11ea-231b-a52e7382c1bc\nmd\"\"\"Recall the mean value theorem:\n\nLet $f(x)$ be a function that is continuous on $[a,b]$ and differentiable on $(a,b)$.\n\nThen there is a number $c$ in between $a,b$ such that:\n\n$$f'(c) = \\frac{f(b)-f(a)}{b-a}$$.\n\nThis means that there is a point with a derivative equal to the slope between the boundary points. \n\nLet's take the following function:\n\n$$f(x) = x^3+2x-x \\text{ on } [-1,2]$$\"\"\"\n\n# ╔═╡ bc85d0e0-f40d-11ea-2344-dd5ea4b66cde\nmd\"\"\" By the mean value theorem:\n\n$$\\frac{f(b)-f(a)}{b-a}= \\frac{(10)-(-2)}{2-(-1)} = 4 = f'(c)$$\n\nfor some $c$ in $(-1,2)$.\n\nWith some algebra and rearranging, we find \n\n$$c = \\frac{-4+\\sqrt{76}}{6}= 0.7863$$.\n\nGraph:\n\"\"\"\n\n# ╔═╡ 40d54e00-f40b-11ea-3ddf-a39ce834ea41\nusing Gadfly\n\n# ╔═╡ 54dca870-f411-11ea-1f67-ad216b5b2e49\nset_default_plot_size(20cm, 15cm)\n\n# ╔═╡ dd853160-f40c-11ea-318e-5751cdc6ffdf\nbegin\n\tp = plot((x)->(x^3+2x-x),-1,2)\n\tpush!(p,Coord.cartesian(fixed=true))\n\tpush!(p,Guide.title(\"f(x)\"))\nend\n\n\n# ╔═╡ 5e773960-f40f-11ea-1894-0b4feb0e99e3\nbegin\n\tpush!(p,layer(x=[0.7863],y=[1.2724], size=[0.25], color=[colorant\"gold\"]))\n\tpush!(p,layer((x)->(4x-1.8728),0,2))\n\tpush!(p,layer((x)->(4x+2),-1,2))\nend\n\n\n# ╔═╡ Cell order:\n# ╟─40d54e00-f40b-11ea-3ddf-a39ce834ea41\n# ╠═5a0472c2-f40b-11ea-231b-a52e7382c1bc\n# ╟─54dca870-f411-11ea-1f67-ad216b5b2e49\n# ╟─dd853160-f40c-11ea-318e-5751cdc6ffdf\n# ╠═bc85d0e0-f40d-11ea-2344-dd5ea4b66cde\n# ╠═5e773960-f40f-11ea-1894-0b4feb0e99e3\n", "meta": {"hexsha": "4308d23cec79dd9615e60284c86495f73ff3a18d", "size": 1541, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "derivatives/mvt.jl", "max_stars_repo_name": "thomastjdavis/CalculusViz.jl", "max_stars_repo_head_hexsha": "225eefeb88f42689e05b50deed50101faaeb447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-17T05:15:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T05:15:52.000Z", "max_issues_repo_path": "mvt.jl", "max_issues_repo_name": "thomastjdavis/CalculusViz.jl", "max_issues_repo_head_hexsha": "225eefeb88f42689e05b50deed50101faaeb447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mvt.jl", "max_forks_repo_name": "thomastjdavis/CalculusViz.jl", "max_forks_repo_head_hexsha": "225eefeb88f42689e05b50deed50101faaeb447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7076923077, "max_line_length": 99, "alphanum_fraction": 0.659312135, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7750020886219307}}
{"text": "using FFTW, BenchmarkTools, FourierFlows, Random\nusing LinearAlgebra: mul!, ldiv!\nusing Random: seed!\n\nseed!(1234) # for reproducibility\n\nLx, Ly = 2π, 3π\nnx, ny = 256, 256\nT, tolerance = Float64, 1e-12\n# T, tolerance = Float32, 1e-6\n\ngr =  TwoDGrid(nx, Lx, ny, Ly, T=T)\n\n# test function used in bench tests\nf = real(ifft(rand(T, (nx, ny)) + im*rand(T, (nx, ny))))\nfcomplex  = Complex.(f)\n\n# initialize empty arrays\ndfdx = zeros(T, (nx, ny))\ndfdx_c = zeros(Complex{T}, (nx, ny))\n fh  = zeros(Complex{T}, (gr.nk, gr.nl))\n fhr = zeros(Complex{T}, (gr.nkr, gr.nl))\n\n# various ways of computing ∂f/∂x\n\nfunction dx_using_fft(f)\n  fh = fft(f)\n  dfdx = real(ifft(im*gr.k .* fh))\n  return dfdx\nend\n\nfunction dx_using_rfft(f)\n  fhr = rfft(f)\n  dfdx = irfft(im*gr.kr .* fhr, nx)\n  return dfdx\nend\n\neffort = FFTW.PATIENT\nFFTW.set_num_threads(Sys.CPU_THREADS)\nfftplan = plan_fft(Array{T, 2}(undef, nx, ny), flags=effort)\nrfftplan = plan_rfft(Array{T, 2}(undef, nx, ny), flags=effort)\n\nfunction dx_using_fftplan(f)\n  fh = fftplan*f\n  @. fh = im*gr.k * fh\n  dfdx = fftplan \\ fh\n  return real.(dfdx)\nend\n\nfunction dx_using_rfftplan(f)\n  fhr = rfftplan*f\n  @. fhr = im*gr.kr * fhr\n  dfdx = rfftplan \\ fhr\n  return dfdx\nend\n\nfunction dx_using_fftplan_mul(f)\n  mul!(fh, fftplan, fcomplex) #fftplan within mul! only works if all arrays are complex-valued\n  @. fh = im*gr.k * fh\n  ldiv!(dfdx_c, fftplan, fh) #fftplan within ldiv! only works if all arrays are complex-valued\n  return real.(dfdx_c)\nend\n\nfunction dx_using_rfftplan_mul(f)\n  mul!(fhr, rfftplan, f)\n  @. fhr = im*gr.kr * fhr\n  ldiv!(dfdx, rfftplan, fhr)\n  return dfdx\nend\n\ndfdx1 = dx_using_fft(f)\ndfdx2 = dx_using_rfft(f)\ndfdx3 = dx_using_fftplan(f)\ndfdx4 = dx_using_rfftplan(f)\ndfdx5 = dx_using_fftplan_mul(f)\ndfdx6 = dx_using_rfftplan_mul(f)\n\nif (isapprox(dfdx1, dfdx2, rtol=tolerance) && isapprox(dfdx1, dfdx3, rtol=tolerance) \n    && isapprox(dfdx1, dfdx4, rtol=tolerance) && isapprox(dfdx1, dfdx5, rtol=tolerance) \n    && isapprox(dfdx1, dfdx6, rtol=tolerance))\n #make sure that all functions compute ∂f/∂x the same \n  \n  println(\"Performing bench tests for 2D FFTs using nx=\", nx, \" and ny=\", ny, \" grid-points with \", T, \" arithmetic.\")\n  println(\" \")\n  println(\"computing ∂f/∂x using fft\")\n  @btime dx_using_fft(f);\n  println(\" \")\n  println(\"computing ∂f/∂x using rfft\")\n  @btime dx_using_rfft(f);\n  println(\" \")\n  println(\"computing ∂f/∂x using fftplan\")\n  @btime dx_using_fftplan(f);\n  println(\" \")\n  println(\"computing ∂f/∂x using rfftplan\")\n  @btime dx_using_rfftplan(f);\n  println(\" \")\n  println(\"computing ∂f/∂x using fftplan & mul!\")\n  @btime dx_using_fftplan_mul(f);\n  println(\" \")\n  println(\"computing ∂f/∂x using rfftplan & mul!\")\n  @btime dx_using_rfftplan_mul(f);\nelse\n  error(\"something went wrong while computing the derivatives\")\nend\n", "meta": {"hexsha": "04c524555a4efa4de7091be190790e4b84fa3afb", "size": 2798, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchFFT.jl", "max_stars_repo_name": "navidcy/BenchFFT.jl", "max_stars_repo_head_hexsha": "2c2aa22d92be7bae85aa0fe701721f8d8d107dbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-12-21T01:58:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-25T21:05:05.000Z", "max_issues_repo_path": "benchFFT.jl", "max_issues_repo_name": "navidcy/BenchFFT.jl", "max_issues_repo_head_hexsha": "2c2aa22d92be7bae85aa0fe701721f8d8d107dbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchFFT.jl", "max_forks_repo_name": "navidcy/BenchFFT.jl", "max_forks_repo_head_hexsha": "2c2aa22d92be7bae85aa0fe701721f8d8d107dbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6476190476, "max_line_length": 118, "alphanum_fraction": 0.6840600429, "num_tokens": 1012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7750020870618141}}
{"text": "# Solve level-set equations in 2D using the Jiang-Lin-Tadmor method\r\n# Alex Tam, 09/11/2021\r\n\r\n\"Function to solve level-set equation\"\r\nfunction level_set(V, ϕ, par, dx, dy, dt)\r\n    ϕn = Array{Float64}(undef, par.Nx, par.Ny) # Pre-allocate array of ϕ\r\n    # Compute solutions on staggered grid using Lin-Tadmor\r\n    ϕs = lt_staggered(V, ϕ, par, dx, dy, dt)\r\n    # Compute derivatives on staggered grid\r\n    dxϕs = Array{Float64}(undef, par.Nx-1, par.Ny-1) # Pre-allocate x-derivatives at staggered grid points\r\n    dyϕs = Array{Float64}(undef, par.Nx-1, par.Ny-1) # Pre-allocate y-derivatives at staggered grid points\r\n    for i = 1:par.Nx-1\r\n        for j = 1:par.Ny-1 # Loop over staggered grid points\r\n            if i == 1\r\n                dxϕs[i,j] = (ϕs[i+1,j]-ϕs[i,j])/dx # ϕ'_{i+1/2,j+1/2}/Δx\r\n            elseif i == par.Nx-1\r\n                dxϕs[i,j] = (ϕs[i,j]-ϕs[i-1,j])/dx # ϕ'_{i+1/2,j+1/2}/Δx\r\n            else\r\n                dxϕs[i,j] = minmod(par.θ*(ϕs[i+1,j]-ϕs[i,j])/dx, (ϕs[i+1,j]-ϕs[i-1,j])/(2*dx), par.θ*(ϕs[i,j]-ϕs[i-1,j])/dx) # ϕ'_{i+1/2,j+1/2}/Δx\r\n            end\r\n            if j == 1\r\n                dyϕs[i,j] = (ϕs[i,j+1]-ϕs[i,j])/dy # ϕ`_{i+1/2,j+1/2}/Δy\r\n            elseif j == par.Ny-1\r\n                dyϕs[i,j] = (ϕs[i,j]-ϕs[i,j-1])/dy # ϕ`_{i+1/2,j+1/2}/Δy\r\n            else\r\n                dyϕs[i,j] = minmod(par.θ*(ϕs[i,j+1]-ϕs[i,j])/dy, (ϕs[i,j+1]-ϕs[i,j-1])/(2*dy), par.θ*(ϕs[i,j]-ϕs[i,j-1])/dy) # ϕ`_{i+1/2,j+1/2}/Δy\r\n            end\r\n        end\r\n    end\r\n    # Perform cell-averaging at non-staggered points (Jiang 1998)\r\n    for i = 1:par.Nx\r\n        for j = 1:par.Ny # Loop over non-staggered grid points\r\n            if (i == 1) || (j == 1) || (i == par.Nx) || (j == par.Ny) # Ignore boundaries\r\n                ϕn[i,j] = ϕ[i,j]\r\n            else\r\n                ϕn[i,j] = (ϕs[i,j] + ϕs[i-1,j] + ϕs[i,j-1] + ϕs[i-1,j-1])/4 + \r\n                (dx*(dxϕs[i-1,j-1]-dxϕs[i,j-1]) + dx*(dxϕs[i-1,j]-dxϕs[i,j]) + dy*(dyϕs[i-1,j-1]-dyϕs[i-1,j]) + dy*(dyϕs[i,j-1]-dyϕs[i,j]))/16 # Compute non-staggered cell average\r\n            end\r\n        end\r\n    end\r\n    return ϕn\r\nend\r\n\r\n\"Staggered Lin-Tadmor scheme\"\r\nfunction lt_staggered(V, ϕ, par, dx, dy, dt)\r\n    ϕ_stag = Array{Float64}(undef, par.Nx-1, par.Ny-1) # Pre-allocate solution on staggered grid ϕ_stag[i,j] = ϕ[i+1/2, j+1/2], one-based indexing\r\n    V_stag = Array{Float64}(undef, par.Nx-1, par.Ny-1) # Pre-allocate velocity on staggered grid V_stag[i,j] = ϕ[i+1/2, j+1/2], one-based indexing\r\n    dxϕ = Array{Float64}(undef, par.Nx, par.Ny) # Pre-allocate x-derivatives at non-staggered grid points\r\n    dyϕ = Array{Float64}(undef, par.Nx, par.Ny) # Pre-allocate y-derivatives at non-staggered grid points\r\n    ϕ_mid = Array{Float64}(undef, par.Nx, par.Ny) # Pre-allocate mid-values at non-staggered grid points\r\n    # Evaluate derivatives and missing mid-values on full non-staggered grid\r\n    for i = 1:par.Nx\r\n        for j = 1:par.Ny\r\n            # Compute dϕ/dx\r\n            if i == 1 # Boundary condition\r\n                dxϕ[i,j] = (ϕ[i+1,j] - ϕ[i,j])/dx\r\n            elseif i == par.Nx # Boundary condition\r\n                dxϕ[i,j] = (ϕ[i,j] - ϕ[i-1,j])/dx\r\n            else # Apply min-mod at interior grid points\r\n                dxϕ[i,j] = minmod(par.θ*(ϕ[i+1,j]-ϕ[i,j])/dx, (ϕ[i+1,j]-ϕ[i-1,j])/(2*dx), par.θ*(ϕ[i,j]-ϕ[i-1,j])/dx)\r\n            end\r\n            # Compute dϕ/dy\r\n            if j == 1 # Boundary condition\r\n                dyϕ[i,j] = (ϕ[i,j+1] - ϕ[i,j])/dy\r\n            elseif j == par.Ny # Boundary condition\r\n                dyϕ[i,j] = (ϕ[i,j] - ϕ[i,j-1])/dy\r\n            else # Apply min-mod at interior grid points\r\n                dyϕ[i,j] = minmod(par.θ*(ϕ[i,j+1]-ϕ[i,j])/dy, (ϕ[i,j+1]-ϕ[i,j-1])/(2*dy), par.θ*(ϕ[i,j]-ϕ[i,j-1])/dy)\r\n            end\r\n            ϕ_mid[i,j] = ϕ[i,j] - dt/2*hamiltonian_ls(V[i,j], dxϕ[i,j], dyϕ[i,j]) # Missing mid-values\r\n        end\r\n    end\r\n    # Obtain velocity field on staggered grid\r\n    for i = 1:par.Nx-1\r\n        for j = 1:par.Ny-1 # Loop over staggered grid points\r\n            V_stag[i,j] = (V[i,j] + V[i+1,j] + V[i,j+1] + V[i+1,j+1])/4\r\n        end\r\n    end\r\n    # Evaluate solution on staggered grid\r\n    for i = 1:par.Nx-1\r\n        for j = 1:par.Ny-1 # Loop over staggered grid points\r\n            ϕ_stag[i,j] = (ϕ[i,j] + ϕ[i+1,j] + ϕ[i,j+1] + ϕ[i+1,j+1])/4 + \r\n            (dxϕ[i,j]-dxϕ[i+1,j]+dxϕ[i,j+1]-dxϕ[i+1,j+1])*dx/16 + \r\n            (dyϕ[i,j]-dyϕ[i,j+1]+dyϕ[i+1,j]-dyϕ[i+1,j+1])*dy/16 - \r\n            dt/2*(hamiltonian_ls(V_stag[i,j], (ϕ_mid[i+1,j]-ϕ_mid[i,j])/dx, (ϕ_mid[i+1,j+1]-ϕ_mid[i+1,j])/dy) + \r\n            hamiltonian_ls(V_stag[i,j], (ϕ_mid[i+1,j+1]-ϕ_mid[i,j+1])/dx, (ϕ_mid[i,j+1]-ϕ_mid[i,j])/dy))\r\n        end\r\n    end\r\n    return ϕ_stag\r\nend\r\n\r\n\"Minmod function for flux-limiter\"\r\nfunction minmod(a, b, c)\r\n    if (a < 0) && (b < 0) && (c < 0)\r\n        return max(a, b, c)\r\n    elseif (a > 0) && (b > 0) && (c > 0)\r\n        return min(a, b, c)\r\n    else\r\n        return 0.0\r\n    end\r\nend \r\n\r\n\"Evaluate Hamiltonian at one grid point\"\r\nfunction hamiltonian_ls(v, ϕx, ϕy)\r\n    return v*sqrt(ϕx^2 + ϕy^2)\r\nend", "meta": {"hexsha": "d94e2a8d13da9e12b09795d68ce30cef29c50c4e", "size": 5107, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "level-set.jl", "max_stars_repo_name": "alex-tam/2D_Fisher-Stefan_Level-Set", "max_stars_repo_head_hexsha": "9b66c804a1c3969cf3deea22fa0ee02f9a6889a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "level-set.jl", "max_issues_repo_name": "alex-tam/2D_Fisher-Stefan_Level-Set", "max_issues_repo_head_hexsha": "9b66c804a1c3969cf3deea22fa0ee02f9a6889a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "level-set.jl", "max_forks_repo_name": "alex-tam/2D_Fisher-Stefan_Level-Set", "max_forks_repo_head_hexsha": "9b66c804a1c3969cf3deea22fa0ee02f9a6889a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.179245283, "max_line_length": 180, "alphanum_fraction": 0.5165459174, "num_tokens": 2081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.8311430478583169, "lm_q1q2_score": 0.7750020866718978}}
{"text": "module DiffEqsSolver\n\nexport EulerDES, RK2DES, RK4DES, EulerCromerDES, EulerMidPiontDES, VerletDES, VelVerDES\n\nfunction EulerDES(; ẋ::Function, x₀::Vector{T}, t₀::T, t₁::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t₀:h:t₁)\n    xcoll = [x₀]\n    x = x₀\n    for t ∈ tcoll[2:end]\n        x += h * ẋ(t, x)\n        push!(xcoll, x)\n    end\n    return tcoll, xcoll\nend\n\nfunction UnstableDES(; ẋ::Function, x₀::Vector{T}, t₀::T, t₁::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t₀:h:t₁)\n    xcoll = [x₀, x₀ + h * ẋ(t₀, x₀)]\n    for t ∈ tcoll[3:end]\n        xₙ₊₁ = 2 * h * ẋ(t, xcoll[end]) + xcoll[end-1]\n        push!(xcoll, xₙ₊₁)\n    end\n    return tcoll, xcoll\nend\n\nfunction EulerYaghoubDES(; ẋ::Function, x₀::Vector{T}, t₀::T, t₁::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t₀:h:t₁)\n    xcoll = [x₀]\n    x = x₀\n    ẋval = ẋ(t₀, x₀)\n    for t ∈ tcoll[2:end]\n        x += h * ẋval\n        ẋval = ẋ(t, x)\n        push!(xcoll, x)\n    end\n    return tcoll, xcoll\nend\n\nfunction RK2DES(; ẋ::Function, x₀::Vector{T}, t₀::T, t₁::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t₀:h:t₁)\n    xcoll = [x₀]\n    x = x₀\n    for t ∈ tcoll[2:end]\n        K₁ = ẋ(t, x) * h\n        K₂ = h * ẋ(t + h / 2, x + (K₁ * h) / 2)\n        x += K₂\n        push!(xcoll, x)\n    end\n    return tcoll, xcoll\nend\n\nfunction RK4DES(; ẋ::Function, x₀::Vector{T}, t₀::T, t₁::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t₀:h:t₁)\n    xcoll = [x₀]\n    x = x₀\n    for t ∈ tcoll[2:end]\n        K₁ = ẋ(t, x)\n        K₂ = ẋ(t + h / 2, x .+ h / 2 * K₁)\n        K₃ = ẋ(t + h / 2, x .+ h / 2 * K₂)\n        K₄ = ẋ(t + h, x .+ h * K₃)\n        x += (K₁ + 2 * K₂ + 2 * K₃ + K₄) * h / 6\n        push!(xcoll, x)\n    end\n    return tcoll, xcoll\nend\n\nfunction EulerCromerDES(; ẍ::Function, ẋ₀::Vector{T}, x₀::Vector{T}, t₀::T, t₁::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t₀:h:t₁)\n    xcoll = [x₀]\n    ẋcoll = [ẋ₀]\n    x = x₀\n    ẋ = ẋ₀\n    for t ∈ tcoll[2:end]\n        ẋ += h * ẍ(t, x, ẋ)\n        x += h * ẋ\n        push!(xcoll, x)\n        push!(ẋcoll, ẋ)\n    end\n\n    return tcoll, xcoll, ẋcoll\nend\n\nfunction EulerMidPiontDES(; ẍ::Function, ẋ₀::Vector{T}, x₀::Vector{T}, t₀::T, t₁::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t₀:h:t₁)\n    xcoll = [x₀]\n    ẋcoll = [ẋ₀ - (ẍ(t₀, x₀, ẋ₀) * h / 2)]\n    x = x₀\n    ẋ = ẋ₀ - (ẍ(t₀, x₀, ẋ₀) * h / 2)\n\n    for t ∈ tcoll[2:end]\n        ẋ += h * ẍ(t, x, ẋ)\n        x += h * ẋ\n\n        push!(xcoll, x)\n        push!(ẋcoll, ẋ)\n    end\n\n    return tcoll, xcoll, ẋcoll\nend\n\nfunction VerletDES(; ẍ::Function, ẋ₀::Vector{T}, x₀::Vector{T}, t₀::T, t₁::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t₀:h:t₁)\n    xcoll = [x₀, x₀ + ẋ₀ * h + ẍ(t₀, x₀, ẋ₀) * (h^2) / 2]\n    ẋcoll = [ẋ₀, ẋ₀ + ẍ(t₀, x₀, ẋ₀) * h]\n\n    for i ∈ 3:length(tcoll)\n        xᵢ = 2 * xcoll[i-1] - xcoll[i-2] + ẍ(tcoll[i-1], xcoll[i-1], ẋcoll[i-1]) * (h^2)\n        push!(xcoll, xᵢ)\n        ẋᵢ = (xcoll[i] - xcoll[i-1]) / h\n        push!(ẋcoll, ẋᵢ)\n    end\n\n    return tcoll, xcoll, ẋcoll\nend\n\nfunction VelVerDES(; ẍ::Function, ẋ₀::Vector{T}, x₀::Vector{T}, t₀::T, t₁::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t₀:h:t₁)\n    xcoll = [x₀]\n    ẋcoll = [ẋ₀]\n    x = x₀\n    ẋ = ẋ₀\n\n    for t ∈ tcoll[2:end]\n        ẍₙ = ẍ(t, x, ẋ)\n        x += ẋ * h + ẍₙ * (h^2) / 2\n        ẍₙ₊₁ = ẍ(t + h, x, ẋ)\n        ẋ += (ẍₙ + ẍₙ₊₁) * h / 2\n        push!(xcoll, x)\n        push!(ẋcoll, ẋ)\n    end\n\n    return tcoll, xcoll, ẋcoll\nend\n\nend", "meta": {"hexsha": "8e9eb326108b9eff211ed5f4401c9bf8b3fc813f", "size": 3534, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSet9/Codes/DiffEqs/DESolver.jl", "max_stars_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_stars_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSet9/Codes/DiffEqs/DESolver.jl", "max_issues_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_issues_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSet9/Codes/DiffEqs/DESolver.jl", "max_forks_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_forks_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-21T11:07:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-21T11:07:08.000Z", "avg_line_length": 26.1777777778, "max_line_length": 117, "alphanum_fraction": 0.4883984154, "num_tokens": 1671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7750020862819814}}
{"text": "test = \"\"\"939\n7,13,x,x,59,x,31,19\n\"\"\"\n\nfunction parse_input(input::AbstractString)::Tuple\n    (departure, buses) = split(input, r\"\\s+\"; keepempty = false)\n    buses = tryparse.(Int, split(buses, ','))\n    return (parse(Int, departure), buses)\nend\n\nfunction q1(departure::Integer, buses::AbstractVector)::Int\n    buses = filter(!isnothing, buses)\n    bus = buses[argmin([bus - departure % bus for bus in buses])]\n    return (bus - departure % bus) * bus\nend\n\nfunction q2(buses::AbstractVector)::Int\n    return mod_lcm([(bus, rem(1 - i, bus, RoundDown))\n                    for (i, bus) in enumerate(buses)\n                    if bus !== nothing])\nend\n\nfunction mod_lcm(vs::AbstractVector)::Int\n    isempty(vs) && return 0\n    ((v1, m1), rest...) = vs\n    r = map(rest) do (v, m)\n        vp = v ÷ gcd(v, v1)\n        k = findfirst(==(m), [(k * v1 + m1) % v for k in 0:vp - 1]) - 1\n        return (vp, k)\n    end |> mod_lcm\n    return r * v1 + m1\nend\n\nlet\n    (departure, buses) = parse_input(test)\n    @assert q1(departure, buses) == 295\n    @assert q2(buses) == 1068781\nend\n\n(departure, buses) = parse_input(read(\"day13.in\", String))\nprintln(\"Q1: \", q1(departure, buses))\nprintln(\"Q1: \", q2(buses))\n", "meta": {"hexsha": "c13febeb2aab496fb75cf55cc2899f246c6aed72", "size": 1197, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "aoc2020/day13.jl", "max_stars_repo_name": "dhanak/competitive-coding", "max_stars_repo_head_hexsha": "9e28298f8c646f169b7389d0ef20f99c5ef68f00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aoc2020/day13.jl", "max_issues_repo_name": "dhanak/competitive-coding", "max_issues_repo_head_hexsha": "9e28298f8c646f169b7389d0ef20f99c5ef68f00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aoc2020/day13.jl", "max_forks_repo_name": "dhanak/competitive-coding", "max_forks_repo_head_hexsha": "9e28298f8c646f169b7389d0ef20f99c5ef68f00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8372093023, "max_line_length": 71, "alphanum_fraction": 0.5923141186, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.775002078091482}}
{"text": "using Plots\r\n\r\nV(x,y) = (1/2)*(x^2 + y^2 + 2*x^2*y - (2/3)*y^3)\r\nx = y = range(-1,stop = 1, length = 1000)\r\nV(x,y) = (1/2)*(x^2 + y^2 + 2*x^2*y - (2/3)*y^3)\r\nx = y = range(-1,stop = 1, length = 1000)\r\ncontourf(x,y,V)\r\ncontour!(x,y,V,levels=0:1/6:1,title = \"Henon-Heiles potential: Intensity map\",linecolor = :white)\r\n# savefig(\"potential_intensity.png\")\r\n\r\nplot(x,y,V,title = \"Henon-Heiles potential: Surface map\")\r\n# savefig(\"potential_surface.png\")", "meta": {"hexsha": "bace245ee5250d043b5d680255cb2d2368c996f1", "size": 450, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HH_potential.jl", "max_stars_repo_name": "Ved-Mahajan/Henon-Heiles-System", "max_stars_repo_head_hexsha": "061be33a80c66bd4073c39a270fa2ff8fba75b77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HH_potential.jl", "max_issues_repo_name": "Ved-Mahajan/Henon-Heiles-System", "max_issues_repo_head_hexsha": "061be33a80c66bd4073c39a270fa2ff8fba75b77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HH_potential.jl", "max_forks_repo_name": "Ved-Mahajan/Henon-Heiles-System", "max_forks_repo_head_hexsha": "061be33a80c66bd4073c39a270fa2ff8fba75b77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5, "max_line_length": 98, "alphanum_fraction": 0.6, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7749910808590861}}
{"text": "\"\"\"\n        capacity(P::Drip;      # Drip structure\n                 unit = \"bit\"  # optional: unit of capacity (bit or nat).\n                 )\nReturns the amount of information processes per unit of time in the steady state\nof the DRIP `P`.\n\"\"\"\nfunction capacity(P::Drip;      # Drip structure\n                  unit = \"bit\"  # optional: unit of capacity (bit or nat).\n                  )\n    if unit == \"bit\"\n        κ = 0.5*log(det(P.ss.Σ_1)/det(P.ss.Σ_p))/log(2); #returns capacity in bits\n    elseif unit == \"nat\"\n        κ = 0.5*log(det(P.ss.Σ_1)/det(P.ss.Σ_p));        #returns capacity in nats\n    else\n        println(\"Invalid input for unit! Capacity is reported in bits.\")\n        κ = 0.5*log(det(P.ss.Σ_1)/det(P.ss.Σ_p))/log(2);\n    end\n    return(κ)\nend\n\n\"\"\"\n    infinitesum(func; tol = 1e-6,maxit = 1000,start=0)\nReturns the infinite sum `Σₓfunc(x)` starting from `x = start` up to tolderance\n`tol` or max iteration `maxit`.\n\"\"\"\nfunction infinitesum(func; tol = 1e-6,maxit = 1000,start=0)\n    diff  = 1.0\n    infsum = func(start)\n    it    = start + 1\n    while (diff > tol) & (it < maxit)\n        func_it = func(it)\n        infsum += func_it\n        diff = maximum(func_it)\n        it += 1\n    end\n    return(infsum)\nend\n", "meta": {"hexsha": "3982f6daa0f6c90101a95e7ec49ab684304cd36e", "size": 1237, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/aux_funcs.jl", "max_stars_repo_name": "afrouzi/DRIPs.jl", "max_stars_repo_head_hexsha": "4b8f08fdd6eb7deda2fd61cfa3320715a9260156", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-05-04T15:43:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T13:31:29.000Z", "max_issues_repo_path": "src/aux_funcs.jl", "max_issues_repo_name": "afrouzi/DRIPs.jl", "max_issues_repo_head_hexsha": "4b8f08fdd6eb7deda2fd61cfa3320715a9260156", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-04-27T01:39:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-11T00:25:45.000Z", "max_forks_repo_path": "src/aux_funcs.jl", "max_forks_repo_name": "afrouzi/DRIPs.jl", "max_forks_repo_head_hexsha": "4b8f08fdd6eb7deda2fd61cfa3320715a9260156", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-14T03:12:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T02:56:34.000Z", "avg_line_length": 31.7179487179, "max_line_length": 82, "alphanum_fraction": 0.5634599838, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7749760011406588}}
{"text": "#' ---\n#' title: N-Queens\n#' ---\n\n#' **Originally Contributed by**: Matthew Helm\n\n#' The N-Queens problem involves placing N queens on an N x N chessboard such that none of the queens attacks another. In chess, a \n#' queen can move vertically, horizontally, and diagonally so there cannot be more than one queen on any given row, column, or \n#' diagonal.\n\n#' <img src=\"img/n_queens4.png\" style=\"width: auto; height: auto\" alt=\"4 Queens\">\n\n#' *Note that none of the queens above are able to attack any other as a result of their careful placement.*\n\nusing GLPK\nusing JuMP\nusing LinearAlgebra\n\n# N-Queens\nN = 8\n\nmodel = Model(GLPK.Optimizer);\n\n#' Next, let's create an N x N chessboard of binary values. 0 will represent an empty space on the board and 1 will represent a \n#' space occupied by one of our queens:\n\n@variable(model, x[i=1:N, j=1:N], Bin)\n\n#' Now we can add our constraints:\n\n# There must be exactly one queen in a given row/column\nfor i=1:N\n    @constraint(model, sum(x[i, :]) == 1)\n    @constraint(model, sum(x[:, i]) == 1)\nend\n\n# There can only be one queen on any given diagonal\nfor i in -(N-1):(N-1)\n    @constraint(model, sum(diag(x,i)) <= 1)\n    @constraint(model, sum(diag(reverse(x,dims=1), i)) <=1)\nend\n\n#' That's it! We are ready to put our model to work and see if it is able to find a feasible solution:\n\noptimize!(model)\n\n#' We can now review the solution that our model found:\n\nsolution = convert.(Int,value.(x))\n\n#' <img src=\"img/n_queens.png\" style=\"width: auto; height: auto\" alt=\"4 Queens\">\n", "meta": {"hexsha": "72b58484ca7ae2b83d2a89e69764c206132fb60b", "size": 1522, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/modelling/n-queens.jl", "max_stars_repo_name": "mtanneau/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-04T22:17:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-04T22:17:54.000Z", "max_issues_repo_path": "script/modelling/n-queens.jl", "max_issues_repo_name": "mtanneau/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-05T21:03:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-05T21:03:40.000Z", "max_forks_repo_path": "script/modelling/n-queens.jl", "max_forks_repo_name": "mtanneau/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-18T01:29:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-18T01:29:51.000Z", "avg_line_length": 29.2692307692, "max_line_length": 131, "alphanum_fraction": 0.6905387648, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9648551525886192, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7749463735662483}}
{"text": "function exkrls{T}(x::Array{T}, y::Array{T}; nu=1., α=.5, β=0.5, q=.1, λ=0.1, kernelfunc=linear_kernel, maxdict=100)\n\n# krls(x, y)\n#\n# Julia version of the Extended Kernel Recursive Least Squares Algorithm\n#\n# Input:\n# \t\t\t  x : d(dimension) x N(samples) array\n# \t\t\t  y : 1 x N(samples) vector\n# \t         nu : approximate linear dependency (ALD) threshold, controls sparsity (default: 1.)\n# \t     λ : regularization parameter (default: 0.1)\n#        kernel : type of kernel (default : 'linear_kernel')\n#       maxdict : maximum dictionary size (default: 100)\n#         index : how to cycle through samples, 'lin' goes in order, 'rand' goes randomly, or you can provide your own vector index (default: 'lin')\n#\n# Output:\n#\t\t  alpha : weights on dictionary samples\n#\t\t   dict : dictionary samples\n#\t\t   Kinv : Inverse of kernel matrix\n#\t   dict_idx : dictionary sample indicies\n#\n#\n# Citation:\n# Y. Engel, S. Mannor, and R. Meir, “The kernel recursive least-squares algorithm,” IEEE Transactions on Signal Processing, vol. 52, no. 8, pp. 2275–2285, 2004.\n\n\nλ = convert(T, λ)\nnu = convert(T, nu)\n\nλ2 = λ.^2\n\nsz = size(x)\n\ndict = zeros(eltype(x), sz[1], maxdict)\ndict_idx = zeros(eltype(x), maxdict, 1)\n\n\n## Initialize\nK = kernelfunc(x[:,1], x[:,1])\nKinv = (1./K)'\nalpha = (α*y[1] ./ (λ*β+K))'\npr = λ*β / (abs(α)^2)\ndict[:,1] = x[:,1]\ndict_idx[1] = 1\nP = one(eltype(x))\nm = 1\nm2 = 1\n\nfor ii = 2:length(y)\n\n\tm2 = m2 + 1\n\n\tkt = kernelfunc(dict[:,1:m], x[:,ii]) + λ2\n\n\tktt = kernelfunc(x[:,ii], x[:,ii]) + λ2\n\n\tat = Kinv * kt'\n\n\tdt = ktt - kt*at\n\n\tkta = kt*alpha\n\n\te = y[ii] - kta[1]\n\n\tif abs(dt[1]) > nu && m < maxdict\n\n\t\tm = m + 1\n\n\t\tdict[:,m] = x[:,ii]\n\t\tdict_idx[m] = ii\n\n\t\tKinv = (1 ./ dt) .* [dt.*Kinv + at*at' -at; -at' 1]\n\n\t\tP = [P zeros(eltype(x),size(P,1), 1); zeros(eltype(x),1, size(P,1)) 1]\n\n\t\talpha = [alpha - ((at ./ dt) * e); (1./dt)*e]\n\n\t\tif mod(m,50)==0\n\t\t\tprintln(\"Dictionary Size: $m of $maxdict\")\n\t\tend\n\t\t\n\telse\n\n\t\tPat = P*at\n\t\tatPat = 1 + at'*Pat\n\n\t\tqt = Pat / atPat[1]\n\n\t\tatP = (at'*P)\n\n\t\t# P -= ((Pat*(at'*P)) ./ atPat)\n\t\t# optimized as\n\t\tBase.LinAlg.BLAS.gemm!('N', 'N', -one(eltype(y)), qt,atP, one(eltype(y)), P)\n\n\t\t# alpha +=  Kinv*qt*(y[ii] - kt*alpha)\n\t\t# optimized as\n\n\t\tBase.LinAlg.BLAS.gemm!('N', 'N', e, Kinv,qt, one(eltype(y)), alpha)\n\n\t\tif mod(m2,50)==0\n\t\t\tprintln(\"On sample: $m2 of $(sz[2])\")\n\t\tend\n\n\tend\n\nend\n\ndict = dict[:,1:m]\ndict_idx = dict_idx[1:m]\n\n(alpha, dict, Kinv, dict_idx)\n\nend", "meta": {"hexsha": "b11700bd0df305a437fe736588d7cc5cf7e6e9a5", "size": 2421, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/exkrls.jl", "max_stars_repo_name": "the-moliver/KernelRecursiveLeastSquares", "max_stars_repo_head_hexsha": "494f0dcf230b636b7f81d8a6c22be7a1de174e25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/exkrls.jl", "max_issues_repo_name": "the-moliver/KernelRecursiveLeastSquares", "max_issues_repo_head_hexsha": "494f0dcf230b636b7f81d8a6c22be7a1de174e25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/exkrls.jl", "max_forks_repo_name": "the-moliver/KernelRecursiveLeastSquares", "max_forks_repo_head_hexsha": "494f0dcf230b636b7f81d8a6c22be7a1de174e25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4247787611, "max_line_length": 160, "alphanum_fraction": 0.5828170178, "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7749227805201915}}
{"text": "mutable struct RegularizedSVD{T} <: MatrixFactorization{T}\n    P::Array\n    Q::Array\n    preference::Persa.Preference{T}\n    users::Int\n    items::Int\nend\n\nconst RSVD = RegularizedSVD\n\nfunction RegularizedSVD(dataset::Persa.Dataset, features::Int)\n    (users, items) = size(dataset)\n\n    P = rand(users, features)\n    Q = rand(items, features)\n\n    return RegularizedSVD(P, Q, dataset.preference, Persa.users(dataset), Persa.items(dataset))\nend\n\nPersa.predict(model::RegularizedSVD, user::Int, item::Int) = model.P[user, :]' * model.Q[item, :]\n\nfunction objective(model::RegularizedSVD, dataset::Persa.Dataset, λ::Float64)\n    total = 0\n\n    for (u, v, r) in dataset\n        total += (r - model[u, v])^2\n        total += λ * (norm(model.P[u,:])^2 + norm(model.Q[v,:])^2)\n    end\n\n    return total\nend\n\nfunction update!(model::RegularizedSVD, dataset::Persa.Dataset, γ::Float64, λ::Float64)\n\n    idx = shuffle(1:length(dataset))\n\n    for i = 1:length(dataset)\n        (u, v, r) = dataset[idx[i]]\n\n        e = r - Persa.predict(model, u, v)\n\n        P = model.P[u,:]\n        Q = model.Q[v,:]\n\n        model.P[u,:] += γ * (e .* Q .- λ .* P)\n        model.Q[v,:] += γ * (e .* P .- λ .* Q)\n    end\nend\n", "meta": {"hexsha": "3fe6791876081992ca416000a2242b3be5d1a078", "size": 1197, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rsvd.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/ModelBasedCF.jl-e5e64596-b6ca-11e8-20a9-11eddeb55bda", "max_stars_repo_head_hexsha": "b8e80922aaa3aad5f7759ef325d2d599986d099d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-30T10:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-30T10:55:58.000Z", "max_issues_repo_path": "src/rsvd.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/ModelBasedCF.jl-e5e64596-b6ca-11e8-20a9-11eddeb55bda", "max_issues_repo_head_hexsha": "b8e80922aaa3aad5f7759ef325d2d599986d099d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-08T15:56:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T15:56:44.000Z", "max_forks_repo_path": "src/rsvd.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/ModelBasedCF.jl-e5e64596-b6ca-11e8-20a9-11eddeb55bda", "max_forks_repo_head_hexsha": "b8e80922aaa3aad5f7759ef325d2d599986d099d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:54:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:54:52.000Z", "avg_line_length": 24.4285714286, "max_line_length": 97, "alphanum_fraction": 0.5964912281, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7749227758269172}}
{"text": "# Plot of various Mathieu functions, inspired by https://dlmf.nist.gov/28.3\nusing Mathieu, PyPlot\nconst MPL = PyPlot.matplotlib\n\n# get the same line colors\nPyPlot.PyDict(MPL.\"rcParams\")[\"axes.prop_cycle\"] =\n    MPL.cycler(color=[\"#2ca02c\",\"#d62728\",\"#1f77b4\",\"#ff7f0e\"])\n\n# plot parameters\nz = LinRange(0,π/2,101)\nn = 0:3\n\nfor q in [1,10]\n    f,ax = subplots(2,2,figsize=(10,8));\n    f.suptitle(\"Mathieu Functions for \\$q=$q\\$\");\n\n    ax[1].set_title(\"Even π-Periodic Solutions\");\n    ax[1].plot(z, Mathieu.cep(n,q,z));\n    ax[1].legend(string.(\"\\$ce_\",2n,\"\\$\"));\n\n    ax[2].set_title(\"Even π-Antiperiodic Solutions\");\n    ax[2].plot(z, Mathieu.cea(n,q,z));\n    ax[2].legend(string.(\"\\$ce_\",2n.+1,\"\\$\"));\n\n    ax[3].set_title(\"Odd π-Antiperiodic Solutions\");\n    ax[3].plot(z, Mathieu.sea(n,q,z));\n    ax[3].legend(string.(\"\\$se_\",2n.+1,\"\\$\"));\n\n    ax[4].set_title(\"Odd π-Periodic Solutions\");\n    ax[4].plot(z, Mathieu.sep(n,q,z));\n    ax[4].legend(string.(\"\\$se_\",2n.+2,\"\\$\"));\nend\n", "meta": {"hexsha": "5256ef623854a468dae2d1221dca9f976e5b0715", "size": 985, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/functionplots.jl", "max_stars_repo_name": "jebej/Mathieu.jl", "max_stars_repo_head_hexsha": "613825b54e108c7da209c82eb43349d76aec3257", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-08-05T13:47:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-09T23:19:28.000Z", "max_issues_repo_path": "examples/functionplots.jl", "max_issues_repo_name": "jebej/Mathieu.jl", "max_issues_repo_head_hexsha": "613825b54e108c7da209c82eb43349d76aec3257", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-12-12T19:32:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-12T19:32:52.000Z", "max_forks_repo_path": "examples/functionplots.jl", "max_forks_repo_name": "jebej/Mathieu.jl", "max_forks_repo_head_hexsha": "613825b54e108c7da209c82eb43349d76aec3257", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8484848485, "max_line_length": 75, "alphanum_fraction": 0.6101522843, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913354875362, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7749227731606243}}
{"text": "\"\"\"\n   LaguerreWeight(α)\n\nis a quasi-vector representing `x^α * exp(-x)` on `0..Inf`.\n\"\"\"\nstruct LaguerreWeight{T} <: Weight{T}\n    α::T\nend\n\nLaguerreWeight{T}() where T = LaguerreWeight{T}(zero(T))\nLaguerreWeight() = LaguerreWeight{Float64}()\naxes(::LaguerreWeight{T}) where T = (Inclusion(ℝ),)\nfunction getindex(w::LaguerreWeight, x::Number)\n    x ∈ axes(w,1) || throw(BoundsError())\n    x^w.α * exp(-x)\nend\n\nsum(L::LaguerreWeight{T}) where T = gamma(L.α + 1)\n\nstruct Laguerre{T} <: OrthogonalPolynomial{T} \n    α::T\n    Laguerre{T}(α) where T = new{T}(convert(T, α))\nend\nLaguerre{T}() where T = Laguerre{T}(zero(T))\nLaguerre() = Laguerre{Float64}()\nLaguerre(α::T) where T = Laguerre{float(T)}(α)\northogonalityweight(L::Laguerre)= LaguerreWeight(L.α)\n\n==(L1::Laguerre, L2::Laguerre) = L1.α == L2.α\naxes(::Laguerre{T}) where T = (Inclusion(HalfLine{T}()), oneto(∞))\n\n\"\"\"\n     laguerrel(n, α, z)\n\ncomputes the `n`-th generalized Laguerre polynomial, orthogonal with \nrespec to `x^α * exp(-x)`, at `z`.\n\"\"\"\nlaguerrel(n::Integer, α, z::Number) = Base.unsafe_getindex(Laguerre{promote_type(typeof(α), typeof(z))}(α), z, n+1)\n\n\"\"\"\n     laguerrel(n, z)\n\ncomputes the `n`-th Laguerre polynomial, orthogonal with \nrespec to `exp(-x)`, at `z`.\n\"\"\"\nlaguerrel(n::Integer, z::Number) = laguerrel(n, 0, z)\n\n\n# L_{n+1} = (-1/(n+1) x + (2n+α+1)/(n+1)) L_n - (n+α)/(n+1) L_{n-1}\n# - (n+α) L_{n-1} + (2n+α+1)* L_n -(n+1) L_{n+1} = x  L_n\n# x*[L_0 L_1 L_2 …] = [L_0 L_1 L_2 …] * [(α+1)    -(α+1); -1  (α+3)     -(α+2);0  -2   (α+5) -(α+3); …]   \nfunction jacobimatrix(L::Laguerre{T}) where T\n    α = L.α\n    Tridiagonal(-(1:∞), (α+1):2:∞, -(α+1:∞))\nend\n\nrecurrencecoefficients(L::Laguerre{T}) where T = ((-one(T)) ./ (1:∞), ((L.α+1):2:∞) ./ (1:∞), (L.α:∞) ./ (1:∞))\n\n##########\n# Derivatives\n##########\n\n@simplify function *(D::Derivative, L::Laguerre)\n    T = promote_type(eltype(D),eltype(L))\n    D = _BandedMatrix(Fill(-one(T),1,∞), ∞, -1,1)\n    Laguerre(L.α+1)*D\nend", "meta": {"hexsha": "b61ed7be76a39f170099f2c9070bb527cc41f908", "size": 1953, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/classical/laguerre.jl", "max_stars_repo_name": "ioannisPApapadopoulos/ClassicalOrthogonalPolynomials.jl", "max_stars_repo_head_hexsha": "63610e3236dd7ffa9152db00734aab6af28f1793", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-01-26T15:24:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T13:53:03.000Z", "max_issues_repo_path": "src/classical/laguerre.jl", "max_issues_repo_name": "ioannisPApapadopoulos/ClassicalOrthogonalPolynomials.jl", "max_issues_repo_head_hexsha": "63610e3236dd7ffa9152db00734aab6af28f1793", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2021-01-27T21:38:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T14:54:26.000Z", "max_forks_repo_path": "src/classical/laguerre.jl", "max_forks_repo_name": "ioannisPApapadopoulos/ClassicalOrthogonalPolynomials.jl", "max_forks_repo_head_hexsha": "63610e3236dd7ffa9152db00734aab6af28f1793", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-01-27T11:21:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T18:15:59.000Z", "avg_line_length": 29.1492537313, "max_line_length": 115, "alphanum_fraction": 0.5878136201, "num_tokens": 833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133548753619, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7749227711336423}}
{"text": "using Symbolics, Test\n\n@sym x y z m ω t μ\n\n@testset \"   Euler-Lagrange Solver\" begin\n    function Γ(w)\n       t -> UpTuple([t, w(t), D(w)(t)])\n    end\n\n    function Lagrange_Equations(L)\n        w -> D(∂(3)(L)∘Γ(w)) - ∂(2)(L)∘Γ(w)\n    end\n\n    function L_SHO(local_tuple::UpTuple)\n        t, q, qdot = local_tuple.data\n        (0.5m)*qdot^2 - (0.5m*ω^2)*q^2\n    end\n\n    function L_free(local_tuple::UpTuple)\n        t, q, qdot = local_tuple.data\n        (0.5m)*qdot^2\n    end\n\n    function L_pendulum(local_tuple::UpTuple)\n        t, q, qdot = local_tuple.data\n        m*qdot^2/2+cos(q)\n    end\n\n    @test Lagrange_Equations(L_SHO)(x)(t)  == (D(D(x)))(t) * m + (x)(t) * m * ω ^ 2\n    @test Lagrange_Equations(L_free)(x)(t) == (D(D(x)))(t) * m\n    @test Lagrange_Equations(L_pendulum)(x)(t) == (D(D(x)))(t) * m + sin((x)(t))\n\n    # Lagrangian for the free particle in space (3D)\n    function L_free_3d(local_tuple::UpTuple)\n        t, q, qdot = local_tuple.data\n        (qdot[1]^2+qdot[2]^2+qdot[3]^2)/2\n    end\n\n    q = UpTuple([x, y, z])\n\n    lagrange_eqs_fp3d = Lagrange_Equations(L_free_3d)(q)\n    lagrange_eqs_fp3d_t = Lagrange_Equations(L_free_3d)(q)(t)\n    @test typeof(lagrange_eqs_fp3d_t) == UpTuple\n    fp3d_eqs = [(D(D(x)))(t), (D(D(y)))(t), (D(D(z)))(t)] # eqs of motion for the free particle in space\n    @test lagrange_eqs_fp3d_t.data == fp3d_eqs\n    @test lagrange_eqs_fp3d_t == up(fp3d_eqs)\n    @test lagrange_eqs_fp3d_t == UpTuple(fp3d_eqs)\n    @test lagrange_eqs_fp3d(t).data == fp3d_eqs\n    @test lagrange_eqs_fp3d(t) == up(fp3d_eqs)\n    @test lagrange_eqs_fp3d(t) == UpTuple(fp3d_eqs)\n\n    # Lagrangian for the Kepler problem\n    function L_kepler(local_tuple::UpTuple)\n        t, q, qdot = local_tuple.data\n        r = (q[1]^2+q[2]^2)^(1/2)\n        (qdot[1]^2+qdot[2]^2)*(m/2)+μ/r\n    end\n\n    q = UpTuple([x, y])\n\n    # Equivalent to Eq. (1.48) of SICM\n    lagrange_eqs_kepler = Lagrange_Equations(L_kepler)(q)\n    lagrange_eqs_kepler_t = Lagrange_Equations(L_kepler)(q)(t)\n    @test typeof(lagrange_eqs_kepler_t) == UpTuple\n    kepler_eqs = [m * (D(D(x)))(t) + ((x)(t) ^ 2 + (y)(t) ^ 2) ^ -1.5 * (x)(t) * μ, m * (D(D(y)))(t) + ((x)(t) ^ 2 + (y)(t) ^ 2) ^ -1.5 * (y)(t) * μ]\n    @test lagrange_eqs_kepler_t.data == kepler_eqs\n    @test lagrange_eqs_kepler_t == up(kepler_eqs)\n    @test lagrange_eqs_kepler_t == UpTuple(kepler_eqs)\n    @test lagrange_eqs_kepler(t).data == kepler_eqs\n    @test lagrange_eqs_kepler(t) == up(kepler_eqs)\n    @test lagrange_eqs_kepler(t) == UpTuple(kepler_eqs)\n\nend\n", "meta": {"hexsha": "5a543d636189b12113304313c8aafc20e85ae105", "size": 2517, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/eulerlagrange.jl", "max_stars_repo_name": "jagot/Symbolics.jl", "max_stars_repo_head_hexsha": "b8994e3d79803daa3a57012fe9ccbe0b01c346d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 102, "max_stars_repo_stars_event_min_datetime": "2018-01-20T22:35:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T07:29:23.000Z", "max_issues_repo_path": "test/eulerlagrange.jl", "max_issues_repo_name": "jagot/Symbolics.jl", "max_issues_repo_head_hexsha": "b8994e3d79803daa3a57012fe9ccbe0b01c346d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2018-10-02T06:44:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T02:04:30.000Z", "max_forks_repo_path": "test/eulerlagrange.jl", "max_forks_repo_name": "jagot/Symbolics.jl", "max_forks_repo_head_hexsha": "b8994e3d79803daa3a57012fe9ccbe0b01c346d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2018-05-02T19:10:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T09:36:14.000Z", "avg_line_length": 34.0135135135, "max_line_length": 149, "alphanum_fraction": 0.6058800159, "num_tokens": 1007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7749227615289945}}
{"text": "struct FractionalFactorial <: GSAMethod\nend\n\n\"\"\"\nCode based on the theory presetned in:\nSaltelli, A. (2008). Global sensitivity analysis: The primer. Chichester: Wiley, pp. 71-76.\n\"\"\"\n\nusing LinearAlgebra\n\nfunction _recursive_hadamard(k::Integer)\n     \"\"\"\n     Generate a hadamard matrix via recursion.\n     \"\"\"\n     # base case\n     if k == 2\n          return [1 1; 1 -1]\n     else\n          h = _recursive_hadamard(k ÷ 2)\n     end\n\n     return hcat(vcat(h, h), vcat(h, -h))\nend\n\n\nfunction _expanding_window_hadamard(k::Integer)\n     \"\"\"\n     Generate hadamard matrix of size k using expanding window approach.\n     \"\"\"\n     @assert ispow2(k)\n\n     # intialize\n     h = ones(Int64, k, k)\n     h[2,2] = -1\n\n     let\n        bot_row = 2\n        right_col = 2\n        while bot_row < k\n\n             @inbounds cur = h[1:bot_row, 1:right_col]\n\n             new_bot = bot_row+1:bot_row*2\n             new_right = right_col+1:right_col*2\n             # update right\n             @inbounds h[1:bot_row, new_right] = cur\n\n             # update below\n             @inbounds h[new_bot, 1:right_col] = cur\n\n             # update diagonal\n             @inbounds h[new_bot, new_right] = - cur\n\n             # update window for each to 'copy' from.\n             bot_row *= 2\n             right_col *= 2\n        end\n     end\n     return h\nend\n\n\nfunction _generate_hadamard(k::Integer)\n     @assert ispow2(k)\n     return _expanding_window_hadamard(k)\nend\n\n\nfunction generate_ff_design_matrix(num_parameters::Integer)\n     \"\"\"\n     param: num_parameters\n          The number of parameters to be sampled for.\n\n     return:\n          A 2-level fractional factorial design matrix of -1s and 1s with a design of resolution IV.\n\n          The number of rows is 2*number of parameters and the number of columns is the number of parameters.\n\n          See equation (2.31) in Saltelli, A. (2008) for details.\n     \"\"\"\n\n     # If k is not a power of 2, get the next larger number that is\n     # so the hadamard matrices can be computed.\n     k = Integer(round(2^ceil(log2(num_parameters))))\n\n     s = _generate_hadamard(k)\n     design_matrix = vcat(s, -s) # design of resolution IV.\n\n     return design_matrix\nend\n\n\nfunction generate_ff_sample_matrix(design_matrix::Array{Int64,2},  levels_list=nothing)\n      \"\"\"\n\n      Convert the desgin matrix to a matrix whose rows can\n      be used as inputs to a model by replacing low and high values for each parameter\n      with the the low and high end of each parameters range, as specified in levels_list.\n\n      param: design_matrix\n\n            The matrix outputted by 'ff_design' i.e a 2-level fractional\n            factorial design matrix of -1s and 1s with a design of resolution IV.\n            The number of rows is 2*number of parameters and the\n            number of columns is the number of parameters.\n\n      param: levels_list (optional)\n          A list of length equal to the number of parameters, where the elements of\n          the list are 2-tuples.\n\n          The ith tuple corresponds to the the low-value and the high-value of the ith parameter.\n          i.e. levels_list[2][1] corresponds to the low-value of the 2nd parameter,\n          and levels_list[2][2] corresponds to the high-value of the 2nd parameter.\n\n          If no list is provided, the low value for each parameter\n          is assumed to be 0 and the high value is assumed to be 1.\n\n      returns:\n          A matrix with the same dimensions as the design matrix, but with the '-1's replaced with\n          the low value specified for each parameter in level_list, and similar the '1's are replaced\n          with the high values.\n\n          Each row corresponds to a single input vector to be used as input to a model/function.\n      \"\"\"\n      sample_matrix = copy(design_matrix)\n      if !isnothing(levels_list)\n           for (col_index, (low_value, high_value)) in enumerate(levels_list)\n                design_col = @view design_matrix[:,col_index]\n                sample_col = @view sample_matrix[:,col_index]\n\n                sample_col[design_col .== -1] .= low_value\n                sample_col[design_col .== 1] .= high_value\n            end\n      end\n      return sample_matrix\nend\n\nfunction run_model(sample_matrix::AbstractArray, model)\n      \"\"\"\n\n      param: sample_matrix\n            A matrix where each row corresponds to a input vector for \"model\"\n      param: model\n            The function/model to be executed on each row of the sample_matrix.\n            Must return a scalar.\n      return:\n            A vector containing the result of running each row of the\n            sample_matrix through model.\n      \"\"\"\n\n      N = size(sample_matrix)[1]\n      y_out = zeros(N)\n      Threads.@threads for i in 1:N\n          y_out[i] = model(@view sample_matrix[i,:])\n      end\n      return y_out\nend\n\n\nfunction ff_main_effects(design_matrix::AbstractArray, response_values::AbstractArray)\n      \"\"\"\n           Computes the main effect for each parameter\n\n           param: design_matrix\n\n                The matrix outputted by 'ff_design' i.e a 2-level fractional\n                factorial design matrix of -1s and 1s with a design of resolution IV.\n                The number of rows is 2*number of parameters and the\n                number of columns is the number of parameters.\n\n           param: response_values\n\n                An array of values corresponding to the result of running the\n                model on each row of a sample matrix generated by the design_matrix\n\n           return: main_effects\n\n               A vector of the main effects of each parameter on the output.\n\n            See Saltelli, A. equation 2.32 for details.\n      \"\"\"\n\n      num_rows, num_cols = size(design_matrix)\n      @assert num_rows == length(response_values) \"Number of rows in design matrix must match number of responses\"\n\n      main_effects = zeros(num_cols)\n      for column in 1:num_cols\n            contrast_vector = @view design_matrix[:,column]\n            main_effects[column] = dot(response_values, contrast_vector)\n      end\n      return main_effects ./ num_rows\nend\n\nfunction gsa(f, method::FractionalFactorial; num_params, N, p_range = nothing, kwargs...)\n    design_matrix = generate_ff_design_matrix(num_params)\n    sample_matrix = generate_ff_sample_matrix(design_matrix, p_range)\n\n    response_vec = run_model(sample_matrix, f)\n\n    main_effects = ff_main_effects(design_matrix, response_vec)\n    return main_effects, main_effects.^2\nend", "meta": {"hexsha": "03959539492aacd1953b1be80ae081d6e909a2da", "size": 6474, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fractional_factorial_sensitivity.jl", "max_stars_repo_name": "stjordanis/GlobalSensitivity.jl", "max_stars_repo_head_hexsha": "349d01d548efe6dea564ba57cd917acea5a8b71a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fractional_factorial_sensitivity.jl", "max_issues_repo_name": "stjordanis/GlobalSensitivity.jl", "max_issues_repo_head_hexsha": "349d01d548efe6dea564ba57cd917acea5a8b71a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fractional_factorial_sensitivity.jl", "max_forks_repo_name": "stjordanis/GlobalSensitivity.jl", "max_forks_repo_head_hexsha": "349d01d548efe6dea564ba57cd917acea5a8b71a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0495049505, "max_line_length": 114, "alphanum_fraction": 0.640562249, "num_tokens": 1514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7749227601413234}}
{"text": "using LinearAlgebra\nusing Base: require_one_based_indexing\n\n\n\"\"\"\n    systemSolver(A::AbstractMatrix, b::Vector, x_initial::Vector) -> Vector\n\n    Compute the orthogonal projection of a given point to the \nsolution set of a system of linear equations. Also a direct \nmethod for solving systems of linear equations. The output \nis either the projection or inconsistency of the system.\n\n# Arguments\n - `A::AbstractMatrix{Real}`: coefficients of linear equations\n - `b::AbstractVector{Real}`: intended results of equations\n - `x0::AbstractVector{Real}`: initial point for projection\n - `β::Real`: set in order to obtain comparable summands in norm\n\n# References\n> Ján Plesník, Finding the orthogonal projection of a point onto \n> an affine subspace, Linear Algebra and its Applications, Volume 422, \n> Issues 2–3, 2007, Pages 455-470\n\"\"\"\nfunction systemSolver(A::AbstractMatrix{<:Real},    # in: equations matrix (m x n) rows = coefficients\n                    b::AbstractVector{<:Real},      # in: equations results\n                    x0::AbstractVector{<:Real},     # in: initial point\n                    β::Real=1.0)                    # in: optional normalizer\n    \n    require_one_based_indexing(A, b, x0)\n    m, n = size(A)\n    if m != length(b) || n != length(x0)\n        throw(DimensionMismatch(\"dimensions of `A`, $m * $n, does not match one of the lengths of `x0`, $(length(x0)), or `b`, $(length(b))\"))\n    end\n    for i in 1:m\n        iszero(A[i, :]) && throw(ArgumentError(\"`A` rows must be nonzero\"))\n    end\n    iszero(β) && throw(ArgumentError(\"`β` must be nonzero\"))\n\n    if m == 0\n        return x0\n    end\n\n    k = 1\n    p = 1\n    V = hcat(A[1, :])\n    x = x0 + (b[1] - dot(A[1, :], x0))/(dot(A[1, :], V[:, 1])) * V[:, 1]\n\n    denominators = zeros(Real, m-1)\n    \n    while k != m\n        k = k + 1\n        p = p + 1\n        \n        denominators[k-1] = dot((A[k, :] - A[1, :]), V[:, k-1])\n        if denominators[k-1] == 0\n            A[k, :] = - A[k, :]\n            b[k] = - b[k]\n            denominators[k-1] = dot((A[k, :] - A[1, :]), V[:, k-1])\n        end\n\n        w = x0 + β * A[k, :]\n        for j in 2:k\n            w = w + (b[j]-b[1]-dot(A[j, :]-A[1, :], w))/denominators[j-1] * V[:, j-1]\n        end\n\n        u = x + (b[k] - dot(A[k, :], x))/denominators[k-1] * V[:, k-1]\n        if u != w\n            V = hcat(V, w - u)\n            x = u + (b[1] - dot(A[1, :], u))/dot(A[1, :], V[:, k]) * V[:, k]\n        elseif dot(A[k, :], x) == b[k]\n            if k != m\n                A = A[setdiff(1:end, k), :]\n                b = b[setdiff(1:end, k)]\n                k = k - 1\n                m = m - 1\n            end\n        else\n            throw(DomainError(\"the ($p)th equation is inconsistent\"))\n        end\n    end\n    return x\nend", "meta": {"hexsha": "c4b2ce713093ac464a8ccaff24525946e000eac1", "size": 2759, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solver.jl", "max_stars_repo_name": "amir-ni/ALA-extra", "max_stars_repo_head_hexsha": "53bf51a7a2cb06662ff3f64f413f8629216c6441", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/solver.jl", "max_issues_repo_name": "amir-ni/ALA-extra", "max_issues_repo_head_hexsha": "53bf51a7a2cb06662ff3f64f413f8629216c6441", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solver.jl", "max_forks_repo_name": "amir-ni/ALA-extra", "max_forks_repo_head_hexsha": "53bf51a7a2cb06662ff3f64f413f8629216c6441", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6463414634, "max_line_length": 142, "alphanum_fraction": 0.5186661834, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7749187816142051}}
{"text": "\"\"\"\n     l63!(du,u,p,t)\n\n Steps forward the Lorenz63 equations for time `t`. \n Prognostic variables x, y, z are defined as\n elements 1, 2 and 3 of vector `u` and with parameters\n σ, ρ and β defined as elements of vector `p`.\n Elements of du are set to dxdt, dydt and dzdt respectively.\n\n```\n julia> using DifferentialEquations, Plots\n julia> u0=[1.,0.,0.]\n julia> p=[10.,28.,8/3]\n julia> tspan=(0.,100.)\n julia> prob=ODEProblem(l63!,u0,tspan,p)\n julia> sol=solve(prob)\n julia> plot(sol,vars=(1,2,3))\n```\n\n\"\"\"\nfunction l63!(du,u,p,t)\n        x, y, z=u\n        σ, ρ, β=p\n\n        dxdt=σ*(y-x)\n        dydt=ρ*x-x*z-y\n        dzdt=x*y-β*z\n\n        du[1], du[2], du[3]=\n        dxdt , dydt,  dzdt\n        return\nend\n", "meta": {"hexsha": "06ad03a3b809d0232d47c79bd192f41b3abd0eef", "size": 711, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/l63.jl", "max_stars_repo_name": "christophernhill-dev/fall-2021-12.010", "max_stars_repo_head_hexsha": "5b417379d436896c6c20886780a93a4876797a1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-09T19:50:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T19:09:02.000Z", "max_issues_repo_path": "Julia/l63.jl", "max_issues_repo_name": "christophernhill-dev/fall-2021-12.010", "max_issues_repo_head_hexsha": "5b417379d436896c6c20886780a93a4876797a1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/l63.jl", "max_forks_repo_name": "christophernhill-dev/fall-2021-12.010", "max_forks_repo_head_hexsha": "5b417379d436896c6c20886780a93a4876797a1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-12-02T02:15:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T20:30:39.000Z", "avg_line_length": 21.5454545455, "max_line_length": 60, "alphanum_fraction": 0.5864978903, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7749187776308901}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ db4a6b48-99a7-11eb-097b-676aed417c48\nbegin \n\ninclude(\"MultiArmBandit.jl\")\n\nusing .MultiArmBandit \nusing DataFrames \nusing StatsBase, Statistics \nusing Distributions\nusing Gadfly \nimport Random \n\nend\n\n# ╔═╡ b65dd189-456b-40ac-88fc-d05b5e29b396\nmd\" \n\n# Multi-Arm Bandits\n\nA Multi-Arm Bandit is a concept from Reinforcement Learning which is useful for decision making under uncertainty. Take a situation where you have limited time or resources to test multiple drugs, perhaps the COVID vaccines for example. While you could use the standard approach of a clinical trial with randomization, a balanced design, and performing AB tests, this results in many participants not recieving the best treatment, as some of them will be allocated to inferior choices. Ideally, we would like to do both: 1) Show a given treatment is the best choice and 2) Have most people end up benefitting from it. \n\n\nUsing a strategy known as $\\epsilon$-greedy Q learning, the Multi Arm bandit can help accomplish this task in an online manner where the treatments are allocated on the spot. The arm refers to different treatment groups that the bandit can select from. In the beginning, each treatment arm is assigned the same value of $Q_{tmt}=Q_{0}$. Some small amount of noise can be added to break ties. At each step, $(1-\\epsilon)$ of the time the bandit randomly selects from the treatment with the highest $Q_{tmt}$ and updates its corresponding value. $\\epsilon$ of the time, the bandit will select a random treatment instead of the one with the highest Q. The update rule is as follows: \n\n\n$Q_{tmt,t} = Q_{tmt,t-1} + \\frac{R-Q_{tmt,t-1}}{N_{tmt,t}}$ \n\nwhere R is the reward, which is usually just the response Y corresponding to the treatment given. $N_{t+1}$ corresponds to the sample size in the given treatment group after the sample from the group is randomly selected. The bandit will be trying to go for the treatment which maximizes the reward, and so care should be taken that the response is transformed or sign-flipped if necessary so that higher is better. The above update rule can be shown to correspond to the calculation of the sample mean in an online manner if $Q_{0} = 0$. However, we can modify  the updates by adding an explicit learning rate parameter $\\eta$:\n\n$Q_{tmt,t+1} = Q_{tmt,t} + \\eta(R-Q_{tmt,t})$\n\nThis can help improve learning. In this notebook, we will simulate data from 5 groups and examine the impact of setting different parameters for $Q_{0}$ and $\\eta$. \n\nThe source code for the functions used in this demo Pluto notebook can be found in the **MultiArmBandit.jl** module in this repo.\n\n\"\n\n# ╔═╡ 38528382-a1ec-4117-88d4-fbcc019c7302\nmd\"\n\n## Simulate Data \n\nBelow, we simulate n=10000 points from 5 groups each A, B, C, D, E from a normal distibution with mean $\\mu = (-0.3,0.0,0.5,0.8,1.1)$ and $\\sigma = (1, 0.5, 0.3, 0.3, 0.5)$ respectively. The bandit will select points from this simulated dataset. Note that in the ideal situation the ground truth in this simulated example is: \n\n$ E > D > C > B > A $\n\nIdeally, the bandit will come to this same conclusion and choose E most of the time. However, the different SDs for the groups can complicate this choice, as the bandit is greedy and thus converging to E in a finite number of iterations (in the real world, this would correspond to resources or number of patients in the trial) can be more complicated. We can track the bandit's history and plot it over time to examine when convergence occurs. \n\nThe sample mean/SD of each Arm are shown below. The bandit will be selecting samples from each group in an online manner, and so at each step it does NOT have access to every single data point. Instead it must figure out in the finite number of iterations which group is the best\n\n\"\n\n# ╔═╡ 60e50c4e-8120-4306-9c6c-9282fff8eb47\nbegin \n\t\nn = 1000\nRandom.seed!(101)\nA= rand(Normal(-0.3,1),n)\nB= rand(Normal(0,0.5),n)\nC = rand(Normal(0.5,0.3),n)\nD = rand(Normal(0.8,0.3),n)\nE = rand(Normal(1.1,0.5),n)\n\nsimdata = DataFrame(Arm = vcat(fill(\"A\",n),fill(\"B\",n),fill(\"C\",n),fill(\"D\",n),fill(\"E\",n)),\n                    Y = vcat(A,B,C,D,E))\n\nsummary_simdata = combine(groupby(simdata,:Arm),nrow,:Y=>mean=>:meanY,:Y=>std=>:sdY)\nsummary_simdata\nend \n\n# ╔═╡ 65107f38-7916-43a4-b36f-1ef012c43b51\nmd\"\n\n## Create Bandit: $Q_0=0, \\eta=\\frac{1}{N_{tmt,t}}, \\epsilon = 0.1$ \n\nBelow we instantiate the first bandit with all default settings, and allow it to explore 10% of the time while 90% of the time it selects the current best group in a greedy manner. \n\n\"\n\n# ╔═╡ 8ed00c06-7348-49dc-a9f2-041465beb969\nband1=MultiArmBandit.CreateBandit(simdata,:Arm,:Y,track_hist=true)\n\n# ╔═╡ 472fee46-6e48-47a7-9235-ccb7c460f735\nbegin \nRandom.seed!(1001)\nMultiArmBandit.Train!(band1,999,ϵ = 0.1)\nend \n\n# ╔═╡ 1243d0ab-f95c-482d-b81e-3b3eb60907eb\nband1_df = MultiArmBandit.GetHistoryDF(band1)\n\n# ╔═╡ 794d15a3-a4b4-4ffa-9afb-bb19d79e79e5\nplot(band1_df,x=:steps,y=:Q,color=:Group,Geom.line)\n\n# ╔═╡ 5e8e7408-aa48-4a2d-a427-40e8adf81d3c\nband1_summary = summary(band1)\n\n# ╔═╡ 32f83952-c660-4fde-8bd5-ae1a97e7bacd\nmd\"\n\nBased on the above figure, the correct ordering is found after around 250 steps. For the first few steps, the bandit picks Group D which is the 2nd best but eventually finds Group C as a result of the exploration. Lets try to see what happens if we lower the bandit's exploration by setting $\\epsilon = 0.03$. That is, the bandit will select a group randomly (instead of the group it deems the best group at the moment) 3% of the time. \n\n## Create Bandit: $Q_0=0, \\eta=\\frac{1}{N_{tmt,t}}, \\epsilon = 0.03$ \n\n\"\n\n# ╔═╡ 65945e4f-17e9-40ba-870f-88da0c5d13d0\nbegin\nband2=MultiArmBandit.CreateBandit(simdata,:Arm,:Y,track_hist=true)\nRandom.seed!(1102)\nMultiArmBandit.Train!(band2,999,ϵ = 0.03)\nband2_df = MultiArmBandit.GetHistoryDF(band2)\nband2_summary = summary(band2)\nend \n\n# ╔═╡ 3566a579-84dc-4cb6-91ab-833d0d5e9782\nplot(band2_df,x=:steps,y=:Q,color=:Group,Geom.line)\n\n# ╔═╡ a15c8f8f-f077-4758-a668-01c8b562ca95\nmd\"\n\nIn this situation, it took longer (~100 iterations) for the bandit to arrive at the best group\n\nIn the next section, we will change the starting value to be higher at $Q_{0} = 5$. This will tend to encourage a lot more early exploration as this value is much higher than what is possible based on sampling. \n\n## Create Bandit: $Q_0=5, \\eta=\\frac{1}{N_{tmt,t}}, \\epsilon = 0.1$ \n\n\"\n\n# ╔═╡ 77d6e956-219e-40e9-978d-f7e0906a8d6c\nbegin\nband3=MultiArmBandit.CreateBandit(simdata,:Arm,:Y,Q₀=5,track_hist=true)\nRandom.seed!(901)\nMultiArmBandit.Train!(band3,99,ϵ = 0.1)\nband3_df = MultiArmBandit.GetHistoryDF(band3)\nband3_summary = summary(band3)\nend \n\n# ╔═╡ 043f9d99-e8b5-4b33-82ac-3870a2238f85\nplot(band3_df,x=:steps,y=:Q,color=:Group,Geom.line)\n\n# ╔═╡ 50196d6d-8a52-4043-aa9f-e3f43a9ed2a1\nmd\"\n\nIn this case, starting at a value much higher than possible leads to earlier exploration, resulting in the Q value for each group falling rapidly. However, the bandit arrives at the best option E much quicker since it is pulled down less and is essentially guaranteed to be selected since the bandit desperately switches options more in the beginning to try to maintain a high Q value. \n\nIn this next part, we keep $Q_0 = 5$ but set the learning rate $\\eta=0.01$\n\n## Create Bandit: $Q_0=5, \\eta=0.01, \\epsilon = 0.1$ \n\n\n\"\n\n# ╔═╡ 9f3d4773-ac0a-4dd2-992d-b549f58f4021\nbegin\nband4=MultiArmBandit.CreateBandit(simdata,:Arm,:Y,Q₀=5,track_hist=true)\nRandom.seed!(555)\nMultiArmBandit.Train!(band4,2999,ϵ = 0.1,η=0.01)\nband4_df = MultiArmBandit.GetHistoryDF(band4)\nband4_summary = summary(band4)\nend \n\n# ╔═╡ 3789a09f-73fb-4ca8-b267-bbe2d7b32848\nplot(band4_df,x=:steps,y=:Q,color=:Group,Geom.line)\n\n# ╔═╡ 7825e432-9f3b-4099-bf37-0b1b3ccf38c1\nmd\"\n\nIn this case, setting the learning rate to 0.01 leads the bandit to take longer to reach the optimal solution E. Until around 1500 steps, the Q value for all the groups is even. \n\nWhat happens if we increase the learning rate to 1 (but keep $Q_0 = 5$) ? \n\n## Create Bandit: $Q_0=5, \\eta=1, \\epsilon = 0.1$ \n\n\n\n\"\n\n# ╔═╡ 2342907c-75e0-4126-b2df-6ce5a5901bf1\nbegin\nband5=MultiArmBandit.CreateBandit(simdata,:Arm,:Y,Q₀=5,track_hist=true)\nRandom.seed!(1556)\nMultiArmBandit.Train!(band5,2999,ϵ = 0.1,η=1)\nband5_df = MultiArmBandit.GetHistoryDF(band5)\nband5_summary = summary(band5)\nend \n\n# ╔═╡ 7c511272-01f8-4270-bdf7-f4f66e78df07\nplot(band5_df,x=:steps,y=:Q,color=:Group,Geom.line)\n\n# ╔═╡ c1deba65-a93f-4992-958e-38a987346691\nmd\"\n\nNow the plot is extremely noisy, and the bandit cannot seem to differentiate between Group D and Group E very well. We can see in the summary that the bandit tended to select D the most but in the end the Q values of both D/E are about the same. \n\nIn this final parts, we now set $Q_0=0$ again and examine the impact of the two learning rates. \n\n## Create Bandit: $Q_0=0, \\eta=0.01, \\epsilon = 0.1$ \n\n\n\"\n\n# ╔═╡ 8bbfae0c-6648-4f42-a40c-ada03d17bb3a\nbegin\nband6=MultiArmBandit.CreateBandit(simdata,:Arm,:Y,Q₀=0,track_hist=true)\nRandom.seed!(121)\nMultiArmBandit.Train!(band6,2999,ϵ = 0.1,η=0.01)\nband6_df = MultiArmBandit.GetHistoryDF(band6)\nband6_summary = summary(band6)\nend \n\n# ╔═╡ 613e3215-4402-4ba2-8402-2ab5bf1f1247\nplot(band6_df,x=:steps,y=:Q,color=:Group,Geom.line)\n\n# ╔═╡ e7772e4c-b798-4bdd-85c1-6ee291fce282\nmd\"\n\nIn this case, starting at $Q_0=0$ and setting the learning rate $\\eta = 0.01$ leads to the bandit favoring Group C, a suboptimal group, for a long time. It is only after ~2700 iterations that it picks up on Group E. \n\nWhat happens if the learning rate is increased? Will we see the same noisy behavior as before when starting from $Q_0=0$? \n\n## Create Bandit: $Q_0=0, \\eta=1, \\epsilon = 0.1$ \n\n\n\n\"\n\n# ╔═╡ bf545060-f55c-4a91-99f8-c41543c25ebb\nbegin\nband7=MultiArmBandit.CreateBandit(simdata,:Arm,:Y,Q₀=0,track_hist=true)\nRandom.seed!(13)\nMultiArmBandit.Train!(band7,2999,ϵ = 0.1,η=1)\nband7_df = MultiArmBandit.GetHistoryDF(band7)\nband7_summary = summary(band7)\nend \n\n# ╔═╡ 5af03195-5199-48b9-8792-f02da75dc320\nplot(band7_df,x=:steps,y=:Q,color=:Group,Geom.line)\n\n# ╔═╡ a94f1ce9-b874-4da2-af2b-ee8c6840a2d2\nmd\"\n\nThe higher learning rate again leads to noise, and in the end, the bandit has trouble differentiating Group D and E just as before. \n\nIn summary, lowering the learning rate appears to increase the chance of arriving at a suboptimal solution. Increasing the learning rate too much confuses the Bandit and the Q value curves become extremely noisy. \n\nStarting at a higher Q (with no set learning rate) encourages quicker exploration between the groups\n\n\"\n\n# ╔═╡ Cell order:\n# ╟─b65dd189-456b-40ac-88fc-d05b5e29b396\n# ╠═db4a6b48-99a7-11eb-097b-676aed417c48\n# ╟─38528382-a1ec-4117-88d4-fbcc019c7302\n# ╠═60e50c4e-8120-4306-9c6c-9282fff8eb47\n# ╟─65107f38-7916-43a4-b36f-1ef012c43b51\n# ╠═8ed00c06-7348-49dc-a9f2-041465beb969\n# ╠═472fee46-6e48-47a7-9235-ccb7c460f735\n# ╠═1243d0ab-f95c-482d-b81e-3b3eb60907eb\n# ╠═794d15a3-a4b4-4ffa-9afb-bb19d79e79e5\n# ╠═5e8e7408-aa48-4a2d-a427-40e8adf81d3c\n# ╟─32f83952-c660-4fde-8bd5-ae1a97e7bacd\n# ╠═65945e4f-17e9-40ba-870f-88da0c5d13d0\n# ╠═3566a579-84dc-4cb6-91ab-833d0d5e9782\n# ╟─a15c8f8f-f077-4758-a668-01c8b562ca95\n# ╠═77d6e956-219e-40e9-978d-f7e0906a8d6c\n# ╠═043f9d99-e8b5-4b33-82ac-3870a2238f85\n# ╟─50196d6d-8a52-4043-aa9f-e3f43a9ed2a1\n# ╠═9f3d4773-ac0a-4dd2-992d-b549f58f4021\n# ╠═3789a09f-73fb-4ca8-b267-bbe2d7b32848\n# ╟─7825e432-9f3b-4099-bf37-0b1b3ccf38c1\n# ╠═2342907c-75e0-4126-b2df-6ce5a5901bf1\n# ╠═7c511272-01f8-4270-bdf7-f4f66e78df07\n# ╟─c1deba65-a93f-4992-958e-38a987346691\n# ╠═8bbfae0c-6648-4f42-a40c-ada03d17bb3a\n# ╠═613e3215-4402-4ba2-8402-2ab5bf1f1247\n# ╟─e7772e4c-b798-4bdd-85c1-6ee291fce282\n# ╠═bf545060-f55c-4a91-99f8-c41543c25ebb\n# ╠═5af03195-5199-48b9-8792-f02da75dc320\n# ╟─a94f1ce9-b874-4da2-af2b-ee8c6840a2d2\n", "meta": {"hexsha": "ab9ad22ee22e71c440a324267357b99a9c2396fe", "size": 11803, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example_bandit.jl", "max_stars_repo_name": "rokapre/MultiArmBandit", "max_stars_repo_head_hexsha": "0926c0f9a2c0d1e4c1633763b7bce16f6d8e5344", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example_bandit.jl", "max_issues_repo_name": "rokapre/MultiArmBandit", "max_issues_repo_head_hexsha": "0926c0f9a2c0d1e4c1633763b7bce16f6d8e5344", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example_bandit.jl", "max_forks_repo_name": "rokapre/MultiArmBandit", "max_forks_repo_head_hexsha": "0926c0f9a2c0d1e4c1633763b7bce16f6d8e5344", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1254355401, "max_line_length": 680, "alphanum_fraction": 0.7508260612, "num_tokens": 4365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.8918110468756548, "lm_q1q2_score": 0.774829313841561}}
{"text": "function bernoulli(n)\n    A = Vector{Rational{BigInt}}(undef, n + 1)\n    for m = 0 : n\n        A[m + 1] = 1 // (m + 1)\n        for j = m : -1 : 1\n            A[j] = j * (A[j] - A[j + 1])\n        end\n    end\n    return A[1]\nend\n\nfunction display(n)\n    B = map(bernoulli, 0 : n)\n    pad = mapreduce(x -> ndigits(numerator(x)) + Int(x < 0), max, B)\n    argdigits = ndigits(n)\n    for i = 0 : n\n        if numerator(B[i + 1]) & 1 == 1\n            println(\n                \"B(\", lpad(i, argdigits), \") = \",\n                lpad(numerator(B[i + 1]), pad), \" / \", denominator(B[i + 1])\n            )\n        end\n    end\nend\n\ndisplay(60)\n", "meta": {"hexsha": "f5ad9015c4dfa167ef6abb3214ad0993cdb8ef72", "size": 631, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/bernoulli-numbers.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/bernoulli-numbers.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/bernoulli-numbers.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3703703704, "max_line_length": 76, "alphanum_fraction": 0.4310618067, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7748059067001942}}
{"text": "\"\"\"\n    black_body(T, K₀, σ)\n    black_body(T)\n\nThermal infrared, *i.e.* longwave radiation emitted from a black body at temperature T.\n\n- `T`: temperature of the object in Celsius degree\n- `K₀`: absolute zero (°C)\n- `σ` (``W\\\\ m^{-2}\\\\ K^{-4}``) [Stefan-Boltzmann constant](https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law)\n\n# Note\n\n`K₀` and `σ` are taken from [`Constants`](@ref) if not provided.\n\n\"\"\"\nfunction black_body(T, K₀, σ)\n  Tₖ = T - K₀\n  σ * (Tₖ^4.0)\nend\n\nfunction black_body(T)\n    constants = Constants()\n    black_body(T, constants.K₀, constants.σ)\nend\n\n\n\"\"\"\nThermal infrared, *i.e.* longwave radiation emitted from an object at temperature T.\n\n- `T`: temperature of the object in Celsius degree\n- `ε` object [emissivity](https://en.wikipedia.org/wiki/Emissivity) (not to confuse with ε the\nratio of molecular weights from [`Constants`](@ref)). A typical value for a leaf is 0.955.\n- `K₀`: absolute zero (°C)\n- `σ` (``W\\\\ m^{-2}\\\\ K^{-4}``) [Stefan-Boltzmann constant](https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law)\n\n# Note\n\n`K₀` and `σ` are taken from [`Constants`](@ref) if not provided.\n\n# Examples\n\n```julia\n# Thermal infrared radiation of water at 25 °C:\ngrey_body(25.0, 0.96)\n```\n\"\"\"\nfunction grey_body(T, ε, K₀, σ)\n  ε * black_body(T, K₀, σ)\nend\n\nfunction grey_body(T, ε)\n    constants = Constants()\n    grey_body(T, ε, constants.K₀, constants.σ)\nend\n\n\n\"\"\"\n    net_longwave_radiation(T₁,T₂,ε₁,ε₂,F₁,K₀,σ)\n    net_longwave_radiation(T₁,T₂,ε₁,ε₂,F₁)\n\nNet longwave radiation fluxes (*i.e.* thermal radiation, W m-2) between an object and another.\nThe object of interest is at temperature T₁ and has an emissivity ε₁, and the object with\nwich it exchanges energy is at temperature T₂ and has an emissivity ε₂.\n\nIf the result is positive, then the object of interest gain energy.\n\n# Arguments\n\n- `T₁` (Celsius degree): temperature of the target object (object 1)\n- `T₂` (Celsius degree): temperature of the object with which there is potential exchange (object 2)\n- `ε₁`: object 1 emissivity\n- `ε₂`: object 2 emissivity\n- `F₁`: view factor (0-1), *i.e.* visible fraction of object 2 from object 1 (see note)\n- `K₀`: absolute zero (°C)\n- `σ` (``W\\\\ m^{-2}\\\\ K^{-4}``) [Stefan-Boltzmann constant](https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law)\n\n# Note\n\n`F₁`, the view factor (also called shape factor) is a coefficient applied to the semi-hemisphere\nfield of view of object 1 that \"sees\" object 2. E.g. a leaf can be viewed as a plane. If one side\nof the leaf sees only object 2 in its field of view (e.g. the sky), then `F₁ = 1`.\nThen the net longwave radiation flux for this part of the leaf is multiplied by its actual\nsurface to get the exchange. Note that we apply reciprocity between the two objects for\nthe view factor (they have the same value), *i.e.*: A₁F₁₂ = A₂F₂₁.\n\nThen, if we take a leaf as object 1, and the sky as object 2, the visible fraction of\nsky viewed by the leaf would be:\n\n- `0.5` if the leaf is on top of the canopy, *i.e.* the upper side of the leaf sees the sky,\nthe side bellow sees other leaves and the soil.\n- between 0 and 0.5 if it is within the canopy and partly shaded by other objects.\n\nNote that `A₁` for a leaf is twice its common used leaf area, because `A₁` is the **total**\nleaf area of the object that exchange energy.\n\n```julia\n# Net thermal radiation fluxes between a leaf and the sky considering the leaf at the top of\n# the canopy:\nTₗ = 25.0 ; Tₐ = 20.0\nε₁ = 0.955 ; ε₂ = 1.0\nRₗₗ = net_longwave_radiation(Tₗ,Tₐ,ε₁,ε₂,1.0)\nRₗₗ\n\n# Rₗₗ is the net longwave radiation flux between the leaf and the atmosphere per surface area.\n# To get the actual net longwave radiation flux we need to multiply by the surface of the\n# leaf, e.g. for a leaf of 2cm²:\nleaf_area = 2e-4 # in m²\nRₗₗ * leaf_area\n\n# The leaf lose ~0.0055 W towards the atmosphere.\n```\n\n# References\n\nCengel, Y, et Transfer Mass Heat. 2003. A practical approach. New York, NY, USA: McGraw-Hill.\n\"\"\"\nfunction net_longwave_radiation(T₁,T₂,ε₁,ε₂,F₁,K₀,σ)\n    (black_body(T₂,K₀,σ) - black_body(T₁,K₀,σ)) / (1.0 / ε₁ + 1.0 / ε₂ - 1.0) * F₁\nend\n\nfunction net_longwave_radiation(T₁,T₂,ε₁,ε₂,F₁)\n    constants = Constants()\n    net_longwave_radiation(T₁,T₂,ε₁,ε₂,F₁,constants.K₀,constants.σ)\nend\n\n\"\"\"\n    atmosphere_emissivity(Tₐ,eₐ)\n\nEmissivity of the atmoshpere at a given temperature and vapor pressure.\n\n# Arguments\n\n- `Tₐ` (°C): air temperature\n- `eₐ` (kPa): air vapor pressure\n- `K₀` (°C): absolute zero\n\n# Examples\n\n```julia\nTₐ = 20.0\nVPD = 1.5\natmosphere_emissivity(Tₐ, vapor_pressure(Tₐ,VPD))\n```\n\n# References\n\nLeuning, R., F. M. Kelliher, DGG de Pury, et E.-D. SCHULZE. 1995. Leaf nitrogen,\nphotosynthesis, conductance and transpiration: scaling from leaves to canopies ». Plant,\nCell & Environment 18 (10): 1183‑1200.\n\"\"\"\nfunction atmosphere_emissivity(Tₐ,eₐ,K₀)\n    0.642 * (eₐ * 100 / (Tₐ - K₀))^(1 / 7)\nend\n\nfunction atmosphere_emissivity(Tₐ,eₐ)\n    atmosphere_emissivity(Tₐ,eₐ,Constants().K₀)\nend\n", "meta": {"hexsha": "595f6ad1d05504fdd387f00c0fdcb1ecc80e92f1", "size": 4957, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/energy/longwave_energy.jl", "max_stars_repo_name": "SimonTreillou/PlantBiophysics.jl", "max_stars_repo_head_hexsha": "70688f412467a379ed59fac34995f05f88ba8762", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-04T08:34:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T00:03:44.000Z", "max_issues_repo_path": "src/energy/longwave_energy.jl", "max_issues_repo_name": "SimonTreillou/PlantBiophysics.jl", "max_issues_repo_head_hexsha": "70688f412467a379ed59fac34995f05f88ba8762", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-03T21:03:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T10:24:58.000Z", "max_forks_repo_path": "src/energy/longwave_energy.jl", "max_forks_repo_name": "SimonTreillou/PlantBiophysics.jl", "max_forks_repo_head_hexsha": "70688f412467a379ed59fac34995f05f88ba8762", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-04T10:06:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T19:54:52.000Z", "avg_line_length": 31.3734177215, "max_line_length": 119, "alphanum_fraction": 0.7042566068, "num_tokens": 1627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.77480322458396}}
{"text": "# This code presents an example to illustrate how SmolyakApprox can be used\n\nusing SmolyakApprox\n\nfunction test_smolyak_approx()\n\n  d  = 5  # Set the number of dimensions\n  mu = 3  # Set the level of approximation\n\n  g2, m2 =  smolyak_grid(clenshaw_curtis_equidistant,d,mu)\n  grid, multi_ind = smolyak_grid(chebyshev_gauss_lobatto,d,mu)  # Construct the Smolyak grid and the multi index\n\n  # An arbitrary test function\n\n  function test(grid)\n\n    y_value = (grid[:,1].+1).^0.1.*exp.(grid[:,2]).*log.(grid[:,3].+2).^0.2.*(grid[:,4].+2).^0.8.*(grid[:,5].+7).^0.1\n\n    return y_value\n\n  end\n\n  y = test(grid)  # Evaluate the test function on the Smolyak grid\n  y_pl = test(g2)\n\n  point = [0.75, 0.45, 0.82, -0.15, -0.95]  # Choose a point to evaluate the approximated function\n\n  # One way of computing the weights and evaluating the approximated function\n\n  weights = smolyak_weights(y,grid,multi_ind)        # Compute the Smolyak weights\n  y_hat = smolyak_evaluate(weights,point,multi_ind)  # Evaluate the approximated function\n\n  #= A second way of computing the weights and evaluating the approximated function that\n  computes the interpolation matrix just once. =#\n\n  interp_mat = smolyak_inverse_interpolation_matrix(grid,multi_ind)  # Compute the interpolation matrix\n  w = smolyak_weights(y,interp_mat)             # Compute the Smolyak weights\n  y_hatt = smolyak_evaluate(w,point,multi_ind)  # Evaluate the approximated function\n\n  # Piecewise linear\n\n  w_pl = smolyak_pl_weights(y_pl,g2,m2)\n  y_pl_hat = smolyak_pl_evaluate(w_pl,point,g2,m2)\n\n  # Evaluate the exact function at point\n\n  y_actual = test(point')\n\n  # Now consider the ansiotropic case\n\n  mu = [3, 2, 2, 2, 3]\n  grid, multi_ind = smolyak_grid(chebyshev_gauss_lobatto,d,mu)  # Construct the Smolyak grid and the multi index\n  y = test(grid)\n  weights = smolyak_weights(y,grid,multi_ind)                   # Compute the Smolyak weights\n  y_hat_ansio = smolyak_evaluate(weights,point,multi_ind)       # Evaluate the approximated function\n  weights_th = smolyak_weights_threaded(y,grid,multi_ind)                   # Compute the Smolyak weights\n\n  g3, m3 =  smolyak_grid(clenshaw_curtis_equidistant,d,mu)\n  y_pl = test(g3)\n  w_pl_ansio = smolyak_pl_weights(y_pl,g3,m3)\n  y_pl_hat_ansio = smolyak_pl_evaluate(w_pl,point,g3,m3)\n  w_pl_ansio_th = smolyak_pl_weights_threaded(y_pl,g3,m3)\n\n  # Now test the full grid results\n\n  mu = 3\n  grid_full, multi_ind_full = smolyak_grid_full(chebyshev_gauss_lobatto,d,mu) # Construct the Smolyak grid and the multi index\n  y_full = test(grid_full)\n  weights_full = smolyak_weights_full(y_full,grid_full,multi_ind_full)        # Compute the Smolyak weights\n  y_hat_full = smolyak_evaluate_full(weights_full,point,multi_ind_full)       # Evaluate the approximated function\n\n  return y_hat, y_hatt, y_pl_hat, y_actual, y_hat_ansio, y_pl_hat_ansio, y_hat_full\n\nend\n\ntest_smolyak_approx()\n", "meta": {"hexsha": "31f86ed19faa95077563413cedb819b3a3171ea6", "size": 2887, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/example.jl", "max_stars_repo_name": "RJDennis/SmolyakApprox.jl", "max_stars_repo_head_hexsha": "42a669e34fb2417341b24936c1b72873c3c25857", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2018-04-23T15:47:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T10:38:53.000Z", "max_issues_repo_path": "test/example.jl", "max_issues_repo_name": "RJDennis/SmolyakApprox.jl", "max_issues_repo_head_hexsha": "42a669e34fb2417341b24936c1b72873c3c25857", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2017-08-08T00:07:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T11:53:45.000Z", "max_forks_repo_path": "test/example.jl", "max_forks_repo_name": "RJDennis/SmolyakApprox.jl", "max_forks_repo_head_hexsha": "42a669e34fb2417341b24936c1b72873c3c25857", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-12-22T21:24:48.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-07T21:47:10.000Z", "avg_line_length": 37.4935064935, "max_line_length": 126, "alphanum_fraction": 0.7353654312, "num_tokens": 880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7748032118834042}}
{"text": "using LinearAlgebra\nusing PyPlot \nusing Statistics\nusing Distributions\nusing ProgressMeter\n\nσ = 1\nτ = sqrt(10)\nμ = 5\nn = 5\n\n\n\nX = [9.37;10.18;9.16;11.60;10.33]\nμn = mean(X)*n/σ^2/(n/σ^2 + 1/τ^2) + μ*(1/τ^2)/(n/σ^2 + 1/τ^2)\nτn2 = 1/(n/σ^2+1/τ^2)\n\n# Hyperparameters\n# proposal step size\nδ = 3/100\nburnin = 2000\nN = 10000\nθ0 = 0.0\n\nfunction logf(θ)\n    -sum((X.-θ).^2)/2σ^2 - (θ-μ)^2/2τ^2\nend\n\nfunction proposal(x)\n    x + (rand()-0.5)*2 * δ\nend\n\n\nsim = zeros(N)\nsim[1] = θ0\n@showprogress for i = 1:N-1\n    x = sim[i]\n    x_star = proposal(x)\n    Δ =  logf(x_star) - logf(x)\n    if log(rand())<Δ\n        sim[i+1] = x_star \n    else \n        sim[i+1] = x\n    end\nend\nL = logf.(sim)\n\n\n# sim = sim[burnin+1:end]\nfigure(figsize=(12,4))\nsubplot(131)\nplot(sim)\nplot(1:length(sim), ones(length(sim))*μn, \"--\")\ntitle(\"\\$\\\\theta\\$ Value\")\nxlabel(\"Iteration\")\nylabel(\"\\$\\\\theta\\$\")\nsubplot(132)\nplot(L)\ntitle(\"Log likelihood\")\nxlabel(\"Iteration\")\nylabel(\"Log likelihood\")\nsubplot(133)\nhist(sim[burnin+1:end], density=true, bins=50)\ny = pdf.(Normal(μn, sqrt(τn2)), LinRange(8.5,11.5,100))\nplot(LinRange(8.5,11.5,100), y, label=\"Exact\")\ntitle(\"Distribution\")\nxlabel(\"\\$\\\\theta\\$\")\nylabel(\"Density\")\nlegend()\ntight_layout()\n\n", "meta": {"hexsha": "7ee3d15d39e15ec81e029aa473fc4f1dd704d72a", "size": 1209, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/assets/Codes/mcmc.jl", "max_stars_repo_name": "ziyiyin97/ADCME.jl", "max_stars_repo_head_hexsha": "1c9b2c1ae63059d79a5a6a7b86eee64796868755", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 202, "max_stars_repo_stars_event_min_datetime": "2019-06-12T18:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T16:56:46.000Z", "max_issues_repo_path": "docs/src/assets/Codes/mcmc.jl", "max_issues_repo_name": "banren456/ADCME.jl", "max_issues_repo_head_hexsha": "2ed7a0801b6ed90f2236c3cde7a1dca825cbe897", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2019-08-19T19:37:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T11:17:50.000Z", "max_forks_repo_path": "docs/src/assets/Codes/mcmc.jl", "max_forks_repo_name": "banren456/ADCME.jl", "max_forks_repo_head_hexsha": "2ed7a0801b6ed90f2236c3cde7a1dca825cbe897", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 56, "max_forks_repo_forks_event_min_datetime": "2019-07-30T05:50:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:41:07.000Z", "avg_line_length": 16.7916666667, "max_line_length": 62, "alphanum_fraction": 0.6071133168, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416414, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7748032104335426}}
{"text": "include(\"center.jl\")\ninclude(\"cross_validation.jl\")\ninclude(\"mse.jl\")\n\nfunction ridge( X, y, lambda::Number )\n\n    colmeans_X = center!( X )\n    mean_y = center!( y )\n\n    #A = X'*X + diagm( fill( lambda, size(X,2) ) )\n    #w = A\\(X'*y)\n\n    A = [ X ; fill( sqrt( lambda ), ( 1, size(X,2) ) ) ]\n    B = [ y ; fill( 0, ( 1, size(y,2) ) ) ]\n    w = A\\B\n\n    broadcast!( +, X, X, colmeans_X )\n    broadcast!( +, y, y, mean_y )\n\n    bias = mean_y - colmeans_X * w\n\n    return w, bias\n\nend\n\nfunction ridge( X, y, ls, gen = Kfold( size(X,1), 5 ) )\n    if Base.length( ls ) == 1\n        return ridge( X, y, ls[1] )\n    end\n    l_errs = Array( Float64, size(ls,1) )\n    for i in 1:size(ls,1)\n        l = ls[i]\n        train_f(is) = ridge( X[is,:], y[is,:], l )\n        error_f(model,is) = mse( predict( model, X[is,:] ), y[is,:] )\n        l_errs[i] = mean( cross_validate( train_f, error_f, gen ) )\n    end\n    l = ls[ indmin( l_errs ) ]\n    return ridge( X, y, l ), l, l_errs\nend\n\nfunction predict( w, bias, X )\n    return broadcast( +, X*w, bias )\nend\n\nfunction ridgeKernel( K, y, lambda )\n    m = size( K, 1 )\n\n    colmeans_K = center!( K )\n    mean_y = center!( y )\n    \n    for i = 1:m\n        K[i,i] += lambda\n    end\n    w = K \\ y\n    for i = 1:m\n        K[i,i] -= lambda\n    end\n    \n    broadcast!( +, y, y, mean_y )\n    broadcast!( +, K, K, colmeans_K )\n\n    bias = mean_y - colmeans_K * w\n\n    return w, bias\nend\n\nfunction ridgeKernel!( K, y, lambda )\n    m = size( K, 1 )\n\n    colmeans_K = center!( K )\n    mean_y = center!( y )\n   \n    for i = 1:m\n        K[i,i] += lambda\n    end\n    w = K \\ y\n    \n    broadcast!( +, y, y, mean_y )\n\n    bias = mean_y - colmeans_K * w\n\n    return w, bias\nend\n\nfunction predictKernel( w, bias, K )\n    return broadcast( +, K*w, bias )\nend\n\nfunction ridge( kernel::Function, X, y, lambda::Number )\n\n    m = size( X, 1 )\n    K = Array( eltype(y), m, m )\n    for i = 1:m\n        for j = i:m\n            K[i,j] = kernel( X[i,:], X[j,:] )\n            K[j,i] = K[i,j]\n        end\n    end\n\n    w,bias = ridgeKernel!( K, y, lambda )\n\n    return w, bias, kernel, X\n\nend\n\nfunction ridge( kernel::Function, X, y, ls, gen = Kfold( size(X,1), 5 ) )\n    \n    if Base.length( ls ) == 1\n        return ridge( X, y, ls[1], kernel )\n    end\n\n    m = size( X, 1 )\n    K = Array( eltype(y), m, m )\n    for i = 1:m\n        for j = i:m\n            K[i,j] = kernel( X[i,:], X[j,:] )\n            K[j,i] = K[i,j]\n        end\n    end\n\n    l_errs = Array( Float64, size(ls,1) )\n    for i in 1:size(ls,1)\n        l = ls[i]\n        train_f(is) = ridgeKernel( K[is,is], y[is,:], l ), is\n        \n        function error_f(v,is)\n            model, train_is = v\n            yh = predictKernel( model..., K[is,train_is] )\n            return mse( yh, y[is,:] )\n        end\n\n        l_errs[i] = mean( cross_validate( train_f, error_f, gen ) )\n    end\n    l = ls[ indmin( l_errs ) ]\n    w,bias = ridgeKernel!( K, y, l )\n    return (w, bias, kernel, X), l, l_errs\nend\n\nfunction predict( w, bias, kernel, X_model, X )\n    m = size( X, 1 )\n    n = size( X_model, 1 )\n    K = Array( eltype(w), m, n )\n    for i = 1:m\n        for j = 1:n\n            K[i,j] = kernel( X[i,:], X_model[j,:] )\n        end\n    end\n    return predictKernel( w, bias, K )\nend\n\nfunction predict( model, X )\n    predict( model..., X )\nend\n\n\n\n", "meta": {"hexsha": "e3e45681cc5e8e4a2381eedf05da7b499296e4ab", "size": 3314, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ridge.jl", "max_stars_repo_name": "tbepler/julia-regression", "max_stars_repo_head_hexsha": "eb950a1a400092921aa99194ca968c79b1dd5006", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ridge.jl", "max_issues_repo_name": "tbepler/julia-regression", "max_issues_repo_head_hexsha": "eb950a1a400092921aa99194ca968c79b1dd5006", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ridge.jl", "max_forks_repo_name": "tbepler/julia-regression", "max_forks_repo_head_hexsha": "eb950a1a400092921aa99194ca968c79b1dd5006", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1082802548, "max_line_length": 73, "alphanum_fraction": 0.4918527459, "num_tokens": 1154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416412, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7748032104335424}}
{"text": "export getNodalMassMatrix\n\nfunction getNodalMassMatrix(mesh::TetraMesh, sigma::Array{Float64,1})\n\n\tnc = mesh.nc\n  nn = mesh.nn\n\n\tM = zeros(4,4,nc)\n\n\tfor i=1:nc\n\t\tTi = mesh.Tetras[i,:]\n\t  \tXi = mesh.Points[Ti,:]\n\n\t\tM[:,:,i] = getLocalNodalMassMatrix(sigma[i],Xi)\n\n\tend\n\tnodalInd = mesh.Tetras\n\n\tii = zeros(Int64,16*nc)\n\tjj = zeros(Int64,16*nc)\n\t# mm = zeros(Float64,16*nc)\n\n\tcnt = 1\n\tfor i=1:nc\n\t\tfor i2=1:4\n\t\t\tfor i1=1:4\n\t\t\t\tii[cnt] = nodalInd[i,i1]\n\t\t\t\tjj[cnt] = nodalInd[i,i2]\n\t\t\t\t# mm[cnt] = M[i1,i2,i]\n\t\t\t\tcnt    += 1\n\t\t\tend\n\t\tend\n\tend\n  mm = vec(M)\n\n\treturn sparse(ii,jj,mm,nn,nn)\n  \nend\n\n# Nodal mass matrix is independent of geometry. Store mass matrix for unit coefficient and unit volume.\nconst M = (1/20) * [\n  2 1 1 1\n  1 2 1 1\n  1 1 2 1\n  1 1 1 2]\n\nfunction getLocalNodalMassMatrix(sigma::Float64,X::Array{Float64})\n\tv =  getCellVolume(X[1,:], X[2,:], X[3,:], X[4,:])\n\treturn (v * sigma) * M\nend\n", "meta": {"hexsha": "c0cf877682ccd3162fbcc142208b726439200901", "size": 908, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/getNodalMassMatrix.jl", "max_stars_repo_name": "JuliaInv/JTetra", "max_stars_repo_head_hexsha": "f443c7086bbc89a150d34abc158e6d16289212c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/getNodalMassMatrix.jl", "max_issues_repo_name": "JuliaInv/JTetra", "max_issues_repo_head_hexsha": "f443c7086bbc89a150d34abc158e6d16289212c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-12-15T05:51:34.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-15T05:51:34.000Z", "max_forks_repo_path": "src/getNodalMassMatrix.jl", "max_forks_repo_name": "JuliaInv/JTetra", "max_forks_repo_head_hexsha": "f443c7086bbc89a150d34abc158e6d16289212c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-26T18:44:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:13:51.000Z", "avg_line_length": 17.8039215686, "max_line_length": 103, "alphanum_fraction": 0.6167400881, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.774803205881324}}
{"text": "\"\"\"\nCompute the principal eigenvector and eigenvalue of a linear operator 𝕋, where 𝕋 is a Metzler matrix (i.e. off-diagonal components are nonnegative)\n\nDenote a = -minimum(Diagonal(V)), which implies 𝕋 + a * I has all positive entries. Applying Perron Frobenus, there a unique largest eigenvalue for aI + 𝕋, which is real, and the correspondind eigenctor is strictly positive.\nNote that, in particular, it is the eigenvalue with largest real part, and so this also correspoinds to the eigenvalue with largest real part of 𝕋, which happens to be real.\nDenote η(𝕋) the eigenvalue with largest real part of a matrix and ρ(𝕋) the eigenvalue with largest modulus. We have\n\n    η(𝕋) = ρ(𝕋 + a * I) - a\n\nMoreover, the associated eigenvector is real and strictly positive.\n\n\nNote that, when 𝕋 is generator, its rows sum to zero. This means that eigenvalue with largest real part is \n    η(𝕋) = 0\nIn other words, all eigenvalues of 𝕋 have real part <= 0. This means that 𝕋 is a singular M matrix.\n(another proof is to say that, for any s, sI - 𝕋 is a non-singular M-Matrix for any s> 0, since there exists x = e such that (sI - 𝕋) * x > 0). \n\n\"\"\"\nfunction principal_eigenvalue(𝕋; r0 = ones(size(𝕋, 1)))\n    η, r = 0.0, r0\n    a = - minimum(diag(𝕋))\n    try\n        vals, vecs = Arpack.eigs(𝕋 + a * I; v0 = collect(r0), nev = 1, which = :LM)\n        η = vals[1]\n        r = vecs[:, 1]\n    catch\n        vals, vecs = KrylovKit.eigsolve(𝕋 + a * I, collect(r0), 1, :LM; maxiter = size(𝕋, 1))\n        η = vals[1]\n        r = vecs[1]\n    end\n    abs(imag(η)) <= eps() || @warn \"Principal Eigenvalue has an imaginary part\"\n    maximum(abs.(imag.(r))) <= eps() || @warn \"Principal Eigenvector has an imaginary part\"\n    real(η) - a, abs.(r)\nend\n\n", "meta": {"hexsha": "45dcd27a69491dc8de03057bf95ed8eeeea98144", "size": 1730, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/principal_eigenvalue.jl", "max_stars_repo_name": "matthieugomez/ContinuousTimeMarkovOperators", "max_stars_repo_head_hexsha": "e416e0026d0bd1d37dbad2f97b7eceecf3a5ebcb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-06T19:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T17:08:06.000Z", "max_issues_repo_path": "src/principal_eigenvalue.jl", "max_issues_repo_name": "matthieugomez/ContinuousTimeMarkovOperators", "max_issues_repo_head_hexsha": "e416e0026d0bd1d37dbad2f97b7eceecf3a5ebcb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-24T12:09:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T16:24:34.000Z", "max_forks_repo_path": "src/principal_eigenvalue.jl", "max_forks_repo_name": "matthieugomez/ContinuousTimeMarkovOperators", "max_forks_repo_head_hexsha": "e416e0026d0bd1d37dbad2f97b7eceecf3a5ebcb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:47:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-15T08:27:25.000Z", "avg_line_length": 48.0555555556, "max_line_length": 224, "alphanum_fraction": 0.6682080925, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7748032044314623}}
{"text": "function logsumexp(logx::Array{Float64,1})\n    maxlog = maximum(logx)\n    maxlog + log(sum(exp.(logx - maxlog)))\nend\n\nfunction logsumexp(logx::Array{Float64,2}, dim::Int)\n    maxlog = maximum(logx, dim)\n    maxlog + log.(sum(exp.(logx .- maxlog), dim))\nend\n", "meta": {"hexsha": "ac28eb687814593d8e0685c6715f78d2b1ee31a5", "size": 257, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mathutils.jl", "max_stars_repo_name": "probcomp/SMC.jl", "max_stars_repo_head_hexsha": "3eca0f90cc88e98f298ef1b157e5b47765c76cdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-12-23T23:32:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-27T18:04:00.000Z", "max_issues_repo_path": "src/mathutils.jl", "max_issues_repo_name": "probcomp/SMC.jl", "max_issues_repo_head_hexsha": "3eca0f90cc88e98f298ef1b157e5b47765c76cdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mathutils.jl", "max_forks_repo_name": "probcomp/SMC.jl", "max_forks_repo_head_hexsha": "3eca0f90cc88e98f298ef1b157e5b47765c76cdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7, "max_line_length": 52, "alphanum_fraction": 0.6614785992, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9559813513911655, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7748027201965835}}
{"text": "function check(d, M, as)\n    # as is sorted\n    # check if all the cows can have a distance longer than d\n    N = length(as)\n\n    last = 1\n    for i in 1:(M-1)\n        crt = last + 1\n        while crt ≤ N && as[crt] - as[last] < d\n            crt += 1\n        end\n\n        if crt ≥ N\n            return false\n        else\n            last = crt\n        end\n    end\n\n    return true\nend\n\nfunction main()\n    N, M = parse.(Int, split(readline()))\n    as = [parse(Int, readline()) for _ in 1:N]\n    sort!(as)\n    \n    d̲, d̄ = 0, maximum(as)\n    while d̄ - d̲ > 1\n        d = (d̄ + d̲) ÷ 2\n        if check(d, M, as)\n            d̲ = d\n        else\n            d̄ = d\n        end\n    end\n\n    if check(d̄, M, as)\n        println(d̄)\n    else\n        println(d̲)\n    end\nend\n\nmain()", "meta": {"hexsha": "e4e3db3b848ebe2391e4483d931f5b4db388e375", "size": 778, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/chapter06/nicetak/poj2456.jl", "max_stars_repo_name": "tokuma09/algorithm_problems", "max_stars_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-07T15:46:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T15:46:58.000Z", "max_issues_repo_path": "problems/chapter06/nicetak/poj2456.jl", "max_issues_repo_name": "tokuma09/algorithm_problems", "max_issues_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-06-05T14:16:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-10T07:08:28.000Z", "max_forks_repo_path": "problems/chapter06/nicetak/poj2456.jl", "max_forks_repo_name": "tokuma09/algorithm_problems", "max_forks_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.2888888889, "max_line_length": 61, "alphanum_fraction": 0.4293059126, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467158, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7747967664268184}}
{"text": "# ============================================================\n# Thermodynamics\n# ============================================================\n\n\"\"\"\n$(SIGNATURES)\n\nCalculate heat capacity ratio (monatomic gas)\n\"\"\"\nfunction heat_capacity_ratio(K, D::T) where {T<:Integer}\n    γ = begin\n        if D == 1\n            (K + 3.0) / (K + 1.0)\n        elseif D == 2\n            (K + 4.0) / (K + 2.0)\n        elseif D == 3\n            (K + 5.0) / (K + 3.0)\n        end\n    end\n\n    return γ\nend\n\n\"\"\"\n$(SIGNATURES)\n\nCalculate heat capacity ratio (diatomic gas)\n\"\"\"\nfunction heat_capacity_ratio(K, Nr, D::T) where {T<:Integer}\n    γ = begin\n        if D == 1\n            (K + 3.0 + Nr) / (K + 1.0 + Nr)\n        elseif D == 2\n            (K + 4.0 + Nr) / (K + 2.0 + Nr)\n        elseif D == 3\n            (K + 5.0 + Nr) / (K + 3.0 + Nr)\n        end\n    end\n\n    return γ\nend\n\n\n\"\"\"\n$(SIGNATURES)\n\nCalculate speed of sound\n\"\"\"\nsound_speed(λ::Real, γ::Real) = (0.5 * γ / λ)^0.5\n\n\"\"\"\n$(SIGNATURES)\n\"\"\"\nsound_speed(prim::AV, γ) = sound_speed(prim[end], γ)\n\n\"\"\"\n$(TYPEDSIGNATURES)\n\nCalculate sound speed in mixture\n\"\"\"\nfunction sound_speed(prim::AM, γ)\n    c = similar(prim, axes(prim, 2))\n    for j in eachindex(c)\n        c[j] = sound_speed(prim[end, j], γ)\n    end\n\n    return maximum(c)\nend\n", "meta": {"hexsha": "8a07424d3095ee984086f3c2c5aecc0793e4d542", "size": 1276, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Theory/theory_thermo.jl", "max_stars_repo_name": "vavrines/KineticBase.jl", "max_stars_repo_head_hexsha": "d00cefe073346a3bab3b4d3577a95631e320dc9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Theory/theory_thermo.jl", "max_issues_repo_name": "vavrines/KineticBase.jl", "max_issues_repo_head_hexsha": "d00cefe073346a3bab3b4d3577a95631e320dc9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Theory/theory_thermo.jl", "max_forks_repo_name": "vavrines/KineticBase.jl", "max_forks_repo_head_hexsha": "d00cefe073346a3bab3b4d3577a95631e320dc9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.4927536232, "max_line_length": 62, "alphanum_fraction": 0.4561128527, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7747967616172798}}
{"text": "\"Brownian motion process.\"\nimmutable BrownianMotion{Y} <: AItoProcess\n  y0::Y\nend\n\nBrownianMotion() = BrownianMotion(0.0)\n\nconvert(::Type{ItoProcess}, bm::BrownianMotion) = \n    ItoProcess((t,dt,b,db,y)->db, bm.y0)\n\nfunction distribution(bm::BrownianMotion, t) \n  if t == 0 \n    Constant(bm.y0)\n  elseif ndims(bm.y0) == 0\n    Normal(bm.y0, sqrt(t))\n  else \n    MvNormal(bm.y0, eye(length(bm.y0)) * t)\n  end\nend\n\n# BrownianMotionWithDrift\n\nimmutable BrownianMotionWithDrift{Y,S} <: AItoProcess\n  mu::Y\n  sigma::S\n  y0::Y\nend\n\nBrownianMotionWithDrift(mu, sigma) = BrownianMotionWithDrift(mu, sigma, 0.0)\n\n\nconvert(::Type{ItoProcess}, bm::BrownianMotionWithDrift) = \n    ItoProcess((t,dt,b,db,y)-> (bm.mu * dt) .+ (bm.sigma * db), bm.y0)\n\nfunction distribution(bm::BrownianMotionWithDrift, t)\n    if t == 0 \n      Constant(bm.y0) \n    elseif ndims(bm.y0) == 0\n      Normal(bm.y0 + bm.mu * t, bm.sigma * sqrt(t))\n    else\n      MvNormal(bm.y0 + bm.mu * t, bm.sigma *bm.sigma' * t)\n    end\nend\n\nsolution(p::BrownianMotionWithDrift, t, b) =\n  p.y0 + t * p.mu + p.sigma * b\n\n# Geometric Brownian Motion\n\ntype GeometricBrownianMotion <: AItoProcess\n    mu::Float64\n    sigma::Float64\n    y0::Float64\nend\n\nconvert(::Type{ItoProcess}, bm::GeometricBrownianMotion) = \n    ItoProcess((t,dt,b,db,y)-> (bm.mu * dt) * y + bm.sigma * (y .* db), bm.y0)\n\ndistribution(bm::GeometricBrownianMotion, t) = \n    t == 0 ? Constant(bm.y0) :\n    LogNormal(log(bm.y0) + t * (bm.mu - bm.sigma^2 / 2), bm.sigma * sqrt(t))\n\nsolution(p::GeometricBrownianMotion, t, b) = \n    p.y0 * exp(t * (p.mu - p.sigma^2 / 2) + p.sigma * b)\n\n\n\"Ito integral of f(t, B)\"\nimmutable ItoIntegral{F} <: AItoProcess\n  f::F\nend\n\nconvert{F}(::Type{ItoProcess}, ii::ItoIntegral{F}) = \n    ItoProcess((t,dt,b,db,y)->ii.f(t, b).*db, 0.)\n\n\"Process corresponding to solutions of stochastic differential equation\n dy = f(t, y) dt + g(t,y) db.\"\nimmutable SDE{F,G} <: AItoProcess\n  f::F\n  g::G\n  y0::Float64\nend\n\nconvert{F,G}(::Type{ItoProcess}, sde::SDE{F,G}) = \n    ItoProcess((t,dt,b,db,y)->sde.f(t, y).*dt + sde.g(t, y).*db, sde.y0)\n", "meta": {"hexsha": "159e7138a8bb2a040540549f8290b9686354109b", "size": 2076, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basic_processes.jl", "max_stars_repo_name": "mikea/StochasticProcesses.jl", "max_stars_repo_head_hexsha": "6263efcb2cccb50fa3a38760142ab39561bc4110", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-01-05T14:49:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T21:19:39.000Z", "max_issues_repo_path": "src/basic_processes.jl", "max_issues_repo_name": "mikea/StochasticProcesses.jl", "max_issues_repo_head_hexsha": "6263efcb2cccb50fa3a38760142ab39561bc4110", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basic_processes.jl", "max_forks_repo_name": "mikea/StochasticProcesses.jl", "max_forks_repo_head_hexsha": "6263efcb2cccb50fa3a38760142ab39561bc4110", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-06-26T21:50:44.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-22T18:25:45.000Z", "avg_line_length": 24.4235294118, "max_line_length": 78, "alphanum_fraction": 0.6377649326, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.774768242693597}}
{"text": "mutable struct ListNode{T<:Number}\n    val :: T\n    next:: Union{ListNode, Nothing}    \n\n    ListNode(data::Array{T,1}) where T<:Number = begin\n        (head, rest) = Iterators.peel(data)\n        if isempty(rest)\n            new{T}(head::T, nothing)\n        else\n            new{T}(head, ListNode(collect(rest) :: Array{T,1}))\n        end\n    end\nend\n\nfunction node2list(x::Union{ListNode{T}, Nothing}) :: Array{T} where {T<:Number}\n    result = []\n    while x.next != nothing\n        push!(result, x.val)\n        x = x.next\n    end\n    push!(result, x.val)\n    result\nend\n\nfunction addTwoNumbers(a::ListNode{T}, b::ListNode{T}) :: ListNode{T} where T<:Number\n    this_a::Union{ListNode, Nothing}, this_b::Union{ListNode, Nothing} = a, b\n    flag = false\n    result::Array{T} = []\n    while true\n        (this_a == nothing && this_b == nothing) && begin\n            flag && push!(result,1)\n            return ListNode(result)\n        end\n        \n        this_a == nothing && begin\n            append!(result, begin\n                    cache = node2list(this_b)\n                    if flag cache[1] += 1 end\n                    cache\n                    end)\n            return ListNode(result)\n        end\n\n        this_b == nothing && begin\n            append!(result, begin\n                    cache = node2list(this_a)\n                    if flag cache[1] += 1 end\n                    cache\n                    end)\n            return ListNode(result)\n        end\n\n        push!(result, this_a.val + this_b.val + (flag ? 1 : 0))\n        if last(result) >= 10\n            result[lastindex(result)] -= 10\n            flag = true\n        else\n            flag = false\n        end\n        \n        this_a, this_b = this_a.next, this_b.next\n    end\n    ListNode(result)\nend\n", "meta": {"hexsha": "a6e851d0dd2513ced41b0c97d03018ae2f4833b0", "size": 1773, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Add-Two-Numbers/ATN.jl", "max_stars_repo_name": "ccqpein/Arithmetic-Exercises", "max_stars_repo_head_hexsha": "748d7ac1313892d47eb0a66a0b7705e6d33b43ad", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-07-11T03:07:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T06:46:10.000Z", "max_issues_repo_path": "Add-Two-Numbers/ATN.jl", "max_issues_repo_name": "ccqpein/Arithmetic-Exercises", "max_issues_repo_head_hexsha": "748d7ac1313892d47eb0a66a0b7705e6d33b43ad", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Add-Two-Numbers/ATN.jl", "max_forks_repo_name": "ccqpein/Arithmetic-Exercises", "max_forks_repo_head_hexsha": "748d7ac1313892d47eb0a66a0b7705e6d33b43ad", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-12-06T22:19:33.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T22:19:33.000Z", "avg_line_length": 27.2769230769, "max_line_length": 85, "alphanum_fraction": 0.4991539763, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676518712608, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7747682294551859}}
{"text": "using LinearAlgebra\nfunction bernsteinBasis(u, deg)\n    \"\"\"\n    Function returns the values of  Bernstein basis of degree deg at points u\n    Algorithm A1.3 in Piegl & Tiller\n    xi is a 1D array\n    \"\"\"\n    lenU = length(u)\n    B = zeros(lenU, deg+1)\n    B[:, 1] = ones(lenU)\n    u1 = ones(lenU) - u\n    u2 = ones(lenU) + u\n\n    for j in 1:deg\n        saved = zeros(lenU)\n        for k in 1:j\n            temp = B[:,k]\n            B[:,k] = saved + u1.*temp\n            saved  = u2.*temp\n        end\n        B[:,j+1] = saved\n    end\n    B = B./(2^deg)\n\n    #calculate the 1st derivative of Bernstein polynomials\n    dB = zeros(lenU, deg)\n    dB[:,1] = ones(lenU)\n    for j in 1:deg-1\n        saved = zeros(lenU)\n        for k in 0:j-1\n            temp = dB[:,k+1]\n            dB[:,k+1] = saved + u1.*temp\n            saved = u2.*temp\n        end\n        dB[:,j+1] = saved\n    end\n    dB = dB./(2^deg)\n    dB = hcat(zeros(lenU,1), dB, zeros(lenU, 1))\n    dB = (dB[:,1:end-1]-dB[:,2:end])*deg\n\n    #calculate the 2nd derivative of Bernstein polynomials\n    if deg>1\n        ddB = zeros(lenU, deg-1)\n        ddB[:,1] = ones(lenU)\n        for j=1:deg-2\n            saved = zeros(lenU)\n            for k in 0:j-1\n                temp = ddB[:,k+1]\n                ddB[:,k+1] = saved + u1.*temp\n                saved = u2.*temp\n            end\n            ddB[:,j+1] = saved\n        end\n        ddB = ddB./(2^deg)\n        ddB = hcat(zeros(lenU,2), ddB, zeros(lenU,2))\n        ddB = (ddB[:,1:end-2]-2*ddB[:,2:end-1]+ddB[:,3:end])*deg*(deg-1)\n    else\n        ddB = zeros(lenU,deg+1)\n    end\n    return B, dB, ddB\n\n\nend\n\nfunction bezierExtraction(knot, deg)\n    \"\"\"\n    Bezier extraction\n    Based on Algroithm 1, from Borden - Isogeometric finite element data\n    structures based on Bezier extraction\n    \"\"\"\n    m = length(knot)-deg-1;\n    a = deg + 1;\n    b = a + 1;\n    nb = 1;\n    nb_final = length(unique(knot))-1\n    C = zeros(deg+1,deg+1,nb_final)\n    C[:,:,1] = Matrix{Float64}(I, deg+1, deg+1)\n\n    while b<=m\n        C[:,:,nb+1] = Matrix{Float64}(I, deg+1, deg+1)\n        i = b\n        while (b<=m) && (knot[b+1] == knot[b])\n            b = b + 1\n        end\n        multiplicity = b - i + 1\n        alphas = zeros(deg-multiplicity)\n        if multiplicity < deg\n            numerator = knot[b] - knot[a]\n            for j in deg:-1:multiplicity+1\n                alphas[j-multiplicity] = numerator/(knot[a+j]-knot[a])\n            end\n            r = deg - multiplicity\n            for j in 1:r\n                save = r - j + 1\n                s = multiplicity + j\n                for k in deg+1:-1:s+1\n                    alpha = alphas[k-s]\n                    C[:,k,nb] = alpha*C[:,k,nb]+(1-alpha)*C[:,k-1,nb]\n                end\n                if b<=m\n                    C[save:save+j,save,nb+1] = C[deg-j+1:deg+1,deg+1,nb]\n                end\n            end\n            nb = nb + 1\n            if b <= m\n                a = b\n                b = b + 1\n            end\n        elseif multiplicity==deg\n            if b <= m\n                nb = nb + 1\n                a = b\n                b = b + 1\n            end\n        end\n    end\n    @assert nb_final == nb\n    return C, nb\nend\n\n\"\"\"\nCreate the extended knot vector (Subsection 4.3.2 in Scott - Isogeometric\ndata structures based on the Bézier extraction of T-Splines)\n\"\"\"\nfunction formExtendedKnot(localKnot, p)\n    # Repeat the first knot (if needed) so that it appears p+1 times\n    firstKnot = localKnot[1]\n    indexFirst = findall(localKnot.==firstKnot)\n    numRep = length(indexFirst)\n    numNewRepFirst = p+1-numRep\n\n    #repeat the last knot (if needed) so that it appears p+1 times\n    lastKnot = localKnot[end]\n    indexLast = findall(localKnot.==lastKnot)\n    numRep = length(indexLast)\n    numNewRepLast = p+1-numRep\n\n    #form the extended knot vector\n    extendedKnot = vcat(firstKnot*ones(numNewRepFirst), localKnot, lastKnot*ones(numNewRepLast))\n    indexFun = numNewRepFirst + 1\n    return extendedKnot, indexFun\nend\n\n\"\"\"\nCompute the Bézier extraction operator corresponding to the basis functions of\ndegree p with local knot vector localKnot\n\"\"\"\nfunction bezierExtractionLocal(localKnot, p)\n    extendedKnot, indexFun = formExtendedKnot(localKnot, p)\n    #perform Bézier extraction and return the basis with index numNewRepFirst+1\n    C_temp, nb = bezierExtraction(extendedKnot, p)\n    IEN, _ = makeIEN(extendedKnot, nb, p)\n    C = zeros(p+1, nb)\n    for indexSpan = 1:nb\n        C_index = findfirst(IEN[indexSpan,:].==indexFun)\n        C[:, indexSpan] = C_temp[C_index,:,indexSpan]\n    end\n    return C\nend\n", "meta": {"hexsha": "3734f6e7e76226c7eff9bcbcc0eedbd62c7585d3", "size": 4591, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bernstein.jl", "max_stars_repo_name": "canitesc/IGAPack.jl", "max_stars_repo_head_hexsha": "bb2b5e8d01afd9ca8a59055380ca00d2c8f951b1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-07-30T13:49:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T08:18:26.000Z", "max_issues_repo_path": "src/bernstein.jl", "max_issues_repo_name": "canitesc/IGAPack.jl", "max_issues_repo_head_hexsha": "bb2b5e8d01afd9ca8a59055380ca00d2c8f951b1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bernstein.jl", "max_forks_repo_name": "canitesc/IGAPack.jl", "max_forks_repo_head_hexsha": "bb2b5e8d01afd9ca8a59055380ca00d2c8f951b1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-30T13:49:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-09T11:32:36.000Z", "avg_line_length": 28.69375, "max_line_length": 96, "alphanum_fraction": 0.5306033544, "num_tokens": 1450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.8539127529517044, "lm_q1q2_score": 0.7747654831492062}}
{"text": "module problem107\n\ndescription = \"\"\"\nMinimal network\nProblem 107\n\nThe following undirected network consists of seven vertices and twelve edges with a total weight of 243.\n\nThe same network can be represented by the matrix below.\n    \tA\tB\tC\tD\tE\tF\tG\nA\t-\t16\t12\t21\t-\t-\t-\nB\t16\t-\t-\t17\t20\t-\t-\nC\t12\t-\t-\t28\t-\t31\t-\nD\t21\t17\t28\t-\t18\t19\t23\nE\t-\t20\t-\t18\t-\t-\t11\nF\t-\t-\t31\t19\t-\t-\t27\nG\t-\t-\t-\t23\t11\t27\t-\n\nHowever, it is possible to optimise the network by removing some edges and still ensure that all points on the network remain connected. The network which achieves the maximum saving is shown below. It has a weight of 93, representing a saving of 243 − 93 = 150 from the original network.\n\nUsing network.txt (right click and 'Save Link/Target As...'), a 6K text file containing a network with forty vertices, and given in matrix form, find the maximum saving which can be achieved by removing redundant edges whilst ensuring that the network remains connected.\n\"\"\"\n\nimmutable Edge\n  from :: Int\n  to :: Int\n  cost :: Int\nend\n\nimmutable Tree\n  edges :: Vector{Edge}\nend\n\nimmutable Forest\n  trees :: Vector{Tree}\nend\n\n# Find the index of the tree containing node in the forest, or -1 if not found\nfunction tree_index(node :: Int, f :: Forest)\n  for i = 1:length(f.trees)\n    for j = 1:length(f.trees[i].edges)\n      if (f.trees[i].edges[j].from == node || f.trees[i].edges[j].to == node)\n        return i\n      end\n    end\n  end\n  return -1\nend\n\n# Tests if adding Edge e to Forest would connect two previously disconnected trees\nfunction makes_new_connection(e :: Edge, f :: Forest)\n  t1 = tree_index(e.from, f)\n  t2 = tree_index(e.to, f)\n  return t1 < 0 || t2 < 0 || t1 != t2\nend\n\n# Creates Add Edge to Forest, joining any trees that become linked\nfunction add_edge(e :: Edge, f :: Forest)\n  t1 = tree_index(e.from, f)\n  t2 = tree_index(e.to, f)\n\n  # Simple case, neither from/to existed previously, add a new tree\n  if t1 < 0 && t2 < 0\n    return Forest([Tree([e]); f.trees])\n  end\n\n  # One of the trees exists - make a copy and update\n  newtrees = copy(f.trees)\n  if t1 > 0 && t2 < 0\n    newtrees[t1] = Tree([e; f.trees[t1].edges])\n  elseif t1 < 0 && t2 > 0\n    newtrees[t2] = Tree([e; f.trees[t2].edges])\n  else\n    newtrees[t1] = Tree([e; f.trees[t1].edges; f.trees[t2].edges])\n    splice!(newtrees, t2, Tree[])\n  end\n  return Forest(newtrees)\nend\n\n# Convert from matrix representation to Edge vector\nfunction matrix_to_edges(connections :: Matrix{Int})\n  edges = Edge[]\n  for i = 1:size(connections, 1)\n    for j = i+1:size(connections, 2)\n      if connections[i, j] > 0\n        push!(edges, Edge(i, j, connections[i,j]))\n      end\n    end\n  end\n  return edges\nend\n\n\n# Calculate the minimum spanning tree by adding the minimum cost edge to a forest if it links up previously disconnected trees\nfunction minimum_spanning_tree(connections :: Matrix{Int})\n  edges = matrix_to_edges(connections)\n  sort!(edges, by = x -> x.cost)\n  f = Forest(Tree[])\n  for e in edges\n    if makes_new_connection(e, f)\n      f = add_edge(e, f)\n    end\n  end\n  return f.trees[1]\nend\n\nfunction read_network()\n  m = readcsv(\"network.txt\")\n  m[m .== \"-\"] = -1\n  connections = int(m)\n  return connections\nend\n\nfunction solve107()\n  network = read_network()\n  t = minimum_spanning_tree(network)\n  initial_cost = sum([e.cost for e in matrix_to_edges(network)])\n  final_cost = sum([e.cost for e in t.edges])\n  println(\"$initial_cost - $final_cost = $(initial_cost - final_cost)\")\nend\n\nusing Base.Test\n\ntestcase = [\n-1\t16\t12\t21\t-1\t-1\t-1\n16\t-1\t-1\t17\t20\t-1\t-1\n12\t-1\t-1\t28\t-1\t31\t-1\n21\t17\t28\t-1\t18\t19\t23\n-1\t20\t-1\t18\t-1\t-1\t11\n-1\t-1\t31\t19\t-1\t-1\t27\n-1\t-1\t-1\t23\t11\t27\t-1]\n\n@test sum([e.cost for e in minimum_spanning_tree(testcase).edges]) == 93\n\nend", "meta": {"hexsha": "82122f70fb743bc6cf9b0e6c5eb1882933f15c01", "size": 3700, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem107.jl", "max_stars_repo_name": "mbuhot/mbuhot-euler-solutions", "max_stars_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-12-18T13:25:41.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-18T13:25:41.000Z", "max_issues_repo_path": "julia/problem107.jl", "max_issues_repo_name": "mbuhot/mbuhot-euler-solutions", "max_issues_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/problem107.jl", "max_forks_repo_name": "mbuhot/mbuhot-euler-solutions", "max_forks_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4074074074, "max_line_length": 288, "alphanum_fraction": 0.6705405405, "num_tokens": 1181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7747654814626427}}
{"text": "# # Kernel Ridge Regression\n#\n# Building on linear regression, we can fit non-linear data sets by introducing a feature space. In a higher-dimensional feature space, we can overfit the data; ridge regression introduces regularization to avoid this. In this notebook we show how we can use KernelFunctions.jl for *kernel* ridge regression.\n\n## Loading and setup of required packages\nusing KernelFunctions\nusing LinearAlgebra\nusing Distributions\n\n## Plotting\nusing Plots;\ndefault(; lw=2.0, legendfontsize=11.0, ylims=(-150, 500));\n\nusing Random: seed!\nseed!(42);\n\n##\n# ## Toy data\n# Here we use a one-dimensional toy problem. We generate data using the fourth-order polynomial $f(x) = (x+4)(x+1)(x-1)(x-3)$:\n\nf_truth(x) = (x + 4) * (x + 1) * (x - 1) * (x - 3)\n\nx_train = -5:0.5:5\nx_test = -7:0.1:7\n\nnoise = rand(Uniform(-20, 20), length(x_train))\ny_train = f_truth.(x_train) + noise\ny_test = f_truth.(x_test)\n\nplot(x_test, y_test; label=raw\"$f(x)$\")\nscatter!(x_train, y_train; seriescolor=1, label=\"observations\")\n\n##\n# ## Linear regression\n# For training inputs $\\mathrm{X}=(\\mathbf{x}_n)_{n=1}^N$ and observations $\\mathbf{y}=(y_n)_{n=1}^N$, the linear regression weights $\\mathbf{w}$ using the least-squares estimator are given by\n# ```math\n# \\mathbf{w} = (\\mathrm{X}^\\top \\mathrm{X})^{-1} \\mathrm{X}^\\top \\mathbf{y}\n# ```\n# We predict at test inputs $\\mathbf{x}_*$ using\n# ```math\n# \\hat{y}_* = \\mathbf{x}_*^\\top \\mathbf{w}\n# ```\n# This is implemented by `linear_regression`:\n\nfunction linear_regression(X, y, Xstar)\n    weights = (X' * X) \\ (X' * y)\n    return Xstar * weights\nend;\n\n# A linear regression fit to the above data set:\n\ny_pred = linear_regression(x_train, y_train, x_test)\nscatter(x_train, y_train; label=\"observations\")\nplot!(x_test, y_pred; label=\"linear fit\")\n\n##\n# ## Featurization\n# We can improve the fit by including additional features, i.e. generalizing to $\\tilde{\\mathrm{X}} = (\\phi(x_n))_{n=1}^N$, where $\\phi(x)$ constructs a feature vector for each input $x$. Here we include powers of the input, $\\phi(x) = (1, x, x^2, \\dots, x^d)$:\n\nfunction featurize_poly(x; degree=1)\n    return repeat(x, 1, degree + 1) .^ (0:degree)'\nend\n\nfunction featurized_fit_and_plot(degree)\n    X = featurize_poly(x_train; degree=degree)\n    Xstar = featurize_poly(x_test; degree=degree)\n    y_pred = linear_regression(X, y_train, Xstar)\n    scatter(x_train, y_train; legend=false, title=\"fit of order $degree\")\n    return plot!(x_test, y_pred)\nend\n\nplot((featurized_fit_and_plot(degree) for degree in 1:4)...)\n\n##\n# Note that the fit becomes perfect when we include exactly as many orders in the features as we have in the underlying polynomial (4).\n#\n# However, when increasing the number of features, we can quickly overfit to noise in the data set:\n\nfeaturized_fit_and_plot(20)\n\n##\n# ## Ridge regression\n# To counteract this unwanted behaviour, we can introduce regularization. This leads to *ridge regression* with $L_2$ regularization of the weights ([Tikhonov regularization](https://en.wikipedia.org/wiki/Tikhonov_regularization)).\n# Instead of the weights in linear regression,\n# ```math\n# \\mathbf{w} = (\\mathrm{X}^\\top \\mathrm{X})^{-1} \\mathrm{X}^\\top \\mathbf{y}\n# ```\n# we introduce the ridge parameter $\\lambda$:\n# ```math\n# \\mathbf{w} = (\\mathrm{X}^\\top \\mathrm{X} + \\lambda \\mathbb{1})^{-1} \\mathrm{X}^\\top \\mathbf{y}\n# ```\n# As before, we predict at test inputs $\\mathbf{x}_*$ using\n# ```math\n# \\hat{y}_* = \\mathbf{x}_*^\\top \\mathbf{w}\n# ```\n# This is implemented by `ridge_regression`:\n\nfunction ridge_regression(X, y, Xstar, lambda)\n    weights = (X' * X + lambda * I) \\ (X' * y)\n    return Xstar * weights\nend\n\nfunction regularized_fit_and_plot(degree, lambda)\n    X = featurize_poly(x_train; degree=degree)\n    Xstar = featurize_poly(x_test; degree=degree)\n    y_pred = ridge_regression(X, y_train, Xstar, lambda)\n    scatter(x_train, y_train; legend=false, title=\"\\$\\\\lambda=$lambda\\$\")\n    return plot!(x_test, y_pred)\nend\n\nplot((regularized_fit_and_plot(20, lambda) for lambda in (1e-3, 1e-2, 1e-1, 1))...)\n\n##\n# ## Kernel ridge regression\n# Instead of constructing the feature matrix explicitly, we can use *kernels* to replace inner products of feature vectors with a kernel evaluation: $\\langle \\phi(x), \\phi(x') \\rangle = k(x, x')$ or $\\tilde{\\mathrm{X}} \\tilde{\\mathrm{X}}^\\top = \\mathrm{K}$, where $\\mathrm{K}_{ij} = k(x_i, x_j)$.\n#\n# To apply this \"kernel trick\" to ridge regression, we can rewrite the ridge estimate for the weights\n# ```math\n# \\mathbf{w} = (\\mathrm{X}^\\top \\mathrm{X} + \\lambda \\mathbb{1})^{-1} \\mathrm{X}^\\top \\mathbf{y}\n# ```\n# using the [matrix inversion lemma](https://tlienart.github.io/pub/csml/mtheory/matinvlem.html#basic_lemmas)\n# as\n# ```math\n# \\mathbf{w} = \\mathrm{X}^\\top (\\mathrm{X} \\mathrm{X}^\\top + \\lambda \\mathbb{1})^{-1} \\mathbf{y}\n# ```\n# where we can now replace the inner product with the kernel matrix,\n# ```math\n# \\mathbf{w} = \\mathrm{X}^\\top (\\mathrm{K} + \\lambda \\mathbb{1})^{-1} \\mathbf{y}\n# ```\n# And the prediction yields another inner product,\n# ```math\n# \\hat{y}_* = \\mathbf{x}_*^\\top \\mathbf{w} = \\langle \\mathbf{x}_*, \\mathbf{w} \\rangle = \\mathbf{k}_* (\\mathrm{K} + \\lambda \\mathbb{1})^{-1} \\mathbf{y}\n# ```\n# where $(\\mathbf{k}_*)_n = k(x_*, x_n)$.\n#\n# This is implemented by `kernel_ridge_regression`:\n\nfunction kernel_ridge_regression(k, X, y, Xstar, lambda)\n    K = kernelmatrix(k, X)\n    kstar = kernelmatrix(k, Xstar, X)\n    return kstar * ((K + lambda * I) \\ y)\nend;\n\n# Now, instead of explicitly constructing features, we can simply pass in a `PolynomialKernel` object:\n\nfunction kernelized_fit_and_plot(kernel, lambda=1e-4)\n    y_pred = kernel_ridge_regression(kernel, x_train, y_train, x_test, lambda)\n    if kernel isa PolynomialKernel\n        title = string(\"order \", kernel.degree)\n    else\n        title = string(nameof(typeof(kernel)))\n    end\n    scatter(x_train, y_train; label=nothing)\n    return plot!(x_test, y_pred; label=nothing, title=title)\nend\n\nplot((kernelized_fit_and_plot(PolynomialKernel(; degree=degree, c=1)) for degree in 1:4)...)\n\n##\n# However, we can now also use kernels that would have an infinite-dimensional feature expansion, such as the squared exponential kernel:\n\nkernelized_fit_and_plot(SqExponentialKernel())\n", "meta": {"hexsha": "62afc59448bb04eec070c1098c70156957b6c166", "size": 6241, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/kernel-ridge-regression/script.jl", "max_stars_repo_name": "bmharsha/KernelFunctions.jl", "max_stars_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 200, "max_stars_repo_stars_event_min_datetime": "2020-04-07T11:28:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:14:13.000Z", "max_issues_repo_path": "examples/kernel-ridge-regression/script.jl", "max_issues_repo_name": "bmharsha/KernelFunctions.jl", "max_issues_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 324, "max_issues_repo_issues_event_min_datetime": "2020-03-24T16:26:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T07:34:54.000Z", "max_forks_repo_path": "examples/kernel-ridge-regression/script.jl", "max_forks_repo_name": "bmharsha/KernelFunctions.jl", "max_forks_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2020-03-25T10:25:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T21:19:06.000Z", "avg_line_length": 38.2883435583, "max_line_length": 308, "alphanum_fraction": 0.6894728409, "num_tokens": 1895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7747654767287765}}
{"text": "\n#=\ndef linear(a, b, x):\n    return b + a*x\n=#\n\nlinear(a, b, x) = b + a * x\n\n#=\n# a linear demand function is generated for every \n# pair of coefficients in vectors a_vec and b_vec \ndef demand_hypotheses(a_vec, b_vec):\n    for a, b in itertools.product(a_vec, b_vec):\n        yield {\n            'd': functools.partial(linear, a, b),\n            'p_opt': -b/(2*a)\n        }\n=#\n\nfunction demand_hypothesis(f, a, b)\n\tf1(x) = f(a, b, x)\n\treturn DataFrame(\n\t\t:a => a,\n\t\t:b => b,\n\t\t:d => f1,\n        :d_opt => f1(-b / (2a)),\n\t\t:p_opt => -b / (2a)\n\t)\nend\n\nfunction generate_demand_hypothesis(a_range, b_range)\n    h_vec = DataFrame()\n    for a in a_range\n    \tfor b in b_range\n    \t\tdf1 = demand_hypothesis(linear, a, b)\n    \t\tpush!(h_vec, df1[1, :]) \n    \tend\n    end\n    h_vec\nend\n\n", "meta": {"hexsha": "d96a3dab2cff4392e8978eb8fba201ca00fc0cb9", "size": 778, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "approaches/dynamic_pricing/dynamic_pricing/price_demand_models.jl", "max_stars_repo_name": "StatisticalRethinkingJulia/DynamicPricingExamples.jl", "max_stars_repo_head_hexsha": "a6fae1736bf30f7aeed22452630c3ca3f018c50a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-02-19T06:59:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T07:57:57.000Z", "max_issues_repo_path": "approaches/dynamic_pricing/dynamic_pricing/price_demand_models.jl", "max_issues_repo_name": "StatisticalRethinkingJulia/DynamicPricingExamples.jl", "max_issues_repo_head_hexsha": "a6fae1736bf30f7aeed22452630c3ca3f018c50a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "approaches/dynamic_pricing/dynamic_pricing/price_demand_models.jl", "max_forks_repo_name": "StatisticalRethinkingJulia/DynamicPricingExamples.jl", "max_forks_repo_head_hexsha": "a6fae1736bf30f7aeed22452630c3ca3f018c50a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5238095238, "max_line_length": 53, "alphanum_fraction": 0.559125964, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.8539127585282745, "lm_q1q2_score": 0.7747654753680369}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.0\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 4ea0ccfa-9622-11eb-1cf0-e9ae2f927dd2\nhtml\"\"\"\n<div style=\"\nposition: absolute;\nwidth: calc(100% - 30px);\nborder: 50vw solid #282936;\nborder-top: 500px solid #282936;\nborder-bottom: none;\nbox-sizing: content-box;\nleft: calc(-50vw + 15px);\ntop: -500px;\nheight: 500px;\npointer-events: none;\n\"></div>\n\n<div style=\"\nheight: 500px;\nwidth: 100%;\nbackground: #282936;\ncolor: #fff;\npadding-top: 68px;\n\">\n<span style=\"\nfont-family: Vollkorn, serif;\nfont-weight: 700;\nfont-feature-settings: 'lnum', 'pnum';\n\"> <p style=\"\nfont-size: 1.5rem;\nopacity: .8;\n\"><em>Section 2.8</em></p>\n<p style=\"text-align: center; font-size: 2rem;\">\n<em> Linear Model, Data Science, & Simulations </em>\n</p>\n\n<p style=\"\nfont-size: 1.5rem;\ntext-align: center;\nopacity: .8;\n\"><em>Lecture Video</em></p>\n<div style=\"display: flex; justify-content: center;\">\n<div  notthestyle=\"position: relative; right: 0; top: 0; z-index: 300;\">\n<iframe src=\"https://www.youtube.com/embed/O6NTKsR8TjQ\" width=400 height=250  frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe></div>\n</div>\n</div>\n\n<style>\nbody {\noverflow-x: hidden;\n}\n</style>\"\"\"\n\n# ╔═╡ d155ea12-9628-11eb-347f-7754a33fd403\nbegin\n    import Pkg\n    Pkg.activate(mktempdir())\n    Pkg.add([\n        Pkg.PackageSpec(name=\"Plots\", version=\"1\"),\n        Pkg.PackageSpec(name=\"PlutoUI\", version=\"0.7\"),\n        Pkg.PackageSpec(name=\"DataFrames\", version=\"0.22\"),\n        Pkg.PackageSpec(name=\"CSV\", version=\"0.8\"),\n        Pkg.PackageSpec(name=\"GLM\", version=\"1\"),\n        Pkg.PackageSpec(name=\"Distributions\", version=\"0.24\"),\n    ])\n    using Plots, PlutoUI, DataFrames, CSV, GLM, Statistics, LinearAlgebra, Distributions\nend\n\n# ╔═╡ 01506de2-918a-11eb-2a4d-c554a6e54631\nTableOfContents(title=\"📚 Table of Contents\", aside=true)\n\n# ╔═╡ 877deb2c-702b-457b-a54b-f27c277928d4\nmd\"\"\"\n# Julia concepts for data science\n- Data Frames (`DataFrames.jl`)\n- `CSVread`, `CSVwrite` (`CSV.jl`)\n- `lm` (linear model) (`GLM.jl`)\n- `@formula` (formula macro to specify variables to analyze) (`GLM.jl`)\n\n- Underscore as digits separator (e.g. `1_000` for 1000)\n\n- The value of fast simulations.\n\"\"\"\n\n# ╔═╡ 36ce167f-382c-4b9a-be34-83250b10c4e5\nmd\"\"\"\nIn this lecture we will simulate a real world statistical application\nfor the purpose of understanding what statistics is about.  It is very\n\thelpful in simulations to be able to run many examples fast.\n\"\"\"\n\n# ╔═╡ 83912943-a847-420a-bfdb-450027b631e8\nmd\"\"\"\n# Fahrenheit and Celsius Data Set\n\"\"\"\n\n# ╔═╡ 280d112f-d34a-4cc4-9e3a-4ebbfcd5eb51\nn = 10\n\n\n# ╔═╡ b5031c96-db57-4baf-b271-6bb12e29de9b\nx = sort((rand( -10:100, n)))\n\n# ╔═╡ c2f77e8f-a8c0-4144-a8b4-b25dd98ed234\ny = 5/9 .* x  .- 17.7777777 #  same as y =  5/9 .* (x .- 32)\n\n# ╔═╡ ad161b98-f4a1-42ac-ad4f-8b71fabcfde9\nbegin\t\n\tplot(x,y, m=:c, mc=:red,legend=false)\n\txlabel!(\"°F\")\n\tannotate!(-4,16,text(\"°C\",11))\n\t# plot!( x, (x.-30)./2) Dave's cool approximation\nend\n\n# ╔═╡ 8e422886-74ef-4c0f-be1e-fda238c8db44\n[x y]\n\n# ╔═╡ ca21122a-2522-482a-b7ef-bd73e96cb5a9\nmd\"\"\"\n## Julia: Data Frames\nI like to think of a Data Frame as a matrix with labels.\n\"\"\"\n\n# ╔═╡ 41e05b1e-8b5e-45e3-91bb-01355ade9f3d\nmd\"\"\"\n### Data Frame by Columns with labels\n\"\"\"\n\n# ╔═╡ 9d2e3861-ca36-406e-952d-831ca3947e44\ndata = DataFrame(°F=x,°C=y) # Label = data\n\n# ╔═╡ e73854ed-3581-41c4-ada5-e48242033759\nmd\"\"\"\n### Data Frame with a matrix\n\"\"\"\n\n# ╔═╡ 9873d944-b611-46f9-82a7-0cf714a3078c\nbegin\n\tdata2 = DataFrame([x  y]) # convert Matrix to DataFrame\n    rename!(data2,[\"°F\",\"°C\"]) # add column labels\nend\n\n# ╔═╡ 2be44753-afee-4125-b6bc-8866d2293dc2\nMatrix(data2) # Convert back to a matrix (lose label information)\n\n# ╔═╡ 6e07e8fb-fe51-4b37-bfb2-d1466e768754\nmd\"\"\"\n## Julia:Comment about types\n\nNotice that [x y] converts all the data to floats, but columns of a data frame can have different types.\n\"\"\"\n\n# ╔═╡ a755e58a-b16c-4d3b-a85f-81ccf374793f\nmd\"\"\"\n# Reading/Writing CSV (comma separated values) Files\n\"\"\"\n\n# ╔═╡ f1e10fb7-adac-4083-8977-616a505fd591\nmd\"\"\"\n  ## Writing Data to a CSV  file \nreadable by spreadsheet software.\n\"\"\"\n\n# ╔═╡ 2e42986c-2de3-49e6-9c29-a7313c0b1da8\nCSV.write(\"testCSVwrite.csv\", data)\n\n# ╔═╡ 22758dd6-9d04-4616-ba99-1430f2dedf9a\nmd\"\"\"\n ## Reading Data from a CSV file to a DataFrame\n\"\"\"\n\n# ╔═╡ aff6a616-6d8b-4584-a6f2-195decef7774\ndata_again = CSV.read(\"testCSVwrite.csv\", DataFrame ) \n\n# ╔═╡ 338da13a-3c26-4366-a669-ac3e24f31577\ndata_again[:,\"°F\" ] #or data_again[:,1]\n\n# ╔═╡ 5a742546-1e4d-4aee-bed1-cb10c543e439\ndata_again[:,1]\n\n# ╔═╡ 6a9c8c9a-fac7-42f7-976d-3168132cae48\nmd\"\"\"\n# Noisy Data\n## Add some random noise to the celsius readings\n\"\"\"\n\n# ╔═╡ 3c038b68-8676-4877-9720-38da7c4e0e0e\nbegin\n\tnoisy_data = copy(data)  # Noisy DataFrame\n\tnoisy_data[:, \"°C\" ] .+= noise * randn(n)\n\tyy = noisy_data[:, \"°C\" ]\n\tnoisy_data\nend\n\n# ╔═╡ 5a877e40-a101-4f7d-b2a1-ef4cfe5d8807\nbegin\n\t\n\tscatter(x, yy,m=:c,mc=:red, label=\"noisy data\", ylims=(-40,40))\n\tfor i=1 : length(data[:,2])\n\t\tplot!([x[i],x[i]], [m*x[i]+b,yy[i]], color=:gray, ls=:dash, label=false)\n\tend\n\txlabel!(\"°F\")\n\tannotate!(-15,16,text(\"°C\",11))\n\tplot!(x, m.*x .+ b,  color=:blue, label=\"best fit line\")\n\tplot!(x,y,alpha=.5, color=:red, label=\"theory\") # theoretical \n\tplot!(legend=:top)\nend\n\n# ╔═╡ 83c28c76-2eab-49f9-9999-05df85054520\nmd\"\"\"\n# The noise slider (so I can find it easily)\n\"\"\"\n\n# ╔═╡ ba671804-dc6d-415c-89de-9cf6294907b3\nmd\"\"\"\nnoise = $(@bind noise Slider(0:.5:1000, show_value = true ))\n\"\"\"\n\n# ╔═╡ e8683a71-5822-4491-9ccd-20e0fc3bf531\nmd\"\"\"\n## Statistics Software Outputs Mysterious Tables\nexample output from the \"linear model\"  (`lm`) which we store in the variable `ols` for ordinary least squares (by contrast weighted least squares treats the vertical displacements with unequally with differing weights.)\n\"\"\"\n\n# ╔═╡ 0489e5d8-51ca-4955-83e1-95ea353d9cf2\nols = lm(@formula(°C ~ °F), noisy_data)\n\n# ╔═╡ 9a65aee4-ab8e-4ab7-be6f-cc2a2e9d5127\nnoisy_data\n\n# ╔═╡ c3539f42-6ca7-47fb-9707-4d11c9e76643\nmd\"\"\"\nThis lecture is about explaining the meaning and significance to every part of this table.\n\"\"\"\n\n# ╔═╡ 469d809f-424f-4595-ad43-a5b2cc055304\nmd\"\"\"\n# Regression a few ways \n\"\"\"\n\n# ╔═╡ 6128b8fd-9b85-4896-a0bf-934a0733fafb\nmd\"\"\"\n## The \"Coef.\" column in the table gives the slope and intercept of the best fit line\n\"\"\"\n\n# ╔═╡ 9eb7caaa-438d-4bcb-9c54-4a0fa72c61de\nb, m = [ one.(x) x]\\ yy  # The mysterious linear algebra solution using \"least squares\"\n\n# ╔═╡ 0e8fce45-f1c0-41d4-996a-d6093182afee\nfunction linear_regression(x,y)   # a direct computation from the data\n\tn = length(x)\n\tx0  = x.-mean(x)\n\ty0 = y.-mean(y)\n\t\n\tmᵉ = sum( x0 .* y0 ) / sum(  x0.^2 ) # slope estimate\n\tbᵉ = mean(y) - mᵉ * mean(x) # intercept estimate\n\t\n\ts2ᵉ = sum(  (mᵉ.*x .+ bᵉ .- y).^2 ) /(n-2) # noise estimate\n\tbᵉ,mᵉ,s2ᵉ\nend\n\n# ╔═╡ 71590890-38b6-440e-b61b-ece6c49ac602\nlinear_regression(x,yy)\n\n# ╔═╡ f7cc7146-9ee6-4d87-b024-2a91863f4b24\nmd\"\"\"\n[So why is it called \"Regression\" anyway?](http://blog.minitab.com/blog/statistics-and-quality-data-analysis/so-why-is-it-called-regression-anyway) Dalton's original meaning not quite what it means today.\n\"\"\"\n\n# ╔═╡ f64815e2-44b8-4585-9269-9a62655c984c\nmd\"\"\"\n# Demystifying the word \"Model\"\n\n    Step I:  The Model is y = m*x + b + σ*randn() . \n    This means that out there in the real world are b, m, and σ.  You\n    don't know them.  \n    \n    Step II: You do, however, have data points x and y which allow you\n    to compute an bᵉ,  mᵉ, and σᵉ.  A statistician would call these estimates\n    based on your data points. If you ran the experiment again, you would\n    get different data points.\n    \n    The computer lets us run the experiment as many times as we want just to see what happens.\n    \n        In summary, there are three kinds of variables.  The model variables b, m, and σ which are unknown.  The predictor variable x which is considered fixed and known.  The response variable y which is considered noisy.\n\"\"\"\n\n# ╔═╡ feb3c45e-88f4-4ffc-a4a0-e89489187c8d\nmd\"\"\"\n## Understanding the relationship `°C ~ 1 + °F`\n\"\"\"\n\n# ╔═╡ 99069dd7-e088-4626-aa29-e48d6f9a474e\nols\n\n# ╔═╡ 051a9e38-9a84-4ead-96fa-24c86c2b9f2d\nmd\"\"\"\n`°C ~ 1 + °F` means the celsius (y) is (Coef1)*1 + (Coef2)*(°F),\n\nin general `y ~ 1 + x1 + x2 + x3` is shorthand for\n``y = c_0 + c_1 x_1 + c_2 x_2 + c_3 x_3``, etc.\n\"\"\"\n\n# ╔═╡ 2f33ee51-0725-46c2-9f1b-a61cd68abab1\nmd\"\"\"\n# Simulating the real world: running many noisy models\n\"\"\"\n\n# ╔═╡ e4acd97b-22f7-4812-9898-1a485887a5f2\nfunction simulate(σ,howmany)\n\t[linear_regression(x,y .+ σ * randn(length(x)))   for i=1:howmany]\n\t#[linear_regression(x,y .+ (σ * sqrt(12)) * (-.5 .+ rand(length(x))))   for i=1:howmany]\n\t# [linear_regression(x,y .+ (σ ) * ( rand([-1,1],length(x))))   for i=1:howmany]\n\t\nend\n\n# ╔═╡ 4e413b40-81c4-4160-9d01-046c2d179a06\nhowmany = 100_000\n\n# ╔═╡ 7b94db0d-f46b-4621-9413-1dc787ae9a39\nmd\"\"\"\n## Julia: underscore as a digits separator\n\"\"\"\n\n# ╔═╡ 51a28b67-ad64-4cf2-a0e6-a78fb101eb15\ns = simulate(σ, howmany)\n\n# ╔═╡ d451af49-3139-4329-a885-a210b1760f74\ns[1] # first simulation,  intercept, slope, estimation of noise σ\n\n# ╔═╡ c7455f7a-9c72-42f5-8238-1799cad96f6c\nmd\"\"\"\n## Simulated intercepts ($howmany simulations)\n\"\"\"\n\n# ╔═╡ d2971801-2cdb-4b9f-8ec8-c74cbb2a0b31\nmd\"\"\"\nσ = $(@bind σ Slider(0:.1:3, show_value=true, default=1))\n\"\"\"\n\n# ╔═╡ e1e8c140-bc4e-400d-beb2-0986e071c3a3\nbegin\t\n\thistogram( first.(s) , alpha=.6, bins=100, norm=true)\n\tvline!([-17.777777],color=:white)\n\ttitle!(\"intercept\")\n\txlims!(-17.7777-3,-17.7777+3)\n\tylims!(0,1)\n\tplot!(legend=false)\n\t\nend\n\n# ╔═╡ 1429be09-a31f-415f-9c3d-f32b085ef68d\nmd\"\"\"\nExperimental mean of the intercept\n\"\"\"\n\n# ╔═╡ da321202-0dc5-44ad-aac0-f3ea0d229243\nmean(first.(s)), -17.777777\n\n# ╔═╡ 2aceb366-a067-4271-9362-c320f4735ed1\nmd\"\"\"\nExperimental std of the intercept\n\"\"\"\n\n# ╔═╡ 58f548fd-f6d0-479d-8469-bc886783f9a7\nstd( first.(s))\n\n# ╔═╡ 07be9435-bc07-4a18-aad8-3ff19f5bcce4\nmd\"\"\"\nStatisticians know an exact formula for the theoretical std of the intercept\n\"\"\"\n\n# ╔═╡ 1a6ad08d-c3bb-47e7-bdee-156bbff3aeda\n    sb = σ * norm(x)  / norm(x.-mean(x)) / sqrt(n)\n        \n\n# ╔═╡ c55e4894-db71-4729-a1a1-5f68b45e3bf5\nmd\"\"\"\n## Simulated slopes ($howmany simulations)\n\"\"\"\n\n# ╔═╡ f50d66eb-0357-4017-ac9b-99e63cd52dc0\nbegin\n\thistogram( getindex.(s,2), alpha=.6, bins=100, norm=true, legend=false )\n\ttitle!(\"slope\")\n\tvline!([5/9],color=:white)\n\txlims!(5/9-.1, 5/9+.1)\n\tylims!(0,100)\nend\n\n# ╔═╡ 5c7a7361-f0e7-473a-9e38-226828aa00ca\nmd\"\"\"\nSample mean of the slope\n\"\"\"\n\n# ╔═╡ acf0e90e-8f1f-451f-9f0f-70a0bcc7efca\nmean(getindex.(s,2)), .555555\n\n# ╔═╡ c9f65e15-f222-4a88-98c2-9e1d8b5ec3eb\nmd\"\"\"\nSample std of the slope.\n\"\"\"\n\n# ╔═╡ 2589a369-8b21-406d-906d-71b18e4c7895\nstd( getindex.(s,2))\n\n# ╔═╡ ed6a0e6a-2d0c-4f77-9b08-1a5b5d56dd34\nmd\"\"\"\nStatisticians know a formula for the theoretical std of the slope.\n\"\"\"\n\n# ╔═╡ 61d1c1f7-e070-413b-8a92-76f44d237206\n σ  / norm(x.-mean(x))\n\n# ╔═╡ 94d80ad6-0403-4322-aa9f-647c291c19d7\nmd\"\"\"\n## Simulated σ ($howmany simulations)\n\"\"\"\n\n# ╔═╡ ce89b805-39a2-49e6-8781-c557aa73ed27\nbegin\t\n\thistogram( last.(s) ./ (σ^2/(n-2)) , alpha=.6, bins=100, norm=true,legend=false)\n\tvline!([1],color=:white)\n\ttitle!(\"residual\")\n\tvline!([n-2],color=:white, lw=4)\n\t#xlims!(0,20)\n\t#ylims!(0,.13)\n\tplot!( x-> pdf(Chisq(n-2),x) , lw=4 , color=:red )\n\tplot!()\n\t\nend\n\n# ╔═╡ 75f9b5e9-775d-4767-9da6-222f977da686\nmean( last.(s)  )\n\n# ╔═╡ 797c9f2f-0b85-4435-b1c0-edc8cf67f738\nσ^2\n\n# ╔═╡ 6e0b2452-9f8b-4730-8072-a663704893c5\nstd(last.(s))\n\n# ╔═╡ bf537a3a-b7c6-4c64-8b44-85511c3d492e\n (σ^2/ sqrt((n-2)/2))\n\n# ╔═╡ 1340818c-3391-420b-aa94-acaea8a47d7d\nmd\"\"\"\n# The Linear Model Table\n\"\"\"\n\n# ╔═╡ 829607ff-25e0-4585-9c5c-d132ecb86cc8\nols # = lm(@formula(°C ~ °F), noisy_data)\n\n# ╔═╡ 3fc0a4a8-6719-4920-99c7-bd576225214e\n-24.3784  / 19.0397\n\n# ╔═╡ 24a7ad28-936c-47dc-bc53-d1ddbf39d05d\n0.686156 / 0.330459\n\n# ╔═╡ 9233dc6a-7578-4d72-b0c2-c3bb110a9fbe\nmd\"\"\"\n## The Coef column is just the regression formula for the best line\n\"\"\"\n\n# ╔═╡ 07e02bb6-380d-40dd-86ad-19d713cd1657\nmᵉ, bᵉ, σ²ᵉ =  linear_regression(x, yy)\n\n# ╔═╡ b14593ba-cb8c-4f28-8fb0-2d2df479357b\nmd\"\"\"\n## The Std. error column\n\"\"\"\n\n# ╔═╡ ac204681-b9df-471b-a22e-9d8f68679151\nmd\"\"\"\nAbove we saw that statisticians had formulas for the exact std of the slope and intercept:\n\n `std(intercept) = σ * norm(x)  / norm(x.-mean(x)) / sqrt(n)`\n\n` std(slope) =  σ  / norm(x.-mean(x))`\n\"\"\"\n\n# ╔═╡ 08f43fff-fbd8-468f-8b3b-efd1829f4fc0\nmd\"\"\"\nLet's replace σ with our estimate √σ²ᵉ\n\"\"\"\n\n# ╔═╡ 43ec6124-c3e5-4f34-b0d9-1a0b069aa3e0\nsqrt(σ²ᵉ) * norm(x) / norm(x.-mean(x)) / sqrt(n)\n\n# ╔═╡ 3fe71215-bbf2-40e9-bcfc-0bc9b3ac94c8\nsqrt(σ²ᵉ) / norm(x.-mean(x))\n\n# ╔═╡ a2b27841-256e-4898-aeca-04c4f44138fb\nmd\"\"\"\nSee those are the numbers in the magic table above.  I always love when I can reproduce the numbers myself.  It makes me feel I understand it.\n\"\"\"\n\n# ╔═╡ 8851dca3-e1a6-46b2-9745-f175ef0b0fae\nmd\"\"\"\n## The t column\n\"\"\"\n\n# ╔═╡ ccfcb4d9-5a88-48fb-9568-1147a74f6eec\nmd\"\"\"\nThe t column, is simply the Coeff column divided by the Std. error column which we will use in a hypothesis test in the upcoming column.\n\"\"\"\n\n# ╔═╡ 13858c0a-3e7a-4742-a821-97dd9a45109d\nmd\"\"\"\n### The t-distribution\n\"\"\"\n\n# ╔═╡ b2c3c1e5-e569-4c6f-bad9-055a25d73dce\nmd\"\"\"\nIn a statistics class you will likely see a random variable known as a t-distribution.\n(with parameter k). It is the ratio of a standard normal to a χ distribution with parameter k. Let's just use `randn` to simulate. For the data sets of most of today's experiments, the normal distribution is close enough to t, that nobody needs to even use t much anymore.  In any event, with a t or a normal we are using this distribution because we are cognizant of the fact that the true σ is unknown and is merely being estimated.\n\"\"\"\n\n# ╔═╡ 305e4dfc-af7d-4667-8da8-a7ba5fd20fa6\nrand_t(k) = sqrt(k)* randn() / norm( randn(k))\n\n# ╔═╡ a648ba4f-fec4-4fa7-b328-1b52070224eb\nmd\"\"\"\nk = $(@bind k Slider(3:100, show_value=true))\n\"\"\"\n\n# ╔═╡ d652df7d-7364-4da4-b51e-9fc88b978cda\nbegin\n\n\thistogram([rand_t(k) for i=1:100000], norm=true, bins=500, label=false)\n\tplot!( x-> pdf(TDist(k),x) , lw=4 , color=:red, label=\"t dist\" )\n\tplot!( x->pdf(Normal(),x), color=:green, lw=2, label=\"normal dist\")\n\txlims!(-3, 3)\n\tylims!(0, .4)\nend\n\n# ╔═╡ 2e530106-57a8-46a9-8f99-49a871d43255\nmd\"\"\"\n## The Pr(>|t|)  column \nis the area of the curve outside of the interval [-t,t].\n\"\"\"\n\n# ╔═╡ a990b133-ce50-4edf-81e1-1e78aeff8cd6\nmd\"\"\"\nIn statistics we ask if the coefficient ought to be considered 0 (which means in this case the data has no intercept or does not depend on x) or whether the coefficients are signficant with some probability.  The Pr(>|t|) column gives us the probablity that we should accept the hypothesis that the coefficients might reasonably be just 0.\n\nIn a proper statistical test, you should decide at what level you might be willing to accept the hypothesis, example .99, .95, or .9  might be a reasonable level, and if the test gives a smaller probability, you will accept that the coefficients are signficant.  It is not proper to produce the able and then decide whether to use .99, say.\n\"\"\"\n\n# ╔═╡ 3d0ea801-d66b-4e4e-90da-3a7dce28140d\nmd\"\"\"\n# Degrees of Freedom\n\"\"\"\n\n# ╔═╡ 6fb223bb-f193-414d-9144-df180d09bea1\nmd\"\"\"\nIt is interesting to see that the sum of squares of a demeaned Gaussian vector is the size -1.  This is the reason for the (n-1) in the sample mean for variance.\n\"\"\"\n\n# ╔═╡ fb495ba4-52e6-4e0d-bd9c-981700edfebc\nmd\"\"\"\nHow many degrees of freedom are in a \"demeaned\" vector of normals?\n\"\"\"\n\n# ╔═╡ cdc4b25d-d05f-40c8-9c79-265876f01523\n   \nmean([ (v = randn(17);v.-=mean(v);sum(v.^2)) for i=1:1_000_000])\n\n# ╔═╡ 967c5e3e-ab4c-45de-953c-aff6d16229af\nmd\"\"\"\nIf you ever wondered why the sample variance always has you dividing by (n-1)\nand not n, this is the crux of the reason.\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─4ea0ccfa-9622-11eb-1cf0-e9ae2f927dd2\n# ╠═d155ea12-9628-11eb-347f-7754a33fd403\n# ╠═01506de2-918a-11eb-2a4d-c554a6e54631\n# ╟─877deb2c-702b-457b-a54b-f27c277928d4\n# ╟─36ce167f-382c-4b9a-be34-83250b10c4e5\n# ╟─83912943-a847-420a-bfdb-450027b631e8\n# ╠═280d112f-d34a-4cc4-9e3a-4ebbfcd5eb51\n# ╠═b5031c96-db57-4baf-b271-6bb12e29de9b\n# ╠═c2f77e8f-a8c0-4144-a8b4-b25dd98ed234\n# ╟─ad161b98-f4a1-42ac-ad4f-8b71fabcfde9\n# ╠═8e422886-74ef-4c0f-be1e-fda238c8db44\n# ╟─ca21122a-2522-482a-b7ef-bd73e96cb5a9\n# ╟─41e05b1e-8b5e-45e3-91bb-01355ade9f3d\n# ╠═9d2e3861-ca36-406e-952d-831ca3947e44\n# ╟─e73854ed-3581-41c4-ada5-e48242033759\n# ╠═9873d944-b611-46f9-82a7-0cf714a3078c\n# ╠═2be44753-afee-4125-b6bc-8866d2293dc2\n# ╟─6e07e8fb-fe51-4b37-bfb2-d1466e768754\n# ╟─a755e58a-b16c-4d3b-a85f-81ccf374793f\n# ╟─f1e10fb7-adac-4083-8977-616a505fd591\n# ╠═2e42986c-2de3-49e6-9c29-a7313c0b1da8\n# ╟─22758dd6-9d04-4616-ba99-1430f2dedf9a\n# ╠═aff6a616-6d8b-4584-a6f2-195decef7774\n# ╠═338da13a-3c26-4366-a669-ac3e24f31577\n# ╠═5a742546-1e4d-4aee-bed1-cb10c543e439\n# ╟─6a9c8c9a-fac7-42f7-976d-3168132cae48\n# ╟─3c038b68-8676-4877-9720-38da7c4e0e0e\n# ╟─5a877e40-a101-4f7d-b2a1-ef4cfe5d8807\n# ╟─83c28c76-2eab-49f9-9999-05df85054520\n# ╟─ba671804-dc6d-415c-89de-9cf6294907b3\n# ╟─e8683a71-5822-4491-9ccd-20e0fc3bf531\n# ╠═0489e5d8-51ca-4955-83e1-95ea353d9cf2\n# ╠═9a65aee4-ab8e-4ab7-be6f-cc2a2e9d5127\n# ╟─c3539f42-6ca7-47fb-9707-4d11c9e76643\n# ╟─469d809f-424f-4595-ad43-a5b2cc055304\n# ╟─6128b8fd-9b85-4896-a0bf-934a0733fafb\n# ╠═9eb7caaa-438d-4bcb-9c54-4a0fa72c61de\n# ╠═0e8fce45-f1c0-41d4-996a-d6093182afee\n# ╠═71590890-38b6-440e-b61b-ece6c49ac602\n# ╟─f7cc7146-9ee6-4d87-b024-2a91863f4b24\n# ╟─f64815e2-44b8-4585-9269-9a62655c984c\n# ╟─feb3c45e-88f4-4ffc-a4a0-e89489187c8d\n# ╠═99069dd7-e088-4626-aa29-e48d6f9a474e\n# ╟─051a9e38-9a84-4ead-96fa-24c86c2b9f2d\n# ╟─2f33ee51-0725-46c2-9f1b-a61cd68abab1\n# ╠═e4acd97b-22f7-4812-9898-1a485887a5f2\n# ╠═4e413b40-81c4-4160-9d01-046c2d179a06\n# ╟─7b94db0d-f46b-4621-9413-1dc787ae9a39\n# ╠═51a28b67-ad64-4cf2-a0e6-a78fb101eb15\n# ╠═d451af49-3139-4329-a885-a210b1760f74\n# ╟─c7455f7a-9c72-42f5-8238-1799cad96f6c\n# ╟─d2971801-2cdb-4b9f-8ec8-c74cbb2a0b31\n# ╠═e1e8c140-bc4e-400d-beb2-0986e071c3a3\n# ╟─1429be09-a31f-415f-9c3d-f32b085ef68d\n# ╠═da321202-0dc5-44ad-aac0-f3ea0d229243\n# ╟─2aceb366-a067-4271-9362-c320f4735ed1\n# ╠═58f548fd-f6d0-479d-8469-bc886783f9a7\n# ╟─07be9435-bc07-4a18-aad8-3ff19f5bcce4\n# ╠═1a6ad08d-c3bb-47e7-bdee-156bbff3aeda\n# ╟─c55e4894-db71-4729-a1a1-5f68b45e3bf5\n# ╠═f50d66eb-0357-4017-ac9b-99e63cd52dc0\n# ╟─5c7a7361-f0e7-473a-9e38-226828aa00ca\n# ╠═acf0e90e-8f1f-451f-9f0f-70a0bcc7efca\n# ╟─c9f65e15-f222-4a88-98c2-9e1d8b5ec3eb\n# ╠═2589a369-8b21-406d-906d-71b18e4c7895\n# ╟─ed6a0e6a-2d0c-4f77-9b08-1a5b5d56dd34\n# ╠═61d1c1f7-e070-413b-8a92-76f44d237206\n# ╟─94d80ad6-0403-4322-aa9f-647c291c19d7\n# ╠═ce89b805-39a2-49e6-8781-c557aa73ed27\n# ╠═75f9b5e9-775d-4767-9da6-222f977da686\n# ╠═797c9f2f-0b85-4435-b1c0-edc8cf67f738\n# ╠═6e0b2452-9f8b-4730-8072-a663704893c5\n# ╠═bf537a3a-b7c6-4c64-8b44-85511c3d492e\n# ╟─1340818c-3391-420b-aa94-acaea8a47d7d\n# ╠═829607ff-25e0-4585-9c5c-d132ecb86cc8\n# ╠═3fc0a4a8-6719-4920-99c7-bd576225214e\n# ╠═24a7ad28-936c-47dc-bc53-d1ddbf39d05d\n# ╟─9233dc6a-7578-4d72-b0c2-c3bb110a9fbe\n# ╠═07e02bb6-380d-40dd-86ad-19d713cd1657\n# ╟─b14593ba-cb8c-4f28-8fb0-2d2df479357b\n# ╟─ac204681-b9df-471b-a22e-9d8f68679151\n# ╟─08f43fff-fbd8-468f-8b3b-efd1829f4fc0\n# ╠═43ec6124-c3e5-4f34-b0d9-1a0b069aa3e0\n# ╠═3fe71215-bbf2-40e9-bcfc-0bc9b3ac94c8\n# ╟─a2b27841-256e-4898-aeca-04c4f44138fb\n# ╟─8851dca3-e1a6-46b2-9745-f175ef0b0fae\n# ╟─ccfcb4d9-5a88-48fb-9568-1147a74f6eec\n# ╟─13858c0a-3e7a-4742-a821-97dd9a45109d\n# ╟─b2c3c1e5-e569-4c6f-bad9-055a25d73dce\n# ╠═305e4dfc-af7d-4667-8da8-a7ba5fd20fa6\n# ╟─a648ba4f-fec4-4fa7-b328-1b52070224eb\n# ╠═d652df7d-7364-4da4-b51e-9fc88b978cda\n# ╟─2e530106-57a8-46a9-8f99-49a871d43255\n# ╟─a990b133-ce50-4edf-81e1-1e78aeff8cd6\n# ╟─3d0ea801-d66b-4e4e-90da-3a7dce28140d\n# ╟─6fb223bb-f193-414d-9144-df180d09bea1\n# ╟─fb495ba4-52e6-4e0d-bd9c-981700edfebc\n# ╠═cdc4b25d-d05f-40c8-9c79-265876f01523\n# ╟─967c5e3e-ab4c-45de-953c-aff6d16229af\n", "meta": {"hexsha": "4abe57561491da221ac293cf2c30f40932880abf", "size": 20218, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/week9/linearmodel_datascience.jl", "max_stars_repo_name": "rfhklwt/18S191_notebook", "max_stars_repo_head_hexsha": "beb6001d2fc92a317cb9e578a60d83222512bebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/week9/linearmodel_datascience.jl", "max_issues_repo_name": "rfhklwt/18S191_notebook", "max_issues_repo_head_hexsha": "beb6001d2fc92a317cb9e578a60d83222512bebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/week9/linearmodel_datascience.jl", "max_forks_repo_name": "rfhklwt/18S191_notebook", "max_forks_repo_head_hexsha": "beb6001d2fc92a317cb9e578a60d83222512bebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4294032023, "max_line_length": 434, "alphanum_fraction": 0.7040261153, "num_tokens": 9328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.9073122238669025, "lm_q1q2_score": 0.7747654721226659}}
{"text": "#---------------------------------------------------------\n# # [LazyGrids ndgrid](@id 1-ndgrid)\n#---------------------------------------------------------\n\n# This page explains the `ndgrid` method(s) in the Julia package\n# [`LazyGrids`](https://github.com/JuliaArrays/LazyGrids.jl).\n\n# ### Setup\n\n# Packages needed here.\n\nusing LazyGrids: ndgrid, ndgrid_array\nusing LazyGrids: btime, @timeo # not exported; just for timing tests here\nusing BenchmarkTools: @benchmark\nusing InteractiveUtils: versioninfo\n\n\n# ### Overview\n\n# We begin with simple illustrations.\n\n# The Julia method `ndgrid_array` in this package\n# is comparable to Matlab's `ndgrid` function.\n# It is given a long name here\n# to discourage its use,\n# because the lazy `ndgrid` version is preferable.\n# The package provides `ndgrid_array`\n# mainly for testing and timing comparisons.\n\n(xa, ya) = ndgrid_array(1.0:3.0, 1:2)\n\n#\nxa\n\n#\nya\n\n\n# This package provides a \"lazy\" version of `ndgrid` that appears to the user\n# to be the same, but under the hood it is not storing huge arrays.\n\n(xl, yl) = ndgrid(1.0:3.0, 1:2)\n\n#\nxl\n\n#\nyl\n\n\n# The following example illustrates the memory savings\n# (thanks to Julia's powerful `AbstractArray` type):\n\n(xl, yl) = ndgrid(1:100, 1:200)\n(xa, ya) = ndgrid_array(1:100, 1:200)\nsizeof(xl), sizeof(xa)\n\n\n# One can do everything with a lazy array that one would expect\n# from a \"normal\" array, e.g., multiplication and summation:\n\nsum(xl * xl'), sum(xa * xa')\n\n\n# ### Using lazy `ndgrid`\n\n# Many applications with multiple variables\n# involve evaluating functions over a *grid* of values.\n\n# As a simple example (for illustration),\n# one can numerically approximate the area of the unit circle\n# by sampling that circle over a grid of x,y values,\n# corresponding to numerical evaluation of the double integral\n# ``∫ ∫ 1_{\\{x^2 + y^2 < 1\\}} \\, dx \\, dy``.\n# There are many ways to implement this approximation in Julia,\n# given a vector of `x` and `y` samples.\n\nΔ = 1/2^10\nx = range(-1, stop=1, step=Δ)\ny = copy(x)\n\n@inline circle(x::Real, y::Real) = abs2(x) + abs2(y) < 1\n@inline circle(xy::NTuple{2}) = circle(xy...)\n\n# The documentation below has many timing comparisons.\n# The times in the Julia comments are on a 2017 iMac with Julia 1.6.1;\n# the times printed out are whatever server GitHub actions uses.\n# Using a trick to [capture output](https://fredrikekre.github.io/Literate.jl/v2/generated/example/#Output-Capturing),\n# let's find out:\n\nio = IOBuffer()\nversioninfo(io)\nsplit(String(take!(io)), '\\n')\n\n\n# A basic double loop is the C/Fortran way.\n# It uses minimal memory (only 48 bytes) but is somewhat slow.\n\nfunction method0(x,y) # basic double loop\n    sum = 0.0\n    for x in x, y in y\n        sum += circle(x,y)\n    end\n    return sum * Δ^2\nend\n\narea0 = method0(x,y)\nt = @benchmark method0($x,$y) # 10.5 ms (3 allocations: 48 bytes)\nbtime(t)\n\n\n# The loop version does not look much like the math.\n# It often seems natural to think of a grid of x,y values\n# and simply sum over that grid, accounting for the grid spacing,\n# using a function like this:\n\narea(xx,yy) = sum(circle.(xx,yy)) * Δ^2\n\n\n# Users coming from Matlab who are unfamiliar with its newer broadcast\n# capabilities might use an `ndgrid` of arrays, like in the following code,\n# to compute the area.\n# But this array approach is much slower and uses much more memory,\n# so it does not scale well to higher dimensions.\n\nfunction area_array(x, y)\n    (xa, ya) = ndgrid_array(x, y)\n    return area(xa, ya)\nend\n@assert area_array(x, y) ≈ area0\nt = @benchmark area_array($x, $y) # 21.4 ms (11 allocations: 64.57 MiB)\nbtime(t)\n\n\n# To be fair, one might have multiple uses of the grids `xa,ya`\n# so perhaps they should be excluded from the timing.\n# Separating that allocation makes the timing look faster,\n# but it still uses a lot of memory,\n# both for allocating the grids, and for the `circle.` broadcast\n# in the `area` function above:\n\n(xa, ya) = ndgrid_array(x, y)\n@assert area(xa, ya) ≈ area0\nt = @benchmark area($xa, $ya) # 5.2 ms (7 allocations: 516.92 KiB)\nbtime(t)\n\n\n# The main point of this package is to provide\n# a lazy version of `ndgrid` that uses minimal memory.\n\n(xl, yl) = ndgrid(x, y)\n@assert xl == xa\n@assert yl == ya\nsizeof(xa), sizeof(xl)\n\n\n# Now there is essentially no memory overhead for the grids,\n# but memory is still used for the `circle.` broadcast.\n\n@assert area(xl,yl) ≈ area0\nt = @benchmark area($xl,$yl) # 3.7 ms (7 allocations: 516.92 KiB)\nbtime(t)\n\n\n# Furthermore, creating this lazy ndgrid is so efficient\n# that we can include its construction time\n# and still have performance comparable to the array version\n# that had pre-allocated arrays.\n\nfunction area_lazy(x, y)\n    (xl, yl) = ndgrid(x, y)\n    return area(xl, yl)\nend\n@assert area_lazy(x, y) ≈ area0\nt = @benchmark area_lazy($x, $y) # 3.7 ms (7 allocations: 516.92 KiB)\nbtime(t)\n\n\n# ### More details\n\n# The comparisons below here might be more\n# for the curiosity of the package developers\n# than for most users...\n\n# One can preallocate memory to store the `circle.` array,\n# to avoid additional memory during the area calculation:\n\nout = Array{Float64}(undef, length(x), length(y))\nfunction area!(xx, yy)\n    global out .= circle.(xx,yy)\n    return sum(out) * Δ^2\nend\n@assert area!(xl,yl) ≈ area0\nt = @benchmark area!(xl,yl) # 4.8 ms (4 allocations: 128 bytes)\nbtime(t)\n\n\n# Interestingly, the lazy version is *faster* than the array version,\n# presumably because of the overheard of moving data from RAM to CPU:\n\n@assert area!(xa,ya) ≈ area0\nt = @benchmark area!(xa,ya) # 6.2 ms (4 allocations: 80 bytes)\nbtime(t)\n\n\n# One can avoid allocating the output array by using a loop\n# with [CartesianIndices](https://julialang.org/blog/2016/02/iteration):\n\nfunction area_ci(xx, yy)\n    size(xx) == size(yy) || throw(\"size\")\n    sum = 0.0\n    @inbounds for c in CartesianIndices(xx)\n        sum += circle(xx[c], yy[c])\n    end\n    return sum * Δ^2\nend\n\n\n# With this approach the lazy version is a bit faster\n# than the array version:\n\n@assert area_ci(xl,yl) ≈ area0\nt = @benchmark area_ci(xl,yl) # 5.2 ms (3 allocations: 48 bytes)\nbtime(t)\n\n#\n@assert area_ci(xa,ya) ≈ area0\nt = @benchmark area_ci(xa,ya) # 5.9 ms (3 allocations: 48 bytes)\nbtime(t)\n\n\n# Alternatively one can use a linear index for loop,\n# that also avoids the extra memory of `circle.` above,\n# but is slower, especially for the lazy arrays\n# that are optimized for Cartesian indexing:\n\nfunction area_for2(xx,yy)\n    size(xx) == size(yy) || throw(\"size\")\n    sum = 0.0\n    @inbounds for i in 1:length(xx)\n        sum += circle(xx[i], yy[i])\n    end\n    return sum * Δ^2\nend\n@assert area_for2(xa, ya) ≈ area0\nt = @benchmark area_for2($xa, $ya) # 5.9 ms (3 allocations: 48 bytes)\nbtime(t)\n\n#\n@assert area_for2(xl, yl) ≈ area0\nt = @benchmark area_for2($xl, $yl) # 15.4 ms (3 allocations: 48 bytes)\nbtime(t)\n\n\n# Some Julia users would\n# [recommend using broadcast](https://discourse.julialang.org/t/meshgrid-function-in-julia/48679/25).\n# In this case, broadcast is reasonably fast, but still uses a lot of memory\n# for the `circle.` output in the simplest implementation.\n\nareab(x,y) = sum(circle.(x,y')) * Δ^2\n@assert areab(x,y) ≈ area0\nt = @benchmark areab($x,$y) # 11.6 ms (7 allocations: 516.92 KiB)\nbtime(t)\n\n\n# Using `zip` can avoid the \"extra\" memory beyond the grids,\n# but seems to have some undesirable overhead,\n# presumably because `zip` uses linear indexing:\n\nareaz(xa, ya) = sum(circle, zip(xa,ya)) * Δ^2\n@assert areaz(xa, ya) ≈ area0\nt = @benchmark areaz($xa, $ya) # 3.9 ms (3 allocations: 48 bytes)\nbtime(t)\n\n#\n@assert areaz(xl, yl) ≈ area0\nt = @benchmark areaz($xl, $yl) # 12.2 ms (3 allocations: 48 bytes)\nbtime(t)\n\n\n# One can also ensure low memory by using a product iterator,\n# but the code starts to look pretty different from the math at this point\n# and it is not much faster than broadcast here.\n\nareap(x,y) = sum(circle, Iterators.product(x, y)) * Δ^2\n@assert areap(x,y) ≈ area0\nt = @benchmark areap($x, $y) # 9.9 ms (3 allocations: 48 bytes)\nbtime(t)\n\n\n# ### 3D case\n\n# A 3D example is finding (verifying) the volume of a unit sphere.\n\nsphere(x::Real,y::Real,z::Real) = abs2(x) + abs2(y) + abs2(z) < 1\nsphere(r::NTuple) = sum(abs2, r) < 1\n\n\n# Storing three 3D arrays of size 2049^3 Float64 would take 192GB,\n# so already we must greatly reduce the sampling to use either\n# `broadcast` or `ndgrid_array`.\n# Furthermore, the `broadcast` requires annoying `reshape` steps:\n\nΔc = 1/2^8 # coarse grid\nxc = range(-1, stop=1, step=Δc)\nyc = xc\nzc = xc\nnc = length(zc)\n3 * nc^3 * 8 / 1024^3 # GB prediction\n\n# Here is broadcast in 3D (yuch!):\n\nvol_br(x,y,z,Δ) = sum(sphere.(\n        repeat(x, 1, length(y), length(z)),\n        repeat(reshape(y, (1, :, 1)), length(x), 1, length(z)),\n        repeat(reshape(z, (1, 1, :)), length(x), length(y), 1),\n    )) * Δ^3\nvol_br([0.],[0.],[0.],Δc) # warm-up\n@timeo vol0 = vol_br(xc,yc,zc,Δc) # 2.7 sec, 3.0 GiB, roughly (4/3)π\n\nfunction vol_ci(xx, yy, zz, Δ)\n    size(xx) == size(yy) == size(zz) || throw(\"size\")\n    sum = 0.0\n    @inbounds for c in CartesianIndices(xx)\n        sum += sphere(xx[c], yy[c], zz[c])\n    end\n    return sum * Δ^3\nend\n\n# Here is the lazy version:\n(xlc, ylc, zlc) = ndgrid(xc, yc, zc) # warm-up\n@timeo (xlc, ylc, zlc) = ndgrid(xc, yc, zc); # 0.000022 sec (1.8 KiB)\n\n#\nvol_ci([0.], [0.], [0.], Δc) # warm-up\n@timeo vol_ci(xlc, ylc, zlc, Δc) # 0.2 sec, 1.4 MiB\n\n\n# Creating the grid of arrays itself is quite slow, even for the coarse grid:\n(xac, yac, zac) = ndgrid_array(xc, yc, zc) # warm-up\n@timeo (xac, yac, zac) = ndgrid_array(xc, yc, zc) # 1.8 sec 3.0GiB\n\n# Once created, the array version is no faster than the lazy version:\n@timeo vol_ci(xac, yac, zac, Δc) # 0.2 seconds (1.1 MiB)\n\n# Using `zip` is more concise (but slower):\nvol_zip(xx, yy, zz, Δ) = sum(sphere, zip(xx,yy,zz)) * Δ^3\n\n#\nvol_zip([0.], [0.], [0.], Δc) # warm-up\n@timeo vol_zip(xlc, ylc, zlc, Δc) # 1.0 sec, 26 MiB\n\n\n# Using zip for the array version seems to have less overhead\n# so that is a potential for future improvement:\n\n@assert vol_zip(xac, yac, zac, Δc) ≈ vol0\n@timeo vol_zip(xac, yac, zac, Δc) # 0.19 sec, 16 byte\n\n\n# Importantly, with the lazy ndgrid now we can return to the fine scale;\n# it takes a few seconds, but it is feasible because of the low memory.\nz = copy(x)\n@timeo (xlf, ylf, zlf) = ndgrid(x, y, z) # 0.000023 sec\n\n#\n@timeo vol_ci(xlf, ylf, zlf, Δ) # 12.7 sec, 16 bytes\n\n\n# I was hoping that with a lazy grid, now we could explore\n# higher-dimensional spheres.  But with the current `zip` overhead\n# it was too slow, even with coarse grid.\n# @timeo (π^2/2, sum(sphere, zip(ndgrid(xc,xc,xc,xc)...)) * Δc^4)\n\n# Probably I need to learn more about stuff like `pairs(IndexCartesian(), A)`\n# [e.g., this PR](https://github.com/JuliaLang/julia/pull/38150).\n# Another day...\n", "meta": {"hexsha": "e47609ce5b4c7039198e4cfff990fc676712094d", "size": 10766, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/lit/examples/1-ndgrid.jl", "max_stars_repo_name": "JuliaArrays/LazyGrids.jl", "max_stars_repo_head_hexsha": "399d6112c91f3778f0c769bf58ccd8e24f69881f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-07-10T19:23:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T16:16:28.000Z", "max_issues_repo_path": "docs/lit/examples/1-ndgrid.jl", "max_issues_repo_name": "JuliaArrays/LazyGrids.jl", "max_issues_repo_head_hexsha": "399d6112c91f3778f0c769bf58ccd8e24f69881f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-07-06T14:46:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T18:09:09.000Z", "max_forks_repo_path": "docs/lit/examples/1-ndgrid.jl", "max_forks_repo_name": "JuliaArrays/LazyGrids.jl", "max_forks_repo_head_hexsha": "399d6112c91f3778f0c769bf58ccd8e24f69881f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-06T14:33:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T14:33:09.000Z", "avg_line_length": 28.4814814815, "max_line_length": 118, "alphanum_fraction": 0.6723945755, "num_tokens": 3438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.9073122163480667, "lm_q1q2_score": 0.7747654690753631}}
{"text": "using JuMP\nusing Clp\n\nCARBS = 50\nPROTEIN = 40\nFAT = 60\n\nm = Model(Clp.Optimizer)\n\n@variable(m, steak ≥ 0)\n@variable(m, potatoes ≥ 0)\n\n@objective(m, Min, 8 * steak + 4 * potatoes)\n\n\n\n\n@constraint(m, 5 * steak + 15 * potatoes ≥ CARBS)\n@constraint(m, 20 * steak + 5 * potatoes ≥ PROTEIN)\n@constraint(m, 15 * steak + 2 * potatoes ≤ FAT)\n\nprint(m)\n\noptimize!(m)\n\nstatus = termination_status(m)\n\nprintln(\"Solution status: \", status)\n\nprintln(\"Objective value: \", objective_value(m))\nprintln(\"potatoes = \", value(steak))\nprintln(\"steak = \", value(potatoes))\n", "meta": {"hexsha": "26be897d033dcd0b1c8cf90207ba5488272b357c", "size": 551, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week2/example_1.jl", "max_stars_repo_name": "InzamamRahaman/COMP6925-2021", "max_stars_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-23T23:33:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T01:47:28.000Z", "max_issues_repo_path": "week2/example_1.jl", "max_issues_repo_name": "InzamamRahaman/COMP6925-2021", "max_issues_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week2/example_1.jl", "max_forks_repo_name": "InzamamRahaman/COMP6925-2021", "max_forks_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.696969697, "max_line_length": 51, "alphanum_fraction": 0.666061706, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338057771059, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.774642593702095}}
{"text": "export RandomPatch\n\n\"\"\"\n    RandomPatch()\n\nA random patch. For this we first draw entries of a vector `v` independently from a\ncomplex normal distribution (`randn(ComplexF64)`). And then normalize `v` with respect\nto the 2-norm.\n\"\"\"\nstruct RandomPatch <: AbstractAffinePatch end\n\nstruct RandomPatchState{T,N} <: AbstractAffinePatchState{N}\n    v::PVector{T,N}\nend\n\nis_global_patch(::RandomPatch) = true\n\nfunction state(::RandomPatch, x::PVector)\n    v = similar(x, ComplexF64)\n    Random.randn!(v)\n    LinearAlgebra.normalize!(v)\n    RandomPatchState(v)\nend\n\nonpatch!(x::AbstractVector, state::RandomPatchState) = onpatch!(x, state.v)\nevaluate!(u, state::RandomPatchState, x::PVector) = evaluate_patch!(u, state.v, x)\njacobian!(U, state::RandomPatchState, x::PVector) = jacobian_patch!(U, state.v, x)\n", "meta": {"hexsha": "f4764339192c6fa1dc212aa6eab3edb55d643fad", "size": 801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "v1/src/affine_patches/random_patch.jl", "max_stars_repo_name": "mbauman/HomotopyContinuation.jl", "max_stars_repo_head_hexsha": "3253f86b2752303b0ed8616e07bccf8bfbb7f24d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "v1/src/affine_patches/random_patch.jl", "max_issues_repo_name": "mbauman/HomotopyContinuation.jl", "max_issues_repo_head_hexsha": "3253f86b2752303b0ed8616e07bccf8bfbb7f24d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "v1/src/affine_patches/random_patch.jl", "max_forks_repo_name": "mbauman/HomotopyContinuation.jl", "max_forks_repo_head_hexsha": "3253f86b2752303b0ed8616e07bccf8bfbb7f24d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6071428571, "max_line_length": 86, "alphanum_fraction": 0.7303370787, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862455, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7746425882798318}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 0810c98f-2526-4ab4-9cd5-a662434e332d\nbegin\n\tusing Statistics\n\tusing StatsBase\n\tusing Plots\nend\n\n# ╔═╡ a4283cac-c253-11ec-1d76-495287bbab72\nmd\"\"\"\n# Bootstrap Method Notes\n\nI'm working through Lorna Yen's article [An Introduction to the Bootstrap Method](https://towardsdatascience.com/an-introduction-to-the-bootstrap-method-58bcb51b4d60). The Bootstrap Method was introduced by Bradley Efron in 1979.\n\nDate: 2022 April 22\n\n\n## The Bootstrap Sampling Method\n\nWe need to make an inference about an estimate (e.g. sample mean) for a population parameter $$\\theta$$ (e.g. population mean).\n\nBasic Steps in a bootstrap method:\n\n1. Start with a sample of size $$n$$.\n2. Create $$B$$ Bootstrap Samples of size $$n$$ by drawing from the original sample with replacement.\n3. Evaluate the statistic $$\\theta$$ on each sample, giving us $$B$$ estimates.\n4. Constrtuct a sampling distribution with these bootstrap statistics and use it to make further statistical inference, such as estimating the standard error for $$\\theta$$ or obtaining a confidence interval for $$\\theta$$.\n\"\"\"\n\n# ╔═╡ c33fde47-ac17-4194-973b-cdb277907b60\nmd\"\"\"\n## Motivation - The Esimator's Standard Error\n\nHow can we evaluate the accuracy of an estimator?\n\nExample: We want to esimate the number of times your 100 student pick up their phones in a day. 30 students installed an app which tells you how many times they picked up their phones. We will calculate the mean of these 30 students and get an estimate for pickups.\n\"\"\"\n\n# ╔═╡ e42b8dfb-1a75-448c-acc1-3255c87a0edf\npickups = rand(0:500, 100)\n\n# ╔═╡ 0e14ff27-5d05-4367-947e-d97e96ddfa8e\nmd\"\"\"\n\nThe population mean is **$(mean(pickups))** pickups. Now, let's get our sample of 30 students. Note that this is performed without replacement.\n\n\"\"\"\n\n# ╔═╡ fbbc6413-0afb-4531-8113-bb85afd2710d\nresponses = sample(pickups, 30)\n\n# ╔═╡ 0ed657f2-8f2b-4e8f-a375-9c8986448340\nmd\"\"\"\n\nOur sample mean is **$(round(mean(responses); digits=2))** with standard deviation **$(round(std(responses); digits=2))**.\n\nThis is called a point estimate, but what we want is the true number of pickups in the whole lab.\n\nAn **estimator** is a rule for calculating an estimate. In this case, we are using sample mean, denoted $$\\bar{X}$$. A **population parameter** is a numeric summary about a population. In this case, this is the average time of phone pickups per day, denoted $$\\mu$$.\n\nBut how accurate is the estimate result? (How far is $$\\bar{X}$$ from $$\\mu$$?) The common measure is the standard error.\n\"\"\"\n\n# ╔═╡ c30c49a1-2821-4ada-ab10-5cac70a99e87\nmd\"\"\"\n## Standard Error\n\n**The standard error of an estimator is it's standard deviation.** Often times we do not know the parameters, and must use an estimated standard error.\n\n### Standard Error of Sample Mean\n\n$$\\sigma_{\\bar{x}} = \\frac{\\sigma}{\\sqrt{n}}$$\n\nwhere $$\\sigma$$ is the standard deviation of the population and $$n$$ is the size of the sample. However, we do not know the standard devation of the population. Thus, we use estimated standard error, where we use the sample standard deviation $$S$$ in place of $$\\sigma$$.\n\n$$\\sigma_{\\bar{x}} \\approx \\frac{S}{\\sqrt{n}}$$\n\nwhere\n\n$$S = \\sum_{i=1}^n\\frac{(x_i-\\bar{x})^2}{n-1}$$\n\n\nThis means that for us, **$$S=$$ $(round(std(responses);digits=2))** and **$$\\sigma_{\\bar{x}}\\approx$$ $(round(std(responses) / sqrt(length(responses));digits=2))**.\n\nWith the assumption that the estimator as a normal distribution, then we expect our estimate to be within $$\\bar{x}\\pm\\sigma_{\\bar{x}}$$ 68% of the time and within $$\\bar{x}\\pm2\\sigma_{\\bar{x}}$$ 95% of the time.\n\"\"\"\n\n# ╔═╡ 520524ab-53ef-4edb-bc58-f6a86620a126\nmd\"\"\"\n### The Real World\n\nAssumptions we have used so far: \n\n - We can easily estimate the standard error of our statistic of interest.\n - We assume the estimator follows a normal distribution.\n\nBut in the real world:\n\n - It is hard to know information about the population or it's distribution.\n - The standard error is hard to evaluate standard error in general. For instance, the standard error of the median is hard to know.\n\nThe bootstrap method helps us in these cases.\n\"\"\"\n\n# ╔═╡ fda6b303-a082-4f44-8341-49446b100609\nmd\"\"\"\n## The Bootstrap Method Explained\n\n### Scenario\n\nAssume want to estimate the standard error of a statistic to make an inference about a population parameter, such as for construction the corresponding confidence interval. Assume further that:\n\n - We don't know anything about the population.\n - There is no precise formula for estimating the standard error of the statistic.\n\nLet $$X_1, X_2, \\dots, X_n$$ be a random sample from a population $$P$$ with distribution function $$F$$ Let $$M=g(X_1, X_2, \\dots, X_n)$$ be our statistic for the parameter of interest. We want to know the variance of $$M$$,denoted $$Var(M)$$.\n\nChallenges:\n\n - We can't determine the variance of the population since we don't know it. Thus, we need to estimate the variance and estimate the standard error.\n - In the real world, we don't always have a simple formula for evaluting the estimated variance or than sample means.\n\nBefore we get to esimating the variance, we'll introduce a common practical way, through simulation, assuming we know $$P$$.\n\"\"\"\n\n# ╔═╡ 4453da4c-12fc-427d-9f9c-89476bf65541\nmd\"\"\"\n### Simulation\n\nIf we know $$P$$, we can generate $$B$$ random samples of size $$n$$, and calculate the statistic on each. Using these $$B$$ measurements, we can get a mean and a variance. The law of large numbers tells us the sample mean and variance of these $$B$$ statistics converges to the true variance as more samples are taken.\n\nBelow, we will use $$B=100000$$ for the phone problem above. First we'll look at  the distribution of the sample means, and then we will look at what the average mean converges to.\n\"\"\"\n\n# ╔═╡ f9153c34-d26b-4e54-847e-c3bae8cdb4df\nsims = [mean(sample(pickups, 30; replace=false)) for x in 1:100000]\n\n# ╔═╡ d273d1b8-e66c-4461-ab55-b2a4fe578d0c\nhistogram(sims, fillcolor=:black, plot_title=\"Histogram of Sample Means\", legend = false)\n\n# ╔═╡ 14b9e9b0-d67b-4376-80a5-cb0b76602174\nconvergence = [mean(sims[1:i]) for i in 1:100000]\n\n# ╔═╡ ceb8a078-4c55-40e7-a1bf-41bc357eaf86\nplot(convergence, \n\tlinecolor=:black, \n\tplottitle=\"Convergence of Sample Means\",\n\txlabel=\"Number of Simulations\",\n\tylabel=\"Mean of first N Simulations\",\n\tlegend=false)\n\n# ╔═╡ 3c1f21fb-be76-446d-b27f-54119ee4835a\nmd\"\"\"\nIn the distribution chart, we see that the means are normally distributed, and centered just below 250. \n\nIn the bottom chart, after running 1000000 experiments, we see that the mean quickly approaches a stable value. The final value is $(round(convergence[100000]; digits=2)) which is very close to the true value of $(round(mean(pickups);digits=2)). \n\"\"\"\n\n# ╔═╡ 1e05bcbc-cf0a-47ba-a1be-cb2e9bafff78\nmd\"\"\"\n### The Empirical Distribution Function and Plug-in Principle\n\nBut we can't use simulation because we don't know $$P$$.\n\nWe will use the empirical distribution function to approximate the distribution function of the population and will apply the plug-in principle to get an estimate for Var(M), which is the plug-in estimator.\n\n#### The Empirical Distribution Function\n\nWe'll build a CDF from data. The EDF is a discrete distribution that weights each point equally. It forms a step function that increases by $$1/n$$ at each data point. (The data points are placed on the x-axis and the y-value incrases by $$1/n$$ at each.)\n\n\n#### The Statistical Functional\n\nThe bootstram method uses the EDF as an estimator for the CDF of the population. However, to apply the EDF as an estimator for our statistic $$M$$, we need to formulate M as a function of a CDF. Functions of CDFs are known as **statistical functionals**.\n\nExamples:\nIf a random variable $$X$$ has CDF $$F$$ and PDF $$p(x)$$, \n\n$$E(x) = \\int x dF(x) = \\int xp(x)dx,$$\n\nnoting that $$dF(x) = p(x)dx$$. \n\nWhen $$X$$ is discrete, we instead have\n\n$$E(X) = \\int xdF(x) = \\sum_x P(x)$$\n\nHow about Variance?\n\n$$\\sigma^2 = \\int x^2dF(x) - (\\int xdF(x))^2$$\n\nWhat we're doing is rewriting statistics as functions of their CDFs. Thus we can rewrite our statistic as $$M=g(F)$$ for population with CDF $$F$$.\n\n#### The Plug-In Principle\n\nCombining the EDF and the Statistical Functional gives us the Plug-In Principle.\n\nSimply plug in the EDF for the true CDF $$F$$, enabling us to evaluate $$M=g(F).$$\n\nFormally, we say that for a parameter of interest $$\\theta=g(F)$$, if $$\\hat{F}$$ is an estimator for $$F$$, the plug-in estimator for $$\\theta$$ is defined to be $$\\hat{\\theta} = g(\\hat{F})$$.\n\"\"\"\n\n# ╔═╡ 56116619-fd06-4af1-9e6c-d78b8f166542\nmd\"\"\"\n#### Plugging in the EDF for an unknown distribution\nSay we have some statistic defined as follows\n\n$$g(F) = \\int r(x)dF(x)$$.\n\nThe EDF for our data is \n\n$$\\hat{F} = \\frac{1}{n}\\sum_{i=1}^n1(x_i\\leq x)$$\n\nIts PMF is \n\n$$f(x) = \\frac{1}{n}, x\\in {\\{x_1, \\dots, x_n\\}}$$\n\nThus, the esimator for $$M$$ is \n\n$$\\hat{M} = g(\\hat{F}) = \\int r(x)d\\hat{F}(x).$$\n\nUsing our knowledge of the PDF (I guess), we can translate this into:\n\n$$\\hat{M} = \\frac{1}{n}\\sum_{i=1}^n r(x_i)$$.\n\nNote that if we let $$r(x)=x$$, we get the plug-in estimator for the population mean, which is just the sample mean.\n\n---\nOk, so we're almost there, but we still can't use this method to compute $$Var(\\hat{M})$$, I assume because we can't make the jump to discrete like we did above. So we're returning to simulation.\n\"\"\"\n\n# ╔═╡ 06fef3c2-21cf-41d4-b645-6d3dbb75450c\nmd\"\"\"\n\n#### Bootstrap Variance Estimation\n\nLet's use simulation to approximate the variance of our estimator. The original procedure has us draw a sample from $$F$$, $$B$$ times. We don't have $$F$$, we'll use the EDF instead. \n\nSteps for simulation:\n\n1. Draw a sample from the EDF.\n2. Obtain a plug-in statistic $$\\hat{M} = g(\\hat{F})$$\n3. Replicate the two procedures $$B$$ times.\n4. Get the variance in these $$B$$ statistics and use it to **approximate the true variance of the plug-in statistic**.\n\"\"\"\n\n# ╔═╡ a2a3d276-f33e-40e3-bf66-bfeeb0c99f95\nmd\"\"\"\n\n**Drawing from the EDF**\n\nBy defintion of the EDF, each point is equally weighted. Thus, sampling from the EDF is just drawing n observations with replacement, as introduced at the beginning.\n\"\"\"\n\n# ╔═╡ 58ac0581-bde8-4940-9020-a738f695a2fd\nmd\"\"\"\n\n## Assumptions, Applicability\n\nQuestions:\n\n1. Will the variance result obtained from this process, $$S^2$$, be a good estimator for $$Var(\\hat{M})$$?\n2. Will $$Var(\\hat{M})$$ be a good approximation of $$Var(M)$$?\n\n$$S^2 = \\frac{1}{B}\\sum_{j=1}^B(\\hat{M_j})^2 - (\\frac{1}{B}\\sum_{j=1}^B\\hat{M_j})^2 \\approx Var(\\hat{M};\\hat{F}) \\approx Var(M;F)$$.\n\nThese are two distinct types of error. The difference between $$S^2$$ and $$Var(\\hat{M})$$ is **simulation error** (the first approximate equality sign above). The difference between $$Var(\\hat{M})$$ and $$Var(M)$$ is **approximation error** (the second approximate equality sign above).\n\nSimulation error is improved with larger $$B$$.\n\nApproximation error will be small if the following conditions are met:\n1. The EDF must use enough data to approximate $$F$$ well.\n2. There are some smoothness conditions on the statistic g.\n\n1 is easy but 2 is concerning. The important thing is that variance does in fact meet these smoothness conditions so the bootstrap method can be used to estimate it.\n\n## Implementation\n\nLet's actually do the thing on the original problem.\n\"\"\"\n\n# ╔═╡ dd9e01ed-64c6-43cf-bde2-add77d470770\nbootmeans = [mean(sample(responses, 30; replace=true)) for x in 1:100000]\n\n# ╔═╡ 38c6b0b4-08a9-49ed-8268-1cdfd3861d2a\nbootmean = mean(bootmeans)\n\n# ╔═╡ fddd7c16-90b7-45dc-bcd0-8fbae1b64bb4\ntruemean = mean(pickups)\n\n# ╔═╡ cb88575d-719b-44d6-aebe-e071e5a90069\nbootmeanstd = sqrt(var(bootmeans))\n\n# ╔═╡ 57c0deb6-feb6-4e79-bc1d-a57a6e678eda\ntruestderror = std(pickups) / (30^(.5))\n\n# ╔═╡ 5b9bc0f6-c43d-4ea5-9ce6-2aa41d0ec74a\nmd\"\"\"\nAnd that's it, we're done. We see that we have calculated an estimate for the standard deviation. The bootstrap simulation gave us **$(round(bootmeanstd;digits=2))** and the true standerd error for a sample size of 30 was **$(round(truestderror;digits=2))**. \n\nBefore, we needed to assume that the standard error of the sample was a good estimate for the standard deviation of the population, but we had to assume our estimator followed a normal distribution and that it was easy to calculate the standard error for our statistic. The bootstrap method let us sidestep that, and we only needed the following assumtions: \n1. We need a smooth measure of error, formulated as a statistical functional (we used variance)\n2. We needed a good estimate of $$F$$\n\n**How can we reduce the error in our error estimate?**\n\nWith higher a higher sample size, (we used 30) we will have a better EDF and less approximation error. With more simulations, we will have less simulation error. This will give us a better estimate of the error.\n\"\"\"\n\n# ╔═╡ d9166184-8705-49c4-a7e9-0bba61adcaae\nmd\"\"\"\n\n### Oh and one more thing...\n\nDid we get a better mean? We had only one sample, which had a mean of $(mean(responses)). The bootstrap method provided us with $(round(bootmean;digits=2)), which is nearly identical. So we didn't use this to get a better mean, merely to to an estimate of the error in that measurement. Perhaps however, this would not be true with a different statistic. I don't know, this was just my own observation.\n\"\"\"\n\n# ╔═╡ e41995a5-1591-4404-b585-3c4e9aac49bf\nmd\"\"\"\n\n## Thoughts \n\n- How do we know if we have a good enough estimate of $$F$$?\n- How do we apply this to statistical simulation of computer architecture?\n  - Can we use this to get estimates on the error for our Markov models?\n- How do we use this in an online fashion?\n\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nStatistics = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\nStatsBase = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\n\n[compat]\nPlots = \"~1.27.6\"\nStatsBase = \"~0.33.16\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\njulia_version = \"1.7.1\"\nmanifest_format = \"2.0\"\n\n[[deps.Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"af92965fb30777147966f58acb05da51c5616b5f\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.3\"\n\n[[deps.ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[deps.Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[deps.Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[deps.Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[deps.Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"4b859a208b2397a7a623a03449e4636bdb17bcf2\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+1\"\n\n[[deps.ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"9950387274246d08af38f6eef8cb5480862a435f\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.14.0\"\n\n[[deps.ChangesOfVariables]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"bf98fa45a0a4cee295de98d4c1462be26345b9a1\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.2\"\n\n[[deps.ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"12fc73e5e0af68ad3137b886e3f7c1eacfca2640\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.17.1\"\n\n[[deps.ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[deps.Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[deps.Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"b153278a25dd42c65abbf4e62344f9d22e59191b\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.43.0\"\n\n[[deps.CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[deps.Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[deps.DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[deps.DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"3daef5523dd2e769dad2365274f760ff5f282c7d\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.11\"\n\n[[deps.DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[deps.Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[deps.DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[deps.Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[deps.DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[deps.Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[deps.EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[deps.Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"bad72f730e9e91c08d9427d5e8db95478a3c323d\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.4.8+0\"\n\n[[deps.FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[deps.FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[deps.FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[deps.Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[deps.Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[deps.FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[deps.FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[deps.GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"51d2dfe8e590fbd74e7a842cf6d13d8a2f45dc01\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.6+0\"\n\n[[deps.GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"RelocatableFolders\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"af237c08bda486b74318c8070adb96efa6952530\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.64.2\"\n\n[[deps.GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"cd6efcf9dc746b06709df14e462f0a3fe0786b1e\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.64.2+0\"\n\n[[deps.GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"83ea630384a13fc4f002b77690bc0afeb4255ac9\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.2\"\n\n[[deps.Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[deps.Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"a32d672ac2c967f3deb8a81d828afc739c838a06\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+2\"\n\n[[deps.Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[deps.Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[deps.HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"0fa77022fe4b511826b39c894c90daf5fce3334a\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.17\"\n\n[[deps.HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"129acf094d168394e80ee1dc4bc06ec835e510a3\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+1\"\n\n[[deps.IniFile]]\ngit-tree-sha1 = \"f550e6e32074c939295eb5ea6de31849ac2c9625\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.1\"\n\n[[deps.InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[deps.InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"91b5dcf362c5add98049e6c29ee756910b03051d\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.3\"\n\n[[deps.IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[deps.IterTools]]\ngit-tree-sha1 = \"fa6287a4469f5e048d763df38279ee729fbd44e5\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.4.0\"\n\n[[deps.IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[deps.JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"abc9885a7ca2052a736a600f7fa66209f96506e1\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.4.1\"\n\n[[deps.JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"3c837543ddb02250ef42f4738347454f95079d4e\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.3\"\n\n[[deps.JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b53380851c6e6664204efb2e62cd24fa5c47e4ba\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.2+0\"\n\n[[deps.LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[deps.LERC_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"bf36f528eec6634efc60d7ec062008f171071434\"\nuuid = \"88015f11-f218-50d7-93a8-a6af411a945d\"\nversion = \"3.0.0+1\"\n\n[[deps.LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[deps.LaTeXStrings]]\ngit-tree-sha1 = \"f2355693d6778a178ade15952b7ac47a4ff97996\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.3.0\"\n\n[[deps.Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"6f14549f7760d84b2db7a9b10b88cd3cc3025730\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.14\"\n\n[[deps.LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[deps.LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[deps.LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[deps.LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[deps.Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[deps.Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"0b4a5d71f3e5200a7dff793393e09dfc2d874290\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+1\"\n\n[[deps.Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[deps.Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[deps.Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[deps.Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[deps.Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[deps.Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"LERC_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"c9551dd26e31ab17b86cbd00c2ede019c08758eb\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+1\"\n\n[[deps.Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[deps.LinearAlgebra]]\ndeps = [\"Libdl\", \"libblastrampoline_jll\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[deps.LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"a970d55c2ad8084ca317a4658ba6ce99b7523571\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.12\"\n\n[[deps.Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[deps.MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[deps.Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[deps.MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[deps.MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[deps.Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[deps.Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[deps.Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[deps.MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[deps.NaNMath]]\ngit-tree-sha1 = \"737a5957f387b17e74d4ad2f440eb330b39a62c5\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"1.0.0\"\n\n[[deps.NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[deps.Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"887579a3eb005446d514ab7aeac5d1d027658b8f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+1\"\n\n[[deps.OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[deps.OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ab05aa4cc89736e95915b01e7279e61b1bfe33b8\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.14+0\"\n\n[[deps.Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[deps.OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[deps.PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[deps.Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"3b429f37de37f1fc603cc1de4a799dc7fbe4c0b6\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.3.0\"\n\n[[deps.Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[deps.Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[deps.PlotThemes]]\ndeps = [\"PlotUtils\", \"Statistics\"]\ngit-tree-sha1 = \"8162b2f8547bc23876edd0c5181b27702ae58dce\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"3.0.0\"\n\n[[deps.PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"bb16469fd5224100e422f0b027d26c5a25de1200\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.2.0\"\n\n[[deps.Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"Pkg\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\", \"UnicodeFun\", \"Unzip\"]\ngit-tree-sha1 = \"6f2dd1cf7a4bbf4f305a0d8750e351cb46dfbe80\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.27.6\"\n\n[[deps.Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"47e5f437cc0e7ef2ce8406ce1e7e24d44915f88d\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.3.0\"\n\n[[deps.Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[deps.Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"c6c0f690d0cc7caddb74cef7aa847b824a16b256\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+1\"\n\n[[deps.REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[deps.Random]]\ndeps = [\"SHA\", \"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[deps.RecipesBase]]\ngit-tree-sha1 = \"6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.2.1\"\n\n[[deps.RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"dc1e451e15d90347a7decc4221842a022b011714\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.5.2\"\n\n[[deps.Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[deps.RelocatableFolders]]\ndeps = [\"SHA\", \"Scratch\"]\ngit-tree-sha1 = \"cdbd3b1338c72ce29d9584fdbe9e9b70eeb5adca\"\nuuid = \"05181044-ff0b-4ac5-8273-598c1e38db00\"\nversion = \"0.1.3\"\n\n[[deps.Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.3.0\"\n\n[[deps.SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[deps.Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[deps.Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[deps.SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[deps.Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[deps.Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[deps.SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[deps.SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[deps.StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"cd56bf18ed715e8b09f06ef8c6b781e6cdc49911\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.4.4\"\n\n[[deps.Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[deps.StatsAPI]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"c82aaa13b44ea00134f8c9c89819477bd3986ecd\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.3.0\"\n\n[[deps.StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"8977b17906b0a1cc74ab2e3a05faa16cf08a8291\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.16\"\n\n[[deps.StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"57617b34fa34f91d536eb265df67c2d4519b8b98\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.5\"\n\n[[deps.TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[deps.TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[deps.Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"OrderedCollections\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"5ce79ce186cc678bbb5c5681ca3379d1ddae11a1\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.7.0\"\n\n[[deps.Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[deps.Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[deps.URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[deps.UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[deps.Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[deps.UnicodeFun]]\ndeps = [\"REPL\"]\ngit-tree-sha1 = \"53915e50200959667e78a92a418594b428dffddf\"\nuuid = \"1cfade01-22cf-5700-b092-accc4b62d6e1\"\nversion = \"0.4.1\"\n\n[[deps.Unzip]]\ngit-tree-sha1 = \"34db80951901073501137bdbc3d5a8e7bbd06670\"\nuuid = \"41fe7b60-77ed-43a1-b4f0-825fd5a5650d\"\nversion = \"0.1.2\"\n\n[[deps.Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[deps.Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4528479aa01ee1b3b4cd0e6faef0e04cf16466da\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.25.0+0\"\n\n[[deps.XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[deps.XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[deps.Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[deps.Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[deps.Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[deps.Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[deps.Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[deps.Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[deps.Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[deps.Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[deps.Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[deps.Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[deps.Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[deps.Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[deps.Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[deps.Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[deps.Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[deps.Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[deps.Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[deps.Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[deps.Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[deps.Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e45044cd873ded54b6a5bac0eb5c971392cf1927\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.2+0\"\n\n[[deps.libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[deps.libblastrampoline_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"OpenBLAS_jll\"]\nuuid = \"8e850b90-86db-534c-a0d3-1478176c7d93\"\n\n[[deps.libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[deps.libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[deps.libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"b910cb81ef3fe6e78bf6acee440bda86fd6ae00c\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+1\"\n\n[[deps.nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[deps.p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[deps.x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[deps.x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[deps.xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─0810c98f-2526-4ab4-9cd5-a662434e332d\n# ╟─a4283cac-c253-11ec-1d76-495287bbab72\n# ╟─c33fde47-ac17-4194-973b-cdb277907b60\n# ╟─e42b8dfb-1a75-448c-acc1-3255c87a0edf\n# ╟─0e14ff27-5d05-4367-947e-d97e96ddfa8e\n# ╠═fbbc6413-0afb-4531-8113-bb85afd2710d\n# ╟─0ed657f2-8f2b-4e8f-a375-9c8986448340\n# ╟─c30c49a1-2821-4ada-ab10-5cac70a99e87\n# ╟─520524ab-53ef-4edb-bc58-f6a86620a126\n# ╟─fda6b303-a082-4f44-8341-49446b100609\n# ╟─4453da4c-12fc-427d-9f9c-89476bf65541\n# ╟─f9153c34-d26b-4e54-847e-c3bae8cdb4df\n# ╟─d273d1b8-e66c-4461-ab55-b2a4fe578d0c\n# ╟─14b9e9b0-d67b-4376-80a5-cb0b76602174\n# ╟─ceb8a078-4c55-40e7-a1bf-41bc357eaf86\n# ╟─3c1f21fb-be76-446d-b27f-54119ee4835a\n# ╟─1e05bcbc-cf0a-47ba-a1be-cb2e9bafff78\n# ╟─56116619-fd06-4af1-9e6c-d78b8f166542\n# ╟─06fef3c2-21cf-41d4-b645-6d3dbb75450c\n# ╟─a2a3d276-f33e-40e3-bf66-bfeeb0c99f95\n# ╟─58ac0581-bde8-4940-9020-a738f695a2fd\n# ╠═dd9e01ed-64c6-43cf-bde2-add77d470770\n# ╠═38c6b0b4-08a9-49ed-8268-1cdfd3861d2a\n# ╠═fddd7c16-90b7-45dc-bcd0-8fbae1b64bb4\n# ╠═cb88575d-719b-44d6-aebe-e071e5a90069\n# ╠═57c0deb6-feb6-4e79-bc1d-a57a6e678eda\n# ╟─5b9bc0f6-c43d-4ea5-9ce6-2aa41d0ec74a\n# ╟─d9166184-8705-49c4-a7e9-0bba61adcaae\n# ╟─e41995a5-1591-4404-b585-3c4e9aac49bf\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "8c3f87406b752ef0d2b6d35fb31f4cd739e0972b", "size": 45675, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "stats/bootstrap01.jl", "max_stars_repo_name": "plavin/plavin.github.io", "max_stars_repo_head_hexsha": "4afaf1fbe1bd0b8c0cadf5da5618ac776dcb264c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stats/bootstrap01.jl", "max_issues_repo_name": "plavin/plavin.github.io", "max_issues_repo_head_hexsha": "4afaf1fbe1bd0b8c0cadf5da5618ac776dcb264c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stats/bootstrap01.jl", "max_forks_repo_name": "plavin/plavin.github.io", "max_forks_repo_head_hexsha": "4afaf1fbe1bd0b8c0cadf5da5618ac776dcb264c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3944223108, "max_line_length": 402, "alphanum_fraction": 0.7338368911, "num_tokens": 19052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.8991213745668094, "lm_q1q2_score": 0.7746274318914071}}
{"text": "function linsolve_pcg( Lmat::SparseMatrixCSC{Float64,Int64},\n                       prec::SparseMatrixCSC{Float64,Int64},\n                       b::Array{Float64,1};\n                       x0 = nothing,\n                       NiterMax = 1000, TOL=5.e-10,\n                       convmsg=false, showprogress=false )\n    #\n    Npoints = size(b)[1]\n    if x0 == nothing\n        x = zeros( Float64, Npoints )\n    else\n        x = copy(x0)\n    end\n    #\n    r = zeros( Float64, Npoints )\n    p = zeros( Float64, Npoints )\n    z = zeros( Float64, Npoints )\n    #\n    nabla2_x = Lmat*x\n    r = b - nabla2_x\n    z = apply_prec_ilu0( prec, r)\n    p = copy(z)\n\n    rsold = dot( r, z )\n\n    for iter = 1 : NiterMax\n        #\n        nabla2_x = Lmat*p\n        #\n        alpha = rsold/dot( p, nabla2_x )\n        #\n        x = x + alpha * p\n        r = r - alpha * nabla2_x\n        z = apply_prec_ilu0( prec, r)\n        #\n        rsnew = dot( z, r )\n        # deltars = rsold - rsnew\n        if showprogress\n            @printf(\"%8d %18.10e\\n\", iter, sqrt(abs(rsnew)))\n        end\n        #\n        if sqrt(abs(rsnew)) < TOL\n            if convmsg\n                @printf(\"#Convergence achieved in linsolve_pcg: %8d iterations.\\n\", iter)\n            end\n            break\n        end\n        #\n        p = z + (rsnew/rsold) * p\n        #\n        rsold = rsnew\n    end\n    #\n    return x\n    #\nend # of function\n", "meta": {"hexsha": "532d01de5a66b8d942c994335c162b17723944ed", "size": 1396, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LF/LF_common/linsolve_pcg.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "LF/LF_common/linsolve_pcg.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LF/LF_common/linsolve_pcg.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 24.4912280702, "max_line_length": 89, "alphanum_fraction": 0.4577363897, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7745564214898205}}
{"text": "\nfunction trinary_to_decimal(str)\n    dec = 0\n    for (i, ch) in enumerate(reverse(str))\n        d = Int(ch) - 48\n        if !(0 <= d <= 2)\n            return 0\n        end\n        dec += d * 3^(i - 1)\n    end\n    return dec\nend\n", "meta": {"hexsha": "de41c1adf718c17a6e1eda05df405f524a9cc940", "size": 229, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercism-solutions/julia/trinary/trinary.jl", "max_stars_repo_name": "twolodzko/Learning", "max_stars_repo_head_hexsha": "e5af2bdf6f65648c3c159343e14d63c157384009", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercism-solutions/julia/trinary/trinary.jl", "max_issues_repo_name": "twolodzko/Learning", "max_issues_repo_head_hexsha": "e5af2bdf6f65648c3c159343e14d63c157384009", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercism-solutions/julia/trinary/trinary.jl", "max_forks_repo_name": "twolodzko/Learning", "max_forks_repo_head_hexsha": "e5af2bdf6f65648c3c159343e14d63c157384009", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.6153846154, "max_line_length": 42, "alphanum_fraction": 0.4585152838, "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951607140232, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7745564149722847}}
{"text": "\n\nimport Base.randperm\n\n\n\"The path graph on n vertices\"\nfunction pathGraph(n::Int64)\n  x = append!(collect(1:(n-1)), collect(2:n))\n  y = append!(collect(2:n), collect(1:(n-1)))\n  w = ones(2 * (n - 1))\n  return sparse(x, y, w)\nend # pathGraph\n\n\n\"The complete graph\" \nfunction completeGraph(n::Int64)\n  return sparse(ones(n,n) - eye(n))\nend # completeGraph\n\n\n\"\"\"The simple ring on n vertices\"\"\"\nfunction ringGraph(n::Int64)\n    a = spdiagm(ones(n-1),1,n,n)\n    a[1,n] = 1\n    a = a + a'\nend\n\n\"\"\"A generalization of a ring graph.\nThe vertices are integers modulo n.\nTwo are connected if their difference is in gens.\nFor example, \n\n```\ngeneralizedRing(17, [1 5])\n```\n\"\"\"\nfunction generalizedRing(n::Int64, gens)\n    k = length(gens)\n    m = 2*n*k\n    ai = zeros(Int64,m)\n    aj = zeros(Int64,m)\n    ind = 1\n    for i in 0:(n-1)\n        for j in 1:k\n            ai[ind] = i\n            aj[ind] = mod(i+gens[j],n)\n            ind = ind + 1\n            ai[ind] = i\n            aj[ind] = mod(i-gens[j],n)\n            ind = ind + 1\n        end\n    end\n    return sparse(1+ai,1+aj,ones(m),n,n)\n    #return ai, aj\nend\n\n\"\"\"A random generalized ring graph of degree k.\nGens always contains 1, and the other k-1 edge types\nare chosen from an exponential distribution\"\"\"\nfunction randGenRing(n::Int64, k::Integer)\n    # if any of n, 2n, 3n etc. is in gens we will have self loops\n    gens = [0]\n    while 0 in (gens % n)\n        gens = [1; 1 + ceil(Integer,exp(rand(k-1)*log(n-1)))]\n    end\n\n    return generalizedRing(n, gens)\nend\n\n\n\"\"\"\n~~~\ngeneralizedNecklace{Tv, Ti}(A::SparseMatrixCSC{Tv, Ti}, H::SparseMatrixCSC, k::Int64)\n~~~\n\n Constructs a generalized necklace graph starting with two graphs A and H. The\nresulting new graph will be constructed by expanding each vertex in H to an\ninstance of A. k random edges will be generated between components. Thus, the\nresulting graph may have weighted edges.\n\"\"\"\n\nfunction generalizedNecklace{Tv, Ti}(A::SparseMatrixCSC{Tv, Ti}, H::SparseMatrixCSC, k::Int64)\n  a = findnz(A)\n  h = findnz(H)\n\n  # these are square matrices\n  n = A.n\n  m = H.n\n\n  newI = Ti[]\n  newJ = Ti[]\n  newW = Tv[]\n\n  # duplicate the vertices in A so that each vertex in H corresponds to a copy of A\n  for i in 1:m\n    newI = append!(newI, a[1] + n * (i - 1))\n    newJ = append!(newJ, a[2] + n * (i - 1))\n    newW = append!(newW, a[3])\n  end\n\n  # for each edge in H, add k random edges between two corresponding components\n  # multiedges will be concatenated to a single edge with higher cost\n  for i in 1:length(h[1])\n    u = h[1][i]\n    v = h[2][i]\n\n    if (u < v)\n      #component x is from 1 + (x - 1) * n to n + (x - 1) * n\n      for edgeToAdd in 1:k\n        newU = rand(1:n) + n * (u - 1)\n        newV = rand(1:n) + n * (v - 1)\n        append!(newI, [newU, newV])\n        append!(newJ, [newV, newU])\n        append!(newW, [1, 1])\n      end\n    end\n  end\n\n  return sparse(newI, newJ, newW)\nend # generalizedNecklace\n\n\n\"\"\"The d dimensional hypercube.  Has 2^d vertices\"\"\"\nfunction hyperCube(d::Int64)\n  a = sparse([0 1; 1 0])\n\n  for i = 1:(d-1)\n    k = 2^i\n    D = speye(k)\n    a = [a D; D a]\n  end\n\n  return a\nend # hyperCube\n\n\"\"\"The complete binary tree on n vertices\"\"\"\nfunction completeBinaryTree(n::Int64)\n\n  k = div(n-1,2)\n  a = sparse(collect(1:k),2*collect(1:k),1,n,n) + sparse(collect(1:k),2*collect(1:k)+1,1,n,n)\n\n  if 2*k+1 < n\n    a[n-1,n] = 1\n  end\n\n  a = a + a'\n\n  return a\nend # completeBinaryTree\n\n\"\"\" An n by n grid with random weights. User can specify the weighting scheme. \"\"\"\nfunction wGrid2(n::Int64; weightGen::Function=rand)\n    gr2 = sparse(grid2(n));\n\n    gr2.nzval = Float64[weightGen() for i in 1:nnz(gr2)]\n\n    # symmetrize\n    gr2 = tril(gr2) + tril(gr2)'\n\n    return gr2\nend\n\n\"\"\" An n^3 grid with random weights. User can specify the weighting scheme. \"\"\"\nfunction wGrid3(n::Int64; weightGen::Function=rand)\n    gr2 = grid2(n);\n    \n    a = kron(speye(n), gr2);\n    b = kron(gr2, speye(n));\n\n    gr3 = sparse(a + b);\n    gr3.nzval = Float64[weightGen() for i in 1:nnz(gr3)]\n\n    # symmetrize\n    gr3 = tril(gr3) + tril(gr3)'\n\n    return gr3\nend\n\n\"\"\"An n-by-m grid graph.  iostropy is the weighting on edges in one direction.\"\"\"\nfunction grid2(n::Int64, m::Int64; isotropy=1)\n  a = kron(speye(n),spdiagm(ones(m-1),1,m,m))\n  a = a + isotropy*kron(spdiagm(ones(n-1),1,n,n), speye(m))\n  a = a + a'\n  return a\nend # grid2\n\ngrid2(n::Int64) = grid2(n,n)\n\n\"\"\"Coordinates for plotting the vertices of the n-by-m grid graph\"\"\"\nfunction grid2coords(n::Int64, m::Int64)\n  x = kron(collect(1:n),ones(m))\n  y = kron(ones(n),collect(1:m))\n  return x, y\nend # grid2coords\n\ngrid2coords(n) = grid2coords(n, n)\n\n\n\"\"\"A random matching on n vertices\"\"\"\nfunction randMatching(n::Int64)\n\n  p = randperm(n)\n  n1 = convert(Int64,floor(n/2))\n  n2 = 2*n1\n  a = sparse(p[1:n1],p[(n1+1):n2],ones(n1),n,n)\n\n  a = a + a'\n\n  return a\n\nend # randMatching\n\n\"\"\"A sum of k random matchings on n vertices\"\"\"\nfunction randRegular(n::Int64, k::Int64)\n  a = randMatching(n)\n  for i in 2:k\n    a = a + randMatching(n)\n  end\n\n  return a\nend # randRegular\n\n\n\"\"\"Create a graph on n vertices.\nFor each vertex, give it k edges to randomly chosen prior\nvertices.\nThis is a variety of a preferential attachment graph.    \n\"\"\"\nfunction grownGraph(n::Int64, k::Int64)\n  a = spzeros(n,n)\n\n  for i = 1:k\n    a = a + sparse(2:n,ceil(Integer,collect(1:n-1).*rand(n-1)),1,n,n)\n  end\n\n  a = a + a'\nend # grownGraph\n\n# used in grownGraphD\nfunction randSet(n::Integer,k::Integer)\n    if n == k\n        return collect(1:n)\n    elseif n < k\n        error(\"n must be at least k\")\n    else\n\n        s = sort(ceil(Integer,n*rand(k)))\n        good = (minimum(s[2:end]-s[1:(end-1)]) > 0)\n        while good == false\n            s = sort(ceil(Integer,n*rand(k)))\n            good = (minimum(s[2:end]-s[1:(end-1)]) > 0)\n        end\n\n        return s\n\n    end\nend\n\n\"\"\"Like a grownGraph, but it forces the edges to all be distinct.\nIt starts out with a k+1 clique on the first k vertices\"\"\"\nfunction grownGraphD(n::Int64, k::Int64)\n    a = spzeros(n,n)\n\n    u = zeros(Int64, k*(n-k-1))\n    v = zeros(Int64, k*(n-k-1))\n\n    for i in (k+2):n\n        nb = randSet(i-1,k)\n        u[(i-k-2)*k + collect(1:k)] = i\n        v[(i-k-2)*k + collect(1:k)] = nb\n    end\n\n    a = sparse(u,v,1,n,n)\n\n    (ai,aj) = findnz(triu(ones(k+1,k+1),1))\n    a = a + sparse(ai,aj,1,n,n)\n    a = a + a'\n\nend # grownGraphD\n\n\"\"\"A preferential attachment graph in which each vertex has k edges to those\nthat come before.  These are chosen with probability p to be from a random vertex,\nand with probability 1-p to come from the endpoint of a random edge.\nIt begins with a k-clique on the first k+1 vertices.\"\"\"\nfunction prefAttach(n::Int64, k::Int64, p::Float64)\n    if n == (k+1)\n        return sparse(ones(Float64,n,n) - eye(Float64,n))\n    elseif n <= k\n        error(\"n must be more than k\")\n    else\n\n        u = zeros(Int64,n*k)\n        v = zeros(Int64,n*k)\n\n\n        # fill in the initial clique\n        # this will accidentally double every edge in the clique\n        # we clean it up at the end\n        ind = 1\n        for i in 1:(k+1)\n            for j in 1:(k+1)\n                if i != j\n                    u[ind] = i\n                    v[ind] = j\n                    ind += 1\n                end\n            end\n        end\n\n        s = zeros(Int64,k)\n        for i in (k+2):n\n            distinct = false\n            while distinct == false\n                for j in 1:k\n                    if rand(Float64) < p\n                        s[j] = rand(1:(i-1))\n                    else\n                        s[j] = v[rand(1:(k*(i-1)))]\n                    end\n                end\n                s = sort(s)\n                distinct = true\n                for ii in 1:(k-1)\n                    if s[ii] == s[ii+1]\n                        distinct = false\n                    end\n                end\n                # distinct = (minimum(s[2:end]-s[1:(end-1)]) > 0)\n\n            end\n\n            for j in 1:k\n                u[ind] = i\n                v[ind] = s[j]\n                ind += 1\n            end\n\n        end # for i\n\n        w = ones(Float64,n*k)\n\n        w[1:(k*(k+1))] = 1/2\n\n\n        a = sparse(u,v,w,n,n)\n        a = a + a'\n        return a\n    end\nend\n\n\n\"\"\"Randomly permutes the vertex indices\"\"\"\nfunction randperm(mat::AbstractMatrix)\n    perm = randperm(mat.n)\n    return mat[perm,perm]\nend\n\nrandperm(f::Expr) = randperm(eval(f))\n\n\n\"\"\"Generate a random graph on n vertices with m edges.\nThe actual number of edges will probably be smaller, as we sample\nwith replacement\"\"\"\nfunction ErdosRenyi(n::Integer, m::Integer)\n    ai = rand(1:n, m)\n    aj = rand(1:n, m)\n    ind = (ai .!= aj)\n    mat = sparse(ai[ind],aj[ind],1,n,n)\n    uniformWeight!(mat)\n    return mat\nend\n\n\"\"\"Generate an ER graph with average degree k,\nand then return the largest component.\nWill probably have fewer than n vertices.\nIf you want to add a tree to bring it back to n,\ntry ErdosRenyiClusterFix.\"\"\"\nfunction ErdosRenyiCluster(n::Integer, k::Integer)\n    m = ceil(Integer,n*k/2)\n    ai = rand(1:n, m)\n    aj = rand(1:n, m)\n    ind = (ai .!= aj)\n    mat = sparse(ai[ind],aj[ind],1,n,n)\n    mat = mat + mat'\n   \n    return biggestComp(mat)\nend\n\n\"\"\"Like an Erdos-Renyi cluster, but add back a tree so\nit has n vertices\"\"\"\nfunction ErdosRenyiClusterFix(n::Integer, k::Integer)\n    m1 = ErdosRenyiCluster(n, k)\n    n2 = n - size(m1)[1]\n    if (n2 > 0)\n        m2 = completeBinaryTree(n2)\n        return joinGraphs(m1,m2,1)\n    else\n        return m1\n    end\nend\n\n    \n    \n\"\"\"Generate a random graph with n vertices from one of our natural distributions\"\"\"\nfunction pureRandomGraph(n::Integer)\n   \n    gr = []\n    wt = []\n    \n    push!(gr,:(pathGraph($n)))\n    push!(wt,1)\n\n    push!(gr,:(ringGraph($n)))\n    push!(wt,3)\n\n    push!(gr,:(completeBinaryTree($n)))\n    push!(wt,3)\n\n    push!(gr,:(grownGraph($n,2)))\n    push!(wt,6)\n\n    push!(gr,:(grid2(ceil(Integer,sqrt($n)))[1:$n,1:$n]))\n    push!(wt,6)\n\n    push!(gr,:(randRegular($n,3)))\n    push!(wt,6)\n\n    push!(gr,:(ErdosRenyiClusterFix($n,2)))\n    push!(wt,6)\n\n    if n >= 4\n        push!(gr,:(randGenRing($n,4)))\n        push!(wt,6)\n    end\n\n    i = sampleByWeight(wt)\n\n    # make sure get a connected graph\n    its = 0\n    mat = eval(gr[i])\n\n    while (~isConnected(mat)) && (its < 100)\n        i = sampleByWeight(wt)\n        mat = eval(gr[i])\n        its += 1\n    end\n    if its == 100\n        error(\"Getting a disconnected graph from $(gr[i])\")\n    end\n\n    if (sum(diag(mat)) > 0)\n        error(\"nonzero diag from $(gr[i])\")\n    end\n\n    \n    return floatGraph(mat)\n      \nend\n\n\"\"\"sample an index with probability proportional to its weight given here\"\"\"\nfunction sampleByWeight(wt)\n    r = rand(1)*sum(wt)\n    find(cumsum(wt) .> r)[1]\nend\n\n\"\"\"A Chimera graph with some weights.  The weights just appear when graphs are combined.\nFor more interesting weights, use `wtedChimera`\"\"\"\nfunction semiWtedChimera(n::Integer)\n\n    if (n < 2)\n        gr = sparse([0.0])\n\n        return randperm(gr)\n    end\n\n    r = rand()^2\n    \n    if (n < 30) || (rand() < .2)\n\n        gr = pureRandomGraph(n)\n\n        return randperm(gr)\n    end\n\n    if (n < 200) \n        # just join disjoint copies of graphs\n\n        n1 = 10 + floor(Integer,(n-20)*rand())\n        n2 = n - n1\n        k = ceil(Integer,exp(rand()*log(min(n1,n2)/2)))\n\n        gr = joinGraphs(r*chimera(n1),chimera(n2),k)\n\n        return randperm(gr)\n    end\n\n    # split with probability .7\n\n    if (rand() < .7)\n        n1 = ceil(Integer,10*exp(rand()*log(n/20)))\n\n        n2 = n - n1\n        k = floor(Integer,1+exp(rand()*log(min(n1,n2)/2)))\n\n        gr = joinGraphs(r*chimera(n1),chimera(n2),k)\n\n        return randperm(gr)\n\n    else\n        n1 = floor(Integer,10*exp(rand()*log(n/100)))\n\n        n2 = floor(Integer, n / n1)\n\n        if (rand() < .5)\n\n            gr = productGraph(r*chimera(n1),chimera(n2))\n\n        else\n\n            k = floor(Integer,1+exp(rand()*log(min(n1,n2)/10)))\n            gr = generalizedNecklace(r*chimera(n1),chimera(n2),k)\n\n        end\n\n        n3 = n - size(gr)[1]\n        if (n3 > 0)\n            gr = joinGraphs(gr,chimera(n3),2)\n\n        end\n\n        return randperm(gr)\n        \n    end\nend\n\n\n\"\"\"Builds a chimeric graph on n vertices.\nThe components come from pureRandomGraph,\nconnected by joinGraphs, productGraph and generalizedNecklace\"\"\"\nfunction chimera(n::Integer)\n\n\n    gr = semiWtedChimera(n)\n    unweight!(gr)\n\n    return gr\n        \nend\n\n\"\"\"Builds the kth chimeric graph on n vertices.\nIt does this by resetting the random number generator seed.\nIt should captute the state of the generator before that and then\nreturn it, but it does not yet.\"\"\"\nfunction chimera(n::Integer, k::Integer)\n    srand(100*n+k)\n    g = chimera(n)\n    return g\nend\n\n\"\"\"Applies one of a number of random weighting schemes to the edges of the graph\"\"\"\nfunction randWeight(a)\n\n    if (rand() < .2)\n        return a\n    end\n    \n    n = a.n\n    (ai,aj) = findnz(a)\n    m = length(ai)\n    \n    # potentials or edge-based\n\n    if (rand() < .3)\n        w = rand(m)\n\n    else\n        v = randn(a.n)\n\n        # mult by matrix ?\n        if (rand() < .5)\n\n            invdeg = spdiagm(1./(a*ones(size(a)[1])))\n            if (rand() < .5)\n                for i in 1:10\n                    v = a * (invdeg * v)\n                    v = v - mean(v)\n                end\n            else\n                for i in 1:10\n                    v = v - a * (invdeg * v)\n                    v = v - mean(v)\n                end\n            end\n        end\n\n        w = abs(v[ai]-v[aj]) \n\n    end\n\n    # reciprocate or not?\n\n    w[w.==0] = 1\n    w[isnan(w)] = 1\n\n    if (rand() < .5)\n        w = 1./w\n    end\n\n    w = w / mean(w)\n\n    ar = sparse(ai,aj,w,n,n)\n    ar = ar + ar';\n    return ar\nend\n\n\"\"\"Builds the kth wted chimeric graph on n vertices.\nIt does this by resetting the random number generator seed.\nIt should captute the state of the generator before that and then\nreturn it, but it does not yet.\"\"\"\nfunction wtedChimera(n::Integer, k::Integer)\n    srand(100*n+k)\n    g = wtedChimera(n)\n    return g\nend\n\nfunction semiWtedChimera(n::Integer, k::Integer)\n    srand(100*n+k)\n    g = semiWtedChimera(n)\n    return g\nend\n\n\n\"\"\"Generate a chimera, and then apply a random weighting scheme\"\"\"\nfunction wtedChimera(n::Integer)\n    return randWeight(semiWtedChimera(n))\nend\n\n", "meta": {"hexsha": "70339cae98b80b7225810d941bde7686a1919118", "size": 14326, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/graphGenerators.jl", "max_stars_repo_name": "JuliaPackageMirrors/Laplacians.jl", "max_stars_repo_head_hexsha": "553ea964b95359462ef4b8b6b01383310ab88f41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/graphGenerators.jl", "max_issues_repo_name": "JuliaPackageMirrors/Laplacians.jl", "max_issues_repo_head_hexsha": "553ea964b95359462ef4b8b6b01383310ab88f41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/graphGenerators.jl", "max_forks_repo_name": "JuliaPackageMirrors/Laplacians.jl", "max_forks_repo_head_hexsha": "553ea964b95359462ef4b8b6b01383310ab88f41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4545454545, "max_line_length": 94, "alphanum_fraction": 0.5612871702, "num_tokens": 4506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8670357598021707, "lm_q1q2_score": 0.77453120700492}}
{"text": "using ..Galerkin:\n    galerkin_matrix,\n    galerkin_projection!,\n    galerkin_projection  # for Documenter only...\n\nusing LinearAlgebra:\n    cholesky!,\n    Cholesky,\n    ldiv!\n\n@doc raw\"\"\"\n    MinimiseL2Error <: AbstractApproxMethod\n\nApproximate a given function ``f(x)`` by minimisation of the ``L^2`` distance\nbetween ``f`` and its spline approximation ``g(x)``.\n\n# Extended help\n\nMinimises the ``L^2`` distance between the two functions:\n\n```math\n{\\left\\lVert f - g \\right\\rVert}^2 = \\left< f - g, f - g \\right>,\n```\n\nwhere\n\n```math\n\\left< u, v \\right> = ∫_a^b u(x) \\, v(x) \\, \\mathrm{d}x\n```\n\nis the inner product between two functions, and ``a`` and ``b`` are the\nboundaries of the prescribed B-spline basis.\nHere, ``g`` is the spline ``g(x) = ∑_{i = 1}^N c_i \\, b_i(x)``, and\n``\\{ b_i \\}_{i = 1}^N`` is a prescribed B-spline basis.\n\nOne can show that the optimal coefficients ``c_i`` minimising the ``L^2`` error\nare the solution to the linear system ``\\bm{M} \\bm{c} = \\bm{φ}``,\nwhere ``M_{ij} = \\left< b_i, b_j \\right>`` and ``φ_i = \\left< b_i, f \\right>``.\nThese two terms are respectively computed by [`galerkin_matrix`](@ref) and\n[`galerkin_projection`](@ref).\n\nThe integrals associated to ``\\bm{M}`` and ``\\bm{φ}`` are computed via\nGauss--Legendre quadrature.\nThe number of quadrature nodes is chosen as a function of the order ``k`` of the\nprescribed B-spline basis, ensuring that ``\\bm{M}`` is computed exactly (see\nalso [`galerkin_matrix`](@ref)).\nIn the particular case where ``f`` is a polynomial of degree ``k - 1``, this\nalso results in an exact computation of ``\\bm{φ}``.\nIn more general cases, as long as ``f`` is smooth enough, this is still expected\nto yield a very good approximation of the integral, and thus of the optimal coefficients ``c_i``.\n\n\"\"\"\nstruct MinimiseL2Error <: AbstractApproxMethod end\n\nfunction approximate(f, B::AbstractBSplineBasis, m::MinimiseL2Error)\n    T = typeof(f(first(knots(B))))\n    S = Spline{T}(undef, B)\n    M = galerkin_matrix(B)  # by default it's a BandedMatrix\n\n    # We annotate the return type to avoid inference issue in ArrayLayouts...\n    # https://github.com/JuliaMatrices/ArrayLayouts.jl/issues/66\n    Mfact = cholesky!(M) :: Cholesky{eltype(M), typeof(parent(M))}\n\n    data = (; M = Mfact)\n    A = SplineApproximation(m, S, data)\n    approximate!(f, A)\nend\n\nfunction _approximate!(f, A, m::MinimiseL2Error)\n    @assert method(A) === m\n    S = spline(A)\n    cs = coefficients(S)\n    galerkin_projection!(f, cs, basis(S))  # computes rhs onto cs\n    ldiv!(data(A).M, cs)  # now cs = M \\ rhs\n    A\nend\n", "meta": {"hexsha": "9c04e90230384196ae658f8bd871aa9e8fb391b9", "size": 2566, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SplineApproximations/minimiseL2.jl", "max_stars_repo_name": "jipolanco/BasisSplines", "max_stars_repo_head_hexsha": "16c689d6464adc9f467b451fe17df3221df67c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-11-03T21:11:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T19:09:34.000Z", "max_issues_repo_path": "src/SplineApproximations/minimiseL2.jl", "max_issues_repo_name": "jipolanco/BasisSplines", "max_issues_repo_head_hexsha": "16c689d6464adc9f467b451fe17df3221df67c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2020-06-29T07:46:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T16:25:06.000Z", "max_forks_repo_path": "src/SplineApproximations/minimiseL2.jl", "max_forks_repo_name": "jipolanco/BasisSplines", "max_forks_repo_head_hexsha": "16c689d6464adc9f467b451fe17df3221df67c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3246753247, "max_line_length": 97, "alphanum_fraction": 0.6675759938, "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7745255538498825}}
{"text": "module TSNE\n\nusing LinearAlgebra, ProgressBars\nusing Statistics: mean, mean!\nusing Printf: @printf, @sprintf\n\nexport tsne\n\n\"\"\"\n    Hbeta!(P::AbstractVector, D::AbstractVector, beta::Number)\n\nCompute the point perplexities `P` given its squared distances to the other\npoints `D` and the precsion of Gaussian distribution `beta`.\n\"\"\"\nfunction Hbeta!(P::AbstractVector, D::AbstractVector, beta::Number)\n    @inbounds P .= exp.(D .* -beta)\n    sumP = sum(P)\n    H = log(sumP) + beta * dot(D, P) / sumP\n    @inbounds P ./= sumP\n    return H\nend\n\n\"\"\"\n    x2p(D::AbstractMatrix{T}, tol::Number = 1e-5, perplexity::Number = 30.0)\n\nConvert `n×n` squared distances matrix `D` into `n×n` perplexities matrix `P`.\nPerforms a binary search to get P-values in such a way that each conditional\nGaussian has the same perplexity.\n\"\"\"\nfunction x2p(X::AbstractMatrix{T}, tol::Number = 1e-5,\n     perplexity::Number = 30.0; max_iter::Integer = 50,\n\t progress = true) where T <: Number\n    # Initializing some variables\n    n, d = size(X)\n    sum_X = sum(x->x^2, X, dims = 2)\n\tD = fill(zero(T), (n, n))\n\tBLAS.gemm!('N', 'T', -2.0, X, X, 0.0, D)\n    D .+= sum_X .+ sum_X'\n    P = fill(zero(T), n, n)\n    beta = fill(one(T), n)\n    logU = log(perplexity)\n    Di = fill(zero(T), n)\n    thisP = similar(Di)\n    # Loop over all datapoints\n\tif progress\n\t\tpb = ProgressBar(1:n)\n\t\tset_description(pb, \"Computing P-values...\")\n\telse\n\t\tpb = 1:n\n\tend\n    for i in pb\n        # Compute the Gaussian kernel and entropy for the current precision\n        betamin = 0.0\n        betamax = Inf\n        betai = 1.0\n        copyto!(thisP, view(P, i, :))\n        copyto!(Di, view(D, :, i))\n        Di[i] = prevfloat(Inf) \t\t # exclude D[i,i] from minimum(), yet make it finite and exp(-D[i,i])==0.0\n        minD = minimum(Di)     \t\t # distance of i-th point to its closest neighbour\n        @inbounds Di .-= minD  \t\t # entropy is invariant to offsetting Di, which helps to avoid overflow\n        H = Hbeta!(thisP, Di, betai)\n\n        Hdiff = H - logU\n        tries = 0\n\n        while abs(Hdiff) > tol && tries < max_iter\n            # If not, increase or decrease precision\n            if Hdiff > 0.0\n                betamin = betai\n                betai = isfinite(betamax) ? (betai + betamax) / 2 : betai * 2\n            else\n                betamax = betai\n                betai = (betai + betamin) / 2\n            end\n            # Recompute the values\n            H = Hbeta!(thisP, Di, betai)\n            Hdiff = H - logU\n            tries += 1\n        end\n        # Set the final row of P\n        @inbounds P[i, :] .= thisP\n        beta[i] = betai\n    end\n    # Return final P matrix\n    @printf(\"Mean σ: %f\\n\", mean(sqrt.(1.0 ./ beta)))\n    return P\nend\n\n\"\"\"\n    pca(X::AbstractMatrix, ndims::Integer = 50)\n\nRun PCA on `X` to reduce the number of its dimensions to `ndims`.\n\"\"\"\nfunction pca(X::AbstractMatrix, ndims::Integer = 50)\n    (n, d) = size(X)\n    (d <= ndims) && return X\n    Y = X .- mean(X, dims = 1)\n    C = Symmetric((Y' * Y) ./ (n - 1))\n    Ceig = eigen(C, (d - ndims + 1):d) # take eigvects for top ndims largest eigvals\n    return Y * reverse(Ceig.vectors, dims = 2)\nend\n\n\"\"\"\n    tsne(X::AbstractMatrix{T}, no_dims=2, initial_dims=50,\n     max_iter::Integer=1000, perplexity=30.0) where T<:Number\n\nApply t-SNE (t-Distributed Stochastic Neighbor Embedding) to `X`,\ni.e. embed its points into `ndims` dimensions preserving close neighbours.\n\nReturns the `point×ndims` matrix of calculated embedded coordinates.\n\nDifferent from original implementation: the default is not to use PCA for initialization.\n\n### Arguments\n\t* `no_dims` determines the number of dimensions in the final t-SNE embedding\n\t* `initial_dims` the number of dimensions of the dataset after apllying\n\tPCA to initialize the solution\n\t* `max_iter` how many iterations of t-SNE to perform\n\t* `perplexity` the number of \"effective neighbours\" of a datapoint,\n\tusually increases with the amount of points in the dataset. Typical\n\tvalues are between 5 and 50, the default is 30\n\t* `min_gain`, `eta`, `cheat_scale`, `initial_momentum`, `final_momentum`,\n\t`stop_cheat_iter`, `momentum_switch_iter` low level parameters of t-SNE optimization\n\"\"\"\nfunction tsne(X::AbstractMatrix{T}, no_dims = 2, initial_dims::Integer = 50,\n     max_iter::Integer = 1000, perplexity::Number = 30.0;\n\t initial_momentum::Number = 0.5, final_momentum = 0.8, eta::Integer = 500,\n\t min_gain::Number = 0.01, cheat_scale::Number = 4.0, progress = true,\n\t stop_cheat_iter::Integer = 100, momentum_switch_iter::Integer = 20) where T <: Number\n\n\tX = pca(X, initial_dims)\n    n, d = size(X)\n    Y = randn(n, no_dims)\t\t\t  # embedded final matrix\n    dY = fill(zero(T), n, no_dims)    # gradient vector\n    iY = fill(zero(T), n, no_dims)    # momentum vector\n    gains = fill(one(T), n, no_dims)  # how much momentum is affected by gradient\n    P = x2p(X, 1e-5, perplexity)\n    P .+= P'\t\t\t\t\t\t  # symmetriztion\n    P .*= cheat_scale / sum(P)\t\t  # early exaggeration + normalization\n    P .= max.(P, 1e-12)\n\n    # Pre-allocating some matrixes\n\tL = fill!(similar(P), zero(T))\t  # temp matrix for Student-t and gradient steps\n    Q = fill!(similar(P), zero(T))\t  # temp matrix with low dimensional probabilities\n\tsum_Y = fill(zero(T), n)\n\tY_mean = fill(zero(T), 1, no_dims)\n\terror = similar(P)\n\tlast_error = NaN\n\n    # Run iterations\n\tpb = progress ? ProgressBar(1:max_iter) : 1:max_iter\n    for iter in pb\n        # Compute pairwise affinities\n        sum!(x->x^2, sum_Y, Y)\n\t\t# L = 2YY'\n\t\tBLAS.gemm!('N', 'T', -2.0, Y, Y, 0.0, L)\n\t\t# Student-t Distribution\n\t\t# L = 1/(1 + sum_Y + sum_Y' + L)\n\t\t@inbounds for j in 1:size(L, 2)\n\t\t\t@inbounds for i in 1:size(L, 1)\n\t\t\t\tL[i, j] = 1 / (1 + sum_Y[j] + sum_Y[i] + L[i, j])\n\t\t\tend\n\t\tend\n\t\tfill!(sum_Y, 0.0)\n        inv_sum_Q = 1.0 / sum(L)\n\t\t@inbounds for j = 1:size(Q, 2)\n\t\t\tPj = view(P, :, j)\n\t\t\tQj = view(Q, :, j)\n\t\t\tLj = view(L, :, j)\n\t\t\t# Diagonal should be zero\n\t\t\tLj[j] = 0.0\n\t\t\t@inbounds for i = 1:size(Lj, 1)\n\t\t\t\tQj[i] = ifelse(Lj[i] > 1e-12, Lj[i] * inv_sum_Q, 1e-12)\n\t\t\t\t# Reusing L for gradient step\n\t\t\t\tLj[i] *= (Pj[i] - Qj[i])\n\t\t\t\t# Reusing sum_Y for column sums\n\t\t\t\tsum_Y[i] += Lj[i]\n\t\t\tend\n\t\tend\n\t\t# Compute gradient\n\t\t@inbounds for (i, ldiag) in enumerate(sum_Y)\n\t\t\tL[i, i] -= ldiag\n\t\tend\n\t\t# dY = -4LY\n\t\tBLAS.gemm!('N', 'N', -4.0, L, Y, 0.0, dY)\n        # Perform the update\n        momentum = iter <= momentum_switch_iter ? initial_momentum : final_momentum\n        @inbounds for i in eachindex(gains)\n            gains[i] = max(ifelse(((dY[i] > 0.) == (iY[i] > 0.)),\n                                gains[i] * 0.8,\n                                gains[i] + 0.2),\n                                min_gain)\n            iY[i] = momentum * iY[i] - eta * (gains[i] * dY[i])\n            Y[i] += iY[i]\n        end\n        @inbounds Y .-= mean!(Y_mean, Y)\n        # Compute current value of cost function\n        if iter % 50 == 0\n\t\t\tmap!((x, y)->x * log(x / y), error, P, Q)\n\t\t\tlast_error = sum(error)\n        end\n\n\t\tprogress && set_description(pb, string(@sprintf(\"Error: %.4f\", last_error)))\n\n        # Stop lying about P-values\n        if iter == stop_cheat_iter\n            P ./= 4.0\n        end\n    end\n    # Return solution\n    return Y\nend\n\nend  # module TSNE\n", "meta": {"hexsha": "314a2fe79ac480d7f3661ff2fdf1e6dde04286d4", "size": 7226, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tsne.jl", "max_stars_repo_name": "CombatOrpheus/t-sne-julia", "max_stars_repo_head_hexsha": "72939df6df0be4bf07dc1dbccba34c0bc2fad411", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-06-02T12:15:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-10T00:31:36.000Z", "max_issues_repo_path": "tsne.jl", "max_issues_repo_name": "CombatOrpheus/t-sne-julia", "max_issues_repo_head_hexsha": "72939df6df0be4bf07dc1dbccba34c0bc2fad411", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tsne.jl", "max_forks_repo_name": "CombatOrpheus/t-sne-julia", "max_forks_repo_head_hexsha": "72939df6df0be4bf07dc1dbccba34c0bc2fad411", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6093023256, "max_line_length": 107, "alphanum_fraction": 0.5949349571, "num_tokens": 2322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.774525553259977}}
{"text": "###################################\n## Example code\n## for Bayesian Gaussin Mixture Model\n\nusing PyPlot, PyCall\npush!(LOAD_PATH,\".\")\nimport GaussianMixtureModel\n\n\"\"\"\nVisualize data & estimation in 2D space.\n\"\"\"\nfunction visualize_2D(X::Matrix{Float64}, S::Matrix{Float64}, S_est::Matrix{Float64}, text)\n    cmp = get_cmap(\"jet\")\n\n    K1 = size(S, 1)\n    K2 = size(S_est, 1)\n    col1 = [pycall(cmp.o, PyAny, Int(round(val)))[1:3] for val in linspace(0,255,K1)]    \n    col2 = [pycall(cmp.o, PyAny, Int(round(val)))[1:3] for val in linspace(0,255,K2)]    \n\n    f, (ax1, ax2) = subplots(1,2,num=text)\n    f[:clf]()\n    f, (ax1, ax2) = subplots(1,2,num=text)\n\n    for k in 1 : K1\n        ax1[:scatter](X[1, S[k,:].==1], X[2, S[k,:].==1], color=col1[k])\n    end\n    ax1[:set_title](\"truth\")\n    \n    for k in 1 : K2\n        ax2[:scatter](X[1, S_est[k,:].==1], X[2, S_est[k,:].==1], color=col2[k])\n    end\n\n    ax2[:set_title](\"estimation\")\nend\n\n\"\"\"\nRun a test script for 2D data clustering.\n\"\"\"\nfunction test_2D()\n    ## set model\n    D = 2 # data dimension\n    K = 4 #  number of mixture components\n    alpha = 100.0 * ones(K)\n    beta = 0.1\n    m = zeros(D)\n    nu = D + 1.0\n    W = eye(D)\n    cmp = [GaussianMixtureModel.GW(beta, m, nu, W) for _ in 1 : K]\n    bgmm = GaussianMixtureModel.BGMM(D, K, alpha, cmp)\n    \n    ## generate data\n    N = 300\n    gmm = GaussianMixtureModel.sample_GMM(bgmm)\n    X, S = GaussianMixtureModel.sample_data(gmm, N)\n    \n    ## inference\n    max_iter = 100\n    tic()\n    S_est, post_bgmm, VB = GaussianMixtureModel.learn_VI(X, bgmm, max_iter)\n    #S_est, post_bgmm, VB = GaussianMixtureModel.learn_GS(X, bgmm, max_iter)\n    #S_est, post_bgmm, VB = GaussianMixtureModel.learn_CGS(X, bgmm, max_iter)\n    toc()\n\n    ## plot\n    visualize_2D(X, S, GaussianMixtureModel.winner_takes_all(S_est), \"2D plot\")\n\n    # VB check\n    figure(\"ELBO\")\n    clf()\n    plot(VB)\n    ylabel(\"ELBO\")\n    xlabel(\"iterations\")\n    show()\nend\n\ntest_2D()\n", "meta": {"hexsha": "72b264721126a70898bc1198a3bb6bcb9430d14f", "size": 1960, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/demo_GaussianMixtureModel.jl", "max_stars_repo_name": "triwave33/BayesBook", "max_stars_repo_head_hexsha": "86967e67381b01181ae3b3ad28d46011140dcc5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 158, "max_stars_repo_stars_event_min_datetime": "2017-10-19T13:33:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:59:21.000Z", "max_issues_repo_path": "src/demo_GaussianMixtureModel.jl", "max_issues_repo_name": "triwave33/BayesBook", "max_issues_repo_head_hexsha": "86967e67381b01181ae3b3ad28d46011140dcc5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2018-01-29T08:36:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-01T14:32:34.000Z", "max_forks_repo_path": "src/demo_GaussianMixtureModel.jl", "max_forks_repo_name": "triwave33/BayesBook", "max_forks_repo_head_hexsha": "86967e67381b01181ae3b3ad28d46011140dcc5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2017-10-20T00:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T20:34:22.000Z", "avg_line_length": 25.4545454545, "max_line_length": 91, "alphanum_fraction": 0.5918367347, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.7744764921796083}}
{"text": "# transfer_operators.jl : tranform quantities from fine to coarse grid and back\n\n# TransferKind\nabstract type TransferKind end\n\nstruct Injection <: TransferKind end\n\nstruct FullWeighting <: TransferKind end\n\nstruct HalfWeighting <: TransferKind end\n\nstruct Cubic <: TransferKind end\n\nBase.broadcastable(kind::TransferKind) = Ref(kind)\n\n# TransferOperator\nabstract type TransferOperator end\n\nstruct Restriction <: TransferOperator end\n\nstruct Interpolation <: TransferOperator end\n\n# GridTransferOperator\nstruct GridTransferOperator{K<:TransferKind,O<:TransferOperator}\n    kind::K\n    op::O\nend\n\n# stencil definitions\nstencil(op::GridTransferOperator{Injection,Restriction}) = @SVector [0,1.,0] \n\nstencil(op::GridTransferOperator{FullWeighting,Restriction}) = @SVector [1/4,1/2,1/4] \n\nstencil(op::GridTransferOperator{FullWeighting,Interpolation}) = @SVector [1/2,1,1/2]\n\nstencil(op::GridTransferOperator{Cubic,Interpolation}) = @SVector [-1/16,0,9/16,1,9/16,0,-1/16]\n\n# TODO: half weighting needs a 2d stencil...\n\n# restriction\nR₁(op::TransferKind,n::Int) = expand(GridTransferOperator(op,Restriction()),n) # 1d restriction operator\nR(op::TransferKind,n::Int) = R₁(op,n)\nR(op::TransferKind,n::Int...) = kron(R₁.(op,n)...)\nrestrict(u::Vector{T},op::TransferKind,n::Int...) where {T<:AbstractFloat} = R(op,n...)*u\n\n# interpolation\nP₁(op::TransferKind,n::Int) = expand(GridTransferOperator(op,Interpolation()),2n) # 1d interpolation operator\nP(op::TransferKind,n::Int) = P₁(op,n)\nP(op::TransferKind,n::Int...) = kron(P₁.(op,n)...)\ninterpolate(u::Vector{T},op::TransferKind,n::Int...) where {T<:AbstractFloat} = P(op,n...)*u\n\n# prolongation = interpolation\nprolongate(u,op) = interpolate(u,op)\n\n# expand\nfunction expand(op::GridTransferOperator{K,O} where {K,O},n)\n    st = stencil(op)\n    R = CartesianIndices((n-1,))\n    I1, Iend = extrema(R)\n    Is = Int[]\n    Js = Int[]\n    Vs = Float64[]\n    @inbounds for I in R\n        if iseven(I.I[1])\n            is,js,vs = _stencil2mat(st,I,I1,Iend)\n            push!(Is,is.>>1...)\n            push!(Js,js...)\n            push!(Vs,vs...)\n        end\n    end\n    operator2matrix(op,Is,Js,Vs)\nend\n\noperator2matrix(op::GridTransferOperator{K,Interpolation} where {K},Is,Js,Vs) = sparse(Js,Is,Vs)\noperator2matrix(op::GridTransferOperator{K,Restriction} where {K},Is,Js,Vs) = sparse(Is,Js,Vs)\n", "meta": {"hexsha": "63e9b6f15d8f144181c06af633fa2183f8503ade", "size": 2330, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/grid_transfer_operators.jl", "max_stars_repo_name": "PieterjanRobbe/SimpleMultigrid.jl", "max_stars_repo_head_hexsha": "eb8475709569c37f97c84a3605cccf43a3458352", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-03-08T16:56:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T09:07:40.000Z", "max_issues_repo_path": "src/grid_transfer_operators.jl", "max_issues_repo_name": "PieterjanRobbe/SimpleMultigrid.jl", "max_issues_repo_head_hexsha": "eb8475709569c37f97c84a3605cccf43a3458352", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-01-30T17:50:12.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-30T17:50:12.000Z", "max_forks_repo_path": "src/grid_transfer_operators.jl", "max_forks_repo_name": "PieterjanRobbe/SimpleMultigrid.jl", "max_forks_repo_head_hexsha": "eb8475709569c37f97c84a3605cccf43a3458352", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6578947368, "max_line_length": 109, "alphanum_fraction": 0.6978540773, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7744764914041545}}
{"text": "\"Implements Zeckendorf's theorem and outputs a Zeckendorf sequence {cᵪ | c ∈ {0, 1}}\"\nfunction zeckendorf{T <: Integer}(n::T)\n    @assert n >= 0 \"n is required to be larger or equal than zero\"\n\n    x, z = 2, 2\n    fib_cache = [1, 1]\n\n    # find fib(z-1) <= n <= fib(z)\n    while z <= n\n        x += 1\n        z = fib_cache[x-1] + fib_cache[x-2]\n        push!(fib_cache, z)\n    end\n\n    c = falses(x-1)\n\n    for i in (x-1):-1:1\n        if fib_cache[i] <= n\n            n -= fib_cache[i]\n            c[i] = true\n        end\n    end\n\n    return c\nend\n\n\"Generates a binary string from a boolean array in reverse order\"\nbinary_string{T <: AbstractArray{Bool}}(A::T) = join(map(Int, reverse(A)))\n", "meta": {"hexsha": "ca6d9994cc25f81d90ceb912e95d5b476d2f7733", "size": 690, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "zeckendorf/zeckendorf.jl", "max_stars_repo_name": "mooxmirror/julia-experiments", "max_stars_repo_head_hexsha": "b1af03c5b32f7131da38abc6aab5fb70ee29a96b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "zeckendorf/zeckendorf.jl", "max_issues_repo_name": "mooxmirror/julia-experiments", "max_issues_repo_head_hexsha": "b1af03c5b32f7131da38abc6aab5fb70ee29a96b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "zeckendorf/zeckendorf.jl", "max_forks_repo_name": "mooxmirror/julia-experiments", "max_forks_repo_head_hexsha": "b1af03c5b32f7131da38abc6aab5fb70ee29a96b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7931034483, "max_line_length": 85, "alphanum_fraction": 0.552173913, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191348157373, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7742660076307428}}
{"text": "# Poisson\n\n\"\"\"\npoipmf!(lambda, prob; left = 0, right = length(prob)-1+left)\npoipmf(lambda, right; left = 0)\n\nCompute the p.m.f. of Poisson distribution with mean lambda.\n`left` and `right` are the domain of Poisson distribution.\nThey should be choosen so that the total probability in the domain becomes 1.\nIn `poipmf!``, the p.m.f. is saved to the vector `prob`.\nThe right can be obtained from `rightbound`.\nThe retuen value is the normalizing constant so that the total sum of `prob` is 1, called the weight.\n`poipmf` returns a tuple of (weight, prob).\n\"\"\"\n\n@origin (prob => left) function poipmf!(lambda::Tv, prob::Vector{Tv};\n    left::Ti = 0, right::Ti = length(prob)-1+left) where {Tv, Ti}\n    @inbounds begin\n        log2piOver2::Tv = log(2*pi) / 2\n        mode::Ti = floor(Ti, lambda)\n        if mode >= 1\n            prob[mode] = exp(-lambda + mode * log(lambda) \n                - log2piOver2 - (mode + 1/2) * log(mode) + mode)\n        else\n            prob[mode] = exp(-lambda)\n        end\n        # down\n        for j = mode:-1:left+1\n            prob[j-1] = j / lambda * prob[j]\n        end\n        # up\n        for j = mode:right-1\n            prob[j+1] = lambda / (j+1) * prob[j]\n        end\n        # compute W\n        weight::Tv = 0\n        s::Ti = left\n        t::Ti = right\n        while s < t\n            if prob[s] <= prob[t]\n                weight += prob[s]\n                s += 1\n            else\n                weight += prob[t]\n                t -= 1\n            end\n        end\n        weight += prob[s]\n    end\nend\n\nfunction poipmf(lambda::Tv, right::Ti; left::Ti = 0) where {Tv, Ti}\n    prob = Vector{Tv}(undef, right-left+1)\n    weight = poipmf!(lambda, prob, left=left, right=right)\n    (weight, prob)\nend\n\n\"\"\"\ncpoipmf!(lambda, prob, cprob; left = 0, right = length(prob)-1+left)\ncpoipmf(lambda, right; left = 0)\n\nCompute the p.m.f. and complementary c.d.f. of Poisson distribution with mean lambda.\n`left` and `right` are the domain of Poisson distribution.\nThey should be choosen so that the total probability in the domain becomes 1.\nIn `cpoipmf!``, the p.m.f. and c.d.f. are stored to `prob` and `cprob`, respectively.\nThe right can be obtained from `rightbound`.\nThe retuen value is the normalizing constant so that the total sum of `prob` is 1, called the weight.\n`cpoipmf` returns a tuple of (weight, prob, cprob).\n\"\"\"\n\n@origin (prob => left, cprob => left) function cpoipmf!(lambda::Tv, prob::Vector{Tv}, cprob::Vector{Tv}; left::Ti = 0, right::Ti = length(prob)-1+left) where {Tv, Ti}\n    weight::Tv = poipmf!(lambda, prob, left=left, right=right)\n    @inbounds begin\n        cprob[right] = 0\n        for k = right-1:-1:left\n            cprob[k] = cprob[k+1] + prob[k+1]\n        end\n        weight\n    end\nend\n\nfunction cpoipmf(lambda::Tv, right::Ti; left::Ti = 0) where {Tv, Ti}\n    prob = Vector{Tv}(undef, right-left+1)\n    cprob = Vector{Tv}(undef, right-left+1)\n    weight = cpoipmf!(lambda, prob, cprob, left=left, right=right)\n    (weight, prob, cprob)\nend\n\n\"\"\"\nrightbound(::Type{Ti} = Int, lambda::Tv, q::Tv = Tv(1.0e-8))\n\nCompute the rightbound of Poisson distribution with mean lambda.\nThe rightbound finds a quantile so that the complementary c.d.f. becomes `q`.\n\"\"\"\n\nfunction rightbound(lambda::Tv, q::Tv = Tv(1.0e-8))::Int where {Tv}\n    rightbound(Int, lambda, q)\nend\n\nfunction rightbound(::Type{Ti}, lambda::Tv, q::Tv = Tv(1.0e-8))::Ti where {Tv, Ti}\n    z = cquantile(Normal(), q)\n    if lambda < 3.0\n        ll = exp(-lambda)\n        total = ll\n        right::Ti = 0\n        while true\n            right += 1\n            ll *= lambda / right\n            total += ll\n            if total + q >= 1.0\n                break\n            end\n        end\n        right\n    else\n        right = floor(Ti, (z + sqrt(4.0 * lambda - 1.0))^2 / 4.0 + 1.0)\n    end\nend\n", "meta": {"hexsha": "8a5da2bc9fe93cc026aa9ae4756c312be3cea15d", "size": 3813, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/_poisson.jl", "max_stars_repo_name": "JuliaReliab/NMarkov.jl", "max_stars_repo_head_hexsha": "cdaacdfe9801af84ea5f6a9cbb4108d77e2a8a0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/_poisson.jl", "max_issues_repo_name": "JuliaReliab/NMarkov.jl", "max_issues_repo_head_hexsha": "cdaacdfe9801af84ea5f6a9cbb4108d77e2a8a0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-07T06:12:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-07T06:13:58.000Z", "max_forks_repo_path": "src/_poisson.jl", "max_forks_repo_name": "JuliaReliab/NMarkov.jl", "max_forks_repo_head_hexsha": "cdaacdfe9801af84ea5f6a9cbb4108d77e2a8a0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0420168067, "max_line_length": 166, "alphanum_fraction": 0.5790715972, "num_tokens": 1178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.8558511414521922, "lm_q1q2_score": 0.7742461842809313}}
{"text": "\"\"\"\n    GaussianLikelihood(σ²)\n\nGaussian likelihood with `σ²` variance. This is to be used if we assume that the \nuncertainity associated with the data follows a Gaussian distribution.\n\n```math\n    p(y|f) = Normal(y | f, σ²)\n```\nOn calling, this would return a normal distribution with mean `f` and variance σ².\n\"\"\"\nstruct GaussianLikelihood{T<:Real}\n    σ²::T\nend\n\nGaussianLikelihood() = GaussianLikelihood(1e-6)\n\n@functor GaussianLikelihood\n\n(l::GaussianLikelihood)(f::Real) = Normal(f, sqrt(l.σ²))\n\n(l::GaussianLikelihood)(fs::AbstractVector{<:Real}) = MvNormal(fs, sqrt(l.σ²))\n\n\"\"\"\n    HeteroscedasticGaussianLikelihood(σ²)\n\nHeteroscedastic Gaussian likelihood. \nThis is a Gaussian likelihood whose mean and the log of whose variance are functions of the\nlatent process.\n\n```math\n    p(y|[f, g]) = Normal(y | f, exp(g))\n```\nOn calling, this would return a normal distribution with mean `f` and variance `exp(g)`.\n\"\"\"\nstruct HeteroscedasticGaussianLikelihood end\n\n(::HeteroscedasticGaussianLikelihood)(f::AbstractVector{<:Real}) = Normal(f[1], exp(f[2]))\n\n(::HeteroscedasticGaussianLikelihood)(fs::AbstractVector) = MvNormal(first.(fs), exp.(last.(fs)))\n", "meta": {"hexsha": "cfc8006f7f5810d69181ac34d06a64f7794caacf", "size": 1157, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/likelihoods/gaussian.jl", "max_stars_repo_name": "kaandocal/GPLikelihoods.jl", "max_stars_repo_head_hexsha": "ee43721a04885e305a9102d89d0660a12e2d4ec5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/likelihoods/gaussian.jl", "max_issues_repo_name": "kaandocal/GPLikelihoods.jl", "max_issues_repo_head_hexsha": "ee43721a04885e305a9102d89d0660a12e2d4ec5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/likelihoods/gaussian.jl", "max_forks_repo_name": "kaandocal/GPLikelihoods.jl", "max_forks_repo_head_hexsha": "ee43721a04885e305a9102d89d0660a12e2d4ec5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2195121951, "max_line_length": 97, "alphanum_fraction": 0.7277441659, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7742178213550613}}
{"text": "function getPost(testResult)\n\n    # Create a Dictionary containing the possible combinations:\n    P = Dict()\n\n    # Idea: solve by recursive calls of function,\n    # constantly updating the prior --> not implemented\n\n    deseaseFrequency = 0.001\n    truePositives    = 0.99\n    falsePositives   = 0.05\n\n    ### Priors:\n    P[\":(\"] = deseaseFrequency\n    P[\":)\"] = 1.0 - P[\":(\"]\n\n    ### Likelihoods\n    # Positive test restuls, given status:\n    P[\"+|:(\"] = truePositives\n    P[\"+|:)\"] = falsePositives\n    # Negative test restuls, given status:\n    P[\"-|:(\"] = 1.0 - truePositives\n    P[\"-|:)\"] = 1.0 - falsePositives\n\n    # Update for each new measurement:\n    for i in 1:length(testResult)\n        # Marginal Likelihoods:\n        P[\"+\"] = P[\"+|:(\"] * P[\":(\"] + P[\"+|:)\"] * P[\":)\"]\n        P[\"-\"] = P[\"-|:(\"] * P[\":(\"] + P[\"-|:)\"] * P[\":)\"]\n\n        ### Posteriors:\n        P[\":(|+\"] = P[\"+|:(\"] * P[\":(\"] / P[\"+\"]\n        P[\":(|-\"] = P[\"-|:(\"] * P[\":(\"] / P[\"-\"]\n        P[\":)|+\"] = 1.0 - P[\":(|+\"]\n        P[\":)|-\"] = 1.0 - P[\":(|-\"]\n\n        # Update priors to the posteriors:\n        P[\":(\"] = P[string(\":(|\",testResult[i])]\n        P[\":)\"] = 1.0 - P[\":(\"]\n    end\n\n    # Desired Posteriors are the new Priors:\n    # If no test result, then this also works, because the posterior = prior\n    posteriors = [P[\":(\"], P[\":)\"]]\n\n    return posteriors\nend\n\n# Enter the received results:\nmyResult = \"+-\"\n\n# Show the posteriors for each step when receiving test results,\n# including \"no result\" at the start:\nfor i in 1:length(myResult)+1\n    print(\"\\nAccumulated Results: \")\n    println(myResult[1:i-1])\n    println(\"[P(:(|T), P(:)|T)] = \",getPost(myResult[1:i-1]))\n    print(\"Sanity check: Sum(P) = \")\n    println(sum(getPost(myResult[1:i-1])))\nend\n", "meta": {"hexsha": "268a528690c641155dc0ce3643675fd12bb71ee0", "size": 1750, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "A3/A3-TaskA.jl", "max_stars_repo_name": "vis-florum/Applied-Bayesian-Data-Analysis", "max_stars_repo_head_hexsha": "6d460443269d920ea61859df9434938139245c2b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A3/A3-TaskA.jl", "max_issues_repo_name": "vis-florum/Applied-Bayesian-Data-Analysis", "max_issues_repo_head_hexsha": "6d460443269d920ea61859df9434938139245c2b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A3/A3-TaskA.jl", "max_forks_repo_name": "vis-florum/Applied-Bayesian-Data-Analysis", "max_forks_repo_head_hexsha": "6d460443269d920ea61859df9434938139245c2b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6885245902, "max_line_length": 76, "alphanum_fraction": 0.5131428571, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7742178207139357}}
{"text": "## --- Hafnium isotopes\n\n    # Calculate the initial Hf ratio and epsilon Hf at time t Ma\n    function eHf(Hf176_Hf177, Lu176_Hf177, t; eHfOnly::Bool=true)\n\n        # Lutetium decay constant (Soderlund et al., 2004\n        lambda = 1.867E-11\n\n        # Present-day CHUR composition (Bouvier et al., 2008)\n        CHUR_Hf176_Hf177 = 0.282785\n        CHUR_Lu176_Hf177 = 0.0336\n\n        # Calculate initial Hf ratio at time t\n        Hf176_Hf177_t = Hf176_Hf177 .- Lu176_Hf177.*(exp.(t .* 10^6*lambda) .- 1)\n\n        # Calculate CHUR Hf ratio at time t\n        CHUR_Hf176_Hf177_t = CHUR_Hf176_Hf177 .- CHUR_Lu176_Hf177.*(exp.(t .* 10^6*lambda) .- 1)\n\n        # Calculate corresponding epsilon Hf\n        eHf=(Hf176_Hf177_t ./ CHUR_Hf176_Hf177_t .- 1) .* 10^4\n\n        if eHfOnly\n            return eHf\n        else\n            return (eHf, Hf176_Hf177_t)\n        end\n    end\n    export eHf\n\n    function bin_bsr_eHf(x,Hf176_Hf177,Lu176_Hf177,age,min,max,nbins,x_sigma,Hf176_Hf177_sigma,Lu176_Hf177_sigma,age_sigma,nresamples)\n        data = hcat(x,Hf176_Hf177,Lu176_Hf177,age)\n        sigma = hcat(x_sigma,Hf176_Hf177_sigma,Lu176_Hf177_sigma,age_sigma)\n\n        means = Array{Float64}(undef,nbins,nresamples)\n        c = Array{Float64}(undef,nbins)\n        for i=1:nresamples\n            dbs = bsresample(data,sigma,length(age))\n            eHf_resampled = eHf(dbs[:,2], dbs[:,3], dbs[:,4])\n            (c,m,s) = binmeans(dbs[:,1], eHf_resampled, min, max, nbins)\n            means[:,i] = m\n        end\n\n        m = nanmean(means,dim=2)\n        el = m - nanpctile(means,2.5,dim=2)\n        eu = nanpctile(means,97.5,dim=2) - m\n\n        return (c, m, el, eu)\n    end\n    export bin_bsr_eHf\n\n\n## ---\n", "meta": {"hexsha": "04cf059eb8c7f59b0025bb6f78842d5765807bfe", "size": 1694, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utilities/Geochronology.jl", "max_stars_repo_name": "brenhinkeller/StatGeochem.jl", "max_stars_repo_head_hexsha": "43c6ee9d6ffd49c2aac78083c3ae4640663e23d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2018-11-08T20:09:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T01:19:41.000Z", "max_issues_repo_path": "src/utilities/Geochronology.jl", "max_issues_repo_name": "brenhinkeller/StatGeochem.jl", "max_issues_repo_head_hexsha": "43c6ee9d6ffd49c2aac78083c3ae4640663e23d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-05-04T05:34:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T06:23:42.000Z", "max_forks_repo_path": "src/utilities/Geochronology.jl", "max_forks_repo_name": "brenhinkeller/StatGeochem.jl", "max_forks_repo_head_hexsha": "43c6ee9d6ffd49c2aac78083c3ae4640663e23d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-10-03T17:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T20:57:44.000Z", "avg_line_length": 31.9622641509, "max_line_length": 134, "alphanum_fraction": 0.6092089728, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.774217813149627}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction _rhotheta{T<:AbstractFloat}(period::T, periastron::T, eccentricity::T,\n                                     semimajor_axis::T, inclination::T,\n                                     omega::T, omega2::T, epoch::T)\n    rho = theta = -one(period)\n    # See chapter 55.\n    n = 360.0/period\n    M = deg2rad(n*(epoch - periastron))\n    E = kepler_solver(M, eccentricity)\n    r  = semimajor_axis*(1.0 - eccentricity*cos(E))\n    nu = trueanom(E, eccentricity)\n    # Convert variables in radians.\n    omega2      = deg2rad(omega2)\n    inclination = deg2rad(inclination)\n    omega       = deg2rad(omega)\n    theta = omega + atan2(sin(nu + omega2)*cos(inclination), cos(nu + omega2))\n    rho   = r*cos(nu + omega2)/cos(theta - omega)\n    # Convert theta to degrees and for it to be in [0, 360) range.\n    theta = cirrange(rad2deg(theta))\n    return rho, theta\nend\n\n\"\"\"\n    rhotheta(period, periastron, eccentricity, semimajor_axis, inclination, omega, omega2, epoch) -> rho, theta\n\n### Purpose ###\n\nCalculate the separation and position angle of a binary star.\n\n### Explanation ###\n\nThis function will return the separation \\$\\\\rho\\$ and position angle\n\\$\\\\theta\\$ of a visual binary star derived from its orbital elements.  The\nalgorithms described in the following book will be used: Meeus J., 1992,\nAstronomische Algorithmen, Barth.  Compared to the examples given at page 400\nand no discrepancy found.\n\n### Arguments ###\n\n* `period`: period [year]\n* `periastro`: time of periastron passage [year]\n* `eccentricity`: eccentricity of the orbit\n* `semimajor_axis`: semi-major axis [arc second]\n* `inclination`: inclination angle [degree]\n* `omega`: node [degree]\n* `omega2`: longitude of periastron [degree]\n* `epoch`: epoch of observation [year]\n\nAll input parameters have to be scalars.\n\n### Output ###\n\nThe 2-tuple \\$(\\\\rho, \\\\theta)\\$, where\n\n* \\$\\\\rho\\$: separation [arc second]\n* \\$\\\\theta\\$: position angle [degree]\n\n### Example ###\n\nFind the position of Eta Coronae Borealis at the epoch 2016\n\n``` julia\nρ, θ = rhotheta(41.623, 1934.008, 0.2763, 0.907, 59.025, 23.717, 219.907, 2016)\n# => (0.6351167848228113,214.42513388052114)\n```\n\n### Notes ###\n\nCode of this function is based on IDL Astronomy User's Library.\n\"\"\"\nrhotheta(period::Real, periastron::Real, eccentricity::Real,\n         semimajor_axis::Real, inclination::Real,\n         omega::Real, omega2::Real, epoch::Real) =\n             _rhotheta(promote(float(period), float(periastron),\n                               float(eccentricity), float(semimajor_axis),\n                               float(inclination), float(omega),\n                               float(omega2), float(epoch))...)\n", "meta": {"hexsha": "d8bb4c764b74b7dd1cd48ebebf447bbc18ec338c", "size": 2752, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rhotheta.jl", "max_stars_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_stars_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rhotheta.jl", "max_issues_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_issues_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rhotheta.jl", "max_forks_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_forks_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4, "max_line_length": 111, "alphanum_fraction": 0.6424418605, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761565, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7742178125724921}}
{"text": "#############################################################################\n#############################################################################\n#\n# This file implements factorization \n#                                                                               \n#############################################################################\n#############################################################################\n\n\"\"\"\nFactors a polynomial over the field Z_p.\n\nReturns a vector of tuples of (irreducible polynomials (mod p), multiplicity) such that their product of the list (mod p) is f. Irreducibles are fixed points on the function factor.\n\"\"\"\nfunction factor(f::Polynomial, prime::Int)::Vector{Tuple{Polynomial,Int}}\n    #Cantor Zassenhaus factorization\n\n    f_modp = mod(f, prime)\n    degree(f_modp) ≤ 1 && return [(f_modp,1)]\n\n    # make f primitive\n    ff = prim_part(f_modp)(prime)      \n    # @show \"after prim:\", ff\n\n     # make f square-free\n    squares_poly = gcd(f, derivative(ff), prime) \n    ff = (ff ÷ squares_poly)(prime) \n    # @show \"after square free:\", ff\n\n    # make f monic\n    old_coeff = leading(ff).coeff\n    ff = (ff ÷ old_coeff)(prime)        \n    # @show \"after monic:\", ff\n\n    dds = dd_factor(ff, prime)\n\n    ret_val = Tuple{Polynomial,Int}[]\n\n    for (k,dd) in enumerate(dds)\n        sp = dd_split(dd, k, prime)\n        sp = map((p)->(p ÷ leading(p).coeff)(prime),sp) #makes the polynomials inside the list sp, monic\n        for mp in sp\n            push!(ret_val, (mp, multiplicity(f_modp,mp,prime)) )\n        end\n    end\n\n    #Append the leading coefficient as well\n    push!(ret_val, (leading(f_modp).coeff* one(Polynomial), 1) )\n\n    return ret_val\nend\n\n\"\"\"\nExpand a factorization.\n\"\"\"\nfunction expand_factorization(factorization::Vector{Tuple{Polynomial,Int}})::Polynomial \n    length(factorization) == 1 && return first(factorization[1])^last(factorization[1])\n    return *([first(tt)^last(tt) for tt in factorization]...)\nend\n\n\"\"\"\nCompute the number of times g divides f\n\"\"\"\nfunction multiplicity(f::Polynomial, g::Polynomial, prime::Int)::Int\n    degree(gcd(f, g, prime)) == 0 && return 0\n    return 1 + multiplicity((f ÷ g)(prime), g, prime)\nend\n\n\n\"\"\"\nDistinct degree factorization.\n\nGiven a square free polynomial `f` returns a list, `g` such that `g[k]` is a product of irreducible polynomials of degree `k` for `k` in 1,...,degree(f) ÷ 2, such that the product of the list (mod `prime`) is equal to `f` (mod `prime`).\n\"\"\"\nfunction dd_factor(f::Polynomial, prime::Int)::Array{Polynomial}\n    x = x_poly()\n    w = deepcopy(x)\n    g = Array{Polynomial}(undef,degree(f)) #Array of polynomials indexed by degree\n\n    #Looping over degrees\n    for k in 1:degree(f)\n        w = rem(pow_mod(w,prime,prime), f)(prime)\n        g[k] = gcd(w - x, f, prime) \n        f = (f ÷ g[k])(prime)\n    end\n\n\n    #edge case for final factor\n    f != one(Polynomial) && push!(g,f)\n    \n    return g\nend\n\n\"\"\"\nDistinct degree split.\n\nReturns a list of irreducible polynomials of degree `d` so that the product of that list (mod prime) is the polynomial `f`.\n\"\"\"\nfunction dd_split(f::Polynomial, d::Int, prime::Int)::Vector{Polynomial}\n    f = mod(f,prime)\n    degree(f) == d && return [f]\n    degree(f) == 0 && return []\n    w = rand(Polynomial, degree = d, monic = true)\n    w = mod(w,prime)\n    n_power = (prime^d-1) ÷ 2\n    g = gcd(pow_mod(w,n_power,prime) - one(Polynomial), f, prime)\n    ḡ = (f ÷ g)(prime) # g\\bar + [TAB]\n    return vcat(dd_split(g, d, prime), dd_split(ḡ, d, prime) )\nend", "meta": {"hexsha": "6438d69707967125cb92cb697b2770a73db61d8a", "size": 3533, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polynomial_factorization/factor.jl", "max_stars_repo_name": "s4642266/2504_2021_project1", "max_stars_repo_head_hexsha": "41948baa4fc9d069980697df0b5ba8b022978699", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polynomial_factorization/factor.jl", "max_issues_repo_name": "s4642266/2504_2021_project1", "max_issues_repo_head_hexsha": "41948baa4fc9d069980697df0b5ba8b022978699", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polynomial_factorization/factor.jl", "max_forks_repo_name": "s4642266/2504_2021_project1", "max_forks_repo_head_hexsha": "41948baa4fc9d069980697df0b5ba8b022978699", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2021-09-05T21:53:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T12:11:07.000Z", "avg_line_length": 32.712962963, "max_line_length": 236, "alphanum_fraction": 0.5655250495, "num_tokens": 949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7742178077646585}}
{"text": "function set_up_operator(p::Param)\n\n    # Variables\n    rmin        = p.rmin\n    rmax        = p.rmax\n    rnodes      = p.rnodes\n\n    thnodes     = p.thnodes\n\n    #Create position vectors\n    dr = (rmax - rmin)/(rnodes-1)\n    r = [rmin + (i-1)*dr for i in 1:rnodes]\n    \n    dth = 2*pi/(thnodes)\n    theta = [ (i-1)*dth for i in 1:thnodes]\n    \n    #Create Differential Operators \n    Dr  =   Diff_Operator_2D(1 ,1, [dr,dth] , [rnodes,thnodes]) \n    Drr =   Diff_Operator_2D(2 ,1, [dr,dth] , [rnodes,thnodes])\n\n    Dp  =  Diff_Operator_2D_Periodic(1 ,2, [dr,dth] , [rnodes,thnodes]) \n    Dpp =  Diff_Operator_2D_Periodic(2 ,2, [dr,dth] , [rnodes,thnodes])\n    \n    one_over_r2 = spzeros(rnodes*thnodes,rnodes*thnodes)\n\n    for i in 1:rnodes*thnodes\n        one_over_r2[i,i] = (1/r[1 + (i-1)%rnodes])^2\n    end\n\n    RHS_Opp = Drr + one_over_r2*Dpp + (0.25)*one_over_r2\n    #sparse(Drr + (0.25)*one_over_r2*I  + one_over_r2*Dpp);\n\n    av1 = zeros(rnodes*thnodes)\n    av2 = zeros(rnodes*thnodes)\n    \n    #Operator structure\n    return Opps(r, theta , av1 , av2  , Dr, Dp, RHS_Opp)\n    \nend", "meta": {"hexsha": "52d01700dc355a2df58d5042a94826ef62c6597b", "size": 1087, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sim_utils/setup_operators.jl", "max_stars_repo_name": "diogoribeiro98/Zilindroa.jl", "max_stars_repo_head_hexsha": "d0323ac88745eb282671c52936a543dd8de70093", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sim_utils/setup_operators.jl", "max_issues_repo_name": "diogoribeiro98/Zilindroa.jl", "max_issues_repo_head_hexsha": "d0323ac88745eb282671c52936a543dd8de70093", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sim_utils/setup_operators.jl", "max_forks_repo_name": "diogoribeiro98/Zilindroa.jl", "max_forks_repo_head_hexsha": "d0323ac88745eb282671c52936a543dd8de70093", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8717948718, "max_line_length": 72, "alphanum_fraction": 0.5915363385, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.7742178063544256}}
{"text": "using Plots, LaTeXStrings; pyplot()\n\nxGrid = 0:0.01:10\nuGrid = 0:0.01:1\nbusy = 0.8\n\nF(t)= t<=0 ? 0 : 1 - busy*exp(-(1-busy)t)\n\ninfimum(B) = isempty(B) ? Inf : minimum(B)\ninvF(u) = infimum(filter((x) -> (F(x) >= u),xGrid))\n\np1 = plot(xGrid,F.(xGrid), c=:blue, xlims=(-0.1,10), ylims=(0,1), \n\txlabel=L\"x\", ylabel=L\"F(x)\")\n\np2 = plot(uGrid,invF.(uGrid), c=:blue, xlims=(0,0.95), ylims=(0,maximum(xGrid)),\n\txlabel=L\"u\", ylabel=L\"F^{-1}(u)\")\n    \nplot(p1, p2, legend=:none, size=(800, 400))", "meta": {"hexsha": "96690ec6d71b974bf40f49194d6122bf51272b6a", "size": 485, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/inverseCDF.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "3_chapter/inverseCDF.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "3_chapter/inverseCDF.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 26.9444444444, "max_line_length": 80, "alphanum_fraction": 0.5793814433, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693659780477, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7742013255507596}}
{"text": "\"\"\"\n    sphere_mesh(ne, radius::FT, wtype::AbstractSphereWarp) where {FT<:AbstractFloat}\n\nGenerates a sphere mesh of a given `radius`, warp type and number of elements along each side\nof a cubed surface. The sphere mesh is generated by applying the warping function to a cube panel mesh.\n\"\"\"\nfunction sphere_mesh(ne, radius::FT, wtype::AbstractSphereWarp) where {FT<:AbstractFloat}\n    mesh = cube_panel_mesh(ne, FT)\n    mesh.coordinates .-= FT(0.5)\n    mesh.coordinates .*= (FT(2) * radius)\n    for i = 1:mesh.nverts\n        mesh.coordinates[i, :] .= cubed_sphere_warp(wtype, mesh.coordinates[i, :]...)\n    end\n    return mesh\nend\n\n\"\"\"\n    cubed_sphere_warp(::EquiangularSphereWarp, a, b, c)\n\nGiven points `(a, b, c)` on the surface of a cube, warp the points out to a\nspherical shell of radius `R` based on the equiangular gnomonic grid proposed by\n[Ronchi1996]\n\nReturns a tuple of (x1, x2, x3), where x1, x2, x3 are the corresponding coordinates on a sphere\nof radius R.\n\nThe \"Cubed Sphere\": A New Method for the Solution of Partial Differential Equations in Spherical Geometry\nC. RONCHI,*,1 R. IACONO,* AND P. S. PAOLUCCI†\nJOURNAL OF COMPUTATIONAL PHYSICS 124, 93–114 (1996)\nhttps://github.com/CliMA/ClimateMachine.jl/blob/master/src/Numerics/Mesh/Topologies.jl\n\"\"\"\nfunction cubed_sphere_warp(wtype::EquiangularSphereWarp, a, b, c)\n    R = max(abs(a), abs(b), abs(c))\n    function f(sR, ξ, η)\n        X, Y = tan(π * ξ / 4), tan(π * η / 4)\n        ζ1 = sR / sqrt(X^2 + Y^2 + 1)\n        ζ2, ζ3 = X * ζ1, Y * ζ1\n        ζ1, ζ2, ζ3\n    end\n\n    fdim = argmax(abs.((a, b, c)))\n    if fdim == 1\n        if a < 0\n            # (-R, *, *) : formulas for Face I from Ronchi, Iacono, Paolucci (1996)\n            #              but for us face IV of the developed net of the cube\n            x1, x2, x3 = f(-R, b / a, c / a)\n        elseif a > 0\n            # ( R, *, *) : formulas for Face III from Ronchi, Iacono, Paolucci (1996)\n            #              but for us face II of the developed net of the cube\n            x1, x2, x3 = f(R, b / a, c / a)\n        end\n    elseif fdim == 2\n        if b < 0\n            # ( *,-R, *) : formulas for Face II from Ronchi, Iacono, Paolucci (1996)\n            #              but for us face V of the developed net of the cube\n            x2, x1, x3 = f(-R, a / b, c / b)\n        elseif b > 0\n            # ( *, R, *) : formulas for Face IV from Ronchi, Iacono, Paolucci (1996)\n            #              but for us face III of the developed net of the cube\n            x2, x1, x3 = f(R, a / b, c / b)\n        end\n    elseif fdim == 3\n        if c > 0\n            # ( *, *, R) : formulas for Face V from Ronchi, Iacono, Paolucci (1996)\n            #              but for us face VI of the developed net of the cube\n            x3, x2, x1 = f(R, b / c, a / c)\n        elseif c < 0\n            # ( *, *,-R) : formulas for Face VI from Ronchi, Iacono, Paolucci (1996)\n            #              but for us face I of the developed net of the cube\n            x3, x2, x1 = f(-R, b / c, a / c)\n        end\n    end\n\n    return x1, x2, x3\nend\n\n\"\"\"\n    cubed_sphere_warp(::EquidistantSphereWarp, a, b, c)\n\nReturns a tuple of (x1, x2, x3), where x1, x2, x3 are the corresponding coordinates on a sphere\nof radius R.\n\nhttps://github.com/CliMA/ClimateMachine.jl/blob/master/src/Numerics/Mesh/Topologies.jl\n\"\"\"\nfunction cubed_sphere_warp(wtype::EquidistantSphereWarp, a, b, c)\n    R = max(abs(a), abs(b), abs(c))\n    r = hypot(a, b, c)\n\n    return R * a / r, R * b / r, R * c / r\nend\n\n\"\"\"\n    cube_panel_mesh(ne)\n\nThis function builds a cube panel mesh with a resolution of `ne` elements along each edge.\n\n               v8 (xs,xe,xe)          v7 (xe,xe,xe)\n                 o--------e11---------o       \n                /|                   /|                                   \n               / |                  / |       \n              /  |                 /  |       \n            e12  e8               e10 e7       \n            /    |               /    |       \n           /     |            v6/     |       \n       v5 o--------e9----------o      |       \n          |    v4o------e3-----|------o v3 (xe,xe,xs)\n          |     /   o------->  |     / \n          |    /   /           |    / \n          e5  e4  /           e6   e2 \n          |  /   /             |  / \n          | /   /              | / \n          |/   o               |/ \n          o--------e1----------o   \n         v1                    v2 \n       (xs,xs,xs)               (xe,xs,xs)\n\n       panel 1 => 1 4 3 2\n       panel 2 => 2 3 7 6\n       panel 3 => 3 4 8 7\n       panel 4 => 1 5 8 4\n       panel 5 => 1 2 6 5\n       panel 6 => 5 6 7 8\n\n       edge  1 => 1 2 \n       edge  2 => 2 3\n       edge  3 => 3 4\n       edge  4 => 4 1\n       edge  5 => 1 5\n       edge  6 => 2 6\n       edge  7 => 3 7\n       edge  8 => 4 8\n       edge  9 => 5 6\n       edge 10 => 6 7\n       edge 11 => 7 8\n       edge 12 => 8 5\n\n\n            v8 +---e11---+ v7\n               | ^       |\n               | |       |\n              e8 ^   3   e7 \n               | |       |\n            v4 | o--<-o  | v3      v7        v8\n  v8 +---e8----+---e3----+----e7---+---e11---+\n     | ^       | o-->->  | o-->--> | ^       | \n     | |       | |       | |       | |       |\n   e12 ^  4   e4 ^  1   e2 ^  2   e10^  6   e12\n     | |       | |       | |       | |       |\n     | o-<-<-o | o       | o       | o<-<--o |\n     +---e5----+---e1----+----e6---+----e9---+\n    v5       v1| o-->--o | v2      v6        v5\n               |       | |\n              e5    5  | e6\n               |       ↓ |\n               |         |\n               +---e9----+\n              v5         v6\n\"\"\"\nfunction cube_panel_mesh(ne::I, ::Type{FT}) where {FT<:AbstractFloat,I<:Integer}\n    xs, xe = FT(0), FT(1)\n    nverts = (ne + 1)^3 - (ne - 1)^3\n    nfaces = 12 * ne + 6 * (2 * ne * (ne - 1))\n    nelems = 6 * ne * ne\n    nbndry = 0\n\n    nx = ne + 1\n\n    nfaces_edg = 12 * ne\n\n    emat = reshape(1:nelems, ne, ne, 6)\n    ndmat = zeros(I, ne + 1, ne + 1)\n\n    panel_verts = [\n        1 2 3 1 1 5\n        4 3 4 5 2 6\n        3 7 8 8 6 7\n        2 6 7 4 5 8\n    ]\n    panel_edges = [\n        4 2 3 5 1 9\n        3 7 8 12 6 10\n        2 10 11 8 9 11\n        1 6 7 4 5 12\n    ]\n    panel_edges_rev = Bool.([\n        1 0 0 0 0 0\n        1 0 0 1 0 0\n        1 1 1 1 1 0\n        1 1 1 0 1 0\n    ])\n    # node coordinates\n    xc = range(xs, xe; step = FT(1 / ne)) # [xs, xs+Δ, xs+2Δ, ..., xe]\n    xci = view(xc, 2:ne)                   # [xs+Δ, xs+2Δ, ..., xe-Δ]\n    xcir = view(xc, ne:-1:2)                # reverse(xci)\n    sc = ones(FT, ne - 1) * xs              # [xs, ...., xs]\n    ec = ones(FT, ne - 1) * xe              # [xe, ...., xe]\n    # where Δ = (xe-xs)/ne\n    sc2 = ones(FT, (ne - 1) * (ne - 1)) * xs\n    ec2 = ones(FT, (ne - 1) * (ne - 1)) * xe\n\n    xci12 = repeat(xci, outer = ne - 1)\n    xci1r2 = repeat(xcir, outer = ne - 1)\n    xci21 = repeat(xci, inner = ne - 1)\n\n    edge_nodes = reshape(1:((ne-1)*12), ne - 1, 12) .+ 8\n    # coordinates\n    coordinates = vcat(\n        hcat(\n            [xs, xe, xe, xs, xs, xe, xe, xs], # x1,\n            [xs, xs, xe, xe, xs, xs, xe, xe], # x2,\n            [xs, xs, xs, xs, xe, xe, xe, xe], # x3 vertex coordinates\n        ),\n        vcat(\n            hcat(xci, sc, sc), # edge 1\n            hcat(ec, xci, sc), # edge 2\n            hcat(xcir, ec, sc), # edge 3\n            hcat(sc, xcir, sc), # edge 4\n            hcat(sc, sc, xci), # edge 5\n            hcat(ec, sc, xci), # edge 6\n            hcat(ec, ec, xci), # edge 7\n            hcat(sc, ec, xci), # edge 8\n            hcat(xci, sc, ec), # edge 9\n            hcat(ec, xci, ec), # edge 10\n            hcat(xcir, ec, ec), # edge 11\n            hcat(sc, xcir, ec), # edge 12\n        ),\n        hcat(xci21, xci12, sc2), # panel 1\n        hcat(ec2, xci12, xci21), # panel 2\n        hcat(xci1r2, ec2, xci21), # panel 3\n        hcat(sc2, xci21, xci12), # panel 4\n        hcat(xci12, sc2, xci21), # panel 5\n        hcat(xci12, xci21, ec2), # panel 6\n    )\n    face_interior = reshape(1:((ne-1)*(ne-1)), ne - 1, ne - 1)\n\n    nfc1i = (nx - 2) * (nx - 1) # panels with normals along local first direction\n    nfc2i = (nx - 1) * (nx - 2) # panels with normals along local second direction\n    nfci = nfc1i + nfc2i\n    fci1 = reshape(1:nfc1i, nx - 2, nx - 1)\n    fci2 = reshape(1:nfc2i, nx - 1, nx - 2)\n\n    fcmat1 = zeros(I, nx, nx - 1) # face numbering\n    fcmat2 = zeros(I, nx - 1, nx) # for each panel\n\n    edge_faces = reshape(1:(12*ne), ne, 12)\n\n    face_verts = zeros(I, nfaces, 2)\n    face_neighbors = zeros(I, nfaces, 5)\n    face_boundary = Vector{I}(zeros(nfaces)) # all interior nodes (no boundaries)\n    elem_verts = zeros(I, nelems, 4)\n    elem_faces = zeros(I, nelems, 4)\n\n\n    for sfc = 1:6\n        ndmat[1, 1],\n        ndmat[ne+1, 1],  # panel vertices\n        ndmat[ne+1, ne+1],\n        ndmat[1, ne+1] = panel_verts[:, sfc]\n\n        ndmat[2:ne, 1] .=\n            panel_edges_rev[1, sfc] ? reverse(edge_nodes[:, panel_edges[1, sfc]]) :\n            edge_nodes[:, panel_edges[1, sfc]]  # panel edges\n\n        ndmat[end, 2:ne] .=\n            panel_edges_rev[2, sfc] ? reverse(edge_nodes[:, panel_edges[2, sfc]]) :\n            edge_nodes[:, panel_edges[2, sfc]]\n\n        ndmat[ne:-1:2, end] .=\n            panel_edges_rev[3, sfc] ? reverse(edge_nodes[:, panel_edges[3, sfc]]) :\n            edge_nodes[:, panel_edges[3, sfc]]\n\n        ndmat[1, ne:-1:2, end] .=\n            panel_edges_rev[4, sfc] ? reverse(edge_nodes[:, panel_edges[4, sfc]]) :\n            edge_nodes[:, panel_edges[4, sfc]]\n\n        offset = 8 + 12 * (ne - 1) + (sfc - 1) * (ne - 1) * (ne - 1) # interior\n        ndmat[2:ne, 2:ne] .= face_interior .+ offset\n\n        fcmat1[1, end:-1:1] .=\n            panel_edges_rev[4, sfc] ? reverse(edge_faces[:, panel_edges[4, sfc]]) :\n            edge_faces[:, panel_edges[4, sfc]]\n\n        fcmat1[end, :] .=\n            panel_edges_rev[2, sfc] ? reverse(edge_faces[:, panel_edges[2, sfc]]) :\n            edge_faces[:, panel_edges[2, sfc]]\n\n        fcmat2[:, 1] .=\n            panel_edges_rev[1, sfc] ? reverse(edge_faces[:, panel_edges[1, sfc]]) :\n            edge_faces[:, panel_edges[1, sfc]]\n\n        fcmat2[end:-1:1, end] .=\n            panel_edges_rev[3, sfc] ? reverse(edge_faces[:, panel_edges[3, sfc]]) :\n            edge_faces[:, panel_edges[3, sfc]]\n\n        off = ne * 12 + (sfc - 1) * nfci\n\n        fcmat1[2:(end-1), :] .= fci1 .+ off\n        fcmat2[:, 2:(end-1)] .= fci2 .+ (off + nfc1i)\n\n        face_verts[fcmat1[:], 1] .= ndmat[:, 1:ne][:] # face nodes\n        face_verts[fcmat1[:], 2] .= ndmat[:, 2:(ne+1)][:]\n        face_verts[fcmat2[:], 1] .= ndmat[1:ne, :][:]\n        face_verts[fcmat2[:], 2] .= ndmat[2:(ne+1), :][:]\n\n        if sfc == 1\n            bdy1 = emat[:, 1:1, 5]'\n            bdy2 = emat[ne:-1:1, 1:1, 3]'\n            bdy3 = emat[1:1, 1:ne, 4]'\n            bdy4 = emat[:, 1:1, 2]\n        elseif sfc == 2\n            bdy1 = emat[ne:ne, :, 5]\n            bdy2 = emat[1:1, :, 3]\n            bdy3 = emat[:, ne:ne, 1]\n            bdy4 = emat[ne:ne, :, 6]'\n        elseif sfc == 3\n            bdy1 = emat[ne:ne, :, 2]\n            bdy2 = emat[:, ne:ne, 4]'\n            bdy3 = emat[ne:ne, ne:-1:1, 1]'\n            bdy4 = emat[ne:-1:1, ne:ne, 6]\n        elseif sfc == 4\n            bdy1 = emat[:, 1:1, 1]'\n            bdy2 = emat[1:1, :, 6]\n            bdy3 = emat[1:1, :, 5]'\n            bdy4 = emat[ne:ne, :, 3]'\n        elseif sfc == 5\n            bdy1 = emat[:, 1:1, 4]'\n            bdy2 = emat[1:1, :, 2]\n            bdy3 = emat[1:1, :, 1]'\n            bdy4 = emat[:, 1:1, 6]\n        else # sfc == 6\n            bdy1 = emat[ne:ne, :, 4]\n            bdy2 = emat[:, ne:ne, 2]'\n            bdy3 = emat[:, ne:ne, 5]\n            bdy4 = emat[ne:-1:1, ne:ne, 3]\n        end\n        face_neighbors[fcmat1[:], 1] .= vcat(bdy1, emat[:, :, sfc])[:]\n        face_neighbors[fcmat1[:], 3] .= vcat(emat[:, :, sfc], bdy2)[:]\n        face_neighbors[fcmat2[:], 1] .= hcat(bdy3, emat[:, :, sfc])[:]\n        face_neighbors[fcmat2[:], 3] .= hcat(emat[:, :, sfc], bdy4)[:]\n\n        elem_verts[emat[:, :, sfc][:], :] .= hcat(\n            ndmat[1:ne, 1:ne][:], # node numbers (local node 1)\n            ndmat[2:(ne+1), 1:ne][:], # for each element (local node 2)\n            ndmat[2:(ne+1), 2:(ne+1)][:], #(local node 3)\n            ndmat[1:ne, 2:(ne+1)][:], # (local node 4)\n        )\n\n        elem_faces[emat[:, :, sfc][:], :] .= hcat(\n            fcmat2[:, 1:(nx-1)][:], # (local face 1)\n            fcmat1[2:nx, :][:],   # each element (local face 2)\n            fcmat2[:, 2:nx][:], # (local face 3)\n            fcmat1[1:(nx-1), :][:], # face numbers for (local face 4)\n        )\n    end\n\n    ref_fc_verts = [\n        1 2 3 4\n        2 3 4 1\n    ]\n\n    for fc = 1:nfaces\n        elems = (face_neighbors[fc, 1], face_neighbors[fc, 3])\n        for e = 1:2\n            el = elems[e]\n            localface = findfirst(elem_faces[el, :] .== fc)\n            face_neighbors[fc, 2+(e-1)*2] = localface\n        end\n        # setting up relative orientation\n        or1 =\n            elem_verts[elems[1], ref_fc_verts[:, face_neighbors[fc, 2]]] ==\n            face_verts[fc, :] ? 1 : -1\n        or2 =\n            elem_verts[elems[2], ref_fc_verts[:, face_neighbors[fc, 4]]] ==\n            face_verts[fc, :] ? 1 : -1\n        face_neighbors[fc, 5] = or1 * or2\n    end\n\n    boundary_tags = sort(unique(face_boundary))\n    face_boundary_tags = sort(face_boundary)\n    face_boundary = sortperm(face_boundary)\n\n    face_boundary_offset = I[1, length(face_boundary)+1]\n\n    boundary_tag_names = (:interior,)\n\n    # add unique vertex iterator information\n    vtconn = map(i -> zeros(I, i), zeros(I, nverts))\n\n    for el = 1:nelems\n        for lv = 1:4\n            vt = elem_verts[el, lv]\n            push!(vtconn[vt], el, lv)\n        end\n    end\n    unique_verts = I[]\n    uverts_conn = I[]\n    uverts_offset = I.([1])\n    for vt = 1:nverts\n        lconn = length(vtconn[vt])\n        if lconn > 0\n            push!(unique_verts, vt)\n            push!(uverts_conn, vtconn[vt]...)\n            push!(uverts_offset, uverts_offset[end] + lconn)\n        end\n    end\n\n    return Mesh2D(\n        nverts,\n        nfaces,\n        nelems,\n        nbndry,\n        coordinates,\n        unique_verts,\n        uverts_conn,\n        uverts_offset,\n        face_verts,\n        face_neighbors,\n        face_boundary,\n        boundary_tags,\n        boundary_tag_names,\n        face_boundary_offset,\n        elem_verts,\n        elem_faces,\n    )\nend\n\nfunction unfold_cube_panel_to_plane(\n    x::FTA1D,\n    y::FTA1D,\n    z::FTA1D,\n    panelno::Int,\n) where {FT<:AbstractFloat,FTA1D<:AbstractVector{FT}}\n    @assert 1 ≤ panelno ≤ 6\n    n = length(x)\n    xx = similar(x)\n    yy = similar(x)\n\n    if panelno == 1\n        xx = x\n        yy = y\n    elseif panelno == 2\n        xx = z .+ FT(1)\n        yy = y\n    elseif panelno == 3\n        xx = x\n        yy = z .+ FT(1)\n    elseif panelno == 4\n        xx = -z\n        yy = y\n    elseif panelno == 5\n        xx = x\n        yy = -z\n    elseif panelno == 6\n        xx = 3 .- x\n        yy = y\n    end\n\n    return xx, yy\nend\n", "meta": {"hexsha": "72348f2fa18c5afeeefd9ea7fd881a53cad14dc9", "size": 15079, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sphere_mesh.jl", "max_stars_repo_name": "CliMA/GCMMesh", "max_stars_repo_head_hexsha": "cb953b54592cb2d4954e7b67de4bb29783b4737e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-15T11:31:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T07:10:37.000Z", "max_issues_repo_path": "src/sphere_mesh.jl", "max_issues_repo_name": "CliMA/GCMMesh", "max_issues_repo_head_hexsha": "cb953b54592cb2d4954e7b67de4bb29783b4737e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-11-04T20:59:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-17T00:32:21.000Z", "max_forks_repo_path": "src/sphere_mesh.jl", "max_forks_repo_name": "CliMA/GCMMesh", "max_forks_repo_head_hexsha": "cb953b54592cb2d4954e7b67de4bb29783b4737e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7804347826, "max_line_length": 105, "alphanum_fraction": 0.4591816433, "num_tokens": 5357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535723, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7742013222579108}}
{"text": "\n\"\"\"\n    K, Cl = h2synthesize(P::ExtendedStateSpace, γ = nothing)\n\nSynthesize H₂-optimal controller K and calculate the closed-loop transfer function from `w` to `z`.\nRef: Cha. 14.5 in Robust and Optimal Control.\n\nIf `γ = nothing`, use the formulas for H₂ in Ch 14.5. If γ is a large value, the H∞ formulas are used. As γ → ∞, these two are equivalent. The h∞ formulas do a coordinate transfromation that handles slightly more general systems so if you run into an error, it might be worth trying setting γ to something large, e.g., 1000.\n\"\"\"\nfunction h2synthesize(P::ExtendedStateSpace, γ = nothing)\n\n    if γ === nothing\n        X2, Y2, F2, L2 = _solvematrixequations2(P)\n        Â2 = P.A + P.B2*F2 + L2*P.C2\n        K = ss(Â2, -L2, F2, 0)\n        return K, lft(ss(P), K)\n    end\n    \n    P̄, Ltrans12, Rtrans12, Ltrans21, Rtrans21 = _transformp2pbar(P)\n    X2, Y2, F2, L2 = _solvematrixequations(P̄, γ)\n\n    _checkfeasibility(\n        X2,\n        Y2,\n        γ,\n        1e-3,\n        10;\n        verbose = false,\n    ) || throw(DomainError(\"Not feasible for γ = $γ\"))\n\n\n    K = _synthesizecontroller(\n        P̄,\n        X2,\n        Y2,\n        F2,\n        L2,\n        γ,\n        Ltrans12,\n        Rtrans12,\n        Ltrans21,\n        Rtrans21,\n    )\n    Cl = lft(ss(P), K)\n    K, Cl\nend\n\nfunction _solvematrixequations2(P::ExtendedStateSpace)\n\n    A = P.A\n    B1 = P.B1\n    B2 = P.B2\n    C1 = P.C1\n    C2 = P.C2\n    D11 = P.D11\n    D12 = P.D12\n    D21 = P.D21\n    D22 = P.D22\n\n    P1 = size(C1, 1)\n    P2 = size(C2, 1)\n    M1 = size(B1, 2)\n    M2 = size(B2, 2)\n\n    HX = [A zeros(size(A)); -C1'*C1 -A'] - [B2; -C1'*D12] * [D12'*C1 B2']\n    HY = [A' zeros(size(A)); -B1*B1' -A] - [C2'; -B1*D21'] * [D21*B1' C2]\n\n    # Solve matrix equations\n    X2 = _solvehamiltonianare(HX)\n    Y2 = _solvehamiltonianare(HY)\n\n    F2 = -(B2'X2 + D12'C1)\n\n    L2 = -(B1 * D21' + Y2 * C2')\n\n    return X2, Y2, F2, L2\nend", "meta": {"hexsha": "aa2e408ded6d8d2096197f54bc33945f9811a14c", "size": 1905, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/h2_design.jl", "max_stars_repo_name": "ven-k/RobustAndOptimalControl.jl", "max_stars_repo_head_hexsha": "fdc9ec8e13a95be903357c51359216511d5e03ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2021-04-19T04:51:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T07:56:20.000Z", "max_issues_repo_path": "src/h2_design.jl", "max_issues_repo_name": "ven-k/RobustAndOptimalControl.jl", "max_issues_repo_head_hexsha": "fdc9ec8e13a95be903357c51359216511d5e03ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-05-15T09:05:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T19:25:31.000Z", "max_forks_repo_path": "src/h2_design.jl", "max_forks_repo_name": "ven-k/RobustAndOptimalControl.jl", "max_forks_repo_head_hexsha": "fdc9ec8e13a95be903357c51359216511d5e03ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-09-07T06:22:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T08:15:01.000Z", "avg_line_length": 24.7402597403, "max_line_length": 324, "alphanum_fraction": 0.5585301837, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693659780477, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7742013212876194}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.6\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ f29303e2-1d66-11eb-3313-f335871e9674\nusing Pkg, DrWatson\n\n# ╔═╡ f2935b8a-1d66-11eb-02e8-3dacec840928\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing LinearAlgebra, StatsBase, DataFrames\nend\n\n# ╔═╡ 7877839e-1d66-11eb-0a3c-5953d222ccbc\nmd\"## Listing 1.8\"\n\n# ╔═╡ f293d704-1d66-11eb-36d8-4bb2f8dff940\nmd\"##### Transition probability matrix.\"\n\n# ╔═╡ f2a01cf8-1d66-11eb-3573-d91ed64fb7bc\nP = [0.5 0.4 0.1;\n     0.3 0.2 0.5;\n     0.5 0.3 0.2];\n\n# ╔═╡ f2a0c444-1d66-11eb-0f37-99e69755fe8f\nmd\"##### First way.\"\n\n# ╔═╡ f2a67846-1d66-11eb-022c-6f0a51c33a42\npiProb1 = (P^100)[1,:]\n\n# ╔═╡ f2b43238-1d66-11eb-3713-c5c8f2d4af76\nmd\"##### Second way.\"\n\n# ╔═╡ f2b4d63e-1d66-11eb-3d9f-65ba9b1ac506\nbegin\n\tA = vcat((P' - I)[1:2,:],ones(3)')\n\tb = [0 0 1]'\n\tpiProb2 = (A\\b)[:, 1]\nend\n\n# ╔═╡ f2c17bc8-1d66-11eb-0569-9b84c6b33cca\nmd\"##### Third way.\"\n\n# ╔═╡ f2c2e8fa-1d66-11eb-3421-3d76cd8c9a73\nbegin\n\teigVecs = eigvecs(copy(P'))\n\thighestVec = eigVecs[:,findmax(abs.(eigvals(P)))[2]]\n\tpiProb3 = Array{Float64}(highestVec)/norm(highestVec,1)\nend\n\n# ╔═╡ f2d180ba-1d66-11eb-216b-e3e640811323\nmd\"##### Fourth way.\"\n\n# ╔═╡ f2da9662-1d66-11eb-1f95-3da69865d370\nbegin\nnumInState = zeros(Int,3)\n\tstate = 1\n\tN = 10^6\n\tfor t in 1:N\n\t\tnumInState[state] += 1\n\t\tglobal state = sample(1:3,weights(P[state,:]))\n\tend\n\tpiProb4 = numInState/N\nend\n\n# ╔═╡ f2dbd9d2-1d66-11eb-12b9-af2d7f1f73da\nDataFrame(:piProb1 => piProb1, :piProb2 => piProb2, :piProb3 => piProb3, :piProb4 => piProb4)\n\n# ╔═╡ f2e37750-1d66-11eb-3f4e-e7b249fb2052\nmd\"## End of listing 1.8\"\n\n# ╔═╡ Cell order:\n# ╟─7877839e-1d66-11eb-0a3c-5953d222ccbc\n# ╠═f29303e2-1d66-11eb-3313-f335871e9674\n# ╠═f2935b8a-1d66-11eb-02e8-3dacec840928\n# ╟─f293d704-1d66-11eb-36d8-4bb2f8dff940\n# ╠═f2a01cf8-1d66-11eb-3573-d91ed64fb7bc\n# ╟─f2a0c444-1d66-11eb-0f37-99e69755fe8f\n# ╠═f2a67846-1d66-11eb-022c-6f0a51c33a42\n# ╟─f2b43238-1d66-11eb-3713-c5c8f2d4af76\n# ╠═f2b4d63e-1d66-11eb-3d9f-65ba9b1ac506\n# ╟─f2c17bc8-1d66-11eb-0569-9b84c6b33cca\n# ╠═f2c2e8fa-1d66-11eb-3421-3d76cd8c9a73\n# ╟─f2d180ba-1d66-11eb-216b-e3e640811323\n# ╠═f2da9662-1d66-11eb-1f95-3da69865d370\n# ╠═f2dbd9d2-1d66-11eb-12b9-af2d7f1f73da\n# ╟─f2e37750-1d66-11eb-3f4e-e7b249fb2052\n", "meta": {"hexsha": "3d763bfe97516c60955d64c2e85e70c2bbf8ce9d", "size": 2248, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/01/listing1.08.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/01/listing1.08.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/01/listing1.08.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 24.9777777778, "max_line_length": 93, "alphanum_fraction": 0.7037366548, "num_tokens": 1288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8652240877899776, "lm_q1q2_score": 0.7741933995726533}}
{"text": "\"\"\"\n    stumpff!(beta, x, Gz)\n\nCalculates the values of the c-functions and returns the first four g-functions, which will be used to solve Kepler's equation.\n\n```math\nc_{0} = \\\\cos(\\\\sqrt{z}) \\\\hspace{3cm} c_{1} = \\\\frac{\\\\sin(\\\\sqrt{z})}{\\\\sqrt{z}} \\\\hspace{3cm} c_{n} = \\\\frac{1}{n!} - z c_{n-2} \\\\hspace{3cm} G_{n} = x^n c_{n}\n```\n\n# Args\n\n* `beta`: a coefficient calculated in function `KeplerFlow`, which equals to `µ`/`a` (where `a` is the semi-major axis and `mu` the standard gravitational parameters of the bodies involved).\n* `x`: current estimation of the universal anomaly to solve the universal Kepler equation.\n* `Gz`: array of four elements, in which the first four g-functions will be saved.\n\"\"\"\nfunction stumpff!(beta, x, Gz)\n    z = beta * (x^2)\n    \n    # C-funtzioak\n    if (z < 0)\n        Gz[1] = cosh(sqrt(abs(z)))\n        Gz[2] = sinh(sqrt(abs(z)))/sqrt(abs(z))\n    else\n        Gz[1] = cos(sqrt(z))\n        Gz[2] = sin(sqrt(z))/sqrt(z)\n    end\n    \n    for i = 3:4\n        Gz[i] = (1.0 - Gz[i-2])/z\n    end\n    \n    # G-funtzioak\n    for i = 2:4\n        Gz[i] *= x^(i-1)\n    end\nend\n\n\n\n\n\"\"\"\n    keplerSolve!(x0, beta, eta0, zeta0, r0, Gz, dt, trace)\n\nSolves the universal equation of kepler. In this equation, G_{2} and G_{3} are the third and fourth g-functions, respectively.\n\n```math\nr_{0}X + \\\\eta_{0}G_{2} + \\\\zeta_{0}G_{3} - dt = 0\n```\n\n# Args\n\n* `x0`: initial estimation of the universal anomaly.\n* `beta`: a coefficient calculated in function `KeplerFlow`, which equals to `µ`/`a` (where `a` is the semi-major axis and `mu` the standard gravitational parameters of the bodies involved).\n* `eta0`: a coefficient that is needed to solve, calculated in function `KeplerFlow`.\n* `zeta0`: another quantity of the equation it is needed to solve \n* `r0`: initial distance between the two bodies.\n* `Gz`: array of the first four g-functions. Instead of defining it on each execution of the function, the same array is used in the whole simulation. That is why it's passed as an argument.\n* `dt`: time-step of the Kepler-flow.\n* `trace`: boolean value that shows information of the execution if true.\n\n# Returns\n\n* `r`: distance between the two bodies after time-step dt.\n\"\"\"\nfunction keplerSolve!(x0, beta, eta0, zeta0, r0, Gz, dt, trace)\n    \n    xi = x0 # initial estimation\n    r = r0\n    imax = 50\n    error = Inf\n    tol = sqrt(eps(typeof(xi))) / 100\n    \n    for i in 1:imax\n        \n        stumpff!(beta, xi, Gz)\n        fx = r0*xi + eta0*Gz[3] + zeta0*Gz[4] - dt\n        r = r0 + eta0*Gz[2] + zeta0*Gz[3]\n        eta = eta0*Gz[1] + zeta0*Gz[2]\n        eps = fx / (r - (fx*eta)/(2*r))\n        xi -= eps\n        error = abs(eps)\n        \n        if trace\n            println(\"### $i. Iteration ###\")\n            println(\"GZ: $Gz\")\n            println(\"R: $r\")\n            println(\"X$i: $xi\")\n            println(\"Epsilon: $eps\\n\")\n        end\n        \n        if error < tol\n            if trace\n                println(\"Stop-condition achieved.\")\n                println(\"Universal anomaly X = $xi\\n\")\n            end\n            return r\n        end\n        \n    end\n    \n    if trace\n        println(\"Newton's method didn't converge.\")\n        println(\"Last calculated universal anomaly X = $xi\\n\")\n    end\n    \n    return r\nend\n\n\n\n\n\"\"\"\n    keplerFlow(r0_bek, v0_bek, dt, mu, Gz, trace = false)\n\nDefines the position and speeds of a particle -after a time-step- orbiting another body given its initial position and speeds.\n\n# Args\n\n* `r0_bek`: position vector of the secondary body orbiting the primary body.\n* `v0_bek`: velocity vector of the secondary body orbiting the primary body.\n* `dt`: time-step, the function returns the new position and speed vectors after dt time has passed.\n* `mu`: standard gravitational parameter of the two bodies.\n* `r0`: initial distance between the two bodies.\n* `Gz`: array of the first four g-functions. Instead of defining it on each execution of the function, the same array is used in the whole simulation. That is why it's passed as an argument.\n* `trace`: boolean value that shows information of the execution if true.\n\n# Returns\n\n* `r_bek`: the position vector of the body after dt time from the initial values.\n* `v_bek`: the position vector of the body after dt time from the initial values.\n\"\"\"\nfunction keplerFlow(r0_bek, v0_bek, dt, mu, Gz, trace = false)\n    \n    r0 = norm(r0_bek)\n    v02 = dot(v0_bek,v0_bek) \n    eta = dot(r0_bek,v0_bek)\n    alpha = mu/r0\n    beta = 2.0*alpha - v02\n    zeta = mu - beta*r0\n     \n    # with beta, we can know the shape of the orbit\n    if trace\n        if beta > 0.0\n            println(\"Orbit is elliptic.\\n\")\n        elseif beta < 0.0\n            println(\"Orbit is hyperbolic.\\n\")\n        else beta == 0.0\n            println(\"Orbit is parabolic.\\n\")\n        end\n    end\n    \n    ### Initial estimation ###\n    x0 = (dt/r0) * (1.0 - eta/2.0) \n    if trace\n        println(\"X0 = $x0\\n\")\n    end\n    \n    ### Solve equation ###\n    r = keplerSolve!(x0, beta, eta, zeta, r0, Gz, dt, trace)\n        \n    rinv = 1.0/r\n    ### New position vector ###\n    f = -alpha*Gz[3]\n    g = r0*Gz[2] + eta*Gz[3]\n   \n    r_bek = f * r0_bek + g * v0_bek + r0_bek\n    \n    ### New speed vector ###\n    df = -alpha*Gz[2]*rinv\n    dg = -mu*Gz[3]*rinv\n    \n    v_bek = df * r0_bek + dg * v0_bek + v0_bek\n    \n    if trace\n        println(\"New position vector: R = $r0_bek\")\n        println(\"New speed vector: V = $v0_bek\")\n    end\n    \n    return r_bek, v_bek\n    \nend\n\n\n\n\n\"\"\"\n    keplerFlowWithKahan(r0_bek, v0_bek, dt, mu, Gz, trace, r_k, v_k)\n\nDefines the position and speeds of a particle -after a time-step- orbiting another body given its initial position and speeds. When the new vectors are calculated, Kahan's algorithm is applied. \n\n# Args\n\n* `r0_bek`: position vector of the secondary body orbiting the primary body.\n* `v0_bek`: speed vector of the secondary body orbiting the primary body.\n* `dt`: time-step, the function returns the new position and speed vectors after dt time has passed.\n* `mu`: standard gravitational parameter of the two bodies.\n* `r0`: initial distance between the two bodies.\n* `Gz`: array of the first four g-functions. Instead of defining it on each execution of the function, the same array is used in the whole simulation. That is why it's passed as an argument.\n* `trace`: boolean value that shows information of the execution if true.\n* `r_k`: lost information in the sum of the ``f`` and ``g`` coefficients is saved here and used in the next iteration (for positions).\n* `v_k`: lost information in the sum of the ``\\\\dot{f}`` and ``\\\\dot{g}`` coefficients is saved here and used in the next iteration (for velocities).\n\n# Returns\n\n* `r_bek`: the position vector of the body after dt time-step from the initial values.\n* `v_bek`: the velocity vector of the body after dt time-step from the initial values.\n\"\"\"\nfunction keplerFlowWithKahan(r0_bek, v0_bek, dt, mu, Gz, trace, r_k, v_k)\n        \n    r0 = norm(r0_bek)\n    v02 = dot(v0_bek,v0_bek) \n    eta = dot(r0_bek,v0_bek)\n    alpha = mu/r0\n    beta = 2.0*alpha - v02\n    zeta = mu - beta*r0\n     \n    # with beta, we can know the shape of the orbit\n    if trace\n        if beta > 0.0\n            println(\"Orbit is elliptic.\\n\")\n        elseif beta < 0.0\n            println(\"Orbit is hyperbolic.\\n\")\n        else beta == 0.0\n            println(\"Orbit is parabolic.\\n\")\n        end\n    end\n    \n    ### Initial estimation ###\n    x0 = (dt/r0) * (1.0 - eta/2.0) \n    if trace\n        println(\"X0 = $x0\\n\")\n    end\n    \n    ### Solve equation ###\n    r = keplerSolve!(x0, beta, eta, zeta, r0, Gz, dt, trace)\n        \n    rinv = 1.0/r\n    ### New position vector ###\n    f = -alpha*Gz[3]\n    g = r0*Gz[2] + eta*Gz[3]\n   \n    r0_bek_aux = copy(r0_bek)\n    kahanSum!(r0_bek, f * r0_bek + g * v0_bek, r_k)\n    \n    ### New speed vector ###\n    df = -alpha*Gz[2]*rinv\n    dg = -mu*Gz[3]*rinv\n    \n    kahanSum!(v0_bek, df * r0_bek_aux + dg * v0_bek, v_k)\n    \n    if trace\n        println(\"New position vector: R = $r0_bek\")\n        println(\"New speed vector: V = $v0_bek\")\n    end\n    \n    return r0_bek, v0_bek\nend\n\n\n\n\n\"\"\"\n    keplerStep!(r, v, dt, mu, Gz, trace)\n\nDrifts all particles/bodies under ``\\\\mathcal{H}_{\\\\mathrm{Kepler}}`` hamiltonian.\n\n```math\n\\\\mathcal{H}_{\\\\mathrm{Kepler}}(\\\\textbf{q}, \\\\textbf{p}) = \\\\sum_{i=2}^{N} \\\\frac{\\\\textbf{p'}^{2}_{i}}{2 m_{i}'} - \\\\sum_{i=2}^{N} \\\\frac{Gm_{i}^{'}M_{i}}{\\\\mid \\\\textbf{q}_{i}^{'} \\\\mid} \n```\n\n# Args\n\n* `r`: NxD matrix, where N is the number of bodies and D the dimensions. Initially must contain the initial positions of the bodies, but the output positions will be saved here as well (NxD, where N is the number of bodies  and D is the number of dimensions).\n* `v`: NxD matrix. Initially must contain the initial speeds of the bodies, but the output speeds will be saved here as well (NxD, where N is the number of bodies and D is the number of dimensions).\n* `dt`: time-step between the initial and final positions and speeds.\n* `mu`: N array. Standard gravitational parameter of the N bodies.\n* `r0`: initial distance between the two bodies.\n* `Gz`: array of the first four g-functions. Instead of defining it on each execution of the function, the same array is used in the whole simulation. That is why it's passed as an argument.\n* `trace`: boolean value that shows information of the execution if true.\n\"\"\"\nfunction keplerStep!(r, v, dt, mu, Gz, trace)\n    # drift all particles under H_Kepler\n    for i in 2:size(r)[1]\n        r[i,:], v[i,:] = keplerFlow(r[i,:], v[i,:], dt, mu[i], Gz, trace)\n    end\nend\n\n\n\n\n\"\"\"\n    keplerStepWithKahan!(r, v, dt, mu, Gz, trace, r_k, v_k)\n\nDrifts all particles/bodies under ``\\\\mathcal{H}_{\\\\mathrm{Kepler}}`` hamiltonian.\n\n```math\n\\\\mathcal{H}_{\\\\mathrm{Kepler}}(\\\\textbf{q}, \\\\textbf{p}) = \\\\sum_{i=2}^{N} \\\\frac{\\\\textbf{p'}^{2}_{i}}{2 m_{i}'} - \\\\sum_{i=2}^{N} \\\\frac{Gm_{i}^{'}M_{i}}{\\\\mid \\\\textbf{q}_{i}^{'} \\\\mid} \n```\n\n# Args\n\n* `r`: NxD matrix, where N is the number of bodies and D the dimensions. Initially must contain the initial positions of the bodies, but the output positions will be saved here as well.\n* `v`: NxD matrix. Initially must contain the initial speeds of the bodies, but the output speeds will be saved here as well.\n* `dt`: time-step between the initial and final positions and speeds.\n* `mu`: array of N elements, containing standard gravitational parameters of the N bodies.\n* `r0`: initial distance between the two bodies.\n* `Gz`: array of the first four g-functions. Instead of defining it on each execution of the function, the same array is used in the whole simulation. That is why it's passed as an argument.\n* `trace`: boolean value that shows information of the execution if true.\n* `r_k`: auxiliary variable to save extra information of Kahan's algorithm (positions). Same dimension as `r`.\n* `v_k`: auxiliary variable to save extra information of Kahan's algorithm (velocities). Same dimension as `v`.\n\"\"\"\nfunction keplerStepWithKahan!(r, v, dt, mu, Gz, trace, r_k, v_k)\n    ### drift all particles under H_Kepler  \n    for i in 2:size(r)[1]\n        r[i,:], v[i,:] =keplerFlowWithKahan(r[i,:], v[i,:], dt, mu[i], Gz, trace, r_k[i,:], v_k[i,:])\n    end\nend", "meta": {"hexsha": "78f936b0ab85285367552f589620e818aefdaba6", "size": 11190, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/keplerianOrbits.jl", "max_stars_repo_name": "salanueva/KeplerFlow", "max_stars_repo_head_hexsha": "4e370d6fd76100974d31ad548629f52217b4e96f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/keplerianOrbits.jl", "max_issues_repo_name": "salanueva/KeplerFlow", "max_issues_repo_head_hexsha": "4e370d6fd76100974d31ad548629f52217b4e96f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/keplerianOrbits.jl", "max_forks_repo_name": "salanueva/KeplerFlow", "max_forks_repo_head_hexsha": "4e370d6fd76100974d31ad548629f52217b4e96f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2996845426, "max_line_length": 259, "alphanum_fraction": 0.6291331546, "num_tokens": 3410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7741902080380048}}
{"text": "using Plots\npyplot()\n\n#---------------------------------------------------------------------#\n#This code plots the Stability of for the 1D Wave Equation.\n#Written by F.X. Giraldo on 03/2019\n#           Department of Applied Maths\n#           Naval Postgraduate School\n#           Monterey; CA 93943-5216\n#Variables:\n#---------------------------------------------------------------------#\n#method=input(\" 1=FE & Upwind \\n 2=FE & Centered \\n 3=FE & Downwind \\n 4=BE & Upwind \\n 5=BE & Centered \\n 6=BE & Downwind \\n 7=TR & Upwind \\n 8=TR & Centered \\n 9=TR & Downwind \\n Enter Method: \")\nmethod=1\n\nn=100\ndtheta=2*pi/n\ntheta=0:dtheta:2*pi\nif (method <= 3)\n    cmax=1\nelseif [method >= 4]\n    cmax=10\nend\nm=10*cmax\ndc=cmax/m\nc=0:dc:cmax\nem1=exp.(-im*theta)\nep1=exp.(+im*theta)\n\na=ones(size(em1))\n#Plot Stability of Specific Equations\nxmatrix=Array{Float64}(undef,n,m+2)\nymatrix=Array{Float64}(undef,n,m+2)\nif method == 1 #FE + Upwind\n    for j=1:m+1\n        z=a - c[j]*(a - em1) #1st order upwind [explicit 1st order in time]\n        xmatrix[:,j]=real(z)\n        ymatrix[:,j]=imag(z)\n    end\nelseif method == 2 #FE + Centered\n    for j=2:m+1\n        z=a - 0.5*c[j]*(ep1 - em1); #2nd order centered [explicit 1st order in time]\n        xmatrix[:,j]=real(z)\n        ymatrix[:,j]=imag(z)\n    end\nelseif method == 3 #FE + Downwind\n    for j=2:m+1\n        z=a - c[j]*(ep1 - a); #1st order downwind [explicit 1st order in time]\n        xmatrix[:,j]=real(z)\n        ymatrix[:,j]=imag(z)\n    end\nelseif method == 4 #BE + Upwind\n    for j=2:m+1\n        z=a/(a + c[j]*(a - em1)) #1st order uwpind, (implicit 1st order in time)\n        xmatrix[:,j]=real(z)\n        ymatrix[:,j]=imag(z)\n    end\nelseif method == 5 #BE + Centered\n    for j=2:m+1\n        z=a/(a + 0.5*c[j]*(ep1 - em1)) #2nd order centered, (implicit 1st order in time)\n        xmatrix[:,j]=real(z)\n        ymatrix[:,j]=imag(z)\n    end\nelseif method == 6 #BE + Downwind\n    for j=2:m+1\n        z=a/(a + c[j]*(ep1 - a)) #1st order downwind, (implicit 1st order in time)\n        xmatrix[:,j]=real(z)\n        ymatrix[:,j]=imag(z)\n    end\nelseif method == 7 #TR + Upwind\n    for j=2:m+1\n        z=(a - 0.5*c[j]*(a - em1))./(a + 0.5*c[j]*(a - em1)) #1st order upwind [Trapezoidal 2nd order in time]\n        xmatrix[:,j]=real(z)\n        ymatrix[:,j]=imag(z)\n    end\nelseif method == 8 #TR + Centered\n    for j=2:m+1\n        z=(a - 0.25*c[j]*(ep1 - em1))./(a + 0.25*c[j]*(ep1 - em1)) #2nd order centered [TR 2nd order in time]\n        xmatrix[:,j]=real(z)\n        ymatrix[:,j]=imag(z)\n    end\nelseif method == 9 #TR + Downwind\n    for j=2:m+1\n        z=(a - 0.5*c[j]*(ep1 - a))./(a + 0.5*c[j]*(ep1 - a)) #1st order downwind [TR 2nd order in time]\n        xmatrix[:,j]=real(z)\n        ymatrix[:,j]=imag(z)\n    end\nend\n\n#Plot Unit Circle\nz=ep1\nxmatrix[:,m+2]=real(z)\nymatrix[:,m+2]=imag(z)\n#plot_handle=plot(xmatrix,ymatrix,leg=false,w=2,aspect_ratio=1)\nplot(xmatrix,ymatrix,leg=false,w=1,line=(:dash,1),aspect_ratio=1)\nplot!(real(z),imag(z),leg=false,w=1,color=[:black],aspect_ratio=1)\nxaxis!(\"Re(z)\")\nyaxis!(\"Im(z)\")\ntitle!(\"Von Neumann Stability Analysis\")\n#display(plot(plot_handle))\n", "meta": {"hexsha": "a86dbf56a370d947eec3a481bf8238b9699b300c", "size": 3127, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapters/Chapter_01/fxg_book_ch1_stability.jl", "max_stars_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_stars_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-12-28T06:19:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:40:33.000Z", "max_issues_repo_path": "Chapters/Chapter_01/fxg_book_ch1_stability.jl", "max_issues_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_issues_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-29T19:12:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-29T21:53:41.000Z", "max_forks_repo_path": "Chapters/Chapter_01/fxg_book_ch1_stability.jl", "max_forks_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_forks_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:35:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T06:53:34.000Z", "avg_line_length": 31.27, "max_line_length": 197, "alphanum_fraction": 0.5577230572, "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7741902078675563}}
{"text": "function entropy(partitionSet, N)\n    return mapreduce(x -> -(length(x) / N) * log(length(x) / N), +, partitionSet)\nend\n\nfunction getPartitionSet(vector, nrOfClusters)\n    d = Dict(zip(1:nrOfClusters,[Int[] for _ in 1:nrOfClusters]));\n    for i in 1:length(vector)\n        push!(d[vector[i]], i)\n    end\n    return collect(values(d))\nend\n\n\nfunction mutualInformation(partitionSetA, partitionSetB, N)\n\n\n    anonFunc = (x) -> (\n                intersection = size(intersect(partitionSetA[x[1]], partitionSetB[x[2]]),1);\n                return intersection > 0 ?\n                        (intersection/N) * log((intersection * N) / (size(partitionSetA[x[1]],1) * size(partitionSetB[x[2]],1))) : 0;\n    )\n\n    mapreduce(anonFunc, + , product(1:length(partitionSetA),1:length(partitionSetB)))\nend\n\n\nfunction normalizedMutualInformation(partitionSetA, partitionSetB, N)\n    mutualInformation(partitionSetA, partitionSetB, N) / ((entropy(partitionSetA, N)  + entropy(partitionSetB, N)) / 2)\nend\n", "meta": {"hexsha": "927a221d41a8e8e15e3e9fecdd3699e8c183334d", "size": 987, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "eval.jl", "max_stars_repo_name": "Twelve33/LandmarkSpectralClustering", "max_stars_repo_head_hexsha": "0e6c639b99b1784232f8750d6a0dac44e7577e14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eval.jl", "max_issues_repo_name": "Twelve33/LandmarkSpectralClustering", "max_issues_repo_head_hexsha": "0e6c639b99b1784232f8750d6a0dac44e7577e14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eval.jl", "max_forks_repo_name": "Twelve33/LandmarkSpectralClustering", "max_forks_repo_head_hexsha": "0e6c639b99b1784232f8750d6a0dac44e7577e14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9, "max_line_length": 133, "alphanum_fraction": 0.6534954407, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7741902030287704}}
{"text": "# # Chebyshev center\n# Boyd & Vandenberghe, \"Convex Optimization\"\n# Joëlle Skaf - 08/16/05\n#\n# Adapted for Convex.jl by Karanveer Mohan and David Zeng - 26/05/14\n#\n# The goal is to find the largest Euclidean ball (i.e. its center and\n# radius) that lies in a polyhedron described by affine inequalites in this\n# fashion: $P = \\{x : a_i'*x \\leq b_i, i=1,\\ldots,m \\}$ where $x \\in \\mathbb{R}^2$.\n\nusing Convex\nusing LinearAlgebra\nimport SCS\n\n# Generate the input data\na1 = [2; 1];\na2 = [2; -1];\na3 = [-1; 2];\na4 = [-1; -2];\nb = ones(4, 1);\n\n# Create and solve the model\nr = Variable(1)\nx_c = Variable(2)\np = maximize(r)\np.constraints += a1' * x_c + r * norm(a1, 2) <= b[1];\np.constraints += a2' * x_c + r * norm(a2, 2) <= b[2];\np.constraints += a3' * x_c + r * norm(a3, 2) <= b[3];\np.constraints += a4' * x_c + r * norm(a4, 2) <= b[4];\nsolve!(p, SCS.Optimizer; silent_solver = true)\np.optval\n\n# Generate the figure\nx = range(-1.5, stop = 1.5, length = 100);\ntheta = 0:pi/100:2*pi;\nusing Plots\nplot(x, x -> -x * a1[1] / a1[2] + b[1] / a1[2])\nplot!(x, x -> -x * a2[1] / a2[2] + b[2] / a2[2])\nplot!(x, x -> -x * a3[1] / a3[2] + b[3] / a3[2])\nplot!(x, x -> -x * a4[1] / a4[2] + b[4] / a4[2])\nplot!(\n    evaluate(x_c)[1] .+ evaluate(r) * cos.(theta),\n    evaluate(x_c)[2] .+ evaluate(r) * sin.(theta),\n    linewidth = 2,\n)\nplot!(\n    title = \"Largest Euclidean ball lying in a 2D polyhedron\",\n    legend = nothing,\n)\n", "meta": {"hexsha": "0da6b3e5015d2cfb2cfb58257649ac46202a448c", "size": 1410, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/general_examples/chebyshev_center.jl", "max_stars_repo_name": "baggepinnen/Convex.jl", "max_stars_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 327, "max_stars_repo_stars_event_min_datetime": "2015-01-22T01:00:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T16:42:11.000Z", "max_issues_repo_path": "docs/examples_literate/general_examples/chebyshev_center.jl", "max_issues_repo_name": "baggepinnen/Convex.jl", "max_issues_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 275, "max_issues_repo_issues_event_min_datetime": "2015-01-12T19:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-05T19:05:45.000Z", "max_forks_repo_path": "docs/examples_literate/general_examples/chebyshev_center.jl", "max_forks_repo_name": "baggepinnen/Convex.jl", "max_forks_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 121, "max_forks_repo_forks_event_min_datetime": "2015-01-23T21:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T13:58:39.000Z", "avg_line_length": 28.2, "max_line_length": 83, "alphanum_fraction": 0.5872340426, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.8418256472515684, "lm_q1q2_score": 0.7741786764649495}}
{"text": "\"\"\"\n    function spearman_corr(;\n        players::Array{Player},\n        ranking_scheme1::String,\n        ranking_scheme2::String\n    )::Float64\n\nCalculates the Spearman Correlation between two ranks.\n\nArguments\n=========\n- `players`:\n    the players whose rankings to consider.\n- `ranking_scheme1`:\n    ranking scheme 1 to use.\n- `ranking_scheme2`:\n    ranking scheme 2 to use.\n\"\"\"\n\nfunction spearman_corr(;\n    players::Array{Player},\n    ranking_scheme1::String,\n    ranking_scheme2::String\n)::Float64\n    rankings1 = map(player -> player.rankings[ranking_scheme1], players)\n    rankings2 = map(player -> player.rankings[ranking_scheme2], players)\n    return corspearman(rankings1, rankings2)\nend\n\n\n\"\"\"\n    function kendtau_corr(;\n        players::Array{Player},\n        ranking_scheme1::String,\n        ranking_scheme2::String\n    )::Float64\n\nCalculates the Kendall Tau Correlation between two ranks.\n\nArguments\n=========\n- `players`:\n    the players whose rankings to consider.\n- `ranking_scheme1`:\n    ranking scheme 1 to use.\n- `ranking_scheme2`:\n    ranking scheme 2 to use.\n\"\"\"\n\nfunction kendtau_corr(;\n    players::Array{Player},\n    ranking_scheme1::String,\n    ranking_scheme2::String\n)::Float64\n    rankings1 = map(player -> player.rankings[ranking_scheme1], players)\n    rankings2 = map(player -> player.rankings[ranking_scheme2], players)\n    return corkendall(rankings1, rankings2)\nend", "meta": {"hexsha": "f74b2b76df0dbb766ca84451a0d71e88aba89010", "size": 1401, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/metric/correlation.jl", "max_stars_repo_name": "Danial-Hussain/Tennis-Ranking", "max_stars_repo_head_hexsha": "0cc4f4e27158c0690a9d70b4bdb1ec621e11d212", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/metric/correlation.jl", "max_issues_repo_name": "Danial-Hussain/Tennis-Ranking", "max_issues_repo_head_hexsha": "0cc4f4e27158c0690a9d70b4bdb1ec621e11d212", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/metric/correlation.jl", "max_forks_repo_name": "Danial-Hussain/Tennis-Ranking", "max_forks_repo_head_hexsha": "0cc4f4e27158c0690a9d70b4bdb1ec621e11d212", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1551724138, "max_line_length": 72, "alphanum_fraction": 0.693076374, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7741786708442322}}
{"text": "# # 220: 2D Nonlinear Poisson with boundary reaction and boundary species\n# ([source code](SOURCE_URL))\n\nmodule Example220_NonlinearPoisson2D_BoundarySpecies\n\nusing Printf\nusing VoronoiFVM\nusing ExtendableGrids\nusing GridVisualize\n\nfunction main(;n=10,Plotter=nothing,verbose=false,unknown_storage=:sparse)\n    \n    \n    h=1.0/convert(Float64,n)\n    X=collect(0.0:h:1.0)\n    Y=collect(0.0:h:1.0)\n    \n\n\n    grid=VoronoiFVM.Grid(X,Y)\n    \n    \n    k=1.0\n    eps=1.0\n    physics=VoronoiFVM.Physics(\n    num_species=3,\n    breaction=function(f,u,node)\n        if  node.region==2\n            f[1]=k*(u[1]-u[3])\n            f[3]=k*(u[3]-u[1])+ k*(u[3]-u[2])\n            f[2]=k*(u[2]-u[3])\n        end\n    end,\n    \n    bstorage=function(f,u,node)\n        if  node.region==2\n            f[3]=u[3]\n        end\n    end,\n    \n    \n    flux=function(f,u0,edge)\n        u=unknowns(edge,u0)\n        f[1]=eps*(u[1,1]-u[1,2])\n        f[2]=eps*(u[2,1]-u[2,2])\n    end,\n    \n    source=function(f,node)\n        x1=node[1]-0.5\n        x2=node[2]-0.5\n        f[1]=exp(-20.0*(x1^2+x2^2))\n    end,\n    \n    storage=function(f,u,node)\n        f[1]=u[1]\n        f[2]=u[2]\n    end\n    )\n    \n    sys=VoronoiFVM.System(grid,physics,unknown_storage=unknown_storage)\n    \n    enable_species!(sys,1,[1])\n    enable_species!(sys,2,[1])\n    enable_boundary_species!(sys,3,[2])\n\n    \n    function tran32!(a,b)\n        a[1]=b[2]\n    end\n    \n    bgrid2=subgrid(grid,[2],boundary=true,transform=tran32!)\n   \n    inival=unknowns(sys)\n    inival.=0.0\n    U=unknowns(sys)\n\n    eps=1.0e-2\n    \n    control=VoronoiFVM.NewtonControl()\n    control.verbose=verbose\n    control.tol_linear=1.0e-5\n    control.tol_relative=1.0e-5\n    control.max_lureuse=0\n    tstep=0.01\n    time=0.0\n    istep=0\n    u5=0\n    p=GridVisualizer(Plotter=Plotter,layout=(3,1))\n    while time<1\n        time=time+tstep\n        solve!(U,inival,sys,control=control,tstep=tstep)\n        inival.=U\n        if verbose\n            @printf(\"time=%g\\n\",time)\n        end\n        tstep*=1.0\n        istep=istep+1\n        U_bound=view(U[3,:],bgrid2)\n        u5=U_bound[5]\n        scalarplot!(p[1,1],grid,U[1,:],clear=true)\n        scalarplot!(p[2,1],grid,U[2,:])\n        scalarplot!(p[3,1],bgrid2,U_bound,show=true,flimits=(0,0.0025))\n    end\n    return u5\nend\n\nfunction test()\n    main(unknown_storage=:sparse) ≈ 0.0020781361856598\n    main(unknown_storage=:dense) ≈ 0.0020781361856598\nend\nend\n", "meta": {"hexsha": "ea1f291edce33bd84edf42ebb4d4b8b0d84dd818", "size": 2420, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Example220_NonlinearPoisson2D_BoundarySpecies.jl", "max_stars_repo_name": "NunoEdgarGFlowHub/VoronoiFVM.jl", "max_stars_repo_head_hexsha": "c9f5834a2052414e9d174e7c423d9d68e1406fd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Example220_NonlinearPoisson2D_BoundarySpecies.jl", "max_issues_repo_name": "NunoEdgarGFlowHub/VoronoiFVM.jl", "max_issues_repo_head_hexsha": "c9f5834a2052414e9d174e7c423d9d68e1406fd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Example220_NonlinearPoisson2D_BoundarySpecies.jl", "max_forks_repo_name": "NunoEdgarGFlowHub/VoronoiFVM.jl", "max_forks_repo_head_hexsha": "c9f5834a2052414e9d174e7c423d9d68e1406fd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6071428571, "max_line_length": 74, "alphanum_fraction": 0.5731404959, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642528975397, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7741786653700579}}
{"text": "@doc raw\"\"\"\n    Segment2\n\nAn object `s` of the data type [`Segment2`](@ref) is a directed straight line\nsegment in the two-dimensional Euclidean plane ``Ε^2``, i.e. a straight line\nsegment ``[p, q]`` connecting two points ``p, q ∈ ℝ^2``.\n\nThe segment is topologically closed, i.e. the end points belong to it. Point `p`\nis called the *source* and `q` is called the *target* of `s`. The length of `s`\nis the Euclidean distance between `p` and `q`. Note that there is only a\nfunction to compute the square of the length, because otherwise we had to\nperform a square root operation which is expensive, and may not be exact.\n\"\"\"\nSegment2\n\n\"\"\"\n    Segment2(p::Point2, q::Point2)\n\nIntroduces a segment `s` with source `p` and target `q`.\n\nThe segment is directed from the source towards the target.\n\"\"\"\nSegment2(p::Point2, q::Point2)\n\n\"\"\"\n    ==(s::Segment2, q::Segment2)\n\nTest for equality: Two segments are equal, iff their sources and targets are\nequal.\n\"\"\"\n==(s::Segment2, q::Segment2)\n\n\"\"\"\n    source(s::Segment2)\n\nThe source of `s`.\n\"\"\"\nsource(s::Segment2)\n\n\"\"\"\n    target(s::Segment2)\n\nThe target of `s`.\n\"\"\"\ntarget(s::Segment2)\n\n\"\"\"\n    min(s::Segment2)\n\nReturns the point of `s` with lexicographically smallest coordinate.\n\"\"\"\nmin(s::Segment2)\n\n\"\"\"\n    max(s::Segment2)\n\nReturns the point of `s` with lexicographically largest coordinate.\n\"\"\"\nmax(s::Segment2)\n\n@doc raw\"\"\"\n    vertex(s::Segment2, i::Integer)\n\nReturns source of target or `s`: `vertex(s, 0)` returns the source of `s`,\n`vertex(s, 1)` returns the target of `s`\n\nThe parameter `i` is taken module 2, which gives easy access to the other\nvertex.\n\"\"\"\nvertex(s::Segment2, i::Integer)\n\n\"\"\"\n    point(s::Segment2, i::Integer)\n\nReturns `vertex(s, i)`.\n\"\"\"\npoint(s::Segment2, i::Integer)\n\n\"\"\"\n    squared_length(s::Segment2)\n\nReturns the squared lenght of `s`.\n\"\"\"\nsquared_length(s::Segment2)\n\n\"\"\"\n    direction(s::Segment2)\n\nReturns the direction from source to target of `s`.\n\"\"\"\ndirection(s::Segment2)\n\n\"\"\"\n    to_vector(s::Segment2)\n\nReturns the vector `target(s) - source(s)`.\n\"\"\"\nto_vector(s::Segment2)\n\n\"\"\"\n    opposite(s::Segment2)\n\nReturns a segment with source and target point interchanged.\n\"\"\"\nopposite(s::Segment2)\n\n\"\"\"\n    supporting_line(s::Segment2)\n\nReturns the line `l` passing through `s`.\n\"\"\"\nsupporting_line(s::Segment2)\n\n\"\"\"\n    is_degenerate(s::Segment2)\n\nSegment `s` is degenerate, if source and target are equal.\n\"\"\"\nis_degenerate(s::Segment2)\n\n\"\"\"\n    is_horizontal(s::Segment2)\n\nSegment `s` is horizontal, if both the source and target's ``y``-coordinate is\nthe same.\n\"\"\"\nis_horizontal(s::Segment2)\n\n\"\"\"\n    is_vertical(s::Segment2)\n\nSegment `s` is vertical, if both the source and target's ``x``-coordinate is\nthe same.\n\"\"\"\nis_vertical(s::Segment2)\n\n\"\"\"\n    has_on(s::Segment2, p::Point2)\n\nA point is on `s`, iff it is equal to the source or target of `s` or if it is\nin the interior of `s`.\n\"\"\"\nhas_on(s::Segment2, p::Point2)\n\n\"\"\"\n    collinear_has_on(s::Segment2, p::Point2)\n\nChecks if point `p` is on segment `s`.\n\n!!! info \"Precondition\"\n\n    `p` is on the supporting line of `s`.\n\"\"\"\ncollinear_has_on(s::Segment2, p::Point2)\n\n\"\"\"\n    bbox(s::Segment2)\n\nReturns a bounding box containing `s`.\n\"\"\"\nbbox(s::Segment2)\n\n\"\"\"\n    transform(s::Segment2, t::AffTransformation2)\n\nReturns the segment obtained by applying `t` on the source and the target of\n`s`.\n\"\"\"\ntransform(s::Segment2, t::AffTransformation2)\n", "meta": {"hexsha": "6d13447d26de320d7938e2065a5e1aff61676822", "size": 3395, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernel/segment_2.jl", "max_stars_repo_name": "rgcv/CGAL.jl", "max_stars_repo_head_hexsha": "a3d55993938f271f3243fb86cb59f2e481bac7d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-07-17T22:06:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T08:32:54.000Z", "max_issues_repo_path": "src/kernel/segment_2.jl", "max_issues_repo_name": "rgcv/CGAL.jl", "max_issues_repo_head_hexsha": "a3d55993938f271f3243fb86cb59f2e481bac7d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-10-31T19:37:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T20:04:37.000Z", "max_forks_repo_path": "src/kernel/segment_2.jl", "max_forks_repo_name": "rgcv/CGAL.jl", "max_forks_repo_head_hexsha": "a3d55993938f271f3243fb86cb59f2e481bac7d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-16T13:55:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T18:07:26.000Z", "avg_line_length": 19.9705882353, "max_line_length": 80, "alphanum_fraction": 0.6777614138, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7741786653700578}}
{"text": "using UtilitiesForMRI, Random\n\n# Cartesian domain\nn = (128,128,128)\nh = (1f0, 1f0, 1f0)\nX = spatial_sampling(Float32, n; h=h)\n\n# Cartesian sampling (dense)\nphase_encoding = (1,2)\nK = kspace_Cartesian_sampling(X; phase_encoding=phase_encoding)\n# using PyPlot\n# figure()\n# plot3D(K[1][:,1],  K[1][:,2],  K[1][:,3], \".\")\n# plot3D(K[10][:,1], K[10][:,2], K[10][:,3], \".\")\n# plot3D(K[20][:,1], K[20][:,2], K[20][:,3], \".\")\n# plot3D(K[128*(10-1)+1][:,1], K[128*(10-1)+1][:,2], K[128*(10-1)+1][:,3], \".\")\n# plot3D(K[128*(20-1)+1][:,1], K[128*(20-1)+1][:,2], K[128*(20-1)+1][:,3], \".\")\n# plot3D(K[128^2][:,1], K[128^2][:,2], K[128^2][:,3], \".\")\n\n# Cartesian sampling (randomized)\nsubsampling = (1:128^2)[randperm(128^2)][1:32]\nK = kspace_Cartesian_sampling(X; phase_encoding=(1,3), subsampling=subsampling)\n# figure()\n# for i = 1:32\n#     plot3D(K[i][:,1], K[i][:,2], K[i][:,3], \".\")\n# end\n\n# for i = 1:50:128^2\n#     plot3D(K[i][:,1], K[i][:,2], K[i][:,3], \".\")\n# end", "meta": {"hexsha": "9ae15e7206086c51cd4ab74736e27cd93f503b17", "size": 960, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_kspace_sampling.jl", "max_stars_repo_name": "grizzuti/UtilitiesForMRI", "max_stars_repo_head_hexsha": "71e3ed5237ea4263b2d1d9af6f494f3c9066f631", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_kspace_sampling.jl", "max_issues_repo_name": "grizzuti/UtilitiesForMRI", "max_issues_repo_head_hexsha": "71e3ed5237ea4263b2d1d9af6f494f3c9066f631", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_kspace_sampling.jl", "max_forks_repo_name": "grizzuti/UtilitiesForMRI", "max_forks_repo_head_hexsha": "71e3ed5237ea4263b2d1d9af6f494f3c9066f631", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0, "max_line_length": 79, "alphanum_fraction": 0.54375, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7741786635746415}}
{"text": "# Examples presented in class - Lecture 1\n# written by Fabricio - 07/09/2018\n\nusing JuMP, Cbc\n# JuMP is for implementing math. programming models;\n# Cbc is for solving them.\n\n# Example 1 - resource allocation\n\n# Problem data\ni = 1:2 # i=1: Seattle; i=2: San Diego\nj = 1:3 # j=1: New York; j=2: Chicago; j=3: Miami\n\nC = [350 600] # Capacities of the factories\nD = [325 300 275] # Demand of clients\nT = [2.5 1.7 1.8\n     3.5 1.9 1.4] # Transportation costs\n\n# Model implementation\n# Creates a model and informs the solver to be used\nm = Model(solver = CbcSolver())\n\n# Decision variable for the total transported\n@variable(m, x[i,j] >= 0)\n\n# Capacity constraint\n@constraint(m, cap[i = 1:2], sum(x[i,j] for j = 1:3) <= C[i])\n# Demand constraint\n@constraint(m, dem[j = 1:3], sum(x[i,j] for i = 1:2) >= D[j])\n\n# Total distribution cost that we want to minimise\n@objective(m, Min, sum(T[i,j]*x[i,j] for i=1:2, j=1:3))\n\nprintln(m) # Prints the mathematical model for debugging\nsolve(m) # Solve the model\n\n# Prints the optimal solution\nprintln(\"\\nDistribution plan: \\n\", getvalue(x))\n\n#################################################################\n\n\n\n\n\n\n# Example 2 - portfolio optimisation\n\nusing Ipopt, Plots\n# Ipopt is for solving nonlinear problems - different technology\n# Plots is for plotting (!)\n\n# Read the daily prices data from a .csv file.\ndata = readcsv(\"prices.csv\")\n#First row has the names of the stocks\nstock_names = data[1, 1:end-2]\n#Last two columns has data and US$ rate\nprices_data = data[2:end, 1:end-2]\n\n#Having a peek at the data\n\ncs = plot(prices_data, label = stock_names)\nplotlyjs()\n\ngui(cs)\n#Returns are calculated as (p(t+1) - p(t))/p(t-1)\nreturns_data = diff(prices_data) ./ prices_data[1:end-1,:]\n\n#Number of days and stocks in data\nT, n =  size(returns_data)\n#Calculates expected return and covariance\nμ, Σ =  mean(returns_data, 1), cov(returns_data)\n# Input form the model: minimum average return required.\nr_min = 0.2\n\nport = Model(solver=IpoptSolver())\n\n#allocation variables\n@variable(port, 0 <= x[1:n] <= 1);\n\n#notice the division by T to correct the average\n@constraint(port, sum(μ[j]*x[j] for j=1:n) >= r_min/T);\n\n@objective(port, Min , sum(x[i]*Σ[i,j]*x[j] for i=1:n,j=1:n));\n\nsolve(port);\n\nalloc = getvalue(x)\n# Should be the same as r_min\nret = μ*alloc*T\n# Looking at risk as the st. deviation of the returns.\nrisk = sqrt(alloc'*Σ*alloc*T)\n\n# Organising the data for plotting. In an array, they are\n# considered different series (with different colours)\nstock_names = convert(Array{String}, stock_names)\nalloc = convert(Array{Float64}, alloc)\n# plots a pie chart\npie(stock_names, alloc, legend = false)\n\n#################################################################\n\n\n\n\n\n\n# Example 3 - Robust Knapsack Problem\n\nusing Distributions, ECOS, LaTeXStrings\n# Distributions includes probability distributions,\n# ECOS is a solver that we need because of the stucture of the problem\n# LatexStrings is to write LaTeX in our plots\n\nN = 18\n\n#Input data\nvalue = [50, 40, 70, 55, 80, 35, 65, 50, 60, 85, 20, 45, 55, 25, 80, 45, 45, 65]\nweight_average = [3.5, 4, 5.5, 5, 6, 4.5, 6, 4, 5.5, 7, 5, 4.5, 7, 3.5, 5.5, 3.5, 4, 6.5]\nweight_stdev = weight_average*0.3\n\n#Randomly generating initial data using normal distribution\nweight_data = Array{Float64}(100,N)\nfor j= 1:N\n   weight_data[:,j] = rand(Normal(weight_average[j], weight_stdev[j]), 100)\nend\n\n#Input data: weight limit (capacity)\ncapacity = 20\n\n# Protection elipsoid: adds 50% of weight as a protection level\nP = 0.5*weight_average\n\n# Declaring the model and solving it as a function.\nfunction solve_robust_model(N, value, weight_average, P, Γ)\n    m = Model(solver = ECOSSolver()) #creates the model, select the solver\n\n    @variable(m, 0 <= x[1:N] <= 1 ) # creates the binary variables x, one for each item\n\n    @constraint(m, sum(weight_average[j]*x[j] for j = 1:N) + Γ*norm(P'*x) <= capacity) # declare the knapsack constraint\n\n    @objective(m, Max, sum(value[j]*x[j] for j = 1:N)) # declare the objective function\n\n    solve(m)\n\n    return getvalue(x)\nend\n\n# This function simulates the item selection againts feasibility.\nfunction feasibility_estimate(solution, repetitions)\n    feasible_count = 0\n    actual_weight = zeros(18)\n    for n= 1:repetitions\n        for j= 1:N\n           # generate random weights according to distribution\n           actual_weight[j] = rand(Normal(weight_average[j], weight_stdev[j]))\n        end\n        #if total weight more than capacity => problem infeasible.\n        if actual_weight'*solution <= capacity\n            feasible_count += 1\n        end\n    end\n    return feasible_count/repetitions\nend\n\n# generate a range of Gammas to try\nΓ_range = linspace(0,1,10)\n\n# storing the results of each run\nfeas = []\ntotal_value = []\nΓ_used = []\n\n# for each Gamma, solve te model and store the results\nfor Γ in Γ_range\n    println(Γ)\n    x = solve_robust_model(N, value, weight_average, P, Γ)\n    push!(Γ_used, Γ)\n    push!(feas, feasibility_estimate(x,5000))\n    push!(total_value, value'x)\nend\n\n# potting the results from simulation\np1 = plot(Γ_used, feas, xlabel = L\"\\Gamma\", ylabel = \"feas. prob.\", legend=false)\np2 = plot(Γ_used, total_value, xlabel = L\"\\Gamma\", ylabel = \"total value\", legend=false, color=:orange)\nplot(p1,p2, layout = (2,1))\n\n#################################################################\n\n\n\n\n\n# Example 4 - Classification\n\n# Generating random multivariate data.\ndata11 = rand(Normal(8, 4), 100)\ndata12 = rand(Normal(12, 2), 100)\ndata1 = [data11 data12]\n\ndata01 = rand(Normal(2, 6), 100)\ndata02 = rand(Normal(5, 2), 100)\ndata0 = [data01 data02]\n\nscatter(data1[:,1], data1[:,2], label=\"Pos. obs.\")\nscatter!(data0[:,1], data0[:,2], label=\"Neg. obs.\")\n\nfunction classify(data1, data0, δ)\n    m = Model(solver = IpoptSolver())\n\n    @variable(m, u[1:100] >= 0)\n    @variable(m, v[1:100] >= 0)\n    @variable(m, a[1:2])\n    @variable(m, b)\n\n    @constraint(m, error1[i=1:100], sum(a[j]*data1[i,j] for j = 1:2) - b - u[i] <= -1)\n    @constraint(m, error0[i=1:100], sum(a[j]*data0[i,j] for j = 1:2) - b + v[i] >= 1)\n\n# This parameter trades off accuracy and robustness for the classifier\n    @objective(m, Min, sum(u[i] for i=1:100) + sum(v[i] for i=1:100)\n        + δ*(sum(a[j]^2 for j=1:2)))\n\n    solve(m);\n\n    return getvalue(a), getvalue(b), getvalue(u), getvalue(v)\nend\n\na, b, u1, v1 = classify(data1, data0, 0.01);\n\n# Calculating the points on plane defined by a and b\nx1 = linspace(-10,20,100);\nx2 = (b - a[1]*x1)/ a[2];\n# boundaries of the slab\nx2u = (b + 1 - a[1]*x1)/ a[2];\nx2d = (b - 1 - a[1]*x1)/ a[2];\nplot!(x1, [x2u x2 x2d],\n    xlabel = \"x_1\",\n    ylabel = \"x_2\",\n    label= [ \"\", \"Classifier\", \"\"] ,\n    color=[:green :green :green],\n    linestyle=[ :dot :solid :dot],\n    )\n\n# another classifier, with δ=50\na, b, u2, v2 = classify(data1, data0, 100);\nx2 = (b - a[1]*x1)/ a[2];\nx2u = (b + 1 - a[1]*x1)/ a[2];\nx2d = (b - 1 - a[1]*x1)/ a[2];\nplot!(x1, [x2u x2 x2d],\n    xlabel = \"x_1\",\n    ylabel = \"x_2\",\n    legend = false,\n    color=[:purple :purple :purple],\n    linestyle=[:dot :solid :dot],\n    )\n", "meta": {"hexsha": "b48654b30cd4fabc20f86cdd5fb70fb7981dd34f", "size": 7051, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/lectures/Lecture_1/Figures/Julia/.ipynb_checkpoints/Lecture_1-checkpoint.jl", "max_stars_repo_name": "gamma-opt/CourseParser.jl", "max_stars_repo_head_hexsha": "be59cf09c2c8b34373a6cd0f972f46528c4233dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/lectures/Lecture_1/Figures/Julia/.ipynb_checkpoints/Lecture_1-checkpoint.jl", "max_issues_repo_name": "gamma-opt/CourseParser.jl", "max_issues_repo_head_hexsha": "be59cf09c2c8b34373a6cd0f972f46528c4233dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/lectures/Lecture_1/Figures/Julia/.ipynb_checkpoints/Lecture_1-checkpoint.jl", "max_forks_repo_name": "gamma-opt/CourseParser.jl", "max_forks_repo_head_hexsha": "be59cf09c2c8b34373a6cd0f972f46528c4233dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.54296875, "max_line_length": 120, "alphanum_fraction": 0.6410438236, "num_tokens": 2271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7741785881070656}}
{"text": "# Load Julia packages (libraries)\n\nusing Pkg, DrWatson\n\n#@quickactivate \"SR2StanPluto\"\nusing StanSample\nusing StatisticalRethinking\n\n# Define the Stan language model\n\nstan8_5s = \"\ndata{\n  int N;\n  vector[N] y;\n}\nparameters{\n  real sigma;\n  real a1;\n  real a2;\n}\nmodel{\n  real mu;\n  a1 ~ normal(0, 10);\n  a2 ~ normal(0, 10);\n  mu = a1 + a2;\n  y ~ normal( mu , sigma );\n}\n\";\n\n# Define the Stanmodel and set the output format to :mcmcchains.\n\nm8_5s = SampleModel(\"m8.5s\", stan8_5s);\n\n# Input data for cmdstan\n\nm8_5_data = Dict(\"N\" => 100, \"y\" => rand(Normal(0, 1), 100));\n\n# Sample using cmdstan\n\nrc8_5s = stan_sample(m8_5s, data=m8_5_data);\n  \nrethinking = \"\n       mean   sd   5.5% 94.5% n_eff Rhat\na1    -0.08 7.15 -11.34 11.25  1680    1\na2    -0.05 7.15 -11.37 11.19  1682    1\nsigma  0.90 0.07   0.81  1.02  2186    1\n\";\n\n# Describe the draws\nif success(rc8_5s)\n  part8_5s = read_samples(m8_5s, :particles)\n  part8_5s |> display\nend\n", "meta": {"hexsha": "875c0c2fa8c22061ea86b242f0425a0b5b1618a4", "size": 936, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/08/m8.5s.jl", "max_stars_repo_name": "StatisticalRethinkingJulia/SR2StanPluto.jl", "max_stars_repo_head_hexsha": "6eea864f4ca098320d7bc295c6254304c86d7d19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-17T01:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T00:23:37.000Z", "max_issues_repo_path": "models/08/m8.5s.jl", "max_issues_repo_name": "StatisticalRethinkingJulia/SR2StanPluto.jl", "max_issues_repo_head_hexsha": "6eea864f4ca098320d7bc295c6254304c86d7d19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/08/m8.5s.jl", "max_forks_repo_name": "StatisticalRethinkingJulia/SR2StanPluto.jl", "max_forks_repo_head_hexsha": "6eea864f4ca098320d7bc295c6254304c86d7d19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-21T21:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T21:01:50.000Z", "avg_line_length": 17.3333333333, "max_line_length": 64, "alphanum_fraction": 0.6442307692, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7741785831112188}}
{"text": "const EARTH_RADIUS_EQUATORIAL = 6378137.0\nconst EARTH_RADIUS_POLAR = 6356752.3\n\n\"\"\"\n`CoordinateDistance(lat1, lon1, lat2, lon2; calcfunc, radius)`\n\nDescription\n===========\n\nCalculates distance between (lat1, lon1) and (lat2, lon2).\n\nUsage\n=====\n\n  CoordinateDistance(latStart, longStart, latEnd, longEnd)\n\n  CoordinateDistance(latStart, longStart, latEnd, longEnd, calcfunc=haversine)\n\n  CoordinateDistance(latStart, longStart, latEnd, longEnd, radius=EARTH_RADIUS_POLAR)\n\n  CoordinateDistance((latStart, longStart), (latEnd, longEnd))\n\nArguments\n=========\n\n- **`lat1`** : Latitude of the first point. Must be a float.\n- **`lon1`** : Longitude of the first point. Must be a float.\n- **`lat2`** : Latitude of the second point. Must be a float.\n- **`lon2`** : Longitude of the second point. Must be a float.\n- **`calcfunc`** : Function that calculates distance between point 1 and 2. Defaults to\n  Vincenty. Haversine and Flat Pythagorean is also available.\n- **`radius`** : Radius of the Earth. Defaults to EARTH_RADIUS_EQUATORIAL - about 6378.137KM.\n  EARTH_RADIUS_POLAR is also available.\n\"\"\"\nfunction coord_distance(\n          lat1::AbstractFloat,\n          lon1::AbstractFloat,\n          lat2::AbstractFloat,\n          lon2::AbstractFloat;\n          calcfunc::Function=vincenty,\n          radius::AbstractFloat=EARTH_RADIUS_EQUATORIAL,\n          units::Unitful.FreeUnits=u\"m\",\n          returntype::Type=AbstractFloat, args...)\n  v = calcfunc(lat1, lon1, lat2, lon2, radius; args...)\n  v = isnan(v) ? 0. : v\n  units !== u\"m\" ? dist_convert(v, units, returntype) : v\nend\n\nfunction coord_distance(\n          coord1::Coordinate,\n          coord2::Coordinate;\n          args...)\n  v = coord_distance(coord1[1], coord1[2], coord2[1], coord2[2]; args...)\nend\n\n\"\"\"\n```julia\nhaversine(\n  lat1::AbstractFloat,\n  lon1::AbstractFloat,\n  lat2::AbstractFloat,\n  lon2::AbstractFloat,\n  radius::AbstractFloat\n)\n```\n\n\nHaversine Formula for Great Circle Distance\n========================\nThe Haversine formula presides on spherical trigonometry to calculate\nstraight distance between two points on a unit sphere; that is to say\n\"how the crow flies\" across a perfect sphere.\n\"\"\"\nfunction haversine(\n          lat1::AbstractFloat,\n          lon1::AbstractFloat,\n          lat2::AbstractFloat,\n          lon2::AbstractFloat,\n          radius::AbstractFloat; args...)::AbstractFloat\n  lat1 = deg2rad(lat1)\n  lon1 = deg2rad(lon1)\n  lat2 = deg2rad(lat2)\n  lon2 = deg2rad(lon2)\n\n  latΔ = lat2 - lat1\n  lonΔ = lon2 - lon1\n\n  a = sin(.5latΔ)^2 + cos(lat1)*cos(lat2)*sin(.5lonΔ)^2\n  c = 2asin(min(1, sqrt(a)))\n\n  return radius * c\nend\n\n\n\n\"\"\"\n```julia\nflatpythagorean(\n  lat1::AbstractFloat,\n  lon1::AbstractFloat,\n  lat2::AbstractFloat,\n  lon2::AbstractFloat,\n  radius::AbstractFloat\n)\n```\n\nPythagorean Theorem for Coordinate Distance\n========================\nUtilizing Pythagorean's Theorem to calculate coordinate distance\nassumes that the Earth is flat. While erroneous, when the distance\nbetween the points is less than 20 kilometers the expected error\nfor the majority of the United States will be less than 20 meters.\nLatitudes above 50 degrees (Alaska) will be less than 30 meters, and\nlatitudes below 30 degrees (Southern US / Hawaii) will be less than\n9 meters.\n\n\"\"\"\nfunction flatpythagorean(\n          lat1::AbstractFloat,\n          lon1::AbstractFloat,\n          lat2::AbstractFloat,\n          lon2::AbstractFloat,\n          radius::AbstractFloat; args...)::AbstractFloat\n  lat1 = deg2rad(lat1)\n  lon1 = deg2rad(lon1)\n  lat2 = deg2rad(lat2)\n  lon2 = deg2rad(lon2)\n\n  a = π/2 - lat1\n  b = π/2 - lat2\n  c = sqrt(a^2 + b^2 - 2*a*b*cos(lon2-lon1))\n\n  return radius * c\nend\n\n\n\"\"\"\n```julia\nvincenty(\n  lat1::AbstractFloat,\n  lon1::AbstractFloat,\n  lat2::AbstractFloat,\n  lon2::AbstractFloat\n  radiusA::AbstractFloat=EARTH_RADIUS_EQUATORIAL;\n  radiusB::AbstractFloat=EARTH_RADIUS_POLAR,\n  tol::AbstractFloat=1e-12,     # Error tolerance\n  maxiter::Int=1000,            # Maximum iterations before convergence\n  verbose::Bool=true            # Print out warnings\n)\n```\n\nVincenty's Formula for Great Circle Distance\n========================\nThe Vincenty formula provides improved accuracy over the Haversine implementation\nat the expense of some added complexity and diminished computational performance.\nUnlike the Haversine formula, Vincenty's solution assumes the sphere is oblate (flattened)\nwhich is a more appropriate shape for the Earth's actual curvature.\n\"\"\"\nfunction vincenty(\n          lat1::AbstractFloat,\n          lon1::AbstractFloat,\n          lat2::AbstractFloat,\n          lon2::AbstractFloat,\n          radiusA::AbstractFloat=EARTH_RADIUS_EQUATORIAL;\n          radiusB::AbstractFloat=EARTH_RADIUS_POLAR,\n          tol::AbstractFloat=1e-12,\n          maxiter::Int=1000,\n          verbose::Bool=true, args...)::AbstractFloat\n  lat1 = deg2rad(lat1)\n  lon1 = deg2rad(lon1)\n  lat2 = deg2rad(lat2)\n  lon2 = deg2rad(lon2)\n\n  a = radiusA\n  b = radiusB\n  ƒ = (a - b) / a\n  b = (1 - ƒ)*a\n\n  u1 = atan((1-ƒ)*tan(lat1))\n  u2 = atan((1-ƒ)*tan(lat2))\n  L = lon2 - lon1\n  sinσ = 0.\n  cosσ = 0.\n  cos2α = 0.\n  cos2σm = 0.\n  σ = 0.\n\n  λ = copy(L)\n  λ2 = λ\n  δ = 1. + tol\n  n = 0\n\n  while δ > tol && n < maxiter\n    n += 1\n    sinσ = sqrt( (cos(u2)*sin(λ))^2 + (cos(u1)*sin(u2)-sin(u1)*cos(u2)*cos(λ))^2 )\n    cosσ = sin(u1)*sin(u2) + cos(u1)*cos(u2)*cos(λ)\n    σ = atan(sinσ/cosσ)\n    sinα = (cos(u1)*cos(u2)*sin(λ))/sinσ\n    cos2α = 1 - sinα^2\n    cos2σm = cosσ - (2*sin(u1)*sin(u2))/cos2α\n    C = ƒ/16 * cos2α*(4 + ƒ*(4-3cos2α))\n\n    x1 = cos2σm + C*cosσ*(-1+2cos2σm^2)\n    x2 = σ + C*sinσ*x1\n    λ = L + (1-C)*ƒ*sinα*x2\n    δ = abs(λ-λ2)\n    λ2 = copy(λ)\n  end\n\n  if n == maxiter && δ > tol && verbose\n    println(\"Warning: vincenty formula did not converge to desired tolerance.\")\n  end\n\n  μ2 = cos2α * (a^2 - b^2)/(b^2)\n  A = 1 + μ2/16384*(4096 + μ2*(-768+μ2*(320-175μ2)))\n  B = (μ2/1024)*(256 + μ2*(-128+μ2*(74-47μ2)))\n\n  x3 = cos2σm + .25B*(cosσ*(-1+2cos2σm^2))\n  x4 = (1/6)*B*cos2σm*(-3+4sinσ^2)*(-3+4cos2σm^2)\n  Δσ = B*sinσ*(x3-x4)\n\n  return b*A*(σ - Δσ)\nend\n", "meta": {"hexsha": "d4aeb8bb10894fd3d2cc4560abdb1061a0023ec8", "size": 6047, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distance.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ZipCode.jl-0cef87d0-566b-5ace-96b7-ad13d8157ade", "max_stars_repo_head_hexsha": "70fe9e6c9639d884698229e9ca9f993439726d24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distance.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ZipCode.jl-0cef87d0-566b-5ace-96b7-ad13d8157ade", "max_issues_repo_head_hexsha": "70fe9e6c9639d884698229e9ca9f993439726d24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distance.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ZipCode.jl-0cef87d0-566b-5ace-96b7-ad13d8157ade", "max_forks_repo_head_hexsha": "70fe9e6c9639d884698229e9ca9f993439726d24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9955357143, "max_line_length": 93, "alphanum_fraction": 0.6479245907, "num_tokens": 1937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7741785811632579}}
{"text": "# circle.jl\n\nabstract type AbstractHyperSphere{N,T} <: EuclideanDomain{N,T} end\n\n\n\n\"\"\"\nThe unit sphere (of radius 1) in `N` dimensions.\n\"\"\"\nstruct UnitHyperSphere{N,T} <: AbstractHyperSphere{N,T} end\n\nUnitHyperSphere{N}() where N = UnitHyperSphere{N,Float64}()\n\nconst UnitCircle{T} = UnitHyperSphere{2,T}\nconst UnitSphere{T} = UnitHyperSphere{3,T}\n\nconvert(::Type{Domain{SVector{N,T}}}, d::UnitHyperSphere{N}) where {N,T} =\n    UnitHyperSphere{N,T}()\n\nindomain(x, ::UnitHyperSphere) = norm(x) == 1\n\napprox_indomain(x, ::UnitHyperSphere, tolerance) = 1-tolerance <= norm(x) <= 1+tolerance\n\nboundary(::UnitHyperBall{N,T}) where {N,T} = UnitHyperSphere{N,T}()\n\nisempty(::UnitHyperSphere) = false\n\n\"Create an ellipse curve with semi-axes lengths `a` and `b` respectively.\"\nellipse(a::Number, b::Number) = ellipse(promote(a,b)...)\nellipse(a::T, b::T) where {T <: Number} = scaling_map(a, b) * UnitCircle{T}()\n\n\"Create an ellipse-shaped domain with semi-axes lengths `a` and `b` respectively.\"\nellipse_shape(a::Number, b::Number) = ellipse_shape(promote(a,b)...)\nellipse_shape(a::T, b::T) where {T <: Number} = scaling_map(a, b) * UnitDisk{T}()\n\n\n\"\"\"\nThe map `[cos(2πt), sin(2πt)]` from `[0,1)` to the unit circle in `ℝ^2`.\n\"\"\"\nstruct UnitCircleMap{S,T} <: AbstractMap{S,T} end\n\nparameterization(d::UnitCircle) = UnitCircleMap{subeltype(d),eltype(d)}()\n\ndomain(d::UnitCircleMap{S}) where S = HalfOpenRightInterval{S}(0, 1)\n\nimage(m::UnitCircleMap{S}) where S = UnitCircle{S}()\n\napplymap(m::UnitCircleMap{S}, t) where S = SVector(cos(2*S(pi)*t), sin(2*S(pi)*t))\n\nfunction gradient(m::UnitCircleMap{S}, t) where S\n    a = 2*S(pi)\n    SVector(-a*sin(a*t), a*cos(a*t))\nend\n\n\n\"\"\"\n`AngleMap` is a left inverse of `UnitCircleMap`. A 2D vector `x` is projected onto\nthe intersection point with the unit circle of the line connecting `x` to the\norigin. The angle of this point, scaled to the interval `[0,1)`, is the result.\n\"\"\"\nstruct AngleMap{S,T} <: AbstractMap{S,T}\nend\n\ndomain(d::AngleMap{S,T}) where {S,T} = FullSpace{S}()\n\nrange(m::AngleMap{S,T}) where {S,T} = HalfOpenRightInterval{T}(0, 1)\n\nfunction applymap(m::AngleMap, x)\n    twopi = 2*convert(codomaintype(m), pi)\n    θ = atan(x[2],x[1])\n    if θ < 0\n        # atan2 returns an angle in (-π,π], convert to [0,2π) using periodicity.\n        θ += twopi\n    end\n    # And divide by 2π to scale to [0,1)\n    θ / twopi\nend\n\nleft_inverse(m::UnitCircleMap{S,T}) where {S,T} = AngleMap{T,S}()\n\nright_inverse(m::AngleMap{S,T}) where {S,T} = UnitCircleMap{T,S}()\n", "meta": {"hexsha": "f914bacea5f7ddcb3a9c66ea236d6ff47ad5a666", "size": 2501, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/domains/circle.jl", "max_stars_repo_name": "daanhb/DomainSets.jl", "max_stars_repo_head_hexsha": "0e96511ce953584b9d0b2cfead78f1e8116cae17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/domains/circle.jl", "max_issues_repo_name": "daanhb/DomainSets.jl", "max_issues_repo_head_hexsha": "0e96511ce953584b9d0b2cfead78f1e8116cae17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/domains/circle.jl", "max_forks_repo_name": "daanhb/DomainSets.jl", "max_forks_repo_head_hexsha": "0e96511ce953584b9d0b2cfead78f1e8116cae17", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5, "max_line_length": 88, "alphanum_fraction": 0.6721311475, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7741785803152225}}
{"text": "function agm(x::T, y::T) where {T<:Real}\n    a, b = x, y\n    epsilon = eps(min(a,b))\n\n    signbit(a) != signbit(b) && throw(DomainError(\"$a * $b must be nonnegative\"))\n\n    while abs(a-b) > epsilon\n     c = (a + b) * 0.5\n     b = sqrt(a * b)\n     a = c\n    end\n\n    return a\nend\n\nagm1(x::T) where {T<:Real} = agm(one(T), x)\n", "meta": {"hexsha": "ca2bfb842e5d6bf56b0122a9ff31f7d09a4e4ebf", "size": 324, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/special/agm.jl", "max_stars_repo_name": "UnofficialJuliaMirror/DoubleFloats.jl-497a8b3b-efae-58df-a0af-a86822472b78", "max_stars_repo_head_hexsha": "ccf0c6a690f81eec84caf080c99d58d11e72432d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 107, "max_stars_repo_stars_event_min_datetime": "2018-02-07T14:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:44:41.000Z", "max_issues_repo_path": "src/math/special/agm.jl", "max_issues_repo_name": "UnofficialJuliaMirror/DoubleFloats.jl-497a8b3b-efae-58df-a0af-a86822472b78", "max_issues_repo_head_hexsha": "ccf0c6a690f81eec84caf080c99d58d11e72432d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 125, "max_issues_repo_issues_event_min_datetime": "2018-04-15T13:56:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:12:12.000Z", "max_forks_repo_path": "src/math/special/agm.jl", "max_forks_repo_name": "UnofficialJuliaMirror/DoubleFloats.jl-497a8b3b-efae-58df-a0af-a86822472b78", "max_forks_repo_head_hexsha": "ccf0c6a690f81eec84caf080c99d58d11e72432d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2018-04-27T10:17:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:44:20.000Z", "avg_line_length": 19.0588235294, "max_line_length": 81, "alphanum_fraction": 0.5030864198, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.77417857447134}}
{"text": "using DifferentialEquations\nusing Plots\nplotlyjs()\n\n\n\n#constants\ng=9.81       #acceleration due to gravity [ms^-2]\nm=3000       #mass of capsule [Kg]\n\n#initial conditions\nu₀=[3,0.1,0.1,0.5]\nr₀=6\nv₀=0\n\n#function to compute lagrangian\nfunction lagrangian!(du,u,p,t)\n    θ,ω,ϕ,ψ=u\n    v=v₀\n    r=r₀+v*t\n    du[1]=dθ=ω\n    du[2]=dω=sin(θ)*cos(θ)*ψ^2-((2*v*ω)/r)+((g*sin(θ))/r)\n    du[3]=dϕ=ψ\n    du[4]=dψ=-((2*v*ψ)/r)-(2*cot(θ)*ω*ψ)\nend\n\n#time interval\ntspan=(0.0,20.0)\n\n#defining the problem and solving\nprob=ODEProblem(lagrangian!,u₀,tspan)\nsol1=solve(prob,saveat=0.1,reltol=1e-1,abstol=1e-4)\nsol2=solve(prob,saveat=0.1)\nsol3=solve(prob,saveat=0.1,reltol=1e-5,abstol=1e-8)\n\n#extracting solution\nU1=sol1[1:end,:]\n(θ1,ω1,ϕ1,ψ1)=[U1[x,:] for x in 1:size(U1,1)]\nt=sol1.t\n\nU2=sol2[1:end,:]\n(θ2,ω2,ϕ2,ψ2)=[U2[x,:] for x in 1:size(U2,1)]\nt=sol2.t\n\nU3=sol3[1:end,:]\n(θ3,ω3,ϕ3,ψ3)=[U3[x,:] for x in 1:size(U3,1)]\nt=sol3.t\n\n\n#plotting the solutions for different tolerances\n\np1=plot(sol1,vars=(0,1),label=\"rtol=1e-1,atol=1e-4\",\n    color=\"green\", xaxis=\"t (s)\", yaxis=\"θ (rad)\")\np2=plot!(p1,sol2,vars=(0,1),label=\"rtol=1e-3,atol=1e-6\",\n    color=\"blue\", xaxis=\"t (s)\", yaxis=\"θ (rad)\")\np3=plot!(p2,sol3,vars=(0,1),label=\"rtol=1e-5,atol=1e-8\",\n    color=\"red\", xaxis=\"t (s)\", yaxis=\"θ (rad)\")\ndisplay(plot(p3))\nsavefig(\"./plots/error_control_1.png\")\n\np4=plot(sol1,vars=(0,3),label=\"rtol=1e-1,atol=1e-4\",\n    color=\"green\", xaxis=\"t (s)\", yaxis=\"ϕ (rad)\")\np5=plot!(p4,sol2,vars=(0,3),label=\"rtol=1e-3,atol=1e-6\",\n    color=\"blue\", xaxis=\"t (s)\", yaxis=\"ϕ (rad)\")\np6=plot!(p5,sol3,vars=(0,3),label=\"rtol=1e-5,atol=1e-8\",\n    color=\"red\", xaxis=\"t (s)\", yaxis=\"ϕ (rad)\")\ndisplay(plot(p6))\nsavefig(\"./plots/error_control_2.png\")\n", "meta": {"hexsha": "ee756a45904390c93366fd32dab4ded33809298b", "size": 1712, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Modeling the Dragon Module as a Pendulum/Scripts/ex2-case-1-error-control.jl", "max_stars_repo_name": "Ramana-bharathi/modelling-recovery-module", "max_stars_repo_head_hexsha": "7d522aef4ae184f7ca9991056de7327e2a782eef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Modeling the Dragon Module as a Pendulum/Scripts/ex2-case-1-error-control.jl", "max_issues_repo_name": "Ramana-bharathi/modelling-recovery-module", "max_issues_repo_head_hexsha": "7d522aef4ae184f7ca9991056de7327e2a782eef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modeling the Dragon Module as a Pendulum/Scripts/ex2-case-1-error-control.jl", "max_forks_repo_name": "Ramana-bharathi/modelling-recovery-module", "max_forks_repo_head_hexsha": "7d522aef4ae184f7ca9991056de7327e2a782eef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8115942029, "max_line_length": 57, "alphanum_fraction": 0.6261682243, "num_tokens": 825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7741690801242722}}
{"text": "\"\"\"\n# Usage\n\n    solve(prob::SingleTermFODEProblem, h, GL())\nGrunwald Letnikov method for fractional ordinary differential equations\n\n```tex\n@INPROCEEDINGS{8742063,  \nauthor={Clemente-López, D. and Muñoz-Pacheco, J. M. and Félix-Beltrán, O. G. and Volos, C.},  \nbooktitle={2019 8th International Conference on Modern Circuits and Systems Technologies (MOCAST)},   \ntitle={Efficient Computation of the Grünwald-Letnikov Method for ARM-Based Implementations of Fractional-Order Chaotic Systems},\nyear={2019},   \ndoi={10.1109/MOCAST.2019.8742063}}\n```\n\"\"\"\nstruct GL <: FractionalDiffEqAlgorithm end\n\nfunction solve(FODE::SingleTermFODEProblem, h, ::GL)\n    @unpack f, α, u0, tspan = FODE\n    t0 = tspan[1]; T = tspan[2]\n    N::Int = floor(Int, (T-t0)/h)+1\n    c = zeros(Float64, N)\n\n    cp::Float64 = 1.0\n    for j = 1:N\n        c[j] = (1-(1+α)/j)*cp\n        cp = c[j]\n    end\n\n    # Initialization\n    y = zeros(Float64, N)\n    y[1] = u0\n\n    @fastmath @inbounds @simd for i = 2:N\n        right = 0\n        @fastmath @inbounds @simd for j=1:i-1\n            right += c[j]*y[i-j]\n        end\n        y[i] = f(t0+(i-1)*h, y[i-1])*h^α - right\n    end\n    return FODESolution(collect(t0:h:T), y)\nend", "meta": {"hexsha": "3e99b79bbff3afa6f61cff9bece735170d173083", "size": 1192, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/singletermfode/GL.jl", "max_stars_repo_name": "SciFracX/FractionalDiffEq.jl", "max_stars_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-11-05T12:49:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:57:20.000Z", "max_issues_repo_path": "src/singletermfode/GL.jl", "max_issues_repo_name": "SciFracX/FractionalDiffEq.jl", "max_issues_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-11-01T22:05:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:57:19.000Z", "max_forks_repo_path": "src/singletermfode/GL.jl", "max_forks_repo_name": "SciFracX/FractionalDiffEq.jl", "max_forks_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.380952381, "max_line_length": 128, "alphanum_fraction": 0.6258389262, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7741528274163919}}
{"text": "# Parts of this code were taken / derived from Graphs.jl. See LICENSE for\n# licensing details.\n\n\n\"\"\"\n    struct FloydWarshallState{T, U}\n\nAn [`AbstractPathState`](@ref) designed for Floyd-Warshall shortest-paths calculations.\n\"\"\"\nstruct FloydWarshallState{T, U<:Integer}<:AbstractPathState\n    dists::Matrix{T}\n    parents::Matrix{U}\nend\n\n@doc_str \"\"\"\nfloyd_warshall_shortest_paths(g, distmx=DefaultDistance())\nUse the [Floyd-Warshall algorithm](http://en.wikipedia.org/wiki/Floyd–Warshall_algorithm)\nto compute the shortest paths between all pairs of vertices in graph `g` using an\noptional distance matrix `distmx`. Return a [`FloydWarshallState`](@ref) with relevant\ntraversal information.\n\n### Performance\nSpace complexity is on the order of ``\\\\mathcal{O}(|V|^2)``.\n\"\"\"\nfunction floyd_warshall_shortest_paths{T}(\n    g::AbstractGraph,\n    distmx::AbstractMatrix{T} = DefaultDistance()\n)\n    U = eltype(g)\n    n_v = nv(g)\n    dists = fill(typemax(T), (Int(n_v),Int(n_v)))\n    parents = zeros(U, (Int(n_v),Int(n_v)))\n\n    # fws = FloydWarshallState(Matrix{T}(), Matrix{Int}())\n    for v in 1:n_v\n        dists[v,v] = zero(T)\n    end\n    undirected = !is_directed(g)\n    for e in edges(g)\n        u = src(e)\n        v = dst(e)\n\n        d = distmx[u,v]\n\n        dists[u,v] = min(d, dists[u,v])\n        parents[u,v] = u\n        if undirected\n            dists[v,u] = min(d, dists[v,u])\n            parents[v,u] = v\n        end\n    end\n    for w in vertices(g), u in vertices(g), v in vertices(g)\n        if dists[u,w] == typemax(T) || dists[w,v] == typemax(T)\n            ans = typemax(T)\n        else\n            ans = dists[u,w] + dists[w,v]\n        end\n        if dists[u,v] > ans\n            dists[u,v] = dists[u,w] + dists[w,v]\n            parents[u,v] = parents[w,v]\n        end\n    end\n    fws = FloydWarshallState(dists, parents)\n    return fws\nend\n\nfunction enumerate_paths(s::FloydWarshallState{T, U}, v::Integer) where T where U<:Integer\n    pathinfo = s.parents[v,:]\n    paths = Vector{Vector{U}}()\n    for i in 1:length(pathinfo)\n        if (i == v) || (s.dists[v,i] == typemax(T))\n            push!(paths, Vector{U}())\n        else\n            path = Vector{U}()\n            currpathindex = i\n            while currpathindex != 0\n                push!(path,currpathindex)\n                currpathindex = pathinfo[currpathindex]\n            end\n            push!(paths, reverse(path))\n        end\n    end\n    return paths\nend\n\nenumerate_paths(s::FloydWarshallState) = [enumerate_paths(s, v) for v in 1:size(s.parents,1)]\nenumerate_paths(st::FloydWarshallState, s::Integer, d::Integer) = enumerate_paths(st, s)[d]\n", "meta": {"hexsha": "c29207570b7f433daefa2b9053a8f15dcd993d6e", "size": 2626, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/shortestpaths/floyd-warshall.jl", "max_stars_repo_name": "AsileBcd/JohnsonCycles", "max_stars_repo_head_hexsha": "4928bc05eaaad75a6d05a1390be9f5840c68705e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/shortestpaths/floyd-warshall.jl", "max_issues_repo_name": "AsileBcd/JohnsonCycles", "max_issues_repo_head_hexsha": "4928bc05eaaad75a6d05a1390be9f5840c68705e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/shortestpaths/floyd-warshall.jl", "max_forks_repo_name": "AsileBcd/JohnsonCycles", "max_forks_repo_head_hexsha": "4928bc05eaaad75a6d05a1390be9f5840c68705e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8409090909, "max_line_length": 93, "alphanum_fraction": 0.6035795887, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7741528120279115}}
{"text": "# Practical Review: Extremum Estimators (Ch. 13)\n\n##\n#= \tLet's start with a simple problem, where we can get the the answers using\n\tanalytic methods. This will let us apply numeric methods, and we will be\n\table to verify that they give us the correct results. To start, let's\n\tdefine some data, and do the basic OLS computations\n=#\t\nusing Econometrics\nn = 5\nx = [ones(n) 1:n]\nβ = [10., -1.]\nϵ = randn(n)\ny = x*β + ϵ\nols(y,x);\n\n##\n\n#= \tOK, now let's do this as we would if we did not have access to\n\tthe analytic results. First, we compute the extremum estimator\n\tusing numeric minimization.\n=#\nusing Statistics, Optim\nobjᵢ = β -> (y-x*β).^2.  \t# iᵗʰ obs contrib to sum of squares\nobj = β -> mean(objᵢ(β))\t# average objective\ntol = 1e-08\nβhat = Optim.optimize(obj, zeros(2), LBFGS(), \n        \tOptim.Options(g_tol = tol,x_tol=tol,f_tol=tol);\n\t\t\tautodiff=:forward).minimizer\n\n##\n\n#=\tHow do we get the estimated standard errors, using extremum estimation\n\ttheory? We need estimators of ℐ, the covariance of the score \n\tcontributions, and 𝒥, the Hessian matrix.\n=#\n\n# the calculations to get ℐ hat\n\n# first, we need the score contributions, the matrix that collects\n# the derivatives of each observation's contribution to the objective\n\n# Note to self: remember crtl-enter will evaluate a single line.\n\nusing ForwardDiff\nsc =  ForwardDiff.jacobian(objᵢ, βhat) # get the score contributions\n# from theory, we know that sc = -2x.*ϵcat. Let's use this verify\n# that the automatic differentiation worked.\nsc - (-2x.*(y - x*βhat))\n\n##\n\n# Next, we use the score contributions to estimate ℐ \nℐhat = zeros(2,2)\nfor i = 1:n\n\tℐhat .+= sc[i,:]*sc[i,:]'\nend\nℐhat ./= n\n# you could also use simply cov(sc), which converges to the same thing.\n\n\n##\n\n# next, we need the estimate of the limiting Hessian, which is just\n# the Hessian of the objective function, at the estimate\n𝒥hat = ForwardDiff.hessian(obj, βhat)\n\n# We know that this should be 2x'x/n. Let's check:\n2x'x/n\n##\n\n# now, we can compute the estimated standard errors, to compare to what we saw\n# from the analytic results, above\nusing LinearAlgebra\nv∞ = inv(𝒥hat)*ℐhat*inv(𝒥hat) # this is the estimate of the limiting var of √n(β-β⁰) \nse = sqrt.(diag(v∞/n))   # to get small sample est. variance, divide by n\n\n##\n\n# the last problem is for a correctly specified model, Case I in the notes.\n# Let's look at an incorrectly specified model, Case III in the notes, to\n# verify that the extremum theory works here, too.\n\n# Let's work with Problem 1, in the exercises at the end of Chapter 13.\n# In this problem, the true model is quadratic, but we erroneously estimate\n# a linear model. The problem asks for an analytic solution. Here, let's\n# approach it numerically.\n# generate data\nusing Plots\nfunction dgp(n)\n\tx = sort(rand(n))\n\ty = 1. .- x.^2 + randn(n)\n\tx,y\nend\nx,y = dgp(100)\nscatter(x,y, legend=false, title=\"y = 1 - x² + N(0,1)\")\n\n##\n\n# Here's an OLS fit, just to have a look\nusing Econometrics\nn = 100\nx,y = dgp(n)\nX = [ones(n) x] # define regressor matrix for linear approximation about 0\nb, junk = ols(y,X)\nfitted = X*b\nplot!(x,fitted)\n\n##\n\n# We know that the pseudo-true parameter values are 7/6 and -1. Let's verify\n# that the OLS estimates are asymptotically normally distributed about these\n# values. To do this, we will construct asymptotic 100x(1-α)% confidence intervals,\n# and verify that the pseudo-true values lie inside them approximately 100x(1-α)% of\n# the times we repeat the procedure, at least when n is large enough\nusing LinearAlgebra, Statistics, Distributions\nn = 20 \t\t\t\t# try small and large values here,\n\t\t\t\t\t# to see accuracy of asymptotic approximation\nreps = 10000\nα = 0.05\t\t\t# try out 90, 95 and 99% CIs\ncrit = quantile(Normal(),1-α/2)\nβ⁰ = [7/6; -1.]\ninci = zeros(reps, 2)\nfor i = 1:reps\n\tx,y = dgp(n)\n\tX = [ones(n) x] # define regressor matrix for linear approximation about 0\n\tβhat, vβhat, junk = ols(y, X, silent=true)\n\tse = sqrt.(diag(vβhat))\n\tinci[i,:] = (β⁰ .>= βhat .- crit*se) .& (β⁰ .<= βhat .+ crit*se)\nend\nci = Int64(100*(1-α))\nprintln(\"Coverage of $ci% CIs\")\nmean(inci, dims=1) # these should be approximately 1-α, at least when n is large enough\n\n##\n\n# To conclude, this summary has shown that the extremum estimation theory is\n# working for two cases, a correctly specified model, and an incorrectly specified\n# model. We have seen how to get I and J, now to compute the asymptotic variance,\n# and how to verify that confidence intervals (which are computed using I and J)\n# have correct coverage, at least asymptotically.\n\n\n", "meta": {"hexsha": "e3a630def97a6f1258b51d617d17743dad6a507f", "size": 4515, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PracticalSummaries/13-ExtremumEstimators.jl", "max_stars_repo_name": "mcreel/EconometricsNotes", "max_stars_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-19T18:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T18:23:45.000Z", "max_issues_repo_path": "PracticalSummaries/13-ExtremumEstimators.jl", "max_issues_repo_name": "mcreel/EconometricsNotes", "max_issues_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PracticalSummaries/13-ExtremumEstimators.jl", "max_forks_repo_name": "mcreel/EconometricsNotes", "max_forks_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3541666667, "max_line_length": 87, "alphanum_fraction": 0.7083056478, "num_tokens": 1372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.774152803933474}}
{"text": "using ITensors,\n      LinearAlgebra,\n      QuadGK\n\nconst βc = 0.5*log(sqrt(2.0)+1.0)\n\nfunction ising_free_energy(β::Real,J::Real=1.0)\n  k = β*J\n  c = cosh(2.0*k)\n  s = sinh(2.0*k)\n  xmin = 0.0\n  xmax = π\n  integrand(x) = log(c^2+sqrt(s^4+1-2*s^2*cos(x)))\n  integral,err = quadgk(integrand, xmin, xmax)::Tuple{Float64,Float64}\n  return -(log(2.0)+integral/π)/(2.0*β)\nend\n\nfunction ising_magnetization(β::Real)\n β>βc && return (1.0-sinh(2.0*β)^(-4))^(1/8)\n return 0.0\nend\n\nfunction ising_mpo(sh::Tuple{Index,Index},sv::Tuple{Index,Index},\n                   β::Real,J::Real=1.0;\n                   sz::Bool=false,dual_lattice::Bool=true)\n  d = dim(sh[1])\n  T = ITensor(sh[1],sh[2],sv[1],sv[2])\n  if dual_lattice\n    for i = 1:d\n      T[i,i,i,i] = 1.0\n    end\n    sz && (T[1,1,1,1] = -T[1,1,1,1])\n    Q = [exp(β*J) exp(-β*J); exp(-β*J) exp(β*J)]\n    D,U = eigen(Symmetric(Q))\n    √Q = U*Diagonal(sqrt.(D))*U'\n    Xh1 = ITensor(vec(√Q),sh[1],sh[1]')\n    Xh2 = ITensor(vec(√Q),sh[2],sh[2]')\n    Xv1 = ITensor(vec(√Q),sv[1],sv[1]')\n    Xv2 = ITensor(vec(√Q),sv[2],sv[2]')\n    T = replacetags(T*Xh1*Xh2*Xv1*Xv2,\"1\",\"0\")\n  else\n    sig(s) = 1.0-2.0*(s-1)\n    E0 = -4.0\n    for s1 = 1:d, s2 = 1:d, s3 = 1:d, s4 = 1:d\n      E = sig(s1)*sig(s2)+sig(s2)*sig(s3)+sig(s3)*sig(s4)+sig(s4)*sig(s1)\n      val = exp(-β*(E-E0))\n      T[sh[1](s1),sv[2](s2),sh[2](s3),sv[1](s4)] = val\n    end\n  end\n  return T\nend\n\n", "meta": {"hexsha": "04ef8c9915ab5b1dbd43dd61be2310441e1e16b7", "size": 1394, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/2d_classical_ising.jl", "max_stars_repo_name": "nickrobinson251/ITensors.jl", "max_stars_repo_head_hexsha": "1f5e5aba3a3c9029282396c12bb01e54835a6f7e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-28T11:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-28T11:47:49.000Z", "max_issues_repo_path": "test/2d_classical_ising.jl", "max_issues_repo_name": "nickrobinson251/ITensors.jl", "max_issues_repo_head_hexsha": "1f5e5aba3a3c9029282396c12bb01e54835a6f7e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/2d_classical_ising.jl", "max_forks_repo_name": "nickrobinson251/ITensors.jl", "max_forks_repo_head_hexsha": "1f5e5aba3a3c9029282396c12bb01e54835a6f7e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-28T11:47:51.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-28T11:47:51.000Z", "avg_line_length": 26.3018867925, "max_line_length": 73, "alphanum_fraction": 0.5329985653, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238083, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7741243160869339}}
{"text": "\"\"\"\n    q4\n\nCompute the solution of the Poisson equation of heat conduction with a nonzero\nheat source. Quadrilateral four-node elements are used.\n\"\"\"\nmodule q4\n\nusing LinearAlgebra\nusing SparseArrays\nusing MeshCore.Exports\nusing MeshCore: @_check\nusing MeshSteward.Exports\nusing Elfel.Exports\nusing UnicodePlots\n\nA = 1.0 # length of the side of the square\nkappa =  1.0; # conductivity matrix\nQ = -6.0; # internal heat generation rate\ntempf(x, y) =(1.0 + x^2 + 2.0 * y^2);#the exact distribution of temperature\nN = 1000;# number of subdivisions along the sides of the square domain\n\nfunction genmesh()\n    conn = Q4block(A, A, N, N)\n    mesh = Mesh()\n    attach!(mesh, conn)\n    return mesh\nend\n\nfunction assembleKF(fesp, kappa, Q)\n    function integrate!(am, av, geom, elit, qpit, kappa, Q)\n        nedof = ndofsperel(elit)\n        ke = LocalMatrixAssembler(nedof, nedof, 0.0)\n        fe = LocalVectorAssembler(nedof, 0.0)\n        for el in elit\n            init!(ke, eldofs(el), eldofs(el))\n            init!(fe, eldofs(el))\n            for qp in qpit\n                Jac, J = jacjac(el, qp)\n                gradN = bfungrad(qp, Jac)\n                JxW = J * weight(qp)\n                N = bfun(qp)\n                for j in 1:nedof\n                    for i in 1:nedof\n                        ke[i, j] += dot(gradN[i], gradN[j]) * (kappa * JxW)\n                    end\n                    fe[j] += N[j] * Q * JxW\n                end\n            end\n            assemble!(am, ke)\n            assemble!(av, fe)\n        end\n        return am, av\n    end\n\n    elit = FEIterator(fesp)\n    qpit = QPIterator(fesp, (kind = :Gauss, order = 2))\n    geom = geometry(fesp.mesh)\n    am = start!(SysmatAssemblerSparse(0.0), ndofs(fesp), ndofs(fesp))\n    av = start!(SysvecAssembler(0.0), ndofs(fesp))\n\n    @time integrate!(am, av, geom, elit, qpit, kappa, Q)\n\n    return finish!(am), finish!(av)\nend\n\nfunction solve!(T, K, F, nu)\n    @time KT = K * T\n    @time T[1:nu] = K[1:nu, 1:nu] \\ (F[1:nu] - KT[1:nu])\nend\n\nfunction checkcorrectness(fesp)\n    geom = geometry(fesp.mesh)\n    ir = baseincrel(fesp.mesh)\n    T = attribute(ir.right, \"T\")\n    std = 0.0\n    for i in 1:length(T)\n        std += abs(T[i][1] - tempf(geom[i]...))\n    end\n    @_check (std / length(T)) <= 1.0e-9\nend\n\nfunction run()\n    mesh = genmesh()\n    fesp = FESpace(Float64, mesh, FEH1_Q4())\n    bir = boundary(mesh);\n    vl = connectedv(bir);\n    locs = geometry(mesh)\n    for i in vl\n        setebc!(fesp, 0, i, 1, tempf(locs[i]...))\n    end\n    numberfreedofs!(fesp)\n    numberdatadofs!(fesp)\n    @show nunknowns(fesp)\n    K, F = assembleKF(fesp, kappa, Q)\n    T = fill(0.0, ndofs(fesp))\n    gathersysvec!(T, fesp)\n    solve!(T, K, F, nunknowns(fesp))\n    scattersysvec!(fesp, T)\n    makeattribute(fesp, \"T\", 1)\n    checkcorrectness(fesp)\n    vtkwrite(\"q4-T\", baseincrel(mesh), [(name = \"T\",)])\nend\n\nend\n\n@time q4.run()\n# q4.run()\n", "meta": {"hexsha": "06ddbdb07ca4df4d5c33e1fafc94c5f887376cba", "size": 2893, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/heat/poisson/q4.jl", "max_stars_repo_name": "PetrKryslUCSD/Elfem.jl", "max_stars_repo_head_hexsha": "4bbd57db0541dd08c181936110f4753c2d6079d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-05-17T21:30:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T19:06:50.000Z", "max_issues_repo_path": "examples/heat/poisson/q4.jl", "max_issues_repo_name": "PetrKryslUCSD/Elfem.jl", "max_issues_repo_head_hexsha": "4bbd57db0541dd08c181936110f4753c2d6079d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-07-15T02:11:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-29T01:26:23.000Z", "max_forks_repo_path": "examples/heat/poisson/q4.jl", "max_forks_repo_name": "PetrKryslUCSD/Elfem.jl", "max_forks_repo_head_hexsha": "4bbd57db0541dd08c181936110f4753c2d6079d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5412844037, "max_line_length": 78, "alphanum_fraction": 0.5713791912, "num_tokens": 941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7741243044110865}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,jl:hydrogen\n#     text_representation:\n#       extension: .jl\n#       format_name: hydrogen\n#       format_version: '1.3'\n#       jupytext_version: 1.11.2\n#   kernelspec:\n#     display_name: Julia 1.6.2\n#     language: julia\n#     name: julia-1.6\n# ---\n\n# %% [markdown]\n# https://discourse.julialang.org/t/solving-a-petersen-matrix-with-julia/67674\n\n# %%\nusing DifferentialEquations\nusing Parameters\nusing StaticArrays\nusing Plots\n\n# %%\nfunction f(u, p, t)\n    @unpack M, k1, kf, kr, kcat = p\n    A, B, S, E, ES, P = u\n    v = SVector(k1*A*B^2, kf*E*S, kr*ES, kcat*ES)\n    M*v\nend\n\n# %%\nM = [\n    -1  0  0  0\n    -2  0  0  0\n    +1 -1 +1  0\n     0 -1 +1 +1\n     0 +1 -1 -1\n     0  0  0 +1\n]\n\np = (\n    M = SMatrix{6, 4, Float64}(M),\n    k1 = 1.0, \n    kf = 1.0, \n    kr = 1.0, \n    kcat = 1.0, \n)\n\nu0 = SVector(\n    #= A  =# 1.5, \n    #= B  =# 1.2, \n    #= S  =# 0.0, \n    #= E  =# 1.0, \n    #= ES =# 0.0, \n    #= P  =# 0.0,\n)\n\ntspan = (0.0, 10.0)\n\n# %%\nprob = ODEProblem(f, u0, tspan, p)\nsol = solve(prob)\nlabel = [\"A\" \"B\" \"S\" \"E\" \"ES\" \"P\"]\nlinestyle = [:dash :dash :dashdot :dashdot :solid :solid]\nplot(sol; label, linestyle, lw=1.5)\n\n# %%\nfunction g(u, p, t)\n    @unpack M, k1, kf, kr, kcat = p\n    A, B, S, E, ES, P = u\n    dA = -k1*A*B^2\n    dB = -2k1*A*B^2\n    dS = k1*A*B^2 - kf*E*S + kr*ES\n    dE  = -kf*E*S + kr*ES + kcat*ES\n    dES =  kf*E*S - kr*ES - kcat*ES\n    dP = kcat*ES\n    SVector(dA, dB, dS, dE, dES, dP)\nend\n\n# %%\nprob = ODEProblem(g, u0, tspan, p)\nsol = solve(prob)\nlabel = [\"A\" \"B\" \"S\" \"E\" \"ES\" \"P\"]\nlinestyle = [:dash :dash :dashdot :dashdot :solid :solid]\nplot(sol; label, linestyle, lw=1.5)\n\n# %%\n", "meta": {"hexsha": "5645cc660d1558412e1fdeca04f4a219a5ae21aa", "size": 1674, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0019/Petersen matrix.jl", "max_stars_repo_name": "genkuroki/public", "max_stars_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-06-06T00:33:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T06:56:08.000Z", "max_issues_repo_path": "0019/Petersen matrix.jl", "max_issues_repo_name": "genkuroki/public", "max_issues_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0019/Petersen matrix.jl", "max_forks_repo_name": "genkuroki/public", "max_forks_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-02T11:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T11:46:05.000Z", "avg_line_length": 18.6, "max_line_length": 78, "alphanum_fraction": 0.5035842294, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.8740772466456689, "lm_q1q2_score": 0.7741103280932905}}
{"text": "# This file investigates MSE with respect to free variables \n\nusing FractalTools \nusing GeometryBasics\nusing Makie \n\n# Construct interpolation data  \nf(x, y) = [\n    x^2 + y^2 + 1, \n    x^2 - y^2\n    ]\n# ngon = Triangle(\n#     Point(BigFloat(0.), BigFloat(0.)), \n#     Point(BigFloat(1.), BigFloat(0.)), \n#     Point(BigFloat(0.5), BigFloat(1.)))\n\nngon = Triangle(\n    Point(BigFloat(-5.), BigFloat(-5.)), \n    Point(BigFloat(5), BigFloat(-5.)), \n    Point(BigFloat(0), BigFloat(5.)))\nnpts = 100\npts = getdata(f, ngon, npts)\n\n# Construct test data \ntpts = getdata(ngon, npts)\nntpts = length(tpts)\n\n# Compute errors \nfvals = getindex.(map(pt -> f(pt...), tpts), 1)\nfreevars = 0.001 : 0.001 : 0.025 \nmse = map(freevars) do freevar\n    interp = interpolate(pts, HInterp2D(fill(freevar, 2, 2)))\n    ivals = getindex.(map(pt -> interp(pt...), tpts), 1)\n    sum((fvals - ivals).^2) / ntpts\nend \n\n# Plot mse \nfig = Figure() \nax = fig[1, 1] = Axis(fig, xlabel=\"Free Variable\", ylabel=\"MSE\", title=\"2D Hidden Interpolation MSE\") \nstem!(ax, freevars, mse, color=:black)\nsave(joinpath(@__DIR__, \"hinterp2d_mse.png\"), fig)\ndisplay(fig)\n", "meta": {"hexsha": "c16cf878baf6a2ca34cf754dd7a3603667428bd8", "size": 1124, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiment_1/interpolation_mse_vs_freevars/hinterp2d/hinterp2d.jl", "max_stars_repo_name": "zekeriyasari/FractalTools.jl", "max_stars_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-08T12:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T12:50:16.000Z", "max_issues_repo_path": "experiment_1/interpolation_mse_vs_freevars/hinterp2d/hinterp2d.jl", "max_issues_repo_name": "zekeriyasari/FractalTools.jl", "max_issues_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-09-05T18:22:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T10:09:46.000Z", "max_forks_repo_path": "experiment_1/interpolation_mse_vs_freevars/hinterp2d/hinterp2d.jl", "max_forks_repo_name": "zekeriyasari/FractalTools.jl", "max_forks_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1395348837, "max_line_length": 102, "alphanum_fraction": 0.6325622776, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7741072277081767}}
{"text": "#!/usr/bin/julia\n\n# Trizen\n# 17 September 2016\n# https://github.com/trizen\n\n# A decently efficient algorithm for computing the results of the Kempner/Smarandache function.\n\n# See also: https://projecteuler.net/problem=549\n#           https://en.wikipedia.org/wiki/Kempner_function\n#           http://mathworld.wolfram.com/SmarandacheFunction.html\n\n# ∑S(i) for 2 ≤ i ≤ 10^2 == 2012\n# ∑S(i) for 2 ≤ i ≤ 10^6 == 64938007616\n# ∑S(i) for 2 ≤ i ≤ 10^8 == 476001479068717\n\nusing Primes\n\nfunction smarandache(n::Int64, cache)\n\n    isprime(n) && return n\n\n    f = factor(n)\n\n    count = 0\n    distinct = true\n    for v in values(f)\n        count += v\n        if (distinct && v != 1)\n            distinct = false\n        end\n    end\n\n    distinct && return maximum(keys(f))\n\n    if (length(f) == 1)\n\n        k = collect(keys(f))[1]\n\n        (count <= k) && return k*count\n\n        if haskey(cache, n)\n            return cache[n]\n        end\n\n        max = k*count\n        ff  = factorial(BigInt(max - k))\n\n        while (ff % n == 0)\n            max -= k\n            ff /= max\n        end\n\n        cache[n] = max\n        return max\n    end\n\n    arr = Int64[]\n\n    for (k,v) in f\n        push!(arr, v == 1 ? k : smarandache(k^v, cache))\n    end\n\n    maximum(arr)\nend\n\n#\n## Tests\n#\n\nfunction test()\n    cache = Dict{Int64, Int64}()\n\n    limit = 10^2\n    sumS = 0\n\n    for k in 2:limit\n        sumS += smarandache(k, cache)\n    end\n\n    println(\"∑S(i) for 2 ≤ i ≤ $limit == $sumS\")\n\n    if (limit == 100 && sumS != 2012)\n        warn(\"However that is incorrect! (expected: 2012)\")\n    end\nend\n\ntest()\n", "meta": {"hexsha": "40d1558efd77863b472568be385c344dd7a3a0a7", "size": 1588, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Math/smarandache_function.jl", "max_stars_repo_name": "trizen/julia-scripts", "max_stars_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-03-22T09:38:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T21:38:31.000Z", "max_issues_repo_path": "Math/smarandache_function.jl", "max_issues_repo_name": "trizen/julia-scripts", "max_issues_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/smarandache_function.jl", "max_forks_repo_name": "trizen/julia-scripts", "max_forks_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8426966292, "max_line_length": 95, "alphanum_fraction": 0.5346347607, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7741072277081767}}
{"text": "\"\"\"\n# Available lower level routines\n* [`besseljs3d`](@ref) spherical Bessel function eval\n\"\"\"\nfunction lower_level_routs() end\n\n\"\"\"\n    function fj, fjder = besseljs3d(nterms,z;scale=1.0,ifder=0)\nThis subroutine evaluates the first `nterms` spherical Bessel \nfunctions, and if requested, their derivatives.\nIt incorporates a scaling parameter `scale` so that\n      \n      \tfjs_n(z)=j_n(z)/SCALE^n\n      \tfjder_n(z)=\\\\frac{\\\\partial fjs_n(z)}{\\\\partial z}\n# Input\n* `nterms::Integer` order of expansion of output array `fjs` \n* `z::ComplexF64` argument of the spherical Bessel functions\n* `scale::Float64` scaling factor\n* `ifder::Integer1` flag indicating whether to calculate `fjder`\n      \t          0\tNO\n      \t          1\tYES\nOUTPUT:\n* `fjs::Array{ComplexF64}` array of length `nterms+1` of scaled Bessel functions.\n* `fjder::Array{ComplexF64}` array of derivatives of scaled Bessel functions, if requested.\n\"\"\"\nfunction besseljs3d(nterms::Integer,z::ComplexF64;scale::Float64=1.0,\n                    ifder::Integer=0)\n\n    @assert (nterms >= 0)\n    if (ifder !=0 && ifder != 1)\n        @warn \"unexpected value in ifder, no ders computed\"\n    end\n\n    fjs = Array{ComplexF64}(undef,nterms+1)\n    fjder = ComplexF64(0)\n\n    \n    \n    if ifder == 1\n        fjder = Array{ComplexF64}(undef,nterms+1)\n    end\n    \n    # fortran interface\n    # subroutine besseljs3d(nterms,z,scale,fjs,ifder,fjder)\n    \n    ccall((:besseljs3d_,libfmm3d),Cvoid,(Fi,Fc,Fd,Fc,Fi,Fc),\n          nterms,z,scale,fjs,ifder,fjder)\n\n    if ifder != 1\n        fjder = nothing\n    end\n\n    return fjs, fjder\n    \nend\n", "meta": {"hexsha": "644c18e470f2269f9ddf3652340cc79fd78059ea", "size": 1591, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/src/lower_level_routines.jl", "max_stars_repo_name": "mipals/FMM3D", "max_stars_repo_head_hexsha": "ee380988cb1236568f2ff87c2fb949c82b493132", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-10T09:23:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-10T09:23:58.000Z", "max_issues_repo_path": "julia/src/lower_level_routines.jl", "max_issues_repo_name": "mipals/FMM3D", "max_issues_repo_head_hexsha": "ee380988cb1236568f2ff87c2fb949c82b493132", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/src/lower_level_routines.jl", "max_forks_repo_name": "mipals/FMM3D", "max_forks_repo_head_hexsha": "ee380988cb1236568f2ff87c2fb949c82b493132", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4107142857, "max_line_length": 91, "alphanum_fraction": 0.6511627907, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857204, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7741072237853313}}
{"text": "\n\"\"\"\nThis file checks whether QuadGK.quadgk() can integrate numerically to arbitrary precision using BigFloat types. To check, I look at the integral:\n\n    ∫_0^1 cosh(xt) dt\n\nwhich has a known closed analytic form:\n\n    sinh(x)/x,  x!=0\n\nwhich we can use for comparison. x has to be parsed as a BigFloat type using\nBigFloat(\"\\$x\") (remove space in actual code) NOT BigFloat(x) which would just convert a Float64 type to a BigFloat (and so would only be accurate to 64 bits). To check that passing BigFloat(\"\\$x\") into sinh(x)/x gives an accurate arbitrary precision answer (and not plagued by rounding errors), I checked with wolframalpha answers which does produce arb. prec. answers and they matched and so passing BigFloat(\"\\$x\") into sinh(x)/x gives a good check of whether quadgk above works to arb. prec. too.\n\nI confirmed that quadgk can give arb prec answers (I just using it incorrectly previously to give Float64 accurate results), so now using the correct method, I convert hyperbolic_integral_two() from check_hyperbolic_integral.jl:\n\n    β/2 ∫_0^1 (1 - cosh(Ωβ(1-x)/2)) cosh(xβ/2) / (a^2 - β^2 x^2/4 - bcosh(vβx/2))^{3/2} dx\n\ninto arb prec version and see what it gives. Spoilers: it's super slow, further confirmation that it's now arb prec.\n\"\"\"\n\n\"\"\"\nThis function just evaluates the integral:\n\n    ∫_0^1 cosh(xt) dt\n\nusing quadgk. To make it arbitrary precision, the limits have to be parsed properly into a BigFloat type using BigFloat(\"#\") and the absolute tolerance of the integration has to be set to the machine accuracy of your required precision. This is obtained using eps(x::BigFloat) (e.g. eps(Float64) ~ 2.22e-16) and set with atol = eps(x::BigFloat). The precision of the BigFloats can then be changed using setprecision(BigFloat, precision::Int) externally.\n\"\"\"\nfunction cosh_integral(x)\n    err = eps(x)\n    integrand(t) = cosh(x * t)\n    integral = quadgk(t -> integrand(t), BigFloat(\"0\"), BigFloat(\"1\"), atol = err)\nend\n\n\"\"\"\nJust the exact closed analytic answer to the cosh integral used for comparison. x has to be parsed as a BigFloat(\"#\") before passing into the function to evaluate it at higher precision properly.\n\"\"\"\nfunction exact_form(x)\n    sinh(x) / x\nend\n\n\"\"\"\nCheck outputs of the two above functions.\n\"\"\"\n\nsetprecision(BigFloat, 128) # set the precision of the BigFloat types.\nx_range = BigFloat(\"5\")\n\n# for bits = 128 and x_range = BigFloat(\"5\") if get:\n# 0.005659 seconds (13.49 k allocations: 768.068 KiB)\n@time exact = [exact_form(x) for x in x_range]\n# exact = fill(14.84064211555775179540189439921291311993)\n@show(exact)\n# 0.374177 seconds (1.00 M allocations: 46.879 MiB, 3.29% gc time)\n@time integral = [cosh_integral(x) for x in x_range]\n# fill((14.84064211555775179540189439921291311988, 2.350988701644575015937473074444491355637e-38))\n@show(integral)\n# Can see that the integral uses large memory allocations. Last two digits differing is common for BigFloat precisions (natural rounding error from float arithmatic) but we can see that the answers match to 128 bit precision.\n\n\"\"\"\nUsing the arbitrary precision quadgk method used above, apply this to the hyperbolic integral I have been trying to solve i.e. hyperbolic_integral_one() in check_hyperbolic_integrals.jl. I actually use hyperbolic_integral_two() here as the change of variables to the limits [0,1] makes it easier for quadgk to evaluate at higher βs.\n\nThis allocates a lot of memory to evaluating the integral. So I did use @code_typewarn to check that there are no type-stabilities, but it did not find any so I think this large memory allocation is just a result of small atol set by the machine precision. For 128 bits this is atol ~ 1.93e-34.\n\"\"\"\nfunction hyperbolic_integral_two(Ω, β, α, v, w)\n\n    err = eps(Ω)\n\n    # Initialise constants.\n    R = (v^2 - w^2) / (w^2 * v)\n    a = sqrt(β^2 / 4 + R * β * coth(β * v / 2))\n    b = R * β / sinh(β * v / 2)\n\n    coefficient = 2 * α * β^(3 // 2) * v^3 / (3 * sqrt(π) * sinh(β / 2) * w^3)\n\n    integrand(x) = (1 - cosh(Ω * β * (1 - x) / 2)) * cosh(x * β / 2) / (a^2 - β^2 * x^2 / 4 - b * cosh(v * β * x / 2))^(3 // 2)\n\n    integral = quadgk(x -> integrand(x), BigFloat(\"0.0\"), BigFloat(\"1.0\"), atol = err)\n\n    return coefficient * β * integral[1] / 2\nend\n\n\"\"\"\nCheck output and timing of the above function.\n\"\"\"\n\nsetprecision(BigFloat, 128)\nΩ_range = [BigFloat(\"12.01\")]\nβ = BigFloat(\"4.0\")\nα = BigFloat(\"7.0\")\nv = BigFloat(\"5.8\")\nw = BigFloat(\"1.6\")\n# For Ω_range = [BigFloat(\"12.01\")], β = BigFloat(\"4.0\"), α = BigFloat(\"7.0\"), v = BigFloat(\"5.8\"), w = BigFloat(\"1.6\") I get:\n# 209.267907 seconds (1.02 G allocations: 37.016 GiB, 5.82% gc time)\n@time hyp = hyperbolic_integral_two.(Ω_range, β, α, v, w)\n# hyp = BigFloat[-7.214150399279151977978320029665100466133e+09]\n@show(hyp)\n# This takes a LONG TIME to evaluate, with a massive 1.02 G allocations to allocate 37.016 GiB memory!\n", "meta": {"hexsha": "125779c43d094e2b86f7ffa62aec7857d2677151", "size": 4853, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "arb/quadgk_test.jl", "max_stars_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_stars_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-07-26T17:46:18.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-26T17:46:18.000Z", "max_issues_repo_path": "arb/quadgk_test.jl", "max_issues_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_issues_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arb/quadgk_test.jl", "max_forks_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_forks_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.5204081633, "max_line_length": 500, "alphanum_fraction": 0.7088398928, "num_tokens": 1475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564154, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7740995695350226}}
{"text": "##############################\n## by Qin Yu, Nov 2018\n## using Julia 1.0.1\n##############################\n\n############################## Starting here:\n# If this gives error, please call:\n# using Pkg # Julia 1.0.1 only\n# Pkg.add(\"Plots\")\n# Pkg.add(\"GR\")\n\nusing LinearAlgebra\nusing Plots\nusing Printf\n\n############################## Linear Regression with Polynomial Basis on Simple Dataset:\n# Prepare Data\n# Let's try to see the effect of polynomial basis,\n# on this extremely simple dataset, S:\nS = [(1,3),(2,2),(3,0),(4,5)]\nplot(S, line=:scatter, lab=\"data set\")\n\nx = [x[1] for x in S]\ny = [y[2] for y in S]\n\n# Formulae - Find 𝝎:\nphik(x, k) = [xi^k for xi in x]  # ϕₖ(𝒙) = ..., for vector 𝒙, all inputs\nphi1tok(x, k) = [phik(x, i) for i in 0:k-1]  # Φ(𝒙) = 𝒙 ⋅ 𝝋 = 𝒙 ⋅ (ϕ₁(), ϕ₂(), ..., ϕₖ())\ntransformed_x_kk(x, k) = hcat(phi1tok(x, k)...)  # Φ(𝒙) as a matrix\nw_k(x, y, k) = transformed_x_kk(x, k) \\ y  # 𝝎 = Φ\\𝒚\n\n# Formulae - Equation of Fitted Regression Line:\nw_phi_k(x_test, x_train, y, k) = dot(transformed_x_kk(x_test, k), w_k(x_train, y, k))  # ̂𝑦 = Φ(𝑥) ⋅ 𝝎\n\nplot(S, line=:scatter, lab=\"data set\", legend=:bottomright)\nW = zeros(4, 4)\nfor i = 1:4\n    𝒘Φ(x_test) = w_phi_k(x_test, x, y, i)\n    display(plot!(𝒘Φ, 0, 4, lab=\"k = $i\"))\n    W[i,1:i] = w_k(x, y, i)\n\n    # print the formulae for these curves\n    print(\"k = $i, f(x) = \")\n    for j = 1:i\n        j > 1 && print(\" + \")\n        @printf \"%.2f\" W[i,j]\n        j > 1 && print(\"x^$(j-1)\")\n    end\n    print(\"\\n\")\nend\nsavefig(\"./graph/1.1.pdf\")\n\n\n############################## Training Error\n# SSE = 𝚺ᵢ(𝑦ᵢ - ̂𝑦ᵢ)² = 𝚺ᵢ(𝑦ᵢ - Φ(𝑥ᵢ) ⋅ 𝝎)²\n# MSE = SSE/N, where N = number_of_rows(input_data_set), here is S\n# (here I use N as the book ESLII uses, standing for m in qestions)\nsse_k(x, y, k) = sum((y - transformed_x_kk(x, k) * w_k(x, y, k)).^2)\nmse_k(x, y, k) = sse_k(x, y, k) / first(size(y))\n\nMSE = [mse_k(x, y, i) for i = 1:4]\nplot(MSE, xlabel=\"k\", lab=\"MSE\")\nsavefig(\"./graph/1.2.pdf\")\n", "meta": {"hexsha": "db9b04bfc3c352920075222a18a4a5aa2e1597b3", "size": 1951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1.Linear_Regression_Basis_Function.jl", "max_stars_repo_name": "qin-yu/julia-regression-boston-housing", "max_stars_repo_head_hexsha": "6ad1096f88c46688e5a7cfdbe10aba02f9075cdc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-03-07T13:44:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T06:42:02.000Z", "max_issues_repo_path": "1.Linear_Regression_Basis_Function.jl", "max_issues_repo_name": "qin-yu/ml-julia-boston-housing", "max_issues_repo_head_hexsha": "6ad1096f88c46688e5a7cfdbe10aba02f9075cdc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1.Linear_Regression_Basis_Function.jl", "max_forks_repo_name": "qin-yu/ml-julia-boston-housing", "max_forks_repo_head_hexsha": "6ad1096f88c46688e5a7cfdbe10aba02f9075cdc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-02-04T09:47:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-10T02:24:53.000Z", "avg_line_length": 30.484375, "max_line_length": 102, "alphanum_fraction": 0.5351101999, "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582995, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7740995662254603}}
{"text": "export RSA, rsa_encrypt, rsa_decrypt, coprime_inv_mod\n\nusing Primes: nextprime\n\nusing RingSignature.Util\n\nstruct EGCDResult{T<:Integer}\n    \"Bézout coefficient x\"\n    x::T\n\n    \"Bézout coefficient y\"\n    y::T\n\n    \"greatest common divisor\"\n    gcd::T\n\n    \"a / gcd\"\n    quot_a::T\n\n    \"b / gcd\"\n    quot_b::T\nend\n\n#=\n\ns` is the coefficient of `a` throughout the process of successive divisions, so is `t` to `b`.\n\n$r_k = a s_k + b t_k$ always holds (easy to prove by induction).\n\nSee https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Proof for details.\n\n=#\n\"Extended GCD\"\nfunction egcd(a::T, b::T)::EGCDResult{T} where T<:Integer\n    (r0, r) = (a, b)\n    (s0, s) = (one(T), zero(T))\n    (t0, t) = (zero(T), one(T))\n\n    while !iszero(r)\n        q = r0 ÷ r\n        (r0, r) = (r, r0 - r * q)\n        (s0, s) = (s, s0 - s * q)\n        (t0, t) = (t, t0 - t * q)\n    end\n\n    EGCDResult(s0, t0, r0, t, s)\nend\n\n#=\nWhen a and b are coprimes,\n\n    a x + b y = gcd(a, b)  =>  a x = 1 (mod b)\n=#\n\n\"Precondition: `x` and `m` are coprime\"\nfunction coprime_inv_mod(x::T, m::T)::T where T<:Integer\n    inv_x = egcd(x, m).x\n    inv_x < 0 ? inv_x + m : inv_x\nend\n\n\"Generates a `n_bits`-bit random prime\"\nfunction random_prime(n_bits::Int)::BigInt\n    # √2 × 2^(n_bits - 1)\n    lower = BigInt(round(2 ^ (n_bits - 0.5)))\n    upper = big(2) ^ n_bits - 1\n    while true\n        p = nextprime(rand(lower:upper))\n        if p <= upper\n            return p\n        end\n    end\nend\n\nstruct RSA\n    \"Key size in bits\"\n    key_size::Int\n\n    \"The `(e, n)` pair\"\n    public_key::Tuple{BigInt, BigInt}\n\n    \"The `(d, n)` pair\"\n    private_key::Tuple{BigInt, BigInt}\n\n    function RSA(key_size::Int, e::BigInt=big(65537))\n        if key_size % 8 != 0\n            error(\"`key_size` is not a multiple of 8\")\n        end\n\n        while true\n            p = random_prime(key_size ÷ 2)\n            q = random_prime(key_size ÷ 2)\n            if p == q\n                continue\n            end\n\n            # Better to use Carmichael's totient\n            totient = (p - 1) * (q - 1)\n            if egcd(e, totient).gcd != 1\n                continue\n            end\n            # FIXME: also need to check the #bits of `p - q` is enough\n\n            n = p * q\n            d = coprime_inv_mod(e, totient)\n            pub_key = (e, n)\n            pri_key = (d, n)\n            return new(key_size, pub_key, pri_key)\n        end\n    end\nend\n\nfunction rsa_encrypt(rsa::RSA, m::BigInt)::BigInt\n    (e, n) = rsa.public_key\n    powermod(m, e, n)\nend\n\nfunction rsa_decrypt(rsa::RSA, c::BigInt)::BigInt\n    (d, n) = rsa.private_key\n    powermod(c, d, n)\nend\n\nfunction rsa_encrypt(rsa::RSA, m_bytes::Vector{UInt8})::Vector{UInt8}\n    m = convert(BigInt, m_bytes)\n    c = rsa_encrypt(rsa, m)\n    convert(Vector{UInt8}, c)\nend\n\nfunction rsa_decrypt(rsa::RSA, c_bytes::Vector{UInt8})::Vector{UInt8}\n    c = convert(BigInt, c_bytes)\n    m = rsa_decrypt(rsa, c)\n    convert(Vector{UInt8}, m)\nend\n", "meta": {"hexsha": "c7308208e885cc3453af7496fb189601085d8698", "size": 2953, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "RingSignature/src/rsa.jl", "max_stars_repo_name": "gyk/TrivialSolutions", "max_stars_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T05:51:37.000Z", "max_issues_repo_path": "RingSignature/src/rsa.jl", "max_issues_repo_name": "gyk/TrivialSolutions", "max_issues_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RingSignature/src/rsa.jl", "max_forks_repo_name": "gyk/TrivialSolutions", "max_forks_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2030075188, "max_line_length": 94, "alphanum_fraction": 0.557399255, "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799462157138, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7740828027954004}}
{"text": "\n\n### Algoritms and Recursion #####\n\n# Guess-and-check algoritm\n\n\n\nfunction guessandckeck(x)\n    #initialize variable\n    counter = 1\n    # algoritm\n    for guess in 0:abs(x)\n        if guess^3 > abs(x)\n            println(\"\\n$x is not a perfect cube!\")\n            break\n        end\n        if guess^3 != abs(x)\n            println(counter, \"\\tGuess = $guess\\tGuess Cubed = $(guess^3)\")\n            counter += 1\n        else\n            if x < 0\n                guess = -guess\n            end\n            println(counter, \"\\tGuess = $guess\\tGuess cubed = $(guess^3)\")\n            println(\"\\nThe cube root of $x is $guess.\")\n            break\n        end\n    end\nend\n\nguessandckeck(7)\nguessandckeck(8)\nguessandckeck(-8)\n\n# guess and check only works for cubed value and not perfect for negative value. So lets try another algoritm\n\n# Approximate solution\n\nfunction approximation(x)\n\n    # initialize\n    guess = 0.0\n    counter = 1\n    increment = 0.01\n    sensetivity = 0.1\n\n    # algoritm\n    while abs(guess^3 - x) >= sensetivity && abs(guess^3) <= abs(x)\n        println(counter, \"\\tGuess = $guess\\tGuess cubed = $(guess^3)\")\n        guess += increment\n        counter += 1\n    end\n\n    println(counter, \"\\tGuess = $guess\\tGuess cubed = $(guess^3)\")\n    guess = round(guess, digits = 2)\n    x < 0 ? guess = -guess : guess = guess\n    println(\"\\nThe cube root of $x is approximately $guess.\")\nend\n\napproximation(6)\n\n\n# approximation algoritm works fine but not efficient for large numbers.  So,  Lets look at another algoritm\n\n# Binary search algoritm\n\nfunction binarysearch(x)\n\n    # initialize\n\n    low = 0\n    high = x\n    guess = (low + high) /2\n    counter = 1\n    sensetivity = 0.01\n\n    #algoritm\n\n    while abs(guess^3 -x) ≥ sensetivity\n        println(counter, \"\\tGuess = $guess\\tGuess cubed = $(guess^3)\")\n\n        if abs(guess^3) < abs(x)\n            low = guess\n        else\n            high = guess\n        end\n\n        guess  = (low + high) /2\n        counter += 1\n        \n    end\n    println(counter, \"\\tGuess = $guess\\tGuess cubed = $(guess^3)\")\n    guess = round(guess, digits = 3)\n    println(\"\\nThe cube root of $x is approximately $guess.\")\nend\n\nbinarysearch(6)\n\n\n# performance comparation\n\nusing BenchmarkTools\n\n@benchmark guessandckeck(1_000_000)\n@benchmark approximation(1_000_000)\n@benchmark binarysearch(1_000_000)\n\n\n\n\n# Recursion \n\n# recursion is a process that divides a problem into sub problem to solve larger one\n\n# think on multipication, Z × 5  =  z + z + z + z + z\n\n\n# multipication as iteravive solution\n\nfunction multi_iterative(x,y)\n    result = 0\n\n    for i in 1:y\n        result += x\n        println(\"$i\\t$x * $i\\t= $result\")\n    end\n\n    println(\"\\n$x * $y = $result\\n\")\n    return result \nend\n\n\nmulti_iterative(5,10)\n\n# multipication as recursion\n\nfunction multi_recursive(x,y)\n    if y == 1\n\n        println(\"multi_recursive($x, $y)\\t = $x\\n\")\n        return x\n    else\n\n        println(\"multi_recursive($x, $y)\\t = $x + multi_recursive($x, $(y - 1))\")\n        return x + multi_recursive(x, y - 1)\n    end\n    \nend\n\n\nmulti_recursive(5,10)\n\n# factorial as iterative method\n\nfunction FactorialIterative(x)\n    result = 1\n\n    for i in 1:x\n        result *= i\n\n        println(\"$i factorial = $result\")\n    end\n\n    println(\"\\nThe Factorial of $x is $result\\n\")\n    return result\nend\n\nFactorialIterative(5)\n\n# factorial as recursion method\n\nfunction FactorialRecursive(x)\n\n    if x == 1\n\n        println(\"FactorialRecursive($x) = $x\\n\")\n        return 1\n    else\n        println(\"FactorialRecursive($x) = $x * FactorialRecursive($(x - 1))\")\n        return x * FactorialRecursive(x - 1)\n    end\nend\n\n\n\n\n\n", "meta": {"hexsha": "b51ff299a75c992733e836e36e22383a7b092b9c", "size": 3645, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Notebooks/lecture4-1.jl", "max_stars_repo_name": "fmyilmaz/EconMathFall2020", "max_stars_repo_head_hexsha": "12655168cbde5b2daf039c9fa728c748ff4121e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-25T12:26:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T05:10:16.000Z", "max_issues_repo_path": "Notebooks/lecture4-1.jl", "max_issues_repo_name": "fmyilmaz/EconMathFall2020", "max_issues_repo_head_hexsha": "12655168cbde5b2daf039c9fa728c748ff4121e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notebooks/lecture4-1.jl", "max_forks_repo_name": "fmyilmaz/EconMathFall2020", "max_forks_repo_head_hexsha": "12655168cbde5b2daf039c9fa728c748ff4121e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2857142857, "max_line_length": 109, "alphanum_fraction": 0.5936899863, "num_tokens": 1031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7740796426153663}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 232c24de-0e30-11eb-1544-53cb0b45ec9b\nbegin\n\timport Pkg\n\tPkg.activate(mktempdir())\n\tPkg.add([\n\t\t\"Colors\",\n\t\t\"Plots\",\n\t\t\"PlutoUI\",\n\t\t])\n\tusing Colors\n\tusing Plots\n\tusing PlutoUI\nend\n\n# ╔═╡ beed7b48-0e2b-11eb-2805-edf0be651fc3\nmd\"\"\"\n### Lecture 22: Solving Partial Differential Equations (PDEs) Numerically\n**Part I: One-dimensional advection and diffusion**\n\n#### 1) Advection\n\nConsider the following differential equation for temperature $T(x,t)$,\n\n$\\frac{\\partial T}{\\partial t} = - U \\frac{\\partial T}{\\partial x}$\n\nwhich describes the rate of change of temperature due to a uniform flow of speed $U$ in the $\\mathbf{x}$ direction.\n\n**Notation**:\nSince this differential equation includes derivatives in both time $t$ **and** space $x$, we replace the *ordinary* deriative symbol $d$ with a *partial* derivative symbol $\\partial$, and call the equation a **partial differential equation (PDE)**.\n\n#### 1.1) Discretizing in time: forward finite difference\n**A.k.a. *Euler's Method*$\\,$**\n\nAs in our solution of the \"zero-dimenisonal\" energy balance model ODE, we begin by discretizing time using a *forward finite difference* scheme:\n\n$\\frac{T_{n+1}-T_{n}}{\\Delta t} = - U \\frac{\\partial T}{\\partial x},$\n\nwhere $\\Delta t \\equiv t_{n+1} - t_{n}$ is a uniform discrete **timestep**.\n\"\"\"\n\n# ╔═╡ e74322be-12d6-11eb-3f27-f17821669699\nmd\"\n#### 1.2) Discretizing in space: centered finite difference\n\nWe now need to discretize the spatial derivative. Unlike for differencing in time, we no longer have a prefered direction for the discretization and so we use a *centered finite difference*:\n\n$\\frac{T_{n+1,\\, i}-T_{n,\\, i}}{\\Delta t} = - U \\frac{T_{n,\\, i+1} - T_{n,\\, i-1}}{2 \\Delta x},$\n\nwhere $\\Delta x \\equiv x_{i+1} - x_{i} = x_{i} - x_{i-1}$ is a uniform discrete **grid spacing**.\n\"\n\n# ╔═╡ c9a1719a-12d6-11eb-1c8c-13e1f75bc852\nmd\"**Note:** You should think of the *centered* finite difference average of the *right* (forward) and *left* (backward) finite differences:\n\n$\\frac{1}{2}\\left(\\frac{T_{n,\\, i+1} - T_{n,\\, i}}{\\Delta x} + \\frac{T_{n,\\, i} - T_{n,\\, i-1}}{\\Delta x} \\right) = \\frac{T_{n,\\, i+1} - T_{n,\\, i-1}}{2 \\Delta x}$\n\n\"\n\n# ╔═╡ c3f99436-0f49-11eb-33b6-e78c150d4ff5\nmd\"\"\"\n#### 1.3) Algorithmic procedure: time-stepping\n\nJust as before, we re-order the equation to solve for the temperature of the $i$th grid cell at the next timestep $t_{n+1}$,\n\n$T_{n+1,\\, i} = T_{n,\\, i} + \\Delta t \\left(-U \\frac{T_{n,\\, i+1} - T_{n,\\, i-1}}{2 \\Delta x} \\right),$\n\nwhich allows us to recursively advance in time, for each $i$, given some initial condition $T_{0,\\, i}$ for all $i$.\n\n#### 1.4) Numerical grid and boundary conditions\nConsider solving this on a grid $i \\in [1,\\, N_{i}]$. How do we handle the edge case $i=1$, where $T_{n+1,\\, 1}$ depends on $T_{n+1,\\, 0}$, which is undefined?\n\nFor both this point $i=1$ and the other extreme $i=N_{i}$, we need a **boundary condition**. There are a number of ways of doing this, and we will explore some alternative kinds of boundary conditions later, but the simplest is a *periodic boundary condition*, which wraps the grid around by setting $T_{n,\\, 0} = T_{n,\\, N_{i}}$ and $T_{n,\\, 1} = T_{n,\\, N_{i}+1}$\n\"\"\"\n\n# ╔═╡ 0967dc46-0f4d-11eb-13b2-2b2042595b6e\nmd\"#### 2) Numerical implementation\"\n\n# ╔═╡ 19273c8a-0f4d-11eb-3caf-678f073c6b1a\nmd\"##### 2.1) Setting up the model parameters\n\nTo keep things simple, let us consider our temperature equation as a model of temperature variations in a one-dimensional ocean current of length $L=1$ m and with a speed $U = 1$ m/s.\n\nThe choice of the **discretization resolution** $N_{i}$ is up to the modeller, but here we make it $N_{i} = 10$ because we will be able to easily pick out each of the individual grid cells in plots below.\n\"\n\n# ╔═╡ e700c752-0e2d-11eb-2c61-3959bdba269a\nbegin\n\tnx = 10\n\tLx = 1.\n\tΔx = Lx/nx\n\tΔt = 0.001\n\tU = 1.\n\t\n\tx = Δx/2.:Δx:Lx\nend;\n\n# ╔═╡ 5b1b6802-0e2e-11eb-1fa6-1ddd5478cc54\nbegin\n\t# Initial conditions\n\tT = sin.(2π*x);\n\tt = [0.]\nend;\n\n# ╔═╡ 4463cf8c-0ef8-11eb-2c6e-45d982d5687a\nfunction advect(T)\n\treturn U*(circshift(T, (1)) .- circshift(T, (-1)))/(2Δx)\nend\n\n# ╔═╡ 67cb0ed2-0efa-11eb-2645-495dba94ea64\nfunction timestep!(t, T)\n\tT .+= Δt*(advect(T))\n\tt .+= Δt\nend\n\n# ╔═╡ ba1ea938-0f44-11eb-0fac-cd1afe507d57\ntimestepButton = @bind go Button(\"Timestep\")\n\n# ╔═╡ 18a3f9dc-0e6d-11eb-0b31-0b5296c2e83b\nbegin\n\t⏩ = nothing\n\tgo\n\tnT = 50\n\tfor i = 1:nT\n\t\ttimestep!(t, T)\n\tend\nend;\n\n# ╔═╡ f2c7638a-0e34-11eb-2210-9f9b0c3519fe\nfunction temperature_heatmap(T)\n\tp = plot(xticks=x, yticks=nothing, size=(700,90))\n\tplot!(p, x, [0.], reshape(T, (size(T)...,1))', st=:heatmap, clims=(-1., 1.))\nend;\n\n# ╔═╡ b19bfb58-0f4e-11eb-218f-8d930b7afff6\nmd\"#### 2) Diffusion\n\n$\\frac{\\partial T}{\\partial t} = \\kappa \\frac{\\partial^{2} T}{\\partial x^{2}}$\n\n\nAgain, we discretize the equation by considering the derivatives one at a time:\n\n$\\frac{T_{n+1,\\, i} - T_{n,\\, i}}{\\Delta t} = \\kappa \\frac{\\partial^{2} T}{\\partial x^{2}}$\n\n$\\frac{T_{n+1,\\, i} - T_{n,\\, i}}{\\Delta t} = \\kappa \\left( \\frac{\\frac{\\partial T}{\\partial x}|_{n,\\, i+0.5} - \\frac{\\partial T}{\\partial x}|_{n,\\, i-0.5}}{\\Delta x} \\right)$\n\n$\\frac{T_{n+1,\\, i} - T_{n,\\, i}}{\\Delta t} = \\kappa \\left( \\frac{\\frac{T_{n,\\, i+1} - T_{n,\\, i}}{\\Delta x} - \\frac{T_{n,\\, i} - T_{n,\\, i-1}}{\\Delta x}}{\\Delta x}\\right)$\n\n$\\frac{T_{n+1,\\, i} - T_{n,\\, i}}{\\Delta t} = \\kappa \\left( \\frac{T_{n,\\, i+1} - 2 T_{n,\\, i} + T_{n,\\, i-1}}{(\\Delta x)^{2}}\\right)$\n\"\n\n\n\n# ╔═╡ 37bed6e8-12da-11eb-1c36-c7f92fe732e4\nκ = 0.05\n\n# ╔═╡ 3e1d44b6-12da-11eb-16ac-2524d0e0d900\nfunction diffuse(T)\n\treturn κ*(circshift(T, (1)) .- 2*T .+ circshift(T, (-1)))/(Δx^2)\nend\n\n# ╔═╡ 43d1272a-2113-11eb-1d03-c948d11a8423\n# function timestep!(t, T)\n# \tT .+= Δt*(diffuse(T))\n# \tt .+= Δt\n# end\n\n# ╔═╡ 74a36fd4-2113-11eb-2d3e-3be5e4318dea\ntimestepButton\n\n# ╔═╡ d2c101c8-0f4e-11eb-0c4f-0972be924ce1\nmd\"#### 3) Advection-Diffusion\"\n\n# ╔═╡ 7c490fd2-2113-11eb-3239-f72cc77c0b53\n# function timestep!(t, T)\n# \tT .+= Δt*(advect(T) .+ diffuse(T))\n# \tt .+= Δt\n# end\n\n# ╔═╡ 894b97f4-2113-11eb-3b86-2986a6cd4fd1\ntimestepButton\n\n# ╔═╡ b00f7bec-12da-11eb-3e20-7769cc2bd0ec\nmd\"\n#### 4) Finite differences as kernels acting on an array\n\n##### 4.1) Analogies between image processing and PDEs\n\n##### 4.1.1) Blurring (Gaussian kernel) vs. Laplacian operator\n\n##### 4.1.2) Edge detection (Sobel kernel) vs. Gradient operator\n\"\n\n# ╔═╡ 70ae3138-0f44-11eb-1a8d-d3b5a39c1b42\nmd\"\"\"#### Pluto Book-keeping\"\"\"\n\n# ╔═╡ 845e102a-0f44-11eb-3935-2d9a0efecedc\nas_svg(x) = PlutoUI.Show(MIME\"image/svg+xml\"(), repr(MIME\"image/svg+xml\"(), x))\n\n# ╔═╡ 00cc530a-0e35-11eb-133b-ef8e30ea7b12\nbegin\n\t⏩\n\tp1 = plot(x, T, label=\"Temperature\", ylim=[-1.1, 1.1], xlim=[0., 1.], marker=:c)\n\tannotate!(p1, [(0.05, 0.9, string(\"t = \", round(t[1], digits=2)))])\n\tp2 = temperature_heatmap(T)\n\tp = plot(p1, p2, layout=grid(2, 1, heights=[0.7 , 0.3]), size=(680,250))\n\tas_svg(p)\nend\n\n# ╔═╡ 4c5b62fa-2113-11eb-14ff-2bd776efe96c\nas_svg(p)\n\n# ╔═╡ 869c4be8-2113-11eb-0703-f905fe93142f\nas_svg(p)\n\n# ╔═╡ Cell order:\n# ╟─beed7b48-0e2b-11eb-2805-edf0be651fc3\n# ╟─e74322be-12d6-11eb-3f27-f17821669699\n# ╟─c9a1719a-12d6-11eb-1c8c-13e1f75bc852\n# ╟─c3f99436-0f49-11eb-33b6-e78c150d4ff5\n# ╟─0967dc46-0f4d-11eb-13b2-2b2042595b6e\n# ╟─19273c8a-0f4d-11eb-3caf-678f073c6b1a\n# ╠═e700c752-0e2d-11eb-2c61-3959bdba269a\n# ╠═5b1b6802-0e2e-11eb-1fa6-1ddd5478cc54\n# ╠═4463cf8c-0ef8-11eb-2c6e-45d982d5687a\n# ╠═67cb0ed2-0efa-11eb-2645-495dba94ea64\n# ╠═ba1ea938-0f44-11eb-0fac-cd1afe507d57\n# ╠═00cc530a-0e35-11eb-133b-ef8e30ea7b12\n# ╠═18a3f9dc-0e6d-11eb-0b31-0b5296c2e83b\n# ╠═f2c7638a-0e34-11eb-2210-9f9b0c3519fe\n# ╟─b19bfb58-0f4e-11eb-218f-8d930b7afff6\n# ╠═37bed6e8-12da-11eb-1c36-c7f92fe732e4\n# ╠═3e1d44b6-12da-11eb-16ac-2524d0e0d900\n# ╠═43d1272a-2113-11eb-1d03-c948d11a8423\n# ╠═74a36fd4-2113-11eb-2d3e-3be5e4318dea\n# ╠═4c5b62fa-2113-11eb-14ff-2bd776efe96c\n# ╟─d2c101c8-0f4e-11eb-0c4f-0972be924ce1\n# ╠═7c490fd2-2113-11eb-3239-f72cc77c0b53\n# ╠═894b97f4-2113-11eb-3b86-2986a6cd4fd1\n# ╠═869c4be8-2113-11eb-0703-f905fe93142f\n# ╟─b00f7bec-12da-11eb-3e20-7769cc2bd0ec\n# ╟─70ae3138-0f44-11eb-1a8d-d3b5a39c1b42\n# ╠═232c24de-0e30-11eb-1544-53cb0b45ec9b\n# ╠═845e102a-0f44-11eb-3935-2d9a0efecedc\n", "meta": {"hexsha": "39f69200127c2a33e2ffa9622e251783a918d085", "size": 8584, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_notebooks/week12/3_advection_diffusion.jl", "max_stars_repo_name": "mathijsvdv/ComputationalThinking", "max_stars_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lecture_notebooks/week12/3_advection_diffusion.jl", "max_issues_repo_name": "mathijsvdv/ComputationalThinking", "max_issues_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecture_notebooks/week12/3_advection_diffusion.jl", "max_forks_repo_name": "mathijsvdv/ComputationalThinking", "max_forks_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1428571429, "max_line_length": 365, "alphanum_fraction": 0.6726467847, "num_tokens": 3813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418158002491, "lm_q2_score": 0.8376199673867853, "lm_q1q2_score": 0.7740796376113692}}
{"text": "# Compute C = A * B, using a cache-obvious multiplication algorithm\n\nfunction add_matmul_rec!(m,n,p, i0,j0,k0, C,A,B)\n    if m+n+p <= 64   # base case: naive matmult for sufficiently large matrices\n        for i = 1:m\n            for k = 1:p\n                c = zero(eltype(C))\n                for j = 1:n\n                    @inbounds c += A[i0+i,j0+j] * B[j0+j,k0+k]\n                end\n                @inbounds C[i0+i,k0+k] += c\n            end\n        end\n    else\n        m2 = m ÷ 2; n2 = n ÷ 2; p2 = p ÷ 2\n        add_matmul_rec!(m2, n2, p2, i0, j0, k0, C, A, B)\n        \n        add_matmul_rec!(m-m2, n2, p2, i0+m2, j0, k0, C, A, B)\n        add_matmul_rec!(m2, n-n2, p2, i0, j0+n2, k0, C, A, B)\n        add_matmul_rec!(m2, n2, p-p2, i0, j0, k0+p2, C, A, B)\n        \n        add_matmul_rec!(m-m2, n-n2, p2, i0+m2, j0+n2, k0, C, A, B)\n        add_matmul_rec!(m2, n-n2, p-p2, i0, j0+n2, k0+p2, C, A, B)\n        add_matmul_rec!(m-m2, n2, p-p2, i0+m2, j0, k0+p2, C, A, B)\n        \n        add_matmul_rec!(m-m2, n-n2, p-p2, i0+m2, j0+n2, k0+p2, C, A, B)\n    end\n    return C\nend\n\nfunction matmul_rec!(C, A, B)\n    m,n = size(A)\n    n,p = size(B)\n    size(C) == (m,p) || error(\"incorrect dimensions \", size(C), \" ≠ $m × $p\")\n    fill!(C, 0)\n    return add_matmul_rec!(m,n,p, 0,0,0, C,A,B)\nend\n\n\nmatmul_rec(A, B) = matmul_rec!(Array{promote_type(eltype(A), eltype(B))}(undef,size(A,1), size(B,2)),A, B)\n\n# Example:\n# A = rand(50,60)\n# B = rand(60,70)\n# matmul_rec(A,B)", "meta": {"hexsha": "c77c459c23c951247a014a671e18f358a404ab69", "size": 1468, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Code/Numerical Analysis & Machine Learning/Matrix Multiplication/CacheObliviousMatrixMultiplication.jl", "max_stars_repo_name": "BambooFlower/Math-Scripts", "max_stars_repo_head_hexsha": "ee89c4f8a1fe80f355e2daa0baa4f94374ee3ab5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-03-10T13:21:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-20T19:52:53.000Z", "max_issues_repo_path": "Code/Numerical Analysis & Machine Learning/Matrix Multiplication/CacheObliviousMatrixMultiplication.jl", "max_issues_repo_name": "BambooFlower/Math-Scripts", "max_issues_repo_head_hexsha": "ee89c4f8a1fe80f355e2daa0baa4f94374ee3ab5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-25T14:25:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-25T14:28:07.000Z", "max_forks_repo_path": "Code/Numerical Analysis & Machine Learning/Matrix Multiplication/CacheObliviousMatrixMultiplication.jl", "max_forks_repo_name": "BambooFlower/Math-Scripts", "max_forks_repo_head_hexsha": "ee89c4f8a1fe80f355e2daa0baa4f94374ee3ab5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-25T13:17:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T15:11:25.000Z", "avg_line_length": 32.6222222222, "max_line_length": 106, "alphanum_fraction": 0.5006811989, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8376199613065411, "lm_q1q2_score": 0.774079637242363}}
{"text": "using TensorToolbox\nusing LinearAlgebra\nusing Arpack\nusing TensorDecompositions\n\nfunction lranmf_mu(X, r ; max_iter=200, tol = 1.0E-3, verbose = false)\n    # lranmf_mu is effective when r << min(n,m)\n    # input is a onnegative matrix\n    # proposed by Guoxu Zhou in 2012\n    # https://ieeexplore.ieee.org/document/6166354\n\n    n, m = size(X)\n    epsilon = 0.0001\n\n    # See step1 in section II-B in the paper\n    if r == min(n, m)\n        svd_X = svd(X)\n    else\n        svd_X = svds(X; nsv=r, ritzvec=true)[1]\n    end\n    Achil = svd_X.U * diagm(svd_X.S)\n    Bchil = svd_X.V\n\n    # See step2 in section II-B in the paper\n    A = rand(n, r)\n    B = rand(m, r)\n    cost_at_init = norm(X - A*B')\n    previous_cost = cost_at_init\n    for iter = 1:max_iter\n        B .= B .* ( max.( Bchil*(Achil' * A), epsilon ) ) ./ ( B*(A'*A) )\n        A .= A .* ( max.( Achil*(Bchil' * B), epsilon ) ) ./ ( A*(B'*B) )\n\n        if tol > 0 && iter % 10 == 0\n            cost = norm(X - A*B')\n            if verbose\n                println(\"iter: $iter cost: $cost\")\n            end\n            if (previous_cost - cost) / cost_at_init < tol\n                break\n            end\n            previous_cost = cost\n        end\n    end\n\n    # A * B' is rank-r matrix\n    return A, B'\nend\n", "meta": {"hexsha": "54fd3403e8f87ecf6e2d5475e44ec0cf32db0f9b", "size": 1266, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/nmf.jl", "max_stars_repo_name": "gkazunii/Legendre-tucker-rank-reduction", "max_stars_repo_head_hexsha": "303d5b3cb5e559841ad0df20adb40966e18b1248", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-09-30T06:58:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T16:08:44.000Z", "max_issues_repo_path": "src/utils/nmf.jl", "max_issues_repo_name": "gkazunii/Legendre-tucker-rank-reduction", "max_issues_repo_head_hexsha": "303d5b3cb5e559841ad0df20adb40966e18b1248", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/nmf.jl", "max_forks_repo_name": "gkazunii/Legendre-tucker-rank-reduction", "max_forks_repo_head_hexsha": "303d5b3cb5e559841ad0df20adb40966e18b1248", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.375, "max_line_length": 73, "alphanum_fraction": 0.5331753555, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7740796354923624}}
{"text": "using SpecialFunctions\n\"Abstract quadrature type\"\nabstract type QUADRATURE_TYPE end\n\n\"Gauss-Jacobi quadrature type\"\nstruct GJ <: QUADRATURE_TYPE end\n\"Gauss-Lobatto-Jacobi quadrature type\"\nstruct GLJ <: QUADRATURE_TYPE end\n\"Gauss-Radau-Jacobi quadrature type includind the left end\"\nstruct GRJM <: QUADRATURE_TYPE end\n\"Gauss-Radau-Jacobi quadrature type includind the right end\"\nstruct GRJP <: QUADRATURE_TYPE end\n\n# Calculate a ratio of Gamma functions without overflow\nfunction gamma_ratio(num::T, denom::T) where {T<:Number}\n    if num>1 && denom>1\n        exp((logabsgamma(num))[1] - (logabsgamma(denom))[1])\n    else\n        gamma(num) / gamma(denom)\n    end\nend\n\n\n\"\"\"\nGauss-type quadrature\n\nNumerical integrals in the domain [-1,1] can be computed\nfrom knowledge of the function in a set of nodes and the\ncorresponding nodes, such that\n\n```math\n\\\\int_{-1}^1 (1-x)^a (1+x)^b (1-xf(x)\\\\:dx \\\\approx \\\\sum_{i=1}^N w^{a,b}_i f(x_i)\n```\n\nThe parameters `a` and `b` form a famility of quadrature rules. But if one or both\nof the ends are specified, other quadrature families are possible:\n\n * No ends are specified, Gauss-Jacobi quadrature (GJ)\n * Both ends are specified, Gauss-Lobatto-Jacobi quadrature (GLJ)\n * A single end is specified, Gauss-Radau-Jacobi quadrature (if +1 is specified, GRJP, if -1, GRJM)\n\nTo compute the nodes, the following functions are available:\n\n * `zgj` (Gauss-Jacobi)\n * `zglj` (Gauss-Lobatto-Jacobi)\n * `zgrjm` (Gauss-Radau-Jacobi, -1)\n * `zgrjp` (Gauss-Radau-Jacobi, +1)\n\nAll these functions have the following parameters:\n\n * `Q`  Number of quadrature nodes\n * `a` (a) weight\n * `b` (b) weight\n *  type Data type to be used, `Float64` is the default\n\nTo compute the weights, first the zeros (`z`) should be computed and then the weights are computed\nwith the following functions:\n\n * `wgj(z, a, b)`\n * `wglj(z, a, b)`\n * `wgrjm(z, a, b)`\n * `wgrjp(z, a, b)`\n\n ### Derivatives\n\nThe nodes used in the quadrature rules are convenient when using high order Lagrange interpolation\nTo compute derivatives. The following functions are used to compute the derivative matrix such that\n`du = D*u`:\n\n * `dgj(z, a, b)`\n * `dglj(z, a, b)`\n * `dgrjm(z, a, b)`\n * `dgrjp(z, a, b)`\n\n### Examples\n\nSee the notebooks availbale with the package.\n\n\"\"\"\nfunction zgj(Q, a, b, ::Type{T}=Float64) where {T<:Number}\n    jacobi_zeros(Q, a, b, T)\nend\n\nzgj(Q) = zgj(Q, 0.0, 0.0)\nzgj(Q, a) = zgj(Q, a, zero(a))\n\nfunction zglj(Q, a, b, ::Type{T}=Float64) where {T<:Number}\n    z = jacobi_zeros(Q-2, a+1, b+1, T)\n    o = one(T)\n    return [-o; z; o]\nend\nzglj(Q) = zglj(Q, 0.0, 0.0)\nzglj(Q, a) = zglj(Q, a, zero(a))\n\n\nfunction zgrjm(Q, a, b, ::Type{T}=Float64) where {T<:Number}\n    z = jacobi_zeros(Q-1, a, b+1, T)\n    return [-one(T); z]\nend\nzgrjm(Q) = zgrjm(Q, 0.0, 0.0)\nzgrjm(Q, a) = zgrjm(Q, a, zero(a))\n\n\nfunction zgrjp(Q, a, b, ::Type{T}=Float64) where {T<:Number}\n    z = jacobi_zeros(Q-1, a+1, b, T)\n    return [z; one(T)]\nend\nzgrjp(Q) = zgrjp(Q, 0.0, 0.0)\nzgrjp(Q, a) = zgrjp(Q, a, zero(a))\n\n\nfunction wgj(z::AbstractArray{T}, alpha=0, beta=0) where {T<:Number}\n    a = convert(T, alpha)\n    b = convert(T, beta)\n\n    Q::Int = length(z)\n    o = one(T)\n    coef = 2^(a+b+1) * gamma_ratio(a+Q+1, Q+o) * gamma_ratio(b+Q+1, a+b+Q+1)\n    w = [djacobi(zz, Q, a, b) for zz=z]\n\n    for i = 1:Q\n        ww = w[i]\n        x = z[i]\n        w[i] = o / (ww*ww) * coef / (o - x*x)\n    end\n\n    return w\nend\n\n\nfunction wglj(z::AbstractArray{T}, alpha=0, beta=0) where {T<:Number}\n    a = convert(T, alpha)\n    b = convert(T, beta)\n    o = one(T)\n    Q = length(z)\n\n    coef = 2^(a+b+1) / (Q-o) * gamma_ratio(a+Q, Q*o) * gamma_ratio(b+Q, a+b+Q+1)\n    \n    w = [jacobi(zz, Q-1, a, b) for zz=z]\n    w[1] = (b+1) * coef / (w[1]*w[1])\n    w[Q] = (a+1) * coef / (w[Q]*w[Q])\n\n    for i = 2:(Q-1)\n        ww = w[i]\n        w[i] = coef / (ww * ww)\n    end\n\n    return w\nend\n\nfunction wgrjm(z::AbstractArray{T}, alpha=0, beta=0) where {T<:Number}\n    a = convert(T, alpha)\n    b = convert(T, beta)\n    o = one(T)\n\n    Q = length(z)\n\n    coef = 2^(a+b) / (b+Q) * gamma_ratio(a+Q, Q*o) * gamma_ratio(b+Q, a+b+Q+1)\n\n    w = [jacobi(zz, Q-1, a, b) for zz=z]\n\n    for i = 1:Q\n        ww = w[i]\n        w[i] = coef / (ww*ww) * (o - z[i])\n    end\n\n    w[1] *= (b + o)\n\n    return w\nend\n\n\nfunction wgrjp(z::AbstractArray{T,1}, alpha=0, beta=0) where {T<:Number}\n    a = convert(T, alpha)\n    b = convert(T, beta)\n    Q = length(z)\n    o = one(T)\n\n    coef = 2^(a+b) / (a+Q) * gamma_ratio(a+Q, Q*o) * gamma_ratio(b+Q, a+b+Q+1)\n\n    w = [jacobi(zz, Q-1, a, b) for zz=z]\n\n    for i = 1:Q\n        ww = w[i]\n        w[i] = coef / (ww*ww) * (o + z[i])\n    end\n\n    w[Q] *= (a + o)\n\n    return w\nend\n\n\nfunction dgj(z::AbstractArray{T,1}, alpha=0, beta=0) where {T<:Number}\n\n    Q = length(z)\n    a = convert(T, alpha)\n    b = convert(T, beta)\n    o = one(T)\n\n    djac = [djacobi(zz, Q, alpha, beta) for zz=z]\n\n    D = zeros(T, Q, Q)\n    for i = 1:Q\n        for k = 1:Q\n            if i != k\n                D[i,k] = (djac[i]/djac[k]) / (z[i]-z[k])\n            else\n                D[i,i] = (a-b + (a + b + 2) * z[i]) / (o - z[k]^2) / 2\n            end\n        end\n    end\n\n    return D\nend\n\n\nfunction dglj(z::AbstractArray{T,1}, alpha=0, beta=0) where {T<:Number}\n\n    Q = length(z)\n    a = convert(T, alpha)\n    b = convert(T, beta)\n    o = one(T)\n\n    djac = zeros(T,Q)\n    djac[1] = (-1)^Q * 2 * gamma_ratio(Q+b, Q-o) / gamma(b+2)\n    djac[Q] = -2 * gamma_ratio(Q+a, Q-o) / gamma(a+2)\n    for i = 2:(Q-1)\n        djac[i] = (o-z[i]*z[i]) * djacobi(z[i], Q-2, a+1, b+1)\n    end\n\n    D = zeros(T, Q, Q)\n    for i = 1:Q\n        for k = 1:Q\n            if i != k\n                D[i,k] = (djac[i]/djac[k]) / (z[i]-z[k])\n            else\n                D[i,i] = (a - b + (a + b)*z[i]) / (2*(o - z[i]^2))\n            end\n        end\n    end\n\n    D[1,1] = (a - (Q-1)*(Q+a+b)) / (2*(b + 2))\n    D[Q,Q] = -(b - (Q-1)*(Q+a+b)) / (2*(a + 2))\n\n    return D\n\nend\n\n\nfunction dgrjm(z::AbstractArray{T,1}, alpha=0, beta=0) where {T<:Number}\n\n    Q = length(z)\n    a = convert(T, alpha)\n    b = convert(T, beta)\n    o = one(T)\n\n    djac = zeros(T,Q)\n    for i = 2:Q\n        djac[i] = (1+z[i]) * djacobi(z[i], Q-1, a, b+1)\n    end\n    djac[1] = (-1)^(Q-1) * gamma_ratio(Q+b+1, Q*o) / gamma(b+2)\n\n    D = zeros(T, Q, Q)\n    for i = 1:Q\n        for k = 1:Q\n            if i != k\n                D[i,k] = (djac[i]/djac[k]) / (z[i]-z[k])\n            else\n                D[i,i] = (a - b + 1 + (a + b + 1)*z[i]) / (2*(1 - z[i]^2))\n            end\n        end\n    end\n\n    D[1,1] = -(Q-1)*(Q+a+b+1) / (2*(b + 2))\n\n    return D\n\nend\n\n\nfunction dgrjp(z::AbstractArray{T,1}, alpha=0, beta=0) where {T<:Number}\n\n    Q = length(z)\n    a = convert(T, alpha)\n    b = convert(T, beta)\n    o = one(T)\n\n    djac = zeros(T,Q)\n    for i = 1:(Q-1)\n        djac[i] = (1-z[i]) * djacobi(z[i], Q-1, a+1, b)\n    end\n    djac[Q] = - gamma_ratio(Q+a+1, Q*o) / gamma(a+2)\n\n    D = zeros(T, Q, Q)\n    for i = 1:Q\n        for k = 1:Q\n            if i != k\n                D[i,k] = (djac[i]/djac[k]) / (z[i]-z[k])\n            else\n                D[i,i] = (a - b - 1 + (a + b + 1)*z[i]) / (2*(1 - z[i]^2))\n            end\n        end\n    end\n\n    D[Q,Q] = (Q-1)*(Q+a+b+1) / (2*(a + 2))\n\n    return D\n\nend\n\n\n\"\"\"\nAbstract interface of Gauss-type quadrature rules\n\nCan be used for any `AbstractFloat` type data.\n\"\"\"\nstruct Quadrature{T<:Number,QT<:QUADRATURE_TYPE}\n    \"Number of quadrature nodes\"\n    Q::Int\n    \"a weight\"\n    a::T\n    \"b weight\"\n    b::T\n    \"Quadrature nodes\"\n    z::Array{T, 1}\n    \"Quadrature weights\"\n    w::Array{T, 1}\n    \"Quadrature derivative matrix\"\n    D::Array{T, 2}\nend\n\n\"\"\"\nReturn the zeros of a Gauss type quadrature\n\"\"\"\nqzeros(::Type{GJ}, Q, a=0, b=0, ::Type{T}=Float64) where {T<:Number} = zgj(Q, a, b, T)\nqzeros(::Type{GLJ}, Q, a=0, b=0, ::Type{T}=Float64) where {T<:Number} = zglj(Q, a, b, T)\nqzeros(::Type{GRJM}, Q, a=0, b=0, ::Type{T}=Float64) where {T<:Number} = zgrjm(Q, a, b, T)\nqzeros(::Type{GRJP}, Q, a=0, b=0, ::Type{T}=Float64) where {T<:Number} = zgrjp(Q, a, b, T)\n\n\"\"\"\nReturn the weights of a Gauss type quadrature\n\"\"\"\nqweights(::Type{GJ}, z::AbstractArray{T}, a=0, b=0) where {T<:Number} = wgj(z, a, b)\nqweights(::Type{GLJ}, z::AbstractArray{T}, a=0, b=0) where {T<:Number} = wglj(z, a, b)\nqweights(::Type{GRJM}, z::AbstractArray{T}, a=0, b=0) where {T<:Number} = wgrjm(z, a, b)\nqweights(::Type{GRJP}, z::AbstractArray{T}, a=0, b=0) where {T<:Number} = wgrjp(z, a, b)\n\n\"\"\"\nReturn the derivative matrix of a Gauss type quadrature\n\"\"\"\nqdiff(::Type{GJ}, z::AbstractArray{T}, a=0, b=0) where {T<:Number} = dgj(z, a, b)\nqdiff(::Type{GLJ}, z::AbstractArray{T}, a=0, b=0) where {T<:Number} = dglj(z, a, b)\nqdiff(::Type{GRJM}, z::AbstractArray{T}, a=0, b=0) where {T<:Number} = dgrjm(z, a, b)\nqdiff(::Type{GRJP}, z::AbstractArray{T}, a=0, b=0) where {T<:Number} = dgrjp(z, a, b)\n\n\n\"\"\"\nCreate a `Quadrature` object given its type, order and weights.\n\"\"\"\nfunction Quadrature(::Type{QT}, Q, a=0, b=0,\n                    ::Type{T}=Float64) where {T<:Number, QT<:QUADRATURE_TYPE}\n    aa = convert(T, a)\n    bb = convert(T, b)\n    z = qzeros(QT, Q, aa, bb, T)\n    w = qweights(QT, z, aa, bb)\n    D = qdiff(QT, z, aa, bb)\n    Quadrature{T,QT}(Q, aa, bb, z, w, D)\nend\n\n\"Return quadrature type\"\nqtype(q::Quadrature{T,QT}) where {T,QT} = QT\n\"Return quadrature nodes\"\nqzeros(q::QT) where {QT<:Quadrature} = q.z\n\"Return quadrature weights\"\nqweights(q::QT) where {QT<:Quadrature} = q.w\n\"Return quadrature derivative matrix\"\nqdiff(q::QT) where {QT<:Quadrature} = q.D\n\"Return number of quadrature nodes\"\nnum_points(q::QT) where {QT<:Quadrature} = q.Q\n\"Return quadrature `a` weight\"\nqalpha(q::QT) where {QT<:Quadrature} = q.a\n\"Return quadrature `b` weight\"\nqbeta(q::QT) where {QT<:Quadrature} = q.b\n\n\"\"\"\nCompute the Lagrange polynomial\n\nThis function computes the Lagrange polynomial at point `x` corresponding to\nthe `i`-th node of the set `z`\n\nThere is also a modifying version `lagrange!` used to computing the polynomials\nat several points of an array `x`\n\"\"\"\nfunction lagrange(i, x, z)\n    nz = length(z)\n\n    l = one(z[1])\n\n    for k = 1:(i-1)\n        l = l * (x-z[k]) / (z[i]-z[k])\n    end\n\n    for k = (i+1):nz\n        l = l * (x-z[k]) / (z[i]-z[k])\n    end\n\n    return l\nend\n\n\n\n\"\"\"\nInterpolation matrix\n\nOften it is necessary to compute the values of a function approximated using\nLagrange interpolation through a set of points `z`. If this will be repeated\noften, a matrix can be computed that allows the easy computation using the simple\nexpression `fx = Imat * fz`\n\"\"\"\nfunction interp_mat(x::AbstractArray{T}, z::AbstractArray{T}) where {T<:Number}\n\n    Q = length(z)\n    np = length(x)\n\n    Imat = zeros(T, np, Q)\n    for i = 1:Q, k=1:np\n        Imat[k,i] = lagrange(i, x[k], z)\n    end\n\n    return(Imat)\n\nend\n\n\n\n\n@doc (@doc zgj) zglj\n@doc (@doc zgj) zgrjm\n@doc (@doc zgj) zgrjp\n\n@doc (@doc zgj) wgj\n@doc (@doc zgj) wglj\n@doc (@doc zgj) wgrjm\n@doc (@doc zgj) wgrjp\n\n@doc (@doc zgj) dgj\n@doc (@doc zgj) dglj\n@doc (@doc zgj) dgrjm\n@doc (@doc zgj) dgrjp\n\n", "meta": {"hexsha": "5b725b11b4790202e375638fbf2359d333fc267c", "size": 11014, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gauss_quad.jl", "max_stars_repo_name": "pjabardo/Jacobi.jl", "max_stars_repo_head_hexsha": "c1bfe73688ca47da70a5dc3b46083237382d41c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2015-11-23T03:17:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T16:38:43.000Z", "max_issues_repo_path": "src/gauss_quad.jl", "max_issues_repo_name": "pjabardo/Jacobi.jl", "max_issues_repo_head_hexsha": "c1bfe73688ca47da70a5dc3b46083237382d41c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2018-08-08T20:38:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-09T15:22:25.000Z", "max_forks_repo_path": "src/gauss_quad.jl", "max_forks_repo_name": "pjabardo/Jacobi.jl", "max_forks_repo_head_hexsha": "c1bfe73688ca47da70a5dc3b46083237382d41c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2016-01-08T20:07:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:22:22.000Z", "avg_line_length": 24.3672566372, "max_line_length": 99, "alphanum_fraction": 0.5599237334, "num_tokens": 4209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.774079628246356}}
{"text": "function twodElliptic(N=25, κ=1.0)\n#\n#  Solves a linear elliptic PDE on the unit square\n#     - ∇⋅(κ∇u) = q\n#---------------------------------------------------------------------------78--\n\n#  include(\"twodMesh.jl\")\n#  include(\"twodQuadratureRule.jl\")\n#  @everywhere include(\"twodShape.jl\")\n#  @everywhere include(\"twodBilinear.jl\")\n#  @everywhere include(\"twodLinForm.jl\")\n\n  rule  = 7     # points in quadrature formula, adjust for different unit tests\n                # options are 1, 3 (2nd degree), 7 (5th degree), \n                # 13 (7th degree), and 19 (9th degree).\n\n  #  Set the verification example\n  function uExact(x)\n    C = 0.2/π^2\n    return C*sin.(π*x[:,1])*sin.(2*π*x[:,2])\n  end\n#  f(x)=x[1]+x[2];            # right-hand side function definition.\n#  @everywhere function f(x::Array{Float64,2})\n  function f(x::Array{Float64,2})\n    return sin.(π*x[:,1]).*sin.(2*π*x[:,2])\n  end\n\n  #  Specify the geometry/mesh\n  #-----------------------------------------------------------------------------\n  xMin = 0.0\n  xMax = 1.0\n  yMin = 0.0\n  yMax = 1.0\n  nNodesX = N \n  nNodesY = N\n  x,eConn,iB = twodMesh( xMin,xMax, yMin,yMax, \"quadratic\", nNodesX,nNodesY )\n\n  #  Get problem dimensions\n  #-----------------------------------------------------------------------------\n  nNodes = size(x,1)\n  nElements = size(eConn,1)\n\n  nDirichlet = length(iB)\n\n  #  Set the index into equation numbers\n  #-----------------------------------------------------------------------------\n  ide = zeros(Int64,nNodes,1)\n  \n  global nUnk = 0\n  for i=1:nNodes\n    global nUnk = nUnk+1\n    ide[i,1] = nUnk\n  end\n\n  # ide = 1:nNodes\n\n  #  Integrate system matrices, element-by-element\n  #-----------------------------------------------------------------------------\n  r,s,w = twodQuadratureRule(rule)\n  o     = ones(rule)\n  κ_g   = κ*ones(rule)\n\n  nElDOF   = size(eConn,2)\n  nElDOF2  = nElDOF*nElDOF\n  nEntries = nElements*nElDOF2\n  II  = Array{Int64,1}(undef, nEntries)    #SharedArray(Int32,nEntries);\n  JJ  = Array{Int64,1}(undef, nEntries)    #SharedArray(Int32,nEntries);\n  AA  = Array{Float64,1}(undef, nEntries)  #SharedArray(Float64,nEntries);\n  b   = zeros(Float64,nNodes,1)            #SharedArray(Float64,nNodes);\n\n#  @sync @parallel for k=1:nElements\n  for k=1:nElements\n    #xg  = Array(Float64,rule,2);\n    #wg  = Array(Float64,rule);\n    #phi = Array(Float64,rule,nElDOF);\n    #p_x = Array(Float64,rule,nElDOF);\n    #p_y = Array(Float64,rule,nElDOF);\n   \n    nLocal = eConn[k,:][:]\n    xLocal = x[nLocal,:]\n\n    xg,wg,ϕ,ϕ_x,ϕ_y = twodShape( xLocal, r, s, w )\n    fg   = f(xg)         # forcing function evaluated at quadrature points\n\n    ALoc = twodBilinear( κ_g, ϕ_x, ϕ_x, wg ) + twodBilinear( κ_g, ϕ_y, ϕ_y, wg )\n    bLoc = twodLinForm(   fg,      ϕ  , wg )\n\n    index = (k-1)*nElDOF2    # compute base index (k could be in any order)\n    lDOF = ide[nLocal,1][:]\n\n    for nt = 1:nElDOF\n      nTest = ide[nLocal[nt],1]\n      for nu = 1:nElDOF\n        nUnkU = ide[nLocal[nu],1]\n\n        index = index + 1\n        II[index] = nTest   # lDOF[nu]\n        JJ[index] = nUnkU   # lDOF[nt]\n        AA[index] = ALoc[nt,nu]\n      end\n\n      b[nTest] = b[nTest] + bLoc[nt] #b[lDOF[nt]] = b[lDOF[nt]] + bLoc[nt]\n    end\n  end\n\n  A = sparse(II,JJ,AA)\n\n  interiorNodes = 1:nNodes\n  interiorNodes = setdiff(interiorNodes,iB)\n\n  knownIndexU = iB\n\n#  dirichletU = Array{Float64,1}(undef,nDirichlet)\n#  for i=1:nDirichlet\n#    dirichletU = uExact(x[i,:])\n#  end\n\n  u = zeros(Float64,nNodes)\n  u[interiorNodes] = A[interiorNodes,interiorNodes]\\b[interiorNodes]\n\n  #print(\"$(u)\")\n\n  return x,eConn,u\nend\n\n", "meta": {"hexsha": "b4c38b8a39130b99d544380c3b4406b0d15c085f", "size": 3589, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/twodElliptic.jl", "max_stars_repo_name": "jborggaard/FEMfunctions.jl", "max_stars_repo_head_hexsha": "a282cc99d817987f8c579c7b40f31bb2154b11a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/twodElliptic.jl", "max_issues_repo_name": "jborggaard/FEMfunctions.jl", "max_issues_repo_head_hexsha": "a282cc99d817987f8c579c7b40f31bb2154b11a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/twodElliptic.jl", "max_forks_repo_name": "jborggaard/FEMfunctions.jl", "max_forks_repo_head_hexsha": "a282cc99d817987f8c579c7b40f31bb2154b11a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4841269841, "max_line_length": 80, "alphanum_fraction": 0.5402619114, "num_tokens": 1232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889438, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7740575078715931}}
{"text": "# Problem 2 - Project Euler\n# http://projecteuler.net/index.php?section=problems&id=2\nfunction fibevensum(a, b, sum, xmax)\n    if a >= xmax\n        sum\n    elseif a % 2 == 0\n        fibevensum(b, a + b, sum + a, xmax)\n    else\n        fibevensum(b, a + b, sum, xmax)\n    end\nend\n\nprintln(fibevensum(1,2,0, 4000000))\n", "meta": {"hexsha": "85966f09735f532af7b92b02f6e75e75ff05907d", "size": 316, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/problem002.jl", "max_stars_repo_name": "emergent/ProjectEuler", "max_stars_repo_head_hexsha": "ec1c92cc47fde80efddeb0346d9b0fa511df1f00", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Julia/problem002.jl", "max_issues_repo_name": "emergent/ProjectEuler", "max_issues_repo_head_hexsha": "ec1c92cc47fde80efddeb0346d9b0fa511df1f00", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/problem002.jl", "max_forks_repo_name": "emergent/ProjectEuler", "max_forks_repo_head_hexsha": "ec1c92cc47fde80efddeb0346d9b0fa511df1f00", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5714285714, "max_line_length": 57, "alphanum_fraction": 0.5981012658, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813394, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7740575074446868}}
{"text": "function mh(\n    likelihood::Function,\n    prior::Function,\n    propdistpdf::Function,\n    propdistsample::Function,\n    startval::Vector,\n    mcit::Int64,\n    burn::Int64\n    )\n\n    sample = zeros(mcit,length(startval))\n    sample[1,:] = startval\n\n    for i in 1:mcit-1\n        curr = sample[i,:]\n\n        #create new sample\n        proposalval = curr + propdistsample()\n\n        #calculate acceptance probability\n        A = (likelihood(proposalval)/likelihood(curr)*prior(proposalval)/\n            prior(curr)*propdistpdf(proposalval-curr)/\n            propdistpdf(curr-proposalval))[1]\n\n        #accept or reject sample\n        if A>=rand(Uniform(0,1))\n            sample[i+1,:] = proposalval\n        else\n            sample[i+1,:] = curr\n        end\n    end\n    return sample[burn+1:mcit,:]\nend\n\nfunction gibbssample(\n    condist::Vector,\n    startval::Vector,\n    mcit::Int64,\n    burn::Int64\n    )\n\n    sample = zeros(mcit, length(startval))\n    sample[1,:] = startval\n\n    for i in 1:mcit-1\n        sample[i+1,:] = sample[i,:]\n        for j in 1:size(sample, 2)\n            #update each variable by itself\n            sample[i+1,j] = condist[j](sample[i+1,:])\n        end\n    end\n    return sample[burn+1:mcit,:]\nend\n\nfunction tresample(\n    sset::Array,\n    hatw::Array\n    )\n    snum = size(sset,1)\n    rsset = zeros(snum, size(sset,2))\n    hatwn = zeros(snum, 1)\n    number = [1:snum...]\n\n    for i in 1:snum\n        #resample according to weight\n        resample = StatsBase.sample(number, ProbabilityWeights(vec(hatw)))\n        rsset[i,:] = sset[resample, :]\n        hatwn[i] = hatw[resample]\n    end\n    return rsset, hatwn\nend\n\nfunction calcbeta(\n    likelihood::Function,\n    betaj::Float64,\n    sset::Array,\n    snum::Int64\n    )\n\n    betaj1 = betaj + (1.1 - betaj)*0.5\n    likelihoodcov = zeros(snum, 1)\n    step = (1.1 - betaj)*0.25\n    cov = 0\n\n    for i in 1:snum\n        likelihoodcov[i] = likelihood(sset[i,:])\n    end\n    #beta approximates so that coefficient of variance --> 1\n    while cov> 1.0001 || cov < 0.9999\n        cov = std(likelihoodcov.^(betaj1-betaj))/mean(likelihoodcov.^(betaj1-betaj))\n        if cov < 1\n            betaj1 += step\n            step = 0.5*step\n        else\n            betaj1 -= step\n            step = 0.5*step\n        end\n        if betaj1>1\n            break\n        end\n    end\n    betaj1 = min(1, betaj1)\n    return betaj1, likelihoodcov.^(betaj1-betaj)\nend\n\nfunction calcsigma(\n    sset::Array,\n    hatw::Array,\n    gamma::Real\n    )\n    sdim = size(sset, 2)\n    snum = size(sset, 1)\n\n    thet = zeros(sdim, 1)\n    sig = zeros(sdim, sdim)\n\n    #formula for calculating Sigma in Ching and Chen 2007\n    for i in 1:snum\n        thet = thet + sset[i,:].*hatw[i]\n    end\n\n    for i in 1:snum\n        sig = sig + ((sset[i,:]-thet)*(sset[i,:]-thet)').*hatw[i]\n    end\n    sig = sig.*gamma^2\n\n    return sig\nend\n\nfunction tmcmc(\n    likelihood::Function,\n    prior::Function,\n    priorsample::Function,\n    snum::Int64,\n    gamma::Real\n    )\n\n    j = 0\n    betaj = 0.0\n    sset = priorsample(snum)\n\n\n    while betaj < 1\n        betaj1, w = calcbeta(likelihood, betaj, sset, snum)\n        hatw = w./sum(w)#normalize\n\n        sset, w = tresample(sset, hatw)\n        hatw = w./sum(w)\n\n        sig = calcsigma(sset, hatw, gamma)\n\n        for i in 1:snum\n            #MH step for each sample\n            mvpropdist = MvNormal(zeros(size(sset, 2)), sig)\n            propdistsample() = rand(mvpropdist)\n            propdistpdf(x) = pdf(mvpropdist, x)\n            likelihoodbeta(x) = likelihood(x)^(betaj1)\n            sset[i,:] = mh(likelihoodbeta, prior, propdistpdf, propdistsample, sset[i,:], 2,1)\n        end\n        betaj = betaj1\n    end\n\n    return sset\nend\n\nfunction resample(\n    sset::Array,\n    hatw::Array\n    )\n    snum = size(sset,1)\n    rsset = zeros(snum, size(sset,2))\n    number = [1:snum...]\n\n    for i in 1:snum\n        #weighted resampling\n        resample = StatsBase.sample(number, ProbabilityWeights(vec(hatw)))\n        rsset[i,:] = sset[resample, :]\n    end\n\n    return rsset\nend\n\nfunction smc(\n    likelihood::Function,\n    prior::Function,\n    priorsample::Function,\n    propdistpdf::Function,\n    propdistsample::Function,\n    snum::Int64,\n    term::Function\n    )\n\n    j = 0\n    sset = priorsample(snum)\n    w = zeros(snum,1)\n\n    #calculate weights\n    for i in 1:snum\n        w[i] = likelihood(sset[i,:])*prior(sset[i,:])\n    end\n\n    hatw = w./sum(w)#normalize\n\n    while term(sset, j)\n        j += 1\n        Neff = 1/sum(hatw.^2)#efficient sample size\n        if Neff < snum/2 #test for degeneracy\n            sset = resample(sset, hatw)\n            hatw = ones(snum,1)./snum\n        end\n\n        rsset = zeros(snum, size(sset,2))\n        w = zeros(snum, 1)\n\n        for i in 1:snum\n            #one step in a random direction\n            rsset[i,:] = sset[i,:] + propdistsample()\n            w[i] = hatw[i].*likelihood(rsset[i,:])/likelihood(sset[i,:])*\n                prior(rsset[i,:])/prior(sset[i,:])*\n                propdistpdf(rsset[i,:]-sset[i,:])/propdistpdf(sset[i,:]-rsset[i,:])\n        end\n\n        sset = rsset\n        hatw = w./sum(w)\n    end\n    return sset\nend\n\nfunction calcequaltails(\n    dsample::Array,\n    quantile::Float64,\n    )\n    snum = size(dsample, 1)\n    dsample = sort(dsample, dims = 1)\n\n    #calc cutoff points\n    low = floor(Int32,snum*(1-quantile)/2)\n    high = floor(Int32,snum - snum*(1-quantile)/2)\n\n    rv = zeros(2, size(dsample,2))\n\n    for i in 1:size(dsample,2)\n        rv[:,i] = [dsample[low,i]; dsample[high,i]]\n    end\n    return rv\nend\n\nfunction grconvergence(\n    likelihood::Function,\n    prior::Function,\n    priorsample::Function,\n    propdistpdf::Function,\n    propdistsample::Function,\n    mcit::Int64,\n    nchains::Int64\n    )\n\n    startval = priorsample(nchains)\n    dims = size(startval, 2)\n    rhat = 0\n    mcitb = floor(Int, mcit/2)\n    samples = zeros(floor(Int, mcit/2), size(startval,2), nchains)\n\n    #create n Markov chains\n    for i in 1:nchains\n        samples[:,:,i] = mh(likelihood, prior, propdistpdf, propdistsample,startval[i,:], mcit, floor(Int, mcit/2))\n    end\n\n    if dims == 1\n        chainvariance = zeros(nchains)\n        chainmean = zeros(nchains)\n        overallmean = 0\n        for i in 1:nchains\n            chainmean[i] = mean(samples[:,1,i], dims=1)[1]\n            overallmean += chainmean[i]/nchains\n            for j in 1:floor(Int,mcit/2) chainvariance[i] += (samples[j,1,i] - chainmean[i])^2 end\n        end\n        #vector of variances for each chain\n        chainvariance = chainvariance./(mcitb-1)\n\n        #variance of all chains\n        mvariance = 0\n        for i in 1:nchains mvariance += chainvariance[i]/nchains end\n\n        #variance bias estimator\n        Bn = 0\n        for i in 1:nchains Bn += (chainmean[i]-overallmean)^2 end\n        Bn = Bn/(nchains-1)\n\n        #over corrected variance\n        sig2 = ((mcitb-1)/mcitb)*mvariance + Bn\n\n        rhat = sqrt(sig2/mvariance)\n    else\n        chainvariance = zeros(dims, dims, nchains)\n        chainmean = zeros(dims, nchains)\n        overallmean = zeros(dims)\n\n        for i in 1:nchains\n            chainmean[:, i] = mean(samples[:,:,i], dims=1)\n            overallmean += chainmean[:, i]./nchains\n            for j in 1:floor(Int, mcit/2)\n                v = samples[j,:,i]-chainmean[:,i]\n                chainvariance[:,:,i] += v*v'\n            end\n        end\n        #array of covariance matrices for each chain\n        chainvariance = chainvariance./(mcitb-1)\n\n        #covariance matrix of all chains\n        mvariance = zeros(dims, dims)\n        for i in 1:nchains mvariance += chainvariance[:,:,i]./nchains end\n\n        #bias estimator\n        Bn = zeros(dims, dims)\n        for i in 1:nchains\n            v = chainmean[:,i] - overallmean\n            Bn += v*v'\n        end\n\n        Bn = Bn*mcitb/(nchains-1)\n        mvariance = inv(mvariance)\n        maxeig = maximum(eigvals(mvariance*Bn))\n\n        rhat = sqrt((mcitb-1)/mcitb + maxeig/mcitb)\n    end\n\n    return rhat\nend\n", "meta": {"hexsha": "c1334aab0ea5d32a94287b62553b697d69a1bd18", "size": 8014, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simulations/bayesianinference.jl", "max_stars_repo_name": "sitoryu/UncertaintyQuantification.jl", "max_stars_repo_head_hexsha": "f0e63fd3bfc176d8271b83ee999923690331472f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulations/bayesianinference.jl", "max_issues_repo_name": "sitoryu/UncertaintyQuantification.jl", "max_issues_repo_head_hexsha": "f0e63fd3bfc176d8271b83ee999923690331472f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulations/bayesianinference.jl", "max_forks_repo_name": "sitoryu/UncertaintyQuantification.jl", "max_forks_repo_head_hexsha": "f0e63fd3bfc176d8271b83ee999923690331472f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2848484848, "max_line_length": 115, "alphanum_fraction": 0.5618916895, "num_tokens": 2501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816422, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7740378672689359}}
{"text": "#=\nSquare-function with gradient\n=#\nfunction f_square(x)\n    return x^2\nend\n\nfunction g_square(x)\n    return 2*x\nend\n\n#=\nLogistic-regression loss-function, gradient and sub-gradient\n=#\n\nfunction f_logreg()\n    return function(x_i,y_i,θ,λ)\n        return log(1+exp(-y_i*dot(θ,x_i)))\n    end\nend\n\nfunction f_logreg(X,y,θ,λ)\n    return function(θ)\n        data = X\n        labels = y\n        λ = λ\n        funcVal = 0\n        # size(data,1) = 1000 datapoints\n        for i in 1:size(data,1)\n            # x = 784*1 column vector\n            x_i = data[i:i,:]'\n            funcVal += log( 1+ exp(-labels[i] * dot(θ,x_i) ) )\n        end\n        funcVal += λ/2*(norm(θ,2)^2)\n        return funcVal\n    end\nend\n\nfunction g_logreg(X,y,θ,λ)\n    return function(θ)\n        data = X\n        labels = y\n        λ = λ\n        # n-dim-column-vector\n        array = zeros(size(data,2))\n        # add l2 norm\n        array += λ * θ\n        # iterate datapoints\n        for i in 1:size(data,1)\n            # pick i-th datapoint\n        \tx_i = data[i:i,:]'\n            exponential = exp(-labels[i]*dot(θ,x_i))\n            array += (-labels[i]*x_i * exponential)/(1+exponential)\n        end\n        return array\n    end\nend\n\nfunction sub_g_logreg()\n        return function(x_i,y_i,θ,λ)\n              exponential = exp(-y_i*dot(θ,x_i))\n              return (-y_i * x_i * exponential) / ( 1 + exponential ) + λ * θ\n        end\nend\n\n#=\nhinge-loss - Loss-function and gradient\n=#\nfunction f_svm(X,y,θ,λ)\n    return function(θ)\n        X = X\n        y = y\n        λ = λ\n        fval = 0\n        # datapoints\n        for i in 1:size(X,1)\n            x_i = X[i:i,:]'\n            fval += max(0, (1 - y[i]*dot(θ,x_i)))\n        end\n        fval = fval / size(X,1)\n        fval += λ/2 * norm(θ,2)\n        return fval\n    end\nend\n\n#=\nCompute the gradient for one datapoint for hinge-loss.\n=#\nfunction sub_g_svm()\n    return function(x_i,y_i,θ,λ)\n      val = 1 - (y_i * dot(θ,x_i))\n      if val < 0\n          return λ * θ;\n      else\n          return -y_i * x_i + λ * θ;\n      end\n  end\nend\n\n#=\nRosenbrock-function and its gradient.\n=#\nfunction f_rosenbrock(x_k)\n    return 100*(x_k[2]-x_k[1]^2)^2+(1-x_k[1])^2\nend\n\n\nfunction g_rosenbrock(x_k)\n    return [ -400*x_k[1]*(x_k[2]-x_k[1]^2)-2(1-x_k[1]) ; 200*x_k[1]*(x_k[2]-x_k[1]^2) ]\nend\n", "meta": {"hexsha": "2f13e63dacb5ad4079fc26fbe08952ff2dbe2c0a", "size": 2304, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/Functions.jl", "max_stars_repo_name": "zagazao/num-opt", "max_stars_repo_head_hexsha": "54444008be831a7bb51e845b688f41b5239d285d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-02-01T11:02:20.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-11T22:51:30.000Z", "max_issues_repo_path": "src/functions/Functions.jl", "max_issues_repo_name": "zagazao/num-opt", "max_issues_repo_head_hexsha": "54444008be831a7bb51e845b688f41b5239d285d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/Functions.jl", "max_forks_repo_name": "zagazao/num-opt", "max_forks_repo_head_hexsha": "54444008be831a7bb51e845b688f41b5239d285d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7567567568, "max_line_length": 87, "alphanum_fraction": 0.5212673611, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7740378563344968}}
{"text": "function exp!(X::IntervalBox)\n    x, y = X\n\n    y = y ∩ exp(x)\n    x = x ∩ log(y)\n\n    return IntervalBox(x, y)\nend\n\n\"\"\"\nReverse function for `exp`.\n\"\"\"\nfunction exp_rev(y::Interval, x::Interval)\n    y_new = y ∩ (0..∞)\n    x_new = x ∩ log(y)\n    return y_new, x_new\nend\n\n\"\"\"\nReverse function for `exp2`.\n\"\"\"\nfunction exp2_rev(y::Interval, x::Interval)\n    y_new = y ∩ (0..∞)\n    x_new = x ∩ log2(y)\n\n    return y_new, x_new\nend\n\n\"\"\"\nReverse function for `exp10`.\n\"\"\"\nfunction exp10_rev(y::Interval, x::Interval)\n    y_new = y ∩ (0..∞)\n    x_new = x ∩ log10(y)\n\n    return y_new, x_new\nend\n\n\"\"\"\nReverse function for `expm1`.\n\"\"\"\nfunction expm1_rev(y::Interval, x::Interval)\n    y_new = y ∩ (-1.0..∞)\n    x_new = x ∩ log1p(y)\n\n    return y_new, x_new\nend\n\n\nfunction log!(X::IntervalBox)  # y = log(x)\n    x, y = X\n\n    x = x ∩ exp(y)\n    y = y ∩ log(x)\n\n    return IntervalBox(x, y)\nend\n\n\"\"\"\nReverse function for `log`: ``y = \\\\log(x)``\n\"\"\"\nfunction log_rev(y::Interval, x::Interval)\n    x_new = x ∩ exp(y)\n\n    return y, x_new\nend\n\n\"\"\"\nReverse function for `log2`: ``y = \\\\log2(x)``\n\"\"\"\nfunction log2_rev(y::Interval, x::Interval)\n    x_new = x ∩ exp2(y)\n\n    return y, x_new\nend\n\n\n\"\"\"\nReverse function for `log10`: ``y = \\\\log10(x)``\n\"\"\"\nfunction log10_rev(y::Interval, x::Interval)\n    x_new = x ∩ exp10(y)\n\n    return y, x_new\nend\n\n\"\"\"\nReverse function for `log1p`: ``y = \\\\log1p(x)``\n\"\"\"\nfunction log1p_rev(y::Interval, x::Interval)\n    x_new = x ∩ expm1(y)\n\n    return y, x_new\nend\n", "meta": {"hexsha": "743f16e0ccec72f9a4cd52a061d43fdaa13fc489", "size": 1486, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/exponential.jl", "max_stars_repo_name": "kaarthiksundar/IntervalContractors.jl", "max_stars_repo_head_hexsha": "488b206aafc6e562655a0e395a0d6ca2217272ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-02-27T20:15:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T17:55:10.000Z", "max_issues_repo_path": "src/exponential.jl", "max_issues_repo_name": "kaarthiksundar/IntervalContractors.jl", "max_issues_repo_head_hexsha": "488b206aafc6e562655a0e395a0d6ca2217272ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2017-05-03T14:08:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-04T20:43:33.000Z", "max_forks_repo_path": "src/exponential.jl", "max_forks_repo_name": "kaarthiksundar/IntervalContractors.jl", "max_forks_repo_head_hexsha": "488b206aafc6e562655a0e395a0d6ca2217272ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-05-04T04:46:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T23:30:35.000Z", "avg_line_length": 15.6421052632, "max_line_length": 48, "alphanum_fraction": 0.5767160162, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7740378552766335}}
{"text": "using ReachabilityAnalysis, Symbolics, Plots\n\n@variables x y z\nconst positive_orthant = HPolyhedron([x >= 0, y >= 0, z >= 0], [x, y, z])\n\nfunction prod_dest_verif(sol; T=100.0, target=10.0)\n\n    # convert to a zonotopic flowpipe\n    solz = overapproximate(sol, Zonotope)\n\n    # project the final reach-set onto the space variables x, y, z\n    X = project(solz(T), vars=(1, 2, 3))\n\n    # check that all variables are nonnegative\n    nonnegative = X ⊆ positive_orthant\n\n    # compute the volume of the last reach-set\n    H = overapproximate(X, Hyperrectangle)\n    vol = volume(H)\n\n    # check that that target belongs to the minkowski sum of the reach-sets projected in each coordinate\n    B = convert(IntervalBox, H) # get the product-of-intervals representation\n    contains_target = target ∈ sum(B)\n\n    return nonnegative && contains_target, vol\nend\n\n@taylorize function prod_dest_I!(du, u, params, t)\n    local a = 0.3\n    x, y, z = u[1], u[2], u[3]\n\n    du[1] = - (x * y) / (1 + x)\n    du[2] = (x * y) / (1 + x) - a * y\n    du[3] = a * y\n    return du\nend\n\nX0 = (9.5 .. 10.0) × (0.01 .. 0.01) × (0.01 .. 0.01)\nprob = @ivp(x'= prod_dest_I!(x), dim:3, x(0) ∈ X0)\n\nsolI = solve(prob, T=100.0, alg=TMJets(abstol=1e-11, orderT=7, orderQ=1));\n\nproperty, vol = prod_dest_verif(solI)\n\nplot(solI, vars=(0, 3), linecolor=:orange, color=:orange, alpha=0.3, lab=\"I\")\n\n@taylorize function prod_dest_IP!(du, u, params, t)\n    x, y, z, a = u[1], u[2], u[3], u[4]\n\n    du[1] = - (x * y) / (1 + x)\n    du[2] = (x * y) / (1 + x) - a * y\n    du[3] = a * y\n    du[4] = zero(x)\n    return du\nend\n\nX0 = (9.98 .. 9.98) × (0.01 .. 0.01) × (0.01 .. 0.01) × (0.296 .. 0.304)\nprob = @ivp(x'= prod_dest_IP!(x), dim:4, x(0) ∈ X0)\n\nsolP = solve(prob, T=100.0, alg=TMJets(abstol=1e-12, orderT=7, orderQ=1));\n\nproperty, vol = prod_dest_verif(solP)\n\nplot(solP, vars=(0, 3), linecolor=:blue, color=:blue, alpha=0.3, lab=\"P\")\n\nX0 = (9.5 .. 10.0) × (0.01 .. 0.01) × (0.01 .. 0.01) × (0.296 .. 0.304)\nprob = @ivp(x'= prod_dest_IP!(x), dim:4, x(0) ∈ X0)\n\nsolIP = solve(prob, T=100.0, alg=TMJets(abstol=1e-11, orderT=7, orderQ=1));\n\nproperty, vol = prod_dest_verif(solIP)\n\nplot(solIP, vars=(0, 3), linecolor=:red, color=:red, alpha=0.3, lab=\"I & P\")\n\n@taylorize function prod_dest_I_optimized!(du, u, params, t)\n    local a = 0.3\n    x, y, z = u[1], u[2], u[3]\n\n    num = x * y\n    den = 1 + x\n    aux = num/den\n    aux2 = a * y\n    du[1] = -aux\n    du[2] = aux - aux2\n    du[3] = aux2\n    return du\nend\n\n@taylorize function prod_dest_IP_optimized!(du, u, params, t)\n    x, y, z, a = u[1], u[2], u[3], u[4]\n\n    num = x * y\n    den = 1 + x\n    aux = num/den\n    aux2 = a * y\n    du[1] = -aux\n    du[2] = aux - aux2\n    du[3] = aux2\n    du[4] = zero(x)\n    return du\nend\n\n", "meta": {"hexsha": "e3a1a3c418908cb85a929eee5abd25751de28909", "size": 2736, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/models/ProductionDestruction.jl", "max_stars_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_stars_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2020-03-30T16:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:26:48.000Z", "max_issues_repo_path": "test/models/ProductionDestruction.jl", "max_issues_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_issues_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 258, "max_issues_repo_issues_event_min_datetime": "2020-03-30T14:13:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T17:07:04.000Z", "max_forks_repo_path": "test/models/ProductionDestruction.jl", "max_forks_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_forks_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-04-23T03:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T23:11:32.000Z", "avg_line_length": 26.5631067961, "max_line_length": 104, "alphanum_fraction": 0.5760233918, "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7740378543357799}}
{"text": "export Poisson\n\n\"\"\"\nDescription:\n\n    Poisson factor node\n\n    Real scalars\n    l > 0 (rate)\n\n    f(out, l) = Poisson(out|l) = 1/(x!) * l^x * exp(-l)\n\nInterfaces:\n\n    1. out\n    2. l\n\nConstruction:\n\n    Poisson(id=:some_id)\n\"\"\"\nmutable struct Poisson <: SoftFactor\n    id::Symbol\n    interfaces::Vector{Interface}\n    i::Dict{Symbol,Interface}\n\n    function Poisson(out, l; id=generateId(Poisson))\n        @ensureVariables(out, l)\n        self = new(id, Array{Interface}(undef, 2), Dict{Symbol, Interface}())\n        addNode!(currentGraph(), self)\n        self.i[:out] = self.interfaces[1] = associate!(Interface(self), out)\n        self.i[:l] = self.interfaces[2] = associate!(Interface(self), l)\n        return self\n    end\nend\n\nslug(::Type{Poisson}) = \"Poisson\"\n\nformat(dist::ProbabilityDistribution{Univariate, Poisson}) = \"$(slug(Poisson))(l=$(format(dist.params[:l])))\"\n\nProbabilityDistribution(::Type{Univariate}, ::Type{Poisson}; l=1.0) = ProbabilityDistribution{Univariate, Poisson}(Dict(:l=>l))\nProbabilityDistribution(::Type{Poisson}; l=1.0) = ProbabilityDistribution{Univariate, Poisson}(Dict(:l=>l))\n\ndims(dist::ProbabilityDistribution{Univariate, Poisson}) = 1\n\nvague(::Type{Poisson}) = ProbabilityDistribution(Univariate, Poisson, l=huge)\n\nisProper(dist::ProbabilityDistribution{Univariate, Poisson}) = (0 < dist.params[:l] < huge)\n\nunsafeMean(dist::ProbabilityDistribution{Univariate, Poisson}) = Float64(dist.params[:l])\n\nunsafeVar(dist::ProbabilityDistribution{Univariate, Poisson}) = Float64(dist.params[:l])\n\nlogPdf(dist::ProbabilityDistribution{Univariate, Poisson}, x) = x*log(dist.params[:l]) - dist.params[:l] - logfactorial(x)\n\nsample(dist::ProbabilityDistribution{Univariate, Poisson}) = poisinvcdf(dist.params[:l], rand())\n\n# ∑ [λ^k*log(k!)]/k! from k=0 to inf\n# Approximates the above sum for calculation of averageEnergy and differentialEntropy\n# @ref https://arxiv.org/pdf/1708.06394.pdf\nfunction apprSum(l, j=100)\n    sum([(l)^(k)*logfactorial(k)/exp(logfactorial(k)) for k in collect(0:j)])\nend\n\n# Entropy functional\n# @ref https://en.wikipedia.org/wiki/Poisson_distribution\nfunction differentialEntropy(dist::ProbabilityDistribution{Univariate, Poisson})\n    l = clamp(dist.params[:l], tiny, huge)\n    l*(1-log(l)) + exp(-l)*apprSum(l)\nend\n\n# Average energy functional\nfunction averageEnergy(::Type{Poisson}, marg_out::ProbabilityDistribution{Univariate}, marg_l::ProbabilityDistribution{Univariate})\n    unsafeMean(marg_l) -\n    unsafeMean(marg_out)*unsafeLogMean(marg_l) +\n    exp(-unsafeMean(marg_out))*apprSum(unsafeMean(marg_out))\nend\n", "meta": {"hexsha": "fb697dda92942aabee301aac27e692cefac5d93e", "size": 2574, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/factor_nodes/poisson.jl", "max_stars_repo_name": "biaslab/ForneyLab.jl", "max_stars_repo_head_hexsha": "b10b7200bec8696dc2c5d96bb3a0b8e64126614e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 124, "max_stars_repo_stars_event_min_datetime": "2018-06-28T13:30:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T05:33:24.000Z", "max_issues_repo_path": "src/factor_nodes/poisson.jl", "max_issues_repo_name": "biaslab/ForneyLab.jl", "max_issues_repo_head_hexsha": "b10b7200bec8696dc2c5d96bb3a0b8e64126614e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 120, "max_issues_repo_issues_event_min_datetime": "2018-08-29T14:29:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T13:48:44.000Z", "max_forks_repo_path": "src/factor_nodes/poisson.jl", "max_forks_repo_name": "biaslab/ForneyLab.jl", "max_forks_repo_head_hexsha": "b10b7200bec8696dc2c5d96bb3a0b8e64126614e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2018-07-12T08:19:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T02:49:44.000Z", "avg_line_length": 33.0, "max_line_length": 131, "alphanum_fraction": 0.7086247086, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701655, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7740378513962088}}
{"text": "function assemble_system!(problem::AllenCahnProblem1D{TLBC, TRBC, TA}) where {TLBC <: NeumannBC, TRBC <: NeumannBC, TA <: SparseMatrixCSC}   \n    # Construct first row corresponding to uₓ(a) = vₗ\n    problem.A[1,1] = -2\n    problem.A[1,2] = 2\n\n    # Construct rows corresponding to interior mesh points\n    for i ∈ 2:problem.nₓ + 1\n        problem.A[i, i - 1] = 1\n        problem.A[i,i] = -2\n        problem.A[i, i + 1] = 1\n    end\n\n    # Construct last row corresponding to uₓ(b) = vᵣ\n    problem.A[end, end] = -2\n    problem.A[end, end - 1] = 2\n\n    @. problem.A *= 1/(problem.Δx)^2\n    \n    return problem\nend\n\nfunction assemble_system!(problem::AllenCahnProblem1D{TLBC, TRBC, TA}) where {TLBC <: PeriodicBC, TRBC <: PeriodicBC, TA <: SparseMatrixCSC}   \n    # Construct first row corresponding to u₀\n    problem.A[1,1] = -2\n    problem.A[1,2] = 1\n    problem.A[1, end] = 1\n\n    # Construct rows corresponding to interior mesh points\n    for i ∈ 2:problem.nₓ\n        problem.A[i, i - 1] = 1\n        problem.A[i,i] = -2\n        problem.A[i, i + 1] = 1\n    end\n\n    # Construct last row corresponding to uₙ\n    problem.A[end, 1] = 1\n    problem.A[end, end - 1] = 1\n    problem.A[end, end] = -2\n\n    @. problem.A *= 1/(problem.Δx)^2\n    \n    return problem\nend", "meta": {"hexsha": "1607b6fab749551670cab855706212cfde0dc6f1", "size": 1260, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/assembly.jl", "max_stars_repo_name": "liamfdoherty/AllenCahn.jl", "max_stars_repo_head_hexsha": "871aa90a7216feb00c84a600883d9531a197e7f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/assembly.jl", "max_issues_repo_name": "liamfdoherty/AllenCahn.jl", "max_issues_repo_head_hexsha": "871aa90a7216feb00c84a600883d9531a197e7f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/assembly.jl", "max_forks_repo_name": "liamfdoherty/AllenCahn.jl", "max_forks_repo_head_hexsha": "871aa90a7216feb00c84a600883d9531a197e7f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3023255814, "max_line_length": 143, "alphanum_fraction": 0.5976190476, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7740378499264233}}
{"text": "\"\"\"\nA SYK model solver based on a forward fixed-point iteration method.\n\n The self-energy of the SYK model is given by,\n\n    Σ(τ) = J² * G(τ) * G(τ) * G(β-τ),\n    \n where Green's function of the SYK model is given by the Dyson equation,\n\n    G(iωₙ) = -1/(iωₙ -μ + Σ(iωₙ))\n\n We solve the Dyson equation self-consistently by a weighted fixed point iteration, \n with weight `mix` assigned to the new iterate and weight `1-mix` assigned to the previous iterate. \n\n The self-energy is evaluated in the imaginary time domain, \n and the Dyson equation is solved in the Matsubara frequency domain.\n\n The SYK Green's function has particle-hole symmetry when μ=0. \n You may enforce such symmetry by setting `symmetry = :ph` when initialize the DLR grids.\n A symmetrized solver tends to be more robust than a unsymmetrized one.\n\"\"\"\n\nusing Lehmann\nusing Printf\n\ndiff(a, b) = maximum(abs.(a - b)) # return the maximum deviation between a and b\n\nconformal_tau(τ, β) = π^(1 / 4) / sqrt(2β) * 1 / sqrt(sin(π * τ / β))\n\nfunction syk_sigma_dlr(d, G_x, J = 1.0; sumrule = nothing, verbose = false)\n\n    tau_k = d.τ # DLR imaginary time nodes\n    tau_k_rev = d.β .- tau_k # Reversed imaginary time nodes\n\n    G_x_rev = tau2tau(d, G_x, tau_k_rev, sumrule = sumrule, verbose = verbose) # G at beta - tau_k\n\n    Sigma_x = J .^ 2 .* G_x .^ 2 .* G_x_rev # SYK self-energy in imaginary time\n\n    return Sigma_x\nend\n\nfunction dyson(d, sigma_q, mu)\n    if d.symmetry == :ph #symmetrized G\n        @assert mu ≈ 0.0 \"Only the case μ=0 enjoys the particle-hole symmetry.\"\n        return 1im * imag.(-1 ./ (d.ωn * 1im .- mu .+ sigma_q))\n    elseif d.symmetry == :none\n        return -1 ./ (d.ωn * 1im .- mu .+ sigma_q)\n    else\n        error(\"Not implemented!\")\n    end\nend\n\nfunction solve_syk_with_fixpoint_iter(d, mu, tol = d.rtol * 10; mix = 0.1, maxiter = 5000, G_x = zeros(ComplexF64, length(d)), sumrule = nothing, verbose = true)\n\n    for iter in 1:maxiter\n\n        Sigma_x = syk_sigma_dlr(d, G_x, sumrule = sumrule, verbose = verbose)\n\n        G_q_new = dyson(d, tau2matfreq(d, Sigma_x), mu)\n\n        G_x_new = matfreq2tau(d, G_q_new, sumrule = sumrule, verbose = verbose)\n\n\n        if verbose\n            if iter % (maxiter / 10) == 0\n                println(\"round $iter: change $(diff(G_x_new, G_x))\")\n            end\n        end\n        if maximum(abs.(G_x_new .- G_x)) < tol && iter > 10\n            break\n        end\n\n        G_x = mix * G_x_new + (1 - mix) * G_x # Linear mixing\n    end\n    return G_x\nend\n\nfunction printG(d, G_x)\n    @printf(\"%15s%40s%40s%40s\\n\", \"τ\", \"DLR imag\", \"DLR real\", \"asymtotically exact\")\n    for i in 1:d.size\n        if d.τ[i] <= d.β / 2\n            @printf(\"%15.8f%40.15f%40.15f%40.15f\\n\", d.τ[i], imag(G_x[i]), real(G_x[i]), conformal_tau(d.τ[i], d.β))\n        end\n    end\n    println()\nend\n\nverbose = false\n\nprintstyled(\"=====    Prepare the expected Green's function of the SYK model     =======\\n\", color = :yellow)\ndsym_correct = DLRGrid(Euv = 5.0, β = 10000.0, isFermi = true, rtol = 1e-14, symmetry = :ph) # Initialize DLR object\nG_x_correct = solve_syk_with_fixpoint_iter(dsym_correct, 0.00, mix = 0.1, verbose = false)\nprintG(dsym_correct, G_x_correct)\n\nprintstyled(\"=====    Test Symmetrized and Unsymmetrized DLR solver for SYK model     =======\\n\", color = :yellow)\n\n@printf(\"%30s%30s%30s%30s%20s\\n\", \"Euv\", \"sym_solver\", \"unsym_solver\", \"unsym_solver+sum_rule\", \"good or bad\")\nfor Euv in LinRange(5.0, 10.0, 50)\n\n    rtol = 1e-10\n    β = 10000.0\n    # printstyled(\"=====     Symmetrized DLR solver for SYK model     =======\\n\", color = :yellow)\n    mix = 0.01\n    dsym = DLRGrid(Euv = Euv, β = β, isFermi = true, rtol = rtol, symmetry = :ph, rebuild = true, verbose = false) # Initialize DLR object\n    G_x_ph = solve_syk_with_fixpoint_iter(dsym, 0.00, mix = mix, sumrule = nothing, verbose = verbose)\n\n    # printstyled(\"=====     Unsymmetrized DLR solver for SYK model     =======\\n\", color = :yellow)\n    mix = 0.01\n    dnone = DLRGrid(Euv = Euv, β = β, isFermi = true, rtol = rtol, symmetry = :none, rebuild = true, verbose = false) # Initialize DLR object\n    G_x_none = solve_syk_with_fixpoint_iter(dnone, 0.00, mix = mix, sumrule = nothing, verbose = verbose)\n\n    # printstyled(\"=====     Unsymmetrized DLR solver for SYK model     =======\\n\", color = :yellow)\n    mix = 0.01\n    G_x_none_sumrule = solve_syk_with_fixpoint_iter(dnone, 0.00, mix = mix, sumrule = 1.0, verbose = verbose)\n    # printG(dnone, G_x_none)\n\n    # printstyled(\"=====     Unsymmetrized versus Symmetrized DLR solver    =======\\n\", color = :yellow)\n    # @printf(\"%15s%40s%40s%40s\\n\", \"τ\", \"sym DLR (interpolated)\", \"unsym DLR\", \"difference\")\n    # G_x_interp = tau2tau(dsym_correct, G_x_correct, dnone.τ)\n    # for i in 1:dnone.size\n    #     if dnone.τ[i] <= dnone.β / 2\n    #         @printf(\"%15.8f%40.15f%40.15f%40.15f\\n\", dnone.τ[i], real(G_x_interp[i]), real(G_x_none[i]), abs(real(G_x_interp[i] - G_x_none[i])))\n    #     end\n    # end\n\n    G_x_interp_ph = tau2tau(dsym_correct, G_x_correct, dsym.τ)\n    G_x_interp_none = tau2tau(dsym_correct, G_x_correct, dnone.τ)\n    G_x_interp_none_sumrule = tau2tau(dsym_correct, G_x_correct, dnone.τ)\n    d_ph = diff(G_x_interp_ph, G_x_ph)\n    d_none = diff(G_x_interp_none, G_x_none)\n    d_none_sumrule = diff(G_x_interp_none_sumrule, G_x_none_sumrule)\n    flag = (d_ph < 100rtol) && (d_none < 100rtol) && (d_none_sumrule < 100rtol) ? \"good\" : \"bad\"\n\n    @printf(\"%30.15f%30.15e%30.15e%30.15e%20s\\n\", Euv, d_ph, d_none, d_none_sumrule, flag)\n    # println(\"symmetric Euv = $Euv maximumal difference: \", diff(G_x_interp, G_x_ph))\n    # println(\"non symmetric Euv = $Euv maximumal difference: \", diff(G_x_interp, G_x_none))\n\nend\n\n\n", "meta": {"hexsha": "b980d6710fd1245265b2c15af1ba2cc4bb47a5be", "size": 5685, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/SYK.jl", "max_stars_repo_name": "kunyuan/Lehmann.jl", "max_stars_repo_head_hexsha": "c417f12baa7a44019e6908a914833d1166afcceb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-07-12T01:43:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T15:11:34.000Z", "max_issues_repo_path": "example/SYK.jl", "max_issues_repo_name": "kunyuan/Lehmann.jl", "max_issues_repo_head_hexsha": "c417f12baa7a44019e6908a914833d1166afcceb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-15T01:22:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-11T03:13:02.000Z", "max_forks_repo_path": "example/SYK.jl", "max_forks_repo_name": "quantumstatistics/Lehmann.jl", "max_forks_repo_head_hexsha": "c417f12baa7a44019e6908a914833d1166afcceb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3191489362, "max_line_length": 161, "alphanum_fraction": 0.6397537379, "num_tokens": 1913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7739535443210853}}
{"text": "#=\nThe decimal number, 585 = 1001001001 (binary), is palindromic in both bases.\n\nFind the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.\n\n(Please note that the palindromic number, in either base, may not include leading zeros.)\n=#\n\nfunction isdecpalindrome(a)\n  digits(a) == reverse(digits(a))\nend\n\nfunction isbinarypalindrome(a)\n  digits(a, base=2) == reverse(digits(a, base=2))\nend\n\nfunction calc()\n  total = 0\n  for i in 1:999_999\n    if isdecpalindrome(i) && isbinarypalindrome(i)\n      total += i\n    end\n  end\n  total\nend\n@time println(calc())\n", "meta": {"hexsha": "59da1184700de2c064ce0eb01ada12255458ff55", "size": 591, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p36.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p36.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p36.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 21.8888888889, "max_line_length": 96, "alphanum_fraction": 0.7072758037, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7739535398369255}}
{"text": "# indicator of a simplex\n\n\"\"\"\n  IndSimplex(a::Union{Real, Integer}=1.0)\n\nReturns the function `g = ind{x : x ⩾ 0, sum(x) = a}`.\n\"\"\"\n\nimmutable IndSimplex{T <: Union{Real, Integer}} <: IndicatorConvex\n  a::T\n  function IndSimplex(a::T)\n    if a <= 0\n      error(\"parameter a must be positive\")\n    else\n      new(a)\n    end\n  end\nend\n\nIndSimplex{T <: Union{Real, Integer}}(a::T=1.0) = IndSimplex{T}(a)\n\nfunction (f::IndSimplex){T <: Real}(x::AbstractArray{T,1})\n  if all(x .>= 0) && abs(sum(x)-f.a) <= 1e-14\n    return 0.0\n  end\n  return +Inf\nend\n\nfunction prox!{T <: Real}(f::IndSimplex, x::AbstractArray{T}, y::AbstractArray{T}, gamma::Real=1.0)\n# Implements Algorithm 1 in Condat, \"Fast projection onto the simplex and the l1 ball\", Mathematical Programming, 158:575–585, 2016.\n# We should consider implementing the other algorithms reviewed there, and the one proposed in the paper.\n  n = length(x)\n  p = []\n  if ndims(x) == 1\n    p = sort(x, rev=true)\n  else\n    p = sort(x[:], rev=true)\n  end\n  s = 0\n  for i = 1:n-1\n    s = s + p[i]\n    tmax = (s - f.a)/i\n    if tmax >= p[i+1]\n      @inbounds for j in eachindex(y)\n        y[j] = x[j] < tmax ? 0.0 : x[j] - tmax\n      end\n      return 0.0\n    end\n  end\n  tmax = (s + p[n] - f.a)/n\n  @inbounds for j in eachindex(y)\n    y[j] = x[j] < tmax ? 0.0 : x[j] - tmax\n  end\n  return 0.0\nend\n\nfun_name(f::IndSimplex) = \"indicator of the probability simplex\"\nfun_dom(f::IndSimplex) = \"AbstractArray{Real}\"\nfun_expr(f::IndSimplex) = \"x ↦ 0 if x ⩾ 0 and sum(x) = a, +∞ otherwise\"\nfun_params(f::IndSimplex) = \"a = $(f.a)\"\n\nfunction prox_naive{T <: Real}(f::IndSimplex, x::AbstractArray{T}, gamma::Real=1.0)\n  low = minimum(x)\n  upp = maximum(x)\n  v = x\n  s = Inf\n  for i = 1:100\n    if abs(s)/f.a <= 1e-15\n      break\n    end\n    alpha = (low+upp)/2\n    v = max.(x - alpha, 0.0)\n    s = sum(v) - f.a\n    if s <= 0\n      upp = alpha\n    else\n      low = alpha\n    end\n  end\n  return v, 0.0\nend\n", "meta": {"hexsha": "76bcd85961c899f9380cc54dab9e467ebe78d0cb", "size": 1935, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indSimplex.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/indSimplex.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/indSimplex.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5975609756, "max_line_length": 132, "alphanum_fraction": 0.5834625323, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8723473746782093, "lm_q1q2_score": 0.7739505955298801}}
{"text": "# These examples illustrate common operations on polyhedra using [Polyhedra.jl](https://github.com/JuliaPolyhedra/Polyhedra.jl):\n#\n# - [Convex hull](#Convex-hull).\n# - [Intersection](#Intersection).\n#\n# We start by choosing a polyhedral library that will be used for computing the H-representation from the V-representation and vice-versa as well as removing redundant points.\n# In these example, we use the default library available in Polyhedra but it can be replaced by any other library listed [here](https://juliapolyhedra.github.io/), e.g. by changing the last two lines below by `import CDDLib` and `lib = CDDLib.Library()` to use [CDDLib](https://github.com/JuliaPolyhedra/CDDLib.jl).\n\nusing Test #jl\nusing Polyhedra\nimport GLPK\nlib = DefaultLibrary{Float64}(GLPK.Optimizer)\n\n# ### Convex hull <a name=\"Convex-hull\"></a>\n#\n# The binary convex hull operation between two polyhedra is obtained with the [`convexhull`](https://juliapolyhedra.github.io/Polyhedra.jl/latest/utilities.html#Polyhedra.convexhull) function.\n#\n# Below we compute the convex hull of the union of two polygons from their V-representation.\n\nP1 = polyhedron(vrep([\n    -1.9 -1.7\n    -1.8  0.5\n     1.7  0.7\n     1.9 -0.3\n     0.9 -1.1\n]), lib)\n\nP2 = polyhedron(vrep([\n    -2.5 -1.1\n    -0.8  0.8\n     0.1  0.9\n     1.8 -1.2\n     1.3  0.1\n]), lib)\n\nPch = convexhull(P1, P2)\n\n# Note that the convex hull operation is done in the V-representation so no representation conversion is needed for this operation since `P1` and `P2` where constructed from their V-representation:\n\nhrepiscomputed(P1), hrepiscomputed(P2), hrepiscomputed(Pch) #!jl\n@test (hrepiscomputed(P1), hrepiscomputed(P2), hrepiscomputed(Pch)) == (false, false, false) #jl\n\n# Let us note that the `convexhull` of a V-representation contains points and rays and represents the convex hull of the points together with the conic hull of the rays. So, `convexhull(P1, P2)` does the union of the vertices:\n\nnpoints(Pch) #!jl\n@test npoints(Pch) == 10 #jl\n\n# However, if we want to remove the redundant points we can use `removevredundancy!`:\n\nremovevredundancy!(Pch)\nnpoints(Pch) #!jl\n@test npoints(Pch) == 8 #jl\n\n# We can plot the polygons and the convex hull of their union using the `plot` function. For further plotting options see the [Plots.jl](http://docs.juliaplots.org/latest/) documentation.\n# We can see below the 8 redundant points highlighted with green dots, the two points that are not highlighted are the redundant ones.\n\nusing Plots                          #!jl\nplot(P1, color=\"blue\", alpha=0.2)    #!jl\nplot!(P2, color=\"red\", alpha=0.2)    #!jl\nplot!(Pch, color=\"green\", alpha=0.1) #!jl\nscatter!(Pch, color=\"green\")         #!jl\n\n# ### Intersection <a name=\"Intersection\"></a>\n#\n# Intersection of polyhedra is obtained with the [`intersect`](https://juliapolyhedra.github.io/Polyhedra.jl/latest/utilities.html#Base.intersect) function.\n#\n# Below we compute the intersection of the two polygons from the previous example.\n\nPint = intersect(P1, P2)\n@test nhalfspaces(Pint) == 10 #jl\n\n# While `P1` and `P2` have been constructed from their V-representation, their H-representation has been computed to build the intersection `Pint`.\n\nhrepiscomputed(P1), vrepiscomputed(P1), hrepiscomputed(P2), vrepiscomputed(P2) #!jl\n@test (hrepiscomputed(P1), vrepiscomputed(P1), hrepiscomputed(P2), vrepiscomputed(P2)) == (true, true, true, true) #jl\n\n# On the other hand, `Pint` is constructed from its H-representation hence its V-representation has not been computed yet.\n\nhrepiscomputed(Pint), vrepiscomputed(Pint) #!jl\n@test (hrepiscomputed(Pint), vrepiscomputed(Pint)) == (true, false) #jl\n\n# We can obtain the number of points in the intersection with `npoints` as follows:\n\nnpoints(Pint) #!jl\n@test npoints(Pint) == 8 #jl\n\n# Note that this triggers the computation of the V-representation:\n\nhrepiscomputed(Pint), vrepiscomputed(Pint) #!jl\n@test (hrepiscomputed(Pint), vrepiscomputed(Pint)) == (true, true) #jl\n\n# We can plot the polygons and their intersection using the `plot` function.\n\nusing Plots                            #!jl\nplot(P1, color=\"blue\", alpha=0.2)      #!jl\nplot!(P2, color=\"red\", alpha=0.2)      #!jl\nplot!(Pint, color=\"yellow\", alpha=0.6) #!jl\n", "meta": {"hexsha": "8713f26ed23b3659c7090469868bbed2dd970663", "size": 4209, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Convex hull and intersection.jl", "max_stars_repo_name": "bzinberg/Polyhedra.jl", "max_stars_repo_head_hexsha": "6ce8dd1fb75f7d4937b280951cef86bc367d6588", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Convex hull and intersection.jl", "max_issues_repo_name": "bzinberg/Polyhedra.jl", "max_issues_repo_head_hexsha": "6ce8dd1fb75f7d4937b280951cef86bc367d6588", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Convex hull and intersection.jl", "max_forks_repo_name": "bzinberg/Polyhedra.jl", "max_forks_repo_head_hexsha": "6ce8dd1fb75f7d4937b280951cef86bc367d6588", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9489795918, "max_line_length": 315, "alphanum_fraction": 0.7184604419, "num_tokens": 1275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875223, "lm_q2_score": 0.8723473630627235, "lm_q1q2_score": 0.7739505774195115}}
{"text": "\n\"\"\"\nfilter_matrix_meshwidth(f, domain, N)\n\nAssemble discrete filtering matrix from a continuous filter `f` width constant width\n\\$h(x) = \\\\Delta x / 2\\$.\n\"\"\"\nfunction filter_matrix_meshwidth(f::TopHatFilter, domain::PeriodicIntervalDomain, N)\n    x = discretize(domain, N)\n    Δx = 1 // N * (domain.right - domain.left)\n    h = f.width\n    h₀ = h(x[1])\n\n    all(≈(h(x[1])), h.(x)) || error(\"Filter width must be constant\")\n    if Δx .≈ 2h₀\n        # Three point stencil\n        inds = [-1, 0, 1]\n        stencil = [1 // 24, 11 // 12, 1 // 24]\n    elseif Δx .≈ h₀\n        # Three point stencil\n        inds = [-1, 0, 1]\n        stencil = [1 // 6, 4 // 6, 1 // 6]\n    else\n        error(\"Filter width must be equal to mesh width\")\n    end\n\n    # Five point stencil\n    # inds = [-2, -1, 0, 1, 2]\n    # stencil = [-6 // 2033, 77 // 1440, 863 // 960, 77 // 1440, -6 // 2033]\n\n    # Construct banded matrix\n    diags = [i => fill(s, N - abs(i)) for (i, s) ∈ zip(inds, stencil)]\n    W = spdiagm(diags...)\n\n    # Periodic extension of three point stencil\n    W[1, end] = stencil[1]\n    W[end, 1] = stencil[end]\n\n    # Periodic extension of five point stencil\n    # W[1, [end - 1, end]] = stencil[[1, 2]]\n    # W[2, end] = stencil[1]\n    # W[end - 1, 1] = stencil[end]\n    # W[end, [1, 2]] = stencil[[end-1, end]]\n\n    W\nend\n\n\nfunction filter_matrix_meshwidth(f::TopHatFilter, domain::ClosedIntervalDomain, N)\n    x = discretize(domain, N)\n    Δx = 1 // N * (domain.right - domain.left)\n    h = f.width\n    h₀ = h(x[1])\n\n    all(≈(h(x[1])), h.(x)) || error(\"Filter width must be constant\")\n    Δx ≈ 2h₀ || error(\"Filter width must be equal to mesh width\")\n\n    # Three point stencil\n    inds = [-1, 0, 1]\n    stencil = [1 / 24, 11 / 12, 1 / 24]\n\n    # Five point stencil\n    # inds = [-2, -1, 0, 1, 2]\n    # stencil = [-6 / 2033, 77 / 1440, 863 / 960, 77 / 1440, -6 / 2033]\n\n    # Construct banded matrix\n    diags = [i => fill(s, N + 1 - abs(i)) for (i, s) ∈ zip(inds, stencil)]\n    W = spdiagm(diags...)\n\n    # Boundary weights for three point stencil\n    W[1, [1, 2]] = [3 / 4, 1 / 4]\n    W[end, [end, end - 1]] = [3 / 4, 1 / 4]\n\n    # Boundary weights for five point stencil\n    # W[1, [1, 2, 3]] = [2 / 3, 5 / 12, -1 / 12]\n    # W[2, [1, 2, 3, 4]] = [1/24, 11/12, 1/24, 0]\n    # W[end - 1, [end, end - 1, end - 2, end - 3]] = [1/24, 11/12, 1/24, 0]\n    # W[end, [end, end - 1, end - 2]] = [2 / 3, 5 / 12, -1 / 12]\n\n    W\nend\n", "meta": {"hexsha": "1469a3421e687b86787131873e428b147da1baee", "size": 2423, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrices/filter_matrix_meshwidth.jl", "max_stars_repo_name": "agdestein/DiscreteFiltering.jl", "max_stars_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-23T12:51:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T12:51:11.000Z", "max_issues_repo_path": "src/matrices/filter_matrix_meshwidth.jl", "max_issues_repo_name": "agdestein/DiscreteFiltering.jl", "max_issues_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrices/filter_matrix_meshwidth.jl", "max_forks_repo_name": "agdestein/DiscreteFiltering.jl", "max_forks_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5487804878, "max_line_length": 84, "alphanum_fraction": 0.5257944697, "num_tokens": 947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966656805269, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7739132815254814}}
{"text": "\n\nfunction euclidean_distance(vec1, vec2)\n    sqrt(sum([(vec1[i]-vec2[i])^2 for i in 1:length(vec1)]))\nend\n\n\nfunction k_nearest_neighbour(eigenface_table, new_eigenface, k)\n    n=length(eigenface_table)\n    distances = [euclidean_distance(eigenface_table[i][2], new_eigenface) for i in 1:n]\n    nearest_neighbours = [eigenface_table[i] for i in sortperm(distances)[1:k]]\n    classes = unique([neighbour[1] for neighbour in nearest_neighbours])\n    nearest = nearest_neighbours[1][1]\n    inverse_distance(neighbour) = 1/(euclidean_distance(neighbour, new_eigenface))\n    min = 0\n    for class in classes\n        freq = sum([inverse_distance(neighbour[2]) for neighbour in filter(x->x[1]==class, nearest_neighbours)])\n        if freq > min\n            min = freq\n            nearest = class\n        end\n    end\n    nearest\nend\n\n\nfunction test_model(proj, images, d, n, k)\n    labels = unique(map(x->x[2], images))\n    training_set = reduce(vcat,[map(x->x[1], filter(x->x[2] == labels[i], images))[1:n+1] for i in 1:size(labels, 1)])\n    image_matrix = images_to_image_matrix(training_set)\n    transformed = transpose(transpose(proj[:,1:d])*image_matrix)\n    eigenface_table = reduce(vcat, [[[labels[i+1] [transformed[j,:]]] for j in (i*(n+1)+1):(i*(n+1)+n+1)] for i in 0:size(labels, 1)-1])\n    correct = 0\n    for i in 1:length(training_set)\n        test_eigenface = eigenface_table[i]\n        data = reduce(vcat, [eigenface_table[1:i-1], eigenface_table[i+1:end]])\n        if k_nearest_neighbour(data, test_eigenface[2], k) == test_eigenface[1]\n            correct = correct + 1\n        end\n    end\n    return correct/length(training_set)\nend\n", "meta": {"hexsha": "92111621dc6cc2cb4e61e236a84998ed74e9cadb", "size": 1643, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/classification.jl", "max_stars_repo_name": "ethanmorris99/MTHE493.jl", "max_stars_repo_head_hexsha": "bd1cc11fd839e57f608780e22c6c3289efa1d2f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/classification.jl", "max_issues_repo_name": "ethanmorris99/MTHE493.jl", "max_issues_repo_head_hexsha": "bd1cc11fd839e57f608780e22c6c3289efa1d2f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/classification.jl", "max_forks_repo_name": "ethanmorris99/MTHE493.jl", "max_forks_repo_head_hexsha": "bd1cc11fd839e57f608780e22c6c3289efa1d2f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2093023256, "max_line_length": 136, "alphanum_fraction": 0.6634205721, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7739132783969364}}
{"text": "\n# generate a random pos def matrix with eigenvalues between 0.1 and 2\nfunction generate_pos_def_matrix(n::Int64,rng)\n\tX = rand(rng, n, n)\n\t# any real square matrix can be QP decomposed into a orthogonal matrix and an uppertriangular matrix R\n\tQ, R = qr(X)\n\teigs = rand(rng ,n) .* (2 .- 0.1) .+ 0.1\n\tX = Q * Matrix(Diagonal(eigs)) * Q'\n\tX = 0.5 * (X + X')\n\treturn X\nend\n\nfunction is_numerically_pos_sem_def(X, atol)\n\tX = X ./ 2\n\tX = X + X'\n\n\tF = eigfact(X)\n\tif size(find( x-> x < -atol, F[:values]), 1) == 0\n\t\treturn true\n\telse\n\t\treturn false\n\tend\nend\n\nfunction is_numerically_symmetric(X,atol)\n\tn = size(X, 2)\n\tfor i = 1:n-1, j = i+1:n\n\t\tif abs(X[i, j] - X[j, i]) >= atol\n\t\t\treturn false\n\t\tend\n\tend\n\treturn true\nend\n\n\nfunction find_nonsymmetric_component(X)\n\tfor i = 2:size(X, 1), j = 1:(i - 1)\n\t\tif abs(X[i, j] - X[j, i]) > 0.0\n\t\t\treturn i, j, abs(X[i, j] - X[j, i])\n\t\tend\n\tend\nend\n\nfunction find_different_elements(A, B)\n\tif size(A) != size(B)\n\t\terror(\"Matrices are not the same size\")\n\tend\n\tm, n = size(A)\n\tdiff_el = Array[]\n\tfor iii = 1:m, jjj = 1:n\n\t\tif A[iii, jjj] != B[iii, jjj]\n\t\t\tpush!(diff_el, [iii, jjj])\n\t\tend\n\tend\n\treturn diff_el\nend\n\nfunction duplicate_sparsity_pattern(A)\n\tm, n = size(A)\n\tB = zeros(m, n)\n\tfor iii = 1:m, jjj = 1:n\n\t\tif A[iii, jjj] != 0\n\t\t\tB[iii, jjj] = 1\n\t\tend\n\tend\n\treturn B\n\nend\n\nfunction recreate_sparse_matrix(A)\n\trowInd = A.rowval\n\tcolPtr = A.colptr\n\tval = A.nzval\n\n\t#compute column indices\n\tcolInd = zeros(Int64, length(rowInd))\n\tcval = 1\n\tfor iii = 2:length(colPtr)\n\t\tcurrentPtr = colPtr[iii]\n\t\tprevPtr = colPtr[iii - 1]\n\t\tcolInd[prevPtr:currentPtr - 1] = cval\n\t\tcval += 1\n\tend\n\n\t# sort rowInd and vals\n\tp = sortperm(rowInd)\n\treturn sparse(rowInd, colInd, val, size(A, 1), size(A, 2))\nend\n\n# Geometric mean from https://github.com/JuliaStats/StatsBase.jl\nfunction gmean(a::AbstractArray{T}) where T<:Real\n\ts = 0.0\n\tn = length(a)\n\tfor i in 1:n\n\t\ttmp = a[i]\n\t\tif tmp < 0.0\n\t\t\tthrow(DomainError())\n\t\telseif tmp == 0.0\n\t\t\treturn 0.0\n\t\telse\n\t\t\ts += log(tmp)\n\t\tend\n\tend\n\treturn exp(s / n)\nend\n", "meta": {"hexsha": "907dc157771dee5b4efd5f67b8c0dcc22434cdde", "size": 2027, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/UnitTests/COSMOTestUtils.jl", "max_stars_repo_name": "UnofficialJuliaMirror/COSMO.jl-1e616198-aa4e-51ec-90a2-23f7fbd31d8d", "max_stars_repo_head_hexsha": "f90cc6218d86db2fcd47b7ca533df2aa1c51f7ce", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/UnitTests/COSMOTestUtils.jl", "max_issues_repo_name": "UnofficialJuliaMirror/COSMO.jl-1e616198-aa4e-51ec-90a2-23f7fbd31d8d", "max_issues_repo_head_hexsha": "f90cc6218d86db2fcd47b7ca533df2aa1c51f7ce", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/UnitTests/COSMOTestUtils.jl", "max_forks_repo_name": "UnofficialJuliaMirror/COSMO.jl-1e616198-aa4e-51ec-90a2-23f7fbd31d8d", "max_forks_repo_head_hexsha": "f90cc6218d86db2fcd47b7ca533df2aa1c51f7ce", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1226415094, "max_line_length": 103, "alphanum_fraction": 0.6314750863, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7739115242120801}}
{"text": "#\n# Restricted Two-body Problem models\n# \n\n\"\"\"\nA `ModelingToolkit.ODESystem` for the Restricted Two-body Problem. \n\nThe order of the states follows: `[x, y, z, ẋ, ẏ, ż]`.\n\nThe order of the parameters follows: `[μ]`.\n\n# Extended Help\nThe Restricted Two-body Problem is a simplified dynamical model \ndescribing one small body (spacecraft, etc.) and one celestial \nbody. The gravity of the celestial body exhibits a force on the \nsmall body. This model is commonly used as a simplification to \ndescibe our solar systems' planets orbiting our sun, or a \nspacecraft orbiting Earth. \n\n### Usage\n\n```julia\nmodel = R2BP() \n```\n\"\"\"\n@memoize function R2BP(; stm=false, structural_simplify=true, name=:R2BP)\n\n    @parameters t μ \n    @variables x(t) y(t) z(t) ẋ(t) ẏ(t) ż(t)\n    δ = Differential(t)\n    r = @SVector [x,y,z]\n    v = @SVector [ẋ,ẏ,ż]\n\n    eqs = vcat(\n        δ.(r) .~ v,\n        δ.(v) .~ -μ .* (r ./ norm(r)^3)\n    )\n\n    if stm \n        @variables Φ[1:6,1:6](t)\n        Φ = Symbolics.scalarize(Φ)\n        A = Symbolics.jacobian(map(el -> el.rhs, eqs), vcat(r,v))\n    \n        LHS = map(δ, Φ)\n        RHS = map(simplify, A * Φ)\n\n        eqs = vcat(eqs, [LHS[i] ~ RHS[i] for i in 1:length(LHS)])\n    end\n\n    if string(name) == \"R2BP\" && stm \n        modelname = Symbol(\"R2BPWithSTM\")\n    else\n        modelname = name\n    end\n\n    sys = ODESystem(\n        eqs, t, stm  ? vcat(r,v,Φ...) : vcat(r,v), [μ]; \n        name = modelname\n    )\n    return structural_simplify ? ModelingToolkit.structural_simplify(sys) : sys\nend\n\n\"\"\"\nReturns an `ODEFunction` for R2BP dynamics. \nResults are cached with `Memoize.jl`.\n\nThe order of the states follows: `[x, y, z, ẋ, ẏ, ż]`.\n\nThe order of the parameters follows: `[μ]`.\n\n# Extended Help\n\n### Usage\n\nThe `stm`, `structural_simplify`, and `name` keyword arguments \nare passed to `R2BP`. All other keyword arguments are passed\ndirectly to `SciMLBase.ODEFunction`.\n\n```julia\nf = R2BPFunction(; stm=false, structural_simplify=true, name=:R2BP, jac=true)\nlet u = randn(6), p = randn(1), t = 0\n    f(u, p, t)\nend\n```\n\"\"\"\n@memoize function R2BPFunction(; stm=false, structural_simplify=true, name=:R2BP, kwargs...)\n    defaults = (; jac=true)\n    options  = merge(defaults, kwargs)\n    return ODEFunction(\n        R2BP(; stm=stm, structural_simplify=structural_simplify, name=name);\n        options...\n    )\nend", "meta": {"hexsha": "2a904bdda951c63d8a0a602c5ffd4ebfc7283750", "size": 2358, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/R2BP.jl", "max_stars_repo_name": "cadojo/AstrodynamicalSystems.jl", "max_stars_repo_head_hexsha": "6b9521b9bef2eda6cf00ea9ab1be156ddc3fb074", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-06-05T18:49:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T19:41:59.000Z", "max_issues_repo_path": "src/R2BP.jl", "max_issues_repo_name": "cadojo/AstrodynamicalSystems.jl", "max_issues_repo_head_hexsha": "6b9521b9bef2eda6cf00ea9ab1be156ddc3fb074", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-19T05:38:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-06T02:18:43.000Z", "max_forks_repo_path": "src/R2BP.jl", "max_forks_repo_name": "cadojo/AstrodynamicalSystems.jl", "max_forks_repo_head_hexsha": "6b9521b9bef2eda6cf00ea9ab1be156ddc3fb074", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3548387097, "max_line_length": 92, "alphanum_fraction": 0.6251060221, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7739115238171276}}
{"text": "function deflate_leading_zeros(ps::Vector{T}) where {T}\n    ## trim any 0s from the end of ps\n    N = findlast(!iszero, ps)\n    K = findfirst(!iszero, ps)\n\n    N == 0 && return(zeros(T,0), length(ps))\n    ps = ps[K:N]\n    ps, K-1\nend\n\n## take poly [p0, p1, ..., pn] and return\n## [q_m-1, q_m-2, ..., q0], k\n## where we trim of k roots of 0, and then make p monic, then reverese\n## monomial x^5\nfunction reverse_poly(ps::Vector{T}) where {T}\n    # assume we have called deflate_leading_zeros\n    qs = reverse(ps./ps[end])[2:end]\n    qs\nend\n\n#\nfunction quadratic_equation(a::T, b::T, c::T) where {T <: Real}   \n    qdrtc(a, -(0.5)*b, c)\nend\n\n## make more robust\nfunction quadratic_equation(a::Complex{T}, b::Complex{T}, c::Complex{T}) where {T}\n    d = sqrt(b^2 - 4*a*c)\n    e1 = (-b + d)/(2a); e2 = (-b-d)/(2a)\n    return (real(e1), imag(e1), real(e2), imag(e2))\n    \nend\n\n## Kahan quadratic equation with fma\n##  https://people.eecs.berkeley.edu/~wkahan/Qdrtcs.pdf\n\n## solve ax^2 - 2bx + c\nfunction qdrtc(a::T, b::T, c::T) where {T <: Real}\n    # z1, z2 roots of ax^2 - 2bx + c\n    d = discr(a,b,c)  # (b^2 - a*c), as 2 removes 4\n    \n    if d <= 0\n        r = b/a  # real\n        s = sqrt(-d)/a #imag\n        return (r,s,r,-s)\n    else\n        r = sqrt(d) * (sign(b) + iszero(b)) + b\n        return (r/a, zero(T), c/r, zero(T))\n    end\nend\n\n## more work could be done here.\nfunction discr(a::T,b::T,c::T) where {T}\n    pie = 3.0 # depends on 53 or 64 bit...\n    d = b*b - a*c\n    e = b*b + a*c\n\n    pie*abs(d) > e && return d\n\n    p = b*b\n    dp = muladd(b,b,-p)\n    q = a*c\n    dq = muladd(a,c,-q)\n\n    (p-q) + (dp - dq)\nend\n\n##\n## solve degree 2 or less case\nfunction solve_simple_cases(ps::Vector{T}) where {T}\n    S = T <: Complex ? T : Complex{T}\n    \n    N = length(ps)\n    \n    if N <= 1\n        return S[]\n    elseif N == 2\n        return S[-ps[1]/ps[2]]\n    elseif N == 3\n        c,b,a = ps\n        r1,i1, r2,i2 = quadratic_equation(a,b,c)\n        S[complex(r1, i1), complex(r2, i2)]\n    end\nend\n\n", "meta": {"hexsha": "9e3f650b114e1d1c83b5ac057b7b099c9f3cd019", "size": 2007, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/amvw/utils.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialZeros.jl-11d3f387-6b1b-5124-abbd-847758a5de3c", "max_stars_repo_head_hexsha": "ba0bb5e84cc7094c5025d217123ffc205686b2b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-03-30T14:15:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:23:08.000Z", "max_issues_repo_path": "src/amvw/utils.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialZeros.jl-11d3f387-6b1b-5124-abbd-847758a5de3c", "max_issues_repo_head_hexsha": "ba0bb5e84cc7094c5025d217123ffc205686b2b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-03-31T02:39:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-05T12:05:33.000Z", "max_forks_repo_path": "src/amvw/utils.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialZeros.jl-11d3f387-6b1b-5124-abbd-847758a5de3c", "max_forks_repo_head_hexsha": "ba0bb5e84cc7094c5025d217123ffc205686b2b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-08-27T13:48:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T12:01:17.000Z", "avg_line_length": 23.3372093023, "max_line_length": 82, "alphanum_fraction": 0.5356253114, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7739115185203795}}
{"text": "using SurrealNumbers \nout_dir = \"Data/\"\n\n# addition table\nx = convert.(SurrealFinite, [0, 1/2, 1, 2])\nA = zeros(SurrealFinite, length(x), length(x))    \nB = zeros(Int, length(x), length(x))    \nfor i=1:length(x)\n    for j=1:length(x)\n        A[i,j] = x[i] + x[j]\n        B[i,j] = generation(x[i]) + generation(x[j])\n    end\nend\nfloat.(A)\nA\ngeneration.(A)\n# A .== canonicalise.(A)\niscanonical.(A)\nB\n\na10 = convert(SurrealFinite, 3/2)\na11 = convert(SurrealFinite, 1/2) + convert(SurrealFinite, 1)\na12 = convert(SurrealFinite, 3/4) + convert(SurrealFinite, 3/4)\n\nfile = \"$(out_dir)addition_ex_10.dot\"\nFID = open(file, \"w\")\nsurreal2dag(FID, a10)\nclose(FID)\nrun(`dot -Tpdf -O $file`)\n\nfile = \"$(out_dir)addition_ex_11.dot\"\nFID = open(file, \"w\")\nsurreal2dag(FID, a11)\nclose(FID)\nrun(`dot -Tpdf -O $file`)\n\nfile = \"$(out_dir)addition_ex_12.dot\"\nFID = open(file, \"w\")\nsurreal2dag(FID, a12)\nclose(FID)\nrun(`dot -Tpdf -O $file`)\n\n", "meta": {"hexsha": "b707fe76da8d52e78a9b802c55b2cb46f9e01de8", "size": 920, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/addition_tables.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SurrealNumbers.jl-58abba7c-3f8b-5571-af36-87c463197a71", "max_stars_repo_head_hexsha": "163775d1f8ef1a218e7096075efa0df07b235091", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-18T16:53:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-18T16:53:27.000Z", "max_issues_repo_path": "examples/addition_tables.jl", "max_issues_repo_name": "ElsevierSoftwareX/SOFTX_2018_184", "max_issues_repo_head_hexsha": "7a3c2814eb3c3023ff0c060bfeb414d1cae50b4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/addition_tables.jl", "max_forks_repo_name": "ElsevierSoftwareX/SOFTX_2018_184", "max_forks_repo_head_hexsha": "7a3c2814eb3c3023ff0c060bfeb414d1cae50b4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3953488372, "max_line_length": 63, "alphanum_fraction": 0.6434782609, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561135, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7739115121163024}}
{"text": "using JuMP, Gurobi, Distributions, StatsFuns, StatsBase\r\n\r\n\r\nconst gurobi_env = Gurobi.Env()\r\n\r\n\r\nconst numVariables = 100\r\nconst numJCC = 100\r\nconst conRHS = (numVariables*1.0)^2\r\n\r\n\r\n\r\nxi_mean = zeros(Float64,numVariables)\r\nxi_covariance = 0.5*ones(Float64,numJCC,numJCC)\r\n\r\nfor j = 1:numVariables\r\n\txi_mean[j] = j*1.0/numVariables\r\nend\r\n\r\nfor i = 1:numJCC\r\n\txi_covariance[i,i] = 1.0\r\nend\r\n\r\nxi_cov_chol_tmp = cholfact(xi_covariance)\r\nxi_cov_chol = xi_cov_chol_tmp[:L]\r\n\r\nxi_mean_mat = zeros(Float64,numJCC,numVariables)\r\nfor j = 1:numVariables\r\n\txi_mean_mat[:,j] = xi_mean[j]*ones(numJCC)\r\nend\r\n\r\n\r\n# tailored implementation of multivariate normal distribution\r\nfunction myMvNormal(numSamples::Int64)\r\n\r\n\txi = zeros(Float64,numJCC,numVariables,numSamples)\r\n\t\r\n\txi_tmp = rand(Normal(0.0,1.0),numJCC,numVariables,numSamples)\r\n\tfor samp = 1:numSamples\r\n\t\txi[:,:,samp] = xi_cov_chol*xi_tmp[:,:,samp] + xi_mean_mat\r\n\tend\r\n\t\r\n\treturn xi\r\nend\r\n\r\n\r\n# generate random samples from multivariate normal distribution\r\nfunction generateRandomSamples(numSamples::Int64)\r\n\r\n\txi = myMvNormal(numSamples)\r\n\t\r\n\treturn xi\r\nend\r\n\r\n\r\n\r\n\r\nsrand(1234)\r\n\r\n# generate samples to estimate actual risk level of solution\r\nconst numAnalyticalSamples = 100000\r\nconst xi_analytical = generateRandomSamples(numAnalyticalSamples)\r\n\r\nsrand()\r\n\r\n\r\n\r\n\r\n# compute conservative bound on the probability that\r\n# constraints aren't satisfied\r\nfunction boundRiskLevel(x::Array{Float64},reliabilityLevel::Float64=1E-06)\r\n\r\n\tconst numSamples = size(xi_analytical,3)\r\n\tsimpleEst::Bool = false\r\n\r\n\tnumViolated::Int64 = checkScenarioConstraints(x,xi_analytical)\r\n\t\r\n\triskLevel::Float64 = Inf\r\n\t\r\n\tif(simpleEst)\r\n\t\triskLevel = numViolated*1.0/numSamples\r\n\t\treturn riskLevel\r\n\telse\r\n\t\tif(numViolated == 0)\r\n\t\t\triskLevel = -log(reliabilityLevel)/numSamples\r\n\t\t\treturn riskLevel\r\n\t\tend\r\n\t\r\n\t\t # termination criterion for bisection\r\n\t\tgamma_tolerance::Float64 = 0.1/numSamples\r\n\t\t\r\n\t\t# use tail bounds on binomial distribution to estimate lower and upper bounds\r\n\t\tgamma_low::Float64 = (numViolated - sqrt(-numSamples*log(reliabilityLevel)/2.0))/numSamples\r\n\t\tif(gamma_low < 0.0)\r\n\t\t\tgamma_low = 0.0\r\n\t\tend\r\n\t\tgamma_up::Float64 = (numViolated + sqrt(-numSamples*log(reliabilityLevel)/2.0))/numSamples\r\n\t\tif(gamma_up > 1.0)\r\n\t\t\tgamma_up = 1.0\r\n\t\tend\r\n\t\t\r\n\t\tgamma::Float64 = 0.0\r\n\t\tfunc_value::Float64 = 0.0\r\n\r\n\t\t# use bisection to solve the nonlinear equation\r\n\t\twhile (gamma_up - gamma_low > gamma_tolerance)\r\n\r\n\t\t\tgamma = (gamma_low + gamma_up)/2.0\r\n\t\t\tfunc_value = -reliabilityLevel\r\n\t\t\tfor i = 1:numViolated\r\n\t\t\t\ttmp_func = i*log(gamma) + (numSamples-i)*log(1-gamma) + lfact(numSamples) - lfact(numSamples-i) - lfact(i)\r\n\t\t\t\tfunc_value += exp(tmp_func)\r\n\t\t\t\tif(func_value > 0)\r\n\t\t\t\t\tbreak\r\n\t\t\t\tend\r\n\t\t\tend\r\n\t\t\tif(func_value > 0)\r\n\t\t\t\tgamma_low = (gamma_low + gamma_up)/2.0\r\n\t\t\telse\r\n\t\t\t\tgamma_up = (gamma_low + gamma_up)/2.0\r\n\t\t\tend\r\n\r\n\t\tend\r\n\t\t\r\n\t\triskLevel = gamma_up\r\n\t\treturn riskLevel\r\n\tend\r\n\r\nend\r\n\r\n\r\n# determines if all constraints are satisfied for a given single scenario\r\n# returns one if scenario constraints are all satisfied, zero otherwise\r\nfunction checkScenarioConstraints(x::Array{Float64},xi::Array{Float64})\r\n\r\n\tnumSamples::Int64 = size(xi,3)\r\n\r\n\tnumViolated::Int64 = 0\r\n\tfor samp = 1:numSamples\t\t\t\r\n\t\tfor i = 1:numJCC\r\n\t\t\tcon::Float64 = evaluateConstraint(i,x,xi[i,:,samp])\r\n\t\t\tif(con > 0)\r\n\t\t\t\tnumViolated += 1\r\n\t\t\t\tbreak\r\n\t\t\tend\r\n\t\tend\t\r\n\tend\r\n\r\n\treturn numViolated\r\nend\r\n\r\n\r\n# evaluate the constraint values for given decision vector x,\r\n# realization of the random variables xi, and constraint scalings\r\nfunction evaluateConstraint(index::Int64,x::Array{Float64},xi::Array{Float64})\r\n\r\n\tcon::Float64 = norm(xi.*x)^2 - conRHS\r\n\r\n\treturn con\r\nend\r\n\r\n\r\nNumSamples = 50\r\n\r\n# solution file name\r\nconst baseDirName = \"C:/Users/rkannan/Desktop/SA for CCP/Scenario approximation/experiments/normopt_noniid_scenapprox/\"\r\n\r\n\r\nfor samp = 1:NumSamples\r\n\r\n\tconst dirName = baseDirName * string(samp) * \"/\"\r\n\r\n\tconst fileName = dirName * \"solution.txt\"\r\n\r\n\tconst outputFile = dirName * \"trueRiskLevels.txt\"\r\n\topen(outputFile, \"w\") do f\r\n\tend\r\n\r\n\tconst timeFile = dirName * \"trueRiskTime.txt\"\r\n\topen(timeFile, \"w\") do f\r\n\tend\r\n\r\n\tsoln = readdlm(fileName)\r\n\r\n\tconst numPoints = size(soln,1)\r\n\r\n\tfor iter = 1:numPoints\r\n\t\ttic()\r\n\t\ttrueRiskLevel::Float64 = boundRiskLevel(soln[iter,:])\r\n\t\triskTime = toq()\r\n\t\tprintln(\"Risk level #\",iter,\" : \",trueRiskLevel,\"  time: \",riskTime)\r\n\t\topen(outputFile, \"a\") do f\r\n\t\t\twrite(f,\"$trueRiskLevel \\n\")\r\n\t\tend\r\n\t\topen(timeFile, \"a\") do f\r\n\t\t\twrite(f,\"$riskTime \\n\")\r\n\t\tend\r\n\tend\r\n\r\nend", "meta": {"hexsha": "1642aa4489be07243aa6bfdbc855165070b73404", "size": 4585, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Scenario approximation/normopt_noniid/normopt_noniid_evaluateRiskLevels.jl", "max_stars_repo_name": "rohitkannan/SA-for-CCP", "max_stars_repo_head_hexsha": "8bb62c8e095eb6a825807c016617d1999c744d24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-12-22T08:52:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T07:23:15.000Z", "max_issues_repo_path": "Scenario approximation/normopt_noniid/normopt_noniid_evaluateRiskLevels.jl", "max_issues_repo_name": "rohitkannan/SA-for-CCP", "max_issues_repo_head_hexsha": "8bb62c8e095eb6a825807c016617d1999c744d24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scenario approximation/normopt_noniid/normopt_noniid_evaluateRiskLevels.jl", "max_forks_repo_name": "rohitkannan/SA-for-CCP", "max_forks_repo_head_hexsha": "8bb62c8e095eb6a825807c016617d1999c744d24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-21T23:45:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-25T17:29:29.000Z", "avg_line_length": 22.925, "max_line_length": 120, "alphanum_fraction": 0.6950926936, "num_tokens": 1346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.7739115098241167}}
{"text": "function create_testfuncs(g::OneDGrid{Tg,<:Array}) where Tg\n    g.nx > 8 || error(\"nx must be > 8\")\n    m = 5\n    k₀ = g.k[2] # Fundamental wavenumber\n\n    # Analytic function\n    φ = π/3\n    f₁ = @. cos(m*k₀*g.x + φ)\n\n    # Transform of f₁ three ways\n     f₁h = fft(f₁)\n    f₁hr = rfft(f₁)\n    f₁hr_mul = zeros(Complex{eltype(g.x)}, g.nkr)\n    mul!(f₁hr_mul, g.rfftplan, f₁)\n\n    # Analytical values of the fft and rfft\n     f₁h_analytical = zeros(Complex{Float64}, size(f₁h))\n    f₁hr_analytical = zeros(Complex{Float64}, size(f₁hr))\n\n    for i in 1:g.nk\n      if abs(real(g.k[i])) == m*k₀\n        f₁h_analytical[i] = -exp(sign(real(g.k[i]))*im*φ)*g.nx/2\n      end\n    end\n\n    for i in 1:g.nkr\n      if abs(real(g.k[i])) == m*k₀\n        f₁hr_analytical[i] = -exp(sign(real(g.kr[i]))*im*φ)*g.nx/2\n      end\n    end\n\n    f₁, f₁h, f₁hr, f₁hr_mul, f₁h_analytical, f₁hr_analytical\nend\n\n\nfunction create_testfuncs(g::TwoDGrid{Tg,<:Array}) where Tg\n    g.nx > 8 || error(\"nx must be > 8\")\n    m, n = 5, 2\n    k₀ = g.k[2]\n    l₀ = g.l[2]\n\n    # Analytic functions\n    f₁ = @. cos(m*k₀*g.x) * cos(n*l₀*g.y)\n    f₂ = @. sin(m*k₀*g.x + n*l₀*g.y)\n\n     f₁h = fft(f₁)\n     f₂h = fft(f₂)\n    f₁hr = rfft(f₁)\n    f₂hr = rfft(f₂)\n\n    f₁hr_mul = zeros(Complex{eltype(g.x)}, (g.nkr, g.nl))\n    f₂hr_mul = zeros(Complex{eltype(g.x)}, (g.nkr, g.nl))\n    mul!(f₁hr_mul, g.rfftplan, f₁)\n    mul!(f₂hr_mul, g.rfftplan, f₂)\n\n    # Theoretical results\n     f₁h_analytical = zeros(Complex{eltype(g.x)}, size(f₁h))\n     f₂h_analytical = zeros(Complex{eltype(g.x)}, size(f₂h))\n    f₁hr_analytical = zeros(Complex{eltype(g.x)}, size(f₁hr))\n    f₂hr_analytical = zeros(Complex{eltype(g.x)}, size(f₂hr))\n\n    for j in 1:g.nl, i in 1:g.nk\n      if ( abs(real(g.k[i])) == m*k₀ && abs(real(g.l[j])) == n*l₀ )\n        f₁h_analytical[i, j] = - g.nx*g.ny/4\n      end\n      if ( real(g.k[i]) == m*k₀ && real(g.l[j]) == n*l₀ )\n        f₂h_analytical[i, j] = -g.nx*g.ny/2\n      elseif ( real(g.k[i]) == -m*k₀ && real(g.l[j]) == -n*l₀ )\n        f₂h_analytical[i, j] = g.nx*g.ny/2\n      end\n    end\n    f₂h_analytical = -im*f₂h_analytical;\n\n    for j in 1:g.nl, i in 1:g.nkr\n      if ( abs(g.kr[i])==m*k₀ && abs(g.l[j])==n*l₀ )\n        f₁hr_analytical[i, j] = - g.nx*g.ny/4\n      end\n      if ( real(g.kr[i]) == m*k₀ && real(g.l[j]) == n*l₀ )\n        f₂hr_analytical[i, j] = -g.nx*g.ny/2\n      elseif ( real(g.kr[i]) == -m*k₀ && real(g.l[j]) == -n*l₀ )\n        f₂hr_analytical[i, j] = g.nx*g.ny/2\n      end\n    end\n    f₂hr_analytical = -im*f₂hr_analytical;\n\n    f₁, f₂, f₁h, f₂h, f₁hr, f₂hr, f₁hr_mul, f₂hr_mul, f₁h_analytical, f₁hr_analytical, f₂h_analytical, f₂hr_analytical\nend\n\n@has_cuda begin\n  function create_testfuncs(g::OneDGrid{Tg, <:CuArray}) where Tg\n    cpugrid = OneDGrid(g.nx, g.Lx)\n    out = create_testfuncs(cpugrid)\n    return map(x->CuArray(x), out)\n  end\n\n  function create_testfuncs(g::TwoDGrid{Tg, <:CuArray}) where Tg\n    cpugrid = TwoDGrid(g.nx, g.Lx, g.ny, g.Ly)\n    out = create_testfuncs(cpugrid)\n    return map(x->CuArray(x), out)\n  end\nend", "meta": {"hexsha": "db8613e4d9fce95fc8f77827dda896b929738c73", "size": 3031, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/createffttestfunctions.jl", "max_stars_repo_name": "UnofficialJuliaMirror/FourierFlows.jl-2aec4490-903f-5c70-9b11-9bed06a700e1", "max_stars_repo_head_hexsha": "079fddb30256f719dcd071f57a2451af2e993e27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-15T18:46:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T18:46:22.000Z", "max_issues_repo_path": "test/createffttestfunctions.jl", "max_issues_repo_name": "UnofficialJuliaMirror/FourierFlows.jl-2aec4490-903f-5c70-9b11-9bed06a700e1", "max_issues_repo_head_hexsha": "079fddb30256f719dcd071f57a2451af2e993e27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/createffttestfunctions.jl", "max_forks_repo_name": "UnofficialJuliaMirror/FourierFlows.jl-2aec4490-903f-5c70-9b11-9bed06a700e1", "max_forks_repo_head_hexsha": "079fddb30256f719dcd071f57a2451af2e993e27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-15T18:46:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T18:46:24.000Z", "avg_line_length": 30.0099009901, "max_line_length": 118, "alphanum_fraction": 0.5743978885, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303728259492, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7739115096266406}}
{"text": "losses = [[10, 0],\n          [1, 50],\n          [0, 200]]\n\n\nnum_actions = length(losses)\n\n\nfunction expected_loss_of_action(prob_spam, action)\n    #TODO: Return expected loss over a Bernoulli random variable\n    #      with mean prob_spam.\n    #      Losses are given by the table above.\n    losses = [[10, 0],\n              [1, 50],\n              [0, 200]]\n    loss = losses[action]\n    length_prob_spam = length(prob_spam)\n\n\n\n    non_prob = 1 .- prob_spam\n    expect_loss = [prob_spam[i]*loss[1]+non_prob[i]*loss[2] for i in 1:length_prob_spam]\n    return expect_loss\nend\n\nprob_range = range(0., stop=1., length=500)\n\nusing Plots\nfor action in 1:num_actions\n  display(plot!(prob_range, expected_loss_of_action(prob_range, action)))\nend\n\nfunction optimal_action(prob_spam)\n    #TODO: return best action given the probability of spam.\n    # Hint: Julia's findmin function might be helpful.\n\n    losses = [[10, 0],[1, 50],[0, 200]]\n    non_prob_spam = 1-prob_spam\n    expected_loss = []\n    for i in 1:3\n        loss = losses[i]\n        push!(expected_loss, loss[1]*prob_spam+loss[2]*non_prob_spam)\n    end\n    return findmin(expected_loss)\nend\n\nprob_range = range(0, stop=1., length=500)\noptimal_losses = []\noptimal_actions = []\nfor p in prob_range\n    # TODO:  Compute the optimal action and its expected loss for\n    # probability of spam given by p.\n    res = optimal_action(p)\n    push!(optimal_losses,res[1])\n    push!(optimal_actions,res[2])\n\nend\noptimal_actions\nplot(prob_range, optimal_losses, linecolor=optimal_actions)\n", "meta": {"hexsha": "0a42627b8829e3d32a46b26efa4d6b37124dd4ed", "size": 1529, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CS/CSC412/code.jl", "max_stars_repo_name": "jerrysun103/uoft", "max_stars_repo_head_hexsha": "6264583d27c7db94596d29c73804e6d9155de191", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CS/CSC412/code.jl", "max_issues_repo_name": "jerrysun103/uoft", "max_issues_repo_head_hexsha": "6264583d27c7db94596d29c73804e6d9155de191", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CS/CSC412/code.jl", "max_forks_repo_name": "jerrysun103/uoft", "max_forks_repo_head_hexsha": "6264583d27c7db94596d29c73804e6d9155de191", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4833333333, "max_line_length": 88, "alphanum_fraction": 0.6664486593, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.7738159239862501}}
{"text": "\n\"\"\"\n```julia\nrandToeplitz(d, n;  norm, hermitian)  \n```\n- `d` : entry distribution\n- `n` : dimension\n- `norm` : default `false`;  if `norm` set to `true`, then the matrix will be normlaized with ``n^{-1/2}``.  \n- `hermitian`: default `true`; if `true` the matrix will be Hermitian\n\n# Examples\n\nGenerate a ``4 \\\\times 4`` random Hermitian Toeplitz matrix with entries Standard Normal.\n```julia\nrandToeplitz(4)\n\n4×4 Matrix{Float64}:\n  1.10207   -0.47292   -0.745498   1.06809\n -0.47292    1.10207   -0.47292   -0.745498\n -0.745498  -0.47292    1.10207   -0.47292\n  1.06809   -0.745498  -0.47292    1.10207\n```\nGenerate a ``4 \\\\times 4`` normalized random Toeplitz matrix with entries `Exponential(1)`.\n```julia\nusing Distributions\nrandToeplitz(Exponential(1),4, norm = true, hermitian = false)\n\n4×4 Matrix{Float64}:\n 0.667888  0.260045  1.48812   0.477305\n 1.50374   0.667888  0.260045  1.48812\n 1.1475    1.50374   0.667888  0.260045\n 0.363966  1.1475    1.50374   0.667888\n```\n\"\"\"\nfunction  randToeplitz(d::D, n::Int;  norm = false::Bool, hermitian=true::Bool)  where D<:S\n    if hermitian\n      t = rand(d,n)\n      t = [t[n:-1:2]'..., t...]\n    else\n      t = rand(d,2n-1)\n    end\n    M = zeros(eltype(d),n,n)\n    for i in 1:n,j in 1:n\n        M[i,j]=t[i-j+n]\n    end\n\n    if norm  return M/sqrt(n) end\n    M\n\nend\n\nfunction randToeplitz(n::Int; norm=false::Bool, hermitian=true::Bool)\n  return randToeplitz(Normal(),n,norm=norm,hermitian=hermitian)\nend\n\n\n\"\"\"\n```julia\nrandHankel(d, n;  norm )  \n\nrandHankel(n;  norm)\n```\n- `d` : entry distribution\n- `n` : dimension\n- `norm` : default `false`,  if `norm` set to `true`, then the matrix will be normlaized with ``n^{-1/2}``.  \n\n# Examples\n\nGenerate a ``5\\\\times 5`` random Hankel matrix with entries uniformly distributed on ``\\\\{1, i, \\\\pi \\\\}``\n```julia\nrandHankel((1,im,pi),5)\n\n5×5 Matrix{Number}:\n  1   1  im  1   1\n  1  im   1  1   π\n im   1   1  π   π\n  1   1   π  π   π\n  1   π   π  π  im\n```\n\n\"\"\"\nfunction randHankel(d::D, n::Int;  norm = false::Bool)  where D<:S\n  h = rand(d,2n-1)\n  M = zeros(eltype(d),n,n)\n  for i in 1:n\n    M[i,:] = h[i:i+n-1]\n  end\n\n  if norm  return M/sqrt(n) end\n  M\nend\n\nfunction randHankel(n::Int;  norm = false::Bool)\n  return randHankel(Normal(),n,norm=norm)\nend", "meta": {"hexsha": "508ad9f423cc43d47429d9cea05cd6aacb8c3857", "size": 2250, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/StructuredMatrices.jl", "max_stars_repo_name": "weiyang2048/RandomMatrix.jl", "max_stars_repo_head_hexsha": "d112a17d928c84583759177849a76eae1942e947", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-04-27T04:28:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T17:21:23.000Z", "max_issues_repo_path": "src/StructuredMatrices.jl", "max_issues_repo_name": "weiyang607/RandomMatrix.jl", "max_issues_repo_head_hexsha": "d112a17d928c84583759177849a76eae1942e947", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-04-13T02:48:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T22:13:44.000Z", "max_forks_repo_path": "src/StructuredMatrices.jl", "max_forks_repo_name": "weiyang607/RandomMatrix.jl", "max_forks_repo_head_hexsha": "d112a17d928c84583759177849a76eae1942e947", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6842105263, "max_line_length": 109, "alphanum_fraction": 0.6102222222, "num_tokens": 913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.896251378675949, "lm_q2_score": 0.8633916134888613, "lm_q1q2_score": 0.773815923926644}}
{"text": "### A Pluto.jl notebook ###\n# v0.18.0\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 93b38489-898a-4695-a167-5f5a782ef0e8\nusing DifferentialEquations\n\n# ╔═╡ 8a49cf89-d1c8-4847-8b9b-70b23c2b609c\nusing Plots\n\n# ╔═╡ 3e86dfc7-8567-4b0d-a75a-13422acfa20a\nusing HypertextLiteral\n\n# ╔═╡ 71bcf780-2eb2-487f-b90e-1a2b3f740e19\nusing PlutoUI\n\n# ╔═╡ 1de38637-f5d2-4679-a6f6-2a9672a9e5ea\nusing ParameterizedFunctions\n\n# ╔═╡ 6458ccf4-03b2-4d7f-8206-dcdeef1bc020\nmd\"## 4. Differential equations solvers\n\nNormally, each modern language has implemented solvers for dynamical systems in the form of differential equations. In Matlab the command is called ode23, in Python is ODEINT, In Julia, we first need to initialize the package for differenetial equations,\"\n\n# ╔═╡ 23c6e540-3049-419b-bf82-4141977f9a0f\nmd\"To take advantage of these solvers, we have to place the equations that result from the mass action analysis inside a vector function `f` that takes several input values. We use the same approximation of the state vector `u` used for the Euler method. Next we define a vector of parameters `p` with the kinetic rate constants of the interactions involved. In Julia:\"\n\n# ╔═╡ ed4267e2-8c95-4d78-955f-b89cdb125f18\nfunction simpleODE1!(du,u,p,t)\n    k = p\n    du[1] = -k*u[1]*u[2]\n    du[2] = -k*u[1]*u[2]\n    du[3] = k*u[1]*u[2]   \nend\n\n# ╔═╡ 423bf107-0d98-48f6-b780-932fd216b803\nmd\"Notice here we used the in-place format which writes the output to the preallocated vector `du`. For systems of equations the in-place format is faster. We define a bector with the initial concentrations of the variables `u₀`. For our model, the only parameter is the rate constant `k`, therefore we build the parameter collection `p` as\"\n\n# ╔═╡ 5c41d702-aab7-44a8-9347-a26ed27703ed\nk=1;\n\n# ╔═╡ 0995aee5-f4f9-4d75-9651-5513bd243a36\np=(k);\n\n# ╔═╡ 9913179f-1a94-4d20-87ff-bd2c2bec7530\nu₀=[0.02,0.01,0];\n\n# ╔═╡ 3ac8e1d7-429f-4ae3-8b33-beafaf9bf043\nmd\"Next, we define the `tspan` vector, which now it has only two components: the initial and final time point for the simulation\"\n\n# ╔═╡ 379f8c7e-3f7c-43f4-8387-f75728b3c4a3\ntspan = (0.0,100.0);\n\n# ╔═╡ f25d32de-fd9f-408d-b3b8-0b4707467186\nmd\"In Julia, we need to define an __ODEProblem__ type using the constructor call. This is done by specifying this function __simpleODE__, the initial condition `u₀`, the time span `tspan` and the parameters  `p`:\"\n\n# ╔═╡ 93854457-e209-42ea-b533-5a018ad2024b\nprob1 = ODEProblem(simpleODE1!,u₀,tspan,p)\n\n# ╔═╡ 292bcc76-e7e6-4628-a839-5e83f8caba68\nsol1 = solve(prob1)\n\n# ╔═╡ edebc440-cf82-4ba4-a97e-90da9220690b\nmd\"`sol1.t` stores the time points and `sol1.u` is an array storing the solution at the corresponding time points. \n\nHowever, when dealing with systems of equations, `sol1` also acts like an array. `sol1[i]` returns the solution at the `i`th time point.\"\n\n# ╔═╡ cd970122-8288-40d8-ac15-564ca8cb26f3\nsol1.t[3],sol1.u[3]\n\n# ╔═╡ e4f3b341-4136-4f77-884b-e9c403e45d09\nmd\"Additionally, the solution acts like a matrix where `sol[j,i]` is the value of the `j`th variable at time `i`:\"\n\n# ╔═╡ 981c2e93-9495-4482-9c5c-970c6c8e03d2\nsol1[:,3]\n\n# ╔═╡ 6837c59d-1d1b-4ff6-8016-dd81703226c9\nbegin\n\tplot(sol1,label=[\"a\",\"b\",\"c\"])\n\ttitle!(\"ODE solver in Julia\")\n\txlabel!(\"Time [s]\")\n\tylabel!(\"Concentration [M]\")\nend\n\n# ╔═╡ f67a4f14-3051-4e43-9fbf-a332d1b59dd7\nmd\"One interesting feature is that, by default, the solution is a continuous function. So you do not need to extrapolate to a curve\"\n\n# ╔═╡ b0f2ef4b-29c2-44d9-9382-dd5421260296\nsol1(60.4)\n\n# ╔═╡ 995b908f-ccf8-48ba-a45c-024f8d6527f4\nmd\"We can see how the implemented ODE solver chooses the time variable depending of the stiffness of the solution of the ODE. This saves a lot of time and computer power. Quite often, each ODE solver handles the integration time diferently, and choosing one or the other is impontant and depends on the problem to solve. We can see that the stock solver in Julia only solves the following few points\"\n\n# ╔═╡ ce923957-2f70-4023-bab4-8a73a6fd3800\nsol1_ = solve(prob1,dense=false)\n\n# ╔═╡ 65cd089f-7563-4696-a5fa-81074ef8bb33\nplot(sol1_,label=[\"a\",\"b\",\"c\"],seriestype=:scatter)\n\n# ╔═╡ b4696fcc-8c09-4563-88e2-0aca1d734eba\nmd\"### 5.1 A DSL for Parameterized Functions\n\nIn many cases you may be defining a lot of functions with parameters. There exists the domain-specific language (DSL) defined by the `@ode_def` macro for helping with this common problem. Using this feature in Julia, we can rewrite the `simpleODE!` function as:\"\n\n# ╔═╡ d8158943-8ba2-4176-b3d7-e99197c82e1b\nsimpleODE2! = @ode_def abetterway2 begin\n  da = -k*a*b\n  db = -k*a*b\n  dc = k*a*b\n    end k\n\n# ╔═╡ 75c7c433-c228-4417-be7b-f1f50b2c4921\nbegin\n\tprob2 = ODEProblem(simpleODE2!,u₀,tspan,p)\n\tsol2 = solve(prob2)\n\tplot(sol2,label=[\"a\",\"b\",\"c\"])\n\ttitle!(\"ODE solver using DSL\")\n\txlabel!(\"Time [s]\")\n\tylabel!(\"Concentration [M]\")\nend\n\n# ╔═╡ 8a5644dc-69cf-44dc-b5f7-eadc8c3aa0a7\nmd\"## 5. Reversible reactions and equilibrium \n\nNow we will use the same approach  to solve the reversible reaction \n\n```math \na + b \\overset{k_1}{\\underset{k_2}{\\longleftrightarrow}} c \\tag{7}\n```\n\nwith rate constants `k1`, and `k2` for the forward and reverse reaction, and with initial concentrations $X_1(0)$, $X_2(0)$ and $X_3(0)$. The stoichometric matrices are\n\n```math\nA=\\begin{bmatrix}\n 1 & 1 & 0 \\\\  0 & 0 & 1 \\end{bmatrix} ;\nB=\\begin{bmatrix}\n0 & 0 & 1  \\\\\n1 & 1 & 0 \n\\end{bmatrix} ; \\tag{8}\n```\n\"\n\n# ╔═╡ d275e770-76f0-4a9f-8628-1abfc4eeedf5\nbegin\n\tA=[1 1 0 ; 0 0 1]\n\tB=[0 0 1 ; 1 1 0]\n\tstoichiometric_matrix= (B-A)'\n\tprintln(\"The stoichiometric matrix is $stoichiometric_matrix \")\nend\n\n# ╔═╡ 416c8f55-154a-4953-8162-b0c2e6069f48\nmd\" in this particular case\n\n```math\nK=\\begin{pmatrix}\n k_1 & 0   \\tag{9}\\\\ \n 0 &  k_2  \\\\ \n\\end{pmatrix}\n```\n\nand \n\n```math\nX^A=\\begin{pmatrix}\nX_1^1\\cdot X_2^1 \\cdot X_3^0\\\\\nX_1^0\\cdot X_2^0 \\cdot X_3^1\n\\end{pmatrix} = \\begin{pmatrix}\nX_1 \\cdot X_2 \\\\\nX_3\n\\end{pmatrix} \\tag{10}\n```\n\n```math\n\\begin{align}\n \\begin{bmatrix}\n\\frac{\\mathrm{d} X_1}{\\mathrm{d} t}\\\\ \\frac{\\mathrm{d} X_2}{\\mathrm{d} t} \\\\ \\frac{\\mathrm{d} X_3}{\\mathrm{d} t} \n\\end{bmatrix}&=  \\begin{bmatrix}\n - 1  & 1 \\\\ -1  & 1 \\\\ 1 & -1\\end{bmatrix} \\begin{bmatrix}\nk_1 & 0\\\\ \n 0& k_2\n\\end{bmatrix}\\begin{pmatrix}\nX_1 \\cdot X_2 \\\\\nX_3\n\\end{pmatrix} = \\begin{bmatrix}\n - 1  & 1 \\\\ -1  & 1 \\\\ 1 & -1\\end{bmatrix}\\begin{pmatrix}\n k_1 \\cdot X_1 \\cdot X_2 \\\\\nk_2 \\cdot X_3\n\\end{pmatrix} \\tag{11}\n\\end{align}\n```\n\nMultiplying and substituting for the original names of the variables, we have the set of differential equations. \n\n```math\n\\frac{da}{dt} = -k_1 \\cdot a \\cdot b + k_2 \\cdot c \\tag{12}\n```\n\n```math\n\\frac{db}{dt} = -k_1 \\cdot a \\cdot b + k_2 \\cdot \\tag{13}c\n```\n\n```math\n\\frac{dc}{dt} = k_1 \\cdot a \\cdot b - k_2 \\cdot \\tag{14}c\n```\n\n\nTo use the ode solver, $p$ now holds the two parameters required to solve the system, $k_1$, and $k_2$. So\n\n\"\n\n# ╔═╡ a7993c27-7f27-40e6-8d63-ff74b31e6935\nfunction simpleODErev!(du,u,p,t)\n    k1,k2 = p\n    du[1] = -k1*u[1]*u[2]+k2*u[3]\n    du[2] = -k1*u[1]*u[2]+k2*u[3]\n    du[3] = k1*u[1]*u[2]-k2*u[3] \nend\n\n# ╔═╡ 05e01d78-de55-4655-b792-5ce62abea53a\nbegin\n\tk1=1;k2=0.01; # we could also make this an array, or any other type!\n\tprob4 = ODEProblem(simpleODErev!,u₀,tspan,(k1,k2))\n\tsol4 = solve(prob4)\n\tplot(sol4,label=[\"a\",\"b\",\"c\"])\n\ttitle!(\"ODE solver in Julia\")\n\txlabel!(\"Time [s]\")\n\tylabel!(\"Concentration [M]\")\nend\n\n# ╔═╡ 353b1a99-0c87-4286-9b22-3c5f72145e52\nmd\"or, using the DSL notation avaliable in Julia\"\n\n# ╔═╡ dd5601e5-fc2a-4927-9292-f6bf2f51d2a0\nsimpleODE2_rev! = @ode_def amuchbetterway begin\n  da = -k1*a*b+k2*c\n  db = -k1*a*b+k2*c\n  dc = k1*a*b-k2*c\n    end k1 k2\n\n# ╔═╡ 50e9d7ee-68b1-497c-bd91-0be168e0b964\nbegin\n\tprob = ODEProblem(simpleODE2_rev!,u₀,tspan,(k1,k2))\n\tsol = solve(prob)\n\tplot(sol,label=[\"a\",\"b\",\"c\"])\n\ttitle!(\"reversible ODE solver using DSL\")\n\txlabel!(\"Time [s]\")\n\tylabel!(\"Concentration [M]\")\nend\n\n# ╔═╡ 4481524c-8117-4835-b46e-ebe9d6878f40\nmd\"Now instead of using the Mass Conservation to reduce the number of variables, we will practice another method to simplify the system. For instance, one of teh things that we can do when we have the differential equations of a system is to find the values at equilibrium. Since we already know that the equilibrium is reached when the speed of the reaction is zero, we have \n\n```math\n\\frac{\\mathrm{d} c_{eq}}{\\mathrm{d} t}=0\n```\nwe have:\n\n```math\n\\begin{align}\nk_2 \\cdot c_{eq}= k_1 \\cdot a_{eq}\\cdot b_{eq} \\tag{15}\\\\\nc_{eq}= \\frac{k_1 \\cdot a_{eq}\\cdot b_{eq}}{k_2} \\tag{16}\n\\end{align}\n```\n\nIn addition, based on the restrictions imposed by the Mass conservation, since  \n```math\n\\frac{\\mathrm{d} c}{\\mathrm{d} t}=-\\frac{\\mathrm{d} a}{\\mathrm{d} t} \n```\nat any time, the condition $[a]+[c]=[a_o]$ is true at all time points. thererefore we can rewrite the equilibrium equation as:\n\n\n```math\n\\begin{align}\nc_{eq}= \\frac{k_1 \\cdot (a_{0}-c_{eq})\\cdot b_{eq}}{k_2} \\tag{17}\\\\\nc_{eq}= \\frac{k_1 \\cdot a_{0}\\cdot b_{eq}}{k_2}-\\frac{k_1 \\cdot c_{eq}\\cdot b_{eq}}{k_2}  \\tag{18}\\\\\nc_{eq}+\\frac{k_1 \\cdot c_{eq}\\cdot b_{eq}}{k_2} = \\frac{k_1 \\cdot a_{0}\\cdot b_{eq}}{k_2} \\tag{19}\\\\\nc_{eq}(1+\\frac{k_1 \\cdot b_{eq}}{k_2}) = \\frac{k_1 \\cdot a_{0}\\cdot b_{eq}}{k_2} \\tag{20}\\\\\nc_{eq}(\\frac{k_2+k_1 \\cdot b_{eq}}{k_2}) = \\frac{k_1 \\cdot a_{0}\\cdot b_{eq}}{k_2} \\tag{21}\\\\\nc_{eq}= \\frac{k_1 \\cdot a_{0}\\cdot b_{eq}}{k_2+k_1 \\cdot b_{eq}} \\tag{22}\\\\\n\\end{align}\n```\n\nso, divinding numerator and denominator by $k_1$\n\n```math\n\\begin{align}\nc_{eq}= \\frac{a_{0}\\cdot b_{eq}}{\\frac{k_2}{k_1}+\\cdot b_{eq}} \\tag{23}\\\\\nc_{eq}= \\frac{a_{0}\\cdot b_{eq}}{K_{eq}+ b_{eq}} \\tag{24}\n\\end{align}\n```\n\n\nwhere $K_{eq}$ is the equilibirum constant, defined as:\n\n```math\n\\begin{equation}\nK_{eq}=\\frac{k_2}{k_1} \\tag{25}\n\\end{equation}\n```\n\"\n\n# ╔═╡ 63e0ac0e-c6a1-40f4-8af9-a0a5eaabf344\nbegin\n\tBB=sol4[2,:]\n\tc_eq=BB*u₀[1]./(BB.+(k2/k1))\n\tplot(sol4,label=[\"a\",\"b\",\"c\"])\n\tplot!(sol4.t,c_eq,label=\"C_eq\")\n\ttitle!(\"Reversible ODE solver using DSL and Equilibrium solution\")\n\txlabel!(\"Time [s]\")\n\tylabel!(\"Concentration [M]\")\nend\n\n# ╔═╡ 0b3661cc-ca0e-485d-bcdb-4fbc339c0195\nmd\"We see that the value predicted for variable $c_{eq}$ at equilibrium it gets closer to the real value as we approach the equilibrium. So it is only a good approximation after 90 seconds or so. This approximation will be used later on the course when we combine reactions that are fast with reactions that are slow. In these conditions, we can assume that one of the reactions (the fast one) is allways at equilibirum, so one of teh variables is almost constant, allowing us to simplify the system. \n\n## 6. Conclusion\n\nThe combination of the differential form of Mass Action and the Mass conservation form a very powerfull tandem to derive and simplify the ODEs that govern the dynamcis of any system of interacting species. \"\n\n# ╔═╡ 52196376-6060-4fd6-8fcc-d1505075bae8\n@htl(\"\"\"\n\n<div class='blue-background'>\n</div>\n\n<script>\n// more about selecting elements later!\ncurrentScript.previousElementSibling.innerText = \"Exercise: Solve numerically the following reversible reaction using a solver from the programming language of your preference (you may need to write your code as separate  functions). Use the Mass Conservation Law to simplify the system (only three ODEs) \"\n\n</script>\n\n<style>\n.blue-background {\n\tpadding: .5em;\n\tbackground: lightblue;\n\tcolor: black;\n}\n</style>\n\n\"\"\")\n\n# ╔═╡ 62516169-0e2e-4907-a87d-65af79e0926f\nmd\"\n```math\nNaCO_3 + CaCl_2  \\overset{k_1}{\\underset{k_2}{\\longleftrightarrow}}  CaCO_3 + 2 NaCl\n```\nUse the following values\"\n\n# ╔═╡ 26c8db68-c21d-4f94-a93c-a82eb7753d3e\nbegin\n\tk1_=2.3e0;  # units 1/(Ms)\n\tk2_=2.5e0;  # units 1/(M M s)\n\ta₀=0.02; # units (M)\n\tb₀=0.01; # units (M)\n\tc₀=0; # units (M)\n\td₀=0; # units (M)\nend\n\n# ╔═╡ 143ef067-a8ec-4cc5-b2b5-43746529d4c6\nmd\"### Solution of Task 2\n\n\n```math\n\\begin{align} \n a + b  &\\overset{k_1}{\\longrightarrow}  c + 2 d \\tag{25}\\\\\n c + 2 d &\\overset{k_2}{\\longrightarrow} a + b \\tag{26}\n \\end{align}\n```\n\nwe have calculated already the differential equations based on Mass Action Kinetics,which gives us a system of four coupled ODEs:\n\n```math\n\\begin{align}        \n            \\frac{ da }{dt} &= - k_1 \\cdot a \\cdot b + k_2 \\cdot c \\cdot d^2  \\tag{29}\\\\ \n            \\frac{ db }{dt} &= - k_1 \\cdot a \\cdot b + k_2 \\cdot c \\cdot d^2   \\tag{30}  \\\\\n             \\frac{ dc }{dt} &=  k_1 \\cdot a \\cdot b - k_2 \\cdot c \\cdot d^2  \\tag{31}  \\\\\n              \\frac{ dd }{dt} &= 2 k_1 \\cdot a  \\cdot b - 2 k_2 \\cdot c \\cdot d^2   \\tag{32}  \\\\\n\\end{align}\n```\n\n\n\nNext, we solve the equations numerically:\"\n\n# ╔═╡ a627aa52-e44a-4f83-99af-40e316643b3c\nsimpleODE3! = @ode_def abetterway3 begin\n  da = -k1 * a * b + k2 * c * d^2\n  db = -k1 * a * b + k2 * c * d^2\n  dc = k1 * a * b - k2 * c * d^2\n  dd = 2 * k1 * a * b - 2 * k2 * c * d^2\n    end k1 k2\n\n# ╔═╡ d12f7049-25b8-4cca-b2f4-788a2314c973\nbegin\n\tprob5 = ODEProblem(simpleODE3!,[a₀,b₀,c₀,d₀],tspan,(k1_,k2_))\n\tsol5 = solve(prob5)\n\tplot(sol5,label=[\"s\" \"e1s\" \"e2p\" \"p\"])\n\ttitle!(\"reversible ODE solver using DSL\")\n\txlabel!(\"Time [s]\")\n\tylabel!(\"Concentration [M]\")\nend\n\n# ╔═╡ 75f33bbd-2340-4c92-aef3-77a33dd6ae3e\nmd\"We will now take advantage of the Mass Conservation law to reduce the numbre of equations of the system. Based on the previous analysis, we calculated the coefficients of the vector $C \\cdot (B-A)^T =0$, obatining the following relation between the variables. \n\n```math\n\\begin{align}\n a(t) + b(t)+ c(t)+\\frac{d(t)}{2}= cte \n\\end{align}\n```\n\nSince this is valid for every time, we can write:\n\n```math\n\\begin{align}\n  a(t) + b(t)+ c(t)+\\frac{d(t)}{2}= cte= a(0) + b(0)+ c(0)+\\frac{d(0)}{2} \n\\end{align}\n```\n\n\nso we can eliminate one of the variables, for instance $c$ :\n\n```math\n\\begin{align}\n  c(t)= a(0) + b(0) + c(0) + \\frac{d(0)}{2} - a(t) - b(t) - \\frac{d(t)}{2} = cte - a(t) - b(t) - \\frac{d(t)}{2}\n\\end{align}\n```\n\n\nand only solve a system of three equations, \n\n\n```math\n\\begin{align}        \n            \\frac{ da }{dt} &= - k_1 \\cdot a \\cdot b + k_2  (cte - a - b - \\frac{d}{2})  d^2 \\\\ \n            \\frac{ db }{dt} &= - k_1 \\cdot a \\cdot b + k_2 (cte - a - b - \\frac{d}{2}) d^2  \\\\\n              \\frac{ dd }{dt} &= 2 k_1 \\cdot a  \\cdot b - 2 k_2 (cte - a - b - \\frac{d}{2}) d^2\n\\end{align}\n```\n\n\n\n\"\n\n# ╔═╡ d268c6a7-45db-42a1-9a63-77800663ad6e\nsimpleODE4! = @ode_def abetterway4 begin\n  da = -k1 * a * b + k2 * (cte - a - b - d/2) * d^2\n  db = -k1 * a * b + k2 * (cte - a - b - d/2) * d^2\n  dd = 2 * k1 * a * b - 2 * k2 * (cte - a - b - d/2) * d^2\n    end k1 k2 cte\n\n# ╔═╡ a1dc49b8-52b4-474f-9463-9231ac879b90\nbegin\n\tcte=a₀+b₀+c₀+d₀/2\n\tprob7 = ODEProblem(simpleODE4!,[a₀,b₀,d₀],tspan,(k1,k2,cte))\n\tsol7 = solve(prob7)\n\tplot(sol7)\n\ttitle!(\"reversible ODE solver using DSL\")\n\txlabel!(\"Time [s]\")\n\tylabel!(\"Concentration [M]\")\nend\n\n# ╔═╡ 0e0f7785-e323-4aed-8dd4-e7fa91eddd4a\nplot!(sol7.t,a₀.+b₀.+c₀.+(d₀./2).-(sol7[1,:].+sol7[2,:].+(sol7[3,:]./2)),label=\"c(t)\")\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nDifferentialEquations = \"0c46a032-eb83-5123-abaf-570d42b7fbaa\"\nHypertextLiteral = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nParameterizedFunctions = \"65888b18-ceab-5e60-b2b9-181511a3b968\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\n\n[compat]\nDifferentialEquations = \"~7.1.0\"\nHypertextLiteral = \"~0.9.3\"\nParameterizedFunctions = \"~5.13.1\"\nPlots = \"~1.25.8\"\nPlutoUI = \"~0.7.37\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\njulia_version = \"1.7.2\"\nmanifest_format = \"2.0\"\n\n[[deps.AbstractPlutoDingetjes]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"8eaf9f1b4921132a4cff3f36a1d9ba923b14a481\"\nuuid = \"6e696c72-6542-2067-7265-42206c756150\"\nversion = \"1.1.4\"\n\n[[deps.AbstractTrees]]\ngit-tree-sha1 = \"03e0550477d86222521d254b741d470ba17ea0b5\"\nuuid = \"1520ce14-60c1-5f80-bbc7-55ef81b5835c\"\nversion = \"0.3.4\"\n\n[[deps.Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"af92965fb30777147966f58acb05da51c5616b5f\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.3\"\n\n[[deps.ArgCheck]]\ngit-tree-sha1 = \"a3a402a35a2f7e0b87828ccabbd5ebfbebe356b4\"\nuuid = \"dce04be8-c92d-5529-be00-80e4d2c0e197\"\nversion = \"2.3.0\"\n\n[[deps.ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[deps.ArnoldiMethod]]\ndeps = [\"LinearAlgebra\", \"Random\", \"StaticArrays\"]\ngit-tree-sha1 = \"62e51b39331de8911e4a7ff6f5aaf38a5f4cc0ae\"\nuuid = \"ec485272-7323-5ecc-a04f-4719b315124d\"\nversion = \"0.2.0\"\n\n[[deps.ArrayInterface]]\ndeps = [\"Compat\", \"IfElse\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"Static\"]\ngit-tree-sha1 = \"1ee88c4c76caa995a885dc2f22a5d548dfbbc0ba\"\nuuid = \"4fba245c-0d91-5ea0-9b3e-6abc04ee57a9\"\nversion = \"3.2.2\"\n\n[[deps.ArrayLayouts]]\ndeps = [\"FillArrays\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"e1ba79094cae97b688fb42d31cbbfd63a69706e4\"\nuuid = \"4c555306-a7a7-4459-81d9-ec55ddd5c99a\"\nversion = \"0.7.8\"\n\n[[deps.Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[deps.AutoHashEquals]]\ngit-tree-sha1 = \"45bb6705d93be619b81451bb2006b7ee5d4e4453\"\nuuid = \"15f4f7f2-30c1-5605-9d31-71845cf9641f\"\nversion = \"0.2.0\"\n\n[[deps.BandedMatrices]]\ndeps = [\"ArrayLayouts\", \"FillArrays\", \"LinearAlgebra\", \"Random\", \"SparseArrays\"]\ngit-tree-sha1 = \"ce68f8c2162062733f9b4c9e3700d5efc4a8ec47\"\nuuid = \"aae01518-5342-5314-be14-df237901396f\"\nversion = \"0.16.11\"\n\n[[deps.BangBang]]\ndeps = [\"Compat\", \"ConstructionBase\", \"Future\", \"InitialValues\", \"LinearAlgebra\", \"Requires\", \"Setfield\", \"Tables\", \"ZygoteRules\"]\ngit-tree-sha1 = \"d648adb5e01b77358511fb95ea2e4d384109fac9\"\nuuid = \"198e06fe-97b7-11e9-32a5-e1d131e6ad66\"\nversion = \"0.3.35\"\n\n[[deps.Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[deps.Baselet]]\ngit-tree-sha1 = \"aebf55e6d7795e02ca500a689d326ac979aaf89e\"\nuuid = \"9718e550-a3fa-408a-8086-8db961cd8217\"\nversion = \"0.1.1\"\n\n[[deps.Bijections]]\ngit-tree-sha1 = \"705e7822597b432ebe152baa844b49f8026df090\"\nuuid = \"e2ed5e7c-b2de-5872-ae92-c73ca462fb04\"\nversion = \"0.1.3\"\n\n[[deps.BitTwiddlingConvenienceFunctions]]\ndeps = [\"Static\"]\ngit-tree-sha1 = \"5e98d6a6aa92e5758c4d58501b7bf23732699fa3\"\nuuid = \"62783981-4cbd-42fc-bca8-16325de8dc4b\"\nversion = \"0.1.2\"\n\n[[deps.BoundaryValueDiffEq]]\ndeps = [\"BandedMatrices\", \"DiffEqBase\", \"FiniteDiff\", \"ForwardDiff\", \"LinearAlgebra\", \"NLsolve\", \"Reexport\", \"SparseArrays\"]\ngit-tree-sha1 = \"fe34902ac0c3a35d016617ab7032742865756d7d\"\nuuid = \"764a87c0-6b3e-53db-9096-fe964310641d\"\nversion = \"2.7.1\"\n\n[[deps.Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[deps.CEnum]]\ngit-tree-sha1 = \"215a9aa4a1f23fbd05b92769fdd62559488d70e9\"\nuuid = \"fa961155-64e5-5f13-b03f-caf6b980ea82\"\nversion = \"0.4.1\"\n\n[[deps.CPUSummary]]\ndeps = [\"Hwloc\", \"IfElse\", \"Static\"]\ngit-tree-sha1 = \"849799453de85b55e78550fc7b0c8f442eb497ab\"\nuuid = \"2a0fbf3d-bb9c-48f3-b0a9-814d99fd7ab9\"\nversion = \"0.1.8\"\n\n[[deps.CSTParser]]\ndeps = [\"Tokenize\"]\ngit-tree-sha1 = \"6cc1759204bed5a4e2a5c2f00901fd5d90bc7a62\"\nuuid = \"00ebfdb7-1f24-5e51-bd34-a7502290713f\"\nversion = \"3.3.1\"\n\n[[deps.Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"4b859a208b2397a7a623a03449e4636bdb17bcf2\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+1\"\n\n[[deps.ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"f9982ef575e19b0e5c7a98c6e75ee496c0f73a93\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.12.0\"\n\n[[deps.ChangesOfVariables]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"bf98fa45a0a4cee295de98d4c1462be26345b9a1\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.2\"\n\n[[deps.CloseOpenIntervals]]\ndeps = [\"ArrayInterface\", \"Static\"]\ngit-tree-sha1 = \"7b8f09d58294dc8aa13d91a8544b37c8a1dcbc06\"\nuuid = \"fb6a15b2-703c-40df-9091-08a04967cfa9\"\nversion = \"0.1.4\"\n\n[[deps.ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"12fc73e5e0af68ad3137b886e3f7c1eacfca2640\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.17.1\"\n\n[[deps.ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[deps.Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[deps.Combinatorics]]\ngit-tree-sha1 = \"08c8b6831dc00bfea825826be0bc8336fc369860\"\nuuid = \"861a8166-3701-5b0c-9a16-15d98fcdc6aa\"\nversion = \"1.0.2\"\n\n[[deps.CommonMark]]\ndeps = [\"Crayons\", \"JSON\", \"URIs\"]\ngit-tree-sha1 = \"4cd7063c9bdebdbd55ede1af70f3c2f48fab4215\"\nuuid = \"a80b9123-70ca-4bc0-993e-6e3bcb318db6\"\nversion = \"0.8.6\"\n\n[[deps.CommonSolve]]\ngit-tree-sha1 = \"68a0743f578349ada8bc911a5cbd5a2ef6ed6d1f\"\nuuid = \"38540f10-b2f7-11e9-35d8-d573e4eb0ff2\"\nversion = \"0.2.0\"\n\n[[deps.CommonSubexpressions]]\ndeps = [\"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"7b8a93dba8af7e3b42fecabf646260105ac373f7\"\nuuid = \"bbf7d656-a473-5ed7-a52c-81e309532950\"\nversion = \"0.3.0\"\n\n[[deps.Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"44c37b4636bc54afac5c574d2d02b625349d6582\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.41.0\"\n\n[[deps.CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[deps.CompositeTypes]]\ngit-tree-sha1 = \"d5b014b216dc891e81fea299638e4c10c657b582\"\nuuid = \"b152e2b5-7a66-4b01-a709-34e65c35f657\"\nversion = \"0.1.2\"\n\n[[deps.CompositionsBase]]\ngit-tree-sha1 = \"455419f7e328a1a2493cabc6428d79e951349769\"\nuuid = \"a33af91c-f02d-484b-be07-31d278c5ca2b\"\nversion = \"0.1.1\"\n\n[[deps.ConstructionBase]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"f74e9d5388b8620b4cee35d4c5a618dd4dc547f4\"\nuuid = \"187b0558-2788-49d3-abe0-74a17ed4e7c9\"\nversion = \"1.3.0\"\n\n[[deps.Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[deps.Crayons]]\ngit-tree-sha1 = \"249fe38abf76d48563e2f4556bebd215aa317e15\"\nuuid = \"a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f\"\nversion = \"4.1.1\"\n\n[[deps.DEDataArrays]]\ndeps = [\"ArrayInterface\", \"DocStringExtensions\", \"LinearAlgebra\", \"RecursiveArrayTools\", \"SciMLBase\", \"StaticArrays\"]\ngit-tree-sha1 = \"31186e61936fbbccb41d809ad4338c9f7addf7ae\"\nuuid = \"754358af-613d-5f8d-9788-280bf1605d4c\"\nversion = \"0.2.0\"\n\n[[deps.DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[deps.DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"3daef5523dd2e769dad2365274f760ff5f282c7d\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.11\"\n\n[[deps.DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[deps.Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[deps.DefineSingletons]]\ngit-tree-sha1 = \"0fba8b706d0178b4dc7fd44a96a92382c9065c2c\"\nuuid = \"244e2a9f-e319-4986-a169-4d1fe445cd52\"\nversion = \"0.1.2\"\n\n[[deps.DelayDiffEq]]\ndeps = [\"ArrayInterface\", \"DataStructures\", \"DiffEqBase\", \"LinearAlgebra\", \"Logging\", \"NonlinearSolve\", \"OrdinaryDiffEq\", \"Printf\", \"RecursiveArrayTools\", \"Reexport\", \"UnPack\"]\ngit-tree-sha1 = \"ceb3463f2913eec2f0af5f0d8e1386fb546fdd32\"\nuuid = \"bcd4f6db-9728-5f36-b5f7-82caef46ccdb\"\nversion = \"5.34.0\"\n\n[[deps.DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[deps.DensityInterface]]\ndeps = [\"InverseFunctions\", \"Test\"]\ngit-tree-sha1 = \"80c3e8639e3353e5d2912fb3a1916b8455e2494b\"\nuuid = \"b429d917-457f-4dbc-8f4c-0cc954292b1d\"\nversion = \"0.4.0\"\n\n[[deps.DiffEqBase]]\ndeps = [\"ArrayInterface\", \"ChainRulesCore\", \"DEDataArrays\", \"DataStructures\", \"Distributions\", \"DocStringExtensions\", \"FastBroadcast\", \"ForwardDiff\", \"FunctionWrappers\", \"IterativeSolvers\", \"LabelledArrays\", \"LinearAlgebra\", \"Logging\", \"MuladdMacro\", \"NonlinearSolve\", \"Parameters\", \"PreallocationTools\", \"Printf\", \"RecursiveArrayTools\", \"RecursiveFactorization\", \"Reexport\", \"Requires\", \"SciMLBase\", \"Setfield\", \"SparseArrays\", \"StaticArrays\", \"Statistics\", \"SuiteSparse\", \"ZygoteRules\"]\ngit-tree-sha1 = \"d75333ab19d6d01c53bb350a9aabb074ba768a9d\"\nuuid = \"2b5f629d-d688-5b77-993f-72d75c75574e\"\nversion = \"6.81.3\"\n\n[[deps.DiffEqCallbacks]]\ndeps = [\"DataStructures\", \"DiffEqBase\", \"ForwardDiff\", \"LinearAlgebra\", \"NLsolve\", \"OrdinaryDiffEq\", \"Parameters\", \"RecipesBase\", \"RecursiveArrayTools\", \"SciMLBase\", \"StaticArrays\"]\ngit-tree-sha1 = \"e57ecaf9f7875714c164ccca3c802711589127cf\"\nuuid = \"459566f4-90b8-5000-8ac3-15dfb0a30def\"\nversion = \"2.20.1\"\n\n[[deps.DiffEqJump]]\ndeps = [\"ArrayInterface\", \"Compat\", \"DataStructures\", \"DiffEqBase\", \"FunctionWrappers\", \"Graphs\", \"LinearAlgebra\", \"PoissonRandom\", \"Random\", \"RandomNumbers\", \"RecursiveArrayTools\", \"Reexport\", \"StaticArrays\", \"TreeViews\", \"UnPack\"]\ngit-tree-sha1 = \"628ddc7e2b44e214232e747b22f1a1d9a8f14467\"\nuuid = \"c894b116-72e5-5b58-be3c-e6d8d4ac2b12\"\nversion = \"8.1.0\"\n\n[[deps.DiffEqNoiseProcess]]\ndeps = [\"DiffEqBase\", \"Distributions\", \"LinearAlgebra\", \"Optim\", \"PoissonRandom\", \"QuadGK\", \"Random\", \"Random123\", \"RandomNumbers\", \"RecipesBase\", \"RecursiveArrayTools\", \"Requires\", \"ResettableStacks\", \"SciMLBase\", \"StaticArrays\", \"Statistics\"]\ngit-tree-sha1 = \"d6839a44a268c69ef0ed927b22a6f43c8a4c2e73\"\nuuid = \"77a26b50-5914-5dd7-bc55-306e6241c503\"\nversion = \"5.9.0\"\n\n[[deps.DiffResults]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"c18e98cba888c6c25d1c3b048e4b3380ca956805\"\nuuid = \"163ba53b-c6d8-5494-b064-1a9d43ac40c5\"\nversion = \"1.0.3\"\n\n[[deps.DiffRules]]\ndeps = [\"IrrationalConstants\", \"LogExpFunctions\", \"NaNMath\", \"Random\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"84083a5136b6abf426174a58325ffd159dd6d94f\"\nuuid = \"b552c78f-8df3-52c6-915a-8e097449b14b\"\nversion = \"1.9.1\"\n\n[[deps.DifferentialEquations]]\ndeps = [\"BoundaryValueDiffEq\", \"DelayDiffEq\", \"DiffEqBase\", \"DiffEqCallbacks\", \"DiffEqJump\", \"DiffEqNoiseProcess\", \"LinearAlgebra\", \"LinearSolve\", \"OrdinaryDiffEq\", \"Random\", \"RecursiveArrayTools\", \"Reexport\", \"SteadyStateDiffEq\", \"StochasticDiffEq\", \"Sundials\"]\ngit-tree-sha1 = \"3f3db9365fedd5fdbecebc3cce86dfdfe5c43c50\"\nuuid = \"0c46a032-eb83-5123-abaf-570d42b7fbaa\"\nversion = \"7.1.0\"\n\n[[deps.Distances]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"3258d0659f812acde79e8a74b11f17ac06d0ca04\"\nuuid = \"b4f34e82-e78d-54a5-968a-f98e89d6e8f7\"\nversion = \"0.10.7\"\n\n[[deps.Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[deps.Distributions]]\ndeps = [\"ChainRulesCore\", \"DensityInterface\", \"FillArrays\", \"LinearAlgebra\", \"PDMats\", \"Printf\", \"QuadGK\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"Test\"]\ngit-tree-sha1 = \"38012bf3553d01255e83928eec9c998e19adfddf\"\nuuid = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nversion = \"0.25.48\"\n\n[[deps.DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[deps.DomainSets]]\ndeps = [\"CompositeTypes\", \"IntervalSets\", \"LinearAlgebra\", \"StaticArrays\", \"Statistics\"]\ngit-tree-sha1 = \"5f5f0b750ac576bcf2ab1d7782959894b304923e\"\nuuid = \"5b8099bc-c8ec-5219-889f-1d9e522a28bf\"\nversion = \"0.5.9\"\n\n[[deps.Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[deps.DynamicPolynomials]]\ndeps = [\"DataStructures\", \"Future\", \"LinearAlgebra\", \"MultivariatePolynomials\", \"MutableArithmetics\", \"Pkg\", \"Reexport\", \"Test\"]\ngit-tree-sha1 = \"74e63cbb0fda19eb0e69fbe622447f1100cd8690\"\nuuid = \"7c1d4256-1411-5781-91ec-d7bc3513ac07\"\nversion = \"0.4.3\"\n\n[[deps.EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[deps.EllipsisNotation]]\ndeps = [\"ArrayInterface\"]\ngit-tree-sha1 = \"d7ab55febfd0907b285fbf8dc0c73c0825d9d6aa\"\nuuid = \"da5c29d0-fa7d-589e-88eb-ea29b0a81949\"\nversion = \"1.3.0\"\n\n[[deps.Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ae13fcbc7ab8f16b0856729b050ef0c446aa3492\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.4.4+0\"\n\n[[deps.ExponentialUtilities]]\ndeps = [\"ArrayInterface\", \"LinearAlgebra\", \"Printf\", \"Requires\", \"SparseArrays\"]\ngit-tree-sha1 = \"3e1289d9a6a54791c1ee60da0850f4fd71188da6\"\nuuid = \"d4d017d3-3776-5f7e-afef-a10c40355c18\"\nversion = \"1.11.0\"\n\n[[deps.ExprTools]]\ngit-tree-sha1 = \"56559bbef6ca5ea0c0818fa5c90320398a6fbf8d\"\nuuid = \"e2ba6199-217a-4e67-a87a-7c52f15ade04\"\nversion = \"0.1.8\"\n\n[[deps.FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[deps.FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[deps.FastBroadcast]]\ndeps = [\"LinearAlgebra\", \"Polyester\", \"Static\"]\ngit-tree-sha1 = \"0f8ef5dcb040dbb9edd98b1763ac10882ee1ff03\"\nuuid = \"7034ab61-46d4-4ed7-9d0f-46aef9175898\"\nversion = \"0.1.12\"\n\n[[deps.FastClosures]]\ngit-tree-sha1 = \"acebe244d53ee1b461970f8910c235b259e772ef\"\nuuid = \"9aa1b823-49e4-5ca5-8b0f-3971ec8bab6a\"\nversion = \"0.3.2\"\n\n[[deps.FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"deed294cde3de20ae0b2e0355a6c4e1c6a5ceffc\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.12.8\"\n\n[[deps.FiniteDiff]]\ndeps = [\"ArrayInterface\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"StaticArrays\"]\ngit-tree-sha1 = \"ec299fdc8f49ae450807b0cb1d161c6b76fd2b60\"\nuuid = \"6a86dc24-6348-571c-b903-95158fe2bd41\"\nversion = \"2.10.1\"\n\n[[deps.FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[deps.Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[deps.Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[deps.ForwardDiff]]\ndeps = [\"CommonSubexpressions\", \"DiffResults\", \"DiffRules\", \"LinearAlgebra\", \"LogExpFunctions\", \"NaNMath\", \"Preferences\", \"Printf\", \"Random\", \"SpecialFunctions\", \"StaticArrays\"]\ngit-tree-sha1 = \"1bd6fc0c344fc0cbee1f42f8d2e7ec8253dda2d2\"\nuuid = \"f6369f11-7733-5829-9624-2563aa707210\"\nversion = \"0.10.25\"\n\n[[deps.FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[deps.FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[deps.FunctionWrappers]]\ngit-tree-sha1 = \"241552bc2209f0fa068b6415b1942cc0aa486bcc\"\nuuid = \"069b7b12-0de2-55c6-9aab-29f3d0a68a2e\"\nversion = \"1.1.2\"\n\n[[deps.Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[deps.GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"51d2dfe8e590fbd74e7a842cf6d13d8a2f45dc01\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.6+0\"\n\n[[deps.GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"RelocatableFolders\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"4a740db447aae0fbeb3ee730de1afbb14ac798a1\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.63.1\"\n\n[[deps.GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"aa22e1ee9e722f1da183eb33370df4c1aeb6c2cd\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.63.1+0\"\n\n[[deps.GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[deps.Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[deps.Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"a32d672ac2c967f3deb8a81d828afc739c838a06\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+2\"\n\n[[deps.Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[deps.Graphs]]\ndeps = [\"ArnoldiMethod\", \"Compat\", \"DataStructures\", \"Distributed\", \"Inflate\", \"LinearAlgebra\", \"Random\", \"SharedArrays\", \"SimpleTraits\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"57c021de207e234108a6f1454003120a1bf350c4\"\nuuid = \"86223c79-3864-5bf0-83f7-82e725a168b6\"\nversion = \"1.6.0\"\n\n[[deps.Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[deps.HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"0fa77022fe4b511826b39c894c90daf5fce3334a\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.17\"\n\n[[deps.HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"129acf094d168394e80ee1dc4bc06ec835e510a3\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+1\"\n\n[[deps.HostCPUFeatures]]\ndeps = [\"BitTwiddlingConvenienceFunctions\", \"IfElse\", \"Libdl\", \"Static\"]\ngit-tree-sha1 = \"3965a3216446a6b020f0d48f1ba94ef9ec01720d\"\nuuid = \"3e5b6fbb-0976-4d2c-9146-d79de83f2fb0\"\nversion = \"0.1.6\"\n\n[[deps.Hwloc]]\ndeps = [\"Hwloc_jll\"]\ngit-tree-sha1 = \"92d99146066c5c6888d5a3abc871e6a214388b91\"\nuuid = \"0e44f5e4-bd66-52a0-8798-143a42290a1d\"\nversion = \"2.0.0\"\n\n[[deps.Hwloc_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d8bccde6fc8300703673ef9e1383b11403ac1313\"\nuuid = \"e33a78d0-f292-5ffc-b300-72abe9b543c8\"\nversion = \"2.7.0+0\"\n\n[[deps.Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[deps.HypertextLiteral]]\ngit-tree-sha1 = \"2b078b5a615c6c0396c77810d92ee8c6f470d238\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.3\"\n\n[[deps.IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[deps.IfElse]]\ngit-tree-sha1 = \"debdd00ffef04665ccbb3e150747a77560e8fad1\"\nuuid = \"615f187c-cbe4-4ef1-ba3b-2fcf58d6d173\"\nversion = \"0.1.1\"\n\n[[deps.Inflate]]\ngit-tree-sha1 = \"f5fc07d4e706b84f72d54eedcc1c13d92fb0871c\"\nuuid = \"d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9\"\nversion = \"0.1.2\"\n\n[[deps.IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[deps.InitialValues]]\ngit-tree-sha1 = \"4da0f88e9a39111c2fa3add390ab15f3a44f3ca3\"\nuuid = \"22cec73e-a1b8-11e9-2c92-598750a2cf9c\"\nversion = \"0.3.1\"\n\n[[deps.InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[deps.IntervalSets]]\ndeps = [\"Dates\", \"EllipsisNotation\", \"Statistics\"]\ngit-tree-sha1 = \"3cc368af3f110a767ac786560045dceddfc16758\"\nuuid = \"8197267c-284f-5f27-9208-e0e47529a953\"\nversion = \"0.5.3\"\n\n[[deps.InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.2\"\n\n[[deps.IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[deps.IterTools]]\ngit-tree-sha1 = \"fa6287a4469f5e048d763df38279ee729fbd44e5\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.4.0\"\n\n[[deps.IterativeSolvers]]\ndeps = [\"LinearAlgebra\", \"Printf\", \"Random\", \"RecipesBase\", \"SparseArrays\"]\ngit-tree-sha1 = \"1169632f425f79429f245113b775a0e3d121457c\"\nuuid = \"42fd0dbc-a981-5370-80f2-aaf504508153\"\nversion = \"0.9.2\"\n\n[[deps.IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[deps.JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"abc9885a7ca2052a736a600f7fa66209f96506e1\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.4.1\"\n\n[[deps.JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"3c837543ddb02250ef42f4738347454f95079d4e\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.3\"\n\n[[deps.JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b53380851c6e6664204efb2e62cd24fa5c47e4ba\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.2+0\"\n\n[[deps.JuliaFormatter]]\ndeps = [\"CSTParser\", \"CommonMark\", \"DataStructures\", \"Pkg\", \"Tokenize\"]\ngit-tree-sha1 = \"0d1eb5e5a6b8b9d324a9abfa5ee092156e59a6da\"\nuuid = \"98e50ef6-434e-11e9-1051-2b60c6c9e899\"\nversion = \"0.22.2\"\n\n[[deps.KLU]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"SuiteSparse_jll\"]\ngit-tree-sha1 = \"cae5e3dfd89b209e01bcd65b3a25e74462c67ee0\"\nuuid = \"ef3ab10e-7fda-4108-b977-705223b18434\"\nversion = \"0.3.0\"\n\n[[deps.Krylov]]\ndeps = [\"LinearAlgebra\", \"Printf\", \"SparseArrays\"]\ngit-tree-sha1 = \"6333cc5b848295895f3b23eb763d020fc8e05867\"\nuuid = \"ba0b0d4f-ebba-5204-a429-3ac8c609bfb7\"\nversion = \"0.7.12\"\n\n[[deps.KrylovKit]]\ndeps = [\"LinearAlgebra\", \"Printf\"]\ngit-tree-sha1 = \"0328ad9966ae29ccefb4e1b9bfd8c8867e4360df\"\nuuid = \"0b1a1467-8014-51b9-945f-bf0ae24f4b77\"\nversion = \"0.5.3\"\n\n[[deps.LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[deps.LERC_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"bf36f528eec6634efc60d7ec062008f171071434\"\nuuid = \"88015f11-f218-50d7-93a8-a6af411a945d\"\nversion = \"3.0.0+1\"\n\n[[deps.LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[deps.LaTeXStrings]]\ngit-tree-sha1 = \"f2355693d6778a178ade15952b7ac47a4ff97996\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.3.0\"\n\n[[deps.LabelledArrays]]\ndeps = [\"ArrayInterface\", \"ChainRulesCore\", \"LinearAlgebra\", \"MacroTools\", \"StaticArrays\"]\ngit-tree-sha1 = \"3696fdc1d3ef6e4d19551c92626066702a5db91c\"\nuuid = \"2ee39098-c373-598a-b85f-a56591580800\"\nversion = \"1.7.1\"\n\n[[deps.Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a8f4f279b6fa3c3c4f1adadd78a621b13a506bce\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.9\"\n\n[[deps.LayoutPointers]]\ndeps = [\"ArrayInterface\", \"LinearAlgebra\", \"ManualMemory\", \"SIMDTypes\", \"Static\"]\ngit-tree-sha1 = \"6dd77ee76188b0365f7d882d674b95796076fa2c\"\nuuid = \"10f19ff3-798f-405d-979b-55457f8fc047\"\nversion = \"0.1.5\"\n\n[[deps.LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[deps.LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[deps.LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[deps.LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[deps.Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[deps.Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"0b4a5d71f3e5200a7dff793393e09dfc2d874290\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+1\"\n\n[[deps.Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[deps.Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[deps.Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[deps.Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[deps.Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[deps.Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"LERC_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"c9551dd26e31ab17b86cbd00c2ede019c08758eb\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+1\"\n\n[[deps.Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[deps.LineSearches]]\ndeps = [\"LinearAlgebra\", \"NLSolversBase\", \"NaNMath\", \"Parameters\", \"Printf\"]\ngit-tree-sha1 = \"f27132e551e959b3667d8c93eae90973225032dd\"\nuuid = \"d3d80556-e9d4-5f37-9878-2ab0fcc64255\"\nversion = \"7.1.1\"\n\n[[deps.LinearAlgebra]]\ndeps = [\"Libdl\", \"libblastrampoline_jll\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[deps.LinearSolve]]\ndeps = [\"ArrayInterface\", \"DocStringExtensions\", \"IterativeSolvers\", \"KLU\", \"Krylov\", \"KrylovKit\", \"LinearAlgebra\", \"RecursiveFactorization\", \"Reexport\", \"Requires\", \"SciMLBase\", \"Setfield\", \"SparseArrays\", \"SuiteSparse\", \"UnPack\"]\ngit-tree-sha1 = \"55e98c887e31f5c7a1901328e3f8ccd806024f45\"\nuuid = \"7ed4a6bd-45f5-4d41-b270-4a48e9bafcae\"\nversion = \"1.11.3\"\n\n[[deps.LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"e5718a00af0ab9756305a0392832c8952c7426c1\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.6\"\n\n[[deps.Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[deps.LoopVectorization]]\ndeps = [\"ArrayInterface\", \"CPUSummary\", \"ChainRulesCore\", \"CloseOpenIntervals\", \"DocStringExtensions\", \"ForwardDiff\", \"HostCPUFeatures\", \"IfElse\", \"LayoutPointers\", \"LinearAlgebra\", \"OffsetArrays\", \"PolyesterWeave\", \"SIMDDualNumbers\", \"SLEEFPirates\", \"SpecialFunctions\", \"Static\", \"ThreadingUtilities\", \"UnPack\", \"VectorizationBase\"]\ngit-tree-sha1 = \"67c0dfeae307972b50009ce220aae5684ea852d1\"\nuuid = \"bdcacae8-1622-11e9-2a5c-532679323890\"\nversion = \"0.12.101\"\n\n[[deps.MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[deps.ManualMemory]]\ngit-tree-sha1 = \"bcaef4fc7a0cfe2cba636d84cda54b5e4e4ca3cd\"\nuuid = \"d125e4d3-2237-4719-b19c-fa641b8a4667\"\nversion = \"0.1.8\"\n\n[[deps.Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[deps.MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[deps.MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[deps.Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[deps.Metatheory]]\ndeps = [\"AutoHashEquals\", \"DataStructures\", \"Dates\", \"DocStringExtensions\", \"Parameters\", \"Reexport\", \"TermInterface\", \"ThreadsX\", \"TimerOutputs\"]\ngit-tree-sha1 = \"0886d229caaa09e9f56bcf1991470bd49758a69f\"\nuuid = \"e9d8d322-4543-424a-9be4-0cc815abe26c\"\nversion = \"1.3.3\"\n\n[[deps.MicroCollections]]\ndeps = [\"BangBang\", \"InitialValues\", \"Setfield\"]\ngit-tree-sha1 = \"6bb7786e4f24d44b4e29df03c69add1b63d88f01\"\nuuid = \"128add7d-3638-4c79-886c-908ea0c25c34\"\nversion = \"0.1.2\"\n\n[[deps.Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[deps.Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[deps.ModelingToolkit]]\ndeps = [\"AbstractTrees\", \"ArrayInterface\", \"ConstructionBase\", \"DataStructures\", \"DiffEqBase\", \"DiffEqCallbacks\", \"DiffEqJump\", \"DiffRules\", \"Distributed\", \"Distributions\", \"DocStringExtensions\", \"DomainSets\", \"Graphs\", \"IfElse\", \"InteractiveUtils\", \"JuliaFormatter\", \"LabelledArrays\", \"Latexify\", \"Libdl\", \"LinearAlgebra\", \"MacroTools\", \"NaNMath\", \"NonlinearSolve\", \"RecursiveArrayTools\", \"Reexport\", \"Requires\", \"RuntimeGeneratedFunctions\", \"SafeTestsets\", \"SciMLBase\", \"Serialization\", \"Setfield\", \"SparseArrays\", \"SpecialFunctions\", \"StaticArrays\", \"SymbolicUtils\", \"Symbolics\", \"UnPack\", \"Unitful\"]\ngit-tree-sha1 = \"7e7e2a06bf7885a304c60ffb1540e3dac1f42335\"\nuuid = \"961ee093-0014-501f-94e3-6117800e7a78\"\nversion = \"8.4.0\"\n\n[[deps.MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[deps.MuladdMacro]]\ngit-tree-sha1 = \"c6190f9a7fc5d9d5915ab29f2134421b12d24a68\"\nuuid = \"46d2c3a1-f734-5fdb-9937-b9b9aeba4221\"\nversion = \"0.2.2\"\n\n[[deps.MultivariatePolynomials]]\ndeps = [\"DataStructures\", \"LinearAlgebra\", \"MutableArithmetics\"]\ngit-tree-sha1 = \"fa6ce8c91445e7cd54de662064090b14b1089a6d\"\nuuid = \"102ac46a-7ee4-5c85-9060-abc95bfdeaa3\"\nversion = \"0.4.2\"\n\n[[deps.MutableArithmetics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"Test\"]\ngit-tree-sha1 = \"842b5ccd156e432f369b204bb704fd4020e383ac\"\nuuid = \"d8a4904e-b15c-11e9-3269-09a3773c0cb0\"\nversion = \"0.3.3\"\n\n[[deps.NLSolversBase]]\ndeps = [\"DiffResults\", \"Distributed\", \"FiniteDiff\", \"ForwardDiff\"]\ngit-tree-sha1 = \"50310f934e55e5ca3912fb941dec199b49ca9b68\"\nuuid = \"d41bc354-129a-5804-8e4c-c37616107c6c\"\nversion = \"7.8.2\"\n\n[[deps.NLsolve]]\ndeps = [\"Distances\", \"LineSearches\", \"LinearAlgebra\", \"NLSolversBase\", \"Printf\", \"Reexport\"]\ngit-tree-sha1 = \"019f12e9a1a7880459d0173c182e6a99365d7ac1\"\nuuid = \"2774e3e8-f4cf-5e23-947b-6d7e65073b56\"\nversion = \"4.5.1\"\n\n[[deps.NaNMath]]\ngit-tree-sha1 = \"b086b7ea07f8e38cf122f5016af580881ac914fe\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.7\"\n\n[[deps.NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[deps.NonlinearSolve]]\ndeps = [\"ArrayInterface\", \"FiniteDiff\", \"ForwardDiff\", \"IterativeSolvers\", \"LinearAlgebra\", \"RecursiveArrayTools\", \"RecursiveFactorization\", \"Reexport\", \"SciMLBase\", \"Setfield\", \"StaticArrays\", \"UnPack\"]\ngit-tree-sha1 = \"b61c51cd5b9d8b197dfcbbf2077a0a4e1505278d\"\nuuid = \"8913a72c-1f9b-4ce2-8d82-65094dcecaec\"\nversion = \"0.3.14\"\n\n[[deps.OffsetArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"043017e0bdeff61cfbb7afeb558ab29536bbb5ed\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.8\"\n\n[[deps.Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"887579a3eb005446d514ab7aeac5d1d027658b8f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+1\"\n\n[[deps.OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[deps.OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[deps.OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"648107615c15d4e09f7eca16307bc821c1f718d8\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.13+0\"\n\n[[deps.OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[deps.Optim]]\ndeps = [\"Compat\", \"FillArrays\", \"ForwardDiff\", \"LineSearches\", \"LinearAlgebra\", \"NLSolversBase\", \"NaNMath\", \"Parameters\", \"PositiveFactorizations\", \"Printf\", \"SparseArrays\", \"StatsBase\"]\ngit-tree-sha1 = \"045d10789f5daff18deb454d5923c6996017c2f3\"\nuuid = \"429524aa-4258-5aef-a3af-852621145aeb\"\nversion = \"1.6.1\"\n\n[[deps.Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[deps.OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[deps.OrdinaryDiffEq]]\ndeps = [\"Adapt\", \"ArrayInterface\", \"DataStructures\", \"DiffEqBase\", \"DocStringExtensions\", \"ExponentialUtilities\", \"FastClosures\", \"FiniteDiff\", \"ForwardDiff\", \"LinearAlgebra\", \"LinearSolve\", \"Logging\", \"LoopVectorization\", \"MacroTools\", \"MuladdMacro\", \"NLsolve\", \"NonlinearSolve\", \"Polyester\", \"PreallocationTools\", \"RecursiveArrayTools\", \"Reexport\", \"SparseArrays\", \"SparseDiffTools\", \"StaticArrays\", \"UnPack\"]\ngit-tree-sha1 = \"df82fa0f9f90f669cc3cf9e3f0400e431e0704ac\"\nuuid = \"1dea7af3-3e70-54e6-95c3-0bf5283fa5ed\"\nversion = \"6.6.6\"\n\n[[deps.PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[deps.PDMats]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"SuiteSparse\"]\ngit-tree-sha1 = \"ee26b350276c51697c9c2d88a072b339f9f03d73\"\nuuid = \"90014a1f-27ba-587c-ab20-58faa44d9150\"\nversion = \"0.11.5\"\n\n[[deps.ParameterizedFunctions]]\ndeps = [\"DataStructures\", \"DiffEqBase\", \"DocStringExtensions\", \"Latexify\", \"LinearAlgebra\", \"ModelingToolkit\", \"Reexport\", \"SciMLBase\"]\ngit-tree-sha1 = \"2f48f745e976dc5575bbc301e6c63b8fb5f12155\"\nuuid = \"65888b18-ceab-5e60-b2b9-181511a3b968\"\nversion = \"5.13.1\"\n\n[[deps.Parameters]]\ndeps = [\"OrderedCollections\", \"UnPack\"]\ngit-tree-sha1 = \"34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe\"\nuuid = \"d96e819e-fc66-5662-9728-84c9c7592b0a\"\nversion = \"0.12.3\"\n\n[[deps.Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"13468f237353112a01b2d6b32f3d0f80219944aa\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.2.2\"\n\n[[deps.Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[deps.Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[deps.PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[deps.PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"6f1b25e8ea06279b5689263cc538f51331d7ca17\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.1.3\"\n\n[[deps.Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\", \"UnicodeFun\", \"Unzip\"]\ngit-tree-sha1 = \"eb1432ec2b781f70ce2126c277d120554605669a\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.25.8\"\n\n[[deps.PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"ColorTypes\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"bf0a1121af131d9974241ba53f601211e9303a9e\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.37\"\n\n[[deps.PoissonRandom]]\ndeps = [\"Random\", \"Statistics\", \"Test\"]\ngit-tree-sha1 = \"44d018211a56626288b5d3f8c6497d28c26dc850\"\nuuid = \"e409e4f3-bfea-5376-8464-e040bb5c01ab\"\nversion = \"0.4.0\"\n\n[[deps.Polyester]]\ndeps = [\"ArrayInterface\", \"BitTwiddlingConvenienceFunctions\", \"CPUSummary\", \"IfElse\", \"ManualMemory\", \"PolyesterWeave\", \"Requires\", \"Static\", \"StrideArraysCore\", \"ThreadingUtilities\"]\ngit-tree-sha1 = \"de33c49a06d7eb1eef40b83fe873c1c2cba25623\"\nuuid = \"f517fe37-dbe3-4b94-8317-1923a5111588\"\nversion = \"0.6.4\"\n\n[[deps.PolyesterWeave]]\ndeps = [\"BitTwiddlingConvenienceFunctions\", \"CPUSummary\", \"IfElse\", \"Static\", \"ThreadingUtilities\"]\ngit-tree-sha1 = \"0bc9e1a21ba066335a5207ac031ee41f72615181\"\nuuid = \"1d0040c9-8b98-4ee7-8388-3f51789ca0ad\"\nversion = \"0.1.3\"\n\n[[deps.PositiveFactorizations]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"17275485f373e6673f7e7f97051f703ed5b15b20\"\nuuid = \"85a6dd25-e78a-55b7-8502-1745935b8125\"\nversion = \"0.2.4\"\n\n[[deps.PreallocationTools]]\ndeps = [\"Adapt\", \"ArrayInterface\", \"ForwardDiff\", \"LabelledArrays\"]\ngit-tree-sha1 = \"e4cb8d4a2edf9b3804c1fb2c2de57d634ff3f36e\"\nuuid = \"d236fae5-4411-538c-8e31-a6e3d9e00b46\"\nversion = \"0.2.3\"\n\n[[deps.Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"2cf929d64681236a2e074ffafb8d568733d2e6af\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.3\"\n\n[[deps.Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[deps.Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[deps.QuadGK]]\ndeps = [\"DataStructures\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"78aadffb3efd2155af139781b8a8df1ef279ea39\"\nuuid = \"1fd47b50-473d-5c70-9696-f719f8f3bcdc\"\nversion = \"2.4.2\"\n\n[[deps.REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[deps.Random]]\ndeps = [\"SHA\", \"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[deps.Random123]]\ndeps = [\"Libdl\", \"Random\", \"RandomNumbers\"]\ngit-tree-sha1 = \"0e8b146557ad1c6deb1367655e052276690e71a3\"\nuuid = \"74087812-796a-5b5d-8853-05524746bad3\"\nversion = \"1.4.2\"\n\n[[deps.RandomNumbers]]\ndeps = [\"Random\", \"Requires\"]\ngit-tree-sha1 = \"043da614cc7e95c703498a491e2c21f58a2b8111\"\nuuid = \"e6cf234a-135c-5ec9-84dd-332b85af5143\"\nversion = \"1.5.3\"\n\n[[deps.RecipesBase]]\ngit-tree-sha1 = \"6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.2.1\"\n\n[[deps.RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"37c1631cb3cc36a535105e6d5557864c82cd8c2b\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.5.0\"\n\n[[deps.RecursiveArrayTools]]\ndeps = [\"Adapt\", \"ArrayInterface\", \"ChainRulesCore\", \"DocStringExtensions\", \"FillArrays\", \"LinearAlgebra\", \"RecipesBase\", \"Requires\", \"StaticArrays\", \"Statistics\", \"ZygoteRules\"]\ngit-tree-sha1 = \"5144e1eafb2ecc75765888a4bdcd3a30a6a08b14\"\nuuid = \"731186ca-8d62-57ce-b412-fbd966d074cd\"\nversion = \"2.24.1\"\n\n[[deps.RecursiveFactorization]]\ndeps = [\"LinearAlgebra\", \"LoopVectorization\", \"Polyester\", \"StrideArraysCore\", \"TriangularSolve\"]\ngit-tree-sha1 = \"7ad4c2ef15b7aecd767b3921c0d255d39b3603ea\"\nuuid = \"f2c3362d-daeb-58d1-803e-2bc74f2840b4\"\nversion = \"0.2.9\"\n\n[[deps.Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[deps.Referenceables]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"e681d3bfa49cd46c3c161505caddf20f0e62aaa9\"\nuuid = \"42d2dcc6-99eb-4e98-b66c-637b7d73030e\"\nversion = \"0.1.2\"\n\n[[deps.RelocatableFolders]]\ndeps = [\"SHA\", \"Scratch\"]\ngit-tree-sha1 = \"cdbd3b1338c72ce29d9584fdbe9e9b70eeb5adca\"\nuuid = \"05181044-ff0b-4ac5-8273-598c1e38db00\"\nversion = \"0.1.3\"\n\n[[deps.Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.3.0\"\n\n[[deps.ResettableStacks]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"256eeeec186fa7f26f2801732774ccf277f05db9\"\nuuid = \"ae5879a3-cd67-5da8-be7f-38c6eb64a37b\"\nversion = \"1.1.1\"\n\n[[deps.Rmath]]\ndeps = [\"Random\", \"Rmath_jll\"]\ngit-tree-sha1 = \"bf3188feca147ce108c76ad82c2792c57abe7b1f\"\nuuid = \"79098fc4-a85e-5d69-aa6a-4863f24498fa\"\nversion = \"0.7.0\"\n\n[[deps.Rmath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"68db32dff12bb6127bac73c209881191bf0efbb7\"\nuuid = \"f50d1b31-88e8-58de-be2c-1cc44531875f\"\nversion = \"0.3.0+0\"\n\n[[deps.RuntimeGeneratedFunctions]]\ndeps = [\"ExprTools\", \"SHA\", \"Serialization\"]\ngit-tree-sha1 = \"cdc1e4278e91a6ad530770ebb327f9ed83cf10c4\"\nuuid = \"7e49a35a-f44a-4d26-94aa-eba1b4ca6b47\"\nversion = \"0.5.3\"\n\n[[deps.SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[deps.SIMDDualNumbers]]\ndeps = [\"ForwardDiff\", \"IfElse\", \"SLEEFPirates\", \"VectorizationBase\"]\ngit-tree-sha1 = \"62c2da6eb66de8bb88081d20528647140d4daa0e\"\nuuid = \"3cdde19b-5bb0-4aaf-8931-af3e248e098b\"\nversion = \"0.1.0\"\n\n[[deps.SIMDTypes]]\ngit-tree-sha1 = \"330289636fb8107c5f32088d2741e9fd7a061a5c\"\nuuid = \"94e857df-77ce-4151-89e5-788b33177be4\"\nversion = \"0.1.0\"\n\n[[deps.SLEEFPirates]]\ndeps = [\"IfElse\", \"Static\", \"VectorizationBase\"]\ngit-tree-sha1 = \"1410aad1c6b35862573c01b96cd1f6dbe3979994\"\nuuid = \"476501e8-09a2-5ece-8869-fb82de89a1fa\"\nversion = \"0.6.28\"\n\n[[deps.SafeTestsets]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"36ebc5622c82eb9324005cc75e7e2cc51181d181\"\nuuid = \"1bc83da4-3b8d-516f-aca4-4fe02f6d838f\"\nversion = \"0.0.1\"\n\n[[deps.SciMLBase]]\ndeps = [\"ArrayInterface\", \"CommonSolve\", \"ConstructionBase\", \"Distributed\", \"DocStringExtensions\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"Logging\", \"RecipesBase\", \"RecursiveArrayTools\", \"StaticArrays\", \"Statistics\", \"Tables\", \"TreeViews\"]\ngit-tree-sha1 = \"f4862c0cb4e34ed182718221028ba1bf50742108\"\nuuid = \"0bca4576-84f4-4d90-8ffe-ffa030f20462\"\nversion = \"1.26.1\"\n\n[[deps.Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[deps.Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[deps.Setfield]]\ndeps = [\"ConstructionBase\", \"Future\", \"MacroTools\", \"Requires\"]\ngit-tree-sha1 = \"0afd9e6c623e379f593da01f20590bacc26d1d14\"\nuuid = \"efcf1570-3423-57d1-acb7-fd33fddbac46\"\nversion = \"0.8.1\"\n\n[[deps.SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[deps.Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[deps.SimpleTraits]]\ndeps = [\"InteractiveUtils\", \"MacroTools\"]\ngit-tree-sha1 = \"5d7e3f4e11935503d3ecaf7186eac40602e7d231\"\nuuid = \"699a6c99-e7fa-54fc-8d76-47d257e15c1d\"\nversion = \"0.9.4\"\n\n[[deps.Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[deps.SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[deps.SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[deps.SparseDiffTools]]\ndeps = [\"Adapt\", \"ArrayInterface\", \"Compat\", \"DataStructures\", \"FiniteDiff\", \"ForwardDiff\", \"Graphs\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"StaticArrays\", \"VertexSafeGraphs\"]\ngit-tree-sha1 = \"5036f3584c60ab8b9c87d73bb7105f4832d7b2ea\"\nuuid = \"47a9eef4-7e08-11e9-0b38-333d64bd3804\"\nversion = \"1.20.1\"\n\n[[deps.SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"8d0c8e3d0ff211d9ff4a0c2307d876c99d10bdf1\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"2.1.2\"\n\n[[deps.SplittablesBase]]\ndeps = [\"Setfield\", \"Test\"]\ngit-tree-sha1 = \"39c9f91521de844bad65049efd4f9223e7ed43f9\"\nuuid = \"171d559e-b47b-412a-8079-5efa626c420e\"\nversion = \"0.1.14\"\n\n[[deps.Static]]\ndeps = [\"IfElse\"]\ngit-tree-sha1 = \"7f5a513baec6f122401abfc8e9c074fdac54f6c1\"\nuuid = \"aedffcd0-7271-4cad-89d0-dc628f76c6d3\"\nversion = \"0.4.1\"\n\n[[deps.StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"a635a9333989a094bddc9f940c04c549cd66afcf\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.3.4\"\n\n[[deps.Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[deps.StatsAPI]]\ngit-tree-sha1 = \"d88665adc9bcf45903013af0982e2fd05ae3d0a6\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.2.0\"\n\n[[deps.StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"51383f2d367eb3b444c961d485c565e4c0cf4ba0\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.14\"\n\n[[deps.StatsFuns]]\ndeps = [\"ChainRulesCore\", \"InverseFunctions\", \"IrrationalConstants\", \"LogExpFunctions\", \"Reexport\", \"Rmath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"f35e1879a71cca95f4826a14cdbf0b9e253ed918\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.15\"\n\n[[deps.SteadyStateDiffEq]]\ndeps = [\"DiffEqBase\", \"DiffEqCallbacks\", \"LinearAlgebra\", \"NLsolve\", \"Reexport\", \"SciMLBase\"]\ngit-tree-sha1 = \"3e057e1f9f12d18cac32011aed9e61eef6c1c0ce\"\nuuid = \"9672c7b4-1e72-59bd-8a11-6ac3964bc41f\"\nversion = \"1.6.6\"\n\n[[deps.StochasticDiffEq]]\ndeps = [\"Adapt\", \"ArrayInterface\", \"DataStructures\", \"DiffEqBase\", \"DiffEqJump\", \"DiffEqNoiseProcess\", \"DocStringExtensions\", \"FillArrays\", \"FiniteDiff\", \"ForwardDiff\", \"LinearAlgebra\", \"Logging\", \"MuladdMacro\", \"NLsolve\", \"OrdinaryDiffEq\", \"Random\", \"RandomNumbers\", \"RecursiveArrayTools\", \"Reexport\", \"SparseArrays\", \"SparseDiffTools\", \"StaticArrays\", \"UnPack\"]\ngit-tree-sha1 = \"5f88440e7470baad99f559eed674a46d2b6b96f7\"\nuuid = \"789caeaf-c7a9-5a7d-9973-96adeb23e2a0\"\nversion = \"6.44.0\"\n\n[[deps.StrideArraysCore]]\ndeps = [\"ArrayInterface\", \"CloseOpenIntervals\", \"IfElse\", \"LayoutPointers\", \"ManualMemory\", \"Requires\", \"SIMDTypes\", \"Static\", \"ThreadingUtilities\"]\ngit-tree-sha1 = \"12cf3253ebd8e2a3214ae171fbfe51e7e8d8ad28\"\nuuid = \"7792a7ef-975c-4747-a70f-980b88e8d1da\"\nversion = \"0.2.9\"\n\n[[deps.StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"d21f2c564b21a202f4677c0fba5b5ee431058544\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.4\"\n\n[[deps.SuiteSparse]]\ndeps = [\"Libdl\", \"LinearAlgebra\", \"Serialization\", \"SparseArrays\"]\nuuid = \"4607b0f0-06f3-5cda-b6b1-a6196a1729e9\"\n\n[[deps.SuiteSparse_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"Pkg\", \"libblastrampoline_jll\"]\nuuid = \"bea87d4a-7f5b-5778-9afe-8cc45184846c\"\n\n[[deps.Sundials]]\ndeps = [\"CEnum\", \"DataStructures\", \"DiffEqBase\", \"Libdl\", \"LinearAlgebra\", \"Logging\", \"Reexport\", \"SparseArrays\", \"Sundials_jll\"]\ngit-tree-sha1 = \"76d881c22a2f3f879ad74b5a9018c609969149ab\"\nuuid = \"c3572dad-4567-51f8-b174-8c6c989267f4\"\nversion = \"4.9.2\"\n\n[[deps.Sundials_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"OpenBLAS_jll\", \"Pkg\", \"SuiteSparse_jll\"]\ngit-tree-sha1 = \"04777432d74ec5bc91ca047c9e0e0fd7f81acdb6\"\nuuid = \"fb77eaff-e24c-56d4-86b1-d163f2edb164\"\nversion = \"5.2.1+0\"\n\n[[deps.SymbolicUtils]]\ndeps = [\"AbstractTrees\", \"Bijections\", \"ChainRulesCore\", \"Combinatorics\", \"ConstructionBase\", \"DataStructures\", \"DocStringExtensions\", \"DynamicPolynomials\", \"IfElse\", \"LabelledArrays\", \"LinearAlgebra\", \"Metatheory\", \"MultivariatePolynomials\", \"NaNMath\", \"Setfield\", \"SparseArrays\", \"SpecialFunctions\", \"StaticArrays\", \"TermInterface\", \"TimerOutputs\"]\ngit-tree-sha1 = \"bfa211c9543f8c062143f2a48e5bcbb226fd790b\"\nuuid = \"d1185830-fcd6-423d-90d6-eec64667417b\"\nversion = \"0.19.7\"\n\n[[deps.Symbolics]]\ndeps = [\"ArrayInterface\", \"ConstructionBase\", \"DataStructures\", \"DiffRules\", \"Distributions\", \"DocStringExtensions\", \"DomainSets\", \"IfElse\", \"Latexify\", \"Libdl\", \"LinearAlgebra\", \"MacroTools\", \"Metatheory\", \"NaNMath\", \"RecipesBase\", \"Reexport\", \"Requires\", \"RuntimeGeneratedFunctions\", \"SciMLBase\", \"Setfield\", \"SparseArrays\", \"SpecialFunctions\", \"StaticArrays\", \"SymbolicUtils\", \"TermInterface\", \"TreeViews\"]\ngit-tree-sha1 = \"074e08aea1c745664da5c4b266f50b840e528b1c\"\nuuid = \"0c5d862f-8b57-4792-8d23-62f2024744c7\"\nversion = \"4.3.0\"\n\n[[deps.TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[deps.TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[deps.Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"bb1064c9a84c52e277f1096cf41434b675cd368b\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.6.1\"\n\n[[deps.Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[deps.TermInterface]]\ngit-tree-sha1 = \"7aa601f12708243987b88d1b453541a75e3d8c7a\"\nuuid = \"8ea1fca8-c5ef-4a55-8b96-4e9afe9c9a3c\"\nversion = \"0.2.3\"\n\n[[deps.Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[deps.ThreadingUtilities]]\ndeps = [\"ManualMemory\"]\ngit-tree-sha1 = \"884539ba8c4584a3a8173cb4ee7b61049955b79c\"\nuuid = \"8290d209-cae3-49c0-8002-c8c24d57dab5\"\nversion = \"0.4.7\"\n\n[[deps.ThreadsX]]\ndeps = [\"ArgCheck\", \"BangBang\", \"ConstructionBase\", \"InitialValues\", \"MicroCollections\", \"Referenceables\", \"Setfield\", \"SplittablesBase\", \"Transducers\"]\ngit-tree-sha1 = \"6dad289fe5fc1d8e907fa855135f85fb03c8fa7a\"\nuuid = \"ac1d9e8a-700a-412c-b207-f0111f4b6c0d\"\nversion = \"0.1.9\"\n\n[[deps.TimerOutputs]]\ndeps = [\"ExprTools\", \"Printf\"]\ngit-tree-sha1 = \"97e999be94a7147d0609d0b9fc9feca4bf24d76b\"\nuuid = \"a759f4b9-e2f1-59dc-863e-4aeb61b1ea8f\"\nversion = \"0.5.15\"\n\n[[deps.Tokenize]]\ngit-tree-sha1 = \"0952c9cee34988092d73a5708780b3917166a0dd\"\nuuid = \"0796e94c-ce3b-5d07-9a54-7f471281c624\"\nversion = \"0.5.21\"\n\n[[deps.Transducers]]\ndeps = [\"Adapt\", \"ArgCheck\", \"BangBang\", \"Baselet\", \"CompositionsBase\", \"DefineSingletons\", \"Distributed\", \"InitialValues\", \"Logging\", \"Markdown\", \"MicroCollections\", \"Requires\", \"Setfield\", \"SplittablesBase\", \"Tables\"]\ngit-tree-sha1 = \"1cda71cc967e3ef78aa2593319f6c7379376f752\"\nuuid = \"28d57a85-8fef-5791-bfe6-a80928e7c999\"\nversion = \"0.4.72\"\n\n[[deps.TreeViews]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d0d7a3fe2f30d6a7f833a5f19f7c7a5b396eae6\"\nuuid = \"a2a6695c-b41b-5b7d-aed9-dbfdeacea5d7\"\nversion = \"0.3.0\"\n\n[[deps.TriangularSolve]]\ndeps = [\"CloseOpenIntervals\", \"IfElse\", \"LayoutPointers\", \"LinearAlgebra\", \"LoopVectorization\", \"Polyester\", \"Static\", \"VectorizationBase\"]\ngit-tree-sha1 = \"c3ab8b77b82fd92e2b6eea8a275a794d5a6e4011\"\nuuid = \"d5829a12-d9aa-46ab-831f-fb7c9ab06edf\"\nversion = \"0.1.9\"\n\n[[deps.URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[deps.UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[deps.UnPack]]\ngit-tree-sha1 = \"387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b\"\nuuid = \"3a884ed6-31ef-47d7-9d2a-63182c4928ed\"\nversion = \"1.0.2\"\n\n[[deps.Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[deps.UnicodeFun]]\ndeps = [\"REPL\"]\ngit-tree-sha1 = \"53915e50200959667e78a92a418594b428dffddf\"\nuuid = \"1cfade01-22cf-5700-b092-accc4b62d6e1\"\nversion = \"0.4.1\"\n\n[[deps.Unitful]]\ndeps = [\"ConstructionBase\", \"Dates\", \"LinearAlgebra\", \"Random\"]\ngit-tree-sha1 = \"b649200e887a487468b71821e2644382699f1b0f\"\nuuid = \"1986cc42-f94f-5a68-af5c-568840ba703d\"\nversion = \"1.11.0\"\n\n[[deps.Unzip]]\ngit-tree-sha1 = \"34db80951901073501137bdbc3d5a8e7bbd06670\"\nuuid = \"41fe7b60-77ed-43a1-b4f0-825fd5a5650d\"\nversion = \"0.1.2\"\n\n[[deps.VectorizationBase]]\ndeps = [\"ArrayInterface\", \"CPUSummary\", \"HostCPUFeatures\", \"Hwloc\", \"IfElse\", \"LayoutPointers\", \"Libdl\", \"LinearAlgebra\", \"SIMDTypes\", \"Static\"]\ngit-tree-sha1 = \"e9a35d501b24c127af57ca5228bcfb806eda7507\"\nuuid = \"3d5dd08c-fd9d-11e8-17fa-ed2836048c2f\"\nversion = \"0.21.24\"\n\n[[deps.VertexSafeGraphs]]\ndeps = [\"Graphs\"]\ngit-tree-sha1 = \"8351f8d73d7e880bfc042a8b6922684ebeafb35c\"\nuuid = \"19fa3120-7c27-5ec5-8db8-b0b0aa330d6f\"\nversion = \"0.2.0\"\n\n[[deps.Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[deps.Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"66d72dc6fcc86352f01676e8f0f698562e60510f\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.23.0+0\"\n\n[[deps.XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[deps.XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[deps.Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[deps.Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[deps.Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[deps.Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[deps.Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[deps.Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[deps.Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[deps.Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[deps.Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[deps.Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[deps.Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[deps.Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[deps.Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[deps.Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[deps.Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[deps.Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[deps.Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[deps.Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[deps.Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[deps.Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e45044cd873ded54b6a5bac0eb5c971392cf1927\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.2+0\"\n\n[[deps.ZygoteRules]]\ndeps = [\"MacroTools\"]\ngit-tree-sha1 = \"8c1a8e4dfacb1fd631745552c8db35d0deb09ea0\"\nuuid = \"700de1a5-db45-46bc-99cf-38207098b444\"\nversion = \"0.2.2\"\n\n[[deps.libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[deps.libblastrampoline_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"OpenBLAS_jll\"]\nuuid = \"8e850b90-86db-534c-a0d3-1478176c7d93\"\n\n[[deps.libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[deps.libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[deps.libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"b910cb81ef3fe6e78bf6acee440bda86fd6ae00c\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+1\"\n\n[[deps.nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[deps.p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[deps.x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[deps.x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[deps.xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─6458ccf4-03b2-4d7f-8206-dcdeef1bc020\n# ╠═93b38489-898a-4695-a167-5f5a782ef0e8\n# ╠═8a49cf89-d1c8-4847-8b9b-70b23c2b609c\n# ╠═3e86dfc7-8567-4b0d-a75a-13422acfa20a\n# ╠═71bcf780-2eb2-487f-b90e-1a2b3f740e19\n# ╟─23c6e540-3049-419b-bf82-4141977f9a0f\n# ╠═ed4267e2-8c95-4d78-955f-b89cdb125f18\n# ╟─423bf107-0d98-48f6-b780-932fd216b803\n# ╠═5c41d702-aab7-44a8-9347-a26ed27703ed\n# ╠═0995aee5-f4f9-4d75-9651-5513bd243a36\n# ╠═9913179f-1a94-4d20-87ff-bd2c2bec7530\n# ╟─3ac8e1d7-429f-4ae3-8b33-beafaf9bf043\n# ╠═379f8c7e-3f7c-43f4-8387-f75728b3c4a3\n# ╟─f25d32de-fd9f-408d-b3b8-0b4707467186\n# ╠═93854457-e209-42ea-b533-5a018ad2024b\n# ╠═292bcc76-e7e6-4628-a839-5e83f8caba68\n# ╟─edebc440-cf82-4ba4-a97e-90da9220690b\n# ╠═cd970122-8288-40d8-ac15-564ca8cb26f3\n# ╟─e4f3b341-4136-4f77-884b-e9c403e45d09\n# ╠═981c2e93-9495-4482-9c5c-970c6c8e03d2\n# ╠═6837c59d-1d1b-4ff6-8016-dd81703226c9\n# ╟─f67a4f14-3051-4e43-9fbf-a332d1b59dd7\n# ╠═b0f2ef4b-29c2-44d9-9382-dd5421260296\n# ╟─995b908f-ccf8-48ba-a45c-024f8d6527f4\n# ╠═ce923957-2f70-4023-bab4-8a73a6fd3800\n# ╠═65cd089f-7563-4696-a5fa-81074ef8bb33\n# ╟─b4696fcc-8c09-4563-88e2-0aca1d734eba\n# ╠═1de38637-f5d2-4679-a6f6-2a9672a9e5ea\n# ╠═d8158943-8ba2-4176-b3d7-e99197c82e1b\n# ╠═75c7c433-c228-4417-be7b-f1f50b2c4921\n# ╟─8a5644dc-69cf-44dc-b5f7-eadc8c3aa0a7\n# ╠═d275e770-76f0-4a9f-8628-1abfc4eeedf5\n# ╟─416c8f55-154a-4953-8162-b0c2e6069f48\n# ╠═a7993c27-7f27-40e6-8d63-ff74b31e6935\n# ╠═05e01d78-de55-4655-b792-5ce62abea53a\n# ╟─353b1a99-0c87-4286-9b22-3c5f72145e52\n# ╠═dd5601e5-fc2a-4927-9292-f6bf2f51d2a0\n# ╠═50e9d7ee-68b1-497c-bd91-0be168e0b964\n# ╟─4481524c-8117-4835-b46e-ebe9d6878f40\n# ╠═63e0ac0e-c6a1-40f4-8af9-a0a5eaabf344\n# ╟─0b3661cc-ca0e-485d-bcdb-4fbc339c0195\n# ╟─52196376-6060-4fd6-8fcc-d1505075bae8\n# ╟─62516169-0e2e-4907-a87d-65af79e0926f\n# ╠═26c8db68-c21d-4f94-a93c-a82eb7753d3e\n# ╟─143ef067-a8ec-4cc5-b2b5-43746529d4c6\n# ╠═a627aa52-e44a-4f83-99af-40e316643b3c\n# ╠═d12f7049-25b8-4cca-b2f4-788a2314c973\n# ╟─75f33bbd-2340-4c92-aef3-77a33dd6ae3e\n# ╠═d268c6a7-45db-42a1-9a63-77800663ad6e\n# ╠═a1dc49b8-52b4-474f-9463-9231ac879b90\n# ╠═0e0f7785-e323-4aed-8dd4-e7fa91eddd4a\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "a6f4b8136215dfed83746037423d917c72a3458b", "size": 80062, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "13 ODE solvers.jl", "max_stars_repo_name": "davidgmiguez/PlutoNotebooks", "max_stars_repo_head_hexsha": "7997ea6a3a6bc942a621b66804fb711b4bad440d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "13 ODE solvers.jl", "max_issues_repo_name": "davidgmiguez/PlutoNotebooks", "max_issues_repo_head_hexsha": "7997ea6a3a6bc942a621b66804fb711b4bad440d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "13 ODE solvers.jl", "max_forks_repo_name": "davidgmiguez/PlutoNotebooks", "max_forks_repo_head_hexsha": "7997ea6a3a6bc942a621b66804fb711b4bad440d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1127649977, "max_line_length": 603, "alphanum_fraction": 0.7327696036, "num_tokens": 35159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.863391599428538, "lm_q1q2_score": 0.77381590653986}}
{"text": "using ClassicalOrthogonalPolynomials, Plots, Test\nimport ArrayLayouts: diagonal\n\n###\n# We can solve ODEs like the Airy equation\n#\n# u(-1) = airyai(-1)\n# u(1) = airyai(1)\n# u'' = x * u\n#\n# using the ultraspherical spectral method. \n\nT = Chebyshev()\nC = Ultraspherical(2)\nx = axes(T,1)\nD = Derivative(x)\n\nc = [T[[begin,end],:]; C \\ ((D^2 - diagonal(x))*T)] \\ [airyai(-1); airyai(1); zeros(∞)]\nu = T*c\n\n@test u[0.0] ≈ airyai(0.0)\nplot(u)\n\n\n##\n# Lee & Greengard\n# ε*u'' - x*u' + u = 0, u(-1) = 1, u(1) = 2\n##\n\nT = ChebyshevT()\nC = Ultraspherical(2)\nx = axes(T,1)\nD = Derivative(x)\n\nε = 1/100\nA = [T[[begin,end],:]; C \\ ((ε*D^2 - x .* D + I) * T)]\nc = A \\ [1; 2; zeros(∞)]\nu = T*c\nplot(u)\n\nC \\ (ε*D^2 - x .* D + I) ", "meta": {"hexsha": "6d7579a6f5589b1b2ba7a1ad37362063588764a3", "size": 710, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ultrasphericalspectralmethod.jl", "max_stars_repo_name": "ioannisPApapadopoulos/ClassicalOrthogonalPolynomials.jl", "max_stars_repo_head_hexsha": "63610e3236dd7ffa9152db00734aab6af28f1793", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-01-26T15:24:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T13:53:03.000Z", "max_issues_repo_path": "examples/ultrasphericalspectralmethod.jl", "max_issues_repo_name": "ioannisPApapadopoulos/ClassicalOrthogonalPolynomials.jl", "max_issues_repo_head_hexsha": "63610e3236dd7ffa9152db00734aab6af28f1793", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2021-01-27T21:38:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T14:54:26.000Z", "max_forks_repo_path": "examples/ultrasphericalspectralmethod.jl", "max_forks_repo_name": "ioannisPApapadopoulos/ClassicalOrthogonalPolynomials.jl", "max_forks_repo_head_hexsha": "63610e3236dd7ffa9152db00734aab6af28f1793", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-01-27T11:21:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T18:15:59.000Z", "avg_line_length": 17.3170731707, "max_line_length": 87, "alphanum_fraction": 0.5450704225, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104924150546, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7737971520183472}}
{"text": "#=\nThe four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.\n\n73167176531330624919225119674426574742355349194934\n96983520312774506326239578318016984801869478851843\n85861560789112949495459501737958331952853208805511\n12540698747158523863050715693290963295227443043557\n66896648950445244523161731856403098711121722383113\n62229893423380308135336276614282806444486645238749\n30358907296290491560440772390713810515859307960866\n70172427121883998797908792274921901699720888093776\n65727333001053367881220235421809751254540594752243\n52584907711670556013604839586446706324415722155397\n53697817977846174064955149290862569321978468622482\n83972241375657056057490261407972968652414535100474\n82166370484403199890008895243450658541227588666881\n16427171479924442928230863465674813919123162824586\n17866458359124566529476545682848912883142607690042\n24219022671055626321111109370544217506941658960408\n07198403850962455444362981230987879927244284909188\n84580156166097919133875499200524063689912560717606\n05886116467109405077541002256983155200055935729725\n71636269561882670428252483600823257530420752963450\nFind the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?\n=#\n\nfunction greatest_adjacent_digit_product(adjacent_digits)\n  i = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450\n  i_digits = digits(i)\n  largest_product = 1\n  for x in 1:length(i_digits)-adjacent_digits\n    product = 1\n    for y in 1:adjacent_digits\n      product *= i_digits[x+y]\n    end\n    largest_product = product > largest_product ? product : largest_product\n  end\n  largest_product\nend\n@time println(greatest_adjacent_digit_product(13))\n", "meta": {"hexsha": "4f23725028b94c5bdbb374b6d28cfec9ef03ad8e", "size": 2658, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p8.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p8.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p8.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 64.8292682927, "max_line_length": 1006, "alphanum_fraction": 0.9315274643, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7737570300622288}}
{"text": "# Code from @devmotion\n# https://github.com/devmotion/\\\n# CalibrationErrorsDistributions.jl/blob/main/src/distances/bures.jl\n\n\"\"\"\n    tr_sqrt(A::AbstractMatrix)\n\nCompute ``\\\\operatorname{tr}\\\\big(A^{1/2}\\\\big)``.\n\"\"\"\ntr_sqrt(A::AbstractMatrix) = LinearAlgebra.tr(sqrt(A))\ntr_sqrt(A::PDMats.PDMat) = tr_sqrt(A.mat)\ntr_sqrt(A::PDMats.PDiagMat) = sum(sqrt, A.diag)\ntr_sqrt(A::PDMats.ScalMat) = A.dim * sqrt(A.value)\n\n\"\"\"\n    _gaussian_ot_A(A::AbstractMatrix, B::AbstractMatrix)\n\nCompute\n```math\nA^{1/2} B A^{1/2}.\n```\n\"\"\"\nfunction _gaussian_ot_A(A::AbstractMatrix, B::AbstractMatrix)\n    sqrt_A = sqrt(A)\n    return sqrt_A * B * sqrt_A\nend\nfunction _gaussian_ot_A(A::PDMats.PDiagMat, B::AbstractMatrix)\n    return sqrt.(A.diag) .* B .* sqrt.(A.diag')\nend\nfunction _gaussian_ot_A(A::StridedMatrix, B::PDMats.PDMat)\n    return PDMats.X_A_Xt(B, sqrt(A))\nend\n_gaussian_ot_A(A::PDMats.PDMat, B::PDMats.PDMat) = _gaussian_ot_A(A.mat, B)\n_gaussian_ot_A(A::AbstractMatrix, B::PDMats.PDiagMat) = _gaussian_ot_A(B, A)\n_gaussian_ot_A(A::PDMats.PDMat, B::StridedMatrix) = _gaussian_ot_A(B, A)\n\n\"\"\"\n    sqbures(A::AbstractMatrix, B::AbstractMatrix)\n\nCompute the squared Bures metric\n```math\n\\\\operatorname{tr}(A) + \\\\operatorname{tr}(B)\n- \\\\operatorname{tr}\\\\Big({\\\\big(A^{1/2} B A^{1/2}\\\\big)}^{1/2}\\\\Big).\n```\n\"\"\"\nfunction sqbures(A::AbstractMatrix, B::AbstractMatrix)\n    return LinearAlgebra.tr(A) + LinearAlgebra.tr(B) - 2 * tr_sqrt(_gaussian_ot_A(A, B))\nend\n\n# diagonal matrix\nfunction sqbures(A::PDMats.PDiagMat, B::PDMats.PDiagMat)\n    if !(A.dim == B.dim)\n        throw(ArgumentError(\"matrices must have the same dimensions.\"))\n    end\n    return sum(zip(A.diag, B.diag)) do (x, y)\n        abs2(sqrt(x) - sqrt(y))\n    end\nend\n\n# scaled identity matrix\nfunction sqbures(A::PDMats.ScalMat, B::AbstractMatrix)\n    return LinearAlgebra.tr(A) + LinearAlgebra.tr(B) - 2 * sqrt(A.value) * tr_sqrt(B)\nend\nsqbures(A::AbstractMatrix, B::PDMats.ScalMat) = sqbures(B, A)\nsqbures(A::PDMats.ScalMat, B::PDMats.ScalMat) = A.dim * abs2(sqrt(A.value) - sqrt(B.value))\n\n# combinations\nfunction sqbures(A::PDMats.PDiagMat, B::PDMats.ScalMat)\n    sqrt_B = sqrt(B.value)\n    return sum(A.diag) do x\n        abs2(sqrt(x) - sqrt_B)\n    end\nend\nsqbures(A::PDMats.ScalMat, B::PDMats.PDiagMat) = sqbures(B, A)\n", "meta": {"hexsha": "a9b50b7d3bdabaf34e68d79940c60739df45108d", "size": 2277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances/bures.jl", "max_stars_repo_name": "zsteve/OptimalTransport.jl", "max_stars_repo_head_hexsha": "ab9bc76a13c106f451ef58126cab07758f905f3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2020-05-07T13:52:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T21:34:03.000Z", "max_issues_repo_path": "src/distances/bures.jl", "max_issues_repo_name": "juliohm/ExactOptimalTransport.jl", "max_issues_repo_head_hexsha": "1b1d3da31fdbc13f6488c49c10b453ac47baf75c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 49, "max_issues_repo_issues_event_min_datetime": "2020-05-15T16:48:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-18T18:38:46.000Z", "max_forks_repo_path": "src/distances/bures.jl", "max_forks_repo_name": "juliohm/ExactOptimalTransport.jl", "max_forks_repo_head_hexsha": "1b1d3da31fdbc13f6488c49c10b453ac47baf75c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-05-27T21:56:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-19T19:15:09.000Z", "avg_line_length": 30.36, "max_line_length": 91, "alphanum_fraction": 0.6881862099, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258009, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.7737570289644048}}
{"text": "module PortHamiltonianBenchmarkSystems\n\nusing LinearAlgebra, SparseArrays\n\ninclude(\"IOFormats.jl\")\ninclude(\"Downloads.jl\")\n\n\"\"\"\n   `gugercin_pH_msd_chain(; n_cells=50, m=2, c_i=1.0, m_i=4.0, k_i=4.0)`\n\nThis function returns the port Hamiltonian mass-spring-damper system described in\nS. Gugercin et al.:\n      Structure-preserving tangential interpolation for model reduction of\n      port-Hamiltonian systems\n# Arguments\n- `n_cells`: The number of masses. The system dimension is `2n_cells`\n- `c_i`: The amount of damping\n- `m_i`: The weight of the masses\n- `k_i`: The stiffness of the springs\n# Outputs\nMatrices: ``J, R, Q, B``. The resulting transfer function is ``H(s) = B^\\\\mathsf{T} Q  (sI-(J-R)Q)^{-1}B``.\n\"\"\"\nfunction gugercin_pH_msd_chain(;\n    n_cells=50::Int,\n    m=2::Int,\n    c_i=1.0,\n    m_i=4.0,\n    k_i=4.0\n  )\n  n=2*n_cells;\n  # B is initialized as dense matrix. Since all results of transfer function\n  # computations will lead to dense results.\n  B=zeros(n,m);\n  [B[2*i,i]=1.0 for i in 1:m]\n  J=spzeros(n,n);\n  [J[i,i+1]=1.0 for i in 1:2:(n-1)];\n  J=J-J'\n  # Set constants.\n  R=spzeros(n,n);\n  [R[i,i]=c_i for i in 2:2:n]\n  Q=spzeros(n,n);\n  Q[1,1]=k_i\n  [Q[i,i]=2*k_i for i in 3:2:(n-1)]\n  [Q[i,i]=1/m_i for i in 2:2:n]\n  [Q[i,i+2]=-k_i for i in 1:2:(n-2)]\n  [Q[i+2,i]=-k_i for i in 1:2:(n-2)]\n  return J, R, Q, B\nend\n\n\"\"\"\n`poro_elasticity_model(;\n    n = 980,\n    rho = 1e-3,\n    alpha = 0.79,\n    M = 1/7.80e3,\n    kappanu = 633.33,\n    eta = 1e-4,\n    force_download = false\n  )`\n\nThis function returns a port-Hamiltonian model of linear poroelasticity in a\nbounded Lipschitz domain as described in\n    Altmann, Mehrmann, Unger: Port-Hamiltonian Formulations of Poroelastic\n    Network Models\n# Arguments\n- `n`: System dimension (can only be either: 320, 980, or 1805). Default = 980.\n- `rho`: density. Default = `1e-3`.\n- `alpha`: Biot-Willis fluid-solid coupling coefficient. Default = 0.79.\n- `bm`: Biot-Modulus. Default = `1/7.8e3`.\n- `kappanu`: Quotient kappa/Nu, where kappa denotes the permeability and nu denotes the fluid viscosity. Default = 633.33.\n- `eta`: artificial damping coefficient. Default = `1e-4`.\n\"\"\"\nfunction poro_elasticity_model(;\n    n = 980,\n    rho = 1e-3,\n    alpha = 0.79,\n    bm = 1/7.80e3,\n    kappanu = 633.33,\n    eta = 1e-4,\n    force_download = false\n  )\n  Y, D, M, K, Bp, Bf, A = load_poro_raw_data(\n    n=n,\n    force_download = force_download\n  )\n  Y = rho*sparse(Y)\n  D = alpha*sparse(D)\n  M = 1/bm .* sparse(M)\n  K = kappanu*sparse(K)\n  A = sparse(A)\n  Bp = Bp'\n  Bf = Bf'\n  n = size(A, 1);\n  m = size(M, 1);\n  E = [Y spzeros(n,n+m); spzeros(n,n) A spzeros(n,m); spzeros(m,n+n) M];\n  J = [spzeros(n,n) -A D';A spzeros(n,n+m); -D spzeros(m,n+m)];\n  R = [spzeros(n,2*n+m); spzeros(n,2*n+m); spzeros(m,2*n) K] + eta*I\n  B = [zeros(n,1); Bf; Bp];\n  return E, J, R, B\nend\n\nfunction load_poro_raw_data(;\n    n = 980,\n    force_download = false\n  )\n  filename = \"poro-n$n.mat\"\n  url = \"https://zenodo.org/record/5702554/files/poro-n$n.mat?download=1\"\n  if n == 980\n    md5_hash = hex(0x2961a189be7049ffe2d476b18cb1f678)\n  elseif n == 320\n    md5_hash = hex(0x97afe8c34f0e9a56bbe86d0a51b7b626)\n  elseif n == 1805\n    md5_hash = hex(0xc61f6687da9cd26cbf2d880d7d3a9ac9)\n  else\n    throw(ArgumentError(\"Model size is either 320, 980, or 1805\"))\n  end\n  download_system_data_if_required(\n    filename,\n    url,\n    md5_hash,\n    force_download = force_download\n  )\n  dd = loadMAT(get_filepath(filename))\n  return dd[\"Y\"], dd[\"D\"], dd[\"M\"], dd[\"K\"], dd[\"Bp\"], dd[\"Bf\"], dd[\"A\"]\nend\n\ninclude(\"RCLLadders.jl\")\n\nexport gugercin_pH_msd_chain, poro_elasticity_model\n\nend # module\n", "meta": {"hexsha": "aa1f94d2cf1f3d37e4a0c2f7d13ff7bd9bab5c91", "size": 3626, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PortHamiltonianBenchmarkSystems.jl", "max_stars_repo_name": "Amanibus/PortHamiltonianBenchmarkSystems", "max_stars_repo_head_hexsha": "93f70e304ebc204f7013238e642e688a6546dc0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PortHamiltonianBenchmarkSystems.jl", "max_issues_repo_name": "Amanibus/PortHamiltonianBenchmarkSystems", "max_issues_repo_head_hexsha": "93f70e304ebc204f7013238e642e688a6546dc0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-10T20:32:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-12T09:31:35.000Z", "max_forks_repo_path": "src/PortHamiltonianBenchmarkSystems.jl", "max_forks_repo_name": "Amanibus/PortHamiltonianBenchmarkSystems", "max_forks_repo_head_hexsha": "93f70e304ebc204f7013238e642e688a6546dc0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4696969697, "max_line_length": 122, "alphanum_fraction": 0.6439602868, "num_tokens": 1380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7737570182283406}}
{"text": "\"\"\"\n    struct ConvexRealSet\nConvex real set (similar to a line segment).\nParameters: lower bound, upper bound: floating point numbers\n            includelower, includeupper: boolean true or false to indicate whether\n            the set has a closed boundary (set to true) or open (set to false).\n\"\"\"\nmutable struct ConvexRealSet\n    lower::Float64\n    includelower::Bool\n    upper::Float64\n    includeupper::Bool\n    function ConvexRealSet(lo, up, incllo, inclup)\n       this = new()\n       this.upper = Float64(up)\n       this.lower = Float64(lo)\n       this.includelower = incllo\n       this.includeupper = inclup\n       this\n    end\nend\n\n\nfunction ∈(s, xelem)\n    x = Float64(xelem)\n    if(x == s.lower)\n        if(s.includelower)\n            return true\n        else\n            return false\n        end\n    elseif(x == s.upper)\n        if(s.includeupper)\n            return true\n        else\n            return false\n        end\n    end\n    s.lower < x && x < s.upper\nend\n\n\n⋃(aset, bset, x) = (∈(aset, x) || ∈(bset, x))\n\n⋂(aset, bset, x) = (∈(aset, x) && ∈(bset, x))\n\n-(aset, bset, x) = (∈(aset, x) && !∈(bset, x))\n\nisempty(s::ConvexRealSet) = (s.lower > s.upper) ||\n                           ((s.lower == s.upper) && !s.includeupper && !s.includelower)\n\n\nconst s1 = ConvexRealSet(0.0, 1.0, false, true)\nconst s2 = ConvexRealSet(0.0, 2.0, true, false)\nconst s3 = ConvexRealSet(1.0, 2.0, false, true)\nconst s4 = ConvexRealSet(0.0, 3.0, true, false)\nconst s5 = ConvexRealSet(0.0, 1.0, false, false)\nconst s6 = ConvexRealSet(0.0, 1.0, true, true)\nconst sempty = ConvexRealSet(0.0, -1.0, true, true)\nconst testlist = [0, 1, 2]\n\n\nfunction testconvexrealset()\n    for i in testlist\n        println(\"Testing with x = $i.\\nResults:\")\n        println(\"    (0, 1] ∪ [0, 2): $(⋃(s1, s2, i))\")\n        println(\"    [0, 2) ∩ (1, 2]: $(⋂(s2, s3, i))\")\n        println(\"    [0, 3) − (0, 1): $(-(s4, s5, i))\")\n        println(\"    [0, 3) − [0, 1]: $(-(s4, s6, i))\\n\")\n    end\n    print(\"The set sempty is \")\n    println(isempty(sempty) ? \"empty.\" : \"not empty.\")\nend\n\n\ntestconvexrealset()\n", "meta": {"hexsha": "ba779dc6aebd1582d8db808cc2fe944ae4ef5d93", "size": 2080, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/set-of-real-numbers.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/set-of-real-numbers.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/set-of-real-numbers.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.012987013, "max_line_length": 87, "alphanum_fraction": 0.5610576923, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.8705972667296309, "lm_q1q2_score": 0.7737509763964574}}
{"text": "using LinearAlgebra\n\n# order 4\nh = [\n  2.1259737557798e-01,\n  1.0260290400758e+00,\n  1.0775123588954e+00,\n  9.8607273802835e-01,\n  1, 1, 1, 1\n  ]\ne = [1//1, 0, 0, 0, 0, 0, 0, 0]\nH = Diagonal(h)\n\nq1 = [0,\n  6.5605279837843e-01,\n  -1.9875859409017e-01,\n  4.2705795711740e-02,\n  0, 0, 0, 0]'\nq2 = [-q1[2], 0,\n  8.1236966439895e-01,\n  -1.5631686602052e-01,\n  0, 0, 0, 0]'\nq3 = [-q1[3], -q2[3], 0,\n  6.9694440364211e-01,\n  -1//12, 0, 0, 0]'\nq4 = [-q1[4], -q2[4], -q3[4], 0,\n  2//3, -1//12, 0, 0]'\nq5 = [-q1[5] -q2[5] -q3[5] -q4[5] 0 2//3 -1//12 0]\nq6 = [0 0 0 1//12 -2//3 0 2//3 -1//12]\nq7 = [0 0 0 0 1//12 -2//3 0 2//3]\nq8 = [0 0 0 0 0 1//12 -2//3 0]\nQ = vcat(q1, q2, q3, q4, q5, q6, q7, q8)\n\nD1 = H \\ (Q - 1//2*e*e'); display(D1)\n\n\n\n# order 6\nh = [\n  1.3030223027124e-01,\n  6.8851501587715e-01,\n  9.5166202564389e-01,\n  9.9103890475697e-01,\n  1.0028757074552e+00,\n  9.9950151111941e-01,\n  1, 1, 1\n  ]\ne = [1//1, 0, 0, 0, 0, 0, 0, 0, 0]\nH = Diagonal(h)\n\nq1 = [0,\n  6.6042071945824e-01,\n  -2.2104152954203e-01,\n  7.6243679810093e-02,\n  -1.7298206716724e-02,\n  1.6753369904210e-03,\n  0, 0, 0]'\nq2 = [-q1[2], 0,\n  8.7352798702787e-01,\n  -2.6581719253084e-01,\n  5.7458484948314e-02,\n  -4.7485599871040e-03,\n  0, 0, 0]'\nq3 = [-q1[3], -q2[3], 0,\n  8.1707122038457e-01,\n  -1.8881125503769e-01,\n  2.4226492138960e-02,\n  0, 0, 0]'\nq4 = [-q1[4], -q2[4], -q3[4], 0,\n  7.6798636652679e-01,\n  -1.5715532552963e-01,\n  1//60, 0, 0]'\nq5 = [-q1[5], -q2[5], -q3[5], -q4[5], 0,\n  7.5266872305402e-01,\n  -3//20, 1//60, 0]'\nq6 = [-q1[6], -q2[6], -q3[6], -q4[6], -q5[6], 0,\n  3//4, -3//20, 1//60]'\nq7 = [0 0 0 -1//60 3//20 -3//4 0 3//4 -3//20]\nq8 = [0 0 0 0 -1//60 3//20 -3//4 0 3//4]\nq9 = [0 0 0 0 0 -1//60 3//20 -3//4 0]\nQ = vcat(q1, q2, q3, q4, q5, q6, q7, q8, q9)\n\nD1 = H \\ (Q - 1//2*e*e'); display(D1)\n\n\n\n# order 8\nh = [\n  1.0758368078310e-01,\n  6.1909685107891e-01,\n  9.6971176519117e-01,\n  1.1023441350947e+00,\n  1.0244688965833e+00,\n  9.9533550116831e-01,\n  1.0008236941028e+00,\n  9.9992060631812e-01,\n  1, 1, 1, 1]\ne = [1//1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nH = Diagonal(h)\n\nq1 = [0,\n  6.7284756079369e-01,\n  -2.5969732837062e-01,\n  1.3519390385721e-01,\n  -6.9678474730984e-02,\n  2.6434024071371e-02,\n  -5.5992311465618e-03,\n  4.9954552590464e-04,\n  0, 0, 0, 0]'\nq2 = [-q1[2], 0,\n  9.4074021172233e-01,\n  -4.0511642426516e-01,\n  1.9369192209331e-01,\n  -6.8638079843479e-02,\n  1.3146457241484e-02,\n  -9.7652615479254e-04,\n  0, 0, 0, 0]'\nq3 = [-q1[3], -q2[3], 0,\n  9.4316393361096e-01,\n  -3.5728039257451e-01,\n  1.1266686855013e-01,\n  -1.8334941452280e-02,\n  8.2741521740941e-04,\n  0, 0, 0, 0]'\nq4 = [-q1[4], -q2[4], -q3[4], 0,\n  8.7694387866575e-01,\n  -2.4698058719506e-01,\n  4.7291642094198e-02,\n  -4.0135203618880e-03,\n  0, 0, 0, 0]'\nq5 = [-q1[5], -q2[5], -q3[5], -q4[5], 0,\n  8.1123946853807e-01,\n  -2.0267150541446e-01,\n  3.8680398901392e-02,\n  -3.5714285714286e-03,\n  0, 0, 0]'\nq6 = [-q1[6], -q2[6], -q3[6], -q4[6], -q5[6], 0,\n  8.0108544742793e-01,\n  -2.0088756283071e-01,\n  3.8095238095238e-02,\n  -3.5714285714286e-03,\n  0, 0]'\nq7 = [-q1[7], -q2[7], -q3[7], -q4[7], -q5[7], -q6[7], 0,\n  8.0039405922650e-01,\n  -1//5, 4//105, -1//280, 0]'\nq8 = [-q1[8], -q2[8], -q3[8], -q4[8], -q5[8], -q6[8], -q7[8], 0,\n  4//5, -1//5, 4//105, -1//280]'\nq9 = [0 0 0 0 1//280 -4//105 1//5 -4//5 0 4//5 -1//5 4//105]\nq10 = [0 0 0 0 0 1//280 -4//105 1//5 -4//5 0 4//5 -1//5]\nq11 = [0 0 0 0 0 0 1//280 -4//105 1//5 -4//5 0 4//5]\nq12 = [0 0 0 0 0 0 0 1//280 -4//105 1//5 -4//5 0]\nQ = vcat(q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12)\n\nD1 = H \\ (Q - 1//2*e*e'); display(D1)\n", "meta": {"hexsha": "d34d6664d8289cf463bcb4157f97c47af282a3c0", "size": 3546, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dev/MattssonAlmquistVanDerWeide2018Accurate_dev.jl", "max_stars_repo_name": "ranocha/SummationByPartsOperators.jl", "max_stars_repo_head_hexsha": "2f6ec738e7387553024cd82f4abff9a38fcefc96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2018-12-06T19:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T19:17:47.000Z", "max_issues_repo_path": "dev/MattssonAlmquistVanDerWeide2018Accurate_dev.jl", "max_issues_repo_name": "ranocha/SummationByPartsOperators.jl", "max_issues_repo_head_hexsha": "2f6ec738e7387553024cd82f4abff9a38fcefc96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2017-12-17T12:07:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T14:10:41.000Z", "max_forks_repo_path": "dev/MattssonAlmquistVanDerWeide2018Accurate_dev.jl", "max_forks_repo_name": "ranocha/SummationByPartsOperators.jl", "max_forks_repo_head_hexsha": "2f6ec738e7387553024cd82f4abff9a38fcefc96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:01:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:01:43.000Z", "avg_line_length": 22.8774193548, "max_line_length": 64, "alphanum_fraction": 0.5476593345, "num_tokens": 2257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632329799586, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.773738506667924}}
{"text": "using Roots, EngEconomics\n\n# Given\nA_InitCost = -10000\nA_AnnualSavings = 3000\nB_InitCost = -13500\nB_AnnualSavings = 3000\nB_AnnualSavingsGradient = 500\nMARR = 0.06\nN = 5\n\n# Choose\nΔInitCost = B_InitCost - A_InitCost\nΔAnnualCost(x) = B_AnnualSavings + B_AnnualSavingsGradient * singlePaymentPresentWorthArithmetic(x, N) - A_AnnualSavings\nΔIRR(x) = ΔInitCost + ΔAnnualCost(x)\nΔIRR_ans = find_zero(ΔIRR, 0.05)\n\nprintln(\"ΔIRR > MARR ==> Alternative B is better\")\n", "meta": {"hexsha": "27fd4034059e5a7cf8020814a6b0a232b6e1c72d", "size": 458, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/examples/irr_3.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/examples/irr_3.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/examples/irr_3.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1052631579, "max_line_length": 120, "alphanum_fraction": 0.768558952, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474181553805, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7737216020016238}}
{"text": "#=\nBy starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.\n\n3\n7 4\n2 4 6\n8 5 9 3\n\nThat is, 3 + 7 + 4 + 9 = 23.\n\nFind the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows.\n\nNOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are 2^99 altogether! If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)\n=#\n#a =\n\nfunction calc()\n  lines = readlines(open(dirname(@__FILE__()) * \"/../Resources/p67.txt\"))\n  arr = map(x -> [parse(Int64, s) for s = split(strip(x), ',')], lines)\n  result = Array[]\n  push!(result, arr[length(arr)])\n  for row in reverse(1:length(arr)-1)\n    nextrow = Int64[]\n    for column in 1:length(arr[row])\n      lowleft = last(result)[column]\n      lowright = last(result)[column+1]\n      center = arr[row][column]\n      push!(nextrow, max(center+lowleft, center+lowright))\n    end\n    push!(result, nextrow)\n  end\n  last(result)[1]\nend\n@time println(calc())\n", "meta": {"hexsha": "f16c573d547dd8f4621050045a4be7d9d9cc2dbe", "size": 1248, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p67.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p67.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p67.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 35.6571428571, "max_line_length": 316, "alphanum_fraction": 0.6866987179, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7737164534726079}}
{"text": "module hw1_4\n\nusing LinearAlgebra, PlotlyJS, ORCA\n\nexport total_manuever, plot_maneuver\n\nfunction oe_to_rθh(oe::Vector,μ::Real) :: Vector\n\n  a,e,i,Ω,ω,ν = oe\n  return [a*(1-e^2)/(1+e*cos(ν)),\n  0,\n  0,\n  (μ/sqrt(μ*a*(1-e^2)))*e*sin(ν),\n  (μ/sqrt(μ*a*(1-e^2)))*(1+e*cos(ν)),\n  0]\n\nend\n\nfunction rθh_to_xyz(rθh_vec::Vector,oe::Vector)\n\n  a,e,i,Ω,ω,ν = oe\n  θ = ω+ν\n  cΩ,sΩ,ci,si,cθ,sθ = cos(Ω),sin(Ω),cos(i),sin(i),cos(θ),sin(θ)\n  DCM = [cΩ*cθ-sΩ*ci*sθ -cΩ*sθ-sΩ*ci*cθ sΩ*si;\n  sΩ*cθ+cΩ*ci*sθ -sΩ*sθ+cΩ*ci*cθ -cΩ*si;\n  si*sθ si*cθ ci]\n  DCM = kron(Matrix(I,2,2),DCM)\n  return DCM*rθh_vec\n\nend\n\nfunction oe_to_xyz(oe::Vector,μ::Real)\n\n  return rθh_to_xyz(oe_to_rθh(oe,μ),oe)\n\nend\n\nfunction xyz_to_oe(cart_vec::Vector,μ::Real)\n\n  r_xyz, v_xyz = cart_vec[1:3],cart_vec[4:6]\n  r = norm(r_xyz)\n  h_xyz = cross(r_xyz,v_xyz) #km^2/s\n  h = norm(h_xyz) #km^2/s\n  ξ = dot(v_xyz,v_xyz)/2 - μ/r #km^2 s^-2\n  a = -μ/(2ξ) #km\n  e = sqrt(1 + (2h^2*ξ)/μ^2)\n  e_xyz = cross(v_xyz,h_xyz)/μ - r_xyz/r\n  i = acos(h_xyz[3]/h) #rad\n  n_xyz = cross([0,0,1],h_xyz)\n  Ω = acos(dot(n_xyz,[1,0,0])/norm(n_xyz))\n  ω = acos((dot(n_xyz,e_xyz)/(norm(n_xyz)*e)))\n  ν = acos((dot(r_xyz,e_xyz))/(r*norm(e_xyz)))\n  Ω = dot(n_xyz,[0,1,0]) > 0. ? Ω : -Ω\n  ω = dot(e_xyz,[0,0,1]) > 0. ? ω : -ω\n  ν = dot(r_xyz,v_xyz) > 0. ? ν : -ν\n  return [a,e,i,Ω,ω,ν]\n\nend\n\nfunction total_manuever(r1::Float64, \n                        r2::Float64,\n                        i1::Float64, \n                        i2::Float64, \n                        i3::Float64, \n                        i4::Float64, \n                        μ::Float64)\n  if i2 > i3\n    return Inf\n  else\n    a1 = r1\n    a2 = (r1+r2)/2\n    e1 = 0\n    e2 = (r2-r1)/(r2+r1)\n    v1_pre = oe_to_xyz([a1, 0., i1, 0., 0., 0.], μ)[4:6]\n    v1_post = oe_to_xyz([a2, e2, i2, 0., 0., 0.], μ)[4:6]\n    v2_pre = oe_to_xyz([a2, e2, i2, 0., 0., π], μ)[4:6]\n    v2_post = oe_to_xyz([a2, e2, i3, 0., 0., π], μ)[4:6]\n    v3_pre = oe_to_xyz([a2, e2, i3, 0., 0., 0.], μ)[4:6]\n    v3_post = oe_to_xyz([a1, e1, i4, 0., 0., 0.], μ)[4:6]\n    Δv1 = norm(v1_post-v1_pre)\n    Δv2 = norm(v2_post-v2_pre)\n    Δv3 = norm(v3_post-v3_pre)\n    return Δv1 + Δv2 + Δv3\n  end\nend\n\nfunction plot_maneuver(r1::Float64, r2::Float64, Δ_i::Float64,  μ::Float64, lim::Float64)\n  N = 200\n  node1_inc = node3_inc = collect(range(0, length=N, stop=lim))\n  z = zeros(Float64, N, N)\n  base = zeros(Float64, N, N, 2)\n  for i in 1:N\n    for j in 1:N\n      z[i,j] = total_manuever(r1, r2, 0., node1_inc[i], Δ_i-node3_inc[j], Δ_i, μ) \n      base[i,j,:] = [node1_inc[i], node3_inc[j]]\n    end\n  end\n\n  data = contour(;z=z, x=node1_inc, y=node3_inc, \n                 name=\"ΔV\", contours=attr(size=0.2),\n                 colorbar=attr(title=attr(text=\"ΔV (km/s)\")))\n  if lim < Δ_i\n    layout = Layout(\n      ;title=\"Total ΔV vs. Δi₁ and Δi₃ for a 90° Bi-Elliptic Transfer (zoomed)\",\n      width=920,\n      height=920,\n      xaxis=attr(title=attr(text=\"Δi₁ (radians)\")),\n      yaxis=attr(title=attr(text=\"Δi₃ (radians)\")))\n    p = Plot(data, layout)\n    savefig(p::Union{Plot,PlotlyJS.SyncPlot}, \"hw1_4_zoomed.png\")\n  else\n    layout = Layout(\n      ;title=\"Total ΔV vs. Δi₁ and Δi₃ for a 90° Bi-Elliptic Transfer\",\n      width=920,\n      height=920,\n      xaxis=attr(title=attr(text=\"Δi₁ (radians)\")),\n      yaxis=attr(title=attr(text=\"Δi₃ (radians)\")))\n    p = Plot(data, layout)\n    savefig(p::Union{Plot,PlotlyJS.SyncPlot}, \"hw1_4.png\")\n  end\n  display(plot(p))\n\n  min, position = findmin(z)\n  angles = base[position, :]\n  println(\"Found min: \", min)\n  println(\"At: \", 180/π*angles[1], \"°, \", 180/π*angles[2], \"°\")\n  while true\n    println(\"Ctrl+C to close\")\n    sleep(10)\n  end\nend\n\nend\n", "meta": {"hexsha": "b9d4cf96c370cc9c6c8874ebfb9efedfbefc7ec1", "size": 3652, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "hw1/prob4.jl", "max_stars_repo_name": "rconnorjohnstone/optimal_trajectories", "max_stars_repo_head_hexsha": "fb2522d0729516046f782fbed6a34f92b8bf8b9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw1/prob4.jl", "max_issues_repo_name": "rconnorjohnstone/optimal_trajectories", "max_issues_repo_head_hexsha": "fb2522d0729516046f782fbed6a34f92b8bf8b9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw1/prob4.jl", "max_forks_repo_name": "rconnorjohnstone/optimal_trajectories", "max_forks_repo_head_hexsha": "fb2522d0729516046f782fbed6a34f92b8bf8b9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2537313433, "max_line_length": 89, "alphanum_fraction": 0.5596933187, "num_tokens": 1581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.773665895151393}}
{"text": "\"\"\"\n    hyperbola2(x, s1, s2, Δy, xoff=0.0, yoff=0.0)\n\nOne branch of a hyperbola as a function of x given by\n\n- s1: asymptote slope for x<0\n- s2: asymptote slope for x>0\n- Δy: absolute value of abcissa at x=0\n- optionally shift the origin by xoff, yoff\n\nRef https://maurow.bitbucket.io/docs/hyperbola.html\n\"\"\"\nfunction hyperbola(x, s1, s2, Δy, xoff=0.0, yoff=0.0)\n    x = x-xoff\n    # Deal with degenerate cases and select the right branch of the hyperbola\n    if Δy==0 # return two lines\n        i1 = x.<0\n        i2 = x.>=0\n        return vcat(s1*x[i1], s2*x[i2]) + yoff\n    elseif s1==s2 # return one line\n        branch = 0\n    elseif s1>s2\n        branch = -1\n        s1,s2 = s2,s1\n    else\n        branch = +1\n    end\n    B = (s1+s2)/2\n    C = -Δy^2\n    D = - (s2-s1)^2/4\n    return B*x + branch * sqrt(-D*x.^2-C) + yoff\nend\n\n\"\"\"\n    hyperbola01(x, Δy, xoff=0.0, yoff=0.0)\n\nA hyperbola with asymptotes y=0 for x<0 and y=x for x>0, and\nabcissa Δy.  Its origin can be moved with xoff and yoff.\n\"\"\"\nfunction hyperbola01(x, Δy, xoff=0.0, yoff=0.0)\n    x = x-xoff\n    B = 1/2\n    C = -Δy^2\n    D = -1/4\n    return B*x + sqrt(-D*x^2-C) + yoff\nend\n\n\"\"\"\n    max_smooth(x0, x, delta)\n\nto replace\n\n    max(x0, x)\n\nfor a fixed x0 and varying x.  `delta` gives the difference:\ndelta = max_smooth(x0,x0,delta)-x0,\nwhich is the maximal difference for any x.\n\nNote, all returned values >= x0 (== for delta==0).\n\"\"\"\nmax_smooth(x0, x, delta) =\n    delta==0 ? max(x0,x) : hyperbola01(x, delta, x0, x0)\n\"\"\"\n    min_smooth(x0, x, delta)\n\nsee max_smooth\n\"\"\"\nmin_smooth(x0, x, delta) = -max_smooth(-x0, -x, delta)\n\n\n####\n# Sigmoid smoothing\n\n\"\"\"\n    sigmoid(x, x0, w)\n\nSmooth transition function from 0 to 1.  At x0+w its value is about 0.99,\nat x0-w about 0.01.\n\"\"\"\nsigmoid(x, x0, w) = 1/(1+exp(-(x-x0)/w*5))\n\n\n\"\"\"\n    fn_cap(x0, width, fn, x, args...)\n\nInstead of\n\n    max(fn(x0,args...), fn(x, args...))\n\nwhere at x0+/-width the value is to 1% correct.\n\nThere is also the not recommended:\n\n    fn_cap_(f0, width, fn, args...)\n\nwhere at f0+/-width the value is to 1% correct.\n\"\"\"\nfunction fn_cap(x0, width, fn, x, args...)\n    ff = fn(x, args...)\n    f0 = fn(x0, args...)\n    si = sigmoid(x, x0, width)\n    f0*(1-si) + ff*si\nend\nfunction fn_cap_(f0, width, fn, args...)\n    ff = fn.(args...)\n    si = sigmoid.(ff, f0, width)\n    f0.*(1-si) + ff.*si\nend\n\n\"\"\"\n    val_cap(x0,x,width)\ninstead of\n    max(x0, x)\n\nwith the return value within 1% for x=x0+/-width.\n\"\"\"\nfunction val_cap(x0,x,width)\n    si = sigmoid(x,x0,width)\n    x0*(1-si)+x*si\nend\n", "meta": {"hexsha": "cb556feb9bc6a467ddd6babab958468185b7e678", "size": 2530, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/smoothing-functions.jl", "max_stars_repo_name": "mauro3/VAWTools.jl", "max_stars_repo_head_hexsha": "496a184bae8782091ab09cd32d0efe69047e92b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/smoothing-functions.jl", "max_issues_repo_name": "mauro3/VAWTools.jl", "max_issues_repo_head_hexsha": "496a184bae8782091ab09cd32d0efe69047e92b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/smoothing-functions.jl", "max_forks_repo_name": "mauro3/VAWTools.jl", "max_forks_repo_head_hexsha": "496a184bae8782091ab09cd32d0efe69047e92b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-07-15T08:03:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:08:15.000Z", "avg_line_length": 20.9090909091, "max_line_length": 77, "alphanum_fraction": 0.5916996047, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7736658929590325}}
{"text": "cd(@__DIR__) # changes the directory to the current directory, the default I guess is the HOME\nusing Pkg; Pkg.activate(\".\"); Pkg.instantiate()\n\nusing OrdinaryDiffEq, ModelingToolkit, DiffEqOperators, DomainSets\n\n@parameters t, x\n@variables u(..)\nDt = Differential(t)\nDx = Differential(x)\nDxx = Differential(x)^2\n\n# PDE\neq  = Dt(u(t,x)) + u(t,x)*Dx(u(t,x)) ~ 0 #- (0.01/pi)*Dxx(u(t,x))\n\n# Initial and boundary conditions\nbcs = [u(0,x) ~ -sin(pi*x),\n       u(t,-1) ~ 0.,\n       u(t,1) ~ 0.,\n       u(t,-1) ~ u(t,1)]\n\n# Space and time domains\ndomains = [t ∈ Interval(0.0,1.0),\n           x ∈ Interval(-1.0,1.0)]\n# Discretization\ndx = 0.1\n\n# PDE system - ModelingToolkit\n@named pdesys = PDESystem(eq,bcs,domains,[t,x],[u(t,x)])\n\norder = 2\ndiscretization = MOLFiniteDifference([x=>dx],t;centered_order=order)\n\n# Convert the PDE problem into an ODE problem\nprob = discretize(pdesys,discretization)\n\n# Solve ODE problem\nusing OrdinaryDiffEq\nsol = solve(prob,Vern9(),saveat=0.1)\n\n#= # Plot results and compare with exact solution\nx = (0:dx:1)[2:end-1]\nt = sol.t\n\nusing Plots\nplt = plot()\n\nfor i in 1:length(t)\n    plot!(x,sol.u[i],label=\"Numerical, t=$(t[i])\")\nend\ndisplay(plt)\nsavefig(\"plot.png\") =#", "meta": {"hexsha": "a74adda86f3cb248f412b591d2388640924d63e3", "size": 1192, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "burgers/burgersfd.jl", "max_stars_repo_name": "carlos-hernani/julia101", "max_stars_repo_head_hexsha": "3c5c877cf585ddab5674aa839880029db31387b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "burgers/burgersfd.jl", "max_issues_repo_name": "carlos-hernani/julia101", "max_issues_repo_head_hexsha": "3c5c877cf585ddab5674aa839880029db31387b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "burgers/burgersfd.jl", "max_forks_repo_name": "carlos-hernani/julia101", "max_forks_repo_head_hexsha": "3c5c877cf585ddab5674aa839880029db31387b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3725490196, "max_line_length": 94, "alphanum_fraction": 0.6535234899, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.773665890470189}}
{"text": "# indicator of a simplex\n\nexport IndSimplex\n\n\"\"\"\n**Indicator of a simplex**\n\n    IndSimplex(a=1.0)\n\nReturns the indicator of the set\n```math\nS = \\\\left\\\\{ x : x \\\\geq 0, \\\\sum_i x_i = a \\\\right\\\\}.\n```\nBy default `a=1.0`, therefore ``S`` is the probability simplex.\n\"\"\"\nstruct IndSimplex{R <: Real} <: ProximableFunction\n    a::R\n    function IndSimplex{R}(a::R) where {R <: Real}\n        if a <= 0\n            error(\"parameter a must be positive\")\n        else\n            new(a)\n        end\n    end\nend\n\nis_convex(f::IndSimplex) = true\nis_set(f::IndSimplex) = true\n\nIndSimplex(a::R=1.0) where {R <: Real} = IndSimplex{R}(a)\n\nfunction (f::IndSimplex)(x::AbstractArray{R}) where R <: Real\n    if all(x .>= 0) && sum(x) ≈ f.a\n        return R(0)\n    end\n    return R(Inf)\nend\n\nfunction simplex_proj_condat!(y::AbstractArray{R}, a, x::AbstractArray{R}) where R\n    # Implements algorithm proposed in:\n    # Condat, L. \"Fast projection onto the simplex and the l1 ball\",\n    # Mathematical Programming, 158:575–585, 2016.\n    v = [x[1]]\n    v_tilde = R[]\n    rho = x[1] - a\n    N = length(x)\n    for k in 2:N\n        if x[k] > rho\n            rho += (x[k] - rho) / (length(v) + 1)\n            if rho > x[k] - a\n                push!(v, x[k])\n            else\n                append!(v_tilde, v)\n                v = [x[k]]\n                rho = x[k] - a\n            end\n        end\n    end\n    for z in v_tilde\n        if z > rho\n            push!(v, z)\n            rho += (z - rho) / length(v)\n        end\n    end\n    v_changed = true\n    while v_changed == true\n        v_changed = false\n        k = 1\n        while k <= length(v)\n            z = v[k]\n            if z <= rho\n                deleteat!(v, k)\n                v_changed = true\n                rho += (rho - z) / length(v)\n            else\n                k = k + 1\n            end\n        end\n    end\n    y .= max.(x .- rho, R(0))\nend\n\nfunction prox!(y::AbstractArray{R}, f::IndSimplex, x::AbstractArray{R}, _::R=R(1)) where R <: Real\n    simplex_proj_condat!(y, f.a, x)\n    return R(0)\nend\n\nfun_name(f::IndSimplex) = \"indicator of the probability simplex\"\nfun_dom(f::IndSimplex) = \"AbstractArray{Real}\"\nfun_expr(f::IndSimplex) = \"x ↦ 0 if x ⩾ 0 and sum(x) = a, +∞ otherwise\"\nfun_params(f::IndSimplex) = \"a = $(f.a)\"\n\nfunction prox_naive(f::IndSimplex, x::AbstractArray{R}, _::R=R(1)) where R <: Real\n    low = minimum(x)\n    upp = maximum(x)\n    v = x\n    s = Inf\n    for i = 1:100\n        if abs(s)/f.a ≈ 0\n            break\n        end\n        alpha = (low+upp)/2\n        v = max.(x .- alpha, R(0))\n        s = sum(v) - f.a\n        if s <= 0\n            upp = alpha\n        else\n            low = alpha\n        end\n    end\n    return v, R(0)\nend\n", "meta": {"hexsha": "3e15ead11f0764214aee344de3f6081bd48c2f86", "size": 2711, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indSimplex.jl", "max_stars_repo_name": "fabian-sp/ProximalOperators.jl", "max_stars_repo_head_hexsha": "c9a250f8836e41450bada594ed23baa22dc8e928", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2016-10-29T12:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:11:52.000Z", "max_issues_repo_path": "src/functions/indSimplex.jl", "max_issues_repo_name": "kul-forbes/ProximalOperators.jl", "max_issues_repo_head_hexsha": "fcd3d987f6af7d701cd32c61e6c14594baa6289e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2016-10-26T16:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T20:38:48.000Z", "max_forks_repo_path": "src/functions/indSimplex.jl", "max_forks_repo_name": "fabian-sp/ProximalOperators.jl", "max_forks_repo_head_hexsha": "c9a250f8836e41450bada594ed23baa22dc8e928", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T10:40:24.000Z", "avg_line_length": 23.9911504425, "max_line_length": 98, "alphanum_fraction": 0.4987089635, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7736658893868308}}
{"text": "# Examples from Luc Jaulin, Michel Kieffer, Olivier Didrit and Eric Walter - Applied Interval Analysis\n\nusing IntervalArithmetic, IntervalRootFinding, StaticArrays\n\nA = [4..5 -1..1 1.5..2.5; -0.5..0.5 -7.. -5 1..2; -1.5.. -0.5 -0.7.. -0.5 2..3]\nsA = SMatrix{3}{3}(A)\nmA = MMatrix{3}{3}(A)\n\nb = [3..4, 0..2, 3..4]\nsb = SVector{3}(b)\nmb = MVector{3}(b)\n\np = fill(-1e16..1e16, 3)\n\nrts = gauss_seidel_interval!(p, A, b, precondition=true) # Gauss-Seidel Method; precondition=true by default\nrts = gauss_seidel_interval!(p, sA, sb, precondition=true) # Gauss-Seidel Method; precondition=true by default\nrts = gauss_seidel_interval!(p, mA, mb, precondition=true) # Gauss-Seidel Method; precondition=true by default\n\nrts = gauss_seidel_interval(A, b, precondition=true) # Gauss-Seidel Method; precondition=true by default\nrts = gauss_seidel_interval(sA, sb, precondition=true) # Gauss-Seidel Method; precondition=true by default\nrts = gauss_seidel_interval(mA, mb, precondition=true) # Gauss-Seidel Method; precondition=true by default\n\nrts = gauss_seidel_contractor!(p, A, b, precondition=true) # Gauss-Seidel Method (Vectorized); precondition=true by default\nrts = gauss_seidel_contractor!(p, sA, sb, precondition=true) # Gauss-Seidel Method (Vectorized); precondition=true by default\nrts = gauss_seidel_contractor!(p, mA, mb, precondition=true) # Gauss-Seidel Method (Vectorized); precondition=true by default\n\nrts = gauss_seidel_contractor(A, b, precondition=true) # Gauss-Seidel Method (Vectorized); precondition=true by default\nrts = gauss_seidel_contractor(sA, sb, precondition=true) # Gauss-Seidel Method (Vectorized); precondition=true by default\nrts = gauss_seidel_contractor(mA, mb, precondition=true) # Gauss-Seidel Method (Vectorized); precondition=true by default\n\nrts = gauss_elimination_interval!(p, A, b, precondition=true) # Gaussian Elimination; precondition=true by default\nrts = gauss_elimination_interval(A, b, precondition=true) # Gaussian Elimination; precondition=true by default\n", "meta": {"hexsha": "918bcb69065e320e4bb1eca50966b632f2b9cd75", "size": 1998, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/linear_eq.jl", "max_stars_repo_name": "ericphanson/IntervalRootFinding.jl", "max_stars_repo_head_hexsha": "21be6924ec971ccc0c61a5f1e171f3b8f35c42c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 109, "max_stars_repo_stars_event_min_datetime": "2017-04-18T21:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T18:49:59.000Z", "max_issues_repo_path": "examples/linear_eq.jl", "max_issues_repo_name": "ericphanson/IntervalRootFinding.jl", "max_issues_repo_head_hexsha": "21be6924ec971ccc0c61a5f1e171f3b8f35c42c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 166, "max_issues_repo_issues_event_min_datetime": "2017-04-16T05:11:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-30T23:06:12.000Z", "max_forks_repo_path": "examples/linear_eq.jl", "max_forks_repo_name": "ericphanson/IntervalRootFinding.jl", "max_forks_repo_head_hexsha": "21be6924ec971ccc0c61a5f1e171f3b8f35c42c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2017-04-18T13:43:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T17:52:34.000Z", "avg_line_length": 60.5454545455, "max_line_length": 125, "alphanum_fraction": 0.7587587588, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787997, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7736658888451511}}
{"text": "#=\nFunctions to compute quadratic sums\n\n@author : Spencer Lyon <spencer.lyon@nyu.edu>\n\n@date : 2014-08-19\n=#\n\n\"\"\"\nComputes the expected discounted quadratic sum\n\n    q(x_0) = E sum_{t=0}^{infty} beta^t x_t' H x_t\n\n\nHere {x_t} is the VAR process x_{t+1} = A x_t + C w_t with {w_t}\nstandard normal and x_0 the initial condition.\n\n##### Arguments\n- `A::Union{Float64, Matrix{Float64}}` The n x n matrix described above (scalar)\nif n = 1\n- `C::Union{Float64, Matrix{Float64}}` The n x n matrix described above (scalar)\nif n = 1\n- `H::Union{Float64, Matrix{Float64}}` The n x n matrix described above (scalar)\nif n = 1\n- `beta::Float64`: Discount factor in (0, 1)\n- `x_0::Union{Float64, Vector{Float64}}` The initial condtion. A conformable\narray (of length n) or a scalar if n=1\n\n##### Returns\n\n- `q0::Float64` : Represents the value q(x_0)\n\n##### Notes\n\nThe formula for computing q(x_0) is q(x_0) = x_0' Q x_0 + v where\n\n- Q is the solution to Q = H + beta A' Q A and\n- v = \\trace(C' Q C) \\beta / (1 - \\beta)\n\n\"\"\"\nfunction var_quadratic_sum(A::ScalarOrArray, C::ScalarOrArray, H::ScalarOrArray,\n                           bet::Real, x0::ScalarOrArray)\n    n = size(A, 1)\n\n    # coerce shapes\n    A = reshape([A;], n, n)\n    C = reshape([C;], n, n)\n    H = reshape([H;], n, n)\n    x0 = reshape([x0;], n)\n\n    # solve system\n    Q = solve_discrete_lyapunov(sqrt(bet) .* A', H)\n    cq = C'*Q*C\n    v = trace(cq) * bet / (1 - bet)\n    q0 = x0'*Q*x0 + v\n    return q0[1]\nend\n\n\"\"\"\nComputes the quadratic sum\n\n    V = sum_{j=0}^{infty} A^j B A^{j'}\n\nV is computed by solving the corresponding discrete lyapunov equation using the\ndoubling algorithm.  See the documentation of `solve_discrete_lyapunov` for\nmore information.\n\n##### Arguments\n\n- `A::Matrix{Float64}` : An n x n matrix as described above.  We assume in order\nfor convergence that the eigenvalues of A have moduli bounded by unity\n- `B::Matrix{Float64}` : An n x n matrix as described above.  We assume in order\nfor convergence that the eigenvalues of B have moduli bounded by unity\n- `max_it::Int(50)` : Maximum number of iterations\n\n##### Returns\n\n- `gamma1::Matrix{Float64}` : Represents the value V\n\n\"\"\"\nfunction m_quadratic_sum(A::Matrix, B::Matrix; max_it=50)\n    solve_discrete_lyapunov(A, B, max_it)\nend\n", "meta": {"hexsha": "9031c18c33c6d4caa4d92892da670bf8d7cb650d", "size": 2265, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/quadsums.jl", "max_stars_repo_name": "ranjanan/QuantEcon.jl", "max_stars_repo_head_hexsha": "fe2be6b95b517414b810089c49f295746d93f3eb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-07T16:49:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-07T16:49:55.000Z", "max_issues_repo_path": "src/quadsums.jl", "max_issues_repo_name": "ranjanan/QuantEcon.jl", "max_issues_repo_head_hexsha": "fe2be6b95b517414b810089c49f295746d93f3eb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/quadsums.jl", "max_forks_repo_name": "ranjanan/QuantEcon.jl", "max_forks_repo_head_hexsha": "fe2be6b95b517414b810089c49f295746d93f3eb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9642857143, "max_line_length": 80, "alphanum_fraction": 0.6587196468, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7736658827841061}}
{"text": "\"\"\"\n    prlyap(A, C) -> X\n\nSolve the reverse-time periodic discrete-time Lyapunov equation\n\n    A'σXA + C = X\n\nwhere `σ` is the forward shift operator `σX(i) = X(i+1)`.                 \n\nFor the periodic matrices `A` and `C` with the same sampling period and commensurate periods, \nthe periodic matrix `X` is determined, whose period is automatically set to the\nthe least common period of `A` and `C`.  \n\"\"\"\nfunction prlyap(A::PeriodicArray, C::PeriodicArray) \n   A.Ts ≈ C.Ts || error(\"A and C must have the same sampling time\")\n   period = promote_period(A, C)\n   nta = numerator(rationalize(period/A.period))\n   K = nta*A.nperiod*A.dperiod\n   X = pslyapd(A.M, C.M; adj = true)\n   return PeriodicArray(X, period; nperiod = div(K,size(X,3)))\nend\nprlyap(A::PeriodicArray, C::AbstractMatrix) = prlyap(A, PeriodicArray(C, A.Ts; nperiod = 1))\n\"\"\"\n    pflyap(A, C) -> X\n\nSolve the forward-time periodic discrete-time Lyapunov equation\n\n    A'XA + C = σX\n\nwhere `σ` is the forward shift operator `σX(i) = X(i+1)`.                 \n\nFor the periodic matrices `A` and `C` with the same sampling period and commensurate periods, \nthe periodic matrix `X` is determined, whose period is automatically set to the\nthe least common period of `A` and `C`.  \n\"\"\"\nfunction pflyap(A::PeriodicArray, C::PeriodicArray) \n   A.Ts ≈ C.Ts || error(\"A and C must have the same sampling time\")\n   period = promote_period(A, C)\n   nta = numerator(rationalize(period/A.period))\n   K = nta*A.nperiod*A.dperiod\n   X = pslyapd(A.M, C.M; adj = false)\n   return PeriodicArray(X, period; nperiod = div(K,size(X,3)))\nend\npflyap(A::PeriodicArray, C::AbstractMatrix) = pflyap(A, PeriodicArray(C, A.Ts; nperiod = 1))\n\"\"\"\n    pslyapd(A, C; adj = true) -> X\n\nSolve the periodic discrete-time Lyapunov equation.\n\nFor the square `n`-th order periodic matrices `A(i)`, `i = 1, ..., pa` and \n`C(i)`, `i = 1, ..., pc`  of periods `pa` and `pc`, respectively, \nthe periodic solution `X(i)`, `i = 1, ..., p` of period `p = lcm(pa,pc)` of the \nperiodic Lyapunov equation is solved:  for `adj = true`,  \n\n    A(i)'*X(i+1)*A(i) + C(i) = X(i), i = 1, ..., p    \n\nand for `adj = false`   \n\n    A(i)*X(i)*A(i)' + C(i) = X(i+1), i = 1, ..., p.   \n\nThe periodic matrices `A` and `C` are stored in the `n×n×pa` and `n×n×pc` 3-dimensional \narrays `A` and `C`, respectively, and `X` results as a `n×n×p` 3-dimensional array.  \n\nThe periodic discrete analog of the Bartels-Steward method based on the periodic Schur form\nof the periodic matrix `A` is employed [1].\n\n_Reference:_\n\n[1] A. Varga. Periodic Lyapunov equations: some applications and new algorithms. \n              Int. J. Control, vol, 67, pp, 69-87, 1997.\n\"\"\"\nfunction pslyapd(A::AbstractArray{T1, 3}, C::AbstractArray{T2, 3}; adj::Bool = true) where {T1, T2}\n   n = LinearAlgebra.checksquare(A[:,:,1])\n   pa = size(A,3)\n   pc = size(C,3)\n   (LinearAlgebra.checksquare(C[:,:,1]) == n && all([issymmetric(C[:,:,i]) for i in 1:pc])) ||\n      throw(DimensionMismatch(\"all C[:,:,i] must be $n x $n symmetric matrices\"))\n   p = lcm(pa,pc)\n\n   T = promote_type(T1, T2)\n   T <: BlasFloat  || (T = promote_type(Float64,T))\n   A1 = T1 == T ? A : A1 = convert(Array{T,3},A)\n   C1 = T2 == T ? C : C1 = convert(Array{T,3},C)\n\n   # Reduce A to Schur form and transform C\n   AS, Q, _, KSCHUR = pschur(A1)\n   \n   #X = Q'*C*Q\n   X = Array{T,3}(undef, n, n, p)\n\n   for i = 1:p\n       ia = mod(i-1,pa)+1\n       ic = mod(i-1,pc)+1\n       ia1 = mod(i,pa)+1\n\n       X[:,:,i] = adj ? utqu(view(C1,:,:,ic),view(Q,:,:,ia)) : \n                        utqu(view(C1,:,:,ic),view(Q,:,:,ia1)) \n   end\n   # solve A'σXA - X + C = 0\n   pdlyaps!(KSCHUR, AS, X; adj)\n\n   #X <- Q*X*Q'\n   for i = 1:p\n       ia = mod(i-1,pa)+1\n       utqu!(view(X,:,:,i),view(Q,:,:,ia)')\n   end\n   return X\nend\n\"\"\"\n     pslyapdkr(A, C; adj = true) -> X\n\nSolve the periodic discrete-time Lyapunov matrix equation\n\n      A'σXA + C = X, if adj = true,\n\nor \n\n      A*X*A' + C =  σX, if adj = false, \n\nwhere `σ` is the forward shift operator `σX(i) = X(i+1)`.                 \nThe Kronecker product expansion of equations is employed. `A` and `C` are\nperiodic square matrices, and `A` must not have characteristic multipliers on the unit circle.\nThis function is not recommended for large order matrices or large periods.\n\"\"\"\nfunction pslyapdkr(A::AbstractArray{T, 3}, C::AbstractArray{T, 3}; adj = true) where {T}\n    m, n, pc = size(C)\n    n == LinearAlgebra.checksquare(A[:,:,1]) \n    m == LinearAlgebra.checksquare(C[:,:,1]) \n    m == n  || throw(DimensionMismatch(\"A and C have incompatible dimensions\"))\n    pa = size(A,3)\n    n2 = n*n\n    p = lcm(pa,pc)\n    N = p*n2\n    R = zeros(T, N, N)\n    adj ? copyto!(view(R,N-n2+1:N,1:n2),kron(A[:,:,pa]',A[:,:,pa]')) : \n          copyto!(view(R,1:n2,N-n2+1:N),kron(A[:,:,pa],A[:,:,pa])) \n    (i2, j2) = adj ? (n2, n2+n2) : (n2+n2, n2)\n    for i = 1:p-1\n        i1 = i2-n2+1\n        j1 = j2-n2+1\n        ia = mod(i-1,pa)+1\n        adj ? copyto!(view(R,i1:i2,j1:j2),kron(A[:,:,ia]',A[:,:,ia]')) : \n              copyto!(view(R,i1:i2,j1:j2),kron(A[:,:,ia],A[:,:,ia])) \n        i2 += n2\n        j2 += n2\n    end\n    indc = mod.(0:p-1,pc).+1\n    return adj ? reshape((I-R) \\ (C[:,:,indc][:]), n, n, p) : \n    reshape((I-R) \\ (C[:,:,circshift(indc,1)][:]), n, n, p)\nend\nfunction pdlyaps!(KSCHUR::Int, A::StridedArray{T1,3}, C::StridedArray{T1,3}; adj = true) where {T1<:BlasReal}\n   n = LinearAlgebra.checksquare(A[:,:,1])\n   pa = size(A,3)\n   pc = size(C,3)\n   (LinearAlgebra.checksquare(C[:,:,1]) == n && all([issymmetric(C[:,:,i]) for i in 1:pc])) ||\n      throw(DimensionMismatch(\"all C[:,:,i] must be $n x $n symmetric matrices\"))\n   rem(pc,pa) == 0 || error(\"the period of C must be an integer multiple of A\")\n   (KSCHUR <= 0 || KSCHUR > pa ) && \n         error(\"KSCHUR has a value $KSCHUR, which is inconsistent with A \")\n\n   if pa == 1 && pc == 1   \n      lyapds!(view(A,:,:,1), view(C,:,:,1); adj)\n      return C[:,:,:]\n   end\n   ONE = one(T1)\n\n   # determine the dimensions of the diagonal blocks of real Schur form\n\n   G = Array{T1,3}(undef,2,2,pc)\n   W = Matrix{Float64}(undef,2,14)\n   WX = Matrix{Float64}(undef,4,5)\n   ba, p = MatrixEquations.sfstruct(A[:,:,KSCHUR])\n   if adj\n      #\n      # Solve    A(j)'*X(j+1)*A(j) + C(j) = X(j) .\n      #\n      # The (K,L)th blocks of X(j), j = 1, ..., p are determined\n      # starting from upper-left corner column by column by\n      #\n      #   A(j)(K,K)'*X(j+1)(K,L)*A(j)(L,L) - X(j)(K,L) = -C(j)(K,L) - R(j)(K,L)\n      #\n      # where\n      #                K              L-1\n      #   R(j)(K,L) = SUM {A(j)(I,K)'*SUM [X(j+1)(I,J)*A(j)(J,L)]}\n      #               I=1             J=1\n      #             \n      #                 K-1\n      #             +  {SUM [A(j)(I,K)'*X(j+1)(I,L)]}*A(j)(L,L)\n      #                 I=1\n      i = 1\n      @inbounds  for kk = 1:p\n          dk = ba[kk]\n          k = i:i+dk-1\n          j = 1\n          ir = 1:i-1\n          for ll = 1:kk\n              dl = ba[ll]\n              j1 = j+dl-1\n              l = j:j1\n              Ckl = view(C,k,l,1:pc)\n              y = view(G,1:dk,1:dl,1:pc)\n              copyto!(y,Ckl)\n              if kk > 1\n                 # C(j+1)[l,k] = C(j+1)[l,ir]*A(j)[ir,k]\n                 ic = 1:j1\n                 for ii = 1:pc\n                     ia = mod(ii-1,pa)+1\n                     ii1 = mod(ii,pc)+1\n                     mul!(view(C,l,k,ii1),view(C,l,ir,ii1),view(A,ir,k,ia))\n                     #y += C(j+1)[ic,k]'*A(j)[ic,l]\n                     mul!(view(y,:,:,ii),transpose(view(C,ic,k,ii1)),view(A,ic,l,ia),ONE,ONE)\n                 end\n              end\n              Ckl[:,:,:] .= dpsylv2(adj, dk, dl, KSCHUR, view(A,k,k,1:pa), view(A,l,l,1:pa), y, W, WX)\n              if ll == kk && dl == 2\n                 for ii = 1:pc\n                     temp = 0.5*(Ckl[1,2,ii]+Ckl[2,1,ii])\n                     Ckl[1,2,ii] = temp; Ckl[2,1,ii] = temp\n                 end\n              end\n              j += dl\n              if ll < kk\n                 # C(j+1)[l,k] += C(j+1)[k,l]'*A(j)[k,k]\n                 for ii = 1:pc\n                     ia = mod(ii-1,pa)+1\n                     ii1 = mod(ii,pc)+1\n                     mul!(view(C,l,k,ii1),transpose(view(C,k,l,ii1)),view(A,k,k,ia),ONE,ONE) \n                 end\n              end\n          end\n          if kk > 1\n             # C(j)[ir,k] = C(j)[k,ir]'\n             for ii = 1:pc\n                 transpose!(view(C,ir,k,ii),view(C,k,ir,ii))\n             end\n          end\n          i += dk\n      end\n   else\n      #\n      # Solve    A(j)*X(j)*A(j)' + C(j) = X(j+1) .\n      #\n      # The (K,L)th block of X(j) is determined starting from\n      # bottom-right corner column by column by\n      #\n      #    A(j)(K,K)*X(j)(K,L)*A(j)(L,L)' - X(j+1)(K,L) = -C(j)(K,L) - R(j)(K,L)\n      #\n      # Where\n      #\n      #                 N               N\n      #    R(j)(K,L) = SUM {A(j)(K,I)* SUM [X(j)(I,J)*A(j)(L,J)']} +\n      #                I=K            J=L+1\n      #              \n      #                N\n      #             { SUM [A(j)(K,J)*X(j)(J,L)]}*A(j)(L,L)'\n      #              J=K+1\n      j = n\n      for ll = p:-1:1\n          dl = ba[ll]\n          l = j-dl+1:j\n          i = n\n          ir = j+1:n\n          for kk = p:-1:ll\n              dk = ba[kk]\n              i1 = i-dk+1\n              k = i1:i\n              Clk = view(C,l,k,1:pc)\n              y = view(G,1:dl,1:dk,1:pc)\n              copyto!(y,Clk)\n              if ll < p\n                 ic = i1:n\n                 for ii = 1:pc\n                     ia = mod(ii-1,pa)+1\n                     # C(j)[k,l] = C(j)[k,ir]*A(j)[l,ir]'\n                     mul!(view(C,k,l,ii),view(C,k,ir,ii),transpose(view(A,l,ir,ia)))\n                     # y += (A(j)[k,ic]*C(j)[ic,l])'\n                     mul!(view(y,:,:,ii),transpose(view(C,ic,l,ii)),transpose(view(A,k,ic,ia)),ONE,ONE)\n                 end\n              end\n              Clk[:,:,:] .= dpsylv2(adj, dl, dk, KSCHUR, view(A,l,l,1:pa), view(A,k,k,1:pa), y, W, WX)\n              i -= dk\n              if i >= j\n                 for ii = 1:pc\n                     ia = mod(ii-1,pa)+1\n                     # C(j)[k,l] += (A(j)[l,l]*C(j)[l,k])'\n                     mul!(view(C,k,l,ii),transpose(view(C,l,k,ii)),transpose(view(A,l,l,ia)),ONE,ONE)\n                 end\n              else\n                 break\n              end\n          end\n          if ll < p\n             ir = i+2:n\n             for ii = 1:pc\n                 # C(j)[ir,l] = C(j)[l,ir]'\n                 transpose!(view(C,ir,l,ii),view(C,l,ir,ii))\n             end\n          end\n          j -= dl\n      end\n   end\n   return C[:,:,:]\nend\nfunction dpsylv2(REV::Bool, N1::Int, N2::Int, KSCHUR::Int, TL::StridedArray{T,3}, TR::StridedArray{T,3}, \n                 B::StridedArray{T,3}, W::AbstractMatrix{T}, WX::AbstractMatrix{T}) where {T}\n#     To solve for the N1-by-N2 matrices X_j, j = 1, ..., P, \n#     1 <= N1,N2 <= 2, in the P simultaneous equations: \n\n#     if REV = true\n\n#       TL_j'*X_(j+1)*TR_j - X_j = B_j, X_(P+1) = X_1  (1) \n\n#     or if REV = false\n\n#       TL_j*X_j*TR_j' - X_(j+1) = B_j, X_(P+1) = X_1  (2)\n\n#     where TL_j is N1 by N1, TR_j is N2 by N2, B_j is N1 by N2,\n#     and ISGN = 1 or -1.  \n\n#     NOTE: This routine is primarily intended to be used in conjuntion \n#           with solvers for periodic Lyapunov equations. Thus, both \n#           TL and TR are formed from the diagonal blocks of the same\n#           matrix in periodic real Schur form. W and WX are working matrices\n#           allocated only once in the caller routine. \n#           TL and TR are assumed to have the same period, but \n#           B may have different period than TL and TR. The period\n#           of B must be an integer multiple of that of TL and TR.\n#           In the interests of speed, this routine does not\n#                   check the inputs for errors.\n\n#     METHOD\n\n#     An initial approximation X_j, j=1, ..., P, is computed by reducing\n#     the system (1) or (2) to an equivalent single Lyapunov equation. \n#     Then, the accuracy of the solution is iteratively improved by \n#     performing forward or backward sweeps depending on the stability\n#     of eigenvalues. A maximum of 30 sweeps are performed. \n\n#     REFERENCES\n\n#     [1] A. Varga.\n#         Periodic Lyapunov equations: some applications and new algorithms.\n#         Int. J. Control, vol, 67, pp, 69-87, 1997.\n\n\tIND(J,P) = mod( J-1, P ) + 1\n   P = size(TL,3)\n   PB = size(B,3)\n   i1 = 1:N1; i2 = 1:N2;\n   Xw = view(WX,:,1:4)\n   Yw = view(WX,:,5)\n   Z = view(W,:,7:8)\n   X = Array{T,3}(undef, N1, N2, PB)\n\n   # Quick return if possible.\n   (N1 == 0 || N2 == 0) && (return X)\n   if P == 1 && PB == 1\n      copyto!(view(X,i1,i2,1), view(B,i1,i2,1))\n      MatrixEquations.lyapdsylv2!(REV, view(X, i1, i2, 1),  N1, N2, view(TL, i1, i1, 1), view(TR, i2, i2, 1), Xw, Yw) \n      return X[:,:,:]\n   end\n   # partition working space\n   AL = view(W,:,1:2)\n   AR = view(W,:,3:4)\n   Q = view(W,:,5:6)\n   ZOLD = view(W,:,9:10)\n   ATMP = view(W,:,11:12)\n   BTMP = view(W,:,13:14)\n   \n   EPSM = 2*eps(T)\n\n#     Define\n\n#       AL(i,j) := TL_{j+i-1}*...*TL_{j+1}*TL_{j}, AL(j,j) := I;\n#       AR(i,j) := TR_{j+i-1}*...*TR_{j+1}*TR_{j}, AR(j,j) := I;\n\n#     If REV = true, compute an initial approximation for \n#     X_{KSCHUR+1} = Z by solving \n  \n#       AL(KSCHUR+P+1,KSCHUR+1)'*Z*AR(KSCHUR+P+1,KSCHUR+1)  - Z = Qr(KSCHUR+1) \n\n#     where \n\n#       Qr(j)  = B_{j} + TL_{j}'*Qr(j+1)*TR_{j},  Qr(KSCHUR) = B(KSCHUR), \n#                for j = KSCHUR+P-1, ..., KSCHUR+1\n\n#     If REV = false, compute an initial approximation for \n#     X_{KSCHUR} = Z by solving \n  \n#       AL(KSCHUR+P,KSCHUR)*Z*AR(KSCHUR+P,KSCHUR)'  - Z = Qf(KSCHUR) \n\n#     where \n\n#       Qf(j)  = B_{j} + TL_{j}*Qf(j-1)*TR_{j}',  Qf(KSCHUR) = B(KSCHUR), \n#                for j = KSCHUR+1, ..., KSCHUR+P-1\n   x = 1\n   if REV \n      L1 = KSCHUR+PB-1\n      L2 = KSCHUR+1\n      LSTEP = -1\n   else\n      L1 = KSCHUR+1\n      L2 = KSCHUR+PB-1\n      LSTEP = 1\n   end\n   AL[ i1, i1 ] = TL[ i1, i1, KSCHUR ]\n   AR[ i2, i2 ] = TR[ i2, i2, KSCHUR ]\n   Q[i1,i2] = B[i1,i2,KSCHUR]\n\n   if  N1 == 1 && N2 == 1 \n       for JJ = L1:LSTEP:L2\n           J = IND( JJ, P )\n           JB = IND( JJ, PB )\n           X11 =  TL[ 1, 1, J ]\n           Y11 = TR[ 1, 1, J ]\n           AL[ 1, 1 ] = AL[ 1, 1] * X11\n           AR[ 1, 1 ] = AR[ 1, 1] * Y11\n           Q[ 1, 1 ] = B[ 1, 1, JB] + X11 * Q[ 1, 1 ] * Y11\n       end\n   elseif N1 == 1 && N2 == 2 \n       for JJ = L1:LSTEP:L2\n           J = IND( JJ, P )\n           JB = IND( JJ, PB )\n           X11 =  TL[ 1, 1, J ]\n           AL[ 1, 1 ] = AL[ 1, 1] * X11\n           Q[1,1] = X11*Q[1,1]\n           Q[1,2] = X11*Q[1,2]\n\n           Y11 = TR[ 1, 1, J ]\n           Y22 = TR[ 2, 2, J ]\n           Y12 = TR[ 1, 2, J ]\n           if REV \n               AR[1,2] = AR[1,1]*Y12 + AR[1,2]*Y22\n               AR[1,1] = AR[1,1]*Y11 \n               AR[2,2] = AR[2,1]*Y12 + AR[2,2]*Y22\n               AR[2,1] = AR[2,1]*Y11\n               Q[1,2] = Q[1,1]*Y12 + Q[1,2]*Y22 + B[ 1, 2, JB ]\n               Q[1,1] = Q[1,1]*Y11 + B[ 1, 1, JB ]\n           else\n               AR[1,1] = Y11*AR[1,1] + Y12*AR[2,1]\n               AR[2,1] = Y22*AR[2,1]\n               AR[1,2] = Y11*AR[1,2] + Y12*AR[2,2]\n               AR[2,2] = Y22*AR[2,2]\n               Q[1,1] = Q[1,1]*Y11 + Q[1,2]*Y12 + B[ 1, 1, JB ]\n               Q[1,2] = Q[1,2]*Y22 + B[ 1, 2, JB ]\n           end\n       end\n   elseif N1 == 2 && N2 == 1 \n       for JJ = L1:LSTEP:L2\n           J = IND( JJ, P )\n           JB = IND( JJ, PB )\n           X11 = TL[ 1, 1, J ]\n           X12 = TL[ 1, 2, J ]\n           X22 = TL[ 2, 2, J ]\n           if REV \n              AL[1,2] = AL[1,1]*X12 + AL[1,2]*X22\n              AL[1,1] = AL[1,1]*X11 \n              AL[2,2] = AL[2,1]*X12 + AL[2,2]*X22\n              AL[2,1] = AL[2,1]*X11\n              Q[2,1] = X12*Q[1,1] + X22*Q[2,1]\n              Q[1,1] = X11*Q[1,1]\n           else\n              AL[1,1] = X11*AL[1,1] + X12*AL[2,1]\n              AL[2,1] = X22*AL[2,1]\n              AL[1,2] = X11*AL[1,2] + X12*AL[2,2]\n              AL[2,2] = X22*AL[2,2]\n              Q[1,1] = X11*Q[1,1] + X12*Q[2,1]\n              Q[2,1] = X22*Q[2,1]\n            end\n\n            Y11 = TR[ 1, 1, J ]\n            AR[1,1] = AR[1,1]*Y11\n            Q[1,1] = Q[1,1]*Y11 + B[ 1, 1, JB ]\n            Q[2,1] = Q[2,1]*Y11 + B[ 2, 1, JB ]\n       end\n   elseif N1 == 2 && N2 == 2 \n       for JJ = L1:LSTEP:L2\n          J = IND( JJ, P )\n          JB = IND( JJ, PB )\n          X11 = TL[ 1, 1, J ]\n          X12 = TL[ 1, 2, J ]\n          X22 = TL[ 2, 2, J ]\n          if REV \n             AL[1,2] = AL[1,1]*X12 + AL[1,2]*X22\n             AL[1,1] = AL[1,1]*X11 \n             AL[2,2] = AL[2,1]*X12 + AL[2,2]*X22\n             AL[2,1] = AL[2,1]*X11\n             Q[2,1] = X12*Q[1,1] + X22*Q[2,1]\n             Q[1,1] = X11*Q[1,1]\n             Q[2,2] = X12*Q[1,2] + X22*Q[2,2]\n             Q[1,2] = X11*Q[1,2]\n          else\n             AL[1,1] = X11*AL[1,1] + X12*AL[2,1]\n             AL[2,1] = X22*AL[2,1]\n             AL[1,2] = X11*AL[1,2] + X12*AL[2,2]\n             AL[2,2] = X22*AL[2,2]\n             Q[1,1] = X11*Q[1,1] + X12*Q[2,1]\n             Q[2,1] = X22*Q[2,1]\n             Q[1,2] = X11*Q[1,2] + X12*Q[2,2]\n             Q[2,2] = X22*Q[2,2]\n          end\n\n          Y11 = TR[ 1, 1, J ]\n          Y12 = TR[ 1, 2, J ]\n          Y22 = TR[ 2, 2, J ]\n          if REV \n             AR[1,2] = AR[1,1]*Y12 + AR[1,2]*Y22\n             AR[1,1] = AR[1,1]*Y11 \n             AR[2,2] = AR[2,1]*Y12 + AR[2,2]*Y22\n             AR[2,1] = AR[2,1]*Y11\n             Q[1,2] = Q[1,1]*Y12 + Q[1,2]*Y22 + B[ 1, 2, JB ]\n             Q[1,1] = Q[1,1]*Y11 + B[ 1, 1, JB ]\n             Q[2,2] = Q[2,1]*Y12 + Q[2,2]*Y22 + B[ 2, 2, JB ]\n             Q[2,1] = Q[2,1]*Y11 + B[ 2, 1, JB ]\n          else\n             AR[1,1] = Y11*AR[1,1] + Y12*AR[2,1]\n             AR[2,1] = Y22*AR[2,1]\n             AR[1,2] = Y11*AR[1,2] + Y12*AR[2,2]\n             AR[2,2] = Y22*AR[2,2]\n             Q[1,1] = Q[1,1]*Y11 + Q[1,2]*Y12 + B[ 1, 1, JB ]\n             Q[1,2] = Q[1,2]*Y22 + B[ 1, 2, JB ]\n             Q[2,1] = Q[2,1]*Y11 + Q[2,2]*Y12 + B[ 2, 1, JB ]\n             Q[2,2] = Q[2,2]*Y22 + B[ 2, 2, JB ]\n          end\n       end\n   end\n   Z[i1,i2] = -Q[i1,i2]\n#     Compute X_[KSCHUR+1] (if REV=.TRUE.) or X_KSCHUR (if REV=.FALSE.).\n   MatrixEquations.lyapdsylv2!(REV, view(Z,i1,i2), N1, N2, view(AL,i1,i1), view(AR,i2,i2), Xw, Yw) \n   XNORM = norm(view(Z,i1,i2), Inf)\n   XNORM == 0 && (XNORM = one(T))\n  \n#     Determine the type of iteration to use\n\n   if N1 == 1\n      EL = abs( AL[1,1] )\n   else\n      EL = sqrt( abs( AL[1,1]*AL[2,2] - AL[1,2]*AL[2,1] ) )\n   end\n   if N2 == 1\n      ER = abs( AR[1,1] )\n   else\n      ER = sqrt( abs( AR[1,1]*AR[2,2] - AR[1,2]*AR[2,1] ) )\n   end\n   STAB = EL*ER < one(T)\n\n#     Save initial X_[KSCHUR+1].\n\n   ZOLD[i1,i2] = Z[i1,i2]\n\n#     Set iteration indices.\n\n   if REV \n      if STAB \n          L1 = KSCHUR + PB\n          L2 = KSCHUR + 1\n          LSTEP = -1\n          ITIND = -1\n      else\n          L1 = KSCHUR + 1\n          L2 = KSCHUR + PB \n          LSTEP = 1\n          ITIND = 0\n      end\n   else\n      if STAB \n          L1 = KSCHUR \n          L2 = KSCHUR + PB - 1 \n          LSTEP = 1\n          ITIND = 0\n      else\n          L1 = KSCHUR + PB - 1 \n          L2 = KSCHUR \n          LSTEP = -1\n          ITIND = -1\n      end\n   end\n   for ITER = 1:30\n       if N1 == 1 && N2 == 1 \n          if STAB \n\n#             Use direct recursion.\n\n             for JJ = L1:LSTEP:L2\n               J = IND( JJ, P )\n               JB = IND( JJ, PB )\n               J1 = IND( JJ+ITIND+1, PB )\n               Z[1,1] = TL[ 1, 1, J ] * Z[1,1] * TR[ 1, 1, J ] - B[ 1, 1, JB ] \n               X[ 1, 1, J1 ] = Z[ 1, 1 ]\n             end\n          else\n\n#             Use inverse recursion.\n\n             for JJ = L1:LSTEP:L2\n                  J = IND( JJ, P )\n                  JB = IND( JJ, PB )\n                  J1 = IND( JJ+ITIND+1, PB )\n                  Z[1,1] = (Z[1,1] + B[ 1, 1, JB ] ) / TL[ 1, 1, J ] / TR[ 1, 1, J ]\n                  X[ 1, 1, J1 ] = Z[ 1, 1 ]\n             end\n          end\n       elseif N1 == 1 && N2 == 2 \n          if STAB \n\n#              Use direct recursion.\n\n             for JJ = L1:LSTEP:L2\n                 J = IND( JJ, P )\n                 JB = IND( JJ, PB )\n                 J1 = IND( JJ+ITIND+1, PB )\n                 X11 = TL[ 1, 1, J ]\n                 Y11 = TR[ 1, 1, J ]\n                 Y22 = TR[ 2, 2, J ]\n                 if REV \n                    Y12 = TR[ 1, 2, J ]\n                    Y21 = TR[ 2, 1, J ]\n                 else\n                    Y12 = TR[ 2, 1, J ]\n                    Y21 = TR[ 1, 2, J ]\n                 end\n\n                 Z[1,1] = X11*Z[1,1]\n                 Z[1,2] = X11*Z[1,2]\n                 TEMP = Z[1,1]*Y11 + Z[1,2]*Y21\n                 Z[1,2] = Z[1,1]*Y12 + Z[1,2]*Y22 - B[ 1, 2, JB ]\n                 Z[1,1] = TEMP - B[ 1, 1, JB ]\n                 X[ 1, 1, J1 ] = Z[ 1, 1 ]\n                 X[ 1, 2, J1 ] = Z[ 1, 2 ]\n              end\n          else\n\n#              Use inverse recursion.\n\n             for JJ = L1:LSTEP:L2\n                 J = IND( JJ, P )\n                 JB = IND( JJ, PB )\n                 J1 = IND( JJ+ITIND+1, PB )\n                 BTMP[ 1, 1 ] = ( Z[1,1] + B[1,1,JB] ) / TL[ 1, 1, J ]\n                 BTMP[ 2, 1 ] = ( Z[1,2] + B[1,2,JB] ) / TL[ 1, 1, J ]\n                 ATMP[ 1, 1 ] = TR[ 1, 1, J ]\n                 ATMP[ 2, 2 ] = TR[ 2, 2, J ]\n                 if REV \n                    ATMP[ 1, 2 ] = TR[ 2, 1, J ]\n                    ATMP[ 2, 1 ] = TR[ 1, 2, J ]\n                 else\n                    ATMP[ 1, 2 ] = TR[ 1, 2, J ]\n                    ATMP[ 2, 1 ] = TR[ 2, 1, J ]\n                 end\n\n                 #CALL DGESV( 2, 1, ATMP, 2, JPIV, BTMP, 2, INFO )\n                 luslv!(ATMP,view(BTMP,1:2,1:1))\n                 #BTMP = ATMP\\BTMP\n                 Z[ 1, 1 ] = BTMP[ 1, 1 ]\n                 Z[ 1, 2 ] = BTMP[ 2, 1 ]\n                 X[ 1, 1, J1 ] = Z[ 1, 1 ]\n                 X[ 1, 2, J1 ] = Z[ 1, 2 ]\n              end\n          end\n       elseif N1 == 2 && N2 == 1 \n          if STAB \n\n#              Use direct recursion.\n\n             for JJ = L1:LSTEP:L2\n                 J = IND( JJ, P )\n                 JB = IND( JJ, PB )\n                 J1 = IND( JJ+ITIND+1, PB )\n                 X11 = TL[ 1, 1, J ]\n                 X22 = TL[ 2, 2, J ]\n                 if REV \n                    X12 = TL[ 2, 1, J ]\n                    X21 = TL[ 1, 2, J ]\n                 else\n                    X12 = TL[ 1, 2, J ]\n                    X21 = TL[ 2, 1, J ]\n                 end\n                 Y11 = TR[ 1, 1, J ]\n\n                 TEMP = X11*Z[1,1] + X12*Z[2,1]\n                 Z[2,1] = X21*Z[1,1] + X22*Z[2,1]\n                 Z[1,1] = TEMP\n                 Z[1,1] = Z[1,1]*Y11 - B[ 1, 1, JB ]\n                 Z[2,1] = Z[2,1]*Y11 - B[ 2, 1, JB ]\n                 X[ 1, 1, J1 ] = Z[ 1, 1 ]\n                 X[ 2, 1, J1 ] = Z[ 2, 1 ]\n              end\n          else\n\n#              Use inverse recursion.\n\n             for JJ = L1:LSTEP:L2\n                 J = IND( JJ, P )\n                 JB = IND( JJ, PB )\n                 J1 = IND( JJ+ITIND+1, PB )\n                 Z[ 1, 1 ] = ( Z[1,1] + B[1,1,JB] ) / TR[ 1, 1, J ]\n                 Z[ 2, 1 ] = ( Z[2,1] + B[2,1,JB] ) / TR[ 1, 1, J ]\n                 ATMP[ 1, 1 ] = TL[ 1, 1, J ]\n                 ATMP[ 2, 2 ] = TL[ 2, 2, J ]\n                 if REV \n                    ATMP[ 1, 2 ] = TL[ 2, 1, J ]\n                    ATMP[ 2, 1 ] = TL[ 1, 2, J ]\n                 else\n                    ATMP[ 1, 2 ] = TL[ 1, 2, J ]\n                    ATMP[ 2, 1 ] = TL[ 2, 1, J ]\n                 end\n\n                 #CALL DGESV( 2, 1, ATMP, 2, JPIV, Z, 2, INFO )\n                 luslv!(ATMP,view(Z,1:2,1:1))\n                 #Z = ATMP\\Z\n                 X[ 1, 1, J1 ] = Z[ 1, 1 ]\n                 X[ 2, 1, J1 ] = Z[ 2, 1 ]\n              end\n          end\n       elseif N1 == 2 && N2 == 2 \n          if STAB \n\n#              Use direct recursion.\n\n             for JJ = L1:LSTEP:L2\n                 J = IND( JJ, P )\n                 JB = IND( JJ, PB )\n                 J1 = IND( JJ+ITIND+1, PB )\n                 X11 = TL[ 1, 1, J ]\n                 X22 = TL[ 2, 2, J ]\n                 Y11 = TR[ 1, 1, J ]\n                 Y22 = TR[ 2, 2, J ]\n                 if REV \n                    X12 = TL[ 2, 1, J ]\n                    X21 = TL[ 1, 2, J ]\n                    Y12 = TR[ 1, 2, J ]\n                    Y21 = TR[ 2, 1, J ]\n                 else\n                    X12 = TL[ 1, 2, J ]\n                    X21 = TL[ 2, 1, J ]\n                    Y12 = TR[ 2, 1, J ]\n                    Y21 = TR[ 1, 2, J ]\n                 end\n\n                 TEMP = X11*Z[1,1] + X12*Z[2,1]\n                 Z[2,1] = X21*Z[1,1] + X22*Z[2,1]\n                 Z[1,1] = TEMP\n                 TEMP = X11*Z[1,2] + X12*Z[2,2]\n                 Z[2,2] = X21*Z[1,2] + X22*Z[2,2]\n                 Z[1,2] = TEMP\n                 TEMP = Z[1,1]*Y11 + Z[1,2]*Y21\n                 Z[1,2] = Z[1,1]*Y12 + Z[1,2]*Y22 - B[ 1, 2, JB ]\n                 Z[1,1] = TEMP - B[ 1, 1, JB ]\n                 TEMP = Z[2,1]*Y11 + Z[2,2]*Y21\n                 Z[2,2] = Z[2,1]*Y12 + Z[2,2]*Y22 - B[ 2, 2, JB ]\n                 Z[2,1] = TEMP - B[ 2, 1, JB ]\n                 X[ 1, 1, J1 ] = Z[ 1, 1 ]\n                 X[ 2, 1, J1 ] = Z[ 2, 1 ]\n                 X[ 1, 2, J1 ] = Z[ 1, 2 ]\n                 X[ 2, 2, J1 ] = Z[ 2, 2 ]\n              end\n          else\n\n#              Use inverse recursion.\n\n             for JJ = L1:LSTEP:L2\n                 J = IND( JJ, P )\n                 JB = IND( JJ, PB )\n                 J1 = IND( JJ+ITIND+1, PB )\n                 BTMP[ 1, 1 ] = Z[ 1, 1 ] + B[ 1, 1, JB ]\n                 BTMP[ 2, 1 ] = Z[ 1, 2 ] + B[ 1, 2, JB ]\n                 BTMP[ 1, 2 ] = Z[ 2, 1 ] + B[ 2, 1, JB ]\n                 BTMP[ 2, 2 ] = Z[ 2, 2 ] + B[ 2, 2, JB ]\n                 ATMP[ 1, 1 ] = TR[ 1, 1, J ]\n                 ATMP[ 2, 2 ] = TR[ 2, 2, J ]\n                 if REV \n                    ATMP[ 1, 2 ] = TR[ 2, 1, J ]\n                    ATMP[ 2, 1 ] = TR[ 1, 2, J ]\n                 else\n                    ATMP[ 1, 2 ] = TR[ 1, 2, J ]\n                    ATMP[ 2, 1 ] = TR[ 2, 1, J ]\n                 end\n\n                 #CALL DGESV( 2, 2, ATMP, 2, JPIV, BTMP, 2, INFO )\n                 luslv!(ATMP,view(BTMP,1:2,1:2))\n                 #BTMP = ATMP\\BTMP\n                 Z[ 1, 1 ] = BTMP[ 1, 1 ]\n                 Z[ 1, 2 ] = BTMP[ 2, 1 ]\n                 Z[ 2, 1 ] = BTMP[ 1, 2 ]\n                 Z[ 2, 2 ] = BTMP[ 2, 2 ]\n\n                 ATMP[ 1, 1 ] = TL[ 1, 1, J ]\n                 ATMP[ 2, 2 ] = TL[ 2, 2, J ]\n                 if REV \n                    ATMP[ 1, 2 ] = TL[ 2, 1, J ]\n                    ATMP[ 2, 1 ] = TL[ 1, 2, J ]\n                 else\n                    ATMP[ 1, 2 ] = TL[ 1, 2, J ]\n                    ATMP[ 2, 1 ] = TL[ 2, 1, J ]\n                 end\n\n                 #CALL DGESV( 2, 2, ATMP, 2, JPIV, Z, 2, INFO )\n                 luslv!(ATMP,view(Z,1:2,1:2))\n                 #Z = ATMP\\Z\n                 X[ 1, 1, J1 ] = Z[ 1, 1 ]\n                 X[ 1, 2, J1 ] = Z[ 1, 2 ]\n                 X[ 2, 1, J1 ] = Z[ 2, 1 ]\n                 X[ 2, 2, J1 ] = Z[ 2, 2 ]\n              end\n          end\n       end\n       DNORM = zero(T)\n       for J = 1:N2\n          for I = 1:N1\n             DNORM = max( DNORM, abs( ZOLD[I,J] - Z[I,J] ) )\n             ZOLD[ I, J ] = Z[ I, J ]\n          end\n       end\n       #println(\"XNORM = $XNORM DNORM = $DNORM\")\n       DNORM <= EPSM*XNORM && (return -X)\n   end\n   @warn \"iterative process not converging: solution may be inaccurate\"\n   return -X\n#   END of DPSYLV2\nend\n@inline function luslv!(A::AbstractMatrix{T}, B::AbstractMatrix{T}) where T\n   #\n   #  fail = luslv!(A,B)\n   #\n   # This function is a speed-oriented implementation of a Gaussion-elimination based\n   # solver of small order linear equations of the form A*X = B. The computed solution X\n   # overwrites the vector B, while the resulting A contains in its upper triangular part,\n   # the upper triangular factor U of its LU decomposition.\n   # The diagnostic output parameter fail, of type Bool, is set to false in the case\n   # of normal return or is set to true if the exact singularity of A is detected\n   # or if the resulting B has non-finite components.\n   #\n   n, m = size(B)\n   @inbounds begin\n         for k = 1:n\n            # find index max\n            kp = k\n            if k < n\n                amax = abs(A[k, k])\n                for i = k+1:n\n                    absi = abs(A[i,k])\n                    if absi > amax\n                        kp = i\n                        amax = absi\n                    end\n                end\n            end\n            iszero(A[kp,k]) && return true\n            if k != kp\n               # Interchange\n               for i = 1:n\n                   tmp = A[k,i]\n                   A[k,i] = A[kp,i]\n                   A[kp,i] = tmp\n               end\n               for j = 1:m \n                   tmp = B[k,j]\n                   B[k,j] = B[kp,j]\n                   B[kp,j] = tmp\n               end\n            end\n            # Scale first column\n            Akkinv = inv(A[k,k])\n            i1 = k+1:n\n            Ak = view(A,i1,k)\n            rmul!(Ak,Akkinv)\n            # Update the rest of A and B\n            for j = k+1:n\n                axpy!(-A[k,j],Ak,view(A,i1,j))\n            end\n            for j = 1:m \n                axpy!(-B[k,j],Ak,view(B,i1,j))\n            end\n         end\n         ldiv!(UpperTriangular(A), view(B,:,:))\n         return any(!isfinite, B)\n   end\nend\n", "meta": {"hexsha": "876e3233878786b436294e9ad5b36c31f098fb64", "size": 29621, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pslyap.jl", "max_stars_repo_name": "andreasvarga/PeriodicSystems.jl", "max_stars_repo_head_hexsha": "3c87149555e3734d04104fc012716f0654e146e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pslyap.jl", "max_issues_repo_name": "andreasvarga/PeriodicSystems.jl", "max_issues_repo_head_hexsha": "3c87149555e3734d04104fc012716f0654e146e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pslyap.jl", "max_forks_repo_name": "andreasvarga/PeriodicSystems.jl", "max_forks_repo_head_hexsha": "3c87149555e3734d04104fc012716f0654e146e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7369020501, "max_line_length": 118, "alphanum_fraction": 0.3991087404, "num_tokens": 11142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.7736387908014835}}
{"text": "\nmodule BS\n\nusing ..Distributions\nimport ..Roots\n\n#\n# types\n#\n\nstruct D₁Parts{T}\n    numerator::T\n    denominator::T\nend\n\nabstract type BSOption end\n\n\"European call option.\"\nstruct EuropeanCall <: BSOption end\n\n\"European put option.\"\nstruct EuropeanPut <: BSOption end\n\n@inline N(x) = cdf(Normal(), x)\n\n@inline D₁Parts(s, k, t, σ) = D₁Parts(log(s/k) + (σ^2/2)*t, σ*sqrt(t))\n\n@inline d₁(parts::D₁Parts) = parts.numerator / parts.denominator\n@inline d₂(parts::D₁Parts) = d₁(parts) - parts.denominator\n\n@inline d₁(s, k, t, σ) = d₁(D₁Parts(s, k, t, σ))\n@inline d₂(s, k, t, σ) = d₂(D₁Parts(s, k, t, σ))\n\n@inline function bscall(s, k, t, σ)\n    parts = D₁Parts(s, k, t, σ)\n    return s*N(d₁(parts)) - k*N(d₂(parts))\nend\n\n@inline function bsput(s, k, t, σ)\n    parts = D₁Parts(s, k, t, σ)\n    return k*N(-d₂(parts)) - s*N(-d₁(parts))\nend\n\n@inline price(::EuropeanCall, s, k, t, σ) = bscall(s, k, t, σ)\n@inline price(::EuropeanPut, s, k, t, σ) = bsput(s, k, t, σ)\n\nfunction impvol(opt::BSOption, observed_price, s, k, t, interval::Tuple=infer_impvol_interval(opt, observed_price, s, k, t))\n    f(σ) = observed_price - price(opt, s, k, t, σ)\n    return Roots.find_zero(f, interval, Roots.Bisection())\nend\n\nfunction infer_impvol_interval(opt::BSOption, observed_price, s, k, t)\n    # most instruments have volatility values below 100%\n    min_vol = 0.0\n    max_vol = 1.0\n    if observed_price <= price(opt, s, k, t, max_vol)\n        return (min_vol, max_vol)\n    end\n\n    # will increment max_vol 10x until we reach a final interval\n    while true\n        min_vol = max_vol\n        max_vol = min_vol * 10\n        if observed_price <= price(opt, s, k, t, max_vol)\n            return (min_vol, max_vol)\n        end\n    end\nend\n\n#\n# Greeks\n#\n\n@inline delta(::EuropeanCall, s, k, t, σ) = N(d₁(s, k, t, σ))\n@inline delta(::EuropeanPut, s, k, t, σ) = N(d₁(s, k, t, σ)) - 1\n\n@inline function theta(::EuropeanCall, s, k, t, r, σ)\n    parts = D₁Parts(s, k, t, σ)\n    return -(s * pdf(Normal(), d₁(parts)) * σ) / ( 2*sqrt(t) ) - r*k*N(d₂(parts))\nend\n\n@inline function theta(::EuropeanPut, s, k, t, r, σ)\n    parts = D₁Parts(s, k, t, σ)\n    return -(s * pdf(Normal(), d₁(parts)) * σ) / ( 2*sqrt(t) ) + r*k*N(-d₂(parts))\nend\n\n@inline function gamma(s, k, t, σ)\n    parts = D₁Parts(s, k, t, σ)\n    return pdf(Normal(), d₁(parts)) / (s * parts.denominator)\nend\n@inline gamma(::BSOption, s, k, t, σ) = gamma(s, k, t, σ)\n\n\n@inline vega(s, k, t, σ) = s*sqrt(t)*pdf(Normal(), d₁(s, k, t, σ))\n@inline vega(::BSOption, s, k, t, σ) = vega(s, k, t, σ)\n\n@inline rho(::EuropeanCall, s, k, t, σ) = k*t*N(d₂(s, k, t, σ))\n@inline rho(::EuropeanPut, s, k, t, σ) = -k*t*N(-d₂(s, k, t, σ))\n\nend # module\n", "meta": {"hexsha": "dfa03473ec9692a4cbd0c570dd1279ee500863b9", "size": 2664, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BS.jl", "max_stars_repo_name": "haharay/FinancialDSL.jl", "max_stars_repo_head_hexsha": "a0aee2ae3382f83748beef16ad3af505f962e66b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-07-28T22:53:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T02:57:59.000Z", "max_issues_repo_path": "src/BS.jl", "max_issues_repo_name": "haharay/FinancialDSL.jl", "max_issues_repo_head_hexsha": "a0aee2ae3382f83748beef16ad3af505f962e66b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BS.jl", "max_forks_repo_name": "haharay/FinancialDSL.jl", "max_forks_repo_head_hexsha": "a0aee2ae3382f83748beef16ad3af505f962e66b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-23T22:17:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-23T22:17:37.000Z", "avg_line_length": 26.3762376238, "max_line_length": 124, "alphanum_fraction": 0.6058558559, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429474, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7735881825395886}}
{"text": "\"\"\"\n    geometric_factors(x, y, Dr, Ds)\n    geometric_factors(x, y, z, Dr, Ds, Dt)\n\nCompute metrics of mappings between \"real\" elements and reference elements,\noutward pointing normals on faces of every elements, and Jacobian.\n\nx,y,z are arrays of coordinates, and Dr, Ds, Dt are nodal differentiation matrices\n\nGeometric terms in 3D are constructed to ensure satisfaction of free-stream\npreservation using the curl-based construction of David Kopriva (2001).\n\n\"\"\"\n\n# 2D version\nfunction geometric_factors(x, y, Dr, Ds)\n    \"Transformation and Jacobian\"\n\n    xr = Dr*x;   xs = Ds*x;\n    yr = Dr*y;   ys = Ds*y;\n\n    J = -xs.*yr + xr.*ys;\n    rxJ =  ys;  sxJ = -yr;\n    ryJ = -xs;  syJ =  xr;\n\n    return rxJ, sxJ, ryJ, syJ, J\nend\n\n# 3D version. Filters = tuple of filtering matrices.\nfunction geometric_factors(x, y, z, Dr, Ds, Dt, Filters=(I,I,I))\n\n    xr = Dr*x;  xs = Ds*x;  xt = Dt*x\n    yr = Dr*y;  ys = Ds*y;  yt = Dt*y\n    zr = Dr*z;  zs = Ds*z;  zt = Dt*z\n\n    Fr = (Dr*y).*z\n    Fs = (Ds*y).*z\n    Ft = (Dt*y).*z\n    Fr,Fs,Ft = ((A,x)->A*x).(Filters,(Fr,Fs,Ft))\n    rxJ = Dt*(Fs) - Ds*(Ft)\n    sxJ = Dr*(Ft) - Dt*(Fr)\n    txJ = Ds*(Fr) - Dr*(Fs)\n\n    Fr = (Dr*x).*z\n    Fs = (Ds*x).*z\n    Ft = (Dt*x).*z\n    Fr,Fs,Ft = ((A,x)->A*x).(Filters,(Fr,Fs,Ft))\n    ryJ = -(Dt*(Fs) - Ds*(Ft))\n    syJ = -(Dr*(Ft) - Dt*(Fr))\n    tyJ = -(Ds*(Fr) - Dr*(Fs))\n\n    Fr = (Dr*y).*x\n    Fs = (Ds*y).*x\n    Ft = (Dt*y).*x\n    Fr,Fs,Ft = ((A,x)->A*x).(Filters,(Fr,Fs,Ft))\n    rzJ = -(Dt*(Fs) - Ds*(Ft))\n    szJ = -(Dr*(Ft) - Dt*(Fr))\n    tzJ = -(Ds*(Fr) - Dr*(Fs))\n\n    J = @. xr*(ys*zt-zs*yt) - yr*(xs*zt-zs*xt) + zr*(xs*yt-ys*xt)\n\n    return rxJ, sxJ, txJ, ryJ, syJ, tyJ, rzJ, szJ, tzJ, J\nend\n", "meta": {"hexsha": "c47c4d623d935a80ac170edcb648fd14061d53c9", "size": 1685, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CommonUtils/geometric_factors.jl", "max_stars_repo_name": "yiminllin/ESDG-Fourier", "max_stars_repo_head_hexsha": "0cbd36add7b06e0fa43335daf7188ccaea461e6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CommonUtils/geometric_factors.jl", "max_issues_repo_name": "yiminllin/ESDG-Fourier", "max_issues_repo_head_hexsha": "0cbd36add7b06e0fa43335daf7188ccaea461e6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CommonUtils/geometric_factors.jl", "max_forks_repo_name": "yiminllin/ESDG-Fourier", "max_forks_repo_head_hexsha": "0cbd36add7b06e0fa43335daf7188ccaea461e6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.328125, "max_line_length": 82, "alphanum_fraction": 0.5400593472, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778012346835, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7735448076519813}}
{"text": "module PolyharmonicInterpolation\nusing LinearAlgebra\n\nexport PolyharmonicInterpolator,polyharmonicSpline\n\nstruct PolyharmonicInterpolator\n\tknots::AbstractArray\n\tvalues::Vector{Float64}\n\tnPts::Int\n\tdim::Int\n\torder::Int\n\tw::Vector{Float64}\n\tv::Vector{Float64}\nend\n\nPolyharmonicInterpolator(knots::AbstractArray{T},values::Vector{T},\norder::Int=2) where T <: Real = begin\n\n\t# Check to make sure knots is N x d and values is N x 1\n\tif size(knots)[1] != length(values)\n\t\terror(\"knots and values length must agree\")\n\tend\n\n\tif length(size(knots)) == 1\n\t\tnPts = length(knots)\n\t\tdim = 1\n\telse\n\t\tnPts,dim = size(knots)\n\tend\n\n\t# initialize w and v\n\tw = Vector{Float64}(undef,nPts)\n\tv = Vector{Float64}(undef,dim+1)\n\n\t# Fill npts and dim using the dimension of knots\n\tcomputeWeights(PolyharmonicInterpolator(knots,values,nPts,dim,order,w,v))\n\nend\n\nfunction polyharmonicRBF(r::Float64,k::Int)\n\n\n\tif r >= 1\n\t\tval = (k % 2 == 0) ? r^k*log(r) : r^k\n\telse\n\t\tval = (k % 2 == 0) ? r^(k-1)*log(r^r) : r^k\n\tend\n\n\treturn val\n\nend\n\nfunction createBlockMatrix(p::PolyharmonicInterpolator)\n\n\t# Create the matrix of differences between the knots\n\tdist = [norm(p.knots[i,:] - p.knots[j,:]) for i in 1:p.nPts, j in 1:p.nPts]\n\n\t# Create the matrix A\n\tA = map(r->polyharmonicRBF(r,p.order),dist)\n\n\t# Create the matrix B\n\tB = [ones(p.nPts) p.knots];\n\n\treturn A,B\n\n\nend\n\nfunction computeWeights(p::PolyharmonicInterpolator)\n\n\t# Create block matrices used to solve for weights\n\tA,B = createBlockMatrix(p)\n\n\t# Make block matrix for the symmetric linear system\n\tblockMat = [A B; transpose(B) zeros(p.dim+1,p.dim+1)]\n\n\t# Get weights nPts and number of dimensions\n\tweights = blockMat \\ [p.values; zeros(p.dim+1,1)]\n\n\tp.w .= weights[1:p.nPts]\n\tp.v .= weights[p.nPts+1:end]\n\n\treturn p\n\nend\n\nfunction polyharmonicSpline(p::PolyharmonicInterpolator,interpPoints::AbstractArray)\n\n\t# Check to see the dimensions of the interpPoints array agree\n\tlet\n\t\tnInterpDims = nothing\n\t\ttry\n\t\t\t_, nInterpDims = size(interpPoints)\n\t\tcatch\n\t\t\tnInterpDims = 1\n\t\tend\n\n\t\tif p.dim != nInterpDims\n\t\t\terror(\"dimension of knots and points to be interpolated must agree\")\n\t\tend\n\tend\n\n\t# Initialize array\n\tinterpValues = zeros(size(interpPoints)[1])\n\n\tfor (i,point) in enumerate(eachrow(interpPoints))\n\n\t\ttmppoint =[1.0;point]\n\n\t\t# Get distance to all scattered points\n\t\tdist = sqrt.(sum((p.knots .- point').^2,dims=2))\n\n\t\t# reduce to normal size (Julia returns a 2 dimensional row array for some reason...)\n\t\tdist = reduce(vcat,dist)\n\n\t\t# Get distance between basis and point of interest and compute the\n\t\t# polyharmonic basis\n\t\tphi = map(r->polyharmonicRBF(r,p.order),dist)\n\n\t\tinterpValues[i] = p.w'phi + p.v'tmppoint\n\n\tend\n\n\treturn interpValues\n\nend\n\nend\n", "meta": {"hexsha": "85bddbb2d5cc4894dbe58844d26566ab5e71c5ad", "size": 2692, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/polyHarmonicInterp.jl", "max_stars_repo_name": "MathOnco/ploidyEvolution", "max_stars_repo_head_hexsha": "5e7211f2e6ef7a19ac3c72c5836d8aa3298177b6", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-04T03:21:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T03:21:23.000Z", "max_issues_repo_path": "Julia/polyHarmonicInterp.jl", "max_issues_repo_name": "MathOnco/ploidyEvolution", "max_issues_repo_head_hexsha": "5e7211f2e6ef7a19ac3c72c5836d8aa3298177b6", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2021-08-16T17:12:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T12:54:12.000Z", "max_forks_repo_path": "Julia/polyHarmonicInterp.jl", "max_forks_repo_name": "MathOnco/ploidyEvolution", "max_forks_repo_head_hexsha": "5e7211f2e6ef7a19ac3c72c5836d8aa3298177b6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-25T18:59:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-25T18:59:27.000Z", "avg_line_length": 20.8682170543, "max_line_length": 86, "alphanum_fraction": 0.7091381872, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778000158576, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.773544806667088}}
{"text": "using LinearAlgebraicRepresentation, ViewerGL, SparseArrays\nLar = LinearAlgebraicRepresentation; GL = ViewerGL\nusing Base.union\n\n# 3D Boolean example generation\n#-------------------------------------------------------------------------------\nn,m,p = 1,1,1\nV,(VV,EV,FV,CV) = Lar.cuboidGrid([n,m,p],true)\ncube = V,FV,EV\n\nV,FV = Lar.sphere()()\nEV = Lar.simplexFacets(FV)\nsphere = V,FV,EV\n\n# three cubes in \"assembly\"\nassembly = Lar.Struct([ cube,\n    Lar.t(.3,.4,.25), Lar.r(pi/5,0,0), Lar.r(0,0,pi/12), cube,\n    Lar.t(-.2,.4,-.2), Lar.r(0,pi/5,0), Lar.r(0,pi/12,0), cube ])\n\nV,FV,EV = Lar.struct2lar(assembly)\nGL.VIEW([ GL.GLGrid(V,FV), GL.GLFrame ]);\n\nW, (copEV, copFE, copCF), boolmatrix = Lar.bool3d(assembly)\nMatrix(boolmatrix)\n#three-chains = [ for k = 1:3]\n\nA = boolmatrix[:,2]\nB = boolmatrix[:,3]\nC = boolmatrix[:,4]\nAorB = A .| B\nAandB = A .& B\nAxorB = AorB .& (.! AandB)\nAorBorC = A .| B .| C\nAorBorC = .|(A,B,C)\nAandBandC = A .& B .& C\nAandBandC = .&(A,B,C)\nAminusBminusC = .&(A, .!(B .| C)) # A - B - C\n\nunione = .|(A,B,C)\nunione = Matrix(copCF)' * Int.(unione) # coord vector of Faces\nintersection = Matrix(copCF)' * Int.(AandBandC) # coord vector of Faces\ndifference = Matrix(copCF)' * Int.(AminusBminusC) # coord vector of Faces\n\nV,CVs,FVs,EVs = Lar.pols2tria(W, copEV, copFE, copCF) # whole assembly\nFs = unione\nV,CVs,FVs,EVs = Lar.pols2tria(W, copEV, copFE, copCF, Fs) # part of assembly\n\n\n\n\n\n# EV = Lar.cop2lar(copEV)\n# EVor = [ev for (k,ev) in enumerate(EV) if abs(union[k])==1 ]\n# EVand = [ev for (k,ev) in enumerate(EV) if abs(intersection[k])==1 ]\n# EVxor = [ev for (k,ev) in enumerate(EV) if abs(xor[k])==1 ]\n\n\n\n\nGL.VIEW(GL.GLExplode(V,FVs,1.,1.,1.,99,1));\nGL.VIEW(GL.GLExplode(V,EVs,1.,1.,1.,99,1));\nmeshes = GL.GLExplode(V,CVs[2:end],1.5,1.5,1.5,99,1);\nGL.VIEW( push!( meshes, GL.GLFrame) );\n\n# GL.VIEW(GL.GLExplode(V,[EVor],1.,1.,1.,99,1));\n\n\nGL.VIEW([ GL.GLGrid(V,EV, GL.COLORS[1],0.5), GL.GLFrame ]);\n", "meta": {"hexsha": "0e5e51f555a10ff3733e545fc71f6964642f8fda", "size": 1927, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/3d/bool3d.jl", "max_stars_repo_name": "ramorimo/LinearAlgebraicRepresentation.jl", "max_stars_repo_head_hexsha": "53fb941a83f11967361518e5a981679b851e45ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/3d/bool3d.jl", "max_issues_repo_name": "ramorimo/LinearAlgebraicRepresentation.jl", "max_issues_repo_head_hexsha": "53fb941a83f11967361518e5a981679b851e45ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/3d/bool3d.jl", "max_forks_repo_name": "ramorimo/LinearAlgebraicRepresentation.jl", "max_forks_repo_head_hexsha": "53fb941a83f11967361518e5a981679b851e45ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9275362319, "max_line_length": 80, "alphanum_fraction": 0.6050856253, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8688267779364222, "lm_q1q2_score": 0.7735114638970031}}
{"text": "immutable Point{T<:FloatingPoint}\n    x::T\n    y::T\nend\n\nimmutable Circle{T<:FloatingPoint}\n    c::Point{T}\n    r::T\nend\nCircle{T<:FloatingPoint}(a::Point{T}) = Circle(a, zero(T))\n\nusing AffineTransforms\n\nfunction circlepoints{T<:FloatingPoint}(a::Point{T}, b::Point{T}, r::T)\n    cp = Circle{T}[]\n    r >= 0 || return (cp, \"No Solution, Negative Radius\")\n    if a == b\n        if abs(r) < 2eps(zero(T))\n            return (push!(cp, Circle(a)), \"Point Solution, Zero Radius\")\n        else\n            return (cp, \"Infinite Solutions, Indefinite Center\")\n        end\n    end\n    ca = Complex(a.x, a.y)\n    cb = Complex(b.x, b.y)\n    d = (ca + cb)/2\n    tfd = tformtranslate([real(d), imag(d)])\n    tfr = tformrotate(angle(cb-ca))\n    tfm = tfd*tfr\n    u = abs(cb-ca)/2\n    r-u > -5eps(r) || return(cp, \"No Solution, Radius Too Small\")\n    if r-u < 5eps(r)\n        push!(cp, Circle(apply(Point, tfm*[0.0, 0.0]), r))\n        return return (cp, \"Single Solution, Degenerate Centers\")\n    end\n    v = sqrt(r^2 - u^2)\n    for w in [v, -v]\n        push!(cp, Circle(apply(Point, tfm*[0.0, w]), r))\n    end\n    return (cp, \"Two Solutions\")\nend\n", "meta": {"hexsha": "050bcdea117117802947ce7dcdd25833fc3f1753", "size": 1136, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/circles-of-given-radius-through-two-points-1.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/circles-of-given-radius-through-two-points-1.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/circles-of-given-radius-through-two-points-1.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0476190476, "max_line_length": 72, "alphanum_fraction": 0.5625, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7735071107304793}}
{"text": "using Measurements\nusing Printf\ninclude(\"/home/jefter66/Projects/Lablib/src/Stats.jl\")\ninclude(\"/home/jefter66/Projects/Lablib/src/LeastSquares.jl\")\nγ(h1,h3) = return (h1) / (h1 - h3);\n\nΔh = 0.1;\n\nh1 = [18.1 ± Δh, 16.0 ± Δh, 17.6 ± Δh];\nh3 = [5.7, 4,5.1];\n\nɣs = [γ(h1[1],h3[1]), γ(h1[2],h3[2]), γ(h1[3],h3[3])];\ndeviation(ɣs);\n\nA(d) = return π * (d^2 / 4);\n# ΔA = 0.00001;\n\nP0 = 691 * 133.322 ± 0.01; # ΔP = 0.01;\ng = 9.81;\n\nd = 0.016 ± 0.001; # Δd = 0.001;\nm = 0.0167 ± 0.0001; # Δm = 0.0001;\nV = 0.0104  ± 0.0001; # ΔV = 0.0001;\nP = (m * g)/A(d) + P0;\nT = 1.2  ± 0.01; # ΔT = 0.01;\n\n𝛄 = 4 * π^2 * ((m * V)/(P * A(d)^2 * T^2));\n#x, Δx = m * V, Δm * V + ΔV * m;\n#y, Δy = P*A(d)^2 * T^2, 2*T*ΔT*(P*A(d)^2)  +  (ΔP * A(d)^2 + 2 * A(d) * ΔA * P);\n#Δ𝛄 = 4 * π^2 * (Δx * y + Δy * x) / (y^2);\n\n\n@printf(\"𝛄 = %.6f ± %.6f\", 𝛄.val, 𝛄.err);\n\n\n\nx = [24.7,1.0,-196.0,97.0];\ny = [69.2,62.8,17.7,82.3];\n\n\nleastSquares(x,y);\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "6dc33c85b78a84801893b07d0692fcedca1c1c46", "size": 919, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Fisica experimental/02/06/p6-calcs.jl", "max_stars_repo_name": "jefter66/notes", "max_stars_repo_head_hexsha": "adf8753b166162dcb898470932db2235c5d5966b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Fisica experimental/02/06/p6-calcs.jl", "max_issues_repo_name": "jefter66/notes", "max_issues_repo_head_hexsha": "adf8753b166162dcb898470932db2235c5d5966b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Fisica experimental/02/06/p6-calcs.jl", "max_forks_repo_name": "jefter66/notes", "max_forks_repo_head_hexsha": "adf8753b166162dcb898470932db2235c5d5966b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0196078431, "max_line_length": 81, "alphanum_fraction": 0.4733405876, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7735071107263272}}
{"text": "using CompEcon\nusing Dierckx\nusing Statistics\n\n\nlinspace(a,b,n) = range(a, stop=b, length=n)\n\n# Create functions to test against\n@. f1(x, y) = sin(x) * cos(y)\n@. f2(x, y) = exp(x) * cos(y)\n@. f3(x, y) = 1.5 + log(x * y)\nfs = [f1, f2, f3]\nnf = length(fs)\n\nx = collect(linspace(.5, 2, 35))\ny = collect(linspace(.2, 4, 35))\n\nfunction compare_D_CE_levels(f::Function, x::Array{Float64, 1}, y::Array{Float64, 1}, order::Int)\n\n    # Create Dierckx Spline (and data)\n    n = length(x)\n    z = f(x, y')\n    dspl = Spline2D(x, y, z; s=0.0, kx=order, ky=order)\n\n    # Create CompEcon Spline (and data)\n    cebasis_x = Basis(SplineParams(x, 0, order))\n    cebasis_y = Basis(SplineParams(y, 0, order))\n    cebasis = Basis(cebasis_x, cebasis_y)\n    xx = nodes(cebasis)[1]\n    yy = f(xx[:, 1], xx[:, 2])\n    c, bs = funfitxy(cebasis, xx, yy)\n\n    # Evaluate Splines on finer grid\n    xfine = collect(linspace(x[1], x[end], 2*n + 1))\n    yfine = collect(linspace(y[1], y[end], 2*n + 1))\n    zfine = f(xfine, yfine')\n\n    deval = Dierckx.evalgrid(dspl, xfine, yfine)\n    derr = abs.(zfine .- deval)\n\n    ceeval = CompEcon.funeval(c, cebasis, gridmake(xfine, yfine))\n    ceerr = abs.(zfine .- reshape(ceeval, 2*n+1, 2*n+1))\n\n    return derr, ceerr\nend\n\n\nfor i=1:nf\n\n    curr_f = fs[i]\n\n    derr1_levels, ceerr1_levels = compare_D_CE_levels(curr_f, x, y, 1)\n    derr2_levels, ceerr2_levels = compare_D_CE_levels(curr_f, x, y, 2)\n    derr3_levels, ceerr3_levels = compare_D_CE_levels(curr_f, x, y, 3)\n\n    println(\"Linear Approximation to Function\")\n    println(\"Dierckx Level Errors \\n\\t Max: $(maximum(derr1_levels)) \\n\\t Min: $(minimum(derr1_levels)) \\n\\t Mean: $(mean(derr1_levels))\")\n    println(\"CompEcon Level Errors \\n\\t Max: $(maximum(ceerr1_levels)) \\n\\t Min: $(minimum(ceerr1_levels)) \\n\\t Mean: $(mean(ceerr1_levels))\")\n\n    println(\"Quadratic Approximation to Function\")\n    println(\"Dierckx Level Errors \\n\\t Max: $(maximum(derr2_levels)) \\n\\t Min: $(minimum(derr2_levels)) \\n\\t Mean: $(mean(derr2_levels))\")\n    println(\"CompEcon Level Errors \\n\\t Max: $(maximum(ceerr2_levels)) \\n\\t Min: $(minimum(ceerr2_levels)) \\n\\t Mean: $(mean(ceerr2_levels))\")\n\n    println(\"Cubic Approximation to Function\")\n    println(\"Dierckx Level Errors \\n\\t Max: $(maximum(derr3_levels)) \\n\\t Min: $(minimum(derr3_levels)) \\n\\t Mean: $(mean(derr3_levels))\")\n    println(\"CompEcon Level Errors \\n\\t Max: $(maximum(ceerr3_levels)) \\n\\t Min: $(minimum(ceerr3_levels)) \\n\\t Mean: $(mean(ceerr3_levels))\")\n\nend\n", "meta": {"hexsha": "b8376bd757ca7ffff7b74486a25e7040d18db782", "size": 2482, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demo/dierckxcompare_2d.jl", "max_stars_repo_name": "magerton/BasisMatrices.jl", "max_stars_repo_head_hexsha": "093925e67c2452a1f2da872571aff84d93cfac2d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2016-10-26T02:36:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-22T22:05:15.000Z", "max_issues_repo_path": "demo/dierckxcompare_2d.jl", "max_issues_repo_name": "magerton/BasisMatrices.jl", "max_issues_repo_head_hexsha": "093925e67c2452a1f2da872571aff84d93cfac2d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 58, "max_issues_repo_issues_event_min_datetime": "2016-10-25T21:55:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T10:14:37.000Z", "max_forks_repo_path": "demo/dierckxcompare_2d.jl", "max_forks_repo_name": "magerton/BasisMatrices.jl", "max_forks_repo_head_hexsha": "093925e67c2452a1f2da872571aff84d93cfac2d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:47:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T23:07:07.000Z", "avg_line_length": 35.9710144928, "max_line_length": 142, "alphanum_fraction": 0.6522965351, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7735071079964614}}
{"text": "using .FFTW\nlaplacianunwrap(ϕ) = laplacianunwrap!(copy(ϕ))\nfunction laplacianunwrap!(ϕ::AbstractArray)\n    FFTW.set_num_threads(Threads.nthreads())\n    ϕ .+= 2π .* k(ϕ)\nend\n\n# Schofield and Zhu 2003, https://doi.org/10.1364/OL.28.001194\nk(ϕw) = 1 / 2π .* ∇⁻²(∇²_nw(ϕw) - ∇²(ϕw))  # (1)\n\n∇²(x) = -(2π)^ndims(x) / length(x) .* idct(pqterm(size(x)) .* dct(x))  # (2)\n\n∇⁻²(x) = -length(x) / (2π)^ndims(x) .* idct(dct(x) ./ pqterm(size(x)))  # (3)\n\n∇²_nw(ϕw) = cos.(ϕw) .* ∇²(sin.(ϕw)) .- sin.(ϕw) .* ∇²(cos.(ϕw))  # (in text)\n\n\npqterm(sz::NTuple{1}) = (1:sz[1]).^2  # 1D case\npqterm(sz::NTuple{2}) = [p^2 + q^2 for p in 1:sz[1], q in 1:sz[2]]  # 2D case\npqterm(sz::NTuple{3}) = [p^2 + q^2 + t^2 for p in 1:sz[1], q in 1:sz[2], t in 1:sz[3]]  # 3D case\npqterm(sz::NTuple{4}) = [p^2 + q^2 + t^2 + r^2 for p in 1:sz[1], q in 1:sz[2], t in 1:sz[3], r in 1:sz[4]]  # 4D case\n\n\"\"\"\n    laplacianunwrap(ϕ::AbstractArray)\n\nPerforms laplacian unwrapping on the input phase. (1D - 4D)\nThe phase has to be scaled to radians.\nThe implementation is close to the original publication: Schofield and Zhu 2003, https://doi.org/10.1364/OL.28.001194.\nIt is not the fastest implementation of laplacian unwrapping (doesn't use discrete laplacian).\n\"\"\"\nlaplacianunwrap, laplacianunwrap!", "meta": {"hexsha": "3367cb6bd08c9eb31e6955d4a6db142cdecf00d0", "size": 1260, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/laplacianunwrapping.jl", "max_stars_repo_name": "vfonov/MriResearchTools.jl", "max_stars_repo_head_hexsha": "324a52195bbc845a58afa16a3dd18dc245c54edf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/laplacianunwrapping.jl", "max_issues_repo_name": "vfonov/MriResearchTools.jl", "max_issues_repo_head_hexsha": "324a52195bbc845a58afa16a3dd18dc245c54edf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/laplacianunwrapping.jl", "max_forks_repo_name": "vfonov/MriResearchTools.jl", "max_forks_repo_head_hexsha": "324a52195bbc845a58afa16a3dd18dc245c54edf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6451612903, "max_line_length": 118, "alphanum_fraction": 0.6198412698, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897426182322, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7735071066356802}}
{"text": "\nfunction generate_window_functions_expr()\n    # x_exprW = :(clamp.(- border_in .+ abs.(scale .* (x .- offset))./(border_out-border_in),0,1))\n    x_exprW = :(clamp.(1 .-(abs.(scale .* (x .- offset)).-border_in)./(border_out .- border_in),0,1)) \n    x_exprW2 = :(clamp.((abs.(scale .* (x .- offset)).-border_in)./(border_out .- border_in),0,Inf))  # no outer border and starting from 0 at the inner border\n    x_exprRW = :(clamp.(1 .-(sqrt.(sum((scale .* (x .- offset)).^2)).-border_in)./(border_out .- border_in),0,1)) \n    # Attention: The function below returns the square distance to avoid sqrt followed by squaring in the gaussian\n    x_exprRW2 = :(clamp.((sum((scale .* (x .- offset)).^2).-border_in)./(border_out .- border_in),0,Inf))   # no outer border and starting from 0 at the inner border\n\n    functions = [  # see https://en.wikipedia.org/wiki/Window_function \n        (:(window_linear),  :(x -> T(prod(($x_exprW))))),\n        (:(window_edge),  :(x -> T(prod(($x_exprW).>0.5)))),\n        (:(window_hanning),  :(x -> T(prod(sinpi.(0.5 .* ($x_exprW)).^2)))),\n        (:(window_half_cos),  :(x -> T(prod(sinpi.(0.5 .* ($x_exprW)))))),\n        (:(window_hamming),  :(x -> T(prod(0.54 .-0.46.*cospi.(($x_exprW)))))),\n        (:(window_blackman_harris),  :(x -> T(prod(0.35875 .- 0.48829.*cospi.($x_exprW).+0.14128.*cospi.(2 .*$x_exprW).-0.01168.*cospi.(3 .*$x_exprW))))),\n        (:(window_gaussian),  :(x -> T(prod(exp.(-2 .* abs2.($x_exprW2)))))),\n        (:(window_radial_linear),  :(x -> T($x_exprRW))),\n        (:(window_radial_edge),  :(x -> T(($x_exprRW).>0.5))),\n        (:(window_radial_hanning),  :(x -> T(sinpi.(0.5 .* ($x_exprRW)).^2))),\n        (:(window_radial_hamming),  :(x -> T((0.54 .-0.46.*cospi.(($x_exprRW)))))),\n        (:(window_radial_blackman_harris),  :(x -> T((0.35875 .-0.48829.*cospi.($x_exprRW).+0.14128.*cospi.(2 .*$x_exprRW).-0.01168.*cospi.(3 .*$x_exprRW))))),\n        (:(window_radial_gaussian),  :(x -> T(exp.(-2 .*($x_exprRW2))))),\n    ]\n    x_expr8 = :(exp(.- sum(abs2.(x .- offset).*scale))) # scale is 1/(2 sigma^2)\n    return functions\nend\n\n# we automatically generate the functions for different windows like hanning \nfor F in generate_window_functions_expr() \n    # default functions with certain offset and scaling behavior\n    @eval function $(F[1])(::Type{T}, size::NTuple{N, Int};\n                           offset=CtrFT,\n                           scale=ScaFTEdge, border_in=0.8, border_out=1.0, dims=ntuple(+, N)) where{N, T} \n        scale_init = get_scale(size, scale)\n        scale = ntuple(i -> i ∈ dims ? scale_init[i] : zero(scale_init[1]), N)\n        offset = get_offset(size, offset)\n        IndexFunArray(T, $(F[2]), size) \n    end\n    \n    # change order of offset and scale\n    @eval function $(F[1])(size::NTuple{N, Int}; \n                           offset=CtrFT, \n                           scale=ScaFTEdge, border_in=0.8, border_out=1.0, dims=ntuple(+, N)) where{N} \n        T = $DEFAULT_T \n        $(F[1])(T, size, scale=scale, offset=offset, border_in=border_in, border_out=border_out, dims=dims) \n    end\n\n    # convenient wrapper to provide an array as input\n    @eval function $(F[1])(arr::AbstractArray{T, N}; \n                           offset=CtrFT, \n                           scale=ScaFTEdge, border_in=0.8, border_out=1.0, dims=ntuple(+, N)) where{N, T} \n        $(F[1])(default_type(T, $DEFAULT_T), size(arr), scale=scale, offset=offset, border_in=border_in, border_out=border_out, dims=dims)\n    end\n\n    @eval export $(F[1])\nend\n\n\n", "meta": {"hexsha": "cad3edebdf72d790e675972ae06071a48d5f9d38", "size": 3515, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/window_ifas.jl", "max_stars_repo_name": "bionanoimaging/IndexFunArray.jl", "max_stars_repo_head_hexsha": "7ed1a50052077c570daffb22257004e5fc547772", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-21T02:27:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T03:04:51.000Z", "max_issues_repo_path": "src/window_ifas.jl", "max_issues_repo_name": "bionanoimaging/IndexFunArray.jl", "max_issues_repo_head_hexsha": "7ed1a50052077c570daffb22257004e5fc547772", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-03-21T15:57:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T13:12:43.000Z", "max_forks_repo_path": "src/window_ifas.jl", "max_forks_repo_name": "bionanoimaging/IndexFunArrays.jl", "max_forks_repo_head_hexsha": "7ed1a50052077c570daffb22257004e5fc547772", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.5833333333, "max_line_length": 165, "alphanum_fraction": 0.5769559033, "num_tokens": 1131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783526, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7735070957037604}}
{"text": "# All square roots are periodic when written as continued fractions and can be\n# written in the form:\n#\n# √N = a0 + 1 / (a1 + 1 / (a2 + 1 / (a3 + ...)))\n#\n# For example, let us consider √23:\n# √23 = 4 + √23 − 4 = 4 + 1 / (1 / (√23 − 4)) = 4 + 1 / (1 + (√23 − 3) / 7)\n#\n# If we continue we would get the following expansion:\n# √23 = 4 + 1 / (1 + 1 / (3 + 1 / (1 + 1 / (8 + ...))))\n#\n# The process can be summarised as follows:\n#\n# a0 = 4, 1 / (23√ - 4) = (√23 + 4) / 7 = 1 + (√23 - 3) / 7\n# a1 = 1, 7 / (23√ - 3) = 7 * (23√+3)14 = 3 + (√23 - 3) / 2\n# a2 = 3, 2 / (23√ - 3) = 2 * (23√+3)14 = 1 + (√23 - 4) / 7\n# a3 = 1, 7 / (23√ - 4) = 7 * (23√+4)7 = 8 + √23 - 4\n# a4 = 8, 1 / (23√ - 4) = (√23 + 4) / 7 = 1 + (√23 - 3) / 7\n# a5 = 1, 7 / (23√ - 3) = 7 * (√23 + 3) / 14 = 3 + (√23 - 3) / 2\n# a6 = 3, 2 / (23√ - 3) = 2 * (√23 + 3) / 14 = 1 + (√23 - 4) / 7\n# a7 = 1, 7 / (23√ - 4) = 7 * (√23 + 4) / 7 = 8 + √23 - 4\n# \n# It can be seen that the sequence is repeating. For conciseness, we use the\n# notation √23 = [4;(1,3,1,8)], to indicate that the block (1,3,1,8) repeats\n# indefinitely.\n#\n# The first ten continued fraction representations of (irrational) square roots\n# are:\n#\n# √2 = [1;(2)], period=1\n# √3 = [1;(1,2)], period=2\n# √5 = [2;(4)], period=1\n# √6 = [2;(2,4)], period=2\n# √7 = [2;(1,1,1,4)], period=4\n# √8 = [2;(1,4)], period=2\n# √10 = [3;(6)], period=1\n# √11 = [3;(3,6)], period=2\n# √12 = [3;(2,6)], period=2\n# √13 = [3;(1,1,1,1,6)], period=5\n#\n# Exactly four continued fractions, for N ≤ 13, have an odd period.\n#\n# How many continued fractions for N ≤ 10000 have an odd period?\n\nusing ProjectEulerSolutions\n\n# A continued fraction period ends when the a,m,d tuple matches a previously\n# seen one.  Just maintain the list of tuples until one matches, measuring the\n# length of the continued fraction period to find the odd numbered ones.\nfunction p064solution(n_max::Integer=10)::Integer\n\n    odd_count = 0\n    for n in 2:n_max\n        a0 = floor(sqrt(n))\n        if sqrt(n) == a0\n            continue\n        end\n        a0 = Integer(a0)\n        a, m, d = a0, 0, 1\n        s = Array{Tuple{Integer, Integer, Integer}, 1}()\n        while true\n            m = d * a - m\n            d = div(n - m * m, d)\n            a = div(a0 + m, d)\n            key = (a, m, d)\n            if length(s) > 0 && key == s[1]\n                break\n            else\n                push!(s, (a, m, d))\n            end\n        end\n        if length(s) % 2 == 1\n            odd_count += 1\n        end\n    end\n    return odd_count\nend\n\np064 = Problems.Problem(p064solution)\n\nProblems.benchmark(p064, 10_000)\n", "meta": {"hexsha": "ba30aa6ae2d4a62c76bd8abb91fa0d01c6c23ae1", "size": 2592, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/064.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/064.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/064.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6097560976, "max_line_length": 79, "alphanum_fraction": 0.4980709877, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240125464115, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7734475265178864}}
{"text": "\n# Example of logistic map from Keith Briggs's 2006 paper\n\n\nusing ExactReals\n\n\n\"Iterate the function `f` for `n` steps, starting at `x0`.\"\nfunction iterates(f, n, x0)\n\n    x = x0\n\n    for i in 1:n\n        x = f(x)\n    end\n\n    return x\nend\n\n\"Logistic map\"\nlogistic(a, x) = a * x * (1 - x)\nlogistic(a) = x -> logistic(a, x)\n\na = rationalize(3.999)\nx0 = rationalize(0.9)\nn = 54\n\ny = iterates(logistic(ExactReal(a)), n, ExactReal(x0))\n\n@show y > ExactReal(1//2)\n\n# Floating point:\n\nz = iterates(logistic(float(a)), n, float(x0))\n\n@show z > 0.5\n\nnothing\n\n#\n# using IntervalArithmetic\n#\n# x = interval(big\"0.9\")\n#\n# iterates(logistic(@biginterval(3.999)), 53, @biginterval(0.9)) |> showfull\n#\n# iterates(logistic(I\"3.999\"), 53, I\"0.9\")\n#\n# showfull(I\"3.999\")\n#\n# # example where double precision is on wrong side of 1/2:\n# iterates(logistic(3.999), 54, 0.9)\n#\n# iterates(logistic(@biginterval(3.999)), 54, @biginterval(0.9)) |> showfull\n#\n#\n# @time y = iterates(logistic(ExactReal(3999//1000)), 54, ExactReal(9//10))\n#\n# y > ExactReal(1//2)\n", "meta": {"hexsha": "bcfcddcfaece58198772ff20fe5e47efbb187c66", "size": 1036, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/logistic.jl", "max_stars_repo_name": "JuliaTagBot/ExactReals.jl", "max_stars_repo_head_hexsha": "17f0eada34523a7b0692e79435c90eaaeb097daf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-01-07T12:43:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T18:30:08.000Z", "max_issues_repo_path": "examples/logistic.jl", "max_issues_repo_name": "JuliaTagBot/ExactReals.jl", "max_issues_repo_head_hexsha": "17f0eada34523a7b0692e79435c90eaaeb097daf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-01-07T06:18:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-08T03:39:39.000Z", "max_forks_repo_path": "examples/logistic.jl", "max_forks_repo_name": "JuliaTagBot/ExactReals.jl", "max_forks_repo_head_hexsha": "17f0eada34523a7b0692e79435c90eaaeb097daf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:45:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:45:16.000Z", "avg_line_length": 17.2666666667, "max_line_length": 76, "alphanum_fraction": 0.6322393822, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7734475259210377}}
{"text": "function Sch_solve_Emin_cg( LF::LF3dGrid, Vpot, Ncol::Int64;\n                            v0 = nothing,\n                            α_t=3e-5, Niter=1000,\n                            verbose=false )\n  #\n  Npoints = LF.Nx * LF.Ny * LF.Nz\n  ΔV = LF.LFx.h * LF.LFy.h * LF.LFz.h\n  #\n  # Setup trial solution\n  #\n  if v0 == nothing\n    # random trial solution\n    srand(1234)\n    v = rand( Npoints, Ncol )\n    v = orthonormalize( LF, v )\n  else\n    v = copy(v0)\n    # v0 is assumed to be ortonormalized\n  end\n  #\n  Energies = calc_Energies( LF, Vpot, v )\n  #\n  Etot_old = Energies.Total\n  #\n  g     = zeros(Float64,Npoints,Ncol)\n  g_old = zeros(Float64,Npoints,Ncol)\n  d     = zeros(Float64,Npoints,Ncol)\n  d_old = zeros(Float64,Npoints,Ncol)\n  #\n  β = 0\n  α = 0\n  for iter = 1:Niter\n    g = calc_grad( LF, Vpot, v )\n    #\n    if iter != 1\n      β = trace( g' * g)/trace( g_old'*g_old )\n      #β = trace( (g-g_old)'*g ) / trace( g_old'*g_old )\n      #β = trace( (g-g_old)'*g )/ trace( (g-g_old)'*d )\n    end\n    d = -g + β*d_old\n    #\n    # compute gradient at trial step\n    #\n    v2 = orthonormalize(LF, v + α_t*d)\n    g_t = calc_grad( LF, Vpot, v2 )\n    #\n    # compute estimate of best step and update current trial vectors\n    #\n    denum = trace( (g - g_t)' * d )\n    if denum != 0.0\n      α = abs( α_t * trace( g'*d )/denum )\n    else\n      α = 0.0\n    end\n    v = v + α*d\n    #\n    v = orthonormalize( LF, v )\n    Energies = calc_Energies( LF, Vpot, v )\n    Etot = Energies.Total\n    #\n    if verbose\n      @printf(\"%8d %16.9e %16.9e\\n\", iter, Etot, abs(Etot-Etot_old))\n    end\n    if abs(Etot-Etot_old) < 1.e-7\n      if verbose\n        @printf(\"Emin CG converges in %8d iterations\\n\", iter)\n      end\n      break\n    end\n    Etot_old = Etot\n    #\n    g_old = g[:,:]\n    d_old = d[:,:]\n  end\n  return Energies, v\nend\n", "meta": {"hexsha": "70a0f18b3403882e37b5411744ee3f3a96600cea", "size": 1818, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LF/sch_3d/Sch_solve_Emin_cg.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "LF/sch_3d/Sch_solve_Emin_cg.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LF/sch_3d/Sch_solve_Emin_cg.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 23.6103896104, "max_line_length": 68, "alphanum_fraction": 0.5264026403, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164656, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.773447525091612}}
{"text": "\"\"\"\n    P(n, τ)\n\nReturns the value of the Legendre polynomial of degree `n` at `τ`.\n(Recursive function used in `../test`).\n\"\"\"\nfunction P(n::Integer, τ::T) where T <: AbstractFloat\n    if n == 0\n        return one(T)\n    elseif n == 1\n        return τ\n    else\n        return ( (2n-1) * τ * P(n-1, τ) - (n-1) * P(n-2, τ) ) / n\n    end\nend\n\n\"\"\"\n    legendre_polys!(P, τ)\n\nIf `τ` is a scalar, then `P` is a vector with `P[n+1]` equal to the value \nof the Legendre polynomial of degree `n` at `τ`.\n\nIf `τ` is a vector, then `P` is a matrix with `P[n+1,j]` equal to the value\nof the Legendre polynomial of degree `n` at `τ[j]`.\n\"\"\"\nfunction legendre_polys!(P::AbstractVector{T}, τ::T) where T <: AbstractFloat\n    I = length(P)\n    if I ≥ 1\n        P[1] = one(T)\n    end\n    if I ≥ 2\n        P[2] = τ\n    end\n    for j = 1:I, i = 1:I-2\n        P[i+2] = ((2i+1) * τ * P[i+1] - i * P[i] ) / (i+1)\n    end\nend\n\nfunction legendre_polys!(P::AbstractMatrix{T}, τ::AbstractVector{T}\n                        ) where T <: AbstractFloat\n    I = size(P, 1)\n    J = size(P, 2)\n    @argcheck length(τ) == J\n    if I ≥ 1\n        for j = 1:J\n            P[1,j] = one(T)\n        end\n    end\n    if I ≥ 2\n        for j = 1:J\n            P[2,j] = τ[j]\n        end\n    end\n    for j = 1:J, i = 1:I-2\n        P[i+2,j] = ((2i+1) * τ[j] * P[i+1,j] - i * P[i,j] ) / (i+1)\n    end\nend\n\n\"\"\"\n    dP(n, τ)\n\nReturns the value of the derivative of the Legendre polynomial of degree `n` \nat `τ`.  (Recursive function used in `../test`).\n\"\"\"\nfunction dP(n::Integer, τ::T) where T <: AbstractFloat\n    if n == 0\n        return zero(T)\n    elseif n == 1\n        return one(T)\n    else\n        return ( (2n-1) * τ * dP(n-1, τ) - n * dP(n-2, τ) ) / ( n - 1 )\n    end\nend\n\nfunction deriv_legendre_polys!(dP::AbstractVector{T}, τ::T\n                              ) where T <: AbstractFloat\n    I = length(dP)\n    if I ≥ 1\n        dP[1] = zero(T)\n    end\n    if I ≥ 2\n        dP[2] = one(T)\n    end\n    for i = 1:I-2\n        dP[i+2] = ( (2i+1) * τ * dP[i+1] - (i+1) * dP[i] ) / i\n    end\nend\n\nfunction deriv_legendre_polys!(dP::AbstractMatrix{T}, τ::AbstractVector{T}\n                               ) where T <: AbstractFloat\n    I = size(dP, 1)\n    J = size(dP, 2)\n    @argcheck length(τ) == J\n    if I ≥ 1\n        for j = 1:J\n            dP[1,j] = zero(T)\n        end\n    end\n    if I ≥ 2\n        for j = 1:J\n            dP[2,j] = one(T)\n        end\n    end\n    for j = 1:J, i = 1:I-2\n        dP[i+2,j] = ((2i+1) * τ[j] * dP[i+1,j] - (i+1) * dP[i,j] ) / i\n    end\nend\n\n\"\"\"\n    pcwise_t, pcwise_U = evaluate_pcwise_poly(U, t, ppI, store)\n\"\"\"\nfunction evaluate_pcwise_poly!(U::Vector{Vector{T}}, t::OffsetVector{T},\n                               ppI::Integer, store::Store{T}\n                              ) where { T <: AbstractFloat }\n    τ = range(-one(T), stop=one(T), length=ppI) \n    pcwise_t, pcwise_U = evaluate_pcwise_poly!(U, t, τ, store) \n    return pcwise_t, pcwise_U\nend\n\nfunction evaluate_pcwise_poly!(U::Vector{Vector{T}}, t::OffsetVector{T},\n                               τ::AbstractVector{T}, store::Store{T}\n                              ) where T <: AbstractFloat \n    N = length(U)\n    ppI = length(τ)\n    @argcheck ppI ≤ store.ppImax\n    pcwise_t = Array{T}(undef, ppI, N)\n    pcwise_U = similar(pcwise_t) \n    evaluate_pcwise_poly!(pcwise_t, pcwise_U, U, t, τ, store) \n    return pcwise_t, pcwise_U\nend\n\nfunction evaluate_pcwise_poly!(pcwise_t::Matrix{T}, pcwise_U::Matrix{T},\n                               U::Vector{Vector{T}}, t::OffsetVector{T},\n                               τ::AbstractVector{T}, store::Store{T}\n                              ) where { T <: AbstractFloat }\n    N = length(U)\n    pts_per_interval = length(τ)\n    @argcheck size(pcwise_t) == (pts_per_interval, N)\n    @argcheck size(pcwise_U) == (pts_per_interval, N)\n    @argcheck length(t) == N+1\n    rmax = store.rmax\n    Ψ = view(store.Ψ, 1:rmax, 1:pts_per_interval)\n    legendre_polys!(Ψ, τ)\n    for n = 1:N\n        rn = length(U[n])\n        for m = 1:pts_per_interval\n            pcwise_t[m,n] = ( (1-τ[m])*t[n-1] + (1+τ[m])*t[n] ) / 2\n            s = zero(T)\n            for j = 1:rn\n                s += U[n][j] * Ψ[j,m]\n            end\n            pcwise_U[m,n] = s\n        end\n    end\nend\n\nfunction Fourier_Legendre_coefs(u::Function, r::Integer, t::OffsetArray{T},\n                                store::Store{T}) where T <: AbstractFloat\n    N = length(t) - 1\n    rmax = store.rmax\n    a = Vector{Vector{T}}(undef, N)\n    M = store.Mmax\n    τ, wτ = rule(store.legendre[M])\n    Ψ = view(store.Ψ, 1:r, 1:M)\n    legendre_polys!(Ψ, τ)\n    for n = 1:N\n        a[n] = Vector{T}(undef, r)\n        for j = 1:r\n            s = zero(T)\n            for m = 1:M\n                tnm = ( (1-τ[m])*t[n-1] + (1+τ[m])*t[n] ) / 2\n                s += wτ[m] * u(tnm) * Ψ[j,m]\n            end\n            a[n][j] = (2j-1) * s / 2\n        end\n    end\n    return a\nend\n\nfunction reconstruction_pts(In::Tuple{T,T}, r::Integer) where T <: AbstractFloat\n    tnm1, tn = In\n    tstar = reconstruction_pts(T, r)\n    tstar[0] = tnm1\n    for m = 1:r-1\n        tstar[m] = ( ( 1 - tstar[m] ) * tnm1 + ( tstar[m] + 1 ) * tn ) / 2\n    end\n    tstar[r] = tn\n    return tstar\nend\n\nfunction reconstruction_pts(::Type{T}, r::Integer) where T <: AbstractFloat\n    right = GaussQuadrature.right\n    τ, wτ = GaussQuadrature.legendre(T, r, right)\n    return OffsetArray([ -one(0); τ ], 0:r)\nend\n\n\"\"\"\n    Uhat = reconstruction(U, u0, store)\n\"\"\"\nfunction reconstruction(U::Vector{Vector{T}}, u0::T, \n                        store::Store{T}) where T <: AbstractFloat\n    Uhat = reconstruction(U, u0, store.rmax)\n    return Uhat\nend\n\n\"\"\"\n    Uhat = reconstruction(U, u0, rmax)\n\"\"\"\nfunction reconstruction(U::Vector{Vector{T}}, u0::T, \n\t                rmax::Integer) where T <: AbstractFloat\n    N = length(U)\n    Uhat = Vector{Vector{T}}(undef, N)\n    pow = OffsetArray{T}(undef, 0:rmax)\n    pow[0] = one(T)\n    for n = 1:rmax\n        pow[n] = -pow[n-1]\n    end\n    r1 = length(U[1])\n    @argcheck r1+1 ≤ rmax\n    U_left = zero(T)   # U_left  = U(t[0] + 0) = value at the left endpoint.\n    U_right = zero(T)  # U_right = U(t[1] - 0) = value at the right endpoint.\n    for j = 1:r1\n        U_left += pow[j-1] * U[1][j]\n        U_right += U[1][j]\n    end\n    jumpU0 = U_left - u0\n    Uhat[1] = Vector{T}(undef, r1+1)\n    Uhat[1][1:r1] .= U[1][1:r1]\n    Uhat[1][r1] += pow[r1] * jumpU0 / 2\n    Uhat[1][r1+1] = - pow[r1] * jumpU0 / 2\n    for n = 2:N\n        rn = length(U[n])\n        @argcheck rn + 1 ≤ rmax\n        U_left = zero(T) # U_left = U(t[n-1] + 0 )\n        for j = 1:rn\n            U_left += pow[j-1] * U[n][j]\n        end\n        jumpUnm1 = U_left - U_right\n        Uhat[n] = Vector{T}(undef, rn+1)\n        Uhat[n][1:rn] .= U[n][1:rn]\n        Uhat[n][rn] += pow[rn] * jumpUnm1 / 2\n        Uhat[n][rn+1]  = -pow[rn] * jumpUnm1 / 2\n        U_right = zero(T) # U_right = U(t[n] - 0 )\n        for j = 1:rn\n            U_right += U[n][j]\n        end\n    end\n    return Uhat\nend\n\nfunction max_order(U::Vector{Vector{T}}) where T <: AbstractFloat\n    N = length(U)\n    r = length(U[1])\n    for n = 2:N\n        rn = length(U[n])\n        r = max(r, rn)\n    end\n    return r\nend\n\nfunction jumps(U::Vector{Vector{T}}, t::OffsetVector{T}, \n\tu0::T) where T <: AbstractFloat\n    N = length(t) - 1\n    r = max_order(U)\n    JU = OffsetVector{T}(undef, 0:N-1)\n    U_left = u0\n    U_right = zero(T)\n    pow = ones(T, r)\n    pow[2:2:r] .= -one(T)\n    for n = 1:N\n\tU_left = zero(T)\n\tfor j = 1:r\n\t    U_left += pow[j] * U[n][j]\n\tend\n\tJU[n-1] = U_left\n    end\n    JU[0] -= u0\n    for n = 2:N\n\tU_right = sum(U[n-1])\n\tJU[n-1] -= U_right\n    end\n    return JU\nend\n\nfunction dG_error_estimator(JU::OffsetVector{T}, t::OffsetVector{T},\n        r::Integer, τ::AbstractVector{T}) where T <: AbstractFloat\n    N = length(t) - 1\n    pts_per_interval = length(τ)\n    pcwise_t = Matrix{T}(undef, pts_per_interval, N)\n    pcwise_approx_err = similar(pcwise_t)\n    Ψ = Matrix{T}(undef, r+1, pts_per_interval)\n    legendre_polys!(Ψ, τ)\n    if r % 2 == 0\n        sign = 1\n    else\n        sign = -1\n    end\n    for n = 1:N\n        for m = 1:pts_per_interval\n            pcwise_t[m,n] = ( (1-τ[m])*t[n-1] + (1+τ[m])*t[n] ) / 2\n            pcwise_approx_err[m,n] = (sign/2) * JU[n-1] * ( Ψ[r+1,m] - Ψ[r,m] )\n        end\n    end\n    return pcwise_t, pcwise_approx_err\nend\n\nfunction dG_error_estimator(JU::OffsetVector{T}, t::OffsetVector{T},\n        r::Integer, pts_per_interval::Integer) where T <: AbstractFloat\n    τ = range(-1.0, 1.0, length=pts_per_interval)\n    return dG_error_estimator(JU, t, r, τ)\nend\n", "meta": {"hexsha": "087cdc694c46718538b8a4d622da2f98201557eb", "size": 8600, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/parts/legendre_utils.jl", "max_stars_repo_name": "billmclean/FractionalTimeDG.jl", "max_stars_repo_head_hexsha": "165bd96ac1355befaed4dff25172cc255e883768", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/parts/legendre_utils.jl", "max_issues_repo_name": "billmclean/FractionalTimeDG.jl", "max_issues_repo_head_hexsha": "165bd96ac1355befaed4dff25172cc255e883768", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/parts/legendre_utils.jl", "max_forks_repo_name": "billmclean/FractionalTimeDG.jl", "max_forks_repo_head_hexsha": "165bd96ac1355befaed4dff25172cc255e883768", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5641025641, "max_line_length": 80, "alphanum_fraction": 0.511627907, "num_tokens": 3056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7734475244947633}}
{"text": "\r\nfunction step_size(x0, zero_tol = 1e-15)\r\n    #=\r\n    if abs(x0) <= zero_tol\r\n        x0 = copysign(zero_tol, x0)\r\n    end\r\n    =#\r\n    h = sqrt( eps(x0) )\r\n    return h\r\nend\r\n\r\nfunction step_size_cbrt(x0, zero_tol = 1e-15)\r\n    #=\r\n    if abs(x0) <= zero_tol\r\n        x0 = copysign(zero_tol, x0)\r\n    end\r\n    =#\r\n    h = cbrt( eps(x0) )\r\n    return h\r\nend\r\n\r\n\r\n\r\nfunction numdiff_fw(f, x0)\r\n    # f: R -> R\r\n    #=\r\n    h = step_size(x0)\r\n    x1 = x0 + h\r\n    f0 = f(x0)\r\n    f1 = f(x1)\r\n    g = (f1 - f0) / h\r\n    return g\r\n    =#\r\n    h = step_size(x0)\r\n    numdiff_fw(f, x0, h)\r\nend\r\n\r\nfunction numdiff_fw(f, x0, h)\r\n    # f: R -> R\r\n    f0 = f(x0)\r\n    numdiff_fw(f, x0, h, f0)\r\nend\r\n\r\nfunction numdiff_fw(f, x0, h, f0)\r\n    # f: R -> R\r\n    x1 = x0 + h\r\n    f1 = f(x1)\r\n    g = (f1 - f0) / h\r\nend\r\n\r\n\r\n\r\nfunction numdiff_bw(f, x0)\r\n    # f: R -> R\r\n     #=\r\n    h = step_size(x0)\r\n    x1 = x0 - h\r\n    f0 = f(x0)\r\n    f1 = f(x1)\r\n    g = (f0 - f1) / h\r\n    =#\r\n    h = step_size(x0)\r\n    numdiff_bw(f, x0, h)\r\nend\r\n\r\nfunction numdiff_bw(f, x0, h)\r\n    f0 = f(x0)\r\n    numdiff_bw(f, x0, h, f0)\r\nend\r\n\r\nfunction numdiff_bw(f, x0, h, f0)\r\n    x1 = x0 - h\r\n    f1 = f(x1)\r\n    g = (f0 - f1) / h\r\nend\r\n\r\nfunction numdiff_central(f, x0)\r\n    # f: R -> R\r\n    h = step_size_cbrt(x0)\r\n    xm1 = x0 - h\r\n    xp1 = x0 + h\r\n    fm1 = f(xm1)\r\n    fp1 = f(xp1)\r\n    g = (fp1 - fm1) / (2*h)\r\n    return g\r\nend\r\n\r\n\r\nfunction gradient_fw(f, x0)\r\n    # f: R^n -> R\r\n    # g_i = df / dx_i\r\n    h = step_size.(x0)\r\n    return gradient_fw(f, x0, h)\r\nend\r\n\r\nfunction gradient_fw(f, x0, h)\r\n    # f: R^n -> R\r\n    # g_i = df / dx_i\r\n    f0 = f(x0)\r\n    return gradient_fw(f, x0, h, f0)\r\nend\r\n\r\nfunction gradient_fw(f, x0, h, f0)\r\n    # f: R^n -> R\r\n    # g_i = df / dx_i\r\n    g = similar(x0)\r\n    x1 = copy(x0)\r\n    for kk = 1:length(x0)\r\n        x1[kk] += h[kk] \r\n        f1 = f(x1)\r\n        g[kk] = (f1 - f0) / h[kk] \r\n        x1[kk] -= h[kk] \r\n    end\r\n    return g\r\nend\r\n\r\n\r\nfunction directional_diff_fw(f, x0, d)\r\n    h = step_size( norm(d) )\r\n    return directional_diff_fw(f, x0, d, h)\r\nend\r\n\r\nfunction directional_diff_fw(f, x0, d, h)\r\n    f0 = f(x0)\r\n    return directional_diff_fw(f, x0, d, h, f0)\r\nend\r\n\r\nfunction directional_diff_fw(f, x0, d, h, f0)\r\n\r\n    g = zero(eltype(x0))\r\n    \r\n    x1 = x0 + d * h\r\n    f1 = f(x1)\r\n\r\n    g = (f1 - f0) / h\r\n\r\n    return g\r\nend\r\n\r\n\r\nfunction jacobian_fw(f, x0)\r\n    # f: R^n -> R^m\r\n    # g_ij = df_i / dx_j\r\n\r\n    h = step_size.(x0)  # n-by-1\r\n    return jacobian_fw(f, x0, h)\r\nend\r\n\r\nfunction jacobian_fw(f, x0, h)\r\n    # f: R^n -> R^m\r\n    # g_ij = df_i / dx_j\r\n\r\n    f0 = f(x0)                  # m-by-1\r\n    return jacobian_fw(f, x0, h, f0)   # m-by-n\r\nend\r\n\r\nfunction jacobian_fw(f, x0, h, f0)\r\n    # f: R^n -> R^m\r\n    # g_ij = df_i / dx_j\r\n\r\n    jac = zeros(eltype(f0), length(f0), length(x0)) # m-by-n\r\n    x1 = copy(x0)\r\n    for kk = 1:length(x0)\r\n        x1[kk] += h[kk] \r\n        f1 = f(x1)\r\n        jac[:, kk] = (f1 .- f0) ./ h[kk]\r\n        x1[kk] -= h[kk] \r\n    end\r\n    return jac\r\nend\r\n\r\n\r\nfunction jacobian_fw!(jac, f, x0)\r\n    # f: R^n -> R^m\r\n    # g_ij = df_i / dx_j\r\n\r\n    h = step_size.(x0)  # n-by-1\r\n    return jacobian_fw!(jac, f, x0, h)\r\nend\r\n\r\nfunction jacobian_fw!(jac, f, x0, h)\r\n    # f: R^n -> R^m\r\n    # g_ij = df_i / dx_j\r\n\r\n    f0 = f(x0)                  # m-by-1\r\n    return jacobian_fw!(jac, f, x0, h, f0)   # m-by-n\r\nend\r\n\r\nfunction jacobian_fw!(jac, f, x0, h, f0)\r\n    # f: R^n -> R^m\r\n    # g_ij = df_i / dx_j\r\n\r\n    f1 = similar(f0)\r\n    x1 = copy(x0)\r\n    for kk = 1:length(x0)\r\n        x1[kk]     += h[kk] \r\n        f1         .= f(x1)\r\n        jac[:, kk] .= (f1 .- f0) ./ h[kk]\r\n        x1[kk]     -= h[kk] \r\n    end\r\n    return jac\r\nend\r\n\r\n", "meta": {"hexsha": "c9d56f469000e8b7a0f5fb469620950fa1e3f598", "size": 3723, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/common/numder/src/num_diff.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "__lib__/math/common/numder/src/num_diff.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "__lib__/math/common/numder/src/num_diff.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.25, "max_line_length": 61, "alphanum_fraction": 0.4593070105, "num_tokens": 1486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565739, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7734475222390629}}
{"text": "# This file includes the MonteCarlo simulation of PSK modulation scheme and compares \n# the numerical results with the theoretical results. \n\nusing DigitalCommunications \nusing Plots \n\n# Simulation parameters \nk = 3 \nM = 2^k \nnsymbols = Int(1e6) \nnbits = k * nsymbols\nebno = collect(0 : 10)         \nesno = ebno .+ 10 * log10(k)    \n\n# Communcation system components  \ngen = SymbolGenerator(nsymbols, M) \nmodulator = Modulator(PSK(M))\nchannel = AWGNChannel() \ndetector = Detector(modulator(1:M))\n\n# Monte Carlo simulation \nmessage = gen.symbols  \nsymerr = zeros(length(esno))\nfor i in 1 : length(symerr)\n    channel.esno = esno[i]  # Update channel snr\n    mbar = message |> modulator |> channel |> detector  # Extracted message signal \n    symerr[i] = sum(mbar .!= message) / length(message)  # Symbol error rate \nend\n\n# Plots\nplt = plot(title=\"$M-PSK\", xlabel=\"ebno [dB]\", ylabel=\"Pe\") \nplot!(ebno, berpsk.(esno, M), marker=:circle, yscale=:log10, label=\"theoretical\")\nplot!(ebno, symerr, marker=:circle, yscale=:log10, label=\"montecarlo\")\n", "meta": {"hexsha": "9ea804c84de3929bc7a4ec539fb9c6025a7cea1a", "size": 1042, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/vector_simulations/montecarlopsk.jl", "max_stars_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_stars_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-03T20:02:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T06:43:38.000Z", "max_issues_repo_path": "example/vector_simulations/montecarlopsk.jl", "max_issues_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_issues_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-11-26T21:56:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-03T19:54:59.000Z", "max_forks_repo_path": "example/vector_simulations/montecarlopsk.jl", "max_forks_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_forks_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-20T12:53:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T12:53:43.000Z", "avg_line_length": 30.6470588235, "max_line_length": 85, "alphanum_fraction": 0.6957773512, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847496, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7734443974733587}}
{"text": "module Spirograph\n\nusing Plots\n\nfunction lastly()\n    plot!(aspectratio = 1, legend = false, axis = false, grid = false, ticks = false)\nend\n\n@inline inner_angle(a::Int, b::Int, t::Real)::Float64 = b * t / a\n\n@inline function spot(a::Int, b::Int, offset::Real, t::Real)::Complex{Float64}\n    θ = inner_angle(a, b, t)\n    return im * ((a + b) * exp(θ * im) + offset * exp(t * im))\nend\n\n@inline stop_t(a::Int, b::Int) = 2 * π * (lcm(a, b) ÷ abs(b))\n\nfunction spiro_points(a::Int, b::Int, offset::Real, step::Real)\n    if a <= 0 || b == 0\n        error(\n            \"Radius of fixed circle must be positive and radius of the rolling disk must be nonzero\",\n        )\n    end\n    T = stop_t(a, b) #+ step\n    return [spot(a, b, offset, t) for t = 0:step:T]\nend\n\n_DEFAULT_STEP = 0.05\n\n\"\"\"\n    spirograph(a,b,offset;args...)\nDraw a spirograph picture where\n+ `a` is the radius of the fixed wheel,\n+ `b` is the radius of the moving wheel, and\n+ `offset` is the distance from the center of the moving wheel to the pen.\n\nThe optional `args` are passed to `plot`. \n\n## Example\n`spirograph(20,-9,12,linecolor=:green)`\n\"\"\"\nfunction spirograph(a::Int, b::Int, offset::Real, step::Real = _DEFAULT_STEP; args...)\n    pts = spiro_points(a, b, offset, step)\n    plot(real(pts), imag(pts); args...)\n    lastly()\nend\n\n\"\"\"\n    spirograph!\nSame as `spirograph` but does not clear the drawing screen first. This way spirograph\nimages can be combined.\n\"\"\"\nfunction spirograph!(a::Int, b::Int, offset::Real, step::Real = _DEFAULT_STEP; args...)\n    pts = spiro_points(a, b, offset, step)\n    plot!(real(pts), imag(pts); args...)\n    lastly()\nend\n\nexport spirograph, spirograph!\nend # module\n", "meta": {"hexsha": "15d25863bd604a61cd7001785de728ef79871cb2", "size": 1665, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Spirograph.jl", "max_stars_repo_name": "scheinerman/Spirograph.jl", "max_stars_repo_head_hexsha": "0e2b92f423b21b42458154b6f9f84ba6cf21c4b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-10T05:57:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T05:57:13.000Z", "max_issues_repo_path": "src/Spirograph.jl", "max_issues_repo_name": "scheinerman/Spirograph.jl", "max_issues_repo_head_hexsha": "0e2b92f423b21b42458154b6f9f84ba6cf21c4b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Spirograph.jl", "max_forks_repo_name": "scheinerman/Spirograph.jl", "max_forks_repo_head_hexsha": "0e2b92f423b21b42458154b6f9f84ba6cf21c4b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2950819672, "max_line_length": 101, "alphanum_fraction": 0.6378378378, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7734443852526934}}
{"text": "#=\n\n   The Euro coin problem.\n\n   From Think Bayes, page 33ff\n   \"\"\"\n   A statistical statement appeared in \"The Guardian\" on Friday January 4, 2002:\n      When spun on edge 250 times, a Belgian one-euro coin\n      came up heads 140 times and tails 110. 'It looks very\n      suspicious to me,' said Barry Blight, a statistics lecturer\n      at the London School of Economics. 'If the coin were\n      unbiased, the chance of getting a result as extreme as\n      that would be less than 7%.'\n\n   But do these data give evidence that the coin is biased rather than fair?\n   \"\"\"\n\n  Model 1\n  mean(prob): 0.5639764325445531\n  Distributions of variable probLt0_5 (num:0)\n  0.00000 =>    9896  (0.989600)\n  1.00000 =>     104  (0.010400)\n\n  Distributions of variable probGt0_5 (num:0)\n  1.00000 =>    9896  (0.989600)\n  0.00000 =>     104  (0.010400)\n\n  Model 2\n  Summary Statistics\n  parameters       mean       std   naive_se      mcse         ess      rhat   ess_per_sec \n      Symbol    Float64   Float64    Float64   Float64     Float64   Float64       Float64 \n\n        prob     0.5496    0.0296     0.0003    0.0026     52.7368    1.0154        6.8901\n       heads   139.9668    1.8488     0.0185    0.0332   2384.8100    1.0002      311.5770\n   probLt0_5     0.0006    0.0245     0.0002    0.0006   1544.1256    1.0005      201.7410\n   probGt0_5     0.9994    0.0245     0.0002    0.0006   1544.1256    1.0005      201.7410\n\n\n   Cf ~/blog/euro_coin_problem.blog\n      ~/psi/euro_coin_problem.blog\n      ~/webppl/euro_coin_problem.jl\n\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n@model function euro_coin_problem1()\n    n = 250\n    \n    # Probability of throwing head\n    prob ~ Beta(2,2) # Uniform(0,1)\n    coin ~ filldist(flip(prob),n)\n    \n    sum250 ~ Dirac(sum([coin[i] == true ? 1 : 0 for i in 1:n]))\n    true ~ Dirac(sum250 == 140)\n\n    probLt0_5 ~ Dirac(prob < 0.5)\n    probGt0_5 ~ Dirac(prob > 0.5)\n    \nend\n\n# Simpler and faster\n@model function euro_coin_problem2()\n    prob ~ Beta(2,2)\n    heads ~ Binomial(250,prob)\n    \n    true ~ Dirac(heads==140)\n\n    probLt0_5 ~ Dirac(prob < 0.5)\n    probGt0_5 ~ Dirac(prob > 0.5)\n\nend\n\n\nprintln(\"Model 1\")\nmodel = euro_coin_problem1()\n\nnum_chains = 4\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(5), 10_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 10_000)\n\n# display(chns)\n# display(plot(chns))\n\nprintln(\"mean(prob): \", mean(chns[:prob]))\nshow_var_dist_pct(chns, :probLt0_5)\nshow_var_dist_pct(chns, :probGt0_5)\n    \n\nprintln(\"\\nModel 2\")\nmodel = euro_coin_problem2()\n\nnum_chains = 4\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(5), 10_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 10_000)\n\ndisplay(chns)\n# display(plot(chns))\n\nshow_var_dist_pct(chns, :probLt0_5)\nshow_var_dist_pct(chns, :probGt0_5)\n\n", "meta": {"hexsha": "a67f7ba552ed88a1abad3d1eb7e7dbbbfe9809c8", "size": 2939, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/euro_coin_problem.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/euro_coin_problem.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/euro_coin_problem.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 26.2410714286, "max_line_length": 91, "alphanum_fraction": 0.6342293297, "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7733988040800183}}
{"text": "function serial_pi_estimation(n_samples)\n    n_inside = 0;\n\n    x = zeros(2);\n\n    for _ in 1:n_samples\n        @. x = rand();\n        if(norm(x,2)<1)\n            n_inside+=1;\n        end\n    end\n\n    pi_estimate = 4 * n_inside/n_samples;\n\n    return pi_estimate\n\nend\n\nfunction pi_estimation(n_samples)\n    n_inside = 0;\n\n    x_inside = zeros(Bool, n_samples);\n\n    x = zeros(2);\n    Threads.@threads for j in 1:n_samples\n        @. x = rand();\n        if(norm(x,2)<1)\n            x_inside[j] = 1;\n        end\n    end\n\n    n_inside = sum(x_inside);\n\n    pi_estimate = 4 * n_inside/n_samples;\n\n    return pi_estimate\n\nend\n\nfunction atomic_pi_estimation(n_samples)\n\n    n_inside = Atomic{Int}(0);\n\n    x = zeros(2);\n\n    Threads.@threads for _ in 1:n_samples\n        @. x = rand();\n        if(norm(x,2)<1)\n            atomic_add!(n_inside,1);\n        end\n    end\n\n    pi_estimate = 4 * n_inside[]/n_samples;\n\n    return pi_estimate\n\nend", "meta": {"hexsha": "8ef6630cc5f6e580083acecc361562392c7f0d92", "size": 934, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PiMC/src/estimators.jl", "max_stars_repo_name": "liamfdoherty/Math_540_2021", "max_stars_repo_head_hexsha": "6b84b88ca1c587650a82f5bc9351f27a518e104d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PiMC/src/estimators.jl", "max_issues_repo_name": "liamfdoherty/Math_540_2021", "max_issues_repo_head_hexsha": "6b84b88ca1c587650a82f5bc9351f27a518e104d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PiMC/src/estimators.jl", "max_forks_repo_name": "liamfdoherty/Math_540_2021", "max_forks_repo_head_hexsha": "6b84b88ca1c587650a82f5bc9351f27a518e104d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.3859649123, "max_line_length": 43, "alphanum_fraction": 0.5642398287, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.8499711832583696, "lm_q1q2_score": 0.7733947428834389}}
{"text": "using Pkg\nPkg.activate(pwd())\n\n# # Functions\n\nfunction plus(x,y)\n    x + y\nend\n\n#+\n\nplus(2, 3)\nplus(2, -3)\n\n#+\n\nfunction plus(x,y)\n    return x + y\nend\n\n#+\n\nfunction plus(x, y)\n    return x + y\n    println(\"I am a useless line of code!!\")\nend\n\n#+\n\nplus(4, 5)\nplus(3, -5)\n\n#+\n\nfunction powers(x)\n    return x, x^2, x^3, x^4\nend\n\n#+\n\nps = powers(2)\ntypeof(ps)\n\n#+\n\nx1, x2, x3, x4 = powers(2)\nx3\n\n# ### Exercise:\n# Write function `power(x::Real, p::Integer)` that for a number $x$ and a (possibly\n# negative) integer $p$ computes $x^p$ without using the `^` operator. Use only basic\n# arithmetic operators `+`, `-`, `*`, `/` and the `if` condition. The annotation\n# `p::Integer` ensures that the input `p` is always an integer.\n#\n# **Hint:** use recursion.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n# \n# ## One-line functions\n\n\nplus(x, y) = x + y\n\n#+\n\nplus(4, 5)\nplus(3, -5)\n\n#+\n\nf(φ) = -4sin(φ - π/12)\n\n#+\n\ng(x) = (x -= 1; x *= 2; x)\n\n#+\n\ng(3)\n\n# ### Exercise:\n# Write a one-line function that returns `true` if the input argument is an even number and\n# `false` otherwise.\n#\n# **Hint:** use modulo function and [ternary operator](@ref Ternary-operator) `?`.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n# \n# ## Optional arguments\n\n\nhello(x = \"world\") = println(\"Hello $(x).\")\n\n#+\n\nhello()\nhello(\"people\")\n\n#+\n\npowers(x, y = x*x, z = y*x, v = z*x) = x, y, z, v\n\n#+\n\npowers(2)\npowers(2, 3)\n\n#+\n\nf(x = 1, y = x) = (x, y)\ng(x = y, y = 1) = (x, y)\n\n#+\n\nf()\ng()\n\n# ### Exercise:\n# Write a function which computes the value of the following quadratic form\n# $$\n# q_{a,b,c}(x,y) = ax^2 + bxy + cy^2,\n# $$\n# where $a, b, c, x \\in \\mathbb{R}$. Use optional arguments to set default values for\n# parameters\n# $$\n# a = 1, \\quad b = 2a, \\quad c = 3(a + b).\n# $$\n# What is the function value at point $(4, 2)$ for default parameters? What is the\n# function value at the same point if we use $c = 3$?\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n# \n# ## Keyword arguments\n\nlinear(x; a = 1, b = 0) = a*x + b\n\n#+\n\nlinear(2)\nlinear(2; a = 2)\nlinear(2; b = 4)\nlinear(2; a = 2, b = 4)\n\n#+\n\nlinear(b = 4, 2, a = 2) # If you use this, you will burn in hell 🔥🔥🔥🔥\n\n#+\n\na, b = 2, 4\n\nlinear(2; a = a, b = b)\nlinear(2; a, b)\n\n# ### Exercise:\n# Write a probability density function for the\n# [Gaussian distribution](https://en.wikipedia.org/wiki/Normal_distribution)\n# $$\n# f_{\\mu, \\sigma}(x) = \\frac{1}{\\sigma \\sqrt{ 2\\pi }} \\exp\\left\\{ -\\frac{1}{2} \\left(\n# \\frac{x - \\mu}{\\sigma} \\right) ^2 \\right\\},\n# $$\n# where $\\mu \\in \\mathbb{R}$ and $\\sigma^2 > 0$. Use keyword arguments to obtain the\n# standardized normal distribution ($\\mu = 0$ and $\\sigma = 1$). Check that the inputs\n# are correct.\n#\n# Bonus: verify that this function is a probability density function, i.e., its integral\n# equals 1.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n# \n# ## Variable number of arguments\n\nnargs(x...) = println(\"Number of arguments: \", length(x))\n\n#+\n\nnargs()\nnargs(1, 2, \"a\", :b, [1,2,3])\n\n#+\n\nargs = (1, 2, 3)\n\nnargs(args[1], args[2], args[3])\nnargs(args...)\nnargs(args)\n\n#+\n\nnargs(1:100)\nnargs(1:100...)\n\n#+\n\nnargs([1,2,3,4,5])\nnargs([1,2,3,4,5]...)\n\n#+\n\nroundmod(x, y; kwargs...) = round(mod(x, y); kwargs...)\n\n#+\n\nroundmod(12.529, 5)\nroundmod(12.529, 5; digits = 2)\nroundmod(12.529, 5; sigdigits = 2)\n\n# ### Exercise:\n# Write a function `wrapper`, that accepts a number and applies one of `round`, `ceil` or\n# `floor` functions based on the keyword argument `type`. Use the function to solve the\n# following tasks:\n# - Round `1252.1518` to the nearest larger integer and convert the resulting value\n# to `Int64`.\n# - Round `1252.1518` to the nearest smaller integer and convert the resulting value\n# to `Int16`.\n# - Round `1252.1518` to `2` digits after the decimal point.\n# - Round `1252.1518` to `3` significant digits.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n# \n# ## Anonymous functions\n\n\nh1 = function (x)\n    x^2 + 2x - 1\nend\n\n#+\n\nh2 = x ->  x^2 + 2x - 1\n\n#+\n\nusing Plots\n\nf(x,a) = (x + a)^2\nplot(-1:0.01:1, x -> f(x,0.5))\n\n#+\n\nmap(x -> x^2 + 2x - 1, [1,3,-1])\n\n#+\n\nmap([1,3,-1], [2,4,-2]) do x, y\n    println(\"x = $(x), y = $(y)\")\n    return x + y\nend\n\n#+\n\nfunction f(x, y)\n    println(\"x = $(x), y = $(y)\")\n    return x + y\nend\n\nmap(f, [1,3,-1], [2,4,-2])\n\n# ## Dot syntax for vectorizing functions\n\nx = [0, π/2, 3π/4];\nA = zeros(length(x));\n\nfor (i, xi) in enumerate(x)\n    A[i] = sin(xi)\nend\n\nA\n\n#+\n\nA = [sin(xi) for xi in x]\n\n#+\n\nA = sin.(x)\n\n#+\n\nplus(x::Real, y::Real) = x + y\n\n#+\n\nplus(1,3)\nplus(1.4,2.7)\n\n#+\n\nx = [1,2,3,4]; # column vector\n\nplus(x, x)\nplus.(x, x)\n\n#+\n\nbroadcast(plus, x, x)\n\n#+\n\ny = [1 2 3 4]; # row vector\n\nplus.(x, y)\nplus.(x, 1)\n\n# ## Function composition and piping\n\n(sqrt ∘ +)(3, 6) # equivalent to sqrt(3 + 6)\n(sqrt ∘ abs ∘ sum)([-3, -6, -7])  # equivalent to sqrt(abs(sum([-3, -6, -7])))\n\n#+\n\n[-3, -6, -7] |> sum |> abs |> sqrt\n[-4, 9, -16] .|> abs .|> sqrt\n\n#+s\n\n[\"a\", \"list\", \"of\", \"strings\"] .|> [uppercase, reverse, titlecase, length]\n", "meta": {"hexsha": "9cae65cd377def2fa0d23e3eab2d8e39a618840d", "size": 4898, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_04/01-functions.jl", "max_stars_repo_name": "JuliaTeachingCTU/Julia-for-Optimization-and-Learning-Scripts", "max_stars_repo_head_hexsha": "8e00299449736e4ccf47c247aa9d80f99a7e5b92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lecture_04/01-functions.jl", "max_issues_repo_name": "JuliaTeachingCTU/Julia-for-Optimization-and-Learning-Scripts", "max_issues_repo_head_hexsha": "8e00299449736e4ccf47c247aa9d80f99a7e5b92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecture_04/01-functions.jl", "max_forks_repo_name": "JuliaTeachingCTU/Julia-for-Optimization-and-Learning-Scripts", "max_forks_repo_head_hexsha": "8e00299449736e4ccf47c247aa9d80f99a7e5b92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.2798833819, "max_line_length": 91, "alphanum_fraction": 0.5581870151, "num_tokens": 1842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.9099070103134425, "lm_q1q2_score": 0.7733947382112021}}
{"text": "# # 205: 2D Nonlinear Poisson equation\n# ([source code](SOURCE_URL))\n\nmodule Example205_NonlinearPoisson2D\n\nusing Printf\nusing VoronoiFVM\nusing ExtendableGrids\nusing ExtendableSparse\nusing GridVisualize\n\n\n\nfunction main(;n=10,Plotter=nothing,verbose=false, unknown_storage=:sparse, max_lureuse=0,\n              factorization=LUFactorization())\n    h=1.0/convert(Float64,n)\n    X=collect(0.0:h:1.0)\n    Y=collect(0.0:h:1.0)\n\n\n    grid=VoronoiFVM.Grid(X,Y)\n    \n    eps=1.0e-2\n    \n    physics=VoronoiFVM.Physics(\n        num_species=1,\n        reaction=function(f,u,node)\n        f[1]=u[1]^2\n        end,\n        \n        flux=function(f,u0,edge)\n        u=unknowns(edge,u0)\n        f[1]=eps*(u[1,1]^2-u[1,2]^2)\n        end,\n        \n        source=function(f,node)\n        x1=node[1]-0.5\n        x2=node[2]-0.5\n        f[1]=exp(-20.0*(x1^2+x2^2))\n        end,\n        \n        storage=function(f,u,node)\n        f[1]=u[1]\n        end)\n    sys=VoronoiFVM.System(grid,physics,unknown_storage=unknown_storage)\n    enable_species!(sys,1,[1])\n\n    boundary_dirichlet!(sys,1,2,0.1)\n    boundary_dirichlet!(sys,1,4,0.1)\n    \n    inival=unknowns(sys)\n    U=unknowns(sys)\n    inival.=0.5\n\n\n    control=VoronoiFVM.NewtonControl()\n    control.verbose=verbose\n    control.tol_linear=1.0e-5\n    control.max_lureuse=max_lureuse\n    control.factorization=factorization\n    tstep=0.01\n    time=0.0\n    u15=0\n    p=GridVisualizer(Plotter=Plotter)\n    while time<1.0\n        time=time+tstep\n        solve!(U,inival,sys,control=control,tstep=tstep)\n        u15=U[15]\n        inival.=U\n\n        if verbose\n            @printf(\"time=%g\\n\",time)\n        end\n\n        scalarplot!(p[1,1],grid,U[1,:],Plotter=Plotter,clear=true,show=true)\n        tstep*=1.0\n    end\n    return u15\nend\n\nfunction test()\n    # test at once for iterative solution here\n    testval=0.3554284760906605\n    main(unknown_storage=:sparse,max_lureuse=0) ≈  testval &&\n        main(unknown_storage=:dense,max_lureuse=0) ≈ testval &&\n        main(unknown_storage=:sparse,max_lureuse=10) ≈ testval &&\n        main(unknown_storage=:dense,max_lureuse=10) ≈ testval &&\n        main(unknown_storage=:sparse,max_lureuse=0, factorization=ILU0Preconditioner()) ≈ testval &&\n        main(unknown_storage=:dense,max_lureuse=0, factorization=ILU0Preconditioner()) ≈ testval \nend\nend\n", "meta": {"hexsha": "d5cdeec918b74bc5847d2617fa94841f0566011c", "size": 2319, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Example205_NonlinearPoisson2D.jl", "max_stars_repo_name": "mattlie82/VoronoiFVM.jl", "max_stars_repo_head_hexsha": "819cdc967f4cf8fad6b14e271296b365ff6e51c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Example205_NonlinearPoisson2D.jl", "max_issues_repo_name": "mattlie82/VoronoiFVM.jl", "max_issues_repo_head_hexsha": "819cdc967f4cf8fad6b14e271296b365ff6e51c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Example205_NonlinearPoisson2D.jl", "max_forks_repo_name": "mattlie82/VoronoiFVM.jl", "max_forks_repo_head_hexsha": "819cdc967f4cf8fad6b14e271296b365ff6e51c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2065217391, "max_line_length": 100, "alphanum_fraction": 0.6313065977, "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672954, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7733947321618686}}
{"text": "# See https://en.wikipedia.org/wiki/Derivative\n# Examples from https://github.com/JuliaSymbolics/Symbolics.jl\n\nusing Symbolics\n\n@variables x y z\n\nexpressions = [\n    :(Symbolics.derivative(x + x^2, x))\n    :(Symbolics.derivative(x + 2x^2 + 6x^3 - 5x^4, x))\n    :(Symbolics.derivative(cos(x) * sin(x), x))\n    :(Symbolics.derivative(exp(x), x))\n    :(Symbolics.derivative(log(x), x))\n    :(Symbolics.jacobian([x + x*y, x^4 + y], [x, y]))\n    :(Symbolics.hessian(x^4 + z, [x, y, z]))\n]\n\nfor expr in expressions\n    println(\"[] :julia-answer \\\"\\\"\\\"\", escape_string(string(expr)), \" = \", eval(expr), \"\\\"\\\"\\\".\")\nend\n", "meta": {"hexsha": "9738d586a55230620477113c3416d45609bc0b2b", "size": 611, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "reasoning/julia/derivative.jl", "max_stars_repo_name": "pmoura/eye", "max_stars_repo_head_hexsha": "03a4be110f5e9f8f21a6b1ac2756d79cc6518386", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reasoning/julia/derivative.jl", "max_issues_repo_name": "pmoura/eye", "max_issues_repo_head_hexsha": "03a4be110f5e9f8f21a6b1ac2756d79cc6518386", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reasoning/julia/derivative.jl", "max_forks_repo_name": "pmoura/eye", "max_forks_repo_head_hexsha": "03a4be110f5e9f8f21a6b1ac2756d79cc6518386", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0952380952, "max_line_length": 97, "alphanum_fraction": 0.6088379705, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7733439151846369}}
{"text": "__precompile__()\n\nmodule mbInterpolate\nexport interpolateLanczos, interpolateTrigonometric\n\nusing mbUtil\n\n\"\"\"\n    interpolateLanczos(V, a::Integer)\n\nsimple periodic (!) Lanczos interpolation\n\"\"\"\nfunction interpolateLanczos(V,a::Integer)\n\treturn mbUtil.vectorize() do y\n\t\tsum = zero(V[1])\n\t\tN = length(V)\n\t\tfor i in floor(Integer,y)+(-a+1:a)\n\t\t\tlocal tmp = y-i\n\t\t\tsum += sinc(tmp)*sinc(tmp/a)*V[mod(i-1,N) + 1]\n\t\tend\n\t\treturn sum\n\tend\nend\ninterpolateLanczos(V, a::Integer, x) = interpolateLanczos(V,a)(x)\n\n\n\n\"\"\"\n    interpolateTrigonometric(a₀, a, b)\nReturns trigonometric polynomial.\nUse with 2a,-2b and divide by 2m+1 to use with rfft coefficients.\n\"\"\"\nfunction interpolateTrigonometric(a₀, a, b)\n\treturn mbUtil.vectorize() do x\n\t\ta₀ + reduce(0, 1:length(a)) do I,i\n\t\t\ttmp = i*x\n\t\t\tI + a[i]*cos(tmp) + b[i]*sin(tmp)\n\t\tend\n\tend\nend\ninterpolateTrigonometric(a₀, a, b, x) = interpolateTrigonometric(a₀, a, b)(x)\n\nend #module\n", "meta": {"hexsha": "23668eac536305bbe4dd8284170812fefd563efc", "size": 923, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "master/lib/mbInterpolate.jl", "max_stars_repo_name": "285714/ncm", "max_stars_repo_head_hexsha": "fcf289c7ef5f8500ebcb238e36c6a7ee9e054147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "master/lib/mbInterpolate.jl", "max_issues_repo_name": "285714/ncm", "max_issues_repo_head_hexsha": "fcf289c7ef5f8500ebcb238e36c6a7ee9e054147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "master/lib/mbInterpolate.jl", "max_forks_repo_name": "285714/ncm", "max_forks_repo_head_hexsha": "fcf289c7ef5f8500ebcb238e36c6a7ee9e054147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9772727273, "max_line_length": 77, "alphanum_fraction": 0.6944745395, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7733439103763585}}
{"text": "\"\"\"\n    PoisLik <: Likelihood\n\nPoisson likelihood\n```math\np(yᵢ = k | fᵢ) = θᵏ\\\\exp(-θ)/k!\n```\nfor ``k ∈ N₀``, where ``θ = \\\\exp(f)`` and ``f`` is the latent Gaussian process.\n\"\"\"\nstruct PoisLik <: Likelihood end\n\n#log of probability density\nfunction log_dens(poisson::PoisLik, f::VecF64, y::Vector{Int})\n    #where we exponentiate for positivity f = exp(fi)\n    return y.*f - exp.(f) - lgamma.(1.0 .+ y)\nend\n\n#derivative of pdf wrt latent function\nfunction dlog_dens_df(poisson::PoisLik, f::VecF64, y::Vector{Int})\n    return y - exp.(f)\nend\n\n#mean and variance under likelihood\nmean_lik(poisson::PoisLik, f::VecF64) = exp.(f)\nvar_lik(poisson::PoisLik, f::VecF64) = exp.(f)\n\nget_params(poisson::PoisLik) = []\nnum_params(poisson::PoisLik) = 0\n\n\n", "meta": {"hexsha": "1f340ae43d9ff7e013d2b07ba2ab52afd96d2b93", "size": 744, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/likelihoods/poisson.jl", "max_stars_repo_name": "jbrea/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/likelihoods/poisson.jl", "max_issues_repo_name": "jbrea/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/likelihoods/poisson.jl", "max_forks_repo_name": "jbrea/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0, "max_line_length": 80, "alphanum_fraction": 0.6666666667, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7732629859991285}}
{"text": "## Barycentric formula\n\nexport bary,barysum\n\nfunction bary(v::Vector{Float64},pts::Vector{Float64},x::Float64)\n  n=length(v)\n  @assert n == length(pts)\n\n\n  retd = .5/(x-pts[1])\n  retn = v[1]*retd\n\n  for i = 2:2:n-1\n    @inbounds cd = 1./(x-pts[i])\n    retd -= cd\n    @inbounds retn -= v[i]*cd\n  end\n\n  for i = 3:2:n-1\n    @inbounds cd = 1./(x-pts[i])\n    retd += cd\n    @inbounds retn += v[i]*cd\n  end\n\n  cd = .5*(-1.)^(n-1)/(x-pts[n])\n  retd += cd\n  retn += v[n]*cd\n\n  retn/retd\nend\n\n\nbary(v::Vector{Float64},x::Float64)=bary(v,chebyshevpoints(length(v);kind=2),x)\n\nfunction randomadaptivebary(f::Function)\n  r=rand()\n  fr=f(r)\n  err=1.\n  logn=1\n\n  tol=200eps()\n\n  vals=Float64[]\n\n  while err > tol\n      n=2^logn + 1\n      pts=chebyshevpoints(n;kind=2)\n      vals=f(pts)\n      err=abs(bary(vals,pts,r)-fr)/n\n      logn+=1\n  end\n\n  vals\nend\n", "meta": {"hexsha": "c57c9a4251bd14bacbd63d480ea904ab2141496d", "size": 842, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LinearAlgebra/bary.jl", "max_stars_repo_name": "JuliaPackageMirrors/ApproxFun.jl", "max_stars_repo_head_hexsha": "f73e9d168b0d139efa2953b1bad7fac808db2d8d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LinearAlgebra/bary.jl", "max_issues_repo_name": "JuliaPackageMirrors/ApproxFun.jl", "max_issues_repo_head_hexsha": "f73e9d168b0d139efa2953b1bad7fac808db2d8d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LinearAlgebra/bary.jl", "max_forks_repo_name": "JuliaPackageMirrors/ApproxFun.jl", "max_forks_repo_head_hexsha": "f73e9d168b0d139efa2953b1bad7fac808db2d8d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.3090909091, "max_line_length": 79, "alphanum_fraction": 0.5712589074, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7732629831050835}}
{"text": "# By default, Julia/LLVM does not use fused multiply-add operations (FMAs).\n# Since these FMAs can increase the performance of many numerical algorithms,\n# we need to opt-in explicitly.\n# See https://ranocha.de/blog/Optimizing_EC_Trixi for further details.\n@muladd begin\n\n\n\"\"\"\n    ln_mean(x, y)\n\nCompute the logarithmic mean\n\n    ln_mean(x, y) = (y - x) / (log(y) - log(x)) = (y - x) / log(y / x)\n\nProblem: The formula above has a removable singularity at `x == y`. Thus,\nsome care must be taken to implement it correctly without problems or loss\nof accuracy when `x ≈ y`. Here, we use the approach proposed by\nIsmail and Roe (2009).\nSet ξ = y / x. Then, we have\n\n    (y - x) / log(y / x) = (x + y) / log(ξ) * (ξ - 1) / (ξ + 1)\n\nSet f = (ξ - 1) / (ξ + 1) = (y - x) / (x + y). Then, we use the expansion\n\n    log(ξ) = 2 * f * (1 + f^2 / 3 + f^4 / 5 + f^6 / 7) + O(ξ^9)\n\nInserting the first few terms of this expansion yields\n\n    (y - x) / log(ξ) ≈ (x + y) * f / (2 * f * (1 + f^2 / 3 + f^4 / 5 + f^6 / 7))\n                     = (x + y) / (2 + 2/3 * f^2 + 2/5 * f^4 + 2/7 * f^6)\n\nSince divisions are usually more expensive on modern hardware than\nmultiplications (Agner Fog), we try to avoid computing two divisions. Thus,\nwe use\n\n    f^2 = (y - x)^2 / (x + y)^2\n        = (x * (x - 2 * y) + y * y) / (x * (x + 2 * y) + y * y)\n\nGiven ε = 1.0e-4, we use the following algorithm.\n\n    if f^2 < ε\n      # use the expansion above\n    else\n      # use the direct formula (y - x) / log(y / x)\n    end\n\n# References\n- Ismail, Roe (2009).\n  Affordable, entropy-consistent Euler flux functions II: Entropy production at shocks.\n  [DOI: 10.1016/j.jcp.2009.04.021](https://doi.org/10.1016/j.jcp.2009.04.021)\n- Agner Fog.\n  Lists of instruction latencies, throughputs and micro-operation breakdowns\n  for Intel, AMD, and VIA CPUs.\n  https://www.agner.org/optimize/instruction_tables.pdf\n\"\"\"\n@inline function ln_mean(x, y)\n  epsilon_f2 = 1.0e-4\n  f2 = (x * (x - 2 * y) + y * y) / (x * (x + 2 * y) + y * y) # f2 = f^2\n  if f2 < epsilon_f2\n    return (x + y) / @evalpoly(f2, 2, 2/3, 2/5, 2/7)\n  else\n    return (y - x) / log(y / x)\n  end\nend\n\n\"\"\"\n    inv_ln_mean(x, y)\n\nCompute the inverse `1 / ln_mean(x, y)` of the logarithmic mean\n[`ln_mean`](@ref).\n\nThis function may be used to increase performance where the inverse of the\nlogarithmic mean is needed, by replacing a (slow) division by a (fast)\nmultiplication.\n\"\"\"\n@inline function inv_ln_mean(x, y)\n  epsilon_f2 = 1.0e-4\n  f2 = (x * (x - 2 * y) + y * y) / (x * (x + 2 * y) + y * y) # f2 = f^2\n  if f2 < epsilon_f2\n    return @evalpoly(f2, 2, 2/3, 2/5, 2/7) / (x + y)\n  else\n    return log(y / x) / (y - x)\n  end\nend\n\n\nend # @muladd\n", "meta": {"hexsha": "a7066d93b0bbdf1b19af4265b676d0a260e1ad87", "size": 2673, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/auxiliary/math.jl", "max_stars_repo_name": "andrewwinters5000/Trixi.jl", "max_stars_repo_head_hexsha": "3ae92e69cd1c27ca4a169771db11723d166ab481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/auxiliary/math.jl", "max_issues_repo_name": "andrewwinters5000/Trixi.jl", "max_issues_repo_head_hexsha": "3ae92e69cd1c27ca4a169771db11723d166ab481", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/auxiliary/math.jl", "max_forks_repo_name": "andrewwinters5000/Trixi.jl", "max_forks_repo_head_hexsha": "3ae92e69cd1c27ca4a169771db11723d166ab481", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.375, "max_line_length": 87, "alphanum_fraction": 0.593714927, "num_tokens": 997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7732629831050835}}
{"text": "# Question\n# Find the sum of all the multiples of 3 or 5 below 1000.\n\n# Time\n# O(1)\n\nfunction ap(n, d, a)\n    return n*(2*a + (n-1)*d)/2\nend\nfunction main()\n    limit = 1000\n    n3 =  floor(1000/3)\n    n5 = floor((1000-1)/5)\n    n15 = floor(1000/15)\n    \n    sum = ap(n3, 3, 3) + ap(n5, 5, 5) - ap(n15, 15, 15)\n    println(convert(Int, trunc(sum)))\nend\n\n@time main()\n", "meta": {"hexsha": "905d31a2251c9fdd8004cde2d0987dfc501ea3eb", "size": 367, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1.jl", "max_stars_repo_name": "BlackWingedKing/ProjectEuler.jl", "max_stars_repo_head_hexsha": "ea0f57d8d90dbb8a8660843dddff080a957cfbd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1.jl", "max_issues_repo_name": "BlackWingedKing/ProjectEuler.jl", "max_issues_repo_head_hexsha": "ea0f57d8d90dbb8a8660843dddff080a957cfbd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1.jl", "max_forks_repo_name": "BlackWingedKing/ProjectEuler.jl", "max_forks_repo_head_hexsha": "ea0f57d8d90dbb8a8660843dddff080a957cfbd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4761904762, "max_line_length": 57, "alphanum_fraction": 0.5585831063, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7732629813991044}}
{"text": "\"\"\"\nConvert a vector `w` to a symmetric matrix `P` as\nP = [\n    w[1] ⋅ ⋅ ⋅ ⋅ ...;\n    w[2] w[n+1]  ...;\n    w[3] w[n+2]  ...;\n    ...  ...        ;\n    w[n] ...        ;\n]\n# Notes\nIt should be compatible with `convert_quadratic_to_linear_basis`.\n\"\"\"\nfunction convert_to_matrix(w::AbstractVector)::AbstractMatrix\n    # n(n+1)/2 x 1 -> n x n\n    _l = length(w)\n    l = Int((-1 + sqrt(1+4*2*_l)) / 2)  # P is l x l lower triangular matrix with elements of w\n    P = zeros(l, l)\n    idx = 1\n    for i in 1:l\n        for j in i:l\n            if i == j\n                P[j, i] = w[idx]\n            else\n                P[j, i] = 0.5 * w[idx]\n                P[i, j] = 0.5 * w[idx]\n            end\n            idx += 1\n        end\n    end\n    P\n    # # n^2 x 1 -> n x n for convenience...\n    # l = Int(sqrt(length(w)))\n    # P = zeros(l, l)\n    # idx = 1\n    # for i in 1:l\n    #     for j in 1:l\n    #         P[j, i] = w[idx]\n    #         idx += 1\n    #     end\n    # end\n    # P\nend\n\n\"\"\"\nBasis transformation for linear ADP and IRL;\nxᵀ * P * x = wᵀ * ϕ(x)\nwhere ϕ(x) = [x1^2, x2*x1, x3*x1, ..., xn*x1, x2^2, x3*x2, x4*x2, ..., xn*x2, x3^2, x4*x3, ...]\n# Notes\nIt should be compatible with `convert_to_matrix`.\n\"\"\"\nfunction convert_quadratic_to_linear_basis(x::AbstractVector)\n    ## Notes\n    ## ϕ(x) = (I_m ⊗ x) x;\n    ## Px = (I_m ⊗ xᵀ) w\n    ## where P ∈ ℝ^{m×n}, w ∈ ℝ^{nm×1}, I_m: m×m identity matrix, ⊗: Kronecker product\n    # n = length(x)\n    # kron(Matrix(I, n, n), x) * x\n    ## for dimension reduction\n    n = length(x)\n    ϕ = zeros(Int(n*(n+1)/2))\n    idx = 1\n    for i in 1:n\n        for j in i:n\n            ϕ[idx] = x[j] * x[i]\n            idx += 1\n        end\n    end\n    ϕ\nend\n", "meta": {"hexsha": "6093309de5b362670d82076aa156971d4d971a86", "size": 1694, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/convert.jl", "max_stars_repo_name": "fdcl-data-driven-control/DataDrivenControl.jl", "max_stars_repo_head_hexsha": "bcbb872426ef5d154a4524bffd00431813b030ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-30T06:17:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T09:55:48.000Z", "max_issues_repo_path": "src/utils/convert.jl", "max_issues_repo_name": "fdcl-data-driven-control/DataDrivenControl.jl", "max_issues_repo_head_hexsha": "bcbb872426ef5d154a4524bffd00431813b030ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2021-12-30T05:40:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-24T03:48:57.000Z", "max_forks_repo_path": "src/utils/convert.jl", "max_forks_repo_name": "fdcl-data-driven-control/DataDrivenControl.jl", "max_forks_repo_head_hexsha": "bcbb872426ef5d154a4524bffd00431813b030ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2, "max_line_length": 95, "alphanum_fraction": 0.4539551358, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7732629796931252}}
{"text": "######\n# This example shows how to do function approximation in 2D using Padua points\n# and in 3D by hand\n######\n\nusing ApproxFun\n    import ApproxFun: transform\nf = (x,y) -> exp(x*y)\n\nS = Chebyshev(0..1)^2\n\nN = 10^2; p = points(S, N) # 105 padua points\nf̃ = (xy) -> f(xy[1], xy[2])\nF = f̃.(p)\nF̌ = transform(S, F)  # 105 Chebyshev^2 coefficients ordered by polynomial degree\nf̌ = Fun(S, F̌)\nf̌(0.1,0.2) ≈ f(0.1,0.2)\n\n\nS = Chebyshev(0..1)\np_x = points(S, 10)\np_y = points(S, 10)'\np_z = reshape(points(S, 10), 1, 1, 10)\n\nf = (x,y,z) -> exp(x*y+z)\n\nF = f.(p_x, p_y, p_z)\n\nfor k = 1:size(F,2),j=1:size(F,3)\n    F[:,k,j] = transform(S,F[:,k,j])\nend\nfor k = 1:size(F,1),j=1:size(F,3)\n    F[k,:,j] = transform(S,F[k,:,j])\nend\nfor k = 1:size(F,1),j=1:size(F,2)\n    F[k,j,:] = transform(S,F[k,j,:])\nend\n\nf̌ = function(x,y,z)\n    ret1 = Array{Float64}(undef, size(F,2), size(F,3))\n    for j=1:size(F,2),l=1:size(F,3)\n        ret1[j,l] = Fun(S,F[:,j,l])(x)\n    end\n    ret2 = Array{Float64}(undef, size(F,3))\n    for l=1:size(F,3)\n        ret2[l] = Fun(S,ret1[:,l])(y)\n    end\n    Fun(S, ret2)(z)\nend\n\nf̌(0.1,0.2,0.3) ≈ f(0.1,0.2,0.3)\n", "meta": {"hexsha": "2ca0f985302227ee2f5f63ccdadf145bc719e2a2", "size": 1125, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Extras/Manual 3D interpolation.jl", "max_stars_repo_name": "putianyi889/ApproxFunExamples", "max_stars_repo_head_hexsha": "b519a2b2a197607561028fea53a327493bfb344e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2018-06-01T04:19:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T10:15:11.000Z", "max_issues_repo_path": "Extras/Manual 3D interpolation.jl", "max_issues_repo_name": "putianyi889/ApproxFunExamples", "max_issues_repo_head_hexsha": "b519a2b2a197607561028fea53a327493bfb344e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-03-27T09:32:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-30T08:52:42.000Z", "max_forks_repo_path": "Extras/Manual 3D interpolation.jl", "max_forks_repo_name": "putianyi889/ApproxFunExamples", "max_forks_repo_head_hexsha": "b519a2b2a197607561028fea53a327493bfb344e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-07-25T00:08:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T12:38:42.000Z", "avg_line_length": 21.6346153846, "max_line_length": 81, "alphanum_fraction": 0.5431111111, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.77326297765207}}
{"text": "\n#=\n\nSolves the price function for the Lucas tree in a continuous state\nsetting, using piecewise linear approximation for the sequence of\ncandidate price functions.  The consumption endownment follows the\nlog linear AR(1) process\n\n    log y' = alpha log y + sigma epsilon\n\nwhere y' is a next period y and epsilon is an iid standard normal\nshock. Hence\n\n    y' = y^alpha * xi   where xi = e^(sigma * epsilon)\n\nThe distribution phi of xi is\n\n    phi = LN(0, sigma^2) where LN means lognormal\n\n@authors : Spencer Lyon <spencer.lyon@nyu.edu>, John Stachurski\n\n\nReferences\n----------\n\nhttp://quant-econ.net/jl/markov_asset.html\n\n=#\n\nusing QuantEcon\nusing Distributions\n\n\n\"\"\"\nA function that takes two arrays and returns a function that approximates the\ndata using continuous piecewise linear interpolation.\n\n\"\"\"\nfunction lin_interp(x_vals::Vector{Float64}, y_vals::Vector{Float64})\n    # == linear interpolation inside grid, constant values outside grid == #\n    w = LinInterp(x_vals, y_vals)\n    return w\nend\n\n\n\n\"\"\"\nThe Lucas asset pricing model --- parameters and grid data\n\"\"\"\ntype LucasTree\n    gamma::Real       # coefficient of risk aversion \n    beta::Real        # Discount factor in (0, 1)\n    alpha::Real       # Correlation coefficient in the shock process\n    sigma::Real       # Volatility of shock process\n    phi::Distribution # Distribution for shock process\n    grid::Vector      # Grid of points on which to evaluate prices.\n    shocks::Vector    # Draws of the shock\n    h::Vector         # The h function represented as a vector\nend\n\n\n\n\"\"\"\nConstructor for the Lucas asset pricing model \n\"\"\"\nfunction LucasTree(;gamma=2.0, \n                beta=0.95, \n                alpha=0.9, \n                sigma=0.1,\n                grid_size=100)\n\n    phi = LogNormal(0.0, sigma)\n    shocks = rand(phi, 500)\n\n    # == build a grid with mass around stationary distribution == #\n    ssd = sigma / sqrt(1 - alpha^2)\n    grid_min, grid_max = exp(-4 * ssd), exp(4 * ssd)\n    grid = collect(linspace(grid_min, grid_max, grid_size))\n\n    # == set h(y) = beta * int u'(G(y,z)) G(y,z) phi(dz) == #\n    h = similar(grid)\n    for (i, y) in enumerate(grid)\n        h[i] = beta * mean((y^alpha .* shocks).^(1 - gamma))\n    end\n\n    return LucasTree(gamma,\n                    beta,\n                    alpha,\n                    sigma,\n                    phi,\n                    grid,\n                    shocks,\n                    h)\nend\n\n\n\"\"\"\nThe approximate Lucas operator, which computes and returns updated function\nTf on the grid points.\n\"\"\"\nfunction lucas_operator(lt::LucasTree, f::Vector{Float64})\n\n    # == unpack names == #\n    grid, alpha, beta, h = lt.grid, lt.alpha, lt.beta, lt.h\n    z = lt.shocks\n\n    Tf = similar(f)\n    Af = lin_interp(grid, f)\n\n    for (i, y) in enumerate(grid)\n        Tf[i] = h[i] + beta * mean(Af.(y^alpha .* z))\n    end\n    return Tf\nend\n\n\n\"\"\"\nCompute the equilibrium price function associated with Lucas tree `lt`\n\"\"\"\nfunction compute_lt_price(lt::LucasTree, max_iter=500)\n\n    # == Simplify names == #\n    grid = lt.grid\n    alpha, beta, gamma = lt.alpha, lt.beta, lt.gamma\n\n    # == Create suitable initial vector to iterate from == # \n    f_init = zeros(grid)  \n\n    func(f_vec) = lucas_operator(lt, f_vec)\n    f = compute_fixed_point(func, f_init; \n                                    max_iter=max_iter, \n                                    err_tol=1e-4, \n                                    verbose=false)\n\n    # p(y) = f(y) * y^gamma\n    price = f .* grid.^(gamma)\n\n    return price\nend\n\n", "meta": {"hexsha": "368c816afc36c84e078edbedc10442c2dcf9325e", "size": 3530, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lucas_model/lucastree.jl", "max_stars_repo_name": "oyamad/QuantEcon.lectures.code", "max_stars_repo_head_hexsha": "a8a17e753857e0157f18337264114ce7cb23e841", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-06T04:09:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-06T04:09:21.000Z", "max_issues_repo_path": "lucas_model/lucastree.jl", "max_issues_repo_name": "zhouweimin-econ/QuantEcon.lectures.code", "max_issues_repo_head_hexsha": "a8a17e753857e0157f18337264114ce7cb23e841", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lucas_model/lucastree.jl", "max_forks_repo_name": "zhouweimin-econ/QuantEcon.lectures.code", "max_forks_repo_head_hexsha": "a8a17e753857e0157f18337264114ce7cb23e841", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-04-21T21:41:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T22:09:19.000Z", "avg_line_length": 25.0354609929, "max_line_length": 77, "alphanum_fraction": 0.6016997167, "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7732629764030583}}
{"text": "# memory_function.jl\n\n\"\"\"\nχ(Ω::Float64, α::Float64, v::Float64, w::Float64)\n\n    Calculate the memory function χ(Ω) of the polaron at finite temperatures (equation (35a) in FHIP 1962) for a given frequency Ω. v and w are the variational polaron parameters that minimise the free energy, for the supplied α Frohlich coupling.\n\"\"\"\nfunction χ(Ω, β, α, v, w)\n\n    # FHIP1962, page 1011, eqn (47c).\n    R = (v^2 - w^2) / (w^2 * v)\n\n    # FHIP1962, page 1009, eqn (35c).\n    D(x) = w^2 / v^2 * (R * (1 - cos(v * x)) * coth(β * v / 2) + x^2 / β - 1im * (R * sin(v * x) + x))\n\n    # FHIP1962, page 1009, eqn (36).\n    S(x) = 2 * α / (3 * √π) * (exp(1im * x) + 2 * cos(x) / (exp(β) - 1)) / (D(x))^(3 / 2)\n\n    # FHIP1962, page 1009, eqn (35a).\n    integrand(x) = (1 - exp(-1im * Ω * x)) * imag(S(x))\n    QuadGK.quadgk(x -> integrand(x), 0.0, Inf)[1]\nend\n\n\"\"\"\nχ(Ω::Float64, α::Float64, v::Float64, w::Float64)\n\n    Calculate the memory function χ(Ω) of the polaron at zero-temperatures (equation (35a) in FHIP 1962) for a given frequency Ω. v and w are the variational polaron parameters that minimise the free energy, for the supplied α Frohlich coupling.\n\"\"\"\nfunction χ(Ω, α, v, w)\n\n    # FHIP1962, page 1011, eqn (47c).\n    R = (v^2 - w^2) / (w^2 * v)\n\n    # FHIP1962, page 1009, eqn (35c) with β → ∞.\n    D(x) = w^2 / v^2 * (R * (1 - cos(v * x)) - 1im * (R * sin(v * x) + x))\n\n    # FHIP1962, page 1009, eqn (36) with β → ∞.\n    S(x) = 2 * α / (3 * √π) * exp(1im * x) / (D(x))^(3 / 2)\n\n    # FHIP1962, page 1009, eqn (35a). Set upper limit < ∞ but very large so cos argument finite.\n    integrand(x) = (1 - exp(-1im * Ω * x)) * imag(S(x))\n    QuadGK.quadgk(x -> integrand(x), 0.0, 1e200)[1]\nend\n\n\"\"\"\nχ_dc(β::Float64, α::Float64, v::Float64, w::Float64)\n\n    Calculate the memory function lim(Ω → 0){χ(Ω) / Ω} of the polaron at finite temperatures (equation (35a) in FHIP 1962) at zero frequency. v and w are the variational polaron parameters that minimise the free energy, for the supplied α Frohlich coupling.\n\"\"\"\nfunction χ_dc(β, α, v, w)\n\n    # FHIP1962, page 1011, eqn (47c).\n    R = (v^2 - w^2) / (w^2 * v)\n\n    # FHIP1962, page 1009, eqn (35c).\n    D(x) = w^2 / v^2 * (R * (1 - cos(v * x)) * coth(β * v / 2) + x^2 / β - 1im * (R * sin(v * x) + x))\n\n    # FHIP1962, page 1009, eqn (36).\n    S(x) = 2 * α / (3 * √π) * (exp(1im * x) + 2 * cos(x) / (exp(β) - 1)) / (D(x))^(3 / 2)\n\n    # Set frequency small enough to mimic Ω = 0 without generating numerical instabilities in integral.\n    Ω = 1e-200\n\n    # FHIP1962, page 1009, eqn (35a). Readily divided by Ω to get sinc function in integrand rather than sine which would give 0 all the time.\n    integrand(x) = (1 - exp(-1im * Ω * x)) * imag(S(x)) / Ω\n    QuadGK.quadgk(x -> integrand(x), 0.0, Inf)[1]\nend", "meta": {"hexsha": "c191c24fbd858d33c8078256decb7b40ec8c755b", "size": 2754, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/memory_function.jl", "max_stars_repo_name": "Neutrino155/PolaronPathIntegrals.jl", "max_stars_repo_head_hexsha": "ed17579530069fb1f8f064a151b933267be8f973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-30T22:38:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T11:00:29.000Z", "max_issues_repo_path": "src/memory_function.jl", "max_issues_repo_name": "Neutrino155/PolaronPathIntegrals.jl", "max_issues_repo_head_hexsha": "ed17579530069fb1f8f064a151b933267be8f973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/memory_function.jl", "max_forks_repo_name": "Neutrino155/PolaronPathIntegrals.jl", "max_forks_repo_head_hexsha": "ed17579530069fb1f8f064a151b933267be8f973", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1044776119, "max_line_length": 257, "alphanum_fraction": 0.5777051561, "num_tokens": 1131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768144, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7732629717420885}}
{"text": "include(\"Kernals.jl\")\ninclude(\"gaussian_process.jl\")\n\n\nfunction uniform(a,b,N)\n    rand(N)*(b-a)+a\nend\n\nusing Distributions\nn=50 #number of test points\nN=10;#Number of training points\nXtest=linspace(-5,5,n); #Xtest are all of available points to check on the axis\nX=uniform(-5,5,N); #X is the values we will sample at and train\nnoise_dist=Normal(0,10.0^(-6)) #Distribution of Noise\nY=sin(X)+rand(noise_dist) #Y is our function values with noise \nK=cov_gen(std_exp_square_ker,Xtest,Xtest)+eye(length(Xtest))*1e-6\nL=ctranspose(chol(K));\ndist=MvNormal(zeros(n),eye(K)) # We draw f from N(0,I)L which is the same as N(0,K)\nfprior=L*rand(dist,3); #Each column is a function\n\n\n\nusing PyPlot\nfig = figure(\"pyplot_plot\",figsize=(5,5))\nax = axes()\nfill_between(Xtest,-2*diag(K),2*diag(K),facecolor=\"#a6a6a6\")#This fills confindence interval for two standard \n#deviations, currently the variance is one (as we take off diagonal)\nplot(Xtest,fprior,alpha=0.75)\ntitle(\"N=3 Multivariate Gaussians\")\nylabel(\"f(x)\")\nxlabel(\"x\")\ngrid(\"off\")\nshow()\n\n\n\nD=[(X[i],Y[i]) for i=1:length(X)];\nmu,sigma,D = gaussian_process(std_exp_square_ker,D,1e-6,Xtest);\nmu=reshape(mu,length(mu));\nsigma=reshape(sigma,length(sigma));\ny=map(x->x[2],D);   # these are our y noisy function\nx=map(x->x[1],D); #These are our x training points\nusing PyPlot\nfig = figure(\"pyplot_plot\",figsize=(5,5))\nax = axes()\nfill_between(Xtest,mu-2*sigma,mu+2*sigma,facecolor=\"#a6a6a6\")#This fills confindence interval for two standard \n#deviations, currently the variance is one (as we take off diagonal)\nplot(x,y,linewidth=0,marker=\"o\")\n\ntitle(\"N=3 Multivariate Gaussians\") \nylabel(\"f(x)\")\nxlabel(\"x\")\ngrid(\"off\")\nshow()\n", "meta": {"hexsha": "e9dec52a2af22edbfc46e8ddc25510409f308fe2", "size": 1665, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Builds:RNN's:Examples/examples/Gauss_Proc_run1.jl", "max_stars_repo_name": "LawrenceMMStewart/Bayesian_Optimization", "max_stars_repo_head_hexsha": "e04aa7c8447d3226ae712eee563def0b5e55f843", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-08-09T21:17:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T16:49:48.000Z", "max_issues_repo_path": "Builds:RNN's:Examples/examples/Gauss_Proc_run1.jl", "max_issues_repo_name": "LawrenceMMStewart/Bayesian_Optimization", "max_issues_repo_head_hexsha": "e04aa7c8447d3226ae712eee563def0b5e55f843", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Builds:RNN's:Examples/examples/Gauss_Proc_run1.jl", "max_forks_repo_name": "LawrenceMMStewart/Bayesian_Optimization", "max_forks_repo_head_hexsha": "e04aa7c8447d3226ae712eee563def0b5e55f843", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2727272727, "max_line_length": 111, "alphanum_fraction": 0.7213213213, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.773261999692079}}
{"text": "function circle_len1(θ; n_pts=1000000)\n    xmin, xmax = cos(θ), 1\n    ts = sort(rand(n_pts))\n    xs = @. (xmax-xmin)/(1. - 0.) * ts + xmin\n    ys = @. sqrt(1 - xs * xs)\n    d = zero(eltype(xs))\n    for i in 1:(length(xs)-1)\n        d += sqrt((xs[i+1]-xs[i])^2+(ys[i+1]-ys[i])^2)\n    end\n    println(d)\n    println(θ)\nend\n\nfunction circle_len2(θ; n_pts=1000000)\n    xmin, xmax = cos(θ), 1\n    t = sort(rand(n_pts))\n    x = @. (xmax-xmin)/(1. - 0.) * t + xmin\n    y = @. sqrt(1 - x * x)\n    ds = @. sqrt((x[2:end] - x[1:end-1])^2+(y[2:end] - y[1:end-1])^2)\n    d=sum(ds)\n    println(d)\n    println(θ)\nend\n\nfunction circle_len3(θ; n_pts=1000000)\n    ts = θ * sort(rand(n_pts))\n    xs = sin.(ts)\n    ys = cos.(ts)\n    d = zero(eltype(xs))\n    for i in 1:(length(xs)-1)\n        d += sqrt((xs[i+1]-xs[i])^2+(ys[i+1]-ys[i])^2)\n    end\n    println(d)\n    println(θ)\nend\n\ncircle_len3(2π)", "meta": {"hexsha": "eaa47560be1edba56ffcd7a0107a048e533876c0", "size": 878, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "curveLength/curve_length.jl", "max_stars_repo_name": "terasakisatoshi/juliaExer", "max_stars_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-02T01:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-04T12:03:25.000Z", "max_issues_repo_path": "curveLength/curve_length.jl", "max_issues_repo_name": "terasakisatoshi/juliaExer", "max_issues_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "curveLength/curve_length.jl", "max_forks_repo_name": "terasakisatoshi/juliaExer", "max_forks_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7297297297, "max_line_length": 69, "alphanum_fraction": 0.5079726651, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7732619931951642}}
{"text": "#############################\n##  Numerical experiments associated with section 5.1.2\n#############################\n## While the paper does not explicitly treat third kind Volterra equations, an extension to these\n## cases is relatively straightforward. Note that while in general there won't be exponential convergence\n## unless the involved powers are favorably smooth, our method still achieves higher accuracy than many competitor methods.\n##\n\nusing ApproxFun, MultivariateOrthogonalPolynomials, BandedMatrices, BlockBandedMatrices, SpecialFunctions, Plots\nusing SparseVolterraExamples\n\n#############################\n## Problem in Equation (17)\n#############################\n####\n## The following block computes the coefficient vector of the approximation for a given polynomial order of approximation n.\n## The accuracy obtained depends on both the polynomial order for the multiplication as well as the solution.\n## Choosing the same order is fine in most cases but better accuracy can be obtained by adjusting for a given problem.\nfunction solveSec512A(n,multin)\n    gf(x) = x^(2/3)*(10/3*x^(7/3)-3/16*x^(14/3));\n    Kfun(x,y) = y;\n    V = triVolterraFullKernelOpP01(Kfun,n,true);\n        V = reflectPabtoPba(n)*WLoweringP01P00(n)*V;\n        V = Conversion(Jacobi(0,0,0..1),Jacobi(1,2,0..1))[1:n,1:n]*V;\n        V = Multiplication(Fun(x->x^(2/3),Jacobi(1,2,0..1),multin),Jacobi(1,2,0..1))[1:n,1:n]*Derivative(Jacobi(0,1,0..1),1)[1:n,1:n]-V\n    coeff = [DirectEvalLHSP10at0(n);V[1:n-1,1:n]] \\ [0;pad(Fun(x->gf(x),Jacobi(1,2, 0..1)).coefficients,n-1)]\n    return coeff\nend\n####\n## Plot the analytic solution against the computed solution\ncoeff = solveSec512A(50,40)\nplot(Fun(Jacobi(0,1,0..1),coeff),grid=false,xlabel=\"x\",ylabel=\"u(x)\",label=\"sparse method\")\nplot!(x->(x)^(10/3),0,1,grid=false,xlabel=\"x\",ylabel=\"u(x)\",label=\"analytic solution\")\n####\n## Check the numerical error.\nplot(x->(Fun(Jacobi(0,1,0..1),coeff)(x)-(x)^(10/3)),0,1,grid=false,xlabel=\"x\",ylabel=\"error\",label=false)\n\n#############################\n## Problem in Equation (18)\n#############################\n####\n## The following block computes the coefficient vector of the approximation for a given polynomial order of approximation n.\n## The accuracy obtained depends on both the polynomial order for the multiplication as well as the solution.\n## Choosing the same order is fine in most cases but better accuracy can be obtained by adjusting for a given problem.\nfunction solveSec512B(n,multin)\n    gf(x) = 9/2*x^4-1/20*x^(11/2)-1/6*x^6;\n    Kfun(x,y) = sqrt(y);\n    V = triVolterraFullKernelOpP01(Kfun,n,true,n);\n        V = reflectPabtoPba(n)*WLoweringP01P00(n)*V;\n        V = Conversion(Jacobi(0,0,0..1),Jacobi(1,2,0..1))[1:n,1:n]*V;\n        V = Multiplication(Fun(x->sqrt(x),Jacobi(1,2,0..1),multin),Jacobi(1,2,0..1))[1:n,1:n]*Derivative(Jacobi(0,1,0..1),1)[1:n,1:n]-(1/20)*Conversion(Jacobi(0,1,0..1),Jacobi(1,2,0..1))[1:n,1:n]*Multiplication(Fun(x->x,Jacobi(0,1,0..1),n),Jacobi(0,1,0..1))[1:n,1:n]-V\n    coeff = [DirectEvalLHSP10at0(n);V[1:n-1,1:n]] \\ [0;pad(Fun(x->gf(x),Jacobi(1,2, 0..1)).coefficients,n-1)]\n    return coeff\nend\n####\n## Plot the analytic solution against the computed solution\ncoeff = solveSec512B(80,30)\nplot(Fun(Jacobi(0,1,0..1),coeff),grid=false,xlabel=\"x\",ylabel=\"u(x)\",label=\"sparse method\")\nplot!(x->(x)^(9/2),0,1,grid=false,xlabel=\"x\",ylabel=\"u(x)\",label=\"analytic solution\")\n####\n## Check the numerical error.\nplot(x->(Fun(Jacobi(0,1,0..1),coeff)(x)-(x)^(9/2)),0,1,grid=false,xlabel=\"x\",ylabel=\"error\",label=false)\n", "meta": {"hexsha": "301317277bc868cbf6f1a8a5e436485f716c2dac", "size": 3524, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Section 5-1-2 - Methods for third kind VIDEs.jl", "max_stars_repo_name": "TSGut/SparseVolterraExamples.jl", "max_stars_repo_head_hexsha": "277733c70dfe78b65d1d9ad289de9dbeacda27b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-18T16:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T16:58:42.000Z", "max_issues_repo_path": "examples/Section 5-1-2 - Methods for third kind VIDEs.jl", "max_issues_repo_name": "TSGut/SparseVolterraExamples.jl", "max_issues_repo_head_hexsha": "277733c70dfe78b65d1d9ad289de9dbeacda27b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-09T15:39:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T15:59:37.000Z", "max_forks_repo_path": "examples/Section 5-1-2 - Methods for third kind VIDEs.jl", "max_forks_repo_name": "TSGut/SparseVolterraExamples.jl", "max_forks_repo_head_hexsha": "277733c70dfe78b65d1d9ad289de9dbeacda27b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.9365079365, "max_line_length": 268, "alphanum_fraction": 0.6597616345, "num_tokens": 1121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.773261985745465}}
{"text": "module Flatland\n\nusing LinearAlgebra\n\nabstract type Shape end\n\nabstract type AbstractRectangle <: Shape end\n\nmutable struct Rectangle <: AbstractRectangle\n    x::Float64\n    y::Float64\n    l::Float64\n    w::Float64\n    function Rectangle((x, y); l=1.0, w=1.0)\n        return new(x, y, l, w)\n    end\nend\n\nfunction Rectangle((xmin, xmax), (ymin, ymax))\n    @assert xmin < xmax && ymin < ymax \"Corners have to be ordered: `xmin < xmax && ymin < ymax `\"\n    x = (xmin + xmax) / 2\n    y = (ymin + ymax) / 2\n    l = xmax - xmin\n    w = ymax - ymin\n    return Rectangle((x, y), l=l, w=w)\nend\n\nmutable struct Square <: AbstractRectangle\n    x::Float64\n    y::Float64\n    l::Float64\n    function Square((x, y); l=1.0)\n        return new(x, y, l)\n    end\nend\n\nlw(shape::Rectangle) = shape.l, shape.w\nlw(shape::Square) = shape.l, shape.l\n\nmutable struct RegularPolygon{N} <: Shape \n    x::Float64\n    y::Float64\n    R::Float64\n    θ::Float64  # angle\n    function RegularPolygon((x, y), n::Int; R=1.0, θ=0.0)\n        @assert n ≥ 3 \"polygons need a minimum of three corners\"\n        return new{n}(x, y, R, θ)\n    end\nend\n\n#=\n`Circle`s are pretty straightforward, having a center and a radius.\n=#\n\nmutable struct Circle <: Shape\n    x::Float64\n    y::Float64\n    R::Float64\n    function Circle((x, y); R=1.0)\n        return new(x, y, R)\n    end\nend\n\nabstract type AbstractTriangle <: Shape end\n\nmutable struct Triangle <: AbstractTriangle\n    x1::Float64\n    x2::Float64\n    x3::Float64\n    y1::Float64\n    y2::Float64\n    y3::Float64\n    Triangle((x1, y1), (x2, y2), (x3, y3)) = new(x1, x2, x3, y1, y2, y3)\nend\n\n\nncorners(::AbstractRectangle) = 4\nncorners(::AbstractTriangle) = 3\nncorners(::Circle) = 0\nncorners(::RegularPolygon{N}) where {N} = N\n\n\n\nfunction corners(shape::AbstractRectangle)\n    x, y = center(shape)\n    l, w = lw(shape)\n    return [(x+l/2, y+w/2), (x-l/2, y+w/2), (x-l/2, y-w/2), (x+l/2, y-w/2)]\nend\n\nfunction corners(shape::RegularPolygon)\n    x, y = center(shape)\n    θ = shape.θ\n    R = shape.R\n    n = ncorners(shape)\n    return [(x+R*cos(t+θ), y+R*sin(t+θ)) for t in range(0, step=2π/n, length=n)]\nend\n\nfunction corners(shape::Triangle)\n    return [(shape.x1, shape.y1), (shape.x2, shape.y2), (shape.x3, shape.y3)]\nend\n\ncenter(shape::Shape) = shape.x, shape.y\n\nfunction center(shape::Triangle)\n    (x1, y1), (x2, y2), (x3, y3) = corners(shape)\n    return ((x1 + x2 + x3) / 3, (y1 + y2 + y3) / 3)\nend\n\n# xycoords returns two of the outline vectors: ycoords and ycoords, for `Circle`, you can specify the number of points to take\n# (50 by default).\n\nxycoords(s::Shape) = [first(p) for p in corners(s)], [last(p) for p in corners(s)]\n\nfunction xycoords(shape::Circle; n=50)\n    ts = range(0, 2π, length=n)\n    return shape.x .+ shape.R * cos.(ts), shape.y .+ shape.R * sin.(ts)\nend\n\n# x,y-bounding\n\n#=\nThe fuctions below yield the outer limits of the x and y axes of your shape. Can you complete the method as a oneliner?\n\nHint: The function `extrema` could be useful here...\n=#\n\nxlim(shape::Shape) = extrema(xycoords(shape)[1])\nxlim(shape::Circle) = (shape.x - shape.R, shape.x + shape.R)\nxlim(shape::AbstractRectangle) = (shape.x - 0.5shape.l, shape.x + 0.5shape.l)\n\nylim(shape::Shape) = extrema(xycoords(shape)[2])\nylim(shape::Circle) = (shape.y - shape.R, shape.y + shape.R)\nylim(shape::AbstractRectangle) = (shape.y - 0.5lw(shape)[2], shape.y + 0.5lw(shape)[2])\n\nboundingbox(shape::Shape) = Rectangle(xlim(shape), ylim(shape))\n\n# # Area\n\n#=\nNext, we compute the area of our shapes. \n=#\n\narea(shape::AbstractRectangle) = prod(lw(shape))\n\nfunction area(shape::RegularPolygon)\n    R = shape.R\n    n = ncorners(shape)\n    dθ = 2π / n  # angle of a triangle\n    h = R * cos(dθ/2)\n    b = R * sin(dθ/2)\n    return b * h * n\nend\n\nfunction area(shape::Triangle)\n    (x1, y1), (x2, y2), (x3, y3) = corners(shape)\n    return abs(x1*y2 + x2*y3 + x3*y1 - y1*x2 - y2*x3 - y3*x1) / 2\nend\n\narea(shape::Circle) = shape.R^2 * π\n\n# move, rotate and scale\n\n#=\nMoving, rotating and scaling should also work.\nImportant, the functions work in-place, meaning that the modify your structure (that is why use use `mutable` structures).\n\nFor `Circle` and `AbstractRectangle` types, `rotate!` leaves them unchanged.\n\nHint: Rotations are in radials, so between $0$ and $2\\pi$.\n=#\n\nfunction move!(shape::Shape, (dx, dy))\n    shape.x += dx\n    shape.y += dy\nend\n\nfunction move!(shape::Triangle, (dx, dy))\n    shape.x1 += dx\n    shape.x2 += dx\n    shape.x3 += dx\n    shape.y1 += dy\n    shape.y2 += dy\n    shape.y3 += dy\n    shape\nend\n\nrotate!(shape::Union{Circle,AbstractRectangle}, dθ) = shape\n\nfunction rotate!(shape::RegularPolygon, dθ)\n    shape.θ += dθ\n    shape\nend\n\n\nfunction rotate!(shape::Triangle, dθ)\n    xc, yc = center(shape)\n    # center triangle\n    move!(shape, (-xc, -yc))\n    (x1, y1), (x2, y2), (x3, y3) = corners(shape)\n    cosdθ = cos(dθ)\n    sindθ = sin(dθ)\n    shape.x1 = x1 * cos(dθ) - y1 * sin(dθ)\n    shape.x2 = x2 * cos(dθ) - y2 * sin(dθ)\n    shape.x3 = x3 * cos(dθ) - y3 * sin(dθ)\n    shape.y1 = y1 * cos(dθ) + x1 * sin(dθ)\n    shape.y2 = y2 * cos(dθ) + x2 * sin(dθ)\n    shape.y3 = y3 * cos(dθ) + x3 * sin(dθ)\n    # set to original position\n    move!(shape, (xc, yc))\n    shape\nend\n\nfunction scale!(shape::Union{Circle,RegularPolygon}, a)\n    @assert a > 0 \"scaling has to be a positive number\"\n    shape.R *= a\nend\n\nfunction scale!(shape::Rectangle, a)\n    @assert a > 0 \"scaling has to be a positive number\"\n    shape.w *= a\n    shape.l *= a\nend\n\nfunction scale!(shape::Square, a)\n    @assert a > 0 \"scaling has to be a positive number\"\n    shape.w *= a\nend\n\nfunction scale!(shape::Triangle, a)\n    @assert a > 0 \"scaling has to be a positive number\"\n    xc, yc = center(shape)\n    move!(shape, (-xc, -yc))\n    shape.x1 *= a\n    shape.x2 *= a\n    shape.x3 *= a\n    shape.y1 *= a\n    shape.y2 *= a\n    shape.y3 *= a\n    move!(shape, (xc, yc))\n    return shape\nend\n\n# plotting utilities\n\n\nusing RecipesBase\n\n#=\nOK, let's take a look at our shapes! We use `RecipesBase` to allow plotting.\nThis falls back on `xycoords` (can you see how it works?), so make sure this method is operational.\n=#\n\n@recipe function f(s::Shape)\n    xguide --> \"x\"\n    yguide --> \"y\"\n    label --> \"\"\n    aspect_ratio := :equal\n    seriestype := :shape\n    x, y = xycoords(s)\n    return x, y\nend\n\n\nBase.in((x, y), s::Circle) = (s.x - x)^2 + (s.y - y)^2 ≤ s.R^2\n\nfunction Base.in((x, y), shape::AbstractRectangle)\n    xc, yc = center(shape)\n    l, w = lw(shape)\n    return (xc - 0.5l ≤ x ≤ xc + 0.5l) && (yc - 0.5w ≤ y ≤ yc + 0.5w)\nend\n\ncrossprod((x1, y1), (x2, y2)) = x1 * y2 - x2 * y1\n\n\"\"\"\n    same_side((a, b), p, q)\n\nGiven a line described by two points, `a` and `b`, check whether two points\n`p` and `q` are on the same side.\n\"\"\"\nfunction same_side((a, b), p, q)\n    # normal vector on the line\n    n = (a[2] - b[2], b[1] - a[1])\n    # check if they are on both sides by projection\n\treturn sign(n ⋅ (p .- a)) == sign(n ⋅ (q .-a ))\nend\n\n\"\"\"\n    linecross((p1, p2), (q1, q2))\n\nCheck whether line segments `(p1, p2)` and `(q1, q2)` intersect.\n\"\"\"\nfunction linecross((p1, p2), (q1, q2))\n    v = p2 .- p1\n    w = q2 .- q1\n    vw = crossprod(v, w)\n    t = crossprod(q1 .- p1, w) / vw\n    s = crossprod(q1 .- p1, v) / vw\n    return 0.0 ≤ t ≤ 1.0 &&  0.0 ≤ s ≤ 1.0\nend\n\nfunction Base.in(q, s::Triangle)\n    p1, p2, p3 = corners(s)\n    return same_side((p1, p2), p3, q) && \n            same_side((p2, p3), p1, q) &&\n            same_side((p3, p1), p2, q)\nend\n\nfunction Base.in(q, shape::Shape)\n    corns = corners(shape)\n    n = ncorners(shape)\n    c = center(shape)\n    # check if q is always on the same side as the center\n    for i in 1:n-1\n        !same_side((corns[i], corns[i+1]), c, q) && return false\n    end\n    !same_side((corns[end], corns[1]), c, q) && return false\n    return true\nend\n\n@inline function boundboxes_overlap(shape1::Shape, shape2::Shape)\n    (xmin1, xmax1), (xmin2, xmax2) = xlim(shape1), xlim(shape2)\n    (ymin1, ymax1), (ymin2, ymax2)  = ylim(shape1), ylim(shape2)\n    # check for x and y overlap\n    return (xmin1 ≤ xmin2 ≤ xmax1 || xmin1 ≤ xmax2 ≤ xmax1 || xmin2 ≤ xmin1 ≤ xmax2) &&\n            (ymin1 ≤ ymin2 ≤ ymax1 || ymin1 ≤ ymax2 ≤ ymax1 ||ymin2 ≤ ymin1 ≤ ymax2)\nend\n\nBase.intersect(shape1::AbstractRectangle, shape2::AbstractRectangle) = boundboxes_overlap(shape1, shape2)\n\nfunction Base.intersect(shape1::T, shape2::T) where {T<:Shape}\n    (shape1.x - shape2.x)^2 + (shape1.y - shape2.y)^2 > (shape1.R + shape2.R)^2 && return false\n    return center(shape1) ∈ shape2 ||\n            center(shape2) ∈ shape1 ||\n            any(c->c ∈ shape2, corners(shape1)) ||\n            any(c->c ∈ shape1, corners(shape2))\nend\n\n\n\nfunction Base.intersect(shape1::Triangle, shape2::Triangle)\n    # first check if the bounding boxes overlap\n    boundboxes_overlap(shape1, shape2) || return false\n    # yes? \n    # now check if one shape is within the other one\n    p1, p2, p3 = corners(shape1)\n    q1, q2, q3 = corners(shape2)\n    (p1 ∈ shape2 || q1 ∈ shape1) && return true\n    # if not, we have to check whether two lines intersect\n    return linecross((p1, p2), (q1, q2)) ||\n            linecross((p1, p2), (q2, q3)) ||\n            linecross((p1, p2), (q1, q3)) ||\n            linecross((p3, p2), (q1, q2)) ||\n            linecross((p3, p2), (q2, q3)) ||\n            linecross((p3, p2), (q1, q3))\nend\n    \n\n\nfunction Base.intersect(shape1::Circle, shape2::Circle)\n    c1 = center(shape1)\n    c2 = center(shape2)\n    d = sum(abs2, c1 .- c2) |> sqrt\n    return d < shape1.R + shape2.R\nend\n\n\n# random generation\n\n#=\nFinally, `randplace!` takes a shape, rotates it randomly and moves it randomly within the bounds of the limits\n`(xmin, xmax)` and `(ymin, ymax)`.\n=#\n\n\nfunction randplace!(shape::Shape, (xmin, xmax), (ymin, ymax); rotate=true)\n    # random rotation\n    rotate && rotate!(shape, 2π * rand())\n    # random tranlation within bound\n    dxmin, dxmax = (xmin, xmax) .- xlim(shape)\n    dymin, dymax = (ymin, ymax) .- ylim(shape)\n    dx = (dxmax - dxmin) * rand() + dxmin\n    dy = (dymax - dymin) * rand() + dymin\n    move!(shape, (dx, dy))\n    return shape\nend\n\nfunction rejection_sampling!(shapes::Vector{<:Shape}, xlims, ylims)\n    trials = 0\n    n = length(shapes)\n    while true\n        trials += 1\n        for (i, shape) in enumerate(shapes)\n            randplace!(shape, xlims, ylims)\n            # any intersection with previous shapes: start again\n            overlap = false\n            for j in 1:i-1\n                if intersect(shape, shapes[j])\n                    overlap = true\n                    break\n                end\n            end\n            overlap && break\n            i==n && return shapes, trials\n        end\n    end\nend\n\n# function to place `n` copies of a given `shape`.\n\nfunction rejection_sampling(shape, n, xlims, ylims)\n    shapes = [deepcopy(shape) for i in 1:n]\n    trials = rejection_sampling!(shapes, xlims, ylims)\n    return shapes, trials\nend\n\nend", "meta": {"hexsha": "e32d9a767875046a6960d52309731a662712fd7d", "size": 10897, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/flatland.jl", "max_stars_repo_name": "jpgmolina/DS-Julia2925", "max_stars_repo_head_hexsha": "4d96351afb72f4107fa12561a6a460dcd3c617e3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-02-03T14:07:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T13:27:08.000Z", "max_issues_repo_path": "src/flatland.jl", "max_issues_repo_name": "jpgmolina/DS-Julia2925", "max_issues_repo_head_hexsha": "4d96351afb72f4107fa12561a6a460dcd3c617e3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 74, "max_issues_repo_issues_event_min_datetime": "2020-11-23T22:50:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:49:00.000Z", "max_forks_repo_path": "src/flatland.jl", "max_forks_repo_name": "jpgmolina/DS-Julia2925", "max_forks_repo_head_hexsha": "4d96351afb72f4107fa12561a6a460dcd3c617e3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-01-31T14:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-19T07:11:30.000Z", "avg_line_length": 26.1947115385, "max_line_length": 126, "alphanum_fraction": 0.6016334771, "num_tokens": 3612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8670357529306639, "lm_q1q2_score": 0.7732320662393943}}
{"text": "using Distributions\nusing StatsBase: var\n\n########## GDEMO ##################\n# Example partially based on https://stats.stackexchange.com/a/266672/234110 and\n# http://www2.stat.duke.edu/~rcs46/modern_bayes17/lecturesModernBayes17/lecture-7/07-gibbs.pdf.\n# We follow the model used in https://github.com/TuringLang/Turing.jl/blob/60724e22a9831066fc2e0e82d428bd4922bda6e8/test/test_utils/models.jl#L2,\n# with normally distributed observations and conjugate priors for both parameters:\n# λ ~ Gamma(α₀, θ₀)\n# m ~ Normal(0, √(1 / λ))\n# Xᵢ ~ Normal(m, √(1 / λ)) (iid)\n    \n\nfunction gdemo_forward(N, α₀, θ₀)\n    λ = rand(Gamma(α₀, θ₀))\n    σ = √(1 / λ)\n    m = rand(Normal(0, σ))\n    x = rand(Normal(m, σ), N)\n    return (m=m, λ=λ), x\nend\n\nfunction gdemo_logjoint(α₀, θ₀, x, m, λ)\n    σ = √(1 / λ)\n    return logpdf(Gamma(α₀, θ₀), λ) +\n        logpdf(Normal(0, σ), m) +\n        sum(logpdf.(Normal(m, σ), x))\nend\n\nfunction gdemo_statistics(x)\n    # The conditionals and posterior can be formulated in terms of the following statistics:\n    N = length(x) # number of samples\n    x̄ = mean(x) # sample mean\n    s² = var(x; mean=x̄, corrected=false) # sample variance\n    return N, x̄, s²\nend\n\nfunction gdemo_cond_m(α₀, θ₀, x, λ)\n    N, x̄, s² = gdemo_statistics(x)\n    mₙ = N * x̄ / (N + 1)\n    λₙ = λ * (N + 1)\n    σₙ = √(1 / λₙ)\n    return Normal(mₙ, σₙ)\n    # return Normal(7/6, 0.00001)\nend\n\nfunction gdemo_cond_λ(α₀, θ₀, x, m)\n    N, x̄, s² = gdemo_statistics(x)\n    αₙ = α₀ + (N - 1) / 2 + 1\n    βₙ = (s² * N / 2 + m^2 / 2 + inv(θ₀))\n    return Gamma(αₙ, inv(βₙ))\nend\n\n\nfunction gdemo(x; α₀=2.0, θ₀=inv(3.0))\n    cond_m((λ,)) = gdemo_cond_m(α₀, θ₀, x, λ)\n    cond_λ((m,)) = gdemo_cond_λ(α₀, θ₀, x, m)\n    conditionals = (m=cond_m, λ=cond_λ)\n    return conditionals\nend\n\n\n############### Mixture of two Gaussians ####################\n# see http://www.cs.columbia.edu/~blei/fogm/2015F/notes/mixtures-and-gibbs.pdf\n# μ ~ arraydist(Normal.(fill(m, K), fill(λ, K)))\n# z ~ arraydist(Categorical.(fill(π, N)))\n# x ~ arraydist(Normal.(μ[z], σ))\n\nfunction mixture_cond_z(π, K, m, λ, σ, x, μ)\n    function mixtureweight(x)\n        p = π .* pdf.(Normal.(μ, σ), Ref(x))\n        return p ./ sum(p)\n    end\n    return Product(Categorical.(mixtureweight.(x)))\nend\n\nfunction mixture_cond_μ(π, K, m, λ, σ, x, z)\n    n = [count(z .== k) for k = 1:K]\n\n    # If there were no observations assigned to center `k`, `n[k] == 0`, and\n    # we use the prior instead.\n    x_bar = [(n[k] != 0) ? (sum(x[z .== k]) / n[k]) : m for k = 1:K]\n    λ_hat = [(n[k] != 0) ? inv(n[k] / σ^2 + 1/λ^2) : λ for k = 1:K]\n    μ_hat = [(n[k] != 0) ? x_bar[k] * (n[k] / σ^2) * λ_hat[k] : m for k = 1:K]\n\n    return Product(Normal.(μ_hat, λ_hat))\nend\n\n\nfunction mixture(π, K, m, λ, σ, x)\n    cond_z((μ,)) = mixture_cond_z(π, K, m, λ, σ, x, μ)\n    cond_μ((z,)) = mixture_cond_μ(π, K, m, λ, σ, x, z)\n    return (z=cond_z, μ=cond_μ)\nend\n\n\n\n########### 1D ISING MODEL #########################\nfunction ising_conditional(β, i, M)\n    return function (neighbours)\n        x_prev = neighbours[mod1(i - 1, M - 1)]\n        x_next = neighbours[mod1(i, M - 1)]\n        p₁ = exp(-β * (x_prev + x_next))\n        p₂ = exp(-β * (abs(x_prev - 1) + abs(x_next - 1)))\n        return Bernoulli(p₁ / (p₁ + p₂))\n    end\nend\n\nfunction isingdemo(β, M)\n    # One dimensional Ising model on a circle, without external field;\n    # see https://stats.stackexchange.com/a/312044/234110\n    conditional_dists = [Symbol(:x, i) => ising_conditional(β, i, M) for i = 1:M]\n    conditionals = merge(NamedTuple(), conditional_dists)\nend\n\nfunction ising_conditional(β, i, j, M, N)\n    return function (neighbours)\n        x_prev = neighbours[mod1(i - 1, M - 1)]\n        x_next = neighbours[mod1(i, M - 1)]\n        x_down = neighbours[mod1(j - 1, N - 1)]\n        x_up = neighbours[mod1(j, N - 1)]\n        p₁ = exp(-β * (x_prev + x_next + x_up + x_down))\n        p₂ = exp(-β * (abs(x_prev - 1) + abs(x_next - 1) + abs(x_up - 1) + abs(x_down - 1)))\n        return Bernoulli(p₁ / (p₁ + p₂))\n    end\nend\n\nfunction isingdemo(β, M, N)\n    # One dimensional Ising model on a circle, without external field;\n    # see https://stats.stackexchange.com/a/312044/234110\n    conditional_dists = [Symbol(:x, i, j) => ising_conditional(β, i, j, M, N) for i = 1:M, j = 1:N]\n    conditionals = merge(NamedTuple(), conditional_dists)\nend\n\nfunction visualize_ising(θ::AbstractVector{<:Real})\n    join(v == 1 ? '\\u2588' : ' ' for v in values(θ))\nend\n\nfunction visualize_ising(θ::AbstractMatrix{<:Real})\n    join((join(v == 1 ? '\\u2588' : ' ' for v in row) for row in eachrow(θ)), '\\n')\nend\n", "meta": {"hexsha": "9bc27d63d04be11e003f0b5c622d89fde89637b8", "size": 4586, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testmodels.jl", "max_stars_repo_name": "phipsgabler/LittleGibbs.jl", "max_stars_repo_head_hexsha": "682c9d899cb49780c63d00dcdc52f8c0597943ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-04T16:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T16:47:18.000Z", "max_issues_repo_path": "test/testmodels.jl", "max_issues_repo_name": "phipsgabler/LittleGibbs.jl", "max_issues_repo_head_hexsha": "682c9d899cb49780c63d00dcdc52f8c0597943ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-02-17T18:24:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-10T08:07:44.000Z", "max_forks_repo_path": "test/testmodels.jl", "max_forks_repo_name": "phipsgabler/LittleGibbs.jl", "max_forks_repo_head_hexsha": "682c9d899cb49780c63d00dcdc52f8c0597943ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.524822695, "max_line_length": 145, "alphanum_fraction": 0.5883122547, "num_tokens": 1709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.773218371620687}}
{"text": "#=\nAuthor: Stephan Scholz\nYear: 2021\n\nThis file contains a machine learning approach (SciML) for the van der Pol oscillator\n=#\n\n# ODE function of van der Pol oscillator\nfunction vdp(dx, x, p, t)\n\n    μ = p[1]\n\n    dx[1] = μ * (x[1] - 1/3 * x[1]^3 - x[2] ) \n    dx[2] = 1/μ * x[1]\nend\n\ntspan = (0.0, 100.0) # time span\nx0    = [0.5, 0.5]   # initial values\np     = [1.0]        # parameter: μ\ntsteps= 0.1          # saved time steps\n\n\nusing DifferentialEquations\nprob = ODEProblem( vdp, x0, tspan, p )      # Build ODEProblem\nsol = solve(prob, Tsit5(), saveat = tsteps) # Solve ODEProblem\n\n# using Plots\n# plot(sol, title=\"Solution of the van der Pol oscillator\")\n\n\n# MACHINE LEARNING\nfunction loss(p)\n    sol_pred = solve(prob, Tsit5(), p=p, saveat = tsteps)\n    loss = sum(abs2, sol - sol_pred)\n    return loss, sol_pred\nend\n\npred_param = [] # Stores all found parameters\n\ncallback = function (p, l, pred)\n    display(l)\n    append!(pred_param, p)\n   \n    # Tell sciml_train to not halt the optimization. If return true, then\n    # optimization stops.\n    return false\nend\n\nusing DiffEqFlux\n\np_ml = [0.1] # Initial parameter\nloss(p_ml)   # Test whether loss function works\n\n# Run ML training\nresult_ode = DiffEqFlux.sciml_train(loss, p_ml, ADAM(0.1), cb = callback, maxiters=100)\n\n# Build and plot Cost function\nx_min = 0.1\nx_max = 2\nx_step = 0.01\nx_range = range(x_min,x_max,step=x_step)\nNlength = length(x_range)\n\nloss_results = zeros(Nlength)\nidx = 1;\nfor i in x_range\n   loss_results[idx],_ = loss([i])\n   idx += 1;\nend\n\n# Cost function \nplot(x_range, loss_results, label=\"loss\", title=\"Cost function\", xaxis=(\"Parameter μ\"))\n\n\n# Save Machine Learning results as gif\n@gif for pp in pred_param\n    sol_remade = solve(remake(prob, p=[pp]), Tsit5(), saveat=tsteps)\n    \n    # Phase portrait\n    pp_text = string( \"μ = \", string(round(pp; digits=3)) )\n    plot(sol_remade[1,:], sol_remade[2,:], annotations=(0.1, 0, Plots.text(pp_text, :left)), title=\"Phase portrait of van der Pol oscillator\", label=false)\n    \n    # Oscillation\n    # plot(sol_remade, title=\"Machine Learning of van der Pol oscillator\", label=[\"x1\" \"x2\"], legend=:bottomright)\n    \nend\n\n", "meta": {"hexsha": "8e6cf2a336effe1b4832d8eb410bbc6c24f81a37", "size": 2157, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/machine_learning/van_der_pol_oscillator.jl", "max_stars_repo_name": "stephans3/ProjectsTemplate.jl", "max_stars_repo_head_hexsha": "282dfb8aa97e867ff15327bd0f17223fc9a3777d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/machine_learning/van_der_pol_oscillator.jl", "max_issues_repo_name": "stephans3/ProjectsTemplate.jl", "max_issues_repo_head_hexsha": "282dfb8aa97e867ff15327bd0f17223fc9a3777d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/machine_learning/van_der_pol_oscillator.jl", "max_forks_repo_name": "stephans3/ProjectsTemplate.jl", "max_forks_repo_head_hexsha": "282dfb8aa97e867ff15327bd0f17223fc9a3777d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5113636364, "max_line_length": 155, "alphanum_fraction": 0.6601761706, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7732183678850397}}
{"text": "#Demo 2: Reflection coefficients\n#-------------------------------------------------------------------------------\nusing InspectDR\nusing Colors\nimport Graphics: width, height\n\n\n#==Input\n===============================================================================#\n\n#Constants\n#-------------------------------------------------------------------------------\nblack = RGB24(0, 0, 0)\nwhite = RGB24(1, 1, 1)\nred = RGB24(1, 0, 0)\ngreen = RGB24(0, 1, 0)\nblue = RGB24(0, 0, 1)\nμ0 = 4pi*1e-7 #F/m\nϵ0 = 8.854e-12 #H/m\n\n\n#Input data\n#-------------------------------------------------------------------------------\nfmax = 10e9\nfstep = 50e6\nf = collect(0:fstep:fmax)\nℓ = 50e-3 #Meters\nZL = Float64[1e6, 377, 60.0]\n_colors = [blue, red, green]\n\n\n#==Equations\n===============================================================================#\nΓ(Z; Zref::Real=50.0) = (Z - Zref) ./ (Z + Zref)\n#ZC: Characteristic impedance\n#ZL: Load impendance (termination)\nfunction Zline(ℓ::Real, f::Vector, ZL::Number; ZC::Number=50.0, α::Real=0, μ::Real=μ0, ϵ::Real=ϵ0)\n\tj = im\n\tβ = f*(2pi*sqrt(μ*ϵ))\n\tγ = α+j*β\n\ttanh_γℓ = tanh(γ*ℓ)\n\treturn ZC*(ZL+ZC*tanh_γℓ)./(ZC+ZL*tanh_γℓ)\nend\nfunction Γline(ℓ::Real, f::Vector, ZL::Number; ZC::Number=50.0, Zref::Number=50.0, α::Real=0, μ::Real=μ0, ϵ::Real=ϵ0)\n\treturn Γ(Zline(ℓ, f, ZL; ZC=ZC, α=α, μ=μ, ϵ=ϵ), Zref=Zref)\nend\n\n#Calculations\n#-------------------------------------------------------------------------------\nΓload = []\nfor ZLi in ZL\n\t_Γ = Γline(ℓ, f, ZLi, ZC=40)\n\tpush!(Γload, _Γ)\nend\n\n\n#==Generate plot\n===============================================================================#\nmplot = InspectDR.Multiplot(title=\"Transmission Line Example\")\nmplot.ncolumns = 2\n\nplot_linf = InspectDR.Plot2D()\n\tplot_linf.axes = InspectDR.axes(:lin, :dB20)\n\tplot_linf.ext_full = InspectDR.PExtents2D(ymax=5)\n#\tplot_linf.layout.legend.enabled=true\nplot_logf = InspectDR.Plot2D()\n\tplot_logf.axes = InspectDR.axes(:log10, :dB20)\n\tplot_logf.ext_full = InspectDR.PExtents2D(xmin=10e6,ymax=5)\n\tplot_logf.layout.grid = grid(vmajor=true, vminor=true, hmajor=true)\nplot_ysmith = InspectDR.Plot2D()\n\tplot_ysmith.axes = InspectDR.axes(:smith, :Y)\n\tplot_ysmith.ext_full = InspectDR.PExtents2D(xmin=-1.2,xmax=1.2,ymin=-1.2,ymax=1.2)\n\tplot_ysmith.layout.legend.enabled=true\nplot_smith = InspectDR.Plot2D()\n\tplot_smith.axes = InspectDR.axes(:smith, :Z, ref=50)\n\tplot_smith.ext_full = InspectDR.PExtents2D(xmin=-1.2,xmax=1.2,ymin=-1.2,ymax=1.2)\n\tplot_smith.layout.legend.enabled=true\n\nfor plot in [plot_linf, plot_logf]\n\ta = plot.annotation\n\ta.title = \"Reflection Coefficient (Γ)\"\n\ta.xlabel = \"Frequency (Hz)\"\n\ta.ylabel = \"Magnitude (dB)\"\nend\n\na = plot_ysmith.annotation\n\ta.title = \"Y-Smith Chart\"\n\ta.xlabel = \"Real(Γ)\"\n\ta.ylabel = \"Imaginary(Γ)\"\n\na = plot_smith.annotation\n\ta.title = \"Z-Smith Chart\"\n\ta.xlabel = \"Real(Γ)\"\n\ta.ylabel = \"Imaginary(Γ)\"\n\n#Select which plots to actually display:\nplotlist = [plot_linf, plot_logf, plot_ysmith, plot_smith]\n#plotlist = [plot_smith]\n\nfor plot in plotlist\n\tfor i in 1:length(Γload)\n\t\twfrm = add(plot, f, Γload[i], id=\"ZL=$(ZL[i])\")\n\t\twfrm.line = line(color=_colors[i], width=2)\n\tend\n\n\tadd(mplot, plot)\nend\n\ngplot = display(InspectDR.GtkDisplay(), mplot)\n\n\n#==Save multi-plot to file\n===============================================================================#\n\nmaximize_square = true\nif maximize_square\n\t#Target plot size to get square Smith plots without gaps:\n\tlyt = plot_smith.layout\n\t\tlyt.wdata = 500\n\t\tlyt.hdata = 500\n\tbb = InspectDR.plotbounds(lyt, plot_smith.axes) #Required\n\t\tmplot.wplot = width(bb)\n\t\tmplot.hplot = height(bb)\nend\n\nInspectDR.write_png(\"export_multiplot.png\", mplot)\nInspectDR.write_svg(\"export_multiplot.svg\", mplot)\nInspectDR.write_eps(\"export_multiplot.eps\", mplot)\nInspectDR.write_pdf(\"export_multiplot.pdf\", mplot)\n\n:DONE\n", "meta": {"hexsha": "04b23334b9eca448cf894968ee5301b28b6c6053", "size": 3791, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "sample/demo2.jl", "max_stars_repo_name": "JuliaPackageMirrors/InspectDR.jl", "max_stars_repo_head_hexsha": "a9e6aa05c053c3eb5a65d8a32199934560afb80d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sample/demo2.jl", "max_issues_repo_name": "JuliaPackageMirrors/InspectDR.jl", "max_issues_repo_head_hexsha": "a9e6aa05c053c3eb5a65d8a32199934560afb80d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sample/demo2.jl", "max_forks_repo_name": "JuliaPackageMirrors/InspectDR.jl", "max_forks_repo_head_hexsha": "a9e6aa05c053c3eb5a65d8a32199934560afb80d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7196969697, "max_line_length": 117, "alphanum_fraction": 0.5842785545, "num_tokens": 1249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7732183678850396}}
{"text": "\"\"\"\n    eom_mediated_link(u, p, t) -> SVector{9}\n\nEquations of motion for a three-subsystem dynamical system where `X` and `Y` are\ndriven by `Z`. At the default value of the coupling constant `c = 0`, the\nresponses `X` and `Y` are already synchronized to the driver `Z`.\nThe frequencies `ωx`, `ωy` and ``ωz` have near unit ratios by default.\n\n# References\nKrakovská, Anna, et al. \"Comparison of six methods for the detection of causality in a bivariate time series.\" Physical Review E 97.4 (2018): 042207\n\"\"\"\nfunction eom_mediated_link(u, p, t)\n    ωx, ωy, ωz, k, l, m, c = (p...,)\n    x₁, x₂, x₃, y₁, y₂, y₃, z₁, z₂, z₃ = (u...,)\n\n    dx₁ = -ωx*x₂ - x₃ + c*(z₁ - x₁)\n\tdx₂ = ωx*x₁ + k*x₂\n\tdx₃ = l + x₃*(x₁ - m)\n\n\tdy₁ = -ωy*y₂ - y₃ + c*(z₁ - y₁)\n\tdy₂ = ωy*y₁ + k*y₂\n\tdy₃ = l + y₃*(y₁ - m)\n\n\tdz₁ = -ωz*z₂ - z₃\n\tdz₂ = ωz*z₁ + k*z₂\n\tdz₃ = l + z₃*(z₁ - m)\n\n    SVector{9}(dx₁, dx₂, dx₃, dy₁, dy₂, dy₃, dz₁, dz₂, dz₃)\nend\n\nfunction mediated_link(u₀, ωx, ωy, ωz, k, l, m, c)\n    p = [ωx, ωy, ωz, k, l, m, c]\n    ContinuousDynamicalSystem(eom_mediated_link, u₀, p)\nend\n\n\"\"\"\n    mediated_link(;u₀ = rand(9), ωx = 1, ωy = 1.015, ωz = 0.985,\n        k = 0.15, l = 0.2, m = 10.0, c = 0.06) -> ContinuousDynamicalSystem\n\nEquations of motion for a three-subsystem dynamical system where `X` and `Y` are\ndriven by `Z`. At the default value of the coupling constant `c = 0`, the\nresponses `X` and `Y` are already synchronized to the driver `Z`.\n\nThe dynamics is generated by the vector field:\n\n```math\n\\\\begin{aligned}\ndx_1 &= -\\\\omega_x x_2 - x_3 + c*(z_1 - x_1) \\\\\ndx_2 &= \\\\omega_x x_1 + k*x_2 \\\\\ndx_3 &= l + x_3(x_1 - m) \\\\\ndy_1 &= -\\\\omega_y y_2 - y_3 + c*(z_1 - y_1) \\\\\ndy_2 &= \\\\omega_y y_1 + k*y_2 \\\\\ndy_3 &= l + y_3(y_1 - m) \\\\\ndz_1 &= -\\\\omega_z z_2 - z_3 \\\\\ndz_2 &= \\\\omega_z z_1 + k*z_2 \\\\\ndz_3 &= l + z_3(z_1 - m) \\\\\n\\end{aligned}\n```\n\n# References\nKrakovská, Anna, et al. \"Comparison of six methods for the detection of causality in a bivariate time series.\" Physical Review E 97.4 (2018): 042207\n\"\"\"\nmediated_link(;u₀ = rand(9), ωx = 1, ωy = 1.015, ωz = 0.985,\n            k = 0.15, l = 0.2, m = 10.0, c = 0.06) =\n    mediated_link(u₀, ωx, ωy, ωz, k, l, m, c)\n", "meta": {"hexsha": "02f6914c6658d8d44b1be42bc50e44f309ffe194", "size": 2159, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/systems/continuous_systems/mediated_link.jl", "max_stars_repo_name": "tormolle/CausalityTools.jl", "max_stars_repo_head_hexsha": "b8c1014349358d8cdb5eddc1bcac9303f475d90b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/systems/continuous_systems/mediated_link.jl", "max_issues_repo_name": "tormolle/CausalityTools.jl", "max_issues_repo_head_hexsha": "b8c1014349358d8cdb5eddc1bcac9303f475d90b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/systems/continuous_systems/mediated_link.jl", "max_forks_repo_name": "tormolle/CausalityTools.jl", "max_forks_repo_head_hexsha": "b8c1014349358d8cdb5eddc1bcac9303f475d90b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7121212121, "max_line_length": 148, "alphanum_fraction": 0.604446503, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646393, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7732183660597406}}
{"text": "\"\"\"\nLog of the InverseGamma PDF. Equivalent to using Distributions; logpdf(InverseGamma(α, β), x)\nhttps://en.wikipedia.org/wiki/Inverse-gamma_distribution\n\"\"\"\nfunction log_inverse_gamma(x::Real, α::Real=1., β::Real=1.; d::Integer=0)\n    @assert 0 <= d <= 2\n    if d == 0\n        x > 0 ? val = -(β / x) - (1 + α) * log(x) + α * log(β) - loggamma(α) : val = -Inf\n    elseif d == 1\n        x > 0 ? val = (β / x - (1 + α)) / x : val = 0\n    else\n        x > 0 ? val = (-2 * β / x + (1 + α)) / (x * x) : val = 0\n    end\n    return val\nend\n\n\nfunction gamma_mode_std_2_alpha_theta(m::Real, s::Real)\n    θ = (sqrt(m ^ 2 + 4 * s ^ 2) - m) / 2\n    α = m / θ + 1\n    return [α, θ]\nend\n\n\"\"\"\nLog of the Gamma PDF. Equivalent to using Distributions; logpdf(Gamma(α, β), x)\nhttps://en.wikipedia.org/wiki/Gamma_distribution\n\"\"\"\nfunction log_gamma(x::Real, parameters::Vector{<:Real}; d::Integer=0, passed_mode_std::Bool=false)\n    @assert 0 <= d <= 2\n    @assert length(parameters) == 2\n    assert_positive(parameters)\n    if passed_mode_std\n        parameters = gamma_mode_std_2_alpha_theta(parameters[1], parameters[2])\n    end\n    α = parameters[1]\n    θ = parameters[2]\n    if d == 0\n        x > 0 ? val = -(x / θ) + (α - 1) * log(x) - α * log(θ) - loggamma(α) : val = -Inf\n    elseif d == 1\n        x > 0 ? val = (α - 1) / x - 1 / θ : val = 0\n    else\n        x > 0 ? val = -(α - 1) / (x * x) : val = 0\n    end\n    return val\nend\n\ngauss_cdf(x::Real) = (1 + erf(x))/2\n\n\"log of the Gaussian PDF. Equivalent to using Distributions; logpdf(Gaussian(μ, σ), x)\"\nfunction log_gaussian(x::Real, parameters::Vector{<:Real}; d::Integer=0, min::Real=-Inf, max::Real=Inf)\n    @assert 0 <= d <= 2\n    @assert length(parameters) == 2\n    μ = parameters[1]\n    σ = parameters[2]\n    assert_positive(σ)\n    @assert min < max\n    normalization = 1 - gauss_cdf(min - μ) - gauss_cdf(μ - max)\n    if d == 0\n        (min < x < max) ? val = -((x - μ)^2/(2 * σ * σ)) - log(sqrt(2 * π) * σ) - log(normalization) : val = -Inf\n    elseif d == 1\n        (min < x < max) ? val = -(x - μ)/(σ * σ) : val = 0\n    else\n        (min < x < max) ? val = -1 / (σ * σ) : val = 0\n    end\n    return val\nend\n\n\"Log of the Uniform PDF.\"\nfunction log_uniform(x::Real, min_max::Vector{<:Real}=[0,1]; d::Integer=0)\n    @assert 0 <= d <= 2\n    @assert length(min_max) == 2\n    min, max = min_max\n    @assert min < max\n    if d == 0\n        min <= x <= max ? -log(max - min) : -Inf\n    else\n        return 0\n    end\nend\n\n\"\"\"\nLog of the log-Uniform PDF.\nFlattens out in log space starting at shift\nAlso known as a (modified in shifted case) Jeffrey's prior\n\"\"\"\nfunction log_loguniform(x::Real, min_max::Vector{<:Real}; d::Integer=0, shift::Real=0)\n    @assert 0 <= d <= 2\n    @assert length(min_max) == 2\n    min, max = min_max\n    @assert 0 < min + shift < max + shift\n    xpshift = x + shift\n    if d == 0\n        min <= x <= max ? val = -log(xpshift) - log(log((max + shift)/(min + shift))) : val = -Inf\n    elseif d == 1\n        min <= x <= max ? val = -1 / xpshift : val = 0\n    elseif d == 2\n        min <= x <= max ? val = 1 / (xpshift * xpshift) : val = 0\n    end\n    return val\nend\n\n\n\"\"\"\nLog of the Rayleigh PDF.\n\"\"\"\nfunction log_Rayleigh(x::Real, σ::Real; d::Integer=0)\n    @assert 0 <= d <= 2\n    if d == 0\n        0 <= x <= 1 ? val = -(x * x / (2 * σ * σ)) + log(x / σ / σ) -  log(1 - exp(-1 / (2 * σ * σ))) : val = -Inf\n    elseif d == 1\n        0 <= x <= 1 ? val = 1 / x - x / σ / σ : val = 0\n    elseif d == 2\n        0 <= x <= 1 ? val = -1 / x / x - 1 / σ / σ : val = 0\n    end\n    return val\nend\n\n\n\"\"\"\nLog of the 2D circle PDF\n\"\"\"\nfunction log_circle(x::Vector{<:Real}, min_max_r::Vector{<:Real}; d::Vector{<:Integer}=[0,0])\n    @assert minimum(d) == 0\n    @assert maximum(d) <= 2\n    @assert sum(d) <= 2\n\n    @assert length(x) == length(min_max_r) == length(d) == 2\n    min_r, max_r = min_max_r\n\n    # @assert min_r < sqrt(dot(x, x)) < max_r\n    # @assert min_θ < atan(x[1], x[2]) < max_θ\n    if all(d .== 0)\n        min_r < sqrt(dot(x, x)) < max_r ? val = -log(2 * π * (max_r ^ 2 - min_r ^ 2)) : val = -Inf\n    else\n        return 0\n    end\n    return val\nend\n\n\n\"\"\"\nLog of the 2D unit cone PDF\n\"\"\"\nfunction log_cone(x::Vector{<:Real}; d::Vector{<:Integer}=[0,0])\n    @assert minimum(d) >= 0\n    @assert maximum(d) <= 2\n    @assert sum(d) <= 2\n\n    @assert length(x) == length(d) == 2\n\n    r_sq = dot(x, x)  # x^2 + y^2\n    r = sqrt(r_sq)\n    if d == [0,0]\n        0 <= r < 1 ? val = log(3 / π * (1 - r)) : val = -Inf\n    elseif d == [0,1]\n        0 <= r < 1 ? val = x[2] / (r_sq - r) : val = 0\n    elseif d == [0,2]\n        0 <= r < 1 ? val = (-x[2] ^ 2 * r + x[1] ^ 2 * (r - 1)) /\n            (r ^ 3 * (1 - 2 * r + r_sq)) : val = 0\n    elseif d == [1,0]\n        0 <= r < 1 ? val = x[1] / (r_sq - r) : val = 0\n    elseif d == [1,1]\n        0 <= r < 1 ? val = (x[1] * x[2] * (1 - 2 * r)) /\n            (r ^ 3 * (1 - 2 * r + r_sq)) : val = 0\n    elseif d == [2,0]\n        0 <= r < 1 ? val = (-x[1] ^ 2 * r + x[2] ^ 2 * (r - 1)) /\n            (r ^ 3 * (1 - 2 * r + r_sq)) : val = 0\n    end\n    return val\nend\n\n\n\"\"\"\nLog of the 2D unit quadratic cone PDF\n\"\"\"\nfunction log_quad_cone(x::Vector{<:Real}; d::Vector{<:Integer}=[0,0])\n    @assert minimum(d) >= 0\n    @assert maximum(d) <= 2\n    @assert sum(d) <= 2\n\n    @assert length(x) == length(d) == 2\n\n    r_sq = dot(x, x)  # x^2 + y^2\n    r = sqrt(r_sq)\n    if d == [0,0]\n        0 <= r < 1 ? val = log(6 / π * (1 - 2 * r + r_sq)) : val = -Inf\n    elseif d == [0,1]\n        0 <= r < 1 ? val = 2 * x[2] / (r_sq - r) : val = 0\n    elseif d == [0,2]\n        0 <= r < 1 ? val = 2 * (-x[2] ^ 2 * r + x[1] ^ 2 * (r - 1)) /\n            (r ^ 3 * (1 - 2 * r + r_sq)) : val = 0\n    elseif d == [1,0]\n        0 <= r < 1 ? val = 2 * x[1] / (r_sq - r) : val = 0\n    elseif d == [1,1]\n        0 <= r < 1 ? val = (2 * x[1] * x[2] * (1 - 2 * r)) /\n            (r ^ 3 * (1 - 2 * r + r_sq)) : val = 0\n    elseif d == [2,0]\n        0 <= r < 1 ? val = 2 * (-x[1] ^ 2 * r + x[2] ^ 2 * (r - 1)) /\n            (r ^ 3 * (1 - 2 * r + r_sq)) : val = 0\n    end\n    return val\nend\n\n\n\"\"\"\nLog of the 2D unit cubic cone PDF\n\"\"\"\nfunction log_cubic_cone(x::Vector{<:Real}; d::Vector{<:Integer}=[0,0])\n    @assert minimum(d) >= 0\n    @assert maximum(d) <= 2\n    @assert sum(d) <= 2\n\n    @assert length(x) == length(d) == 2\n\n    r_sq = dot(x, x)  # x^2 + y^2\n    r = sqrt(r_sq)\n    if d == [0,0]\n        0 <= r < 1 ? val = log(10 / π * (1 - r)^3) : val = -Inf\n    elseif d == [0,1]\n        0 <= r < 1 ? val = 3 * x[2] / (r_sq - r) : val = 0\n    elseif d == [0,2]\n        0 <= r < 1 ? val = 3 * (-x[2] ^ 2 * r + x[1] ^ 2 * (r - 1)) /\n            (r ^ 3 * (1 - 2 * r + r_sq)) : val = 0\n    elseif d == [1,0]\n        0 <= r < 1 ? val = 3 * x[1] / (r_sq - r) : val = 0\n    elseif d == [1,1]\n        0 <= r < 1 ? val = (3 * x[1] * x[2] * (1 - 2 * r)) /\n            (r ^ 3 * (1 - 2 * r + r_sq)) : val = 0\n    elseif d == [2,0]\n        0 <= r < 1 ? val = 3 * (-x[1] ^ 2 * r + x[2] ^ 2 * (r - 1)) /\n            (r ^ 3 * (1 - 2 * r + r_sq)) : val = 0\n    end\n    return val\nend\n\n\n\"\"\"\nLog of the 2D rotated Rayleigh PDF that is cutoff at r=1\nONLY ROUGHLY NORMALIZED according to σ = 1/5\n\"\"\"\nfunction log_rot_Rayleigh(x::Vector{<:Real}; d::Vector{<:Integer}=[0,0], σ=1/5)\n    @assert minimum(d) >= 0\n    @assert maximum(d) <= 2\n    @assert sum(d) <= 2\n\n    @assert length(x) == length(d) == 2\n    r_sq = dot(x, x)  # x^2 + y^2\n    r = sqrt(r_sq)\n    σ_sq = σ ^ 2\n    log_norm = -2 * log(σ) - 0.454215\n    if d == [0,0]\n        0 <= r < 1 ? val = -r_sq / (2 * σ_sq) + log(r) + log_norm : val = -Inf\n    elseif d == [0,1]\n        0 <= r < 1 ? val = -x[2] * (r_sq - σ_sq) / (r_sq * σ_sq) : val = 0\n    elseif d == [0,2]\n        0 <= r < 1 ? val = -(x[1] ^ 4 + x[1] ^ 2 * (2 * x[2] ^ 2 - σ_sq) + x[2] ^ 2 * (x[2] ^ 2 + σ_sq)) / (r_sq ^ 2 * σ_sq) : val = 0\n    elseif d == [1,0]\n        0 <= r < 1 ? val = -x[1] * (r_sq - σ_sq) / (r_sq * σ_sq) : val = 0\n    elseif d == [1,1]\n        0 <= r < 1 ? val = -2 * x[1] * x[2] / r_sq ^ 2 : val = 0\n    elseif d == [2,0]\n        0 <= r < 1 ? val = -(x[2] ^ 4 + x[2] ^ 2 * (2 * x[1] ^ 2 - σ_sq) + x[1] ^ 2 * (x[1] ^ 2 + σ_sq)) / (r_sq ^ 2 * σ_sq) : val = 0\n    end\n    return val\nend\n\n\n\"\"\"\nLog of the bivariate normal PDF\nNOTE THAT THAT WHEN USING lows!=[-∞,...], THIS IS NOT PROPERLY NORMALIZED\n\"\"\"\nfunction log_bvnormal(x::Vector{T}, Σ::Cholesky{T,Matrix{T}}; μ::Vector{T}=zeros(T, length(x)), d::Vector{<:Integer}=[0,0], lows::Vector{T}=zeros(T, length(x)) .- Inf) where {T<:Real}\n    @assert minimum(d) >= 0\n    @assert maximum(d) <= 2\n    @assert sum(d) <= 2\n\n    @assert length(x) == length(d) == length(μ) == 2\n    y = x - μ\n\n    if sum(d) == 0\n        all(x .>= lows) ? val = -nlogL(Σ, y) : val = -Inf\n    elseif sum(d) == 1\n        y1 = Float64.(d)\n        all(x .>= lows) ? val = -dnlogLdθ(y1, Σ \\ y) : val = 0\n    elseif d == [0,2]\n        y1 = y2 = [0, 1.]\n        all(x .>= lows) ? val = -d2nlogLdθ(y2, [0,0.], Σ \\ y, Σ \\ y1) : val = 0\n    elseif d == [1,1]\n        y1 = [1, 0.]\n        y2 = [0, 1.]\n        all(x .>= lows) ? val = -d2nlogLdθ(y2, [0,0.], Σ \\ y, Σ \\ y1) : val = 0\n    elseif d == [2,0]\n        y1 = y2 = [1, 0.]\n        all(x .>= lows) ? val = -d2nlogLdθ(y2, [0,0.], Σ \\ y, Σ \\ y1) : val = 0\n    end\n    return val\nend\nfunction bvnormal_covariance(σ11::Real, σ22::Real, ρ::Real)\n    assert_positive(σ11, σ22)\n    @assert 0 <= ρ <= 1\n    v12 = σ11*σ22*ρ\n    return ridge_chol([σ11^2 v12;v12 σ22^2])\nend\n", "meta": {"hexsha": "0ea3d065ccf369654ff19bab21cb9ab9e5619895", "size": 9427, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/prior_functions.jl", "max_stars_repo_name": "eford/GPLinearODEMaker.jl", "max_stars_repo_head_hexsha": "85209a72e5a679b974abc4cdfe3cbea27194b242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/prior_functions.jl", "max_issues_repo_name": "eford/GPLinearODEMaker.jl", "max_issues_repo_head_hexsha": "85209a72e5a679b974abc4cdfe3cbea27194b242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-05-09T18:12:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T18:12:58.000Z", "max_forks_repo_path": "src/prior_functions.jl", "max_forks_repo_name": "eford/GPLinearODEMaker.jl", "max_forks_repo_head_hexsha": "85209a72e5a679b974abc4cdfe3cbea27194b242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0098684211, "max_line_length": 183, "alphanum_fraction": 0.4674870054, "num_tokens": 3915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620585273153, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7732152103519846}}
{"text": "import Distributions\nimport SpecialFunctions\n\n\"\"\"    gaussianMechConstant(ϵ::Real,δ::Real)\nCompute the proportionality constant κ(ϵ,δ) for the Gaussian mechanism.\n\"\"\"\nfunction gaussianMechConstant(ϵ::Real, δ::Real)\n    K = sqrt(2) * SpecialFunctions.erfinv(1-2δ)\n    return (K+sqrt(K^2+2ϵ))/(2ϵ)\nend\n\n\"\"\"    (k₁, k₂) = gaussianMechConstant2(ϵ::Real,δ::Real)\nCompute the proportionality constant κ(ϵ,δ) for the Gaussian mechanism,\nboth with the formula using the inverse Q-function (k₁), and according to the\napproximation of Theorem A.1 in Dwork and Roth's book (k₂, higher value).\n\"\"\"\nfunction gaussianMechConstant2(ϵ::Real, δ::Real)\n    K = sqrt(2) * SpecialFunctions.erfinv(1-2δ)\n    return ((K+sqrt(K^2+2ϵ))/(2ϵ), sqrt(2log(1.25/δ))/ϵ)\nend\n\n\"\"\"    mean_dp(x::Vector,epsilon::Float64,delta::Float64=0.0)\nCompute the average of a set of numbers contained in the vector x,\nin an (ϵ,δ)-differentially private way. It is assumed that each entry\nx_i of the vector is in [0,1], and the adjacency relation looks at\narbitrary variations in one entry x_i, within this interval.\n\"\"\"\nfunction mean_dp(x::Vector, ϵ::Real, δ::Real=0.0)\n    if δ == 0.0\n        d = Distributions.Laplace(0, 1/(ϵ*length(x)))\n    else\n        d = Distributions.Normal(0, gaussianMechConstant(ϵ,δ)/length(x))\n    end\n    return Distributions.mean(x) + Distributions.rand(d)\nend\n\n\"\"\"    laplaceMech(x,f,l1sens::Real,ϵ::Real)\nComputes a randomized version to f(x) according to the\nLaplace mechanism, for ϵ-differential privacy. l1sens is\nthe l1-sensitivity of f, which must be computed and provided by the user.\nf must take values in R^k, for some k, i.e., return an array of k real values.\n\"\"\"\nfunction laplaceMech(x, f, l1sens::Real, ϵ::Real)\n    t = f(x)\n    d = Distributions.Laplace(0, l1sens/ϵ)\n    return (t .+ Distributions.rand(d, length(t)))\nend\n\n\"\"\"    gaussianMech(x,f,l2sens::Real,ϵ::Real,δ::Real)\nComputes a randomized version to f(x) according to the\nGaussian mechanism, for (ϵ,δ)-differential privacy. l2sens is\nthe l2-sensitivity of f, which must be computed by the user.\nf must take values in R^k, from some k, i.e., return an array\nof k real values.\n\"\"\"\nfunction gaussianMech(x, f, l2sens::Real, ϵ::Real, δ::Real)\n    t = f(x)\n    d = Distributions.Normal(0, gaussianMechConstant(ϵ, δ) * l2sens)\n    return (t .+ Distributions.rand(d, length(t)))\nend\n\n\"\"\"    truncatedLaplaceMech(x,f,l1sens::Real,ϵ::Real,δ::Real)\nComputes a randomized version to f(x) according to the\ntruncated Laplace mechanism, for (ϵ,δ)-differential privacy.\nThis scheme adds bounded noise.\nl1sens is the l1-sensitivity of f, which must be computed and provided by the\nuser. f must take values in R^k, for some k, i.e., return an array of k real\nvalues.\n\nReturns: (r, a) where r is a noisy version of f(x), and a defines the\nsupport of the noise distribution (in the interval [f(x)-a, f(x)+a])\n\"\"\"\nfunction truncatedLaplaceMech(x, f, l1sens::Real, ϵ::Real, δ::Real)\n    t = f(x)\n    k = length(t)\n    λ = l1sens/ϵ\n    a = λ * log( 1 + exp(ϵ) * (k*(1-exp(-ϵ/k)))/(2*δ) )\n    # alternative, more conservative but indpt of k\n    # a = λ * log(1 + ϵ * exp(ϵ) / (2*δ))\n    d1 = Distributions.Laplace(0, λ)\n    d = Distributions.truncated(d1, -a, a)\n    return (t .+ Distributions.rand(d, length(t)), a)\nend\n", "meta": {"hexsha": "343e6cab6491bd8906da8f5481fb682a3278bc8b", "size": 3259, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "cipherlab-poly/PrivateDynamicData.jl", "max_stars_repo_head_hexsha": "1b9be6b7b244814483c0105b5221df2c41faee5a", "max_stars_repo_licenses": ["AFL-1.1"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-20T08:59:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T08:59:23.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "cipherlab-poly/PrivateDynamicData.jl", "max_issues_repo_head_hexsha": "1b9be6b7b244814483c0105b5221df2c41faee5a", "max_issues_repo_licenses": ["AFL-1.1"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "cipherlab-poly/PrivateDynamicData.jl", "max_forks_repo_head_hexsha": "1b9be6b7b244814483c0105b5221df2c41faee5a", "max_forks_repo_licenses": ["AFL-1.1"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7976190476, "max_line_length": 78, "alphanum_fraction": 0.6910095121, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620539235895, "lm_q2_score": 0.8056321913146128, "lm_q1q2_score": 0.773215206643075}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.0\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 2d6d0588-f4e4-4cad-8353-9c0ba020fec6\nbegin\n\tusing FileIO\n\tusing ImageShow\n\tusing ImageIO\n\tusing PlutoUI\n\tusing Cbc\n\tusing DataFrames\n\tusing Distances\n\tusing JuMP\n\tusing LinearAlgebra\nend\n\n# ╔═╡ d44f3f70-705b-43a2-85c0-a441e08fbbe6\nload(\"Pydata_Jeddah_22_new-06.png\")\n\n# ╔═╡ a12d1135-ce89-414c-866e-14b4415e1990\nmd\"\"\"\n# Geographical Clustering of Saudi Cities With Additional Constraint\n**Originally Contributed by**: Matthew Helm ([with help from Mathieu Tanneau on Julia Discourse](https://discourse.julialang.org/t/which-jump-jl-solver-for-this-problem/43350/17?u=mthelm85))\n**Customized by**: Hassan Alsawadi\n\"\"\"\n\n# ╔═╡ d35c109a-e5b6-4c01-a9c2-333b883783f2\nmd\"\"\"\n#### Intializing packages\n\n_When running this notebook for the first time, this could take up to 5 minutes. Hang in there!_\n\"\"\"\n\n# ╔═╡ 2877f488-1ab3-46da-8a49-7db65c3d8a45\nmd\"\"\"\n## Objective\nThe goal of this exercise is to cluster 𝑛 cities into 𝑘 groups, minimizing the total pairwise distance between cities and ensuring that the variance in the total populations of each group is relatively small.\n\nFor this example, we'll use the 20 most populous cities in Saudi Arabia.\n\"\"\"\n\n# ╔═╡ cf6d3f77-781d-4cd0-ad45-9c5c58380354\ncities = DataFrame(\n    city=[\"Riyadh\", \"Jeddah\", \"Mecca\", \"Medina\", \"Dammam\", \"Abha\", \"Ha'il\", \"Hofuf\", \"Al-Mubarraz\", \"Sakakah\", \"Taif\", \"Khamis Mushait\", \"Jubail\", \"Buraydah\", \"Tabuk\", \"Najran\", \"Qatif\", \"Khobar\", \"Al Bahah\", \"Hafr Al-Batin\"],\n    population=[7676654, 4697000, 2042000, 1488782, 1252523, 1093705, 936465, 858395, 837000, 779480, 695000, 667000, 684531, 669000, 667000, 505652, 474573, 455541, 366000, 359000],\n    lat=[24.633333, 21.543333, 21.4225, 24.466667, 26.433333, 18.216944, 27.516667, 25.383333, 25.383333, 29.969722, 21.275094, 18.3, 27, 26.333333, 28.397222, 17.491667, 26.556, 26.283333, 20.0125, 28.434167],\n    lon=[46.716667, 39.172778, 39.823333, 39.6, 50.1, 42.505278, 41.683333, 49.583333, 49.6, 40.2, 40.406156, 42.733333, 49.666667, 43.966667, 36.578889, 44.132222, 49.996, 50.2, 41.465278, 45.963611])\n\n# ╔═╡ 11c8323a-9cd5-4580-93d9-ebcd085b4551\nmd\"\"\"\n## Model Specifics\nWe will cluster these 20 cities into 3 different groups and we will assume that the ideal or target population  𝑃  for a group is simply the total population of the 20 cities divided by 3:\n\"\"\"\n\n# ╔═╡ 0a9212cd-4c79-4752-930b-45dce6a1f3e8\nbegin\n\tn = size(cities,1)\n\tk = 3\n\tP = sum(cities.population) / k\nend\n\n# ╔═╡ 7f7439d3-3d3b-4098-8be5-ca9aa59373ce\nmd\"\"\"### Obtaining the distances between each city\nLet's leverage the *Distances.jl* package to compute the pairwise Haversine distance between each of the cities in our data\nset and store the result in a variable we'll call `dm`:\n\"\"\"\n\n# ╔═╡ 3e708ffa-05d9-4cf7-ba4c-11ca5a3e43e7\ndm = Distances.pairwise(Haversine(6372.8), Matrix(cities[:, [3,4]])', dims=2)\n\n# ╔═╡ 54082ac4-c31d-4d27-9cc3-5248018c6838\nmd\"\"\"Our distance matrix is symmetric so we'll convert it to a `LowerTriangular` matrix so that we can better interpret the\nobjective value of our model (if we don't do this the total distance will be doubled):\"\"\"\n\n# ╔═╡ 6bc42cc7-e3d4-4470-bece-6af950280372\ndm2 = LowerTriangular(dm)\n\n# ╔═╡ a5f3abe7-a843-4ea5-8e77-dfd075b243a5\nmd\"\"\"\n## Build the model\nNow that we have the basics taken  care of, we can set up our model, create decision variables, add constraints, and then\nsolve.\n\nFirst, we'll set up a model that leverages the [Cbc](https://github.com/coin-or/Cbc) solver. Next, we'll set up a binary\nvariable $x_{i,k}$ that takes the value $1$ if city $i$ is in group $k$ and $0$ otherwise. Each city must be in a group, so\nwe'll add the constraint $\\sum_kx_{i,k} = 1$ for every $i$.\n\"\"\"\n\n# ╔═╡ ee41a6b3-fb13-4269-ab22-ad2a85bf26e5\nbegin\n\tmodel = Model(Cbc.Optimizer)\n\t\n\t@variable(model, x[1:n, 1:k], Bin)\n\t\n\tfor i in 1:n\n\t    @constraint(model, sum(x[i,:]) == 1)\n\tend\nend\n\n# ╔═╡ dd262e8b-4697-4aa7-9bc7-a32ac25c96dc\nmd\"\"\"\nThe total population of a group $k$ is $Q_k = \\sum_ix_{i,k}q_i$ where $q_i$ is simply the $i$th value from the `population`\ncolumn in our `cities` DataFrame. Let's add constraints so that $\\alpha \\leq (Q_k - P) \\leq \\beta$. We'll set $\\alpha$\nequal to -2,500,000 and $\\beta$ equal to 2,500,000. By adjusting these thresholds you'll find that there is a tradeoff\nbetween having relatively even populations between groups and having geographically close cities within each group. In\nother words, the larger the absolute values of $\\alpha$ and $\\beta$, the closer together the cities in a group will be but\nthe variance between the group populations will be higher.\n\"\"\"\n\n# ╔═╡ d5fc7ca7-33cd-4f8a-aecf-8897bcd40e15\nbegin\n\tα = -2_500_000\n\tβ = 2_500_000\n\tfor i in 1:k\n\t    @constraint(model, (x' * cities.population)[i] - P <= β)\n\t    @constraint(model, (x' * cities.population)[i] - P >= α)\n\tend\nend\n\n# ╔═╡ 4ab84877-f5d8-4c1b-b0d2-346f0048bb20\nmd\"\"\"\nNow we need to add one last binary variable $z_{i,j}$ to our model that we'll use to compute the total distance between the \ncities in our groups, defined as  $\\sum_{i,j}d_{i,j}z_{i,j}$. Variable $z_{i,j}$ will equal $1$ if cities $i$ and $j$ are \nin the same group, and $0$ if they are not in the same group.\n\nTo ensure that $z_{i,j} = 1$ if and only if cities $i$ and $j$ are in the same group, we add the constraints $z_{i,j} \\geq \nx_{i,k} + x_{j,k} - 1$ for every pair $i,j$ and every $k$:\n\"\"\"\n\n# ╔═╡ 1054b6a4-1c28-46b6-88a4-6f7cae84edee\nbegin\n\t@variable(model, z[1:n,1:n], Bin)\n\t\n\tfor k in 1:k, i in 1:n, j in 1:n\n\t    @constraint(model, z[i,j] >= x[i,k] + x[j,k] - 1)\n\tend\nend\n\n# ╔═╡ 07f58656-4826-4ce5-8c97-bf5570f0fc60\nmd\"\"\"\nWe can now add an objective to our model which will simply be to minimize the dot product of $z$ and our distance matrix,\n`dm`. We can then call `optimize!` and review the results.\n\"\"\"\n\n# ╔═╡ 17088a0b-a568-431c-8d01-13f957e2a4c0\nbegin\n\t@objective(model, Min, dot(z,dm));\n\t\n\toptimize!(model)\nend\n\n# ╔═╡ 4ded521e-c41f-4927-854b-86f8912269db\nmd\"\"\"## Reviewing the Results\nNow that we have results, we can add a column to our `cities` DataFrame for the group and then loop through our $x$\nvariable to assign each city to its group. Once we have that, we can look at the total population for each group and also\nplot the cities and their groups to verify visually that they are grouped by geographic proximity.\n\"\"\"\n\n# ╔═╡ dab4e559-9dc6-4a72-8d38-9a0487b6251a\nPlutoUI.with_terminal() do\n\tcities.group = zeros(n)\n\t\n\tfor i in 1:n, j in 1:k\n\t    if round(value.(x)[i,j]) == 1.0\n\t        cities.group[i] = j\n\t    end\n\tend\n\t\n\tfor group in groupby(cities, :group)\n\t    @show group\n\t    println(\"\")\n\t    @show sum(group.population)\n\t    println(\"\")\n\tend\nend\n\n# ╔═╡ aa340dc7-8833-4e40-b63e-c602096e40e3\nmd\"\"\"\nThe populations of each group are fairly even and we can see from the plot below that the groupings look good in terms of\ngeographic proximity:\n\"\"\"\n\n# ╔═╡ a2fad4bc-66fa-4466-ae29-b495590f035f\nload(\"output.png\")\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nCbc = \"9961bab8-2fa3-5c5a-9d89-47fab24efd76\"\nDataFrames = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nDistances = \"b4f34e82-e78d-54a5-968a-f98e89d6e8f7\"\nFileIO = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nImageIO = \"82e4d734-157c-48bb-816b-45c225c6df19\"\nImageShow = \"4e3cecfd-b093-5904-9786-8bbb286a6a31\"\nJuMP = \"4076af6c-e467-56ae-b986-b466b2749572\"\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\n\n[compat]\nCbc = \"~0.9.1\"\nDataFrames = \"~1.3.2\"\nDistances = \"~0.10.7\"\nFileIO = \"~1.13.0\"\nImageIO = \"~0.6.1\"\nImageShow = \"~0.3.3\"\nJuMP = \"~0.22.3\"\nPlutoUI = \"~0.7.34\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[ASL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6252039f98492252f9e47c312c8ffda0e3b9e78d\"\nuuid = \"ae81ac8f-d209-56e5-92de-9978fef736f9\"\nversion = \"0.1.3+0\"\n\n[[AbstractFFTs]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"6f1d9bc1c08f9f4a8fa92e3ea3cb50153a1b40d4\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"1.1.0\"\n\n[[AbstractPlutoDingetjes]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"8eaf9f1b4921132a4cff3f36a1d9ba923b14a481\"\nuuid = \"6e696c72-6542-2067-7265-42206c756150\"\nversion = \"1.1.4\"\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"af92965fb30777147966f58acb05da51c5616b5f\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.3\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[BenchmarkTools]]\ndeps = [\"JSON\", \"Logging\", \"Printf\", \"Profile\", \"Statistics\", \"UUIDs\"]\ngit-tree-sha1 = \"4c10eee4af024676200bc7752e536f858c6b8f93\"\nuuid = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\nversion = \"1.3.1\"\n\n[[BinaryProvider]]\ndeps = [\"Libdl\", \"Logging\", \"SHA\"]\ngit-tree-sha1 = \"ecdec412a9abc8db54c0efc5548c64dfce072058\"\nuuid = \"b99e7846-7c00-51b0-8f62-c81ae34c0232\"\nversion = \"0.5.10\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[CEnum]]\ngit-tree-sha1 = \"215a9aa4a1f23fbd05b92769fdd62559488d70e9\"\nuuid = \"fa961155-64e5-5f13-b03f-caf6b980ea82\"\nversion = \"0.4.1\"\n\n[[Calculus]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"f641eb0a4f00c343bbc32346e1217b86f3ce9dad\"\nuuid = \"49dc2e85-a5d0-5ad3-a950-438e2897f1b9\"\nversion = \"0.5.1\"\n\n[[Cbc]]\ndeps = [\"BinaryProvider\", \"CEnum\", \"Cbc_jll\", \"Libdl\", \"MathOptInterface\", \"SparseArrays\"]\ngit-tree-sha1 = \"6656166f484075dd146c9f452b1428116eaf76d4\"\nuuid = \"9961bab8-2fa3-5c5a-9d89-47fab24efd76\"\nversion = \"0.9.1\"\n\n[[Cbc_jll]]\ndeps = [\"ASL_jll\", \"Artifacts\", \"Cgl_jll\", \"Clp_jll\", \"CoinUtils_jll\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"OpenBLAS32_jll\", \"Osi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"a3c5986d7713bce4260d9826deead060a17c8e2d\"\nuuid = \"38041ee0-ae04-5750-a4d2-bb4d0d83d27d\"\nversion = \"200.1000.501+0\"\n\n[[Cgl_jll]]\ndeps = [\"Artifacts\", \"Clp_jll\", \"CoinUtils_jll\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Osi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"11eb7b7688925e9751b5d7a187aaa4291eae2664\"\nuuid = \"3830e938-1dd0-5f3e-8b8e-b3ee43226782\"\nversion = \"0.6000.300+0\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"7dd38532a1115a215de51775f9891f0f3e1bac6a\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.12.1\"\n\n[[ChangesOfVariables]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"bf98fa45a0a4cee295de98d4c1462be26345b9a1\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.2\"\n\n[[Clp_jll]]\ndeps = [\"Artifacts\", \"CoinUtils_jll\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"METIS_jll\", \"MUMPS_seq_jll\", \"OpenBLAS32_jll\", \"Osi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"b1031dcfbb44553194c9e650feb5ab65e372504f\"\nuuid = \"06985876-5285-5a41-9fcb-8948a742cc53\"\nversion = \"100.1700.601+0\"\n\n[[CodecBzip2]]\ndeps = [\"Bzip2_jll\", \"Libdl\", \"TranscodingStreams\"]\ngit-tree-sha1 = \"2e62a725210ce3c3c2e1a3080190e7ca491f18d7\"\nuuid = \"523fee87-0ab8-5b00-afb7-3ecf72e48cfd\"\nversion = \"0.7.2\"\n\n[[CodecZlib]]\ndeps = [\"TranscodingStreams\", \"Zlib_jll\"]\ngit-tree-sha1 = \"ded953804d019afa9a3f98981d99b33e3db7b6da\"\nuuid = \"944b1d66-785c-5afd-91f1-9de20f533193\"\nversion = \"0.7.0\"\n\n[[CoinUtils_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"OpenBLAS32_jll\", \"Pkg\"]\ngit-tree-sha1 = \"44173e61256f32918c6c132fc41f772bab1fb6d1\"\nuuid = \"be027038-0da8-5614-b30d-e42594cb92df\"\nversion = \"200.1100.400+0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[ColorVectorSpace]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"LinearAlgebra\", \"SpecialFunctions\", \"Statistics\", \"TensorCore\"]\ngit-tree-sha1 = \"3f1f500312161f1ae067abe07d13b40f78f32e07\"\nuuid = \"c3611d14-8923-5661-9e6a-0046d554d3a4\"\nversion = \"0.9.8\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[CommonSubexpressions]]\ndeps = [\"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"7b8a93dba8af7e3b42fecabf646260105ac373f7\"\nuuid = \"bbf7d656-a473-5ed7-a52c-81e309532950\"\nversion = \"0.3.0\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"44c37b4636bc54afac5c574d2d02b625349d6582\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.41.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Crayons]]\ngit-tree-sha1 = \"249fe38abf76d48563e2f4556bebd215aa317e15\"\nuuid = \"a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f\"\nversion = \"4.1.1\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataFrames]]\ndeps = [\"Compat\", \"DataAPI\", \"Future\", \"InvertedIndices\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"Markdown\", \"Missings\", \"PooledArrays\", \"PrettyTables\", \"Printf\", \"REPL\", \"Reexport\", \"SortingAlgorithms\", \"Statistics\", \"TableTraits\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"ae02104e835f219b8930c7664b8012c93475c340\"\nuuid = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nversion = \"1.3.2\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"3daef5523dd2e769dad2365274f760ff5f282c7d\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.11\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[DiffResults]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"c18e98cba888c6c25d1c3b048e4b3380ca956805\"\nuuid = \"163ba53b-c6d8-5494-b064-1a9d43ac40c5\"\nversion = \"1.0.3\"\n\n[[DiffRules]]\ndeps = [\"IrrationalConstants\", \"LogExpFunctions\", \"NaNMath\", \"Random\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"dd933c4ef7b4c270aacd4eb88fa64c147492acf0\"\nuuid = \"b552c78f-8df3-52c6-915a-8e097449b14b\"\nversion = \"1.10.0\"\n\n[[Distances]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"3258d0659f812acde79e8a74b11f17ac06d0ca04\"\nuuid = \"b4f34e82-e78d-54a5-968a-f98e89d6e8f7\"\nversion = \"0.10.7\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[FileIO]]\ndeps = [\"Pkg\", \"Requires\", \"UUIDs\"]\ngit-tree-sha1 = \"80ced645013a5dbdc52cf70329399c35ce007fae\"\nuuid = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nversion = \"1.13.0\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[ForwardDiff]]\ndeps = [\"CommonSubexpressions\", \"DiffResults\", \"DiffRules\", \"LinearAlgebra\", \"LogExpFunctions\", \"NaNMath\", \"Preferences\", \"Printf\", \"Random\", \"SpecialFunctions\", \"StaticArrays\"]\ngit-tree-sha1 = \"1bd6fc0c344fc0cbee1f42f8d2e7ec8253dda2d2\"\nuuid = \"f6369f11-7733-5829-9624-2563aa707210\"\nversion = \"0.10.25\"\n\n[[Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[Graphics]]\ndeps = [\"Colors\", \"LinearAlgebra\", \"NaNMath\"]\ngit-tree-sha1 = \"1c5a84319923bea76fa145d49e93aa4394c73fc2\"\nuuid = \"a2bd30eb-e257-5431-a919-1863eab51364\"\nversion = \"1.1.1\"\n\n[[Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[HypertextLiteral]]\ngit-tree-sha1 = \"2b078b5a615c6c0396c77810d92ee8c6f470d238\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.3\"\n\n[[IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[ImageBase]]\ndeps = [\"ImageCore\", \"Reexport\"]\ngit-tree-sha1 = \"b51bb8cae22c66d0f6357e3bcb6363145ef20835\"\nuuid = \"c817782e-172a-44cc-b673-b171935fbb9e\"\nversion = \"0.1.5\"\n\n[[ImageCore]]\ndeps = [\"AbstractFFTs\", \"ColorVectorSpace\", \"Colors\", \"FixedPointNumbers\", \"Graphics\", \"MappedArrays\", \"MosaicViews\", \"OffsetArrays\", \"PaddedViews\", \"Reexport\"]\ngit-tree-sha1 = \"9a5c62f231e5bba35695a20988fc7cd6de7eeb5a\"\nuuid = \"a09fc81d-aa75-5fe9-8630-4744c3626534\"\nversion = \"0.9.3\"\n\n[[ImageIO]]\ndeps = [\"FileIO\", \"JpegTurbo\", \"Netpbm\", \"OpenEXR\", \"PNGFiles\", \"QOI\", \"Sixel\", \"TiffImages\", \"UUIDs\"]\ngit-tree-sha1 = \"464bdef044df52e6436f8c018bea2d48c40bb27b\"\nuuid = \"82e4d734-157c-48bb-816b-45c225c6df19\"\nversion = \"0.6.1\"\n\n[[ImageShow]]\ndeps = [\"Base64\", \"FileIO\", \"ImageBase\", \"ImageCore\", \"OffsetArrays\", \"StackViews\"]\ngit-tree-sha1 = \"d0ac64c9bee0aed6fdbb2bc0e5dfa9a3a78e3acc\"\nuuid = \"4e3cecfd-b093-5904-9786-8bbb286a6a31\"\nversion = \"0.3.3\"\n\n[[Imath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"87f7662e03a649cffa2e05bf19c303e168732d3e\"\nuuid = \"905a6f67-0a94-5f89-b386-d35d92009cd1\"\nversion = \"3.1.2+0\"\n\n[[IndirectArrays]]\ngit-tree-sha1 = \"012e604e1c7458645cb8b436f8fba789a51b257f\"\nuuid = \"9b13fd28-a010-5f03-acff-a1bbcff69959\"\nversion = \"1.0.0\"\n\n[[Inflate]]\ngit-tree-sha1 = \"f5fc07d4e706b84f72d54eedcc1c13d92fb0871c\"\nuuid = \"d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9\"\nversion = \"0.1.2\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.2\"\n\n[[InvertedIndices]]\ngit-tree-sha1 = \"bee5f1ef5bf65df56bdd2e40447590b272a5471f\"\nuuid = \"41ab1584-1d38-5bbf-9106-f11c6c58b48f\"\nversion = \"1.1.0\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"abc9885a7ca2052a736a600f7fa66209f96506e1\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.4.1\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"3c837543ddb02250ef42f4738347454f95079d4e\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.3\"\n\n[[JpegTurbo]]\ndeps = [\"CEnum\", \"FileIO\", \"ImageCore\", \"JpegTurbo_jll\", \"TOML\"]\ngit-tree-sha1 = \"a77b273f1ddec645d1b7c4fd5fb98c8f90ad10a5\"\nuuid = \"b835a17e-a41a-41e7-81f0-2f016b05efe0\"\nversion = \"0.1.1\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b53380851c6e6664204efb2e62cd24fa5c47e4ba\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.2+0\"\n\n[[JuMP]]\ndeps = [\"Calculus\", \"DataStructures\", \"ForwardDiff\", \"JSON\", \"LinearAlgebra\", \"MathOptInterface\", \"MutableArithmetics\", \"NaNMath\", \"OrderedCollections\", \"Printf\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\"]\ngit-tree-sha1 = \"fe0f87cc077fc6a23c21e469318993caf2947d10\"\nuuid = \"4076af6c-e467-56ae-b986-b466b2749572\"\nversion = \"0.22.3\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"e5718a00af0ab9756305a0392832c8952c7426c1\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.6\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[METIS_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"1d31872bb9c5e7ec1f618e8c4a56c8b0d9bddc7e\"\nuuid = \"d00139f3-1899-568f-a2f0-47f597d42d70\"\nversion = \"5.1.1+0\"\n\n[[MUMPS_seq_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"METIS_jll\", \"OpenBLAS32_jll\", \"Pkg\"]\ngit-tree-sha1 = \"29de2841fa5aefe615dea179fcde48bb87b58f57\"\nuuid = \"d7ed1dd3-d0ae-5e8e-bfb4-87a502085b8d\"\nversion = \"5.4.1+0\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[MappedArrays]]\ngit-tree-sha1 = \"e8b359ef06ec72e8c030463fe02efe5527ee5142\"\nuuid = \"dbb5928d-eab1-5f90-85c2-b9b0edb7c900\"\nversion = \"0.4.1\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MathOptInterface]]\ndeps = [\"BenchmarkTools\", \"CodecBzip2\", \"CodecZlib\", \"JSON\", \"LinearAlgebra\", \"MutableArithmetics\", \"OrderedCollections\", \"Printf\", \"SparseArrays\", \"Test\", \"Unicode\"]\ngit-tree-sha1 = \"e8c9653877adcf8f3e7382985e535bb37b083598\"\nuuid = \"b8f27783-ece8-5eb3-8dc8-9495eed66fee\"\nversion = \"0.10.9\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MosaicViews]]\ndeps = [\"MappedArrays\", \"OffsetArrays\", \"PaddedViews\", \"StackViews\"]\ngit-tree-sha1 = \"b34e3bc3ca7c94914418637cb10cc4d1d80d877d\"\nuuid = \"e94cdb99-869f-56ef-bcf0-1ae2bcbe0389\"\nversion = \"0.3.3\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[MutableArithmetics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"Test\"]\ngit-tree-sha1 = \"842b5ccd156e432f369b204bb704fd4020e383ac\"\nuuid = \"d8a4904e-b15c-11e9-3269-09a3773c0cb0\"\nversion = \"0.3.3\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"b086b7ea07f8e38cf122f5016af580881ac914fe\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.7\"\n\n[[Netpbm]]\ndeps = [\"FileIO\", \"ImageCore\"]\ngit-tree-sha1 = \"18efc06f6ec36a8b801b23f076e3c6ac7c3bf153\"\nuuid = \"f09324ee-3d7c-5217-9330-fc30815ba969\"\nversion = \"1.0.2\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[OffsetArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"043017e0bdeff61cfbb7afeb558ab29536bbb5ed\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.8\"\n\n[[OpenBLAS32_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ba4a8f683303c9082e84afba96f25af3c7fb2436\"\nuuid = \"656ef2d0-ae68-5445-9ca0-591084a874a2\"\nversion = \"0.3.12+1\"\n\n[[OpenEXR]]\ndeps = [\"Colors\", \"FileIO\", \"OpenEXR_jll\"]\ngit-tree-sha1 = \"327f53360fdb54df7ecd01e96ef1983536d1e633\"\nuuid = \"52e1d378-f018-4a11-a4be-720524705ac7\"\nversion = \"0.3.2\"\n\n[[OpenEXR_jll]]\ndeps = [\"Artifacts\", \"Imath_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"923319661e9a22712f24596ce81c54fc0366f304\"\nuuid = \"18a262bb-aa17-5467-a713-aee519bc75cb\"\nversion = \"3.1.1+0\"\n\n[[OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[Osi_jll]]\ndeps = [\"Artifacts\", \"CoinUtils_jll\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"OpenBLAS32_jll\", \"Pkg\"]\ngit-tree-sha1 = \"28e0ddebd069f605ab1988ab396f239a3ac9b561\"\nuuid = \"7da25872-d9ce-5375-a4d3-7a845f58efdd\"\nversion = \"0.10800.600+0\"\n\n[[PNGFiles]]\ndeps = [\"Base64\", \"CEnum\", \"ImageCore\", \"IndirectArrays\", \"OffsetArrays\", \"libpng_jll\"]\ngit-tree-sha1 = \"eb4dbb8139f6125471aa3da98fb70f02dc58e49c\"\nuuid = \"f57f5aa1-a3ce-4bc8-8ab9-96f992907883\"\nversion = \"0.3.14\"\n\n[[PaddedViews]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"03a7a85b76381a3d04c7a1656039197e70eda03d\"\nuuid = \"5432bcbf-9aad-5242-b902-cca2824c8663\"\nversion = \"0.5.11\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"13468f237353112a01b2d6b32f3d0f80219944aa\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.2.2\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PkgVersion]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"a7a7e1a88853564e551e4eba8650f8c38df79b37\"\nuuid = \"eebad327-c553-4316-9ea0-9fa01ccd7688\"\nversion = \"0.1.1\"\n\n[[PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"ColorTypes\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"8979e9802b4ac3d58c503a20f2824ad67f9074dd\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.34\"\n\n[[PooledArrays]]\ndeps = [\"DataAPI\", \"Future\"]\ngit-tree-sha1 = \"db3a23166af8aebf4db5ef87ac5b00d36eb771e2\"\nuuid = \"2dfb63ee-cc39-5dd5-95bd-886bf059d720\"\nversion = \"1.4.0\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"2cf929d64681236a2e074ffafb8d568733d2e6af\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.3\"\n\n[[PrettyTables]]\ndeps = [\"Crayons\", \"Formatting\", \"Markdown\", \"Reexport\", \"Tables\"]\ngit-tree-sha1 = \"dfb54c4e414caa595a1f2ed759b160f5a3ddcba5\"\nuuid = \"08abe8d2-0d0c-5749-adfa-8a2ac140af0d\"\nversion = \"1.3.1\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Profile]]\ndeps = [\"Printf\"]\nuuid = \"9abbd945-dff8-562f-b5e8-e1ebf5ef1b79\"\n\n[[ProgressMeter]]\ndeps = [\"Distributed\", \"Printf\"]\ngit-tree-sha1 = \"afadeba63d90ff223a6a48d2009434ecee2ec9e8\"\nuuid = \"92933f4c-e287-5a05-a399-4b506db050ca\"\nversion = \"1.7.1\"\n\n[[QOI]]\ndeps = [\"ColorTypes\", \"FileIO\", \"FixedPointNumbers\"]\ngit-tree-sha1 = \"18e8f4d1426e965c7b532ddd260599e1510d26ce\"\nuuid = \"4b34888f-f399-49d4-9bb3-47ed5cae4e65\"\nversion = \"1.0.0\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.3.0\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Sixel]]\ndeps = [\"Dates\", \"FileIO\", \"ImageCore\", \"IndirectArrays\", \"OffsetArrays\", \"REPL\", \"libsixel_jll\"]\ngit-tree-sha1 = \"8fb59825be681d451c246a795117f317ecbcaa28\"\nuuid = \"45858cf5-a6b0-47a3-bbea-62219f50df47\"\nversion = \"0.1.2\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"8d0c8e3d0ff211d9ff4a0c2307d876c99d10bdf1\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"2.1.2\"\n\n[[StackViews]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"46e589465204cd0c08b4bd97385e4fa79a0c770c\"\nuuid = \"cae243ae-269e-4f55-b966-ac2d0dc13c15\"\nversion = \"0.1.1\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"95c6a5d0e8c69555842fc4a927fc485040ccc31c\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.3.5\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"c3d8ba7f3fa0625b062b82853a7d5229cb728b6b\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.2.1\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"bb1064c9a84c52e277f1096cf41434b675cd368b\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.6.1\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[TensorCore]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"1feb45f88d133a655e001435632f019a9a1bcdb6\"\nuuid = \"62fd8b95-f654-4bbd-a8a5-9c27f68ccd50\"\nversion = \"0.1.1\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[TiffImages]]\ndeps = [\"ColorTypes\", \"DataStructures\", \"DocStringExtensions\", \"FileIO\", \"FixedPointNumbers\", \"IndirectArrays\", \"Inflate\", \"OffsetArrays\", \"PkgVersion\", \"ProgressMeter\", \"UUIDs\"]\ngit-tree-sha1 = \"991d34bbff0d9125d93ba15887d6594e8e84b305\"\nuuid = \"731e570b-9d59-4bfa-96dc-6df516fadf69\"\nversion = \"0.5.3\"\n\n[[TranscodingStreams]]\ndeps = [\"Random\", \"Test\"]\ngit-tree-sha1 = \"216b95ea110b5972db65aa90f88d8d89dcb8851c\"\nuuid = \"3bb67fe8-82b1-5028-8e26-92a6c54297fa\"\nversion = \"0.9.6\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libsixel_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"78736dab31ae7a53540a6b752efc61f77b304c5b\"\nuuid = \"075b6546-f08a-558a-be8f-8157d0f608a5\"\nversion = \"1.8.6+1\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─d44f3f70-705b-43a2-85c0-a441e08fbbe6\n# ╟─a12d1135-ce89-414c-866e-14b4415e1990\n# ╟─d35c109a-e5b6-4c01-a9c2-333b883783f2\n# ╠═2d6d0588-f4e4-4cad-8353-9c0ba020fec6\n# ╟─2877f488-1ab3-46da-8a49-7db65c3d8a45\n# ╠═cf6d3f77-781d-4cd0-ad45-9c5c58380354\n# ╟─11c8323a-9cd5-4580-93d9-ebcd085b4551\n# ╠═0a9212cd-4c79-4752-930b-45dce6a1f3e8\n# ╟─7f7439d3-3d3b-4098-8be5-ca9aa59373ce\n# ╠═3e708ffa-05d9-4cf7-ba4c-11ca5a3e43e7\n# ╟─54082ac4-c31d-4d27-9cc3-5248018c6838\n# ╠═6bc42cc7-e3d4-4470-bece-6af950280372\n# ╟─a5f3abe7-a843-4ea5-8e77-dfd075b243a5\n# ╠═ee41a6b3-fb13-4269-ab22-ad2a85bf26e5\n# ╟─dd262e8b-4697-4aa7-9bc7-a32ac25c96dc\n# ╠═d5fc7ca7-33cd-4f8a-aecf-8897bcd40e15\n# ╟─4ab84877-f5d8-4c1b-b0d2-346f0048bb20\n# ╠═1054b6a4-1c28-46b6-88a4-6f7cae84edee\n# ╟─07f58656-4826-4ce5-8c97-bf5570f0fc60\n# ╠═17088a0b-a568-431c-8d01-13f957e2a4c0\n# ╟─4ded521e-c41f-4927-854b-86f8912269db\n# ╠═dab4e559-9dc6-4a72-8d38-9a0487b6251a\n# ╟─aa340dc7-8833-4e40-b63e-c602096e40e3\n# ╟─a2fad4bc-66fa-4466-ae29-b495590f035f\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "46e9ad0965a3379ddbadc2c6a654f8b77230e19c", "size": 32406, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "geographic_clustering.jl", "max_stars_repo_name": "halsawadi/geographical-clustering-of-saudi-cities-with-additional-constraint", "max_stars_repo_head_hexsha": "eb557c0aeea9e52222224f7d4d35906297e16988", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geographic_clustering.jl", "max_issues_repo_name": "halsawadi/geographical-clustering-of-saudi-cities-with-additional-constraint", "max_issues_repo_head_hexsha": "eb557c0aeea9e52222224f7d4d35906297e16988", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geographic_clustering.jl", "max_forks_repo_name": "halsawadi/geographical-clustering-of-saudi-cities-with-additional-constraint", "max_forks_repo_head_hexsha": "eb557c0aeea9e52222224f7d4d35906297e16988", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0336391437, "max_line_length": 280, "alphanum_fraction": 0.7341850275, "num_tokens": 14367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.7732002370170352}}
{"text": "@doc raw\"\"\"\n    galerkin_projection(\n        f, B::AbstractBSplineBasis,\n        [deriv = Derivative(0)], [VectorType = Vector{Float64}],\n    )\n\nPerform Galerkin projection of a function `f` onto the given basis.\n\nBy default, returns a vector with values\n\n```math\nφ_i = ⟨ b_i, f ⟩\n= ∫_a^b b_i(x) \\, f(x) \\, \\mathrm{d}x,\n```\n\nwhere ``a`` and ``b`` are the boundaries of the B-spline basis\n``\\{ b_i \\}_{i = 1}^N``.\n\nThe integrations are performed using Gauss--Legendre quadrature.\nThe number of quadrature nodes is chosen so that the result is exact when ``f``\nis a polynomial of degree ``k - 1`` (or, more generally, a spline belonging to\nthe space spanned by the basis `B`).\nHere ``k`` is the order of the B-spline basis.\nIn the more general case, this function returns a quadrature approximation of\nthe projection.\n\nSee also [`galerkin_projection!`](@ref) for the in-place operation, and\n[`galerkin_matrix`](@ref) for more details.\n\"\"\"\nfunction galerkin_projection(\n        f, B::AbstractBSplineBasis,\n        deriv = Derivative(0),\n        ::Type{V} = Vector{Float64},\n    ) where {V <: AbstractVector}\n    N = length(B)\n    φ = V(undef, N)\n    galerkin_projection!(f, φ, B, deriv)\nend\n\n\"\"\"\n    galerkin_projection!(\n        f, φ::AbstractVector, B::AbstractBSplineBasis, [deriv = Derivative(0)],\n    )\n\nCompute Galerkin projection ``φ_i = ⟨ b_i, f ⟩``.\n\nSee [`galerkin_projection`](@ref) for details.\n\"\"\"\nfunction galerkin_projection!(\n        f, φ::AbstractVector, B::AbstractBSplineBasis, deriv = Derivative(0),\n    )\n    N = length(B)\n    if length(φ) != N\n        throw(DimensionMismatch(\"incorrect length of output vector φ\"))\n    end\n    Base.require_one_based_indexing(φ)\n\n    k = order(B)\n    ts = knots(B)\n\n    # Quadrature information (nodes, weights).\n    quadx, quadw = _quadrature_prod(Val(2k - 2))\n    @assert length(quadx) == k  # we need k quadrature points per knot segment\n\n    fill!(φ, 0)\n\n    nlast = last(eachindex(ts))\n\n    # We loop over all knot segments Ω[n] = (ts[n], ts[n + 1]).\n    # For all B-splines with support in this segment, we integrate the product\n    # B[i] * f over this segment, adding the result to φ[i].\n    @inbounds for n in eachindex(ts)\n        n == nlast && break\n        tn, tn1 = ts[n], ts[n + 1]\n        tn1 == tn && continue  # interval of length = 0\n\n        metric = QuadratureMetric(tn, tn1)\n\n        # Unnormalise quadrature nodes, such that xs ∈ [tn, tn1]\n        xs = metric .* quadx\n        # @assert all(x -> tn ≤ x ≤ tn1, xs)\n\n        is = nonzero_in_segment(B, n)\n\n        # This is a property of B-spline bases, which should be preserved by\n        # derived (recombined) bases.\n        @assert 0 < length(is) ≤ k\n\n        # Evaluate all required basis functions on quadrature nodes.\n        bis = eval_basis_functions(B, is, xs, deriv)\n\n        fs = ntuple(i -> f(xs[i]), Val(length(xs)))  # this works fine!\n\n        # For some reason, the alternatives below allocate and give bad\n        # performance... (on Julia 1.7-beta2)\n        # fs = map(f, xs)\n        # fs = f.(xs)\n\n        for (ni, i) in enumerate(is)\n            bs = bis[ni]\n            φ[i] += metric.α * ((bs .* fs) ⋅ quadw)\n        end\n    end\n\n    φ\nend\n", "meta": {"hexsha": "3e6649098209ded5d8863aa59ec1682f5dedb954", "size": 3188, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Galerkin/projection.jl", "max_stars_repo_name": "jipolanco/BSplineKit.jl", "max_stars_repo_head_hexsha": "195c1d79efdabcc441d68d6911d5cff5095cea93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-11-03T21:11:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T19:09:34.000Z", "max_issues_repo_path": "src/Galerkin/projection.jl", "max_issues_repo_name": "jipolanco/BSplineKit.jl", "max_issues_repo_head_hexsha": "195c1d79efdabcc441d68d6911d5cff5095cea93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2020-06-29T07:46:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T16:25:06.000Z", "max_forks_repo_path": "src/Galerkin/projection.jl", "max_forks_repo_name": "jipolanco/BSplineKit.jl", "max_forks_repo_head_hexsha": "195c1d79efdabcc441d68d6911d5cff5095cea93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7943925234, "max_line_length": 79, "alphanum_fraction": 0.615119197, "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7732002332600896}}
{"text": "#=\n  From https://probmods.org/chapters/conditioning.html\n  (WebPPL):\n  \"\"\"\n  This classic Bayesian inference task is a special case of conditioning. Kahneman and Tversky, \n  and Gigerenzer and colleagues, have studied how people make simple judgments like the following:\n\n  The probability of breast cancer is 1% for a woman at 40 who participates in a routine screening. \n  If a woman has breast cancer, the probability is 80% that she will have a positive mammography. \n  If a woman does not have breast cancer, the probability is 9.6% that she will also have a \n  positive mammography. A woman in this age group had a positive mammography in a routine \n  screening. What is the probability that she actually has breast cancer?\n\n  What is your intuition? Many people without training in statistical inference judge the \n  probability to be rather high, typically between 0.7 and 0.9. The correct answer is much lower, \n  less than 0.1, as we can see by running this WebPPL inference:\n  \"\"\"\n\n  p(breastCancer): 0.0737\n\n  According to the WebPPL model:\n    breastCancer:\n    false : 0.922360248447205\n    true : 0.07763975155279507\n\n=#\n\nusing Turing\ninclude(\"jl_utils.jl\")\n\n@model function medical_diagnosis2()\n    breastCancer ~ flip(0.01)\n    positiveMammogram ~ breastCancer ? flip(0.8) : flip(0.096)\n\n    true ~ Dirac(positiveMammogram)\n\nend\n\nmodel = medical_diagnosis2()\n\nchns = sample(model, MH(), 10_000)\n# chns = sample(model, PG(15), 10_000)\n# chns = sample(model, IS(), 10_000)\n# chns = sample(model, SMC(), 10_000)\n\ndisplay(chns)\n", "meta": {"hexsha": "918e3343a56098aa77e148495e90eb15533799ed", "size": 1542, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/medical_diagnosis2.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/medical_diagnosis2.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/medical_diagnosis2.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 32.8085106383, "max_line_length": 100, "alphanum_fraction": 0.7373540856, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7732002166901586}}
{"text": "using Pkg; Pkg.add(\"Plots\")\nusing Plots\n# IJulia.clear_output(true)\n\n# Define functions and parameters\nH=4000.;L=H/10.;A=20.;C=50.;D=2.5;B=8.;E=5.e-4;\nft(x,L)=exp(-x/L)\nth1(z)=A*ft.(-z .+ L, L);\nth2(z)=C*ft(D*(-z .+ L), L);\n\n# Plot for equally spaced discrete points\nnpt=1000;\nz=-collect(range(0, 1, length=npt)) .* H\nphi1=th1.(z)\nphi2=th2.(z)\ntheta=phi1 .- phi2 .+ B .+ E .* z;\nplot( theta ,z,label=false, lw=3, color = :black )\nplot!(phi1 .+ B ,z,label=false , line=(:dash) )\nplot!(phi2 .+ B ,z,label=false , line=(:dash) )\n\n# Plot for ECCO 50-level discrete points\ndzECCO50l=[10.00, 10.00, 10.00, 10.00, 10.00, 10.00, 10.00, 10.01, \n    10.03, 10.11, 10.32, 10.80, 11.76, 13.42, 16.04 , 19.82, \n    24.85,31.10, 38.42, 46.50, 55.00, 63.50, 71.58, 78.90, \n     85.15, 90.18, 93.96, 96.58, 98.25, 99.25,100.01,101.33,\n    104.56,111.33,122.83,139.09,158.94,180.83,203.55,226.50,\n     249.50,272.50,295.50,318.50,341.50,364.50,387.50,410.50,\n    433.50,456.50];\ndz=dzECCO50l;\nz=-(cumsum(dz).-dz./2);\nphi1=th1.(z)\nphi2=th2.(z)\ntheta=phi1 .- phi2 .+ B .+ E .* z;\nplot( theta ,z,label=false, lw=3, color = :black )\nplot!(phi1 .+ B ,z,label=false , line=(:dash) )\nplot!(phi2 .+ B ,z,label=false , line=(:dash) )\n\n\n", "meta": {"hexsha": "53c45534c418d3ffdf39c955799c0aa51e400460", "size": 1210, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "impldiff/tzprof.jl", "max_stars_repo_name": "christophernhill/climahacks", "max_stars_repo_head_hexsha": "c5db08e8dcc76204ee21dfed5457599bec31d7f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "impldiff/tzprof.jl", "max_issues_repo_name": "christophernhill/climahacks", "max_issues_repo_head_hexsha": "c5db08e8dcc76204ee21dfed5457599bec31d7f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "impldiff/tzprof.jl", "max_forks_repo_name": "christophernhill/climahacks", "max_forks_repo_head_hexsha": "c5db08e8dcc76204ee21dfed5457599bec31d7f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0256410256, "max_line_length": 67, "alphanum_fraction": 0.5991735537, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995703, "lm_q2_score": 0.8418256452674009, "lm_q1q2_score": 0.7732002165780498}}
{"text": "#!/usr/bin/julia\n\n# Date: 21 August 2016\n# https://github.com/trizen\n\n# An efficient algorithm for computing large Fibonacci numbers, modulus some n.\n# Algorithm from: http://codeforces.com/blog/entry/14516\n\nfunction fibmod(n::Int64, mod::Int64)\n\n    n <= 1 && return n\n    cache = Dict{Int64, Int64}()\n\n    function f(n::Int64)\n\n        n <= 1           && return 1\n        haskey(cache, n) && return cache[n]\n\n        k = div(n, 2)\n\n        cache[n] =\n            if n % 2 == 0\n                (f(k) * f(k  ) + f(k-1) * f(k-1)) % mod\n            else\n                (f(k) * f(k+1) + f(k-1) * f(k  )) % mod\n            end\n    end\n\n    f(n-1)\nend\n\nprintln(fibmod(1000, 10^4))\n", "meta": {"hexsha": "dc5cac22ca42ed84764063eaad54f8be1d9122f3", "size": 678, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Math/modular_fibonacci.jl", "max_stars_repo_name": "trizen/julia-scripts", "max_stars_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-03-22T09:38:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T21:38:31.000Z", "max_issues_repo_path": "Math/modular_fibonacci.jl", "max_issues_repo_name": "trizen/julia-scripts", "max_issues_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/modular_fibonacci.jl", "max_forks_repo_name": "trizen/julia-scripts", "max_forks_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5454545455, "max_line_length": 79, "alphanum_fraction": 0.5, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007596, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7731694038754455}}
{"text": "data = [\n    8.9 14.0 4.3 19.9 2.1 28.0 3.6 1.3 4.3;\n    13.5 9.3 4.1 17.5 4.5 26.6 5.7 2.1 4.0;\n    18.0 9.9 3.3 19.5 5.7 28.1 4.8 2.4 6.5;\n    13.9 10.0 4.7 25.8 2.2 24.0 6.2 1.6 2.9;\n    9.5 13.6 3.6 23.4 2.5 22.4 4.2 1.8 3.7;\n    13.1 10.1 3.1 23.8 2.3 25.6 2.8 2.4 4.9;\n    17.4 5.7 4.7 20.6 4.3 24.3 4.7 3.4 3.3;\n    11.4 12.5 4.1 18.8 3.4 18.6 5.2 1.5 3.8\n]\n\nN = size(data)[1]\nprototypes = copy(data)\nclusters = [[i] for i = 1:N]\nC = length(clusters)\n\nd²(x⃗, y⃗) = sum((x⃗ - y⃗).^2)\nd′(x⃗ᵢ, x⃗ⱼ, nᵢ, nⱼ) = ((nᵢ * nⱼ) / (nᵢ + nⱼ)) * sum((x⃗ᵢ - x⃗ⱼ).^2)\n\nT = 2 # C\n\nfor t = 1:T\n    D = [i<j ? d′(prototypes[i, :], prototypes[j, :], length(clusters[i]), length(clusters[j])) : (i == j ? Inf : Inf) for i = 1:C, j = 1:C]\n    _, idx = findmin(D)\n    i, j = idx[1], idx[2]\n\n    append!(clusters[i], clusters[j])\n    deleteat!(clusters, j)\n    C = length(clusters)\n\n    prototypes = Matrix{Float64}(undef, C, 9)\n    for c = 1:C\n        vectors = [data[k, :] for k in clusters[c]]\n        mean = sum(vectors) / length(vectors)\n        prototypes[c, :] = mean\n    end\n\n    variances = zeros(C)\n    for r = 1:C\n        for k in clusters[r]\n            variances[r] += d²(data[k, :], prototypes[r, :])\n        end\n    end\n    total_variance = sum(variances)\n    println(\"total variance = $total_variance\")\nend\n", "meta": {"hexsha": "ec89abae0afbe91de3a5e19b3b2e2e731429f5ce", "size": 1306, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Wards.jl", "max_stars_repo_name": "tmwatchanan/UnsupervisedLearning.jl", "max_stars_repo_head_hexsha": "d3b54c334bcb0651023da2a0fd1990f1db218a3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Wards.jl", "max_issues_repo_name": "tmwatchanan/UnsupervisedLearning.jl", "max_issues_repo_head_hexsha": "d3b54c334bcb0651023da2a0fd1990f1db218a3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Wards.jl", "max_forks_repo_name": "tmwatchanan/UnsupervisedLearning.jl", "max_forks_repo_head_hexsha": "d3b54c334bcb0651023da2a0fd1990f1db218a3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7872340426, "max_line_length": 140, "alphanum_fraction": 0.5122511485, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7731524243131381}}
{"text": "\"\"\"\n```\nfunction interp(x::Vector{T}, x_knot::Vector{T}) where T<:AbstractFloat\n```\nCompute linear interpolation over 1D grid. It extrapolates outside of\nknot points. (SeHyoun Ahn, March 2017)\n\n# Arguments:\n- `x_fine`: x grid to interpolate to\n- `x_knot`: x knot points to interpolate from\n\n# Output:\n`V`: matrix giving interpolation values\n\n# Example:\n```\nx_fine = linspace(-1,1,300)'\nx_knot = linspace(0,2,20)'\nV = interp(x_fine, x_knot)\nplot(V * (x_knot.^5 + x_knot * 0.5))\n```\n\"\"\"\nfunction interp(x::Vector{T}, x_knot::Vector{T}) where {T<:AbstractFloat}\n    loc = sum(broadcast(-, x, x_knot') .>= 0, dims=2)\n    loc = max.(min.(loc, length(x_knot) - 1), 1)\n\n    t = (x - x_knot[loc]) ./ (x_knot[loc+1] - x_knot[loc])\n    ind_x = 1:length(x)\n\n    i = vec(repeat(ind_x,2,1))\n    j = [loc; loc + 1]\n    v = [(1 - t); t]\n\n    return SparseArrays.sparse(i, j, v, length(x), length(x_knot))\nend\n\n\"\"\"\n```\nfunction interp(x_fine::Vector{T}, y_fine::Vector{T},\n                x_knot::Vector{T}, y_knot::Vector{T}) where {T<:Float64}\n```\nCompute linear interpolation over 2D grid. It extrapolates outside of\nknot points. (SeHyoun Ahn, March 2017)\n\n# Arguments\n - `x_fine::Vector{T}`: x grid to interpolate to\n - `y_fine::Vector{T}`: y grid to interpolate to\n - `x_knot::Vector{T}`: x knot points to interpolate from\n - `y_knot::Vector{T}`: y knot points to interpolate from\n\n# Output\n - `V`: sparse matrix giving interpolation values\n\n# Example\n```\nx_fine = linspace(0,2,80)'\ny_fine = linspace(-1,1,100)'\nx_knot = linspace(0,1,10)'\ny_knot = linspace(0,1,10)'\n\nV = interp(x_fine, y_fine, x_knot, y_knot)\n\nz = broadcast(+, x_knot.^3 + exp(-x_knot), (y_knot' - 0.5).^2)\nsurf(x_fine,y_fine,reshape(V * vec(z), 80, 100)')\n```\n\"\"\"\nfunction interp(x_fine::Vector{T}, y_fine::Vector{T},\n                x_knot::Vector{T}, y_knot::Vector{T}) where {T<:Float64}\n\n    n_x      = length(x_knot)\n    ind_fine = 1:length(x_fine) * length(y_fine)\n\n    loc_x = sum(broadcast(-, x_fine, x_knot') .>= 0, dims=2)\n    loc_x = vec(max.(min.(loc_x, n_x - 1), 1))\n\n    loc_y = sum(broadcast(-, y_fine, y_knot') .>= 0, dims=2)\n    loc_y = max.(min.(loc_y, length(y_knot) - 1), 1)'\n\n    t_x = (x_fine .- x_knot[loc_x]) ./ (x_knot[loc_x .+ 1] .- x_knot[loc_x])\n    t_y = ((y_fine .- vec(y_knot[loc_y])) ./\n           (vec(y_knot[loc_y .+ 1]) .- vec(y_knot[loc_y])))'\n\n    j_SW = broadcast(+, loc_x,      n_x.*(loc_y .- 1))\n    j_SE = broadcast(+, loc_x .+ 1, n_x.*(loc_y .- 1))\n    j_NW = broadcast(+, loc_x,      n_x.*(loc_y))\n    j_NE = broadcast(+, loc_x .+ 1, n_x.*(loc_y))\n    v_SW = broadcast(*, (1 .- t_x), (1 .- t_y))\n    v_SE = broadcast(*, (t_x),      (1 .- t_y))\n    v_NW = broadcast(*, (1 .- t_x), (t_y))\n    v_NE = broadcast(*, (t_x),      (t_y))\n\n    i = vec(repeat(ind_fine, 4, 1))\n    j = [vec(j_SW); vec(j_SE); vec(j_NW); vec(j_NE)]\n    v = [vec(v_SW); vec(v_SE); vec(v_NW); vec(v_NE)]\n\n    return SparseArrays.sparse(i, j, v, length(x_fine) * length(y_fine), n_x * length(y_knot))\nend\n", "meta": {"hexsha": "8b62762fc758c2156b0a0cb819b1df46d565aafc", "size": 2973, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/heterogeneous/two_asset_hank/interp.jl", "max_stars_repo_name": "vpmerila/DSGE.jl", "max_stars_repo_head_hexsha": "9fd9b04e366a23dd8a7b05302e4c985185d0ead5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 822, "max_stars_repo_stars_event_min_datetime": "2015-12-03T13:42:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T16:12:55.000Z", "max_issues_repo_path": "src/models/heterogeneous/two_asset_hank/interp.jl", "max_issues_repo_name": "vpmerila/DSGE.jl", "max_issues_repo_head_hexsha": "9fd9b04e366a23dd8a7b05302e4c985185d0ead5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2016-06-20T14:42:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T16:14:10.000Z", "max_forks_repo_path": "src/models/heterogeneous/two_asset_hank/interp.jl", "max_forks_repo_name": "vpmerila/DSGE.jl", "max_forks_repo_head_hexsha": "9fd9b04e366a23dd8a7b05302e4c985185d0ead5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 226, "max_forks_repo_forks_event_min_datetime": "2015-12-03T16:53:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T09:52:56.000Z", "avg_line_length": 30.3367346939, "max_line_length": 94, "alphanum_fraction": 0.601749075, "num_tokens": 1087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7731004091178736}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,jl:light\n#     text_representation:\n#       extension: .jl\n#       format_name: light\n#       format_version: '1.4'\n#       jupytext_version: 1.2.1\n#   kernelspec:\n#     display_name: Julia 1.1.1\n#     language: julia\n#     name: julia-1.1\n# ---\n\n# # DifferentialEquations.jl Workshop Exercise 1\n#\n# - Exercise 1 takes the user through solving a stiff ordinary differential equation\n#   and using the ModelingToolkit.jl to automatically convert the function to a\n#   symbolic form to derive the analytical Jacobian to speed up the solver. The\n#   same biological system is then solved with stochasticity, utilizing\n#   EnsembleProblems to understand 95% bounds on the solution. Finally,\n#   probabilistic programming is employed to perform Bayesian parameter estimation\n#   of the parameters against data.\n\n# # Problem 1: Investigating Sources of Randomness and Uncertainty in a Stiff Biological System (B)\n#\n# In this problem we will walk through the basics of simulating models with\n# DifferentialEquations.jl. Let's take the\n# [Oregonator model of the Belousov-Zhabotinskii chemical reaction system](https://www.radford.edu/~thompson/vodef90web/problems/demosnodislin/Demos_Pitagora/DemoOrego/demoorego.pdf).\n# This system describes a classical example in non-equilibrium thermodynmics\n# and is a well-known natural chemical oscillator.\n#\n# ## Part 1: Simulating the Oregonator ODE model\n#\n# When modeling, usually one starts off by investigating the deterministic model.\n# The deterministic ODE formulation of the Oregonator is\n# given by the equations\n#\n# $$\\begin{align}\n# \\frac{dx}{dt} &= s(y-xy + x - qx^2)\\\\\n# \\frac{dy}{dt} &= (-y - xy + z)/s\\\\\n# \\frac{dz}{dt} &= w(x - z)\\end{align}$$\n\n# +\nusing ModelingToolkit, DifferentialEquations, Plots\n\n@parameters t s w q\n@variables x(t) y(t) z(t)\n@derivatives D'~t\n# -\n\neqs = [D(x) ~ s*(y-x*y+x-q*x^2),\n       D(y) ~ (-y - x*y + z)/s,\n       D(z) ~ w*(x - z)]\n\nde = ODESystem(eqs)\n\ngenerate_function(de, [x,y,z], [s, w, q])\n\nf = ODEFunction(de, [x,y,z], [s, w, q])\n\n# with parameter values $s=77.27$, $w=0.161$, and $q=8.375 \\times 10^{-6}$, and\n# initial conditions $x(0)=1$, $y(0)=2$, and $z(0)=3$. Use\n# [the tutorial on solving ODEs](http://docs.juliadiffeq.org/latest/tutorials/ode_example.html)\n# to solve this differential equation on the\n# timespan of $t\\in[0,360]$ with the default ODE solver. To investigate the result,\n# plot the solution of all components over time, and plot the phase space plot of\n# the solution (hint: use `vars=(1,2,3)`). What shape is being drawn in phase space?\n\nu0 = [1.0,2.0,3.0]\ntspan = (0.0,360.0)\np = [77.27,0.161,8.375e-6]\nprob = ODEProblem(f,u0,tspan,p)\n\nsol = solve(prob);\n\nplot(sol,vars=(1,2,3))\n\n# ## Part 2: Investigating Stiffness\n#\n# Because the reaction rates of `q` vs `s` is very large, this model has a \"fast\"\n# system and a \"slow\" system. This is typical of ODEs which exhibit a property\n# known as stiffness. Stiffness changes the ODE solvers which can handle the\n# equation well. [Take a look at the ODE solver page](http://docs.juliadiffeq.org/latest/solvers/ode_solve.html)\n# and investigate solving the equation using methods for non-stiff equations\n# (ex: `Tsit5`) and stiff equations (ex: `Rodas5`).\n#\n# Benchmark using $t\\in[0,50]$ using `@btime` from BenchmarkTools.jl. What\n# happens when you increase the timespan?\n\n\n\n\n\n# ## (Optional) Part 3: Specifying Analytical Jacobians (I)\n#\n# Stiff ODE solvers internally utilize the Jacobian of the ODE system in order\n# to improve the stepsizes in the solution. However, computing and factorizing\n# the Jacobian is costly, and thus it can be beneficial to provide the analytical\n# solution.\n#\n# Use the\n# [ODEFunction definition page](http://docs.juliadiffeq.org/latest/features/performance_overloads.html)\n# to define an `ODEFunction` which holds both the OREGO ODE and its Jacobian, and solve using `Rodas5`.\n#\n# ## (Optional) Part 4: Automatic Symbolicification and Analytical Jacobian Calculations\n#\n# Deriving Jacobians by hand is tedious. Thankfully symbolic mathematical systems\n# can do the work for you. And thankfully, DifferentialEquations.jl has tools\n# to automatically convert numerical problems into symbolic problems to perform\n# the analysis on!\n#\n# follow the [ModelingToolkit.jl README](https://github.com/JuliaDiffEq/ModelingToolkit.jl)\n# to automatically convert your ODE definition\n# to its symbolic form using `modelingtoolkitize` and calculate the analytical\n# Jacobian. Use the compilation functions to build the `ODEFunction` with the\n# embedded analytical solution.\n#\n# ## Part 5: Adding stochasticity with stochastic differential equations\n#\n# How does this system react in the presense of stochasticity? We can investigate\n# this question by using stochastic differential equations. A stochastic\n# differential equation formulation of this model is known as the multiplicative\n# noise model, is created with:\n#\n# $$\\begin{align}\n# dx &= s(y-xy + x - qx^2)dt + \\sigma_1 x dW_1\\\\\n# dy &= \\frac{-y - xy + z}{s}dt + \\sigma_2 y dW_2\\\\\n# dz &= w(x - z)dt + \\sigma_3 z dW_3\\end{align}$$\n#\n# with $\\sigma_i = 0.1$ where the `dW` terms describe a Brownian motion, a\n# continuous random process with normally distributed increments. Use the\n# [tutorial on solving SDEs](http://docs.juliadiffeq.org/latest/tutorials/sde_example.html)\n# to solve simulate this model. Then,\n# [use the `EnsembleProblem`](http://docs.juliadiffeq.org/latest/features/ensemble.html)\n# to generate and plot 100 trajectories of the stochastic model, and use\n# `EnsembleSummary` to plot the mean and 5%-95% region over time.\n#\n# Try solving with the `ImplicitRKMil` and `SOSRI` methods. Notice that it isn't\n# stiff every single time!\n#\n# (For fun, see if you can make the Euler-Maruyama `EM()` method solve this equation.\n# This requires a choice of `dt` small enough to be stable. This is the \"standard\"\n# method!)\n#\n# ## Part 6: Gillespie jump models of discrete stochasticity\n#\n# When biological models have very few particles, continuous models no longer\n# make sense, and instead using the full discrete formulation can be required\n# to accuracy describe the dynamics. A discrete differential equation, or\n# Gillespie model, is a continuous-time Markov chain with Poisson-distributed\n# jumps. A discrete description of the Oregonator model is given by a chemical\n# reaction systems:\n\nA+Y -> X+P\nX+Y -> 2P\nA+X -> 2X + 2Z\n2X  -> A + P (note: this has rate kX^2!)\nB + Z -> Y\n\n# where reactions take place at a rate which is propoertional to its components,\n# i.e. the first reaction has a rate `k*A*Y` for some `k`.\n# Use the [tutorial on Gillespie SSA models](http://docs.juliadiffeq.org/latest/tutorials/discrete_stochastic_example.html)\n# to implement the `JumpProblem` for this model, and use the `EnsembleProblem`\n# and `EnsembleSummary` to characterize the stochastic trajectories.\n#\n# For what rate constants does the model give the oscillatory dynamics for the\n# ODE approximation? For information on the true reaction rates, consult\n# [the original paper](https://pubs.acs.org/doi/abs/10.1021/ja00780a001).\n#\n# ## Part 7: Probabilistic Programming / Bayesian Parameter Estimation with DiffEqBayes.jl + Turing.jl (I)\n#\n# In many casees, one comes to understand the proper values for their model's\n# parameters by utilizing data fitting techniques. In this case, we will use\n# the DiffEqBayes.jl library to perform a Bayesian estimation of the parameters.\n# For our data we will the following potential output:\n\nt = 0.0:1.0:30.0\ndata = [1.0 2.05224 2.11422 2.1857 2.26827 2.3641 2.47618 2.60869 2.7677 2.96232 3.20711 3.52709 3.97005 4.64319 5.86202 9.29322 536.068 82388.9 57868.4 1.00399 1.00169 1.00117 1.00094 1.00082 1.00075 1.0007 1.00068 1.00066 1.00065 1.00065 1.00065\n        2.0 1.9494 1.89645 1.84227 1.78727 1.73178 1.67601 1.62008 1.56402 1.50772 1.45094 1.39322 1.33366 1.2705 1.19958 1.10651 0.57194 0.180316 0.431409 251.774 591.754 857.464 1062.78 1219.05 1335.56 1419.88 1478.22 1515.63 1536.25 1543.45 1539.98\n        3.0 2.82065 2.68703 2.58974 2.52405 2.48644 2.47449 2.48686 2.52337 2.58526 2.67563 2.80053 2.9713 3.21051 3.5712 4.23706 12.0266 14868.8 24987.8 23453.4 19202.2 15721.6 12872.0 10538.8 8628.66 7064.73 5784.29 4735.96 3877.66 3174.94 2599.6]\n\n# [Follow the exmaples on the parameter estimation page](http://docs.juliadiffeq.org/latest/analysis/parameter_estimation.html#Bayesian-Methods-1)\n# to perform a Bayesian parameter estimation. What are the most likely parameters\n# for the model given the posterior parameter distributions?\n#\n# Use the `ODEProblem` to perform the fit. If you have time, use the `EnsembleProblem`\n# of `SDEProblem`s to perform a fit over averages of the SDE solutions. Note that\n# the SDE fit will take significantly more computational resources! See the GPU\n# parallelism section for details on how to accelerate this.\n#\n# ## (Optional) Part 8: Using DiffEqBiological's Reaction Network DSL\n#\n# DiffEqBiological.jl is a helper library for the DifferentialEquations.jl\n# ecosystem for defining chemical reaction systems at a high leevel for easy\n# simulation in these various forms. Use the descrption\n# [from the Chemical Reaction Networks documentation page](http://docs.juliadiffeq.org/latest/models/biological.html)\n# to build a reaction network and generate the ODE/SDE/jump equations, and\n# compare the result to your handcoded versions.\n#\n#\n", "meta": {"hexsha": "42a2f1df6f714066904dff718257cd6156b0cbf2", "size": 9424, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemOne.jl", "max_stars_repo_name": "pnavaro/NotesJuliaCon2019", "max_stars_repo_head_hexsha": "e419ac7eda7c3616ba8c5b5a9b3a90bac3fef1d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemOne.jl", "max_issues_repo_name": "pnavaro/NotesJuliaCon2019", "max_issues_repo_head_hexsha": "e419ac7eda7c3616ba8c5b5a9b3a90bac3fef1d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemOne.jl", "max_forks_repo_name": "pnavaro/NotesJuliaCon2019", "max_forks_repo_head_hexsha": "e419ac7eda7c3616ba8c5b5a9b3a90bac3fef1d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.4236453202, "max_line_length": 251, "alphanum_fraction": 0.7411926995, "num_tokens": 2826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.9032941969413321, "lm_q1q2_score": 0.7730853877857161}}
{"text": "@doc raw\"\"\"\r\n```\r\nZ,p,q = retrieve_surface(algorithm::DiscreteShape, img::AbstractArray, iterations::Int=2000)\r\n```\r\nAttempts to produce a heightmap from a grayscale image by minimization of a set\r\nof Euler-Lagrange equations. This is done discretely at each point in the image\r\nutilizing the second derivates of the surface normals and their Fourier Transforms.\r\n# Output\r\nReturns an M by N array of Float `Z` that represents the reconstructed height at\r\nthe point and the gradients in M by N arrays of Float 'p' and 'q'.\r\n# Details\r\nThe algorithm attempts to minimise the brightness deviation ``ϵ`` through the\r\nbrightness constraint ``\\epsilon_1`` and smoothness constraint ``\\epsilon_2``\r\nas defined bellow:\r\n```math\r\n\\epsilon=\\iint((\\epsilon_1+\\lambda\\epsilon_2))dxdy=\\iint((E(x,y)-R(p,q))^2+\r\n\\lambda(p_x^2+q_x^2+p_y^2+q_y^2))\r\n```\r\nThis is minimised using the Euler-Lagrange equations defined as;\r\n```math\r\n\\dfrac{\\delta\\epsilon}{\\delta p}-\\dfrac{\\delta}{\\delta x}\\dfrac{\\delta\\epsilon}{\r\n\\delta p_x}-\\dfrac{\\delta}{\\delta y}\\dfrac{\\delta\\epsilon}{\\delta p_y}=0\r\n```\r\nand\r\n```math\r\n\\dfrac{\\delta\r\n\\epsilon}{\\delta q}-\\dfrac{\\delta}{\\delta x}\\dfrac{\\delta\\epsilon}{\\delta q_x}-\r\n\\dfrac{\\delta}{\\delta y}\\dfrac{\\delta\\epsilon}{\\delta q_y}=0\r\n```\r\nwhich become:\r\n```math\r\n\\begin{gathered}\r\n-2(E-R)\\dfrac{\\delta R}{\\delta p}-2\\lambda p_{xx}-2\\lambda p_{yy}=0\\\\\r\n-2(E-R)\\dfrac{\\delta R}{\\delta p}-2\\lambda q_{xx}-2\\lambda q_{yy}=0\r\n\\end{gathered}\r\n```\r\nwhich can be further simplified to give:\r\n```math\r\n\\begin{gathered}\r\n\\nabla^2p=\\dfrac{1}{\\lambda}(R-E)\\dfrac{\\delta R}{\\delta p}\\\\\r\n\\nabla^2q=\\dfrac{1}{\\lambda}(R-E)\\dfrac{\\delta R}{\\delta q}\r\n\\end{gathered}\r\n```\r\nwhere ``\\nabla^2p=p_{xx}+p_{yy}`` and ``\\nabla^2q=q_{xx}+q_{yy}`` are Laplacians\r\nof p and q.\r\n\r\nHowever, for computation we are dealing with a discreate case of these equations\r\nwhich can be defined as below:\r\n```math\r\n\\begin{gathered}\r\np_{i,j}=\\bar{p}_{i,j}+\\dfrac{1}{4\\lambda}(E-R)\\dfrac{\\delta R}{\\delta p}\\\\q_{i,j}=\r\n\\bar{q}_{i,j}+\\dfrac{1}{4\\lambda}(E-R)\\dfrac{\\delta R}{\\delta q}\\\\\r\n\\end{gathered}\r\n```\r\nwhere\r\n```math\r\n\\bar{p}_{i,j}=\\dfrac{p_{i+1,j}+p_{i-1,j}+p_{i,j+1}+p_{i,j-1}}{4}\r\n```\r\nand\r\n```math\r\n\\bar{q}_{i,j}=\\dfrac{q_{i+1,j}+q_{i-1,j}+q_{i,j+1}+q_{i,j-1}}{4}\r\n```\r\nFinally, the algorithm needs to enforce integrability on p and q and retrieve\r\nthe surface Z. This can be done by taking the Fast Fourier Transform of p and q\r\n()``c_p(\\omega_x,\\omega_y)`` and ``c_q(\\omega_x,\\omega_y)``) and then using the\r\nInverse Fast Fourier Transform to recover Z and update p and q as per bellow:\r\n```math\r\n\\begin{gathered}\r\np=\\sum c_p(\\omega_x,\\omega_y)e^{j(\\omega_xx+\\omega_yy)}\\\\\r\nq=\\sum c_q(\\omega_x,\\omega_y)e^{j(\\omega_xx+\\omega_yy)}\\\\Z=\\sum c(\\omega_x,\\omega_y)\r\ne^{j(\\omega_xx+\\omega_yy)}\\\\\r\n\\end{gathered}\r\n```\r\nwhere\r\n```math\r\nc(\\omega_x,\\omega_y)=\\dfrac{-j(\\omega_xc_p(\\omega_x,\\omega_y)+\\omega_yc_q(\\omega_x\r\n,\\omega_y))}{\\omega_x^2+\\omega_y^2}\r\n```\r\n\r\nThe `albedo` and `illumination_direction` can be manually defined using the\r\nfunction signature:\r\n```\r\nZ,p,q = retrieve_surface(algorithm::DiscreteShape, img::AbstractArray, albedo::Real, illumination_direction::Vector{T} where T <: Real, iterations::Int=2000)\r\n```\r\nNote: if `albedo` and `illumination_direction` are not supplied they will be\r\ncalculated at runtime using `estimate_img_properties`.\r\n# Arguments\r\nThe function arguments are described in more detail below.\r\n##  `img`\r\nAn `AbstractArray` storing the grayscale value of each pixel within\r\nthe range [0,1].\r\n## `albedo`\r\nA `Real` that specifies the albedo (amount of light reflected) of the image. If\r\n`albedo` is specified to must the `illumination_direction`.\r\n## `illumination_direction`\r\nA `Vector{T} where T <: Real` that specifies the tilt value to be used by the\r\nalgorithm. The `illumination_direction` should be a vector of the form [x,y,z]\r\nwhere x,y,z are int he range [0,1]. If `illumination_direction` is specified\r\nto must the `albedo`.\r\n## `iterations`\r\nAn `Int` that specifies the number of iterations the algorithm is to perform. If\r\nleft unspecified a default value of 2000 is used.\r\n## `smoothness`\r\nAn `Int` that specifies the strength of the smoothness constraint in the minimised\r\nfunction.\r\n# Example\r\nCompute the heightmap for a synthetic image generated by `generate_surface`.\r\n```julia\r\nusing Images, Makie, ShapeFromShading\r\n\r\n#generate synthetic image\r\nimg = generate_surface(SynthSphere(), 1, [0.2,0,0.9], radius = 5)\r\n\r\n#calculate the heightmap (using 500 iterations)\r\nZ,p,q = retrieve_surface(DiscreteShape(), img, 500)\r\n\r\n#normalize to maximum of 1 (not necessary but makes displaying easier)\r\nZ = Z./maximum(Z)\r\n\r\n#display using Makie (Note: Makie can often take several minutes first time)\r\nr = 0.0:0.1:2\r\nsurface(r, r, Z)\r\n```\r\n# Reference\r\n1. S. Elhabian, \"Hands on Shape from Shading\", Computer Vision and Image Processing, 2008.\r\n\"\"\"\r\nfunction retrieve_surface(algorithm::DiscreteShape, img::AbstractArray, iterations::Int=2000; smoothness::Int=1000)\r\n    ρ,I,σ,τ = estimate_img_properties(img)\r\n    λ=smoothness\r\n    return retrieve_surface(DiscreteShape(), img, ρ, I, iterations, smoothness=λ)\r\nend\r\n\r\nfunction retrieve_surface(algorithm::DiscreteShape, img::AbstractArray, albedo::Real, illumination_direction::Vector{T} where T <: Real, iterations::Int=2000; smoothness::Int=1000)\r\n    ρ = albedo\r\n    I = illumination_direction\r\n    E = Array{Float64}(img)\r\n\r\n    #initialize variables\r\n    p = zeros(Complex{Float64},axes(E))\r\n    q = zeros(Complex{Float64},axes(E))\r\n    R = zeros(Complex{Float64},axes(E))\r\n    Z = zeros(axes(E))\r\n    return solve_EulerLagrange(ρ, I, iterations, p, q, R, smoothness, E, Z)\r\nend\r\n", "meta": {"hexsha": "8ae95b864ca26612670e872d6cb29f8e774de731", "size": 5662, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/discreteshape.jl", "max_stars_repo_name": "JuliaTagBot/ShapeFromShading.jl", "max_stars_repo_head_hexsha": "c602cf16e4c795b65164e6d96b26cbdfc0d2e0c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/discreteshape.jl", "max_issues_repo_name": "JuliaTagBot/ShapeFromShading.jl", "max_issues_repo_head_hexsha": "c602cf16e4c795b65164e6d96b26cbdfc0d2e0c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-02-08T06:23:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T17:29:42.000Z", "max_forks_repo_path": "src/discreteshape.jl", "max_forks_repo_name": "JuliaTagBot/ShapeFromShading.jl", "max_forks_repo_head_hexsha": "c602cf16e4c795b65164e6d96b26cbdfc0d2e0c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-01-08T04:40:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T20:13:00.000Z", "avg_line_length": 39.0482758621, "max_line_length": 181, "alphanum_fraction": 0.7011656658, "num_tokens": 1755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639694252316, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.7730327490641916}}
{"text": "# algorithm on page 504 of https://people.maths.ox.ac.uk/trefethen/barycentric.pdf\nfunction barycentric_lagrange_weights(x)\n    n = length(x) - 1   \n    w = similar(x)\n    w[1] = 1.0\n    for j in 1:n\n        for k in 0:j-1\n            w[k+1] = (x[k+1] - x[j+1]) * w[k+1]\n        end    \n        w[j+1] = prod(0:j-1) do k\n            x[j+1] - x[k+1]\n        end    \n    end\n    for j in 0:n\n        w[j+1] = 1/w[j+1]\n    end    \n    return w\nend    \n\n# equation 4.2 of https://people.maths.ox.ac.uk/trefethen/barycentric.pdf\nfunction barycentric_lagrange_matrix(xs,xt,w=barycentric_lagrange_weights(xs))\n    ns = length(xs)    \n    nt = length(xt)\n    d = similar(xt)    \n    for i in 1:nt\n        d[i] = sum(zip(xs,w)) do (x,w)\n            w /(xt[i]-x)\n        end    \n    end\n    A= [w[j]/(xt[i]-xs[j]) / d[i] for i in 1:nt, j in 1:ns]\n    return A\nend    \n", "meta": {"hexsha": "f573fcd95ce317690b76a5bc39f187b610e5847a", "size": 858, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Interpolation/lagrange.jl", "max_stars_repo_name": "WaveProp/WaveProp", "max_stars_repo_head_hexsha": "4d589a093d6d590d2f7bf0bfdf2cc8e2da1b1fec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-15T13:46:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T07:16:38.000Z", "max_issues_repo_path": "src/Interpolation/lagrange.jl", "max_issues_repo_name": "WaveProp/WaveProp", "max_issues_repo_head_hexsha": "4d589a093d6d590d2f7bf0bfdf2cc8e2da1b1fec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-06-24T20:14:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-25T11:07:01.000Z", "max_forks_repo_path": "src/Interpolation/lagrange.jl", "max_forks_repo_name": "WaveProp/WaveProp", "max_forks_repo_head_hexsha": "4d589a093d6d590d2f7bf0bfdf2cc8e2da1b1fec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-15T17:31:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T09:43:13.000Z", "avg_line_length": 26.0, "max_line_length": 82, "alphanum_fraction": 0.5093240093, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7730247442237087}}
{"text": "# indicator of the ball of matrices with (at most) a given rank\n\n\"\"\"\n  IndBallRank(r::Int=1)\n\nReturns the function `g = ind{X : rank(X) ⩽ r}`, for an integer parameter `r > 0`.\n\"\"\"\n\nimmutable IndBallRank{I <: Integer} <: IndicatorNonconvex\n  r::I\n  function IndBallRank(r::I)\n    if r <= 0\n      error(\"parameter r must be a positive integer\")\n    else\n      new(r)\n    end\n  end\nend\n\nIndBallRank{I <: Integer}(r::I=1) = IndBallRank{I}(r)\n\nfunction (f::IndBallRank){T <: RealOrComplex}(x::AbstractArray{T,2})\n  maxr = minimum(size(x))\n  if maxr <= f.r return 0.0 end\n  svdobj = svds(x, nsv=f.r+1)[1]\n  # the tolerance in the following line should be customizable\n  if svdobj[:S][end]/svdobj[:S][1] <= 1e-14\n    return 0.0\n  end\n  return +Inf\nend\n\nfunction prox!{T <: Real}(f::IndBallRank, x::AbstractArray{T,2}, y::AbstractArray{T,2}, gamma::Real=1.0)\n  maxr = minimum(size(x))\n  if maxr <= f.r\n    y[:] = x\n    return 0.0\n  end\n  svdobj = svds(x, nsv=f.r)[1]\n  for i = 1:size(x,1)\n    for j = 1:size(x,2)\n      y[i,j] = 0.0\n      for k = 1:f.r\n          if VERSION >= v\"0.6.0-dev.2071\"\n              y[i,j] += svdobj[:U][i,k]*svdobj[:S][k]*svdobj[:Vt][k,j]\n          else\n              y[i,j] += svdobj[:U][i,k]*svdobj[:S][k]*svdobj[:Vt][j,k]\n          end\n      end\n    end\n  end\n  return 0.0\nend\n\nfunction prox!{T <: Complex}(f::IndBallRank, x::AbstractArray{T,2}, y::AbstractArray{T,2}, gamma::Real=1.0)\n  maxr = minimum(size(x))\n  if maxr <= f.r\n    y[:] = x\n    return 0.0\n  end\n  svdobj = svds(x, nsv=f.r)[1]\n  for i = 1:size(x,1)\n    for j = 1:size(x,2)\n      y[i,j] = 0.0 + 0.0im\n      for k = 1:f.r\n          if VERSION >= v\"0.6.0-dev.2071\"\n              y[i,j] += svdobj[:U][i,k]*svdobj[:S][k]*svdobj[:Vt][k,j]\n          else\n              y[i,j] += svdobj[:U][i,k]*svdobj[:S][k]*conj(svdobj[:Vt][j,k])\n          end\n      end\n    end\n  end\n  return 0.0\nend\n\nfun_name(f::IndBallRank) = \"indicator of the set of rank-r matrices\"\nfun_dom(f::IndBallRank) = \"AbstractArray{Real,2}, AbstractArray{Complex,2}\"\nfun_expr(f::IndBallRank) = \"x ↦ 0 if rank(x) ⩽ r, +∞ otherwise\"\nfun_params(f::IndBallRank) = \"r = $(f.r)\"\n\nfunction prox_naive{T <: RealOrComplex}(f::IndBallRank, x::AbstractArray{T,2}, gamma::Real=1.0)\n  maxr = minimum(size(x))\n  if maxr <= f.r\n    y = x\n    return y, 0.0\n  end\n  U, S, V = svd(x)\n  M = U[:,1:f.r]*spdiagm(S[1:f.r])\n  y = M*V[:,1:f.r]'\n  return y, 0.0\nend\n", "meta": {"hexsha": "193d939bd38e96dde57dc6407014c428a992b44c", "size": 2389, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indBallRank.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/indBallRank.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/indBallRank.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.688172043, "max_line_length": 107, "alphanum_fraction": 0.5638342403, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388752, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7730144002853453}}
{"text": "export σx, σy, σz, 𝟙, up, down, ⊗, speye, identity_op, single_spin_op, correlator, op_list, symmetrize_state, symmetrize_op, nspins\n\n\nconst σx = sparse([0 1; 1 0])\nconst σy = sparse([0 -im; im 0])\nconst σz = sparse([1 0; 0 -1])\nconst 𝟙 = spdiagm([1, 1])\n\nconst up = [1,0]\nconst down = [0,1]\n\nconst ⊗ = kron\n\nspeye(k::Integer) = spdiagm([1 for _ in 1:k])\nidentity_op(k::Integer) = speye(2^k)\n\n\"\"\"\n    nspins(obj)\n\nGive number of spins in the system this object belongs to.\n\"\"\"\nfunction nspins(system_size::Int)\n    N = Int(ceil(log2(system_size)))\n    2^N == system_size || throw(ArgumentError(\"$(system_size) is not a power of 2!\"))\n    N\nend\nnspins(state::AbstractVector) = nspins(length(state))\nnspins(op::AbstractMatrix) = size(op,1) == size(op, 2) ? nspins(size(op, 1)) : throw(ArgumentError(\"The operator is not a square-matrix!\"))\n\nsingle_spin_op(op, k::Integer, N::Integer) = identity_op(k-1) ⊗ op ⊗ identity_op(N-k)\ncorrelator(op, i::Integer, j::Integer, N::Integer) = i > j ? correlator(op, j, i, N) : identity_op(i-1) ⊗ op ⊗ identity_op(j-i-1) ⊗ op ⊗ identity_op(N-j)\n\nop_list(op, N::Integer) = [single_spin_op(op, k, N) for k in 1:N]\n", "meta": {"hexsha": "2c504dccf50049c6f4ce542cc57c45b4d57aaf0c", "size": 1145, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spin_half.jl", "max_stars_repo_name": "abraemer/XXZNumerics.jl", "max_stars_repo_head_hexsha": "a54068accd79306e9e2b934b5bf83c4487f64dbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-08T17:29:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T17:29:26.000Z", "max_issues_repo_path": "src/spin_half.jl", "max_issues_repo_name": "abraemer/XXZNumerics.jl", "max_issues_repo_head_hexsha": "a54068accd79306e9e2b934b5bf83c4487f64dbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-25T06:08:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-09T11:31:02.000Z", "max_forks_repo_path": "src/spin_half.jl", "max_forks_repo_name": "abraemer/XXZNumerics.jl", "max_forks_repo_head_hexsha": "a54068accd79306e9e2b934b5bf83c4487f64dbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6764705882, "max_line_length": 153, "alphanum_fraction": 0.6620087336, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7730143880551664}}
{"text": "# # Welford's algorithm\n#\n# * Welford, B. P. (1962). \"Note on a method for calculating corrected sums of squares and products\". Technometrics. 4 (3): 419–420. doi:10.2307/1266577. JSTOR 1266577\n# * [Welford's online algorithm - Algorithms for calculating variance - Wikipedia](https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm)\n\n\nusing Transducers\nusing Transducers: R_, start, next, complete, inner, xform, wrap, unwrap, wrapping\n\nstruct MeanVar <: Transducer\nend\n\n\nfunction Transducers.start(rf::R_{MeanVar}, result)\n    private_state = (0, 0.0, 0.0)\n    return wrap(rf, private_state, start(inner(rf), result))\nend\n\n\nfunction Transducers.next(rf::R_{MeanVar}, result, input)\n    wrapping(rf, result) do st, iresult\n        (n, μ, M2) = st\n        n += 1\n        δ = input - μ\n        μ += δ/n\n        δ2 = input - μ\n        M2 += δ*δ2\n        iinput = (μ, M2 / (n-1))\n        iresult = next(inner(rf), iresult, iinput)\n        return (n, μ, M2), iresult\n    end\nend\n\nfunction Transducers.complete(rf::R_{MeanVar}, result)\n    _private_state, inner_result = unwrap(rf, result)\n    return complete(inner(rf), inner_result)\nend\n\ncollect(MeanVar(),randn(10))\n\n@time foldl(right, MeanVar(), 1:100)\n", "meta": {"hexsha": "8512bf9371a7f75a15c4b28997d864681872df9b", "size": 1239, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/meanvar.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Transducers.jl-28d57a85-8fef-5791-bfe6-a80928e7c999", "max_stars_repo_head_hexsha": "abfa98490d7f1af655dc2d276dca31964a153c9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 185, "max_stars_repo_stars_event_min_datetime": "2020-06-05T03:56:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:54:59.000Z", "max_issues_repo_path": "examples/meanvar.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Transducers.jl-28d57a85-8fef-5791-bfe6-a80928e7c999", "max_issues_repo_head_hexsha": "abfa98490d7f1af655dc2d276dca31964a153c9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 283, "max_issues_repo_issues_event_min_datetime": "2018-12-29T14:33:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-29T17:36:28.000Z", "max_forks_repo_path": "examples/meanvar.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Transducers.jl-28d57a85-8fef-5791-bfe6-a80928e7c999", "max_forks_repo_head_hexsha": "abfa98490d7f1af655dc2d276dca31964a153c9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-07-02T09:11:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T12:08:58.000Z", "avg_line_length": 29.5, "max_line_length": 176, "alphanum_fraction": 0.6698950767, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.7729871982045778}}
{"text": "# # Time Dependent Problems\n#\n# ![](transient_heat.gif)\n#\n# *Figure 1*: Visualization of the temperature time evolution on a unit\n# square where the prescribed temperature on the upper and lower parts\n# of the boundary increase with time.\n#\n#-\n#md # !!! tip\n#md #     This example is also available as a Jupyter notebook:\n#md #     [`transient_heat_equation.ipynb`](@__NBVIEWER_ROOT_URL__/examples/transient_heat_equation.ipynb).\n#-\n#\n# ## Introduction\n#\n# In this example we extend the heat equation by a time dependent term, i.e.\n# ```math\n#  \\frac{\\partial u}{\\partial t}-\\nabla \\cdot (k \\nabla u) = f  \\quad x \\in \\Omega,\n# ```\n#\n# where $u$ is the unknown temperature field, $k$ the heat conductivity,\n# $f$ the heat source and $\\Omega$ the domain. For simplicity we set $f = 1$\n# and $k = 1$. We define homogeneous Dirichlet boundary conditions along the left and right edge of the domain.\n# ```math\n# u(x,t) = 0 \\quad x \\in \\partial \\Omega_1,\n# ```\n# where $\\partial \\Omega_1$ denotes the left and right boundary of $\\Omega$.\n#\n# Further, we define heterogeneous Dirichlet boundary conditions at the top and bottom edge $\\partial \\Omega_2$.\n# We choose a linearly increasing function $a(t)$ that describes the temperature at this boundary\n# ```math\n# u(x,t) = a(t) \\quad x \\in \\partial \\Omega_2.\n# ```\n# The semidiscrete weak form is given by\n# ```math\n# \\int_{\\Omega}\\frac{\\partial u}{\\partial t}\\cdot v \\ d\\Omega + \\int_{\\Omega} \\nabla v \\cdot \\nabla u \\ d\\Omega = \\int_{\\Omega} v \\ d\\Omega,\n# ```\n# where $v$ is a suitable test function. Now, we still need to discretize the time derivative. An implicit Euler scheme is applied,\n# which yields:\n# ```math\n# \\int_{\\Omega}u_{n+1}\\cdot v \\ d\\Omega + \\Delta t\\int_{\\Omega} \\nabla v \\cdot \\nabla u_{n+1} \\ d\\Omega = \\Delta t\\int_{\\Omega} v \\ d\\Omega + \\int_{\\Omega} u_{n}\\cdot v \\ d\\Omega.\n# ```\n# If we assemble the discrete operators, we get the following algebraic system:\n# ```math\n# \\mathbf{M} \\mathbf{u}_{n+1} + Δt \\mathbf{K} \\mathbf{u}_{n+1} = Δt \\mathbf{f} + \\mathbf{M} \\mathbf{u}_{n}\n# ```\n# In this example we apply the boundary conditions to the assembled discrete operators (mass matrix $\\mathbf{M}$ and stiffnes matrix $\\mathbf{K}$)\n# only once. We utilize the fact that in finite element computations Dirichlet conditions can be applied by\n# zero out rows and columns that correspond\n# to a prescribed dof in the system matrix ($\\mathbf{A} = Δt \\mathbf{K} + \\mathbf{M}$) and setting the value of the right-hand side vector to the value\n# of the Dirichlet condition. Thus, we only need to apply in every time step the Dirichlet condition to the right-hand side of the problem.\n#-\n# ## Commented Program\n#\n# Now we solve the problem in Ferrite. What follows is a program spliced with comments.\n#md # The full program, without comments, can be found in the next [section](@ref heat_equation-plain-program).\n#\n# First we load Ferrite, and some other packages we need.\nusing Ferrite, SparseArrays\n# We create the same grid as in the heat equation example.\ngrid = generate_grid(Quadrilateral, (100, 100));\n\n# ### Trial and test functions\n# Again, we define the structs that are responsible for the `shape_value` and `shape_gradient` evaluation.\ndim = 2\nip = Lagrange{dim, RefCube, 1}()\nqr = QuadratureRule{dim, RefCube}(2)\ncellvalues = CellScalarValues(qr, ip);\n\n# ### Degrees of freedom\n# After this, we can define the `DofHandler` and distribute the DOFs of the problem.\ndh = DofHandler(grid)\npush!(dh, :u, 1)\nclose!(dh);\n\n# By means of the `DofHandler` we can allocate the needed `SparseMatrixCSC`.\n# `M` refers here to the so called mass matrix, which always occurs in time related terms, i.e.\n# ```math\n# M_{ij} = \\int_{\\Omega} u_i \\cdot v_j \\ d\\Omega,\n# ```\n# where $u_i$ and $v_j$ are trial and test functions, respectively.\nK = create_sparsity_pattern(dh);\nM = create_sparsity_pattern(dh);\n# We also preallocate the right hand side\nf = zeros(ndofs(dh));\n\n# ### Boundary conditions\n# In order to define the time dependent problem, we need some end time `T` and something that describes\n# the linearly increasing Dirichlet boundary condition on $\\partial \\Omega_2$.\nmax_temp = 100\nΔt = 1\nT = 200\nch = ConstraintHandler(dh);\n\n# Here, we define the boundary condition related to $\\partial \\Omega_1$.\n∂Ω₁ = union(getfaceset.((grid, ), [\"left\", \"right\"])...)\ndbc = Dirichlet(:u, ∂Ω₁, (x, t) -> 0)\nadd!(ch, dbc);\n# While the next code block corresponds to the linearly increasing temperature description on $\\partial \\Omega_2$.\n∂Ω₂ = union(getfaceset.((grid, ), [\"top\", \"bottom\"])...)\ndbc = Dirichlet(:u, ∂Ω₂, (x, t) -> t*(max_temp/T))\nadd!(ch, dbc)\nclose!(ch)\nupdate!(ch, 0.0);\n\n# ### Assembling the linear system\n# As in the heat equation example we define a `doassemble!` function that assembles the diffusion parts of the equation:\nfunction doassemble_K!(K::SparseMatrixCSC, f::Vector, cellvalues::CellScalarValues{dim}, dh::DofHandler) where {dim}\n\n    n_basefuncs = getnbasefunctions(cellvalues)\n    Ke = zeros(n_basefuncs, n_basefuncs)\n    fe = zeros(n_basefuncs)\n\n    assembler = start_assemble(K, f)\n\n    @inbounds for cell in CellIterator(dh)\n\n        fill!(Ke, 0)\n        fill!(fe, 0)\n\n        reinit!(cellvalues, cell)\n\n        for q_point in 1:getnquadpoints(cellvalues)\n            dΩ = getdetJdV(cellvalues, q_point)\n\n            for i in 1:n_basefuncs\n                v  = shape_value(cellvalues, q_point, i)\n                ∇v = shape_gradient(cellvalues, q_point, i)\n                fe[i] += v * dΩ\n                for j in 1:n_basefuncs\n                    ∇u = shape_gradient(cellvalues, q_point, j)\n                    Ke[i, j] += (∇v ⋅ ∇u) * dΩ\n                end\n            end\n        end\n\n        assemble!(assembler, celldofs(cell), fe, Ke)\n    end\n    return K, f\nend\n#md nothing # hide\n# In addition to the diffusive part, we also need a function that assembles the mass matrix `M`.\nfunction doassemble_M!(M::SparseMatrixCSC, cellvalues::CellScalarValues{dim}, dh::DofHandler) where {dim}\n\n    n_basefuncs = getnbasefunctions(cellvalues)\n    Me = zeros(n_basefuncs, n_basefuncs)\n\n    assembler = start_assemble(M)\n\n    @inbounds for cell in CellIterator(dh)\n\n        fill!(Me, 0)\n\n        reinit!(cellvalues, cell)\n\n        for q_point in 1:getnquadpoints(cellvalues)\n            dΩ = getdetJdV(cellvalues, q_point)\n\n            for i in 1:n_basefuncs\n                v  = shape_value(cellvalues, q_point, i)\n                for j in 1:n_basefuncs\n                    u = shape_value(cellvalues, q_point, j)\n                    Me[i, j] += (v ⋅ u) * dΩ\n                end\n            end\n        end\n\n        assemble!(assembler, celldofs(cell), Me)\n    end\n    return M\nend\n#md nothing # hide\n# ### Solution of the system\n# We first assemble all parts in the prior allocated `SparseMatrixCSC`.\nK, f = doassemble_K!(K, f, cellvalues, dh)\nM = doassemble_M!(M, cellvalues, dh)\nA = (Δt .* K) + M;\n# Now, we need to save all boundary condition related values of the unaltered system matrix `A`, which is done\n# by `get_rhs_data`. The function returns a `RHSData` struct, which contains all needed informations to apply\n# the boundary conditions solely on the right-hand-side vector of the problem.\nrhsdata = get_rhs_data(ch, A);\n# We set the initial time step, denoted by uₙ,  to $\\mathbf{0}$.\nuₙ = zeros(length(f));\n# Here, we apply **once** the boundary conditions to the system matrix `A`.\napply!(A, ch);\n\n# To store the solution, we initialize a `paraview_collection` (.pvd) file.\npvd = paraview_collection(\"transient-heat.pvd\");\n\n# At this point everything is set up and we can finally approach the time loop.\nfor t in 0:Δt:T\n    #First of all, we need to update the Dirichlet boundary condition values.\n    update!(ch, t)\n\n    #Secondly, we compute the right-hand-side of the problem.\n    b = Δt .* f .+ M * uₙ\n    #Then, we can apply the boundary conditions of the current time step.\n    apply_rhs!(rhsdata, b, ch)\n\n    #Finally, we can solve the time step and save the solution afterwards.\n    u = A \\ b;\n\n    vtk_grid(\"transient-heat-$t\", dh) do vtk\n        vtk_point_data(vtk, dh, u)\n        vtk_save(vtk)\n        pvd[t] = vtk\n    end\n   #At the end of the time loop, we set the previous solution to the current one and go to the next time step.\n   uₙ .= u\nend\n# In order to use the .pvd file we need to store it to the disk, which is done by:\nvtk_save(pvd);\n\n#md # ## [Plain program](@id transient_heat_equation-plain-program)\n#md #\n#md # Here follows a version of the program without any comments.\n#md # The file is also available here:\n#md # [`transient_heat_equation.jl`](transient_heat_equation.jl).\n#md #\n#md # ```julia\n#md # @__CODE__\n#md # ```\n", "meta": {"hexsha": "eecb94c6bcdc16150aa46202f7e720d28d1bc78d", "size": 8653, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/literate/transient_heat_equation.jl", "max_stars_repo_name": "cfgarciar/Ferrite.jl", "max_stars_repo_head_hexsha": "e36a48f253c67201e51d1dc82e3a6b83ddbf9429", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/src/literate/transient_heat_equation.jl", "max_issues_repo_name": "cfgarciar/Ferrite.jl", "max_issues_repo_head_hexsha": "e36a48f253c67201e51d1dc82e3a6b83ddbf9429", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/src/literate/transient_heat_equation.jl", "max_forks_repo_name": "cfgarciar/Ferrite.jl", "max_forks_repo_head_hexsha": "e36a48f253c67201e51d1dc82e3a6b83ddbf9429", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6294642857, "max_line_length": 179, "alphanum_fraction": 0.6750260025, "num_tokens": 2506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7729871960839315}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.21\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ b425dc3c-89aa-11eb-29f0-271d5d515fb2\nusing IterTools: product\n\n# ╔═╡ e80d9c13-4601-46b8-a6fe-6fc4cfddd31d\nusing Yao\n\n# ╔═╡ 2f7f49f4-89b3-11eb-3bc3-ebc27d833a26\nusing LinearAlgebra: I\n\n# ╔═╡ 1a3b87dd-b03e-44c9-8cac-906da4327396\nmd\"\"\"\nThe concepts to be introduced in this notebook, such as the Ising model, simulated annealing, and the transverse Ising model, play an important role in today's quantum algorithms and quantum computing paradigms, including quantum annealing, the quantum approximate optimization algorithm, and quantum-enhanced sampling. Here we give some insight on how these physical building blocks work.\n\n# The Ising model\n\nWe would like to make a connection between the computational hardness of a problem and how difficult it is to solve a corresponding physical system. The Ising model is the most basic model to do this. It is an extensively studied model and one of the most basic examples to teach statistical mechanics and phase transitions, but we only require an elementary understanding of it.\n\nImagine that you have two magnets fixed on the same axis.\n\"\"\"\n\n# ╔═╡ b3d03fd8-89a6-11eb-31c3-d77d45414e64\nbegin \n\timport PlutoUI\n\tPlutoUI.LocalResource(\"../figures/two_magnets.svg\", :width => 200, :alt => \"Two magnets\")\nend\n\n# ╔═╡ 31807b64-89a7-11eb-1957-9fd9c5e60f41\nmd\"\"\"\nThey will naturally anti-align: one will have north pole facing up, the second the south pole facing up. We can think of them as two binary variables, $\\sigma_1$ and $\\sigma_2$. Say, if the north pole is facing up, we assign the value +1 to the variable, and -1 otherwise. To abstract away from magnets, in general, we call these variables spins. So in the optimal configuration, their product is -1:\n\n`` \\sigma_1\\sigma_2=-1 ``\n\nWe can think of this as the energy of the system: the lowest energy is called the ground state energy. Note that there are two physical configurations corresponding to this optimum: $\\sigma_1=+1, \\sigma_2=-1$, and $\\sigma_1=-1, \\sigma_2=+1$.\n\nIf we keep adding more magnets to this system, we can sum up their pairwise interaction to get the total energy. The total energy of the system is called the Hamiltonian, and we will denote it by $H$. So if we have $N$ magnets arranged along a straight line, we have\n\n`` H=\\sum_{i=1}^{N-1} \\sigma_i \\sigma_{i+1}``.\n\nWe did a simplification here: we assumed that remote magnets do not interact with each other (e.g. there is no such term as $\\sigma_i\\sigma_{i+2}$. In general, the interactions modeled depend on the layout of the spins and assumptions about the physical model: there will be some graph describing the connectivity of interactions. To reflect this, we write\n\n`` H=\\sum_{<i,j>} \\sigma_i \\sigma_{j}``,\n\nwhere $<i,j>$ typically means nearest neighbours, but it is up to us to declare what nearest neighbours mean.\n\nNow imagine that the distance is not the same between each pair. In other words, some pairs interact more than others. We can express this by adding a parameter that describes the interaction strength:\n\n`` H=-\\sum_{<i,j>} J_{ij} \\sigma_i \\sigma_{j}``,\n\nwhere $J_{ij}$ is a real number. We added a negative sign to the Hamiltonian: this is by convention. If the spins are antiferromagnetic, that is, they behave as we would expect from magnets, then all $J_{ij}$ values would be negative. That cancels out the negative sign of the sum, so we still expect that each product $\\sigma_i\\sigma_j$ would give you -1 in the optimum configuration.\n\nThe model is fairly complicated by this point. Imagine that you have many spins and not all of them behave like magnets (that is, $J_{ij}$ can take both negative and positive values for different pairs). Nature still wants to find the lowest energy configuration, though. Let's take a look at how we would do it in code. Let's calculate the energy of spins on a line, given some couplings and a spin configuration:\n\"\"\"\n\n# ╔═╡ ca4a2698-7d5f-4480-9e6e-6bc4dd3f8a3a\ncalculate_energy(J, σ) = -sum(J_ij*σ[i]*σ[i+1] for (i,J_ij) in enumerate(J))\n\n# ╔═╡ 0aff9cab-8f0d-42ee-ab52-cc96b0a05895\nmd\"\"\"\nLet's give it a fixed set of couplings and a spin configuration on three sites:\n\"\"\"\n\n# ╔═╡ b84763a1-996a-4d50-ab7d-8126d758ce4b\nbegin\n\tJ = [1.0, -1.0]\n\tσ = [+1, -1, +1]\nend\n\n# ╔═╡ d6241dd0-0540-40c9-8d7d-8554c182a1c0\nmd\"\"\"\nThe energy of this is\n\"\"\"\n\n# ╔═╡ 7972486c-eb23-461d-8998-ccb5474049f5\ncalculate_energy(J, σ)\n\n# ╔═╡ f2133911-8380-47a1-823f-49f5425f5f15\nmd\"\"\"\nIs this the ground state? How do we know? We are interested in the minimum, but we cannot use some gradient-based method to find it, since the variables are binary, plus the optimization landscape is nonconvex. So the easiest choice is an exhaustive search of all possibilities:\n\"\"\"\n\n# ╔═╡ bc02c9c9-3fc1-486e-b837-e6e3113f4069\nlet\n\tt = r =[]\n\tfor σ in collect(product([+1,-1], [+1, -1], [+1, -1]))\n\t    t = [t;calculate_energy(J, σ)]\n\t\tr = [r; [i for i in σ]]\n\tend\n\t(t,r) = hcat(t), reshape(r, 8,3)\nend\n\n# ╔═╡ 6b89bdf8-7c27-4a87-8375-3e80aa4a2bdd\nmd\"\"\"\nWe see that -2 is the optimum, with two optimal configurations, but we had to enumerate all possibilities to figure this out. For this particular case, there are more clever ways to find the best solution, but in the general case, this is not the case.\n\nTo get to the general case, we need one more component, an external field. Imagine that you add a large magnet below each and every one of our magnets, creating an external magnetic field for each site. If this field is strong enough, it can override the pairwise interaction and flip the magnets. We model this by adding a linear term to the Hamiltonian:\n\n`` H=-\\sum_{<i,j>} J_{ij} \\sigma_i \\sigma_{j} - \\sum_i h_i \\sigma_i``,\n\nwhere $h_i$ is the strength of the external field. This is the full description of the *classical Ising model*. The Hamiltonian describes the energy, but in computer science language, it means it expresses the objective function we want to minimize. The corresponding computer science problem is called quadratic unconstrained binary optimization (QUBO), where the only difference is that the variables take values in $\\{0, 1\\}$, but that is only a constant shift. QUBOs are NP-hard in general, that is, we are not aware of an efficient polynomial time algorithm to solve any given QUBO. So the generic strategy is the exhaustive search we did above, which takes exponentially many steps in the number of sites (variables).\n\nAs we mentioned, nature seeks the minimum energy configuration. So how does computational hardness map to physical difficulty? Imagine that the energy difference between the ground state and the next lowest energy state (also called the first excited state) is small, but the energetic cost of going from one to the other is high. A cartoon picture of this is the following:\n\"\"\"\n\n# ╔═╡ 41dd7fe8-89ac-11eb-3b00-a5df2682ae75\nPlutoUI.LocalResource(\"../figures/energy_landscape.svg\", :width => 300, :alt => \"Energy Landscape\")\n\n# ╔═╡ 6e79b61e-89ac-11eb-238e-d5a2f77d0008\nmd\"\"\"\nIf we start from a random configuration, we might get stuck in the local optimum denoted by the green spot. This is what happens in metals if they are cooled down too quickly: the crystal lattice will have imperfections and the metal will not have the desired properties. A process called *annealing* helps in metallurgy: by increasing the temperature, the chance of overcoming the potential barrier increases and the crystal structure can reconfigure itself. If the barrier is high and the energy difference is small between the ground state and the first excited state, the probability of this happening drops. This is what it means that the problem is difficult to do in a physical system.\n\nAnnealing inspired a heuristic algorithm called *simulated annealing*. This defines a temperature to be able to hop out of local minima. The temperature is lowered over time to find the actual minimum. Simulated annealing has many implementations. Here we'll use the one implemented in dimod to solve our problem above:\n\"\"\"\n\n# ╔═╡ 54f1adc8-ef80-4801-86f5-835b1d499336\nimport dimod\n\n# ╔═╡ 3adf3d6f-1d41-464c-a3d1-8558478600f3\nmd\"\"\"\nThe simulated annealing solver requires us to define the couplings as a dictionary between spins, and we must also pass the external field values as a dictionary. The latter is all zeros for us.\n\"\"\"\n\n# ╔═╡ 4405ace5-a383-4810-81b4-cae1fcb2222c\nJ = {(0, 1): 1.0, (1, 2): -1.0}\nh = {0:0, 1:0, 2:0}\n\n# ╔═╡ 5efc75f4-3de1-4b0e-b9f4-87e74cda9103\nmd\"\"\"\nWe instantiate an Ising model:\n\"\"\"\n\n# ╔═╡ 0ce517fd-1989-400a-bfe7-77ce043a7ac2\nmodel = dimod.BinaryQuadraticModel(h, J, 0.0, dimod.SPIN)\n\n# ╔═╡ 536f1777-09e3-48de-82a5-0058dc921b95\nmd\"\"\"\nFinally, we create a simulated annealing sampler that pulls out potentially optimal solutions, and we read out 10 possible solutions:\n\"\"\"\n\n# ╔═╡ ee4c6fd4-7082-4a74-bcd5-9a101e6fb1e3\nsampler = dimod.SimulatedAnnealingSampler()\nresponse = sampler.sample(model, num_reads=10)\n\n# ╔═╡ b9f62b85-8648-4c96-b571-69fe67ab4ccd\nmd\"\"\"\nYou can see that this configuration is actually easy, since you get the optimal solution -2 most of the time:\n\"\"\"\n\n# ╔═╡ cedb40a8-91b8-40e3-a37d-2e2da894dddc\n[solution.energy for solution in response.data()].count(-2)\n\n# ╔═╡ c0a1d5c7-7e97-4eb9-b423-543132776439\nmd\"\"\"\nSimulated annealing is a classical heuristic algorithm. Quantum annealing uses physical effects to find the global optimum of an Ising model: it uses thermal effects just like annealing in metallurgy, but it also uses quantum effects like tunneling to overcome potential barriers.\n\nThe Ising model also plays an important role in quantum-enhanced sampling, but that idea requires a better understanding of the role of temperature, which we will revisit in a subsequent notebook.\n\"\"\"\n\n# ╔═╡ f0398f32-79da-4c74-b3f3-40f47d4a18f5\nmd\"\"\"\n# The transverse-field Ising model\n\"\"\"\n\n# ╔═╡ 55ff9df7-574b-4963-992b-7905e2c24331\nmd\"\"\"\nWe discussed the Hamiltonian of the classical Ising model. We can write the same Hamiltonian in a quantum mechanical form. In quantum mechanics, the Hamiltonian is not a function of variables, but of operators. We will simulate what it means in a quantum circuit.\n\"\"\"\n\n# ╔═╡ 51f0a505-6608-435d-b28c-7ab2d2398e0a\nmd\"\"\"\nThe operator that replicates the effect of what we have seen in the classical case is the Pauli-Z matrix, defined as $\\begin{bmatrix}1 & 0\\\\ 0& -1\\end{bmatrix}$. Let's see what it does on the elements of the computational basis:\n\"\"\"\n\n# ╔═╡ 5cc78f38-5061-4212-b9dc-a2d740caf65f\nlet\n\tq = zero_state(1)\n\tstate(q |> put(1, 1=>Z))\nend\n\n# ╔═╡ 529cba9b-cc11-4e20-b9a5-2eb432236ff2\nmd\"\"\"\nThis is nothing but the $|0\\rangle$ state. In other words, it does not do anything to $|0\\rangle$, which can also be thought of as multiplying it by +1. Let's try it on $|1\\rangle$:\n\"\"\"\n\n# ╔═╡ d311efdc-8ea4-4579-950b-114d17d1b6ea\nlet\n\tq = zero_state(1)\n\tstate(q |> chain(1, put(1=>X), put(1=>Z)))\nend\n\n# ╔═╡ a5c79e07-f541-4910-9bea-7553b7d4374c\nmd\"\"\"\nWe get $-|1\\rangle$, which means it adds a minus sign to it. This way we have the +1, -1 values, just the same way as in the classical formalism. If we write $\\sigma^Z_i$ for the operator $Z$ at a site $i$, the quantum mechanical Hamiltonian of the classical Ising model reads as\n\n`` H=-\\sum_{<i,j>} J_{ij} \\sigma^Z_i \\sigma^Z_{j} - \\sum_i h_i \\sigma^Z_i``.\n\nTechnically speaking, we should put a hat on $H$ and on all of the $\\sigma^Z_i$ to indicate that they are operators, and not numbers or variables, but we omit this for notational simplicity.\n\nThe expectation value $<H>$ of the Hamiltonian is the energy of the system, and the corresponding quantum state $|\\psi\\rangle$ is the configuration of that energy level. We can create the quantum mechanical version of calculating the energy, matching the function we defined above for the classical mechanical variant:\n\"\"\"\n\n# ╔═╡ cb9c2854-2050-4767-9f2c-9499062f5539\ncalculate_energy_expectation(state, hamiltonian) = Float64(real(conj(state'ᵀ) * hamiltonian * state))\n\n# ╔═╡ 39a8fa28-4750-496b-8f80-feb34f0fa876\nmd\"\"\"\nIt is a bit tricky to define the Hamiltonian with the $\\sigma^Z_i$ operators, since saying that it acts on site $i$ means that it acts trivially on all other sites. So, for instance, for two sites, if we act on site one, the actual operator is $\\sigma^Z\\otimes I$, and acting on site two, we have $I \\otimes \\sigma^Z$. The above function to calculate the energy takes numpy arrays, so we manually define $\\sigma^Z$ and calculate the energy of the Hamiltonian $H=-\\sigma^Z_1\\sigma^Z_2  - 0.5 (\\sigma^Z_1 + \\sigma^Z_2)$ on the state $|00\\rangle$.\n\"\"\"\n\n# ╔═╡ 7b1acb49-4ea6-4b7e-9982-4c64a8cdd54f\nbegin\n\tPauliZ = [1 0; 0 -1]\n\tIZ = kron(Matrix(I, 2, 2), PauliZ)\n\tZI = kron(PauliZ, Matrix(I, 2, 2))\n\tZZ = kron(PauliZ, PauliZ)\n\tH = -ZZ + -0.5*(ZI+IZ)\n\tψ = kron([1, 0], [1, 0])\n\tcalculate_energy_expectation(ψ, H)\nend\n\n# ╔═╡ 132f9367-fabe-477e-a3f2-63d65b1cc1ae\nmd\"\"\"\nThis Hamiltonian commutes, which means all of its operators are commutative, which is a clear sign of nothing much quantum going on.\n\nTo make this a quantum Ising model, we need to add a term that does not commute with the rest of the terms. A transverse field is such, which is an on-site interaction just like the external field. Its effect is described by the Pauli-X operator (the NOT gate), which we will denote by $\\sigma^X_i$ for a site $i$. It is very easy to see that the Pauli-Z and the Pauli-X do not commute:\n\"\"\"\n\n# ╔═╡ de97610f-33a2-4cae-a5b5-b3a0f56fa3dc\nlet\n\tq = zero_state(1)\n\tmd\"Pauli-X, then Pauli-Z:\", state(q |> chain(1, put(1=>X), put(1=>Z)))\nend\n\n# ╔═╡ bc5307be-89b3-11eb-0083-11121b2d595e\nlet\n\tq = zero_state(1)\n\tmd\"Pauli-Z, then Pauli-X:\", state(q |> chain(1, put(1=>Z), put(1=>X)))\nend\n\n# ╔═╡ c1920c45-c30b-40fb-9abc-58c5e176d891\nmd\"\"\"\nThere is a clear sign difference.\n\nThere are many other ways of making the Ising Hamiltonian noncommuting, but adding the onsite Pauli-X operations leads to the *transverse field Ising model*. Its Hamiltonian reads as\n\n`` H=-\\sum_{<i,j>} J_{ij} \\sigma^Z_i \\sigma^Z_{j} - \\sum_i h_i \\sigma^Z_i - \\sum_i g_i \\sigma^X_i``.\n\nThe transverse field Ising model is critically important to explain how quantum annealing works because by adding the $\\sigma^X$ part to the Hamiltonian it becomes possible to exploit quantum effects like tunnelling. It is also important for understanding the quantum approximation optimization algorithms, since it was inspired by quantum annealing.\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─1a3b87dd-b03e-44c9-8cac-906da4327396\n# ╟─b3d03fd8-89a6-11eb-31c3-d77d45414e64\n# ╟─31807b64-89a7-11eb-1957-9fd9c5e60f41\n# ╠═ca4a2698-7d5f-4480-9e6e-6bc4dd3f8a3a\n# ╟─0aff9cab-8f0d-42ee-ab52-cc96b0a05895\n# ╠═b84763a1-996a-4d50-ab7d-8126d758ce4b\n# ╟─d6241dd0-0540-40c9-8d7d-8554c182a1c0\n# ╠═7972486c-eb23-461d-8998-ccb5474049f5\n# ╟─f2133911-8380-47a1-823f-49f5425f5f15\n# ╠═b425dc3c-89aa-11eb-29f0-271d5d515fb2\n# ╠═bc02c9c9-3fc1-486e-b837-e6e3113f4069\n# ╟─6b89bdf8-7c27-4a87-8375-3e80aa4a2bdd\n# ╟─41dd7fe8-89ac-11eb-3b00-a5df2682ae75\n# ╟─6e79b61e-89ac-11eb-238e-d5a2f77d0008\n# ╠═54f1adc8-ef80-4801-86f5-835b1d499336\n# ╟─3adf3d6f-1d41-464c-a3d1-8558478600f3\n# ╠═4405ace5-a383-4810-81b4-cae1fcb2222c\n# ╟─5efc75f4-3de1-4b0e-b9f4-87e74cda9103\n# ╠═0ce517fd-1989-400a-bfe7-77ce043a7ac2\n# ╟─536f1777-09e3-48de-82a5-0058dc921b95\n# ╠═ee4c6fd4-7082-4a74-bcd5-9a101e6fb1e3\n# ╟─b9f62b85-8648-4c96-b571-69fe67ab4ccd\n# ╠═cedb40a8-91b8-40e3-a37d-2e2da894dddc\n# ╟─c0a1d5c7-7e97-4eb9-b423-543132776439\n# ╟─f0398f32-79da-4c74-b3f3-40f47d4a18f5\n# ╟─55ff9df7-574b-4963-992b-7905e2c24331\n# ╠═e80d9c13-4601-46b8-a6fe-6fc4cfddd31d\n# ╟─51f0a505-6608-435d-b28c-7ab2d2398e0a\n# ╠═5cc78f38-5061-4212-b9dc-a2d740caf65f\n# ╟─529cba9b-cc11-4e20-b9a5-2eb432236ff2\n# ╠═d311efdc-8ea4-4579-950b-114d17d1b6ea\n# ╟─a5c79e07-f541-4910-9bea-7553b7d4374c\n# ╠═cb9c2854-2050-4767-9f2c-9499062f5539\n# ╟─39a8fa28-4750-496b-8f80-feb34f0fa876\n# ╠═2f7f49f4-89b3-11eb-3bc3-ebc27d833a26\n# ╠═7b1acb49-4ea6-4b7e-9982-4c64a8cdd54f\n# ╟─132f9367-fabe-477e-a3f2-63d65b1cc1ae\n# ╠═de97610f-33a2-4cae-a5b5-b3a0f56fa3dc\n# ╠═bc5307be-89b3-11eb-0083-11121b2d595e\n# ╟─c1920c45-c30b-40fb-9abc-58c5e176d891\n", "meta": {"hexsha": "f3c937a8d8f55fd9be1183b36587e017d866789f", "size": 16057, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia_yao_version/04_Classical_and_Quantum_Many-Body_Physics.jl", "max_stars_repo_name": "VarLad/qml-mooc", "max_stars_repo_head_hexsha": "1ece1b7736a95abc4d138644cfba1354a81b6e0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia_yao_version/04_Classical_and_Quantum_Many-Body_Physics.jl", "max_issues_repo_name": "VarLad/qml-mooc", "max_issues_repo_head_hexsha": "1ece1b7736a95abc4d138644cfba1354a81b6e0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia_yao_version/04_Classical_and_Quantum_Many-Body_Physics.jl", "max_forks_repo_name": "VarLad/qml-mooc", "max_forks_repo_head_hexsha": "1ece1b7736a95abc4d138644cfba1354a81b6e0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.063973064, "max_line_length": 723, "alphanum_fraction": 0.7538145357, "num_tokens": 5543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.772987187972971}}
{"text": "# A geometric graph is one in which vertices are mapped to points and\n# two vertices are adjacent if the distance between them is at most 1\n# (or a set value).\n\nexport GeometricGraph, RandomGeometricGraph\n\n\"\"\"\n`GeometricGraph(A)` where `A` is an `m` by `n` matrix creates a\ngeometric graph in which the columns of `A` are the points\nrepresenting the vertices `1:n`. Two vertices are adjacent iff the\ndistance between the points is at most `1` (or an optional second\nparameter, `d`).\n\"\"\"\nfunction GeometricGraph(A::Array{T,2}, d::Real = 1) where {T<:Real}\n    r, n = size(A)\n    G = IntGraph(n)\n    dd::T = d * d\n\n    for i = 1:n-1\n        vi = A[:, i]\n        for j = i+1:n\n            vj = A[:, j]\n            dv = vi - vj\n            if dot(dv, dv) <= dd\n                add!(G, i, j)\n            end\n        end\n    end\n    return G\nend\n\n\"\"\"\n`GeometricGraph(f)` where `f` is a `Dict` mapping vertex names to\nvectors creates a geometric graph in which two vertices are adjacent\niff distance between their points is at most `1` (or `d` if given as a\nsecond argument).\n\"\"\"\nfunction GeometricGraph(f::Dict{S,Vector{T}}, d::Real = 1) where {S,T<:Real}\n    G = SimpleGraph{S}()\n    vtcs = collect(keys(f))\n    for v in vtcs\n        add!(G, v)\n    end\n\n    dd = d * d\n    n = length(vtcs)\n    for i = 1:n-1\n        vi = f[vlist[i]]\n        for j = i+1:n\n            vj = f[vlist[j]]\n            dv = vi - vj\n            if dot(dv, dv) <= dd\n                add!(G, vlist[i], vlist[j])\n            end\n        end\n    end\n    return G\nend\n\n\"\"\"\n`RandomGeometricGraph(n::Int, dim::Int=2, d::Real=1)` creates a random\ngeometric graph by generating `n` points at random in the unit\n`dim`-cube. Vertices are adjacent if their corresponding points are at\ndistance at most `d`.\n\"\"\"\nfunction RandomGeometricGraph(n::Int, dim::Int = 2, d::Real = 1)\n    return GeometricGraph(rand(dim, n), d)\nend\n", "meta": {"hexsha": "4b66f45aa50ab050fd35ffa228dc4ca0970c8f0c", "size": 1882, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GeometricGraphs.jl", "max_stars_repo_name": "scheinerman/SimpleGraphRepresentations.jl", "max_stars_repo_head_hexsha": "815367c0a545ef60e49f8b26944770f50b42a407", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GeometricGraphs.jl", "max_issues_repo_name": "scheinerman/SimpleGraphRepresentations.jl", "max_issues_repo_head_hexsha": "815367c0a545ef60e49f8b26944770f50b42a407", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GeometricGraphs.jl", "max_forks_repo_name": "scheinerman/SimpleGraphRepresentations.jl", "max_forks_repo_head_hexsha": "815367c0a545ef60e49f8b26944770f50b42a407", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:13:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T01:13:04.000Z", "avg_line_length": 27.2753623188, "max_line_length": 76, "alphanum_fraction": 0.5924548353, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7729871875430079}}
{"text": "using Roots\n\n# Given\nP = 170000\nF = 813000\nn = 15\n\n# find i\ni = (F / P)^(1/n) - 1\n\n@assert isapprox(F, P * (1 + i)^n; atol=0.01)\n", "meta": {"hexsha": "d8d7fe1e0e7748a144e53fb2d1a94c84d8624a83", "size": 129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps2/p2.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/ps2/p2.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/ps2/p2.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 10.75, "max_line_length": 45, "alphanum_fraction": 0.5348837209, "num_tokens": 63, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9481545348152283, "lm_q2_score": 0.8152324983301567, "lm_q1q2_score": 0.7729663902204861}}
{"text": "#=\nA perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.\n\nA number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.\n\nAs 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.\n\nFind the sum of all the positive integers which cannot be written as the sum of two abundant numbers.\n=#\n\nfunction sum_proper_divisors(n)\n  prod = 1\n  k = 2\n  while k*k <= n\n    p = 1\n    while n%k==0\n      p=p*k+1\n      n = div(n,k)\n    end\n    prod*=p\n    k += 1\n  end\n  if n>1\n    prod*=1+n\n  end\n  prod\nend\n\nfunction abundant_numbers_less_than(n)\n  arr = Int64[]\n  for i in 1:n-1\n    if sum_proper_divisors(i) > i+i\n      push!(arr, i)\n    end\n  end\n  arr\nend\n\nfunction calc(n)\n  abundant_nums = abundant_numbers_less_than(n)\n  canbewrittenasabundant = Bool[false for x in 1:n]\n  for i in 1:length(abundant_nums)\n    for j in 1:length(abundant_nums)\n      if abundant_nums[i] + abundant_nums[j] <= n\n        canbewrittenasabundant[abundant_nums[i]+abundant_nums[j]] = true\n      else\n        break\n      end\n    end\n  end\n\n  total = 0\n  for i in 1:n\n    total += canbewrittenasabundant[i] ? 0 : i\n  end\n  total\nend\n@time println(calc(28_124))\n", "meta": {"hexsha": "a100678cde7e4c29dc7ce418586330408f796ff4", "size": 1786, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p23.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p23.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p23.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 30.2711864407, "max_line_length": 476, "alphanum_fraction": 0.6926091825, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7729467315501186}}
{"text": "\"\"\"\n    mae(ŷ, y; agg=mean)\n\nReturn the loss corresponding to mean absolute error: \n\n    agg(abs.(ŷ .- y))\n\"\"\"\nmae(ŷ, y; agg=mean) = agg(abs.(ŷ .- y))\n\n\"\"\"\n    mse(ŷ, y; agg=mean)\n\nReturn the loss corresponding to mean square error: \n    \n    agg((ŷ .- y).^2)\n\"\"\"\nmse(ŷ, y; agg=mean) = agg((ŷ .- y).^2)\n\n\"\"\"\n    msle(ŷ, y; agg=mean, ϵ=eps(ŷ))\n\nThe loss corresponding to mean squared logarithmic errors, calculated as\n\n    agg((log.(ŷ .+ ϵ) .- log.(y .+ ϵ)).^2)\n\nThe `ϵ` term provides numerical stability.\nPenalizes an under-estimation more than an over-estimatation.\n\"\"\"\nmsle(ŷ, y; agg=mean, ϵ=epseltype(ŷ)) = agg((log.((ŷ .+ ϵ) ./ (y .+ ϵ))).^2)\n\n\"\"\"\n    huber_loss(ŷ, y; δ=1, agg=mean)\n\nReturn the mean of the [Huber loss](https://en.wikipedia.org/wiki/Huber_loss)\ngiven the prediction `ŷ` and true values `y`.\n\n                 | 0.5 * |ŷ - y|,            for |ŷ - y| <= δ\n    Huber loss = |\n                 |  δ * (|ŷ - y| - 0.5 * δ), otherwise\n\"\"\"\nfunction huber_loss(ŷ, y; agg=mean, δ=ofeltype(ŷ, 1))\n   abs_error = abs.(ŷ .- y)\n   #TODO: remove dropgrad when Zygote can handle this function with CuArrays\n   temp = Zygote.dropgrad(abs_error .<  δ)\n   x = ofeltype(ŷ, 0.5)\n   agg(((abs_error.^2) .* temp) .* x .+ δ*(abs_error .- x*δ) .* (1 .- temp))\nend\n\n\"\"\"\n    crossentropy(ŷ, y; dims=1, ϵ=eps(ŷ), agg=mean)\n\nReturn the cross entropy between the given probability distributions;\ncalculated as\n\n    agg(-sum(y .* log.(ŷ .+ ϵ); dims=dims))\n\nCross entropy is tipically used as a loss in multi-class classification,\nin which case the labels `y` are given in a one-hot format. \n`dims` specifies the dimension (or the dimensions) containing the class probabilities.\nThe prediction `ŷ` is supposed to sum to one across `dims`,\nas would be the case with the output of a [`softmax`](@ref) operation. \n\nUse of [`logitcrossentropy`](@ref) is recomended over `crossentropy` for \nnumerical stability.\n\nSee also: [`Flux.logitcrossentropy`](@ref), [`Flux.bce_loss`](@ref), [`Flux.logitbce_loss`](@ref)\n\"\"\"\nfunction crossentropy(ŷ, y; dims=1, agg=mean, ϵ=epseltype(ŷ))\n    agg(.-sum(xlogy.(y, ŷ .+ ϵ); dims=dims))\nend\n\n\"\"\"\n    logitcrossentropy(ŷ, y; dims=1, ϵ=eps(ŷ), agg=mean)\n\nReturn the crossentropy computed after a [`Flux.logsoftmax`](@ref) operation;\ncalculated as \n\n    agg(.-sum(y .* logsoftmax(ŷ; dims=dims); dims=dims))\n\n`logitcrossentropy(ŷ, y)` is mathematically equivalent to\n[`Flux.crossentropy(softmax(ŷ), y)`](@ref) but it is more numerically stable.\n\nSee also: [`Flux.crossentropy`](@ref), [`Flux.bce_loss`](@ref), [`Flux.logitbce_loss`](@ref)\n\"\"\"\nfunction logitcrossentropy(ŷ, y; dims=1, agg=mean)\n    agg(.-sum(y .* logsoftmax(ŷ; dims=dims); dims=dims))\nend\n\n\"\"\"\n    bce_loss(ŷ, y; agg=mean, ϵ=eps(ŷ))\n\nReturn the binary cross-entropy loss, computer as \n\n    agg(@.(-y*log(ŷ + ϵ) - (1-y)*log(1-ŷ + ϵ)))\n    \nThe `ϵ` term provides numerical stability.\n\nTypically, the prediction `ŷ` is given by the output of a [`sigmoid`](@ref) activation.\n\nUse of `logitbce_loss` is recomended over `bce_loss` for numerical stability.\n\nSee also: [`Flux.crossentropy`](@ref), [`Flux.logitcrossentropy`](@ref), [`Flux.logitbce_loss`](@ref)\n\"\"\"\nfunction bce_loss(ŷ, y; agg=mean, ϵ=epseltype(ŷ))\n    agg(@.(-xlogy(y, ŷ+ϵ) - xlogy(1-y, 1-ŷ+ϵ)))\nend\n# Re-definition to fix interaction with CuArrays.\n# CUDA.@cufunc bce_loss(ŷ, y; ϵ=eps(ŷ)) = -y*log(ŷ + ϵ) - (1 - y)*log(1 - ŷ + ϵ)\n\n\"\"\"\n    logitbce_loss(ŷ, y; agg=mean)\n\nMathematically equivalent to\n[`Flux.bce_loss(σ(ŷ), y)`](@ref) but is more numerically stable.\n\nSee also: [`Flux.crossentropy`](@ref), [`Flux.logitcrossentropy`](@ref), [`Flux.bce_loss`](@ref)\n```\n\"\"\"\nfunction logitbce_loss(ŷ, y; agg=mean)\n    agg(@.((1-y)*ŷ - logσ(ŷ)))\nend\n# Re-definition to fix interaction with CuArrays.\n# CUDA.@cufunc logitbce_loss(ŷ, y) = (1 - y)*ŷ - logσ(ŷ)\n\n\n\"\"\"\n    kldivergence(ŷ, y; agg=mean)\n\nReturn the\n[Kullback-Leibler divergence](https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence)\nbetween the given probability distributions.\n\nKL divergence is a measure of how much one probability distribution is different\nfrom the other.\nIt is always non-negative and zero only when both the distributions are equal\neverywhere.\n\"\"\"\nfunction kldivergence(ŷ, y; dims=1, agg=mean, ϵ=epseltype(ŷ))\n  entropy = agg(sum(xlogx.(y), dims=dims))\n  cross_entropy = crossentropy(ŷ, y; dims=dims, agg=agg, ϵ=ϵ)\n  return entropy + cross_entropy\nend\n\n\"\"\"\n    poisson_loss(ŷ, y)\n\n# Return how much the predicted distribution `ŷ` diverges from the expected Poisson\n# distribution `y`; calculated as `sum(ŷ .- y .* log.(ŷ)) / size(y, 2)`.\nREDO\n[More information.](https://peltarion.com/knowledge-center/documentation/modeling-view/build-an-ai-model/loss-functions/poisson_loss).\n\"\"\"\npoisson_loss(ŷ, y; agg=mean) = agg(ŷ .- xlogy.(y, ŷ))\n\n\"\"\"\n    hinge_loss(ŷ, y; agg=mean)\n\nReturn the [hinge_loss loss](https://en.wikipedia.org/wiki/Hinge_loss) given the\nprediction `ŷ` and true labels `y` (containing 1 or -1); calculated as\n`sum(max.(0, 1 .- ŷ .* y)) / size(y, 2)`.\n\nSee also: [`squared_hinge_loss`](@ref)\n\"\"\"\nhinge_loss(ŷ, y; agg=mean) = agg(max.(0, 1 .-  ŷ .* y))\n\n\"\"\"\n    squared_hinge_loss(ŷ, y)\n\nReturn the squared hinge_loss loss given the prediction `ŷ` and true labels `y`\n(containing 1 or -1); calculated as `sum((max.(0, 1 .- ŷ .* y)).^2) / size(y, 2)`.\n\nSee also: [`hinge_loss`](@ref)\n\"\"\"\nsquared_hinge_loss(ŷ, y; agg=mean) = agg((max.(0, 1 .- ŷ .* y)).^2)\n\n\"\"\"\n    dice_coeff_loss(ŷ, y; smooth=1)\n\nReturn a loss based on the dice coefficient.\nUsed in the [V-Net](https://arxiv.org/pdf/1606.04797v1.pdf) image segmentation\narchitecture.\nSimilar to the F1_score. Calculated as:\n\n    1 - 2*sum(|ŷ .* y| + smooth) / (sum(ŷ.^2) + sum(y.^2) + smooth)\n\"\"\"\ndice_coeff_loss(ŷ, y; smooth=ofeltype(ŷ, 1.0)) = 1 - (2*sum(y .* ŷ) + smooth) / (sum(y.^2) + sum(ŷ.^2) + smooth) #TODO agg\n\n\"\"\"\n    tversky_loss(ŷ, y; β=0.7)\n\nReturn the [Tversky loss](https://arxiv.org/pdf/1706.05721.pdf).\nUsed with imbalanced data to give more weight to false negatives.\nLarger β weigh recall more than precision (by placing more emphasis on false negatives)\nCalculated as:\n    1 - sum(|y .* ŷ| + 1) / (sum(y .* ŷ + β*(1 .- y) .* ŷ + (1 - β)*y .* (1 .- ŷ)) + 1)\n\"\"\"\nfunction tversky_loss(ŷ, y; β=ofeltype(ŷ, 0.7))\n    #TODO add agg\n    num = sum(y .* ŷ) + 1\n    den = sum(y .* ŷ + β*(1 .- y) .* ŷ + (1 - β)*y .* (1 .- ŷ)) + 1\n    1 - num / den\nend\n             \n\"\"\"\n    xlogx(x)\n\nReturn `x * log(x)` for `x ≥ 0`, handling `x = 0` by taking the downward limit.\n\"\"\"\nfunction xlogx(x)\n  result = x * log(x)\n  ifelse(iszero(x), zero(result), result)\nend\n\nCUDA.@cufunc function xlogx(x)\n  result = x * log(x)\n  ifelse(iszero(x), zero(result), result)\nend\n\n\"\"\"\n    xlogy(x, y)\n\nReturn `x * log(y)` for `y > 0` with correct limit at `x = 0`.\n\"\"\"\nfunction xlogy(x, y)\n  result = x * log(y)\n  ifelse(iszero(x), zero(result), result)\nend\n\nCUDA.@cufunc function xlogy(x, y)\n  result = x * log(y)\n  ifelse(iszero(x), zero(result), result)\nend\n\n@adjoint function broadcasted(::typeof(xlogy), x::Zygote.Numeric, y::Zygote.Numeric)\n  res = xlogy.(x, y)\n  res, Δ -> (nothing, Zygote.unbroadcast(x, xlogy.(Δ, y)), Zygote.unbroadcast(y, Δ .* x ./ y))\nend\n\n\n\"\"\"\n    flatten(x::AbstractArray)\n\nReshape arbitrarly-shaped input into a matrix-shaped output\npreserving the last dimension size. \nEquivalent to `reshape(x, :, size(x)[end])`.\n\"\"\"\nfunction flatten(x::AbstractArray)\n  return reshape(x, :, size(x)[end])\nend\n\n# TODO normalise over last dimension is typically what you want to do. \n# Deprecation path: `normalise(x; dims=1)` -> `normalise(x; dims)` -> `normalise(x; dims=size(x)[end])`  \n\"\"\"\n    normalise(x; dims, ϵ=1e-5)\n\nNormalise `x` to mean 0 and standard deviation 1 across the dimensions given by `dims`.\n`ϵ` is a small additive factor added to the denominator for numerical stability.\n\"\"\"\nfunction normalise(x::AbstractArray; dims, ϵ=ofeltype(x, 1e-5))\n  μ = mean(x, dims=dims)\n    #   σ = std(x, dims=dims, mean=μ, corrected=false) # use this when #478 gets merged\n  σ = std(x, dims=dims, corrected=false)\n  return (x .- μ) ./ (σ .+ ϵ)\nend", "meta": {"hexsha": "c6a1a5952450890ecb2fc963d52dcb6e4c18c46c", "size": 8139, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/layers/stateless.jl", "max_stars_repo_name": "aterenin/Flux.jl", "max_stars_repo_head_hexsha": "dbe75ad2b34c1a01b231a771f5dd18d0ce6b30c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/layers/stateless.jl", "max_issues_repo_name": "aterenin/Flux.jl", "max_issues_repo_head_hexsha": "dbe75ad2b34c1a01b231a771f5dd18d0ce6b30c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/layers/stateless.jl", "max_forks_repo_name": "aterenin/Flux.jl", "max_forks_repo_head_hexsha": "dbe75ad2b34c1a01b231a771f5dd18d0ce6b30c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9467680608, "max_line_length": 134, "alphanum_fraction": 0.6392677233, "num_tokens": 2835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7729420567623827}}
{"text": "module HWfuncapp\n\nusing FastGaussQuadrature # to get chebyshevnodes\n\n# you dont' have to use PyPlot. I did much of it in PyPlot, hence\n# you will see me often qualify code with `PyPlot.plot` or so.\n# using PyPlot\nimport ApproXD: getBasis, BSpline\nusing Distributions\nusing BasisMatrices\nusing LinearAlgebra, SpecialFunctions\nusing ApproxFun\nusing Plots\n\nexport q1, q2, q3, q7\n\nChebyT(x,deg) = cos(acos(x)*deg)\nunitmap(x,lb,ub) = 2 .* (x .- lb) ./ (ub .- lb) .- 1\t#[a,b] -> [-1,1]\nabmap(x,lb,ub) = 0.5 .* (ub .+ lb) .+ 0.5 .* (ub .- lb) .* x\t# [-1,1] -> [a,b]\nfunction chebpol(x, n)\n\tΦ = zeros(size(x,1),n) # chebyshev polynomials basis\n\tfor i in 1:size(x,1)\n\t\tfor j in 1:n\n\t\t\tΦ[i,j] = ChebyT(x[i],j-1)\n\t\t\t# Φ[i,j] = abmap(Φ[i,j], lb, ub)\n\t\tend\n\tend\n\treturn Φ\nend\n\n\nfunction q1(n=15)\n\tlb = -3\n\tub = 3\n\tx = range(lb, stop = ub ,length = n)\n\t# generate Chebyshev nodes\n\tS, y = gausschebyshev(n)\n\t# Scale Chebyshev nodes on -3 to 3 domain\n\tϕ = abmap(S, lb, ub) # Chebyshev nodes on -3, 3\n\t# define function\n\tf(x) = x .+ 2x.^2 - exp.(-x)\n\t# Evaluate function at chebyshev nodes\n\tY = f(ϕ)\n\n\t# Build Function grid\n\tΦ = chebpol(S, n)\n\n\t# Estimate parameters of approximation\n\tc = Φ\\Y\n\n\t# Evaluate approximation\n\tYhat = Φ*c\n\n\t# Test accuracy on larger sample\n\tn_new = range(lb, stop = ub ,length = 100)\n\t# Evaluate function\n\tY_new = f(n_new)\n\t# Build Polynomial grid\n\tΦ_new = chebpol(unitmap(n_new,lb,ub), n)\n\n\t# Evaluate using fitted coefficients\n\tYhat_new = Φ_new*c\n\n\t# Plot\n\tp = Any[]\n\tpush!(p,Plots.plot(n_new, [Y_new, Yhat_new], label=[\"True value\" \"Approximation\"], marker=([:none :diamond])))\n\terr = Y_new .- Yhat_new\n\tpush!(p, Plots.plot(n_new, err, label=\"Approximation error\"))\n\tPlots.plot(p...)\n\t# without using PyPlot, just erase the `PyPlot.` part\n\tPlots.savefig(Plots.plot(p...), joinpath(dirname(@__FILE__),\"..\",\"q1.png\"))\n\treturn Dict(\"error\"=>maximum(abs,err))\nend\n\n\nfunction q2(b=4)\n\t@assert b > 0\n\tn = 15\n\t# use ApproxFun.jl to do the same:\n\tdeg = n - 1\n\tub = b\n\tlb = -b\n\tS = Chebyshev(lb..ub)\n\tp = range(lb,stop=ub,length=n)  # a non-default grid\n\t# define function\n\tf(x) = x .+ 2x.^2 - exp.(-x)\n\t# evaluate function\n\tv = f(p)           # values at the non-default grid\n\tV = Array{Float64}(undef,n,deg + 1) # Create a Vandermonde matrix by evaluating the basis at the grid\n\n\tfor k = 1:deg+1\n\t    V[:,k] = Fun(S,[zeros(k-1);1]).(p) # Evaluate Chebyshev basis at p\n\t\t# [zeros(k-1);1] is the identity matrix, all observations have same k degree Chebyshev basis function, evaluated at a different point\n\tend\n\tV\n\tg = Fun(S,V\\v);\n\t@show g(1.1)\n\t@show f(1.1)\n\n\tn_new = range(lb, stop = ub, length = 100)\n\tp = Any[]\n\tpush!(p,Plots.plot(n_new, [f(n_new), g.(n_new)], label=[\"True value\" \"Approximation\"], marker=([:none :diamond])))\n\terr = f(n_new) .- g.(n_new)\n\tpush!(p, Plots.plot(n_new, err, label=\"Approximation error\"))\n\tfig = Plots.plot(p...)\n\n\tPlots.savefig(fig,joinpath(dirname(@__FILE__),\"..\",\"q2.png\"))\nend\n\n\nfunction q3(b=10)\n\n\tx = Fun(identity,-b..b)\n\tf = sin(x^2)\n\tg = cos(x)\n\th = f - g\n\tr = roots(h)\n\n\tPlots.plot(h, label=\"h(x)\")\n\tPlots.scatter!(r,h.(r), label=\"Roots\")\n\tPlots.savefig(joinpath(dirname(@__FILE__),\"..\",\"q3.png\"))\n\t# xbis = Fun(identity,-b..0)\n\tg = cumsum(h) # indefinite  integral\n\tg = g + h(-b) # definite integral with constant of integration\n\tintegral = norm(g(0) - g(-b)) # definite integral from -b to 0\n\t# p is your plot\n\treturn (integral)\nend\n\n# optinal\nfunction q4()\n\n\treturn fig\nend\n\n\n# I found having those useful for q5\nmutable struct ChebyType\n\tf::Function # fuction to approximate\n\tnodes::Union{Vector,LinRange} # evaluation points\n\tbasis::Matrix # basis evaluated at nodes\n\tcoefs::Vector # estimated coefficients\n\n\tdeg::Int \t# degree of chebypolynomial\n\tlb::Float64 # bounds\n\tub::Float64\n\n\t# constructor\n\tfunction ChebyType(_nodes::Union{Vector,LinRange},_deg,_lb,_ub,_f::Function)\n\t\tn = length(_nodes)\n\t\ty = _f(_nodes)\n\t\t_basis = Float64[ChebyT(unitmap(_nodes[i],_lb,_ub),j) for i=1:n,j=0:_deg]\n\t\t_coefs = _basis \\ y  # type `?\\` to find out more about the backslash operator. depending the args given, it performs a different operation\n\t\t# create a ChebyComparer with those values\n\t\tnew(_f,_nodes,_basis,_coefs,_deg,_lb,_ub)\n\tend\nend\n\n# function to predict points using info stored in ChebyType\nfunction predict(Ch::ChebyType,x_new)\n\n\ttrue_new = Ch.f(x_new)\n\tbasis_new = Float64[ChebyT(unitmap(x_new[i],Ch.lb,Ch.ub),j) for i=1:length(x_new),j=0:Ch.deg]\n\tbasis_nodes = Float64[ChebyT(unitmap(Ch.nodes[i],Ch.lb,Ch.ub),j) for i=1:length(Ch.nodes),j=0:Ch.deg]\n\tpreds = basis_new * Ch.coefs\n\tpreds_nodes = basis_nodes * Ch.coefs\n\n\treturn Dict(\"x\"=> x_new,\"truth\"=>true_new, \"preds\"=>preds, \"preds_nodes\" => preds_nodes)\nend\n\nfunction q5(deg=(5,9,15),lb=-1.0,ub=1.0)\n\n\trunge(x) = 1.0 ./ (1 .+ 25 .* x.^2)\n\n\n\tPyPlot.savefig(joinpath(dirname(@__FILE__),\"..\",\"q5.png\"))\n\nend\n\n\n\nfunction q6()\n\n\t# compare 2 knot vectors with runge's function\n\n\tPyPlot.savefig(joinpath(dirname(@__FILE__),\"..\",\"q6.png\"))\n\nend\n\nfunction q7(n=13)\n\tf(x) = abs.(x).^0.5\n\n\t# Regular grid\n\tbs = BSpline(13,3,-1,1) #13 knots, degree 3 in [0,1], no multiplicity\n\t# 3 knots grid\n\tmultiknots = vcat(range(-1,stop = -0.1,length = 5),0,0,0, range(0.1,stop = 1,length =5))\n\tbs2 = BSpline(multiknots, 3)\n\n\t# Evaluate function of interest\n\tx = range(-1,stop =1.0, length = 65)\n\tY = f(x)\n\n\t# Evaluate basis on grid\n\tB = Array(getBasis(collect(x),bs))\n\tB2 = Array(getBasis(collect(x),bs2))\n\n\t# Solve for parameters\n\tc = B\\Y\n\tc2 = B2\\Y\n\n\t# Compute fitted values\n\tYhat = B*c\n\tYhatbis = B2*c2\n\n\t# Compute fitting errors\n\terr = Y .- Yhat\n\terrbis = Y .- Yhatbis\n\n\t# Plot\n\tp = Any[]\n\tpush!(p,Plots.plot(x, Y, title = \"True function\"))\n\tpush!(p,Plots.plot(x, [Yhat, Yhatbis], label = [\"uniform\" \"multiplicity\"], title=\"Approximations\"))\n\tpush!(p,Plots.plot(x, [err, errbis], label = [\"uniform\" \"multiplicity\"], title=\"Errors\"))\n\treturn Plots.plot(p...)\n\tPlots.savefig(joinpath(dirname(@__FILE__),\"..\",\"q7.png\"))\nend\n\n\n\t# function to run all questions\nfunction runall()\n\t@info(\"running all questions of HW-funcapprox:\")\n\tq1(15)\n\tq2(3)\n\tq3(10)\n\tq4()\n\tq5()\n\tq6()\n\tq7()\nend\n\n\n\nend # module\n", "meta": {"hexsha": "b60db136c1813134dc14f4b4f4adcf2112ef68d5", "size": 6082, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HWfuncapp.jl", "max_stars_repo_name": "tpellet/HWfuncapp.jl", "max_stars_repo_head_hexsha": "55320351d502f63ddadad210fb5a400c7d674a92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HWfuncapp.jl", "max_issues_repo_name": "tpellet/HWfuncapp.jl", "max_issues_repo_head_hexsha": "55320351d502f63ddadad210fb5a400c7d674a92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HWfuncapp.jl", "max_forks_repo_name": "tpellet/HWfuncapp.jl", "max_forks_repo_head_hexsha": "55320351d502f63ddadad210fb5a400c7d674a92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9262295082, "max_line_length": 141, "alphanum_fraction": 0.6588293325, "num_tokens": 2154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642906, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7729177471166199}}
{"text": "#=\n  Monty Hall problem\n\n  From the PyMC3 model in the talk\n  \"Carlo Revolution is Open Source: Probabilistic Programming with PyMC3?Austin Rochford\"\n  https://www.safaribooksonline.com/videos/open-data-science/9780135432792/9780135432792-ODSC_11\n  Around time 9:00\n\n\n  Which mean that if we selected d1 it will be 1/3 chance of being the price door.\n  Changing to d3 would - however - give a 2/3 change of getting the price.\n\n\n  Distributions of variable prize\n  door3      =>    6685  (0.668500)\n  door1      =>    3312  (0.331200)\n  door2      =>       3  (0.000300)\n\n\n  See ~/blog/monty_hall.blog\n      ~/psi/monty_hall.psi\n      ~/webppl/monty_hall.wppl\n\n=#\n\n# using Memoization\nusing Turing # , StatsPlots, DataFrames\n# using ReverseDiff, Zygote, Tracker\n# Turing.setadbackend(:reversediff)\n# Turing.setadbackend(:zygote)\n# Turing.setadbackend(:tracker)\ninclude(\"jl_utils.jl\")\n\n\n@model function monty_hall()\n    # There are 3 doors.\n    d1 = 1\n    d2 = 2\n    d3 = 3\n\n    # The prize can be behind any door 1..3.\n    prize = DiscreteUniform(1,3)\n\n    # Which door will Monty open?\n    # Assumption (WLOG): We always select door 1.\n    prize ~ DiscreteUniform(1,3)\n    open  ~ DiscreteUniform(1,3);\n    open ~ (prize == d1) ? Categorical([0.0, 0.5,0.5]) :\n            (prize == d2 ? Categorical([0.0, 0.0,1.0]) : Categorical([0.0, 1.0,0.0]))\n\n    # We see that Monty opens door 2.\n    true ~ Dirac(open == d2)\n\n    # What are the probabilities that the price is behind\n    # - door d1 (the one we selected, i.e don't switch)\n    # - or door d3 (i.e. switch door)\n\nend\n\nmodel = monty_hall()\nnum_chns = 4\n\n# chns = sample(model, Prior(), 10_000)\nchns = sample(model, MH(), 10_000)\n# chns = sample(model, PG(20), 1_000)\n# chns = sample(model, IS(), 10_000)\n# chns = sample(model, SMC(), 10_000)\n\ndisplay(chns)\n\nshow_var_dist_pct(chns, :prize,[\"door1\",\"door2\",\"door3\"])\n", "meta": {"hexsha": "41bf91f44f8789631a22702166206e973d4a6110", "size": 1870, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/monty_hall.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/monty_hall.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/monty_hall.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 25.9722222222, "max_line_length": 96, "alphanum_fraction": 0.6556149733, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7729177398051658}}
{"text": "using DiffEqSensitivity, OrdinaryDiffEq, Zygote, LinearAlgebra, FiniteDiff, Test\r\nA  = [1.0*im  2.0; 3.0 4.0]\r\nu0 = [1.0 0.0*im; 0.0 1.0]\r\ntspan = (0.0, 1.0)\r\n\r\nfunction f(u,p,t)\r\n    (A*u)*(p[1]*t + p[2]*t^2 + p[3]*t^3 + p[4]*t^4)\r\nend\r\n\r\np = [1.5 + im, 1.0, 3.0, 1.0]\r\nprob = ODEProblem{false}(f,u0,tspan,p)\r\n\r\nutarget = [0.0*im 1.0; 1.0 0.0]\r\n\r\nfunction loss_adjoint(p)\r\n    ufinal = last(solve(prob, Tsit5(), p=p, abstol=1e-12, reltol=1e-12, sensealg = InterpolatingAdjoint()))\r\n    loss = 1 - abs(tr(ufinal*utarget')/2)^2\r\n    return loss\r\nend\r\n\r\ngrad1 = Zygote.gradient(loss_adjoint,Complex{Float64}[1.5, 1.0, 3.0, 1.0])[1]\r\ngrad2 = FiniteDiff.finite_difference_gradient(loss_adjoint,Complex{Float64}[1.5, 1.0, 3.0, 1.0])\r\n@test grad1 ≈ grad2\r\n\r\nfunction rhs(u, p, t)\r\n    p .* u\r\nend\r\n\r\nfunction loss_fun(sol)\r\n    final_u = sol[:, end]\r\n    err = sum(abs.(final_u))\r\n    return err\r\nend\r\n\r\nfunction inner_loop(prob, p, loss_fun; sensealg = InterpolatingAdjoint())\r\n    sol = solve(prob, Tsit5(), p=p,  saveat=0.1; sensealg)\r\n    err = loss_fun(sol)\r\n    return err\r\nend\r\n\r\ntspan = (0.0, 1.0)\r\np = [1.0]\r\nu0=[1.0, 2.0]\r\nprob = ODEProblem(rhs, u0, tspan, p)\r\ngrads = Zygote.gradient((p)->inner_loop(prob, p, loss_fun), p)[1]\r\n\r\nu0=[1.0 + 2.0*im, 2.0 + 1.0*im]\r\nprob = ODEProblem(rhs, u0, tspan, p)\r\ndp1 = Zygote.gradient((p)->inner_loop(prob, p, loss_fun), p)[1]\r\ndp2 = Zygote.gradient((p)->inner_loop(prob, p, loss_fun; sensealg = QuadratureAdjoint()), p)[1]\r\ndp3 = Zygote.gradient((p)->inner_loop(prob, p, loss_fun; sensealg = BacksolveAdjoint()), p)[1]\r\n@test dp1 ≈ dp2 ≈ dp3\r\n@test eltype(dp1) <: Float64\r\n", "meta": {"hexsha": "824a6bf1ab5a48316883e7965aa09ae965e9bb26", "size": 1616, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/complex_adjoints.jl", "max_stars_repo_name": "stjordanis/DiffEqSensitivity.jl", "max_stars_repo_head_hexsha": "8f8753b9fda0300b76a68a22b7f86ee0b7eda635", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 136, "max_stars_repo_stars_event_min_datetime": "2020-04-06T13:59:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T10:57:27.000Z", "max_issues_repo_path": "test/complex_adjoints.jl", "max_issues_repo_name": "stjordanis/DiffEqSensitivity.jl", "max_issues_repo_head_hexsha": "8f8753b9fda0300b76a68a22b7f86ee0b7eda635", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 212, "max_issues_repo_issues_event_min_datetime": "2020-03-26T16:26:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T11:16:41.000Z", "max_forks_repo_path": "test/complex_adjoints.jl", "max_forks_repo_name": "stjordanis/DiffEqSensitivity.jl", "max_forks_repo_head_hexsha": "8f8753b9fda0300b76a68a22b7f86ee0b7eda635", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2020-04-24T15:53:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T03:53:22.000Z", "avg_line_length": 29.9259259259, "max_line_length": 108, "alphanum_fraction": 0.620049505, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.7728789930766174}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.20\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 8ffa93f8-7e46-11eb-24dd-d3a098d446db\nrun(`pwd`)\n\n# ╔═╡ 771d9d7c-7e45-11eb-333b-89c14c371bb1\nbegin\n  import Pkg\n  Pkg.activate(mktempdir())\n  Pkg.add([\n\t  #\"AudioDisplay\",\n\t  #\"AudioIO\",\n      \"PyPlot\",\n  ])\nend\n\n# ╔═╡ 3890caac-7e40-11eb-1abf-cb2d856fde8b\nmd\"\"\"\n$x[n] = A \\cos(\\omega n T + \\phi) = A \\cos(2\\pi f n T + \\phi)$\n\n- ``A``: amplitude\n- ``\\omega``: angular frequency (`radians/sec`)\n- ``f = \\omega / 2\\pi``: frequency in Hertz (`cycles/sec`)\n- ``\\phi``: initial phase (`radians`)\n- ``n``: time index\n- ``t = nT = n / f_s``, where $f_s$ is the sampling frequency\n\"\"\"\n\n# ╔═╡ 0d70902e-7e44-11eb-353e-a9a2b3249ede\nbegin\n  A = .8\n  f = 1000    # i.e. 1000 cycles/sec\n  ϕ = pi/2\n  fs = 44100  # i.e. 44100 samples/sec\n  t = range(-.002, .002, step=1/fs)\n  x = A .* cos.(2π*f.*t .+ ϕ)\n  size(x)\nend\n\n# ╔═╡ 4a3f2772-7e44-11eb-22ed-a1fe51593505\nt, size(t)\n\n# ╔═╡ e439ba0e-7e44-11eb-3650-b974bc440e07\nsize(@. A * cos(2π*f*t + ϕ))\n\n# ╔═╡ Cell order:\n# ╠═8ffa93f8-7e46-11eb-24dd-d3a098d446db\n# ╠═771d9d7c-7e45-11eb-333b-89c14c371bb1\n# ╟─3890caac-7e40-11eb-1abf-cb2d856fde8b\n# ╠═0d70902e-7e44-11eb-353e-a9a2b3249ede\n# ╠═4a3f2772-7e44-11eb-22ed-a1fe51593505\n# ╠═e439ba0e-7e44-11eb-3650-b974bc440e07\n", "meta": {"hexsha": "913e25572557c5425f32d4924fbea545b149ce9e", "size": 1279, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "stanford/2019/01-intro.jl", "max_stars_repo_name": "phunc20/dsp", "max_stars_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-12T18:32:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T18:32:06.000Z", "max_issues_repo_path": "stanford/2019/01-intro.jl", "max_issues_repo_name": "phunc20/dsp", "max_issues_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stanford/2019/01-intro.jl", "max_forks_repo_name": "phunc20/dsp", "max_forks_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4385964912, "max_line_length": 62, "alphanum_fraction": 0.6325254105, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.7728789836197247}}
{"text": "# ------------------------------------------------------------------------------------------------------------------------------- #\n# compute_log_return_array(data::DataFrame,map::Pair{Symbol,Symbol}; Δt::Float64 = 1.0) -> DataFrame\n\n# Computes μ of historical price data. \n\n# # Arguments:\n# data_table  \tDataFrame holding the historical price data\n# map \t        Different data APIs return data with different field names. The map arg connects the time field to price field\n# Δt \t\t    Time step size. Default is 1.0 in the units you want the μ to be calculated in\n# ------------------------------------------------------------------------------------------------------------------------------ #\nfunction compute_log_return_array(data_table::DataFrame, map::Pair{Symbol,Symbol}; Δt = (1.0 / 365.0))\n\n    # initialize -\n    (number_of_rows, _) = size(data_table)\n    return_table = DataFrame(timestamp = Date[], P1 = Float64[], P2 = Float64[], μ = Float64[])\n\n    # main loop -\n    for row_index = 2:number_of_rows\n\n        # grab the date -\n        tmp_date = data_table[row_index, map.first]\n\n        # grab the price data -\n        yesterday_close_price = data_table[row_index-1, map.second]\n        today_close_price = data_table[row_index, map.second]\n\n        # compute the diff -\n        μ = (1 / Δt) * log(today_close_price / yesterday_close_price)\n\n        # push! -\n        push!(return_table, (tmp_date, yesterday_close_price, today_close_price, μ))\n    end\n\n    # return -\n    return return_table\nend\n\nfunction compute_log_return_array(ticker_symbol_array::Array{String,1}, data_tables::Dict{String,DataFrame}, \n    map::Pair{Symbol,Symbol}; Δt = (1.0 / 365.0))\n\n    # initialize -\n    number_of_ticker_symbols = length(ticker_symbol_array)\n    data_dictionary = Dict{String,DataFrame}()\n\n    # process -\n    for ticker_symbol_index ∈ 1:number_of_ticker_symbols\n\n        # get the ticker symbol for this index -\n        ticker_symbol = ticker_symbol_array[ticker_symbol_index]\n\n        # get the data frame for this index -\n        df = data_tables[ticker_symbol]\n\n        # compute the return -\n        data_dictionary[ticker_symbol] = compute_log_return_array(df, map; Δt = Δt)\n    end\n\n    # return -\n    return data_dictionary\nend\n\nfunction compute_fractional_return_array(data::Array{Float64,1}; \n    multiplier::Float64 = 1.0)\n\n    # what is the length of the array?\n    number_of_steps = length(data)\n    Δ_array = Array{Float64,1}()\n\n    for step_index ∈ 2:number_of_steps\n\n        # compute -\n        P₁ = data[step_index-1]\n        P₂ = data[step_index]\n        Δ = multiplier*(P₂ - P₁)/(P₁)\n\n        # grab -\n        push!(Δ_array,Δ)\n    end\n\n    # return -\n    return Δ_array;\nend\n\nfunction compute_fractional_return_array(data::Array{Float64,2}; \n    multiplier::Float64 = 1.0)\n\n    # what is the length of the array?\n    (number_of_steps, number_of_cols) = size(data)\n    Δ_array = Array{Float64,2}(undef, number_of_steps - 1, number_of_cols)\n\n    for col_index ∈ 1:number_of_cols\n        for step_index ∈ 2:number_of_steps\n\n            # compute -\n            P₁ = data[step_index-1,col_index]\n            P₂ = data[step_index, col_index]\n            Δ = multiplier*(P₂ - P₁)/(P₁)\n    \n            # grab -\n            Δ_array[step_index - 1, col_index] = Δ\n        end\n    end\n\n    # return -\n    return Δ_array;\nend\n\nfunction compute_fractional_return_array(data_table::DataFrame, map::Pair{Symbol,Symbol};\n    multiplier::Float64=1.0)\n\n    # initialize -\n    (number_of_rows, _) = size(data_table)\n    return_table = DataFrame(timestamp = Date[], P1 = Float64[], P2 = Float64[], μ = Float64[])\n\n    # main loop -\n    for row_index = 2:number_of_rows\n\n        # grab the date -\n        tmp_date = data_table[row_index, map.first]\n\n        # grab the price data -\n        yesterday_close_price = data_table[row_index-1, map.second]\n        today_close_price = data_table[row_index, map.second]\n\n        # compute the diff -\n        μ = ((today_close_price/yesterday_close_price) - 1.0)*multiplier;\n\n        # push! -\n        push!(return_table, (tmp_date, yesterday_close_price, today_close_price, μ))\n    end\n\n    # return -\n    return return_table\nend\n\nfunction compute_fractional_return_array(ticker_symbol_array::Array{String,1}, data_tables::Dict{String,DataFrame}, map::Pair{Symbol,Symbol}; \n    multiplier::Float64=1.0)\n\n    # initialize -\n    number_of_ticker_symbols = length(ticker_symbol_array)\n    data_dictionary = Dict{String,DataFrame}()\n\n    # process -\n    for ticker_symbol_index ∈ 1:number_of_ticker_symbols\n\n        # get the ticker symbol for this index -\n        ticker_symbol = ticker_symbol_array[ticker_symbol_index]\n\n        # get the data frame for this index -\n        df = data_tables[ticker_symbol]\n\n        # compute the return -\n        data_dictionary[ticker_symbol] = compute_fractional_return_array(df, map; multiplier=multiplier)\n    end\n\n    # return -\n    return data_dictionary\nend\n\nfunction compute_discrete_geometric_brownian_motion_trajectory(model::GeometricBrownianMotionModel, \n    initial_condition::Float64, number_of_steps::Int64; Δt::Float64 = 1.0, N::Int64 = 100)\n\n    # initialize -\n    state_array = Array{Float64,2}(undef, number_of_steps, N)\n    state_array[1,:] .= initial_condition\n\n    # get data from the model -\n    μ = model.μ\n    σ = model.σ\n\n    # calculate the random term -\n    d = Normal{Float64}(0.0, 1.0)\n\n    # calculate the drift term -\n    drift_term = μ*Δt\n\n    # main: sample paths -\n    for sample_path_index ∈ 1:N\n\n        # generate new sequence of steps for this sample path -\n        random_terms = σ*sqrt(Δt)*rand(d,number_of_steps)\n        \n        # solve the model -\n        for time_step_index ∈ 2:number_of_steps\n            \n            # grab the current price P₁ -\n            P₁ = state_array[time_step_index-1,sample_path_index]\n            \n            # compute the price difference -\n            ΔP = P₁*(drift_term+random_terms[time_step_index])\n\n            # capture -\n            state_array[time_step_index,sample_path_index] = (P₁ + ΔP)\n        end\n    end\n\n    # return -\n    return state_array\nend\n\nfunction compute_rwm_cumulative_probabilty(compare::Function, price_array::Array{Float64,1})\n\n    # initialize -\n    number_of_samples = length(price_array)\n    tmp_array = BitArray(undef, (number_of_samples, 1))\n\n    # main -\n    for sample_index = 1:number_of_samples\n\n        # get the sample price -\n        sample_price = price_array[sample_index]\n\n        # check: which is larger, sample or target price?\n        compare(sample_price) ? tmp_array[sample_index] = 1 : tmp_array[sample_index] = 0\n    end\n\n    # sum the tmp_array -\n    number_of_larger_values = sum(tmp_array)\n\n    # compute the probability -\n    return (number_of_larger_values / number_of_samples)\nend\n\nfunction compute_rwm_cumulative_probabilty(price_array::Array{Float64,1}, target_price::Float64)\n\n    # initialize -\n    number_of_samples = length(price_array)\n    tmp_array = Array{Int64,1}()\n\n    # main -\n    for sample_index = 1:number_of_samples\n\n        # get the sample price -\n        sample_price = price_array[sample_index]\n\n        # check: which is larger, sample or target price?\n        sample_price <= target_price ? push!(tmp_array, 1) : push!(tmp_array, 0)\n    end\n\n    # sum the tmp_array -\n    number_of_larger_values = sum(tmp_array)\n\n    # compute the probability -\n    return (number_of_larger_values / number_of_samples)\nend\n\nfunction compute_minvar_portfolio_allocation(μ,Σ,target_return::Float64; \n    w_lower::Float64 = 0.0, w_upper::Float64 = 1.0)\n\n    # initialize -\n    number_of_assets = length(μ)\n    w = Variable(number_of_assets)\n    risk = quadform(w,Σ)\n    ret  = dot(w,μ)\n\n    # setup problem -\n    p = minimize(risk)\n    p.constraints += [sum(w)==1.0, w_lower <= w, w <= w_upper, ret >= target_return]\n    Convex.solve!(p, SCS.Optimizer(verbose = false))\n\n    # return -\n    return (p.status, evaluate(w), p.optval, evaluate(ret))\nend\n\nfunction compute_cybernetic_portfolio_allocation(μ,Σ)\n\n    # how many assets do we have?\n    𝒫 = length(μ)\n\n    # initialize -\n\tterm_array = Array{Float64,1}(undef, 𝒫)\n\tfor term_index ∈ 1:𝒫\n\t\tterm_array[term_index] = max(0.0, μ[term_index]/Σ[term_index,term_index])\n\tend\n\n    # compute the u-variable -\n\t𝒵 = sum(term_array)\n\n    # if we have no good options (all the returns are negative, then all allocations would be zero)\n    if (𝒵 == 0)\n        u_variable_array = zeros(𝒫)\n    else\n        u_variable_array = (1/𝒵)*term_array\n    end\n\n    # return -\n    return u_variable_array\nend\n\nfunction compute_average_fractional_return_and_covariance(tickers::Array{String,1}, data::Dict{String,DataFrame}, \n    start::Date, stop::Date)\n\n    # need to grab the number of time steps -\n    test_df = Serenity.extract_data_block_for_date_range(data[tickers[1]], start, stop)\n\tnumber_of_time_steps = nrow(test_df)\n\n    # initialize -\n    μ_bar = Array{Float64,1}()\n    R_array = Array{Float64,2}(undef, number_of_time_steps, length(tickers))\n\n    # process each ticker -\n    for (ticker_index, ticker) ∈ enumerate(tickers)\n\n        # get the data for the data range -\n        df = data[ticker]\n        df_slice = extract_data_block_for_date_range(df,start,stop)\n\n        # compute the return -\n\t\tavg_val = mean(df_slice[!,:μ])\n\t\tpush!(μ_bar, avg_val)\n\n        # build R_array -\n\t\tfor step_index = 1:number_of_time_steps\n\t\t\tR_array[step_index, ticker_index] = df_slice[step_index,:μ]\n\t\tend\n    end\n\n    # compute the covariance -\n    Σ = cov(R_array)\n\n    # return -\n    return (μ_bar,Σ)\nend\n\n", "meta": {"hexsha": "8ba31d8a0d19d1c78879c61edb7aecbd9cd0dd34", "size": 9557, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Compute.jl", "max_stars_repo_name": "Pooksoft/Serenity", "max_stars_repo_head_hexsha": "3b6d2434225ab9f4a340838b2948537dc7503362", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-06T12:10:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T03:28:43.000Z", "max_issues_repo_path": "src/Compute.jl", "max_issues_repo_name": "Alba-Intelligence/Serenity", "max_issues_repo_head_hexsha": "3b6d2434225ab9f4a340838b2948537dc7503362", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Compute.jl", "max_forks_repo_name": "Alba-Intelligence/Serenity", "max_forks_repo_head_hexsha": "3b6d2434225ab9f4a340838b2948537dc7503362", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-02T03:28:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T21:38:27.000Z", "avg_line_length": 29.4061538462, "max_line_length": 142, "alphanum_fraction": 0.6462278958, "num_tokens": 2437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7727946524023526}}
{"text": "\n\"\"\"\nBulkAndTailsDist(κ₀,τ₀,ϕ₀,κ₁,τ₁,ϕ₁,ν)\nThe *Bulk-And-Tails (BATs) distribution* has cumulative distribution function\n```math\nF(x) = T_ν(H(x))\n```\nwhere T_ν is the student-t cdf with ν degrees of freedom and H is a monotone increasing function.\nϕ₀ and ϕ₁ are location parameters for the lower and upper tails.\nτ₀ and τ₁ are scale parameters for the lower and upper tails.\nκ₀ and κ₁ are shape parameters for the lower and upper tails.\nNegative κ indicates a bounded tail. Positive κ indicates a heavy tail.\nThe case κ=0, defined by continuity, indicates a thin Gaussian tail.\n\n`fitbats` provides maximum likelihood estimation for these parameters. In addition, we provide \n`pdf`, `cdf`, `logpdf`, `logcdf`, `quantile`, and `rand` functions for `BulkAndTailsDist`, all of which follow the \n`Distributions.jl` framework. We also provide R-friendly versions of these functions and show how to call them from R.\n\n```julia\nBulkAndTailsDist(κ₀,τ₀,ϕ₀,κ₁,τ₁,ϕ₁,ν)     # BATs distribution\nparams(d)        # Get the parameters\nminimum(d)       # lower bound of support\nmaximum(d)       # upper bound of support\n```\nExternal links\n* [Stein, M. L. (2021).  A parametric model for distributions with flexible behavior in both tails. Environmetrics, 32(2):Paper No. e2658, 24.](https://onlinelibrary.wiley.com/doi/abs/10.1002/env.2658)\n\"\"\"\nstruct BulkAndTailsDist{T<:Real} <: ContinuousUnivariateDistribution\nκ₀::T\nτ₀::T\nϕ₀::T\nκ₁::T\nτ₁::T\nϕ₁::T\nν::T\nend\n\nDistributions.params(d::BulkAndTailsDist) = (d.κ₀,d.τ₀,d.ϕ₀,d.κ₁,d.τ₁,d.ϕ₁,d.ν)\nDistributions.minimum(d::BulkAndTailsDist) = (d.κ₀ ≥ 0.0 ? -Inf : d.ϕ₀ - d.τ₀*iΨ(-1.0/d.κ₀))\nDistributions.maximum(d::BulkAndTailsDist) = (d.κ₁ ≥ 0.0 ? Inf : d.ϕ₁ + d.τ₁*iΨ(-1.0/d.κ₁))\n\nBulkAndTailsDist(κ₀::Real,τ₀::Real,ϕ₀::Real,κ₁::Real,τ₁::Real,ϕ₁::Real,ν::Real) = BulkAndTailsDist(promote(κ₀,τ₀,ϕ₀,κ₁,τ₁,ϕ₁,ν)...)\n\nfunction BulkAndTailsDist(xv) \n    @assert length(xv) == 7 \"Please provide 7 arguments.\"\n    BulkAndTailsDist(xv...) \nend", "meta": {"hexsha": "7ca27aa54b5d332dbace2423d732655b017cf294", "size": 1964, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BulkAndTailsDist_struct.jl", "max_stars_repo_name": "cgeoga/BulkAndTails.jl", "max_stars_repo_head_hexsha": "d694aa18993d3d1aec83299bf48996b6051352bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-11-30T17:34:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T19:52:24.000Z", "max_issues_repo_path": "src/BulkAndTailsDist_struct.jl", "max_issues_repo_name": "cgeoga/BulkAndTails.jl", "max_issues_repo_head_hexsha": "d694aa18993d3d1aec83299bf48996b6051352bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-17T14:35:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T21:02:50.000Z", "max_forks_repo_path": "src/BulkAndTailsDist_struct.jl", "max_forks_repo_name": "cgeoga/BulkAndTails.jl", "max_forks_repo_head_hexsha": "d694aa18993d3d1aec83299bf48996b6051352bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-16T15:55:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-16T15:55:11.000Z", "avg_line_length": 41.7872340426, "max_line_length": 201, "alphanum_fraction": 0.7230142566, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.77279464379139}}
{"text": "using Plots\nusing LaTeXStrings\n\ntanh_step(x) = (1 - tanh(x)) / 2\n\nν₀ = 1f-4\nν₋ = 0.1f0\nν₂ = 1f0\n\nRiᶜ = 0.25\nΔRi₊ = 0.1\nΔRi₋ = 0.1\n\nRis = -1:0.001:2\nmpp(Ri, ν₀, ν₋, Riᶜ, ΔRi) = ν₀ + ν₋ * tanh_step((Ri - Riᶜ) / ΔRi)\nmpp_ca(Ri, ν₀, ν₋, ν₂, Riᶜ, ΔRi₊) = ν₀ + ν₋ * tanh_step((Ri - Riᶜ) / ΔRi₊) + ν₂ * tanh_step((Ri + Riᶜ) / ΔRi₋)\n\nmpp_str = \"Modified Pac-Phil\"\nmpp_ca_str = \"New Modified Pac-Phil\"\n\nplot(Ris, mpp.(Ris, ν₀, ν₋, Riᶜ, ΔRi₊), label=mpp_str)\nplot!(Ris, mpp_ca.(Ris, ν₀, ν₋, ν₂, Riᶜ, ΔRi₊), label=mpp_ca_str)\ntitle!(\"Diffusivity Profiles Comparison\")\nsavefig(\"Output/diffusivity_schemes_comparison.pdf\")\n# color_palette = distinguishable_colors(2, [RGB(1,1,1), RGB(0,0,0)], dropseed=true)\n\n# fig = Figure()\n# ax = Axis(fig[1, 1], yscale=log10)\n# lines!(ax, Ris, mpp.(Ris, ν₀, ν₋, Riᶜ, ΔRi), color=color_palette[1], label=L\"\\nu_0\")\n# lines!(ax, Ris, mpp_ca.(Ris, ν₀, ν₋, ν₂, Riᶜ, ΔRi), color=color_palette[2])\n# axislegend(ax)\n# current_figure()\n", "meta": {"hexsha": "5852589a957171b4f8e70a9bfafd2d5a9f9c52af", "size": 951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "wind_mixing/plot_diffusivity_profile.jl", "max_stars_repo_name": "CliMA/ClimateParameterizations.jl", "max_stars_repo_head_hexsha": "1263e2edefced4e03e925d6bfa60ba1f1940e8c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2020-12-23T06:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:05:51.000Z", "max_issues_repo_path": "wind_mixing/plot_diffusivity_profile.jl", "max_issues_repo_name": "CliMA/OceanParameterizations.jl", "max_issues_repo_head_hexsha": "5942c66ba8724b9661db170acb239ca3a2abd5c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-12-05T02:43:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T14:27:03.000Z", "max_forks_repo_path": "wind_mixing/plot_diffusivity_profile.jl", "max_forks_repo_name": "ali-ramadhan/ClimateParameterizations.jl", "max_forks_repo_head_hexsha": "1263e2edefced4e03e925d6bfa60ba1f1940e8c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-17T18:06:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T18:06:40.000Z", "avg_line_length": 28.8181818182, "max_line_length": 110, "alphanum_fraction": 0.6330178759, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.772794630602347}}
{"text": "# Estimates 5 separate models for the Nerlove Cobb-Douglas model,\n# and does a Chow test for pooled coefficients\nusing Econometrics, Plots, DelimitedFiles, LinearAlgebra\nfunction main()\ndata = readdlm(\"nerlove.data\")\ndata = data[:,2:6]\ndata = log.(data)\nn = size(data,1)\ny = data[:,1]\nx = data[:,2:end]\nx = [ones(n,1) x]\n#b, junk, junk, junk = ols(y, x, names=names)\nk = size(x,2)\n\n# create the block diagonal X matrix corresponding to separate coefficients\nbig_x = zeros(n,5*k)\nfor i=1:k\n\tstartrow = (i-1)*29+1\n\tendrow = i*29\n\tstartcol =(i-1)*k + 1\n\tendcol = i*k\n\tbig_x[startrow:endrow,startcol:endcol] += x[startrow:endrow,:]\nend\nx = big_x\n\nnames = [\"constant\", \"output\",\"labor\", \"fuel\", \"capital\"]\nnames = [names; names; names; names; names] # copy 5 times\n\nprintln(\"Nerlove model: 5 separate regressions for different output levels\")\nb, junk, junk, junk = ols(y, x, names=names)\noutput = 1:5\noutput = output .*5 .+2 .- 5\noutput = b[output,:]\nrts = 1 ./ output\n\n# gset term X11\ngroup = 1:5\ngroup = group\nplot(group, rts, label = \"\", yaxis=\"RTS\", xaxis = \"Output Group\", show=true)\n#savefig(\"rts.png\")\n\n# Chow test\nR = Matrix{Float64}(I, 5, 5)\nZ = zeros(5,5)\nR = [\n\tR -R Z Z Z;\n\tR Z -R Z Z;\n\tR Z Z -R Z;\n\tR Z Z Z -R]\nr = zeros(20,1)\n\nprintln(\"Chow test: note that the restricted model\")\nprintln(\"gives the same results as the original model\")\nols(y, x, R=R, r=r, names=names)\nTestStatistics(y, x, R, r)\nreturn\nend\nmain()\n\n", "meta": {"hexsha": "0830562993a354a5a8945490a509eef68e43ba67", "size": 1424, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/Restrictions/ChowTest.jl", "max_stars_repo_name": "Hiroakiyusheng/Econometrics", "max_stars_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "Examples/Restrictions/ChowTest.jl", "max_issues_repo_name": "Hiroakiyusheng/Econometrics", "max_issues_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "Examples/Restrictions/ChowTest.jl", "max_forks_repo_name": "Hiroakiyusheng/Econometrics", "max_forks_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 23.7333333333, "max_line_length": 76, "alphanum_fraction": 0.6629213483, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913356558485, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7727865453947887}}
{"text": "using Distributions\nusing Plots\npyplot()\n\ninclude(\"gen_data.jl\")\ninclude(\"particle_filters.jl\")\n\n\"\"\"Experimental parameters\"\"\"\n\n# Visualization options\nviz_particles = true\n\n# Number of particles\nN = 20\n\n# Time horizon\nT = 100\n\n# Experimental parameters\ntransition = 1.0\nemission = 1.0\nprocess_noise = 0.9\nmeasurement_noise = 0.3\n\n# Prior state\nprior = [0, 1]\n\n# Generate signal\nobservations, latent_states = LGDS(transition,\n                                   emission,\n                                   process_noise,\n                                   measurement_noise,\n                                   prior;\n                                   time_horizon=T)\n\n# Check signal visually\nscatter(1:T, observations, color=\"blue\", label=\"observations\")\nplot!(1:T, latent_states[2:end], color=\"red\", label=\"latent states\")\n\n\"\"\"SIS filter\"\"\"\n\n# Nominal distributions\np_transition(a) = Normal(a, sqrt(process_noise))\np_likelihood(b) = Normal(b, sqrt(measurement_noise))\n\n# Call SIS filter\nsamples, weights = sequential_importance_sampling(observations,\n                                                  p_transition,\n                                                  p_likelihood,\n                                                  num_particles=N,\n                                                  imp_processp=inv(process_noise),\n                                                  imp_measurementp=inv(measurement_noise))\n\n# Generate posterior distribution\nposterior_mean = sum(weights .* samples, dims=2)\nposterior_var = sum(weights .* (broadcast(-, samples, posterior_mean)).^2, dims=2)\n\n# Visualize particles\nscatter(1:T, observations, color=\"blue\", label=\"observations\")\nplot!(1:T, latent_states[2:end], color=\"red\", label=\"latent states\")\nplot!(1:T, posterior_mean[2:end], color=\"purple\", label=\"inferred\")\nplot!(1:T, posterior_mean[2:end],\n      ribbon=[sqrt.(posterior_var[2:end]), sqrt.(posterior_var[2:end])],\n      color=\"purple\", alpha=0.1, label=\"\")\nxlabel!(\"time (t)\")\nylabel!(\"signal\")\nsavefig(pwd()*\"/viz/sis.png\")\n\nif viz_particles\n\n    # Show sample spreads\n    scatter(1:T, observations, color=\"blue\", label=\"observations\")\n    for t = 2:T\n        scatter!((t-1).*ones(1,N), samples[t,:], markersize=weights[t,:]*50, markercolor=\"purple\", label=\"\")\n    end\n    savefig(pwd()*\"/viz/sis_particles.png\")\nend\n\n\"\"\"SIR filter\"\"\"\n\n# Nominal distributions\np_transition(a) = Normal(a, sqrt(process_noise))\np_likelihood(b) = Normal(b, sqrt(measurement_noise))\n\n# Call filter\nsamples, weights = sequential_importance_resampling(observations,\n                                                    p_transition,\n                                                    p_likelihood,\n                                                    num_particles=N,\n                                                    imp_processp=inv(process_noise),\n                                                    imp_measurementp=inv(measurement_noise))\n\n# Generate posterior distribution\nposterior_mean = sum(weights .* samples, dims=2)\nposterior_var = sum(weights .* (broadcast(-, samples, posterior_mean)).^2, dims=2)\n\n# Visualize particles\nscatter(1:T, observations, color=\"blue\", label=\"observations\")\nplot!(1:T, latent_states[2:end], color=\"red\", label=\"latent states\")\nplot!(1:T, posterior_mean[2:end], color=\"purple\", label=\"inferred\")\nplot!(1:T, posterior_mean[2:end],\n    ribbon=[sqrt.(posterior_var[2:end]), sqrt.(posterior_var[2:end])],\n    color=\"purple\", alpha=0.1, label=\"\")\nxlabel!(\"time (t)\")\nylabel!(\"signal\")\nsavefig(pwd()*\"/viz/sir.png\")\n\nif viz_particles\n\n    # Show sample spreads\n    scatter(1:T, observations, color=\"blue\", label=\"observations\")\n    for t = 2:T\n        scatter!((t-1).*ones(1,N), samples[t,:], markersize=weights[t,:]*50, markercolor=\"purple\", label=\"\")\n    end\n    savefig(pwd()*\"/viz/sir_particles.png\")\nend\n\n\"\"\"Bootstrap filter\"\"\"\n\n# Nominal distributions\np_transition(a) = Normal(a, sqrt(process_noise))\np_likelihood(b) = Normal(b, sqrt(measurement_noise))\n\n# Call filter\nsamples, weights = bootstrap_filter(observations,\n                                    p_transition,\n                                    p_likelihood,\n                                    num_particles=N)\n\n# Generate posterior distribution\nposterior_mean = sum(weights .* samples, dims=2)\nposterior_var = sum(weights .* (broadcast(-, samples, posterior_mean)).^2, dims=2)\n\n# Visualize particles\nscatter(1:T, observations, color=\"blue\", label=\"observations\")\nplot!(1:T, latent_states[2:end], color=\"red\", label=\"latent states\")\nplot!(1:T, posterior_mean[2:end], color=\"purple\", label=\"inferred\")\nplot!(1:T, posterior_mean[2:end],\n    ribbon=[sqrt.(posterior_var[2:end]), sqrt.(posterior_var[2:end])],\n    color=\"purple\", alpha=0.1, label=\"\")\nxlabel!(\"time (t)\")\nylabel!(\"signal\")\nsavefig(pwd()*\"/viz/bootstrap.png\")\n\nif viz_particles\n\n    # Show sample spreads\n    scatter(1:T, observations, color=\"blue\", label=\"observations\")\n    for t = 2:T\n        scatter!((t-1).*ones(1,N), samples[t,:], markersize=weights[t,:]*50, markercolor=\"purple\", label=\"\")\n    end\n    savefig(pwd()*\"/viz/bootstrap_particles.png\")\nend\n\n\"\"\"RB-SIR filter\"\"\"\n\n# Nominal distributions\nα = 0.5\nimp_pp = inv(process_noise)\nimp_mp = inv(measurement_noise)\nnominal_dynamics(u) = Normal(u, sqrt(α))\nimportance_dist(u,y) = Normal(inv(imp_pp + imp_mp)*(imp_pp*u + imp_mp*y), sqrt(inv(imp_pp + imp_mp)))\n\n# Functions\nA(x) = x\nQ(x) = x^2\nH(x) = x\nR(x) = x^2\n\n# Call filter\nsamples, weights, means, cvars = rao_blackwellized_particle_filter(observations,\n                                                                   nominal_dynamics,\n                                                                   importance_dist,\n                                                                   A, Q, H, R,\n                                                                   num_particles=N,\n                                                                   resampling_threshold=0.5)\n\n# Generate posterior distribution\nposterior_mean = sum(weights .* samples .* means, dims=2)\nposterior_cvar = sum(weights .* samples.^2 .* cvars, dims=2)\n\n# Visualize particles\nscatter(1:T, observations, color=\"blue\", label=\"observations\")\nplot!(1:T, latent_states[2:end], color=\"red\", label=\"latent states\")\nplot!(1:T, posterior_mean[2:end], color=\"purple\", label=\"inferred\")\nplot!(1:T, posterior_mean[2:end],\n      ribbon=[sqrt.(posterior_cvar[2:end]), sqrt.(posterior_cvar[2:end])],\n      color=\"purple\", alpha=0.1, label=\"\")\nxlabel!(\"time (t)\")\nylabel!(\"signal\")\nsavefig(pwd()*\"/viz/rb-sir.png\")\n\nif viz_particles\n\n    # Show sample spreads\n    scatter(1:T, observations, color=\"blue\", label=\"observations\")\n    for t = 2:T\n        scatter!((t-1).*ones(1,N), samples[t,:], markersize=weights[t,:]*50, markercolor=\"purple\", label=\"\")\n    end\n    savefig(pwd()*\"/viz/rb-sir_particles.png\")\nend\n", "meta": {"hexsha": "7fd468af754480318883783fc30839da4605c9d0", "size": 6830, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_pf.jl", "max_stars_repo_name": "wmkouw/kalman-filters", "max_stars_repo_head_hexsha": "0f10bc523170d2b3d33242ecdb0ca46f7159ab8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-08-01T03:27:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T22:05:24.000Z", "max_issues_repo_path": "test/test_pf.jl", "max_issues_repo_name": "wmkouw/kalman-filters", "max_issues_repo_head_hexsha": "0f10bc523170d2b3d33242ecdb0ca46f7159ab8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_pf.jl", "max_forks_repo_name": "wmkouw/kalman-filters", "max_forks_repo_head_hexsha": "0f10bc523170d2b3d33242ecdb0ca46f7159ab8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-01T03:27:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T03:27:19.000Z", "avg_line_length": 33.8118811881, "max_line_length": 108, "alphanum_fraction": 0.5907759883, "num_tokens": 1581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7727865364843988}}
{"text": "\"\"\"\n    function strength(\n        team::Team,\n        method::String\n    )::Float64\n\nCalculates the combined strength of a team.\n\nArguments\n=========\n- `team`:\n    a team of players.\n- `method`\n    the method for calculating team strength\n        current methods include:\n            - \"Simple Average\" \n                assigns strength to be average of individual player strengths.\n            - \"Weighted Average\"\n\"\"\"\n\nfunction strength(team::Team, method::String)::Float64\n    if method == \"Simple Average\"\n        p1_strength = strength(team.player1)\n        p2_strength = strength(team.player2)\n        return (p1_strength + p2_strength) / 2.0\n    else\n        throw(DomainError(method, \"this method isn't supported\"))\n    end\nend\n\n\n\"\"\"\n    function probabilityOfWinning(\n        team1::Team, \n        team2::Team,\n        method::String\n    )::Float64\n\nCalculates the probability of team1 beating team2.\n\nArguments\n=========\n- `team1`:\n    the team for whose probability is calculated.\n- `team2`\n    the opposing team.\n- `method`:\n    method to determine the probability team 1 beats team 2.\n    options:\n        1) \"BT\" - Bradley Terry Model\n        2) \"BT_Exp\" - Bradely Terry Exponential Model\n\"\"\"\n\nfunction probabilityOfWinning(\n    team1::Team, \n    team2::Team,\n    method::String\n)::Float64\n    team1_strength = strength(team1, \"Simple Average\")\n    team2_strength = strength(team2, \"Simple Average\")\n    if method == \"BT\"\n        return (team1_strength / (team1_strength + team2_strength)) \n    elseif method == \"BT_Exp\"\n        return (exp(team1_strength) / (exp(team1_strength) + exp(team2_strength)))\n    else\n        throw(DomainError(method, \"this method isn't supported\"))\n    end\nend\n", "meta": {"hexsha": "e9ab55d6ae1588e1dcec8612f151cdd286c28d5c", "size": 1706, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/agent/team.jl", "max_stars_repo_name": "Danial-Hussain/Tennis-Ranking", "max_stars_repo_head_hexsha": "0cc4f4e27158c0690a9d70b4bdb1ec621e11d212", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/agent/team.jl", "max_issues_repo_name": "Danial-Hussain/Tennis-Ranking", "max_issues_repo_head_hexsha": "0cc4f4e27158c0690a9d70b4bdb1ec621e11d212", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/agent/team.jl", "max_forks_repo_name": "Danial-Hussain/Tennis-Ranking", "max_forks_repo_head_hexsha": "0cc4f4e27158c0690a9d70b4bdb1ec621e11d212", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7246376812, "max_line_length": 82, "alphanum_fraction": 0.6359906213, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.7727865289014498}}
{"text": "using LinearAlgebra\r\n\r\nexport Affine\r\n\r\n\"\"\"\r\n    Affine()\r\n    Affine(A, b)\r\n\r\nProjection to an affine set such that `Ax = b`.\r\n\"\"\"\r\n\r\nstruct Affine{T <: Real} <: ConvexSet\r\n    VVt::Matrix{T}\r\n    pinv_A_b::Vector{T}\r\n    function Affine(\r\n        A::Matrix{T}, \r\n        b::Vector{T}; \r\n        atol::Real = 0.0, \r\n        rtol::Real = (eps(real(float(one(T)))) * min(size(A)...)) * iszero(atol)\r\n        ) where T <: Real\r\n        size(A, 1) == length(b) || throw(ArgumentError(\r\n            \"Number of rows of A does not match length of b\")\r\n            )\r\n        A = LinearAlgebra.svd(A, full = false)\r\n        tol = max(rtol * maximum(A.S), atol)\r\n        Σ_pinv = zeros(length(A.S))\r\n        index = A.S .> tol\r\n        Σ_pinv[index] = 1. ./ A.S[index]\r\n        Σ_pinv[findall(.!isfinite.(Σ_pinv))] .= 0.\r\n        VVt = A.V * A.Vt\r\n        pinv_A_b = A.V * Diagonal(Σ_pinv) * transpose(A.U) * b\r\n        new{T}(VVt, pinv_A_b)\r\n    end\r\nend\r\n\r\nfunction project!(s::Affine{T}, v::Vector{T}, y::Vector{T}) where T <: Real\r\n    v .= y - s.VVt * y + s.pinv_A_b\r\nend\r\n\r\nfunction project(s::Affine{T}, y::Vector{T}) where T <: Real \r\n    project!(s, similar(y), y)\r\nend", "meta": {"hexsha": "c6c12987b87cd482a6bfe4cbd5b037c57b2d532f", "size": 1170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/affine.jl", "max_stars_repo_name": "BrendonChau/Projections.jl", "max_stars_repo_head_hexsha": "08adee3966f6658b8d03371d14fa12b0e9cf6b53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/affine.jl", "max_issues_repo_name": "BrendonChau/Projections.jl", "max_issues_repo_head_hexsha": "08adee3966f6658b8d03371d14fa12b0e9cf6b53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/affine.jl", "max_forks_repo_name": "BrendonChau/Projections.jl", "max_forks_repo_head_hexsha": "08adee3966f6658b8d03371d14fa12b0e9cf6b53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8571428571, "max_line_length": 81, "alphanum_fraction": 0.5196581197, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067276593032, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7727549850615367}}
{"text": "@symbol_func function K_BS(cur_reactor::AbstractReactor)\n  cur_K = 4.879\n\n  cur_K *= K_n(cur_reactor)\n\n  cur_K *= 1 + cur_reactor.kappa_95 ^ 2\n\n  cur_K /= 2\n\n  cur_K *= sqrt(cur_reactor.epsilon) ^ 5\n\n  cur_K *= _C_B(cur_reactor)\n\n  cur_K\nend\n\n@symbol_func function _C_B(cur_reactor::AbstractReactor)\n  cur_nu_n = cur_reactor.nu_n\n  cur_nu_T = cur_reactor.nu_T\n\n  cur_func = function (cur_rho)\n    cur_value = 1.0 - cur_rho ^ 2\n\n    cur_value ^= cur_nu_n + cur_nu_T - 1\n\n    cur_value *= sqrt(cur_rho) ^ 5\n\n    cur_value /= b_p(cur_reactor.gamma, cur_rho)\n\n    cur_value\n  end\n\n  cur_reactor.is_symbolic &&\n    ( cur_func = cur_func(rho_sym) )\n\n  cur_C_B = norm_int(cur_func)\n\n  cur_C_B *= 1 + cur_nu_n\n\n  cur_C_B *= 1 + cur_nu_T\n\n  cur_C_B *= cur_nu_n + 0.054 * cur_nu_T\n\n  cur_C_B\nend\n", "meta": {"hexsha": "f5a814684fb08bd19c57bd36144100503ac8be31", "size": 786, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/methods/reactors/coefficients/k_bs.jl", "max_stars_repo_name": "djsegal/Fusion.jl", "max_stars_repo_head_hexsha": "a0540fbf3345a778965fa092e9e56907a44c6521", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-12-31T10:16:41.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-13T22:41:17.000Z", "max_issues_repo_path": "src/methods/reactors/coefficients/k_bs.jl", "max_issues_repo_name": "djsegal/Fusion.jl", "max_issues_repo_head_hexsha": "a0540fbf3345a778965fa092e9e56907a44c6521", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2017-04-11T05:06:15.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-23T05:06:33.000Z", "max_forks_repo_path": "src/methods/reactors/coefficients/k_bs.jl", "max_forks_repo_name": "djsegal/Fussy.jl", "max_forks_repo_head_hexsha": "a0540fbf3345a778965fa092e9e56907a44c6521", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-04-26T16:58:21.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-27T15:25:51.000Z", "avg_line_length": 17.0869565217, "max_line_length": 56, "alphanum_fraction": 0.6781170483, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075701109193, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7727395827905066}}
{"text": "# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see\n# that the 6th prime is 13.\n#\n# What is the 10,001st prime number?\n\nusing ProjectEulerSolutions\n\n# Run Sieve of Eratosthenes to get primes.  Estimate the value of the n'th\n# prime to be ~x, where x / log(x) < n.\nfunction p007solution(n::Integer=3)::Integer\n\n    # Roughly estimate the value of the n'th prime\n    x = floor(Integer, n^(1.2))\n    while x / log(x) < n\n        x += n\n    end\n\n    res = sieve_eratosthenes(x)\n    return res[n]\nend\n\np007 = Problems.Problem(p007solution)\n\nProblems.benchmark(p007, 10_001)", "meta": {"hexsha": "3546982a4f08220f988daa56bc200a35ede3a936", "size": 593, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/007.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/007.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/007.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7083333333, "max_line_length": 76, "alphanum_fraction": 0.671163575, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.959154282922475, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7727255645215798}}
{"text": "# calculate probability by \n# gaussian distribution pdf\n# plot as 2d-contour\n# 3 different contours\n\nmodule MultiGaussDist\n    using Plots, Base.Iterators, LinearAlgebra\n    pyplot()\n    \n    function pdf(x, mu, cov_mat)\n        # determinant\n        det_mat = det(cov_mat)\n\n        diff_x = x - mu\n        return exp(-((diff_x'/cov_mat)*diff_x)/2)/(2*pi*sqrt(det_mat))\n    end\n\n    function main(is_test=false)\n        # x-y grid\n        vx = 0:200\n        vy = 0:100\n\n        # mu, covariance matrix\n        # contour a\n        mu_a = [50; 50]\n        cov_a = [50 0; 0 100]\n        # contour b\n        mu_b = [100; 50]\n        cov_b = [125 0; 0 25]\n        # contour c\n        mu_c = [150; 50]\n        cov_c = [100 -25*sqrt(3); -25*sqrt(3) 50]\n\n        # probability density\n        # contour a\n        z_a = [pdf([x; y], mu_a, cov_a) for x in vx, y in vy]\n        # contour b\n        z_b = [pdf([x; y], mu_b, cov_b) for x in vx, y in vy]\n        # contour c\n        z_c = [pdf([x; y], mu_c, cov_c) for x in vx, y in vy]\n\n        # plot contours\n        contour(vx, vy, z_a', c=:haline, aspect_ratio=:equal)\n        contour!(vx, vy, z_b', c=:haline, aspect_ratio=:equal)\n        contour!(vx, vy, z_c', c=:haline, aspect_ratio=:equal)\n        \n        if is_test == false\n            save_path = joinpath(split(@__FILE__, \"src\")[1], \"src/prob_stats/multi_dim_gauss_dist/multiple_gauss_dist/multiple_gauss_dist.png\")\n            savefig(save_path)\n        end\n    end\nend", "meta": {"hexsha": "b723035e9ee8a53c62655bd3ad39e4f8ee5b6f48", "size": 1471, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/prob_stats/multi_dim_gauss_dist/multiple_gauss_dist/multiple_gauss_dist.jl", "max_stars_repo_name": "ShisatoYano/JuliaAutonomy", "max_stars_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2021-03-10T12:43:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T16:40:19.000Z", "max_issues_repo_path": "src/prob_stats/multi_dim_gauss_dist/multiple_gauss_dist/multiple_gauss_dist.jl", "max_issues_repo_name": "ShisatoYano/JuliaAutonomy", "max_issues_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/prob_stats/multi_dim_gauss_dist/multiple_gauss_dist/multiple_gauss_dist.jl", "max_forks_repo_name": "ShisatoYano/JuliaAutonomy", "max_forks_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-14T02:46:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T09:19:40.000Z", "avg_line_length": 28.2884615385, "max_line_length": 143, "alphanum_fraction": 0.5486063902, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576265, "lm_q2_score": 0.8056321819811829, "lm_q1q2_score": 0.7727255596887036}}
{"text": "function rotation_matrix(theta, ax)\n    x,y,z = LinearAlgebra.normalize(ax)\n    c = cos(theta)\n    s = sin(theta)\n    R = [(c+x^2*(1-c)) (x*y*(1-c)-s*z) (z*x*(1-c)+s*y);\n         (x*y*(1-c)+s*z) (c+y^2*(1-c)) (z*y*(1-c)-s*x);\n         (x*z*(1-c)-s*y) (y*z*(1-c)+s*x) (c+z^2*(1-c))]\n    return R\nend\nfunction parallel_transport(coordinate::Matrix{T_Number}) where {T_Number<:Number}\n    r = copy(coordinate)\n    n_points = size(r, 1)\n    if size(r, 2) == 2\n        r = cat(r, zeros(eltype(r), size(r, 1)), dims = 2)\n    end\n    t = 1.0:size(r,1)\n    dt = (maximum(t) - minimum(t)) / length(r)\n    dr = gradient(r)\n    ddr = gradient(dr)\n    dddr = gradient(ddr)\n\n\n    T = similar(dr)\n    N = similar(dr)\n    B = similar(dr)\n    T[1, :] = LinearAlgebra.normalize(dr[1, :])\n    B[1, :] = LinearAlgebra.normalize([T[1,2], -T[1,1], 0 ])\n    N[1, :] = LinearAlgebra.normalize(cross(B[1, :], T[1, :]))\n    for i = 2:n_points\n        T[i, :] = LinearAlgebra.normalize(dr[i, :])\n        b_ = cross(T[i-1,:],T[i,:])\n        if isapprox(norm(b_),0)\n            B[i, :] = B[i-1,:]\n        else\n            b_ = LinearAlgebra.normalize(b_)\n            phi = acos(dot(T[i-1,:],T[i,:]))\n            R = rotation_matrix(phi,b_)\n            B[i, :] = R * B[i-1,:]\n        end\n        N[i, :] = LinearAlgebra.normalize(cross(B[i, :], T[i, :]))\n    end\n\n\n    ds = Array{eltype(dr),1}(undef, n_points)\n    curvature = similar(ds)\n    torsion = similar(ds)\n\n    for i in eachindex(ds)\n        selected_dr = dr[i, :]\n        selected_ddr = ddr[i, :]\n        selected_dddr = dddr[i, :]\n        ds[i] = norm(selected_dr)\n\n        dr_cross_ddr = cross(selected_dr, selected_ddr)\n        curvature_num = norm(dr_cross_ddr) # || dr X ddr ||\n        curvature_denom = norm(selected_dr)^3 # || dr ||^3\n        curvature[i] = curvature_num / curvature_denom\n\n        torsion_num = dot(dr_cross_ddr, selected_dddr) # (dr X ddr) . dddr\n        torsion_denom = norm(dr_cross_ddr)^2 # || dr X ddr ||^2\n        torsion[i] = torsion_num / torsion_denom\n    end\n    speed = ds ./ dt\n    return T,N,B,curvature,torsion,speed\nend\n", "meta": {"hexsha": "33a7e140aa4b6a650f2c1074acc54966c740a4e2", "size": 2091, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/parallel_transport.jl", "max_stars_repo_name": "yusri-dh/MVApp.jl", "max_stars_repo_head_hexsha": "c5694839d2229982b0ae5cec7c18390019222c7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-28T07:25:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T11:59:15.000Z", "max_issues_repo_path": "src/parallel_transport.jl", "max_issues_repo_name": "yusri-dh/MovingFrame.jl", "max_issues_repo_head_hexsha": "1be0d7e4ec1f20d898dfbaf9f85e5b9ac86c7b6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/parallel_transport.jl", "max_forks_repo_name": "yusri-dh/MovingFrame.jl", "max_forks_repo_head_hexsha": "1be0d7e4ec1f20d898dfbaf9f85e5b9ac86c7b6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6818181818, "max_line_length": 82, "alphanum_fraction": 0.5308464849, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154281754899, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7727255591048435}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction _polrec(radius::T, angle::T, degrees::Bool) where {T<:AbstractFloat}\n    if degrees\n        angle = deg2rad(angle)\n    end\n    s, c = sincos(angle)\n    return radius * c, radius * s\nend\n\n\"\"\"\n    polrec(radius, angle[, degrees=true]) -> x, y\n\n### Purpose ###\n\nConvert 2D polar coordinates to rectangular coordinates.\n\n### Explanation ###\n\nThis is the partial inverse function of `recpol`.\n\n### Arguments ###\n\n* `radius`: radial coordinate of the point.  It may be a scalar or an array.\n* `angle`: the angular coordinate of the point.  It may be a scalar or an array\n  of the same lenth as `radius`.\n* `degrees` (optional boolean keyword): if `true`, the `angle` is assumed to be\n  in degrees, otherwise in radians.  It defaults to `false`.\n\nMandatory arguments can also be passed as the 2-tuple `(radius, angle)`, so that\nit is possible to execute `recpol(polrec(radius, angle))`.\n\n### Output ###\n\nA 2-tuple `(x, y)` with the rectangular coordinate of the input.  If `radius`\nand `angle` are arrays, `x` and `y` are arrays of the same length as `radius`\nand `angle`.\n\n### Example ###\n\nGet rectangular coordinates \\$(x, y)\\$ of the point with polar coordinates \\$(r,\n\\\\varphi) = (1.7, 227)\\$, with angle \\$\\\\varphi\\$ expressed in degrees.\n\n```jldoctest\njulia> using AstroLib\n\njulia> x, y = polrec(1.7, 227, degrees=true)\n(-1.1593972121062475, -1.2433012927525897)\n```\n\n\"\"\"\npolrec(radius::Real, angle::Real; degrees::Bool=false) =\n    _polrec(promote(float(radius), float(angle))..., degrees)\n\npolrec(r_a::Tuple{Real, Real}; degrees::Bool=false) = polrec(r_a...,\n                                                             degrees=degrees)\n\nfunction polrec(r::AbstractArray{R}, a::AbstractArray{A};\n                degrees::Bool=false) where {R<:Real, A<:Real}\n    @assert length(r) == length(a)\n    typer = float(R)\n    x = similar(r, typer)\n    y = similar(r, typer)\n    for i in eachindex(r)\n        x[i], y[i] = polrec(r[i], a[i], degrees=degrees)\n    end\n    return x, y\nend\n", "meta": {"hexsha": "94e6b0cfc74f712a5fc468bbcdfb137816ae780c", "size": 2086, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polrec.jl", "max_stars_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_stars_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2016-09-11T14:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T20:45:36.000Z", "max_issues_repo_path": "src/polrec.jl", "max_issues_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_issues_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 64, "max_issues_repo_issues_event_min_datetime": "2017-01-19T21:03:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:27:46.000Z", "max_forks_repo_path": "src/polrec.jl", "max_forks_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_forks_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:11:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:55:21.000Z", "avg_line_length": 29.8, "max_line_length": 80, "alphanum_fraction": 0.6404602109, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.7727186138361455}}
{"text": "# # Comparison between SSA and SA\n\n#=\nIn this example, I compare changes in the SA and in the SSA for a matrix that varies\nparametrically.\n=#\n\n# ### Initialization\nusing Plots,NamedColors\nusing LinearAlgebra\nusing Random\nusing SmoothedSpectralAbscissa ; const SSA=SmoothedSpectralAbscissa\nRandom.seed!(0);\n\n# the function below generates a random non-normal matrix\nfunction rand_nonnormal(n::Integer,(ud::Real)=1.01)\n  mat = randn(n,n) ./ sqrt(n)\n  sh = schur(mat)\n  upd = diagm(0=>fill(1.0,n),1=>fill(ud,n-1))\n  return sh.vectors*upd*sh.Schur*inv(upd)*sh.vectors'\nend;\n\n# ### Example matrix generated  parametrically\nn = 100\nmat1 = rand_nonnormal(n,0.8)\nmat2 = randn(n,n) ./ sqrt(n)\nmat(θ) = @. θ*mat1 + (1-θ)*mat2\n\nthetas = range(0.0,1.0;length=100);\n\n# Now we look at the spectral abscissa as a function of the parameter\n## #src\n\n# ### Set ϵ for the SSA\nssa_eps_vals = [0.005,0.001,0.0005];\n\n# ### Compute and plot the SA\nsas = map(θ->SSA.spectral_abscissa(mat(θ)),thetas)\nplt=plot(thetas,sas ; color=:black, linewidth=3,lab=\"SA\",\n  xlabel=\"θ\",ylabel=\"SA value\",leg=:top)\n\n# ### Compute and plot the SSA\nmycols=cgrad([colorant\"DarkGreen\",colorant\"orange\"])\nfor ϵ in ssa_eps_vals\n  ssas = map(θ->SSA.ssa(mat(θ),ϵ),thetas)\n  plot!(plt,thetas,ssas ; linewidth=2.5 ,\n    lab=\"SSA $ϵ\",palette=mycols)\nend\nplot!(plt,xlabel=\"θ\",ylabel=\"SA/SSA value\",leg=:top)\n\n#=\nThis plot shows that the SSA is a smoothed version of the SA, and\ncoverges to it as as ϵ decreases.\nMoreover if we reduce the SSA parametrically, we find (approximately) a good minimum for\nthe SA, as well.\n=#\n\n\n# Literate.markdown(\"examples/01_show_ssa.jl\",\"docs/src\";documenter=true,repo_root_url=\"https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl/blob/master\") #src\n", "meta": {"hexsha": "3a99426db12c4bbc6cf786592b538e0734b08bbd", "size": 1736, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/01_show_ssa.jl", "max_stars_repo_name": "dylanfesta/SmoothedSpectralAbscissa.jl", "max_stars_repo_head_hexsha": "c76945b165c6f63a4c2d04596e575031765e5641", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/01_show_ssa.jl", "max_issues_repo_name": "dylanfesta/SmoothedSpectralAbscissa.jl", "max_issues_repo_head_hexsha": "c76945b165c6f63a4c2d04596e575031765e5641", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-02-21T00:56:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-04T22:57:50.000Z", "max_forks_repo_path": "examples/01_show_ssa.jl", "max_forks_repo_name": "dylanfesta/SmoothedSpectralAbscissa.jl", "max_forks_repo_head_hexsha": "c76945b165c6f63a4c2d04596e575031765e5641", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9333333333, "max_line_length": 164, "alphanum_fraction": 0.7148617512, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.8740772368049822, "lm_q1q2_score": 0.7727186019338844}}
{"text": "using Random, Plots, StatsPlots, Distributions, DataFrames, Printf, SpecialFunctions\n# Define student t distribution with loc and scale parameter\n# https://juliastats.org/Distributions.jl/v0.21/univariate/#Distributions.LocationScale\n# https://discourse.julialang.org/t/scale-and-location-to-tdist-in-distributions/74360\n# p(x|\\nu, \\mu, \\sigma^2) = \\frac{\\Gamma(\\frac{\\nu+1}{2})}{\\Gamma(\\frac{\\nu}{2})\\sqrt{\\pi\\nu\\sigma^2}}\\left[1 + \\frac{(x-\\mu)^2}{\\nu\\sigma^2}\\right]^{-\\frac{\\nu+1}{2}}\n\"\"\"\nt-distribution probability density function from definition.\n\"\"\"\nfunction tdist_from_def(x, ν, μ, σ)\n    return (gamma((ν+1)/2) / (gamma(ν/2) * sqrt(pi*ν*σ^2)) * (1 + (x-μ)^2/(ν*σ^2))^(-(ν+1)/2))\nend\n\n\"\"\"\nt-distribution probability density function usinf Distributions.LocationScale\n\"\"\"\nfunction tdist_from_LocationScale(ν, μ, σ)\n    return LocationScale(μ, σ, TDist(ν))\nend\n\n# tdist_from_def(5, 7, 10, 0.7)\n# pdf(tdist_from_LocationScale(7, 10, 0.7), 5)\n\n# Define calculation of posterior\n\"\"\"\nConjugate Priors for Normal Dist parameters (μ|σ^2 ~ Normal, σ^2 ~ InverseGamma)\n\n    Inputs\n    ------\n    data: data (0 or 1)\n    α0: shape parameter of prior (Gamma dist)\n    β0: inversed scale parameter of prior (Gamma dist)\n    prob: credible interval probability (0 < prob < 1)\n\n    Outputs\n    -------\n    results: posterior summary stats table (DataFrames)\n    α_star: shape parameter of posterior (Gamma dist)\n    β: inversed scale parameter (1/θ) of posterior (Gamma dist)\n\n\"\"\"\nfunction gaussian_stats(data, μ0, n0, ν0, λ0, prob)\n    # posterior\n    n = size(data)[1]\n    mean_data = mean(data)\n    ssd_data = (n-1) * var(data) # var is unbiased variance scaled by n-1\n    n_star = n + n0\n    μ_star = (n * mean_data + n0 * μ0) / n_star\n    ν_star = n + ν0\n    λ_star = ssd_data + (n * n0 / n_star) * (μ0 - mean_data)^2 + λ0\n    τ_star = sqrt(λ_star / (ν_star * n_star))\n\n    posterior_σ_sq = InverseGamma(ν_star/2, λ_star/2)\n    marginal_posterior_μ = LocationScale(μ_star, τ_star, TDist(ν_star))\n\n    sd_μ = std(marginal_posterior_μ)\n    ci_μ_upper = quantile(marginal_posterior_μ, prob - (1-prob)/2)\n    ci_μ_lower = quantile(marginal_posterior_μ, (1-prob)/2)\n    ci_μ = [ci_μ_lower, ci_μ_upper]\n    mean_σ_sq = mean(posterior_σ_sq)\n    mode_σ_sq = mode(posterior_σ_sq)\n    median_σ_sq = median(posterior_σ_sq)\n    sd_σ_sq = std(posterior_σ_sq)\n    ci_σ_sq_upper = quantile(posterior_σ_sq, prob - (1-prob)/2)\n    ci_σ_sq_lower = quantile(posterior_σ_sq, (1-prob)/2)\n    ci_σ_sq = [ci_σ_sq_lower, ci_σ_sq_upper]\n\n    stats_μ = reshape([μ_star, μ_star, μ_star, sd_μ, ci_μ], 1, 5)\n    stats_σ_sq = reshape([mean_σ_sq, median_σ_sq, mode_σ_sq, sd_σ_sq, ci_σ_sq], 1, 5)\n\n    stats_string = [\"Mean\", \"Median\", \"Mode\", \"SD\", \"CI\"]\n    results = DataFrame([stats_μ; stats_σ_sq], stats_string)\n    return results, marginal_posterior_μ, posterior_σ_sq\nend\n\n# Generate moc data\nμ = 1.0\nσ = 2.0\nn = 50\nRandom.seed!(99)\ndata = rand(Normal(μ, σ), n)\n# histogram(data, bins=20)\n\n# Set prior\nμ0 = 0.0\nn0 = 0.2\nν0 = 5.0\nλ0 = 7.0\nτ0 = sqrt(λ0 / (ν0 * n0))\n\nprior_σ_sq = InverseGamma(ν0/2, λ0/2)\nmarginal_prior_μ = LocationScale(μ0, τ0, TDist(ν0))\n\n# Calculate posterior statistics\nprob = 0.95\nresults, marginal_posterior_μ, posterior_σ_sq = gaussian_stats(data, μ0, n0, ν0, λ0, prob)\nprint(results)\n\n# Visualize Posterior\nl = @layout [grid(1, 2)]\n\np1 = plot(\n    marginal_prior_μ, xlims=(-6, 6), ylims=(0, 1.55), xlabel=\"μ\", ylabel=\"Probability Density\", \n    label=@sprintf(\"prior: T(ν=%.1f, μ=%.1f, σ^2=%.1f)\", params(params(marginal_prior_μ)[3])[1], params(marginal_prior_μ)[1], params(marginal_prior_μ)[2]), linestyle=:dash)\nplot!(marginal_posterior_μ, label=@sprintf(\"posterior: T(ν=%.1f, μ=%.1f, σ^2=%.1f)\", params(params(marginal_posterior_μ)[3])[1], params(marginal_posterior_μ)[1], params(marginal_posterior_μ)[2]), linestyle=:solid)\n\np2 = plot(\n    prior_σ_sq, xlims=(0, 10), ylims=(0, 0.65), xlabel=\"σ^2\", ylabel=\"Probability Density\", \n    label=@sprintf(\"prior: InverseGamma(α=%.1f, θ=%.1f)\", params(prior_σ_sq)[1], params(prior_σ_sq)[2]), linestyle=:dash)\nplot!(posterior_σ_sq, label=@sprintf(\"posterior: InverseGamma(α=%.1f, θ=%.1f)\", params(posterior_σ_sq)[1], params(posterior_σ_sq)[2]), linestyle=:solid)\n\nplot(p1, p2, laypout=l)\n# μの推定ヘタクソじゃね?", "meta": {"hexsha": "531175142e17a8199f48ba84e7d7ea87018b1726", "size": 4243, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jlbayes_conjugate_gaussian.jl", "max_stars_repo_name": "hessihan/julia_bayes_intro", "max_stars_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jlbayes_conjugate_gaussian.jl", "max_issues_repo_name": "hessihan/julia_bayes_intro", "max_issues_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jlbayes_conjugate_gaussian.jl", "max_forks_repo_name": "hessihan/julia_bayes_intro", "max_forks_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8839285714, "max_line_length": 213, "alphanum_fraction": 0.6827716239, "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7726946214351241}}
{"text": "\r\nstruct UnscentedKF\r\n\txk::Vector\r\n\txp::Vector\r\n\tP::AbstractMatrix\r\n\tK::AbstractMatrix\r\n\tw_mean::Vector\r\n\tw_cov::Vector\r\n\tX::AbstractMatrix\r\n\tw_mean_::Vector\r\n\tw_cov_::Vector\r\n\tX_::AbstractMatrix\r\n\tPyy::AbstractMatrix\r\n\tPxy::AbstractMatrix\r\n\tfilter::SquareRootFilter\r\nend\r\n\r\n\"\"\"\r\n\tsol = unscented_kalman(\r\n        y, x₀, f, g, P, R, Q;\r\n        α=1e-3, κ=1.0, β=2.0, sqrt_filter=CholeskySqrt(),\r\n        )\r\n\r\nPerforms the non-linear adaptive unscented Kalman filter algorithm for the estimation of\r\na state y. This is the additive (zero mean) noise case.\r\n\r\ny:  Vector with one measurement (observation) of m = length(x) variables\r\nx₀: A priori estimation of the variables\r\nf:\tState Model\r\ng:\tMeasurement Model\r\nP:  Initial predicted process covariance matrix\r\nR:  Measurement (observable) covariance matrix\r\nQ:  Process noise covariance matrix\r\n\r\nα:  Distance between the sample point and mean point: 1 ≤ α ≤ 1e-3 (default)\r\nκ:  Scaling factor (default 1.0)\r\nβ:  Prior knowledge of the distribution (default 2.0, Gaussian process)\r\n\r\nsqrt_filter: Square root filtering technique for the covariance matrix.\r\n\t\t\t Accepted values are: CholeskyModSqrt() (default), SVDSqrt(), CholeskySqrt()\r\n\r\nsol: UnscentedKF type\r\n\txk:  \t Kalman filter state estimation\r\n\txp:  \t Predicted state estimate\r\n    P:   \t Process covariance matrix a posteriori\r\n    K:   \t Kalman gain\r\n\tw_mean:  Weights of the mean\r\n\tw_cov: \t Weights of the covariance\r\n\tS:\t\t Sigma matrix, size = (num_variables, 2*num_variables+1)\r\n\tw_mean_: Weights of the mean expanded (updated process)\r\n\tw_cov_:  Weights of the covariance expanded (updated process)\r\n\tS_:      Sigma matrix expanded (updated process), size = (#variables, 2*(2*num_variables+1))\r\n\tPyy:     Covariance matrix measurement upate\r\n\tPxy:\t Cross-covariance matrix measurement upate\r\n\tfilter:  Filter used for the covariance matrix\r\n\r\n\"\"\"\r\nfunction unscented_kalman(\r\n\tx::Vector,\r\n    x₀::Vector,\r\n    f::Function,\r\n    g::Function,\r\n    P::AbstractMatrix,\r\n\tR::AbstractMatrix,\r\n\tQ::AbstractMatrix;\r\n\tα::Real=1e-3,\r\n\tκ::Real=3-length(x),\r\n\tβ::Real=2.0,\r\n\tsqrt_filter::SquareRootFilter=CholeskyModSqrt(),\r\n\t)\r\n\r\n\tm = length(x₀)\r\n\r\n\t## Predict process\r\n\t# Sigma points and weights\r\n\t_X = _sigma_points(x₀, P, sqrt_filter, α, κ, β, m)\r\n\tw_m, w_c = _mean_covariance_weights(m; α=α, β=β, κ=κ)\r\n\t# Propagate sigma points through the non-linear function\r\n\tX_ = _propagate_sigma_nlf(f, _X)\r\n\t# Predicted state estimation, a priori,\r\n\tx̂ = _estimation(X_, w_m)\r\n\t# Predicted process covariance matrix, a priori\r\n\tP_ = _covariance_matrix_ukf(P, X_, x̂, w_c, Q)\r\n\r\n\t## Update process\r\n\t# Sigma points a posteriori\r\n\t_Y = _sigma_points(X_, R, sqrt_filter, α, κ, β, size(X_, 1))\r\n\tw_m_, w_c_ = _mean_covariance_weights(2*m; α=α, β=β, κ=κ)\r\n\t# Measurement estimation\r\n\tY_ = _propagate_sigma_nlf(g, _Y)\r\n\tŷ = _estimation(Y_, w_m_)\r\n\t# Covariance matrix\r\n\tPyy = _covariance_matrix_ukf(P, Y_, ŷ, w_c_, R)\r\n\t# Cross-covariance matrix\r\n\tPxy = _covariance_matrix_ukf(P, _Y, x̂, Y_, ŷ, w_c_)\r\n\t# Kalman gain\r\n\tK = _kalman_gain(P, Pxy, Pyy)\r\n\t# State estimation measurement update (a posteriori)\r\n\txk = muladd(K, (x .- ŷ), x̂)\r\n\t# Covariance matrix measurement update (a posteriori)\r\n\tP_ .= P_ .- K*Pyy*K'\r\n\r\n\treturn UnscentedKF(\r\n\t\tvec(xk), vec(x̂),\r\n\t\tP_, K,\r\n\t\tvec(w_m), vec(w_c), X_,\r\n\t\tvec(w_m_), vec(w_c_), Y_,\r\n\t\tPyy, Pxy,\r\n\t\tsqrt_filter,\r\n\t\t)\r\nend\r\n\r\nfunction _sigma_points(\r\n\tx::Vector, P::AbstractMatrix, filter, α::Real, β::Real, κ::Real, m::Int64,\r\n\t)\r\n\tλ = α^2 * (m + κ) - m\r\n\tPi = _square_root_filter(filter, sqrt(m + λ) .* P)\r\n\treturn hcat(x, x .+ Pi, x .- Pi)\r\nend\r\n\r\nfunction _sigma_points(\r\n\tX::Matrix, P::AbstractMatrix, filter, α::Real, β::Real, κ::Real, m::Int64,\r\n\t)\r\n\tλ = α^2 * (m + κ) - m\r\n\tPi = _square_root_filter(filter, sqrt(m + λ).*P)\r\n\treturn hcat(X, X[:,1] .+ Pi, X[:,1] .- Pi)\r\nend\r\n\r\nfunction _mean_covariance_weights(m::Int64; α::Real=1e-3, β::Real=2.0, κ::Real=1.0)\r\n\tλ = α^2 * (m + κ) - m\r\n\tw_m = ones(2*m + 1) .* 0.5 / (m + λ) # mean weights\r\n\tw_c = copy(w_m) # covariance weights\r\n\tw_m[1] = λ / (m + λ)\r\n\tw_c[1] += one(β) + β - α^2\r\n\treturn w_m, w_c\r\nend\r\n\r\n_propagate_sigma_nlf(f::Function, χ::Array) = (x -> f(x))(χ)\r\n\r\n_estimation_product(X::Matrix, w::Vector) = ((A, x) -> x' .* A)(X, w)\r\nfunction _estimation(X::Matrix, w::Vector)\r\n\treturn vec(sum(_estimation_product(X::Matrix, w::Vector), dims=2))\r\nend\r\n\r\nfunction _covariance_matrix_ukf(P::AbstractMatrix, X::Matrix, x::Vector, w::Vector, N)\r\n\tA = X .- x\r\n\treturn _return_type(P, w' .* A*A' .+ N)\r\nend\r\n\r\nfunction _covariance_matrix_ukf(\r\n\tP::AbstractMatrix, X::Matrix, x::Vector, Y::Matrix, y::Vector, w::Vector,\r\n\t)\r\n\treturn _return_type(P, (w' .* (X .- x)) * (Y .- y)')\r\nend\r\n\r\nfunction _kalman_gain(P::AbstractMatrix, Pxy::AbstractMatrix, Pyy::AbstractMatrix)\r\n\tF = qr(Pyy)\r\n\treturn _return_type(P, F.R \\ (F.Q' * Pxy))\r\nend\r\n", "meta": {"hexsha": "af021af5be8ca50e985380ffccaffd3f5f7f8254", "size": 4831, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "UnscentedKalmanFilter.jl", "max_stars_repo_name": "lnacquaroli/KalmanFilter.jl", "max_stars_repo_head_hexsha": "9746b6b1079c499323f777ecf7077a995ec49f78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "UnscentedKalmanFilter.jl", "max_issues_repo_name": "lnacquaroli/KalmanFilter.jl", "max_issues_repo_head_hexsha": "9746b6b1079c499323f777ecf7077a995ec49f78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UnscentedKalmanFilter.jl", "max_forks_repo_name": "lnacquaroli/KalmanFilter.jl", "max_forks_repo_head_hexsha": "9746b6b1079c499323f777ecf7077a995ec49f78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.19375, "max_line_length": 94, "alphanum_fraction": 0.6619747464, "num_tokens": 1582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7726946194139704}}
{"text": "#############\n# This demonstrates the Chebyshev transform and inverse transform,\n# explaining precisely the normalization and points\n#############\n\nusing FastTransforms\n\n# first kind points -> first kind polynomials\nn = 20\np_1 = chebyshevpoints(Float64, n; kind=1)\nf = exp.(p_1)\nf̌ = chebyshevtransform(f; kind=1)\n\nf̃ = x -> [cos(k*acos(x)) for k=0:n-1]' * f̌\nf̃(0.1) ≈ exp(0.1)\n\n# first kind polynomials -> first kind points\nichebyshevtransform(f̌; kind=1) ≈ exp.(p_1)\n\n# second kind points -> first kind polynomials\np_2 = chebyshevpoints(Float64, n; kind=2)\nf = exp.(p_2)\nf̌ = chebyshevtransform(f; kind=2)\n\nf̃ = x -> [cos(k*acos(x)) for k=0:n-1]' * f̌\nf̃(0.1) ≈ exp(0.1)\n\n# first kind polynomials -> second kind points\nichebyshevtransform(f̌; kind=2) ≈ exp.(p_2)\n\n\n# first kind points -> second kind polynomials\nn = 20\np_1 = chebyshevpoints(Float64, n; kind=1)\nf = exp.(p_1)\nf̌ = chebyshevutransform(f; kind=1)\nf̃ = x -> [sin((k+1)*acos(x))/sin(acos(x)) for k=0:n-1]' * f̌\nf̃(0.1) ≈ exp(0.1)\n\n# second kind polynomials -> first kind points\nichebyshevutransform(f̌; kind=1) ≈ exp.(p_1)\n\n\n# second kind points -> second kind polynomials\np_2 = chebyshevpoints(Float64, n; kind=2)[2:n-1]\nf = exp.(p_2)\nf̌ = chebyshevutransform(f; kind=2)\nf̃ = x -> [sin((k+1)*acos(x))/sin(acos(x)) for k=0:n-3]' * f̌\nf̃(0.1) ≈ exp(0.1)\n\n# second kind polynomials -> second kind points\nichebyshevutransform(f̌; kind=2) ≈ exp.(p_2)\n", "meta": {"hexsha": "313467c5b50825da7de0bb5974c666d1c2ebe2c7", "size": 1412, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/chebyshev.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/FastTransforms.jl-057dd010-8810-581a-b7be-e3fc3b93f78c", "max_stars_repo_head_hexsha": "766d3076b4e3b32206169a4310d4211c2e0a1902", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-15T03:23:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T03:23:28.000Z", "max_issues_repo_path": "examples/chebyshev.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/FastTransforms.jl-057dd010-8810-581a-b7be-e3fc3b93f78c", "max_issues_repo_head_hexsha": "766d3076b4e3b32206169a4310d4211c2e0a1902", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/chebyshev.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/FastTransforms.jl-057dd010-8810-581a-b7be-e3fc3b93f78c", "max_forks_repo_head_hexsha": "766d3076b4e3b32206169a4310d4211c2e0a1902", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.641509434, "max_line_length": 66, "alphanum_fraction": 0.6529745042, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954106, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.772694615651461}}
{"text": "# Computes A^(⊗p) = A ⊗ A ⊗ ... ⊗ A\n# where ⊗ is the Kronecker product\n# Since p > 0, B will be kron'd at least once so it will be a Matrix{T}\n# This is not easy to guess for Julia inference so I annotate the return type\nfunction (kronpow(A::MT, p)::MT) where MT <: AbstractMatrix\n    @assert p > 0\n    B = 1\n    C = A\n    bitmap = 1\n    while bitmap <= p\n        if (bitmap & p) != 0\n            B = kron(B, C)\n        end\n        C = kron(C, C)\n        bitmap <<= 1\n    end\n    B\nend\n", "meta": {"hexsha": "4d5dfebec69c8aff6e4063056cd58ac52479cb24", "size": 486, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kronecker.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SwitchOnSafety.jl-ceb7f16a-07bf-5f4a-9354-b68f01b1610f", "max_stars_repo_head_hexsha": "e9fefe2cb8f45f27ed9ea95d3edee725e8b85122", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2017-11-24T10:29:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T15:10:52.000Z", "max_issues_repo_path": "src/kronecker.jl", "max_issues_repo_name": "blegat/SwitchedSystems.jl", "max_issues_repo_head_hexsha": "88c6c64f7499de1fc8b039cfc2da393778f1e4c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2017-10-02T09:26:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T15:14:00.000Z", "max_forks_repo_path": "src/kronecker.jl", "max_forks_repo_name": "blegat/SwitchedSystems.jl", "max_forks_repo_head_hexsha": "88c6c64f7499de1fc8b039cfc2da393778f1e4c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-11-29T13:44:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T11:08:56.000Z", "avg_line_length": 25.5789473684, "max_line_length": 77, "alphanum_fraction": 0.5390946502, "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7726946153716633}}
{"text": "@doc \"\"\"\nA simple bisection solver. Included for backwards compatability with previous scripts.\nf is a function\na is one starting point\nb is another starting point\nf(a) and f(b) must have opposite signs.\nn is optional and is the number of iterations\n\"\"\"->function mybisect(f,a,b,n=50)\n## Introduction\n# Code from Introduction to Numerical Methods and Matlab Programming for\n# Engineers( P.19)\n# T. Young & M.J. Mohlenkamp\n# Ohio University\n\n\n# function [x e] = mybisect (f,a,b,n)\n# Does n iterations of the bisection method for a function f\n# Inputs : f -- a function\n# a,b -- left and right edges of the interval\n# n -- the number of bisections to do.\n# Outputs : x -- the estimated solution of f(x) = 0\n# e -- an upper bound on the error\n# evaluate at the ends and make sure there is a sign change\n## Code\nc = f(a)\nd = f(b)\nif (c*d > 0.0)\n    error(\"Function has same sign at both endpoints.\" )\nend\n\nfor i in 1:n\n    # find the middle and evaluate there\n    x = (a + b )/2;\n    y = f(x);\n\n    if (y == 0.0) # solved the equation exactly\n        e = 0;\n        break # jumps out of the for loop\n    end\n    # decide which half to keep , so that the signs at the ends differ\n    if (c*y < 0)\n        b=x;\n    else\n        a=x;\n    end\nend\n# set the best estimate for x and the error bound\nx = (a + b )/2;\ne = (b-a )/2;\n\n\nreturn x\nend\n", "meta": {"hexsha": "d1e9f5e9c544048c1a26cacfdbcaad571a9a2314", "size": 1334, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MyBisect.jl", "max_stars_repo_name": "EliMattingly22/MPI_Tools", "max_stars_repo_head_hexsha": "159b4afe8e3b5143598d67e48a9ac130fc062af4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MyBisect.jl", "max_issues_repo_name": "EliMattingly22/MPI_Tools", "max_issues_repo_head_hexsha": "159b4afe8e3b5143598d67e48a9ac130fc062af4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MyBisect.jl", "max_forks_repo_name": "EliMattingly22/MPI_Tools", "max_forks_repo_head_hexsha": "159b4afe8e3b5143598d67e48a9ac130fc062af4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-06T20:49:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T20:49:56.000Z", "avg_line_length": 24.7037037037, "max_line_length": 86, "alphanum_fraction": 0.6499250375, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8244619177503206, "lm_q1q2_score": 0.7726946093082022}}
{"text": "#==============================================================================\n    Code for solving the Hamiltonian Jacboi Bellman for\n\t   an basic model: ρv(a) = max_{c} u(c) + v'(a)[s(a)]\n\t   Where s(a) = w + ra - c(a)\n\n\tTranslated Julia code from Matlab code by Ben Moll:\n        http://www.princeton.edu/~moll/HACTproject.htm\n\n        Updated to Julia 1.0.0\n==============================================================================#\n\nusing Parameters, Distributions, Plots, SparseArrays, LinearAlgebra\n\nσ= 2.0 #\nρ = 0.05 #the discount rate\nr = 0.045 # the depreciation rate\nw = 0.1\n\nH = 500\na_min = -0.02\na_max = 1.0\n\na = LinRange(a_min, a_max, H)\na = convert(Array, a) # create grid for a values\nda = (a_max-a_min)/(H-1)\n\nmaxit = 10000\nε = 10e-6\n\nΔ = 1000\n\ndVf, dVb= [zeros(H,1) for i =1:2]\n\n#initial guess for V\nv0 = (w.+r.*a).^(1-σ)/(1-σ)/ρ\nv= v0\n\ndist=[]\n\nfor n=1:maxit\n\tV=v\n    #forward difference\n    dVf[1:H-1] = (V[2:H]-V[1:H-1])/da;\n    dVf[H]= 0;\n\n\t# backward difference\n\tdVb[2:H] = (V[2:H]-V[1:H-1])/da\n\tdVb[1] = (w.+r.*a_min).^(-σ) # the boundary condition\n\n\tI_concave = dVb .> dVf\n\n    # consumption and savings with forward difference\n    cf = dVf.^(-1/σ)\n    ssf = w.+r.*a-cf\n\n    # consumption and savings with backward difference\n\tcb = dVb.^(-1/σ)\n\tssb = w.+r.*a-cb\n\n    # consumption and savings at steady state\n    c0=w.+r.*a\n    dV0 =c0.^(-σ)\n\n    #look at the sign of the drift\n        #to choose forward or backward difference\n    If = ssf .> 0 # positive drift ⇒ forward difference\n    Ib = ssb .< 0  # negative drift ⇒ backward difference\n    I0 = (1.0.-If-Ib)\n\n    dV_Upwind = dVf.*If + dVb.*Ib + dV0.*I0\n\n     global c = dV_Upwind.^(-1/σ)\n     u = c.^(1-σ)/(1-σ)\n\n     # create the transition matrix\n     X = -min.(ssb,0)/da\n     Y = -max.(ssf,0)/da + min.(ssb,0)/da\n     Z = max.(ssf,0)/da\n\n\n     A = sparse(Diagonal(Y[:])) + [zeros(1,H); sparse(Diagonal(X[2:H])) zeros(H-1,1)] + [zeros(H-1,1) sparse(Diagonal(Z[1:H-1])); zeros(1,H)]\n     B = (ρ + 1/Δ)*sparse(I, H, H) - A\n\n     b = u + V/Δ\n     V = B\\b\n     V_change = V-v\n     global v= V\n\n\tpush!(dist,findmax(abs.(V_change))[1])\n\tif dist[n] .< ε\n\t\tprintln(\"Value Function Converged Iteration=\")\n\t\tprintln(n)\n\t\tbreak\n\tend\nend\n\nplot(dist, grid=false,\n\t\txlabel=\"Iteration\", ylabel=\"||V^{n+1} - V^n||\",\n\t\tylims=(-0.001,0.030),\n\t\tlegend=false, title=\"\")\npng(\"Convergence\")\n\n\nv_err = c.^(1-σ)/(1-σ) + dVb.*(w .+ r.*a -c) - ρ.*v\n\nplot(a, v_err, grid=false,\n\t\txlabel=\"k\", ylabel=\"Error in the HJB equation\",\n\t\txlims=(a_min,a_max),\n\t\tlegend=false, title=\"\")\npng(\"HJB_error\")\n\n\nplot(a, v, grid=false,\n\t\txlabel=\"a\", ylabel=\"V(a)\",\n\t\txlims=(a_min,a_max),\n\t\tlegend=false, title=\"\")\npng(\"Value_function_vs_a\")\n\nplot(a, c, grid=false,\n\t\txlabel=\"a\", ylabel=\"c(a)\",\n\t\txlims=(a_min,a_max),\n\t\tlegend=false, title=\"\")\npng(\"c(a)_vs_a\")\n\n# approximation at the borrowing constraint\na_dot = w.+ r.*a -c\n\nplot(a, a_dot, grid=false,\n\t\txlabel=\"a\", ylabel=\"s(a)\",\n\t\txlims=(a_min,a_max), title=\"\", label=\"s(a)\", legend=:bottomleft)\nplot!(a, zeros(H,1), label=\"\")\npng(\"stateconstraint\")\n", "meta": {"hexsha": "f28661c3a9888f252858152a22d021a8fe5c1c10", "size": 3048, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Moll_Code/Section15-General_Continuous_Time_Models/HJB_simple_implicit/HJB_simple_implicit.jl", "max_stars_repo_name": "chandlerlester/Radio_Free_Julia", "max_stars_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-02-26T11:52:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T12:41:38.000Z", "max_issues_repo_path": "Moll_Code/Section15-General_Continuous_Time_Models/HJB_simple_implicit/HJB_simple_implicit.jl", "max_issues_repo_name": "chandlerlester/Radio_Free_Julia", "max_issues_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Moll_Code/Section15-General_Continuous_Time_Models/HJB_simple_implicit/HJB_simple_implicit.jl", "max_forks_repo_name": "chandlerlester/Radio_Free_Julia", "max_forks_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-11T08:09:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-30T18:54:12.000Z", "avg_line_length": 22.9172932331, "max_line_length": 141, "alphanum_fraction": 0.5603674541, "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7726946081420841}}
{"text": "\"\"\"\n    Haversine(radius)\n\nThe haversine distance between two locations on a sphere of given `radius`.\n\nLocations are described with longitude and latitude in degrees.\nThe computed distance has the same units as that of the radius.\n\"\"\"\nstruct Haversine{T<:Real} <: Metric\n    radius::T\nend\n\nconst VecOrLengthTwoTuple{T} = Union{AbstractVector{T}, NTuple{2, T}}\n\nfunction (dist::Haversine)(x::VecOrLengthTwoTuple, y::VecOrLengthTwoTuple)\n    length(x) == length(y) == 2 || haversine_error()\n\n    @inbounds begin\n        # longitudes\n        Δλ = deg2rad(y[1] - x[1])\n\n        # latitudes\n        φ₁ = deg2rad(x[2])\n        φ₂ = deg2rad(y[2])\n    end\n\n    Δφ = φ₂ - φ₁\n\n    # haversine formula\n    a = sin(Δφ/2)^2 + cos(φ₁)*cos(φ₂)*sin(Δλ/2)^2\n\n    # distance on the sphere\n    2 * dist.radius * asin( min(√a, one(a)) ) # take care of floating point errors\nend\n\nhaversine(x::VecOrLengthTwoTuple, y::VecOrLengthTwoTuple, radius::Real) = Haversine(radius)(x, y)\n\n@noinline haversine_error() = throw(ArgumentError(\"expected both inputs to have length 2 in Haversine distance\"))\n", "meta": {"hexsha": "8a08cffe8bf242b5fe795e12adcd94fdcfa339a8", "size": 1073, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/haversine.jl", "max_stars_repo_name": "Sh4pe/Distances.jl", "max_stars_repo_head_hexsha": "7f3a28c0d1372e3b3edbcbc28f00ba5645e1bbdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-21T09:53:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-21T09:53:58.000Z", "max_issues_repo_path": "src/haversine.jl", "max_issues_repo_name": "Sh4pe/Distances.jl", "max_issues_repo_head_hexsha": "7f3a28c0d1372e3b3edbcbc28f00ba5645e1bbdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-09T15:38:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-09T22:25:46.000Z", "max_forks_repo_path": "src/haversine.jl", "max_forks_repo_name": "Sh4pe/Distances.jl", "max_forks_repo_head_hexsha": "7f3a28c0d1372e3b3edbcbc28f00ba5645e1bbdb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5128205128, "max_line_length": 113, "alphanum_fraction": 0.670083877, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878721, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7726946066961682}}
{"text": "using PyPlot\nusing LinearAlgebra: norm, dot\n\na = [ 0.5  -1.0   0.25\n      1.0   0.5  -1.0 ]\nc = (1/3) * sum(a, dims=2)\n\nfigure(1)\n\nfunction level_sets(a, j, ξ)\n    prev = [3, 1, 2]\n    succ = [2, 3, 1]\n    m = length(ξ)\n    start = zeros(2, m)\n    finish = zeros(2, m)\n    for k = 1:m\n        η = -0.3\n        start[:,k] = ( a[:,prev[j]] + ξ[k] * ( a[:,j] - a[:,prev[j]] ) \n                      + η * ( a[:,succ[j]] - a[:,prev[j]] ) )\n        η = 1.1 - ξ[k] \n        finish[:,k] = ( a[:,prev[j]] + ξ[k] * ( a[:,j] - a[:,prev[j]] ) \n                      + η * ( a[:,succ[j]] - a[:,prev[j]] ) )\n    end\n    return start, finish\nend\n\nfunction draw_level_sets(a, j)\n    offset = [ 0.1   0.0  -0.1 \n               0.0   0.1  -0.2 ]\n    s = latexstring(\"\\\\xi_\", j, \"=\")\n    vals = [\"0\", \"1/3\", \"2/3\", \"1\"]\n    ha = [\"left\", \"center\", \"right\"]\n    va = [\"center\", \"center\", \"center\"]\n    ξ = [0, 1/3, 2/3, 1]\n    start, finish = level_sets(a, j, ξ)\n    for k = 1:4\n        plot([ start[1,k], finish[1,k] ], [ start[2,k], finish[2,k] ], \"b\",\n            linewidth=0.5)\n        text(start[1,k]+offset[1,j], start[2,k]+offset[2,j],\n             latexstring(s, vals[k]), color=\"b\",\n             horizontalalignment=ha[j], verticalalignment=va[j])\n    end\nend\n\nfunction draw_triangle(a, c, d)\n    J = [1, 2, 3, 1]\n    plot(a[1,J], a[2,J], \"-k\")\n    for j = 1:3\n        s = latexstring(\"a_\", j)\n        offset = a[:,j] - c\n        offset *= d / norm(offset)\n        text(a[1,j]+offset[1], a[2,j]+offset[2], s, color=\"r\",\n            horizontalalignment=\"center\", verticalalignment=\"center\")\n    end\n    plot(a[1,:], a[2,:], \"ro\", c[1], c[2], \"ko\")\nend\n\nfor j = 1:3\n   draw_level_sets(a, j)\nend\ndraw_triangle(a, c, 0.2)\ntext(c[1]+0.06, c[2]-0.02, L\"c\",\n     horizontalalignment=\"left\", verticalalignment=\"center\")\naxis(\"equal\")\naxis(\"off\")\nsavefig(\"barycentric.pdf\")\n\nfigure(2)\n\nfunction draw_vectors(a, b, c)\n    prev = [3, 1, 2]\n    succ = [2, 3, 1]\n    quiver([ c[1], c[1], c[1] ], [ c[2], c[2], c[2] ], b[1,:], b[2,:],\n           angles=\"xy\", scale_units=\"xy\", scale=1, \n           width=0.004, headwidth=5, color=\"g\")\n    offset = [ -0.1   0.1   -0.1\n                0.05  0.07   0.0 ]\n    for j = 1:3\n        text(c[1]+b[1,j]+offset[1,j], c[2]+b[2,j]+offset[2,j],\n                 latexstring(\"b_\", j), color=\"g\",\n                 horizontalalignment=\"center\", verticalalignment=\"center\")\n        bhat = b[:,j] / norm(b[:,j])\n        λ = dot(c - a[:,succ[j]], bhat)\n        foot = c - λ * bhat\n        plot([c[1], foot[1]], [c[2], foot[2]], \"--k\")\n        side = a[:,succ[j]] - a[:,prev[j]]\n        v = side / norm(side)\n        plot(foot[1] .+ 0.1*[ bhat[1], bhat[1]+v[1], v[1]],\n             foot[2] .+ 0.1*[ bhat[2], bhat[2]+v[2], v[2]], linewidth=0.5, \"-k\")\n    end\nend\n\nA = [ (a[:,1]-a[:,3]) (a[:,2]-a[:,3]) ]\nB = inv(A')\nb = [ B[:,1] B[:,2] -sum(B, dims=2) ]\n\ndraw_vectors(a, b, c)\ndraw_triangle(a, c, 0.15)\naxis(\"equal\")\naxis([-2.4, 1.4, -2.4, 2.4])\naxis(\"off\")\nsavefig(\"b_vectors.pdf\")\n\nfigure(3)\n\nfunction draw_quadratic_triangle(a, c, d, sz=12)\n    J = [1, 2, 3, 1]\n    plot(a[1,J], a[2,J], \"-k\")\n    m = zeros(2, 3)\n    m[:,1] = ( a[:,3] + a[:,2] ) / 2\n    m[:,2] = ( a[:,1] + a[:,3] ) / 2\n    m[:,3] = ( a[:,2] + a[:,1] ) / 2\n    for j = 1:3\n        s = latexstring(\"a_\", j)\n        offset = a[:,j] - c\n        offset *= d / norm(offset)\n        text(a[1,j]+offset[1], a[2,j]+offset[2], s, color=\"r\",\n            horizontalalignment=\"center\", verticalalignment=\"center\",\n            fontsize=sz)\n        s = latexstring(\"m_\", j)\n        offset = m[:,j] - c\n        offset *= d / norm(offset)\n        text(m[1,j]+offset[1], m[2,j]+offset[2], s, color=\"r\",\n            horizontalalignment=\"center\", verticalalignment=\"center\",\n            fontsize=sz)\n    end\n    plot(a[1,:], a[2,:], \"ro\", m[1,:], m[2,:], \"ro\")\nend\n\ndraw_quadratic_triangle(a, c, 0.15)\naxis(\"equal\")\naxis(\"off\")\nsavefig(\"midpoints.pdf\")\n", "meta": {"hexsha": "2ec349f752f36bb4f78a286b2a3001a235204462", "size": 3909, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chap6/barycentric.jl", "max_stars_repo_name": "billmclean/ComputationalMathsNotes", "max_stars_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T21:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:30:20.000Z", "max_issues_repo_path": "src/chap6/barycentric.jl", "max_issues_repo_name": "billmclean/ComputationalMathsNotes", "max_issues_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chap6/barycentric.jl", "max_forks_repo_name": "billmclean/ComputationalMathsNotes", "max_forks_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.171641791, "max_line_length": 80, "alphanum_fraction": 0.4627782041, "num_tokens": 1517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7726510071312044}}
{"text": "m = 21          # The number of 'space' nodes\nn = 401         # The number of 'time' nodes\nτ = 10/(n-1)    # Time step size\nh = 1/(m-1)     # Space step size\n\nλ = 0.3\nα = 0.3+0.1*(1-cos(1))         # Integral of g(x) = 0.3 +0.1sin(x) = 0.3+0.1(1-cos1)\nx = vec(linspace(0,1,m))\nt = vec(linspace(0,10,n))\n\nα = 0.3+0.1*(1-cos(1))         # Integral of g(x) = 0.3 +0.1sin(x) = 0.3+0.1(1-cos1)\nμ = 1./(1-x).^2; μ[1] = 0; μ[m] = 0;\nβ = zeros(m,m)\nγ = (1-λ*τ+h*τ/2)\n\noptv = 0.85 + 0.05cos(2π*t)   # The optimal distribution we are aiming at\n\n\n## Calcuate A\nA = zeros(m,m)\n\nfor i=2:m-1\n    A[i,i-1] = 1 - τ*μ[i] + τ/h\n    A[i,i+1] = 1 - τ*μ[i] - τ/h\nend\n\n\n\n## Calculate g\ng = (0.3+0.1*sin(x))\n\n## Quadrature\nfunction mu(x)\n    return 1/(1-x)^2\nend\n\nfunction f(x)\n    ## Use just the x part\n    ## Remaining cos(πt) should be multiplied later\n    return 0.1*sin(1-x)*sin(1-x)\nend\n\nfunction fmu(x)\n    return f(x)mu(x)\nend\n\nweights = [(18+√30)/36,(18-√30)/36]\npoint1 = √(3-2(√6)/(√5))/√7\npoint2 = √(3+2(√6)/(√5))/√7\n\n## Integrate wrt x\nfx = weights[1]*fmu((point1+1)/2)+weights[1]*fmu((-point1+1)/2)+weights[2]*fmu((point2+1)/2)+weights[2]*fmu((-point2+1)/2)\nfx = fx/2\n## Multiply by time vector\nfxt = fx*cos(π*t)\n\n## Calculate β\nβ = zeros(n,n)\nβ[1,1] = α\nfor j=2:n\n    for k = 1:j-1\n       a = (A^(j-1-k))'*μ\n       β[j,k] = dot(μ,g)[1]\n    end\n       β[j,j] = α\nend\n\nB = zeros(n,n)\nB[1,1] = α\nfor j=2:n\n    for k=1:j\n        B[j,:] += γ^(j-k)*β[k,:]\n    end\nend\nB = τ*B\nd = zeros(n,1)\nfor i=1:n\n  d[i] = γ^(i-1)*0.9\nend\n\nestb = pinv(B)*vec(d-optv)\nestv = -B*estb + d\nerrv = norm(estv-optv,2);\nc = estb + fxt - 0.3optv\n\n\nw = zeros(m,n)\nw[1,:] = λ*estv\nw[1,1] = 0\nfor i=2:n\n    w[:,i] = A*w[:,i]-τ*estb[i]*g\nend\nM = ones(m)\np1hat = M'*w*h\n\n\n#Pkg.add(\"Gadfly\")\n#Pkg.add(\"Cairo\")\nusing Gadfly\nusing Cairo\ndraw(PDF(\"estv.pdf\",6inch, 3inch), plot(x=t, y=estv, Guide.XLabel(\"Time\"), Guide.YLabel(\"Estimated p0\"),Guide.XTicks(ticks=[0:1:10])))\ndraw(PDF(\"error.pdf\",6inch, 3inch), plot(x=t, y=abs(estv-optv), Guide.XLabel(\"Time\"), Guide.YLabel(\"Absolute Error\"),Guide.XTicks(ticks=[0:1:10])))\ndraw(PDF(\"estb.pdf\",6inch, 3inch), plot(x=t,y=estb, Guide.XLabel(\"Time\"), Guide.YLabel(\"b(t)\"),Guide.XTicks(ticks=[0:1:10])))\ndraw(PDF(\"p1hat.pdf\",6inch, 3inch), plot(x=t,y=p1hat, Guide.XLabel(\"Time\"), Guide.YLabel(\"p1hat(t)\"), Guide.YTicks(ticks=[0:0.0025:0.0225]), Guide.XTicks(ticks=[0:1:10])))\n", "meta": {"hexsha": "19961bec448582efeec97bffde60e048b2c02b88", "size": 2374, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/main.jl", "max_stars_repo_name": "saketkc/math-501-project", "max_stars_repo_head_hexsha": "95b9d9f3084f50ffb8280558ebd790bf007aa2d5", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-04-29T18:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2015-04-29T18:33:37.000Z", "max_issues_repo_path": "src/main.jl", "max_issues_repo_name": "saketkc/math-501-project", "max_issues_repo_head_hexsha": "95b9d9f3084f50ffb8280558ebd790bf007aa2d5", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.jl", "max_forks_repo_name": "saketkc/math-501-project", "max_forks_repo_head_hexsha": "95b9d9f3084f50ffb8280558ebd790bf007aa2d5", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6095238095, "max_line_length": 171, "alphanum_fraction": 0.5560235889, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750373915658, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7726093163316048}}
{"text": "# generate ramps for hasak\n# ramps are 257 point arrays which are interpolated\ncosine_series1(size, k, a0,  a1) = \n    a0 - a1 * cos((2π * k) / (size-1))\ncosine_series2( size, k, a0, a1, a2) = \n    cosine_series1(size, k, a0, a1) + a2 * cos((2 * 2π * k) / (size-1))\ncosine_series3(size, k, a0, a1, a2, a3) = \n    cosine_series2(size, k, a0, a1, a2) - a3 * cos((3 * 2π * k) / (size-1))\n# hann ramp element\nhann(k, size) = \n    Integer(round(32767 * cosine_series1(size, k, 0.50, 0.50)))\n# blackman harris ramp element\nblackman_harris(k, size) = \n    Integer(round(32767 * cosine_series3(size, k, 0.3587500, 0.4882900, 0.1412800, 0.0116800)))\n# linear ramp element\ntriangular(k, size) =\n    Integer(round(32767 * (1.0 - abs( (k - ((size-1)/2.0)) / ((size-1)/2.0) ))))\n# sine table element\nsine(k, size) = \n    Integer(round(32767 * sin(2π * k / size)))\n\n# format tables\nusing Printf\nformat_table(t) = join([@sprintf(\"%s%6d\", i>1 && (i%8)==1 ? \"\\n\" : \"\", t[i]) for i in 1:length(t)], \",\")\n@printf(\"const int16_t hann_ramp[257] = {\\n%s\\n};\\n\", format_table([hann(k,512) for k in 0:256]))\n@printf(\"const int16_t blackman_harris_ramp[257] = {\\n%s\\n};\\n\", format_table([blackman_harris(k,512) for k in 0:256]))\n@printf(\"const int16_t linear_ramp[257] = {\\n%s\\n};\\n\", format_table([triangular(k,512) for k in 0:256]))\n@printf(\"const int16_t sine_table[257] = {\\n%s\\n};\\n\", format_table([sine(k,256) for k in 0:256]))\n", "meta": {"hexsha": "c05836c20c6604204817555a39468a53ebc999ae", "size": 1409, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "doc/tables.jl", "max_stars_repo_name": "recri/hasak", "max_stars_repo_head_hexsha": "24a12581deebd53e94103fcd0af36a29dae17b51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-03-25T09:04:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T04:57:57.000Z", "max_issues_repo_path": "doc/tables.jl", "max_issues_repo_name": "recri/hasak", "max_issues_repo_head_hexsha": "24a12581deebd53e94103fcd0af36a29dae17b51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-05T20:21:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-05T20:21:23.000Z", "max_forks_repo_path": "doc/tables.jl", "max_forks_repo_name": "recri/hasak", "max_forks_repo_head_hexsha": "24a12581deebd53e94103fcd0af36a29dae17b51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-26T06:35:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T06:35:07.000Z", "avg_line_length": 48.5862068966, "max_line_length": 119, "alphanum_fraction": 0.6302342087, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750466836961, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.772609312953111}}
{"text": "# This file investigates integration error with respect to floating point precison. \n\nusing FractalTools \nusing Makie \n\n# Construct interpolation data \nf(x, y) = x^2 + y^2 + 1\nprecisions = 2 .^ (7 : 11)\n\n\n# Specify theoretical value \nfval = 35 / 48\n\nnpts = 100\nmse = map(precisions) do prec \n    # Set precision \n    setprecision(prec) do \n        freevar = BigFloat(0.001)\n\n        # Construct interpolation data \n        ngon = [\n            BigFloat.([0.0, 0.0]), \n            BigFloat.([1.0, 0.0]), \n            BigFloat.([0.5, 1.0])\n        ]\n        pts = getdata(f, ngon, npts)\n\n        # Compute integration.\n        ival = integrate(pts, Interp2D(freevar))        \n\n        # Compute errro \n        abs(fval - ival)\n    end \nend \n\n# Plot mse \nfig = Figure() \nax = fig[1, 1] = Axis(fig, xlabel=\"Precision\", ylabel=\"Integration Error\", title=\"2D Integration Error\") \nstem!(ax, precisions, mse, color=:black)\nsave(joinpath(@__DIR__, \"integ2d_error.png\"), fig)\ndisplay(fig)\n", "meta": {"hexsha": "a7bcc8467668acf39dfd2e6fc12348e5c6a6d1b0", "size": 979, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiment_1/integration_error_vs_precision/integ2d/integ2d.jl", "max_stars_repo_name": "zekeriyasari/FractalTools.jl", "max_stars_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-08T12:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T12:50:16.000Z", "max_issues_repo_path": "experiment_2/integration_error_vs_precision/integ2d/integ2d.jl", "max_issues_repo_name": "zekeriyasari/FractalTools.jl", "max_issues_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-09-05T18:22:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T10:09:46.000Z", "max_forks_repo_path": "experiment_2/integration_error_vs_precision/integ2d/integ2d.jl", "max_forks_repo_name": "zekeriyasari/FractalTools.jl", "max_forks_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3095238095, "max_line_length": 105, "alphanum_fraction": 0.5965270684, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013548, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7726093097255073}}
{"text": "#############################################################################\n# lieb_ando.jl\n# Returns tr(K' * A^{1-t} * K * B^t) where A and B are positive semidefinite\n# matrices and K is an arbitrary matrix (possibly rectangular).\n#\n# Disciplined convex programming information:\n#    lieb_ando(A,B,K,t) is concave in (A,B) for t in [0,1], and convex\n#    in (A,B) for t in [-1,0] or [1,2]. K is a fixed matrix.\n#\n# Seems numerically unstable when t is on the endpoints of these ranges.\n#\n# All expressions and atoms are subtypes of AbstractExpr.\n# Please read expressions.jl first.\n#\n#REFERENCE\n#   Ported from CVXQUAD which is based on the paper: \"Lieb's concavity\n#   theorem, matrix geometric means and semidefinite optimization\" by Hamza\n#   Fawzi and James Saunderson (arXiv:1512.03401)\n#############################################################################\n\nconst MatrixOrConstant = Union{AbstractMatrix,Constant}\n\nfunction lieb_ando(\n    A::MatrixOrConstant,\n    B::MatrixOrConstant,\n    K::MatrixOrConstant,\n    t::Rational,\n)\n    if t < -1 || t > 2\n        throw(DomainError(t, \"t must be between -1 and 2\"))\n    end\n    return real(tr(K' * A^(1 - t) * K * B^t))\nend\n\nfunction lieb_ando(\n    A::MatrixOrConstant,\n    B::AbstractExpr,\n    K::MatrixOrConstant,\n    t::Rational,\n)\n    if t < -1 || t > 2\n        throw(DomainError(t, \"t must be between -1 and 2\"))\n    end\n    KAK = K' * A^(1 - t) * K\n    KAK = (KAK + KAK') / 2\n    return trace_mpower(B, t, KAK)\nend\n\nfunction lieb_ando(\n    A::AbstractExpr,\n    B::MatrixOrConstant,\n    K::MatrixOrConstant,\n    t::Rational,\n)\n    if t < -1 || t > 2\n        throw(DomainError(t, \"t must be between -1 and 2\"))\n    end\n    KBK = K * B^t * K'\n    KBK = (KBK + KBK') / 2\n    return trace_mpower(A, 1 - t, KBK)\nend\n\nfunction lieb_ando(\n    A::AbstractExpr,\n    B::AbstractExpr,\n    K::MatrixOrConstant,\n    t::Rational,\n)\n    n = size(A, 1)\n    m = size(B, 1)\n    Kvec = reshape(K', n * m, 1)\n    KvKv = Kvec * Kvec'\n    KvKv = (KvKv + KvKv') / 2\n    Im = Matrix(1.0 * I, m, m)\n    In = Matrix(1.0 * I, n, n)\n\n    is_complex =\n        sign(A) == ComplexSign() ||\n        sign(B) == ComplexSign() ||\n        sign(Constant(K)) == ComplexSign()\n    if is_complex\n        T = HermitianSemidefinite(n * m)\n    else\n        T = Semidefinite(n * m)\n    end\n\n    if t >= 0 && t <= 1\n        # Concave function\n        add_constraint!(\n            T,\n            T in GeomMeanHypoCone(kron(A, Im), kron(In, conj(B)), t, false),\n        )\n        return real(tr(KvKv * T))\n    elseif (t >= -1 && t <= 0) || (t >= 1 && t <= 2)\n        # Convex function\n        add_constraint!(\n            T,\n            T in GeomMeanEpiCone(kron(A, Im), kron(In, conj(B)), t, false),\n        )\n        return real(tr(KvKv * T))\n    else\n        throw(DomainError(t, \"t must be between -1 and 2\"))\n    end\nend\n", "meta": {"hexsha": "a7c6f4e43f95b1ddb744c874598f573f2e383c2e", "size": 2846, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/atoms/sdp_cone/lieb_ando.jl", "max_stars_repo_name": "baggepinnen/Convex.jl", "max_stars_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 327, "max_stars_repo_stars_event_min_datetime": "2015-01-22T01:00:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T16:42:11.000Z", "max_issues_repo_path": "src/atoms/sdp_cone/lieb_ando.jl", "max_issues_repo_name": "baggepinnen/Convex.jl", "max_issues_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 275, "max_issues_repo_issues_event_min_datetime": "2015-01-12T19:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-05T19:05:45.000Z", "max_forks_repo_path": "src/atoms/sdp_cone/lieb_ando.jl", "max_forks_repo_name": "baggepinnen/Convex.jl", "max_forks_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 121, "max_forks_repo_forks_event_min_datetime": "2015-01-23T21:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T13:58:39.000Z", "avg_line_length": 27.1047619048, "max_line_length": 77, "alphanum_fraction": 0.5442726634, "num_tokens": 898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750360641185, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7726093087099951}}
{"text": "using UncertaintyQuantification\n\nfunction likelihood(x)\n    eigvaln = [1.51 0.33; 4.01 0.30; 3.16 0.27; 3.21 0.18; 2.19 0.33; 1.71 0.23;\n 2.73 0.21; 5.51 0.20; 1.95 0.11; 4.48 0.20; 1.43 0.16; 2.91 0.26; 3.81 0.23;\n 3.58 0.25; 2.62 0.25]\n\n    sig = [1 0.1]\n\n    la1 = (x[1] + 2*x[2] + sqrt(x[1].^2 + 4*x[2].^2))/2\n    la2 = (x[1] + 2*x[2] - sqrt(x[1].^2 + 4*x[2].^2))/2\n\n    model = [la1 la2]\n    rv = 0\n\n    for i in 1:2\n        for j in 1:15\n            rv += ((eigvaln[j,i] - model[i])/sig[i])^2\n        end\n    end\n    return exp(-1/2*rv)\n end\n\n \n tuningsig = [0.04 0; 0 0.04]\n propdist = MvNormal([0;0], tuningsig)\n propdistsample() = rand(propdist)\n propdistpdf(x) = pdf(propdist, x)\n\n priorsample(n) = rand(Uniform(0.001,4),(n, 2))\n\n function uniformprior(x) \n    if x[1] > 0.001 && x[1] < 4 && x[2] > 0.001 && x[2] < 4\n        rv = 1\n    else \n        rv = 0\n    end\n    return  rv\n end\n\n function term(sset, j)\n    #cov = std(sset)/mean(sset) \n    #coefficient of variance is an alternative way to terminate the sampler\n    rv = true\n    if j >= 1 rv = false end\n    return rv\n end\n\n\ntmcmcexsample = tmcmc(likelihood, uniformprior, priorsample, 1000, 0.001)\n\nsmcexsample = smc(likelihood, uniformprior, priorsample, propdistpdf, propdistsample, 1000, term)\n\nmhexsample = mh(likelihood, uniformprior, propdistpdf, propdistsample, [2.84, 2.33], 1000, 0)\n", "meta": {"hexsha": "fede9a50d124194c2e0a491a24f37d65257ee92b", "size": 1361, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demo/bayesianinference/eigenvalueexample.jl", "max_stars_repo_name": "sitoryu/UncertaintyQuantification.jl", "max_stars_repo_head_hexsha": "f0e63fd3bfc176d8271b83ee999923690331472f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demo/bayesianinference/eigenvalueexample.jl", "max_issues_repo_name": "sitoryu/UncertaintyQuantification.jl", "max_issues_repo_head_hexsha": "f0e63fd3bfc176d8271b83ee999923690331472f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo/bayesianinference/eigenvalueexample.jl", "max_forks_repo_name": "sitoryu/UncertaintyQuantification.jl", "max_forks_repo_head_hexsha": "f0e63fd3bfc176d8271b83ee999923690331472f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7454545455, "max_line_length": 97, "alphanum_fraction": 0.5811903012, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464604, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.7726093053918576}}
{"text": "# JuMP example for the Julia Working Group\r\n\r\n# Reproduce the example HS071.\r\n# HS071\r\n# min x1 * x4 * (x1 + x2 + x3) + x3\r\n# st  x1 * x2 * x3 * x4 >= 25\r\n#     x1^2 + x2^2 + x3^2 + x4^2 = 40\r\n#     1 <= x1, x2, x3, x4 <= 5\r\n# Start at (1,5,5,1)\r\n# End at (1.000..., 4.743..., 3.821..., 1.379...)\r\n\r\n# First install the package, and a solver\r\n#Pkg.add(\"JuMP\")\r\n#Pkg.add(\"Ipopt\") #solver\r\n\r\n# Load these packages\r\nusing JuMP\r\nusing Ipopt\r\n#using NLopt\r\n\r\ntic()  #start clock\r\n\r\n#Create the model object\r\nm = Model()\r\n#m = Model(solver = NLoptSolver(algorithm=:LD_SLSQP))\r\n#m=Model(solver=IpoptSolver(tol=1e-8, max_iter=5000)) # can use the argument solver to pass solver options\r\n\r\n#Defining Variables - These are defined using the @defVar macro. The first argument of\r\n# @defVar(m,x) will always be the model to associate the variable with. You can also\r\n# impose the bounds on the variable here; and start values (using the start option)\r\n@defVar(m, 1<=x[1:4]<=5)\r\n# Set start value\r\nsetValue(x[1],1)\r\nsetValue(x[2],5)\r\nsetValue(x[3],5)\r\nsetValue(x[4],1)\r\n\r\n# One can also create variables manually one by one as:\r\n# x = Variable(m::Model, lower::Number, upper::Number, category::Symbol, name::String)\r\n# Bounds can also be set using setLower(x::Variable, lower) and setUpper(x::Variable, lower)\r\n\r\n\r\n# Objective function - I will show the syntax for a nonlinear objective function. For the\r\n# syntax for linear objective functions, see the documentation. Essentially one needs to\r\n# use setObjective() or @setObjective() rather than @setNLObjective()\r\n# For nonlinear objectives, these are defined using the macro @setNLObjective()\r\n\r\n@setNLObjective(m::Model, :Min, x[1]*x[4]*(x[1]+x[2]+x[3])+x[3] )\r\n\r\n# Next, set constraints.\r\n# Linear constraints are added through the macro @addConstraint()\r\n# Nonlinear constraints are added through the @addNLConstraint() macro\r\n@addNLConstraint(m::Model, x[1]*x[2]*x[3]*x[4]>=25 )\r\n@addNLConstraint(m::Model, x[1]^2 + x[2]^2 + x[3]^2 + x[4]^2 == 40)\r\n\r\n# Finally, solve the model\r\nsolve(m)\r\n\r\n# Let's look at the solutions\r\nprintln(\"x=\", getValue(x))\r\n\r\ntoc()\r\n", "meta": {"hexsha": "326bde3c78ece6320d26a386fdd846bae57ada47", "size": 2104, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JuMP/JuMP_Example.jl", "max_stars_repo_name": "floswald/ucl-econ-julia", "max_stars_repo_head_hexsha": "c0b9077382d4245fb1276ae2f517cc9372259c25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-08-18T00:50:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-18T00:50:53.000Z", "max_issues_repo_path": "JuMP/JuMP_Example.jl", "max_issues_repo_name": "floswald/ucl-econ-julia", "max_issues_repo_head_hexsha": "c0b9077382d4245fb1276ae2f517cc9372259c25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-05-01T13:10:23.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-14T08:44:31.000Z", "max_forks_repo_path": "JuMP/JuMP_Example.jl", "max_forks_repo_name": "floswald/ucl-econ-julia", "max_forks_repo_head_hexsha": "c0b9077382d4245fb1276ae2f517cc9372259c25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-04-25T11:54:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T01:23:04.000Z", "avg_line_length": 33.3968253968, "max_line_length": 107, "alphanum_fraction": 0.6715779468, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538935, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7726035602287954}}
{"text": "using Plots;gr()\n\nT = 1000\ndt = 0.001\ny_0 = 0\ng_0 = 1\n\nfunction euler_method(y_0, g_0, T, dt)\n    y = zeros(T)\n    y[1] = y_0\n\n    f = y_0\n    g = g_0\n    for t = 1:T-1\n        y[t+1] = y[t] + dt*g\n        g = g + dt*(6*g - 9*y[t+1])\n    end\n\n    y\nend\n\nexact_solution(t) = t*exp(3*t)\n\nt = 0:dt:(T-1)dt\ny = euler_method(y_0, g_0, T, dt)\n\nplot(t, exact_solution, color=:cornflowerblue, label=\"Exact\",xlabel=\"t\",ylabel=\"y\")\nplot!(t, y, color=:coral, linestyle=:dash, label=\"Numerical\",xlabel=\"t\",ylabel=\"y\")\nsavefig(\"2nd_order_euler.png\")", "meta": {"hexsha": "4533c9f3aad9914f70f5cc507b9a08e223812382", "size": 536, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ode/2nd_order_euler.jl", "max_stars_repo_name": "nocotan/numerical_calculus.jl", "max_stars_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-07T06:26:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T06:21:01.000Z", "max_issues_repo_path": "ode/2nd_order_euler.jl", "max_issues_repo_name": "nocotan/numerical_calculus.jl", "max_issues_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-01-10T08:22:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-08T13:31:00.000Z", "max_forks_repo_path": "ode/2nd_order_euler.jl", "max_forks_repo_name": "nocotan/numerical_calculus.jl", "max_forks_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-10T05:59:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T13:22:34.000Z", "avg_line_length": 18.4827586207, "max_line_length": 83, "alphanum_fraction": 0.572761194, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7725580131132631}}
{"text": "include(\"fft.jl\")\ninclude(\"multigrid.jl\")\nfunction get_f{T}(u::AbstractArray{T,2}, eps::T)\n\"\"\"Get the f with left hand side\"\"\"\n    mx,my=size(u)\n    fft=rFFTWrapper(u)\n    lap = similar(u)\n    laplacian!(u,lap,fft)\n    dx=similar(u)\n    dy=similar(u)\n    set_not_calculated(fft)\n    derivx!(u,dx,fft)\n    derivy!(u,dy,fft)\n    @inbounds for x in 1:mx\n        for y in 1:my\n            lap[x,y] += eps * (dx[x,y]^2 + dy[x,y]^2 + lap[x,y] * u[x,y])\n        end\n    end\n    return lap\nend\n\nfunction solver{T}(f::AbstractArray{T,2}, eps::T, tol::T, maxiter=50)\n\"\"\"Solving the equation with laplacian\"\"\"\n    mx,my=size(f)\n    fft=rFFTWrapper(f)\n    u=zeros(f)\n    newu=similar(u)\n    dx=similar(u)\n    dy=similar(u)\n    rhs=similar(u)\n    iter=0\n    err=T[]\n    while iter < maxiter\n        iter += 1\n        derivx!(u,dx,fft)\n        derivy!(u,dy,fft)\n        @inbounds for x in 1:mx\n            for y in 1:my\n                rhs[x,y]= (f[x,y] - eps * (dx[x,y]^2 + dy[x,y]^2)) / (one(T) + eps * u[x,y])\n            end\n        end\n        solve_laplacian!(rhs,newu,fft)\n        e=vecnorm(newu - u) / vecnorm(f)\n        push!(err,e)\n        if e < tol\n            break\n        end\n        u,newu=newu,u\n    end\n    return u,err\nend\n\nfunction iteration{T}(grid::gridWrapper, eps::T, err::Array{T,1}, maxiter=4)\n    mx,my=size(grid.f)\n    iter=0\n    while iter < maxiter\n        iter += 1\n        derivx!(grid.u,grid.dx,grid.fft)\n        derivy!(grid.u,grid.dy,grid.fft)\n        @inbounds for x in 1:mx\n            for y in 1:my\n                grid.rhs[x,y]= (grid.f[x,y] - eps * (grid.dx[x,y]^2 + grid.dy[x,y]^2)) / (one(T) + eps * grid.u[x,y])\n            end\n        end\n        solve_laplacian!(grid.rhs,grid.newu,grid.fft)\n        grid.u,grid.newu=grid.newu,grid.u\n        push!(err,vecnorm(grid.newu - grid.u) / vecnorm(grid.f))\n    end\nend\n\nfunction iteration{T}(grid::gridWrapper, eps::T, maxiter=4)\n    mx,my=size(grid.f)\n    iter=0\n    while iter < maxiter\n        iter += 1\n        derivx!(grid.u,grid.dx,grid.fft)\n        derivy!(grid.u,grid.dy,grid.fft)\n        @inbounds for x in 1:mx\n            for y in 1:my\n                grid.rhs[x,y]= (grid.f[x,y] - eps * (grid.dx[x,y]^2 + grid.dy[x,y]^2)) / (one(T) + eps * grid.u[x,y])\n            end\n        end\n        solve_laplacian!(grid.rhs,grid.newu,grid.fft)\n        grid.u,grid.newu=grid.newu,grid.u\n    end\nend\n\n\nfunction multigrid_solver{T}(f::AbstractArray{T,2}, eps::T, tol::T, maxiter=32)\n\"\"\"Solve the equation with multigrid\"\"\"\n    mx,my=size(f)\n    grid1=gridWrapper(f)\n    f2=similar(f,div(mx,2),div(my,2))\n    restriction!(f,f2)\n    grid2=gridWrapper(f2)\n    f3=similar(f,div(mx,4),div(my,4))\n    restriction!(f2,f3)\n    grid3=gridWrapper(f3)\n    f4=similar(f,div(mx,8),div(my,8))\n    restriction!(f3,f4)\n    grid4=gridWrapper(f4)\n    err=T[]\n    full_cycle(iteration,grid1,grid2,grid3,grid4,eps,tol)\n    iter=0\n    while iter < maxiter\n        iter += 1\n        iteration(grid1,eps,err)\n        if vecnorm(grid1.u - grid1.newu) < tol * vecnorm(grid1.f)\n            break\n        end\n    end\n    return grid1.u,err\nend\n\n", "meta": {"hexsha": "acf6100a3b2a8362ff4ffe65cfb2f07521cb207c", "size": 3091, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solver.jl", "max_stars_repo_name": "JerryLingjieMei/NonlinearPDE", "max_stars_repo_head_hexsha": "70cc856d049daa50d369c14039116b6db2e58dc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-02-24T15:35:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T08:00:31.000Z", "max_issues_repo_path": "src/solver.jl", "max_issues_repo_name": "JerryLingjieMei/NonlinearPDE", "max_issues_repo_head_hexsha": "70cc856d049daa50d369c14039116b6db2e58dc6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solver.jl", "max_forks_repo_name": "JerryLingjieMei/NonlinearPDE", "max_forks_repo_head_hexsha": "70cc856d049daa50d369c14039116b6db2e58dc6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-01T14:32:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T14:32:33.000Z", "avg_line_length": 26.8782608696, "max_line_length": 117, "alphanum_fraction": 0.5483662245, "num_tokens": 1055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.772497935858754}}
{"text": "function integral(A::AbstractInterpolation, t::Number)\n    bw, fw = samples(A)\n    idx = max(1+bw, min(searchsortedlast(A.t, t), length(A.t) - fw))\n    _integral(A, idx, t)\nend\n\nfunction integral(A::AbstractInterpolation, t1::Number, t2::Number)\n    bw, fw = samples(A)\n    # the index less than or equal to t1\n    idx1 = max(1+bw, min(searchsortedlast(A.t, t1), length(A.t) - fw))\n    # the index less than t2\n    idx2 = max(2+bw, min(searchsortedlast(A.t, t2), length(A.t) - fw))\n    if A.t[idx2] == t2\n        idx2-=1\n    end\n    total = zero(eltype(A))\n    for idx in idx1:idx2\n        lt1 = idx == idx1 ? t1 : A.t[idx]\n        lt2 = idx == idx2 ? t2 : A.t[idx+1]\n        total += _integral(A, idx, lt2)-_integral(A, idx, lt1)\n    end\n    total\nend\n\nsamples(A::LinearInterpolation{<:AbstractVector}) = (0, 1)\nfunction _integral(A::LinearInterpolation{<:AbstractVector{<:Number}}, idx::Number, t::Number)\n  t1 = A.t[idx]\n  t2 = A.t[idx+1]\n  u1 = A.u[idx]\n  u2 = A.u[idx+1]\n  t^2*(u1 - u2)/(2*t1 - 2*t2) + t*(t1*u2 - t2*u1)/(t1 - t2)\nend\n\nsamples(A::ConstantInterpolation{<:AbstractVector}) = (0, 1)\nfunction _integral(A::ConstantInterpolation{<:AbstractVector}, idx::Number, t::Number)\n  if A.dir === :left\n    # :left means that value to the left is used for interpolation\n    return A.u[idx]*t\n  else\n    # :right means that value to the right is used for interpolation\n    return A.u[idx+1]*t\n  end\nend\n\nsamples(A::QuadraticInterpolation{<:AbstractVector}) = (0, 2)\nfunction _integral(A::QuadraticInterpolation{<:AbstractVector{<:Number}}, idx::Number, t::Number)\n  t1 = A.t[idx]\n  t2 = A.t[idx+1]\n  t3 = A.t[idx+2]\n  u1 = A.u[idx]\n  u2 = A.u[idx+1]\n  u3 = A.u[idx+2]\n  (t^3*(-t1*u2 + t1*u3 + t2*u1 - t2*u3 - t3*u1 + t3*u2)/\n  (3*t1^2*t2 - 3*t1^2*t3 - 3*t1*t2^2 + 3*t1*t3^2 + 3*t2^2*t3 - 3*t2*t3^2) +\n  t^2*(t1^2*u2 - t1^2*u3 - t2^2*u1 + t2^2*u3 + t3^2*u1 - t3^2*u2)/\n  (2*t1^2*t2 - 2*t1^2*t3 - 2*t1*t2^2 + 2*t1*t3^2 + 2*t2^2*t3 - 2*t2*t3^2) +\n  t*(t1^2*t2*u3 - t1^2*t3*u2 - t1*t2^2*u3 + t1*t3^2*u2 + t2^2*t3*u1 - t2*t3^2*u1)/\n  (t1^2*t2 - t1^2*t3 - t1*t2^2 + t1*t3^2 + t2^2*t3 - t2*t3^2))\nend\n\nsamples(A::QuadraticSpline{<:AbstractVector{<:Number}}) = (0, 1)\nfunction _integral(A::QuadraticSpline{<:AbstractVector{<:Number}}, idx::Number, t::Number)\n  t1 = A.t[idx]\n  t2 = A.t[idx+1]\n  u1 = A.u[idx]\n  z1 = A.z[idx]\n  z2 = A.z[idx+1]\n  t^3*(z1 - z2)/(6*t1 - 6*t2) + t^2*(t1*z2 - t2*z1)/(2*t1 - 2*t2) + t*(-t1^2*z1 - t1^2*z2 + 2*t1*t2*z1 + 2*t1*u1 - 2*t2*u1)/(2*t1 - 2*t2)\nend\n\nsamples(A::CubicSpline{<:AbstractVector{<:Number}}) = (0, 1)\nfunction _integral(A::CubicSpline{<:AbstractVector{<:Number}}, idx::Number, t::Number)\n  t1 = A.t[idx]\n  t2 = A.t[idx+1]\n  u1 = A.u[idx]\n  u2 = A.u[idx+1]\n  z1 = A.z[idx]\n  z2 = A.z[idx+1]\n  h2 = A.h[idx+1]\n  (t^4*(-z1 + z2)/(24*h2) + t^3*(-t1*z2 + t2*z1)/(6*h2) +\n  t^2*(h2^2*z1 - h2^2*z2 + 3*t1^2*z2 - 3*t2^2*z1 - 6*u1 + 6*u2)/(12*h2) +\n  t*(h2^2*t1*z2 - h2^2*t2*z1 - t1^3*z2 - 6*t1*u2 + t2^3*z1 + 6*t2*u1)/(6*h2))\nend", "meta": {"hexsha": "c944fefc00a3cf507718a0afad2a94127130d601", "size": 2965, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/integrals.jl", "max_stars_repo_name": "UMCTM/DataInterpolations.jl", "max_stars_repo_head_hexsha": "1dbd529ecb49fb1739ddefb00fa4ba53e9f76154", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-12-10T15:43:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-23T17:52:57.000Z", "max_issues_repo_path": "src/integrals.jl", "max_issues_repo_name": "UMCTM/DataInterpolations.jl", "max_issues_repo_head_hexsha": "1dbd529ecb49fb1739ddefb00fa4ba53e9f76154", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-12-11T01:54:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-08T22:32:58.000Z", "max_forks_repo_path": "src/integrals.jl", "max_forks_repo_name": "UMCTM/DataInterpolations.jl", "max_forks_repo_head_hexsha": "1dbd529ecb49fb1739ddefb00fa4ba53e9f76154", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-11T14:43:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-11T14:43:34.000Z", "avg_line_length": 35.7228915663, "max_line_length": 137, "alphanum_fraction": 0.5817875211, "num_tokens": 1338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7724979329571442}}
{"text": "using BenchmarkTools\nusing StaticArrays\n# this is a slower but pretty solution. took inspiration from a reddit comment\n\nconst start = SVector{300}(map(str -> [parse(Int,str[l]) for l in findall(r\"[[:digit:]]+\", str)], readlines(\"inputs/6-10/06.txt\"))[1])\n\nfunction day6(start, days)\n  c = zeros(Int, 9)\n  for x in start\n    c[x] += 1\n  end\n  for _ in 1:days-1\n    c = circshift(c, -1)\n    c[7] += c[end]\n  end\n  sum(c)\nend\n\nprintln(\"Day 6 Part 1: \",day6(start, 80))\nprintln(\"Day 6 Part 2: \",day6(start, 256))\n\n\nconst A = SMatrix{9,9}([\n 0  1  0  0  0  0  0  0  0\n 0  0  1  0  0  0  0  0  0\n 0  0  0  1  0  0  0  0  0\n 0  0  0  0  1  0  0  0  0\n 0  0  0  0  0  1  0  0  0\n 0  0  0  0  0  0  1  0  0\n 1  0  0  0  0  0  0  1  0\n 0  0  0  0  0  0  0  0  1\n 1  0  0  0  0  0  0  0  0\n])\n\n\nfunction day6transition( days)\n  c = zeros(Int, 9)\n  for x in start\n    c[x] += 1\n  end\n  StC = SVector{9}(c)\n  (A^days) * StC |> sum\nend\n\n@btime day6transition( 256)\n", "meta": {"hexsha": "7db08c4c1a8480b85d15bd6f12fe94ddd361bedb", "size": 951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/days6-10/day6v2.jl", "max_stars_repo_name": "sawyerWeld/AdventofCode2021", "max_stars_repo_head_hexsha": "748beef1bfd4c1b3c780841ae645022f873ea274", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/days6-10/day6v2.jl", "max_issues_repo_name": "sawyerWeld/AdventofCode2021", "max_issues_repo_head_hexsha": "748beef1bfd4c1b3c780841ae645022f873ea274", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/days6-10/day6v2.jl", "max_forks_repo_name": "sawyerWeld/AdventofCode2021", "max_forks_repo_head_hexsha": "748beef1bfd4c1b3c780841ae645022f873ea274", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6739130435, "max_line_length": 134, "alphanum_fraction": 0.5499474238, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7724979287224112}}
{"text": "\nusing Turing\n\n\n@model function two_model(x)\n    # Hyper-parameters\n    μ0 = 0.0\n    σ0 = 1.0\n\n    # Draw weights.\n    π1 ~ Beta(1, 1)\n    π2 = 1 - π1\n\n    # Draw locations of the components.\n    μ1 ~ Normal(μ0, σ0)\n    μ2 ~ Normal(μ0, σ0)\n\n    # Draw latent assignment.\n    z ~ Categorical([π1, π2])\n\n    # Draw observation from selected component.\n    if z == 1\n        x ~ Normal(μ1, 1.0)\n    else\n        x ~ Normal(μ2, 1.0)\n    end\nend\n\n\nusing Turing.RandomMeasures\n\n\n# Concentration parameter.\nα = 10.0\n\n# Random measure, e.g. Dirichlet process.\nrpm = DirichletProcess(α)\n\n# Cluster assignments for each observation.\nz = Vector{Int}()\n\n# Maximum number of observations we observe.\nNmax = 500\n\nfor i in 1:Nmax\n    # Number of observations per cluster.\n    K = isempty(z) ? 0 : maximum(z)\n    nk = Vector{Int}(map(k -> sum(z .== k), 1:K))\n\n    # Draw new assignment.\n    push!(z, rand(ChineseRestaurantProcess(rpm, nk)))\nend\n\n\nusing Plots\n\n# Plot the cluster assignments over time \n@gif for i in 1:Nmax\n    scatter(\n        collect(1:i),\n        z[1:i];\n        markersize=2,\n        xlabel=\"observation (i)\",\n        ylabel=\"cluster (k)\",\n        legend=false,\n    )\nend\n\n\n@model function infiniteGMM(x)\n    # Hyper-parameters, i.e. concentration parameter and parameters of H.\n    α = 1.0\n    μ0 = 0.0\n    σ0 = 1.0\n\n    # Define random measure, e.g. Dirichlet process.\n    rpm = DirichletProcess(α)\n\n    # Define the base distribution, i.e. expected value of the Dirichlet process.\n    H = Normal(μ0, σ0)\n\n    # Latent assignment.\n    z = tzeros(Int, length(x))\n\n    # Locations of the infinitely many clusters.\n    μ = tzeros(Float64, 0)\n\n    for i in 1:length(x)\n\n        # Number of clusters.\n        K = maximum(z)\n        nk = Vector{Int}(map(k -> sum(z .== k), 1:K))\n\n        # Draw the latent assignment.\n        z[i] ~ ChineseRestaurantProcess(rpm, nk)\n\n        # Create a new cluster?\n        if z[i] > K\n            push!(μ, 0.0)\n\n            # Draw location of new cluster.\n            μ[z[i]] ~ H\n        end\n\n        # Draw observation.\n        x[i] ~ Normal(μ[z[i]], 1.0)\n    end\nend\n\n\nusing Plots, Random\n\n# Generate some test data.\nRandom.seed!(1)\ndata = vcat(randn(10), randn(10) .- 5, randn(10) .+ 10)\ndata .-= mean(data)\ndata /= std(data);\n\n\n# MCMC sampling\nRandom.seed!(2)\niterations = 1000\nmodel_fun = infiniteGMM(data);\nchain = sample(model_fun, SMC(), iterations);\n\n\n# Extract the number of clusters for each sample of the Markov chain.\nk = map(\n    t -> length(unique(vec(chain[t, MCMCChains.namesingroup(chain, :z), :].value))),\n    1:iterations,\n);\n\n# Visualize the number of clusters.\nplot(k; xlabel=\"Iteration\", ylabel=\"Number of clusters\", label=\"Chain 1\")\n\n\nhistogram(k; xlabel=\"Number of clusters\", legend=false)\n\n\nif isdefined(Main, :TuringTutorials)\n    Main.TuringTutorials.tutorial_footer(WEAVE_ARGS[:folder], WEAVE_ARGS[:file])\nend\n\n", "meta": {"hexsha": "9acf83603e6399a6dcda90f188809d27e6868c12", "size": 2875, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/06-infinite-mixture-model/06_infinite-mixture-model.jl", "max_stars_repo_name": "TuringLang/TuringTutorialsOutput", "max_stars_repo_head_hexsha": "0928cc205032f4b117b5d1dd1512b1621fb5674a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/06-infinite-mixture-model/06_infinite-mixture-model.jl", "max_issues_repo_name": "TuringLang/TuringTutorialsOutput", "max_issues_repo_head_hexsha": "0928cc205032f4b117b5d1dd1512b1621fb5674a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/06-infinite-mixture-model/06_infinite-mixture-model.jl", "max_forks_repo_name": "TuringLang/TuringTutorialsOutput", "max_forks_repo_head_hexsha": "0928cc205032f4b117b5d1dd1512b1621fb5674a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9652777778, "max_line_length": 84, "alphanum_fraction": 0.611826087, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.772497927417264}}
{"text": "using DrWatson\n@quickactivate \"StatReth\"\n\n# %%\n\"\"\"2M4\ncard1 = bb\ncard2 = bw\ncard3 = ww\n\nways to get b with card1: 2\nways to get b with card2: 1\nways to get b with card3: 0\ntotal ways to get b: 3\notherside also black means this is card1\nprobability of card1 = (ways to get b with card1) / (total ways to get b) = 2/3\n\"\"\"\n\n# %%\n\"\"\"2M5\ncard1 = bb\ncard2 = bw\ncard3 = ww\ncard4 = bb\n\nways to get b with card1: 2\nways to get b with card2: 1\nways to get b with card3: 0\nways to get b with card4: 2\ntotal ways to get b: 5\notherside also black means this is card1 or card4\nprobability of card1 = (ways to get b with card1) / (total ways to get b) = 2/5\nprobability of card4 = (ways to get b with card4) / (total ways to get b) = 2/5\nprobability of either card1 or card4 = (probability of card1) + (probability of card4)\n                                     = 2/5 + 2/5 = 4/5\n\"\"\"\n\n# %%\n\"\"\"2M6\ncard1 = bb\ncard2 = bw\ncard3 = ww\n\nways to get b with card1: 2  |  ways to get card1: 1\nways to get b with card2: 1  |  ways to get card2: 2\nways to get b with card3: 0  |  ways to get card3: 3\ntotal ways to get b: 4\notherside also black means this is card1\nprobability of card1 = (ways to get b with card1) / (total ways to get b) = 2/4\n\"\"\"\n\n# %%\n\"\"\"2M7\ncard1 = bb\ncard2 = bw\ncard3 = ww\n\nscenarios:\n\nfirst draw: side of first draw, second draw: side of first draw -> ok/no\n\ncard1: b1, card2: b  -> no, second card not white\ncard1: b1, card2: w  -> ok\ncard1: b1, card3: w1 -> ok\ncard1: b1, card3: w2 -> ok\n\ncard1: b2, card2: b  -> no, second card not white\ncard1: b2, card2: w  -> ok\ncard1: b2, card3: w1 -> ok\ncard1: b2, card3: w2 -> ok\n\ncard2: b, card1: b1  -> no, second card not white\ncard2: b, card1: b2  -> no, second card not white\ncard2: b, card3: w1  -> ok\ncard2: b, card3: w2  -> ok\n\ncard2: w, card1: b1  -> no, first card not black\ncard2: w, card1: b2  -> no, first card not black\ncard2: w, card3: w1  -> no, first card not black\ncard2: w, card3: w2  -> no, first card not black\n\ncard3: w1, card1: b1 -> no, first card not black\ncard3: w1, card1: b2 -> no, first card not black\ncard3: w1, card2: b  -> no, first card not black\ncard3: w1, card2: w  -> no, first card not black\n\ncard3: w2, card1: b1 -> no, first card not black\ncard3: w2, card1: b2 -> no, first card not black\ncard3: w2, card2: b  -> no, first card not black\ncard3: w2, card2: w  -> no, first card not black\n\nnumber of possible/ok scenarios: 8\npossible scenarios with card1 as first card: 6\nprobability for card1 = 6/8 = 0.75\n\"\"\"\n", "meta": {"hexsha": "94f75c2fcd9917a4d45bd9e56614b51cafd3db5c", "size": 2487, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/ch02/2M4-7.jl", "max_stars_repo_name": "karajan9/statisticalrethinking", "max_stars_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-06-03T14:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T16:52:26.000Z", "max_issues_repo_path": "exercises/ch02/2M4-7.jl", "max_issues_repo_name": "karajan9/statisticalrethinking", "max_issues_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-13T05:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T14:05:57.000Z", "max_forks_repo_path": "exercises/ch02/2M4-7.jl", "max_forks_repo_name": "karajan9/statisticalrethinking", "max_forks_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-01T13:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-03T23:40:53.000Z", "avg_line_length": 26.1789473684, "max_line_length": 86, "alphanum_fraction": 0.652995577, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.772497924196362}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     text_representation:\n#       extension: .jl\n#       format_name: light\n#       format_version: '1.3'\n#       jupytext_version: 0.8.6\n#   kernelspec:\n#     display_name: Julia 1.0.3\n#     language: julia\n#     name: julia-1.0\n# ---\nmodule SIRModel\nusing DifferentialEquations\n\nfunction sir_ode(du, u, p, t)  \n    #Infected per-Capita Rate\n    β = p[1]\n    #Recover per-capita rate\n    γ = p[2]\n    \n    #Susceptible Individuals\n    S = u[1]\n    #Infected by Infected Individuals\n    I = u[2]\n   \n    du[1] = -β * S * I\n    du[2] = β * S * I - γ * I\n    du[3] = γ * I\nend\n\n#Pram = (Infected Per Capita Rate, Recover Per Capita Rate)\npram = [0.1,0.05]\n#Initial Prams = (Susceptible Individuals, Infected by Infected Individuals)\ninit = [0.99,0.01,0.0]\ntspan = (0.0,200.0)\n\nsir_prob = ODEProblem(sir_ode, init, tspan, pram)\n\nsir_sol = solve(sir_prob, saveat = 0.1);\n\n# Visualization\nusing Plots\nplot(sir_sol,xlabel=\"Time\",ylabel=\"Number\")\n\nfunction sir_ode2(du,u,p,t)\n    S,I,R = u\n    b,g = p\n    du[1] = -b*S*I\n    du[2] = b*S*I-g*I\n    du[3] = g*I\nend\nparms = [0.1,0.05]\ninit = [0.99,0.01,0.0]\ntspan = (0.0,200.0)\nsir_prob2 = ODEProblem(sir_ode2,init,tspan,parms)\nsir_sol = solve(sir_prob2,saveat = 0.1)\nend\n", "meta": {"hexsha": "294a0c0c991a993ae2fce79464b897b80969d4eb", "size": 1268, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/epicookbook/notebooks/SimpleDeterministicModels/SIRModel.jl", "max_stars_repo_name": "mikiec84/SemanticModels.jl", "max_stars_repo_head_hexsha": "f81baf0789cc547375f300429d0fd49c866d5339", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2018-12-05T15:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T08:38:01.000Z", "max_issues_repo_path": "examples/epicookbook/notebooks/SimpleDeterministicModels/SIRModel.jl", "max_issues_repo_name": "mikiec84/SemanticModels.jl", "max_issues_repo_head_hexsha": "f81baf0789cc547375f300429d0fd49c866d5339", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 177, "max_issues_repo_issues_event_min_datetime": "2018-12-10T13:31:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-06T21:39:54.000Z", "max_forks_repo_path": "examples/epicookbook/notebooks/SimpleDeterministicModels/SIRModel.jl", "max_forks_repo_name": "mikiec84/SemanticModels.jl", "max_forks_repo_head_hexsha": "f81baf0789cc547375f300429d0fd49c866d5339", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2019-01-23T14:07:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T15:43:21.000Z", "avg_line_length": 20.7868852459, "max_line_length": 76, "alphanum_fraction": 0.6025236593, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7724979206281906}}
{"text": "# Polynomial covariance function\n\n\"\"\"\n    Poly <: Kernel\n\nPolynomial kernel (covariance)\n```math\nk(x,x') = σ²(xᵀx' + c)ᵈ\n```\nwith signal standard deviation ``σ``, additive constant ``c``, and degree ``d``.\n\"\"\"\nmutable struct Poly <: Kernel\n    \"Constant\"\n    c::Float64\n    \"Signal variance\"\n    σ2::Float64\n    \"Degree of polynomial\"\n    deg::Int\n    \"Priors for kernel parameters\"\n    priors::Array\n\n    \"\"\"\n        Poly(lc::Float64, lσ::Float64, deg::Int)\n\n    Create `Poly` with signal standard deviation `exp(lσ)`, additive constant `exp(lc)`,\n    and degree `deg`.\n    \"\"\"\n    Poly(lc::Float64, lσ::Float64, deg::Int) = new(exp(lc), exp(2 * lσ), deg, [])\nend\n\nfunction KernelData(k::Poly, X::MatF64)\n    XtX=X'*X\n    LinearAlgebra.copytri!(XtX, 'U')\n    LinIsoData(XtX)\nend\nkernel_data_key(k::Poly, X::MatF64) = \"LinIsoData\"\n\n_cov(poly::Poly, xTy) = poly.σ2*(poly.c.+xTy).^poly.deg\nfunction Statistics.cov(poly::Poly, x::VecF64, y::VecF64)\n    K = _cov(poly, dot(x,y))\nend\nfunction cov!(cK::MatF64, poly::Poly, X::MatF64, data::LinIsoData)\n    cK .= _cov(poly, data.XtX)\nend\n@inline @inbounds function cov_ij(poly::Poly, X::MatF64, data::LinIsoData, i::Int, j::Int, dim::Int)\n    return _cov(poly, data.XtX[i, j])\nend\nStatistics.cov(poly::Poly, X::MatF64, data::LinIsoData) = _cov(poly, data.XtX)\n\nget_params(poly::Poly) = Float64[log(poly.c), log(poly.σ2) / 2]\nget_param_names(poly::Poly) = [:lc, :lσ]\nnum_params(poly::Poly) = 2\n\nfunction set_params!(poly::Poly, hyp::VecF64)\n    length(hyp) == 2 || throw(ArgumentError(\"Polynomial function has two parameters\"))\n    poly.c = exp(hyp[1])\n    poly.σ2 = exp(2 * hyp[2])\nend\n\n@inline dk_dlc(poly::Poly, xTy::Float64) = poly.c*poly.deg*poly.σ2*(poly.c+xTy).^(poly.deg-1)\n@inline dk_dlσ(poly::Poly, xTy::Float64) = 2 * _cov(poly,xTy)\n@inline function dKij_dθp(poly::Poly, X::MatF64, i::Int, j::Int, p::Int, dim::Int)\n    if p==1\n        return dk_dlc(poly, dotij(X,i,j,dim))\n    else\n        return dk_dlσ(poly, dotij(X,i,j,dim))\n    end\nend\n@inline function dKij_dθp(poly::Poly, X::MatF64, data::LinIsoData, i::Int, j::Int, p::Int, dim::Int)\n    if p==1\n        return dk_dlc(poly, data.XtX[i,j])\n    else\n        return dk_dlσ(poly, data.XtX[i,j])\n    end\nend\n", "meta": {"hexsha": "90ec59ebf9d0617a572bf4ed82fff913baf3fc9a", "size": 2214, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/poly.jl", "max_stars_repo_name": "jbrea/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/poly.jl", "max_issues_repo_name": "jbrea/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/poly.jl", "max_forks_repo_name": "jbrea/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1315789474, "max_line_length": 100, "alphanum_fraction": 0.6382113821, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.772497919642336}}
{"text": "@inline function two_inv(b::T) where {T}\n     hi = inv(b)\n     lo = fma(-hi, b, one(T))\n     lo /= b\n     return hi, lo\nend\n\n@inline function two_div(a::T, b::T) where {T}\n     hi = a / b\n     lo = fma(-hi, b, a)\n     lo /= b\n     return hi, lo\nend\n\n@inline function two_sqrt(a::T) where {T}\n    hi = sqrt(a)\n    lo = fma(-hi, hi, a)\n    lo /= 2\n    lo /= hi\n    return hi, lo\nend\n\n\n\"\"\"\n    ad_minus_bc(a, b, c, d)\n\nComputes the determinant of a 2x2 matrix.\n\"\"\"\nfunction ad_minus_bc(a::T, b::T, c::T, d::T) where {T}\n    adhi, adlo = two_prod(a,d)\n    bchi, bclo = two_prod(b,c)\n    return four_sum(adhi, adlo, -bchi, -bclo)\nend\n\n\n#=\n   two_fma from three_fma algorithm from\n   Sylvie Boldo and Jean-Michel Muller\n   Some Functions Computable with a Fused-mac\n=#\n\n\"\"\"\n   two_fma(a, b, c)\n\nComputes `s = fl(fma(a,b,c))` and `e1 = err(fma(a,b,c))`.\n\"\"\"\nfunction two_fma(a::T, b::T, c::T) where {T}\n     x = fma(a, b, c)\n     if isinf(x)\n        return (x, zero(T))\n     end\n     y, z = two_prod(a, b)\n     t, z = two_sum(c, z)\n     t, u = two_sum(y, t)\n     y = ((t - x) + u)\n     y = y + z\n     return x, y\nend\n\n#=\n\"Concerning the division, the elementary rounding error is\ngenerally not a floating point number, so it cannot be computed\nexactly. Hence we cannot expect to obtain an error\nfree transformation for the division. ...\nThis means that the computed approximation is as good as\nwe can expect in the working precision.\"\n-- http://perso.ens-lyon.fr/nicolas.louvet/LaLo05.pdf\n\nWhile the sqrt algorithm is not strictly an errorfree transformation,\nit is known to be reliable and is recommended for general use.\n\"Augmented precision square roots, 2-D norms and\n   discussion on correctly reounding xsqrt(x^2 + y^2)\"\nby Nicolas Brisebarre, Mioara Joldes, Erik Martin-Dorel,\n   Hean-Michel Muller, Peter Kornerup\n=#\n", "meta": {"hexsha": "cfa3328a55b3bfe3b4e73e2bc77d5b9b3bccb830", "size": 1818, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/leasterror.jl", "max_stars_repo_name": "nestordemeure/ErrorfreeArithmetic.jl", "max_stars_repo_head_hexsha": "af69f112260be0c99f21ce7f3e71d83ae891dc18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/leasterror.jl", "max_issues_repo_name": "nestordemeure/ErrorfreeArithmetic.jl", "max_issues_repo_head_hexsha": "af69f112260be0c99f21ce7f3e71d83ae891dc18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/leasterror.jl", "max_forks_repo_name": "nestordemeure/ErrorfreeArithmetic.jl", "max_forks_repo_head_hexsha": "af69f112260be0c99f21ce7f3e71d83ae891dc18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9210526316, "max_line_length": 69, "alphanum_fraction": 0.6298129813, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370537, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7724971813949405}}
{"text": "export takens_best_estimate\n\n\"\"\"\n    takens_best_estimate(X, εmax, metric = Chebyshev(),εmin = 0) → D_C, D_C_95u, D_C_95l\nUse the so-called \"Takens' best estimate\" [^Takens1985][^Theiler1988]\nmethod for estimating the correlation dimension\n`D_C` and the upper (`D_C_95u`) and lower (`D_C_95l`) confidence limit for the given dataset `X`.\n\nThe original formula is\n```math\nD_C \\\\approx \\\\frac{C(\\\\epsilon_\\\\text{max})}{\\\\int_0^{\\\\epsilon_\\\\text{max}}(C(\\\\epsilon) / \\\\epsilon) \\\\, d\\\\epsilon}\n```\nwhere ``C`` is the [`correlationsum`](@ref) and ``\\\\epsilon_\\\\text{max}`` is an upper cutoff.\nHere we use the later expression\n```math\nD_C \\\\approx - \\\\frac{1}{\\\\eta},\\\\quad \\\\eta = \\\\frac{1}{(N-1)^*}\\\\sum_{[i, j]^*}\\\\log(||X_i - X_j|| / \\\\epsilon_\\\\text{max})\n```\nwhere the sum happens for all ``i, j`` so that ``i < j`` and ``||X_i - X_j|| < \\\\epsilon_\\\\text{max}``.\nIn the above expression, the bias in the original paper has already been corrected, as suggested in [^Borovkova1999].\n\nThe confidence limits are estimated from the log-likelihood function by finding\nthe values of `D_C` where the function has fallen by 2 from its maximum, see e.g.\n[^Barlow] chapter 5.3\nBecause the CLT does not apply (no independent measurements), the limits are not\nneccesarily symmetric.\n\nAccording to [^Borovkova1999], introducing a lower cutoff `εmin` can make the\nalgorithm more stable (no divergence), this option is given but defaults to zero.\n\nIf `X` comes from a delay coordinates embedding of a timseries `x`, a recommended value\nfor ``\\\\epsilon_\\\\text{max}`` is `std(x)/4`.\n\n[^Takens1985]: Takens, On the numerical determination of the dimension of an attractor, in: B.H.W. Braaksma, B.L.J.F. Takens (Eds.), Dynamical Systems and Bifurcations, in: Lecture Notes in Mathematics, Springer, Berlin, 1985, pp. 99–106.\n[^Theiler1988]: Theiler, [Lacunarity in a best estimator of fractal dimension. Physics Letters A, 133(4–5)](https://doi.org/10.1016/0375-9601(88)91016-X)\n[^Borovkova1999]: Borovkova et al., [Consistency of the Takens estimator for the correlation dimension. The Annals of Applied Probability, 9, 05 1999.](https://doi.org/10.1214/aoap/1029962747)\n[^Barlow]: Barlow, R., Statistics - A Guide to the Use of Statistical Methods in the Physical Sciences. Vol 29. John Wiley & Sons, 1993\n\"\"\"\nfunction takens_best_estimate(X, εmax, metric = Chebyshev(); εmin=0)\n    n, η, N = 0, zero(eltype(X)), length(X)\n    @inbounds for i in 1:N\n        for j in i+1:N\n            d = evaluate(metric, X[i], X[j])\n            if εmin < d < εmax\n                n += 1\n                η += log(d/εmax)\n            end\n        end\n    end\n    # bias-corrected version (log-likelihood function shifted on x-axis)\n    α = -(n-1)/η\n    # biased version (maximum of original log-likelihood function)\n    α_b = -n/η\n    # value of maximum of original log-likelihood function\n    mxl = n*log(α_b) + α_b * η\n    # at the 95%-confidence interval, the log-l function has dropped by 2\n    # -> log_l(x) - mxl + 2 = 0\n    # this is a result of the invariance of the MLE, a really nice property\n    # these limits are not going to be perfectly symmetric (CLT does not apply)\n    mn, mx = fzeros(x-> n * log(x) + η * x - mxl +2 , 0,2*α)\n\n    # Since the bias-correction is just a shift of the log-l function on the\n    # x-axis, we can easily shift the confidence limits by the bias α-α_b\n    α95u = α - α_b + mn\n    α95l = α - α_b + mx\n\n    return α, α95u, α95l\nend\n", "meta": {"hexsha": "7b3ba67cd2a12be4edb8c50fbb941b1c0ce84f94", "size": 3439, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dimensions/takens_best_estimate.jl", "max_stars_repo_name": "onkyo14taro/ChaosTools.jl", "max_stars_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 168, "max_stars_repo_stars_event_min_datetime": "2018-01-07T15:46:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T13:38:24.000Z", "max_issues_repo_path": "src/dimensions/takens_best_estimate.jl", "max_issues_repo_name": "onkyo14taro/ChaosTools.jl", "max_issues_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 176, "max_issues_repo_issues_event_min_datetime": "2017-12-19T20:26:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:08:23.000Z", "max_forks_repo_path": "src/dimensions/takens_best_estimate.jl", "max_forks_repo_name": "onkyo14taro/ChaosTools.jl", "max_forks_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2018-01-27T07:59:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T10:08:36.000Z", "avg_line_length": 50.5735294118, "max_line_length": 238, "alphanum_fraction": 0.6746147136, "num_tokens": 1083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8539127603871312, "lm_q1q2_score": 0.7724926400039815}}
{"text": "# # Gradient of a scalar field\n#\n# This example shows different methods to compute the gradient of a real-valued\n# 3D scalar field ``θ(\\bm{x})`` in Fourier space, where $\\bm{x} = (x, y, z)$.\n# It is assumed that the field is periodic with period $L = 2π$ along all\n# dimensions.\n#\n# ## General procedure\n#\n# The discrete Fourier expansion of ``θ`` writes\n# ```math\n# θ(\\bm{x}) = ∑_{\\bm{k} ∈ \\Z^3} \\hat{θ}(\\bm{k}) \\, e^{i \\bm{k} ⋅ \\bm{x}},\n# ```\n# where $\\bm{k} = (k_x, k_y, k_z)$ are the Fourier wave numbers and $\\hat{θ}$ is\n# the discrete Fourier transform of $θ$.\n# Then, the spatial derivatives of $θ$ are given by\n# ```math\n# \\frac{∂ θ(\\bm{x})}{∂ x_i} =\n# ∑_{\\bm{k} ∈ \\Z^3} i k_i \\hat{θ}(\\bm{k}) \\, e^{i \\bm{k} ⋅ \\bm{x}},\n# ```\n# where the subscript $i$ denotes one of the spatial components $x$, $y$ or\n# $z$.\n#\n# In other words, to compute $\\bm{∇} θ = (∂_x θ, ∂_y θ, ∂_z θ)$, one has to:\n# 1. transform $θ$ to Fourier space to obtain $\\hat{θ}$,\n# 2. multiply $\\hat{θ}$ by $i \\bm{k}$,\n# 3. transform the result back to physical space to obtain $\\bm{∇} θ$.\n\n# ## Preparation\n\n# In this section, we initialise a random real-valued scalar field $θ$ and compute\n# its FFT.\n# For more details see the [Tutorial](@ref).\n\nusing MPI\nusing PencilFFTs\nusing Random\n\nMPI.Init()\n\n## Input data dimensions (Nx × Ny × Nz)\ndims = (64, 32, 64)\n\n## Apply a 3D real-to-complex (r2c) FFT.\ntransform = Transforms.RFFT()\n\n## Automatically create decomposition configuration\ncomm = MPI.COMM_WORLD\npen = Pencil(dims, comm)\n\n## Create plan\nplan = PencilFFTPlan(pen, transform)\n\n## Allocate data and initialise field\nθ = allocate_input(plan)\nrandn!(θ)\n\n## Perform distributed FFT\nθ_hat = plan * θ\nnothing  # hide\n\n# Finally, we initialise the output that will hold ∇θ in Fourier space.\n# Noting that ∇θ is a vector field, we choose to store it as a tuple of\n# 3 PencilArrays.\n\n∇θ_hat = allocate_output(plan, Val(3))\n\n## This is equivalent:\n## ∇θ_hat = ntuple(d -> similar(θ_hat), Val(3))\n\nsummary(∇θ_hat)\n\n# ## Fourier wave numbers\n\n# In general, the Fourier wave numbers are of the form\n# ``k_i = 0, ±\\frac{2π}{L_i}, ±\\frac{4π}{L_i}, ±\\frac{6π}{L_i}, …``,\n# where ``L_i`` is the period along dimension ``i``.\n# When a real-to-complex Fourier transform is applied, roughly half of\n# these wave numbers are redundant due to the Hermitian symmetry of the complex\n# Fourier coefficients.\n# In practice, this means that for the fastest dimension $x$ (along which\n# a real-to-complex transform is performed), the negative wave numbers are\n# dropped, i.e. ``k_x = 0, \\frac{2π}{L_x}, \\frac{4π}{L_x}, …``.\n\n# The `AbstractFFTs` package provides a convenient way to generate the Fourier\n# wave numbers, using the functions\n# [`fftfreq`](https://juliamath.github.io/AbstractFFTs.jl/stable/api/#AbstractFFTs.fftfreq)\n# and\n# [`rfftfreq`](https://juliamath.github.io/AbstractFFTs.jl/stable/api/#AbstractFFTs.rfftfreq).\n# We can use these functions to initialise a \"grid\" of wave numbers associated to\n# our 3D real-to-complex transform:\n\nusing AbstractFFTs: fftfreq, rfftfreq\n\nbox_size = (2π, 2π, 2π)  # Lx, Ly, Lz\nsample_rate = 2π .* dims ./ box_size\n\n## In our case (Lx = 2π and Nx even), this gives kx = [0, 1, 2, ..., Nx/2].\nkx = rfftfreq(dims[1], sample_rate[1])\n\n## In our case (Ly = 2π and Ny even), this gives\n## ky = [0, 1, 2, ..., Ny/2-1, -Ny/2, -Ny/2+1, ..., -1] (and similarly for kz).\nky = fftfreq(dims[2], sample_rate[2])\nkz = fftfreq(dims[3], sample_rate[3])\n\nkvec = (kx, ky, kz)\n\n# Note that `kvec` now contains the wave numbers associated to the global domain.\n# In the following, we will only need the wave numbers associated to the portion\n# of the domain handled by the local MPI process.\n\n# ## [Method 1: global views](@id gradient_method_global)\n\n# [`PencilArray`](https://jipolanco.github.io/PencilArrays.jl/dev/PencilArrays/#PencilArrays.PencilArray)s, returned for instance by [`allocate_input`](@ref)\n# and  [`allocate_output`](@ref), take indices that start at 1, regardless of the\n# location of the subdomain associated to the local process on the global grid.\n# (In other words, `PencilArray`s take *local* indices.)\n# On the other hand, we have defined the wave number vector `kvec` which,\n# for each MPI process, is defined over the global domain, and as such it takes\n# *global* indices.\n\n# One straightforward way of making data arrays compatible with wave numbers is\n# to use global views, i.e. arrays that take global indices.\n# These are generated from `PencilArray`s by calling the [`global_view`](https://jipolanco.github.io/PencilArrays.jl/dev/PencilArrays/#PencilArrays.global_view-Tuple{PencilArray})\n# function.\n# Note that, in general, global indices do *not* start at 1 for a given MPI\n# process.\n# A given process will own a range of data given by indices in `(i1:i2, j1:j2,\n# k1:k2)`.\n\nθ_glob = global_view(θ_hat)\n∇θ_glob = global_view.(∇θ_hat)\nsummary(θ_glob)\n\n# Once we have global views, we can combine data and wave numbers using the\n# portion of global indices owned by the local MPI process, as shown below.\n# We can use `CartesianIndices` to iterate over the global indices associated to\n# the local process.\n\nfor I in CartesianIndices(θ_glob)\n    i, j, k = Tuple(I)  # unpack indices\n\n    ## Wave number vector associated to current Cartesian index.\n    local kx, ky, kz  # hide\n    kx = kvec[1][i]\n    ky = kvec[2][j]\n    kz = kvec[3][k]\n\n    ## Compute gradient in Fourier space.\n    ## Note that modifying ∇θ_glob also modifies the original PencilArray ∇θ_hat.\n    ∇θ_glob[1][I] = im * kx * θ_glob[I]\n    ∇θ_glob[2][I] = im * ky * θ_glob[I]\n    ∇θ_glob[3][I] = im * kz * θ_glob[I]\nend\n\n# The above loop can be written in a slightly more efficient manner by precomputing\n# `im * θ_glob[I]`:\n\n@inbounds for I in CartesianIndices(θ_glob)\n    i, j, k = Tuple(I)\n\n    local kx, ky, kz  # hide\n    kx = kvec[1][i]\n    ky = kvec[2][j]\n    kz = kvec[3][k]\n\n    u = im * θ_glob[I]\n\n    ∇θ_glob[1][I] = kx * u\n    ∇θ_glob[2][I] = ky * u\n    ∇θ_glob[3][I] = kz * u\nend\n\n# Also note that the above can be easily written in a more generic way, e.g. for\n# arbitrary dimensions, thanks in part to the use of `CartesianIndices`.\n# Moreover, in the above there is no notion of the dimension permutations\n# discussed in [the tutorial](@ref tutorial:output_data_layout), as it is all\n# hidden behind the implementation of `PencilArray`s.\n# And as seen later in the [benchmarks](@ref gradient_benchmarks),\n# these (hidden) permutations have zero cost, as the speed is identical\n# to that of a function that explicitly takes into account these permutations.\n\n# Finally, we can perform a backwards transform to obtain $\\bm{∇} θ$ in physical\n# space:\n\n∇θ = plan \\ ∇θ_hat;\n\n# Note that the transform is automatically broadcast over the three fields\n# of the `∇θ_hat` vector, and the result `∇θ` is also a tuple of\n# three `PencilArray`s.\n\n# ## [Method 2: explicit global indexing](@id gradient_method_global_explicit)\n\n# Sometimes, one does not need to write generic code.\n# In our case, one often knows the dimensionality of the problem and the\n# memory layout of the data (i.e. the underlying index permutation).\n\n# Below is a reimplementation of the above loop, using explicit indices instead\n# of `CartesianIndices`, and assuming that the underlying index permutation is\n# `(3, 2, 1)`, that is, data is stored in $(z, y, x)$ order.\n# As discussed in [the tutorial](@ref tutorial:output_data_layout),\n# this is the default for transformed arrays.\n# This example also serves as a more explicit explanation for what is going on\n# in the [first method](@ref gradient_method_global).\n\n## Get local data range in the global grid.\nrng = axes(θ_glob)  # = (i1:i2, j1:j2, k1:k2)\n\n# For the loop below, we're assuming that the permutation is (3, 2, 1).\n# In other words, the fastest index is the *last* one, and not the first one as\n# it is usually in Julia.\n# If the permutation is not (3, 2, 1), things will still work (well, except for\n# the assertion below!), but the loop order will not be optimal.\n\n@assert permutation(θ_hat) === Permutation(3, 2, 1)\n\n@inbounds for i in rng[1], j in rng[2], k in rng[3]\n    local kx, ky, kz  # hide\n    kx = kvec[1][i]\n    ky = kvec[2][j]\n    kz = kvec[3][k]\n\n    ## Note that we still access the arrays in (i, j, k) order.\n    ## (The permutation happens behind the scenes!)\n    u = im * θ_glob[i, j, k]\n\n    ∇θ_glob[1][i, j, k] = kx * u\n    ∇θ_glob[2][i, j, k] = ky * u\n    ∇θ_glob[3][i, j, k] = kz * u\nend\n\n# ## [Method 3: using local indices](@id gradient_method_local)\n\n# Alternatively, we can avoid global views and work directly on `PencilArray`s\n# using local indices that start at 1.\n# In this case, part of the strategy is to construct a \"local\" grid of wave\n# numbers that can also be accessed with local indices.\n# This can be conveniently done using the\n# [`localgrid`](https://jipolanco.github.io/PencilArrays.jl/dev/LocalGrids/#PencilArrays.LocalGrids.localgrid)\n# function of the PencilArrays.jl package, which accepts a `PencilArray` (or\n# its associated `Pencil`) and the global coordinates (here `kvec`):\n\ngrid_fourier = localgrid(θ_hat, kvec)\n\n# Note that one can directly iterate on the returned grid object:\n\n@inbounds for I in CartesianIndices(grid_fourier)\n    ## Wave number vector associated to current Cartesian index.\n    local k⃗  # hide\n    k⃗ = grid_fourier[I]\n    u = im * θ_hat[I]\n    ∇θ_hat[1][I] = k⃗[1] * u\n    ∇θ_hat[2][I] = k⃗[2] * u\n    ∇θ_hat[3][I] = k⃗[3] * u\nend\n\n# This implementation is as efficient as the other examples, while being\n# slightly shorter to write.\n# Moreover, it is quite generic, and can be made independent of the number of\n# dimensions with little effort.\n\n# ## [Method 4: using broadcasting](@id gradient_method_broadcast)\n\n# Finally, note that the local grid object returned by `localgrid` makes it is\n# possible to compute the gradient using broadcasting, thus fully avoiding scalar\n# indexing.\n# This can be quite convenient in some cases, and can also be very useful if\n# one is working on GPUs (where scalar indexing is prohibitively expensive).\n# Using broadcasting, the above examples simply become:\n\n@. ∇θ_hat[1] = im * grid_fourier[1] * θ_hat\n@. ∇θ_hat[2] = im * grid_fourier[2] * θ_hat\n@. ∇θ_hat[3] = im * grid_fourier[3] * θ_hat\nnothing  # hide\n\n# Once again, as shown in the [benchmarks](@ref gradient_benchmarks) further\n# below, this method performs quite similarly to the other ones.\n\n# ## Summary\n\n# The `PencilArrays` module provides different alternatives to deal with\n# MPI-distributed data that may be subject to dimension permutations.\n# In particular, one can choose to work with *global* indices (first two\n# examples), with *local* indices (third example), or to avoid scalar indexing\n# altogether (fourth example).\n\n# If one wants to stay generic, making sure that the same code will work for\n# arbitrary dimensions and will be efficient regardless of the underlying\n# dimension permutation, methods [1](@ref gradient_method_global), [3](@ref\n# gradient_method_local) or [4](@ref gradient_method_broadcast) should be\n# preferred.\n# These use `CartesianIndices` and make no assumptions on possible dimension\n# permutations, which are by default enabled in the output of PencilFFTs\n# transforms.\n# In fact, such permutations are completely invisible in the implementations.\n\n# The [second method](@ref gradient_method_global_explicit) uses explicit\n# `(i, j, k)` indices.\n# It assumes that the underlying permutation is `(3, 2, 1)` to loop with `i` as\n# the *slowest* index and `k` as the *fastest*, which is the optimal order in\n# this case given the permutation.\n# As such, the implementation is less generic than the others, and\n# differences in performance are negligible with respect to more generic variants.\n\n# ## [Benchmark results](@id gradient_benchmarks)\n\n# The following are the benchmark results obtained from running\n# [`examples/gradient.jl`](https://github.com/jipolanco/PencilFFTs.jl/blob/master/examples/gradient.jl)\n# on a laptop, using 2 MPI processes and Julia 1.7.2, with an input array of\n# global dimensions ``64 × 32 × 64``.\n# The different methods detailed above are marked on the right.\n# The \"lazy\" marks indicate runs where the wave numbers were represented by\n# lazy `Frequencies` objects (returned by `rfftfreq` and `fftfreq`). Otherwise,\n# they were collected into `Vector`s.\n# For some reason, plain `Vector`s are faster when working with grids generated\n# by `localgrid`.\n\n# In the script, additional implementations can be found which rely on a more\n# advanced understanding of permutations and on the internals of the\n# [`PencilArrays`](https://jipolanco.github.io/PencilArrays.jl/dev/) package.\n# For instance, `gradient_local_parent!` directly works with the raw\n# data stored in Julia `Array`s, while `gradient_local_linear!` completely\n# avoids `CartesianIndices` while staying generic and efficient.\n# Nevertheless, these display roughly the same performance as the above examples.\n#\n#         gradient_global_view!...                  89.900 μs\n#         gradient_global_view! (lazy)...           92.060 μs  [Method 1]\n#         gradient_global_view_explicit!...         88.958 μs\n#         gradient_global_view_explicit! (lazy)...  81.055 μs  [Method 2]\n#         gradient_local!...                        92.305 μs\n#         gradient_grid!...                         92.770 μs\n#         gradient_grid! (lazy)...                  101.388 μs  [Method 3]\n#         gradient_grid_broadcast!...               88.606 μs\n#         gradient_grid_broadcast! (lazy)...        151.020 μs  [Method 4]\n#         gradient_local_parent!...                 92.248 μs\n#         gradient_local_linear!...                 91.212 μs\n#         gradient_local_linear_explicit!...        90.992 μs\n", "meta": {"hexsha": "b34ca6f07f8a509c345c0f39152d6fa1115b9be0", "size": 13742, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples/gradient.jl", "max_stars_repo_name": "corentin-dev/PencilFFTs.jl", "max_stars_repo_head_hexsha": "20d6d917fa40ba3ea446ce9d6efe1a60edf14ed2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/examples/gradient.jl", "max_issues_repo_name": "corentin-dev/PencilFFTs.jl", "max_issues_repo_head_hexsha": "20d6d917fa40ba3ea446ce9d6efe1a60edf14ed2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/examples/gradient.jl", "max_forks_repo_name": "corentin-dev/PencilFFTs.jl", "max_forks_repo_head_hexsha": "20d6d917fa40ba3ea446ce9d6efe1a60edf14ed2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6568047337, "max_line_length": 179, "alphanum_fraction": 0.6970601077, "num_tokens": 3969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715774, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7724926344456077}}
{"text": "\"\"\"\n\teulermethod(f, t0, x0; kwargs...)\n\t\nSolves the differential equation x'(t) = f(t, x(t)) using the euler method.\n\n# Arguments\n- `f`: Derivative function\n- `t0`: Initial time\n- `x0`: Initial position\n\n# Keywords\n- `h`: step of the method\n- `iter`: number of iterations\n\n# Returns\n- `Array{typeof(x0 + h*f(t0, x0))}`: the approximated solution\n\"\"\"\nfunction eulermethod(f, t0, x0; h = 1e-3, iter = 10000)\n\tt = t0\n\tx = Array{typeof(x0 + h*f(t0, x0))}(undef, iter)\n\tx[1] = x0\n\tfor j = 2:iter\n\t\tx[j] = x[j-1] + h*f(t, x[j-1])\n\t\tt += h\n\tend\n\treturn x\nend\n\n\"\"\"\n\ttargetting_eulermethod(f, dist, t0, x0; kwargs...)\n\t\nSolves the differential equation x'(t) = f(t, x(t))\nusing a modification of the euler method to stop close to a given target.\nThe algorithm is similar to the original euler method,\nbut the function dist(x) specifies the signed distance from the new point to the target,\nif it is less than 0 then it is discarded and the method's time step divided by two,\notherwise it becomes part of the solution.\nThe algorithm stops when the distance is positive and less than the admitted error\nor when the maximum iterations limit is reached.\n\n# Arguments\n- `f`: Derivative function\n- `dist`: Function for the signed distance to the target\n- `t0`: Initial time\n- `x0`: Initial position\n\n# Keywords\n- `h`: step of the method\n- `iter`: number of iterations\n\n# Returns\n- `Array{typeof(t0)}, Array{typeof(x0 + h*f(t0, x0))}`: times and values obtained\n\"\"\"\nfunction targetting_eulermethod(f, dist, t0, x0; h = 1e-3, error = 1e-4, maxit = 100000)\n\tt = typeof(t0+h)[t0]\n\tx = Array{typeof(x0 + h*f(t0, x0)), 1}()\n\tpush!(x, x0)\n\twhile dist(last(x)) >= error && maxit > 0\n\t\tnx = last(x) + h*f(last(t), last(x))\n\t\td = dist(nx)\n\t\tif (d < zero(d))\n\t\t\th /= 2\n\t\telse\n\t\t\tpush!(t, last(t)+h)\n\t\t\tpush!(x, nx)\n\t\tend\n\t\tmaxit -= 1\n\tend\n\treturn t, x\nend\n\n", "meta": {"hexsha": "1ece772b4db5f890580a4116b9099fe5d563dc68", "size": 1831, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/IterativeMethods.jl", "max_stars_repo_name": "useredsa/numeric-differential-equations", "max_stars_repo_head_hexsha": "7647a20120ce0a05ee5223b0ce81ad63d8aee115", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/IterativeMethods.jl", "max_issues_repo_name": "useredsa/numeric-differential-equations", "max_issues_repo_head_hexsha": "7647a20120ce0a05ee5223b0ce81ad63d8aee115", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IterativeMethods.jl", "max_forks_repo_name": "useredsa/numeric-differential-equations", "max_forks_repo_head_hexsha": "7647a20120ce0a05ee5223b0ce81ad63d8aee115", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4305555556, "max_line_length": 88, "alphanum_fraction": 0.6602949208, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7724926310823763}}
{"text": "\nusing Plots\nusing LaTeXStrings\n\nfunction euler(init,pars,dt,tmax)\n    N = Int(tmax/dt)\n    x = Vector(undef,N+1)\n    y = Vector(undef,N+1)\n    x[1] = init[1]\n    y[1] = init[2]\n    for i in 1:N\n        dx = a*x[i] - b*x[i]*y[i]\n        dy = c*x[i]*y[i] - d*y[i]\n        x[i+1] = x[i] + dt*dx\n        y[i+1] = y[i] + dt*dy\n    end\n    t = range(1,length=N+1,step=dt)\n    return t,[x,y]\nend\n\na= 2/3; b=4/30; c=1/10; d=1\npars = [a,b,c,d]\ninit = [10,15]\nt,x = euler(init,pars,1e-3,50)\n\ninit2 = [15,10]\nt2,x2 = euler(init2,pars,1e-3,50);\n\np1 = plot(t,x, label=\"\",xlabel=\"Time\", ylabel=\"pop. [au]\", title = L\"x_0 < y_0\")\np2 = plot(t2,x2, label=[\"Prey\",\"Predator\"],legendtitle=\"Species\",xlabel=\"Time\", title = L\"x_0 > y_0\")\nplot(p1,p2)\n\nplot([x[1],x2[1]],[x[2],x2[2]],label=[L\"x_0 < y_0\",L\"x_0 > y_0\"],legendtitle=\"init\",title=\"Phase space\",xlabel=\"x\",ylabel=\"y\")\n\nfunction euler_noise(init,pars,dt,tmax,sd)\n    N = Int(tmax/dt)\n    x = Vector(undef,N+1)\n    y = Vector(undef,N+1)\n    x[1] = init[1]\n    y[1] = init[2]\n    for i in 1:N\n        dx = a*x[i] - b*x[i]*y[i]\n        dy = c*x[i]*y[i] - d*y[i]\n        noisex = sqrt(dt)*randn()*sd[1]\n        noisey = sqrt(dt)*randn()*sd[2]\n        x[i+1] = x[i] + dt*dx + noisex\n        y[i+1] = y[i] + dt*dy + noisey\n        if x[i+1]<0 x[i+1] = 0 end\n        if y[i+1]<0 y[i+1] = 0 end\n    end\n    t = range(1,length=N+1,step=dt)\n    return t,[x,y]\nend\n\ninit = [10,10]\nt,x = euler_noise(init,pars,1e-3,100,[.3,.3])\nt2,x2 = euler_noise(init,pars,1e-3,100,[0,0])\n\np1 = plot(t,x, label=\"\",xlabel=\"Time\", ylabel=\"pop. [au]\", title = \"noise\")\np2 = plot(t2,x2, label=[\"Prey\",\"Predator\"],legendtitle=\"Species\",xlabel=\"Time\", title = \"no noise\")\nplot(p1,p2)\n\np1 = plot(t,[x[1],x2[1]], label=\"\",xlabel=\"Time\", ylabel=\"pop. [au]\", title = \"Prey\")\np2 = plot(t2,[x[2],x2[2]], label=[\"noise\",\"no noise\"],legendtitle=\"Species\",xlabel=\"Time\", title = \"Predator\")\nplot(p1,p2)\n\nplot([x[1],x2[1]],[x[2],x2[2]],label=[\"noise\",\"no noise\"],title=\"Phase space\",xlabel=\"x\",ylabel=\"y\")\n\nfunction euler_ext(init,pars,dt,tmax,sd)\n    N = Int(tmax/dt)\n    x = Vector(undef,N+1)\n    y = Vector(undef,N+1)\n    x[1] = init[1]\n    y[1] = init[2]\n    for i in 1:N\n        dx = a*x[i]*(1-x[i]/K) - b*x[i]*y[i]/(x[i]+S)\n        dy = c*x[i]*y[i]/(x[i]+S) - d*y[i]\n        noisex = sqrt(dt)*randn()*sd[1]\n        noisey = sqrt(dt)*randn()*sd[2]\n        x[i+1] = x[i] + dt*dx + noisex\n        y[i+1] = y[i] + dt*dy + noisey\n        if x[i+1]<0 x[i+1] = 0 end\n        if y[i+1]<0 y[i+1] = 0 end\n    end\n    t = range(1,length=N+1,step=dt)\n    return t,[x,y]\nend\n\npars = a,b,c,d,K,S = [1,1,1,1/3,30,10]\ninit = [1,1]\nt,x1  = euler_ext(init,pars,1e-3,100,[0.5,0.5])\nt,x1no = euler_ext(init,pars,1e-3,100,[0,0])\n\ninit = [10,10]\nt,x10  = euler_ext(init,pars,1e-3,100,[0.5,0.5])\nt,x10no = euler_ext(init,pars,1e-3,100,[0,0]);\n\np1 = plot(t,[x1[1]  ,x10[1]]  ,label=\"\",title=\"Prey\",ylabel=\"noise\")\np2 = plot(t,[x1[2]  ,x10[2]]  ,title=\"Predator\",label=[L\"x_0 = y_0 = 1\",L\"x_0 = y_0 = 10\"])\np3 = plot(t,[x1no[1],x10no[1]],label=\"\",xlabel=\"time\",ylabel=\"no noise\")\np4 = plot(t,[x1no[2],x10no[2]],label=\"\",xlabel=\"time\")\nplot(p1,p2,p3,p4)\n\np1 = plot([x1[1],x10[1]],[x1[2],x10[2]],label=\"\",title=\"nnoise\",xlabel=\"x\",ylabel=\"y\")\np2 = plot([x1no[1],x10no[1]],[x1no[2],x10no[2]],label=[L\"x_0 = y_0 = 1\",L\"x_0 = y_0 = 10\"],title=\"no noise\",xlabel=\"x\",ylabel=\"y\")\nplot(p1,p2)\n\n## Interpretation:\n# K = carrying capacity or maximum population size (if population is greater than K it decreases, if population is lower than K it increases)\n# S = Michaelis constant: concentration at half reaction rate v/2\n# Change of system by multiplying v~x/(x+S):\n# reaction rate linear for small x (v~x/S), saturation for large x (v~1)\n# Change of system by adding -x/K:\n# population maximum evens out (otherwise x or y can go to infinity)\n# noise:\n# no attractor\n", "meta": {"hexsha": "e696f4fe4a86bed38c9d8ec3895d9351f0e9ae48", "size": 3835, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Exercises/Tutorial_1_LotkaVolterra.jl", "max_stars_repo_name": "dlill/DynSysBio2019", "max_stars_repo_head_hexsha": "6fdf691a2fd184ac7fa665bc2865c619570f05f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-24T12:34:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-24T12:34:57.000Z", "max_issues_repo_path": "Exercises/Tutorial_1_LotkaVolterra.jl", "max_issues_repo_name": "dlill/DynSysBio2019", "max_issues_repo_head_hexsha": "6fdf691a2fd184ac7fa665bc2865c619570f05f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercises/Tutorial_1_LotkaVolterra.jl", "max_forks_repo_name": "dlill/DynSysBio2019", "max_forks_repo_head_hexsha": "6fdf691a2fd184ac7fa665bc2865c619570f05f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-04-24T12:33:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-31T09:20:23.000Z", "avg_line_length": 32.7777777778, "max_line_length": 141, "alphanum_fraction": 0.5637548892, "num_tokens": 1588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.772492622815333}}
{"text": "# ## ロジスティック回帰\n# ### 例29\n# シグモイド関数を定義しておきます。\n# ```julia\n# sigmoid(x::Matrix, β::Vector) = 1 / (1 + exp(-x*β))\n# ```\nusing Joe, Plots\nusing Plots.PlotMeasures # hide\nPlots.reset_defaults() # hide\ndefault( # hide\n    titlefont  = font(\"JuliaMono\", default(:titlefontsize),  ),  # hide\n    guidefont  = font(\"JuliaMono\",  default(:guidefontsize),  ), # hide\n    tickfont   = font(\"JuliaMono\", default(:tickfontsize),   ), # hide\n    legendfont = font(\"JuliaMono\",  default(:legendfontsize), ), # hide\n    left_margin = 30px, # hide\n    bottom_margin = 30px # hide\n) # hide\np29 = plot(xlims=(-10,10), xlabel=\"x\",ylabel=\"P(Y=1|x)\",\n            legend=:topleft, title=\"ロジスティック曲線\")\nx29 = insert_ones(-10:0.1:10)\nfor i in [0, 0.2, 0.5, 1, 2, 10]\n    plot!(p29, x29[:,2], Joe.sigmoid(x29,[0,i]),label=\"$i\")\nend\n\nsavefig(p29,joinpath(@OUTPUT,\"fig2-1.svg\")) # hide\n# \\fig{fig2-1}\n\n# ## ニュートン・ラフソン法\n# ### 例31\n# $x^2-1=0$を4を初期値として数値計算で解く問題。10回でどの程度近づくか。\n# せっかくなので、 微分をあらわに書き下すのではなくて、自動微分パッケージを使ってみることにします。\n# 見た目が$x \\leftarrow x - \\dfrac{f(x)}{f'(x)}$という公式のまんまですね。\nusing Zygote\nf(x) = x^2 -1\nlet # hide\nx=4 \nfor i in 1:10\n    x -= f(x)/f'(x)\n    println(x)\nend\nend # hide\n\n# ### 例31\n# 2変数関数が2つある場合。 Zygote.jlにjacobianがなかったので、ForwardDiff.jlを使ってみます。\n\nusing ForwardDiff\n\nf(x,y) = [x^2+y^2-1, x+y]\nlet # hide\nz = [3,4]\nfor i in 1:10\n    z -= ForwardDiff.jacobian(x->f(x[1], x[2]),z) \\ f(z[1],z[2]) \n    println(z)\nend\nend # hide\n\n# ### 例33\n# 最尤推定によりロジスティック回帰を行う問題。\n# $\\nabla l(\\beta_0, \\beta) = 0$を求める問題を解いてみる。\nusing Joe, Random, LinearAlgebra\nusing Plots\nN=1000; p=2; Random.seed!(1)\nX = insert_ones(randn(N,p))\nβ = randn(p+1)\nprob = @. 1/(1 + exp($*(X,β)))\nthreshold=0.5\ny = ifelse.(rand(N) .> prob,1,-1) # ここまでデータ生成\n@show y β;\n# せっかくなのでデータを可視化してみます。\ndata1 = X[y .== 1, 2:3]\ndata2 = X[y .== -1, 2:3]\np33=scatter(data1[:,1],data1[:,2],ylims=(-5,5),marker=:auto, label=\"y=1\")\nscatter!(p33,data2[:,1],data2[:,2],marker=:auto,label=\"y=-1\")\nplot!(p33,x-> -β[1]/β[3] - β[2]/β[3]*x, label=\"β\")\nsavefig(p33,joinpath(@OUTPUT,\"fig2-2.svg\")) # hide\n# \\fig{fig2-2}\nγ = randn(2+1) #初期値\nγ2 = copy(γ) #別解用にコピー\n@show γ\nW(v::Vector) = @.(v/(1+ v)^2) |> diagm\nt = true\nfor i in 1:10\n    global γ\n    s=X*γ\n    v = @. exp(-y*s)\n    u = @. y*v/(1+v)\n    γ += ((X'*W(v)*X) \\ X') * u\n    #δ'*δ < 0.001 && (t = false)\n    @show γ\nend \nplot!(x-> -γ[1]/γ[3] - γ[2]/γ[3]*x, label=\"γ\")\n# 今度は横着をして、ヘシアンを使って計算してみます。\nusing Zygote, LinearAlgebra\nl(γ,X=X,y=y) = sum(@. log( 1 /(1+exp(*($*(X,γ),-y))))) #対数尤度関数\n\nfor i in 1:10\n    global γ2\n    δ =  Zygote.hessian(l,γ2) \\ l'(γ2)\n    γ2 -= δ\n    @show γ2\nend\n\nplot!(p33,x-> -γ2[1]/γ2[3] - γ2[2]/γ2[3]*x, label=\"γ2\")\nsavefig(p33,joinpath(@OUTPUT,\"fig2-2-2.svg\")) # hide\n# \\fig{fig2-2-2}\n# \\lineskip\n# だいたい同じような境界線が得られることが分かりました。\n# ### 例34\n# データの半分を使ってロジスティック回帰で学習し、残りのデータで検証する練習。\n# まずデータを生成します。 \nusing Joe, Random, Distributions, Plots, LinearAlgebra\nRandom.seed!(123)\nn=100\nx34 = vcat(randn(n).+1,randn(n).-1) |> insert_ones \ny34 = vcat(ones(n),-ones(n));\n# 訓練データとテストデータを分けて可視化します。\nindex = sample(1:2n,2n,replace=false); #ランダムなインデックスを作り\ntrain = index[begin:n];# 学習用とテスト用にインデックスを分ける。\ntest = index[n+1:end];\nX_train = x34[train,:];y_train = y34[train]\nX_test = x34[test,:];y_test = y34[test]\np34 = scatter(X_train[:,2],y_train,label=\"train\")\nscatter!(p34,X_test[:,2],y_test,label=\"test\")\nsavefig(p34,joinpath(@OUTPUT,\"fig2-2-3.svg\")) # hide\n# \\fig{fig2-2-3}\n# \\lineskip\n# \\note{\n    # **訓練データとテストデータを分ける方法**\n    # \n    # 原著のpythonコードでは以下のようになっています。\n    # ```python\n    # import numpy as np \n    # train = np.random.choice(2*n, int(n), replace=false)\n    # test = list(set(range(n))-set(train))\n    # ```\n    # setを使った書き方は便利ですが、juliaでは重複を許さずにランダムに並べたインデックスを二つに分ける\n    # 方法を使いました。\n    # ```julia\n    # using StatsBase \n    # index = sample(1:n,n,replace=false);\n    # train = index[begin:Int(n/2)];\n    # test = index[Int(n/2)+1:end];\n    # ```\n    # でもよく考えるとsetdiffを使えば十分でした。\n    # ```julia\n    # train = sample(1:2n,n,replace=false); test = setdiff(1:2n,train)\n    # ```\n# }\n# ループは原著の方法に従いました。\nβ = [0,0] #初期値\nγ = randn(2)\nwhile sum(β-γ)^2 > 0.001\n    global β, γ\n    local W\n    β = γ\n    s = X_train*β\n    v = @. exp(-s*y_train)\n    u = @. y_train*v/(1+v)\n    w = @. v/(1+v)^2\n    W = diagm(w)\n    z = @. s + u/w\n    γ = (X_train'*W*X_train)\\(X_train'*W*z)\n    @show γ;\nend\n# 次にこのγを使って、テストデータを予測してみます。 正誤をカウントする関数を次のように定義します。\n# ```julia\n# function table_count(test,pred)\n#     @assert length(test) == length(pred)\n#     m = unique(test) |> length\n#     count = zeros(Int,m,m)\n#     for i in 1:length(test)\n#         count[test[i],pred[i]] += 1\n#     end\n#     return count\n# end\n# ```\nusing Joe:table_count\ny_pred = X_test*γ .|> x -> ifelse(x>0,2,1)\ny_answer = y_test .|> x -> ifelse(x>0,2,1)\ntable = table_count(y_answer,y_pred)\n@show table;\n正答率 = sum(diag(table)) / sum(table)\n# ## 2.3 線形判別と二次判別\n# ### 例35\n# まずは与えられた平均と分散共分散行列から二次元正規分布のデータを2種類生成します。\nusing Distributions, Random,Plots, LinearAlgebra, Parameters\nμ₁=[2,2];  Σ₁ = [2 0; 0 2]\nμ₂=[-3,-3]; Σ₂ = [1 -0.8; -0.8 1]\n\nN = 100;Random.seed!(123)\ndata1 = rand(MvNormal(μ₁,Σ₁),100) |> transpose\ndata2 = rand(MvNormal(μ₂,Σ₂),100) |> transpose\np35 = scatter(data1[:,1],data1[:,2])\nscatter!(p35, data2[:,1],data2[:,2])\n\nsavefig(p35,joinpath(@OUTPUT,\"fig2-3.svg\")) # hide\n# \\fig{fig2-3}\n# \\lineskip\n# ここまでデータの生成。\n# 生成したデータから平均と分散共分散行列を計算する。\nμ̂₁ = mean(data1,dims=1)'; Σ̂₁ = cov(data1,dims=1);\nμ̂₂ = mean(data2,dims=1)' ; Σ̂₂ = cov(data2,dims=1);\n# \\warning{mean関数で行列の列方向の平均をとる時、得られるデータは二次元の横ベクトルになっている。\n# 縦ベクトルとして扱いたいので、転置(正確には複素共役）をしている。}\n# それぞれの分布の情報を複合型にまとめておきます。\n# ```julia\n# @with_kw struct QDA \n#     μ::Array # 平均\n#     Σ::Matrix # 分散共分散行列\n#     invΣ::Array = inv(Σ) # 分散共分散行列の逆行列\n#     detΣ = det(Σ) # 分散共分散行列の行列式\n# end\n# ```\n# \\note{しれっとパラメータを初期化した複合型を使っていますが、ここではParameters.jlとい\n# うサードパーティライブラリを使っています。}\n# また、多変量正規分布の対数尤度を取得する関数を以下のように定義します。\n# ここでは、juliaのfunction-like objectの機能を利用しています。\n# また、可変長引数(x...)を利用して、データが3次元以上の場合にも拡張しています。\n# キーワード付き引数に事前確率を加えています。\n# \\note{function-like objectの機能を使うと、複合型のインスタンスを関数のように\n# 使うことができ、再利用しやすくなります。}\n# ```julia\n# function (qda::QDA)(x...,prior=1.0)\n#     data = collect(x)\n#     @unpack μ,invΣ,detΣ = qda\n#     a = -0.5*(data-μ)' * invΣ * (data-μ) \n#     a[1] - log(detΣ) - log(prior)\n# end\n# ```\nusing Joe: QDA\nparam1=QDA(μ= μ̂₁,Σ = Σ̂₁);param2=QDA(μ = μ̂₂,Σ = Σ̂₂)\n\nhanbetsu(x,y) = param1(x,y) - param2(x,y)\nx35=-5:0.1:5;y35=-5:0.1:5;\nscatter(data1[:,1],data1[:,2])\nscatter!( data2[:,1],data2[:,2])\np35_2=contour!(x35,y35, hanbetsu.(x35,y35'), title=\"QDA\")\nsavefig(p35_2,joinpath(@OUTPUT,\"fig2-4.svg\")) # hide\n# \\fig{fig2-4}\n# \n# 線形判別を行う場合は、分散共分散行列が等しいことを仮定します。\n# data1とdata2を、それぞれ中心化後に統合したデータセットについて、\n# 新たな分散共分散行列を求めることにします。 \nΣ_L =  vcat(data1 .- μ̂₁' , data2 .- μ̂₂') |> cov\nparam1_L=QDA(μ= μ̂₁,Σ =Σ_L );param2_L=QDA(μ = μ̂₂,Σ = Σ_L)\nhanbetsu_L(x,y) = param1_L(x,y) - param2_L(x,y)\np35_3=contour!(p35,x35,y35, hanbetsu_L.(x35,y35'), title=\"LDA\")\nsavefig(p35_3,joinpath(@OUTPUT,\"fig2-5.svg\")) # hide\n# \\fig{fig2-5}\n\n# ### 例36 (Fisherのあやめ)\n# まずRDatasetsからirisのデータセットを読み込みます。\nusing ScikitLearn, StatsBase, Random\nusing Joe:QDA\n@sk_import datasets: load_iris\niris = load_iris()\nx = iris[\"data\"]\ny = iris[\"target\"]\n# 訓練データとテストデータを分けます。\nRandom.seed!(123)\nn = length(y)\nindex = sample(1:n,n,replace=false); #ランダムなインデックスを作り\ntrain = index[begin:Int(n/2)];# 学習用とテスト用にインデックスを分ける。\ntest = index[Int(n/2)+1:end];\nX_train= x[train,:]; X_test = x[test,:];\ny_train = y[train]; y_test = y[test];\n# それぞれのあやめの訓練データの平均と分散共分散行列を求めて保存する。\nParams = QDA[]\nfor i in 1:3\n    μ,Σ =  mean_and_cov(X_train[y_train .==i,:])\n    push!(Params, QDA(μ=μ', Σ=Σ)) #μは行ベクトルであることに注意\nend\n\n# テストデータで検証する。対数尤度を最大化するラベルを選択します。\ny_pred = similar(y_test)\nfor i in 1:length(y_test)\n    y_pred[i] = argmax([param(X_test[i,:]...) for param in Params])\nend\n\nusing Joe:table_count\ntable_count(y_test,y_pred)\n\n# ### 問29 事前確率が分かっている場合\n# あやめの事前確率が[0.5,0.25,0.25]だったときは、対数をとって足せば良いでしょう。\n# キーワード付き引数で事前確率を指定できるようにしたので、\n# 少し書き換えるだけで対応可能です。今回の場合、予測結果に対して影響は少ないようです。\npriors = [0.5,0.25,0.25]\ny_pred2 = similar(y_test)\nfor i in 1:length(y_test)\n    y_pred2[i] = argmax([Params[j](X_test[i,:]...;prior=priors[j]) for j in 1:3])\nend\ntable_count(y_test,y_pred2)\n# ## K近傍法\n# まず、K近傍法による関数を定義します。原著の記法をほぼ踏襲しています。\n# タイブレーキングが少し重複した書き方になっているのが残念。\n# ```julia\n# using LinearAlgebra, StatsBase\n# function knn(X_train::Matrix,y_train::Vector,X_test::Vector, k)\n#     n = size(X_train)[1]\n#     distance = [norm(X_train[i,:]-X_test) for i in 1:n]\n#     S = sortperm(distance)[1:k]\n#     u = counts(y_train[S], 1:k)\n#     u_max = maximum(u)\n#     m = findall(c->c==u_max,u)\n#     while length(m)!==1 #タイブレーキング\n#         k -=1\n#         S = S[1:k]\n#         u = counts(S, 1:k)\n#         u_max = maximum(u)\n#         m = findall(c->c==u_max,u)\n#     end\n#     return m[1]\n# end\n# ```\n# テストデータが複数の場合は多重ディスパッチで対応します。 \n# ```julia\n# function knn(X_train::Matrix,y_train::Vector,X_test::Matrix, k)\n#     l = size(X_test)[1]\n#     w = Array{Int}(undef,l)\n#     for i in 1:l\n#         w[i] = knn(X_train,y_train,X_test[i,:], k)\n#     end\n#     return w\n# end\n# ```\n# ### 例37 Fisherのあやめ returns\n# 例36と同じデータを使ってK近傍法でやってみます。\nusing Joe:knn,table_count\ny_pred_knn = knn(X_train,y_train,X_test,3)\ntable_count(y_test,y_pred_knn)\n# この乱数の種の場合だと、二次判別とそれほど精度は変わりません。\n# ## ROC曲線\n# ### 例38 \n# x, y という表記はpositive, negativeに\n# 添え字を陽性をp(positive), 陰性をn(negative)に変えています。\n# また、varはσに変更しています。\nusing Distributions, Plots\nμₚ = 1; μₙ = -1 \nσₚ=1; σₙ =1\nNₚ = 1000; Nₙ = 10000\npositive = rand(Normal(μₚ,σₚ),Nₚ)\nnegative = rand(Normal(μₙ,σₙ),Nₙ)\nθ = exp.(-10:0.1:100);\nU = Vector{Float64}(undef,length(θ))\nV = Vector{Float64}(undef,length(θ))\nfor i in 1:length(θ)\n    global U,V # hide\n    U[i] = sum(@. pdf(Normal(μₚ,σₚ),negative) / pdf(Normal(μₙ,σₙ),negative) > θ[i]) / Nₙ\n    V[i] = sum(@. pdf(Normal(μₚ,σₚ),positive) / pdf(Normal(μₙ,σₙ),positive) > θ[i]) / Nₚ\nend\n\nAUC = 0\nfor i in 1:length(θ)-1\n    global AUC # hide\n    AUC += abs(U[i+1]-U[i])*V[i]\nend\np38 = plot(U,V,xlabel=\"False Positive\",ylabel=\"False Negative\",\n            title=\"ROC curve\",legend=false,\n            ann = (0.5,0.5,\"AUC = $(round(AUC,digits=2))\"))\n\nsavefig(p38,joinpath(@OUTPUT,\"fig2-6.svg\")) # hide\n# \\fig{fig2-6}", "meta": {"hexsha": "5edbdb8f6e03bea691c835e11f788907579ae066", "size": 10083, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/_literate/ex_chap2.jl", "max_stars_repo_name": "lethal8723/Joe.jl", "max_stars_repo_head_hexsha": "f30bf44f7e662ae58dded2ec675540b2996fe90a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/_literate/ex_chap2.jl", "max_issues_repo_name": "lethal8723/Joe.jl", "max_issues_repo_head_hexsha": "f30bf44f7e662ae58dded2ec675540b2996fe90a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/_literate/ex_chap2.jl", "max_forks_repo_name": "lethal8723/Joe.jl", "max_forks_repo_head_hexsha": "f30bf44f7e662ae58dded2ec675540b2996fe90a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8535911602, "max_line_length": 88, "alphanum_fraction": 0.6291778241, "num_tokens": 5194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7724926194521017}}
{"text": "\n# we write a function that returns a root of func in the\n# interval [low, high] with relative error tol, assuming such a root exists\nfunction binarySearch(func, low, high, tol)\n\n\t# we repeat until the tolorance condition is met\n\twhile abs(high - low)/2 > tol * abs(high + low)/2\n\n\t\t# we define mid as the midpoint of the interval [low, high]\n\t\tmid = (low + high)/2\n\n\t\t# we check if the value of func at high and mid have the same sign\n\t\tif func(high) * func(mid) > 0\n\n\t\t\t# and reassign [low, high] accordingly\n\t\t    high = mid\n\t\telse\n\t\t    low = mid\n\t\tend\n\tend\n\n\t# we return the avarage of low and high as the approximate root\n\treturn (low + high)/2;\nend\n", "meta": {"hexsha": "acc1b7ba1116c2fa7e13936cd4ec68f9ec1696cd", "size": 656, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1a/Root Finding/binarySearch.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "1a/Root Finding/binarySearch.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "1a/Root Finding/binarySearch.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 26.24, "max_line_length": 75, "alphanum_fraction": 0.6798780488, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7724755071792194}}
{"text": "# https://en.wikipedia.org/wiki/Kernel_(statistics)\n\n\n## these functions inspired by KernelFunctions.jl\n# --- begin\nabstract type AbstractKernel end\n\n\n\"\"\"\n    (k::AbstractKernel)(x, xg)\n\nEvaluate the kernel for the pair of values `(x,xg)`.\n\"\"\"\n(k::AbstractKernel)(x, xg) = kern(k, x, xg)\nkern(k::AbstractKernel, x, xg) = scaling(k) * unscaledkern(k,x,xg)\nbandwidth(k::AbstractKernel) = k.h\nscaling(k::AbstractKernel) = k.constant / k.h\n\n\nfunction Base.show(io::IO, k::T) where {T<:AbstractKernel}\n    return print(io, \"$T (h = \", k.h, \")\")\nend\n# --- end\n\n\n# Gaussian\nstruct GaussianKernel{T<:Real,S<:Real} <: AbstractKernel\n    h::T\n    constant::S\nend\nGaussianKernel(h::T; constant::S=1/sqrt(2*pi)) where {T,S} = GaussianKernel{T,S}(h,constant)\nunscaledkern(k::GaussianKernel, x, xg) =  exp(-((x-xg)/k.h)^2 / 2)\n\n\n\"\"\"\n    NormalKernel(h)\n\nAlias of [`GaussianKernel`](@ref).\n\"\"\"\nconst NormalKernel = GaussianKernel\n\n\n\n\n# Uniform\nstruct UniformKernel{T<:Real,S<:Real} <: AbstractKernel\n    h::T\n    constant::S\nend\nUniformKernel(h::T; constant::S=1/2) where {T,S} = UniformKernel{T,S}(h,constant)\nunscaledkern(k::UniformKernel, x::T, xg) where {T} = abs((x-xg)/k.h) <= 1 ? one(T) : zero(T)\n\n\n\n\n# Epanechnikov\nstruct EpanechnikovKernel{T<:Real,S<:Real} <: AbstractKernel\n    h::T\n    constant::S\nend\nEpanechnikovKernel(h::T; constant::S=3/4) where {T,S} = EpanechnikovKernel{T,S}(h,constant)\nunscaledkern(k::EpanechnikovKernel, x::T, xg) where {T} = abs((x-xg)/k.h) <= 1 ? 1 - ((x-xg)/k.h)^2 : zero(T)\n", "meta": {"hexsha": "51eae574f3c8354796770cea1b465697e90ca477", "size": 1500, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels.jl", "max_stars_repo_name": "tbeason/NonparametricRegression.jl", "max_stars_repo_head_hexsha": "ff9b306d623ea4f38da44f6446bfb1b58418cb26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-12-26T18:00:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T09:57:45.000Z", "max_issues_repo_path": "src/kernels.jl", "max_issues_repo_name": "tbeason/NonparametricRegression.jl", "max_issues_repo_head_hexsha": "ff9b306d623ea4f38da44f6446bfb1b58418cb26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-26T00:47:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T20:48:31.000Z", "max_forks_repo_path": "src/kernels.jl", "max_forks_repo_name": "tbeason/NonparametricRegression.jl", "max_forks_repo_head_hexsha": "ff9b306d623ea4f38da44f6446bfb1b58418cb26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8095238095, "max_line_length": 109, "alphanum_fraction": 0.656, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7724754972058059}}
{"text": "\"\"\"\nR ではウェルチの方法による一元元配置分散分析がデフォルトなのであるが，Julia にはないので以下の関数を定義しておく。\n\n関数定義\nUnequalVarianceOneWayANOVATestOneWayANOVATest(groups::AbstractVector{<:Real}...)\n\nOneWayANOVATest(groups::AbstractVector{<:Real}...) の場合と同じく，引数として各標本の観測データベクトルを列挙する。\n\"\"\"\n\nusing Statistics, Distributions\n\nfunction UnequalVarianceOneWayANOVATest(groups::AbstractVector{<:Real}...)\n    roundn(x, digits) = round(x, digits=digits)\n    formatp(p) = p < 0.00001 ? \"< 0.00001\" : \"= \" * string(roundn(p, 5))\n    ni = Int[]\n    mi = Float64[]\n    vi = Float64[]\n    for x in groups\n        append!(ni, length(x))\n        append!(mi, mean(x))\n        append!(vi, var(x))\n    end\n    k = length(ni)\n    wi = ni ./ vi\n    sum_wi = sum(wi)\n    tmp = sum((1 .- wi ./ sum_wi).^2 ./ (ni .- 1)) ./ (k^2 - 1)\n    m = sum(wi .* mi) / sum_wi\n    df1, df2 = k - 1, 1 / 3tmp\n    F = sum(wi .* (mi .- m).^2) / (df1 * (1 + 2 * (k - 2) * tmp))\n    p = ccdf(FDist(df1, df2), F)\n    println(\"F = $(roundn(F, 5)),  df1 = $df1,  df2 = $(roundn(df2, 5)),  p-value $(formatp(p)))\")\nend;\n\n\"\"\"\n使用例\n\njulia> g1 = [27.7, 45.2, 32.8, 49.5, 31.0, 55.5, 31.7, 53.9];\n\njulia> g2 = [38.0, 47.4, 55.3, 52.5, 39.2, 34.9];\n\njulia> g3 = [44.0, 29.8, 42.5, 23.4, 20.7, 57.3, 42.0, 56.8, 44.1, 32.7];\n\njulia> UnequalVarianceOneWayANOVATest(g1, g2, g3)\nF = 0.51339,  df1 = 2,  df2 = 13.589,  p-value = 0.60962)\n\n\"\"\"\n", "meta": {"hexsha": "2e73bf61b24d443555c511b616c0027fd7d65c9a", "size": 1340, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "UnequalVarianceOneWayANOVATest.jl", "max_stars_repo_name": "r-de-r/stats", "max_stars_repo_head_hexsha": "69ae834ecb55f737106900a1f14674e55cc1f972", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "UnequalVarianceOneWayANOVATest.jl", "max_issues_repo_name": "r-de-r/stats", "max_issues_repo_head_hexsha": "69ae834ecb55f737106900a1f14674e55cc1f972", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UnequalVarianceOneWayANOVATest.jl", "max_forks_repo_name": "r-de-r/stats", "max_forks_repo_head_hexsha": "69ae834ecb55f737106900a1f14674e55cc1f972", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5106382979, "max_line_length": 98, "alphanum_fraction": 0.5708955224, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7724754941851538}}
{"text": "function rtuples(T::Type{<:Number}, D::Int, k::Int)::Vector{NTuple{D,T}}\n    return [tuple(rand(T,D)...) for i in 1:k];\nend\nfunction rarrays(T::Type{<:Number}, D::Int, k::Int)::Vector{Vector{T}}\n    return [rand(T,D) for i in 1:k];\nend\nfunction totuples(data)\n    return [tuple(e...) for e in data];\nend\nfunction get_perfect_data(; n = 100)\n    cs = [(-5,-5),(0,5),(5,-5)]\n    dt = Vector{Tuple{Float64,Float64}}();\n    xr = randn(n);\n    yr = randn(n);\n    for rd in 1:n\n        for c in cs\n            push!(dt, (xr[rd] + c[1], yr[rd] + c[2]))\n        end\n    end\n    return dt;\nend\nfunction center_coords(ps)\n    s = ps[1];\n    for i in 2:length(ps)\n         s = s .+ ps[i]\n    end\n    return s ./ length(ps);\nend\nfunction assign(p::T, cs::Vector{T}) where T\n    findmin(distance(p,cs))[2];\nend\nfunction assign(ps::Vector{T}, cs::Vector{T}) where T\n    return [findmin(distance(p,cs))[2] for p in ps];\nend\nfunction distance(p1, p2)\n    return sqrt(sum((p1 .- p2).^2))\nend\nfunction distance(p1::T, ps::Vector{T}) where T\n    return [distance(p1,p) for p in ps];\nend\nfunction ave_distance(p, ps)\n    length(ps) == 0 && return zero(eltype(p))\n    ds = distance(p,ps)\n    return sum(ds)/length(ps);\nend\nfunction generate_test_2d_data(k; r = 35, n = 1000)\n    cs = [(rand()*r,rand()*r) for i in 1:k];\n    dt = Vector{Tuple{Float64,Float64}}();\n    xr = randn(n);\n    yr = randn(n);\n    for rd in 1:n\n        for c in cs\n            push!(dt, (xr[rd] + c[1], yr[rd] + c[2]))\n        end\n    end\n    return dt;\nend\nexport fake_data\nfunction fake_data()\n    return get_perfect_data();\nend\nfunction remove(col::Vector, td)\n    col[[1:(td-1);(td+1):end]];\nend\nfunction remove!(col::Vector, td)\n    temp = remove(col,td);\n    pop!(col);\n    col .= temp;\n    return col;\nend\n", "meta": {"hexsha": "c6503ba337660775a7ccd5c0d526ba4ae51db0a8", "size": 1766, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Tools.jl", "max_stars_repo_name": "josePereiro/KMeanClusttering.jl", "max_stars_repo_head_hexsha": "44328608e979066b773ac4c4246dec595b93a161", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Tools.jl", "max_issues_repo_name": "josePereiro/KMeanClusttering.jl", "max_issues_repo_head_hexsha": "44328608e979066b773ac4c4246dec595b93a161", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Tools.jl", "max_forks_repo_name": "josePereiro/KMeanClusttering.jl", "max_forks_repo_head_hexsha": "44328608e979066b773ac4c4246dec595b93a161", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8732394366, "max_line_length": 72, "alphanum_fraction": 0.5775764439, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7724457353267716}}
{"text": "#=\n\n    This is a port of the SPPL model random-sequence.pynb\n    \"\"\"\n    In this notebook, we will implement and query the following probabilistic model of a random sequence in SPPL.\n\n    For i=0, X[0]  is a standard normal.\n    For i>0 \n        if  X[i−1] is negative, then  X[i] is a standard normal\n        otherwise, let  W[i] be the outcome of a fair coin:\n            if  W[i]=0 , then  X[i]=0.5∗(X[i−1])2+X[i−1] \n            othewrise(sic!),  X[i] is a standard normal.\n\n    \"\"\"\n\n    The SPPL model give the following (exact) probabilities\n    (adjusted for Python's 0 base):\n\n    * Pr(X[1]>0)\t\t    = 0.50\n    * Pr(X[1]>0 | X[2]>0)\t= 0.647\n    * Pr(X[1]>0 | X[3]>0)\t= 0.544\n\n\n    This model:\n\n    We want the probability of X[1] > 0 given by:\n    * No observation:  \n           t    mean: 0.5046   std: 0.5000\n\n    * We observe X[2] > 0\n           t    mean:0.6420    std:0.4797\n\n    * We observe X[3] > 0\n           t    mean: 0.5402   std: 0.4984 \n\n=#\n\nusing Turing, StatsPlots, Distributions, StatsBase\nusing CSV\ninclude(\"jl_utils.jl\")\n\n@model function random_sequence() \n    X = tzeros(3)\n    W = tzeros(3)\n    \n    X[1] ~ Normal()\n    for i in 2:3\n        if X[i-1] > 0\n            X[i] ~ Normal(0, 1)\n            W[i] ~ Dirac(0.0)\n        else\n            W[i] ~ Bernoulli(0.5)\n            if W[i] == 0\n                X[i] ~ Dirac( 0.5*X[i-1]^2 + X[i-1])  # Dirac((X[i-1]^2 / 2 + X[i-1])\n            else\n                X[i] ~ Normal(0, 1)\n            end \n        end\n    end\n\n    # Observations:\n    true ~ Dirac(X[2] > 0)\n    # true ~ Dirac(X[3] > 0)\n\n    # What is the probability that X[1] > 0?\n    t ~ Dirac(X[1] > 0)\nend \n\nmodel = random_sequence()\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(10), 1_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 10_000)\n\n# chns = sample(model, HMC(0.1,6), 1_000)\n# chns = sample(model, NUTS(), 1_000)\n\ndisplay(chns[[:t]])\ndisplay(chns)\n", "meta": {"hexsha": "8096cf07b4c041a1f95a2f6bbc466378a01527a1", "size": 1977, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/random_sequence.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/random_sequence.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/random_sequence.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 24.1097560976, "max_line_length": 113, "alphanum_fraction": 0.5240263025, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.8705972667296309, "lm_q1q2_score": 0.7723979021094829}}
{"text": "using Hydrogen\nusing AtomicLevels\nusing Test\n\n# The Lyman and Balmer series radial dipole moments are given by\n# Eq. (63.4)\n\nlyman²(n) = 2^8*n^7*(n-1)^(2n-5)/((n+1)^(2n+5))\n\nbalmer_s²(n) = 2^17*n^7*(n^2-1)*(n-2)^(2n-6)/((n+2)^(2n+6))\n\nfunction balmer_p²(n,ℓ)\n    if ℓ == 0\n        2^15*n^9*(n-2)^(2n-6)/(3*(n+2)^(2n+6))\n    elseif ℓ == 2\n        2^19*n^9*(n^2-1)*(n-2)^(2n-7)/(3*(n+2)^(2n+7))\n    end\nend\n\nfunction lyman_balmer²(o, n, ℓ)\n    # Eq. (BS63.5)\n    n == o.n && return (3/2*n*√(n^2-max(ℓ,o.ℓ)^2))^2\n    n = float(n)\n    if o == o\"1s\"\n        lyman²(n)\n    elseif o == o\"2s\"\n        balmer_s²(n)\n    elseif o == o\"2p\"\n        balmer_p²(n, ℓ)\n    end\nend\n\n@testset \"Hydrogen.jl\" begin\n    @testset \"Factorial ratios\" begin\n        for a = 1:6\n            for b = 1:6\n                @test Hydrogen.factorial_ratio(a,b) == factorial(a)/factorial(b)\n            end\n        end\n    end\n\n    @testset \"Radial dipole moments\" begin\n        # We cannot compare with Table 13 of Bethe and Salpeter 1977,\n        # since it provides so few figures and some of the values\n        # appear to be wrong. Instead, we compare with the specific\n        # formulas for the Lyman and Balmer series.\n\n        for (j,(o,ℓ′)) in enumerate([(o\"1s\",1), (o\"2s\",1), (o\"2p\",0), (o\"2p\",2)])\n            for n′ = 1+ℓ′:8\n                @test radial_dipole_moment(o, Orbital(n′, ℓ′))^2 ≈\n                    lyman_balmer²(o, n′, ℓ′)\n            end\n        end\n    end\n\n    @testset \"Orbitals\" begin\n        # Error conditions:\n        @test_throws ArgumentError non_relativistic_orbital(0, 0)\n        @test_throws ArgumentError non_relativistic_orbital(-1, 0)\n        @test_throws ArgumentError non_relativistic_orbital(1, 1)\n        @test_throws ArgumentError non_relativistic_orbital(2, -1)\n        @test_throws MethodError non_relativistic_orbital(2.5, -1)\n        # Check values:\n        P10 = non_relativistic_orbital(1, 0)\n        @test P10(0) ≈ 0.0\n    end\nend\n", "meta": {"hexsha": "3487c4438bffe14802a5b6a4b3ed2198a03ee093", "size": 1952, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JuliaAtoms/Hydrogen.jl", "max_stars_repo_head_hexsha": "b92a18f86d42bbf60990960339748dc95d6ec655", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "JuliaAtoms/Hydrogen.jl", "max_issues_repo_head_hexsha": "b92a18f86d42bbf60990960339748dc95d6ec655", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-05-28T00:44:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T10:40:30.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "JuliaAtoms/Hydrogen.jl", "max_forks_repo_head_hexsha": "b92a18f86d42bbf60990960339748dc95d6ec655", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-16T01:57:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-16T01:57:06.000Z", "avg_line_length": 28.7058823529, "max_line_length": 81, "alphanum_fraction": 0.5635245902, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522863, "lm_q2_score": 0.8152324915965393, "lm_q1q2_score": 0.7723358111536806}}
{"text": "#\n#--------------------------------------#\nexport linearFEM\n#--------------------------------------#\n\"\"\"\n 1D linear FEM operators in (0,1)\n\"\"\"\nfunction linearFEM(N)\n\n\tn  = N + 1\n\tdz = 1/N\n    z  = linspace(0,1,n)\n\n    dn = ones(n)\n    dN = ones(N)\n\n    A = Tridiagonal(-1*dN,2*dn ,-1*dN) / dz # == D'*B*D\n    B = Tridiagonal(1dN/6,2dn/3,1dN/6) * dz\n    C = Tridiagonal(-dN/2,0dn  ,dN/2)        # == B * D\n    D = Tridiagonal( 0dN ,-1dn ,1dN)   / dz  # attempt second order?\n\n    A[1,1]     = 0.5 * A[1,1]\n    A[end,end] = 0.5 * A[end,end]\n\n    B[1,1]     = 0.5 * B[1,1]\n    B[end,end] = 0.5 * B[end,end]\n\n    w = B * ones(n)\n\nreturn z,w,A,B,C,D\nend\n", "meta": {"hexsha": "a45ff2f693f53892aa8f4694b6346e636eb9bd98", "size": 649, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fem.jl", "max_stars_repo_name": "vpuri3/reluFEM", "max_stars_repo_head_hexsha": "c488332f106d358a5bfefd4b3ea5fc3666aa8b12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-24T22:25:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T22:25:26.000Z", "max_issues_repo_path": "src/fem.jl", "max_issues_repo_name": "vpuri3/reluFEM", "max_issues_repo_head_hexsha": "c488332f106d358a5bfefd4b3ea5fc3666aa8b12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-08-17T20:35:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-17T20:59:13.000Z", "max_forks_repo_path": "src/fem.jl", "max_forks_repo_name": "vpuri3/reluFEM", "max_forks_repo_head_hexsha": "c488332f106d358a5bfefd4b3ea5fc3666aa8b12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.28125, "max_line_length": 68, "alphanum_fraction": 0.4252696456, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092411, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.772335810534267}}
{"text": "\"\"\"\n    MIPVerify(optimizer)\n\nMIPVerify computes maximum allowable disturbance using mixed integer linear programming.\n\n# Problem requirement\n1. Network: any depth, ReLU activation\n2. Input: hyperrectangle\n3. Output: halfspace\n\n# Return\n`AdversarialResult`\n\n# Method\nMILP encoding. Use presolve to compute a tight node-wise bounds first.\nDefault `optimizer` is `GLPKSolverMIP()`.\n\n# Property\nSound and complete.\n\n# Reference\n\nV. Tjeng, K. Xiao, and R. Tedrake,\n[\"Evaluating Robustness of Neural Networks with Mixed Integer Programming,\"\n*ArXiv Preprint ArXiv:1711.07356*, 2017.](https://arxiv.org/abs/1711.07356)\n\n[https://github.com/vtjeng/MIPVerify.jl](https://github.com/vtjeng/MIPVerify.jl)\n\"\"\"\n@with_kw struct MIPVerify{O<:AbstractMathProgSolver}\n    optimizer::O\nend\n\nfunction solve(solver::MIPVerify, problem::Problem)\n    model = Model(solver = solver.optimizer)\n    neurons = init_neurons(model, problem.network)\n    deltas = init_deltas(model, problem.network)\n    add_complementary_set_constraint!(model, problem.output, last(neurons))\n    bounds = get_bounds(problem)\n    encode_mip_constraint!(model, problem.network, bounds, neurons, deltas)\n    o = max_disturbance!(model, first(neurons) - problem.input.center)\n    status = solve(model, suppress_warnings = true)\n    if status == :Infeasible\n        return AdversarialResult(:SAT)\n    end\n    if getvalue(o) >= minimum(problem.input.radius)\n        return AdversarialResult(:SAT)\n    else\n        return AdversarialResult(:UNSAT, getvalue(o))\n    end\nend", "meta": {"hexsha": "cee142e01aec8612a717053f028620ac5ccb83ba", "size": 1520, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/optimization/mipVerify.jl", "max_stars_repo_name": "awesome-archive/NeuralVerification.jl", "max_stars_repo_head_hexsha": "ea68308ca1594787f508cde583e1e34b4b3a25db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/optimization/mipVerify.jl", "max_issues_repo_name": "awesome-archive/NeuralVerification.jl", "max_issues_repo_head_hexsha": "ea68308ca1594787f508cde583e1e34b4b3a25db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimization/mipVerify.jl", "max_forks_repo_name": "awesome-archive/NeuralVerification.jl", "max_forks_repo_head_hexsha": "ea68308ca1594787f508cde583e1e34b4b3a25db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4, "max_line_length": 88, "alphanum_fraction": 0.7401315789, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810421953309, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7723358096466596}}
{"text": "#    Problem : GROUP A\n#    *********\n#    Another function with nontrivial groups and repetitious elements.\n#\n#    Original SIF Source:\n#    N. Gould, private communication.\n#\n#    Implementation translated from Source:\n#    http://eprints.tsu.ge/234/14/Tests%20collection-K-F.pdf\n#\n#    COSINE.SIF classification OUR2-AN-V-0\n#\n#    Number of variables (variable)\n\nf = (x) -> begin\n    fx = 0.0\n    for i in 1:lastindex(x)-1\n        α = -0.5x[i+1]+x[i]^2\n        fx += cos(α)\n    end\n    return fx\nend\n\ng! = (g, x) -> begin\n    for i in 1:lastindex(x)-1\n        α = -0.5x[i+1]+x[i]^2\n        g[i] -= 2.0sin(α)x[i]\n        g[i+1] += 0.5sin(α)\n    end\n    return g\nend\n \nfg! = (g, x) -> begin\n    fx = 0.0 \n    for i in 1:lastindex(x)-1\n        α = -0.5x[i+1]+x[i]^2\n        fx += cos(α)\n        g[i] -= 2.0sin(α)*x[i]\n        g[i+1] += 0.5sin(α)\n    end\n    return fx, g\nend\n\ninit = (n::Int=10000) -> begin\n    n < 2 && @warn(\"COSINE: number of variables must be ≥ 2\")\n    return n, ones(n)\nend\n\nTestSet[\"COSINE\"] = UncProgram(\"COSINE\", f, g!, fg!, init)", "meta": {"hexsha": "aee67871988066fac29fcd44dad9de20566f7622", "size": 1054, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/programs/COSINE.jl", "max_stars_repo_name": "danphenderson/UncNLPrograms.jl", "max_stars_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/programs/COSINE.jl", "max_issues_repo_name": "danphenderson/UncNLPrograms.jl", "max_issues_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/programs/COSINE.jl", "max_forks_repo_name": "danphenderson/UncNLPrograms.jl", "max_forks_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5102040816, "max_line_length": 70, "alphanum_fraction": 0.5284629981, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810407096791, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7723358063090741}}
{"text": "export rref, rref!, solve, solve_augmented\n\n\"\"\"\n`swap_rows!(A,i,j)` swaps rows `i` and `j` in the matrix `A`.\n\"\"\"\nfunction swap_rows!(A::Array{T,2}, i::Int, j::Int) where T\n  if i==j\n    return nothing\n  end\n  A[ [i,j], :] = A[ [j,i], :]\n  return nothing\nend\n\n\n\"\"\"\n`add_row_to_row!(A,i,j)` adds row `i` to row `j` in the matrix `A`.\n\"\"\"\nfunction add_row_to_row!(A::Array{T,2},i::Int,j::Int) where T<:Number\n  A[j,:] += A[i,:]\n  return nothing\nend\n\n# The following functions developed by Tara Abrishami\n\n\"\"\"\n`rref!(A)` overwrites `A` with its row reduced echelon form.\n\"\"\"\nfunction rref!(A::Array{GF2,2})\n  r, c = size(A)\n  s = 0\n  for x in 1:r\n    b = false\n    while !b && x + s <= c\n      if A[x, x+s] == 1\n        break\n      elseif A[x, x + s] == 0\n        for y in x:r\n          if A[y, x + s] == 1\n            swap_rows!(A, y, x)\n            b = true\n            break\n          end\n        end\n      end\n      if !b\n        s = s + 1\n      end\n    end\n    for m in 1:r\n      if x + s <= c && m != x && A[m, x+s] == 1\n        add_row_to_row!(A, x, m)\n      end\n    end\n  end\nend\n\n\"\"\"\n`rref(A)` returns the row reduced echelon form of `A`.\n\"\"\"\nfunction rref(A::Array{GF2,2})\n  AA = copy(A)\n  rref!(AA)\n  return AA\nend\n\n\n\"\"\"\n`solve(A,b)` returns a solution `x` to the linear system\n`A*x == b` or throws an error if no solution can be found.\n\"\"\"\nfunction solve(A::Array{GF2, 2}, b::Array{GF2, 1})\n  r, c = size(A)\n  if r != size(b)[1]\n    error(\"Dimensionally incorrect input\")\n  end\n  C = [A b]\n  return solve_augmented(C)\nend\n\n# returns a single solution to the system with matrix C1\nfunction solve_augmented(C1::Array{GF2, 2})\n  r, c = size(C1)\n  D = copy(C1)\n  rref!(D)\n  x = 0\n  for a in 1:r\n   in = true\n   for b in 1:c-1\n     if D[a, b] != 0\n       in = false\n     end\n   end\n   if in && D[a, c] != 0\n     error(\"Inconsistent system\")\n   end\n  end\n  ret = zeros(GF2, c-1)\n  for p in 1:r\n    if D[p, c] == 1\n      for n in 1:c-1\n        if D[p, n] == 1\n          ret[n] = 1\n          break\n        end\n      end\n    end\n  end\n  return ret\nend\n\n\n\nimport Base.inv\n\nfunction inv(A::Array{GF2,2})\n  n,m = size(A)\n  if n!= m\n    error(\"Cannot invert a matrix that isn't square.\")\n  end\n  if det(A)==0\n    error(\"Cannot invert a singular matrix.\")\n  end\n  In = Matrix{GF2}(I,n,n)\n\n  AB = [A  In]\n  rref!(AB)\n\n  B = AB[:,n+1:end]\n  return B\nend\n\n\n\n\n\nfunction LinearAlgebra.nullspace(A::Array{GF2, 2})\n  r, c = size(A)\n  M = rref(A)\n  ret = zeros(GF2, c)\n  s = 0\n  x = 1\n  left = false\n  while x <= c\n    if x > r\n      left = true\n      break\n    end\n    if x + s > c\n      break\n    end\n    if M[x, x+s] == 1\n      x = x + 1\n      continue\n    else\n      p = zeros(GF2, c)\n      p[x + s] = 1\n      for t in 1:r\n        if M[t, x + s] == 1\n          for q in 1:c\n            if M[t, q] == 1\n              p[q] = 1\n              break\n            end\n          end\n        end\n      end\n      s = s + 1\n      ret = hcat(ret, p)\n    end\n  end\n  if left\n    while x + s <= c\n      p = zeros(GF2, c)\n      p[x + s] = 1\n      for t in 1:r\n        if M[t, x + s] == 1\n          for q in 1:c\n            if M[t, q] == 1\n              p[q] = 1\n              break\n            end\n          end\n        end\n      end\n      s = s + 1\n      ret = hcat(ret, p)\n    end\n  end\n  ret = ret[:, 1:size(ret,2) .!= 1]\n  return ret\nend\n\nexport solve_all\n\"\"\"\n`solve_all(A,b)` returns a solution to `A*x==b` together with\na basis for the nullspace of `A`.\n\"\"\"\nfunction solve_all(A::Array{GF2, 2}, b::Array{GF2, 1})\n  return solve(A, b), nullspace(A)\nend\n\nexport nullity\n\"\"\"\n`nullity(A)` returns the dimension of the nullspace of `A`.\n\"\"\"\nfunction nullity(A::Array{GF2,2})\n  NS = nullspace(A)\n  (x,n) = size(NS)\n  return n\nend\n\nfunction LinearAlgebra.rank(A::Array{GF2,2})\n  r,c = size(A)\n  n = nullity(A)\n  return c-n\nend\n", "meta": {"hexsha": "37168ffa3e17cbaf9851006ca5d4462578426da1", "size": 3802, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solving.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleGF2.jl-26dc7fb7-0d88-57af-8ff4-0a7e14249ddd", "max_stars_repo_head_hexsha": "9901f5bfa9cf6f2b77f57ead4ad7853b93f17d85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/solving.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleGF2.jl-26dc7fb7-0d88-57af-8ff4-0a7e14249ddd", "max_issues_repo_head_hexsha": "9901f5bfa9cf6f2b77f57ead4ad7853b93f17d85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solving.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleGF2.jl-26dc7fb7-0d88-57af-8ff4-0a7e14249ddd", "max_forks_repo_head_hexsha": "9901f5bfa9cf6f2b77f57ead4ad7853b93f17d85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5207373272, "max_line_length": 69, "alphanum_fraction": 0.5028932141, "num_tokens": 1385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7722990144198438}}
{"text": "# ---\n# title: 224. Basic Calculator\n# id: problem224\n# author: Qling\n# date: 2021-03-10\n# difficulty: Hard\n# categories: Math, Stack\n# link: <https://leetcode.com/problems/basic-calculator/description/>\n# hidden: true\n# ---\n# \n# Implement a basic calculator to evaluate a simple expression string.\n# \n# The expression string may contain open `(` and closing parentheses `)`, the\n# plus `+` or minus sign `-`, **non-negative** integers and empty spaces ` `.\n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: \"1 + 1\"\n#     Output: 2\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: \" 2-1 + 2 \"\n#     Output: 3\n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: \"(1+(4+5+2)-3)+(6+8)\"\n#     Output: 23\n# \n# **Note:**\n# \n#   * You may assume that the given expression is always valid.\n#   * **Do not** use the `eval` built-in library function.\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction calculate(s::String)::Int\n    res, num, sign, stk = 0, 0, 1, []\n    for c in s\n        if isdigit(c)\n            num = 10 * num + parse(Int, c)\n        elseif c in ['-', '+']\n            res += num * sign\n            num = 0\n            sign = (c == '-') ? -1 : 1\n        elseif c == '('\n            push!(stk, res)\n            push!(stk, sign)\n            res, sign = 0, 1\n        elseif c == ')'\n            res += num * sign\n            res *= pop!(stk)\n            res += pop!(stk)\n            num = 0\n        end\n    end\n\n    return res + num * sign\nend\n## @lc code=end\n", "meta": {"hexsha": "a5da4fdd796420ce95960d1d7697ded80b7e0024", "size": 1471, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/224.basic-calculator.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/224.basic-calculator.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/224.basic-calculator.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 20.4305555556, "max_line_length": 77, "alphanum_fraction": 0.4894629504, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338057771059, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7722787548464513}}
{"text": "using Plots\nusing BenchmarkTools\n\nfunction vfsolvex(vnew, kgrid, tolerance, imax, σ)\n    β = 0.9\n\n    v = vnew .+ 2*tolerance\n    cartesianindex = Array{CartesianIndex{2}, length(v)}\n    i = 1\n    \n    c = kgrid .- kgrid'\n    c[c .< 0] .= 0\n    u = (c .^ (1-σ) .- 1) ./ (1-σ)\n    u[kgrid .- kgrid' .< 0] .= -Inf\n\n    while maximum(abs.(v - vnew)) > tolerance && i <= imax\n        v = vnew;\n        \n        (vnew, cartesianindex) = findmax(u .+ β*v', dims = 2);\n        i += 1;\n    end\n    kprimeindex = getindex.(cartesianindex, 2)\n    return (v = vnew, kprime = kgrid[kprimeindex], kprimeindex = kprimeindex)\nend\n\n\nkupper = 5\nklower = 0.01\nn = 1000\nkgrid = collect(range(klower, stop = kupper, length = n))\n(v, kprime, kprimeindex) = vfsolvex(zeros(n), kgrid, 0.001, 1000, 1.5);\n\nscatter(kgrid, v, label = \"v\")\nscatter(kgrid, kprime, label = \"k'\")\n\nfunction policy(x)\n    e=getindex(findall(kgrid .== x),1)\n    return kprime[e]  \nend \n\nT = 100\nkpath = zeros(T)\nk = kgrid[1000]\nfor i in 1:T\n    k = policy(k)\n    kpath[i] = k\nend \ntime = collect(range(1, T, length = T))\nscatter(time, kpath, label = \"kpath\")\n", "meta": {"hexsha": "21e96530e132b534c3a3aa0e494b409620da2f42", "size": 1110, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Dynamic Programming/DM2.jl", "max_stars_repo_name": "paradoxuu/AS-1", "max_stars_repo_head_hexsha": "3d7b03e5806dca30dcd19a7a6acdea9c994bbde7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Dynamic Programming/DM2.jl", "max_issues_repo_name": "paradoxuu/AS-1", "max_issues_repo_head_hexsha": "3d7b03e5806dca30dcd19a7a6acdea9c994bbde7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Dynamic Programming/DM2.jl", "max_forks_repo_name": "paradoxuu/AS-1", "max_forks_repo_head_hexsha": "3d7b03e5806dca30dcd19a7a6acdea9c994bbde7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2, "max_line_length": 77, "alphanum_fraction": 0.5783783784, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7722550770891834}}
{"text": "ENV[\"GKSwstype\"] = \"100\" #src\n\n# # Getting Started with Data Science in Julia\n#\n# > [A]lways bite the bullet with regard to understanding the basics of the data first before you do anything else...\n# >\n# > \\- Caitlin Smallwood, Vice President of Science and Algorithms at Netflix\n\nprintln(\"Hello, Data Science World!\")\n\n# # What does your data look like?\n#\n# Before you can solve complex problems with data, you should have a firm grasp on what your data looks like.  Are your variables continuous or categorical?  What do the distributions look like?  Are there missing observations?  Are variables correlated?  All of these questions arise in the data science workflow, so it's helpful to know the answers from the start of your analysis.\n\n# Let's start with loading the [**`Statistics`**](https://docs.julialang.org/en/latest/stdlib/Statistics/) package, which provides basic statistical operations like means, variances, etc.\n\nusing Statistics\n\n# You can examine the items that a package exports with the `names` function.\n\nnames(Statistics)\n\n# To start, let's try some of the functions from **`Statistics`** on simulated data.\n\nx = randn(100, 3)\n\nmean(x, dims=1)  # calculate over first dimension (column means)\n\n#-\n\ncor(x)  # correlation matrix  \n\n# For a more realistic example, let's load some data from the **`RDatasets`** package, which has a large collection of datasets that get loaded as a `DataFrame`.  \n\n# The [`\"iris\"` dataset](https://en.wikipedia.org/wiki/Iris_flower_data_set) is a collection of measurements for three different species of the iris flower: Iris Setosa, Iris Virginica, and Iris Versicolor (shown below).  The measurements consist of length and width of the petal and sepal (part underneath the flower).\n\n# <img src=\"https://upload.wikimedia.org/wikipedia/commons/4/41/Iris_versicolor_3.jpg\" width=400>\n\nusing RDatasets\n\niris = dataset(\"datasets\", \"iris\")\n\n# DataFrames are discussed in another course module.  For now, we'll just use the fact that data vectors from the DataFrame can be selected with `mydf.mycol`:\n\niris.SepalLength\n\n# What is the average sepal width across all three species?\n\nmean(iris.SepalWidth)\n\n# Maximum and minimum?\n\n@show minimum(iris.SepalWidth)\n@show maximum(iris.SepalWidth)\nextrema(iris.SepalWidth)\n\n# Is petal width correlated with petal length?\n\ncor(iris.PetalWidth, iris.PetalLength)\n\n# While we could examine each column separately, a much quicker way to summarize our variables is with the `describe` function:\n\ndescribe(iris)\n\n\n# # Random Sampling\n#\n# <img src=\"assets/sample.png\" width=400>\n#\n# [Random Sampling](https://en.wikipedia.org/wiki/Sampling_(statistics)) plays an integral part in many data science tasks, such as:\n#\n# - Splitting data into multiple datasets for [cross validation](https://en.wikipedia.org/wiki/Cross-validation_(statistics)).\n# - Subsampling a large dataset to something more manageable.\n# - Running statistical simulations.\n# - [Statistical Bootstrap](https://en.wikipedia.org/wiki/Bootstrapping_(statistics))\n#\n# The **`StatsBase`** package has the `sample` function to factilitate sampling [with or without replacement](https://en.wikipedia.org/wiki/Sampling_(statistics)#Replacement_of_selected_units).\n# Imagine you had a bag with 20 numbers in it.\n# Sampling with replacement means that you put the number you drew back into the bag before the next draw.\n# Just like rolling a dice, each draw is _independent_ and a given number might get drawn again.\n# On the other hand, if you were to _not_ put the drawn number back in the bag, that would be representative of sampling without replacement.\n# Each draw is _dependent_ upon all previous draws as those numbers are no longer available for selection.\n# For bootstrapping and statistical simulations, it's typical to use sampling with replacement.\n# While the two behave nearly the same if the sample is a very small fraction of the overall population, it becomes important to sample without replacement if the sample is large or if using uneven importance weights.\n\nusing StatsBase\n\ny1 = sample(1:20, 20, replace=true)  # replaces units after being selected\n\n#-\n\ny2 = sample(1:20, 20, replace=false)  # DOES NOT replace units after being selected\n\n# Next we'll use the [`countmap`](http://juliastats.github.io/StatsBase.jl/latest/search.html?q=countmap) function to get the count of each unique value in our samples.  Notice that when we do sampling *without* replacement, the values will only appear one time.  When sampling *with* replacement, any given selected item is then placed back into the pool of possible items to select from.\n\ncountmap(y1)\n\n#- \n\ncountmap(y2)\n\n# This is just a small sample (pun intended) of the features in **`StatsBase`**.  For a more complete look of what is possible, check out the [documentation](http://juliastats.github.io/StatsBase.jl/latest/index.html).\n\n\n\n\n# # Parametric Distributions\n#\n# The [**`Distributions`**](https://github.com/JuliaStats/Distributions.jl) package provides an interface for working with probability distributions.  The full documentation is [here](https://juliastats.github.io/Distributions.jl/stable/).  \n\n# Here we'll also load the **`StatsPlots`** package (more on this in the next course module) to visualize the probability distributions.\n\nusing Distributions, StatsPlots\n\nplot(Normal(), label = \"Normal(0, 1)\")\n\n#-\n\nplot!(Gamma(5, 1), label = \"Gamma(5, 1)\")\n\n# The package defines a number of functions that together create a consistent \"grammar\" for discussing distributions:\n#\n# - Probability density function: `pdf`\n# - Cumulative distribution function: `cdf`\n# - The inverse cumulative distribution function with the standard `quantile` statistical function\n# - etc.\n\n\nd = Normal()\n\npdf(d, 0), cdf(d, 0), mean(d), var(d), quantile(d, .5), mode(d)\n\n#-\n\nd = Gamma(5, 1)\n\npdf(d, 0), cdf(d, 0), mean(d), var(d), quantile(d, .5), mode(d)\n\n# As an example, let's write a function that uses [Newton's Method](https://en.wikipedia.org/wiki/Newton%27s_method) that can find a given quantile for any continuous univariate distribution.  Newton's method attempts to find the root for a function $f$ by performing iterations of the form:\n#\n# $$\\theta^{(t)} = \\theta^{(t-1)} - \\frac{f(\\theta^{(t-1)})}{f'(\\theta^{(t-1)})}.$$\n#\n# For quantiles, we want to find the root of the function $F(\\theta) - q$ where $F$ is the cumulative density function of the distribtuion and $q \\in (0, 1)$.  Using **`Distributions`**, this looks something like\n\nfunction myquantile(d::Distribution, q::Number)\n    θ = mean(d)\n    for i in 1:20\n        θ -= (cdf(d, θ) - q) / pdf(d, θ)  # θ = θ - (F(θ) - q) / F'(θ)\n    end\n    θ\nend\n\n# Does our `myquantile` function work as expected?  Let's try out our function on several distributions.\n\nd = Normal()\nmyquantile(d, .5), quantile(d, .5)\n\n#-\n\nd = Gamma(4,3)\nmyquantile(d, .7), quantile(d, .7)\n\n# The above example shows off the power of generic functions.  Instead of hard-coding the distribution (as would be necessary in R), we can write functions in terms of an arbitrary distribution (without extra effort).  This gives us a lot of flexibility for tasks such as writing [Gibbs Samplers](https://en.wikipedia.org/wiki/Gibbs_sampling) that can swap out distributions with ease.\n", "meta": {"hexsha": "daa129be37957321bd3e2bc143ef4d436147df82", "size": 7226, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Data_Science_1/02-getting-started.jl", "max_stars_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_stars_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2020-02-13T00:50:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T07:57:22.000Z", "max_issues_repo_path": "Courses/Data_Science_1/02-getting-started.jl", "max_issues_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_issues_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2019-10-30T16:22:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-26T20:02:43.000Z", "max_forks_repo_path": "Courses/Data_Science_1/02-getting-started.jl", "max_forks_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_forks_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2020-02-26T11:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T22:34:53.000Z", "avg_line_length": 44.0609756098, "max_line_length": 389, "alphanum_fraction": 0.743980072, "num_tokens": 1806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7722550715512347}}
{"text": "#script for the 2D Linear elasticity problem\n#plate with a hole under tension at infinity benchmark\ninclude(\"../src/Solver2D.jl\")\ninclude(\"../src/SplinePlotting.jl\")\n\n#Material properties\nEmod = 1e5\nnu = 0.3\nCmat = Emod/(1-nu^2)*[1  nu  0; nu  1  0; 0  0  (1-nu)/2]\nmaterial = Material2D(Emod, nu, Cmat)\n\n#define the domain geometry\nR = 1.\nL = 4.\ncenter = [0., 0.]\nsang = π/2\neang = π\n\nbottom_crv =  nrbcirc(R, center, sang, eang)\nbottom_crv = nrbreverse(bottom_crv)\nright_seg = nrbline([0, R], [0, L])\nleft_seg = nrbline([-R, 0], [-L, 0])\nup_seg = nrbline([-L, 0], [-L, L], [0, L])\nnrb = nrbcoons(bottom_crv, up_seg, left_seg, right_seg)\n\n#degree elevate and refine\ndegP = [3, 3]\nnum_subdiv = [10, 20]\nnrb = nrbdegelev(nrb, degP.+1-nrb.order)\n_, _, new_knots = kntrefine(nrb.knots, num_subdiv, degP, degP.-1)\nnrb = nrbkntins(nrb, new_knots)\n# Plots.surface(reuse = false)\n# plt = nrbctrlplot(nrb)\n# display(plt)\n\n#symmetry Dirichlet B.C., u_y = 0 for y=0 and u_x=0 for x=0\nu_bound_dir_symy0(x,y) = [undef, 0]\nu_bound_dir_symx0(x,y) = [0, undef]\n# traction at infinity\ntx = 10\n\n\n#define the exact solution\nfunction exact_disp(x,y)\n    cart2pol(x, y) = hypot(x, y), atan(y, x)\n    r, th = cart2pol(x, y)\n    ux = (1+nu)/Emod*tx*(1/(1+nu)*r*cos(th)+2*R^2/((1+nu)*r)*cos(th)+R^2/(2*r)*cos(3*th)-R^4/(2*r^3)*cos(3*th))\n    uy = (1+nu)/Emod*tx*(-nu/(1+nu)*r*sin(th)-(1-nu)*R^2/((1+nu)*r)*sin(th)+\n            R^2/(2*r)*sin(3*th)-R^4/(2*r^3)*sin(3*th))\n    return [ux, uy]\nend\n\nfunction exact_stress(x,y)\n    cart2pol(x, y) = hypot(x, y), atan(y, x)\n    r, th = cart2pol(x, y)\n    sigma_rr = tx/2*(1-R^2/r^2)+tx/2*(1-4*R^2/r^2+3*R^4/r^4)*cos(2*th) \n    sigma_tt = tx/2*(1+R^2/r^2)-tx/2*(1+3*R^4/r^4)*cos(2*th)\n    sigma_rt = -tx/2*(1+2*R^2/r^2-3*R^4/r^4)*sin(2*th)\n\n    A = [cos(th)^2 sin(th)^2 2*sin(th)*cos(th); sin(th)^2 cos(th)^2 -2*sin(th)*cos(th);\n        -sin(th)*cos(th) sin(th)*cos(th) cos(th)^2-sin(th)^2]\n    stress = A\\[sigma_rr;sigma_tt;sigma_rt]\n    return stress\nend\n\"\"\"\nDefine the Neumann boundary condition derived from the exact stresses\n\"\"\"\nfunction u_bound_neu(x,y)\n    tol_eq=1e-10\n    ex_stress = exact_stress(x,y)\n    if abs(x+L)<tol_eq \n        #on the boundary x=-L the outer normal is (-1, 0)\n        nx = -1\n        ny = 0\n    elseif abs(y-L)<tol_eq\n        #on the boundary y=L, the outer normal is (0, 1)\n        nx = 0\n        ny = 1\n    else\n        error(\"Point not on the Neumann boundary\")\n    end\n    tx = nx*ex_stress[1]+ny*ex_stress[3]\n    ty = nx*ex_stress[3]+ny*ex_stress[2]\n    return tx, ty\nend\n\nbound_left = Boundary2D(\"Dirichlet\", \"Left\", u_bound_dir_symy0)\nbound_right = Boundary2D(\"Dirichlet\", \"Right\", u_bound_dir_symx0)\nbound_up = Boundary2D(\"Neumann\", \"Up\", u_bound_neu)\nbound_all = [bound_left, bound_right, bound_up]\n\n#generate the NURBS mesh\nIGAmesh = genMesh(nrb)\n\ngauss_rule = [genGaussLegendre(degP[1]+1), genGaussLegendre(degP[2]+1)]\nstiff = assemble_stiff_elast2D(IGAmesh, Cmat, gauss_rule)\n#Assume no body forces  \nrhs = zeros(2*IGAmesh.numBasis)\nbcdof_all, elem_all = classifyBoundary2D(IGAmesh)\nlhs, rhs = applyBCnurbsElast(IGAmesh, bound_all, stiff, rhs, bcdof_all, elem_all, gauss_rule)\nprintln(\"Solving linear system with $(length(rhs)) DOFs\")\n@time sol0 = lhs\\rhs\n@time plotSolElast(IGAmesh, Cmat, sol0, \"PlateHoleC0\")\n@time plotSolErrorElast(IGAmesh, Cmat, sol0, exact_disp, exact_stress, \"PlateHoleC0Err\")\n@time relL2Err, relH1Err = compErrorNormElast(IGAmesh, Cmat, sol0, exact_disp, exact_stress, gauss_rule)\nprintln(\"Relative L2-norm error is $relL2Err\")\nprintln(\"Relative energy-norm error is $relH1Err\")\n\n", "meta": {"hexsha": "fbb97c0c540e4e14ea75056df068273bdcbea608", "size": 3569, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/PlateHoleC0.jl", "max_stars_repo_name": "canitesc/IGAPack.jl", "max_stars_repo_head_hexsha": "bb2b5e8d01afd9ca8a59055380ca00d2c8f951b1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-07-30T13:49:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T08:18:26.000Z", "max_issues_repo_path": "examples/PlateHoleC0.jl", "max_issues_repo_name": "canitesc/IGAPack.jl", "max_issues_repo_head_hexsha": "bb2b5e8d01afd9ca8a59055380ca00d2c8f951b1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/PlateHoleC0.jl", "max_forks_repo_name": "canitesc/IGAPack.jl", "max_forks_repo_head_hexsha": "bb2b5e8d01afd9ca8a59055380ca00d2c8f951b1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-30T13:49:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-09T11:32:36.000Z", "avg_line_length": 32.7431192661, "max_line_length": 111, "alphanum_fraction": 0.6550854581, "num_tokens": 1401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7722550697018082}}
{"text": "\"\"\"\n    Newton{M}\n\n`Newton` dispatches to the Newton direction for `LineSearch` algorithm and uses the Hessian \nin `TrustRegion` models.\n\n# Fields\n- `modify::M`: the Hessian modification method to enforce positive definiteness\n\"\"\"\nstruct Newton{M}\n    modify::M\nend\n\nNewton() = Newton(MultipleIdentity())\n\norder(::Newton) = SecondOrder()\n\nfunction approx_hessian(n::Newton, state)\n    ∇²f = state.∇²f\n    isposdef(∇²f) && return ∇²f\n    return n.modify(∇²f)\nend\n\nfunction direction(n::Newton, state)\n    ∇f = state.∇f\n    ∇²f = approx_hessian(n::Newton, state)\n    return -inv(∇²f) * ∇f\nend\n\n\"\"\"\n    MultipleIdentity{B, S}\n\nModify the Hessian by adding some multiples, τ, of the identity matrix, as described in \nNocedal and Wright's Numerical Optimization.\n\n# Fields\n- `β::B`: constant to compute appropriate τ\n- `scale::S`: scale factor to expand τ\n\"\"\"\nstruct MultipleIdentity{B, S}\n    β::B\n    scale::S\n\n    function MultipleIdentity(β, ρ)\n        β > 0 || error(\"β must be positive\")\n        ρ > 1 || error(\"ρ must be larger than 1\")\n        new{typeof(β), typeof(ρ)}(β, ρ)\n    end\nend\n\n\"\"\"\n    MultipleIdentity(; beta=1e-3, scale=2.0)\n\nInitiate `MultipleIdentity` method to modify the Hessian.\n\"\"\"\nMultipleIdentity(; beta=1e-3, scale=2.0) = MultipleIdentity(beta, scale)\n\nfunction (mi::MultipleIdentity)(∇²f::Matrix{T}) where T\n    β = T(mi.β)\n    scale = T(mi.scale)\n    τ = -minimum(diag(∇²f)) + β\n    h = similar(∇²f)\n    while true\n        h .= ∇²f + τ*I\n        isposdef(h) && return h\n        τ = max(scale*τ, β)\n    end\nend", "meta": {"hexsha": "0f02abef4eb3f42994ab4c0d018d1fb8a8546ac7", "size": 1536, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/multivariate/misc/newton.jl", "max_stars_repo_name": "lhnguyen-vn/Optini.jl", "max_stars_repo_head_hexsha": "81e94ff764daa9819edae4b4b8211726a7de0821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-24T21:26:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T21:26:59.000Z", "max_issues_repo_path": "src/multivariate/misc/newton.jl", "max_issues_repo_name": "lhnguyen-vn/Optini.jl", "max_issues_repo_head_hexsha": "81e94ff764daa9819edae4b4b8211726a7de0821", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multivariate/misc/newton.jl", "max_forks_repo_name": "lhnguyen-vn/Optini.jl", "max_forks_repo_head_hexsha": "81e94ff764daa9819edae4b4b8211726a7de0821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-18T21:08:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T21:08:54.000Z", "avg_line_length": 22.5882352941, "max_line_length": 92, "alphanum_fraction": 0.6412760417, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7722550678472155}}
{"text": "#\n# Quadratic fit\n# \n\nstruct Quadratic\n  a :: Float64\n  b :: Float64\n  c :: Float64\n  R :: Float64\n  x :: Vector{Float64}\n  y :: Vector{Float64}\n  ypred :: Vector{Float64}\n  residues :: Vector{Float64}\nend\n\n\"\"\"\n`fitquad(x,y)` or `fitquadratic(x,y)`\n\nObtains the quadratic fit: ``y = a*x^2 + b*x + c``\n\nOptional lower and upper bounds for a and b can be provided using, for example:\n\n```\nfitquad(x,y, lower(b=0.), upper(a=5.,b=7.) )\n```\nand the intercept `c` can be fixed with\n\n```\nfitquad(x,y, c=3.)\n```\n\n# Examples\n```jldoctest\njulia>  x = sort(rand(10)); y = x.^2 .+ rand(10);\n\njulia> fit = fitquad(x,y)\n\n ------------------- Quadratic Fit ------------- \n\n Equation: y = ax^2 + bx + c \n\n With: a = 1.9829681649993036\n       b = -1.24215737650827\n       c = 0.9410816080128867\n\n Pearson correlation coefficient, R = 0.8452759310204063\n Average square residue = 0.039620067833833005\n\n Predicted Y: ypred = [0.778952191090992, 0.7759243614999851...\n residues = [0.0550252612868799, -0.15207394277809727...\n\n ----------------------------------------------- \n\n```\n\"\"\" \nfunction fitquadratic(X :: AbstractArray{<:Real}, Y :: AbstractArray{<:Real}; \n                      l :: lower = lower(), u :: upper = upper(), c = nothing,\n                      options :: Options = Options())\n  # Check data\n  X, Y = checkdata(X,Y,options)\n  # Set bounds\n  vars = [ VarType(:a,Number,1), \n           VarType(:b,Number,1),\n           VarType(:c,Nothing,1) ]\n  lower, upper = setbounds(vars,l,u)   \n  if c == nothing\n    # Set model\n    @. model(x,p) = p[1]*x^2 + p[2]*x + p[3]\n    # Fit\n    fit = find_best_fit(model, X, Y, length(vars), options, lower, upper)\n    # Analyze results and return\n    R = pearson(X,Y,model,fit)\n    x, y, ypred = finexy(X,options.fine,model,fit) \n    return Quadratic(fit.param...,R,x,y,ypred,fit.resid)\n  else\n    lower = lower[1:length(vars)-1]\n    upper = upper[1:length(vars)-1]\n    # Set model\n    @. model_const(x,p) = p[1]*x^2 + p[2]*x + c\n    # Fit\n    fit = find_best_fit(model_const, X, Y, length(vars)-1, options, lower, upper)\n    # Analyze results and return\n    R = pearson(X,Y,model_const,fit)\n    x, y, ypred = finexy(X,options.fine,model_const,fit) \n    return Quadratic(fit.param...,c,R,x,y,ypred,fit.resid)\n  end\nend\nfitquad = fitquadratic\n\nfunction Base.show( io :: IO, fit :: Quadratic )\n  println(\"\")\n  println(\" ------------------- Quadratic Fit ------------- \")\n  println(\"\")\n  println(\" Equation: y = ax^2 + bx + c \")\n  println(\"\")\n  println(\" With: a = \", fit.a)\n  println(\"       b = \", fit.b)\n  println(\"       c = \", fit.c)\n  println(\"\")\n  println(\" Pearson correlation coefficient, R = \", fit.R)\n  println(\" Average square residue = \", mean(fit.residues.^2))\n  println(\"\")\n  println(\" Predicted Y: ypred = [\",fit.ypred[1],\", \",fit.ypred[2],\"...\")\n  println(\" residues = [\", fit.residues[1],\", \",fit.residues[2],\"...\")\n  println(\"\")\n  println(\" ----------------------------------------------- \")\nend\n\nexport fitquad, fitquadratic\n", "meta": {"hexsha": "7f43a9bd2205e731ea684f9b2c638eb626abb507", "size": 2973, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fitquadratic.jl", "max_stars_repo_name": "m3g/EasyF", "max_stars_repo_head_hexsha": "601df86cb3927a195d91558a4027bb5e949771c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-04-07T12:58:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T13:42:50.000Z", "max_issues_repo_path": "src/fitquadratic.jl", "max_issues_repo_name": "m3g/EasyF", "max_issues_repo_head_hexsha": "601df86cb3927a195d91558a4027bb5e949771c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-17T14:34:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-24T14:19:10.000Z", "max_forks_repo_path": "src/fitquadratic.jl", "max_forks_repo_name": "m3g/EasyFit.jl", "max_forks_repo_head_hexsha": "601df86cb3927a195d91558a4027bb5e949771c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-08-19T20:58:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-17T18:43:12.000Z", "avg_line_length": 27.0272727273, "max_line_length": 81, "alphanum_fraction": 0.5691220989, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682086, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7722550678368838}}
{"text": "abstract type AbstractLQR <: AbstractController end\n\n\"\"\"\nInfinite-horizon continuous-time linear quadratic regulator (LQR).\n\"\"\"\nstruct LQR <: AbstractLQR\n    A\n    B\n    Q\n    R\nend\n\nfunction RunningCost(lqr::LQR)\n    @unpack Q, R = lqr\n    return function (x, u)\n        x'*Q*x + u'*R*u\n    end\nend\n\nfunction ARE_solution(lqr::LQR)\n    @unpack A, B, Q, R = lqr\n    P, _, _ = MatrixEquations.arec(A, B*inv(R)*B', Q)\n    P\nend\n\nfunction optimal_gain(lqr::LQR)\n    @unpack B, R = lqr\n    P = ARE_solution(lqr)\n    K = inv(R) * B' * P\nend\n\n\"\"\"\nMinimise J = ∫ (x' Q x + u' R u) from 0 to ∞\n\"\"\"\nfunction Command(lqr::LQR)\n    K = optimal_gain(lqr)\n    return function (x)\n        -K*x\n    end\nend\n\nfunction solutions(lqr::LQR)\n    P = ARE_solution(lqr)\n    K = optimal_gain(lqr)\n    optimal_controller = Command(lqr)\n    P, K, optimal_controller\nend\n", "meta": {"hexsha": "185450baa6d385e3ac91d05dcd53d36cec975589", "size": 845, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/environments/controllers/LQR.jl", "max_stars_repo_name": "JinraeKim/FSimZoo.jl", "max_stars_repo_head_hexsha": "3409a94e4f192008bc40d0edfec24e05ae9a5dc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-09-25T23:53:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T03:09:29.000Z", "max_issues_repo_path": "src/environments/controllers/LQR.jl", "max_issues_repo_name": "JinraeKim/FSimZoo.jl", "max_issues_repo_head_hexsha": "3409a94e4f192008bc40d0edfec24e05ae9a5dc5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-09-28T17:54:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T04:16:43.000Z", "max_forks_repo_path": "src/environments/controllers/LQR.jl", "max_forks_repo_name": "JinraeKim/FSimZoo.jl", "max_forks_repo_head_hexsha": "3409a94e4f192008bc40d0edfec24e05ae9a5dc5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-26T10:09:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-26T10:09:43.000Z", "avg_line_length": 17.6041666667, "max_line_length": 66, "alphanum_fraction": 0.6094674556, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197139, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7722288410749593}}
{"text": "##### MEAN-VARIANCE OPTIMIZATION\n#This is not supposed to produce great results, since mean and covariance\n#is supposed to be very exact before good weights are found\nusing JuMP\nusing Gurobi\nusing StatsBase\nusing DataFrames\nusing CSV\ninclude(\"SupportFunction.jl\")\ninclude(\"DataLoad.jl\")\nprintln(\"Leeeeroooy Jenkins\")\n#Esben's path\npath = \"$(homedir())/Documents/GitHub/Thesis/Data/MonthlyReturns\"\n\nmainData = loadIndexDataNoDurLOGReturn(path)\n\nmainDataArr = Array(mainData)\n\nstartRow = 1\nendRow = 100\ntrainingObservations = 100\nmainXarr = mainDataArr[startRow:endRow,1:10]\nindexes = size(mainXarr)[2]\n\n\n#### WITH RISK AVERSION\n\nnRows = size(mainDataArr)[1]\nnCols = size(mainDataArr)[2]\n\n##LOOP TO TEST IT\nportfolioMVTotal = []\nportfolioMVTotal = push!(portfolioMVTotal, 1)\nportfolioMVIndividual = []\nportfolioMVIndividual = push!(portfolioMVIndividual, 0)\nwMVtracker = zeros((nRows-trainingObservations-1),10)\n\n\nw1N = repeat([0.1], outer = 10)\nportfolio1NTotal = []\nportfolio1NTotal = push!(portfolio1NTotal, 1)\nportfolio1NIndividual = []\nportfolio1NIndividual = push!(portfolio1NIndividual, 0)\n\nfor rStart = 1:(nRows-trainingObservations-1)\n    startRow = rStart\n    endRow = (rStart-1)+trainingObservations\n    mainXarr = mainDataArr[startRow:endRow,1:10]\n    indexes = size(mainXarr)[2]\n\n    #creating the covariance matrix of the training data\n    Sigma = cov(mainXarr)\n\n    #creating the mean of the returns for SAA (forecasts should be used instead)\n    Mu = mean(mainXarr, 1)'\n\n    #setting risk aversion.\n    gamma = 10\n\n    M = JuMP.Model(solver = GurobiSolver(OutputFlag = 0))\n    @variables M begin\n            w[1:indexes]\n    end\n    @objective(M,Min, gamma*w'*Sigma*w-(Mu'*w)[1]) #efficient frontier\n    @constraint(M, 0 .<= w)\n    @constraint(M, sum(w[i] for i=1:indexes) == 1)\n\n    solve(M)\n    wStar = getvalue(w)\n    for i = 1:length(wStar)\n        if wStar[i] >=0.5\n            println(\"Index $i is chosen\")\n        end\n    end\n    wMVtracker[rStart,:] = wStar\n\n    #creating the forecastRow in arithmetic returns (not log returns)\n    #then we can multiply and sum across the row\n    forecastRow = exp(mainDataArr[(endRow+1):(endRow+1),1:10])\n\n    periodReturn = Array(forecastRow*wStar)[1]\n    currentLength = length(portfolioMVTotal)\n    portfolioMVTotal = push!(portfolioMVTotal, portfolioMVTotal[currentLength]*periodReturn)\n    portfolioMVIndividual = push!(portfolioMVIndividual, periodReturn)\n\n    period1NReturn = Array(forecastRow*w1N)[1]\n    current1NLength = length(portfolio1NTotal)\n    portfolio1NTotal = push!(portfolio1NTotal, portfolio1NTotal[current1NLength]*period1NReturn)\n    portfolio1NIndividual = push!(portfolio1NIndividual, period1NReturn)\nend\n\n#Checking the total return of the portfolio by checking last index\nportfolioMVTotal[length(portfolioMVTotal)]\nportfolio1NTotal[length(portfolio1NTotal)]\n\nportfolioMVTotal = convert(Array{Float64,1}, portfolioMVTotal)\nportfolioMVIndividual = convert(Array{Float64,1}, portfolioMVIndividual)\n(mean(portfolioMVIndividual)-1)*100\nstd(portfolioMVIndividual)\nSharpeRatioMV = (mean(portfolioMVIndividual)-1)/std(portfolioMVIndividual)\n\nportfolio1NTotal = convert(Array{Float64,1}, portfolio1NTotal)\nportfolio1NIndividual = convert(Array{Float64,1}, portfolio1NIndividual)\n(mean(portfolio1NIndividual)-1)*100\nstd(portfolio1NIndividual)\nSharpeRatio1N = (mean(portfolio1NIndividual)-1)/std(portfolio1NIndividual)\n\ncombinedPortfolios = hcat(portfolioMVTotal, portfolio1NTotal, portfolioMVIndividual, portfolio1NIndividual)\nwritedlm(\"MV100obsG10versus1N.csv\", combinedPortfolios,\",\")\n\n\nwritedlm(\"MV100obsPortfolioWeightsG10.csv\", wMVtracker,\",\")\n\nfunction meanVariancePPDOptimization(fullX, startRow, endRow, gammaValue, meanForecasts)\n    mainXarr = fullX[startRow:endRow, 1:10]\n    w1N = repeat([0.1], outer = 10)\n\n    #creating the covariance matrix of the training data\n    Sigma = cov(mainXarr)\n\n    #using the PPD mean forecasts\n    Mu = meanForecasts\n\n    #setting risk aversion.\n    gamma = gammaValue\n\n    M = JuMP.Model(solver = GurobiSolver(OutputFlag = 0))\n    @variables M begin\n            w[1:indexes]\n    end\n    @objective(M,Min, gamma*w'*Sigma*w-(Mu'*w)[1]) #efficient frontier\n    @constraint(M, 0 .<= w)\n    @constraint(M, sum(w[i] for i=1:indexes) == 1)\n\n    solve(M)\n    wStar = getvalue(w)\n\n    #creating the forecastRow in arithmetic returns (not log returns)\n    #then we can multiply and sum across the row\n    forecastRow = exp(fullX[(endRow+1):(endRow+1),1:10])\n\n    periodReturn = Array(forecastRow*wStar)[1]\n    period1NReturn = Array(forecastRow*w1N)[1]\n\n    return periodReturn, period1NReturn, wStar\nend\n\n\n\"\"\"\nKeeps track of returns for both the proposed method and 1/N.\nNeeds the overall array as well as the two next returns to push\n\"\"\"\n\nfunction trackPortfolioReturns(ReturnOverall, individualReturn, newPeriodReturn, Return1NOverall, Individual1NReturn, period1NReturn)\n    currentLength = length(ReturnOverall)\n    ReturnOverall = push!(ReturnOverall, ReturnOverall[currentLength]*newPeriodReturn)\n    individualReturn = push!(individualReturn, newPeriodReturn)\n\n    current1NLength = length(Return1NOverall)\n    Return1NOverall = push!(Return1NOverall, Return1NOverall[current1NLength]*period1NReturn)\n    Individual1NReturn = push!(Individual1NReturn, period1NReturn)\nend\n\nfunction trackPortfolioWeights(weights, periodWeights, iteration)\n    weights[iteration, 1:10] = periodWeights\nend\n\n\n\n\n\n\"\"\"\nUtilizing LASSO to create a classification; 1, it goes up, 0, it goes down\nThe portfolio is then a 1/K, where K is the amount of indexes predicted to go up\nNo weighting between them or variance optimization, hence quite basic\n\"\"\"\nfunction ClassificationPortfolio(fullX, firstRow, indicators)\n\nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n####SOCP FORM OF MEAN-VARIANCE\nusing JuMP\nusing Gurobi\nusing StatsBase\nusing DataFrames\nusing CSV\ninclude(\"SupportFunction.jl\")\ninclude(\"DataLoad.jl\")\nprintln(\"Leeeeroooy Jenkins\")\n#Esben's path\npath = \"$(homedir())/Documents/GitHub/Thesis/Data/MonthlyReturns\"\n\nmainData = loadIndexDataNoDurLOGReturn(path)\n\nmainDataArr = Array(mainData)\nindexes = 10\n\n\n#### WITH RISK AVERSION\n\nnRows = size(mainDataArr)[1]\nnCols = size(mainDataArr)[2]\n\n##LOOP TO TEST IT\nportfolioMVTotal = []\nportfolioMVTotal = push!(portfolioMVTotal, 1)\nportfolioMVIndividual = []\nportfolioMVIndividual = push!(portfolioMVIndividual, 0)\nwMVtracker = zeros((nRows-trainingObservations-1),10)\n\n\nw1N = repeat([0.1], outer = 10)\nportfolio1NTotal = []\nportfolio1NTotal = push!(portfolio1NTotal, 1)\nportfolio1NIndividual = []\nportfolio1NIndividual = push!(portfolio1NIndividual, 0)\n\nfor rStart = 1:(nRows-trainingObservations-1)\n    startRow = rStart\n    endRow = (rStart-1)+trainingObservations\n    mainXarr = mainDataArr[startRow:endRow,1:10]\n    indexes = size(mainXarr)[2]\n\n    #creating the covariance matrix of the training data\n    Sigma = cov(mainXarr)\n    #A=U^(T)U where U is upper triangular with real positive diagonal entries\n    F = lufact(Sigma)\n    U = F[:U]  #Cholesky factorization of Sigma\n    #creating the mean of the returns for SAA (forecasts should be used instead)\n    Mu = mean(mainXarr, 1)'\n\n    #setting risk aversion.\n    gamma = 1000\n\n    M = JuMP.Model(solver = GurobiSolver(OutputFlag = 0))\n    @variables M begin\n            w[1:indexes]\n            u[1:indexes]\n            z\n            y\n    end\n\n    @objective(M,Min, gamma*y - (Mu'*w)[1])\n    @constraint(M, 0 .<= w)\n    @constraint(M, sum(w[i] for i=1:indexes) == 1)\n    @constraint(M, norm([2*U'*w;y-1]) <= y+1)\n    solve(M)\n    wStar = getvalue(w)\n\n    wMVtracker[rStart,:] = wStar\n\n    #creating the forecastRow in arithmetic returns (not log returns)\n    #then we can multiply and sum across the row\n    forecastRow = (exp10(mainDataArr[(endRow+1):(endRow+1),1:10])-1)*100\n\n    periodReturn = Array(forecastRow*wStar)[1]\n    currentLength = length(portfolioMVTotal)\n    portfolioMVTotal = push!(portfolioMVTotal, portfolioMVTotal[currentLength]*periodReturn)\n    portfolioMVIndividual = push!(portfolioMVIndividual, periodReturn)\n\n    period1NReturn = Array(forecastRow*w1N)[1]\n    current1NLength = length(portfolio1NTotal)\n    portfolio1NTotal = push!(portfolio1NTotal, portfolio1NTotal[current1NLength]*period1NReturn)\n    portfolio1NIndividual = push!(portfolio1NIndividual, period1NReturn)\nend\n\n#Checking the total return of the portfolio by checking last index\nportfolioMVTotal[length(portfolioMVTotal)]\nportfolio1NTotal[length(portfolio1NTotal)]\n\nportfolioMVTotal = convert(Array{Float64,1}, portfolioMVTotal)\nportfolioMVIndividual = convert(Array{Float64,1}, portfolioMVIndividual)\n(mean(portfolioMVIndividual)-1)*100\nstd(portfolioMVIndividual)\nSharpeRatioMV = (mean(portfolioMVIndividual)-1)/std(portfolioMVIndividual)\n\nportfolio1NTotal = convert(Array{Float64,1}, portfolio1NTotal)\nportfolio1NIndividual = convert(Array{Float64,1}, portfolio1NIndividual)\n(mean(portfolio1NIndividual)-1)*100\nstd(portfolio1NIndividual)\nSharpeRatio1N = (mean(portfolio1NIndividual)-1)/std(portfolio1NIndividual)\n\nwritedlm(\"MVWeights2.csv\", wMVtracker,\",\")\n2.98\n", "meta": {"hexsha": "138962fea36be1e7fcd955d017e5a1ead54defd7", "size": 9034, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ML/MeanVariancePlain.jl", "max_stars_repo_name": "skipperafrosenborg/Thesis", "max_stars_repo_head_hexsha": "832a20dea181fdf6e3410a10c1acac1142af7831", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-29T08:00:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-29T08:00:53.000Z", "max_issues_repo_path": "ML/MeanVariancePlain.jl", "max_issues_repo_name": "skipperafrosenborg/Thesis", "max_issues_repo_head_hexsha": "832a20dea181fdf6e3410a10c1acac1142af7831", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ML/MeanVariancePlain.jl", "max_forks_repo_name": "skipperafrosenborg/Thesis", "max_forks_repo_head_hexsha": "832a20dea181fdf6e3410a10c1acac1142af7831", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-01-29T08:02:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-29T08:02:34.000Z", "avg_line_length": 30.3154362416, "max_line_length": 133, "alphanum_fraction": 0.7421961479, "num_tokens": 2520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359675, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7722201369579867}}
{"text": "#****************************************************************#\r\n# VeysiADN 17 Apr 2021\r\n# Advanced Robotics Homework 4 Codes\r\n#****************************************************************#\r\nusing LinearAlgebra\r\nconst lAlgebra = LinearAlgebra\r\n#****************************************************************#\r\n# Returns normalized version of given matrix/array\r\nfunction Normalize(N)\r\n    return N/lAlgebra.norm(N)\r\nend\r\n#****************************************************************#\r\n# Returns 4x4 twist matrix ‘se3mat’ (an element of Lie Algebra se3)\r\n# from given twist vector (= 6x1 vector) ‘xi\r\nfunction VecToSe3( xi )\r\n    w_skew = [ 0   -xi[3]   xi[2];\r\n              xi[3]   0    -xi[1];\r\n             -xi[2]  xi[1]    0 ]\r\n    return vcat(hcat(w_skew,xi[4:6]), zeros(1, 4))\r\nend\r\n#****************************************************************#\r\n# Returns twist vector ‘xi’ from given twist matrix ‘se3mat’\r\nfunction Se3ToVec( se3mat )\r\n    omg = [se3mat[3, 2], se3mat[1, 3],se3mat[2, 1]]\r\n    v = se3mat[1:3, 4]\r\n    return vcat(omg,v)\r\nend\r\n#****************************************************************#\r\n# Calculates and return rotation matrix ‘R’ by\r\n# evaluating matrix exponential of 3x3 skew symmetric matrix ‘so3mat’\r\n\r\nfunction MatrixExp3(so3mat)\r\n        omg = [so3mat[3, 2], so3mat[1, 3],so3mat[2, 1]]\r\n        theta = lAlgebra.norm(omg)\r\n        omg_n = so3mat / theta\r\n        return lAlgebra.I + sin(theta) * omg_n + (1 - cos(theta)) * omg_n * omg_n\r\nend\r\n\r\n#****************************************************************#\r\n# Calculates and return transformation matrix ‘g’ by\r\n# evaluating matrix exponential of 4x4 twist matrix ‘se3mat’\r\nfunction MatrixExp6( se3mat )\r\n    omg = [se3mat[3, 2], se3mat[1, 3],se3mat[2, 1]]\r\n    theta = lAlgebra.norm(omg)\r\n    omg_n = se3mat[1:3, 1:3] / theta\r\n    temp  = hcat(MatrixExp3(se3mat[1:3, 1:3]),\r\n                         (lAlgebra.I * theta +\r\n                          (1 - cos(theta)) * omg_n +\r\n                          (theta - sin(theta)) * omg_n * omg_n) *\r\n                         se3mat[1:3, 4] / theta)\r\n    return    vcat(temp,[0 0 0 1])\r\nend\r\n", "meta": {"hexsha": "e38ce2ef3771a93d330362760f3c74be14be1db4", "size": 2146, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HW4_VeysiADIN.jl", "max_stars_repo_name": "veysiadn/AdvancedRoboticsJulia", "max_stars_repo_head_hexsha": "0484999de1908b73fd19c7c78f5c8471a62610ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW4_VeysiADIN.jl", "max_issues_repo_name": "veysiadn/AdvancedRoboticsJulia", "max_issues_repo_head_hexsha": "0484999de1908b73fd19c7c78f5c8471a62610ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW4_VeysiADIN.jl", "max_forks_repo_name": "veysiadn/AdvancedRoboticsJulia", "max_forks_repo_head_hexsha": "0484999de1908b73fd19c7c78f5c8471a62610ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4905660377, "max_line_length": 82, "alphanum_fraction": 0.4580615098, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921834855049, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7722201353759481}}
{"text": "\"\"\"\n    AffineDistribution(μ, σ, ρ)\n\nA shifted and scaled (affinely transformed) version of `ρ`.\n\nIf ``Z`` is a random variable with distribution `ρ`, then `AffineDistribution(μ, σ, ρ)` is\nthe distribution of the random variable\n```math\nX = μ + σ Z\n```\n\nIf `ρ` is a discrete univariate distribution, the probability mass function of the\ntransformed distribution is given by\n```math\nP(X = x) = P\\\\left(Z = \\\\frac{x-μ}{σ} \\\\right).\n```\n\nIf `ρ` is a continuous univariate distribution with probability density function ``f_Z``,\nthe probability density function of the transformed distribution is given by\n```math\nf_X(x) = \\\\frac{1}{|σ|} f_Z\\\\left( \\\\frac{x-μ}{σ} \\\\right).\n```\n\nWe recommend against using the `AffineDistribution` constructor directly. Instead, use\n`+`, `-`, `*`, and `/`. These are optimized for specific distributions and will fall back\non `AffineDistribution` only when they need to.\n\nAffine transformations of discrete variables are easily affected by rounding errors. If you\nare getting incorrect results, try using exact `Rational` types instead of floats.\n\n```julia\nd = μ + σ * ρ       # Create location-scale transformed distribution\nparams(d)           # Get the parameters, i.e. (μ, σ, ρ)\n```\n\"\"\"\nstruct AffineDistribution{T<:Real, S<:ValueSupport, D<:UnivariateDistribution{S}} <: UnivariateDistribution{S}\n    μ::T\n    σ::T\n    ρ::D\n    function AffineDistribution{T,S,D}(μ::T, σ::T, ρ::D; check_args=true) where {T<:Real, S<:ValueSupport, D<:UnivariateDistribution{S}}\n        check_args && @check_args(AffineDistribution, σ > zero(σ))\n        new{T, S, D}(μ, σ, ρ)\n    end\nend\n\nfunction AffineDistribution(μ::T, σ::T, ρ::UnivariateDistribution; check_args::Bool=true) where {T<:Real}\n    _T = promote_type(eltype(ρ), T)\n    D = typeof(ρ)\n    S = value_support(D)\n    return AffineDistribution{_T,S,D}(_T(μ), _T(σ), ρ; check_args=check_args)\nend\n\nfunction AffineDistribution(μ::Real, σ::Real, ρ::UnivariateDistribution; check_args::Bool=true)\n    return AffineDistribution(promote(μ, σ)..., ρ; check_args=check_args)\nend\n\n# aliases\nconst LocationScale{T,S,D} = AffineDistribution{T,S,D}\nfunction LocationScale(μ::Real, σ::Real, ρ::UnivariateDistribution; check_args::Bool=true)\n    Base.depwarn(\"`LocationScale` is deprecated, use `AffineDistribution` instead\", :LocationScale)\n    if check_args && σ ≤ 0  # preparation for future PR where I remove σ > 0 check\n        throw(ArgumentError(\"σ must be strictly positive.\"))\n    end\n    return AffineDistribution(μ, σ, ρ; check_args=false)\nend\n\nconst ContinuousAffineDistribution{T<:Real,D<:ContinuousUnivariateDistribution} = AffineDistribution{T,Continuous,D}\nconst DiscreteAffineDistribution{T<:Real,D<:DiscreteUnivariateDistribution} = AffineDistribution{T,Discrete,D}\n\nBase.eltype(::Type{<:AffineDistribution{T}}) where T = T\n\nminimum(d::AffineDistribution) = d.μ + d.σ * minimum(d.ρ)\nmaximum(d::AffineDistribution) = d.μ + d.σ * maximum(d.ρ)\nsupport(d::AffineDistribution) = affinedistribution_support(d.μ, d.σ, support(d.ρ))\nfunction affinedistribution_support(μ::Real, σ::Real, support::RealInterval)\n    return RealInterval(μ + σ * support.lb, μ + σ * support.ub)\nend\naffinedistribution_support(μ::Real, σ::Real, support) = μ .+ σ .* support\n\nAffineDistribution(μ::Real, σ::Real, d::AffineDistribution) = AffineDistribution(μ + d.μ * σ, σ * d.σ, d.ρ)\n\n#### Conversions\n\nconvert(::Type{AffineDistribution{T}}, μ::Real, σ::Real, ρ::D) where {T<:Real, D<:UnivariateDistribution} = AffineDistribution(T(μ),T(σ),ρ)\nconvert(::Type{AffineDistribution{T}}, d::AffineDistribution{S}) where {T<:Real, S<:Real} = AffineDistribution(T(d.μ),T(d.σ),d.ρ, check_args=false)\n\n#### Parameters\n\nlocation(d::AffineDistribution) = d.μ\nscale(d::AffineDistribution) = d.σ\nparams(d::AffineDistribution) = (d.μ,d.σ,d.ρ)\npartype(::AffineDistribution{T}) where {T} = T\n\n#### Statistics\n\nmean(d::AffineDistribution) = d.μ + d.σ * mean(d.ρ)\nmedian(d::AffineDistribution) = d.μ + d.σ * median(d.ρ)\nmode(d::AffineDistribution) = d.μ + d.σ * mode(d.ρ)\nmodes(d::AffineDistribution) = d.μ .+ d.σ .* modes(d.ρ)\n\nvar(d::AffineDistribution) = d.σ^2 * var(d.ρ)\nstd(d::AffineDistribution) = d.σ * std(d.ρ)\nskewness(d::AffineDistribution) = skewness(d.ρ)\nkurtosis(d::AffineDistribution) = kurtosis(d.ρ)\n\nisplatykurtic(d::AffineDistribution) = isplatykurtic(d.ρ)\nisleptokurtic(d::AffineDistribution) = isleptokurtic(d.ρ)\nismesokurtic(d::AffineDistribution) = ismesokurtic(d.ρ)\n\nentropy(d::ContinuousAffineDistribution) = entropy(d.ρ) + log(d.σ)\nentropy(d::DiscreteAffineDistribution) = entropy(d.ρ)\n\nmgf(d::AffineDistribution,t::Real) = exp(d.μ*t) * mgf(d.ρ,d.σ*t)\n\n#### Evaluation & Sampling\n\npdf(d::ContinuousAffineDistribution, x::Real) = pdf(d.ρ,(x-d.μ)/d.σ) / d.σ\npdf(d::DiscreteAffineDistribution, x::Real) = pdf(d.ρ,(x-d.μ)/d.σ)\n\nlogpdf(d::ContinuousAffineDistribution,x::Real) = logpdf(d.ρ,(x-d.μ)/d.σ) - log(d.σ)\nlogpdf(d::DiscreteAffineDistribution, x::Real) = logpdf(d.ρ,(x-d.μ)/d.σ)\n\nfor f in (:cdf, :ccdf, :logcdf, :logccdf)\n    @eval $f(d::AffineDistribution, x::Real) = $f(d.ρ, (x - d.μ) / d.σ)\nend\n\nquantile(d::AffineDistribution,q::Real) = d.μ + d.σ * quantile(d.ρ,q)\n\nrand(rng::AbstractRNG, d::AffineDistribution) = d.μ + d.σ * rand(rng, d.ρ)\ncf(d::AffineDistribution, t::Real) = cf(d.ρ,t*d.σ) * exp(1im*t*d.μ)\ngradlogpdf(d::ContinuousAffineDistribution, x::Real) = gradlogpdf(d.ρ,(x-d.μ)/d.σ) / d.σ\n\n#### Syntactic sugar for simple transforms of distributions, e.g., d + x, d - x, and so on\n\nBase.:+(d::UnivariateDistribution, x::Real) = AffineDistribution(x, one(x), d)\nBase.:+(x::Real, d::UnivariateDistribution) = d + x\nBase.:*(x::Real, d::UnivariateDistribution) = AffineDistribution(zero(x), x, d)\nBase.:*(d::UnivariateDistribution, x::Real) = x * d\nBase.:-(d::UnivariateDistribution, x::Real) = d + -x\nBase.:/(d::UnivariateDistribution, x::Real) = inv(x) * d\n", "meta": {"hexsha": "d2c030d32e4d7865a6f90871a07fd32ca5c280b2", "size": 5825, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/locationscale.jl", "max_stars_repo_name": "mohamed82008/Distributions.jl", "max_stars_repo_head_hexsha": "93a542d8ce3a818959d604d5268d3ddba2a5af25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/locationscale.jl", "max_issues_repo_name": "mohamed82008/Distributions.jl", "max_issues_repo_head_hexsha": "93a542d8ce3a818959d604d5268d3ddba2a5af25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/locationscale.jl", "max_forks_repo_name": "mohamed82008/Distributions.jl", "max_forks_repo_head_hexsha": "93a542d8ce3a818959d604d5268d3ddba2a5af25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3120567376, "max_line_length": 147, "alphanum_fraction": 0.7007725322, "num_tokens": 1875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7722201314957092}}
{"text": "using ForwardDiff, BenchmarkTools, StaticArrays\n\n# Using StaticArrays #\n#--------------------#\n\n@inline eom(u) = @SVector [3.8*u[1]*(1-u[1])-0.05*(u[2]+0.35)*(1-2*u[3]),\n0.1*((u[2]+0.35)*(1-2*u[3])-1 )*(1-1.9*u[1]),\n3.78*u[3]*(1-u[3])+0.2*u[2]]\n\n@inline function manual_jacobian(x)\n    return @SMatrix [3.8*(1 - 2x[1]) -0.05*(1-2x[3]) 0.1*(x[2] + 0.35);\n    -0.19((x[2] + 0.35)*(1-2x[3]) - 1)  0.1*(1-2x[3])*(1-1.9x[1])  -0.2*(x[2] + 0.35)*(1-1.9x[1]);\n    0.0  0.2  3.78(1-2x[3]) ]\nend\n\n@inline function manual_jacobian!(J, x)\n  J[1,1] = 3.8*(1 - 2x[1]); J[1,2] = -0.05*(1-2x[3]); J[1,3] = 0.1*(x[2] + 0.35);\n  J[2,1] = 0.19((x[2] + 0.35)*(1-2x[3]) - 1); J[2,2] = 0.1*(1-2x[3])*(1-1.9x[1])\n  J[2,3] = -0.2*(x[2] + 0.35)*(1-1.9x[1])\n  J[3,1] = 0.0; J[3,2] = 0.2; J[3,3] = 3.78(1-2x[3])\n  return J\nend\n\n@inline forward_jacobian(u) = ForwardDiff.jacobian(eom, u)\n\nu = SVector{3}(rand(3)); J = rand(3,3)\n\n# sanity check\n@assert manual_jacobian(u) == forward_jacobian(u)\n\nprintln(\"---- eom(::SVector) benchmark results ----\")\ndisplay(@benchmark eom($u))\n\nprintln(\"---- manual_jacobian(::SVector) benchmark results ----\")\ndisplay(@benchmark manual_jacobian($u))\n\nprintln(\"---- forward_jacobian(::SVector) benchmark results ----\")\ndisplay(@benchmark forward_jacobian($u))\n\n# sanity check\n@assert manual_jacobian(u) == forward_jacobian(u)\n\n@inline forward_jacobian!(J, u) = ForwardDiff.jacobian!(J, eom, u)\n\nprintln(\"---- manual_jacobian_inplace(::SVector) benchmark results ----\")\ndisplay(@benchmark manual_jacobian!($J, $u))\n\nprintln(\"---- forward_jacobian_inplace(::SVector) benchmark results ----\")\ndisplay(@benchmark forward_jacobian!($J, $u))\n\n\n# Using Base Arrays #\n#-------------------#\n\n@inline function eom!(du, x)\n  x1, x2, x3 = x[1], x[2], x[3]\n  du[1] = 3.8*x1*(1-x1)-0.05*(x2+0.35)*(1-2*x3)\n  du[2] = 0.1*((x2+0.35)*(1-2*x3)-1 )*(1-1.9*x1)\n  du[3] = 3.78*x3*(1-x3)+0.2*x2\nend\n\n@inline function manual_jacobian!(J, x)\n  J[1,1] = 3.8*(1 - 2x[1]); J[1,2] = -0.05*(1-2x[3]); J[1,3] = 0.1*(x[2] + 0.35);\n  J[2,1] = 0.19((x[2] + 0.35)*(1-2x[3]) - 1); J[2,2] = 0.1*(1-2x[3])*(1-1.9x[1])\n  J[2,3] = -0.2*(x[2] + 0.35)*(1-1.9x[1])\n  J[3,1] = 0.0; J[3,2] = 0.2; J[3,3] = 3.78(1-2x[3])\n  return J\nend\n\n@inline forward_jacobian!(J, du, u, cfg) = ForwardDiff.jacobian!(J, eom!, du, u, cfg)\n\nu = rand(3)\ndu = zeros(3)\nJ = zeros(3, 3)\ncfg = ForwardDiff.JacobianConfig(eom!, du, u)\n\nprintln(\"---- eom!(::Vector, ::Vector) benchmark results ----\")\ndisplay(@benchmark eom!($du, $u))\n\nprintln(\"---- manual_jacobian!(::Matrix, ::Vector) benchmark results ----\")\ndisplay(@benchmark manual_jacobian!($J, $u))\n\nprintln(\"---- forward_jacobian!(::Matrix, ::Vector, ::Vector, ::JacobianConfig) benchmark results ----\")\ndisplay(@benchmark forward_jacobian!($J, $du, $u, $cfg))\n", "meta": {"hexsha": "9b552ae917318d58b3068db21710ecaf710c092f", "size": 2757, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/benchmarks/jrevels_more.jl", "max_stars_repo_name": "felixcremer/DynamicalSystems.jl", "max_stars_repo_head_hexsha": "0623090e62a357486a1df974436d0e31a8843fe1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 585, "max_stars_repo_stars_event_min_datetime": "2017-09-14T10:59:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:41:49.000Z", "max_issues_repo_path": "test/benchmarks/jrevels_more.jl", "max_issues_repo_name": "felixcremer/DynamicalSystems.jl", "max_issues_repo_head_hexsha": "0623090e62a357486a1df974436d0e31a8843fe1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 101, "max_issues_repo_issues_event_min_datetime": "2017-09-08T17:07:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T15:41:36.000Z", "max_forks_repo_path": "test/benchmarks/jrevels_more.jl", "max_forks_repo_name": "felixcremer/DynamicalSystems.jl", "max_forks_repo_head_hexsha": "0623090e62a357486a1df974436d0e31a8843fe1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 75, "max_forks_repo_forks_event_min_datetime": "2017-09-24T14:32:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T09:19:44.000Z", "avg_line_length": 32.4352941176, "max_line_length": 104, "alphanum_fraction": 0.5727239753, "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7722201261050476}}
{"text": "#! /usr/bin/julia\n\n# Rosetta Code, Amicable pairs\n\nfunction pcontrib{T<:Integer}(p::T, a::T)\n    n = one(T)\n    pcon = one(T)\n    for i in 1:a\n        n *= p\n        pcon += n\n    end\n    return pcon\nend\n\nfunction divisorsum{T<:Integer}(n::T)\n    dsum = one(T)\n    for (p, a) in factor(n)\n        dsum *= pcontrib(p, a)\n    end\n    dsum -= n\nend\n\nfunction aliquotclassifier{T<:Integer}(n::T)\n    a = T[n]\n    b = divisorsum(a[end])\n    len = 1\n    while len < 17 && !(b in a) && 0 < b && b < 2^47+1\n        push!(a, b)\n        b = divisorsum(a[end])\n        len += 1\n    end\n    if b in a\n        1 < len || return (\"Perfect\", a)\n        if b == a[1]\n            2 < len || return (\"Amicable\", a)\n            return (\"Sociable\", a)\n        elseif b == a[end]\n            return (\"Aspiring\", a)\n        else\n            return (\"Cyclic\", push!(a, b))\n        end\n    end\n    push!(a, b)\n    b != 0 || return (\"Terminating\", a)\n    return (\"Non-terminating\", a)\nend\n\nprintln(\"Classification Tests:\")\ntests = [1:12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488]\nfor i in tests\n    (class, a) = aliquotclassifier(i)\n    println(@sprintf(\"%8d => \", i), @sprintf(\"%16s, \", class), a)\nend\n\n    \n", "meta": {"hexsha": "5c63cd916d492cbd7991309ec835694e7fb386bd", "size": 1205, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/completed/aliquot_seq_class.jl", "max_stars_repo_name": "MichaeLeroy/rosetta-code", "max_stars_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/completed/aliquot_seq_class.jl", "max_issues_repo_name": "MichaeLeroy/rosetta-code", "max_issues_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/completed/aliquot_seq_class.jl", "max_forks_repo_name": "MichaeLeroy/rosetta-code", "max_forks_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5178571429, "max_line_length": 77, "alphanum_fraction": 0.4987551867, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7722089071175819}}
{"text": "using Plots, Distributions, LaTeXStrings, Statistics, StatsPlots, JLD, ProgressBars, StatsBase\n\nfunction Metropolis(p :: Function, steps :: Integer, dx :: Real, X₀ :: Real)\n    success=0\n    x= X₀\n    xList=Float64[i for i in 1:steps]\n    n=0\n    for n in 1:steps\n        xList[n]=x\n        y= x + rand(Uniform(-dx, dx))\n        if rand()< p(y)/p(x)\n            x=y\n            success+=1\n        end\n    end\n    return xList, success/steps\nend\n\n#histogram\nxList, successful_steps=Metropolis(x -> ℯ^(-x^2/2), 10^5, 3 , 0.0)\nsave(\"../../chapter8/8.1/HistoData.jld\",\"xList\", xList, \"SuccessfulSteps\", successful_steps)\nhistogram(xList, normalize=true, alpha=0.7, label=\"Normal line\")\nplot!(Normal(0,1), ylabel=\"Probability Density\", xlabel=\"x\",\n    title=L\"Guassian\\ Distribution\\ for\\ 100000\\ steps\\ and\\ a_r=%$successful_steps\", label=\"Metropolis Series\", dpi=600)\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter8\\\\HistoPlot.png\")\n#acceptence rate per unit length\nN=100\nstepsList= range(0.1, 50, length=N)\naᵣData=[]\nfor n in ProgressBar(1:N)\n    xList, successful_steps=Metropolis(x -> ℯ^(-x^2/2), 10^5, stepsList[n] , 0.0)\n    push!(aᵣData, successful_steps)\nend\nplot(stepsList,aᵣData , xlabel=L\"dx\", ylabel=L\"a_r(dx)\", title=\"Acceptance per Length of Steps\", label=nothing, dpi=600)\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter8\\\\acceptance_ratio.png\")\n#C(j)_j plot\nstepsList=[15.9, 7.95, 5.27, 3.88, 2.94, 2.2, 1.57, 1.03, 0.5]\naᵣList=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\nCⱼList=[]\nfor n in ProgressBar(1:9)\n    xList, successful_steps=Metropolis(x -> ℯ^(-x^2/2), 10^5, stepsList[n] , 0.0)\n    push!(CⱼList, autocor(xList))\nend\nsave(\"../../chapter8/8.1/CjList.jld\",\"CjList\",CⱼList)\nselectedNums=[1, 3, 6, 9 ]\n\nplot()\nfor i in selectedNums\n    plot!(1:length(CⱼList[i]), CⱼList[i], linewidth=3, label=L\"a_r\\ =\\ %$(aᵣList[i])\")\nend\nplot!(ylabe=\"Cⱼ\", xlabel=\"j\", title=L\"C_j \\_\\ j\", dpi=600)\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter8\\\\Cj_j.png\")\n#length correlation\nlogCl=[]\nξList=Float64[]\nx=[i for i in 1:10]\nfor i in CⱼList\n    push!(logCl,log.(i[1:10]))\nend\nhcat(x, ones(10))\nfor y in logCl\n    ξ⁽⁻¹⁾, Const= hcat(x, ones(10)) \\ y\n    ξ= -1/ξ⁽⁻¹⁾\n    push!(ξList, ξ)\nend\nplot(aᵣList, ξList, title=\"Correlation Length\", xlabel=L\"a_r\", ylabel=L\"\\xi\", label=nothing)\nscatter!(aᵣList, ξList, dpi=600, label=nothing)\nsave(\"../../chapter8/8.1/xiList.jld\",\"ξList\",ξList)\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter8\\\\correlationLength.png\")\n", "meta": {"hexsha": "3c134cb423c600eba1235797dd2f44f2c55306af", "size": 2581, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter8/8.1.jl", "max_stars_repo_name": "narges8k/computational_physics", "max_stars_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter8/8.1.jl", "max_issues_repo_name": "narges8k/computational_physics", "max_issues_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter8/8.1.jl", "max_forks_repo_name": "narges8k/computational_physics", "max_forks_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T09:55:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T09:55:00.000Z", "avg_line_length": 36.8714285714, "max_line_length": 121, "alphanum_fraction": 0.6644711352, "num_tokens": 991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7722089071175819}}
{"text": "# ---\n# title: 492. Construct the Rectangle\n# id: problem492\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Easy\n# categories: Math\n# link: <https://leetcode.com/problems/construct-the-rectangle/description/>\n# hidden: true\n# ---\n# \n# A web developer needs to know how to design a web page's size. So, given a\n# specific rectangular web page's area, your job by now is to design a\n# rectangular web page, whose length L and width W satisfy the following\n# requirements:\n# \n#   1. The area of the rectangular web page you designed must equal to the given target area.\n#   2. The width `W` should not be larger than the length `L`, which means `L >= W`.\n#   3. The difference between length `L` and width `W` should be as small as possible.\n# \n# Return _an array`[L, W]` where `L` and `W` are the length and width of the web\n# page you designed in sequence._\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: area = 4\n#     Output: [2,2]\n#     Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. \n#     But according to requirement 2, [1,4] is illegal; according to requirement 3,  [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: area = 37\n#     Output: [37,1]\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: area = 122122\n#     Output: [427,286]\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= area <= 107`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "b57d33f99c9d5abca236e1f282883e8934a19c3e", "size": 1550, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/492.construct-the-rectangle.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/unresolved/492.construct-the-rectangle.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/unresolved/492.construct-the-rectangle.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 24.21875, "max_line_length": 168, "alphanum_fraction": 0.6141935484, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7722089068683332}}
{"text": "# # Group Isomorphism\n\n# ## Set up Basic Functions\n\nusing TightBindingLattice\nusing Formatting\nfunction display_matrix(io::IO, matrix::AbstractMatrix; prefix::AbstractString=\"\")\n    width = ceil(Int, maximum(length(\"$item\") for item in matrix)/4)*4\n    for row in eachrow(matrix)\n        for (icol, col) in enumerate(row)\n            print(io, icol == 1 ? prefix : \" \")\n            printfmt(io, \"{:>$(width)s}\", \"$col\")\n        end\n        println(io)\n    end\nend\n\n# ## Generate Two Isomorphic Groups\n\ngroup1 = FiniteGroup([\n    1 2 3 4;\n    2 1 4 3;\n    3 4 2 1;\n    4 3 1 2;\n]);\ngroup2 = let mtab1 = group1.multiplication_table,\n             mtab2 = zeros(Int, (4, 4)),\n             mapping = [1, 3, 2, 4]\n             for i in 1:4, j in 1:4\n                 mtab2[mapping[i], mapping[j]] = mapping[mtab1[i,j]]\n             end\n             FiniteGroup(mtab2)\n         end;\n\n\n# ## Group Multiplication Tables\n\nprintln(\"Multiplication Table of G₁\")\nprintln(\"--------------------------\")\ndisplay_matrix(stdout, group_multiplication_table(group1))\nprintln()\n\nprintln(\"Multiplication Table of G₂\")\nprintln(\"--------------------------\")\ndisplay_matrix(stdout, group_multiplication_table(group2))\nprintln()\n\n\n# ## Group Isomorphism\n\nprintln(\"Group Isomorphism  ϕ: G₁ → G₂\")\nprintln(\"-----------------------------\")\nϕ = group_isomorphism(group1, group2)\nfor g in 1:group_order(group1)\n    println(\"  ϕ($g) = $(ϕ[g])\")\nend\nprintln()\n\nmtab2 = zeros(Int, (group_order(group1), group_order(group1)))\nfor g in 1:group_order(group1), h in 1:group_order(group1)\n    mtab2[ϕ[g], ϕ[h]] = ϕ[ group_product(group1, g, h) ]\nend\n\nprintln(\"Multiplication Table of ϕ(G₁)\")\nprintln(\"-----------------------------\")\ndisplay_matrix(stdout, mtab2)\nprintln()\nprintln(\"  ϕ(g)⋅ϕ(h) = ϕ(g⋅h)\")\nprintln(\"  ϕ(G₁) ≡ G₂ should hold.\")\n", "meta": {"hexsha": "85bc342c6b08301ccff1bf7d56d045aed7668466", "size": 1803, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example_group_isomorphism.jl", "max_stars_repo_name": "kyungminlee/TightBindingLattice.jl", "max_stars_repo_head_hexsha": "e479bcdc582e4fc04d069e4e4012ae75e7e61cb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-27T01:30:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-27T01:30:15.000Z", "max_issues_repo_path": "examples/example_group_isomorphism.jl", "max_issues_repo_name": "kyungminlee/TightBindingLattice.jl", "max_issues_repo_head_hexsha": "e479bcdc582e4fc04d069e4e4012ae75e7e61cb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/example_group_isomorphism.jl", "max_forks_repo_name": "kyungminlee/TightBindingLattice.jl", "max_forks_repo_head_hexsha": "e479bcdc582e4fc04d069e4e4012ae75e7e61cb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7571428571, "max_line_length": 82, "alphanum_fraction": 0.586245147, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7722089029789198}}
{"text": "# # Usage example:\n# npts = 10\n# rho = 0.9\n# sig = 0.01\n# gridpts, transition = rouwenhorst(npts, rho, sig)\n\n\nfunction RouwenNormalize!(A)\n    A[2:end-1, :] ./= 2\n    nothing\nend\n\nfunction rouwenupdate!(Πold, Πnew, p, q)\n    Nold = size(Πold, 1)\n    Πnew[1:Nold, 1:Nold] = p*Πold\n    Πnew[1:Nold, 2:(Nold+1)] .+= (1-p)*Πold\n    Πnew[2:(Nold+1), 1:Nold] .+= (1-q)*Πold\n    Πnew[2:(Nold+1), 2:(Nold+1)] .+= q*Πold\n    nothing\nend\n\nfunction rouwenmat(N, p, q)\n    initmat = [p 1-p;1-q q]\n    if N==2\n        ret = initmat\n    else\n        currmat = initmat\n        for n = 3:N\n            nextmat = fill(0., (n, n))\n            rouwenupdate!(currmat, nextmat, p, q)\n            currmat = nextmat\n            RouwenNormalize!(currmat)\n        end\n        ret = currmat\n    end\n    return(ret)\nend\n\nfunction rouwenhorst(npts, ρ, σ)\n    # Discretizes\n    # y′ = ρ y +  σ ϵ\n\n    ω = σ/sqrt(1-ρ^2) # Long run std dev\n    # println(\"Long run variance: $ω\")\n    q = (1+ρ)/2\n\n    points = range(-ω*sqrt(npts - 1),\n                   ω*sqrt(npts-1),\n                   length=npts)\n\n    # points = GenGrid(uniform(npts, bds))\n    Π = rouwenmat(npts, q, q)\n    return points, Π\nend\n", "meta": {"hexsha": "d07201410ac7c2d77db18b1ccc46e3aadb2ae3a1", "size": 1169, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "rouwenhorst.jl", "max_stars_repo_name": "pereiragc/rouwenhorst", "max_stars_repo_head_hexsha": "fd43fb81c8256be5a5700e1eaa0c2df9e0369dfa", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-30T15:02:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T15:02:06.000Z", "max_issues_repo_path": "rouwenhorst.jl", "max_issues_repo_name": "pereiragc/rouwenhorst", "max_issues_repo_head_hexsha": "fd43fb81c8256be5a5700e1eaa0c2df9e0369dfa", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rouwenhorst.jl", "max_forks_repo_name": "pereiragc/rouwenhorst", "max_forks_repo_head_hexsha": "fd43fb81c8256be5a5700e1eaa0c2df9e0369dfa", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2545454545, "max_line_length": 51, "alphanum_fraction": 0.5218135158, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7722089011588377}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.17\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 42338250-4387-11eb-1d21-a3b1adbf202c\nbegin\n\tusing Pkg\n    Pkg.activate(pwd())\nend\n\n# ╔═╡ 593f78f0-4387-11eb-3175-93d23999fd88\nbegin\n\tusing CSV\n\tusing Statistics\n\tusing DataFrames\nend\n\n# ╔═╡ 9d6fccb0-4395-11eb-34d8-8de61157070c\nusing Colors\n\n# ╔═╡ 1d3942f0-4387-11eb-05e8-85639ea3579a\nmd\"\"\"\n# Data Mining\n## Assignment 3 - Correlation Matrix\n### Aadam - CS1945\n\"\"\"\n\n# ╔═╡ b3196bd0-43a3-11eb-3831-65d049f3abef\nmd\"\"\"\n# Data Transformation\nReads `iris` data from [http://archive.ics.uci.edu/ml/datasets/Iris](http://archive.ics.uci.edu/ml/datasets/Iris), transforms it, and saves the transformed data into `data/iris_transformed.txt` file.\n\"\"\"\n\n# ╔═╡ bd551d90-4387-11eb-1e63-a5993648b680\nfunction transform(csv_path)\n\tdf = CSV.read(csv_path, DataFrame, datarow=1) # read from CSV\n\tinsertcols!(df, 1, :row => axes(df, 1) ) # add column with row numbers\n\t\n\t# change categorical values to numeric\n\tdf.Column5 = replace.(df.Column5, Ref(\"Iris-setosa\" => 1))\n\tdf.Column5 = replace.(df.Column5, Ref(\"Iris-versicolor\" => 2))\n\tdf.Column5 = replace.(df.Column5, Ref(\"Iris-virginica\" => 3))\n\tdf[!,:Column5] = parse.(Int,df[!, :Column5])\n\t\n\t# add data size info\n\topen(\"data/iris_transformed.txt\", \"w\") do io\n\t\tprintln(io, size(df)[1])\n\t\tprintln(io, size(df)[2])\n\t\tprintln(io, \"\")\n\tend\n\t\n\t# append CSV data to file\n\tCSV.write(\"data/iris_transformed.txt\", df, header=false, append=true)\n\tdf\nend\n\n# ╔═╡ 4f544fa0-438c-11eb-1c71-f10ea0b7747c\ndf = transform(\"data/iris.data\")[:, 2:end-1]\n\n# ╔═╡ afbd4320-4390-11eb-1e7a-df636c495cba\nmd\"\"\"\n# Calculate Correlation Matrix\nThe correlation matrix will be a NXN matrix (where N is number of records in your input dataset) containing Pearson’s correlation coefficient between each of the row in data matrix. Pearson’s correlation coefficient formula:\n\n$\\frac{{}\\sum_{i=1}^{n} (x_i - \\overline{x})(y_i - \\overline{y})}\n{\\sqrt{\\sum_{i=1}^{n} (x_i - \\overline{x})^2(y_i - \\overline{y})^2}}$\n\"\"\"\n\n# ╔═╡ eaa97310-438f-11eb-2ad5-d141a81d9791\nfunction cor_col(x::AbstractVector, mx, y::AbstractVector, my)\n    n = length(x)\n    \n\t# Initialize the accumulators\n\txx = zero(sqrt(abs2(one(x[1]))))\n\tyy = zero(sqrt(abs2(one(y[1]))))\n\txy = zero(x[1] * y[1]')\n\n\tfor i in eachindex(x, y)\n\t\txi = x[i] - mx\n\t\tyi = y[i] - my\n\t\txx += abs2(xi)\n\t\tyy += abs2(yi)\n\t\txy += xi * yi'\n\tend\n    return clamp(xy / max(xx, yy) / sqrt(min(xx, yy) / max(xx, yy)), -1, 1)\nend\n\n# ╔═╡ 578bf662-43a4-11eb-3d40-0b491ad520b2\nfunction cor(X::AbstractMatrix)\n\tn = size(X)[1]\n\tcormat = zeros(n, n)\n\t\n\tfor i in 1:n\n\t\tfor j in i:n\n\t\t\tcormat[i, j] = cor_col(X[i, :], mean(X[i, :]), X[j, :], mean(X[j, :]))\n\t\t\tcormat[j, i] = cormat[i, j]\n\t\tend\n\tend\n\tcormat\nend\n\n# ╔═╡ 0eb51410-438d-11eb-0a4b-a59b660f63dd\ncor_matrix = cor(Matrix(df))\n\n# ╔═╡ 0ecb0d10-438d-11eb-2b61-a783a5176442\nmd\"\"\"\n# Discretize\nCalculate median/mean of each column of the correlation matrix and set all the values in that column that are above the calculated median/mean to 1 and rest to 0.\n\"\"\"\n\n# ╔═╡ 0ee10610-438d-11eb-193c-3d806714919a\ncor_mean = mean(cor_matrix, dims=1)\n\n# ╔═╡ 0ef59f80-438d-11eb-15f0-6986acb67f16\ncor_median = median(cor_matrix, dims=1)\n\n# ╔═╡ 0b236830-4395-11eb-129b-65553ddfc548\ncor_mean_matrix = zeros(size(cor_matrix));\n\n# ╔═╡ 16ab1130-4395-11eb-3d46-ad660d6c74c6\ncor_median_matrix = zeros(size(cor_matrix));\n\n# ╔═╡ 0f0d1f20-438d-11eb-27ef-b9a25e3b9436\nfor i in 1:size(cor_matrix)[1]\n\tcor_mean_matrix[:, i] = cor_matrix[:, i] .> cor_mean[i]\n\tcor_median_matrix[:, i] = cor_matrix[:, i] .> cor_median[i]\nend\n\n# ╔═╡ c0379bb0-4395-11eb-269b-19b8db40b0d5\nmd\"\"\"\n# Visualize\nConvert the discretized matrix into bitmap.\n\"\"\"\n\n# ╔═╡ 1257b542-4398-11eb-3aec-d9c38c46ccf3\nmd\"\"\"\n### Median Discretized Correlation Matrix\n\"\"\"\n\n# ╔═╡ 9d8884d2-4395-11eb-294b-5d0b022f06e5\nGray.(cor_median_matrix)\n\n# ╔═╡ 23e78ec2-4398-11eb-35d0-0b6de4d620de\nmd\"\"\"\n### Mean Discretized Correlation Matrix\n\"\"\"\n\n# ╔═╡ f627fab0-4397-11eb-00e1-0f3bc6802852\nGray.(cor_mean_matrix)\n\n# ╔═╡ Cell order:\n# ╟─1d3942f0-4387-11eb-05e8-85639ea3579a\n# ╟─42338250-4387-11eb-1d21-a3b1adbf202c\n# ╠═593f78f0-4387-11eb-3175-93d23999fd88\n# ╟─b3196bd0-43a3-11eb-3831-65d049f3abef\n# ╠═bd551d90-4387-11eb-1e63-a5993648b680\n# ╠═4f544fa0-438c-11eb-1c71-f10ea0b7747c\n# ╟─afbd4320-4390-11eb-1e7a-df636c495cba\n# ╠═eaa97310-438f-11eb-2ad5-d141a81d9791\n# ╠═578bf662-43a4-11eb-3d40-0b491ad520b2\n# ╠═0eb51410-438d-11eb-0a4b-a59b660f63dd\n# ╟─0ecb0d10-438d-11eb-2b61-a783a5176442\n# ╠═0ee10610-438d-11eb-193c-3d806714919a\n# ╠═0ef59f80-438d-11eb-15f0-6986acb67f16\n# ╠═0b236830-4395-11eb-129b-65553ddfc548\n# ╠═16ab1130-4395-11eb-3d46-ad660d6c74c6\n# ╠═0f0d1f20-438d-11eb-27ef-b9a25e3b9436\n# ╟─c0379bb0-4395-11eb-269b-19b8db40b0d5\n# ╠═9d6fccb0-4395-11eb-34d8-8de61157070c\n# ╟─1257b542-4398-11eb-3aec-d9c38c46ccf3\n# ╠═9d8884d2-4395-11eb-294b-5d0b022f06e5\n# ╟─23e78ec2-4398-11eb-35d0-0b6de4d620de\n# ╠═f627fab0-4397-11eb-00e1-0f3bc6802852\n", "meta": {"hexsha": "723c0e3e29ea862ebcf068768ded068067d1f70b", "size": 4920, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3.correlation/notebook.jl", "max_stars_repo_name": "aadimator/CSE553-Data-Mining", "max_stars_repo_head_hexsha": "8acc3a1dafe297b37c2e3a355ba00e9e2b1981a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3.correlation/notebook.jl", "max_issues_repo_name": "aadimator/CSE553-Data-Mining", "max_issues_repo_head_hexsha": "8acc3a1dafe297b37c2e3a355ba00e9e2b1981a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3.correlation/notebook.jl", "max_forks_repo_name": "aadimator/CSE553-Data-Mining", "max_forks_repo_head_hexsha": "8acc3a1dafe297b37c2e3a355ba00e9e2b1981a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9545454545, "max_line_length": 224, "alphanum_fraction": 0.7046747967, "num_tokens": 2201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7722088958647575}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,jl:hydrogen\n#     text_representation:\n#       extension: .jl\n#       format_name: hydrogen\n#       format_version: '1.3'\n#       jupytext_version: 1.11.2\n#   kernelspec:\n#     display_name: Julia 1.8.0-DEV\n#     language: julia\n#     name: julia-1.8\n# ---\n\n# %%\nVERSION\n\n# %%\nusing Plots\ndefault(size=(400, 250))\n\nusing Random\nRandom.seed!(4649373)\n\n# %%\nx = range(0, 1; length=10)\n\nf(x) = sinpi(2x)\nnoise = 0.2randn(length(x))\nt = f.(x) + noise\n\nxs = range(extrema(x)...; length=1000)\nplot(xs, f.(xs); label=\"\", xlabel=\"x\", ylabel=\"t\")\nscatter!(x, t; label=\"\", color=3)\n\n# %%\nPP = []\nfor d in (0, 1, 3, 9)\n    X = x.^(0:d)'\n    w = X\\t\n    g(x) = evalpoly(x, w)\n    P = plot(xs, f.(xs); label=\"\")\n    plot!(xs, g.(xs); label=\"degree $d\")\n    scatter!(x, t; label=\"\")\n    push!(PP, P)\nend\nplot(PP...; size=(800, 500))\n\n# %%\nPP = []\nfor d in (0, 1, 3, 9)\n    X = x.^(0:d)'\n    w = X'X\\X't\n    g(x) = evalpoly(x, w)\n    P = plot(xs, f.(xs); label=\"\")\n    plot!(xs, g.(xs); label=\"degree $d\")\n    scatter!(x, t; label=\"\")\n    push!(PP, P)\nend\nplot(PP...; size=(800, 500))\n\n# %%\nusing SymPy\nn = 5\nx = collect(symbols(\"x1:$(n+1)\", real=true))\n\n# %%\nt = collect(symbols(\"t1:$(n+1)\", real=true))\n\n# %%\nd = 3\nX = x.^(0:d)'\n\n# %%\nA = X'X\n\n# %%\nT = X't\n\n# %%\n", "meta": {"hexsha": "693e09a621efd1dbdc8836aa88cd78138ed16d90", "size": 1302, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0005/PRML Chap.1 Ex.1.1.jl", "max_stars_repo_name": "genkuroki/public", "max_stars_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-06-06T00:33:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T06:56:08.000Z", "max_issues_repo_path": "0005/PRML Chap.1 Ex.1.1.jl", "max_issues_repo_name": "genkuroki/public", "max_issues_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0005/PRML Chap.1 Ex.1.1.jl", "max_forks_repo_name": "genkuroki/public", "max_forks_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-02T11:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T11:46:05.000Z", "avg_line_length": 15.8780487805, "max_line_length": 50, "alphanum_fraction": 0.5069124424, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.868826784729373, "lm_q1q2_score": 0.7721774551898415}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ ca32437b-65ce-401b-93fc-1f3b7011ae88\nbegin\n    import Pkg\n    # activate the shared project environment\n    Pkg.activate(Base.current_project())\n    using Omega, Distributions, UnicodePlots\nend\n\n# ╔═╡ daa9fd86-5a36-4aa2-842e-477cdb19b8d5\nmd\"# Probability Dilution\nProbability dilution is refers to scenarios where one can increase one's confidence by increasing the noisyness of one's measurement device.\n\nHere we'll use an example on microcrip certification to demonstrate.\"\n\n# ╔═╡ 62257a75-2949-4afc-8543-fe3fa4073be5\nmd\"## Example: Chip certification\n\nImagine you're a microchip certification engineer.  You probe microchips coming off the supply line to see if they are good or bad.  A microchip is bad if its power pin (which is the first pin) has a zero voltage.  If any of the other pins have zero voltage it's salvageable, and we'll say it's a good pin.  For simplicitly, we assume that only one (and exactly one) pin is faulty.\"\n\n# ╔═╡ 53572568-9d02-465a-baba-1c624d79d4b5\nmd\"We'll express our prior belief over which pin is faulty using a discrete uniform distribution over the 10 pins:\"\n\n# ╔═╡ f0f80b1a-d090-11eb-2b0d-d11fd8196311\n#using Omega, Distributions, UnicodePlots\n\n# ╔═╡ 4936c45a-a5bf-49cb-bfdc-c05883d5982b\nfaulty_pin = @~ DiscreteUniform(1, 10)\n\n# ╔═╡ 57c308fa-a2e7-49fb-b52d-41346ee7ea0d\nmd\"The probe tells us which pin is faulty.  Unfortunately, the probe is a little error prone.  Under normal operation it gives back the true answer, but with some probability it just gives back a random answer between 1 and 10\"\n\n# ╔═╡ d3af8df6-5375-4a52-9432-41ef6227af0c\nerror_prob = Variable(ω -> 0.01) # constant random variable\n\n# ╔═╡ b0769639-7b6a-4d95-bc8d-bdedd5d27c4f\nerror_occurred = @~ Bernoulli(error_prob)\n\n# ╔═╡ 8e2fb0c5-ca50-4bcb-85bf-d78c06ea5653\nalternative_pin = @~ DiscreteUniform(1, 10)\n\n# ╔═╡ ad3ec928-dc20-4987-aaed-78e8c4141d3e\nfunction measure(ω)\n\tif error_occurred(ω)\n\t\talternative_pin(ω)\n\telse\n\t\tfaulty_pin(ω)\n\tend\nend\n\n# ╔═╡ 87199546-b427-4908-9531-28d40995efa8\nmd\"As described above, a chip is bad if the faulty_pin is pin 1\"\n\n# ╔═╡ 4b8285ca-0fa8-4c38-a2a9-870169a2c1d7\nbad_chip = faulty_pin ==ₚ 1\n\n# ╔═╡ 021546fa-267d-4789-b6a5-b69d7eea01e6\nmd\"We'll define a function `prob` to estimate the probability that an event is true:\"\n\n# ╔═╡ 0ed2799b-0e1b-434a-85be-99a3869a89c7\nprob(x; n = 1000) = mean(randsample(x, n))\n\n# ╔═╡ 505f497c-2852-44f2-bf17-8bfb12886554\nmd\"The probability that it's a bad chip is:\"\n\n# ╔═╡ fc03484c-206d-4c3d-90f9-773e3b9b0a90\nprob(bad_chip)\n\n# ╔═╡ 413d05ce-ed65-406e-be97-32a2bad22d92\nmd\"Now suppose we use our probe and observe a measurement of 1\"\n\n# ╔═╡ ff0aced3-466f-44e8-8d84-9521fca7c7c4\nevidence = measure ==ₚ 1;\n\n# ╔═╡ 233e3ee2-e56c-4c4d-a53d-83c144c303d0\nmd\"Given the evidence, we can look at our conditional belief over which pin is faulty:\"\n\n# ╔═╡ 5774b63a-d492-490e-862a-0c3645722885\nhistogram(randsample(cnd(faulty_pin, evidence), 1000))\n\n# ╔═╡ c6d93cdd-a2bd-4e5b-b835-1509cc582978\nmd\"And compute the conditional probability that it is indeed a bad chip (faulty pin == 1)\"\n\n# ╔═╡ 32b3da83-0fb4-4a99-9742-46f9ad13eb8b\nconditional_bad_chip = cnd(bad_chip, evidence);\n\n# ╔═╡ 5ddfb321-d696-4853-bb9a-f3b8593f074d\nmd\"Given the evidence, the conditional probability the chip is bad is high, at:\"\n\n# ╔═╡ ff904fa3-898b-4c35-a1c4-8a08ca5f82df\nprob_bad = prob(conditional_bad_chip)\n\n# ╔═╡ ae28acc2-fb0f-4189-bdaa-574a3e090f75\nmd\"The certification handbook says a chip can be ceritifed if there's less than a 20% chance that it is faulty\"\n\n# ╔═╡ dbe58fac-bc39-4ee1-8930-6bb4e8453317\ncan_certify(p) = p < 0.3\n\n# ╔═╡ 03ac41b7-10fd-4466-976d-f2815fe655a2\nmd\"Clearly, we cannot certify this chip:\"\n\n# ╔═╡ 6b9ac9fa-56c3-453f-aba7-69cd193d91c3\ncan_certify(prob_bad)\n\n# ╔═╡ 9ef8cafd-49e5-439a-9723-479babd7e6d7\nmd\"### A Noisier Probe\n\\\"Not to worry!\\\" your colleague, Sneaky Simon says.  \\\"Just use the bad probe.\\\"\"\n\n# ╔═╡ 8c128635-e46d-418e-8c51-d74fc55973e4\nmd\"We'll use `intervene` in Omega to construct a different model where the error rate is different\"\n\n# ╔═╡ aa15703f-6137-4d67-bb25-bec070d3d193\nerror_prob_noisy = 0.9\n\n# ╔═╡ da0608ac-94bd-4ba1-81be-1cde40bd4cae\nconditional_bad_chip_noisy_probe = intervene(conditional_bad_chip, error_prob => error_prob_noisy);\n\n# ╔═╡ 828161b0-c32e-4ae8-9206-1f7ce95dfda4\nprob_bad_noisy = prob(conditional_bad_chip_noisy_probe)\n\n# ╔═╡ 1e1a3659-0a82-46c1-9b6e-0f8de142f9be\nmd\"Job done?\"\n\n# ╔═╡ b6470b88-3ac0-4ccf-81df-c6f80e409a64\ncan_certify(prob_bad_noisy)\n\n# ╔═╡ abe64bc4-cdef-4cb5-80cc-2e99e792ecab\nmd\"Apparently, Sneaky Simon was right.  Using the bad probe has allowed us to certify the chip.  Is this right?  If not, what has gone wrong?\"\n\n# ╔═╡ 672b6bfa-54ce-4b12-80f0-ee930a777cbc\nprobwow = pw(prob, rid(conditional_bad_chip_noisy_probe, (faulty_pin, alternative_pin)))\n\n# ╔═╡ 36a6cb8a-f81e-4e05-9dd0-a475e88ab62c\n# histogram(randsample(probwow, 100))\n\n# ╔═╡ Cell order:\n# ╟─daa9fd86-5a36-4aa2-842e-477cdb19b8d5\n# ╟─62257a75-2949-4afc-8543-fe3fa4073be5\n# ╟─53572568-9d02-465a-baba-1c624d79d4b5\n# ╠═f0f80b1a-d090-11eb-2b0d-d11fd8196311\n# ╠═ca32437b-65ce-401b-93fc-1f3b7011ae88\n# ╠═4936c45a-a5bf-49cb-bfdc-c05883d5982b\n# ╟─57c308fa-a2e7-49fb-b52d-41346ee7ea0d\n# ╠═d3af8df6-5375-4a52-9432-41ef6227af0c\n# ╠═b0769639-7b6a-4d95-bc8d-bdedd5d27c4f\n# ╠═8e2fb0c5-ca50-4bcb-85bf-d78c06ea5653\n# ╠═ad3ec928-dc20-4987-aaed-78e8c4141d3e\n# ╟─87199546-b427-4908-9531-28d40995efa8\n# ╠═4b8285ca-0fa8-4c38-a2a9-870169a2c1d7\n# ╟─021546fa-267d-4789-b6a5-b69d7eea01e6\n# ╠═0ed2799b-0e1b-434a-85be-99a3869a89c7\n# ╟─505f497c-2852-44f2-bf17-8bfb12886554\n# ╠═fc03484c-206d-4c3d-90f9-773e3b9b0a90\n# ╟─413d05ce-ed65-406e-be97-32a2bad22d92\n# ╠═ff0aced3-466f-44e8-8d84-9521fca7c7c4\n# ╟─233e3ee2-e56c-4c4d-a53d-83c144c303d0\n# ╠═5774b63a-d492-490e-862a-0c3645722885\n# ╟─c6d93cdd-a2bd-4e5b-b835-1509cc582978\n# ╠═32b3da83-0fb4-4a99-9742-46f9ad13eb8b\n# ╟─5ddfb321-d696-4853-bb9a-f3b8593f074d\n# ╠═ff904fa3-898b-4c35-a1c4-8a08ca5f82df\n# ╟─ae28acc2-fb0f-4189-bdaa-574a3e090f75\n# ╠═dbe58fac-bc39-4ee1-8930-6bb4e8453317\n# ╟─03ac41b7-10fd-4466-976d-f2815fe655a2\n# ╠═6b9ac9fa-56c3-453f-aba7-69cd193d91c3\n# ╟─9ef8cafd-49e5-439a-9723-479babd7e6d7\n# ╟─8c128635-e46d-418e-8c51-d74fc55973e4\n# ╠═aa15703f-6137-4d67-bb25-bec070d3d193\n# ╠═da0608ac-94bd-4ba1-81be-1cde40bd4cae\n# ╠═828161b0-c32e-4ae8-9206-1f7ce95dfda4\n# ╟─1e1a3659-0a82-46c1-9b6e-0f8de142f9be\n# ╠═b6470b88-3ac0-4ccf-81df-c6f80e409a64\n# ╟─abe64bc4-cdef-4cb5-80cc-2e99e792ecab\n# ╠═672b6bfa-54ce-4b12-80f0-ee930a777cbc\n# ╠═36a6cb8a-f81e-4e05-9dd0-a475e88ab62c\n", "meta": {"hexsha": "d8a41aa4cf74549861c9935ccb2a5f8b9a73f7e4", "size": 6560, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "OmegaExamples/src/dilution.jl", "max_stars_repo_name": "zenna/expect", "max_stars_repo_head_hexsha": "48bd661df410777eeb8940876a5cc8817eed2ac5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "OmegaExamples/src/dilution.jl", "max_issues_repo_name": "zenna/expect", "max_issues_repo_head_hexsha": "48bd661df410777eeb8940876a5cc8817eed2ac5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OmegaExamples/src/dilution.jl", "max_forks_repo_name": "zenna/expect", "max_forks_repo_head_hexsha": "48bd661df410777eeb8940876a5cc8817eed2ac5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2430939227, "max_line_length": 382, "alphanum_fraction": 0.7620426829, "num_tokens": 3106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.8887587920192298, "lm_q1q2_score": 0.772177448198}}
{"text": "using GR, LinearAlgebra, LowRankApprox, Formatting, ImageFiltering, Images, Plots, ImageMagick, Colors, TestImages, ImageView, ImageTransformations\n\nI=load(\"rgb.jpg\")\n\nG=Gray.(I)\n# size(G)\n\nA=imresize(G, ratio=1/5)\n# rank(A), size(A), eltype(A)\n\n(p,q)=size(A)\nB=Array{Float64}(A)\nU, S, V=psvd(B)\nB010=sum(S[n]*U[1:p,n]*(V[1:q,n])' for n=1:10);\nB030=sum(S[n]*U[1:p,n]*(V[1:q,n])' for n=1:30);\nB050=sum(S[n]*U[1:p,n]*(V[1:q,n])' for n=1:50);\nB070=sum(S[n]*U[1:p,n]*(V[1:q,n])' for n=1:70);\n\nplot(Gray.(B), \n    xaxis=false, \n    xticks=false, \n    yaxis=false, \n    yticks=false, \n    grid=false, \n    title=\"B=B(365) 365 by 548 full rank matrix\")\nsavefig(\"grayscale_svd_365.png\")\n\nplot(Gray.(B010), \n    xaxis=false, \n    xticks=false, \n    yaxis=false, \n    yticks=false, \n    grid=false, \n    title=\"B(10) rank 10 approximation\")\nsavefig(\"grayscale_svd_010.png\")\n\nplot(Gray.(B030), \n    xaxis=false, \n    xticks=false, \n    yaxis=false, \n    yticks=false, \n    grid=false, \n    title=\"B(30) rank 30 approximation\")\nsavefig(\"grayscale_svd_030.png\")\n\nplot(Gray.(B050), \n    xaxis=false, \n    xticks=false, \n    yaxis=false, \n    yticks=false, \n    grid=false, \n    title=\"B(50) rank 50 approximation\")\nsavefig(\"grayscale_svd_050.png\")\n\nplot(Gray.(B070), \n    xaxis=false, \n    xticks=false, \n    yaxis=false, \n    yticks=false, \n    grid=false, \n    title=\"B(70) rank 70 approximation\")\nsavefig(\"grayscale_svd_070.png\")\n\n", "meta": {"hexsha": "5fe668a67a43c68472561621ee11cc10a4fc51d5", "size": 1420, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "grayscale_svd.jl", "max_stars_repo_name": "hiroyuki-chihara/julia.samples", "max_stars_repo_head_hexsha": "3341be942f2d9c087dc7201c7a6c1fff714632ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-24T22:19:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T22:19:52.000Z", "max_issues_repo_path": "grayscale_svd.jl", "max_issues_repo_name": "hiroyuki-chihara/julia.samples", "max_issues_repo_head_hexsha": "3341be942f2d9c087dc7201c7a6c1fff714632ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grayscale_svd.jl", "max_forks_repo_name": "hiroyuki-chihara/julia.samples", "max_forks_repo_head_hexsha": "3341be942f2d9c087dc7201c7a6c1fff714632ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1875, "max_line_length": 147, "alphanum_fraction": 0.6281690141, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102580527665, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7721740719831499}}
{"text": "# logreg.jl\n#\n# Code for logistic regression, but this version uses mini-batches.\n#\n# In this case, for a triple (a, b, x), where a, x are n-vectors and b\n# is {-/+ 1} valued, the objective is\n#\n#  F(x, a, b) = log(1 + exp(-b * a' * x)).\n\nusing Distributions;\n\n# (A, b, x) = GenerateLogisticData(m::Int64 = 200, n::Int64 = 20;\n#                                  condition_number::Float64 = 1.0,\n#                                  snr::Float64 = 1.0)\n#\n# Generates logistic regression data where the data matrix A is m-by-n,\n# the label (target) vector b is length m, and the distribution of b is\n#\n#  p(b | a, x) = exp(b * a' * x) / (1 + exp(b * a' * x)),\n#\n# for b in {-1, 1}. The parameter snr governs the mean magnitude of\n# the inner products A * x, that is, the margins. (High snr means less\n# noise in the labels).\nfunction GenerateLogisticData(m::Int64 = 200, n::Int64 = 20;\n                              condition_number::Float64 = 1.0,\n                              snr::Float64 = 1.0)\n  A = randn(m, n);\n  if (condition_number > 1.0)\n    # Make A have condition number given\n    condition_vec = Vector(LinRange(1.0, condition_number, n));\n    condition_vec = condition_vec / norm(condition_vec);\n    A = A .* repeat(condition_vec', outer = (m, 1));\n  end\n  x = randn(n);\n  mean_inner_product = mean(abs.(A * x));\n  # Make it so that the mean inner product between data and x is equal\n  # to snr (the signal to noise ratio).\n  x = snr * x / mean_inner_product;\n  margins = A * x;\n  probs = 1 ./ (1 .+ exp.(-margins));\n  b = sign.(rand(m) .- 1 + probs);\n  return (A, b, x);\nend\n\n# o = LogisticRegressionObj(A::Matrix{Float64}, b::Vector{Float64},\n#                           x::Vector{Float64})\n#\n# Computes and returns logistic regression objective (mean log loss).\nfunction LogisticRegressionObj(A::Matrix{Float64}, b::Vector{Float64},\n                               x::Vector{Float64})\n  margins = b .* (A * x);\n  pos_inds = (margins .> 0);\n  neg_inds = (margins .<= 0);\n  obj = (sum(log.(1 .+ exp.(-margins[pos_inds])))\n         + sum(log.(1 .+ exp.(margins[neg_inds])) - margins[neg_inds]));\n  return obj / size(A, 1);\nend\n\n# g = LogisticRegressionGrad(A::Matrix{Float64}, b::Vector{Float64},\n#                            x::Vector{Float64})\n#\n# Computes and returns the gradient of the logistic regression loss.\nfunction LogisticRegressionGrad(A::Matrix{Float64}, b::Vector{Float64},\n                                x::Vector{Float64})\n  margins = b .* (A * x);\n  probs = b ./ (1 .+ exp.(margins));\n  grad = -A' * probs;\n  return grad / size(A, 1);\nend\n\n# x = SGUpdateLogistic(A::SubArray{Float64, 2}, b::SubArray{Float64, 1},\n#                        x_init::Vector{Float64}, stepsize::Float64)\n#\n# Computes and applies a minibatch stochastic gradient update to the\n# vector x_init for the logistic regression loss. The entire minibatch is\n# in the SubArrays (A, b), which can be treated like matrices.\nfunction SGUpdateLogistic(A::SubArray{Float64, 2}, b::SubArray{Float64, 1},\n                          x_init::Vector{Float64}, stepsize::Float64)\n  # Replace this code to return the correct update.\n  return x_init;\nend\n\n# x = TruncatedUpdateLogistic(A::SubArray{Float64, 2},\n#                             b::SubArray{Float64, 1},\n#                             x_init::Vector{Float64}, stepsize::Float64)\n#\n# Performs a mini-batch update using the truncated model for logistic\n# regression. In particular, letting a_i be the rows of the matrix A and\n# b_i the associated labels, uses that the logistic loss has lower-bound 0\n# to make the approximation\n#\n#  F_approx(x) = max{ F_0 + g' * (x - x_init), 0 }\n#\n# where F_0 = (1/m) sum_{i=1}^m log(1 + exp(-b_i * a_i' * x)) and\n#\n#   g = (d / dx) (1/m) sum_{i = 1}^m log(1 + exp(-b_i * a_i' * x))\n#\n# is the gradient on the mini-batch.\nfunction TruncatedUpdateLogistic(A::SubArray{Float64, 2},\n                                 b::SubArray{Float64, 1},\n                                 x_init::Vector{Float64}, stepsize::Float64)\n  # Replace this code to return the correct update.\n  return x_init;\nend\n\nfunction TruncatedUpdateLogistic(a::Vector{Float64},\n                                 b::Float64,\n                                 x_init::Vector{Float64}, stepsize::Float64)\n  # Replace this code to return the correct update.\n  return x_init;\nend\n\nfunction SGUpdateLogistic(a::Vector{Float64}, b::Float64,\n                          x_init::Vector{Float64}, stepsize::Float64)\n  # Replace this code to return the correct update.\n  return x_init;\nend\n", "meta": {"hexsha": "bf1d2f4f4853ad55c9599dd83ac47495c88037be", "size": 4516, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Machine Learning Summer School 2019 (London, UK)/tutorials/optimization/logreg.jl", "max_stars_repo_name": "xuedong/rlss2019", "max_stars_repo_head_hexsha": "d7468c2fcf269d8afd6fb0f44993aa9797867944", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Machine Learning Summer School 2019 (London, UK)/tutorials/optimization/logreg.jl", "max_issues_repo_name": "xuedong/rlss2019", "max_issues_repo_head_hexsha": "d7468c2fcf269d8afd6fb0f44993aa9797867944", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Machine Learning Summer School 2019 (London, UK)/tutorials/optimization/logreg.jl", "max_forks_repo_name": "xuedong/rlss2019", "max_forks_repo_head_hexsha": "d7468c2fcf269d8afd6fb0f44993aa9797867944", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2711864407, "max_line_length": 76, "alphanum_fraction": 0.6011957484, "num_tokens": 1291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.7721547984302207}}
{"text": "\nusing JuMP\nmodel = Model();\n\n\n@variable(model, free_x)\n\n\n@variable(model, keyword_x, lower_bound = 1, upper_bound = 2)\n\n\nhas_upper_bound(keyword_x)\n\n\nupper_bound(keyword_x)\n\n\n@variable(model, a[1:2, 1:2])\n\n\nn = 10\nl = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]\nu = [10; 11; 12; 13; 14; 15; 16; 17; 18; 19]\n\n@variable(model, l[i] <= x[i = 1:n] <= u[i])\n\n\n@variable(model, y[i = 1:2, j = 1:2] >= 2i + j)\n\n\n@variable(model, z[i = 2:3, j = 1:2:3] >= 0)\n\n\n@variable(model, w[1:5,[\"red\", \"blue\"]] <= 1)\n\n\n@variable(model, u[i = 1:3, j = i:5])\n\n\n@variable(model, v[i = 1:9; mod(i, 3) == 0])\n\n\n@variable(model, integer_z, integer = true)\n\n\n@variable(model, binary_z, binary = true)\n\n\n@variable(model, psd_x[1:2, 1:2], PSD)\n\n\n@variable(model, sym_x[1:2, 1:2], Symmetric)\n\n\nmodel = Model()\n@variable(model, x)\n@variable(model, y)\n@variable(model, z[1:10]);\n\n\n@constraint(model, con, x <= 4)\n\n\n@constraint(model, [i = 1:3], i * x <= i + 1)\n\n\n@constraint(model, [i = 1:2, j = 2:3], i * x <= j + 1)\n\n\n@constraint(model, [i = 1:2, j = 1:2; i != j], i * x <= j + 1)\n\n\nfor i in 1:3\n    @constraint(model, 6x + 4y >= 5i)\nend\n\n\n@constraint(model, [i in 1:3], 6x + 4y >= 5i)\n\n\n@constraint(model, sum(z[i] for i in 1:10) <= 1)\n\n\nusing GLPK\n\nmodel = Model(GLPK.Optimizer)\n@variable(model, x >= 0)\n@variable(model, y >= 0)\nset_objective_sense(model, MOI.MIN_SENSE)\nset_objective_function(model, x + y)\n\noptimize!(model)\n       \n@show objective_value(model);\n\n\nobjective_sense(model)\n\n\nobjective_function(model)\n\n\nobjective_function_type(model)\n\n\nvector_model = Model(GLPK.Optimizer)\n\nA= [ 1 1 9  5;\n     3 5 0  8;\n     2 0 6 13]\n\nb = [7; 3; 5]\n\nc = [1; 3; 5; 2]\n\n@variable(vector_model, x[1:4] >= 0)\n@constraint(vector_model, A * x .== b)\n@objective(vector_model, Min, c' * x)\n\noptimize!(vector_model)\n\n@show objective_value(vector_model);\n\n", "meta": {"hexsha": "715328aa4546b9dac4c739fa340ccd333d76fec2", "size": 1809, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/introduction/variables_constraints_objective.jl", "max_stars_repo_name": "mtanneau/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 75, "max_stars_repo_stars_event_min_datetime": "2020-06-15T13:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T12:58:48.000Z", "max_issues_repo_path": "test/introduction/variables_constraints_objective.jl", "max_issues_repo_name": "mtanneau/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-05-27T05:36:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T09:52:29.000Z", "max_forks_repo_path": "test/introduction/variables_constraints_objective.jl", "max_forks_repo_name": "mtanneau/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-10-09T09:32:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T17:41:21.000Z", "avg_line_length": 14.5887096774, "max_line_length": 62, "alphanum_fraction": 0.600331675, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.7721547920621507}}
{"text": "using Random,Distributions,StatsBase,Plots,HypothesisTests,Measures; pyplot()\nRandom.seed!(3)\n\ndist = Gamma(2, 2.5)\ndistH0 = Exponential(5)\nn = 100\ndata = rand(dist,n)\n\nFhat = ecdf(data)\ndiffF(dist, x) = sqrt(n)*(Fhat(x) - cdf.(dist,x))\nxGrid = 0:0.001:30\nksStat = maximum(abs.(diffF(distH0, xGrid)))\n\nM = 10^5\nKScdf(x) = sqrt(2pi)/x*sum([exp(-(2k-1)^2*pi^2 ./(8x.^2)) for k in 1:M])\n\nprintln(\"p-value calculated via series: \",\n\t1-KScdf(ksStat))\nprintln(\"p-value calculated via Kolmogorov distribution: \",\n\t1-cdf(Kolmogorov(),ksStat),\"\\n\")\n\nprintln(ApproximateOneSampleKSTest(data,distH0))\n\np1 = plot(xGrid, Fhat(xGrid), \n\tc=:black, lw=1, label=\"ECDF from data\")\np1 = plot!(xGrid, cdf.(dist,xGrid), \n\tc=:blue, ls=:dot, label=\"CDF under \\n actual distribution\")\np1 = plot!(xGrid, cdf.(distH0,xGrid), \n\tc=:red, ls=:dot, label=\"CDF under \\n postulated H0\", \n\txlims=(0,20), ylims=(0,1), xlabel = \"x\", ylabel = \"Probability\")\n\np2= plot(cdf.(dist,xGrid), diffF(dist, xGrid),lw=0.5, \n\tc=:blue,\tlabel=\"KS Process under \\n actual distribution\")\np2 = plot!(cdf.(distH0,xGrid), diffF(distH0, xGrid), lw=0.5, \n\tc=:red, xlims=(0,1), label=\"KS Process under \\n postulated H0\",\n    xlabel = \"t\", ylabel = \"K-S Process\")\n\nplot(p1, p2, legend=:bottomright, size=(800, 400), margin = 5mm)", "meta": {"hexsha": "30d174e8553d3e93e18d6c5b7e9a0f08356944ed", "size": 1270, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "7_chapter/ksBrownian.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "7_chapter/ksBrownian.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "7_chapter/ksBrownian.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 33.4210526316, "max_line_length": 77, "alphanum_fraction": 0.6653543307, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7721254311579828}}
{"text": "# module Angles\n\nexport\n    wrap_to_2pi,\n    wrap_to_pi,\n    angular_difference\n\nwrap_to_2pi(θ) = mod(θ,2π)\n\n\"\"\"\n    `wrap_to_pi(θ₀)`\n\n    wraps the angle θ₀ to a value in (-π,π]\n\"\"\"\nfunction wrap_to_pi(θ₀)\n    # θ = θ₀\n    θ = wrap_to_2pi(θ₀)\n    # while θ > π\n    if θ > π\n        θ = θ - 2π\n    # end\n    # while θ <= -π\n    elseif θ <= -π\n        θ += 2π\n    end\n    return θ\nend\n\nfunction angular_difference(θ1,θ2)\n    t1 = wrap_to_2pi(θ1)\n    t2 = wrap_to_2pi(θ2)\n    if t2 < t1\n        return -angular_difference(t2,t1)\n    end\n    wrap_to_pi(t2 - t1)\nend\n\n\n\"\"\"\n    intersections_between_circles(v1,v2,r1,r2)\n\"\"\"\nfunction intersections_between_circles(v1,v2,r1,r2)\n    d = norm(v1-v2)\n    if d > r1+r2\n        return nothing\n    elseif d < 1e-4 # almost collocated\n        return nothing\n    elseif d + r1 < r2 || d + r2 < r1 # completely contained\n        return nothing\n    else\n        x1,y1 = v1[1], v1[2]\n        x2,y2 = v2[1], v2[2]\n        l = (r1^2 - r2^2 + d^2)/(2*d)\n        h = sqrt(r1^2-l^2)\n        v0 = (l/d) * [(x2-x1), (y2-y1)] .+ v1\n        dv = (h/d) * [(y2-y1), -(x2-x1)]\n\n        return v0 .+ dv, v0 .- dv\n    end\nend\n\nfunction nearest_points_between_circles(v1,v2,r1,r2)\n    d = norm(v1-v2)\n    vec = v2 .- v1\n    if d > r1+r2\n        return v1 + normalize(vec) * r1,  v2 - normalize(vec) * r2\n    elseif d + r1 < r2 # circle 1 contained in circle 2 \n        return v1 - normalize(vec) * r1,  v2 - normalize(vec) * r2\n    elseif d + r2 < r1 # circle 2 contained in circle 1\n        return v1 + normalize(vec) * r1,  v2 + normalize(vec) * r2\n    elseif d < 1e-4 # almost collocated\n        return nothing\n    else\n        return intersections_between_circles(v1,v2,r1,r2)\n    end\nend", "meta": {"hexsha": "d0cb38c03a8aa15b92daef7594f70825a7a85ade", "size": 1710, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/angles.jl", "max_stars_repo_name": "kylejbrown17/GraphUtils.jl", "max_stars_repo_head_hexsha": "bc68e8ca6697e2ec24298eaf59b1b8cd2e08def7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/angles.jl", "max_issues_repo_name": "kylejbrown17/GraphUtils.jl", "max_issues_repo_head_hexsha": "bc68e8ca6697e2ec24298eaf59b1b8cd2e08def7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/angles.jl", "max_forks_repo_name": "kylejbrown17/GraphUtils.jl", "max_forks_repo_head_hexsha": "bc68e8ca6697e2ec24298eaf59b1b8cd2e08def7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5, "max_line_length": 66, "alphanum_fraction": 0.5555555556, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7721254173678898}}
{"text": "using IterativeSolvers\n\nA = Float64[\n  16 4 8;\n  4 5 -4;\n  8 -4 22;\n]\na = Float64[16; 18; -22]\nr = vcat(collect(1:6), collect(10:10:100))\nprintln()\n\nx_j = [(i=i, j=jacobi(A, a; maxiter=i)) for i in r]\nA * x_j[11].j |> display\nprintln()\n\nx_gs = [(i=i, gs=gauss_seidel(A, a; maxiter=i)) for i in r]\nA * x_gs[11].gs |> display\nprintln()\n\nω = 1.0\nx_sor = [(i=i, sor=sor(A, a, ω; maxiter=i)) for i in r]\nA * x_sor[11].sor |> display\nprintln()\n\nx_ssor = [(i=i, ssor=ssor(A, a, ω; maxiter=i)) for i in r]\nx_ssor |> display\nprintln()\nA * x_ssor[11].ssor |> display\nprintln()\n", "meta": {"hexsha": "504af4d82e52bc80bb6c623d7fcb009c8110057a", "size": 567, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch02/ex-jacobi.jl", "max_stars_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_stars_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "examples/ch02/ex-jacobi.jl", "max_issues_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "examples/ch02/ex-jacobi.jl", "max_forks_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 18.9, "max_line_length": 59, "alphanum_fraction": 0.5978835979, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7721254153997341}}
{"text": "@doc raw\"\"\"\n    LinearMixingModelKernel(k::Kernel, H::AbstractMatrix)\n    LinearMixingModelKernel(Tk::AbstractVector{<:Kernel},Th::AbstractMatrix)\n\nKernel associated with the linear mixing model, taking a vector of `m` kernels and a `m × p` matrix H for a function with `p` outputs. Also accepts a single kernel `k` for use across all `m` basis vectors. \n\n# Definition\n\nFor inputs ``x, x'`` and output dimensions ``p_x, p_{x'}'``, the kernel is defined as[^BPTHST]\n```math\nk\\big((x, p_x), (x, p_{x'})\\big) = H_{:,p_{x}}K(x, x')H_{:,p_{x'}}\n```\nwhere ``K(x, x') = Diag(k_1(x, x'), ..., k_m(x, x'))`` with zero off-diagonal entries.\n``H_{:,p_{x}}`` is the ``p_x``-th column (`p_x`-th output) of ``H \\in \\mathbb{R}^{m \\times p}``\nrepresenting ``m`` basis vectors for the ``p`` dimensional output space of ``f``.\n``k_1, \\ldots, k_m`` are ``m`` kernels, one for each latent process, ``H`` is a\nmixing matrix of ``m`` basis vectors spanning the output space.\n\n[^BPTHST]: Wessel P. Bruinsma, Eric Perim, Will Tebbutt, J. Scott Hosking, Arno Solin, Richard E. Turner (2020). [Scalable Exact Inference in Multi-Output Gaussian Processes](https://arxiv.org/pdf/1911.06287.pdf).\n\"\"\"\nstruct LinearMixingModelKernel{Tk<:AbstractVector{<:Kernel},Th<:AbstractMatrix} <: MOKernel\n    K::Tk\n    H::Th\n    function LinearMixingModelKernel(Tk::AbstractVector{<:Kernel}, H::AbstractMatrix)\n        @assert length(Tk) == size(H, 1) \"Number of kernels and number of rows in H must match\"\n        return new{typeof(Tk),typeof(H)}(Tk, H)\n    end\nend\n\nfunction LinearMixingModelKernel(k::Kernel, H::AbstractMatrix)\n    return LinearMixingModelKernel(Fill(k, size(H, 1)), H)\nend\n\nfunction (κ::LinearMixingModelKernel)((x, px)::Tuple{Any,Int}, (y, py)::Tuple{Any,Int})\n    (px > size(κ.H, 2) || py > size(κ.H, 2) || px < 1 || py < 1) &&\n        error(\"`px` and `py` must be within the range of the number of outputs\")\n    return sum(κ.H[i, px] * κ.K[i](x, y) * κ.H[i, py] for i in 1:length(κ.K))\nend\n\nfunction Base.show(io::IO, k::LinearMixingModelKernel)\n    return print(io, \"Linear Mixing Model Multi-Output Kernel\")\nend\n\nfunction Base.show(io::IO, mime::MIME\"text/plain\", k::LinearMixingModelKernel)\n    print(io, \"Linear Mixing Model Multi-Output Kernel. Kernels:\")\n    for k in k.K\n        print(io, \"\\n\\t\")\n        show(io, mime, k)\n    end\nend\n", "meta": {"hexsha": "87f2fd465ef4177f0f86f114bf0414e0b6ffd018", "size": 2325, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mokernels/lmm.jl", "max_stars_repo_name": "molet/KernelFunctions.jl", "max_stars_repo_head_hexsha": "d6161f217bcdfd548143f590a653ddcf22cde5c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mokernels/lmm.jl", "max_issues_repo_name": "molet/KernelFunctions.jl", "max_issues_repo_head_hexsha": "d6161f217bcdfd548143f590a653ddcf22cde5c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-20T12:51:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:51:15.000Z", "max_forks_repo_path": "src/mokernels/lmm.jl", "max_forks_repo_name": "molet/KernelFunctions.jl", "max_forks_repo_head_hexsha": "d6161f217bcdfd548143f590a653ddcf22cde5c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.5882352941, "max_line_length": 213, "alphanum_fraction": 0.6623655914, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7721254083091719}}
{"text": "function num_conbination(n::Int64, d::Int64)\n    div(factorial(n+d), factorial(n)*factorial(d)) - 1\nend\n\n\n\"\"\"\n    make_design_matrix(x, dims)\nThis function return the design matrix.\n\n# Parameters\n- `x`: input data\n- `dims`: degree of design matrix\n\n# Example\n```jldoctest regression\njulia> make_design_matrix(x, dims = 2) |> size\n(20, 5)\n```\n\"\"\"\nfunction make_design_matrix(x; dims = 2)\n    n_datas, n_features = size(x)\n    out_features = num_conbination(n_features, dims)\n    y = Array{Float64}(undef, n_datas, out_features)\n    current = 1\n    y[:, current : current+n_features-1] = x\n    index = collect(current : current+n_features-1)\n    current += n_features\n    push!(index, current)\n    for _ in 2 : dims\n        new = []\n        stop = index[end]\n        for feature_idx in 1 : n_features\n            start = index[feature_idx]\n            push!(new, current)\n            next= current + stop - start\n            next <= current && break\n            @. y[:, current : next-1] = y[:, start:stop-1] * x[:, feature_idx]\n            current = next\n        end\n        push!(new, current)\n        index = new\n    end\n    return y\nend", "meta": {"hexsha": "014a5eb5f1bf6562555380457daf8c1a8824fa59", "size": 1138, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Regression/BFM.jl", "max_stars_repo_name": "simonp0420/HorseML.jl", "max_stars_repo_head_hexsha": "ccdf43e2854fba367ba73ee70e81a3b90dc9bc6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-12-16T22:10:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T07:09:36.000Z", "max_issues_repo_path": "src/Regression/BFM.jl", "max_issues_repo_name": "simonp0420/HorseML.jl", "max_issues_repo_head_hexsha": "ccdf43e2854fba367ba73ee70e81a3b90dc9bc6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-12-12T14:13:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T14:00:10.000Z", "max_forks_repo_path": "src/Regression/BFM.jl", "max_forks_repo_name": "simonp0420/HorseML.jl", "max_forks_repo_head_hexsha": "ccdf43e2854fba367ba73ee70e81a3b90dc9bc6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-28T21:15:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T21:15:30.000Z", "avg_line_length": 25.8636363636, "max_line_length": 78, "alphanum_fraction": 0.5984182777, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321452198369, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7721244696384933}}
{"text": "fib(n) = n < 2 ? n : fib(n-1) + fib(n-2)\n\nfibTailRecursive(a, b=0, c=1) = a === 0 ? b : fibTailRecursive(a - 1, c, b + c)\n\nfibFormula(n) = round(((5 ^ .5 + 1) / 2) ^ n / (5 ^ .5))\n\nfunction fibLinear(n)\n  x,y = (0,1)\n  for i = 1:n\n    x,y = (y, x+y)\n  end\n  return x\nend\n\nfunction fibMatrix(n)\n  prevMatrix = BigInt[1 1; 1 0]\n  matrix = prevMatrix ^ n\n  matrix[2, 1]\nend\n\ninput = length(ARGS) === 0 ? 29 : parse(Int, ARGS[1])\nprintln(fibMatrix(input))\n", "meta": {"hexsha": "9c544bac5009a47f83a17a57c076d81150732c3d", "size": 452, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "language/julia/fib.jl", "max_stars_repo_name": "A1rPun/nurture", "max_stars_repo_head_hexsha": "d050837444a7ffb6d38be78044e7c1678f92b2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-30T17:12:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-30T17:12:31.000Z", "max_issues_repo_path": "language/julia/fib.jl", "max_issues_repo_name": "A1rPun/nurture", "max_issues_repo_head_hexsha": "d050837444a7ffb6d38be78044e7c1678f92b2b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "language/julia/fib.jl", "max_forks_repo_name": "A1rPun/nurture", "max_forks_repo_head_hexsha": "d050837444a7ffb6d38be78044e7c1678f92b2b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.652173913, "max_line_length": 79, "alphanum_fraction": 0.5508849558, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7721052819249383}}
{"text": "\n# Compute F-statistic, given vector of vectors\n#ANOVA\nfunction f(R)\n    X = vcat(R...)\n    N = length(X)\n    nj = length.(R)\n    X̅ = mean(X)\n    X̅j = mean.(R)\n    k = length(R)\n    top = sum(nj .*(X̅j .- X̅) .^2) /(k-1)\n    bottom = sum([sum((R[i] .- X̅j[i]) .^2) for i in 1:k])/(N-k)\n    return top/bottom\nend\nfunction f_slow(R,N,nj,X̅,k)\n    X̅j = mean.(R)\n    top = sum(nj .*(X̅j .- X̅) .^2) /(k-1)\n    bottom = sum([sum((R[i] .- X̅j[i]) .^2) for i in 1:k])/(N-k)\n    return top/bottom\nend\n\nfunction f(R,N,nj,X̅,k)\n    X̅j = mean.(R)\n    top = 0.0\n    bottom = 0.0\n    @inbounds for i in 1:k\n        top += nj[i] * (X̅j[i] - X̅)^2\n        for j in 1:nj[i]\n            bottom += (R[i][j] - X̅j[i])^2\n        end\n    end\n    top/= (k-1)\n    bottom /= (N-k)\n    return top/bottom\nend\n\n#Pairwise ANOVA\nfunction f_pairs(R) \n    n = length(R)\n    F = zeros(n,n)\n    for j in 1:n-1\n        for i in j+1:n\n            F[i,j] = f([R[i],R[j]])\n        end\n    end\n    return F\nend\nfunction f_pairs(R ::Vector,N ::Array{Int},nj ::Matrix{Tuple},X̅ ::Matrix{Float64}) \n    n = length(R)\n    F = zeros(n,n)\n    for j in 1:n-1\n        for i in j+1:n\n            F[i,j] = f([R[i],R[j]],N[i,j],nj[i,j],X̅[i,j],2)\n        end\n    end\n    return F\nend\n# get parameter values corresponding to each pairwise combination of groups\nfunction get_pars(R)\n    n = length(R)\n    N_p = Array{Int}(undef,n,n)\n    nj_p= Array{Tuple}(undef,n,n)\n    X̅_p = Array{Float64}(undef,n,n)\n\n    for j in 1:n-1\n        for i in j+1:n\n            N_p[i,j] = length(R[i]) + length(R[j])\n            nj_p[i,j] = (length(R[i]) , length(R[j]))\n            X̅_p[i,j] = mean(vcat(R[i]...,R[j]...))\n        end\n    end\n    return N_p,nj_p,X̅_p\nend\n", "meta": {"hexsha": "e43c5017f7ea366099bd295d4d080d71d9d4995c", "size": 1706, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ANOVA.jl", "max_stars_repo_name": "EvoArt/BetaDisp.jl", "max_stars_repo_head_hexsha": "83f1292011cf81897c5dbab910f895c4a931c704", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-19T22:47:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T10:39:25.000Z", "max_issues_repo_path": "src/ANOVA.jl", "max_issues_repo_name": "EvoArt/BetaDisp.jl", "max_issues_repo_head_hexsha": "83f1292011cf81897c5dbab910f895c4a931c704", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-03T20:30:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-03T20:30:34.000Z", "max_forks_repo_path": "src/ANOVA.jl", "max_forks_repo_name": "EvoArt/BetaDispersion.jl", "max_forks_repo_head_hexsha": "83f1292011cf81897c5dbab910f895c4a931c704", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0540540541, "max_line_length": 84, "alphanum_fraction": 0.4876905041, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7721052785811331}}
{"text": "using SparseArrays, LinearAlgebra\n\"\"\"\n    as_to_bs(a1, a2)\n\nCalculate reciprocal lattice vectors, `b1` and `b2`, from the real space lattice\nvectors, `a1` and `a2`.\n\"\"\"\nfunction as_to_bs(a1, a2)\n    b1 = 2pi * [+a2[2],-a2[1]] / (+a1[1]*a2[2]-a1[2]*a2[1])\n    b2 = 2pi * [-a1[2],+a1[1]] / (-a2[1]*a1[2]+a2[2]*a1[1])\n    return b1, b2\nend\n\n\n\"\"\"\n    bs_to_as(b1, b2)\n\nCalculate real space lattice vectors, `a1` and `a2`, from reciprocal lattice\nvectors, `b1` and `b2`.\n\nThis is actually the same as `as_to_bs`, but I think having both functions makes\nthe intention of the code more obvious.\n\"\"\"\nfunction bs_to_as(b1, b2)\n    return as_to_bs(b1, b2)\nend\n\n\"\"\"\n    DEX, DEY, DHX, DHY = diff_yee2(NGRID,RES,BC,kinc=nothing)\n=================\n- `NGRID`: [Nx Ny] grid size.\n- `RES`: [dx dy] grid resolution of the 1X grid.\n- `BC`: [xbc ybc] boundary conditions, `-2`: periodic (requires kinc), `0`: Dirichlet.\n- `kinc`: [kx ky] incident wave vector. This argument is only needed for periodic boundaries.\nPosition on the grid: m = (ny - 1)*Nx + nx\n\"\"\"\nfunction diff_yee2(NGRID::Matrix{Float64}, RES::Matrix{Float64}, BC::Matrix{Int64}, a1::Array{<:Real,1}, a2::Array{<:Real,1}, kinc=nothing)\n    if kinc != nothing\n        kinc0 = kinc\n    end\n    p(nx,ny,NX)::Int64 = nx+NX*(ny-1)\n    dx = RES[1]; dy = RES[2]\n    NX = NGRID[1]; NY = NGRID[2]; N = NX*NY;\n    Lamx = NX * dx\n    Lamy = NY * dy\n    N = convert(Int64,N);NX = convert(Int64,NX);NY = convert(Int64,NY)\n    if NX == 1\n        if BC[1] == 0\n            DEX = spzeros(N, N)\n        else\n            DEX = spdiagm(0 => im*kinc0[2]*ones(N))\n        end\n    else\n        DEX = spdiagm(0 => -1 ./ dx .* ones(ComplexF64, N), 1 => 1 ./ dx .* ones(ComplexF64, N - 1))\n        for ny=1:(NY-1)\n            DEX[p(NX,ny,NX),p(NX+1,ny,NX)] = 0  # Dirichlet BC\n        end\n        if BC[1]==-2\n            for ny=1:NY\n                DEX[p(NX,ny,NX),p(1,ny,NX)]=exp(-im*transpose(kinc0)*a1*Lamx)/dx # periodic BC\n            end\n\n        end\n    end\n\n    if NY==1\n        if BC[2] == 0\n            DEY = spzeros(N,N)\n        else\n            DEY = spdiagm(0 => im*kinc0[1]*ones(N))\n        end\n    else\n        DEY = spdiagm(0 => -1 ./dy.*ones(N), NX => 1 ./dy.*ones(N - NX)) .+ 0*im\n        if BC[2]==-2\n            for nx=1:NX\n                DEY[p(nx,NY,NX),p(nx,1,NX)]=exp(-im*transpose(kinc0)*a2*Lamy)/dy # periodic BC\n            end\n        end\n    end\n\n    DHX=-DEX'\n    DHY=-DEY'\n    return DEX,DEY,DHX,DHY\nend\n\n\n# \"\"\"\n#     DiagonalMatrix(diag::AbstractVector{ComplexF64})\n\n# A sparse diagonal matrix that can be used in left division (D \\\\ X)\n# \"\"\"\n# struct DiagonalMatrix <: AbstractMatrix{ComplexF64}\n#     diag::AbstractVector{ComplexF64}\n# end\n# Base.size(A::DiagonalMatrix) = (length(A.diag), length(A.diag))\n# Base.getindex(A::DiagonalMatrix, I::Vararg{Int,2}) = I[1]==I[2] ? A.diag[I[1]] : 0\n\neye(M) = Matrix{ComplexF64}(I, M, M)\ndiag_R(mat) = mat[diagind(mat)]\n\nfunction mask(M)\n    mat = zeros(M,M)\n    for i = -(M-1):M-1\n        mat = mat + diagm(i=>(-1)^(i)*ones(M-abs(i)))\n    end\n    return mat\nend", "meta": {"hexsha": "212536da7cc61706a4b184bea47b44dd9d1bc3ab", "size": 3059, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "kabume/Peacock.jl", "max_stars_repo_head_hexsha": "c0986ed8f2fab576211ae0779efa4b527ade8347", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-09-27T11:26:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T12:41:44.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "kabume/Peacock.jl", "max_issues_repo_head_hexsha": "c0986ed8f2fab576211ae0779efa4b527ade8347", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "kabume/Peacock.jl", "max_forks_repo_head_hexsha": "c0986ed8f2fab576211ae0779efa4b527ade8347", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5887850467, "max_line_length": 139, "alphanum_fraction": 0.5573716901, "num_tokens": 1134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7721052752373273}}
{"text": "\"\"\"\nmutable struct InverseDistanceSurrogate{X,Y,P,L,U} <: AbstractSurrogate\n\nThe square polynomial model can be expressed by 𝐲 = 𝐗β + ϵ, with β = 𝐗ᵗ𝐗⁻¹𝐗ᵗ𝐲\n\"\"\"\nmutable struct SecondOrderPolynomialSurrogate{X,Y,B,L,U} <: AbstractSurrogate\n    x::X\n    y::Y\n    β::B\n    lb::L\n    ub::U\nend\n\nfunction SecondOrderPolynomialSurrogate(x,y,lb,ub)\n    X = _construct_2nd_order_interp_matrix(x, first(x))\n    Y = _construct_y_matrix(y, first(y))\n    β = X\\Y\n    return SecondOrderPolynomialSurrogate(x, y, β, lb, ub)\nend\n\nfunction _construct_2nd_order_interp_matrix(x, x_el)\n    n = length(x)\n    d = length(x_el)\n    D = 1 + 2*d + d*(d-1)÷2\n    X = ones(eltype(x_el), n, D)\n    for i = 1:n, j = 1:d\n        X[i, j+1] = x[i][j]\n    end\n    idx = d + 1\n    for j = 1:d, k = j+1:d\n        idx += 1\n        for i = 1:n\n            X[i, idx] = x[i][j]*x[i][k]\n        end\n    end\n    for i = 1:n, j = 1:d\n        X[i, j+1+d+d*(d-1)÷2] = x[i][j]^2\n    end\n    return X\nend\n\n_construct_y_matrix(y, y_el::Number) = y\n_construct_y_matrix(y, y_el) = [y[i][j] for i=1:length(y), j=1:length(y_el)]\n\nfunction (my_second_ord::SecondOrderPolynomialSurrogate)(val)\n    #just create the val vector as X and multiply\n    d = length(val)\n\n    y = my_second_ord.β[1, :]\n    for j = 1:d\n        y += val[j]*my_second_ord.β[j+1, :]\n    end\n    idx = d + 1\n    for j = 1:d, k = j+1:d\n        idx += 1\n        y += val[j] * val[k] * my_second_ord.β[idx, :]\n    end\n    for j = 1:d\n        y += val[j]^2 * my_second_ord.β[j+1+d+d*(d-1)÷2, :]\n    end\n    return _match_container(y, first(my_second_ord.y))\nend\n\nfunction add_point!(my_second::SecondOrderPolynomialSurrogate, x_new, y_new)\n    if eltype(x_new) == eltype(my_second.x)\n        append!(my_second.x, x_new)\n        append!(my_second.y, y_new)\n    else\n        push!(my_second.x, x_new)\n        push!(my_second.y, y_new)\n    end\n    X = _construct_2nd_order_interp_matrix(my_second.x, first(my_second.x))\n    Y = _construct_y_matrix(my_second.y, first(my_second.y))\n    β = X\\Y\n    my_second.β = β\n    nothing\nend\n", "meta": {"hexsha": "a6de9989dce2c3cdd3bfacdbf0991a43d8383472", "size": 2040, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SecondOrderPolynomialSurrogate.jl", "max_stars_repo_name": "vikram-s-narayan/surrogates.jl", "max_stars_repo_head_hexsha": "6aaf17af3b903b173f995419d6705aff6206da06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 154, "max_stars_repo_stars_event_min_datetime": "2020-03-26T20:47:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T07:53:09.000Z", "max_issues_repo_path": "src/SecondOrderPolynomialSurrogate.jl", "max_issues_repo_name": "vikram-s-narayan/surrogates.jl", "max_issues_repo_head_hexsha": "6aaf17af3b903b173f995419d6705aff6206da06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 170, "max_issues_repo_issues_event_min_datetime": "2020-05-02T14:47:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T06:24:48.000Z", "max_forks_repo_path": "src/SecondOrderPolynomialSurrogate.jl", "max_forks_repo_name": "vikram-s-narayan/surrogates.jl", "max_forks_repo_head_hexsha": "6aaf17af3b903b173f995419d6705aff6206da06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2020-03-29T10:14:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T23:41:15.000Z", "avg_line_length": 26.1538461538, "max_line_length": 77, "alphanum_fraction": 0.5941176471, "num_tokens": 737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895028, "lm_q2_score": 0.8354835371034369, "lm_q1q2_score": 0.772105274795522}}
{"text": "# Copyright (c) 2021\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nusing LinearAlgebra; \n\n\"\"\"\n    SL0(A::Matrix{Float64}, b::Vector{Float64}; maxiter=100, epsilon=0.01, sigma_decrease_factor=0.85)\n\nFind the solution to Ax=b using Iterative Recursive Least Squares.\n\n### Input\n\n- `A`       -- Matrix: Ax=b \n- `b`       -- Vector: Ax=b\n- `sigma_decrease_factor` -- (optional) number of optmization iterations \n- `epsilon` -- (optional) threshold to stop optimizing\n- `maxiter` -- (optional) max number of iterations \n\n### Output\n\nSolution to Ax=b (Vector{Float64})\n\n### Algorithm\n\nSmoothed L0 (http://ee.sharif.edu/~SLzero/)\n\n\"\"\"\nfunction SL0(A::Matrix{Float64}, \n             b::Vector{Float64};\n             sigma_decrease_factor=.85, \n             maxiter=150, \n             epsilon=.001)\n    \n    # set up the locals \n    local mu_0, L, A_pinv, s, x; \n\n    # assign constants \n    mu_0 = 2;          # The  value  of  mu_0  scales  the sequence of mu\n    L = 3;             # number  of  iterations of the internal (steepest ascent) loop\n    A_pinv = pinv(A);  # pseudo-inverse of matrix A defined by A_pinv=A'*inv(A*A')\n\n    # initialize the solution \n    s = A_pinv*b;\n    sigma = 2*maximum(abs.(s));\n\n    for j = 1:maxiter\n\n        for i = 1:L\n            delta = s.*exp.(-abs.(s).^2/sigma^2);\n            s -= mu_0*delta; \n            s -= A_pinv*(A*s - b);\n        end\n        sigma *= sigma_decrease_factor;\n    end\n    x = s;\n    i = abs.(x) .< epsilon;\n    x[i] = zeros(sum(i));\n    return x\nend\n\n# A = randn(10, 50); b = randn(10);\n# x = SL0(A, b);\n# println(x)\n", "meta": {"hexsha": "d466358f2b87e3afb000dca4993c8a23d200a1a6", "size": 2588, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SL0.jl", "max_stars_repo_name": "gditzler/CompSense.jl", "max_stars_repo_head_hexsha": "c4dee7f673f8415858b0c6d013247c66c5a8b3c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SL0.jl", "max_issues_repo_name": "gditzler/CompSense.jl", "max_issues_repo_head_hexsha": "c4dee7f673f8415858b0c6d013247c66c5a8b3c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SL0.jl", "max_forks_repo_name": "gditzler/CompSense.jl", "max_forks_repo_head_hexsha": "c4dee7f673f8415858b0c6d013247c66c5a8b3c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.950617284, "max_line_length": 102, "alphanum_fraction": 0.6553323029, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7720804466654348}}
{"text": "using Plots,Statistics,LaTeXStrings,JLD,LsqFit\nfunction NeighborReturner(network_, i, j)\n    neighbors=[]\n    if j!=1 && network_[i,j-1]!=0\n        push!(neighbors, network_[i,j-1]) # the left neighbor--> neighbor[1]\n    end\n    if i!=1 && network_[i-1,j]!=0 #if true --> the neighbors[2] is the upper neighbor\n        push!(neighbors,network_[i-1,j])\n    end\n    return neighbors\nend\nfunction LabelFinder(a, L)\n    while L[a] != L[L[a]]\n        a = L[a]\n    end\n    return L[a]\nend\nfunction percolation_check(network_,L,dim)\n    first_col=[]\n    last_col=[]\n    for i in 1:dim\n        if network_[i,1]!=0\n            push!(first_col,LabelFinder(network_[i,1],L))\n        end\n    end\n    for i in 1:dim\n        if network_[i,dim]!=0\n            push!(last_col,LabelFinder(network_[i,dim],L))\n        end\n    end\n    return intersect(first_col,last_col)\nend\nfunction percolation(dim,p)\n    network_=zeros(Int, dim, dim)\n    L=[]\n    S=[]\n    counter=1\n    for col in 1:dim\n        for row in 1:dim\n            if p>rand()\n                neighbors=NeighborReturner(network_, row, col)\n                if length(neighbors)==0\n                    network_[row,col]=counter\n                    push!(L, counter)\n                    push!(S, 1)\n                    #println(S)\n                    counter+=1\n                elseif length(neighbors)==1\n                    network_[row,col]=LabelFinder(neighbors[1], L)\n                    S[LabelFinder(neighbors[1], L)]+=1\n                elseif length(neighbors)==2 && LabelFinder(neighbors[1],L)==LabelFinder(neighbors[2],L)\n                    network_[row,col]=LabelFinder(neighbors[1], L)\n                    S[LabelFinder(neighbors[1], L)]+=1\n                else\n                    S[LabelFinder(neighbors[1], L)]+=1+S[LabelFinder(neighbors[2], L)]\n                    S[LabelFinder(neighbors[2], L)]=0\n                    network_[row,col]=LabelFinder(neighbors[1], L)\n                    L[neighbors[2]]=LabelFinder(neighbors[1], L)\n                end\n            end\n        end\n    end\n    return network_,L,S\nend\nfunction RadiusOfGyration(network_,L,S,dim)\n    if length(Set(S)) < 3\n        return 0.0\n    end\n    if findall(x->x==maximum(S),S)[1] ∈ percolation_check(network_,L,dim)\n        S[findall(x->x==maximum(S),S)[1]]=0 #the infinit cluster is omitted from S in this way.\n    end\n    cluster_size=maximum(S)\n    S_max=findall(x->x==maximum(S),S)[1]\n    numerator=0\n    i_nums=[]\n    j_nums=[]\n    for coordinate_num in findall(x->x==S_max,network_)\n        push!(i_nums, coordinate_num[1])\n        push!(j_nums, coordinate_num[2])\n    end\n    i_com=mean(i_nums)\n    j_com=mean(j_nums)\n    TheFraction_list=[]\n    for i in 1:dim\n        for j in 1:dim\n             if network_[i, j]==S_max\n                push!(TheFraction_list,((i-i_com)^2 + (j-j_com)^2))\n            end\n        end\n    end\n    RadiusOfGyration=sqrt(mean(TheFraction_list))\n    return RadiusOfGyration\nend\ndim_list=[10,20,40,80,160]\nSavedData_std=[]\nSavedData_mean=[]\nfor n in 1:5\n    dim=dim_list[n]\n    Meanlist = []\n    STDlist = []\n    probability=[hcat(0:0.03:0.25)...,hcat(0.25:0.02:0.75)...,hcat(0.75:0.03:1)...]\n    for p in probability\n        xi=[]\n        for run_num in 1:1000\n            network_,L,S=percolation(dim,p)\n            push!(xi,RadiusOfGyration(network_,L,S,dim))\n        end\n        push!(STDlist, std(xi))\n        push!(Meanlist, mean(xi))\n    end\n    push!(SavedData_std, STDlist)\n    push!(SavedData_mean, Meanlist)\nend\nsave(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter4\\\\4.5\\\\AllData_HK.jld\",\n\"std_data\", SavedData_std,\n\"mean_data\", SavedData_mean)\n\n#creating the figures:\nload(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter4\\\\4.5\\\\AllData_HK.jld\")\n#plot withough error bars:\nplot(dpi=400)\nfor i in 1:5\n    dim=dim_list[i]\n    scatter!(probability, SavedData_mean[i][1:43],label=nothing,markersize=3,c=:black,alpha=0.3)\n    plot!(probability, SavedData_mean[i][1:43],label=L\"L=%$dim\")\n\nend\nscatter!(xlabel=\"P\", ylabel=L\"\\xi\", title=L\"\\xi\\_ P\")\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter4\\\\Fig\\\\4.5_plot.png\")\n#scatter plot including error bars:\nplot(dpi=400)\nfor i in 1:5\n    dim=dim_list[i]\n    scatter!(probability, SavedData_mean[i][1:43],yerr=SavedData_std[i][1:43],markersize=3,\n    alpha=0.7,label=L\"L=%$dim\")\n\nend\nscatter!(xlabel=\"P\", ylabel=L\"\\xi\", title=L\"\\xi\\_ P\")\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter4\\\\Fig\\\\4.5_scatter.png\")\n#getting Pc(∞) and ν:\nxdata=[]\nydata=dim_list\nfor i in 1:5\n    Pc_L= probability[findall(x->x==maximum(SavedData_mean[i]),SavedData_mean[i])[1]]\n    push!(xdata, Pc_L)\n\nend\nprintln(xdata)\nprintln(ydata)\n@.model(x,p)=abs(x-p[1])^(-p[2])\np0=[1.3, 0.59]\nfit=curve_fit(model, xdata, ydata, p0)\n#result: ν-->0.61 , Pc(∞)-->1.02\n", "meta": {"hexsha": "12b986e6455c6893a51b89d800205d61b208898e", "size": 4852, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter4/4.5/4.5.jl", "max_stars_repo_name": "narges8k/computational_physics", "max_stars_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter4/4.5/4.5.jl", "max_issues_repo_name": "narges8k/computational_physics", "max_issues_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter4/4.5/4.5.jl", "max_forks_repo_name": "narges8k/computational_physics", "max_forks_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T09:55:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T09:55:00.000Z", "avg_line_length": 31.5064935065, "max_line_length": 103, "alphanum_fraction": 0.5968672712, "num_tokens": 1481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7720804412775233}}
{"text": "##### OVERRIDES FOR EFFICIENCY / CORRECTNESS\n\nfunction add_vertices!(g::AbstractSimpleWeightedGraph, n::Integer)\n    T = eltype(g)\n    U = weighttype(g)\n    (nv(g) + one(T) <= nv(g)) && return false       # test for overflow\n    emptycols = spzeros(U, nv(g) + n, n)\n    g.weights = hcat(g.weights, emptycols[1:nv(g), :])\n    g.weights = vcat(g.weights, emptycols')\n    return true\nend\n\nfunction degree_matrix(g::AbstractSimpleWeightedGraph, T::DataType=weighttype(g); dir::Symbol=:out)\n    if is_directed(g)\n        if dir == :out\n            d = vec(sum(g.weights, dims=1))\n        elseif dir == :in\n            d = vec(sum(g.weights, dims=2))\n        elseif dir == :both\n            d = vec(sum(g.weights, dims=1)) + vec(sum(g.weights, dims=2))\n        else\n            throw(DomainError(dir, \"invalid argument, only accept :in, :out and :both\"))\n        end\n    else\n        d = vec(sum(g.weights, dims=1))\n    end\n    return SparseMatrixCSC(T.(diagm(0=>d)))\nend\n\nfunction adjacency_matrix(g::AbstractSimpleWeightedGraph, T::DataType=weighttype(g); dir::Symbol=:out)\n    if dir == :out\n        return SparseMatrixCSC(T.(copy(g.weights))')\n    else\n        return T.(copy(g.weights))\n    end\nend\n\nfunction laplacian_matrix(g::AbstractSimpleWeightedGraph, T::DataType=weighttype(g); dir::Symbol=:out)\n    degree_matrix(g, T; dir=dir) - adjacency_matrix(g, T; dir=dir)\nend\n\nfunction pagerank(g::SimpleWeightedDiGraph, α=0.85, n::Integer=100, ϵ=1.0e-6)\n    A = weights(g)\n    S = vec(sum(A, dims=1))\n    S = 1 ./ S\n    S[findall(S .== Inf)] .= 0.0\n    M = A'  # need a separate line due to bug #17456 in julia\n    # scaling the adjmat to stochastic adjacency matrix\n    M = (Diagonal(S) * M)'\n    N = Int(nv(g))\n    # solution vector\n    x = fill(1.0 / N, N)\n    # personalization vector\n    p = fill(1.0 / N, N)\n    # temporary to hold the results of SpMV\n    y = zeros(Float64, N)\n    # adjustment for leaf nodes in digraph\n    dangling_weights = p\n    is_dangling = findall(S .== 0)\n    # save some flops by precomputing this\n    pscaled = (1 .- α) .* p\n    for _ in 1:n\n        xlast = x\n        # in place SpMV to conserve memory\n        mul!(y, M, x)\n        # using broadcast to avoid temporaries\n        x = α .* (y .+ sum(x[is_dangling]) .* dangling_weights) .+ pscaled\n        # l1 change in solution convergence criterion\n        err = sum(abs, (x .- xlast))\n        if (err < N * ϵ)\n            return x\n        end\n    end\n    error(\"Pagerank did not converge after $n iterations.\")\nend\n\nsavegraph(fn::AbstractString, g::AbstractSimpleWeightedGraph, gname::AbstractString=\"graph\"; compress=true) =\n    savegraph(fn, g, gname, SWGFormat(), compress=compress)\n\nsavegraph(fn::AbstractString, d::Dict{T, U}; compress=true) where T <: AbstractString where U <: AbstractSimpleWeightedGraph =\n    savegraph(fn, d, SWGFormat(), compress=compress)\n\n# It is possible that this is suboptimal, but it is the most trivial extension of the implementation used in Graphs.jl\nfunction cartesian_product(g::G, h::G) where G <: AbstractSimpleWeightedGraph\n    z = G(nv(g) * nv(h))\n    id(i, j) = (i - 1) * nv(h) + j\n    for e in edges(g)\n        i1, i2 = Tuple(e)\n        for j = 1:nv(h)\n            add_edge!(z, id(i1, j), id(i2, j), weight(e))\n        end\n    end\n\n    for e in edges(h)\n        j1, j2 = Tuple(e)\n        for i in vertices(g)\n            add_edge!(z, id(i, j1), id(i, j2), weight(e))\n        end\n    end\n    return z\nend\n\n# Connected Components on a Sparse Matrix\n\nfunction _cc(g::SimpleWeightedGraph{T,U}) where T where U\n    a = weights(g)\n    comp = 0\n    n = size(a, 1)\n    marks = zeros(T, n)\n    queue = Vector{T}()\n    for i = 1:n\n        if marks[i] == 0\n            comp += 1\n            push!(queue, i)\n            while !isempty(queue)\n                v = pop!(queue)\n                marks[v] = comp\n                for index in nzrange(a,v)\n                    n = a.rowval[index]\n                    if marks[n] == 0\n                        push!(queue, n)\n                    end\n                end\n            end\n        end\n    end\n    marks, comp\nend\n\nfunction connected_components(g::SimpleWeightedGraph{T,U}) where T where U\n    marks, num_cc = _cc(g)\n    cc = [Vector{T}() for i = 1:num_cc]\n    for (i,v) in enumerate(marks)\n        push!(cc[v], i)\n    end\n    cc\nend\n\nfunction induced_subgraph(g::T, vlist::AbstractVector{U}) where T <: AbstractSimpleWeightedGraph where U <: Integer\n    E = eltype(g)\n    allunique(vlist) || throw(ArgumentError(\"Vertices in subgraph list must be unique\"))\n    new_weights = g.weights[E.(vlist), E.(vlist)]\n    newg = zero(g)\n    newg.weights = new_weights\n    return newg, Vector{E}(vlist)\nend\n", "meta": {"hexsha": "eb6a19d43fdc50b99df9f4ec51718272b942c868", "size": 4663, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/overrides.jl", "max_stars_repo_name": "scheidan/SimpleWeightedGraphs.jl-1", "max_stars_repo_head_hexsha": "e500596d906193d2de8d052f72ceeb750c1de1bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 57, "max_stars_repo_stars_event_min_datetime": "2017-07-09T11:38:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T10:39:16.000Z", "max_issues_repo_path": "src/overrides.jl", "max_issues_repo_name": "scheidan/SimpleWeightedGraphs.jl-1", "max_issues_repo_head_hexsha": "e500596d906193d2de8d052f72ceeb750c1de1bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 79, "max_issues_repo_issues_event_min_datetime": "2017-07-15T19:10:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-22T11:55:02.000Z", "max_forks_repo_path": "src/overrides.jl", "max_forks_repo_name": "scheidan/SimpleWeightedGraphs.jl-1", "max_forks_repo_head_hexsha": "e500596d906193d2de8d052f72ceeb750c1de1bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34, "max_forks_repo_forks_event_min_datetime": "2017-07-10T16:18:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T09:12:07.000Z", "avg_line_length": 31.7210884354, "max_line_length": 126, "alphanum_fraction": 0.5867467296, "num_tokens": 1372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7720804386708497}}
{"text": "# Matern 5/2 isotropic covariance function\n\n\"\"\"\n    Mat52Iso <: MaternIso\n\nIsotropic Matern 5/2 kernel (covariance)\n```math\nk(x,x') = σ²(1+√5|x-x'|/ℓ + 5|x-x'|²/(3ℓ²))\\\\exp(- √5|x-x'|/ℓ)\n```\nwith length scale ``ℓ`` and signal standard deviation ``σ``.\n\"\"\"\nmutable struct Mat52Iso{T<:Real} <: MaternIso\n    \"Length scale\"\n    ℓ::T\n    \"Signal variance\"\n    σ2::T\n    \"Priors for kernel parameters\"\n    priors::Array\nend\n\n\"\"\"\nMatern 5/2 isotropic covariance function\n    \n    Mat52Iso(ll::Real, lσ::Real)\n\n# Arguments\n  - `ll::Real`: length scale (given on log scale)\n  - `lσ::Real`: signal standard deviation (given on log scale)  \n\"\"\"\nMat52Iso(ll::T, lσ::T) where T = Mat52Iso{T}(exp(ll), exp(2 * lσ), [])\n\nfunction set_params!(mat::Mat52Iso, hyp::AbstractVector)\n    length(hyp) == 2 || throw(ArgumentError(\"Matern 5/2 has two parameters, received $(length(hyp)).\"))\n    mat.ℓ, mat.σ2 = exp(hyp[1]), exp(2 * hyp[2])\nend\nget_params(mat::Mat52Iso{T}) where T = T[log(mat.ℓ), log(mat.σ2) / 2]\nget_param_names(mat::Mat52Iso) = [:ll, :lσ]\nnum_params(mat::Mat52Iso) = 2\n\ncov(mat::Mat52Iso, r::Number) =\n    (s = √5 * r / mat.ℓ; mat.σ2 * (1 + s + s^2 / 3) * exp(-s))\n\n@inline dk_dll(mat::Mat52Iso, r::Real) =\n    (s = √5 * r / mat.ℓ; mat.σ2 / 3 * s^2 * (1 + s) * exp(-s))\n", "meta": {"hexsha": "d7e345ebd497333d5234d9acfd6af889cffa7d6a", "size": 1266, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/mat52_iso.jl", "max_stars_repo_name": "mcusi/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 284, "max_stars_repo_stars_event_min_datetime": "2015-07-31T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T07:08:58.000Z", "max_issues_repo_path": "src/kernels/mat52_iso.jl", "max_issues_repo_name": "mcusi/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 171, "max_issues_repo_issues_event_min_datetime": "2015-05-28T12:04:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T06:48:23.000Z", "max_forks_repo_path": "src/kernels/mat52_iso.jl", "max_forks_repo_name": "mcusi/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-05-31T12:44:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:21:38.000Z", "avg_line_length": 28.1333333333, "max_line_length": 103, "alphanum_fraction": 0.6082148499, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7720804367127385}}
{"text": "## Canonical Form of Normal distribution\n\nimmutable NormalCanon <: ContinuousUnivariateDistribution\n    η::Float64       # σ^(-2) * μ\n    λ::Float64    # σ^(-2)\n    μ::Float64       # μ\n\n    function NormalCanon(η::Real, λ::Real)\n        @check_args(NormalCanon, λ > zero(λ))\n    \tnew(η, λ, η / λ)\n    end\n    NormalCanon() = new(0.0, 1.0, 0.0)\nend\n\n@distr_support NormalCanon -Inf Inf\n\n\n## conversion between Normal and NormalCanon\n\nBase.convert(::Type{Normal}, d::NormalCanon) = Normal(d.μ, 1.0 / sqrt(d.λ))\nBase.convert(::Type{NormalCanon}, d::Normal) = (λ = 1.0 / σ^2; NormalCanon(λ * d.μ, λ))\ncanonform(d::Normal) = convert(NormalCanon, d)\n\n\n#### Parameters\n\nparams(d::NormalCanon) = (d.η, d.λ)\n\n\n#### Statistics\n\nmean(d::NormalCanon) = d.μ\nmedian(d::NormalCanon) = mean(d)\nmode(d::NormalCanon) = mean(d)\n\nskewness(d::NormalCanon) = 0.0\nkurtosis(d::NormalCanon) = 0.0\n\nvar(d::NormalCanon) = 1.0 / d.λ\nstd(d::NormalCanon) = sqrt(var(d))\n\nentropy(d::NormalCanon) = 0.5 * (log2π + 1.0 - log(d.λ))\n\n\n#### Evaluation\n\npdf(d::NormalCanon, x::Float64) = (sqrt(d.λ) / sqrt2π) * exp(-0.5 * d.λ * abs2(x - d.μ))\nlogpdf(d::NormalCanon, x::Float64) = 0.5 * (log(d.λ) - log2π - d.λ * abs2(x - d.μ))\n\nzval(d::NormalCanon, x::Float64) = (x - d.μ) * sqrt(d.λ)\nxval(d::NormalCanon, z::Float64) = d.μ + z / sqrt(d.λ)\n\ncdf(d::NormalCanon, x::Float64) = normcdf(zval(d,x))\nccdf(d::NormalCanon, x::Float64) = normccdf(zval(d,x))\nlogcdf(d::NormalCanon, x::Float64) = normlogcdf(zval(d,x))\nlogccdf(d::NormalCanon, x::Float64) = normlogccdf(zval(d,x))\n\nquantile(d::NormalCanon, p::Float64) = xval(d, norminvcdf(p))\ncquantile(d::NormalCanon, p::Float64) = xval(d, norminvccdf(p))\ninvlogcdf(d::NormalCanon, lp::Float64) = xval(d, norminvlogcdf(lp))\ninvlogccdf(d::NormalCanon, lp::Float64) = xval(d, norminvlogccdf(lp))\n\n\n#### Sampling\n\nrand(cf::NormalCanon) = cf.μ + randn() / sqrt(cf.λ)\nrand!{T<:Real}(cf::NormalCanon, r::AbstractArray{T}) = rand!(convert(Normal, cf), r)\n", "meta": {"hexsha": "3714ada2899118bf5398cc3f9df2cde6901dad26", "size": 1952, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/normalcanon.jl", "max_stars_repo_name": "ericproffitt/Distributions.jl", "max_stars_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/normalcanon.jl", "max_issues_repo_name": "ericproffitt/Distributions.jl", "max_issues_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/normalcanon.jl", "max_forks_repo_name": "ericproffitt/Distributions.jl", "max_forks_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7058823529, "max_line_length": 88, "alphanum_fraction": 0.6413934426, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8438950947024556, "lm_q1q2_score": 0.7720804319733899}}
{"text": "# Map-MCMC for mixtures.\r\n\r\n# This code assumes the following functions have been defined:\r\n#   likelihood(x[j],theta)\r\n#   log_v_prior(v)\r\n#   log_theta_prior(theta)\r\n#   theta_prop(theta)\r\n#   log_theta_prop(theta,thetap)\r\n#   new_thetas(m)\r\n\r\nfunction sampler(x,n_samples,m,c,sigma,zeta)\r\n    # x = data (array of datapoints)\r\n    # n_samples = # of MCMC iterations\r\n    # m = maximum # of mixture components\r\n    # c = cutoff point for weight map\r\n    # sigma = scale of weight proposals\r\n    # zeta = power to raise likelihood to\r\n\r\n    n = length(x)\r\n    \r\n    # initialize state\r\n    v = zeros(m); v[1] = 2*c; v[2:end] = c/2 # latent weights\r\n    q = max(v-c,0) # mapped weights (unnormalized)\r\n    s = sum(q)\r\n    theta = new_thetas(m)\r\n\r\n    # initialize vars for computing likelihood\r\n    L = [likelihood(x[j],theta[i]) for i=1:m, j=1:n]\r\n    M = vec(q'*L)  # mixture density with unnormalized weights\r\n    ll = sum(log(M)) - n*log(s)  # log-lik\r\n    Mp = zeros(n)  # Mp and Lp will hold proposed values\r\n    Lp = zeros(n)\r\n\r\n    # record-keeping\r\n    k_r = zeros(n_samples)\r\n    m_r = zeros(n_samples,m)\r\n    l_r = zeros(n_samples,m)\r\n    v_r = zeros(n_samples,m)\r\n    nta = 0  # number of theta proposals accepted\r\n    nva = 0  # number of v proposals accepted\r\n    \r\n    # draw samples\r\n    for iter = 1:n_samples\r\n        # update parameters with Metropolis-Hastings moves\r\n        for i = 1:m\r\n            thetap = theta_prop(theta[i])\r\n            llp = -n*log(s)\r\n            for j = 1:n\r\n                Lp[j] = likelihood(x[j],thetap)\r\n                Mp[j] = max(M[j] + q[i]*(Lp[j] - L[i,j]), 0)  \r\n                # Note: max(.,0) prevents negative values due to roundoff error.\r\n                llp += log(Mp[j])\r\n            end\r\n            # compute acceptance probability\r\n            top = log_theta_prior(thetap) + zeta*llp + log_theta_prop(thetap,theta[i])\r\n            bot = log_theta_prior(theta[i]) + zeta*ll + log_theta_prop(theta[i],thetap)\r\n            p_accept = min(1, exp(top-bot))\r\n            # accept or reject\r\n            if rand() < p_accept\r\n                theta[i] = copy(thetap)\r\n                for j = 1:n; L[i,j] = Lp[j]; end\r\n                M,Mp = Mp,M\r\n                ll = llp\r\n                nta += 1\r\n            end\r\n        end\r\n        \r\n        # update weights with Metropolis-Hastings moves\r\n        for i = 1:m\r\n            vp = v[i]*exp(randn()*sigma)\r\n            qp = max(vp-c,0)\r\n            sp = s + qp - q[i]\r\n            if sp > 0\r\n                llp = -n*log(sp)\r\n                for j = 1:n\r\n                    Mp[j] = max(M[j] + (qp - q[i])*L[i,j], 0)\r\n                    llp += log(Mp[j])\r\n                end\r\n                # compute acceptance probability\r\n                top = log_v_prior(vp) + zeta*llp - log(v[i])\r\n                bot = log_v_prior(v[i]) + zeta*ll - log(vp)\r\n                p_accept = min(1, exp(top-bot))\r\n                # accept or reject\r\n                if rand() < p_accept\r\n                    v[i] = vp\r\n                    q[i] = qp\r\n                    s = sp\r\n                    M,Mp = Mp,M\r\n                    ll = llp\r\n                    nva += 1\r\n                end\r\n            end\r\n        end\r\n\r\n        # record\r\n        k_r[iter] = sum(q.>0)  # number of active components\r\n        for i = 1:m\r\n            m_r[iter,i] = theta[i][1]  # means\r\n            l_r[iter,i] = theta[i][2]  # precisions\r\n            v_r[iter,i] = v[i]  # latent weights\r\n        end\r\n\r\n        # visualize mixture components during sampling\r\n        if false\r\n            figure(10); clf(); hold(true)\r\n            xs = linspace(-5,5,1000)\r\n            for i = 1:m\r\n                if q[i]>0\r\n                    plot(xs,(q[i]/s)*normpdf(xs,theta[i][1],theta[i][2]))\r\n                end\r\n            end\r\n            draw()\r\n        end\r\n    end\r\n    art = nta/(m*n_samples)  # MH acceptance rate for theta proposals\r\n    arv = nva/(m*n_samples)  # MH acceptance rate for v proposals\r\n    return (q/s),theta,k_r,v_r,art,arv,m_r,l_r\r\nend\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "e4cb1543ab08166838173ac58ae359d6ed57d3b4", "size": 4052, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "mixtures/core.jl", "max_stars_repo_name": "jwmi/CoarsenedPosterior", "max_stars_repo_head_hexsha": "dc230af244281f5fb9a9f657d2a534eb1a720560", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-16T23:26:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-16T23:26:55.000Z", "max_issues_repo_path": "mixtures/core.jl", "max_issues_repo_name": "jwmi/CoarsenedPosterior", "max_issues_repo_head_hexsha": "dc230af244281f5fb9a9f657d2a534eb1a720560", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mixtures/core.jl", "max_forks_repo_name": "jwmi/CoarsenedPosterior", "max_forks_repo_head_hexsha": "dc230af244281f5fb9a9f657d2a534eb1a720560", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-10-21T14:06:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-29T16:06:46.000Z", "avg_line_length": 32.6774193548, "max_line_length": 88, "alphanum_fraction": 0.473840079, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.772056006480391}}
{"text": "# # Symmetry reducting a strong relaxation of the quadratic assigment problem\r\n# Here, we are going to show how to load a QAP from QABLib, formulate \r\n# a strong semidefinite relaxation of it, symmetry reduce it, and finally solve it.\r\n\r\n# ## Quadratic assigment problems\r\n# QAPs are given by two quadratic matrices $A$ and $B$. The objective is to permute \r\n# the rows and columns of $B$, such that the inner product between the matrices is \r\n# minimized.\r\n#\r\n# ``\\mathrm{QAP}(A,B) = \\min_{\\phi\\in S_n} \\sum_{i,j=1}^n a_{ij}b_{\\phi(i)\\phi(j)}``\r\n#\r\n# QAPs are notoriously hard to solve exactly, but there exist strong polynomial time\r\n# relaxations, such as the following semidefinite programming relaxation:\r\n#\r\n# ```math\r\n# \\begin{aligned}\r\n# \\min\\enspace & \\langle B\\otimes A ,Y\\rangle\\\\\r\n# \\mathrm{s.t.}\\enspace & \\langle I_n\\otimes E_{jj},Y\\rangle=1 \\text{ for }j\\in [n],\\\\\r\n# & \\langle E_{jj}\\otimes I_n,Y\\rangle=1 \\text{ for }j\\in [n],\\\\\r\n# & \\langle I_n\\otimes (J_n-I_n)+(J_n-I_n)\\otimes I_n,Y\\rangle =0, \\\\\r\n# & \\langle J_{n^2},Y\\rangle = n^2,\\\\\r\n# & Y\\in D^{n^2},\r\n# \\end{aligned}\r\n# ```\r\n#\r\n# But in practice this relaxation is often too big to be solved directly.\r\n\r\n\r\n# ## Loading the data of a QAP\r\nusing SparseArrays, LinearAlgebra\r\nusing Test #src\r\n\r\nfile = joinpath(@__DIR__, \"esc16j.dat\")\r\ndata = open(file) do file\r\n    read(file, String)\r\nend\r\ndata = split(data, [' ', '\\n', '\\r'], keepempty = false)\r\n\r\nn = parse(Int64, data[1])\r\nA = zeros(Int64, n, n)\r\nB = zeros(Int64, n, n)\r\n\r\npos = 2\r\nfor x = 1:n\r\n    for y = 1:n\r\n        A[x, y] = parse(Int64, data[pos])\r\n        global pos += 1\r\n    end\r\nend\r\nfor x = 1:n\r\n    for y = 1:n\r\n        B[x, y] = parse(Int64, data[pos])\r\n        global pos += 1\r\n    end\r\nend\r\n\r\n\r\n# ## Building the SDP (in vectorized standard form)\r\nn = size(A, 1)\r\n\r\n## Objective\r\nCPrg = sparse(kron(B, A))\r\n\r\nIn = sparse(I, n, n)\r\nJn = ones(n, n)\r\n\r\n## Vectorised constraint matrices as rows of large matrix APrg\r\nAPrg = spzeros(2n + 1, n^4)\r\nbPrg = zeros(2n + 1)\r\ncurrentRow = 1\r\n\r\nfor j = 1:n\r\n    Ejj = spzeros(n, n)\r\n    Ejj[j, j] = 1.0\r\n    APrg[currentRow, :] = vec(kron(In, Ejj))\r\n    bPrg[currentRow] = 1\r\n    global currentRow += 1\r\n    ## Last constraint is linearly dependent on others\r\n    if (j < n)\r\n        APrg[currentRow, :] = vec(kron(Ejj, In))\r\n        bPrg[currentRow] = 1\r\n        global currentRow += 1\r\n    end\r\nend\r\n\r\nAPrg[currentRow, :] = vec(kron(In, Jn - In) + kron(Jn - In, In))\r\nbPrg[currentRow] = 0\r\ncurrentRow += 1\r\nAPrg[currentRow, :] = vec(ones(n^2, n^2))\r\nbPrg[currentRow] = n^2\r\n\r\nCPrg = sparse(vec(0.5 * (CPrg + CPrg')));\r\n\r\n# ## Symmetry reducing the SDP \r\n\r\n# We first determine an optimal admissible partition subspace\r\nusing SDPSymmetryReduction\r\nP = admPartSubspace(CPrg, APrg, bPrg, true)\r\nP.n\r\n\r\n@test P.n == 150 #src\r\n# And then we block-diagonalize it \r\nblkD = blockDiagonalize(P, true);\r\n@test sort(blkD.blkSizes) == sort([7, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) #src\r\n\r\n# ## Determining the coefficients of the reduced SDP \r\nPMat = hcat([sparse(vec(P.P .== i)) for i = 1:P.n]...)\r\nnewA = APrg * PMat\r\nnewB = bPrg\r\nnewC = CPrg' * PMat;\r\n\r\n## Removing linearly dependent constraints #src\r\n# using RowEchelon  #src\r\n# T = rref!(Matrix(hcat(newA,newB))) #src\r\n# r = rank(T) #src\r\n# newA = T[1:r,1:end-1] #src\r\n# newB = T[1:r,end] #src\r\n# length(newB) #src\r\n\r\n# ## Solving the reduced SDP with JuMP and CSDP\r\n\r\nusing JuMP, CSDP\r\nm = Model(CSDP.Optimizer)\r\n\r\n## Initialize variables corresponding parts of the partition P\r\n## >= 0 because the original SDP-matrices are entry-wise nonnegative\r\nx = @variable(m, x[1:P.n] >= 0)\r\n\r\n@constraint(m, newA * x .== newB)\r\n@objective(m, Max, newC * x)\r\n\r\npsdBlocks = sum(blkD.blks[i] .* x[i] for i = 1:P.n)\r\nfor blk in psdBlocks\r\n    if size(blk, 1) > 1\r\n        @constraint(m, blk in PSDCone())\r\n    else\r\n        @constraint(m, blk .>= 0)\r\n    end\r\nend\r\n\r\noptimize!(m)\r\n#\r\ntermination_status(m)\r\n#\r\nobjective_value(m)\r\n\r\n@test objective_value(m) ≈ 48.3042 atol = 5#src", "meta": {"hexsha": "aa41faa6eb9c35c3b80254d6901b9fa924bc4f2e", "size": 4001, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/QuadraticAssignmentProblems.jl", "max_stars_repo_name": "DanielBrosch/SDPSymmetryReduction.jl", "max_stars_repo_head_hexsha": "cc934307800e556aea124838153f4c46177110c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-10-21T02:31:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T17:37:10.000Z", "max_issues_repo_path": "docs/src/examples/QuadraticAssignmentProblems.jl", "max_issues_repo_name": "DanielBrosch/SDPSymmetryReduction.jl", "max_issues_repo_head_hexsha": "cc934307800e556aea124838153f4c46177110c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-09T11:21:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T15:14:57.000Z", "max_forks_repo_path": "docs/src/examples/QuadraticAssignmentProblems.jl", "max_forks_repo_name": "DanielBrosch/SDPSymmetryReduction.jl", "max_forks_repo_head_hexsha": "cc934307800e556aea124838153f4c46177110c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2176870748, "max_line_length": 87, "alphanum_fraction": 0.6168457886, "num_tokens": 1374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.772055980261322}}
{"text": "using OffsetArrays\nusing SpecialFunctions: gamma, erfcx\nusing PyPlot\nusing Polynomials\nusing Printf\nusing LinearAlgebra\n\nΓ(z) = gamma(z)\n\nfunction pade(α::T, β::T, m::Integer, n::Integer) where T <: AbstractFloat\n    if mod(m+n,2) == 0\n        throw(ArgumentError(\"m+n must be odd\"))\n    end\n    r = div(m+n-1,2)\n    a = OffsetArray{T}(undef, 0:m-1)\n    b = OffsetArray{T}(undef, 0:n-1)\n    pow = one(T)\n    for k = 0:m-1\n        a[k] = pow / Γ(β+k*α)\n        pow = -pow\n    end\n    b[0] = zero(T)\n    pow = one(T)\n    for k = 1:n-1\n        pow = -pow\n        b[k] = pow * sinpi(k*α-β) * Γ(1+k*α-β) / π\n    end\n    A = zeros(T, 2r-1, 2r-1)\n    rhs = zeros(T, 2r-1)\n    if m ≥ r+1\n        for k = 1:r-1\n            A[k,k] = one(T)\n            for j = 1:k\n                A[k,r-1+j] = -a[k-j]\n            end\n            rhs[k] = a[k]\n        end\n        for k = r:m-1\n            for j = 1:r\n                A[k,r-1+j] = -a[k-j]\n            end\n            rhs[k] = a[k]\n        end\n        for k = r-n+1:r-1\n            row = k+r\n            A[row,k] = one(T)\n            for j = k+1:r\n                col = j + r - 1\n                A[row,col] = -b[j-k]\n            end\n        end\n    else\n        for k = 1:m-1\n            A[k,k] = one(T)\n            for j = 1:k\n                col = r - 1 + j\n                A[k,col] = -a[k-j]\n            end\n            rhs[k] = a[k]\n        end\n        for k = 1:n-r-1\n            row = k + m - 1\n            for j = 1:r\n                col = r - 1 + j\n                A[row,col] = -b[j+k]\n            end\n            rhs[row] = b[k]\n        end\n        for j = 1:r\n            col = r - 1 + j \n            A[r,col] = -b[j]\n        end\n        rhs[r] = -a[0]\n        for k = 1:r-1\n            row = r + k\n            A[row,k] = one(T)\n            for j = k+1:r\n                col = r - 1 + j\n                A[row,col] = -b[j-k]\n            end\n        end\n    end\n    coeffs = A \\ rhs\n    p = OffsetArray{T}(undef, 0:r-1)\n    q = OffsetArray{T}(undef, 0:r)\n    p[0] = a[0]\n    for k = 1:r-1\n        p[k] = coeffs[k]\n    end\n    q[0] = one(T)\n    for k = 1:r\n        q[k] = coeffs[k+r-1]\n    end\n    return p, q, A, rhs\nend\n\n#T = BigFloat\nT = Float64\nr = 3\nα = 1 / parse(T, \"2\")\nβ = parse(T, \"1\")\nx = range(zero(T), parse(T, \"10\"), length=201)\ny = erfcx.(x)\nfigure(1)\nfor m = r:5\n    n = 2r + 1 - m\n    @printf(\"%3d  %3d\", m, n)\n    p, q, A, rhs = pade(α, β, m, n)\n    @printf(\"  %5.2f\\n\", cond(A))\n    P = Polynomial(p[0:r-1])\n    Q = Polynomial(q[0:r])\n    err = P.(x) ./ Q.(x) - y\n    plot(x, err, label=\"m, n = $m, $n\")\nend\nlegend()\ngrid(true)\n\nfigure(2)\n#for (r, m, n) in [(4, 5, 4), (8, 9, 8), (12, 13, 12), (16, 17, 16)]\nfor (r, m, n) in [(4, 5, 4), (8, 9, 8), (12, 13, 12)]\n    p, q, A, rhs = pade(α, β, m, n)\n    println(\"cond(A) = \", cond(A))\n    display(p)\n    display(q)\n    P = Polynomial(p[0:r-1])\n    Q = Polynomial(q[0:r])\n    err = P.(x) ./ Q.(x) - y\n    semilogy(x, abs.(err), label=\"m, n = $m, $n\")\nend\nlegend()\ngrid(true)\n", "meta": {"hexsha": "211f4cc92324f197fc5dd199eccdfb9ee0c97b55", "size": 2985, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiments/pade2.jl", "max_stars_repo_name": "billmclean/MittagLefflerFunctions.jl", "max_stars_repo_head_hexsha": "5244e7fce7efeee160edfc76eb7cab5e7624ae8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments/pade2.jl", "max_issues_repo_name": "billmclean/MittagLefflerFunctions.jl", "max_issues_repo_head_hexsha": "5244e7fce7efeee160edfc76eb7cab5e7624ae8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experiments/pade2.jl", "max_forks_repo_name": "billmclean/MittagLefflerFunctions.jl", "max_forks_repo_head_hexsha": "5244e7fce7efeee160edfc76eb7cab5e7624ae8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6136363636, "max_line_length": 74, "alphanum_fraction": 0.3902847571, "num_tokens": 1158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004808, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7720559719731515}}
{"text": "function can_cut(c, k, as)\n    sum([ceil(Int, a/c) - 1 for a in as]) ≤ k\nend\n\n\nfunction solve()\n    n, k = [parse(Int, x) for x in split(readline())]\n    as = [parse(Int, x) for x in split(readline())]\n\n    lb, ub = 0, maximum(as)\n    while lb + 1 < ub\n        c = ceil(Int, (ub + lb) / 2)\n        if can_cut(c, k, as)\n            ub = c\n        else\n            lb = c\n        end\n    end\n    ceil(Int, ub)\nend\n\nprintln(solve())\n", "meta": {"hexsha": "bfd73ab74a947eb22a5a35b2d5f16115b4d0d37c", "size": 430, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "abc171-180/abc174/e.jl", "max_stars_repo_name": "aishikawa/atcoder-julia", "max_stars_repo_head_hexsha": "93339ea6dd954b0739b3895a5625f94433e33baf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "abc171-180/abc174/e.jl", "max_issues_repo_name": "aishikawa/atcoder-julia", "max_issues_repo_head_hexsha": "93339ea6dd954b0739b3895a5625f94433e33baf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "abc171-180/abc174/e.jl", "max_forks_repo_name": "aishikawa/atcoder-julia", "max_forks_repo_head_hexsha": "93339ea6dd954b0739b3895a5625f94433e33baf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6956521739, "max_line_length": 53, "alphanum_fraction": 0.4813953488, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7720559714768644}}
{"text": "\n\nfunction read_Species_From_Text_File(file_name)\n    return reaction_matrix\nend\n\n\n\nfunction calculate_concentration(c_0, λ, Δt)\n    Λ = Diagonal(λ)\n    R = assemble_transformation_matrix_inverse(λ)\n    S = assemble_transformation_matrix(λ)\n    A = S * Λ * R * Δt\n    return exp(A) * c_0\nend\n\n\n\nfunction transformation_matrix_inverse_ij(i, j, λ)\n    s_ij::eltype(λ) = 1.0\n    # Loop over species ancestor index l for species i with (i-j) generations\n    for l = j:(i-1)\n        s_ij *= λ[l] / (λ[l] - λ[i])\n    end\n    return s_ij\nend\n\n\n\nfunction transformation_matrix_ij(i, j, λ)\n    s_ij = λ[j] / (λ[i] - λ[j])\n    # Loop over species ancestor index l for species i with (i-j) generations\n    for l = (j+1):(i-1)\n        s_ij *= λ[l] / (λ[l] - λ[j])\n    end\n    return s_ij\nend\n\n\n\nfunction assemble_transformation_matrix(λ)\n    n = length(λ)\n    S = zeros(eltype(λ), length(λ), length(λ))\n    S = UnitLowerTriangular(S)\n    for i = 2:n\n        for j = 1:(i-1)\n            S[i, j] = transformation_matrix_ij(i, j, λ)\n        end\n    end\n    return S\nend\n\n\n\nfunction assemble_transformation_matrix_inverse(λ)\n    n = length(λ)\n    R = zeros(eltype(λ), length(λ), length(λ))\n    R = UnitLowerTriangular(R)\n    for i = 2:n\n        for j = 1:i\n            R[i, j] = transformation_matrix_inverse_ij(i, j, λ)\n        end\n    end\n    return R\nend\n\n\n\nfunction retrieve_generation_number(i, j)\n    return (i - j)\nend\n\n\n\nfunction transformation_matrix_5x5(λ = [1.0; 2.0; 3.0; 4.0; 5.0])\n\n    s = zeros(5, 5)\n    s[1, 1] = 1\n\n    s[2, 1] = λ[1] / (λ[2] - λ[1])\n    s[3, 1] = λ[1] / (λ[3] - λ[1]) * λ[2] / (λ[2] - λ[1])\n    s[4, 1] = λ[1] / (λ[4] - λ[1]) * λ[2] / (λ[2] - λ[1]) * λ[3] / (λ[3] - λ[1])\n    s[5, 1] =\n        λ[1] / (λ[5] - λ[1]) * λ[2] / (λ[2] - λ[1]) *\n        λ[3] / (λ[3] - λ[1]) * λ[4] / (λ[4] - λ[1])\n\n    s[2, 2] = 1\n    s[3, 2] = λ[2] / (λ[3] - λ[2])\n    s[4, 2] = λ[2] / (λ[4] - λ[2]) * λ[3] / (λ[3] - λ[2])\n    s[5, 2] = λ[2] / (λ[5] - λ[2]) * λ[3] / (λ[3] - λ[2]) * λ[4] / (λ[4] - λ[2])\n\n    s[3, 3] = 1\n    s[4, 3] = λ[3] / (λ[4] - λ[3])\n    s[5, 3] = λ[3] / (λ[5] - λ[3]) * λ[4] / (λ[4] - λ[3])\n\n    s[4, 4] = 1\n    s[5, 4] = λ[4] / (λ[5] - λ[4])\n\n    s[5, 5] = 1\n\n    return s\nend\n\n\n\nfunction transformation_matrix_inverse_5x5(λ = [1.0; 2.0; 3.0; 4.0; 5.0])\n\n    s = zeros(5, 5)\n    s[1, 1] = 1\n\n    s[2, 1] = λ[1] / (λ[1] - λ[2])\n    s[3, 1] = λ[1] / (λ[1] - λ[3]) * λ[2] / (λ[2] - λ[3])\n    s[4, 1] = λ[1] / (λ[1] - λ[4]) * λ[2] / (λ[2] - λ[4]) * λ[3] / (λ[3] - λ[4])\n    s[5, 1] =\n        λ[1] / (λ[1] - λ[5]) * λ[2] / (λ[2] - λ[5]) * λ[3] / (λ[3] - λ[5]) *\n        λ[4] / (λ[4] - λ[5])\n\n    s[2, 2] = 1\n    s[3, 2] = λ[2] / (λ[2] - λ[3])\n    s[4, 2] = λ[2] / (λ[2] - λ[4]) * λ[3] / (λ[3] - λ[4])\n    s[5, 2] = λ[2] / (λ[2] - λ[5]) * λ[3] / (λ[3] - λ[5]) * λ[4] / (λ[4] - λ[5])\n\n    s[3, 3] = 1\n    s[4, 3] = λ[3] / (λ[3] - λ[4])\n    s[5, 3] = λ[3] / (λ[3] - λ[5]) * λ[4] / (λ[4] - λ[5])\n\n    s[4, 4] = 1\n    s[5, 4] = λ[4] / (λ[4] - λ[5])\n\n    s[5, 5] = 1\n\n    return s\nend\n", "meta": {"hexsha": "c67c95d4e71789ae5fdc5593a3ac0363386c613b", "size": 2996, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "main.jl", "max_stars_repo_name": "rannewan/RadioactiveDecayNetwork", "max_stars_repo_head_hexsha": "421a5252bc3b695227ca9b57de3790219482cfb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.jl", "max_issues_repo_name": "rannewan/RadioactiveDecayNetwork", "max_issues_repo_head_hexsha": "421a5252bc3b695227ca9b57de3790219482cfb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.jl", "max_forks_repo_name": "rannewan/RadioactiveDecayNetwork", "max_forks_repo_head_hexsha": "421a5252bc3b695227ca9b57de3790219482cfb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3582089552, "max_line_length": 80, "alphanum_fraction": 0.4449265688, "num_tokens": 1468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.8198933381139646, "lm_q1q2_score": 0.772055970747305}}
{"text": "#=\nSmall illustation on the capacitated vehicle routing problem (CVRP)\nJust run the script for an illustration\n\nMathematical model based on: https://www.researchgate.net/publication/323173028_Two_models_of_the_capacitated_vehicle_routing_problem\nusing modified indices to match Julia's 1-based indexing\n\nIn this model we eliminate all subtour explicitely, keep in mind that this is very expensive  \nas the number of subtours grows exponentially with the number of cities! A modified approach is to solve the\nrelaxed problem (i.e. without subtour constraints) and only add them when they occur (thus solving the model again),\nadding the constraint that prohibits the subtour that was found during the previous iteration cf.\nhttps://how-to.aimms.com/Articles/332/332-Implicit-Dantzig-Fulkerson-Johnson.html\nfor a clear explanation.\n\n=#\nusing JuMP\nusing GLPK\nusing Plots\nusing Combinatorics:powerset # may require additional install\n\n\"\"\"\nMultiple Vehicle Routing problem (using the entire set of possible subtours for subtour elimination)\n\"\"\"\nfunction MVRP()\n    # general problem setup #\n    # --------------------- #\n    # number of cities\n    n = 6\n    # pick random locations\n    coord_x = rand(n+1)\n    coord_y = rand(n+1)\n    dist(x_1, x_2, y_1, y_2) = sqrt((x_1 - x_2)^2 + (y_1 - y_2)^2)\n    # cost matrix (symmetrical, distances, depot is city 1) \n    c = zeros(n+1, n+1)\n    for i in 1:n+1\n        for j in i+1:n+1\n            c[i,j] = dist(coord_x[i], coord_x[j], coord_y[i], coord_y[j])\n        end\n    end\n    c .+= c'\n    # demand for each city (number of e.g. number of pallets)\n    d = rand(1:10, n+1)\n    d[1] = 0 # no demand @ depot\n    # truck capacity (equal for all trucks, can easily be extended to different size trucks)\n    Q = 20\n    # minimum number of trucks for order to be feasible:\n    p = ceil(Int,sum(d) / Q)\n    @info \"$(p) trucks required\"\n\n\n    # Linear programming setup #\n    # ------------------------ #\n    model = Model(with_optimizer(GLPK.Optimizer))\n    # Add variables (x_{i,j,p}: edge from i > j by truck p, Boolean valued)\n    @variable(model, x[1:n+1,1:n+1,1:p], Bin)\n    # Add objective\n    @objective(model, Min, sum(sum(x[:,:,i] .* c) for i in 1:p))\n    # Add constraints\n    for r in 1:p\n        # each vehicle can leave the depot only once\n        @constraint(model, sum(x[1, j, p] for j in 2:n+1) == 1)\n        # sum of the demands of the customers visited in a route is less than or equal to the capacity of the vehicle\n        @constraint(model, sum(d[j]*x[i,j,r] for i in 1:n+1 for j in 2:n+1 if i≠j) <= Q)\n        # the number of the vehicles arriving at every customer and entering the depot is equal to the number of the vehicles leaving\n        for j in 1:n+1\n            @constraint(model, sum(x[i,j,r] for i in 1:n+1 if i≠j) == sum(x[j,i,r] for i in 1:n+1))\n        end\n    end\n    # ensure that each customer is visited by exactly one vehicle\n    for j in 2:n+1\n        @constraint(model, sum(x[i,j,r] for r in 1:p for i in 1:n+1 if i≠j) == 1)\n    end\n    \n    #=\n    # eliminate sub-tours (essential but costly)\n    for subset in powerset(2:n+1, 2, n)\n        @constraint(model, sum(x[i,j,r] for r in 1:p for i in subset for j in subset if i≠j) <= length(subset) - 1 )\n    end\n    =#\n    # Solve problem\n    optimize!(model)\n    @info \"termination status: $(termination_status(model))\"\n    @info \"objective_value $(objective_value(model))\"\n\n\n\n    #     Nice illustration    #\n    # ------------------------ #\n    marks = [:circle for _ in 1:n+1]\n    marks[1] = :cross\n    fig = plot()\n    scatter!(fig, coord_x[1:1], coord_y[1:1], marker=:cross, label=\"Depot\", color=:black,markersize=12)\n    scatter!(fig, coord_x[2:end], coord_y[2:end], marker=:circle, label=\"Stores\", color=:gray )\n    for r in 1:p\n        inds = findall(x-> !iszero(x), value.(x[:,:,r]))\n        for ind in inds\n            xx = [coord_x[ind[1]]; coord_x[ind[2]]]\n            yy = [coord_y[ind[1]]; coord_y[ind[2]]]\n            plot!(fig, xx, yy, color=r, label=\"\")\n        end\n    end\n    title!(fig, \"lay-out for $(p) trucks with $(n) cities\")\n    display(fig)\nend\n\n\"\"\"\nMultiple Trip Vehicle Routing problem\n\nImplementation according to the 4-index formulation, also uses the entire set of subtours (similar to the other example)\n\nRemark: since we are mimimising the total time of all trips, it can happen that a single truck gets two trips, while the \nother one gets nothing at all. In a simulation context, you should take this into account.\n\"\"\"\nfunction MTVRP()\n    # general problem setup #\n    # --------------------- #\n    # number of cities\n    n = 7\n    # pick random locations\n    coord_x = rand(n+1)\n    coord_y = rand(n+1)\n    dist(x_1, x_2, y_1, y_2) = sqrt((x_1 - x_2)^2 + (y_1 - y_2)^2)\n    # cost matrix (symmetrical, distances, depot is city 1) \n    c = zeros(n+1, n+1)\n    for i in 1:n+1\n        for j in i+1:n+1\n            c[i,j] = dist(coord_x[i], coord_x[j], coord_y[i], coord_y[j])\n        end\n    end\n    c .+= c'\n    # demand for each city (number of e.g. number of pallets)\n    d = rand(1:10, n+1)\n    d[1] = 0 # no demand @ depot\n    # truck capacity (equal for all trucks, can easily be extended to different size trucks)\n    Q = 20\n    V = 2 # number of vehicles\n    R = 3 # number of trips/vehicle\n    TH = 5 # max trip length => results in \"infeasible\" \n    # minimum number of trucks for order to be feasible:\n    @info \"$(ceil(Int,sum(d) / Q)) trips required for a solution\"\n    @info \"$(V) trucks used, max $(R) trips per truck, total work time $(TH)\"\n    # Linear programming setup #\n    # ------------------------ #\n    model = Model(with_optimizer(GLPK.Optimizer))\n    # Add variables \n    # x_{i,j,v, r}: edge from i > j by truck v on trip r, Boolean valued\n    @variable(model, x[1:n+1, 1:n+1, 1:V, 1:R], Bin)\n    # y_{i, v, r}: 1 if trip r of vehicle v visits vertex i, Boolean valued\n    @variable(model, y[1:n+1, 1:V, 1:R], Bin)\n    \n    # Add objective (slices)\n    @objective(model, Min, sum(sum(x[:,:,v,r] .* c) for v in 1:V for r in 1:R)) # (1)\n    \n    # Add constraints\n    for i in 2:n+1\n        @constraint(model, sum(y[i,v,r] for v in 1:V for r in 1:R) == 1) # (2)\n    end\n\n    for v in 1:V\n        for r in 1:R\n            for i in 1:n+1\n                @constraint(model, sum(x[i,j,v,r] for j in 1:n+1 if j≠i) == y[i,v,r]) # (3)\n                @constraint(model, sum(x[j,i,v,r] for j in 1:n+1 if j≠i) == y[i,v,r]) # (3)\n                @constraint(model, sum(x[j,i,v,r] for j in 1:n+1 if j≠i) == sum(x[i,j,v,r] for j in 1:n+1 if j≠i)) # (3)\n            end\n\n            @constraint(model, sum(d[i] * y[i,v,r] for i in 2:n+1) <= Q) # (4)\n            for subset in powerset(2:n+1, 2, n)\n                @constraint(model, sum(x[i,j,v,r] for i in subset for j in subset if i≠j) <= length(subset) - 1 ) # (5)\n            end\n        \n        end\n    end\n\n    for v in 1:V\n        @constraint(model, sum(sum(x[:,:,v,r] .* c) for r in 1:R) <= TH) # (6)\n    end\n\n    optimize!(model)\n    @info \"termination status: $(termination_status(model))\"\n    @info \"objective_value $(objective_value(model))\"\n    \n    #     Nice illustration    #\n    # ------------------------ #\n    marks = [:circle for _ in 1:n+1]\n    marks[1] = :cross\n    fig = plot()\n    scatter!(fig, coord_x[1:1], coord_y[1:1], marker=:cross, label=\"Depot\", color=:black,markersize=12)\n    scatter!(fig, coord_x[2:end], coord_y[2:end], marker=:circle, label=\"Stores\", color=:gray )\n    for v in 1:V\n        for r in 1:R\n            inds = findall(x-> !iszero(x), value.(x[:,:,v,r]))\n            for ind in inds\n                xx = [coord_x[ind[1]]; coord_x[ind[2]]]\n                yy = [coord_y[ind[1]]; coord_y[ind[2]]]\n                plot!(fig, xx, yy, color=v, label=\"\", line=r)\n            end\n            @info \"truck $(v), route $(r): $(round(sum(c[inds]), digits=2)) kms\"\n        end\n    end\n    title!(fig, \"lay-out for $(V) trucks with $(n) cities, max $(R) routes per truck\\ncolor= truck, line thickness=route\")\n    display(fig)\nend\n\n\nMVRP()\n#MTVRP()", "meta": {"hexsha": "35e452a718705ff8d6edd0ac7c3cbb8b73005db8", "size": 8005, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Exercises/jumpsnippet.jl", "max_stars_repo_name": "BenLauwens/ES313.jl", "max_stars_repo_head_hexsha": "5a7553e53c288834f768d26e0d5aa22f9062b6af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-12-17T16:00:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-18T04:09:25.000Z", "max_issues_repo_path": "Exercises/jumpsnippet.jl", "max_issues_repo_name": "BenLauwens/ES313", "max_issues_repo_head_hexsha": "5a7553e53c288834f768d26e0d5aa22f9062b6af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercises/jumpsnippet.jl", "max_forks_repo_name": "BenLauwens/ES313", "max_forks_repo_head_hexsha": "5a7553e53c288834f768d26e0d5aa22f9062b6af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-08-27T13:41:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:00:53.000Z", "avg_line_length": 38.6714975845, "max_line_length": 133, "alphanum_fraction": 0.5907557776, "num_tokens": 2454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7720559657570236}}
{"text": "# ------------------------------------------------------------\n# Truncated cosine and its Fourier transform\n\n# Support = [-1/2,1/2]\nfunction tcos(x)\n\tif 0.0 <= x <= 0.5\n\t\treturn cos(2*pi*x)\n\telse\n\t\treturn 0.0\n\tend\nend\n\nfunction ftcos(xi)\n\tif abs(xi) == 1.0\n\t\treturn 0.25 + 0.0*im\n\telse\n\t\treturn im*xi*( 1 + exp(-pi*xi*im) ) / (2*pi*(1 - xi^2))\n\tend\nend\n\n\n# Overload ftcos to vector input\n@vectorize_1arg Float64 ftcos\n\n\n# ------------------------------------------------------------\n# Reconstruct truncated cosine in Haar basis\n\nusing GeneralizedSampling\n\nJ = 5\nM = 2^(J+2)\n# Both GeneralizedSampling and Plots (below) have a grid function\nxi = GeneralizedSampling.grid(M, 0.5)\nf = ftcos(xi)\n\nT = Freq2Wave(xi, \"haar\", J)\nwcoef = T \\ f\n\n\n# ------------------------------------------------------------\n# Plot reconstruction\n\nusing IntervalWavelets\n\nx, yw = weval( real(wcoef), \"haar\", 10 )\n\nusing Plots\n\np = plot(x, tcos, \n         linecolor=:red,\n         linewidth=2,\n         label=\"true\"\n        )\n\nplot!(p, x, yw, \n      linecolor=:black,\n      linewidth=2,\n      label=\"approximation\"\n     )\n\ndisplay(p)\n\n", "meta": {"hexsha": "f4da1c637f4aaf0240cd68357622e9c7783f3551", "size": 1110, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/truncated_cosine.jl", "max_stars_repo_name": "JuliaTagBot/GeneralizedSampling.jl", "max_stars_repo_head_hexsha": "e59303fd4c2a0250149d61c7956d5eb73407cdb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-07-20T22:01:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-19T12:43:03.000Z", "max_issues_repo_path": "examples/truncated_cosine.jl", "max_issues_repo_name": "JuliaTagBot/GeneralizedSampling.jl", "max_issues_repo_head_hexsha": "e59303fd4c2a0250149d61c7956d5eb73407cdb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-17T00:43:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:31:40.000Z", "max_forks_repo_path": "examples/truncated_cosine.jl", "max_forks_repo_name": "JuliaTagBot/GeneralizedSampling.jl", "max_forks_repo_head_hexsha": "e59303fd4c2a0250149d61c7956d5eb73407cdb1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-03-29T03:11:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:46:59.000Z", "avg_line_length": 17.34375, "max_line_length": 65, "alphanum_fraction": 0.5189189189, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7720559631886941}}
{"text": "using DifferentialEquations\n\nfunction sirmodel(du, u, p, t)\n    S = u[1]\n    I = u[2]\n    R = u[3]\n    dS = -p[1]*S*I\n    dI = p[1]*S*I-p[2]*I\n    dR = p[2]*I\n    du[1] = dS\n    du[2] = dI\n    du[3] = dR\nend\n\nfunction solveSIR(N, β, γ)\n\n    tspan = (0.0, 160.0)\n    u0 = [N-1.0, 1.0, 0.0]\n    p = [β, γ]\n\n    prob = ODEProblem(sirmodel, u0, tspan, p)\n\n    sol = solve(prob)\n\n    return sol\nend\n\nfunction calcEffectiveReproduction(sol)\n\n    v = Array{Float64,1}()\n    t = Array{Float64,1}()\n    for index in 2:length(sol)\n        push!(v, sol[index][2]/sol[index-1][2])\n        push!(t, sol.t[index])\n    end\n\n    return [v,t]\nend\n", "meta": {"hexsha": "c99852a7dab89301ebcd6ccf33ae984f74a1785f", "size": 630, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "epidemic_model/sir_model/sir_ode/sirmodel.jl", "max_stars_repo_name": "seisyuu-hantatsushi/julia", "max_stars_repo_head_hexsha": "5c03715836c5e1c3e8246684d0290455b34dc04f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "epidemic_model/sir_model/sir_ode/sirmodel.jl", "max_issues_repo_name": "seisyuu-hantatsushi/julia", "max_issues_repo_head_hexsha": "5c03715836c5e1c3e8246684d0290455b34dc04f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "epidemic_model/sir_model/sir_ode/sirmodel.jl", "max_forks_repo_name": "seisyuu-hantatsushi/julia", "max_forks_repo_head_hexsha": "5c03715836c5e1c3e8246684d0290455b34dc04f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.1538461538, "max_line_length": 47, "alphanum_fraction": 0.5174603175, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296944, "lm_q2_score": 0.8104789109591831, "lm_q1q2_score": 0.7720412387325325}}
{"text": "function jaccard_similarity(set1::Array, set2::Array)\n\n    intersec = 0.0\n    set1 = unique(set1)\n    set2 = unique(set2)\n\n    for i in set1\n        for j in set2\n            if i == j\n                intersec += 1.0\n            end\n        end\n    end\n    return intersec / (length(set1) + length(set2) - intersec)\nend\n", "meta": {"hexsha": "084534b6818c0dcaefff6060e07b34f0f3108059", "size": 320, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/JaccardSimilarity.jl", "max_stars_repo_name": "eRRe-i/MyDistanceSimilarityPKG.jl", "max_stars_repo_head_hexsha": "9c45e2da36eedcd2f230e5a2bdd4262ca18ed5f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/JaccardSimilarity.jl", "max_issues_repo_name": "eRRe-i/MyDistanceSimilarityPKG.jl", "max_issues_repo_head_hexsha": "9c45e2da36eedcd2f230e5a2bdd4262ca18ed5f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/JaccardSimilarity.jl", "max_forks_repo_name": "eRRe-i/MyDistanceSimilarityPKG.jl", "max_forks_repo_head_hexsha": "9c45e2da36eedcd2f230e5a2bdd4262ca18ed5f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0, "max_line_length": 62, "alphanum_fraction": 0.53125, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.952574129515172, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.77204123437611}}
{"text": "\"\"\"\nElliptic Curve\n==============\n\nReferences\n----------\n\n- https://en.wikipedia.org/wiki/Elliptic_curve\n- \"An Introduction to the Theory of Elliptic Curves\", Joseph H. Silverman\n- https://andrea.corbellini.name/2015/05/17/elliptic-curve-cryptography-a-gentle-introduction/\n\"\"\"\nmodule EllipticCurveCrypto\n\ninclude(\"field.jl\")\n\nexport\n    Point, EllipticCurve, is_on_curve,\n    ec_zero, ec_add, ec_neg, ec_scalar_mul, ec_scalar_mul_ml\n\nstruct Point{T}\n    x::T\n    y::T\nend\n\n# `T` might be mutable (e.g. `BigInt`) and compare using object identity by default.\nfunction Base.:(==)(a::Point{T}, b::Point{T}) where T\n    a.x == b.x && a.y == b.y\nend\n\nfunction Base.:(≈)(a::Point{T}, b::Point{T}) where T\n    a.x ≈ b.x && a.y ≈ b.y\nend\n\n\"\"\"\nElliptic curve (with characteristic >= 5) `y ^ 2 = x ^ 3 + a * x + b`.\n\"\"\"\nstruct EllipticCurve{T}\n    field::Field{T}\n\n    a::T\n    b::T\n\n    function EllipticCurve(f::F, a::T, b::T) where {T, F<:Field{T}}\n        a = f_from(f, a)\n        b = f_from(f, b)\n        if f_add(f,\n            f_mul(f, f_pow(f, a, 3), f_from(f, T(4))),\n            f_mul(f, f_pow(f, b, 2), f_from(f, T(27)))) == f_zero(f)\n            error(\"The curve is singular\")\n        end\n        new{T}(f, a, b)\n    end\nend\n\nfunction is_on_curve(ec::EllipticCurve{T}, p::Point{T})::Bool where T\n    if p == ec_zero(ec)\n        return true\n    end\n\n    f = ec.field\n    a = ec.a\n    b = ec.b\n    x = p.x\n    y = p.y\n    lhs = f_pow(f, y, 2)\n    rhs = f_add(f,\n        f_add(f, f_pow(f, x, 3), f_mul(f, x, a)),\n        b)\n    lhs == rhs\nend\n\n# Zero, also the infinity.\nfunction ec_zero(ec::EllipticCurve{T})::Point{T} where T\n    z = f_zero(ec.field)\n    Point(z, z)\nend\n\nfunction ec_add(ec::EllipticCurve{T}, p1::Point{T}, p2::Point{T})::Point{T} where T\n    f = ec.field\n    z = ec_zero(ec)\n\n    s = if p1 == z\n        return p2\n    elseif p2 == z\n        return p1\n    elseif p1.x == p2.x\n        if f_add(f, p1.y, p2.y) == f_zero(f)\n            return z\n        else\n            # Doubling\n            (x, y) = (p1.x, p1.y)\n            numer = f_add(f, f_mul(f, f_from(f, T(3)), f_pow(f, x, 2)), ec.a)\n            denom = f_mul(f, f_from(f, T(2)), y)\n            f_div(f, numer, denom)\n        end\n    else\n        f_div(f, f_sub(f, p2.y, p1.y), f_sub(f, p2.x, p1.x))\n    end\n\n    x = f_sub(f, f_mul(f, s, s), f_add(f, p1.x, p2.x))\n    y = f_sub(f, f_mul(f, s, f_sub(f, p1.x, x)), p1.y)\n    Point(x, y)\nend\n\nfunction ec_neg(ec::EllipticCurve{T}, p::Point{T})::Point{T} where T\n    Point(p.x, f_neg(ec.field, p.y))\nend\n\n# Double-and-add algorithm\nfunction ec_scalar_mul(ec::EllipticCurve{T}, p::Point{T}, s::Int)::Point{T} where T\n    acc = ec_zero(ec)\n    while s != 0\n        if s & 1 != 0\n            acc = ec_add(ec, acc, p)\n        end\n        p = ec_add(ec, p, p)\n        s >>= 1\n    end\n    acc\nend\n\n# Side-channel attack resistent multiplication.\n\"Point multiplication using Montgomery ladder.\"\nfunction ec_scalar_mul_ml(ec::EllipticCurve{T}, p::Point{T}, s::Int)::Point{T} where T\n    # p * d = \\sum_{i = 0..m} p * (d_i 2^i)          ...0-based\n    #       = \\sum_{i = 1..m} p * (d_i 2^(i - 1))    ...1-based\n    d = digits(s, base=2)\n    m = length(d)\n\n    # Invariants:\n    #\n    #     r0 = p * t0 = p * (s >> (i - 1))\n    #     r1 = p * t1 = p * (t0 + 1)\n    r0 = ec_zero(ec)\n    r1 = p\n    for i in m:-1:1\n        if d[i] == 0\n            r1 = ec_add(ec, r0, r1)  # t0 + (t0 + 1) => (2 * t0) + 1\n            r0 = ec_add(ec, r0, r0)  # 2 * t0\n        else\n            r0 = ec_add(ec, r0, r1)  # t0 + (t0 + 1) => 2 * t0 + 1\n            r1 = ec_add(ec, r1, r1)  # 2 * (t0 + 1) => (2 * t0 + 1) + 1\n        end\n    end\n    r0\nend\n\nend # module\n", "meta": {"hexsha": "c7d4f4d1313a1e341a3b0e66167f21a96e4f4f05", "size": 3657, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "EllipticCurve/src/EllipticCurveCrypto.jl", "max_stars_repo_name": "gyk/TrivialSolutions", "max_stars_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T05:51:37.000Z", "max_issues_repo_path": "EllipticCurve/src/EllipticCurveCrypto.jl", "max_issues_repo_name": "gyk/TrivialSolutions", "max_issues_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EllipticCurve/src/EllipticCurveCrypto.jl", "max_forks_repo_name": "gyk/TrivialSolutions", "max_forks_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5436241611, "max_line_length": 94, "alphanum_fraction": 0.5157232704, "num_tokens": 1345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296944, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7720412343719135}}
{"text": "function tensorproduct(x::Array{Float64,2},porder::Int)::Tuple{Array{Float64,2},Array{Float64,2},Array{Float64,2},Array{Float64,2}}\n# #TENSORPRODUCT Vandermonde matrices for tensor product polynomials in [0,1]^d\n# #\n# #   [F,FX,FY,FZ] = TENSORPRODUCT(X,P)\n# #\n# #      X:         Coordinates of the points wherethe polynomials\n# #                 are to be evaluated (npoints,dim)\n# #      PORDER:    Maximum order of the polynomials consider. That\n# #                 is all polynomials of complete degree up to p,\n# #                 npoly = (PORDER+1)*(PORDER+1)*(PORDER+1)\n# #      F:         Vandermonde matrix (npoints,npoly)\n# #      FX:        Vandermonde matrix for the derivative of the Koornwinder\n# #                 polynomials w.r.t. x (npoints,npoly)\n# #      FY:        Vandermonde matrix for the derivative of the Koornwinder\n# #                 polynomials w.r.t. y (npoints,npoly)\n# #      FZ:        Vandermonde matrix for the derivative of the Koornwinder\n# #                 polynomials w.r.t. z (npoints,npoly)\n# #\n\nn,dim = size(x);\n\n\nif dim== 1 # 1D\n        f,fx = legendrepolynomial(x,porder);  # Legendre basis\n        fy=[0.0 0.0];\n        fz=[0.0 0.0];\nelseif dim == 2 # 2D\n        g1,gx = legendrepolynomial(x[:,1],porder); # Legendre basis in x direction\n        g2,gy = legendrepolynomial(x[:,2],porder); # Legendre basis in y direction\n        f  = zeros(Float64,n,(porder+1)*(porder+1));\n        fx = 0*f;\n        fy = 0*f;\n        fz=[0.0 0.0];\n        # perform tensor product to obtain the shape functions and their\n        # derivatives on the unit square\n        for ii=1:n\n            tm = kron(g2[ii,:],g1[ii,:]);\n            f[ii,:] =  kron(g2[ii,:],g1[ii,:]);\n            fx[ii,:] = kron(g2[ii,:],gx[ii,:]);\n            fy[ii,:] = kron(gy[ii,:],g1[ii,:]);\n        end\nelseif dim==3\n        g1,gx=legendrepolynomial(x[:,1],porder); # Legendre basis in x direction\n        g2,gy=legendrepolynomial(x[:,2],porder); # Legendre basis in y direction\n        g3,gz=legendrepolynomial(x[:,3],porder); # Legendre basis in z direction\n        f  = zeros(Float64,n,(porder+1)*(porder+1)*(porder+1));\n        fx = 0*f;\n        fy = 0*f;\n        fz = 0*f;\n        # perform tensor product to obtain the shape functions and their\n        # derivatives on the unit cube\n        for ii=1:n\n            f[ii,:] =  kron(g3[ii,:],kron(g2[ii,:],g1[ii,:]));\n            fx[ii,:] = kron(g3[ii,:],kron(g2[ii,:],gx[ii,:]));\n            fy[ii,:] = kron(g3[ii,:],kron(gy[ii,:],g1[ii,:]));\n            fz[ii,:] = kron(gz[ii,:],kron(g2[ii,:],g1[ii,:]));\n        end\nelse\n        error(\"Only can handle dim=1, dim=2 or dim=3\");\nend\n\nreturn f, fx, fy, fz;\n\nend\n", "meta": {"hexsha": "6374ec01d2f62b36c59080e8a6dafd3809fea132", "size": 2673, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Version0.2/Julia/Preprocessing/tensorproduct.jl", "max_stars_repo_name": "glwagner/Exasim", "max_stars_repo_head_hexsha": "ee4540443435f958fa2ca78d59cbf9cff0fe69de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2020-12-09T20:24:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T17:19:23.000Z", "max_issues_repo_path": "Version0.2/Julia/Preprocessing/tensorproduct.jl", "max_issues_repo_name": "glwagner/Exasim", "max_issues_repo_head_hexsha": "ee4540443435f958fa2ca78d59cbf9cff0fe69de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2020-11-25T20:37:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T15:53:11.000Z", "max_forks_repo_path": "Version0.2/Julia/Preprocessing/tensorproduct.jl", "max_forks_repo_name": "glwagner/Exasim", "max_forks_repo_head_hexsha": "ee4540443435f958fa2ca78d59cbf9cff0fe69de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-11-30T15:34:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T21:06:00.000Z", "avg_line_length": 41.1230769231, "max_line_length": 131, "alphanum_fraction": 0.5503179948, "num_tokens": 835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191348157373, "lm_q2_score": 0.8080672135527631, "lm_q1q2_score": 0.7719620713241893}}
{"text": "include(\"getdigit_n.jl\")\ninclude(\"myprintf.jl\")\nusing Printf\nusing .GetDigit_n\nusing .MyPrintf\n\nconst DIGIT = 100\nconst MAXN = 100\n\nfunction factorial(m)\n    return m < 2 ? BigFloat(1) : reduce(*, [BigFloat(i) for i in 2:m])\nend\n\nfunction ramanujan(n)\n    res = BigFloat(0)\n    for k = 0:n\n        numerator = factorial(4 * k) * (BigFloat(1103) + BigFloat(26390 * k))\n        denominator = (factorial(k) * (BigFloat(396))^(BigFloat(k)))^(BigFloat(4))\n\n        res += numerator / denominator\n    end\n\n    return BigFloat(9801) / (res * BigFloat(2) * sqrt(BigFloat(2)))\nend\n\nfunction main()\n    n = GetDigit_n.getn(ramanujan, MAXN, DIGIT, true)\n    precision = GetDigit_n.getdigit(ramanujan, n, DIGIT, true)\n    precision = GetDigit_n.getdigit_2(ramanujan, n, DIGIT, precision)\n\n    setprecision(precision)\n    MyPrintf.myprintf(\"π（計算値） = \", DIGIT, ramanujan(n))\n    MyPrintf.myprintf(\"π（厳密値） = \", DIGIT, BigFloat(π))\n    @printf(\"n = %d, 計算%d桁で、%d桁求まりました\\n\", n, precision, DIGIT)\nend\n\nmain()", "meta": {"hexsha": "b23da4cbd134567eb7b7e08da1f64a46afca2e46", "size": 990, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ramanujan.jl", "max_stars_repo_name": "dc1394/pi_julia", "max_stars_repo_head_hexsha": "a097705dab169aea82b8639638fded92cef32bbe", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ramanujan.jl", "max_issues_repo_name": "dc1394/pi_julia", "max_issues_repo_head_hexsha": "a097705dab169aea82b8639638fded92cef32bbe", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ramanujan.jl", "max_forks_repo_name": "dc1394/pi_julia", "max_forks_repo_head_hexsha": "a097705dab169aea82b8639638fded92cef32bbe", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7567567568, "max_line_length": 82, "alphanum_fraction": 0.6535353535, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191259110589, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7719620685442667}}
{"text": "export ScaledBeta, TrGeometric, TrBinomial, StringCategorical, likelihood, log_likelihood\nexport normalising_const\n## Scaled beta distribution\n\"\"\"\nScaled Beta distribution. Instantiate with ScaledBeta() e.g.\n```\nd = ScaledBeta(α, β, 0.0, 10.0)\n```\nwould make a ScaledBeta type d which is bounded by 0.0 and 10.0. Note\n- (α,β) are usual parameters;\n- lb = lower bound;\n- ub = upper bound.\n\"\"\"\nstruct ScaledBeta<:ContinuousUnivariateDistribution\n    α::Float64\n    β::Float64\n    lb::Float64\n    ub::Float64\nend\n\nDistributions.rand(d::ScaledBeta) = d.lb + (d.ub-d.lb) * rand(Beta(d.α, d.β))\nDistributions.mean(d::ScaledBeta) = d.lb + (d.ub-d.lb) * ( d.α / (d.α + d.β) )\nDistributions.pdf(d::ScaledBeta, x::Real) = (d.lb ≤ x ≤ d.ub) ? pdf(Beta(d.α, d.β), (x - d.lb)/(d.ub-d.lb))/(d.ub-d.lb) : 0\nDistributions.minimum(d::ScaledBeta) = d.lb\nDistributions.maximum(d::ScaledBeta) = d.ub\n\n## Trucated geometric\n\"\"\"\n`TrGeomtric(p::Float64, lb::Int, ub::Int)` \n\nTruncated Geometric distribution. Note:\n- lb = lower bound = samllest possible value (default=0)\n- ub = upper bound = largest possible value.\nInstantiation:\n\n1. `TrGeometric(p, ub)` -  here `lb` defaults to 0\n2. `TrGeometric(p, lb, ub)` here `lb` is specified\n\n\"\"\"\nstruct TrGeometric<:DiscreteUnivariateDistribution\n    p::Float64 # Prob param\n    lb::Int # Lower bound (smallest value)\n    ub::Int  # Upper bound\nend\n\nfunction normalising_const(d::TrGeometric)\n    return (1 - (1-d.p)^(d.ub-d.lb+1))\nend \n\nTrGeometric(p::Float64, ub::Int) = TrGeometric(p, 0, ub)\n\nfunction Distributions.pdf(d::TrGeometric, x::Integer)\n    _insupport = insupport(d, x)\n    return _insupport ? d.p*(1-d.p)^(x-d.lb) / normalising_const(d) : 0.0\nend\n\nfunction Distributions.logpdf(d::TrGeometric, x::Integer)\n    _insupport = insupport(d, x)\n    return _insupport ? log(d.p) + (x-d.lb) * log(1-d.p) -  log(normalising_const(d)) : -Inf\nend\n\nfunction Distributions.cdf(d::TrGeometric, x::Number)\n    if d.lb ≤ x ≤ d.ub\n        return ( 1 - (1 - d.p)^(trunc(Int,x)-d.lb+1) )/normalising_const(d)\n    else\n        return float(x > d.ub)\n    end\nend\n\n# Here I make use of closed form of generalised inverse of the TrGeom dist.\n# Not sure if this is the fastest implementation\nfunction Distributions.quantile(d::TrGeometric, q::Real)\n    return 0.0<q<1.0 ? ceil(Int, log(1-q*normalising_const(d))/log(1-d.p) - 1 )+d.lb : d.ub*(p≥1.0) + d.lb*(q≤0.0)\nend\n\nDistributions.minimum(d::TrGeometric) = d.lb\nDistributions.maximum(d::TrGeometric) = d.ub\n\n#Truncated Binomial wrappper - solves the problem of when we have n=0\n\nstruct TrBinomial <: DiscreteUnivariateDistribution\n    n::Int\n    p::Real\n    lb::Int\n    ub::Int\n    dist::Distribution\n    function TrBinomial(n::Int, p::Real, lb::Int, ub::Int)\n        @assert (lb ≤ ub) \"Lower bound must be ≤ upper bound.\"\n        if lb < ub \n            tmp_dist = Truncated(Binomial(n, p), lb, ub)\n        else \n            tmp_dist = DiscreteUniform(lb, ub)\n        end \n        new(n, p, lb, ub, tmp_dist)\n    end\nend \n\nfunction Distributions.rand(d::TrBinomial)\n    return rand(d.dist)\nend\nfunction Distributions.rand(d::TrBinomial, n::Int)\n    return rand(d.dist, n)\nend \n\n\nstruct StringCategorical <: DiscreteUnivariateDistribution\n    x::Vector{String}\n    p::Vector{T} where T<:Real\n    latent_dist::Distribution\n    probability_map::Dict{String, Float64}\n    function StringCategorical(x::Vector{String}, p::Vector{T} where T<: Real)\n        latent_dist = Categorical(p)\n        probability_map = Dict(val => prob for (val, prob) in zip(x, p))\n        new(x, p, latent_dist, probability_map)\n    end \nend \n\nDistributions.pdf(d::StringCategorical, val::String) = d.probability_map[val]\nfunction likelihood(d::StringCategorical, val::Vector{String})\n    z = 1.0\n    for s in val\n        z *= pdf(d, s)\n    end \n    return z\nend \n\nDistributions.logpdf(d::StringCategorical, val::String) = log(d.probability_map[val])\nfunction log_likelihood(d::StringCategorical, val::Vector{String})\n    z = 0.0\n    for s in val\n        z += logpdf(d, s)\n    end \n    return z\nend \n\n\nfunction Distributions.rand(d::StringCategorical)\n    return d.x[rand(d.latent_dist)]\nend \n\nfunction Distributions.rand(d::StringCategorical, n::Int)\n    return d.x[rand(d.latent_dist, n)]\nend \n", "meta": {"hexsha": "50911554312d93b55501128a740af806071d5962", "size": 4233, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Types/distributions.jl", "max_stars_repo_name": "gmbolt/InteractionNetworkModels.jl", "max_stars_repo_head_hexsha": "bdea22adf934ca60185e68ca47d7396fb1069f94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Types/distributions.jl", "max_issues_repo_name": "gmbolt/InteractionNetworkModels.jl", "max_issues_repo_head_hexsha": "bdea22adf934ca60185e68ca47d7396fb1069f94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Types/distributions.jl", "max_forks_repo_name": "gmbolt/InteractionNetworkModels.jl", "max_forks_repo_head_hexsha": "bdea22adf934ca60185e68ca47d7396fb1069f94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3958333333, "max_line_length": 123, "alphanum_fraction": 0.6692652965, "num_tokens": 1324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191271831558, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7719620563252383}}
{"text": "using SymPy\n\n@syms px1 py1 lambda1 vx1 vy1 px2 py2 lambda2 vx2 vy2\n\nlx1 = px1 + lambda1*vx1\nly1 = py1 + lambda1*vy1\n\nlx2 = px2 + lambda2*vx2\nly2 = py2 + lambda2*vy2\n\nlx12 = solve(lx1-lx2, lambda2)[1]\nl2i = subs(ly2, lambda2, lx12)\n\nsol = solve(ly1-l2i, lambda1)[1]\n\nxi = simplify(subs(lx1, lambda1, sol))\nyi = simplify(subs(ly1, lambda1, sol))\n", "meta": {"hexsha": "32a21f9720cffb74321e33f9018a8aa357678d23", "size": 344, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/symbolics/LinesIntersection.jl", "max_stars_repo_name": "control13/SearchBall.jl", "max_stars_repo_head_hexsha": "622a69b264e4e22717a023d849cdd6ad155e342d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/symbolics/LinesIntersection.jl", "max_issues_repo_name": "control13/SearchBall.jl", "max_issues_repo_head_hexsha": "622a69b264e4e22717a023d849cdd6ad155e342d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/symbolics/LinesIntersection.jl", "max_forks_repo_name": "control13/SearchBall.jl", "max_forks_repo_head_hexsha": "622a69b264e4e22717a023d849cdd6ad155e342d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1111111111, "max_line_length": 53, "alphanum_fraction": 0.6860465116, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7719551959814055}}
{"text": "abstract type PrimeField <: Number end\n\ninfield(x::Number,y::Number) = x >= 0 && x < y\n\n\"Represents FieldElement type in which 𝑛 ∈ 𝐹𝑝 and 𝑝 ∈ ℙ\"\nstruct FieldElement <: PrimeField\n    𝑛::Integer\n    𝑝::Integer\n    FieldElement(𝑛,𝑝) = !infield(𝑛,𝑝) ? throw(DomainError(\"𝑛 is not in field range\")) : new(𝑛,𝑝)\nend\n\n\"Formats PrimeField as 𝑛 : 𝐹ₚ\"\nfunction show(io::IO, z::PrimeField)\n    print(io, z.𝑛, \" : 𝐹\", z.𝑝)\nend\n\n\"Returns true if both 𝑛 and 𝑝 are the same\"\n==(𝑋₁::PrimeField,𝑋₂::PrimeField) = 𝑋₁.𝑝 == 𝑋₂.𝑝 && 𝑋₁.𝑛 == 𝑋₂.𝑛\n==(::PrimeField,::Integer) = false\n\n\n\"Adds two numbers of the same field\"\nfunction +(𝑋₁::PrimeField,𝑋₂::PrimeField)\n    if 𝑋₁.𝑝 != 𝑋₂.𝑝\n        throw(DomainError(\"Cannot operate on two numbers in different Fields\"))\n    else\n        𝑛 = mod(𝑋₁.𝑛 + 𝑋₂.𝑛, 𝑋₁.𝑝)\n        return typeof(𝑋₁)(𝑛, 𝑋₁.𝑝)\n    end\nend\n\n\"Substracts two numbers of the same field\"\nfunction -(𝑋₁::PrimeField,𝑋₂::PrimeField)\n    if 𝑋₁.𝑝 != 𝑋₂.𝑝\n        throw(DomainError(\"Cannot operate on two numbers in different Fields\"))\n    else\n        𝑛 = mod(𝑋₁.𝑛 - 𝑋₂.𝑛, 𝑋₁.𝑝)\n        return typeof(𝑋₁)(𝑛, 𝑋₁.𝑝)\n    end\nend\n\n\"Multiplies two numbers of the same field\"\nfunction *(𝑋₁::PrimeField,𝑋₂::PrimeField)\n    if 𝑋₁.𝑝 != 𝑋₂.𝑝\n        throw(DomainError(\"Cannot operate on two numbers in different Fields\"))\n    else\n        𝑛 = mod(𝑋₁.𝑛 * 𝑋₂.𝑛, 𝑋₁.𝑝)\n        return typeof(𝑋₁)(𝑛, 𝑋₁.𝑝)\n    end\nend\n\n\"Multiplies a PrimeField by an Integer\"\nfunction *(𝑐::Integer,𝑋::PrimeField)\n    𝑛 = mod(𝑐 * 𝑋.𝑛, 𝑋.𝑝)\n    return typeof(𝑋)(𝑛, 𝑋.𝑝)\nend\n\n\"Returns 𝑋ᵏ using Fermat's Little Theorem\"\nfunction ^(𝑋::PrimeField,𝑘::Int)\n    𝑛 = powermod(𝑋.𝑛, mod(𝑘, (𝑋.𝑝 - 1)), 𝑋.𝑝)\n    return typeof(𝑋)(𝑛, 𝑋.𝑝)\nend\n\n\"Returns 1/𝑋 as a special case of exponentiation where 𝑘 = -1\"\nfunction inv(𝑋::PrimeField)\n    𝑛 = powermod(𝑋.𝑛, mod(-1, (𝑋.𝑝 - 1)), 𝑋.𝑝)\n    return typeof(𝑋)(𝑛, 𝑋.𝑝)\nend\n\nfunction div(𝑋₁::PrimeField,𝑋₂::PrimeField)\n    return 𝑋₁ / 𝑋₂\nend\n\n\"Returns 𝑋₁/𝑋₂ using Fermat's Little Theorem\"\nfunction /(𝑋₁::PrimeField,𝑋₂::PrimeField)\n    if 𝑋₁.𝑝 != 𝑋₂.𝑝\n        throw(DomainError(\"Cannot operate on two numbers in different Fields\"))\n    else\n        𝑛 = mod(𝑋₁.𝑛 * powermod(𝑋₂.𝑛, 𝑋₁.𝑝 - 2, 𝑋₁.𝑝), 𝑋₁.𝑝)\n        return typeof(𝑋₁)(𝑛, 𝑋₁.𝑝)\n    end\nend\n", "meta": {"hexsha": "83f648a9fe70e70f0f43017a5128f90684292f25", "size": 2225, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/primefield.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ECC.jl-a99b485a-c5c8-540e-ab00-7a7265134077", "max_stars_repo_head_hexsha": "2ea9cdfea2f773317c432e5eb2771f2c4990f6b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/primefield.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ECC.jl-a99b485a-c5c8-540e-ab00-7a7265134077", "max_issues_repo_head_hexsha": "2ea9cdfea2f773317c432e5eb2771f2c4990f6b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-11-30T17:15:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T17:22:14.000Z", "max_forks_repo_path": "src/primefield.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ECC.jl-a99b485a-c5c8-540e-ab00-7a7265134077", "max_forks_repo_head_hexsha": "2ea9cdfea2f773317c432e5eb2771f2c4990f6b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-07-11T18:59:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:52:38.000Z", "avg_line_length": 26.8072289157, "max_line_length": 96, "alphanum_fraction": 0.6296629213, "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693617046216, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7719551782709856}}
{"text": "# p28b.jl - eigenmodes of Laplacian on the disk\n\n# r coordinate, ranging from -1 to 1 (N must be odd)\nN = 25; N2 = Int((N-1)/2);\n(D,r) = cheb(N); D2 = D^2;\nD1 = D2[2:N2+1,2:N2+1]; D2 = D2[2:N2+1,N:-1:N2+2];\nE1 =  D[2:N2+1,2:N2+1]; E2 =  D[2:N2+1,N:-1:N2+2];\n\n# t = theta coordinate, ranging from 0 to 2*pi (M must be even):\nM = 20; dt = 2*pi/M; t = dt*(1:M); M2 = Int(M/2);\nD2t = toeplitz([-pi^2/(3*dt^2)-1/6; @. .5*(-1)^(2:M)/sin(dt*(1:M-1)/2)^2]);\n\n# Laplacian in polar coordinates:\nR = diagm(1./r[2:N2+1]);\nZ = zeros(M2,M2); I = eye(M2);\nL = kron(D1+R*E1,eye(M)) + kron(D2+R*E2,[Z I;I Z]) + kron(R^2,D2t);\n\n# Compute 25 eigenmodes:\nindex = 1:25;\n(Lam,V) = eig(-L); ii = sortperm(abs.(Lam))[index];\nLam = Lam[ii]; V = V[:,ii];\nLam = sqrt.(real(Lam/Lam[1]));\n\n# Plot nodal lines:\n(rr,tt) = (r[1:N2+1],[0;t]);\n(xx,yy) = @. (cos(tt)*rr',sin(tt)*rr');\nz = exp.(1im*pi*(-100:100)/100);  clf();\nfor i = 1:25\n    subplot(5,5,i);\n    u = reshape(real(V[:,i]),M,N2);\n    u = [zeros(M+1) u[[M;1:M],:]];\n    u = u/norm(u[:],Inf);\n    plot(real(z),imag(z));\n    xlim(-1.07,1.07); ylim(-1.07,1.07); axis(\"off\"); axis(\"equal\");\n    contour(xx,yy,u,levels=[0]);\n    title(\"$(signif(Lam[i],5))\",fontsize=8);\nend\n", "meta": {"hexsha": "c92f970bbd957839b58ca33bba10eda2af1a3d2e", "size": 1198, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p28b.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p28b.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p28b.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5263157895, "max_line_length": 75, "alphanum_fraction": 0.5300500835, "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238083, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7719349066461173}}
{"text": "#=\nStarting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.\n\n37 36 35 34 33 32 31\n38 17 16 15 14 13 30\n39 18  5  4  3 12 29\n40 19  6  1  2 11 28\n41 20  7  8  9 10 27\n42 21 22 23 24 25 26\n43 44 45 46 47 48 49\n\nIt is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.\n\nIf one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?\n=#\nusing Primes\n\nfunction calc()\n  start, step = 1,2\n  iterations, currentsquaresize = 3,3\n  cprimes, call = 0,1\n  while true\n    start += step\n    for i in start:step:(start+(iterations*step))\n      if isprime(i)\n        cprimes = cprimes + 1\n      end\n      call = call + 1\n    end\n    ratio = cprimes / call\n    if ratio < 0.1\n      return currentsquaresize\n    end\n    start += (iterations*step)\n    currentsquaresize += 2\n    step += 2\n  end\nend\n@time println(calc())\n", "meta": {"hexsha": "bd47d8a122e5b41ee0f12fd3b1082f6161efb4f2", "size": 1216, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p58.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p58.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p58.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 30.4, "max_line_length": 261, "alphanum_fraction": 0.6891447368, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7719313374573661}}
{"text": "\n\"\"\"\n    sphericalhankel2(nu, x)\n\nSpherical Hankel function of the second kind, order `nu`\nand argument `x`.\n\"\"\"\nfunction sphericalhankel2(nu, x)\n    jn = SpecialFunctions.sphericalbesselj(nu, x)\n    yn = SpecialFunctions.sphericalbessely(nu, x)\n    return jn - im*yn\nend\n\n\"\"\"\n    sphericalhankel1(nu, x)\n\nSpherical Hankel function of the first kind, order `nu`\nand argument `x`.\n\"\"\"\nfunction sphericalhankel1(nu, x)\n    return conj(sphericalhankel2(nu, x))\nend\n\n\"\"\"\n    sphericalhankel2_and_derivatives(nu::UnitRange, x)\n    sphericalhankel2_and_derivatives(nu::Number, x)\n\nEvaluates the spherical Hankel function of the second kind, its first and \nsecond derivative, for orders `nu::UnitRange` and argument `x`.\n\"\"\"\nfunction sphericalhankel2_and_derivatives(nu::UnitRange, x)\n    start = nu.start\n    stop = nu.stop\n    len = stop-start+1   # number of terms to compute\n    sph = sphericalhankel2.(start:stop+2, x)  # compute two more terms\n    # compute first derivative using recurrence\n    # h_n'(x) = -h_{n+1}(x) + n/x*h_n(z)\n    sph_d = similar(sph, len+1)   # compute one more term\n    n = stop+1   # order\n    for index in len+1:-1:1\n        sph_d[index] = -sph[index+1] + n/x*sph[index]\n        n -= 1\n    end\n    # compute second derivative using recurrence\n    # h_n''(x) = n / x^2 * (x * h_n'(x) - h_n(x)) - h_{n+1}'(x)\n    sph_dd = similar(sph, len)\n    n = stop   # order\n    for index in len:-1:1\n        sph_dd[index] = n / x^2 * (x*sph_d[index] - sph[index]) - sph_d[index+1]\n        n -= 1\n    end\n    return sph[1:len], sph_d[1:len], sph_dd\nend\nfunction sphericalhankel2_and_derivatives(nu::Number, x)\n    sph, sph_d, sph_dd = sphericalhankel2_and_derivatives(nu:nu, x)\n    return first(sph), first(sph_d), first(sph_dd)\nend\n\n\"\"\"\n    sphericalhankel1_and_derivatives(nu::UnitRange, x)\n    sphericalhankel1_and_derivatives(nu::Number, x)\n\nEvaluates the spherical Hankel function of the first kind, its first and \nsecond derivative, for orders `nu` and argument `x`.\n\"\"\"\nfunction sphericalhankel1_and_derivatives(nu, x)\n    return conj.(sphericalhankel2_and_derivatives(nu, x))\nend\n\n\"\"\"\n    riccatihankel2_and_derivatives(nu::UnitRange, x)\n\nEvaluates the spherical Riccati-Bessel Hankel function of the second kind, its first and \nsecond derivative, for orders `nu::UnitRange` and argument `x`.\n\"\"\"\nfunction riccatihankel2_and_derivatives(nu::UnitRange, x)\n    sph, sph_d, sph_dd = sphericalhankel2_and_derivatives(nu, x)\n    rh = x.*sph\n    rh_d = sph + x.*sph_d\n    rh_dd = 2*sph_d + x.*sph_dd\n    return rh, rh_d, rh_dd\nend", "meta": {"hexsha": "3ddb1d1fa2a07bf0019561b80807498d4533633e", "size": 2544, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bessel.jl", "max_stars_repo_name": "Riarrieta/MieSeries", "max_stars_repo_head_hexsha": "35ded72e7f5b43c24f7ddbd3081d9ae2d78a2ed7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bessel.jl", "max_issues_repo_name": "Riarrieta/MieSeries", "max_issues_repo_head_hexsha": "35ded72e7f5b43c24f7ddbd3081d9ae2d78a2ed7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bessel.jl", "max_forks_repo_name": "Riarrieta/MieSeries", "max_forks_repo_head_hexsha": "35ded72e7f5b43c24f7ddbd3081d9ae2d78a2ed7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0243902439, "max_line_length": 89, "alphanum_fraction": 0.6855345912, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850021922959, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7719313345257949}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.4\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local iv = try Base.loaded_modules[Base.PkgId(Base.UUID(\"6e696c72-6542-2067-7265-42206c756150\"), \"AbstractPlutoDingetjes\")].Bonds.initial_value catch; b -> missing; end\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)\n        el\n    end\nend\n\n# ╔═╡ d2e14b19-98d7-4fba-8bd9-bbbb47e002f6\nbegin\n\tbigbreak = HTML(\"<br>\"^4);\n\tusing PlutoUI\n\tusing Test\nend\n\n# ╔═╡ ce3c8fde-802a-11ec-1b1a-31be58ae3474\nmd\"\"\"\n# Conditionals\nwith the if keyword\nIn Julia, the syntax\n\n```julia\nif *condition 1*\n    *option 1*\nelseif *condition 2*\n    *option 2*\nelse\n    *option 3*\nend\n```\nallows us to conditionally evaluate one of our options.\n\nFor example, we might want to implement the FizzBuzz test: \ngiven a number, N, print\n-  \"Fizz\" if N is divisible by 3,\n-  \"Buzz\" if N is divisible by 5, and\n-  \"FizzBuzz\" if N is divisible by 3 and 5.\n\nOtherwise just print the number itself! Enter your choice for N here:\n\"\"\"\n\n# ╔═╡ fd2ee11d-1734-457b-b587-4128b474b772\n@bind N PlutoUI.Slider(1:20, show_value = true)\n\n# ╔═╡ 7b619e85-abb8-4115-a9df-b5fedd04a8e4\nmd\"N = $N\"\n\n# ╔═╡ da9796ce-4572-4d2d-bb96-5949f52d46d0\nwith_terminal() do \n\t\n\tif (N % 3 == 0) && (N % 5 == 0) \n\t\t# `&&` means \"AND\"; % computes the remainder after division\n\t    println(\"FizzBuzz\")\n\telseif N % 3 == 0\n\t    println(\"Fizz\")\n\telseif N % 5 == 0\n\t    println(\"Buzz\")\n\telse\n\t    println(N)\n\tend\n\t\nend\n\n# ╔═╡ aca5d158-2902-4b7a-bf50-6f7a722f5ea7\nmd\"\"\"\nwith ternary operators\nFor this last block, we could instead use the ternary operator with the syntax\n```julia\na ? b : c\n```\nwhich equates to\n```julia\nif a\n    b\nelse\n    c\nend\n```\n\"\"\"\n\n# ╔═╡ 8a3c8101-0c2a-438f-ba58-b80e9b14bc10\nmd\"\nNow let's say we want to return the larger of two numbers. Give x and y values here: \"\n\n# ╔═╡ 5732d2dc-c411-4c56-9720-ce6d979fc60f\nx = 10\n\n# ╔═╡ d993ffa0-c613-4b4b-baeb-a223ce408217\ny = 30\n\n# ╔═╡ 782a5034-9184-4a55-b877-bd0bb4e4aebb\nmd\"Using the if and else keywords, we might write:\n\"\n\n# ╔═╡ 14d69119-9a68-428b-a857-56298b42aee5\nif x > y\n    x\nelse\n    y\nend\n\n# ╔═╡ 46533172-0fe1-406b-a52d-23305282d43b\nmd\"and as a ternary operator, the conditional looks like this:\"\n\n# ╔═╡ b13c9cc4-3c4e-4416-896f-d5cbdc2d51c0\n(x > y) ? x : y\n\n# ╔═╡ 8b81523f-79dc-46ba-8e4e-5dbc19d5d434\ntrue ? 5 : 2 * 6\n\n# ╔═╡ 7925dfa8-63b1-4fc2-beae-922fa93aa081\n( false  ?  1  : 2 )\n\n# ╔═╡ fdfb1f2e-6105-43dd-92cf-4b78e1db8e73\nbigbreak\n\n# ╔═╡ 61aa9056-ebfe-4c06-a752-d081ece68167\nmd\"\"\"\n## Exercises\n\n5.1\n\nWrite a conditional statement that prints \"negative\", \"zero\" or \"odd\" according to the input number `N`.\n\n\"\"\"\n\n# ╔═╡ 75efd803-be55-4d0f-b8c8-6b63dd90d68c\nmd\"\"\"M = $(@bind M PlutoUI.Slider(-100:100, show_value = true)) \"\"\"\n\n# ╔═╡ 8f1298ab-309f-4d4d-8165-4ee522f3b1c8\nwith_terminal() do \n\t# modify this cell to return \"negative\", \"zero\" and \"positive\".\n\tprintln(M)\nend\n\n# ╔═╡ 602b3c77-e46e-4592-a787-4aeed77eb059\nbigbreak\n\n# ╔═╡ c7c1ec65-49ed-4ae9-b9a9-0d82a346af81\nmd\"\"\"\n5.2 \n\nUse the ternary operator to construct a reasonable answer from Bob in the dialog below.\n\"\"\"\n\n# ╔═╡ 283c45af-47a3-4446-b873-205d8aa568e7\nmd\"\"\"\n**Alice:** _Is the number $M even?_\n \n**Bob:**   _I don't know._\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nTest = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[compat]\nPlutoUI = \"~0.7.32\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\njulia_version = \"1.7.1\"\nmanifest_format = \"2.0\"\n\n[[deps.AbstractPlutoDingetjes]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"8eaf9f1b4921132a4cff3f36a1d9ba923b14a481\"\nuuid = \"6e696c72-6542-2067-7265-42206c756150\"\nversion = \"1.1.4\"\n\n[[deps.ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[deps.Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[deps.Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[deps.ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[deps.CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[deps.Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[deps.Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[deps.FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[deps.Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[deps.HypertextLiteral]]\ngit-tree-sha1 = \"2b078b5a615c6c0396c77810d92ee8c6f470d238\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.3\"\n\n[[deps.IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[deps.InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[deps.JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[deps.LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[deps.LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[deps.LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[deps.LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[deps.Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[deps.LinearAlgebra]]\ndeps = [\"Libdl\", \"libblastrampoline_jll\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[deps.Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[deps.Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[deps.MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[deps.Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[deps.MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[deps.NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[deps.OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[deps.Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b5cfbb704034b5b4c1869e36634438a047df065\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.2.1\"\n\n[[deps.Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[deps.PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"ColorTypes\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"ae6145ca68947569058866e443df69587acc1806\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.32\"\n\n[[deps.Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[deps.REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[deps.Random]]\ndeps = [\"SHA\", \"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[deps.Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[deps.SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[deps.Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[deps.Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[deps.SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[deps.Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[deps.TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[deps.Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[deps.Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[deps.UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[deps.Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[deps.Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[deps.libblastrampoline_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"OpenBLAS_jll\"]\nuuid = \"8e850b90-86db-534c-a0d3-1478176c7d93\"\n\n[[deps.nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[deps.p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─d2e14b19-98d7-4fba-8bd9-bbbb47e002f6\n# ╟─ce3c8fde-802a-11ec-1b1a-31be58ae3474\n# ╟─fd2ee11d-1734-457b-b587-4128b474b772\n# ╟─7b619e85-abb8-4115-a9df-b5fedd04a8e4\n# ╠═da9796ce-4572-4d2d-bb96-5949f52d46d0\n# ╟─aca5d158-2902-4b7a-bf50-6f7a722f5ea7\n# ╟─8a3c8101-0c2a-438f-ba58-b80e9b14bc10\n# ╠═5732d2dc-c411-4c56-9720-ce6d979fc60f\n# ╠═d993ffa0-c613-4b4b-baeb-a223ce408217\n# ╟─782a5034-9184-4a55-b877-bd0bb4e4aebb\n# ╠═14d69119-9a68-428b-a857-56298b42aee5\n# ╟─46533172-0fe1-406b-a52d-23305282d43b\n# ╠═b13c9cc4-3c4e-4416-896f-d5cbdc2d51c0\n# ╠═8b81523f-79dc-46ba-8e4e-5dbc19d5d434\n# ╠═7925dfa8-63b1-4fc2-beae-922fa93aa081\n# ╟─fdfb1f2e-6105-43dd-92cf-4b78e1db8e73\n# ╟─61aa9056-ebfe-4c06-a752-d081ece68167\n# ╟─75efd803-be55-4d0f-b8c8-6b63dd90d68c\n# ╠═8f1298ab-309f-4d4d-8165-4ee522f3b1c8\n# ╟─602b3c77-e46e-4592-a787-4aeed77eb059\n# ╟─c7c1ec65-49ed-4ae9-b9a9-0d82a346af81\n# ╠═283c45af-47a3-4446-b873-205d8aa568e7\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "0a76074c53bd8498da67c81f75810fda8a555473", "size": 10361, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "slides/4 - Conditionals.jl", "max_stars_repo_name": "SteffenPL/Julia-for-mathematicians", "max_stars_repo_head_hexsha": "accd6bc8f4e064a1d55ae5f903607778ca84a79a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "slides/4 - Conditionals.jl", "max_issues_repo_name": "SteffenPL/Julia-for-mathematicians", "max_issues_repo_head_hexsha": "accd6bc8f4e064a1d55ae5f903607778ca84a79a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slides/4 - Conditionals.jl", "max_forks_repo_name": "SteffenPL/Julia-for-mathematicians", "max_forks_repo_head_hexsha": "accd6bc8f4e064a1d55ae5f903607778ca84a79a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7736318408, "max_line_length": 196, "alphanum_fraction": 0.7142167744, "num_tokens": 4704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.8902942319436397, "lm_q1q2_score": 0.7719169480760686}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,jl:hydrogen\n#     text_representation:\n#       extension: .jl\n#       format_name: hydrogen\n#       format_version: '1.3'\n#       jupytext_version: 1.11.2\n#   kernelspec:\n#     display_name: Julia 1.7.0-beta3\n#     language: julia\n#     name: julia-1.7\n# ---\n\n# %%\nusing Random, Statistics, Plots\n\nfunction diff!(X)\n    @inbounds for i in reverse(keys(X)[begin:end-1])\n        X[i+1] -= X[i]\n    end\n    X\nend\n\nfunction randsimplex!(rng::AbstractRNG, X)\n    X[end] = one(eltype(X))\n    Y = @view X[begin:end-1]\n    rand!(rng, Y)\n    sort!(Y)\n    X .*= length(X)\n    diff!(X)\nend\nrandsimplex(rng::AbstractRNG, N, T=Float64) = randsimplex!(rng, Vector{T}(undef, N))\nrandsimplex!(X) = randsimplex!(Random.default_rng(), X)\nrandsimplex(N, T=Float64) = randsimplex!(Vector{T}(undef, N))\n\nn = 10^4\nA = randsimplex(n)\n@show mean(A), var(A)\nhistogram(A; norm=true, alpha=0.3, label=\"randsimplex($n)\")\nplot!(x->exp(-x), 0, 6; xlim=(-0.1, 6), lw=2, label=\"Exponential(1) dist\")\n\n# %%\nstruct Simplex{T} N::Int end\nSimplex(N) = Simplex{Float64}(N)\n\nfunction Random.rand!(rng::AbstractRNG,\n        X::AbstractVector{T}, d::Random.SamplerTrivial{Simplex{T}}) where T\n    @assert length(X) == d[].N\n    randsimplex!(rng, X)\nend\nBase.rand(rng::AbstractRNG, d::Random.SamplerTrivial{Simplex{T}}) where T =\n    rand!(rng, Vector{T}(undef, d[].N), d)\n\n# %%\nusing BenchmarkTools\n\nX = zeros(10)\nd = Simplex(10)\n@btime rand!($X, $d)\n\n# %%\nrand(Simplex(10))\n\n# %%\nusing Random, LinearAlgebra, Statistics, Plots\n\nfunction randsphere!(rng::AbstractRNG, X)\n    randn!(X)\n    X .*= √(length(X)) / norm(X)\nend\nrandsphere(rng::AbstractRNG, N, T=Float64) = randsphere!(rng, Vector{T}(undef, N))\nrandsphere!(X) = randsphere!(Random.default_rng(), X)\nrandsphere(N, T=Float64) = randsphere!(Vector{T}(undef, N))\n\nn = 10^4\nA = randsphere(n)\n@show mean(A), var(A)\nhistogram(A; norm=true, alpha=0.3, xlim=(-5, 5), label=\"randsphere($n)\")\nplot!(x->exp(-x^2/2)/√(2π), -5, 5; lw=2, label=\"standard normsl dist\")\n\n# %%\n", "meta": {"hexsha": "8088f292effd9fc65c501063b54f09ae5d7177d7", "size": 2055, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0013/rand of uniform dist on simplex.jl", "max_stars_repo_name": "genkuroki/public", "max_stars_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-06-06T00:33:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T06:56:08.000Z", "max_issues_repo_path": "0013/rand of uniform dist on simplex.jl", "max_issues_repo_name": "genkuroki/public", "max_issues_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0013/rand of uniform dist on simplex.jl", "max_forks_repo_name": "genkuroki/public", "max_forks_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-02T11:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T11:46:05.000Z", "avg_line_length": 24.1764705882, "max_line_length": 84, "alphanum_fraction": 0.6228710462, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8902942246666266, "lm_q1q2_score": 0.7719169295313131}}
{"text": "\nusing OrdinaryDiffEq, ParameterizedFunctions, ODE, ODEInterfaceDiffEq, LSODA,\n      Sundials, DiffEqDevTools\n\nf = @ode_def LotkaVolterra begin\n  dx = a*x - b*x*y\n  dy = -c*y + d*x*y\nend a b c d\n\np = [1.5,1.0,3.0,1.0]\nprob = ODEProblem(f,[1.0;1.0],(0.0,10.0),p)\n\nabstols = 1.0 ./ 10.0 .^ (6:13)\nreltols = 1.0 ./ 10.0 .^ (3:10);\nsol = solve(prob,Vern7(),abstol=1/10^14,reltol=1/10^14)\ntest_sol = TestSolution(sol)\nusing Plots; gr()\n\n\nplot(sol)\n\n\nsetups = [Dict(:alg=>DP5())\n          #Dict(:alg=>ode45()) # fail\n          Dict(:alg=>dopri5())\n          Dict(:alg=>Tsit5())\n          Dict(:alg=>Vern6())\n]\nwp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,maxiters=10000,numruns=100)\nplot(wp)\n\n\nsetups = [Dict(:alg=>DP5())\n          #Dict(:alg=>ode45())\n          Dict(:alg=>Tsit5())\n          Dict(:alg=>Vern6())\n]\nwp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,maxiters=10000,error_estimate=:L2,dense_errors=true,numruns=100)\nplot(wp)\n\n\nsetups = [Dict(:alg=>DP8())\n          #Dict(:alg=>ode78()) # fails\n          Dict(:alg=>Vern7())\n          Dict(:alg=>Vern8())\n          Dict(:alg=>dop853())\n          Dict(:alg=>Vern6())\n]\nwp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,maxiters=1000,numruns=100)\nplot(wp)\n\n\nsetups = [Dict(:alg=>odex())\n          Dict(:alg=>ddeabm())\n          Dict(:alg=>Vern7())\n          Dict(:alg=>Vern8())\n          Dict(:alg=>CVODE_Adams())\n          #Dict(:alg=>lsoda())\n          Dict(:alg=>Vern6())\n          Dict(:alg=>ARKODE(Sundials.Explicit(),order=6))\n          ]\nwp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,maxiters=1000,numruns=100)\nplot(wp)\n\n\nsetups = [Dict(:alg=>DP8())\n          #Dict(:alg=>ode78())\n          Dict(:alg=>Vern7())\n          Dict(:alg=>Vern8())\n          Dict(:alg=>Vern6())\n]\nwp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,dense=true,maxiters=1000,error_estimate=:L2,numruns=100)\nplot(wp)\n\n\nusing DiffEqBenchmarks\nDiffEqBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])\n\n", "meta": {"hexsha": "173d80c18b0842ca33f2f7cdb625bcfc2b633711", "size": 2103, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/NonStiffODE/LotkaVolterra_wpd.jl", "max_stars_repo_name": "jamesjscully/DiffEqBenchmarks.jl", "max_stars_repo_head_hexsha": "4a47f59717f3166864fa4f1b96a0faa5a0db7764", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-01T00:02:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T00:02:56.000Z", "max_issues_repo_path": "script/NonStiffODE/LotkaVolterra_wpd.jl", "max_issues_repo_name": "jamesjscully/DiffEqBenchmarks.jl", "max_issues_repo_head_hexsha": "4a47f59717f3166864fa4f1b96a0faa5a0db7764", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/NonStiffODE/LotkaVolterra_wpd.jl", "max_forks_repo_name": "jamesjscully/DiffEqBenchmarks.jl", "max_forks_repo_head_hexsha": "4a47f59717f3166864fa4f1b96a0faa5a0db7764", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6202531646, "max_line_length": 131, "alphanum_fraction": 0.6176890157, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8670357580842941, "lm_q1q2_score": 0.771916924216239}}
{"text": "using StanSample, Distributions\n\nN = 100;\ndf = DataFrame(\n    height = rand(Normal(10, 2), N),\n    leg_prop = rand(Uniform(0.4, 0.5), N),\n);\ndf.leg_left = df.leg_prop .* df.height + rand(Normal(0, 0.02), N);\ndf.leg_right = df.leg_prop .* df.height + rand(Normal(0, 0.03), N);\n\nstan6_1 = \"\ndata {\n  int <lower=1> N;\n  vector[N] H;\n  vector[N] LL;\n  vector[N] LR;\n}\nparameters {\n  real a;\n  vector[2] b;\n  real <lower=0> sigma;\n}\nmodel {\n  vector[N] mu;\n  mu = a + b[1] * LL + b[2] * LR;\n  a ~ normal(10, 100);\n  b ~ normal(2, 10);\n  sigma ~ exponential(1);\n  H ~ normal(mu, sigma);\n}\n\";\n\n\nm6_1s = SampleModel(\"m6.1s\", stan6_1);\ndata = (H = df.height, LL = df.leg_left, LR = df.leg_right, N = size(df, 1));\n\nrc6_1s = stan_sample(m6_1s; data);\nif success(rc6_1s)\n    nt6_1s = read_samples(m6_1s)\nend\n\nnt6_1s.b |> display\nprintln()\nmean(nt6_1s.b, dims=2) |> display\n\ninit = (a = 2.0, b = [1.0, 2.0], sigma = 1.0)\nrc6_2s = stan_sample(m6_1s; data, init);\nif success(rc6_1s)\n    nt6_2s = read_samples(m6_1s)\nend\n\nnt6_2s.b |> display\nprintln()\nmean(nt6_2s.b, dims=2) |> display\nprintln()\n\nread_summary(m6_1s) |> display\nprintln()\n\npost6_1s_df = read_samples(m6_1s; output_format=:dataframe) |> display\nprintln()\n\npart6_1s = read_samples(m6_1s; output_format=:particles) |> display\n", "meta": {"hexsha": "1d7061e30d6c5110ff5bea9567de87e31bab09fa", "size": 1274, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/Walkthrough2/walkthrough2.jl", "max_stars_repo_name": "Mechachleopteryx/Stan.jl", "max_stars_repo_head_hexsha": "a98b50009fac79d608c94fd2c91bdef9070acefc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Examples/Walkthrough2/walkthrough2.jl", "max_issues_repo_name": "Mechachleopteryx/Stan.jl", "max_issues_repo_head_hexsha": "a98b50009fac79d608c94fd2c91bdef9070acefc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/Walkthrough2/walkthrough2.jl", "max_forks_repo_name": "Mechachleopteryx/Stan.jl", "max_forks_repo_head_hexsha": "a98b50009fac79d608c94fd2c91bdef9070acefc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.90625, "max_line_length": 77, "alphanum_fraction": 0.636577708, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.8333245953120234, "lm_q1q2_score": 0.7719116760971294}}
{"text": "# # Bound on Global Extremum\n\n#md # [![](https://mybinder.org/badge_logo.svg)](@__BINDER_ROOT_URL__/generated/Polynomial Optimization/bound_on_blobal_extremum.ipynb)\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/generated/Polynomial Optimization/bound_on_global_extremum.ipynb)\n# **Adapted from**: SOSTOOLS' SOSDEMO3 (See Section 4.3 of [SOSTOOLS User's Manual](http://sysos.eng.ox.ac.uk/sostools/sostools.pdf))\n\nusing Test #src\nusing DynamicPolynomials\n@polyvar x1 x2\n\n# The Goldstein-Price function $f(x)$ is defined as follows:\n\nf1 = x1 + x2 + 1\nf2 = 19 - 14x1 + 3x1^2 - 14x2 + 6x1*x2 + 3x2^2\nf3 = 2x1 - 3x2\nf4 = 18 - 32x1 + 12x1^2 + 48x2 - 36x1*x2 + 27x2^2\nf = (1 + f1^2 * f2) * (30 + f3^2 * f4)\n\n# We need to pick an SDP solver, see [here](https://jump.dev/JuMP.jl/v0.21.6/installation/#Supported-solvers) for a list of the available choices.\n# We use `SOSModel` instead of `Model` to be able to use the `>=` syntax for Sum-of-Squares constraints.\n\nusing SumOfSquares\nusing CSDP\nsolver = optimizer_with_attributes(CSDP.Optimizer, MOI.Silent() => true)\nmodel = SOSModel(solver);\n\n# We create the decision variable $\\gamma$ that will be the lower bound to the Goldstein-Price function.\n# We maximize it to have the highest possible lower bound.\n\n@variable(model, γ)\n@objective(model, Max, γ)\n\n# We constrain $\\gamma$ to be a lower bound with the following constraint\n# that ensures that $f(x_1, x_2) \\ge \\gamma$ for all $x_1, x_2$.\n\n@constraint(model, f >= γ)\n\nJuMP.optimize!(model)\n\n# We verify that the solver has found a feasible solution:\n\nJuMP.primal_status(model)\n@test JuMP.primal_status(model) == MOI.FEASIBLE_POINT || JuMP.primal_status(model) == MOI.NEARLY_FEASIBLE_POINT #src\n\n# We can now obtain the lower bound either with `value(γ)` or `objective_value(model)`:\n\nobjective_value(model)\n@test objective_value(model) ≈ 3 rtol=1e-2 #src\n", "meta": {"hexsha": "10512011abd73c0eb11956836423ead9593058e0", "size": 1895, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/tutorials/Polynomial Optimization/bound_on_global_extremum.jl", "max_stars_repo_name": "blegat/SumOfSquares", "max_stars_repo_head_hexsha": "a4e1a6ac8853bb3df3e46e33e6cce658c1c6df12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2016-11-10T11:05:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-10T09:08:47.000Z", "max_issues_repo_path": "docs/src/tutorials/Polynomial Optimization/bound_on_global_extremum.jl", "max_issues_repo_name": "blegat/SumOfSquares", "max_issues_repo_head_hexsha": "a4e1a6ac8853bb3df3e46e33e6cce658c1c6df12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 138, "max_issues_repo_issues_event_min_datetime": "2016-11-23T01:37:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-08T18:13:22.000Z", "max_forks_repo_path": "docs/src/tutorials/Polynomial Optimization/bound_on_global_extremum.jl", "max_forks_repo_name": "blegat/SumOfSquares", "max_forks_repo_head_hexsha": "a4e1a6ac8853bb3df3e46e33e6cce658c1c6df12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2017-03-16T20:55:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T19:05:37.000Z", "avg_line_length": 38.6734693878, "max_line_length": 155, "alphanum_fraction": 0.7313984169, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7719098438232423}}
{"text": "using DynamicAxisWarping, DSP, LPVSpectral, Distances, SpectralDistances\n\n# Create two signals\nN = 48_000\ng(x,N) = exp(-10*(x-N/2)^2/N^2)\nt = 1:N\nf = range(0.01, stop=1, length=N)\ny = sin.(t .* f) .* g.(t, N)\ny1 = [y; 0y] .+ 0.1 .* randn.()\ny2 = [0y; y] .+ 0.1 .* randn.()\n\nplot([y1 y2])\n#\nM1,M2 = melspectrogram.((y1,y2), 2048)\nplot(plot(M1), plot(M2))\n# Calculate the Dynamic Time-Warping cost between them (I do this in √ domain since that appears to produce the nicest looking plots)\n@btime dtw(.√(M1.power), .√(M2.power))[1] evals=1 samples=5\n# Calculating this distance is rather fast.\n# Visualize the coupling matrix. The green line should cross diagonally (since the two signals are the same) starting halfway along the axes (since one signal is shifted by 50% of the length copared to the other).\ndtwplot(.√(M1.power), .√(M2.power), linecolor=:green)\n#\n\n# The code above used the squared Euclidean distance between spectra for each time point. We can replace that distance with a transport-based distance instead.\n# We thus combine dynamic time warping with a transport-based cost along the frequency axis\nn,m = size(M1.power)\ndist = DiscreteGridTransportDistance(Cityblock(), n, n)\ndtw(.√(M1.power), .√(M2.power), dist)[1]\n#\ndtwplot(.√(M1.power), .√(M2.power), dist, linecolor=:green)\n# We now see that the valley through which the path can move is slightly wider. This happens since there is now an additional degree of freedom due to transport along the frequency axis. Since there is no need for that transport in this case, the resulting path remains almost the same.\n# We can create the need for some transport along the frequency axis\n\nf1 = range(0.01, stop=1, length=N)\nf2 = range(0.1, stop=1, length=N).^2\ny10 = sin.(t .* f1) .* g.(t, N)\ny20 = sin.(t .* f2) .* g.(t, N)\ny1 = [y10; 0y10] .+ 0.1 .* randn.()\ny2 = [0y20; y20] .+ 0.1 .* randn.()\nM1,M2 = melspectrogram.((y1,y2), 2048)\nplot(plot(M1), plot(M2))\n# We now redo the same stuff as above\ndtw(.√(M1.power), .√(M2.power))[1]\n#\ndtwplot(.√(M1.power), .√(M2.power), linecolor=:green)\n#\ndtw(.√(M1.power), .√(M2.power), dist)[1]\n#\ndtwplot(.√(M1.power), .√(M2.power), dist, linecolor=:green)\n# We expect to see less time warping (straighter green line) now when it's allowed to fudge the distance a bit by shuffling mass along the frequency axis.\n# How long time does it take to compute such a distance? (on a laptop, expect about 3x improvement on desktop)\n@btime dtw($(M1.power), $(M2.power), $dist)\n@btime dtw($(M1.power), $(M2.power), radiuslimits(50,m,m)..., $dist)\n# The size of the spectrogram\nsize(M1.power)\n# The complexity is almost linear in the number of frequency bins, but quadratic in the number of time steps.\n", "meta": {"hexsha": "b8e94ea1c9a2e7ed32e72b26970b0c5452c4e8f3", "size": 2692, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/frequency_warping.jl", "max_stars_repo_name": "paciops/DynamicAxisWarping.jl", "max_stars_repo_head_hexsha": "1c7dc135fd2964868fe148049a888538c3f3c21a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2020-04-24T13:09:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T23:34:19.000Z", "max_issues_repo_path": "examples/frequency_warping.jl", "max_issues_repo_name": "paciops/DynamicAxisWarping.jl", "max_issues_repo_head_hexsha": "1c7dc135fd2964868fe148049a888538c3f3c21a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2020-04-25T08:24:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T06:46:00.000Z", "max_forks_repo_path": "examples/frequency_warping.jl", "max_forks_repo_name": "paciops/DynamicAxisWarping.jl", "max_forks_repo_head_hexsha": "1c7dc135fd2964868fe148049a888538c3f3c21a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-05-14T10:47:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T13:14:10.000Z", "avg_line_length": 48.0714285714, "max_line_length": 286, "alphanum_fraction": 0.6976225854, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7719098414303017}}
{"text": "module proj\nusing LinearAlgebra\n# ! indicates that the variable is modified\n\nfunction infnorm(x,n,γ)\n# compute ∞-norm of x\n# ---\n# x : input vector \t\t\t\t(real n-vector)\n# n : length of x\n# γ : temp storage variable\t\t(real scalar)    !\n\n\tγ = 0.0\n\tfor j=1:n\n\t\tγ = max(γ,abs(x[j]))\n\tend\n\treturn γ\nend\n\nfunction hlfspace!(x,z,u,ζ,n,β)\n# projection onto halfspace { x | u⋅x ≤ ζ }\n# ---\n# x : projected result\t\t\t\t\t(real n-vector) !\n# z : vector to be projected\t\t\t(real n-vector) \n# u : normal to supporting hyperplane \t(real n-vector)\n# ζ : scalar on RHS \t\t\t\t\t(real scalar)\n# β : temporary variable                (real scalar)   !\n\n\t@assert BLAS.nrm2(n,u,1)≈1 \"Normal vector u should have unit norm.\"\n\n\tβ = BLAS.dot(n,z,1,u,1) - ζ\n\n\tif β > 0 \n\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\taxpy!(-β,u,x)\n\telse\n\t\tBLAS.blascopy!(n,z,1,x,1)\n\tend\n\nend\n\nfunction hlfspace2!(x,z,u1,u2,ζ1,ζ2,n,β,α1,α2)\n# projection onto intersection of two halfspaces { x | u1⋅x ≤ ζ1 } ∩ { x | u2⋅x ≤ ζ2 }\n# ---\n# x  : projected result\t\t\t\t\t(real n-vector) !\n# z  : vector to be projected\t\t\t(real n-vector) \n# u1 : normal to supporting hyperplane \t(real n-vector)\n# u2 : normal to supporting hyperplane \t(real n-vector)\n# ζ1 : scalar on RHS \t\t\t\t\t(real scalar)\n# ζ1 : scalar on RHS \t\t\t\t\t(real scalar)\n# β  : temporary variable               (real scalar)   !\n# α1 : temporary variable               (real scalar)   !\n# α2 : temporary variable               (real scalar)   !\n\n\t@assert BLAS.nrm2(n,u1,1)≈1 \"Normal vector u1 should have unit norm.\" \n\t@assert BLAS.nrm2(n,u2,1)≈1 \"Normal vector u2 should have unit norm.\" \n\n\tβ = BLAS.dot(n,u1,1,u2,1)\n\tα1 = BLAS.dot(n,z,1,u1,1)\n\tα2 = BLAS.dot(n,z,1,u2,1)\n\n\tif β ≈ 1\n\t\tβ = min(ζ1,ζ2)\n\t\tif α1 > β\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\t\taxpy!(β-α1,u1,x)\n\t\telse\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\tend\n\telseif β ≈ -1\n\t\t@assert ζ1+ζ2>0 \"The two halfspaces do not intersect.\"\n\t\tif α1 < -ζ2\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\t\taxpy!(-α1-ζ2,u1,x)\t\t\n\t\telseif α1 > ζ1\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\t\taxpy!(-α1+ζ1,u1,x)\n\t\telse\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\tend\n\telse\n\t\tif α1-ζ1+β*(ζ2-α2)>0 && α2-ζ2+β*(ζ1-α1)>0\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\t\taxpy!((α1-ζ1+β*(ζ2-α2))/(β*β-1),u1,x)\n\t\t\taxpy!((α2-ζ2+β*(ζ1-α1))/(β*β-1),u2,x)\n\t\telseif α2>ζ2 && α1-ζ1+β*(ζ2-α2)≤0\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\t\taxpy!(ζ2-α2,u2,x)\n\t\telseif α1>ζ1 || α2>ζ2\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\t\taxpy!(ζ1-α1,u1,x)\n\t\telse\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\tend\n\tend\n\nend\n\nfunction box!(x,z,l,u,n)\n# projection onto l∞-norm ball\n# ---\n# x : projected result\t\t\t(real n-vector) !\n# z : vector to be projected\t(real n-vector) \n# l : lower bound\t\t\t \t(real scalar)\n# u : upper bound \t\t\t\t(real scalar)\n# n : length of z \t\t\t\t(integer)\n\n\t@assert u>l \"Upper bound should be greater than lower bound.\"\n\n\tfor j = 1:n\n\t\tx[j] = min(u,max(z[j],l))\n\tend\n\nend\n\nfunction ball!(x,z,r,n)\n# projection onto l2-norm ball\n# ---\n# x : projected result\t\t\t(real n-vector) !\n# z : vector to be projected\t(real n-vector) \n# r : radius of l2-norm ball \t(real scalar)\n# n : length of z \t\t\t\t(integer)\n\t\n\t@assert r>0 \"Radius should be positive.\"\n\n\tBLAS.blascopy!(n,z,1,x,1)\n\tBLAS.scal!(n,r/max(BLAS.nrm2(n,x,1),r),x,1)\n\nend\n\nfunction soc!(x,z,α,n,β)\n# projection onto second-order cone (aka soc, ice-cream, lorentz cone) \n# type 1 : cone axis along last coordinate and arctan(α) is the cone angle\n# ---\n# x : projected result \t\t     (real n-vector) !\n# z : vector to be projected\t (real n-vector)\n# α : tan(cone angle)\t\t\t (real scalar)\n# n : length of z (integer)\t\t (integer)\t\n# β : temp storage variable  \t (real scalar)   !\n\n\t@assert α>0 \"Cone angle arctan(α) must be positive.\"\n\n\tβ = BLAS.nrm2(n-1,z,1)\n\n\tif β ≤ α*z[n]\n\t\tBLAS.blascopy!(n,z,1,x,1)\n\telseif α*β + z[n] ≤ 0\n\t\tfill!(x,0.0)\n\telse\n\t\tBLAS.blascopy!(n-1,z,1,x,1)\n\t\tx[n] = (β*α+z[n])/(α*α+1)\n\t\tBLAS.scal!(n-1,α*x[n]/β,x,1)\n\tend\n\nend\n\nfunction soc2!(x,z,θ1,θ2,u,n,β,γ,κ)\n# projection onto second-order cone (aka soc, ice-cream, lorentz cone) \n# type 2 : cone axis along unit vector u and arccos(θ) is the cone angle\n# ---\n# x  : projected result \t\t\t(real n-vector) !\n# z  : vector to be projected\t\t(real n-vector)\n# θ1 : cos(cone angle) \t\t\t\t(real scalar)\n# θ2 : sin(cone angle) \t\t\t\t(real scalar)\n# u  : unit vector along cone axis\t(real n-vector)\n# n  : length of z \t\t\t\t\t(integer)\n# β  : temp storage variable \t\t(real scalar)   !\n# γ  : temp storage variable \t\t(real scalar)   !\n# κ  : temp storage variable \t\t(real n-vector) !\n\n\t@assert min(θ1,1-θ1)>0 && min(θ2,1-θ2)>0 \"θ1,θ2 ∈ [0,1]\"\n\t@assert BLAS.nrm2(n,u,1)≈1 \"u must be a unit vector\"\n\n\tβ = BLAS.nrm2(n,z,1)\n\tγ = BLAS.dot(n,z,1,u,1)\n\n\tif θ1*β ≤ γ\n\t\tBLAS.blascopy!(n,z,1,x,1)\n\telseif β*θ2 + γ ≤ 0\n\t\tfill!(x,0.0)\n\telse\n\t\tBLAS.blascopy!(n,u,1,x,1)\n\t\tBLAS.blascopy!(n,z,1,κ,1)\n\t\taxpy!(-γ,u,κ)\n\t\taxpby!(θ2/BLAS.nrm2(n,κ,1),κ,θ1,x)\n\t\tBLAS.scal!(n,BLAS.dot(n,z,1,x,1),x,1)\n\tend\n\nend\n\nfunction soc_ball!(x,z,α,r,n,β)\n# projection onto intersection of soc cone and l2-norm ball\n# ---\n# x : projected result \t\t\t(real n-vector) !\n# z : vector to be projected\t(real n-vector)\n# α : tan(cone angle) \t\t\t(real scalar)\n# r : radius of l2-norm ball \t(real scalar)\n# n : length of z \t\t\t\t(integer)\n# β : temp storage variable \t(real scalar)   !\n\n\tsoc!(x,z,α,n,β)\n\tball!(x,x,r,n)\n\nend\n\nfunction soc2_ball!(x,z,θ1,θ2,u,r,n,β,γ,κ)\n# projection onto intersection of soc cone and l2-norm ball\n# ---\n# x  : projected result \t\t\t(real n-vector) !\n# z  : vector to be projected\t\t(real n-vector)\n# θ1 : cos(cone angle) \t\t\t\t(real scalar)\n# θ2 : cos(cone angle) \t\t\t\t(real scalar)\n# u  : unit vector along cone axis\t(real n-vector)\n# r  : radius of l2-norm ball \t\t(real scalar)\n# n  : length of z \t\t\t\t\t(integer)\n# β  : temp storage variable \t\t(real scalar)   !\n# γ  : temp storage variable \t\t(real scalar)   !\n# κ  : temp storage variable \t\t(real n-vector) !\n\n\tsoc2!(x,z,θ1,θ2,u,n,β,γ,κ)\n\tball!(x,x,r,n)\n\nend\n\nfunction admm!(x,y,u,z,f1,f2,α,β,ϵ,n,γ1,γ2,κ1,κ2)\n# projection onto intersection of two sets with respective projections defined by f1 and f2\n# ---\n# x  : projected result (copy 1)\t(real n-vector) !\n# y  : projected result (copy 2)\t(real n-vector) !\n# u  : dual variable \t\t\t\t(real n-vector) !\n# z  : vector to be projected\t\t(real n-vector)\n# f1 : projection function\t\t\t(function: f!(θ,ψ) where θ is modified)\n# f2 : projection function \t\t\t(function: f!(θ,ψ) where θ is modified)\n# α  : ADMM step size\t\t\t\t(real scalar)\n# β  : 1/(1+α) \t\t\t\t\t\t(real scalar)\n# ϵ  : ADMM termination criteria  \t(real scalar)\n# n  : length of z\t\t\t\t\t(integer)\n# γ  : temp storage variable        (real scalar)   !\n# γ2 : temp storage variable \t\t(real scalar)   !\n# κ1 : temp storage variable \t\t(real n-vector) !\n# κ2 : temp storage variable \t\t(real n-vector) !\n\t\n# x, y and u may hold values from previous call to admm! (warm-starting)\n\n\n\tf1(κ1,z)\n\tf2(κ2,z)\n\tκ1 .= κ1 .- z\n\tκ2 .= κ2 .- z\n\tγ1 = BLAS.nrm2(n,κ2,1)\n\tγ1 = max(γ1,BLAS.nrm2(n,κ1,1))\n\tif γ1 ≤ ϵ\n\t    BLAS.blascopy!(n,z,1,x,1)\n\t\tBLAS.blascopy!(n,z,1,y,1)\n\t\t# κ2[1] will be zero fortunately\n\t\tκ2[1] = 0.0 # inserted for type-stability\n\telse\n\t\tκ1 .= z .- u\n\t\taxpy!(α,y,κ1)\n\t\tBLAS.scal!(n,β,κ1,1)\n\t\tf1(x,κ1)\n\t\tκ2 .= z .+ u\n\t\taxpy!(α,x,κ2)\n\t\tBLAS.scal!(n,β,κ2,1)\n\t\tf2(y,κ2)\n\t\tκ1 .= x .- y\n\t\taxpy!(α,κ1,u)\n\n\t\tκ2[1] = infnorm(κ1,n,γ2)\n\t\tγ1 = 1.0\n\t\twhile κ2[1]≥ϵ\n\t\t\tκ1 .= z .- u\n\t\t\taxpy!(α,y,κ1)\n\t\t\tBLAS.scal!(n,β,κ1,1)\n\t\t\tf1(x,κ1)\n\t\t\tκ2 .= z .+ u\n\t\t\taxpy!(α,x,κ2)\n\t\t\tBLAS.scal!(n,β,κ2,1)\n\t\t\tf2(y,κ2)\n\t\t\tκ1 .= x .- y\n\t\t\taxpy!(α,κ1,u)\n\n\t\t\tγ1 = γ1 + 1.0 # iteration counter\n\n\t\t\tκ2[1] = infnorm(κ1,n,γ2)\n\t\tend\n\t\tκ2[1] = γ1 # store the iteration count\n\tend\n\nend\n\nfunction multi_admm!(x,y,u,z,f,α,β,ϵ,n,N,γ1,γ2,ψ,κ)\n# projection onto intersection of N sets with projections defined by f[i], i=1,...,N\n# ---\n# x  : projected results (copy 1)\t(N-vector of real n-vectors) !\n# y  : projected results (copy 2)\t(N-vector of real n-vectors) !\n# u  : dual variable \t\t\t\t(N-vector of real n-vectors) !\n# z  : vector to be projected\t\t(real n-vector)\n# f  : N projection functions   \t(N-vector of functions: f[i]!(θ,ψ) where θ is modified, i=1,...,N)\n# α  : ADMM step-size\t\t\t\t(positive scalar)\n# β  : 1/(2α(N-1)+1)\t\t\t\t(positive scalar)\n# n  : length of z \t\t\t\t\t(integer)\n# N  : no. of sets\t\t\t\t\t(integer)\n# γ1 : temp storage variable  \t\t(real scalar)                !\n# γ2 : temp storage variable  \t\t(real scalar)                !\n# ψ  : temp storage variable  \t\t(real scalar)                !\n# κ  : temp storage variable        (real n-vector)              !\n\n\t@assert length(f)==N \"No. of projection functions is not N.\"\n\t# @assert N ≥ 3 \"Use admm! for fewer than 3 sets.\"\n\n\t# γ1 = 100.0\n\t# ψ = 0.0 # iteration counter\n\n\tfor i = 1:N\n\t\tκ .= x[i] # BLAS.blascopy!(n,x[i],1,κ,1)\n\t\tlmul!(N-2,κ)\n\t\tfor j = 1:N\n\t\t\tκ .= κ .+ x[j]  \n\t\tend\n\t\tlmul!(α,κ)\n\t\tκ .= κ .- u[i] .+ z\n\t\tlmul!(β,κ) \n\t\tf[i](y[i],κ)\n\tend\n\n\tγ1 = 0.0 # holds termination criteria value\n\tx[1] .= y[1]\n\tfor i = 2:N\n\t\tx[i] .= y[i]\n\t\tκ .= x[1] .- x[i]\n\n\t\tγ1 = max(γ1,infnorm(κ,n,γ2))\n\tend\n\n\tfor i = 1:N\n\t\tκ .= x[i]\n\t\tlmul!(N,κ)\n\t\tfor j = 1:N\n\t\t\tκ .= κ .- x[j]\n\t\tend\n\t\taxpy!(α,κ,u[i])\n\tend\n\t\n\tψ = 1.0\n\n\twhile γ1≥ϵ \n\t\tfor i = 1:N\n\t\t\tκ .= x[i] # BLAS.blascopy!(n,x[i],1,κ,1)\n\t\t\tlmul!(N-2,κ)\n\t\t\tfor j = 1:N\n\t\t\t\tκ .= κ .+ x[j]  \n\t\t\tend\n\t\t\tlmul!(α,κ)\n\t\t\tκ .= κ .- u[i] .+ z\n\t\t\tlmul!(β,κ) \n\t\t\tf[i](y[i],κ)\n\t\tend\n\n\t\tγ1 = 0.0 # holds termination criteria value\n\t\tx[1] .= y[1]\n\t\tfor i = 2:N\n\t\t\tx[i] .= y[i]\n\t\t\tκ .= x[1] .- x[i]\n\n\t\t\tγ1 = max(γ1,infnorm(κ,n,γ2))\n\t\tend\n\n\t\tfor i = 1:N\n\t\t\tκ .= x[i]\n\t\t\tlmul!(N,κ)\n\t\t\tfor j = 1:N\n\t\t\t\tκ .= κ .- x[j]\n\t\t\tend\n\t\t\taxpy!(α,κ,u[i])\n\t\tend\n\t\t\n\t\tψ = ψ + 1.0\n\tend \n\tκ[1] = ψ\n\nend\n\nend", "meta": {"hexsha": "1c876c107db6dab086e4844dc90a262c3fee0c5e", "size": 9472, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PIPG/proj_funcs.jl", "max_stars_repo_name": "purnanandelango/pipg-demo", "max_stars_repo_head_hexsha": "8bf86c3f549470361d5358846ef5b53306bb199e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-02-04T22:25:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:41:59.000Z", "max_issues_repo_path": "PIPG/proj_funcs.jl", "max_issues_repo_name": "UW-ACL/pipg-demo", "max_issues_repo_head_hexsha": "8bf86c3f549470361d5358846ef5b53306bb199e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PIPG/proj_funcs.jl", "max_forks_repo_name": "UW-ACL/pipg-demo", "max_forks_repo_head_hexsha": "8bf86c3f549470361d5358846ef5b53306bb199e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7310704961, "max_line_length": 99, "alphanum_fraction": 0.5806587838, "num_tokens": 3905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7718684793113054}}
{"text": "\"\"\"\n    Original Code Taken from GraphLayout.jl\n    Use the spring/repulsion model of Fruchterman and Reingold (1991):\n        Attractive force:  f_a(d) =  d^2 / k\n        Repulsive force:  f_r(d) = -k^2 / d\n    where d is distance between two vertices and the optimal distance\n    between vertices k is defined as C * sqrt( area / num_vertices )\n    where C is a parameter we can adjust\n    Arguments:\n    adj_matrix Adjacency matrix of some type. Non-zero of the eltype\n               of the matrix is used to determine if a link exists,\n               but currently no sense of magnitude\n    C          Constant to fiddle with density of resulting layout\n    MAXITER    Number of iterations we apply the forces\n    INITTEMP   Initial \"temperature\", controls movement per iteration\n\"\"\"\nfunction layout_spring{T}(adj_matrix::Array{T,2}, dim=1; C=2.0, MAXITER=100, INITTEMP=2.0)\n\n    size(adj_matrix, 1) != size(adj_matrix, 2) && error(\"Adj. matrix must be square.\")\n    const N = size(adj_matrix, 1)\n\n    # Initial layout is random on the square [-1,+1]^2\n    locs_x = 2*rand(N) .- 1.0\n    locs_y = 2*rand(N) .- 1.0\n    locs_z = 2*rand(N) .- 1.0\n\n    # The optimal distance bewteen vertices\n    const K = C * sqrt(4.0 / N)\n\n    # Store forces and apply at end of iteration all at once\n    force_x = zeros(N)\n    force_y = zeros(N)\n    force_z = zeros(N)\n\n    # Iterate MAXITER times\n    @inbounds for iter = 1:MAXITER\n        # Calculate forces\n        for i = 1:N\n            force_vec_x = 0.0\n            force_vec_y = 0.0\n            force_vec_z = 0.0\n            for j = 1:N\n                i == j && continue\n                d_x = locs_x[j] - locs_x[i]\n                d_y = locs_y[j] - locs_y[i]\n                d_z = locs_z[j] - locs_z[i]\n                d   = sqrt(d_x^2 + d_y^2 + d_z^2)\n                if adj_matrix[i,j] != zero(eltype(adj_matrix)) || adj_matrix[j,i] != zero(eltype(adj_matrix))\n                    F_d = d / K - K^2 / d^2\n                else\n                    F_d = -K^2 / d^2\n                end\n\n                force_vec_x += F_d*d_x\n                force_vec_y += F_d*d_y\n                force_vec_z += F_d*d_z\n            end\n            force_x[i] = force_vec_x\n            force_y[i] = force_vec_y\n            force_z[i] = force_vec_z\n        end\n\n        TEMP = INITTEMP / iter\n        # Now apply them, but limit to temperature\n        for i = 1:N\n            force_mag  = sqrt(force_x[i]^2 + force_y[i]^2 + force_z[i]^2)\n            scale      = min(force_mag, TEMP)/force_mag\n            locs_x[i] += force_x[i] * scale\n            locs_y[i] += force_y[i] * scale\n            locs_z[i] += force_y[i] * scale\n        end\n    end\n\n    # Scale to unit square\n    min_x, max_x = minimum(locs_x), maximum(locs_x)\n    min_y, max_y = minimum(locs_y), maximum(locs_y)\n    min_z, max_z = minimum(locs_z), maximum(locs_z)\n    function scaler(z, a, b)\n        2.0*((z - a)/(b - a)) - 1.0\n    end\n    map!(z -> scaler(z, min_x, max_x), locs_x)\n    map!(z -> scaler(z, min_y, max_y), locs_y)\n    map!(z -> scaler(z, min_z, max_z), locs_z)\n\n    if dim == 0\n        locs_z = zeros(size(locs_x))\n    end    \n\n    return locs_x,locs_y,locs_z\nend\n", "meta": {"hexsha": "4959b3b4ee7f4148b296e3e416915234c33b86d7", "size": 3172, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spring.jl", "max_stars_repo_name": "UnofficialJuliaMirror/NetworkViz.jl-1070d6b7-bf31-58fb-9220-e7913ad0860a", "max_stars_repo_head_hexsha": "77d08dc64a71bda8beefc33441d99b83dca7a3f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2016-03-12T19:25:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:15:30.000Z", "max_issues_repo_path": "src/spring.jl", "max_issues_repo_name": "UnofficialJuliaMirror/NetworkViz.jl-1070d6b7-bf31-58fb-9220-e7913ad0860a", "max_issues_repo_head_hexsha": "77d08dc64a71bda8beefc33441d99b83dca7a3f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2016-03-08T20:36:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-23T10:52:27.000Z", "max_forks_repo_path": "src/spring.jl", "max_forks_repo_name": "UnofficialJuliaMirror/NetworkViz.jl-1070d6b7-bf31-58fb-9220-e7913ad0860a", "max_forks_repo_head_hexsha": "77d08dc64a71bda8beefc33441d99b83dca7a3f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2016-03-28T10:52:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-06T22:26:19.000Z", "avg_line_length": 34.8571428571, "max_line_length": 109, "alphanum_fraction": 0.5539092055, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7718684619098827}}
{"text": "function next_chebyshev(previous::Sum_Of_Functions, two_previous::Sum_Of_Functions, dim_name::Symbol)\n    return PE_Function(2.0,Dict{Symbol,PE_Unit}(dim_name => PE_Unit(0.0,0.0,1))) * previous - two_previous\nend\n\nfunction get_first_kind_Chebyshevs(num::Int, dim_name::Symbol)\n    if num < 1\n        error(\"Select a positive number of Chebyshevs to return\")\n    else\n        first_kind_chebyshevs = Array{Sum_Of_Functions}(undef, num)\n        first_kind_chebyshevs[1] = Sum_Of_Functions([PE_Function(1.0,Dict{Symbol,PE_Unit}(dim_name => PE_Unit(0.0,0.0,0)))])\n        if num > 1\n            first_kind_chebyshevs[2] = Sum_Of_Functions([PE_Function(1.0,Dict{Symbol,PE_Unit}(dim_name => PE_Unit(0.0,0.0,1)))])\n        end\n        for n in 3:num\n            first_kind_chebyshevs[n] = next_chebyshev(first_kind_chebyshevs[n-1], first_kind_chebyshevs[n-2], dim_name)\n        end\n        return first_kind_chebyshevs\n    end\nend\nfunction get_second_kind_Chebyshevs(num::Int, dim_name::Symbol)\n    if num < 1\n        error(\"Select a positive number of Chebyshevs to return\")\n    else\n        second_kind_chebyshevs = Array{Sum_Of_Functions}(undef, num)\n        second_kind_chebyshevs[1] = Sum_Of_Functions([PE_Function(1.0,Dict{Symbol,PE_Unit}(dim_name => PE_Unit(0.0,0.0,0)))])\n        if num > 1\n            second_kind_chebyshevs[2] = Sum_Of_Functions([PE_Function(2.0,Dict{Symbol,PE_Unit}(dim_name => PE_Unit(0.0,0.0,1)))])\n        end\n        for n in 3:num\n            second_kind_chebyshevs[n] = next_chebyshev(second_kind_chebyshevs[n-1], second_kind_chebyshevs[n-2], dim_name)\n        end\n        return second_kind_chebyshevs\n    end\nend\n\n\"\"\"\n    get_chevyshevs_up_to(num::Int, first_kind::Bool = true; dim_name::Symbol = default_symbol)\n    Output all chebyshev polynomials up to degree num.\n\"\"\"\nfunction get_chevyshevs_up_to(num::Int, first_kind::Bool = true; dim_name::Symbol = default_symbol)\n    if first_kind\n        return get_first_kind_Chebyshevs(num,dim_name)\n    else\n        return get_second_kind_Chebyshevs(num,dim_name)\n    end\nend\n", "meta": {"hexsha": "c25fe656106ceec51fbe132d70d108d774f7c2c1", "size": 2051, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chebyshevs.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/MultivariateFunctions.jl-54e48022-12d0-513b-b20d-e273c072c6db", "max_stars_repo_head_hexsha": "f9169da3ceed2f3e8a70a2338054facd8e596df6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-01-04T14:13:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T14:12:13.000Z", "max_issues_repo_path": "src/chebyshevs.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/MultivariateFunctions.jl-54e48022-12d0-513b-b20d-e273c072c6db", "max_issues_repo_head_hexsha": "f9169da3ceed2f3e8a70a2338054facd8e596df6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-01-06T10:06:34.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-06T10:07:27.000Z", "max_forks_repo_path": "src/chebyshevs.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/MultivariateFunctions.jl-54e48022-12d0-513b-b20d-e273c072c6db", "max_forks_repo_head_hexsha": "f9169da3ceed2f3e8a70a2338054facd8e596df6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6382978723, "max_line_length": 129, "alphanum_fraction": 0.7001462701, "num_tokens": 657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8519528057272544, "lm_q1q2_score": 0.7718605651109154}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.20\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 03cc6704-70eb-11eb-2f5f-d727783a1f53\nbegin\n\tusing Pkg\n\tPkg.activate(\"MLJ_env\", shared=true)\nend\n\n# ╔═╡ 6d52e124-70eb-11eb-2c56-5dcea746627e\nbegin\n\tusing MLJ\n\tusing CSV\n\tusing DataFrames\n\tusing PlutoUI\nend\n\n# ╔═╡ b738e190-70ef-11eb-04da-8105c8390b73\nusing Random\n\n# ╔═╡ a9f436f6-70fc-11eb-394e-f7a9755bb779\nusing Test\n\n# ╔═╡ 28cfd44c-70fc-11eb-0155-f984980e96f6\nusing Printf # Pkg.add(\"Printf\")\n\n# ╔═╡ 62c32226-70ea-11eb-3914-730e6d2ec0a4\nmd\"\"\"\n## C02 - w01: Simple Linear Regression\n\nIn this notebook we will use data on house sales in King County to predict house prices using simple (one input) linear regression. we will\n  - compute important summary statistics\n  - Write a function to compute the Simple Linear Regression weights using the closed form solution\n  - Write a function to make predictions of the output given the input feature\n  - Turn the regression around to predict the input given the output\n  - Compare two different models for predicting house prices\n  - *Finally use a predefined MLJ solution*\n\"\"\"\n\n# ╔═╡ ec3daae4-70eb-11eb-08df-416f041130f6\n\n\n# ╔═╡ fa6be52e-70eb-11eb-2050-0bd51777d5d0\nsales = CSV.File(\"../../ML_UW_Spec/C02/w01/data/kc_house_test_data.csv\"; \n\theader=true) |> DataFrame;\n\n# ╔═╡ 39ca1334-70ed-11eb-2ee9-5bda94ba96f5\nfirst(sales, 7)\n\n# ╔═╡ 53b101ac-70f1-11eb-3844-3d5f21d9b7aa\nsize(sales)\n\n# ╔═╡ d2a6fa36-70f7-11eb-3817-b36402af12f2\neltype.(eachcol(sales))\n\n# ╔═╡ 299273f6-70f4-11eb-11c9-035af4af7032\nmd\"\"\"\n### Split data into training and testing set\n\"\"\"\n\n# ╔═╡ 55c029d2-70f4-11eb-00ac-0b7698d7b6e2\nfunction train_test_split(df; split=0.8, seed=42) \n\tRandom.seed!(seed)\n\t(nr, nc) = size(df)\n\tnrp = round(Int, nr * split)\n\trow_ixes = shuffle(1:nr)\n\tdf_train = view(df[row_ixes, :], 1:nrp, 1:nc)\n\tdf_test = view(df[row_ixes, :], nrp+1:nr, 1:nc)\n\t(df_train, df_test)\nend\n\n# ╔═╡ d403506c-70f4-11eb-386f-ad0152978098\nsales_train, sales_test = train_test_split(sales);\n\n# ╔═╡ fff80614-70f3-11eb-137d-cbf3fcbaf98f\nfirst(sales_train, 7)\n\n# ╔═╡ 24949900-70f0-11eb-24f4-bd5c33121397\nfirst(sales_test, 3)\n\n# ╔═╡ 11aafb94-70f4-11eb-2438-8320f2e6cb5b\nsize(sales_train), size(sales_test)\n\n# ╔═╡ 1fb75280-70f8-11eb-1cc3-29a08a026bcc\n# mean and sum of a column\nmean(sales_train[!, :bedrooms]), sum(sales_train[!, :bedrooms])\n\n# ╔═╡ 799514b8-70f8-11eb-0d03-e5fe5b1c0cb4\nsales_train[!, :bedrooms] .* sales_train[!, :bedrooms] \n\n# ╔═╡ 7c9c2c1a-70f9-11eb-3ddc-d90788056518\nlength(sales_train[!, :bedrooms])\n\n# ╔═╡ cc20e6e0-70f9-11eb-2b0d-7bd7f07d4733\ntypeof(sales_train[!, :bedrooms])\n\n# ╔═╡ 416a6240-70f9-11eb-1962-e77cb5215607\nmd\"\"\"\n### Build a generic simple linear regression function\n\"\"\"\n\n# ╔═╡ 5b5efd00-70f9-11eb-36f1-75d629b148e6\nfunction slope(X, y)::Float64\n\tsx, sy = sum(X), sum(y)\n\tn = length(X)\n\tnum = sum(X .* y) - (1/n) * sx * sy\n\tden = sum(X .* X) - (1/n) * sx * sx\n\tnum / den\nend\n\n# ╔═╡ c40f3ea0-70f9-11eb-2ff0-9b1e9c4f3084\nintercept(X, y, slope) = mean(y) - slope * mean(X)\n\n# ╔═╡ 04b3c642-70fa-11eb-3e0b-b9b86108e1af\nfunction simple_linear_regression(X, y)::Tuple{Real, Real}\n\t_slope = slope(X, y)\n\t_intercept = intercept(X, y, _slope)\n\t(_intercept, _slope)\nend\n\n# ╔═╡ 4e0f51e4-70fa-11eb-2511-b9813e9c82bb\nbegin\n\ttest_feature = collect(1:5) \n\ttest_output = 1 .+ test_feature\n\t\n\t(test_intercept, test_slope) = simple_linear_regression(test_feature, test_output)\n\t\n\t@test test_intercept ≈ 1.0\n\t@test test_slope ≈ 1.0\nend\n\n# ╔═╡ 64258a92-70fb-11eb-08d4-b11d5f75639f\nbegin\n\tsqft_intercept, sqft_slope = simple_linear_regression(\n\t\tsales_train[!, :sqft_living], sales_train[!, :price])\n\n\twith_terminal() do\n\t\t@printf(\"Intercept: %.4f\\n\", sqft_intercept)\n\t\t@printf(\"Slope:  %.4f\\n\", sqft_slope)\n\tend\nend\n\n# ╔═╡ beee3bd2-70fc-11eb-38cd-e7e8fda2f883\nmd\"\"\"\n### Predicting Values\n\nNow that we have the model parameters: intercept and slope we can make predictions.\n\nCreate a function to return the predicted output given the input_feature, slope and intercept.\n\n\"\"\"\n\n# ╔═╡ deda4470-70fc-11eb-20a2-15820ab34231\nfunction get_regression_predictions(input_feature, intercept::Real, \n\t\tslope::Real)\n    slope .* input_feature .+ intercept\nend\n\n# ╔═╡ 1ed980ae-70fd-11eb-07ed-09b7648af658\nmd\"\"\"\nNow that we can calculate a prediction given the slope and intercept let's make a prediction.\n\n**Quiz Question**: Using your Slope and Intercept from above, what is the predicted price for a house with 2650 sqft?\n\"\"\"\n\n# ╔═╡ 490bda66-70fd-11eb-3cd3-e7ccd064c7ec\nwith_terminal() do\n\thouse_sqft = 2650\n\testimated_price = get_regression_predictions(house_sqft, \n\t\tsqft_intercept, sqft_slope)\n\t\n\t@printf(\"The estimated price for a house with %d squarefeet is %.2f\\n\", \n\t\thouse_sqft, \n\t\testimated_price)\nend\n\n# ╔═╡ 96f5469a-70fd-11eb-1f17-675eeff21970\nmd\"\"\"\n### Residual Sum of Squares\n\nNow that we have a model and can make predictions let's evaluate our model using Residual Sum of Squares (RSS). Recall that RSS is the sum of the squares of the residuals and the residuals is just a fancy word for the difference between the predicted output and the true output.\n\nCreate a function (`get_residual_sum_of_squares`) to compute the RSS of a simple linear regression model given the input_feature, output, intercept and slope.\n\n\"\"\"\n\n# ╔═╡ b5e12f56-70fd-11eb-1bf7-cbdfa36fc673\nfunction get_residual_sum_of_squares(input_feature, output, \n\t\tintercept::Real, slope::Real)\n    ## 1. get the predictions\n    yhat = get_regression_predictions(input_feature, intercept, slope)\n    diff = (yhat .- output)   ## 2. compute the residuals \n    rss = sum(diff .* diff)  ## 3. square the residuals and add them up\n    return rss\nend\n\n# ╔═╡ 25479c96-70ff-11eb-2b86-29c052eb2f87\ntest_slope\n\n# ╔═╡ 064ec37c-70fe-11eb-3bce-a79f7208c876\nmd\"\"\"\nLet's test our `get_residual_sum_of_squares` function by applying it to the test model where the data lie exactly on a line. Since they lie exactly on a line the residual sum of squares should be zero!\n\"\"\"\n\n# ╔═╡ 1b0643d0-70fe-11eb-250c-53e54279e747\n@test get_residual_sum_of_squares(test_feature, test_output, \n\ttest_intercept, test_slope) ≈ 0.0\n\n# ╔═╡ 5e2a432e-70ff-11eb-3e61-bffdc0ebd46e\nmd\"\"\"\nNow use your function to calculate the RSS on training data from the squarefeet model calculated above.\n\n**Quiz Question**: According to this function and the slope and intercept from the squarefeet model What is the RSS for the simple linear regression using squarefeet to predict prices on *training* data?\n\n\"\"\"\n\n# ╔═╡ 7e8bcf82-70ff-11eb-1c79-a56db6635447\nbegin\n\trss_prices_on_sqft = get_residual_sum_of_squares(sales_train[!, :sqft_living], \n\t\tsales_train[!, :price], \n        sqft_intercept, \n\t\tsqft_slope)\n\twith_terminal() do\n\t\t@printf(\"The RSS of predicting Prices based on Square Feet is: %1.3e\\n\", rss_prices_on_sqft)\n\tend\nend\n\n# ╔═╡ 0afc9a02-7100-11eb-0578-8b470fbb1d32\nmd\"\"\"\n### Predict the squarefeet given price\n\n\nWhat if we want to predict the squarefoot given the price? \n\nSince we have an equation $y = a + b \\times x$ we can solve the function for x, so that if we have the intercept (a) and the slope (b) and the price (y) we can solve for the estimated squarefeet (x) with: \n$x = \\frac{y - a}{b}$.\n\nCreate a function (`inverse_regression_predictions`) to compute the inverse regression estimate, i.e. predict the input_feature given the output.\n\"\"\"\n\n# ╔═╡ 5936bff2-7100-11eb-3673-03eb5174f2b0\nfunction inverse_regression_predictions(output, intercept::Real, slope::Real)\n    (output .- intercept) ./ slope\nend\n\n# ╔═╡ 7f548db8-7100-11eb-1a71-cfa1b2817f83\nmd\"\"\"\nNow that we have a function to compute the squarefeet given the price from our simple regression model let's see how big we might expect a house that costs \\$800,000 to be.\n\n**Quiz Question**: According to this function and the regression slope and intercept from (3) what is the estimated square-feet for a house costing \\$800,000?\n\n\"\"\"\n\n# ╔═╡ 967a4d8e-7100-11eb-369c-a7eef43335a2\nbegin\n\thouse_price = 800000\n\testimated_squarefeet = inverse_regression_predictions(house_price, \n\t\tsqft_intercept, \n\t\tsqft_slope)\n\t\n\twith_terminal() do\n\t\t@printf(\"The estimated squarefeet for a house worth %.2f is %.3f\\n\", house_price, estimated_squarefeet)\n\tend\nend\n\n# ╔═╡ f8cb4844-7100-11eb-2036-f1691f9277ba\nmd\"\"\"\n### New Model: estimate prices from bedrooms\n\nWe have made one model for predicting house prices using squarefeet, but there are many other features in the sales DataFrame. \n\nUse your simple linear regression function to estimate the regression parameters from predicting Prices based on number of bedrooms. Use the *training* data!\n\n\"\"\"\n\n# ╔═╡ 1a89af3e-7101-11eb-274d-43bbcf50db13\nbedr_intercept, bedr_slope = simple_linear_regression(\n\tsales_train[!, :bedrooms], \n\tsales_train[!, :price]\n)\n\n# ╔═╡ 4d0ca242-7101-11eb-1001-7bb71d3b8de6\nmd\"\"\"\n### Test your Linear Regression Algorithm\n\nNow we have two models for predicting the price of a house. How do we know which one is better? Calculate the RSS on the *test* data (remember this data wasn't involved in learning the model). Compute the RSS from predicting prices using bedrooms and from predicting prices using squarefeet.\n\n**Quiz Question**: Which model (square feet or bedrooms) has lowest RSS on TEST data? Think about why this might be the case.\n\n\"\"\"\n\n# ╔═╡ 69a38e9e-7101-11eb-2e57-83829ceb7ab9\nbegin\n\t## Compute RSS when using bedrooms on test data:\n\trss_prices_on_bedr = get_residual_sum_of_squares(sales_test[!, :bedrooms], \n        sales_test[!, :price], \n        bedr_intercept, \n\t\tbedr_slope)\n\twith_terminal() do\n\t\t@printf(\"The RSS of predicting Prices based on number of Bedrooms is: %1.3e\\n \", rss_prices_on_bedr)\n\tend\nend\n\n# ╔═╡ d043648a-7101-11eb-1b30-8d7ff3b37b7a\nbegin\n\t## Compute RSS when using squarefeet on test data:\n\trss_prices_on_sqft_t = get_residual_sum_of_squares(sales_test[!, :sqft_living], \n        sales_test[!, :price], \n        sqft_intercept, \n\t\tsqft_slope)\n\twith_terminal() do\n\t\t@printf(\"The RSS of predicting Prices based on Squarefeet is: %1.3e\\n \", rss_prices_on_sqft_t)\n\tend\nend\n\n# ╔═╡ Cell order:\n# ╟─62c32226-70ea-11eb-3914-730e6d2ec0a4\n# ╠═03cc6704-70eb-11eb-2f5f-d727783a1f53\n# ╠═6d52e124-70eb-11eb-2c56-5dcea746627e\n# ╟─ec3daae4-70eb-11eb-08df-416f041130f6\n# ╠═fa6be52e-70eb-11eb-2050-0bd51777d5d0\n# ╠═39ca1334-70ed-11eb-2ee9-5bda94ba96f5\n# ╠═53b101ac-70f1-11eb-3844-3d5f21d9b7aa\n# ╠═d2a6fa36-70f7-11eb-3817-b36402af12f2\n# ╟─299273f6-70f4-11eb-11c9-035af4af7032\n# ╠═b738e190-70ef-11eb-04da-8105c8390b73\n# ╠═55c029d2-70f4-11eb-00ac-0b7698d7b6e2\n# ╠═d403506c-70f4-11eb-386f-ad0152978098\n# ╠═fff80614-70f3-11eb-137d-cbf3fcbaf98f\n# ╠═24949900-70f0-11eb-24f4-bd5c33121397\n# ╠═11aafb94-70f4-11eb-2438-8320f2e6cb5b\n# ╠═1fb75280-70f8-11eb-1cc3-29a08a026bcc\n# ╠═799514b8-70f8-11eb-0d03-e5fe5b1c0cb4\n# ╠═7c9c2c1a-70f9-11eb-3ddc-d90788056518\n# ╠═cc20e6e0-70f9-11eb-2b0d-7bd7f07d4733\n# ╟─416a6240-70f9-11eb-1962-e77cb5215607\n# ╠═5b5efd00-70f9-11eb-36f1-75d629b148e6\n# ╠═c40f3ea0-70f9-11eb-2ff0-9b1e9c4f3084\n# ╠═04b3c642-70fa-11eb-3e0b-b9b86108e1af\n# ╠═a9f436f6-70fc-11eb-394e-f7a9755bb779\n# ╠═4e0f51e4-70fa-11eb-2511-b9813e9c82bb\n# ╠═28cfd44c-70fc-11eb-0155-f984980e96f6\n# ╠═64258a92-70fb-11eb-08d4-b11d5f75639f\n# ╟─beee3bd2-70fc-11eb-38cd-e7e8fda2f883\n# ╠═deda4470-70fc-11eb-20a2-15820ab34231\n# ╟─1ed980ae-70fd-11eb-07ed-09b7648af658\n# ╠═490bda66-70fd-11eb-3cd3-e7ccd064c7ec\n# ╟─96f5469a-70fd-11eb-1f17-675eeff21970\n# ╠═b5e12f56-70fd-11eb-1bf7-cbdfa36fc673\n# ╠═25479c96-70ff-11eb-2b86-29c052eb2f87\n# ╟─064ec37c-70fe-11eb-3bce-a79f7208c876\n# ╠═1b0643d0-70fe-11eb-250c-53e54279e747\n# ╟─5e2a432e-70ff-11eb-3e61-bffdc0ebd46e\n# ╠═7e8bcf82-70ff-11eb-1c79-a56db6635447\n# ╟─0afc9a02-7100-11eb-0578-8b470fbb1d32\n# ╠═5936bff2-7100-11eb-3673-03eb5174f2b0\n# ╟─7f548db8-7100-11eb-1a71-cfa1b2817f83\n# ╠═967a4d8e-7100-11eb-369c-a7eef43335a2\n# ╟─f8cb4844-7100-11eb-2036-f1691f9277ba\n# ╠═1a89af3e-7101-11eb-274d-43bbcf50db13\n# ╟─4d0ca242-7101-11eb-1001-7bb71d3b8de6\n# ╠═69a38e9e-7101-11eb-2e57-83829ceb7ab9\n# ╠═d043648a-7101-11eb-1b30-8d7ff3b37b7a\n", "meta": {"hexsha": "d427c5fd072c58c943a724732d24356c5fa37a9b", "size": 11910, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "C02/w01/C02w01_nb_pa.jl", "max_stars_repo_name": "pascal-p/ML_UW_Spec", "max_stars_repo_head_hexsha": "5e19916b62fd776b1412ba31d06b41049a1ec7d8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "C02/w01/C02w01_nb_pa.jl", "max_issues_repo_name": "pascal-p/ML_UW_Spec", "max_issues_repo_head_hexsha": "5e19916b62fd776b1412ba31d06b41049a1ec7d8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C02/w01/C02w01_nb_pa.jl", "max_forks_repo_name": "pascal-p/ML_UW_Spec", "max_forks_repo_head_hexsha": "5e19916b62fd776b1412ba31d06b41049a1ec7d8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4523160763, "max_line_length": 291, "alphanum_fraction": 0.7465994962, "num_tokens": 4798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.9059898159413479, "lm_q1q2_score": 0.7718605622459853}}
{"text": "\"\"\"\n    find_maxlength_subarray(array::Array{Int64,1})\n\nFind the maximum length of a subarray with a given continuous depending sequence of numbers.\nFor this reason, the minimum and maximum element in every subarray will be tracked and\ncompared with the incremental distance. So if the difference of the value is equal to the\ndifference of the increment in the array, the length will be updated.\n\n\n# Arguments\n- `array::Array{Int64,1}`: Unsorted array\n\n\n# Examples\n```julia-repl\njulia> import ClassicAlgorithmsCollections\njulia> arr = [10, 12, 11, 9, 13, 14, 17, 18, 15]\njulia> ClassicAlgorithmsCollections.find_maxlength_subarray(arr)\n5\n```\n\"\"\"\nfunction find_maxlength_subarray(array::Array{Int64,1})\n\n    # Initialize result\n    max_len = 1\n    n = length(array)\n    for i in 1:n\n        min_array = array[i]\n        max_array = array[i]\n\n        for j in (i+1):n\n            if min_array > array[j]\n                min_array = array[j]\n            end\n            if max_array < array[j]\n                max_array = array[j]\n            end\n            if ((max_array - min_array) == (j - i))\n                if max_len < (max_array - min_array)\n                    max_len = max_array - min_array + 1\n                end\n            end\n        end\n    end\n    return max_len\nend\n", "meta": {"hexsha": "0461980ba9d3a5ae7677328b4131bba6f146cb83", "size": 1284, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/StringAndArray/FindMaxLengthSubarray.jl", "max_stars_repo_name": "Anselmoo/ClassicAlgorithmsCollections", "max_stars_repo_head_hexsha": "9f802c4f317492e19b0b8bb6d9020d8450e00772", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/StringAndArray/FindMaxLengthSubarray.jl", "max_issues_repo_name": "Anselmoo/ClassicAlgorithmsCollections", "max_issues_repo_head_hexsha": "9f802c4f317492e19b0b8bb6d9020d8450e00772", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2020-09-03T06:47:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-20T06:58:58.000Z", "max_forks_repo_path": "src/StringAndArray/FindMaxLengthSubarray.jl", "max_forks_repo_name": "Anselmoo/ClassicAlgorithmsCollections", "max_forks_repo_head_hexsha": "9f802c4f317492e19b0b8bb6d9020d8450e00772", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3191489362, "max_line_length": 92, "alphanum_fraction": 0.6214953271, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989810230102, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.7718605505691436}}
{"text": "using Plots\nusing Random\nusing NearestNeighbors\n\nglobal my_seed = 1001\nRandom.seed!(my_seed)\n\nfunction inv_dist_itp_test(idxs, dists, p, values)\n    avg_inv_dist = 0\n    f = 0\n    for i in 1:length(idxs)\n        idx = idxs[i]\n        inv_dist = 1/dists[i]^p\n        avg_inv_dist += inv_dist\n        f += values[idx]*inv_dist\n    end\n    f = f/avg_inv_dist\nend\n\nfunction inv_dist_itp(idxs::AbstractVector,\n                      dists::AbstractVector,\n                      p::AbstractFloat,\n                      values::AbstractVector)\n    avg_inv_dist = 0\n    f = 0\n    for i in 1:length(idxs)\n        idx = idxs[i]\n        if idx > 0\n            inv_dist = 1/dists[i]^p\n            avg_inv_dist += inv_dist\n            f += values[idx]*inv_dist\n        elseif idx == -5\n            # lower boundary\n            f+=0\n        elseif idx == -6\n            # upper boundary\n            f+=0\n        end\n    end\n    f = f/avg_inv_dist\nend\n\nfunction sample_function(x, y)\n    return exp(-x^2 - y^2)\nend\n\nn_samples = 100\n\nsamples = rand(2, n_samples).*2 .-1\nx_samples = samples[1,:]\ny_samples = samples[2,:]\n\n# Create a tree\ntree = KDTree(samples)\n\nk = 15\n\nfunction_values = sample_function.(x_samples, y_samples)\n\nraster_size = 500\nx_range = LinRange(-1,1,raster_size)\ny_range = LinRange(-1,1,raster_size)\n\ngr()\n\nfunction plot_the_itp(p)\n\n    raster_values = Matrix{Float64}(undef, (raster_size, raster_size))\n\n    for i in 1:raster_size\n        for j in 1:raster_size\n            raster_site = [x_range[i], y_range[j]]\n            nearest_neighbours = knn(tree, raster_site, k)\n            raster_values[i, j] = inv_dist_itp_test(nearest_neighbours[1],\n                                                    nearest_neighbours[2],\n                                                    p,\n                                                    function_values)\n        end\n    end\n    heatmap(x_range,\n            y_range,\n            raster_values,\n            title=\"p=$p, $k neighbours\",\n            dpi=350,\n            aspect_ratio=:equal,\n            xlim=[-1,1])\n    savefig(\"../img/InverseDistance/inv_dist_$(Int(p*100))_$(k)\")\nend\n\np = [3]\nfor i in p\n    plot_the_itp(i)\nend\n\ntrue_values = Matrix{Float64}(undef, (raster_size, raster_size))\nfor i in 1:raster_size\n    for j in 1:raster_size\n        true_values[i, j] = sample_function(x_range[i], y_range[j])\n    end\nend\n\nheatmap(x_range,\n        y_range,\n        true_values,\n        title=\"True Function\",\n        dpi=350,\n        aspect_ratio=:equal,\n        xlim=[-1,1])\nsavefig(\"../img/InverseDistance/inv_dist_comparison\")\n\nscatter(x_samples,\n        y_samples,\n        title=\"samples\",\n        dpi=350,\n        aspect_ratio=:equal,\n        xlim=[-1,1],\n        xlabel=raw\"$x$\",\n        ylabel=raw\"$y$\")\nsavefig(\"../img/InverseDistance/sample_points\")\n", "meta": {"hexsha": "42ae10e90e239714d743b8045d1d3a7135327223", "size": 2805, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_itp.jl", "max_stars_repo_name": "meudnaes/VoronoiRT", "max_stars_repo_head_hexsha": "448eead8fa6e911ed40e2dfaba5baa1c9ef54cf2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-03T08:56:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T08:56:57.000Z", "max_issues_repo_path": "test/test_itp.jl", "max_issues_repo_name": "meudnaes/VoronoiRT", "max_issues_repo_head_hexsha": "448eead8fa6e911ed40e2dfaba5baa1c9ef54cf2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-02-18T09:50:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T12:10:56.000Z", "max_forks_repo_path": "test/test_itp.jl", "max_forks_repo_name": "meudnaes/VoronoiRT", "max_forks_repo_head_hexsha": "448eead8fa6e911ed40e2dfaba5baa1c9ef54cf2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.375, "max_line_length": 74, "alphanum_fraction": 0.5550802139, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7717161017636748}}
{"text": "\"\"\"\nx = admm(A, B; ...)\n\nSolves non-negative least-squares problem by the Alternating Direction Method\nof Multipliers (ADMM).\n\nOptional arguments:\n    ρ: penalty parameter (set heuristically by default)\n    ε: tolerance for stopping (small number times sqrt[m*n] by default)\n\nReferences:\n    S. Boyd, N. Parikh, E. Chu, B. Peleato, and J. Eckstein (2011). Distributed\n    Optimization and Statistical Learning via the Alternating Direction Method\n    of Multipliers. Foundations and Trends in Machine Learning.\n\n    http://stanford.edu/~eryu/nnlsqr.html\n\"\"\"\nfunction admm(A::Matrix{Float64},\n\t          B::Matrix{Float64};\n\t          ρ=max(0.1,vecnorm(A)^2/size(A,2)),\n\t          ε=sqrt(size(A,2)*size(B,2))*1e-15,\n\t          kwargs...)\n\n\t# Dimensions\n\tm,k = size(A)\n\tn = size(B,2)\n\n\t# Cache matrices\n\tAtB = A'*B \n\tAtAρ = A'*A + eye(k)*ρ\n\n\t# Cache cholesky factorization\n\tL = cholfact(AtAρ)\n\t\n\t# Matrix storing the solutions\n\tX = zeros(k,n)\n\n\t# Initialize variables\t\n\tZ,U = zeros(k,n),zeros(k,n)\n\tX = L \\ (AtB+ρ*(Z-U))\n\t\n\t# Solve\n\twhile vecnorm(X-Z) > ε\n\t\tZ = max(0,X+U)\n\t\tU = U+X-Z\n\t\tX = L \\ (AtB+ρ*(Z-U))\n\tend\n\n\t# Z ≈ X, return Z because nonnegativity is strictly enforced\n\treturn Z\nend\n\n", "meta": {"hexsha": "1fdc0add6a05c137015eb2c4c5b2f56e62e02ec8", "size": 1190, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/admm.jl", "max_stars_repo_name": "JuliaPackageMirrors/NonNegLeastSquares.jl", "max_stars_repo_head_hexsha": "788b44005e50c79c68c3aa75ef5cb7a26387eb1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/admm.jl", "max_issues_repo_name": "JuliaPackageMirrors/NonNegLeastSquares.jl", "max_issues_repo_head_hexsha": "788b44005e50c79c68c3aa75ef5cb7a26387eb1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/admm.jl", "max_forks_repo_name": "JuliaPackageMirrors/NonNegLeastSquares.jl", "max_forks_repo_head_hexsha": "788b44005e50c79c68c3aa75ef5cb7a26387eb1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4528301887, "max_line_length": 79, "alphanum_fraction": 0.6411764706, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7716963662336234}}
{"text": "const P = big(2)^256 - 2^32 - 977\nconst N = big\"0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141\"\n\ninfield(x::Integer) = x >= 0 && x < P\n\n\"`FieldElement` represents an element in 𝐹ₚ where `P = 2²⁵⁶ - 2³² - 977`\"\nstruct FieldElement <: Number\n     𝑛::BigInt\n     FieldElement(𝑛) = !infield(𝑛) ? throw(NotInField()) : new(𝑛)\nend\n\nFieldElement(x::FieldElement) = x\nFieldElement(x::Union{Int128, Int64, Int32, Int16, Int8, Unsigned}) = FieldElement(big(x))\n𝐹 = FieldElement\n\n\"Formats FieldElement showing 𝑛 in hexadecimal format\"\nfunction show(io::IO, z::FieldElement)\n    print(io, string(z.𝑛, base = 16),\"\\n(in scep256k1 field)\")\nend\n\n==(𝑋₁::FieldElement, 𝑋₂::FieldElement) = 𝑋₁.𝑛 == 𝑋₂.𝑛\n==(::FieldElement, ::Integer) = false\n+(𝑋₁::FieldElement, 𝑋₂::FieldElement) = 𝐹(mod(𝑋₁.𝑛 + 𝑋₂.𝑛, P))\n-(𝑋₁::FieldElement, 𝑋₂::FieldElement) = 𝐹(mod(𝑋₁.𝑛 - 𝑋₂.𝑛, P))\n*(𝑋₁::FieldElement, 𝑋₂::FieldElement) = 𝐹(mod(𝑋₁.𝑛 * 𝑋₂.𝑛, P))\n*(𝑐::Integer, 𝑋::FieldElement) = 𝐹(mod(𝑐 * 𝑋.𝑛, P))\n*(𝑋::FieldElement, 𝑐::Integer) = *(𝑐, 𝑋)\n^(𝑋::FieldElement, 𝑘::Int) = 𝐹(powermod(𝑋.𝑛, mod(𝑘, (P - 1)), P))\n/(𝑋₁::FieldElement, 𝑋₂::FieldElement) = 𝐹(mod(𝑋₁.𝑛 * powermod(𝑋₂.𝑛, P - 2, P), P))\ndiv(𝑋₁::FieldElement, 𝑋₂::FieldElement) = 𝑋₁ / 𝑋₂\ninv(𝑋::FieldElement) = 𝐹(powermod(𝑋.𝑛, mod(-1, (P - 1)), P))\nsqrt(𝑋::FieldElement) = 𝑋^fld(P + 1, 4)\n", "meta": {"hexsha": "83de0ffb89701cd77af999bd8a2282ebc720bbc1", "size": 1325, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lib/FieldElement.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Secp256k1.jl-bfa37bea-997f-11e9-0e02-2d50932a0e04", "max_stars_repo_head_hexsha": "db4c6740fa5d29dc85c5d3f94465329a18204b3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lib/FieldElement.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Secp256k1.jl-bfa37bea-997f-11e9-0e02-2d50932a0e04", "max_issues_repo_head_hexsha": "db4c6740fa5d29dc85c5d3f94465329a18204b3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/FieldElement.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Secp256k1.jl-bfa37bea-997f-11e9-0e02-2d50932a0e04", "max_forks_repo_head_hexsha": "db4c6740fa5d29dc85c5d3f94465329a18204b3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1515151515, "max_line_length": 90, "alphanum_fraction": 0.6528301887, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870767, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7716963637772472}}
{"text": "# This file illustrates calculation of energy spectral density and total enery of a rectangular pulse. \n\nusing FFTW\nusing Plots; plotlyjs() \n\n# Define pulse \nT = 1 / 10 \np(t) = 0 ≤ t ≤ T ? 1 : 0 \n\n# Construct the signal\nfs = 1000\nts = 1 / fs \nl = 2^10\nt = (0 : l - 1) * ts\nx = p.(t)\n\n# Compute fft \nxf = fft(x)\npsd = abs.(xf).^2\nff = (0 : 1 / (l - 1) : 1) * fs\n\n# Compute energies \nΔf = fs / (l - 1)\nΔt = ts\nEt = sum(abs.(x).^2) * Δt\nEf = sum(psd) * Δf / (fs^2)\n@show Et, Ef\n\n# Plots \nplt = plot(layout=2) \nplot!(t[1:500], x[1:500], subplot=1)\nplot!(ff, psd, subplot=2)\ndisplay(plt)\n", "meta": {"hexsha": "a8b5020991fccfc2f53bd6b5e2ff03ce587560ae", "size": 583, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/dsp/pulse.jl", "max_stars_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_stars_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-03T20:02:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T06:43:38.000Z", "max_issues_repo_path": "example/dsp/pulse.jl", "max_issues_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_issues_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-11-26T21:56:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-03T19:54:59.000Z", "max_forks_repo_path": "example/dsp/pulse.jl", "max_forks_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_forks_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-20T12:53:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T12:53:43.000Z", "avg_line_length": 17.1470588235, "max_line_length": 103, "alphanum_fraction": 0.576329331, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799462157138, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7716908992991124}}
{"text": "#=\nThere are exactly ten ways of selecting three from five, 12345:\n\n123, 124, 125, 134, 135, 145, 234, 235, 245, and 345\n\nIn combinatorics, we use the notation, 5C3 = 10.\n\nIn general,\n\nnCr =\nn!\nr!(n−r)!\n,where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1.\nIt is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.\n\nHow many, not necessarily distinct, values of  nCr, for 1 ≤ n ≤ 100, are greater than one-million?\n=#\nfunction combine(n, r)\n  factorial(n)/(factorial(r)factorial(n-r))\nend\n\nfunction calc()\n  sum = 0\n  for n in 1:100, r in reverse(1:n)\n    if combine(BigInt(n), BigInt(r)) > 1_000_000\n      sum = sum + 1\n    end\n  end\n  sum\nend\n@time println(calc())\n", "meta": {"hexsha": "954e55f5a4a94cdb70656d309ee807f48fd9cae4", "size": 680, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p53.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p53.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p53.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 21.25, "max_line_length": 98, "alphanum_fraction": 0.6411764706, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799420543366, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7716908982589916}}
{"text": "function isprime(n::Int64)\n    if n <= 3\n        return n > 1\n    elseif n % 2 == 0 || n % 3 == 0\n        return false\n    end\n    i = 5\n    while i^2 <= n\n        if n % i == 0 || n % (i+2) == 0\n            return false\n        end\n        i += 6\n    end\n    return true\nend\n\nfunction get_smallest_divisor(n::Int64)\n    k = 2\n    while n % k ≠ 0\n        k += 1\n    end\n    return k\nend\n\nfunction get_prime_factors(N::Int64)\n    S = Vector{Int64}()\n    while true\n        !isprime(N) || break\n        k = get_smallest_divisor(N)\n        push!(S, k)\n        N::Int64 = N/k\n    end\n    push!(S, N)\n    return S\nend\n\nfunction reverse_int(n::Int64)\n    if n <= 9\n        return n\n    else\n        return parse(Int, reduce(string, digits(n)))\n    end\nend\n\nfunction totient(n::Int64)\n    result::Float64 = n\n    p = 2\n    while p*p <= n\n        if n % p == 0\n            while n % p == 0\n                n = n//p\n            end\n            result *= (1.0 - (1.0 / p)) \n        end\n        p += 1\n    end\n    \n    if n > 1\n        result *= (1.0 - (1.0 / n))\n    end\n    \n    return result\nend\n\nfunction prime_sieve(N::Int64)\n    iscoprime(P, i) = !any(x -> i % x == 0, P)\n\n    primes = Int64[]\n    for num = 2:N\n        if iscoprime(primes, num)\n            push!(primes, num)\n        end\n    end\n    primes\nend", "meta": {"hexsha": "a305a65d3844d369406da7961f1e650426a8329f", "size": 1306, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/useful_functions.jl", "max_stars_repo_name": "jkynaston/ProjectEuler.jl", "max_stars_repo_head_hexsha": "84dba07bc8f532ce819811ee896ca643c7bce3b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/useful_functions.jl", "max_issues_repo_name": "jkynaston/ProjectEuler.jl", "max_issues_repo_head_hexsha": "84dba07bc8f532ce819811ee896ca643c7bce3b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/useful_functions.jl", "max_forks_repo_name": "jkynaston/ProjectEuler.jl", "max_forks_repo_head_hexsha": "84dba07bc8f532ce819811ee896ca643c7bce3b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4133333333, "max_line_length": 52, "alphanum_fraction": 0.4555895865, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799399736476, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7716908943011399}}
{"text": "# The Jacobi method for solving an equation system\n# Ax = b\n# is an iterative method, where the k:th approximation\n# to the solution is calculated as\n# x⁽ᵏ⁺¹⁾ = D⁻¹(b - Rx⁽ᵏ⁾),\n# where D is the diagonal elements of A, and\n# R = A - D.\n\ntype JacobiSolver <: Solver\n    A\n    Dinv\n    R\n    tol\n    ω\n    maxiter\n    function JacobiSolver(A, tol, ω=2./3, maxiter = 10)\n        D = Diagonal(diag(A))\n        new(A, inv(D), A-D, tol, ω, maxiter)\n    end\nend\n\n# This implementation assumes that x is reasonably \"close\" to b; this\n# is the case if A = I + Ξ, with |Ξ| << 1.\nfunction solve!(b::StridedVecOrMat, J::JacobiSolver)\n    xp = ones(b)\n    x = xp\n    for k = 1:J.maxiter\n        x = J.ω*(J.Dinv*(b - J.R*xp)) + (1-J.ω)*xp\n        if norm(J.A*x-b) < J.tol\n            break\n        end\n        xp = x\n    end\n    b[:] = x\nend\n\nexport JacobiSolver, solve!\n", "meta": {"hexsha": "5a8f09b4445855245fc59fcb299477bcd8d24d62", "size": 856, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/jacobi_solver.jl", "max_stars_repo_name": "jagot/RepeatedSolvers.jl", "max_stars_repo_head_hexsha": "127de3b85be41fba8d06c7c289e257faa1d1b39a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/jacobi_solver.jl", "max_issues_repo_name": "jagot/RepeatedSolvers.jl", "max_issues_repo_head_hexsha": "127de3b85be41fba8d06c7c289e257faa1d1b39a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-04-14T20:17:05.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-14T20:17:05.000Z", "max_forks_repo_path": "src/jacobi_solver.jl", "max_forks_repo_name": "jagot/RepeatedSolvers.jl", "max_forks_repo_head_hexsha": "127de3b85be41fba8d06c7c289e257faa1d1b39a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-07T10:01:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T10:01:06.000Z", "avg_line_length": 22.5263157895, "max_line_length": 69, "alphanum_fraction": 0.5700934579, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.771678270997748}}
{"text": "\"\"\"\n    ⊗(A, B)\n\nCompute the kronecker product, ``A\\\\otimes B``.\n\n# Examples\n```julia-repl\njulia> [1 0; 0 1]⊗[1 0; 0 -1]\n4×4 Array{Int64,2}:\n 1   0  0   0\n 0  -1  0   0\n 0   0  1   0\n 0   0  0  -1\n```\n\"\"\"\n⊗(A, B) = kron(A, B)\n\n\n\"\"\"\n    ⊗(A, B, C...)\n\nCompute the kronecker product, ``A\\\\otimes B\\\\otimes C \\\\cdots``.\n\"\"\"\nfunction ⊗(A, B, C...)\n    A = kron(A, B)\n    for Ci in C\n        A = kron(A, Ci)\n    end\n    return A\nend\n", "meta": {"hexsha": "a1e32ed3ccc6ebaa8cfdc358eccad03731ea2463", "size": 428, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kronecker_product.jl", "max_stars_repo_name": "Shoichiro-Tsutsui/QuantumGate.jl", "max_stars_repo_head_hexsha": "161677e0425abd1f7993d7f9a08dc32e4d69f5fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kronecker_product.jl", "max_issues_repo_name": "Shoichiro-Tsutsui/QuantumGate.jl", "max_issues_repo_head_hexsha": "161677e0425abd1f7993d7f9a08dc32e4d69f5fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kronecker_product.jl", "max_forks_repo_name": "Shoichiro-Tsutsui/QuantumGate.jl", "max_forks_repo_head_hexsha": "161677e0425abd1f7993d7f9a08dc32e4d69f5fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.8064516129, "max_line_length": 65, "alphanum_fraction": 0.464953271, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308073258009, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7716782653356462}}
{"text": "nprocs()==1 && addprocs()\n\n@everywhere logis(x) = 1 ./ (1 .+ exp(-x))\n@everywhere dlogis(x) = logis(x) .* (1 .- logis(x))\n\n@everywhere function dfa!(w1,w2,w3,B1,B2,inp,out)\n    a1 = w1 * inp\n    z1 = logis(a1)\n    a2 = w2 * z1\n    z2 = logis(a2)\n    ay = w3 * z2\n    y = logis(ay)\n    err = y - out\n    d_a1 = (B1.*err) .* dlogis(a1) \n    d_a2 = (B2.*err) .* dlogis(a2) \n    w1 .-= d_a1 * inp'\n    w2 .-= d_a2 * z1'\n    w3 .-= err * z2'\n    return Dict(\"output\"=>y,\"err\"=>err)\nend\n\n@everywhere function bp!(bp_w1,bp_w2,bp_w3,inp,out)\n    bp_a1 = bp_w1*inp\n    bp_z1 = logis(bp_a1)\n    bp_a2 = bp_w2 * bp_z1\n    bp_z2 = logis(bp_a2)\n    bp_ay = bp_w3 * bp_z2\n    bp_y = logis(bp_ay)\n    bp_err = bp_y - out\n    bp_d_a3 = (bp_err) .* dlogis(bp_ay)\n    bp_d_a2 = (bp_w3' * bp_d_a3) .* dlogis(bp_a2)\n    bp_d_a1 = (bp_w2' * bp_d_a2) .* dlogis(bp_a1)\n    bp_w1 .-= bp_d_a1 * inp'\n    bp_w2 .-= bp_d_a2 * bp_z1'\n    bp_w3 .-= bp_d_a3 * bp_z2'\n    return Dict(\"output\"=>bp_y,\"err\"=>bp_err)\nend\n\ninp = [1 1 ; 0 1 ; 1 0 ; 0 0]'\nout = [0 1 1 0]\ny=zeros(size(out))\nn_hidden = 15; # Number of hidden units\nnum_iterations = 1000; #Number of learning steps\ntrials = 50;\n\ne_store = SharedArray(Float64,(num_iterations,trials))\nbp_e_store = SharedArray(Float64,(num_iterations,trials))\ny_store = SharedArray(Float64,(size(out,2),num_iterations))\nbp_y_store = SharedArray(Float64,(size(out,2),num_iterations))\n\n@elapsed @sync @parallel for jj = 1:trials\n    w1 = randn(n_hidden,size(inp,1))\n    w2 = randn(n_hidden,n_hidden)\n    w3 = randn(size(out,1),n_hidden)\n          \n    B1=rand(n_hidden,1)\n    B2=rand(n_hidden,1)    \n    \n    bp_w1 = randn(n_hidden,size(inp,1))\n    bp_w2 = randn(n_hidden,n_hidden)\n    bp_w3 = randn(size(out,1),n_hidden) \n    \n    for ii = 1:num_iterations       \n        dfa_res = dfa!(w1,w2,w3,B1,B2,inp,out)       \n        bp_res = bp!(bp_w1,bp_w2,bp_w3,inp,out)       \n        if jj == 1\n            y_store[:,ii] = dfa_res[\"output\"]'\n            bp_y_store[:,ii] = bp_res[\"output\"]'\n        end       \n        e_store[ii,jj] = sum(abs(dfa_res[\"err\"]))\n        bp_e_store[ii,jj] = sum(abs(bp_res[\"err\"]))\n    end\nend\n\nusing Plots\nl = @layout [\n    a b\n    c d\n]\n\ngr()\np1=plot(y_store',label=[\"1,1\" \"0,1\" \"1,0\" \"0,0\"],title=\"DFA\")\np2=plot(bp_y_store',label=[\"1,1\" \"0,1\" \"1,0\" \"0,0\"],title=\"BP\")\np3=plot([e_store[:,1] bp_e_store[:,1]],label=[\"DFA\" \"BP\"],title=\"First Trial\")\np4=plot([mean(e_store,2) mean(bp_e_store,2)],label=[\"DFA\" \"BP\"],title=\"Mean Error\")\nplot(p1,p2,p3,p4,layout=l)\n", "meta": {"hexsha": "c23085b45e09601064e249a57cb151b28763de8a", "size": 2497, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dfa-prelim.jl", "max_stars_repo_name": "ppalmes/ULTalkApril-2017", "max_stars_repo_head_hexsha": "2b0023c7504042b8092e8cf535b5af622ab0db22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-03-01T19:58:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T18:27:41.000Z", "max_issues_repo_path": "dfa-prelim.jl", "max_issues_repo_name": "ppalmes/ULTalkApril-2017", "max_issues_repo_head_hexsha": "2b0023c7504042b8092e8cf535b5af622ab0db22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dfa-prelim.jl", "max_forks_repo_name": "ppalmes/ULTalkApril-2017", "max_forks_repo_head_hexsha": "2b0023c7504042b8092e8cf535b5af622ab0db22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-03-04T11:31:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T09:16:37.000Z", "avg_line_length": 28.7011494253, "max_line_length": 83, "alphanum_fraction": 0.5851021225, "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776496, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7716782628813433}}
{"text": "\"\"\"\n    dominates(p1::Array, p2::Array)\n\n    Return true if each element in p1 is not less than the corresponding element in p2 and at least one element in p1 is bigger than the corresponding element in p2.\n\n# Arguments\n- `p1::Array`: Numeric array of n elements.\n- `p2::Array`: Numeric array of n elements.\n\n# Examples\n```julia-repl\njulia> dominates([1,2,3], [1,2,1])\ntrue\njulia> dominates([0,0,0,0], [1,0,0,0])\nfalse\n```\n\n# References\nDeb, Kalyanmoy, et al. \"A fast elitist non-dominated sorting genetic algorithm for multi-objective optimization: NSGA-II.\" \nInternational conference on parallel problem solving from nature. Springer, Berlin, Heidelberg, 2000.\n\"\"\"\nfunction dominates(p1::Array, p2::Array)::Bool\n    n = length(p1)\n    notworse = count(i -> p1[i] < p2[i], 1:n)\n    better   = count(i -> p1[i] > p2[i], 1:n)\n    return (notworse == 0) && (better > 0)\nend\n\n\n\n\"\"\"\n    ndsranks(data)\n\n    Sort multidimensional data usin non-dominated sorting algorithm.\n\n# Arguments\n- `data::DataFrame`: DataFrame of variables.\n\n# References\nDeb, Kalyanmoy, et al. \"A fast elitist non-dominated sorting genetic algorithm for multi-objective optimization: NSGA-II.\" \nInternational conference on parallel problem solving from nature. Springer, Berlin, Heidelberg, 2000.\n\"\"\"\nfunction ndsranks(data::DataFrame)::Array{Int}\n    \n    mat = convert(Matrix, data)\n    \n    return ndsranks(mat)\n\nend\n\n\n\n\"\"\"\n    ndsranks(data)\n\n    Sort multidimensional data usin non-dominated sorting algorithm.\n\n# Arguments\n- `data::Matrix`: n x k matrix of observations where n is number of observations and k is number of variables.\n\n# Examples\n```julia-repl\n  \n```\n\n# References\nDeb, Kalyanmoy, et al. \"A fast elitist non-dominated sorting genetic algorithm for multi-objective optimization: NSGA-II.\" \nInternational conference on parallel problem solving from nature. Springer, Berlin, Heidelberg, 2000.\n\"\"\"\nfunction ndsranks(data::Matrix)::Array{Int64}\n    \n    n, p = size(data)\n\n    ranks = zeros(Int64, n)\n    \n    mat = convert(Matrix, data)\n    \n    @inbounds for i in 1:n\n        @inbounds for j in 1:n\n            if i != j \n                if dominates(mat[i,:], mat[j,:])\n                    ranks[i] += 1\n                end\n            end\n        end\n    end\n\n    return ranks\nend\n\n\n\nfunction nds(data::DataFrame)\n\n    ranks = ndsranks(data)\n\n    bestIndex = sortperm(ranks) |> last\n\n    result = NDSResult(\n        ranks,\n        bestIndex\n    )\n\n    return result\nend\n\n\n", "meta": {"hexsha": "505dc5a0c29cac388ee8e0b6ad563a58da07b8cd", "size": 2463, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nds.jl", "max_stars_repo_name": "ersagunkuruca/JMcDM", "max_stars_repo_head_hexsha": "d7caeb1b039e022ca0959355fba00465795a2d70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nds.jl", "max_issues_repo_name": "ersagunkuruca/JMcDM", "max_issues_repo_head_hexsha": "d7caeb1b039e022ca0959355fba00465795a2d70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nds.jl", "max_forks_repo_name": "ersagunkuruca/JMcDM", "max_forks_repo_head_hexsha": "d7caeb1b039e022ca0959355fba00465795a2d70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8055555556, "max_line_length": 165, "alphanum_fraction": 0.6601705238, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308054739519, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7716782598194527}}
{"text": "using LinearAlgebra\n\nA = [2 3 0;\n     1 2 4;\n     0 2 1]\n\nprintln(\"A+A=\", A+A)\nprintln(\"A-A=\", A-A)\nprintln(\"A*A=\", A*A)\nprintln(\"5*A=\", 5*A)", "meta": {"hexsha": "b3cfec2b41efa2cfe12dc058bc5bf3af27ef40db", "size": 141, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear_algebra/basic_operation.jl", "max_stars_repo_name": "nocotan/numerical_calculus.jl", "max_stars_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-07T06:26:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T06:21:01.000Z", "max_issues_repo_path": "linear_algebra/basic_operation.jl", "max_issues_repo_name": "nocotan/numerical_calculus.jl", "max_issues_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-01-10T08:22:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-08T13:31:00.000Z", "max_forks_repo_path": "linear_algebra/basic_operation.jl", "max_forks_repo_name": "nocotan/numerical_calculus.jl", "max_forks_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-10T05:59:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T13:22:34.000Z", "avg_line_length": 14.1, "max_line_length": 20, "alphanum_fraction": 0.5106382979, "num_tokens": 63, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308147331958, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7716782595036823}}
{"text": "# squared Euclidean distance from a set\n\nexport SqrDistL2\n\n\"\"\"\n**Squared distance from a convex set**\n\n    SqrDistL2(ind_S, λ=1.0)\n\nGiven `ind_S` the indicator function of a convex set ``S``, and an optional positive parameter `λ`, returns the (weighted) squared Euclidean distance from ``S``, that is function\n```math\ng(x) = \\\\tfrac{λ}{2}\\\\mathrm{dist}_S^2(x) = \\\\min \\\\left\\\\{ \\\\tfrac{λ}{2}\\\\|y - x\\\\|^2 : y \\\\in S \\\\right\\\\}.\n```\n\"\"\"\nstruct SqrDistL2{R <: Real, T <: ProximableFunction} <: ProximableFunction\n  ind::T\n  lambda::R\n  function SqrDistL2{R,T}(ind::T, lambda::R) where {R <: Real, T<:ProximableFunction}\n    if !is_convex(ind) || !is_set(ind)\n      error(\"`ind` must be the indicator of a convex set\")\n    end\n    if lambda < 0\n      error(\"parameter λ must be nonnegative\")\n    else\n      new(ind, lambda)\n    end\n  end\nend\n\nis_prox_accurate(f::SqrDistL2) = is_prox_accurate(f.ind)\nis_convex(f::SqrDistL2) = true\nis_smooth(f::SqrDistL2) = true\nis_quadratic(f::SqrDistL2) = is_affine(f.ind)\nis_strongly_convex(f::SqrDistL2) = is_singleton(f.ind)\n\nSqrDistL2(ind::T, lambda::R=1.0) where {R <: Real, T <: ProximableFunction} = SqrDistL2{R, T}(ind, lambda)\n\nfunction (f::SqrDistL2)(x::AbstractArray{T}) where T <: RealOrComplex\n  p, = prox(f.ind, x)\n  return (f.lambda/2)*normdiff2(x,p)\nend\n\nfunction prox!(y::AbstractArray{T}, f::SqrDistL2, x::AbstractArray{T}, gamma::Real=1.0) where T <: RealOrComplex\n  p, = prox(f.ind, x)\n  sqrd = (f.lambda/2)*normdiff2(x,p)\n  c1 = 1/(1+f.lambda*gamma)\n  c2 = f.lambda*gamma*c1\n  for k in eachindex(p)\n    y[k] = c1*x[k] + c2*p[k]\n  end\n  return sqrd*c1^2\nend\n\nfunction gradient!(y::AbstractArray{T}, f::SqrDistL2, x::AbstractArray{T}) where T <: RealOrComplex\n  p, = prox(f.ind, x)\n  dist2 = normdiff2(x,p)\n  y .= f.lambda.*(x .- p)\n  return (f.lambda/2)*dist2\nend\n\nfun_name(f::SqrDistL2) = \"squared Euclidean distance from a convex set\"\nfun_dom(f::SqrDistL2) = fun_dom(f.ind)\nfun_expr(f::SqrDistL2) = \"x ↦ (λ/2) inf { ||x-y||^2 : y ∈ S} \"\nfun_params(f::SqrDistL2) = string(\"λ = $(f.lambda), S = \", typeof(f.ind))\n\nfunction prox_naive(f::SqrDistL2, x::AbstractArray{T}, gamma::Real=1.0) where T <: RealOrComplex\n  p, = prox(f.ind, x)\n  sqrd = (f.lambda/2)*norm(x-p)^2\n  gamlam = f.lambda*gamma\n  return 1/(1+gamlam)*x + gamlam/(1+gamlam)*p, sqrd/(1+gamlam)^2\nend\n", "meta": {"hexsha": "160aaf7c4d70064dec30bd4809041db4cb114508", "size": 2315, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/calculus/sqrDistL2.jl", "max_stars_repo_name": "lostella/ProximalOperators.jl", "max_stars_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-15T13:57:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T13:57:52.000Z", "max_issues_repo_path": "src/calculus/sqrDistL2.jl", "max_issues_repo_name": "lostella/ProximalOperators.jl", "max_issues_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/calculus/sqrDistL2.jl", "max_forks_repo_name": "lostella/ProximalOperators.jl", "max_forks_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1527777778, "max_line_length": 178, "alphanum_fraction": 0.6552915767, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258009, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7716782573651499}}
{"text": "# ---\n# title: 462. Minimum Moves to Equal Array Elements II\n# id: problem462\n# author: Indigo\n# date: 2021-02-04\n# difficulty: Medium\n# categories: Math\n# link: <https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/description/>\n# hidden: true\n# ---\n# \n# Given a **non-empty** integer array, find the minimum number of moves required\n# to make all array elements equal, where a move is incrementing a selected\n# element by 1 or decrementing a selected element by 1.\n# \n# You may assume the array's length is at most 10,000.\n# \n# **Example:**\n# \n#     \n#     \n#     Input:\n#     [1,2,3]\n#     \n#     Output:\n#     2\n#     \n#     Explanation:\n#     Only two moves are needed (remember each move increments or decrements one element):\n#     \n#     [1,2,3]  =>  [2,2,3]  =>  [2,2,2]\n#     \n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction min_moves2(nums::Vector{Int})\n    median = partialsort!(nums, (length(nums) + 1) ÷ 2)\n    return sum(abs, num - median for num in nums)\nend\n## @lc code=end\n", "meta": {"hexsha": "f593554e2d8a364f35a253fddd443919af0ccb22", "size": 1010, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/462.minimum-moves-to-equal-array-elements-ii.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/462.minimum-moves-to-equal-array-elements-ii.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/462.minimum-moves-to-equal-array-elements-ii.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 23.488372093, "max_line_length": 93, "alphanum_fraction": 0.6326732673, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308054739519, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7716782538415804}}
{"text": "\"\"\"\r\n    fm = mergespec_spaceonly(ra,f,kmax)\r\n\r\nSpectral merging of coarse field `ra` and fine field `f` at wavenumber `kmax`.\r\n\"\"\"\r\nfunction mergespec_spaceonly(ra,f,kmax)\r\n\r\n(nx,ny)=size(f);\r\n(nax,nay)=size(ra);\r\n\r\nDFTr=zeros(Complex{Float64},nax,nax);\r\nDFTf=zeros(Complex{Float64},nx,nx);\r\n\r\n#fft di tutto il campo f\r\nDFTf=fft(f)\r\n   \r\n#fft di tutto il campo r\r\nDFTr=fft(ra);\r\n\r\nDFTr=fftshift(DFTr); #centro la fft\r\nDFTf=fftshift(DFTf); #centro la fft\r\nDFTfm=zeros(Complex{Float64},nx,nx);\r\nDFTr2=zeros(Complex{Float64},nax+1,nax+1);\r\n\r\n#DFTr[nax+1,:,:]=NaN;\r\n#DFTr[:,nax+1,:]=NaN;\r\nDFTr2[1:nax,1:nax]=DFTr[:,:]\r\nDFTr2[nax+1,1:nax]=conj(DFTr[1,:]);\r\nDFTr2[1:nax,nax+1]=conj(DFTr[:,1]);\r\n\r\nkmax2=kmax^2;\r\n\r\n# We need to fix the phases of the large scale field!\r\n# The first pixel of the large field is centered in dxl/2 with dxl=2pi/nax\r\n# The first pixel of the fine field is centered in dxs/2 with dxf=2pi/nax\r\nddx=2*pi/nax/2-2*pi/nx/2;\r\n\r\n for j=1:nx\r\n     for i=1:nx\r\n            kx=-div(nx,2)+i-1;\r\n            ky=-div(nx,2)+j-1;\r\n            k2=(kx^2+ky^2); \r\n            ir=div(nax,2)+1+kx;\r\n            jr=div(nax,2)+1+ky;\r\n            if(k2<=kmax2)\r\n                DFTfm[i,j]=DFTr2[ir,jr]*exp(-1im*ddx*kx-1im*ddx*ky);;\r\n            else\r\n                DFTfm[i,j]=DFTf[i,j];\r\n            end\r\n     end\r\nend\r\n\r\nDFTfm=ifftshift(DFTfm);\r\nfm=ifft(DFTfm);\r\nfm=real(fm);\r\n\r\nend\r\n", "meta": {"hexsha": "31308f08b82a4d9de09b79058abe4fc988bba8a1", "size": 1386, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rf/mergespec_spaceonly.jl", "max_stars_repo_name": "UnofficialJuliaMirror/RainFARM.jl-e9a4e08f-a0a3-5224-a821-6d0231c12d6b", "max_stars_repo_head_hexsha": "740f4edff721692e13168b132503aa62d5fea574", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rf/mergespec_spaceonly.jl", "max_issues_repo_name": "UnofficialJuliaMirror/RainFARM.jl-e9a4e08f-a0a3-5224-a821-6d0231c12d6b", "max_issues_repo_head_hexsha": "740f4edff721692e13168b132503aa62d5fea574", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rf/mergespec_spaceonly.jl", "max_forks_repo_name": "UnofficialJuliaMirror/RainFARM.jl-e9a4e08f-a0a3-5224-a821-6d0231c12d6b", "max_forks_repo_head_hexsha": "740f4edff721692e13168b132503aa62d5fea574", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8965517241, "max_line_length": 79, "alphanum_fraction": 0.5800865801, "num_tokens": 522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258009, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7716782533799016}}
{"text": "haversine(lat1, lon1, lat2, lon2) =\n    2 * 6372.8 * asin(sqrt(sind((lat2 - lat1) / 2) ^ 2 +\n    cosd(lat1) * cosd(lat2) * sind((lon2 - lon1) / 2) ^ 2))\n\n@show haversine(36.12, -86.67, 33.94, -118.4)\n", "meta": {"hexsha": "2331c2b90612784887cec40d80459cb95bc78ae4", "size": 200, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/haversine-formula.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/haversine-formula.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/haversine-formula.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3333333333, "max_line_length": 59, "alphanum_fraction": 0.56, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9793540728763411, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7716636304762184}}
{"text": "module HWfuncapp\n\nusing FastGaussQuadrature # to get chebyshevnodes\n\n# you dont' have to use PyPlot. I did much of it in PyPlot, hence\n# you will see me often qualify code with `PyPlot.plot` or so.\nusing PyPlot  \nimport ApproXD: getBasis, BSpline\nusing Distributions\nusing ApproxFun\nusing Plots\nexport TT, ChebyT, q1\n\n\nChebyT(x,deg) = cos(acos(x)*deg)\nunitmap(x,lb,ub) = 2 .* (x .- lb) ./ (ub .- lb) .- 1\t#[a,b] -> [-1,1]\n\nn=15\nmap(x,lb,ub) = 0.5 .* (lb .+ ub) .+ 0.5 .* (ub .- lb) .* x\n\nfunction Cheby(x,deg)\nlen=length(x)\npsi = ones(len,deg)\nfor i in 1:len\nfor j in 1:deg\npsi[i,j] = ChebyT(x[i],j-1) \nend\nend\nreturn psi\nend\n\n\n\nfunction q1(n=15)\nlb, ub, inter, Nod = -3, 3, 100, gausschebyshev(n)[1]#Values for evaluation\nx = range(lb,stop = ub,length = n)#\npsi = map(Nod, lb, ub) #Evaluation\n    \nf(x) = x .+ 2x.^2 - exp.(-x)#Function to evaluate\nPSI=inv(Cheby(Nod,n))\nev=f(psi)\nResEv=PSI*ev\n    \ntestX=range(lb, stop=ub, length=inter)\ntestY=f(testX)\n   \ntestMap=map(testX, lb, ub)\ntestPsi=Cheby(unitmap(testMap), n)\n\nResEv=testPsi*PSI\n    \ntestError=ev-ResEv\n \n#PyPlot.plot()   \np = Plots.plot(layout = 2, dpi = 400)\nPlots.plot!(p[1],testX,testY,label = \"Test Y\",lw = 1,linecolor = \"black\")\nPlots.plot!(p[1],testX,ResEv, label = \"Result Evaluation\", lw = 2,linestyle = :dot, linecolor = \"pink\")\nPlots.plot!(p[2],testX,testError, label = \"Test Error\", lw = 1, linecolor = \"blue\")\n    \n# without using PyPlot, just erase the `PyPlot.` part\nPyPlot.savefig(joinpath(dirname(@__FILE__),\"..\",\"q1.png\"))\nreturn Dict(:error=>maximum(abs,err))\nend\n\n\nend # module\n\n\n\n", "meta": {"hexsha": "42907861bad72ae941cfb20ca7e70c63f0371dee", "size": 1560, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HWfuncapp.jl", "max_stars_repo_name": "nicolasghio/HWfuncapp.jl", "max_stars_repo_head_hexsha": "0cc811062fc157403c392b8c89f6e586f3a43687", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HWfuncapp.jl", "max_issues_repo_name": "nicolasghio/HWfuncapp.jl", "max_issues_repo_head_hexsha": "0cc811062fc157403c392b8c89f6e586f3a43687", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HWfuncapp.jl", "max_forks_repo_name": "nicolasghio/HWfuncapp.jl", "max_forks_repo_head_hexsha": "0cc811062fc157403c392b8c89f6e586f3a43687", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2857142857, "max_line_length": 103, "alphanum_fraction": 0.6557692308, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7716405210377828}}
{"text": "# ## 多項式回帰\n# ### 例52\n# sin関数に乱数を足した観測データを多項式で回帰します。\n# \\lineskip\n# データの生成\nusing Plots, Joe, Random\nusing Plots.PlotMeasures # hide\nPlots.reset_defaults() # hide\ngr() # hide\ndefault( # hide\n    titlefont  = font(\"JuliaMono\", default(:titlefontsize),  ), # hide\n    guidefont  = font(\"JuliaMono\",  default(:guidefontsize),  ), # hide\n    tickfont   = font(\"JuliaMono\", default(:tickfontsize),   ), # hide\n    legendfont = font(\"JuliaMono\",  default(:legendfontsize), ), # hide\n    left_margin = 30px, # hide\n    bottom_margin = 30px # hide\n) # hide\nRandom.seed!(12)\nn = 100; x = randn(n); y = sin.(x) + randn(n);\np52 = scatter(x,y,xlabel=\"x\", ylabel=\"y\", label=false, legend=:topleft);\n# 3、5、7次の多項式で回帰します。\n# 多項式回帰用にデータセットを作る関数を定義したので、これを使ってみます。\n# ```julia\n# polynomial(x::Vector, P::Int) = hcat([x.^p for p in 1:P]...)\n# polynomial(x::AbstractRange, P::Int)= polynomial(collect(x),P)\n# ```\nusing Joe:polynomial\np_set = [3,5,7]\nx_seq = -3:0.1:3 \nfor p in p_set\n    global x, y, x_seq, p52 # hide\n    X = polynomial(x,p)\n    β̂ = multiple_regression(X,y)\n    ŷ = insert_ones(polynomial(x_seq,p))*β̂\n    plot!(p52, x_seq,ŷ,label=\"p = $p\")\nend\nsavefig(p52,joinpath(@OUTPUT,\"fig6-1.svg\")) # hide\n# \\fig{fig6-1}\n# ### 例53\n# 矩形波に雑音をノイズをのせたデータを作って、フィッティングします。\n# まずはデータを生成します。\nusing Plots, Random\nRandom.seed!(123)\nn = 100; x = randn(n) * π\ny = abs.(round.(x) .%2) * 2  .- 1+ randn(n)*0.2 \np53 = scatter(x,y,label= false);\n# 基底関数が、$f_1(x) = 1$、 $f_2(x) = \\cos(x) $、 $f_3(x) = \\cos(2x)$、\n# $f_4(x) = \\cos(3x)$の場合と、$f_1(x) = 1$、 $f_2(x) = \\sin(x) $、 $f_3(x) = \\sin(2x)$、\n# $f_4(x) = \\sin(4x)$の場合とでそれぞれ回帰分析します。\n# 準備として先ほどのpolynomial関数をべき乗以外にも対応できるように多重ディスパッチで拡張します。\n# ```julia\n# polynomial(x::Vector, P::Int, f::Function) = hcat([f.(p*x) for p in 1:P]...)\n# polynomial(x::AbstractRange, P::Int, f::Function) = polynomial(collect(x), P, f)\n# ```\n# $(-8,8)$の区間でフィッティングします。\nx_seq = -8:0.2:8\n# cosの場合\nX_cos = polynomial(x,3,cos)\nβ̂_cos = multiple_regression(X_cos,y)\nŷ_cos = insert_ones(polynomial(x_seq,3,cos))*β̂_cos;\n# sinの場合\nX_sin = polynomial(x,3,sin)\nβ̂_sin = multiple_regression(X_sin,y)\nŷ_sin = insert_ones(polynomial(x_seq,3,sin))*β̂_sin;\n# 可視化します。\nplot!(p53,x_seq,ŷ_cos,label=\"cos\")\nplot!(p53,x_seq,ŷ_sin,label=\"sin\")\nsavefig(p53,joinpath(@OUTPUT,\"fig6-2.svg\")) # hide\n# \\fig{fig6-2}\n# \\lineskip\n# cosを基底にとったほうが、上手くフィッティングできることが確認できました。\n# ## スプライン回帰\n# スプライン回帰については、まずスプラインに関する複合型を作って、\n# function-like objectを実装しました。\n# spline_matrix関数は、あとで変更できるようにキーワード引数にしました。\n# \n# ```julia\n# using Parameters\n# @with_kw mutable struct Spline{T<:Number}\n#     xmin::T = -1.0\n#     xmax::T = 1.0\n#     K::Int = 5\n# end \n# function spline_matrix(x::Vector,K::Int,xmin,xmax)\n#     n = length(x)\n#     Knots = range(xmin,stop=xmax,length=K)\n#     X = zeros(n,K+4)\n#     X[:,1] .= 1\n#     X[:,2] .= x\n#     X[:,3] .= x.^2\n#     X[:,4] .= x.^3\n#     for j in 1:K \n#         X[:,j+4] = @. max(x - Knots[j], 0)^3\n#     end\n#     return X\n# end\n# function (s::Spline)(x::Vector, y::Vector, x_pred::Vector;\n#           spline_matrix::Function=spline_matrix)\n#     @unpack xmin, xmax, K = s\n#     Knots = range(xmin,stop=xmax,length=K)\n#     X = spline_matrix(x,K,xmin,xmax)\n#     X_pred = spline_matrix(x_pred,K,xmin,xmax)\n#     β = (X'X)\\X'y\n#     ypred = X_pred*β\n# end\n# (s::Spline)(x::Vector, y::Vector, x_pred::AbstractRange;kwargs...) = s(x,y,collect(x_pred);kwargs...)\n# ```\n# ### 例54\n# sinカーブに乱数を加えたデータにスプライン回帰でフィッティングします。\n# 分割点数が7以上でデータに追随していることがわかります。\nusing Plots, Random\nusing Joe: Spline\nusing Joe\nRandom.seed!(123)\nn = 100; x = randn(n)*2π; y = sin.(x) + 0.2randn(n)\np54 = scatter(x,y,xlims=(-5,5),xlabel=\"x\",ylabel=\"f(x)\",label=false)\nK_set = 5:2:9 \nfor K in K_set\n    spline = Spline(xmin=-2π, xmax=2π, K=K)\n    u_seq = -5:0.2:5\n    v_seq = spline(x,y,u_seq)\n    plot!(p54, u_seq,v_seq, label=\"K = $K\")\nend\nsavefig(p54,joinpath(@OUTPUT,\"fig6-5.svg\")) # hide\n# \\fig{fig6-5}\n# ### 例56 自然なスプライン曲線\n# スプライン曲線の両端が直線になっているものです。\n# 原著では、関数dとか関数hを定義して使っていました。\n# そんなことはしたくないけど、いい名前もないので、関数内で定義して使うことにしました。\n# ```julia\n# function natural_spline_matrix(x::Vector, K::Int, xmin, xmax)\n#     n = length(x)\n#     Knots = range(xmin,stop=xmax,length=K)\n#     X = zeros(n,K)\n#     X[:,1] .= 1\n#     X[:,2] .= x\n#     d(x::Vector,a::Number,b::Number) =  @. (max(x-a,0)^3 - max(x-b,0)^3) / (b-a)\n#     for j in 1:K-2\n#         X[:,j+2] = d(x,Knots[j],Knots[end]) - d(x,Knots[end-1],Knots[end])\n#     end\n#     return X\n# end\n# ```\n# 例54と同じデータに、ただのスプラインと自然なスプラインの回帰を適用し、\n# 結果を可視化します。まずデータの生成とスプライン型を定義します。\nusing Plots, Random\nusing Joe: Spline\nusing Joe\nRandom.seed!(123)\nn = 100; x = randn(n)*2π; y = sin.(x) + 0.2randn(n)\nspline6 = Spline(xmin=-5, xmax=5, K=6);\nspline11 = Spline(xmin=-5, xmax=5, K=11);\n# 次に回帰を行います。自然なスプラインで回帰を行う場合には、キーワード引数を指定します。\nu_seq = -6:0.02:6;\nv_seq6 = spline6(x,y,u_seq);\nv_seq11 = spline11(x,y,u_seq);\nw_seq6 = spline6(x,y,u_seq;splinematrix=Joe.natural_spline_matrix);\nw_seq11 = spline11(x,y,u_seq;splinematrix=Joe.natural_spline_matrix);\n# 可視化します。\np56_1 = scatter(x,y,xlims=(-7,7),xlabel=\"x\",ylabel=\"f(x),g(x)\",label=false,title=\"K=6\")\np56_2 = scatter(x,y,xlims=(-7,7),xlabel=\"x\",ylabel=\"f(x),g(x)\",label=false,title=\"K=11\")\nplot!(p56_1,u_seq,v_seq6,label=\"spline\")\nplot!(p56_1,u_seq,w_seq6,label=\"natural spline\")\nvline!(p56_1,[-5,5];linewidth=1,label=false)\nvline!(p56_1,range(-5,stop=5,length=6);linestyle=:dash,label=false)\nplot!(p56_2,u_seq,v_seq11,label=\"spline\")\nplot!(p56_2,u_seq,w_seq11,label=\"natural spline\")\nvline!(p56_2,[-5,5];linewidth=1,label=false)\nvline!(p56_2,range(-5,stop=5,length=11);linestyle=:dash,label=false)\np56 = plot(p56_1,p56_2,layout=(2,1))\nsavefig(p56,joinpath(@OUTPUT,\"fig6-7.svg\")) # hide\n# \\fig{fig6-7}\n# ## 平滑化スプライン\n# 平滑化スプラインは区切り点を指定するときにデータ点自身を使っていたので、\n# 以下のように書き直しました。(function-like objectにするまでもなかった。)\n# ```julia\n# struct SmoothingSpline\n#     x::Vector\n# end\n# function (s::SmoothingSpline)(y::Vector,x_pred::Union{Vector,AbstractRange};λ=0)\n#     x = s.x\n#     X = smoothing_spline_matrix(x,x)\n#     G = green_silverman(x)\n#     γ = (X'X + λ*G)\\X'y\n#     X_pred = smoothing_spline_matrix(x_pred,x)\n#     ypred = X_pred*γ\n# end\n# ```\n# ただし、smoothing_spline_matrixとgreen_silverman関数は以下の通りです。\n# ```julia\n# function smoothing_spline_matrix(x::Vector,Knots::Union{Vector, AbstractRange})\n#     n = length(x)\n#     K = length(Vector)\n#     X = zeros(n,K)\n#     X[:,1] .= 1\n#     X[:,2] .= x\n#     d(x::Vector,a::Number,b::Number) =  @. (max(x-a,0)^3 - max(x-b,0)^3) / (b-a)\n#     for j in 1:K-2\n#         X[:,j+2] = d(x,Knots[j],Knots[end]) - d(x,Knots[end-1],Knots[end])\n#     end\n#     return X\n# end\n\n# function green_silverman(x::Vector)\n#     n = length(x)\n#     g = zeros(n,n)\n#     for i in 3:n ,j in i:n\n#         g[j,i] =(12(x[end]-x[end-1])*(x[end-1]-x[j-2])*(x[end-1]-x[i-2])+\n#                 (x[end-1]-x[j-2])^2*(12x[end-1]+6x[j-2]-18x[i-2]))/\n#                 (x[end]-x[i-2])/(x[end]-x[j-2])\n#         g[i,j] = g[j,i]\n#     end\n#     return g\n# end\n# ```\n# ### 例57\n# $x\\in(-5,5)$の一様分布からサンプルを生成します。\n# 原著では、サンプル生成コードが間違っているようなので、ipynbの記述を参照しました。\nusing Plots, Random, Distributions\nusing Joe: SmoothingSpline\nusing Joe\nRandom.seed!(11)\nn = 100;\nx = rand(Uniform(-5,5),n); y = x .+ 2sin.(x) + randn(n)\nindex = sortperm(x); x = x[index]; y = y[index]\n\np57 = scatter(x,y,label=false)\n\nsspline = SmoothingSpline(x)\nu_seq = -8:0.02:8\nλ_set = [40,400,1000]\nfor λ in λ_set\n    global u_seq, p57 # hide\n    v_seq = sspline(y,u_seq,λ=λ)\n    plot!(p57,u_seq,v_seq,label=\"λ = $λ\")\nend\np57\nplot!(p57,u_seq,sspline(y,u_seq,λ=1),label=\"λ = 1\")\nsavefig(p57,joinpath(@OUTPUT, \"fig6-8.svg\")) # hide\n# \\fig{fig6-8}\n# \\lineskip\n# $\\lambda$が大きくなると、直線に近くなっていくようです。\n# ### 例58 クロスバリデーションによる平滑化スプラインの正則化乗数の最適化\n# 3章で使った線形回帰の場合の高速なクロスバリデーションの公式\n# $$CV[\\lambda] \\coloneqq \\sum_{S}||(I - H_S[\\lambda])^{-1}e_S ||^2$$\n# $$H_S[\\lambda] \\coloneqq X_s(X^\\mathsf{T}X+\\lambda G)^{-1}X^\\mathsf{T}_S$$\n# を利用して、$\\lambda$の最適化を行います。\n# 以下のcv_ss_fast関数を定義して利用します。\n# ```julia\n# function cv_ss_fast(X::AbstractArray,y::Vector,G::AbstractArray,K::Int;λ=0)\n#     n = length(y); m = round(Int,n/K)\n#     H = X*((X'X + λ*G)\\X')\n#     e = (I(n) - H)*y\n#     S = 0\n#     @views for j in 1:K\n#         test = j*m-m+1:j*m;\n#         err = (I(m)-H[test,test]) \\ e[test]\n#         S += dot(err,err)\n#     end\n#     return S/n,tr(H)\n# end\n# ```\n# 3章の使ったcv_fast関数とほぼ同様ですが、定数項の列を付けないことと、\n# 正則化乗数が引数になっていること、クロスバリデーション誤差だけでなく、\n# Hのトレースも返していることなどが異なります。\n# まずはデータを生成します。\nusing Random, Distributions\nRandom.seed!(11)\nn = 100; x = rand(Uniform(-5,5),n) ; y = x -0.02sin.(x)-0.1randn(n);\nindex = sortperm(x); x = x[index]; y = y[index];\n# XとGを計算します。\nX = Joe.smoothing_spline_matrix(x,x);\nG = Joe.green_silverman(x);\n# クロスバリデーション誤差とHのトレース(有効自由度)を求めます。\nresult = hcat([collect(Joe.cv_ss_fast(X,y,G,n,λ=λ)) for λ in 1:50]...)\nusing Plots\np58 = plot(result[2,:], result[1,:],label= false, \n            xlabel=\"有効自由度\", ylabel=\"CVによる予測誤差\",\n            title = \"有効自由度とCVによる予測誤差\")\nsavefig(p58,joinpath(@OUTPUT,\"fig6-9.svg\")) \n# \\fig{fig6-9}\n# \\lineskip\n# (注)ちなみに生成するデータによって、グラフの形はかなり変わります。\n# ## 局所回帰\n# ### 例60 nadaraya-watson推定量\n# nadaraya-watson推定量の計算の実装です。\n# カーネルは関数の引数にして、別のものに変更できるようにしました。(ここでは他のカーネルは出てきませんが。)\n# ```julia\n# epanechnikov(x,y,λ) = norm(x-y)/λ |> c -> max(0.75*(1-c^2),0)\n# \n# function nadaraya_watson_estimator(x_observed::Vector,y_observed::Vector,kk::Function,x_pred::TP;λ=1.0) where {TP<:Number}\n#     n = length(y_observed)\n#     S = 0; T = 0;\n#     for i in 1:n\n#         S += kk(x_observed[i],x_pred,λ)*y_observed[i]\n#         T += kk(x_observed[i],x_pred,λ)\n#     end\n#     result = T == 0 ? 0 : S/T\n#     return result\n# end\n# ベクトル化にも対応しています。\n# function nadaraya_watson_estimator(x_observed::Vector,y_observed::Vector,kk::Function,x_pred::Union{Vector,AbstractRange};λ=1.0) \n#     y_pred = [nadaraya_watson_estimator(x_observed,y_observed,kk,xp; λ) for xp in x_pred]\n# end\n# ```\n# \\note{epanechnikoc関数に絶対値の処理は必要になりますが、abs関数を使うよりもLinearAlgebra.jlのnormを使った方が、多次元化に対応できて良いと思います。}\n# トイデータとしてsin関数にノイズをのせたデータを作成します。\nusing Random\nRandom.seed!(123)\nn=250;x = 2randn(n); y = sin.(2π*x) + randn(n)/4\n\nusing Plots\np58 = scatter(x,y,xlims=(-3,3),label=false)\nxx = -3:0.1:3\nusing Joe:nadaraya_watson_estimator, epanechnikov\nusing LinearAlgebra\n# $\\lambda=0.05,0.25$の場合にプロットしてみます。\nplot!(p58,xx,nadaraya_watson_estimator(x,y,epanechnikov,xx;λ=0.05),\n         label=\"λ = 0.05\");\nplot!(p58,xx,nadaraya_watson_estimator(x,y,epanechnikov,xx;λ=0.25),\n         label=\"λ = 0.25\");\n# クロスバリデーションで$\\lambda$を最適化してプロットしてみます。\nλ_seq = 0.05:0.01:1\nSS_min = Inf\nλ_best = λ_seq[1]\nfor λ in λ_seq\n    global SS_min, λ_best,n,x,y # hide\n    SS = 0\n    m = Int(n/10)\n    for k in 1:10\n        test = k*m-m+1:k*m\n        train = setdiff(1:n,test)\n        y_pred = nadaraya_watson_estimator(x[train],y[train],epanechnikov,x[test];λ=λ)\n        SS += dot(y[test]-y_pred,y[test]-y_pred)\n    end\n    if SS < SS_min\n        SS_min = SS\n        λ_best = λ\n    end\nend\n\nplot!(p58,xx,nadaraya_watson_estimator(x,y,epanechnikov,xx;λ=λ_best), label=\"λ = λ_best\")\nsavefig(p58,joinpath(@OUTPUT,\"fig6-10.svg\")) # hide\n# \\fig{fig6-10}\n# \\lineskip\n# $\\lambda_{best}$はこの程度の値になるようです。\n@show λ_best;\n# ### 例61 局所線形回帰\n# カーネル関数$k$を成分に持った対角行列$\\bm{W}$を\n# $$\\bm{W} = \\begin{bmatrix}\n#  k(x,x_1) & \\cdots & 0 \\\\\n#  \\vdots & \\ddots & \\vdots \\\\\n#  0 & \\cdots & k(x,x_n) \\end{bmatrix} $$\n# とした時、\n# $$ L \\coloneqq (\\bm{y} - \\bm{Xβ}(x))^\\mathsf{T}\\bm{W}(\\bm{y} - \\bm{Xβ}(x)) $$\n# を最小化する$\\bm{\\beta}(x)$を求めます。\n# $$ \\dfrac{\\partial L}{\\partial \\bm{\\beta}} = \n# -2\\bm{X}^\\mathsf{T}\\bm{W}(\\bm{y} - \\bm{Xβ}(x))=0$$とおくと、\n# $$ \\bm{\\beta}(x) = (\\bm{X}^\\mathsf{T}\\bm{WX})^{-1}\\bm{X}^\\mathsf{T}\\bm{Wy}$$\n# で係数を求めることができます。この処理を関数で実装するわけですが、原著のlocalという関数名は良くないので、\n# local_regressionという名前で実装しました。例では1次元に限定していましたが、\n# 多次元データにも対応させています。\n# ```julia\n# function local_regression(x::Matrix{T}, \n#                           y::Vector{T},\n#                           kernel::Function;\n#                           x_pred=x, λ=1) where {T<:Number}\n#     N,_ = size(x)\n#     @assert N==length(y)\n#     X = insert_ones(x)\n#     m,_ = size(x_pred) \n#     y_pred = Vector{T}(undef,m)\n#     for j in 1:m\n#         W = [kernel(x[i,:],x_pred[j,:],λ) for i in 1:N] |> diagm\n#         β̂ = (X'*W*X)\\X'*W*y\n#         y_pred[j] = dot(insert_ones(x_pred[j,:]),β̂)\n#     end\n#     return y_pred\n# end\n# function local_regression(x::Vector{T}, y::Vector{T},kernel::Function;x_pred=x,λ=1) where {T<:Number}\n#     return local_regression(x[:,:],y,kernel;x_pred=x_pred[:,:],λ=λ)\n# end\n# ```\n# トイデータとしてsin関数にノイズをのせたデータを作成します。\nusing Random,Joe\nRandom.seed!(123)\nn=30; x = 2π*rand(n) .- π; y = sin.(x) .+ randn()\np61 = scatter(x,y,label=false)\nm = 200;U = -π:π/m:π;\n# 正則化パラメータ$\\lambda=1$の条件で回帰分析を行ってプロットします。\nV = Joe.local_regression(x,y,Joe.epanechnikov;x_pred=U)\nplot!(p61,U,V,label=false,title = \"局所線形回帰(p=1, N=30)\")\nsavefig(p61,joinpath(@OUTPUT,\"fig6-11.svg\")) # hide\n# \\fig{fig6-11}\n# \\lineskip\n# 予測したい場所の数だけ回帰分析の計算を行わないといけないので、元データの数が多い時は\n# 計算が大変そうです。\n# ## 一般化加法モデル\n# ### 例62\n# 基底関数の数が有限個なら線形回帰の手法で係数を求められるけど、\n# 数が多すぎると逆行列を解くのが大変でどうしましょうとい３う話。\n# バックフィッティングは例63で実装します。\n# ### 例63\n# 以下のようなpolyfit関数を実装しました。\n# ```julia\n# function polyfit(x,y;x_pred=x, P::Int=3)\n#     X = polynomial(x,P)\n#     X_pred=polynomial(x_pred,P)\n#     β̂ = multiple_regression(X,y)\n#     y_pred = insert_ones(X_pred) * β̂\n# end\n# ```\n# [例６１](#例61)のデータに一般加法モデルを適用します。\n# 先に多項式でフィッティングして残りを局所線形回帰で求めていきます。\nusing Random,Joe\nRandom.seed!(123)\nn=30; x = 2π*rand(n) .- π; sort!(x); y = sin.(x) .+ randn()\ny₁ = zeros(n); y₂ = zeros(n)\nfor k in 1:10\n    global x,y,y₁,y₂ # hide\n    y₁ = Joe.polyfit(x,y-y₂)\n    y₂ = Joe.local_regression(x,y-y₁,Joe.epanechnikov)\nend\nusing Plots\np62_1 = plot(x,y₁,label=false,xlabel=\"x\",ylabel=\"f(x)\",title=\"多項式回帰(3次)\")\np62_2 = plot(x,y₂,label=false,xlabel=\"x\",ylabel=\"f(x)\",title=\"局所線形回帰\")\np62　= plot(p62_1,p62_2,layout=(1,2))\nsavefig(p62,joinpath(@OUTPUT,\"fig6-12.svg\")) # hide\n# \\fig{fig6-12}\n# \\lineskip\n# 大体３次多項式で回帰されていて、残りが局所線形回帰されていることが分かります。\n# 先に3次多項式で回帰したためでしょうか。 確認してみることにします。\nusing Random,Joe\nRandom.seed!(123)\nn=30; x = 2π*rand(n) .- π; sort!(x); y = sin.(x) .+ randn()\ny₁ = zeros(n); y₂ = zeros(n)\nusing Plots \nfor k in 1:10\n    global x,y,y₁,y₂ # hide\n    y₂ = Joe.local_regression(x,y-y₁,Joe.epanechnikov)\n    y₁ = Joe.polyfit(x,y-y₂)\nend\np62_3 = plot(x,y₁,label=false,xlabel=\"x\",ylabel=\"f(x)\",title=\"多項式回帰(3次)\")\np62_4 = plot(x,y₂,label=false,xlabel=\"x\",ylabel=\"f(x)\",title=\"局所線形回帰\")\np62_5　= plot(p62_3,p62_4,layout=(1,2)) \nsavefig(p62_5,joinpath(@OUTPUT,\"fig6-12-2.svg\")) # hide\n# \\fig{fig6-12-2}\n# \\lineskip\n# 多項式回帰の影響が減って、局所線形回帰の成分が大きくなることが確認できました。", "meta": {"hexsha": "e2f6ed142ae4f7a981bb3374d14645e003e3076c", "size": 14452, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/_literate/ex_chap6.jl", "max_stars_repo_name": "lethal8723/Joe.jl", "max_stars_repo_head_hexsha": "f30bf44f7e662ae58dded2ec675540b2996fe90a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/_literate/ex_chap6.jl", "max_issues_repo_name": "lethal8723/Joe.jl", "max_issues_repo_head_hexsha": "f30bf44f7e662ae58dded2ec675540b2996fe90a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/_literate/ex_chap6.jl", "max_forks_repo_name": "lethal8723/Joe.jl", "max_forks_repo_head_hexsha": "f30bf44f7e662ae58dded2ec675540b2996fe90a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1870824053, "max_line_length": 131, "alphanum_fraction": 0.6320232494, "num_tokens": 6922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.7716163821198194}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Plots, LaTeXStrings\nend;\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.12\"\n\n# ╔═╡ 1aa41898-3afa-11eb-2f49-570853ce6435\nbegin\n\tmu, sig = 2, 3\n\teta = sqrt(3)*sig/pi\n\tn, N = 15, 10^4\n\tdNormal   = Normal(mu, sig)\n\tdLogistic = Logistic(mu, eta)\n\talphaUsed = 0.001:0.001:0.1\nend;\n\n# ╔═╡ 874034ba-3b2b-11eb-2b77-c1d2d28a1116\nfunction alphaSimulator(dist, n, alpha)\n    popVar        = var(dist)\n    coverageCount = 0\n    for _ in 1:N\n        sVar = var(rand(dist, n))\n        L = (n - 1) * sVar / quantile(Chisq(n-1),1-alpha/2)\n        U = (n - 1) * sVar / quantile(Chisq(n-1),alpha/2)\n        coverageCount +=  L < popVar && popVar < U\n    end\n    1 - coverageCount/N\nend\n\n# ╔═╡ 87407402-3b2b-11eb-36de-2b731fe48190\nbegin\n\tscatter(alphaUsed, alphaSimulator.(dNormal,n,alphaUsed), \n\t\tc=:blue, msw=0, label=\"Normal\")\n\tscatter!(alphaUsed, alphaSimulator.(dLogistic, n, alphaUsed), \n\t\tc=:red, msw=0, label=\"Logistic\")\n\tplot!([0,0.1],[0,0.1],c=:black, label=\"1:1 slope\", \n\t\txlabel=L\"\\alpha\"*\" used\", ylabel=L\"\\alpha\"*\" actual\", \n\t\tlegend=:topleft, xlim=(0,0.1), ylims=(0,0.2))\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.12\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═1aa41898-3afa-11eb-2f49-570853ce6435\n# ╠═874034ba-3b2b-11eb-2b77-c1d2d28a1116\n# ╠═87407402-3b2b-11eb-36de-2b731fe48190\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "ecb3e86eead360bd74f1838a11d863913747a21c", "size": 1725, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/06/listing6.12.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/06/listing6.12.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/06/listing6.12.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 26.953125, "max_line_length": 63, "alphanum_fraction": 0.6747826087, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7715718031417846}}
{"text": "# ============================================================================\n# Example 1 from *Reachability analysis of linear systems with uncertain\n# parameters and inputs*. TODO: Agregar referencia completa.\n# ============================================================================\n\n# initial set\nX0 = BallInf([1.0, 1.0], 0.1)\n\n# linear ODE: x' = Ax\nA = IntervalMatrix([-1.0 ± 0.05 -4.0 ± 0.05;\n                    4.0 ± 0.05 -1.0 ± 0.05])\n\n# IVP(LCS(A), X0) TODO: remove\ninterval2D_linear = @ivp x' = Ax, x(0) ∈ X0\n\n# affine ODE: x' = Ax + Bu\nB = IntervalMatrix(hcat([1.0 ± 0.0; 1.0 ± 0.0])) # why hcat?\nU = Interval(-0.05, 0.05)\n\n# IVP(CLCCS(A, B, nothing, U), X0) TODO: remove\ninterval2D_affine = @ivp x' = Ax + Bu, x(0) ∈ X0, u ∈ U\n", "meta": {"hexsha": "889dd491bd47609f7f6bdf5909c54605780d05e9", "size": 746, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/models/linear/interval2D.jl", "max_stars_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_stars_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2020-03-30T16:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:26:48.000Z", "max_issues_repo_path": "test/models/linear/interval2D.jl", "max_issues_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_issues_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 258, "max_issues_repo_issues_event_min_datetime": "2020-03-30T14:13:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T17:07:04.000Z", "max_forks_repo_path": "test/models/linear/interval2D.jl", "max_forks_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_forks_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-04-23T03:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T23:11:32.000Z", "avg_line_length": 33.9090909091, "max_line_length": 78, "alphanum_fraction": 0.4691689008, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7714650774500602}}
{"text": "using AlphaStructures\nusing ViewerGL\nGL =  ViewerGL\n\n\"\"\"\nReturn points from file.\n\"\"\"\nfunction load_points(filename::String)::Matrix\n    io = open(filename, \"r\")\n    point = readlines(io)\n    close(io)\n\n    b = [tryparse.(Float64,split(point[i], \" \")) for i in 1:length(point)]\n    V = hcat(b...)\n    return V\nend\n\nV = load_points(\"examples/examples3D/model/griffin.txt\")\n\n# view points\nGL.VIEW([\n\tGL.GLPoints(permutedims(V))\n])\n\n# points by columns\nfiltration = AlphaStructures.alphaFilter(V);\nVV, EV, FV, TV = AlphaStructures.alphaSimplex(V, filtration, 0.35)\n\n#view all simplices\nGL.VIEW(\n\t[\n\t\tGL.GLGrid(V, EV, GL.COLORS[1], 0.6) # White\n\t\tGL.GLGrid(V, FV, GL.COLORS[2], 0.8) # Red\n\t\tGL.GLGrid(V, TV, GL.COLORS[3], 0.6) # Green\n\t]\n);\n", "meta": {"hexsha": "055b95358c66c70f676b8e89cd104557808cf8c8", "size": 737, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/examples3D/griffin.jl", "max_stars_repo_name": "eOnofri04/AlphaShape.jl", "max_stars_repo_head_hexsha": "8f7bef006b41fd49dfcc7cc99f6e666b5f858574", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-04T17:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-04T17:41:16.000Z", "max_issues_repo_path": "examples/examples3D/griffin.jl", "max_issues_repo_name": "eOnofri04/AlphaStructures.jl", "max_issues_repo_head_hexsha": "301489190bcbf776f8202c2ede23be42d30aab36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-07-09T13:50:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-30T09:25:43.000Z", "max_forks_repo_path": "examples/examples3D/griffin.jl", "max_forks_repo_name": "eOnofri04/AlphaStructures.jl", "max_forks_repo_head_hexsha": "301489190bcbf776f8202c2ede23be42d30aab36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9189189189, "max_line_length": 74, "alphanum_fraction": 0.6594301221, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632329799586, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7714650742690017}}
{"text": "# The BiMix distribution samples from a `leftdistribution` distribution with\n# probability `p` and the `rightdistribution` with probability `1-p`. this\n# is useful for efficiently defining mixture models upon two distributions,\n# since it computes a marginalized pdf, thus saving the extra node in the\n# execution trace for the mixture assignment.\n\nstruct BiMix{T<:Distribution,U<:Distribution}\n    prob :: Float64\n    leftdistribution :: T\n    rightdistribution :: U\nend\n\nfunction Distributions.logpdf(bimix::BiMix, value)\n    pleft = log(bimix.prob) + logpdf(bimix.leftdistribution, value)\n    pright = log1p(-bimix.prob) + logpdf(bimix.rightdistribution, value)\n    \n    m = max(pleft, pright)\n    m + log(exp(pleft - m) + exp(pright - m))\nend\n\nfunction Base.rand(bimix::BiMix)\n    left = rand() <= bimix.prob\n    rand(left ? bimix.leftdistribution : bimix.rightdistribution)\nend\n", "meta": {"hexsha": "67a4589084c16a0232909252f10bbf7e2f6dd7e2", "size": 883, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distributions/bimix.jl", "max_stars_repo_name": "matthieubulte/Probabilistic.jl", "max_stars_repo_head_hexsha": "8eb68f7c9372570657efb8362ff5bc7b09bca62b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distributions/bimix.jl", "max_issues_repo_name": "matthieubulte/Probabilistic.jl", "max_issues_repo_head_hexsha": "8eb68f7c9372570657efb8362ff5bc7b09bca62b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distributions/bimix.jl", "max_forks_repo_name": "matthieubulte/Probabilistic.jl", "max_forks_repo_head_hexsha": "8eb68f7c9372570657efb8362ff5bc7b09bca62b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.32, "max_line_length": 76, "alphanum_fraction": 0.731596829, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632261523027, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7714650709140131}}
{"text": "# Numerical Integration\n\nstruct GaussLegendre\n    nip::Int  # number of integral points\n    nodes::Vector{Float64}\n    weights::Vector{Float64}\n    function GaussLegendre(nip::Int)\n        nodes, weights = gausslegendre(nip)\n        return new(nip, nodes, weights)\n    end\nend\n\n\"\"\"\nIntegrate on interval\n\"\"\"\nfunction integrate(func, I1::ClosedInterval{<:Real}, gl1)\n    nip1, nodes1, weights1 = gl1.nip, gl1.nodes, gl1.weights\n    dnodes1 = (IntervalSets.width(I1) * nodes1 .+ sum(extrema(I1))) / 2\n\n    S1 = weights1[1] * func(dnodes1[1])\n    for i1 in 2:nip1\n        S1 += weights1[i1] * func(dnodes1[i1])\n    end\n\n    return S1 * IntervalSets.width(I1) / 2\nend\n\n\"\"\"\nIntegrate on rectangular region.\n\"\"\"\nfunction integrate(func, I1::ClosedInterval{<:Real}, I2::ClosedInterval{<:Real}, gl1, gl2)\n    nip1, nodes1, weights1 = gl1.nip, gl1.nodes, gl1.weights\n    nip2, nodes2, weights2 = gl2.nip, gl2.nodes, gl2.weights\n    dnodes1 = (IntervalSets.width(I1) * nodes1 .+ sum(extrema(I1))) / 2\n    dnodes2 = (IntervalSets.width(I2) * nodes2 .+ sum(extrema(I2))) / 2\n\n    S2 = weights2[1] * func(dnodes1[1], dnodes2[1])\n    for i2 in 2:nip2\n        S2 += weights2[i2] * func(dnodes1[1], dnodes2[i2])\n    end\n    S1 = weights1[1] * S2\n    for i1 in 2:nip1\n        S2 = weights2[1] * func(dnodes1[i1], dnodes2[1])\n        for i2 in 2:nip2\n            S2 += weights2[i2] * func(dnodes1[i1], dnodes2[i2])\n        end\n        S1 += weights1[i1] * S2\n    end\n\n    return S1 * IntervalSets.width(I1) * IntervalSets.width(I2) / 4\nend\n\n\"\"\"\nIntegrate on rectangular solid\n\"\"\"\nfunction integrate(func, I1::ClosedInterval{<:Real}, I2::ClosedInterval{<:Real}, I3::ClosedInterval{<:Real}, gl1, gl2, gl3)\n    nip1, nodes1, weights1 = gl1.nip, gl1.nodes, gl1.weights\n    nip2, nodes2, weights2 = gl2.nip, gl2.nodes, gl2.weights\n    nip3, nodes3, weights3 = gl3.nip, gl3.nodes, gl3.weights\n    dnodes1 = (IntervalSets.width(I1) * nodes1 .+ sum(extrema(I1))) / 2\n    dnodes2 = (IntervalSets.width(I2) * nodes2 .+ sum(extrema(I2))) / 2\n    dnodes3 = (IntervalSets.width(I3) * nodes3 .+ sum(extrema(I3))) / 2\n\n    S3 = weights3[1] * func(dnodes1[1],dnodes2[1],dnodes3[1])\n    for i3 in 2:nip3\n        S3 += weights3[i3] * func(dnodes1[1],dnodes2[1],dnodes3[i3])\n    end\n    S2 = weights2[1] * S3\n    for i2 in 2:nip2\n        S3 = weights3[1] * func(dnodes1[1],dnodes2[i2],dnodes3[1])\n        for i3 in 2:nip3\n            S3 += weights3[i3] * func(dnodes1[1],dnodes2[i2],dnodes3[i3])\n        end\n        S2 += weights2[i2] * S3\n    end\n    S1 = weights1[1] * S2\n    for i1 in 2:nip1\n        S3 = weights3[1] * func(dnodes1[i1],dnodes2[1],dnodes3[1])\n        for i3 in 2:nip3\n            S3 += weights3[i3] * func(dnodes1[i1],dnodes2[1],dnodes3[i3])\n        end\n        S2 = weights2[1] * S3\n        for i2 in 2:nip2\n            S3 = weights3[1] * func(dnodes1[i1],dnodes2[i2],dnodes3[1])\n            for i3 in 2:nip3\n                S3 += weights3[i3] * func(dnodes1[i1],dnodes2[i2],dnodes3[i3])\n            end\n            S2 += weights2[i2] * S3\n        end\n        S1 += weights1[i1] * S2\n    end\n\n    return S1 * IntervalSets.width(I1) * IntervalSets.width(I2)  * IntervalSets.width(I3) / 8\nend\n", "meta": {"hexsha": "1889c148e02a0cc87ea710babda552ba04ba05ba", "size": 3174, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/_Integral.jl", "max_stars_repo_name": "hyrodium/BasicBSpline.jl", "max_stars_repo_head_hexsha": "4fa0c7ba69b62c8c115cbd98c4aa3223dd2e89a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2020-04-26T03:49:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T06:34:42.000Z", "max_issues_repo_path": "src/_Integral.jl", "max_issues_repo_name": "hyrodium/BasicBSpline.jl", "max_issues_repo_head_hexsha": "4fa0c7ba69b62c8c115cbd98c4aa3223dd2e89a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 103, "max_issues_repo_issues_event_min_datetime": "2020-07-04T15:00:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:55:41.000Z", "max_forks_repo_path": "src/_Integral.jl", "max_forks_repo_name": "hyrodium/BasicBSpline.jl", "max_forks_repo_head_hexsha": "4fa0c7ba69b62c8c115cbd98c4aa3223dd2e89a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4105263158, "max_line_length": 123, "alphanum_fraction": 0.6036546944, "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632247867717, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.7714650610925492}}
{"text": "# using Pkg; for p in (\"Knet\",\"ArgParse\"); haskey(Pkg.installed(),p) || Pkg.add(p); end\n\n\"\"\"\n\nLinReg is a simple linear regression example using artificially\ngenerated data. You can run the demo using `julia linreg.jl` on the\ncommand line or `julia> LinReg.main()` at the Julia prompt.  Use\n`julia linreg.jl --help` or `julia> LinReg.main(\"--help\")` for a list\nof options.  The quadratic loss will be printed at every epoch and\noptimized parameters will be returned.\n\n\"\"\"\nmodule LinReg\nusing Knet, CUDA, ArgParse, Random\n\npredict(w,x)=(w*x)\n\nloss(w,x,y)=(sum(abs2,y-predict(w,x)) / size(x,2))\n\nlossgradient = grad(loss)\n\nfunction train(w, data; lr=.02, epochs=10)\n    for epoch=1:epochs\n        for (x,y) in data\n            g = lossgradient(w, x, y)\n            w -= lr * g\n        end\n    end\n    return w\nend\n\nfunction test(w, data)\n    sumloss = numloss = 0\n    for (x,y) in data\n        sumloss += loss(w,x,y)\n        numloss += 1\n    end\n    return sumloss/numloss\nend\n\n\n# Data generator:\n\nstruct LRData; w; batchsize; epochsize; noise; rng; atype; end\n\nfunction LRData(outputdims,inputdims; batchsize=20, epochsize=10000, noise=.01, rng=Random.GLOBAL_RNG, atype=Array)\n    LRData(convert(atype, randn(rng,outputdims,inputdims)),batchsize,epochsize,noise,rng,atype)\nend\n\nfunction Base.iterate(l::LRData, n=0)\n    if n >= l.epochsize; return nothing; end\n    (outputdims, inputdims) = size(l.w)\n    x = convert(l.atype, rand(l.rng, inputdims, l.batchsize))\n    y = l.w * x + convert(l.atype, l.noise * randn(l.rng, outputdims, l.batchsize))\n    return ((x,y), n+l.batchsize)\nend\n\n\n# Main loop:\n\nfunction main(args=ARGS)\n    s = ArgParseSettings()\n    s.description=\"linreg.jl (c) Deniz Yuret, 2016. Linear regression example with artificial data.\"\n    s.exc_handler=ArgParse.debug_handler\n    @add_arg_table s begin\n        (\"--atype\"; default=\"$(Knet.array_type[])\"; help=\"array type: Array for cpu, KnetArray for gpu\")\n        (\"--batchsize\"; arg_type=Int; default=20; help=\"number of instances in a minibatch\")\n        (\"--epochs\"; arg_type=Int; default=10; help=\"number of epochs for training\")\n        (\"--epochsize\"; arg_type=Int; default=10000; help=\"number of instances per epoch\")\n        (\"--fast\"; action=:store_true; help=\"skip loss printing for faster run\")\n        (\"--inputdims\"; arg_type=Int; default=100; help=\"input dimensions\")\n        (\"--lr\"; arg_type=Float64; default=0.02; help=\"learning rate\")\n        (\"--noise\"; arg_type=Float64; default=0.01; help=\"noise in data\")\n        (\"--outputdims\"; arg_type=Int; default=10; help=\"output dimensions\")\n        (\"--seed\"; arg_type=Int; default=-1; help=\"random number seed: use a nonnegative int for repeatable results\")\n        (\"--gcheck\"; arg_type=Int; default=0; help=\"check N random gradients\")\n    end\n    isa(args, AbstractString) && (args=split(args))\n    if in(\"--help\", args) || in(\"-h\", args)\n        ArgParse.show_help(s; exit_when_done=false)\n        return\n    end\n    o = parse_args(args,s; as_symbols=true)\n    println(s.description)\n    println(\"opts=\",[(k,v) for (k,v) in o]...)\n    o[:seed] > 0 && Knet.seed!(o[:seed])\n    atype = eval(Meta.parse(o[:atype]))\n    data = LRData(o[:outputdims], o[:inputdims]; batchsize=o[:batchsize], epochsize=o[:epochsize], noise=o[:noise], atype=atype)\n    w = convert(atype, 0.1*randn(o[:outputdims], o[:inputdims]))\n    println((:epoch,0,:loss,test(w,data)))\n    if o[:fast]\n        @time w = train(w, data; epochs=o[:epochs], lr=o[:lr])\n        println((:epoch,o[:epochs],:loss,test(w,data)))\n    else\n        @time for epoch=1:o[:epochs]\n            w = train(w, data; epochs=1, lr=o[:lr])\n            println((:epoch,epoch,:loss,test(w,data)))\n            if o[:gcheck] > 0\n                gradcheck(loss, w, first(data)...; gcheck=o[:gcheck], verbose=true)\n            end\n        end\n    end\n    return w\nend\n\n# This allows both non-interactive (shell command) and interactive calls like:\n# $ julia linreg.jl --epochs 10\n# julia> LinReg.main(\"--epochs 10\")\nPROGRAM_FILE == \"linreg.jl\" && main(ARGS)\n\nend\n\n\n# SAMPLE RUN 65f57ff+ Wed Sep 14 10:02:30 EEST 2016\n#\n# linreg.jl (c) Deniz Yuret, 2016. Linear regression example with artificial data.\n# opts=(:lr,0.02)(:atype,\"KnetArray\")(:epochsize,10000)(:inputdims,100)(:noise,0.01)(:epochs,10)(:gcheck,0)(:seed,-1)(:outputdims,10)(:batchsize,20)(:fast,true)\n# (:epoch,0,:loss,349.84485494071095)\n#   1.320391 seconds (1.65 M allocations: 164.061 MB, 1.85% gc time)\n# (:epoch,10,:loss,0.0010327464077591123)\n", "meta": {"hexsha": "f01f986f6d9a4e9a9a7e2feb910686b9908896a4", "size": 4485, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/synthetic-linreg/linreg.jl", "max_stars_repo_name": "AndrewSerra/Knet.jl", "max_stars_repo_head_hexsha": "cbbcb670667b1707ad1b1d7c637784e36a98b81e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1492, "max_stars_repo_stars_event_min_datetime": "2015-09-30T07:05:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T14:48:46.000Z", "max_issues_repo_path": "examples/synthetic-linreg/linreg.jl", "max_issues_repo_name": "AndrewSerra/Knet.jl", "max_issues_repo_head_hexsha": "cbbcb670667b1707ad1b1d7c637784e36a98b81e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 604, "max_issues_repo_issues_event_min_datetime": "2016-02-05T06:32:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T20:09:19.000Z", "max_forks_repo_path": "examples/synthetic-linreg/linreg.jl", "max_forks_repo_name": "AndrewSerra/Knet.jl", "max_forks_repo_head_hexsha": "cbbcb670667b1707ad1b1d7c637784e36a98b81e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 340, "max_forks_repo_forks_event_min_datetime": "2015-10-28T07:47:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:51:11.000Z", "avg_line_length": 37.0661157025, "max_line_length": 160, "alphanum_fraction": 0.6441471572, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.8774767890838836, "lm_q1q2_score": 0.7714308771308013}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6dd76507-be07-4c3a-9747-99eca74d3519\nbegin\n\tfilter!(path -> path != \"@v#.#\", LOAD_PATH)\n\tusing Pkg\n\tPkg.activate(Base.current_project())\n\tPkg.instantiate()\n\tusing PlutoUI, StatisticsWithJulia\n\tPlutoUI.TableOfContents(title = \"初识 Julia\")\nend\n\n# ╔═╡ 3baed4bd-1c0c-4d44-b7ab-f7c0627fda1b\nbegin\n\tPkg.add(\"AbstractTrees\") # command + /: 切换为注释形式\n\tusing AbstractTrees\n\tAbstractTrees.children(x::Type) = subtypes(x)\n\twith_terminal(() -> print_tree(Number))\nend\n\n# ╔═╡ 2edcc72c-bfa4-4623-a34f-220c0df9c4d3\nbegin\n\tPkg.add(\"HTTP\")\n\tPkg.add(\"JSON\")\n\tusing HTTP, JSON\nend\n\n# ╔═╡ d507db6a-f869-4dc3-b7ef-fd3518fc1660\nPkg.add.([\"Plots\", \"LaTeXStrings\", \"Measures\"])\n\n# ╔═╡ 2fdb3281-7229-4f18-b9d9-bc5e3086d903\nusing Statistics\n\n# ╔═╡ f924796f-52f3-4b4b-aa47-61a179874647\nusing Plots, LaTeXStrings, Measures\n\n# ╔═╡ ec3f7b5c-cee9-432f-b33c-a08e16c0171a\nStatisticsWithJulia.header(title = @__FILE__, author=\"\")\n\n# ╔═╡ 9d98fa7a-3654-40a0-8a96-75c3fca007ae\nmd\"\"\"\n## 本章讲义\n\n- [讲义下载](http://likan.oss-cn-beijing.aliyuncs.com/StatisticsWithJulia/01-%E5%88%9D%E8%AF%86Julia.pdf)\n\n\"\"\"\n\n# ╔═╡ 42da8f74-1b44-11ec-32f2-276bdcef1c69\nmd\"\"\"\n## 1.1. 你好世界\n\"\"\"\n\n# ╔═╡ e71aacbb-efff-4b93-b5c4-cbdfa88981ad\nmd\"\"\"\n- `command/control + m`: 把当下单元格切换到markdown格式\n\"\"\"\n\n# ╔═╡ 0660d564-9a26-417d-9a2c-42ef181187c2\nwith_terminal() do\n    println(\"你好， 世界!\")\nend\n\n# ╔═╡ 77c5ddd3-ddfc-4a57-ab48-e9db765057d3\nwith_terminal(() -> println(\"你好， 世界!\"))\n\n# ╔═╡ 8eefb8aa-ae85-4231-abf5-9948cdc92ec1\nmd\"\"\"\n`do f() end` 等价于 `（） -> f()`\n\"\"\"\n\n# ╔═╡ d22fc28f-c591-4db2-8275-54d93fda85e9\nf(x) = BigInt(x)^BigInt(x)\n\n# ╔═╡ 4ece5fc8-18d5-408a-851b-31ce58015e72\nmap(x -> 3x, 1:10)\n\n# ╔═╡ c266f6e2-4e8e-4870-ac38-d4d0e8b9d042\nmap(1:10) do x\n\t3x\nend\n\n# ╔═╡ 8f3277e9-7905-4beb-9ef1-c3e18b2f449a\nmap(x -> rand(), 1:10)\n\n# ╔═╡ f6e99ac9-2183-4ea2-991e-f3422b1d1f20\nmap(__ -> rand(), 1:10)\n\n# ╔═╡ cd0ce1b4-9bc9-4218-95e9-e576abeb1af1\n# map(() -> rand(), 1:10) # 不合语法\n\n# ╔═╡ 37fec978-f817-4aa8-85fc-4912eaeb402e\nhelloArray = [\"你好\", \"👋\", \"世界\"]\n\n# ╔═╡ adc183db-ff23-43de-8cf6-a961d13c2f01\nwith_terminal() do\n\tfor i ∈ eachindex(helloArray)\n\t\tprintln(helloArray[i])\n\tend\nend\n\n# ╔═╡ 4f1ce95f-2f2f-4817-9d5f-348184a1b800\n[i^2 for i in 1:10 for __ in 1:10] # 一维数组\n\n# ╔═╡ dec64158-9161-4b37-b19f-432a5635719e\n[i^2 for i in 1:10, __ in 1:10]   # 矩阵\n\n# ╔═╡ 5a401f10-09d2-4939-87fe-621f469a68ee\nSquare = [i^2 for i in 1:10]\n\n# ╔═╡ c2c7c916-1ba8-4e14-a25b-e15faf676f8a\nwith_terminal() do\n\tfor i ∈ eachindex(Square)\n\t\t\tprintln(Square[i])\n\tend\nend\n\n# ╔═╡ 93b0afb2-e9f3-434d-b21a-2ccad6a12d90\n[rand() for __ in 1:100]\n\n# ╔═╡ 8bcc15c7-d66a-40cc-9f33-50c6de62fadc\nmd\"\"\"\n### 运行速度\n\"\"\"\n\n# ╔═╡ 428c124a-1052-45c8-a49b-b1047267d644\nmd\"\"\"\n- LaTeX Syntax\n\n```math\ny = \\frac{\\displaystyle\\sum_{i=1}^\\infty}{\\epsilon\\times\\sigma}\n\n```\n\"\"\"\n\n# ╔═╡ 863624c7-f378-467a-bed2-94182bae73b7\nwith_terminal() do \n\t@time begin\n\t\tglobal data = Float64[]\n\t\tfor __ in 1:10^6\n\t\t\tgroup = Float64[]\n\t\t\tfor __ in 1:5*10^2\n\t\t\t\tpush!(group, rand())\n\t\t\tend\n\t\t\tpush!(data, mean(group))\n\t\tend\n\tend\nend\n\n# ╔═╡ 0e8b6a32-ba23-4e37-b78c-8ffb3779a43e\n\"98%的平均值位于 $(quantile(data, 0.01)) 和 $(quantile(data, 0.99)) 之间。\"\n\n# ╔═╡ 9e35d6a1-df94-4a27-9e04-234548495780\nwith_terminal() do\n\t@time global data2 = [mean(rand(5 * 10 ^ 2)) for __ in 1 : 10 ^ 6]\nend\n\n# ╔═╡ 1b45a9bf-56c7-4b7b-bdd5-b4fcaa572ec0\n\"98%的平均值位于 $(quantile(data2, 0.01)) 和 $(quantile(data2, 0.99)) 之间。\"\n\n# ╔═╡ 60b263eb-f786-40c4-b60b-2daabdacba7b\nmd\"\"\"\n### 类型和多重派发\n\"\"\"\n\n# ╔═╡ b0db7a9c-2498-46c5-bf3c-280d3083ba88\n# @edit 1 + 2\n\n# ╔═╡ 412ee0c1-26ad-4b9f-9d6e-c552d8431e76\n# @edit 1.0 + 2\n\n# ╔═╡ aa5e313d-19d9-4300-a65e-f547f7e571d0\nmutable struct zhan\n\tdt::Int64\nend\n\n# ╔═╡ 0ba25fa7-72cb-4d6e-bfaf-eddcf12b9f9c\nx = zhan(4)\n\n# ╔═╡ d5251a23-b71e-4faf-9f5a-f6ab1d2ffb7d\ny = zhan(8)\n\n# ╔═╡ b717d872-0d16-4556-a6c8-1ccc3c7b76c3\nBase.:+(x::zhan, y::zhan) = x.dt * 100 + y.dt * 200\n\n# ╔═╡ a0322171-cff9-48bb-9f73-792c8ea4798f\nfunction g(x)\n\tx + 1000\nend\n\n# ╔═╡ 3711c338-748f-448e-a06d-d3c29094a14b\nmap(g, 1:10)\n\n# ╔═╡ f77b7762-29ee-4472-a4ee-a5c1a6dfb369\nsqrt.(Square) .+ 100\n\n# ╔═╡ e9d5ee6c-de1a-41ee-850e-a6f5471537ea\n@. sqrt(Square) + 100\n\n# ╔═╡ 90fe2c2b-d62d-40b5-9a34-0eb1e9836250\n[10 + x for x in 1:100]\n\n# ╔═╡ 72b3ed37-3f3f-4a7d-9036-dadb06c3e1e4\nx + y\n\n# ╔═╡ 8c6e966d-9185-4a44-8cd9-e69528cee54b\n# methods(+)\n\n# ╔═╡ 1e9be5f5-ab15-4a29-8fd6-d20fee084ad5\nabstract type LIKANZHAN <: Signed end #抽象类型\n\n# ╔═╡ 59b884e5-a55a-42f6-9ed4-404d55eae5e9\nmd\"\"\"\n## 1.2. 几个例子\n\"\"\"\n\n# ╔═╡ 3cbd7219-7fb0-4c6e-a2ad-724e97b67d94\nfunction bubbleSort!(a)\n\tn = length(a)\n\tfor i ∈ 1:n-1\n\t\tfor j ∈ 1:n-i\n\t\t\tif a[j] > a[j+1]\n\t\t\t\ta[j], a[j+1] = a[j+1], a[j] # Julian Way\n\t\t\tend\n\t\tend\n\tend\n\treturn a\nend\n\n# ╔═╡ 93a86467-cf02-4d3c-b127-79247a588250\ndata3 = [65, 66, 55, 44, 20, 34, 78, 80]\n\n# ╔═╡ 0423223e-90c5-4d86-8370-66ddee6ba496\nwith_terminal() do\n\t@time bubbleSort!(rand(10^5))\nend\n\n# ╔═╡ 721c67fd-6d40-4171-89c4-21a1c0064880\nwith_terminal() do\n\t@time sort!(rand(10^5))\nend\n\n# ╔═╡ 5a4dd40b-d917-4634-a4d4-255c63d68d3f\nmd\"\"\"\n- 网络接口和 JSON\n\"\"\"\n\n# ╔═╡ 20097ff6-c516-454c-978f-4c92e6c72d52\ndata4 = HTTP.request(\"GET\",\"https://ocw.mit.edu/ans7870/6/6.006/s08/lecturenotes/files/t8.shakespeare.txt\");\n\n# ╔═╡ fbbc0558-7916-4308-b8be-4428f47ca4e5\nshakespeare = String(data4)\n\n# ╔═╡ 290d3b7f-ee12-476c-a4f2-189671c84398\n# shakespeareWords = split(shakespeare)\n\n# ╔═╡ cc728038-b20f-4b93-97a7-883d5734a0b2\n# jsonWords = HTTP.request(\"GET\", \"https://raw.githubusercontent.com/\"*\"h-Klok/StatsWithJuliaBook/master/data/jsonCode.json\")\n\n# ╔═╡ 2eca9295-370d-41e9-95a4-b56ee2b0e1dc\n\"julia\" * \" is good\"\n\n# ╔═╡ b4c5a72d-5ce1-4e21-a04f-8344d1023648\nstring(\"Julia\", \" is Good\", \". Python\", \" is slow.\")\n\n# ╔═╡ 4f11cc1a-a78e-4d6c-8bd2-857f85f48aa8\nls = 1:7\n\n# ╔═╡ 50039da8-2c71-4a1d-8cc1-2d4bd8126988\ntypeof(ls)\n\n# ╔═╡ efb2b80c-af6c-4f6e-bcba-e57c7c39cab3\ncollect(ls)\n\n# ╔═╡ 1ca893dd-2040-47df-8fa0-c3cb4dd0d7dc\nmd\"\"\"\n- 数据存储的常见格式：数组\n\"\"\"\n\n# ╔═╡ dbbcd955-e0c9-4a6c-81bf-fe5c5ad2f018\nmd\"\"\"\n- 数据存储的另外格式： 词典\n\"\"\"\n\n# ╔═╡ 5565b0a4-792b-40f6-82a2-f8f642432129\ndct = Dict(\"x\" => collect(ls), \"y\" => collect(ls .+ 1) )\n\n# ╔═╡ 6d4175a4-af6e-4a08-bcd2-0b1966ae9035\ngetindex(dct, \"x\")\n\n# ╔═╡ c4a58e43-2ea8-48fa-a99d-09f83b1b8ba8\nmd\"\"\"\n- 数据存储的另外格式： 元组\n\"\"\"\n\n# ╔═╡ e0e5ef4a-fc35-4d9b-9a34-a9439d87051d\nvec = [1, 2, 3]; typeof(vec)\n\n# ╔═╡ c9d041cb-6a29-449a-8909-b529e8c562a6\nyz = (1, 2, 4); typeof(yz)\n\n# ╔═╡ c77241fb-bd9e-4270-bd04-e8b5bcb2406b\nmd\"\"\"\n## 1.3. 做图初步\n\"\"\"\n\n# ╔═╡ 87296377-fe6d-4225-b114-a8c3b8bea1bc\nwith_terminal() do\n\tPkg.status()\nend\n\n# ╔═╡ aa61efe4-b3a2-4379-a748-f37cd7f9c6fb\nf(x, y) = x^2 + y^2\n\n# ╔═╡ 9d9f4d96-7755-4fd1-851a-092929ad1ac7\nf(6)\n\n# ╔═╡ 8b0db1dd-5d79-42e5-9763-ca4ef7259060\nmap(f, 1:10)\n\n# ╔═╡ 182ab07b-a3e6-47f0-8de5-d59113027c43\nf0(x) = f(x, 0)\n\n# ╔═╡ 6262451f-4dcf-4f84-8be6-2f8fbf2631bd\nf2(x) = f(x, 2)\n\n# ╔═╡ 3d664567-d879-41f7-9e1a-cdfc08e4e7c9\nxVals, yVals = -5:0.1:5, -5:0.1:5\n\n# ╔═╡ 5e03a17e-861e-4749-b18e-00e293d24f28\nplot([f0, f2], xVals) # command + /\n\n# ╔═╡ 4d5c7119-f2bf-44ed-bc20-5597a795fbcd\nplot(xVals, [f0.(xVals), f2.(xVals)],\n\tcolor = [:blue :green],\n\txlims = (-6, 6),\n\tylims = (-5, 30),\n\txlabel = \"Range of X\",\n\tylabel = L\"f(x, \\cdot)\",\n\tlabel = [L\"f(x, 0)\" L\"f(x, 2)\"],\n\tlegends = :bottomleft\n)\n\n# ╔═╡ af2e86c1-4c58-4577-9ae9-313f8ae78475\np1 = annotate!(0, -0.2, text(\"(0, 0) the mainimum \\n of f(x, 0)\", :left, :top, 10))\n\n# ╔═╡ 9461292e-3658-41e2-8349-45790fa7c9e0\nz = [f(x, y) for y in yVals, x in xVals];\n\n# ╔═╡ 7e03b8d1-1ddb-435f-b9ba-b72b0c44da18\np2 = surface(xVals, yVals, z,\n\tcolor = cgrad([:blue, :red]),\n\tlegend = :none,\n\tylabel = \"y\",\n\tzlabel = L\"f(x, y)\"\n)\n\n# ╔═╡ e54420c1-1ff3-4f38-b9b8-0e3a18127c9a\nM = z[1:10, 1:10];\n\n# ╔═╡ 458dfaeb-0370-4e61-90a2-f5b54a0fab42\np3 = heatmap(M, \n\tcolor = cgrad([:blue, :red]),\n\tylabel = \"y\",\n\txticks = ([1:10; ], xVals),\n\tyticks = ([1:10; ], yVals)\n)\n\n# ╔═╡ b7729c93-781a-46ec-b057-65c4e9e15a04\nplot(p1, p2, p3, layout = (1, 3), size = (1200, 400), xlabel = \"x\", margin = 5mm)\n\n# ╔═╡ 543de112-675c-4368-957d-f37647ad85bd\n L\"\\frac{\\delta}{\\gamma\\times \\cdots}\"\n\n# ╔═╡ 37f6486e-e03c-4ddb-bca6-d13157d69822\nplot([f0, f2], 1:0.5:10, \n\tseriestype = [:scatter, :line], \n\tmarkersize = 6,\n\tlinewidth = 3, linecolor = :green, \n\tlegend = false)\n\n# ╔═╡ 68d89124-d6e9-4609-b12a-d3b508733680\n# surface() # 等价于 plot(.., seriestype = :surface,...,)\n\n# ╔═╡ 6003cd52-89ea-4d93-ac00-43ca395357b8\nmd\"\"\"\n### 1.3.1 希尔顿序列\n\"\"\"\n\n# ╔═╡ 92c42555-8550-4c1b-9b1a-502813c40237\nmd\"\"\"\n- 条件句\n\"\"\"\n\n# ╔═╡ 5c3f1925-ebfb-4bef-8425-635262927bf1\nfunction ff1(x)\n\tif x % 3 == 0\n\t\treturn \"$x 除以 3 的余数是 0\"\n\telseif x % 3 == 1\n\t\treturn \"$x 除以 3 的余数是 1\"\n\telse\n\t\treturn \"$x 除以 3 的余数是 2\"\n\tend\nend\n\n# ╔═╡ ec02b4a7-529b-4d37-ba4b-bf146a33ee0f\n[ff1(x) for x in 1:5]\n\n# ╔═╡ 954f166b-e8db-4cf7-a0a2-75ab3b3acbe0\nfunction ff2(x)\n\tif x % 3 == 0\n\t\treturn \"x 除3的余数是 0\"\n\tend\nend\n\n# ╔═╡ e97dcedb-4b53-4ce8-a0e9-ed20b77d8b2d\n[ff2(x) for x in 1:5]\n\n# ╔═╡ f662c9f4-8004-43d6-ad1e-872ad3d24e48\nmd\"\"\"\n- 类型稳定性： 除号可能会改变数据的类型\n\"\"\"\n\n# ╔═╡ c72335d5-39e3-4ab9-a398-e3960dcafe0c\nxd = Int(2)\n\n# ╔═╡ 8ebae10c-3148-43fe-9b14-f07934c3b2ea\ntypeof(xd)\n\n# ╔═╡ e49a1426-bcf5-453a-8753-2bb8387e67eb\nyd = xd/2\n\n# ╔═╡ 46bd26e6-c1bf-4fa3-890a-2d424865c2dc\ntypeof(yd)\n\n# ╔═╡ 55e79482-e30e-4eea-b083-cac2a9667348\nmd\"\"\"\n- 希尔顿序列\n\"\"\"\n\n# ╔═╡ 9537df9b-7fc8-4b32-bc7c-d8ee8730d73a\nfunction hailLength1(x::Int)\n\tn = 0\n\twhile x != 1\n\t\tif x % 2 == 0\n\t\t\tx = Int(x / 2)\n\t\telse\n\t\t\tx = 3x + 1\n\t\tend\n\t\tn += 1 # 等价于 n = n + 1, *=, /= \n\tend\n\treturn n\nend\n\n# ╔═╡ 6434a9f1-aa8a-491f-ac7e-c58b3a4b2638\nfunction hailLength(x::Int)\n\tn = 0\n\twhile x != 1\n\t\tx = x % 2 == 0 ? Int(x / 2) : 3x + 1\n\t\tn += 1\n\tend\n\treturn n\nend\n\n# ╔═╡ 4abd57c6-1a0c-4e7c-a195-d07ddc299b2c\nmd\"\"\"\n注意： `condition ? res1 : res2` 等价于 `if condition res1 else res2`\n\"\"\"\n\n# ╔═╡ aa2c895f-7219-4b98-bf50-c96d676ead09\nx2 = 13\n\n# ╔═╡ 5fb204e1-d150-4a3c-ac19-6fa5b67b072b\nif x2 % 2 == 1 \"奇数\" else \"偶数\" end\n\n# ╔═╡ c0df29b8-368d-40d1-bad0-73493531903a\nlengths = [hailLength(x0) for x0 in 2:10^7];\n\n# ╔═╡ 51046c66-6e14-420e-8a5e-5a58580841a6\n# histogram(lengths)\n\n# ╔═╡ 3659f664-3fc3-48bd-94e3-f57ae84e7301\nplot(lengths, seriestype = :histogram,\n\tbins = 1000,\n\t# fill = (:green, true) # 元组\n\tfill = true, color = :green,\n\tnormed = true, legend = false,\n\tlinealpha = 0.2\n)\n\n# ╔═╡ 9392cdfb-ceef-40ac-a67b-8c7ca33de123\nmd\"\"\"\n### 1.3.2 动图\n\"\"\"\n\n# ╔═╡ 20605ee6-f245-4e77-b014-a8e42a520e8d\nn = 10\n\n# ╔═╡ c69f8278-9627-458b-8204-91ae08efbf92\npoints = [exp(2 * pi * im * k / n) for k in 1:n];\n\n# ╔═╡ a5f4d797-db11-4d6a-8906-b4af6804a936\nplot(points, seriestype = :scatter, legend = false);\n\n# ╔═╡ 46f62dad-820b-42d3-8cdd-ab02cacabc47\nxPts, yPts = real.(points), imag.(points);\n\n# ╔═╡ 758082fe-038e-4090-b658-111db3ee1f13\nedges  = [(v, u) for v in 1:n for u in (v+1):n];\n\n# ╔═╡ 931e4862-c109-4b17-9048-7826f3dd0c6f\nanimate = Animation();\n\n# ╔═╡ 3017c6db-acee-422d-bb97-692495972631\nplot(xPts, yPts, seriestype = :scatter, legend = false) # 等价于 scatter(xPts, yPts)\n\n# ╔═╡ 404716dd-7a05-4f3b-b336-cab7fc679ed1\nfor i in eachindex(edges)\n\tu, v = edges[i][1], edges[i][2]\n\txpoints = [xPts[u], xPts[v]]\n\typoints = [yPts[u], yPts[v]]\n\tplot!(xpoints, ypoints, line = :red, legend = false)\n\tframe(animate)\nend\n\n# ╔═╡ 43b3b163-05a7-4c06-a948-bf5c001b7af0\ngif(animate)\n\n# ╔═╡ 4c0169d7-b280-4326-aa79-9c979280077a\nmd\"\"\"\n## 1.4. 随机数\n\"\"\"\n\n# ╔═╡ 694d2ceb-233f-49ea-9416-9e8a8f272d38\nmd\"\"\"\n## 1.6. 嵌入其他语言\n\"\"\"\n\n# ╔═╡ 72a095fa-c5cf-4eb1-909d-d8b49af0bdc9\nStatisticsWithJulia.list_notebooks(@__FILE__)\n\n# ╔═╡ 8a20fa4c-338c-48c9-a12a-02e6d67153df\nStatisticsWithJulia.footer() ## FFFFF\n\n# ╔═╡ Cell order:\n# ╟─ec3f7b5c-cee9-432f-b33c-a08e16c0171a\n# ╟─6dd76507-be07-4c3a-9747-99eca74d3519\n# ╟─9d98fa7a-3654-40a0-8a96-75c3fca007ae\n# ╟─42da8f74-1b44-11ec-32f2-276bdcef1c69\n# ╟─e71aacbb-efff-4b93-b5c4-cbdfa88981ad\n# ╠═0660d564-9a26-417d-9a2c-42ef181187c2\n# ╠═77c5ddd3-ddfc-4a57-ab48-e9db765057d3\n# ╟─8eefb8aa-ae85-4231-abf5-9948cdc92ec1\n# ╠═d22fc28f-c591-4db2-8275-54d93fda85e9\n# ╠═9d9f4d96-7755-4fd1-851a-092929ad1ac7\n# ╠═4ece5fc8-18d5-408a-851b-31ce58015e72\n# ╠═8b0db1dd-5d79-42e5-9763-ca4ef7259060\n# ╠═a0322171-cff9-48bb-9f73-792c8ea4798f\n# ╠═3711c338-748f-448e-a06d-d3c29094a14b\n# ╠═c266f6e2-4e8e-4870-ac38-d4d0e8b9d042\n# ╠═8f3277e9-7905-4beb-9ef1-c3e18b2f449a\n# ╠═f6e99ac9-2183-4ea2-991e-f3422b1d1f20\n# ╠═cd0ce1b4-9bc9-4218-95e9-e576abeb1af1\n# ╠═37fec978-f817-4aa8-85fc-4912eaeb402e\n# ╠═adc183db-ff23-43de-8cf6-a961d13c2f01\n# ╠═4f1ce95f-2f2f-4817-9d5f-348184a1b800\n# ╠═dec64158-9161-4b37-b19f-432a5635719e\n# ╠═5a401f10-09d2-4939-87fe-621f469a68ee\n# ╠═c2c7c916-1ba8-4e14-a25b-e15faf676f8a\n# ╠═2fdb3281-7229-4f18-b9d9-bc5e3086d903\n# ╠═f77b7762-29ee-4472-a4ee-a5c1a6dfb369\n# ╠═e9d5ee6c-de1a-41ee-850e-a6f5471537ea\n# ╠═93b0afb2-e9f3-434d-b21a-2ccad6a12d90\n# ╠═90fe2c2b-d62d-40b5-9a34-0eb1e9836250\n# ╟─8bcc15c7-d66a-40cc-9f33-50c6de62fadc\n# ╠═428c124a-1052-45c8-a49b-b1047267d644\n# ╠═863624c7-f378-467a-bed2-94182bae73b7\n# ╠═0e8b6a32-ba23-4e37-b78c-8ffb3779a43e\n# ╠═9e35d6a1-df94-4a27-9e04-234548495780\n# ╠═1b45a9bf-56c7-4b7b-bdd5-b4fcaa572ec0\n# ╟─60b263eb-f786-40c4-b60b-2daabdacba7b\n# ╠═b0db7a9c-2498-46c5-bf3c-280d3083ba88\n# ╠═412ee0c1-26ad-4b9f-9d6e-c552d8431e76\n# ╠═aa5e313d-19d9-4300-a65e-f547f7e571d0\n# ╠═0ba25fa7-72cb-4d6e-bfaf-eddcf12b9f9c\n# ╠═d5251a23-b71e-4faf-9f5a-f6ab1d2ffb7d\n# ╠═b717d872-0d16-4556-a6c8-1ccc3c7b76c3\n# ╠═72b3ed37-3f3f-4a7d-9036-dadb06c3e1e4\n# ╠═8c6e966d-9185-4a44-8cd9-e69528cee54b\n# ╠═1e9be5f5-ab15-4a29-8fd6-d20fee084ad5\n# ╠═3baed4bd-1c0c-4d44-b7ab-f7c0627fda1b\n# ╟─59b884e5-a55a-42f6-9ed4-404d55eae5e9\n# ╠═3cbd7219-7fb0-4c6e-a2ad-724e97b67d94\n# ╠═93a86467-cf02-4d3c-b127-79247a588250\n# ╠═0423223e-90c5-4d86-8370-66ddee6ba496\n# ╠═721c67fd-6d40-4171-89c4-21a1c0064880\n# ╠═5a4dd40b-d917-4634-a4d4-255c63d68d3f\n# ╠═2edcc72c-bfa4-4623-a34f-220c0df9c4d3\n# ╠═20097ff6-c516-454c-978f-4c92e6c72d52\n# ╠═fbbc0558-7916-4308-b8be-4428f47ca4e5\n# ╠═290d3b7f-ee12-476c-a4f2-189671c84398\n# ╠═cc728038-b20f-4b93-97a7-883d5734a0b2\n# ╠═2eca9295-370d-41e9-95a4-b56ee2b0e1dc\n# ╠═b4c5a72d-5ce1-4e21-a04f-8344d1023648\n# ╠═4f11cc1a-a78e-4d6c-8bd2-857f85f48aa8\n# ╠═50039da8-2c71-4a1d-8cc1-2d4bd8126988\n# ╠═efb2b80c-af6c-4f6e-bcba-e57c7c39cab3\n# ╟─1ca893dd-2040-47df-8fa0-c3cb4dd0d7dc\n# ╟─dbbcd955-e0c9-4a6c-81bf-fe5c5ad2f018\n# ╠═5565b0a4-792b-40f6-82a2-f8f642432129\n# ╠═6d4175a4-af6e-4a08-bcd2-0b1966ae9035\n# ╟─c4a58e43-2ea8-48fa-a99d-09f83b1b8ba8\n# ╠═e0e5ef4a-fc35-4d9b-9a34-a9439d87051d\n# ╠═c9d041cb-6a29-449a-8909-b529e8c562a6\n# ╟─c77241fb-bd9e-4270-bd04-e8b5bcb2406b\n# ╠═d507db6a-f869-4dc3-b7ef-fd3518fc1660\n# ╠═f924796f-52f3-4b4b-aa47-61a179874647\n# ╠═87296377-fe6d-4225-b114-a8c3b8bea1bc\n# ╠═aa61efe4-b3a2-4379-a748-f37cd7f9c6fb\n# ╠═182ab07b-a3e6-47f0-8de5-d59113027c43\n# ╠═6262451f-4dcf-4f84-8be6-2f8fbf2631bd\n# ╠═3d664567-d879-41f7-9e1a-cdfc08e4e7c9\n# ╠═5e03a17e-861e-4749-b18e-00e293d24f28\n# ╠═4d5c7119-f2bf-44ed-bc20-5597a795fbcd\n# ╠═af2e86c1-4c58-4577-9ae9-313f8ae78475\n# ╠═9461292e-3658-41e2-8349-45790fa7c9e0\n# ╠═7e03b8d1-1ddb-435f-b9ba-b72b0c44da18\n# ╠═e54420c1-1ff3-4f38-b9b8-0e3a18127c9a\n# ╠═458dfaeb-0370-4e61-90a2-f5b54a0fab42\n# ╠═b7729c93-781a-46ec-b057-65c4e9e15a04\n# ╠═543de112-675c-4368-957d-f37647ad85bd\n# ╠═37f6486e-e03c-4ddb-bca6-d13157d69822\n# ╠═68d89124-d6e9-4609-b12a-d3b508733680\n# ╟─6003cd52-89ea-4d93-ac00-43ca395357b8\n# ╟─92c42555-8550-4c1b-9b1a-502813c40237\n# ╠═5c3f1925-ebfb-4bef-8425-635262927bf1\n# ╠═ec02b4a7-529b-4d37-ba4b-bf146a33ee0f\n# ╠═954f166b-e8db-4cf7-a0a2-75ab3b3acbe0\n# ╠═e97dcedb-4b53-4ce8-a0e9-ed20b77d8b2d\n# ╟─f662c9f4-8004-43d6-ad1e-872ad3d24e48\n# ╠═c72335d5-39e3-4ab9-a398-e3960dcafe0c\n# ╠═8ebae10c-3148-43fe-9b14-f07934c3b2ea\n# ╠═e49a1426-bcf5-453a-8753-2bb8387e67eb\n# ╠═46bd26e6-c1bf-4fa3-890a-2d424865c2dc\n# ╟─55e79482-e30e-4eea-b083-cac2a9667348\n# ╠═9537df9b-7fc8-4b32-bc7c-d8ee8730d73a\n# ╠═6434a9f1-aa8a-491f-ac7e-c58b3a4b2638\n# ╠═4abd57c6-1a0c-4e7c-a195-d07ddc299b2c\n# ╠═aa2c895f-7219-4b98-bf50-c96d676ead09\n# ╠═5fb204e1-d150-4a3c-ac19-6fa5b67b072b\n# ╠═c0df29b8-368d-40d1-bad0-73493531903a\n# ╠═51046c66-6e14-420e-8a5e-5a58580841a6\n# ╠═3659f664-3fc3-48bd-94e3-f57ae84e7301\n# ╟─9392cdfb-ceef-40ac-a67b-8c7ca33de123\n# ╠═20605ee6-f245-4e77-b014-a8e42a520e8d\n# ╠═c69f8278-9627-458b-8204-91ae08efbf92\n# ╠═a5f4d797-db11-4d6a-8906-b4af6804a936\n# ╠═46f62dad-820b-42d3-8cdd-ab02cacabc47\n# ╠═758082fe-038e-4090-b658-111db3ee1f13\n# ╠═931e4862-c109-4b17-9048-7826f3dd0c6f\n# ╠═3017c6db-acee-422d-bb97-692495972631\n# ╠═404716dd-7a05-4f3b-b336-cab7fc679ed1\n# ╠═43b3b163-05a7-4c06-a948-bf5c001b7af0\n# ╟─4c0169d7-b280-4326-aa79-9c979280077a\n# ╟─694d2ceb-233f-49ea-9416-9e8a8f272d38\n# ╟─72a095fa-c5cf-4eb1-909d-d8b49af0bdc9\n# ╟─8a20fa4c-338c-48c9-a12a-02e6d67153df\n", "meta": {"hexsha": "57e47ab91ea14e523247011c3bb20cc99c184858", "size": 16487, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/01-Introducing-Julia.jl", "max_stars_repo_name": "likanzhan/StatisticsWithJulia.jl", "max_stars_repo_head_hexsha": "612dee1036b6cffd0853c44bd80fe1bcd3a31a0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/01-Introducing-Julia.jl", "max_issues_repo_name": "likanzhan/StatisticsWithJulia.jl", "max_issues_repo_head_hexsha": "612dee1036b6cffd0853c44bd80fe1bcd3a31a0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/01-Introducing-Julia.jl", "max_forks_repo_name": "likanzhan/StatisticsWithJulia.jl", "max_forks_repo_head_hexsha": "612dee1036b6cffd0853c44bd80fe1bcd3a31a0d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5707898659, "max_line_length": 125, "alphanum_fraction": 0.6955176806, "num_tokens": 9760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.7714308631232801}}
{"text": "using JuMP, Ipopt, LinearAlgebra\n\n## Example from Nocedal 16.2 (p 452-453)\nx̄ = [2;-1;1]\nλ = [3;-2]\n\n# set up model\nm = JuMP.Model(solver=IpoptSolver(print_level=0))\n\n# set up primal variables\nn = 3\n@variable(m, x[1:n])\n\n# set up constraints\nG = [6. 2. 1.; 2. 5. 2.; 1. 2. 4.]\nc = [-8.; -3.; -3]\nA = [1. 0. 1.; 0. 1. 1.]\nb = [3.; 0.]\n\n@objective(m, Min, 0.5*x'*G*x + x'*c)\n\n@constraint(m, con, A*x .== b)\n\nprint(m)\n\nstatus = JuMP.solve(m)\n\n# Solution\nprintln(\"Objective value: \", getobjectivevalue(m))\nprintln(\"x = \", getvalue(x))\nprintln(\"λ = \", getdual(con))\n\n\n##\n\n# set up model\nm = JuMP.Model(solver=IpoptSolver())\n\n# set up primal variables\nn = 3\n@variable(m, x[1:n])\n\n# set up constraints\nG = [6. 2. 1.; 2. 5. 2.; 1. 2. 4.]\nc = [-8.; -3.; -3]\nA = [1. 0. 1.; 0. 1. 1.]\nb = [3.; 0.]\n\n@objective(m, Min, x'*x)\n\n@constraint(m, con, G*x - c .== 0)\n# @constraint(m, con2, A*x .== b)\n\nprint(m)\n\nstatus = JuMP.solve(m)\n\n# Solution\nprintln(\"Objective value: \", getobjectivevalue(m))\nprintln(\"x = \", getvalue(x))\nprintln(\"λ = \", getdual(con))\n", "meta": {"hexsha": "3bd619e9c6016b482d8c2bdbffbb954ec342de8f", "size": 1039, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "development/qp_with_JuMP_example.jl", "max_stars_repo_name": "GathererA/TrajectoryOptimization.jl", "max_stars_repo_head_hexsha": "c036b790555553b3477c7bebeaea118e17e43142", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-01T16:16:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-01T16:16:08.000Z", "max_issues_repo_path": "development/qp_with_JuMP_example.jl", "max_issues_repo_name": "GathererA/TrajectoryOptimization.jl", "max_issues_repo_head_hexsha": "c036b790555553b3477c7bebeaea118e17e43142", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "development/qp_with_JuMP_example.jl", "max_forks_repo_name": "GathererA/TrajectoryOptimization.jl", "max_forks_repo_head_hexsha": "c036b790555553b3477c7bebeaea118e17e43142", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.7580645161, "max_line_length": 50, "alphanum_fraction": 0.5697786333, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474194456936, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.771419277950542}}
{"text": "## Simple PageRank\n# This treats everything as a dense matrix :(\nA = [0 1 1 1 1 0 1 0 0 0\n     1 0 0 0 0 0 0 0 0 0\n     0 0 0 0 1 1 1 0 0 0\n     1 1 0 0 1 1 0 1 0 0\n     1 1 1 1 0 0 0 0 1 0\n     0 0 1 0 0 0 1 0 1 1\n     0 0 0 0 0 1 0 0 0 1\n     0 0 0 0 0 0 0 0 1 0\n     0 0 0 0 0 0 0 1 0 0\n     0 0 0 0 0 0 0 0 0 0]\nd = sum(A,dims=2)\n##\nusing Printf\nfor i=1:10\n  for j=1:10\n    if i==j\n      @printf(\"1 & \")\n    elseif A[j,i] != 0\n      @printf(\"-\\\\alpha/%i & \", d[j])\n    else\n      @printf(\"0 & \")\n    end\n  end\n  println(\"\\\\\\\\\")\nend\n## Build the I - alpha D^+ A'\nalpha = 0.85\nM = zeros(size(A)...)\nfor i=1:10\n  for j=1:10\n    if i==j\n      M[i,j] = 1\n    elseif A[j,i] != 0\n      M[i,j] = -alpha*A[j,i]/d[j]\n    else\n      M[i,j] = 0\n    end\n  end\nend\nM[:,end] .= -alpha/10\nM[end,end] += 1\nM[:,1]\n##\nb = ones(size(A,1))/size(A,1)*(1-alpha)\nx = M\\b\n", "meta": {"hexsha": "2b9d7fcc334c90b0a24adc177846cbacd92a2eeb", "size": 851, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2-unit-1-demos/ranking-simple.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "2-unit-1-demos/ranking-simple.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2-unit-1-demos/ranking-simple.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 17.7291666667, "max_line_length": 45, "alphanum_fraction": 0.4582843713, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474194456936, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.771419277950542}}
{"text": "# ---\n# title: 1175. Prime Arrangements\n# id: problem1175\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Easy\n# categories: Math\n# link: <https://leetcode.com/problems/prime-arrangements/description/>\n# hidden: true\n# ---\n# \n# Return the number of permutations of 1 to `n` so that prime numbers are at\n# prime indices (1-indexed.)\n# \n# _(Recall that an integer  is prime if and only if it is greater than 1, and\n# cannot be written as a product of two positive integers both smaller than\n# it.)_\n# \n# Since the answer may be large, return the answer **modulo`10^9 + 7`**.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: n = 5\n#     Output: 12\n#     Explanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: n = 100\n#     Output: 682289015\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= n <= 100`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "144e3d6aa11a22d6f04a0d3a89acf0de75875a52", "size": 1016, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1175.prime-arrangements.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/unresolved/1175.prime-arrangements.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/unresolved/1175.prime-arrangements.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 19.5384615385, "max_line_length": 131, "alphanum_fraction": 0.6053149606, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.8757869932689566, "lm_q1q2_score": 0.7713906163811811}}
{"text": "@polly function kernel_adi(tsteps, u, v, p, q)\n    n = size(u,1)\n\n    DX = 1.0 / n\n    DY = 1.0 / n\n    DT = 1.0 / tsteps\n    B1 = 2.0\n    B2 = 1.0\n    mul1 = B1 * DT / (DX * DX)\n    mul2 = B2 * DT / (DY * DY)\n\n    a = -mul1 /  2.0;\n    b = 1.0 + mul1\n    c = a\n    d = -mul2 / 2.0\n    _e = 1.0 + mul2\n    f = d\n\n    for t = 1:tsteps\n        # Column Sweep\n        for i = 2:(n-1)\n            v[1,i] = 1.0\n            p[i,1] = 0.0\n            q[i,1] = v[1,i]\n            for j = 2:(n-1)\n                p[i,j] = -c / (a * p[i,j-1] + b)\n                q[i,j] = (-d*u[j,i-1]+(1.0+2.0*d)*u[j,i] - f*u[j,i+1]-a*q[i,j-1])/(a*p[i,j-1]+b)\n            end\n\n            v[n,i] = 1.0\n            for j = (n-1):-1:2\n                v[j,i] = p[i,j] * v[j+1,i] + q[i,j]\n            end\n        end\n\n        # Row Sweep\n        for i = 2:(n-1)\n            u[i,1] = 1.0\n            p[i,1] = 0.0\n            q[i,1] = u[i,1]\n            for j = 2:(n-1)\n                p[i,j] = -f / (d*p[i,j-1] + _e)\n                q[i,j] = (-a*v[i-1,j]+(1.0+2.0*a)*v[i,j] - c*v[i+1,j]-d*q[i,j-1])/(d*p[i,j-1]+_e)\n            end\n\n            u[i,n] = 1.0\n            for j = (n-1):-1:2\n                u[i,j] = p[i,j] * u[i,j+1] + q[i,j]\n            end\n        end\n    end\nend\n\nlet\n    tsteps = 500\n    n = 1000\n\n    u = zeros(Float32, n, n)\n    v = zeros(Float32, n, n)\n    p = zeros(Float32, n, n)\n    q = zeros(Float32, n, n)\n\n    for i = 1:n, j = 1:n\n        u[i,j] =  (i + n-j) / n\n    end\n\n    SUITE[\"adi\"] = @benchmarkable kernel_adi($tsteps, u, v, p, q) setup = (u = copy($u); v = copy($v); p = copy($p); q = copy($q))\nend\n", "meta": {"hexsha": "b458e8fdbfd1d79a74df9b2b76bbe3e2e9639c35", "size": 1602, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stencils/adi.jl", "max_stars_repo_name": "MatthiasJReisinger/PollyBenchmarks.jl", "max_stars_repo_head_hexsha": "a13e08dc6a4f3f5e97d62d71c517db5fc5e6bc95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-02-21T22:46:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-07T16:03:10.000Z", "max_issues_repo_path": "src/stencils/adi.jl", "max_issues_repo_name": "MatthiasJReisinger/PollyBenchmarks.jl", "max_issues_repo_head_hexsha": "a13e08dc6a4f3f5e97d62d71c517db5fc5e6bc95", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stencils/adi.jl", "max_forks_repo_name": "MatthiasJReisinger/PollyBenchmarks.jl", "max_forks_repo_head_hexsha": "a13e08dc6a4f3f5e97d62d71c517db5fc5e6bc95", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-05-08T01:57:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T22:49:00.000Z", "avg_line_length": 23.2173913043, "max_line_length": 130, "alphanum_fraction": 0.34082397, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321808, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7713438349589431}}
{"text": "using Plots, Distributions, LaTeXStrings\n\n# Evaluates target distribution π(q)\nfunction π_q(q)\n    return 0.3*1/sqrt(2*pi)*exp(-(q+2)^2/2) + 0.7*1/sqrt(pi)*exp(-(q-3)^2)\nend\n\n# Evaluates conditional probability π(p|q)\nfunction π_pq(p,q)\n    return pdf(Normal(0, 1), p)\nend\n\n# Evaluates Kinetic enery K(p,q)\nfunction K(p,q)\n    return -log(π_pq(p,q))\nend\n\n# Evaluates Potential energy V(q)\nfunction V(q)\n    return -log(π_q(q))\nend\n\n# Evaluates dV/dq at q\nfunction dV_dq(q)\n    return 1/π_q(q) * (0.3*1/sqrt(2*pi)*(q+2)*exp(-(q+2)^2/2) +\n    0.7*2/sqrt(pi)*(q-3)*exp(-(q-3)^2))\nend\n\n# Compute Hamiltonian at q,p\nfunction H(p,q)\n    return K(p,q) + V(q)\nend\n\n\n# Gets a trajectory of length L with n steps\nfunction get_trajectory(q,p,L,n)\n    # Flip sign of momentum\n    # p *= -1\n\n    # Step size\n    ϵ = L/n\n\n    q_trajectory = zeros(n)\n    p_trajectory = zeros(n)\n\n    q_trajectory[1] = q\n    p_trajectory[1] = p\n\n    for j=2:n\n        ψ = p_trajectory[j-1] - ϵ/2 * dV_dq(q_trajectory[j-1])\n        q_trajectory[j] = q_trajectory[j-1] + ϵ*ψ\n        p_trajectory[j] = ψ - ϵ/2*dV_dq(q_trajectory[j])\n    end\n\n    return q_trajectory, p_trajectory\nend\n\nfunction hmc_alg(q₀, p₀)\n    # Number of samples to return\n    n = 20000\n\n    q_samples = zeros(n)\n    p_samples = zeros(n)\n    q_samples[1] = q₀\n    p_samples[1] = p₀\n\n    trajectory_length = 1\n    trajectory_partitions = 3\n\n    for j=2:n\n\n        q = q_samples[j-1]\n        p = rand(Normal(0,1))\n        q_proposal_trajectory, p_proposal_trajectory =\n        get_trajectory(q, p, trajectory_length, trajectory_partitions)\n\n        # Proposal\n        q_L = last(q_proposal_trajectory)\n        p_L = last(p_proposal_trajectory)\n\n        # Compute acceptance probabilty\n        α = min(1, exp(H(p,q) - H(-p_L,q_L)))\n\n        if rand() < α\n            q_samples[j] = q_L\n            p_samples[j] = -p_L\n        else\n            q_samples[j] = q\n            p_samples[j] = p\n        end\n\n    end\n\n    return q_samples\nend\n\n# Generate HMC samples\nsamples = hmc_alg(0,1)\n\n# Plot histogram of samples\nx_vals = -5:0.01:5\ny_vals = [π_q(q) for q in x_vals]\nPlots.plot(x_vals, y_vals,\n bg = RGB(247/255, 236/255, 226/255),\n grid = false,\n legend = false,\n xlabel = L\"q\",\n ylabel = L\"\\pi(q)\")\nhistogram!(samples, color = \"blue\", opacity = 0.15, normalize = true)\n\n\nsavefig(\"../images/hmc_ex_1_histogram.svg\")\n", "meta": {"hexsha": "fc140edce99c4a419438e2d6843311f1ed3779fa", "size": 2348, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/stochastic-approximations/code/hmc_ex_1.jl", "max_stars_repo_name": "seanrattana/courses", "max_stars_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-08-21T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T15:46:58.000Z", "max_issues_repo_path": "content/stochastic-approximations/code/hmc_ex_1.jl", "max_issues_repo_name": "seanrattana/courses", "max_issues_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-08-23T06:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-26T12:47:12.000Z", "max_forks_repo_path": "content/stochastic-approximations/code/hmc_ex_1.jl", "max_forks_repo_name": "seanrattana/courses", "max_forks_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-08-18T21:23:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T19:14:33.000Z", "avg_line_length": 20.7787610619, "max_line_length": 74, "alphanum_fraction": 0.6081771721, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875642, "lm_q2_score": 0.8128673133042216, "lm_q1q2_score": 0.7713438273319977}}
{"text": "using LinearAlgebra: Matrix, sqrt\nusing LinearAlgebra\nusing FFTW\nusing MAT\n\nfunction alpha1D(k, N)\n    if k>0\n        return sqrt(2/N)\n    else\n        return sqrt(1/N)\n    end\nend\n\nfunction alpha2D(k, l, N)\n    if k==0 && l==0\n        return 1/N\n    elseif l==0 || k==0\n        return sqrt(2)/N\n    else\n        return 2/N\n    end\nend\n\n\n\nfunction mDCT(v)\n    N = length(v)\n    c = zeros(1, N)\n\n    for k = 0:(N-1)\n        sum = 0.0\n        for i = 0:(N-1)\n            sum = sum + v[i+1] * cos(k*pi*((2*i+1)/(2*N)))\n        end\n        c[k+1] = alpha1D(k,N) * sum\n    end\n    return c\nend\n\n\nfunction miDCT(c)\n    N = length(c)\n    v = zeros(1,N)\n    for j = 0:(N-1)\n        for k = 0:(N-1)\n            ak= alpha1D(k,N)\n            v[j+1] = v[j+1] +(c[k+1] * ak * cos(pi*k*((2*j)+1)/(2*N)))\n        end\n    end\n    return v\nend\n\nfunction mDCT2n4(matrix)\n    N = size(matrix,1)\n    M = size(matrix,1)\n\n    cmat = zeros(N, M)\n\n    for k = 0:(N-1)\n        for l = 0:(M-1)\n            sum = 0\n            for i = 0:(N-1)\n                for j = 0:(M-1)\n                    sum = sum + (matrix[i+1, j+1] * cos(k*pi*((2*i+1)/(2*N))) * cos(l*pi*((2*j+1)/(2*M))))\n                end\n            end\n            cmat[k+1, l+1] = alpha2D(k,l,N) * sum\n        end\n    end\n    return cmat\nend\n\n\nfunction miDCT2n4(cmat)\n    N = size(matrix,1)\n    M = size(matrix,2)\n    matrix = zeros(N, M)\n    sum = 0\n    for i = 0:(N-1)\n        for j = 0:(M-1)\n            for k = 0:(N-1)\n                for l = 0:(M-1)\n                    ak2 = alpha2D(k,l,N)\n                    matrix[i+1, j+1] = matrix[i+1, j+1] + (cmat[k+1, l+1] *ak2 *cos(pi*k*((2*i)+1)/(2*N)) * cos(pi*l*((2*j)+1)/(2*M)))\n                end\n            end\n        end\n    end\n    return matrix\nend\n\n\nfunction mDCT2n3(matrix)\n    N = size(matrix,1)\n    M = size(matrix,2)\n    cmat = zeros(N,M)\n\n\n    for j = 0:(N-1)\n        ind = j+1\n        cmat[ind, :] = mDCT(matrix[ind,:])\n    end\n    cmatT = transpose(cmat)\n    for k = 0:(M-1)\n        cmatT[k+1,:] = mDCT(cmatT[k+1,:]) \n    end\n    cmat = transpose(cmatT)\n    return cmat \nend\n\nfunction miDCT2n3(cmat)\n    N = size(cmat,1)\n    M = size(cmat,2)\n    matrix = zeros(N,M)\n    matrixT = zeros(N,M)\n\n    for j = 0:(N-1)\n        matrix[j+1,:] = miDCT(cmat[j+1,:])\n    end\n    matrixT = transpose(matrix)\n    for k = 0:(M-1)\n        matrixT[k+1,:] = miDCT(matrixT[k+1,:])\n    end\n    matrix = transpose(matrixT)\n    return matrix\nend\n\n\n", "meta": {"hexsha": "50a5d3128d2b14983cf652d863125c9e34a41dd8", "size": 2433, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mydct.jl", "max_stars_repo_name": "illoxian/bitmap-compressor-tool", "max_stars_repo_head_hexsha": "65532205b410edb67ec09a4e5ff36cbd4bd45c73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mydct.jl", "max_issues_repo_name": "illoxian/bitmap-compressor-tool", "max_issues_repo_head_hexsha": "65532205b410edb67ec09a4e5ff36cbd4bd45c73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mydct.jl", "max_forks_repo_name": "illoxian/bitmap-compressor-tool", "max_forks_repo_head_hexsha": "65532205b410edb67ec09a4e5ff36cbd4bd45c73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8604651163, "max_line_length": 134, "alphanum_fraction": 0.4488286067, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948917260153714, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7713438238091527}}
{"text": "\nimport LinearAlgebra\n\nimport RungeKutta.Tableaus: get_lobatto_nodes, get_lobatto_weights, get_gauss_nodes\n\n\n@doc raw\"\"\"\nThe projective Lobatto-GLRK coefficients are implicitly given by\n```math\n\\sum \\limits_{j=1}^{s} a_{ij} c_{j}^{k-1} = \\frac{\\bar{c}_i^k}{k}  \\qquad i = 1 , \\, ... , \\, \\sigma , \\; k = 1 , \\, ... , \\, s ,\n```\nwhere $c$ are Gauß-Legendre nodes with $s$ stages and $\\bar{c}$ are Gauß-Lobatto nodes with $\\sigma$ stages.\n\"\"\"\nfunction get_lobatto_glrk_coefficients(s, σ=s+1, T=Float64)\n    if σ == 1\n        @error \"Lobatto III coefficients for one stage are not defined.\"\n    end\n\n    c = get_gauss_nodes(s)\n    b̄ = get_lobatto_weights(σ)\n    c̄ = get_lobatto_nodes(σ)\n    M = [ c[j]^(k-1) for k in 1:s, j in 1:s ]\n    \n    row(i) = begin\n        r = [ c̄[i]^k / k for k in 1:s ]\n        M \\ r\n    end\n    \n    ā = vcat([row(i)' for i in 1:σ]...)\n\n    CoefficientsIRK{T}(:LobattoIIIGLRK, s^2, s, σ, ā, b̄, c̄)\nend\n\n\nfunction get_lobatto_ω_matrix(s)\n    as = TableauLobattoIIIA(s).a[2:s,1:s]\n    es = zeros(s)\n    es[s] = 1\n\n    Q = vcat( hcat(as, zeros(s-1)), hcat(zeros(s)', 1) )\n    L = vcat( as, es' )\n    ω = inv(L) * Q\n    \n    return ω\nend\n", "meta": {"hexsha": "7d9df429ab894c4cad6d19d755dfe85491c0f8ed", "size": 1165, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tableaus/coefficients_lob.jl", "max_stars_repo_name": "JuliaGNI/GeometricIntegrators.jl", "max_stars_repo_head_hexsha": "bf1ca810d75e43c1d89e4981beea35451858155a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-12-29T10:41:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T11:48:39.000Z", "max_issues_repo_path": "src/tableaus/coefficients_lob.jl", "max_issues_repo_name": "JuliaGNI/GeometricIntegrators.jl", "max_issues_repo_head_hexsha": "bf1ca810d75e43c1d89e4981beea35451858155a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2020-11-16T16:45:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T17:51:11.000Z", "max_forks_repo_path": "src/tableaus/coefficients_lob.jl", "max_forks_repo_name": "michakraus/GeometricIntegrators.jl", "max_forks_repo_head_hexsha": "fcca462f25a1f9d5ff0954d5d71ef7cd1389ab3e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-05T12:54:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T18:19:13.000Z", "avg_line_length": 25.3260869565, "max_line_length": 129, "alphanum_fraction": 0.5785407725, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172572644807, "lm_q2_score": 0.8128673155708976, "lm_q1q2_score": 0.7713438236114774}}
{"text": "\"\"\"\n    lorenz_key(x_init, y_init, z_init, num_keys; α=10.0, ρ=28.0, β=2.667, dt=0.01, scaling_factor=10.0^16, upper_bound=256.0)\n\nGenerates 3 vectors of pseudo-random numbers using Lorenz system of differential\nequations.\n\nThe equations -\n\n\\$\\\\frac{dx}{dt} = α * (y - x)\\$\n\\$\\\\frac{dy}{dt} = x * (ρ - z) - y\\$\n\\$\\\\frac{dz}{dt} = x * y - β * z\\$\n\n# Arguments\n- `x_init::Float64`: Initial value of x.\n- `y_init::Float64`: Initial value of y.\n- `z_init::Float64:` Initial value of z.\n- `num_keys::Int64`: Number of keys (in a single list) to be generated.\n- `α::Float64`: Constant associated with Lorenz system of differential equations.\n- `ρ::Float64`: Constant associated with Lorenz system of differential equations.\n- `β::Float64`: Constant associated with Lorenz system of differential equations.\n- `scaling_factor::Float64=10.0^16`: Factor to be multiplied to the generated value of pseudo-random\n    number. Ideally, the factor should be > upper_bound.\n- `upper_bound::Float64=256.0`: Upper bound of keys (not included). Use 256 for encrypting images\n    as the RGB values of a pixel varies from 0 to 255.\n\n# Returns\n- `x::Vector{Int64}`: Generated pseudo-random keys corresponding to x values.\n- `y::Vector{Int64}`: Generated pseudo-random keys corresponding to y values.\n- `z::Vector{Int64}`: Generated pseudo-random keys corresponding to z values.\n\n# Example\n```jldoctest\njulia> lorenz_key(0.01, 0.02, 0.03, 20)\n([0, 0, 256, 24, 129, 42, 54, 134, 43, 179, 85, 19, 24, 44, 71, 210, 238, 152, 22, 27], [0, 0, 240, 55, 25, 163, 89, 243, 123, 5, 197, 64, 227, 54, 188, 226, 154, 134, 64, 69], [0, 0, 80, 227, 178, 204, 89, 33, 144, 139, 105, 208, 108, 155, 61, 254, 57, 102, 149, 47])\n```\n\"\"\"\nfunction lorenz_key(\n    x_init::Float64,\n    y_init::Float64,\n    z_init::Float64,\n    num_keys::Int64;\n    α::Float64=10.0,\n    ρ::Float64=28.0,\n    β::Float64=2.667,\n    dt::Float64=0.01,\n    scaling_factor::Float64=10.0^16,\n    upper_bound::Float64=256.0\n)\n    # Initializing 3 empty lists\n    x = zeros(Float64, num_keys)\n    y = zeros(Float64, num_keys)\n    z = zeros(Float64, num_keys)\n\n    # Initializing initial values\n    x[1], y[1], z[1] = x_init, y_init, z_init\n\n    # System of equations\n    for i = 1:num_keys - 1\n        x[i + 1] = x[i] + (α * (y[i] - x[i]) * dt)\n        y[i + 1] = y[i] + ((x[i] * (ρ - z[i]) - y[i]) * dt)\n        z[i + 1] = z[i] + ((x[i] * y[i] - β * z[i]) * dt)\n    end\n\n    for i = 1:length(x)\n        x[i] = x[i] * scaling_factor % upper_bound\n        y[i] = y[i] * scaling_factor % upper_bound\n        z[i] = z[i] * scaling_factor % upper_bound\n    end\n\n    x = round.(Int, x)\n    y = round.(Int, y)\n    z = round.(Int, z)\n\n    return x, y, z\nend\n", "meta": {"hexsha": "352bf238e8733244c0426c7810d1cb3335960a0a", "size": 2682, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lorenz_key.jl", "max_stars_repo_name": "Saransh-cpp/ChaoticEncryption.jl", "max_stars_repo_head_hexsha": "93baccf0d54a8446343f56b0e114bf56ec5d195c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2022-02-16T17:00:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T21:14:34.000Z", "max_issues_repo_path": "src/lorenz_key.jl", "max_issues_repo_name": "Saransh-cpp/ChaoticEncryption.jl", "max_issues_repo_head_hexsha": "93baccf0d54a8446343f56b0e114bf56ec5d195c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2022-02-17T13:23:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:46:00.000Z", "max_forks_repo_path": "src/lorenz_key.jl", "max_forks_repo_name": "Saransh-cpp/ChaoticEncryption.jl", "max_forks_repo_head_hexsha": "93baccf0d54a8446343f56b0e114bf56ec5d195c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2022-02-19T07:19:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T08:45:48.000Z", "avg_line_length": 35.2894736842, "max_line_length": 268, "alphanum_fraction": 0.6222967934, "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611563610179, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.771336922615035}}
{"text": "#############################################################################\n# lieb_ando.jl\n# Returns tr(K' * A^{1-t} * K * B^t) where A and B are positive semidefinite\n# matrices and K is an arbitrary matrix (possibly rectangular).\n#\n# Disciplined convex programming information:\n#    lieb_ando(A,B,K,t) is concave in (A,B) for t in [0,1], and convex\n#    in (A,B) for t in [-1,0] or [1,2]. K is a fixed matrix.\n#\n# Seems numerically unstable when t is on the endpoints of these ranges.\n#\n# All expressions and atoms are subtypes of AbstractExpr.\n# Please read expressions.jl first.\n#\n#REFERENCE\n#   Ported from CVXQUAD which is based on the paper: \"Lieb's concavity\n#   theorem, matrix geometric means and semidefinite optimization\" by Hamza\n#   Fawzi and James Saunderson (arXiv:1512.03401)\n#############################################################################\n\nconst MatrixOrConstant = Union{AbstractMatrix, Constant}\n\nfunction lieb_ando(A::MatrixOrConstant, B::MatrixOrConstant, K::MatrixOrConstant, t::Rational)\n    if t < -1 || t > 2\n        throw(DomainError(t, \"t must be between -1 and 2\"))\n    end\n    return real(tr(K' * A^(1-t) * K * B^t))\nend\n\nfunction lieb_ando(A::MatrixOrConstant, B::AbstractExpr, K::MatrixOrConstant, t::Rational)\n    if t < -1 || t > 2\n        throw(DomainError(t, \"t must be between -1 and 2\"))\n    end\n    KAK = K' * A^(1-t) * K\n    KAK = (KAK+KAK')/2\n    return trace_mpower(B, t, KAK)\nend\n\nfunction lieb_ando(A::AbstractExpr, B::MatrixOrConstant, K::MatrixOrConstant, t::Rational)\n    if t < -1 || t > 2\n        throw(DomainError(t, \"t must be between -1 and 2\"))\n    end\n    KBK = K * B^t * K'\n    KBK = (KBK+KBK')/2\n    return trace_mpower(A, 1-t, KBK)\nend\n\nfunction lieb_ando(A::AbstractExpr, B::AbstractExpr, K::MatrixOrConstant, t::Rational)\n    n = size(A,1)\n    m = size(B,1)\n    Kvec = reshape(K',n*m,1)\n    KvKv = Kvec * Kvec'\n    KvKv = (KvKv+KvKv')/2\n    Im = Matrix(1.0*I, m, m)\n    In = Matrix(1.0*I, n, n)\n\n    is_complex = sign(A) == ComplexSign() || sign(B) == ComplexSign() || sign(Constant(K)) == ComplexSign()\n    if is_complex\n        T = HermitianSemidefinite(n*m)\n    else\n        T = Semidefinite(n*m)\n    end\n\n    if t >= 0 && t <= 1\n        # Concave function\n        add_constraint!(T, T in GeomMeanHypoCone(kron(A,Im), kron(In,conj(B)), t, false))\n        return real(tr(KvKv * T))\n    elseif (t >= -1 && t <= 0) || (t >= 1 && t <= 2)\n        # Convex function\n        add_constraint!(T, T in GeomMeanEpiCone(kron(A,Im), kron(In,conj(B)), t, false))\n        return real(tr(KvKv * T))\n    else\n        throw(DomainError(t, \"t must be between -1 and 2\"))\n    end\nend\n", "meta": {"hexsha": "2bd9e77755af8f9556a2de821ec0fd8e3c261b70", "size": 2641, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/atoms/sdp_cone/lieb_ando.jl", "max_stars_repo_name": "JinraeKim/Convex.jl", "max_stars_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 123, "max_stars_repo_stars_event_min_datetime": "2020-06-16T21:56:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:05:39.000Z", "max_issues_repo_path": "src/atoms/sdp_cone/lieb_ando.jl", "max_issues_repo_name": "JinraeKim/Convex.jl", "max_issues_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122, "max_issues_repo_issues_event_min_datetime": "2020-06-14T00:19:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T14:02:09.000Z", "max_forks_repo_path": "src/atoms/sdp_cone/lieb_ando.jl", "max_forks_repo_name": "JinraeKim/Convex.jl", "max_forks_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2020-08-21T07:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T13:40:50.000Z", "avg_line_length": 34.75, "max_line_length": 107, "alphanum_fraction": 0.5865202575, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611586300241, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7713369221751573}}
{"text": "function rref(mat::Matrix)\n    # make a copy of the original matrix\n    ret = float(copy(mat))\n    # # ret = copy(mat)\n    # initialize an array to memorize the pivots\n    pivot = []\n    # it's assumed that the matrix has $m$ rows and $n$ columns\n    m, n = size(ret)\n    # $i$ and $j$ are used to represent iterators of row and column,\n    # respectively\n    i = j = 1\n    # part of `forward elimination'\n    while i <= m && j <= n\n        # find the entry with largest absolute value\n        imax, vmax = 0.0, 0.0\n        for itr1 in i : m\n            if vmax < abs(ret[itr1, j])\n                imax, vmax = itr1, abs(ret[itr1, j])\n            end\n        end\n        # but this one seems to work pretty fine?\n        (vmax > 0) ? (k = imax) : (j += 1; continue)\n        # # if vmax > 0\n        # #     k = imax\n        # # else \n        # #     j += 1\n        # #     continue\n        # # end\n        # add the pivot position to the array\n        push!(pivot, (i, j))\n        # exchange the rows\n        for itr1 in i : n\n            ret[i, itr1], ret[k, itr1] = ret[k, itr1], ret[i, itr1]\n        end\n        # `forward elimination'\n        for itr1 in (i + 1) : m\n            scaler = ret[itr1, j] / ret[i, j]\n            for itr2 in (j + 1) : n\n                ret[itr1, itr2] -= ret[i, itr2] * scaler\n            end\n            # manually set this entry to 0, in case of using\n            # LU factorization\n            ret[itr1, j] = 0\n        end\n        i += 1\n        j += 1\n    end\n    # part of `back subsitution'\n    for itr1 in length(pivot) : -1 : 1\n        # get the pivot\n        i, j = pivot[itr1]\n        # `back subsitution`\n        for itr2 in 1 : (i - 1)\n            scaler = ret[itr2, j] / ret[i, j]\n            for itr3 in j : n\n                ret[itr2, itr3] -= ret[i, itr3] * scaler\n            end\n        end\n        # make entry on the pivot be 1\n        # and a little trick in order not to create a new variable\n        for itr2 in n : -1 : j\n            ret[i, itr2] /= ret[i, j]\n        end\n    end\n    return ret\nend", "meta": {"hexsha": "99b72f3c358908a5569df22993f0ab513c9cb681", "size": 2054, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear-algebra/rref.jl", "max_stars_repo_name": "Shimushushushu/Etude-Rhapsody", "max_stars_repo_head_hexsha": "cdca63ca92a44f0f31e716cf4acd3e0de17c9181", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear-algebra/rref.jl", "max_issues_repo_name": "Shimushushushu/Etude-Rhapsody", "max_issues_repo_head_hexsha": "cdca63ca92a44f0f31e716cf4acd3e0de17c9181", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear-algebra/rref.jl", "max_forks_repo_name": "Shimushushushu/Etude-Rhapsody", "max_forks_repo_head_hexsha": "cdca63ca92a44f0f31e716cf4acd3e0de17c9181", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1212121212, "max_line_length": 68, "alphanum_fraction": 0.4712755599, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7713153641536291}}
{"text": "#!/usr/bin/env julia\n# 1.7: Roots of a polynomial\nusing Roots\n\nfunction polynomialGenerator(a...)\n  n = length(a) - 1\n  poly = function (x)\n    return sum([a[i + 1] * x^i for i in 0:n])\n  end\n  return poly\nend\n\npolynomial = polynomialGenerator(1, 3, -10)\nzeroVals = find_zeros(polynomial, -10, 10)\nprintln(\"Zeros of the function f(x): \", zeroVals)\n", "meta": {"hexsha": "7541d445ae19ba2dd6f625530775da8bc708ce8e", "size": 348, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Basic/roots.jl", "max_stars_repo_name": "Fernal73/LearnJulia", "max_stars_repo_head_hexsha": "fc55f851d2c2cd20559b80074d60309b47d81fe8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Basic/roots.jl", "max_issues_repo_name": "Fernal73/LearnJulia", "max_issues_repo_head_hexsha": "fc55f851d2c2cd20559b80074d60309b47d81fe8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Basic/roots.jl", "max_forks_repo_name": "Fernal73/LearnJulia", "max_forks_repo_head_hexsha": "fc55f851d2c2cd20559b80074d60309b47d81fe8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.75, "max_line_length": 49, "alphanum_fraction": 0.6666666667, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7713153635323035}}
{"text": "##############################################################\n\"\"\"\n$(SIGNATURES)\n\nCalculation of Bernoulli function via Horner scheme based on Taylor\ncoefficients around 0.\n\"\"\"\n\nfunction bernoulli_horner(x)\n    y=x/47_900_160\n    y=x*y\n    y=x*(-1/1_209_600+y)\n    y=x*y\n    y=x*(1/30_240+y)\n    y=x*y\n    y=x*(-1/720+y)\n    y=x*y\n    y=x*(1/12+y)\n    y=x*(-1/2+y)\n    y=1+y\nend\n\n\n# Bernoulli thresholds optimized for Float64\nconst bernoulli_small_threshold=0.25\nconst bernoulli_large_threshold=40.0\n##############################################################\n\"\"\"\n$(SIGNATURES)\n\nBernoulli function ``B(x)=\\\\frac{x}{e^x-1}`` for exponentially\nfitted upwinding.\n\nThe name `fbernoulli` has been chosen to avoid confusion\nwith Bernoulli from JuliaStats/Distributions.jl\n\nReturns a real number containing the result.\n\"\"\"\nfunction fbernoulli(x)\n    if x<-bernoulli_large_threshold\n        -x\n    elseif x>bernoulli_large_threshold\n\tzero(x)\n    else\n        expx=exp(x)\n        expxm1=expx-1.0\n        if abs(expxm1)>bernoulli_small_threshold\n            x/expxm1\n        else\n            bernoulli_horner(x)\n        end\n    end\nend\n\n##############################################################\n\n\n\"\"\" \n$(SIGNATURES)\n\nBernoulli function ``B(x)=\\\\frac{x}{e^x-1}`` for exponentially\nfitted upwind, joint evaluation for positive and negative\nargument\n\nUsually, we need ``B(x), B(-x)`` togehter, \nand it is cheaper to calculate them together.\n\nReturns two real numbers containing the result for argument\n`x` and argument `-x`.\n\nThe error in comparison with the evaluation of the original expression\nwith BigFloat is less than 1.0e-15\n\"\"\"\nfunction fbernoulli_pm(x)\n    if x< -bernoulli_large_threshold\n        return -x, zero(x)\n    elseif x>bernoulli_large_threshold\n\treturn zero(x),x\n    else\n        expx=exp(x)\n        expxm1=expx-1.0\n        if abs(expxm1)>bernoulli_small_threshold\n            bp=x/expxm1\n            bm=x/(1.0-1.0/expx)\n            return bp,bm\n        else\n            y=bernoulli_horner(x)\n            return y,x+y\n        end\n    end\nend\n", "meta": {"hexsha": "8a9e799e23d4539520179bb5410e4c6259fadcb4", "size": 2057, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vfvm_functions.jl", "max_stars_repo_name": "PatricioFarrell/VoronoiFVM.jl", "max_stars_repo_head_hexsha": "690943ff455c91f16d114ad52cc83f2e8fa84e58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/vfvm_functions.jl", "max_issues_repo_name": "PatricioFarrell/VoronoiFVM.jl", "max_issues_repo_head_hexsha": "690943ff455c91f16d114ad52cc83f2e8fa84e58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vfvm_functions.jl", "max_forks_repo_name": "PatricioFarrell/VoronoiFVM.jl", "max_forks_repo_head_hexsha": "690943ff455c91f16d114ad52cc83f2e8fa84e58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3586956522, "max_line_length": 70, "alphanum_fraction": 0.5935828877, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.771315363352612}}
{"text": "# --- User Parameters\n\n# Number of samples to use to estimate probability distributions\nsample_size = 10000;\n\n# --- Imports\n\nimport Distributions\nusing Distributions: MvNormal, ContinuousUnivariateDistribution, cdf\nusing HypothesisTests\nusing LinearAlgebra\nusing Plots\nusing Random\nusing StatsBase: Histogram, fit\n\n# --- Internal Parameters\n\n# ------ Uniformity test parameters\n\n# p-value cutoff\np_value_cutoff = 0.1;\n\n# maximum number of attempts to generate a sample of vectors\nmax_attempts = 10;\n\n# --- Probability distribution for θ (angle between vector and x_1-axis)\n\nstruct ThetaDistribution <: ContinuousUnivariateDistribution\n    n::Integer\nend\n\nfunction Distributions.cdf(dist::ThetaDistribution, x::Real)\n    # Preparations\n    k = dist.n-2\n\n    # Compute pdf\n    value = 0\n    if k % 2 == 0\n        # Precompute re-used coefficients\n        sgn = (-1)^(k÷2)\n        k_choose_k_over_2 = binomial(big(k), k÷2)\n        \n        for j = 0:(k÷2 - 1)\n            value += (-1)^j * binomial(big(k), j) * sin((k - 2*j) * x) / (k - 2*j)\n        end\n        value *= 2\n        value += sgn * k_choose_k_over_2 * x  # contribution from i = k÷2 term\n        value *= sgn / π / k_choose_k_over_2\n\n    else\n        norm_ = 0\n        for j = 0:(k-1)÷2\n            coef = (-1)^j * binomial(big(k), j) / (k - 2*j)\n            value += coef * (1 - cos((k - 2*j) * x))\n            norm_ += coef\n        end\n        value /= 2 * norm_\n\n    end\n\n    return value\nend\n\n# --- Tests\n\n# 2D: cdf(x) = x / π\ntheta_dist_2d = ThetaDistribution(2)\nfor x = range(0, π; length=10)\n    computed_cdf = cdf(theta_dist_2d, x)\n    expected_cdf = x / π\n    @assert (computed_cdf ≈ expected_cdf) \"Expected: $(expected_cdf). Got: $(computed_cdf)\"\nend\n\n# 3D: cdf(x) = 0.5 * (1 - cos(x))\ntheta_dist_3d = ThetaDistribution(3)\nfor x = range(0, π; length=10)\n    computed_cdf = cdf(theta_dist_3d, x)\n    expected_cdf = 0.5 * (1 - cos(x))\n    @assert (computed_cdf ≈ expected_cdf) \"Expected: $(expected_cdf). Got: $(computed_cdf)\"\nend\n\nfunction generate_blades(n::Integer, s::Integer, sample_size::Integer)::Tuple\n    \"\"\"\n    Generate a sample of s-dimensional blades in an n-dimensional space where each blade\n    is defined by unit vectors drawn from a uniform distribution over the surface of an\n    unit n-sphere.\n\n    Parameters\n    ----------\n    n: dimension of space\n\n    s: grade of blades\n\n    sample_size: number of blades to include in sample\n    \n    Return values\n    -------------\n    vectors: sample of vectors\n    \n    uniformity_stats: results of tests for uniformity of sample on unit n-sphere\n    \"\"\"\n    # --- Set up uniformity tests\n\n    theta_dist = ThetaDistribution(n)\n    AD_p_value = 0\n    KS_p_value = 0\n\n    # --- Generate sample of vectors\n\n    num_attempts = 0\n    vectors = undef\n    while ( ((AD_p_value < p_value_cutoff) || (KS_p_value < p_value_cutoff)) &&\n            (num_attempts < max_attempts) )\n\n        # Generate new sample\n        dist = MvNormal(zeros(n), ones(n))\n        num_vectors = sample_size * s\n        vectors = rand(dist, num_vectors)\n        for i = 1:num_vectors\n            vectors[:, i] /= norm(vectors[:, i])\n        end\n\n        # Perform test for uniformity on unit n-sphere\n        thetas = map(i -> atan(norm(vectors[:, i][2:end]), vectors[:, i][1]), 1:num_vectors)\n\n        # Anderson-Darling Test\n        AD_p_value = pvalue(OneSampleADTest(thetas, theta_dist))\n\n        # Kolmogorov-Smirnov Test\n        KS_p_value = pvalue(ExactOneSampleKSTest(thetas, theta_dist))\n\n        # Update attempt count\n        num_attempts += 1\n    end\n\n    # --- Group vectors into blades\n\n    blades = []\n    for i = 1:sample_size\n        push!(blades, vectors[:, (i-1)*s+1:i*s])\n    end\n\n    # --- Save uniformity test results\n\n    uniformity_stats = (\n        success=(num_attempts < max_attempts),\n        num_attempts=num_attempts,\n        AD_p_value=AD_p_value,\n        KS_p_value=KS_p_value,\n    )\n    \n    return blades, uniformity_stats\nend\n\n# --- Generate blades\n\n# Parameters\nn_2d = 2;  # dimension of space\ns = 2;  # grade of blades\n\n# Generate sample of blades\nblades, uniformity_stats = generate_blades(n_2d, s, sample_size)\nif !uniformity_stats[:success]\n    println(\"FAILED to generated sample with sufficient uniformity on unit circle.\")\n    display(uniformity_stats)\nend\n\n# --- Compute blade volumes\n\nsigned_volumes = Vector{Float64}()\nfor i = 1:sample_size\n    F = qr(blades[i])\n    signed_volume = det(F.R)\n    push!(signed_volumes, signed_volume)\nend\n\nvolumes = abs.(signed_volumes);\n\n# --- Compute distributions\n\n# Histogram parameters\nnum_hist_bins = 50\n\n# Plot histograms\nhist_bins_signed = range(-1, 1; length=num_hist_bins)\nplt_signed = plot(histogram(signed_volumes; bins=hist_bins_signed, normalize=true))\n\nhist_bins = range(0, 1; length=num_hist_bins)\nplt = plot(histogram(volumes; bins=hist_bins, normalize=true))\n\ndisplay(plt_signed)\ndisplay(plt)\n\n# Compute empirical volume distributions\nhist_signed = fit(Histogram, signed_volumes; nbins=num_hist_bins)\nedf_signed = normalize(hist_signed; mode=:pdf);\n\nhist = fit(Histogram, volumes; nbins=num_hist_bins)\nedf = normalize(hist; mode=:pdf);\n\n# --- Generate blades\n\n# Parameters\nn_3d = 3;  # dimension of space\ns = 2;  # grade of blades\n\n# Generate sample of blades\nblades, uniformity_stats = generate_blades(n_3d, s, sample_size)\nif !uniformity_stats[:success]\n    println(\"FAILED to generated sample with sufficient uniformity on unit sphere.\")\n    display(uniformity_stats)\nend\n\n# --- Compute blade volumes\n\nsigned_volumes = Vector{Float64}()\nfor i = 1:sample_size\n    F = qr(blades[i])\n    signed_volume = det(F.R)\n    push!(signed_volumes, signed_volume)\nend\n\nvolumes = abs.(signed_volumes);\n\n# --- Compute distributions\n\n# Histogram parameters\nnum_hist_bins = 50\n\n# Plot histograms\nhist_bins_signed = range(-1, 1; length=num_hist_bins)\nplt_signed = plot(histogram(signed_volumes; bins=hist_bins_signed, normalize=true))\n\nhist_bins = range(0, 1; length=num_hist_bins)\nplt = plot(histogram(volumes; bins=hist_bins, normalize=true))\n\ndisplay(plt_signed)\ndisplay(plt)\n\n# Compute empirical volume distributions\nhist_signed = fit(Histogram, signed_volumes; nbins=num_hist_bins)\nedf_signed = normalize(hist_signed; mode=:pdf);\n\nhist = fit(Histogram, volumes; nbins=num_hist_bins)\nedf = normalize(hist; mode=:pdf);\n\n# --- Generate blades\n\n# Parameters\nn = 100;  # dimension of space\ns = 10;  # grade of blades\n\n# Generate sample of vectors\nblades, uniformity_stats = generate_blades(n, s, sample_size)\nif !uniformity_stats[:success]\n    println(\"FAILED to generated sample with sufficient uniformity on unit $(n)-sphere.\")\n    display(uniformity_stats)\nend\n\n# --- Compute blade volumes\n\nsigned_volumes = Vector{Float64}()\nfor i = 1:sample_size\n    F = qr(blades[i])\n    signed_volume = det(F.R)\n    push!(signed_volumes, signed_volume)\nend\n\nvolumes = abs.(signed_volumes);\n\n# --- Compute distributions\n\n# Histogram parameters\nnum_hist_bins = 50\n\n# Plot histograms\nhist_bins_signed = range(-1, 1; length=num_hist_bins)\nplt_signed = plot(histogram(signed_volumes; bins=hist_bins_signed, normalize=true))\n\nhist_bins = range(0, 1; length=num_hist_bins)\nplt = plot(histogram(volumes; bins=hist_bins, normalize=true))\ndisplay(plt_signed)\ndisplay(plt)\n\n# Compute empirical volume distributions\nhist_signed = fit(Histogram, signed_volumes; nbins=num_hist_bins)\nedf_signed = normalize(hist_signed; mode=:pdf);\n\nhist = fit(Histogram, volumes; nbins=num_hist_bins)\nedf = normalize(hist; mode=:pdf);\n\n# --- Generate blades\n\n# Parameters\nn = 500;  # dimension of space\ns = 10;  # grade of blades\n\n# Generate sample of vectors\nblades, uniformity_stats = generate_blades(n, s, sample_size)\nif !uniformity_stats[:success]\n    println(\"FAILED to generated sample with sufficient uniformity on unit $(n)-sphere.\")\n    display(uniformity_stats)\nend\n\n# --- Compute blade volumes\n\nsigned_volumes = Vector{Float64}()\nfor i = 1:sample_size\n    F = qr(blades[i])\n    signed_volume = det(F.R)\n    push!(signed_volumes, signed_volume)\nend\n\nvolumes = abs.(signed_volumes);\n\n# --- Compute distributions\n\n# Histogram parameters\nnum_hist_bins = 50\n\n# Plot histograms\nhist_bins_signed = range(-1, 1; length=num_hist_bins)\nplt_signed = plot(histogram(signed_volumes; bins=hist_bins_signed, normalize=true))\n\nhist_bins = range(0, 1; length=num_hist_bins)\nplt = plot(histogram(volumes; bins=hist_bins, normalize=true))\ndisplay(plt_signed)\ndisplay(plt)\n\n# Compute empirical volume distributions\nhist_signed = fit(Histogram, signed_volumes; nbins=num_hist_bins)\nedf_signed = normalize(hist_signed; mode=:pdf);\n\nhist = fit(Histogram, volumes; nbins=num_hist_bins)\nedf = normalize(hist; mode=:pdf);\n", "meta": {"hexsha": "cb48a84df00b8e47f951ea6a53575aa237130cda", "size": 8651, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/2022-02-18-Distributions_of_Blade_Volumes.jl", "max_stars_repo_name": "ktchu/RESEARCH-math-exploration", "max_stars_repo_head_hexsha": "38a39ade4ec9d7047e82808b30172883845634bc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/2022-02-18-Distributions_of_Blade_Volumes.jl", "max_issues_repo_name": "ktchu/RESEARCH-math-exploration", "max_issues_repo_head_hexsha": "38a39ade4ec9d7047e82808b30172883845634bc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/2022-02-18-Distributions_of_Blade_Volumes.jl", "max_forks_repo_name": "ktchu/RESEARCH-math-exploration", "max_forks_repo_head_hexsha": "38a39ade4ec9d7047e82808b30172883845634bc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7470238095, "max_line_length": 92, "alphanum_fraction": 0.6909027858, "num_tokens": 2349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7713153613089437}}
{"text": "function numcollatz(n)\n\tnumiters = 0\n\twhile n > 1\n\t\t#print(\"$n \")\n\t\tif n % 2 == 0\n\t\t\tn = div(n,2)\n\t\telse\n\t\t\tn = 3n + 1\n\t\tend\n\t\t#println(\"$n\")\n\t\tnumiters += 1\n\tend\n\treturn numiters\nend\n\nfunction main()\n\tN = 1_000_000\n\n\tbests = 0\n\tbestl = 0\n\ti = 0\n\twhile i <= N\n\t\ti += 1\n\t\tl = numcollatz(i)\n\t\tif l > bestl\n\t\t\tprintln(\"$i $l\")\n\t\t\tbestl = l\n\t\t\tbests = i\n\t\tend\n\tend\n\tprintln(\"start=$bests length=$bestl\")\nend\n\nmain()\n", "meta": {"hexsha": "4c67c8664a7035c01527bc78600e6dba2bccef05", "size": 412, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problem14.jl", "max_stars_repo_name": "cmey/euler", "max_stars_repo_head_hexsha": "b61faa9f421992e1c859f354e67125e681156584", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problem14.jl", "max_issues_repo_name": "cmey/euler", "max_issues_repo_head_hexsha": "b61faa9f421992e1c859f354e67125e681156584", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem14.jl", "max_forks_repo_name": "cmey/euler", "max_forks_repo_head_hexsha": "b61faa9f421992e1c859f354e67125e681156584", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.7714285714, "max_line_length": 38, "alphanum_fraction": 0.5509708738, "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.8824278772763471, "lm_q1q2_score": 0.7713101134129814}}
{"text": "#Wigner semicircle distribution\n\nimportall Distributions\nexport Semicircle\n\nimmutable Semicircle <: ContinuousUnivariateDistribution\n    mean::Float64\n    radius::Float64\n    Semicircle(mu, r) = r > 0 ? new(float64(mu), float64(r)) : \n        error(\"radius r must be positive\") #Constructor\nend\n\n#Standardized distribution - mean 0, variance 1\nSemicircle(mu) = Semicircle(mu, 2.0)\nSemicircle() = Semicircle(0.0, 2.0)\n\n# Distribution function methods\n###############################\n\n# cumulative distribution function\nfunction cdf(X::Semicircle, x::Real)\n    r, a = X.mean, X.radius\n    insupport(x) ? 0.5 + (x-a)/(pi*r^2) * sqrt(r^2 - (x-a)^2) + 1/pi * asin((x-a)/r) : (x>a ? 1.0 : 0.0)\nend\n\n# probability density function\nfunction pdf(X::Semicircle, x::Real)\n    r, a = X.mean, X.radius\n    insupport(x) ? 2/(pi*r^2) * sqrt(r^2 - (x-a)^2) : 0.0\nend\n\n# predicate is x in the support of the distribution?\ninsupport(X::Semicircle, x::Real)=abs(x)<=X.radius\n\n\n#Entropy methods\n################\n\n# entropy of distribution in nats\nentropy(X::Semicircle)=log(pi*X.radius) - 0.5\n\n#Measures of central tendency methods\n#####################################\n\n# mean of distribution\nmean(X::Semicircle)=X.mean\n\n# median of distribution\nmedian(X::Semicircle)=X.mean\n\n# mode(s) of distribution as vector\nmodes(X::Semicircle)=[X.mean]\n\n# kurtosis of the distribution\nkurtosis(X::Semicircle)=2\n\n# skewness of the distribution\nskewness(X::Semicircle)=0\n\n# standard deviation of distribution\nstd(X::Semicircle)=X.radius/2\n\n# variance of distribution\nvar(X::Semicircle)=std(X)^2\n\n# moment of distribution\nif _HAVE_GSL\n  function moment(X::Semicircle, order::Integer)\n    a, r = X.mean, X.radius\n    if X.mean != 0 \n      a^n*hypergeom([(1-n)/2, -n/2], 2, (r/a)^2)\n    else\n      order%2 ? (0.5*r)^(2n) * catalan(div(order,2)) : 0\n    end\n  end\nelse\n  function moment(X::Semicircle, order::Integer)\n    error(\"The moment of a semicircle distribution requires the GSL module to be loaded.\")\n  end\nend\n\n# cumulant of distribution\nfunction cumulant(X::Semicircle, order::Integer)\n  if X.mean != 0 error(\"not supported\") end\n  if order%2\n    order==0 ? 1 : (0.5*r)^(2n) * lassalle(order/2) \n  else\n    0\n  end\nend\n\n# free cumulant of distribution\nfunction freecumulant(X::Semicircle, order::Integer)\n  if order == 0\n    return 1\n  elseif order == 1\n    return mean(X)\n  elseif order == 2\n    return var(X)\n  else\n    return 0\n  end\nend\n\n\n#Generating function methods\n############################\n\n# characteristic function \nfunction cf(X::Semicircle, t::Real)\n  r = t * X.mean\n  2 * besselj(1, r)/r\nend\n\n# moment generating function\nfunction mgf(X::Semicircle, t::Real)\n  r = t * X.mean\n  2 * besseli(1, r)/r\nend\n\n#Sampling methods\n#################\n\n# random sampler\n# Use relationship with beta distribution\nfunction rand(X::Semicircle)\n  Y = rand(Beta(1.5, 1.5))\n  X.mean + 2 * X.radius * Y - X.radius\nend\n\n\n", "meta": {"hexsha": "6cdb5d0ffbbfa17dddf63ad8fc4ebb430e93ceef", "size": 2890, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/densities/Semicircle.jl", "max_stars_repo_name": "mschauer/RandomMatrices.jl", "max_stars_repo_head_hexsha": "c9138d4acfcd27c34981401874e1abbe4ec93b73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/densities/Semicircle.jl", "max_issues_repo_name": "mschauer/RandomMatrices.jl", "max_issues_repo_head_hexsha": "c9138d4acfcd27c34981401874e1abbe4ec93b73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/densities/Semicircle.jl", "max_forks_repo_name": "mschauer/RandomMatrices.jl", "max_forks_repo_head_hexsha": "c9138d4acfcd27c34981401874e1abbe4ec93b73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8939393939, "max_line_length": 104, "alphanum_fraction": 0.6474048443, "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.7712929701618235}}
{"text": "# ---\n# title: 264. Ugly Number II\n# id: problem264\n# author: Indigo\n# date: 2021-06-05\n# difficulty: Medium\n# categories: Math, Dynamic Programming, Heap\n# link: <https://leetcode.com/problems/ugly-number-ii/description/>\n# hidden: true\n# ---\n# \n# Write a program to find the `n`-th ugly number.\n# \n# Ugly numbers are **positive numbers** whose prime factors only include `2, 3,\n# 5`.\n# \n# **Example:**\n# \n#     \n#     \n#     Input: n = 10\n#     Output: 12\n#     Explanation:1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.\n# \n# **Note:**  \n# \n#   1. `1` is typically treated as an ugly number.\n#   2. `n` **does not exceed 1690**.\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction nth_ugly_number(n::Int)\n    dp = Vector{Int}(undef, n)\n    p2 = p3 = p5 = dp[1] = 1\n    for i in 2:n\n        nums = dp[p2] * 2, dp[p3] * 3, dp[p5] * 5\n        dp[i] = minimum(nums)\n        p2 += dp[i] == nums[1]\n        p3 += dp[i] == nums[2]\n        p5 += dp[i] == nums[3]        \n    end\n    return dp[n]\nend\n## @lc code=end\n", "meta": {"hexsha": "81fcdec0b7ed887a91950c22fc11099bc784f5c2", "size": 1037, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/264.ugly-number-ii.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/264.ugly-number-ii.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/264.ugly-number-ii.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 22.0638297872, "max_line_length": 94, "alphanum_fraction": 0.5554484089, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.771292966964806}}
{"text": "\n# safe log(x) function, log 0 = 0\nsafelog(x) = x > zero(x) ? log2(x) : zero(x)\nsafediv(x, y) = y == zero(y) ? zero(y) : x / y\n# general functions for entropy\n\n\n\"\"\"\n    make_joint_distribution(N::NT) where {NT<:AbstractEcologicalNetwork}\n\nReturns a double stochastic matrix from the adjacency or incidence matrix.\nRaises an error if the matrix contains negative values. Output in bits.\n\"\"\"\nfunction make_joint_distribution(N::NT) where {NT<:AbstractEcologicalNetwork}\n    !(typeof(N) <: QuantitativeNetwork) || any(N.A .≥ 0) || throw(DomainError(\"Information only for nonnegative interaction values\"))\n    return N.A / sum(N.A)\nend\n\n\"\"\"\n   entropy(P::AbstractArray)\n\nComputes the joint entropy of a double stochastic matrix. Does not perform any\nchecks whether the matrix is normalized. Output in bits.\n\"\"\"\nfunction entropy(P::AbstractArray)\n    return - sum(P .* safelog.(P))\nend\n\n\"\"\"\n   entropy(P::AbstractArray, dims::I)\n\nComputes the marginal entropy of a double stochastic matrix. `dims` indicates\nwhether to compute the entropy for the rows (`dims`=1) or columns (`dims`=2).\nDoes not perform any checks whether the matrix is normalized. Output in bits.\n\"\"\"\nfunction entropy(P::AbstractArray, dims::I) where I <: Int\n    return entropy(sum(P', dims=dims))\nend\n\n\"\"\"\n   entropy(N::AbstractEcologicalNetwork)\n\nComputes the joint entropy of an ecological network. Output in bits.\n\"\"\"\nfunction entropy(N::NT) where {NT<:AbstractEcologicalNetwork}\n    P = make_joint_distribution(N)\n    return entropy(P)\nend\n\n\"\"\"\n   entropy(N::AbstractEcologicalNetwork, dims::I)\n\nComputes the marginal entropy of an ecological network. `dims` indicates\nwhether to compute the entropy for the rows (`dims`=1) or columns (`dims`=2).\nOutput in bits.\n\"\"\"\nfunction entropy(N::NT, dims::I) where {NT<:AbstractEcologicalNetwork, I <: Int}\n    P = make_joint_distribution(N)\n    return entropy(P, dims)\nend\n\n\"\"\"\n   conditional_entropy(P::AbstractArray, given::I)\n\nComputes the conditional entropy of double stochastic matrix. If `given = 1`,\nit is the entropy of the columns, and visa versa when `given = 2`. Output in bits.\n\"\"\"\nfunction conditional_entropy(P::AbstractArray, given::I) where I <: Int\n    dims = (given % 2) + 1\n    return - sum(P .* safelog.(safediv.(P, sum(P, dims=dims))))\nend\n\n\"\"\"\n   conditional_entropy(N::AbstractEcologicalNetwork, given::I)\n\nComputes the conditional entropy of an ecological network. If `given = 1`,\nit is the entropy of the columns, and visa versa when `given = 2`.\n\"\"\"\nfunction conditional_entropy(N::NT, given::I) where {NT<:AbstractEcologicalNetwork, I <: Int}\n    P = make_joint_distribution(N)\n    return conditional_entropy(P, given)\nend\n\n\"\"\"\n    mutual_information(P::AbstractArray)\n\nComputes the mutual information of a double stochastic matrix. Output in bits.\n\"\"\"\nfunction mutual_information(P::AbstractArray)\n    I = entropy(P, 1) - conditional_entropy(P, 2)\n    return max(I, zero(I))  # might give small negative value\nend\n\n\"\"\"\n    mutual_information(P::AbstractArray)\n\nComputes the mutual information of an ecological network. Output in bits.\n\"\"\"\nfunction mutual_information(N::NT) where {NT<:AbstractEcologicalNetwork}\n    P = make_joint_distribution(N)\n    return mutual_information(P)\nend\n\n\"\"\"\n    variation_information(P::AbstractArray)\n\nComputes the variation of information of a double stochastic matrix. Output in\nbits.\n\"\"\"\nfunction variation_information(P::AbstractArray)\n    return conditional_entropy(P, 1) + conditional_entropy(P, 2)\nend\n\n\"\"\"\n    variation_information(N::AbstractEcologicalNetwork)\n\nComputes the variation of information of an ecological network. Output in\nbits.\n\"\"\"\nfunction variation_information(N::NT) where {NT <: AbstractEcologicalNetwork}\n    P = make_joint_distribution(N)\n    return variation_information(P)\nend\n\n\"\"\"\n    diff_entropy_uniform(P::AbstractArray)\n\nComputes the difference in entropy of the marginals compared to the entropy of\nan uniform distribution. The parameter `dims` indicates which marginals are used,\nwith both if no value is provided. Output in bits.\n\"\"\"\nfunction diff_entropy_uniform(P::AbstractArray)\n    D = log2(length(P)) - entropy(P, 1) - entropy(P, 2)\n    return max(zero(D), D)\nend\n\n\"\"\"\n    diff_entropy_uniform(P::AbstractArray, dims::I)\n\nComputes the difference in entropy of the marginals compared to the entropy of\nan uniform distribution. The parameter `dims` indicates which marginals are used,\nwith both if no value is provided. Output in bits.\n\"\"\"\nfunction diff_entropy_uniform(P::AbstractArray, dims::I) where {I <: Int}\n    D = log2(size(P, dims)) - entropy(P, dims)\n    return max(zero(D), D)\nend\n\n\"\"\"\n    diff_entropy_uniform(N::AbstractEcologicalNetwork, dims::I=nothing)\n\nComputes the difference in entropy of the marginals compared to the entropy of\nan uniform distribution. The parameter `dims` indicates which marginals are used,\nwith both if no value is provided. Output in bits.\n\"\"\"\nfunction diff_entropy_uniform(N::NT, dims=nothing) where {NT <: AbstractEcologicalNetwork}\n    if dims == nothing\n        P = make_joint_distribution(N)\n        return diff_entropy_uniform(P)\n    else  # compute marginals\n        typeof(dims) <: Int || throw(ArgumentError(\"dims should be an integer (1 or 2)\"))\n        P = make_joint_distribution(N)\n        return diff_entropy_uniform(P, dims)\n    end\nend\n\n\"\"\"\n    information_decomposition(N::AbstractEcologicalNetwork; norm::Bool=false, dims::I=nothing)\n\nPerforms an information theory decomposition of a given ecological network, i.e.\nthe information content in the normalized adjacency matrix is split in:\n\n- `:D` : difference in entropy of marginals compared to an uniform distribition\n- `:I` : mutual information\n- `:V` : variation of information / conditional entropy\n\nIf `norm=true`, the components are normalized such that their sum is equal to 1.\nOne can optinally give the dimision, indicating whether to compute the indices\nfor the rows (`dims=1`), columns (`dims=2`) or the whole matrix (default).\n\nResult is returned in a Dict. Outputs in bits.\n\"\"\"\nfunction information_decomposition(N::NT; norm::Bool=false, dims::I=nothing) where {NT <: AbstractEcologicalNetwork, I <: Union{Int, Nothing}}\n    decomposition = Dict{Symbol, Float64}()\n    P = make_joint_distribution(N)\n    if dims == nothing\n        # difference marginal entropy\n        decomposition[:D] = diff_entropy_uniform(P)\n        # mutual information\n        decomposition[:I] = 2mutual_information(P)\n        # variance of information\n        decomposition[:V] = variation_information(P)\n    else\n        decomposition[:D] = diff_entropy_uniform(P, dims)\n        decomposition[:I] = mutual_information(P)\n        decomposition[:V] = conditional_entropy(P, (dims % 2) + 1)\n    end\n    if norm\n        potential_information = sum(values(decomposition))\n        for key in keys(decomposition)\n            decomposition[key] /= potential_information\n        end\n    end\n    return decomposition\nend\n\n\"\"\"\n    convert2effective(indice::Real)\n\nConvert an information theory indices in an effective number (i.e. number of\ncorresponding interactions).\n\"\"\"\nfunction convert2effective(indice::R) where R <: Real\n    return 2.0^indice\nend\n\n\"\"\"\n    potential_information(N::NT)\n\nComputes the maximal potential information in a network, corresponding to\nevery species interacting with every other species. Compute result for the\nmarginals using the optional parameter `dims`. Output in bits.\n\"\"\"\nfunction potential_information(N::NT) where NT <: AbstractEcologicalNetwork\n    m, n = size(N)\n    return log2(m) + log2(n)\nend\n\n\"\"\"\n    potential_information(N::NT, dims::I)\n\nComputes the maximal potential information in a network, corresponding to\nevery species interacting with every other species. Compute result for the\nmarginals using the optional parameter `dims`. Output in bits.\n\"\"\"\nfunction potential_information(N::NT, dims::I) where {NT <: AbstractEcologicalNetwork, I <: Int}\n    return log2(size(N)[dims])\nend\n", "meta": {"hexsha": "f3956c04d91ff1b882186903d2986be5b03a20cc", "size": 7934, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/information/entropy.jl", "max_stars_repo_name": "MichielStock/EcologicalNetworks.jl", "max_stars_repo_head_hexsha": "ac69a8975011593adeed2b65548c6b2012966e83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/information/entropy.jl", "max_issues_repo_name": "MichielStock/EcologicalNetworks.jl", "max_issues_repo_head_hexsha": "ac69a8975011593adeed2b65548c6b2012966e83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/information/entropy.jl", "max_forks_repo_name": "MichielStock/EcologicalNetworks.jl", "max_forks_repo_head_hexsha": "ac69a8975011593adeed2b65548c6b2012966e83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1966527197, "max_line_length": 142, "alphanum_fraction": 0.7291404084, "num_tokens": 1866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7712929606991799}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.21\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ feadb782-9905-4e05-a0c9-e1b1b54fb3b0\nbegin\n\tusing Distributions\n\tn_samples = 100\n\tp_1 = 0.2\n\tx_data = rand(Binomial(1, p_1), n_samples)\nend\n\n# ╔═╡ c54da392-7d0b-11eb-278e-b3a7ec910fc7\nbegin\n\tusing Gaston; set(showable=\"svg\")\n\tp0 = range(0, 1;length=100)\n\tp1 = 1 .- p0\n\tplot(p0, p1, Axes(xrange = (-1, 1), yrange = (-1, 1), zeroaxis=\"\", xtics=\"axis\", ytics=\"axis\"))\n\tplot!([0.1,1], [1,0.2], supp=[\"p₀\",\"p₁\"], w=\"labels\")\nend\n\n# ╔═╡ e42579e4-5e98-4cca-a425-a3b356dd03ba\nbegin\n\tusing LinearAlgebra\n\tp = [0.8, 0.2]\n\tnorm(p, 1)\nend\n\n# ╔═╡ 6de3cf91-1739-49ac-aac5-0dcd72871461\nbegin\n\tusing Yao\n\tq = zero_state(1)\nend\n\n# ╔═╡ 0ef307d4-84d3-11eb-10e7-07cc58485fba\ninclude(\"./essentials.jl\"); import .essentials\n\n# ╔═╡ 4f69ca95-0111-40d3-b74b-34e999f4f185\nmd\"\"\"\nProbability theory is a cornerstone for machine learning. We can think of quantum states as probability distributions with certain properties that make them different from our classical notion of probabilities. Contrasting these properties is an easy and straightforward introduction to the most basic concepts we need in quantum computing.\n\nApart from probability theory, linear algebra is also critical for many learning protocols. As we will see, geometry and probabilities are intrinsically linked in quantum computing, but geometric notions are also familiar in dealing with classical probability distributions. This notebook first talks about classical probabilities and stochastic vectors, and introduces quantum states as a natural generalization.\n\nThroughout this course, we will assume finite probability distributions and finite dimensional spaces. This significantly simplifies notation and most quantum computers operate over finite dimensional spaces, so we do not lose much in generality.\n\n\n# Classical probability distributions\n\nLet us toss a biased coin. Without getting too technical, we can associate a random variable $X$ with the output: it takes the value 0 for heads and the value 1 for tails. We get heads with probability $P(X=0) = p_0$ and tails with $P(X=1) = p_1$ for each toss of the coin. In classical, Kolmogorovian probability theory, $p_i\\geq 0$ for all $i$, and the probabilities sum to one: $\\sum_i p_i = 1$. Let's sample this distribution\n\"\"\"\n\n# ╔═╡ c3898a67-d4b2-46a0-b5cc-69420762cd62\nmd\"\"\"\nWe naturally expect that the empirically observed frequencies also sum to one:\n\"\"\"\n\n# ╔═╡ 02a05ce8-35ad-4192-a9d6-e7d3cc29e6ba\nbegin\n\tfrequency_of_zeros, frequency_of_ones = 0, 0\n\tfor x in x_data\n\t    if x==1\n\t        frequency_of_ones += 1/n_samples\n\t    else\n    \t    frequency_of_zeros += 1/n_samples\n\t\tend\n\tend\n\tfrequency_of_ones+frequency_of_zeros\nend\n\n# ╔═╡ a776d9b8-9adb-4985-9830-165acb8d805b\nmd\"\"\"\nSince $p_0$ and $p_1$ must be non-negative, all possible probability distributions are restricted to the positive orthant. The normalization constraint puts every possible distribution on a straight line. This plot describes all possible probability distributions by biased and unbiased coins.\n\"\"\"\n\n# ╔═╡ 8c7034ce-8286-4d06-9fe1-17581695219c\nmd\"\"\"\nWe may also arrange the probabilities in a vector $\\vec{p} = \\begin{bmatrix} p_0 \\\\ p_1 \\end{bmatrix}$. Here, for notational convenience, we put an arrow above the variable representing the vector, to distinguish it from scalars. You will see that quantum states also have a standard notation that provides convenience, but goes much further in usefulness than the humble arrow here.\n\nA vector representing a probability distribution is called a *stochastic vector*. The normalization constraint essentially says that the norm of the vector is restricted to one in the $l_1$ norm. In other words, $||\\vec{p}||_1 = \\sum_i |p_i| = 1$. This would be the unit circle in the $l_1$ norm, but since $p_i\\geq 0$, we are restricted to a quarter of the unit circle, just as we plotted above. We can easily verify this with numpy's norm function:\n\"\"\"\n\n# ╔═╡ 13533ef2-3be4-4aea-981d-0bc77ec5db57\nmd\"\"\"\nWe know that the probability of heads is just the first element in the $\\vec{p}$, but since it is a vector, we could use linear algebra to extract it. Geometrically, it means that we project the vector to the first axis. This projection is described by the matrix $\\begin{bmatrix} 1 & 0\\\\0 & 0\\end{bmatrix}$. The length in the $l_1$ norm gives the sought probability:\n\"\"\"\n\n# ╔═╡ 0d931337-ad9b-45d1-85fa-2b89f052099d\nbegin\n\tΠ₀ = [1 0;0 0]\n\tnorm(Π₀ * p)\nend\n\n# ╔═╡ 29c91dc7-cfda-42d4-bd0f-f479c611339e\nmd\"\"\"\nWe can repeat the process to get the probability of tails:\n\"\"\"\n\n# ╔═╡ c1ec3e28-93fc-42d5-8ef7-454cdb7f7c33\nbegin\n\tΠ₁ = [0 0; 0 1]\n\tnorm(Π₁ * p)\nend\n\n# ╔═╡ de543889-d698-4926-a2a2-9aea48578fd8\nmd\"\"\"\nThe two projections play an equivalent role to the values 0 and 1 when we defined the probability distribution. In fact, we could define a new random variable called $\\Pi$ that can take the projections $\\Pi_0$ and $\\Pi_1$ as values and we would end up with an identical probability distribution. This may sound convoluted and unnatural, but the measurement in quantum mechanics is essentially a random variable that takes operator values, such as projections.\n\"\"\"\n\n# ╔═╡ caa23a10-d43e-4a8c-b987-af69b55ed16e\nmd\"\"\"\nWhat happens when we want to transform a probability distribution to another one? For instance, to change the bias of a coin, or to describe the transition of a Markov chain. Since the probability distribution is also a stochastic vector, we can apply a matrix on the vector, where the matrix has to fulfill certain conditions. A left *stochastic matrix* will map stochastic vectors to stochastic vectors when multiplied from the left: its columns add up to one. In other words, it maps probability distributions to probability distributions. For example, starting with a unbiased coin, the map $M$ will transform the distribution to a biased coin:\n\"\"\"\n\n# ╔═╡ cac5a2c0-6913-4997-b29d-154250be44dd\nlet\n\tp = [0.5, 0.5]\n\tM = [0.7 0.6; 0.3 0.4]\n\tnorm(M * p)\nend\n\n# ╔═╡ 1dee601c-2f9f-46d8-be37-99d31e589ebe\nmd\"\"\"\nOne last concept that will come handy is entropy. A probability distribution's entropy is defined as $H(p) = - \\sum_i p_i \\log_2 p_i$. Let us plot it over all possible probability distributions of coin tosses:\n\"\"\"\n\n# ╔═╡ 15416de9-5fe1-4cb7-a5bb-b4227fd9ad4a\nlet\n\tϵ = 10^-10\n\tp_0 = range(ϵ, 1-ϵ;length = 100)\n\tp_1 = 1 .- p_0\n\tH = -1 .* (p_0 .* log.(2,p_0) .+ p_1 .* log.(2, p_1))\n\tplot(p_0, H, Axes(ylabel=\"'H'\", xlabel=\"'p₀'\", xrange = (0,1), yrange = (0,1)))\n\tplot!([0.5, 0.5], [0,1], ls = :dash)\nend\n\n# ╔═╡ d803bf96-6cd4-4874-a3f7-ed7c0bf16267\nmd\"\"\"\nHere we can see that the entropy is maximal for the unbiased coin. This is true in general: the entropy peaks for the uniform distribution. In a sense, this is the most unpredictable distribution: if we get heads with probability 0.2, betting tails is a great idea. On the other hand, if the coin is unbiased, then a deterministic strategy is of little help in winning. Entropy quantifies this notion of surprise and unpredictability.\n\"\"\"\n\n# ╔═╡ 4cf8cd38-ac26-48f5-8507-9ac56fb90867\nmd\"\"\"\n# Quantum states\n\nA classical coin is a two-level system: it is either heads or tails. At a first look a quantum state is a probability distribution, and the simplest case is a two-level state, which we call a qubit. Just like the way we can write the probability distribution as a column vector, we can write a quantum state as a column vector. For notational convenience that will become apparent later, we write the label of a quantum state in what is called a ket in the Dirac notation. So for instance, for some qubit, we can write \n\n``|\\psi\\rangle = \\begin{bmatrix} a_0 \\\\ a_1 \\\\ \\end{bmatrix}.``\n\nIn other words, a ket is just a column vector, exactly like the stochastic vector in the classical case. Instead of putting an arrow over the name of the variable to express that it is a vector, we use the ket to say that it is a column vector that represents a quantum state. There's more to this notation, as we will see.\n\nThe key difference to classical probability distributions and stochastic vectors is the normalization constraint. The square sum of their absolute values adds up to 1:\n\n$\\sqrt{|a_0|^2+|a_1|^2}=1,$\n\nwhere $a_0, a_1\\in \\mathbb{C}$. In other words, we are normalizing in the $l_2$ norm instead of the $l_1$ norm. Furthermore, we are no longer restricted to the positive orthant: the components of the quantum state vector, which we call *probability amplitudes*, are complex valued.\n\nLet us introduce two special qubits, corresponding to the canonical basis vectors in two dimensions: $|0\\rangle$ and $|1\\rangle$.\n\n$|0\\rangle = \\begin{bmatrix} 1 \\\\ 0 \\\\ \\end{bmatrix}, \\,\\,\\, |1\\rangle = \\begin{bmatrix} 0 \\\\ 1 \\\\ \\end{bmatrix}.$\n\nThis basis is also called the computational basis in quantum computing.\n\nWe can expand an arbitrary qubit state in this basis:\n\n$|\\psi\\rangle = \\begin{bmatrix} a_0 \\\\ a_1 \\\\ \\end{bmatrix}=a_0\\begin{bmatrix} 1 \\\\ 0 \\\\ \\end{bmatrix} + a_1 \\begin{bmatrix} 0 \\\\ 1 \\\\ \\end{bmatrix}= a_0|0\\rangle+a_1|1\\rangle.$\n\nThis expansion in a basis is called a superposition. If we sample the qubit state, we obtain the outcome 0 with probability $|a_0|^2$, and 1 with probability $|a_1|^2$. This is known as the Born rule; you will learn more about measurements and this rule in a subsequent notebook.\n\nFor now, let's take a look at how we can simulate classical coin tossing on a quantum computer. Let's start with a completely biased case where we get heads with probability 1. This means that our qubit $|\\psi\\rangle=|0\\rangle$. We create a circuit of a single qubit and a single classical register where the results of the sampling (measurements) go.\n\"\"\"\n\n# ╔═╡ 1b623852-7074-4211-bbcd-a65ac55c3070\nmd\"\"\"\nAny qubit is initialized in $|0\\rangle$, so if we measure it right away, we should get our maximally biased coin.\n\"\"\"\n\n# ╔═╡ 9e2a3016-ac1a-447c-a223-3c4b80c62025\nmeasure(q)\n\n# ╔═╡ 3e692d90-58ce-4562-a3fa-4d73e24b7b62\nmd\"\"\"\nLet us execute it a hundred times and study the result\n\"\"\"\n\n# ╔═╡ ee624636-c6fa-434a-bd6a-7048e755dffa\nresult = measure(q, nshots=100)\n\n# ╔═╡ 0ebecb30-7db3-11eb-0dab-6ba6b1b2522a\nbegin\n\tusing StatsBase\n\t[fit(Histogram, Int.(result), 0:2).weights string.(0:1)]\nend\n\n# ╔═╡ d6fc78fa-ba2e-45bf-af00-45fee2fd017e\nmd\"\"\"\nAs expected, all of our outcomes are $0$. \nTo understand the possible quantum states, we use the Bloch sphere visualization. Since the probability amplitudes are complex and there are two of them for a single qubit, this would require a four-dimensional space. Now since the vectors are normalized, this removes a degree of freedom, allowing a three-dimensional representation with an appropriate embedding. This embedding is the Bloch sphere. It is slightly different than an ordinary sphere in three dimensions: we identify the north pole with the state $|0\\rangle$, and the south pole with $|1\\rangle$. In other words, two orthogonal vectors appear as if they were on the same axis -- the axis Z. The computational basis is just one basis: the axes X and Y represent two other bases. Any point on the surface of this sphere is a valid quantum state. This is also true the other way around: every pure quantum state is a point on the Bloch sphere. Here it 'pure' is an important technical term and it essentially means that the state is described by a ket (column vector). Later in the course we will see other states called mix states that are not described by a ket (you will see later that these are inside the Bloch sphere).\n\nTo make it less abstract, let's plot our $|0\\rangle$ on the Bloch sphere:\n\"\"\"\n\n# ╔═╡ ba3d9b32-88dd-11eb-3b2a-0f96968e5bcb\nessentials.plot_blochsph(state(zero_state(1)))\n\n# ╔═╡ 63946ad1-d28d-4759-8898-085f189e57db\nmd\"\"\"\nCompare this sphere with the straight line in the positive orthant that describes all classical probability distributions of coin tosses. You can already see that there is a much richer structure in the quantum probability space.\n\nLet us pick another point on the Bloch sphere, that is, another distribution. Let's transform the state $|0\\rangle$ to $\\frac{1}{\\sqrt{2}}(|0\\rangle + |1\\rangle)$. This corresponds to the unbiased coin, since we will get 0 with probability $|\\frac{1}{\\sqrt{2}}|^2=1/2$, and the other way around. There are many ways to do this transformation. We pick a rotation around the Y axis by $\\pi/2$, which corresponds to the matrix $\\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1 & -1\\\\1 & 1\\end{bmatrix}$.\n\"\"\"\n\n# ╔═╡ a9bfa0e3-b128-43b1-af54-579d2bdcb3b7\nessentials.plot_hist(measure(zero_state(1) |> Ry(π/2), nshots=1024))\n\n# ╔═╡ 0ee44bd4-e41f-4977-b71c-9bc04bba0385\nmd\"\"\"\nTo get an intuition why it is called a rotation around the Y axis, let's plot it on the Bloch sphere:\n\"\"\"\n\n# ╔═╡ 770ae76e-6521-4613-b781-3627847ffae9\nessentials.plot_blochsph(state(zero_state(1) |> Ry(π/2)))\n\n# ╔═╡ 85bea7c1-71ba-4b6b-9341-affd291c0a7c\nmd\"\"\"\nIt does exactly what it says: it rotates from the north pole of the Bloch sphere.\n\nWhy is interesting to have complex probability amplitudes instead of non-negative real numbers? To get some insight, take a look what happens if we apply the same rotation to $|1\\rangle$. To achieve this, first we flip $|0\\rangle$ to $|1\\rangle$ by applying a NOT gate (denoted by X in quantum computing) and then the rotation.\n\"\"\"\n\n# ╔═╡ a2eaec0e-63a1-4771-899e-240289173b90\nessentials.plot_blochsph(state(zero_state(1) |> chain(1, put(1=>X), put(1=>Ry(π/2)))))\n\n# ╔═╡ d054d2e6-da5d-4070-8b93-c81f07af756d\nmd\"\"\"\nYou can verify that the result is $\\frac{1}{\\sqrt{2}}(-|0\\rangle + |1\\rangle)$. That is, the exact same state as before, except that the first term got a minus sign: it is a negative probability amplitude. Note that the difference cannot be observed from the statistics:\n\"\"\"\n\n# ╔═╡ 0c6bdade-da51-4442-90d4-f3c36aa06e4c\nbegin\n\tessentials.plot_hist(measure(zero_state(1) |> chain(1, put(1=>X), put(1=>Ry(π/2))), nshots=1024))\nend\n\n# ╔═╡ ca2b7743-b2b3-4335-8c4c-2647492072ed\nmd\"\"\"\nIt still looks like an approximately unbiased coin. Yet, that negative sign -- or any complex value -- is what models *interference*, a critically important phenomenon where probability amplitudes can interact in a constructive or a destructive way. To see this, if we apply the rotation twice in a row on $|0\\rangle$, we get another deterministic output, $|1\\rangle$, although in between the two, it was some superposition. \n\"\"\"\n\n# ╔═╡ 21a24eb3-6104-4f6a-bae5-d11e504aad62\nessentials.plot_hist(measure(zero_state(1) |> chain(1, put(1=>Ry(π/2)), put(1=>Ry(π/2))), nshots=1024))\n\n# ╔═╡ 5846d249-d73f-46d7-a1b9-09efc42ef331\nmd\"\"\"\nMany quantum algorithms exploit interference, for instance, the seminal [Deutsch-Josza algorithm](https://en.wikipedia.org/wiki/Deutsch–Jozsa_algorithm), which is among the simplest to understand its significance.\n\"\"\"\n\n# ╔═╡ 2994d86d-c2ba-417b-aa0e-b0c7d0956008\nmd\"\"\"\n# More qubits and entanglement\n\nWe have already seen that quantum states are probability distributions normed to 1 in the $l_2$ norm and we got a first peek at interference. If we introduce more qubits, we see another crucial quantum effect emerging. To do that, we first have to define how we write down the column vector for describing two qubits. We use a tensor product, which, in the case of qubits, is equivalent to the Kronecker product. Given two qubits, $|\\psi\\rangle=\\begin{bmatrix}a_0\\\\a_1\\end{bmatrix}$ and $|\\psi'\\rangle=\\begin{bmatrix}b_0\\\\b_1\\end{bmatrix}$, their product is $|\\psi\\rangle\\otimes|\\psi'\\rangle=\\begin{bmatrix}a_0b_0\\\\ a_0b_1\\\\ a_1b_0\\\\ a_1b_1\\end{bmatrix}$. Imagine that you have two registers $q_0$ and $q_1$, each can hold a qubit, and both qubits are in the state $|0\\rangle$. Then this composite state would be described by according to this product rule as follows:\n\"\"\"\n\n# ╔═╡ f98f70cf-aaf2-4710-9ef7-33c401b10c06\nlet\n\tq0 = [1, 0]\n\tq1 = [1, 0]\n\tkron(q0, q1)\nend\n\n# ╔═╡ 2f1a3452-a122-41f2-8ab7-df4e1cc01b02\nmd\"\"\"\nThis is the $|0\\rangle\\otimes|0\\rangle$ state, which we often abbreviate as $|00\\rangle$. The states $|01\\rangle$, $|10\\rangle$, and $|11\\rangle$ are defined analogously, and the four of them give the canonical basis of the four dimensional complex space, $\\mathbb{C}^2\\otimes\\mathbb{C}^2$.\n\nNow comes the interesting and counter-intuitive part. In machine learning, we also work with high-dimensional spaces, but we never construct it as a tensor product: it is typically $\\mathbb{R}^d$ for some dimension $d$. The interesting part of writing the high-dimensional space as a tensor product is that not all vectors in can be written as a product of vectors in the component space.\n\nTake the following state: $|\\phi^+\\rangle = \\frac{1}{\\sqrt{2}}(|00\\rangle+|11\\rangle)$. This vector is clearly in $\\mathbb{C}^2\\otimes\\mathbb{C}^2$, since it is a linear combination of two of the basis vector in this space. Yet, it cannot be written as $|\\psi\\rangle\\otimes|\\psi'\\rangle$ for some $|\\psi\\rangle$, $|\\psi'\\rangle\\in\\mathbb{C}^2$.\n\nTo see this, assume that it can be written in this form. Then\n\n$|\\phi^+\\rangle = \\frac{1}{\\sqrt{2}}(|00\\rangle+|11\\rangle) = \\begin{bmatrix}a_0b_0\\\\ a_0b_1\\\\ a_1b_0\\\\ a_1b_1\\end{bmatrix} = a_0b_0|00\\rangle + a_0b_1|01\\rangle + a_1b_0|10\\rangle + a_1b_1|11\\rangle.$\n\n$|01\\rangle$ and $|10\\rangle$ do not appear on the left-hand side, so their coefficients must be zero: $a_1b_0=0$ and $a_0b_1=0$. This leads to a contradiction, since $a_1$ cannot be zero ($a_1b_1=1$), so $b_0$ must be zero, but $a_0b_0=1$. Therefore $|\\phi^+\\rangle$ cannot be written as a product.\n\nStates that cannot be written as a product are called entangled states. This is the mathematical form of describing a phenomenon of strong correlations between random variables that exceed what is possible classically. Entanglement plays a central role in countless quantum algorithms. A simple example is [quantum teleportation](https://en.wikipedia.org/wiki/Quantum_teleportation). We will also see its applications in quantum machine learning protocols.\n\nWe will have a closer look at entanglement in a subsequent notebook on measurements, but as a teaser, let us look at the measurement statistics of the $|\\phi^+\\rangle$ state. The explanation of the circuit preparing it will also come in a subsequent notebook.\n\"\"\"\n\n# ╔═╡ a7cdf304-48d2-4485-b473-dd2248bb7ce6\nessentials.plot_hist(measure(zero_state(2) |> chain(2, put(1=>H), control(1, 2=>X)), nshots=1024))\n\n# ╔═╡ 5a2944be-209c-4fbe-b1b1-19a5f9df4316\nmd\"\"\"\nNotice that 01 or 10 never appear in the measurement statistics.\n\"\"\"\n\n# ╔═╡ ec3512fa-22de-4123-bb1f-440b899ac901\nmd\"\"\"\n# Further reading\n\nChapter 9 in Quantum Computing since Democritus by Scott Aaronson describes a similar approach to understanding quantum states -- in fact, the interference example was lifted from there.\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─4f69ca95-0111-40d3-b74b-34e999f4f185\n# ╠═feadb782-9905-4e05-a0c9-e1b1b54fb3b0\n# ╟─c3898a67-d4b2-46a0-b5cc-69420762cd62\n# ╠═02a05ce8-35ad-4192-a9d6-e7d3cc29e6ba\n# ╟─a776d9b8-9adb-4985-9830-165acb8d805b\n# ╠═c54da392-7d0b-11eb-278e-b3a7ec910fc7\n# ╟─8c7034ce-8286-4d06-9fe1-17581695219c\n# ╠═e42579e4-5e98-4cca-a425-a3b356dd03ba\n# ╟─13533ef2-3be4-4aea-981d-0bc77ec5db57\n# ╠═0d931337-ad9b-45d1-85fa-2b89f052099d\n# ╟─29c91dc7-cfda-42d4-bd0f-f479c611339e\n# ╠═c1ec3e28-93fc-42d5-8ef7-454cdb7f7c33\n# ╟─de543889-d698-4926-a2a2-9aea48578fd8\n# ╟─caa23a10-d43e-4a8c-b987-af69b55ed16e\n# ╠═cac5a2c0-6913-4997-b29d-154250be44dd\n# ╟─1dee601c-2f9f-46d8-be37-99d31e589ebe\n# ╠═15416de9-5fe1-4cb7-a5bb-b4227fd9ad4a\n# ╟─d803bf96-6cd4-4874-a3f7-ed7c0bf16267\n# ╟─4cf8cd38-ac26-48f5-8507-9ac56fb90867\n# ╠═6de3cf91-1739-49ac-aac5-0dcd72871461\n# ╟─1b623852-7074-4211-bbcd-a65ac55c3070\n# ╠═9e2a3016-ac1a-447c-a223-3c4b80c62025\n# ╟─3e692d90-58ce-4562-a3fa-4d73e24b7b62\n# ╠═ee624636-c6fa-434a-bd6a-7048e755dffa\n# ╠═0ebecb30-7db3-11eb-0dab-6ba6b1b2522a\n# ╟─d6fc78fa-ba2e-45bf-af00-45fee2fd017e\n# ╠═0ef307d4-84d3-11eb-10e7-07cc58485fba\n# ╠═ba3d9b32-88dd-11eb-3b2a-0f96968e5bcb\n# ╟─63946ad1-d28d-4759-8898-085f189e57db\n# ╠═a9bfa0e3-b128-43b1-af54-579d2bdcb3b7\n# ╟─0ee44bd4-e41f-4977-b71c-9bc04bba0385\n# ╠═770ae76e-6521-4613-b781-3627847ffae9\n# ╟─85bea7c1-71ba-4b6b-9341-affd291c0a7c\n# ╠═a2eaec0e-63a1-4771-899e-240289173b90\n# ╟─d054d2e6-da5d-4070-8b93-c81f07af756d\n# ╠═0c6bdade-da51-4442-90d4-f3c36aa06e4c\n# ╟─ca2b7743-b2b3-4335-8c4c-2647492072ed\n# ╠═21a24eb3-6104-4f6a-bae5-d11e504aad62\n# ╟─5846d249-d73f-46d7-a1b9-09efc42ef331\n# ╟─2994d86d-c2ba-417b-aa0e-b0c7d0956008\n# ╠═f98f70cf-aaf2-4710-9ef7-33c401b10c06\n# ╟─2f1a3452-a122-41f2-8ab7-df4e1cc01b02\n# ╠═a7cdf304-48d2-4485-b473-dd2248bb7ce6\n# ╟─5a2944be-209c-4fbe-b1b1-19a5f9df4316\n# ╟─ec3512fa-22de-4123-bb1f-440b899ac901\n", "meta": {"hexsha": "30ace6858faf3402a4a46592233d287f69651273", "size": 20581, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia_yao_version/01_Classical_and_Quantum_Probability_Distributions.jl", "max_stars_repo_name": "VarLad/qml-mooc", "max_stars_repo_head_hexsha": "1ece1b7736a95abc4d138644cfba1354a81b6e0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia_yao_version/01_Classical_and_Quantum_Probability_Distributions.jl", "max_issues_repo_name": "VarLad/qml-mooc", "max_issues_repo_head_hexsha": "1ece1b7736a95abc4d138644cfba1354a81b6e0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia_yao_version/01_Classical_and_Quantum_Probability_Distributions.jl", "max_forks_repo_name": "VarLad/qml-mooc", "max_forks_repo_head_hexsha": "1ece1b7736a95abc4d138644cfba1354a81b6e0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.46875, "max_line_length": 1187, "alphanum_fraction": 0.7520528643, "num_tokens": 7034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793113, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7712929583656212}}
{"text": "# indicator of nonpositive orthant\n\n\"\"\"\n  IndNonpositive()\n\nReturns the indicator function the nonpositive orthant, that is\n\n  `g(x) = 0 if x ⩽ 0, +∞ otherwise`\n\"\"\"\n\nimmutable IndNonpositive <: IndicatorConvexCone end\n\n\nfunction (f::IndNonpositive){R <: Real}(x::AbstractArray{R})\n  for k in eachindex(x)\n    if x[k] > 0\n      return +Inf\n    end\n  end\n  return 0.0\nend\n\nfunction prox!{R <: Real}(f::IndNonpositive, x::AbstractArray{R}, y::AbstractArray{R}, gamma::Real=1.0)\n  for k in eachindex(x)\n    if x[k] > 0\n      y[k] = zero(R)\n    else\n      y[k] = x[k]\n    end\n  end\n  return 0.0\nend\n\nfun_name(f::IndNonpositive) = \"indicator of the Nonpositive cone\"\nfun_dom(f::IndNonpositive) = \"AbstractArray{Real}\"\nfun_expr(f::IndNonpositive) = \"x ↦ 0 if all(0 ⩾ x), +∞ otherwise\"\nfun_params(f::IndNonpositive) = \"none\"\n\nfunction prox_naive{R <: Real}(f::IndNonpositive, x::AbstractArray{R}, gamma::Real=1.0)\n  y = min.(zero(R), x)\n  return y, 0.0\nend\n", "meta": {"hexsha": "265954ef552590bca7ccf199b5e6bb4f1d96c2c4", "size": 949, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indNonpositive.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/indNonpositive.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/indNonpositive.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0697674419, "max_line_length": 103, "alphanum_fraction": 0.6543730242, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7712790707229977}}
{"text": "using StochasticDelayDiffEq\r\nusing Random\r\nusing SparseArrays\r\n\r\nfunction sir_dde!(du,u,h,p,t)\r\n    (S,I,R) = u\r\n    (β,c,τ) = p\r\n    N = S+I+R\r\n    infection = β*c*I/N*S\r\n    (Sd,Id,Rd) = h(p, t-τ) # Time delayed variables\r\n    Nd = Sd+Id+Rd\r\n    recovery = β*c*Id/Nd*Sd\r\n    @inbounds begin\r\n        du[1] = -infection\r\n        du[2] = infection - recovery\r\n        du[3] = recovery\r\n    end\r\n    nothing\r\nend;\r\n\r\n# Define a sparse matrix by making a dense matrix and setting some values as not zero\r\nA = zeros(3,2)\r\nA[1,1] = 1\r\nA[2,1] = 1\r\nA[2,2] = 1\r\nA[3,2] = 1\r\nA = SparseArrays.sparse(A);\r\n\r\n# Make `g` write the sparse matrix values\r\nfunction sir_delayed_noise!(du,u,h,p,t)\r\n    (S,I,R) = u\r\n    (β,c,τ) = p\r\n    N = S+I+R\r\n    infection = β*c*I/N*S\r\n    (Sd,Id,Rd) = h(p, t-τ) # Time delayed variables\r\n    Nd = Sd+Id+Rd\r\n    recovery = β*c*Id/Nd*Sd\r\n    du[1,1] = -sqrt(infection)\r\n    du[2,1] = sqrt(infection)\r\n    du[2,2] = -sqrt(recovery)\r\n    du[3,2] = sqrt(recovery)\r\nend;\r\n\r\nfunction condition(u,t,integrator) # Event when event_f(u,t) == 0\r\n  u[2]\r\nend;\r\nfunction affect!(integrator)\r\n  integrator.u[2] = 0.0\r\nend;\r\ncb = ContinuousCallback(condition,affect!);\r\n\r\nδt = 0.1\r\ntmax = 40.0\r\ntspan = (0.0,tmax)\r\nt = 0.0:δt:tmax;\r\nu0 = [990.0,10.0,0.0]; # S,I,R\r\n\r\nfunction sir_history(p, t)\r\n    [1000.0, 0.0, 0.0]\r\nend;\r\n\r\np = [0.05,10.0,4.0]; # β,c,τ\r\nRandom.seed!(1234);\r\n\r\nprob_sdde = SDDEProblem(sir_dde!,sir_delayed_noise!,u0,sir_history,tspan,p;noise_rate_prototype=A);\r\nsol_sdde = solve(prob_sdde,LambaEM(),callback=cb);\r\n", "meta": {"hexsha": "cb9492ebe32a5462e60cbe6a12adda8903dd6bbe", "size": 1541, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/nondiagonal_sparse_noise.jl", "max_stars_repo_name": "JuliaDiffEq/StochasticDelayDiffEq.jl", "max_stars_repo_head_hexsha": "7f9780169008de6ffa9fe26d6d76a04eacb44035", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:31:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-21T18:44:49.000Z", "max_issues_repo_path": "test/nondiagonal_sparse_noise.jl", "max_issues_repo_name": "ChrisRackauckas/StochasticDelayDiffEq.jl", "max_issues_repo_head_hexsha": "7f9780169008de6ffa9fe26d6d76a04eacb44035", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-01-03T14:49:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-04T00:55:26.000Z", "max_forks_repo_path": "test/nondiagonal_sparse_noise.jl", "max_forks_repo_name": "ChrisRackauckas/StochasticDelayDiffEq.jl", "max_forks_repo_head_hexsha": "7f9780169008de6ffa9fe26d6d76a04eacb44035", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:37:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:37:30.000Z", "avg_line_length": 23.0, "max_line_length": 100, "alphanum_fraction": 0.5859831278, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.771279066975387}}
{"text": "using StatisticalRethinking, Optim\n#gr(size=(600,600));\n\np_grid = range(0, step=0.001, stop=1)\nprior = ones(length(p_grid))\nlikelihood = [pdf(Binomial(9, p), 6) for p in p_grid]\nposterior = likelihood .* prior\nposterior = posterior / sum(posterior)\nsamples = sample(p_grid, Weights(posterior), length(p_grid));\nsamples[1:5]\n\nN = 10000\nsamples = sample(p_grid, Weights(posterior), N);\n\nchn = MCMCChains.Chains(reshape(samples, N, 1, 1), [\"toss\"]);\n\nMCMCChains.describe(chn)\n\nplot(chn)\n\np = Vector{Plots.Plot{Plots.GRBackend}}(undef, 2)\np[1] = scatter(1:N, samples, markersize = 2, ylim=(0.0, 1.3), lab=\"Draws\")\n\nw = 6\nn = 9\nx = 0:0.01:1\np[2] = density(samples, ylim=(0.0, 5.0), lab=\"Sample density\")\np[2] = plot!( x, pdf.(Beta( w+1 , n-w+1 ) , x ), lab=\"Conjugate solution\")\n\nplot(p..., layout=(1, 2))\n\n# This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl\n\n", "meta": {"hexsha": "7522775185f418ab9401a567605aa4318b4e294b", "size": 891, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapters/03/clip-02-05.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_stars_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/03/clip-02-05.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_issues_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/03/clip-02-05.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_forks_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2058823529, "max_line_length": 87, "alphanum_fraction": 0.6722783389, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.8633916082162402, "lm_q1q2_score": 0.7712758496326982}}
{"text": "# indicator of the free cone\n\nexport IndFree\n\n\"\"\"\n**Indicator of the free cone**\n\n    IndFree()\n\nReturns the indicator function of the whole space, or \"free cone\", *i.e.*,\na function which is identically zero.\n\"\"\"\nstruct IndFree <: ProximableFunction end\n\nis_separable(f::IndFree) = true\nis_convex(f::IndFree) = true\nis_affine(f::IndFree) = true\nis_cone(f::IndFree) = true\nis_smooth(f::IndFree) = true\nis_quadratic(f::IndFree) = true\n\nconst Zero = IndFree\n\nfunction (f::IndFree)(x::AbstractArray{T}) where {R, T <: RealOrComplex{R}}\n    return R(0)\nend\n\nfunction prox!(y::AbstractArray{T}, f::IndFree, x::AbstractArray{T}, args...) where {R, T <: RealOrComplex{R}}\n    y .= x\n    return R(0)\nend\n\nfunction gradient!(y::AbstractArray{T}, f::IndFree, x::AbstractArray{T}) where {R, T <: RealOrComplex{R}}\n    y .= T(0)\n    return R(0)\nend\n\nfun_name(f::IndFree) = \"indicator of the free cone\"\nfun_dom(f::IndFree) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::IndFree) = \"x ↦ 0\"\nfun_params(f::IndFree) = \"none\"\n\nfunction prox_naive(f::IndFree, x::AbstractArray{R}, gamma=R(1)) where {R, T <: RealOrComplex{R}}\n    return x, R(0)\nend\n", "meta": {"hexsha": "26b988a7397759035747029d1a04be42aec51163", "size": 1143, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indFree.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_stars_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/indFree.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_issues_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/indFree.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_forks_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.847826087, "max_line_length": 110, "alphanum_fraction": 0.6824146982, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.863391617003942, "lm_q1q2_score": 0.7712758476733553}}
{"text": "# ---\n# title: 991. Broken Calculator\n# id: problem991\n# author: Indigo\n# date: 2021-05-31\n# difficulty: Medium\n# categories: Math, Greedy\n# link: <https://leetcode.com/problems/broken-calculator/description/>\n# hidden: true\n# ---\n# \n# On a broken calculator that has a number showing on its display, we can\n# perform two operations:\n# \n#   * **Double** : Multiply the number on the display by 2, or;\n#   * **Decrement** : Subtract 1 from the number on the display.\n# \n# Initially, the calculator is displaying the number `X`.\n# \n# Return the minimum number of operations needed to display the number `Y`.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: X = 2, Y = 3\n#     Output: 2\n#     Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: X = 5, Y = 8\n#     Output: 2\n#     Explanation: Use decrement and then double {5 -> 4 -> 8}.\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: X = 3, Y = 10\n#     Output: 3\n#     Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.\n#     \n# \n# **Example 4:**\n# \n#     \n#     \n#     Input: X = 1024, Y = 1\n#     Output: 1023\n#     Explanation: Use decrement operations 1023 times.\n#     \n# \n# \n# \n# **Note:**\n# \n#   1. `1 <= X <= 10^9`\n#   2. `1 <= Y <= 10^9`\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction broken_calc(x::Integer, y::Integer)\n    cnt = 0\n    while x < y\n        isodd(y) ? (y += 1) : y >>= 1\n        cnt += 1\n    end\n    return cnt + x - y\nend\n## @lc code=end\n", "meta": {"hexsha": "67675689bfe34f347cd514c407eac35fea1cb5a6", "size": 1531, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/991.broken-calculator.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/991.broken-calculator.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/991.broken-calculator.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 19.1375, "max_line_length": 83, "alphanum_fraction": 0.5447419987, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8633916029436189, "lm_q1q2_score": 0.7712758473749857}}
{"text": "using Base.Iterators\nusing Zygote\n\n\"\"\"\n    xlogx(x::Number)\n\nCompute `x * log(x)`, returning zero if `x` is zero. (Copied from StatsFuns.jl package.)\n\"\"\"\nfunction xlogx(x::Number)\n    result = x * log(x)\n    ifelse(iszero(x), zero(result), result)\nend\n\n\"\"\"\nCompute the von Neumann entropy of a density matrix `ρ`.\n\"\"\"\nneumann_entropy(ρ::AbstractMatrix) = -sum(xlogx.(real(eigvals(Matrix(ρ)))))\n\n\"\"\"\n    binary_entropy(p::Number)\n\nCompute the binary entropy of `p` (natural logarithm).\n\"\"\"\nbinary_entropy(p::Number) = -(xlogx(p) + xlogx(1 - p))\n\neig_entropy(θlist) = -sum(xlogx.(sum(θlist .* eigvs)))\n\n\"\"\"\nCompute `-log(Z)`, with `Z` the partition function.\n\"\"\"\nthermal_logZ(βH::AbstractMatrix) = -log(tr(exp(-Matrix(βH))))\n\n\"\"\"\nUse representation of density matrix in terms of Pauli matrices; cos(θ) is Bloch vector coefficient of Pauli-Z for each qubit\n\"\"\"\nlatent_density(θlist) = DensityMatrix(kron([[1, 0, 0, cos(θ)] for θ in θlist]...), length(θlist))\n\n\"\"\"\nTrace distance to target density matrix `σ`.\n\"\"\"\ntrdistance(θlist, σ, cgc) = 0.5 * opnorm(real.(matrix(apply(latent_density(θlist), cgc))) - σ, 1)\n\n\n\"\"\"\nCalculate fidelity as defined in arxiv:1910.02071\n\"\"\"\nfunction fidelity(θlist, σtherm, cgc)\n    ρsqrt = sqrt(real.(matrix(apply(latent_density(θlist), cgc))))\n    return real(tr(sqrt(ρsqrt * σtherm * ρsqrt))^2)\nend\n\nfunction trans_mat(L::Int)\n    A = [1 0; 0 0; 0 0; 0 1]\n    Avec = fill(A, L)\n    kron(Avec...)\nend\n\nfunction ngradient(f, xs::AbstractArray...)\n    grads = zero.(xs)\n    for (x, Δ) in zip(xs, grads), i in 1:length(x)\n        δ = sqrt(eps())\n        tmp = x[i]\n        x[i] = tmp - δ/2\n        y1 = f(xs...)\n        x[i] = tmp + δ/2\n        y2 = f(xs...)\n        x[i] = tmp\n        Δ[i] = (y2-y1)/δ\n        if eltype(x) <: Complex\n            # derivative with respect to imaginary part\n            x[i] = tmp - im*δ/2\n            y1 = f(xs...)\n            x[i] = tmp + im*δ/2\n            y2 = f(xs...)\n            x[i] = tmp\n            Δ[i] += im*(y2-y1)/δ\n        end\n    end\n    return grads\nend\n\nsigmoid(z::Real) = 1.0 / (1.0 + exp(-z))", "meta": {"hexsha": "7e1df2c96004c9d13a7e007d2836e3164e6481ab", "size": 2071, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "density_demo/src/util.jl", "max_stars_repo_name": "cmendl/density-matrix-bloch-qcircuit", "max_stars_repo_head_hexsha": "1ffac6814f83fc8f3c81dbeb9e972843c35780eb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "density_demo/src/util.jl", "max_issues_repo_name": "cmendl/density-matrix-bloch-qcircuit", "max_issues_repo_head_hexsha": "1ffac6814f83fc8f3c81dbeb9e972843c35780eb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "density_demo/src/util.jl", "max_forks_repo_name": "cmendl/density-matrix-bloch-qcircuit", "max_forks_repo_head_hexsha": "1ffac6814f83fc8f3c81dbeb9e972843c35780eb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-25T16:15:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T16:15:49.000Z", "avg_line_length": 25.256097561, "max_line_length": 125, "alphanum_fraction": 0.5832930951, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7712718256182082}}
{"text": "module NewtonsMethod\n\nusing ForwardDiff\n\nfunction newtonroot(f, fp; x0, tol=1e-7, maxiter=1000)\n    abserror = Inf\n    iter = 1\n    x = x0\n    while abserror > tol && iter <= maxiter\n        x_new = x - f(x)/fp(x)\n        iter = iter +1\n        abserror = abs(x_new - x)\n        x = x_new\n    end\n    return x\nend\n\nfunction newtonroot(f; x0, tol = 1e-7, maxiter=1000)\n    fp = x -> ForwardDiff.derivative(f, x)\n    newtonroot(f, fp; x0=x0, tol=tol, maxiter=maxiter)\nend\n\nexport newtonroot\nend\n", "meta": {"hexsha": "714223a8ed0f07c0cc6004a95cae21a65847afcf", "size": 493, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NewtonsMethod.jl", "max_stars_repo_name": "ykkan/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "7cde23f25d50a3a5469492d481aad00c701a4849", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NewtonsMethod.jl", "max_issues_repo_name": "ykkan/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "7cde23f25d50a3a5469492d481aad00c701a4849", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NewtonsMethod.jl", "max_forks_repo_name": "ykkan/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "7cde23f25d50a3a5469492d481aad00c701a4849", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.72, "max_line_length": 54, "alphanum_fraction": 0.6085192698, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7712718164236788}}
{"text": "# Successive Projection Algorithm (SPA) for separable NMF\n#\n#   Reference: N. Gillis and S. A. Vavasis, \"Fast and robust recursive\n#   algorithms for separable nonnegative matrix factorization,\" \n#   IEEE Transactions on Pattern Analysis and Machine Intelligence, \n#   vol. 36, no. 4, pp. 698-714, 2013. \n\nmutable struct SPA{T}\n    obj::Symbol   # objective :mse or :div\n\n    function SPA{T}(;obj=:mse) where T\n        obj == :mse || obj == :div || throw(ArgumentError(\"Invalid value for obj.\"))\n        new{T}(obj)\n    end\nend\n\n\"\"\"\nseparable_data(m,n,k)\nGenerate a (m x n) matrix X of nonnegative, separable data\nwith nonnegative rank k. The rows of X correspond to\nobservations and the columns of X correspond to features.\nThe separability condition implies that the columns of H\ncan be permuted to form a (k x k) diagonal block, and \nthe sum of the entries of each column of H is at most one. \nThus, the (scaled) columns of W appear in X.\n\"\"\"\nfunction separable_data(m, n, k)\n    W = rand(m, k)\n    \n    # impose separability\n    V = rand(k, n-k)\n    V ./= sum(V, dims=1)\n    H = [Matrix(I, k, k) V]\n    # permute columns of H\n    H = H[:, randperm(n)]\n    \n    return W, H\nend\n\n# initialization\nfunction spa(X::Matrix{T}, k::Integer; nnls_alg::Tuple{Symbol, Symbol}=(:pivot, :cache)) where T\n\n    # Normalize data so that columns of X sum to one\n    R = X ./ sum(X, dims=1)\n\n    # W = R[:,ai], where ai are the \"anchor indices\"\n    # (ai forms the convex hull of columns in R)\n    ai = Vector{Int}(undef, k)\n\n    # Add columns of X that are furthest from span(W)\n    for j = 1:k\n        # Add column with the largest residual\n        ai[j] = argmax(vec(sum(R.^2, dims=1)))\n        \n        # Project R onto the selected column\n        p = R[:,ai[j]]         \t# column we're projecting on\n        R -= p*(p'*R) ./(p'*p) \t# new residual matrix\n    end\n    \n    # Estimate W as the anchor columns of X\n    W = X[:,ai]\n    \n    # Estimate H by non-negative least squares: minimize ||X - W*H||\n    H = nonneg_lsq(W, X, alg=:fnnls)\n    projectnn!(H) \n\n    return W, H\nend\n\n# calculate statistics for result\nfunction solve!(alg::SPA{T}, X, W, H) where T\n    if alg.obj == :mse\n        objv = convert(T, 0.5) * sqL2dist(X, W*H)\n    elseif alg.obj == :div\n        objv = gkldiv(X, W*H)\n    else\n        error(\"Invalid value for obj.\")\n    end\n    return Result{T}(W, H, 0, true, objv)\nend\n\n", "meta": {"hexsha": "8896b17bdebf62f446ecbf99d9e271dc9d125824", "size": 2385, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spa.jl", "max_stars_repo_name": "eric-nam/NMF.jl", "max_stars_repo_head_hexsha": "c211e7cb6f9f69b3ada48fddfa073a4f4d62de76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-01-08T23:59:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T11:49:30.000Z", "max_issues_repo_path": "src/spa.jl", "max_issues_repo_name": "eric-nam/NMF.jl", "max_issues_repo_head_hexsha": "c211e7cb6f9f69b3ada48fddfa073a4f4d62de76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2015-01-25T09:51:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T16:28:07.000Z", "max_forks_repo_path": "src/spa.jl", "max_forks_repo_name": "eric-nam/NMF.jl", "max_forks_repo_head_hexsha": "c211e7cb6f9f69b3ada48fddfa073a4f4d62de76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 45, "max_forks_repo_forks_event_min_datetime": "2015-03-20T21:55:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T02:27:53.000Z", "avg_line_length": 29.0853658537, "max_line_length": 96, "alphanum_fraction": 0.6167714885, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7712718146939838}}
{"text": "#=\n\n  Gaussian mixture model.\n\n  cf ~/blog/gaussian_mixture_model.blog\n     ~/psi/gaussian_mixture_model.psi\n     ~/webppl/gaussian_mixture_model.wppl\n\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n@model function gaussian_mixture_model()\n    x = [0.2,1.0,0.5,0.6]\n    n = length(x)\n\n    p ~ Beta(0.5, 1)\n    a ~ Uniform(-1, 1)\n    b ~ Uniform(-1, 1)\n\n    z = tzeros(n)\n    x = tzeros(n)\n    for i in 1:n\n        z[i] ~ Bernoulli(p)\n        if z[i] == 1\n            x[i] ~ Normal(a, 1.0)\n        else\n            x[i] ~ Normal(b, 1.0)\n        end\n    end\n\n    a_is_greater_than_b ~ Dirac(a > b)\n\nend\n\nmodel = gaussian_mixture_model()\n\nnum_chns = 4\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), MCMCThreads(), 100_000, num_chns)\n# chns = sample(model, MH(), MCMCThreads(), 10_000, num_chns)\n# chns = sample(model, MH(), 100_000)\n\n# chns = sample(model, PG(15), MCMCThreads(), 10_000, num_chns)\n\n# chns = sample(model, SMC(1000), MCMCThreads(), 10_000, num_chns)\nchns = sample(model, SMC(), 40_000)\n# chns = sample(model, IS(), 10_000)\n\n#\n# chns = sample(model, Gibbs(HMC(0.1,5,:a,:b),PG(15,:p,:a_is_greater_than_b)), 10_000)\n# chns = sample(model, Gibbs(NUTS(1000,0.65,:a,:b),PG(15,:p,:a_is_greater_than_b)), 10_000)\n\n\ndisplay(chns)\n# display(plot(chns))\n\n# show_var_dist_pct(chns,:a,20)\n# show_var_dist_pct(chns,:b,20)\n# show_var_dist_pct(chns,:p,20)\n\nshow_var_dist_pct(chns,:a_is_greater_than_b)\n", "meta": {"hexsha": "76326bc940181789851cac2c56f69393cb857c12", "size": 1440, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/gaussian_mixture_model.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/gaussian_mixture_model.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/gaussian_mixture_model.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 22.1538461538, "max_line_length": 91, "alphanum_fraction": 0.6319444444, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7712718145574702}}
{"text": "\"\"\"\n#### function ```get_area(x1::Float64, x2::Float64, a::Float64, b::Float64)```\n<br>\n\n    Description of ```get_area```\n    ----------------------------------------\nReturns the area under trapezoid, where \"roof\" is defined by a linear function y = ax +b. \n\n\"\"\"\nfunction get_area(x1::Float64, x2::Float64, a::Float64, b::Float64)\n    # area under the trapezoid is A = Δx * ⟨y⟩\n    # where Δx is the width of the base of trapezoid\n    # and ⟨y⟩ is mean height\n    \n    Δx = abs(x2-x1) \n    mean_y = abs( get_line_point(x2,a,b) + get_line_point(x1,a,b)) / 2\n    return Δx * mean_y\nend\n\n\"\"\"\n#### function ```get_row_volume(df_row::DataFrame, thickness = 0.001)```\n<br>\n\n    Description of ```get_row_volume```\n    ----------------------------------------\nReturns the volume of trapezoid, where \"roof\" is defined by a linear function y = ax +b and thickness is the step between rows - ΔE. \n```df_row``` is the df subset where df.E1 .== e1, e1 is the constant energy for which the linear approximation was made. \n\n\"\"\"\nfunction get_row_volume(df_row::DataFrame, thickness = 0.001)\n    totalArea = sum(get_area.(df_row.minE, df_row.maxE, df_row.a, df_row.b))\n    volume = totalArea*thickness\n    return volume\nend\n\n\"\"\"\n#### function ```get_total_volume(df_rebinned::DataFrame, thickness = 0.001)```\n<br>\n\n    Description of ```get_total_volume```\n    ----------------------------------------\nReturns the total volume as a sum of all rows. Thickness is the step between energies, ΔE. \n\n\"\"\"\nfunction get_total_volume(df_rebinned::DataFrame, thickness = 0.001)\n    volume = 0.0\n    for e in unique(df_rebinned.E1)\n        volume += get_row_volume(df_rebinned[df_rebinned.E1 .== e, :], thickness)\n    end\n    return volume\nend\n\n\"\"\"\n#### function ```get_segment_volume(df::DataFrame, X1::Float64, X2::Float64, thickness = 0.001)```\n<br>\n\n    Description of ```get_segment_volume```\n    ----------------------------------------\nReturns the volume of a segment enclosing x1, x2. \n\n\"\"\"\nfunction get_segment_volume(df::DataFrame, X1::Float64, X2::Float64, thickness = 0.001)\n    X1 < minimum(df.minE) && (X1 = minimum(df.minE))  #if x1 is less than the lowest minE value in df, set X1 to the lowest value \n    X2 > maximum(df.maxE) && (X2 = maximum(df.maxE))  #if x2 is more than the highest minE value in df, set X2 to the highest value \n    \n\n    df_segment = subset(df, :minE => e -> e .<= X1, :maxE => e -> e .> X1, view = :true) # return df subset where minE < X1 < maxE\n\n    if nrow(df_segment) == 0\n        return 0.0\n    end\n\n    A = 0.0\n     \n    if(X1 > df_segment.minE[1]) && (X2 < df_segment.maxE[1] )                     # if the bounds are within one line region\n        A += get_area(X1, X2, df_segment.a[1], df_segment.b[1])\n        return A*thickness\n    end\n    \n    while df_segment.maxE[1] - X2 < 0\n        A += get_area(X1, df_segment.maxE[1], df_segment.a[1], df_segment.b[1])\n        X1 = df_segment.maxE[1]\n        df_segment = subset(df, :minE => e -> e .<= X1, :maxE => e -> e .> X1, view = :true)\n\n    end\n    A += get_area(df_segment.minE[1], X2, df_segment.a[1], df_segment.b[1])\n    return A*thickness\nend\n\n\n\"\"\"\n#### function ```get_volume_matrix(df::DataFrame, eMin, eMax, dE, thickness = 0.001)```\n<br>\n\n    Description of ```get_volume_matrix```\n    ----------------------------------------\nReturns a square matrix of volumes. Each cell defines volume of a segment defined by dE1*dE2 = dE^2.\n\n\"\"\"\nfunction get_volume_matrix(df::DataFrame, eMin, eMax, dE, thickness = 0.001) #returns square matrix with volumes\n    dims = length(minimum(df.E1):dE:maximum(df.E1))  # dimension of the square matrix\n        \n    volumesTruncated = zeros(dims,dims) # final volume to output with dimensions n x n \n    temp_volumes = zeros(dims, length(unique(df.E1)))  # 30x2997\n    \n    for (idxE1, uniqueE1) in enumerate(unique(df.E1))  #1:2997\n        df_e1 = subset(df, :E1 => e -> e .== uniqueE1)\n        \n        for (idxEnergy, energy) in enumerate(eMin:dE:eMax) # 1:30\n            temp_volumes[idxEnergy, idxE1] = get_segment_volume(df_e1, energy, energy+dE, thickness)\n        end\n    end\n    \n    n = floor(Int,length(unique(df.E1))/ dims )  # how many cols to truncate\n    for r in 1:length(temp_volumes[:,1])              # truncating n cols into 1\n        volumesTruncated[r,:] = [sum(temp_volumes[r,i:i+n]) for i in 1:n:length(temp_volumes[r,:])-n]\n    end\n    return volumesTruncated\nend", "meta": {"hexsha": "85d0d38cbae81416722c2cab052a0538e2181f92", "size": 4400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Volume.jl", "max_stars_repo_name": "Shoram444/MPRebinSpectra.jl", "max_stars_repo_head_hexsha": "7fc14bd678844473062d9d22f7aef9a4123a93c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Volume.jl", "max_issues_repo_name": "Shoram444/MPRebinSpectra.jl", "max_issues_repo_head_hexsha": "7fc14bd678844473062d9d22f7aef9a4123a93c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Volume.jl", "max_forks_repo_name": "Shoram444/MPRebinSpectra.jl", "max_forks_repo_head_hexsha": "7fc14bd678844473062d9d22f7aef9a4123a93c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.974789916, "max_line_length": 133, "alphanum_fraction": 0.6113636364, "num_tokens": 1292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475810629194, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7712569107457006}}
{"text": "\n######################################################################\n# weierstrasspoints.jl: Addition laws for projective points on Weierstrass curves\n######################################################################\n\nexport infinity, projective_add, projective_scalar_mul\n\n\n######################################################################\n# Basic methods\n######################################################################\n\n\"\"\"\nGet the point at infinity on an elliptic curve in Weierstrass form.\n\"\"\"\nfunction infinity(E::AbstractWeierstrass)\n    R = base_ring(E)\n    return EllipticPoint(Nemo.zero(R), Nemo.one(R), Nemo.zero(R), E)\nend\n\nfunction zero(E::AbstractWeierstrass)\n\treturn infinity(E)\nend\n\n\n######################################################################\n# Addition law\n######################################################################\n\n\"\"\"\nGet the opposite of a point on an elliptic curve in Weierstrass form.\n\"\"\"\nfunction -(P::EllipticPoint)\n\tE = P.curve\n\tx, y, z = coordinates(P)\n\ta1, _, a3, _, _ = a_invariants(E)\n    return EllipticPoint(x, - y - a1 * x - a3 * z, z, E)\nend\n\n\"\"\"\nGet the sum of two normalized projective points on the same Weierstrass curve, assuming they are not equal and not inverse of each other.\n\"\"\"\nfunction _addgeneric(P::EllipticPoint{T}, Q::EllipticPoint{T}) where T<:Nemo.FieldElem\n    E = P.curve\n\ta1, a2, a3, _, _ = a_invariants(E)\n\t\n\txq, yq, zq = coordinates(Q)\n\t@assert zq == 1\n\txp, yp, zp = coordinates(P)\n\t@assert zp == 1\n\t\n\t#sanity check\n\t@assert xp != xq\n\t\n    denom = xq - xp\n\tinverse = 1//denom\n    lambda = (yq - yp) * inverse\n    nu = (yp * xq - xp * yq) * inverse\n    \n    Xplus = lambda^2 + a1 * lambda - a2 - xp - xq\n    Yplus = -(lambda + a1) * Xplus - nu - a3\n    Zplus = Nemo.one(base_ring(P))\n    return EllipticPoint(Xplus, Yplus, Zplus, E)\nend\n\n\"\"\"\nGet the sum of two normalized projective points on the same Weierstrass curve, assuming they have equal x-coordinate.\n\"\"\"\nfunction _addequalx(P::EllipticPoint{T}, Q::EllipticPoint{T}) where T<:Nemo.FieldElem\n    E = P.curve\n\ta1, a2, a3, a4, a6 = a_invariants(E)\n\t\n\txp, yp, zp = coordinates(P)\n\t@assert zp == 1\n\txq, yq, zq = coordinates(Q)\n\t@assert zq == 1\n\t\n\t#sanity check\n\t@assert xp == xq\n\t\n    denom = yp + yq + a1 * xq + a3\n    if iszero(denom)\n\t    return infinity(E)\n    else\n\t\tinverse = 1//denom\n\t    lambda = (3 * xp^2 + 2 * a2 * xp + a4 - a1 * yp) * inverse\n\t    nu = (- xp^3 + a4 * xp + 2 * a6 - a3 * yp) * inverse\n\t    Xplus = lambda^2 + a1 * lambda - a2 - xp - xq\n        Yplus = -(lambda + a1) * Xplus - nu - a3\n        Zplus = one(base_ring(P))\n\t    return EllipticPoint(Xplus, Yplus, Zplus, E)\n    end\nend\n\n\"\"\"\nGet the double of a normalized point.\n\"\"\"\nfunction _double(P::EllipticPoint)\n\tif isinfinity(P)\n\t\treturn infinity(P.curve)\n\telse\n\t\treturn _addequalx(P, P)\n\tend\nend\n\n\n\"\"\"\nGet the sum of two projective points on the same Weierstrass curve.\n\n\"\"\"\nfunction +(P::EllipticPoint{T}, Q::EllipticPoint{T}) where T<:Nemo.FieldElem\n    P = normalized(P)\n    Q = normalized(Q)\n\txp, _, _ = coordinates(P)\n\txq, _, _ = coordinates(Q)\n    if isinfinity(P)\n        return Q\n    elseif isinfinity(Q)\n        return P\n    elseif xp == xq\n\t\treturn _addequalx(P,Q)\n    else\n\t\treturn _addgeneric(P,Q)\n    end\nend\n\nfunction -(P::EllipticPoint{T}, Q::EllipticPoint{T}) where T<:FieldElem\n\treturn P + (-Q)\nend\n\n\"\"\"\nGet a scalar multiple of a point on a Weierstrass curve.\n\"\"\"\n\nfunction *(k::Integer, P::EllipticPoint)\n\tE = P.curve\n\tP = normalized(P)\n\tif k == 0\n\t\treturn infinity(E)\n\telseif k<0\n\t\treturn (-k) * (-P)\n\telse\n\t\tif isinfinity(P)\n\t\t\treturn infinity(E)\n\t\telse\n\t\t\treturn _ladder(k, P)\n\t\tend\n\tend\nend\n\n# function *(k::Integer, P::EllipticPoint)\n# \treturn k * P\n# end\n\nfunction _ladder(m::Integer, P::EllipticPoint)\n    p0 = P\n    for b in Iterators.drop(Iterators.reverse(digits(Int8, m, base=2)), 1)\n        if (b == 0)\n            p0 = _double(p0)\n        else\n            p0 = P + _double(p0)\n        end\n    end\n    return p0\nend\n\n######################################################################\n# Projective addition law for Short Weierstrass curves\n######################################################################\n\n# P = (x1, y1, z1)\n# Q = (x2, y2, z2)\n# P + Q = (x3, y3, z3)\n# if P != Q then\n# x3 = (x2 z1 - x1 z2) [ (y2 z1 - y1 z2)^2 z1 z2 - (x2 z1 - x1 z2)^2 (x2 z1 + x1 z2) ]\n# y3 = (y2 z1 - y1 z2) [ (x2 z1 - x1 z2)^2 (x2 z1 + 2 x1 z2) - (y2 z1 - y1 z2)^2 z1 z2 ] - (x2 z1 - x1 z2)^3 y1 z2\n# z3 = (x2 z1 - x1 z2)^3 z1 z2\n# if P = Q then\n# x3 = 2 y1 z1 [ (a z1^2 + 3 x1^2)^2 - 8 x1 y1^2 z1 ]\n# y3 = (a z1^2 + 3 x1^2 ) [ 12 x1 y1^2 z1 - a^2 (z1^2 + 3 x1^2)^2 ] - 8 y1^4 z1^2\n# z3 = (2 y1 z1)^3\n\n#This function is only to be used with distinct points on the same short Weierstrass curve\n#xdet is x2 z1 - x1 z2, and ydet is y2 z1 - y1 z2\nfunction _projective_add_neq(P::EllipticPoint{T}, Q::EllipticPoint{T}, xdet::T, ydet::T) where T\n\tx1, y1, z1 = coordinates(P)\n\tx2, y2, z2 = coordinates(Q)\n\txdet2 = xdet^2\n\txdet3 = xdet2 * xdet\n\tydet2 = ydet^2\n\tz1z2 = z1 * z2\n\t#we could save a few multiplications in what follows\n\tx3 = xdet * ( ydet2 * z1z2 - xdet2 * (x2 * z1 + x1 * z2) )\n\ty3 = ydet * ( xdet2 * (x2 * z1 + 2 * x1 * z2) - ydet2 * z1z2 ) - xdet3 * y1 * z2\n\tz3 = xdet3 * z1z2\n\tres = Point(x3, y3, z3, base_curve(P))\n\t#@assert isvalid(res) #sanity check\n\treturn res\nend\n\n#This function is only to be used with a point on a short Weierstrass curve\nfunction _projective_dbl(P::EllipticPoint{T}) where T\n\tx, y, z = coordinates(P)\n\t_, _, _, a, b = a_invariants(base_curve(P))\n\tfactor = a * z^2 + 3 * x^2\n\tfactor2 = factor^2\n\tyz = y * z\n\txy2z = x * y * yz\n\t#we could save again a few multiplications in what follows\n\txprime = 2 * yz * ( factor2 - 8 * xy2z )\n\typrime = factor * ( 12 * xy2z - factor2 ) - 8 * (yz)^2 * y^2\n\tzprime = 8 * (yz)^3\n\tres = Point(xprime, yprime, zprime, base_curve(P))\n\t#@assert isvalid(res) #sanity check\n\treturn res\nend\n\n#This function is only to be used with two points on the same short Weierstrass curve\n#Compute xdet and ydet, if they are both zero go to _projective_dbl\nfunction projective_add(P::EllipticPoint{T}, Q::EllipticPoint{T}) where T\n\tx1, y1, z1 = coordinates(P)\n\tx2, y2, z2 = coordinates(Q)\n\txdet = x2 * z1 - x1 * z2\n\tydet = y2 * z1 - y1 * z2\n\tif ((xdet == 0) & (ydet == 0))\n\t\treturn _projective_dbl(P)\n\telse\n\t\treturn _projective_add_neq(P, Q, xdet, ydet)\n\tend\nend\n\n#Here we assume v is a positive integer and P lives on a short Weierstrass curve\nfunction _projective_scalar_mul(P::EllipticPoint, v::Integer)\n    P0 = P\n    for b in Iterators.drop(Iterators.reverse(digits(Int8, v, base=2)), 1)\n        P0 = _projective_dbl(P0)\n        if (b == 1)\n            P0 = projective_add(P0, P)\n        end\n    end\n    return P0\nend\n\nfunction projective_scalar_mul(P::EllipticPoint, v::Integer)\n\tif v == 0\n\t\treturn infinity(base_curve(E))\n\telseif v < 0\n\t\treturn - _projective_scalar_mul(P, -v)\n\telse\n\t\treturn _projective_scalar_mul(P, v)\n\tend\nend\n\n\n\n", "meta": {"hexsha": "f79677b2a16aba41eddd9679ed035febb002c888", "size": 6946, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/weierstrasspoints.jl", "max_stars_repo_name": "defeo/EllipticCurves.jl", "max_stars_repo_head_hexsha": "c69fa0b38f59b0bca0f98eccce425fcbb2489f57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-27T03:56:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-27T03:56:51.000Z", "max_issues_repo_path": "src/weierstrasspoints.jl", "max_issues_repo_name": "defeo/EllipticCurves.jl", "max_issues_repo_head_hexsha": "c69fa0b38f59b0bca0f98eccce425fcbb2489f57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/weierstrasspoints.jl", "max_forks_repo_name": "defeo/EllipticCurves.jl", "max_forks_repo_head_hexsha": "c69fa0b38f59b0bca0f98eccce425fcbb2489f57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-11T08:00:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T02:05:17.000Z", "avg_line_length": 27.1328125, "max_line_length": 137, "alphanum_fraction": 0.5803340052, "num_tokens": 2394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7712569055370209}}
{"text": "#################################\n## Bayesian model selection demo\n## for polynomial regression\n\nusing PyPlot, PyCall\nusing Distributions\n\nfunction poly(X_raw, M)\n    N = size(X_raw, 1)\n    X = zeros(M, N)\n    for m in 0 : M - 1\n        X[m+1,:] = X_raw.^m\n    end\n    return X\nend\n\nfunction learn_bayes(X_raw, Y, M, sig2_y, Sig_w, X_lin)\n    X = poly(X_raw, M)\n    N = size(X_raw, 1)\n    \n    # calc posterior\n    Sig_w_h = inv(X*inv(sig2_y*eye(N))*X' + inv(Sig_w))\n    mu_w_h = Sig_w_h * (X * inv(sig2_y * eye(N)) * Y)\n\n    # calc predictive\n    X_test = poly(X_lin, M)\n    Y_est = (mu_w_h'*X_test)'\n    sig2_y_prd = sig2_y + diag(X_test'Sig_w_h*X_test)\n    \n    # calc evidence\n    evidence = -0.5*(sum(Y)*inv(sig2_y) +N*log.(sig2_y) + N*log.(2*pi)\n                     + logdet(Sig_w)\n                     - (mu_w_h'*inv(Sig_w_h)*mu_w_h)[1] - logdet(Sig_w_h)\n                     )\n    return Y_est, sqrt.(sig2_y_prd), evidence\nend\n\nfunction test()\n    # linspace\n    X_lin = linspace(-1, 7, 200)\n    \n    # generate data\n    N = 10\n    sig2_y = 0.1\n    X = 2*pi*rand(N)\n    Y_true = [sin.(x) for x in X_lin]\n    Y_obs = [sin.(x) + sig2_y * randn() for x in X]\n    \n    dims = [1, 2, 3, 4, 5, 10]\n    \n    # learning via Bayes\n    sig2_w = 1.0\n    Y_bayes = [learn_bayes(X, Y_obs, m, sig2_y, sig2_w*eye(m), X_lin) for m in dims]\n\n    #############\n    # compute evidences\n    evidence = [learn_bayes(X, Y_obs, m, sig2_y, sig2_w*eye(m), X_lin)[3] for m in dims]\n    figure(\"evidence\")\n    clf()\n    plot(1:length(dims), evidence)\n    xticks(1:length(dims),dims)\n    ylabel((\"\\$\\\\ln p(\\\\bf{Y}|\\\\bf{X})\\$\"), fontsize=20)\n    xlabel((\"\\$M\\$\"), fontsize=20)\n    \n    #############\n    # visualize\n    x_min = X_lin[1]\n    x_max = X_lin[end]\n    y_min = -4\n    y_max = 4\n    \n    figure(\"prediction\")\n    clf()\n    for k in 1 : 6\n        subplot(230 + k)\n        plot(X_lin, Y_bayes[k][1])\n        plot(X_lin, Y_bayes[k][1] + Y_bayes[k][2], \"c--\")\n        plot(X_lin, Y_bayes[k][1] - Y_bayes[k][2], \"c--\")\n        plot(X, Y_obs, \"ko\")\n        xlim([x_min, x_max])\n        ylim([y_min, y_max])\n        text(x_max - 2.5, y_max - 1, @sprintf(\"M=%d\", dims[k]))\n    end\n    show()\nend\n\ntest()\n\n", "meta": {"hexsha": "eb19ab33fdefab77f936cf666c96f3bc3a892b74", "size": 2187, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/demo_PolynomialRegression.jl", "max_stars_repo_name": "triwave33/BayesBook", "max_stars_repo_head_hexsha": "86967e67381b01181ae3b3ad28d46011140dcc5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 158, "max_stars_repo_stars_event_min_datetime": "2017-10-19T13:33:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:59:21.000Z", "max_issues_repo_path": "src/demo_PolynomialRegression.jl", "max_issues_repo_name": "triwave33/BayesBook", "max_issues_repo_head_hexsha": "86967e67381b01181ae3b3ad28d46011140dcc5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2018-01-29T08:36:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-01T14:32:34.000Z", "max_forks_repo_path": "src/demo_PolynomialRegression.jl", "max_forks_repo_name": "triwave33/BayesBook", "max_forks_repo_head_hexsha": "86967e67381b01181ae3b3ad28d46011140dcc5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2017-10-20T00:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T20:34:22.000Z", "avg_line_length": 24.5730337079, "max_line_length": 88, "alphanum_fraction": 0.5208047554, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7712569026460953}}
{"text": "\"\"\"\nStore the singular value decomposition of a matrix:\n\n    A = UΣV'\n\n\"\"\"\nstruct LowRankMatrix{T} <: AbstractMatrix{T}\n    U::Matrix{T}\n    Σ::Matrix{T}\n    V::Matrix{T}\nend\n\nsize(L::LowRankMatrix) = size(L.U, 1), size(L.V, 1)\nrank(L::LowRankMatrix) = size(L.Σ,1)\nnorm(L::LowRankMatrix) = first(L.Σ)\ncond(L::LowRankMatrix) = ifelse(rank(L) < minimum(size(L)), Inf, first(L.Σ)/last(L.Σ))\n\nistriu(L::LowRankMatrix) = false\nistril(L::LowRankMatrix) = false\nissymmetric(L::LowRankMatrix) = false\nishermitian(L::LowRankMatrix) = false\n\nfunction getindex(L::LowRankMatrix{T},i::Integer,j::Integer) where T\n    ret = zero(T)\n    U, Σ, V, r = L.U, L.Σ, L.V, rank(L)\n    # for k = r:-1:1\n    #     ret += U[i,k]*Σ[k,k]*V[j,k]\n    # end\n    U[i,:]'*Σ*V[j,:]\n\n    # ret\nend\n", "meta": {"hexsha": "1fcdeebcb9a5f912333549552e0fc00c1db49f61", "size": 764, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LowRankMatrix.jl", "max_stars_repo_name": "kuanxu/AlmostBandedMatrices.jl", "max_stars_repo_head_hexsha": "5d954bb50cc3c23f9e50556972aa5a55f0961b04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LowRankMatrix.jl", "max_issues_repo_name": "kuanxu/AlmostBandedMatrices.jl", "max_issues_repo_head_hexsha": "5d954bb50cc3c23f9e50556972aa5a55f0961b04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-24T20:10:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-24T20:10:23.000Z", "max_forks_repo_path": "src/LowRankMatrix.jl", "max_forks_repo_name": "kuanxu/AlmostBandedMatrices.jl", "max_forks_repo_head_hexsha": "5d954bb50cc3c23f9e50556972aa5a55f0961b04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1515151515, "max_line_length": 86, "alphanum_fraction": 0.6112565445, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475683211323, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7712568898456016}}
{"text": "# Counts the number of local maxima.\r\nfunction count_maxima(histogram::AbstractArray)\r\n    maxima_count = 0\r\n    valid_range = firstindex(histogram)+1:lastindex(histogram)-1\r\n    for i in valid_range\r\n        if  histogram[i-1] < histogram[i] > histogram[i+1]\r\n            maxima_count += 1\r\n        end\r\n    end\r\n    return maxima_count\r\nend\r\n\r\nfunction find_maxima_indices(histogram::AbstractArray)\r\n    indices = Array{Int, 1}()\r\n    t = 0\r\n    valid_range = firstindex(histogram)+1:lastindex(histogram)-1\r\n    for i in valid_range\r\n        if histogram[i-1] < histogram[i] > histogram[i+1]\r\n            push!(indices, i)\r\n        end\r\n    end\r\n    return indices\r\nend\r\n\r\nfunction smooth_histogram(histogram::AbstractArray, max_iterations::Int)\r\n    histogram_local = convert.(Float32, histogram)\r\n    maxima_count = count_maxima(histogram)\r\n    smooth_histogram = similar(histogram_local)\r\n    lb = firstindex(histogram_local)\r\n    ub = lastindex(histogram_local)\r\n    iterations = 0\r\n    # Smooth histogram until at most two peaks remain or max_iterations is reached.\r\n    while maxima_count > 2 && iterations < max_iterations\r\n        smooth_histogram[lb] = (2*histogram_local[lb] + histogram_local[lb+1]) / 3\r\n        smooth_histogram[ub] = (2*histogram_local[ub] + histogram_local[ub-1]) / 3\r\n        for i in lb+1:ub-1\r\n            smooth_histogram[i] = (histogram_local[i-1] + histogram_local[i] + histogram_local[i+1]) / 3\r\n        end\r\n        maxima_count = count_maxima(smooth_histogram)\r\n        copyto!(histogram_local, smooth_histogram)\r\n        iterations += 1\r\n    end\r\n    return histogram_local\r\nend\r\n", "meta": {"hexsha": "7eda3737364ea48a9049b984c4547ccd77e55768", "size": 1622, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/common.jl", "max_stars_repo_name": "betttris13/HistogramThresholding.jl", "max_stars_repo_head_hexsha": "e751b92dad5add53601f7ce2c5d58921f104c6d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-01-07T18:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-10T09:10:19.000Z", "max_issues_repo_path": "src/common.jl", "max_issues_repo_name": "betttris13/HistogramThresholding.jl", "max_issues_repo_head_hexsha": "e751b92dad5add53601f7ce2c5d58921f104c6d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2019-01-07T05:43:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-24T04:03:55.000Z", "max_forks_repo_path": "src/common.jl", "max_forks_repo_name": "betttris13/HistogramThresholding.jl", "max_forks_repo_head_hexsha": "e751b92dad5add53601f7ce2c5d58921f104c6d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-01-05T02:39:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T20:13:12.000Z", "avg_line_length": 36.0444444444, "max_line_length": 105, "alphanum_fraction": 0.6639950678, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213880824791, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7712376475770029}}
{"text": "# This file contains additional custom distibutions using the interface of Distibutions.jl\n\n\"\"\"\n    Sine()\n\nA custom univariate distribution.\nThe pdf is a sine function defined between 0 and π.\nThis is a common prior distribution used when fitting orbits to astrometry.\n\nThe full Distributions.jl interface is not yet defined for this distribution,\nbut the following methods work:\npdf, logpdf, minimum, maximum, insupport, mean, var, cdf, quantile\n\"\"\"\nstruct Sine <: ContinuousUnivariateDistribution end\nexport Sine\n\nfunction Distributions.pdf(d::Sine, x::Real)\n    if 0 < x < π\n        return sin(x)/2\n    else\n        return 0\n    end\nend\nfunction Distributions.logpdf(d::Sine, x::Real)\n    if 0 < x < π\n        return log(sin(x)/2)\n    else\n        return -Inf\n    end\nend\nDistributions.minimum(d::Sine) = 0\nDistributions.maximum(d::Sine) = π\nDistributions.insupport(d::Sine, x::Real) = 0 < x < π\nDistributions.mean(d::Sine) = π/2\n\n# See https://stats.libretexts.org/Bookshelves/Probability_Theory/Probability_Mathematical_Statistics_and_Stochastic_Processes_(Siegrist)/05%3A_Special_Distributions/5.27%3A_The_Sine_Distribution\nDistributions.var(d::Sine) = 1/4 - 2/pi^2 \nDistributions.cdf(d::Sine, x::Real)= 1/2*(1-cos(x))\nDistributions.quantile(d::Sine, p::Real) = acos(1-2p)\n", "meta": {"hexsha": "b59c589f4a6dff3e933ce3dbf0e41610c74d617b", "size": 1280, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distributions.jl", "max_stars_repo_name": "sefffal/DirectDetections.jl", "max_stars_repo_head_hexsha": "c72ffe3b4664154131de1b2bfb7f4c233138b03c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distributions.jl", "max_issues_repo_name": "sefffal/DirectDetections.jl", "max_issues_repo_head_hexsha": "c72ffe3b4664154131de1b2bfb7f4c233138b03c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2022-02-24T18:37:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T16:49:31.000Z", "max_forks_repo_path": "src/distributions.jl", "max_forks_repo_name": "sefffal/DirectDetections.jl", "max_forks_repo_head_hexsha": "c72ffe3b4664154131de1b2bfb7f4c233138b03c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0, "max_line_length": 195, "alphanum_fraction": 0.73203125, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7712376445742557}}
{"text": "## This is to test the first derivative of sin\nusing MAT,Plots,LinearAlgebra\nconst USE_GPU=false;  # Use GPU? If this is set false, then no GPU needs to be available\nusing ParallelStencil\nusing ParallelStencil.FiniteDifferences1D\n@static if USE_GPU\n    @init_parallel_stencil(CUDA,Float64,3);\nelse\n    @init_parallel_stencil(Threads,Float64,3);\nend\ndx=.001;\nx=0:dx:6*pi;\nnx=length(x);\ny=cos.(x);\n## analytical expression of d^2y/dx^2\nd2y_dx2=-cos.(x);\n## d^2y/dx^2 2nd-order accuracy\n@parallel function Dx_inn_2nd_order_accuracy(in,out,dx)\n    @inn(out)=@d_1(in)/dx;\n    return nothing\nend\n\n@parallel_indices (iy) function u_1_plus_2nd_order_accuracy(in,out)\nout[2:end-1]=in[:];\nreturn nothing\nend\n\n@parallel_indices (iy) function u_1_minus_2nd_order_accuracy(in,out)\nout[1:end-2]=in[:];\nreturn nothing\nend\n\ndtt=@zeros(nx-2,);\ntt=@zeros(nx,);\nd2y_dx2_2nd_order_accuracy=@zeros(nx,);\n\n@parallel Dx_inn_2nd_order_accuracy(y,dtt,dx);\n@parallel (1:1) u_1_minus_2nd_order_accuracy(dtt,tt);\n@parallel Dx_inn_2nd_order_accuracy(tt,dtt,dx);\n@parallel (1:1) u_1_plus_2nd_order_accuracy(dtt,d2y_dx2_2nd_order_accuracy);\n## d^2y/dx^2 8th-order accuracy\n@parallel function Dx_inn_8th_order_accuracy(in,out,dx)\n    @inn(out)=@d_8(in)/dx;\n    return nothing\nend\n\n@parallel_indices (iy) function u_1_plus_8th_order_accuracy(in,out)\nout[4:end-2]=in[:];\nreturn nothing\nend\n\n@parallel_indices (iy) function u_1_minus_8th_order_accuracy(in,out)\nout[3:end-3]=in[:];\nreturn nothing\nend\n\ndtt=@zeros(nx-5,);\ntt=@zeros(nx,);\nd2y_dx2_8th_order_accuracy=@zeros(nx,);\n\n@parallel Dx_inn_8th_order_accuracy(y,dtt,dx);\n@parallel (1:1) u_1_minus_8th_order_accuracy(dtt,tt);\n@parallel Dx_inn_8th_order_accuracy(tt,dtt,dx);\n@parallel (1:1) u_1_plus_8th_order_accuracy(dtt,d2y_dx2_8th_order_accuracy);\n## d^2y/dx^2 12th-order accuracy\n@parallel function Dx_inn_12th_order_accuracy(in,out,dx)\n    @inn(out)=@d_12(in)/dx;\n    return nothing\nend\n\n@parallel_indices (iy) function u_1_plus_12th_order_accuracy(in,out)\nout[6:end-4]=in[:];\nreturn nothing\nend\n\n@parallel_indices (iy) function u_1_minus_12th_order_accuracy(in,out)\nout[5:end-5]=in[:];\nreturn nothing\nend\n\ndtt=@zeros(nx-9,);\ntt=@zeros(nx,);\nd2y_dx2_12th_order_accuracy=@zeros(nx,);\n\n@parallel Dx_inn_12th_order_accuracy(y,dtt,dx);\n@parallel (1:1) u_1_minus_12th_order_accuracy(dtt,tt);\n@parallel Dx_inn_12th_order_accuracy(tt,dtt,dx);\n@parallel (1:1) u_1_plus_12th_order_accuracy(dtt,d2y_dx2_12th_order_accuracy);\n## plot derivatives\nIND=30:nx-30;\n\nplot(x[IND],d2y_dx2[IND],label=\"analytical\",color=\"red\",title=\"d^2y/dx^2\",lw=3);\nplot!(x[IND],d2y_dx2_2nd_order_accuracy[IND],label=\"2nd-order\",color=\"blue\",lw=3)\nplot!(x[IND],d2y_dx2_8th_order_accuracy[IND],label=\"8th-order\",color=\"green\",lw=3)\nplot!(x[IND],d2y_dx2_12th_order_accuracy[IND],label=\"12th-order\",color=\"yellow\",lw=3)\n## plot error\nplot(x[IND],d2y_dx2_2nd_order_accuracy[IND]-d2y_dx2[IND],label=\"2nd-order\",color=\"blue\",lw=3);\nplot!(x[IND],d2y_dx2_8th_order_accuracy[IND]-d2y_dx2[IND],label=\"8th-order\",color=\"green\",lw=3);\nplot!(x[IND],d2y_dx2_12th_order_accuracy[IND]-d2y_dx2[IND],label=\"12th-order\",color=\"yellow\",lw=3)\n## norm error\ne1=norm(d2y_dx2_2nd_order_accuracy[IND]-d2y_dx2[IND],2)\ne2=norm(d2y_dx2_8th_order_accuracy[IND]-d2y_dx2[IND],2)\ne3=norm(d2y_dx2_12th_order_accuracy[IND]-d2y_dx2[IND],2)\n", "meta": {"hexsha": "7f1eb3f9c05d663eade3a6212f8c22a908d4af25", "size": 3292, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/test_1D.jl", "max_stars_repo_name": "deconvolution/ParallelStencil.jl", "max_stars_repo_head_hexsha": "58dddae5ba46053fa4a942e2a271422d97f6013e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/test_1D.jl", "max_issues_repo_name": "deconvolution/ParallelStencil.jl", "max_issues_repo_head_hexsha": "58dddae5ba46053fa4a942e2a271422d97f6013e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/test_1D.jl", "max_forks_repo_name": "deconvolution/ParallelStencil.jl", "max_forks_repo_head_hexsha": "58dddae5ba46053fa4a942e2a271422d97f6013e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6538461538, "max_line_length": 98, "alphanum_fraction": 0.7679222357, "num_tokens": 1192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8577681086260461, "lm_q1q2_score": 0.7712376385687607}}
{"text": "using LinearAlgebra\n\n\"\"\"\n    lattice(s, N, ispbc=true)\n\nCreate a adjacency matrix of lattice `s` with size ``N``.\nThe periodic boundary condition is imposed by default.\nAdmissible values for `s` are:\n\n| `s`                      | graph type                       |\n| :------------------------|:---------------------------------|\n| :chain                   | A one dimensional chain.         |\n| :square                  | A two dimensional square lattice.|\n\n# Examples\n```julia-repl\njulia> lattice(:chain, 3)\n[0 1 1\n 1 0 1\n 1 1 0]\n\njulia> lattice(:square, 4, ispbc=false)\n[0 1 1 0\n 1 0 0 1\n 1 0 0 1\n 0 1 1 0]\n```\n\"\"\"\nfunction lattice(s::Symbol, N::Int; ispbc=true)\n    graphmap = Dict(\n        :chain => chain_graph,\n        :square => square_graph,\n    )\n\n    if (s in keys(graphmap))\n        return graphmap[s](N, ispbc)\n    end\n    throw(ArgumentError(\"$s is not a valid graph\"))\nend\n\n\n\"\"\"\n    chain_graph(N, ispbc)\n\nAn adjacency matrix of a chain graph with length ``N``.\n\n# Examples\n```julia-repl\njulia> chain_graph(3)\n[0 1 1\n 1 0 1\n 1 1 0]\n```\n\"\"\"\nfunction chain_graph(N, ispbc)\n    @assert N > 0 \"N must be larger than 1.\"\n    if N == 1\n        return [0]\n    end\n    A = Matrix(SymTridiagonal(zeros(Int, N), ones(Int, N-1)))\n    if ispbc\n        A[1, N] += 1\n        A[N, 1] += 1\n    end\n    A\nend\n\n\n\"\"\"\n    issquare(N)\n\nCheck whether the number is perfect square or not.\n\n# Examples\n```julia-repl\njulia> issquare(2)\nfalse\n\njulia> issquare(4)\ntrue\n```\n\"\"\"\nfunction issquare(N)\n    isqrt(N)^2 == N\nend\n\n\n\"\"\"\n    square_graph(N, ispbc)\n\nAn adjacency matrix of a square lattice whose number of vertices is ``N``.\n\n# Examples\n```julia-repl\njulia> square_graph(4)\n[0 2 2 0\n 2 0 0 2\n 2 0 0 2\n 0 2 2 0]\n\njulia> square_graph(4, ispbc=false)\n[0 1 1 0\n 1 0 0 1\n 1 0 0 1\n 0 1 1 0]\n```\n\"\"\"\nfunction square_graph(N, ispbc)\n    @assert N > 0 \"N must be larger than 1.\"\n    @assert issquare(N) \"N must be a perfect square number.\"\n    L = isqrt(N)\n    if N == 1\n        return [0]\n    end\n\n    A = transpose(reshape(1:N, L,L))\n    h = [(A[CartesianIndex(i,j)], A[CartesianIndex(i,pbc(j+1,L))]) for i in 1:L for j in 1:L]\n    v = [(A[CartesianIndex(i,j)], A[CartesianIndex(pbc(i+1,L),j)]) for i in 1:L for j in 1:L]\n    bonds = vcat(v, h)\n\n    h = [(A[CartesianIndex(i,1)], A[CartesianIndex(i,L)]) for i in 1:L]\n    v = [(A[CartesianIndex(1,j)], A[CartesianIndex(L,j)]) for j in 1:L]\n    pbcbonds = vcat(v, h)\n\n    Res = zeros(Int, N, N)\n    for b in bonds\n        Res[b[1], b[2]] += 1\n        Res[b[2], b[1]] += 1\n    end\n    if !ispbc\n        for b in pbcbonds\n            Res[b[1], b[2]] -= 1\n            Res[b[2], b[1]] -= 1\n        end\n    end\n    Res\nend\n", "meta": {"hexsha": "5e47aa6630cdadc700770808fb67f15de1a5154e", "size": 2653, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lattice.jl", "max_stars_repo_name": "Shoichiro-Tsutsui/QuantumSpin.jl", "max_stars_repo_head_hexsha": "853bbd630dbd88e69297550ce473c13d9ad1ffa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lattice.jl", "max_issues_repo_name": "Shoichiro-Tsutsui/QuantumSpin.jl", "max_issues_repo_head_hexsha": "853bbd630dbd88e69297550ce473c13d9ad1ffa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lattice.jl", "max_forks_repo_name": "Shoichiro-Tsutsui/QuantumSpin.jl", "max_forks_repo_head_hexsha": "853bbd630dbd88e69297550ce473c13d9ad1ffa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2246376812, "max_line_length": 93, "alphanum_fraction": 0.5442894836, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7712045629601528}}
{"text": "\"\"\"\n    circmean(x)\n\nCompute the circular mean of `x` in radians.\n\n[1] N. I. Fisher, Statistical Analysis of Circular Data. Cambridge University Press, 1993.\n\"\"\"\nfunction circmean(x)\n    s = mean(sin, x)\n    c = mean(cos, x)\n\n    atan(s, c)\nend\n\n\"\"\"\n    circmeand(x)\n\nCompute the circular mean of `x` in degrees.\n\n[1] N. I. Fisher, Statistical Analysis of Circular Data. Cambridge University Press, 1993.\n\"\"\"\nfunction circmeand(x)\n    s = mean(sind, x)\n    c = mean(cosd, x)\n\n    atand(s, c)\nend\n\n\"\"\"\n    circstd(x)\n\nCompute the circular standard deviation of `x` in radians.\n\n[1] N. I. Fisher, Statistical Analysis of Circular Data. Cambridge University Press, 1993.\n\"\"\"\nfunction circstd(x)\n    s = mean(sin, x)\n    c = mean(cos, x)\n\n    sqrt(-2*log(hypot(c, s)))\nend\n\n\"\"\"\n    circstdd(x)\n\nCompute the circular standard deviation of `x` in degrees.\n\n[1] N. I. Fisher, Statistical Analysis of Circular Data. Cambridge University Press, 1993.\n\"\"\"\nfunction circstdd(x)\n    s = mean(sind, x)\n    c = mean(cosd, x)\n\n    rad2deg(sqrt(-2*log(hypot(c, s))))\nend\n\n\"\"\"\n    mean_std_range(x, events) -> Tuple(avg, std)\n\nFind the average range and range variability of `x` for the set of all intervals given by\n`events`.\n\"\"\"\nfunction mean_std_range(x, events::AbstractVector{Int})\n    mi, mx = intervalextrema(x, events)\n    roms = mx - mi\n\n    return mean(roms), std(roms)\nend\n\n\"\"\"\n    avgextrema(x, events) -> Tuple(min, max)\n\nFind the average minima and maxima for the set of all intervals given by `events`.\n\"\"\"\nfunction avgextrema(x, events::AbstractVector{Int})\n    mi, mx = intervalextrema(x, events)\n\n    return mean(mi), mean(mx)\nend\n\nfunction intervalextrema(x::AbstractVector{T}, events) where T\n    rgs = intervals(events; endincluded=false)\n    mi = Vector{T}(undef, length(rgs))\n    mx = Vector{T}(undef, length(rgs))\n\n    intervalextrema!(mi, mx, x, rgs)\nend\n\nfunction intervalextrema!(mi, mx, x, rgs)\n    @inbounds for (i, rg) in enumerate(rgs)\n        mi[i], mx[i] = extrema(view(x, rg))\n    end\n\n    return mi, mx\nend\n\n", "meta": {"hexsha": "e38767bd66305a76d878ca5f3a87feffd1c0e734", "size": 2026, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/reductions.jl", "max_stars_repo_name": "halleysfifthinc/Biomechanics.jl", "max_stars_repo_head_hexsha": "963bdd17f367f121263fdd6f29ca1829ea9c28c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-07T14:39:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-07T14:39:47.000Z", "max_issues_repo_path": "src/reductions.jl", "max_issues_repo_name": "halleysfifthinc/Biomechanics.jl", "max_issues_repo_head_hexsha": "963bdd17f367f121263fdd6f29ca1829ea9c28c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/reductions.jl", "max_forks_repo_name": "halleysfifthinc/Biomechanics.jl", "max_forks_repo_head_hexsha": "963bdd17f367f121263fdd6f29ca1829ea9c28c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8865979381, "max_line_length": 90, "alphanum_fraction": 0.6569595262, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7712045625185706}}
{"text": "\"\"\"get all groups\"\"\"\nfunction getgrp(node_memory::Vector{Dict{Int,Int}})\n    groups = Dict{Int,Vector{Int}}()\n    for i=1:length(node_memory)\n        for k in keys(node_memory[i])\n            if haskey(groups, k)\n                push!(groups[k], i)\n            else\n                groups[k] = [i]\n            end\n        end\n    end\n    collect(values(groups))\nend\n\n\"\"\"\ncalculate the entropy of a probility distribution\n\"\"\"\nfunction entropy(P::Vector{Float64})\n    H = 0.0\n    for i=1:length(P)\n        # treat 0*log(0) as being equal to zero\n        H += P[i] > 0.0 ? P[i]*log(P[i]) : 0.0\n    end\n    -H > 0 ? -H : 0.0\nend\n\n\"\"\"read groups from file\"\"\"\nfunction readgrp(filename)\n    groups = Vector{Int}[]\n    f = open(filename, \"r\")\n    for ll in eachline(f)\n        push!(groups, [parse(Int, i) for i in split(chomp(ll))])\n    end\n    groups\nend\n\n\"\"\"write groups to file\"\"\"\nfunction writegrp(filename, groups::Vector{Vector{Int}})\n    f = open(filename, \"w\")\n    for i=1:length(groups)\n        for j=1:length(groups[i])-1\n            print(f, groups[i][j],' ')\n        end\n        print(f, groups[i][end],'\\n')\n    end\n    close(f)\nend\n\n\"\"\"read membership from file\"\"\"\nfunction readmsp(filename)\n    membership = Dict{Int, Vector{Int}}()\n    f = open(filename, \"r\")\n    for ll in eachline(f)\n        entries = [parse(Int, i) for i in split(chomp(ll))]\n        membership[entries[1]] = entries[2:end]\n    end\n    membership\nend\n\n\"\"\"write membership to file\"\"\"\nfunction writemsp(filename, membership::Dict{Int, Vector{Int}})\n    f = open(filename, \"w\")\n    for k in sort(collect(keys(membership)))\n        print(f, k, '\\t')\n        for j=1:length(membership[k])-1\n            print(f, membership[k][j], ' ')\n        end\n        print(f, membership[k][end], '\\n')\n    end\n    close(f)\nend\n\n\"\"\"transform membership to groups\"\"\"\nfunction msp2grp(membership::Dict{Int, Vector{Int}})\n    groups = Dict{Int, Vector{Int}}()\n    for (k,v) in membership\n        for i in v\n            if haskey(groups, i)\n                push!(groups[i], k)\n            else\n                groups[i] = [k]\n            end\n        end\n    end\n    collect(values(groups))\nend\n\n\"\"\"transform groups to membership\"\"\"\nfunction grp2msp(groups::Vector{Vector{Int}})\n    membership = Dict{Int, Vector{Int}}()\n    for i=1:length(groups)\n        for j=1:length(groups[i])\n            if haskey(membership, groups[i][j])\n                push!(membership[groups[i][j]], i)\n            else\n                membership[groups[i][j]] = [i]\n            end\n        end\n    end\n    membership\nend\n", "meta": {"hexsha": "c33552e492153916efe26bed91cd09b466481621", "size": 2557, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "afternone/SLPA.jl", "max_stars_repo_head_hexsha": "af207d7d851172a82e0f35ab4459c2f2d12af5da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "afternone/SLPA.jl", "max_issues_repo_head_hexsha": "af207d7d851172a82e0f35ab4459c2f2d12af5da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "afternone/SLPA.jl", "max_forks_repo_head_hexsha": "af207d7d851172a82e0f35ab4459c2f2d12af5da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8252427184, "max_line_length": 64, "alphanum_fraction": 0.5494720375, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7711892435932424}}
{"text": "@doc raw\"\"\"\n    PolynomialKernel([a=1 [,c=1 [,d=3]]])\n\nThe polynomial kernel is a Mercer kernel given by:\n\n```\n    κ(x,y) = (a⋅xᵀy + c)ᵈ   α > 0, c ≧ 0, d ∈ ℤ⁺\n```\n\n# Examples\n\n```jldoctest; setup = :(using MLKernels)\njulia> PolynomialKernel(2.0f0)\nPolynomialKernel{Float32}(2.0,1.0,3)\n\njulia> PolynomialKernel(2.0f0, 2.0)\nPolynomialKernel{Float64}(2.0,2.0,3)\n\njulia> PolynomialKernel(2.0f0, 2.0, 2)\nPolynomialKernel{Float64}(2.0,2.0,2)\n```\n\"\"\"\nstruct PolynomialKernel{T<:AbstractFloat} <: MercerKernel{T}\n    a::T\n    c::T\n    d::T\n    function PolynomialKernel{T}(\n            a::Real=T(1),\n            c::Real=T(1),\n            d::Real=T(3)\n        ) where {T<:AbstractFloat}\n        @check_args(PolynomialKernel, a, a >  zero(a), \"a > 0\")\n        @check_args(PolynomialKernel, c, c >= zero(c), \"c ≧ 0\")\n        @check_args(PolynomialKernel, d, d >= one(d) && d == trunc(d), \"d ∈ ℤ₊\")\n        return new{T}(a, c, d)\n    end\nend\n\nfunction PolynomialKernel(\n        a::T₁=1.0,\n        c::T₂=T₁(1),\n        d::T₃=convert(promote_float(T₁,T₂), 3)\n    ) where {T₁<:Real,T₂<:Real,T₃<:Real}\n    T = promote_float(T₁,T₂,T₃)\n    return PolynomialKernel{T}(a, c, d)\nend\n\n@inline basefunction(::PolynomialKernel) = ScalarProduct()\n\n@inline function kappa(κ::PolynomialKernel{T}, xᵀy::T) where {T}\n    return (κ.a*xᵀy + κ.c)^(κ.d)\nend\n\nfunction convert(::Type{K}, κ::PolynomialKernel) where {K>:PolynomialKernel{T}} where T\n    return PolynomialKernel{T}(κ.a, κ.c, κ.d)\nend", "meta": {"hexsha": "530154a686b17b3f971956b48142c5b0dda8dc54", "size": 1464, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernelfunctions/mercer/polynomial.jl", "max_stars_repo_name": "trthatcher/Kernels.jl", "max_stars_repo_head_hexsha": "c95971efc89b76f05e39cbdf5213507fe4351d63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85, "max_stars_repo_stars_event_min_datetime": "2015-04-21T16:40:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T00:25:21.000Z", "max_issues_repo_path": "src/kernelfunctions/mercer/polynomial.jl", "max_issues_repo_name": "trthatcher/Kernels.jl", "max_issues_repo_head_hexsha": "c95971efc89b76f05e39cbdf5213507fe4351d63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 81, "max_issues_repo_issues_event_min_datetime": "2015-04-22T16:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-03T14:32:44.000Z", "max_forks_repo_path": "src/kernelfunctions/mercer/polynomial.jl", "max_forks_repo_name": "trthatcher/Kernels.jl", "max_forks_repo_head_hexsha": "c95971efc89b76f05e39cbdf5213507fe4351d63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2015-04-22T15:59:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-21T19:02:01.000Z", "avg_line_length": 26.1428571429, "max_line_length": 87, "alphanum_fraction": 0.6004098361, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7711892362907574}}
{"text": "  # Function to be minimized\n  f(x::Vector{Float64}) = x[1]^2 + x[2]^2\n\n  # Minimizer by random search\n  function randomsearch(f,ntrial)\n    fbest = 1.e30\n    x = Vector{Float64}(undef,2)\n    xbest = Vector{Float64}(undef,2)\n    xbest[1] = -10. + 20. * rand()\n    xbest[2] = -10. + 20. * rand()\n    for i in 1:ntrial       \n      x[1] = xbest[1] + 1.e-3*(-1.e0 + 2.e0 * rand())\n      x[2] = xbest[2] + 1.e-3*(-1.e0 + 2.e0 * rand())\n      fx = f(x)\n      if fx < fbest\n        fbest = fx\n        xbest[1] = x[1]\n        xbest[2] = x[2]\n        println(i,\" New best point: \", x,\" f(x) = \", fx)\n      end\n    end\n    println(\" Best point found: \",xbest,\" f = \", fbest)\n  end\n", "meta": {"hexsha": "396d464011065e3fbbd9c65cf32e43b419c3f14c", "size": 672, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MINIMIZATIONS/randomsearch.jl", "max_stars_repo_name": "viniciuspiccoli/simulationQP934", "max_stars_repo_head_hexsha": "1187384bddb098dba854d01db66d82891f6d6dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MINIMIZATIONS/randomsearch.jl", "max_issues_repo_name": "viniciuspiccoli/simulationQP934", "max_issues_repo_head_hexsha": "1187384bddb098dba854d01db66d82891f6d6dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MINIMIZATIONS/randomsearch.jl", "max_forks_repo_name": "viniciuspiccoli/simulationQP934", "max_forks_repo_head_hexsha": "1187384bddb098dba854d01db66d82891f6d6dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0, "max_line_length": 56, "alphanum_fraction": 0.4910714286, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7711840313058248}}
{"text": "# Slope Limiters\n# note that r = (u - ul)/(ur - u)\n# and we set a = u - ul, b = ur - u to define the limiters\n\nfunction minmod(a,b,c)\n  if (a > 0 && b > 0 && c > 0)\n    min(a,b,c)\n  elseif (a < 0 && b < 0 && c < 0)\n    max(a,b,c)\n  else\n    zero(a)\n  end\nend\n\nstruct GeneralizedMinmodLimiter <: AbstractSlopeLimiter\n    θ::Float64\nend\n\nGeneralizedMinmodLimiter(;θ=1.0) = GeneralizedMinmodLimiter(θ)\n(limiter::GeneralizedMinmodLimiter)(a,b) =minmod(limiter.θ*a,0.5*(a+b),limiter.θ*b)\n\nfunction minmod(a,b)\n  0.5*(sign(a)+sign(b))*min(abs(a),abs(b))\nend\n\nstruct MinmodLimiter <: AbstractSlopeLimiter end\n(::MinmodLimiter)(a,b) = minmod(a,b)\n\nstruct OsherLimiter <: AbstractSlopeLimiter\n    β::Float64\nend\nOsherLimiter(;β=1.0) = OsherLimiter(β)\n(limiter::OsherLimiter)(a,b) = max(zero(a),min(a,limiter.β*b))\n\nstruct SuperbeeLimiter <: AbstractSlopeLimiter end\n(::SuperbeeLimiter)(a,b) = max(zero(a),min(2*a,b),min(a,2*b))\n\n\"\"\"\nfunction compute_slopes(u, mesh, θ, M, ::Type{Val{true}})\n  Estimate slopes of the discretization of function u,\n      using a generalized minmod limiter\n  inputs:\n  `u` discrete approx of function u\n  'nonscalar' bool\n  `θ` parameter of generalized minmod limiter\n  `mesh` problem mesh\n  `Type{Val}` bool to choose threaded version\n\"\"\"\nfunction compute_slopes(u::AbstractArray, mesh::AbstractFVMesh, slopeLimiter::AbstractSlopeLimiter, nonscalar::Bool, ::Type{Val{true}})\n  ∇u = similar(u)\n  Threads.@threads for j in cell_indices(mesh)\n      inner_slopes_loop!(∇u,j,u,mesh,slopeLimiter,nonscalar)\n  end\n  ∇u\nend\n\nfunction compute_slopes(u::AbstractArray, mesh::AbstractFVMesh, slopeLimiter::AbstractSlopeLimiter, nonscalar::Bool, ::Type{Val{false}})\n  ∇u = similar(u)\n  for j in cell_indices(mesh)\n      inner_slopes_loop!(∇u,j,u,mesh,slopeLimiter,nonscalar)\n  end\n  ∇u\nend\n\nfunction inner_slopes_loop!(∇u,j,u,mesh,slopeLimiter::AbstractSlopeLimiter,nonscalar)\n  ul = cellval_at_left(j,u,mesh)\n  ur = cellval_at_right(j+1,u,mesh)\n  if nonscalar\n    @inbounds for i = 1:size(u,1)\n      ∇u[i,j] = slopeLimiter(u[i,j]-ul[i], ur[i]-u[i,j])\n    end\n  else\n    ∇u[j] = slopeLimiter(u[j]-ul, ur-u[j])\n  end\nend", "meta": {"hexsha": "4aa7f466d8f6d174edcc71d0c7d000669357b25c", "size": 2129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/limiters.jl", "max_stars_repo_name": "Paulms/ConservationLawsDiffEq.jl", "max_stars_repo_head_hexsha": "9b7e5f13865a65a0d77614eae508044d0528c9a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-07-10T00:00:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T15:45:29.000Z", "max_issues_repo_path": "src/limiters.jl", "max_issues_repo_name": "jamesamiller/ConservationLawsDiffEq.jl", "max_issues_repo_head_hexsha": "9b7e5f13865a65a0d77614eae508044d0528c9a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2018-06-01T15:01:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T08:08:21.000Z", "max_forks_repo_path": "src/limiters.jl", "max_forks_repo_name": "jamesamiller/ConservationLawsDiffEq.jl", "max_forks_repo_head_hexsha": "9b7e5f13865a65a0d77614eae508044d0528c9a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-08-02T13:11:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T22:21:30.000Z", "avg_line_length": 28.3866666667, "max_line_length": 136, "alphanum_fraction": 0.6885861907, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7711840295370282}}
{"text": "\n#=\n\nFilename: asset_pricing.jl\n\n@authors: Spencer Lyon, Tom Sargent, John Stachurski\n\nComputes asset prices with a Lucas style discount factor when the endowment\nobeys geometric growth driven by a finite state Markov chain.  That is,\n\n.. math::\n    d_{t+1} = g(X_{t+1}) d_t\n\nwhere \n\n    * :math:`\\{X_t\\}` is a finite Markov chain with transition matrix P.\n\n    * :math:`g` is a given positive-valued function\n\nReferences\n----------\n\n    http://quant-econ.net/py/markov_asset.html\n\n=#\n\nusing QuantEcon\n\n# A default Markov chain for the state process\nrho = 0.9\nsigma = 0.02\nn = 25  \ndefault_mc = tauchen(n, rho, sigma)\n\ntype AssetPriceModel\n    beta :: Float64    # Discount factor\n    gamma :: Float64   # Coefficient of risk aversion\n    mc :: MarkovChain  # State process\n    n :: Int           # Number of states\n    g :: Function      # Function mapping states into growth rates\nend\n\nfunction AssetPriceModel(;beta=0.96, gamma=2.0, mc=default_mc, g=exp)\n    n = size(mc.p)[1]\n    return AssetPriceModel(beta, gamma, mc, n, g) \nend\n\n\n\"\"\"\nStability test for a given matrix Q.\n\"\"\"\nfunction test_stability(ap::AssetPriceModel, Q::Matrix)\n    sr = maximum(abs(eigvals(Q)))\n    if sr >= 1 / ap.beta\n        msg = \"Spectral radius condition failed with radius = $sr\"\n        throw(ArgumentError(msg))\n    end\nend\n\n\n\"\"\"\nComputes the price-dividend ratio of the Lucas tree.\n\n\"\"\"\nfunction tree_price(ap::AssetPriceModel)\n    # == Simplify names, set up matrices  == #\n    beta, gamma, P, y = ap.beta, ap.gamma, ap.mc.p, ap.mc.state_values\n    y = reshape(y, 1, ap.n)\n    J = P .* ap.g(y).^(1 - gamma)\n\n    # == Make sure that a unique solution exists == #\n    test_stability(ap, J)\n\n    # == Compute v == #\n    I = eye(ap.n)\n    Ones = ones(ap.n)\n    v = (I - beta * J) \\ (beta * J * Ones)\n\n    return v\nend\n\n\n\"\"\"\nComputes price of a consol bond with payoff zeta\n\n\"\"\"\nfunction consol_price(ap::AssetPriceModel, zeta::Float64)\n    # == Simplify names, set up matrices  == #\n    beta, gamma, P, y = ap.beta, ap.gamma, ap.mc.p, ap.mc.state_values\n    y = reshape(y, 1, ap.n)\n    M = P .* ap.g(y).^(- gamma)\n\n    # == Make sure that a unique solution exists == #\n    test_stability(ap, M)\n\n    # == Compute price == #\n    I = eye(ap.n)\n    Ones = ones(ap.n)\n    p = (I - beta * M) \\ ( beta * zeta * M * Ones)\n\n    return p\nend\n\n\n\"\"\"\nComputes price of a perpetual call option on a consol bond.\n\n\"\"\"\nfunction call_option(ap::AssetPriceModel, zeta::Float64, p_s::Float64, epsilon=1e-7)\n\n    # == Simplify names, set up matrices  == #\n    beta, gamma, P, y = ap.beta, ap.gamma, ap.mc.p, ap.mc.state_values\n    y = reshape(y, 1, ap.n)\n    M = P .* ap.g(y).^(- gamma)\n\n    # == Make sure that a unique console price exists == #\n    test_stability(ap, M)\n\n    # == Compute option price == #\n    p = consol_price(ap, zeta)\n    w = zeros(ap.n, 1)\n    error = epsilon + 1\n    while (error > epsilon)\n        # == Maximize across columns == #\n        w_new = max(beta * M * w, p - p_s)\n        # == Find maximal difference of each component and update == #\n        error = maximum(abs(w-w_new))\n        w = w_new\n    end\n\n    return w\nend\n\n", "meta": {"hexsha": "c39f874bfb6c8b59d1ad1bb25882c274e9e143d7", "size": 3119, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "markov_asset/asset_pricing.jl", "max_stars_repo_name": "oyamad/QuantEcon.lectures.code", "max_stars_repo_head_hexsha": "a8a17e753857e0157f18337264114ce7cb23e841", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-06T04:09:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-06T04:09:21.000Z", "max_issues_repo_path": "markov_asset/asset_pricing.jl", "max_issues_repo_name": "zhouweimin-econ/QuantEcon.lectures.code", "max_issues_repo_head_hexsha": "a8a17e753857e0157f18337264114ce7cb23e841", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "markov_asset/asset_pricing.jl", "max_forks_repo_name": "zhouweimin-econ/QuantEcon.lectures.code", "max_forks_repo_head_hexsha": "a8a17e753857e0157f18337264114ce7cb23e841", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-04-21T21:41:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T22:09:19.000Z", "avg_line_length": 23.276119403, "max_line_length": 84, "alphanum_fraction": 0.6120551459, "num_tokens": 915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7711840262429355}}
{"text": "\"\"\"\n`CircStats` contains routines for investigating the statistics of circular\ndata.\n\nBy default, all input and output from routines is in radians, but in general passing\n`true` as the last argument to a routine will change this to degrees.\n\"\"\"\nmodule CircStats\n\nusing Printf\n\nimport Distributions\n\nusing StatsBase: mean\n\nexport\n    # Summary stats\n    cdist,\n    cmean,\n    cmedian,\n    cresultant,\n    cstd,\n    cvariance,\n    # Distributions\n    von_mises_cdf,\n    von_mises_pdf,\n    # Fitting/estimation\n    fit_vonMises,\n    # Hypothesis testing\n    V_test,\n    watson_U2,\n    watson_U2n\n\ninclude(\"Datasets.jl\")\nusing .Datasets\n\ninclude(\"hypothesistests.jl\")\n\n\"\"\"\n    cdist(a, b, degrees::Bool=false) -> angle\n\nReturn the angular distance from `a` to `b` (b - a) in the forward\ndirection; hence if `b` is 'behind' `a`, `distance` will be negative.\n\nAngles are confined to be the smaller possible angle, so are in the range\n[-π:π], or [-180°:180°].\n\nAngles are in radians, unless `degrees` == true.\n\"\"\"\ncdist(a, b) = mod(b - a + pi, 2π) - pi\ncdist(a, b, degrees::Bool) =\n    degrees ? rad2deg(cdist(deg2rad(a), deg2rad(b))) : cdist(a, b)\n\n\"\"\"\n    cmean(a::Array, degrees::Bool=false) -> mean\n\nReturn the mean angle from the set of angles in `a`.\n\nAngles are in radians, unless `degrees` == true.\n\"\"\"\ncmean(a) = atan(sum(sin.(a)), sum(cos.(a)))\ncmean(a, degrees::Bool) = degrees ? rad2deg(cmean(deg2rad.(a))) : cmean(a)\n\n\"\"\"\n    cmedian(a::Array, degrees::Bool=false, axial=false) -> median\n\nReturn the median angle from the set of angles `a`.\n\nAngles are in radians, unless `degrees` == true.\n\"\"\"\nfunction cmedian(a, degrees::Bool=false, axial::Bool=false)\n    medians = Vector{Float64}()\n    A = Float64.(sort(a))\n    n = length(A)\n    degrees && (A .= deg2rad.(A))\n    axial && (A .= 2A)\n    # Compute trial bisectors, which are either the points themselves or adjacent means\n    p = Array{Float64}(undef, n)\n    if iseven(n)\n        for i = 1:n\n            j = (i + 1 <= n) ? i + 1 : 1\n            p[i] = cmean([A[i], A[j]])\n        end\n    else\n        p[:] .= A[:]\n    end\n    # Try all possible diameters\n    for i = 1:n\n        # Count points on either side of diameter\n        n_plus = sum(cdist.(p[i], A) .> 0)\n        n_minus = sum(cdist.(p[i], A) .< 0)\n        if n_plus == n_minus\n            # Determine which side of circle is correct direction by counting the number\n            # within pi/2 of each of the two opposing possible medians\n            if sum(abs.(cdist.(p[i], A)) .<= pi/2) > sum(abs.(cdist.(p[i], A)) .> pi/2)\n                push!(medians, A[i])\n            else\n                push!(medians, (A[i] + 2pi)%2pi - pi)\n            end\n        end\n    end\n    # If there is more than one median, take the mean thereof (Otieno & Anderson-Cook\n    # (2003), Journal of Modern Applied Statistical Methods, 2(1), 168-176)\n    median = if length(medians) > 1\n        cmean(medians)\n    elseif length(medians) == 1\n        medians[1]\n    else\n        error(\"Zero medians found.  Are data axial but axial!=true?\")\n    end\n    degrees && (median = rad2deg(median))\n    axial && (median /= 2)\n    median\nend\n\n\"\"\"\n    cresultant(a, degrees=false) -> R\n    cresultant(a, w, degrees=false) -> Rc\n\nReturn the resultant vector length, `R`, from a set of angles, `a`.\n\nIf data are binned by binwidth `w`, an unbiased estimate of `R`, `Rc` is returned\nwhen `w` is supplied.\n\nAngles are in radians, unless `degrees` == true.\n\"\"\"\ncresultant(a, degrees::Bool=false) = degrees ?\n    sqrt(sum(sin.(deg2rad.(a)))^2 + sum(cos.(deg2rad.(a)))^2)/length(a) :\n    sqrt(sum(sin.(a))^2 + sum(cos.(a))^2)/length(a)\ncresultant(a, w::Real, degrees::Bool=false) = degrees ?\n    cresultant(a, true)*deg2rad(w)/(2sin(deg2rad(w)/2)) : cresultant(a)*w/(2sin(w/2))\n\n\"\"\"\n    cstd(a, degrees=false) -> σ\n\nReturn the standard deviation, `σ`, for a set of angles `a`.\n\nAngles are in radians, unless `degrees == true`.\n\"\"\"\ncstd(a, degrees::Bool=false) = sqrt(-2*log(cresultant(a, degrees)))\n\n\"\"\"\n    cvariance(a, degrees=false) -> σ²\n\nReturn the circular variance, `σ²`, of a set of angles `a`.\n\nAngles are in radians, unless `degrees == true`.\n\"\"\"\nfunction cvariance(a, degrees::Bool=false)\n    a_mean = cmean(a, degrees)\n    if degrees\n        1 - sum(cos.(deg2rad.(a .- a_mean)))/length(a)\n    else\n        1 - sum(cos.(a .- a_mean))/length(a)\n    end\nend\n\n\"\"\"\n    von_mises_pdf(a, µ, κ, degrees=false) -> p\n\nReturn the Von Mises probability density function at `a`, for a von Mises\ndistribution with circular mean `µ` and concentration `κ`.\n\nAngles are in radians, unless `degrees` == true.\n\"\"\"\nvon_mises_pdf(a, mu::Real, k::Real, degrees::Bool=false) = degrees ?\n                                    von_mises_pdf(deg2rad(a), deg2rad(mu), k) :\n                                    Distributions.pdf(Distributions.VonMises(mu, k), a)\n\n\"\"\"\n    von_mises_cdf(a, μ, κ, degrees=false) -> cdf\n\nReturn the von Mises cumulative distribution function at\n`a` for a distribution with mean `μ` and concentration `κ`.\n\nAngles are in radians, unless `degrees` == true.\n\"\"\"\nfunction von_mises_cdf(a, μ, κ, degrees=false)\n    degrees && (μ = deg2rad(μ))\n    d = Distributions.VonMises(μ, κ)\n    Distributions.cdf(d, degrees ? deg2rad(a) : a)\nend\n\n\"\"\"\n    fit_vonMises(θ, degrees=false; axial=false) -> μ, κ\n\nReturn the maximum-likelihood values of the mean `μ` and concentration\n`κ` for the von Mises distribution which fits the set of angles `θ`.\n\nIf `axial` is `true`, then the data are assumed to have a π (or 180°)\nambiguity.\n\nAngles are in radians, unless `degrees` == true.\n\"\"\"\nfunction fit_vonMises(θ, degrees=false; axial=false)\n    degrees && (θ = deg2rad.(θ))\n    axial && (θ = 2θ)\n    μ = cmean(θ)\n    κ = estimate_kappa_vonMises(θ, μ)\n    degrees ? (rad2deg(μ), κ) : (μ, κ)\nend\n\n\"\"\"\n    estimate_kappa_vonMises(θ, μ) -> κ\n\nReturn the maximum likelihood estimation of the concentration\nparameter `κ` for the best-fitting von Mises distribution, given\na set of angles `θ` in radians.\n\nUses the polynomial approximation given by Best and Fisher (1981).\n**N.B.** This may not be reliable when R̄ is small (e.g., < 0.7).\n\"\"\"\nfunction estimate_kappa_vonMises(θ, μ)\n    R̄ = mean(cos.(θ .- μ))\n    if 0 <= R̄ < 0.53\n        2R̄ + R̄^3 + 5R̄^5/6\n    elseif 0.53 <= R̄ < 0.85\n        -0.4 + 1.39R̄ + 0.43/(1 - R̄)\n    elseif R̄ >= 0.85\n        1/(R̄^3 - 4R̄^2 + 3R̄)\n    end\nend\n\nend # module\n", "meta": {"hexsha": "6ba9cb6d83a57f9dfd73215cac749c1e2784a2fb", "size": 6373, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CircStats.jl", "max_stars_repo_name": "anowacki/CircStats.jl", "max_stars_repo_head_hexsha": "a4e69ade75155b809b2c79623cdabb6df6632a0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-09T18:52:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-20T01:11:10.000Z", "max_issues_repo_path": "src/CircStats.jl", "max_issues_repo_name": "anowacki/CircStats.jl", "max_issues_repo_head_hexsha": "a4e69ade75155b809b2c79623cdabb6df6632a0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-03-23T17:17:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T15:38:23.000Z", "max_forks_repo_path": "src/CircStats.jl", "max_forks_repo_name": "anowacki/CircStats.jl", "max_forks_repo_head_hexsha": "a4e69ade75155b809b2c79623cdabb6df6632a0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:44:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T16:56:54.000Z", "avg_line_length": 28.3244444444, "max_line_length": 88, "alphanum_fraction": 0.619174643, "num_tokens": 1962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7711840224618415}}
{"text": "# The SteinGaussianPowerKernel has base kernel of the form:\n#\n# k(x, y) = ((1 + gamma*||x||^alpha)*(1 + gamma*||y||^alpha))^-1 *\n#   exp(-1/(2*beta)*||x-y||^2)\n#\n# where ||.|| is the L2 norm. This is gauranteed to enforce\n# that k is a universal kernel that vanishes at infinity.\n\ntype SteinGaussianPowerKernel <: SteinGaussianWeightedKernel\n    # the alpha parameter\n    alpha::Float64\n    # the beta parameter\n    beta::Float64\n    # the gamma parameter\n    gamma::Float64\nend\n\n# have default parameters of alpha = 2.5,  beta = 1.0, gamma = 1.0\nSteinGaussianPowerKernel() = SteinGaussianPowerKernel(2.5, 1.0, 1.0)\n\nSteinGaussianPowerKernel(alpha::Float64) = SteinGaussianPowerKernel(alpha, 1.0, 1.0)\n\n# The term (1 + gamma*||z||^alpha)^-1\nfunction _Qz(ker::SteinGaussianPowerKernel, z::Array{Float64, 1})\n    Qz = 1 + ker.gamma * norm(z,2)^ker.alpha\n    1.0 / Qz\nend\n\n# The term ((1 + gamma*||x||^alpha)*(1 + gamma*||y||^alpha))^-1\nfunction Q(ker::SteinGaussianPowerKernel, x::Array{Float64, 1}, y::Array{Float64, 1})\n    _Qz(ker, x) * _Qz(ker, y)\nend\n\nfunction dxj_Q(ker::SteinGaussianPowerKernel, x::Array{Float64,1}, y::Array{Float64,1}, j::Int64)\n    fx = _Qz(ker, x); fy = _Qz(ker, y)\n    mx = norm(x, 2)^(ker.alpha - 2)\n    -x[j] * ker.alpha * ker.gamma * fx^2 * fy * mx\nend\n\nfunction dxjyj_Q(ker::SteinGaussianPowerKernel, x::Array{Float64,1}, y::Array{Float64,1}, j::Int64)\n    mx = norm(x, 2)^(ker.alpha - 2.0)\n    my = norm(y, 2)^(ker.alpha - 2.0)\n    x[j] * y[j] * ker.alpha^2 * ker.gamma^2 * mx * my * Q(ker, x, y)^2\nend\n", "meta": {"hexsha": "02b0852aa033dff6765c9980042acfdd15148038", "size": 1535, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/SteinGaussianPowerKernel.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SteinDiscrepancy.jl-d014d5ac-0f4d-54d5-9198-0ab2ca96d67f", "max_stars_repo_head_hexsha": "bc3e08b745763d2ea466e74d8b254091d0bcca91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2017-07-05T08:38:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-20T18:16:24.000Z", "max_issues_repo_path": "src/kernels/SteinGaussianPowerKernel.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SteinDiscrepancy.jl-d014d5ac-0f4d-54d5-9198-0ab2ca96d67f", "max_issues_repo_head_hexsha": "bc3e08b745763d2ea466e74d8b254091d0bcca91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-05-23T04:58:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:34:20.000Z", "max_forks_repo_path": "src/kernels/SteinGaussianPowerKernel.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SteinDiscrepancy.jl-d014d5ac-0f4d-54d5-9198-0ab2ca96d67f", "max_forks_repo_head_hexsha": "bc3e08b745763d2ea466e74d8b254091d0bcca91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2017-05-23T04:56:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T06:10:56.000Z", "avg_line_length": 34.1111111111, "max_line_length": 99, "alphanum_fraction": 0.6423452769, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.7711840220965902}}
{"text": "\nusing OrdinaryDiffEq, LinearAlgebra, ForwardDiff, Plots; gr()\nH(q,p) = norm(p)^2/2 - inv(norm(q))\nL(q,p) = q[1]*p[2] - p[1]*q[2]\n\npdot(dp,p,q,params,t) = ForwardDiff.gradient!(dp, q->-H(q, p), q)\nqdot(dq,p,q,params,t) = ForwardDiff.gradient!(dq, p-> H(q, p), p)\n\ninitial_position = [.4, 0]\ninitial_velocity = [0., 2.]\ninitial_cond = (initial_position, initial_velocity)\ninitial_first_integrals = (H(initial_cond...), L(initial_cond...))\ntspan = (0,20.)\nprob = DynamicalODEProblem(pdot, qdot, initial_velocity, initial_position, tspan)\nsol = solve(prob, KahanLi6(), dt=1//10);\n\n\nplot_orbit(sol) = plot(sol,vars=(3,4), lab=\"Orbit\", title=\"Kepler Problem Solution\")\n\nfunction plot_first_integrals(sol, H, L)\n    plot(initial_first_integrals[1].-map(u->H(u[2,:], u[1,:]), sol.u), lab=\"Energy variation\", title=\"First Integrals\")\n    plot!(initial_first_integrals[2].-map(u->L(u[2,:], u[1,:]), sol.u), lab=\"Angular momentum variation\")\nend\nanalysis_plot(sol, H, L) = plot(plot_orbit(sol), plot_first_integrals(sol, H, L))\n\n\nanalysis_plot(sol, H, L)\n\n\nsol2 = solve(prob, DPRKN6())  # dt is not necessary, because unlike symplectic\n                              # integrators DPRKN6 is adaptive\n@show sol2.u |> length\nanalysis_plot(sol2, H, L)\n\n\nsol3 = solve(prob, ERKN4()) # dt is not necessary, because unlike symplectic\n                            # integrators ERKN4 is adaptive\n@show sol3.u |> length\nanalysis_plot(sol3, H, L)\n\n\nsol4 = solve(prob, Tsit5())\n@show sol4.u |> length\nanalysis_plot(sol4, H, L)\n\n\nusing DiffEqCallbacks\n\nplot_orbit2(sol) = plot(sol,vars=(1,2), lab=\"Orbit\", title=\"Kepler Problem Solution\")\n\nfunction plot_first_integrals2(sol, H, L)\n    plot(initial_first_integrals[1].-map(u->H(u[1:2],u[3:4]), sol.u), lab=\"Energy variation\", title=\"First Integrals\")\n    plot!(initial_first_integrals[2].-map(u->L(u[1:2],u[3:4]), sol.u), lab=\"Angular momentum variation\")\nend\n\nanalysis_plot2(sol, H, L) = plot(plot_orbit2(sol), plot_first_integrals2(sol, H, L))\n\nfunction hamiltonian(du,u,params,t)\n    q, p = u[1:2], u[3:4]\n    qdot(@view(du[1:2]), p, q, params, t)\n    pdot(@view(du[3:4]), p, q, params, t)\nend\n\nprob2 = ODEProblem(hamiltonian, [initial_position; initial_velocity], tspan)\nsol_ = solve(prob2, RK4(), dt=1//5, adaptive=false)\nanalysis_plot2(sol_, H, L)\n\n\nfunction first_integrals_manifold(residual,u)\n    residual[1:2] .= initial_first_integrals[1] - H(u[1:2], u[3:4])\n    residual[3:4] .= initial_first_integrals[2] - L(u[1:2], u[3:4])\nend\n\ncb = ManifoldProjection(first_integrals_manifold)\nsol5 = solve(prob2, RK4(), dt=1//5, adaptive=false, callback=cb)\nanalysis_plot2(sol5, H, L)\n\n\nfunction energy_manifold(residual,u)\n    residual[1:2] .= initial_first_integrals[1] - H(u[1:2], u[3:4])\n    residual[3:4] .= 0\nend\nenergy_cb = ManifoldProjection(energy_manifold)\nsol6 = solve(prob2, RK4(), dt=1//5, adaptive=false, callback=energy_cb)\nanalysis_plot2(sol6, H, L)\n\n\nfunction angular_manifold(residual,u)\n    residual[1:2] .= initial_first_integrals[2] - L(u[1:2], u[3:4])\n    residual[3:4] .= 0\nend\nangular_cb = ManifoldProjection(angular_manifold)\nsol7 = solve(prob2, RK4(), dt=1//5, adaptive=false, callback=angular_cb)\nanalysis_plot2(sol7, H, L)\n\n\nusing DiffEqTutorials\nDiffEqTutorials.tutorial_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])\n\n", "meta": {"hexsha": "be9f97b1c486a513f6a37d684086774e46ef47af", "size": 3274, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/models/05-kepler_problem.jl", "max_stars_repo_name": "isaacsas/DiffEqTutorials.jl", "max_stars_repo_head_hexsha": "46c1701ef613aacbd678bde7437a3c8de363990d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-22T12:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-22T12:30:52.000Z", "max_issues_repo_path": "script/models/05-kepler_problem.jl", "max_issues_repo_name": "isaacsas/DiffEqTutorials.jl", "max_issues_repo_head_hexsha": "46c1701ef613aacbd678bde7437a3c8de363990d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/models/05-kepler_problem.jl", "max_forks_repo_name": "isaacsas/DiffEqTutorials.jl", "max_forks_repo_head_hexsha": "46c1701ef613aacbd678bde7437a3c8de363990d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.74, "max_line_length": 119, "alphanum_fraction": 0.6863164325, "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7711840202060432}}
{"text": "# Script to generate Figures 18 and 19\nusing FileIO, Images, ImageFiltering, JLD2, MultiscaleGraphSignalTransforms, MultivariateStats, Plots, StatsBase\ninclude(\"auxilaries.jl\")\n\n# Set up the resolution and display size\ngr(dpi=200, size=(800,600))\n\n# Load the original 512x512 composite texture image and its mastge\ntextures = FileIO.load(\"5block.png\")\ntextures = Matrix{Float64}(textures) # convert it to a regular matrix\n\n# Compute the mask image using the Gabor features + PCA\n#\n# Step 1: Parameter setups\n# Orientations\nndir = 2\nΘ = [ π/3; 5*π/6 ]\n\n# Spatial frequencies\nΞ = [0.2; 0.3; 0.4; 0.5]\n# Convert them to wavelengths\nΛ = 1.0 ./ Ξ\n\n# Gaussian bandwidth for Gabor filters\nbw = 1.0\nσ = 1.0/π * sqrt(log(2)/2) * (2^bw+1)/(2^bw-1)\n\n# Spatial aspect ratio: σx = σ; σy = σ/γ\nγ = 1.0\n\n# Step 2: Apply Gabor filters; the same size as the input image.\nm, n = size(textures)\n\nK = length(Θ) *length(Λ) # K should be square number\nF = zeros(m, n, K) # This is the space for the Gabor filtered images\nFg = zeros(m, n, K) # This is the space for the Gaussian smoothed version of F\nkr = zeros(m+1, n+1, K)\nki = zeros(m+1, n+1, K)\n\nk = 1\nkl = (0, 0)\nfor θ in Θ\n    for λ in Λ\n        kernel = Kernel.gabor(m, n, λ*σ, θ, λ, γ, 0.0)\n        kernel[1] ./= 2*π*σ*σ/γ\n        kernel[2] ./= 2*π*σ*σ/γ\n        global kl = size(kernel[1])\n        kr[1:kl[1],1:kl[2],k] = kernel[1]\n        ki[1:kl[1],1:kl[2],k] = kernel[2]\n        cker = (centered(kernel[1]), centered(kernel[2]))\n        F[:,:,k] = sqrt.(imfilter(textures, reflect(cker[1])).^2 + \n            imfilter(textures, reflect(cker[2])).^2)\n        # \"reflect\"ing the kernel is necessary for convolution;\n        # otherwise it does the correlation.\n        Fg[:,:,k] = imfilter(F[:,:,k], Kernel.gaussian(3.0*λ))\n        global k += 1\n    end\nend \n\n# Display those Gabor features\nplot(K, layout=(length(Θ),length(Λ)), framestyle=:none, legend=false)\nfor k = 1:K\n    heatmap!(kr[226:286,226:286,k], subplot=k, ratio=1, yaxis=:flip, showaxis=false, \n        ticks=false, c=:grays, clims=(minimum(kr), maximum(kr)), colorbar=false)\nend\ndisplay(current())\n\n# Displaying the imaginary part of Gabor kernels may not be necessary...\n#plot(K, layout=(Int(sqrt(K)),Int(sqrt(K))), framestyle=:none, legend=false)\n#for k = 1:K\n#    heatmap!(ki[:,:,k], subplot=k, ratio=1, yaxis=:flip, showaxis=false, \n#      ticks=false, c=:grays, clims=(minimum(ki), maximum(ki)), colorbar=false)\n#end\n#display(current())\n\nplot(K, layout=(length(Θ),length(Λ)), framestyle=:none, legend=false)\nfor k = 1:K\n    heatmap!(Fg[:,:,k], subplot=k, ratio=1, yaxis=:flip, showaxis=false, \n        ticks=false, c=:grays, clims=(0, maximum(F)), colorbar=false)\nend\ndisplay(current())\n\n# Step 3.  Compute the PCA and extract the first principal component\nXtr=reshape(Fg, (m*n, K))\nXtr=Xtr'\ndt=StatsBase.fit(ZScoreTransform, Xtr) # Each variable is standardized to have \n# mean 0, stddev 1\nXtr=StatsBase.transform(dt, Xtr)\nM = MultivariateStats.fit(PCA, Xtr)\nYtr=MultivariateStats.transform(M, Xtr)\nYtr=Ytr'\nYtr=reshape(Ytr, (m, n, size(Ytr, 2)))\nplot(K, layout=(length(Θ),length(Λ)), framestyle=:none, legend=false)\nfor k = 1:outdim(M)\n    heatmap!(Ytr[:,:,k], subplot=k, ratio=1, yaxis=:flip, showaxis=false, \n             ticks=false, c=:grays, clims=(minimum(Ytr), maximum(Ytr)), colorbar=false)\nend\ndisplay(current())\n\nmask = Ytr[:,:,1]\ndisplay(heatmap(mask, ratio=1, c=:grays, yaxis=:flip))\n# End of 512 x 512 mask generation.\n\n#\n# Subsample both the original and mask images to 128 x 128\n#\ntextures = deepcopy(textures[1:4:end,1:4:end])\nmask = deepcopy(mask[1:4:end,1:4:end])\nm, n = size(textures) # recapture the subsampled matrix size\n\n#\n# Normalize the mask\n#\nmask = (mask.-minimum(mask))./(maximum(mask)-minimum(mask));\n\n#\n# Generate Fig. 18a\n#\ndisplay(heatmap(textures, ratio=1, yaxis =:flip, showaxis = false, ticks = false,\n        color = :grays, colorbar = false))\nsavefig(\"textures_orig.pdf\")\nsavefig(\"textures_orig.png\")\n\n#\n# Generate Fig. 18b\n#\ndisplay(heatmap(mask, ratio=1, yaxis =:flip, showaxis = false, ticks = false,\n        color = :grays, colorbar = false))\nsavefig(\"textures_mask.pdf\")\nsavefig(\"textures_mask.png\")\n\n#\n# Now, let's compute the weight matrix based on the Gaussian affinity\n# of the small windows (or radius r) around pixels and the pixel locations.\n#\n# Set up the key parameters\nr = 3 # specify radius of neighbors; so far the best\nσ = 0.0005 # the best so far with r=3 or r=5\n\n# Do the weight matrix computation\nW = image_Gaussian_affinity(mask, r, σ)    \n\n#\n# Generate G (GraphSig object) and GP (GraphPart object) using the computed\n# weight matrix W, and the subsampled texture image as a graph signal.\n# Note that GraphSig requires a matrix data even if it is just a one vector, i.e., f = textures[:] does not work!\nG = GraphSig(W, f = reshape(textures, (length(textures), 1)))\nGP = partition_tree_fiedler(G)\ndmatrix = ghwt_analysis!(G, GP=GP)\n\n#\n# Construct or search the specific basis\n#\n# Haar\nBS_haar = bs_haar(GP)\ndvec_haar = dmatrix2dvec(dmatrix, GP, BS_haar)\n\n# Walsh\nBS_walsh = bs_walsh(GP)\ndvec_walsh = dmatrix2dvec(dmatrix, GP, BS_walsh)\n\n# GHWT_c2f\ndvec_c2f, BS_c2f = ghwt_c2f_bestbasis(dmatrix, GP)\n\n# GHWT_f2c\ndvec_f2c, BS_f2c = ghwt_f2c_bestbasis(dmatrix, GP)\n\n# eGHWT\ndvec_eghwt, BS_eghwt = eghwt_bestbasis(dmatrix, GP)\n\n#\n# Generate Figure 19a (Approximation error plot)\n#\nDVEC = [ dvec_haar[:], dvec_walsh[:], dvec_c2f[:], dvec_f2c[:], dvec_eghwt[:] ]\nT = [ \"Graph Haar\", \"Graph Walsh\", \"GHWT_c2f \", \"GHWT_f2c\", \"eGHWT\" ]\nL = [ (:dashdot,:orange), (:dashdot,:blue), (:solid, :red), (:solid, :green), \n      (:solid, :black) ]\napprox_error2(DVEC, T, L, 0.5)\nsavefig(\"textures_approx_error_r3_sigma0005.pdf\")\nsavefig(\"textures_approx_error_r3_sigma0005.png\")\n\n#\n# Generate Figure 19b (Top 9 eGHWT basis vectors)\n#\ntop_vectors_plot3(dvec_eghwt, m, n, BS_eghwt, GP)\nsavefig(\"textures_eghwt09_r3_sigma0005.pdf\")\nsavefig(\"textures_eghwt09_r3_sigma0005.png\")\n", "meta": {"hexsha": "314c3c90741b0691ef5c8b1fd6709adce9c72268", "size": 5925, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/paperscripts/eGHWT2021/figs1819.jl", "max_stars_repo_name": "BoundaryValueProblems/MTSG.jl", "max_stars_repo_head_hexsha": "8cf8e2b3035876b5ceda45109b0847a60b581a7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-02T18:39:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-19T15:45:17.000Z", "max_issues_repo_path": "test/paperscripts/eGHWT2021/figs1819.jl", "max_issues_repo_name": "haotian127/MultiscaleGraphSignalTransforms.jl", "max_issues_repo_head_hexsha": "85ba99e505283491ac69e979737bbb712b698a6e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2021-04-27T23:00:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-03T11:03:17.000Z", "max_forks_repo_path": "test/paperscripts/eGHWT2021/figs1819.jl", "max_forks_repo_name": "haotian127/MultiscaleGraphSignalTransforms.jl", "max_forks_repo_head_hexsha": "85ba99e505283491ac69e979737bbb712b698a6e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-04-24T21:46:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T04:32:31.000Z", "avg_line_length": 31.5159574468, "max_line_length": 113, "alphanum_fraction": 0.678649789, "num_tokens": 1980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558356, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7711840131308562}}
{"text": "using EconPDEs\n\nmutable struct WangWangYangModel\n    μ::Float64 \n    σ::Float64\n    r::Float64\n    ρ::Float64  \n    γ::Float64 \n    ψ::Float64\n    wmax::Float64\nend\n\nfunction WangWangYangModel(;μ = 0.01, σ = 0.1, r = 0.05, ρ = 0.06, γ = 2, ψ = 0.5, wmax = 5000.0)\n    WangWangYangModel(μ, σ, r, ρ, γ, ψ, wmax)\nend\n\nfunction initialize_stategrid(m::WangWangYangModel; n = 1000)\n    OrderedDict(:w => range(0.0, stop = m.wmax, length = n))\nend\n\nfunction initialize_y(m::WangWangYangModel, stategrid)\n    OrderedDict(:p => 1 .+stategrid[:w])\nend\n    \nfunction (m::WangWangYangModel)(state::NamedTuple, y::NamedTuple)\n    μ = m.μ ;  σ = m.σ ;  r = m.r ;  ρ = m.ρ ;  γ = m.γ ;  ψ = m.ψ ; wmax = m.wmax\n    w = state.w\n    p, pw, pww = y.p, y.pw, y.pww\n    c = (r + ψ * (ρ - r)) * p * pw^(-ψ)\n    μw = (r - μ + σ^2) * w + 1 - c\n    # One only needs a ghost node if μw <= 0 (since w^2p_ww = 0). In this case, we obtain a formula for pw so that c <= 1\n    if w ≈ 0.0 && μw <= 0.0\n       pw = ((r + ψ * (ρ - r)) * p)^(1 / ψ)\n       c = 1.0\n       μw = 0.0\n    end\n    # At the top, I use the solution of the unconstrainted, i.e. pw = 1 (I could also do reflecting boundary but less elegant)\n    pt = (((r + ψ * (ρ - r)) * pw^(1 - ψ) - ψ * ρ) / (ψ - 1) + μ - γ * σ^2 / 2) * p + ((r - μ + γ * σ^2) * w + 1) * pw + σ^2 * w^2 / 2  * (pww - γ * pw^2 / p)\n    μw = (r - μ + σ^2) * w + 1 - c\n    return (pt,), (μw,), (w = w, p = p, pw = pw, pww = pww, μw = μw, c = c)\nend\n\n\n", "meta": {"hexsha": "90482b5ac71f0799a28b2b32309b4ed6f41265c6", "size": 1458, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ConsumptionProblem/WangWangYang.jl", "max_stars_repo_name": "FuZhiyu/EconPDEs.jl", "max_stars_repo_head_hexsha": "ed58adaf859e595f94ff99114e4038974791ae05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/ConsumptionProblem/WangWangYang.jl", "max_issues_repo_name": "FuZhiyu/EconPDEs.jl", "max_issues_repo_head_hexsha": "ed58adaf859e595f94ff99114e4038974791ae05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ConsumptionProblem/WangWangYang.jl", "max_forks_repo_name": "FuZhiyu/EconPDEs.jl", "max_forks_repo_head_hexsha": "ed58adaf859e595f94ff99114e4038974791ae05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1363636364, "max_line_length": 158, "alphanum_fraction": 0.5150891632, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505204, "lm_q2_score": 0.8244619263765706, "lm_q1q2_score": 0.7711575912770878}}
{"text": "using FractionalTimeDG\nusing PyPlot\n\nα = 3/4\nN = 1000\nr = 4\nM = 2r\nversion = 1\n\nstore = Store(α, r, M)\nH = coef_H_uniform!(r, N, M, store, version)\n\nℓ = collect(1:N-1)\n\nfunction max_antidiags(H)\n    r = size(H[0], 1)\n    N = length(H)\n    γ = zeros(N-1, 2r-1)\n    for m = 2:2r\n        for ℓbar = 1:N-1\n            if m ≤ r\n                antidiag = [ H[ℓbar][i,m-i] for i = 1:m-1 ]\n            else\n                antidiag = [ H[ℓbar][i,m-i] for i = m-r:r ]\n            end\n#            println(antidiag)\n            largest = maximum(abs.(antidiag))\n            if largest ≥ eps(Float64)\n                γ[ℓbar, m-1] = largest\n            else\n                γ[ℓbar, m-1] = NaN\n            end\n        end\n    end\n    return γ\nend\n\nγ = max_antidiags(H)\n\nfigure(2)\nfmt = [\":\", \"--\", \"-.\", \"-\", \":\", \"--\", \"-.\"]\nfor m = 2:2r\n    loglog(ℓ, γ[:,m-1], fmt[m-1])\nend\nlegend([latexstring(\"i+j=$m\") for m = 2:2r])\ngrid(true)\nxlabel(L\"$\\bar\\ell$\", fontsize=12)\nsavefig(\"fig2.eps\")\n", "meta": {"hexsha": "5b584eeee972c6dd223d149d1ed2e101a5b63d33", "size": 976, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/figure2.jl", "max_stars_repo_name": "billmclean/FractionalTimeDG.jl", "max_stars_repo_head_hexsha": "165bd96ac1355befaed4dff25172cc255e883768", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/figure2.jl", "max_issues_repo_name": "billmclean/FractionalTimeDG.jl", "max_issues_repo_head_hexsha": "165bd96ac1355befaed4dff25172cc255e883768", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/figure2.jl", "max_forks_repo_name": "billmclean/FractionalTimeDG.jl", "max_forks_repo_head_hexsha": "165bd96ac1355befaed4dff25172cc255e883768", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9183673469, "max_line_length": 59, "alphanum_fraction": 0.4692622951, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7711575807680334}}
{"text": "@doc raw\"\"\"\n    SeriesAccelerations\n\nThis modules provides an algorithm for calculating infinite series efficiently.\nCurrently, two algorithms are provided. `accel_cohen_villegas_zagier()` for an\nalternating series, and `accel_wynn_eps()` for more general series.\n\"\"\"\nmodule SeriesAccelerations\n\n\nexport accel_cohen_villegas_zagier\nexport accel_wynn_eps\n\n\n################# Cohen, Villegas, Zagier 2000 algorithm #####################\n\n@doc raw\"\"\"\n    accel_cohen_villegas_zagier(ak)\n\nEstimate the sum over the array `ak`. It is assumed without check that the\nelements in the array have alternating sign and the series converges.\n\nThis algorithm is\n[presented](https://people.mpim-bonn.mpg.de/zagier/files/exp-math-9/fulltext.pdf)\nin [Cohen et al 2000]\n(https://www.tandfonline.com/doi/abs/10.1080/10586458.2000.10504632).\n\"\"\"\nfunction accel_cohen_villegas_zagier(ak)\n    T = eltype(ak)\n    n = length(ak)\n    d = (3 + √T(8))^n\n    d = (d + 1/d) / 2\n    b = -T(1)\n    c = -d\n    s = T(0)\n    for k=0:n-1\n        c = b - c\n        s += (-1)^k * c * ak[k+1]\n        b = (k + n) * (k - n) * b / ((k + 1/T(2)) * (k + 1))\n    end\n    return s / d\nend\n\n\n################ Wynn 1956 epsilon-algorithm #################################\n\nfunction next_j!(c2, ϵ, n)\n    c1 = (c2 & 1) + 1  # c1 is the other column (row, actually)\n    for i=1:n\n        ϵ[c1,i] = ϵ[c1,i+1] + 1 / (ϵ[c2,i+1] - ϵ[c2,i])\n    end\n    return c1\nend\n\n\nfunction accel_wynn_eps!(ϵ)\n    N = size(ϵ, 2)\n    c = 2\n    for j=1:N-1\n        c = next_j!(c, ϵ, N - j)\n    end\n    return ϵ[c,1]\nend\n\n\n@doc raw\"\"\"\n    accel_wynn_eps(ak)\n\nEstimate the sum over the array `ak`. It is assumed without check that the\nseries converges.\n\nThe algorithm used is [Wynn's\nepsilon-algorithm](https://www.ams.org/journals/mcom/1956-10-054/S0025-5718-1956-0084056-6/S0025-5718-1956-0084056-6.pdf)\npresented in [Wynn 1956](https://www.jstor.org/stable/2002183).\n\"\"\"\nfunction accel_wynn_eps(ak)\n    ΔN = 1 - (length(ak) & 1)  # 1 for even length, 0 for odd\n    N = length(ak) - ΔN\n    ϵ = Array{eltype(ak)}(undef, 2, N)\n    for n=1:N\n        ϵ[1,n] = zero(eltype(ak))\n        ϵ[2,n] = sum(ak[1:n+ΔN])\n    end\n    return accel_wynn_eps!(ϵ)\nend\n\n\nend\n\n\n# vim: set sw=4 et sts=4 :\n", "meta": {"hexsha": "0abc7641d48897819332e0d44218bfd185332966", "size": 2216, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SeriesAccelerations.jl", "max_stars_repo_name": "hsgg/QuadOsc.jl", "max_stars_repo_head_hexsha": "104a6826db661f08e797ab94d4fcb6b0e413aa0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SeriesAccelerations.jl", "max_issues_repo_name": "hsgg/QuadOsc.jl", "max_issues_repo_head_hexsha": "104a6826db661f08e797ab94d4fcb6b0e413aa0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SeriesAccelerations.jl", "max_forks_repo_name": "hsgg/QuadOsc.jl", "max_forks_repo_head_hexsha": "104a6826db661f08e797ab94d4fcb6b0e413aa0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0869565217, "max_line_length": 121, "alphanum_fraction": 0.6083032491, "num_tokens": 795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7711575803446447}}
{"text": "include(\"./src/functions/Functions.jl\")\ninclude(\"./src/evaluate/Evaluate.jl\")\ninclude(\"./src/linesearch/Linesearch.jl\")\n\nusing MAT\n\nfunction logregGD(X, y, lambda, epsilon=1e-4, maxiter=1000,maxLSiter=25, verbose=false)\n\tm = size(X,1) # i have m datapoints\n\tn = size(X,2) # n = dimension of the problem\n\ttheta = zeros(784,1)\n\tmultiplier = 0.5\n\tf_likelihood = f_logreg(X,y,theta,lambda)\n\tg_likelihood = g_logreg(X,y,theta,lambda)\n\toptimal = false\n\n\tlikelihood = Inf\n\tfor i in 1:maxiter\n        likelihood = f_likelihood(theta)\n        gradient = g_likelihood(theta)\n\t\talpha = 1\n\n\t\t# check optimality with inf norm\n\t\tif norm(gradient,Inf) < epsilon\n\t\t\treturn (theta,\"optimal\")\n\t\tend\n\t\t# find step size\n\t\tlineSearchIter = 0\n        # Linesearch\n        for j in 1:maxLSiter\n            f_xk_alpha_k = f_likelihood(theta + ( alpha * -gradient))\n            f_xk_plus_grad = likelihood + (epsilon*alpha*gradient' * -gradient)[1]\n            #@printf(\"%f \\t < \\t %f\\n\",f_xk_alpha_k,f_xk_plus_grad)\n\n            if  ! (f_xk_alpha_k < f_xk_plus_grad)\n                alpha = alpha * multiplier\n                lineSearchIter += 1\n            else\n                break\n            end\n        end\n\n\t\tif verbose\n            @printf(\"%i \\t\\t %f \\t %f \\t %f \\t\\t %i \\n\",i,likelihood,norm(gradient,Inf),alpha,lineSearchIter)\n\t\tend\n\t\t# descent\n\t\ttheta = theta + alpha * -gradient\n\tend\n\treturn (theta,\"maxIter\")\nend\n\ndataLocation = \"data/mnist67.scale.1k.mat\"\n\n# 784 dimensions | 1000 data points\nfile = matopen(dataLocation)\ntmp = read(file, \"X\")\n\nX = full(tmp)\ny = read(file,\"y\")\n\ntheta, state = logregGD(X,y,0,1e-4,1000,20,true)\n@printf(\"Optimization finished with state %s.\\n\",state)\naccuracy = evaluate(X,y,theta)\n@printf(\"Accuracy of solution : %f %%.\\n\",accuracy*100)\n\ntheta, state = logregGD(X,y,0.1,1e-4,1000,20,true)\n@printf(\"Optimization finished with state %s.\\n\",state)\naccuracy = evaluate(X,y,theta)\n@printf(\"Accuracy of solution : %f %%.\\n\",accuracy*100)\n\ntheta, state = logregGD(X,y,100,1e-4,1000,20,true)\n@printf(\"Optimization finished with state %s.\\n\",state)\naccuracy = evaluate(X,y,theta)\n@printf(\"Accuracy of solution : %f %%.\\n\",accuracy*100)\n\ntheta, state = logregGD(X,y,1000,1e-4,1000,20,true)\n@printf(\"Optimization finished with state %s.\\n\",state)\naccuracy = evaluate(X,y,theta)\n@printf(\"Accuracy of solution : %f %%.\\n\",accuracy*100)\n", "meta": {"hexsha": "69192e05b876a185ebef0a26da3921c456eac5f3", "size": 2347, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "GradientDescent.jl", "max_stars_repo_name": "zagazao/num-opt", "max_stars_repo_head_hexsha": "54444008be831a7bb51e845b688f41b5239d285d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-02-01T11:02:20.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-11T22:51:30.000Z", "max_issues_repo_path": "GradientDescent.jl", "max_issues_repo_name": "zagazao/num-opt", "max_issues_repo_head_hexsha": "54444008be831a7bb51e845b688f41b5239d285d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GradientDescent.jl", "max_forks_repo_name": "zagazao/num-opt", "max_forks_repo_head_hexsha": "54444008be831a7bb51e845b688f41b5239d285d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7088607595, "max_line_length": 109, "alphanum_fraction": 0.653174265, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465044347828, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7711575768416262}}
{"text": "@doc raw\"\"\"\n# Lotka-Volterra model in 2D with \"singular\" Lagrangian\n\n```math\n\\begin{aligned}\nL (q, \\dot{q}) &= \\frac{\\log q_2}{q_1} \\, \\dot{q_1} - H(q) , \\\\\nH(q) &= a_1 \\, q_1 + a_2 \\, q_2 + b_1 \\, \\log q_1 + b_2 \\, \\log q_2\n\\end{aligned}\n```\n\nThis Lagrangian is equivalent to the Lagrangian of the symmetric Lotka-Volterra model. It\ndiffers only by a gauge transformation with the term ``- 1/2 \\, d(\\log(q_1) \\log(q_2))/dt``.\nIt leads to the same Euler-Lagrange equations but to a different variational integrator.\n\"\"\"\nmodule LotkaVolterra2dSingular\n\n    ϑ₁(t, q) = + log(q[2]) / q[1]\n    ϑ₂(t, q) = zero(eltype(q))\n\n    dϑ₁dx₁(t, q) = - log(q[2]) / q[1]^2\n    dϑ₁dx₂(t, q) = + 1 / (q[1] * q[2])\n\n    dϑ₂dx₁(t, q) = zero(eltype(q))\n    dϑ₂dx₂(t, q) = zero(eltype(q))\n\n\n    # ϑ₁(t, q) = zero(eltype(q))\n    # ϑ₂(t, q) = - log(q[1]) / q[2]\n\n    # dϑ₁dx₁(t, q) = zero(eltype(q))\n    # dϑ₁dx₂(t, q) = zero(eltype(q))\n\n    # dϑ₂dx₁(t, q) = - 1 / (q[2] * q[1])\n    # dϑ₂dx₂(t, q) = + log(q[1]) / q[2]^2\n\n\n    include(\"lotka_volterra_2d_common.jl\")\n    include(\"lotka_volterra_2d_equations.jl\")\n\nend\n", "meta": {"hexsha": "c742524923b117cba876282443e2057eee30d85f", "size": 1094, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lotka_volterra_2d_singular.jl", "max_stars_repo_name": "DDMGNI/GeometricProblems.jl", "max_stars_repo_head_hexsha": "367f4cf63ff614c3051c7760b835889fdb7a040f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lotka_volterra_2d_singular.jl", "max_issues_repo_name": "DDMGNI/GeometricProblems.jl", "max_issues_repo_head_hexsha": "367f4cf63ff614c3051c7760b835889fdb7a040f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-02-11T01:23:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-24T11:06:23.000Z", "max_forks_repo_path": "src/lotka_volterra_2d_singular.jl", "max_forks_repo_name": "DDMGNI/GeometricProblems.jl", "max_forks_repo_head_hexsha": "367f4cf63ff614c3051c7760b835889fdb7a040f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6829268293, "max_line_length": 92, "alphanum_fraction": 0.5776965265, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012717045181, "lm_q2_score": 0.8152324983301567, "lm_q1q2_score": 0.7710479336555136}}
{"text": "function claytonCopula(θ::Int64, samples::Int64, dim::Int64)\n\tres = zeros(dim, samples)\n\tU_dist = Uniform(0,1)\n\tγ_dist = Gamma(1/θ,1)\n\tfor i = 1:samples\n\t\tV = rand(U_dist, dim)\n\t\tγ = rand(γ_dist, 1)\n\t\tΨ(t) = (t+1)^(-1/θ)\n\t\tU_γ = Ψ.(-log.(V)./γ)\n        for j = 1:dim\n            res[j,i] = U_γ[j]\n        end\n\tend\n    return res\nend", "meta": {"hexsha": "3d9a53d0b99bcb1fe529c847768b1a59a29aa597", "size": 332, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/archmCopula.jl", "max_stars_repo_name": "Xiar-fatah/MvrtCopula.jl", "max_stars_repo_head_hexsha": "7d8e9f27b84c9b7f1313db7a51f62411b0ebc480", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/archmCopula.jl", "max_issues_repo_name": "Xiar-fatah/MvrtCopula.jl", "max_issues_repo_head_hexsha": "7d8e9f27b84c9b7f1313db7a51f62411b0ebc480", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/archmCopula.jl", "max_forks_repo_name": "Xiar-fatah/MvrtCopula.jl", "max_forks_repo_head_hexsha": "7d8e9f27b84c9b7f1313db7a51f62411b0ebc480", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1333333333, "max_line_length": 60, "alphanum_fraction": 0.5481927711, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7710479256734367}}
{"text": "using FdeSolver\nusing Plots\nusing SpecialFunctions\n\n## inputs\ntSpan = [0, 1]     # [intial time, final time]\ny0 = 0             # intial value\nβ = 0.5            # order of the derivative\nh=2^-5\n\n# Equation\npar = β\nF(t, y, par) = (40320 ./ gamma(9 - par) .* t .^ (8 - par) .- 3 .* gamma(5 + par / 2)\n           ./ gamma(5 - par / 2) .* t .^ (4 - par / 2) .+ 9/4 * gamma(par + 1) .+\n           (3 / 2 .* t .^ (par / 2) .- t .^ 4) .^ 3 .- y .^ (3 / 2))\n# Jacobian\nJacobF(t, y, par) = -(3 / 2) .* y .^ (1 / 2)\n\n## Numerical solution\nt, Yapp = FDEsolver(F, tSpan, y0, β, par, h = h, StopIt = \"Convergence\", tol = 10e-8, itmax = 30)\n\nt1, Yapp1 = FDEsolver(F, tSpan, y0, β, par, JF = JacobF, tol = 10e-8, itmax = 30)\n\n#plot\nplot(t, Yapp, linewidth = 5, title = \"Solution of a 1D fractional IVP\",\n     xaxis = \"Time (t)\", yaxis = \"y(t)\", label = \"Approximation\")\nplot!(t1, Yapp1, linewidth = 5, ls = :dot, label = \"Approximation with Jacobian\")\nplot!(t, t -> (t.^8 - 3 * t .^ (4 + β / 2) + 9 / 4 * t.^β),\n      lw = 3, ls = :dash, label = \"Exact solution\")\n", "meta": {"hexsha": "566dda28871074933c307a7a20338fd199597299", "size": 1050, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/fDE1D.jl", "max_stars_repo_name": "FDE-Solver/FDE_Solver", "max_stars_repo_head_hexsha": "f0f06cff60d8bccbb61c588e0aba9df3bc4dd961", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-10-01T00:17:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T09:21:11.000Z", "max_issues_repo_path": "examples/fDE1D.jl", "max_issues_repo_name": "FDE-Solver/FDE_Solver", "max_issues_repo_head_hexsha": "f0f06cff60d8bccbb61c588e0aba9df3bc4dd961", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2021-09-13T10:53:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T08:00:50.000Z", "max_forks_repo_path": "examples/fDE1D.jl", "max_forks_repo_name": "moeinkh88/FDE_Solver", "max_forks_repo_head_hexsha": "f0f06cff60d8bccbb61c588e0aba9df3bc4dd961", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-10T12:59:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T12:59:53.000Z", "avg_line_length": 35.0, "max_line_length": 97, "alphanum_fraction": 0.5180952381, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7710479138135626}}
{"text": "# (c) David Barber, University College London 2015\n#= How this works:\n\nGENERAL AUTODIFF THEORY:\n\nAccording to the general autodiff theory (see my online notes http://web4.cs.ucl.ac.uk/staff/D.Barber/publications/ParameterTying.pdf) the total derivative t[n] at a node n in the graph is related to the children c of node n by\n \\sum_c t[c] df[c]/df[n]\n\nor, in the notation used in the code\n\ngrad_n = \\sum_c grad_c* df[c]/df[n]\n\nRETURNING A TOTAL DERIVATIVE FUNCTION:\n\nConsider a node that computes h=sigma(W*x).  Since the output of this node h is a vector, we need to calculate all the derivatives from these elements of this child h to its parents W and x. For example,\n\ndh[i]/dW[a,b] = dsigma(W[a,:]'*x)*x[b]*delta[i,a]\n\nwhere delta[i,a] is the Kronecker delta function and dsigma is the derivative of the transfer function sigma. However, when we use this as part of the reverse recursion, the Kronecker delta gives a simplification, namely\n\n\\sum_i grad_c[i]dh[i]/dW[a,b] = grad_c[a]dsigma(W[a,:]'*x)*x[b]\n\nWhat this means is that we can exploit the mathematical simplication that results from the Kronecker delta and return instead a derivative as a function of the child total derivative grad_c. For example, for the logistic sigmoid, dsigma=sigma*(1-sigma) and we use\n\n(grad_c.*f_c.*(1.-f_c))*x'   for the derivative wrt W\nW'*(grad_c.*f_c.*(1.-f_c))   for the derivative wrt x\n\nHere f_c is the value of the child node (which is sigma(W*x).\n\nThe derivative can then be returned directly as a function of the node value, the parent node values and the child node value -- no additional storage is required. This is more efficient than defining two nodes, first h=W*x, then sigma(h); here we would have to store the value h and also sigma(h), which will cost roughly twice as much in terms of storage.\n\nREUSING INFORMATION BY STORING AUXILIARY VALUES:\n\nSome computational savings can be made in the reverse pass by reusing results computed during the forward pass.\n\nFor example, for the logistic sigmoid, we calculate f=sigma(W*h) on the forward pass. The derivative pass requires us to calculate dsigma(W*x) but since this is equal to sigma(W*h)*(1-sigma(W*h)) this is just a simple function of the forward pass result, namely f.*(1-f) so that we can simply reuse the forward calculation values, without having to compute the sigmoid function again in the reverse pass -- this saves on computation.\n\nThe code therefore allows during the forward pass to store auxilliary information at a node that might be useful for speeding up the computation in the backward pass. The deriviate can then be a function of the forward pass value (f_c) or the auxilliary information (faux_c) stored at the forward pass node.\n\nNote that the functions all have two versions -- a standard one which returns a value, and an inplace version that updates an existing value. (The CUDA versions only require the inplace routines).  The standard one is only required during compilation. All subsequent uses of the function are inplace.\n\nThe gradients are defined to update preexisting gradients -- inplace. It's also important to bear in mind that (at each backward pass, after iniitalisating gradients to zero) we must add gradients at a node. An explanation for this is that we can have situations in which a variable x has two directed paths to a variable f. For example, f=sum([x x]).\n\n\n\nFor future, it would be interesting to map any function f and reduce it with sum\n\nfunction Fsumf(f,x...)\n    return sum(f(collect(x)))\nend\nThen\nDsumf(derivativeIDX,s,a,t,grad,reset,D,f,x...)=t.*D[f](x[derivativeIDX])\nWe could even then find the symbolic derivative df of f. We wouldn't want to have to do this each time we call the function though.\nWe could I think do this with a Dict.\n    D=Dict()\n    D[\"x^2\"]=(x)->2x\n    We can then evaluate using\n    D[\"x^2\"](3.2)\n    We can then make the Dict and the function f both nodes in the graph\n    For the GPU though we would need to have compiled kernels for each function f and its associated derivative df\n=#\n\n# --------------------------------------------------------------------------------------\n# Functions and their Derivatives:\n\n# functions are defined as F(x)=(self,aux). Here self is the function value and aux is the auxiliary value (it can be empty []) that might be useful to speed up the return pass calculation.\n\nDerivative=Dict() # mappings of functions to their derivatives\nInplace=Dict() # Inplace version of function\n\n\n#TODO:\n# sqrt, power fn, trig functions,\n# diagm(A)+\n# diag(A) for both CPU and GPU (note that diagm(A) is implemented for both GPU and CPU)\n# A/s where s is a 1x1 array and A is an array\n# A.*B', A'.*B, A'.*B' for CPU and GPU; currently these are computed using A.*trans(B), etc which is wasteful\n# A./B', A'./B, A'./B' for CPU and GPU\n# array subindexing (see old code at end) Not sure if this is really necessary\n# The KL loss methods are expensive if one only wants to maximise the corresponding likelihood. Could make versions with a flag to drop the entropy term\n# Some of the GPU demos are very slow -- DemoLSTMsimple, for example. Need to investigate why.\n\nf=[\n   \"Fnx\", \"Ftanh\",\n   \"Fstanh\", \"Fsigmoid\", \"Frectlin\",\n   \"FAhadamardprodB\",    \"FAhadamarddivB\",\n   \"Fsum\", \"Fmean\",\n   \"FsumSquare\",    \"FmeanSquare\",\n   \"FAX\", \"FAXplusBias\",\n   \"Fxpy\", \"Fxmy\",\n   \"FmeanSquareLoss\",\n   \"FBinaryKullbackLeiblerLoss\", \"FBinaryKullbackLeiblerLossXsigmoidY\",\n   \"FsigmoidAXplusBias\",\n   \"FrectlinAXplusBias\",\n   \"FstanhAXplusBias\",\n   \"Fsoftmax\",   \"FKLsoftmax\",\n   \"Fexp\", \"Flog\",\n   \"Ftranspose\",\n   \"FAtransposeX\",\n   \"FAXtranspose\",\n   \"FAtransposeXtranspose\",\n   \"FXtransposePY\",\n   \"FXPYtranspose\",\n   \"FXtransposePYtranspose\",\n   \"FXtransposeMY\",\n   \"FXMYtranspose\",\n   \"FXtransposeMYtranspose\",\n   \"FmeanAbs\",\"Fabs\",\n   \"Fvcat\", \"Fhcat\",\n   \"Fdiagm\", \"FdiagAmultX\", \"FAmultdiagX\",\n   \"FabsAXplusBias\",\n   \"Felu\",\n   \"Fabs\",\n   \"Fkinklin\",\n   \"FkinklinAXplusBias\",\n   \"Falex\",\n   \"Fgetcol\",\n   \"Fgetrow\"\n   ]\n\nfor fn in f\n    include(\"functions/\"*fn*\".jl\");  println(fn);\nend\n\ninclude(\"TrainingAlgorithms.jl\")\n\n\n## Negative function: f(x)=-x\n#Fnegative(x)=(-x,[])\n#Dnegative=Array(Function,1)\n#Dnegative[1]=dnegative1(x,self,aux,t)=-t.*ones(size(x))\n#Dnegative[1]=dnegative1(x::Float32,self,aux,t)=-t\n#Derivative[Fnegative]=Dnegative # Define dictionary lookup\n#export Fnegative\n#export dnegative1 # need for source code execution\n#ADnegative(n)=ADnode(Fnegative,n)\n#export ADnegative\n\n## KL Loss: f(p,q)=KL(p,q)\n#FKLLoss(p::Array{Float32,2},q::Array{Float32,2})=begin DN=prod(size(p));(sum(p.*(log(p)-log(q)))/DN,DN); end\n#DKLLoss=Array(Function,2)\n#DKLLoss[1]=DKLLoss1(p::Array{Float32,2},q::Array{Float32,2},self,aux,t)=t.*(1+log(p)-log(q))/aux\n#DKLLoss[2]=DKLLoss2(p::Array{Float32,2},q::Array{Float32,2},self,aux,t)=t.*(p./q)./aux\n#Derivative[FKLLoss]=DKLLoss\n#export FKLLoss,DKLLoss\n#export DKLLoss1,DKLLoss2 # need for source code execution\n#ADKLLoss(np,nq)=ADnode(FKLLoss,[np nq])\n#export ADKLLoss\n#\n# Multinomial Logistic Loss: -sum(log(p_c)) where p\\propto exp(x) and c is a bit array of the same size as x\n#FMultLogisticLoss(c::BitArray{2},x::Array{Float32,2})=begin DN=prod(size(x));logZ=logsumexp(x);aux=(logZ,DN); return (#(-sum(x[c])+sum(logZ))/DN,aux); end\n#DMultLogisticLoss=Array(Function,2)\n#DMultLogisticLoss[1]=DMultLogisticLoss1(c::BitArray{2},x::Array{Float32,2},self,aux,t)=nan # not needed\n#DMultLogisticLoss[2]=DMultLogisticLoss2(c::BitArray{2},x::Array{Float32,2},self,aux,t)=begin p=zeros(size(c)); p[c]=1.#; return t.*(exp(x.-aux[1])-p)./aux[2]; end\n#Derivative[FMultLogisticLoss]=DMultLogisticLoss\n#export FMultLogisticLoss,DMultLogisticLoss\n#export DMultLogisticLoss1,DMultLogisticLoss2 # need for source code execution\n#ADMultLogisticLoss(nc,nx)=ADnode(FMultLogisticLoss,[nc nx])\n#export ADMultLogisticLoss\n#\n##Logistic Loss: -sum(log(sigma(c.*x)))/prod(size(x)) c[i] is +1 or -1 class variable\n#FLogisticLoss(c::Array{Float32,2},x::Array{Float32,2})=begin DN=prod(size(x)); aux=(1./(1.+exp(-c.*x)),DN); return (-s#um(log(aux[1]))/DN,aux); end\n#DLogisticLoss=Array(Function,2)\n#DLogisticLoss[1]=DLogisticLoss1(c::Array{Float32,2},x::Array{Float32,2},self,aux,t)=-t.*(1.-aux[1]).*x/aux[2]\n#DLogisticLoss[2]=DLogisticLoss2(c::Array{Float32,2},x::Array{Float32,2},self,aux,t)=-t.*(1.-aux[1]).*c/aux[2]\n#\n#FLogisticLoss(c::Array{Float32},x::Array{Float32})=begin DN=prod(size(x)); aux=(1./(1.+exp(-c.*x)),DN); return (-sum(l#og(aux[1]))/DN,aux); end\n#DLogisticLoss=Array(Function,2)\n#DLogisticLoss[1]=DLogisticLoss1(c::Array{Float32,1},x::Array{Float32,2},self,aux,t)=-t.*(1.-aux[1]).*x/aux[2]\n#DLogisticLoss[2]=DLogisticLoss2(c::Array{Float32,1},x::Array{Float32,2},self,aux,t)=-t.*(1.-aux[1]).*c/aux[2]\n#Derivative[FLogisticLoss]=DLogisticLoss\n#export FLogisticLoss,DLogisticLoss\n#export DLogisticLoss1,DLogisticLoss2 # need for source code execution\n#ADLogisticLoss(nc,nx)=ADnode(FLogisticLoss,[nc nx])\n#export ADLogisticLoss\n\n\n## Array subindexing:\n#Fgetcol(x,col)=begin if col>0 tmp=zeros(size(x,1),1); tmp[:]=x[:,col]; return (tmp, zeros(size(x))) else retur#n (zeros(size(x,1)), zeros(size(x))); end; end\n#Dgetcol=Array(Function,2)\n#Dgetcol[1]=dgetcol1(x,col,self,aux,t)=begin if col>0 aux[:,col]=t; return aux; else return zeros(size(x)); end#; end\n#Dgetcol[2]=dgetcol2(x,col,self,aux,t)=[] # can't differentiate wrt col index\n#Derivative[Fgetcol]=Dgetcol\n#export Fgetcol\n#export dgetcol1,dgetcol2 # need for source code execution\n#ADgetcol(n,col)=ADnode(Fgetcol,[n col])\n#export ADgetcol\n\n\n#    md=CuModule(\"gaxpy2.ptx\",false)\n#    gaxpy2=CuFunction(md,\"gaxpy2\")\n#    function gaxpy2!(alpha::CudaArray,B::CudaArray,C::CudaArray)\n#        launch(gaxpy2,size(B,1),size(B,2),(alpha,B,C))\n#    end\n#    export gaxpy2!\n\n#    md=CuModule(\"gaxpy3.ptx\",false)\n#    gaxpy3=CuFunction(md,\"gaxpy3\")\n#    function gaxpy3!(alpha::CudaArray,B::CudaArray,C::CudaArray)\n#        launch(gaxpy3,(size(B,1),size(B,2)),1,(length(B),alpha,B,C))\n#    end\n#    export gaxpy3!\n\n#    md=CuModule(\"gaxpy4.ptx\",false)\n#    gaxpy4=CuFunction(md,\"gaxpy4\")\n#    function gaxpy4!(alpha::CudaArray,B::CudaArray,C::CudaArray)\n#        launch(gaxpy4,(size(B,1),size(B,2)),1024,(length(B),alpha,B,C))\n#    end\n#    export gaxpy4!\n#    export gaxpy4\n\n\n#    md=CuModule(\"serialsum.ptx\",false)\n#    serialsumkernel=CuFunction(md,\"serialsum\")\n#    function serialsum(A::CudaArray)\n#        gy=CudaArray(ones(1,1))\n#        launch(serialsumkernel,1,1,(length(A),A,gy))\n#        return gy\n#    end\n#    export serialsum\n\n", "meta": {"hexsha": "0168d905d2fde45354e43a1ef39d16a4878b9acc", "size": 10483, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/defs.jl", "max_stars_repo_name": "davidbarber/AutoDiff", "max_stars_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2016-03-20T20:52:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T07:31:59.000Z", "max_issues_repo_path": "src/defs.jl", "max_issues_repo_name": "davidbarber/AutoDiff", "max_issues_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-06-17T20:12:48.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-17T20:12:48.000Z", "max_forks_repo_path": "src/defs.jl", "max_forks_repo_name": "davidbarber/AutoDiff", "max_forks_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-01-11T21:36:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-06T21:04:40.000Z", "avg_line_length": 47.2207207207, "max_line_length": 433, "alphanum_fraction": 0.7129638462, "num_tokens": 3264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.771047154759488}}
{"text": "# Question 1: Modifisere binærsøk\n## Binærsøk er en enkel, men viktig algoritme med mange bruksområder. Les om den i appendiks C («Binærsøk») i pensumheftet.\n## Under vises julia-koden for funksjonen bisect_left som er en variant av binærsøk. Denne har noen forskjeller sammenliknet med Bisect-algoritmen fra pensumheftet. Dersom det finnes flere forekomster av v i tabellen, returneres en indeks slik at om v settes inn på denne indeksen, havner elementet direkte til venstre for de andre forekomstene. Dersom v ikke finnes i A er indeksen som returneres slik at v kan settes inn på denne indeksen i sortert rekkefølge.\n\nfunction bisect_left(A, p, r, v)\n    i = p\n    if p < r\n       q = floor(Int, (p+r)/2)  # floor() er en innebygd funksjon som runder ned. ceil() runder opp.\n       if v <= A[q]\n           i = bisect_left(A, p, q, v)\n       else\n           i = bisect_left(A, q+1, r, v)\n       end\n    end\n    return i\nend  \n\n#Implementer funksjonen => bisect_right(A, p, r, v)\n\n\nfunction bisect_right(A, p, r, v)\n    i = p\n    if p < r\n        q = floor(Int, (p+r)/2)\n        if v < A[q]\n            i = bisect_right(A, p, q, v)\n       \telse\n            i = bisect_right(A, q+1, r, v)\n        end\n    end\n    return i\nend\n\nA = [0,1,1,1,2,3,4,5,6,7,8,9]\n\nV = 1\n#@info \"V\" V\n#@info \"index where we want to insert V\"  bisect_left(A,1,length(A)+1,V)\n#@info \"The list is still\" A\n\n@info \"Bisect_left\" bisect_left(A,1,length(A)+1,V) \"should be 2\"\n@info \"Bisect_right\" bisect_right(A,1,length(A)+1,V) \"Should be 5\"\n\n\n", "meta": {"hexsha": "4e50619bdfb15fffd6bba6beb413f008f5e6e753", "size": 1515, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "O3/O3-Workbench.jl", "max_stars_repo_name": "SjoenH/TDT4120-2018", "max_stars_repo_head_hexsha": "fcee77a921cc3437e226d42910848892e3d481a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "O3/O3-Workbench.jl", "max_issues_repo_name": "SjoenH/TDT4120-2018", "max_issues_repo_head_hexsha": "fcee77a921cc3437e226d42910848892e3d481a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "O3/O3-Workbench.jl", "max_forks_repo_name": "SjoenH/TDT4120-2018", "max_forks_repo_head_hexsha": "fcee77a921cc3437e226d42910848892e3d481a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6666666667, "max_line_length": 462, "alphanum_fraction": 0.6429042904, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.771047143808027}}
{"text": "# Hinge loss function\n\nexport SqrHingeLoss\n\n\"\"\"\n**Squared Hinge loss**\n\n  SqrHingeLoss(y, μ=1.0)\n\nReturns the function\n```math\nf(x) = μ⋅∑_i \\\\max\\\\{0, 1 - y_i ⋅ x_i\\\\}^2,\n```\nwhere `y` is an array and `μ` is a positive parameter.\n\"\"\"\nstruct SqrHingeLoss{R <: Real, T <: AbstractArray{R}} <: ProximableFunction\n  y::T\n  mu::R\n  function SqrHingeLoss{R, T}(y::T, mu::R) where {R <: Real, T <: AbstractArray{R}}\n    if mu <= 0\n      error(\"parameter mu must be positive\")\n    else\n      new(y, mu)\n    end\n  end\nend\n\nis_separable(f::SqrHingeLoss) = true\nis_convex(f::SqrHingeLoss) = true\nis_smooth(f::SqrHingeLoss) = true\n\nSqrHingeLoss(b::T, mu::R=1.0) where {R <: Real, T <: AbstractArray{R}} = SqrHingeLoss{R, T}(b, mu)\n\n(f::SqrHingeLoss)(x::T) where {R <: Real, T <: AbstractArray{R}} = f.mu*sum(max.(zero(R), (one(R) .- f.y.*x)).^2)\n\nfunction gradient!(y::AbstractArray{R}, f::SqrHingeLoss{R, T}, x::AbstractArray{R}) where {R <: Real, T}\n\tsum = zero(R)\n\tfor i in eachindex(x)\n\t\tzz = 1-f.y[i]*x[i]\n\t\tz = max(zero(R), zz)\n\t\ty[i] = z .> 0 ? -2*f.mu*f.y[i]*zz : 0\n\t\tsum += z^2\n\tend\n\treturn f.mu*sum\nend\n\nfunction prox!(z::AbstractArray{R}, f::SqrHingeLoss{R, T}, x::AbstractArray{R}, gamma::R=one(R)) where {R, T}\n    v = zero(R)\n    for k in eachindex(x)\n        if f.y[k]*x[k] >= 1\n            z[k] = x[k]\n        else\n            z[k] = (x[k] + 2*f.mu*gamma*f.y[k])/(1+2*f.mu*gamma*f.y[k]^2)\n            v += (1-f.y[k]*z[k])^2\n        end\n    end\n    return f.mu*v\nend\n\nfun_name(f::SqrHingeLoss) = \"squared hinge loss\"\nfun_dom(f::SqrHingeLoss) = \"AbstractArray{Real}\"\nfun_expr(f::SqrHingeLoss) = \"x ↦ μ * sum( max(0,1-b*x_i)^2, i=1,...,n )\"\nfun_params(f::SqrHingeLoss) = \"b = $(typeof(f.y)), μ = $(f.mu)\"\n\nfunction prox_naive(f::SqrHingeLoss{R, T}, x::AbstractArray{R}, gamma::R=one(R)) where {R, T}\n    flag = f.y.*x .<= 1\n    z = copy(x)\n    z[flag] = (x[flag] .+ 2 .* f.mu.*gamma.*f.y[flag])./(1. + 2 .* f.mu.*gamma.*f.y[flag].^2)\n    return z, f.mu*sum(max.(0.0, 1 .- f.y.*z).^2)\nend\n", "meta": {"hexsha": "67812610b1a375fb1301960ea55a9dab4b58b738", "size": 1989, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/sqrHingeLoss.jl", "max_stars_repo_name": "lostella/ProximalOperators.jl", "max_stars_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-15T13:57:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T13:57:52.000Z", "max_issues_repo_path": "src/functions/sqrHingeLoss.jl", "max_issues_repo_name": "lostella/ProximalOperators.jl", "max_issues_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/sqrHingeLoss.jl", "max_forks_repo_name": "lostella/ProximalOperators.jl", "max_forks_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.014084507, "max_line_length": 113, "alphanum_fraction": 0.5696329814, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7710471428577274}}
{"text": "\n# coding: utf-8\n\n# In[1]:\n\n\n#this is a test on how recursion with memory reduces time complexity\n\n\n# In[2]:\n\n\n#this is the fibonacci recursion function without memory\n#it is basically algorithm 101 for any coding language\nfunction fib(n)\n    \n    if n==1\n        return 1\n    elseif n==2\n        return 1\n    elseif n<=0\n        printstyled(\"Invalid input\",color=:red)\n        return\n    else\n        return fib(n-1)+fib(n-2)\n    \n    end\nend\n\n\n# In[3]:\n\n\n#i need a global dictionary to do the memorization\n#or i can change function mmz(n) into mmz(n,memoization)\nglobal memoization=Dict(1=>1,2=>1)\n\n\n# In[4]:\n\n\n#mmz(n) is recursion with memory\n#everytime we do the calculation, we store it in the dictionary\n#i denote the key as the n th fibonacci number\n#the value as the number itself\n#if we can find the key in dictionary\n#we simply return the value\n#if not, we compute and update the dictionary then return the value\nfunction mmz(n)\n    \n    if n<=0\n        printstyled(\"Invalid input\",color=:red)\n        return\n    end    \n    \n    if !(n in keys(memoization))\n        global memoization[n]=mmz(n-1)+mmz(n-2)\n    end\n    \n    return memoization[n]\nend\n\n\n# In[5]:\n\n\n#using ijulia inline magic\n#equivalent to %timeit in ipython\n#0.000093 seconds\n@time begin\n    fib(20)\nend\n\n\n# In[6]:\n\n\n#0.019746 seconds (5.60 k allocations: 335.035 KiB)\n#it seems to be slower\n#but if we compute mmz(30) now\n#its much faster than fib(30)\n@time begin\n    mmz(20)\nend\n\n\n# In[7]:\n\n\n#0.021588 seconds\n@time begin\n    fib(30)\nend\n\n\n# In[8]:\n\n\n#0.000023 seconds (52 allocations: 832 bytes)\n@time begin\n    mmz(30)\nend\n\n", "meta": {"hexsha": "a953563cad40e745b241264cab5ab05a761fe94e", "size": 1604, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "fibonacci with memoization.jl", "max_stars_repo_name": "je-suis-tm/recursion-and-dynamic-programming", "max_stars_repo_head_hexsha": "55a6085cd45b73426379ff947d9a842ef7d325bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-03-22T10:31:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:30:17.000Z", "max_issues_repo_path": "fibonacci with memoization.jl", "max_issues_repo_name": "slowbrain/recursion-and-dynamic-programming", "max_issues_repo_head_hexsha": "1cd77db1e7940fee15fc8aa2cedd3ab84e10374f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fibonacci with memoization.jl", "max_forks_repo_name": "slowbrain/recursion-and-dynamic-programming", "max_forks_repo_head_hexsha": "1cd77db1e7940fee15fc8aa2cedd3ab84e10374f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2019-10-27T12:34:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T13:54:37.000Z", "avg_line_length": 15.4230769231, "max_line_length": 68, "alphanum_fraction": 0.6546134663, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.8705972717658209, "lm_q1q2_score": 0.7710283422680473}}
{"text": "\"\"\"\n    perm_rows(A::AbstractMatrix, p::Vector{Int64})::AbstractMatrix\n\nApply a permutation to the rows of a given Matrix.\nUsed to create corresponding permutation matrices with `A = identity`.\n\"\"\"\nfunction perm_rows(A::AbstractMatrix, p::Vector{Int64})::AbstractMatrix\n    if !isperm(p)\n        throw(\"p is not a permutation.\")\n        return nothing\n    end\n    B = copy(A)\n    for i in 1:length(p)\n        B[i,:] = A[p[i],:]\n    end\n    return B\nend\n\n\"\"\"\n    perm_cols(A::AbstractMatrix, p::Vector{Int64})::AbstractMatrix\n\nApply a permutation to the columns of a given Matrix.\nUsed to create corresponding inverse permutation matrices with `A = identity`.\n\"\"\"\nfunction perm_cols(A::AbstractMatrix, p::Vector{Int64})::AbstractMatrix\n    if !isperm(p)\n        throw(\"p is not a permutation.\")\n        return nothing\n    end\n    B = copy(A)\n    for i in 1:length(p)\n        B[:,i] = A[:,p[i]]\n    end\n    return B\nend\n\n\"\"\"\n    apply_permutation(A::AbstractMatrix, p::Vector{Int64})::AbstractMatrix\n\nApplies a given permutation-vector `p` to the given matrix `A` using the corresponding permutation-matrices.\n\"\"\"\nfunction apply_permutation(A::AbstractMatrix, p::Vector{Int64})::AbstractMatrix\n    if !isperm(p)\n        throw(\"p is not a permutation.\")\n        return nothing\n    end\n    n = length(p)\n    if size(A, 1) != n || size(A,2) != n\n        throw(\"Only square matrices allowed with the same number of rows/columns as the permutation.\")\n        return nothing\n    end\n    I = id(n)\n    P = perm_rows(I, p)\n    P_inv = perm_cols(I,p)\n    return P * A * P_inv\nend\n\n\"\"\"\n    print_permutation_cycles(labelled_list::Bijection{String, T}, permutations::Vector{Vector{Int64}}, filename_identifier::String; filename_prefix=\"permutation_cycles_\") where T\n\nApplies all given permutations to all given labelled elements and prints out the permutation cycles using the labels. \nThe output is redirected and appended to a file `filename_prefix * filename_identifier * \".txt\"`, e.g. `\"permutation_cycles_1.txt\"`\n\"\"\"\nfunction print_permutation_cycles(labelled_list::Bijection{String, T}, permutations::Vector{Vector{Int64}}, filename_identifier::String; filename_prefix=\"permutation_cycles_\") where T\n    # construct the filename\n    filename = filename_prefix * filename_identifier * \".txt\"\n    n = length(permutations[1])\n    # start output in \"append\" mode\n    open(filename, \"a\") do io\n        for k in sort(String.(keys(labelled_list)))\n            for i in 1:length(permutations)\n                el_prev = labelled_list[k]\n                found = String[]\n                cond = true\n                I = id(n)\n                p = permutations[i]\n                P = perm_rows(I, p)\n                P_inv = perm_cols(I,p)\n                \n                print(io, \"p[$i]: \" * k)\n                push!(found, k)\n                while cond\n                    el = P * el_prev * P_inv\n                    lbl = labelled_list(el)\n                    print(io, \" → \" * lbl)\n                    if lbl in found\n                        cond = false\n                    end\n                    push!(found, lbl)\n                    el_prev = el\n                end\n                println(io,\"\")\n            end\n        end\n    end\nend", "meta": {"hexsha": "ce3dc1871c29a777f3573cdd1dd1230092f5c37b", "size": 3226, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/permutations.jl", "max_stars_repo_name": "Fhoeddinghaus/AntiIdClosedGroup.jl", "max_stars_repo_head_hexsha": "47576926259d8fc27128fab8b9c0b03d70b653c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/permutations.jl", "max_issues_repo_name": "Fhoeddinghaus/AntiIdClosedGroup.jl", "max_issues_repo_head_hexsha": "47576926259d8fc27128fab8b9c0b03d70b653c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/permutations.jl", "max_forks_repo_name": "Fhoeddinghaus/AntiIdClosedGroup.jl", "max_forks_repo_head_hexsha": "47576926259d8fc27128fab8b9c0b03d70b653c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6041666667, "max_line_length": 183, "alphanum_fraction": 0.5976441414, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.8856314632529872, "lm_q1q2_score": 0.7710283386714947}}
{"text": "# ---\n# title: 1103. Distribute Candies to People\n# id: problem1103\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Easy\n# categories: Math\n# link: <https://leetcode.com/problems/distribute-candies-to-people/description/>\n# hidden: true\n# ---\n# \n# We distribute some number of `candies`, to a row of **`n = num_people`**\n# people in the following way:\n# \n# We then give 1 candy to the first person, 2 candies to the second person, and\n# so on until we give `n` candies to the last person.\n# \n# Then, we go back to the start of the row, giving `n + 1` candies to the first\n# person, `n + 2` candies to the second person, and so on until we give `2 * n`\n# candies to the last person.\n# \n# This process repeats (with us giving one more candy each time, and moving to\n# the start of the row after we reach the end) until we run out of candies.  The\n# last person will receive all of our remaining candies (not necessarily one\n# more than the previous gift).\n# \n# Return an array (of length `num_people` and sum `candies`) that represents the\n# final distribution of candies.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: candies = 7, num_people = 4\n#     Output: [1,2,3,1]\n#     Explanation:\n#     On the first turn, ans[0] += 1, and the array is [1,0,0,0].\n#     On the second turn, ans[1] += 2, and the array is [1,2,0,0].\n#     On the third turn, ans[2] += 3, and the array is [1,2,3,0].\n#     On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: candies = 10, num_people = 3\n#     Output: [5,2,3]\n#     Explanation:\n#     On the first turn, ans[0] += 1, and the array is [1,0,0].\n#     On the second turn, ans[1] += 2, and the array is [1,2,0].\n#     On the third turn, ans[2] += 3, and the array is [1,2,3].\n#     On the fourth turn, ans[0] += 4, and the final array is [5,2,3].\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * 1 <= candies <= 10^9\n#   * 1 <= num_people <= 1000\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "a091f5a3e93d2260eca203e74aad442f05170315", "size": 2078, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1103.distribute-candies-to-people.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/unresolved/1103.distribute-candies-to-people.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/unresolved/1103.distribute-candies-to-people.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 29.2676056338, "max_line_length": 111, "alphanum_fraction": 0.6183830606, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.870597271765821, "lm_q2_score": 0.8856314662716159, "lm_q1q2_score": 0.7710283383260326}}
{"text": "# This file includes node dynamics \n\nabstract type AbstractNode end\n\n\"\"\"\n    $TYPEDEF\n\nLorenz dyanmics \n\n# Fields \n\n    $TYPEDFIELDS\n\"\"\"\n@kwdef mutable struct Lorenz <: AbstractNode\n    σ::Float64 = 10.0\n    β::Float64 = 8 / 3\n    ρ::Float64 = 35.0\n    x::Vector{Float64} = rand(3)\n    t::Float64 = 0.0\nend\n\nfunction (node::Lorenz)(dx, x, u, t)\n    dx[1] = node.σ * (x[2] - x[1])\n    dx[2] = x[1] * (node.ρ - x[3]) - x[2]\n    dx[3] = x[1] * x[2] - node.β * x[3]\nend\n\ndimension(::Type{Lorenz}) = 3\n\n\"\"\"\n    $TYPEDEF\n\nRossler dyanmics \n\n# Fields \n\n    $TYPEDFIELDS\n\"\"\"\n@kwdef mutable struct Rossler <: AbstractNode\n    a::Float64 = 0.2\n    b::Float64 = 0.2\n    c::Float64 = 5.7\n    x::Vector{Float64} = rand(3)\n    t::Float64 = 0.0\nend\n\nfunction (node::Rossler)(dx, x, u, t)\n    dx[1] = -x[2] - x[1]\n    dx[2] = x[1] + node.a * x[2]\n    dx[3] = node.b + x[3] * (x[1] - node.c)\nend\n\ndimension(::Type{Rossler}) = 3\n\n# Piecewise Chua diode \n@kwdef struct Diode\n    a::Float64 = -8 / 7\n    b::Float64 = -5 / 7\nend\n\nfunction (diode::Diode)(x)\n    if x > 1\n        diode.b * x + diode.a - diode.b\n    elseif abs(x) ≤ 1\n        diode.a * x\n    else\n        diode.b * x - diode.a + diode.b\n    end\nend\n\n@kwdef mutable struct Chua <: AbstractNode\n    diode::Diode = Diode()\n    α::Float64 = 9.0\n    β::Float64 = 100 / 7\n    x::Vector{Float64} = 1e-3 * rand(3)\n    t::Float64 = 0.00\nend\n\nfunction (ds::Chua)(dx::AbstractVector, x::AbstractVector, u, t)\n    dx[1] = ds.α * (x[2] - x[1] - ds.diode(x[1]))\n    dx[2] = x[1] - x[2] + x[3]\n    dx[3] = -ds.β * x[2]\nend\n", "meta": {"hexsha": "5a1101466395388ba665345d1e343917c0fb3fc1", "size": 1551, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nodes.jl", "max_stars_repo_name": "zekeriyasari/DynamicalNetworks.jl", "max_stars_repo_head_hexsha": "c890bdfc8c8d703fef67106092190ff3b540f370", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-09T06:25:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-22T21:20:21.000Z", "max_issues_repo_path": "src/nodes.jl", "max_issues_repo_name": "zekeriyasari/DynamicalNetworks.jl", "max_issues_repo_head_hexsha": "c890bdfc8c8d703fef67106092190ff3b540f370", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-05-24T21:52:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-20T11:33:03.000Z", "max_forks_repo_path": "src/nodes.jl", "max_forks_repo_name": "zekeriyasari/DynamicalNetworks.jl", "max_forks_repo_head_hexsha": "c890bdfc8c8d703fef67106092190ff3b540f370", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.4642857143, "max_line_length": 64, "alphanum_fraction": 0.5415860735, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771663, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7710168847185028}}
{"text": "\"\"\"\n    Const <: Kernel\n\nConstant kernel\n```math\nk(x,x') = σ²\n```\nwith signal standard deviation ``σ``.\n\"\"\"\nmutable struct Const{T} <: Kernel where {T<:Real}\n    \"Signal variance\"\n    σ2::T\n    \"Priors for kernel parameters\"\n    priors::Array\nend\n\n\"\"\"\nConstant kernel function\n    \n    Const(lσ::T)\n\n# Arguments\n  - `lσ::Real`: signal standard deviation (given on log scale)  \n\"\"\"\nConst(lσ::T) where T = Const{T}(exp(2 * lσ), [])\n\nfunction set_params!(cons::Const, hyp::AbstractVector)\n    length(hyp) == 1 || throw(ArgumentError(\"Constant kernel has one parameter, received $(length(hyp)).\"))\n    cons.σ2 = exp(2.0*hyp[1])\nend\n\nget_params(cons::Const{T}) where T = T[log(cons.σ2)/2.0]\nget_param_names(cons::Const) = [:lσ]\nnum_params(cons::Const) = 1\n\ncov(cons::Const) = cons.σ2\nfunction cov(cons::Const, x::AbstractVector, y::AbstractVector)\n    return cov(cons)\nend\n\n@inline dk_dlσ(cons::Const) = 2.0*cov(cons)\n@inline function dKij_dθp(cons::Const, X1, X2, i::Int, j::Int, p::Int, dim::Int)\n    if p == 1\n        return dk_dlσ(cons)\n    else\n        return NaN\n    end\nend\n", "meta": {"hexsha": "23bfdf2e5a058c0fd7eab6123386db278b940cc6", "size": 1076, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/const.jl", "max_stars_repo_name": "mcusi/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 284, "max_stars_repo_stars_event_min_datetime": "2015-07-31T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T07:08:58.000Z", "max_issues_repo_path": "src/kernels/const.jl", "max_issues_repo_name": "mcusi/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 171, "max_issues_repo_issues_event_min_datetime": "2015-05-28T12:04:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T06:48:23.000Z", "max_forks_repo_path": "src/kernels/const.jl", "max_forks_repo_name": "mcusi/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-05-31T12:44:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:21:38.000Z", "avg_line_length": 21.9591836735, "max_line_length": 107, "alphanum_fraction": 0.6394052045, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.771016881872962}}
{"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 065a1e67-6b63-43df-9d6d-303af08d8434\nbegin\n\tusing Pkg\n\tPkg.activate(joinpath(Pkg.devdir(), \"MLCourse\"))\n    using PlutoUI\n    PlutoUI.TableOfContents()\nend\n\n# ╔═╡ 034f7cc2-eacd-11eb-29e2-810a573295cf\nusing LinearAlgebra\n\n# ╔═╡ 034f7c90-eacd-11eb-1b40-8722209689fa\nusing DataFrames # load the DataFrames package\n\n# ╔═╡ 034f7d1a-eacd-11eb-1d48-591daf597cd6\nusing Random\n\n# ╔═╡ 034f7d3a-eacd-11eb-1144-65f9acfcf24c\nbegin\n\tusing Plots\n\tplotly()\nend\n\n# ╔═╡ 034f7d58-eacd-11eb-3189-bff16ec27739\nusing Distributions\n\n# ╔═╡ 034f7d76-eacd-11eb-24cc-fd8d53d736c2\nusing Statistics\n\n# ╔═╡ d6e5fe02-21a5-486c-a237-878be1d95439\nbegin\n    using MLCourse\n    MLCourse.list_notebooks(@__FILE__)\nend\n\n# ╔═╡ f3508747-da29-47c9-a98e-22ea15caaf2f\nMarkdown.parse(\"Hi and welcome to an introduction to the Julia programming language.\n\n$(haskey(ENV, \"html_export\") ? \"This page was created with an interactive [Pluto notebook](https://plutojl.org/). If you want to run it locally on your machine, follow the instructions [here](https://github.com/jbrea/MLCourse).\" :\n\"This is an interactive Pluto notebook. You can create new cells by clicking any \\\"+\\\" above or below existing cells. In these cells you can write code and run it by clicking the play button or [Shift] + [Enter] on your keyboard (or [Ctrl] + [Enter]).\nThe output gets displayed above the cell. Have a look at [this website](https://plutojl.org/) if you want to learn more about Pluto notebooks.\n\nTo get help, please open the Live docs at the bottom right of this page and click on the code you want to get help for. For example, click on the ÷ symbol in the 8th cell below.\")\n\nIf you want to learn more about Julia visit [julialang.org](https://julialang.org).\nIn the following sections you find links to different chapters of the [manual](https://docs.julialang.org/en/v1/). There is also this [cheat sheet](https://juliadocs.github.io/Julia-Cheat-Sheet/).\")\n\n# ╔═╡ d92c0729-c7ab-42cc-b713-30f00e237833\nmd\"# Mathematical Operations\n\nHere is the [link](https://docs.julialang.org/en/v1/manual/mathematical-operations/) to the respective section in the Julia manual.\"\n\n# ╔═╡ b8630ee9-d2c0-4cd0-b3f7-77f66e997a80\n\n\n# ╔═╡ 034f7b46-eacd-11eb-1aa2-f380d08206cc\n1 + 2\n\n# ╔═╡ 034f7b64-eacd-11eb-1618-6de6def66405\n2 * 3\n\n# ╔═╡ 034f7b6e-eacd-11eb-1733-650ad4da2730\n3 ^ 2\n\n# ╔═╡ 034f7b78-eacd-11eb-003a-5b5801c19d80\n3 == 9 / 3 # test for equality\n\n# ╔═╡ 034f7b6e-eacd-11eb-184a-d504fab31681\n4 / 3 # compute the fraction as a floating point number\n\n# ╔═╡ fb3677a9-1610-49dd-96e4-3bd7badc58db\n4 // 3 # leave the fraction as a fraction\n\n# ╔═╡ 884f568b-079c-47d6-a597-34b67925f195\n4//3 * 3//2 * 1//7 # simplify fractions\n\n# ╔═╡ 034f7b84-eacd-11eb-2836-11cebedb05b9\n5 ÷ 2 # Write this symbol with \\div [TAB]. Try it in a new cell!\n\n# ╔═╡ 52efdece-3c21-43d4-a826-3b96e3a23e60\nmd\"# Variables and Simple Functions\n\nSee also [here](https://docs.julialang.org/en/v1/manual/variables/).\"\n\n# ╔═╡ 034f7ba0-eacd-11eb-3fc1-9dca0e072755\nx = 2\n\n# ╔═╡ 034f7ba0-eacd-11eb-23ae-cd327563ec60\ny = 4.5\n\n# ╔═╡ 034f7ba0-eacd-11eb-3347-49deb13761d9\nz = x * y\n\n# ╔═╡ 121b3dbb-f86c-44b8-8b0f-f6b4d0b9992f\nmd\"In the following cells we apply simple built-in functions to the variables defined above. If you change the values of these variables, the output of the cells below will also change, thanks to the reactivity of this notebook. Try it by assigning another value to `x` in the cell above.\"\n\n# ╔═╡ 034f7baa-eacd-11eb-33f2-5f619e4a7832\nsin(x)\n\n# ╔═╡ 034f7bb2-eacd-11eb-006b-7b935e35af66\nexp(x)\n\n# ╔═╡ 034f7bb2-eacd-11eb-214b-cbfc83965c26\nlog(x)\n\n# ╔═╡ ec1dd4c4-d61d-4fdb-b576-3fe3b059eb3a\ntypeof(2)\n\n# ╔═╡ 1a3387ee-b59d-49d7-9cca-2a8bd04eaaad\ntypeof(2.0)\n\n# ╔═╡ 034f7b96-eacd-11eb-0c81-ad33210de120\ntypeof(4//3)\n\n# ╔═╡ 034f7b96-eacd-11eb-2ee1-cd8e6813a726\ntypeof(2f0)\n\n# ╔═╡ 0f4e3f45-71dd-41b2-a0b3-c55a04ace61f\nmd\"In the following cells you see 3 different ways to define custom functions. See also [here](https://docs.julialang.org/en/v1/manual/functions/), and, in particular, [here](https://docs.julialang.org/en/v1/manual/functions/#man-anonymous-functions) for anonymous functions.\"\n\n# ╔═╡ 034f7bbe-eacd-11eb-2e95-a93ad2d5e867\nmyfunc(x, y) = 2 * x + 3 - y # creates a new function called `myfunc`\n\n# ╔═╡ 034f7bbe-eacd-11eb-2c36-d3949367ce5a\nmyfunc(x, y)\n\n# ╔═╡ e0ec7ba3-4858-4572-994d-953caa98080b\nanonfunc = x -> x^2 # creates an anonymous function called `anonfunc`\n\n# ╔═╡ 04da39a1-e3bc-4086-b555-6cea2cf1689d\nanonfunc(4)\n\n# ╔═╡ 034f7bc8-eacd-11eb-0396-5b743b505b2a\nfunction longfunc(x, y)\n    tmp = x + y\n    tmp ^ 2 - 0.25 # the result of the last line is the output\nend\n\n# ╔═╡ 034f7bc8-eacd-11eb-31f9-c119d1dfb8a5\nlongfunc(x, y)\n\n# ╔═╡ ce3c7687-c7a9-4b5d-9a55-51514ed90fd9\nmd\"We will sometimes use the pipe operator to chain functions.\"\n\n# ╔═╡ 034f7bd2-eacd-11eb-28f3-b707012e1db0\nx |> sin |> exp |> log10\n\n# ╔═╡ 034f7bd2-eacd-11eb-1789-7380a89d5339\nlog10(exp(sin(x)))\n\n# ╔═╡ 034f7cd6-eacd-11eb-0f8c-11179c3ab480\nmd\" # Strings and Markdown\n\nSee also [here](https://docs.julialang.org/en/v1/manual/strings/)\nand [here](https://docs.julialang.org/en/v1/stdlib/Markdown/).\n\"\n\n# ╔═╡ 034f7cd6-eacd-11eb-0f8c-11179c3ab48f\ns1 = \"Hi! \"\n\n# ╔═╡ 034f7ce0-eacd-11eb-3c49-e39b8d3e917f\ns2 = \"Welcome to Machine Learning\"\n\n# ╔═╡ 034f7ce0-eacd-11eb-18a1-bd2d1849b9bc\ns1 * s2\n\n# ╔═╡ 034f7cec-eacd-11eb-3262-bdc0f2e13a3a\ns1 ^ 3 * s2\n\n# ╔═╡ 034f7cec-eacd-11eb-27da-9bb861643df2\nsplit(s2)\n\n# ╔═╡ 832ce046-ab34-4623-9d02-793dc5748208\nmd\"Sometimes we want to paste something computed into a string. This is called [interpolation](https://docs.julialang.org/en/v1/manual/strings/#string-interpolation).\"\n\n# ╔═╡ 91b0de0c-221c-468e-9077-5233aedeb4ca\nanswer = 42\n\n# ╔═╡ 0c7ae3ec-a40f-4e3e-85d8-3f79f091e3b4\n\"The answer is $answer.\" # we interpolate with the dollar sign\n\n# ╔═╡ 732ae082-b90f-4108-9872-36077fb2c54c\nmd\"Whenever you see just text here, it is actually the output of a markdown cell.\nMarkdown cells can be written in two ways: either as a markdown string `md\\\"this is a markdown string\\\"` (note the trailing `md`) or as `Markdown.parse(\\\"this is a markdown string\\\")`.\nYou can look at the code of this cell by toggling its visibility with the \\\"eye\\\"\nbutton on the left. For you to take notes, it may be useful to know some of the\nmarkdown features. We look at some in the cell below.\n\"\n\n# ╔═╡ 6bfb60b4-964e-46ec-adc2-ec9e9a0f8158\nmd\"#### This is a fourth level header\n\n[This is a link](https://docs.julialang.org/en/v1/)\n\n- here we have a list\n- of multiple items\n   1. with different levels.\n   1. The number you put here doesn't matter.\n   0. The markdown interpreter knows how to count.\n\nBelow you see a Julia code block:\n\n```julia\nmy_fancy_function(x) = x^x # here I define my function\nmy_fancy_function(3) == 27\n```\n\nand here is the same thing in python:\n\n```python\ndef my_fancy_function(x): # here I define my function\n    return x**x\n\nmy_fancy_function(3) == 27\n```\n\nThis is a formula ``E = mc^2``.\n\nAnd below we have some nicely colored text boxes.\n\n!!! note\n\n    Sometimes I just note random stuff.\n\n!!! tip\n\n    It is useful to know markdown.\n\n!!! warning \\\"Don't forget the exercises!\\\"\n\n    No pain, no gain!\n\n!!! danger \\\"Machine Learning Can Be Addictive\\\"\n\n    Rumours say that in the past there were students that liked their first\n    Machine Learning course so much that they decided to pursue a career in\n    Machine Learning.\n\"\n\n# ╔═╡ 0efb1f1a-8051-4843-aa68-1f4ad8618f92\nmd\"# Vectors, Matrices and Arrays\n\nSee also [here](https://docs.julialang.org/en/v1/manual/arrays/).\"\n\n# ╔═╡ 034f7bdc-eacd-11eb-1999-9b62efdb4128\nv = [1, 2, 3] # this is a vector\n\n# ╔═╡ 034f7cba-eacd-11eb-2f1a-836ccc185dd9\npush!(v, 12)\n\n# ╔═╡ 034f7cba-eacd-11eb-3901-2bc3d0ff0e39\npop!(v)\n\n# ╔═╡ 50d83a01-f4c5-45c1-9c81-ed71d8313642\nmd\"If you wonder about the ! in the function names: have a look [here](https://docs.julialang.org/en/v1/manual/style-guide/#bang-convention).\"\n\n# ╔═╡ 034f7bfa-eacd-11eb-1839-371285e2c6ed\nw = [1 2 3] # this is a matrix with 1 row and 3 columns\n\n# ╔═╡ 034f7be4-eacd-11eb-1616-2df92f244e73\nv[1] # access to the first element of the vector\n\n# ╔═╡ 034f7bf0-eacd-11eb-0b3f-69f172657051\nv[2] = 4 # assign value 4 to the second element of the vector\n\n# ╔═╡ 034f7bf0-eacd-11eb-012e-997132cd41c6\nv # here we check that the second element is indeed 4 now\n\n# ╔═╡ 034f7bfa-eacd-11eb-2bf8-c795453a8959\nm = [1 2 3\n     4 5 6\n     7 8 9] # this is a 3 x 3 matrix.\n\n# ╔═╡ 034f7c04-eacd-11eb-3448-832bd75c3356\nm[3, 2] # accessing the element in the 3 row, second column\n\n# ╔═╡ 9c34e4ef-4eba-459f-a7ff-b20708155e65\nm' # transpose the matrix\n\n# ╔═╡ e576bf44-9cc1-4053-b40f-b82c8c39c89d\nmd\"Any function can be applied element-wise to arrays using the [dot syntax](https://docs.julialang.org/en/v1/manual/functions/#man-vectorized).\"\n\n# ╔═╡ 034f7c0e-eacd-11eb-114f-9dbad3e74dd6\nsin.(v)\n\n# ╔═╡ 034f7c0e-eacd-11eb-1b73-27539a68f26d\nexp.(m)\n\n# ╔═╡ 034f7c16-eacd-11eb-0d0b-518b28558fda\nv .+ 3\n\n# ╔═╡ 034f7c16-eacd-11eb-2cb0-8b1198bfcb78\nmyfunc.(v, v)\n\n# ╔═╡ 034f7ccc-eacd-11eb-1613-cbdf2386b60b\nm * v  # matrix vector multiplication\n\n# ╔═╡ 034f7ccc-eacd-11eb-2ab4-599e0ed86304\nv' * v # inner product\n\n# ╔═╡ 034f7cd6-eacd-11eb-37bb-f1930f2f2772\neigvals(m) # compute the Eigen values\n\n# ╔═╡ c997a07f-bc89-4c29-9945-62046b6889d2\nmd\"To concatenate vectors and matrices we have the following syntax (see also [here](https://docs.julialang.org/en/v1/manual/arrays/#man-array-concatenation)).\"\n\n# ╔═╡ 07fd5baf-ae0b-4e74-97a6-5a6e14644122\n[[1, 2, 3]; [77, 88, 99]] # the semicolon concatenates the two vectors\n\n# ╔═╡ 11422ca4-c096-4167-aa53-de312615348e\nmd\"The same can be achieved with\"\n\n# ╔═╡ 0ace8c81-e481-4323-9b20-116de412330a\nvcat([1, 2, 3], [77, 88, 99])\n\n# ╔═╡ 5d09ccbf-5a51-41f7-a7ef-84cf2cc5fa1f\n[[1, 2, 3] [77, 88, 99]] # alternatively you can use hcat([1, 2, 3], [77, 88, 99])\n\n# ╔═╡ 9fd6e8c1-7b84-4d76-abef-9e3da4a56dc7\nmd\"Sometimes it is easier to construct a vector or matrix with [comprehension](https://docs.julialang.org/en/v1/manual/arrays/#man-comprehensions).\"\n\n# ╔═╡ e33c0eea-4f5c-4fc8-800d-fa16335eedd0\n[i^2 for i in [3, 4, 9, 7]]\n\n# ╔═╡ 315e5a3b-dc28-4c3b-8fc2-3442cb7590be\n[i^2 for i in [3, 4, 9, 7] if isodd(i)]\n\n# ╔═╡ 45deab46-9a8c-4d22-9460-980a3900396f\n[\"$i, $j\" for i in 1:5, j in 1:5] # see string interpolation above for the $\n\n# ╔═╡ b91eda3c-95cb-4372-9c6b-03fa6a6b02b2\nmd\"# Ranges\n\nSee also [here](https://docs.julialang.org/en/v1/base/math/#Base.::).\"\n\n# ╔═╡ 034f7c16-eacd-11eb-3877-6ba06a933698\ncollect(1:10) # 1:10 is a range; the function `collect` turns it into a vector\n\n# ╔═╡ 034f7c22-eacd-11eb-3ab7-b30813d11e94\nr1 = 1:.1:10 # a range from 1 to 10 with step-size 0.1\n\n# ╔═╡ 034f7c2c-eacd-11eb-1aae-97b030af71e9\nr3 = 10:-.1:1 # a range from 10 to 1 with step-size -0.1\n\n# ╔═╡ 034f7c2c-eacd-11eb-1f56-052874c5c6ab\ncollect(r3)\n\n# ╔═╡ 034f7c36-eacd-11eb-0188-cd307154555c\nexp.(r1) # apply exp to the range\n\n# ╔═╡ 034f7c40-eacd-11eb-26d9-956b65235a10\nv[2:3] # you can use ranges to access multiple elements of a vector or matrix\n\n# ╔═╡ 4237f5df-208d-44c4-90d7-db0efbe7b710\nv[[1, 3]] # a vector of indices can also be used\n\n# ╔═╡ 034f7c40-eacd-11eb-1beb-bb9e9bb325db\nv[2:end]\n\n# ╔═╡ 034f7c4a-eacd-11eb-0de4-537297318c85\nv[begin:2]\n\n# ╔═╡ 034f7c4a-eacd-11eb-03ed-bfc7b532501b\nm[:, 2] # the colon : alone is a short-hand for begin:end\n\n# ╔═╡ 034f7c54-eacd-11eb-2918-ef8f2befddc1\nm[1:2, 2:3]\n\n# ╔═╡ 034f7c54-eacd-11eb-2fe9-5330d3cd3cd5\nfunction is_larger_than_10(x)\n\tresult = \"\"\n    for i in 1:10 # ranges are useful to construct for loops\n        if x < i\n            return result * \" is smaller than 10\"\n        else\n            result *= \"|\"\n        end\n    end\n    result * \"... is larger than 10\"\nend\n\n# ╔═╡ 034f7c5e-eacd-11eb-24c6-d7e7213a7a5e\nis_larger_than_10(4)\n\n# ╔═╡ 034f7c5e-eacd-11eb-1ff7-55f09fb796fe\nis_larger_than_10(78)\n\n# ╔═╡ d9ad1d6d-a3b5-4a83-bda9-05ee43ded9d6\nmd\"# Tuples\n\nSee also [here](https://docs.julialang.org/en/v1/manual/functions/#Tuples).\"\n\n# ╔═╡ 034f7c68-eacd-11eb-1e11-d77379c677c8\nt = (2, 3, 4., \"bla\")\n\n# ╔═╡ 034f7c68-eacd-11eb-12e6-51022c54f6ed\ntypeof(t)\n\n# ╔═╡ 034f7c72-eacd-11eb-28a5-d7d6f3b9f75a\nt[1]\n\n# ╔═╡ 034f7c72-eacd-11eb-1cc2-91eaa2de5e25\nt[4]\n\n# ╔═╡ 034f7c7c-eacd-11eb-1aaa-297c951dd8cd\nnt = (year = 1789,\n\t  event = \"French Revolution\",\n\t  slogan = \"liberté, égalité, fraternité\")\n\n# ╔═╡ 034f7c88-eacd-11eb-28f2-c1c7e05279c6\ntypeof(nt)\n\n# ╔═╡ 034f7c88-eacd-11eb-14fe-b3d49ff91622\nnt.year\n\n# ╔═╡ 034f7c90-eacd-11eb-0d1c-5dbd7b62d55c\nnt.slogan\n\n# ╔═╡ df8588cb-400b-4423-9766-e6cac2c9717a\nmd\"# DataFrames\n\nDataFrames are tables with named columns.\nWe will constantly use DataFrames to organize data.\nSee also [the documentation of the DataFrames.jl package](https://dataframes.juliadata.org/stable/).\"\n\n# ╔═╡ 034f7c9a-eacd-11eb-2e85-29c5bffbc39a\ndf = DataFrame(year = [1789, 1863],\n               event = [\"French Revolution\", \"Foundation of Red Cross\"],\n               slogan = [\"liberté, égalité, fraternité\", missing])\n\n# ╔═╡ 034f7cae-eacd-11eb-39dc-ab39e97cc716\npush!(df, [1789,\n           \"George Washington becomes first president of the USA\",\n           \"Deeds, not Words.\"]) # append a new row to the already created dataframe\n\n# ╔═╡ 034f7c9a-eacd-11eb-3aee-0bab7ab5d502\ndf.year\n\n# ╔═╡ 034f7ca4-eacd-11eb-2f3b-c1dd9be6ad84\ndf[:, 1] # we can also access columns like for matrices\n\n# ╔═╡ 034f7ca4-eacd-11eb-054e-1f930c99d304\ndropmissing(df) # removes all rows with missing entries.\n\n# ╔═╡ 034f7cae-eacd-11eb-38c0-57df4ba09992\ndf[1, :] # show the first row\n\n# ╔═╡ 034f7cc2-eacd-11eb-0f0f-ff16d1ac454b\ndf[df.year .== 1789, [:year, :slogan]] # select all rows where year == 1789 and columns year and slogan\n\n# ╔═╡ 034f7cf4-eacd-11eb-302f-55b164df3b90\nmd\"# Random Numbers\n\nSee also [here](https://docs.julialang.org/en/v1/stdlib/Random/).\n\"\n\n# ╔═╡ 034f7cf4-eacd-11eb-302f-55b164df3b9f\nrand() # a sample from the uniform distribution over the interval [0, 1).\n\n# ╔═╡ 034f7cf4-eacd-11eb-003c-133f34cca508\nrand() # different number than in the cell above.\n\n# ╔═╡ 034f7cfe-eacd-11eb-2514-4b6fdbc42e8f\nrand(10)\n\n# ╔═╡ 034f7d08-eacd-11eb-2694-51c1baa997e6\nrand(3, 3)\n\n# ╔═╡ 034f7d12-eacd-11eb-1673-c94969427bbf\nrandn() # a sample from the normal distribution with mean 0 and variance 1\n\n# ╔═╡ 034f7d12-eacd-11eb-261c-a5de2f06f420\nrand((:bla, \"bli\", 3, 1.2))\n\n# ╔═╡ 034f7d1a-eacd-11eb-1e34-21d5eef62940\nRandom.seed!(123) # sets the seed of the random number generator to 123\n\n# ╔═╡ 034f7d26-eacd-11eb-066c-538e5b614536\nrand()\n\n# ╔═╡ 034f7d30-eacd-11eb-081f-970c4daee184\nRandom.seed!(123) # resets the seed\n\n# ╔═╡ 034f7d30-eacd-11eb-0b09-7b3b9ac47570\nrand() # same result as when `rand()` was called last time.\n\n# ╔═╡ 034f7d3a-eacd-11eb-3fbe-6dc4ab1efd50\nmd\"# Plotting\n\nSee also the [documentation of the Plots.jl package](http://docs.juliaplots.org/latest/)\n\"\n\n# ╔═╡ 034f7d3a-eacd-11eb-3fbe-6dc4ab1efd56\nplot(1:4, rand(4))\n\n# ╔═╡ 034f7d3a-eacd-11eb-1ef3-4f89b8e5aee9\nscatter(rand(100), rand(100))\n\n# ╔═╡ 034f7d44-eacd-11eb-0ab2-2f0d2caed9d6\nwith_terminal(plotattr) # get some help on plotting attributes\n\n# ╔═╡ 034f7d4c-eacd-11eb-3960-d10d1c16075d\nwith_terminal(plotattr, :Series)\n\n# ╔═╡ 034f7d4c-eacd-11eb-3841-97ca37e34c9f\nwith_terminal(plotattr, :Series, \"label\")\n\n# ╔═╡ 034f7d58-eacd-11eb-123f-9b563a7ae27e\nscatter(rand(100), rand(100), label = \"my data\", xlabel = \"X1\", ylabel = \"X2\")\n\n# ╔═╡ 4ca1cd98-a24b-491f-b9ac-28a7daf96d50\nmd\"To compose figures with multiple elements, you can use the `!` version of the plotting functions\"\n\n# ╔═╡ 65e73d27-3709-4894-87ab-432343d314c6\nbegin # we use begin to write a cell with multiple lines\n\tscatter(1:50, sqrt.(1:50) .+ randn(50), label = \"data points\")\n\tplot!(sqrt, color = :red, label = \"square root function\")\nend\n\n# ╔═╡ 9f69c2ab-2940-40ce-b164-07bfa6cc1697\nmd\"Instead of `begin`-`end`-blocks we will also use `let`-`end`-blocks. Variables computed in `let`-blocks are local to that cell, whereas variables defined in `begin`-blocks are global and can be accessed by other cells. (With the `;` at the end of the cell we suppress the output).\"\n\n# ╔═╡ e7ed9e83-7f17-4d9a-a49b-e87bc0747035\nbegin\n\ta_global_variable = 17\n\tanother_global_variable = \"Hi\"\nend;\n\n# ╔═╡ 0d66592a-d098-4ab5-9323-503db8fc73f6\na_global_variable * 3\n\n# ╔═╡ a9a3f29e-4931-4464-9bc5-af6598815f24\n\"$another_global_variable there!\"\n\n# ╔═╡ 6e65247f-b285-49e5-a16e-31b4541225bf\nlet\n\ta_local_variable = 17\n\tanother_local_variable = \"Hi\"\nend;\n\n# ╔═╡ fcd77620-f18a-499b-87c4-fffaa876e59f\na_local_variable * 3\n\n# ╔═╡ 034f7d62-eacd-11eb-3840-51c0622eb8a0\nmd\"# Distributions\n\nSee also the [documentation of the Distributions.jl package](https://juliastats.org/Distributions.jl/stable/)\n\"\n\n# ╔═╡ 034f7d62-eacd-11eb-3840-51c0622eb8a9\nd1 = Normal(3, 2.5)\n\n# ╔═╡ 034f7d6c-eacd-11eb-0eb6-277bf88c13d3\nrand(d1) # draw a sample from this normal distribution\n\n# ╔═╡ 034f7d6c-eacd-11eb-2792-d773a2c77cb6\nrand(d1, 10) # draw 10 samples from this distriution\n\n# ╔═╡ 034f7d6c-eacd-11eb-0dc0-3bd2b5a24d38\nmean(rand(d1, 10^5))\n\n# ╔═╡ 034f7d76-eacd-11eb-141d-0f90eef73f08\nstd(rand(d1, 10^5)) # standard deviation\n\n# ╔═╡ 034f7d7e-eacd-11eb-0945-2dda6be01349\nd2 = Bernoulli(.7)\n\n# ╔═╡ 034f7d7e-eacd-11eb-2a1b-933e1231c220\nrand(d2, 10)\n\n# ╔═╡ 034f7d8a-eacd-11eb-1dc0-d99d481ab6fa\nmd\"# Other Packages\n\nHere are some other popular Julia packages. They are not relevant for this course, but maybe you want to explore them at some point.\n* [Symbolics](https://github.com/JuliaSymbolics/Symbolics.jl)\n* [DifferentialEquations](https://github.com/SciML/DifferentialEquations.jl)\n* [Optim](https://github.com/JuliaNLSolvers/Optim.jl)\n* [Images](https://github.com/JuliaImages/Images.jl)\n* [Turing](https://github.com/TuringLang/Turing.jl)\n\"\n\n# ╔═╡ 4a03cfae-9876-4cf0-a498-d750853191cb\nmd\"\"\"# Exercises\n\n1. Create a data frame with 3 columns named A, B and C.\n   1. Column A contains 5 random numbers sampled from a Bernoulli distribution with rate 0.3, column B contains 5 random numbers from the uniform distribution over the interval [0, 1), and column C contains 5 samples from the set `(:hip, :hop)`.\n   2. Create a vector whose i'th element contains the sum of the i'th entries of columns A and B of the data frame created in 1.\n   3. Select all rows with `:hop` in column C and display the resulting data frame.\n1. \n   1. Use comprehension (see \"Vectors, Matrices, Arrays\") to create a vector where with all numbers of the form ``x^y`` with ``x=1, \\ldots, 10``, ``y = 2, \\ldots, 7`` and ``y > x``.\n   2. Compute the sum of the square root of this numbers.\n2. \n   1. Write a function that returns the smallest entry of a vector (without using the built-in function `minimum`, `argmin` or `findmin`).\n   2. Test your function on a vector of 10 randomly sampled integers in the range 1 to 100.\n3. \n   1. Plot the `cos` function on the interval 0 to 4π. Hint: type `\\pi + [Tab]` to enter the symbol π. To learn how to place custom tick labels on the x-axis, type `xticks` in a cell and open the \\\"Live docs\\\" at the bottom-right.\n   2. Add a scatter plot with 100 points whose ``x`` and ``y`` coordinates are randomly sampled from the interval ``[0, 1)`` on top of the figure with the cosine.\n\"\"\"\n\n# ╔═╡ 0314376e-ff8c-4ad0-8a4b-f94f04f31f2c\nMLCourse.footer()\n\n# ╔═╡ Cell order:\n# ╟─f3508747-da29-47c9-a98e-22ea15caaf2f\n# ╟─d92c0729-c7ab-42cc-b713-30f00e237833\n# ╠═b8630ee9-d2c0-4cd0-b3f7-77f66e997a80\n# ╠═034f7b46-eacd-11eb-1aa2-f380d08206cc\n# ╠═034f7b64-eacd-11eb-1618-6de6def66405\n# ╠═034f7b6e-eacd-11eb-1733-650ad4da2730\n# ╠═034f7b78-eacd-11eb-003a-5b5801c19d80\n# ╠═034f7b6e-eacd-11eb-184a-d504fab31681\n# ╠═fb3677a9-1610-49dd-96e4-3bd7badc58db\n# ╠═884f568b-079c-47d6-a597-34b67925f195\n# ╠═034f7b84-eacd-11eb-2836-11cebedb05b9\n# ╟─52efdece-3c21-43d4-a826-3b96e3a23e60\n# ╠═034f7ba0-eacd-11eb-3fc1-9dca0e072755\n# ╠═034f7ba0-eacd-11eb-23ae-cd327563ec60\n# ╠═034f7ba0-eacd-11eb-3347-49deb13761d9\n# ╟─121b3dbb-f86c-44b8-8b0f-f6b4d0b9992f\n# ╠═034f7baa-eacd-11eb-33f2-5f619e4a7832\n# ╠═034f7bb2-eacd-11eb-006b-7b935e35af66\n# ╠═034f7bb2-eacd-11eb-214b-cbfc83965c26\n# ╠═ec1dd4c4-d61d-4fdb-b576-3fe3b059eb3a\n# ╠═1a3387ee-b59d-49d7-9cca-2a8bd04eaaad\n# ╠═034f7b96-eacd-11eb-0c81-ad33210de120\n# ╠═034f7b96-eacd-11eb-2ee1-cd8e6813a726\n# ╟─0f4e3f45-71dd-41b2-a0b3-c55a04ace61f\n# ╠═034f7bbe-eacd-11eb-2e95-a93ad2d5e867\n# ╠═034f7bbe-eacd-11eb-2c36-d3949367ce5a\n# ╠═e0ec7ba3-4858-4572-994d-953caa98080b\n# ╠═04da39a1-e3bc-4086-b555-6cea2cf1689d\n# ╠═034f7bc8-eacd-11eb-0396-5b743b505b2a\n# ╠═034f7bc8-eacd-11eb-31f9-c119d1dfb8a5\n# ╟─ce3c7687-c7a9-4b5d-9a55-51514ed90fd9\n# ╠═034f7bd2-eacd-11eb-28f3-b707012e1db0\n# ╠═034f7bd2-eacd-11eb-1789-7380a89d5339\n# ╟─034f7cd6-eacd-11eb-0f8c-11179c3ab480\n# ╠═034f7cd6-eacd-11eb-0f8c-11179c3ab48f\n# ╠═034f7ce0-eacd-11eb-3c49-e39b8d3e917f\n# ╠═034f7ce0-eacd-11eb-18a1-bd2d1849b9bc\n# ╠═034f7cec-eacd-11eb-3262-bdc0f2e13a3a\n# ╠═034f7cec-eacd-11eb-27da-9bb861643df2\n# ╟─832ce046-ab34-4623-9d02-793dc5748208\n# ╠═91b0de0c-221c-468e-9077-5233aedeb4ca\n# ╠═0c7ae3ec-a40f-4e3e-85d8-3f79f091e3b4\n# ╟─732ae082-b90f-4108-9872-36077fb2c54c\n# ╠═6bfb60b4-964e-46ec-adc2-ec9e9a0f8158\n# ╟─0efb1f1a-8051-4843-aa68-1f4ad8618f92\n# ╠═034f7bdc-eacd-11eb-1999-9b62efdb4128\n# ╠═034f7cba-eacd-11eb-2f1a-836ccc185dd9\n# ╠═034f7cba-eacd-11eb-3901-2bc3d0ff0e39\n# ╟─50d83a01-f4c5-45c1-9c81-ed71d8313642\n# ╠═034f7bfa-eacd-11eb-1839-371285e2c6ed\n# ╠═034f7be4-eacd-11eb-1616-2df92f244e73\n# ╠═034f7bf0-eacd-11eb-0b3f-69f172657051\n# ╠═034f7bf0-eacd-11eb-012e-997132cd41c6\n# ╠═034f7bfa-eacd-11eb-2bf8-c795453a8959\n# ╠═034f7c04-eacd-11eb-3448-832bd75c3356\n# ╠═9c34e4ef-4eba-459f-a7ff-b20708155e65\n# ╟─e576bf44-9cc1-4053-b40f-b82c8c39c89d\n# ╠═034f7c0e-eacd-11eb-114f-9dbad3e74dd6\n# ╠═034f7c0e-eacd-11eb-1b73-27539a68f26d\n# ╠═034f7c16-eacd-11eb-0d0b-518b28558fda\n# ╠═034f7c16-eacd-11eb-2cb0-8b1198bfcb78\n# ╠═034f7ccc-eacd-11eb-1613-cbdf2386b60b\n# ╠═034f7ccc-eacd-11eb-2ab4-599e0ed86304\n# ╠═034f7cc2-eacd-11eb-29e2-810a573295cf\n# ╠═034f7cd6-eacd-11eb-37bb-f1930f2f2772\n# ╟─c997a07f-bc89-4c29-9945-62046b6889d2\n# ╠═07fd5baf-ae0b-4e74-97a6-5a6e14644122\n# ╟─11422ca4-c096-4167-aa53-de312615348e\n# ╠═0ace8c81-e481-4323-9b20-116de412330a\n# ╠═5d09ccbf-5a51-41f7-a7ef-84cf2cc5fa1f\n# ╟─9fd6e8c1-7b84-4d76-abef-9e3da4a56dc7\n# ╠═e33c0eea-4f5c-4fc8-800d-fa16335eedd0\n# ╠═315e5a3b-dc28-4c3b-8fc2-3442cb7590be\n# ╠═45deab46-9a8c-4d22-9460-980a3900396f\n# ╟─b91eda3c-95cb-4372-9c6b-03fa6a6b02b2\n# ╠═034f7c16-eacd-11eb-3877-6ba06a933698\n# ╠═034f7c22-eacd-11eb-3ab7-b30813d11e94\n# ╠═034f7c2c-eacd-11eb-1aae-97b030af71e9\n# ╠═034f7c2c-eacd-11eb-1f56-052874c5c6ab\n# ╠═034f7c36-eacd-11eb-0188-cd307154555c\n# ╠═034f7c40-eacd-11eb-26d9-956b65235a10\n# ╠═4237f5df-208d-44c4-90d7-db0efbe7b710\n# ╠═034f7c40-eacd-11eb-1beb-bb9e9bb325db\n# ╠═034f7c4a-eacd-11eb-0de4-537297318c85\n# ╠═034f7c4a-eacd-11eb-03ed-bfc7b532501b\n# ╠═034f7c54-eacd-11eb-2918-ef8f2befddc1\n# ╠═034f7c54-eacd-11eb-2fe9-5330d3cd3cd5\n# ╠═034f7c5e-eacd-11eb-24c6-d7e7213a7a5e\n# ╠═034f7c5e-eacd-11eb-1ff7-55f09fb796fe\n# ╟─d9ad1d6d-a3b5-4a83-bda9-05ee43ded9d6\n# ╠═034f7c68-eacd-11eb-1e11-d77379c677c8\n# ╠═034f7c68-eacd-11eb-12e6-51022c54f6ed\n# ╠═034f7c72-eacd-11eb-28a5-d7d6f3b9f75a\n# ╠═034f7c72-eacd-11eb-1cc2-91eaa2de5e25\n# ╠═034f7c7c-eacd-11eb-1aaa-297c951dd8cd\n# ╠═034f7c88-eacd-11eb-28f2-c1c7e05279c6\n# ╠═034f7c88-eacd-11eb-14fe-b3d49ff91622\n# ╠═034f7c90-eacd-11eb-0d1c-5dbd7b62d55c\n# ╟─df8588cb-400b-4423-9766-e6cac2c9717a\n# ╠═034f7c90-eacd-11eb-1b40-8722209689fa\n# ╠═034f7c9a-eacd-11eb-2e85-29c5bffbc39a\n# ╠═034f7cae-eacd-11eb-39dc-ab39e97cc716\n# ╠═034f7c9a-eacd-11eb-3aee-0bab7ab5d502\n# ╠═034f7ca4-eacd-11eb-2f3b-c1dd9be6ad84\n# ╠═034f7ca4-eacd-11eb-054e-1f930c99d304\n# ╠═034f7cae-eacd-11eb-38c0-57df4ba09992\n# ╠═034f7cc2-eacd-11eb-0f0f-ff16d1ac454b\n# ╟─034f7cf4-eacd-11eb-302f-55b164df3b90\n# ╠═034f7cf4-eacd-11eb-302f-55b164df3b9f\n# ╠═034f7cf4-eacd-11eb-003c-133f34cca508\n# ╠═034f7cfe-eacd-11eb-2514-4b6fdbc42e8f\n# ╠═034f7d08-eacd-11eb-2694-51c1baa997e6\n# ╠═034f7d12-eacd-11eb-1673-c94969427bbf\n# ╠═034f7d12-eacd-11eb-261c-a5de2f06f420\n# ╠═034f7d1a-eacd-11eb-1d48-591daf597cd6\n# ╠═034f7d1a-eacd-11eb-1e34-21d5eef62940\n# ╠═034f7d26-eacd-11eb-066c-538e5b614536\n# ╠═034f7d30-eacd-11eb-081f-970c4daee184\n# ╠═034f7d30-eacd-11eb-0b09-7b3b9ac47570\n# ╟─034f7d3a-eacd-11eb-3fbe-6dc4ab1efd50\n# ╠═034f7d3a-eacd-11eb-1144-65f9acfcf24c\n# ╠═034f7d3a-eacd-11eb-3fbe-6dc4ab1efd56\n# ╠═034f7d3a-eacd-11eb-1ef3-4f89b8e5aee9\n# ╠═034f7d44-eacd-11eb-0ab2-2f0d2caed9d6\n# ╠═034f7d4c-eacd-11eb-3960-d10d1c16075d\n# ╠═034f7d4c-eacd-11eb-3841-97ca37e34c9f\n# ╠═034f7d58-eacd-11eb-123f-9b563a7ae27e\n# ╟─4ca1cd98-a24b-491f-b9ac-28a7daf96d50\n# ╠═65e73d27-3709-4894-87ab-432343d314c6\n# ╟─9f69c2ab-2940-40ce-b164-07bfa6cc1697\n# ╠═e7ed9e83-7f17-4d9a-a49b-e87bc0747035\n# ╠═0d66592a-d098-4ab5-9323-503db8fc73f6\n# ╠═a9a3f29e-4931-4464-9bc5-af6598815f24\n# ╠═6e65247f-b285-49e5-a16e-31b4541225bf\n# ╠═fcd77620-f18a-499b-87c4-fffaa876e59f\n# ╟─034f7d62-eacd-11eb-3840-51c0622eb8a0\n# ╠═034f7d58-eacd-11eb-3189-bff16ec27739\n# ╠═034f7d62-eacd-11eb-3840-51c0622eb8a9\n# ╠═034f7d6c-eacd-11eb-0eb6-277bf88c13d3\n# ╠═034f7d6c-eacd-11eb-2792-d773a2c77cb6\n# ╠═034f7d6c-eacd-11eb-0dc0-3bd2b5a24d38\n# ╠═034f7d76-eacd-11eb-24cc-fd8d53d736c2\n# ╠═034f7d76-eacd-11eb-141d-0f90eef73f08\n# ╠═034f7d7e-eacd-11eb-0945-2dda6be01349\n# ╠═034f7d7e-eacd-11eb-2a1b-933e1231c220\n# ╟─034f7d8a-eacd-11eb-1dc0-d99d481ab6fa\n# ╟─4a03cfae-9876-4cf0-a498-d750853191cb\n# ╟─d6e5fe02-21a5-486c-a237-878be1d95439\n# ╟─065a1e67-6b63-43df-9d6d-303af08d8434\n# ╟─0314376e-ff8c-4ad0-8a4b-f94f04f31f2c\n", "meta": {"hexsha": "7240439e436c8ca75ae9f1e4d8dac24a73321877", "size": 25365, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/introduction.jl", "max_stars_repo_name": "ablaom/MLCourse", "max_stars_repo_head_hexsha": "24dccbdcb5be7dff8b2731d5bd583a0c753c72c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/introduction.jl", "max_issues_repo_name": "ablaom/MLCourse", "max_issues_repo_head_hexsha": "24dccbdcb5be7dff8b2731d5bd583a0c753c72c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/introduction.jl", "max_forks_repo_name": "ablaom/MLCourse", "max_forks_repo_head_hexsha": "24dccbdcb5be7dff8b2731d5bd583a0c753c72c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.375, "max_line_length": 289, "alphanum_fraction": 0.7323082988, "num_tokens": 12220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.9252299514223379, "lm_q1q2_score": 0.7710168671798165}}
{"text": "\"\"\"\n    ECON 602 Problem Set 1 Question 4\n\"\"\"\n\nusing Roots, Plots\n\nfunction adequilibrium(π, γ, ωA, ωB, p_0)\n    # solve for equilibrium price and consumption\n    # p_0 is initial guess for numerical solver\n    println(\"\\n AD equilibrium:\")\n     @show π, γ, ωA, ωB;\n\n    f(p, π, γ, ωA, ωB) = π*(ωA[1] + p*ωB[1]) + 1/(1 + p*(p*π/(1-π))^(-1/γ))*(ωA[2] + p*ωB[2]) - ωA[1] - ωA[2]\n    cA(p, π, γ, ωA, ωB) = [π*(ωA[1] + p*ωB[1]), 1/(1 + p*(p*π/(1 - π))^(-1/γ))*(ωA[2] + p*ωB[2])]\n    cB(p, π, γ, ωA, ωB) = [(1 - π)/p * (ωA[1] + p*ωB[1]), 1/(p + (p*π/(1 - π))^(1/γ))*(ωA[2] + p*ωB[2])]\n\n    # It never hurts to plot and see what you're working with\n    plot(p -> f(p, π, γ, ωA, ωB), 0, 4)\n    plot!(x -> 0, 0, 4)\n    \n    @show p_star = fzero(p -> f(p, π, γ, ωA, ωB), p_0);\n    #=\n     The first argument, p -> f(p, π, γ, ωA, ωB), defines and 'anonymous'\n     function of only p. It is a 'wrapper' for the function f that assigns\n     the values to all other parameters as they are currently defined.\n    =#\n    \n    @show cA = cA(p_star, π, γ, ωA, ωB);\n    @show cB = cB(p_star, π, γ, ωA, ωB);\n    return (p_star = p_star, cA = cA, cB = cB)  \nend\n\nfunction adequilibrium_alt(π, γ, ωA, ωB, p_min, p_max)\n    println(\"\\n AD equilibrium (alternative function):\")\n    # solve for equilibrium price and consumption\n    # alternative syntax and solution algorithm using bounds\n    @show π, γ, ωA, ωB;\n\n    f(p, π, γ, ωA, ωB) = π*(ωA[1] + p*ωB[1]) + 1/(1 + p*(p*π/(1-π))^(-1/γ))*(ωA[2] + p*ωB[2]) - ωA[1] - ωA[2]\n    cA(p, π, γ, ωA, ωB) = [π*(ωA[1] + p*ωB[1]), 1/(1 + p*(p*π/(1 - π))^(-1/γ))*(ωA[2] + p*ωB[2])]\n    cB(p, π, γ, ωA, ωB) = [(1 - π)/p * (ωA[1] + p*ωB[1]), 1/(p + (p*π/(1 - π))^(1/γ))*(ωA[2] + p*ωB[2])]\n\n    # It never hurts to plot and see what you're working with\n    plot(p -> f(p, π, γ, ωA, ωB), p_min, p_max)\n    plot!(x -> 0, p_min, p_max)\n    \n    # Alternative to anonymous function\n    f(p) = f(p, π, γ, ωA, ωB)\n    #=\n     Note that this is a distinct function from the first \n     function I defined, as it has a different number of\n     arguments\n    =#\n    @show p_star = fzero(f, p_min, p_max);\n    #=\n     This provides an allowable range for solutions between\n     0.01 and 4, rather than a single initial guess. This \n     can be useful to prevent the algorithm from searching\n     for negatives prices for example.\n    =#\n    \n    @show cA = cA(p_star, π, γ, ωA, ωB);\n    @show cB = cB(p_star, π, γ, ωA, ωB);\n    return (p_star = p_star, cA = cA, cB = cB);\nend\n\n# q4e\nωA = [2, 5];\nωB = [5, 2];\nγ = 2;\nπ = 0.5;\nq4e = adequilibrium(π, γ, ωA, ωB, 1.1);\nq4e_alt = adequilibrium_alt(π, γ, ωA, ωB, 0.01, 10.);\n\n# q4f\nωA = [2, 5];\nωB = [5, 2];\nγ = 2;\n# π = 0.25\nπ = 0.25;\nq4f_π025 = adequilibrium(π, γ, ωA, ωB, 1.1);\n# π = 0.75\nπ = 0.75;\nq4f_π075 = adequilibrium(π, γ, ωA, ωB, 1.1);\n", "meta": {"hexsha": "00731ab7f131a5649c873caa829eca2b79ac0914", "size": 2795, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PS1_Q4.jl", "max_stars_repo_name": "PhilipCaoChicago/ECON602_2021", "max_stars_repo_head_hexsha": "ef62b3763663c076ab5ea40009a57232ba338885", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-17T23:05:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T04:17:50.000Z", "max_issues_repo_path": "src/PS1_Q4.jl", "max_issues_repo_name": "PhilipCaoChicago/ECON602_2021", "max_issues_repo_head_hexsha": "ef62b3763663c076ab5ea40009a57232ba338885", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PS1_Q4.jl", "max_forks_repo_name": "PhilipCaoChicago/ECON602_2021", "max_forks_repo_head_hexsha": "ef62b3763663c076ab5ea40009a57232ba338885", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-09-21T19:07:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T22:37:40.000Z", "avg_line_length": 32.8823529412, "max_line_length": 109, "alphanum_fraction": 0.5402504472, "num_tokens": 1265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894576856559, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7708953103733537}}
{"text": "__precompile__()\nmodule BarycentricLagrange\n# Barycentric Lagrange Interpolation.\n# Berrut, J.-P., & Trefethen, L. N. (2004).\n# SIAM Review, 46(3), 501–517. doi:10.1137/S36144502417716\n\nexport bclag_interp_eval\nexport bclag_interp_matrix\nexport bclag_interp_weights\n\nfunction bclag_interp_eval(x, f, xi, w)\n    # fi = bclag_interp_eval(x, f, xi, w)\n    # xi scalar, not in x\n    tmp = w ./ (xi - x)\n    fi = sum(f.*tmp)/sum(tmp)\n    return fi\nend\nbclag_interp_eval(x, f, xi) = bclag_interp_eval(x, f, xi, bclag_interp_weights(x))\n\nfunction bclag_interp_matrix(x, xi, w)\n    n = length(x)\n    N = length(xi)\n    @assert length(w)==n\n\n    B = zeros(N, n)\n    denom = zeros(N)\n    exact = zeros(Int64, N)\n    for j=1:n\n        for k=1:N\n            xdiff = xi[k]-x[j]\n            if xdiff != 0\n                temp = w[j]/xdiff\n                B[k,j] = temp\n                denom[k] += temp\n            else\n                exact[k] = j\n            end\n        end\n    end\n\n    B ./= denom\n    for jj=1:N\n        if exact[jj] != 0\n            B[jj,:] = 0.0\n            B[jj + N*(exact[jj]-1)] = 1.0\n        end\n    end\n    return B\nend\nbclag_interp_matrix(x, xi) = bclag_interp_matrix(x, xi, bclag_interp_weights(x))\n\n\nfunction bclag_interp_weights(x)\n    n = length(x);\n    w = zeros(n);\n    for j=1:n\n        w[j] = 1/prod(x[j]-x[1:n.!=j]);\n    end\n    return w\nend\n\n\nend # module\n", "meta": {"hexsha": "8c70bed60390f40c601de86179f83365cad8b465", "size": 1380, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/src/BarycentricLagrange.jl", "max_stars_repo_name": "askhamwhat/inse-fiem-2d", "max_stars_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-08-20T12:53:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:15:10.000Z", "max_issues_repo_path": "julia/src/BarycentricLagrange.jl", "max_issues_repo_name": "askhamwhat/inse-fiem-2d", "max_issues_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/src/BarycentricLagrange.jl", "max_forks_repo_name": "askhamwhat/inse-fiem-2d", "max_forks_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-28T18:44:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T04:17:59.000Z", "avg_line_length": 21.5625, "max_line_length": 82, "alphanum_fraction": 0.5492753623, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7708953088454941}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.0\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 3ea4f8be-d0a7-455d-b58e-3e81ea61f9c1\nusing Plots,Images, Combinatorics, PlutoUI, Colors, ImageIO, LinearAlgebra\n\n# ╔═╡ 8de53f65-0d4a-4af0-a890-609ddcc92b36\nmodule Solution\n\tfunction monge_brute_force(C)\n\t  n, m = size(C)\n\t  @assert n == m \"C should be square\"\n\t  # loop over all permutations and to find the\n\t  # matching with the lowest cost\n\n\t  best_cost = typemax(eltype(C))\n\t  for p in permutations(1:n)\n\t\t  cost = zero(eltype(C))\n\t\t  for (i, j) in enumerate(p)\n\t\t\tcost += C[i,j]\n\t\t  end\n\t\t  if cost < best_cost\n\t\t\tbest_cost = cost\n\t\t\tglobal best_perm = p\n\t\t  end\n\t\tend\n\t  return best_perm, best_cost\n\tend\n\n\texport X1, X2, monge_brute_force\n\n\n\t# SINKHORN\n\t# -------\n    mean(x) = sum(x) / length(x)\n\n\tusing LinearAlgebra\n\n\tfunction sinkhorn(C::Matrix, a::Vector, b::Vector; λ=1.0, ϵ=1e-8)\n\t\tn, m = size(C)\n\t\t@assert n == length(a) && m == length(b) throw(DimensionMismatch(\"a and b do not match\"))\n\t\t@assert sum(a) ≈ sum(b) \"a and b don't have equal sums\"\n\t\tu, v = copy(a), copy(b)\n\t\tM = exp.(-λ * (C .- mean(C)))\n\t\t# normalize this matrix\n\t\twhile maximum(abs.(a .- Diagonal(u) * (M * v))) > ϵ\n\t\t\tu .= a ./ (M * v)\n\t\t\tv .= b ./ (M' * u)\n\t\t  end\n\t\treturn Diagonal(u) * M * Diagonal(v)\n\t  end\n\n\texport sinkhorn\n\t\nend\n\n# ╔═╡ 6f9362d0-1bb6-11ec-2b8b-491ef1f091e5\nmd\"\"\"\n# Optimal Transportation\n\n*STMO*\n\n**Michiel Stock**\n\n![](https://github.com/MichielStock/STMO/blob/master/chapters/06.OptimalTransport/Figures/logo.png?raw=true)\n\"\"\"\n\n# ╔═╡ ccb9bf05-1830-4c56-bf28-312c5d324484\nmd\"\"\"\n## Motivation\n\nOptimal transportation deals with transforming one distribution into another while minizing a cost function. The problem can be formulated as a maximum entropy function, leading to an elegant solution using the *Sinkhorn algorithm*. Optimal transportation is used in computer vision, machine learning, astonomy, bioinformatics, ecology etc.\n\"\"\"\n\n# ╔═╡ 65a73b72-967d-4a62-af17-f71b286f3303\nmd\"\"\"\n## Motivating example: a party in the research group\n\nLet's have a party in our research unit! Pastries and party hats for everyone! We ask Tinne, our laboratory manager, to make some desserts: an airy merveilleux, some delicious eclairs, a big bowl of dark chocolate mousse, a sweet passion fruit-flavored bavarois and moist carrot cake (we got to have our vegetables). If we mentally cut all these sweets into portions, we have twenty portions.\n\"\"\"\n\n# ╔═╡ ed3f476c-2205-43a7-a4cf-5941a0d0afd0\nstaff = [\"Bernard\", \"Jan\", \"Willem\", \"Hilde\", \"Steffie\", \"Marlies\", \"Tim\", \"Wouter\"]\n\n# ╔═╡ 0e579d2e-9b78-4a56-a30d-883cec0ad5d6\ndesserts = [\"merveilleux\", \"eclair\", \"chocolate mousse\", \"bavarois\", \"carrot cake\"]\n\n# ╔═╡ ce639d43-7481-43f4-8724-1da9c18d716a\na = [3.0, 3, 3, 4, 2, 2, 2, 1]\n\n# ╔═╡ c32441ee-c62d-4ee7-8e1b-ff7de1072d43\nb = [4.0, 2, 6, 4, 4]\n\n# ╔═╡ 245acb05-d58b-4ca6-9cf4-e59ff50e86c9\nmd\"As engineers and mathematicians, we pride ourselves in doing things the optimal way. So how can we divide the desserts to make everybody as happy as possible? As I am preparing a course on optimization, I went around and asked which of those treats they liked. On a scale between -2 and 2, with -2 being something they hated and 2 being their absolute favorite, the desert preferences of the teaching staff is given below (students: take note!).\"\n\n# ╔═╡ 114c8c91-34f3-4256-ab0f-c1fbd64e4827\npreferences = [2 2 1 0 0;\n              0 -2 -2 -2 2;\n              1 2 2 2 -1;\n              2 1 0 1 -1;\n              0.5 2 2 1 0;\n              0 1 1 1 -1;\n             -2 2 2 1 1;\n              2 1 2 1 -1]\n\n# ╔═╡ 01e3b967-e441-4041-8bd8-5cfc0e0ebaa4\nCdessert = -preferences;  # cost\n\n# ╔═╡ 7dbf484a-f3fb-4510-b500-57f4b13c0f59\nbegin\n\theatmap(preferences, title=\"preferences\", color=:balance)\n\tyticks!(1:8, staff)\n\txticks!(1:5, desserts)\nend\n\n# ╔═╡ b3440682-8443-4052-bbf2-8f593c4e54c3\nmd\"See how most people like eclairs and chocolate mousse, but merveilleus are a more polarizing dessert! Jan is lactose intolerant, so he only gave a high score to the carrot cake by default.\n\nThe task is clear: divide these desserts in such a way that people get their portions of the kinds they like the most!\n\"\n\n# ╔═╡ 984effce-9a76-4bbb-9105-06887dfa629e\nmd\"\"\"\n## The Monge problem\n\nThe original version of optimal transport was formulated by Gaspard Monge in 1781. Here, $n=m$ and the goal is to connect $n$ sources with $n$ sinks to minimize a cost:\n\n$$\\min_{\\sigma\\in\\text{Perm(n)}} \\frac{1}{n}\\sum_{i=1}^nC_{i,\\sigma(i)}\\,,$$\n\nwith $\\text{Perm(n)}$ the set of all permutation of $n$ elements.\n\n> **Example**: There are $n$ mines mining iron ore and a collection of $n$ factories. Given a distance between every mine and every factory, select one factory for every mine such that the total cost (=transportation distance) is minimized.\n\nThe **Monge problem** is a *discrete combinatorial optimization problem*:\n\n- The size of the search space is $n!$, for $n=70$, there are more than $10^{100}$ permutations!\n- Can be solved using the [Hungarian algorithm](https://en.wikipedia.org/wiki/Hungarian_algorithm).\n- Restrictive: two sets to match must be of same size. How to deal with different weights?\n\nFor working with probability distributions, we require a way to perform *soft-matching*.\n\"\"\"\n\n# ╔═╡ 9567f11f-486a-4960-8b69-42d2e5ee413f\nmd\"\"\"\n### Exercise: cell tracking\n\nIn a microscopy imaging experiment we monitor ten moving cells at time $t_1$ and some time later at time $t_2$. Between these times, the cells have moved. An image processing algorithm determined the coordinates of every cell in the two images. We want to know which cell in the first corresponds to the second image. To this end, search the assignment that minimizes the sum of the squared Euclidian distances between cells from the first image versus the corresponding cell of the second image.\n\n1. `X1` and `X2` contain the $x,y$ coordinates of the cells for the two images. Compute the matrix $C$ containing the pairwise squared Euclidean distance. You can use the function `dist` provided by us.\n2. Complete the function `monge_brute_force` to use brute-force search for the best permutation. You might find the function `permutations` from the `Combinatorics` library useful. How large is your search space? Time your function.\n3. Make a plot connecting the cells.\n\"\"\"\n\n# ╔═╡ b85b69fb-bfdb-41bd-a6a1-1aebe3077e08\nwith_terminal() do\n\tfor p in permutations([1, 2, 3])\n  \t\tprintln(p)\n\tend\nend\n\n# ╔═╡ cc62b7b1-fe34-4a19-846d-ca6c7fb69ff9\nfunction monge_brute_force(C)\n  n, m = size(C)\n  @assert n == m \"C should be square\"\n  # loop over all permutations and to find the\n  # matching with the lowest cost\n  return best_perm, best_cost\nend\n\n# ╔═╡ 1468ec48-bedb-4977-8b88-794d89e5ae8f\nC_cells = missing\n\n# ╔═╡ 88569ef5-bc60-4a77-aa72-fc9bdf66b3a4\n# add the lines to the cells\n\n# ╔═╡ da2cc178-64c7-4b30-909a-24fb402a489b\nmd\"\"\"\n## The optimal transportion problem\n\nLet us introduce some notation so we can formally state this as an optimization problem. Let $\\mathbf{a}$ be the vector containing the amount of dessert every person may eat. In this case $\\mathbf{a} = [3,3,3,4,2,2,2,1]^\\intercal$ (in general the dimension of $\\mathbf{r}$ is $n$). Similarly, $\\mathbf{c}$ denotes the vector of how much there is of every dessert, i.e. $\\mathbf{b}=[4, 2, 6, 4, 4]^\\intercal$ (in general the dimension of $\\mathbf{b}$ is $m$). Often $\\mathbf{a}$ and $\\mathbf{b}$ represent marginal probability distributions, hence their values are nonzero sum to one.\n\nLet $U(\\mathbf{a}, \\mathbf{b})$ be the set of positive $n\\times m$ matrices for which the rows sum to $\\mathbf{a}$ and the columns sum to $\\mathbf{b}$:\n\n$$U(\\mathbf{a}, \\mathbf{b}) = \\{P\\in \\mathbb{R}_{>0}^{n\\times m}\\mid P\\mathbf{1}_m = \\mathbf{a}, P^\\intercal\\mathbf{1}_n = \\mathbf{b}\\}\\,.$$\n\nFor our problem, $U(\\mathbf{a}, \\mathbf{b})$ contains all the ways of dividing the desserts for my colleagues. Note that we assume here that we can slice every dessert however we like. We do not have only to give whole pieces of pie but can provide any fraction we want.\n\nThe preferences of each person for each dessert is also stored in a matrix. To be consistent with the literature, this will be stored in a $n\\times m$ *cost* matrix $C$. The above matrix is a preference matrix that can easily be changed into a cost matrix by flipping the sign of every element.\n\nSo finally, the problem we want to solve is formally posed as\n\n$$d_C(\\mathbf{r}, \\mathbf{c}) = \\min_{P\\in U(\\mathbf{a}, \\mathbf{b})}\\, \\sum_{i,j}P_{ij}C_{ij}\\,.$$\n\nThis is called the *optimal transportation* between $\\mathbf{a}$ and $\\mathbf{b}$. It can be solved relatively easily using linear programming.\n\nThe optimum, $d_C(\\mathbf{a}, \\mathbf{b})$, is called the *Wasserstein metric*. It is basically a distance between two probability distributions. It is sometimes also called the *earth mover distance* as it can be interpreted as how much 'dirt' you have to move to change one 'landscape' (distribution) in another.\n\"\"\"\n\n# ╔═╡ bdd25212-576e-4b81-8178-1212ac759cbc\nmd\"\"\"\n## Choosing a bit of everything\n\nConsider a slightly modified form of the optimal transport:\n\n$$d_C^\\lambda(\\mathbf{a}, \\mathbf{b}) = \\min_{P\\in U(\\mathbf{a}, \\mathbf{b})}\\, \\sum_{i,j}P_{ij}C_{ij} - \\frac{1}{\\lambda}H(P)\\,,$$\n\nin which the minimizer $d^\\lambda_C(\\mathbf{a}, \\mathbf{b})$ is called the *Sinkhorn distance*. Here, the extra term\n\n$$H(P) = -\\sum_{i,j}P_{ij}\\log P_{ij}$$\n\nis the *information entropy* of $P$. One can increase the entropy by making the distribution more homogeneous, i.e., giving everybody a more equal share of every dessert. The parameter $\\lambda$ determines the trade-off between the two terms: trying to give every person only their favorites or encouraging equal distributions. Machine learners will recognize this as similar to regularization in, for example, ridge regression. Similar to that for machine learning problems, a tiny bit of shrinkage of the parameter can lead to improved performance, the Sinkhorn distance is also observed to work better than the Wasserstein distance on some problems. This is because we use a very natural prior on the distribution matrix $P$: in the absence of a cost, everything should be homogeneous!\n\nIf you squint your eyes a bit, you can also recognize a Gibbs free energy minimization problem into this, containing energy, entropy, physical restrictions ($U(\\mathbf{a}, \\mathbf{b})$) and a temperature ($1/\\lambda$). This could be used to describe a system of two types of molecules (for example proteins and ligands) which have a varying degree of cross-affinity for each other.\n\"\"\"\n\n# ╔═╡ c9cdf082-e986-4a21-8348-cc9faeeeb25a\nmd\"\"\"\n### An elegant algorithm for Sinkhorn distances\n\nEven though the entropic regularization can be motivated, to some extent, it appears that we have made the problem harder to solve because we added an extra term. Remarkably, there exists a very simple and efficient algorithm to obtain the optimal distribution matrix $P_\\lambda^\\star$ and the associated $d_C^\\lambda(\\mathbf{a}, \\mathbf{b})$! This algorithm starts from the observation that the elements of the optimal distribution matrices are of the form\n\n$$(P_\\lambda^\\star)_{ij} = \\alpha_i\\beta_j e^{-\\lambda C_{ij}}\\,,$$\n\nwith $\\alpha_1,\\ldots,\\alpha_n$ and $\\beta_1,\\ldots,\\beta_n$ some constants that have to be determined such that the rows, resp. columns, sum to $\\mathbf{r}$, resp. $\\mathbf{c}$! The optimal distribution matrix can be obtained by the following algorithm.\n\n> **given**: cost matrix $C$, marginals $\\mathbf{a}$, $\\mathbf{a}$ and $\\lambda\\ge0$\n>\n> **initialize**: $P_\\lambda = e^{-\\lambda C}$\n>\n> **repeat**\n>> 1. **scale the rows** such that the row sums match $\\mathbf{a}$\n>> 2. **scale the columns** such that the column sums match $\\mathbf{b}$\n>\n> **until** convergence\n\"\"\"\n\n# ╔═╡ efe892d3-23a3-4545-8c05-7ca9c90a9c81\nmd\"**Assignments**\n1. Complete the code below to solve optimal transport using the Sinkhorn algorithm.\n2. Solve the dessert problem, once for $\\lambda=0.1$ and once for $\\lambda=10$.\"\n\n# ╔═╡ 8214f18f-5d45-455f-b2ce-01085377cdf1\nfunction sinkhorn(C::Matrix, a::Vector, b::Vector; λ=1.0, ϵ=1e-8)\n    n, m = size(C)\n    @assert n == length(a) && m == length(b) throw(DimensionMismatch(\"a and b do not match\"))\n    @assert sum(a) ≈ sum(b) \"a and b don't have equal sums\"\n    u, v = copy(a), copy(b)\n    M = missing  # complete this\n    # normalize this matrix\n    while maximum(abs.(a .- Diagonal(u) * (M * v))) > ϵ\n        # scale u\n        # scale v\n      end\n    return Diagonal(u) * M * Diagonal(v)\n  end\n\n# ╔═╡ 425ce568-f3a2-4e73-a6f9-e0373f71436e\n# solve the dessert problem for λ=0.1\n\n# ╔═╡ f320803a-0439-4881-9570-3b4f6621d044\n# solve the dessert problem for λ=10\n\n# ╔═╡ 0295836f-0672-4903-a3f1-9004a187481b\n\n\n# ╔═╡ 8d015b52-96a2-4e7a-9827-76a14fe6b58b\nmd\"\"\"\n\nUsing this algorithm, we can compute the optimal distribution of desserts, shown below.\n\n![The solution of the dessert problem with $\\lambda=10$, an excellent approximation of the unregularized problem.](https://github.com/MichielStock/STMO/blob/master/chapters/06.OptimalTransport/Figures/desserts_high_lamda.png?raw=true)\n\nHere, everybody only has desserts they like. Note that for example, Jan gets three pieces of carrot cake (the only thing he can eat) while Tim receives the remaining portion (he is the only person with some fondness of this dessert). If we decrease the regularization parameter $\\lambda$, we encourage a more homogeneous distribution, though some people will have to try some sweets which are not their favorites...\n\n![The solution with a slightly lower $\\lambda$. Clearly, a different optimal distribution is obtained.](raw=truehttps://github.com/MichielStock/STMO/blob/master/chapters/06.OptimalTransport/Figures/desserts_high_lamda.png?raw=trueg)\n\nThe optimal transport problem, with or without entropic regularization has a beautiful geometric interpretation, shown below.\n\n![A geometric view of the optimal transport problem.](https://github.com/MichielStock/STMO/blob/master/chapters/06.OptimalTransport/Figures/desserts_low_lamda.png?raw=true)\n\nThe cost matrix determines a direction in which distributions are better or worse. The set $U(\\mathbf{r}, \\mathbf{c})$ contains all feasible distributions. In the unregularized case, the optimum $P^\\star$ is usually found in one of the corners of such a set. When adding the entropic regularizer, we restrict ourselves to distributions with a minimum of entropy, lying within the smooth red curve. Because we don't have to deal with the sharp corners of $U(\\mathbf{r}, \\mathbf{c})$ anymore, it is easier to find the optimum. As special cases, when $\\lambda\\rightarrow \\infty$, then $P^\\star_\\lambda$ will become closers to $P^\\star$ (until the algorithm runs into numerical difficulties). For $\\lambda\\rightarrow 0$ on the other hand, only the entropic term is taken into account and $P_\\lambda^\\star=\\mathbf{a}\\mathbf{b}^\\intercal$. This is bivariate distribution where the rows and columns are independent.\n\"\"\"\n\n# ╔═╡ 531be0de-e969-42db-a2fa-f9d125797296\nmd\"\"\"\n## Application: color transfer\n\nIn this exercise, we will apply optimal transportation to transfer the color scheme of one image to the other. We will read two images and exact the colors of the pixels (RGB encoded). Using optimal transport, a softmatching can be obtained between the pixels of te repective images. Then, every pixel of the first image can be recomputed using a weighted sum of the pixels of the second image (or vice versa).\n\nFirst, we will load two images. Feel free to use your own!\n\"\"\"\n\n# ╔═╡ 653a441a-bf0f-4606-a49d-da360d8922dc\ndownload(\"https://github.com/MichielStock/STMO/blob/master/chapters/06.OptimalTransport/Figures/butterfly3.jpg?raw=true\", \"image1.jpg\")\n\n# ╔═╡ f5d8bd7d-c335-4a10-9cdf-c8f4e953a4ce\ndownload(\"https://github.com/MichielStock/STMO/blob/master/chapters/06.OptimalTransport/Figures/butterfly2.jpg?raw=true\", \"image2.jpg\")\n\n# ╔═╡ c365eb3f-a7a7-485c-b696-02dd7fccbde3\nimage1 = load(\"image1.jpg\")\n\n# ╔═╡ 648ead24-cd9b-4fe5-97b4-f7a458c9f374\nimage2 = load(\"image2.jpg\")\n\n# ╔═╡ d160a399-7908-48af-9384-c245344e3bdd\nmd\"These images might be large, so let's subsample them!\"\n\n# ╔═╡ 8c92dbde-e6a3-42aa-a6a6-b2e615fc9f29\nsubsample(image, every=8) = image[1:every:size(image,1), 1:every:size(image,2)]\n\n# ╔═╡ 3fb7114f-c765-4153-be6c-66af2d629338\nimage1ss = subsample(image1)\n\n# ╔═╡ 80e00b5d-3206-4d26-81ed-1228122a60ac\nimage2ss = subsample(image2)\n\n# ╔═╡ 02b3e106-64e9-4fb4-b4b5-9e1bbe7b8a6d\nmd\"Take a look at the distribution of colors!\"\n\n# ╔═╡ 1161be1d-9fcf-45e4-9127-c8560adcca5a\ncolors1 = vec(image1ss)\n\n# ╔═╡ cc587c5b-bdf1-426a-8733-f4a2ce33637e\ncolors2 = vec(image2ss)\n\n# ╔═╡ ad3eebaa-4fa2-438a-a088-16334dba3a89\nn_colors1 = length(colors1)\n\n# ╔═╡ 11deb453-bd6e-43b1-b1e1-61606644eef8\nn_colors2 = length(colors2)\n\n# ╔═╡ e52d67d0-b161-403a-85c6-1bb59354f2ee\nmd\"The `Colors` package contains a function `colordiff` that quantifies the perceptive difference between two colors. It it an ideal cost function!\"\n\n# ╔═╡ dfe40afd-5153-4315-8511-cba00806d7e5\nmd\"Use this to compute the pairwise distances between all the colors!\"\n\n# ╔═╡ 7733a347-47bc-4a98-ac54-7139a945de0c\nCcol = [colordiff(c1, c2) for c1 in colors1, c2 in colors2]\n\n# ╔═╡ 0d719be9-aa39-4d12-9530-d50feb179753\nmd\"Now, each pixel of one image is soft-matched to pixels of the other picture. Recolor each pixel based on the weighted average of its assigned pixels to do the color transfer.\"\n\n# ╔═╡ 84470c18-41f7-4ed8-b6a8-25eefbc97e41\na_col = ones(n_colors1) / n_colors1\n\n# ╔═╡ 6be95f94-e71f-4447-bc7a-cf1bfcda49a4\nb_col = ones(n_colors2) / n_colors2\n\n# ╔═╡ 49fd9af6-f5a5-4f82-a39d-39f741430df6\nPcolors = Solution.sinkhorn(Ccol,\n\t\t\ta_col,\n\t\t\tb_col, λ=10, ϵ=1e-5)\n\n# ╔═╡ 96792a45-2a1f-48de-a514-e5dfd97aabf7\nmd\"Then, we can compute the transport between the two collections of pixels. Since every pixel is equally important, we give an uniform weight for each pixel, e.g., $\\mathbf{a}=\\mathbf{1}_n/m$ and $\\mathbf{b}=\\mathbf{1}_m/m$\"\n\n# ╔═╡ fa81b789-a1ec-42cc-b73f-2fb1e6d343c3\n\"\"\"\nMaps one distribution to the other\n\"\"\"\nmapdistr(X, P) = Diagonal(sum(P, dims=2)[:].^-1) * P * X\n\n# ╔═╡ e07b9f46-3cbe-490e-8e42-60470db2d4b4\nimage1_transf = reshape(mapdistr(colors2, Pcolors), size(image1ss))\n\n# ╔═╡ 64dcfee5-941c-417f-9698-18f57e4887f6\nimage2_transf = reshape(mapdistr(colors1, Pcolors'), size(image2ss))\n\n# ╔═╡ be1024ce-78fb-4436-9771-d1d952bfa69b\nmd\"## References\n\n- Gabriel Peyré and Marco Cuturi, *Computational Optimal Transport*, ArXiv:1803.00567, 2018.\n\"\n\n# ╔═╡ 15da4690-13fd-4b05-ac12-b5ccc2898bd0\nbegin\n\tmyblue = \"#304da5\"\n\tmygreen = \"#2a9d8f\"\n\tmyyellow = \"#e9c46a\"\n\tmyorange = \"#f4a261\"\n\tmyred = \"#e76f51\"\n\tmyblack = \"#50514F\"\n\n\tmycolors = [myblue, myred, mygreen, myorange, myyellow]\nend;\n\n# ╔═╡ 0b50b550-8c2b-43d7-849b-73ee8f60ff52\nbegin\n\tha = bar(a, color=mygreen, title=\"staff\");\n\txticks!(1:8, staff)\n\thb = bar(b, color=myorange, title=\"desserts\");\n\txticks!(1:5, desserts)\n\tplot(ha, hb)\nend\n\n# ╔═╡ 49b390b5-2192-43d9-ac71-337e2d19799b\nmyr, myg, myb = parse(Colorant, myred), parse(Colorant, mygreen), parse(Colorant, myblue)\n\n# ╔═╡ 49193509-14ea-4f0f-8fc1-14e7a924d2d7\ncolordiff(myr, myg)  # difference between red and green\n\n# ╔═╡ 627d6a6f-1c20-4242-8fc8-0a6a2ed91549\ncolordiff(myb, myg)  # difference between blue and green\n\n# ╔═╡ 086947e8-1baf-43c6-9c64-f10187b0a9c4\nX1 = [-3.334062779243765 -0.4501346178106358;\n-17.089568765347632 13.122166467239909;\n-14.347484681558905 -6.733978925249632;\n4.023051337264342 -9.962304692857852;\n-8.463617750898711 -7.272060919414795;\n4.411632356371395 18.33766410251966;\n0.33231514398722767 -8.943403560908134;\n4.312466564646311 -4.769277598451736;\n-0.1530439721692118 9.400009756002328;\n-5.9829675943508995 0.07220200778660099];\n\n# ╔═╡ ba9e51ae-f9d5-4ffe-af79-7bff04ae41b1\nX2 = [-15.776290315139038 -5.26704453200824;\n5.035133784625716 6.388525577583841;\n-1.302878737641465 -14.087978411169559;\n-17.05014605333986 10.189492174622178;\n-10.102710138685817 1.6112603598816224;\n-17.880416477734084 -5.15108311036524;\n-18.49092111472347 -5.193032093476489;\n1.2972905950753137 34.72586483583929;\n1.3580992685186684 7.334727533023157;\n-7.482909025521323 6.326317440680775];\n\n# ╔═╡ 1104b6a8-e781-4f58-ba2d-798ebbc11422\nbegin\n\tp_cells = scatter(X1[:,1], X1[:,2], color=myorange,\n\t\tlabel=\"location cells at t1\", legend=:topleft)\n\txlabel!(\"\\$x\\$\")\n\tylabel!(\"\\$y\\$\")\n\tscatter!(X2[:,1], X2[:,2], color=mygreen, label=\"location cells at t2\")\n\t\n\tp_cells\nend\n\n# ╔═╡ 31627338-8e0b-4568-a85b-3d7414c87769\nbegin\n\t\"\"\"\n\tCompute Euclidean distance between two vectors.\n\t\"\"\"\n\tdist(x::AbstractVector, y::AbstractVector) = sqrt(sum((x .- y).^2))\n\t\"\"\"\n\tCompute Euclidean distance matrix between two matrices.\n\t\"\"\"\n\tdist(X::AbstractMatrix, Y::AbstractMatrix) = [dist(X[i,:], Y[j,:]) for i in 1:size(X,1), j in 1:size(Y,1)]\n\t\"\"\"\n\tCompute Euclidean distance matrix.\n\t\"\"\"\n\tdist(X::AbstractMatrix) = dist(X::AbstractMatrix, X::AbstractMatrix)\nend\n\n# ╔═╡ 3070288a-8060-4da0-8007-41b69c606521\ncolorscatter(colors; kwargs...) = scatter(red.(colors), green.(colors), blue.(colors),\n                        xlabel=\"red\", ylabel=\"green\", zlabel=\"blue\", color=colors, label=\"\")\n\n# ╔═╡ ef606085-c423-4287-b4db-62ce3ddd0ed7\nplot(\n  colorscatter(colors1, title=\"figure 1\"),\n  colorscatter(colors2, title=\"figure 2\"))\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nColors = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nCombinatorics = \"861a8166-3701-5b0c-9a16-15d98fcdc6aa\"\nImageIO = \"82e4d734-157c-48bb-816b-45c225c6df19\"\nImages = \"916415d5-f1e6-5110-898d-aaa5f9f070e0\"\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\n\n[compat]\nColors = \"~0.12.8\"\nCombinatorics = \"~1.0.2\"\nImageIO = \"~0.5.8\"\nImages = \"~0.24.1\"\nPlots = \"~1.22.1\"\nPlutoUI = \"~0.7.10\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[AbstractFFTs]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"485ee0867925449198280d4af84bdb46a2a404d0\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"1.0.1\"\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[ArrayInterface]]\ndeps = [\"Compat\", \"IfElse\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"Static\"]\ngit-tree-sha1 = \"b8d49c34c3da35f220e7295659cd0bab8e739fed\"\nuuid = \"4fba245c-0d91-5ea0-9b3e-6abc04ee57a9\"\nversion = \"3.1.33\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[AxisAlgorithms]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"a4d07a1c313392a77042855df46c5f534076fab9\"\nuuid = \"13072b0f-2c55-5437-9ae7-d433b7a33950\"\nversion = \"1.0.0\"\n\n[[AxisArrays]]\ndeps = [\"Dates\", \"IntervalSets\", \"IterTools\", \"RangeArrays\"]\ngit-tree-sha1 = \"d127d5e4d86c7680b20c35d40b503c74b9a39b5e\"\nuuid = \"39de3d68-74b9-583c-8d2d-e117c070f3a9\"\nversion = \"0.4.4\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[CEnum]]\ngit-tree-sha1 = \"215a9aa4a1f23fbd05b92769fdd62559488d70e9\"\nuuid = \"fa961155-64e5-5f13-b03f-caf6b980ea82\"\nversion = \"0.4.1\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"f2202b55d816427cd385a9a4f3ffb226bee80f99\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+0\"\n\n[[CatIndices]]\ndeps = [\"CustomUnitRanges\", \"OffsetArrays\"]\ngit-tree-sha1 = \"a0f80a09780eed9b1d106a1bf62041c2efc995bc\"\nuuid = \"aafaddc9-749c-510e-ac4f-586e18779b91\"\nversion = \"0.2.2\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"bd4afa1fdeec0c8b89dad3c6e92bc6e3b0fec9ce\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.6.0\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"9995eb3977fbf67b86d0a0a0508e83017ded03f2\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.14.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[ColorVectorSpace]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"LinearAlgebra\", \"SpecialFunctions\", \"Statistics\", \"TensorCore\"]\ngit-tree-sha1 = \"45efb332df2e86f2cb2e992239b6267d97c9e0b6\"\nuuid = \"c3611d14-8923-5661-9e6a-0046d554d3a4\"\nversion = \"0.9.7\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Combinatorics]]\ngit-tree-sha1 = \"08c8b6831dc00bfea825826be0bc8336fc369860\"\nuuid = \"861a8166-3701-5b0c-9a16-15d98fcdc6aa\"\nversion = \"1.0.2\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"4866e381721b30fac8dda4c8cb1d9db45c8d2994\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.37.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[ComputationalResources]]\ngit-tree-sha1 = \"52cb3ec90e8a8bea0e62e275ba577ad0f74821f7\"\nuuid = \"ed09eef8-17a6-5b46-8889-db040fac31e3\"\nversion = \"0.3.2\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[CoordinateTransformations]]\ndeps = [\"LinearAlgebra\", \"StaticArrays\"]\ngit-tree-sha1 = \"6d1c23e740a586955645500bbec662476204a52c\"\nuuid = \"150eb455-5306-5404-9cee-2592286d6298\"\nversion = \"0.6.1\"\n\n[[CustomUnitRanges]]\ngit-tree-sha1 = \"1a3f97f907e6dd8983b744d2642651bb162a3f7a\"\nuuid = \"dc8bdbbb-1ca9-579f-8c36-e416f6a65cce\"\nversion = \"1.0.2\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distances]]\ndeps = [\"LinearAlgebra\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"9f46deb4d4ee4494ffb5a40a27a2aced67bdd838\"\nuuid = \"b4f34e82-e78d-54a5-968a-f98e89d6e8f7\"\nversion = \"0.10.4\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"a32185f5428d3986f47c2ab78b1f216d5e6cc96f\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.5\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[EllipsisNotation]]\ndeps = [\"ArrayInterface\"]\ngit-tree-sha1 = \"8041575f021cba5a099a456b4163c9a08b566a02\"\nuuid = \"da5c29d0-fa7d-589e-88eb-ea29b0a81949\"\nversion = \"1.1.0\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FFTViews]]\ndeps = [\"CustomUnitRanges\", \"FFTW\"]\ngit-tree-sha1 = \"70a0cfd9b1c86b0209e38fbfe6d8231fd606eeaf\"\nuuid = \"4f61f5a4-77b1-5117-aa51-3ab5ef4ef0cd\"\nversion = \"0.3.1\"\n\n[[FFTW]]\ndeps = [\"AbstractFFTs\", \"FFTW_jll\", \"LinearAlgebra\", \"MKL_jll\", \"Preferences\", \"Reexport\"]\ngit-tree-sha1 = \"463cb335fa22c4ebacfd1faba5fde14edb80d96c\"\nuuid = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nversion = \"1.4.5\"\n\n[[FFTW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea\"\nuuid = \"f5851436-0d7a-5f13-b9de-f02708fd171a\"\nversion = \"3.3.10+0\"\n\n[[FileIO]]\ndeps = [\"Pkg\", \"Requires\", \"UUIDs\"]\ngit-tree-sha1 = \"3c041d2ac0a52a12a27af2782b34900d9c3ee68c\"\nuuid = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nversion = \"1.11.1\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"dba1e8614e98949abfa60480b13653813d8f0157\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+0\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"c2178cfbc0a5a552e16d097fae508f2024de61a3\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.59.0\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"ef49a187604f865f4708c90e3f431890724e9012\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.59.0+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"7bf67e9a481712b3dbe9cb3dac852dc4b1162e02\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+0\"\n\n[[Graphics]]\ndeps = [\"Colors\", \"LinearAlgebra\", \"NaNMath\"]\ngit-tree-sha1 = \"2c1cf4df419938ece72de17f368a021ee162762e\"\nuuid = \"a2bd30eb-e257-5431-a919-1863eab51364\"\nversion = \"1.1.0\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"60ed5f1643927479f845b0135bb369b031b541fa\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.14\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"8a954fed8ac097d5be04921d595f741115c1b2ad\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+0\"\n\n[[HypertextLiteral]]\ngit-tree-sha1 = \"72053798e1be56026b81d4e2682dbe58922e5ec9\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.0\"\n\n[[IdentityRanges]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"be8fcd695c4da16a1d6d0cd213cb88090a150e3b\"\nuuid = \"bbac6d45-d8f3-5730-bfe4-7a449cd117ca\"\nversion = \"0.3.1\"\n\n[[IfElse]]\ngit-tree-sha1 = \"28e837ff3e7a6c3cdb252ce49fb412c8eb3caeef\"\nuuid = \"615f187c-cbe4-4ef1-ba3b-2fcf58d6d173\"\nversion = \"0.1.0\"\n\n[[ImageAxes]]\ndeps = [\"AxisArrays\", \"ImageCore\", \"Reexport\", \"SimpleTraits\"]\ngit-tree-sha1 = \"794ad1d922c432082bc1aaa9fa8ffbd1fe74e621\"\nuuid = \"2803e5a7-5153-5ecf-9a86-9b4c37f5f5ac\"\nversion = \"0.6.9\"\n\n[[ImageContrastAdjustment]]\ndeps = [\"ColorVectorSpace\", \"ImageCore\", \"ImageTransformations\", \"Parameters\"]\ngit-tree-sha1 = \"2e6084db6cccab11fe0bc3e4130bd3d117092ed9\"\nuuid = \"f332f351-ec65-5f6a-b3d1-319c6670881a\"\nversion = \"0.3.7\"\n\n[[ImageCore]]\ndeps = [\"AbstractFFTs\", \"Colors\", \"FixedPointNumbers\", \"Graphics\", \"MappedArrays\", \"MosaicViews\", \"OffsetArrays\", \"PaddedViews\", \"Reexport\"]\ngit-tree-sha1 = \"db645f20b59f060d8cfae696bc9538d13fd86416\"\nuuid = \"a09fc81d-aa75-5fe9-8630-4744c3626534\"\nversion = \"0.8.22\"\n\n[[ImageDistances]]\ndeps = [\"ColorVectorSpace\", \"Distances\", \"ImageCore\", \"ImageMorphology\", \"LinearAlgebra\", \"Statistics\"]\ngit-tree-sha1 = \"6378c34a3c3a216235210d19b9f495ecfff2f85f\"\nuuid = \"51556ac3-7006-55f5-8cb3-34580c88182d\"\nversion = \"0.2.13\"\n\n[[ImageFiltering]]\ndeps = [\"CatIndices\", \"ColorVectorSpace\", \"ComputationalResources\", \"DataStructures\", \"FFTViews\", \"FFTW\", \"ImageCore\", \"LinearAlgebra\", \"OffsetArrays\", \"Requires\", \"SparseArrays\", \"StaticArrays\", \"Statistics\", \"TiledIteration\"]\ngit-tree-sha1 = \"bf96839133212d3eff4a1c3a80c57abc7cfbf0ce\"\nuuid = \"6a3955dd-da59-5b1f-98d4-e7296123deb5\"\nversion = \"0.6.21\"\n\n[[ImageIO]]\ndeps = [\"FileIO\", \"Netpbm\", \"OpenEXR\", \"PNGFiles\", \"TiffImages\", \"UUIDs\"]\ngit-tree-sha1 = \"13c826abd23931d909e4c5538643d9691f62a617\"\nuuid = \"82e4d734-157c-48bb-816b-45c225c6df19\"\nversion = \"0.5.8\"\n\n[[ImageMagick]]\ndeps = [\"FileIO\", \"ImageCore\", \"ImageMagick_jll\", \"InteractiveUtils\", \"Libdl\", \"Pkg\", \"Random\"]\ngit-tree-sha1 = \"5bc1cb62e0c5f1005868358db0692c994c3a13c6\"\nuuid = \"6218d12a-5da1-5696-b52f-db25d2ecc6d1\"\nversion = \"1.2.1\"\n\n[[ImageMagick_jll]]\ndeps = [\"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pkg\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"1c0a2295cca535fabaf2029062912591e9b61987\"\nuuid = \"c73af94c-d91f-53ed-93a7-00f77d67a9d7\"\nversion = \"6.9.10-12+3\"\n\n[[ImageMetadata]]\ndeps = [\"AxisArrays\", \"ColorVectorSpace\", \"ImageAxes\", \"ImageCore\", \"IndirectArrays\"]\ngit-tree-sha1 = \"ae76038347dc4edcdb06b541595268fca65b6a42\"\nuuid = \"bc367c6b-8a6b-528e-b4bd-a4b897500b49\"\nversion = \"0.9.5\"\n\n[[ImageMorphology]]\ndeps = [\"ColorVectorSpace\", \"ImageCore\", \"LinearAlgebra\", \"TiledIteration\"]\ngit-tree-sha1 = \"68e7cbcd7dfaa3c2f74b0a8ab3066f5de8f2b71d\"\nuuid = \"787d08f9-d448-5407-9aad-5290dd7ab264\"\nversion = \"0.2.11\"\n\n[[ImageQualityIndexes]]\ndeps = [\"ColorVectorSpace\", \"ImageCore\", \"ImageDistances\", \"ImageFiltering\", \"OffsetArrays\", \"Statistics\"]\ngit-tree-sha1 = \"1198f85fa2481a3bb94bf937495ba1916f12b533\"\nuuid = \"2996bd0c-7a13-11e9-2da2-2f5ce47296a9\"\nversion = \"0.2.2\"\n\n[[ImageShow]]\ndeps = [\"Base64\", \"FileIO\", \"ImageCore\", \"OffsetArrays\", \"Requires\", \"StackViews\"]\ngit-tree-sha1 = \"832abfd709fa436a562db47fd8e81377f72b01f9\"\nuuid = \"4e3cecfd-b093-5904-9786-8bbb286a6a31\"\nversion = \"0.3.1\"\n\n[[ImageTransformations]]\ndeps = [\"AxisAlgorithms\", \"ColorVectorSpace\", \"CoordinateTransformations\", \"IdentityRanges\", \"ImageCore\", \"Interpolations\", \"OffsetArrays\", \"Rotations\", \"StaticArrays\"]\ngit-tree-sha1 = \"e4cc551e4295a5c96545bb3083058c24b78d4cf0\"\nuuid = \"02fcd773-0e25-5acc-982a-7f6622650795\"\nversion = \"0.8.13\"\n\n[[Images]]\ndeps = [\"AxisArrays\", \"Base64\", \"ColorVectorSpace\", \"FileIO\", \"Graphics\", \"ImageAxes\", \"ImageContrastAdjustment\", \"ImageCore\", \"ImageDistances\", \"ImageFiltering\", \"ImageIO\", \"ImageMagick\", \"ImageMetadata\", \"ImageMorphology\", \"ImageQualityIndexes\", \"ImageShow\", \"ImageTransformations\", \"IndirectArrays\", \"OffsetArrays\", \"Random\", \"Reexport\", \"SparseArrays\", \"StaticArrays\", \"Statistics\", \"StatsBase\", \"TiledIteration\"]\ngit-tree-sha1 = \"8b714d5e11c91a0d945717430ec20f9251af4bd2\"\nuuid = \"916415d5-f1e6-5110-898d-aaa5f9f070e0\"\nversion = \"0.24.1\"\n\n[[Imath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"87f7662e03a649cffa2e05bf19c303e168732d3e\"\nuuid = \"905a6f67-0a94-5f89-b386-d35d92009cd1\"\nversion = \"3.1.2+0\"\n\n[[IndirectArrays]]\ngit-tree-sha1 = \"c2a145a145dc03a7620af1444e0264ef907bd44f\"\nuuid = \"9b13fd28-a010-5f03-acff-a1bbcff69959\"\nversion = \"0.5.1\"\n\n[[Inflate]]\ngit-tree-sha1 = \"f5fc07d4e706b84f72d54eedcc1c13d92fb0871c\"\nuuid = \"d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9\"\nversion = \"0.1.2\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[IntelOpenMP_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d979e54b71da82f3a65b62553da4fc3d18c9004c\"\nuuid = \"1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0\"\nversion = \"2018.0.3+2\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[Interpolations]]\ndeps = [\"AxisAlgorithms\", \"ChainRulesCore\", \"LinearAlgebra\", \"OffsetArrays\", \"Random\", \"Ratios\", \"Requires\", \"SharedArrays\", \"SparseArrays\", \"StaticArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"61aa005707ea2cebf47c8d780da8dc9bc4e0c512\"\nuuid = \"a98d9a8b-a2ab-59e6-89dd-64a1c18fca59\"\nversion = \"0.13.4\"\n\n[[IntervalSets]]\ndeps = [\"Dates\", \"EllipsisNotation\", \"Statistics\"]\ngit-tree-sha1 = \"3cc368af3f110a767ac786560045dceddfc16758\"\nuuid = \"8197267c-284f-5f27-9208-e0e47529a953\"\nversion = \"0.5.3\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"f76424439413893a832026ca355fe273e93bce94\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.0\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a4b12a1bd2ebade87891ab7e36fdbce582301a92\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.6\"\n\n[[LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"761a393aeccd6aa92ec3515e428c26bf99575b3b\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+0\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"DocStringExtensions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"34dc30f868e368f8a17b728a1238f3fcda43931a\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.3\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MKL_jll]]\ndeps = [\"Artifacts\", \"IntelOpenMP_jll\", \"JLLWrappers\", \"LazyArtifacts\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"5455aef09b40e5020e1520f551fa3135040d4ed0\"\nuuid = \"856f044c-d86e-5d09-b602-aeab76dc8ba7\"\nversion = \"2021.1.1+2\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"5a5bc6bf062f0f95e62d0fe0a2d99699fed82dd9\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.8\"\n\n[[MappedArrays]]\ngit-tree-sha1 = \"e8b359ef06ec72e8c030463fe02efe5527ee5142\"\nuuid = \"dbb5928d-eab1-5f90-85c2-b9b0edb7c900\"\nversion = \"0.4.1\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MosaicViews]]\ndeps = [\"MappedArrays\", \"OffsetArrays\", \"PaddedViews\", \"StackViews\"]\ngit-tree-sha1 = \"b34e3bc3ca7c94914418637cb10cc4d1d80d877d\"\nuuid = \"e94cdb99-869f-56ef-bcf0-1ae2bcbe0389\"\nversion = \"0.3.3\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[Netpbm]]\ndeps = [\"ColorVectorSpace\", \"FileIO\", \"ImageCore\"]\ngit-tree-sha1 = \"09589171688f0039f13ebe0fdcc7288f50228b52\"\nuuid = \"f09324ee-3d7c-5217-9330-fc30815ba969\"\nversion = \"1.0.1\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[OffsetArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"c0e9e582987d36d5a61e650e6e543b9e44d9914b\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.7\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+0\"\n\n[[OpenEXR]]\ndeps = [\"Colors\", \"FileIO\", \"OpenEXR_jll\"]\ngit-tree-sha1 = \"327f53360fdb54df7ecd01e96ef1983536d1e633\"\nuuid = \"52e1d378-f018-4a11-a4be-720524705ac7\"\nversion = \"0.3.2\"\n\n[[OpenEXR_jll]]\ndeps = [\"Artifacts\", \"Imath_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"923319661e9a22712f24596ce81c54fc0366f304\"\nuuid = \"18a262bb-aa17-5467-a713-aee519bc75cb\"\nversion = \"3.1.1+0\"\n\n[[OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[PNGFiles]]\ndeps = [\"Base64\", \"CEnum\", \"ImageCore\", \"IndirectArrays\", \"OffsetArrays\", \"libpng_jll\"]\ngit-tree-sha1 = \"e14c485f6beee0c7a8dcf6128bf70b85f1fe201e\"\nuuid = \"f57f5aa1-a3ce-4bc8-8ab9-96f992907883\"\nversion = \"0.3.9\"\n\n[[PaddedViews]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"646eed6f6a5d8df6708f15ea7e02a7a2c4fe4800\"\nuuid = \"5432bcbf-9aad-5242-b902-cca2824c8663\"\nversion = \"0.5.10\"\n\n[[Parameters]]\ndeps = [\"OrderedCollections\", \"UnPack\"]\ngit-tree-sha1 = \"34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe\"\nuuid = \"d96e819e-fc66-5662-9728-84c9c7592b0a\"\nversion = \"0.12.3\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"438d35d2d95ae2c5e8780b330592b6de8494e779\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.3\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PkgVersion]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"a7a7e1a88853564e551e4eba8650f8c38df79b37\"\nuuid = \"eebad327-c553-4316-9ea0-9fa01ccd7688\"\nversion = \"0.1.1\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"2537ed3c0ed5e03896927187f5f2ee6a4ab342db\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.0.14\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\"]\ngit-tree-sha1 = \"4c2637482176b1c2fb99af4d83cb2ff0328fc33c\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.22.1\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"HypertextLiteral\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"Suppressor\"]\ngit-tree-sha1 = \"26b4d16873562469a0a1e6ae41d90dec9e51286d\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.10\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[ProgressMeter]]\ndeps = [\"Distributed\", \"Printf\"]\ngit-tree-sha1 = \"afadeba63d90ff223a6a48d2009434ecee2ec9e8\"\nuuid = \"92933f4c-e287-5a05-a399-4b506db050ca\"\nversion = \"1.7.1\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RangeArrays]]\ngit-tree-sha1 = \"b9039e93773ddcfc828f12aadf7115b4b4d225f5\"\nuuid = \"b3c3ace0-ae52-54e7-9d0b-2c1406fd6b9d\"\nversion = \"0.3.2\"\n\n[[Ratios]]\ndeps = [\"Requires\"]\ngit-tree-sha1 = \"01d341f502250e81f6fec0afe662aa861392a3aa\"\nuuid = \"c84ed2f1-dad5-54f0-aa8e-dbefe2724439\"\nversion = \"0.4.2\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"44a75aa7a527910ee3d1751d1f0e4148698add9e\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.2\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"7ad0dfa8d03b7bcf8c597f59f5292801730c55b8\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.4.1\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[Rotations]]\ndeps = [\"LinearAlgebra\", \"StaticArrays\", \"Statistics\"]\ngit-tree-sha1 = \"2ed8d8a16d703f900168822d83699b8c3c1a5cd8\"\nuuid = \"6038ab10-8711-5258-84ad-4b1120ba62dc\"\nversion = \"1.0.2\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[SimpleTraits]]\ndeps = [\"InteractiveUtils\", \"MacroTools\"]\ngit-tree-sha1 = \"5d7e3f4e11935503d3ecaf7186eac40602e7d231\"\nuuid = \"699a6c99-e7fa-54fc-8d76-47d257e15c1d\"\nversion = \"0.9.4\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"ad42c30a6204c74d264692e633133dcea0e8b14e\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.6.2\"\n\n[[StackViews]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"46e589465204cd0c08b4bd97385e4fa79a0c770c\"\nuuid = \"cae243ae-269e-4f55-b966-ac2d0dc13c15\"\nversion = \"0.1.1\"\n\n[[Static]]\ndeps = [\"IfElse\"]\ngit-tree-sha1 = \"a8f30abc7c64a39d389680b74e749cf33f872a70\"\nuuid = \"aedffcd0-7271-4cad-89d0-dc628f76c6d3\"\nversion = \"0.3.3\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3240808c6d463ac46f1c1cd7638375cd22abbccb\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.12\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"1958272568dc176a1d881acb797beb909c785510\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.0.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"8cbbc098554648c84f79a463c9ff0fd277144b6c\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.10\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.3\"\n\n[[Suppressor]]\ngit-tree-sha1 = \"a819d77f31f83e5792a76081eee1ea6342ab8787\"\nuuid = \"fd094767-a336-5f1f-9728-57cf17d0bbfb\"\nversion = \"0.2.0\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"1162ce4a6c4b7e31e0e6b14486a6986951c73be9\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.5.2\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[TensorCore]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"1feb45f88d133a655e001435632f019a9a1bcdb6\"\nuuid = \"62fd8b95-f654-4bbd-a8a5-9c27f68ccd50\"\nversion = \"0.1.1\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[TiffImages]]\ndeps = [\"ColorTypes\", \"DocStringExtensions\", \"FileIO\", \"FixedPointNumbers\", \"IndirectArrays\", \"Inflate\", \"OffsetArrays\", \"OrderedCollections\", \"PkgVersion\", \"ProgressMeter\"]\ngit-tree-sha1 = \"632a8d4dbbad6627a4d2d21b1c6ebcaeebb1e1ed\"\nuuid = \"731e570b-9d59-4bfa-96dc-6df516fadf69\"\nversion = \"0.4.2\"\n\n[[TiledIteration]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"52c5f816857bfb3291c7d25420b1f4aca0a74d18\"\nuuid = \"06e1c1a7-607b-532d-9fad-de7d9aa2abac\"\nversion = \"0.3.0\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[UnPack]]\ngit-tree-sha1 = \"387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b\"\nuuid = \"3a884ed6-31ef-47d7-9d2a-63182c4928ed\"\nversion = \"1.0.2\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\"]\ngit-tree-sha1 = \"2839f1c1296940218e35df0bbb220f2a79686670\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.18.0+4\"\n\n[[WoodburyMatrices]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"59e2ad8fd1591ea019a5259bd012d7aee15f995c\"\nuuid = \"efce3f68-66dc-5838-9240-27a6d6f5f9b6\"\nversion = \"0.5.3\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─6f9362d0-1bb6-11ec-2b8b-491ef1f091e5\n# ╠═3ea4f8be-d0a7-455d-b58e-3e81ea61f9c1\n# ╟─ccb9bf05-1830-4c56-bf28-312c5d324484\n# ╟─65a73b72-967d-4a62-af17-f71b286f3303\n# ╠═ed3f476c-2205-43a7-a4cf-5941a0d0afd0\n# ╠═0e579d2e-9b78-4a56-a30d-883cec0ad5d6\n# ╠═ce639d43-7481-43f4-8724-1da9c18d716a\n# ╠═c32441ee-c62d-4ee7-8e1b-ff7de1072d43\n# ╟─0b50b550-8c2b-43d7-849b-73ee8f60ff52\n# ╟─245acb05-d58b-4ca6-9cf4-e59ff50e86c9\n# ╠═114c8c91-34f3-4256-ab0f-c1fbd64e4827\n# ╠═01e3b967-e441-4041-8bd8-5cfc0e0ebaa4\n# ╟─7dbf484a-f3fb-4510-b500-57f4b13c0f59\n# ╟─b3440682-8443-4052-bbf2-8f593c4e54c3\n# ╟─984effce-9a76-4bbb-9105-06887dfa629e\n# ╟─9567f11f-486a-4960-8b69-42d2e5ee413f\n# ╟─1104b6a8-e781-4f58-ba2d-798ebbc11422\n# ╟─b85b69fb-bfdb-41bd-a6a1-1aebe3077e08\n# ╠═cc62b7b1-fe34-4a19-846d-ca6c7fb69ff9\n# ╠═1468ec48-bedb-4977-8b88-794d89e5ae8f\n# ╠═88569ef5-bc60-4a77-aa72-fc9bdf66b3a4\n# ╟─da2cc178-64c7-4b30-909a-24fb402a489b\n# ╟─bdd25212-576e-4b81-8178-1212ac759cbc\n# ╟─c9cdf082-e986-4a21-8348-cc9faeeeb25a\n# ╟─efe892d3-23a3-4545-8c05-7ca9c90a9c81\n# ╠═8214f18f-5d45-455f-b2ce-01085377cdf1\n# ╠═425ce568-f3a2-4e73-a6f9-e0373f71436e\n# ╠═f320803a-0439-4881-9570-3b4f6621d044\n# ╠═0295836f-0672-4903-a3f1-9004a187481b\n# ╟─8d015b52-96a2-4e7a-9827-76a14fe6b58b\n# ╟─531be0de-e969-42db-a2fa-f9d125797296\n# ╠═653a441a-bf0f-4606-a49d-da360d8922dc\n# ╠═f5d8bd7d-c335-4a10-9cdf-c8f4e953a4ce\n# ╠═c365eb3f-a7a7-485c-b696-02dd7fccbde3\n# ╠═648ead24-cd9b-4fe5-97b4-f7a458c9f374\n# ╟─d160a399-7908-48af-9384-c245344e3bdd\n# ╠═8c92dbde-e6a3-42aa-a6a6-b2e615fc9f29\n# ╠═3fb7114f-c765-4153-be6c-66af2d629338\n# ╠═80e00b5d-3206-4d26-81ed-1228122a60ac\n# ╠═02b3e106-64e9-4fb4-b4b5-9e1bbe7b8a6d\n# ╠═1161be1d-9fcf-45e4-9127-c8560adcca5a\n# ╠═cc587c5b-bdf1-426a-8733-f4a2ce33637e\n# ╠═ad3eebaa-4fa2-438a-a088-16334dba3a89\n# ╠═11deb453-bd6e-43b1-b1e1-61606644eef8\n# ╠═ef606085-c423-4287-b4db-62ce3ddd0ed7\n# ╟─e52d67d0-b161-403a-85c6-1bb59354f2ee\n# ╠═49b390b5-2192-43d9-ac71-337e2d19799b\n# ╠═49193509-14ea-4f0f-8fc1-14e7a924d2d7\n# ╠═627d6a6f-1c20-4242-8fc8-0a6a2ed91549\n# ╟─dfe40afd-5153-4315-8511-cba00806d7e5\n# ╠═7733a347-47bc-4a98-ac54-7139a945de0c\n# ╟─0d719be9-aa39-4d12-9530-d50feb179753\n# ╠═84470c18-41f7-4ed8-b6a8-25eefbc97e41\n# ╠═6be95f94-e71f-4447-bc7a-cf1bfcda49a4\n# ╠═49fd9af6-f5a5-4f82-a39d-39f741430df6\n# ╟─96792a45-2a1f-48de-a514-e5dfd97aabf7\n# ╠═fa81b789-a1ec-42cc-b73f-2fb1e6d343c3\n# ╠═e07b9f46-3cbe-490e-8e42-60470db2d4b4\n# ╠═64dcfee5-941c-417f-9698-18f57e4887f6\n# ╟─be1024ce-78fb-4436-9771-d1d952bfa69b\n# ╟─15da4690-13fd-4b05-ac12-b5ccc2898bd0\n# ╟─086947e8-1baf-43c6-9c64-f10187b0a9c4\n# ╟─ba9e51ae-f9d5-4ffe-af79-7bff04ae41b1\n# ╟─31627338-8e0b-4568-a85b-3d7414c87769\n# ╟─3070288a-8060-4da0-8007-41b69c606521\n# ╠═8de53f65-0d4a-4af0-a890-609ddcc92b36\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "5a661fd51122ce032608b1ce18102dbf53f2ca80", "size": 66707, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapters/06.OptimalTransport/optimal_transportation.jl", "max_stars_repo_name": "mathematiguy/STMO", "max_stars_repo_head_hexsha": "44a2c8b986632ca943cb6a3b3b09f327235432b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/06.OptimalTransport/optimal_transportation.jl", "max_issues_repo_name": "mathematiguy/STMO", "max_issues_repo_head_hexsha": "44a2c8b986632ca943cb6a3b3b09f327235432b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/06.OptimalTransport/optimal_transportation.jl", "max_forks_repo_name": "mathematiguy/STMO", "max_forks_repo_head_hexsha": "44a2c8b986632ca943cb6a3b3b09f327235432b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2041271612, "max_line_length": 908, "alphanum_fraction": 0.7379885169, "num_tokens": 28721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7708953087828107}}
{"text": "\nfunction pidigits(N::Int, printOut::Bool)\n    \"\"\"\n    See http://shootout.alioth.debian.org/u64q/performance.php?test=pidigits#about\n\n    Transliterated from Mario Pernici Python's program\n\n\n    INPUT:\n\n    - N -- a positive integer giving the number of digits of pi to be computed\n\n    - printOut -- a boolean specifying if we want intermediate printouts of digits in packets of 10\n\n    OUTPUT:\n\n    - returns the last ten digits anyway\n\n    - prints all the digits in packets of 10 iff printOut == true\n\n    \"\"\"\n\n    i = k = ns = 0\n    k1 = 1\n    n,a,d,t,u = map(BigInt,(1,0,1,0,0))\n\n    while true\n        k += 1\n        t = n << 1\n        n *= k\n        a += t\n        k1 += 2\n        a *= k1\n        d *= k1\n\n        if a >= n\n            t,u = divrem(n*3 +a, d)\n            u += n\n            if d > u\n                ns = ns*10 + t\n                i += 1\n                if mod(i,10) == 0\n                    if printOut\n                        print(ns)\n                        @printf(\"\\t:%d\\n\", i)\n                    end\n                    if i >= N\n                        return ns\n                    end\n                    ns = 0\n                end\n                a -= d*t\n                a *= 10\n                n *= 10\n\n            end\n        end\n    end\nend\n\nperf_pidigits(N::Int=1000) = pidigits(N,false)\n", "meta": {"hexsha": "a19c69de58a5e046318e4fb1de72fe4e483261e2", "size": 1330, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/shootout/pidigits.jl", "max_stars_repo_name": "vilterp/BaseBenchmarks.jl", "max_stars_repo_head_hexsha": "8f68550ddc89311c53b3342f4241dc62a7d65990", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2016-05-11T11:20:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T20:44:39.000Z", "max_issues_repo_path": "src/shootout/pidigits.jl", "max_issues_repo_name": "vilterp/BaseBenchmarks.jl", "max_issues_repo_head_hexsha": "8f68550ddc89311c53b3342f4241dc62a7d65990", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 158, "max_issues_repo_issues_event_min_datetime": "2016-01-07T22:09:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T21:54:24.000Z", "max_forks_repo_path": "src/shootout/pidigits.jl", "max_forks_repo_name": "invenia/BaseBenchmarks.jl", "max_forks_repo_head_hexsha": "89d290636d93054aa690580f89ce5260a9f3ab36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46, "max_forks_repo_forks_event_min_datetime": "2016-01-07T21:59:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T20:48:30.000Z", "avg_line_length": 21.4516129032, "max_line_length": 99, "alphanum_fraction": 0.4210526316, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7708953071922675}}
{"text": "# # Faster convergence for linear dynamcs\n\n#=\nIn this example, I show how the SSA can be used as objective to guarantee\nconvergence or faster convergence for a linear dynamical system.\n=#\n\n# ## Optimization of all matrix elements\n\n# ### Initialization\nusing Plots,NamedColors\nusing LinearAlgebra\nusing Random\nusing SmoothedSpectralAbscissa ; const SSA=SmoothedSpectralAbscissa\nRandom.seed!(0);\n\n# ### Linear Dynamics\n\n#=\nConsider continuous linear dynamics, regulated by\n```math\n\\frac{\\text{d} \\mathbf{x}}{\\text{d}t} = A \\mathbf{x}\n```\nThe soluton is analytic and takes the form:\n```math\n\\mathbf{x}(t) = \\exp( A\\,t )\\;\\mathbf{x}_0\n```\nWhere $\\mathbf{x}_0$ are the initial conditions. The function below computes the dynamical\nevolution of the system.\n=#\n\nfunction run_linear_dyn(A::Matrix{R},x0::Vector{R},tmax::Real,dt::Real=0.01) where R\n  ts = range(0,tmax;step=dt)\n  ret = Matrix{R}(undef,length(x0),length(ts))\n  for (k,t) in enumerate(ts)\n    ret[:,k]=exp(A.*t)*x0\n  end\n  retnrm = mapslices(norm,ret;dims=1)[:]\n  return ts,ret,retnrm\nend;\n\n\n# ### The optimization of the objective is done through Optim.jl and BFGS\nusing Optim\n\nfunction objective_and_grad_simple(x::Vector{R},grad::Union{Nothing,Vector{R}},\n    n::Integer,ssa_eps::R,alloc::SSA.SSAAlloc) where R\n  mat=reshape(x,(n,n))\n  gradmat = isnothing(grad) ? nothing : similar(mat)\n  obj = SSA.ssa!(mat,gradmat,alloc,ssa_eps)\n  if !isnothing(grad)\n    for i in eachindex(gradmat)\n      grad[i]=gradmat[i]\n    end\n  end\n  return obj\nend;\n## #src\n# ### Start with an unstable matrix\n\nn = 50\nA = randn(n,n) ./ sqrt(n) + 0.2I\nx0=randn(n)\ntimes,_,dyn_norms = run_linear_dyn(A,x0,3.,0.1)\n\nplot(times,dyn_norms; leg=false,linewidth=3,color=:black,xlabel=\"time\",ylabel=\"norm(x(t))\")\n\n# as expected, the norm grows exponentially with time.\n\n# ### Now do the gradient-based optimization\nconst ssa_eps=0.001\nconst alloc = SSA.SSAAlloc(n)\nconst y0 = A[:];\n\n#=\nThe objective function to be minimized is\n```math\n\\text{obj}(A) = \\text{SSA}(A) + \\lambda \\frac12 \\left\\| A - A_0 \\right\\|^2\n```\nWhere $\\lambda$ sets the relative weight.\nWe are reducing the SSA while keeping the matrix elements close to their initial value.\nAdding some form of regularization is **always** necessary when otpimizing. If not,\nthe SSA would run to $-\\infty$.\n=#\n\nfunction objfun!(F,G,y)\n  λ = 50.0/length(y) # regularizer weight\n  obj=objective_and_grad_simple(y,G,n,ssa_eps,alloc) # SSA and gradient\n  ydiffs = y.-y0\n  obj += 0.5*λ*mapreduce(x->x^2,+,ydiffs) # add the regularizer\n  if !isnothing(G)\n    @. G += λ*ydiffs # add gradient of regularizer\n  end\n  return obj\nend;\n\n# ### Optimize and show the results\n\nopt_out = optimize(Optim.only_fg!(objfun!),A[:],BFGS(),Optim.Options(iterations=50))\ny_opt=Optim.minimizer(opt_out)\nA_opt = reshape(y_opt,(n,n))\ntimes,_,dyn_norms_opt = run_linear_dyn(A_opt,x0,3.,0.1)\nplot(times,dyn_norms_opt;\n  leg=false,linewidth=3,color=:blue,xlabel=\"time\",ylabel=\"norm(x(t)) optimized\")\n\n#=\nThe optimized matrix produces stable dynamics, as shown in the plot above.\n\nWe can also take a look at the matrices before and after optimization\n=#\n\nheatmap(hcat(A,fill(NaN,n,10),A_opt);ratio=1,axis=nothing,ticks=nothing,border=:none,\n  colorbar=nothing)\n\n#=\nThe optimized version simply has negative diagonal terms.\n\nThis may appear a bit trivial. In the next part, I optimize a system *excluding* the diagonal.\n=#\n\n\n# ## Optimization that excludes the diagonal\n\n#=\nHere I consider a matrix that is stable, but produces a large nonlinear amplification.\nIt is generated by the function:\n=#\nfunction rand_nonnormal(n::Integer,(ud::Real)=1.01)\n  mat = randn(n,n) ./ sqrt(n)\n  @show SSA.spectral_abscissa(mat)\n  mat = mat -  (1.1*SSA.spectral_abscissa(mat))*I\n  sh = schur(mat)\n  upd = diagm(0=>fill(1.0,n),1=>fill(ud,n-1))\n  return sh.vectors*upd*sh.Schur*inv(upd)*sh.vectors'\nend\n# Let's make one and see how it looks like\nA = rand_nonnormal(n,1.0)\nx0=randn(n)\ntimes,dyn_t,dyn_norms = run_linear_dyn(A,x0,30.,0.5)\nplot(times,dyn_norms;\n  leg=false,linewidth=3,color=:black,xlabel=\"time\",ylabel=\"norm(x(t))\")\n\n#=\nThe norm is initally amplified, and decreases slowly. This is due to the\nnon-normality of matrix $A$.\n=#\n\n# ### Objective function that excludes diagonal\n\nfunction objective_and_grad_nodiag(x::Vector{R},grad::Union{Nothing,Vector{R}},\n    n::Integer,ssa_eps::R,alloc::SSA.SSAAlloc,A0::Matrix{R}) where R\n  mat=reshape(x,(n,n))\n  for i in 1:n\n    mat[i,i]=A0[i,i] # diagonal copied from original matrix\n  end\n  gradmat = isnothing(grad) ? nothing : similar(mat)\n  obj = SSA.ssa!(mat,gradmat,alloc,ssa_eps)\n  if !isnothing(grad)\n    for i in 1:n\n      gradmat[i,i] = 0.0 # diagonal has zero gradient\n    end\n    for i in eachindex(gradmat)\n      grad[i]=gradmat[i] # copy the gradient\n    end\n  end\n  return obj\nend;\n\n# ### Optimizer and optimization\n\n#=\nThe only difference from before is using\n`objective_and_grad_nodiag` rather than `objective_and_grad_simple`\n=#\n\nconst ssa_eps=0.001\nconst alloc = SSA.SSAAlloc(n)\nconst y0 = A[:];\n\nfunction objfun!(F,G,y)\n  λ = 1.0/length(y) # regularizer weight\n  obj=objective_and_grad_nodiag(y,G,n,ssa_eps,alloc,A) # add the regularizer\n  ydiffs = y.-y0\n  obj += 0.5*λ*mapreduce(x->x^2,+,ydiffs)\n  if !isnothing(G)\n    @. G += λ*ydiffs # gradient of regularizer\n  end\n  return obj\nend\n\nopt_out = optimize(Optim.only_fg!(objfun!),A[:],BFGS(),Optim.Options(iterations=50))\ny_opt=Optim.minimizer(opt_out)\nA_opt = reshape(y_opt,(n,n));\n\n# Now the optimized matrix looks remarkably similar to ro the original one,\n# as shown below.\nheatmap(hcat(A,fill(NaN,n,10),A_opt);ratio=1,axis=nothing,ticks=nothing,border=:none)\n\n# Here I show the differences between $A$ and $A_{\\text{opt}}$.\n# (in case you don't believe they are different)\nheatmap(A-A_opt;ratio=1,axis=nothing,ticks=nothing,border=:none)\n\n# Let's compare the time evolution of the norms\ntimes,dyn_t_opt,dyn_norms_opt = run_linear_dyn(A_opt,x0,30.,0.5)\nplot(times,[dyn_norms dyn_norms_opt];\n      leg=:topright,linewidth=3,color=[:black :blue],\n      xlabel=\"time\",ylabel=\"norm(x(t))\", label=[\"before otpimization\" \"after optimization\"])\n#=\n![So much stability!](./meme1.png)\n=#\n\n# ## Extras\n\n#=\nIn gradient based optimization with no automatic differentiation, it is\nalways necessary to test the gradient of the objective function.\nThe procedure is illustrated below.\n=#\n\nusing Calculus\nfunction test_gradient(myobjfun,y0)\n  grad_an = similar(y0)\n  _ = myobjfun(1.0,grad_an,y0) # compute gradient analytically\n  grad_num = Calculus.gradient(y->myobjfun(1.0,nothing,y),y0) # compute it numerically\n  return (grad_an,grad_num)\nend\n\n_ = let do_the_test = false\n  if do_the_test\n    (x1,x2)=test_gradient(objfun!,randn(n^2))\n    scatter(x1,x2;ratio=1)\n    plot!(identity)\n  end\nend\n", "meta": {"hexsha": "b28a88bd6470c7ab588402917d323ae33d9953c4", "size": 6737, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/02_dynamics.jl", "max_stars_repo_name": "dylanfesta/SmoothedSpectralAbscissa.jl", "max_stars_repo_head_hexsha": "c76945b165c6f63a4c2d04596e575031765e5641", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/02_dynamics.jl", "max_issues_repo_name": "dylanfesta/SmoothedSpectralAbscissa.jl", "max_issues_repo_head_hexsha": "c76945b165c6f63a4c2d04596e575031765e5641", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-02-21T00:56:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-04T22:57:50.000Z", "max_forks_repo_path": "examples/02_dynamics.jl", "max_forks_repo_name": "dylanfesta/SmoothedSpectralAbscissa.jl", "max_forks_repo_head_hexsha": "c76945b165c6f63a4c2d04596e575031765e5641", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6680851064, "max_line_length": 94, "alphanum_fraction": 0.7124833012, "num_tokens": 2088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7708953056017243}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames\n\tusing Plots, LaTeXStrings\n\tusing Calculus, SpecialFunctions\n\tRandom.seed!(1)\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.27\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\txGrid = -5:0.01:5\n\n\tPhiA(x) = 0.5*(1+erf(x/sqrt(2)))\n\tPhiB(x) = cdf(Normal(),x)\n\n\tText(\"Maximum difference between two CDF implementations: $(maximum(PhiA.(xGrid) - PhiB.(xGrid)))\")\nend\n\n# ╔═╡ 28860946-21c1-11eb-228d-09798b3886ad\nbegin\n\tnormalDensity(z) = pdf(Normal(),z)\n\n\td0 = normalDensity.(xGrid)\n\td1 = derivative.(normalDensity,xGrid)\n\td2 = second_derivative.(normalDensity, xGrid)\n\n\tplot(xGrid, [d0 d1 d2], c=[:blue :red :green],label=[L\"f(x)\" L\"f'(x)\" L\"f''(x)\"])\n\tplot!([-5,5],[0,0],  color=:black, lw=0.5, xlabel=\"x\", xlims=(-5,5), label=\"\")\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.27\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═28860946-21c1-11eb-228d-09798b3886ad\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "706e71b2d4a9e1a09fb5736086d09d4f4cbe9450", "size": 1384, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.27.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.27.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.27.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.6296296296, "max_line_length": 100, "alphanum_fraction": 0.7066473988, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.7708953008300947}}
{"text": "# Solves the Poisson equation using the Mixed finite element method \nusing Revise\nusing AdFem\nusing DelimitedFiles\nusing SparseArrays\nusing PyPlot\n\n\nn = 50\nmmesh = Mesh(n, n, 1/n, degree = BDM1)\n\ntestCase = [\n    ((x, y)->begin\n        x * (1-x) * y * (1-y)\n    end, \n    (x, y)->begin\n        -2x*(1-x) -2y*(1-y)\n    end),  # test case 1\n    ((x, y)->begin\n        x^2 * (1-x) * y * (1-y)^2\n    end, \n    (x, y)->begin\n        2*x^2*y*(1 - x) + 2*x^2*(1 - x)*(2*y - 2) - 4*x*y*(1 - y)^2 + 2*y*(1 - x)*(1 - y)^2\n    end) ,# test case 2\n    (\n        (x, y)->x*y, \n        (x, y)->0.0\n    ), # test case 3\n    (\n        (x, y)->x^2 * y^2 + 1/(1+x^2), \n        (x, y)->2*x^2 + 8*x^2/(x^2 + 1)^3 + 2*y^2 - 2/(x^2 + 1)^2\n    ), # test case 4\n]\n\nfor k = 1:4\n    @info \"TestCase $k...\"\n    ufunc, ffunc = testCase[k]\n\n    A = compute_fem_bdm_mass_matrix1(mmesh)\n    B = compute_fem_bdm_div_matrix1(mmesh)\n    C = [A -B'\n        -B spzeros(mmesh.nelem, mmesh.nelem)]\n\n    gD = bcedge(mmesh)\n    t1 = eval_f_on_boundary_edge(ufunc, gD, mmesh)\n    g = compute_fem_traction_term1(t1, gD, mmesh) \n    t2 = eval_f_on_gauss_pts(ffunc, mmesh)\n    f = compute_fvm_source_term(t2, mmesh)\n    rhs = [-g; f]\n\n    sol = C\\rhs\n    u = sol[mmesh.ndof+1:end]\n    close(\"all\")\n    figure(figsize=(15, 5))\n    subplot(131)\n    title(\"Reference\")\n    xy = fvm_nodes(mmesh)\n    x, y = xy[:,1], xy[:,2]\n    uf = ufunc.(x, y)\n    visualize_scalar_on_fvm_points(uf, mmesh)\n    subplot(132)\n    title(\"Numerical\")\n    visualize_scalar_on_fvm_points(u, mmesh)\n    subplot(133)\n    title(\"Absolute Error\")\n    visualize_scalar_on_fvm_points( abs.(u - uf) , mmesh)\n    savefig(\"bdm$k.png\")\nend", "meta": {"hexsha": "15ec08deba2facc42e3a55934c572c3d425ff6fd", "size": 1660, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/snippets/BDM/poisson.jl", "max_stars_repo_name": "kailaix/AdFem.jl", "max_stars_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2020-10-18T01:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:13:24.000Z", "max_issues_repo_path": "docs/src/snippets/BDM/poisson.jl", "max_issues_repo_name": "kailaix/AdFem.jl", "max_issues_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-10-19T03:51:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:38:46.000Z", "max_forks_repo_path": "docs/src/snippets/BDM/poisson.jl", "max_forks_repo_name": "kailaix/AdFem.jl", "max_forks_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-11-05T11:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T19:30:09.000Z", "avg_line_length": 24.4117647059, "max_line_length": 91, "alphanum_fraction": 0.5409638554, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627598, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7708807150490906}}
{"text": "# Module to perform optional kabsch rotation to minimise distance between two structures before interpolating between them\nmodule Kabsch\n\nusing DelimitedFiles\n\nusing LinearAlgebra\nusing Statistics\n\nexport kabsch_rotate\n\nfunction translate_to_centroid(coord_matrix)\n    # Normalises the molecular coordinates by centering them.\n    center = mean(coord_matrix,dims=1)\n    translated_geom = coord_matrix .- center\n    return translated_geom\nend\n\nfunction optimal_rotation_matrix(CCmatrix)\n    # Returns 3x3 matrix that can be applied to P to get Q\n    # Previous implementation, not general (for cases of non-invertible matrices)\n    # ORmatrix = sqrt(transpose(CCmatrix)*CCmatrix)*inv(CCmatrix)\n    # Using SVD instead\n    u,sing,vt = svd(CCmatrix)\n    if sign(det(transpose(vt)*transpose(u))) == 1.0\n        ORmatrix = transpose(vt)*transpose(u)\n    elseif sign(det(transpose(vt)*transpose(u))) == -1.0\n        mat = [1. 0. 0.;0. 1. 0.; 0. 0. -1.]\n        ORmatrix = transpose(vt)*mat*transpose(u)\n    else\n        println(\"Error: Issue with SVD routine in finding optimal rotation matrix\")\n    end\n    return ORmatrix\nend\n\nfunction xyz2matrix(input_xyz)\n    # Imports .xyz file format as data frame, and converts it to an N x 3 Matrix\n    raw_xyz=readdlm(input_xyz)\n    natoms=size(raw_xyz)[1]\n    just_coords=Array{Float64}(raw_xyz[2:natoms,2:4])\n    return just_coords\nend\n\nfunction kabsch_rotate(Pgeom,Qgeom)\n    # Returns the two geometries in xyz format, one of which has been translated, the\n    # other translated and rotated \n    # Pgeom = xyz2matrix(p_xyz)\n    # Qgeom = xyz2matrix(q_xyz)\n\n    normalisedP = (translate_to_centroid(Pgeom))\n    normalisedQ = (translate_to_centroid(Qgeom))\n    \n    # Calculate cross covariance matrix\n    xcov = transpose(normalisedP)*normalisedQ\n    orot = optimal_rotation_matrix(xcov)\n    \n    num_atoms = size(normalisedP)[1]\n    rotated = zeros(Float64,num_atoms,3)\n    \n    for i=1:num_atoms\n        rotated[i,:] = orot*normalisedP[i,:]\n    end\n\n    RMSD_value = norm(rotated-normalisedQ)\n\n    println(\"The RMSD between these two structures is \",RMSD_value)\n\n    return rotated, normalisedQ\nend  \n\nend\n\n\n\n", "meta": {"hexsha": "88592083b2e1c089ee9a96fe862ddc531033d9ff", "size": 2152, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kabsch.jl", "max_stars_repo_name": "dasha-shchep/LIIC", "max_stars_repo_head_hexsha": "3de14eac035992f601692098c37e71c81f880d56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kabsch.jl", "max_issues_repo_name": "dasha-shchep/LIIC", "max_issues_repo_head_hexsha": "3de14eac035992f601692098c37e71c81f880d56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-23T14:20:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T14:20:54.000Z", "max_forks_repo_path": "src/kabsch.jl", "max_forks_repo_name": "dasha-shchep/LIIC", "max_forks_repo_head_hexsha": "3de14eac035992f601692098c37e71c81f880d56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0810810811, "max_line_length": 122, "alphanum_fraction": 0.7123605948, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142225532629, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7708807129399469}}
{"text": "\"\nThis script contains the functions to evaluate the expectation values ⟨Â⟩ for the displaced oscillator\n\nThe parameters to be given are: ω, λ, g, γ, α, and a list of sampled times t, plus r and θ for the squeezed states\n\n\"\n\nexport ann_a, num_a, quad_a, quads_a, nums_a\n\n\"`quad_a(α, λ, ω, γ, t)` evaluate the position quadrature operator average for the coherent state. α ∈ Complex\"\nquad_a(α, λ, ω, γ, t) = (α + (λ/ω)) * exp(-γ * t * (1 - exp(1im * ω/γ))) + (conj(α) + (λ/ω)) * exp(-γ * t * (1 - exp(-1im * ω/γ))) - 2 * (λ/ω)\n\n\"`num_a(α, λ, ω, γ, t)` evaluate the number operator average for the coherent state. α ∈ Complex\"\nnum_a(α, λ, ω, γ, t) = abs2(α) + (λ/ω) * (α + conj(α)) + 2 * (λ/ω)^2 - (λ/ω) * ((α + (λ/ω)) * exp(-γ * t * (1 - exp(1im * ω/γ))) + (conj(α) + (λ/ω)) * exp(-γ * t * (1 - exp(-1im * ω/γ))))\n\n# Squeezed coefficients\nμ(r) = cosh(r)\nν(r, θ) = exp(1im * θ) * sinh(r)\n\n\"`quads_a(α, r, θ, λ, ω, γ, t)` evaluate the position quadrature operator average for the squeezed state. α ∈ Complex\"\nquads_a(α, r, θ, λ, ω, γ, t) = (μ(r) * conj(α) + conj(ν(r, θ)) * α + (λ/ω)) * exp(-γ * t * (1 - exp(1im * ω/γ))) + (μ(r) * α + ν(r, θ) * conj(α) + (λ/ω)) * exp(-γ * t * (1 - exp(-1im * ω/γ))) - 2 * (λ/ω)\n\n# Number operator squeezed coefficients\nncf1(r, θ, α) = (μ(r)^2 + abs2(ν(r, θ))) * abs2(α)\nncf2(r, θ, α) = μ(r) * (ν(r, θ) * conj(α)^2 + conj(ν(r, θ)) * α^2)\nncf3(r, θ, α) = (μ(r) - conj(ν(r, θ))) * α + (μ(r) - ν(r, θ)) * conj(α)\nncf4(r, θ, α) = μ(r) * conj(α) - conj(ν(r, θ)) * α\nncf5(r, θ, α) = μ(r) * α - ν(r, θ) * conj(α)\n\n\"`nums_a(α, r, θ, λ, ω, γ, t)` evaluate the number operator average for the squeezed state. α ∈ Complex\"\nnums_a(α, r, θ, λ, ω, γ, t) = (ncf1(r, θ, α) - ncf2(r, θ, α) + (λ/ω) * ncf3(r, θ, α) + 2 * (λ/ω)^2 + abs2(ν(r, θ))) - (λ/ω) * ((ncf4(r, θ, α) + (λ/ω)) * exp(-γ * t * (1 - exp(1im * ω/γ))) + (ncf5(r, θ, α) + (λ/ω)) * exp(-γ * t * (1 - exp(-1im * ω/γ))))\n", "meta": {"hexsha": "2d215264aab4ff830f5b0bc0dcdcec7e2dd2ad62", "size": 1896, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Funcs_Displaced.jl", "max_stars_repo_name": "rurz/IntrinsicDecoherence", "max_stars_repo_head_hexsha": "72f7f4e6d3f3a6d420e56410ded2bb5c18d0e79c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Funcs_Displaced.jl", "max_issues_repo_name": "rurz/IntrinsicDecoherence", "max_issues_repo_head_hexsha": "72f7f4e6d3f3a6d420e56410ded2bb5c18d0e79c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-10T05:06:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-24T05:24:46.000Z", "max_forks_repo_path": "src/Funcs_Displaced.jl", "max_forks_repo_name": "rurz/IntrinsicDecoherence", "max_forks_repo_head_hexsha": "72f7f4e6d3f3a6d420e56410ded2bb5c18d0e79c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.25, "max_line_length": 252, "alphanum_fraction": 0.5232067511, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142225532629, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.7708807064088503}}
{"text": "module GreatValueMath\n\nusing Statistics\nusing DataFrames\n\n# min-max feature scaling\nfunction normalize(data::DataFrame, field::String)::DataFrame\n    ma = maximum(data[!, field])\n    mi = minimum(data[!, field])\n    for (index, i) in enumerate(eachrow(data))\n        data[index, field] = (i[field] - mi)/(ma - mi)\n    end\n    return data\nend\n\nfunction theil_sen_linear_regression(data::DataFrame, x::String, y::String)\n    𝐧 = nrow(data)\n    if 𝐧 > 1\n      # independent variable vector\n      xᵢ = data[!, x]\n      # dependent variable vector\n      yᵢ = data[!, y]\n      # mean of dependent vector\n      yₘ = (1/𝐧)*sum(yᵢ)\n      # https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator\n      m = median([(yᵢ[i+1]-yᵢ[i])/(xᵢ[i+1]-xᵢ[i]) for i ∈ 1:𝐧-1])\n      𝑏 = median([(yᵢ[i]-m*xᵢ[i]) for i ∈ 1:𝐧])\n      # https://en.wikipedia.org/wiki/Coefficient_of_determination\n      # predicted vector\n      fᵢ = [(m*x+𝑏) for x ∈ xᵢ]\n      # residual vector\n      𝖾ᵢ = [(yᵢ[i]-fᵢ[i]) for i ∈ 1:𝐧]\n      SStot = sum([abs2(yᵢ[i]-yₘ) for i ∈ 1:𝐧])\n      SSres = sum([abs2(𝖾ᵢ[i]) for i ∈ 1:𝐧])\n      𝐑² = 1 - (SSres/SStot)\n      return Dict(\"𝐑²\" => 𝐑², \"m\" => m, \"𝑏\" => 𝑏)\n    else\n      return false\n    end\nend\n\nexport normalize\nexport theil_sen_linear_regression\n\nend # module\n", "meta": {"hexsha": "d40377a9c0b24af06cebd304dd3eee6098c798e2", "size": 1269, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GreatValueMath.jl", "max_stars_repo_name": "rory-linehan/GreatValueMath.jl", "max_stars_repo_head_hexsha": "89529f1c7bae9e448170a523b24abb6d674eb272", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GreatValueMath.jl", "max_issues_repo_name": "rory-linehan/GreatValueMath.jl", "max_issues_repo_head_hexsha": "89529f1c7bae9e448170a523b24abb6d674eb272", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GreatValueMath.jl", "max_forks_repo_name": "rory-linehan/GreatValueMath.jl", "max_forks_repo_head_hexsha": "89529f1c7bae9e448170a523b24abb6d674eb272", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5869565217, "max_line_length": 75, "alphanum_fraction": 0.5902285264, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142225532629, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.770880704231818}}
{"text": "\nusing FFTW\nusing Plots\n\nn = 128\nL = 30\ndx = L/n\nt = -L/2:dx:L/2-dx\nf(x) = cos(x)*exp(-x^2/25) #Function\ndf(x) = -sin(x)*exp(-x^2/25) - 2*x*f(x)/25 #Derivative\n\n# Approximate derivative using finite Differences...\ndfFD = zeros(n)\nfor k = 1:n-1\n    dfFD[k] = (f(t[k+1])-f(t[k]))/dx\nend\ndfFD[n] = dfFD[n-1];\n\n# Derivative using FFT (spectral derivative)\nfhat = fft(f.(t))\nkappa = (2pi/L)*(-n/2:n/2-1)\nkappa = fftshift(kappa) # Re-order fft frequencies\ndfhat = im*kappa.*fhat\ndfFFT = real(ifft(dfhat))\n\n# Plotting commands\nplot(t, f)\nplot!(t, df)\nplot!(t, dfFD)\nplot!(t, dfFFT)", "meta": {"hexsha": "3167117fe5b67f331ee5ef36101cc9ca00455119", "size": 574, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ddsae/CODE/CH02/CH02_SEC02_3_SpectralDerivative.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "ddsae/CODE/CH02/CH02_SEC02_3_SpectralDerivative.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "ddsae/CODE/CH02/CH02_SEC02_3_SpectralDerivative.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 19.1333333333, "max_line_length": 54, "alphanum_fraction": 0.6236933798, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561694652216, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.7708782519893488}}
{"text": "# using Pkg\r\n# Pkg.add(\"DataStructures\")\r\nusing DataStructures\r\n\r\nstruct Node\r\n    parent\r\n    f::Int64\r\n    g::Int64\r\n    board::Array{Int64,1}\r\nend\r\n\r\nfunction findblank(A::Array{Int64,1})\r\n    x = size(A,1)\r\n    for i = 1:x\r\n        if A[i] == x\r\n            return i\r\n        end\r\n    end\r\n    return -1\r\nend\r\n\r\nfunction up(A::Array{Int64,1})\r\n    N = size(A,1)\r\n    Nsq = isqrt(N)\r\n    blank = findblank(A)\r\n    B = copy(A)\r\n    if blank / Nsq <= 1\r\n        return A\r\n    end\r\n    B[blank-Nsq],B[blank] = B[blank],B[blank-Nsq]\r\n    return B\r\nend\r\n\r\nfunction down(A::Array{Int64,1})\r\n    N = size(A,1)\r\n    Nsq = isqrt(N)\r\n    blank = findblank(A)\r\n    B = copy(A)\r\n    if (blank / Nsq) > (Nsq -1)\r\n        return A\r\n    end\r\n    B[blank+Nsq],B[blank] = B[blank],B[blank+Nsq]\r\n    return B\r\nend\r\n\r\nfunction left(A::Array{Int64,1})\r\n    N = size(A,1)\r\n    Nsq = isqrt(N)\r\n    blank = findblank(A)\r\n    B = copy(A)\r\n    if (blank % Nsq) == 1\r\n        return A\r\n    end\r\n    B[blank-1],B[blank] = B[blank],B[blank-1]\r\n    return B\r\nend\r\n\r\nfunction right(A::Array{Int64,1})\r\n    N = size(A,1)\r\n    Nsq = isqrt(N)\r\n    blank = findblank(A)\r\n    B = copy(A)\r\n    if (blank % Nsq) == 0\r\n        return A\r\n    end\r\n    B[blank+1],B[blank] = B[blank],B[blank+1]\r\n    return B\r\nend\r\n\r\nfunction manhattan(A::Array{Int64,1})\r\n    N = size(A,1)\r\n    Nsq = isqrt(N)\r\n    r = 0\r\n    for i in 1:N\r\n        if (A[i]==i || A[i]==N)\r\n            continue\r\n        end\r\n        row1 = floor((A[i]-1) / Nsq)\r\n        col1 = (A[i]-1) % Nsq\r\n        row2 = floor((i-1) / Nsq)\r\n        col2 = (i-1) % Nsq\r\n        r+= abs(row1 - row2) + abs(col1 - col2)\r\n    end\r\n    return r\r\nend  \r\n\r\n# start = [1,2,3,4,5,6,7,9,8]\r\n# start = [6,5,4,1,7,3,9,8,2] #26 moves\r\n# start = [7,8,4,11,12,14,10,15,16,5,3,13,2,1,9,6] # 50 moves\r\n# start = [7,14,16,9,10,2,11,13,6,15,4,12,5,1,8,3] # 54 moves\r\nstart = [15,14,1,6,9,11,4,12,16,10,7,3,13,8,5,2] # 52 moves\r\ngoal = [x for x in 1:length(start)]\r\n# println(\"The manhattan distance of $start is  $(manhattan(start))\")\r\ng = 0\r\nf = g + manhattan(start)\r\npq = PriorityQueue()\r\nactions = [up,down,left,right]\r\ndd = Dict{Array{Int64,1},Int64}()\r\nsnode = Node(C_NULL,f,g,start)\r\nenqueue!(pq,snode,f)\r\npos_seen = 0\r\nmoves = 0\r\nwhile (!isempty(pq))\r\n    current = dequeue!(pq)\r\n    if haskey(dd,current.board)\r\n        continue\r\n    else\r\n        push!(dd, current.board =>current.f)\r\n    end\r\n    if (current.board == goal)\r\n        while(current.board != start)\r\n            h = current.f - current.g\r\n            println(\"$(current.board) $(current.f) $h\")\r\n            global moves +=1\r\n            current = current.parent[]\r\n        end\r\n        println(start)\r\n        println(\"$start solved in $moves moves after looking at $pos_seen positions\")\r\n        break\r\n    end\r\n    global pos_seen+=1\r\n    for i in 1:4\r\n        if (i == 1)\r\n            nextmove = up(current.board)\r\n        elseif (i == 2)\r\n            nextmove = down(current.board)\r\n        elseif (i == 3)\r\n            nextmove = left(current.board)\r\n        else\r\n            nextmove = right(current.board)\r\n        end\r\n        # if (nextmove === nothing || nextmove == current.board || haskey(dd,nextmove))\r\n        if (nextmove == current.board || haskey(dd,nextmove))\r\n            # println(\"I continued $pos_seen\")\r\n            continue\r\n        else\r\n            newg = current.g + 1\r\n            newf = newg + manhattan(nextmove)\r\n            n = Node(Ref(current),newf,newg,nextmove)\r\n            enqueue!(pq,n,newf)\r\n        end\r\n    end\r\nend\r\nprintln(\"END\")\r\n", "meta": {"hexsha": "11e50c69908f9fc778725444a7b35344510ce5a5", "size": 3549, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Npuzzle.jl", "max_stars_repo_name": "gregory1506/Julia_Npuzzle", "max_stars_repo_head_hexsha": "5f6166c923814dbfd5ba1518a94328379f09bdec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Npuzzle.jl", "max_issues_repo_name": "gregory1506/Julia_Npuzzle", "max_issues_repo_head_hexsha": "5f6166c923814dbfd5ba1518a94328379f09bdec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Npuzzle.jl", "max_forks_repo_name": "gregory1506/Julia_Npuzzle", "max_forks_repo_head_hexsha": "5f6166c923814dbfd5ba1518a94328379f09bdec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.475862069, "max_line_length": 88, "alphanum_fraction": 0.5114116653, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7708701498456303}}
{"text": "module AReg\nusing PolynomialRoots\nusing StatsBase\nusing Statistics\n\nexport ARp, ARp_est, fit , simulate,simulateAR1, unc_mean\n##\n\"Autoregressive Structure (only normal errors are considered for the moment)\"\nmutable struct ARp\n    vecpar::Vector{Real}\n    sigma::Real\n    start_vals::Vector{Real}\nend\n\nmutable struct ARp_est\n    ar::ARp\n    obs::Vector{Real}\n    estimates::Vector{Real}\n    sigma::Real\nend\n\n\nfunction unc_mean(arp::ARp)\n    \"compute the unconditional mean of an ARp type\"\n    p = length(arp.vecpar)\n    p==0 ? (return 0) : (return arp.vecpar[1]/(1-sum(arp.vecpar[2:end])))\nend\nfunction is_ar_stationary(arp::ARp)\n    coeff = arp.vecpar\n    #coefficients of the characteristic polynomial\n    char_pol_coeff = [coeff[1]; - coeff[2:end]]\n    #compute the roots of the char poly\n    tmp =abs2.(roots(Array{Float64}(char_pol_coeff)))\n    #if all the roots lie outside the unit circle then the process is stationary\n    all(tmp.>1) ? (return true,unc_mean(arp)) : (return false)\nend\n\n\n\n##\n\"fit an AR(p) with predetermined p, the starting values are not estimated\nTo Do : need to add a method for the observations only.. it should return the\nARp_est with optimal p\n\"\nfunction fitARp(obs::Vector{<:Real}, order;demean=true)\n    p = order # number of autoregressive terms (constant excluded)\n    \n    ## Ols estimation of the AR(p) coefficients\n    Y = obs[p+1:end]\n    T = length(Y)\n    X = ones(T,p+1)\n    #println(p)\n    for i=1:p\n        X[:,p+2-i] = obs[p+1-i:end-i]\n    end\n\n    est_par = (X'*X)\\(X'Y)\n    #standard deviation of residuals\n    sigma = std(X*est_par - Y)\n    return est_par, sigma\nend\n\nfunction fitARp(obs::Vector{<:Real},arp::ARp;demean=true)\n    p = length(arp.vecpar)-1\n    est_par, sigma = fitARp(obs, p)\n    \n    return ARp_est(arp,obs,est_par, sigma)\nend\n\n\"Sample an AR process of lenght T and  parameters specified in vecpar starting\nfrom phi_0 to phi_p where p is the order of the process\"\nfunction simulate(ar::ARp,T::Int=1000)\n    sigma = ar.sigma\n    vecpar = ar.vecpar\n    start_vals = ar.start_vals\n    #Y_T = zeros(T)\n    p = length(vecpar)-1\n    epsilon_T = sigma.* randn(T)\n    Y_T = epsilon_T\n\n    if isempty(start_vals) # if no start values are given pick them at ranUtilities\n        if p>0\n            start_vals = sigma.*randn(p)\n        else\n            start_vals = []\n        end\n    end\n    lagged_vals = start_vals\n    for t = 1:T\n        Y_T[t] +=  vecpar'*[1;lagged_vals ]\n        if p>0\n            next_lagged_vals = circshift(lagged_vals,-1)\n            next_lagged_vals[end] = Y_T[t]\n        else\n            next_lagged_vals = Y_T[t]\n        end\n        lagged_vals = next_lagged_vals\n    end\n    return Y_T\nend\n\n\nfunction simulateAR1(vecPar::Vector{<:Real},sigma::Float64;T::Int=1000)\n    #start on the unconditional mean\n    μ = vecPar[1]./(1-vecPar[2])\n    #Y_T = zeros(T)\n    epsilon_T = sigma.* randn(T)\n    Y_T = epsilon_T\n    lagged_val = μ\n    for t = 1:T\n        Y_T[t] +=  vecPar[1] + vecPar[2] * lagged_val\n        lagged_val = Y_T[t]\n    end\n    return Y_T\nend\n\n\n\nfunction ar1_variance(x)\n    try \n        return AReg.fitARp(Float64.(x), 1)[2]\n    catch \n        return NaN\n    end\nend\nexport ar1_variance\n\n\n\n\n\nend\n", "meta": {"hexsha": "7135bae6f452c8db9cb4fb2e2f446c584682498b", "size": 3188, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/AReg.jl", "max_stars_repo_name": "domenicodigangi/ScoreDrivenERGM.jl", "max_stars_repo_head_hexsha": "71008a54d1397e6fd0c42489de6ebf7ff0a1ae2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AReg.jl", "max_issues_repo_name": "domenicodigangi/ScoreDrivenERGM.jl", "max_issues_repo_head_hexsha": "71008a54d1397e6fd0c42489de6ebf7ff0a1ae2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AReg.jl", "max_forks_repo_name": "domenicodigangi/ScoreDrivenERGM.jl", "max_forks_repo_head_hexsha": "71008a54d1397e6fd0c42489de6ebf7ff0a1ae2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.969924812, "max_line_length": 83, "alphanum_fraction": 0.6433500627, "num_tokens": 961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7708701494068918}}
{"text": "\"\"\"\n## deemat!\n\nThis subroutine returns the elastic dee matrix for ih=3 (plane strain),\nih=4 (axisymmetry or plane strain elastoplasticity) or ih=6\n(three dimensions).\n\n### Method\n```julia\ndeemat!(dee, e, v)\n```\n\n### Arguments\n```julia\n* dee::Matrix{Float64}         : Dee matrix (Updated)\n* e::Float64                   : Young's modulus\n* v::Float64                   : Poisson's ratio\n```\n\"\"\"\nfunction deemat!(dee::Array{Float64, 2}, e::Float64, v::Float64)\n#\n# This subroutine returns the elastic dee matrix for ih=3 (plane strain),\n# ih=4 (axisymmetry or plane strain elastoplasticity) or ih=6\n# (three dimensions).\n#\n  ih=size(dee,1)\n  v1 = 1.0-v\n  c = e/((1.0+v)*(1.0-2v))\n  if ih == 3\n    dee[1,1] = v1*c\n    dee[2,2] = v1*c\n    dee[1,2] = v*c\n    dee[2,1] = v*c\n    dee[3,3] = 0.5*c*(1.0-2v)\n  elseif ih == 4\n    dee[1,1] = v1*c\n    dee[2,2] = v1*c\n    dee[4,4] = v1*c\n    dee[3,3] = 0.5*c*(1.0-2v) \n    dee[1,2] = v*c\n    dee[2,1] = v*c\n    dee[1,4] = v*c\n    dee[4,1] = v*c\n    dee[2,4] = v*c\n    dee[4,2] = v*c\n  elseif ih == 6\n   v2 = v/(1.0-v)\n   vv = (1.0-2v)/(1.0-v)*0.5\n   for i in 1:3\n    dee[i,i] = 1.0\n   end\n   for i in 4:6\n     dee[i,i] = vv\n   end\n    dee[1,2] = v2\n    dee[2,1] = v2\n    dee[1,3] = v2\n    dee[3,1] = v2\n    dee[2,3] = v2\n    dee[3,2] = v2\n    dee[:, :] = dee*e/(2.0*(1.0+v)*vv)\n  else\n   println(\"wrong size for dee matrix\")\n  end\nend", "meta": {"hexsha": "b150d618a162abf3a7017096f1f6bf7a9ea24d9a", "size": 1374, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PtFEM/Main/deemat.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PtFEM.jl-9b64898b-da2a-5774-a656-fd6fb605642c", "max_stars_repo_head_hexsha": "35a9d7c796a92f5d44bd37a2af574fb366fa51ba", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2017-04-16T11:52:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T06:41:59.000Z", "max_issues_repo_path": "src/PtFEM/Main/deemat.jl", "max_issues_repo_name": "UnofficialJuliaMirror/PtFEM.jl-9b64898b-da2a-5774-a656-fd6fb605642c", "max_issues_repo_head_hexsha": "35a9d7c796a92f5d44bd37a2af574fb366fa51ba", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2018-07-04T00:14:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:16.000Z", "max_forks_repo_path": "src/PtFEM/Main/deemat.jl", "max_forks_repo_name": "UnofficialJuliaMirror/PtFEM.jl-9b64898b-da2a-5774-a656-fd6fb605642c", "max_forks_repo_head_hexsha": "35a9d7c796a92f5d44bd37a2af574fb366fa51ba", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2017-05-28T21:43:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T12:43:12.000Z", "avg_line_length": 21.1384615385, "max_line_length": 73, "alphanum_fraction": 0.5211062591, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7708701489681531}}
{"text": "\"\"\"\nConstruct a basis for identity tangent space of differomorphisms, using the fourier\nbasis. The notation for the is in accordance with the project thesis, with \"_\"\n denoting the \"flipping\"  [bi(x, y), 0] -> [0, bi(y, x)]\n\"\"\"\n\n\"\"\"\nTYPE 1 Basis Function: Sines\n\"\"\"\nfunction ξ(k)\n    return x ->  [√2*sin(π*k*x[1]), 0.]\nend\n\nfunction ξx(k)\n    return x -> √2π*k*cos(π*k*x[1]) \nend\n\nfunction Dξ(k)\n    return x -> [[√2π*k*cos(π*k*x[1]) 0.]; [0. 0.]]\nend\n\n\n\n\"\"\"\nTYPE 2 Basis Function: Sines*Cosines\n\"\"\"\nfunction η(k, l)\n    return x -> [2*sin(π*k*x[1])*cos(2π*l*x[2]), 0.]\nend\n\nfunction ηx(k, l)\n    return x -> 2π*k*cos(π*k*x[1])*cos(2π*l*x[2])\nend\n\nfunction Dη(k, l)\n    return x -> [[2π*k*cos(π*k*x[1])*cos(2π*l*x[2]) -4π*l*sin(π*k*x[1])*sin(2π*l*x[2])]; [0. 0.]]\nend\n\n\"\"\"\nTYPE 3 Basis Function: Sines*Sines\n\"\"\"\nfunction φ(k, l)\n    return x -> [2*sin(π*k*x[1])*sin(2π*l*x[2]), 0.]\nend\n\nfunction φx(k, l)\n    return x -> 2π*k*cos(π*k*x[1])*sin(2π*l*x[2])\nend\n\nfunction Dφ(k, l)\n    return x -> [[2π*k*cos(π*k*x[1])*sin(2π*l*x[2]) 4π*l*sin(π*k*x[1])*cos(2π*l*x[2])];[0. 0.]]\nend\n\n\n\"\"\"\n***********************************\nNow for the y-driection vector fields\n*************************************\n\"\"\"\n\n\"\"\"\nTYPE 1 Basis Function: Sines\n\"\"\"\nfunction _ξ(l)\n    return x ->  [0., √2*sin(π*l*x[2])]\nend\n\nfunction _ξy(l)\n    return x -> √2π*l*cos(π*l*x[2]) \nend\n\nfunction _Dξ(l)\n    return x -> [[0. 0.]; [0. √2π*l*cos(π*l*x[2])]]\nend\n\n\n\"\"\"\nTYPE 2 Basis Function: Sines*Cosines\n\"\"\"\nfunction _η(l, k)\n    return x -> [0., 2*sin(π*l*x[2])*cos(2π*k*x[1])]\nend\n\nfunction _ηy(l, k)\n    return x -> 2π*l*cos(π*l*x[2])*cos(2π*k*x[1])\nend\n\nfunction _Dη(l, k)\n    return x -> [[0. 0.]; [-4π*k*sin(π*l*x[2])*sin(2π*k*x[1]) 2π*l*cos(π*l*x[2])*cos(2π*k*x[1])]]\nend\n\n\n\"\"\"\nTYPE 2 Basis Function: Sines*Sines\n\"\"\"\nfunction _φ(l, k)\n    return x -> [0., 2*sin(π*l*x[2])*sin(2π*k*x[1])]\nend\n\nfunction _φy(l, k)\n    return x -> 2π*l*cos(π*l*x[2])*sin(2π*k*x[1])\nend\n\nfunction _Dφ(l, k)\n    return x -> [[0. 0.]; [4π*k*sin(π*l*x[2])*cos(2π*k*x[1]) 2π*l*cos(π*l*x[2])*sin(2π*k*x[1])]]\nend\n\n\n\"\"\"\nFunction for constructing bass functions with necessary derivatives\n    * K::Int : Maximal Frequency of trigonometric functions\n\nReturns:\n    * B, DB, divB, H1, H2::Array{Function}\n\"\"\"\nfunction construct_basis(K::Int)\n    N = K + 2K^2\n    \n    # Declare output function arrays\n    B = Array{Function}(undef, 2N) # Basis functions\n    DB = Array{Function}(undef, 2N) # Jacobians of basis functions\n    divB = Array{Function}(undef, 2N) # Divergence of basis functions.\n    \n    # Loop through type 1 basis functions (only sines)\n    for i in 1:K\n        k = i\n        \n        # Basis Functions\n        B[i] = ξ(k)\n        B[N + i] = _ξ(k)\n        \n        # Jacobian Matrices\n        DB[i] = Dξ(k)\n        DB[N + i] = _Dξ(k)\n\n        # Divergence \n        divB[i] = ξx(k)\n        divB[N + i] = _ξy(k)\n    end\n    \n\n    for i in (K+1):(K+K^2)\n        # Remap indices i -> j, k, l\n        j = i - K\n        k = ((j-1) ÷ K) + 1\n        l = j - K * ((j-1) ÷ K)\n        \n        # Basis Functions\n        B[i] = η(k, l)\n        B[N + i] = _η(k, l)\n        \n        # Jacobian Matrices\n        DB[i] = Dη(k, l)\n        DB[N + i] = _Dη(k, l)\n\n        # Divergence \n        divB[i] = ηx(k, l)\n        divB[N + i] = _ηy(k, l)\n    end\n    \n    for i in (K + K^2 + 1):N\n        # Remap indices i -> j, k, l\n        j = i - (K + K^2)\n        k = ((j-1) ÷ K) + 1\n        l = j - K * ((j-1) ÷ K)\n        \n\n        # Basis Functions\n        B[i] = φ(k, l)\n        B[N + i] = _φ(k, l)\n        \n        # Jacobian Matrices\n        DB[i] = Dφ(k, l)\n        DB[N + i] = _Dφ(k, l)\n\n        # Divergence \n        divB[i] = φx(k, l)\n        divB[N + i] = _φy(k, l)\n    end\n    \n    return B, DB, divB\nend", "meta": {"hexsha": "fd4498677447e7f06293272f1bea728ec5c26fdb", "size": 3750, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fourier-basis.jl", "max_stars_repo_name": "jorgenriseth/SurfaceRegistration.jl", "max_stars_repo_head_hexsha": "6b0305fedc552e6fe5c5d74aa0df8a1cc27971ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fourier-basis.jl", "max_issues_repo_name": "jorgenriseth/SurfaceRegistration.jl", "max_issues_repo_head_hexsha": "6b0305fedc552e6fe5c5d74aa0df8a1cc27971ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fourier-basis.jl", "max_forks_repo_name": "jorgenriseth/SurfaceRegistration.jl", "max_forks_repo_head_hexsha": "6b0305fedc552e6fe5c5d74aa0df8a1cc27971ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6043956044, "max_line_length": 97, "alphanum_fraction": 0.492, "num_tokens": 1470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660962919971, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7708687252544811}}
{"text": "using LinearAlgebra\nusing KernelFunctions\n\n\n\"\"\"\n    correlation_kernel_Gram(B,R,unif_samples,all_samples,test_samples,k,sigma)\n\nCompute Gram matrix of correlation kernel on test data.\n\n# Arguments\n- `B::Array{Float64,2}`: B matrix with same size as K.\n- `R:Array{Float64,2}`: Cholesky s.t. K = R'R\n- `unif_samples:Array{Float64,2}`: number of uniformly sampled points for correlation kernel approximaton\n- `all_samples:Array{Float64,2}`: array containing all points used to write the representer\n- `test_samples:Array{Float64,2}`: test samples for evaluating the Gram matrix\n- `k:kernel`: RKHS kernel function; see KernelFunctions.\n- `sigma:Float`: RKHS kernel bandwidth.\n\n# Output\n- `GramK::Array{Float64,2}`: Gram matrix of size |test_samples| x |test_samples|\n\n\"\"\"\nfunction correlation_kernel_Gram(B,R,unif_samples,all_samples,test_samples,k,sigma)\n\n    F = cholesky(B).U; # B = F'F\n\n    # construct cross kernel matrices\n    x_m = (all_samples)'/(sigma);\n    x_p = (unif_samples)'/(sigma);\n    K_mp = kernelmatrix(k, x_m, x_p);\n\n    x_t = (test_samples)'/(sigma);\n    K_mt = kernelmatrix(k, x_m, x_t);\n\n    T_1 = F*((R')\\K_mp);\n    p = size(K_mp,2);\n    M = (1/p)*T_1*T_1' + I;\n\n    T_2 = F*((R')\\K_mt);\n\n    GramK = T_2'*(M\\T_2); \n\n    GramK = 0.5*(GramK+GramK');\n\n    return GramK;\nend\n\n\n\"\"\"\n    likelihood_kernel_Gram(B,R,all_samples,test_samples,k,sigma)\n\nCompute Gram matrix of likelihood kernel on test data.\n\n# Arguments\n- `B::Array`: B matrix with same size as K.\n- `R:Array`: Cholesky s.t. K = R'R\n- `all_samples:Array`: array containing all points used to write the representer\n- `test_samples:Array`: test samples for evaluating the Gram matrix\n- `k:kernel`: RKHS kernel function; see KernelFunctions.\n- `sigma:Float`: RKHS kernel bandwidth.\n\n# Output\n- `GramA::Array{Float64,2}`: Gram matrix of size |test_samples| x |test_samples|\n\n\"\"\"\nfunction likelihood_kernel_Gram(B,R,all_sples,test_sples,k,sigma)\n\n    F = cholesky(B).U; # B = F'F  \n    \n    # construct cross kernel matrices\n    x_m = (all_sples)'/(sigma);\n    x_t = (test_sples)'/(sigma);\n    K_mt = kernelmatrix(k, x_m, x_t);\n\n    T = F*((R')\\K_mt);\n    GramA = T'*T;\n\n    return GramA;\nend\n\n", "meta": {"hexsha": "c1ad3eca674bf52e3c69c416d3fb73c2ffee39dd", "size": 2167, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "algo/kernels.jl", "max_stars_repo_name": "mrfanuel/LearningContinuousDPPs.jl", "max_stars_repo_head_hexsha": "e4d595dadca262278d43f457ed009e1ff2452989", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algo/kernels.jl", "max_issues_repo_name": "mrfanuel/LearningContinuousDPPs.jl", "max_issues_repo_head_hexsha": "e4d595dadca262278d43f457ed009e1ff2452989", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algo/kernels.jl", "max_forks_repo_name": "mrfanuel/LearningContinuousDPPs.jl", "max_forks_repo_head_hexsha": "e4d595dadca262278d43f457ed009e1ff2452989", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7530864198, "max_line_length": 105, "alphanum_fraction": 0.6820489156, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182845, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7708687240177831}}
{"text": "\ndegtorad(deg) = deg*π/180\n\n# adapted from Distances.jl\n@inline function haversine(λ₁, φ₁, λ₂, φ₂)\n    Δλ = λ₂ - λ₁  # longitudes\n    Δφ = φ₂ - φ₁  # latitudes\n\n    # haversine formula\n    a = sin(Δφ/2)^2 + cos(φ₁)*cos(φ₂)*sin(Δλ/2)^2\n    \n    # # distance on the sphere\n    2 * 6_371_000 * asin( min(√a, one(a)) ) # take care of floating point errors\nend\n\nfunction dist_pairwise(long, lat)\n    dim = size(long, 1)\n    dist = Array{Float64}(undef, dim, dim)\n    @fastmath @inbounds for i ∈ axes(dist, 1), j ∈ 1:i\n        dist[i, j] = haversine(long[i], lat[i], long[j], lat[j])\n    end\n    return Symmetric(dist, :L)\nend\n\nfunction dist_pointwise!(out, long_point, lat_point, long_vec, lat_vec)\n    @fastmath @inbounds for i ∈ eachindex(out)\n        out[i] = haversine(long_point, lat_point, long_vec[i], lat_vec[i])\n    end\n    return out\nend\n\nfunction fill_diag!(matrix, value)\n    foreach(i -> matrix[i, i] = value, 1:size(matrix, 1))\nend\n", "meta": {"hexsha": "6bd7f68614e305011ae0a3b5cf2d890e25623800", "size": 941, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "gen35/BeerTest", "max_stars_repo_head_hexsha": "3ed7074e0e44aa28b556c6af0425c64613260317", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "gen35/BeerTest", "max_issues_repo_head_hexsha": "3ed7074e0e44aa28b556c6af0425c64613260317", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "gen35/BeerTest", "max_forks_repo_head_hexsha": "3ed7074e0e44aa28b556c6af0425c64613260317", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8857142857, "max_line_length": 80, "alphanum_fraction": 0.6301806589, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660989095221, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7708687229602151}}
{"text": "#=\nEuler discovered the remarkable quadratic formula:\n\nn² + n + 41\n\nIt turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 41² + 41 + 41 is clearly divisible by 41.\n\nThe incredible formula  n² − 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, −79 and 1601, is −126479.\n\nConsidering quadratics of the form:\n\nn² + an + b, where |a| < 1000 and |b| < 1000\n\nwhere |n| is the modulus/absolute value of n\ne.g. |11| = 11 and |−4| = 4\nFind the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0.\n=#\n\nusing Primes\n\nfunction longestprimerun(a,b)\n  i = 0\n  while isprime((i^2)+(a*i)+b)\n    i+= 1\n  end\n  i\nend\n\nfunction calc()\n  (mina, maxa) = (-1000, 1000)\n  (largesta, largestb) = (0,0)\n  largest = 0\n  for a in mina:maxa, b in mina:maxa\n    primerun = longestprimerun(a,b)\n    if primerun > largest\n      (largesta, largestb) = (a,b)\n      largest = primerun\n    end\n  end\n  largesta * largestb\nend\n@time println(calc())\n", "meta": {"hexsha": "78fe31bb6291c31e751019f143a38193a067da3e", "size": 1236, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p27.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p27.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p27.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 28.7441860465, "max_line_length": 235, "alphanum_fraction": 0.6779935275, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966096291997, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.770868720845079}}
{"text": "module CubicEquation\n\nexport Solver\n\ntype Solver\nend\n\nfunction (solver::Solver)(a::Real, b::Real, c::Real, d::Real)\n    if a == zero(typeof(a))\n        return Base.error(\"Can't solve. a=0 in a*x³ + b*x² + c*x + d =0\")\n    end\n    f = (3c/a - (b/a)^2) / 3\n    g = (2(b/a)^3 - (9*b*c/a^2) + 27d/a) / 27\n    h = g^2 / 4 + f^3 / 27\n    if f == zero(typeof(f)) && g == zero(typeof(g)) && h == zero(typeof(h))\n        x1 = x2 = x3 = -cbrt(d/a)\n        return [x1, x2, x3]\n    elseif  h <= zero(typeof(h))\n        return three_real_root(a, b, g, h)\n    elseif h > zero(typeof(h))\n        return one_real_root(a, b, g, h)\n    end\n\n    return Base.error(\"Can't solve when a=$(a) b=$(b) c=$(c) d=$(d)\")\nend\n\nfunction three_real_root(a::Real, b::Real, g::Float64, h::Float64)\n    i = (g^2 / 4 - h)^(1/2)\n    j = cbrt(i)\n    K = acos(-(g/2i))\n    L = -j\n    M = cos(K/3)\n    N = sqrt(3) * sin(K/3)\n    P = -(b/3a)\n    x1 = 2j * cos(K/3) - (b/3a)\n    x2 = L * (M + N) + P\n    x3 = L * (M - N) + P\n    return sort([x1, x2, x3])\nend\n\nfunction one_real_root(a::Real, b::Real, g::Float64, h::Float64)\n    R = -g/2 + sqrt(h)\n    S = cbrt(R)\n    T = -g/2 - sqrt(h)\n    U = cbrt(T)\n    x1 = (S + U) - (b/3a)\n    x2 = -(S + U)/2 - (b/3a) - im*(S-U)*sqrt(3) / 2\n    x3 = -(S + U)/2 - (b/3a) + im*(S-U)*sqrt(3) / 2\n    return Union{Real,Complex}[x1, x2, x3]\nend\n\nfunction (solver::Solver)(a::Real, b::Real, c::Real)\n    if a == zero(typeof(a))\n        return Base.error(\"Can't solve. a=0 in a*x² + b*x + c = 0\")\n    end\n\n    # Discriminant for quadratic equation\n    D = b^2 - 4*a*c\n\n    if D >= zero(typeof(D))\n        return [(-b - √(D)) / 2a, (-b + √(D)) / 2a]\n    elseif D < zero(typeof(D))\n        return [(-b - √(-D)*im) / 2a, (-b + √(-D)*im) / 2a]\n    else\n        return Base.error(\"Can't solve when a=$(a) b=$(b) c=$(c)\")\n    end\nend\n\nend #end module\n", "meta": {"hexsha": "59c02bbf725cd9abf2201e0f7caac88970b20f1b", "size": 1837, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CubicEquation.jl", "max_stars_repo_name": "KanchiShimono/CubicEquation.jl", "max_stars_repo_head_hexsha": "5a1dab3c4dc61d25d791f934f34834214ac85a74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CubicEquation.jl", "max_issues_repo_name": "KanchiShimono/CubicEquation.jl", "max_issues_repo_head_hexsha": "5a1dab3c4dc61d25d791f934f34834214ac85a74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CubicEquation.jl", "max_forks_repo_name": "KanchiShimono/CubicEquation.jl", "max_forks_repo_head_hexsha": "5a1dab3c4dc61d25d791f934f34834214ac85a74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2428571429, "max_line_length": 75, "alphanum_fraction": 0.4839412085, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660989095221, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7708687185508128}}
{"text": "# If an integer is passed down to the function, it means that the user is requesting an exact number of iterations.\r\nfunction bisection_it(f,ansatz::Tuple{Float64,Float64}; N::Int64=100)\r\n    (lower,upper) = ansatz\r\n    mid = 0\r\n    for _ in 1:N\r\n        \r\n    mid = (lower + upper)/2\r\n        \r\n        if f(lower)*f(mid) < 0\r\n            upper = mid\r\n        elseif f(lower)*f(mid) > 0\r\n            lower = mid\r\n        else\r\n            return mid\r\n        end\r\n        \r\n    end\r\n    return mid\r\nend\r\n\r\n# f(x) = sin(x)\r\n# bisection(f,(2.,4.))\r\n\r\n\r\n#If then a Float is passed to the function, then it means it must mean an objective relative error.\r\nfunction bisection_err(f,ansatz::Tuple{Float64,Float64}; error::Float64=0.01)\r\n    mid = (lower + upper)/2;\r\n    ea = 1; #Initialize\r\n    #We do the first iteration, otherwise, there is no way to have a relative error to measure\r\n    if f(lower)*f(mid) < 0\r\n        upper = mid\r\n    elseif f(lower)*f(mid) > 0\r\n        lower = mid\r\n    else\r\n        return mid\r\n    end\r\n    #Now we start doing the iterations until it is done\r\n    while ea > error\r\n        last = mid #We store the last approximation\r\n        mid = (lower + upper)/2\r\n        ea = abs((mid-last)/mid);\r\n        \r\n        if f(lower)*f(mid) < 0\r\n            upper = mid\r\n        elseif f(lower)*f(mid) > 0\r\n            lower = mid\r\n        else\r\n            return mid\r\n        end\r\n        \r\n    end\r\n    return mid\r\nend", "meta": {"hexsha": "74998fdf4015f2b40e05235688889e534b9779e9", "size": 1441, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bisection.jl", "max_stars_repo_name": "leogabac/FiscomTools.jl", "max_stars_repo_head_hexsha": "6f47512c3ccc1a866088141fc367554cdf88dc84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bisection.jl", "max_issues_repo_name": "leogabac/FiscomTools.jl", "max_issues_repo_head_hexsha": "6f47512c3ccc1a866088141fc367554cdf88dc84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bisection.jl", "max_forks_repo_name": "leogabac/FiscomTools.jl", "max_forks_repo_head_hexsha": "6f47512c3ccc1a866088141fc367554cdf88dc84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1886792453, "max_line_length": 116, "alphanum_fraction": 0.5385149202, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7708055826731041}}
{"text": "# ---\n# title: 688. Knight Probability in Chessboard\n# id: problem688\n# author: Indigo\n# date: 2021-06-29\n# difficulty: Medium\n# categories: Dynamic Programming\n# link: <https://leetcode.com/problems/knight-probability-in-chessboard/description/>\n# hidden: true\n# ---\n# \n# On an `N`x`N` chessboard, a knight starts at the `r`-th row and `c`-th column\n# and attempts to make exactly `K` moves. The rows and columns are 0 indexed, so\n# the top-left square is `(0, 0)`, and the bottom-right square is `(N-1, N-1)`.\n# \n# A chess knight has 8 possible moves it can make, as illustrated below. Each\n# move is two squares in a cardinal direction, then one square in an orthogonal\n# direction.\n# \n# \n# \n# ![](https://assets.leetcode.com/uploads/2018/10/12/knight.png)\n# \n# \n# \n# Each time the knight is to move, it chooses one of eight possible moves\n# uniformly at random (even if the piece would go off the chessboard) and moves\n# there.\n# \n# The knight continues moving until it has made exactly `K` moves or has moved\n# off the chessboard. Return the probability that the knight remains on the\n# board after it has stopped moving.\n# \n# \n# \n# **Example:**\n# \n#     \n#     \n#     Input: 3, 2, 0, 0\n#     Output: 0.0625\n#     Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.\n#     From each of those positions, there are also two moves that will keep the knight on the board.\n#     The total probability the knight stays on the board is 0.0625.\n#     \n# \n# \n# \n# **Note:**\n# \n#   * `N` will be between 1 and 25.\n#   * `K` will be between 0 and 100.\n#   * The knight always initially starts on the board.\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction knight_probability(n::Int, k::Int, row::Int, col::Int)\n    dp = fill(0, n, n, 2)\n    dp[row + 1, col + 1, 1] = 1\n    for i in 1:k\n        dp1 = @view(dp[:, :, mod1(i, 2)])\n        dp2 = @view(dp[:, :, mod1(i + 1, 2)])\n        idcs = CartesianIndices(dp2)\n        for I in idcs, hop in ((1, 2), (2, 1), (-1, 2), (2, -1), (1, -2), (-2, 1), (-1, -2), (-2, -1))\n            new_I = I + CartesianIndex(hop) \n            new_I ∈ idcs && (dp2[new_I] += dp1[I])            \n        end\n        fill!(dp1, 0)\n    end\n    return sum(dp) / 8 ^ k\nend\n## @lc code=end\n", "meta": {"hexsha": "2c075c3d9859892468a2248c023d82ac1a0c399e", "size": 2243, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/688.knight-probability-in-chessboard.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/688.knight-probability-in-chessboard.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/688.knight-probability-in-chessboard.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 29.9066666667, "max_line_length": 102, "alphanum_fraction": 0.6143557735, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.770805582673104}}
{"text": "import Voronoi\n\nusing Random\nusing Printf\ninclude(\"Draw.jl\")\n\n\nfunction randf(start, finish, n)\n   v = rand(n)\n   return map(x -> start + x*(finish-start), v)\nend\nRandom.seed!(100)\n\nWIDTH = 100.0\nHEIGHT = 100.0\n\nfunction benchmarkLloyd(Z::Array{Tuple{Real, Real}, 1}, ϵ::Number)\n   global WIDTH, HEIGHT\n\n   points = deepcopy(Z)\n\n   results = Array{Tuple{Real, Real, Real, Real}}([])\n\n   times = @elapsed V, f, ∇f, ξ = Voronoi.Optimization.init(points, WIDTH, HEIGHT)\n   evaluations = 1\n   push!(results, (f, ξ, evaluations, times))\n\n   while ξ > ϵ\n      time = @elapsed V, f, ξ = Voronoi.Optimization.lloydIteration(points, V)\n\n      evaluations += 1\n      times += time\n\n      push!(results, (f, ξ, evaluations, times))\n   end\n\n   return results\nend\n\nfunction benchmarkGradient(Z::Array{Tuple{Real, Real}, 1}, ϵ::Number)\n   global WIDTH, HEIGHT\n\n   points = deepcopy(Z)\n\n   results = Array{Tuple{Real, Real, Real, Real}}([])\n\n   times = @elapsed V, f, ∇f, ξ = Voronoi.Optimization.init(points, WIDTH, HEIGHT)\n   evaluations = 1\n   push!(results, (f, ξ, evaluations, times))\n   μ = 0.5\n   α = 0.01\n   λ₀ = 0.01\n\n   while ξ > ϵ\n      d = ∇f\n\n      time = @elapsed V, f, ∇f, ξ, evals = Voronoi.Optimization.lineSearch(points, d, α, λ₀, μ, ϵ, V, f, ∇f, ξ)\n\n      evaluations += evals\n      times += time\n\n      push!(results, (f, ξ, evaluations, times))\n   end\n\n   return results\nend\n\nfunction benchmark(n, ϵ)\n   global WIDTH, HEIGHT\n\n   points = convert(Array{Tuple{Real, Real}}, collect(zip(randf(1, WIDTH-1, n), randf(1, HEIGHT-1, n))))\n\n   lloyd_results = benchmarkLloyd(points, ϵ)\n   gradient_results = benchmarkGradient(points, ϵ)\n\n   lloyd_f = Array{Number}([])\n   lloyd_ξ = Array{Number}([])\n   lloyd_evals = Array{Number}([])\n   lloyd_time = Array{Number}([])\n   gradient_f = Array{Number}([])\n   gradient_ξ = Array{Number}([])\n   gradient_evals = Array{Number}([])\n   gradient_time = Array{Number}([])\n\n   i = 1\n   t₀ = lloyd_results[1][4]\n   for (fᵢ, ξᵢ, evalsᵢ, timeᵢ) in lloyd_results\n      push!(lloyd_f, fᵢ)\n      push!(lloyd_ξ, ξᵢ)\n      push!(lloyd_evals, evalsᵢ)\n      push!(lloyd_time, timeᵢ - t₀)\n      i += 1\n   end\n\n   i = 1\n   t₀ = gradient_results[1][4]\n   for (fᵢ, ξᵢ, evalsᵢ, timeᵢ) in gradient_results\n      push!(gradient_f, fᵢ)\n      push!(gradient_ξ, ξᵢ)\n      push!(gradient_evals, evalsᵢ)\n      push!(gradient_time, timeᵢ - t₀)\n      i += 1\n   end\n\n   #@printf(\"f = %.10g\\t\\t|∇f| = %.10g\\t\\ttime: %s seconds\\n\", f, ξ, time)\n   #@printf(\"f = %.10g\\t\\t|∇f| = %.10g\\t\\ttime: %s seconds\\n\", f, ξ, time)\n\n   Draw.init(0, 0)\n   Draw.clear(string(\"n = \", n))\n   Draw.plot(lloyd_time, lloyd_f, \"xkcd:azure\", \"Algoritmo de Lloyd\", \"-\")\n   Draw.plot(gradient_time, gradient_f, \"xkcd:tomato\", \"Método do Gradiente\", \":\")\n   Draw.legend(\"Tempo (s)\", \"Valor da Função Objetivo\")\n   Draw.commit()\n   println(\"Press Return to finish.\")\n   command = readline(stdin)\n\n   Draw.init(0, 0)\n   Draw.clear(string(\"n = \", n))\n   Draw.plot(lloyd_time, lloyd_ξ, \"xkcd:azure\", \"Algoritmo de Lloyd\", \"-\")\n   Draw.plot(gradient_time, gradient_ξ, \"xkcd:tomato\", \"Método do Gradiente\", \":\")\n   Draw.legend(\"Tempo (s)\", \"Norma do Gradiente\")\n   Draw.commit()\n   println(\"Press Return to finish.\")\n   command = readline(stdin)\nend\n\nϵ = 10^-2\nbenchmark(3, ϵ)\nbenchmark(30, ϵ)\nbenchmark(100, ϵ)\nbenchmark(300, ϵ)\nbenchmark(1000, ϵ)\n", "meta": {"hexsha": "005f9054d5b3a6ccbfb6dac9ff4cba8fa9eee30f", "size": 3327, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Voronoi/demos/benchmark.jl", "max_stars_repo_name": "arthursantana/coveringWithCircles", "max_stars_repo_head_hexsha": "96e77ddb4ededfacfaee953ed1434154fb9e9e44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Voronoi/demos/benchmark.jl", "max_issues_repo_name": "arthursantana/coveringWithCircles", "max_issues_repo_head_hexsha": "96e77ddb4ededfacfaee953ed1434154fb9e9e44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Voronoi/demos/benchmark.jl", "max_forks_repo_name": "arthursantana/coveringWithCircles", "max_forks_repo_head_hexsha": "96e77ddb4ededfacfaee953ed1434154fb9e9e44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.015037594, "max_line_length": 111, "alphanum_fraction": 0.6212804328, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640645, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7708055765520186}}
{"text": "# Numbers and symbols can't be simplified further\nsimplify(n::Number) = n\nsimplify(s::Symbol) = s\n\n# Handles all lengths for ex.args\n# Removes any 0's in a sum\nfunction simplify_sum(ex::Expr)\n    new_args = map(x -> simplify(x), filter(x -> x != 0, ex.args[2:end]))\n    if length(new_args) == 0\n        return 0\n    # Special Case: simplify(:(+x)) == x\n    elseif length(new_args) == 1\n        return new_args[1]\n    else\n        unshift(new_args, :+)\n        return Expr(:call, new_args, Any)\n    end\nend\n\n# Assumes length(ex.args) == 3\n# Removes any 0's in a subtraction\nfunction simplify_subtraction(ex::Expr)\n    new_args = map(x -> simplify(x), filter(x -> x != 0, ex.args[2:end]))\n    if length(new_args) == 0\n        return 0\n    # Special Case: simplify(:(x - x)) == 0\n    elseif length(new_args) == 2 && new_args[1] == new_args[2]\n        return 0\n    else\n        unshift(new_args, :-)\n        return Expr(:call, new_args, Any)\n    end\nend\n\n# Handles all lengths for ex.args\n# Removes any 1's in a product\nfunction simplify_product(ex::Expr)\n    new_args = map(x -> simplify(x), filter(x -> x != 1, ex.args[2:end]))\n    if length(new_args) == 0\n        return 1\n    # Special Case: simplify(:(*x)) == x\n    elseif length(new_args) == 1\n        return new_args[1]\n    # Special Case: simplify(:(x * y * z * 0)) == 0\n    elseif any(new_args .== 0)\n        return 0\n    else\n        unshift(new_args, :*)\n        return Expr(:call, new_args, Any)\n    end\nend\n\n# Assumes length(ex.args) == 3\nfunction simplify_quotient(ex::Expr)\n    new_args = map(x -> simplify(x), ex.args[2:end])\n    # Special Case: simplify(:(x / 1)) == x\n    if new_args[2] == 1\n        return new_args[1]\n    # Special Case: simplify(:(0 / x)) == 0\n    elseif new_args[1] == 0\n        return 0\n    else\n        unshift(new_args, :/)\n        return Expr(:call, new_args, Any)\n    end\nend\n\n# Assumes length(ex.args) == 3\nfunction simplify_power(ex::Expr)\n    new_args = map(x -> simplify(x), ex.args[2:end])\n    # Special Case: simplify(:(x ^ 0)) == 1\n    if new_args[2] == 0\n        return 1\n    # Special Case: simplify(:(x ^ 1)) == x\n    elseif new_args[2] == 1\n        return new_args[1]\n    # Special Case: simplify(:(0 ^ x)) == 0\n    elseif new_args[1] == 0\n        return 0\n    # Special Case: simplify(:(1 ^ x)) == 1\n    elseif new_args[1] == 1\n        return 1\n    else\n        unshift(new_args, :^)\n        return Expr(:call, new_args, Any)\n    end\nend\n\n# Lookup table of simplification rules\nsimplify_lookup = {\n                    :+ => simplify_sum,\n                    :- => simplify_subtraction,\n                    :* => simplify_product,\n                    :/ => simplify_quotient,\n                    :^ => simplify_power\n                  }\n\n# The simplest form of an expression is a fixed point of simplify()\nfunction simplify(ex::Expr)\n    if ex.head == :call\n        if all(map(a -> isa(a, Number), ex.args[2:end]))\n            return eval(ex)\n        end\n        if has(simplify_lookup, ex.args[1])\n            new_ex = simplify_lookup[ex.args[1]](ex)\n            while new_ex != ex\n                new_ex, ex = simplify(new_ex), new_ex\n            end\n            return new_ex\n        else\n          return ex\n        end\n    else\n        return ex\n    end\nend\n\n# The Constant Rule\n# d/dx c = 0\ndifferentiate(x::Number, target::Symbol) = 0\n\n# The Symbol Rule\n# d/dx x = 1\n# d/dx y = 0\nfunction differentiate(s::Symbol, target::Symbol)\n    if s == target\n        return 1\n    else\n        return 0\n    end\nend\n\n# The Sum Rule for Unary and Binary +\n# d/dx +(f) = +(d/dx f)\n# d/dx (f + g) = d/dx f + d/dx g\nfunction differentiate_sum(ex::Expr, target::Symbol)\n    if ex.head != :call || ex.args[1] != :+\n        error(\"Not a valid sum call: $(ex)\")\n    end\n    n = length(ex.args)\n    new_args = Array(Any, n)\n    new_args[1] = :+\n    for i in 2:n\n        new_args[i] = differentiate(ex.args[i], target)\n    end\n    return Expr(:call, new_args, Any)\nend\n\n# The Subtraction Rule for Unary and Binary -\n# d/dx -(f) = -(d/dx f)\n# d/dx (f - g) = d/dx f - d/dx g\nfunction differentiate_subtraction(ex::Expr, target::Symbol)\n    if ex.head != :call || ex.args[1] != :-\n        error(\"Not a valid subtraction call: $(ex)\")\n    end\n    n = length(ex.args)\n    new_args = Array(Any, n)\n    new_args[1] = :-\n    for i in 2:n\n        new_args[i] = differentiate(ex.args[i], target)\n    end\n    return Expr(:call, new_args, Any)\nend\n\n# The Product Rule\n# d/dx (f * g) = (d/dx f) * g + f * (d/dx g)\n# d/dx (f * g * h) = (d/dx f) * g * h + f * (d/dx g) * h + ...\nfunction differentiate_product(ex::Expr, target::Symbol)\n    if ex.head != :call || ex.args[1] != :*\n        error(\"Not a valid product call: $(ex)\")\n    end\n    n = length(ex.args)\n    res_args = Array(Any, n)\n    res_args[1] = :+\n    for i in 2:n\n       new_args = Array(Any, n)\n       new_args[1] = :*\n       for j in 2:n\n           if j == i\n               new_args[j] = differentiate(ex.args[j], target)\n           else\n               new_args[j] = ex.args[j]\n           end\n       end\n       res_args[i] = Expr(:call, new_args, Any)\n    end\n    return Expr(:call, res_args, Any)\nend\n\n# The Quotient Rule\n# d/dx (f / g) = ((d/dx f) * g - f * (d/dx g)) / g^2\nfunction differentiate_quotient(ex::Expr, target::Symbol)\n    if ex.head != :call || ex.args[1] != :/\n        error(\"Not a valid quotient call: $(ex)\")\n    end\n    return Expr(:call,\n                {\n                    :/,\n                    Expr(:call,\n                         {\n                            :-,\n                            Expr(:call,\n                                 {\n                                    :*,\n                                    differentiate(ex.args[2], target),\n                                    ex.args[3]\n                                 },\n                                 Any),\n                            Expr(:call,\n                                 {\n                                    :*,\n                                    ex.args[2],\n                                    differentiate(ex.args[3], target)\n                                 },\n                                 Any)\n                         },\n                         Any),\n                    Expr(:call,\n                         {\n                            :^,\n                            ex.args[3],\n                            2\n                         },\n                         Any)\n                },\n                Any)\nend\n\n# The Power Rule:\n# Case 1: x^n <=> /dx x^n = n * x^(n - 1)\n# Case 2: x^x <=> d/dx x^x = x^x (log(x) + 1)\n# Case 3: n^n <=> d/dx n^n = 0\n# Case 4: n^x <=> n^x * log(n)\n# TODO: Handle general case for things like sin(x)^2\nfunction differentiate_power(ex::Expr, target::Symbol)\n    if ex.head != :call || ex.args[1] != :^\n        error(\"Not a valid power call: $(ex)\")\n    end\n    if ex.args[2] == target && ex.args[3] != target\n        return Expr(:call,\n                    {\n                        :*,\n                        ex.args[3],\n                        Expr(:call,\n                             {\n                                :^,\n                                ex.args[2],\n                                Expr(:call,\n                                     {\n                                         :-,\n                                         ex.args[3],\n                                         1\n                                     },\n                                     Any)\n                             },\n                             Any)\n                    },\n                    Any)\n    elseif ex.args[2] == target && ex.args[3] == target\n        return Expr(:call,\n                    {\n                        :*,\n                        Expr(:call,\n                             {\n                                :^,\n                                target,\n                                target\n                             },\n                             Any),\n                        Expr(:call,\n                             {\n                                :+,\n                                Expr(:call,\n                                     {\n                                        :log,\n                                        target\n                                     },\n                                     Any),\n                                1\n                             },\n                             Any)\n                    },\n                    Any)\n    elseif ex.args[2] != target && ex.args[3] != target\n        return ex\n    else\n        return Expr(:call,\n                    {\n                        :*,\n                        Expr(:call,\n                             {\n                                :^,\n                                ex.args[2],\n                                ex.args[3]\n                             },\n                             Any),\n                        Expr(:call,\n                             {\n                                :log,\n                                ex.args[2]\n                             },\n                             Any)\n                    },\n                    Any)\n    end\nend\n\n# The Sin Rule:\n# d/dx sin(x) = cos(x)\nfunction differentiate_sin(ex::Expr, target::Symbol)\n    if ex.head != :call || ex.args[1] != :sin\n        error(\"Not a valid sin call: $(ex)\")\n    end\n    return Expr(:call,\n                {\n                    :*,\n                    Expr(:call,\n                         {\n                            :cos,\n                            ex.args[2]\n                         },\n                         Any),\n                    differentiate(ex.args[2], target)\n                },\n                Any)\nend\n\n# The Cos Rule:\n# d/dx cos(x) = -sin(x)\nfunction differentiate_cos(ex::Expr, target::Symbol)\n    if ex.head != :call || ex.args[1] != :cos\n        error(\"Not a valid cos call: $(ex)\")\n    end\n    return Expr(:call,\n                {\n                    :*,\n                    Expr(:call,\n                         {\n                            :-,\n                            Expr(:call,\n                                 {\n                                    :sin,\n                                    ex.args[2]\n                                 },\n                                 Any)\n                         },\n                         Any),\n                    differentiate(ex.args[2], target)\n                },\n                Any)\nend\n\n# The Tan Rule:\n# d/dx tan(x) = 1 + tan(x)^2\nfunction differentiate_tan(ex::Expr, target::Symbol)\n    if ex.head != :call || ex.args[1] != :tan\n        error(\"Not a valid tan call: $(ex)\")\n    end\n    return Expr(:call,\n                {\n                    :*,\n                    Expr(:call,\n                         {\n                            :+,\n                            1,\n                            Expr(:call,\n                                 {\n                                    :^,\n                                    Expr(:call,\n                                         {\n                                            :tan,\n                                            ex.args[2]\n                                         },\n                                         Any),\n                                    2\n                                 },\n                                 Any)\n                         },\n                         Any),\n                    differentiate(ex.args[2], target)\n                },\n                Any)\nend\n\n# The Exp Rule:\n# d/dx exp(x) = exp(x)\nfunction differentiate_exp(ex::Expr, target::Symbol)\n    if ex.head != :call || ex.args[1] != :exp\n        error(\"Not a valid exp call: $(ex)\")\n    end\n    return Expr(:call,\n                {\n                    :*,\n                    Expr(:call,\n                         {\n                            :exp,\n                            ex.args[2]\n                         },\n                         Any),\n                    differentiate(ex.args[2], target)\n                },\n                Any)\nend\n\n# The Log Rule:\n# d/dx log(x) = 1 / x\nfunction differentiate_log(ex::Expr, target::Symbol)\n    if ex.head != :call || ex.args[1] != :log\n        error(\"Not a valid log call: $(ex)\")\n    end\n    return Expr(:call,\n                {\n                    :*,\n                    Expr(:call,\n                         {\n                            :/,\n                            1,\n                            ex.args[2]\n                         },\n                         Any),\n                    differentiate(ex.args[2], target)\n                },\n                Any)\nend\n\n# Lookup table of differentation rules\ndifferentiate_lookup = {\n                          :+ => differentiate_sum,\n                          :- => differentiate_subtraction,\n                          :* => differentiate_product,\n                          :/ => differentiate_quotient,\n                          :^ => differentiate_power,\n                          :sin => differentiate_sin,\n                          :cos => differentiate_cos,\n                          :tan => differentiate_tan,\n                          :exp => differentiate_exp,\n                          :log => differentiate_log\n                       }\n\nfunction differentiate(ex::Expr, target::Symbol)\n    if ex.head == :call\n        if has(differentiate_lookup, ex.args[1])\n            return simplify(differentiate_lookup[ex.args[1]](ex, target))\n        else\n            error(\"Don't know how to differentiate $(ex.args[1])\")\n        end\n    else\n        return simplify(differentiate(ex.head))\n    end\nend\nfunction differentiate(ex::Expr, targets::Vector{Symbol})\n    n = length(targets)\n    exprs = Array(Expr, n)\n    for i in 1:n\n        exprs[i] = differentiate(ex, targets[i])\n    end\n    return exprs\nend\n\ndifferentiate(ex::Expr) = differentiate(ex, :x)\n\nfunction differentiate(s::String, target::Symbol)\n    differentiate(parse(s)[1], target)\nend\nfunction differentiate(s::String, targets::Vector{Symbol})\n    differentiate(parse(s)[1], targets)\nend\nfunction differentiate(s::String, target::String)\n    differentiate(parse(s)[1], symbol(target))\nend\nfunction differentiate{T <: String}(s::String, targets::Vector{T})\n    differentiate(parse(s)[1], map(target -> symbol(target), targets))\nend\nfunction differentiate(s::String)\n    differentiate(parse(s)[1], :x)\nend\n\n# begin x = 1; eval(differentiate(:(sin(x)), :x)) end\n\n# Full out differentation returns an immediately evaluable Julia function\n\n# function derivative(ex::Expr, target::Symbol)\n#     function f(x)\n#         d_ex = differentiate(ex, target)\n#         return eval(d_ex)\n#     end\n#     return f\n# end\n\n# function derivative(ex::Expr, target::Symbol, x::Any)\n#     d_ex = differentiate(ex, target)\n#     return eval(d_ex)\n# end\n", "meta": {"hexsha": "930c1fb2350ef8183d450d284a7809db0ba678e7", "size": 14801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/symbolic.jl", "max_stars_repo_name": "aviks/Calculus.jl", "max_stars_repo_head_hexsha": "4a80d5903bfda4b02bc17331734d756009a08fa6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-22T09:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-22T09:31:52.000Z", "max_issues_repo_path": "src/symbolic.jl", "max_issues_repo_name": "aviks/Calculus.jl", "max_issues_repo_head_hexsha": "4a80d5903bfda4b02bc17331734d756009a08fa6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/symbolic.jl", "max_forks_repo_name": "aviks/Calculus.jl", "max_forks_repo_head_hexsha": "4a80d5903bfda4b02bc17331734d756009a08fa6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9615384615, "max_line_length": 73, "alphanum_fraction": 0.3936220526, "num_tokens": 3286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363299661721, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7707715651709529}}
{"text": "# Helper functions for spherical geometry\n\nusing Rotations\n\n\"\"\"\n    c2s(x, y, z) -> [θ, ϕ]\n    c2s(xyz::AbstractVector) -> [θ, ϕ]\n    c2s(xyz::AbstractMatrix) -> [θs; ϕs]\n\nConvert Cartesian vector `[x, y, z]` (or `xyz`) to spherical unit vector `[θ,\nϕ]`.  For AbstractMatrix `xyz`, each column is converted and the results are\nreassmebled into a Matrix using `hcat`.\n\"\"\"\nfunction c2s(x,y,z)\n    θ=atan(y,x)\n    ϕ=atan(z, hypot(x,y))\n    [θ, ϕ]\nend\n\nfunction c2s(xyz::AbstractVector{<:Real})\n    c2s(xyz[1], xyz[2], xyz[3])\nend\n\nfunction c2s(xyz::AbstractMatrix{<:Real})\n    @views reduce(hcat, c2s.(xyz[1,:], xyz[2,:], xyz[3,:]))\nend\n\n\"\"\"\n    s2c(θ, ϕ) -> [x, y, z)\n    s2c(θϕ::AbstractVector) -> [x, y, z]\n    s2c(θϕ::AbstractMaxtrix) -> [xs; ys; zs]\n\nConvert spherical unit vector `[θ, ϕ]` (or `θϕ`) to Cartesian unit vector `[x,\ny, z]`.  For AbstractMatrix `θϕ`, each column is converted and the results are\nreassmebled into a Matrix using `hcat`.\n\"\"\"\nfunction s2c(θ,ϕ)\n    z, r = sincos(ϕ)\n    y, x = sincos(θ) .* r\n    [x, y, z]\nend\n\nfunction s2c(θϕ::AbstractVector{<:Real})\n    s2c(θϕ[1], θϕ[2])\nend\n\nfunction s2c(θϕ::AbstractMatrix{<:Real})\n    @views reduce(hcat, s2c.(θϕ[1,:], θϕ[2,:]))\nend\n\n\"\"\"\n    beamrings(θ, ϕ; nrings=4, dϕ=deg2rad(10/3600)) -> Matrix\n\nCompute the centers of beams that are arranged in concentric rings around the\nspherical coordinates `(θ, ϕ)`, both in radians with `θ` being the longitudinal\ncoordinate and `ϕ` being the latitudinal coordinate.  The number of rings for\nwhich beam centers are returned is given by `nrings`, which defaults to 4.  The\nrings are radially separated by `dϕ` radians, which defaults to the equivalent\nof 10 arcseconds.  The beams returned do not form a packed hexagon because that\nis not possible on a sperical sky, but the number of beams per ring does follow\nthe hexagonal packing convention of `6n` beams for ring `n` (when `n>0`).  The\nso-called boresight beam center at `(θ, ϕ)` is included as well, so 61 beam\ncenters are returned for `nrings==4`.  More generally,\n`nbeams=6*sum(1:nrings)+1` beam centers are returned in a `2xnbeams` Matrix,\nwhere the first row contains the `θ_beam` coordinates and the second row\ncontains the `ϕ_beam` coordinates.\n\"\"\"\nfunction beamrings(θ, ϕ; nrings=4, dϕ=deg2rad(10/3600))\n    nbeams = 6 * sum(1:nrings) + 1\n    θs = Vector{Float64}(undef, nbeams)\n    ϕs = Vector{Float64}(undef, nbeams)\n    θs[1] = 0.0\n    ϕs[1] = π/2\n    b=2\n    for r in 1:nrings\n        nθ = 6r\n        dθ = 2π/nθ\n        ϕr = π/2 - r * dϕ\n        for i in 0:nθ-1\n            θs[b] = i*dθ\n            ϕs[b] = ϕr\n            b += 1\n        end\n    end\n    reduce(hcat, c2s.(Ref(RotZY(θ, π/2-ϕ)) .* s2c.(θs, ϕs)))\nend\n", "meta": {"hexsha": "4960534c07af0e6fa50dde83dc29a3d75564afef", "size": 2691, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spherical.jl", "max_stars_repo_name": "david-macmahon/FringeExplorer.jl", "max_stars_repo_head_hexsha": "788f0e0067cc4e1c18ab0f0376d158fdfb32e53a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/spherical.jl", "max_issues_repo_name": "david-macmahon/FringeExplorer.jl", "max_issues_repo_head_hexsha": "788f0e0067cc4e1c18ab0f0376d158fdfb32e53a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spherical.jl", "max_forks_repo_name": "david-macmahon/FringeExplorer.jl", "max_forks_repo_head_hexsha": "788f0e0067cc4e1c18ab0f0376d158fdfb32e53a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9310344828, "max_line_length": 79, "alphanum_fraction": 0.6413972501, "num_tokens": 1001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363299661721, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7707715651709529}}
{"text": "using LinearAlgebra\r\nusing Plots\r\n\r\ndatapoints=[2.4 420;\r\n            2.0 350;\r\n            2.1 310;\r\n            1.8 280;\r\n            1.3 75]\r\nA = hcat(ones(size(datapoints,1)),datapoints[:,1])\r\nb = datapoints[:,2]\r\n\r\nx = A\\b\r\n\r\nline = t -> x[1] + x[2]*t\r\n\r\nscatter(datapoints[:,1], datapoints[:,2], legend=:none)\r\nplot!(line, legend=:none)\r\nylabel!(\"weight, in pounds\")\r\nxlabel!(\"length, in meters\")\r\n", "meta": {"hexsha": "f6fb62745631e23abfcd726ee452f037c99b2721", "size": 404, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter1/SimpleLinearModel.jl", "max_stars_repo_name": "julianschnidder/CompUQ4InvProblems", "max_stars_repo_head_hexsha": "f69fe03a99eb5aa1672ce5e2f4c30c4601820cd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1/SimpleLinearModel.jl", "max_issues_repo_name": "julianschnidder/CompUQ4InvProblems", "max_issues_repo_head_hexsha": "f69fe03a99eb5aa1672ce5e2f4c30c4601820cd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1/SimpleLinearModel.jl", "max_forks_repo_name": "julianschnidder/CompUQ4InvProblems", "max_forks_repo_head_hexsha": "f69fe03a99eb5aa1672ce5e2f4c30c4601820cd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2, "max_line_length": 56, "alphanum_fraction": 0.5420792079, "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7707715615630428}}
{"text": "euler(f::Function, T::Number, t0::Int, t1::Int, h::Int) = collect(begin T += h * f(T); T end for t in t0:h:t1)\n\n# Prints a series of arbitrary values in a tabular form, left aligned in cells with a given width\ntabular(width, cells...) = println(join(map(s -> rpad(s, width), cells)))\n\n# prints the table according to the task description for h=5 and 10 sec\nfor h in (5, 10)\n    print(\"Step $h:\\n\\n\")\n    tabular(15, \"Time\", \"Euler\", \"Analytic\")\n    t = 0\n    for T in euler(y -> -0.07 * (y - 20.0), 100.0, 0, 100, h)\n        tabular(15, t, round(T,6), round(20.0 + 80.0 * exp(-0.07t), 6))\n        t += h\n    end\n    println()\nend\n", "meta": {"hexsha": "63ea39ec8960d69f8732ace93ed893d6e461ca37", "size": 630, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/euler-method.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/euler-method.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/euler-method.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0588235294, "max_line_length": 110, "alphanum_fraction": 0.5936507937, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467158, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7707715598945211}}
{"text": "export correlationsum_fixedmass\n\nusing SpecialFunctions, Random\n\n\"\"\"\n    correlationsum_fixedmass(data, max_j; metric = Euclidean(), M = length(data)) → rs, ys\nA fixed mass algorithm for the calculation of the fractal dimension ``\\\\Delta`` according\nto [^Grassberger1988] with `max_j` the maximum number of neighbours that\nshould be considered for the calculation, `M` defines the number of points\nconsidered for the calculation, default is the whole data set.\n\nImplements\n```math\n\\\\Delta \\\\overline{\\\\log r^{(j)}} \\\\sim Ψ(j) - \\\\log N\n```\nwhere `` \\\\Psi(j) = \\\\frac{\\\\text{d} \\\\log Γ(j)}{\\\\text{d} j}\n``, `rs` = ``\\\\overline{\\\\log r^{(j)}}`` and `ys` = ``\\\\Psi(j) - \\\\log N``.\n\n``\\\\Delta`` can be computed by using `linear_region(rs, ys)`.\n\n[^Grassberger1988]: Peter Grassberger (1988) [Finite sample Corrections to Entropy and Dimension Estimates, Physics Letters A 128(6-7)](https://doi.org/10.1016/0375-9601(88)90193-4)\n\"\"\"\nfunction correlationsum_fixedmass(data, max_j; metric = Euclidean(), M = length(data), w = 0)\n    N = length(data)\n    M > N && throw(ArgumentError(\"The number of points used for the calculation `M` should not exceed the number of points provided.\"))\n    # Transform the data into a tree.\n    tree = searchstructure(KDTree, data, metric)\n    # Calculate all nearest neighbours up to max_j.\n    _, distances =\n        bulksearch(\n            tree,\n            N == M ? data.data : data[view(randperm(N), 1:M)],\n            NeighborNumber(max_j),\n            Theiler(w),\n        )\n    # The epsilons define the left side of the equation\n    ys = [digamma(j) - log(N) for j in 1:max_j]\n    # Holds the mean value of the logarithms of the distances.\n    rs = zeros(max_j)\n    for dists in distances\n        for j in 1:max_j\n            rs[j] += log(dists[j])\n        end\n    end\n    return rs ./ M, ys\nend\n", "meta": {"hexsha": "d76dd1f7407468296022fd123715a587844ad5cf", "size": 1830, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dimensions/correlation_fixedmass.jl", "max_stars_repo_name": "onkyo14taro/ChaosTools.jl", "max_stars_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 168, "max_stars_repo_stars_event_min_datetime": "2018-01-07T15:46:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T13:38:24.000Z", "max_issues_repo_path": "src/dimensions/correlation_fixedmass.jl", "max_issues_repo_name": "onkyo14taro/ChaosTools.jl", "max_issues_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 176, "max_issues_repo_issues_event_min_datetime": "2017-12-19T20:26:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:08:23.000Z", "max_forks_repo_path": "src/dimensions/correlation_fixedmass.jl", "max_forks_repo_name": "onkyo14taro/ChaosTools.jl", "max_forks_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2018-01-27T07:59:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T10:08:36.000Z", "avg_line_length": 38.9361702128, "max_line_length": 181, "alphanum_fraction": 0.6480874317, "num_tokens": 512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.7707715596236547}}
{"text": "\nusing OrdinaryDiffEq\nusing DiffEqCallbacks\nusing Surrogates\nusing DataFrames\nusing RCall\nusing Random\nusing Plots;\n\n\nR\"library(hmer)\";\n\n\nRandom.seed!(123)\nR\"set.seed(123)\";\n\n\nfunction sir_ode!(du,u,p,t)\n    (S,I,R) = u\n    (β,γ) = p\n    @inbounds begin\n        du[1] = -β*S*I\n        du[2] = β*S*I - γ*I\n        du[3] = γ*I\n    end\n    nothing\nend;\n\n\ntmax = 10000.0\ntspan = (0.0,tmax)\nδt = 1.0;\n\n\nn_train = 50 # Number of training samples\nn_test = 1000; # Number of test samples\n\n\n# Parameters are β, γ\nlb = [0.00005, 0.1]\nub = [0.001, 1.0];\n\n\nN = 1000.0\nu0 = [990.0,10.0,0.0]\np = [0.0005,0.25]\nprob_ode = ODEProblem(sir_ode!,u0,tspan,p);\n\n\nsampler = LatinHypercubeSample();\n\n\nθ = Surrogates.sample(n_train,lb,ub,sampler);\n\n\nlogit = (x) -> log(x/(1-x))\ninvlogit = (x) -> exp(x)/(exp(x)+1.0)\ncb_ss = TerminateSteadyState()\nlogit_final_size = function(z)\n  prob = remake(prob_ode;p=z)\n  sol = solve(prob, ROS34PW3(),callback=cb_ss)\n  fsp = sol[end][3]/N\n  logit(fsp)\nend;\n\n\nlfs = logit_final_size.(θ);\n\n\ntraining_df = DataFrame(θ)\nrename!(training_df,[\"b\",\"g\"])\ntraining_df[!,:lfs] = lfs;\n\n\ninput_ranges = Dict(:b => [lb[1], ub[1]], :g => [lb[2], ub[2]])\noutput_names = [\"lfs\"];\n\n\n@rput training_df\n@rput output_names\n@rput input_ranges;\n\n\nR\"emulator <- emulator_from_data(training_df, output_names, input_ranges)\"\n\n\nθ_test = sample(n_test,lb,ub,sampler)\nlfs_test = logit_final_size.(θ_test);\n\n\ntest_df = DataFrame(θ_test)\nrename!(test_df,[\"b\",\"g\"])\ntest_df[!,:lfs] = lfs_test\n@rput test_df; # copy to R\n\n\nR\"lfs_test_pred <- list()\"\nR\"lfs_test_pred$mean <- emulator$lfs$get_exp(test_df)\"\nR\"lfs_test_pred$unc <- emulator$lfs$get_cov(test_df)\"\n@rget lfs_test_pred;\n\n\nscatter(invlogit.(lfs_test),\n        invlogit.(lfs_test_pred[:mean]),\n        xlabel = \"Model final size\",\n        ylabel = \"Surrogate final size\",\n        legend = false,\n        title = \"Test set\")\n\n\nβ_grid = collect(lb[1]:0.00001:ub[1])\nθ_eval = [(βᵢ,0.25) for βᵢ in β_grid]\neval_df = DataFrame(θ_eval)\nrename!(eval_df,[\"b\",\"g\"])\n@rput eval_df\nR\"lfs_eval <- list()\"\nR\"lfs_eval$mean <- emulator$lfs$get_exp(eval_df)\"\nR\"lfs_eval$unc <- emulator$lfs$get_cov(eval_df)\"\n@rget lfs_eval\nfs_eval = invlogit.(lfs_eval[:mean])\nfs_eval_uc = invlogit.(lfs_eval[:mean] .+ 1.96 .* sqrt.(lfs_eval[:unc]))\nfs_eval_lc = invlogit.(lfs_eval[:mean] .- 1.96 .* sqrt.(lfs_eval[:unc]))\nplot(β_grid,\n     fs_eval,\n     xlabel = \"Infectivity parameter, β\",\n     ylabel = \"Final size\",\n     label = \"Model\")\nplot!(β_grid,\n      invlogit.(logit_final_size.(θ_eval)),\n      ribbon = (fs_eval .- fs_eval_lc, fs_eval_uc - fs_eval),\n      label = \"Surrogate\",\n      legend = :right)\n\n\nγ_grid = collect(lb[2]:0.001:ub[2])\nθ_eval = [(0.001,γᵢ) for γᵢ in γ_grid]\neval_df = DataFrame(θ_eval)\nrename!(eval_df,[\"b\",\"g\"])\n@rput eval_df\nR\"lfs_eval <- list()\"\nR\"lfs_eval$mean <- emulator$lfs$get_exp(eval_df)\"\nR\"lfs_eval$unc <- emulator$lfs$get_cov(eval_df)\"\n@rget lfs_eval\nfs_eval = invlogit.(lfs_eval[:mean])\nfs_eval_uc = invlogit.(lfs_eval[:mean] .+ 1.96 .* sqrt.(lfs_eval[:unc]))\nfs_eval_lc = invlogit.(lfs_eval[:mean] .- 1.96 .* sqrt.(lfs_eval[:unc]))\nplot(γ_grid,\n     fs_eval,\n     xlabel = \"Recovery rate, γ\",\n     ylabel = \"Final size\",\n     label = \"Model\")\nplot!(γ_grid,\n      invlogit.(logit_final_size.(θ_eval)),\n      ribbon = (fs_eval .- fs_eval_lc, fs_eval_uc - fs_eval),\n      label = \"Surrogate\")\n\n\nobs = logit_final_size(p)\nobs_lc = logit(0.99*invlogit(obs))\nobs_uc = logit(1.01*invlogit(obs))\ntarget = Dict(:lfs => [obs_lc, obs_uc])\n@rput target\n\n\nR\"new_points <- generate_new_runs(emulator, $n_test, target, method = 'lhs', cutoff = 3)\"\n@rget new_points;\n\n\nl = @layout [a b]\npl1 = histogram(new_points[!,:b],legend=false,xlim=(lb[1],ub[1]),bins=lb[1]:0.00005:ub[1],title=\"NROY values for β\")\nvline!(pl1,[p[1]])\npl2 = histogram(new_points[!,:g],legend=false,xlim=(lb[2],ub[2]),bins=lb[2]:0.05:ub[2],title=\"NROY values for γ\")\nvline!(pl2,[p[2]])\nplot(pl1, pl2, layout = l)\n\n", "meta": {"hexsha": "ab2302fbd65121a8ae3591f0e18cc914097772ad", "size": 3920, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_hmer/ode_hmer.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/ode_hmer/ode_hmer.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/ode_hmer/ode_hmer.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2727272727, "max_line_length": 116, "alphanum_fraction": 0.6515306122, "num_tokens": 1403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7707715538054902}}
{"text": "\"\"\"\n    GaussLik <: Likelihood\n\nGaussian, a.k.a. Normal, likelihood\n```math\np(y | f, σ) = 1 / √(2πσ²) \\\\exp(-(x - f)²/(2σ²)),\n```\nwhere standard deviation ``σ`` is a non-fixed hyperparameter and ``f`` is the latent\nGaussian process.\n\"\"\"\nmutable struct GaussLik <: Likelihood\n    \"Standard deviation\"\n    σ::Float64\n    \"Priors for likelihood parameters\"\n    priors::Array\n\n    \"\"\"\n        GaussLik(lσ::Float64)\n\n    Create `GaussLik` with standard deviation `exp(lσ)`.\n    \"\"\"\n    GaussLik(lσ::Float64) = new(exp(lσ), [])\nend\n\n# log of probability density\nfunction log_dens(gauss::GaussLik, f::VecF64, y::VecF64)\n    return (-0.5 * log(2 * pi) - log(gauss.σ)) .- 0.5 * ((y - f) / gauss.σ).^2\nend\n\n# derivative of log pdf wrt latent function\nfunction dlog_dens_df(gauss::GaussLik, f::VecF64, y::VecF64)\n    return [(yi-fi)/gauss.σ^2 for (fi,yi) in zip(f,y)]\nend\n\n# derivative of log pdf wrt to parameters\nfunction dlog_dens_dθ(gauss::GaussLik, f::VecF64, y::VecF64)\n    return gauss.σ*[-1/gauss.σ + 1/gauss.σ^3*(yi-fi).^2 for (fi,yi) in zip(f,y)]\nend\n\n#mean and variance under likelihood\nmean_lik(gauss::GaussLik, f::VecF64) = f\nvar_lik(gauss::GaussLik, f::VecF64) = ones(length(f))*gauss.σ^2\n\n\nfunction set_params!(gauss::GaussLik, hyp::VecF64)\n    length(hyp) == 1 || throw(ArgumentError(\"Gaussian/Normal likelihood has only one free parameter\"))\n    gauss.σ = exp(hyp[])\nend\n\nget_params(gauss::GaussLik) = Float64[log(gauss.σ)]\nnum_params(gauss::GaussLik) = 1\n\n\n#Computes the predictive mean and variance\nfunction predict_obs(gauss::GaussLik, fmean::VecF64, fvar::VecF64)\n    return fmean, fvar + gauss.σ^2\nend\n", "meta": {"hexsha": "0023a819048bc0558c1352d8306d87775ca794b1", "size": 1613, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/likelihoods/gaussian.jl", "max_stars_repo_name": "jbrea/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/likelihoods/gaussian.jl", "max_issues_repo_name": "jbrea/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/likelihoods/gaussian.jl", "max_forks_repo_name": "jbrea/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8103448276, "max_line_length": 102, "alphanum_fraction": 0.6726596404, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7707715490707906}}
{"text": "export\n    Line,\n    get_polar_angle,\n    get_distance,\n    get_side\n\nimmutable Line\n    C::VecE2\n    θ::Float64\nend\nLine(A::VecE2, B::VecE2) = Line((A+B)/2, atan2(B - A))\n\nBase.:-(line::Line, V::VecE2) = Line(line.C - V, line.θ)\nBase.:+(line::Line, V::VecE2) = Line(line.C + V, line.θ)\n\nget_polar_angle(line::Line) = line.θ\nrot(line::Line, Δθ::Float64) = Line(line.C, line.θ+Δθ)\nBase.rot180(line::Line) = rot(line, 1π)\nBase.rotl90(line::Line) = rot(line,  π/2)\nBase.rotr90(line::Line) = rot(line, -π/2)\n\n\"\"\"\nThe distance between the line and the point P\n\"\"\"\nfunction get_distance(line::Line, P::VecE2)\n\n    ab = polar(1.0, line.θ)\n    pb = P - line.C\n\n    denom = abs2(ab)\n    if denom ≈ 0.0\n        return 0.0\n    end\n\n    r = dot(ab, pb)/denom\n    return abs(P - (line.C + r*ab))\nend\n\n\n\"\"\"\nWhat side of the line you are on\nIs -1 if on the left, 1 if on the right, and 0 if on the line\n\"\"\"\nfunction get_side(line::Line, p::VecE2, ε::Float64=1e-10)\n    ab = polar(1.0, line.θ)\n    signed_dist = ab.x*(p.y-line.C.y) - ab.y*(p.x-line.C.x)\n    if abs(signed_dist) < ε\n        return 0\n    else\n        return sign(signed_dist)\n    end\nend", "meta": {"hexsha": "e7b5e6d4f3b310cf0b07911e3095b5ce46fd5fe5", "size": 1136, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geom/lines.jl", "max_stars_repo_name": "wxuejing/Vec.jl", "max_stars_repo_head_hexsha": "38294563ad20d5e5f864fff19886d0d74a504c87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/geom/lines.jl", "max_issues_repo_name": "wxuejing/Vec.jl", "max_issues_repo_head_hexsha": "38294563ad20d5e5f864fff19886d0d74a504c87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geom/lines.jl", "max_forks_repo_name": "wxuejing/Vec.jl", "max_forks_repo_head_hexsha": "38294563ad20d5e5f864fff19886d0d74a504c87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8461538462, "max_line_length": 61, "alphanum_fraction": 0.6029929577, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545274901876, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7707238341039774}}
{"text": "\"\"\"\n    frst(signal, α, p)\n\nComputing the α order fractional sine transform of the input **signal**.\n\n# Example\n\n```julia-repl\njulia> frst([1,2,3], 0.5, 2)\n3-element Vector{ComplexF64}:\n1.707106781186548 + 1.207106781186547im\n1.9999999999999998 - 1.7071067811865481im\n-1.1213203435596437 - 1.2071067811865468im\n```\n\n### References\n\n```tex\n@article{article,\nauthor = {Pei, Soo-Chang and Yeh, Min-Hung},\nyear = {2001},\nmonth = {07},\npages = {1198 - 1207},\ntitle = {The discrete fractional cosine and sine transforms},\nvolume = {49},\njournal = {Signal Processing, IEEE Transactions on},\ndoi = {10.1109/78.923302}\n}\n```\n\"\"\"\nfunction frst(signal, α, p)\n    N = length(signal)\n    @views signal = signal[:]\n    p = min(max(2, p), N-1)\n    E = dFRST(N,p)\n    result = E *(exp.(-im*pi*α*collect(0:N-1)) .*(E' *signal))\n    return result\nend\n\nfunction dFRST(N, p)\n    N1 = 2*N+2\n    d2 = [1, -2, 1]\n\n    d_p = 1\n    s = 0\n    st = zeros(1, N1)\n\n    for k = 1:floor(Int, p/2)\n        if isa(d_p, Number) \n            d_p = @. d2*d_p\n        else\n            d_p = conv(d2, d_p)\n        end\n        st[vcat(collect(N1-k+1:N1), collect(1:k+1))] = d_p\n        st[1]=0\n        temp=vcat(union(1, collect(1:k-1)), union(2,collect(1:k-1)))\n        temp = temp[:] ./collect(1:2*k)\n        s=s.+(-1)^(k-1)*prod(temp)*2*st\n    end\n\n    H = Toeplitz(s[:], s[:]) +diagm(real.(fft(s[:])))\n\n    V = hcat(zeros(N), reverse(zeros(N, N)+I, dims=1), zeros(N), -(zeros(N, N)+I)) ./sqrt(2)\n\n    Od = V*H*V'\n\n    _, vo = eigen(Od)\n\n    return reverse(reverse(vo, dims=2), dims=1)\nend", "meta": {"hexsha": "aa39851fd0e17b8aa6fde23e73ff1995cbd065b9", "size": 1553, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/frst.jl", "max_stars_repo_name": "SciFracX/FractionalTransforms.jl", "max_stars_repo_head_hexsha": "f343419db8e79a3f08ae1d95faae5495f877317b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-11-07T22:00:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T00:49:40.000Z", "max_issues_repo_path": "src/frst.jl", "max_issues_repo_name": "SciFracX/FractionalTransforms.jl", "max_issues_repo_head_hexsha": "f343419db8e79a3f08ae1d95faae5495f877317b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-16T15:53:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T06:08:16.000Z", "max_forks_repo_path": "src/frst.jl", "max_forks_repo_name": "SciFracX/FractionalTransforms.jl", "max_forks_repo_head_hexsha": "f343419db8e79a3f08ae1d95faae5495f877317b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-08T12:06:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T12:06:40.000Z", "avg_line_length": 22.1857142857, "max_line_length": 92, "alphanum_fraction": 0.5666452028, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502203, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7707238302707706}}
{"text": "using EngEconomics, Plots, ColorSchemes, Colors\nplotly()\n\n\nuwEngColorScheme = ColorScheme([parse(Colorant, \"#D0B4E7\"), parse(Colorant, \"#FFFFFF\"), parse(Colorant, \"#57058B\"), parse(Colorant, \"#8100B4\")])\n\nF = 50\nA_base = 7\ni_base = 0.10\nsensitivityVector = [.90, 0.95, 1.0, 1.05, 1.10]\n\nbaseN = log(F / A_base * i_base + 1) / log(1 + i_base)\n\nN_annualSavings = log.(F ./ (A_base .* sensitivityVector) .* i_base .+ 1) ./ log(1 + i_base)\nN_interestRate  = log.(F / A_base .* (sensitivityVector * i_base) .+ 1) ./ log.(1 .+ (i_base .* sensitivityVector))\n\nplot(sensitivityVector, N_annualSavings, label=\"Annual Savings Sensitivity\",\n\txlabel=\"Sensitivity (+/- 5%, 10%)\", ylabel=\"Number of Years\",\n\tpalette=cgrad(uwEngColorScheme))\nplot!(sensitivityVector, N_interestRate, label=\"Interest Rate Sensitivity\")\n", "meta": {"hexsha": "2ab6763d917d95f6e65db84ee3fbca0319f0c7b2", "size": 803, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps8/p1.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/ps8/p1.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/ps8/p1.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2380952381, "max_line_length": 144, "alphanum_fraction": 0.696139477, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.770723823590738}}
{"text": "# span.jl\n\n@doc \"\"\"\n### findSpan\n\nDetermines the knot span index, i\n\n**Inputs**\n\n*  `u` : coordinate value (u,v,w is the coordinate space in 3D)\n*  `U` : Knot vector\n*  `k` : B-spline order\n*  `nctl` : Number of control points\n\n**Outputs**\n\n*  `span` : Knot span index\n\nSOURCE: The NURBS book 2nd Edition, Algorithm A2.1\n\n\"\"\"->\n\nfunction findSpan(u::Tffd, U::AbstractArray{Tffd,1}, k::Int, nctl::Int) where Tffd\n\n  if u >= U[nctl+1]\n    return nctl  # Special case when u = last term of knot vector\n  elseif u < U[k]\n    return k  # When u lies at the starting point of the curve\n  end\n\n  low = k-1\n  high = nctl+1\n  span = div(low + high, 2)\n  # Do a binary search\n  while u < U[span] || u >= U[span+1]\n    if u < U[span]\n      high = span\n    else\n      low = span\n    end  # End if\n    span = div(low+high, 2)\n  end  # End while\n\n  return span\nend  # End function findSpan\n", "meta": {"hexsha": "288b89680fe80aa071be39c3ad49ba5617c2fda4", "size": 876, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/span.jl", "max_stars_repo_name": "OptimalDesignLab/FFD.jl", "max_stars_repo_head_hexsha": "13a6139cc36d9609af100cda8747902c0e0730a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-05-10T14:41:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-19T01:25:03.000Z", "max_issues_repo_path": "src/span.jl", "max_issues_repo_name": "OptimalDesignLab/FFD.jl", "max_issues_repo_head_hexsha": "13a6139cc36d9609af100cda8747902c0e0730a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/span.jl", "max_forks_repo_name": "OptimalDesignLab/FFD.jl", "max_forks_repo_head_hexsha": "13a6139cc36d9609af100cda8747902c0e0730a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-12T05:33:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T10:33:51.000Z", "avg_line_length": 19.0434782609, "max_line_length": 82, "alphanum_fraction": 0.6073059361, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7707195555013922}}
{"text": "## Linear algebra API for adjacency matrix\nusing LinearAlgebra\n\nfunction adjacency_matrix(adj::AbstractMatrix, T::DataType=eltype(adj))\n    m, n = size(adj)\n    (m == n) || throw(DimensionMismatch(\"adjacency matrix is not a square matrix: ($m, $n)\"))\n    T.(adj)\nend\n\n\"\"\"\n    degrees(g[, T; dir=:out])\n\nDegree of each vertex. Return a vector which contains the degree of each vertex in graph `g`.\n\n# Arguments\n- `g`: should be a adjacency matrix, `SimpleGraph`, `SimpleDiGraph` (from LightGraphs) or `SimpleWeightedGraph`, `SimpleWeightedDiGraph` (from SimpleWeightedGraphs).\n- `T`: result element type of degree vector; default is the element type of `g` (optional).\n- `dir`: direction of degree; should be `:in`, `:out`, or `:both` (optional).\n\n# Examples\n```jldoctest\njulia> using GeometricFlux\n\njulia> m = [0 1 1; 1 0 0; 1 0 0];\n\njulia> GeometricFlux.degrees(m)\n3-element Array{Int64,1}:\n 2\n 1\n 1\n\n```\n\"\"\"\nfunction degrees(adj::AbstractMatrix, T::DataType=eltype(adj); dir::Symbol=:out)\n    if issymmetric(adj)\n        d = vec(sum(adj, dims=1))\n    else\n        if dir == :out\n            d = vec(sum(adj, dims=1))\n        elseif dir == :in\n            d = vec(sum(adj, dims=2))\n        elseif dir == :both\n            d = vec(sum(adj, dims=1)) + vec(sum(adj, dims=2))\n        else\n            throw(DomainError(dir, \"invalid argument, only accept :in, :out and :both\"))\n        end\n    end\n    d\nend\n\n\"\"\"\n    degree_matrix(g[, T; dir=:out])\n\nDegree matrix of graph `g`. Return a matrix which contains degrees of each vertex in its diagonal.\nThe values other than diagonal are zeros.\n\n# Arguments\n- `g`: should be a adjacency matrix, `FeaturedGraph`, `SimpleGraph`, `SimpleDiGraph` (from LightGraphs) or `SimpleWeightedGraph`, `SimpleWeightedDiGraph` (from SimpleWeightedGraphs).\n- `T`: result element type of degree vector; default is the element type of `g` (optional).\n- `dir`: direction of degree; should be `:in`, `:out`, or `:both` (optional).\n\n# Examples\n```jldoctest\njulia> using GeometricFlux\n\njulia> m = [0 1 1; 1 0 0; 1 0 0];\n\njulia> GeometricFlux.degree_matrix(m)\n3×3 SparseArrays.SparseMatrixCSC{Int64,Int64} with 3 stored entries:\n  [1, 1]  =  2\n  [2, 2]  =  1\n  [3, 3]  =  1\n```\n\"\"\"\nfunction degree_matrix(adj::AbstractMatrix, T::DataType=eltype(adj); dir::Symbol=:out)\n    d = degrees(adj, T, dir=dir)\n    return SparseMatrixCSC(T.(diagm(0=>d)))\nend\n\n\"\"\"\n    inv_sqrt_degree_matrix(g[, T; dir=:out])\n\nInverse squared degree matrix of graph `g`. Return a matrix which contains inverse squared degrees of each vertex in its diagonal.\nThe values other than diagonal are zeros.\n\n# Arguments\n- `g`: should be a adjacency matrix, `FeaturedGraph`, `SimpleGraph`, `SimpleDiGraph` (from LightGraphs) or `SimpleWeightedGraph`, `SimpleWeightedDiGraph` (from SimpleWeightedGraphs).\n- `T`: result element type of degree vector; default is the element type of `g` (optional).\n- `dir`: direction of degree; should be `:in`, `:out`, or `:both` (optional).\n\"\"\"\nfunction inv_sqrt_degree_matrix(adj::AbstractMatrix, T::DataType=eltype(adj); dir::Symbol=:out)\n    d  = inv.(sqrt.(degrees(adj, T, dir=dir)))\n    return Diagonal(d)\nend\n\n\"\"\"\n    laplacian_matrix(g[, T; dir=:out])\n\nLaplacian matrix of graph `g`.\n\n# Arguments\n- `g`: should be a adjacency matrix, `FeaturedGraph`, `SimpleGraph`, `SimpleDiGraph` (from LightGraphs) or `SimpleWeightedGraph`, `SimpleWeightedDiGraph` (from SimpleWeightedGraphs).\n- `T`: result element type of degree vector; default is the element type of `g` (optional).\n- `dir`: direction of degree; should be `:in`, `:out`, or `:both` (optional).\n\"\"\"\nfunction laplacian_matrix(adj::AbstractMatrix, T::DataType=eltype(adj); dir::Symbol=:out)\n    degree_matrix(adj, T, dir=dir) - SparseMatrixCSC(T.(adj))\nend\n\n\"\"\"\n    normalized_laplacian(g[, T; selfloop=false])\n\nNormalized Laplacian matrix of graph `g`.\n\n# Arguments\n- `g`: should be a adjacency matrix, `FeaturedGraph`, `SimpleGraph`, `SimpleDiGraph` (from LightGraphs) or `SimpleWeightedGraph`, `SimpleWeightedDiGraph` (from SimpleWeightedGraphs).\n- `T`: result element type of degree vector; default is the element type of `g` (optional).\n- `selfloop`: adding self loop while calculating the matrix (optional).\n\"\"\"\nfunction normalized_laplacian(adj::AbstractMatrix, T::DataType=eltype(adj); selfloop::Bool=false)\n    selfloop && (adj += I)\n    inv_sqrtD = inv_sqrt_degree_matrix(adj, T, dir=:both)\n    T.(I - inv_sqrtD * adj * inv_sqrtD)\nend\n\n@doc raw\"\"\"\n    scaled_laplacian(adj::AbstractMatrix[, T::DataType]) \n\nScaled Laplacien matrix of graph `g`, \ndefined as ``\\hat{L} = \\frac{2}{\\lambda_{max}} L - I`` where ``L`` is the normalized Laplacian matrix.\n\n# Arguments\n- `g`: should be a adjacency matrix, `FeaturedGraph`, `SimpleGraph`, `SimpleDiGraph` (from LightGraphs) or `SimpleWeightedGraph`, `SimpleWeightedDiGraph` (from SimpleWeightedGraphs).\n- `T`: result element type of degree vector; default is the element type of `g` (optional).\n\"\"\"\nfunction scaled_laplacian(adj::AbstractMatrix, T::DataType=eltype(adj))\n    T(2. / eigmax(adj)) * normalized_laplacian(adj, T) - I\nend\n\nfunction neighbors(adj::AbstractMatrix, T::DataType=eltype(adj))\n    n = size(adj,1)\n    @assert n == size(adj,2) \"adjacency matrix is not a square matrix.\"\n    A = (adj .!= zero(T))\n    if !issymmetric(adj)\n        A = A .| A'\n    end\n    indecies = collect(1:n)\n    ne = Vector{Int}[indecies[view(A, :, i)] for i = 1:n]\n    return ne\nend\n", "meta": {"hexsha": "e0e3cb4ba4d7509efddb9e378adb20cd6c0e0ade", "size": 5406, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operations/linalg.jl", "max_stars_repo_name": "ilancoulon/GeometricFlux.jl", "max_stars_repo_head_hexsha": "27334437a35fcf5ecd633eadf4c472add6c8d53b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/operations/linalg.jl", "max_issues_repo_name": "ilancoulon/GeometricFlux.jl", "max_issues_repo_head_hexsha": "27334437a35fcf5ecd633eadf4c472add6c8d53b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/operations/linalg.jl", "max_forks_repo_name": "ilancoulon/GeometricFlux.jl", "max_forks_repo_head_hexsha": "27334437a35fcf5ecd633eadf4c472add6c8d53b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8013245033, "max_line_length": 182, "alphanum_fraction": 0.684054754, "num_tokens": 1590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.8558511432905479, "lm_q1q2_score": 0.7707194561552075}}
{"text": "# This example solution is partially derived from the Julia base implementation of rational numbers (MIT license)\n# https://github.com/JuliaLang/julia/blob/52bafeb981bac548afd2264edb518d8d86944dca/base/rational.jl\n# https://github.com/JuliaLang/julia/blob/52bafeb981bac548afd2264edb518d8d86944dca/LICENSE.md\n\nimport Base: +, *, ^, -, /, <, <=, inv, show, promote_rule\n\nstruct RationalNumber{T<:Integer} <: Real\n    num::T\n    den::T\n\n    # reduce to lowest terms\n    function RationalNumber{T}(num::Integer, den::Integer) where T<:Integer\n        num == den == zero(T) && throw(ArgumentError(\"zero($T)//zero($T) is not a valid rational number\"))\n        num2, den2 = sign(den) < 0 ? Base.divgcd(-num, -den) : Base.divgcd(num, den)\n        new(num2, den2)\n    end\nend\n\nRationalNumber(num::T, den::T) where {T<:Integer} = RationalNumber{T}(num, den)\n\nnumerator(x::RationalNumber) = x.num\ndenominator(x::RationalNumber) = x.den\n\nRationalNumber{T}(x::Integer) where {T<:Integer} = RationalNumber{T}(convert(T, x), convert(T, 1))\n\npromote_rule(::Type{RationalNumber{T}}, ::Type{S}) where {T<:Integer,S<:Integer} = RationalNumber{promote_type(T,S)}\n\nshow(io::IO, x::RationalNumber) = (show(io, numerator(x)); print(io, \"//\"); show(io, denominator(x)))\n\n# Helper method\nnumden(x::RationalNumber) = numerator(x), denominator(x)\n\n# Arithmetics\nfunction +(x::RationalNumber, y::RationalNumber)\n    a, b = numden(x)\n    c, d = numden(y)\n\n    RationalNumber(a * d + b * c, b * d)\nend\n\n-(x::RationalNumber, y::RationalNumber) = x + (-1) * y\n-(x::RationalNumber) = -1 * x\n\nfunction *(x::RationalNumber, y::RationalNumber)\n    a, b = numden(x)\n    c, d = numden(y)\n\n    RationalNumber(a * c, b * d)\nend\n\ninv(x::RationalNumber) = RationalNumber(denominator(x), numerator(x))\n/(x::RationalNumber, y::RationalNumber) = x * inv(y)\n\n^(x::Real, y::RationalNumber) = x^(numerator(y) / denominator(y))\n\n# Ordering\n<(x::RationalNumber, y::RationalNumber) = x.den == y.den ? x.num < y.num : x.num * y.den < y.num * x.den\n<=(x::RationalNumber, y::RationalNumber) = x.den == y.den ? x.num <= y.num : x.num * y.den <= y.num * x.den\n", "meta": {"hexsha": "10f5b520fe69f11602c0cab0a657a9b751eb344d", "size": 2104, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/rational-numbers/example.jl", "max_stars_repo_name": "tomerarnon/julia-1", "max_stars_repo_head_hexsha": "6313e702d82f4fee10efdf29e943df50857cd7b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 42, "max_stars_repo_stars_event_min_datetime": "2017-06-27T01:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:34:10.000Z", "max_issues_repo_path": "exercises/rational-numbers/example.jl", "max_issues_repo_name": "tomerarnon/julia-1", "max_issues_repo_head_hexsha": "6313e702d82f4fee10efdf29e943df50857cd7b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 269, "max_issues_repo_issues_event_min_datetime": "2017-06-19T13:56:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T22:15:18.000Z", "max_forks_repo_path": "exercises/rational-numbers/example.jl", "max_forks_repo_name": "tomerarnon/julia-1", "max_forks_repo_head_hexsha": "6313e702d82f4fee10efdf29e943df50857cd7b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 69, "max_forks_repo_forks_event_min_datetime": "2017-06-20T18:47:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T22:15:52.000Z", "avg_line_length": 35.6610169492, "max_line_length": 116, "alphanum_fraction": 0.6663498099, "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7707194499302055}}
{"text": "# indicator of the Cartesian product of real binary sets\n\nexport IndBinary\n\n\"\"\"\n**Indicator of the product of binary sets**\n\n    IndBinary(low, up)\n\nReturns the indicator function of the set\n```math\nS = \\\\{ x : x_i = low_i\\\\ \\\\text{or}\\\\ x_i = up_i \\\\},\n```\nParameters `low` and `up` can be either scalars or arrays of the same dimension as the space.\n\"\"\"\nstruct IndBinary{T, S} <: ProximableFunction\n    low::T\n    high::S\nend\n\nis_set(f::IndBinary) = true\n\nIndBinary() = IndBinary(0.0, 1.0)\n\nIndBinary_low(f::IndBinary{<: Number, S}, i) where S = f.low\nIndBinary_low(f::IndBinary{T, S}, i) where {T, S} = f.low[i]\nIndBinary_high(f::IndBinary{T, <: Number}, i) where T = f.high\nIndBinary_high(f::IndBinary{T, S}, i) where {T, S} = f.high[i]\n\nfunction (f::IndBinary)(x::AbstractArray{C}) where {R <: Real, C <: RealOrComplex{R}}\n    for k in eachindex(x)\n        if x[k] != IndBinary_low(f, k) && x[k] != IndBinary_high(f, k)\n            return R(Inf)\n        end\n    end\n    return R(0)\nend\n\nfunction prox!(y::AbstractArray{T}, f::IndBinary, x::AbstractArray{T}, gamma::R=R(1)) where {R <: Real, T <: Union{R, Complex{R}}}\n    for k in eachindex(x)\n        low = IndBinary_low(f, k)\n        high = IndBinary_high(f, k)\n        if abs(x[k] - low) < abs(x[k] - high)\n            y[k] = low\n        else\n            y[k] = high\n        end\n    end\n    return R(0)\nend\n\nfun_name(f::IndBinary) = \"indicator of binary array\"\nfun_dom(f::IndBinary) = \"AbstractArray{Real}\"\n\nfunction prox_naive(f::IndBinary, x::AbstractArray{T}, gamma::R=R(1)) where {R <: Real, T <: Union{R, Complex{R}}}\n    distlow = abs.(x .- f.low)\n    disthigh = abs.(x .- f.high)\n    indlow = distlow .< disthigh\n    indhigh = distlow .>= disthigh\n    y = f.low.*indlow + f.high.*indhigh\n    return y, R(0)\nend\n", "meta": {"hexsha": "a1299b3d51ffa4a2d9ee3acf9065f31780be298c", "size": 1776, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indBinary.jl", "max_stars_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_stars_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2016-10-29T12:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:11:52.000Z", "max_issues_repo_path": "src/functions/indBinary.jl", "max_issues_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_issues_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2016-10-26T16:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T20:38:48.000Z", "max_forks_repo_path": "src/functions/indBinary.jl", "max_forks_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_forks_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T10:40:24.000Z", "avg_line_length": 28.1904761905, "max_line_length": 130, "alphanum_fraction": 0.6086711712, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7707194470161913}}
{"text": "import Distributions: Normal, pdf, cdf\n\n###############################\n# Type Definition/Constructors\n###############################\nmutable struct Grid\n    points::Vector{Float64}\n    weights::Vector{Float64}\n    scale::Float64\n    Grid(points, weights, scale) = sum(weights) ≈ scale ? new(points, weights, scale) : error(\"scaled weights do not sum up properly\")\nend\n\n# Constructor utilizing a custom weight calculation function\nfunction Grid(quadrature::Function,\n              lower_bound::T, upper_bound::T,\n              n_points::Int; scale::Float64 = 1.) where {T<:Real}\n    grid, weights = quadrature(lower_bound, upper_bound, n_points)\n    Grid(reshape(grid, size(grid)[1]), weights, scale)\nend\n\n####################\n# Quadrature rules\n####################\n# Enforce that quadrature rules with additional keyword arguments get mapped to\n# A pre-populated version of that rule that only accepts 3 arguments:\n# Lower bound, upper bound, and number of points\nfunction uniform_quadrature(lower_bound::T, upper_bound::T, n_points::Int;\n                            scale::T = 1) where {T<:Real}\n    grid = collect(range(lower_bound, stop = upper_bound, length = n_points))\n    weights = fill(scale/n_points, n_points)\n    return grid, weights\nend\n\nfunction uniform_quadrature(scale::T = 1) where {T<:Real}\n    return (lb, ub, n) -> uniform_quadrature(lb, ub, n, scale = scale)\nend\n\n# NOTE: Should modify chebpts function to return cleaner types...\n# Kind indicates the \"kind\" of the chebyshev polynomial grid\n# The terminology is generally, \"Chebyshev polynomials of the Nth kind\"\nfunction curtis_clenshaw_quadrature(lower_bound::T, upper_bound::T,\n                                    n_points::Int; kind::Int = 2) where {T<:Real}\n    grid, weights = chebpts(n_points, lower_bound, upper_bound, kind)\n    return grid', dropdims(weights', dims=2)\nend\n\nfunction curtis_clenshaw_quadrature(kind::Int = 2)\n    return (lb, ub, n) -> curtis_clenshaw_quadrature(lb, ub, n, kind = kind)\nend\n\n# Tauchen86 developed a method for \"finding a discrete-valued Markov chain\n# whose sample paths approximate well those of a vector autoregression\"\n# Hence the method below is the Tauchen86 method applied to a general AR(1).\nfunction tauchen86(μ::AbstractFloat,ρ::AbstractFloat,σ::AbstractFloat,n::Int64,λ::AbstractFloat)\n    #output is xgrid, xprob\n    # x_t+1 = μ + ρ x_t + σ e_{t+1}, e_t+1 ∼ N(0,1)\n    xhi = μ/(1-ρ) + λ*sqrt(σ^2/(1-ρ)^2)\n    xlo = μ/(1-ρ) - λ*sqrt(σ^2/(1-ρ)^2)\n    xgrid = zeros(n);\n    xscale =(xhi-xlo)/(n-1)\n\n    for i=1:n\n        xgrid[i] = xlo + xscale*(i-1)\n    end\n    m=zeros(n-1);\n    for i=1:n-1\n        m[i] = (xgrid[i]+xgrid[i+1])/2\n    end\n    xprob = zeros(n,n) # xprob[i,j] = Pr(x_t+1=xgrid[j]|x_t=xgrid[i])\n    for i=1:n # this is the state today\n        normie = Normal(μ+ρ*xgrid[i],σ)\n        normpdf(x) = pdf.(normie,x)\n        normcdf(x) = cdf.(normie,x)\n        for j=2:n-1\n            xprob[i,j] = normcdf(m[j]) - normcdf(m[j-1])\n        end\n        xprob[i,1] = normcdf(m[1])\n        xprob[i,n] = 1 - normcdf(m[n-1])\n    end\n    xprob = xprob./sum(xprob, dims = 2) # make sure the rows sum to 1\n    return ( xgrid,xprob, xscale )\nend\n\n# However, Tauchen86 can also be applied to \"degenerate\" AR(1)s where ρ = 0.\n# i.e. i.i.d noise with mean μ, std. σ, but the way the returned\n# Markov transition matrix, xprob, is used in the code, assumes it to be\n# 1-dimensional, since the second-dimension of the Markov transition matrix is trivial\n# (since the process is i.i.d).\nfunction tauchen86(μ::AbstractFloat, σ::AbstractFloat, n::Int64, λ::AbstractFloat)\n    xgrid, xprob, xscale = tauchen86(μ, 0., σ, n, λ)\n    return xgrid, vec(xprob[:, 1]), xscale\nend\n\n####################\n# Grid-based utils\n####################\nfunction get_grid(m::AbstractDSGEModel, grid_name::Symbol)\n    return m.grids[grid_name]\nend\n\nfunction quadrature_sum(x::Vector{T}, grid::Grid) where {T<:Real}\n    return sum(grid.weights .* x .* grid.points)\nend\n\nfunction quadrature_sum(grid::Grid, x::Vector{T}) where {T<:Real}\n    return sum(x, grid)\nend\n\n# # Defining arithmetic on/standard function evaluation of grids\n# for op in (:(Base.:+),\n           # :(Base.:-),\n           # :(Base.:*),\n           # :(Base.:/))\n           # # Exponentiation also omitted because of broadcasting issues\n\n    # @eval ($op)(g::Grid, x::Integer)           = ($op)(g.points, x)\n    # @eval ($op)(g::Grid, x::Number)            = ($op)(g.points, x)\n    # if op == :(Base.:/)\n        # op = :(Base.:./) # Will not work because the syntax for broadcasting has been\n                         # # updated to broadcast(/, ...)?\n        # @eval ($op)(x::Integer, g::Grid)       = ($op)(x, g.points)\n        # @eval ($op)(x::Number, g::Grid)        = ($op)(x, g.points)\n    # end\n# end\n\n# for f in (:(Base.:-),\n          # :(Base.:<),\n          # :(Base.:>),\n          # :(Base.:<=),\n          # :(Base.:>=))\n\n    # @eval ($f)(g::Grid) = ($f)(g.points)\n\n    # # Similar issues with broadcasting...\n    # if f != :(Base.:-)\n        # @eval ($f)(g::Grid, x::Number) = ($f)(g.points, x)\n    # end\n# end\n", "meta": {"hexsha": "a92dd4c622d86fc74a0c8d458231babfa36d42df", "size": 5078, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/grids.jl", "max_stars_repo_name": "vpmerila/DSGE.jl", "max_stars_repo_head_hexsha": "9fd9b04e366a23dd8a7b05302e4c985185d0ead5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 822, "max_stars_repo_stars_event_min_datetime": "2015-12-03T13:42:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T16:12:55.000Z", "max_issues_repo_path": "src/grids.jl", "max_issues_repo_name": "vpmerila/DSGE.jl", "max_issues_repo_head_hexsha": "9fd9b04e366a23dd8a7b05302e4c985185d0ead5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2016-06-20T14:42:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T16:14:10.000Z", "max_forks_repo_path": "src/grids.jl", "max_forks_repo_name": "vpmerila/DSGE.jl", "max_forks_repo_head_hexsha": "9fd9b04e366a23dd8a7b05302e4c985185d0ead5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 226, "max_forks_repo_forks_event_min_datetime": "2015-12-03T16:53:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T09:52:56.000Z", "avg_line_length": 36.5323741007, "max_line_length": 134, "alphanum_fraction": 0.5998424577, "num_tokens": 1522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7707194378771742}}
{"text": "using Plots, LaTeXStrings, Statistics\n\nfunction Deposition(;len, tot_time)\n    surf = [0 for i=1:len]\n    AvgList = [0.0 for i=1:tot_time]\n    for n in 2:tot_time+1\n        randsurf = rand(1:len)\n        for i in randsurf\n            index = FindLeast(surf, i, len)\n            surf[index] += 1\n        end\n        AvgList[n-1] = mean(surf)\n    end\n    return AvgList\nend\n\nfunction sides(n, L)\n    if n == L\n        return n-1 , 1\n    elseif n == 1\n        return L , n+1\n    else\n        return n-1, n+1\n    end\nend\n\nfunction FindLeast(surface, index_,L_surf)\n    i1 , i2 = sides(index_, L_surf)\n    lens = Dict(surface[i1]=>i1,\n        surface[index_]=>index_,\n        surface[i2]=>i2)\n    minlen = min(surface[i1],surface[index_],surface[i2])\n    return lens[minlen]\nend\n\nfunction Linear_fit(;Time, AvgList, tot_time)\n    A = [hcat(Time[1:tot_time]) reshape(ones(tot_time), tot_time, 1)]\n    b = reshape(AvgList[1:tot_time], tot_time, 1)\n    line = (A \\ b)\n    return line\nend\n\niternum = 1000\nParameters = Dict(:len => 300,\n                    :tot_time => 50,)\nallAvg = [ [0.0 for i in 1:Parameters[:tot_time]] for j = 1:iternum]\nmeanAvg = [0.0 for i in 1:Parameters[:tot_time]]\nvars = [0.0 for i in 1:Parameters[:tot_time]]\nfor i in 1:iternum\n    AvgList = Deposition(;Parameters...)\n    allAvg[i] = AvgList\n    meanAvg += AvgList\n    print(\"\\r$i\")\nend\nmeanAvg /= iternum\nfor i in 1:Parameters[:tot_time]\n    vars[i] = std(hcat(allAvg...)[i,:])\nend\n\nTime = 0:Parameters[:tot_time]-1\n\nParaline = Dict(\n                :Time => Time[1:end],\n                :AvgList => meanAvg[1:end],\n                :tot_time => 30)\nLine = Linear_fit(;Paraline...)\nX = Time[1]:Time[50]\nY = X .* Line[1] .+ Line[2]\nLine[2]\nplot(X,Y,c=:black,label = L\"y = %$(round(Line[1],digits= 3))x + %$(round(Line[2],digits= 3))\")\nscatter!(Time[1:end], meanAvg[1:end],\n    # xlims = (1, Parameters[:tot_time]),\n    c = :steelblue,\n    xlabel= L\"Time\",\n    ylabel= L\"H_{(t)}\",\n    title= L\"~H_{(t)}-Time~\\ (L = %$(Parameters[:len]))\",\n    label = L\"Data\\ point\",\n    yerror = vars)\n    # legend = nothing)\n\nsavefig(\"../../Figs/Q1/H-t(L=$(Parameters[:len])).pdf\")\n", "meta": {"hexsha": "74fdc9214bb4e640971afc1ed3d36700c524b6ae", "size": 2136, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSet3/Codes/Q1/Q1-H(t).jl", "max_stars_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_stars_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSet3/Codes/Q1/Q1-H(t).jl", "max_issues_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_issues_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSet3/Codes/Q1/Q1-H(t).jl", "max_forks_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_forks_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-21T11:07:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-21T11:07:08.000Z", "avg_line_length": 26.0487804878, "max_line_length": 94, "alphanum_fraction": 0.574906367, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035763237924, "lm_q2_score": 0.8887587964389112, "lm_q1q2_score": 0.7705856614048301}}
{"text": "# example from https://github.com/malmaud/TensorFlow.jl\nusing Distributions\nusing Printf\n\n# Generate some synthetic data\nx = randn(100, 50)\nw = randn(50, 10)\ny_prob = exp.(x*w)\ny_prob ./= sum(y_prob,dims=2)\n\nfunction draw(probs)\n    y = zeros(size(probs))\n    for i in 1:size(probs, 1)\n        idx = rand(Categorical(probs[i, :]))\n        y[i, idx] = 1\n    end\n    return y\nend\n\ny = draw(y_prob)\n\n# Build the model\nreset_default_graph()\nsess = Session()\n\nX = placeholder(Float64, shape=[nothing, 50])\nY_obs = placeholder(Float64, shape=[nothing, 10])\n\nvariable_scope(\"test_logisitic_model\"; initializer=random_normal_initializer(0, .001), reuse=AUTO_REUSE) do\n    global W = get_variable(\"W\", shape=[50, 10], dtype=Float64)\n    global B = get_variable(\"B\", shape=[10], dtype=Float64)\nend\n\nY=softmax(X*W + B)\n\nLoss = -sum(log(Y).*Y_obs)\n# adam = AdamOptimizer()\n# minimize_op = minimize(adam, Loss)\n\n# # Run training\n# init(sess)\n# for epoch in 1:1000\n#     cur_loss, _ = run(sess, [Loss, minimize_op], feed_dict=Dict(X=>x, Y_obs=>y))\n#     println(@sprintf(\"Current loss is %.2f.\", cur_loss))\n# end\n\nfunction print_loss(loss_evaled)\n    println(loss_evaled)\nend\n\nopt = ScipyOptimizerInterface(Loss, method=\"L-BFGS-B\",options=Dict(\"maxiter\"=> 100))\ninit(sess)\nScipyOptimizerMinimize(sess, opt, feed_dict=Dict(X=>x, Y_obs=>y), loss_callback=print_loss, fetches=[Loss])\n", "meta": {"hexsha": "e1c266d2a7b4176cffecfe2d6adb5dee2c11a753", "size": 1367, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/logistic.jl", "max_stars_repo_name": "EricDarve/ADCME.jl", "max_stars_repo_head_hexsha": "7eb334354e3ba5427a3f13a4a60e0f6ca5eec006", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-12T21:14:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-12T21:14:41.000Z", "max_issues_repo_path": "test/logistic.jl", "max_issues_repo_name": "EricDarve/ADCME.jl", "max_issues_repo_head_hexsha": "7eb334354e3ba5427a3f13a4a60e0f6ca5eec006", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/logistic.jl", "max_forks_repo_name": "EricDarve/ADCME.jl", "max_forks_repo_head_hexsha": "7eb334354e3ba5427a3f13a4a60e0f6ca5eec006", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3148148148, "max_line_length": 107, "alphanum_fraction": 0.6891002195, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506726044381, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.770569447044079}}
{"text": "\nusing DifferentialEquations\nusing OrdinaryDiffEq\nusing Distributions\nusing MonteCarloMeasurements\nusing StatsBase\nusing Plots\n\n\nfunction sir_ode!(du,u,p,t)\n    (S,I,R) = u\n    (β,c,γ) = p\n    N = S+I+R\n    @inbounds begin\n        du[1] = -β*c*I/N*S\n        du[2] = β*c*I/N*S - γ*I\n        du[3] = γ*I\n    end\n    nothing\nend;\n\n\nδt = 1.0\ntmax = 40.0\ntspan = (0.0,tmax);\n\n\nN = 1000.0;\n\n\nn_samples = 1000; # Number of samples\n\n\np = [Particles(n_samples,Uniform(0.01,0.1)),\n      Particles(n_samples,Uniform(5,20.0)),\n      Particles(n_samples,Uniform(0.1,1.0))]\n\n\nI₀=Particles(n_samples,Uniform(1.0,50.0))\nu0 = [N-I₀,I₀,0.0]\n\n\nprob_ode = ODEProblem(sir_ode!,u0,tspan,p);\n\n\nsol_ode = solve(prob_ode, Tsit5(), dt=δt);\n\n\ns20 = sol_ode(20.0)\n\n\nl = @layout [a b c]\nbinwidth = 50\npl1 = histogram(s20[1],bins=0:binwidth:N, title=\"S(20)\", xlabel=\"S\", ylabel=\"Frequency\", color=:blue)\npl2 = histogram(s20[2],bins=0:binwidth:N, title=\"I(20)\", xlabel=\"I\", ylabel=\"Frequency\", color=:red)\npl3 = histogram(s20[3],bins=0:binwidth:N, title=\"R(20)\", xlabel=\"R\", ylabel=\"Frequency\", color=:green)\nplot(pl1,pl2,pl3,layout=l,legend=false)\n\n\ncorkendall(hcat(Array(p),Array(I₀)),Array(s20))\n\n", "meta": {"hexsha": "b870dfeaa580a99c1000886193c144ff368e275e", "size": 1169, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_montecarlomeasurements/ode_montecarlomeasurements.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/ode_montecarlomeasurements/ode_montecarlomeasurements.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/ode_montecarlomeasurements/ode_montecarlomeasurements.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8548387097, "max_line_length": 102, "alphanum_fraction": 0.6407185629, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067147399245, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7705694419912018}}
{"text": "export Cos\n\n\"\"\"\n`Cos([domainType=Float64::Type,] dim_in::Tuple)`\n\nCreates a cosine non-linear operator with input dimensions `dim_in`:\n```math\n\\\\cos (\\\\mathbf{x} ).\n```\n\n\"\"\"\nstruct Cos{T,N} <: NonLinearOperator\n\tdim::NTuple{N,Int}\nend\n\nfunction Cos(DomainType::Type, DomainDim::NTuple{N,Int}) where {N} \n\tCos{DomainType,N}(DomainDim)\nend\n\nCos(DomainDim::NTuple{N,Int}) where {N} = Cos{Float64,N}(DomainDim)\nCos(DomainDim::Vararg{Int}) = Cos{Float64,length(DomainDim)}(DomainDim)\n\nfunction mul!(y::AbstractArray{T,N}, L::Cos{T,N}, x::AbstractArray{T,N}) where {T,N}\n\ty .= cos.(x)\nend\n\nfunction mul!(y::AbstractArray, \n              J::AdjointOperator{Jacobian{A,TT}}, \n              b::AbstractArray) where {T,N, A<: Cos{T,N}, TT <: AbstractArray{T,N}}\n    L = J.A\n    y .= -conj.(sin.(L.x)).*b\nend\n\nfun_name(L::Cos) = \"cos\"\n\nsize(L::Cos) = (L.dim, L.dim)\n\ndomainType(L::Cos{T,N}) where {T,N} = T\ncodomainType(L::Cos{T,N}) where {T,N} = T\n", "meta": {"hexsha": "f5fd9cf890f618ff5a340aca25be27a12c8aab4a", "size": 938, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nonlinearoperators/Cos.jl", "max_stars_repo_name": "nantonel/AbstractOperators.jl", "max_stars_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2017-08-28T17:28:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-21T18:53:01.000Z", "max_issues_repo_path": "src/nonlinearoperators/Cos.jl", "max_issues_repo_name": "nantonel/AbstractOperators.jl", "max_issues_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2017-11-17T14:43:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-23T20:02:48.000Z", "max_forks_repo_path": "src/nonlinearoperators/Cos.jl", "max_forks_repo_name": "nantonel/AbstractOperators.jl", "max_forks_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-09-02T08:56:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T18:56:33.000Z", "avg_line_length": 23.45, "max_line_length": 84, "alphanum_fraction": 0.6343283582, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067260443809, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7705694386653625}}
{"text": "using Polynomials\n\nfunction mypolyval(p::Poly,x::Number)\n    s=p[0]\n    t=one(x)\n    for i=1:length(p)-1\n        t*=x\n        s+=p[i]*t\n    end\n    s\nend \n\nfunction myhorner(p::Poly,x::Number)\n    s=p[end]\n    for i=length(p)-2:-1:0\n        s=s*x+p[i]\n    end\n    s\nend\n\nn=10001\npbig=Poly(rand(n))\nx=0.12345;", "meta": {"hexsha": "f8576baed70e2078a9f441259a44be326f2e0724", "size": 308, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Module A - Short Julia Course/myfunctions.jl", "max_stars_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_stars_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2016-06-10T09:40:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:00:08.000Z", "max_issues_repo_path": "src/Module A - Short Julia Course/myfunctions.jl", "max_issues_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_issues_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Module A - Short Julia Course/myfunctions.jl", "max_forks_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_forks_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2016-06-21T14:20:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T17:03:59.000Z", "avg_line_length": 13.3913043478, "max_line_length": 37, "alphanum_fraction": 0.5324675325, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567177, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7705645332663458}}
{"text": "export AbLoss, MSE, MAD, LOGIT, altloss\n\nabstract type AbLoss end\n# Notation\n#       y = Observed target\n#       z = fit Σ_j ϕ(X, ω_j)\n# Methods\n#       Loss evaluation\n#       Generalized Residual\nvalnderv(l::AbLoss, y, z) = l(y, z), derv(l, y, z)\naltloss(l::AbLoss) =  (_...) -> NaN\n\n################################################################################\ntype MSELoss <: AbLoss\nend\n\nconst MSE = MSELoss()\n\n(l::MSELoss)(y, z) = sum(abs2, z-y)/2\nderv(::MSELoss, y, z) = z-y\nderv2(::MSELoss, y, z) = 1.\nfunction valnderv(::MSELoss, y, z)\n  diff = z-y\n  sum(abs2, diff)/2, diff\nend\n\n################################################################################\ntype MADLoss <: AbLoss\nend\n\nconst MAD = MADLoss()\n\n(l::MADLoss)(y, z) =  sum(abs, z-y)\nderv(::MADLoss, y, z) = sign.(z-y)\nderv2(::MADLoss, y, z) = 0.\nfunction valnderv(::MADLoss, y, z)\n    diff = z-y\n    sum(abs, diff), sign.(diff)\nend\n\n################################################################################\ntype LogitLoss <: AbLoss\nend\n\nconst LOGIT = LogitLoss()\n\nlog1plusexp(x) = (x<0.) ? log1p(exp(x)) : x+log1p(exp(-x))\nsigmoid(x) = (x<0.) ? exp(x)/(1.+exp(x)) : 1./(1.+exp(-x))\n(l::LogitLoss)(y, z) =  sum(log1plusexp.(z)) - y'*z\nderv(::LogitLoss, y, z) = sigmoid.(z) - y\nderv2(::LogitLoss, y, z) = (s=sigmoid.(z); (1-s).*s)\n\"\"\"\nbits(sigmoid(-64)) = \"0011101000101001011010011101010001110011001000011110010011001100\"\nbits(1-(1-sigmoid(-64))) = \"0000000000000000000000000000000000000000000000000000000000000000\"\n\"\"\"\n\nmisclassification(y, z, threshold=.5) = sum(y .!= (sigmoid.(z) .≥ threshold))\naltloss(::LogitLoss) =  misclassification\n################################################################################\n", "meta": {"hexsha": "18c1d9467cb5b66da1b25c5f1564525d1ab3f9db", "size": 1704, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Tlosses.jl", "max_stars_repo_name": "rakeshvar/AnyBoost.jl", "max_stars_repo_head_hexsha": "f2477b1737e8834d622b1e3b7269bd133b25e544", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-06-27T20:40:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T07:35:44.000Z", "max_issues_repo_path": "src/Tlosses.jl", "max_issues_repo_name": "rakeshvar/AnyBoost.jl", "max_issues_repo_head_hexsha": "f2477b1737e8834d622b1e3b7269bd133b25e544", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-06-22T03:59:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-18T05:27:02.000Z", "max_forks_repo_path": "src/Tlosses.jl", "max_forks_repo_name": "rakeshvar/AnyBoost.jl", "max_forks_repo_head_hexsha": "f2477b1737e8834d622b1e3b7269bd133b25e544", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4, "max_line_length": 93, "alphanum_fraction": 0.5070422535, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7705645320668475}}
{"text": "# some kernels\nepanechnikov(x::Tp) where {Tp<:AbstractFloat} = Tp( (abs(x) ≤  1.0) ? 0.75 * (1.0-x*x) : 0.0 )\ngaussian(x::Tp) where {Tp<:AbstractFloat} = Tp( exp( -0.5 * x * x) * 0.3989422804014327 )\ntriweight(x::Tp) where {Tp<:AbstractFloat} = Tp( (abs(x) ≤ 1.0) ? 1.09375 * (1.0-x*x)^3  : 0.0 )\nuniform(x::Tp) where {Tp<:AbstractFloat} = Tp( (abs(x) ≤ 1.0) ? 0.5 : 0.0 )\ncosinus(x::Tp) where {Tp<:AbstractFloat} = Tp( (abs(x) ≤ 1.0) ?   0.7853981633974483    * cos( 1.5707963267948966 * x ) : 0.0 )\nquartic(x::Tp) where {Tp<:AbstractFloat} = Tp( (abs(x) ≤ 1.0) ? 0.9375 * (1.0 - x*x)^2 : 0.0 )\n", "meta": {"hexsha": "d345e35ff5c6990d4ff25427ec50b1111154bd77", "size": 596, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels.jl", "max_stars_repo_name": "NittanyLion/LogDensity.jl", "max_stars_repo_head_hexsha": "f55de4f4adfcbf9406667fa0661f55f61be967d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels.jl", "max_issues_repo_name": "NittanyLion/LogDensity.jl", "max_issues_repo_head_hexsha": "f55de4f4adfcbf9406667fa0661f55f61be967d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-13T18:05:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T18:05:49.000Z", "max_forks_repo_path": "src/kernels.jl", "max_forks_repo_name": "NittanyLion/LogDensity.jl", "max_forks_repo_head_hexsha": "f55de4f4adfcbf9406667fa0661f55f61be967d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 74.5, "max_line_length": 127, "alphanum_fraction": 0.5755033557, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104865, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7705645244998811}}
{"text": "\"\"\"\n# `SphericalGeom`\n\nCalculate properties on a sphere.\n\nBy default, calculations are made in degrees, and all routines have a final\nargument `degrees` which may be set to false for radians.  This is advantageous\nwhen making repeated calculations or when using large arrays in terms of speed.\n\"\"\"\nmodule SphericalGeom\n\nimport StaticArrays: SVector\n\nimport Base.step\n\nexport\n    azimuth,\n    cart2geog,\n    delta,\n    geog2cart,\n    great_circle,\n    great_circle_azimuth,\n    nearest_to_gcp,\n    project_to_gcp,\n    sample,\n    step\n\n\"\"\"\n    cart2geog(x, y, z, degrees::Bool=true) -> lon, lat, r\n\nCompute the longitude, latitude and radius given the cartesian coordinates `x`,\n`y` and `z`, where `x` is at (lon,lat) = (0,0), `y` is at (90°,0) and `z` is\nthrough lat = 90°.\n\"\"\"\nfunction cart2geog(x, y, z, degrees::Bool=true)\n    r = sqrt(x^2 + y^2 + z^2)\n    r == 0. && return zero(x), zero(x), zero(x)\n    lon = atan(y, x)\n    lat = asin(z/r)\n    degrees ? (rad2deg(lon), rad2deg(lat), r) : (lon, lat, r)\nend\n\nfunction cart2geog(x::AbstractArray, y::AbstractArray, z::AbstractArray, degrees::Bool=true)\n    dims = size(x)\n    dims == size(y) == size(z) || throw(ArgumentError(\"All arrays must have same length\"))\n    T = promote_type(float.(eltype.((x, y, z)))...)\n    lon, lat, r = Array{T}(dims), Array{T}(dims), Array{T}(dims)\n    for i in eachindex(lon)\n        lon[i], lat[i], r[i] = cart2geog(x[i], y[i], z[i], degrees)\n    end\n    lon, lat, r\nend\n\n\"\"\"\n    delta(lon1, lat1, lon2, lat2, degrees::Bool=true) -> d\n\nCompute the angular distance `d` on the sphere between two points, (`lon1`, `lat1`)\nand (`lon2`, `lat2`).  Points and distance are read and returned in degrees\nby default; use `degrees=false` for radians.\n\"\"\"\nfunction delta(lon1, lat1, lon2, lat2, degrees::Bool=true)\n    if degrees\n        lon1, lat1, lon2, lat2 = deg2rad(lon1), deg2rad(lat1), deg2rad(lon2), deg2rad(lat2)\n    end\n    d = atan(sqrt(\n               (cos(lat2)*sin(lon2-lon1))^2 + (cos(lat1)*sin(lat2) -\n                sin(lat1)*cos(lat2)*cos(lon2-lon1))^2),\n               sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2)*cos(lon2-lon1)\n              )\n    degrees ? rad2deg(d) : d\nend\n\n\"\"\"\n    geog2cart(lon, lat, r, degrees::Bool=true) -> x, y, z\n    geog2cart(lon, lat, degrees::Bool=true) -> x, y, z\n\nReturn the cartesian coordinates given the geographic longitude, latitude and\nradius `lon`, `lat` and `r`.\n\nIf `r` is not given, points are returned on the unit sphere.\n\"\"\"\nfunction geog2cart(lon, lat, r, degrees::Bool=true)\n    points_valid(lon, lat, degrees) || error(\"geog2cart: Points are not on the sphere\")\n    degrees && begin lon, lat = deg2rad(lon), deg2rad(lat) end\n    x = r*cos(lon)*cos(lat)\n    y = r*sin(lon)*cos(lat)\n    z = r*sin(lat)\n    x, y, z\nend\nfunction geog2cart(lon::AbstractArray, lat::AbstractArray, r::AbstractArray, degrees::Bool=true)\n    size(lon) == size(lat) == size(r) ||\n        throw(ArgumentError(\"Sizes of lon, lat and r must be the same\"))\n    T = promote_type(float.(eltype.((lon, lat, r)))...)\n    x = Array{T}(undef, size(lon))\n    y, z = similar(x), similar(x)\n    for i in eachindex(lon)\n        x[i], y[i], z[i] = geog2cart(lon[i], lat[i], r[i], degrees)\n    end\n    x, y, z\nend\ngeog2cart(lon::AbstractArray, lat::AbstractArray, degrees::Bool=true) =\n    geog2cart(lon, lat, fill(one(eltype(lon)), size(lon)), degrees)\n\n\n\"\"\"\n    step(lon, lat, az, delta, degrees::Bool=true) -> lon1, lat1\n\nCompute the end point (`lon1`, `lat1`) reached by travelling on the sphere along\nazimuth `az` for `delta` angular distance.  Points, angles and distance are read\nand returned in degrees by default; use `degrees=false` for radians.\n\"\"\"\nfunction step(lon, lat, az, delta, degrees::Bool=true)\n    if degrees\n        delta <= 180 || error(\"step: delta cannot be more than 180°\")\n        lon, lat, az, delta = deg2rad(lon), deg2rad(lat), deg2rad(az), deg2rad(delta)\n    else\n        delta <= pi || error(\"step: delta cannot be more than π radians\")\n    end\n    lat2 = asin(sin(lat)*cos(delta) + cos(lat)*sin(delta)*cos(az))\n    lon2 = lon + atan(sin(az)*sin(delta)*cos(lat),\n                      cos(delta)-sin(lat)*sin(lat2))\n    if degrees\n        lon2, lat2 = rad2deg(lon2), rad2deg(lat2)\n    end\n    lon2, lat2\nend\n\n\"\"\"\n    azimuth(lon1, lat1, lon2, lat2, degrees::Bool=true) -> az\n\nCompute the azimuth `az` from point (`lon1`, `lat1`) to (`lon2`, `lat2`) on the sphere.\nPoints and azimuth are read and returned in degrees by default; use `degrees=false`\nfor radians.\n\"\"\"\nfunction azimuth(lon1, lat1, lon2, lat2, degrees::Bool=true)\n    if degrees\n        lon1, lat1, lon2, lat2 = deg2rad(lon1), deg2rad(lat1), deg2rad(lon2), deg2rad(lat2)\n    end\n    azimuth = atan(sin(lon2-lon1)*cos(lat2),\n                   cos(lat1)*sin(lat2) - sin(lat1)*cos(lat2)*cos(lon2-lon1))\n    degrees ? rad2deg(azimuth) : azimuth\nend\n\n\"\"\"\n    sample(d=5, degrees::Bool=true) -> lon[], lat[]\n\nCreate a set of points which approximately evenly sample the sphere, spaced about `d`\ndegrees apart (default 5°).  Returns arrays `lon` and `lat` containing the longitude\nand latitude (degrees).  Spacing and points are read and returned in degrees by default;\nuse `false` as last argument to use radians.\n\"\"\"\nfunction sample(d=5, degrees::Bool=true)\n    nmax = 50000\n    lon = Array(Float64, nmax)\n    lat = Array(Float64, nmax)\n    n = 1\n    dlat = d\n    dlon = dlat\n    lat[n] = 90.0\n    lon[n] = 0.0\n    lon_i = 0.0\n    lat_i = lat[1] - dlat\n    while lat_i > -90.0\n        dlon_i = dlon/sind(90.0 - lat_i)\n        n_i = round(Int, 360.0/dlon_i)\n        for i = 1:n_i\n            n += 1\n            n <= nmax || error(\"Number of points greater than predetermined limits ($nmax)\")\n            lat[n] = lat_i\n            lon[n] = lon_i\n            lon_i = mod(lon_i + dlon_i, 360.0)\n        end\n        lon_i = mod(lon_i + dlon_i, 360.0)\n        lat_i = lat_i - dlat\n    end\n    n += 1\n    lat[n] = -90.0\n    lon[n] = 0.0\n    lon[1:n] = mod(lon[1:n] + 180.0, 360.0) - 180.0\n    degrees ? (lon[1:n], lat[1:n]) : (rad2deg(lon[1:n], rad2deg(lat[1:n])))\nend\n\n\"\"\"\n    project_to_gcp(lon_gc, lat_gc, lon_p, lat_p, degrees::Bool=true) -> lon, lat\n\nProject the point at (`lon_p`, `lat_p`) onto the great circle defined by the\npole to the circle (`lon_gc`, `lat_gc`), returning the point (`lon`, `lat`).\n\"\"\"\nfunction project_to_gcp(long, latg, lonp, latp, degrees::Bool=true)\n    # Convert to vectors\n    g = SVector(geog2cart(long, latg, degrees)...)\n    p = SVector(geog2cart(lonp, latp, degrees)...)\n    # Pole to the gcp containing g and p\n    gp = g × p\n    # Check for point and pole being the same\n    norm(gp) ≈ 0. && error(\"Point and pole to plane the same\")\n    gp = normalize(gp)\n    pp = gp × g\n    acos(p⋅pp) > π/2 && (pp *= -1)\n    lon, lat, r = cart2geog(pp[1], pp[2], pp[3], degrees)\n    lon, lat\nend\n\n\"\"\"\n    nearest_to_gcp(lon_gc, lat_gc, lons, lats, degrees::Bool=trye) -> i, lon, lat\n\nFind the nearest point to the great circle defined by the pole (`lon_gc`, `lat_gc`)\nwhich occurs in the vectors `lons` and `lats`.  The index `i` and values at that index\n`lon` and `lat` are returned.\n\"\"\"\nfunction nearest_to_gcp(long, latg, lons::AbstractArray, lats::AbstractArray, degrees::Bool=true)\n    length(lons) == length(lats) ||\n        throw(ArgumentError(\"lons and lats must have same number of points\"))\n    mindist = Inf\n    imin = 0\n    for (i, (lon, lat)) in enumerate(zip(lons, lats))\n        lonp, latp = project_to_gcp(long, latg, lon, lat, degrees)\n        dist = delta(lon, lat, lonp, latp, degrees)\n        if dist < mindist\n            mindist = dist\n            imin = i\n        end\n    end\n    imin, lons[imin], lats[imin]\nend\n\n\"\"\"\n    great_circle(lon, lat, azimuth, degrees::Bool=true) -> lon_gc, lat_gc\n    great_circle(lon1, lat1, lon2, lat2, degrees::Bool=true) -> lon_gc, lat_gc\n\nDetermine the great circle, defined by the pole at (`lon_gc`, `lat_gc`), given by\neither (the first form), a point and an azimuth, or (the second) two points on the\nsphere.\n\"\"\"\nfunction great_circle(lon, lat, azimuth, degrees::Bool=true)\n    dist = degrees ? 45 : π/4\n    lonp, latp = step(lon, lat, azimuth, dist, degrees)\n    great_circle(lon, lat, lonp, latp, degrees)\nend\nfunction great_circle(lon1, lat1, lon2, lat2, degrees::Bool=true)\n    p1 = SVector(geog2cart(lon1, lat1, degrees)...)\n    p2 = SVector(geog2cart(lon2, lat2, degrees)...)\n    p1 ≈ p2 && error(\"Two points overlap (are: $p1 and $p2)\")\n    delta(lon1, lat1, lon2, lat2, degrees) ≈ (degrees ? 180 : π) &&\n        error(\"Points are antipodal (are: $p1 and $p2)\")\n    gp = p1 × p2\n    lon, lat, r = cart2geog(gp[1], gp[2], gp[3], degrees)\n    lon, lat\nend\n\n\"\"\"\n    great_circle_azimuth(long, latg, lonp, latp, degrees::Bool=true) -> azimuth\n\nReturn the local `azimuth` of the great circle with pole (`long`, `latg`) where\nthe point (`lonp`, `latp`) projects onto the great circle.\n\"\"\"\nfunction great_circle_azimuth(long, latg, lonp, latp, degrees::Bool=true)\n    lon, lat = project_to_gcp(long, latg, lonp, latp, degrees)\n    mod(azimuth(lon, lat, long, latg, degrees) + (degrees ? 90 : π/2), (degrees ? 360 : 2π))\nend\n\n\"\"\"\n    points_valid(lon, lat, degrees::Bool=true) -> ::Bool\n\nReturn `true` if all points in arrays `lon` and `lat` are on the sphere.\n`lon` is ignored, but `lat` is checked to see if points are in the range\n-90°–90° (-π–π).  Points are read and returned in degrees by default; use\n`degrees=false` for radians.\n\"\"\"\npoints_valid(lon, lat, degrees::Bool=true) =\n    degrees ? !any(abs.(lat) .> 90.) : !any(abs.(lat) .> pi/2.)\n\nend # module\n", "meta": {"hexsha": "156fae95002326aa3caedd8d4121340215bb22df", "size": 9530, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SphericalGeom.jl", "max_stars_repo_name": "anowacki/SphericalGeom.jl", "max_stars_repo_head_hexsha": "dd56469e76159dd5f7f287d1927e54d18886e5d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SphericalGeom.jl", "max_issues_repo_name": "anowacki/SphericalGeom.jl", "max_issues_repo_head_hexsha": "dd56469e76159dd5f7f287d1927e54d18886e5d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SphericalGeom.jl", "max_forks_repo_name": "anowacki/SphericalGeom.jl", "max_forks_repo_head_hexsha": "dd56469e76159dd5f7f287d1927e54d18886e5d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7810218978, "max_line_length": 97, "alphanum_fraction": 0.6293809024, "num_tokens": 3017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.770564523900132}}
{"text": "\"\"\"\n    tracking_error(asset_returns, benchmark_returns; multiplier=1.0)\n\nCalculates the ex-post Tracking Error based on the standard deviation of the active returns.\n\n# Formula\n\n    TE = std(asset_returns - benchmark_returns) * sqrt(multiplier)\n\n# Arguments\n- `asset_returns`:      Vector of asset returns.\n- `benchmark_returns`:  Vector of benchmark returns.\n- `multiplier`:         Optional scalar multiplier, i.e. use `12` to annualize monthly returns, and use `252` to annualize daily returns.\n\"\"\"\nfunction tracking_error(asset_returns, benchmark_returns; multiplier=1.0)\n    std(asset_returns .- benchmark_returns) * sqrt(multiplier)\nend\n", "meta": {"hexsha": "a4f7469968256d9674f65c8d979b7a6114c77ff1", "size": 644, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tracking_error.jl", "max_stars_repo_name": "rbeeli/RiskPerf.jl", "max_stars_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-07T19:19:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T19:19:09.000Z", "max_issues_repo_path": "src/tracking_error.jl", "max_issues_repo_name": "rbeeli/RiskPerf.jl", "max_issues_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tracking_error.jl", "max_forks_repo_name": "rbeeli/RiskPerf.jl", "max_forks_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7777777778, "max_line_length": 137, "alphanum_fraction": 0.751552795, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7705645201740917}}
{"text": "# this is the funtion that appears in the\n# FoggySurface and FoggyContour graphics,\n# It is the Octave sombrero, tilted a bit\nfunction FoggyMountainObj(θ₁, θ₂)\n   \tr = sqrt(θ₁^2.0 + θ₂^2.0) + 1e-10\n\tz = sin(r) / (2*r)\n\tz = z + θ₁/40.0 - 2*(θ₁/40.0)^2.0 + θ₂/40.0 - 2*(θ₂/40.0)^2.0 \n\tz = -z/10.0 # switch to minimization\nend\n\nfunction FoggyMountainObj(θ)\n\tθ₁ = θ[1]\n\tθ₂ = θ[2]\n    FoggyMountainObj(θ₁, θ₂)\nend\n", "meta": {"hexsha": "109973b342753de3676798291b5dcc46c8164009", "size": 409, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/NonlinearOptimization/FoggyMountainObj.jl", "max_stars_repo_name": "Hiroakiyusheng/Econometrics", "max_stars_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-19T18:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T18:23:45.000Z", "max_issues_repo_path": "Examples/NonlinearOptimization/FoggyMountainObj.jl", "max_issues_repo_name": "Hiroakiyusheng/Econometrics", "max_issues_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/NonlinearOptimization/FoggyMountainObj.jl", "max_forks_repo_name": "Hiroakiyusheng/Econometrics", "max_forks_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5625, "max_line_length": 63, "alphanum_fraction": 0.6405867971, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811611608241, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7705544760002412}}
{"text": "# # Specifying and fine-tuning prior distributions\n#\n# This example shows how to specify priors in `ParameterEstimocean`\n# and illustrates some of their properties.\n#\n# ## Install dependencies\n#\n# First let's make sure we have all required packages installed.\n\n# ```julia\n# using Pkg\n# pkg\"add ParameterEstimocean, Oceananigans, Distributions, CairoMakie\"\n# ```\n#\n# Then we import packages\n\nusing ParameterEstimocean\nusing CairoMakie\nusing Distributions\n\n# # What's a prior?\n#\n# A \"prior\" is a probability distribution for an known parameter that\n# represents \"prior knowledge\" of the problem at hand, before we generate\n# new knowledge with a new model-data comparison via ensemble Kalman inversion (EKI).\n#\n# In the (EKI) context, a prior distribution determines (i) the initial distribution\n# of parameter values in the ensemble and (ii) the mapping between physical space\n# where constraints on parameter values are applied, and the \"unconstrained\" space\n# in which the EKI dynamics evolve (and where parameters are assumed normally-distributed).\n#\n# # Prior flavors\n#\n# `ParameterEstimocean` supports three types of prior\n# distributions. The normal prior distribution is provided by `Distributions.jl`,\n\nnormal_prior = Normal(0.1, 0.1)\n\n# For `LogNormal` priors, we provide a special constructor that takes the `mean` and\n# standard deviation `std` of the prior distribution in _constrained_ space:\n\nlognormal_prior = lognormal(mean=0.1, std=0.1)\n\n# `lognormal` calculates `μ` and `σ` for `Distributions.Lognormal(μ, σ)`.\n# Parameters with a `Lognormal` prior distribution are _strictly_ positive.\n# Finally, the \"scaled\" logit-normal prior,\n\nlogitnormal_prior = ScaledLogitNormal(bounds=(0, 0.2))\n\n# can be used to provide strict upper and lower bounds for parameter values.\n#\n# ## Samples\n#\n# Sampling the distributions reveals their properties. We define a function to use\n# later, too.\n\nfunction visualize_priors(priors; samples = 10^6)\n    fig = Figure()\n    ax = Axis(fig[1, 1:9], xlabel=\"Random samples of priors\", ylabel=\"Density\")\n\n    for (prior, name) in zip(values(priors), keys(priors))\n        density!(ax, rand(prior, samples), label=replace(string(name), \"_\" => \" \"))\n    end\n\n    axislegend(ax)\n\n    return fig, ax\nend\n\nfig, ax = visualize_priors(Dict(\"Normal\" => normal_prior,\n                                \"Log normal\" => lognormal_prior,\n                                \"Scaled logit-normal\" => logitnormal_prior))\n\nxlims!(ax, -0.5, 1.5)\nsave(\"prior_flavors.svg\", fig); nothing # hide \n\n# ![](prior_flavors.svg)\n\n# We note three important features:\n#\n# 1. `Normal` samples can be negative.\n# 2. `Lognormal` samples cannot be negative, but can have large positive values.\n# 3. `ScaledLogitNormal` samples have compact support, and thus strict upper and lower bounds.\n#\n# Boundedness is a very useful property of `ScaledLogitNormal`, so we\n# explore specifying `ScaledLogitNormal` priors in more detail.\n#\n# # Fine-tuning a `ScaledLogitNormal` prior\n#\n# We can tune the \"width\" of a `ScaledLogitNormal` by supplying the\n# standard-deviation `σ`:\n\nlogit_priors = Dict(\"Narrow (σ = 0.1)\"                 => ScaledLogitNormal(σ = 0.1),\n                    \"Default (σ = 1)\"                  => ScaledLogitNormal(σ = 1),\n                    \"Weird (σ = 4 with bounds=(0, 1))\" => ScaledLogitNormal(σ = 4))\n\nfig, ax = visualize_priors(logit_priors)\nxlims!(ax, -0.1, 1.1)\nsave(\"logit_normal_widths.svg\", fig); nothing #hide \n\n# ![](logit_normal_widths.svg)\n\n# Smaller standard deviations produce narrower prior distributions.\n# However, weird shapes can result when a standard deviation is specified\n# that's larger than the bounds interval (eg `σ > diff(bounds)`).\n# In the above example we're using the default `bounds = (0, 1)`.\n#\n# Another way to build `ScaledLogitNormal` prior is to specify\n# a central `interval` and `mass`. This allows us to shift the center of\n# mass relative to the bounds (here we use the default `bounds=(0, 1)`),\n# and provides a slightly safer way to tune a distribution.\n\nshifted_priors = Dict(\"Shifted left\"  => ScaledLogitNormal(interval=(0.2, 0.3), mass=0.9),\n                      \"Shifted right\" => ScaledLogitNormal(interval=(0.7, 0.8), mass=0.9),\n                      \"Centered\"      => ScaledLogitNormal(interval=(0.2, 0.8), mass=0.6))\n\nfig, ax = visualize_priors(shifted_priors)\nxlims!(ax, -0.1, 1.1)\nsave(\"logit_normal_shifting.svg\", fig); nothing #hide \n\n# ![](logit_normal_shifting.svg)\n#\n# The \"Centered\" case uses a `mass` that's proportional to the relative width spanned\n# by `interval` (eg `mass = diff(interval) / diff(bounds)`) to produce a nearly\n# uniform distribution within the bounds.\n\n", "meta": {"hexsha": "5c8d0c917b3906b0e815421183e4e04513aaae4f", "size": 4662, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/exploring_priors.jl", "max_stars_repo_name": "CliMA/ParameterEstimocean.jl", "max_stars_repo_head_hexsha": "c94bc6e98422d8458ad0cf3fc0529d1bada8dd96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-09T13:10:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T13:10:41.000Z", "max_issues_repo_path": "examples/exploring_priors.jl", "max_issues_repo_name": "CliMA/OceanLearning.jl", "max_issues_repo_head_hexsha": "48204cfea9116fdd3be5edb5e7bbe7598e2fae2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2022-03-09T05:47:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T04:58:22.000Z", "max_forks_repo_path": "examples/exploring_priors.jl", "max_forks_repo_name": "CliMA/ParameterEstimocean.jl", "max_forks_repo_head_hexsha": "c94bc6e98422d8458ad0cf3fc0529d1bada8dd96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7086614173, "max_line_length": 94, "alphanum_fraction": 0.7029172029, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7704786802256011}}
{"text": "## Basic weight functions\n\nexport LebesgueMeasure,\n    Lebesgue,\n    LebesgueDomain,\n    lebesguemeasure,\n    dx,\n    LegendreWeight,\n    JacobiWeight,\n    ChebyshevWeight,\n    ChebyshevTWeight,\n    ChebyshevUWeight,\n    LaguerreWeight,\n    HermiteWeight,\n    GaussianWeight,\n    DiracWeight,\n    point,\n    jacobi_α,\n    jacobi_β,\n    laguerre_α\n\n\n####################\n# Lebesgue measures\n####################\n\n\n\"Supertype of Lebesgue measures\"\nabstract type LebesgueMeasure{T} <: Weight{T} end\n\nunsafe_weightfun(μ::LebesgueMeasure, x) = one(codomaintype(μ))\n\nislebesguemeasure(m::Measure) = false\nislebesguemeasure(m::LebesgueMeasure) = true\n\n==(μ1::LebesgueMeasure, μ2::LebesgueMeasure) = support(μ1) == support(μ2)\n\n\n\"The Lebesgue measure on the space `FullSpace{T}`.\"\nstruct Lebesgue{T} <: LebesgueMeasure{T}\nend\n\nLebesgue() = Lebesgue{Float64}()\nsimilar(μ::Lebesgue, ::Type{T}) where {T} = Lebesgue{T}()\n\nBase.show(io::IO, μ::Lebesgue) = print(io, \"dx\")\n\n\n\"The Lebesgue measure on the unit interval `[0,1]`.\"\nstruct LebesgueUnit{T} <: LebesgueMeasure{T}\nend\n\nLebesgueUnit() = LebesgueUnit{Float64}()\nsimilar(μ::LebesgueUnit, ::Type{T}) where {T <: Real} = Lebesgue{T}()\nsupport(μ::LebesgueUnit{T}) where {T} = UnitInterval{T}()\n\nisnormalized(μ::LebesgueUnit) = true\n\nBase.show(io::IO, μ::LebesgueUnit) = print(io, \"dx(0..1)\")\n\n\n\"Lebesgue measure supported on a general domain.\"\nstruct LebesgueDomain{T} <: LebesgueMeasure{T}\n    domain  ::  Domain{T}\nend\n\nsimilar(μ::LebesgueDomain, ::Type{T}) where {T} = LebesgueDomain{T}(μ.domain)\nsupport(m::LebesgueDomain) = m.domain\n\nBase.show(io::IO, mime::MIME\"text/plain\", μ::LebesgueDomain) = composite_show(io, mime, μ)\nDisplay.displaystencil(μ::LebesgueDomain) = [\"dx(\", support(μ), \")\"]\n\n\n###############\n# Dirac weight\n###############\n\n\"A continuous Dirac measure at a point\"\nstruct DiracWeight{T} <: Weight{T}\n    point   ::  T\nend\n\nsimilar(μ::DiracWeight, ::Type{T}) where {T} = DiracWeight{T}(μ.point)\n\npoint(μ::DiracWeight) = μ.point\nsupport(μ::DiracWeight) = Point(μ.point)\nisnormalized(μ::DiracWeight) = true\nunsafe_weightfun(μ::DiracWeight, x) = convert(codomaintype(μ), Inf)\n\nBase.show(io::IO, μ::DiracWeight) = iszero(point(μ)) ? print(io, \"δ(x)dx\") : print(io, \"δ(x-$(repr(point(μ))))dx\")\n\n\n###################################\n# Classical orthogonal polynomials\n###################################\n\n\n\"The Legendre weight is a Lebesgue measure on the interval `[-1,1]`.\"\nstruct LegendreWeight{T} <: LebesgueMeasure{T}\nend\nLegendreWeight() = LegendreWeight{Float64}()\n\nsimilar(μ::LegendreWeight, ::Type{T}) where {T <: Real} = LegendreWeight{T}()\nsupport(μ::LegendreWeight{T}) where {T} = ChebyshevInterval{T}()\n\nBase.show(io::IO, μ::LegendreWeight) = print(io, \"dx(-1..1)  (Legendre)\")\nDisplay.object_parentheses(μ::LegendreWeight) = true\n\n\n\"Supertype of Jacobi weights.\"\nabstract type AbstractJacobiWeight{T} <: Weight{T} end\n\n==(μ1::AbstractJacobiWeight, μ2::AbstractJacobiWeight) =\n    jacobi_α(μ1) == jacobi_α(μ2) && jacobi_β(μ1) == jacobi_β(μ2)\n\n\"The Jacobi weight on the interval `[-1,1]`.\"\nstruct JacobiWeight{T} <: AbstractJacobiWeight{T}\n    α   ::  T\n    β   ::  T\n\n    JacobiWeight{T}(α = zero(T), β = zero(T)) where {T} = new(α, β)\nend\nJacobiWeight() = JacobiWeight{Float64}()\nJacobiWeight(α, β) = JacobiWeight(promote(α, β)...)\nJacobiWeight(α::T, β::T) where {T<:AbstractFloat} = JacobiWeight{T}(α, β)\nJacobiWeight(α::N, β::N) where {N<:Number} = JacobiWeight(float(α), float(β))\n\njacobi_weightfun(x, α, β) = (1+x)^α * (1-x)^β\n\nsimilar(μ::JacobiWeight, ::Type{T}) where {T <: Real} = JacobiWeight{T}(μ.α, μ.β)\nsupport(μ::JacobiWeight{T}) where {T} = ChebyshevInterval{T}()\nunsafe_weightfun(μ::JacobiWeight, x) = jacobi_weightfun(x, μ.α, μ.β)\n\njacobi_α(μ::JacobiWeight) = μ.α\njacobi_β(μ::JacobiWeight) = μ.β\n\nBase.show(io::IO, μ::JacobiWeight) = print(io, \"(1+x)^$(jacobi_α(μ))(1-x)^$(jacobi_β(μ)) dx  (Jacobi)\")\nDisplay.object_parentheses(μ::JacobiWeight) = true\n\n\n\"\"\"\nThe `Chebyshev` or `ChebyshevT` weight is the measure on `[-1,1]` with the\nChebyshev weight function `w(x) = 1/√(1-x^2)`.\n\"\"\"\nstruct ChebyshevTWeight{T} <: AbstractJacobiWeight{T}\nend\nChebyshevTWeight() = ChebyshevTWeight{Float64}()\n\nconst ChebyshevWeight = ChebyshevTWeight\n\nchebyshev_weight_firstkind(x) = 1/sqrt(1-x^2)\n\njacobi_α(μ::ChebyshevTWeight{T}) where {T} = -one(T)/2\njacobi_β(μ::ChebyshevTWeight{T}) where {T} = -one(T)/2\n\nsimilar(μ::ChebyshevTWeight, ::Type{T}) where {T <: Real} = ChebyshevTWeight{T}()\nsupport(μ::ChebyshevTWeight{T}) where {T} = ChebyshevInterval{T}()\nunsafe_weightfun(μ::ChebyshevTWeight, x) = chebyshev_weight_firstkind(x)\n\nweightfunction(μ::ChebyshevTWeight) = chebyshev_weight_firstkind\n\nBase.show(io::IO, μ::ChebyshevTWeight) = print(io, \"1/√(1+x)^2 dx  (ChebyshevT)\")\nDisplay.object_parentheses(μ::ChebyshevTWeight) = true\n\n\n\"\"\"\nThe ChebyshevU weight is the measure on `[-1,1]` with the Chebyshev weight\nfunction of the second kind `w(x) = √(1-x^2).`\n\"\"\"\nstruct ChebyshevUWeight{T} <: AbstractJacobiWeight{T}\nend\nChebyshevUWeight() = ChebyshevUWeight{Float64}()\n\nchebyshev_weight_secondkind(x) = sqrt(1-x^2)\n\njacobi_α(μ::ChebyshevUWeight{T}) where {T} = one(T)/2\njacobi_β(μ::ChebyshevUWeight{T}) where {T} = one(T)/2\n\nsimilar(μ::ChebyshevUWeight, ::Type{T}) where {T <: Real} = ChebyshevUWeight{T}()\nsupport(μ::ChebyshevUWeight{T}) where {T} = ChebyshevInterval{T}()\nunsafe_weightfun(μ::ChebyshevUWeight, x) = chebyshev_weight_secondkind(x)\n\nweightfunction(μ::ChebyshevUWeight) = chebyshev_weight_secondkind\n\nBase.show(io::IO, μ::ChebyshevUWeight) = print(io, \"√(1+x)^2 dx  (ChebyshevU)\")\nDisplay.object_parentheses(μ::ChebyshevUWeight) = true\n\n\nconvert(::Type{JacobiWeight}, μ::LegendreWeight{T}) where {T} =\n    JacobiWeight{T}(0, 0)\nconvert(::Type{JacobiWeight}, μ::ChebyshevTWeight{T}) where {T} =\n    JacobiWeight{T}(-one(T)/2, -one(T)/2)\nconvert(::Type{JacobiWeight}, μ::ChebyshevUWeight{T}) where {T} =\n    JacobiWeight{T}(one(T)/2, one(T)/2)\n\nfunction convert(::Type{ChebyshevTWeight}, μ::JacobiWeight{T}) where {T}\n    (jacobi_α(μ) ≈ -one(T)/2 && jacobi_β(μ) ≈ -one(T)/2) || throw(InexactError(:convert, ChebyshevTWeight, μ))\n    ChebyshevTWeight{T}()\nend\n\nfunction convert(::Type{ChebyshevUWeight}, μ::JacobiWeight{T}) where {T}\n    (jacobi_α(μ) ≈ one(T)/2 && jacobi_β(μ) ≈ one(T)/2) || throw(InexactError(:convert, ChebyshevUWeight, μ))\n    ChebyshevUWeight{T}()\nend\n\nfunction convert(::Type{LegendreWeight}, μ::JacobiWeight{T}) where {T}\n    (μ.α ≈ 0 && μ.β ≈ 0) || throw(InexactError(:convert, LegendreWeight, μ))\n    LegendreWeight{T}()\nend\n\njacobi_α(μ::LegendreWeight{T}) where {T} = zero(T)\njacobi_β(μ::LegendreWeight{T}) where {T} = zero(T)\n\n==(μ1::AbstractJacobiWeight, μ2::LegendreWeight) =\n    jacobi_α(μ1) == jacobi_α(μ2) && jacobi_β(μ1) == jacobi_β(μ2)\n==(μ1::LegendreWeight, μ2::AbstractJacobiWeight) =\n    jacobi_α(μ1) == jacobi_α(μ2) && jacobi_β(μ1) == jacobi_β(μ2)\n\n\n\"The generalised Laguerre measure on the halfline `[0,∞)`.\"\nstruct LaguerreWeight{T} <: Weight{T}\n    α   ::  T\n\n    LaguerreWeight{T}(α = zero(T)) where {T} = new(α)\nend\nLaguerreWeight() = LaguerreWeight{Float64}()\nLaguerreWeight(α::T) where {T<:AbstractFloat} = LaguerreWeight{T}(α)\nLaguerreWeight(α) = LaguerreWeight(float(α))\n\nlaguerre_weightfun(x, α) = exp(-x) * x^α\n\nsimilar(μ::LaguerreWeight, ::Type{T}) where {T <: Real} = LaguerreWeight{T}(μ.α)\nsupport(μ::LaguerreWeight{T}) where {T} = HalfLine{T}()\nisnormalized(m::LaguerreWeight) = m.α == 0\n\nunsafe_weightfun(μ::LaguerreWeight, x) = laguerre_weightfun(x, μ.α)\n\nlaguerre_α(μ::LaguerreWeight) = μ.α\n\nBase.show(io::IO, μ::LaguerreWeight) =\n    laguerre_α(μ) == 0 ? print(io, \"exp(-x)dx  (Laguerre)\") : print(io, \"x^$(laguerre_α(μ))exp(-x)dx  (Laguerre)\")\nDisplay.object_parentheses(μ::LaguerreWeight) = true\n\n\n\"The Hermite measure with weight exp(-x^2) on the real line.\"\nstruct HermiteWeight{T} <: Weight{T}\nend\nHermiteWeight() = HermiteWeight{Float64}()\n\nhermite_weightfun(x) = exp(-x^2)\n\nsimilar(μ::HermiteWeight, ::Type{T}) where {T <: Real} = HermiteWeight{T}()\nunsafe_weightfun(μ::HermiteWeight, x) = hermite_weightfun(x)\n\nweightfunction(μ::HermiteWeight) = hermite_weightfun\n\nBase.show(io::IO, μ::HermiteWeight) = print(io, \"exp(-x^2)dx  (Hermite)\")\nDisplay.object_parentheses(μ::HermiteWeight) = true\n\n\n\"The Gaussian measure with weight exp(-|x|^2/2).\"\nstruct GaussianWeight{T} <: Weight{T}\nend\nGaussianWeight() = GaussianWeight{Float64}()\n\ngaussian_weightfun(x, ::Type{T} = prectype(x)) where {T} =\n    1/(2*convert(T, pi))^(length(x)/2) * exp(-norm(x)^2)\n\nsimilar(μ::GaussianWeight, ::Type{T}) where {T} = GaussianWeight{T}()\nisnormalized(μ::GaussianWeight) = true\nunsafe_weightfun(μ::GaussianWeight, x) = gaussian_weightfun(x, prectype(μ))\n\nBase.show(io::IO, μ::GaussianWeight{T}) where {T<:StaticTypes} =\n    print(io, \"1/(2π)^($(euclideandimension(T)/2)) exp(-|x|^2)dx  (Gauss)\")\nBase.show(io::IO, μ::GaussianWeight) = print(io, \"C(d) exp(-|x|^2)dx  (Gauss)\")\nDisplay.object_parentheses(μ::GaussianWeight) = true\n\n\n\n\"The Lebesgue measure associated with the given domain\"\nlebesguemeasure(domain::UnitInterval{T}) where {T} = LebesgueUnit{T}()\nlebesguemeasure(domain::ChebyshevInterval{T}) where {T} = LegendreWeight{T}()\nlebesguemeasure(domain::FullSpace{T}) where {T} = Lebesgue{T}()\nlebesguemeasure(domain::Domain{T}) where {T} = LebesgueDomain{T}(domain)\n\ndx(domain::Domain) = lebesguemeasure(domain)\n", "meta": {"hexsha": "088b9ee5420abc7114f8e96606687b45825cd353", "size": 9350, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/weights.jl", "max_stars_repo_name": "daanhb/DomainIntegrals.jl", "max_stars_repo_head_hexsha": "357fe662f549c1f02e18c67b7e15797a6b671aa1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/weights.jl", "max_issues_repo_name": "daanhb/DomainIntegrals.jl", "max_issues_repo_head_hexsha": "357fe662f549c1f02e18c67b7e15797a6b671aa1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/weights.jl", "max_forks_repo_name": "daanhb/DomainIntegrals.jl", "max_forks_repo_head_hexsha": "357fe662f549c1f02e18c67b7e15797a6b671aa1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5783972125, "max_line_length": 114, "alphanum_fraction": 0.6864171123, "num_tokens": 3280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.770474824043569}}
{"text": "# # [Sparse Identification with noisy data](@id noisy_sindy)\n#\n# Many real world data sources are corrupted with measurment noise, which can have \n# a big impact on the recovery of the underlying equations of motion. This example show how we can \n# use [`collocation`](@ref collocation) and [`batching`](@ref DataSampler) to perform SINDy in the presence of \n# noise. \n\nusing DataDrivenDiffEq\nusing LinearAlgebra\nusing ModelingToolkit\nusing OrdinaryDiffEq\n#md using Plots\n#md gr()\n\nfunction pendulum(u, p, t)\n    x = u[2]\n    y = -9.81sin(u[1]) - 0.3u[2]^3 -3.0*cos(u[1]) - 10.0*exp(-((t-5.0)/5.0)^2)\n    return [x;y]\nend\n\nu0 = [0.99π; -1.0]\ntspan = (0.0, 15.0)\nprob = ODEProblem(pendulum, u0, tspan)\nsol = solve(prob, Tsit5(), saveat = 0.01);\n\n# We add random noise to our measurements. \n\nX = sol[:,:] + 0.2 .* randn(size(sol));\nts = sol.t;\n\n#md plot(ts, X', color = :red)\n#md plot!(sol, color = :black)\n\n# To estimate the system, we first create a [`DataDrivenProblem`](@ref) via feeding in the measurement data.\n# Using a [Collocation](@ref) method, it automatically provides the derivative and smoothes the trajectory. Control signals can be passed\n# in as a function `(u,p,t)->control` or an array of measurements.\n\nprob = ContinuousDataDrivenProblem(X, ts, GaussianKernel() ,\n    U = (u,p,t)->[exp(-((t-5.0)/5.0)^2)], p = ones(2))\n\n#md plot(prob, size = (600,600))\n\n# Now we infer the system structure. First we define a [`Basis`](@ref) which collects all possible candidate terms.\n# Since we want to use SINDy, we call `solve` with an [`Optimizer`](@ref sparse_optimization), in this case [`STLSQ`](@ref) which iterates different sparsity thresholds\n# and returns a pareto optimal solution of the underlying [`sparse_regression!`](@ref). Note that we include the control signal in the basis as an additional variable `c`.\n\n@variables u[1:2] c[1:1]\n@parameters w[1:2]\nu = collect(u)\nc = collect(c)\nw = collect(w)\n\nh = Num[sin.(w[1].*u[1]);cos.(w[2].*u[1]); polynomial_basis(u, 5); c]\n\nbasis = Basis(h, u, parameters = w, controls = c)\n\n# To solve the problem, we also define a [`DataSampler`](@ref) which defines randomly shuffled minibatches of our data and selects the \n# best fit.\n\nsampler = DataSampler(Batcher(n = 5, shuffle = true, repeated = true))\nλs = exp10.(-10:0.1:-1)\nopt = STLSQ(λs)\nres = solve(prob, basis, opt, progress = false, sampler = sampler, denoise = false, normalize = false, maxiter = 5000)\nprintln(res) #hide\n\n# !!! info\n#     A more detailed description of the result can be printed via `print(res, Val{true})`, which also includes the discovered equations and parameter values.\n# \n# Where the resulting [`DataDrivenSolution`](@ref) stores information about the inferred model and the parameters:\n\nsystem = result(res)\nparams = parameters(res)\nprintln(system) #hide\nprintln(params) #hide\n\n# And a visual check of the result can be perfomed via plotting the result\n\n#md plot(\n#md     plot(prob), plot(res), layout = (1,2)\n#md )\n\n\n#md # ## [Copy-Pasteable Code](@id autoregulation_copy_paste)\n#md #\n#md # ```julia\n#md # @__CODE__\n#md # ```\n\n## Test #src\nfor r_ in [res] #src\n    @test all(aic(r_) .> 1e3) #src\n    @test all(determination(r_) .>= 0.9) #src\nend #src\n\n\n", "meta": {"hexsha": "17ee165eac93cd2ea99c78d01fb886f55c34c6cd", "size": 3197, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples/10_noisy_nonlinear.jl", "max_stars_repo_name": "AlCap23/DataDrivenDiffEq", "max_stars_repo_head_hexsha": "3be031060d5a3cad08473506be60108e572ac0fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-11-04T08:23:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-21T15:09:29.000Z", "max_issues_repo_path": "docs/examples/10_noisy_nonlinear.jl", "max_issues_repo_name": "AlCap23/DataDrivenDiffEq", "max_issues_repo_head_hexsha": "3be031060d5a3cad08473506be60108e572ac0fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-11-01T19:14:19.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-02T10:44:15.000Z", "max_forks_repo_path": "docs/examples/10_noisy_nonlinear.jl", "max_forks_repo_name": "AlCap23/DataDrivenDiffEq", "max_forks_repo_head_hexsha": "3be031060d5a3cad08473506be60108e572ac0fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3020833333, "max_line_length": 171, "alphanum_fraction": 0.6884579293, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7704748145144903}}
{"text": "#===============================================================================\n\nThe radical of n, rad(n), is the product of distinct prime factors of n. For\nexample, 504 = 2^3 × 3^2 × 7, so rad(504) = 2 × 3 × 7 = 42.\n\nWe shall define the triplet of positive integers (a, b, c) to be an abc-hit if:\n\n    gcd(a, b) = gcd(a, c) = gcd(b, c) = 1\n    a < b\n    a + b = c\n    rad(abc) < c\n\nFor example, (5, 27, 32) is an abc-hit, because:\n\n    gcd(5, 27) = gcd(5, 32) = gcd(27, 32) = 1\n    5 < 27\n    5 + 27 = 32\n    rad(4320) = 30 < 32\n\nIt turns out that abc-hits are quite rare and there are only thirty-one abc-hits\nfor c < 1000, with ∑c = 12523.\n\nFind ∑c for c < 120000.\n\n--------------------------------------------------------------------------------\n\nAnalyse\n-------\n\n1) a < b; a + b = c < bound\n    a)  ⇒ 2a < a + b = c < bound - 1 ⇒ 1 ≤ a < bound ÷ 2\n    b)  ⇒ b < bound - a\n\n2) if a and b are coprime, then c = a+b is coprime with a and with b\n    => gcd(a, b) = 1 ⇒ gcd(a, c) = gcd(b, c) = 1\n\n3) gcd(a, b) == 1 ⇔ gcd(rad(a), rad(b)) == 1\n\n4) if a and b are coprime, the rad(ab) = rad(a) rad(b)\n\n5) rad(n) = 1 if n = 1\n          ≥ 2 if n > 1\n\n6) So the conditions can be simplifed to\n        gcd(a, b) = 1\n        1 ≤ a < bound ÷ 2\n        a < b < bound - a\n        c = a + b\n        rad(a) rad(b) rad(c) < c\n\n7) Precomputing rad(n) for all n in 2..bound-2\n\n\ncase a=1\n--------\n    gcd(1,b) = 1 is granted\n    2 ≤ b ≤ bound-2\n    c = 1+b\n    rad(b) rad(c) < c ⇒ rad(b) < (1+b) ÷ 2\n                      ⇒ rad(b) rad(1+b) < 1+b\n\n    Therefore the constraints are:\n        1 < b < bound-1\n        c = b+1\n        rad(b) rad(b+1) < (b+1)\n\n\ncase a>1\n--------\n    a < b => a+1 ≤ b,\n    2a+1 ≤ a + b = c < bound => a < (bound-1)÷2\n                             => a ≤ (bound-1)÷2 -1\n    rad(a) ≥ 2, rad(b) ≥ 2, rad(c) ≥ 2\n    rad(a) rad(b) rad(a+b) < a+b ⇒ rad(a) < c ÷ 4\n                                 ⇒ rad(b) < c ÷ (2 rad(a))\n\n    Therefore the constraints are:\n        2   ≤ a ≤ (bound-1)÷2 -1\n        a+1 ≤ b ≤ bound - 1 - a\n        gcd(a,b) = 1\n        c = a + b\n        rad(a) < c ÷ 4                  < (bound-1) ÷ 4\n        rad(b) < c ÷ (2 rad(a))         < (bound-1) ÷ 4\n        rad(c) < c ÷ (rad(a) rad(b))    < (bound-1) ÷ 4\n\n\nConclusion\n==========\n\nThe principle behind the algorithm is to precompute rad(n) for 2 ≤ n ≤ bound-, and to proceed to all possible tests before computing gcd(rad(a), rad(b)).\n\nNote that precomputing gcd(rad(a), rad(b)) for all possible a and b is not efficient.\n\n===============================================================================#\n\nimport Primes\n\n\nfunction euler(bound::Int)\n    #precimpute the radicals\n    rad = Array{Int}(bound-1)\n    for n in 1:bound-1\n        rad[n]=prod(keys(Primes.factor(n)))\n    end\n\n    res::Int = 0\n\n    # case a=1\n    for b in 2:bound-2\n        c=b+1\n        if (rad[b]*rad[c] < c) res+=c end\n    end\n\n    # case a>1\n    for a in 2:(bound-1) ÷ 2 -1\n        rad_a = rad[a]\n        if (rad_a ≥ (bound-1) ÷ 4) continue end\n\n        for b in a+1:bound-1-a\n            rad_b = rad[b]\n            c=a+b\n            if (rad_a * rad_b * rad[c] ≥ c) continue end\n            if (gcd(rad_a, rad_b) == 1) res += c end\n        end\n    end\n\n    res\nend\n\nprintln(\"  1_000: $(euler(  1_000))\")\n@time println(\"120_000: $(euler(120_000))\")\n", "meta": {"hexsha": "993bfc17fd331fe7225a94fd23479e17d156ca82", "size": 3305, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0127.jl", "max_stars_repo_name": "dpieroux/euler", "max_stars_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "0127.jl", "max_issues_repo_name": "dpieroux/euler", "max_issues_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0127.jl", "max_forks_repo_name": "dpieroux/euler", "max_forks_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0378787879, "max_line_length": 153, "alphanum_fraction": 0.4429652042, "num_tokens": 1204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7704492275665576}}
{"text": "if VERSION >= v\"0.6.0-\"\n    using SpecialFunctions: besseli\nend\n\n# This file contains different window functions.\n# The function getWindow returns a pair of window functions based on a string\n\nfunction getWindow(window::Symbol)\n    if window == :gauss\n        return window_gauss, window_gauss_hat\n    elseif window == :spline\n        return window_spline, window_spline_hat\n    elseif window == :kaiser_bessel_rev\n        return window_kaiser_bessel_rev, window_kaiser_bessel_rev_hat\n    else # default to kaiser_bessel\n        return window_kaiser_bessel, window_kaiser_bessel_hat\n    end\nend\n\nfunction window_kaiser_bessel(x,n,m,sigma)\n    b = pi*(2-1/sigma)\n    arg = m^2-n^2*x^2\n    if abs(x) < m/n\n        y = sinh(b*sqrt(arg))/sqrt(arg)/pi\n    elseif abs(x) > m/n\n        y = zero(x)\n    else\n        y = b/pi\n    end\n    return y\nend\n\nfunction window_kaiser_bessel_hat(k,n,m,sigma)\n    b = pi*(2-1/sigma)\n    return besseli(0,m*sqrt(b^2-(2*pi*k/n)^2))\nend\n\nfunction window_kaiser_bessel_rev(x,n,m,sigma)\n    b = pi*(2-1/sigma)\n    if abs(x) < m/n\n        arg = m*b*sqrt(1-(n*x/m)^2)\n        y = 0.5/m*besseli(0,arg)\n    else\n        y = zero(x)\n    end\n    return y\nend\n\nfunction window_kaiser_bessel_rev_hat(k,n,m,sigma)\n    b = pi*(2-1/sigma)\n\n    arg = sqrt(complex((2*pi*m*k/n)^2-(m*b)^2))\n    return sinc(arg/pi)\nend\n\n\nfunction window_gauss(x,n,m,sigma)\n    b = m / pi\n    if abs(x) < m/n\n        y = 1 / sqrt(pi*b) * exp(-(n*x)^2 / b)\n    else\n        y =  zero(x)\n    end\n    return y\nend\n\nfunction window_gauss_hat(k,n,m,sigma)\n    b = m / pi\n    return exp(-(pi*k/(n))^2 * b)\nend\n\nfunction cbspline(m,x)\n    if m == 1\n        if x>=0 && x<1\n            y = one(x)\n        else\n            y = zero(x)\n        end\n    else\n        y = x/(m-1)*cbspline(m-1,x) + (m-x)/(m-1)*cbspline(m-1,x-1)\n    end\n    return y\nend\n\nfunction window_spline(x,n,m,sigma)\n    if abs(x) < m/n\n        y = cbspline(2*m, n*x+m)\n    else\n        y = zero(x)\n    end\n    return y\nend\n\nfunction window_spline_hat(k,n,m,sigma)\n    return (sinc(k/n))^(2*m)\nend\n", "meta": {"hexsha": "985220b6ab3b0d33e7f3d1f0241c8ab20ba06cc1", "size": 2050, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/windowFunctions.jl", "max_stars_repo_name": "tknopp/NFFT.jl", "max_stars_repo_head_hexsha": "a01b37c5662b6f214a1d63e42f9efe86cf2de38f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2015-06-23T06:43:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T00:35:44.000Z", "max_issues_repo_path": "src/windowFunctions.jl", "max_issues_repo_name": "tknopp/NFFT.jl", "max_issues_repo_head_hexsha": "a01b37c5662b6f214a1d63e42f9efe86cf2de38f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 53, "max_issues_repo_issues_event_min_datetime": "2015-08-24T10:06:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T13:43:47.000Z", "max_forks_repo_path": "src/windowFunctions.jl", "max_forks_repo_name": "tknopp/NFFT.jl", "max_forks_repo_head_hexsha": "a01b37c5662b6f214a1d63e42f9efe86cf2de38f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2015-03-30T16:23:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T09:19:05.000Z", "avg_line_length": 21.1340206186, "max_line_length": 77, "alphanum_fraction": 0.5887804878, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7704492262901781}}
{"text": "\nd=2;\nA=Array{Int64,3}(d,d,d); B=Array{Int64,3}(d,d,d); C=zeros(Int64,d,d)\nfor i in 1:d,j in 1:d,k in 1:d\n    A[i,j,k] = 2i+j^2-k^3\n    B[i,j,k] = i+2j+4k\nend\n\ntic()\nfor i in 1:size(A,1)\n    for j in 1:size(A,3)\n        for k in 1:size(A,1)\n            for n in 1:size(B,3)\n                C[j,n] += A[i,j,k]*B[k,i,n]\n            end\n        end\n    end\nend\ntoc()\nprint(\"Matrix C is \", C)\n\nA_permuted = permutedims(A,[2,1,3]); B_permuted = permutedims(B,[2,1,3]);\nA_reshaped = reshape(A_permuted,2,4); B_reshaped = reshape(B_permuted,4,2);\ntic()\nC_reshaped = A_reshaped*B_reshaped;\ntoc()\nprint(\"Matrix C is \", C_reshaped)\n\nA=rand(Int64,100,100,100); B=rand(Int64,100,100,100); \nC=zeros(Int64,100,100);\n\ntic()\nfor i in 1:size(A,1)\n    for j in 1:size(A,3)\n        for k in 1:size(A,1)\n            for n in 1:size(B,3)\n                C[j,n] += A[i,j,k]*B[k,i,n]\n            end\n        end\n    end\nend\ntoc()\n\nA_reshaped=reshape(permutedims(A,[2,1,3]),100,10000); \nB_reshaped=reshape(permutedims(B,[2,1,3]),10000,100);\ntic()\nC_reshaped = A_reshaped*B_reshaped;\ntoc()\n\nX=Complex{Float64}[0.0 1.0;1.0 0.0]; \nY=Complex{Float64}[0.0im -1.0im;1.0im 0.0im]; \nZ=Complex{Float64}[1.0 0.0;0.0 -1.0];\nh=kron(X,X)+kron(Y,Y)+kron(Z,Z);\nN=4; C=2; d=2;\nH=zeros(Complex{Float64},d^N,d^N);\n\nfor l in 0:N-C\n    H+=kron(kron(eye(d^l),h),eye(d^(N-C-l)))\nend\nE,V = eig(H)\nprint(\"The first eigenvalues are: \", E[1:11])\n\nfunction diagonalization_model(h::Matrix{T},N::Int64;C::Int64=2,\n        d::Int64=2,method_sparse::Bool=true) where {T}\n    H=zeros(T,d^N,d^N)\n    for l in 0:N-C\n        H+=kron(kron(eye(d^l),h),eye(d^(N-C-l),d^(N-C-l)))\n    end\n    if method_sparse\n        E,V = eigs(H;nev=10,which=:SR)\n    else\n        E,V = eig(H)\n    end\n    return E\nend\n\n@time diagonalization_model(h,12)\n\n@time diagonalization_model(h,12,method_sparse=false)\n\nfunction permR2(i::Int64,P::Int64)\n    return mod.(collect(1:P)+i-2,P)+1\nend\n\nfunction permL2(i::Int64,P::Int64)\n    return mod.(collect(1:P)-i,P)+1\nend\n\nfunction H_wavefunction(h_tilde::Matrix{T},phi::Array{T,P},N::Int64;\n        OBC::Int64=1,d::Int64=2,C::Int64=2) where {T,P}\n    H_phi = zeros(T,fill(d,C+1)...,d^(N-C-1))\n    for i in 1:N-OBC\n        if N == 1\n            phi = permutedims(phi,permR2(1,P))\n            H_phi = permutedims(H_phi,permR2(1,P))\n            phi_tmp = h_tilde*reshape(phi,d^C,d^(N-C))\n            phi_tmp = reshape(phi_tmp,fill(d,C+1)...,d^(N-C-1))\n            H_phi = reshape(H_phi,fill(d,C+1)...,d^(N-C-1))\n            H_phi += phi_tmp\n        else\n            phi = permutedims(phi,permR2(2,P))\n            H_phi = permutedims(H_phi,permR2(2,P))\n            phi_tmp = h_tilde*reshape(phi,d^C,d^(N-C))\n            phi_tmp = reshape(phi_tmp,fill(d,C+1)...,d^(N-C-1))\n            H_phi = reshape(H_phi,fill(d,C+1)...,d^(N-C-1))\n            phi = reshape(phi,fill(d,C+1)...,d^(N-C-1))\n            H_phi += phi_tmp\n        end\n    end\n    if OBC == 1\n        return(reshape(permutedims(H_phi,permR2(2,P)),d^N))\n    elseif OBC == 0\n        return(reshape(H_phi,d^N))\n    end\nend\n\nfunction power_method(h::Matrix{T},N::Int64;OBC::Int64=1,d::Int64=2,\n        C::Int64=2,tol::Float64=1e-4) where {T}\n    #phi = rand(T,fill(d,C+1)...,d^(N-C-1))\n    #phi = collect(Complex{Float64},1:2^N)\n    phi = rand(T,d^N)\n    phi = phi/sqrt(dot(conj(phi),phi))\n    phi = reshape(phi,fill(d,C+1)...,d^(N-C-1))\n    list_E_tmp = []\n    E,V = eig(h)\n    alpha=max(E...)\n    h_tilde = h - alpha*kron(eye(d),eye(d))\n    i = 1\n    bool = true\n    while bool\n        H_phi = H_wavefunction(h_tilde,phi,N,OBC=OBC)\n        #H_phi = H_phi/dot(conj(H_phi),H_phi)\n        phi = reshape(phi,d^N)\n        #E = dot(conj(phi),H_phi)/dot(conj(phi),phi) + α*(N-OBC)\n        E = dot(conj(phi),H_phi) + alpha*(N-OBC)\n        #println(\"E = \", E)\n        push!(list_E_tmp,E)\n        if i>2 && abs(list_E_tmp[i]-list_E_tmp[i-1])<tol\n           bool = false\n           println(\"Desired precision reached!\")\n        end\n        i+=1\n        phi = reshape(phi,fill(d,C+1)...,d^(N-C-1))\n        phi = reshape(H_phi/sqrt(dot(conj(H_phi),H_phi)),fill(d,C+1)...,d^(N-C-1))\n    end\n    println(\"E = \",E)\n    println(\"Number of iterations = \", i)\nend\n\n@time power_method(h,4,tol=1e-9)\n\n@time power_method(h,12,tol=1e-9)\n\n@time power_method(h,16,OBC=0,tol=1e-9)\n\n@time power_method(h,16,tol=1e-9)\n\n@time power_method(h,25)\n\n@time power_method(h,25,OBC=0)\n", "meta": {"hexsha": "f3dbd535633e99faa82c7b0a3554a4d1d21ac778", "size": 4366, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "doc/LatexDocumentation/Tensor_network_homework_1.jl", "max_stars_repo_name": "oliviersimard/SuperStiff", "max_stars_repo_head_hexsha": "3dd08456bd0baeed1df7a68413abfa6b64a33484", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/LatexDocumentation/Tensor_network_homework_1.jl", "max_issues_repo_name": "oliviersimard/SuperStiff", "max_issues_repo_head_hexsha": "3dd08456bd0baeed1df7a68413abfa6b64a33484", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/LatexDocumentation/Tensor_network_homework_1.jl", "max_forks_repo_name": "oliviersimard/SuperStiff", "max_forks_repo_head_hexsha": "3dd08456bd0baeed1df7a68413abfa6b64a33484", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1180124224, "max_line_length": 82, "alphanum_fraction": 0.5611543747, "num_tokens": 1668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305638, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7704492252589225}}
{"text": "@doc \"\"\"\n  Splits a floating-point number `a` into two parts `a = h + l` such that the\n  halves `h` and `l` are non-overlapping and `|x| ≥ |y|`. That is, both halves\n  have at most `s-1` nonzero bits, where `s = ceil(p/2)` and `p` is the\n  precision (`p = 24` for `Float32` and `p = 53` for `Float64`).\n\n  References:\n\n    * T.J. Dekker, A floating-point technique for extending the available\n      precision, Numerische Mathematik 18, pp. 224–242, 1971.\n  \"\"\" ->\n# TODO: Extend the definition to floating-point arrays\nfor T in (Float32, Float64)\n  @eval begin\n    function fsplit(a::$T)\n      # Float32: factor = 2^12 + 1 = 4097\n      # Float64: factor = 2^27 + 1 = 134217729\n      f = $(convert(T, 2^ceil(precision(T)/2)+1));\n      c = a * f\n      h = c - (c-a)\n      l = a - h\n      h, l\n    end\n  end\nend\n\n\n@doc \"\"\"\n  Computes the error-free multiplication `a * b = x + y`, where `x = fl(a * b)`,\n  for floating-point numbers `a` and `b`. This algorithm uses all cross products\n  between the halves generated by `fsplit` from `a` and `b`. It requires 17\n  flops.\n\n  References:\n\n    * T.J. Dekker, A floating-point technique for extending the available\n      precision, Numerische Mathematik 18, pp. 224–242, 1971.\n  \"\"\" ->\n# TODO: Extend the definition to floating-point arrays\nfunction err_mul{T<:IEEE754}(a::T, b::T)\n  x = a * b\n  ah, al = fsplit(a)\n  bh, bl = fsplit(b)\n  y = al*bl - (((x - ah*bh) - al*bh) - ah*bl)\n  x, y\nend\n\n\n@doc \"\"\"\n  Computes the error-free transformation `a * b = x + y`, where `x = fl(a * b)`,\n  for floating-point numbers `a` and `b`. By using the fused multiply-add (FMA)\n  operation, it only requires 2 flops instead of the 17 flops required by\n  `err_mul` but the improvement in execution time typically a less than that.\n\n  References:\n\n    * T. Ogita, S.M. Rump, and S. Oishi, Accurate sum and dot product, SIAM\n      Journal on Scientific Computing 26, pp. 1955–1988, 2005.\n  \"\"\" ->\n# TODO: Extend the definition to floating-point arrays\nfunction err_fast_mul{T<:IEEE754}(a::T, b::T)\n  x = a * b\n  y = fma(a, b, -x)\n  x, y\nend\n", "meta": {"hexsha": "75f59d34d82614f57e5eb1a0edddf5deebc35e12", "size": 2067, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mul.jl", "max_stars_repo_name": "JuliaPackageMirrors/ErrorFreeTransforms.jl", "max_stars_repo_head_hexsha": "8404370db86c85f150469ec36259bce33103bb51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mul.jl", "max_issues_repo_name": "JuliaPackageMirrors/ErrorFreeTransforms.jl", "max_issues_repo_head_hexsha": "8404370db86c85f150469ec36259bce33103bb51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-11-25T13:03:27.000Z", "max_issues_repo_issues_event_max_datetime": "2015-11-25T15:42:28.000Z", "max_forks_repo_path": "src/mul.jl", "max_forks_repo_name": "JuliaPackageMirrors/ErrorFreeTransforms.jl", "max_forks_repo_head_hexsha": "8404370db86c85f150469ec36259bce33103bb51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:13:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:13:42.000Z", "avg_line_length": 31.3181818182, "max_line_length": 80, "alphanum_fraction": 0.6274794388, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7704492237374186}}
{"text": "\nusing Turing\nusing DifferentialEquations\n\n# Load StatsPlots for visualizations and diagnostics.\nusing StatsPlots\n\nusing LinearAlgebra\n\n# Set a seed for reproducibility.\nusing Random\nRandom.seed!(14);\n\n\n# Define Lotka-Volterra model.\nfunction lotka_volterra(du, u, p, t)\n    # Model parameters.\n    α, β, γ, δ = p\n    # Current state.\n    x, y = u\n\n    # Evaluate differential equations.\n    du[1] = (α - β * y) * x # prey\n    du[2] = (δ * x - γ) * y # predator\n\n    return nothing\nend\n\n# Define initial-value problem.\nu0 = [1.0, 1.0]\np = [1.5, 1.0, 3.0, 1.0]\ntspan = (0.0, 10.0)\nprob = ODEProblem(lotka_volterra, u0, tspan, p)\n\n# Plot simulation.\nplot(solve(prob, Tsit5()))\n\n\nsol = solve(prob, Tsit5(); saveat=0.1)\nodedata = Array(sol) + 0.8 * randn(size(Array(sol)))\n\n# Plot simulation and noisy observations.\nplot(sol; alpha=0.3)\nscatter!(sol.t, odedata'; color=[1 2], label=\"\")\n\n\n@model function fitlv(data, prob)\n    # Prior distributions.\n    σ ~ InverseGamma(2, 3)\n    α ~ truncated(Normal(1.5, 0.5), 0.5, 2.5)\n    β ~ truncated(Normal(1.2, 0.5), 0, 2)\n    γ ~ truncated(Normal(3.0, 0.5), 1, 4)\n    δ ~ truncated(Normal(1.0, 0.5), 0, 2)\n\n    # Simulate Lotka-Volterra model. \n    p = [α, β, γ, δ]\n    predicted = solve(prob, Tsit5(); p=p, saveat=0.1)\n\n    # Observations.\n    for i in 1:length(predicted)\n        data[:, i] ~ MvNormal(predicted[i], σ^2 * I)\n    end\n\n    return nothing\nend\n\nmodel = fitlv(odedata, prob)\n\n# Sample 3 independent chains with forward-mode automatic differentiation (the default).\nchain = sample(model, NUTS(0.65), MCMCSerial(), 1000, 3; progress=false)\n\n\nplot(chain)\n\n\nplot(; legend=false)\nposterior_samples = sample(chain[[:α, :β, :γ, :δ]], 300; replace=false)\nfor p in eachrow(Array(posterior_samples))\n    sol_p = solve(prob, Tsit5(); p=p, saveat=0.1)\n    plot!(sol_p; alpha=0.1, color=\"#BBBBBB\")\nend\n\n# Plot simulation and noisy observations.\nplot!(sol; color=[1 2], linewidth=1)\nscatter!(sol.t, odedata'; color=[1 2])\n\n\n@model function fitlv2(data::AbstractVector, prob)\n    # Prior distributions.\n    σ ~ InverseGamma(2, 3)\n    α ~ truncated(Normal(1.5, 0.5), 0.5, 2.5)\n    β ~ truncated(Normal(1.2, 0.5), 0, 2)\n    γ ~ truncated(Normal(3.0, 0.5), 1, 4)\n    δ ~ truncated(Normal(1.0, 0.5), 0, 2)\n\n    # Simulate Lotka-Volterra model but save only the second state of the system (predators).\n    p = [α, β, γ, δ]\n    predicted = solve(prob, Tsit5(); p=p, saveat=0.1, save_idxs=2)\n\n    # Observations of the predators.\n    data ~ MvNormal(predicted.u, σ^2 * I)\n\n    return nothing\nend\n\nmodel2 = fitlv2(odedata[2, :], prob)\n\n# Sample 3 independent chains.\nchain2 = sample(model2, NUTS(0.45), MCMCSerial(), 5000, 3; progress=false)\n\n\nplot(; legend=false)\nposterior_samples = sample(chain2[[:α, :β, :γ, :δ]], 300; replace=false)\nfor p in eachrow(Array(posterior_samples))\n    sol_p = solve(prob, Tsit5(); p=p, saveat=0.1)\n    plot!(sol_p; alpha=0.1, color=\"#BBBBBB\")\nend\n\n# Plot simulation and noisy observations.\nplot!(sol; color=[1 2], linewidth=1)\nscatter!(sol.t, odedata'; color=[1 2])\n\n\nfunction delay_lotka_volterra(du, u, h, p, t)\n    # Model parameters.\n    α, β, γ, δ = p\n\n    # Current state.\n    x, y = u\n    # Evaluate differential equations\n    du[1] = α * h(p, t - 1; idxs=1) - β * x * y\n    du[2] = -γ * y + δ * x * y\n\n    return nothing\nend\n\n# Define initial-value problem.\np = (1.5, 1.0, 3.0, 1.0)\nu0 = [1.0; 1.0]\ntspan = (0.0, 10.0)\nh(p, t; idxs::Int) = 1.0\nprob_dde = DDEProblem(delay_lotka_volterra, u0, h, tspan, p);\n\n\nsol_dde = solve(prob_dde; saveat=0.1)\nddedata = Array(sol_dde) + 0.5 * randn(size(sol_dde))\n\n# Plot simulation and noisy observations.\nplot(sol_dde)\nscatter!(sol_dde.t, ddedata'; color=[1 2], label=\"\")\n\n\n@model function fitlv_dde(data, prob)\n    # Prior distributions.\n    σ ~ InverseGamma(2, 3)\n    α ~ Truncated(Normal(1.5, 0.5), 0.5, 2.5)\n    β ~ Truncated(Normal(1.2, 0.5), 0, 2)\n    γ ~ Truncated(Normal(3.0, 0.5), 1, 4)\n    δ ~ Truncated(Normal(1.0, 0.5), 0, 2)\n\n    # Simulate Lotka-Volterra model.\n    p = [α, β, γ, δ]\n    predicted = solve(prob, MethodOfSteps(Tsit5()); p=p, saveat=0.1)\n\n    # Observations.\n    for i in 1:length(predicted)\n        data[:, i] ~ MvNormal(predicted[i], σ^2 * I)\n    end\nend\n\nmodel_dde = fitlv_dde(ddedata, prob_dde)\n\n# Sample 3 independent chains.\nchain_dde = sample(model_dde, NUTS(0.65), MCMCSerial(), 300, 3; progress=false)\n\n\nplot(chain_dde)\n\n\nplot(; legend=false)\nposterior_samples = sample(chain_dde[[:α, :β, :γ, :δ]], 300; replace=false)\nfor p in eachrow(Array(posterior_samples))\n    sol_p = solve(prob_dde, MethodOfSteps(Tsit5()); p=p, saveat=0.1)\n    plot!(sol_p; alpha=0.1, color=\"#BBBBBB\")\nend\n\n# Plot simulation and noisy observations.\nplot!(sol_dde; color=[1 2], linewidth=1)\nscatter!(sol_dde.t, ddedata'; color=[1 2])\n\n\nusing Zygote, DiffEqSensitivity\n\n# Sample a single chain with 1000 samples using Zygote.\nsetadbackend(:zygote)\nsample(model, NUTS(0.65), 1000; progress=false)\n\n\n@model function fitlv_sensealg(data, prob)\n    # Prior distributions.\n    σ ~ InverseGamma(2, 3)\n    α ~ truncated(Normal(1.5, 0.5), 0.5, 2.5)\n    β ~ truncated(Normal(1.2, 0.5), 0, 2)\n    γ ~ truncated(Normal(3.0, 0.5), 1, 4)\n    δ ~ truncated(Normal(1.0, 0.5), 0, 2)\n\n    # Simulate Lotka-Volterra model and use a specific algorithm for computing sensitivities.\n    p = [α, β, γ, δ]\n    predicted = solve(\n        prob;\n        p=p,\n        saveat=0.1,\n        sensealg=InterpolatingAdjoint(; autojacvec=ReverseDiffVJP(true)),\n    )\n\n    # Observations.\n    for i in 1:length(predicted)\n        data[:, i] ~ MvNormal(predicted[i], σ^2 * I)\n    end\n\n    return nothing\nend;\n\nmodel_sensealg = fitlv_sensealg(odedata, prob)\n\n# Sample a single chain with 1000 samples using Zygote.\nsetadbackend(:zygote)\nsample(model_sensealg, NUTS(0.65), 1000; progress=false)\n\n\nu0 = [1.0, 1.0]\ntspan = (0.0, 10.0)\nfunction multiplicative_noise!(du, u, p, t)\n    x, y = u\n    du[1] = p[5] * x\n    return du[2] = p[6] * y\nend\np = [1.5, 1.0, 3.0, 1.0, 0.1, 0.1]\n\nfunction lotka_volterra!(du, u, p, t)\n    x, y = u\n    α, β, γ, δ = p\n    du[1] = dx = α * x - β * x * y\n    return du[2] = dy = δ * x * y - γ * y\nend\n\nprob_sde = SDEProblem(lotka_volterra!, multiplicative_noise!, u0, tspan, p)\n\nensembleprob = EnsembleProblem(prob_sde)\ndata = solve(ensembleprob, SOSRI(); saveat=0.1, trajectories=1000)\nplot(EnsembleSummary(data))\n\n\n@model function fitlv_sde(data, prob)\n    # Prior distributions.\n    σ ~ InverseGamma(2, 3)\n    α ~ truncated(Normal(1.3, 0.5), 0.5, 2.5)\n    β ~ truncated(Normal(1.2, 0.25), 0.5, 2)\n    γ ~ truncated(Normal(3.2, 0.25), 2.2, 4.0)\n    δ ~ truncated(Normal(1.2, 0.25), 0.5, 2.0)\n    ϕ1 ~ truncated(Normal(0.12, 0.3), 0.05, 0.25)\n    ϕ2 ~ truncated(Normal(0.12, 0.3), 0.05, 0.25)\n\n    # Simulate stochastic Lotka-Volterra model.\n    p = [α, β, γ, δ, ϕ1, ϕ2]\n    predicted = solve(prob, SOSRI(); p=p, saveat=0.1)\n\n    # Early exit if simulation could not be computed successfully.\n    if predicted.retcode !== :Success\n        Turing.@addlogprob! -Inf\n        return nothing\n    end\n\n    # Observations.\n    for i in 1:length(predicted)\n        data[:, i] ~ MvNormal(predicted[i], σ^2 * I)\n    end\n\n    return nothing\nend;\n\n\nmodel_sde = fitlv_sde(odedata, prob_sde)\n\nsetadbackend(:forwarddiff)\nchain_sde = sample(\n    model_sde,\n    NUTS(0.25),\n    5000;\n    init_params=[1.5, 1.3, 1.2, 2.7, 1.2, 0.12, 0.12],\n    progress=false,\n)\nplot(chain_sde)\n\n", "meta": {"hexsha": "481107a0ca113a801cb366e455d709ae2eb5f7b5", "size": 7370, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/10-bayesian-differential-equations/10_bayesian-differential-equations.jl", "max_stars_repo_name": "TuringLang/TuringTutorialsOutput", "max_stars_repo_head_hexsha": "0928cc205032f4b117b5d1dd1512b1621fb5674a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/10-bayesian-differential-equations/10_bayesian-differential-equations.jl", "max_issues_repo_name": "TuringLang/TuringTutorialsOutput", "max_issues_repo_head_hexsha": "0928cc205032f4b117b5d1dd1512b1621fb5674a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/10-bayesian-differential-equations/10_bayesian-differential-equations.jl", "max_forks_repo_name": "TuringLang/TuringTutorialsOutput", "max_forks_repo_head_hexsha": "0928cc205032f4b117b5d1dd1512b1621fb5674a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9830508475, "max_line_length": 93, "alphanum_fraction": 0.6313432836, "num_tokens": 2724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7704492184346458}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.19\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nfunction prn(lambda)\n    k, p = 0, 1\n    while p > MathConstants.e^(-lambda)\n        k += 1\n        p *= rand()\n    end\n    return k-1\nend\n\n# ╔═╡ 0cbc946e-2164-11eb-1b0c-7d4c7a607b1e\nbegin\n\txGrid, lambda, N = 0:16, 5.5, 10^6\n\n\tpDist = Poisson(lambda)\n\tbPmf = pdf.(pDist,xGrid)\n\tdata = counts([prn(lambda) for _ in 1:N],xGrid)/N\nend\n\n# ╔═╡ 0cbcbdf2-2164-11eb-193d-2baa8a6bce0b\nbegin\n\tplot( xGrid, data, \n\t\tline=:stem, marker=:circle, \n\t\tc=:blue, ms=10, msw=0, lw=4, label=\"MC estimate\")\n\tplot!( xGrid, bPmf, line=:stem, \n\t\tmarker=:xcross, c=:red, ms=6, msw=0, lw=2, label=\"PMF\",\n\t\tylims=(0,0.2), xlabel=\"x\", ylabel=\"Probability of x events\")\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.19\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═0cbc946e-2164-11eb-1b0c-7d4c7a607b1e\n# ╠═0cbcbdf2-2164-11eb-193d-2baa8a6bce0b\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "773ed9bcdbf2d0bd0d94243a7f30b0724b8df3f4", "size": 1454, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.19.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.19.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.19.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 24.2333333333, "max_line_length": 62, "alphanum_fraction": 0.689133425, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7704492116103687}}
{"text": "\"\"\"\n    forwardsub(L,b)\n\nSolve the lower-triangular linear system with matrix `L` and right-hand side\nvector `b`.\n\"\"\"\nfunction forwardsub(L,b)\n\nn = size(L,1)\nx = zeros(n)\nfor i = 1:n\n    s = i > 1 ? sum( L[i,j]*x[j] for j=1:i-1 ) : 0\n    x[i] = ( b[i] - s ) / L[i,i]\nend\n\nreturn x\nend\n\n\"\"\"\n    backsub(U,b)\n\nSolve the upper-triangular linear system with matrix `U` and right-hand side\nvector `b`.\n\"\"\"\nfunction backsub(U,b)\n\nn = size(U,1)\nx = zeros(n)\nfor i = n:-1:1\n    s = i < n ? sum( U[i,j]*x[j] for j=i+1:n ) : 0\n    x[i] = ( b[i] - s ) / U[i,i]\nend\n\nreturn x\nend\n\n\"\"\"\n    lufact(A)\n\nCompute the LU factorization of square matrix `A`, returning the factors.\n\"\"\"\nfunction lufact(A)\n\nn = size(A,1)\nL = Matrix(Diagonal(ones(n)))    # puts ones on diagonal\nU = copy(A)\n\n# Gaussian elimination\nfor j = 1:n-1\n  for i = j+1:n\n    L[i,j] = U[i,j] / U[j,j]   # row multiplier\n    U[i,j:n] = U[i,j:n] - L[i,j]*U[j,j:n]\n  end\nend\n\nreturn L,triu(U)\nend\n", "meta": {"hexsha": "0703eac34635083e1a2848d26d4c6c850dab2b6c", "size": 945, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/functions/chapter02.jl", "max_stars_repo_name": "snowdj/fnc-extras", "max_stars_repo_head_hexsha": "ef51fada748de1326a4ce645fbcb0c2499cb2b8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 109, "max_stars_repo_stars_event_min_datetime": "2018-04-21T09:02:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T19:03:54.000Z", "max_issues_repo_path": "julia/functions/chapter02.jl", "max_issues_repo_name": "snowdj/fnc-extras", "max_issues_repo_head_hexsha": "ef51fada748de1326a4ce645fbcb0c2499cb2b8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-12-04T22:17:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T21:04:47.000Z", "max_forks_repo_path": "julia/functions/chapter02.jl", "max_forks_repo_name": "snowdj/fnc-extras", "max_forks_repo_head_hexsha": "ef51fada748de1326a4ce645fbcb0c2499cb2b8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2017-04-02T17:21:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T17:19:57.000Z", "avg_line_length": 16.2931034483, "max_line_length": 76, "alphanum_fraction": 0.5714285714, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7703903844810681}}
{"text": "using Pkg\nusing Plots\nusing DataFrames\npyplot()\n\n### functions for simulations\nfunction calc_new_state(y::AbstractArray,\n    a::Dict, \n    b::Dict, \n    l::Dict;\n    from::Float64=0.01)\n    if length(y)==0\n        y = [from]\n    end\n    y[end]+(1-y[end])*(a[\"walk\"]*(1-exp(-b[\"walk\"]*l[\"walk\"]*a[\"walk\"]*y[end]))+a[\"TTC\"]*(1-exp(-b[\"TTC\"]*l[\"TTC\"]*a[\"TTC\"]*y[end])))\nend\n\nfunction simul(s::Dict,\n               b::Dict, \n               l::Dict;\n               to_perc::Bool=true,\n               from::Float64=0.01,\n               to::Union{Float64, Int}=0.99)\n\n               # initial calculations\n                e1 = (exp(-(s[\"walk\"])/min(s[\"walk\"], s[\"TTC\"])))\n                e2 = (exp(-(s[\"TTC\"])/min(s[\"walk\"], s[\"TTC\"])))\n                a = Dict(\"walk\" => e1/sum([e1,e2]), \"TTC\" => e2/sum([e1,e2]))\n                # simulation loop\n                y = []\n                append!(y, from)\n                if to_perc\n                    while y[end] <= to\n                        append!(y, calc_new_state(y,a,b,l))\n                    end\n                else\n                    for i in 1:to\n                        append!(y, calc_new_state(y,a,b,l))\n                    end\n                end\n                y\nend\n\n#####################################\n### scenario 1:\ns = Dict(\"walk\" => 15, \"TTC\" => 10) # time of travel\nl = Dict(\"walk\" => 0.01, \"TTC\" => 0.02) # contagion\nb = Dict(\"walk\" => 5, \"TTC\" => 5) # interaction frequency\n\nx1 = simul(s,b,l)\nlength(x1) - 1\n\n### scenario 2:\ns = Dict(\"walk\" => 15, \"TTC\" => 10) # time of travel\nl = Dict(\"walk\" => 0.01, \"TTC\" => 0.02) # contagion\nb = Dict(\"walk\" => 3, \"TTC\" => 5) # interaction frequency\n\nx2 = simul(s,b,l)\nlength(x2) - 1\n\n# PLOT1 \nPlots.plot(1:length(x1), x1, linecolor=\"purple\", lw = 2, legend=false, grid=false)\nylabel!(\"% infected\")\nxlabel!(\"days\")\nsavefig(\"plot1.eps\")\n\n\n# PLOT2 \nPlots.plot(1:length(x2), x2, linecolor=\"purple\", lw = 2, legend=false, grid=false)\nylabel!(\"% infected\")\nxlabel!(\"days\")\nsavefig(\"plot2.eps\")\n\n\n###############################\n\n#PLOT3\nPlots.plot(1:length(x1), x1, linecolor=\"purple\", label=\"Scenario 1\", lw=2, grid = false, legend=:topleft)\nPlots.plot!(1:length(x2), x2, linecolor=\"black\", label=\"Scenario 2\", lw=2 #linestyle = :dot, )\n)\nylabel!(\"% infected\")\nxlabel!(\"days\")\nsavefig(\"plot3.eps\")\n\n################################\n\n# PLOT 4\ns = Dict(\"walk\" => 15, \"TTC\" => 10) # time of travel\nl = Dict(\"walk\" => 0.01, \"TTC\" => 0.02) # contagion\nb = Dict(\"walk\" => 3, \"TTC\" => 5) # interaction frequency\n\nresults_full = Dict()\nresults_short = DataFrame()\nfor i in 1:50\n    s[\"TTC\"] = i\n    results_full[i] = simul(s,b,l)\n    append!(results_short, DataFrame(s_ttc = [i], days = [length(results_full[i])-1]))\nend\n\nresults_short # ok\n\nPlots.plot(results_short[!,:s_ttc], results_short[!,:days], linecolor=\"purple\", lw = 2, legend=false, grid=false)\nylabel!(\"days\")\nxlabel!(\"time when taking TTC\")\nsavefig(\"plot4.eps\")\n\n#############################\n\n# PLOT 5\ns = Dict(\"walk\" => 15, \"TTC\" => 10) # time of travel\nl = Dict(\"walk\" => 0.01, \"TTC\" => 0.02) # contagion\nb = Dict(\"walk\" => 3, \"TTC\" => 5) # interaction frequency\n\nresults_full2 = Dict()\nresults_short2 = DataFrame()\nfor i in 1:50\n    s[\"TTC\"] = i\n    results_full2[i] = simul(s,b,l, to_perc=false, to=101)\n    append!(results_short2, DataFrame(s_ttc = [i], infected = results_full2[i][101]))\nend\n\nresults_short2 # ok\n\nPlots.plot(results_short2[!,:s_ttc], results_short2[!,:infected], linecolor=\"purple\", lw = 2, legend=false, grid=false)\nylabel!(\"% infected after 100 days\")\nxlabel!(\"time when taking TTC\")\nsavefig(\"plot5.eps\")\n\n\n\n", "meta": {"hexsha": "d81d3ee67ee07ff6553a266da8f4ce5a763f1901", "size": 3595, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "codes/differential.jl", "max_stars_repo_name": "NykPol/EpidemicInUrbanNetworkToronto", "max_stars_repo_head_hexsha": "8e3215458136771d6e2e351f4f1d23ebfad5eb64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "codes/differential.jl", "max_issues_repo_name": "NykPol/EpidemicInUrbanNetworkToronto", "max_issues_repo_head_hexsha": "8e3215458136771d6e2e351f4f1d23ebfad5eb64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/differential.jl", "max_forks_repo_name": "NykPol/EpidemicInUrbanNetworkToronto", "max_forks_repo_head_hexsha": "8e3215458136771d6e2e351f4f1d23ebfad5eb64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4427480916, "max_line_length": 133, "alphanum_fraction": 0.5312934631, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395168021653, "lm_q2_score": 0.8244619328462579, "lm_q1q2_score": 0.770373246269336}}
{"text": "@model AHMCGaussian(y, N) = begin\n    mu ~ Normal(0, 1)\n    sigma ~ Truncated(Cauchy(0, 5), 0, Inf)\n    y ~ MvNormal(Fill(mu, N), sigma)  # use `Fill(mu, N)` is memory freiendly\nend\n\nAHMCconfig = Turing.NUTS(1000, .85)\n\nCmdStanGaussian = \"\ndata {\n  int<lower=0> N;\n  vector[N] y;\n}\nparameters {\n  real mu;\n  real<lower=0> sigma;\n}\nmodel {\n  mu ~ normal(0,1);\n  sigma ~ cauchy(0,5);\n  y ~ normal(mu,sigma);\n}\n\"\n\nCmdStanConfig = Stanmodel(\n  name = \"CmdStanGaussian\", model=CmdStanGaussian, nchains=1,\n  Sample(\n    num_samples=1000, num_warmup=1000, adapt=CmdStan.Adapt(delta=0.8),\n    save_warmup=true\n  )\n)\n\nstruct GaussianProb{TY <: AbstractVector}\n    \"Observations.\"\n    y::TY\nend\n\nfunction (problem::GaussianProb)(θ)\n    @unpack y = problem   # extract the data\n    @unpack mu, sigma = θ\n    N = length(y)\n    logpdf(MvNormal(Fill(mu, N), sigma), y) + logpdf(Normal(0, 1), mu) +\n      logpdf(Truncated(Cauchy(0, 5), 0, Inf), sigma)\nend\n\n# Define problem with data and inits.\nfunction sampleDHMC(obs, N, nsamples, autodiff)\n  p = GaussianProb(obs);\n  p((mu=0.0, sigma=1.0))\n\n  # Write a function to return properly dimensioned transformation.\n  trans = as((mu=as(Real, -25, 25), sigma=asℝ₊), )\n\n  # Use Flux for the gradient.\n\n  P = TransformedLogDensity(trans, p)\n  ∇P = ADgradient(autodiff, P)\n\n  # Sample from the posterior.\n  results = mcmc_with_warmup(Random.GLOBAL_RNG, ∇P, nsamples; reporter = NoProgressReport())\n\n  # Undo the transformation to obtain the posterior from the chain.\n  posterior = transform.(trans, results.chain)\n\n  chns = nptochain(results, posterior)\n  return chns\nend\n\nsimulateGaussian(; μ=0, σ=1, Nd, kwargs...) = (y=rand(Normal(μ, σ), Nd), N=Nd)\n", "meta": {"hexsha": "8bcd1130535ae3fac095cbefe39f062b3d34c543", "size": 1679, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Models/Gaussian/Gaussian_Models.jl", "max_stars_repo_name": "UnofficialJuliaMirror/MCMCBenchmarks.jl-72ce6e51-3f7f-5ebd-8e88-b86aa3e31c30", "max_stars_repo_head_hexsha": "f228291484c8b84c543be4ae073dc77843067ef2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Models/Gaussian/Gaussian_Models.jl", "max_issues_repo_name": "UnofficialJuliaMirror/MCMCBenchmarks.jl-72ce6e51-3f7f-5ebd-8e88-b86aa3e31c30", "max_issues_repo_head_hexsha": "f228291484c8b84c543be4ae073dc77843067ef2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Models/Gaussian/Gaussian_Models.jl", "max_forks_repo_name": "UnofficialJuliaMirror/MCMCBenchmarks.jl-72ce6e51-3f7f-5ebd-8e88-b86aa3e31c30", "max_forks_repo_head_hexsha": "f228291484c8b84c543be4ae073dc77843067ef2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9857142857, "max_line_length": 92, "alphanum_fraction": 0.6634901727, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951698485602, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7703732437453884}}
{"text": "\"\"\"\n    Module Basis2DQuad\n\nIncludes DG core functions.\n\"\"\"\n\nmodule Basis2DQuad\n\nexport vandermonde_2D, grad_vandermonde_2D\nexport nodes_2D, equi_nodes_2D, quad_nodes_2D\n\nusing Basis1D\nusing CommonUtils\nusing LinearAlgebra\n\n\"\"\"\n    vandermonde_2D(N, r)\n\nInitialize the 2D Vandermonde matrix of order N \"Legendre\" polynomials at\nnodes (r,s)\n\n# Examples\n```jldoctest\n\"\"\"\nfunction vandermonde_2D(N, r, s)\n\n    Np = convert(Int,(N+1)*(N+1))\n    sk = 1\n    V = zeros(length(r), Np);\n    for i=0:N\n        for j=0:N\n            V[:,sk] = jacobiP(r, 0, 0, i).*jacobiP(s, 0, 0, j)\n            sk += 1\n        end\n    end\n    return V\nend\n\n\"\"\"\n    gradV_2D(N, Np, r, s)\n\nInitilize 2D gradient Vandermonde matrix of derivatives 2D \"Legendre\" polynomials\nof order N at (r,s)\n\n# Examples\n```jldoctest\n\"\"\"\nfunction grad_vandermonde_2D(N, r, s)\n\n    Np = convert(Int,(N+1)*(N+1))\n    sk = 1\n    V2Dr = zeros(length(r), Np);\n    V2Ds = zeros(length(r), Np);\n    for i=0:N\n        for j=0:N\n            V2Dr[:,sk] = grad_jacobiP(r, 0, 0, i).*jacobiP(s, 0, 0, j)\n            V2Ds[:,sk] = jacobiP(r, 0, 0, i).*grad_jacobiP(s, 0, 0, j)\n            sk += 1\n        end\n    end\n\n    return V2Dr, V2Ds\nend\n\n# ===================================================\n\n\"\"\"\n    nodes_2D(N)\n\nCompute optimized interpolation nodes using blend & warp method on equilateral\ntriangles for polynomial of order N, with Np points\n\n# Examples\n```jldoctest\n\"\"\"\n\nfunction nodes_2D(N)\n    r1D,w1D = gauss_lobatto_quad(0,0,N)\n    s,r = meshgrid(r1D)\n    return r[:], s[:]\nend\n\n\"\"\"\n    equi_nodes_2D(N)\n\nCompute optimized interpolation nodes using blend & warp method on equilateral\ntriangles for polynomial of order N, with Np points\n\n# Examples\n```jldoctest\n\"\"\"\n\nfunction equi_nodes_2D(N)\n    r1D = LinRange(-1,1,N+1)\n    s,r = meshgrid(r1D)\n\n    return r[:], s[:]\nend\n\n\"\"\"\n    quad_nodes_2D(N)\n\nCompute optimized interpolation nodes using blend & warp method on equilateral\ntriangles for polynomial of order N, with Np points\n\n# Examples\n```jldoctest\n\"\"\"\n\nfunction quad_nodes_2D(N)\n    r1D,w1D = gauss_quad(0,0,N)\n    s,r = meshgrid(r1D)\n    ws,wr = meshgrid(w1D)\n    w = @. wr*ws\n    return r[:], s[:], w[:]\nend\n\nend\n", "meta": {"hexsha": "4a81144a99249bc2f3af946d9d988db35208c9ad", "size": 2177, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Basis2DQuad.jl", "max_stars_repo_name": "jlchan/ESDG-CNS", "max_stars_repo_head_hexsha": "a1ed7ef8e9c4270692ab76e938d0f5b0b44d5298", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-11-09T20:59:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T16:48:18.000Z", "max_issues_repo_path": "src/Basis2DQuad.jl", "max_issues_repo_name": "jlchan/ESDG-CNS", "max_issues_repo_head_hexsha": "a1ed7ef8e9c4270692ab76e938d0f5b0b44d5298", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Basis2DQuad.jl", "max_forks_repo_name": "jlchan/ESDG-CNS", "max_forks_repo_head_hexsha": "a1ed7ef8e9c4270692ab76e938d0f5b0b44d5298", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-11T04:15:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T23:57:17.000Z", "avg_line_length": 18.2941176471, "max_line_length": 81, "alphanum_fraction": 0.6118511713, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7703732417506891}}
{"text": "import CompEcon, BasisMatrices\nusing PyPlot\nusing PyCall\n\nf1(x) = @. exp(-2x)\ng1(x) = @. -2exp(-2x)\n\nfunction univariate_interp(f=f1, g=g1)\n    # fit approximant\n    n = 10; a = -1; b = 1\n    basis = CompEcon.fundefn(:cheb, n, a, b)\n    c = CompEcon.funfitf(basis, f1)\n\n    # graph approximation error for function and derivative\n    x = BasisMatrices.nodeunif(1001, a, b)[1]\n    yact = f(x)\n    dact = g(x)\n    yfit = CompEcon.funeval(c, basis, x)[1]\n    dfit = CompEcon.funeval(c, basis, x, 1)[1]\n\n\n    # Nice plot of function approximation error\n    fig, ax = plt.subplots()\n    ax[:plot](x, yfit-yact)\n    ax[:plot](x, 0*x, \"k--\", linewidth=2)\n    ax[:set_xlabel](\"x\")\n    ax[:set_ylabel](\"Error\")\n    ax[:set_title](\"Error approximating function using Chebyshev\")\n\n    # Nice plot of derivative approximation error\n    fig, ax = plt.subplots()\n    ax[:plot](x, dfit-dact);\n    ax[:plot](x, 0*x, \"k--\", linewidth=2)\n    ax[:set_xlabel](\"x\")\n    ax[:set_ylabel](\"Error\")\n    ax[:set_title](\"Error approximating derivative using Chebyshev\")\nend\n\n\nf2(x) = cos.(x[:, 1]) ./ exp.(x[:, 2])\nfunction bivaraite_interp(f=f2)\n    n = [7 7]\n    a = [0 0]\n    b = [1 1]\n    basis = CompEcon.fundefn(:cheb, n, a, b)\n    c = CompEcon.funfitf(basis, f2)\n\n    fig = plt.figure()\n    nplot = [101 101]\n    x, xcoord = BasisMatrices.nodeunif(nplot, a, b)\n    yfit = CompEcon.funeval(c, basis, x)[1]\n    error = reshape(yfit - f2(x), nplot...)\n    poly3d = surf(xcoord[1], xcoord[2], error)\n\nend\n\nunivariate_interp()\nbivaraite_interp()\n", "meta": {"hexsha": "fa02f4b3065c8349baeb7d342ad3175d2c5159ae", "size": 1521, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demo/demapp00.jl", "max_stars_repo_name": "magerton/BasisMatrices.jl", "max_stars_repo_head_hexsha": "093925e67c2452a1f2da872571aff84d93cfac2d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2016-10-26T02:36:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-22T22:05:15.000Z", "max_issues_repo_path": "demo/demapp00.jl", "max_issues_repo_name": "magerton/BasisMatrices.jl", "max_issues_repo_head_hexsha": "093925e67c2452a1f2da872571aff84d93cfac2d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 58, "max_issues_repo_issues_event_min_datetime": "2016-10-25T21:55:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T10:14:37.000Z", "max_forks_repo_path": "demo/demapp00.jl", "max_forks_repo_name": "magerton/BasisMatrices.jl", "max_forks_repo_head_hexsha": "093925e67c2452a1f2da872571aff84d93cfac2d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:47:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T23:07:07.000Z", "avg_line_length": 25.7796610169, "max_line_length": 68, "alphanum_fraction": 0.6094674556, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678381, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7703732392267417}}
{"text": "\"\"\"\n    UtilFuncs\n\nThis module collects many conventional utility functions\nwhich are provided within the general form ``u(X|\\\\theta):\\\\mathbb{R}^{k}\\\\to\\\\mathbb{R}``.\nwhere ``\\\\theta`` is `tuple` of parameters (in specific types of utility function, they are defined as keyword parameters), and ``k`` is the dimension of utilizable goods.\n\nThere is the contents of utility functions:\n1. `u_log` - logarithm (risk netural, 1 good)\n2. `u_crra` - CRRA\n3. `u_cara` - CARA\n4. `u_ces2` - CES (2 goods)\n5. `u_cesk` - CES (k goods)\n6. `u_cd1` - Cobb-Douglas (1 good)\n7. `u_cd2` - Cobb-Douglas (2 goods)\n8. `u_cdk` - Cobb-Douglas (k goods)\n9. `u_logcd2` - Logarithm Cobb-Douglas (2 goods)\n10. `u_logcdk` - Logarithm Cobb-Douglas (k goods)\n11. `u_leontiefk` - Leontief (k goods)\n\nPlease refer to each specific function for detailed documentations.\n\nThis module depends on:\n1. nothing\n\n@author: Clpr @ GitHub\n\"\"\"\nmodule UtilFuncs\n    export u_log, u_crra, u_cara\n    export u_ces2, u_cesk\n    export u_cd1, u_cd2, u_cdk\n    export u_logcd2, u_logcdk\n    export u_leontiefk\n# =================================\n\"\"\"\n    u_log(x::Real)\n\nLogarithm (risk-netural) utility function for one good\nwhere `x` is naturally required to be positive.\nThe expression of logarithm utility function is:\n``u(x)=\\\\log(x),x>0``\n\"\"\"\nfunction u_log(x::Real)\n    return log(x)::Real\nend # u_log\n\n\n# ----------------\n\"\"\"\n    u_crra(x::Real ; η::Real)\n\nCRRA (constant relative risk aversion) utility function of one good\nwhose expression is:\n``u(x|\\\\eta>0) = \\\\frac{x^{1-\\\\eta}}{1-\\\\eta}``.\nThe relative risk aversion coefficient ``\\\\eta`` must be positive.\nWhen ``\\\\eta`` is one, this function degenerates to logarithm utility function.\n\"\"\"\nfunction u_crra(x::Real ; η::Real = 1.1)\n    if η<0; throw(ErrorException(\"requires positive eta (RRA)\")); end\n    η == 1 ? (return u_log(x)::Real)  :  (return (x^(1-η)/(1-η))::Real)\nend # u_crra\n\n\n# ----------------\n\"\"\"\n    u_cara(x::Real ; α::Real = 1.0)\n\nCARA (constant absolute risk aversion) utility function of one good.\nwhose expression is:\n``u(x|\\\\alpha>0) = -e^{-\\\\alpha x}``.\nThe absolute risk aversion coefficient ``\\\\alpha`` must be positive.\n\"\"\"\nfunction u_cara(x::Real ; α::Real = 1.0)\n    if α<0; throw(ErrorException(\"requires positive alpha (ARA)\")); end\n    return (-exp(-α * x))::Real\nend # u_cara\n\n\n# ----------------\n\"\"\"\n    u_ces2(x1::Real, x2::Real ; ρ::Real = 1.0, β::Real = 1.0, α::Real = 0.5 )\n\nCES (constant elasticity of substitution) utility function whose expression is:\n``u(x_1,x_2)=(\\\\alpha x_1^{\\\\rho} + \\\\(1-alpha) x_2^{\\\\rho})^{\\\\beta/\\\\rho}``\nThe elasticity of substitution is ``\\\\frac{1}{1-\\\\rho}``.\n\nSpecial cases:\n1. when ``\\\\rho=1``, the function has linear/perfect substitution.\n2. when ``\\\\rho=0``, the function becomes Cobb-Douglas function of two goods, i.e. ``u(x_1,x_2)=(x_1^\\\\alpha x_2^{1-\\\\alpha})^{\\\\beta}``\n3. when ``\\\\rho=-\\\\infty``, the function becomes Leontief (perfect complimentary), i.e. ``u(x_1,x_2)=\\\\beta \\\\min\\\\{ x_1,x_2 \\\\}``\n\"\"\"\nfunction u_ces2(x1::Real, x2::Real ; ρ::Real = 1.0, β::Real = 1.0, α::Real = 0.5 )\n    if ρ == 0\n        return ( ( x1^α * x2^(1-α) )^β )::Real\n    elseif ρ == -Inf\n        return ( β * min(x1,x2) )::Real\n    end # if\n    return ( ( α*x1^ρ + (1-α)*x2^ρ )^(β/ρ) )::Real\nend # u_ces2\n\n\n# ----------------\n\"\"\"\n    u_cesk(X::Vector ; W::Vector = ones(length(X)) , β::Real = 1.0, ρ::Real = 1.0 )\n\nCES utility function of k goods whose expression is:\n``u(X)=(\\\\sum w_i \\\\log(x_i)^{\\\\rho})^{\\\\beta/\\\\rho}``.\nrequiring the length of `W` must be equal to the length of `X`.\nThis function does not require the summation of `W` must be 1.\n\nSpecial cases:\n1. when ``\\\\rho=1``, the function has linear/perfect substitution.\n2. when ``\\\\rho=0``, the function becomes Cobb-Douglas function\n3. when ``\\\\rho=-\\\\infty``, the function becomes Leontief (perfect complimentary)\n    \n\"\"\"\nfunction u_cesk(X::Vector ; W::Vector = ones(length(X)) , β::Real = 1.0, ρ::Real = 1.0 )\n    if ρ == 0\n        return ( ( u_cdk(X, W=W) )^β )::Real\n    elseif ρ == -Inf\n        return ( β * u_leontiefk(X) )::Real\n    end # if\n    local U::Real = 0.0\n    for (x,w) in zip(X,W)\n        U += w * x ^ ρ\n    end # for\n    return ( U^(β/ρ) )::Real\nend # u_cesk\n\n\n# ----------------\n\"\"\"\n    u_cd1(x::Real ; θ::Real = 1.0)\n\nCobb-Douglas utility function of one good whose expression is:\n``u(x)=x^\\\\theta``\n\"\"\"\nfunction u_cd1(x::Real ; θ::Real = 1.0)\n    return (x^θ)::Real\nend # u_cd1\n\n\n\n# ----------------\n\"\"\"\n    u_cd2(x::Real ; θ::Real = 0.5)\n\nCobb-Douglas utility function of two good whose expression is:\n``u(x_1,x_2)=x_1^\\\\theta\\\\cdot x_2^{1-\\\\theta}``\n\"\"\"\nfunction u_cd2(x1::Real, x2::Real ; θ::Real = 0.5)\n    return (x1^θ * x2^(1-θ))::Real\nend # u_cd2\n\n\n# ----------------\n\"\"\"\n    u_cdk(X::Vector ; W::Vector = ones(length(X)))\n\nCobb-Douglas utility function of k goods whose expression is:\n``u(X)=\\\\prod \\\\log(x_i)^{w_i}``.\nrequiring the length of `W` must be equal to the length of `X`.\nThis function does not require the summation of `W` must be 1.\n\"\"\"\nfunction u_cdk(X::Vector ; W::Vector = ones(length(X)) )\n    return exp(u_logcdk(X, W = W))::Real\nend # u_cdk\n\n\n# ----------------\n\"\"\"\n    u_logcd2(x1::Real, x2::Real ; β::Real = 1.0 )\n\nLogarithm Cobb-Douglas utility function of k goods whose expression is:\n``u(x_1,x_2)=\\\\log(x_1)+\\\\beta\\\\log(x_2)``\n\"\"\"\nfunction u_logcd2(x1::Real, x2::Real ; β::Real = 1.0 )\n    return ( log(x1) + β * log(x2) )::Real\nend\n\n\n# ----------------\n\"\"\"\n    u_logcdk(X::Vector ; W::Vector = ones(length(X)))\n\nLogarithm Cobb-Douglas utility function whose expression is:\n``u(X)=\\\\sum w_i\\\\log(x_i)``.\nrequiring the length of `W` must be equal to the length of `X`.\n\"\"\"\nfunction u_logcdk(X::Vector ; W::Vector = ones(length(X)) )\n    local U::Real = 0.0\n    for (x,w) in zip(X,W); U += w * x; end # for\n    return U::Real\nend # u_logcdk\n\n\n# ----------------\n\"\"\"\n    u_leontiefk(X::Vector)\n\nLeontief (perfect complimentary) utility function of k goods:\n``u(\\\\mathbf{x})=\\\\min\\\\{x_1,x_2,\\\\dots\\\\}``\n\"\"\"\nfunction u_leontiefk(X::Vector)\n    return findmin(X)\nend # u_leontiefk\n\n\n\n\n\n\n\n\n# =================================\nend # UtilFuncs", "meta": {"hexsha": "4e11d4f3a34c45e049b67abb9a31d9a12f30ec2d", "size": 6129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "DGEtools/UtilFuncs.jl", "max_stars_repo_name": "Clpr/EconToolBox", "max_stars_repo_head_hexsha": "4c2cf1e5ec9a84dc07f76317910aea4682fa508c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DGEtools/UtilFuncs.jl", "max_issues_repo_name": "Clpr/EconToolBox", "max_issues_repo_head_hexsha": "4c2cf1e5ec9a84dc07f76317910aea4682fa508c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DGEtools/UtilFuncs.jl", "max_forks_repo_name": "Clpr/EconToolBox", "max_forks_repo_head_hexsha": "4c2cf1e5ec9a84dc07f76317910aea4682fa508c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.375, "max_line_length": 171, "alphanum_fraction": 0.6054821341, "num_tokens": 2078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7703732337107447}}
{"text": "using LinearAlgebra\n\nfunction matcond(n::Int, c::Float64)\n# Function generates a random square matrix A of size n with\n# a given condition number c.\n# Inputs:\n#\tn: size of matrix A, n>1\n#\tc: condition of matrix A, c>= 1.0\n#\n# Usage: matcond(10, 100.0)\n#\n# Pawel Zielinski\n        if n < 2\n         error(\"size n should be > 1\")\n        end\n        if c< 1.0\n         error(\"condition number  c of a matrix  should be >= 1.0\")\n        end\n        (U,S,V)=svd(rand(n,n))\n        return U*diagm(0 =>[LinRange(1.0,c,n);])*V'\nend\n\n\n\n\n", "meta": {"hexsha": "b864457f61a5e2d224030658fde3670416f6d9cd", "size": 529, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5th-semester/on/lab/lista-2/matcond.jl", "max_stars_repo_name": "jerry-sky/academic-notebook", "max_stars_repo_head_hexsha": "be2d350289441b99168ea40412891bc65b9cb431", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-28T21:53:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T19:24:47.000Z", "max_issues_repo_path": "5th-semester/on/lab/lista-2/matcond.jl", "max_issues_repo_name": "jerry-sky/academic-notebook", "max_issues_repo_head_hexsha": "be2d350289441b99168ea40412891bc65b9cb431", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-02-13T18:07:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T18:16:07.000Z", "max_forks_repo_path": "5th-semester/on/lab/lista-2/matcond.jl", "max_forks_repo_name": "jerry-sky/academic-notebook", "max_forks_repo_head_hexsha": "be2d350289441b99168ea40412891bc65b9cb431", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-28T16:05:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T16:20:00.000Z", "avg_line_length": 20.3461538462, "max_line_length": 67, "alphanum_fraction": 0.5784499055, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9591542805873231, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.770367584831293}}
{"text": "#Minimum cover EMS method\r\nusing JuMP,Gurobi\r\n\r\n#define the model\r\nm =Model(Gurobi.Optimizer)\r\n\r\n#Let n represents the number of decision variables\r\nn=10 \r\n\r\n#declaring variables\r\n@variable(m, x[1:n], Bin) # binary constraint \r\n\r\n#define the objective function\r\n@objective(m , Min, sum(x[i] for i =1:n)) # objective is to minimize the coverage\r\n\r\n#Since decision variables x2,x3,x8 and x10>=1, I declared them in a for-loop together\r\nfor i in [2,3,8,10]\r\n\t@constraint(m,x[i]>=1)    #(x[i] for i in [2,3,8,10]) >=1) \r\nend\r\n\r\n\r\n#additional constraint\r\n@constraint(m, x[1]+x[2]>=1)    #district 2\r\n@constraint(m, x[1]+x[3]>=1)    #district 3\r\n@constraint(m, x[2]+x[4]>=1)\t#district 7\r\n@constraint(m, x[3]+x[4]>=1)\t#district 8\r\n@constraint(m, x[4]+x[6]>=1)\t#district 10\r\n@constraint(m, x[4]+x[5]>=1)\t#district 11\r\n@constraint(m, x[4]+x[5]+x[7]>=1)\t#distict 13\r\n@constraint(m, x[4]+x[5]+x[6]>=1)\t#distict 12\r\n@constraint(m, x[8]+x[9]>=1)\t\t#distict 14, district 18\r\n@constraint(m, x[6]+x[9]>=1)\t\t#distict 15\r\n@constraint(m, x[5]+x[6]>=1)\t\t#distict 16\r\n@constraint(m, x[5]+x[7]+x[10]>=1)\t#distict 17\r\n@constraint(m, x[8]+x[10]>=1)\t\t#distict 19\r\n\r\nprint(m)\r\n\r\n#Printing the optimal solutions obtained\r\nprintln(\"Optimal Solutions:\")\r\nstatus = JuMP.optimize!(m)\r\nprintln(\" Objective value: \",JuMP.objective_value(m))\r\n\r\nprintln(\"Decision variable values:\")\r\nfor i=1:10\r\n  println(\"x[$i] = \",   JuMP.value(x[i]))\r\nend\r\n", "meta": {"hexsha": "47eaf229acb1bd9f4092bde1f96157a3406185db", "size": 1408, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "EMS.jl", "max_stars_repo_name": "Oyekanmi/Optimization-Julia", "max_stars_repo_head_hexsha": "9c89aa41fe14ead83f493c812c9f51d407870d6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-14T14:36:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T14:36:32.000Z", "max_issues_repo_path": "EMS.jl", "max_issues_repo_name": "Oyekanmi/Optimization-Julia", "max_issues_repo_head_hexsha": "9c89aa41fe14ead83f493c812c9f51d407870d6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EMS.jl", "max_forks_repo_name": "Oyekanmi/Optimization-Julia", "max_forks_repo_head_hexsha": "9c89aa41fe14ead83f493c812c9f51d407870d6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3333333333, "max_line_length": 86, "alphanum_fraction": 0.6413352273, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075722839015, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7703518314200237}}
{"text": "\nfunction dayNumber(inDate::Date)\n    return Dates.date2epochdays(inDate)::Integer\nend\n\nexcelcostant = 693959;\n\n\"\"\"\nFrom Excel Number Format to Date\n\n\t\tDate=fromExcelNumberToDate(ExcelNumber)\n\nWhere:\\n\n\t\tExcelNumber = Integer representing a date in the excel format.\n\n\t\tDate      = Date representing the input in the Julia object format.\n\n# Example\n```julia-repl\njulia> fromExcelNumberToDate(45000)\n2023-03-15\n```\n\"\"\"\nfunction fromExcelNumberToDate(num::Integer)::Date\n    return Dates.Dates.epochdays2date(excelcostant + num)\nend\n\n\"\"\"\nActual Number of days between two dates\n\n\t\tndays=daysact(Date1,Date2)\n\nWhere:\\n\n\t\tDate1 = Start date.\n\t\tDate2 = End date.\n\n\t\tndays      = Actual Number of days between Start Date and End Date.\n\n# Example\n```julia-repl\njulia> daysact(Date(1996,10,12),Date(1998,1,10))\n455\n```\n\"\"\"\nfunction daysact(Date1::Date, Date2::Date)::Integer\n    D1 = dayNumber(Date1)\n    D2 = dayNumber(Date2)\n    dayCount = D2 - D1\n    return dayCount\nend\n\nfunction isLastOfFebruary(inDate::Date)::Bool\n    return (Dates.isleapyear(Dates.year(inDate)) && (Dates.day(inDate) == 29) && (Dates.month(inDate) == 2)) || ((!Dates.isleapyear(Dates.year(inDate))) && (Dates.day(inDate) == 28) && (Dates.month(inDate) == 2))\nend\n\ncurrMaxImplemented = 7;\n\n\"\"\"\nFraction of year between two Dates according the following convention\n\n\t\tyfr=yearfrac(Date1,Date2,basis)\n\nWhere:\\n\n\t\tDate1 = Start date.\n\t\tDate2 = End date.\n\t\tbasis = Integer representing the following conventions:\n\t\t\t\t- 0 = (ACT/ACT)\n\t\t\t\t- 1 = (30/360 SIA)\n\t\t\t\t- 2 = (ACT/360)\n\t\t\t\t- 3 = (ACT/365)\n\t\t\t\t- 4 = (30/360 PSA)\n\t\t\t\t- 5 = (30/360 ISDA)\n\t\t\t\t- 6 = (30E/360)\n\t\t\t\t- 7 = (ACT/365 JPN)\n\n\t\tyfr      = fraction of year between start and end date according to basis.\n\n# Example\n```julia-repl\njulia> yearfrac(Date(1996,10,12),Date(1998,1,10),1)\n1.2444444444444445\n```\n\"\"\"\nfunction yearfrac(startDate::Date, endDate::Date, convention::Integer)::Real\n    if (convention < 0)\n        error(\"Negative basis are not defined, check the help\")\n    end\n    if (convention > currMaxImplemented)\n        error(\"Convention not implemented yet\")\n    end\n    if (startDate > endDate)\n        return -yearfrac(endDate, startDate, convention)\n    elseif (startDate == endDate)\n        return 0.0\n    end\n    yearFrac = 0.0\n    y1 = Dates.year(startDate)\n    m1 = Dates.month(startDate)\n    y2 = Dates.year(endDate)\n    m2 = Dates.month(endDate)\n    d1 = Dates.day(startDate)\n    d2 = Dates.day(endDate)\n    if (convention == 0)#(ACT/ACT)\n        Nday = daysact(startDate, endDate)\n        EndOFYear = Date(1)\n        if (isLastOfFebruary(startDate) && (Dates.day(startDate) == 29))\n            EndOFYear = Date(Dates.year(startDate) + 1, 3, 1)\n        else\n            EndOFYear = Date(Dates.year(startDate) + 1, Dates.month(startDate), Dates.day(startDate))\n        end\n        yearFrac = (Nday) / daysact(startDate, EndOFYear)\n    elseif (convention == 1)  #(30/360 SIA)\n        if (isLastOfFebruary(startDate) && isLastOfFebruary(endDate))\n            d2 = 30\n        end\n        if (isLastOfFebruary(startDate) || Dates.day(startDate) == 31)\n            d1 = 30\n        end\n        if (d1 == 30 && d2 == 31)\n            d2 = 30\n        end\n        dy = y2 - y1\n        dm = m2 - m1\n        dd = d2 - d1\n        yearFrac = (360.0 * dy + 30.0 * dm + dd) / 360.0\n    elseif (convention == 2)#(ACT/360)\n        Nday = daysact(startDate, endDate)\n        yearFrac = (Nday) / 360.0\n    elseif (convention == 3)# (ACT/365)\n        Nday = daysact(startDate, endDate)\n        yearFrac = (Nday) / 365.0\n    elseif (convention == 4)# (30/360 PSA)\n        if ((Dates.day(startDate) == 31) || isLastOfFebruary(startDate))\n            d1 = 30\n        end\n        if ((Dates.day(startDate) == 30 || isLastOfFebruary(startDate)) && Dates.day(endDate) == 31)\n            d2 = 30\n        end\n        dy = y2 - y1\n        dm = m2 - m1\n        dd = d2 - d1\n        yearFrac = (360.0 * dy + 30.0 * dm + dd) / 360.0\n\n    elseif (convention == 5)#(30/360 ISDA)\n        y1 = Dates.year(startDate)\n        m1 = Dates.month(startDate)\n        y2 = Dates.year(endDate)\n        m2 = Dates.month(endDate)\n        if (Dates.day(startDate) < 31)\n            d1 = Dates.day(startDate)\n        else\n            d1 = 30\n        end\n        if ((Dates.day(endDate) == 31) && (d1 > 29))\n            d2 = 30\n        else\n            d2 = Dates.day(endDate)\n        end\n        yearFrac = (360.0 * ((y2 - y1)) + 30.0 * ((m2 - m1)) + (d2 - d1)) / 360.0\n\n    elseif (convention == 6)#(30E/360)\n        if (d1 == 31)\n            d1 = 30\n        end\n        if (d2 == 31)\n            d2 = 30\n        end\n        dy = y2 - y1\n        dm = m2 - m1\n        dd = d2 - d1\n        yearFrac = (360.0 * dy + 30.0 * dm + dd) / 360.0\n    elseif (convention == 7)#(ACT/365 JPN)\n        daydistance = [0; 31; 59; 90; 120; 151; 181; 212; 243; 273; 304; 334]\n        dy = y2 - y1\n        dd = d2 - d1\n        dayCount = (365.0 * dy + daydistance[m2] - daydistance[m1] + dd)\n        yearFrac = dayCount / 365.0\n    end\n\n    return yearFrac\nend\n", "meta": {"hexsha": "091ecf87b8947004666c8bdc6cfb7f893f4a60ad", "size": 5035, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dates.jl", "max_stars_repo_name": "rcalxrc08/FinancialToolbox.jl", "max_stars_repo_head_hexsha": "f6da3e9c70ae934f2bf750f5031bbc8df5f18afe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2017-12-06T10:31:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T00:12:30.000Z", "max_issues_repo_path": "src/dates.jl", "max_issues_repo_name": "rcalxrc08/FinancialToolbox.jl", "max_issues_repo_head_hexsha": "f6da3e9c70ae934f2bf750f5031bbc8df5f18afe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2017-08-26T14:47:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T14:32:19.000Z", "max_forks_repo_path": "src/dates.jl", "max_forks_repo_name": "rcalxrc08/FinancialToolbox.jl", "max_forks_repo_head_hexsha": "f6da3e9c70ae934f2bf750f5031bbc8df5f18afe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2017-09-16T11:04:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T15:26:53.000Z", "avg_line_length": 27.6648351648, "max_line_length": 212, "alphanum_fraction": 0.5763654419, "num_tokens": 1631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825847, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7703109543899523}}
{"text": "doc\"\"\"\n    TDist(ν)\n\nThe *Students T distribution* with `ν` degrees of freedom has probability density function\n\n$f(x; d) = \\frac{1}{\\sqrt{d} B(1/2, d/2)}\n\\left( 1 + \\frac{x^2}{d} \\right)^{-\\frac{d + 1}{2}}$\n\n```julia\nTDist(d)      # t-distribution with d degrees of freedom\n\nparams(d)     # Get the parameters, i.e. (d,)\ndof(d)        # Get the degrees of freedom, i.e. d\n```\n\nExternal links\n\n[Student's T distribution on Wikipedia](https://en.wikipedia.org/wiki/Student%27s_t-distribution)\n\n\"\"\"\nimmutable TDist <: ContinuousUnivariateDistribution\n    ν::Float64\n\n    TDist(ν::Real) = (@check_args(TDist, ν > zero(ν)); new(ν))\nend\n\n@distr_support TDist -Inf Inf\n\n\n#### Parameters\n\ndof(d::TDist) = d.ν\nparams(d::TDist) = (d.ν,)\n\n\n#### Statistics\n\nmean(d::TDist) = d.ν > 1.0 ? 0.0 : NaN\nmedian(d::TDist) = 0.0\nmode(d::TDist) = 0.0\n\nfunction var(d::TDist)\n    ν = d.ν\n    ν > 2.0 ? ν / (ν - 2.0) :\n    ν > 1.0 ? Inf : NaN\nend\n\nskewness(d::TDist) = d.ν > 3.0 ? 0.0 : NaN\n\nfunction kurtosis(d::TDist)\n    ν = d.ν\n    ν > 4.0 ? 6.0 / (ν - 4.0) :\n    ν > 2.0 ? Inf : NaN\nend\n\nfunction entropy(d::TDist)\n    h = 0.5 * d.ν\n    h1 = h + 0.5\n    h1 * (digamma(h1) - digamma(h)) + 0.5 * log(d.ν) + lbeta(h, 0.5)\nend\n\n\n#### Evaluation & Sampling\n\n@_delegate_statsfuns TDist tdist ν\n\nrand(d::TDist) = StatsFuns.Rmath.tdistrand(d.ν)\n\nfunction cf(d::TDist, t::Real)\n    t == 0 && return complex(1.0)\n    h = d.ν * 0.5\n    q = d.ν * 0.25\n    t2 = t*t\n    complex(2*(q*t2)^q*besselk(h,sqrt(d.ν)*abs(t))/gamma(h))\nend\n\ngradlogpdf(d::TDist, x::Float64) = -((d.ν + 1.0) * x) / (x^2 + d.ν)\n", "meta": {"hexsha": "664d1a928f61d0ef798257764104cad79abddb4e", "size": 1569, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/tdist.jl", "max_stars_repo_name": "ericproffitt/Distributions.jl", "max_stars_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/tdist.jl", "max_issues_repo_name": "ericproffitt/Distributions.jl", "max_issues_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/tdist.jl", "max_forks_repo_name": "ericproffitt/Distributions.jl", "max_forks_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1153846154, "max_line_length": 97, "alphanum_fraction": 0.5774378585, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7703109487791885}}
{"text": "using DifferentialEquations, Plots, LaTeXStrings\r\n\r\n##\r\nfunction Hénon_Heiles(du,u,p,t)\r\n    x  = u[1]\r\n    y  = u[2]\r\n    dx = u[3]\r\n    dy = u[4]\r\n    du[1] = dx\r\n    du[2] = dy\r\n    du[3] = -x - 2x*y\r\n    du[4] = y^2 - y -x^2\r\nend\r\n\r\n##\r\ninitial1 = [1/6,0.0,-0.2,0.0]\r\ninitial2 = [1/6,0.0 + 0.01,-0.2+0.01,0.0]\r\n\r\n##\r\ne,x,y,ydot = initial1\r\nxdot = sqrt(2*e - ydot^2 - y^2 + (2//3)*y^3)\r\nini = [x,y,xdot,ydot]\r\ntspan = (0,150.)\r\nprob = ODEProblem(Hénon_Heiles, ini, tspan)\r\nsol = solve(prob, Vern9(), abs_tol=1e-16, rel_tol=1e-16,saveat = 0.1);\r\nplot(sol, vars=(1,2), title = \"The orbit of the Hénon-Heiles system\", xaxis = \"x\", yaxis = \"y\", label = false,linecolor = :blue)\r\nscatter!([x],[y],label = false,markercolor = :blue)\r\n\r\n##\r\ne2,x2,y2,ydot2 = initial2\r\nxdot2 = sqrt(2*e2 - ydot2^2 - y2^2 + (2//3)*y2^3)\r\nini2 = [x2,y2,xdot2,ydot2]\r\nprob2 = ODEProblem(Hénon_Heiles, ini2, tspan)\r\nsol2 = solve(prob2, Vern9(), abs_tol=1e-16, rel_tol=1e-16,saveat = 0.1);\r\nplot!(sol2, vars=(1,2), label = false,linecolor = :red)\r\nscatter!([x2],[y2],label = false,markercolor = :red)\r\n", "meta": {"hexsha": "9573a2fd5776d36e5fa8920087ae2b590bb2dbc6", "size": 1075, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HH_orbits.jl", "max_stars_repo_name": "Ved-Mahajan/Henon-Heiles-System", "max_stars_repo_head_hexsha": "061be33a80c66bd4073c39a270fa2ff8fba75b77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HH_orbits.jl", "max_issues_repo_name": "Ved-Mahajan/Henon-Heiles-System", "max_issues_repo_head_hexsha": "061be33a80c66bd4073c39a270fa2ff8fba75b77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HH_orbits.jl", "max_forks_repo_name": "Ved-Mahajan/Henon-Heiles-System", "max_forks_repo_head_hexsha": "061be33a80c66bd4073c39a270fa2ff8fba75b77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0540540541, "max_line_length": 129, "alphanum_fraction": 0.5795348837, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7703109469726435}}
{"text": "\"\"\"\n    Compression(c, d, i; σ = 1.0, μ = 0.0)\n\nMaps ``ℝ → (-1, 1)``.\n\n# Arguments\n- `c`: the \"compression\", i.e., the map ``ℝ → (-1, 1)``,\n- `d`: the \"decompression\", i.e., the map ``(-1, 1) → ℝ``,\n- `i`: the jacobian of the map, i.e., ``∂d(τ) /∂τ``,\n- `σ`, `μ`: control the width and offset in the numerical integrations\n\"\"\"\nstruct Compression\n\tcomp::Function\n\tdecomp::Function\n\tinv_jacobian::Function\n\n\tσ::Float64\n\tμ::Float64\n\tfunction Compression(c, d, i; σ = 1.0, μ = 0.0)\n\t\tσ ≤ 0.0 && error(\"σ needs to be positive\")\n\t\tnew(c, d, i, σ, μ)\n\tend\nend\n\n\"\"\"\n    Algebraic(; σ = 1.0, μ = 0.0)\n\nMaps ``ℝ → (-1, 1)`` by ``t ↦ \\\\frac{t}{1 + |t|}``.\nEquivalent symbol is `:algebraic`.\n\"\"\"\nAlgebraic(; σ = 1.0, μ = 0.0) = Compression(\n\tt ->   t / (1.0 + abs(t)),\n\tτ ->   τ / (1.0 - abs(τ)),\n\tτ -> 1.0 / (1.0 - abs(τ))^2, # == (1.0 + abs( τ / (1.0 - abs(τ)) ) )^2\n\tσ = σ, μ = μ\n)\n\n\"\"\"\n    Exponential(; σ = 1.0, μ = 0.0)\n\nMaps ``ℝ → (-1, 1)`` by ``t ↦ \\\\mathrm{tanh}(t)``.\nEquivalent symbol is `:exponential`.\n\"\"\"\nExponential(; σ = 1.0, μ = 0.0) = Compression(\n\tt -> tanh(t),\n\tτ -> atanh(τ),\n\tτ -> 1.0 / (1.0 - τ^2), # == cosh(atanh(τ))^2\n\tσ = σ, μ = μ\n)\n\n\"\"\"\n    Trigonometric(; σ = 1.0, μ = 0.0)\n\nMaps ``ℝ → (-1, 1)`` by ``t ↦ \\\\frac{2}{π} \\\\mathrm{tan}^{-1}(t)``.\nEquivalent symbol is `:trigonometric`.\n\"\"\"\nTrigonometric(; σ = 1.0, μ = 0.0) = Compression(\n\tt -> 2.0 * atan(t) / π,\n\tτ -> tan(π*τ/2.0),\n\tτ -> π * (1.0 + tan(π*τ/2.0)^2) / 2.0,\n\tσ = σ, μ = μ\n)\n\nCompressions = Dict(\n\t:algebraic     => Algebraic(),\n\t:exponential   => Exponential(),\n\t:trigonometric => Trigonometric()\n)\n", "meta": {"hexsha": "a3b5fc842d4c5ec911e7ec8b06cd28474240e26a", "size": 1578, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/WavePackets/Compressions.jl", "max_stars_repo_name": "KKleinbeck/ChiralWaveguide.jl", "max_stars_repo_head_hexsha": "28b73f044cfcbb67752542cf965f0de6aa933ad9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/WavePackets/Compressions.jl", "max_issues_repo_name": "KKleinbeck/ChiralWaveguide.jl", "max_issues_repo_head_hexsha": "28b73f044cfcbb67752542cf965f0de6aa933ad9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/WavePackets/Compressions.jl", "max_forks_repo_name": "KKleinbeck/ChiralWaveguide.jl", "max_forks_repo_head_hexsha": "28b73f044cfcbb67752542cf965f0de6aa933ad9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8695652174, "max_line_length": 71, "alphanum_fraction": 0.5044359949, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.8376199673867853, "lm_q1q2_score": 0.7703109414383309}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 7c62a2c4-9159-11eb-1b54-452017ea90d9\nusing LinearAlgebra, SparseArrays\n\n# ╔═╡ 7ad16586-9162-11eb-1d94-5188eb8d4c5d\nusing DifferentialEquations, Plots\n\n# ╔═╡ 44df6004-9158-11eb-1a63-651d7dca957b\nmd\"# Heat equation with Robin boundary conditions \n\nConsider a one-dimensional rod $\\Omega = (0,L)$ and time $t \\in (0,T).$ \n\"\n\n# ╔═╡ aff71d6e-9158-11eb-0559-cb7334f4a624\nL = 0.1 # Length of rod\n\n# ╔═╡ 3771dab8-9159-11eb-3a69-cd9b94a10399\nTf = 60.0 # Final simulation time\n\n# ╔═╡ 44dbf81c-9159-11eb-2920-27ee60a7db9a\nmd\"The rod has the physical properties\n- thermal conductivity $\\lambda$,\n- specific heat capacity $c$,\n- mass density $\\rho$.\n\nThe diffusivity constant is given by $\\alpha = \\frac{\\lambda}{c \\rho}$. The heat equation is noted as\n\n$\\dot{\\vartheta}(t,x) = \\alpha \\frac{\\partial^2}{\\partial x^2} \\vartheta(t,x)$\n\nfor $(t,x) \\in (0,T) \\times \\Omega$ with initial condition\n\n$\\vartheta(0,x) = \\vartheta_{0}(x)$ \n\nfor $x \\in \\overline{\\Omega}$.\" \n\n# ╔═╡ 86a40dc8-9158-11eb-16a3-1f776d6bde4e\nbegin\n\tλ = 45.0;    # Thermal conductivity\n\tρ = 7800.0;  # Mass density\n\tcap = 480.0; # Specific heat capacitivity\nend\n\n# ╔═╡ 9e8ee0a2-9158-11eb-0210-4513221b7823\nα = λ/(cap * ρ)   # Diffusivity\n\n# ╔═╡ a4f1e1e2-9158-11eb-0754-a70399a341ba\nmd\"## Boundary conditions  \n\nOn both sides of the rod, heat transfer\n\n$\\phi_{t}(t,x) = - h ~ (\\vartheta(t,x) - \\vartheta_{amb})$\n\nand heat radiation\n\n$\\phi_{r}(t,x) = - \\epsilon \\varrho ~ (\\vartheta(t,x)^4 - \\vartheta_{amb}^4)$\n\nis assumed to operate. Parameter $\\vartheta_{amb}$ describes the ambient temperature, $h>0$ is called the heat transfer coefficient, $\\epsilon \\in (0,1)$ is called emissivity and $\\varrho\\approx 5.67 \\cdot 10^{-8}$ is known as Stefan-Boltzmann constant. For simplicity, $k=\\epsilon \\cdot \\varrho$. \n\nThe sum of $\\phi_{t}$ and $\\phi_{r}$ \n\n$\\phi_{out}(t,x) = \\phi_{t}(t,x) + \\phi_{r}(t,x) = - h ~ (\\vartheta(t,x) - \\vartheta_{amb}) - k ~ (\\vartheta(t,x)^4 - \\vartheta_{amb}^4)$\n\nis the flux from the rod to the environment. Thus, the natural (Robin) boundary conditions are noted as \n\n$\\lambda ~ \\left.\\frac{\\partial}{\\partial x} \\vartheta(\\cdot, x) \\right\\rvert_{x = 0} \\cdot \\vec{n} ~=~ \\lambda ~  \\left. \\frac{\\partial}{\\partial x} \\vartheta(\\cdot, x) \\right\\rvert_{x = L} \\cdot \\vec{n} ~=~ \\phi_{out}(t,x)$\n\nwith outer [normal vector](https://en.wikipedia.org/wiki/Normal_(geometry)) $\\vec{n}$ on the left or right boundary. Here, the normal vector $\\vec{n} = -1$ on the left boundary at $x=0$, and  $\\vec{n} = 1$ on the right boundary at $x=L$.\"\n\n# ╔═╡ 7c9e9a4a-9159-11eb-3dda-59d2aa15f32a\nbegin\n\th = 10.0; # Heat transfer coefficient\n\tϵ = 0.6;  # Emissivity\n\tsb = 5.67*10^(-8) # Stefan-Boltzmann constant\n\tk = ϵ * sb; \t  # Radiation coefficient\nend\n\n# ╔═╡ c5da798e-9160-11eb-1d16-75ce792ef2fe\nθamb = 298.0 # Ambient temperature in Kelvin\n\n# ╔═╡ 7c80218c-9159-11eb-301a-95a428fb76d9\nmd\"### Spatial approximation\n\nThe one-dimensional rod is discretized as a one-dimensional grid with N points and the finite discretization is noted by\n\n$\\Delta x = \\frac{L}{N-1}.$\n\nThe resulting grid points have the position $x^{0} = 0$, $x^{n} = n~\\Delta x$ and $x^{N-1} = L$. The second order derivative is approximated using the [Taylor series](https://en.wikipedia.org/wiki/Taylor_series) as \n\n$\\left. \\frac{\\partial^2 f(x)}{\\partial x^2} \\right\\rvert_{x = \\tilde{x}} \\approx \\frac{1}{\\Delta x^2} \\left[ f(\\tilde{x} - \\Delta x) - 2 f(\\tilde{x}) + f(\\tilde{x} + \\Delta x)  \\right].$\n\nThis [Finite Difference](https://en.wikipedia.org/wiki/Finite_difference_method) scheme is written in matrix-vector form as \n\n$\\frac{\\partial^2 \\vartheta(t,x)}{\\partial x^2} \\approx \\frac{1}{\\Delta x^2}\n\\begin{pmatrix}\n-2 & 1 & 0 & \\cdots &  & 0 \\\\\n1 & -2 & 1 & 0  & \\cdots & \\vdots \\\\\n0 & 1 & -2 & 1 & \\ddots &  \\\\\n & & \\ddots & \\ddots & \\ddots &  & \\\\\n& & & 1 & -2 & 1 \\\\\n& & &  & 1 & -2 \\\\\n\\end{pmatrix}\n~\n\\begin{pmatrix}\n\\vartheta(t, x^{0}) \\\\\n\\vartheta(t, x^{1}) \\\\\n\\vdots \\\\\n\\vartheta(t, x^{N-1}) \\\\\n\\end{pmatrix}.$\n\"\n\n# ╔═╡ 3487893a-915c-11eb-3a04-1fdd31009413\nN = 101 # Number of grid elements\n\n# ╔═╡ 39663578-915c-11eb-108c-2718b706729e\nΔx = L/(N-1) # Finite discretization   \n\n# ╔═╡ 3468092a-915c-11eb-1719-d1b9b04b68e0\n# Diffusion matrix\nM = spdiagm(-1 => ones(N-1), 0 => -2*ones(N), 1 => ones(N-1));\n\n# ╔═╡ 344c1bb6-915c-11eb-2be7-35f340f4caa8\nMatrix(M)[1:5,1:5]\n\n# ╔═╡ 342fe676-915c-11eb-3f22-1d20d5b502ed\nmd\"### Approximated boundary conditions\n\nThe spatial approximation of the heat equation \n\n$\\frac{\\partial^2 \\vartheta(t,x)}{\\partial x^2} \\approx \\frac{1}{\\Delta x^2} \\left( \\vartheta(\\cdot, x^{n-1}) - 2 ~ \\vartheta(\\cdot, x^{n}) + \\vartheta(\\cdot, x^{n+1}) \\right)$\n\ncan not be evaluated directly at the grid points $x^{0}$ and $x^{N-1}$ because they depend on values from the not-existing grid points $x^{-1}$ and $x^{N}$. Therefore, the Neumann boundary condition is used to find $\\vartheta(\\cdot, x^{-1})$ and $\\vartheta(\\cdot, x^{N})$.\n\nThe Robin boundary condition states that the heat flux at both sides is described by\n\n$\\lambda \\left. \\frac{\\partial \\vartheta(\\cdot,x)}{\\partial x}  \\right\\rvert_{x = 0} \\cdot \\vec{n} = -1 \\cdot \\lambda \\frac{\\vartheta(\\cdot, x^{1}) - \\vartheta(\\cdot, x^{-1})}{2 \\Delta x}   = \\phi_{out}(t,x^{0})$\n\non the left boundary and \n\n$\\lambda \\left. \\frac{\\partial \\vartheta(\\cdot,x)}{\\partial x}  \\right\\rvert_{x = L} \\cdot \\vec{n} = \\lambda \\frac{\\vartheta(\\cdot, x^{N}) - \\vartheta(\\cdot, x^{N-2})}{2 \\Delta x}  = \\phi_{out}(t,x^{N-1})$\n\non the right boundary. Reformulating both equations lead to \n\n$\\vartheta(\\cdot, x^{-1}) = \\vartheta(\\cdot, x^{1}) + 2 \\Delta x ~ \\phi_{out}(t,x^{0})$\n\nand\n\n$\\vartheta(\\cdot, x^{N}) = \\vartheta(\\cdot, x^{N-2})  + 2 \\Delta x ~ \\phi_{out}(t,x^{N-1}).$\n\nOn the left boundary one yields \n\n$\\left. \\frac{\\partial^2 \\vartheta(t,x)}{\\partial x^2} \\right\\rvert_{x = 0} \\approx \\frac{1}{\\Delta x^2} \\left( - 2 ~ \\vartheta(\\cdot, x^{0}) + 2 ~ \\vartheta(\\cdot, x^{1}) \\right) + \\frac{2}{\\Delta x} \\phi_{out}(t,x^{0})$\n\nand analog on the right boundary\n\n$\\left. \\frac{\\partial^2 \\vartheta(t,x)}{\\partial x^2} \\right\\rvert_{x = 0} \\approx \\frac{1}{\\Delta x^2} \\left(2 ~ \\vartheta(\\cdot, x^{N-2}) - 2 ~ \\vartheta(\\cdot, x^{N-1}) \\right) + \\frac{2}{\\Delta x} \\phi_{out}(t,x^{N-1}).$\n\nThe diffusion matrix and the approximated flux are noted as\n\n$M = \n\\begin{pmatrix}\n-2 & 2 & 0 & \\cdots &  & 0 \\\\\n1 & -2 & 1 & 0  & \\cdots & \\vdots \\\\\n0 & 1 & -2 & 1 & \\ddots &  \\\\\n & & \\ddots & \\ddots & \\ddots &  & \\\\\n& & & 1 & -2 & 1 \\\\\n& & &  & 2 & -2 \\\\\n\\end{pmatrix}, \\quad\n\n\\Phi_{out}(t) = \n\\begin{pmatrix}\n\\phi_{out}(t, x^{0}) \\\\\n0 \\\\\n\\vdots \\\\\n\\\\\n0 \\\\\n\\phi_{out}(t, x^{N-1}) \\\\\n\\end{pmatrix}.$\n\"\n\n\n# ╔═╡ 3414b70c-915c-11eb-2606-4d1ad425d3ab\n# First row\nM[1,2] = 2;\n\n# ╔═╡ 33cd51a0-915c-11eb-3c62-efc367e08126\n# Last row\nM[end,end-1] = 2;\n\n# ╔═╡ 33af0164-915c-11eb-30f0-313d926c2dae\nmd\"### Heat equation as ODE\n\nAfter the spatial approximation the heat equation has a form of \n\n$\\dot{\\theta}(t) =  \\frac{\\alpha}{\\Delta x^2} ~ M ~ \\theta(t) + \\frac{2 \\alpha}{\\Delta x} ~ \\Phi_{out}(t)$\n\nwith M as diffusion matrix, temperature vector $\\quad \\theta(t) = \\left( \\vartheta(t, x^{0}), \\cdots, \\vartheta(t, x^{N-1}) \\right)^{\\top}$. This is an ordinary differential equation (ODE) that can be solved with common solvers like forward Euler method or Runge-Kutta scheme.\"\n\n# ╔═╡ 328a1ed0-9160-11eb-0892-7d0a9d05a54d\n# Heat Equation as ODE\nfunction heat_eq!(dθ, θ, p, t)\n\t\n\tN = size(θ)\n\tΦout = zeros(N);\n\t\n\tΦout[1] = -h * (θ[1] - θamb) - k*(θ[1]^4 - θamb^4)\n\n\tΦout[end] = -h * (θ[end] - θamb) - k*(θ[end]^4 - θamb^4)\n\n    dθ .= (1/Δx^2) * α * M * θ + (2/Δx) * α * Φout\nend\n\n# ╔═╡ 66d5aee4-9161-11eb-1ef1-2193d9c2f6a2\nmd\"### Initial Conditions\n\nFor simplicity, the initial data of the heat equation is assumed as $\\vartheta_{0}(x)= 1000$ Kelvin for all $x \\in \\left[0,L\\right]$. This function is approximated to gain the initial conditions of the ODE \n\n$\\theta(0) = \\left( 10^3, \\cdots , 10^3 \\right)^{\\top}.$\n\"\n\n# ╔═╡ 91a272be-9162-11eb-1046-8dd9e33653e5\nθ₀ = 10^3 * ones(N)\n\n# ╔═╡ 1571f3f2-9162-11eb-0b63-ff4e25a07572\nmd\"The upper limit of the sampling time has to \n\n$\\Delta t < \\frac{1}{2} \\frac{\\Delta x^2}{\\alpha}.$\n\nto guarantee numerical stability.\"\n\n# ╔═╡ f85a2d4a-9161-11eb-0e0f-851c0750832a\nΔt_ul = (0.5*Δx^2)/α # upper limit of sampling time\n\n# ╔═╡ 5aa78f74-9162-11eb-1bd4-c96f2b90e586\nΔt = 10^(-2) # Sampling time\n\n# ╔═╡ 66ba8b22-9162-11eb-13b0-b14dfcead641\nmd\"## Simulation\"\n\n# ╔═╡ 861018de-9162-11eb-2a01-2354acd868e2\ntspan = (0.0, Tf)\n\n# ╔═╡ e0e033e8-9162-11eb-3fe6-05565991ce77\n# 1-dimensional grid\nxspan = 0 : Δx : L\n\n# ╔═╡ 01b373f0-9163-11eb-3f35-3f645825720f\nprob = ODEProblem( heat_eq!, θ₀, tspan ) # ODE Problem\n\n# ╔═╡ 0103888c-9163-11eb-16ae-371cd6d04c45\nsol = solve(prob,Euler(),dt=Δt,progress=true, save_everystep=false, save_start=true) # Solving the ODE\n\n# ╔═╡ 08dcb90e-9163-11eb-2ff0-7129add62934\nplot(xspan, sol.u[2], xlabel = \"Position x\", ylabel=\"Temperature\", legend=false)\n\n# ╔═╡ Cell order:\n# ╟─44df6004-9158-11eb-1a63-651d7dca957b\n# ╠═aff71d6e-9158-11eb-0559-cb7334f4a624\n# ╠═3771dab8-9159-11eb-3a69-cd9b94a10399\n# ╟─44dbf81c-9159-11eb-2920-27ee60a7db9a\n# ╠═86a40dc8-9158-11eb-16a3-1f776d6bde4e\n# ╠═9e8ee0a2-9158-11eb-0210-4513221b7823\n# ╟─a4f1e1e2-9158-11eb-0754-a70399a341ba\n# ╠═7c9e9a4a-9159-11eb-3dda-59d2aa15f32a\n# ╠═c5da798e-9160-11eb-1d16-75ce792ef2fe\n# ╟─7c80218c-9159-11eb-301a-95a428fb76d9\n# ╠═7c62a2c4-9159-11eb-1b54-452017ea90d9\n# ╠═3487893a-915c-11eb-3a04-1fdd31009413\n# ╠═39663578-915c-11eb-108c-2718b706729e\n# ╠═3468092a-915c-11eb-1719-d1b9b04b68e0\n# ╠═344c1bb6-915c-11eb-2be7-35f340f4caa8\n# ╟─342fe676-915c-11eb-3f22-1d20d5b502ed\n# ╠═3414b70c-915c-11eb-2606-4d1ad425d3ab\n# ╠═33cd51a0-915c-11eb-3c62-efc367e08126\n# ╟─33af0164-915c-11eb-30f0-313d926c2dae\n# ╠═328a1ed0-9160-11eb-0892-7d0a9d05a54d\n# ╟─66d5aee4-9161-11eb-1ef1-2193d9c2f6a2\n# ╠═91a272be-9162-11eb-1046-8dd9e33653e5\n# ╟─1571f3f2-9162-11eb-0b63-ff4e25a07572\n# ╠═f85a2d4a-9161-11eb-0e0f-851c0750832a\n# ╠═5aa78f74-9162-11eb-1bd4-c96f2b90e586\n# ╠═66ba8b22-9162-11eb-13b0-b14dfcead641\n# ╠═7ad16586-9162-11eb-1d94-5188eb8d4c5d\n# ╠═861018de-9162-11eb-2a01-2354acd868e2\n# ╠═e0e033e8-9162-11eb-3fe6-05565991ce77\n# ╠═01b373f0-9163-11eb-3f35-3f645825720f\n# ╠═0103888c-9163-11eb-16ae-371cd6d04c45\n# ╠═08dcb90e-9163-11eb-2ff0-7129add62934\n", "meta": {"hexsha": "6b4bcf97e9d5376336106021e2d30a4631747864", "size": 10317, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/modeling/robin_numerical.jl", "max_stars_repo_name": "stephans3/IntroHeatEquation.jl", "max_stars_repo_head_hexsha": "37e9c9ededeb7cdfc2ffb0c11ac1661d157a0288", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/modeling/robin_numerical.jl", "max_issues_repo_name": "stephans3/IntroHeatEquation.jl", "max_issues_repo_head_hexsha": "37e9c9ededeb7cdfc2ffb0c11ac1661d157a0288", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/modeling/robin_numerical.jl", "max_forks_repo_name": "stephans3/IntroHeatEquation.jl", "max_forks_repo_head_hexsha": "37e9c9ededeb7cdfc2ffb0c11ac1661d157a0288", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2116040956, "max_line_length": 298, "alphanum_fraction": 0.6623049336, "num_tokens": 4620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.919642531177793, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7703109413809924}}
{"text": "# sample from a double well in 1D using HMC\nusing Printf\nusing Random\nusing LinearAlgebra\nusing ForwardDiff\nusing QuadGK\nusing BasicMD\nusing Statistics\n\ninclude(\"potentials.jl\")\n\nβ = 5.0;\nx₀ = [-1.0];\nM = 1.0;\nseed = 100;\nΔt = 2e-1;\nn_iters = 10^4; # number of samples\nnΔt = 10^1; # number of Verlet steps per HMC iteration\nn_save_iters=10;\n\nV = x->DoubleWell(x);\ncfg = ForwardDiff.GradientConfig(V, x₀);\ngradV! = (gradV, x)-> ForwardDiff.gradient!(gradV, V, x, cfg);\n\n# second moment and energy obsrevables\nf₁ = x-> x[1]^2;\nf₂ = x-> V(x[1]);\nobservables = (f₁, f₂);\n\nsampler = HMC(V, gradV!, β, M, Δt, nΔt);\n\nRandom.seed!(100);\nXvals,_ = sample_trajectory(x₀, sampler, options=MDOptions(n_iters=n_iters,n_save_iters=n_save_iters));\nf₁_estimate = mean(f₁.(Xvals));\nf₂_estimate = mean(f₂.(Xvals));\n@printf(\"f₁ estimate with %d samples: %g\\n\",length(Xvals), f₁_estimate);\n@printf(\"f₂ estimate with %d samples: %g\\n\", length(Xvals), f₂_estimate);\nRandom.seed!(100);\nobservable_samples = sample_observables(x₀, sampler, observables, options=MDOptions(n_iters=n_iters,n_save_iters=n_save_iters));\n@printf(\"f₁ estimate with %d samples: %g\\n\",length(observable_samples), mean(observable_samples[1,:]));\n@printf(\"f₂ estimate with %d samples: %g\\n\", length(observable_samples), mean(observable_samples[2,:]));\n", "meta": {"hexsha": "f28556003ed35f358c22583e07ba8dd9c2265bcc", "size": 1301, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/double_hmc2.jl", "max_stars_repo_name": "gideonsimpson/JuBasicMD", "max_stars_repo_head_hexsha": "c9580315b444af066ef7208fa3f20d0753837417", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-04-18T15:52:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-25T23:39:35.000Z", "max_issues_repo_path": "examples/double_hmc2.jl", "max_issues_repo_name": "gideonsimpson/BasicMD.jl", "max_issues_repo_head_hexsha": "2cae68a202b69aa0cac9f005a8559d55613f23be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-16T19:39:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-19T01:43:16.000Z", "max_forks_repo_path": "examples/double_hmc2.jl", "max_forks_repo_name": "gideonsimpson/BasicMD.jl", "max_forks_repo_head_hexsha": "2cae68a202b69aa0cac9f005a8559d55613f23be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-15T16:47:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-15T16:47:46.000Z", "avg_line_length": 30.9761904762, "max_line_length": 128, "alphanum_fraction": 0.7202152191, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642526773001, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7703109376914506}}
{"text": "\"\"\"\n    gammaHSIC(X::Vector{T}, Y::Vector{T})\n\n\"\"\"\n\nfunction gammaHSIC(X::Vector{T}, Y::Vector{T}; randomSubSet = 100, kernelSize = -1) where {T<:Real}\n\n\tM = length(X)\n\n\t# get kernel sizes\n\tif kernelSize == -1\n\t\tsigx = estimateKernelSize(X, sampleSize = randomSubSet)\n\t\tsigy = estimateKernelSize(Y, sampleSize = randomSubSet)\n\telse\n\t\tsigx = kernelSize\n\t\tsigy = kernelSize\n\tend\n\n\tbone = ones(T, M, 1)\n\tH = eye(M) - 1/M * ones(T, M,M)\n\n\tK = rbfDotProduct(X, X, sigx)\n\tL = rbfDotProduct(Y, Y, sigy)\n\n\t# NOTE: these are slightly biased estimates of centred Gram matrices\n\tKc = H*K*H\n\tLc = H*L*H\n\n\t# NOTE: we fit Gamma to testStat*M\n\ttestStat = 1/M * sum(sum(Kc'.*Lc))\n\n\tvarHSIC = (1/6 * Kc.*Lc).^2\n\tvarHSIC = 1/M/(M-1)* (  sum(sum(varHSIC)) - sum(diag(varHSIC))  ) # second subtracted term is bias correction\n\tvarHSIC = 72*(M-4)*(M-5)/M/(M-1)/(M-2)/(M-3) * varHSIC\n\n\tK = K-diagm(0 => diag(K))\n\tL = L-diagm(0 => diag(L))\n\n\tmuX = 1/M/(M-1)*bone'*(K*bone)\n\tmuY = 1/M/(M-1)*bone'*(L*bone)\n\n\tmHSIC  = 1/M * ( 1 .+muX*muY - muX - muY )\n\n\tal = mHSIC^2 / varHSIC\n\tbet = varHSIC*M ./ mHSIC\n\n\treturn 1 - gammacdf(al[1], bet[1], testStat)\n\nend\n", "meta": {"hexsha": "ffe9fb58e222f8806f0972c436a4cc0ed8d3ddf0", "size": 1129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gammaHSIC.jl", "max_stars_repo_name": "millerjoey/HilbertSchmidtIndependenceCriterion.jl", "max_stars_repo_head_hexsha": "fe0d1407ea8f054ecbedb3aa9b1e88eb17f78196", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gammaHSIC.jl", "max_issues_repo_name": "millerjoey/HilbertSchmidtIndependenceCriterion.jl", "max_issues_repo_head_hexsha": "fe0d1407ea8f054ecbedb3aa9b1e88eb17f78196", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gammaHSIC.jl", "max_forks_repo_name": "millerjoey/HilbertSchmidtIndependenceCriterion.jl", "max_forks_repo_head_hexsha": "fe0d1407ea8f054ecbedb3aa9b1e88eb17f78196", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.58, "max_line_length": 110, "alphanum_fraction": 0.6085031001, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7703109358275668}}
{"text": "# I.Y. Kim and O.L. de Weck.  Adaptive weighted-sum method for bi-objective optimization\n# Pareto front generation. Structural and Multidisciplinary Optimization.\n# Vol. 29, Num. 2, pp. 149–158, 2005.\n# https://link.springer.com/article/10.1007/s00158-004-0465-1\n\nusing NSGAIII, PyPlot\n\nfunction plot_pop(P)\n    clf()\n    p = plot(map(x -> x.y[1], P), map(x -> x.y[2], P), \"bo\", markersize=1)\n    !isinteractive() && show()\n    sleep(0.2)\nend\n\n\nconst d = RealCoding(8, [-3, -3], [3, 3])\nz1(x1, x2) = -(3(1-x1)^2 * exp(-x1^2 - (x2+1)^2) - 10(x1/5 - x1^3 - x2^5) * exp(-x1^2-x2^2) -3exp(-(x1+2)^2 - x2^2) + 0.5(2x1 + x2))\nz2(x1, x2) = -(3(1+x2)^2 * exp(-x2^2 - (1-x1)^2) - 10(-x2/5 + x2^3 + x1^5) * exp(-x1^2-x2^2) - 3exp(-(2-x2)^2 - x1^2))\nz(x) = begin \n    x1, x2 = decode(x, d)\n    z1(x1, x2), z2(x1, x2)\nend\nnsga(300, 20, ()->bitrand(d.nbbitstotal), z, 10, fplot = plot_pop)\n", "meta": {"hexsha": "d8275da99690cf7b0c557483636d179d3ee8fdb8", "size": 877, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/KIM_NLP.jl", "max_stars_repo_name": "russelljjarvis/NSGAIII.jl", "max_stars_repo_head_hexsha": "6ef30a61c4d50db8a960761d782da26c3d8a9f89", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-10-15T07:12:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-15T07:12:32.000Z", "max_issues_repo_path": "examples/KIM_NLP.jl", "max_issues_repo_name": "russelljjarvis/NSGAIII.jl", "max_issues_repo_head_hexsha": "6ef30a61c4d50db8a960761d782da26c3d8a9f89", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/KIM_NLP.jl", "max_forks_repo_name": "russelljjarvis/NSGAIII.jl", "max_forks_repo_head_hexsha": "6ef30a61c4d50db8a960761d782da26c3d8a9f89", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-02T11:01:40.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-02T11:01:40.000Z", "avg_line_length": 36.5416666667, "max_line_length": 132, "alphanum_fraction": 0.5781071836, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7703109340019086}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.0\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 5bb6cf00-9b75-4e74-bc75-6a059bc1b32d\n# Učita se paket SymPy\nusing SymPy\n\n# ╔═╡ efc1cf20-8276-11eb-39ba-bd62a4342e68\nmd\"\n# Integrali racionalnih funkcija\n\"\n\n# ╔═╡ d52c1d09-9bee-4359-8e2c-a969a2f32ea3\n# Ova naredba daje popis svih djelova paketa, uglavnom su to funkcije.\n# varinfo(SymPy)\n\n# ╔═╡ 8153dabd-5be6-4308-b7c5-1f4ed54722ab\nbegin\n\t# Izračunajmo nekoliko integrala.\n\tx=Sym(\"x\")\n\tintegrate(x^2*sin(x))\nend\n\n# ╔═╡ 10b872ad-f070-404c-9ec8-19f0bc2032c5\nintegrate(exp(-x^2))\n\n# ╔═╡ 056c397f-7303-464e-9ec6-8cf893bbc98c\n# Primjer rekurzivne formule. Ovo traje malo duže\nintegrate(1/(1+x^2)^13)\n\n# ╔═╡ b29b5f68-8978-4b4b-9b29-4840a4097978\n# Kraća rekurzivna formula\nintegrate(1/(1+x^2)^3)\n\n# ╔═╡ 232dcad5-1984-4421-9c1a-001406096217\nmethods(diff)\n\n# ╔═╡ a2819cd4-d0b3-476a-ab8c-40838db72d54\n# Derivacija\ndiff(x^2*exp(sin(1/x)))\n\n# ╔═╡ 74af42dd-9768-4e91-aa3b-b26c69d6fb68\n# Racionalna funkcija trigonometrijskih funkcija (univerzalna trigonometrijska supstitucija)\nintegrate(1/((2+cos(x))*sin(x)))\n\n# ╔═╡ de024987-9c44-4199-9085-b259980e94a5\nmd\"\"\"\n#### Zadatak 1.5.e)\n\"\"\"\n\n# ╔═╡ 62c5d76c-9eef-40a9-b8c9-446720733f80\nintegrate(1/(4*sin(x)+3*cos(x)+5))\n\n# ╔═╡ 379bc6e9-7a38-4f3e-8e4a-2ff80917880b\nintegrate(1/(sin(x)*(2+cos(x)-2*sin(x))))\n\n# ╔═╡ 28dd8649-ed7c-47e5-b7ab-69e99dc0ce86\n# Ovo traje beskonačno?\n# integrate(cos(x)^3/(sin(x)^2+sin(x)))\n\n# ╔═╡ 12904f05-67c3-4d8a-aefd-e9645e6ef0eb\n# Ovo je isti zadatak kao gore, ali traje kratko. Koristi se jednostavnija supstitucija.\nintegrate((1-sin(x)^2)*cos(x)/(sin(x)^2+sin(x)))\n\n# ╔═╡ bf1829c9-b2fb-4e3b-b92d-38a93513678b\n# Ovo traje jako dugo i ne uspije izračunati nego vrati polazni integral\n# integrate( (2*tan(x)+3)/(sin(x)^2+2*cos(x)^2))\n\n# ╔═╡ 3732f5f7-ed44-4254-8b16-d9d860d2c04f\nmd\"\"\"\nUz supstituciju $t=\\tan(x)$ integral postaje jednostavan:\n\"\"\"\n\n# ╔═╡ 232927bc-ac81-4225-801f-9da5e5842d6d\nbegin\n\tt=Sym(\"t\")\n\tI₁=integrate( (2*t+3)/(t^2+2))\nend\n\n# ╔═╡ 13e53f50-8c7d-403c-85c5-848bf2ccbe94\nbegin\n\t# Vratimo supstituciju natrag\n\tI₂=convert(Function,I₁)\n\tI₂(tan(x))\nend\n\n# ╔═╡ d9ada9db-2651-4895-876b-704e4ed05bcb\nmd\"\"\"\n#### Zadatak 1.6\n\"\"\"\n\n# ╔═╡ f2eb749b-51d6-4875-8e14-1e0f688cdfc7\n# Ovo traje beskonačno!\n# I₄=integrate((1+sinh(x))/((2+cosh(x))*(3+sinh(x))),x)\n# Program treba našu pomoć!!!\n\n# ╔═╡ 244208a5-b153-424b-8305-5b6002fd8186\nmd\"\"\"\n__Univerzalna hiperbolna supstitucija__\n\n$$\\begin{aligned}\nt&=\\tanh(\\frac{x}{2}), \\quad x=2\\mathop{\\mathrm{atanh}}(t),\\quad  dx=\\displaystyle\\frac{2}{1-t^2}dt,\\\\\n\\sinh(x)&=\\displaystyle\\frac{2t}{1-t^2}, \\quad \\cosh(x)=\\displaystyle\\frac{1+t^2}{1-t^2}.\\end{aligned}$$\n\n\"\"\"\n\n# ╔═╡ 78acc71b-b314-4799-b633-4ab5b7958496\nI₄=(1+sinh(x))/((2+cosh(x))*(3+sinh(x)))\n\n# ╔═╡ 463c1ac7-e503-4507-8aca-d671acf04d36\n# supstitucija za sinh(x)\nI₅=subs(I₄,sinh(x),(2*t)/(1-t^2))\n\n# ╔═╡ 1b47139d-6c06-4227-91d2-1556d2f3a9d2\n# Supstitucija za cosh(x)\nI₆=subs(I₅,cosh(x),(1+t^2)/(1-t^2))\n\n# ╔═╡ 646c21be-c589-43b6-b648-3d0dea8353db\n# Pomnožimo s dx\nI₇=I₆*2/(1-t^2)\n\n# ╔═╡ 34320cf9-d978-46ca-ace2-ea638cc602d7\n# Integriramo racionalnu funkciju\nI₈=integrate(I₇,t)\n\n# ╔═╡ 6e0e6146-fefa-4967-938e-1755a0a04607\n# Vratimo supstituciju natrag\nI₉=subs(I₈,t,tanh(x/2))\n\n# ╔═╡ a817a9d1-f9d2-4fb9-ad16-2477a0a6dea6\n\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nSymPy = \"24249f21-da20-56a4-8eb1-6a02cf4ae2e6\"\n\n[compat]\nSymPy = \"~1.0.52\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"a325370b9dd0e6bf5656a6f1a7ae80755f8ccc46\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.7.2\"\n\n[[CommonEq]]\ngit-tree-sha1 = \"d1beba82ceee6dc0fce8cb6b80bf600bbde66381\"\nuuid = \"3709ef60-1bee-4518-9f2f-acd86f176c50\"\nversion = \"0.2.0\"\n\n[[CommonSolve]]\ngit-tree-sha1 = \"68a0743f578349ada8bc911a5cbd5a2ef6ed6d1f\"\nuuid = \"38540f10-b2f7-11e9-35d8-d573e4eb0ff2\"\nversion = \"0.2.0\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"31d0151f5716b655421d9d75b7fa74cc4e744df2\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.39.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Conda]]\ndeps = [\"JSON\", \"VersionParsing\"]\ngit-tree-sha1 = \"299304989a5e6473d985212c28928899c74e9421\"\nuuid = \"8f4d0f93-b110-5947-807f-2305c1781a2d\"\nversion = \"1.5.2\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"a32185f5428d3986f47c2ab78b1f216d5e6cc96f\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.5\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"f76424439413893a832026ca355fe273e93bce94\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"DocStringExtensions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"34dc30f868e368f8a17b728a1238f3fcda43931a\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.3\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"5a5bc6bf062f0f95e62d0fe0a2d99699fed82dd9\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.8\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"a8709b968a1ea6abc2dc1967cb1db6ac9a00dfb6\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.5\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[PyCall]]\ndeps = [\"Conda\", \"Dates\", \"Libdl\", \"LinearAlgebra\", \"MacroTools\", \"Serialization\", \"VersionParsing\"]\ngit-tree-sha1 = \"169bb8ea6b1b143c5cf57df6d34d022a7b60c6db\"\nuuid = \"438e738f-606a-5dbb-bf0a-cddfbfd45ab0\"\nversion = \"1.92.3\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"44a75aa7a527910ee3d1751d1f0e4148698add9e\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.2\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"793793f1df98e3d7d554b65a107e9c9a6399a6ed\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.7.0\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[SymPy]]\ndeps = [\"CommonEq\", \"CommonSolve\", \"LinearAlgebra\", \"Markdown\", \"PyCall\", \"RecipesBase\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"1ef257ecbcab8058595a68ca36a6844b41babcbd\"\nuuid = \"24249f21-da20-56a4-8eb1-6a02cf4ae2e6\"\nversion = \"1.0.52\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[VersionParsing]]\ngit-tree-sha1 = \"80229be1f670524750d905f8fc8148e5a8c4537f\"\nuuid = \"81def892-9a0e-5fdd-b105-ffc91e053289\"\nversion = \"1.2.0\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─efc1cf20-8276-11eb-39ba-bd62a4342e68\n# ╠═5bb6cf00-9b75-4e74-bc75-6a059bc1b32d\n# ╠═d52c1d09-9bee-4359-8e2c-a969a2f32ea3\n# ╠═8153dabd-5be6-4308-b7c5-1f4ed54722ab\n# ╠═10b872ad-f070-404c-9ec8-19f0bc2032c5\n# ╠═056c397f-7303-464e-9ec6-8cf893bbc98c\n# ╠═b29b5f68-8978-4b4b-9b29-4840a4097978\n# ╠═232dcad5-1984-4421-9c1a-001406096217\n# ╠═a2819cd4-d0b3-476a-ab8c-40838db72d54\n# ╠═74af42dd-9768-4e91-aa3b-b26c69d6fb68\n# ╟─de024987-9c44-4199-9085-b259980e94a5\n# ╠═62c5d76c-9eef-40a9-b8c9-446720733f80\n# ╠═379bc6e9-7a38-4f3e-8e4a-2ff80917880b\n# ╠═28dd8649-ed7c-47e5-b7ab-69e99dc0ce86\n# ╠═12904f05-67c3-4d8a-aefd-e9645e6ef0eb\n# ╠═bf1829c9-b2fb-4e3b-b92d-38a93513678b\n# ╟─3732f5f7-ed44-4254-8b16-d9d860d2c04f\n# ╠═232927bc-ac81-4225-801f-9da5e5842d6d\n# ╠═13e53f50-8c7d-403c-85c5-848bf2ccbe94\n# ╟─d9ada9db-2651-4895-876b-704e4ed05bcb\n# ╠═f2eb749b-51d6-4875-8e14-1e0f688cdfc7\n# ╟─244208a5-b153-424b-8305-5b6002fd8186\n# ╠═78acc71b-b314-4799-b633-4ab5b7958496\n# ╠═463c1ac7-e503-4507-8aca-d671acf04d36\n# ╠═1b47139d-6c06-4227-91d2-1556d2f3a9d2\n# ╠═646c21be-c589-43b6-b648-3d0dea8353db\n# ╠═34320cf9-d978-46ca-ace2-ea638cc602d7\n# ╠═6e0e6146-fefa-4967-938e-1755a0a04607\n# ╠═a817a9d1-f9d2-4fb9-ad16-2477a0a6dea6\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "52b8d537f81dd5a4e06985e594d397e526ed750c", "size": 12114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Pluto/Integrali.jl", "max_stars_repo_name": "ivanslapnicar/Matematika", "max_stars_repo_head_hexsha": "6ec31e97470cb10e1e0505421461ede257d64035", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-13T12:02:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-13T12:02:36.000Z", "max_issues_repo_path": "Pluto/Integrali.jl", "max_issues_repo_name": "ivanslapnicar/Matematika", "max_issues_repo_head_hexsha": "6ec31e97470cb10e1e0505421461ede257d64035", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Pluto/Integrali.jl", "max_forks_repo_name": "ivanslapnicar/Matematika", "max_forks_repo_head_hexsha": "6ec31e97470cb10e1e0505421461ede257d64035", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5945330296, "max_line_length": 280, "alphanum_fraction": 0.7237081063, "num_tokens": 5950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7702902057459544}}
{"text": "\"\"\"\n    eom_logistic2(dx, x, p, n) -> function\n\nEquations of motions for a system consisting of two coupled logistic maps where\nX unidirectionally influences Y.\n\nThe parameter `c` controls how strong the dynamical forcing is. Parameters `r₁`\nand `r₂` are set to the chaotic regime by default\n\n# References\n1. Diego, D., Agasøster Haaga, K., & Hannisdal, B. (2018, November 1).\nTransfer entropy computation using the Perron-Frobenius operator.\nEprint ArXiv:1811.01677. Retrieved from\nhttps://ui.adsabs.harvard.edu/#abs/2018arXiv181101677D\n\"\"\"\nfunction eom_logistic2(dx, x, p, n)\n    c, r₁, r₂, σ = (p...,)\n    ξ = rand() # random number from flat distribution on [0, 1]\n    x, y = x[1], x[2]\n    f_xy = (y +  (c*(x + σ*ξ)/2) ) / (1 + (c/2)*(1+σ))\n\n    dx[1] = r₁ * x * (1 - x)\n    dx[2] = r₂ * (f_xy) * (1 - f_xy)\n    return\nend\n\nfunction logistic2(u₀, c, r₁, r₂, σ)\n    p = [c, r₁, r₂, σ]\n    DiscreteDynamicalSystem(eom_logistic2, u₀, p)\nend\n\n\"\"\"\n    logistic2(;u₀ = rand(2), c = 0.1, σ = 0.05,\n        r₁ = 3.78, r₂ = 3.66) -> DiscreteDynamicalSystem\n\nInitialise a system consisting of two coupled logistic maps where X\nunidirectionally influences Y. By default, the parameters `r₁` and `r₂` are set\nto values yielding chaotic behaviour.\n\nThe parameter `c` controls how strong the dynamical forcing is. If `σ > 0`,\ndynamical noise masking the influence of  `x` on `y` equivalent to\n``\\\\sigma \\\\cdot \\\\xi`` is added at each iteration. Here,``\\\\xi`` is a draw from a\nflat distribution on ``[0, 1]``. Thus, setting `σ = 0.05` is equivalent to\nadd dynamical noise corresponding to a maximum of ``5 \\\\%`` of the possible\nrange of values of the logistic map.\n\n\n\nThe equations of motion are\n\n```math\n\\\\begin{aligned}\ndx &= r_1 x(1 - x) \\\\\ndy &= r_2 f(x,y)(1 - f(x,y)),\n\\\\end{aligned}\n```\nwith\n```math\n\\\\begin{aligned}\nf(x,y) = \\\\dfrac{y + \\\\frac{c(x \\\\xi )}{2}}{1 + \\\\frac{c}{2}(1+ \\\\sigma )}\n\\\\end{aligned}\n```\n\nwhere\n\n# References\n\n1. Diego, D., Agasøster Haaga, K., & Hannisdal, B. (2018, November 1).\nTransfer entropy computation using the Perron-Frobenius operator.\nEprint ArXiv:1811.01677. Retrieved from\nhttps://ui.adsabs.harvard.edu/#abs/2018arXiv181101677D\n\n\"\"\"\nlogistic2(;u₀ = rand(2), c = 0.1, r₁ = 3.78, r₂ = 3.66, σ = 0.05) =\n    logistic2(u₀, c, r₁, r₂, σ)\n", "meta": {"hexsha": "ede9ac9b3ad19c6fada76c3977c31ab432c7c4ec", "size": 2266, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/systems/discretemaps/logistic2.jl", "max_stars_repo_name": "tormolle/CausalityTools.jl", "max_stars_repo_head_hexsha": "b8c1014349358d8cdb5eddc1bcac9303f475d90b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/systems/discretemaps/logistic2.jl", "max_issues_repo_name": "tormolle/CausalityTools.jl", "max_issues_repo_head_hexsha": "b8c1014349358d8cdb5eddc1bcac9303f475d90b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/systems/discretemaps/logistic2.jl", "max_forks_repo_name": "tormolle/CausalityTools.jl", "max_forks_repo_head_hexsha": "b8c1014349358d8cdb5eddc1bcac9303f475d90b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8157894737, "max_line_length": 82, "alphanum_fraction": 0.6553398058, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7702902056282193}}
{"text": "#\n#Simple example of a Poisson problem:\n#\n#           y\n#             |\n#             |           u_y = 0\n#          Ly ----------------------------------\n#             |                                |\n#             |                                |\n#             |                                |\n#       u = 0 |    u - u_xx - u_yy = f         | u = 0\n#             |                                |\n#             |                                |\n#             |                                |\n#           -----------------------------------|-----  x\n#                         u_y = 0               Lx\n#\n#Here, \n#\n#      u = sin(omegax x) * cos(omegay y) \n#      f = ( 1 + omegax^2 + omegay^2 ) * sin(omegax x) * cos(omegay y)\n#      omegax = nx pi / Lx\n#      omegay = ny pi / Ly\n#\n\nusing FinElt\nusing FinElt.PlanarPoisson\nusing Printf\n\ninclude(\"params.jl\")\n\nconst omegax = 3 * pi / Lx\nconst omegay = pi / Ly\n\nfunction exact_u(x)\n    return sin(omegax*x[1]) * cos(omegay*x[2]) \nend\n\nfunction f(x)\n    c = 1 + omegax^2 + omegay^2\n    return c * exact_u(x)\nend\n\nell_f(v, z) = P1SourceTimesFunc!(v, z, f)\nlin_functionals = [ (\"Omega\", ell_f) ]\n\nmaxerr = zeros(refinements+1)\n@printf(\"%10s  %12s  %8s  %8s\\n\\n\", \n        \"N\", \"max error\", \"rate\", \"seconds\")\nfor k = 0:refinements\n    start = time()\n    mesh = read_msh_file(\"rect$k.msh\")    \n    vp = VariationalProblem(mesh, [\"Left\", \"Right\"])\n    add_bilin_form!(vp, \"Omega\", grad_dot_grad!)\n    add_bilin_form!(vp, \"Omega\", func_times_func!)\n    add_lin_functnl!(vp, \"Omega\", source_times_func!, f)\n    # Implicit zero boundary conditions.\n    A, b = assembled_linear_system(vp)\n    ufree = A \\ b\n    uh = complete_soln(ufree, vp)\n    u = get_nodal_vals(exact_u, mesh)\n    finish = time()\n    maxerr[k+1] = maximum(abs.(uh-u))\n    N = length(ufree)\n    if k == 0\n        @printf(\"%10d  %12.4e\\n\", N, maxerr[k+1])\n    else\n        rate = log2(maxerr[k]/maxerr[k+1])\n        elapsed = finish - start\n        @printf(\"%10d  %12.4e  %8.4f  %8.4f\\n\", \n                N, maxerr[k+1], rate, elapsed)\n    end\nend\n\n", "meta": {"hexsha": "178e963325645db24c97b838dd22d76363d23910", "size": 2067, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/rectangle/poisson.jl", "max_stars_repo_name": "billmclean/FinElt.jl", "max_stars_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-07-18T20:04:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:29:09.000Z", "max_issues_repo_path": "examples/rectangle/poisson.jl", "max_issues_repo_name": "billmclean/FinElt.jl", "max_issues_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/rectangle/poisson.jl", "max_forks_repo_name": "billmclean/FinElt.jl", "max_forks_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-06-29T15:15:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T18:01:08.000Z", "avg_line_length": 27.56, "max_line_length": 70, "alphanum_fraction": 0.4378326076, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7702902055104837}}
{"text": "using LinearAlgebraicRepresentation\nusing SparseArrays\nLar = LinearAlgebraicRepresentation\nL = Lar\nusing ViewerGL\nGL = ViewerGL\n\nfunction twocubegrids(n,m,p)\n    V,(VV,EV,FV,CV) = Lar.cuboidGrid([n,m,p],true)\n    mybox = (V,CV,FV,EV)\n\n    twocubs = Lar.Struct([mybox, L.t(.3,.4,.5), L.r(pi/5,0,0), L.r(0,0,pi/12), mybox])\n\n    V,CV,FV,EV = Lar.struct2lar(twocubs)\n    GL.VIEW([ GL.GLGrid(V,FV, GL.COLORS[1]) ]);\n\n    cop_EV = Lar.coboundary_0(EV::Lar.Cells);\n    cop_EW = convert(Lar.ChainOp, cop_EV);\n    cop_FE = Lar.coboundary_1(V, FV::Lar.Cells, EV::Lar.Cells);\n    W = convert(Lar.Points, V');\n\n    V, copEV, copFE, copCF = Lar.Arrangement.spatial_arrangement( W, cop_EW, cop_FE)\n\n    EV = Lar.cop2lar(copEV)\n    FE = [findnz(copFE[k,:])[1] for k=1:size(copFE,1)]\n    FV = [collect(Set(cat(EV[e] for e in FE[f]))) for f=1:length(FE)]\n    FV = convert(Lar.Cells, FV)\n    W = convert(Lar.Points, V')\n    WW = [[k] for k=1:size(W,2)]\n\n    #GL.VIEW(GL.numbering(.2)((W,[WW,EV])));\n\n    V,CVs,FVs,EVs = Lar.pols2tria(W, copEV, copFE, copCF)\n    GL.VIEW(GL.GLExplode(V,FVs,1.5,1.5,1.5,99,1));\n    GL.VIEW(GL.GLExplode(V,EVs,1.5,1.5,1.5,99,1));\n    GL.VIEW(GL.GLExplode(V,CVs,5,5,5,99,1));\n\n    return V, copEV, copFE, copCF\nend\n\ntwocubegrids(5,5,5);\n", "meta": {"hexsha": "3f1926e30bd1c706af5aaee1ae49c46e48bb6df0", "size": 1249, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/3d/twocubegrids.jl", "max_stars_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_stars_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-25T16:45:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-25T16:45:01.000Z", "max_issues_repo_path": "examples/3d/twocubegrids.jl", "max_issues_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_issues_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/3d/twocubegrids.jl", "max_forks_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_forks_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7380952381, "max_line_length": 86, "alphanum_fraction": 0.6253002402, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.770290192574636}}
{"text": "# Starting example file for Julia number types\n\n# Julia defines a set of specific sub-types for numbers\n# Signed integers: Int, Int8, Int16, Int32, Int64, BigInt\na = Int16(1)\nprintln(typeof(a))\n\nb = Int(2000)\nprintln(typeof(b))\n\n# Unsigned integers: UInt, UInt8, UInt16, UInt32, UInt64\nc = UInt16(1)\nprintln(typeof(c))\n\nd = UInt(2000)\nprintln(typeof(d))\n\n# typemax() and typemin() will provide max and min values\nprintln(typemax(Int8))\nprintln(typemax(Int32))\nprintln(typemax(Int64))\nprintln(typemin(Int64))\n\n# Use the WORDSIZE property to see what type of system this is \nprintln(Sys.WORD_SIZE)\n\n# Trying to assign a number too large for the type will fail and give an error\n# CANNOT do: a = UInt(300)\n\n# Special values represent Infinity and not-a-number\nprintln(1.0 / 0.0)\nprintln(1.0 / Inf)\nprintln(0.0 / 0.0)\n\n# zero() and one() functions produce values for a given type\nprintln(zero(Float64))\nprintln(one(UInt32))", "meta": {"hexsha": "1201b1ce1e175e6736220b2976c17fc19590cbfd", "size": 919, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2_basics/02_numbers.jl", "max_stars_repo_name": "scaotravis/Julia-Course", "max_stars_repo_head_hexsha": "df88edf368d4eeae5f8c6105853b334d38481ed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2_basics/02_numbers.jl", "max_issues_repo_name": "scaotravis/Julia-Course", "max_issues_repo_head_hexsha": "df88edf368d4eeae5f8c6105853b334d38481ed9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2_basics/02_numbers.jl", "max_forks_repo_name": "scaotravis/Julia-Course", "max_forks_repo_head_hexsha": "df88edf368d4eeae5f8c6105853b334d38481ed9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8378378378, "max_line_length": 78, "alphanum_fraction": 0.733405876, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7702901906173318}}
{"text": "\n# morlet wavelet\nfunction morlet(F::T, fs::T; dtype=Float32) where {T}\n    wtime = range(-1, stop=1, length=Int(2 * fs))\n    s = 6 / ( 2 * pi * F)\n    wavelet = exp.(2im * pi * F .* wtime) .* exp.(-wtime.^2 ./ (2*s^2));\n    return wavelet |> Vector{Complex{dtype}}\nend\n\n\n\"\"\"\nfunction dwt(data, fs, frange; reflection=false, wavelet=morlet)\n\nArguments:\n- data\n- fs\n- frange\n\nKeyword Arguments:\n- reflection\n- wavelet\n\nReturn result:\n\nNote:\ndiscrete wavelet transformation by convolution between the fft results of\noriginal values and the wavelet function.\n\"\"\"\nfunction dwt(data::Vector{D}, fs::T, frange::Vector{T};\n             reflection::Bool=false, wavelet::Function=morlet) where {D, T}\n    data_fft = data\n    if reflection\n        data_flip = reverse(data_fft, dims=1)\n        data_fft = [data_flip;data_fft;data_flip]\n    end\n\n    data_fft = data_fft |> Vector{Complex{Float32}}\n    result = zeros(Complex{Float32}, size(data,1), length(frange))\n\n    for (fidx, ftarget) in enumerate(frange)\n        w = wavelet(ftarget, fs)\n        if reflection\n            result[:, fidx] = DSP.conv(data_fft, w)[Int(fs)+size(data,1):end-Int(fs)-size(data, 1)]\n        else\n            result[:, fidx] = DSP.conv(data_fft, w)[Int(fs):end-Int(fs)]\n        end\n    end\n\n    result\nend\n", "meta": {"hexsha": "b7e5b0aabe16565b901f1051f04f58e1c532dcb1", "size": 1277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LFP/Decomposition.jl", "max_stars_repo_name": "ZaneMuir/NeuroAnalysis.jl", "max_stars_repo_head_hexsha": "e1ef105e73ae0d77430f7ac85a6f98243afd68b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LFP/Decomposition.jl", "max_issues_repo_name": "ZaneMuir/NeuroAnalysis.jl", "max_issues_repo_head_hexsha": "e1ef105e73ae0d77430f7ac85a6f98243afd68b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LFP/Decomposition.jl", "max_forks_repo_name": "ZaneMuir/NeuroAnalysis.jl", "max_forks_repo_head_hexsha": "e1ef105e73ae0d77430f7ac85a6f98243afd68b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0392156863, "max_line_length": 99, "alphanum_fraction": 0.6288175411, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109784205502, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.770288043877147}}
{"text": "mutable struct LinearRegressor\n    _w::AbstractArray{Float64,1}\n    _var::Float64\nend\n\nfunction fitting(\n    regressor::LinearRegressor,\n    Phi::AbstractArray{Float64,2},\n    t::AbstractArray{Float64,1},\n)\n    # Phi is the design matrix of size (n_samples, n_feature)\n    # t is the target vector of size (sample_size, 1)\n    # `pinv(Phi)` = (Phi^T * Phi)^(-1) * Phi^T\n    w = pinv(Phi) * t\n    error = Phi * w - t\n    var = sum(error .^ 2) / size(t)[1]\n\n    regressor._w = w\n    regressor._var = var\nend\n\nfunction predict(\n    regressor::LinearRegressor,\n    phi::AbstractArray{Float64,1},\n    return_std::Bool,\n)\n    # phi is the transformed vector of size n_features\n    y = transpose(phi) * regressor._w\n    std = regressor._var\n\n    if return_std == true\n        return y, std\n    else\n        return y\n    end\nend\n\nfunction predict(\n    regressor::LinearRegressor,\n    Phi::AbstractArray{Float64,2},\n    return_std::Bool,\n)\n    # Phi is the design matrix [phi(x_1), phi(x_2), ,,, phi(x_N)]^T of size (n_samples, n_features)\n    y = Phi * regressor._w\n    std = regressor._var\n\n    if return_std == true\n        return y, std\n    else\n        return y\n    end\nend\n", "meta": {"hexsha": "c0f8bd100dcf032fa9156878c9b6a9cab5d262b6", "size": 1170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear/linear_regressor.jl", "max_stars_repo_name": "soblin/prml-julia", "max_stars_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-10T21:46:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:40:22.000Z", "max_issues_repo_path": "src/linear/linear_regressor.jl", "max_issues_repo_name": "soblin/prml-julia", "max_issues_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/linear/linear_regressor.jl", "max_forks_repo_name": "soblin/prml-julia", "max_forks_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0754716981, "max_line_length": 99, "alphanum_fraction": 0.6264957265, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7702505227827577}}
{"text": "export fac, stirlingNumber\n\ncaching_fac = [1]\nfunction fac(n)\n    if n == 0\n        return 1\n    elseif size(caching_fac, 1) >= n\n        return caching_fac[n]\n    end\n    fac = caching_fac[size(caching_fac, 1)]\n    for i = size(caching_fac, 1)+1:n\n        append!(caching_fac, fac * i)\n    end\n    return caching_fac[n]\nend\n\nfunction stirlingNumber(m, k)\n    if k > m || k < 0 || (m > 0 && k == 0)\n        return 0\n    elseif m == 0 && k == 0\n        return 1\n    else\n        return k * stirlingNumber(m - 1, k) + stirlingNumber(m - 1, k - 1)\n    end\nend\n", "meta": {"hexsha": "4a2f1edbdd2768a5874a2152e3972b7ebabfcb13", "size": 557, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/factorial.jl", "max_stars_repo_name": "EllianCarlos/number-theory-but-in-julia", "max_stars_repo_head_hexsha": "74368fee8002bc53031b8ef6026e72f806efe84d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/factorial.jl", "max_issues_repo_name": "EllianCarlos/number-theory-but-in-julia", "max_issues_repo_head_hexsha": "74368fee8002bc53031b8ef6026e72f806efe84d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/factorial.jl", "max_forks_repo_name": "EllianCarlos/number-theory-but-in-julia", "max_forks_repo_head_hexsha": "74368fee8002bc53031b8ef6026e72f806efe84d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4230769231, "max_line_length": 74, "alphanum_fraction": 0.5547576302, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921834855049, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7702505136293283}}
{"text": "Pkg.add(\"RDatasets\")\nPkg.add(\"Query\")\nPkg.add(\"StatPlots\")\nPkg.add(\"GR\")\n\nusing RDatasets, Plots, Query, DataFrames\n\niris = dataset(\"datasets\", \"iris\")\n\nfunction SplitDFbySpecies(iris, species)\n    df = @from i in iris begin\n         @where i.Species == species\n         @select {i.PetalLength, i.PetalWidth}\n         @collect DataFrame\n    end\n    return df\nend\n\nfunction AttributeDescription(df, name)\n    println(name, \":\\n\")\n    colnames = names(df)\n    ncols = size(colnames)[1]\n    for i in 1:ncols\n        println(colnames[i], \":\")\n        println(\" mean: \", mean(df[i]))\n        println(\" var:  \", var(df[i]))\n    end\n    println()\nend\n\nfunction dfmean(df::DataFrame)\n    return [mean(i) for i in df.columns]\nend\n\nfunction dfcov(df)\n    cols = df.columns\n    ncols = size(cols)[1]\n    ndatas = size(cols[1])[1]\n    array = zeros(ncols, ncols)\n    mean = dfmean(df)\n    for i in 1:ncols\n        for j in 1:ncols\n            array[i, j] = 1/ndatas * (cols[i] .- mean[i])' * (cols[j] .- mean[j])\n        end\n    end\n    return array\nend\n\nfunction scale(df, iris)\n    ncols = length(df.columns)\n    means = dfmean(iris[[:PetalLength, :PetalWidth]])\n    cov = dfcov(iris[[:PetalLength, :PetalWidth]])\n    sigmas = [sqrt(cov[i, i]) for i in 1:ncols]\n    \n    scaler(x, mu, sigma) = (x .- mu) / sigma\n    array = zeros(size(df))\n    for i in 1:ncols\n        array[:, i] = scaler(df[i], means[i], sigmas[i])\n    end\n    return array\nend\n\nsetosa = SplitDFbySpecies(iris, \"setosa\")\nversicolor = SplitDFbySpecies(iris, \"versicolor\")\nvirginica = SplitDFbySpecies(iris, \"virginica\")\n\ngr()\nscatter(setosa[1], setosa[2]; xlabel=\"Petal Length\", ylabel=\"Petal Width\",\n        xlims=(1, 7), ylims=(-1, 4), m=(0.5, :s), label=\"setosa\")\nscatter!(versicolor[1], versicolor[2]; m=(0.5, :c), label=\"versicolor\")\nscatter!(virginica[1], virginica[2]; m=(0.5, :v), label=\"virginica\")\nsavefig(\"figures/unscaled.png\")\n\nsetosa_scaled = scale(setosa, iris)\nversicolor_scaled = scale(versicolor, iris)\nvirginica_scaled = scale(virginica, iris)\n\nscatter(setosa_scaled[:, 1], setosa_scaled[:, 2]; xlabel=\"Petal Length\", ylabel=\"Petal Width\",\n        xlims=(-1.5, 1.5), ylims=(-1.5, 1.5), m=(0.5, :s), label=\"setosa\")\nscatter!(versicolor_scaled[:, 1], versicolor_scaled[:, 2]; m=(0.5, :c), label=\"versicolor\")\nscatter!(virginica_scaled[:, 1], virginica_scaled[:, 2]; m=(0.5, :v), label=\"virginica\")\nsavefig(\"figures/scaled.png\")", "meta": {"hexsha": "0de981bc5ffb501623ad258755c8715601990244", "size": 2402, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JuliaScripts/Scale.jl", "max_stars_repo_name": "koukyo1994/pattern_recognition", "max_stars_repo_head_hexsha": "0bf835b98baa66cdb78aa46c677b8de91790a767", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JuliaScripts/Scale.jl", "max_issues_repo_name": "koukyo1994/pattern_recognition", "max_issues_repo_head_hexsha": "0bf835b98baa66cdb78aa46c677b8de91790a767", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JuliaScripts/Scale.jl", "max_forks_repo_name": "koukyo1994/pattern_recognition", "max_forks_repo_head_hexsha": "0bf835b98baa66cdb78aa46c677b8de91790a767", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2926829268, "max_line_length": 94, "alphanum_fraction": 0.6244796003, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7702505116451152}}
{"text": "\r\nfunction step_size(x0)\r\n    h = sqrt.( eps.( abs.(x0) ) )\r\n    return h\r\nend\r\n\r\nfunction jacobian_fw!(ode_fcn, x0, jac::Matrix, h_tmp, f_tmp)\r\n    # f: R^n -> R^m\r\n    # g_ij = df_i / dx_j\r\n\r\n    h_tmp .= sqrt.( eps.( abs.(x0) ) ) # n-by-1\r\n    return jacobian_fw!(ode_fcn, x0, h_tmp, jac, f_tmp)\r\nend\r\n\r\nfunction jacobian_fw!(ode_fcn, x0, h, jac::Matrix, f_tmp)\r\n    # f: R^n -> R^m\r\n    # g_ij = df_i / dx_j\r\n\r\n    f0    = ode_fcn(x0)                  # m-by-1\r\n    copyto!(f_tmp, f0)\r\n    return jacobian_fw!(ode_fcn, x0, h, f_tmp, jac)   # m-by-n\r\nend\r\n\r\nfunction jacobian_fw!(ode_fcn, x0, h, f0, jac::Matrix)\r\n    # f: R^n -> R^m\r\n    # g_ij = df_i / dx_j\r\n\r\n    x1 = copy(x0)\r\n    for kk = 1:length(x0)\r\n        x1[kk]     += h[kk] \r\n        f1          = ode_fcn(x1)\r\n        jac[:, kk]  = (f1 .- f0) ./ h[kk]\r\n        x1[kk]     -= h[kk] \r\n    end\r\n    return jac\r\nend\r\n\r\n\r\n\r\nfunction time_numdiff_fw!(ode_fcn, t0, dfdt_tmp)\r\n    h = sqrt(eps(abs(t0)))\r\n    return time_numdiff_fw!(ode_fcn, t0, h, dfdt_tmp)\r\nend\r\n\r\nfunction time_numdiff_fw!(ode_fcn, t0, h, dfdt_tmp)\r\n    f0 = ode_fcn(t0)\r\n    return time_numdiff_fw!(ode_fcn, t0, h, f0, dfdt_tmp)\r\nend\r\n\r\nfunction time_numdiff_fw!(ode_fcn, t0, h, f0, dfdt_tmp)\r\n    f1 = ode_fcn(t0 + h)\r\n    dfdt_tmp .= (f1 .- f0) ./ h\r\n    return dfdt_tmp\r\nend\r\n\r\n", "meta": {"hexsha": "3f2974fdeea2152627c01abc3eb3616e3d882a36", "size": 1311, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/ode/src/utils.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "__lib__/math/ode/src/utils.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "__lib__/math/ode/src/utils.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4107142857, "max_line_length": 63, "alphanum_fraction": 0.5385202136, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7702505045718528}}
{"text": "#Linear Kalman filter with control input example\n#This example closely follows that given on \"Greg Czerniak's Website\". Namely\n#the canonball example on this page: http://greg.czerniak.info/guides/kalman1/\n#Basically we shoot a canonball into the air at a given angle of elevation.\n#Using observations of the canonball's velocity and position we're going to\n#track the position of the canonball.\n\n#To use the Kalman Filter we need three things:\n#1) Some observations\n#2) The parameters of the Kalman Filter model describing the system process and\n#the observation model. In this example we also need the control input\n#parameters.\n#3) An initial guess of the state.\n#\n\n#Let's import the modules required to execute the Kalman Filter\nusing StateSpace\nusing Distributions\nusing Gadfly\nusing Colors\n\n################################################################################\n#Section: Generate noisy Observations\n#-------------------------------------------------------------------------------\n#First we're going to provide some parameter values required to model the motion\n#of the canonball.\n\n#Set the Parameters\nelevation_angle = 45.0 #Angle (measured anti-clockwise) between the ground (zero degrees) and the direction the canon ball is fired\nmuzzle_speed = 100.0 #Speed at which the canonball leaves the muzzle\ninitial_velocity = [muzzle_speed*cos(deg2rad(elevation_angle)), muzzle_speed*sin(deg2rad(elevation_angle))] #initial x and y components of the velocity\ngravAcc = 9.81 #gravitational acceleration\ninitial_location = [0.0, 0.0] # initial position of the canonball\nΔt = 0.1 #time between each measurement\n\n#Functions describing the position of canonball\nx_pos(x0::Float64, Vx::Float64, t::Float64) = x0 + Vx*t\ny_pos(y0::Float64, Vy::Float64, t::Float64, g::Float64) = y0 + Vy*t - (g * t^2)/2\n#Function to describe the evolution of the velocity in the vertical direction\nvelocityY(Vy::Float64, t::Float64, g::Float64) = Vy - g * t\n\n#Give variances of the observation noise for the position and velocity\nx_pos_var = 200.0\ny_pos_var = 200.0\nVx_var = 1.0\nVy_var = 1.0\n\n#Set the number of observations and preallocate vectors to store true and noisy\n#measurement values\nnumObs = 145\nx_pos_true = Vector{Float64}(numObs)\nx_pos_obs = Vector{Float64}(numObs)\ny_pos_true = Vector{Float64}(numObs)\ny_pos_obs = Vector{Float64}(numObs)\n\nVx_true = Vector{Float64}(numObs)\nVx_obs = Vector{Float64}(numObs)\nVy_true = Vector{Float64}(numObs)\nVy_obs = Vector{Float64}(numObs)\n\n#Generate the data (true values and noisy observations)\nfor i in 1:numObs\n    x_pos_true[i] = x_pos(initial_location[1], initial_velocity[1], (i-1)*Δt)\n    y_pos_true[i] = y_pos(initial_location[2], initial_velocity[2], (i-1)*Δt, gravAcc)\n    Vx_true[i] = initial_velocity[1]\n    Vy_true[i] = velocityY(initial_velocity[2], (i-1)*Δt, gravAcc)\n\n    x_pos_obs[i] = x_pos_true[i] + randn() * sqrt(x_pos_var)\n    y_pos_obs[i] = y_pos_true[i] + randn() * sqrt(y_pos_var)\n    Vx_obs[i] = Vx_true[i] + randn() * sqrt(Vx_var)\n    Vy_obs[i] = Vy_true[i] + randn() * sqrt(Vy_var)\nend\n#Create the observations vector for the Kalman filter\nobservations = [x_pos_obs Vx_obs y_pos_obs Vy_obs]'\n#End Section: Generate noisy Observations\n################################################################################\n\n################################################################################\n#Section: Describe Kalman Filter parameters\n#-------------------------------------------------------------------------------\n\n#Describe the system parameters\nprocess_matrix = [[1.0, Δt, 0.0, 0.0] [0.0, 1.0, 0.0, 0.0] [0.0, 0.0, 1.0, Δt] [0.0, 0.0, 0.0, 1.0]]'\nprocess_covariance = 0.01*eye(4)\nobservation_matrix = eye(4)\nobservation_covariance = 0.2*eye(4)\ncontrol_matrix = [[0.0, 0.0, 0.0, 0.0] [0.0, 0.0, 0.0, 0.0] [0.0, 0.0, 1.0, 0.0] [0.0, 0.0, 0.0, 1.0]]\ncontrol_input = [0.0, 0.0, -(gravAcc * Δt^2)/2, -(gravAcc * Δt)]\n\n#Create an instance of the LKF with the control inputs\nlinCISMM = LinearGaussianCISSM(process_matrix, process_covariance, observation_matrix, observation_covariance, control_matrix, control_input)\n#End Section: Describe Kalman Filter parameters\n################################################################################\n\n################################################################################\n#Section: Set Initial Guess\n#-------------------------------------------------------------------------------\ninitial_guess_state = [0.0, initial_velocity[1], 500.0, initial_velocity[2]]\ninitial_guess_covariance = eye(4)\ninitial_guess = MvNormal(initial_guess_state, initial_guess_covariance)\n#End Section: Set Initial Guess\n################################################################################\n\n################################################################################\n#Section: Execute Kalman Filter\n#-------------------------------------------------------------------------------\nfiltered_state = filter(linCISMM, observations, initial_guess)\n#End Section: Execute Kalman Filter\n################################################################################\n\n################################################################################\n#Section: Plot Filtered results\n#-------------------------------------------------------------------------------\n#Here we are plotting the filtered results with Gadfly. See the Gadfly\n#documentation for information about how plotting works if you are unfamiliar.\n#Website: http://gadflyjl.org/\n#Plot results\nx_filt = Vector{Float64}(numObs)\ny_filt = Vector{Float64}(numObs)\nfor i in 1:numObs\n    current_state = filtered_state.state[i]\n    x_filt[i] = current_state.μ[1]\n    y_filt[i] = current_state.μ[3]\nend\n\nn = 3\ngetColors = distinguishable_colors(n, Color[LCHab(70, 60, 240)],\n                                   transform=c -> deuteranopic(c, 0.5),\n                                   lchoices=Float64[65, 70, 75, 80],\n                                   cchoices=Float64[0, 50, 60, 70],\n                                   hchoices=linspace(0, 330, 24))\n\ncannonball_plot = plot(\n    layer(x=x_pos_true, y=y_pos_true, Geom.line, Theme(default_color=getColors[3])),\n    layer(x=[initial_guess_state[1]; x_filt], y=[initial_guess_state[3]; y_filt], Geom.line, Theme(default_color=getColors[1])),\n    layer(x=x_pos_obs, y=y_pos_obs, Geom.point, Theme(default_color=getColors[2])),\n    Guide.xlabel(\"X position\"), Guide.ylabel(\"Y position\"),\n    Guide.manual_color_key(\"Colour Key\",[\"Filtered Estimate\", \"Measurements\",\"True Value \"],[getColors[1],getColors[2],getColors[3]]),\n    Guide.title(\"Measurement of a Canonball in Flight\")\n    )\n#End Section: Plot Filtered results\n################################################################################\n", "meta": {"hexsha": "d2ddc20346a892b36701c0d98d2eef8dbecc7fe5", "size": 6710, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/LinearKalmanFilterControlInput_CanonBallExample.jl", "max_stars_repo_name": "npsmc/StateSpace.jl", "max_stars_repo_head_hexsha": "2175c85b23dfbf3178d508a5c749627594e719e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2015-04-30T13:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T12:04:59.000Z", "max_issues_repo_path": "examples/LinearKalmanFilterControlInput_CanonBallExample.jl", "max_issues_repo_name": "npsmc/StateSpace.jl", "max_issues_repo_head_hexsha": "2175c85b23dfbf3178d508a5c749627594e719e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2015-08-12T04:04:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-01T02:35:35.000Z", "max_forks_repo_path": "examples/LinearKalmanFilterControlInput_CanonBallExample.jl", "max_forks_repo_name": "npsmc/StateSpace.jl", "max_forks_repo_head_hexsha": "2175c85b23dfbf3178d508a5c749627594e719e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-02-24T23:33:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T18:55:35.000Z", "avg_line_length": 46.9230769231, "max_line_length": 151, "alphanum_fraction": 0.5965722802, "num_tokens": 1666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009573133051, "lm_q2_score": 0.8418256512199032, "lm_q1q2_score": 0.7701870941919859}}
{"text": "\"\"\"\n    jensen_alpha(asset_returns, benchmark_returns; risk_free=0.0)\n\nJensen's alpha, or simply alpha, is a risk-adjusted excess-performance measure. It indicates the average return of an investment above or below that predicted by the capital asset pricing model (CAPM). The measure adjusts the excess returns such that the risk is identical for the investment and benchmark.\n\n# Arguments\n- `asset_returns`:      Vector of asset returns.\n- `benchmark_returns`:  Vector of benchmark returns (e.g. market portfolio returns for CAPM beta).\n- `risk_free`:          Optional vector or scalar value denoting the risk-free return (must have same frequency as the provided returns, e.g. daily).\n\n# Returns\nJensen's alpha measure.\n\n# Sources\n- Bacon, Carl (2008). Practical Portfolio Performance Measurement and Attribution, 2nd Edition, John Wiley & Sons Ltd. Page 72.\n\"\"\"\nfunction jensen_alpha(asset_returns, benchmark_returns; risk_free=0.0)\n    (α, β) = capm(asset_returns, benchmark_returns; risk_free)\n    α\nend\n\n\n\n\"\"\"\n    modified_jensen(asset_returns, benchmark_returns; risk_free=0.0)\n\nDivides Jensen’s alpha by the systematic risk, which measures the systematic risk-adjusted return per unit of systematic risk. See also `jensen_alpha`\n\n# Arguments\n- `asset_returns`:      Vector of asset returns.\n- `benchmark_returns`:  Vector of benchmark returns (e.g. market portfolio returns for CAPM beta).\n- `risk_free`:          Optional vector or scalar value denoting the risk-free return (must have same frequency as the provided returns, e.g. daily).\n\n# Returns\nModified Jensen's alpha measure.\n\n# Sources\n- Bacon, Carl (2008). Practical Portfolio Performance Measurement and Attribution, 2nd Edition, John Wiley & Sons Ltd. Page 77.\n\"\"\"\nfunction modified_jensen(asset_returns, benchmark_returns; risk_free=0.0)\n    (α, β) = capm(asset_returns, benchmark_returns; risk_free)\n    α / β\nend\n", "meta": {"hexsha": "e6ed0b206654bf96c45b0042e621770f12a2ac76", "size": 1888, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/jensen_alpha.jl", "max_stars_repo_name": "rbeeli/RiskPerf.jl", "max_stars_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-07T19:19:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T19:19:09.000Z", "max_issues_repo_path": "src/jensen_alpha.jl", "max_issues_repo_name": "rbeeli/RiskPerf.jl", "max_issues_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/jensen_alpha.jl", "max_forks_repo_name": "rbeeli/RiskPerf.jl", "max_forks_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9090909091, "max_line_length": 306, "alphanum_fraction": 0.7590042373, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8418256472515684, "lm_q1q2_score": 0.7701870886080432}}
{"text": "\r\n# =========================================================================== #\r\n# Activation Functions\r\n# =========================================================================== #\r\n\r\n\r\nabstract type AbstractActivationFunction\r\nend\r\n\r\nstruct TanhActivationFunction <: AbstractActivationFunction\r\nend\r\n\r\nfunction (act_fcn::TanhActivationFunction)(x)\r\n    return tanh(x)\r\nend\r\n\r\nfunction differentiate(act_fcn::TanhActivationFunction, x)\r\n    return one(typeof(x)) - act_fcn(x)^2\r\nend\r\n\r\nfunction eval(act_fcn::TanhActivationFunction, x)\r\n    return act_fcn(x)\r\nend\r\n\r\n\r\n\r\nstruct ReluActivationFunction <: AbstractActivationFunction\r\nend\r\n\r\nfunction (act_fcn::ReluActivationFunction)(x)\r\n    T = typeof(x)\r\n    z = zero(T)\r\n    return (x < z) * z + (x >= z) * x\r\nend\r\n\r\nfunction differentiate(act_fcn::ReluActivationFunction, x)\r\n    T = typeof(x)\r\n    z = zero(T)\r\n    return (x < z) * z + (x >= z) * one(T)\r\nend\r\n\r\nfunction eval(act_fcn::ReluActivationFunction, x)\r\n    return act_fcn(x)\r\nend\r\n\r\n\r\n\r\n\r\n\r\nstruct IdentityActivationFunction <: AbstractActivationFunction\r\nend\r\n\r\nfunction (act_fcn::IdentityActivationFunction)(x)\r\n    return x\r\nend\r\n\r\nfunction differentiate(act_fcn::IdentityActivationFunction, x)\r\n    return one(typeof(x))\r\nend\r\n\r\nfunction eval(act_fcn::IdentityActivationFunction, x)\r\n    return act_fcn(x)\r\nend\r\n", "meta": {"hexsha": "7ba3fc30ff7c06951dd02287b05070b2aeab738f", "size": 1335, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "neural_networks/src/activation_functions.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "neural_networks/src/activation_functions.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neural_networks/src/activation_functions.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.859375, "max_line_length": 80, "alphanum_fraction": 0.6164794007, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7701870880560722}}
{"text": "\"\"\"\nReturn the rotation angle between two \nvectors of any number of dimensions.\n\nNote that if at least one of the vector is \nthe zero vector, then it returns 0.\nby convention.\n\nArguments\n----------\n:Type{RotationAngle}\n    must be type ``RotationAngle``\n\nvector_1:AbstractArray\n    vector 1\n\nvector_2:AbstractArray \n    vector 2\n\ntol_near_zero=1e-7:AbstractFloat\n    tolerance for being close to zero\n\"\"\"\nfunction gage(::Type{RotationAngle}, vector_1::AbstractArray, vector_2::AbstractArray,\n    tol_near_zero::AbstractFloat=1e-7)\n    @debug @assert length(vector_1) == length(vector_2)\n\n    if nearly_zero(norm(vector_1,2), tol_near_zero)\n        return 0.\n    elseif nearly_zero(norm(vector_2,2), tol_near_zero)\n        return 0.\n    else\n        #= developer's note: (Yuhang Wang 04/17/2016)\n            Sometimes, the normalized dot product is > 1 or < -1 due to\n            error in floating point division.\n            Without proper handling, Julia will report domain error. \n        =#\n        normalized_dot = dot(vector_1/norm(vector_1,2), vector_2/norm(vector_2,2))\n        if normalized_dot > 1.0 \n            return acos(floor(normalized_dot))\n        elseif normalized_dot < -1.0\n            return acos(ceil(normalized_dot))\n        else \n            return acos(normalized_dot)\n        end\n    end\nend", "meta": {"hexsha": "2cd888a3d9a04160eca5dda039cb9752fd9236fb", "size": 1317, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/function/angle/gage_RotationAngle.jl", "max_stars_repo_name": "UMOL/MolecularGeometry.jl", "max_stars_repo_head_hexsha": "9923212a2316413fd86cdf92d7a390d4014c4883", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/function/angle/gage_RotationAngle.jl", "max_issues_repo_name": "UMOL/MolecularGeometry.jl", "max_issues_repo_head_hexsha": "9923212a2316413fd86cdf92d7a390d4014c4883", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/function/angle/gage_RotationAngle.jl", "max_forks_repo_name": "UMOL/MolecularGeometry.jl", "max_forks_repo_head_hexsha": "9923212a2316413fd86cdf92d7a390d4014c4883", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6304347826, "max_line_length": 86, "alphanum_fraction": 0.6666666667, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009573133051, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7701870851154022}}
{"text": "# given a simplex and a face returns:\n# +v if face is the v-th face of the simplex oriented according to the simplex\n# -v if face is the v-th face of the simplex oriented oppositely to the simplex\n# 0 is face is not a face of the simplex\nfunction relorientation(face, simplex)\n\n    v = setdiff(simplex, face)\n    length(v) == 1 || return 0\n\n    # find the position of the missing vertex\n    v = v[1]\n    i = Base.findfirst(simplex, v)\n    s = (-1)^(i-1)\n\n    # remove that vertex from the simplex\n    face2 = Array{Int}(length(simplex)-1)\n    for j in 1 : i-1\n        face2[j] = simplex[j]\n    end\n    for j in i : length(simplex)-1\n        face2[j] = simplex[j+1]\n    end\n\n    # get the permutation that maps face to face2\n    #p = indexin(face, face2)\n    p = [ findfirst(face2,v) for v in face ]\n\n    return s * levicivita(p) * i\nend\n\n\n\"\"\"\n    getcommonedge(cell1, cell2) -> e1, e2, edge\n\nReturns in edge the common vertices of cell1 and cell2. e1 contains the index\nof the vertex of cell1 opposite to this common edge, and with a plus or minus\nsign depending on whether the orientation of the common edge is along or\nagainst the internal orientation of cell1. Similar for e2.\n\"\"\"\nfunction getcommonedge(cell1, cell2)\n    isct = intersect(cell1, cell2)\n    relorientation(isct, cell1), relorientation(isct, cell2), isct\nend\n", "meta": {"hexsha": "59b2b238a6bca3ee030f493dfd44160ae3654646", "size": 1327, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/combinatorics.jl", "max_stars_repo_name": "Elewander/BEAST.jl", "max_stars_repo_head_hexsha": "839799e102e63ca5b899dd9297e1f220d99e756b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/combinatorics.jl", "max_issues_repo_name": "Elewander/BEAST.jl", "max_issues_repo_head_hexsha": "839799e102e63ca5b899dd9297e1f220d99e756b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/combinatorics.jl", "max_forks_repo_name": "Elewander/BEAST.jl", "max_forks_repo_head_hexsha": "839799e102e63ca5b899dd9297e1f220d99e756b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1590909091, "max_line_length": 79, "alphanum_fraction": 0.6782215524, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.770187084839417}}
{"text": "# ------------------------------------------------------------------------------------------\n# # Delay Coordinates & Neighborhoods\n#\n#\n# Topics:\n# * Delay coordinates & why they ROCK!\n# * A `Reconstruction` is a subtype of `AbstractDataset`\n# * Estimating Parameters for `Reconstruction`s\n# * Multiple-time, multiple timeseries `Reconstruction`s\n# * Finding neighborhoods of points in a `Dataset`\n# * Excluding temporal neighbors\n#\n# ---\n#\n# # Delay Coordinates Reconstruction\n# Let's say you have a \"real-world system\" which you measure in an experimental set-up. You\n# are assuming that the system is composed of several dynamic variables, but you can only\n# measure one of them (or some function of the variable).\n#\n# You have a severe lack of recorded information for the system. What do you do?\n# 1. Give up on science, it is a complete waste of time.\n# 2. Use [Taken's theorem](https://en.wikipedia.org/wiki/Takens%27s_theorem), which is\n# indistinguishable from magic.\n#\n# **DynamicalSystems.jl** suggests the third approach.\n#\n# From a timeseries $s$ one can *reconstruct* a state-space $\\mathbf{z}$ simply by shifting\n# $s$ in time, like\n#\n#   $$\\mathbf{z}(n) = (s(n), s(n+\\tau), s(n+2\\tau), \\dots, s(n+(D-1)\\tau))$$\n#\n# This is done with the `Reconstruction(s, D, τ)` function\n# ------------------------------------------------------------------------------------------\n\nusing DynamicalSystems\n\ns = rand(100000)\nD = 3 # reconstruction dimension\nτ = 4 # reconstruction delay\nR = Reconstruction(s, D, τ)\n\n# ------------------------------------------------------------------------------------------\n# ---\n#\n# Here are some nice examples of `Reconstruction`s of a 3D continuous chaotic system, using\n# each of the variables of the system, different delay times and dimension of `2`:\n# ------------------------------------------------------------------------------------------\n\nusing DynamicalSystems, PyPlot\n\nds = Systems.gissinger(ones(3)) # 3D continuous chaotic system, also shown in orbit diagrams tutorial\ndt = 0.05\ndata = trajectory(ds, 1000.0, dt = dt)\n\nxyz = columns(data)\n\nfigure(figsize = (12,10))\nk = 1\nfor i in 1:3\n    for τ in [5, 30, 100]\n        R = Reconstruction(xyz[i], 2, τ)\n        ax = subplot(3,3,k)\n        plot(R[:, 1], R[:, 2], color = \"C$(k-1)\", lw = 0.8)\n        title(\"var = $i, τ = $τ\")\n        k+=1\n    end\nend\n\ntight_layout()\nsuptitle(\"2D Reconstructions\")\nsubplots_adjust(top=0.9);\n\n# ------------------------------------------------------------------------------------------\n# How does this compare to the \"real\" two-dimensional representation of the system?\n# ------------------------------------------------------------------------------------------\n\nfigure(figsize=(6,4))\nplot(data[:, 2], data[:, 3], lw=1.0);\n\n# ------------------------------------------------------------------------------------------\n# ---\n#\n# # `Reconstruction <: AbstractDataset`\n# A `Reconstruction` instance can be passed around and used exactly like a `Dataset`!\n#\n# Let's look at a `Reconstruction` of data from a gissinger system's trajectory above\n# ------------------------------------------------------------------------------------------\n\nR = Reconstruction(data[:, 1], 2, 30)\nR[31:end, 1] == R[1:end-30, 2]\n\na = 0.0\nfor point ∈ R\n    a += mean(point)\nend\na/length(R)\n\n# ------------------------------------------------------------------------------------------\n# **Taken's theorem says that some quantities remain invariant under a reconstruction**\n#\n# We'll show this using a `Reconstruction` with the 3rd dimension of `data`.\n#\n# (D = 2 is not best for this system. D = 3 is better!)\n# ------------------------------------------------------------------------------------------\n\nR = Reconstruction(data[:, 1], 3, 30)\n\n# ------------------------------------------------------------------------------------------\n# Let's compare the information dimension of the `Reconstruction`\n# ------------------------------------------------------------------------------------------\n\nI1 = information_dim(R)\n\n# ------------------------------------------------------------------------------------------\n# and the information dimension of the attractor directly\n# ------------------------------------------------------------------------------------------\n\nI2 = information_dim(data)\n\nprintln(\"|Reconstructed - original| dimension: $(abs(I1 - I2))\")\n\n# ------------------------------------------------------------------------------------------\n# # Estimating Reconstruction Parameters\n#\n# It is important to understand that even though Taken's theorem is 99% magic, it is **not**\n# 100%. One still has to choose \"appropriately good\" values for both the delay time as well\n# as the reconstruction dimension! Thankfully, **DynamicalSystems.jl** has some support for\n# that as well!\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# * `estimate_delay` estimates delay time `τ` using the autocorrelation of the signal\n# * `estimate_dimension` returns an estimator of the embedding dimension `D` using Cao's\n# method\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# # Multiple-time, multiple-timeseries Reconstructions\n#\n# The `Reconstruction` we have seen so far is just a \"Vanilla version\"...\n#\n# One can also perform:\n#\n# 1. Reconstructions with multiple delay times, which tries to capture the effect of\n# multiple timescales existing in a system.\n# 2. Reconstructions with multiple timeseries.\n# 3. Reconstructions with multiple timeseries *and* multiple delay times!\n#\n# See the documentation string of `Reconstruction` for more!\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# # Neighborhoods\n#\n# A \"neighborhood\" is a collection of points that is near a given point. `Dataset`s\n# interface the module\n# [`NearestNeighbors`](https://github.com/KristofferC/NearestNeighbors.jl) in order to find\n# this neighborhood.\n#\n# We use the function `neighborhood`. The call signature is:\n# ```julia\n# neighborhood(point, tree, ntype)\n# ```\n# \n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# `point` is simply the query point. `tree` is the structure required by\n# [`NearestNeighbors`](https://github.com/KristofferC/NearestNeighbors.jl), and is obtained\n# simply by:\n# ------------------------------------------------------------------------------------------\n\ndataset = Dataset(rand(1000,3))\ntree = KDTree(dataset)\n\n# ------------------------------------------------------------------------------------------\n# The third argument to `neighborhood` is the *type* of the neighborhood.\n#\n# * There are two types of neighborhoods!\n#\n# The first one is defined as the `k` nearest points to a given point. It is represented in\n# code by:\n# ------------------------------------------------------------------------------------------\n\nmybuddies = FixedMassNeighborhood(3)\n\n# ------------------------------------------------------------------------------------------\n# *For experts: for a `FixedMassNeighborhood` a KNN search is done*\n# ------------------------------------------------------------------------------------------\n\npoint = ones(3)\nn = neighborhood(point, tree, mybuddies)\n\n# ------------------------------------------------------------------------------------------\n# Notice that the `neighborhood` function does not return the points themselves, but rather\n# the indices of the points in the original data:\n# ------------------------------------------------------------------------------------------\n\nprintln(\"Fixed mass neighborhood of $(point) is:\")\n\nfor i in n\n    println(dataset[i])\nend\n\n# ------------------------------------------------------------------------------------------\n# ---\n#\n# The second type of neighborhood contains all the points that are within some given\n# distance `ε` from the query.\n#\n# In code, we represent this as:\n# ------------------------------------------------------------------------------------------\n\nwhere_u_at = FixedSizeNeighborhood(0.001)\n\n# ------------------------------------------------------------------------------------------\n#  *For experts: for `FixedSizeNeighborhood` an inrange search is done*\n# ------------------------------------------------------------------------------------------\n\nn2 = neighborhood(point, tree, where_u_at)\n\nplz_come_closer = FixedSizeNeighborhood(0.2)\nn2 = neighborhood(point, tree, plz_come_closer)\n\nprintln(\"Fixed size neighborhood of $(point) is:\")\n\nfor i in n2\n    println(dataset[i])\nend\n\n# ------------------------------------------------------------------------------------------\n# Okay, so points that have distance < ε are accepted as a neighborhood.\n#\n# How do we define the \"distance\" though? When defining a `tree`, you can optionally give a\n# distance function. By default Euclidean distance is used, but others also work. For\n# example, we can use the `Distances` package to get distance functions,\n# ------------------------------------------------------------------------------------------\n\nusing Distances\n\n# ------------------------------------------------------------------------------------------\n# and define the distance as the `Distances`'s `Chebyshev` distance:\n# ------------------------------------------------------------------------------------------\n\nfunky_tree = KDTree(dataset, Chebyshev())\n\nn3 = neighborhood(point, funky_tree, plz_come_closer)\n\n# ------------------------------------------------------------------------------------------\n# # Excluding temporal neighbors\n#\n# Before moving on, let's see one last thing.\n#\n# In this example, the point I want the neighborhood of is now part of my dataset:\n# ------------------------------------------------------------------------------------------\n\npoint = dataset[end]\n\n# ------------------------------------------------------------------------------------------\n# Let's calculate again the two neighborhoods\n# ------------------------------------------------------------------------------------------\n\ntree = KDTree(dataset)\n\n# ------------------------------------------------------------------------------------------\n# We'll find suuuuuuuper close neighbors with a **very** small $\\epsilon$:\n# ------------------------------------------------------------------------------------------\n\nε = 0.000001\nwhere_u_at = FixedSizeNeighborhood(ε)\nn2 = neighborhood(point, tree, where_u_at)\n\n# ------------------------------------------------------------------------------------------\n# and now we can find the nearest neighbor:\n# ------------------------------------------------------------------------------------------\n\nmy_best_friend = FixedMassNeighborhood(1)\nn3 = neighborhood(point, tree, my_best_friend)\n\nprintln(n2)\nprintln(n3)\n\nlength(dataset) == n2[1] == n3[1]\n\n# ------------------------------------------------------------------------------------------\n# **What is happening here is that the `neighborhood` also counted the `point` itself, since\n# it is also part of the dataset.**\n#\n# * Almost always this behavior needs to be avoided. For this reason, there is a second\n# method for `neighborhood`:\n#\n# ```julia\n# neighborhood(point, tree, ntype, idx::Int, w::Int = 1)\n# ```\n#\n# In this case, `idx` is the index of the point in the original data. `w` stands for the\n# Theiler window (positive integer).\n#\n# Only points that have index\n# `abs(i - idx) ≥ w` are returned as a neighborhood, to exclude close temporal neighbors.\n#\n# * The default `w=1` is the case of excluding the `point` itself.\n#\n# ---\n#\n# Let's revisit the last example (using the default value of `w = 1`):\n# ------------------------------------------------------------------------------------------\n\npoint = dataset[end]\nidx = length(dataset)\n\nn2 = neighborhood(point, tree, where_u_at, idx)\nn3 = neighborhood(point, tree, my_best_friend, idx)\n\nprintln(n2)\nprintln(n3)\n\n# ------------------------------------------------------------------------------------------\n# As you can see, there isn't *any* neighbor of `point` with distance `< 0.000001` in this\n# dataset, but there is always a nearest neighbor:\n# ------------------------------------------------------------------------------------------\n\nprintln(dataset[n3[1]], \" is the nearest neighbor of \", point)\n\n# ------------------------------------------------------------------------------------------\n# # Docstrings\n# ------------------------------------------------------------------------------------------\n\n?Reconstruction\n\n?neighborhood\n\n?AbstractNeighborhood\n", "meta": {"hexsha": "0fefbbc0b45d8e6a2776032aa7868ee0b16565ed", "size": 12924, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/introduction-to-dynamicalsystems.jl/5. Delay Coordinates & Neighborhoods.jl", "max_stars_repo_name": "grenkoca/JuliaTutorials", "max_stars_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 535, "max_stars_repo_stars_event_min_datetime": "2020-07-15T14:56:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T12:50:32.000Z", "max_issues_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/introduction-to-dynamicalsystems.jl/5. Delay Coordinates & Neighborhoods.jl", "max_issues_repo_name": "grenkoca/JuliaTutorials", "max_issues_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2018-02-25T22:53:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-14T02:15:50.000Z", "max_forks_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/introduction-to-dynamicalsystems.jl/5. Delay Coordinates & Neighborhoods.jl", "max_forks_repo_name": "grenkoca/JuliaTutorials", "max_forks_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 394, "max_forks_repo_forks_event_min_datetime": "2020-07-14T23:22:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:12:57.000Z", "avg_line_length": 38.6946107784, "max_line_length": 101, "alphanum_fraction": 0.44908697, "num_tokens": 2346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7701615717671202}}
{"text": "using LinearAlgebra\nfunction softmax(a)\n    if ndims(a) == 1\n        return exp.(a) ./ sum(exp.(a))\n    else \n        return exp.(a) ./ sum(exp.(a), dims = 2)\n    end\nend\nfunction fit(x, t; alpha = 0.01, tau_max = 1000) \n    function CEE(w, x, t) #this is Cross entropy Error\n        p = softmax(x * w)\n        grad = -(x' * (t - p))\n        return grad / length(x[:, 1]) \n    end\n    if size(x)[1] != size(t)[1]#Processing when the matrix is ​​organized by dependent variable\n        x = x'\n    end\n    x = hcat(ones(size(x)[1], 1), x)\n    w = ones(size(x)[2], size(t)[2])\n    for tau in 1 : tau_max\n        grad = CEE(w, x, t)\n        w -= alpha * grad\n    end\n    return w\nend\n\nfunction forecast(x, w)\n    x = hcat(ones(size(x)[1], 1), x)\n    return softmax(x * w)\nend\n\n#Pass so that the row is each data sample and the column is each feature.\nfunction predict(x, w)\n    x = hcat(ones(size(x)[1], 1), x)\n    s = softmax(x * w)\n    p = [findfirst(s[i, :] .== maximum(s[i, :])) for i in 1:size(s)[1]]\nend\n", "meta": {"hexsha": "624c14efbf91bc9334f211d47b90cb64d30285f3", "size": 1006, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Classification/MS.jl", "max_stars_repo_name": "QGMW22/Horse.jl", "max_stars_repo_head_hexsha": "77be589dbf047a029615dde7773360ebcb5d99b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-19T13:09:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-19T13:09:53.000Z", "max_issues_repo_path": "src/Classification/MS.jl", "max_issues_repo_name": "QGMW22/Horse", "max_issues_repo_head_hexsha": "77be589dbf047a029615dde7773360ebcb5d99b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-21T13:52:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-21T13:52:40.000Z", "max_forks_repo_path": "src/Classification/MS.jl", "max_forks_repo_name": "QGMW22/Horse", "max_forks_repo_head_hexsha": "77be589dbf047a029615dde7773360ebcb5d99b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4736842105, "max_line_length": 95, "alphanum_fraction": 0.541749503, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992895791291, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7701169027641465}}
{"text": "using OrdinaryDiffEq, ModelingToolkit, DiffEqOperators, DomainSets\n# Method of Manufactured Solutions: exact solution\nu_exact = (x,t) -> exp.(-t) * cos.(x)\n\n@parameters t x y\n@variables u(..)\nDxx = Differential(x)^2\nDyy = Differential(y)^2\nDt = Differential(t)\nt_min= 0.\nt_max = 2.0\nx_min = 0.\nx_max = 2.\ny_min = 0.\ny_max = 2.\n\n#xmax = 50.0\n#ymax = 30.0\n#ncells = 50.0\n#dx = x_max / ncells\n\n\nlecturer(x, y) = x > x_max / 2 - dx && x < x_max / 2 + dx && y > y_max / 10 - dx && y < y_max / 10 + dx\nemission(x, y, emisrate) = lecturer(x, y) ? emisrate : 0\n@register emission(x, y, emisrate)\nemisrate = 10;\n\n\n\n# 3D PDE\neq  = Dt(u(t,x,y)) ~ Dxx(u(t,x,y)) + Dyy(u(t,x,y)) + emission(x, y, emisrate)\n#emission(x, y, emisrate) = emisrate\n\nanalytic_sol_func(t,x,y) = exp(x+y)*cos(x+y+4t)\n# Initial and boundary conditionn\n\nbcs = #[u(t_min,x,y) ~ analytic_sol_func(t_min,x,y),\n      [u(t_min,x,y) ~ 0,\n       u(t,x_min,y) ~ 0,\n       u(t,x_max,y) ~ 0,\n       u(t,x,y_min) ~ 0,\n       u(t,x,y_max) ~ 0]\n\n# Space and time domains\ndomains = [t ∈ IntervalDomain(t_min,t_max),\n           x ∈ IntervalDomain(x_min,x_max),\n           y ∈ IntervalDomain(y_min,y_max)]\npdesys = PDESystem([eq],bcs,domains,[t,x,y],[u(t,x,y)])\n\n# Method of lines discretization\ndx = 0.1; dy = 0.1\ndiscretization = MOLFiniteDifference([x=>dx,y=>dy],t)\nprob = ModelingToolkit.discretize(pdesys,discretization)\nsol = solve(prob,Tsit5())\n\n# Ploting\nusing Plots\nxs,ys = [infimum(d.domain):dx:supremum(d.domain) for d in domains]\nu_sol = reshape(sol.u[300], length(xs)-2,length(ys)-2)\n\nplot(xs[2:length(xs)-1], ys[2:length(ys)-1], u_sol, linetype=:contourf,title = \"solution\")\n\n#Animation\nanim = @animate for i ∈ 1:length(sol.t)\n    u_sol = reshape(sol.u[i], length(xs)-2,length(ys)-2)\n    plot(xs[2:length(xs)-1], ys[2:length(ys)-1], u_sol, linetype=:contourf,title = \"solution\")\n\n\nend\ngif(anim, \"anim_fps15.gif\", fps = 15)\n\n", "meta": {"hexsha": "01bd880ce5c035052f9e693a3eb14e150e2fb981", "size": 1882, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "heatequation.jl", "max_stars_repo_name": "minwoos2/tutorials", "max_stars_repo_head_hexsha": "c211a1d47337bb946f1888b687860e0c2438fa45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "heatequation.jl", "max_issues_repo_name": "minwoos2/tutorials", "max_issues_repo_head_hexsha": "c211a1d47337bb946f1888b687860e0c2438fa45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-09T06:33:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T16:04:59.000Z", "max_forks_repo_path": "heatequation.jl", "max_forks_repo_name": "minwoos2/tutorials", "max_forks_repo_head_hexsha": "c211a1d47337bb946f1888b687860e0c2438fa45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-09T05:51:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T05:51:14.000Z", "avg_line_length": 26.1388888889, "max_line_length": 103, "alphanum_fraction": 0.6349628055, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.924141826246517, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7701101133677929}}
{"text": "module CorrelationDimension\n\nimport Plots\n\nusing Statistics: mean, covm, varm\n\nusing Distributions: fit\nusing LinearAlgebra: norm\nusing StatsBase: Histogram\n\nexport correlation_dimension, plot_correlation\n\n\"\"\"\n    correlation_dimension(x; dist=(x1,x2)->norm(x1.-x2)) -> (corrdim, logr, logNr, intercept)\n\nCompute an estimate of the correlation dimension for a set of points in space, with\ncoordinates for the ith point given as `x[:,i]`.\n\nThis is given by\n\nδ̂ = ∂[log N(r)]/∂[log r]\n\nwhere N(r) is the number of point pairs within a distance r of each other.  This is\nestimated by binning the pair-distances into bins (chosen automatically)\nand fitting a straight line through the log-distribution.\n\nThe distance function `dist` by default is the Cartesian 2-norm, but any function may be\nsupplied.\n\nThe function returns a named tuple of the estimate of the correlation dimension, `corrdim`,\nthe lower edges of the distance bins, `logr`, the weights in the distance bins `logNr`, and\nthe `intercept` of the best fitting line (of which the slope is `corrdim`).\n\"\"\"\nfunction correlation_dimension(x; dist=(a,b)->norm(a .- b))\n    D, n = size(x)\n    # List of log(pairwise distances)\n    point1 = Vector{float(eltype(x))}(undef, D)\n    point2 = similar(point1)\n    logr = float(eltype(x))[]\n    for i in 1:n, j in (i+1):n\n        point1 .= x[:,i]\n        point2 .= x[:,j]\n        push!(logr, log(dist(point1, point2)))\n    end\n    # Construct histogram\n    h = fit(Histogram, logr)\n    # Linear regression\n    logr = h.edges[1][1:end-1]\n    logNr = log.(cumsum(h.weights./(n*(n-1)/2)))\n    c, δ̂ = linear_regression(logr, logNr)\n    (corrdim=δ̂, logr=logr, logNr=logNr, intercept=c)\nend\n\n\"\"\"\n    correlation_dimension(x1, x2, ..., xN; kwargs...) -> δ̂\n\nSpecify coordinates with dimension N as N separate vectors.\n\"\"\"\ncorrelation_dimension(x, y, args...; kwargs...) = correlation_dimension(permutedims(hcat(x, y, args...)))\n\n\"\"\"\n    plot_correlation((logr, logNr, slope, intercept))\n\nCreate a plot of the output from `correlation_dimension`.  Input is a tuple\nof the log of the distance bins (`logr`), the weights of the histogram (`logNr`),\nplus the `slope` and `intercept` of the best fitting line.  The `slope` therefore\nis the estimate of the ccorrelation dimension.\n\"\"\"\nfunction plot_correlation((corrdim, logr, logNr, intercept))\n    Plots.scatter(logr, logNr, label=\"Data\", legend=:topleft)\n    Plots.plot!(x->corrdim*x+intercept, label=\"y = $(round(corrdim, sigdigits=3))x + $(round(intercept, sigdigits=3))\")\nend\n\n\"\"\"\n    linear_regression(x, y)\n\nPerform simple linear regression using Ordinary Least Squares. Returns `a` and `b` such\nthat `a + b*x` is the closest straight line to the given points `(x, y)`, i.e., such that\nthe squared error between `y` and `a + b*x` is minimized.\n\"\"\"\nfunction linear_regression(x::AbstractVector, y::AbstractVector)\n    size(x) == size(y) || throw(DimensionMismatch(\"x and y must be the same size\"))\n    mx, my = mean(x), mean(y)\n    b = covm(x, mx, y, my)/varm(x, mx)\n    a = my - b*mx\n    return a, b\nend\n\nend # module\n", "meta": {"hexsha": "0ef3a819c530dd5a285d91dad8ed0ebf8d9ddd5e", "size": 3062, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CorrelationDimension.jl", "max_stars_repo_name": "anowacki/assorted-julia-modules", "max_stars_repo_head_hexsha": "40fe2f109756a5a5f6ef4287bd3c594300fca63d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CorrelationDimension.jl", "max_issues_repo_name": "anowacki/assorted-julia-modules", "max_issues_repo_head_hexsha": "40fe2f109756a5a5f6ef4287bd3c594300fca63d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CorrelationDimension.jl", "max_forks_repo_name": "anowacki/assorted-julia-modules", "max_forks_repo_head_hexsha": "40fe2f109756a5a5f6ef4287bd3c594300fca63d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:44:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:44:09.000Z", "avg_line_length": 34.0222222222, "max_line_length": 119, "alphanum_fraction": 0.6910516003, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7701101027499716}}
{"text": "# Michelle Medina\n# August 11, 2020\n# Testing Convergence of Derivative\n\n\n# USING L2 NORM\nH = []\nE = []\n\nfor N in 50:200\n    grid = Params(N,4)\n\n\txVal = collect(range(0.0, stop=1.0, length = 129))\n\ty = calcNodal(x -> sin(4*pi*x), xVal)\n\tcosx = calcNodal(x -> 4*pi*cos(4*pi*x), xVal)\n\tmodal = Nodal_2_H(y)\n\n\tdy = zeros(length(xVal))\n\tfor index in CartesianIndices(xVal)\n\t\tdy[index] = derivEvaluate(modal, xVal[index])\n\tend\n\n    # u = functionOnGrid(x->sin(x),grid)\n    # dUdx = functionOnGrid(x->cos(x),grid) #known derivative of sin(x)\n    # derivative = Deriv1D(u,grid)\n    \n    #L 2 norm: sum of all the differences between the numerical derivative and\n    #the analytical one squared and then take the square root\n    error = sqrt(sum((dy[2:end-1] - cosx[2:end-1]).^2))\n    \n    h = dX(grid)\n    #append h to the array H and error to the array E\n    append!(H,h) \n    append!(E,error)\n    \nend\n\n#plotting error vs h\nloglog(H,E,\"r-\") \n\n#first order convergence\nloglog(H,H,\"g--\",label=\"1\") \n\n#second order convergence\nloglog(H,H.^2,\"b--\",label=\"2\") \nxlabel(\"h\")\nylabel(\"L 2 Norm\")\nlegend(loc=\"best\",frameon=false)\nshow()", "meta": {"hexsha": "79d0eb3ea2d784cde082a87a0db85ef75a8d5808", "size": 1121, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/DerivConvergenceTest.jl", "max_stars_repo_name": "mmedina002/SparseGrids", "max_stars_repo_head_hexsha": "1662ebcb54f0ffbf6ccf3b5084192bd7b9ab5343", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-30T17:55:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-12T16:25:00.000Z", "max_issues_repo_path": "test/DerivConvergenceTest.jl", "max_issues_repo_name": "mmedina002/SparseGrids", "max_issues_repo_head_hexsha": "1662ebcb54f0ffbf6ccf3b5084192bd7b9ab5343", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/DerivConvergenceTest.jl", "max_forks_repo_name": "mmedina002/SparseGrids", "max_forks_repo_head_hexsha": "1662ebcb54f0ffbf6ccf3b5084192bd7b9ab5343", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-07T15:43:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-07T15:43:21.000Z", "avg_line_length": 22.8775510204, "max_line_length": 78, "alphanum_fraction": 0.640499554, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7701101027499716}}
{"text": "function nlp3(oct::Bool = false)\n    m = JuMP.Model()\n    @variable(m, 0 <= x[1:10])\n    for i = 1:8\n        JuMP.set_lower_bound(x[[1, 2, 4, 6, 7, 8, 9, 10][i]], \n                             [1,1,1,85,90,3,1.2,145][i])\n    end\n    for i = 1:10\n        JuMP.set_upper_bound(x[i], [2000, 16000, 120, 5000, 2000,\n                                    93, 95, 12, 4, 162][i])\n        JuMP.set_start_value(x[i], [1724.90452208, 16000,\n                                    98.0900813608, 3049.1211364,\n                                    1995.02326433, 90.718089075,\n                                    94.2274481766, 10.432474977,\n                                    2.59051951438, 149.682344530][i])\n    end\n    @constraint(m, e1, x[1] - 1.22*x[4] + x[5] == 0)\n    @constraint(m, e2, x[9] + 0.222*x[10] == 35.82)    \n    @constraint(m, e3, 3*x[7] - x[10] == 133)    \n    if !oct\n        @NLconstraint(m, e4, x[7] - 1.098*x[8] + 0.038*(x[8]^2) - 0.325*(x[6] - 89) == 86.35)    \n        @NLconstraint(m, e5, x[4]*x[9]*x[6] + 1000*x[3]*x[6] - 98000*x[3] == 0)    \n        @NLconstraint(m, e6, x[2] + x[5] - x[1]*x[8] == 0)    \n        @NLconstraint(m, e7, 1.12*x[1] + 0.13167*x[8]*x[1] - 0.00667*(x[8]^2)*x[1] - x[4] >= 0)    \n        @NLobjective(m, Min, 5.04*x[1] + 0.035*x[2] + 10*x[3] + 3.36*x[5] - 0.063*x[4]*x[7])   \n        return m     \n    else\n        @variable(m, obj)\n        @objective(m, Min, obj)\n        gm = GlobalModel(model = m, name = \"nlp3\")\n        add_nonlinear_constraint(gm, :(x -> x[7] - 1.098*x[8] + 0.038*(x[8]^2) - 0.325*(x[6] - 89) - 86.35),\n                                vars = [x[6], x[7], x[8]], name = \"e4\", equality=true)\n        add_nonlinear_constraint(gm, :(x -> x[4]*x[9]*x[6] + 1000*x[3]*x[6] - 98000*x[3]), \n                                vars = [x[3], x[4], x[6], x[9]], name = \"e5\", equality = true)\n        add_nonlinear_constraint(gm, :(x -> x[2] + x[5] - x[1]*x[8]), \n                                vars = [x[1], x[2], x[5], x[8]], name = \"e6\", equality = true)\n        add_nonlinear_constraint(gm, :(x -> 1.12*x[1] + 0.13167*x[8]*x[1] - 0.00667*(x[8]^2)*x[1] - x[4]), \n                                vars = [x[1], x[4], x[8]], name = \"e7\")\n        add_nonlinear_constraint(gm, :(x -> 5.04*x[1] + 0.035*x[2] + 10*x[3] + 3.36*x[5] - 0.063*x[4]*x[7]), \n                                vars = [x[1], x[2], x[3], x[4], x[5], x[7]], \n                                dependent_var = obj, name = \"obj\")\n        return gm\n    end\nend\n\n", "meta": {"hexsha": "973a558ad1b7f87491d956b5ccc06958af7f3052", "size": 2470, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "data/baron/nlp3.jl", "max_stars_repo_name": "1ozturkbe/OCTHaGOn.jl", "max_stars_repo_head_hexsha": "222a73c8da834c8e4114b6f29492d8ab917f6722", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data/baron/nlp3.jl", "max_issues_repo_name": "1ozturkbe/OCTHaGOn.jl", "max_issues_repo_head_hexsha": "222a73c8da834c8e4114b6f29492d8ab917f6722", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2022-02-13T15:33:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T15:45:11.000Z", "max_forks_repo_path": "data/baron/nlp3.jl", "max_forks_repo_name": "1ozturkbe/OCTHaGOn.jl", "max_forks_repo_head_hexsha": "222a73c8da834c8e4114b6f29492d8ab917f6722", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.6956521739, "max_line_length": 109, "alphanum_fraction": 0.4174089069, "num_tokens": 1018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522862, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7700950882149911}}
{"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 1e037376-8252-41fb-ae95-93bc9011b7fa\n# we need to install a special package in order to use the gamma function\nusing SpecialFunctions\n\n# ╔═╡ 76d6c2d4-e370-4e83-9d04-ca6fc546bdd9\n# we write a function that returns the exact volume of a hypersphere in d dimensions\nfunction exactVol(d)\n    vol = pi^(d/2) / gamma(1 + d/2)\n    return vol\nend\n\n# ╔═╡ b58cf6d8-291c-49f4-a61a-51f1a7454651\nn = 10000;\n\n# ╔═╡ 2f4a8b5e-f7c9-4abc-b04d-3286207a97b3\ndim = 20;\n\n# ╔═╡ 4da795ef-b8d3-4c94-bb89-7eeaca9602fb\nmd\"Exact volume is:\"\n\n# ╔═╡ 8d8e10d0-2597-4198-92b1-9ab2ebe4b3c8\nexV = exactVol(dim)\n\n# ╔═╡ 6a8c6c37-2a48-47c7-8d40-ca276c8a09d2\n# we write a function that returns a random vector from [0,1]^d with exponential density\nfunction randExp(d, lam)\n\n\t# we generate a uniformly random vector\n\ty = rand(d)\n\n\t# we transform (elementwise) to random numbers in [exp(-lambda),1]\n\ty = exp(-lam) .+ (1-exp(-lam))*y\n\t\n\t# we now get numbers with exponential density\n\tx = -log.(y)/lam\n\treturn x\nend\n\n# ╔═╡ 8de1cad7-ac2c-42ec-9581-1d7ff06d576d\n# we write an improoved function that uses Monte Carlo with exponential importance sampling\n# to estimate the volume of the unit hypersphere in d dimensions.\n# We choose our points x with independent Cartesian components and prob density exp(-lam.xi) / [ lam*((1-exp(-lam)) ].\n# We achieve this by taking xi = (1/lam) log (1/y) where y is chosen uniformly in (exp(-lam),1)\nfunction sphereVolMCImpExp(d, n, lam)\n\tcount = 0.0\n\tfor i = 1:n\n\n\t\t# we generate x according to our distribution\n\t\tx = randExp(d, lam)\n\n\t\t# we calculate the squared norm of x and check if x is inside the hypersphere\n\t\tnorm2 = x' * x\n\t\tif norm2 < 1\n\n\t\t\t# we compute the density at x\n\t\t\trho = 1\n\t\t\tfor i = 1:d\n\n\t\t\t\t# note that y(i) = exp(-lam * x(i))\n\t\t\t\trho *= exp(-lam*x[i]) * lam / (1-exp(-lam))\n\t\t\tend\n\t\t\tcount += 1/rho\n\t\tend\n\tend\n\tvol =  2^d * count / n\n\treturn vol\nend\n\n# ╔═╡ c8381d29-3b9f-4399-9a60-c0b6b620e99c\nsphereVolMCImpExp(20, n, 2)\n\n# ╔═╡ 0e1580e1-cdae-498e-ab14-261f8a96a802\nmd\" We do the calculation $m$ times and check mean/variance:\"\n\n# ╔═╡ 770e2019-420d-415b-b498-96493ac676bf\nm = 1000;\n\n# ╔═╡ dc6e6729-7ce5-45a8-8ecc-b320d283340a\ndata = [sphereVolMCImpExp(20, n, 2) for i in 1:m];\n\n# ╔═╡ fb6c8ff3-d200-4e48-b9ad-aa34d188e675\nmean = sum(data)/m\n\n# ╔═╡ 48b51297-b3fb-4bce-8d41-7af6120b553c\nerror = mean - exV\n\n# ╔═╡ bb18d766-cdad-45b7-aebb-c59763896bd4\nvariance = sum(broadcast(x -> (x-mean)^2, data))/m\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nSpecialFunctions = \"276daf66-3868-5448-9aa4-cd146d93841b\"\n\n[compat]\nSpecialFunctions = \"~1.6.1\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"bdc0937269321858ab2a4f288486cb258b9a0af7\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.3.0\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"727e463cfebd0c7b999bbf3e9e7e16f254b94193\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.34.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"a32185f5428d3986f47c2ab78b1f216d5e6cc96f\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.5\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"f76424439413893a832026ca355fe273e93bce94\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"DocStringExtensions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"3d682c07e6dd250ed082f883dc88aee7996bf2cc\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.0\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"LogExpFunctions\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"a322a9493e49c5f3a10b50df3aedaf1cdb3244b7\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.6.1\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╠═1e037376-8252-41fb-ae95-93bc9011b7fa\n# ╠═76d6c2d4-e370-4e83-9d04-ca6fc546bdd9\n# ╠═b58cf6d8-291c-49f4-a61a-51f1a7454651\n# ╠═2f4a8b5e-f7c9-4abc-b04d-3286207a97b3\n# ╟─4da795ef-b8d3-4c94-bb89-7eeaca9602fb\n# ╠═8d8e10d0-2597-4198-92b1-9ab2ebe4b3c8\n# ╠═6a8c6c37-2a48-47c7-8d40-ca276c8a09d2\n# ╠═8de1cad7-ac2c-42ec-9581-1d7ff06d576d\n# ╠═c8381d29-3b9f-4399-9a60-c0b6b620e99c\n# ╟─0e1580e1-cdae-498e-ab14-261f8a96a802\n# ╠═770e2019-420d-415b-b498-96493ac676bf\n# ╠═dc6e6729-7ce5-45a8-8ecc-b320d283340a\n# ╠═fb6c8ff3-d200-4e48-b9ad-aa34d188e675\n# ╠═48b51297-b3fb-4bce-8d41-7af6120b553c\n# ╠═bb18d766-cdad-45b7-aebb-c59763896bd4\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "a8064fb8b361ed17402946e5e8e57ffb288b2594", "size": 8927, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1a/Monte Carlo integration/mcTest.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "1a/Monte Carlo integration/mcTest.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "1a/Monte Carlo integration/mcTest.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 27.4676923077, "max_line_length": 280, "alphanum_fraction": 0.7170381987, "num_tokens": 4029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7700652362082185}}
{"text": "#=\nThis file is part of Pseudospectra.jl.\n\nJulia translation\ncopyright 2017 Ralph Smith\n\nPortions derived from EigTool\nCopyright (c) 2002-2014, The Chancellor, Masters and Scholars\nof the University of Oxford, and the EigTool Developers. All rights reserved.\n\nSPDX-License-Identifier: BSD-3-Clause\nLicense-Filename: LICENSES/BSD-3-Clause_Eigtool\n=#\n\n\"\"\"\n    numerical_range(A, nstep=20) -> Vector{Complex}\n\nCompute points along the numerical range of a matrix.\n\nNote: this solves an eigensystem for each point, so may be expensive.\n\"\"\"\nfunction numerical_range(A::AbstractMatrix, thmax=20)\n    rayleighquotient(B,x) = dot(x, B * x) / dot(x,x)\n    # m,n = size(A)\n    T = eltype(A)\n    CT = (T <: Real) ? Complex{T} : T\n    z = zeros(CT,2*thmax+2)\n    for i = 0:thmax\n        # upstream allows for interactive cancellation\n\n        # get Hermitian part of rotated A\n        th = (i/thmax)*π\n        Ath = exp(th*1im)*A\n        H = (1/2)*(Ath + Ath')\n        F = eigen(H)\n        d,X = F.values,F.vectors\n\n        # RQ's of A correspond to eigenvalues of H w/ extreme real parts\n        k = sortperm(real(d))\n        z[i+1] = rayleighquotient(A,X[:,k[1]])\n        z[1+i+thmax] = rayleighquotient(A,X[:,k[end]])\n    end\n    z[end] = z[1] # close curve for plotting\n    z\nend\n\n\"\"\"\n    numrange!(ps_data,nstep=20)\n\ncompute the numerical range (a.k.a. field of values) of a dense matrix\nthen store it in the `ps_data`.\n\nNote: this solves an eigensystem for each point, so may be expensive.\n\"\"\"\nfunction numrange!(ps_data::PSAStruct,thmax=20)\n    ps_dict = ps_data.ps_dict\n    # don't recompute if no change\n    if !haskey(ps_dict,:fov) || (length(ps_dict[:fov]) != 2*(thmax+1))\n        # Why does upstream enforce this constraint?\n        if !haskey(ps_dict,:schur_mtx)\n            throw(ArgumentError(\"only implemented for Schur-factored matrices\"))\n        end\n        z = numerical_range(ps_dict[:schur_mtx],thmax)\n        ps_dict[:fov] = z\n    else\n        z = ps_dict[:fov]\n    end\n\n    zoom = ps_data.zoom_list[ps_data.zoom_pos]\n    ax = zoom.ax\n    if mapreduce(w -> ((real(w) < ax[1]) | (real(w) > ax[2]) |\n                       (imag(w) < ax[3]) | (imag(w) > ax[4])),\n                 &, z, init=true)\n        warn(\"The boundary of the numerical range is not visible on the \"\n             * \"current axes; expand axis limits to see it. \"\n             * \"A bounding box is $(extrema(real(z))) $(extrema(imag(z))).\")\n    end\nend\n\n\"\"\"\n    numerical_abscissa(A)\n\nCompute the numerical abscissa of a matrix `A`, `ω(A)`.\n\nUses `eigvals()`. `ω(A)` provides bounds and limiting behavior for\n`norm(expm(t*A))`.\n\"\"\"\nfunction numerical_abscissa(A::AbstractMatrix)\n    (1/2) * maximum(eigvals(A+A'))\nend\n", "meta": {"hexsha": "6e37e72cd67cf0aa9ba46a2748cc861971485f18", "size": 2696, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/numrange.jl", "max_stars_repo_name": "ranocha/Pseudospectra.jl", "max_stars_repo_head_hexsha": "63b3c62dc34707289bb73959bbeaee0529ecee36", "max_stars_repo_licenses": ["BSD-3-Clause", "MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2018-04-19T20:12:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T10:50:20.000Z", "max_issues_repo_path": "src/numrange.jl", "max_issues_repo_name": "ranocha/Pseudospectra.jl", "max_issues_repo_head_hexsha": "63b3c62dc34707289bb73959bbeaee0529ecee36", "max_issues_repo_licenses": ["BSD-3-Clause", "MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-03-19T10:14:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-17T20:58:11.000Z", "max_forks_repo_path": "src/numrange.jl", "max_forks_repo_name": "ranocha/Pseudospectra.jl", "max_forks_repo_head_hexsha": "63b3c62dc34707289bb73959bbeaee0529ecee36", "max_forks_repo_licenses": ["BSD-3-Clause", "MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-04-04T14:38:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T11:08:57.000Z", "avg_line_length": 29.6263736264, "max_line_length": 80, "alphanum_fraction": 0.6242581602, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7700652327650972}}
{"text": "# p28.jl - eigenmodes of Laplacian on the disk (compare p22.jl)\n\n# r coordinate, ranging from -1 to 1 (N must be odd):\nN = 25; N2 = Int((N-1)/2);\n(D,r) = cheb(N); D2 = D^2;\nD1 = D2[2:N2+1,2:N2+1]; D2 = D2[2:N2+1,N:-1:N2+2];\nE1 =  D[2:N2+1,2:N2+1]; E2 =  D[2:N2+1,N:-1:N2+2];\n\n# t = theta coordinate, ranging from 0 to 2*pi (M must be even):\nM = 20; dt = 2*pi/M; t = dt*(1:M); M2 = Int(M/2);\nD2t = toeplitz([-pi^2/(3*dt^2)-1/6; @. .5*(-1)^(2:M)/sin(dt*(1:M-1)/2)^2]);\n\n# Laplacian in polar coordinates:\nR = diagm(1./r[2:N2+1]);\nZ = zeros(M2,M2); I = eye(M2);\nL = kron(D1+R*E1,eye(M)) + kron(D2+R*E2,[Z I;I Z]) + kron(R^2,D2t);\n\n# Compute four eigenmodes:\nindex = [1 3 6 10];\n(Lam,V) = eig(-L); ii = sortperm(abs.(Lam))[index];\nLam = Lam[ii]; V = V[:,ii];\nLam = sqrt.(real(Lam/Lam[1]));\n\n# Plot eigenmodes with nodal lines underneath:\n(rr,tt) = (r[1:N2+1],[0;t]);\n(xx,yy) = @. (cos(tt)*rr',sin(tt)*rr');\nz = exp.(1im*pi*(-100:100)/100);\nfor i = 1:4\n    figure(i); clf();\n    u = reshape(real(V[:,i]),M,N2);\n    u = [zeros(M+1) u[[M;1:M],:]];\n    u = u/norm(u[:],Inf);\n    #plot3D(real(z),imag(z),zeros(size(z)));\n    xlim(-1.05,1.05); ylim(-1.05,1.05); zlim(-1.05,1.05); axis(\"off\");\n    surf(xx,yy,u)\n    gca()[:view_init](20,90); axis(\"square\");\n    contour3D(xx,yy,u-1,levels=[-1]);\n    plot3D(real(z),imag(z),-abs.(z));\n    title(\"Mode $(index[i]):  λ = $(signif(Lam[i],11))\",fontsize=9);\nend\n", "meta": {"hexsha": "97823251dd601a5d876ad900d4ddcbae224ec093", "size": 1395, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p28.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p28.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p28.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0243902439, "max_line_length": 75, "alphanum_fraction": 0.5397849462, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7700510473677112}}
{"text": "#=\nA builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost while ensuring that no two neighboring houses are of the same color.\n\nGiven an N by K matrix where the nth row and kth column represents the cost to build the nth house with kth color, return the minimum cost which achieves this goal.\n=#\n\nfunction minimum_building_cost(cost_matrix)\n    # Create a matrix with the cumulative minimum cost of building the nth house (row) with the kth color (column)\n    cumulative_minimum_cost = zeros(Float64, size(cost_matrix))\n    # For the first house, it is the first row of the cost_matrix\n    cumulative_minimum_cost[1,:] = cost_matrix[1,:]\n    number_of_colors = size(cost_matrix, 2)\n    number_of_houses = size(cost_matrix, 1)\n    # For the second to last houst, for each color, the minimum cumulative cost is the price of building the house in that color + the minimum cumulative cost of building the last house in a different color\n    for house in 2:number_of_houses\n        for color in 1:number_of_colors\n            allowed_prev_colors = setdiff(1:number_of_colors, color)\n            cumulative_minimum_cost[house, color] = cost_matrix[house, color] + minimum(cumulative_minimum_cost[house-1,allowed_prev_colors])\n        end\n    end\n    # We want the minimum cost of building all the house\n    minimum_cost = minimum(cumulative_minimum_cost[end,:])\n    return minimum_cost\nend\n", "meta": {"hexsha": "2ed06c718025c87fcad60d6fbbb15d17e724be67", "size": 1445, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/problem19_minimum_building_cost.jl", "max_stars_repo_name": "DominiqueCaron/daily-coding-problem", "max_stars_repo_head_hexsha": "41234497aa3a2c21c5dff43d86e9153d9582cced", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Solutions/problem19_minimum_building_cost.jl", "max_issues_repo_name": "DominiqueCaron/daily-coding-problem", "max_issues_repo_head_hexsha": "41234497aa3a2c21c5dff43d86e9153d9582cced", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2019-06-17T14:04:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-12T20:01:45.000Z", "max_forks_repo_path": "Solutions/problem19_minimum_building_cost.jl", "max_forks_repo_name": "DominiqueCaron/daily-coding-problem", "max_forks_repo_head_hexsha": "41234497aa3a2c21c5dff43d86e9153d9582cced", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.8, "max_line_length": 206, "alphanum_fraction": 0.7508650519, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731765, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7700510433908667}}
{"text": "module StockCorr\n\nif VERSION >= v\"0.7.0-DEV.3449\"\n    using LinearAlgebra\nend\n\n# The original, unoptimised code that simulates two correlated assets\nfunction perf_stockcorr()\n    ## Correlated asset information\n    CurrentPrice = [78. 102.] # Initial Prices of the two stocks\n    Corr = [1. 0.4; 0.4 1.]   # Correlation Matrix\n    T = 500                   # Number of days to simulate = 2years = 500days\n    n = 10000                 # Number of simulations\n    dt = 1/250                # Time step (1year = 250days)\n    Div = [0.01 0.01]         # Dividend\n    Vol = [0.2 0.3]           # Volatility\n\n    ## Market Information\n    r = 0.03 # Risk-free rate\n\n    ## Define storages\n    SimulPriceA = zeros(T,n) # Simulated Price of Asset A\n    SimulPriceA[1,:] .= CurrentPrice[1]\n    SimulPriceB = zeros(T,n) # Simulated Price of Asset B\n    SimulPriceB[1,:] .= CurrentPrice[2]\n\n    ## Generating the paths of stock prices by Geometric Brownian Motion\n    @static if VERSION <= v\"0.7.0-DEV.5211\"\n        UpperTriangle = chol(Corr) # UpperTriangle Matrix by Cholesky decomposition\n    else\n        UpperTriangle = cholesky(Corr).U\n    end\n\n    for i = 1:n\n       Wiener = randn(T-1,2)\n       CorrWiener = Wiener*UpperTriangle\n       for j = 2:T\n          SimulPriceA[j,i] = SimulPriceA[j-1,i]*exp((r-Div[1]-Vol[1]^2/2)*dt+Vol[1]*sqrt(dt)*CorrWiener[j-1,1])\n          SimulPriceB[j,i] = SimulPriceB[j-1,i]*exp((r-Div[2]-Vol[2]^2/2)*dt+Vol[2]*sqrt(dt)*CorrWiener[j-1,2])\n       end\n    end\n\n    return (SimulPriceA, SimulPriceB)\nend\n\nend # module\n", "meta": {"hexsha": "4451a2aab5f5beb67d565942cee6736c0d87c7fd", "size": 1546, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problem/StockCorr.jl", "max_stars_repo_name": "mschauer/BaseBenchmarks.jl", "max_stars_repo_head_hexsha": "08baef1618ebf33f53a905bb131a51c3e53e1eb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problem/StockCorr.jl", "max_issues_repo_name": "mschauer/BaseBenchmarks.jl", "max_issues_repo_head_hexsha": "08baef1618ebf33f53a905bb131a51c3e53e1eb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problem/StockCorr.jl", "max_forks_repo_name": "mschauer/BaseBenchmarks.jl", "max_forks_repo_head_hexsha": "08baef1618ebf33f53a905bb131a51c3e53e1eb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8936170213, "max_line_length": 111, "alphanum_fraction": 0.6112548512, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7700510429753323}}
{"text": "function factorial(n::Int64)\n    if n == 0 || n == 1\n        return 1\n    else\n        return n * factorial(n-1)\n    end\nend\nn = parse(Int64, readline())\nprintln(factorial(n))", "meta": {"hexsha": "97de3f2117841b34b55087245292cc773f1397e3", "size": 175, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Hackerrank/30 Days of Code/Julia/day 09.jl", "max_stars_repo_name": "Next-Gen-UI/Code-Dynamics", "max_stars_repo_head_hexsha": "a9b9d5e3f27e870b3e030c75a1060d88292de01c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Hackerrank/30 Days of Code/Julia/day 09.jl", "max_issues_repo_name": "Next-Gen-UI/Code-Dynamics", "max_issues_repo_head_hexsha": "a9b9d5e3f27e870b3e030c75a1060d88292de01c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hackerrank/30 Days of Code/Julia/day 09.jl", "max_forks_repo_name": "Next-Gen-UI/Code-Dynamics", "max_forks_repo_head_hexsha": "a9b9d5e3f27e870b3e030c75a1060d88292de01c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4444444444, "max_line_length": 33, "alphanum_fraction": 0.5714285714, "num_tokens": 54, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7700510362682459}}
{"text": "# This file is a part of BAT.jl, licensed under the MIT License (MIT).\n\n# simple 2d convolution with padding\nfunction convolution(input, filter; padding=:same)\n    input_r, input_c = size(input)\n    filter_r, filter_c = size(filter)\n\n    if padding == :same\n        pad_r = (filter_r - 1) ÷ 2 \n        pad_c = (filter_c - 1) ÷ 2 \n        \n        input_padded = zeros(input_r+(2*pad_r), input_c+(2*pad_c))\n        for i in 1:input_r, j in 1:input_c\n            input_padded[i+pad_r, j+pad_c] = input[i, j]\n        end\n        input = input_padded\n        input_r, input_c = size(input)\n    end\n\n    result = zeros(input_r-filter_r+1, input_c-filter_c+1)\n    result_r, result_c = size(result)\n\n    for i in 1:result_r\n        for j in 1:result_c\n            for k in 1:filter_r \n                for l in 1:filter_c \n                    result[i,j] += input[i+k-1,j+l-1]*filter[k,l]\n                end\n            end\n        end\n    end\n\n    return result\nend\n\n\n# gaussian kernel with same σ in both dimensions\nfunction gaussian_kernel(σ::Real; l::Int = 4*ceil(Int,σ)+1)\n    isodd(l) || throw(ArgumentError(\"length must be odd\"))\n    w = l>>1\n    g = σ == 0 ? [exp(0/(2*oftype(σ, 1)^2))] : [exp(-x^2/(2*σ^2)) for x=-w:w]\n    k = g/sum(g)\n    return (k * k')\nend\n\n# gaussian kernel with different σs in both dimensions\nfunction gaussian_kernel(\n    σs::Tuple{Real, Real}; \n    l::Tuple{Int, Int} = (4*ceil(Int,σs[1])+1, 4*ceil(Int,σs[2])+1)\n)\n    all(isodd.(l)) || throw(ArgumentError(\"length must be odd\"))\n    w1 = l[1]>>1\n    g1 = σs[1] == 0 ? [exp(0/(2*oftype(σs[1], 1)^2))] : [exp(-x^2/(2*σs[1]^2)) for x=-w1:w1]\n    k1 = g1/sum(g1)\n\n    w2 = l[2]>>1\n    g2 = σs[2] == 0 ? [exp(0/(2*oftype(σs[2], 1)^2))] : [exp(-x^2/(2*σs[2]^2)) for x=-w2:w2]\n    k2 = g2/sum(g2)\n\n    return (k1 * k2')  \nend\n", "meta": {"hexsha": "59c4b6420c0d9fa848bdccd65035cfe3419aa5cf", "size": 1797, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/convolution_utils.jl", "max_stars_repo_name": "Micki-D/BAT.jl", "max_stars_repo_head_hexsha": "15e470654de300eb99f5b9f5a864764f59ac74db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 136, "max_stars_repo_stars_event_min_datetime": "2017-11-28T20:26:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T11:05:27.000Z", "max_issues_repo_path": "src/utils/convolution_utils.jl", "max_issues_repo_name": "Micki-D/BAT.jl", "max_issues_repo_head_hexsha": "15e470654de300eb99f5b9f5a864764f59ac74db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 283, "max_issues_repo_issues_event_min_datetime": "2017-09-04T09:15:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:55:49.000Z", "max_forks_repo_path": "src/utils/convolution_utils.jl", "max_forks_repo_name": "Micki-D/BAT.jl", "max_forks_repo_head_hexsha": "15e470654de300eb99f5b9f5a864764f59ac74db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2017-08-23T22:17:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T23:52:33.000Z", "avg_line_length": 28.9838709677, "max_line_length": 92, "alphanum_fraction": 0.5537006121, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7700510339535376}}
{"text": "#Constant mean function\n\n\"\"\"\n    MeanConst <: Mean\n\nConstant mean function\n```math\nm(x) = β\n```\nwith constant ``β``.\n\"\"\"\nmutable struct MeanConst <: Mean\n    \"Constant\"\n    β::Float64\n    \"Priors for mean parameters\"\n    priors::Array\n\n    \"\"\"\n        MeanConst(β::Float64)\n\n    Create `MeanConst` with constant `β`.\n    \"\"\"\n    MeanConst(β::Float64) = new(β, [])\nend\n\nmean(mConst::MeanConst, x::AbstractVector) = mConst.β\nmean(mConst::MeanConst, X::AbstractMatrix) = fill(mConst.β, size(X,2))\n\nget_params(mConst::MeanConst) = Float64[mConst.β]\nget_param_names(::MeanConst) = [:β]\nnum_params(mConst::MeanConst) = 1\nfunction set_params!(mConst::MeanConst, hyp::AbstractVector)\n    length(hyp) == 1 || throw(ArgumentError(\"Constant mean function only has 1 parameter\"))\n    mConst.β = hyp[1]\nend\nfunction grad_mean(mConst::MeanConst, x::AbstractVector)\n    dM_theta = ones(1)\n    return dM_theta\nend\n", "meta": {"hexsha": "1ecbfeb80c7d19c446263acbb202381f6c157d2c", "size": 898, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/means/mConst.jl", "max_stars_repo_name": "mcusi/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 284, "max_stars_repo_stars_event_min_datetime": "2015-07-31T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T07:08:58.000Z", "max_issues_repo_path": "src/means/mConst.jl", "max_issues_repo_name": "mcusi/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 171, "max_issues_repo_issues_event_min_datetime": "2015-05-28T12:04:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T06:48:23.000Z", "max_forks_repo_path": "src/means/mConst.jl", "max_forks_repo_name": "mcusi/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-05-31T12:44:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:21:38.000Z", "avg_line_length": 22.45, "max_line_length": 91, "alphanum_fraction": 0.6748329621, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8577681122619885, "lm_q1q2_score": 0.7700143914019719}}
{"text": "push!( LOAD_PATH, \"../\" )\nimport InformationInequalities  # Import the module to  have access to functions\n\n\"\"\"\nList down all conditional Entropy expressions for a given number `n` of random variables. Conditional Entropies are of the form `H(X,Y|Z)` \n```julia-repl\njulia> ConditionalEntropyList(2,\"🍉\")\n[\"H(🍉1)\" \"H(🍉1|🍉2)\" \"H(🍉2)\" \"H(🍉2|🍉1)\"]\n\njulia> ConditionalEntropyList(2)\n[\"H(X1)\" \"H(X1|X2)\" \"H(X2)\" \"H(X2|X1)\"]\n\njulia> ConditionalEntropyList(3,\"dice💠\")\n[\"H(dice💠1)\"\n\"H(dice💠1|dice💠2)\"\n\"H(dice💠1|dice💠2,dice💠3)\"\n\"H(dice💠1|dice💠3)\"\n\"H(dice💠2)\"\n\"H(dice💠2|dice💠1)\"\n\"H(dice💠2|dice💠1,dice💠3)\"\n\"H(dice💠2|dice💠3)\"\n\"H(dice💠3)\"\n\"H(dice💠3|dice💠1)\"\n\"H(dice💠3|dice💠1,dice💠2)\"\n\"H(dice💠3|dice💠2)\"]\n\njulia> ConditionalEntropy(3,\"Z\")\n[\"H(Z1)\"\n\"H(Z1|Z2)\"\n\"H(Z1|Z2,Z3)\"\n\"H(Z1|Z3)\"\n\"H(Z2)\"\n\"H(Z2|Z1)\"\n\"H(Z2|Z1,Z3)\"\n\"H(Z2|Z3)\"\n\"H(Z3)\"\n\"H(Z3|Z1)\"\n\"H(Z3|Z1,Z2)\"\n\"H(Z3|Z2)\"]\n```\n\"\"\"\nfunction ConditionalEntropyList(m::Int64=2,RV::AbstractString=\"X\")\n\ty=  [(\"$(RV)\" .* string(i) *  \"|\" * find_subset(m,i,[],RV)[k]) for i=1:m for k=1:Int64(exp2(m-1)) ]\n\ty0=replace.(y,\"|\" => \"| \")\n\ty1=replace.(y0,\"| $(RV)\" => \"|$(RV)\")\n\ty2=replace.(y1,\"| \" => \"\")\n\tyy = \"H(\" .* y2 .* \")\"\n\treturn yy[:]\nend", "meta": {"hexsha": "b39e5e8f2c5eab28bc0fc64dc690761a99256537", "size": 1169, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/entropy/entropies.jl", "max_stars_repo_name": "nivupai/InformationInequalities.jl", "max_stars_repo_head_hexsha": "9c221fe3985c27187b4752e1792059ff3c09f987", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2022-01-17T18:41:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T23:51:05.000Z", "max_issues_repo_path": "src/entropy/entropies.jl", "max_issues_repo_name": "nivupai/InformationInequalities.jl", "max_issues_repo_head_hexsha": "9c221fe3985c27187b4752e1792059ff3c09f987", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2022-01-15T00:22:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T23:06:52.000Z", "max_forks_repo_path": "src/entropy/entropies.jl", "max_forks_repo_name": "nivupai/InformationInequalities.jl", "max_forks_repo_head_hexsha": "9c221fe3985c27187b4752e1792059ff3c09f987", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8571428571, "max_line_length": 139, "alphanum_fraction": 0.5842600513, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.7700143816100669}}
{"text": "import StatsBase: sample\n\n# Model selection\n\n# Taken from https://royalsocietypublishing.org/doi/pdf/10.1098/rspa.2017.0009\n\"\"\"\n\t$(SIGNATURES)\n\nComputes the Akaike Information Criterion (AIC) given the free parameters `k` for the data `X` and its\nestimate `Y` of the model. `likelihood` can be any function of `X` and `Y`.\n\"\"\"\nfunction AIC(k::Int64, X::AbstractArray, Y::AbstractArray; likelihood = (X,Y) -> sum(abs2, X-Y))\n    @assert size(X) == size(Y) \"Dimensions of trajectories should be equal !\"\n    return 2*k - 2*log(likelihood(X, Y))\nend\n\n# Taken from https://royalsocietypublishing.org/doi/pdf/10.1098/rspa.2017.0009\n\"\"\"\n\t$(SIGNATURES)\n\nComputes the Akaike Information Criterion compensated for finite samples (AICC) given the free parameters `k` for the data `X` and its\nestimate `Y` of the model. `likelihood` can be any function of `X` and `Y`.\n\"\"\"\nfunction AICC(k::Int64, X::AbstractMatrix, Y::AbstractMatrix; likelihood = (X,Y) -> sum(abs2, X-Y))\n    @assert size(X) == size(Y) \"Dimensions of trajectories should be equal !\"\n    return AIC(k, X, Y, likelihood = likelihood)+ 2*(k+1)*(k+2)/(size(X)[2]-k-2)\nend\n\nfunction AICC(k::Int64, X::AbstractVector, Y::AbstractVector; likelihood = (X,Y) -> sum(abs2, X-Y))\n    @assert size(X) == size(Y) \"Dimensions of trajectories should be equal !\"\n    return AIC(k, X, Y, likelihood = likelihood)+ 2*(k+1)*(k+2)/(length(X)-k-2)\nend\n\n# Double check on that\n# Taken from https://www.immagic.com/eLibrary/ARCHIVES/GENERAL/WIKIPEDI/W120607B.pdf\n\"\"\"\n\t$(SIGNATURES)\n\nComputes Bayes Information Criterion (BIC) given the free parameters `k` for the data `X` and its\nestimate `Y` of the model. `likelihood` can be any function of `X` and `Y`.\n\"\"\"\nfunction BIC(k::Int64, X::AbstractMatrix, Y::AbstractMatrix; likelihood = (X,Y) -> sum(abs2, X-Y))\n    @assert size(X) == size(Y) \"Dimensions of trajectories should be equal !\"\n    return - 2*log(likelihood(X, Y)) + k*log(size(X)[2])\nend\n\nfunction BIC(k::Int64, X::AbstractVector, Y::AbstractVector; likelihood = (X,Y) -> sum(abs2, X-Y))\n    @assert size(X) == size(Y) \"Dimensions of trajectories should be equal !\"\n    return - 2*log(likelihood(X, Y)) + k*log(length(X))\nend\n\n# Optimal Shrinkage for data in presence of white noise\n# See D. L. Donoho and M. Gavish, \"The Optimal Hard Threshold for Singular\n# Values is 4/sqrt(3)\", http://arxiv.org/abs/1305.5870\n# Code taken from https://github.com/erichson/optht\n\nfunction optimal_svht(m::Int64, n::Int64; known_noise::Bool = false)\n    @assert m/n > 0\n    @assert m/n <= 1\n\n    β = m/n\n    ω = (8*β) / (β+1+sqrt(β^2+14β+1))\n    c = sqrt(2*(β+1)+ω)\n\n    if known_noise\n        return c\n    else\n        median = median_marcenko_pastur(β)\n        return c / sqrt(median)\n    end\nend\n\nfunction marcenko_pastur_density(t, lower, upper, beta)\n    sqrt((upper-t).*(t-lower))./(2π*beta*t)\nend\n\nfunction incremental_marcenko_pastur(x, beta, gamma)\n    @assert beta <= 1\n    upper = (1+sqrt(beta))^2\n    lower = (1-sqrt(beta))^2\n\n    @inline marcenko_pastur(x) = begin\n        if (upper-x)*(x-lower) > 0\n            return marcenko_pastur_density(x, lower, upper, beta)\n        else\n            return zero(eltype(x))\n        end\n    end\n\n    if gamma ≈ zero(eltype(gamma))\n        i, ϵ = quadgk(x->(x^gamma)*marcenko_pastur(x), x, upper)\n        return i\n    else\n        i, ϵ = quadgk(x->marcenko_pastur(x), x, upper)\n        return i\n    end\nend\n\nfunction median_marcenko_pastur(beta)\n    @assert 0 < beta <= 1\n    upper = (1+sqrt(beta))^2\n    lower = (1-sqrt(beta))^2\n    change = true\n    x = ones(eltype(upper), 5)\n    y = similar(x)\n    while change && (upper - lower > 1e-5)\n        x = range(lower, upper, length = 5)\n        for (i,xi) in enumerate(x)\n            y[i] = one(eltype(x)) - incremental_marcenko_pastur(xi, beta, 0)\n        end\n        any(y .< 0.5) ? lower = maximum(x[y .< 0.5]) : change = false\n        any(y .> 0.5) ? upper = minimum(x[y .> 0.5]) : change = false\n    end\n    return (lower+upper)/2\nend\n\n\"\"\"\n    $(SIGNATURES)\n\nCompute a feature reduced version of the data array `X` via thresholding the\nsingular values by computing the [optimal threshold for singular values](http://arxiv.org/abs/1305.5870).\n\"\"\"\nfunction optimal_shrinkage(X::AbstractArray{T, 2}) where T <: Number\n    m,n = minimum(size(X)), maximum(size(X))\n    U, S, V = svd(X)\n    τ = optimal_svht(m,n)\n    inds = S .>= τ*median(S)\n    return U[:, inds]*Diagonal(S[inds])*V[:, inds]'\nend\n\n\"\"\"\n    $(SIGNATURES)\n\nCompute a feature reduced version of the data array `X` inplace via thresholding the\nsingular values by computing the [optimal threshold for singular values](http://arxiv.org/abs/1305.5870).\n\"\"\"\nfunction optimal_shrinkage!(X::AbstractArray{T, 2}) where T <: Number\n    m,n = minimum(size(X)), maximum(size(X))\n    U, S, V = svd(X)\n    τ = optimal_svht(m,n)\n    inds = S .>= τ*median(S)\n    X .= U[:, inds]*Diagonal(S[inds])*V[:, inds]'\n    return\nend\n", "meta": {"hexsha": "da75ca1c0007531121ff22f639cb65981e838c8e", "size": 4901, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/utils.jl", "max_stars_repo_name": "yewalenikhil65/DataDrivenDiffEq.jl", "max_stars_repo_head_hexsha": "1cdeafc7de8af3b3dad2ef03669e30f81043e22b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2019-11-22T17:20:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-07T17:10:27.000Z", "max_issues_repo_path": "src/utils/utils.jl", "max_issues_repo_name": "yewalenikhil65/DataDrivenDiffEq.jl", "max_issues_repo_head_hexsha": "1cdeafc7de8af3b3dad2ef03669e30f81043e22b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 53, "max_issues_repo_issues_event_min_datetime": "2019-11-22T17:20:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T15:11:55.000Z", "max_forks_repo_path": "src/utils/utils.jl", "max_forks_repo_name": "yewalenikhil65/DataDrivenDiffEq.jl", "max_forks_repo_head_hexsha": "1cdeafc7de8af3b3dad2ef03669e30f81043e22b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-11-22T18:36:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:36:14.000Z", "avg_line_length": 33.8, "max_line_length": 134, "alphanum_fraction": 0.6445623342, "num_tokens": 1548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.770000395600307}}
{"text": "# Comparison of high-level programming languages\n# This is Julia (version 1.3.1)\n\n# Function\nfunction power(x, a)\n  x^a\nend\nthree_squared = power(3, 2)\n\n# Anonymous function\npower2 = (x, a) ->  x^a\n@assert(power2(3, 2) == power(3, 2))\n\n# Assignment form\npower3(x, a) = x^a\n@assert(power3(3, 2) == power(3, 2))\n\n# Variable assignment\nx = power(2, 0.5)\n\n# Standard output\nprintln(x)\n\n# Formatted output\nusing Printf\n@printf(\"%5.2f\\n\", x)\n\n# Definite loop\nfor i in 1:5\n  println(i)\nend\n\n# Indefinite loop\ni = 1\nwhile i <= 5\n  println(i)\n  global i += 1\nend\n\n# List\nelements = [\"H\", \"He\", \"Li\"]  # Array\nprintln(elements)\n\n# Dictionary\nelements = Dict(\n    \"H\" => 1,\n    \"He\" => 2, \n    \"Li\" => 3\n)\nprintln(elements)\n\n# Iterating over collections\nfor (symbol, n) in elements\n  @printf(\"%s: %d\\n\", symbol, n)\nend\n\n# Array literals\n\n# Vector (1d)\nx = [1, 2, 3]\nprintln(x)\n\n# Matrix (2d)\nA = [1 2; 3 4; 5 6]\nprintln(A)\n\n# 3d array (3x2x3)\nZ = ones(3, 2, 3)\nprintln(Z)\n\n# Array dimensions\nprintln(size(x))\nprintln(size(A))\nprintln(size(Z))\n\n# Indexing arrays\nprintln(x[2])\nprintln(A[2,2])\nprintln(A[2])\n\n# Slicing arrays\nprintln(x[2:end])\nprintln(A[:,2])\n\n# Concatenation of vector and 2-d array\nC = [x A]\nprintln(C)\n\n# Array broadcasting\nprintln(1 .- A)\nprintln(A .+ x)\n\n# Linear algebra\nusing LinearAlgebra\nA = [0.8 0; 0 1]\nK = [0.942; 1.074]\nC = [0.2 1]\nX = (I - A + K*C)^-1\nprintln(X)\n\n# Symbolic math\ny = :(a*x^2 + b*x + c)  # Symbolic expressions are built in\nusing Reduce\ndydx = Algebra.df(y,:x)\nx_sol = Algebra.solve(dydx,:x)\ny_sol = Algebra.sub(x_sol,y)\nprintln(dydx)\nprintln(x_sol)\nprintln(y_sol)\n\n# Non-vectorized method\nfunction lorenz(y1, y2, y3, sigma::Float64, \n                beta::Float64, rho::Float64)\n  return (sigma * (y2 - y1), y1 * (rho - y3) - y2, \n          y1 * y2 - beta * y3)\nend\nlorenz(y::Tuple{Float64,Float64,Float64}, \n       sigma::Float64, beta::Float64, \n       rho::Float64) = (\n         lorenz(y[1], y[2], y[3], sigma, beta, rho)\n       )\n\n# Vectorized method 1\n# function lorenz(y1::Array, y2::Array, y3::Array, \n#                 sigma::Float64, beta::Float64, \n#                 rho::Float64)\n#   dy1 = sigma.*(y2.-y1)\n#   dy2 = y1.*(rho.-y3).-y2\n#   dy3 = y1.*y2.-beta.*y3\n#   return [dy1 dy2 dy3]'\n# end\n# lorenz(y::Array, sigma::Float64, beta::Float64, \n#        rho::Float64) = (\n#          lorenz(y[1,:], y[2,:], y[3,:], sigma, beta, rho)\n#        )\n# Vectorized method 2\n# function lorenz(y::Array, sigma::Float64, beta::Float64, \n#   rho::Float64)\n# dy = similar(y)\n# dy[1,:] = sigma.*(y[2,:].-y[1,:])\n# dy[2,:] = y[1,:].*(rho.-y[3,:]).-y[2,:]\n# dy[3,:] = y[1,:].*y[2,:].-beta.*y[3,:]\n# return dy\n# end\n# Vectorized method 3\nfunction lorenz(\n  y::Tuple{Array{Float64,1},Array{Float64,1},Array{Float64,1}}, \n  sigma::Float64, beta::Float64, rho::Float64\n  )\n  return (sigma.*(y[2].-y[1]), y[1].*(rho.-y[3]).-y[2], \n          y[1].*y[2].-beta.*y[3])\nend\n# This is not faster than method 3 above:\nfunction lorenz(y::Array{Float64,2}, sigma::Float64, beta::Float64, \n                rho::Float64)\n  return (sigma.*(y[2,:].-y[1,:]), y[1,:].*(rho.-y[3,:]).-y[2,:], \n          y[1,:].*y[2,:].-beta.*y[3,:])\nend\n\n\n# Parameter values\nbeta = 8 / 3\nsigma = 10.0\nrho = 28.0\ny0 = (-8.0, 8.0, 27.0)\ndy = lorenz(y0, sigma, beta, rho)\nprintln(dy)\n@assert dy == (160.0, -16.0, -136.0)\n\n# Test - vectorized method 2\n# y = repeat([-8.0, 8.0, 27.0], 1, 10)\n# dy = lorenz(y, sigma, beta, rho)\n# @assert size(dy) == size(y)\n# @assert dy == repeat([160.0,  -16.0, -136.0], 1, 10)\n\n# Test - vectorized method 3\ny = (repeat([-8.0],10), repeat([8.0],10), repeat([27.0],10))\ndy = lorenz(y, sigma, beta, rho)\n@assert length(dy) == length(y)\n\ny = randn(3,10000)\ny = (y[1,:], y[2,:], y[3,:])\n@time dy = lorenz(y, sigma, beta, rho)\n\n# Speed Tests\n# Single function call - 0.000006 seconds\n# Vectorized function call method 1 - 0.000404 seconds\n# Vectorized function call method 2 - 0.001036 seconds\n# Vectorized function call method 3 - 0.000187 seconds\n# Note: Why is this 7 times slower than Python?\n# (Using: @time dy = lorenz(y, sigma, beta, rho);)\n", "meta": {"hexsha": "43760c3c7a9a3560f75f8e71ca49e2966e28482d", "size": 4062, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia-examples.jl", "max_stars_repo_name": "billtubbs/lang-comp", "max_stars_repo_head_hexsha": "8acf54a688c60b102f07bef91e6b5cbaaabdd95c", "max_stars_repo_licenses": ["OLDAP-2.3"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-13T17:42:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T19:40:27.000Z", "max_issues_repo_path": "julia-examples.jl", "max_issues_repo_name": "billtubbs/lang-comp", "max_issues_repo_head_hexsha": "8acf54a688c60b102f07bef91e6b5cbaaabdd95c", "max_issues_repo_licenses": ["OLDAP-2.3"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-15T20:05:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-15T20:05:50.000Z", "max_forks_repo_path": "julia-examples.jl", "max_forks_repo_name": "billtubbs/lang-comp", "max_forks_repo_head_hexsha": "8acf54a688c60b102f07bef91e6b5cbaaabdd95c", "max_forks_repo_licenses": ["OLDAP-2.3"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.15625, "max_line_length": 68, "alphanum_fraction": 0.589611029, "num_tokens": 1581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.8918110432813419, "lm_q1q2_score": 0.7699821787206502}}
{"text": "export line, sigmoid, hardsigmoid, relu, elu, selu, tanh, hardtanh, softsign, softplus\n\nfunction line(x)\n    return x\nend\n\nline(x, back::Bool) = 1\n\nfunction sigmoid(x)\n    t = exp(-abs(x))\n    return (x>=0) ? inv(1 + t) : t / (t + 1)\nend\n\nsigmoid(x, back::Bool) = sigmoid(x)*(1-sigmoid(x))\n\nhardsigmoid(x) = max(0, min(1, (x + 2.5) / 6))\n\nfunction hardsigmoid(x, back::Bool)\n    if -2.5 <= x <= 2.5\n        return 0.2\n    else\n        return 0\n    end\nend\n\nrelu(x) = max(0, x)\n\nfunction relu(x, back::Bool)\n    if x <= 0\n        return 0\n    else\n        return 1\n    end\nend\n\nfunction elu(x; alpha = 1)\n    return (x > 0) ? x : (exp(x) - 1)alpha\nend\n\nfunction elu(x, back::Bool; alpha = 1)\n    if x < 0\n        return alpha*exp(x)\n    else\n        return 1\n    end\nend\n\nfunction selu(x)\n    λ = oftype(float(x), selu_λ)\n    α = oftype(float(x), selu_α)\n    return ((x > 0) ? x : (exp(x)-1)α)*λ\nend\n\nfunction selu(x, back::Bool)\n    λ = oftype(float(x), selu_λ)\n    α = oftype(float(x), selu_α)\n    if x < 0\n        return λ*alpha*exp(x)\n    else\n        return λ\n    end\nend\n\nconst selu_λ = 1.0507009873554804934193349852946\nconst selu_α = 1.6732632423543772848170429916717\n\nfunction tanh(x)\n    return exp(x) - exp(-x) / exp(x) + exp(-x)\nend\n\ntanh(x, back::Bool) = 4 / (exp(x) + exp(-x)) ^ 2\n\nfunction hardtanh(x)\n    if x > 1\n        return 1\n    elseif x < -1\n        return -1\n    else\n        return x\n    end\nend\n\nfunction hardtanh(x, back::Bool)\n    if x < -1 || 1 <= x\n        return 0\n    else\n        return 1\n    end\nend\n\nfunction softsign(x)\n    return x / (1 + abs(x))\nend\n\nsoftsign(x, back::Bool) = 1 / ((1 + abs(x))^2)\n\nfunction softplus(x)\n    return log(1 + exp(x))\nend\n\nsoftplus(x, back::Bool) = 1 / (1 + exp(-x))", "meta": {"hexsha": "ef5a83a0858084463e61d1fa221114295c70ec24", "size": 1732, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NeuralNetwork/activations.jl", "max_stars_repo_name": "QGMW22/Horse.jl", "max_stars_repo_head_hexsha": "77be589dbf047a029615dde7773360ebcb5d99b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-19T13:09:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-19T13:09:53.000Z", "max_issues_repo_path": "src/NeuralNetwork/activations.jl", "max_issues_repo_name": "QGMW22/Horse", "max_issues_repo_head_hexsha": "77be589dbf047a029615dde7773360ebcb5d99b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-21T13:52:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-21T13:52:40.000Z", "max_forks_repo_path": "src/NeuralNetwork/activations.jl", "max_forks_repo_name": "QGMW22/Horse", "max_forks_repo_head_hexsha": "77be589dbf047a029615dde7773360ebcb5d99b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1485148515, "max_line_length": 86, "alphanum_fraction": 0.5577367206, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.769982166212987}}
{"text": "\"\"\"\nDetermine the number of meters per pixel\n\n### Parameters\n* `lat`: latitude in radians\n* `z`: zoom level\n\nSource: http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Resolution_and_Scale\n\"\"\"\nfunction resolution(lat::Real, z::Integer)\n    meter_per_pixel = 156543.03 # For zoom = 0 at equator\n    meter_per_pixel * cos(lat) / (2^z)\nend\n\n\"Convert from `lat,lon` to tile numbers (float64)\"\nfunction lonlat2tile(lon::Real, lat::Real, z::Integer)\n    latradian = deg2rad(lat); n = 2^z\n    x = (lon + 180)/360*n\n    y = (1 - log(tan(latradian) + 1/cos(latradian))/pi)/2*n\n    x, y\nend\n\n\"Convert from `lat,lon` to tile numbers, rounding them down to integers\"\nfunction ilonlat2tile(lon::Real, lat::Real, z::Integer)\n    x, y = lonlat2tile(lon, lat, z)\n    floor(Int, x), floor(Int, y)\nend\n\n\"Convert geographical coordinates to tile coordinates\"\nfunction lonlat2tile(\n        lon::Real, lat::Real, z::Integer, xmin::Real, ymin::Real,\n        tilesizex::Integer, tilesizey::Integer\n    )\n    x, y = lonlat2tile(lon, lat, z)\n    floor(Int,(x-xmin)*tilesizex)+1, floor(Int,(y-ymin)*tilesizey)+1\nend\n\nlonlat2tile(basemap::BaseMap, lon::Real, lat::Real) = lonlat2tile(\n    lon, lat, basemap.zoom, basemap.xmin, basemap.ymin,\n    basemap.tilesize[2], basemap.tilesize[1]\n)\n\n\"\"\"\nConvert a box from geographical to tile coordinates (integers), at a given zoom.\n\"\"\"\nfunction tilebox(\n        minlon::Real,\n        minlat::Real,\n        maxlon::Real,\n        maxlat::Real,\n        z::Integer\n    )\n    xmin, ymin = ilonlat2tile(minlon, minlat, z)\n    xmax, ymax = ilonlat2tile(maxlon, maxlat, z)\n    xmin, ymin, xmax, ymax\nend\n\n\"Determine the correct tiles for `(xmin, ymin, xmax, ymax)` at zoom `z`\"\nfunction correctbox(\n        xmin::Integer,\n        ymin::Integer,\n        xmax::Integer,\n        ymax::Integer,\n        z::Integer\n    )\n    new_xmin = max(0, min(xmin, xmax))\n    new_ymin = max(0, min(ymin, ymax))\n    new_xmax = min(2^z - 1, max(xmin, xmax))\n    new_ymax = min(2^z - 1, max(ymin, ymax))\n    new_xmin, new_ymin, new_xmax, new_ymax\nend\n\nfunction boxsize(provider::AbstractProvider, xmin, ymin, xmax, ymax)\n    abs(xmax - xmin) + 1, abs(ymax - ymin) + 1\nend\n", "meta": {"hexsha": "4ec2f44e771cc218a6c22849de9b9bc023ab0942", "size": 2164, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "scls19fr/MapTiles.jl", "max_stars_repo_head_hexsha": "58029f3fb60c202a97aca10214139c0d2eb8396b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-01-14T00:05:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-18T17:31:30.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "scls19fr/MapTiles.jl", "max_issues_repo_head_hexsha": "58029f3fb60c202a97aca10214139c0d2eb8396b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2018-01-06T08:54:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-07T08:10:50.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "scls19fr/MapTiles.jl", "max_forks_repo_head_hexsha": "58029f3fb60c202a97aca10214139c0d2eb8396b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:01:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-04T07:02:00.000Z", "avg_line_length": 28.4736842105, "max_line_length": 84, "alphanum_fraction": 0.6501848429, "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478306, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.769900198396871}}
{"text": "Base.zero(x::arb_series) = arb_series(x.poly.parent(0), x.length)\n\n\"\"\"\n    bessel_j(ν::arb, z::arb_series[, n = length(z)])\n\n> Compute the Taylor series of the Bessel function.\n\nIt's computed using a recursive formula for the Taylor coefficients\nof the Bessel functions and then composing it with `z`.\n\"\"\"\nfunction bessel_j(ν::arb, z::arb_series, n = length(z))\n    res = arb_series(parent(z.poly)(), n)\n\n    if n > 0\n        x = z[0]\n        a0 = bessel_j(ν, x)\n        res[0] = a0\n\n        if !isfinite(a0)\n            return arb_series(parent(z.poly)(fill(NaN, n)), n)\n        end\n\n        if n > 1\n            a1 = 1 // 2 * (bessel_j(ν - 1, x) - bessel_j(ν + 1, x))\n            res[1] = a1\n\n            if !isfinite(a0)\n                return arb_series(parent(z.poly)(fill(NaN, n)), n)\n            end\n\n            if n > 2\n                a2 = 1 // 8 * (bessel_j(ν - 2, x) + bessel_j(ν + 2, x) - 2a0)\n                res[2] = a2\n\n\n                if !isfinite(a0)\n                    return arb_series(parent(z.poly)(fill(NaN, n)), n)\n                end\n\n                if n > 3\n                    a3 = 1 // 48 * (bessel_j(ν - 3, x) - bessel_j(ν + 3, x) - 6a1)\n                    res[3] = a3\n\n\n                    if !isfinite(a0)\n                        return arb_series(parent(z.poly)(fill(NaN, n)), n)\n                    end\n\n                    if n > 4\n                        x2 = x^2\n                        ν2 = ν^2\n                        for i = 4:n-1\n                            k = i - 4\n                            ai =\n                                -(\n                                    res[k] +\n                                    2x * res[k+1] +\n                                    (k^2 + 4k + 4 - ν2 + x2) * res[k+2] +\n                                    (2k^2 + 11k + 15) * x * res[k+3]\n                                ) / (x2 * (k^2 + 7k + 12))\n                            res[i] = ai\n                        end\n                    end\n                end\n            end\n        end\n    end\n    # Compose the Taylor series for the Bessel function with that of z\n    z_tmp = arb_series(deepcopy(z.poly))\n    z_tmp[0] = base_ring(parent(z.poly))(0)\n\n    return Nemo.compose(res, z_tmp, n)\nend\n\n\"\"\"\n    bessel_y(ν::arb, z::arb_series[, n = length(z)])\n\nCompute the Taylor series of the Bessel function.\n\nIt's computed using a recursive formula for the Taylor coefficients of\nthe Bessel functions and then composing it with `z`. Note that since\nboth `bessel_j` and `bessel_y` satisfy the same differential equation\nthe recursive formula is the same.\n\"\"\"\nfunction bessel_y(ν::arb, z::arb_series, n = length(z))\n    res = arb_series(parent(z.poly)(), n)\n\n    if n > 0\n        x = z[0]\n        a0 = bessel_y(ν, x)\n        res[0] = a0\n\n        if !isfinite(a0)\n            return arb_series(parent(z.poly)(fill(NaN, n)), n)\n        end\n\n        if n > 1\n            a1 = 1 // 2 * (bessel_y(ν - 1, x) - bessel_y(ν + 1, x))\n            res[1] = a1\n\n            if !isfinite(a0)\n                return arb_series(parent(z.poly)(fill(NaN, n)), n)\n            end\n\n            if n > 2\n                a2 = 1 // 8 * (bessel_y(ν - 2, x) + bessel_y(ν + 2, x) - 2a0)\n                res[2] = a2\n\n\n                if !isfinite(a0)\n                    return arb_series(parent(z.poly)(fill(NaN, n)), n)\n                end\n\n                if n > 3\n                    a3 = 1 // 48 * (bessel_y(ν - 3, x) - bessel_y(ν + 3, x) - 6a1)\n                    res[3] = a3\n\n\n                    if !isfinite(a0)\n                        return arb_series(parent(z.poly)(fill(NaN, n)), n)\n                    end\n\n                    if n > 4\n                        x2 = x^2\n                        ν2 = ν^2\n                        for i = 4:n-1\n                            k = i - 4\n                            ai =\n                                -(\n                                    res[k] +\n                                    2x * res[k+1] +\n                                    (k^2 + 4k + 4 - ν2 + x2) * res[k+2] +\n                                    (2k^2 + 11k + 15) * x * res[k+3]\n                                ) / (x2 * (k^2 + 7k + 12))\n                            res[i] = ai\n                        end\n                    end\n                end\n            end\n        end\n    end\n    # Compose the Taylor series for the Bessel function with that of z\n    z_tmp = arb_series(deepcopy(z.poly))\n    z_tmp[0] = base_ring(parent(z.poly))(0)\n\n    return Nemo.compose(res, z_tmp, n)\nend\n\n\"\"\"\n    legendre_p(ν::arb_series, μ::arb, z::arb[, n = length(ν)])\n\n> Compute the Taylor series of the Legendre function with respect to\n  the parameter ν.\n\"\"\"\nfunction legendre_p(ν::arb_series, μ::arb, z::arb, n = length(ν))\n    CC = ComplexField(z.parent.prec)\n    PP = AcbPolyRing(CC, :x)\n    νν = PP(ν.poly)\n    μμ = PP(μ)\n    zz = PP(z)\n\n    a = -νν\n    b = νν + 1\n    c = 1 - μμ\n\n    res = PP()\n\n    ccall(\n        (:acb_hypgeom_2f1_series_direct, :libarb),\n        Cvoid,\n        (\n            Ref{acb_poly},\n            Ref{acb_poly},\n            Ref{acb_poly},\n            Ref{acb_poly},\n            Ref{acb_poly},\n            Cint,\n            Clong,\n            Clong,\n        ),\n        res,\n        a,\n        b,\n        c,\n        0.5 * (1 - zz),\n        1,\n        2,\n        CC.prec,\n    )\n\n    realres = arb_series(ν.poly.parent([real(coeff(res, i)) for i = 0:degree(res)]), n)\n    ((1 + z) / (1 - z))^(μ / 2) * realres\nend\n\n\"\"\"\n    legendre_p(ν::arb, μ::arb, z::arb_series[, n = length(z)])\n\n> Compute the Taylor series of the Legendre function.\n\nIt's computed using a recursive formula for the Taylor coefficients\nof the Legendre functions and then composing it with `z`.\n\"\"\"\nfunction legendre_p(ν::arb, μ::arb, z::arb_series, n = length(z))\n    # TODO: Precompute values used several times\n    res = arb_series(parent(z.poly)(), n)\n\n    if n > 0\n        x = z[0]\n        a0 = legendre_p_safe(ν, μ, x)\n        res[0] = a0\n\n        if !isfinite(a0)\n            return arb_series(parent(z.poly)(fill(NaN, n)), n)\n        end\n\n        if n > 1\n            x2 = x^2\n            onemx2 = 1 - x2\n\n            a1 = ((ν + 1) * x * a0 - (ν - μ + 1) * legendre_p_safe(ν + 1, μ, x)) / (onemx2)\n            res[1] = a1\n\n            if !isfinite(a1)\n                return arb_series(parent(z.poly)(fill(NaN, n)), n)\n            end\n\n            if n > 2\n                ν2 = ν^2\n                μ2 = μ^2\n\n                a2 = (2x * a1 - (ν2 + ν - μ2 / (onemx2)) * a0) / (2(onemx2))\n                res[2] = a2\n\n                if n > 3\n                    a3 =\n                        (\n                            4(onemx2)^2 * x * a2 +\n                            2(2μ2 - (ν2 + ν) * (onemx2)) * x * a0 +\n                            ((ν2 + ν + 2) * x2 + μ2 - ν2 - ν + 2) * (onemx2) * a1\n                        ) / (6 * (onemx2)^3)\n                    res[3] = a3\n\n                    if n > 4\n                        onemx22 = onemx2^2\n                        xonemx2 = x * onemx2\n                        ν2pν = ν2 + ν\n                        μ2mν2pν = μ2 - ν2pν\n                        fourx = 4x\n                        for i = 4:n-1\n                            k = i - 4\n                            ai =\n                                (\n                                    (k + 1 + ν) * (ν - k) * res[k] -\n                                    (0.5 * (2k^2 + (5k + 3) - ν2pν)) * fourx * res[k+1] +\n                                    (\n                                        ((-6k^2 - 24k - 24) + ν2pν) * x2 +\n                                        (2k^2 + 8k + 8) +\n                                        μ2mν2pν\n                                    ) * res[k+2] +\n                                    (2(k + 3) * (2k + 5)) * xonemx2 * res[k+3]\n                                ) / (onemx22 * ((k + 4) * (k + 3)))\n                            res[i] = ai\n                        end\n                    end\n                end\n            end\n        end\n    end\n    # Compose the Taylor series for the Legendre function with that of\n    # z\n    z_tmp = arb_series(deepcopy(z.poly))\n    z_tmp[0] = base_ring(parent(z.poly))(0)\n\n    return Nemo.compose(res, z_tmp, n)\nend\n\nfunction legendre_p_safe(ν::arb, μ::arb, z::arb_series, n = length(z))\n    legendre_p(ν, μ, z, n)\nend\n", "meta": {"hexsha": "cce8c209ab0c334380cda6f09ba788866fa7a5ee", "size": 8293, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/arb_series.jl", "max_stars_repo_name": "Joel-Dahne/MethodOfParticularSolutions.jl", "max_stars_repo_head_hexsha": "4025aa47f972c6d0f8f9593f6bf2dfe297172ba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/arb_series.jl", "max_issues_repo_name": "Joel-Dahne/MethodOfParticularSolutions.jl", "max_issues_repo_head_hexsha": "4025aa47f972c6d0f8f9593f6bf2dfe297172ba3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-05T10:50:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-05T11:34:50.000Z", "max_forks_repo_path": "src/arb_series.jl", "max_forks_repo_name": "Joel-Dahne/MethodOfParticularSolutions.jl", "max_forks_repo_head_hexsha": "4025aa47f972c6d0f8f9593f6bf2dfe297172ba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6178571429, "max_line_length": 91, "alphanum_fraction": 0.3843000121, "num_tokens": 2413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542283, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7699001977296781}}
{"text": "#How to build your first Model\n\nusing StatsBase, Gadfly\nusing Distributions\nusing Random\nusing MCHammer\n\n\nclearconsole()\n\n#Key Variables\nn_trials = 10000\nRevenue = rand(TriangularDist(2500000,4000000,3000000), n_trials)\nExpenses = rand(TriangularDist(1400000,3000000,2000000), n_trials)\n\n#Uncorrelated Model (1)\nProfit = Revenue - Expenses\n\n#Apply correlation to random samples\nRev_Exp_Cor = -0.8\ncor_matrix = [1 Rev_Exp_Cor; Rev_Exp_Cor 1]\n\n#Join Trial into an array and apply correlation\nTrials = hcat(Revenue, Expenses)\nTrials = corvar(Trials, n_trials, cor_matrix)\n\n#Correlated Model(2) - Create Correlated Results Array\nProfit_C = Trials[!,1] -Trials[!,2]\nTrials = hcat(Trials[!,1], Trials[!,2], Profit_C)\ncormat(Trials,1)\n\n#Plot Density\nplot(x=[Profit Profit_C], Geom.density, color=[\"Uncorrelated\",\"Correlated\"], Guide.Title(\"Compare Results Methods\"))\n\n#Plot S-Curves\n# plot(layer(ecdf(Profit),minimum(Profit), maximum(Profit), Theme(default_color=\"orange\")),layer(ecdf(Profit_C), minimum(Profit_C), maximum(Profit_C)), Guide.Title(\"Compare Portfolio Methods\"))\n# s_table = hcat(Profit_C,Revenue, Expenses)\n# sensitivity_chrt(s_table,1)\n\n\nprintln(\"Probability of Making 1m or less (uncorrelated) :\",GetCertainty(Profit, 1000000, 0))\nprintln(\"Input Correlation: \", cor(Revenue,Expenses),\"\\n\")\nprintln(\"Probability of Making 1m or less (correlated) :\",GetCertainty(Profit_C, 1000000, 0))\nprintln(\"Input Correlation: \", cor(Trials[:, 1],Trials[:,2]))\nprintln(\"\\n\")\n\nprintln(\"Model Outputs: Revenue, Expenses, Profit, Profit_C\")\nProfit_C\n", "meta": {"hexsha": "3981822e617849233cf79350431b883a8b97d399", "size": 1542, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples/321_Model.jl", "max_stars_repo_name": "louy2/MCHammer.jl", "max_stars_repo_head_hexsha": "9ff708b71cb5192ffdfeb353ae429cdcf49ba978", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-09-26T22:14:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T05:56:01.000Z", "max_issues_repo_path": "docs/examples/321_Model.jl", "max_issues_repo_name": "louy2/MCHammer.jl", "max_issues_repo_head_hexsha": "9ff708b71cb5192ffdfeb353ae429cdcf49ba978", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-05-29T21:28:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T17:29:19.000Z", "max_forks_repo_path": "docs/examples/321_Model.jl", "max_forks_repo_name": "louy2/MCHammer.jl", "max_forks_repo_head_hexsha": "9ff708b71cb5192ffdfeb353ae429cdcf49ba978", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-05-14T23:51:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T22:42:34.000Z", "avg_line_length": 31.4693877551, "max_line_length": 193, "alphanum_fraction": 0.7568093385, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350351, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7699001976649994}}
{"text": "using LinearAlgebra\n\n@enum Orientation::Int8 Colinear = 0 Clockwise = -1 CounterClockwise = 1\n\nfunction mid_point(p1, p2)\n    return (p1 .+ p2) ./ 2\nend\n\nfunction orientation(p1, p2, p3) # orientation\n    val = (p2[2] - p1[2]) * (p3[1] - p2[1]) - (p2[1] - p1[1]) * (p3[2] - p2[2])\n    return val == 0.0 ? Colinear : (val < 0 ? CounterClockwise : Clockwise)\nend\n\n# make edges and dual edges always be in CounterClockwise orientation\nfunction rectify_orientation!(de, dv, v)\n    p1 = [0, 0]\n    p2 = v[2] .- v[1]\n    p3 = dv[2] .- dv[1]\n    or = orientation(p1, p2, p3)\n    if or == Clockwise\n        reverse!(de)\n    elseif or == Colinear\n        error(\"Found three colinear vertices trying to sneak as a triangle! 😠\")\n    end\nend\n\nfunction rectify_orientation!(triangles, vertices)\n    for tri in triangles\n        or = orientation(vertices[tri[1:3]]...)\n        if or == Clockwise\n            reverse!(tri)\n        elseif or == Colinear\n            error(\"Found three colinear vertices trying to sneak as a triangle! 😠\")\n        end\n    end\nend\n\nfunction circumcenter(p1, p2, p3) # circumcenter\n    mat = SMatrix{2}((p1[1] - p2[1]), (p1[1] - p3[1]), (p1[2] - p2[2]), (p1[2] - p3[2]))\n    b = -SVector((p2' * p2 - p1' * p1) / 2, (p3' * p3 - p1' * p1) / 2)\n    x = mat \\ b\nend\n\nfunction longitude(p1, p2) # measure of a line\n    return norm(p1 .- p2)\nend\n\nfunction area(p) # measure of a polygon\n    A = 0.0\n    for i = 2:length(p)\n        A += p[i - 1][1] * p[i][2] - p[i - 1][2] * p[i][1]\n    end\n    A += p[end][1] * p[1][2] - p[end][2] * p[1][1]\n    return abs(A) / 2\nend\n", "meta": {"hexsha": "d15bb61ac762a0107aabe8f49d8c9085a1056c15", "size": 1575, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geometry.jl", "max_stars_repo_name": "Suavesito-Olimpiada/DEC2D.jl", "max_stars_repo_head_hexsha": "526132942bd52cd03e352bf1de85d3e130d74200", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-11T08:10:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-11T08:10:44.000Z", "max_issues_repo_path": "src/geometry.jl", "max_issues_repo_name": "Suavesito-Olimpiada/DEC2D.jl", "max_issues_repo_head_hexsha": "526132942bd52cd03e352bf1de85d3e130d74200", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geometry.jl", "max_forks_repo_name": "Suavesito-Olimpiada/DEC2D.jl", "max_forks_repo_head_hexsha": "526132942bd52cd03e352bf1de85d3e130d74200", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.125, "max_line_length": 88, "alphanum_fraction": 0.5657142857, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478306, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7699001901318431}}
{"text": "function EuropeanCallMC_DeltaBased(K, T, S, sig, r, div, N, M)\n\n## setting parameters\n\ndt = T/N\nnudt = (r - div - 0.5 * sig^2) * dt\nsigsdt = sig * sqrt(dt)\nerddt = exp((r - div) * dt)\n\nbeta1 = -1\n\n## variables to store the sums of the option values\n\nsum_CT = 0\nsum_CT2 = 0\n\n\nfunction CND(X)\n#   y::float64\n#   Exponential::float64\n#   SumA::float64\n#   SumB::float64\n\n  y = abs(X)\n\n  if y > 37\n    cnd = 0\n  else\n    Exponential = exp(-y^2/2)\n\n    if y < 7.07106781186547\n      SumA = 0.0352624965998911 * y + 0.700383064443688\n      SumA = SumA * y + 6.37396220353165\n      SumA = SumA * y + 33.912866078383\n      SumA = SumA * y + 112.079291497871\n      SumA = SumA * y + 221.213596169931\n      SumA = SumA * y + 220.206867912376\n      SumB = 0.0883883476483184 * y + 1.75566716318264\n      SumB = SumB * y + 16.064177579207\n      SumB = SumB * y + 86.7807322029461\n      SumB = SumB * y + 296.564248779674\n      SumB = SumB * y + 637.333633378831\n      SumB = SumB * y + 793.826512519948\n      SumB = SumB * y + 440.413735824752\n      cnd = Exponential * SumA / SumB\n    else\n      SumA = y + 0.65\n      SumA = y + 4 / SumA\n      SumA = y + 3 / SumA\n      SumA = y + 2 / SumA\n      SumA = y + 1 / SumA\n      cnd = Exponential / (SumA * 2.506628274631)\n\n      end\n  end\n\n  if X > 0\n    cnd = 1 - cnd\n  end\n\ncnd\n\nend\n\n\nfunction GDelta(CallPutFlag, S, X, T, r, b, v)\n\n  #require(\"CND.jl\")\n  d1::Float64\n\n  d1 = (log(S / X) + (b + v^2 / 2) * T) / (v * sqrt(T))\n\n  if CallPutFlag == \"c\"\n    delta = exp((b - r) * T) * CND(d1)\n\n  elseif CallPutFlag == \"p\"\n    delta = -exp((b - r) * T) * CND(-d1)\n  end\n\n    delta\n\nend\n\n\n\n\n\n\n\n\n## outer loop is the number of simulations bigger is better\n\nfor j = 1:M\n\n  St = S\n    cv = 0\n\n    ## inner loop is simulating each price path of length N\n  for i = 1:N\n\n    t = (i-1) * dt\n    delta = GDelta(\"c\", St, K, t, r, div, sig)\n\n\n    error = randn()\n    Stn = St * exp(nudt + sigsdt * error) ## note, it only add the changes, does not store the path\n    cv = cv + delta * (Stn-St*erddt)\n    St = Stn\n\n  end\n\n    ## wraps up and stores all the values of each path\n\n  CT = max(0, St - K) + beta1*cv\n  sum_CT = sum_CT + CT\n  sum_CT2 = sum_CT2 + CT^2\n\nend\n\n  ## discounting the average call value\ncall_value = sum_CT / M * exp(-r*T)\n\n\nSD = (sqrt(sum_CT2 - 1/M * (sum_CT^2)) * exp(-2*r*T)) / (M-1)\nSE = SD / sqrt(M)\n\nprintln(\"The Call Value is $call_value\")\nprintln(\"The SD is $SD\")\nprintln(\"The SE is $SE\")\n\nMC = [call_value, SD, SE]\n\nend\n", "meta": {"hexsha": "5a2322925157f81595ddc8f7d12329842de4b08e", "size": 2467, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/IB/PricingEngines/EuropeanCallMC_DeltaBased.jl", "max_stars_repo_name": "SvenDuve/JuliaAOT.jl", "max_stars_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/IB/PricingEngines/EuropeanCallMC_DeltaBased.jl", "max_issues_repo_name": "SvenDuve/JuliaAOT.jl", "max_issues_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IB/PricingEngines/EuropeanCallMC_DeltaBased.jl", "max_forks_repo_name": "SvenDuve/JuliaAOT.jl", "max_forks_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-27T15:45:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-27T15:45:30.000Z", "avg_line_length": 18.4104477612, "max_line_length": 99, "alphanum_fraction": 0.5662748277, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222396, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7699001845355866}}
{"text": "@with_kw struct BlackmanHarrisPulse <: AbstractWaveform\n\thalf_bandwidth::Float64\n\tfc::Float64 = 0.0\nend\nfunction (pulse::BlackmanHarrisPulse)(t)\n\ta0 = 0.353222222\n\ta1 = -0.488\n\ta2 = 0.145\n\ta3 = -0.010222222\n\tT = 1 / pulse.half_bandwidth\n\t if 0 ≤ t ≤ T\n\t return (a0 + a1 * cos((2π*t)/T) + a2 * cos((2π*2*t)/T) +  a3 * cos((2π*3*t)/T)) * cos(2π*pulse.fc*(t)) \n\t else\n\t\t return 0\n\t end\nend\n@with_kw struct DBlackmanHarrisPulse <: AbstractWaveform\n\thalf_bandwidth::Float64\n\tfc::Float64 = 0.0\nend\t\nfunction (pulse::DBlackmanHarrisPulse)(t)\n\ta0 = 0.353222222\n\ta1 = -0.488\n\ta2 = 0.145\n\ta3 = -0.010222222\n\tT = 1 / pulse.half_bandwidth\n\t if 0 ≤ t ≤ T\n\t return -( a1 * sin((2π*t)/T) + a2 * sin((2π*2*t)/T) +  a3 * sin((2π*3*t)/T)) * cos(2π*pulse.fc*(t)) \n\t else\n\t\t return 0\n\t end\nend\t\n\nconst BlackmanHarrisWaveForm = Union{BlackmanHarrisPulse,DBlackmanHarrisPulse}\t\n\t\n@recipe function f(s::BlackmanHarrisWaveForm;nsamples = 20,spectrum = true)\n\tlinewidth := 2\n\tlabel := \"BlackmanHarris Pulse\"\n\tT = 1/s.half_bandwidth\n\tif spectrum \n\t\txlabel := \"frequency\"\n\t\txrange := [-s.fc- 10*s.half_bandwidth,s.fc+ 10*s.half_bandwidth]\n\telse\n\t\txlabel := \"time\"\n\t\txrange := [0,2T]\n\tend\n\tδt = 1/(s.fc+ s.half_bandwidth)/nsamples\n\tt_samples = range(0,20T,step = δt)\n if spectrum return fourier(t_samples,s.(t_samples)) else return (t_samples,s.(t_samples)) end\nend", "meta": {"hexsha": "7991620f9d611e80b97977ac5c051c51e2af2a99", "size": 1337, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Waveforms/BlackmanHarrisWaveForm.jl", "max_stars_repo_name": "MKAbdElrahman/FDTDSolver.jl", "max_stars_repo_head_hexsha": "d6f8bd0cabdde3e073a41f0d6c667b69e3873c3e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Waveforms/BlackmanHarrisWaveForm.jl", "max_issues_repo_name": "MKAbdElrahman/FDTDSolver.jl", "max_issues_repo_head_hexsha": "d6f8bd0cabdde3e073a41f0d6c667b69e3873c3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Waveforms/BlackmanHarrisWaveForm.jl", "max_forks_repo_name": "MKAbdElrahman/FDTDSolver.jl", "max_forks_repo_head_hexsha": "d6f8bd0cabdde3e073a41f0d6c667b69e3873c3e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.74, "max_line_length": 105, "alphanum_fraction": 0.6724008975, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.7698909092671421}}
{"text": "using Graphs\nusing SparseArrays\n\nfunction dijkstra_digraph(mat, nrows, ncols, startindex, endindex)\n    dist = spzeros(Int, length(mat), length(mat))\n    g = SimpleDiGraph(length(mat))\n    for i in 1:length(mat)\n        if i % nrows != 0\n            add_edge!(g, i, i + 1)\n            dist[i, i + 1] = mat[i + 1]\n            add_edge!(g, i + 1, i)\n            dist[i + 1, i] = mat[i]\n        end\n        if i <= length(mat) - nrows\n            add_edge!(g, i, i + nrows)\n            dist[i, i + nrows] = mat[i + nrows]\n            add_edge!(g, i + nrows, i)\n            dist[i + nrows, i] = mat[i]\n        end\n    end\n    return dijkstra_shortest_paths(g, startindex, dist).dists[endindex]\nend\n\nfunction day15()\n    part = [0, 0]\n    lines = filter(!isempty, strip.(readlines(\"AoCdata/AoC_2021_day15.txt\")))\n    nrows, ncols = length(lines), length(first(lines))\n    mat = zeros(Int, nrows, ncols)\n    for i in 1:nrows\n        mat[i, :] = parse.(Int, collect(lines[i]))\n    end\n    part[1] = dijkstra_digraph(mat, nrows, ncols, 1, length(mat))\n\n    mat2 = zeros(Int, ncols * 5, nrows * 5)\n    for c in CartesianIndices(mat2)\n        mat2[c] = mod1(\n            mat[mod1(c[1], nrows), mod1(c[2], ncols)] +\n            (c[1] - 1) ÷ nrows +\n            (c[2] - 1) ÷ ncols,\n            9,\n        )\n    end\n    part[2] = dijkstra_digraph(mat2, nrows * 5, ncols * 5, 1, length(mat2))\n\n    return part\nend\n\npart = day15()\nprintln(\"Part 1: \", part[1])\nprintln(\"Part 2: \", part[2])\n", "meta": {"hexsha": "6955ce884fae4c4723a8c04102296f043b835ca5", "size": 1474, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Day15.jl", "max_stars_repo_name": "wherrera10/Advent-of-Code-2021", "max_stars_repo_head_hexsha": "0fd704052f8b1f8d7ef2e878927bd6f13567d7da", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-31T10:15:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T10:15:36.000Z", "max_issues_repo_path": "src/Day15.jl", "max_issues_repo_name": "wherrera10/Advent-of-Code-2021", "max_issues_repo_head_hexsha": "0fd704052f8b1f8d7ef2e878927bd6f13567d7da", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Day15.jl", "max_forks_repo_name": "wherrera10/Advent-of-Code-2021", "max_forks_repo_head_hexsha": "0fd704052f8b1f8d7ef2e878927bd6f13567d7da", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9019607843, "max_line_length": 77, "alphanum_fraction": 0.5345997286, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7698909061315341}}
{"text": "# Adaptive MvNormal random walk.\n# See: https://www.tandfonline.com/doi/abs/10.1198/jcgs.2009.06134\nmutable struct MvAdaptiveRWM{M <: AbstractVector{<:Real}, V <: AbstractMatrix{<:Real},\n                             B <: Real} <: Metropolis\n  sample_mean::M\n  sample_cov::V\n  beta::B\n  iter::Int\n  d::Int\nend\nfunction MvAdaptiveRWM(v::AbstractVector{<:Real}; beta=0.05, iter=1)\n  d = length(v)\n  return MvAdaptiveRWM(v, eye(d) * 0.01 / d, beta, iter, d)\nend\nfunction update_stats!(rwm::MvAdaptiveRWM, x::AbstractVector{<:Real})\n  rwm.iter += 1\n  update_mean!(rwm.sample_mean, x, rwm.iter)\n  update_cov!(rwm.sample_cov, rwm.sample_mean, x, rwm.iter)\nend\nfunction _update(rng::Random.AbstractRNG, rwm::MvAdaptiveRWM, curr::AbstractVector{<:Real},\n                 logprob::Function)\n  # Update summary stats.\n  update_stats!(rwm, curr)\n\n  # Construct proposal covariance.\n  proposal_cov = if rwm.iter <= 2 * rwm.d || rwm.beta > rand()\n    0.01 * eye(rwm.d) / rwm.d\n  else\n    5.6644 * rwm.sample_cov / rwm.d\n  end\n  proposal_cov .= Matrix(LinearAlgebra.Symmetric(proposal_cov))\n\n  return _update(rng, StaticRWM(MvNormal(proposal_cov)), curr, logprob)\nend\nconst mvarwm = MvAdaptiveRWM\n", "meta": {"hexsha": "57a25d05f187ddc91646215a5c92897dcd5daf9c", "size": 1182, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mvarwm.jl", "max_stars_repo_name": "luiarthur/mcmc.jl", "max_stars_repo_head_hexsha": "a71f5cc8158ac2e356cad3a163bf8b252e77fed8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mvarwm.jl", "max_issues_repo_name": "luiarthur/mcmc.jl", "max_issues_repo_head_hexsha": "a71f5cc8158ac2e356cad3a163bf8b252e77fed8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-05T07:07:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-03T00:59:57.000Z", "max_forks_repo_path": "src/mvarwm.jl", "max_forks_repo_name": "luiarthur/mcmc.jl", "max_forks_repo_head_hexsha": "a71f5cc8158ac2e356cad3a163bf8b252e77fed8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8333333333, "max_line_length": 91, "alphanum_fraction": 0.6835871404, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303728259492, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.7698909058852885}}
{"text": "include(\"header.jl\")\n\n\n#=\n# Dimensionless quantities\nIn this notebook, we will learn about making quantities dimensionless,\nand the physical significance of this.\n=#\n\n# ### Set up the module\nusing MAE103\n#-\nusing Plots\n\n#=\nIn the previous notebook, we made a plot of the velocity field in a gap\nbetween two walls. We'll regenerate the plot here for reference:\n=#\nu(y,Uc,H) = 4*Uc/H^2*y*(H-y)\nH = 1u\"cm\"\nUc = 1u\"m/s\"\ny = range(0u\"cm\",H,length=101)\nv = u.(y,Uc,H)\nplot(v,y,xlim=(0,Inf),ylim=(0,Inf),xlabel=L\"u(y)\",ylabel=L\"y\")\n\n#=\nIn this plot, the data have units---they are *dimensional* data.\nThis is useful, since the plot not only conveys the velocities, but\nalso the gap size and the flow speed.\n\nLet us also note that the plot is quite specific, since it only shows\nthe plot for *one* choice of gap size (1 cm) and *one* choice of flow speed (1 m/s).\nOf course, it is not difficult for us to get plots at different gap sizes\nand flow speeds by simply changing the parameters.\n\nBut suppose that these data were measured in an experiment. For the experiment,\nlet's say we constructed one gap $H$, we applied one flow speed $U_c$, and\nwe measured the resulting profile of fluid velocity across the gap. Then this plot,\nat these specific conditions, would not be directly useful to someone else who would like\nto know the velocity profile in a different size gap at a different flow speed.\n\nIf, instead, we divide the velocity data `v` by flow speed `Uc` and divide the position\ndata `y` by gap size `H`, then we \"scale out\" the specific choices for these parameters:\n=#\nplot(v/Uc,y/H,xlim=(0,Inf),ylim=(0,Inf),xlabel=L\"u(y)/U_c\",ylabel=L\"y/H\",yticks=0:0.25:1)\n\n#=\nThis is a *dimensionless plot*. The values on each axis have no units: they are\ncalled *dimensionless* or *non-dimensional* quantities.\n\nThis plot is more directly useful to another person, because they can read off\nthe values for a particular position *as a fraction of gap height*,\nand find the velocity *as a fraction of the centerline velocity*. Then, they can\n\"scale\" the value to their own situation.\n\nFor example, if a person whose gap size is $H = 3$ cm and centerline velocity is\n$0.5$ m/s wishes to know the velocity at $y = 0.6$ cm, they calculate $y/H = 0.6/3 = 0.2$\nand look up on the plot that $y/H = 0.2$ corresponds to $u/U_c = 0.64$. Thus,\nfor this person's case, $u = 0.64\\times0.5$ m/s  $= 0.32$ m/s.\n=#\n\n#-\n#=\n### Unit as a reference quantity.\nThe principle of \"scaling out\" the parameters is very important. But before we\ngo deeper into this, let us make an observation on units.\n\nA unit is a reference value, and this reference is standardized so we can communicate\nresults with one another on a common foundation. What does it mean to be a reference?\n\nWhen we measure something, it is important to remember that the thing we're measuring is not\nintrinsically tied to any unit. It is more abstract than that. For example, the\ndistance between two points is a physical fact. Our measurement of that distance with\na particular set of units is simply one way (of many) quantifying that fact.\n\nWith that measurement, we are simply comparing that something with another\nthing that has been calibrated on a particular unit system. A ruler is the easiest\nexample of this: the ruler was constructed by marking off lines on a stick,\nwith each line determined from some other calibrated tool that the ruler manufacturer used.\nUltimately, all of these measurement tools refer back to some ultimate standard\nfor the unit (e.g. for a meter, it is length of the path travelled by light in a\nvacuum in 1/(299,792,458) of a second.) As long as we all agree on this standard,\nwe can communicate with each other.\n=#\n#-\n#=\nHowever, we don't quite all agree. Most use SI units, but many still use imperial.\nSo we need conversion factors, and there is opportunity to make mistakes.\n=#\n#-\n#=\n### A more physically-meaningful reference quantity.\nAs we discussed earlier, when we measure something, we are making a comparison\nwith a standardized unit. We can think of this comparison as a ratio of the\nphysical quantity with the standard unit. For example, if we were to say the gap $H$ was\n0.1 cm high, we could also write this statement as\n\n$$\\dfrac{H}{1\\,\\mathrm{cm}} = 0.1$$\n\nHowever, this unit is a reference that we (humans) invented, so it is completely irrelevant\nto physics.\n\nOn the other hand, if we instead choose as a reference some parameter\nin the problem itself, then we are much more likely to have a *physically\nmeaningful* reference. In our example problem, the gap height is clearly physically\nmeaningful, so it serves as a natural *length scale*. The centerline velocity\nis a natural *velocity scale*. These are our *reference scales*.\n\nActually, the statement that the dimensionless velocity plot has \"no units\" isn't\nquite true. There *are* units on this plot. The units of position are \"gap heights\"\nand the units of velocity are \"centerline velocities\". We can say, for example,\nthe: \"the velocity at 0.2 gap heights from the lower wall is 0.64 times the centerline\nvelocity\"). The huge advantage of this \"local\" system of units is that it requires no\nstandarization or international governing body. It is unambiguous to *anyone*,\nincluding to an alien species.\n=#\n\n#-\n#=\n**In summary**, there are several advantages to the dimensionless view:\n- There is no ambiguity about which system we used. It doesn't matter if\n  the original parameters and values were in SI or imperial.\n- Since the laws of physics hold regardless of our system of units, this sort of plot\n    reveals true physical relationships between velocity and location.\n- The dimensionless relationship between $u/U_c$ and $y/H$ is *universal*: it holds\n  for *every* gap size and\n  *every* flow speed. We know that this is true here because the exact velocity\n  field was actually known to us:\n\n  $$u(y) = \\frac{4U_c}{H^2} y (H - y)$$\n\n  But let's divide this by $U_c$ and group $y$ with $H$:\n\n  $$\\dfrac{u}{U_c} = 4 \\dfrac{y}{H}\\left(1 - \\dfrac{y}{H}\\right)$$\n\n  This shows that $u/U_c$ depends on $y/H$ *and nothing\nelse*. There are no \"free\" parameters in this dimensionless relationship. We\nwill return to this point in the next notebook.\n- We are lucky here because we already knew the mathematical equation. In most\ncases, we aren't this lucky. But as we will discuss in the next notebook, once we\n  ascertain the number of dimensionless quantities that fully describe a relationship,\n  we can develop an *empirical correlation of data*. This correlation should *only* be\n  pursued on dimensionless data. A correlation with dimensional coefficients is\n  truly useless.\n=#\n#-\n#=\n### Dimensional homogeneity\nOne last point before move on. When we non-dimensionalize a quantity by a reference\nquantity, they need to be in the same units. If they're not, then we need to\nmake sure the conversion factors are accounted for. For example, let's suppose\nthat the velocites in $u$ are measured in m/s, but the centerline velocity $U_c$ was\nmeasured in ft/s. We obviously have to deal with the conversion between ft and\nm to take the ratio $u/U_c$.\n\nA conversion factor between two systems of units\nis itself a dimensionless quantity. We can obtain the numerical factor with the\nhelp of the `DimensionlessParameter` function. For example, let's consider the\nconversion factor from feet to meters.\n=#\nDimensionlessParameter(1u\"m\"/1u\"ft\")\n\n#=\nWe would multiply $U_c$ in ft/s by this factor to convert it to m/s.\n\nBut we can actually make use of a neat feature to skip this step, because\nthese software tools will carry out the conversion for us! For example, if\nwe divide $u = 0.5$ m/s by $U_c = 3$ ft/s:\n=#\nDimensionlessParameter(0.5u\"m/s\"/3u\"ft/s\")\n\n#=\nThis name `DimensionlessParameter` isn't very descriptive! It might\nbe nice to use a more specific name for this quantity. Let's create\na new function that we can use to set this dimensionless velocity:\n=#\n@nondimvar DimensionlessVelocity\n#=\nNow we can use this to set the ratio of velocities:\n=#\nu_nd = DimensionlessVelocity(0.5u\"m/s\"/3u\"ft/s\")\n", "meta": {"hexsha": "60abe1a4bcb9fe6d5adf3608d5a6ab1fb1050638", "size": 8049, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/literate/1.2-DimensionlessQuantities.jl", "max_stars_repo_name": "jdeldre/MAE103", "max_stars_repo_head_hexsha": "1417d573636e7e88fc0dce795073b8f0a82634f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/literate/1.2-DimensionlessQuantities.jl", "max_issues_repo_name": "jdeldre/MAE103", "max_issues_repo_head_hexsha": "1417d573636e7e88fc0dce795073b8f0a82634f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-03T22:18:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-03T22:18:15.000Z", "max_forks_repo_path": "test/literate/1.2-DimensionlessQuantities.jl", "max_forks_repo_name": "jdeldre/MAE103", "max_forks_repo_head_hexsha": "1417d573636e7e88fc0dce795073b8f0a82634f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2252747253, "max_line_length": 92, "alphanum_fraction": 0.7521431234, "num_tokens": 2084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8740772368049822, "lm_q1q2_score": 0.7698846788398436}}
{"text": "﻿#=\nGeometry in 2d euclidean space\n=#\n\n\"\"\"\ndeltaangle(a::Real, b::Real)\n\nReturn the minimum δ such that\n    a + δ = mod(b, 2π)\n\"\"\"\ndeltaangle(a::Real, b::Real) = atan2(sin(b-a), cos(b-a))\n\n\"\"\"\nDistance between two angles\n\"\"\"\nangledist( a::Real, b::Real ) = abs(deltaangle(a,b))\n\n\"\"\"\nLinear interpolation between angles\n\"\"\"\nlerp_angle(a::Real, b::Real, t::AbstractFloat) = a + deltaangle(a, b)*t\n\n\"\"\"\nTrue if the values are collinear within a tolerance\n\"\"\"\nfunction are_collinear(a::AbstractVec, b::AbstractVec, c::AbstractVec, tol::Float64=1e-8)\n    # http://mathworld.wolfram.com/Collinear.html\n    # if val = 0 then they are collinear\n    val = a.x*(b.y-c.y) + b.x*(c.y-a.y)+c.x*(a.y-b.y)\n    abs(val) < tol\nend\n\n\"\"\"\nTo find orientation of ordered triplet (p, q, r).\nThe function returns following values\n0 --> p, q and r are colinear\n1 --> Clockwise\n2 --> Counterclockwise\n\"\"\"\nfunction orientation(P::VecE2, Q::VecE2, R::VecE2)\n    val = (Q.y - P.y)*(R.x - Q.x) - (Q.x - P.x)*(R.y - Q.y)\n    if val ≈ 0\n        return 0  # colinear\n    end\n    return (val > 0) ? 1 : 2\nend\n\nfunction inertial2body(point::VecE2, reference::VecSE2)\n\n    #=\n    Convert a point in an inertial cartesian coordinate frame\n    to be relative to a body's coordinate frame\n\n    The body's position is given relative to the same inertial coordinate frame\n    =#\n\n    s, c = sin(reference.θ), cos(reference.θ)\n    Δx = point.x - reference.x\n    Δy = point.y - reference.y\n    VecE2(c*Δx + s*Δy, c*Δy - s*Δx)\nend\nfunction inertial2body(point::VecSE2, reference::VecSE2)\n\n    #=\n    Convert a point in an inertial cartesian coordinate frame\n    to be relative to a body's coordinate frame\n\n    The body's position is given relative to the same inertial coordinate frame\n    =#\n\n    s, c = sin(reference.θ), cos(reference.θ)\n    Δx = point.x - reference.x\n    Δy = point.y - reference.y\n    VecSE2(c*Δx + s*Δy, c*Δy - s*Δx, point.θ - reference.θ)\nend\nfunction body2inertial(point::VecE2, reference::VecSE2)\n\n    #=\n    Convert a point in a body-relative cartesian coordinate frame\n    to be relative to a the inertial coordinate frame the body is described by\n    =#\n\n    c, s = cos(reference.θ), sin(reference.θ)\n    VecE2(c*point.x -s*point.y + reference.x, s*point.x +c*point.y + reference.y)\nend\nfunction body2inertial(point::VecSE2, reference::VecSE2)\n\n    #=\n    Convert a point in a body-relative cartesian coordinate frame\n    to be relative to a the inertial coordinate frame the body is described by\n    =#\n\n    c, s = cos(reference.θ), sin(reference.θ)\n    VecSE2(c*point.x -s*point.y + reference.x, s*point.x +c*point.y + reference.y, reference.θ + point.θ)\nend\n\ninclude(\"1d.jl\")\ninclude(\"lines.jl\")\ninclude(\"line_segments.jl\")\ninclude(\"rays.jl\")\ninclude(\"projectiles.jl\")\ninclude(\"solids.jl\")\ninclude(\"hyperplanes.jl\")", "meta": {"hexsha": "a428b2d09ccd239398a1fd7b81d974b97c66f0ed", "size": 2804, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geom/geom.jl", "max_stars_repo_name": "yoshihikokuwahara/Vec.jl", "max_stars_repo_head_hexsha": "f5731358b940002ae81ccc3556d9eca82e713659", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/geom/geom.jl", "max_issues_repo_name": "yoshihikokuwahara/Vec.jl", "max_issues_repo_head_hexsha": "f5731358b940002ae81ccc3556d9eca82e713659", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geom/geom.jl", "max_forks_repo_name": "yoshihikokuwahara/Vec.jl", "max_forks_repo_head_hexsha": "f5731358b940002ae81ccc3556d9eca82e713659", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2233009709, "max_line_length": 105, "alphanum_fraction": 0.6633380884, "num_tokens": 879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7698724019319021}}
{"text": "##\ncd(@__DIR__())\nrot(ϕ) = Complex{Int}(round(Int,cos(deg2rad(ϕ))), round(Int,sin(deg2rad(ϕ))))\nmoves = Dict(\n    'N' => α -> c -> begin (p,d) = c; (p + Complex{Int}(0,α), d) end,\n    'S' => α -> c -> begin (p,d) = c; (p + Complex{Int}(0,-α), d) end,\n    'E' => α -> c -> begin (p,d) = c; (p + Complex{Int}(α,0), d) end,\n    'W' => α -> c -> begin (p,d) = c; (p + Complex{Int}(-α,0), d) end,\n    'L' => ϕ -> c -> begin (p,d) = c; (p, d * rot(ϕ)) end,\n    'R' => ϕ -> c -> begin (p,d) = c; (p, d * rot(-ϕ)) end,\n    'F' => s -> c -> begin (p,d) = c; (p + s * d, d) end,\n)\ndist(p::Complex) = reim(p) .|> abs |> sum\ndist(t::Tuple) = dist(first(t))\ndist(t1::Tuple, t2::Tuple) = dist(t2[1] - t1[1]);\n\n##\nactions = map(eachline(\"test.txt\")) do line\n    moves[line[1]](parse(Int, line[2:end]))\nend;\n\n##\nstart = Complex{Int}(0,0), Complex{Int}(1,0)\nfinish = foldl(actions; init = start) do c, a\n    a(c)\nend\n@show finish\ndist(start, finish)\n\n## PARTE 2\nmoves = Dict(\n    'N' => α -> c -> begin (p,d) = c; (p, d + Complex{Int}(0,α)) end,\n    'S' => α -> c -> begin (p,d) = c; (p, d + Complex{Int}(0,-α)) end,\n    'E' => α -> c -> begin (p,d) = c; (p, d + Complex{Int}(α,0)) end,\n    'W' => α -> c -> begin (p,d) = c; (p, d + Complex{Int}(-α,0)) end,\n    'L' => ϕ -> c -> begin (p,d) = c; (p, d * rot(ϕ)) end,\n    'R' => ϕ -> c -> begin (p,d) = c; (p, d * rot(-ϕ)) end,\n    'F' => s -> c -> begin\n        (p,d) = c\n        (p + s * d, d)\n    end,\n)\nactions = map(eachline(\"input.txt\")) do line\n    moves[line[1]](parse(Int, line[2:end]))\nend;\n\n##\nstart = Complex{Int}(0,0), Complex{Int}(10,1)\nfinish = foldl(actions; init = start) do c, a\n    a(c)\nend\n@show finish\ndist(start, finish)\n", "meta": {"hexsha": "9ede64171092a6137e7ba7437636af7ccedf7106", "size": 1675, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "events/2020/day-12/rain-risk.jl", "max_stars_repo_name": "myrddin89/advent-of-code", "max_stars_repo_head_hexsha": "1401484be662794841c0ac5b863c0fda28e2fe06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "events/2020/day-12/rain-risk.jl", "max_issues_repo_name": "myrddin89/advent-of-code", "max_issues_repo_head_hexsha": "1401484be662794841c0ac5b863c0fda28e2fe06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "events/2020/day-12/rain-risk.jl", "max_forks_repo_name": "myrddin89/advent-of-code", "max_forks_repo_head_hexsha": "1401484be662794841c0ac5b863c0fda28e2fe06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0185185185, "max_line_length": 77, "alphanum_fraction": 0.4764179104, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377284730286, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.769872388586992}}
{"text": "## Multiply 2 matrices\n# checks for invalid dimensions\n# uses 1st method (element dot product method)\n\nfunction outer(A,B)\n  return A * B'\nend\n\nfunction matmul(A,B)\n\n# convert any 1D column vectors into 1*x 2D matrices\n  if ndims(A) = 1\n    A = A[:,:]\n  end\n  \n  if ndims(B) = 1\n    B = B[:,:]\n  end\n  \n# define row and column sizes\n# for each matrix\n  rowA, colA = size(A)\n  rowB, colB = size(B)\n  \n# check that dimensions are valid for multiplication, otherwise throw error\n  if colA != rowB\n    throw(DimensionMismatch(\"Matrices of dimensions $(size(A)) and $(size(B)) cannot be multiplied together\"))\n  end\n\n# initialise zero matrix to hold result\n# matrix size is the outer dimensions of the two matrices\n  result = zeros(rowA, colB)\n\n# calculate A*B, populate zero matrix with results\n# uses the outer products of each row with its corresponding column\n# and adds the results together\n  for i in 1:rowB # could also use colA, as colA = rowB\n      result += outer(A[:, i], B[i, :])\n  end\n  \n# return the result\n  return result\nend\n", "meta": {"hexsha": "efc0eb9b06c4e5c008fcedc39f97bc5cb52b0a2f", "size": 1036, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear-algebra-code-challenges/03Matrix_Multiply.jl", "max_stars_repo_name": "jawuku/julia", "max_stars_repo_head_hexsha": "11ec183e6573d202590ffdb08c756b1ebcd38be8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-16T19:29:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T19:29:57.000Z", "max_issues_repo_path": "linear-algebra-code-challenges/03Matrix_Multiply.jl", "max_issues_repo_name": "jawuku/julia", "max_issues_repo_head_hexsha": "11ec183e6573d202590ffdb08c756b1ebcd38be8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear-algebra-code-challenges/03Matrix_Multiply.jl", "max_forks_repo_name": "jawuku/julia", "max_forks_repo_head_hexsha": "11ec183e6573d202590ffdb08c756b1ebcd38be8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5454545455, "max_line_length": 110, "alphanum_fraction": 0.6862934363, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885904, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7698723831197049}}
{"text": "logrange(x1, x2, n) = (10^y for y in range(log10(x1), log10(x2), length=n))\n\nmutable struct LogRange\n\n    lr::StepRangeLen\n\nend\n\n\nLogRange(first, last, n) = LogRange(range(log10(first), log10(last), length=n))\n\n\nfunction Base.iterate(a::LogRange)\n\n    v, s = iterate(a.lr)\n\n    return 10^v, s\n\nend\n\n\nfunction Base.iterate(a::LogRange, b)\n\n    if b > length(a.lr)\n        return nothing\n    end\n\n    v, s = iterate(a.lr, b)\n\n    return 10^v, s\n\nend\n\n\nBase.length(a::LogRange)      = length(a.lr)\n\nBase.getindex(a::LogRange, i) = 10^getindex(a.lr, i)\n\nBase.firstindex(a::LogRange)  = firstindex(a.lr)\n\nBase.lastindex(a::LogRange)   = lastindex(a.lr)\n\nBase.eltype(::Type{LogRange})  = Real\n", "meta": {"hexsha": "6c489b2a3dbb700d64006d6c6225973ac80ca66c", "size": 687, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/logrange.jl", "max_stars_repo_name": "ngiann/MiscUtil.jl", "max_stars_repo_head_hexsha": "62bb259ae41ffa2f2eaf4c55142523238995919e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/logrange.jl", "max_issues_repo_name": "ngiann/MiscUtil.jl", "max_issues_repo_head_hexsha": "62bb259ae41ffa2f2eaf4c55142523238995919e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-22T10:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T10:56:15.000Z", "max_forks_repo_path": "src/logrange.jl", "max_forks_repo_name": "ngiann/MiscUtil.jl", "max_forks_repo_head_hexsha": "62bb259ae41ffa2f2eaf4c55142523238995919e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.6136363636, "max_line_length": 79, "alphanum_fraction": 0.6390101892, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850128595114, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.769803368802343}}
{"text": "using SparseArrays: sparse\n\nexport constant_constraint\n\"\"\"\n    constant_constraint(comp::CellComplex{N},\n        cells::AbstractVector{Cell{N}}, k::Int) where N\n\nFind a sparse representation of the constraint that a `k-1` form is constant on given\n`k-1` dimensional cells.\n\"\"\"\nfunction constant_constraint(comp::CellComplex{N},\n    cells::AbstractVector{Cell{N}}, k::Int) where N\n    row_inds, col_inds, vals = Int[], Int[], Float64[]\n    for (row_ind, (c1, c2)) in enumerate(zip(cells[1:end-1], cells[2:end]))\n        col1 = findfirst(isequal(c1), comp.cells[k])\n        col2 = findfirst(isequal(c2), comp.cells[k])\n        push!(row_inds, row_ind); push!(col_inds, col1); push!(vals, 1)\n        push!(row_inds, row_ind); push!(col_inds, col2); push!(vals, -1)\n    end\n    return sparse(row_inds, col_inds, vals, length(cells)-1, length(comp.cells[k]))\nend\n\nexport zero_constraint\n\"\"\"\n    zero_constraint(comp::CellComplex{N}, cells::AbstractVector{Cell{N}}, k::Int) where N\n\nFind a sparse representation of the constraint that a `k-1` form is zero on given `k-1`\ndimensional cells.\n\"\"\"\nfunction zero_constraint(comp::CellComplex{N}, cells::AbstractVector{Cell{N}},\n    k::Int) where N\n    col_inds = [findfirst(isequal(c), comp.cells[k]) for c in cells]\n    num_rows = length(col_inds)\n    return sparse(1:num_rows, col_inds, ones(num_rows), num_rows, length(comp.cells[k]))\nend\n", "meta": {"hexsha": "fc1f17a090bdb22cf21633be477962882fbdfdf3", "size": 1381, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/constraints.jl", "max_stars_repo_name": "mgscheer/DiscreteExteriorCalculus.jl", "max_stars_repo_head_hexsha": "6e95c222921fed6119824c2771740f030101ac59", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2019-06-26T08:25:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T01:21:16.000Z", "max_issues_repo_path": "src/constraints.jl", "max_issues_repo_name": "mgscheer/DiscreteExteriorCalculus.jl", "max_issues_repo_head_hexsha": "6e95c222921fed6119824c2771740f030101ac59", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-10-24T22:27:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-09T00:06:56.000Z", "max_forks_repo_path": "src/constraints.jl", "max_forks_repo_name": "mgscheer/DiscreteExteriorCalculus.jl", "max_forks_repo_head_hexsha": "6e95c222921fed6119824c2771740f030101ac59", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2019-06-26T04:21:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T01:21:28.000Z", "avg_line_length": 38.3611111111, "max_line_length": 89, "alphanum_fraction": 0.6915278783, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850021922959, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7698033579922123}}
{"text": "function lagrange_poly_basis(nodes, evalPt)\n    order = length(nodes)\n    poly_coefs = zeros(order)\n    for n in 1:order\n        notn = [1:n-1;n+1:order]\n        poly_coefs[n] = prod(evalPt.-nodes[notn])./prod(nodes[n].-nodes[notn])\n    end\n    return poly_coefs\nend\n\nfunction lagrange_interpolant()\n\nend\nfunction gauss_lobatto_quadrature(fun::Function,a::Float64,b::Float64,n_evals::Int)\n    (b<=a)&&throw(DomainError(\"must have a<b\"))\n    (n_evals<1)&&throw(DomainError(\"n_evals must be > 0\"))\n    if n_evals > 1\n        # the GL nodes\n        # nodes in [-1,1]\n        nodes = Jacobi.zglj(n_evals, 0, 0)\n        weights = Jacobi.wglj(nodes,0,0)*(b-a)/2\n        # shift nodes to [a,b]\n        nodes *= 0.5*(b-a)\n        nodes .+= 0.5*(a+b)\n    else\n        nodes = 0.5*(a+b)\n        weights = (b-a)\n    end\n    fun_vals = fun.(nodes)\n    quad = LinearAlgebra.dot(fun_vals,weights)\nend", "meta": {"hexsha": "14b620525eead06cd6d093418b1f3e40577f7dfc", "size": 886, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polynomials.jl", "max_stars_repo_name": "angus-lewis/SFFM", "max_stars_repo_head_hexsha": "0f96c12a17ff38cd33a04fb99661e92dd87a4adb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polynomials.jl", "max_issues_repo_name": "angus-lewis/SFFM", "max_issues_repo_head_hexsha": "0f96c12a17ff38cd33a04fb99661e92dd87a4adb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polynomials.jl", "max_forks_repo_name": "angus-lewis/SFFM", "max_forks_repo_head_hexsha": "0f96c12a17ff38cd33a04fb99661e92dd87a4adb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5806451613, "max_line_length": 83, "alphanum_fraction": 0.5959367946, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.769803356836378}}
{"text": "using RLinearAlgebra\nusing LinearAlgebra\nusing UnicodePlots\n\nn = 10\nd = 10\nκ = 8.0\n\nA = RLinearAlgebra.generate_matrix(n, d, d, κ)\nb = randn(n)\n\n\nsol = LinearSolver(TypeRPM())\nx = rsolve(sol, A, b)\nplt = lineplot(sol.log.residual_hist, title = \"Default RPM\", xlabel = \"iteration\", ylabel = \"residual\")\nprintln(plt)\n\nsol = LinearSolver(TypeRPM(SamplerKaczmarzCYC()))\nx = rsolve(sol, A, b)\nplt = lineplot(sol.log.residual_hist, title = \"Cyclic Kaczmarz\", xlabel = \"iteration\", ylabel = \"residual\")\nprintln(plt)\n\nsol = LinearSolver(TypeRPM(SamplerKaczmarzCYC(), ProjectionLowCore()))\nx = rsolve(sol, A, b)\nplt = lineplot(sol.log.residual_hist, title = \"Cyclic with Low Core\", xlabel = \"iteration\", ylabel = \"residual\")\nprintln(plt)\n\nsol = LinearSolver(TypeRPM(SamplerKaczmarzCYC(), ProjectionFullCore()))\nx = rsolve(sol, A, b)\nplt = lineplot(sol.log.residual_hist, title = \"Cyclic with Full Core\", xlabel = \"iteration\", ylabel = \"residual\")\nprintln(plt)\n\n\nsol = LinearSolver(TypeRPM(SamplerMotzkin()))\nx = rsolve(sol, A, b)\nplt = lineplot(sol.log.residual_hist, title = \"Motzkin\", xlabel = \"iteration\", ylabel = \"residual\")\nprintln(plt)\n\nsol = LinearSolver(TypeRPM(SamplerMotzkin(), ProjectionLowCore()))\nx = rsolve(sol, A, b)\nplt = lineplot(sol.log.residual_hist, title = \"Motzkin low core\", xlabel = \"iteration\", ylabel = \"residual\")\nprintln(plt)\n\nsol = LinearSolver(TypeRPM(SamplerMotzkin(), ProjectionFullCore()))\nx = rsolve(sol, A, b)\nplt = lineplot(sol.log.residual_hist, title = \"Motzkin full core\", xlabel = \"iteration\", ylabel = \"residual\")\nprintln(plt)\n\nsol = LinearSolver(TypeRPM(SamplerGaussSketch()))\nx = rsolve(sol, A, b)\nplt = lineplot(sol.log.residual_hist, title = \"Gauss\", xlabel = \"iteration\", ylabel = \"residual\")\nprintln(plt)\n\nsol = LinearSolver(TypeRPM(SamplerGaussSketch(), ProjectionLowCore()))\nx = rsolve(sol, A, b)\nplt = lineplot(sol.log.residual_hist, title = \"Gauss Low Core\", xlabel = \"iteration\", ylabel = \"residual\")\nprintln(plt)\n\nsol = LinearSolver(TypeRPM(SamplerGaussSketch(), ProjectionFullCore()))\nx = rsolve(sol, A, b)\nplt = lineplot(sol.log.residual_hist, title = \"Gauss Full Core\", xlabel = \"iteration\", ylabel = \"residual\")\nprintln(plt)\n\n\nsamp = SamplerMotzkin()\nsamp.sampled = true\nsol = LinearSolver(TypeRPM(samp))\nx = rsolve(sol, A, b)\nplt = lineplot(sol.log.residual_hist, title = \"RPM Convergence\", xlabel = \"iteration\", ylabel = \"residual\")\nprintln(plt)\n\n\n\nprintln(\"Plot collection of samplers\")\nplt = lineplot(0:500, zeros(501), width = 100, height = 20, xlabel = \"iteration\", ylabel = \"residual\",\n               ylim = [0, norm(b)])\nsamplers = RPMSamplers()\nfor s in samplers\n    solt = LinearSolver(TypeRPM(s))\n    xx = rsolve(solt, A, b)\n    lineplot!(plt, solt.log.residual_hist)\nend\nprintln(plt)\n\nprintln(\"Randomized Gauss seidel\")\nsol = LinearSolver(TypeRGS())\nx = rsolve(sol, A, b)\nplt = lineplot(sol.log.residual_hist, title = \"Randomized Gauss Seidel\", xlabel = \"iteration\", ylabel = \"residual\")\nprintln(plt)\n", "meta": {"hexsha": "853dd69ff534def5bd8127db7680fbd43aa7f3b2", "size": 2962, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/rpm.jl", "max_stars_repo_name": "numlinalg/RLinearAlgebra.jl", "max_stars_repo_head_hexsha": "757cc7e581303c4fb6db228618f4be5caa02d3b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-05-28T17:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T05:23:14.000Z", "max_issues_repo_path": "examples/rpm.jl", "max_issues_repo_name": "numlinalg/RLinearAlgebra.jl", "max_issues_repo_head_hexsha": "757cc7e581303c4fb6db228618f4be5caa02d3b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-06-16T16:01:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-16T12:28:20.000Z", "max_forks_repo_path": "examples/rpm.jl", "max_forks_repo_name": "numlinalg/RLinearAlgebra.jl", "max_forks_repo_head_hexsha": "757cc7e581303c4fb6db228618f4be5caa02d3b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9111111111, "max_line_length": 115, "alphanum_fraction": 0.7103308575, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7698033477939022}}
{"text": "#= \nProblem 102\nThree distinct points are plotted at random on a Cartesian plane, for which -1000 ≤ x, y ≤ 1000, such that a triangle is formed.\n\nConsider the following two triangles:\n\nA(-340,495), B(-153,-910), C(835,-947)\nX(-175,41), Y(-421,-714), Z(574,-645)\n\nIt can be verified that triangle ABC contains the origin, whereas triangle XYZ does not.\n\nUsing triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the co-ordinates of one thousand \"random\" triangles, find the number of triangles for which the interior contains the origin.\n\nNOTE: The first two examples in the file represent the triangles in the example given above.\n=#\n\nusing DataFrames\n\nfunction containsOrigin(p1, p2, p3)\n    # Change of basis approach...\n    # Shift origin to p1, then write original origin as a linear combination. Problem gets very easy\n    lin_comb = inv([(p2 - p1) (p3 - p1)]) * (-p1)\n    if (lin_comb[1] > 0 && lin_comb[2] > 0 && (lin_comb[1] + lin_comb[2] < 1))\n        return 1\n    end\n    return 0\nend\n    \ndf = readtable(\"appendices/p102_triangles.txt\", header = false)\nnumTriangles = size(df)[1]\n\nresult = zeros(numTriangles)\n\nfor i = 1:numTriangles\n    result[i] = containsOrigin(Array(df[i, 1:2])', Array(df[i, 3:4])', Array(df[i, 5:6])')\nend\n\n@show sum(result)\n", "meta": {"hexsha": "22181eba3843b2f4ab9edabb74b1da671e93d5cc", "size": 1292, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problem-102.jl", "max_stars_repo_name": "mebrunet/project-euler", "max_stars_repo_head_hexsha": "95140634b82c568af468e6c065a3be823b4935c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problem-102.jl", "max_issues_repo_name": "mebrunet/project-euler", "max_issues_repo_head_hexsha": "95140634b82c568af468e6c065a3be823b4935c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem-102.jl", "max_forks_repo_name": "mebrunet/project-euler", "max_forks_repo_head_hexsha": "95140634b82c568af468e6c065a3be823b4935c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1282051282, "max_line_length": 216, "alphanum_fraction": 0.6927244582, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144265, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.769803342252833}}
{"text": "# Raised Cosine distribution\n#\n# Ref: http://en.wikipedia.org/wiki/Raised_cosine_distribution\n#\n\nimmutable Cosine <: ContinuousUnivariateDistribution\n    μ::Float64\n    σ::Float64\n\n    Cosine(μ::Real, σ::Real) = (@check_args(Cosine, σ > zero(σ)); new(μ, σ))\n    Cosine(μ::Real) = new(μ, 1.0)\n    Cosine() = new(0.0, 1.0)\nend\n\n@distr_support Cosine d.μ - d.σ d.μ + d.σ\n\n\n#### Parameters\n\nlocation(d::Cosine) = d.μ\nscale(d::Cosine) = d.σ\n\nparams(d::Cosine) = (d.μ, d.σ)\n\n\n#### Statistics\n\nmean(d::Cosine) = d.μ\n\nmedian(d::Cosine) = d.μ\n\nmode(d::Cosine) = d.μ\n\nvar(d::Cosine) = d.σ^2 * 0.13069096604865779  # 0.130... = 1/3 - 2 / π^2\n\nskewness(d::Cosine) = 0.0\n\nkurtosis(d::Cosine) = -0.59376287559828102362\n\n\n#### Evaluation\n\nfunction pdf(d::Cosine, x::Float64)\n    if insupport(d, x)\n        z = (x - d.μ) / d.σ\n        return (1.0 + cospi(z)) / (2 * d.σ)\n    else\n        return 0.0\n    end\nend\n\nlogpdf(d::Cosine, x::Float64) = insupport(d, x) ? log(pdf(d, x)) : -Inf\n\nfunction cdf(d::Cosine, x::Float64)\n    z = (x - d.μ) / d.σ\n    0.5 * (1.0 + z + sinpi(z) * invπ)\nend\n\nfunction ccdf(d::Cosine, x::Float64)\n    nz = (d.μ - x) / d.σ\n    0.5 * (1.0 + nz + sinpi(nz) * invπ)\nend\n\nquantile(d::Cosine, p::Float64) = quantile_bisect(d, p)\n", "meta": {"hexsha": "9f3ee9364db998d12332eda28897ede401ff6b70", "size": 1235, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/cosine.jl", "max_stars_repo_name": "ericproffitt/Distributions.jl", "max_stars_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/cosine.jl", "max_issues_repo_name": "ericproffitt/Distributions.jl", "max_issues_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/cosine.jl", "max_forks_repo_name": "ericproffitt/Distributions.jl", "max_forks_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0, "max_line_length": 76, "alphanum_fraction": 0.5829959514, "num_tokens": 512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8723473680407889, "lm_q1q2_score": 0.7697836213928995}}
{"text": "module bearingDistributions\nusing Distributions\nusing LinearAlgebra\nusing Plots\n\ninclude(\"App.jl\")\nusing .App\n\nexport Bearing, intersectGrid, bisectionRoots, plotConfidenceInterval, App\n\n\"\"\"\nBearing object.\n\nDefined by a mean direction θ, a standard deviation of direction σ, and a position (x,y).\n\"\"\"\nstruct Bearing\n    θ\n    σ\n    x\n    y\nend\n\n\"\"\"\nfindIntersect(b1::Bearing, b2::Bearing)\n\nThis solves the simultaneous equations of the two paramterized lines as below:\n    x₁ + cos(θ₁)t₁ = x₂ + cos(θ₂)t₂\n    y₁ + sin(θ₁)t₁ = y₂ + sin(θ₂)t₂\n\n    x₁ - x₂ = -cos(θ₁)t₁ + cos(θ₂)t₂\n    y₁ - y₂ = -sin(θ₁)t₁ + sin(θ₂)t₂\n\n    This can be represented in matrix form as:\n    b = Ax̄\n    \n    where:\n    x̄ = [t₁, t₂]\n    A = |-cos(θ₁) cos(θ₂)|\n        |-sin(θ₁) sin(θ₂)|\n        \n    b = [x₁ - x₂, y₁ - y₂]\n\n    Solved by:\n    x̄ = A⁻¹ ⋅ b\n\n    This matrix is singular when θ₁ and θ₂ are parallel, i.e.  mod(θ₁,π) == mod(θ₂,π)\n    In this case, there is a heuristic that sets the \"intersection\" as the midpoint between the two points.\n\n    Furthermore, if tᵢ<0 then there is no defined intersection point (lines pointed away from each other)\n\"\"\"\nfunction findIntersect(b1::Bearing, b2::Bearing)\n    if mod(b1.θ-b2.θ,π)≈0 \n        point = ([b1.x;b1.y] + [b2.x;b2.y])/2\n        return point\n    end\n\n    A = [-cos(b1.θ) cos(b2.θ);\n         -sin(b1.θ) sin(b2.θ)]\n\n    b = [b1.x - b2.x, b1.y - b2.y];\n    \n    t = inv(A) * b;\n    if any(t .< 0)\n        point = ([b1.x;b1.y] + [b2.x;b2.y])/2\n        return point\n    end\n    point = [b1.x, b1.y] + [cos(b1.θ), sin(b1.θ)]*t[1];\n    return point\nend\n\n\n\"\"\"\nboundingBox(b1::Bearing, b2::Bearing)    \n    Return the box [xₗ xᵤ;yₗ yᵤ] around the intersection of two bearings.\n\n    Size the box such that the origin of the bearings will always be included in the box.\n\"\"\"\nfunction boundingBox(b1::Bearing, b2::Bearing)\n    pᵢ = findIntersect(b1, b2);\n    p₁ = [b1.x;b1.y];\n    p₂ = [b2.x;b2.y];\n    d₁ = pᵢ - p₁;\n    d₂ = pᵢ - p₂;\n    D₁ = norm(d₁);\n    D₂ = norm(d₂);\n    D = 1.5*max(D₁, D₂);\n    box = pᵢ .+ 1*[-D D;-D D];\n    box\nend\n\n\"\"\"\nrangeFromBox(box::Array{Number,2}; length = 51)\n\n    Wrapper to splat out the box array.\n\"\"\"\nfunction rangeFromBox(box::Array{T,2} where T<:Number ; length = 51)\n    x,y = rangeFromBox(box...; length)\n    return x,y\nend\n\n\n\"\"\"\nrangeFromBox(x1,y1,x2,y2; length)\n\n    convert `x1`:`x2` and `y1`:`y2` into ranges of length `length`\n\"\"\"\nfunction rangeFromBox(x1,y1,x2,y2; length)\n    x = range(x1, x2; length);\n    y = range(y1, y2; length);\n    return x,y\nend\n\n\"\"\"\nprobabilityGrid(b::Bearing, x::AbstractArray, y::AbstractArray)\n\n    Compute the probability grid over ranges `x` and `y` of bearing `b`\n\"\"\"\nfunction probabilityGrid(b::Bearing, x::AbstractArray, y::AbstractArray)\n    θ = mod(b.θ + π,2π) - π\n    D = Normal(0, b.σ);\n    Θ = atan.(y .- b.y, x' .- b.x) .- θ;\n    Θ = mod.(Θ .+ π, 2π) .-π\n    P = pdf.(D, Θ);\n    ΔA = convert(Float64,x.step * y.step);\n    P = P./sum(P[:])/ΔA;\n    return x, y, P\nend\n\n\"\"\"\nintersectGrid(b1::Bearing, b2::Bearing; length = 51)\n\n    Compute the probability grid of the intersection of `b1` and `b2` over ranges `x` and `y`\n\n    Return the probability grids for `b1`, `b2`, and the intersection.\n\n\"\"\"\nfunction intersectGrid(b1::Bearing, b2::Bearing; length = 51)\n    box = boundingBox(b1, b2);\n    x,y = rangeFromBox(box...; length)\n    _,_,P₁ = probabilityGrid(b1, x, y);\n    _,_,P₂ = probabilityGrid(b2, x, y);\n    Pᵢ = P₁ .* P₂\n    ΔA = convert(Float64,x.step * y.step);\n    Pᵢ = Pᵢ ./ sum(Pᵢ[:])\n    Pᵢ = Pᵢ ./ ΔA;\n    return x, y, Pᵢ, P₁, P₂\nend\n\n\"\"\"\nplotProbabilityGrids(x::AbstractArray, y::AbstractArray, P...)\n\n    Plot of tuple of probability grids `P` on ranges x and y with the default contour levels\n\"\"\"\nfunction plotProbabilityGrids(x::AbstractArray, y::AbstractArray, P...)\n    p = contour(;aspect_ratio=:equal);\n    for P in P\n        contour!(x,y,P)\n    end\n    display(p)\nend\n\n\"\"\"\nplotConfidenceInterval(α::Number, x::AbstractArray, y::AbstractArray, P...)\n\n    Plot the tuple of probability grids `P` on ranges x and y at the defined confidence interval `α`\n\"\"\"\nfunction plotConfidenceInterval(α::Number, x::AbstractArray, y::AbstractArray, P...)\n    handle = contour(;aspect_ratio=:equal);\n    ΔA = convert(Float64,x.step*y.step);\n    zeros = [bisectionRoots((p) -> ΔA*sum(Pⱼ[Pⱼ .> p]) - α, minimum(Pⱼ),maximum(Pⱼ)) for Pⱼ in P]\n    for (i,P) in enumerate(P)\n        contour!(x,y,P; levels=[zeros[i]])\n    end\n    return handle\nend\n\n\"\"\"\nbisectionRoots(f::Function,xₗ::Number,xᵤ::Number; max_iteration = 100, xtol = 1e-3)\n\n    Computes the root of function `f(x)` on the bounded range `[xₗ xᵤ]` with the Bisection algorithm.\n\n    Exit condition is defined by xᵤ-xₗ < xtol\n\"\"\"\nfunction bisectionRoots(f::Function,xₗ::Number,xᵤ::Number; max_iteration = 100, xtol = 1e-3)\n    fₗ  = f(xₗ);\n    fᵤ = f(xᵤ);\n\n    if fₗ == 0\n        return xₗ\n    elseif fᵤ == 0\n        return xᵤ\n    end\n\n    if (fₗ<0 && fᵤ<0) || (fₗ>0 && fᵤ>0)\n        return NaN\n    end\n\n    xᵢ = (xₗ + xᵤ)/2;\n    iter = 1;\n\n    while abs(xᵤ-xₗ) > xtol\n        iter > max_iteration ? break : iter+=1;\n        if sign(f(xᵢ))==sign(fₗ)\n            xₗ = xᵢ\n            xᵢ = (xᵢ + xᵤ)/2\n        else\n            xᵤ = xᵢ\n            xᵢ = (xₗ + xᵢ)/2\n        end\n    end\n    return xᵢ\nend\n\n\n\nend\n", "meta": {"hexsha": "2c9e53e343e7ed8a6d147e7072ed6c250d8bb53e", "size": 5282, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bearingDistributions.jl", "max_stars_repo_name": "alexjbuck/bearingDistributions.jl", "max_stars_repo_head_hexsha": "8d2aa5104b42c5964d7f6733f4822c909b05ef71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bearingDistributions.jl", "max_issues_repo_name": "alexjbuck/bearingDistributions.jl", "max_issues_repo_head_hexsha": "8d2aa5104b42c5964d7f6733f4822c909b05ef71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-12-14T01:02:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-30T01:03:07.000Z", "max_forks_repo_path": "src/bearingDistributions.jl", "max_forks_repo_name": "alexjbuck/bearingDistributions.jl", "max_forks_repo_head_hexsha": "8d2aa5104b42c5964d7f6733f4822c909b05ef71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3410138249, "max_line_length": 107, "alphanum_fraction": 0.594471791, "num_tokens": 1952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615413, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7697439170232786}}
{"text": "\"\"\"\n    integral(f, t = echotime(f))\n\nIntegral of time profile `f` between `0` and `t`. Unless specified, the echotime\nis used as the upper integral limit.\n\nFor the `PGSE`, `SinOGSE`, `CosOGSE` and `DoublePGSE` sequences, analytical\nexpressions are available. Otherwise a numerical integral is computed.\n\"\"\"\nfunction integral(f::TimeProfile, t = echotime(f))\n    quadgk(f, zero(t), t)\nend\n\nfunction integral(f::PGSE, t = echotime(f))\n    δ, Δ = f.δ, f.Δ\n    (zero(t) ≤ t < δ) * t + (δ ≤ t < Δ + δ) * δ - (Δ ≤ t < Δ + δ) * (t - Δ)\nend\n\nfunction integral(f::DoublePGSE, t = echotime(f))\n    δ, Δ, p = f.δ, f.Δ, f.tpause\n    tmid = p + Δ + δ\n    if zero(t) ≤ t < δ\n        t\n    elseif δ ≤ t < Δ\n        δ\n    elseif Δ ≤ t < Δ + δ\n        δ - (t - Δ)\n    elseif tmid ≤ t < tmid + δ\n        t - tmid\n    elseif tmid + δ ≤ t < tmid + Δ\n        δ\n    elseif tmid + Δ ≤ t < tmid + Δ + δ\n        δ - (t - Δ - tmid)\n    else\n        zero(t)\n    end\nend\n\nfunction integral(f::CosOGSE, t = echotime(f))\n    δ, Δ, n = f.δ, f.Δ, f.nperiod\n    ((t < δ) * sin(2π * n * t / δ) - (Δ ≤ t) * sin(2π * n * (t - Δ) / δ)) * δ / (2π * n)\nend\n\nfunction integral(f::SinOGSE, t = echotime(f))\n    δ, Δ, n = f.δ, f.Δ, f.nperiod\n    ((t < δ) * (1 - cos(2π * n * t / δ)) - (Δ ≤ t) * (1 - cos(2π * n * (t - Δ) / δ))) * δ /\n    (2π * n)\nend\n", "meta": {"hexsha": "943dba5138e77ae726d37f1f0fb56dfb257a5309", "size": 1310, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gradients/integral.jl", "max_stars_repo_name": "fachra/SpinDoctor.jl", "max_stars_repo_head_hexsha": "25c633fb8020843728c1004c492a7c33b2fe2e4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2022-03-19T12:53:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:39:38.000Z", "max_issues_repo_path": "src/gradients/integral.jl", "max_issues_repo_name": "fachra/SpinDoctor.jl", "max_issues_repo_head_hexsha": "25c633fb8020843728c1004c492a7c33b2fe2e4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2022-03-13T19:49:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T14:58:15.000Z", "max_forks_repo_path": "src/gradients/integral.jl", "max_forks_repo_name": "fachra/SpinDoctor.jl", "max_forks_repo_head_hexsha": "25c633fb8020843728c1004c492a7c33b2fe2e4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-11T09:54:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T11:10:57.000Z", "avg_line_length": 26.7346938776, "max_line_length": 91, "alphanum_fraction": 0.5061068702, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224331, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7697439137594078}}
{"text": "# Load Julia packages (libraries) needed  for the snippets in chapter 0\n\nusing StatisticalRethinking, Optim\n#gr(size=(600,600));\n\n# CmdStan uses a tmp directory to store the output of cmdstan\n\nProjDir = rel_path(\"..\", \"scripts\", \"04\")\ncd(ProjDir)\n\n# ### snippet 4.24\n\nhowell1 = CSV.read(rel_path(\"..\", \"data\", \"Howell1.csv\"), delim=';')\ndf = convert(DataFrame, howell1);\ndf2 = filter(row -> row[:age] >= 18, df);\nfirst(df2, 5)\n\n# ### snippet 4.25\n\n# Our first model:\n\nm4_1 = \"\n  height ~ Normal(μ, σ) # likelihood\n  μ ~ Normal(178,20) # prior\n  σ ~ Uniform(0, 50) # prior\n\"\n\n# ### snippet 4.26\n\n# Compute MAP\n\nobs = df2[:height]\n\nfunction loglik(x)\n  ll = 0.0\n  ll += log(pdf(Normal(178, 20), x[1]))\n  ll += log(pdf(Uniform(0, 50), x[2]))\n  ll += sum(log.(pdf.(Normal(x[1], x[2]), obs)))\n  -ll\nend\n\n# ### snippet 4.28\n\nx0 = [ 178, 10.0]\nlower = [0.0, 0.0]\nupper = [250.0, 50.0]\n\n# ### snippet 4.27\n\ninner_optimizer = GradientDescent()\n\noptimize(loglik, lower, upper, x0, Fminbox(inner_optimizer))\n\n# Our second model:\n\nm4_2 = \"\n  height ~ Normal(μ, σ) # likelihood\n  μ ~ Normal(178, 0.1) # prior\n  σ ~ Uniform(0, 50) # prior\n\"\n\n# ### snippet 4.29\n\n# Compute MAP\n\nobs = df2[:height]\n\nfunction loglik2(x)\n  ll = 0.0\n  ll += log(pdf(Normal(178, 0.1), x[1]))\n  ll += log(pdf(Uniform(0, 50), x[2]))\n  ll += sum(log.(pdf.(Normal(x[1], x[2]), obs)))\n  -ll\nend\n\noptimize(loglik2, lower, upper, x0, Fminbox(inner_optimizer))\n\n# End of `clip-24-29s.jl`\n", "meta": {"hexsha": "f14c96c682db9d8f6199a33bf31290511c18c2b6", "size": 1443, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/04/clip-24-29s.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_stars_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/04/clip-24-29s.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_issues_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/04/clip-24-29s.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_forks_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.2658227848, "max_line_length": 71, "alphanum_fraction": 0.6112266112, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7697289518792484}}
{"text": "## This is an implementation of\n## Marsaglia, G. and Tsang, W.W., 2000. A simple method for generating gamma\n## variables. ACM Transactions on Mathematical Software (TOMS), 26(3)\n@inline function sampleGamma(α::Float64, rng::RNG) where RNG <: AbstractRNG\n  @assert α > 0.0\n  if α < 1.0\n    return rand(rng)^(1/α)*sampleGamma(1.0+α, rng)\n  end\n  d::Float64 = α - 1/3\n  c::Float64 = 1/sqrt(9*d)\n  while true\n    x::Float64 = randn(rng)\n    v::Float64 = (1 + c*x)^3\n    v < 0 && continue\n    u::Float64 = rand(rng)\n    x2::Float64 = x*x\n    x4::Float64 = x2*x2\n    if u < 1.0 - 0.0331*x4 return d*v end\n    if log(u) < 0.5*x2 + d*(1-v+log(v))\n      return d*v\n    end\n  end\nend\n\n@inline function sampleGamma(α::Float64, β::Float64,\n  rng::RNG = GLOBAL_RNG) where RNG <: AbstractRNG\n  return sampleGamma(α, rng) / β\nend\n", "meta": {"hexsha": "69ecde2c0ea270b96bdd220c30de7bd6e01c777b", "size": 816, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gamma.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NonUniformRandomVariateGeneration.jl-cd27a545-1e2a-5997-b51f-f9caa06aeab2", "max_stars_repo_head_hexsha": "9013cf73fe5814b864b821637935577bba333d31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-09-05T08:52:05.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-05T08:52:05.000Z", "max_issues_repo_path": "src/gamma.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/NonUniformRandomVariateGeneration.jl-cd27a545-1e2a-5997-b51f-f9caa06aeab2", "max_issues_repo_head_hexsha": "9013cf73fe5814b864b821637935577bba333d31", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-02T14:28:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T14:29:00.000Z", "max_forks_repo_path": "src/gamma.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/NonUniformRandomVariateGeneration.jl-cd27a545-1e2a-5997-b51f-f9caa06aeab2", "max_forks_repo_head_hexsha": "9013cf73fe5814b864b821637935577bba333d31", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1379310345, "max_line_length": 76, "alphanum_fraction": 0.6237745098, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176863577751, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7697236591215375}}
{"text": "using ImplicitGraphs, Primes\n\n\"\"\"\n    iPaley(p::Int)\n\nCreate an implicit Paley graph on `p` vertices. \nHere `p` must be a prime congruent to 1 modulo 4. \nThe vertices of the graph are integers in the range\n`0:p-1` and two vertices are adjacent if their difference\nis a quadratic residue mod `p`.\n\"\"\"\nfunction iPaley(p::Int)::ImplicitGraph\n    if !isprime(p) || p % 4 != 1\n        error(\"Argument ($p) must be prime and congruent to 1 mod 4\")\n    end\n\n    vcheck(v::Int) = (0 <= v < p)\n\n    function outs(v::Int)\n        return unique((v + k^2) % p for k = 1:p-1)\n    end\n\n    return ImplicitGraph{Int}(vcheck, outs)\nend\n", "meta": {"hexsha": "ce69e5432acd791e26fc0726f4e0ced22c928ee6", "size": 620, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "extras/iPaley.jl", "max_stars_repo_name": "scheinerman/ImplicitGraphs.jl", "max_stars_repo_head_hexsha": "0cc9c163b88c13c99c1c636589dd1209e63310e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-02-03T22:09:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T00:31:06.000Z", "max_issues_repo_path": "extras/iPaley.jl", "max_issues_repo_name": "scheinerman/ImplicitGraphs.jl", "max_issues_repo_head_hexsha": "0cc9c163b88c13c99c1c636589dd1209e63310e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extras/iPaley.jl", "max_forks_repo_name": "scheinerman/ImplicitGraphs.jl", "max_forks_repo_head_hexsha": "0cc9c163b88c13c99c1c636589dd1209e63310e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8, "max_line_length": 69, "alphanum_fraction": 0.6435483871, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9643214460461698, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.7697086184659748}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.0\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ f66e452c-97db-11eb-23fc-bd95da10e2d6\nusing Plots, FFTW, TestImages, PlutoUI, Images, ImageShow\n\n# ╔═╡ adaa78fa-d805-45e6-ba5f-d91a5d4823d6\nusing ImageContrastAdjustment\n\n# ╔═╡ 09fc6764-2050-4276-8a14-3596368d0c32\nmd\"\"\"\n# How much data do we need?\n\nOne of the challenges of information representation generally is how much data do we need to represent an object/concept sufficiently. It should be noted, that \"represent sufficiently\" is an ill-defined term, since this judgement will be application specific. \n\nIn order to address this question, we are going to assume that a concept can be represented as a function. A concept can be quite general but in this notebook we will be using images as our concepts. That is, an image represents some function and this function can be represented as a combination of __basis functions__. So when we ask, \"How much data do you need?\" can be restated as \"How many basis functions do you need?\"\n\n## What is a basis function?\n\nI'll answer this later.\n\n\nWe will generally need an infinite number of basis functions to represent an arbitrary ???. However, in our digital world we can only use a finite number of basis functions, and with a finite number of basis functions we can only __approximate__ these functions.\n\n\n### Sinusoidal Basis Functions\n\n\n\nIn this notebook we are going to look at information representation in terms of sinusoidal basis functions. The canonical information representation based on sinusoidal basis functions is the [Fourier transform](https://en.wikipedia.org/wiki/Fourier_transform). In 1822 Jean-Baptiste Joseph Fourier demonstrated that (most) continous functions can be represented as a summation of an infinite number of appropriately weighted and phased sinusoidal (sines, cosines, complex exponentials) functions. The sinusoidal functions are an example of __basis__ functions. A key concept in the Fourier transform is the need for an infinite number of basis functions.\n\n\n\nIn applications such as magnetic resonance imaging (MRI) of the human body, we can view the body region being imaged as the continuous function. The MRI technique actually measures samples from the Fourier transform of the person's body region. How we sample this signal relates to both the cost of the acquisition and the integrity (error) of our approximation.\n\nIn communications, how many basis functions we use relates to how quickly we can transmit information using a radio wave or a fiber optic cable.\n\nIn this notebook we are going to look at information representation in terms of sinusoidal basis functions, specifically, the [Discrete Cosine Transform (DCT)](https://en.wikipedia.org/wiki/Discrete_cosine_transform), which is commonly used in signal processing and image.\n\n## Image Example\n\nTo start with, we are going to look at a public domain digital image. As the image is already digitized, we are not going to worry about how the discrete image is only an approximation of the continuous physical object.\n\nI will refer to the inverse DCT of an image as the __spectrum__. The spectrum corresponds to the coefficients for each basis function.\n\nI've taken the DCT of the image and then prior to taking the inverse DCT (IDCT), I've zeroed out a fraction of the spectrum. (NEED TO DEFINE SPECTRUM.) based on the slider value _kp_. _kp_ represents what fraction of the spectrum was kept (not zeroed out) starting with the DC term. So a _kp_ of zero throws out all the original data and a _kp_ of 1 keeps all the original data.\n\n$(@bind go Button(\"Start/Restart\"))\n\"\"\"\n\n# ╔═╡ e50c3024-140d-4312-ad8e-66b94482964b\nmd\"\"\"# DCT Basis Functions\n\nDCT forms the basis of JPEG image compression. In JPEG compression the image is split into 8x8 tiles. The DCT is computed for each tile. As was demonstrated above, an image can be recognized with a high degree of certitude wihtout many of the high frequency terms. JPEG exploits this by discarding the coefficients for high frequency basis functions within the DCT for each tile.\n\nWhat do these basis functions look like? For an 8x8 tile, there are 64 distinct basis functions. We can visualize these basis functions by taking the inverse DCT for a Kronecker Delta spectrum.\n\nPlot the desired basis function by selecting the desired Kronecker Delta value δ(i,j)\n\"\"\"\n\n# ╔═╡ f90425a3-8e6f-440a-8522-5ccd5cca2797\n\nmd\"\"\"\n\nCreate a Different Kronecker Delta spectrum by changin the (i,j) vaues.\n\ni\n$(@bind i Slider(1:1:8))\nj\n$(@bind j Slider(1:1:8))\n\"\"\"\n\n# ╔═╡ 899a3541-9cef-48de-a03d-367223fe3100\nmd\"\"\"### All 64 Basis Functions\"\"\"\n\n# ╔═╡ 99028838-babb-4d29-a400-c321c65e455d\nmd\"\"\"### Code cells are hidden down here\"\"\"\n\n# ╔═╡ 85859f7b-26e2-415e-87f1-b61180449a61\nimages = [i for i in TestImages.remotefiles if ! contains(i, \"tif\") && ! contains(i, \"256\") && ! contains(i, \"color\")] ;\n\n# ╔═╡ 0d142947-1e3c-4adc-b6ca-09c502f89f0e\nbegin\n\tgo\n\tind = rand(1:length(images))\n\tiname = popat!(images, ind)\n\timg = Gray.(testimage(iname));\n\taimg = Float64.(img) ;\n\tkimg = dct(aimg) ;\n\t@bind kp Slider(0:0.01:1, show_value=true)\nend \n\n# ╔═╡ c4d7b864-275a-4e6f-9cc1-74138a1f07ae\nfunction kd2(i,j)\n\timg = zeros((8,8))\n\timg[i,j] = 1\n\timg\nend ;\n\n# ╔═╡ 4369ef1b-4291-4b2f-8bc1-ac011080bb18\nbimg = kd2(i,j) ;\n\n# ╔═╡ 740ecf61-15d7-4b30-8ef8-e9ed339912af\nmd\"\"\"\n### Kronecker Delta Spectrum\n\n$(Gray.(bimg))\n\n### Resulting Basis Function\n\n$(Gray.(6*idct(bimg)))\n\"\"\"\n\n# ╔═╡ 6c43a6ef-41af-4343-910b-04e72fdc87fd\nalg = Equalization(nbins = 256);\n\n# ╔═╡ 2b98ae25-097e-4dd5-aa4b-01a3b06c2fc8\nbegin\n\ttmp3 = zeros(64,64) ;\t\n\tfor j in 0:7\n\t\tfor i in 0:7\n\t\t\ttmp3[i*8+1:i*8+8,j*8+1:j*8+8] =idct(kd2(i+1,j+1))\n\t\tend\n\tend\n\timresize(adjust_histogram(Gray.(tmp3), alg), 256, 256)\nend\n\n# ╔═╡ 628877b2-6e8d-47a1-8dce-752b9d75ab56\nfunction filter_img(kimg, p)\n\tsz = size(kimg)\n\tfsz = convert.(Int64, round.(sz .* p))\n\tf = zeros(sz)\n\tf[1:fsz[1],1:fsz[2]] .= 1\n\tidct(kimg .* f)\nend;\n\t\n\n# ╔═╡ 12fb095f-02a6-48c6-856a-afbc71a6ad64\nfimg = filter_img(kimg, kp) ;\n\n# ╔═╡ 48412713-7266-43dc-a49e-bab349318cce\nmd\"\"\"\n## What do you think this image is?\n\nIncrease kp to provide more basis functions for representing the image. kp represents the fraction of the discrete cosine transform basis functions to use (extending out from the DC term. What is the minimum kp for you to recognize the image?\n\n$(Gray.(fimg))\n\nkp\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nFFTW = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nImageContrastAdjustment = \"f332f351-ec65-5f6a-b3d1-319c6670881a\"\nImageShow = \"4e3cecfd-b093-5904-9786-8bbb286a6a31\"\nImages = \"916415d5-f1e6-5110-898d-aaa5f9f070e0\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nTestImages = \"5e47fb64-e119-507b-a336-dd2b206d9990\"\n\n[compat]\nFFTW = \"~1.4.5\"\nImageContrastAdjustment = \"~0.3.7\"\nImageShow = \"~0.3.1\"\nImages = \"~0.24.1\"\nPlots = \"~1.22.2\"\nPlutoUI = \"~0.7.11\"\nTestImages = \"~1.6.1\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[AbstractFFTs]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"485ee0867925449198280d4af84bdb46a2a404d0\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"1.0.1\"\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[ArrayInterface]]\ndeps = [\"Compat\", \"IfElse\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"Static\"]\ngit-tree-sha1 = \"b8d49c34c3da35f220e7295659cd0bab8e739fed\"\nuuid = \"4fba245c-0d91-5ea0-9b3e-6abc04ee57a9\"\nversion = \"3.1.33\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[AxisAlgorithms]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"a4d07a1c313392a77042855df46c5f534076fab9\"\nuuid = \"13072b0f-2c55-5437-9ae7-d433b7a33950\"\nversion = \"1.0.0\"\n\n[[AxisArrays]]\ndeps = [\"Dates\", \"IntervalSets\", \"IterTools\", \"RangeArrays\"]\ngit-tree-sha1 = \"d127d5e4d86c7680b20c35d40b503c74b9a39b5e\"\nuuid = \"39de3d68-74b9-583c-8d2d-e117c070f3a9\"\nversion = \"0.4.4\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[CEnum]]\ngit-tree-sha1 = \"215a9aa4a1f23fbd05b92769fdd62559488d70e9\"\nuuid = \"fa961155-64e5-5f13-b03f-caf6b980ea82\"\nversion = \"0.4.1\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"f2202b55d816427cd385a9a4f3ffb226bee80f99\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+0\"\n\n[[CatIndices]]\ndeps = [\"CustomUnitRanges\", \"OffsetArrays\"]\ngit-tree-sha1 = \"a0f80a09780eed9b1d106a1bf62041c2efc995bc\"\nuuid = \"aafaddc9-749c-510e-ac4f-586e18779b91\"\nversion = \"0.2.2\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"bd4afa1fdeec0c8b89dad3c6e92bc6e3b0fec9ce\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.6.0\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"a851fec56cb73cfdf43762999ec72eff5b86882a\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.15.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[ColorVectorSpace]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"LinearAlgebra\", \"SpecialFunctions\", \"Statistics\", \"TensorCore\"]\ngit-tree-sha1 = \"45efb332df2e86f2cb2e992239b6267d97c9e0b6\"\nuuid = \"c3611d14-8923-5661-9e6a-0046d554d3a4\"\nversion = \"0.9.7\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"31d0151f5716b655421d9d75b7fa74cc4e744df2\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.39.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[ComputationalResources]]\ngit-tree-sha1 = \"52cb3ec90e8a8bea0e62e275ba577ad0f74821f7\"\nuuid = \"ed09eef8-17a6-5b46-8889-db040fac31e3\"\nversion = \"0.3.2\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[CoordinateTransformations]]\ndeps = [\"LinearAlgebra\", \"StaticArrays\"]\ngit-tree-sha1 = \"6d1c23e740a586955645500bbec662476204a52c\"\nuuid = \"150eb455-5306-5404-9cee-2592286d6298\"\nversion = \"0.6.1\"\n\n[[CustomUnitRanges]]\ngit-tree-sha1 = \"1a3f97f907e6dd8983b744d2642651bb162a3f7a\"\nuuid = \"dc8bdbbb-1ca9-579f-8c36-e416f6a65cce\"\nversion = \"1.0.2\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distances]]\ndeps = [\"LinearAlgebra\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"9f46deb4d4ee4494ffb5a40a27a2aced67bdd838\"\nuuid = \"b4f34e82-e78d-54a5-968a-f98e89d6e8f7\"\nversion = \"0.10.4\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"a32185f5428d3986f47c2ab78b1f216d5e6cc96f\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.5\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[EllipsisNotation]]\ndeps = [\"ArrayInterface\"]\ngit-tree-sha1 = \"8041575f021cba5a099a456b4163c9a08b566a02\"\nuuid = \"da5c29d0-fa7d-589e-88eb-ea29b0a81949\"\nversion = \"1.1.0\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FFTViews]]\ndeps = [\"CustomUnitRanges\", \"FFTW\"]\ngit-tree-sha1 = \"70a0cfd9b1c86b0209e38fbfe6d8231fd606eeaf\"\nuuid = \"4f61f5a4-77b1-5117-aa51-3ab5ef4ef0cd\"\nversion = \"0.3.1\"\n\n[[FFTW]]\ndeps = [\"AbstractFFTs\", \"FFTW_jll\", \"LinearAlgebra\", \"MKL_jll\", \"Preferences\", \"Reexport\"]\ngit-tree-sha1 = \"463cb335fa22c4ebacfd1faba5fde14edb80d96c\"\nuuid = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nversion = \"1.4.5\"\n\n[[FFTW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea\"\nuuid = \"f5851436-0d7a-5f13-b9de-f02708fd171a\"\nversion = \"3.3.10+0\"\n\n[[FileIO]]\ndeps = [\"Pkg\", \"Requires\", \"UUIDs\"]\ngit-tree-sha1 = \"3c041d2ac0a52a12a27af2782b34900d9c3ee68c\"\nuuid = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nversion = \"1.11.1\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"dba1e8614e98949abfa60480b13653813d8f0157\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+0\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"c2178cfbc0a5a552e16d097fae508f2024de61a3\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.59.0\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"ef49a187604f865f4708c90e3f431890724e9012\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.59.0+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"7bf67e9a481712b3dbe9cb3dac852dc4b1162e02\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+0\"\n\n[[Graphics]]\ndeps = [\"Colors\", \"LinearAlgebra\", \"NaNMath\"]\ngit-tree-sha1 = \"2c1cf4df419938ece72de17f368a021ee162762e\"\nuuid = \"a2bd30eb-e257-5431-a919-1863eab51364\"\nversion = \"1.1.0\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"60ed5f1643927479f845b0135bb369b031b541fa\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.14\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"8a954fed8ac097d5be04921d595f741115c1b2ad\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+0\"\n\n[[HypertextLiteral]]\ngit-tree-sha1 = \"72053798e1be56026b81d4e2682dbe58922e5ec9\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.0\"\n\n[[IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[IdentityRanges]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"be8fcd695c4da16a1d6d0cd213cb88090a150e3b\"\nuuid = \"bbac6d45-d8f3-5730-bfe4-7a449cd117ca\"\nversion = \"0.3.1\"\n\n[[IfElse]]\ngit-tree-sha1 = \"28e837ff3e7a6c3cdb252ce49fb412c8eb3caeef\"\nuuid = \"615f187c-cbe4-4ef1-ba3b-2fcf58d6d173\"\nversion = \"0.1.0\"\n\n[[ImageAxes]]\ndeps = [\"AxisArrays\", \"ImageCore\", \"Reexport\", \"SimpleTraits\"]\ngit-tree-sha1 = \"794ad1d922c432082bc1aaa9fa8ffbd1fe74e621\"\nuuid = \"2803e5a7-5153-5ecf-9a86-9b4c37f5f5ac\"\nversion = \"0.6.9\"\n\n[[ImageContrastAdjustment]]\ndeps = [\"ColorVectorSpace\", \"ImageCore\", \"ImageTransformations\", \"Parameters\"]\ngit-tree-sha1 = \"2e6084db6cccab11fe0bc3e4130bd3d117092ed9\"\nuuid = \"f332f351-ec65-5f6a-b3d1-319c6670881a\"\nversion = \"0.3.7\"\n\n[[ImageCore]]\ndeps = [\"AbstractFFTs\", \"Colors\", \"FixedPointNumbers\", \"Graphics\", \"MappedArrays\", \"MosaicViews\", \"OffsetArrays\", \"PaddedViews\", \"Reexport\"]\ngit-tree-sha1 = \"db645f20b59f060d8cfae696bc9538d13fd86416\"\nuuid = \"a09fc81d-aa75-5fe9-8630-4744c3626534\"\nversion = \"0.8.22\"\n\n[[ImageDistances]]\ndeps = [\"ColorVectorSpace\", \"Distances\", \"ImageCore\", \"ImageMorphology\", \"LinearAlgebra\", \"Statistics\"]\ngit-tree-sha1 = \"6378c34a3c3a216235210d19b9f495ecfff2f85f\"\nuuid = \"51556ac3-7006-55f5-8cb3-34580c88182d\"\nversion = \"0.2.13\"\n\n[[ImageFiltering]]\ndeps = [\"CatIndices\", \"ColorVectorSpace\", \"ComputationalResources\", \"DataStructures\", \"FFTViews\", \"FFTW\", \"ImageCore\", \"LinearAlgebra\", \"OffsetArrays\", \"Requires\", \"SparseArrays\", \"StaticArrays\", \"Statistics\", \"TiledIteration\"]\ngit-tree-sha1 = \"bf96839133212d3eff4a1c3a80c57abc7cfbf0ce\"\nuuid = \"6a3955dd-da59-5b1f-98d4-e7296123deb5\"\nversion = \"0.6.21\"\n\n[[ImageIO]]\ndeps = [\"FileIO\", \"Netpbm\", \"OpenEXR\", \"PNGFiles\", \"TiffImages\", \"UUIDs\"]\ngit-tree-sha1 = \"13c826abd23931d909e4c5538643d9691f62a617\"\nuuid = \"82e4d734-157c-48bb-816b-45c225c6df19\"\nversion = \"0.5.8\"\n\n[[ImageMagick]]\ndeps = [\"FileIO\", \"ImageCore\", \"ImageMagick_jll\", \"InteractiveUtils\", \"Libdl\", \"Pkg\", \"Random\"]\ngit-tree-sha1 = \"5bc1cb62e0c5f1005868358db0692c994c3a13c6\"\nuuid = \"6218d12a-5da1-5696-b52f-db25d2ecc6d1\"\nversion = \"1.2.1\"\n\n[[ImageMagick_jll]]\ndeps = [\"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pkg\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"1c0a2295cca535fabaf2029062912591e9b61987\"\nuuid = \"c73af94c-d91f-53ed-93a7-00f77d67a9d7\"\nversion = \"6.9.10-12+3\"\n\n[[ImageMetadata]]\ndeps = [\"AxisArrays\", \"ColorVectorSpace\", \"ImageAxes\", \"ImageCore\", \"IndirectArrays\"]\ngit-tree-sha1 = \"ae76038347dc4edcdb06b541595268fca65b6a42\"\nuuid = \"bc367c6b-8a6b-528e-b4bd-a4b897500b49\"\nversion = \"0.9.5\"\n\n[[ImageMorphology]]\ndeps = [\"ColorVectorSpace\", \"ImageCore\", \"LinearAlgebra\", \"TiledIteration\"]\ngit-tree-sha1 = \"68e7cbcd7dfaa3c2f74b0a8ab3066f5de8f2b71d\"\nuuid = \"787d08f9-d448-5407-9aad-5290dd7ab264\"\nversion = \"0.2.11\"\n\n[[ImageQualityIndexes]]\ndeps = [\"ColorVectorSpace\", \"ImageCore\", \"ImageDistances\", \"ImageFiltering\", \"OffsetArrays\", \"Statistics\"]\ngit-tree-sha1 = \"1198f85fa2481a3bb94bf937495ba1916f12b533\"\nuuid = \"2996bd0c-7a13-11e9-2da2-2f5ce47296a9\"\nversion = \"0.2.2\"\n\n[[ImageShow]]\ndeps = [\"Base64\", \"FileIO\", \"ImageCore\", \"OffsetArrays\", \"Requires\", \"StackViews\"]\ngit-tree-sha1 = \"832abfd709fa436a562db47fd8e81377f72b01f9\"\nuuid = \"4e3cecfd-b093-5904-9786-8bbb286a6a31\"\nversion = \"0.3.1\"\n\n[[ImageTransformations]]\ndeps = [\"AxisAlgorithms\", \"ColorVectorSpace\", \"CoordinateTransformations\", \"IdentityRanges\", \"ImageCore\", \"Interpolations\", \"OffsetArrays\", \"Rotations\", \"StaticArrays\"]\ngit-tree-sha1 = \"e4cc551e4295a5c96545bb3083058c24b78d4cf0\"\nuuid = \"02fcd773-0e25-5acc-982a-7f6622650795\"\nversion = \"0.8.13\"\n\n[[Images]]\ndeps = [\"AxisArrays\", \"Base64\", \"ColorVectorSpace\", \"FileIO\", \"Graphics\", \"ImageAxes\", \"ImageContrastAdjustment\", \"ImageCore\", \"ImageDistances\", \"ImageFiltering\", \"ImageIO\", \"ImageMagick\", \"ImageMetadata\", \"ImageMorphology\", \"ImageQualityIndexes\", \"ImageShow\", \"ImageTransformations\", \"IndirectArrays\", \"OffsetArrays\", \"Random\", \"Reexport\", \"SparseArrays\", \"StaticArrays\", \"Statistics\", \"StatsBase\", \"TiledIteration\"]\ngit-tree-sha1 = \"8b714d5e11c91a0d945717430ec20f9251af4bd2\"\nuuid = \"916415d5-f1e6-5110-898d-aaa5f9f070e0\"\nversion = \"0.24.1\"\n\n[[Imath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"87f7662e03a649cffa2e05bf19c303e168732d3e\"\nuuid = \"905a6f67-0a94-5f89-b386-d35d92009cd1\"\nversion = \"3.1.2+0\"\n\n[[IndirectArrays]]\ngit-tree-sha1 = \"c2a145a145dc03a7620af1444e0264ef907bd44f\"\nuuid = \"9b13fd28-a010-5f03-acff-a1bbcff69959\"\nversion = \"0.5.1\"\n\n[[Inflate]]\ngit-tree-sha1 = \"f5fc07d4e706b84f72d54eedcc1c13d92fb0871c\"\nuuid = \"d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9\"\nversion = \"0.1.2\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[IntelOpenMP_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d979e54b71da82f3a65b62553da4fc3d18c9004c\"\nuuid = \"1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0\"\nversion = \"2018.0.3+2\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[Interpolations]]\ndeps = [\"AxisAlgorithms\", \"ChainRulesCore\", \"LinearAlgebra\", \"OffsetArrays\", \"Random\", \"Ratios\", \"Requires\", \"SharedArrays\", \"SparseArrays\", \"StaticArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"61aa005707ea2cebf47c8d780da8dc9bc4e0c512\"\nuuid = \"a98d9a8b-a2ab-59e6-89dd-64a1c18fca59\"\nversion = \"0.13.4\"\n\n[[IntervalSets]]\ndeps = [\"Dates\", \"EllipsisNotation\", \"Statistics\"]\ngit-tree-sha1 = \"3cc368af3f110a767ac786560045dceddfc16758\"\nuuid = \"8197267c-284f-5f27-9208-e0e47529a953\"\nversion = \"0.5.3\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"f76424439413893a832026ca355fe273e93bce94\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.0\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a4b12a1bd2ebade87891ab7e36fdbce582301a92\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.6\"\n\n[[LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"761a393aeccd6aa92ec3515e428c26bf99575b3b\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+0\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"DocStringExtensions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"34dc30f868e368f8a17b728a1238f3fcda43931a\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.3\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MKL_jll]]\ndeps = [\"Artifacts\", \"IntelOpenMP_jll\", \"JLLWrappers\", \"LazyArtifacts\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"5455aef09b40e5020e1520f551fa3135040d4ed0\"\nuuid = \"856f044c-d86e-5d09-b602-aeab76dc8ba7\"\nversion = \"2021.1.1+2\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"5a5bc6bf062f0f95e62d0fe0a2d99699fed82dd9\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.8\"\n\n[[MappedArrays]]\ngit-tree-sha1 = \"e8b359ef06ec72e8c030463fe02efe5527ee5142\"\nuuid = \"dbb5928d-eab1-5f90-85c2-b9b0edb7c900\"\nversion = \"0.4.1\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MosaicViews]]\ndeps = [\"MappedArrays\", \"OffsetArrays\", \"PaddedViews\", \"StackViews\"]\ngit-tree-sha1 = \"b34e3bc3ca7c94914418637cb10cc4d1d80d877d\"\nuuid = \"e94cdb99-869f-56ef-bcf0-1ae2bcbe0389\"\nversion = \"0.3.3\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[Netpbm]]\ndeps = [\"ColorVectorSpace\", \"FileIO\", \"ImageCore\"]\ngit-tree-sha1 = \"09589171688f0039f13ebe0fdcc7288f50228b52\"\nuuid = \"f09324ee-3d7c-5217-9330-fc30815ba969\"\nversion = \"1.0.1\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[OffsetArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"c0e9e582987d36d5a61e650e6e543b9e44d9914b\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.7\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+0\"\n\n[[OpenEXR]]\ndeps = [\"Colors\", \"FileIO\", \"OpenEXR_jll\"]\ngit-tree-sha1 = \"327f53360fdb54df7ecd01e96ef1983536d1e633\"\nuuid = \"52e1d378-f018-4a11-a4be-720524705ac7\"\nversion = \"0.3.2\"\n\n[[OpenEXR_jll]]\ndeps = [\"Artifacts\", \"Imath_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"923319661e9a22712f24596ce81c54fc0366f304\"\nuuid = \"18a262bb-aa17-5467-a713-aee519bc75cb\"\nversion = \"3.1.1+0\"\n\n[[OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[PNGFiles]]\ndeps = [\"Base64\", \"CEnum\", \"ImageCore\", \"IndirectArrays\", \"OffsetArrays\", \"libpng_jll\"]\ngit-tree-sha1 = \"e14c485f6beee0c7a8dcf6128bf70b85f1fe201e\"\nuuid = \"f57f5aa1-a3ce-4bc8-8ab9-96f992907883\"\nversion = \"0.3.9\"\n\n[[PaddedViews]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"646eed6f6a5d8df6708f15ea7e02a7a2c4fe4800\"\nuuid = \"5432bcbf-9aad-5242-b902-cca2824c8663\"\nversion = \"0.5.10\"\n\n[[Parameters]]\ndeps = [\"OrderedCollections\", \"UnPack\"]\ngit-tree-sha1 = \"34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe\"\nuuid = \"d96e819e-fc66-5662-9728-84c9c7592b0a\"\nversion = \"0.12.3\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"9d8c00ef7a8d110787ff6f170579846f776133a9\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.4\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PkgVersion]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"a7a7e1a88853564e551e4eba8650f8c38df79b37\"\nuuid = \"eebad327-c553-4316-9ea0-9fa01ccd7688\"\nversion = \"0.1.1\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"2537ed3c0ed5e03896927187f5f2ee6a4ab342db\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.0.14\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\"]\ngit-tree-sha1 = \"457b13497a3ea4deb33d273a6a5ea15c25c0ebd9\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.22.2\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"0c3e067931708fa5641247affc1a1aceb53fff06\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.11\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[ProgressMeter]]\ndeps = [\"Distributed\", \"Printf\"]\ngit-tree-sha1 = \"afadeba63d90ff223a6a48d2009434ecee2ec9e8\"\nuuid = \"92933f4c-e287-5a05-a399-4b506db050ca\"\nversion = \"1.7.1\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RangeArrays]]\ngit-tree-sha1 = \"b9039e93773ddcfc828f12aadf7115b4b4d225f5\"\nuuid = \"b3c3ace0-ae52-54e7-9d0b-2c1406fd6b9d\"\nversion = \"0.3.2\"\n\n[[Ratios]]\ndeps = [\"Requires\"]\ngit-tree-sha1 = \"01d341f502250e81f6fec0afe662aa861392a3aa\"\nuuid = \"c84ed2f1-dad5-54f0-aa8e-dbefe2724439\"\nversion = \"0.4.2\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"44a75aa7a527910ee3d1751d1f0e4148698add9e\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.2\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"7ad0dfa8d03b7bcf8c597f59f5292801730c55b8\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.4.1\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[Rotations]]\ndeps = [\"LinearAlgebra\", \"StaticArrays\", \"Statistics\"]\ngit-tree-sha1 = \"2ed8d8a16d703f900168822d83699b8c3c1a5cd8\"\nuuid = \"6038ab10-8711-5258-84ad-4b1120ba62dc\"\nversion = \"1.0.2\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[SimpleTraits]]\ndeps = [\"InteractiveUtils\", \"MacroTools\"]\ngit-tree-sha1 = \"5d7e3f4e11935503d3ecaf7186eac40602e7d231\"\nuuid = \"699a6c99-e7fa-54fc-8d76-47d257e15c1d\"\nversion = \"0.9.4\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"ad42c30a6204c74d264692e633133dcea0e8b14e\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.6.2\"\n\n[[StackViews]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"46e589465204cd0c08b4bd97385e4fa79a0c770c\"\nuuid = \"cae243ae-269e-4f55-b966-ac2d0dc13c15\"\nversion = \"0.1.1\"\n\n[[Static]]\ndeps = [\"IfElse\"]\ngit-tree-sha1 = \"a8f30abc7c64a39d389680b74e749cf33f872a70\"\nuuid = \"aedffcd0-7271-4cad-89d0-dc628f76c6d3\"\nversion = \"0.3.3\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3240808c6d463ac46f1c1cd7638375cd22abbccb\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.12\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"1958272568dc176a1d881acb797beb909c785510\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.0.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"8cbbc098554648c84f79a463c9ff0fd277144b6c\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.10\"\n\n[[StringDistances]]\ndeps = [\"Distances\"]\ngit-tree-sha1 = \"a4c05337dfe6c4963253939d2acbdfa5946e8e31\"\nuuid = \"88034a9c-02f8-509d-84a9-84ec65e18404\"\nversion = \"0.10.0\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.3\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"1162ce4a6c4b7e31e0e6b14486a6986951c73be9\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.5.2\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[TensorCore]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"1feb45f88d133a655e001435632f019a9a1bcdb6\"\nuuid = \"62fd8b95-f654-4bbd-a8a5-9c27f68ccd50\"\nversion = \"0.1.1\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[TestImages]]\ndeps = [\"AxisArrays\", \"ColorTypes\", \"FileIO\", \"OffsetArrays\", \"Pkg\", \"StringDistances\"]\ngit-tree-sha1 = \"db28237376a6b7ae9c9fe05880ece0ab8bb90b75\"\nuuid = \"5e47fb64-e119-507b-a336-dd2b206d9990\"\nversion = \"1.6.1\"\n\n[[TiffImages]]\ndeps = [\"ColorTypes\", \"DocStringExtensions\", \"FileIO\", \"FixedPointNumbers\", \"IndirectArrays\", \"Inflate\", \"OffsetArrays\", \"OrderedCollections\", \"PkgVersion\", \"ProgressMeter\"]\ngit-tree-sha1 = \"632a8d4dbbad6627a4d2d21b1c6ebcaeebb1e1ed\"\nuuid = \"731e570b-9d59-4bfa-96dc-6df516fadf69\"\nversion = \"0.4.2\"\n\n[[TiledIteration]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"5683455224ba92ef59db72d10690690f4a8dc297\"\nuuid = \"06e1c1a7-607b-532d-9fad-de7d9aa2abac\"\nversion = \"0.3.1\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[UnPack]]\ngit-tree-sha1 = \"387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b\"\nuuid = \"3a884ed6-31ef-47d7-9d2a-63182c4928ed\"\nversion = \"1.0.2\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\"]\ngit-tree-sha1 = \"2839f1c1296940218e35df0bbb220f2a79686670\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.18.0+4\"\n\n[[WoodburyMatrices]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"59e2ad8fd1591ea019a5259bd012d7aee15f995c\"\nuuid = \"efce3f68-66dc-5838-9240-27a6d6f5f9b6\"\nversion = \"0.5.3\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─09fc6764-2050-4276-8a14-3596368d0c32\n# ╟─48412713-7266-43dc-a49e-bab349318cce\n# ╟─0d142947-1e3c-4adc-b6ca-09c502f89f0e\n# ╟─e50c3024-140d-4312-ad8e-66b94482964b\n# ╟─f90425a3-8e6f-440a-8522-5ccd5cca2797\n# ╟─740ecf61-15d7-4b30-8ef8-e9ed339912af\n# ╟─899a3541-9cef-48de-a03d-367223fe3100\n# ╟─2b98ae25-097e-4dd5-aa4b-01a3b06c2fc8\n# ╟─99028838-babb-4d29-a400-c321c65e455d\n# ╟─85859f7b-26e2-415e-87f1-b61180449a61\n# ╟─12fb095f-02a6-48c6-856a-afbc71a6ad64\n# ╟─f66e452c-97db-11eb-23fc-bd95da10e2d6\n# ╟─4369ef1b-4291-4b2f-8bc1-ac011080bb18\n# ╟─c4d7b864-275a-4e6f-9cc1-74138a1f07ae\n# ╟─adaa78fa-d805-45e6-ba5f-d91a5d4823d6\n# ╟─6c43a6ef-41af-4343-910b-04e72fdc87fd\n# ╟─628877b2-6e8d-47a1-8dce-752b9d75ab56\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "38a1129baef36313e5255fcc3ff9ee1f76b15956", "size": 50492, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dct_basis_functions2.jl", "max_stars_repo_name": "chapmanbe/exploring_julia", "max_stars_repo_head_hexsha": "110828f2447c4d71b4c72964f177ddbd140bfa85", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dct_basis_functions2.jl", "max_issues_repo_name": "chapmanbe/exploring_julia", "max_issues_repo_head_hexsha": "110828f2447c4d71b4c72964f177ddbd140bfa85", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dct_basis_functions2.jl", "max_forks_repo_name": "chapmanbe/exploring_julia", "max_forks_repo_head_hexsha": "110828f2447c4d71b4c72964f177ddbd140bfa85", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8701657459, "max_line_length": 655, "alphanum_fraction": 0.7414441892, "num_tokens": 22267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.8705972650509008, "lm_q1q2_score": 0.7696421808856594}}
{"text": "\"\"\"\n    The function that will modulate tha activation value of\n    each non-input neuron in the network. It maps the z vale (∑wx + b)\n    of the neurons to ℝ. By default its taken the sigmoid function\n    one(z)/(one(z) + exp(-z)). To change it, just redefine it!!!\n    But remember change the act_function_prime function too!!!!!!\n\"\"\"\nfunction act_function(z::T)::T where T<:Real\n    return sigmoid(z);\nend\n\n\"\"\"\n    The first derivative of the act_function.\n\"\"\"\nfunction act_function_prime(z::T) where T<:Real\n    return sigmoid_prime(z);\nend\n\nfunction sigmoid(z::T)::T where T<:Real\n    return one(z)/(one(z) + exp(-z));\nend\nfunction sigmoid_prime(z::T) where T<:Real\n    return exp(-z)/((one(z) + exp(-z))^2);\nend\n\nReLU_ng = 0.1;\n\nfunction ReLU(z::T)::T where T<:Real\n    return max(ReLU_ng * z, z);\nend\n\nfunction ReLU_prime(z::T)::T where T<:Real\n    if z < 0\n        return ReLU_ng;\n    else\n        return one(z);\n    end\nend\n", "meta": {"hexsha": "0b23a977de397d5fb14c4eb49cc99040ad90a9a9", "size": 933, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ActFunction.jl", "max_stars_repo_name": "josePereiro/FFNetwoks.jl", "max_stars_repo_head_hexsha": "94282dd98dfd88e8919dc1c0a945f60b265d8c98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ActFunction.jl", "max_issues_repo_name": "josePereiro/FFNetwoks.jl", "max_issues_repo_head_hexsha": "94282dd98dfd88e8919dc1c0a945f60b265d8c98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ActFunction.jl", "max_forks_repo_name": "josePereiro/FFNetwoks.jl", "max_forks_repo_head_hexsha": "94282dd98dfd88e8919dc1c0a945f60b265d8c98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9230769231, "max_line_length": 70, "alphanum_fraction": 0.6452304394, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191259110587, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7696358430415876}}
{"text": "# See https://rdrr.io/rforge/copula/man/Sibuya.html\r\n\r\nstruct Sibuya{T<:Real} <: Distributions.DiscreteUnivariateDistribution\r\n    p::T\r\n    function Sibuya(p::T) where {T <: Real}\r\n        new{T}(p)\r\n    end\r\nend\r\nfunction Distributions.rand(rng::Distributions.AbstractRNG, d::Sibuya{T}) where {T <: Real}\r\n    u = rand(rng, T)\r\n    if u <= d.p\r\n        return T(1)\r\n    end\r\n    xMax = 1/eps(T)\r\n    Ginv = ((1-u)*SpecialFunctions.gamma(1-d.p))^(-1/d.p)\r\n    fGinv = floor(Ginv)\r\n    if Ginv > xMax \r\n        return fGinv\r\n    end\r\n    if 1-u < 1/(fGinv*SpecialFunctions.beta(fGinv,1-d.p))\r\n        return ceil(Ginv)\r\n    end\r\n    return fGinv\r\nend\r\n\r\n", "meta": {"hexsha": "7ea9372accbcf0a07982810dd2f8c1b27a80bdc2", "size": 654, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate_distributions/Sibuya.jl", "max_stars_repo_name": "lrnv/Copulas.jl", "max_stars_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2022-02-16T08:18:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:14:07.000Z", "max_issues_repo_path": "src/univariate_distributions/Sibuya.jl", "max_issues_repo_name": "lrnv/Copulas.jl", "max_issues_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-19T06:55:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T09:43:03.000Z", "max_forks_repo_path": "src/univariate_distributions/Sibuya.jl", "max_forks_repo_name": "lrnv/Copulas.jl", "max_forks_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1538461538, "max_line_length": 92, "alphanum_fraction": 0.5840978593, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7695940808441408}}
{"text": "\"\"\"\ncondentropy \\\\\n\nfor the condEntropy function specifically, calculating conditional entropy \\\\\nArguments:\tmarg_dist, marginal distributions \\\\\n\t\t\t\t\t\tcond_dists, conditional distributions \\\\\n\t\t\t\t\t\tbase, the base for entropy calculations \\\\\nReturns:\t\tFloat64, the conditional entropy \\\\\n\"\"\"\n\nfunction condentropy(marg_dist::Array{Float64,1}, cond_dists::Array{Float64}; base::Int=2)\n\tlength(marg_dist) == size(cond_dists)[2] || error(\"Number of marginal and conditional distributions does not match!\")\n\tents = [entropy(cond_dists[:, i], base) for i = 1:size(cond_dists)[2]]\n\treturn sum(marg_dist .* ents)\nend\n", "meta": {"hexsha": "623e51b625d848c8301ed4036e174de5d821452b", "size": 610, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/condentropy.jl", "max_stars_repo_name": "thomasjdelaney/Jentropy.jl", "max_stars_repo_head_hexsha": "7d991182ea3deb1643907edda77b02782da8b933", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-05T18:19:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-05T18:19:27.000Z", "max_issues_repo_path": "src/condentropy.jl", "max_issues_repo_name": "thomasjdelaney/Jentropy.jl", "max_issues_repo_head_hexsha": "7d991182ea3deb1643907edda77b02782da8b933", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/condentropy.jl", "max_forks_repo_name": "thomasjdelaney/Jentropy.jl", "max_forks_repo_head_hexsha": "7d991182ea3deb1643907edda77b02782da8b933", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.125, "max_line_length": 118, "alphanum_fraction": 0.737704918, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7695940775601534}}
{"text": "\nusing DifferentialEquations\nusing DiffEqSensitivity\nusing Random\nusing Distributions\nusing Turing\nusing DataFrames\nusing StatsPlots\n\n\nfunction sir_ode!(du,u,p,t)\n    (S,I,R,C) = u\n    (β,c,γ) = p\n    N = S+I+R\n    infection = β*c*I/N*S\n    recovery = γ*I\n    @inbounds begin\n        du[1] = -infection\n        du[2] = infection - recovery\n        du[3] = recovery\n        du[4] = infection\n    end\n    nothing\nend;\n\n\ntmax = 40.0\ntspan = (0.0,tmax)\nobstimes = 1.0:1.0:tmax\nu0 = [990.0,10.0,0.0,0.0] # S,I.R,C\np = [0.05,10.0,0.25]; # β,c,γ\n\n\nprob_ode = ODEProblem(sir_ode!,u0,tspan,p);\n\n\nsol_ode = solve(prob_ode,\n            Tsit5(),\n            saveat = 1.0);\n\n\nC = Array(sol_ode)[4,:] # Cumulative cases\nX = C[2:end] - C[1:(end-1)];\n\n\nRandom.seed!(1234)\nY = rand.(Poisson.(X));\n\n\nbar(obstimes,Y,legend=false)\nplot!(obstimes,X,legend=false)\n\n\n@model bayes_sir(y) = begin\n  # Calculate number of timepoints\n  l = length(y)\n  i₀  ~ Uniform(0.0,1.0)\n  β ~ Uniform(0.0,1.0)\n  I = i₀*1000.0\n  u0=[1000.0-I,I,0.0,0.0]\n  p=[β,10.0,0.25]\n  tspan = (0.0,float(l))\n  prob = ODEProblem(sir_ode!,\n          u0,\n          tspan,\n          p)\n  sol = solve(prob,\n              Tsit5(),\n              saveat = 1.0)\n  sol_C = Array(sol)[4,:] # Cumulative cases\n  sol_X = sol_C[2:end] - sol_C[1:(end-1)]\n  l = length(y)\n  for i in 1:l\n    y[i] ~ Poisson(sol_X[i])\n  end\nend;\n\n\node_nuts = sample(bayes_sir(Y),NUTS(0.65),10000);\n\n\ndescribe(ode_nuts)\n\n\nplot(ode_nuts)\n\n\nposterior = DataFrame(ode_nuts);\n\n\nhistogram2d(posterior[!,:β],posterior[!,:i₀],\n                bins=80,\n                xlabel=\"β\",\n                ylab=\"i₀\",\n                ylim=[0.006,0.016],\n                xlim=[0.045,0.055],\n                legend=false)\nplot!([0.05,0.05],[0.0,0.01])\nplot!([0.0,0.05],[0.01,0.01])\n\n\nfunction predict(y,chain)\n    # Length of data\n    l = length(y)\n    # Length of chain\n    m = length(chain)\n    # Choose random\n    idx = sample(1:m)\n    i₀ = chain[:i₀][idx]\n    β = chain[:β][idx]\n    I = i₀*1000.0\n    u0=[1000.0-I,I,0.0,0.0]\n    p=[β,10.0,0.25]\n    tspan = (0.0,float(l))\n    prob = ODEProblem(sir_ode!,\n            u0,\n            tspan,\n            p)\n    sol = solve(prob,\n                Tsit5(),\n                saveat = 1.0)\n    out = Array(sol)\n    sol_X = [0.0; out[4,2:end] - out[4,1:(end-1)]]\n    hcat(sol_ode.t,out',sol_X)\nend;\n\n\nXp = []\nfor i in 1:10\n    pred = predict(Y,ode_nuts)\n    push!(Xp,pred[2:end,6])\nend\n\n\nscatter(obstimes,Y,legend=false)\nplot!(obstimes,Xp,legend=false)\n\n", "meta": {"hexsha": "54b4404fe25e958f7e8982ff7b54e23e3654fca5", "size": 2490, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_turing/ode_turing.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 126, "max_stars_repo_stars_event_min_datetime": "2020-04-29T08:41:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:42:53.000Z", "max_issues_repo_path": "script/ode_turing/ode_turing.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2020-04-29T11:44:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:45:15.000Z", "max_forks_repo_path": "script/ode_turing/ode_turing.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2020-04-29T08:01:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T16:55:08.000Z", "avg_line_length": 18.0434782609, "max_line_length": 50, "alphanum_fraction": 0.537751004, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7695940739564564}}
{"text": "\"\"\"\n    value_at_risk(returns, confidence, method; multiplier=1.0)\n\nComputes the Value-at-Risk (VaR) for a given significance level `α` based on the chosen estimation method. The VaR value represents the maximum expected loss at a certain significance level `α`. For a more tail-risk focused measure, see `expected_shortfall`.\n\n# Arguments\n- `returns`:     Vector of asset returns.\n- `α`:           Significance level, e.g. use `0.05` for 95% confidence, or `0.01` for 99% confidence.\n- `method`:      Distribution estimation method: `:historical`, `:gaussian` or `:cornish_fisher`.\n- `multiplier`:  Optional scalar multiplier, i.e. use `12` to annualize monthly returns, and use `252` to annualize daily returns.\n\n# Methods\n- `:historical`:        Historical based on empirical distribution of returns.\n- `:gaussian`:          Gaussian distribution based on parametric fit (mean, variance).\n- `:cornish_fisher`:    Cornish-Fisher based on Gaussian parametric distribution fit adjusted for third and fourth moments (skewness, kurtosis). Cornish-Fisher expansion aims to approximate the quantile of a true distribution by using higher moments (skewness and kurtosis) of that distribution to adjust for its non-normality. See https://thema.u-cergy.fr/IMG/pdf/2017-21.pdf for details.\n\n# Sources\n- Favre, Laurent and Galeano, Jose-Antonio (2002). Mean-Modified Value-at-Risk Optimization with Hedge Funds. Journal of Alternative Investment.\n- Amédée-Manesme, Charles-Olivier and Barthélémy, Fabrice and Maillard, Didier (2017). Computation of the Corrected Cornish–Fisher Expansion using the Response Surface Methodology: Application to VaR and CVaR. THEMA Working Paper n°2017-21, Université de Cergy-Pontoise, France.\n\"\"\"\nfunction value_at_risk(returns, α, method::Symbol; multiplier=1.0)\n    if method == :historical\n        # empirical quantile for VaR estimation\n        return quantile(returns, α) * sqrt(multiplier)\n    elseif method == :gaussian\n        # parametric Gaussian distribution fit\n        μ = mean(returns)\n        σ = std(returns; corrected=false)\n        return quantile(Normal(μ, σ), α)\n    elseif method == :cornish_fisher\n        # third/fourth moment adjusted Gaussian distribution fit\n        # http://www.diva-portal.org/smash/get/diva2:442078/FULLTEXT01.pdf\n        # https://papers.ssrn.com/sol3/papers.cfm?abstract_id=1024151\n        q = quantile(Normal(), α)\n        S = skewness(returns)\n        K = kurtosis(returns; method=:excess)\n        z = q + 1/6*(q^2-1)S + 1/24*(q^3-3q)*K - 1/36*(2q^3-5q)*S^2\n        μ = mean(returns)\n        σ = std(returns; corrected=false)\n        return (μ + z*σ) * sqrt(multiplier)\n    end\n\n    throw(ArgumentError(\"Passed method parameter '$(method)' is invalid, must be one of :historical, :gaussian, :cornish_fisher.\"))\nend\n", "meta": {"hexsha": "48048fb1f02fad758be6446462cd1189a91ab740", "size": 2789, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/value_at_risk.jl", "max_stars_repo_name": "rbeeli/RiskPerf.jl", "max_stars_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-07T19:19:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T19:19:09.000Z", "max_issues_repo_path": "src/value_at_risk.jl", "max_issues_repo_name": "rbeeli/RiskPerf.jl", "max_issues_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/value_at_risk.jl", "max_forks_repo_name": "rbeeli/RiskPerf.jl", "max_forks_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.9777777778, "max_line_length": 389, "alphanum_fraction": 0.7102904267, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7695781671679592}}
{"text": "\"\"\"\n   DiscretizeUniformWidth(alg::Symbol)\nIf `nbins` is a symbol, automatically determine the number of bins to use\n\"\"\"\nstruct DiscretizeUniformWidth <: DiscretizationAlgorithm\n    nbins::Union{Int,Symbol}\nend\n\nfunction get_nbins(alg::Symbol, data::AbstractArray{N}) where {N<:Real}\n\n    n = length(data)\n\n    if alg == :sqrt\n        # Square root (of data size) estimator, used by Excel and other programs for its speed and simplicity.\n        nbins = ceil(Int, sqrt(n))\n    elseif alg == :sturges\n        # R’s default method, only accounts for data size.\n        # Only optimal for gaussian data and underestimates number of bins for large non-gaussian datasets.\n        # It implicitly bases the bin sizes on the range of the data and can perform poorly if n < 30,\n        # because the number of bins will be small—less than seven—and unlikely to show trends in the data well.\n        # It may also perform poorly if the data are not normally distributed.\n        nbins = ceil(Int, log(2,n)) + 1\n    elseif alg == :rice\n        # Estimator does not take variability into account, only data size. Commonly overestimates number of bins required.\n        nbins = ceil(Int, 2cbrt(n))\n    elseif alg == :doane\n        # An improved version of Sturges’ estimator that works better with non-normal datasets.\n        g₁ = moment(data, 3)\n        σ = sqrt((6*(n-2))/((n+1)*(n+3)))\n        nbins = ceil(Int, 1 + log(2,n) + log(2, 1+abs(g₁)/σ))\n    elseif alg == :scott\n        # Less robust estimator that that takes into account data variability and data size.\n        σ = std(data)\n        binwidth = 3.5σ/cbrt(n)\n        lo, hi = extrema(data)\n        nbins = ceil(Int, (hi - lo)/binwidth)\n    elseif alg == :fd # Freedman Diaconis Estimator\n        # Robust (resilient to outliers) estimator that takes into account data variability and data size\n        binwidth = 2iqr(data)/cbrt(n)\n        lo, hi = extrema(data)\n        nbins = ceil(Int, (hi - lo)/binwidth)\n    else # alg == :auto\n        # Maximum of the ‘sturges’ and ‘fd’ estimators. Provides good all round performance\n\n        binwidth = 2iqr(data)/cbrt(n)\n        lo, hi = extrema(data)\n        nbins_fd = ceil(Int, (hi - lo)/binwidth)\n        nbins_sturges = ceil(Int, log(2,n)) + 1\n        nbins = max(nbins_fd, nbins_sturges)\n    end\n\n    nbins\nend\n\nfunction binedges(alg::DiscretizeUniformWidth, data::AbstractArray{N}) where {N<:AbstractFloat}\n    lo, hi = extrema(data)\n    @assert(hi > lo)\n\n    nbins = (isa(alg.nbins, Symbol) ? get_nbins(alg.nbins, data) : alg.nbins)::Int\n\n    convert(Vector{N}, collect(range(lo, stop=hi, length=nbins+1)))\nend\nfunction binedges(alg::DiscretizeUniformWidth, data::AbstractArray{N}) where {N<:Integer}\n    lo, hi = extrema(data)\n    @assert(hi > lo)\n    collect(range(lo, stop=hi, length=alg.nbins+1))\nend", "meta": {"hexsha": "fea26dbaab9d61d938d1055387614d30f7eff67c", "size": 2808, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/disc_uniformwidth.jl", "max_stars_repo_name": "stevengj/Discretizers.jl", "max_stars_repo_head_hexsha": "19aebfd4113b7a55942ef9200a1815133606559c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2015-05-09T21:38:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:51:11.000Z", "max_issues_repo_path": "src/disc_uniformwidth.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Discretizers.jl-6e83dbb3-75ca-525b-8ae2-3751f0dd50b4", "max_issues_repo_head_hexsha": "e7df5b8be570df74bfa4338637712a0e81ee0b46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2015-03-19T21:35:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T03:07:35.000Z", "max_forks_repo_path": "src/disc_uniformwidth.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Discretizers.jl-6e83dbb3-75ca-525b-8ae2-3751f0dd50b4", "max_forks_repo_head_hexsha": "e7df5b8be570df74bfa4338637712a0e81ee0b46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2016-03-30T14:13:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T22:34:15.000Z", "avg_line_length": 41.9104477612, "max_line_length": 123, "alphanum_fraction": 0.6513532764, "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.7695781636281785}}
{"text": "import Base.:+\nimport Base.:*\n\n\nexport Biquaternion\nexport getrotation\nexport gettranslation\n\n\n\"\"\"\n    Represents a bi-quaternion for describing rotation and translation in a unified way.\n\nfields: real and dual.\n\"\"\"\nstruct Biquaternion\n    real::Quaternion\n    dual::Quaternion\n    Biquaternion(qr::Quaternion, qd::Quaternion) = new(qr, qd)\n    Biquaternion(q::Quaternion, t::ℝ³) = begin\n        qr = normalize(q)\n        qd = 0.5 * Quaternion([0; vec(t)]) * qr\n        new(qr, qd)\n    end\nend\n\n\n\"\"\"\n    show(b)\n\nPrint a string representation of the given Biquaternion `b`.\n\"\"\"\nBase.show(io::IO, q::Biquaternion) = print(io, \"$(q.real) + $(q.dual)𝜺\")\n\n\n\"\"\"\n    Biquaternion(q)\n\nConstruct a Biquaternion with the given Biquaternion `q` and also normalize.\n\"\"\"\nBiquaternion(q::Biquaternion) = begin\n    q̂ = normalize(q)\n    Biquaternion(q̂.real, q̂.dual)\nend\n\n\n\"\"\"\n    Biquaternion(rotation)\n\nConstruct a Biquaternion with the given Quaternion `rotation` and also normalize.\n\"\"\"\nBiquaternion(rotation::Quaternion) = Biquaternion(normalize(rotation), ℝ³(0, 0, 0))\n\n\n\"\"\"\n    Biquaternion(translation)\n\nConstruct a Biquaternion with the given ℝ³ `translation`.\n\"\"\"\nBiquaternion(translation::ℝ³) = Biquaternion(Quaternion(1, 0, 0, 0), translation)\n\n\nvec(q::Biquaternion) = [vec(q.real); vec(q.dual)]\n\n\n+(q₁::Biquaternion, q₂::Biquaternion) = Biquaternion(q₁.real + q₂.real, q₁.dual + q₂.dual)\n-(q₁::Biquaternion, q₂::Biquaternion) = Biquaternion(q₁.real - q₂.real, q₁.dual - q₂.dual)\n*(q₁::Biquaternion, q₂::Biquaternion) = Biquaternion(q₁.real * q₂.real,\n                                                     q₁.real * q₂.dual + q₁.dual * q₂.real)\n*(q::Biquaternion, λ::Real) = Biquaternion(λ * q.real, λ * q.dual)\n*(λ::Real, q::Biquaternion) = q * λ\nBase.conj(q::Biquaternion) = Biquaternion(conj(q.real), conj(q.dual))\nnorm(q::Biquaternion) = begin\n    qrnorm = norm(q.real)\n    Q = (conj(q.real) * q.dual + q.real * conj(q.dual)) * (1 / 2qrnorm)\n    scalar = vec(Q)[1]\n    sqrt(qrnorm^2 + scalar^2)\nend\nnormalize(q::Biquaternion) = begin\n    magnitude = norm(q)\n    @assert(magnitude > 1e-5, \"The magnitude is almost equal to zero, too small.\")\n    q * (1 / magnitude)\nend\ngetrotation(q::Biquaternion) = q.real\ngettranslation(q::Biquaternion) = ℝ³(vec(2q.dual * conj(q.real))[2:4])\n\nBase.isapprox(q1::Biquaternion, q2::Biquaternion) = isapprox(q1.real, q2.real) &&\n                                                    isapprox(q1.dual, q2.dual)\n", "meta": {"hexsha": "07ae425d251d1d7d1fe37e046ef9bb9d68894ea6", "size": 2442, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geometry/biquaternions.jl", "max_stars_repo_name": "SimonDanisch/Porta.jl", "max_stars_repo_head_hexsha": "70a5b6586b74f5d76d3add8c9f305071dea13b6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2020-03-28T05:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T22:16:31.000Z", "max_issues_repo_path": "src/geometry/biquaternions.jl", "max_issues_repo_name": "iamazadi/Porta", "max_issues_repo_head_hexsha": "73a97d879d06a1466ff3b966b2ea8e8a846d4c78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-15T12:36:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-15T12:36:59.000Z", "max_forks_repo_path": "src/geometry/biquaternions.jl", "max_forks_repo_name": "iamazadi/Porta", "max_forks_repo_head_hexsha": "73a97d879d06a1466ff3b966b2ea8e8a846d4c78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-09-13T20:28:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T03:31:59.000Z", "avg_line_length": 27.75, "max_line_length": 91, "alphanum_fraction": 0.6457821458, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294984, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.769578162587623}}
{"text": "\r\n\r\nfunction derivative(ex::Constant, wrt::Variable)\r\n    return Constant( default_variable_value() )\r\nend\r\n\r\nfunction derivative(ex::Variable, wrt::Variable)\r\n    T   = typeof(wrt.value)\r\n    val = default_variable_value()\r\n    if ex == wrt\r\n        val = one(T)\r\n    end\r\n    return Constant(val)\r\nend\r\n\r\nfunction derivative(ex::SymbolicExpression, wrt::Variable)\r\n\r\n    if is_unary_operator(ex.head)\r\n        der_ex = __derivative_unary(ex, wrt)\r\n    elseif is_binary_operator(ex.head)\r\n        der_ex = __derivative_binary(ex, wrt)\r\n    else\r\n        error(\"not implemented yet\")\r\n        # er_ex = __derivative_k_ary(ex, wrt)\r\n    end\r\n\r\n    return der_ex\r\nend\r\n\r\nfunction __derivative_unary(ex::SymbolicExpression, wrt::Variable)\r\n\r\n    # dy/dz = sin(x)\r\n    # dy/dz = cos(x) * dx/dz\r\n    #\r\n    # derivative of the arguments\r\n    # derivative of the function itself\r\n\r\n    arg = ex.args[1]\r\n    der_arg = derivative(arg, wrt)\r\n\r\n    sym = ex.head\r\n\r\n    if is_sin_operator(sym)\r\n        der_ex = der_arg * cos(arg)\r\n\r\n    elseif is_cos_operator(sym)\r\n        der_ex = -der_arg * sin(arg)\r\n\r\n    elseif is_tan_operator(sym)\r\n        der_ex = der_arg / (cos(arg) * cos(args))\r\n\r\n    elseif is_sqrt_operator(sym)\r\n        der_ex = der_arg / sqrt(arg)\r\n\r\n    elseif is_cbrt_operator(sym)\r\n        der_ex = der_arg * 1/3 * arg^(-2/3)\r\n\r\n    elseif is_exp_operator(sym)\r\n        der_ex = der_arg * exp(arg)\r\n\r\n    elseif is_log_operator(sym)\r\n        der_ex = der_arg / arg\r\n\r\n    elseif is_log2_operator(sym)\r\n        der_ex = der_arg / (arg * log(2))\r\n\r\n    elseif is_log10_operator(sym)\r\n        der_ex = der_arg / (arg * log(10))\r\n\r\n    elseif is_abs_operator(sym)\r\n        der_ex = der_arg * sign(arg) \r\n\r\n    elseif is_sign_operator(sym)\r\n        der_ex = Constant(0.0)\r\n\r\n    else\r\n        error(\"not implemented yet\")\r\n    end\r\n\r\n\r\n    return der_ex\r\nend\r\n\r\n\r\n\r\nfunction __derivative_binary(ex::SymbolicExpression, wrt::Variable)\r\n\r\n    sym = ex.head\r\n\r\n    if is_plus_operator(sym) || is_product_operator(sym)\r\n        # der_ex = der_left_arg + der_right_arg\r\n        # der_ex = der_left_arg * right_arg + left_arg * der_right_arg\r\n\r\n        df(expr) = derivative(expr, wrt)\r\n        der_args = map(df, ex.args)\r\n\r\n        if is_plus_operator(sym)\r\n            return reduce(+, der_args)\r\n        end\r\n\r\n        L = length(ex.args)\r\n        if L == 2\r\n            left_arg      = ex.args[1]\r\n            right_arg     = ex.args[2]\r\n            der_left_arg  = der_args[1]\r\n            der_right_arg = der_args[2]\r\n\r\n            return der_left_arg * right_arg + left_arg * der_right_arg\r\n        else\r\n            der_ex = der_args[1] * reduce(*, ex.args[2:end])\r\n            for ii = 2:L\r\n                # left   = reduce(*, ex.args[1:ii-1])\r\n                # right  = reduce(*, ex.args[ii+1:end])\r\n                args      = [ex.args[1:ii-1]; der_args[ii]; ex.args[ii+1:end]]\r\n                left_expr = SymbolicExpression(:*, args...)\r\n                der_ex    = der_ex + left_expr # left * der_args[ii] * right\r\n            end\r\n            return der_ex\r\n        end\r\n    end\r\n\r\n    L = length(ex.args)\r\n    if is_minus_operator(sym) && L == 1\r\n        der_right_arg = derivative(ex.args[1], wrt)\r\n        der_ex = -der_right_arg\r\n        return der_ex\r\n    end\r\n\r\n\r\n    left_arg  = ex.args[1]\r\n    right_arg = ex.args[2]\r\n\r\n    der_left_arg  = derivative(left_arg, wrt)\r\n    der_right_arg = derivative(right_arg, wrt)\r\n\r\n    if is_minus_operator(sym)\r\n        der_ex = der_left_arg - der_right_arg\r\n\r\n    elseif is_divide_operator(sym)\r\n        der_ex = (der_left_arg * right_arg - left_arg * der_right_arg) / (right_arg * right_arg)\r\n\r\n    elseif is_power_operator(sym)\r\n        # most complicated expression\r\n        der_ex = ex * (der_left_arg * right_arg / left_arg + der_right_arg * log(left_arg))\r\n\r\n    else\r\n        error(\"not implemented yet\")\r\n    end\r\n\r\n    return der_ex\r\nend\r\n\r\n\r\n\r\n\r\nfunction gradient(\r\n    ex::S,\r\n    wrt_vec::A) where {\r\n        S <: Union{Constant, Variable, SymbolicExpression},\r\n        A <: AbstractArray}\r\n    \r\n    L = length(wrt_vec)\r\n    g = Vector{Any}(undef, L)\r\n\r\n    for ii = 1:L\r\n        g[ii] = symbolics.derivative(ex, wrt_vec[ii])\r\n    end\r\n\r\n    return g\r\nend\r\n\r\n\r\nfunction jacobian(\r\n    ex_vec::S,\r\n    wrt_vec::A) where {\r\n        S <: AbstractArray,\r\n        A <: AbstractArray}\r\n    \r\n    n_row = length(ex_vec)\r\n    n_col = length(wrt_vec)\r\n    jac   = Matrix{Any}(undef, n_row, n_col)\r\n\r\n    for ii = 1:n_row\r\n        ex = ex_vec[ii]\r\n        for jj = 1:n_col\r\n            jac[ii, jj] = symbolics.derivative(ex, wrt_vec[jj])\r\n        end\r\n    end\r\n\r\n    return jac\r\nend\r\n\r\n\r\n", "meta": {"hexsha": "76369d9593459b34cfa2ce7bdb2f06bcabaab44a", "size": 4653, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "symbolics/src/derivative.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "symbolics/src/derivative.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "symbolics/src/derivative.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9845360825, "max_line_length": 97, "alphanum_fraction": 0.5675908016, "num_tokens": 1208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308128813471, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7695781621013998}}
{"text": "module NewtonsMethod\n\ngreet() = print(\"Hello World!\")\n\nusing LinearAlgebra, ForwardDiff\n\nfunction fixedpointmap(f, f_prime, x_0; tolerance=1E-12, maxiter=1000)\n    # setup the algorithm\n#     x_old = iv\n    normdiff = Inf\n    iter = 1\n    if f(x_0) == 0\n        return (value = x_0, normdiff=0, iter=0)\n    end\n    while normdiff > tolerance && iter <= maxiter\n        x_new = x_0 - f(x_0)/f_prime(x_0) # use the passed in map\n        if norm(x_new - x_0) > tolerance && iter > 100\n            println(\"non-convergence \")\n            return #(value = nothing, normdiff=nothing, iter=iter)\n        end\n        normdiff = norm(x_new - x_0)\n        x_0 = x_new\n        iter = iter + 1\n    end\n    return (value = x_0, normdiff=normdiff, iter=iter) # A named tuple\nend\n\n\nD(f) = x -> ForwardDiff.derivative(f, x)\nfunction fixedpointmap(f, x_0; tolerance=1E-12, maxiter=1000)\n    f_prime = D(f)\n    if nothing == fixedpointmap(f, f_prime, x_0)\n        return\n    end\n    x_0, normdiff, iter = fixedpointmap(f, f_prime, x_0, tolerance=tolerance, maxiter=maxiter)\n    return (value = x_0, normdiff=normdiff, iter=iter)\nend\n\nexport fixedpointmap\n\nend # module\n", "meta": {"hexsha": "ef39c66434ea7fe39bd002b9a54f3f44810de869", "size": 1151, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NewtonsMethod.jl", "max_stars_repo_name": "PooyaFa/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "82bbfb6b93e6f9b17e8964d350d3fdad8e2acbfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NewtonsMethod.jl", "max_issues_repo_name": "PooyaFa/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "82bbfb6b93e6f9b17e8964d350d3fdad8e2acbfb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NewtonsMethod.jl", "max_forks_repo_name": "PooyaFa/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "82bbfb6b93e6f9b17e8964d350d3fdad8e2acbfb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4047619048, "max_line_length": 94, "alphanum_fraction": 0.6316246742, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7695640375771052}}
{"text": "# Multicollinearity Test for regression models:\r\n# see associated pdf and data file\r\n# overview of notes: \r\n# if doing regression, the coefficient of each predictor (indepedent) variable tells you how much on average the response changes\r\n# when the variable changes by a unit. however, when variables are corellated (they are not really independent) it makes inference harder\r\n\r\nusing RCall\r\nusing DataFrames\r\nusing CSV\r\nusing GLM\r\nusing Statistics\r\n\r\n# read the first 4 columns (not the columns with S)\r\ndf = CSV.read(\"multicollinearity_regression_models_data.csv\" , header=1, select=(i, name) -> i < 5 && return true) |> DataFrame#, select=(i, name) -> i < 5 && return true)\r\ninsertcols!(df, :pfat_weight => df.pfat .* df.weight) # create interaction term manually\r\n\r\nrmodel = lm(@formula(neck ~ pfat + weight + activity + pfat_weight), df) \r\n# lets calculate the Variance Inflation numbers\r\n# using r2 of the model, calculate VIF\r\n\r\nrmodel1 = lm(@formula(pfat ~  weight + activity + pfat_weight), df)\r\nrmodel2 = lm(@formula(weight ~ pfat + activity + pfat_weight), df)\r\nrmodel3 = lm(@formula(activity ~ pfat + weight + pfat_weight), df)\r\nrmodel4 = lm(@formula(pfat_weight ~ pfat + weight + activity), df)\r\nrmodels = (rmodel1, rmodel2, rmodel3, rmodel4)\r\nvifs = @. 1 / (1 - r2(rmodels))\r\n\r\n# node that for activity, VIF is 1.05 so this variable has no mulitcollinearity. \r\n# for the other ones, there seems to be definitely multicollinearity\r\n# first, let's remove the structural multicollinearity from the interaction term. \r\n# to do tht, we will first mean center the data. \r\n\r\n# there is a bug in Query that messes up the dataframe types and GLM can't read it anymore\r\n# https://discourse.julialang.org/t/query-jl-mutate-command-does-not-preserve-column-types/41231/4\r\n# aa = mean(df.pfat)::Float64\r\n# ab = mean(df.weight)::Float64\r\n# ac = mean(df.activity)::Float64\r\n# ad = mean(df.pfat_weight)::Float64\r\n# df_s = df |> @mutate(pfat_s .= _.pfat .- aa, \r\n#               weight_s .= _.weight .- ab, \r\n#               activity_s .= _.activity .- ac, \r\n#               pfat_weight_s .= _.pfat_weight .- ad) |> DataFrame\r\n             \r\n# equivalent linq\r\n# @from i in df begin\r\n# @select {i..., pfat_s = mean(df.pfat)}\r\n# @collect DataFrame\r\n# end\r\n\r\n# lets use standard method to add columns\r\ndf[!, :neck_s] .= mean(df.neck) .- df.neck \r\ndf[!, :pfat_s] .= mean(df.pfat) .- df.pfat \r\ndf[!, :weight_s] .= mean(df.weight) .- df.weight \r\ndf[!, :activity_s] .= mean(df.activity) .- df.activity \r\ndf[!, :pfat_weight_s] .=  df.pfat_s .* df.weight_s\r\n\r\nsmodel = lm(@formula(neck ~ pfat_s + weight_s + activity_s + pfat_weight_s), df) \r\n# lets calculate the Variance Inflation numbers\r\n# using r2 of the model, calculate VIF\r\nsmodel1 = lm(@formula(pfat_s ~  weight_s + activity_s + pfat_weight_s), df)\r\nsmodel2 = lm(@formula(weight_s ~ pfat_s + activity_s + pfat_weight_s), df)\r\nsmodel3 = lm(@formula(activity_s ~ pfat_s + weight_s + pfat_weight_s), df)\r\nsmodel4 = lm(@formula(pfat_weight_s ~ pfat_s + weight_s + activity_s), df)\r\nsmodels = (smodel1, smodel2, smodel3, smodel4)\r\nvifs = @. 1 / (1 - r2(smodels))\r\n# (3.323870441091722, 4.745648167219831, 1.0530047498114123, 1.9910631706191224) \r\n\r\n# you see now how small the VIFs have gotten just by removing the multicollinearity\r\n", "meta": {"hexsha": "ef45bab3b03f7f6c56c5f22b7eeca595b013d310", "size": 3278, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "multicollinearity/multicollinearity_regression_models.jl", "max_stars_repo_name": "affans/notebooks", "max_stars_repo_head_hexsha": "daf102cde8b99b8c48ef2434176b44ace2719d9d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "multicollinearity/multicollinearity_regression_models.jl", "max_issues_repo_name": "affans/notebooks", "max_issues_repo_head_hexsha": "daf102cde8b99b8c48ef2434176b44ace2719d9d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multicollinearity/multicollinearity_regression_models.jl", "max_forks_repo_name": "affans/notebooks", "max_forks_repo_head_hexsha": "daf102cde8b99b8c48ef2434176b44ace2719d9d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.5072463768, "max_line_length": 172, "alphanum_fraction": 0.69219036, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7695640354962596}}
{"text": "\n\"A `DomainPoint` is a point which is an element of a domain by construction.\"\nabstract type DomainPoint{T} end\n\nin(p::DomainPoint, d::Domain) = domain(p) == d || in(point(p), d)\n\n\n## Points on a sphere\n\n\"A point on the unit sphere.\"\nabstract type SpherePoint{T} <: DomainPoint{T} end\n\ndomain(p::SpherePoint{T}) where {T<:StaticTypes} = UnitSphere{T}()\ndomain(p::SpherePoint{T}) where {T<:AbstractVector} = UnitSphere{T}(length(point(p)))\n\n\"A point on the unit sphere represented by a standard Euclidean vector.\"\nstruct EuclideanSpherePoint{T} <: SpherePoint{T}\n    x   ::  T\nend\npoint(p::EuclideanSpherePoint) = p.x\n\n\n\"A point on the unit sphere represented in spherical coordinates.\"\nstruct SphericalCoordinate{T} <: SpherePoint{SVector{3,T}}\n    θ   ::  T   # inclination or polar angle\n    ϕ   ::  T   # azimuthal angle\nend\n\npoint(p::SphericalCoordinate) = SVector(sin(p.θ)*cos(p.ϕ), sin(p.θ)*sin(p.ϕ), cos(p.θ))\n", "meta": {"hexsha": "faa47f53936fd18ac7283a9f160ad25136ef30cf", "size": 917, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/applications/coordinates.jl", "max_stars_repo_name": "JuliaApproximation/DomainSets.jl", "max_stars_repo_head_hexsha": "5f3918304d3ca14284ca9330be158047c3d32db5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-10-27T21:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T08:22:43.000Z", "max_issues_repo_path": "src/applications/coordinates.jl", "max_issues_repo_name": "JuliaApproximation/DomainSets.jl", "max_issues_repo_head_hexsha": "5f3918304d3ca14284ca9330be158047c3d32db5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 76, "max_issues_repo_issues_event_min_datetime": "2018-10-26T08:52:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T12:50:39.000Z", "max_forks_repo_path": "src/applications/coordinates.jl", "max_forks_repo_name": "JuliaApproximation/Domains.jl", "max_forks_repo_head_hexsha": "cb578c2763e25184eac1026ac47b0b34e1b9028e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-10-28T13:02:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:51:20.000Z", "avg_line_length": 30.5666666667, "max_line_length": 87, "alphanum_fraction": 0.6968375136, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.946596665680527, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7694574991426035}}
{"text": "# ## Data\n\nimport CSV\n\nusing DataFrames\nusing TuringModels: project_root\n\npath = joinpath(project_root, \"data\", \"Kline.csv\")\ndf = CSV.read(path, DataFrame; delim=';')\ndf.log_pop = log.(df.population)\ndf.society = 1:nrow(df)\ndf\n\n# ## Model\n\nusing Turing\n\n@model function m12_6(total_tools, log_pop, society)\n    N = length(total_tools)\n\n    α ~ Normal(0, 10)\n    βp ~ Normal(0, 1)\n\n    σ_society ~ truncated(Cauchy(0, 1), 0, Inf)\n\n    N_society = length(unique(society)) ## 10\n\n    α_society ~ filldist(Normal(0, σ_society), N_society)\n\n    for i in 1:N\n        λ = exp(α + α_society[society[i]] + βp*log_pop[i])\n        total_tools[i] ~ Poisson(λ)\n    end\nend;\n\n# ## Output\n\nchains = sample(\n    m12_6(df.total_tools, df.log_pop, df.society), \n    NUTS(0.95), \n    1000\n)\n\n# \\defaultoutput{}\n\n# ## Original output\n\nm12_6rethinking = \"\n              Mean StdDev lower 0.89 upper 0.89 n_eff Rhat\na              1.11   0.75      -0.05       2.24  1256    1\nbp             0.26   0.08       0.13       0.38  1276    1\na_society[1]  -0.20   0.24      -0.57       0.16  2389    1\na_society[2]   0.04   0.21      -0.29       0.38  2220    1\na_society[3]  -0.05   0.19      -0.36       0.25  3018    1\na_society[4]   0.32   0.18       0.01       0.60  2153    1\na_society[5]   0.04   0.18      -0.22       0.33  3196    1\na_society[6]  -0.32   0.21      -0.62       0.02  2574    1\na_society[7]   0.14   0.17      -0.13       0.40  2751    1\na_society[8]  -0.18   0.19      -0.46       0.12  2952    1\na_society[9]   0.27   0.17      -0.02       0.52  2540    1\na_society[10] -0.10   0.30      -0.52       0.37  1433    1\nsigma_society  0.31   0.13       0.11       0.47  1345    1\n\";\n", "meta": {"hexsha": "250c19ef96ba7d526a6d38e2f13317d530cbf882", "size": 1677, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/over-dispersed-oceanic.jl", "max_stars_repo_name": "BobinMathew/TuringModels.jl", "max_stars_repo_head_hexsha": "a345fcfd427c4fb1f9479654f10f1280f1e4bf2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/over-dispersed-oceanic.jl", "max_issues_repo_name": "BobinMathew/TuringModels.jl", "max_issues_repo_head_hexsha": "a345fcfd427c4fb1f9479654f10f1280f1e4bf2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/over-dispersed-oceanic.jl", "max_forks_repo_name": "BobinMathew/TuringModels.jl", "max_forks_repo_head_hexsha": "a345fcfd427c4fb1f9479654f10f1280f1e4bf2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.203125, "max_line_length": 59, "alphanum_fraction": 0.5408467501, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870765, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7694574874934615}}
{"text": "#!/usr/bin/env julia\n\n#=\n# data should be sorted and works by divide and conquer\n# improved variant of binary search for equally distributed data\n# it tries probing the position\n#\n# Interpolation search finds particular item by computing probe position.\n# Start from middle of list. If not a match, divide list using probe position and find new middle.\n# Do binary search in 2 blocks.\n# Repeat\n#\n# run-time complexity is O(log log n)\n=#\n\nfunction interpolation_search(search_for, data_array, low=1, high=-1)\n  if high == -1\n    high = length(data_array)\n  end\n  if high < low\n    return -1\n  end\n\n  ## calculation of probe position\n  mid = Int(floor(\n          (\n           low +\n           ((high - low) / (data_array[high] - data_array[low])) *\n           (search_for - data_array[low])\n          )\n        ))\n  if mid < low\n    return -1\n  end\n\n  if data_array[mid] == search_for\n    return mid\n  end\n\n  if data_array[mid] < search_for\n    return interpolation_search(search_for, data_array, mid+1, high)\n  else\n    return interpolation_search(search_for, data_array, low, mid-1)\n  end\n\n  -1\nend\n\n     ## 1   2   3   4   5   6   7   8   9   10\ndata = [10, 11, 12, 22, 24, 27, 34, 47, 56, 67]\n\n@time println(\"at index: \", interpolation_search(47, data))\n@time println(\"at index: \", interpolation_search(12, data))\n@time println(\"at index: \", interpolation_search(7, data))\n@time println(\"at index: \", interpolation_search(67, data))\n@time println(\"at index: \", interpolation_search(34, data))\n", "meta": {"hexsha": "dcf080a9349f22278a3d3c6ed23420bd0e2f6bd0", "size": 1495, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "talks-articles/reference/algorithms/interpolation-search.jl", "max_stars_repo_name": "abhishekkr/tutorials_as_code", "max_stars_repo_head_hexsha": "f355dc62a5025b710ac6d4a6ac2f9610265fad54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2015-02-01T23:16:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T16:50:48.000Z", "max_issues_repo_path": "talks-articles/reference/algorithms/interpolation-search.jl", "max_issues_repo_name": "abhishekkr/tutorials_as_code", "max_issues_repo_head_hexsha": "f355dc62a5025b710ac6d4a6ac2f9610265fad54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-02T04:55:48.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-14T10:51:11.000Z", "max_forks_repo_path": "talks-articles/reference/algorithms/interpolation-search.jl", "max_forks_repo_name": "abhishekkr/tutorials_as_code", "max_forks_repo_head_hexsha": "f355dc62a5025b710ac6d4a6ac2f9610265fad54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2015-03-02T08:09:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:25:41.000Z", "avg_line_length": 26.2280701754, "max_line_length": 98, "alphanum_fraction": 0.6595317726, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.769371513768013}}
{"text": "#\n#--------------------------------------#\nexport gordonHall\n#--------------------------------------#\n\"\"\"\n Transfinite interpolation\n\"\"\"\nfunction gordonHall(xrm,xrp,xsm,xsp,yrm,yrp,ysm,ysp,zr,zs)\n\nze  = [-1,1]\nJer = interpMat(zr,ze)\nJes = interpMat(zs,ze)\n\nxv = [xrm[1]   xrp[1]\n      xrm[end] xrp[end]]\n\nyv = [yrm[1]   yrp[1]\n      yrm[end] yrp[end]]\n\nxv = ABu(Jes,Jer,xv)\nyv = ABu(Jes,Jer,yv)\n\n#display(mesh(xv,yv,0*xv,0,90))\n\nx = ABu([],Jer,vcat(xrm',xrp')) .+ ABu(Jes,[],hcat(xsm,xsp)) .- xv\ny = ABu([],Jer,vcat(yrm',yrp')) .+ ABu(Jes,[],hcat(ysm,ysp)) .- yv\n\n#display(mesh(x,y,0*x,0,90))\n\nreturn x,y\nend\n#--------------------------------------#\nexport annulus\n#--------------------------------------#\n\"\"\"\n Convert (r,s) in [-1,1]^2 grid\n internal/external radii r0,r1,\n and angular extent span\n\"\"\"\nfunction annulus(r,s;r0=0.5,r1=1.0,span=2pi)\n\nR  = @. (r1-r0)/2*(r+1) + r0\nth = @. span   /2*(s+1) + 0.\n\nx = @. R * cos(th)\ny = @. R * sin(th)\n\nreturn x,y\nend\n#--------------------------------------#\n#\"\"\"\n# Transforms [-1,1]^2 to annulus with\n# internal/external radii r0,r1,\n# and angular extent span\n#\"\"\"\n#function annulus(r0,r1,span,zr,zs)\n#\n#ze  = [-1.,1.]\n#Jer = interpMat(zr,ze);\n#Jes = interpMat(zs,ze);\n#\n#xrp = 0*zs;\n#yrp = Jes*[-r0,-r1];\n#\n#spn = span-pi/2;\n#\n#xrm = Jes*[r0;r1]*cos(spn);\n#yrm = Jes*[r0;r1]*sin(spn);\n#\n#as = Jer*[-pi/2,spn];\n#xsm = r0 .* cos.(as);\n#ysm = r0 .* sin.(as);\n#\n#xsp = r1 .* cos.(as);\n#ysp = r1 .* sin.(as);\n#\n#pl=plot(xsm,ysm ,label=\"sm\");\n#pl=plot!(xsp,ysp,label=\"sp\");\n#pl=plot!(xrm,yrm,label=\"rm\");\n#pl=plot!(xrp,yrp,label=\"rp\");\n#pl=xlabel!(\"x\")\n#pl=ylabel!(\"y\")\n#display(pl)\n#\n#return gordonHall(xrm,xrp,xsm,xsp,yrm,yrp,ysm,ysp,zr,zs)\n#end\n#--------------------------------------#\n", "meta": {"hexsha": "741affa2ce0b97b69b8ac51172e6c24d3e63e011", "size": 1729, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geom.jl", "max_stars_repo_name": "vpuri3/SpectralElements.jl", "max_stars_repo_head_hexsha": "276bdd7fdfc67796fef64a20e0411044da70928b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-29T01:52:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T02:05:59.000Z", "max_issues_repo_path": "src/geom.jl", "max_issues_repo_name": "vpuri3/SpectralElements.jl", "max_issues_repo_head_hexsha": "276bdd7fdfc67796fef64a20e0411044da70928b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-08-16T19:39:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-17T16:52:52.000Z", "max_forks_repo_path": "src/geom.jl", "max_forks_repo_name": "vpuri3/SEM.jl", "max_forks_repo_head_hexsha": "128b7a8aa48cdc8a981c3668199e856240c04e13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6477272727, "max_line_length": 66, "alphanum_fraction": 0.4962406015, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.769371511474421}}
{"text": "using ODE\n\n\n# Definition of parameters\nconst a = 1.0\nconst b = 0.1\nconst c = 1.5\nconst d = 0.75\n\n\nfunction diffeq(t,u)\n    du = similar(u)\n    # u1: rabbits\n    # u2: foxes\n    du[1] = a*u[1] - b*u[1]*u[2]\n    du[2] = -c*u[2] + d*b*u[1]*u[2]\n    \n    return du\n\nend\n\n# Simulation time\nconst t = collect(range(0.0,stop=18.0,length=1000))\n\n\n# Initial condition\nu0 = zeros(2)\nu0[1] = 10\nu0[2] = 5\n\n\n# Solve ODE\n(sol_t,sol_u) = ode45(diffeq,u0,tpoints=:specified)\n\n\n#= Visualization of Results\n\nusing PyPlot\nplot(sol_t,sol_u)\nshow()\n\n=#", "meta": {"hexsha": "6e7a549a9c666d191294b51dc373d545ef33ea2f", "size": 532, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/test_ODE.jl", "max_stars_repo_name": "camrepo/ode_solver", "max_stars_repo_head_hexsha": "facb6d026440db51b3052e7a6b88184d749b5be0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-07T10:33:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T17:29:25.000Z", "max_issues_repo_path": "julia/test_ODE.jl", "max_issues_repo_name": "camrepo/ode_solver", "max_issues_repo_head_hexsha": "facb6d026440db51b3052e7a6b88184d749b5be0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/test_ODE.jl", "max_forks_repo_name": "camrepo/ode_solver", "max_forks_repo_head_hexsha": "facb6d026440db51b3052e7a6b88184d749b5be0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-15T02:33:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T02:33:12.000Z", "avg_line_length": 12.6666666667, "max_line_length": 51, "alphanum_fraction": 0.6033834586, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957912273285902, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7693700371119077}}
{"text": "### Notation\n#   small letters => vectors\n# capital letters => matrices\n\nfunction build_A(k, u, η, D, D2, ϕ, params)\n    \n    a = params.a\n    N = params.Nϕ\n    g = params.g\n    \n    k2 = k^2\n    ik = 1im*k    \n\n    h = η .+ params.H\n    axcos = a * cos.(ϕ)\n    \n           D = D/a\n       IxCos = diagm(0=>axcos)\n       IoCos = diagm(0=>1 ./ axcos)\n    TwoΩxSin = diagm(0=>params.TwoΩ*sin.(ϕ));\n       UoCos = diagm(0=>u./axcos)\n       UxTan = diagm(0=>u./axcos.*sin.(ϕ))\n       HoCos = diagm(0=>h./axcos)\n       HxCos = diagm(0=>h.*axcos)\n          dU = diagm(0=>D*u);\n          dH = diagm(0=>D*h);\n\n    # Form 1L-RSW Matrix\n    #   [u1, v1, h1]\n\n     U = diagm(0 => u)\n     H = diagm(0 => h)\n     F = diagm(0 => params.TwoΩ .+ 0*ϕ)\n    dU = diagm(0 => D*u)\n    \n    A = [                UoCos             (-TwoΩxSin - UxTan + dU)[:, 2:N]    g*IoCos;\n          -(TwoΩxSin + 2*UxTan)[2:N,:]/k2                     UoCos[2:N,2:N]  -g/k2*D[2:N,:];\n                         HoCos                  (IxCos * D * HxCos)[:, 2:N]     UoCos];\n    return A\nend\n\n", "meta": {"hexsha": "d1c3470407ff4b74b7db8cf0b1c81b1b76bc7f6f", "size": 1052, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ShallowWater/Julia/Spherical/build_A.jl", "max_stars_repo_name": "francispoulin/Linear-Stability-Calculators", "max_stars_repo_head_hexsha": "2e1cf66b0bed95f24ddfeea09ec7d66956cdce64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-22T20:00:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T17:19:18.000Z", "max_issues_repo_path": "ShallowWater/Julia/Spherical/build_A.jl", "max_issues_repo_name": "francispoulin/Linear-Stability-Calculators", "max_issues_repo_head_hexsha": "2e1cf66b0bed95f24ddfeea09ec7d66956cdce64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-27T16:14:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-27T16:14:05.000Z", "max_forks_repo_path": "ShallowWater/Julia/Spherical/build_A.jl", "max_forks_repo_name": "francispoulin/Linear-Stability-Calculators", "max_forks_repo_head_hexsha": "2e1cf66b0bed95f24ddfeea09ec7d66956cdce64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-05-18T11:05:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T18:57:19.000Z", "avg_line_length": 25.0476190476, "max_line_length": 93, "alphanum_fraction": 0.4258555133, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828602, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7693700284123013}}
{"text": "123.4 + 234.5     # This is a comment, ignored by Julia\n\n7 / 3             # Integer division returns floating point\n\n7 ÷ 3             # Truncated integer division (type \\div and press tab)\n\n7 % 3             # Remainder\n\n2^7 - 4           # All integer expression which returns an integer\n\n3 * (4.2 - 9.7)   # Use parentheses to control the order of operations\n\n# We will later learn why the previous result is not exact\n\n5.6e7 ^ 0.1       # Scientific notation, means 5.6⋅10⁷ (not e⁷)\n\n1 + 2\n34 / 3\n\nprintln(1 + 2.1)\nprintln(\"The result is \", -123 / 1000000)\n34 / 3; # The output will not be displayed\n\ntypeof(1.23)\n\ntypeof(-745)\n\ntypeof(1e20)\n\nprintln(typemin(Int64))\nprintln(typemax(Int64))\nprintln(typemin(Int128))\nprintln(typemax(Int128))\n\n\n1000^7\n\nInt128(1000)^7\n", "meta": {"hexsha": "89e6ce8a369327feb0c99ea93b7018af6a460143", "size": 771, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Introduction/Julia_As_A_Calculator.jl", "max_stars_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_stars_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "textbook/_build/jupyter_execute/content/Introduction/Julia_As_A_Calculator.jl", "max_issues_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_issues_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "textbook/_build/jupyter_execute/content/Introduction/Julia_As_A_Calculator.jl", "max_forks_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_forks_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7692307692, "max_line_length": 72, "alphanum_fraction": 0.6485084306, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7693373901918947}}
{"text": "\"\"\"\n```\nshapeFunction(::LinearQuadrangle3D, x, y, z)\n```\nComputes the linear shape functions `N[1:8]` for an `(x, y, z)` point on a 3D linear quadrangle.\n\"\"\"\nfunction shapeFunction(::LinearQuadrangle3D, x, y, z)\n    # N[n](x,y,z) := shape function n.\n    omx = 1 - x\n    omy = 1 - y\n    omz = 1 - z\n    opx = 1 + x\n    opy = 1 + y\n    opz = 1 + z\n\n    N =\n        SVector{8, typeof(x)}(\n            omx * omy * omz,\n            opx * omy * omz,\n            opx * opy * omz,\n            omx * opy * omz,\n            omx * omy * opz,\n            opx * omy * opz,\n            opx * opy * opz,\n            omx * opy * opz,\n        ) / 8\n\n    return N\nend\n\"\"\"\n```\nshapeFunction(::LinearQuadrangle3D, x::AbstractVector, y::AbstractVector, z::AbstractVector)\n```\nComputes the linear shape functions `N[1:8][p]` for `(x, y, z)` point `p` on a 3D linear quadrangle.\n\"\"\"\nfunction shapeFunction(\n    ::LinearQuadrangle3D,\n    x::AbstractVector,\n    y::AbstractVector,\n    z::AbstractVector,\n)\n    numPoints = length(x)\n    @assert numPoints == length(y) == length(z)\n    xType = eltype(x)\n    # N[n, p](x_vec,y_vec,z_vec) := shape function n for point p.\n    N = Array{SVector{8, xType}}(undef, numPoints)\n\n    @inbounds @simd for i in eachindex(x)\n        omx = 1 - x[i]\n        omy = 1 - y[i]\n        omz = 1 - z[i]\n        opx = 1 + x[i]\n        opy = 1 + y[i]\n        opz = 1 + z[i]\n\n        N[i] =\n            SVector{8, xType}(\n                omx * omy * omz,\n                opx * omy * omz,\n                opx * opy * omz,\n                omx * opy * omz,\n                omx * omy * opz,\n                opx * omy * opz,\n                opx * opy * opz,\n                omx * opy * opz,\n            ) / 8\n    end\n\n    return N\nend\n\n\"\"\"\n```\nshapeFunctionDeriv(shape<:AbstractShapeFunction, x, y, z)\n```\nComputes the derivatives of the linear shape functions `N[1:3, 1:8]` for an `(x, y, z)` point on a 3D linear quadrangle.\n\n## Returns\n```\ndNdS[x, n](x,y,z) := x'th derivative of shape function n.\n```\n\"\"\"\nfunction shapeFunctionDeriv(::LinearQuadrangle3D, x, y, z)\n    # dNdS[x, n](x,y,z) := x'th derivative of shape function n.\n    omx = 1 - x\n    omy = 1 - y\n    omz = 1 - z\n    opx = 1 + x\n    opy = 1 + y\n    opz = 1 + z\n\n    dNdS =\n        SMatrix{3, 8, typeof(x)}(\n            -omy * omz,\n            -omx * omz,\n            -omx * omy,\n            omy * omz,\n            -opx * omz,\n            -opx * omy,\n            opy * omz,\n            opx * omz,\n            -opx * opy,\n            -opy * omz,\n            omx * omz,\n            -omx * opy,\n            -omy * opz,\n            -omx * opz,\n            omx * omy,\n            omy * opz,\n            -opx * opz,\n            opx * omy,\n            opy * opz,\n            opx * opz,\n            opx * opy,\n            -opy * opz,\n            omx * opz,\n            omx * opy,\n        ) / 8\n\n    return dNdS\nend\n\"\"\"\n```\nshapeFunctionDeriv(shape<:AbstractShapeFunction, x::AbstractVector, y::AbstractVector, z::AbstractVector)\n```\nComputes the derivatives of the linear shape functions `N[1:3, 1:8]` for an `(x, y, z)` point on a 3D linear quadrangle.\n\n## Returns\n```\ndNdS[x, n, p](x,y,z) := x'th derivative of shape function n for point p.\n```\n\"\"\"\nfunction shapeFunctionDeriv(\n    ::LinearQuadrangle3D,\n    x::AbstractVector,\n    y::AbstractVector,\n    z::AbstractVector,\n)\n    numPoints = length(x)\n    @assert numPoints == length(y) == length(z)\n    xType = eltype(x)\n\n    # dNdS[x, n, p](x,y,z) := x'th derivative of shape function n for point p.\n    dNdS = Array{SMatrix{3, 8, xType}}(undef, numPoints)\n\n    @inbounds @simd for i in eachindex(x)\n        omx = 1 - x[i]\n        omy = 1 - y[i]\n        omz = 1 - z[i]\n        opx = 1 + x[i]\n        opy = 1 + y[i]\n        opz = 1 + z[i]\n\n        dNdS[i] =\n            SMatrix{3, 8, xType}(\n                -omy * omz,\n                -omx * omz,\n                -omx * omy,\n                omy * omz,\n                -opx * omz,\n                -opx * omy,\n                opy * omz,\n                opx * omz,\n                -opx * opy,\n                -opy * omz,\n                omx * omz,\n                -omx * opy,\n                -omy * opz,\n                -omx * opz,\n                omx * omy,\n                omy * opz,\n                -opx * opz,\n                opx * omy,\n                opy * opz,\n                opx * opz,\n                opx * opy,\n                -opy * opz,\n                omx * opz,\n                omx * opy,\n            ) / 8\n    end\n\n    return dNdS\nend\n", "meta": {"hexsha": "bcb808b4aeeb0da1448d38b6cba1bb886cc6fe8f", "size": 4505, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Processing/FEMShapeFunction.jl", "max_stars_repo_name": "dcelisgarza/DDD", "max_stars_repo_head_hexsha": "9257c619240a2b3bbdddd813d5e08ab71a07f7be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-05-30T03:22:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T07:34:42.000Z", "max_issues_repo_path": "src/Processing/FEMShapeFunction.jl", "max_issues_repo_name": "dcelisgarza/DDD.jl", "max_issues_repo_head_hexsha": "9257c619240a2b3bbdddd813d5e08ab71a07f7be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-02-03T10:26:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-11T10:01:38.000Z", "max_forks_repo_path": "src/Processing/FEMShapeFunction.jl", "max_forks_repo_name": "dcelisgarza/DDD", "max_forks_repo_head_hexsha": "9257c619240a2b3bbdddd813d5e08ab71a07f7be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-12-09T07:34:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-10T03:24:45.000Z", "avg_line_length": 24.3513513514, "max_line_length": 120, "alphanum_fraction": 0.4421753607, "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7693373901843344}}
{"text": "using DataDrivenDiffEq\nusing ModelingToolkit\nusing OrdinaryDiffEq\nusing LinearAlgebra\nusing Plots\ngr()\n\n\n\n# Create a\nfunction pendulum(u, p, t)\n    x = u[2]\n    y = -9.81sin(u[1]) - 0.1u[2]^3 -0.2*cos(u[1])\n    return [x;y]\nend\n\nu0 = [0.99π; -1.0]\ntspan = (0.0, 20.0)\nprob = ODEProblem(pendulum, u0, tspan)\nsol = solve(prob, Tsit5(), saveat = 0.3)\n\nplot(sol)\n\n# Create the differential data\nDX = similar(sol[:,:])\nfor (i, xi) in enumerate(eachcol(sol[:,:]))\n    DX[:,i] = pendulum(xi, [], 0.0)\nend\n\n# Create a basis\n@variables u[1:2]\n@parameters w[1:2]\n# Lots of polynomials\npolys = Operation[1]\nfor i ∈ 1:5\n    push!(polys, u.^i...)\n    for j ∈ 1:i-1\n        push!(polys, u[1]^i*u[2]^j)\n    end\nend\n\n# And some other stuff\nh = [w[1]*cos(u[1]); w[2]*sin(u[1]); u[1]*u[2]; u[1]*sin(u[2]); u[2]*cos(u[2]); polys...]\n\nbasis = Basis(h, u, parameters = w)\nprintln(basis)\n\n# Get the reduced basis via the sparse regression\n# Thresholded Sequential Least Squares, works fine for more data\n# than assumptions, converges fast but fails sometimes with too much noise\nopt = STRRidge(1e-2)\n# Enforce all 100 iterations\nΨ = SINDy(sol[:,1:25], DX[:, 1:25], basis, opt, p = [1.0; 1.0], maxiter = 100, convergence_error = 1e-5)\nprintln(Ψ)\nprint_equations(Ψ)\n\n# Lasso as ADMM, typically needs more information, more tuning\nopt = ADMM(1e-2, 1.0)\nΨ = SINDy(sol[:,1:50], DX[:, 1:50], basis, opt, p = [1.0; 1.0], maxiter = 5000, convergence_error = 1e-3)\nprintln(Ψ)\nprint_equations(Ψ)\n\n# Get the associated parameters out of the result\nparameters(Ψ)\n\n# SR3, works good with lesser data and tuning\nopt = SR3(1e-2, 1.0)\nΨ = SINDy(sol[:,1:end], DX[:, 1:end], basis, opt, p = [0.5; 0.5], maxiter = 5000, convergence_error = 1e-5)\nprintln(Ψ)\nprint_equations(Ψ, show_parameter = true)\n\n\n# Vary the sparsity threshold -> gives better results\nλs = exp10.(-5:0.1:-1)\n# Use SR3 with high relaxation (allows the solution to diverge from LTSQ) and high iterations\nopt = SR3(1e-2, 5.0)\nΨ = SINDy(sol[:,1:10], DX[:, 1:10], basis, λs, opt, p = [1.0; 1.0], maxiter = 15000)\nprintln(Ψ)\nprint_equations(Ψ)\n\n# Transform into ODE System\nsys = ODESystem(Ψ)\ndudt = ODEFunction(sys)\nps = parameters(Ψ)\n\n# Simulate\nestimator = ODEProblem(dudt, u0, tspan, ps)\nsol_ = solve(estimator, Tsit5(), saveat = sol.t)\n\n# Yeah! We got it right\nscatter(sol.t[1:10], sol[:,1:10]', color = :red, label = nothing)\nscatter!(sol.t[11:end], sol[:,11:end]', color = :blue, label = nothing)\nplot!(sol_.t, sol_[:, :]', color = :green, label = \"Estimation\")\n\nplot(sol.t, abs.(sol-sol_)')\nnorm(sol[:,:]-sol_[:,:], 2)\n", "meta": {"hexsha": "a8bcdd054cb863e5413559f130d6dc01dcc11ac2", "size": 2549, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/SInDy_Examples.jl", "max_stars_repo_name": "baggepinnen/DataDrivenDiffEq.jl", "max_stars_repo_head_hexsha": "71cfca8e9b095214b418f884dde21b06d24046f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/SInDy_Examples.jl", "max_issues_repo_name": "baggepinnen/DataDrivenDiffEq.jl", "max_issues_repo_head_hexsha": "71cfca8e9b095214b418f884dde21b06d24046f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/SInDy_Examples.jl", "max_forks_repo_name": "baggepinnen/DataDrivenDiffEq.jl", "max_forks_repo_head_hexsha": "71cfca8e9b095214b418f884dde21b06d24046f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2783505155, "max_line_length": 107, "alphanum_fraction": 0.6492742252, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7693373901767742}}
{"text": "# Corresponds to https://en.wikipedia.org/wiki/Logarithmic_distribution\r\nstruct Logarithmic{T<:Real} <: Distributions.DiscreteUnivariateDistribution\r\n    p::T\r\n    function Logarithmic(p::T) where {T <: Real}\r\n        new{T}(p)\r\n    end\r\nend\r\nfunction Distributions.logpdf(d::Logarithmic, x::Real)\r\n    insupport(d, x) ? x*log(d.p) - log(x) - log(-log(1-d.p)) : log(zero(d.p))\r\nend\r\nfunction Distributions.rand(rng::Distributions.AbstractRNG, d::Logarithmic)\r\n    # Sample a Log(p) distribution with the algorithm \"LK\" of Kemp (1981).\r\n    u = rand(rng)\r\n    if u > d.p \r\n        return 1\r\n    end\r\n    q = 1 - (1-d.p)^rand(rng)\r\n    if u < q*q\r\n        return floor(1+log(u)/log(q))\r\n    end\r\n    if u < q\r\n        return 1\r\n    end\r\n    return 2\r\nend\r\n", "meta": {"hexsha": "43b762ac58e7c3546b305bf3a4549234ae3f78f2", "size": 754, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate_distributions/Logarithmic.jl", "max_stars_repo_name": "lrnv/Copulas.jl", "max_stars_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2022-02-16T08:18:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:14:07.000Z", "max_issues_repo_path": "src/univariate_distributions/Logarithmic.jl", "max_issues_repo_name": "lrnv/Copulas.jl", "max_issues_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-19T06:55:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T09:43:03.000Z", "max_forks_repo_path": "src/univariate_distributions/Logarithmic.jl", "max_forks_repo_name": "lrnv/Copulas.jl", "max_forks_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0, "max_line_length": 78, "alphanum_fraction": 0.6061007958, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7693373901692139}}
{"text": "export IdentityLink, LogLink, LogitLink\nexport link, unlink, jacobian_link\n\nabstract type Link end\n\n\"\"\"\n    link(args...)\n\nThe link function is a map that brings a parameter ``f`` in a subspace ``\\\\mathcal{F} \\\\subset \\\\mathbb{R}`` to ``\\\\mathbb{R}``.\n\"\"\"\nfunction link end\n\n\"\"\"\n    unlink(args...)\n\nThe unlink function is the inverse map of [`link`](@ref link). It brings ``\\\\tilde{f}`` in ``\\\\mathbb{R}`` to the subspace ``\\\\mathcal{F} \\\\subset \\\\mathbb{R}``.\n\"\"\"\nfunction unlink end\n\n\"\"\"\n    jacobian_link(args...)\n\nEvaluates the derivative of the [`link`](@ref link) with respect to the parameter ``f``.\n\"\"\"\nfunction jacobian_link end\n\n\"\"\"\n    IdentityLink <: Link\n\nDefine the map ``\\\\tilde{f} = f`` where ``f \\\\in \\\\mathbb{R}`` and ``\\\\tilde{f} \\\\in \\\\mathbb{R}``\n\"\"\"\nstruct IdentityLink <: Link end\n\nlink(::Type{IdentityLink}, param::T) where T = param\nunlink(::Type{IdentityLink}, param_tilde::T) where T = param_tilde\njacobian_link(::Type{IdentityLink}, param::T) where T = one(T)\n\n\"\"\"\n    LogLink <: Link\n\nDefine the map ``\\\\tilde{f} = \\\\ln(f - a)`` where ``f \\\\in [a, \\\\infty), a \\\\in \\\\mathbb{R}`` and ``\\\\tilde{f} \\\\in \\\\mathbb{R}``\n\"\"\"\nstruct LogLink <: Link end\n\nlink(::Type{LogLink}, param::T, lower_bound::T) where T = log(param - lower_bound)\nunlink(::Type{LogLink}, param_tilde::T, lower_bound::T) where T = exp(param_tilde) + lower_bound\njacobian_link(::Type{LogLink}, param::T, lower_bound::T) where T = 1/(param - lower_bound)\n\n\"\"\"\n    LogitLink <: Link\n\nDefine the map ``\\\\tilde{f} = \\\\ln(\\\\frac{f - a}{b - f})`` where ``f \\\\in [a, b], a, b \\\\in \\\\mathbb{R}`` and ``\\\\tilde{f} \\\\in \\\\mathbb{R}``\n\"\"\"\nstruct LogitLink <: Link end\n\nfunction link(::Type{LogitLink}, param::T, lower_bound::T, upper_bound::T) where T \n    return log((param - lower_bound)/(upper_bound - param))\nend\nfunction unlink(::Type{LogitLink}, param_tilde::T, lower_bound::T, upper_bound::T) where T \n    return lower_bound + ((upper_bound - lower_bound)/(1 + exp(-param_tilde)))\nend\nfunction jacobian_link(::Type{LogitLink}, param::T, lower_bound::T, upper_bound::T) where T \n    return (upper_bound + lower_bound)/((upper_bound - param) * (param - lower_bound))\nend\n\nconst LINKS = [\n    IdentityLink;\n    LogLink;\n    LogitLink\n]\n", "meta": {"hexsha": "162867cbbd55b2f47cb7dd399e4de0fa39aee853", "size": 2223, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/link_functions.jl", "max_stars_repo_name": "marinadietze/ScoreDrivenModels.jl", "max_stars_repo_head_hexsha": "4ee85b8d606892535a7b0bf2aec1d976f44d796e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2020-02-05T04:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T18:46:03.000Z", "max_issues_repo_path": "src/link_functions.jl", "max_issues_repo_name": "marinadietze/ScoreDrivenModels.jl", "max_issues_repo_head_hexsha": "4ee85b8d606892535a7b0bf2aec1d976f44d796e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 109, "max_issues_repo_issues_event_min_datetime": "2019-11-26T12:34:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-27T20:16:55.000Z", "max_forks_repo_path": "src/link_functions.jl", "max_forks_repo_name": "LAMPSPUC/GAS.jl", "max_forks_repo_head_hexsha": "e169248c3f8908170868d898a4def97af15774cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:11:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-04T20:05:21.000Z", "avg_line_length": 31.3098591549, "max_line_length": 161, "alphanum_fraction": 0.6486729645, "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7693373808691338}}
{"text": "using EconPDEs, Distributions\n\nstruct AchdouHanLasryLionsMollModel\n    # income process parameters\n    κy::Float64 \n    ybar::Float64\n    σy::Float64\n\n    r::Float64\n\n    # utility parameters\n    ρ::Float64  \n    γ::Float64\n\n    amin::Float64\n    amax::Float64 \nend\n\nfunction AchdouHanLasryLionsMollModel(;κy = 0.1, ybar = 1.0, σy = 0.07, r = 0.03, ρ = 0.05, γ = 2.0, amin = 0.0, amax = 500.0)\n    AchdouHanLasryLionsMollModel(κy, ybar, σy, r, ρ, γ, amin, amax)\nend\n\nfunction (m::AchdouHanLasryLionsMollModel)(state::NamedTuple, value::NamedTuple)\n    (; κy, σy, ybar, r, ρ, γ, amin, amax) = m    \n    (; y, a) = state\n    (; v, vy_up, vy_down, va_up, va_down, vyy, vya, vaa) = value\n    μy = κy * (ybar - y)\n    vy = (μy >= 0) ? vy_up : vy_down\n\n    va = va_up\n    iter = 0\n    @label start\n    va_up = max(va_up, eps())    \n    c = va^(-1 / γ)\n    μa = y + r * a - c\n    if (iter == 0) & (μa <= 0)\n        iter += 1\n        va = va_down\n        @goto start\n    end\n    if (a ≈ amin) && (μa <= 0.0)\n        va = (y + r * amin)^(-γ)\n        c = y + r * amin\n        μa = 0.0\n    end\n    vt = - (c^(1 - γ) / (1 - γ) + μa * va + μy * vy + 0.5 * vyy * σy^2 - ρ * v)\n    return (; vt)\nend\n\nm = AchdouHanLasryLionsMollModel()\ndistribution = Gamma(2 * m.κy * m.ybar / m.σy^2, m.σy^2 / (2 * m.κy))\nstategrid = OrderedDict(:y => range(quantile(distribution, 0.001), quantile(distribution, 0.999), length = 10), \n                        :a =>  range(m.amin, m.amax, length = 100)\n                        )\nyend = OrderedDict(:v => [log(y + max(a, 0.0)) for y in stategrid[:y], a in stategrid[:a]])\nresult = pdesolve(m, stategrid, yend)\n@assert result.residual_norm <= 1e-5\n\n# finite horizon over 20 years\nyend = OrderedDict(:v => [max(a + y)^(1-m.γ)/(1-m.γ) for y in stategrid[:y], a in stategrid[:a]]) \nτs = range(0, stop = 100, step = 1)\nresult  = pdesolve(m, stategrid, yend, τs)\n@assert maximum(result.residual_norm) <= 1e-5\n\n\n# Check marginal value of wealth converges to 1.0 at infinity\n#b = ((m.r + (m.ρ - m.r)/m.γ))^(1/(1 - 1/m.γ))\n#pw = (result[:v] * (1-m.γ)).^(1/(1-m.γ)-1) .* result[:va] ./ b\n", "meta": {"hexsha": "f22988bf0b41fd9c217be8138a0843739efe1d85", "size": 2095, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ConsumptionProblem/AchdouHanLasryLionsMoll_OneAsset.jl", "max_stars_repo_name": "matthieugomez/PDEModels.jl", "max_stars_repo_head_hexsha": "ecdefd0b1e52b2ec3bcebb9498d39057c26afd74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2016-10-06T20:37:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T16:25:39.000Z", "max_issues_repo_path": "examples/ConsumptionProblem/AchdouHanLasryLionsMoll_OneAsset.jl", "max_issues_repo_name": "matthieugomez/PDEModels.jl", "max_issues_repo_head_hexsha": "ecdefd0b1e52b2ec3bcebb9498d39057c26afd74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2018-04-27T17:24:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T01:42:28.000Z", "max_forks_repo_path": "examples/ConsumptionProblem/AchdouHanLasryLionsMoll_OneAsset.jl", "max_forks_repo_name": "matthieugomez/PDEModels.jl", "max_forks_repo_head_hexsha": "ecdefd0b1e52b2ec3bcebb9498d39057c26afd74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38, "max_forks_repo_forks_event_min_datetime": "2016-11-12T15:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:57:36.000Z", "avg_line_length": 30.3623188406, "max_line_length": 126, "alphanum_fraction": 0.5522673031, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7693046246316589}}
{"text": "\n# InverseGamma distribution\n\nexport InverseGamma\n\n@parameterized InverseGamma(shape) ≃ Lebesgue(ℝ₊)\n\nfunction logdensity(μ::InverseGamma{(:shape,)}, x) \n    α = μ.shape\n    xinv = 1/x\n\n    return xlogy(α + 1, xinv) - xinv - loggamma(α) \nend\n\nBase.rand(rng::AbstractRNG, T::Type, μ::InverseGamma{(:shape,)}) = rand(rng, Dists.InverseGamma(μ.shape))\n\n≪(::InverseGamma, ::Lebesgue{X}) where X <: Real = true\n\nTV.as(::InverseGamma) = asℝ₊\n\n# @μσ_methods InverseGamma(shape)\n", "meta": {"hexsha": "e21c362d54002e9c85ec560c1f4b6603921bbe39", "size": 471, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/parameterized/inverse-gamma.jl", "max_stars_repo_name": "keorn/MeasureTheory.jl", "max_stars_repo_head_hexsha": "ffd1969043c691ebc70b77150015374719fb1718", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 274, "max_stars_repo_stars_event_min_datetime": "2020-09-24T13:34:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:36:38.000Z", "max_issues_repo_path": "src/parameterized/inverse-gamma.jl", "max_issues_repo_name": "keorn/MeasureTheory.jl", "max_issues_repo_head_hexsha": "ffd1969043c691ebc70b77150015374719fb1718", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 149, "max_issues_repo_issues_event_min_datetime": "2020-09-23T02:15:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T17:29:21.000Z", "max_forks_repo_path": "src/parameterized/inverse-gamma.jl", "max_forks_repo_name": "keorn/MeasureTheory.jl", "max_forks_repo_head_hexsha": "ffd1969043c691ebc70b77150015374719fb1718", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2020-09-24T13:34:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T23:30:31.000Z", "avg_line_length": 21.4090909091, "max_line_length": 105, "alphanum_fraction": 0.6794055202, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7693046152019603}}
{"text": "# Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are\n# all figurate (polygonal) numbers and are generated by the following formulae:\n# \n# Triangle    P3,n=n(n+1)/2    1, 3, 6, 10, 15, ...\n# Square      P4,n=n2          1, 4, 9, 16, 25, ...\n# Pentagonal  P5,n=n(3n−1)/2   1, 5, 12, 22, 35, ...\n# Hexagonal   P6,n=n(2n−1)     1, 6, 15, 28, 45, ...\n# Heptagonal  P7,n=n(5n−3)/2   1, 7, 18, 34, 55, ...\n# Octagonal   P8,n=n(3n−2)     1, 8, 21, 40, 65, ...\n#\n# The ordered set of three 4-digit numbers: 8128, 2882, 8281, has three\n# interesting properties.\n# 1. The set is cyclic, in that the last two digits of each number is the first\n# two digits of the next number (including the last number with the first).\n# 2. Each polygonal type: triangle (P3,127=8128), square (P4,91=8281), and\n# pentagonal (P5,44=2882), is represented by a different number in the set.\n# 4. This is the only set of 4-digit numbers with this property.\n#\n# Find the sum of the only ordered set of six cyclic 4-digit numbers for which\n# each polygonal type: triangle, square, pentagonal, hexagonal, heptagonal, and\n# octagonal, is represented by a different number in the set.\n\nusing ProjectEulerSolutions\n\n# Solve for n given x and s: P(s,n) = x.\nfunction polygonal_inv(s::Integer, x::Integer)::Float32\n    return (sqrt(8*(s-2)*x + (s-4)^2) + (s-4))/(2*(s-2))\nend\n\n# Implements polygonal number P(s,n) = x, where s is the number of sides.\nfunction polygonal_number(s::Integer, n::Integer)::Integer\n   return div((s - 2) * n * n - n * (s - 4), 2)\nend\n\n# Helper recursive function to find the numbers that match the beginning and\n# ending pairs.\nfunction find_loop!(numbers::Array{Integer,1}, used_polys::Array{Integer,1}, end_pair::Integer, polys::Array{Array{Integer,1},1})::Bool\n    d = 10^(ndigits(numbers[1])-2)\n    if length(numbers) == 6 && end_pair == div(numbers[1], d)\n        return true\n    end\n    ks = filter(x -> !(x in used_polys), 2:length(polys))\n    for k in ks\n        push!(used_polys, k)\n        for n in polys[k]\n            if div(n, d) == end_pair\n                push!(numbers, n)\n                found = find_loop!(numbers, used_polys, n % 100, polys)\n                if found\n                    return true\n                end\n                pop!(numbers)\n            end\n        end\n        pop!(used_polys)\n    end\n    return false\nend\n\n\n# This is a verbose solution primarily due to manipulating the data into the\n# correct data structures.  Only cycle through 4 digit polygonal numbers, then\n# recursively loop through collections, remembering which polygonal numbers\n# have already been used.  There is probably a graph-based solution which find\n# paths through a network (6-partite graph?).\nfunction p061solution(ndig_start::Integer=4, ndig_end::Integer=4)::Integer\n\n    min_n = 10^(ndig_start-1)\n    max_n = 10^ndig_end-1\n\n    polys = Array{Array{Integer,1},1}()\n    # Initialize data structure, making use of vectorized instructions\n    for s = 3:8\n        min_num = Integer(ceil(polygonal_inv(s, min_n)))\n        max_num = Integer(floor(polygonal_inv(s, max_n)))\n\n        # Calculate all 4 digit polygonal numbers for s\n        poly_s = polygonal_number.(s, min_num:max_num)\n\n        # Only keep numbers whose lower halves have two digits\n        lower_s = poly_s .% 100\n        inds = lower_s .> 9\n        push!(polys, poly_s[inds])\n    end\n\n    # Loop through potential starting points, starting with s = 3.  The order\n    # doesn't matter since all polygonal values are eventually used.\n    used_polys = Array{Integer,1}([1])\n    numbers = Array{Integer,1}()\n    for n in polys[1]\n        push!(numbers, n)\n        if find_loop!(numbers, used_polys, n % 100, polys)\n             return sum(numbers)\n        end\n        pop!(numbers)\n    end\n\n    return -1\nend\n\np061 = Problems.Problem(p061solution)\n\nProblems.benchmark(p061, 4, 4)\n", "meta": {"hexsha": "c12ae956a917f21aa8e2994e8e1d2b66af105e01", "size": 3870, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/061.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/061.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/061.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2115384615, "max_line_length": 135, "alphanum_fraction": 0.6441860465, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.769304608007599}}
{"text": "## Packages\nusing Roots, Calculus, Plots\n\n## Function for finding root\nfunction findZero(g, init_guess)\n    \n    xn1 = init_guess;  \n    tol = 10^(-8);\n    distance = 1;\n    iter = 1;\n\n    while distance >= tol\n        xn = xn1;\n        xn1 = xn - g(xn) / derivative(g, xn);\n        xn1 = max(xn1, 0.0001);\n\n        distance = abs(xn1 - xn);\n        iter = iter + 1;\n    end\n\n    return xn1\nend\n\n## Function for defining utility function\nfunction u(c)\n    if c <= 0\n        u = -Inf;\n    else\n        u = c^(1/2);\n    end\n    return u\nend\n\n## Parameters\nβ = 0.8;\nπs1 = 1/2;\nπs2 = 1/2;\nYs1 = 1;\nYs2 = 1/2;\nM = 20; # Number of grids\n\n## Grid for v\nvmax = (πs1 * u(Ys1) + πs2 * u(Ys2)) / (1 - β);\nvgrid = range(0.0, stop = vmax, length = M);\n\n## Iterate on Value function\nPi1 = zeros(M);\ncs1_grid = range(0, stop = Ys1, length = M);\nws1_grid = vgrid;\nws2_grid = vgrid;\n\ndistance = 1;\ntol = 10^(-8);\niter = 1;\n\npolicy_fun = Array{CartesianIndex, 1}(undef, M);\npolicy_cs1 = Array{Int64, 1}(undef, M);\n\nwhile distance >= tol\n    println(\"This is iteration $iter\")\n    Pi = copy(Pi1); \n    \n    for vIndex in 1:M\n        U = Array{Float64, 3}(undef, M, M, M)\n        v = vgrid[vIndex];\n        for cs1Index in 1:M, ws1Index in 1:M, ws2Index in 1:M\n            cs1 = cs1_grid[cs1Index];\n            ws1 = ws1_grid[ws1Index];\n            ws2 = ws2_grid[ws2Index];\n\n            # Solve for cs2\n            f(cs2) = v - (πs1 * (cs1^(1/2) + β * ws1)) - (πs2 * (cs2^(1/2) + β * ws2));\n            cs2 = findZero(f, 1.0);\n\n            U_temp = (πs1 * (u(Ys1 - cs1) + β * Pi[ws1Index])) + \n                     (πs2 * (u(Ys2 - cs2) + β * Pi[ws2Index]));\n\n            if U_temp <= 0.0\n                U[cs1Index, ws1Index, ws2Index] = 0.0;\n            else\n                U[cs1Index, ws1Index, ws2Index] = U_temp;\n            end\n        end\n        Pi1[vIndex], policy_fun[vIndex] = findmax(U[:,:,:]);\n    end\n\n    distance = maximum(abs.(Pi1 - Pi));\n    iter = iter + 1;\nend\n\n## A Check\nλ = range(0.0, stop = 0.999, length = 100);\nu1 = zeros(100);\nu2 = zeros(100);\nfor i in 1:100\n    A = (λ[i] / (1 - λ[i]))^2;\n    cs1 = Ys1 * (A / (1 + A));\n    cs2 = Ys2 * (A / (1 + A));\n    u1[i] = (πs1 * u(cs1) + πs2 * u(cs2)) / (1 - β);\n    u2[i] = (πs1 * u(Ys1 - cs1) + πs2 * u(Ys2 - cs2)) / (1 - β);\nend\n\nplot(vgrid, Pi1, xlabel = \"v\", ylabel = \"P\", label = \"VFI\", legend =:bottomleft)\nplot!(u1, u2, label = \"Theoretical\")", "meta": {"hexsha": "da97705a143123733dd11f0e5c86a04af57056ae", "size": 2400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PS1/Hw1q4.jl", "max_stars_repo_name": "wongr003/ECON8402", "max_stars_repo_head_hexsha": "377b0567205d39f73e2502c4b5eef98818f365be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PS1/Hw1q4.jl", "max_issues_repo_name": "wongr003/ECON8402", "max_issues_repo_head_hexsha": "377b0567205d39f73e2502c4b5eef98818f365be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PS1/Hw1q4.jl", "max_forks_repo_name": "wongr003/ECON8402", "max_forks_repo_head_hexsha": "377b0567205d39f73e2502c4b5eef98818f365be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0769230769, "max_line_length": 87, "alphanum_fraction": 0.5020833333, "num_tokens": 921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7692883663259408}}
{"text": "using OrdinaryDiffEq\n\nfunction LotkaVolterraTest_not_inplace(u,a,t)\n    b,c,d = 1.0,3.0,1.0\n    x,y = u[1],u[2]\n    du = zeros(eltype(u),2)\n    du[1] = a*x - b*x*y\n    du[2] = -c*y + d*x*y\n    du\nend\n\n# forward\nu0 = [1.0;1.0]\ntspan = (0.0,10.0)\nprob = ODEProblem(LotkaVolterraTest_not_inplace,u0,tspan,1.5)\n\nsol = solve(prob,Tsit5())\nt = collect(range(0, stop=10, length=200))\nusing RecursiveArrayTools # for VectorOfArray\nrandomized = VectorOfArray([(sol(t[i]) + .01randn(2)) for i in 1:length(t)])\ndata = convert(Array,randomized)\n\n# inverse\nsoll = solve(prob,Tsit5())\n\ncost_function = build_loss_objective(prob,Tsit5(),L2Loss(t,data),\n                                     maxiters=10000,verbose=false)\nimport Optim\nresult = Optim.optimize(cost_function, 0.0, 10.0)\n", "meta": {"hexsha": "e12933cd4464f80cdfc963b51c785b2c4bb8d0a1", "size": 768, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/out_of_place_odes.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/DiffEqParamEstim.jl-1130ab10-4a5a-5621-a13d-e4788d82bd4c", "max_stars_repo_head_hexsha": "2344b1f54707f8f3b4ee4fab2c9b4dd1ebbee484", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/out_of_place_odes.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/DiffEqParamEstim.jl-1130ab10-4a5a-5621-a13d-e4788d82bd4c", "max_issues_repo_head_hexsha": "2344b1f54707f8f3b4ee4fab2c9b4dd1ebbee484", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-28T23:47:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-28T23:47:15.000Z", "max_forks_repo_path": "test/out_of_place_odes.jl", "max_forks_repo_name": "Vaibhavdixit02/DiffEqParamEstim.jl", "max_forks_repo_head_hexsha": "d68ac5e139eb1005064d1b5f404870c008889d03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6, "max_line_length": 76, "alphanum_fraction": 0.6484375, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7692883643164775}}
{"text": "using Plots\nusing BenchmarkTools\n\nfunction vfsolve(vnew, kgrid, tolerance, imax)\n    α = 0.3\n    δ = 0.1\n    β = 0.9\n\n    v = vnew .+ 2*tolerance\n    cartesianindex = Array{CartesianIndex{2}, length(v)}\n    i = 1\n    \n    c = kgrid.^α + (1-δ)*kgrid .- kgrid'\n    c[c .< 0] .= 0\n    u = log.(c)\n    u[kgrid.^α + (1-δ)*kgrid .- kgrid' .< 0] .= -Inf\n\n    while maximum(abs.(v - vnew)) > tolerance && i <= imax\n        v = vnew;\n        \n        (vnew, cartesianindex) = findmax(u .+ β*v', dims = 2);\n        i += 1;\n    end\n    kprimeindex = getindex.(cartesianindex, 2)\n    return (v = vnew, kprime = kgrid[kprimeindex], kprimeindex = kprimeindex)\nend\n\n\nkupper = 20\nklower = 0.001\nn = 1000\nkgrid = collect(range(klower, stop = kupper, length = n))\n(v, kprime, kprimeindex) = vfsolve(zeros(n), kgrid, 0.001, 1000);\n\nscatter(kgrid, v, label = \"v\")\nscatter(kgrid, kprime, label = \"k'\")\n\n# Checks\nvbasic == v\nkprimebasic == kprime\n\n@btime vfsolve(zeros(n), kgrid, 0.001, 1000);\n@btime vfsolvebasic(zeros(n), kgrid, 0.001, 1000);\n\n# Check k bounds, stepsize, tolerance, imax\nfindall(kprime .== maximum(kgrid))\nany(kprime .== minimum(kgrid))\n\n##\nplot()\nkupper = 2\nklower = 0.001\ntolerance = 0.001\nfor n in [10, 100, 500]\n    kgrid = collect(range(klower, stop = kupper, length = n))\n    (v, kprime, kprimeindex) = vfsolve(zeros(n), kgrid, tolerance, n);\n     display(plot!(kgrid, v, label = \"v, n=$n, tol=$tolerance\"))\n            # display(plot!(kgrid, kprime, label = \"k'\"))\nend\n##", "meta": {"hexsha": "aa2f4b8275338a4f698d99bc985b4ca059bb2c6f", "size": 1475, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Dynamic Programming/demo.jl", "max_stars_repo_name": "paradoxuu/AS-1", "max_stars_repo_head_hexsha": "3d7b03e5806dca30dcd19a7a6acdea9c994bbde7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Dynamic Programming/demo.jl", "max_issues_repo_name": "paradoxuu/AS-1", "max_issues_repo_head_hexsha": "3d7b03e5806dca30dcd19a7a6acdea9c994bbde7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Dynamic Programming/demo.jl", "max_forks_repo_name": "paradoxuu/AS-1", "max_forks_repo_head_hexsha": "3d7b03e5806dca30dcd19a7a6acdea9c994bbde7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5833333333, "max_line_length": 77, "alphanum_fraction": 0.5972881356, "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7692883587188061}}
{"text": "# Starting with 1 and spiralling anticlockwise in the following way, a square\n# spiral with side length 7 is formed.\n# \n# 37 36 35 34 33 32 31\n# 38 17 16 15 14 13 30\n# 39 18  5  4  3 12 29\n# 40 19  6  1  2 11 28\n# 41 20  7  8  9 10 27\n# 42 21 22 23 24 25 26\n# 43 44 45 46 47 48 49\n# \n# It is interesting to note that the odd squares lie along the bottom right\n# diagonal, but what is more interesting is that 8 out of the 13 numbers lying\n# along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.\n# \n# If one complete new layer is wrapped around the spiral above, a square spiral\n# with side length 9 will be formed. If this process is continued, what is the\n# side length of the square spiral for which the ratio of primes along both\n# diagonals first falls below 10%?\n\n\nusing ProjectEulerSolutions\n\n# Create the sequence of corner values and check each for primeness.  Keep a\n# running total to verify that the desired threshold has been met.\nfunction p058solution(thresh::Float64=0.44)::Integer\n    nprimes = 0\n    total_tested = 1\n    startindex = 3\n    i = 2\n    while i == 2 || nprimes / total_tested > thresh\n        nprimes += sum(isprime.(collect(startindex .+ (0:i:i*3))))\n        startindex = startindex + 4*i + 2\n        total_tested += 4\n        i += 2\n    end\n    return i - 1\nend\n\np058 = Problems.Problem(p058solution)\n\nProblems.benchmark(p058, 0.1)\n", "meta": {"hexsha": "625727eef28b7a608db8dd138e67fa8f2d121a7b", "size": 1373, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/058.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/058.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/058.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9302325581, "max_line_length": 79, "alphanum_fraction": 0.6904588492, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109606718245, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7692883493606386}}
{"text": "include(\"../helpers.jl\")\n\nusing Gadfly\nusing Color\n\nL(R) = x -> R * x * (1 - x)\n\nk = 60\nRs = linspace(0.1, 4.0, 10) # [0.1, 0.533, 0.967, 1.4, ...]\nxs = map(R -> iterate(L(R), 0.2, k), Rs)\n\nfps = map(x -> fixedpoint(x, ϵ = 1e-3), xs) # [4, 8, 26, 10, ...]\n\n# Values of R ∈ [3.0, 4.0] have very interesting properties.\n# See Wikipedia or explore them yourself.\n# Doing a Fourier Transform of the sequence will help illuminate these interesting\n# properties\n", "meta": {"hexsha": "93442fb347a2e2e84e6566bb5fe7b287ee6cc779", "size": 456, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "unit-1-introduction-maps/logistic-map.jl", "max_stars_repo_name": "emilbayes/notes-complexity-explorer-nonlinear-dynamics", "max_stars_repo_head_hexsha": "b9543afe65171bc640de09e574ac0ef12f25ee7d", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit-1-introduction-maps/logistic-map.jl", "max_issues_repo_name": "emilbayes/notes-complexity-explorer-nonlinear-dynamics", "max_issues_repo_head_hexsha": "b9543afe65171bc640de09e574ac0ef12f25ee7d", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit-1-introduction-maps/logistic-map.jl", "max_forks_repo_name": "emilbayes/notes-complexity-explorer-nonlinear-dynamics", "max_forks_repo_head_hexsha": "b9543afe65171bc640de09e574ac0ef12f25ee7d", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3333333333, "max_line_length": 82, "alphanum_fraction": 0.6118421053, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7692883475234625}}
{"text": "using Distributions, Calculus, SpecialFunctions, Plots; pyplot()\n\nxGrid = -5:0.01:5\n\nPhiA(x) = 0.5*(1+erf(x/sqrt(2)))\nPhiB(x) = cdf(Normal(),x)\n\nprintln(\"Maximum difference between two CDF implementations: \",\n            maximum(PhiA.(xGrid) - PhiB.(xGrid)))\n\nnormalDensity(z) = pdf(Normal(),z)\n\nd0 = normalDensity.(xGrid)\nd1 = derivative.(normalDensity,xGrid)\nd2 = second_derivative.(normalDensity, xGrid)\n\nplot(xGrid, [d0 d1 d2], c=[:blue :red :green],label=[L\"f(x)\" L\"f'(x)\" L\"f''(x)\"])\nplot!([-5,5],[0,0],  color=:black, lw=0.5, xlabel=\"x\", xlims=(-5,5), label=\"\")", "meta": {"hexsha": "9f2db4d2e01163ab811ef6d5cc5b905ceee3abbc", "size": 568, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/normalCalculus.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "3_chapter/normalCalculus.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "3_chapter/normalCalculus.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 31.5555555556, "max_line_length": 81, "alphanum_fraction": 0.6443661972, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9637799462157138, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.769276414346801}}
{"text": "using Sundials, Plots\npyplot(size=(700,700))\n\nProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n\n  ## f2 routine. Compute function f(x,y).\n\n  function f2(x, y, ydot)\n      ydot[1] = y[2]\n      ydot[2] = 2.0*y[1] - 3.0*y[2] + 3.0*x^2\n  end\n\n  x = 0.0:0.2:5\n  res = Sundials.cvode(f2, [1.0, 0.0], collect(x))\n  res |> display\n  println()\n\n  p1 = plot(x, res[:,1], color=:darkblue,\n    xlabel=\"x\", ylabel=\"y[1]\",\n    title=\"Example Sundials01A (using Sundials.jl)\"\n    )\n  p2 = plot(x, res[:,2], color=:darkred,\n    xlabel=\"x\", ylabel=\"y[2]\"\n    )\n  plot(p1, p2, layout=(2, 1))\n  savefig(\"Sundials01A.png\")\n  gui()\n\nend", "meta": {"hexsha": "32da6a23e9b5b3c444df5af04d4556aad1c8f992", "size": 610, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch07/IVP/Sundials01A.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "examples/ch07/IVP/Sundials01A.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "examples/ch07/IVP/Sundials01A.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 20.3333333333, "max_line_length": 51, "alphanum_fraction": 0.5704918033, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509314, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.769220818882163}}
{"text": "function expectation(g, distr::ContinuousUnivariateDistribution; kwargs...)\n    return first(quadgk(x -> pdf(distr, x) * g(x), extrema(distr)...; kwargs...))\nend\n\n## Assuming that discrete distributions only take integer values.\nfunction expectation(g, distr::DiscreteUnivariateDistribution; epsilon::Real=1e-10)\n    mindist, maxdist = extrema(distr)\n    # We want to avoid taking values up to infinity\n    minval = isfinite(mindist) ? mindist : quantile(distr, epsilon)\n    maxval = isfinite(maxdist) ? maxdist : quantile(distr, 1 - epsilon)\n    return sum(x -> pdf(distr, x) * g(x), minval:maxval)\nend\n\nfunction expectation(g, distr::MultivariateDistribution; nsamples::Int=100, rng::AbstractRNG=GLOBAL_RNG)\n    nsamples > 0 || throw(ArgumentError(\"number of samples should be > 0\"))\n    # We use a function barrier to work around type instability of `sampler(dist)`\n    return mcexpectation(rng, g, sampler(distr), nsamples)\nend\n\nmcexpectation(rng, f, sampler, n) = sum(f, rand(rng, sampler) for _ in 1:n) / n\n\n## Leave undefined until we've implemented a numerical integration procedure\n# function entropy(distr::UnivariateDistribution)\n#     pf = typeof(distr)<:ContinuousDistribution ? pdf : pmf\n#     f = x -> pf(distr, x)\n#     expectation(distr, x -> -log(f(x)))\n# end\n\nfunction kldivergence(P::Distribution{V}, Q::Distribution{V}; kwargs...) where {V<:VariateForm}\n    return expectation(P; kwargs...) do x\n        logp = logpdf(P, x)\n        return (logp > oftype(logp, -Inf)) * (logp - logpdf(Q, x))\n    end\nend\n", "meta": {"hexsha": "2fc2ee47a82b4f71b920286d5c6205d0a0a9cba0", "size": 1524, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functionals.jl", "max_stars_repo_name": "theogf/Distributions.jl", "max_stars_repo_head_hexsha": "620a73acb4992fee8998b562837268defb4bae9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functionals.jl", "max_issues_repo_name": "theogf/Distributions.jl", "max_issues_repo_head_hexsha": "620a73acb4992fee8998b562837268defb4bae9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functionals.jl", "max_forks_repo_name": "theogf/Distributions.jl", "max_forks_repo_head_hexsha": "620a73acb4992fee8998b562837268defb4bae9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5428571429, "max_line_length": 104, "alphanum_fraction": 0.6975065617, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7692208113291131}}
{"text": "\"\"\"\n    Berlage(; <keyword arguments>)\n\nCreate a Berlage wavelet.\n\n# Arguments\n- `dt=0.002`: sampling interval in secs.\n- `f0=20.0`: central frequency in Hz.\n- `m::Real=2`: exponential parameter of Berlage wavelet.\n- `alpha::Real=180.0`: alpha parameter of Berlage wavelet in rad/secs.\n- `phi0::Real`: phase rotation in radians.\n\n# Example\n```julia\njulia> w = Berlage(); plot(w);\n```\n**Reference**\n* Aldridge, David F., 1990, The berlage wavelet: GEOPHYSICS, 55, 1508--1511.\n\"\"\"\nfunction Berlage(; dt=0.002, f0=20.0, m::Real=2, alpha::Real=180.0,\n                 phi0::Real=0.0)\n\n    nw = floor(Int, 2.2/(f0*dt))\n    t = dt*collect(0:1:nw-1)\n    w = (t .^ m).* exp.(-alpha*t) .* cos.(2*pi*f0*t .+ phi0);\n    w = w/maximum(w)\n\nend\n", "meta": {"hexsha": "c65fb6bddd6201113bfce09b86bc60bc695a9a99", "size": 731, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Modelling/Wavelets/Berlage.jl", "max_stars_repo_name": "JuliaTagBot/SeisProcessing.jl", "max_stars_repo_head_hexsha": "96a7b085bd988e70aa3501a3bbbd26c00a5f26f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-01-11T15:55:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T01:39:30.000Z", "max_issues_repo_path": "src/Modelling/Wavelets/Berlage.jl", "max_issues_repo_name": "JuliaTagBot/SeisProcessing.jl", "max_issues_repo_head_hexsha": "96a7b085bd988e70aa3501a3bbbd26c00a5f26f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-11-23T20:51:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T21:44:40.000Z", "max_forks_repo_path": "src/Modelling/Wavelets/Berlage.jl", "max_forks_repo_name": "JuliaTagBot/SeisProcessing.jl", "max_forks_repo_head_hexsha": "96a7b085bd988e70aa3501a3bbbd26c00a5f26f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-01-22T19:03:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-31T11:49:30.000Z", "avg_line_length": 25.2068965517, "max_line_length": 76, "alphanum_fraction": 0.6128590971, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806522, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7692208073305982}}
{"text": "\"\"\"\n    ks89RecursiveResidual(setting; indices, k)\nCalculate recursive residual for the given regression setting and observation.\n# Arguments\n- `setting::RegressionSetting`: RegressionSetting object with a formula and dataset.\n- `indices::ArrayInt,1`: Indices of observations used in the linear model.\n- `k::Int`: Observation indice the recursive residual is calculated for.\n# Notes\n    This is a helper function for the ks89 function and it is not directly used.\n# References\nKianifard, Farid, and William H. Swallow. \"Using recursive residuals, calculated on\nadaptively-ordered observations, to identify outliers in linear regression.\"\nBiometrics (1989): 571-585.\n\"\"\"\nfunction ks89RecursiveResidual(setting::RegressionSetting, indices::Array{Int,1}, k::Int)\n    X, y = @extractRegressionSetting setting\n    return ks89RecursiveResidual(X, y, indices, k)\nend\n\nfunction ks89RecursiveResidual(X::Array{Float64,2}, y::Array{Float64,1}, indices::Array{Int,1}, k::Int)\n    useX = X[indices, :]\n    useY = y[indices]\n    olsreg = ols(useX, useY)\n    betas = coef(olsreg)\n    XX = inv(useX'useX)\n    w = (y[k] - X[k,:]' * betas) / sqrt(1 + X[k,:]' * XX * X[k,:])\n    return w\nend\n\n\n\"\"\"\n    ks89(setting; alpha = 0.05)\nPerform the Kianifard & Swallow (1989) algorithm for the given regression setting.\n# Arguments\n- `setting::RegressionSetting`: RegressionSetting object with a formula and dataset.\n- `alpha::Float64`: Optional argument of the probability of rejecting the null hypothesis.\n# Examples\n```julia-repl\njulia> reg0001 = createRegressionSetting(@formula(stackloss ~ airflow + watertemp + acidcond), stackloss)\njulia> ks89(reg0001)\n2-element Array{Int64,1}:\n  4\n 21\n```\n# References\nKianifard, Farid, and William H. Swallow. \"Using recursive residuals, calculated on\nadaptively-ordered observations, to identify outliers in linear regression.\"\nBiometrics (1989): 571-585.\n\"\"\"\nfunction ks89(setting::RegressionSetting; alpha=0.05)\n    X = designMatrix(setting)\n    y = responseVector(setting)\n    return ks89(X, y, alpha=alpha)\nend\n\n\nfunction ks89(X::Array{Float64,2}, y::Array{Float64,1}; alpha=0.05)\n    stdres = studentizedResiduals(X, y)\n    orderingindices = sortperm(abs.(stdres))\n    n, p = size(X)\n    basisindices = orderingindices[1:p]\n    w = zeros(Float64, n)\n    s = zeros(Float64, n)\n    ws = zeros(Float64, n)\n    @inbounds for i in (p + 1):n\n        index = orderingindices[i]\n        w[index] = ks89RecursiveResidual(X, y, basisindices, index)\n        s[index] = jacknifedS(X, y, index)\n        ws[index] = w[index] / s[index]\n        basisindices = orderingindices[1:i]\n    end\n    td = TDist(n - p - 1)\n    q = quantile(td, alpha)\n    result = filter(i -> abs.(ws[i]) > abs(q), 1:n)\n    return result\nend", "meta": {"hexsha": "66446b75ac5fd460fa35099c5bfe3b0c06f7ff28", "size": 2725, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ks89.jl", "max_stars_repo_name": "angeris/LinRegOutliers", "max_stars_repo_head_hexsha": "093fc64345e6761d8871949ca71f2f1f529cb9e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ks89.jl", "max_issues_repo_name": "angeris/LinRegOutliers", "max_issues_repo_head_hexsha": "093fc64345e6761d8871949ca71f2f1f529cb9e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ks89.jl", "max_forks_repo_name": "angeris/LinRegOutliers", "max_forks_repo_head_hexsha": "093fc64345e6761d8871949ca71f2f1f529cb9e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8552631579, "max_line_length": 105, "alphanum_fraction": 0.6990825688, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7692180659326705}}
{"text": "using Random, LinearAlgebra, Krylov\nusing Plots\nusing RandomizedPreconditioners\nconst RP = RandomizedPreconditioners\n\nn = 500\nμ = 1e-4\n\n# Build Spectrum (exp decay)\nλs = max.(√n * exp.(-(0:n-1) ./ √n), μ)\nplot(λs, lw=3, legend=false, title=\"Spectrum\")\n\n# Build Matrix\nV = Array(qr(randn(n,n)).Q)\nA = V*Diagonal(λs)*V'\nA = 0.5(A + A')\n\n# Build system\nxtrue = randn(n)\nb = A * xtrue\n\n# Build preconditioner\nr = 110\nk = round(Int, r - 5)\nAnys = NystromSketch(A, k, r)\nP = RP.NystromPreconditionerInverse(Anys, μ)\n\n# Solve system\n_, stats_npc = cg(A, b; history=true)\n_, stats_nys = cg(A, b; history=true, M = P)\n_, stats_diag = cg(A, b; history=true, M=Diagonal(diag(A)))\n\nnb = norm(b)\nres_npc = prepend!(stats_npc.residuals, nb)\nres_nys = prepend!(stats_nys.residuals, nb)\nres_diag = prepend!(stats_diag.residuals, nb)\n\nplt_cg = plot(\n    res_npc,\n    dpi=300,\n    lw=2,\n    label=\"No Preconditioner\",\n    ylabel=\"residual\",\n    xlabel=\"iteration\",\n    title=\"Convergence of CG\",\n    legend=:topright,\n    yaxis=:log\n)\nplot!(plt_cg, \n    res_nys,\n    label=\"Nystrom Preconditioner\",\n    lw=2\n)\nplot!(plt_cg, \n    res_diag,\n    label=\"Diagonal Preconditioner\",\n    lw=2\n)\ndisplay(plt_cg)", "meta": {"hexsha": "edd1be312447c7a08dabea8a5c2e52721808e601", "size": 1184, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/pcg.jl", "max_stars_repo_name": "tjdiamandis/RandomizedPreconditioners.jl", "max_stars_repo_head_hexsha": "06de6c9797aab550e9b6dfd73e7bb80ca698f7c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2021-12-18T02:07:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T02:16:55.000Z", "max_issues_repo_path": "examples/pcg.jl", "max_issues_repo_name": "tjdiamandis/RandomizedPreconditioners.jl", "max_issues_repo_head_hexsha": "06de6c9797aab550e9b6dfd73e7bb80ca698f7c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-03-23T03:07:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T18:24:11.000Z", "max_forks_repo_path": "examples/pcg.jl", "max_forks_repo_name": "tjdiamandis/RandomizedPreconditioners.jl", "max_forks_repo_head_hexsha": "06de6c9797aab550e9b6dfd73e7bb80ca698f7c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0677966102, "max_line_length": 59, "alphanum_fraction": 0.6596283784, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7691912399611646}}
{"text": "\"\"\"\n    ot_plan(c, μ, ν; kwargs...)\n\nCompute the optimal transport plan for the Monge-Kantorovich problem with source and target\nmarginals `μ` and `ν` and cost `c`.\n\nThe optimal transport plan solves\n```math\n\\\\inf_{\\\\gamma \\\\in \\\\Pi(\\\\mu, \\\\nu)} \\\\int c(x, y) \\\\, \\\\mathrm{d}\\\\gamma(x, y)\n```\nwhere ``\\\\Pi(\\\\mu, \\\\nu)`` denotes the couplings of ``\\\\mu`` and ``\\\\nu``.\n\nSee also: [`ot_cost`](@ref)\n\"\"\"\nfunction ot_plan end\n\n\"\"\"\n    ot_cost(c, μ, ν; kwargs...)\n\nCompute the optimal transport cost for the Monge-Kantorovich problem with source and target\nmarginals `μ` and `ν` and cost `c`.\n\nThe optimal transport cost is the scalar value\n```math\n\\\\inf_{\\\\gamma \\\\in \\\\Pi(\\\\mu, \\\\nu)} \\\\int c(x, y) \\\\, \\\\mathrm{d}\\\\gamma(x, y)\n```\nwhere ``\\\\Pi(\\\\mu, \\\\nu)`` denotes the couplings of ``\\\\mu`` and ``\\\\nu``.\n\nSee also: [`ot_plan`](@ref)\n\"\"\"\nfunction ot_cost end\n\n#############\n# Discrete OT\n#############\n\n\"\"\"\n    emd(μ, ν, C, optimizer)\n\nCompute the optimal transport plan `γ` for the Monge-Kantorovich problem with source\nhistogram `μ`, target histogram `ν`, and cost matrix `C` of size `(length(μ), length(ν))`\nwhich solves\n```math\n\\\\inf_{γ ∈ Π(μ, ν)} \\\\langle γ, C \\\\rangle.\n```\n\nThe corresponding linear programming problem is solved with the user-provided `optimizer`.\nPossible choices are `Tulip.Optimizer()` and `Clp.Optimizer()` in the `Tulip` and `Clp`\npackages, respectively.\n\"\"\"\nfunction emd(μ, ν, C, model::MOI.ModelLike)\n    # check size of cost matrix\n    nμ = length(μ)\n    nν = length(ν)\n    size(C) == (nμ, nν) || error(\"cost matrix `C` must be of size `(length(μ), length(ν))`\")\n    nC = length(C)\n\n    # define variables\n    x = MOI.add_variables(model, nC)\n    xmat = reshape(x, nμ, nν)\n\n    # define objective function\n    T = float(eltype(C))\n    zero_T = zero(T)\n    MOI.set(\n        model,\n        MOI.ObjectiveFunction{MOI.ScalarAffineFunction{T}}(),\n        MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(float.(vec(C)), x), zero_T),\n    )\n    MOI.set(model, MOI.ObjectiveSense(), MOI.MIN_SENSE)\n\n    # add non-negativity constraints\n    for xi in x\n        MOI.add_constraint(model, MOI.SingleVariable(xi), MOI.GreaterThan(zero_T))\n    end\n\n    # add constraints for source\n    for (i, μi) in zip(axes(xmat, 1), μ) # eachrow(xmat) is not available on Julia 1.0\n        f = MOI.ScalarAffineFunction(\n            [MOI.ScalarAffineTerm(one(μi), xi) for xi in view(xmat, i, :)], zero(μi)\n        )\n        MOI.add_constraint(model, f, MOI.EqualTo(μi))\n    end\n\n    # add constraints for target\n    for (i, νi) in zip(axes(xmat, 2), ν) # eachcol(xmat) is not available on Julia 1.0\n        f = MOI.ScalarAffineFunction(\n            [MOI.ScalarAffineTerm(one(νi), xi) for xi in view(xmat, :, i)], zero(νi)\n        )\n        MOI.add_constraint(model, f, MOI.EqualTo(νi))\n    end\n\n    # compute optimal solution\n    MOI.optimize!(model)\n    status = MOI.get(model, MOI.TerminationStatus())\n    status === MOI.OPTIMAL || error(\"failed to compute optimal transport plan: \", status)\n    p = MOI.get(model, MOI.VariablePrimal(), x)\n    γ = reshape(p, nμ, nν)\n\n    return γ\nend\n\n\"\"\"\n    emd2(μ, ν, C, optimizer; plan=nothing)\n\nCompute the optimal transport cost (a scalar) for the Monge-Kantorovich problem with source\nhistogram `μ`, target histogram `ν`, and cost matrix `C` of size `(length(μ), length(ν))`\nwhich is given by\n```math\n\\\\inf_{γ ∈ Π(μ, ν)} \\\\langle γ, C \\\\rangle.\n```\n\nThe corresponding linear programming problem is solved with the user-provided `optimizer`.\nPossible choices are `Tulip.Optimizer()` and `Clp.Optimizer()` in the `Tulip` and `Clp`\npackages, respectively.\n\nA pre-computed optimal transport `plan` may be provided.\n\"\"\"\nfunction emd2(μ, ν, C, optimizer; plan=nothing)\n    γ = if plan === nothing\n        # compute optimal transport plan\n        emd(μ, ν, C, optimizer)\n    else\n        # check dimensions\n        size(C) == (length(μ), length(ν)) ||\n            error(\"cost matrix `C` must be of size `(length(μ), length(ν))`\")\n        size(plan) == size(C) || error(\n            \"optimal transport plan `plan` and cost matrix `C` must be of the same size\",\n        )\n        plan\n    end\n    return dot(γ, C)\nend\n\n###################################\n# Semidiscrete and continuous 1D OT\n###################################\n\n\"\"\"\n    ot_plan(c, μ::ContinuousUnivariateDistribution, ν::UnivariateDistribution)\n\nCompute the optimal transport plan for the Monge-Kantorovich problem with univariate\ndistributions `μ` and `ν` as source and target marginals and cost function `c` of\nthe form ``c(x, y) = h(|x - y|)`` where ``h`` is a convex function.\n\nIn this setting, the optimal transport plan is the Monge map\n```math\nT = F_\\\\nu^{-1} \\\\circ F_\\\\mu\n```\nwhere ``F_\\\\mu`` is the cumulative distribution function of `μ` and ``F_\\\\nu^{-1}`` is the\nquantile function of `ν`.\n\nSee also: [`ot_cost`](@ref), [`emd`](@ref)\n\"\"\"\nfunction ot_plan(c, μ::ContinuousUnivariateDistribution, ν::UnivariateDistribution)\n    # Use T instead of γ to indicate that this is a Monge map.\n    T(x) = quantile(ν, cdf(μ, x))\n    return T\nend\n\n\"\"\"\n    ot_cost(\n        c, μ::ContinuousUnivariateDistribution, ν::UnivariateDistribution; plan=nothing\n    )\n\nCompute the optimal transport cost for the Monge-Kantorovich problem with univariate\ndistributions `μ` and `ν` as source and target marginals and cost function `c` of\nthe form ``c(x, y) = h(|x - y|)`` where ``h`` is a convex function.\n\nIn this setting, the optimal transport cost can be computed as\n```math\n\\\\int_0^1 c(F_\\\\mu^{-1}(x), F_\\\\nu^{-1}(x)) \\\\mathrm{d}x\n```\nwhere ``F_\\\\mu^{-1}`` and ``F_\\\\nu^{-1}`` are the quantile functions of `μ` and `ν`,\nrespectively.\n\nA pre-computed optimal transport `plan` may be provided.\n\nSee also: [`ot_plan`](@ref), [`emd2`](@ref)\n\"\"\"\nfunction ot_cost(\n    c, μ::ContinuousUnivariateDistribution, ν::UnivariateDistribution; plan=nothing\n)\n    cost, _ = if plan === nothing\n        quadgk(0, 1) do q\n            return c(quantile(μ, q), quantile(ν, q))\n        end\n    else\n        quadgk(0, 1) do q\n            x = quantile(μ, q)\n            return c(x, plan(x))\n        end\n    end\n    return cost\nend\n\n################\n# Discrete 1D OT\n################\n\n# internal iterator for discrete one-dimensional OT problems\n# it returns tuples that consist of the indices of the source and target histograms\n# and the optimal flow between the corresponding points\nstruct Discrete1DOTIterator{T,M,N}\n    mu::M\n    nu::N\nend\n\n# histograms `μ` and `ν` are expected to be iterators of the histograms where the\n# corresponding support is sorted\nfunction Discrete1DOTIterator(μ, ν)\n    T = Base.promote_eltype(μ, ν)\n    return Discrete1DOTIterator{T,typeof(μ),typeof(ν)}(μ, ν)\nend\n\nBase.IteratorEltype(::Type{<:Discrete1DOTIterator}) = Base.HasEltype()\nBase.eltype(::Type{<:Discrete1DOTIterator{T}}) where {T} = Tuple{Int,Int,T}\n\nBase.length(d::Discrete1DOTIterator) = length(d.mu) + length(d.nu) - 1\n\n# we iterate through the source and target histograms\nfunction Base.iterate(\n    d::Discrete1DOTIterator{T}, (i, j, μnext, νnext)=(1, 1, iterate(d.mu), iterate(d.nu))\n) where {T}\n    # if we are done with iterating through the source and/or target histogram,\n    # iteration is stopped\n    if μnext === nothing || νnext === nothing\n        return nothing\n    end\n\n    # unpack next values and states of the source and target histograms\n    μiter, μstate = μnext\n    νiter, νstate = νnext\n\n    # compute next value of the iterator: indices of source and target histograms\n    # and optimal flow between the corresponding points\n    min_iter, max_iter = minmax(μiter, νiter)\n    iter = (i, j, min_iter)\n\n    # compute next state of the iterator\n    diff = max_iter - min_iter\n    state = if μiter < max_iter\n        # move forward in the source histogram\n        (i + 1, j, iterate(d.mu, μstate), (diff, νstate))\n    else\n        # move forward in the target histogram\n        (i, j + 1, (diff, μstate), iterate(d.nu, νstate))\n    end\n\n    return iter, state\nend\n\n\"\"\"\n    ot_plan(c, μ::DiscreteNonParametric, ν::DiscreteNonParametric)\n\nCompute the optimal transport cost for the Monge-Kantorovich problem with univariate\ndiscrete distributions `μ` and `ν` as source and target marginals and cost function `c`\nof the form ``c(x, y) = h(|x - y|)`` where ``h`` is a convex function.\n\nIn this setting, the optimal transport plan can be computed analytically. It is returned as\na sparse matrix.\n\nSee also: [`ot_cost`](@ref), [`emd`](@ref)\n\"\"\"\nfunction ot_plan(_, μ::DiscreteNonParametric, ν::DiscreteNonParametric)\n    # unpack the probabilities of the two distributions\n    μprobs = probs(μ)\n    νprobs = probs(ν)\n\n    # create the iterator\n    # note: support of `DiscreteNonParametric` is sorted\n    iter = Discrete1DOTIterator(μprobs, νprobs)\n\n    # create arrays for the indices of the two histograms and the optimal flow between the\n    # corresponding points\n    n = length(iter)\n    I = Vector{Int}(undef, n)\n    J = Vector{Int}(undef, n)\n    W = Vector{Base.promote_eltype(μprobs, νprobs)}(undef, n)\n\n    # compute the sparse optimal transport plan\n    @inbounds for (idx, (i, j, w)) in enumerate(iter)\n        I[idx] = i\n        J[idx] = j\n        W[idx] = w\n    end\n    γ = sparse(I, J, W, length(μprobs), length(νprobs))\n\n    return γ\nend\n\n\"\"\"\n    ot_cost(\n        c, μ::DiscreteNonParametric, ν::DiscreteNonParametric; plan=nothing\n    )\n\nCompute the optimal transport cost for the Monge-Kantorovich problem with discrete\nunivariate distributions `μ` and `ν` as source and target marginals and cost function `c`\nof the form ``c(x, y) = h(|x - y|)`` where ``h`` is a convex function.\n\nIn this setting, the optimal transport cost can be computed analytically.\n\nA pre-computed optimal transport `plan` may be provided.\n\nSee also: [`ot_plan`](@ref), [`emd2`](@ref)\n\"\"\"\nfunction ot_cost(c, μ::DiscreteNonParametric, ν::DiscreteNonParametric; plan=nothing)\n    return _ot_cost(c, μ, ν, plan)\nend\n\n# compute cost from scratch if no plan is provided\nfunction _ot_cost(c, μ::DiscreteNonParametric, ν::DiscreteNonParametric, ::Nothing)\n    # unpack the probabilities of the two distributions\n    μprobs = probs(μ)\n    νprobs = probs(ν)\n\n    # create the iterator\n    # note: support of `DiscreteNonParametric` is sorted\n    iter = Discrete1DOTIterator(μprobs, νprobs)\n\n    # compute the cost\n    μsupport = support(μ)\n    νsupport = support(ν)\n    cost = sum(w * c(μsupport[i], νsupport[j]) for (i, j, w) in iter)\n\n    return cost\nend\n\n# if a sparse plan is provided, we just iterate through the non-zero entries\nfunction _ot_cost(\n    c, μ::DiscreteNonParametric, ν::DiscreteNonParametric, plan::SparseMatrixCSC\n)\n    # extract non-zero flows\n    I, J, W = findnz(plan)\n\n    # compute the cost\n    μsupport = support(μ)\n    νsupport = support(ν)\n    cost = sum(w * c(μsupport[i], νsupport[j]) for (i, j, w) in zip(I, J, W))\n\n    return cost\nend\n\n# fallback: compute cost matrix (probably often faster to compute cost from scratch)\nfunction _ot_cost(c, μ::DiscreteNonParametric, ν::DiscreteNonParametric, plan)\n    return dot(plan, StatsBase.pairwise(c, support(μ), support(ν)))\nend\n\n################\n# OT Gaussians\n################\n\n\"\"\"\n    ot_cost(::SqEuclidean, μ::MvNormal, ν::MvNormal)\n\nCompute the squared 2-Wasserstein distance between normal distributions `μ` and `ν` as\nsource and target marginals.\n\nIn this setting, the optimal transport cost can be computed as\n```math\nW_2^2(\\\\mu, \\\\nu) = \\\\|m_\\\\mu - m_\\\\nu \\\\|^2 + \\\\mathcal{B}(\\\\Sigma_\\\\mu, \\\\Sigma_\\\\nu)^2,\n```\nwhere ``\\\\mu = \\\\mathcal{N}(m_\\\\mu, \\\\Sigma_\\\\mu)``,\n``\\\\nu = \\\\mathcal{N}(m_\\\\nu, \\\\Sigma_\\\\nu)``, and ``\\\\mathcal{B}`` is the Bures metric.\n\nSee also: [`ot_plan`](@ref), [`emd2`](@ref)\n\"\"\"\nfunction ot_cost(::SqEuclidean, μ::MvNormal, ν::MvNormal)\n    return sqeuclidean(μ.μ, ν.μ) + sqbures(μ.Σ, ν.Σ)\nend\n\n\"\"\"\n    ot_cost(::SqEuclidean, μ::Normal, ν::Normal)\n\nCompute the squared 2-Wasserstein distance between univariate normal distributions `μ` and\n`ν` as source and target marginals.\n\nSee also: [`ot_plan`](@ref), [`emd2`](@ref)\n\"\"\"\nfunction ot_cost(::SqEuclidean, μ::Normal, ν::Normal)\n    return (μ.μ - ν.μ)^2 + (μ.σ - ν.σ)^2\nend\n\n\"\"\"\n    ot_plan(::SqEuclidean, μ::MvNormal, ν::MvNormal)\n\nCompute the optimal transport plan for the Monge-Kantorovich problem with multivariate\nnormal distributions `μ` and `ν` as source and target marginals and cost function\n``c(x, y) = \\\\|x - y\\\\|_2^2``.\n\nIn this setting, for ``\\\\mu = \\\\mathcal{N}(m_\\\\mu, \\\\Sigma_\\\\mu)`` and\n``\\\\nu = \\\\mathcal{N}(m_\\\\nu, \\\\Sigma_\\\\nu)``, the optimal transport plan is the Monge\nmap\n```math\nT \\\\colon x \\\\mapsto m_\\\\nu\n+ \\\\Sigma_\\\\mu^{-1/2}\n{\\\\big(\\\\Sigma_\\\\mu^{1/2} \\\\Sigma_\\\\nu \\\\Sigma_\\\\mu^{1/2}\\\\big)}^{1/2}\\\\Sigma_\\\\mu^{-1/2}\n(x - m_\\\\mu).\n```\n\nSee also: [`ot_cost`](@ref), [`emd`](@ref)\n\"\"\"\nfunction ot_plan(::SqEuclidean, μ::MvNormal, ν::MvNormal)\n    Σμsqrt = μ.Σ^(-1 / 2)\n    A = Σμsqrt * sqrt(_gaussian_ot_A(μ.Σ, ν.Σ)) * Σμsqrt\n    mμ = μ.μ\n    mν = ν.μ\n    T(x) = mν + A * (x - mμ)\n    return T\nend\n\n\"\"\"\n    ot_plan(::SqEuclidean, μ::Normal, ν::Normal)\n\nCompute the optimal transport plan for the Monge-Kantorovich problem with\nnormal distributions `μ` and `ν` as source and target marginals and cost function\n``c(x, y) = \\\\|x - y\\\\|_2^2``.\n\nSee also: [`ot_cost`](@ref), [`emd`](@ref)\n\"\"\"\nfunction ot_plan(::SqEuclidean, μ::Normal, ν::Normal)\n    mμ = μ.μ\n    mν = ν.μ\n    a = ν.σ / μ.σ\n    T(x) = mν + a * (x - mμ)\n    return T\nend\n", "meta": {"hexsha": "82ea71da96e3b5e524764ab720d53ce2c6ca76eb", "size": 13381, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/exact.jl", "max_stars_repo_name": "zsteve/OptimalTransport.jl", "max_stars_repo_head_hexsha": "ab9bc76a13c106f451ef58126cab07758f905f3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2020-05-07T13:52:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T21:34:03.000Z", "max_issues_repo_path": "src/exact.jl", "max_issues_repo_name": "juliohm/ExactOptimalTransport.jl", "max_issues_repo_head_hexsha": "1b1d3da31fdbc13f6488c49c10b453ac47baf75c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 49, "max_issues_repo_issues_event_min_datetime": "2020-05-15T16:48:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-18T18:38:46.000Z", "max_forks_repo_path": "src/exact.jl", "max_forks_repo_name": "juliohm/ExactOptimalTransport.jl", "max_forks_repo_head_hexsha": "1b1d3da31fdbc13f6488c49c10b453ac47baf75c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-05-27T21:56:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-19T19:15:09.000Z", "avg_line_length": 31.2640186916, "max_line_length": 92, "alphanum_fraction": 0.646737912, "num_tokens": 4089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7691912384893007}}
{"text": "# Simple ridge regression based upon the sindy-mpc\n# repository, see https://arxiv.org/abs/1711.05501\n# and https://github.com/eurika-kaiser/SINDY-MPC/blob/master/LICENSE\n\n\"\"\"\n$(TYPEDEF)\n`STLQS` is taken from the [original paper on SINDY](https://www.pnas.org/content/113/15/3932) and implements a\nsequentially thresholded least squares iteration. `λ` is the threshold of the iteration.\nIt is based upon [this matlab implementation](https://github.com/eurika-kaiser/SINDY-MPC/utils/sparsifyDynamics.m).\nIt solves the following problem\n```math\n\\\\argmin_{x} \\\\frac{1}{2} \\\\| Ax-b\\\\|_2 + \\\\lambda \\\\|x\\\\|_2\n```\n\n# Fields\n$(FIELDS)\n\n# Example\n```julia\nopt = STLQS()\nopt = STLQS(1e-1)\nopt = STLQS(Float32[1e-2; 1e-1])\n```\n## Note\nThis was formally `STRRidge` and has been renamed.\n\"\"\"\nmutable struct STLSQ{T} <: AbstractOptimizer{T}\n    \"\"\"Sparsity threshold\"\"\"\n    λ::T\n\n    function STLSQ(threshold::T = 1e-1) where T\n        @assert all(threshold .> zero(eltype(threshold))) \"Threshold must be positive definite\"\n\n        return new{typeof(threshold)}(threshold)\n    end\n\nend\n\nBase.summary(::STLSQ) = \"STLSQ\"\n\nfunction (opt::STLSQ{T})(X, A, Y, λ::U = first(opt.λ);\n    maxiter = maximum(size(A)), abstol::U = eps(eltype(T)),\n    progress = nothing, kwargs...) where {T,U}\n\n    smallinds = abs.(X) .<= λ\n    biginds = @. ! smallinds[:, 1]\n\n    x_i = similar(X)\n    x_i .= X\n\n    xzero = zero(eltype(X))\n    obj = xzero\n    sparsity = xzero\n    conv_measure = xzero\n\n    iters = 0\n    converged = false\n\n    _progress = isa(progress, Progress)\n    initial_prog = _progress ? progress.counter : 0\n\n\n    @views while (iters < maxiter) && !converged\n        iters += 1\n\n        smallinds .= abs.(X) .<= λ\n        X[smallinds] .= xzero\n\n        for j in 1:size(Y, 2)\n            @. biginds = ! smallinds[:, j]\n            X[biginds, j] .= A[:, biginds] \\ Y[:,j]\n        end\n\n        conv_measure = norm(x_i .- X, 2)\n\n        if _progress\n            obj = norm(Y - A*X, 2)\n            sparsity = norm(X, 0, λ)\n\n            ProgressMeter.next!(\n            progress;\n            showvalues = [\n                (:Threshold, λ), (:Objective, obj), (:Sparsity, sparsity),\n                (:Convergence, conv_measure)\n            ]\n            )\n        end\n\n        if conv_measure < abstol\n            converged = true\n\n            _progress ? (progress.counter = initial_prog + maxiter) : nothing\n\n            #    ProgressMeter.update!(\n            #    progress,\n            #    initial_prog + maxiter\n            #    )\n            #end\n\n\n        else\n            x_i .= X\n        end\n    end\n\n    clip_by_threshold!(X, λ; kwargs...)\n    return\nend\n", "meta": {"hexsha": "1d8d879c1ea9b7a4603e9a130446b9e49046c376", "size": 2643, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/optimizers/stlsq.jl", "max_stars_repo_name": "augustinas1/DataDrivenDiffEq.jl", "max_stars_repo_head_hexsha": "dda0763d7e9689c78cc2afc7179f9d574a1d4698", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/optimizers/stlsq.jl", "max_issues_repo_name": "augustinas1/DataDrivenDiffEq.jl", "max_issues_repo_head_hexsha": "dda0763d7e9689c78cc2afc7179f9d574a1d4698", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimizers/stlsq.jl", "max_forks_repo_name": "augustinas1/DataDrivenDiffEq.jl", "max_forks_repo_head_hexsha": "dda0763d7e9689c78cc2afc7179f9d574a1d4698", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.247706422, "max_line_length": 115, "alphanum_fraction": 0.5705637533, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.8333245953120234, "lm_q1q2_score": 0.7691912380507574}}
{"text": "using LinearAlgebra: diagm\nusing SparseArrays: sparse\n\nnormalize_indicator(i::AbstractArray) = i ./ sum(i)\nnormalize_indicator(i::AbstractArray, dims) = i ./ sum(i, dims=dims)\n\nto_indicator_matrix(i::AbstractVector) = diagm(i)\n\nfunction union_diagonal!(A::AbstractMatrix{T}) where {T}\n    for i in 1:min(size(A)...)\n        A[i, i] = one(T)\n    end\n    return A\nend\n\n_generate_slices(n, k) = Base.ntuple(i->(i==n) ? k : Colon(), 2)\n\n\"\"\"\n    graph_filter(ind, order)\n\nGenerate a graph filter of `order`-th order moment depending on the indicator `ind`.\n\n## Arguments\n- `ind`: the indicator vector or matrix with values of 0s or 1s. \n- `order`: the order of moment for a graph filter. If `order=1`, generates a first moment graph filter,\nwhich is the mean operator. If `order=2`, generates a second moment graph filter, which is the covariance operator.\n\"\"\"\nfunction graph_filter(ind::AbstractVector, order::Integer)\n    if order == 1\n        return sparse(normalize_indicator(ind))\n    elseif order == 2\n        adj = to_indicator_matrix(ind)\n        return sparse(normalize_indicator(adj))\n    else\n        throw(ArgumentError(\"order other than 1 and 2 is not supported while get $order.\"))\n    end\nend\n\nfunction graph_filter(adj::AbstractMatrix, order::Integer; dims::Integer=1, self::Bool=true)\n    if order == 1\n        self && union_diagonal!(adj)\n        return sparse(normalize_indicator(adj, dims))\n    elseif order == 2\n        n = dims%2 + 1\n        blocks = [graph_filter(vec(adj[_generate_slices(n, k)...]), 2) for k in 1:size(adj, n)]\n        return cat(blocks...,dims=(1,2))\n    else\n        throw(ArgumentError(\"order other than 1 and 2 is not supported while get $order.\"))\n    end\nend\n\nfunction moment(A::AbstractMatrix, X::AbstractMatrix, order::Integer; dims::Integer=1)\n    if order == 1\n        return first_moment(A, X; dims=dims)\n    elseif order == 2\n        return second_moment(A, X; dims=dims)\n    else\n        throw(ArgumentError(\"order other than 1 and 2 is not supported while get $order.\"))\n    end\nend\n\nfunction first_moment(A::AbstractMatrix, X::AbstractMatrix; dims::Integer=1)\n    adj = A .> 0\n    if dims == 1\n        G = graph_filter(adj, 1; dims=1)\n        return G*X\n    elseif dims == 2\n        G = graph_filter(adj, 1; dims=2)\n        return X*G\n    else\n        throw(ArgumentError(\"dims other than 1 and 2 is not supported while get $dims.\"))\n    end\nend\n\n# second_moment(A::AbstractMatrix, X::AbstractMatrix; dims::Integer=1) = second_moment(A, X, X; dims=dims)\n\n# function second_moment(A::AbstractMatrix, X::AbstractMatrix, Y::AbstractMatrix; dims::Integer=1)\n#     # x' * G_2 * y - (G_1' * x)*(G_1' * y)\n#     adj = A .> 0\n#     if dims == 1\n#         G = graph_filter(adj, 2; dims=1)\n#         return X'*G*Y - first_moment(A, X; dims=1)*first_moment(A, Y; dims=1)'\n#     elseif dims == 2\n#         G = graph_filter(adj, 2; dims=2)\n#         return vec(X')'*G*vec(Y') - first_moment(A, X; dims=2)*first_moment(A, Y; dims=2)'\n#     else\n#         throw(ArgumentError(\"dims other than 1 and 2 is not supported while get $dims.\"))\n#     end\n# end\n", "meta": {"hexsha": "904edabf23a5d5b77942b674f71ef9008693e4b8", "size": 3090, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/moments.jl", "max_stars_repo_name": "yuehhua/SnowyOwl.jl", "max_stars_repo_head_hexsha": "0ca35a190b508ae1b5496e873ade63d6731c3633", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/moments.jl", "max_issues_repo_name": "yuehhua/SnowyOwl.jl", "max_issues_repo_head_hexsha": "0ca35a190b508ae1b5496e873ade63d6731c3633", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-02-16T14:40:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T05:24:51.000Z", "max_forks_repo_path": "src/moments.jl", "max_forks_repo_name": "yuehhua/SnowyOwl.jl", "max_forks_repo_head_hexsha": "0ca35a190b508ae1b5496e873ade63d6731c3633", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3333333333, "max_line_length": 115, "alphanum_fraction": 0.6449838188, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.769191230409128}}
{"text": "module ComplexBigMatrices\n\n\"\"\"\nThis module calculates exp(), log() and eigen() of a complex BigFloat Matrix.\n\"\"\"\n\nexport exp, log, eigen\nimport .Base: exp, log\n\nusing LinearAlgebra\nusing GenericLinearAlgebra\nusing GenericSchur\n\n\"\"\"\n    exp(a::Matrix{Complex{BigFloat}})\nExtends exp() to work with Matrix{Complex{BigFloat}}\n\"\"\"\nfunction exp(a::Matrix{Complex{BigFloat}})\n    eig = eigen(a)\n    eig.vectors*Diagonal(exp.(eig.values))*eig.vectors^(-1)\nend\n\n\n\"\"\"\n    log(a::Matrix{Complex{BigFloat}})\nExtends log() to work with Matrix{Complex{BigFloat}}\n\"\"\"\nfunction log(a::Matrix{Complex{BigFloat}})\n    eig = eigen(a)\n    eig.vectors*Diagonal(log.(eig.values))*eig.vectors^(-1)\nend\n\n\n\"\"\"\n    eigen(a::Matrix{Complex{BigFloat}})\nExtends eigen() to work with Matrix{Complex{BigFloat}}\n\"\"\"\nfunction eigen(a::Matrix{Complex{BigFloat}})\n    LinearAlgebra.eigen(a)\nend\n\nend\n", "meta": {"hexsha": "3f3124f229e96fd71039eafbc338a96f8f5b013a", "size": 866, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ComplexBigMatrices.jl", "max_stars_repo_name": "MalayMDas/ComplexBigMatrices.jl", "max_stars_repo_head_hexsha": "4c857f7c55cd897fb8032f1ce8c91f0822ea8f10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ComplexBigMatrices.jl", "max_issues_repo_name": "MalayMDas/ComplexBigMatrices.jl", "max_issues_repo_head_hexsha": "4c857f7c55cd897fb8032f1ce8c91f0822ea8f10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-25T13:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-29T23:18:11.000Z", "max_forks_repo_path": "src/ComplexBigMatrices.jl", "max_forks_repo_name": "MalayMDas/ComplexBigMatrices.jl", "max_forks_repo_head_hexsha": "4c857f7c55cd897fb8032f1ce8c91f0822ea8f10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1395348837, "max_line_length": 77, "alphanum_fraction": 0.7032332564, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632329799585, "lm_q2_score": 0.8080672112416736, "lm_q1q2_score": 0.7691694681575985}}
{"text": "using JuMP, Mosek, MosekTools, LinearAlgebra, Suppressor, StatsBase, Ipopt, Gurobi\n\nfunction solveNNMFRelax(A, theK)\n    mod=Model(Mosek.Optimizer)\n    n=size(A,1)\n\n    @variable(mod, X[1:n, 1:n], PSD)\n    @variable(mod, Y[1:n, 1:n], Symmetric)\n    @variable(mod, theta[1:n, 1:n], Symmetric)\n    @constraint(mod, X.>=0.0)\n\n    @constraint(mod, Symmetric(Matrix(1.0I, n, n).-Y) in PSDCone());\n\n    @constraint(mod,Symmetric([theta X; X' Y]) in PSDCone());\n\n    @constraint(mod, sum(Y[i,i] for i=1:n)<=theK)\n\n    @objective(mod, Min, sum(theta[i,i] for i=1:n)-2.0*Compat.dot(A, X)+Compat.dot(A,A))\n\n    optimize!(mod)\n\n\n    @show ofv_dual=objective_value(mod)\n    Y_0=value.(Y)\n    # solve for U\n    mod_U=Model(Mosek.Optimizer)\n    @variable(mod_U, U[1:n,1:theK]>=0.0)\n    @variable(mod_U, t)\n    @constraint(mod_U, [t; 1.0; vec(U-Y_0*U)] in RotatedSecondOrderCone());\n    @constraint(mod_U, Y_0*U.>=0.0)\n    @suppress optimize!(mod_U)\n    U_0=value.(U)\n\n    # Solve for a SDD^+ D, where A~=U_0*D*U_0'. Note that 2x2 non-neg psd matrices are completely positive, so this is a valid inner approx.\n    mod2=Model(Mosek.Optimizer)\n    @variable(mod2, D[1:theK, 1:theK], Symmetric)\n    @variable(mod2, M[1:theK, 1:theK, 1:2, 1:2]>=0.0);\n    @constraint(mod2, defineM1[i=1:theK, j=1:theK], M[i,j,1,2]==M[i,j,2,1]);\n    @constraint(mod2, defineM2[i=1:theK, j=1:theK], [M[i,j,1,1]; M[i,j,2,2]; M[i,j, 1,2]] in RotatedSecondOrderCone());\n    @constraint(mod2, defineD[i=1:theK, j=(i+1):theK], D[i,j]==M[i,j,1,2])\n    @constraint(mod2, defineD2[i=1:theK], D[i,i]==sum(M[i,l,2,2] for l=1:(i-1))+sum(M[i,l,1,1] for l=(i+1):theK))\n\n    @variable(mod2, t)\n    @constraint(mod2, [t; 1.0; vec(A-U_0*D*U_0')] in RotatedSecondOrderCone());\n    @objective(mod2, Min, t)\n    optimize!(mod2)\n    X_rounded=U_0*value.(D)*U_0'\n\n    return X_rounded, ofv_dual, objective_value(mod2), U_0*sqrt(value.(D))\nend\n\nfunction solveBM(A, k, V_t)\n    n=size(A,1)\n    ofv_prev=1e10\n    ofv_best=1e10\n    V_t_best=V_t\n    maxEpochs=100\n    rho=0.0001\n    # V_t=rand(n,k)\n\n    for t=1:maxEpochs\n\n    mod1=Model(Mosek.Optimizer)\n\n    @variable(mod1, U[1:n, 1:k])\n    @constraint(mod1, U.>=0.0)\n\n    @objective(mod1, Min, (sum((A[i,j]-U[i,:]'*V_t[j,:])^2 for i=1:n for j=1:n))+rho*sum((U[i,j]-V_t[i,j])^2 for i=1:n for j=1:k))\n    @suppress optimize!(mod1)\n    # @show objective_value(mod1)\n\n    U_t=value.(U)\n\n    mod2=Model(Mosek.Optimizer)\n    @variable(mod2, V[1:n, 1:k])\n    @constraint(mod2, V.>=0.0)\n    @objective(mod2, Min, (sum((A[i,j]-U_t[i,:]'*V[j,:])^2 for i=1:n for j=1:n))+rho*sum((V[i,j]-U_t[i,j])^2 for i=1:n for j=1:k))\n    @suppress optimize!(mod2)\n    # @show objective_value(mod2)\n    V_t=value.(V)\n\n    @show ofv_current=norm(A.-V_t*V_t')^2 # Sometimes find a better solution near the end of the reg path but not actually at the end\n    if ofv_current<ofv_best\n        ofv_best=ofv_current\n        V_t_best=V_t\n    end\n    rho=min(rho*2.0, 1e5)\n\n    if abs(ofv_current-ofv_prev)<1e-4\n        break\n    end\n    ofv_prev=ofv_current\n\n    end\n\n    ofv_final=norm(A.-V_t_best*V_t_best')^2\n\n    return V_t_best*V_t_best', ofv_final\nend\n", "meta": {"hexsha": "3c95f52f9068124e1f1ec3646efd343a47cb1ef3", "size": 3114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Matrix Factorization/convexpenalties.jl", "max_stars_repo_name": "ryancorywright/MatrixPerspectiveSoftware", "max_stars_repo_head_hexsha": "a65c57c317aaaf10298b8e059fcf366614451649", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-13T16:39:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T00:08:59.000Z", "max_issues_repo_path": "Matrix Factorization/convexpenalties.jl", "max_issues_repo_name": "ryancorywright/MatrixPerspectiveSoftware", "max_issues_repo_head_hexsha": "a65c57c317aaaf10298b8e059fcf366614451649", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Matrix Factorization/convexpenalties.jl", "max_forks_repo_name": "ryancorywright/MatrixPerspectiveSoftware", "max_forks_repo_head_hexsha": "a65c57c317aaaf10298b8e059fcf366614451649", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.14, "max_line_length": 140, "alphanum_fraction": 0.6188182402, "num_tokens": 1236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488963, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7691694681505579}}
{"text": "function LineLine(l1::Geometry, l2::Geometry)\n    #Ips = Array{Tuple{Point2D{Float64}, Float64, Float64}, 1}()\n    dx_cx = l2.Ep.x - l2.Sp.x\n    dy_cy = l2.Ep.y - l2.Sp.y\n    bx_ax = l1.Ep.x - l1.Sp.x\n    by_ay = l1.Ep.y - l1.Sp.y\n    Δ = bx_ax * dy_cy - by_ay * dx_cx\n    if abs(Δ) < 1e-4 # colinear\n        if l1.Ep.x == l2.Sp.x # l2 follows l1\n            return (intersect=true, type=\"connect\", Ip=Point4To2D(l1.Ep), Dist1=l1.Length, Dist2=0.0)\n        elseif l2.Ep.x == l1.Sp.x # l1 follows l2\n            return (intersect=true, type=\"connect\", Ip=Point4To2D(l1.Sp), Dist1=0.0, Dist2=l2.Length)\n        elseif onSegment(l1.Sp, l1.Ep, l2.Sp)\n            return (intersect=true, type=\"overlap\", Ip=Point4To2D(l2.Sp), Dist1=Distance2D(l1.Sp, l2.Sp), Dist2=0.0)\n        elseif onSegment(l2.Sp, l2.Ep, l1.Sp)\n            return (intersect=true, type=\"overlap\", Ip=Point4To2D(l1.Sp), Dist1=0.0, Dist2=Distance2D(l2.Sp, l1.Sp))\n        else\n            return (intersect=false, type=\"none\")\n        end\n    else # not colinear\n        ax_cx = l1.Sp.x - l2.Sp.x\n        ay_cy = l1.Sp.y - l2.Sp.y\n        r = (ay_cy * dx_cx - ax_cx * dy_cy) / Δ\n        s = (ay_cy * bx_ax - ax_cx * by_ay) / Δ\n        if (0.0 <= r <= 1.0 &&  0.0 <= s <= 1.0)  # intersection within 2 line-segments\n            Ix = l1.Sp.x + r * bx_ax\n            Iy = l1.Sp.y + r * by_ay\n            Ipc = Point2D(Ix, Iy)\n            dist1 = Distance2D(Point4To2D(l1.Sp), Ipc)\n            dist2 = Distance2D(Point4To2D(l2.Sp), Ipc)\n            return (intersect=true, type=\"cross\", Ip=Ipc, Dist1=dist1, Dist2=dist2)\n        else\n            return (intersect=false, type=\"none\")\n        end\n    end\nend\n\nfunction onSegment(Sp::Point4D{Float64}, Ep::Point4D{Float64}, Pi::Point4D{Float64})\n    if (Pi.x <= max(Sp.x, Ep.x) && Pi.x >= min(Sp.x, Ep.x) &&\n        Pi.y <= max(Sp.y, Ep.y) && Pi.y >= min(Sp.y, Ep.y))\n        return true\n    else\n        return false\n    end\nend\n", "meta": {"hexsha": "f8689ff4dadd3deb31fbe96f29d79edcb55a42c2", "size": 1937, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LineLine.jl", "max_stars_repo_name": "mexsser/Geo.jl", "max_stars_repo_head_hexsha": "c75bac49bbfe876b1038caa46360231ceb6d405c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LineLine.jl", "max_issues_repo_name": "mexsser/Geo.jl", "max_issues_repo_head_hexsha": "c75bac49bbfe876b1038caa46360231ceb6d405c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LineLine.jl", "max_forks_repo_name": "mexsser/Geo.jl", "max_forks_repo_head_hexsha": "c75bac49bbfe876b1038caa46360231ceb6d405c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1086956522, "max_line_length": 116, "alphanum_fraction": 0.5549819308, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7691694648402351}}
{"text": "function chebyshev_weights(f::AbstractArray{T,N},nodes::NTuple{N,Array{T,1}},order::Array{S,1},domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n\n  poly = Array{Array{T,2},1}(undef,N)\n  \n  @inbounds for i = 1:N\n    poly[i] = chebyshev_polynomial(order[i],normalize_node(nodes[i],domain[:,i]))\n  end\n  \n  weights = Array{T,N}(undef,Tuple(order.+1))\n    \n  @inbounds for i in CartesianIndices(weights)\n  \n    numerator   = zero(T)\n    denominator = zero(T)\n  \n    @inbounds for s in CartesianIndices(f)\n  \n      product = one(T)\n      @inbounds for j = 1:N\n        product *= poly[j][s[j],i[j]]\n      end\n  \n      numerator   += f[s]*product\n      denominator += product^2\n  \n    end\n  \n    weights[i] = numerator/denominator\n  \n  end\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extrema(f::AbstractArray{T,N},nodes::NTuple{N,Array{T,1}},order::Array{S,1},domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  n = size(f)\n  \n  poly = Array{Array{T,2},1}(undef,N)\n  \n  @inbounds for i = 1:N\n    poly[i] = chebyshev_polynomial(order[i],normalize_node(nodes[i],domain[:,i]))\n  end\n  \n  weights = Array{T,N}(undef,Tuple(order.+1))\n    \n  @inbounds for i in CartesianIndices(weights)\n  \n    numerator   = zero(T)\n    denominator = zero(T)\n  \n    @inbounds for s in CartesianIndices(f)\n  \n      num = f[s]\n      den = one(T)\n      @inbounds for j = 1:N\n        if s[j] === 1 || s[j] === n[j]\n          scale = 0.5  \n        else\n          scale = 1.0\n        end\n        temp = poly[j][s[j],i[j]]\n        num *= temp*scale\n        den *= (temp^2)*scale\n      end\n  \n      numerator   += num\n      denominator += den\n  \n    end\n  \n    weights[i] = numerator/denominator\n  \n  end\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extended(f::AbstractArray{T,N},nodes::NTuple{N,Array{T,1}},order::Array{S,1},domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  poly       = Array{Array{T,2},1}(undef,N)\n  complement = Array{Array{T,2},1}(undef,N)\n  \n  @inbounds for i = 1:N\n    poly[i]       = chebyshev_polynomial(order[i],normalize_node(nodes[i],domain[:,i]))\n    complement[i] = pinv(poly[i])'\n  end\n  \n  weights = Array{T,N}(undef,Tuple(order.+1))\n    \n  @inbounds for i in CartesianIndices(weights)\n  \n    numerator   = zero(T)\n    denominator = zero(T)\n\n    @inbounds for s in CartesianIndices(f)\n  \n      num = f[s]\n      den = one(T)\n      @inbounds for j = 1:N\n        temp = complement[j][s[j],i[j]]\n        num *= temp\n        den *= temp*poly[j][s[j],i[j]]\n      end\n  \n      numerator   += num\n      denominator += den\n  \n    end\n  \n    weights[i] = numerator/denominator\n  \n  end\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights(f::AbstractArray{T,N},poly::NTuple{N,Array{T,2}},order::Array{S,1}) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = Array{T,N}(undef,Tuple(order.+1))\n    \n  @inbounds for i in CartesianIndices(weights)\n  \n    numerator   = zero(T)\n    denominator = zero(T)\n  \n    @inbounds for s in CartesianIndices(f)\n  \n      product = one(T)\n      @inbounds for j = 1:N\n        product *= poly[j][s[j],i[j]]\n      end\n  \n      numerator   += f[s]*product\n      denominator += product^2\n  \n    end\n  \n    weights[i] = numerator/denominator\n  \n  end\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extrema(f::AbstractArray{T,N},poly::NTuple{N,Array{T,2}},order::Array{S,1}) where {T<:AbstractFloat,N,S<:Integer}\n  \n  n = size(f)\n  \n  weights = Array{T,N}(undef,Tuple(order.+1))\n    \n  @inbounds for i in CartesianIndices(weights)\n  \n    numerator   = zero(T)\n    denominator = zero(T)\n  \n    @inbounds for s in CartesianIndices(f)\n  \n      num = f[s]\n      den = one(T)\n      @inbounds for j = 1:N\n        if s[j] == 1 || s[j] == n[j]\n          scale = 0.5  \n        else\n          scale = 1.0\n        end\n        temp = poly[j][s[j],i[j]]\n        num *= temp*scale\n        den *= (temp^2)*scale\n      end\n  \n      numerator   += num\n      denominator += den\n  \n    end\n  \n    weights[i] = numerator/denominator\n  \n  end\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extended(f::AbstractArray{T,N},poly::NTuple{N,Array{T,2}},order::Array{S,1}) where {T<:AbstractFloat,N,S<:Integer}\n  \n  complement = Array{Array{T,2},1}(undef,N)\n  \n  @inbounds for i = 1:N\n    complement[i] = pinv(poly[i])'\n  end\n  \n  weights = Array{T,N}(undef,Tuple(order.+1))\n    \n  @inbounds for i in CartesianIndices(weights)\n  \n    numerator   = zero(T)\n    denominator = zero(T)\n  \n    @inbounds for s in CartesianIndices(f)\n  \n      num = f[s]\n      den = one(T)\n      @inbounds for j = 1:N\n        temp = complement[j][s[j],i[j]]\n        num *= temp\n        den *= temp*poly[j][s[j],i[j]]\n      end\n  \n      numerator   += num\n      denominator += den\n  \n    end\n  \n    weights[i] = numerator/denominator\n  \n  end\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights(f::AbstractArray{T,N},nodes::NTuple{N,Array{T,1}},order::S,domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  poly = Array{Array{T,2},1}(undef,N)\n  \n  @inbounds for i = 1:N\n    poly[i] = chebyshev_polynomial(order,normalize_node(nodes[i],domain[:,i]))\n  end\n  \n  ord = (order,)\n  for i = 2:N\n    ord = (ord...,order)\n  end\n  \n  weights = Array{T,N}(undef,ord.+1)\n  \n  @inbounds for i in CartesianIndices(weights)\n    if sum(Tuple(i)) <= order+N\n  \n      numerator   = zero(T)\n      denominator = zero(T)\n  \n      @inbounds for s in CartesianIndices(f)\n  \n        product = one(T)\n        @inbounds for j = 1:N\n          product *= poly[j][s[j],i[j]]\n        end\n    \n        numerator   += f[s]*product\n        denominator += product^2\n    \n      end\n  \n      weights[i] = numerator/denominator\n      \n    else\n      weights[i] = zero(T)\n    end\n  \n  end\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extrema(f::AbstractArray{T,N},nodes::NTuple{N,Array{T,1}},order::S,domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  n = size(f)\n    \n  poly = Array{Array{T,2},1}(undef,N)\n  \n  @inbounds for i = 1:N\n    poly[i] = chebyshev_polynomial(order,normalize_node(nodes[i],domain[:,i]))\n  end\n  \n  ord = (order,)\n  for i = 2:N\n    ord = (ord...,order)\n  end\n  \n  weights = Array{T,N}(undef,ord.+1)\n    \n  @inbounds for i in CartesianIndices(weights)\n    if sum(Tuple(i)) <= order+N\n \n      numerator   = zero(T)\n      denominator = zero(T)\n    \n      @inbounds for s in CartesianIndices(f)\n    \n        num = f[s]\n        den = one(T)\n        @inbounds for j = 1:N\n          if s[j] == 1 || s[j] == n[j]\n            scale = 0.5  \n          else\n            scale = 1.0\n          end\n          temp = poly[j][s[j],i[j]]\n          num *= temp*scale\n          den *= (temp^2)*scale\n        end\n    \n        numerator   += num\n        denominator += den\n    \n      end\n    \n      weights[i] = numerator/denominator\n        \n    else\n      weights[i] = zero(T)\n    end\n    \n  end\n    \n  return weights\n    \nend\n  \nfunction chebyshev_weights_extended(f::AbstractArray{T,N},nodes::NTuple{N,Array{T,1}},order::S,domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  poly       = Array{Array{T,2},1}(undef,N)\n  complement = Array{Array{T,2},1}(undef,N)\n  \n  @inbounds for i = 1:N\n    poly[i]       = chebyshev_polynomial(order,normalize_node(nodes[i],domain[:,i]))\n    complement[i] = pinv(poly[i])'\n  end\n  \n  ord = (order,)\n  for i = 2:N\n    ord = (ord...,order)\n  end\n  \n  weights = Array{T,N}(undef,ord.+1)\n    \n  @inbounds for i in CartesianIndices(weights)\n    if sum(Tuple(i)) <= order+N\n  \n      numerator   = zero(T)\n      denominator = zero(T)\n    \n      @inbounds for s in CartesianIndices(f)\n    \n        num = f[s]\n        den = one(T)\n        @inbounds for j = 1:N\n          temp = complement[j][s[j],i[j]]\n          num *= temp\n          den *= temp*poly[j][s[j],i[j]]\n        end\n    \n        numerator   += num\n        denominator += den\n    \n      end\n    \n      weights[i] = numerator/denominator\n        \n    else\n      weights[i] = zero(T)\n    end\n    \n  end\n    \n  return weights\n    \nend\n  \nfunction chebyshev_weights(f::AbstractArray{T,N},poly::NTuple{N,Array{T,2}},order::S) where {T<:AbstractFloat,N,S<:Integer}\n  \n  ord = (order,)\n  for i = 2:N\n    ord = (ord...,order)\n  end\n    \n  weights = Array{T,N}(undef,ord.+1)\n    \n  @inbounds for i in CartesianIndices(weights)\n    if sum(Tuple(i)) <= order+N\n  \n      numerator   = zero(T)\n      denominator = zero(T)\n    \n      @inbounds for s in CartesianIndices(f)\n    \n        product = one(T)\n        @inbounds for j = 1:N\n          product *= poly[j][s[j],i[j]]\n        end\n    \n        numerator   += f[s]*product\n        denominator += product^2\n      \n      end\n    \n      weights[i] = numerator/denominator\n        \n    else\n      weights[i] = zero(T)\n    end\n    \n  end\n    \n  return weights\n    \nend\n  \nfunction chebyshev_weights_extrema(f::AbstractArray{T,N},poly::NTuple{N,Array{T,2}},order::S) where {T<:AbstractFloat,N,S<:Integer}\n  \n  n = size(f)\n  \n  ord = (order,)\n  for i = 2:N\n    ord = (ord...,order)\n  end\n    \n  weights = Array{T,N}(undef,ord.+1)\n    \n  @inbounds for i in CartesianIndices(weights)\n    if sum(Tuple(i)) <= order+N\n  \n      numerator   = zero(T)\n      denominator = zero(T)\n    \n      @inbounds for s in CartesianIndices(f)\n    \n        num = f[s]\n        den = one(T)\n        @inbounds for j = 1:N\n          if s[j] == 1 || s[j] == n[j]\n            scale = 0.5  \n          else\n            scale = 1.0\n          end\n          temp = poly[j][s[j],i[j]]\n          num *= temp*scale\n          den *= (temp^2)*scale\n        end\n    \n        numerator   += num\n        denominator += den\n    \n      end\n    \n      weights[i] = numerator/denominator\n        \n    else\n      weights[i] = zero(T)\n    end\n    \n  end\n    \n  return weights\n    \nend\n  \nfunction chebyshev_weights_extended(f::AbstractArray{T,N},poly::NTuple{N,Array{T,2}},order::S) where {T<:AbstractFloat,N,S<:Integer}\n  \n  complement = Array{Array{T,2},1}(undef,N)\n  @inbounds for i = 1:N\n    complement[i] = pinv(poly[i])'\n  end\n  \n  ord = (order,)\n  for i = 2:N\n    ord = (ord...,order)\n  end\n  \n  weights = Array{T,N}(undef,ord.+1)\n    \n  @inbounds for i in CartesianIndices(weights)\n    if sum(Tuple(i)) <= order+N\n\n      numerator   = zero(T)\n      denominator = zero(T)\n    \n      @inbounds for s in CartesianIndices(f)\n    \n        num = f[s]\n        den = one(T)\n        @inbounds for j = 1:N\n          temp = complement[j][s[j],i[j]]\n          num *= temp\n          den *= temp*poly[j][s[j],i[j]]\n        end\n    \n        numerator   += num\n        denominator += den\n    \n      end\n    \n      weights[i] = numerator/denominator\n        \n    else\n      weights[i] = zero(T)\n    end\n    \n  end\n    \n  return weights\n    \nend\n  \nfunction chebyshev_weights_threaded(f::AbstractArray{T,N},nodes::NTuple{N,Array{T,1}},order::Array{S,1},domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  poly = Array{Array{T,2},1}(undef,N)\n  \n  @inbounds for i = 1:N\n    poly[i] = chebyshev_polynomial(order[i],normalize_node(nodes[i],domain[:,i]))\n  end\n  \n  weights = zeros(Tuple(order.+1))\n    \n  @inbounds @sync @qthreads for i in CartesianIndices(weights)\n  \n    numerator   = zero(T)\n    denominator = zero(T)\n  \n    @inbounds for s in CartesianIndices(f)\n  \n      product = one(T)\n      @inbounds for j = 1:N\n        product *= poly[j][s[j],i[j]]\n      end\n  \n      numerator   += f[s]*product\n      denominator += product^2\n  \n    end\n  \n    weights[i] = numerator/denominator\n  \n  end\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extrema_threaded(f::AbstractArray{T,N},nodes::NTuple{N,Array{T,1}},order::Array{S,1},domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  n = size(f)\n  \n  poly = Array{Array{T,2},1}(undef,N)\n  \n  @inbounds for i = 1:N\n    poly[i] = chebyshev_polynomial(order[i],normalize_node(nodes[i],domain[:,i]))\n  end\n  \n  weights = zeros(Tuple(order.+1))\n    \n  @inbounds @sync @qthreads for i in CartesianIndices(weights)\n  \n    numerator   = zero(T)\n    denominator = zero(T)\n  \n    @inbounds for s in CartesianIndices(f)\n  \n      num = f[s]\n      den = one(T)\n      @inbounds for j = 1:N\n        if s[j] == 1 || s[j] == n[j]\n          scale = 0.5  \n        else\n          scale = 1.0\n        end\n        temp = poly[j][s[j],i[j]]\n        num *= temp*scale\n        den *= (temp^2)*scale\n      end\n  \n      numerator   += num\n      denominator += den\n  \n    end\n  \n    weights[i] = numerator/denominator\n  \n  end\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extended_threaded(f::AbstractArray{T,N},nodes::NTuple{N,Array{T,1}},order::Array{S,1},domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  poly       = Array{Array{T,2},1}(undef,N)\n  complement = Array{Array{T,2},1}(undef,N)\n  \n  @inbounds for i = 1:N\n    poly[i]       = chebyshev_polynomial(order[i],normalize_node(nodes[i],domain[:,i]))\n    complement[i] = pinv(poly[i])'\n  end\n  \n  weights = zeros(Tuple(order.+1))\n    \n  @inbounds @sync @qthreads for i in CartesianIndices(weights)\n  \n    numerator   = zero(T)\n    denominator = zero(T)\n  \n    @inbounds for s in CartesianIndices(f)\n  \n      num = f[s]\n      den = one(T)\n      @inbounds for j = 1:N\n        temp = complement[j][s[j],i[j]]\n        num *= temp\n        den *= temp*poly[j][s[j],i[j]]\n      end\n  \n      numerator   += num\n      denominator += den\n  \n    end\n  \n    weights[i] = numerator/denominator\n  \n  end\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_threaded(f::AbstractArray{T,N},poly::NTuple{N,Array{T,2}},order::Array{S,1}) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = Array{T,N}(undef,Tuple(order.+1))\n    \n  @inbounds @sync @qthreads for i in CartesianIndices(weights)\n  \n    numerator   = zero(T)\n    denominator = zero(T)\n  \n    @inbounds for s in CartesianIndices(f)\n  \n      product = one(T)\n      @inbounds for j = 1:N\n        product *= poly[j][s[j],i[j]]\n      end\n  \n      numerator   += f[s]*product\n      denominator += product^2\n  \n    end\n  \n    weights[i] = numerator/denominator\n  \n  end\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extrema_threaded(f::AbstractArray{T,N},poly::NTuple{N,Array{T,2}},order::Array{S,1}) where {T<:AbstractFloat,N,S<:Integer}\n  \n  n = size(f)\n  \n  weights = Array{T,N}(undef,Tuple(order.+1))\n    \n  @inbounds @sync @qthreads for i in CartesianIndices(weights)\n  \n    numerator   = zero(T)\n    denominator = zero(T)\n  \n    @inbounds for s in CartesianIndices(f)\n  \n      num = f[s]\n      den = one(T)\n      @inbounds for j = 1:N\n        if s[j] == 1 || s[j] == n[j]\n          scale = 0.5  \n        else\n          scale = 1.0\n        end\n        temp = poly[j][s[j],i[j]]\n        num *= temp*scale\n        den *= (temp^2)*scale\n      end\n  \n      numerator   += num\n      denominator += den\n  \n    end\n  \n    weights[i] = numerator/denominator\n  \n  end\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extended_threaded(f::AbstractArray{T,N},poly::NTuple{N,Array{T,2}},order::Array{S,1}) where {T<:AbstractFloat,N,S<:Integer}\n  \n  complement = Array{Array{T,2},1}(undef,N)\n  @inbounds for i = 1:N\n    complement[i] = pinv(poly[i])'\n  end\n  \n  weights = Array{T,N}(undef,Tuple(order.+1))\n    \n  @inbounds @sync @qthreads for i in CartesianIndices(weights)\n  \n    numerator   = zero(T)\n    denominator = zero(T)\n  \n    @inbounds for s in CartesianIndices(f)\n  \n      num = f[s]\n      den = one(T)\n      @inbounds for j = 1:N\n        temp = complement[j][s[j],i[j]]\n        num *= temp\n        den *= temp*poly[j][s[j],i[j]]\n      end\n  \n      numerator   += num\n      denominator += den\n  \n    end\n  \n    weights[i] = numerator/denominator\n  \n  end\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_threaded(f::AbstractArray{T,N},nodes::NTuple{N,Array{T,1}},order::S,domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  poly = Array{Array{T,2},1}(undef,N)\n  \n  @inbounds for i = 1:N\n    poly[i] = chebyshev_polynomial(order,normalize_node(nodes[i],domain[:,i]))\n  end\n  \n  ord = (order,)\n  for i = 2:N\n    ord = (ord...,order)\n  end\n    \n  weights = Array{T,N}(undef,ord.+1)\n    \n  @inbounds @sync @qthreads for i in CartesianIndices(weights)\n    if sum(Tuple(i)) <= order+N\n  \n      numerator   = zero(T)\n      denominator = zero(T)\n    \n      @inbounds for s in CartesianIndices(f)\n    \n        product = one(T)\n        @inbounds for j = 1:N\n          product *= poly[j][s[j],i[j]]\n        end\n    \n        numerator   += f[s]*product\n        denominator += product^2\n      \n      end\n    \n      weights[i] = numerator/denominator\n        \n    else\n      weights[i] = zero(T)\n    end\n    \n  end\n    \n  return weights\n    \nend\n  \nfunction chebyshev_weights_extrema_threaded(f::AbstractArray{T,N},nodes::NTuple{N,Array{T,1}},order::S,domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  n = size(f)\n  \n  poly = Array{Array{T,2},1}(undef,N)\n  \n  @inbounds for i = 1:N\n    poly[i] = chebyshev_polynomial(order,normalize_node(nodes[i],domain[:,i]))\n  end\n  \n  ord = (order,)\n  for i = 2:N\n    ord = (ord...,order)\n  end\n    \n  weights = Array{T,N}(undef,ord.+1)\n    \n  @inbounds @sync @qthreads for i in CartesianIndices(weights)\n    if sum(Tuple(i)) <= order+N\n  \n      numerator   = zero(T)\n      denominator = zero(T)\n    \n      @inbounds for s in CartesianIndices(f)\n    \n        num = f[s]\n        den = one(T)\n        @inbounds for j = 1:N\n          if s[j] == 1 || s[j] == n[j]\n            scale = 0.5  \n          else\n            scale = 1.0\n          end\n          temp = poly[j][s[j],i[j]]\n          num *= temp*scale\n          den *= (temp^2)*scale\n        end\n    \n        numerator   += num\n        denominator += den\n    \n      end\n    \n      weights[i] = numerator/denominator\n        \n    else\n      weights[i] = zero(T)\n    end\n    \n  end\n    \n  return weights\n    \nend\n  \nfunction chebyshev_weights_extended_threaded(f::AbstractArray{T,N},nodes::NTuple{N,Array{T,1}},order::S,domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  poly       = Array{Array{T,2},1}(undef,N)\n  complement = Array{Array{T,2},1}(undef,N)\n  \n  @inbounds for i = 1:N\n    poly[i]       = chebyshev_polynomial(order,normalize_node(nodes[i],domain[:,i]))\n    complement[i] = pinv(poly[i])'\n  end\n  \n  ord = (order,)\n  for i = 2:N\n    ord = (ord...,order)\n  end\n    \n  weights = Array{T,N}(undef,ord.+1)\n    \n  @inbounds @sync @qthreads for i in CartesianIndices(weights)\n    if sum(Tuple(i)) <= order+N\n  \n      numerator   = zero(T)\n      denominator = zero(T)\n    \n      @inbounds for s in CartesianIndices(f)\n    \n        num = f[s]\n        den = one(T)\n        @inbounds for j = 1:N\n          temp = complement[j][s[j],i[j]]\n          num *= temp\n          den *= temp*poly[j][s[j],i[j]]\n        end\n    \n        numerator   += num\n        denominator += den\n    \n      end\n    \n      weights[i] = numerator/denominator\n        \n    else\n      weights[i] = zero(T)\n    end\n    \n  end\n   \n  return weights\n    \nend\n  \nfunction chebyshev_weights_threaded(f::AbstractArray{T,N},poly::NTuple{N,Array{T,2}},order::S) where {T<:AbstractFloat,N,S<:Integer}\n  \n  ord = (order,)\n  for i = 2:N\n    ord = (ord...,order)\n  end\n      \n  weights = Array{T,N}(undef,ord.+1)\n    \n  @inbounds @sync @qthreads for i in CartesianIndices(weights)\n    if sum(Tuple(i)) <= order+N\n  \n      numerator   = zero(T)\n      denominator = zero(T)\n    \n      @inbounds for s in CartesianIndices(f)\n    \n        product = one(T)\n        @inbounds for j = 1:N\n          product *= poly[j][s[j],i[j]]\n        end\n    \n        numerator   += f[s]*product\n        denominator += product^2\n      \n      end\n    \n      weights[i] = numerator/denominator\n        \n    else\n      weights[i] = zero(T)\n    end\n    \n  end\n    \n  return weights\n    \nend\n  \nfunction chebyshev_weights_extrema_threaded(f::AbstractArray{T,N},poly::NTuple{N,Array{T,2}},order::S) where {T<:AbstractFloat,N,S<:Integer}\n  \n  n = size(f)\n  \n  ord = (order,)\n  for i = 2:N\n    ord = (ord...,order)\n  end\n      \n  weights = Array{T,N}(undef,ord.+1)\n    \n  @inbounds @sync @qthreads for i in CartesianIndices(weights)\n    if sum(Tuple(i)) <= order+N\n  \n      numerator   = zero(T)\n      denominator = zero(T)\n    \n      @inbounds for s in CartesianIndices(f)\n    \n        num = f[s]\n        den = one(T)\n        @inbounds for j = 1:N\n          if s[j] == 1 || s[j] == n[j]\n            scale = 0.5  \n          else\n            scale = 1.0\n          end\n          temp = poly[j][s[j],i[j]]\n          num *= temp*scale\n          den *= (temp^2)*scale\n        end\n    \n        numerator   += num\n        denominator += den\n    \n      end\n    \n      weights[i] = numerator/denominator\n        \n    else\n      weights[i] = zero(T)\n    end\n    \n  end\n    \n  return weights\n    \nend\n  \nfunction chebyshev_weights_extended_threaded(f::AbstractArray{T,N},poly::NTuple{N,Array{T,2}},order::S) where {T<:AbstractFloat,N,S<:Integer}\n  \n  complement = Array{Array{T,2},1}(undef,N)\n  @inbounds for i = 1:N\n    complement[i] = pinv(poly[i])'\n  end\n  \n  ord = (order,)\n  for i = 2:N\n    ord = (ord...,order)\n  end\n      \n  weights = Array{T,N}(undef,ord.+1)\n    \n  @inbounds @sync @qthreads for i in CartesianIndices(weights)\n    if sum(Tuple(i)) <= order+N\n  \n      numerator   = zero(T)\n      denominator = zero(T)\n    \n      @inbounds for s in CartesianIndices(f)\n    \n        num = f[s]\n        den = one(T)\n        @inbounds for j = 1:N\n          temp = complement[j][s[j],i[j]]\n          num *= temp\n          den *= temp*poly[j][s[j],i[j]]\n        end\n    \n        numerator   += num\n        denominator += den\n    \n      end\n    \n      weights[i] = numerator/denominator\n        \n    else\n      weights[i] = zero(T)\n    end\n    \n  end\n    \n  return weights\n    \nend\n\nfunction chebyshev_weights(cheb::ChebInterpRoots)\n  \n  weights = chebyshev_weights_threaded(cheb.data,cheb.nodes,cheb.order,cheb.domain)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights(cheb::ChebInterpExtrema)\n  \n  weights = chebyshev_weights_extrema_threaded(cheb.data,cheb.nodes,cheb.order,cheb.domain)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights(cheb::ChebInterpExtended)\n  \n  weights = chebyshev_weights_extended_threaded(cheb.data,cheb.nodes,cheb.order,cheb.domain)\n  \n  return weights\n  \nend\n\nfunction chebyshev_weights(cheb::ChebInterpVertesi)\n  \n  weights = chebyshev_weights_vertesi_threaded(cheb.data,cheb.nodes,cheb.order,cheb.domain)\n  \n  return weights\n  \nend\n\n# Functions for the one-variable case where the nodes are a vector\n  \nfunction chebyshev_weights(f::AbstractArray{T,1},nodes::Array{T,1},order::Union{S,Array{S,1}},domain=[one(T);-one(T)]) where {T<:AbstractFloat,S<:Integer}\n  \n  weights = chebyshev_weights(f,(nodes,),order,domain)\n    \n  return weights\n    \nend\n  \nfunction chebyshev_weights_extrema(f::AbstractArray{T,1},nodes::Array{T,1},order::Union{S,Array{S,1}},domain=[one(T);-one(T)]) where {T<:AbstractFloat,S<:Integer}\n  \n  weights = chebyshev_weights_extrema(f,(nodes,),order,domain)\n    \n  return weights\n    \nend\n  \nfunction chebyshev_weights_extended(f::AbstractArray{T,1},nodes::Array{T,1},order::Union{S,Array{S,1}},domain=[one(T);-one(T)]) where {T<:AbstractFloat,S<:Integer}\n  \n  weights = chebyshev_weights_extended(f,(nodes,),order,domain)\n    \n  return weights\n    \nend\n  \nfunction chebyshev_weights(f::AbstractArray{T,1},poly::Array{T,2},order::Union{S,Array{S,1}}) where {T<:AbstractFloat,S<:Integer}\n    \n  weights = chebyshev_weights(f,(poly,),order)\n    \n  return weights\n    \nend\n    \nfunction chebyshev_weights_extrema(f::AbstractArray{T,1},poly::Array{T,2},order::Union{S,Array{S,1}}) where {T<:AbstractFloat,S<:Integer}\n    \n  weights = chebyshev_weights_extrema(f,(poly,),order)\n    \n  return weights\n    \nend\n  \nfunction chebyshev_weights_extended(f::AbstractArray{T,1},poly::Array{T,2},order::Union{S,Array{S,1}}) where {T<:AbstractFloat,S<:Integer}\n    \n  weights = chebyshev_weights_extended(f,(poly,),order)\n    \n  return weights\n    \nend\n  \n# Functions that allow the nodes to be in an array of arrays\n  \nfunction chebyshev_weights(f::AbstractArray{T,N},nodes::Array{Array{T,1},1},order::Array{S,1},domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights(f,tuple(nodes...),order,domain)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extrema(f::AbstractArray{T,N},nodes::Array{Array{T,1},1},order::Array{S,1},domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n \n  weights = chebyshev_weights_extrema(f,tuple(nodes...),order,domain)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extended(f::AbstractArray{T,N},nodes::Array{Array{T,1},1},order::Array{S,1},domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_extended(f,tuple(nodes...),order,domain)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights(f::AbstractArray{T,N},poly::Array{Array{T,2},1},order::Array{S,1}) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights(f,tuple(poly...),order)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extrema(f::AbstractArray{T,N},poly::Array{Array{T,2},1},order::Array{S,1}) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_extrema(f,tuple(poly...),order)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extended(f::AbstractArray{T,N},poly::Array{Array{T,2},1},order::Array{S,1}) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_extended(f,tuple(poly...),order)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights(f::AbstractArray{T,N},nodes::Array{Array{T,1},1},order::S,domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights(f,tuple(nodes...),order,domain)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extrema(f::AbstractArray{T,N},nodes::Array{Array{T,1},1},order::S,domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_extrema(f,tuple(nodes...),order,domain)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extended(f::AbstractArray{T,N},nodes::Array{Array{T,1},1},order::S,domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_extended(f,tuple(nodes...),order,domain)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights(f::AbstractArray{T,N},poly::Array{Array{T,2},1},order::S) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights(f,tuple(poly...),order)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extrema(f::AbstractArray{T,N},poly::Array{Array{T,2},1},order::S) where {T<:AbstractFloat,N,S<:Integer}\n \n  weights = chebyshev_weights_extrema(f,tuple(poly...),order)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extended(f::AbstractArray{T,N},poly::Array{Array{T,2},1},order::S) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_extended(f,tuple(poly...),order)\n  \n  return weights\n  \nend\n  \n# Threaded functions\n  \nfunction chebyshev_weights_threaded(f::AbstractArray{T,N},nodes::Array{Array{T,1},1},order::Array{S,1},domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_threaded(f,tuple(nodes...),order,domain)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extrema_threaded(f::AbstractArray{T,N},nodes::Array{Array{T,1},1},order::Array{S,1},domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_extrema_threaded(f,tuple(nodes...),order,domain)\n  \n  return weights\n\nend\n  \nfunction chebyshev_weights_extended_threaded(f::AbstractArray{T,N},nodes::Array{Array{T,1},1},order::Array{S,1},domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_extended_threaded(f,tuple(nodes...),order,domain)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_threaded(f::AbstractArray{T,N},poly::Array{Array{T,2},1},order::Array{S,1}) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_threaded(f,tuple(poly...),order)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extrema_threaded(f::AbstractArray{T,N},poly::Array{Array{T,2},1},order::Array{S,1}) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_extrema_threaded(f,tuple(poly...),order)\n  \n  return weights\n \nend\n  \nfunction chebyshev_weights_extended_threaded(f::AbstractArray{T,N},poly::Array{Array{T,2},1},order::Array{S,1}) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_extended_threaded(f,tuple(poly...),order)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_threaded(f::AbstractArray{T,N},nodes::Array{Array{T,1},1},order::S,domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_threaded(f,tuple(nodes...),order,domain)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extrema_threaded(f::AbstractArray{T,N},nodes::Array{Array{T,1},1},order::S,domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_extrema_threaded(f,tuple(nodes...),order,domain)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extended_threaded(f::AbstractArray{T,N},nodes::Array{Array{T,1},1},order::S,domain=[ones(T,1,N);-ones(T,1,N)]) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_extended_threaded(f,tuple(nodes...),order,domain)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_threaded(f::AbstractArray{T,N},poly::Array{Array{T,2},1},order::S) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_threaded(f,tuple(poly...),order)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extrema_threaded(f::AbstractArray{T,N},poly::Array{Array{T,2},1},order::S) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_extrema_threaded(f,tuple(poly...),order)\n  \n  return weights\n  \nend\n  \nfunction chebyshev_weights_extended_threaded(f::AbstractArray{T,N},poly::Array{Array{T,2},1},order::S) where {T<:AbstractFloat,N,S<:Integer}\n  \n  weights = chebyshev_weights_extended_threaded(f,tuple(poly...),order)\n  \n  return weights\n  \nend\n\nconst chebyshev_weights_vertesi          = chebyshev_weights_extended\nconst chebyshev_weights_vertesi_threaded = chebyshev_weights_extended_threaded\n", "meta": {"hexsha": "196dffd8ce91b05058146793e85408f5041ed920", "size": 30433, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chebyshev_weights.jl", "max_stars_repo_name": "RJDennis/ChebyshevApprox", "max_stars_repo_head_hexsha": "9b43654b3b7d00210ca2191b1173c79c7333dad3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-05-15T13:28:38.000Z", "max_stars_repo_stars_event_max_datetime": "2015-05-15T13:28:38.000Z", "max_issues_repo_path": "src/chebyshev_weights.jl", "max_issues_repo_name": "RJDennis/ChebyshevApprox", "max_issues_repo_head_hexsha": "9b43654b3b7d00210ca2191b1173c79c7333dad3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chebyshev_weights.jl", "max_forks_repo_name": "RJDennis/ChebyshevApprox", "max_forks_repo_head_hexsha": "9b43654b3b7d00210ca2191b1173c79c7333dad3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3740399386, "max_line_length": 185, "alphanum_fraction": 0.5984293366, "num_tokens": 9081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7691694604405527}}
{"text": "\"\"\"\ntype-II discrete cosine transform (DCT)\n\"\"\"\nfunction dct!(data::Array{T, 3}) where {T <:AbstractFloat}\n\tdctmat = genmat(size(data, 1))\n\tdctmat1 = genmat(size(data, 2))'\n\t@views @inbounds @fastmath for i in 1:size(data, 3)\n\t\tdata[:, :, i] .= dctmat * data[:, :, i] * dctmat1\n\tend\n\n\tdctmat = genmat(size(data, 3))\n\t@views @inbounds @fastmath for j in 1:size(data, 2), i in 1:size(data, 1)\n\t\tdata[i, j, :] .= dctmat * data[i, j, :]\n\tend\nend\n\n\"\"\"\ninverse discrete cosine transform (DCT)\n\"\"\"\nfunction idct!(data::Array{T, 3}) where {T <:AbstractFloat}\n\tdctmat = genmat(size(data, 3))'\n\t@views @inbounds @fastmath for j in 1:size(data, 2), i in 1:size(data, 1)\n\t\tdata[i, j, :] .= dctmat * data[i, j, :]\n\tend\n\n\tdctmat = genmat(size(data, 1))'\n\tdctmat1 = genmat(size(data, 2))\n\t@views @inbounds @fastmath for i in 1:size(data, 3)\n\t\tdata[:, :, i] .= dctmat * data[:, :, i] * dctmat1\n\tend\nend\n\nfunction genmat(h::Int)::Array{Float64, 2}\n\tmat = Array{Float64, 2}(undef, h, h)\n\tmat[1, :] .= sqrt(1 / h)\n\t@inbounds @fastmath for j in 1:h\n\t\t@simd for i in 2:h\n\t\t\tmat[i, j] = cos(π * (i - 1) * (j - 0.5) / h) * sqrt(2 / h)\n\t\tend\n\tend\n\tmat\nend\n", "meta": {"hexsha": "c54cc66eb33a22651bfad8446a58547b49c0579f", "size": 1132, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Transform/dct.jl", "max_stars_repo_name": "Longhao-Chen/BM3DDenoise.jl", "max_stars_repo_head_hexsha": "3c2a59395843ce0fe29f9bb414bcdf3cab76e7f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-10-04T05:52:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T03:30:24.000Z", "max_issues_repo_path": "src/Transform/dct.jl", "max_issues_repo_name": "Longhao-Chen/BM3DDenoise.jl", "max_issues_repo_head_hexsha": "3c2a59395843ce0fe29f9bb414bcdf3cab76e7f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-08-04T11:24:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T12:14:12.000Z", "max_forks_repo_path": "src/Transform/dct.jl", "max_forks_repo_name": "Longhao-Chen/BM3D.jl", "max_forks_repo_head_hexsha": "3c2a59395843ce0fe29f9bb414bcdf3cab76e7f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-04T11:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T11:13:11.000Z", "avg_line_length": 26.3255813953, "max_line_length": 74, "alphanum_fraction": 0.6033568905, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632234212403, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7691694582336707}}
{"text": "using DelimitedFiles\n\ninput = readdlm(ARGS[1], ' ', Int, '\\n');\n\n# Part 1\nfuel_required(mass) = (mass ÷ 3) - 2;\npart1 = reduce(+, map(fuel_required, input))\nprintln(\"Part 1: \", part1)\n\n# Part 2\nfunction fuel_required_2(mass)\n    fuel = fuel_required(mass)\n    return (fuel > 0) ? fuel + fuel_required_2(fuel) : 0;\nend\npart2 = reduce(+, map(fuel_required_2, input))\nprintln(\"Part 2: \", part2)\n\n# Nothing too crazy here for those familiar with recursion, although reading the instructions carefully always helps.\n# Notice something interesting: the part 2 function does not distribute. That is, you cannot compute\n#   fuel_required_2(part1) + part1\n# to get part2. \n# https://twitter.com/wjholdentech/status/1201023263633219585\n", "meta": {"hexsha": "463e54ae44b069806c16ebf959b24547be570241", "size": 726, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "01/aoc-2019-01.jl", "max_stars_repo_name": "wjholden/Advent-of-Code-2019", "max_stars_repo_head_hexsha": "be82179a974314ad2b578533bc4ccad361c9eab3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-28T16:01:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-28T16:01:20.000Z", "max_issues_repo_path": "01/aoc-2019-01.jl", "max_issues_repo_name": "wjholden/Advent-of-Code-2019", "max_issues_repo_head_hexsha": "be82179a974314ad2b578533bc4ccad361c9eab3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-12-03T09:08:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T11:39:53.000Z", "max_forks_repo_path": "01/aoc-2019-01.jl", "max_forks_repo_name": "wjholden/Advent-of-Code-2019", "max_forks_repo_head_hexsha": "be82179a974314ad2b578533bc4ccad361c9eab3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5652173913, "max_line_length": 117, "alphanum_fraction": 0.7231404959, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7691656871921336}}
{"text": "\n# Auxiliary functions for natural cubic spline interpolation\n\n# Stores parameters for fitted spline polynomials\nmutable struct Spline{T}\n    x::Vector{T} # (x, y) are the original points\n    y::Vector{Float64}\n    params::Vector{Float64} # stores parameters for polynomials. [ a1, b1, c1, d1, a2, b2, c2, d2 ...]\n\n    function Spline(x::Vector{T}, y::Vector{Float64}, params::Vector{Float64}) where {T}\n        polynms_count = length(x) - 1\n        @assert length(params) == polynms_count * 4 \"params length $(length(params)) does not conform to the expected number of polynomials ($(polynms_count))\" # each polynomial has 4 parameters\n        return new{T}(x, y, params)\n    end\nend\n\n# Given a polinomial index, returns the indexer of the last parameter before the first parameter of the referenced polinomial\n_base_param_index_(poly_index::Int) = (poly_index-1)*4\n\n# Performs natural cubic spline interpolation\nfunction splineint(s::Spline{T}, x_out::Number) where {T<:Number}\n    local poly_index::Int = 1\n    local base_idx::Int\n\n    if x_out > s.x[end]\n        # Extrapolation after last point\n        poly_index = length(s.x) - 1\n        base_idx = _base_param_index_(poly_index)\n        return (x_out - s.x[end])*(s.params[base_idx + 2] + 2*s.params[base_idx + 3]*s.x[end] + 3*s.params[base_idx + 4]*(s.x[end]^2)) + s.y[end]\n    elseif x_out < s.x[1]\n        # Extrapolation before first point\n        base_idx = 0\n        return (x_out - s.x[1])*(s.params[base_idx + 2] + 2*s.params[base_idx + 3]*s.x[1] + 3*s.params[base_idx + 4]*(s.x[1]^2)) + s.y[1]\n    else\n        # Interplation\n        while x_out > s.x[poly_index+1]\n            poly_index += 1\n        end\n\n        base_idx = _base_param_index_(poly_index)\n\n        #P1                       P2                    P3                     ...\n        #1   2    3      4        5   6    7      8     9   10   11     12\n        #a + bx + cx^2 + dx^3     a + bx + cx^2 + dx^3  a + bx + cx^2 + dx^3   ...\n        return s.params[base_idx + 1] + s.params[base_idx + 2]*x_out +\n            s.params[base_idx + 3]*(x_out^2) + s.params[base_idx + 4]*(x_out^3)\n    end\nend\n\n# Performs natural cubic spline interpolation\nfunction splineint(s::Spline{T1}, x_out::Vector{T2}) :: Vector{Float64} where {T1, T2}\n    len = length(x_out)\n    y_out = Vector{Float64}(undef, len)\n    for i in 1:len\n        y_out[i] = splineint(s, x_out[i])\n    end\n    return y_out\nend\n\n# Build a Spline object by fitting 3rd order polynomials around points (x_in, y_in)\nfunction splinefit(x_in::Vector{T}, y_in::Vector{Float64}) :: Spline{T} where {T}\n    #\n    # TODO: optimize. See http://www.math.ntnu.no/emner/TMA4215/2008h/cubicsplines.pdf\n    #\n    points_count = length(x_in)\n    @assert points_count == length(y_in) \"x_in and y_in doesn't conform on sizes.\"\n    matrix_n = 4*(points_count-1) # the main matrix is a square matrix matrix_n by matrix_n\n\n    A = zeros(matrix_n, matrix_n)\n    b = zeros(matrix_n)\n\n    # Known values for polys\n\n    # First Point\n    A[1,1] = 1.0\n    A[1,2] = x_in[1]\n    A[1,3] = x_in[1]^2\n    A[1,4] = x_in[1]^3\n    b[1] = y_in[1]\n\n    # Last Point\n    base_idx = 4*(points_count - 2)\n    A[2, base_idx + 1] = 1.0\n    A[2, base_idx + 2] = x_in[points_count]\n    A[2, base_idx + 3] = x_in[points_count]^2\n    A[2, base_idx + 4] = x_in[points_count]^3\n    b[2] = y_in[points_count]\n\n    # Inner Points\n    row = 3\n    for i in 2:(points_count-1)\n        # Connecting to left poly\n        A[row, (i-2)*4 + 1] = 1.0\n        A[row, (i-2)*4 + 2] = x_in[i]\n        A[row, (i-2)*4 + 3] = x_in[i]^2\n        A[row, (i-2)*4 + 4] = x_in[i]^3\n        b[row] = y_in[i]\n\n        row += 1\n\n        # Connecting to right poly\n        A[row, (i-1)*4 + 1] = 1.0\n        A[row, (i-1)*4 + 2] = x_in[i]\n        A[row, (i-1)*4 + 3] = x_in[i]^2\n        A[row, (i-1)*4 + 4] = x_in[i]^3\n        b[row] = y_in[i]\n\n        row += 1\n\n        # Conditions on first order derivatives\n        A[row, (i-2)*4 + 2] = 1.0\n        A[row, (i-2)*4 + 3] = 2.0*x_in[i]\n        A[row, (i-2)*4 + 4] = 3.0*(x_in[i]^2)\n        A[row, (i-1)*4 + 2] = -1.0\n        A[row, (i-1)*4 + 3] = -2.0*x_in[i]\n        A[row, (i-1)*4 + 4] = -3.0*(x_in[i]^2)\n\n        row += 1\n\n        # Conditions on second order derivatives\n        A[row, (i-2)*4 + 3] = 2.0\n        A[row, (i-2)*4 + 4] = 6.0 * x_in[i]\n        A[row, (i-1)*4 + 3] = -2.0\n        A[row, (i-1)*4 + 4] = -6.0 * x_in[i]\n\n        row += 1\n    end\n\n    # Conditions for natural cubic spline\n    A[row, 3] = 2.0\n    A[row, 4] = 6.0 * x_in[1]\n\n    row += 1\n\n    A[row, (points_count-2)*4 + 3] = 2.0\n    A[row, (points_count-2)*4 + 4] = 6.0 * x_in[points_count]\n\n    return Spline(x_in, y_in, A \\ b)\nend\n", "meta": {"hexsha": "0a2d1bc2d04b31a83294e03247bde376423cf6bf", "size": 4675, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/splines.jl", "max_stars_repo_name": "lucasprocessi/InterestRates.jl", "max_stars_repo_head_hexsha": "0f9c309d5e1e3d681dd57172aa066a0da663a5f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2015-08-23T03:14:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T20:31:30.000Z", "max_issues_repo_path": "src/splines.jl", "max_issues_repo_name": "lucasprocessi/InterestRates.jl", "max_issues_repo_head_hexsha": "0f9c309d5e1e3d681dd57172aa066a0da663a5f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2015-08-24T10:13:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T17:09:34.000Z", "max_forks_repo_path": "src/splines.jl", "max_forks_repo_name": "lucasprocessi/InterestRates.jl", "max_forks_repo_head_hexsha": "0f9c309d5e1e3d681dd57172aa066a0da663a5f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2015-10-12T15:07:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:48:25.000Z", "avg_line_length": 33.3928571429, "max_line_length": 194, "alphanum_fraction": 0.5557219251, "num_tokens": 1689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7691616394319484}}
{"text": "# Copyright (c) 2021 Leonardo Banchi <leonardo.banchi@unifi.it> \n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nusing LinearAlgebra, BlockDiagonals\n\n\" symplectic matrix \"\nomega(n::Int) = BlockDiagonal([[0 1.; -1. 0] for k=1:n])\nomega(A::AbstractMatrix) = omega(Int(size(A,1)/2))\n\n\" arrange diagonal elements in a block form \"\nwdiag(D) = BlockDiagonal([ Diagonal([d,d]) for d in D])\n\n\" check if a matrix is symplectic \"\nissymplectic(S) = S*omega(S)*S'≈omega(S)\n\n\" generate a random symplectic matrix \"\nfunction rand_symplectic(n) \n\tA = randn(2n,2n)\n\texp(Hermitian(A)*omega(n))\nend\n\n\" generate a random covariance matrix \"\nfunction rand_covmat(n,σ=1)\n\tv = 1/2 .+ σ*rand(n)\n\tS = rand_symplectic(n)\n\tSymmetric(S*wdiag(v)*S')\nend\n\nfunction _will_init(V)\n\t@assert\tsize(V,1) == size(V,2) && iseven(size(V,1))\n\tInt(size(V,1)/2), omega(V)\nend\n\n\"\"\"\n\tD,S = williamson(V)\n\n\tfind the Williamson decomposition such that \n\tS'*wdiag(D)*S ≈ V\n\"\"\"\nfunction williamson(V)\n\tn, Ω = _will_init(V)\n\tiv12 = inv(sqrt(Symmetric(V)))\n\tJ = iv12*Ω*iv12\n\tf = schur((J-J')/2)\n\tT, Q = f.Schur, f.vectors\n\tP = BlockDiagonal([ sign(T[2k-1,2k]) > 0 ? \n\t\t\t\t\t   [1. 0; 0 1.] : [0 1.; 1. 0] for k=1:n])\n\tD = inv.(diag(P*T*P,1)[1:2:2n])\n\tiS = wdiag(sqrt.(D))*P*Q'*iv12\n\tD, Ω*iS*Ω\nend\n\n\"\"\"\n\tD,S = williamsonNew(V)\n\n\tfind the Williamson decomposition such that \n\tS'*wdiag(D)*S ≈ V\n\tnew algorithm.\n\"\"\"\nfunction williamsonNew(V)\n\tn, Ω = _will_init(V)\n\tλ = sort(real(eigvals(V*Ω*1im)))[n+1:2n]\n\tS = zeros(2n,2n)\n    for m=1:n\n\t    denom = λ[m]*prod(λ[k]^2-λ[m]^2 for k=1:n if k!=m) \n        Vλ = complex.(V)-(1im*λ[m])*Ω\n\t    minorden(k) = det(view(Vλ,setdiff(1:2n,2m),setdiff(1:2n,k)))/denom\n        fam = real(minorden(2m))\n\t    for k=1:n\n            faeven = k==m ? sqrt(fam) : minorden(2k)/sqrt(fam)\n            faodd = -minorden(2k-1)/sqrt(fam)\n            S[2m-1,2k] \t= -real(faodd)\n            S[2m,2k] = imag(faodd)\n            S[2m-1,2k-1] = real(faeven)\n            S[2m,2k-1] = -imag(faeven)\n        end\n\tend\n\tλ, S\nend\n", "meta": {"hexsha": "48274575c1ae8714a5481c8ae44aef6ffa874d78", "size": 3000, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "symplectic.jl", "max_stars_repo_name": "softquanta/symplectic_decomposition", "max_stars_repo_head_hexsha": "b35e5505424aca0d983ee405cef2a98a763cd7a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-13T07:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T09:21:12.000Z", "max_issues_repo_path": "symplectic.jl", "max_issues_repo_name": "softquanta/symplectic_decomposition", "max_issues_repo_head_hexsha": "b35e5505424aca0d983ee405cef2a98a763cd7a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "symplectic.jl", "max_forks_repo_name": "softquanta/symplectic_decomposition", "max_forks_repo_head_hexsha": "b35e5505424aca0d983ee405cef2a98a763cd7a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9278350515, "max_line_length": 80, "alphanum_fraction": 0.6626666667, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7691616353033988}}
{"text": "function ksintegrateInplace(u, Lx, dt, Nt, nsave);\n    u = (1+0im)*u                       # force u to be complex\n    Nx = length(u)                      # number of gridpoints\n    kx = vcat(0:Nx/2-1, 0:0, -Nx/2+1:-1)# integer wavenumbers: exp(2*pi*kx*x/L)\n    alpha = 2*pi*kx/Lx                  # real wavenumbers:    exp(alpha*x)\n    D = 1im*alpha                       # spectral D = d/dx operator \n    L = alpha.^2 - alpha.^4             # spectral L = -D^2 - D^4 operator\n    G = -0.5*D                          # spectral -1/2 D operator\n\n    Nsave = div(Nt, nsave)+1            # number of saved time steps\n    t = (0:Nsave)*(dt*nsave)            # t timesteps\n    U = zeros(Nsave, Nx)                # matrix of u(xⱼ, tᵢ) values\n    U[1,:] = u                          # assign initial condition to U\n    s = 2                               # counter for saved data\n \n    # some convenience variables\n    dt2  = dt/2\n    dt32 = 3*dt/2\n    A_inv = (ones(Nx) - dt2*L).^(-1)\n    B     =  ones(Nx) + dt2*L\n    \n    # compute in-place FFTW plans\n    FFT! = plan_fft!(u, flags=FFTW.ESTIMATE)\n    IFFT! = plan_ifft!(u, flags=FFTW.ESTIMATE)\n\n    # compute nonlinear term Nn = -u u_x \n    Nn  = G.*fft(u.^2);    # Nn = -1/2 d/dx u^2 = -u u_x\n    Nn1 = copy(Nn);        # Nn1 = Nn at first time step\n    FFT!*u;                # transform u physical -> spectral\n    \n    # timestepping loop\n    for n = 1:Nt\n\n        Nn1 .= Nn       # shift nonlinear term in time\n\n        Nn .= u         # put u into Nn \n        IFFT!*Nn;       # transform Nn = u to gridpt values, in place\n        Nn .= Nn.*Nn;   # collocation calculation, set Nn = u^2\n        FFT!*Nn;        # transform Nn = u^2 back to spectral coeffs\n        Nn .= G.*Nn;    # apply G = -1/2d/dx  to compute Nn = -1/2 d/dx (u^2)\n\n        # loop fusion! Julia translates this line into a single for-loop on\n        #   u[i] = A_inv[i] * (B[i]*u[i] + dt32*Nn[i] - dt2*Nn1[i]; \n        # no temporary vectors! \n\n        u .= A_inv .* (B .* u .+ dt32.*Nn .- dt2.*Nn1); \n        \n        if mod(n, nsave) == 0\n            U[s,:] = real(ifft(u))\n            s += 1            \n        end\n    end\n   \n    t,U\nend\n", "meta": {"hexsha": "bd28aa3a9866acf3df9af0c14abc766fe72b1ab9", "size": 2165, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "codes/ksintegrate.jl", "max_stars_repo_name": "raphbacher/julia-intro", "max_stars_repo_head_hexsha": "ecf7d683b46a75fa2214edf55e9873ee57de3834", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "codes/ksintegrate.jl", "max_issues_repo_name": "raphbacher/julia-intro", "max_issues_repo_head_hexsha": "ecf7d683b46a75fa2214edf55e9873ee57de3834", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/ksintegrate.jl", "max_forks_repo_name": "raphbacher/julia-intro", "max_forks_repo_head_hexsha": "ecf7d683b46a75fa2214edf55e9873ee57de3834", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6607142857, "max_line_length": 79, "alphanum_fraction": 0.4697459584, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7691616274390766}}
{"text": "grid_size = 25  \nα_vals = linspace(0.05, 0.5, grid_size)  \nw_bar_vals = similar(α_vals)\n\nmcm = McCallModel()\n\nfor (i, α) in enumerate(α_vals)\n    mcm.α = α\n    w_bar = compute_reservation_wage(mcm)\n    w_bar_vals[i] = w_bar\nend\n\nplot(α_vals, \n     w_bar_vals, \n     lw=2, \n     α=0.7, \n     xlabel=\"job separation rate\",\n     ylabel=\"reservation wage\",\n     label=L\"$\\bar w$ as a function of $\\α$\")\n\n", "meta": {"hexsha": "8aa8998521105917dd0a90c76a138773b9848ea8", "size": 400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "rst_files/_static/code/mccall/mccall_resw_alpha.jl", "max_stars_repo_name": "yywingliang/lecture-source-jl", "max_stars_repo_head_hexsha": "d5859ef7b82b4f130eec34cacd1dc0f2b9f1af22", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2017-05-09T10:45:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:33:27.000Z", "max_issues_repo_path": "rst_files/_static/code/mccall/mccall_resw_alpha.jl", "max_issues_repo_name": "yywingliang/lecture-source-jl", "max_issues_repo_head_hexsha": "d5859ef7b82b4f130eec34cacd1dc0f2b9f1af22", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2017-06-30T01:52:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-01T20:09:47.000Z", "max_forks_repo_path": "rst_files/_static/code/mccall/mccall_resw_alpha.jl", "max_forks_repo_name": "yywingliang/lecture-source-jl", "max_forks_repo_head_hexsha": "d5859ef7b82b4f130eec34cacd1dc0f2b9f1af22", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 117, "max_forks_repo_forks_event_min_datetime": "2017-04-25T16:09:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T02:30:29.000Z", "avg_line_length": 19.0476190476, "max_line_length": 45, "alphanum_fraction": 0.62, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7691563359741123}}
{"text": "\n# we write a function that uses Monte Carlo to estimate the volume of the unit hypersphere in d dimensions using n trials\nfunction sphereVolMC(d, n)\n\n\t# we initialize the counter variable\n\tcount = 0\n\n\t# we perform the Monte Carlo trial n times\n\tfor i = 1:n\n\n\t\t# we generate a vector with d random floats from [0,1]\n\t\tx = rand(d)\n\n\t\t# we calculate the squared norm of x\n\t\tnorm2 = x' * x\n\n\t\t# if x is inside the hypersphere we increment the count\n\t\tif norm2 < 1\n\t\t\tcount += 1\n\t\tend\n\tend\n\n\t# we calculate the estimated volume given by\n\tvol = 2^d * count / n\n\t\n\t# we return the estimated volume\n\treturn vol\nend\n", "meta": {"hexsha": "86184b46fbf916daec513b961513bceb0d1cea1b", "size": 608, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1a/Monte Carlo integration/sphereVolMC.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "1a/Monte Carlo integration/sphereVolMC.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "1a/Monte Carlo integration/sphereVolMC.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 20.9655172414, "max_line_length": 121, "alphanum_fraction": 0.6973684211, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9546474233166328, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7690947022620284}}
{"text": "# calculate standard deviation of sensor data\n\nmodule CalcStdDev\n    using DataFrames, CSV, Statistics\n\n    function main()\n        data_path = joinpath(split(@__FILE__, \"src\")[1], \"data/sensor_data_200.txt\")\n        df_200_mm = CSV.read(data_path, DataFrame, \n                             header=[\"date\", \"time\", \"ir\", \"lidar\"],\n                             delim=' ')\n        \n        # calculate from definition\n        zs = df_200_mm.lidar # observation\n        mean_def = sum(zs) / length(zs) # mean\n        diff_square = [(z - mean_def)^2 for z in zs]\n        \n        sampling_var = sum(diff_square) / length(zs) # sampling variance\n        unbiased_var = sum(diff_square) / (length(zs) - 1) # unbiased variance\n\n        sampling_std_dev = sqrt(sampling_var)\n        unbiased_std_dev = sqrt(unbiased_var)\n\n        # calculate by Statistics\n        stats_std_dev = Statistics.std(zs, corrected=false)\n\n        println(\"Sampling standard deviation = $sampling_std_dev\")\n        println(\"Unbiased standard deviation = $unbiased_std_dev\")\n        println(\"Standard deviation by Statistics = $stats_std_dev\")\n    end\nend", "meta": {"hexsha": "afe4c637761b33b472278a038c3db723795dd8b5", "size": 1122, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/prob_stats/freq_dist/std_dev/calc_std_dev.jl", "max_stars_repo_name": "ShisatoYano/JuliaAutonomy", "max_stars_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2021-03-10T12:43:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T16:40:19.000Z", "max_issues_repo_path": "src/prob_stats/freq_dist/std_dev/calc_std_dev.jl", "max_issues_repo_name": "ShisatoYano/JuliaAutonomy", "max_issues_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/prob_stats/freq_dist/std_dev/calc_std_dev.jl", "max_forks_repo_name": "ShisatoYano/JuliaAutonomy", "max_forks_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-14T02:46:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T09:19:40.000Z", "avg_line_length": 37.4, "max_line_length": 84, "alphanum_fraction": 0.6176470588, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474246069458, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.769094698846479}}
{"text": "using FileIO, Images\r\nusing Plots\r\n\r\npngFileName = \"M:\\\\Matlab\\\\imgArrow.png\"\r\nsavePath = \"C:\\\\Users\\\\phiber\\\\Downloads\\\\imgArrowAnim.gif\"\r\n\r\nfunction main(pngFile, savePath)\r\n\r\n    #### Reading of image to create the function in the complex plane ####\r\n\r\n    # Load PNG file and convert from RBG to 3-dimensional matrix\r\n    img_RGB = load(File{format\"PNG\"}(pngFile))\r\n    img_Mat = permutedims(channelview(img_RGB),(2,3,1))\r\n\r\n    # pxl is a boolean matrix where the elements are true where the drawing exists\r\n    pxl = img_Mat[:,:,1] .!= 1\r\n    findPxl = findall(pxl)\r\n\r\n    # f is an nx2-dimensional matrix where each row is a coordinate for the consecutive step of the animation\r\n    # f can thus be seen as the discrete complex function in the time domain\r\n    f = Array{Int64}(undef,length(findPxl),2) \r\n\r\n    #row (r) and column (c) index of an arbitrary point in the drawing, becomes the starting position of the animation\r\n    r,c = Tuple(findPxl[1]) \r\n    f[1,:] = [r,c]\r\n    pxl[findPxl[1]] = false #Set the \"used\" pixel to false to prevent it to be used again\r\n\r\n    nearIdx = -1:1\r\n\r\n    j = 2\r\n    while true\r\n        # Look at the pixels adjacent to the previous iteration's pixel and find one that is \"drawn\"\r\n        near = pxl[f[j-1,1] .+ nearIdx, f[j-1,2] .+ nearIdx]\r\n        firstNear = findfirst(near)\r\n        if isnothing(firstNear) # if there is no more pixels, break the loop\r\n            break\r\n        end\r\n\r\n        #Set the next coordinate\r\n        rt,ct = Tuple(firstNear)\r\n        r = r+nearIdx[rt]\r\n        c = c+nearIdx[ct]\r\n        f[j,:] = [r,c]\r\n        pxl[r,c] = false #Set the \"used\" pixel to false to prevent it to be used again\r\n        j += 1\r\n    end\r\n\r\n    f = f[begin:j-1,:]\r\n\r\n    #Set the center of the png as the origin\r\n    mid = ceil.(size(pxl) ./2)\r\n\r\n    f[:,1] = f[:,1] .- mid[1]\r\n    f[:,2] = f[:,2] .- mid[2]\r\n\r\n    #### Complex Fourier Series  ####\r\n    t = range(0,1,length = size(f,1)+1) # Discrete time steps\r\n    t = t[begin:end-1]\r\n\r\n    N = 200 #Number of non-static coefficients. Shall be even\r\n    cp = Vector{Complex{Float64}}(undef,Int64(N/2)) #Positive coefficients\r\n    cn = Vector{Complex{Float64}}(undef,Int64(N/2)) #Negative coefficients\r\n    c0 = sum(f[:,1] .+ 1im.* f[:,2]) ./ size(f,1) #static coefficient\r\n    \r\n    # Calculation of Fourier coefficients\r\n    for k=eachindex(cp)\r\n        cp[k] = sum((f[:,1] .+ 1im.*f[:,2]) .* exp.(-k*2im*pi.*t))./size(f,1)\r\n        cn[k] = sum((f[:,1] .+ 1im.*f[:,2]) .* exp.(k*2im*pi.*t))./size(f,1)\r\n    end\r\n    \r\n    # Calculation of function in frequency domain\r\n    function vecsumFunc(tt)\r\n        #Function to calculate the sum of the phasors\r\n        F = c0;\r\n        for k = eachindex(cp)\r\n            F = F + cp[k]*exp(k*2im*pi*tt) + cn[k]*exp(-k*2im*pi*tt)\r\n        end\r\n        return F\r\n    end\r\n\r\n    #### Plotting ####\r\n    # x and y are the real and imaginary parts, respectively \r\n    x = real(vecsumFunc.(t))\r\n    y = imag(vecsumFunc.(t))\r\n\r\n    println(\"Animating...\")\r\n\r\n    anim = @animate for i in 1:length(t)\r\n        fourierplot(x,y,i)\r\n\r\n        plot!([0,real(c0)],[0,imag(c0)], arrow=false,linewidth=1,color=:black, label=false)\r\n        vecSum = c0;\r\n        for k = eachindex(cp)\r\n            plot!([real(vecSum),real(vecSum + cp[k]*exp(k*2im*pi*t[i]))],\r\n             [imag(vecSum),imag(vecSum + cp[k]*exp(k*2im*pi*t[i]))],\r\n             arrow=false,linewidth=1,color=:dodgerblue4, label=false)\r\n            vecSum = vecSum + cp[k]*exp(k*2im*pi*t[i])\r\n            \r\n            plot!([real(vecSum),real(vecSum + cn[k]*exp(-k*2im*pi*t[i]))],\r\n             [imag(vecSum),imag(vecSum + cn[k]*exp(-k*2im*pi*t[i]))],\r\n             arrow=false,linewidth=1,color=:darkred, label=false)\r\n            vecSum = vecSum + cn[k]*exp(-k*2im*pi*t[i])\r\n        end\r\n    end\r\n\r\n    println(\"Create gif...\")\r\n\r\n    gif(anim, savePath, fps = 50)\r\n\r\n    return\r\nend\r\n\r\n@userplot FourierPlot\r\n@recipe function func(cp::FourierPlot)\r\n    x,y,i = cp.args\r\n    n = length(x)\r\n    inds = circshift(1:n,1-i)\r\n    linewidth --> [range(0,0,length = Int64(floor(n/2))); range(0,10,length = Int64(ceil(n/2)))]\r\n    seriesalpha --> [range(0, 0, length = Int64(floor(n/2))); range(0, 1, length = Int64(ceil(n/2)))]\r\n    aspec_ratio --> 1\r\n    label --> false\r\n    size --> (1080,1080)\r\n    framestyle --> :none\r\n    x[inds], y[inds]\r\nend\r\n\r\nmain(pngFileName,savePath)\r\n", "meta": {"hexsha": "ce12e4104d72dd5293610e028a346f0556c2e8c9", "size": 4380, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "FourierAnimateImage.jl", "max_stars_repo_name": "philipbergander/FourierImageAnimation", "max_stars_repo_head_hexsha": "d32f5c953bc20dfc0b228e8e93a030075147136d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FourierAnimateImage.jl", "max_issues_repo_name": "philipbergander/FourierImageAnimation", "max_issues_repo_head_hexsha": "d32f5c953bc20dfc0b228e8e93a030075147136d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FourierAnimateImage.jl", "max_forks_repo_name": "philipbergander/FourierImageAnimation", "max_forks_repo_head_hexsha": "d32f5c953bc20dfc0b228e8e93a030075147136d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.21875, "max_line_length": 119, "alphanum_fraction": 0.5687214612, "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474168650674, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7690946814717042}}
{"text": "#---------------------------------------------------------------------#\n#This function computes the Initial & Exact Solutions.\n#Written by F.X. Giraldo on April 19, 2019\n#           Department of Applied Mathematics\n#           Naval Postgraduate School\n#           Monterey; CA 93943-5216\n#---------------------------------------------------------------------#\nfunction exact_solution(coord,Npoin,case,DFloat)\n\n    #Set some constants\n    c=2*π\n\n    #Initialize\n    qe=zeros(DFloat,Npoin)\n    qeₓ=zeros(DFloat,Npoin)\n    fe=zeros(DFloat,Npoin)\n\n    #Generate Grid Points\n    for I=1:Npoin\n        x=coord[I]\n        if (case == 1) #Gaussian\n            qe[I]=sin(c*x)\n            qeₓ[I]=-c*cos(c*x)\n            fe[I]=-c^2*sin(c*x)\n        end\n    end #I\n    return (qe,qeₓ,fe)\nend\n", "meta": {"hexsha": "c2fc299f31718c18c87438fed628914e1468e723", "size": 782, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Projects/Project_05a_1D_Elliptic/For_Students/julia/exact_solution.jl", "max_stars_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_stars_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-12-28T06:19:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:40:33.000Z", "max_issues_repo_path": "Projects/Project_05a_1D_Elliptic/For_Students/julia/exact_solution.jl", "max_issues_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_issues_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-29T19:12:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-29T21:53:41.000Z", "max_forks_repo_path": "Projects/Project_05a_1D_Elliptic/For_Instructors/julia/exact_solution.jl", "max_forks_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_forks_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:35:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T06:53:34.000Z", "avg_line_length": 26.9655172414, "max_line_length": 71, "alphanum_fraction": 0.4782608696, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172673767972, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7690774334539107}}
{"text": "\"\"\" \n\tMM1(μ, λ)\n\nTạo mô hình M/M/1\n\"\"\"\nstruct MM1{T<:Any} <: AbstractMMCK\n\tλ::Union{T, Real}\n\tμ::Union{T, Real}\n\tρ::Union{T, Real}\n\tfunction MM1(λ, μ)\n\t\tT = Union{typeof(μ), typeof(λ)}\n\t\tnew{T}(λ, μ, λ/μ)\n\tend\n\tfunction MM1(λ::Real, μ::Real)\n\t\tif λ/μ >= 1\n\t\t\t@error \"ρ phải < 1\"\n\t\tend\n\t\tT = Union{typeof(μ), typeof(λ)}\n\t\tnew{T}(λ, μ, λ/μ)\n\tend\nend\n\npn(m::MM1, n::Int) = (1 - m.ρ) * m.ρ^n\nL(m::MM1) = m.ρ / (1 - m.ρ)\nLq(m::MM1) = m.ρ ^ 2 / (1 - m.ρ)\nW(m::MM1) = L(m) / m.λ\nWq(m::MM1) = Lq(m) / m.λ\n", "meta": {"hexsha": "02ab57e582a767925edbc80b949ea0d878f3f7bb", "size": 497, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mm1.jl", "max_stars_repo_name": "ndgnuh/MarkovAndQueueModels.jl", "max_stars_repo_head_hexsha": "30d0c3ecb9da61a466b95b791e8dbefc854ed38f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mm1.jl", "max_issues_repo_name": "ndgnuh/MarkovAndQueueModels.jl", "max_issues_repo_head_hexsha": "30d0c3ecb9da61a466b95b791e8dbefc854ed38f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mm1.jl", "max_forks_repo_name": "ndgnuh/MarkovAndQueueModels.jl", "max_forks_repo_head_hexsha": "30d0c3ecb9da61a466b95b791e8dbefc854ed38f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.75, "max_line_length": 38, "alphanum_fraction": 0.5050301811, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875641, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.7690774289403086}}
{"text": "# Load Julia packages (libraries)\n\nusing Pkg, DrWatson\n\nusing MonteCarloMeasurements\nusing StanSample\nusing StatisticalRethinking\n\ndf = CSV.read(sr_datadir(\"Kline.csv\"), DataFrame);\n\n# New col log_pop, set log() for population data\ndf[!, :log_pop] = map((x) -> log(x), df[!, :population]);\ndf[!, :society] = 1:10;\n\nstan12_6 = \"\ndata {\n    int N;\n    int N_societies;\n    int total_tools[N];\n    real logpop[N];\n    int society[N];\n}\nparameters{\n    real a;\n    real bp;\n    vector[N_societies] a_society;\n    real<lower=0> sigma_society;\n}\nmodel{\n    vector[N_societies] mu;\n    sigma_society ~ cauchy( 0 , 1 );\n    a_society ~ normal( 0 , sigma_society );\n    bp ~ normal( 0 , 1 );\n    a ~ normal( 0 , 10 );\n    for ( i in 1:N ) {\n        mu[i] = a + a_society[society[i]] + bp * logpop[i];\n        mu[i] = exp(mu[i]);\n    }\n    total_tools ~ poisson( mu );\n}\n\";\n\n# Define the SampleModel.\n\nm12_6s = SampleModel(\"m12.6s\",  stan12_6);\n\n# Input data for cmdstan\n\nm12_6_data = Dict(\"N\" => size(df, 1), \"N_societies\" => 10,  \n\"total_tools\" => df[!, :total_tools], \"logpop\" => df[!, :log_pop],\n\"society\" => df[!, :society]);\n        \n# Sample using cmdstan's sample option\n\nrc12_6s = stan_sample(m12_6s, data=m12_6_data);\n\n# Describe the draws\n\nif success(rc12_6s)\n  part12_6s = read_samples(m12_6s, :particles)\n  part12_6s |> display\nend\n", "meta": {"hexsha": "357e99731185ab6b4a9b93218dd4cdd829e74a55", "size": 1335, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/12/m12.6s.jl", "max_stars_repo_name": "pitmonticone/StatisticalRethinkingStan.jl", "max_stars_repo_head_hexsha": "9eee333465b3b8ec5975645c1373b27cf26b5bb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2020-10-10T13:03:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T11:48:45.000Z", "max_issues_repo_path": "models/12/m12.6s.jl", "max_issues_repo_name": "pitmonticone/StatisticalRethinkingStan.jl", "max_issues_repo_head_hexsha": "9eee333465b3b8ec5975645c1373b27cf26b5bb0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/12/m12.6s.jl", "max_forks_repo_name": "pitmonticone/StatisticalRethinkingStan.jl", "max_forks_repo_head_hexsha": "9eee333465b3b8ec5975645c1373b27cf26b5bb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:30:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T00:10:15.000Z", "avg_line_length": 21.1904761905, "max_line_length": 66, "alphanum_fraction": 0.6262172285, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7690774247661525}}
{"text": "## Lecture-3-Least-squares-CVX\n\n## Here are the packages we'll use\nusing Convex\nusing Plots\nplotlyjs() # need to use plotlyjs on my machine for plots.\n\n## Step 1: Create a set of data with a linear model\nm=40\nn=2\nA = randn(m,n)\nxex = [5;1]      # \"b\" = 5 in ax+b and a=1\npts = -10+20*rand(m,1)\nA = [ones(m,1) pts]\nb = A*xex + .5*randn(m,1)\n\n## Show the linear model\nscatter(pts,b)\nxlabel!(\"x\")\nylabel!(\"y\")\n\n##\nx = Variable(n)\nproblem = minimize(sumsquares(b - A*x))\nsolve!(problem)\nxls = x.value\n@show x\n## Show the least squares fit\nscatter(pts,b;label=\"data\")\nplot!([-11; 11], [1 -11; 1 11]*xls;label=\"fit\")\n#xaxis!([-11 11])\ntitle!(\"Least-square fit\")\nxlabel!(\"x\")\nylabel!(\"y\")\n\n## Now we add outliers\noutliers = [-9.5; 9]\noutvals = [20; -15]\nA = [A; ones(length(outliers),1) outliers]\nb = [b; outvals]\nm = size(A,1)\npts = [pts;outliers]\n\n## Show the new data\nscatter(pts,b)\nxlabel!(\"x\")\nylabel!(\"y\")\n\n## Look at the LS fit\nx = Variable(n)\nproblem = minimize(sumsquares(b - A*x))\nsolve!(problem)\nxls = x.value\nplot!([-11; 11], [1 -11; 1 11]*xls;label=\"fit\")\n\n## Solve the Huber problem and look at the fit\nx = Variable(n)\nproblem = minimize(sum(huber(b - A*x)))\nsolve!(problem)\nxr = x.value\nplot!([-11; 11], [1 -11; 1 11]*xr;label=\"fit_huber\")\n", "meta": {"hexsha": "dc133c67982f0948eaca1272029d564162650915", "size": 1248, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Lecture-3-convex_least_squares.jl", "max_stars_repo_name": "dgleich/CS520-2017", "max_stars_repo_head_hexsha": "520148fb52dcf034561b302c6e2f1e9341c9e883", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-23T17:28:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T17:28:01.000Z", "max_issues_repo_path": "Lecture-3-convex_least_squares.jl", "max_issues_repo_name": "dgleich/CS520-2017", "max_issues_repo_head_hexsha": "520148fb52dcf034561b302c6e2f1e9341c9e883", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lecture-3-convex_least_squares.jl", "max_forks_repo_name": "dgleich/CS520-2017", "max_forks_repo_head_hexsha": "520148fb52dcf034561b302c6e2f1e9341c9e883", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2017-01-12T19:45:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-02T16:02:04.000Z", "avg_line_length": 20.1290322581, "max_line_length": 58, "alphanum_fraction": 0.6306089744, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.7690774190817191}}
{"text": "using Plots\nt = collect(-4:0.2:4)\nfunction huber(t; λ = 1)\n    flag = (abs.(t) .< λ)\n    y1 = t.^2 / 2 .* flag .+ (λ * abs.(t) .- λ^2 / 2) .* (1 .- flag)\n    y2 = λ * abs.(t) .- λ^2 / 2\n    return y1, y2\nend\ny1, y2 = huber(t, λ = 2)\nplot(t, y1, label = \"Huber\", legend = :bottomright)\nplot!(t, y2, label = \"Linear\")\n", "meta": {"hexsha": "2c73cf88ae0ff558670c07eac3100370b4043e3b", "size": 316, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "elements_of_statistical_learning/03-Linear-Methods-for-Regression/assets/script.jl", "max_stars_repo_name": "xishansnow/ElementsOfStatisticalLearning", "max_stars_repo_head_hexsha": "23c636a9818572ac87cce3dc1118791fb3ce578e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "elements_of_statistical_learning/03-Linear-Methods-for-Regression/assets/script.jl", "max_issues_repo_name": "xishansnow/ElementsOfStatisticalLearning", "max_issues_repo_head_hexsha": "23c636a9818572ac87cce3dc1118791fb3ce578e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "elements_of_statistical_learning/03-Linear-Methods-for-Regression/assets/script.jl", "max_forks_repo_name": "xishansnow/ElementsOfStatisticalLearning", "max_forks_repo_head_hexsha": "23c636a9818572ac87cce3dc1118791fb3ce578e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3333333333, "max_line_length": 68, "alphanum_fraction": 0.4936708861, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7690475932782337}}
{"text": "# Polynomial covariance function \n\n@doc \"\"\"\n# Description\nConstructor for the Polynomial kernel (covariance)\n\nk(x,x') = σ²(xᵀx'+c)ᵈ\n# Arguments:\n* `lc::Float64`: Log of the constant c\n* `lσ::Float64`: Log of the signal standard deviation σ\n* `d::Int64`   : Degree of the Polynomial\n\"\"\" ->\ntype Poly <: Kernel\n    lc::Float64      # Log of constant\n    lσ::Float64      # Log of signal std\n    deg::Int64       # degree of polynomial\n    Poly(lc::Float64, lσ::Float64, deg::Int64) = new(lc, lσ, deg)\nend\n\nfunction cov(poly::Poly, x::Vector{Float64}, y::Vector{Float64})\n    c = exp(poly.lc)\n    sigma2 = exp(2*poly.lσ)\n\n    K = sigma2*(c+dot(x,y)).^poly.deg\n    return K\nend\n\nget_params(poly::Poly) = Float64[poly.lc, poly.lσ]\nget_param_names(poly::Poly) = [:lc, :lσ]\nnum_params(poly::Poly) = 2\n\nfunction set_params!(poly::Poly, hyp::Vector{Float64})\n    length(hyp) == 2 || throw(ArgumentError(\"Polynomial function has two parameters\"))\n    poly.lc, poly.lσ = hyp\nend\n\nfunction grad_kern(poly::Poly, x::Vector{Float64}, y::Vector{Float64})\n    c = exp(poly.lc)\n    sigma2 = exp(2*poly.lσ)\n    \n    dK_c   = c*poly.deg*sigma2*(c+dot(x,y)).^(poly.deg-1)\n    dK_sigma = 2.0*sigma2*(c+dot(x,y)).^poly.deg\n    dK_theta = [dK_c,dK_sigma]\n    return dK_theta\nend\n", "meta": {"hexsha": "54a66cdf34ea744660efbae45235f1c276d55aaf", "size": 1256, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/poly.jl", "max_stars_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/poly.jl", "max_issues_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/poly.jl", "max_forks_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3043478261, "max_line_length": 86, "alphanum_fraction": 0.6457006369, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211323, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7690475927987345}}
{"text": "using Images, BenchmarkTools\r\n\r\nfunction calc(a,b)\r\n    z = c = complex(a, b)\r\n    for i in 1:3000\r\n        z = z*z + c \r\n        if abs(z) > 3\r\n            return true\r\n        end\r\n    end\r\n    return false\r\nend\r\n\r\nfunction buddha(points::Array{ComplexF64}, h::Int, w::Int)\r\n    img = zeros(RGB,w,h)\r\n    for c::ComplexF64 in points \r\n        i::Int = 0\r\n        z::ComplexF64 = c\r\n        while abs(z) < 3 && i < 1000\r\n            x::Int = trunc(Int,(real(z) + 2)*w/3); y::Int = trunc(Int,(imag(z) + 1.5)*h/3)\r\n            0<x<w && 0<y<h && i > 20 ? img[x,y] += RGB(0,0,0.004) : nothing #log10(i)/3\r\n            z = z*z + c\r\n            i += 1\r\n        end\r\n    end\r\n    return img\r\nend\r\n\r\nfunction main()\r\n    h::Int = 8000\r\n    w::Int = 8000\r\n    points::Array{ComplexF64} = []\r\n    for b in -1.5:3/h:1.5\r\n        for a in -2.:3/w:1.\r\n            calc(a,b) && append!(points, complex(a,b))\r\n        end\r\n    end\r\n    println(\"Init done\")\r\n    return map(clamp01nan, buddha(points,2000,2000))\r\nend\r\n\r\n#@benchmark main()\r\n@time save(\"./out/buddha.png\", main())", "meta": {"hexsha": "7367d909b39d0ea67dc1a96a4337960d5b432aa8", "size": 1063, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Buddha/out/buddha.jl", "max_stars_repo_name": "BoardTM/fractals", "max_stars_repo_head_hexsha": "cb632df4da880336025ad598f2e121a7feb3fcff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Buddha/out/buddha.jl", "max_issues_repo_name": "BoardTM/fractals", "max_issues_repo_head_hexsha": "cb632df4da880336025ad598f2e121a7feb3fcff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Buddha/out/buddha.jl", "max_forks_repo_name": "BoardTM/fractals", "max_forks_repo_head_hexsha": "cb632df4da880336025ad598f2e121a7feb3fcff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7209302326, "max_line_length": 91, "alphanum_fraction": 0.4816556914, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7690475916403522}}
{"text": "\"\"\"\n    ExpLik <: Likelihood\n\nExponential likelihood\n```math\np(y | f) = θ\\\\exp(-θy),\n```\nwhere ``θ = \\\\exp(-f)`` and ``f`` is the latent Gaussian process.\n\"\"\"\nstruct ExpLik <: Likelihood end\n\n#log of probability density\nfunction log_dens(exponential::ExpLik, f::VecF64, y::VecF64)\n    #where we exponentiate for positivity f = exp(fi)\n    return [-fi - exp(-fi)*yi for (fi,yi) in zip(f,y)]\nend\n\n#derivative of pdf wrt latent function\nfunction dlog_dens_df(exponential::ExpLik, f::VecF64, y::VecF64)\n    return [(yi*exp(-fi)-1) for (fi,yi) in zip(f,y)]\nend\n\n#mean and variance under likelihood\nmean_lik(exponential::ExpLik, f::VecF64) = exp.(f)\nvar_lik(exponential::ExpLik, f::VecF64) = exp.(f).^2\n\nget_params(exponential::ExpLik) = []\nnum_params(exponential::ExpLik) = 0\n\n\n\n\n", "meta": {"hexsha": "8c1b5093bf9f07c90736f6f2616e4511fbf7698b", "size": 775, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/likelihoods/exponential.jl", "max_stars_repo_name": "jbrea/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/likelihoods/exponential.jl", "max_issues_repo_name": "jbrea/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/likelihoods/exponential.jl", "max_forks_repo_name": "jbrea/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4848484848, "max_line_length": 65, "alphanum_fraction": 0.6787096774, "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847494, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7690475908214114}}
{"text": "# p16.jl - Poisson eq. on [-1,1]x[-1,1] with u=0 on boundary\n\n# Set up grids and tensor product Laplacian and solve for u:\nN = 24; (D,x) = cheb(N); y = x;\nxx = x[2:N]; yy = y[2:N];\nf = 10*sin.(8*xx'.*(yy-1));\nD2 = D^2; D2 = D2[2:N,2:N]; I = eye(N-1);\nL = kron(I,D2) + kron(D2,I);                       # Laplacian\nfigure(1); clf(); spy(L);\ntic(); u = L\\f[:]; toc();          # solve problem and watch the clock\n\n# Reshape long 1D results onto 2D grid (flipping orientation):\nuu = zeros(N+1,N+1); uu[N:-1:2,N:-1:2] = reshape(u,N-1,N-1);\nvalue = uu[Int(3N/4+1),Int(3N/4+1)];\n\n# Interpolate to finer grid and plot:\nxxx = yyy = -1:.04:1;\ns = interpolate((x[end:-1:1],y[end:-1:1]),uu,Gridded(Linear()));\nuuu = s[xxx,yyy];\nfigure(2); clf(); surf(xxx,yyy,uuu,rstride=1,cstride=1);\nxlabel(\"x\"); ylabel(\"y\"); zlabel(\"u\"); view(-37.5,30);\ntext3D(.4,-.3,-.3,\"\\$u(2^{-1/2},2^{-1/2})\\$ = $(signif(value,11))\",fontsize=9);\n", "meta": {"hexsha": "c7a94fa2263b541e86ac4d15e1f95ecff1268546", "size": 909, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p16.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p16.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p16.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5217391304, "max_line_length": 79, "alphanum_fraction": 0.5577557756, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774729, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7690475900024707}}
{"text": "#! /usr/bin/julia\n\n# Rosetta Code, Find largest left truncatable prime in a given base\n\nfunction addmsdigit{T<:Integer}(p::T, b::T, s::T)\n    a = T[]\n    q = p\n    for i in 1:(b-1)\n        q += s\n        isprime(q) || continue\n        push!(a, q)\n    end\n    return a\nend\n\nfunction lefttruncprime{T<:Integer}(pbase::T)\n    b = convert(BigInt, pbase)\n    a = BigInt[]\n    append!(a, primes(b-1))\n    mlt = zero(BigInt)\n    s = one(BigInt)\n    while !isempty(a)\n        mlt = maximum(a)\n        s *= b\n        for i in 1:length(a)\n            p = shift!(a)\n            append!(a, addmsdigit(p, b, s))\n        end\n    end\n    return mlt\nend\n\nlo, hi = 3, 17\nprint(\"The largest left truncatable primes for bases\")\nprintln(@sprintf \" %d to %d.\" lo hi)\nfor i in lo:hi\n    mlt = lefttruncprime(i)\n    println(@sprintf \"   %3d %d (%s)\" i mlt base(i, mlt))\nend\n\n", "meta": {"hexsha": "40471e15bd2bd098af5cd42dc9b8e9db2c052fc7", "size": 852, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/completed/largest_left_trunc_primes.jl", "max_stars_repo_name": "MichaeLeroy/rosetta-code", "max_stars_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/completed/largest_left_trunc_primes.jl", "max_issues_repo_name": "MichaeLeroy/rosetta-code", "max_issues_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/completed/largest_left_trunc_primes.jl", "max_forks_repo_name": "MichaeLeroy/rosetta-code", "max_forks_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7804878049, "max_line_length": 67, "alphanum_fraction": 0.5469483568, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211323, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.7690475779770699}}
{"text": "\"\"\"\n    Tcmb(z::Real)\n\nComputes the temperature of the CMB at redshift `z`.\n\"\"\"\nTcmb(z::T) where T = ( 2.728 * ( 1.0 + z ) )\n\n\"\"\"\n    kSzPrefac(ν::Real, z::Real, DI_over_I::Bool)\n\nPrefactor for the kinetic Sunyaev-Zel'dovich effect.\n\"\"\"\nfunction kSzPrefac(ν::Real, z::Real, DI_over_I::Bool)\n\n    kSzPrefac  = -1.0 * σ_T / c_light\n\n    if DI_over_I\n        x   = h_planck * ν / ( k_B * Tcmb(z) )\n\n        kSzPrefac *= exp(x) - 1 / (x * exp(x))\n    end\n\n    return kSzPrefac\nend\n\n\"\"\"\n    kinetic_SZ(n_cm3::Real, vel_y_cgs::Real, \n                    ν::Real=1.e9, z::Real=0.0; \n                    DI_over_I::Bool=false)\n\nComputes the kinetic Sunyaev-Zel'dovich effect from electron density `n_cm3` and velocity in y-direction to the projection plane in cgs units `vel_y_cgs`.\nIf `DI_over_I` is set to `true` you also need to provide an observation frequency `ν` and redshift `z`.\n\"\"\"\nfunction kinetic_SZ(n_cm3::Real, vel_y_cgs::Real, \n                    ν::Real=1.e9, z::Real=0.0; \n                    DI_over_I::Bool=false)\n    return kSzPrefac(ν, z, DI_over_I) * n_cm3 * vel_y_cgs\nend\n\n\"\"\"\n    comptonY(n_cm3::Real, T_K::Real, z::Real)\n\nComputes the Compton-Y parameter from electron density `n_cm3` and temperature `T` in Kelvin at redshift `z`.\n\"\"\"\nfunction comptonY(n_cm3::Real, T_K::Real, z::Real)\n    return yPrefac * n_cm3 * ( T_K - Tcmb(z) )\nend\n\n\"\"\"\n    tSzPrefac(ν::Real, z::Real)\n\nComputes the prefactor for the thermal Sunyaev-Zel'dovich effect.\n\"\"\"\nfunction tSzPrefac(ν::Real, z::Real, DI_over_I::Bool)\n\n    x   = h_planck * ν / ( k_B * Tcmb(z) )\n    tSzPrefac = (x * (exp(x) + 1.0) / (exp(x) - 1.0) - 4.0)\n\n    if DI_over_I\n        tSzPrefac *= exp(x) - 1 / (x * exp(x))\n    end\n\n    return tSzPrefac\nend\n\n\"\"\"\n    thermal_SZ(n_cm3::Real, T_K::Real, z::Real=0.0, ν::Real=1.44e9)\n\nComputes the thermal Sunyaev-Zel'dovich effect for electron density `n_cm3` and temperature `T_K` in Kelvin at redshift `z` and observer frequency `ν`.\n\"\"\"\nfunction thermal_SZ(n_cm3::Real, T_K::Real, \n                    z::Real=0.0, ν::Real=1.44e9; \n                    DI_over_I::Bool=false)\n\n    return tSzPrefac(ν, z, DI_over_I) * comptonY(n_cm3, T_K, z)\nend", "meta": {"hexsha": "264fa2bf6607a5410e0d87ae555cff5a4e446c68", "size": 2156, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/effects/sz_effect.jl", "max_stars_repo_name": "stevengj/SPHtoGrid.jl", "max_stars_repo_head_hexsha": "fef471bb7b2c93ce97952a80e3108760d2db4f23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-26T22:35:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T17:32:01.000Z", "max_issues_repo_path": "src/effects/sz_effect.jl", "max_issues_repo_name": "stevengj/SPHtoGrid.jl", "max_issues_repo_head_hexsha": "fef471bb7b2c93ce97952a80e3108760d2db4f23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2020-07-17T07:56:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T13:53:31.000Z", "max_forks_repo_path": "src/effects/sz_effect.jl", "max_forks_repo_name": "stevengj/SPHtoGrid.jl", "max_forks_repo_head_hexsha": "fef471bb7b2c93ce97952a80e3108760d2db4f23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-23T16:51:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T16:51:07.000Z", "avg_line_length": 28.3684210526, "max_line_length": 154, "alphanum_fraction": 0.6145640074, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7690317412579883}}
{"text": "using StaticArrays\n\n\n\n\"\"\"\n    butcher_tableau_radau_2stages()\n\nReturns (A,b,c) corresponding to the Butcher tableau for the 2 stage Radau IIA scheme.\n\"\"\"\nfunction butcher_tableau_radau_2stages()\n\tA = @SMatrix [5/12   -1/12\n\t              3/4    1/4];\n\tb = @SVector [3/4, 1/4];\n\tc = @SVector [1/3, 1.0];\n\treturn (A, b, c);\nend\n\n\"\"\"\n    butcher_tableau_radau_3stages()\n\nReturns (A,b,c) corresponding to the Butcher tableau for the 3 stage Radau IIA scheme.\n\"\"\"\nfunction butcher_tableau_radau_3stages()\n\tA = @SMatrix [(88.0-7.0*sqrt(6.0))/360.0       (296.0-169.0*sqrt(6.0))/1800.0   (-2.0+3.0*sqrt(6.0))/225.0\n\t              (296.0+169.0*sqrt(6.0))/1800.0   (88.0+7.0*sqrt(6.0))/360.0       (-2.0-3.0*sqrt(6.0))/225.0\n\t              (16.0-sqrt(6.0))/36.0            (16.0+sqrt(6.0))/36.0             1/9];\n\tb = @SVector [(16.0-sqrt(6.0))/36.0,    (16.0+sqrt(6.0))/36.0,    1/9];\n\tc = @SVector [(4.0-sqrt(6.0))/10.0,     (4.0+sqrt(6.0))/10.0,     1.0];\n\treturn (A, b, c);\nend\n", "meta": {"hexsha": "7cc4b50c3025e0eff059f8f3c34f6feeefccb720", "size": 973, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/butchertableau.jl", "max_stars_repo_name": "HoBeZwe/BEAST.jl", "max_stars_repo_head_hexsha": "aa122c9eef0435c8b958f5d257be8f6f5793d422", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2018-06-25T21:04:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T12:29:20.000Z", "max_issues_repo_path": "src/utils/butchertableau.jl", "max_issues_repo_name": "HoBeZwe/BEAST.jl", "max_issues_repo_head_hexsha": "aa122c9eef0435c8b958f5d257be8f6f5793d422", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2017-05-16T16:25:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T00:39:41.000Z", "max_forks_repo_path": "src/utils/butchertableau.jl", "max_forks_repo_name": "HoBeZwe/BEAST.jl", "max_forks_repo_head_hexsha": "aa122c9eef0435c8b958f5d257be8f6f5793d422", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2017-05-12T10:28:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T09:50:24.000Z", "avg_line_length": 31.3870967742, "max_line_length": 107, "alphanum_fraction": 0.5621788284, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392797, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7690317382944105}}
{"text": "using Optim\n\nmutable struct HLT\n\tα::Float64\n\tβ::Float64\n\tl₀::Float64\n\tb₀::Float64\n\n\tHLT() = new(0, 0, 0, 0)\n\tHLT(α::Number, β::Number, l₀::Number, b₀::Number) = new(Float64(α), Float64(β),\n\t\tFloat64(l₀), Float64(b₀))\nend\n\n\nfunction loss(model::HLT, time_series)\n\tα, β, l₀, b₀ = model.α, model.β, model.l₀, model.b₀\n\n\tN = length(time_series)\n\n\tl_t, l_t_, b_t = 0, 0, 0 # l_t_ is the variable to save l(t-1)\n\tloss = 0\n\n\tfor t in 1:N\n\t\tif t == 1\n\t\t\tl_t = l₀\n\t\t\tb_t = b₀\n\t\telse\n\t\t\tl_t = time_series[t - 1] * α + (l_t + b_t) * (1 - α) #b_t is taking b(t-1) value\n\t\tend\n\n\t\tl_t_ = l_t\n\t\ty_pred = l_t + b_t\n\t\tloss += (time_series[t] - y_pred)^2\n\tend\n\n\treturn loss\nend\n\n\nfunction fit(model::HLT, y)\n\tlower = [-Inf, -0.001, -Inf, -Inf]\n\tupper = [1., 1., Inf, Inf]\n\tinitial = [model.α, model.β, model.l₀, model.b₀]\n\n\tfunction loss_(parameters::Array{Float64, 1})\n\t\tα, β, l₀, b₀ = parameters\n\t\treturn loss(HLT(α, β, l₀, b₀), y)\n\tend\n\tres = Optim.optimize(loss_, lower, upper, initial)\n\toptimal = Optim.minimizer(res)\n\treturn HLT(optimal[1], optimal[2], optimal[3], optimal[4])\nend\n\n\nfunction forecast(model::HLT, time_series, forecast_length)\n\tN = length(time_series)\n\tα, β, l₀, b₀ = model.α, model.β, model.l₀, model.b₀\n\tl_t, l_t_, b_t = 0, 0, 0\n\tpred = Array{Float64, 1}(undef, forecast_length)\n    \n    #go through the whole time series making the point by point estimate\n\tfor t in 1:N\n\t\tif t == 1\n\t\t\tl_t = l₀\n\t\t\tb_t = b₀\n\t\telse\n\t\t\tl_t = time_series[t - 1] * α + (l_t + b_t) * (1 - α) #b_t \"is\" b(t-1)\n\t\t\tb_t = β * (l_t - l_t_) + (1 - β) * b_t\n\t\tend\n\t\tl_t_ = l_t\n\tend\n    \n    #The parameter´s values to make the forecast are those estimated in the last step of the time series\n\tl_t = time_series[end] * α + (l_t + b_t) * (1 - α)\n\tb_t = β * (l_t - l_t_) + (1 - β) * b_t\n\t\n\tfor i in 1:forecast_length\n\t\t#y_pred = l_t + b_t * i\n\t\t#push!(pred, y_pred)\n\t\tpred[i] = l_t + b_t * i\n\tend\n\t\t\t\n\treturn pred\nend\n", "meta": {"hexsha": "7ddd8caec558e0f412db60e558ad3f67186bedc7", "size": 1892, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "TSeriesForecast/src/holts_trend_method.jl", "max_stars_repo_name": "lambdaclass/julia_time_series_library", "max_stars_repo_head_hexsha": "4e02a71b485f16aff60ce741b0ad3ce2481fed91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TSeriesForecast/src/holts_trend_method.jl", "max_issues_repo_name": "lambdaclass/julia_time_series_library", "max_issues_repo_head_hexsha": "4e02a71b485f16aff60ce741b0ad3ce2481fed91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TSeriesForecast/src/holts_trend_method.jl", "max_forks_repo_name": "lambdaclass/julia_time_series_library", "max_forks_repo_head_hexsha": "4e02a71b485f16aff60ce741b0ad3ce2481fed91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2588235294, "max_line_length": 104, "alphanum_fraction": 0.61205074, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7690317357009644}}
{"text": "using Interpolations\nusing Plots\npyplot()\n\nf(x) = 2 .* cos(6x) .+ sin(14x) .+ 2.5\nc_grid = 0:.2:1\nn = length(c_grid)\n\nAf = interpolate((c_grid, ), f(c_grid), Gridded(Linear()))\n\nf_grid = linspace(0, 1, 150)\n\nplot(f_grid, f, color=:blue, linewidth=2, alpha=0.8, label=\"true function\")\nplot!(f_grid, Af[f_grid], color=:green, linewidth=2, alpha=0.8,\n      label=\"linear approximation\", legend=:top, grid=false)\nN = repmat(c_grid, 1, 2)'\nheights = [zeros(1,n); f(c_grid)']\nplot!(N, heights, color=:black, linestyle=:dash, alpha=0.5, label=\"\")\n", "meta": {"hexsha": "ef16420a383f0f5d7674825239d0a89e70c8020c", "size": 540, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "optgrowth/linapprox.jl", "max_stars_repo_name": "mwhchen/quantecon", "max_stars_repo_head_hexsha": "1a401e3453cbccbcf609945fced1b478b945446e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "optgrowth/linapprox.jl", "max_issues_repo_name": "mwhchen/quantecon", "max_issues_repo_head_hexsha": "1a401e3453cbccbcf609945fced1b478b945446e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optgrowth/linapprox.jl", "max_forks_repo_name": "mwhchen/quantecon", "max_forks_repo_head_hexsha": "1a401e3453cbccbcf609945fced1b478b945446e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-07-04T01:39:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-04T14:06:38.000Z", "avg_line_length": 28.4210526316, "max_line_length": 75, "alphanum_fraction": 0.6574074074, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7690317331075182}}
{"text": "s = string(\n\"73167176531330624919225119674426574742355349194934\",\n\"96983520312774506326239578318016984801869478851843\",\n\"85861560789112949495459501737958331952853208805511\",\n\"12540698747158523863050715693290963295227443043557\",\n\"66896648950445244523161731856403098711121722383113\",\n\"62229893423380308135336276614282806444486645238749\",\n\"30358907296290491560440772390713810515859307960866\",\n\"70172427121883998797908792274921901699720888093776\",\n\"65727333001053367881220235421809751254540594752243\",\n\"52584907711670556013604839586446706324415722155397\",\n\"53697817977846174064955149290862569321978468622482\",\n\"83972241375657056057490261407972968652414535100474\",\n\"82166370484403199890008895243450658541227588666881\",\n\"16427171479924442928230863465674813919123162824586\",\n\"17866458359124566529476545682848912883142607690042\",\n\"24219022671055626321111109370544217506941658960408\",\n\"07198403850962455444362981230987879927244284909188\",\n\"84580156166097919133875499200524063689912560717606\",\n\"05886116467109405077541002256983155200055935729725\",\n\"71636269561882670428252483600823257530420752963450\")\n\na = [Int32(s[i]-48) for i in 1:length(s)]\nprintln(maximum([reduce(*, a[i:i+12]) for i in 1:length(a)-13]))", "meta": {"hexsha": "d19dd41d7cffdc7f86bfe1846b6cffaa5a101e90", "size": 1199, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "008 - Largest Product in a Series/008 - Largest_Product_in_a_Series.jl", "max_stars_repo_name": "LanguageAdventures/Project-Euler-Julia", "max_stars_repo_head_hexsha": "e4ecad7ed0037f6c2472ac25118466c126cbcf38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-27T10:41:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T14:48:59.000Z", "max_issues_repo_path": "008 - Largest Product in a Series/008 - Largest_Product_in_a_Series.jl", "max_issues_repo_name": "LanguageAdventures/Project-Euler-Julia", "max_issues_repo_head_hexsha": "e4ecad7ed0037f6c2472ac25118466c126cbcf38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "008 - Largest Product in a Series/008 - Largest_Product_in_a_Series.jl", "max_forks_repo_name": "LanguageAdventures/Project-Euler-Julia", "max_forks_repo_head_hexsha": "e4ecad7ed0037f6c2472ac25118466c126cbcf38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.9583333333, "max_line_length": 64, "alphanum_fraction": 0.8940783987, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7690317331075179}}
{"text": "# # Fitting a polynomial with kernels\n#\n# First, let us load the relevant packages and define our problem.\n# We want to interpolate a simple polynomial: `(2x-1)² + 2y + xy - 3`.\n\nusing KernelMachines, Statistics, Plots\n\nf(x, y) = (2x-1)^2 + 2y + x * y - 3\nf((x, y)) = f(x, y)\nrg = 0:0.01:1\nN = length(rg)\nflat = hcat(repeat(rg, inner=N), repeat(rg, outer=N))\ntruth = map(f, eachrow(flat))\ntheme(:wong)\nsurface(rg, rg, reshape(truth, N, N), clims=(-3, 1))\n\n# Let us generate a `6 x 6` trainig grid.\n\nN_train = 6\nrg_train = range(0, 1, length=N_train)\nX = hcat(repeat(rg_train, inner=N_train), repeat(rg_train, outer=N_train))\nY = map(f, eachrow(X));\n\n# Now, let us train a Kernel Machine on the problem.\n\nkrm = KernelMachineRegression(X, Y;\n    dims=(3, 3, 3), kernel=multiplicativegaussiankernel)\nfit!(krm)\n\npred_krm = predict(krm, flat)\nsurface(rg, rg, reshape(pred_krm, N, N), clims=(-3, 1))\n\n# In this problem, a simple Kernel Ridge regression also performs very well.\n\nkr = KernelRegression(X, Y)\nfit!(kr)\npred_kr = predict(kr, flat)\nsurface(rg, rg, reshape(pred_kr, N, N), clims=(-3, 1))\n", "meta": {"hexsha": "2619c98b311dc22029ae385305bb77049272f5d6", "size": 1093, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/polynomial.jl", "max_stars_repo_name": "Veos-Digital/KernelMachines.jl", "max_stars_repo_head_hexsha": "fcd74ecd11e585adf168d78c62a99e75f9f0dec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/polynomial.jl", "max_issues_repo_name": "Veos-Digital/KernelMachines.jl", "max_issues_repo_head_hexsha": "fcd74ecd11e585adf168d78c62a99e75f9f0dec1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/polynomial.jl", "max_forks_repo_name": "Veos-Digital/KernelMachines.jl", "max_forks_repo_head_hexsha": "fcd74ecd11e585adf168d78c62a99e75f9f0dec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0256410256, "max_line_length": 76, "alphanum_fraction": 0.6733760293, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388752, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7689984552965243}}
{"text": "using Winston\n\n\n## We create spline bases on for the function space [5,15] -> Real with evenly-spaced nodes, and\n## apply them to the grid x\nx = linspace(5,15,101)\nX1 = linearSplineBFE(x, (5,15), 11)\nX2 = quadraticSplineBFE(x, (5,15), 11)\nX3 = cubicSplineBFE(x, (5,15), 11)\n\np = FramedPlot()\nmap(i -> add(p, Curve(x, X1[:,i], \"color\", \"black\")), 1:3)\nWinston.display(p)\n\np = FramedPlot()\nmap(i -> add(p, Curve(x, X2[:,i], \"color\", \"red\")), 1:5)\nWinston.display(p)\n\np = FramedPlot()\nmap(i -> add(p, Curve(x, X3[:,i], \"color\", \"blue\")), 1:7)\nWinston.display(p)\n\n\n## Now we use a pre-specified set of nodes\nu = [8.05,11.34,12.31,14.53, 14.75]\nX1 = splineBFE(1, x, u)\nX2 = splineBFE(2, x, u)\n\np = FramedPlot()\nmap(i -> add(p, Curve(x, X1[:,i], \"color\", \"black\")), 1:3)\nWinston.display(p)\n\np = FramedPlot()\nmap(i -> add(p, Curve(x, X2[:,i], \"color\", \"black\")), 1:2)\nWinston.display(p)\n", "meta": {"hexsha": "10bc52ecc1d879fc51eaad743bd668a08e7702c1", "size": 880, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/BSplines.jl", "max_stars_repo_name": "JuliaPackageMirrors/BSplines.jl", "max_stars_repo_head_hexsha": "4fdaec1667c0b5ac05ee251519f6887a117168f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/BSplines.jl", "max_issues_repo_name": "JuliaPackageMirrors/BSplines.jl", "max_issues_repo_head_hexsha": "4fdaec1667c0b5ac05ee251519f6887a117168f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/BSplines.jl", "max_forks_repo_name": "JuliaPackageMirrors/BSplines.jl", "max_forks_repo_head_hexsha": "4fdaec1667c0b5ac05ee251519f6887a117168f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4444444444, "max_line_length": 96, "alphanum_fraction": 0.6125, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229959153748, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7689984501557988}}
{"text": "#   Unit \"tools.jl\" of the Diagonalization.jl Package for Julia language\n#\n#   MIT License\n#   Copyright (c) 2019-2021,\n#   Marco Congedo, CNRS, Grenoble, France:\n#   https://sites.google.com/site/marcocongedo/home\n\n# ? CONTENTS :\n#   This unit implements general tools and internal functions.\n\n\"\"\"\n```julia\nfunction eig(A)\n\nfunction eig(A, B)\n```\nCall Julia function [eigen](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.eigen)\nand return its output sorted by descending\norder of eigenvalues.\n\"\"\"\nfunction eig(A)\n   λ, U=eigen(A)\n   return (reverse(λ), reverse(U, dims=2))\nend\n\nfunction eig(A, B)\n   λ, U=eigen(A, B)\n   return (reverse(λ), reverse(U, dims=2))\nend\n\n\n\"\"\"\n```julia\nfunction nonDiagonality(C::Union{Matrix, Diagonal, SorH})\n```\n\nMeasure of deviancy from diagonality of ``n⋅n`` square matrix `C`, defined as\n(Congedo et al., 2008)[🎓](@ref).\n\n``\\\\frac{\\\\sum_{i≠j}|c_{ij}|^2}{(n-1)\\\\sum_{i}|c_{ii}|^2}``\n\nIt is equal to ``0`` if ``C`` is diagonal, equal to ``1`` if\n``C`` is perfectly uniform.\n\n**Examples:**\n```julia\nusing Diagonalizations\nC=ones(10, 10)                   # uniform matrix\nnd=nonDiagonality(C)             # must be 1\nD=Diagonal(abs.(randn(10, 10)))  # diagonal matrix\nnd=nonDiagonality(D)             # must be 0\n```\n\"\"\"\nfunction nonDiagonality(C::Union{Matrix, Diagonal, SorH})\n   n = size(C, 1)\n   n ≠ size(C, 2) && throw(ArgumentError(\"📌, nonDiagonality function: input matrix must be square\"))\n   ssDiag=sumOfSqrDiag(C)\n   return ((sumOfSqr(C)-ssDiag)/ssDiag)/(n-1)\nend\nnonD=nonDiagonality\n\n\n\"\"\"\n```julia\nfunction spForm(P::Union{Mat, Real, Complex})\n```\nMeasure of deviancy from scaled permutation form of ``n⋅n`` square matrix\n`P`, defined as\n\n``\\\\frac{1}{2(n-1)}\\\\bigg(\\\\sum_{row}1-\\\\beta(row)+\\\\sum_{col}1-\\\\beta(col)\\\\bigg)``,\n\nwhere for each *row* and *column* of `P`, β is the maximum of the\nabsolute values divided by the sum of the absolute values.\n\nThis index is equal to ``0`` if in each row and column ``P``\nhas only one non-zero element, that is, if ``P`` is a scaled permutation matrix.\nThe larger the index, the farther away ``P`` is from this form.\n\nThis measure and several existing variants are well-known in the blind source\nseparation / independent component analysis community,\nwhere it is used to compare approximate joint diagonalization\nalgorithms on simulated data. In fact, if ``A`` is the inverse of the\napproximate joint diagonalizer that is used to generate the data\nand ``B`` the approximate joint diagonalizer estimated by an algorithm,\n``P=BA`` must be as close as possible to a scaled permutation matrix\n(see [scale and permutation](@ref)).\n\nReturn 0.0 (zero) if `P` is a real of complex number.\n\n**Examples:**\n\n```julia\nusing Diagonalizations, PosDefManifold\n# create 20 random commuting matrices\n# they all have the same eigenvectors\nCset=randP(3, 20; eigvalsSNR=Inf, commuting=true)\n# estimate the approximate joint diagonalizer (ajd)\na=ajd(Cset)\n# the ajd must be equivalent to the eigenvector matrix of\n# any of the matrices in Cset\nspForm(a.F'*eigvecs(Cset[1]))+1.0≈1.0 ? println(\" ⭐ \") : println(\" ⛔ \")\n```\n\n\"\"\"\nfunction spForm(P::Union{Mat, Real, Complex})\n   if P isa Number return 0.0 end\n   r, c=size(P)\n   r ≠ c && throw(ArgumentError(\"📌, spForm function: input matrix must be square\"))\n   mos(v::AbstractArray)=1.0-(maximum(v)/sum(v)) # 1- max over sum of a vector\n   (sum(mos(abs.(p)) for p∈eachcol(P)) + sum(mos(abs.(p)) for p∈eachrow(P)))/(2*(r-1))\nend\n\n\n\n\"\"\"\n```julia\n(1)\nfunction genDataMatrix(t::Int, n::Int, A=nothing)\n\n(2)\nfunction genDataMatrix(::Type{Complex{T}},\n                       t::Int, n::Int, A=○) where {T<:AbstractFloat}\n```\n\n(1)\nGenerate a ``t⋅n`` random data matrix as ``XA``,\nwhere ``X`` is a ``t⋅n`` matrix with entries randomly drawn\nfrom a Gaussian distribution and ``A`` a ``n⋅n`` symmetric\nmatrix, which, if not provided as argument `A`,\nwill be generated with entries randomly drawn from a uniform\ndistribution ∈[-1, 1].\n\n(2)\nas (1), but ``X`` is generated randomly from a complex\nGaussian distribution and ``A``is Hermitian (complex)\nwhich, if not provided as argument `A`,\nwill be generated with entries randomly drawn from a uniform\ndistribution ∈[-1-i1, 1+i1].\n\n**Examples:**\n```julia\nA=genDataMatrix(100, 20) # (1), real\nA=genDataMatrix(ComplexF64, 100, 20) # (2), complex\n```\n\n\"\"\"\nfunction genDataMatrix(t::Int, n::Int, A=○)\n   if A===○ A=Symmetric((rand(n, n).-0.5).*2) end\n   return randn(t, n)*A\nend\n\nfunction genDataMatrix(::Type{Complex{T}},\n                       t::Int, n::Int, A=○) where {T<:AbstractFloat}\n  if A===○ A=Hermitian([(rand(T).-(0.5+0.5im)).*2. for i=1:n, j=1:n]) end\n  return randn(T, t, n)*A\nend\n\n\n# -------------------------------------------------------- #\n# INTERNAL FUNCTIONS #\n# -------------------------------------------------------- #\n\n\n# EigenDecomposition with a covariance matrix as input\nfunction _getEVD(C :: Union{Hermitian, Symmetric, Mat}, eVar::TeVaro,\n                 eVarMeth::Function, simple::Bool)\n\n   λ, U = eig(C)\n   λ=_checkλ(λ) # make sure no imaginary noise is present (for complex data)\n   simple ? (U, Matrix(U'), Diagonal(λ), ○, ○, ○) :\n   begin\n     eVar===○ ? eVar=0.999 : ○\n     eVar, D, U, p, arev=_ssd!(eVar, λ, U, _minDim(C), eVarMeth)\n     (U, Matrix(U'), D, eVar, λ, arev)\n   end\nend\n\n\n# EigenDecomposition with a data matrix as input\n_getEVD(X::Mat, covEst::StatsBase.CovarianceEstimator, dims::Int64,\n        mean::Tmean, w::Tw, eVar::TeVaro, eVarMeth::Function, simple::Bool) =\n  _getEVD(_cov(X, covEst, dims, mean, w), eVar, eVarMeth, simple)\n\n\n# Whitening with a covariance matrix as input\nfunction _getWhi(C :: Union{Hermitian, Symmetric, Mat}, eVar::TeVaro,\n                 eVarMeth::Function, simple::Bool)\n\n  U, Uⁱ, D, eVar, λ, arev=_getEVD(C, eVar, eVarMeth, simple)\n  if simple\n     if eltype(C)<:Real\n        ispos(diag(D); tol=eps(eltype(C)), rev=true, 🔔=true,\n        msg=\"negative or almost zero eigenvalue\") || throw(ArgumentError(\"A `simple` linear filter cannot be created. See the warning that has been printed in Julia's REPL\"))\n     end\n     (U*D^-0.5, D^0.5*Uⁱ, D, ○, ○, ○)\n  else\n     (U*D^-0.5, D^0.5*Uⁱ, D, eVar, λ, arev)\n  end\nend\n\n# Whitening with a data matrix as input\n_getWhi(X::Mat, covEst::StatsBase.CovarianceEstimator, dims::Int64,\n        mean::Tmean, w::Tw, eVar::TeVaro, eVarMeth::Function, simple::Bool) =\n   _getWhi(_cov(X, covEst, dims, mean, w), eVar, eVarMeth, simple)\n\n\n# convert mean vector for compatibility with StatsBase.jl\nfunction _convert_mean(mean::Tmean, dims::Int, argName::String)\n  length(mean)≠n && throw(ArgumentError(📌*\", _convert_mean internal function: vector \"*argName*\" must have length $n\"))\n  return dims==1 ? Matrix(mean') : mean\nend\n\n# return `X` or `X` with the mean subtracted, depending on `meanX`\nfunction _deMean(X::Mat, dims::Int, meanX::Tmean)\n   if       meanX isa Int\n            return X\n   elseif   meanX===○\n            meanX_=mean(X; dims=dims)\n   elseif   meanX isa AbstractVector\n            meanX_=_convert_mean(meanX, dims, \"meanX\")\n   end\n   #println(\"dims \", dims, \"  sizemeanX_ \", size(meanX_), \" sizeX \", size(X))\n   if       dims==1\n            s=(1, size(X, 2))\n   elseif   dims==2\n            s=(size(X, 1), 1)\n   end\n   size(meanX_)≠s && throw(ArgumentError(📌*\", _deMean internal function: The size of `meanX_` does not fit input matrix `X` with `dims`=$dims\"))\n   return X.-meanX_\nend\n\n# check arguments for one data matrix input\nfunction _check_data(X::Mat, dims::Int64, covEst::StatsBase.CovarianceEstimator, meanX::Tmean, wX::Tw)\n   dims ∈ (1, 2) || throw(ArgumentError(📌*\", _check-data internal function: Argument `dims` may be 1 or 2. dims=$dims\"))\n   wX≠○ && lenght(wX)≠size(X, dims) && throw(ArgumentError(📌*\", _check-data internal function: The size of `wX` does not fit input matrix `X` with `dims`=$dims\"))\n   eltype(X)<:Complex && covEst≠SCM && throw(ArgumentError(📌*\", _check-data internal function: Only the `SCM` (sample covariance matrix) `covEst` estimator can be used for complex data\"))\n   # TODO add check for meanX\n   ishermitian(X) && throw(ArgumentError(📌*\", _check-data internal function: it looks like\n   you want to call a filter constuctor that takes covariance matrices as input,\n   but you are actually calling the constructor that takes data matrices as input.\n   Solution: flag your covariance matrix(ces) argument(s) as Symmetric or Hermitian,\n   for example, `Hermitian(C)`. To do so, you will need to be using LinearAlgebra.\"))\n   return true\nend\n\n# check arguments for two data matrices input\nfunction _check_data(X::Mat, Y::Mat, dims::Int64, covEst::StatsBase.CovarianceEstimator, meanX::Tmean, meanY::Tmean, wXY::Tw)\n   dims ∈ (1, 2) || throw(ArgumentError(📌*\", _check-data internal function: Argument `dims` may be 1 or 2. dims=$dims\"))\n   size(X, dims)==size(Y, dims) || throw(ArgumentError(📌*\", _check-data internal function: The `dims` dimension of argument `X` and `Y` must be the same\"))\n   wXY≠○ && lenght(wXY)≠size(X, dims) && throw(ArgumentError(📌*\", _check-data internal function: The size of `wXY` does not fit input matrix `X` with `dims`=$dims\"))\n   (eltype(X)<:Complex || eltype(Y)<:Complex) && covEst≠SCM && throw(ArgumentError(📌*\", _check-data internal function: Only the `SCM` (sample covariance matrix) `covEst` estimator can be used for complex data\"))\n   # TODO add check for meanX and meanY\n   return true\nend\n\n\n# check arguments for one vector of data matrix input\nfunction _check_data(𝐗::VecMat, dims::Int64, covEst::StatsBase.CovarianceEstimator, meanX::Into, w::Twf)\n   dims ∈ (1, 2) || throw(ArgumentError(📌*\", _check-data internal function: Argument `dims` may be 1 or 2. dims=$dims\"))\n   x=collect(size(X, _flip12(dims)) for X ∈ 𝐗)\n   all(y->y==x[1], x) ||  throw(ArgumentError(📌*\", _check-data internal function: Given `dims`=$dims, all matrices in `𝐗` must have the same dimension $(_flip12(dims))\"))\n   w≠○ && !(w isa Function) && lenght(w)≠length(𝐗) && throw(ArgumentError(📌*\", _check-data internal function: The size of `w` must be equal to the number of matrices in `𝐗`\"))\n   !isempty(findall(x->eltype(x)<:Complex, 𝐗)) && covEst≠SCM && throw(ArgumentError(📌*\", _check-data internal function: Only the `SCM` (sample covariance matrix) `covEst` estimator can be used for complex data\"))\n   # TODO add check for meanX\n   return true\nend\n\n# check arguments for two vectors of data matrix input\nfunction _check_data(𝐗::VecMat, 𝐘::VecMat, dims::Int64, covEst::StatsBase.CovarianceEstimator, meanX::Into, meanY::Into, w::Twf)\n   dims ∈ (1, 2) || throw(ArgumentError(📌*\", _check-data internal function: Argument `dims` may be 1 or 2. dims=$dims\"))\n   length(𝐗)==length(𝐘) || throw(ArgumentError(📌*\", _check-data internal function: The number of matrices in `𝐗` and `𝐘` must be the same\"))\n   x=collect(size(X, dims)-size(Y, dims) for (X, Y) ∈ (𝐗, 𝐘))\n   norm(x)==0 || throw(ArgumentError(📌*\", _check-data internal function: The `dims` dimension of all pairs of matrices in `𝐗` and `𝐘` must be the same\"))\n   w≠○ && !(w isa Function) && lenght(w)≠length(𝐗) && throw(ArgumentError(📌*\", _check-data internal function: The size of `w` must be equal to the number of matrices in `𝐗` and `𝐘`\"))\n   (!isempty(findall(x->eltype(x)<:Complex, 𝐗)) || !isempty(findall(y->eltype(y)<:Complex, 𝐘))) && covEst≠SCM && throw(ArgumentError(📌*\", _check-data internal function: Only the `SCM` (sample covariance matrix) `covEst` estimator can be used for complex data\"))\n   # TODO add check for meanX and meanY\n   return true\nend\n\n#TODO _check_data(𝑿::VecVecMat, dims::Int64, covEst::StatsBase.CovarianceEstimator, meanX::Into, ○)===○ && return\n\n# call StatsBase.cov within one line with or without weights\n# Also, flag the covariance as Symmetric if is real, Hermitian if is complex\n# The mean is subtracted separatedly for consistence with the other _cov method\n# NB!!! covarianceestimations.jl does not work for complex data input!\nfunction _cov(X::Matrix{R},\n              covEst   :: StatsBase.CovarianceEstimator = SCM,\n              dims     :: Int64 = 1,\n              meanX    :: Tmean = 0,\n              wX       :: Tw = ○) where R<:Real\n   #T = R isa Real ? Symmetric : Hermitian\n   X_=_deMean(X, dims, meanX)\n   return wX===○ ? Symmetric(cov(covEst, X_; dims=dims, mean=0)) : # do NOT remove `mean`=0\n                   Symmetric(cov(covEst, X_, wX; dims=dims, mean=0)) # \"\nend\n\n# `covest` is not used but left in for code homogeneity\nfunction _cov(X::Matrix{R},\n              covEst   :: StatsBase.CovarianceEstimator = SCM,\n              dims     :: Int64 = 1,\n              meanX    :: Tmean = 0,\n              wX       :: Tw = ○) where R<:Complex\n   X_=_deMean(X, dims, meanX)\n   wX≠○ ? ( dims==1 ? X__=wX.*X_ : X__=wX'.*X_ ) : X__=X_\n   return dims==1 ? Hermitian((X__'*X__)/size(X, 1)) : Hermitian((X__*X__')/size(X, 2))\nend\n\n# as before for a vector of data matrices at once\n# NB!!! does not work for complex data input as uses the above method!\nfunction _cov(𝐗::VecMat;\n              covEst   :: StatsBase.CovarianceEstimator = SCM,\n              dims     :: Int64 = 1,\n              meanX    :: Into = 0)\n   # once PosDefManifold supports vectors of Symmetric matrices\n   # T = R===Real ? Symmetric : Hermitian\n   # remove `Hermitian` here below and use T instead\n   # _cov will automatically flag its output\n   𝐂=Vector{Hermitian}(undef, length(𝐗))\n   @threads for i=1:length(𝐗)\n               𝐂[i]=Hermitian(_cov(𝐗[i], covEst, dims, meanX, ○))\n   end\n   return 𝐂\nend\n\n\n# cross-covariance within one line with or without weights\n# The mean is subtracted separately since there is no crosscov method in StatsBase\nfunction _cov(X::Matrix{R}, Y::Matrix{R},\n              dims     :: Int64 = 1,\n              meanX    :: Tmean = 0,\n              meanY    :: Tmean = 0,\n              wXY      :: Tw = ○) where R<:Union{Real, Complex}\n   (size(X, dims) ≠ size(Y, dims)) && throw(ArgumentError(📌*\", _cov internal function: the size of matrices `X` and `Y` are not conform for computing cross-covariance with $dims as value of `dims`\"))\n   X_=_deMean(X, dims, meanX)\n   Y_=_deMean(Y, dims, meanY)\n   return wXY===○ ? ( dims==1 ? (X_'*Y_)/size(X, 1) : (X_*Y_')/size(X_, 2) ) :\n                    ( dims==1 ? ((wXY'.*X_')*Y_)/wXY.sum : ((wXY'.*X_)*Y_')/wXY.sum )\nend\n\n# The same as above, for 2 vectors of data matrices at once\n# the cross-covariance if computed for all corresponding pairs\nfunction _cov(𝐗::VecMat, 𝐘::VecMat;\n              dims     :: Int64 = 1,\n              meanX    :: Into = 0,\n              meanY    :: Into = 0)\n   (length(𝐗)≠length(𝐘)) && throw(ArgumentError(📌*\", _cov internal function: vectors 𝐗 and 𝐘 must hold the same number of data matrices\"))\n   𝐂=Vector{Matrix}(undef, length(𝐗))\n   @threads for i=1:length(𝐗)\n               𝐂[i]=_cov(𝐗[i], 𝐘[i], dims, meanX, meanY, ○)\n            end\n   return 𝐂\nend\n\n\n# if     m=1 𝐗 is a vector of k data matrices.\n#           Return a kx1x1 array of their covariance matrices in the k dimension\n# elseif k=1 𝐗 is a vector of m data matrices.\n#           Return a 1xmxm array of all cross-covariances of 𝐗[i] and 𝐗[j], for i,j=1:m\n# elseif 𝐗 is a k-vector of m data matrices.\n#           Return a kxmxm array of all cross-covariances of 𝐗[l][i] and 𝐗[l][j], for l=1:k, i,j=1:m\nfunction _crossCov(𝐗, m, k;\n                   covEst  :: StatsBase.CovarianceEstimator=SCM,\n                   dims    :: Int64 = 1,\n                   meanX   :: Into = 0,\n                   trace1  :: Bool = false,\n                   w       :: Union{Tw, Function}=○)\n    𝒞=Array{Matrix}(undef, k, m, m)\n    if      m==1\n      @inbounds for κ=1:k 𝒞[κ, 1, 1] = _cov(𝐗[κ], covEst, dims, meanX, ○) end\n    elseif  k==1\n      @inbounds for i=1:m-1, j=i+1:m\n                        𝒞[1, i, j] = _cov(𝐗[i], 𝐗[j], dims, meanX, meanX, ○)\n                        𝒞[1, j, i] = 𝒞[1, i, j]'\n                end\n      @inbounds for i=1:m 𝒞[1, i, i] = _cov(𝐗[i], covEst, dims, meanX, ○) end # This is needed for scaling in any case\n    else\n      @inbounds for κ=1:k, i=1:m-1, j=i+1:m\n                        𝒞[κ, i, j] = _cov(𝐗[κ][i], 𝐗[κ][j], dims, meanX, meanX, ○)\n                        𝒞[κ, j, i]=𝒞[κ, i, j]'\n                end\n      @inbounds for κ=1:k, i=1:m 𝒞[κ, i, i] = _cov(𝐗[κ][i], covEst, dims, meanX, ○) end # This is needed for scaling in any case\n    end\n\n    # trace normalize\n    if trace1 || w ≠ ○ _Normalize!(𝒞, m, k, trace1, w) end\n\n    return 𝒞\nend\n\n\n# get index and value of the\n# first value in 𝜆 greater than or equal to eVar (eVarMeth=searchsortedfirst) or\n# last value in 𝜆 less than or equal to eVar (eVarMeth=searchsortedlast),\n# where 𝜆 is the vector with accumulated regularized (sum-normalized) eigenvalues\n# INPUT:\n# the desired explained variance (real) of subspace dimension (int) (evar),\n# the eigenvalues in descending order (λ),\n# the corresponding eigenvectors (U),\n# the maximum theoretical rank of the input matrix (r),\n# the method (eVarMeth function) for determining the subspace dimension.\n# OUTPUT:\n# the actual explained variance (evar!),\n# the first p eigenvalues (λ!),\n# the corresponding first p eigenvectors (U!),\n# the subspace dimension (p),\n# the vector with the accumulated regularized eigenvalues (arev)\nfunction _getssd!(eVar::TeVaro, λ::Vec, r::Int64, eVarMeth::Function)\n   eltype(λ)<:Complex && @warn \"📌, internal function `_getssd!`: the `λ` vector is complex, subspace dimension is based on its absolute values.\"\n   eVar===○ ? eVar=0.999 : ○\n   λ_=abs.(λ)\n   arev = accumulate(+, λ_./sum(λ_))\n   return (eVar isa Int64 ? clamp(eVar, 1, r) : clamp(eVarMeth(arev, eVar), 1, r), arev)\nend\n\n#see PCA and Whitening\nfunction _ssd!(eVar::TeVaro, λ::Vec, U::Mat, r::Int64, eVarMeth::Function)\n   eltype(λ)<:Complex && @warn \"📌, internal function `_ssd!`: the `λ` vector is complex, subspace dimension is based on its absolute values.\"\n   p, arev = _getssd!(eVar, λ, r, eVarMeth)\n   return p==r ? 1. : arev[p], Diagonal(λ[1:p]), U[:, 1:p], p, arev\nend\n\n#see PMCA and CCA\nfunction _ssdxy!(eVar::TeVaro, λ::Vec, U1::Mat, U2::Mat, r::Int64, eVarMeth::Function)\n   eltype(λ)<:Complex && @warn \"📌, internal function `_ssdxy!`: the `λ` vector is complex, subspace dimension  is based on its absolute values.\"\n   p, arev = _getssd!(eVar, λ, r, eVarMeth)\n   return p==r ? 1. : arev[p], Diagonal(λ[1:p]), U1[:, 1:p], U2[:, 1:p], p, arev\nend\n\n# see CSP\nfunction _ssdcsp!(eVar::TeVaro, λ::Vec, U::Mat, r::Int64, eVarMeth::Function, selMeth::Symbol)\n   eltype(λ)<:Complex && @warn \"📌, internal function `_ssdcsp!`: the `λ` vector is complex, subspace dimension  is based on its absolute values.\"\n   λ_=abs.(λ)\n   ratio = λ_./(1.0.-λ_)\n   d = (log.(ratio)).^2\n   h = selMeth==:extremal ? sortperm(d; rev=true) : [i for i=1:length(λ)]\n   arev = accumulate(+, d[h]./sum(d))\n   if     eVar isa Int\n      p = clamp(eVar, 1, r)\n   elseif eVar isa Real\n      p = clamp(eVarMeth(arev, eVar), 1, r)\n   else    #eVar isa nothing, the default\n      if selMeth==:extremal\n         g=exp(sum(log, d)/length(d))\n         p = clamp(searchsortedlast(d[h], g; rev=true), 1, r)\n      else\n         p = clamp(searchsortedlast(ratio, 1; rev=true), 1, clamp(argmin(d), 1, r))\n      end\n   end\n   return p==r ? 1. : arev[p], Diagonal(λ[h[1:p]]), U[:, h[1:p]], p, arev\nend\n\n# see CSTP\nfunction _ssdcstp!(eVar::TeVaro, λ::Vec, U::Mat, V::Mat, r::Int64, eVarMeth::Function)\n   eltype(λ)<:Complex && @warn \"📌, internal function `_ssdcstp!`: the `λ` vector is complex, subspace dimension is based on its absolute values.\"\n   λ_=abs.(λ)\n   arev = accumulate(+, λ_./sum(λ_))\n   if     eVar isa Int\n      p = clamp(eVar, 1, r)\n   elseif eVar isa Real\n      p = clamp(eVarMeth(arev, eVar), 1, r)\n   else    #eVar isa nothing, the default\n      p = clamp(eVarMeth(arev, 0.999), 1, r)\n   end\n   return p==r ? 1. : arev[p], Diagonal(λ[1:p]), U[:, 1:p], V[:, 1:p], p, arev\nend\n\n\n_flip12(i::Int) =\n   if      i==1 return 2\n   elseif  i==2 return 1\n   else throw(ArgumentError, 📌*\", _flip12 internal function: the `dims` argument must be 1 or 2\")\n   end\n\n\n_set_dims(X::Mat)=argmax(collect(size(X)))\n_set_dims(X::Mat, Y::Mat)=argmax(collect(size(X))+collect(size(Y)))\n_set_dims(𝐗::VecMat)=argmax(sum(collect(size(X)) for X ∈ 𝐗))\n_set_dims(𝐗::VecMat, 𝐘::VecMat)=\n    argmax(sum(collect(size(X)) for X ∈ 𝐗)+sum(collect(size(Y)) for Y ∈ 𝐘))\n_set_dims(𝑿::VecVecMat)=argmax(sum(collect(size(𝑿[i][j])) for i=1:length(𝑿) for j=1:length(𝑿[i])) )\n\n\n_minDim(X::Matrix) = minimum(size(X))\n_minDim(X::Matrix, Y::Matrix) = min(minimum(size(X)), minimum(size(Y)))\n_minDim(C::SorH) = size(C, 1)\n_minDim(𝐂::ℍVector) = minimum(size(C, 1) for C ∈ 𝐂)\n_minDim(C1::SorH, C2::SorH) = min(size(C1, 1), size(C2, 1))\n_minDim(𝐗::VecMat) = minimum(minimum(size(X)) for X ∈ 𝐗)\n_minDim(𝐗::VecMat, 𝐘::VecMat) = min(_minDim(𝐗), _minDim(𝐘))\n_minDim(𝑿::VecVecMat) = minimum((minimum(minimum(size(X)) for X ∈ 𝑿[i]) for i=1:length(𝑿)))\n", "meta": {"hexsha": "b39fdc22b0e835124a75d095bc54744df4cc0d13", "size": 20791, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tools.jl", "max_stars_repo_name": "Marco-Congedo/Diagonalizations.jl", "max_stars_repo_head_hexsha": "135473ab7ee9926cb25ac135aadc79e4c716d422", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2020-01-02T05:10:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T02:16:04.000Z", "max_issues_repo_path": "src/tools.jl", "max_issues_repo_name": "Marco-Congedo/Diagonalizations.jl", "max_issues_repo_head_hexsha": "135473ab7ee9926cb25ac135aadc79e4c716d422", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2020-01-01T19:37:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-26T10:38:14.000Z", "max_forks_repo_path": "src/tools.jl", "max_forks_repo_name": "Marco-Congedo/Diagonalizations.jl", "max_forks_repo_head_hexsha": "135473ab7ee9926cb25ac135aadc79e4c716d422", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:20:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T09:32:27.000Z", "avg_line_length": 42.3441955193, "max_line_length": 261, "alphanum_fraction": 0.6388822086, "num_tokens": 7012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388754, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7689984494917442}}
{"text": "\"\"\"\n        mapr(t, a, b, c, d) -> Real\n\nMaps the value `t` from the interval `[a, b]` to `[c, d]`\n\"\"\"\nfunction mapr(t::Real, a::Real, b::Real, c::Real, d::Real)\n    return c + ((d - c) / (b - a)) * (t - a)\nend\n\"\"\"\n        mapr(t, a, b) -> Real\n\nMaps the value `t` from the interval `[0, 1]` to `[a, b]`\n\"\"\"\nmapr(t::Real, a::Real, b::Real) = mapr(t, 0, 1, a, b)\nmapr(t::Real, (a, b)::Tuple, (c, d)::Tuple) = mapr(t, a, b, c, d)\nmapr(t::Real, (a, b)::Tuple) = mapr(t, a, b)\nmapr(t::Real, A::AbstractRange, B::AbstractRange) = mapr(t, extrema(A), extrema(B))\nmapr(t::Real, A::AbstractRange) = mapr(t, extrema(A))", "meta": {"hexsha": "357b025ad6ebfeabcb48d7bb4840b3f7a7c7969f", "size": 610, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math.jl", "max_stars_repo_name": "jorge-brito/Lynx.jl", "max_stars_repo_head_hexsha": "fcf0326f3125c770a4e5273592391a76f0b13ce3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math.jl", "max_issues_repo_name": "jorge-brito/Lynx.jl", "max_issues_repo_head_hexsha": "fcf0326f3125c770a4e5273592391a76f0b13ce3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math.jl", "max_forks_repo_name": "jorge-brito/Lynx.jl", "max_forks_repo_head_hexsha": "fcf0326f3125c770a4e5273592391a76f0b13ce3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8888888889, "max_line_length": 83, "alphanum_fraction": 0.5278688525, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7689984486635747}}
{"text": "using TuringModels\n\nTuring.setadbackend(:reversediff);\n\nd = CSV.read(joinpath(@__DIR__, \"..\", \"..\", \"data\", \"Kline.csv\"), delim=';');\nsize(d) # Should be 10x5\n\n# New col log_pop, set log() for population data\nd[!, :log_pop] = map((x) -> log(x), d[:, :population]);\n\n# New col contact_high, set binary values 1/0 if high/low contact\nd[!, :contact_high] = map((x) -> ifelse(x==\"high\", 1, 0), d[:, :contact]);\n\n# New col where we center(!) the log_pop values\nmean_log_pop = mean(d[:, :log_pop]);\nd[!, :log_pop_c] = map((x) -> x - mean_log_pop, d[:, :log_pop]);\n\n@model m10_10stan_c(total_tools, log_pop_c, contact_high) = begin\n    α ~ Normal(0, 100)\n    βp ~ Normal(0, 1)\n    βc ~ Normal(0, 1)\n    βpc ~ Normal(0, 1)\n\n    for i ∈ 1:length(total_tools)\n        λ = exp(α + βp*log_pop_c[i] + βc*contact_high[i] +\n            βpc*contact_high[i]*log_pop_c[i])\n        total_tools[i] ~ Poisson(λ)\n    end\nend;\n\nchns = sample(m10_10stan_c(d[:, :total_tools], d[:, :log_pop_c],\n  d[:, :contact_high]), Turing.NUTS(0.65), 1000);\n\n# Rethinking result\n\nm_10_10t_c_result = \"\n    mean   sd  5.5% 94.5% n_eff Rhat\n a   3.31 0.09  3.17  3.45  3671    1\n bp  0.26 0.03  0.21  0.32  5052    1\n bc  0.28 0.12  0.10  0.47  3383    1\n bcp 0.07 0.17 -0.20  0.34  4683    1\n\";\n\n# Describe the draws\n\ndescribe(chns)\n\n# End of m10.10t2.jl\n", "meta": {"hexsha": "6d736d3616e0c1587c69b8f558f03d7b31d4aac9", "size": 1316, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/10/m10.10t2.jl", "max_stars_repo_name": "awellis/TuringModels.jl", "max_stars_repo_head_hexsha": "0b9b31b54344d4358f1cd4b398fb03c1030d3a3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/10/m10.10t2.jl", "max_issues_repo_name": "awellis/TuringModels.jl", "max_issues_repo_head_hexsha": "0b9b31b54344d4358f1cd4b398fb03c1030d3a3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/10/m10.10t2.jl", "max_forks_repo_name": "awellis/TuringModels.jl", "max_forks_repo_head_hexsha": "0b9b31b54344d4358f1cd4b398fb03c1030d3a3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8571428571, "max_line_length": 77, "alphanum_fraction": 0.6048632219, "num_tokens": 522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7689984486635747}}
{"text": "\"\"\"\n`AllenCahnProblem1D` - structure to solve the one-dimensional Allen-Cahn equation, that is, solves\n\nuₜ = Auₓₓ + f(u)\n\non (a, b), where A = Δ and f(u) = -u³ + u.\n\"\"\"\nstruct AllenCahnProblem1D{TLBC, TRBC, TA}\n    a::Real # Left endpoint\n    b::Real # Right endpoint\n    ϵ::Real # Model parameter\n    nₓ::Int # Total number of interior spatial mesh points\n    Δx::Real # Spatial mesh spacing\n    x::Vector # Spatial mesh points including boundary\n    nₜ::Int # Number of timesteps\n    t_max::Real # Final time for integration\n    Δt::Real # Length of timestep\n    left_bc::TLBC # Boundary condition on the left endpoint\n    right_bc::TRBC # Boundary condition on the right endpoint\n    A::TA # Matrix approximation of differential operator for the problem\n    rhs::Vector # Right hand side of the end system\n    f::Function # Nonlinear part of semilinear ODE system (u - u³ for this problem)\n    u::Vector # Solution of the problem\nend\n\n\"\"\"\n`BoundaryCondition` - abstract type to include boundary conditions\n\"\"\"\nabstract type BoundaryCondition end\n\n\"\"\"\n`NeumannBC` - structure to house a Neumann boundary condition, i.e., a boundary condition for which\n\nuₓ(a) = vₗ  or  uₓ(b) = vᵣ\n\"\"\"\nstruct NeumannBC <: BoundaryCondition\n    boundary_condition::Real\nend\n\n\"\"\"\n`PeriodicBC` - structure to house a Periodic boundary condition, i.e., a boundary condition for which\n\nu(a) = u(b), uₓ(a) = uₓ(b)\n\"\"\"\nstruct PeriodicBC <: BoundaryCondition\nend\n\n\"\"\"\n`TimeSteppingMethod` - abstract type to include time stepping methods\n\"\"\"\nabstract type TimeSteppingMethod end\n\n\"\"\"\n`BackwardEulerMethod` - structure for Backward Euler method\n\"\"\"\nstruct BackwardEulerMethod <: TimeSteppingMethod\nend\n\n\"\"\"\n`CrankNicolsonMethod` - structure for Crank-Nicolson method\n\"\"\"\nstruct CrankNicolsonMethod <: TimeSteppingMethod\nend", "meta": {"hexsha": "0abedbd343a224c2fd3e21f2d4190d667923429c", "size": 1798, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/structures.jl", "max_stars_repo_name": "liamfdoherty/AllenCahn.jl", "max_stars_repo_head_hexsha": "871aa90a7216feb00c84a600883d9531a197e7f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/structures.jl", "max_issues_repo_name": "liamfdoherty/AllenCahn.jl", "max_issues_repo_head_hexsha": "871aa90a7216feb00c84a600883d9531a197e7f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/structures.jl", "max_forks_repo_name": "liamfdoherty/AllenCahn.jl", "max_forks_repo_head_hexsha": "871aa90a7216feb00c84a600883d9531a197e7f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5396825397, "max_line_length": 101, "alphanum_fraction": 0.7219132369, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7689984465072968}}
{"text": "# g + g^2 + ... + g^(T-1)\npvfactor(g, T) = (g ^ T - 1.0) / (g - 1.0);\n\n# Present value. First entry not discounted.\npresent_value(xV, R) = sum(xV ./ (R .^ (0 : (length(xV)-1))));\n\n# -----------", "meta": {"hexsha": "e4d6e2aa932c7f009e39bd143fbb2b87f58208d4", "size": 193, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/helpers.jl", "max_stars_repo_name": "hendri54/Huggett890", "max_stars_repo_head_hexsha": "131f00f6995bd6f484121933919f29a225a62b52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-30T14:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-20T05:14:19.000Z", "max_issues_repo_path": "src/helpers.jl", "max_issues_repo_name": "hendri54/Huggett890", "max_issues_repo_head_hexsha": "131f00f6995bd6f484121933919f29a225a62b52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/helpers.jl", "max_forks_repo_name": "hendri54/Huggett890", "max_forks_repo_head_hexsha": "131f00f6995bd6f484121933919f29a225a62b52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5714285714, "max_line_length": 62, "alphanum_fraction": 0.4663212435, "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7689984445723699}}
{"text": "#=\n  Euler #20 in Julia.\n\n  Problem 20:\n  \"\"\"\n  n! means n (n 1) ... 3 2 1\n\n  Find the sum of the digits in the number 100!\")\n  \"\"\"\n\n  This Julia program was created by Hakan Kjellerstrand, hakank@gmail.com\n  See also my Julia page: http://www.hakank.org/julia/\n\n=#\n\ninclude(\"Euler.jl\")\n\n# 0.00029684s\nfunction euler20a()\n    return sum(split(factorial(BigInt(100))|>string,\"\").|>j->parse(Int,j))\nend\n\n# 0.00031793s\nfunction euler20b()\n    return sum(digits(factorial(BigInt(100))))\nend\n\n# 0.00032192s\nfunction euler20c()\n    return factorial(BigInt(100))|>digits|>sum\nend\n\nrun_euler(euler20a)\n# run_euler(euler20b)\n# run_euler(euler20c)\n", "meta": {"hexsha": "084f175aea72d719422e73108a95e9ca8ae01251", "size": 638, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/euler20.jl", "max_stars_repo_name": "Wikunia/hakank", "max_stars_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/euler20.jl", "max_issues_repo_name": "Wikunia/hakank", "max_issues_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/euler20.jl", "max_forks_repo_name": "Wikunia/hakank", "max_forks_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 17.7222222222, "max_line_length": 74, "alphanum_fraction": 0.6818181818, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.768998444129667}}
{"text": "matrixdict = Dict(\"hilb\" => hilb, \"hadamard\" => hadamard,\n                  \"cauchy\" => cauchy, \"circul\" => circul,\n                  \"dingdong\" => dingdong, \"frank\" => frank,\n                  \"invhilb\" => invhilb, \"forsythe\" => forsythe,\n                  \"magic\" => magic, \"grcar\" => grcar,\n                  \"triw\" => triw, \"moler\" => moler,\n                  \"pascal\" => pascal, \"kahan\" => kahan,\n                  \"pei\" => pei, \"vand\" => vand,\n                  \"invol\" => invol, \"chebspec\" => chebspec,\n                  \"lotkin\" => lotkin, \"clement\" => clement,\n                  \"fiedler\" => fiedler, \"minij\" => minij,\n                  \"binomial\" => binomialm, \"tridiag\" => tridiag,\n                  \"lehmer\" => lehmer, \"parter\" => parter,\n                  \"chow\" => chow, \"randcorr\" => randcorr,\n                  \"poisson\" => poisson, \"neumann\" => neumann,\n                  \"rosser\" => rosser, \"sampling\" => sampling,\n                  \"wilkinson\" => wilkinson, \"rando\" => rando,\n                  \"randsvd\" => randsvd, \"rohess\" => rohess,\n                  \"kms\" => kms, \"wathen\" => wathen,\n                  \"oscillate\" => oscillate, \"toeplitz\" => toeplitz,\n                  \"hankel\" => hankel, \"golub\" => golub,\n                  \"companion\" => companion,\n                  \"prolate\" => prolate, \"deriv2\" => deriv2,\n                  \"shaw\" => shaw, \"wing\" => wing,\n                  \"foxgood\" => foxgood, \"heat\" => heat,\n                  \"baart\" => baart, \"phillips\" => phillips,\n                  \"gravity\" => gravity, \"blur\" => blur,\n                  \"spikes\" => spikes, \"ursell\" => ursell,\n                  \"parallax\" => parallax, \"erdrey\" => erdrey,\n                  \"gilbert\" => gilbert, \"smallworld\" => smallworld\n                  );\n\nmatrixclass = Dict(\"symmetric\" => [\"hilb\", \"cauchy\", \"circul\", \"dingdong\",\n                                   \"invhilb\", \"moler\", \"pascal\", \"pei\",\n                                   \"clement\", \"fiedler\", \"minij\", \"tridiag\",\n                                   \"lehmer\", \"randcorr\", \"poisson\", \"wilkinson\",\n                                   \"kms\", \"wathen\", \"oscillate\", \"prolate\", \n                                   \"hankel\"],\n\n             \"inverse\" => [\"hilb\", \"hadamard\", \"cauchy\", \"invhilb\",\n                           \"forsythe\", \"magic\", \"triw\", \"moler\", \"pascal\",\n                           \"kahan\", \"pei\", \"vand\", \"invol\", \"lotkin\",\n                           \"clement\", \"fiedler\", \"minij\", \"tridiag\",\n                           \"lehmer\", \"poisson\", \"kms\" ],\n\n             \"ill-cond\" => [\"hilb\", \"cauchy\", \"frank\", \"invhilb\",\n                            \"forsythe\", \"triw\", \"moler\", \"pascal\",\n                            \"kahan\",\"pei\", \"vand\", \"invol\", \"lotkin\",\n                            \"tridiag\", \"rosser\", \"randsvd\", \"kms\", \n                            \"oscillate\", \"prolate\", \"golub\"],\n\n             \"pos-def\" => [\"hilb\", \"cauchy\", \"circul\", \"invhilb\",\n                           \"moler\", \"pascal\", \"pei\", \"minij\", \"tridiag\",\n                           \"lehmer\", \"poisson\", \"kms\", \"wathen\", \"oscillate\"],\n\n             \"eigen\" =>   [\"hadamard\", \"circul\", \"dingdong\", \"frank\",\n                           \"forsythe\", \"grcar\", \"pascal\", \"invol\",\"chebspec\",\n                           \"lotkin\", \"clement\", \"fiedler\", \"minij\",\n                           \"tridiag\", \"parter\", \"chow\", \"poisson\", \"neumann\",\n                           \"rosser\", \"sampling\", \"wilkinson\",\"wathen\", \n                           \"oscillate\"],\n\n             \"sparse\" => [\"poisson\", \"neumann\", \"wathen\", \"blur\", \"erdrey\", \"gilbert\", \n                          \"smallworld\"],\n\n             \"random\" => [\"rosser\", \"rando\", \"randcorr\", \"randsvd\", \"rohess\",\n                          \"wathen\", \"oscillate\", \"golub\", \"erdrey\", \"gilbert\", \"smallworld\"],\n\n             \"regprob\" => [\"deriv2\", \"shaw\", \"wing\", \"foxgood\", \"heat\", \n                           \"baart\", \"phillips\", \"gravity\", \"blur\", \n                           \"spikes\", \"ursell\", \"parallax\"],\n              \"graph\" => [\"erdrey\", \"gilbert\", \"smallworld\"]\n               );\n", "meta": {"hexsha": "0c99fdbab4975f8f43454c884ea5a647da1c105a", "size": 4079, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/data.jl", "max_stars_repo_name": "JuliaPackageMirrors/MatrixDepot.jl", "max_stars_repo_head_hexsha": "86b9c9ce3ad7bf0ea8f282624696c9174c157bcc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/data.jl", "max_issues_repo_name": "JuliaPackageMirrors/MatrixDepot.jl", "max_issues_repo_head_hexsha": "86b9c9ce3ad7bf0ea8f282624696c9174c157bcc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/data.jl", "max_forks_repo_name": "JuliaPackageMirrors/MatrixDepot.jl", "max_forks_repo_head_hexsha": "86b9c9ce3ad7bf0ea8f282624696c9174c157bcc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.1216216216, "max_line_length": 93, "alphanum_fraction": 0.3993625889, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7689738716641424}}
{"text": "__precompile__(true)\n\nmodule IntroLinearAlgebra\n\nusing Pkg, LinearAlgebra, Requires\n\nexport rowswitch,\n       rowscale,\n       rowadd,\n       rref,\n       eigenvalues,\n       eigenspaces,\n       charpoly,\n       zerooutabove!,\n       zerooutbelow!,\n       rownormalize!,\n       setdigits,\n       setalignment,\n       transformation_movie,\n       svdviz\n\nimport Base: show, eps, inv\n\n#-------------------------------------------------------\n# MATRIX TOOLS\n#-------------------------------------------------------\n\nDIGITS = 4\nALIGNMENT = true\n\nRatOrInt = Union{Rational,Integer}\n\n\"\"\"\n    setdigits!(n::Integer)\n\nSet the number of digits (after the decimal point) to \ndisplay (for matrices with floating-point entries). \n\"\"\"\nfunction setdigits!(n::Integer)\n    global DIGITS\n    DIGITS = n\nend\n\n\"\"\"\n    setalignment!(b::Bool)\n\nDetermine whether to align displayed matrix entries\ndisregarding the sign (true) or including the sign (false)\n\"\"\"\nfunction setalignment!(b::Bool)\n    global ALIGNMENT\n    ALIGNMENT = b\nend\n\n\"\"\"\n    texstring(M)\n\nReturn a string for processing by LaTeX to pretty print\nthe matrix `M`\n\"\"\"\nfunction texstring(M::AbstractArray{T,2}) where T \n    ϵ = T<:RatOrInt ? 0 : eps(norm(M,Inf))\n    function neg(x::Real) # test whether a number is\n                          # genuinely negative (-0.0 isn't)\n        return x < -ϵ\n    end\n    prettystring(x::Bool;padding=false) = \"\\\\mathrm{\"*(x ? \"true\" : \"false\")*\"}\"\n    function prettystring(x::RatOrInt;padding=false)\n        if isa(x,Integer)\n            if padding\n                return neg(x) ? string(x) : \"\\\\hphantom{-}\"*string(x)\n            else\n                return string(x)\n            end\n        elseif x.den == 1\n            return prettystring(x.num,padding=padding)\n        else\n            sgn = neg(x.num) ? \"-\" : (padding ? \"\\\\hphantom{-}\" : \"\")\n            return sgn*\"\\\\frac{\"*string(abs(x.num))*\"}{\"*string(x.den)*\"}\"\n        end\n    end\n    function prettystring(x::Real;padding=false)\n        global DIGITS\n        return (neg(x) ? \"-\" : (padding ? \"\\\\hphantom{-}\" : \"\")) *\n            string(round(abs(x);digits=DIGITS))\n    end\n    function prettystring(z::Complex;padding=false)\n        if ~_isnonzero(z.im,[one(typeof(z.im))])\n            return prettystring(z.re)\n        elseif ~_isnonzero(z.re,[one(typeof(z.re))])\n            return (abs(z.im) == 1 ? \"\" : prettystring(z.im))*\"i\"\n        else\n            return prettystring(z.re)*(neg(z.im) ? \"-\" : \"+\")*prettystring(abs(z.im)*im)\n        end\n    end\n\n    s = \"\\$\\\\left[\\\\begin{array}{\" * repeat(\"c\",size(M,2)) * \"}\"\n    global ALIGNMENT\n    columnpadding = T <: Real ? any(M .< -ϵ, dims=1) : repeat([false],size(M,2))\n\n    for i=1:size(M,1)\n        for j=1:size(M,2)\n            thiscolumnpadding = T <: Real ? any(M[:,j] .< -ϵ) : false\n            s *= prettystring(M[i,j],padding=ALIGNMENT&&columnpadding[j])\n            if j < size(M,2)\n                s *= \" & \"\n            end\n        end\n        s *= \" \\\\\\\\ \"\n    end\n    s *= \"\\\\end{array}\\\\right]\\$\"\n    return s\nend\n\ntexstring(M::AbstractArray{T,1}) where T<:Real = texstring(reshape(M,(length(M),1)))\ntexstring(M::RowVector{T}) where T<:Real = texstring(convert(Array{T,2},M))\n\nshow(io::IO,\n     ::MIME\"text/latex\",\n     s::AbstractArray{T,2}) where T <: Real = write(io, texstring(s))\n\nshow(io::IO,\n     ::MIME\"text/latex\",\n     s::AbstractArray{T,1}) where T <: Real = write(io, texstring(s))\n\nshow(io::IO,\n     ::MIME\"text/latex\",\n     s::AbstractArray{T,2}) where T <: Complex = write(io, texstring(s))\n\nshow(io::IO,\n     ::MIME\"text/latex\",\n     s::AbstractArray{T,1}) where T <: Complex = write(io, texstring(s))\n\n\"\"\"\n    rowswitch(M,i,j)\n\nReturn matrix obtained by switching rows `i` and `j` in matrix `M`\n\n```julia \njulia> M = [1//1 2 3; 4 5 6]\njulia> rowswitch(M,1,2)\n2×3 Array{Rational{Int64},2}:\n 4//1  5//1  6//1\n 1//1  2//1  3//1\n```\n\"\"\"\nfunction rowswitch(M::AbstractArray{T,2},i::Integer,j::Integer) where T \n    A = copy(M)\n    A[i,:], A[j,:] = A[j,:], A[i,:]\n    return A\nend\n\n\"\"\"\n    rowscale(M,i,x)\n\nReturn matrix obtained by scaling row `i` in matrix `M` by \na factor of `x`\n\n```julia \njulia> M = [1 2 3; 4 5 6]\njulia> rowscale(M,1,16)\n2×3 Array{Int64,2}:\n 16  32  48\n  4   5   6\n```\n\"\"\"\nfunction rowscale(M::AbstractArray{T,2},i::Integer,x) where T \n    A = copy(convert(Array{promote_type(T,typeof(x)),2},M))\n    A[i,:] *= x\n    return A\nend\n\n\"\"\"\n    rowadd(M,i,j,x)\n\nReturn matrix obtained by adding `x` times row `j` to \nrow `i` in matrix `M`\n\n```julia \njulia> M = [1 2 3; 4 5 6]\njulia> rowadd(M,1,2,-1)\n2×3 Array{Int64,2}:\n -3  -3  -3\n  4   5   6\n```\n\"\"\"\nfunction rowadd(M::AbstractArray{T,2},\n                i::Integer,\n                j::Integer,\n                x) where T \n    A = copy(convert(Array{promote_type(T,typeof(x)),2},M))\n    A[i,:] += x*A[j,:]\n    return A\nend\n\n\"\"\"\n    rowswitch!(M,i,j)\n\nVersion of `rowswitch` that modifies the argument rather than \nreturning a new matrix\n\"\"\"\nfunction rowswitch!(M::AbstractArray{T,2},i::Integer,j::Integer) where T \n    if i == j\n        return nothing\n    else\n        M[i,:], M[j,:] = M[j,:], M[i,:]\n        return nothing\n    end\nend\n\n\"\"\"\n    rowscale!(M,i,j)\n\nVersion of `rowscale` that modifies the argument rather than \nreturning a new matrix\n\"\"\"\nfunction rowscale!(M::AbstractArray{T,2},i::Integer,x) where T \n    M[i,:] *= x\n    return nothing\nend\n\n\"\"\"\n    rowadd!(M,i,j)\n\nVersion of `rowadd` that modifies the argument rather than \nreturning a new matrix\n\"\"\"\nfunction rowadd!(M::AbstractArray{T,2},i::Integer,j::Integer,x) where T \n    M[i,:] += x*M[j,:]\n    return nothing\nend\n\n\"\"\"\n    _isnonzero(x,M)\n\nCheck whether x is nonzero. Symbols count as nonzero, \nand floats count as zero whenever their absolute value\nis less than roundoff error for floats the size of the \nnorm of M. \n\"\"\"\nfunction _isnonzero(x,M::AbstractArray{T}) where T \n    if isa(x,AbstractFloat) || (isa(x,Complex) && isa(x.re,AbstractFloat))\n        ϵ = T <: AbstractFloat ? eps(norm(M,Inf)) : eps(typeof(x))\n        return abs(x) > ϵ\n    else\n        return x != 0\n    end\nend\neps(::Type{Complex{T}}) where T = 3*eps(T)\neps(z::Complex{T}) where T <: AbstractFloat = 3*(eps(z.re) + eps(z.im))\n\nsimplify(x) = isa(x,Real) ? x :\n    (string(typeof(x)) == \"SymPy.Sym\" ? symplify(x) : x)\n\n\"\"\"\n    rref(M;showsteps=false)\n\nCompute the reduced row echelon form of M and return \nthe RREF if `showsteps` is `false`, and the sequence of \nsteps performed to compute the RREF if `showsteps` is \n`true`\n\n```julia \njulia> M = [1//1 2 3; 4 5 6]\njulia> rref(M)\n2×3 Array{Rational{Int64},2}:\n 1//1  0//1  -1//1\n 0//1  1//1   2//1\njulia> rref(M;showsteps=true)\n4-element Array{Array{Rational{Int64},2},1}:\n Rational{Int64}[1//1 2//1 3//1; 4//1 5//1 6//1]  \n Rational{Int64}[1//1 2//1 3//1; 0//1 -3//1 -6//1]\n Rational{Int64}[1//1 2//1 3//1; 0//1 1//1 2//1]  \n Rational{Int64}[1//1 0//1 -1//1; 0//1 1//1 2//1] \n```\n\"\"\"\nfunction rref(M::AbstractArray{T,2};showsteps=false) where T \n    isnonzero(x) = _isnonzero(x,M)\n    S = T <: Rational ? T.parameters[1] : T\n    if T <: RatOrInt\n        newtype = Rational{S}\n    elseif T <: Complex && T.parameters[1] <: Integer\n        newtype = Complex{Rational{T.parameters[1]}}\n    elseif T <: Complex && T.parameters[1] <: Rational\n        newtype = Complex{T.parameters[1]}\n    else\n        newtype = promote_type(typeof(inv(one(T))),T)\n    end\n    A = copy(convert(Array{newtype,2},M))\n    steps = typeof(A)[]\n    current_row = 1\n    for j=1:size(A,2)\n        if ~any(isnonzero.(A[current_row:end,j]))\n            if issubtype(T,AbstractFloat)\n                A[current_row:end,j] = 0\n            end\n        else\n            i = current_row-1 + findfirst(isnonzero.(A[current_row:end,j]))\n            rowswitch!(A,current_row,i)\n            if showsteps push!(steps,copy(A)) end\n            zerooutbelow!(A,current_row,j)\n            if showsteps push!(steps,copy(A)) end\n            rownormalize!(A,current_row)\n            if showsteps push!(steps,copy(A)) end\n            current_row += 1\n            if current_row > size(A,1)\n                break\n            end\n        end\n        map!(simplify,A,A)\n    end\n    for i=size(A,1):-1:1\n        if ~any(isnonzero.(A[i,:]))\n            continue\n        else\n            j = findfirst(isnonzero.(A[i,:]))\n            zerooutabove!(A,i,j)\n            if showsteps push!(steps,copy(A)) end\n        end\n    end\n    if showsteps\n        uniquesteps = typeof(A)[]\n        for i=1:length(steps)\n            if i == 1 || steps[i] != uniquesteps[end]\n                push!(uniquesteps,steps[i])\n            end\n        end\n        return uniquesteps\n    else\n        return A\n    end\nend\n\n\"\"\"\n    zerooutbelow!(M,i,j)\n\nUse row operations to zero out entries in column `j` below row `i`\n\n```julia \njulia> M = [1//1 2 3; 4 5 6]\njulia> zerooutbelow!(M,1,2)\njulia> M\n2×3 Array{Rational{Int64},2}:\n 1//1  2//1   3//1\n 3//2  0//1  -3//2\n```\n\"\"\"\nfunction zerooutbelow!(M::Array{T,2},i::Integer,j::Integer)::Nothing where T\n    for k=i+1:size(M,1)\n        rowadd!(M,k,i,T<:RatOrInt ? -M[k,j]//M[i,j] : -M[k,j]/M[i,j])\n    end\n    return nothing\nend\n\n#----------------------------------------------------------------\n\"\"\"\n    zerooutabove!(M,i,j)\n\nUse row operations to zero out entries in column `j` above row `i`\n\n```julia \njulia> M = [1//1 2 3; 4 5 6]\njulia> zerooutabove!(M,2,2)\njulia> M\njulia> M\n2×3 Array{Rational{Int64},2}:\n -3//5  0//1  3//5\n  4//1  5//1  6//1\n```\n\"\"\"\nfunction zerooutabove!(M::Array{T,2},i::Integer,j::Integer)::Nothing where T \n    for k=1:i-1\n        rowadd!(M,k,i,T<:RatOrInt ? -M[k,j]//M[i,j] : -M[k,j]/M[i,j])\n    end\n    return nothing\nend\n\n#----------------------------------------------------------------\n\"\"\"\n    rownormalize!(M,i)\n\nScale row `i` in matrix `M` to make the leading entry 1\n\n```julia \njulia> M = [1//1 2 3; 4 5 6]\njulia> rownormalize!(M,2)\njulia> M\n2×3 Array{Rational{Int64},2}:\n 1//1  2//1  3//1\n 1//1  5//4  3//2\n```\n\"\"\"\nfunction rownormalize!(M::Array{T,2},i::Integer)::Nothing where T\n    isnonzero(x) = _isnonzero(x,M)\n    j = findfirst(isnonzero.(M[i,:]))\n    rowscale!(M,i, T<:RatOrInt ? 1//M[i,j] : 1/M[i,j])\n    return nothing\nend\n\nfunction inv(A::Union{Array{Rational{T},2},Array{T,2}}) where T <: Integer\n    if size(A,1) != size(A,2)\n        error(\"Matrix not square\")\n    end\n    n = size(A,1)\n    E = rref([A I])\n    C,D = E[:,1:n], E[:,n+1:end]\n    if C != I\n        error(\"Not invertible\")\n    else\n        return D\n    end\nend\n\n\n#----------------------------------------------------------------------------\n# GRAPHICS TOOLS\n#----------------------------------------------------------------------------\n\n\nfunction __init__()\n    \n    Requires.@require SymPy=\"24249f21-da20-56a4-8eb1-6a02cf4ae2e6\" begin\n\n        symplify(x) = SymPy.simplify(x)\n\n        texstring(A::Array{SymPy.Sym}) = SymPy.sympy[:latex](A)\n\n        struct EigenSpace\n            λ\n            mult\n            eigenmatrix\n        end\n        \n        function texstring(E::EigenSpace)\n            s = \"\\\\mathrm{eigenspace}\\\\left(\"\n            s *= \"λ = \"\n            s *= SymPy.latex(E.λ,itex=true)*\", \"\n            s *= \"\\\\mathrm{mult} = \"*string(E.mult)*\", \"\n            s *= \"\\\\mathrm{Col}\\\\left(\"\n            io = IOBuffer()\n            show(io,(MIME\"text/latex\").instance,E.eigenmatrix)\n            s *= String(take!(io))\n            s *= \"\\\\right)\\\\right)\"\n        end\n        \n        function show(io::IO,M::MIME\"text/latex\",E::EigenSpace)\n            write(io,\"\\$\"*texstring(E)*\"\\$\")\n        end\n\n        function show(io::IO,E::EigenSpace)\n            s = \"eigenspace(\\n\"\n            s *= \"λ = \"\n            _io = IOBuffer()\n            show(_io,(MIME\"text/plain\").instance,E.λ)\n            s *= String(take!(_io))\n            s *= \", mult = \"*string(E.mult)*\", \"\n            show(_io,E.eigenmatrix)\n            s *= String(take!(_io))\n            s *= \"\\n)\"\n            print(io,s)\n        end\n\n        function show(io::IO,::MIME\"text/plain\",A::Array{EigenSpace,1})\n            for (k,E) in enumerate(A)\n                show(io,E)\n                if k < length(A)\n                    print(io,\"\\n\\n\")\n                end\n            end\n        end\n\n        function show(io::IO,M::MIME\"text/latex\",A::Array{EigenSpace,1})\n            print(io,\"\\$\\$\\\\begin{bmatrix}\")\n            for E in A\n                write(io,texstring(E))\n                print(io,\"\\\\\\\\\")\n            end\n            print(io,\"\\\\end{bmatrix}\\$\\$\")\n        end\n\n        \"\"\"\n        eigenvalues(M)\n\n        Uses SymPy to find the exact eigenvalues of M\n\n        ```julia \n        julia> M = [1 2; 4 5]\n        julia> eigenvalues(M)\n        2-element Array{SymPy.Sym,1}\n        ⎡3 + 2⋅√3 ⎤\n        ⎢         ⎥\n        ⎣-2⋅√3 + 3⎦\n        ```\n        \"\"\"\n        function eigenvalues(A::Array{T,2}) where T \n            _loadsympy()\n            return SymPy.solve(charpoly(A))\n        end\n\n        \"\"\"\n        eigenvalues(M)\n\n        Use SymPy to find the exact eigenvalues of M\n\n        ```julia \n        julia> M = [1 2; 4 5]\n        julia> eigenspaces(M)\n        eigenspace(\n        λ = 3 + 2 \\\\sqrt{3}, mult = 1, \n        ⎡  1   √3⎤\n        ⎢- ─ + ──⎥\n        ⎢  2   2 ⎥\n        ⎢        ⎥\n        ⎣   1    ⎦\n        )\n\n        eigenspace(\n        λ = - 2 \\\\sqrt{3} + 3, mult = 1, \n        ⎡  √3   1⎤\n        ⎢- ── - ─⎥\n        ⎢  2    2⎥\n        ⎢        ⎥\n        ⎣   1    ⎦\n        )\n        ```\n        \"\"\"\n        function eigenspaces(A::Array{T,2}) where T \n            B = map(x->convert(SymPy.Sym,x),A)\n            return [EigenSpace(a,b,map(SymPy.simplify,hcat(c...))) for\n                    (a,b,c) in SymPy.getindex(B,:eigenvects)()]\n        end\n\n        \"\"\"\n        charpoly(M)\n\n        Uses SymPy to find the characteristic polynomial of M\n    \n        ```julia \n        julia> M = [1 2; 4 5]\n        julia> charpoly(M)\n        ```\n        \"\"\"\n        function charpoly(A::Array{T,2}) where T \n            λ = SymPy.symbols(\"lambda\")\n            B = map(x->convert(SymPy.Sym,x),A)\n            return SymPy.getindex(B,:charpoly)()(λ)\n        end\n        \n    end\n\n    Requires.@require AsyPlots=\"77e5a97a-5ef9-58df-9d21-21957d92d960\" begin \n        \n        \"\"\"\n        transformation_movie(A,n;frames=20)\n\n        Return an array of Graphics2D arrays which give a dynamic\n        picture of how A transforms integer grid lines in [-n,n]^2\n\n        ```julia\n        julia> A = [0 2; -1 0]\n        julia> movie = transformation_movie(A,10,20);\n        julia> using Interact\n        julia> @manipulate for i=1:length(movie)\n                   movie[i]\n               end\n        ```\n        \"\"\"\n        transformation_movie(A::Array{T,2};kwargs...) where T =\n            transformation_movie((x,y)->A*[x;y];kwargs...)\n\n        function transformation_movie(f::Function;\n                                      gridlines::Integer=8,\n                                      frames::Integer=20)\n\n            n = gridlines\n\n            Path = AsyPlots.Path\n            Point = AsyPlots.Point\n            NamedColor = AsyPlots.NamedColor\n\n            mypath(A::Array{<:Real,2};kwargs...) = Path([tuple(A[k,:]...) for k=1:size(A,1)];kwargs...)\n            mypath(A::Array{T,1};kwargs...) where T = Path([tuple(v...) for v in A];kwargs...)\n            sc(r::Real,s::String) = r*NamedColor(s)\n\n            m = 2.05*max(norm(f(n,n),Inf),norm(f(-n,n),Inf))\n            box = mypath([-m -m; m -m; m m; -m m; -m -m];color=\"white\")\n            return [AsyPlots.Plot(vcat([[Path([0 0; m 0]),Path([0 0; m 0])];\n                                        [mypath([(1-t)*[j,k] + t*f(j,k) for j=-n:0.1:n];\n                                                linewidth=1.5,color=sc(0.9,\"DarkRed\")) for k=-n:n];\n                                        [mypath([(1-t)*[j,k] + t*f(j,k) for k=-n:0.1:n];\n                                                linewidth=1.5,color=sc(0.9,\"MidnightBlue\")) for j=-n:n];\n                                        [Point(0,0;linewidth=1e-2)];\n                                        [box]]...))\n                    for t=range(0,stop=1,length=frames)]\n        end\n\n        function svdviz(A::Array{T,2},\n                        B::Array{T,2}=A;\n                        n=5,\n                        frames=20,\n                        gridlinewidth=1,\n                        graylinewidth=1,\n                        pointsize=1,\n                        kwargs...) where T <: Real\n\n            Path = AsyPlots.Path\n            Point = AsyPlots.Point\n            Arrow = AsyPlots.Arrow\n            Plot = AsyPlots.Plot\n            \n            U, Σ, V = svd(A)\n            m = 1.05*max(norm(A*V*[n,n],Inf),norm(A*V*[-n,n],Inf),norm(A*V*[-n,-n],Inf))\n            mybox = Path([-m -m; m -m; m m; -m m; -m -m];color=\"white\")\n            loc(j,k,t) = tuple((j*B*V[:,1] + k*B*V[:,2])*t + (j*V[:,1] + k*V[:,2])*(1-t)...)\n            pts(t) = vcat([Point(loc(j,k,t);linewidth=pointsize) for j=-n:n,k=-n:n]...)\n            bluelines(t) = [Path([loc(j,k,t) for j=-n:n];linewidth=gridlinewidth,color=\"MidnightBlue\") for k=-n:n]\n            redlines(t) = [Path([loc(j,k,t) for k=-n:n];linewidth=gridlinewidth,color=\"DarkRed\") for j=-n:n]\n            graylines = [[Path([(j,k) for j=-n:n];color=\"Gray\",linewidth=graylinewidth,opacity=0.3) for k=-n:n];\n                         [Path([(j,k) for k=-n:n];color=\"Gray\",linewidth=graylinewidth,opacity=0.3) for j=-n:n]]\n            axes = [Path([0 0; 0 m]),Path([0 0; m 0])]\n            basisvectors(t) = [Path([(0,0),tuple([1,0]*(1-t) + A*[1,0]*(t)...)];arrow=Arrow(),linewidth=1.5,color=\"SeaGreen\"),\n                               Path([(0,0),tuple([0,1]*(1-t) + A*[0,1]*(t)...)];arrow=Arrow(),linewidth=1.5,color=\"DarkRed\")]\n            [Plot([graylines;\n                   basisvectors(t);\n                   bluelines(t);\n                   redlines(t);\n                   pts(t);\n                   [mybox]];kwargs...) for t = range(0,stop=1,length=frames)]\n        end\n\n    end\n\nend\n\nend # module\n", "meta": {"hexsha": "20e3dfee085fd413c94fd8bf2fafa34508921f71", "size": 17896, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/IntroLinearAlgebra.jl", "max_stars_repo_name": "JuliaTagBot/IntroLinearAlgebra.jl", "max_stars_repo_head_hexsha": "c07b53618130bb019bac32143774555e286e29e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-10-20T18:13:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-10T02:27:10.000Z", "max_issues_repo_path": "src/IntroLinearAlgebra.jl", "max_issues_repo_name": "JuliaTagBot/IntroLinearAlgebra.jl", "max_issues_repo_head_hexsha": "c07b53618130bb019bac32143774555e286e29e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IntroLinearAlgebra.jl", "max_forks_repo_name": "JuliaTagBot/IntroLinearAlgebra.jl", "max_forks_repo_head_hexsha": "c07b53618130bb019bac32143774555e286e29e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-04-16T08:08:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-31T14:12:38.000Z", "avg_line_length": 28.1383647799, "max_line_length": 126, "alphanum_fraction": 0.4989941886, "num_tokens": 5521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.9005297807787537, "lm_q1q2_score": 0.7689738709156035}}
{"text": "\"\"\" Julia module to check data for a Simpson's statistical paradox \"\"\"\nmodule Simpsons\n\nexport has_simpsons_paradox, make_paradox, plot_clusters, plot_kmeans_by_factor, find_clustering_elbow, simpsons_analysis\n\nusing DataFrames, Distributions, Polynomials, Clustering, Plots\n\n\"\"\"\n    has_simpsons_paradox(df, cause, effect, factor;\n        continuous_threshold = 5, cmax = 5, verbose = true)\n\nReturns true if the data aggregated by `factor` exhibits Simpson's paradox.\nNote that the `cause` and `effect` columns will be converted to Int columns if\nthey are not already numeric in type. A continuous data `factor` column (one\nwith `continuous_threshold` or more discrete levels) will be grouped into a\nat most cmax clusters so as to avoid too many clusters. Prints the regression\nslope directions for overall data and groups if verbose is true.\nExample:\n    df = DataFrame(\n        treatment = [1, 2, 1, 1, 2, 2],\n        recovery = [1, 0, 1, 1, 0, 0],\n        kidney_stone_size = [\"small\", \"small\", \"large\", \"small\", \"large\", \"large\"])\n    has_simpsons_paradox(df, :treatment, :recovery, :kidney_stone_size)\n\"\"\"\nfunction has_simpsons_paradox(df, cause, effect, factor; continuous_threshold = 5, cmax = 5, verbose = true)\n    df1 = DataFrame()\n\n    # Convert cause and effect column data types to numeric if needed\n    df1[:, cause] = (df[1, cause] isa Number ? df[!, cause] : _makenumeric(df[!, cause]))\n    df1[:, effect] = (df[1, effect] isa Number ? df[!, effect] : _makenumeric(df[!, effect]))\n    if df[1, factor] isa Number || length(unique(df[!, factor])) < continuous_threshold\n        df1[:, factor] = df[!, factor]\n    else\n        df1[:, factor] = _makenumeric(df[!, factor])\n    end\n\n    # Do linear regression on the cause versus effect columns.\n    m = Polynomials.fit(df1[!, effect], df1[!, cause], 1)\n    overallslope = m.coeffs[2]\n\n    # Group by the factor and do a similar linear regression on each group when possible\n    # first check for continous factor type, if number of unique values > continuous_threshold\n    fac = df1[!, factor]\n    uni = unique(fac)\n    if length(uni) >= continuous_threshold && uni[1] isa Number\n        # continuous factor, so find best cluster number up to cmax\n        groupmat = zeros(eltype(uni), (2, length(fac)))\n        groupmat[1, :] .= fac\n        _, kmclust = find_clustering_elbow(groupmat, 2, cmax)\n        grou = Symbol(\"grouped\" * string(factor))\n        insertcols!(df1, grou => kmclust.assignments)\n        grouped = groupby(df1, grou)\n    else\n        grouped = groupby(df1, factor)\n    end\n    subgroupslopes = Float64[]\n    for gdf in grouped\n        length(gdf[!, effect]) < 2 && continue\n        gm = Polynomials.fit(gdf[!, effect], gdf[!, cause], 1)\n        length(gm.coeffs) < 2 && continue\n        push!(subgroupslopes, gm.coeffs[2])\n    end\n    if verbose\n        println(\"For cause $cause, effect $effect, and factor $factor:\")\n        println(\"Overall linear trend from cause to effect is \",\n            overallslope > 0 ? \"positive.\" : \"negative.\")\n    end\n    differentslopesigns = false\n    for (i, slp) in enumerate(subgroupslopes)\n        verbose && println(\"    Subgroup $i trend is \", slp > 0 ? \"positive.\" : \"negative.\")\n        if sign(slp) != sign(overallslope)\n            verbose && println(\"        This shows a Simpson paradox type reversal.\")\n            differentslopesigns = true\n        end\n    end\n    verbose && println()\n    return differentslopesigns\nend\n\n\"\"\"\n    make_paradox(nsubgroups = 3 , N = 1024)\n\nReturn a dataframe containing `N` rows of random data in 3 columns `:x` (cause), \n`:y` (effect), and `:z` (cofactor) which displays the Simpson's paradox.\n\"\"\"\nfunction make_paradox(nsubgroups = 3 , N = 1024)\n    rw = rand(nsubgroups)\n    w = rw ./ sum(rw)\n    m = rand(MvNormal([0, 0], 3 .* [1 0.7; 0.7 1]), nsubgroups)\n    cv = [[1 -c; -c 1] for c in rand(Uniform(0.1, 0.9), nsubgroups)]\n\n    dfs = DataFrame(:x => Float64[], :y => Float64[], :z => Int[])\n    for subgroup in 1:nsubgroups\n        subN = Int(round(N .* w[subgroup]))\n        xarr, yarr = Float64[], Float64[]\n        for _ in 1:subN\n            x, y = rand(MvNormal(m[:, subgroup], cv[subgroup]), 2)\n            push!(xarr, x)\n            push!(yarr, y)\n        end\n        samp = DataFrame(:x => xarr, :y => yarr, :z => fill(subgroup, subN))\n        append!(dfs, samp)\n    end\n    return has_simpsons_paradox(dfs, :x, :y, :z, verbose=false) ? dfs : make_paradox(nsubgroups, N)\nend\n\n\"\"\"\n    plot_clusters(df, cause, effect)\n\nPlot, with subplots, clustering of the dataframe using `cause` (X axis) and `effect` (Y axis)\nplotted and color coded by clusterings. Use kmeans clustering analysis on all fields of\ndataframe. Use 2 to 5 as cluster number. Converts non-numeric columns to numeric for processing.\n\"\"\"\nfunction plot_clusters(df, cause, effect)\n    # convert non-numeric columns to numeric ones\n    df1 = DataFrame()\n    for nam in names(df)\n        df1[:, nam] = df[1, nam] isa Number ? df[!, nam] : _makenumeric(df[!, nam])\n    end\n    factors = collect(Matrix(df1)')\n    subplots = Plots.Plot[]\n    for n in 2:5\n        push!(subplots, scatter(df1[!, cause], df1[!, effect],\n            marker_z = kmeans(factors, n).assignments, color = :lightrainbow,\n            title = \"$cause -> $effect with $n clusters\", legend = false,\n            xlabel = cause, ylabel = effect, smooths = true))\n    end\n    plt = scatter(subplots..., layout = (2, 2), smooths=true)\n    display(plt)\nend\n\n\"\"\"\n    plot_kmeans_by_factor(df, cause_column, effect_column, factor_column)\n\nPlot clustering of the dataframe using cause plotted as X, effect as Y, with the `factor_column`\nused for kmeans clustering into between 2 and 5 clusters on the plot.\n\"\"\"\nfunction plot_kmeans_by_factor(df, cause_column, effect_column, factor_column)\n    df1 = DataFrame(cause_column => df[!, cause_column], effect_column => df[!, effect_column],\n        factor_column => df[1, factor_column] isa Number ? df[!, factor_column] : _makenumeric(df[!, factor_column]))\n    fac = df1[!, factor_column]\n    uni = unique(fac)\n    groupmat = zeros(eltype(uni), (2, length(fac)))\n    groupmat[1, :] .= fac\n    karray = [kmeans(groupmat, i) for i in 1:6]\n    x1, y1 = 1, karray[1].totalcost\n    x2, y2 = 6, karray[6].totalcost\n    (_, idx) = findmax(map(i -> distance(x1, y1, x2, y2, i, karray[i].totalcost), 2:5))\n    grou = Symbol(\"grouped\" * string(factor_column))\n    df1[:, grou] = karray[idx + 1].assignments\n    groups = groupby(df1, grou)\n    plt = scatter(df1[!, cause_column], df[!, effect_column], color = :black, smooth = true,\n        title = \"$cause_column -> $effect_column with cofactor $factor_column\",\n        xlabel = cause_column, ylabel = effect_column, legend = false)\n    for (i, gf) in enumerate(groups)\n        scatter!(plt, gf[!, cause_column], gf[!, effect_column], color = _pcolor(i), smooth = true, legend = false)\n    end\n    display(plt)\nend\n\n\"\"\"\n    simpsons_analysis(df, cause_column, effect_column; verbose = true, show_plots = true)\n\nAnalyze the dataframe `df` assuming a cause is in `cause_column` and an effect in\n`effect_column` of the dataframe. Output data including any Simpson's paradox type\nreversals in subgroups found. Plots shown if show_plots is true (default).\n\"\"\"\nfunction simpsons_analysis(df, cause_column, effect_column; verbose=true, show_plots = true)\n    # Plot cluster analysis for clustering numbers 2 through 5\n    show_plots && plot_clusters(df, cause_column, effect_column)\n    # plot clusterings by factor\n    for factor in Symbol.(names(df))\n        factor in [cause_column, effect_column] && continue\n        if show_plots && df[1, factor] isa Number\n            plot_kmeans_by_factor(df, cause_column, effect_column, factor)\n        end\n        has_simpsons_paradox(df, cause_column, effect_column, factor, verbose=verbose)\n    end\nend\n\n\"\"\"\n    find_clustering_elbow(dataarray::AbstractMatrix{<:Real}, cmin = 1, cmax = 5; fclust = kmeans, kwargs...)\n\nFind the \"elbow\" of the totalcost versus cluster number curve, where\ncmin <= elbow <= cmax. Note that in pathological cases where the actual\nminimum of the totalcosts occurs at a cluster count less than that of the\ncurve \"elbow\", the function will return either cmin or the actual cluster\ncount at which the totalcost is at minimum, whichever is larger. The default\nclustering function is kmeans, but other functions which take two required \naguments, a matrix of data plus a desired cluster number and return a\nClusteringResult as defined in the Clustering package may be used.\n<br>\nReturns a tuple: the cluster count and the ClusteringResult at the \"elbow\" optimum.\n\"\"\"\nfunction find_clustering_elbow(dataarray::AbstractMatrix{<:Real}, cmin = 1, cmax = 5; fclust = kmeans, kwargs...)\n    allkmeans = [fclust(dataarray, i, kwargs...) for i in 1:cmax+1]\n    alltotals = map(x -> x.totalcost, allkmeans)\n    _, cidx = findmin(alltotals)\n    x1, y1 = 1, alltotals[1]\n    x2, y2 = cmax + 1, alltotals[cmax + 1]\n    _, idx = findmax(map(i -> distance(x1, y1, x2, y2, i, alltotals[i]), 2:cmax))\n    nclust = cidx < idx + 1 ? max(cmin, cidx) : idx + 1\n    return nclust, allkmeans[nclust]\nend\n\n\n# internal helper functions\n\n\n\"\"\"\n    _makenumeric(a)\n\nReturns an array of counting number integers, `1 <= values <= length(a)`,\nwhere the returned array has its shape and sort order the same as `a`.\n\"\"\"\nfunction _makenumeric(a)\n    d = Dict{eltype(a), Int}()\n    for (i, s) in enumerate(sort(unique(a)))\n        d[s] = i\n    end\n    return map(x -> d[x], a)\nend\n\n\"\"\"\n    distance(x1, y1, x2, y2, x0, y0)\n\nReturn the Euclidean distance from point at `[x0, y0]` to line from `[x1, y1]` to `[x2, y2]`)\n\"\"\"\nfunction distance(x1, y1, x2, y2, x0, y0)\n    return abs((x2 - x1) * (y1 - y0) - (x1 - x0) * (y2 - y1)) / sqrt((x2 - x1)^2 + (y2 - y1)^2)\nend\n\n\"\"\" get one of 6 colors by an index \"\"\"\n_pcolor(i) = collect(palette(:lightrainbow))[mod1(i, 6)]\n\n\nend  # module Simpsons\n\n", "meta": {"hexsha": "b39152c5d1dcb6dd0d2df66b8bf7f489faec5da6", "size": 9901, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Simpsons.jl", "max_stars_repo_name": "wherrera10/Simpsons.jl", "max_stars_repo_head_hexsha": "047ae623b38057a65cf019f62f00b38e2227ea91", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-16T02:06:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-16T02:06:11.000Z", "max_issues_repo_path": "src/Simpsons.jl", "max_issues_repo_name": "wherrera10/Simpsons.jl", "max_issues_repo_head_hexsha": "047ae623b38057a65cf019f62f00b38e2227ea91", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Simpsons.jl", "max_forks_repo_name": "wherrera10/Simpsons.jl", "max_forks_repo_head_hexsha": "047ae623b38057a65cf019f62f00b38e2227ea91", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4267782427, "max_line_length": 121, "alphanum_fraction": 0.6591253409, "num_tokens": 2840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7689401045096461}}
{"text": "## Scalar functions on intervals (no directed rounding used)\n\nmag(a::Interval) = max( abs(a.lo), abs(a.hi) )\nmag(::EmptyInterval{T}) where T = T(NaN)\n\nfunction mig(a::Interval{T}) where T\n    zero_in(a) && return zero(T)\n    r1, r2 = (@round_down(abs(a.lo)), @round_down(abs(a.hi)))\n    min( r1, r2 )\nend\nmig(::EmptyInterval{T}) where T = T(NaN)\n\n# Infimum and supremum of an interval\ninf(a::Interval{T}) where T =\n    ifelse(iszero(a.lo), -zero(T), a.lo) # IEEE 1788-2015 requires negative sign\nsup(a::Interval{T}) where T =\n    ifelse(iszero(a.hi), zero(T), a.hi) # IEEE 1788-2015 requires positive sign\n\n# by convention, empty intervals return values which imply emptiness\ninf(a::EmptyInterval{T}) where T = T(Inf)\nsup(a::EmptyInterval{T}) where T = T(-Inf)\n\n# mid, diam, radius\n\n#= Fallback in case of overflow: a.hi + a.lo == +Inf or a.hi + a.lo == -Inf.\n    This case can not be the default one as it does not pass several\n    IEEE1788-2015 tests for small floats.\n=#\nmidpoint_bounded_safe(a::Interval) = 0.5a.lo + 0.5a.hi\nmidpoint_bounded_accurate(a::Interval{T}) where T = 0.5(a.lo + a.hi) |>\n    x -> ifelse(iszero(x), zero(T), x) # ensure positive sign for zero\n\n# NOTE: mid could be renamed to mean? or median?\n# Compare pg. 64 of the IEEE 1788-2015 standard:\n\"\"\"\n    mid(a::Interval)\n\nFind the midpoint of interval `a`.\n\nFor intervals of the form `[-Inf, x]` or `[x, +Inf]` where `x` is finite, return\nrespectively `nextfloat(-Inf)` and `prevfloat(+Inf)`. Note that it differs from the\nbehavior of `mid(a, α=0.5)`.\n\"\"\"\nfunction mid(a::Interval{T}) where T\n    isentire(a) && return zero(T)\n    a.lo == -Inf && return nextfloat(a.lo)\n    a.hi == +Inf && return prevfloat(a.hi)\n\n    accurate_midpoint = midpoint_bounded_accurate(a)\n    if isfinite(accurate_midpoint)\n        return accurate_midpoint\n    else\n        return midpoint_bounded_safe(a)\n    end\nend\n\nmid(::EmptyInterval{T}) where T = T(NaN)\n\n\"\"\"\n    diam(a::Interval)\n\nReturn the diameter (length) of the `Interval` `a`.\n\"\"\"\ndiam(a::Interval{T}) where T = @round_up(a.hi - a.lo) # cf page 64 of IEEE1788\ndiam(::EmptyInterval{T}) where T = T(NaN)\n\n# Should `radius` this yield diam(a)/2? This affects other functions!\n\"\"\"\n    radius(a::Interval)\n\nReturn the radius of the `Interval` `a`, such that\n`a ⊆ m ± radius`, where `m = mid(a)` is the midpoint.\n\"\"\"\nfunction radius(a::Interval{T}) where T\n    m = mid(a)\n    return max(m - a.lo, a.hi - m)\nend\nradius(::EmptyInterval{T}) where T = T(NaN)\n\n# midpoint-radius forms\nmidpoint_radius(a::ValidInterval) = (mid(a), radius(a))\n", "meta": {"hexsha": "98a95b23ff23169c18a3195060c5f4c4eaf3f263", "size": 2546, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operations/numeric.jl", "max_stars_repo_name": "gwater/IntervalArithmetic.jl", "max_stars_repo_head_hexsha": "0967cbbbaf455af5043bc197139dd0e4c2b40204", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/operations/numeric.jl", "max_issues_repo_name": "gwater/IntervalArithmetic.jl", "max_issues_repo_head_hexsha": "0967cbbbaf455af5043bc197139dd0e4c2b40204", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/operations/numeric.jl", "max_forks_repo_name": "gwater/IntervalArithmetic.jl", "max_forks_repo_head_hexsha": "0967cbbbaf455af5043bc197139dd0e4c2b40204", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0487804878, "max_line_length": 83, "alphanum_fraction": 0.6626080126, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7689400981566175}}
{"text": "using Parameters\n\n\"\"\"\nContains a distribution over a triangulated state space. `dist::Vector{Float64}`\nis the distribution, and `nonzero_inds::Vector{Int}` are the indices of the\nsimplices with non-zero measure.\n\"\"\"\n@with_kw struct InvDist\n    dist::Vector{Float64} = Vector{Float64}() # Distribution over the simplices\n    nonzero_inds::Vector{Int} = Vector{Int}() # indices of nonzero entries\nend\n\n\n\"\"\"\nCompute the invariant probability distribution from a square Markov matrix `M`.\nThis is done by repeated application of `M` on an initially random distribution\nuntil the distribution converges.\n\"\"\"\nfunction estimate_invdist(\n        M::AbstractArray{Float64, 2};\n        N::Int = 100,\n        tolerance::Float64 = 1/10^5,\n        delta::Float64 = 1/10^5\n        )\n\n    #=\n    # Start with a random distribution `Ρ` (big rho). Normalise it so that it\n    # sums to 1 and forms a true probability distribution over the simplices.\n    =#\n    Ρ = rand(Float64, 1, size(M, 1))\n    Ρ = Ρ ./ sum(Ρ, 2)\n\n    #=\n    # Start estimating the invariant distribution. We could either do this by\n    # finding the left-eigenvector of M, or by repeated application of M on Ρ\n    # until the distribution converges. Here, we use the latter approach,\n    # meaning that we iterate until Ρ doesn't change substantially between\n    # iterations.\n    =#\n    distribution = Ρ * M\n\n    distance = norm(distribution - Ρ) / norm(Ρ)\n\n    check = floor(Int, 1 / delta)\n    check_pts = floor.(Int, collect(1:N).' ./ check) .* collect(1:N).'\n    check_pts = check_pts[check_pts .> 0]\n    num_checkpts = size(check_pts, 1)\n    check_pts_counter = 1\n\n    counter = 1\n    while counter <= N && distance >= tolerance\n        counter += 1\n        Ρ = distribution\n\n        # Apply the Markov matrix to the current state of the distribution\n        distribution = Ρ * M\n\n        if (check_pts_counter <= num_checkpts &&\n           counter == check_pts[check_pts_counter])\n\n            check_pts_counter += 1\n            colsum_distribution = sum(distribution, 2)[1]\n            if abs(colsum_distribution - 1) > delta\n                distribution = distribution ./ colsum_distribution\n            end\n        end\n\n        distance = norm(distribution - Ρ) / norm(Ρ)\n    end\n\n    # Do the last normalisation and check\n    colsum_distribution = sum(distribution, 2)[1]\n\n    if abs(colsum_distribution - 1) > delta\n        distribution = distribution ./ colsum_distribution\n    end\n    # Find simplices with strictly positive measure.\n    simplex_inds_nonzero = heaviside(distribution) .* collect(1:size(M, 1)).'\n    simplex_inds_nonzero = round(Int, simplex_inds_nonzero)\n    simplex_inds_nonzero = simplex_inds_nonzero[simplex_inds_nonzero .> 0]\n\n    # Extract the elements of the invariant measure corresponding to these indices\n    return InvDist(dist = vec(distribution), nonzero_inds = simplex_inds_nonzero)\nend\n", "meta": {"hexsha": "3fd5c43683e0d1f727470fdc8f2b3f9897e106c3", "size": 2885, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/invdist.jl", "max_stars_repo_name": "JuliaTagBot/InvariantDistribution.jl", "max_stars_repo_head_hexsha": "885ba204685bf4fd439d8307259eb6a9ad33cb5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/invdist.jl", "max_issues_repo_name": "JuliaTagBot/InvariantDistribution.jl", "max_issues_repo_head_hexsha": "885ba204685bf4fd439d8307259eb6a9ad33cb5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/invdist.jl", "max_forks_repo_name": "JuliaTagBot/InvariantDistribution.jl", "max_forks_repo_head_hexsha": "885ba204685bf4fd439d8307259eb6a9ad33cb5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:03:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:03:00.000Z", "avg_line_length": 33.9411764706, "max_line_length": 82, "alphanum_fraction": 0.6720970537, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476385, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7689400973549838}}
{"text": "\"\"\"\nhorner(c,x)\n\nEvaluate a polynomial whose coefficients are given in ascending\norder in `c`, at the point `x`, using Horner's rule.\n\"\"\"\nfunction horner(c,x)\n\nn = length(c)\ny = c[n]\nfor k in n-1:-1:1\n    y = x*y + c[k]\nend\n\nreturn y\nend\n", "meta": {"hexsha": "37b2ee772405320e3004fb91b1678ba119184861", "size": 238, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter01.jl", "max_stars_repo_name": "tobydriscoll/fnc", "max_stars_repo_head_hexsha": "dde6097e6a9efff3c8cd7748c96214b4fcec2dc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2020-07-15T15:31:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T14:48:49.000Z", "max_issues_repo_path": "src/chapter01.jl", "max_issues_repo_name": "tobydriscoll/fnc", "max_issues_repo_head_hexsha": "dde6097e6a9efff3c8cd7748c96214b4fcec2dc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-07-20T15:42:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T19:08:43.000Z", "max_forks_repo_path": "src/chapter01.jl", "max_forks_repo_name": "tobydriscoll/fnc", "max_forks_repo_head_hexsha": "dde6097e6a9efff3c8cd7748c96214b4fcec2dc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-07-26T17:42:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T06:10:19.000Z", "avg_line_length": 14.0, "max_line_length": 63, "alphanum_fraction": 0.6428571429, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.768940096861468}}
{"text": "# m5.4.MAs.jl\n\nusing Pkg, DrWatson\n\nusing MonteCarloMeasurements\nusing StanSample\nusing StatisticalRethinking\n\n# ### snippet 5.1\n\ndf = CSV.read(sr_datadir(\"WaffleDivorce.csv\"), DataFrame);\n\ndf = DataFrame(\n    :A => df[:, :MedianAgeMarriage],\n    :M => df[:, :Marriage],\n    :D => df[:, :Divorce]\n )\n\nscale!(df, [:M, :A, :D])\n\n# Define the Stan language model\n\nstan5_4_MA = \"\ndata {\n    int N;\n    vector[N] A;\n    vector[N] M;\n}\nparameters {\n    real a;\n    real bMA;\n    real<lower=0> sigma;\n}\nmodel {\n    vector[N] mu = a + bMA * A;\n    a ~ normal( 0 , 0.2 );\n    bMA ~ normal( 0 , 0.5 );\n    sigma ~ exponential( 1 );\n    M ~ normal( mu , sigma );\n}\n\";\n\n# Define the SampleModel\nm5_4_MAs = SampleModel(\"m5.4\", stan5_4_MA);\n\n# Input data\n\nm5_4_data = Dict(\n    \"N\" => size(df, 1), \n    \"M\" => df[:, :M_s],\n    \"A\" => df[:, :A_s] \n);\n\n# Sample using cmdstan\n\nrc5_4_MAs = stan_sample(m5_4_MAs, data=m5_4_data);\n\nif success(rc5_4_MAs)\n\n    # Rethinking results\n\n    rethinking_results = \"\n           mean   sd  5.5% 94.5%\n    a      0.00 0.09 -0.14  0.14\n    bMA   -0.69 0.10 -0.85 -0.54\n    sigma  0.68 0.07  0.57  0.79\n    \";\n\n    part5_4_MAs = read_samples(m5_4_MAs, :particles)\n    part5_4_MAs |> display\n\nend\n\n# End of m5.4.MAs.jl", "meta": {"hexsha": "8581bbde118d88c972717563145a07a1f9c7d68f", "size": 1235, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/05/m5.4.MAs.jl", "max_stars_repo_name": "pitmonticone/StatisticalRethinkingStan.jl", "max_stars_repo_head_hexsha": "9eee333465b3b8ec5975645c1373b27cf26b5bb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2020-10-10T13:03:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T11:48:45.000Z", "max_issues_repo_path": "models/05/m5.4.MAs.jl", "max_issues_repo_name": "pitmonticone/StatisticalRethinkingStan.jl", "max_issues_repo_head_hexsha": "9eee333465b3b8ec5975645c1373b27cf26b5bb0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/05/m5.4.MAs.jl", "max_forks_repo_name": "pitmonticone/StatisticalRethinkingStan.jl", "max_forks_repo_head_hexsha": "9eee333465b3b8ec5975645c1373b27cf26b5bb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:30:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T00:10:15.000Z", "avg_line_length": 16.6891891892, "max_line_length": 58, "alphanum_fraction": 0.5765182186, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7689400945792864}}
{"text": "module KuboOscillator\n\n    export kubo_oscillator_sde_1, kubo_oscillator_psde_1, kubo_oscillator_spsde_1\n    export kubo_oscillator_sde_2, kubo_oscillator_psde_2, kubo_oscillator_spsde_2\n    export kubo_oscillator_sde_3, kubo_oscillator_psde_3, kubo_oscillator_spsde_3\n\n    using GeometricIntegrators.Equations\n\n    q_init_A=[0.5, 0.0]\n    q_init_B=[0.5 0.0 -0.5; 0.0 0.5 0.0]\n\n    noise_intensity = 0.1\n\n    Δt  = 0.01\n    nt  = 10\n\n\n    function kubo_oscillator_sde_v(t,q, v_out)\n        v_out[1]=  q[2]\n        v_out[2]= -q[1]\n    end\n\n\n    function kubo_oscillator_sde_B(t,q, B_out; col=0)\n        noise_intensity = 0.1\n\n        if col==0\n            B_out[1,1]=  noise_intensity*q[2]\n            B_out[2,1]= -noise_intensity*q[1]\n        elseif col==1\n            B_out[1]=  noise_intensity*q[2]\n            B_out[2]= -noise_intensity*q[1]\n        end\n    end\n\n\n    function kubo_oscillator_sde_1()\n        # q_init_A - single deterministic initial condition\n        # Generating 3 sample paths\n        # 1-dimensional noise\n        SDE(1, 3, kubo_oscillator_sde_v, kubo_oscillator_sde_B, q_init_A)\n    end\n\n\n    function kubo_oscillator_sde_2()\n        # q_init_B - interpreted as a single random initial condition\n        # The 3 columns correspond to 3 sample paths\n        # 1-dimensional noise\n        SDE(1, kubo_oscillator_sde_v, kubo_oscillator_sde_B, q_init_B)\n    end\n\n\n    function kubo_oscillator_sde_3()\n        # q_init_B - interpreted as multiple deterministic initial conditions\n        # The 3 columns correspond to 3 different deterministic initial conditions\n        # Generating 3 sample paths for each initial condition\n        # 1-dimensional noise\n        SDE(1, 3, kubo_oscillator_sde_v, kubo_oscillator_sde_B, q_init_B)\n    end\n\n\n    # PSDE\n\n    q_init_C=[0.5]\n    p_init_C=[0.0]\n\n    q_init_D=[0.5 0.0 -0.5]\n    p_init_D=[0.0 0.5 0.0]\n\n\n    function kubo_oscillator_psde_v(t, q, p, v_out)\n        v_out[1]=  p[1]\n    end\n\n    function kubo_oscillator_psde_f(t, q, p, f_out)\n        f_out[1]=  -q[1]\n    end\n\n    function kubo_oscillator_psde_B(t, q, p, B_out)\n        B_out[1,1]= noise_intensity*p[1]\n    end\n\n    function kubo_oscillator_psde_G(t, q, p, G_out)\n        G_out[1,1]= -noise_intensity*q[1]\n    end\n\n\n    function kubo_oscillator_psde_1()\n        # q_init_C - single deterministic initial condition\n        # Generating 3 sample paths\n        # 1-dimensional noise\n        PSDE(1, 3, kubo_oscillator_psde_v, kubo_oscillator_psde_f, kubo_oscillator_psde_B, kubo_oscillator_psde_G, q_init_C, p_init_C)\n    end\n\n\n    function kubo_oscillator_psde_2()\n        # q_init_D - interpreted as a single random initial condition\n        # The 3 columns correspond to 3 sample paths\n        # 1-dimensional noise\n        PSDE(1, kubo_oscillator_psde_v, kubo_oscillator_psde_f, kubo_oscillator_psde_B, kubo_oscillator_psde_G, q_init_D, p_init_D)\n    end\n\n\n    function kubo_oscillator_psde_3()\n        # q_init_D - interpreted as multiple deterministic initial conditions\n        # The 3 columns correspond to 3 different deterministic initial conditions\n        # Generating 3 sample paths for each initial condition\n        # 1-dimensional noise\n        PSDE(1, 3, kubo_oscillator_psde_v, kubo_oscillator_psde_f, kubo_oscillator_psde_B, kubo_oscillator_psde_G, q_init_D, p_init_D)\n    end\n\n\n    # SPSDE\n\n    function kubo_oscillator_spsde_v(t, q, p, v_out)\n        v_out[1]=  p[1]\n    end\n\n    function kubo_oscillator_spsde_f1(t, q, p, f_out)\n        f_out[1]=  -q[1]\n    end\n\n    function kubo_oscillator_spsde_f2(t, q, p, f_out)\n        f_out[1]=  0.0\n    end\n\n    function kubo_oscillator_spsde_B(t, q, p, B_out)\n        B_out[1,1]= noise_intensity*p[1]\n    end\n\n    function kubo_oscillator_spsde_G1(t, q, p, G_out)\n        G_out[1,1]= -noise_intensity*q[1]\n    end\n\n    function kubo_oscillator_spsde_G2(t, q, p, G_out)\n        G_out[1,1]= 0.0\n    end\n\n\n    function kubo_oscillator_spsde_1()\n        # q_init_C - single deterministic initial condition\n        # Generating 3 sample paths\n        # 1-dimensional noise\n        SPSDE(1, 3, kubo_oscillator_spsde_v, kubo_oscillator_spsde_f1, kubo_oscillator_spsde_f2, kubo_oscillator_spsde_B, kubo_oscillator_spsde_G1, kubo_oscillator_spsde_G2, q_init_C, p_init_C)\n    end\n\n\n    function kubo_oscillator_spsde_2()\n        # q_init_D - interpreted as a single random initial condition\n        # The 3 columns correspond to 3 sample paths\n        # 1-dimensional noise\n        SPSDE(1, kubo_oscillator_spsde_v, kubo_oscillator_spsde_f1, kubo_oscillator_spsde_f2, kubo_oscillator_spsde_B, kubo_oscillator_spsde_G1, kubo_oscillator_spsde_G2, q_init_D, p_init_D)\n    end\n\n\n    function kubo_oscillator_spsde_3()\n        # q_init_D - interpreted as multiple deterministic initial conditions\n        # The 3 columns correspond to 3 different deterministic initial conditions\n        # Generating 3 sample paths for each initial condition\n        # 1-dimensional noise\n        SPSDE(1, 3, kubo_oscillator_spsde_v, kubo_oscillator_spsde_f1, kubo_oscillator_spsde_f2, kubo_oscillator_spsde_B, kubo_oscillator_spsde_G1, kubo_oscillator_spsde_G2, q_init_D, p_init_D)\n    end\n\nend\n", "meta": {"hexsha": "993640aaeec93ff5857127fdbeb9a58ec16e8444", "size": 5155, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/kubo_oscillator.jl", "max_stars_repo_name": "krystophny/GeometricIntegrators.jl", "max_stars_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/kubo_oscillator.jl", "max_issues_repo_name": "krystophny/GeometricIntegrators.jl", "max_issues_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/kubo_oscillator.jl", "max_forks_repo_name": "krystophny/GeometricIntegrators.jl", "max_forks_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2424242424, "max_line_length": 193, "alphanum_fraction": 0.6923375364, "num_tokens": 1703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7689400927906208}}
{"text": "##\nusing Random\nusing Plots\nusing LinearAlgebra\ntheme(:dark)\n##\nRandom.seed!(7)\nX = randn(2,100)\nA = randn(2,2)\nY = A*X\nscatter(Y[1,:], Y[2,:], label=\"\", size=(300,300),color=3)\nxlabel!(\"x\")\nylabel!(\"y\")\n##\nsavefig(\"pca-2d-fig.pdf\")\n\n##\nusing Interact\nusing Statistics\nusing Printf\nsettheme!(:nativehtml)\nmp = @manipulate for θ in 0.0:2π/100:2π\n    v = [cos(θ),sin(θ)]\n    z = vec(v'*Y)\n    p = plot(\n      scatter(Y[1,:], Y[2,:], label=\"\",color=3, aspect_ratio=:equal),\n      histogram(z,label=\"\"),\n      size=(900,450),tickfont=16,titlefont=20\n      )\n    plot!(p[1],2*[0,v[1]],2*[0,v[2]],label=\"\",linewidth=2)\n    scatter!(p[1], v[1].*z, v[2].*z, color=2, label=\"\",\n      markerstrokewidth=0,alpha=0.3, markersize=4)\n    xlims!(p[2],(-5,5))\n    ylims!(p[2],(0,30))\n    xlims!(p[1],(-4,4))\n    ylims!(p[1],(-4.5,4.5))\n    title!(p[1],@sprintf(\"Angle = %.2f\", θ))\n    title!(p[2],@sprintf(\"Variance = %.2f\", var(z)))\nend\n## If the figure doesn't show, run\nusing Interact\nui = button()\ndisplay(ui)\n##\nθs = 0.0:π/1000:π\nplot(collect(θs), map(x -> var(vec([cos(x),sin(x)]'*Y)), θs),\n  label=\"\", size=(500,250))\nxlabel!(\"Angle\")\nylabel!(\"Variance\")\n##\nsavefig(\"pca-2d-angle-variance.pdf\")\n## PCA is a way to get this angle automatically!\nfunction mypca(X::AbstractMatrix, donormalize::Bool = false)\n  means = vec(mean(X, dims=2)) # take the average of each coordinate\n  C = X .- means # center each coordinate\n  if donormalize\n    for i=1:size(C,1)\n      normalize!(@view C[i,:])\n    end\n  end\n  U,S,V = svd(C)\nend\nU,S,V = mypca(Y, false)\nU[:,1]\n##\nθpca = atan(-U[2,1],-U[1,1])\n##\nplot(collect(θs), map(x -> var(vec([cos(x),sin(x)]'*Y)), θs),\nlabel=\"\", size=(500,250))\nxlabel!(\"Angle\")\nylabel!(\"Variance\")\nannotate!(θpca, var(vec([cos(θpca),sin(θpca)]'*Y)), text(\"*\", 24, :red))\n##\nsavefig(\"pca-2d-angle-variance-opt.pdf\")\n##\nscatter(Y[1,:], Y[2,:], label=\"\", size=(300,300),color=3)\nplot!(2*[0,-U[1,1]],2*[0,-U[2,1]],label=\"\",linewidth=2, color=5)\n##\nsavefig(\"pca-2d-fig-PCA.pdf\")\n##\nS\n## Save a set of points\npyplot()\ntheme(:default)\nscatter(Y[1,:], Y[2,:], label=\"\", size=(300,300),color=3,\n  framestyle=:none, background=:transparent)\nsavefig(\"pca-2d-data.pdf\")\n", "meta": {"hexsha": "b0ee9d8e9f8e6c1cc5d6e545c4d6648de8f21b0a", "size": 2163, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2-unit-1-demos/pca-2d.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "2-unit-1-demos/pca-2d.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2-unit-1-demos/pca-2d.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 24.5795454545, "max_line_length": 72, "alphanum_fraction": 0.5926953306, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7689400914954712}}
{"text": "function calc_pi(n::Integer)\n   x = rand(n)\n   y = rand(n)\n   num_in_unit_circle = sum(x.*x.+y.*y .< 1)\n   num_in_unit_circle * 4/n\nend\n\nn = 10_000;\ncalc_pi(1)  # Force compile\n@time pi_estimate = calc_pi(n)\nprintln(\"# After \", n, \" itterations, estimated pi to be...\")\nprintln(pi_estimate)\n", "meta": {"hexsha": "22519782e85e1e33111891791120f7292260eeb9", "size": 291, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ex1_serial.jl", "max_stars_repo_name": "PsuAstro528/lab7-start", "max_stars_repo_head_hexsha": "f0ed2b86d60fa018c0e283443b0612b26154e8b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-20T16:09:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-20T16:09:27.000Z", "max_issues_repo_path": "ex1_serial.jl", "max_issues_repo_name": "PsuAstro528/lab7-start", "max_issues_repo_head_hexsha": "f0ed2b86d60fa018c0e283443b0612b26154e8b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-28T17:11:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-28T18:30:15.000Z", "max_forks_repo_path": "ex1_serial.jl", "max_forks_repo_name": "PsuAstro528/lab7-start", "max_forks_repo_head_hexsha": "f0ed2b86d60fa018c0e283443b0612b26154e8b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-03-14T12:28:35.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-26T14:38:22.000Z", "avg_line_length": 22.3846153846, "max_line_length": 61, "alphanum_fraction": 0.6563573883, "num_tokens": 96, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.768940090508439}}
{"text": "# ------------------------------------------------------------------------------------------\n# ## What is learning?\n#\n# Computers read data, as we saw in notebooks 1 and 2. We can then build functions that\n# model that data to make decisions, as we saw in notebooks 3 and 5.\n#\n# But how do you make sure that the model actually fits the data well? In the last notebook,\n# we saw that we can fiddle with the parameters of our function defining the model to reduce\n# the loss function. However, we don't want to have to pick the model parameters ourselves.\n# Choosing parameters ourselves works *well enough* when we have a simple model and only a\n# few data points, but can quickly become extremely complex for more detailed models and\n# larger data sets.\n#\n# Instead, we want our machine to *learn* the parameters that fit the model to our data,\n# without needing us to fiddle with the parameters ourselves. In this notebook, we'll talk\n# about the \"learning\" in machine learning.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ### Motivation: Fitting parameters by hand\n#\n# Let's go back to our example of fitting parameters from notebook 3. Recall that we looked\n# at whether the amount of green in the pictures could distinguish between an apple and a\n# banana, and used a sigmoid function to model our choice of \"apple or banana\" using the\n# amount of green in an image.\n# ------------------------------------------------------------------------------------------\n\nusing Plots; gr()\nusing Images; using Interact\n\nσ(x,w,b) = 1 / (1 + exp(-w*x+b))\n\napple =  load(\"data/10_100.jpg\")\nbanana = load(\"data/104_100.jpg\")\napple_green_amount =  mean(Float64.(green.(apple)))\nbanana_green_amount = mean(Float64.(green.(banana)));\n\n@manipulate for w in -10:0.01:30, b in 0:0.1:30\n    \n    plot(x->σ(x,w,b), 0, 1, label=\"Model\", legend = :topleft, lw=3)\n    scatter!([apple_green_amount],  [0.0], label=\"Apple\")\n    scatter!([banana_green_amount], [1.0], label=\"Banana\")\n    \nend\n\n# ------------------------------------------------------------------------------------------\n# Intuitively, how did you tweak the sliders so that way the model sends apples to 0 and\n# bananas to 1? Most likely, you did the following:\n#\n# #### Move the sliders a bit, see whether the curve moves in the right direction, and if it\n# did, keep doing it.\n#\n# For a machine, \"learning\" is that same process, translated into math!\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## \"Learning by nudging\": The process of descent\n#\n# Let's start to formalize this idea. In order to push the curve in the \"right direction\",\n# we need some measurement of \"how right\" and \"how wrong\" the model is. When we translate\n# the idea of a \"right direction\" into math, we end up with a **loss function**, `L(w, b)`,\n# as we saw in notebook 5. We say that the loss function is lowest when the model `σ(x, w,\n# b)` performs the best.\n#\n# Now we want to create a loss function that is the lowest when the apple is at `0` and the\n# banana is at `1`. If the data (the amount of green) for our apple is $x_1$, then our model\n# will output $σ(x_1,w, b)$ for our apple. So, we want the difference $0 - σ(x_1, w, b)$ to\n# be small. Similarly, if our data for our banana (the banana's amount of green) is $x_2$,\n# we want the difference $1 - σ(x_2, w, b)$ to be small.\n#\n# To create our loss function, let's add together the squares of the difference of the\n# model's output from the desired output for the apple and the banana. We get\n#\n# $$ L(w,b) = (0 - σ(x_1, w, b))^2 + (1 - σ(x_2, w, b))^2. $$\n#\n# $L(w, b)$ is lowest when it outputs `0` for the apple and `1` for the banana, and thus the\n# cost is lowest when the model \"is correct\".\n#\n# We can visualize this function by plotting it in 3D with the `surface` function.\n# ------------------------------------------------------------------------------------------\n\n# plotly()\ngr()\n\nL(w, b) = (0 - σ(apple_green_amount,w,b))^2 + (1 - σ(banana_green_amount,w,b))^2\n\nw_range = 10:0.1:13\nb_range = 0:1:20\n\nL_values = [L(w,b) for b in b_range, w in w_range]\n\n\n@manipulate for w in w_range, b in b_range\n    p1 = surface(w_range, b_range, L_values, xlabel=\"w\", ylabel=\"b\", cam=(70,40), cbar=false, leg=false)\n    scatter!(p1, [w], [b], [L(w,b)+1e-2], markersize=5, color = :blue)\n    p2 = plot(x->σ(x,w,b), 0, 1, label=\"Model\", legend = :topleft, lw=3)\n    scatter!(p2, [apple_green_amount],  [0.0], label=\"Apple\", markersize=10)\n    scatter!(p2, [banana_green_amount], [1.0], label=\"Banana\", markersize=10, xlim=(0,1), ylim=(0,1))\n    plot(p1, p2, layout=(2,1))\nend\n\n# ------------------------------------------------------------------------------------------\n# The blue ball on the 3D plot shows the current parameter choices, plotted as `(w,b)`.\n# Shown below the 3D plot is a 2D plot of the corresponding model with those parameters.\n# Notice that as the blue ball rolls down the hill, the model becomes a better fit. Our loss\n# function gives us a mathematical notion of a \"hill\", and the process of \"learning by\n# nudging\" is simply rolling the ball down that hill.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# To do this mathematically, we need to know which direction is \"downhill\". Recall from\n# calculus that the derivative of `L` with respect to `b` tells you how `L` changes when `b`\n# changes. Thus to roll downhill, we should go in the direction where the derivative is\n# negative (the function goes down) for each parameter. This direction is the negative of\n# what's called the **gradient**, $\\nabla L$. This means that the \"learn by nudging method\"\n# can be rephrased in mathematical terms as:\n#\n# 1. Calculate the gradient\n# 2. Move a little bit in the direction of the negative gradient\n# 3. Repeat\n#\n# This process of rolling the ball in the direction of the negative gradient is called\n# **gradient descent**; written mathematically, it is\n#\n# $$p_{n+1} = p_n - \\eta \\nabla L(p_n).$$\n#\n# Here, $p_n$ represents the vector of current parameters $(w, b)$; $\\nabla L(p_n)$ is the\n# gradient of the loss function, given those parameters. We start from $p_n$ and change it\n# by $\\eta \\nabla L(p_n)$, where $\\eta$ is a small step size that determines how far we move\n# the parameters in the direction of the negative gradient; notice that if you step too far,\n# you'll overshoot the minimum!. The result is $p_{n+1}$, the new vector of parameters.\n#\n# [Picture of Gradient Descent Vectors]\n#\n# If we repeat this process, then we will end up at parameters where the model correctly\n# labels apples as `0` and bananas as `1`. When this happens, the model has learned from the\n# data and can then read pictures and tell you whether they are apples or bananas!\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 1\n#\n# Use the following terms to fill in the sentences below. Terms may be used more than once\n# or not at all:\n# > gradient, loss function, derivative, gradient descent, learning.\n#\n# * We can think of a _(A)_ as a 1D version of a _(B)_.\n# * We can visualize a _(C)_ as a hill.\n# * In the explanation above, rolling downhill is called _(D)_ and means traveling along the\n# _(E)_.\n# * To quantify the correctness of a model we use a _(F)_.\n# * When our program can minimize a _(G)_ on its own, we say it is _(H)_.\n#\n# <br><br>\n#\n# A)<br>\n# B)<br>\n# C)<br>\n# D)<br>\n# E)<br>\n# F)<br>\n# G)<br>\n# H)<br>\n# ------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "3b39b7fb88b5b0e3efa52d39b74145ed630b6b56", "size": 7989, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/09. ML - What is learning.jl", "max_stars_repo_name": "grenkoca/JuliaTutorials", "max_stars_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 535, "max_stars_repo_stars_event_min_datetime": "2020-07-15T14:56:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T12:50:32.000Z", "max_issues_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/09. ML - What is learning.jl", "max_issues_repo_name": "grenkoca/JuliaTutorials", "max_issues_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2018-02-25T22:53:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-14T02:15:50.000Z", "max_forks_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/09. ML - What is learning.jl", "max_forks_repo_name": "grenkoca/JuliaTutorials", "max_forks_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 394, "max_forks_repo_forks_event_min_datetime": "2020-07-14T23:22:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:12:57.000Z", "avg_line_length": 48.4181818182, "max_line_length": 104, "alphanum_fraction": 0.5876830642, "num_tokens": 1961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7689268798109463}}
{"text": "# squared Euclidean distance from a set\n\nimmutable SqrDistL2{R <: Real} <: ProximableFunction\n  ind::IndicatorConvex\n  lambda::R\n  function SqrDistL2(ind::IndicatorConvex, lambda::R)\n    if lambda < 0\n      error(\"parameter λ must be nonnegative\")\n    else\n      new(ind, lambda)\n    end\n  end\nend\n\nSqrDistL2{R <: Real}(ind::IndicatorConvex, lambda::R=1.0) = SqrDistL2{R}(ind, lambda)\n\nfunction (f::SqrDistL2){T <: RealOrComplex}(x::AbstractArray{T})\n  p, = prox(f.ind, x)\n  return (f.lambda/2)*vecnorm(x-p)^2\nend\n\nfunction prox!{T <: RealOrComplex}(f::SqrDistL2, x::AbstractArray{T}, y::AbstractArray{T}, gamma::Real=1.0)\n  p, = prox(f.ind, x)\n  sqrd = (f.lambda/2)*vecnorm(x-p)^2\n  c1 = 1/(1+f.lambda*gamma)\n  c2 = f.lambda*gamma*c1\n  for k in eachindex(p)\n    y[k] = c1*x[k] + c2*p[k]\n  end\n  return sqrd*c1^2\nend\n\nfun_name(f::SqrDistL2) = \"squared Euclidean distance from a convex set\"\nfun_dom(f::SqrDistL2) = fun_dom(f.ind)\nfun_expr(f::SqrDistL2) = \"x ↦ (λ/2) inf { ||x-y||^2 : y ∈ S} \"\nfun_params(f::SqrDistL2) = string(\"λ = $(f.lambda), S = \", typeof(f.ind))\n\nfunction prox_naive{T <: RealOrComplex}(f::SqrDistL2, x::AbstractArray{T}, gamma::Real=1.0)\n  p, = prox(f.ind, x)\n  sqrd = (f.lambda/2)*vecnorm(x-p)^2\n  gamlam = f.lambda*gamma\n  return 1/(1+gamlam)*x + gamlam/(1+gamlam)*p, sqrd/(1+gamlam)^2\nend\n", "meta": {"hexsha": "0488d96befb39a5a7d6b8b3cee18e2879202248f", "size": 1313, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/sqrDistL2.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/sqrDistL2.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/sqrDistL2.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8409090909, "max_line_length": 107, "alphanum_fraction": 0.6519421173, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7689268796659854}}
{"text": "export rotate\r\n\r\nfunction rotate(x::Array{Float64,2}; angle=0.0, point=[0.0, 0.0, 0.0], vector_=[1.0, 0.0, 0.0])\r\n    t = angle/180*pi\r\n    x = x .- vec(point)\r\n    vector_ = vec(vector_)\r\n    unit_vector = vector_/(sqrt(sum(vector_.^2)))\r\n    l, m, n = unit_vector\r\n    c, s = cos(t), sin(t)\r\n    rot = [l*l*(1-c)+c     m*l*(1-c)-n*s   n*l*(1-c)+m*s;\r\n           l*m*(1-c)+n*s   m*m*(1-c)+c     n*m*(1-c)-l*s;\r\n           l*n*(1-c)-m*s   m*n*(1-c)+l*s   n*n*(1-c)+c;]\r\n    x = rot * x\r\n    x = x .+ vec(point)\r\n    return x\r\nend\r\n\r\nfunction rotate(obj::T; angle=0.0, point=[0.0, 0.0, 0.0], vector_=[1.0, 0.0, 0.0]) where T <: Union{Shape, PostOpObj}\r\n    # x, v, y, vol, type\r\n    function func(out)\r\n        x = out[:x]\r\n        x = rotate(x; angle=angle, point=point, vector_=vector_)\r\n        return repack!(out, [:x], [x])\r\n    end\r\n    if isa(obj, Shape)\r\n        return PostOpObj(obj, func)\r\n    elseif isa(obj, PostOpObj)\r\n        push!(obj.operations, func)       \r\n        return obj         \r\n    else\r\n        error(\"Not allowed.\")\r\n    end\r\nend", "meta": {"hexsha": "e994f5d9e3710bec621202e8e897dada39d2b9f3", "size": 1057, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operations/rotate.jl", "max_stars_repo_name": "sajidmannan/PDMesh", "max_stars_repo_head_hexsha": "dc0734b80971773dea47fba820b5bfb5b5672c6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/operations/rotate.jl", "max_issues_repo_name": "sajidmannan/PDMesh", "max_issues_repo_head_hexsha": "dc0734b80971773dea47fba820b5bfb5b5672c6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/operations/rotate.jl", "max_forks_repo_name": "sajidmannan/PDMesh", "max_forks_repo_head_hexsha": "dc0734b80971773dea47fba820b5bfb5b5672c6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0303030303, "max_line_length": 118, "alphanum_fraction": 0.4938505203, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778000158576, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7688604425518983}}
{"text": "function main()\n\tN = 4_000_000\n\ts = 0\n\ti1 = 1\n\ti2 = 1\n\twhile true\n\t\tfib = i1 + i2\n\t\ti1 = i2\n\t\ti2 = fib\n\t\tif fib > N\n\t\t\tbreak\n\t\tend\n\t\tif fib % 2 == 0\n\t\t\ts += fib\n\t\tend\t\n\tend\n\tprintln(s)\nend\n\nmain()", "meta": {"hexsha": "cad93dab0ae560e8ddb26d702b13e1cb60286ddf", "size": 196, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problem2.jl", "max_stars_repo_name": "cmey/euler", "max_stars_repo_head_hexsha": "b61faa9f421992e1c859f354e67125e681156584", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problem2.jl", "max_issues_repo_name": "cmey/euler", "max_issues_repo_head_hexsha": "b61faa9f421992e1c859f354e67125e681156584", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem2.jl", "max_forks_repo_name": "cmey/euler", "max_forks_repo_head_hexsha": "b61faa9f421992e1c859f354e67125e681156584", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 9.8, "max_line_length": 17, "alphanum_fraction": 0.5153061224, "num_tokens": 94, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9572777987970316, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7688604415729692}}
{"text": "using Distributions\n\nxObs     = [18 132; 45 178]\nrowSums  = [sum(xObs[i,:]) for i in 1:2]\ncolSums  = [sum(xObs[:,i]) for i in 1:2]\nn        = sum(xObs)\n\nrowProps = rowSums/n\ncolProps = colSums/n\n\nxExpect  = [colProps[c]*rowProps[r]*n for r in 1:2, c in 1:2]\ntestStat = sum([(xObs[r,c]-xExpect[r,c])^2 / xExpect[r,c] for r in 1:2,c in 1:2])\npVal = ccdf(Chisq(1),testStat)\n\nprintln(\"Chi-squared value: \", testStat)\nprintln(\"P-value: \", pVal)", "meta": {"hexsha": "3831bf85b9fb95bfaff0283826656ee94d8ce371", "size": 439, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "7_chapter/chiSqIndependence.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "7_chapter/chiSqIndependence.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "7_chapter/chiSqIndependence.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 27.4375, "max_line_length": 81, "alphanum_fraction": 0.6264236902, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9632305307578324, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7688378758781079}}
{"text": "\"\"\"\n\n```\nsphereradiusfromshellvolume(volume,step)\n```\n\nComputes the radius that corresponds to a spherical shell of\na given volume.\n\n\"\"\"\nfunction sphereradiusfromshellvolume(volume, step)\n\n    fourthirdsofpi = 4 * pi / 3\n    if 3 * step * volume - pi * step^4 <= 0.0\n        return 0.0\n    end\n    rmin =\n        (sqrt(3 * pi) * sqrt(3 * step * volume - pi * step^4) - 3 * pi * step^2) /\n        (6 * pi * step)\n    return (0.5 * (volume / fourthirdsofpi + 2 * rmin^3))^(1 / 3)\n\nend\n", "meta": {"hexsha": "ffab5a24f96116b252e11a8d007be75a60322ba6", "size": 483, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sphereradiusfromshellvolume.jl", "max_stars_repo_name": "m3g/MDDF", "max_stars_repo_head_hexsha": "efbc8e0dcf426c9b2246217eb9edaf4605318e84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-04T21:33:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-04T21:33:56.000Z", "max_issues_repo_path": "src/sphereradiusfromshellvolume.jl", "max_issues_repo_name": "m3g/MDDF", "max_issues_repo_head_hexsha": "efbc8e0dcf426c9b2246217eb9edaf4605318e84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-31T00:18:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-23T20:04:16.000Z", "max_forks_repo_path": "src/sphereradiusfromshellvolume.jl", "max_forks_repo_name": "m3g/ComplexMixtures", "max_forks_repo_head_hexsha": "efbc8e0dcf426c9b2246217eb9edaf4605318e84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0, "max_line_length": 82, "alphanum_fraction": 0.5859213251, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305360354471, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.768837873154364}}
{"text": "abstract type AbstractUtility end\n\n# Euler equation deviation. Generic!\nfunction euler_dev(\n    u :: AbstractUtility, \n    cV :: AbstractVector{Float64}, \n    betaR :: Float64\n    )\n    muV = marg_utility(u, cV);\n    T = length(cV);\n    devV = muV[1 : (T-1)] ./ muV[2 : T] .- betaR;\n    return devV\nend\n\n\n## ----------  Log\n\nstruct UtilityLog <: AbstractUtility end\n\n# Note the broadcasting dot. This now works for scalars and arrays.\nutility(u :: UtilityLog, c) = log.(c);\nmarg_utility(u :: UtilityLog, c) = 1.0 ./ c;\ninv_utility(u :: UtilityLog, util) = exp.(util);\ninv_marg_utility(u :: UtilityLog, mu) = 1.0 ./ mu;\nc_growth(u :: UtilityLog, betaR) = betaR;\n\n\n## -----------  CRRA\n\nstruct UtilityCRRA <: AbstractUtility \n    sigma :: Float64\nend\n\nutility(u :: UtilityCRRA, c) = (c .^ (1.0 - u.sigma)) ./ (1.0 - u.sigma) .- 1.0;\nmarg_utility(u :: UtilityCRRA, c) = c .^ (-u.sigma);\ninv_utility(u :: UtilityCRRA, util) = ((util .+ 1.0) .* (1.0 - u.sigma)) .^ (1.0 / (1.0 - u.sigma));\ninv_marg_utility(u :: UtilityCRRA, mu) = mu .^ (-1.0 / u.sigma);\nc_growth(u :: UtilityCRRA, betaR) = betaR .^ (1.0 / u.sigma);\n\n\n# -------------", "meta": {"hexsha": "f9def4fdb3b42d2c9d17f28e994fd4b78f6bae04", "size": 1129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utility.jl", "max_stars_repo_name": "hendri54/Econ890", "max_stars_repo_head_hexsha": "07d2c2fa91d6359a8be8ad33374b785f64457435", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-31T09:00:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T09:00:46.000Z", "max_issues_repo_path": "src/utility.jl", "max_issues_repo_name": "hendri54/Econ890", "max_issues_repo_head_hexsha": "07d2c2fa91d6359a8be8ad33374b785f64457435", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utility.jl", "max_forks_repo_name": "hendri54/Econ890", "max_forks_repo_head_hexsha": "07d2c2fa91d6359a8be8ad33374b785f64457435", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5365853659, "max_line_length": 100, "alphanum_fraction": 0.5961027458, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.7688109477876559}}
{"text": "# This file includes the MonteCarlo simulation of ASK modulation scheme and compares \n# the numerical results with the theoretical results. \n\nusing DigitalCommunications \nusing Plots \n\n# Simulation parameters \ntheme(:default)\nplt = plot(legend=:bottomleft) \nfor k in 1 : 3\n    M = 2^k \n    nsymbols = Int(1e6) \n    nbits = k * nsymbols\n    ebno = collect(0 : 10)    \n    esno = ebno .+ 10 * log10(k)\n\n    # Communcation system components  \n    gen = SymbolGenerator(nsymbols, M) \n    modulator = Modulator(ASK(M))\n    channel = AWGNChannel() \n    detector = Detector(modulator(1:M))\n\n    # Monte Carlo simulation \n    message = gen.symbols\n    symerr = zeros(length(esno))\n    for i in 1 : length(symerr)\n        channel.esno = esno[i]  # Update channel snr\n        mbar = message |> modulator |> channel |> detector  # Extracted message signal \n        symerr[i] = sum(mbar .!= message) / length(message)  # Symbol error rate \n    end\n\n    plot!(ebno, berask.(ebno, M), yscale=:log10, lw=0.5, \n        markershape=:auto, color=:black, gridalpha=0.9, minorgrid=true, minorgridalpha=0.5, label=\"$M-ASK-theoretical\")\n    plot!(ebno, symerr,  yscale=:log10, lw=0.5, \n        markershape=:auto, color=:black, gridalpha=0.9, minorgrid=true, minorgridalpha=0.5, label=\"$M-ASK-montecarlo\")\nend\ndisplay(plt) ", "meta": {"hexsha": "55e3726edbdbd5fca64e97a258503f0d093d6f38", "size": 1300, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/vector_simulations/montecarloask.jl", "max_stars_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_stars_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-03T20:02:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T06:43:38.000Z", "max_issues_repo_path": "example/vector_simulations/montecarloask.jl", "max_issues_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_issues_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-11-26T21:56:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-03T19:54:59.000Z", "max_forks_repo_path": "example/vector_simulations/montecarloask.jl", "max_forks_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_forks_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-20T12:53:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T12:53:43.000Z", "avg_line_length": 35.1351351351, "max_line_length": 119, "alphanum_fraction": 0.6615384615, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7688109447418267}}
{"text": "using ITensors,\n      LinearAlgebra,\n      QuadGK\n\nβc() = 0.5*log(sqrt(2.0)+1.0)\n\nfunction ising_free_energy(β::Real,J::Real=1.0)\n  k = β*J\n  c = cosh(2.0*k)\n  s = sinh(2.0*k)\n  xmin = 0.0\n  xmax = π\n  integrand(x) = log(c^2+sqrt(s^4+1-2*s^2*cos(x)))\n  integral,err = quadgk(integrand, xmin, xmax)::Tuple{Float64,Float64}\n  return -(log(2.0)+integral/π)/(2.0*β)\nend\n\nfunction ising_magnetization(β::Real)\n β>βc && return (1.0-sinh(2.0*β)^(-4))^(1/8)\n return 0.0\nend\n\nfunction ising_mpo(sh::Tuple{Index,Index},sv::Tuple{Index,Index},\n                   β::Real,J::Real=1.0;\n                   sz::Bool=false)\n  d = dim(sh[1])\n  T = ITensor(sh[1],sh[2],sv[1],sv[2])\n    for i = 1:d\n      T[i,i,i,i] = 1.0\n    end\n    sz && (T[1,1,1,1] = -T[1,1,1,1])\n    Q = [exp(β*J) exp(-β*J); exp(-β*J) exp(β*J)]\n    D,U = eigen(Symmetric(Q))\n    sqrtQ = U*Diagonal(sqrt.(D))*U'\n    Xh1 = ITensor(vec(sqrtQ),sh[1],sh[1]')\n    Xh2 = ITensor(vec(sqrtQ),sh[2],sh[2]')\n    Xv1 = ITensor(vec(sqrtQ),sv[1],sv[1]')\n    Xv2 = ITensor(vec(sqrtQ),sv[2],sv[2]')\n    T = replacetags(T*Xh1*Xh2*Xv1*Xv2,\"1\",\"0\")\n  return T\nend\n\nfunction ising_partition(sh,sv,β)\n  ny,nx = size(sh)\n  T = Matrix{ITensor}(undef,ny,nx)\n  for iy = 1:ny, ix = 1:nx\n    ixp = per(ix+1,nx)\n    iyp = per(iy+1,ny)\n    T[iy,ix] = ising_mpo((sh[iy,ix],sh[iy,ixp]),(sv[iy,ix],sv[iyp,ix]),β)\n  end\n  return T\nend\n\n", "meta": {"hexsha": "d55c5552908c5fab02072dc71396b97985f13229", "size": 1355, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ctmrg/2d_classical_ising.jl", "max_stars_repo_name": "MichaelSven/ITensors.jl", "max_stars_repo_head_hexsha": "48dc7b7f302fb718e4721f51ea11595ad51d3dec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-10T06:23:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T06:23:09.000Z", "max_issues_repo_path": "examples/ctmrg/2d_classical_ising.jl", "max_issues_repo_name": "MichaelSven/ITensors.jl", "max_issues_repo_head_hexsha": "48dc7b7f302fb718e4721f51ea11595ad51d3dec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ctmrg/2d_classical_ising.jl", "max_forks_repo_name": "MichaelSven/ITensors.jl", "max_forks_repo_head_hexsha": "48dc7b7f302fb718e4721f51ea11595ad51d3dec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-28T11:47:51.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-28T11:47:51.000Z", "avg_line_length": 25.0925925926, "max_line_length": 73, "alphanum_fraction": 0.5579335793, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7688109343625178}}
{"text": "# Load Julia packages (libraries) needed\n\nusing StatisticalRethinking, CmdStan\n#gr(size=(600,600));\n\n# CmdStan uses a tmp directory to store the output of cmdstan\n\nProjDir = rel_path(\"..\", \"scripts\", \"02\")\ncd(ProjDir)\n\n# Define the Stan language model\n\nbinomialstanmodel = \"\n// Inferring a Rate\ndata {\n  int N;\n  int<lower=0> k[N];\n  int<lower=1> n[N];\n}\nparameters {\n  real<lower=0,upper=1> theta;\n  real<lower=0,upper=1> thetaprior;\n}\nmodel {\n  // Prior Distribution for Rate Theta\n  theta ~ beta(1, 1);\n  thetaprior ~ beta(1, 1);\n\n  // Observed Counts\n  k ~ binomial(n, theta);\n}\n\";\n\n# Define the Stanmodel and set the output format to :mcmcchains.\n\nstanmodel = Stanmodel(name=\"binomial\", monitors = [\"theta\"], model=binomialstanmodel,\n  output_format=:mcmcchains);\n\n# Use 16 observations\n\nN2 = 15\nd = Binomial(9, 0.66)\nn2 = Int.(9 * ones(Int, N2));\n\n# Show first 5 (generated) observations\n\nk2 = rand(d, N2);\nk2[1:min(5, N2)]\n\n# Input data for cmdstan\n\nbinomialdata = Dict(\"N\" => length(n2), \"n\" => n2, \"k\" => k2);\n\n# Sample using cmdstan\n \nrc, chn, cnames = stan(stanmodel, binomialdata, ProjDir, diagnostics=false,\n  CmdStanDir=CMDSTAN_HOME);\n\n# Describe the draws\n\nMCMCChains.describe(chn)\n\n# Allocate array of Normal fits\n\nfits = Vector{Normal{Float64}}(undef, 4)\nfor i in 1:4\n  fits[i] = fit_mle(Normal, convert.(Float64, chn.value[:, 1, i]))\n  println(fits[i])\nend\n\n# Plot the 4 chains\n\nmu_avg = sum([fits[i].μ for i in 1:4]) / 4.0;\nsigma_avg = sum([fits[i].σ for i in 1:4]) / 4.0;\n\nif rc == 0\n  p = Vector{Plots.Plot{Plots.GRBackend}}(undef, 4)\n  x = 0:0.001:1\n  for i in 1:4\n    vals = convert.(Float64, chn.value[:, 1, i])\n    μ = round(fits[i].μ, digits=2)\n    σ = round(fits[i].σ, digits=2)\n    p[i] = density(vals, lab=\"Chain $i density\",\n       xlim=(0.45, 1.0), title=\"$(N2) data points\")\n    plot!(p[i], x, pdf.(Normal(fits[i].μ, fits[i].σ), x), lab=\"Fitted Normal($μ, $σ)\")\n  end\n  plot(p..., layout=(4, 1))\n  #savefig(\"m2.1s.pdf\")\nend\n\n# Show the hpd region\n\nhpd(chn, alpha=0.055)\n\n# Compute the hpd bounds for plotting\n\nd, p, c = size(chn);\ntheta = convert(Vector{Float64}, reshape(chn.value, (d*p*c)));\nbnds = quantile(theta, [0.045, 0.945])\n\n# Show hpd region\n\nprintln(\"hpd bounds = $bnds\\n\")\n\n# quadratic approximation\n\n# Compute MAP, compare with CmndStan & MLE\n\ntmp = convert(Array{Float64,3}, chn.value)\ndraws = reshape(tmp, (size(tmp, 1)*size(tmp, 3)),)\n\n# Compute MAP\n\nusing Optim\n\nx0 = [0.5]\nlower = [0.2]\nupper = [1.0]\n\ninner_optimizer = GradientDescent()\n\nfunction loglik(x)\n  ll = 0.0\n  ll += log.(pdf.(Beta(1, 1), x[1]))\n  ll += sum(log.(pdf.(Binomial(9, x[1]), k2)))\n  -ll\nend\n\nres = optimize(loglik, lower, upper, x0, Fminbox(inner_optimizer))\n\n# Summarize mean and sd estimates\n\n# CmdStan mean and sd:\n\n[mean(chn.value), std(chn.value)]\n\n# MAP estimate and associated sd:\n\n[Optim.minimizer(res)[1], std(draws, mean=mean(chn.value))]\n\n# MLE of mean and sd:\n\n[mu_avg, sigma_avg]\n\n# Turing Chain &  89% hpd region boundaries\n\nplot( x, pdf.(Normal( mu_avg , sigma_avg  ) , x ),\nxlim=(0.0, 1.2), lab=\"Normal approximation using MLE\")\nplot!( x, pdf.(Normal( Optim.minimizer(res)[1] , std(draws, mean=mean(chn.value))) , x),\nlab=\"Normal approximation using MAP\")\ndensity!(draws, lab=\"CmdStan chain\")\nvline!([bnds[1]], line=:dash, lab=\"hpd lower bound\")\nvline!([bnds[2]], line=:dash, lab=\"hpd upper bound\")\n\n# End of `02/clip_08s.jl`\n", "meta": {"hexsha": "920be5037502094d3eb2468b027913721880bb43", "size": 3364, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/02/m2.1s.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_stars_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/02/m2.1s.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_issues_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/02/m2.1s.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_forks_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5641025641, "max_line_length": 88, "alphanum_fraction": 0.6516052319, "num_tokens": 1167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7687758340488966}}
{"text": "f = open(\"input07.txt\", \"r\")\n    l = readlines(f)\nclose(f)\n\npositions = [parse(Int, n) for n in split(l[1], \",\")]\n\noptions = collect(minimum(positions):maximum(positions))\nconsumption = zeros(length(options))\nfor (i, k) in enumerate(options)\n    diff = positions - ones(length(positions)) * k\n    fuel = sum([abs(j) for j in diff])\n    consumption[i] = fuel\nend\n\nbest_fuel = minimum(consumption)\nprintln(\"Result 1: $best_fuel\")\n\n\nconsumption = zeros(length(options))\nfor (i, k) in enumerate(options)\n    diff = positions - ones(length(positions)) * k\n    eachfuel = [sum(collect(1:abs(j))) for j in diff]\n    fuel = sum([abs(j) for j in eachfuel])\n    consumption[i] = fuel\nend\n\nnew_best_fuel = minimum(consumption)\nprintln(\"Result 2: $new_best_fuel\")\n", "meta": {"hexsha": "b2cc3f861856b61a306ae091c182f377cfb2f1ff", "size": 752, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "year2021/day07/challenge07.jl", "max_stars_repo_name": "jung-benjamin/advent-of-code", "max_stars_repo_head_hexsha": "0c5236db2abc4aff8ad56043291d20a5b495321a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "year2021/day07/challenge07.jl", "max_issues_repo_name": "jung-benjamin/advent-of-code", "max_issues_repo_head_hexsha": "0c5236db2abc4aff8ad56043291d20a5b495321a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "year2021/day07/challenge07.jl", "max_forks_repo_name": "jung-benjamin/advent-of-code", "max_forks_repo_head_hexsha": "0c5236db2abc4aff8ad56043291d20a5b495321a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9310344828, "max_line_length": 56, "alphanum_fraction": 0.6715425532, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8244619328462579, "lm_q1q2_score": 0.7687722573119101}}
{"text": "cd(@__DIR__)\nusing Revise, DifferentialEvolutionMCMC, Random, Distributions\nusing LinearAlgebra\nRandom.seed!(50514)\n\n# number of variables \nn_μ = 30\n# number of observations per variable \nn_d = 100\n# random μ parameters\nμs = rand(Normal(0.0, 1.0), n_μ)\n# data\ndata = rand(MvNormal(μs, 1.0 * I), n_d)\n\n# function for initial values\nfunction sample_prior()\n    μ = rand(Normal(0, 1), n_μ)\n    σ = rand(truncated(Cauchy(0, 1), 0, Inf))\n    return as_union([μ,σ])\nend\n\n# returns prior log likelihood\nfunction prior_loglike(μ, σ)\n    LL = 0.0\n    LL += sum(logpdf.(Normal(0, 1), μ))\n    LL += logpdf(truncated(Cauchy(0, 1), 0, Inf), σ)\n    return LL\nend\n\n# likelihood function \nfunction loglike(data, μs, σ)\n    return sum(logpdf(MvNormal(μs, σ^2 * I), data))\nend\n\n# upper and lower bounds of parameters\nbounds = ((-Inf,Inf),(0.0,Inf))\n# parameter names \nnames = (:μ,:σ)\n\n# model object\nmodel = DEModel(; \n    sample_prior, \n    prior_loglike, \n    loglike, \n    data,\n    names\n)\n\n# DEMCMC sampler \nde = DE(;\n    sample_prior,\n    bounds, \n    sample = resample,\n    burnin = 5000, \n    n_initial = (n_μ + 1) * 4,\n    Np = 3,\n    n_groups = 1,\n    θsnooker = 0.1,\n)\n# sample from the posterior distribution \nn_iter = 50_000\nchains = sample(model, de, MCMCThreads(), n_iter, progress=true)", "meta": {"hexsha": "497a29e68a17f617e133d6af19444bdf88448476", "size": 1284, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/Multivariate_Guassian_Example.jl", "max_stars_repo_name": "itsdfish/DifferentialEvolutionMCMC.jl", "max_stars_repo_head_hexsha": "3974509006e3df0eef74cf82be71586f2045d421", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-06-22T07:03:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T06:47:34.000Z", "max_issues_repo_path": "Examples/Multivariate_Guassian_Example.jl", "max_issues_repo_name": "itsdfish/DifferentialEvolutionMCMC.jl", "max_issues_repo_head_hexsha": "3974509006e3df0eef74cf82be71586f2045d421", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 40, "max_issues_repo_issues_event_min_datetime": "2020-05-28T11:51:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T11:59:22.000Z", "max_forks_repo_path": "Examples/Multivariate_Guassian_Example.jl", "max_forks_repo_name": "itsdfish/DifferentialEvolutionMCMC.jl", "max_forks_repo_head_hexsha": "3974509006e3df0eef74cf82be71586f2045d421", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7096774194, "max_line_length": 64, "alphanum_fraction": 0.6503115265, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7687722563852738}}
{"text": "using CSV, GLM, Plots; pyplot() \n\ndf = CSV.read(\"../data/IQalc.csv\")\ngroupA = df[df.Group .== \"A\", :]\ngroupB = df[df.Group .== \"B\", :]\ngroupC = df[df.Group .== \"C\", :]\n\nmodel  = fit(LinearModel, @formula(AlcConsumption ~ IQ), df)\nmodelA = fit(LinearModel, @formula(AlcConsumption ~ IQ), groupA)\nmodelB = fit(LinearModel, @formula(AlcConsumption ~ IQ), groupB)\nmodelC = fit(LinearModel, @formula(AlcConsumption ~ IQ), groupC)\n\npred(x)  = coef(model)'  * [1, x]\npredA(x) = coef(modelA)' * [1, x]\npredB(x) = coef(modelB)' * [1, x]\npredC(x) = coef(modelC)' * [1, x]\n\nxlims = collect(extrema(df.IQ))\n\np1 = scatter(df.IQ, df.AlcConsumption, c=:black, msw=0, ma=0.2, label=\"\")\n     plot!(xlims, pred.(xlims), c=:black, label=\"All data\")\n\np2 = scatter(groupA.IQ, groupA.AlcConsumption, c=:blue, msw=0, ma=0.2, label=\"\")\n     scatter!(groupB.IQ, groupB.AlcConsumption, c=:red, msw=0, ma=0.2, label=\"\")\n     scatter!(groupC.IQ, groupC.AlcConsumption, c=:green,msw=0, ma=0.2, label=\"\")\n     plot!(xlims, predA.(xlims), c=:blue, label=\"Group A\")\n     plot!(xlims, predB.(xlims), c=:red, label=\"Group B\")\n     plot!(xlims, predC.(xlims), c=:green, label=\"Group C\")\n\nplot(p1, p2, xlims=(xlims), ylims=(0,1), \n\txlabel=\"IQ\", ylabel=\"Alcohol Metric\", size=(800,400))", "meta": {"hexsha": "d124940db78493a4b7d48577d45845f60b8d8009", "size": 1249, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "8_chapter/simpsonsParadox.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "8_chapter/simpsonsParadox.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "8_chapter/simpsonsParadox.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 40.2903225806, "max_line_length": 81, "alphanum_fraction": 0.6301040833, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7687722523634862}}
{"text": "#    Copyright 2015 Raytheon BBN Technologies\n#  \n#     Licensed under the Apache License, Version 2.0 (the \"License\");\n#     you may not use this file except in compliance with the License.\n#     You may obtain a copy of the License at\n#  \n#       http://www.apache.org/licenses/LICENSE-2.0\n#  \n#     Unless required by applicable law or agreed to in writing, software\n#     distributed under the License is distributed on an \"AS IS\" BASIS,\n#     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#     See the License for the specific language governing permissions and\n#     limitations under the License.\n\nmodule SchattenNorms\n\nexport snorm, nucnorm, trnorm, specnorm, fnorm, dnorm\n\n\"\"\"\nComputes the nuclear norm of a matrix `m`.\n\"\"\"\nfunction nucnorm(m::AbstractMatrix)\n    norm(svdvals(m),1)\nend\n\n\"\"\"\nComputes the trace norm of a matrix `m`.\n\"\"\"\ntrnorm(m::AbstractMatrix) = nucnorm(m)\n\n\"\"\"\nComputes the Frobenius norm of a matrix `m`.\n\"\"\"\nfnorm(m::AbstractMatrix) = vecnorm(m,2)\n\n\"\"\"\nComputes the spectral norm of a matrix `m` (i.e., the maximum singular value).\n\"\"\"\nfunction specnorm(m::AbstractMatrix)\n    return norm(svdvals(m),Inf)\nend\n\n\"\"\"\nComputes the `p`-Schatten norm of a matrix `m`.\n\"\"\"\nfunction snorm(m::AbstractMatrix,p=2.0)\n    p == 2.0 && return vecnorm(m,2)\n    return norm(svdvals(m),p)\nend\n\ninclude(\"dnorm.jl\")\n\nend # module\n", "meta": {"hexsha": "36dffecae7dcf6d499bcb32cedcb74367c4889e7", "size": 1370, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SchattenNorms.jl", "max_stars_repo_name": "JuliaPackageMirrors/SchattenNorms.jl", "max_stars_repo_head_hexsha": "d3e97274f8706eca8d1ce3c0f343d0d7a913c68c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SchattenNorms.jl", "max_issues_repo_name": "JuliaPackageMirrors/SchattenNorms.jl", "max_issues_repo_head_hexsha": "d3e97274f8706eca8d1ce3c0f343d0d7a913c68c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SchattenNorms.jl", "max_forks_repo_name": "JuliaPackageMirrors/SchattenNorms.jl", "max_forks_repo_head_hexsha": "d3e97274f8706eca8d1ce3c0f343d0d7a913c68c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3703703704, "max_line_length": 78, "alphanum_fraction": 0.696350365, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7687722512792289}}
{"text": "\n# norm of off diagonal terms of a square matrix\nfunction norm_off(M)\n    if size(M[1],1)>1\n        return sqrt(sum(abs2(M[i,j]) + abs2(M[j,i]) for i in 1:size(M,1) for j in i+1:size(M,1)))\n    else\n        return 0.0\n    end\nend\n\nfunction diagonalization_iter(D)\n    n = size(D[1],1)\n    s = length(D)\n    \n    X = fill(zero(D[1][1,1]),n,n)\n    Y = fill(zero(D[1][1,1]),n,n)\n\n    A = fill(zero(D[1][1,1]),s,2)\n    b = fill(zero(D[1][1,1]),s)\n    for i in 1:n\n        for j in 1:n\n            if i != j\n                for k in 1:s\n                    A[k,1] = D[k][i,i]\n                    A[k,2] = D[k][j,j]\n                    b[k]   = -D[k][i,j]\n                end\n                v = A\\b\n                X[i,j] =  v[1]\n                Y[i,j] =  v[2]\n            end\n        end\n    end\n    for i in 1:n\n        X[i,i]=1\n        Y[i,i]=1\n    end\n    return X, Y\nend\n\nfunction diagonalization(M::Vector{Matrix{C}},\n                         Info = Dict{String,Any}(\n                             \"maxIter\" => 10,\n                             \"epsIter\" => 1.e-3)) where C\n    n  = length(M)\n    r  = size(M[1],1)\n\n    N   = (haskey(Info,\"maxIter\") ? Info[\"maxIter\"] : 10)\n    eps = (haskey(Info,\"epsIter\") ? Info[\"epsIter\"] : 1.e-3)\n\n    M1 = sum(M[i]*randn(Float64) for i in 1:n)\n    E  = eigvecs(M1)\n\n    F  = inv(E)\n    \n    D  = vcat([Matrix{C}(I,r,r)],[F*M[i]*E for i in 1:length(M)])\n    err = sum(norm_off.(D))\n    delta = sum(norm.(D))\n    #println(\"diag off: \", err)\n\n    Info[\"d0\"] = err\n    nit = 0\n\n    if err/delta > 5.e-2\n        delta = err\n        while nit < N && delta > eps\n            err0 = err\n            X,Y = diagonalization_iter(D)\n            D = [Y*D[i]*X for i in 1:length(D)]\n            E = E*X\n            F = Y*F\n            nit+=1\n            err = sum(norm_off.(D))\n            delta = err0-err\n            #println(\"Off\", nit,\": \", err, \"   delta: \", delta)\n        end\n        Info[\"d*\"]= err\n    end\n    Info[\"nIter\"] = nit\n    \n    Xi = fill(zero(E[1,1]),n,r)\n    for i in 1:r\n    \tfor j in 1:n\n\t    Xi[j,i] = D[j+1][i,i]/D[1][i,i]\n            #Xi[j,i] =(E[:,i]\\(M[j]*E[:,i]))[1]\n\tend\n    end\n    return Xi, E, Info\nend\n\n", "meta": {"hexsha": "e248d18725d0eeddca927ec3e7b8d93066060a43", "size": 2161, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/diagonalisation.jl", "max_stars_repo_name": "blegat/MultivariateSeries.jl", "max_stars_repo_head_hexsha": "a469f5d75ef8e99677400038b76ed057683d4748", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/diagonalisation.jl", "max_issues_repo_name": "blegat/MultivariateSeries.jl", "max_issues_repo_head_hexsha": "a469f5d75ef8e99677400038b76ed057683d4748", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/diagonalisation.jl", "max_forks_repo_name": "blegat/MultivariateSeries.jl", "max_forks_repo_head_hexsha": "a469f5d75ef8e99677400038b76ed057683d4748", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-24T12:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T20:05:47.000Z", "avg_line_length": 23.7472527473, "max_line_length": 97, "alphanum_fraction": 0.4113836187, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7687722506582892}}
{"text": "ν(G, L, Es, p) = p[1]*(G*L-Es/p[2])/(L + p[3]*G)\n\nfunction rate(C)\n    G, L, Es = C\n    p = (9.03f-2, 5.0f-2, 1.9f1)\n    ν(G, L, Es, p)\nend\n\nfunction reaction(du, u, p, t)\n    G, L, Es = u\n    dG  = du[1] = - ν(G, L, Es, p)\n    dL  = du[2] = - ν(G, L, Es, p)\n    dEs = du[3] =   ν(G, L, Es, p)\n    return du\nend\n\nfunction reaction!(du, u, p, t)\n    du = reaction(du, u, p, t)\nend\n\nfunction generate_true_solution(u₀, tₑ; nPoints=20)\n    p = (9.03f-2, 5.0f-2, 1.9f1)\n    tspan = (0.0, tₑ)\n    \n    prob = ODEProblem(reaction!, u₀, tspan, p, saveat=0:tₑ/nPoints:tₑ)\n    sol = solve(prob, Tsit5())\n    G = [c[1] for c in sol.u]\n    L = [c[2] for c in sol.u]\n    Es = [c[3] for c in sol.u]\n    time = sol.t\n\n  return permutedims([G L Es]), time\nend\n\nfunction plot_reaction(data)\n  C, time = data\n\n  pl = plot(xlabel=\"Time (min)\", ylabel=\"Concentration (mM)\", \n      ylims=(-2, 1.2*maximum(C)),\n      xlims=(-2, time[end]*1.01))\n  scatter!(pl, time, C[1,:], label=\"Sucrose\")\n  scatter!(pl, time, C[2,:], label=\"Stearic acid\")\n  scatter!(pl, time, C[3,:], label=\"Sucr-Stea-Esther\")\n  return pl\nend\n\nfunction prediction_vs_data(data, pred)\n    C, time = data\n    \n    pl = plot_reaction(data)\n    lcs = pl.series_list\n    plot!(pl, time, pred[1,:], label = \"\", lc=lcs[1][:linecolor])\n    plot!(pl, time, pred[2,:], label = \"\",  lc=lcs[2][:linecolor])\n    plot!(pl, time, pred[3,:], label = \"\",  lc=lcs[3][:linecolor])\n    return pl\nend", "meta": {"hexsha": "47e3497045f4960ca3ede763b85940cea36af689", "size": 1428, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/helper-functions.jl", "max_stars_repo_name": "Beramos/Workshop-NeuralODE-2020-", "max_stars_repo_head_hexsha": "72619c40737ccaf1caeb0acce7328e7e2227dc15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-11-06T12:33:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T19:31:13.000Z", "max_issues_repo_path": "src/helper-functions.jl", "max_issues_repo_name": "Beramos/Workshop-NeuralODE-2020-", "max_issues_repo_head_hexsha": "72619c40737ccaf1caeb0acce7328e7e2227dc15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/helper-functions.jl", "max_forks_repo_name": "Beramos/Workshop-NeuralODE-2020-", "max_forks_repo_head_hexsha": "72619c40737ccaf1caeb0acce7328e7e2227dc15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-06T10:02:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-23T08:53:05.000Z", "avg_line_length": 25.5, "max_line_length": 70, "alphanum_fraction": 0.5455182073, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.768772249268335}}
{"text": "### jacobisymbol\n\n# `jacobisymbol(a,n)` returns the Jacobi symbol. This is limited to bitstype integers.\n# This is faster than Combinatorics.jacobisymbol for bitstype inputs, but slower for\n#     BigInt inputs. Thus, these methods are complementary.\n    \n\nexport jacobisymbol\n\nmacro flip!(n) :($(esc(n)) = -$(esc(n))) end\nfunction jacobisymbol(a::Union{Signed,Unsigned},n::Union{Signed,Unsigned})\n    if n <= 0 || iseven(n) throw(DomainError()) end    \n    j = 1\n    if n < 0\n        n % 4 == 3  ? @flip!(j)  : nothing\n        @flip!(n)\n    end\n    while a != 0\n        while iseven(a)\n            n % 8 == 3 || n % 8 == 5 ? @flip!(j) : nothing\n            a >>= 1            \n        end\n        (a,n) = (n,a)\n        a % 4 == 3 && n % 4 == 3 ? @flip!(j) : nothing\n        a %= n\n    end    \n    return n == 1 ? j : 0\nend\n\n#Base.@vectorize_2arg Union{Signed,Unsigned} jacobisymbol\n", "meta": {"hexsha": "5e0d2428c0b3240922d4d56de45e8f65937433d5", "size": 882, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/jacobi.jl", "max_stars_repo_name": "JuliaTagBot/PrimeSieve.jl", "max_stars_repo_head_hexsha": "2611a29797dc78e650de2dab260991e5a314d5d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-04-19T20:39:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T02:07:54.000Z", "max_issues_repo_path": "src/jacobi.jl", "max_issues_repo_name": "JuliaTagBot/PrimeSieve.jl", "max_issues_repo_head_hexsha": "2611a29797dc78e650de2dab260991e5a314d5d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-08-02T22:03:18.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T14:29:44.000Z", "max_forks_repo_path": "src/jacobi.jl", "max_forks_repo_name": "JuliaTagBot/PrimeSieve.jl", "max_forks_repo_head_hexsha": "2611a29797dc78e650de2dab260991e5a314d5d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2015-04-20T19:03:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:41:46.000Z", "avg_line_length": 28.4516129032, "max_line_length": 86, "alphanum_fraction": 0.5464852608, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7687274293887947}}
{"text": "# alex's funcion\nc=0.5\nc1mlogc=c*(1-log(c))\n\nfunction alex(x::Array)\n    ind1=x.>-c\n    ind2=x.<=-c    \n    tmp=zeros(size(x))\n    tmp[ind1]=x[ind1]\n    tmp[ind2]=-log(-x[ind2]).*c-c1mlogc\n    ind1=ind2=0\n    return tmp\nend\n\nfunction gradalex(x::Array)\n    ind1=x.>-c\n    ind2=x.<=-c    \n    tmp=zeros(size(x))\n    tmp[ind1]=1.0\n    tmp[ind2]=-c./x[ind2]\n    ind1=ind2=0\n    return tmp\nend\n\n\nFalex(x::Array{Float64,2})=( alex(x) ,[]);\n\nfunction Falex_inplace(value,auxvalue,x::Array{Float64,2})\n    ind1=x.>-c\n    ind2=x.<=-c    \n    tmp=zeros(size(x))\n    tmp[ind1]=x[ind1]+c1mlogc\n    tmp[ind2]=-log(-x[ind2]).*c\n    ind1=ind2=0\n    copy!(value,tmp)\nend\n\nDalex(derivativeIDX,f_c,faux_c,grad_c,grad_n,x)=axpy!(1.0,grad_c.*gradalex(x),grad_n)\n\nif PROC==\"GPU\" # TODO\n    #Falex(x::CudaArray)=(alex(x),[])\n    Falex_inplace(value,aux,x::CudaArray)=alex!(x,value)\n\n    Dalex(derivativeIDX,f_c,faux_c,grad_c,grad_n,x::CudaArray)=gradalex!(grad_c,x,grad_n)\nend\n\nDerivative[Falex]=Dalex\nInplace[Falex]=Falex_inplace\n\nalex(A::ADnode)=ADnode(Falex,A)\nexport alex\n\n\n", "meta": {"hexsha": "a43ab5379dcf61e2988f71c8aab844a78c03ee43", "size": 1057, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/Falex.jl", "max_stars_repo_name": "davidbarber/AutoDiff", "max_stars_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2016-03-20T20:52:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T07:31:59.000Z", "max_issues_repo_path": "src/functions/Falex.jl", "max_issues_repo_name": "davidbarber/AutoDiff", "max_issues_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-06-17T20:12:48.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-17T20:12:48.000Z", "max_forks_repo_path": "src/functions/Falex.jl", "max_forks_repo_name": "davidbarber/AutoDiff", "max_forks_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-01-11T21:36:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-06T21:04:40.000Z", "avg_line_length": 19.5740740741, "max_line_length": 89, "alphanum_fraction": 0.6291390728, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363299661721, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7687274285026029}}
{"text": "# Elliptical Frechet and Marshal Olkim copulas generators\n\n## Elliptical copulas\n\n\"\"\"\n    Gaussian_cop\n\nGaussian copula\n\nFields:\n   - Σ - the correlation matrix must be symmetric, positively defined and with ones on diagonal\n\nConstructor\n\n    Gaussian_cop(Σ::Matrix{T}) where T <: Real\n\n```jldoctest\n\njulia> Gaussian_cop([1. 0.5; 0.5 1.])\nGaussian_cop([1.0 0.5; 0.5 1.0])\n\n```\n\"\"\"\nstruct Gaussian_cop{T} <: Copula{T}\n  Σ::Matrix{T}\n  n::Int\n  function(::Type{Gaussian_cop})(Σ::Matrix{T}) where T <: Real\n    Σ ≈ transpose(Σ) || throw(DomainError(\"Σ matrix not symmetric\"))\n    isposdef(Σ) || throw(DomainError(\"Σ matrix not positivelly defined\"))\n    prod(diag(Σ)) ≈ 1.0 || throw(DomainError(\"Σ matrix do not have ones on diagonal\"))\n    new{T}(Σ,size(Σ,1))\n  end\nend\n\n\nfunction simulate_copula!(U, copula::Gaussian_cop{T}; rng = Random.GLOBAL_RNG) where T\n  Σ = copula.Σ\n  z = transpose(rand(rng, MvNormal(Σ),size(U,1)))\n  for i in 1:size(Σ, 1)\n    d = Normal(0, sqrt.(Σ[i,i]))\n    z[:,i] = cdf.(d, z[:,i])\n  end\n  U .= Array(z)\n  return nothing\nend\n\n\"\"\"\n    Student_cop\n\nt-Student copula\n\nfields\n  - Σ::Matrix{Real} - the correlation matrix must be symmetric, positively defined and with ones on diagonal\n  - ν::Int - the parameter n.o. degrees of freedom we require ν > 0\n\nConstructor:\n\n    Student_cop(Σ::Matrix{Real}, ν::Int)\n\n```jldoctest\n\njulia> Student_cop([1. 0.5; 0.5 1.], 4)\nStudent_cop([1.0 0.5; 0.5 1.0], 4)\n\n```\n\"\"\"\nstruct Student_cop{T} <: Copula{T}\n  Σ::Matrix{T}\n  ν::Int\n  n::Int\n  function(::Type{Student_cop})(Σ::Matrix{T}, ν::Int) where T <: Real\n    Σ ≈ transpose(Σ) || throw(DomainError(\"Σ matrix not symmetric\"))\n    isposdef(Σ) || throw(DomainError(\"Σ matrix not positivelly defined\"))\n    prod(diag(Σ)) ≈ 1.0 || throw(DomainError(\"Σ matrix do not have ones on diagonal\"))\n    ν > 0 || throw(DomainError(\"ν lower or equal zero\"))\n    new{T}(Σ, ν,size(Σ,1))\n  end\nend\n\n\nfunction simulate_copula!(U, copula::Student_cop{T}; rng = Random.GLOBAL_RNG) where T\n  Σ = copula.Σ\n  ν = copula.ν\n  z = transpose(rand(rng, MvNormal(Σ),size(U,1)))\n  V = rand(rng, Chisq(ν), size(z, 1))\n  V = T.(V)\n  for i in 1:size(Σ, 1)\n    x = z[:,i].*sqrt.(ν./V)./sqrt(Σ[i,i])\n    z[:,i] = cdf.(TDist(ν), x)\n  end\n  U .= Array(z)\n  return nothing\nend\n\n\"\"\"\n    Frechet_cop\n\nThe Frechet copula\n\nFileds:\n  - n - number of marginals\n  - α - the parameter of the maximal copula\n  - β - the parameter of the minimal copula\n\nConstructor\n\n    Frechet_cop(n::Int, α::Real)\n\nThe one parameter Frechet copula is a combination of maximal copula with  weight α\nand independent copula with  weight 1-α.\n\nConstructor\n\n    Frechet_cop(n::Int, α::Real, β::Real)\n\nThe two parameters Frechet copula C = α C{max} + β C{min} + (1- α - β) C{⟂}, supported\nonly for n = 2.\n\n```jldoctest\njulia> Frechet_cop(4, 0.5)\nFrechet_cop(4, 0.5, 0.0)\n\njulia> Frechet_cop(2, 0.5, 0.3)\nFrechet_cop(2, 0.5, 0.3)\n```\n\"\"\"\nstruct Frechet_cop{T} <: Copula{T}\n  n::Int\n  α::T\n  β::T\n  function(::Type{Frechet_cop})(n::Int, α::T) where T <: Real\n    0 <= α <= 1 || throw(DomainError(\"generaton not supported for α ∉ [0,1]\"))\n    n > 1 || throw(DomainError(\"n must be greater than 1\"))\n    new{T}(n, α, 0.)\n  end\n  function(::Type{Frechet_cop})(n::Int, α::T, β::T) where T <: Real\n    0 <= α <= 1 || throw(DomainError(\"generaton not supported for α ∉ [0,1]\"))\n    0 <= β <= 1 || throw(DomainError(\"generaton not supported for β ∉ [0,1]\"))\n    n == 2 || throw(AssertionError(\"two parameters Frechet copula supported only for n = 2\"))\n    0 <= α+β <= 1 || throw(DomainError(\"α+β must be in range [0,1]\"))\n    new{T}(n, α, β)\n  end\nend\n\n\n\n\"\"\"\n    simulate_copula!(U::Matrix{Real}, copula::Frechet_cop; rng::AbstractRNG = Random.GLOBAL_RNG)\n\nGiven the preallocated output U, Returns size(U,1) realizations from the Frechet copula - Frechet_cop\nN.o. marginals is size(U,2), requires size(U,2) == copula.n\n\n```jldoctest\njulia> f = Frechet_cop(3, 0.5)\nFrechet_cop(3, 0.5, 0.0)\n\njulia> u = zeros(1,3)\n1×3 Array{Real,2}:\n 0.0  0.0  0.0\n\njulia> Random.seed!(43);\n\njulia> simulate_copula!(u,f)\n\njulia> u\n1×3 Array{Real,2}:\n 0.180975  0.775377  0.888934\n```\n\"\"\"\nfunction simulate_copula!(U, copula::Frechet_cop{T}; rng = Random.GLOBAL_RNG) where T\n  n = copula.n\n  α = copula.α\n  β = copula.β\n  size(U, 2) == n || throw(AssertionError(\"n.o. margins in pre allocated output and copula not equal\"))\n  if (β > 0) & (n == 2)\n    for j in 1:size(U,1)\n      u_el = rand(rng, T, n)\n      frechet_el2!(u_el, α, β, rand(rng, T))\n      U[j,:] = u_el\n    end\n  else\n    for j in 1:size(U,1)\n      u_el = rand(rng, T, n)\n      frechet_el!(u_el, α, rand(rng))\n      U[j,:] = u_el\n    end\n  end\nend\n\n\"\"\"\n  frechet(t::Int, n::Int, α::Real; rng::AbstractRNG)\n\nGiven n-variate random data u ∈ R^{t, n}\nReturns t realization of n variate data generated from one parameter Frechet_cop(n, α).\n\n```jldoctest\njulia> Random.seed!(43);\n\njulia> u = rand(10, 2);\n\njulia> frechet(0.5, u)\n10×2 Array{Real,2}:\n 0.180975   0.661781\n 0.0742681  0.0742681\n 0.888934   0.125437\n 0.0950087  0.0950087\n 0.130474   0.130474\n 0.912603   0.740184\n 0.828727   0.00463791\n 0.400537   0.0288987\n 0.521601   0.521601\n 0.955881   0.851275\n```\n\"\"\"\nfunction frechet(α::T, u; rng) where T\n  for j in 1:size(u, 1)\n    v = rand(rng, T)\n    el = u[j, :]\n    frechet_el!(el, α, v)\n    u[j,:] = el\n  end\n  u\nend\n\n\"\"\"\n  frechet_el!(u::Vector{Real}, α::Real, v::Real)\n\nGiven n-variate random vector changes it to such modeled by the two parameters Frechet_cop(n, α, β).\nv is the random number form [0,1].\n\"\"\"\nfunction frechet_el!(u, α, v)\n  if (α >= v)\n    for i in 1:length(u)-1\n      u[i] = u[end]\n    end\n  end\nend\n\n\"\"\"\n  function frechet_el2!(u::Vector{Real}, α::Real, β::Real, v::Real)\n\nGiven bivariate random vector changes it to such modeled by the two parameters Frechet_cop(n, α, β).\nv is the random number form [0,1]\n\n\"\"\"\nfunction frechet_el2!(u, α, β, v)\n  if (α >= v)\n    u[1] = u[2]\n  elseif (α < v <= α+β)\n    u[1] = 1-u[2]\n  end\nend\n\n### Marshall - Olkin familly\n\n\"\"\"\n    Marshall_Olkin_cop\n\nFields:\n  - n::Int - number of marginals\n  - λ::Vector{Real} - vector of non-negative parameters λₛ, i.e.:\n      λ = [λ₁, λ₂, ..., λₙ, λ₁₂, λ₁₃, ..., λ₁ₙ, λ₂₃, ..., λₙ₋₁ₙ, λ₁₂₃, ..., λ₁₂...ₙ]\n      and n = ceil(Int, log(2, length(λ)-1)).\n\nConstructor\n\n    Marshall_Olkin_cop(λ)\n\nlength(λ) ≧ 3 is required\n\n```jldoctest\njulia> Marshall_Olkin_cop([0.5, 0.5, 0.6])\nMarshall_Olkin_cop(2, [0.5, 0.5, 0.6])\n\njulia> Marshall_Olkin_cop([0.5, 0.5, 0.6, 0.7, 0.7, 0.7, 0.8])\nMarshall_Olkin_cop(3, [0.5, 0.5, 0.6, 0.7, 0.7, 0.7, 0.8])\n```\n\"\"\"\nstruct Marshall_Olkin_cop{T} <: Copula{T}\n  n::Int\n  λ::Vector{T}\n  function(::Type{Marshall_Olkin_cop})(λ::Vector{T}) where T <: Real\n    minimum(λ) >= 0 || throw(AssertionError(\"all parameters must by >= 0 \"))\n    length(λ) >= 3 || throw(AssertionError(\"not supported for length(λ) < 3\"))\n    n = floor(Int, log(2, length(λ)+1))\n    new{T}(n, λ)\n  end\nend\n\n\n\n\"\"\"\n    simulate_copula!(U::Matrix{Real}, copula::Marshall_Olkin_cop; rng::AbstractRNG = Random.GLOBAL_RNG)\n\nGiven the preallocated output U, Returns size(U,1) realizations from the Marshall  Olkin copula - Marshall_Olkin_cop\nN.o. marginals is size(U,2), requires size(U,2) == copula.n\n\n```jldoctest\njulia> u = zeros(1,2)\n1×2 Array{Float64,2}:\n 0.0  0.0\n\njulia> cop = Marshall_Olkin_cop([1.,2.,3.])\nMarshall_Olkin_cop(2, [1.0, 2.0, 3.0])\n\njulia> Random.seed!(43);\n\njulia> simulate_copula!(u,cop)\n\njulia> u\n1×2 Array{Float64,2}:\n 0.854724  0.821831\n```\n\"\"\"\nfunction simulate_copula!(U, copula::Marshall_Olkin_cop{T}; rng = Random.GLOBAL_RNG) where T\n  λ = copula.λ\n  n = copula.n\n  size(U, 2) == n || throw(AssertionError(\"n.o. margins in pre allocated output and copula not equal\"))\n  s = collect(combinations(1:n))\n  for j in 1:size(U,1)\n    u = rand(rng, T, 2^n-1)\n    U[j,:] = mocopula_el(u, n, λ, s)\n  end\nend\n\n\"\"\"\n  mocopula(u::Matrix{Real}, n::Int, λ::Vector{Real})\n\n  Returns: t x n Matrix{Float}, t realizations of n-variate data generated from Marshall-Olkin\n  copula with parameter vector λ of non-negative elements λₛ, given [0,1]ᵗˣˡ ∋ u, where\n  l = 2ⁿ-1\n\n```jldoctest\n\n  julia> mocopula([0.2 0.3 0.4; 0.3 0.4 0.6; 0.4 0.5 0.7], 2, [1., 1.5, 2.])\n  3×2 Array{Float64,2}:\n   0.252982  0.201189\n   0.464758  0.409039\n   0.585662  0.5357\n\n```\n\"\"\"\nfunction mocopula(u, n, λ)\n  T = eltype(u)\n  t = size(u,1)\n  U = zeros(T, t, n)\n  s = collect(combinations(1:n))\n  for j in 1:t\n      U[j,:] = mocopula_el(u[j,:], n, λ, s)\n  end\n  U\nend\n\n\"\"\"\n    mocopula_el(u::Vector{Real}, n::Int, λ::Vector{Real}, s::Vector{Vector{Int}})\n\n```jldoctest\n\njulia> mocopula_el([0.1, 0.2, 0.3], 2, [1., 2., 3.], s)\n2-element Array{Float64,1}:\n 0.20082988502465082\n 0.1344421423967149\n```\n\"\"\"\nfunction mocopula_el(u, n, λ, s)\n  T = eltype(u)\n  l = length(u)\n  U = zeros(T, n)\n  for i in 1:n\n    inds = findall([i in s[k] for k in 1:l])\n    x = minimum([-log(u[k])./(λ[k]) for k in inds])\n    Λ = sum(λ[inds])\n    U[i] = exp.(-Λ*x)\n  end\n    U\nend\n", "meta": {"hexsha": "ef2b3a69fef9b14fc1830508e8cb00a73027858e", "size": 8919, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/eliptic_fr_mo_copulas.jl", "max_stars_repo_name": "ZKSI/DatagenCopulabased.jl", "max_stars_repo_head_hexsha": "fcda2f59484dc6273491519a8d8d684b280c0b09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-02-06T11:00:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-19T23:02:11.000Z", "max_issues_repo_path": "src/eliptic_fr_mo_copulas.jl", "max_issues_repo_name": "ZKSI/DatagenCopulabased.jl", "max_issues_repo_head_hexsha": "fcda2f59484dc6273491519a8d8d684b280c0b09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eliptic_fr_mo_copulas.jl", "max_forks_repo_name": "ZKSI/DatagenCopulabased.jl", "max_forks_repo_head_hexsha": "fcda2f59484dc6273491519a8d8d684b280c0b09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-16T21:59:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-16T21:59:04.000Z", "avg_line_length": 23.6578249337, "max_line_length": 116, "alphanum_fraction": 0.6240609934, "num_tokens": 3562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317102, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7687274238057094}}
{"text": "module V3P\n\n# import Base.+, Base.*, Base./, Base.norm, Base.==, Base.<, Base.>\nimport Base: +, *, /, ==, <, >, norm, dot\nexport Vec3, norm, dist\n\nimmutable Vec3{T}\n    x::T\n    y::T\n    z::T\nend\n\n(+)(a::Vec3, b::Vec3) = Vec3(a.x+b.x, a.y+b.y, a.z+b.z)\n(*)(p::Vec3, s::Real) = Vec3(p.x*s, p.y*s, p.z*s)\n(*)(s::Real, p::Vec3) = p*s\n(/)(p::Vec3, s::Real) = (1.0/s)*p\n\n(==)(a::Vec3, b::Vec3) = (a.x==b.x)&&(a.y==b.y)&&(a.z==b.z) ? true : false;\n\ndot(a::Vec3, b::Vec3) = a.x*b.x + a.y*b.y + a.z*b.z;\nnorm(a::Vec3) = sqrt(dot(a,a));\n\n(<)(a::Vec3, b::Vec3) = norm(a) < norm(b) ? true : false;\n(>)(a::Vec3, b::Vec3) = norm(a) > norm(b) ? true : false;\n\ndist(a::Vec3, b::Vec3) = sqrt((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) + (a.z-b.z)*(a.z-b.z))\n\nend\n", "meta": {"hexsha": "5448e700a08624d4e059ac9310d0ab0722fc20f4", "size": 746, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chp03/Code/V3P.jl", "max_stars_repo_name": "PetrKryslUCSD/Mastering-Julia-1.0", "max_stars_repo_head_hexsha": "375342d933a48142b5b605b9c39cb5922e010691", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chp03/Code/V3P.jl", "max_issues_repo_name": "PetrKryslUCSD/Mastering-Julia-1.0", "max_issues_repo_head_hexsha": "375342d933a48142b5b605b9c39cb5922e010691", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chp03/Code/V3P.jl", "max_forks_repo_name": "PetrKryslUCSD/Mastering-Julia-1.0", "max_forks_repo_head_hexsha": "375342d933a48142b5b605b9c39cb5922e010691", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-15T19:05:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T19:05:40.000Z", "avg_line_length": 25.724137931, "max_line_length": 94, "alphanum_fraction": 0.4785522788, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.7687274209600234}}
{"text": "\"\"\"\n    legendre_point(p::T) where {T<:Integer}\n\nCalculate Legendre points of polynomial degree p\n\"\"\"\nlegendre_point(p::T) where {T<:Integer} = gausslegendre(p + 1)[1]\n\n\n\"\"\"\n    ∂legendre(p::T, x) where {T<:Integer}\n\nCalculate derivatives of Legendre polynomials of degree p at location x\n\"\"\"\n∂legendre(p::T, x) where {T<:Integer} = last(sf_legendre_Pl_deriv_array(p, x)[2])\n\nfunction ∂legendre(p::I, x::T) where {I<:Integer,T<:AbstractArray{<:Real,1}}\n    Δ = similar(x)\n    for i in eachindex(Δ)\n        Δ[i] = ∂legendre(p, x[i])\n    end\n\n    return Δ\nend\n\n\n\"\"\"\n    ∂radau(p::TI, x::TU) where {TI<:Integer,TU<:Union{Real,AbstractArray{<:Real,1}}}\n\nCalculate derivatives of Radau polynomials of degree p at location x\n\"\"\"\nfunction ∂radau(p::TI, x::TU) where {TI<:Integer,TU<:Union{Real,AbstractArray{<:Real,1}}}\n    Δ = ∂legendre(p, x)\n    Δ_plus = ∂legendre(p + 1, x)\n\n    dgl = @. (-1.0)^p * 0.5 * (Δ - Δ_plus)\n    dgr = @. 0.5 * (Δ + Δ_plus)\n\n    return dgl, dgr\nend\n", "meta": {"hexsha": "f8a62b55d0ddacd66c19a818e189e96361da175c", "size": 971, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Polynomial/poly_legendre.jl", "max_stars_repo_name": "vavrines/FR.jl", "max_stars_repo_head_hexsha": "0108d769f4f9df7401d5fa3e8d8ca269cabacdd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-07-01T07:16:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T11:22:48.000Z", "max_issues_repo_path": "src/Polynomial/poly_legendre.jl", "max_issues_repo_name": "vavrines/FR.jl", "max_issues_repo_head_hexsha": "0108d769f4f9df7401d5fa3e8d8ca269cabacdd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-25T20:31:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T10:24:59.000Z", "max_forks_repo_path": "src/Polynomial/poly_legendre.jl", "max_forks_repo_name": "vavrines/FR.jl", "max_forks_repo_head_hexsha": "0108d769f4f9df7401d5fa3e8d8ca269cabacdd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-23T07:06:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T07:06:02.000Z", "avg_line_length": 24.275, "max_line_length": 89, "alphanum_fraction": 0.623069001, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7687274185180213}}
{"text": "\"\"\"Функции для численного дифференцирования с использованием центральных разностей\"\"\"\nmodule NumDiff\n\"\"\"\nНахождение частной производной первого порядка\nот векторозначной функции многих переменных\n\n``derivative(func, [t,] x, k; p, h, order) -> df``\n\nДля вычисления производных используется метод центральных разностей.\n\n# Аргументы\n\n* `func::Function`: функция в виде func(t, x) или func(x).\n* `t::Float64`: обциональный скалярный аргумент функции (время).\n* `x::Vector{Float64}`: векторный аргумент функции `x`.\n* `k::Int`: номер переменной, по которой необходимо взять производную.\n* `h::Float64`: шаг приращения, который необходимо использовать.\n* `order::Int`: порядок точности {2, 4, 6, 8}.\n\n# Возвращаемые значения\n\n`df::Vector{Float64}`: вектор частных производных.\n\"\"\"\nfunction derivative(func::Function, t::Float64, x::Vector{Float64}; k=1, h=0.1, order=4)\n  # Используются центральные конечные разности коэффициенты этих разностей задаются массивом\n  # Заполняем массив коэффициентов\n  a = [[-0.5, 0.0, 0.5], # Порядка 2\n       [1.0/12.0, -2.0/3.0, 0.0, 2.0/3.0, -1.0/12.0], # Порядка 4\n       [-1.0/60.0, 3.0/20.0, -3.0/4.0, 0.0, 3.0/4.0, -3.0/20.0, 1.0/60.0], # Порядка 6\n       [1.0/280.0, -4.0/105.0, 1.0/5.0, -4.0/5.0, 0.0, 4.0/5.0, -1.0/5.0, 4.0/105.0, -1.0/280.0]] # Порядка 8\n\n  # Проверяем по возвращаемому значению,\n  # является ли функция векторной или скалярной\n  if isa(func(t, x), Vector{Float64})\n    df = zeros(func(t, x))\n  elseif isa(func(t, x), Float64)\n    df = 0.0\n  end\n\n  Ih = h * eye(Float64, length(x))\n\n  if order == 2\n    for j = 0:order\n      df = df + a[1][j+1] * func(t, x + (j - 1) * Ih[:, k])\n    end\n  elseif order == 4\n    for j = 0:order\n      df = df + a[2][j+1] * func(t, x + (j - 2) * Ih[:, k])\n    end\n  elseif order == 6\n    for j = 0:order\n      df = df + a[3][j+1] * func(t, x + (j - 3) * Ih[:, k])\n    end\n  elseif order == 8\n    for j = 0:order\n      df = df + a[4][j+1] * func(t, x + (j - 4) * Ih[:, k])\n    end\n  else\n    println(STDERR, \"Variable order = {2, 4, 6, 8}! Using order=4\")\n    for j = 0:order\n      df = df + a[2][j+1] * func(t, x + (j - 2) * Ih[:, k])\n    end\n  end\n\n  return df / h\nend\n\n# Частные производные от функции без параметра t\nfunction derivative(func::Function, x::Vector{Float64}; k=1, h=0.1, order=4)\n  # Заполняем массив коэффициентов\n  a = [[-0.5, 0.0, 0.5], # Порядка 2\n       [1.0/12.0, -2.0/3.0, 0.0, 2.0/3.0, -1.0/12.0], # Порядка 4\n       [-1.0/60.0, 3.0/20.0, -3.0/4.0, 0.0, 3.0/4.0, -3.0/20.0, 1.0/60.0], # Порядка 6\n       [1.0/280.0, -4.0/105.0, 1.0/5.0, -4.0/5.0, 0.0, 4.0/5.0, -1.0/5.0, 4.0/105.0, -1.0/280.0]] # Порядка 8\n\n  # Проверяем по возвращаемому значению,\n  # является ли функция векторной или скалярной\n  if isa(func(x), Vector{Float64})\n    df = zeros(func(x))\n  elseif isa(func(x), Float64)\n    df = 0.0\n  end\n\n  Ih = h * eye(Float64, length(x))\n\n  if order == 2\n    for j = 0:order\n      df = df + a[1][j+1] * func(x + (j - 1) * Ih[:, k])\n    end\n  elseif order == 4\n    for j = 0:order\n      df = df + a[2][j+1] * func(x + (j - 2) * Ih[:, k])\n    end\n  elseif order == 6\n    for j = 0:order\n      df = df + a[3][j+1] * func(x + (j - 3) * Ih[:, k])\n    end\n  elseif order == 8\n    for j = 0:order\n      df = df + a[4][j+1] * func(x + (j - 4) * Ih[:, k])\n    end\n  else\n    println(STDERR, \"Variable order = {2, 4, 6, 8}! Using order=4\")\n    for j = 0:order\n      df = df + a[2][j+1] * func(x + (j - 2) * Ih[:, k])\n    end\n  end\n\n  return df / h\nend\n\n# Частные производные от функции одного аргумента без параметра t\nfunction derivative(func::Function, x::Float64; h=0.1, order=4)\n  # Заполняем массив коэффициентов\n  a = [[-0.5, 0.0, 0.5], # Порядка 2\n       [1.0/12.0, -2.0/3.0, 0.0, 2.0/3.0, -1.0/12.0], # Порядка 4\n       [-1.0/60.0, 3.0/20.0, -3.0/4.0, 0.0, 3.0/4.0, -3.0/20.0, 1.0/60.0], # Порядка 6\n       [1.0/280.0, -4.0/105.0, 1.0/5.0, -4.0/5.0, 0.0, 4.0/5.0, -1.0/5.0, 4.0/105.0, -1.0/280.0]] # Порядка 8\n\n  # Проверяем по возвращаемому значению,\n  # является ли функция векторной или скалярной\n  if isa(func(x), Vector{Float64})\n    df = zeros(func(x))\n  elseif isa(func(x), Float64)\n    df = 0.0\n  end\n\n  if order == 2\n    for j = 0:order\n      df = df + a[1][j+1] * func(x + (j - 1) * h)\n    end\n  elseif order == 4\n    for j = 0:order\n      df = df + a[2][j+1] * func(x + (j - 2) * h)\n    end\n  elseif order == 6\n    for j = 0:order\n      df = df + a[3][j+1] * func(x + (j - 3) * h)\n    end\n  elseif order == 8\n    for j = 0:order\n      df = df + a[4][j+1] * func(x + (j - 4) * h)\n    end\n  else\n    println(STDERR, \"Variable order = {2, 4, 6, 8}! Using order=4\")\n    for j = 0:order\n      df = df + a[2][j+1] * func(x + (j - 2) * h)\n    end\n  end\n\n  return df / h\nend\n\n\"\"\"\nНахождение матрицы Якоби от векторозначной функции многих переменных\n\n``jacobian(func, t, x; h=0.1, order=4) -> J``\n\n# Аргументы\n\n* `func::Function`: функция в виде func(t, x, p).\n* `t::Float64`: скалярный аргумент функции (время).\n* `x::Vector{Float64}`: векторный аргумент функции `x`.\n* `p::Tuple`: параметры функции (даже если их нет).\n* `h::Float64`: шаг приращения, который необходимо использовать.\n* `order::Int`: порядок точности {2, 4, 6, 8}.\n\n# Возвращаемые значения\n\n* `J::Matrix{Float64}(n, n)`: матрица Якоби.\n\"\"\"\nfunction jacobian(func::Function, t::Float64, x::Vector{Float64}; h=0.1, order=4)\n  n = length(x)\n  J = Matrix{Float64}(n, n)\n\n  for i in 1:n\n    J[:, i] = derivative(func, t, x; k=i, h=h, order=order)\n  end\n  return J\nend\nend # module\n", "meta": {"hexsha": "458f12b0bd461e16e491c698541b515920441c9f", "size": 5459, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NumDiff.jl", "max_stars_repo_name": "mngnum/DiffNum.jl", "max_stars_repo_head_hexsha": "bc35d205f5b84263f5ace15f94d03af6c0345a80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NumDiff.jl", "max_issues_repo_name": "mngnum/DiffNum.jl", "max_issues_repo_head_hexsha": "bc35d205f5b84263f5ace15f94d03af6c0345a80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NumDiff.jl", "max_forks_repo_name": "mngnum/DiffNum.jl", "max_forks_repo_head_hexsha": "bc35d205f5b84263f5ace15f94d03af6c0345a80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9945054945, "max_line_length": 109, "alphanum_fraction": 0.5706173292, "num_tokens": 2551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167044, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7687274165585269}}
{"text": "\"\"\"\n    MarcenkoPastur()\nThe Marcenko Pastur Distrbitution (sometimes called the Marchenko-Pastur \nDistribution or Law) has a probability distribution\n\n'''math\nf(x) = \\frac{√{β(ϱ) - x)(x - α(ϱ))}}{2πx} 1_{[α(ϱ),β(ϱ)]}(x)\n'''\nwhere 1_{[a,b]}(x) is the indicator function that returns 1 if x exists in\n[a,b] and returns 0 otherwise\n\nExternal Links\n\n* https://en.wikipedia.org/wiki/Marchenko%E2%80%93Pastur_distribution\n\n\"\"\"\n\nusing Statistics\nusing Distributions\nimport Distributions: @check_args\nimport Distributions: @distr_support\n\nstruct MarcenkoPastur{T<:Real} <: ContinuousUnivariateDistribution\n    ρ::T\n    MarcenkoPastur{T}(ρ::T) where {T<:Real} = new{T}(ρ)\nend\n\nfunction MarcenkoPastur(ρ::T, check_args=true) where {T <: Real}\n    check_args && @check_args(MarcenkoPastur, ρ > zero(ρ))\n    return MarcenkoPastur{T}(ρ)\nend\n\nMarcenkoPastur(ρ::Integer) = MarcenkoPastur(float(ρ))\n\n@distr_support MarcenkoPastur (1-√d.ρ)^2 (1+√d.ρ)^2\n\n#### Conversions\nfunction convert(::Type{MarcenkoPastur{T}}, ρ::Real) where T<:Real\n    MarcenkoPastur(T(ρ))\nend\nfunction convert(::Type{MarcenkoPastur{T}},d::MarcenkoPastur{S}) where {T <: Real, S<: Real}\n    MarcenkoPastur(T(d.ρ),check_args=false)\nend\n\nα(ρ) = (1-√ρ)^2\nβ(ρ) = (1+√ρ)^2\n\n### Parameters\nleftbound(d::MarcenkoPastur) = α(d.ρ)\nrightbound(d::MarcenkoPastur) = β(d.ρ)\nparams(d::MarcenkoPastur) = (d.ρ)\n\n### Statistics\nmean(d::MarcenkoPastur) = d.ρ\nmode(d::MarcenkoPastur) = 2*α(d.ρ)*β(d.ρ)/(α(d.ρ)+β(d.ρ))\n# TODO\n# median(d::MarcenkoPastur)\n# TODO gather analytic form for each and use to determine which one should be\n# in terms of the other\n# var(d::MarcenkoPastur) = \n# std(d::MarcenkoPastur) = \n#\n# skewness(d::MarcenkoPastur)\n# kurtosis(d::MarcenkoPastur)\n#\n# entropy(d::MarcenkoPastur)\n\nfunction pdf(d::MarcenkoPastur, x::Real)\n    if ρ < 1\n        return pdf(d, d.ρ*x)\n    √((β(d.ρ)-x)*(x-α(d.ρ)))/(2π*x)\nend\n\nfunction logpdf(d::MarcenkoPastur, x::Real)\n    0.5*(log(β(d.ρ)-x)+log(x-α(d.ρ))) - log(2π*x)\nend\n\n# TODO\n# function cdf(d::MarcenkoPastur)\n#     \n# end\n#\n# function quantile(d::MarcenkoPastur)\n#\n# end\n#\n# function cquantile(d::MarcenkoPastur)\n#\n# end", "meta": {"hexsha": "e2d6c61f3e86e22a07ec5bbcf49e8f094f022060", "size": 2118, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "MarcenkoPastur.jl", "max_stars_repo_name": "JulianKeane/PCAJuliaDemo", "max_stars_repo_head_hexsha": "e04d3003729e7bccccc2755a2881ab6a87816fbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MarcenkoPastur.jl", "max_issues_repo_name": "JulianKeane/PCAJuliaDemo", "max_issues_repo_head_hexsha": "e04d3003729e7bccccc2755a2881ab6a87816fbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MarcenkoPastur.jl", "max_forks_repo_name": "JulianKeane/PCAJuliaDemo", "max_forks_repo_head_hexsha": "e04d3003729e7bccccc2755a2881ab6a87816fbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.797752809, "max_line_length": 92, "alphanum_fraction": 0.6813031161, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.8633916222765627, "lm_q1q2_score": 0.7686725812212853}}
{"text": "\"\"\"`tmean(x; tr=0.2)`\n\nTrimmed mean of real-valued array `x`.\n\nFind the mean of `x`, omitting the lowest and highest `tr` fraction of the data.\nThis requires `0 <= tr <= 0.5`. The amount of trimming defaults to `tr=0.2`.\n\"\"\"\nfunction tmean{S <: Real}(x::AbstractArray{S}; tr::Real=0.2)\n    tmean!(copy(x), tr=tr)\nend\n\n\n\"\"\"`tmean!(x; tr=0.2)`\n\nTrimmed mean of real-valued array `x`, which sorts the vector `x` in place.\n\nFind the mean of `x`, omitting the lowest and highest `tr` fraction of the data.\nThis requires `0 <= tr <= 0.5`. The trimming fraction defaults to `tr=0.2`.\n\"\"\"\nfunction tmean!{S <: Real}(x::AbstractArray{S}; tr::Real=0.2)\n    if tr < 0 || tr > 0.5\n        error(\"tr cannot be smaller than 0 or larger than 0.5\")\n    elseif tr == 0\n        return mean(x)\n    elseif tr == .5\n        return median!(x)\n    else\n        n   = length(x)\n        lo  = floor(Int64, n*tr)+1\n        hi  = n+1-lo\n        return mean(sort!(x)[lo:hi])\n    end\nend\n\n\n\"\"\"`winval(x; tr=0.2)`\n\nWinsorize real-valued array `x`.\n\nReturn a copy of `x` in which extreme values (that is, the lowest and highest\nfraction `tr` of the data) are replaced by the lowest or highest non-extreme\nvalue, as appropriate. The trimming fraction defaults to `tr=0.2`.\n\"\"\"\nfunction winval{S <: Real}(x::AbstractArray{S}; tr::Real=0.2)\n    const n = length(x)\n    xcopy   = sort(x)\n    ibot    = floor(Int64, tr*n)+1\n    itop    = n-ibot+1\n    xbot, xtop = xcopy[ibot], xcopy[itop]\n    return  [x[i]<=xbot ? xbot : (x[i]>=xtop ? xtop : x[i]) for i=1:n]\nend\n\n\"\"\"`winmean(x; tr=0.2)`\n\nWinsorized mean of real-valued array `x`.\n\nSee `winval` for what Winsorizing (clipping) signifies.\n\"\"\"\nwinmean{S <: Real}(x::AbstractArray{S}; tr=0.2) = mean(winval(x, tr=tr))\n\n\"\"\"`winvar(x; tr=0.2)`\n\nWinsorized variance of real-valued array `x`.\n\nSee `winval` for what Winsorizing (clipping) signifies.\n\"\"\"\nwinvar{S <: Real}(x::AbstractArray{S}; tr=0.2) = var(winval(x, tr=tr))\n\n\"\"\"`winstd(x; tr=0.2)`\n\nWinsorized standard deviation of real-valued array `x`.\n\nSee `winval` for what Winsorizing (clipping) signifies.\n\"\"\"\nwinstd{S <: Real}(x::AbstractArray{S}; tr=0.2) = std(winval(x, tr=tr))\n\n\n\"\"\"`wincov(x, y; tr=0.2)`\n\nCompute the Winsorized covariance between `x` and `y`.\n\nSee `winval` for what Winsorizing (clipping) signifies.\n\"\"\"\nfunction wincov{S <: Real, T <: Real}(x::AbstractArray{S}, y::AbstractArray{T}; tr::Real=0.2)\n    xvec = winval(x, tr=tr)\n    yvec = winval(y, tr=tr)\n    wcov = cov(xvec, yvec)\nend\n\n\n\n\"\"\"`trimse(x; tr=0.2)`\n\nEstimated standard error of the mean for Winsorized real-valued array `x`.\n\nSee `winval` for what Winsorizing (clipping) signifies.\n\"\"\"\ntrimse{S <: Real}(x::AbstractArray{S}; tr::Real=0.2) =\n    sqrt(winvar(x,tr=tr))/((1-2tr)*sqrt(length(x)))\n\n\"\"\"`trimci(x; tr=0.2, alpha=0.05, ...)`\n\nCompute a (1-α) confidence interval for the trimmed mean.\n\nReturns a `RobustStats.testOutput` object.\n\"\"\"\nfunction trimci{S <: Real}(x::AbstractArray{S}; tr::Real=0.2, alpha::Real=0.05, nullvalue::Real=0, method=true)\n    se  = trimse(x, tr=tr)\n    n   = length(x)\n    df::Int64   = n-2*floor(tr*n)-1\n    estimate    = tmean(x, tr=tr)\n    confint     = [estimate-Rmath.qt(1-alpha/2, df)*se,\n                   estimate+Rmath.qt(1-alpha/2, df)*se]\n    statistic   = (estimate-nullvalue)/se\n    pval        = 2*(1-Rmath.pt(abs(statistic),df))\n    METHOD      = method ? \"(1-α) confidence interval for the trimmed mean\\n\": nothing\n    output           = testOutput()\n    output.method    = METHOD\n    output.df        = df\n    output.estimate  = estimate\n    output.ci        = confint\n    output.statistic = statistic\n    output.p         = pval\n    return output\nend\n\n\n\"\"\"`idealf(x)`\n\nCompute the ideal fourths (interpolated quartiles) of real-valued array `x`.\n\nReturns a tuple of (1st_quartile, 3rd_quartile)\n\"\"\"\nfunction idealf{S <: Real}(x::AbstractArray{S})\n    y       = sort(x)\n    n       = length(x)\n    j       = floor(Int64, n/4+5/12) # 25%ile is in [y[j], y[j+1]]\n    k       = n-j+1        # 75%ile is in [y[k],y[k-1]]\n    g       = n/4+5/12 - j   # weighting for the two data surrounding quartiles.\n    (1-g).*y[j]+g.*y[j+1], (1-g).*y[k]+g.*y[k-1]\nend\n\n\"\"\"`pbvar(x; beta=0.2)`\n\nReturn the percentage bend midvariance of real-valued array `x`, a robust, efficient\nmeasure of scale (dispersion). Lower values of beta increase efficiency but reduce\nrobustness.\nThis requires `0 <= beta <= 0.5`. The trimming fraction defaults to `beta=0.2`.\n\"\"\"\nfunction pbvar{S <: Real}(x::AbstractArray{S}; beta::Real=0.2)\n    const n = length(x)\n    med = median(x)\n    absdev = abs.(x-med)\n    sort!(absdev)\n\n    m = floor(Int64, (1-beta)*n+0.5)\n    ω = absdev[m]\n    if ω <= 0   # At least a fraction (1-beta) of all values are identical\n        return 0.0\n    end\n\n    z = 0.0\n    counter = 0\n    for i = 1:n\n        ψ = absdev[i]/ω\n        if abs(ψ) >= 1.0\n            z += 1.0\n        else\n            z += ψ^2\n            counter += 1\n        end\n    end\n    n*(ω^2)*z/(counter^2)\nend\n\n\n\"\"\"`bivar(x; beta=0.2)`\n\nReturn the biweight midvariance of real-valued array `x`, a robust, efficient\nmeasure of scale (dispersion). Lower values of beta increase efficiency but reduce\nrobustness.\nThis requires `0 <= beta <= 0.5`. The trimming fraction defaults to `beta=0.2`.\n\"\"\"\nfunction bivar{S <: Real}(x::AbstractArray{S})\n    const n = length(x)\n    med = median(x)\n    MAD = mad(x)\n    q = Rmath.qnorm(0.75)\n    top = bot = 0.0\n    for i = 1:n\n        u = abs(x[i]-med)./(9.*q.*MAD)\n        if u<1.0\n            top += n*(x[i]-med)*(x[i]-med)*(1-u*u).^4\n            bot += (1-u*u)*(1-5*u*u)\n        end\n    end\n    top/(bot^2)\nend\n\n\n\"\"\"`tauloc(x; cval=4.5)`\n\nReturn the tau measure of location of real-valued array `x`, a robust, efficient\nestimator.\n\"\"\"\nfunction tauloc{S <: Real}(x::AbstractArray{S}; cval::Real=4.5)\n    const n = length(x)\n    med = median(x)\n    s = Rmath.qnorm(0.75)*mad(x)\n    Wnom = Wden = 0.0\n    for i in 1:n\n        y = (x[i]-med)/s\n        temp = (1.0-(y/cval)^2)^2\n        if abs(temp) <= cval\n            Wnom += temp*x[i]\n            Wden += temp\n        end\n    end\n    Wnom/Wden\nend\n\n\n\"\"\"`tauvar(x; cval=3.0)`\n\nReturn the tau measure of dispersion of real-valued array `x`, a robust, efficient\nestimator.\n\"\"\"\nfunction tauvar{S <: Real}(x::AbstractArray{S}; cval::Real=3.0)\n    const n = length(x)\n    s     = Rmath.qnorm(0.75)*mad(x)\n    tloc  = tauloc(x)\n    W     = 0.0\n    cval2 = cval*cval\n    [W    += min(((x[i]-tloc)/s)*((x[i]-tloc)/s), cval2) for i=1:n]\n    s*s*W/n\nend\n\n\n\"\"\"`outbox(x; mbox::Bool=false, ...)`\n\nUse a modified boxplot rule based on the ideal fourths (`idealf`). When the named argument\n`mbox` is set to true, a modification of the boxplot rule suggested by Carling (2000) is used.\n\nReturns an object with vectors `keepid` and `outid` giving the kept/rejected element numbers,\n`nout` (the number of rejected elements), and `outval`, an array of the outlier values.\n\"\"\"\nfunction outbox{S <: Real}(x::AbstractArray{S}; mbox::Bool=false, gval::Real=NaN, method::Bool=true)\n    const n = length(x)\n    lower_quartile, upper_quartile = idealf(x)\n    IQR = upper_quartile-lower_quartile\n    cl = cu = 0.0\n    if mbox\n        if isnan(gval)\n            gval=(17.63*n-23.64)/(7.74*n-3.71)\n        end\n        cl = median(x) - gval*IQR\n        cu = median(x) + gval*IQR\n    elseif !mbox\n        if isnan(gval)\n            gval=1.5\n        end\n        cl = lower_quartile - gval*IQR\n        cu = upper_quartile + gval*IQR\n    end\n    flag = (x.<cl) .| (x.>cu)\n    vec = 1:n\n    outid  = vec[flag]\n    keepid = vec[!flag]\n    outval = x[flag]\n    nout = length(outid)\n    if method && !mbox\n        METHOD = \"Outlier detection method using \\nthe ideal-fourths based boxplot rule\\n\"\n    elseif method && mbox\n        METHOD = \"Outlier detection method using \\nthe ideal-fourths based boxplot rule\\n(using the modification suggested by Carling (2000))\\n\"\n    else\n        METHOD = nothing\n    end\n    outOutput(outid, keepid, outval, nout, METHOD)\nend\n\n\n\"\"\"`msmedse(x)`\n\nReturn the standard error of the median, computed through the method recommended\nby McKean and Sshrader (1984).\"\"\"\nfunction msmedse{S <: Real}(x::AbstractArray{S})\n    const n = length(x)\n    y = sort(x)\n    if duplicated(y)\n        warn(\"Tied values detected. Estimate of standard error might be highly inaccurate, even with n large\")\n    end\n    q995 = Rmath.qnorm(.995)\n    av::Int = round((n+1)/2 - q995*sqrt(n/4))\n    if av == 0\n        av = 1\n    end\n    top::Int = n-av+1\n    abs((y[top]-y[av])/(2q995))\nend\n\n\n\"\"\"`binomci(s, n; alpha=0.05)`\n\nCompute the (1-α) confidence interval for p, the binomial probability of success, given\n`s` successes in `n` trials. Returns an object with components `p_hat` (the observed\nfraction of successes) and `confint=[lo,hi]` (the confidence interval). The computation\nuses Pratt's method.\n\nCan also use `binomci(x; alpha=0.05)`, where x is an array consisting only of 0s\nand 1s. It's equivalent to `binomci(sum(x), length(x), alpha=alpha)`.\"\"\"\nfunction binomci(s::Int, n::Int; alpha::Real=0.05)\n    if s > n\n        error(\"binomci requires s≤n (no more successes than trials)\")\n    elseif s < 0\n        error(\"binomci requires s≥0\")\n    elseif n <= 1\n        error(\"binomci requires n≥2 (at least 2 trials)\")\n    end\n    p_hat=s/n\n    if s == 0\n        upper = 1.0-alpha.^(1/n)\n        return binomciOutput(p_hat, [0,upper], n)\n    elseif s == 1\n        lower = 1-(1-alpha/2).^(1/n)\n        upper = 1-(alpha/2).^(1/n)\n        return binomciOutput(p_hat, [lower, upper], n)\n    elseif s == (n-1)\n        lower = (alpha/2).^(1/n)\n        upper = (1-alpha/2).^(1/n)\n        return binomciOutput(p_hat, [lower, upper], n)\n    elseif s == n\n        lower = alpha.^(1/n)\n        upper = 1\n        return binomciOutput(p_hat, [lower, upper], n)\n    end\n\n    z     = Rmath.qnorm(1-alpha/2)\n    A     = ((s+1)/(n-s))*((s+1)/(n-s))\n    B     = 81.*(s+1)*(n-s)-9.*n-8\n    C     = (0-3)*z*sqrt(9.*(s+1)*(n-s)*(9*n+5-z^2)+n+1)\n    D     = 81.*(s+1)^2-9.*(s+1)*(2+z^2)+1\n    E     = 1+A*((B+C)/D)^3\n    upper = 1/E\n\n    A     = (s/(n-s-1))*(s/(n-s-1))\n    B     = 81.*s*(n-s-1)-9.*n-8\n    C     = 3.*z*sqrt(9.*s*(n-s-1)*(9.*n+5-z^2)+n+1)\n    D     = 81.*s^2-9.*s*(2+z^2)+1\n    E     = 1+A*((B+C)/D)^3\n    lower = 1/E\n    binomciOutput(p_hat, [lower, upper], n)\nend\n\n\nfunction binomci(x::Vector{Int}; alpha::Real=0.05)\n    for i = 1:length(x)\n        if x[i]<0 || x[i] > 1\n            error(\"x vector must contain only values 0 or 1.\")\n        end\n    end\n    binomci(sum(x), length(x), alpha=alpha)\nend\n\n\n\n\"\"\"`acbinomci(s, n; alpha=0.05)`\n\nCompute the (1-α) confidence interval for p, the binomial probability of success, given\n`s` successes in `n` trials. Returns an object with components `p_hat` (the observed\nfraction of successes) and `confint=[lo,hi]` (the confidence interval). The computation\nuses a generalization of the Agresti-Coull  method that was studied by Brown, Cai, & DasGupta.\n\nCan also use `acbinomci(x; alpha=0.05)`, where `x` is an array consisting only of 0s\nand 1s. It's equivalent to `acbinomci(sum(x), length(x), alpha=alpha)`.\"\"\"\nfunction acbinomci(s::Int, n::Int; alpha::Real=0.05)\n    if s > n\n        error(\"acbinomci requires s≤n (no more successes than trials)\")\n    elseif s < 0\n        error(\"acbinomci requires s≥0\")\n    elseif n <= 1\n        error(\"acbinomci requires n≥2 (at least 2 trials)\")\n    end\n    p_hat=s/n\n\n    if s == 0\n        upper = 1.0-alpha.^(1/n)\n        return binomciOutput(p_hat, [0, upper], n)\n    elseif s == 1\n        lower = 1-(1-alpha/2)^(1/n)\n        upper = 1-(alpha/2)^(1/n)\n        return binomciOutput(p_hat, [lower, upper], n)\n    elseif s == (n-1)\n        lower = (alpha/2)^(1/n)\n        upper = (1-alpha/2)^(1/n)\n        return binomciOutput(p_hat, [lower, upper], n)\n    elseif s == n\n        lower = alpha^(1/n)\n        upper = 1\n        return binomciOutput(p_hat, [lower, upper], n)\n    end\n\n    cr    = Rmath.qnorm(1-alpha/2)\n    ntil  = n+cr^2\n    ptil  = (s+cr^2/2)/ntil\n    lower = ptil-cr*sqrt(ptil*(1-ptil)/ntil)\n    upper = ptil+cr*sqrt(ptil*(1-ptil)/ntil)\n    binomciOutput(p_hat, [lower, upper], n)\nend\n\nfunction acbinomci(x::Vector{Int}; alpha::Real=0.05)\n    for i = 1:length(x)\n        if x[i]<0 || x[i] > 1\n            error(\"x vector must contain only values 0 or 1.\")\n        end\n    end\n    acbinomci(sum(x), length(x), alpha=alpha)\nend\n\n\n\"\"\"`_estimate_dispersion(x)`\n\nEstimate dispersion by the following methods. Return the first value that gives\na non-zero dispersion. Each are normalized to 1.0 for Gaussian distributions:\n\n1. Normalized median absolute deviation `mad`,\n1. Normalized inter-quartile range `iqrn`,\n1. Normalized winsorized variance `winvar`.\"\"\"\nfunction _estimate_dispersion{S <: Real}(x::AbstractArray{S})\n    m =  mad(x)\n    m > 0 && return m\n\n    m = iqrn(x)\n    m > 0 && return m\n\n    m =  sqrt(winvar(x)./0.4129)\n    m > 0 && return m\n\n    error(\"All measures of dispersion are equal to 0\")\nend\n\n\n\n\"\"\"`sint(x; alpha=.05)`\n`sint(x, testmedian; alpha=.05)`\n\nCompute the (1-α) confidence interval for the median. In the second form,\nuse the Hettmansperger and Sheather interpolation method to estimate a p-value\nfor the `testmedian`.\"\"\"\nfunction sint{S <: Real}(x::AbstractArray{S}; alpha::Real=0.05, method::Bool=true)\n    const n = length(x)\n    k = Int(Rmath.qbinom(alpha/2.0, n, 0.5))\n    gk = Rmath.pbinom(n-k, n, .5) - Rmath.pbinom(k-1, n, .5)\n    if gk < (1 - alpha)\n        k = k - 1\n        gk = Rmath.pbinom(n-k, n, .5) - Rmath.pbinom(k-1, n, .5)\n    end\n    gkp1 = Rmath.pbinom(n-k-1, n, .5) - Rmath.pbinom(k, n, .5)\n    kp = k + 1\n\n    xsort=sort(x)\n    nmk = n-k\n    nmkp = nmk+1\n    ival = (gk-1+alpha)/(gk-gkp1)\n    lam = ((n-k)*ival)/(k+(n-2k)*ival)\n    low = lam*xsort[kp]+(1-lam)*xsort[k]\n    hi = lam*xsort[nmk]+(1-lam)*xsort[nmkp]\n    if method\n        METHOD=\"Confidence interval for the median\\n\"\n        if duplicated(x)\n            METHOD *= \"Duplicate values detected; hdpb() might have more power\\n\"\n        end\n    else\n        METHOD=nothing\n    end\n    output=testOutput()\n    output.method=METHOD\n    output.ci=[low, hi]\n    output\nend\n\n\nfunction sint{S <: Real}(x::AbstractArray{S}, testmedian;\n    alpha::Real=0.05, method::Bool=true)\n    ci = sint(x, alpha=alpha, method=false).ci\n    med = median(x)\n    cichoice = testmedian<med ? 1 : 2\n\n    # Find the pvalue that excludes testmedian by binary search.\n    minloga = -8.0\n    maxloga = -0.001\n    ciA = sint(x, alpha=exp(minloga)).ci[cichoice]-testmedian\n    ciB = sint(x, alpha=exp(maxloga)).ci[cichoice]-testmedian\n    if ciA*ciB > 0\n        if ciB*(med-testmedian)<0\n            pval = 1.0\n        else\n            pval = 0.0\n        end\n    else\n        while (maxloga-minloga > .0001)\n            newloga = (maxloga+minloga)/2\n            newci = sint(x, alpha=exp(newloga)).ci[cichoice]-testmedian\n            if newci*ciB >= 0\n                ciB = newci\n                maxloga = newloga\n            else\n                ciA = newci\n                minloga = newloga\n            end\n        end\n        pval = exp((maxloga+minloga)/2.0)\n    end\n    if method\n        METHOD=\"Confidence interval for the median with p-val.\\n\"\n        if duplicated(x)\n            METHOD *= \"Duplicate values detected; hdpb() might have more power\\n\"\n        end\n    else\n        METHOD=nothing\n    end\n    output = testOutput()\n    output.method = METHOD\n    output.ci     = ci\n    output.p      = pval\n    output\nend\n\n\n\"\"\"`hpsi(x, bend=1.28)`\n\nEvaluate Huber's ψ function for each value in the vector `x`.\nψ(x) = max( min(x,bend), -bend).\"\"\"\nfunction hpsi{S <: Real}(x::AbstractArray{S}, bend::Real=1.28)\n    ψ = Array(x)\n    ψ[x .> bend] = bend\n    ψ[x .< -bend] = -bend\n    ψ\nend\n\n\n\"\"\"`onestep(x, bend=1.28)`\n\nCompute one-step M-estimator of location using Huber's ψ.\"\"\"\nfunction onestep{S <: Real}(x::AbstractArray{S}, bend::Real=1.28)\n    MED = median(x)\n    MAD = mad(x)\n    y = (x-MED)/MAD\n    A = sum(hpsi(y, bend))\n    B = sum(abs.(y) .<= bend)\n    return MED + MAD*A/B\nend\n\n\"\"\"`bootstrapci(x; est=onestep, alpha=0.05, nboot=2000, nullvalue=NaN)`\n\nCompute a (1-α) confidence interval for the location-estimator function `est`\nusing a bootstrap calculation. The default estimator is `onestep`. If `nullvalue` is\ngiven, it is the target value used when computing a p-value.\n\"\"\"\nfunction bootstrapci{S <: Real}(x::AbstractArray{S}; est::Function=onestep,\n    alpha::Real=0.05, nboot::Integer=2000, seed=2, nullvalue::Real=NaN)\n    if isa(seed, Int)\n        srand(seed)\n    elseif seed\n        srand(2)\n    end\n    const n = length(x)\n    bvec = zeros(nboot)\n    for i = 1:nboot\n        randid=rand(1:n, n)\n        bvec[i]=est(x[randid])\n    end\n    low::Int = round((alpha/2)*nboot) + 1\n    up = nboot-low + 1\n    sort!(bvec)\n\n    pv = NaN\n    if nullvalue != NaN\n        pv = mean(bvec.>nullvalue)+0.5*mean(bvec.==nullvalue)\n        pv = 2min(pv, 1-pv)\n    end\n    estimate = est(x)\n    output = testOutput()\n    output.estimate = estimate\n    output.ci = [bvec[low], bvec[up]]\n    output.p = pv\n    output\nend\n\n\"\"\"`bootstrapse(x; est=median, alpha=0.05, nboot=2000)`\n\nCompute the standard error of the location-estimator function `est`\nusing a bootstrap calculation. The default estimator is `median`.\n\"\"\"\nfunction bootstrapse{S <: Real}(x::AbstractArray{S};\n        nboot::Integer=1000, est::Function=median, seed=2)\n    if isa(seed, Int)\n        srand(seed)\n    elseif seed\n        srand(2)\n    end\n    const n = length(x)\n    bvec = zeros(nboot)\n    for i = 1:nboot\n        randid=rand(1:n, n)\n        bvec[i]=est(x[randid])\n    end\n    std(bvec)\nend\n\n\n\"\"\"`mom(x; bend=2.24)`\n\nReturns a modified one-step M-estimator of location (MOM), which is the unweighted\nmean of all values not more than (bend times the `mad(x)`) away from the data\nmedian.\n\"\"\"\nfunction mom{S <: Real}(x::AbstractArray{S}; bend::Real=2.24)\n    mom!(copy(x), bend=bend)\nend\n\n\"\"\"`mom!(x)`\n\nLike `mom`, but will sort the input vector.\"\"\"\nfunction mom!{S <: Real}(x::AbstractArray{S}; bend::Real=2.24)\n    const n = length(x)\n    med = median!(x)\n    MAD = mad(x)\n    not_extreme = abs.(x-med) .<= bend*MAD\n    mean(x[not_extreme])\nend\n\n\n\"\"\"`momci(x; bend=2.24, alpha=0.05, nboot=2000)`\n\nCompute a bootstrap, (1-α) confidence interval for the MOM-estimator of location based on Huber's ψ.\nThe default number of bootstrap resamplings is nboot=2000.\"\"\"\nfunction momci{S <: Real}(x::AbstractArray{S}; bend::Real=2.24, alpha::Real=0.05,\n    nboot::Integer=2000, seed=2, nullvalue::Real=NaN)\n    estimator(z) = mom!(z, bend=bend)\n    bootstrapci(copy(x), est=estimator, alpha=alpha, nboot=nboot, seed=seed, nullvalue=nullvalue)\nend\n\n\"\"\"`contam_randn([T=Float64], n; epsilon=0.1, k=10.0)`\n\nContaminated normal distribution N(0,1). (That is, with μ=0, σ=1.) A fraction `epsilon` of\nvalues will be N(0,`k`).\"\"\"\nfunction contam_randn(T::Type, n::Integer; epsilon::Real=0.1, k::Real=10)\n    k <= 0 && error(\"k > 0 is required\")\n    epsilon > 1 || epsilon < 0 && error(\"0 ≤ epsilon ≤ 1 is required\")\n    output = randn(T, n)\n    contaminated = rand(n) .< epsilon\n    output[contaminated] *= k\n    return output\nend\n\ncontam_randn(n::Integer; epsilon::Real=0.1, k::Real=10) =\n    contam_randn(Float64, n, epsilon=epsilon, k=k)\n\n\n\n\"\"\"`trimpb(x; tr=0.2, alpha=0.05, nboot=2000, win=false, nullvalue=0.0)`\n\nCompute a (1-α) confidence interval for a trimmed mean with a trimming fraction of `tr`.\n\nUse `nboot` bootstrap samples and `alpha` for α.\n\nIf `win` is a real number, it is the amount of Winsorizing before bootstrapping.\nIf `win` is true, then use 10% Winsorizing. If `win` is false, no Winsorizing is done.\n\nThe p-value is for the hypothesis that trimmed mean equals `nullvalue`.\n\"\"\"\nfunction trimpb{S <: Real}(x::AbstractArray{S}; tr::Real=0.2, alpha::Real=0.05, nboot::Integer=2000,\n                win=false, nullvalue::Real=0.0, seed=2)\n    if isa(win, Bool) && win\n        win = 0.1\n    end\n    if win > tr\n        error(\"trimpb() requires that the amount of Winsorizing ≤ the amount of trimming.\")\n    end\n    wx = winval(x, tr=win)\n\n    estimator(x) = tmean!(x, tr=tr)\n    bootstrapci(wx, est=estimator, alpha=alpha, nboot=nboot, seed=seed, nullvalue=nullvalue)\nend\n\n\n\n\"\"\"`procb(x, y; seed=2)`\n\nCompute a (1-α) confidence interval for Pearson's correlation coefficient.\n\nThis function uses an adjusted percentile bootstrap method that\ngives good results when the error term is heteroscedastic.\n\"\"\"\nfunction pcorb{S <: Real, T <: Real}(x::AbstractArray{S}, y::AbstractArray{T}; seed=2)\n   if isa(seed, Bool)\n        seed && srand(2)\n    else\n        srand(seed)\n    end\n    const n = length(x)\n    # Wow. Every number in this function is totally magic.\n    bvec=zeros(Float64, 599)\n    for i=1:599\n        randid=rand(1:n, n)\n        tempx = x[randid]\n        tempy = y[randid]\n        bvec[i]=cor(tempx, tempy)\n    end\n    if n >= 250\n        ilow, ihi = 15, 584\n    elseif n >= 180\n        ilow, ihi = 14, 585\n    elseif n >= 80\n        ilow, ihi = 11, 588\n    elseif n >= 40\n        ilow, ihi = 8, 592\n    else\n        ilow, ihi = 7, 593\n    end\n    sort!(bvec)\n    output = testOutput()\n    output.estimate = cor(x, y)\n    output.ci = [bvec[ilow], bvec[ihi]]\n    output\nend\n\n\n\n\"\"\"`yuend(x,y; tr=0.2, alpha=0.05)`\n\nCompare the trimmed means of two dependent random variables `x` and `y`.\nThe default amount of trimming `tr` is 20%.\n\nA (1-α) confidence interval for the difference of trimmed mean of `x` minus\nthe trimmed mean of `y` is computed and returned in `yuend.ci`.\nThe significance level is returned in `yuend.siglevel`.\n\"\"\"\nfunction yuend{S <: Real, T <: Real}(x::AbstractArray{S}, y::AbstractArray{T};\n        tr::Real=0.2, alpha::Real=0.05, method::Bool=true)\n    const n = length(x)\n    if n != length(y)\n        error(\"`x` and `y` must agree in length\")\n    end\n    h1::Integer = n - 2*floor(tr*n)\n    q1 = (n - 1)*winvar(x, tr=tr)\n    q2 = (n - 1)*winvar(y, tr=tr)\n    q3 = (n - 1)*wincov(x, y, tr=tr)\n    df = h1 - 1\n    se = sqrt((q1 + q2 - 2q3)/(h1*(h1-1)))\n    crit = Rmath.qt(1 - alpha/2, df)\n    meandif = tmean(x, tr=tr) - tmean(y, tr=tr)\n    confint = [meandif - crit*se, meandif + crit*se]\n    test = meandif/se\n    p = 2*(1 - Rmath.pt(abs(test), df))\n    if method\n        METHOD=\"Comparing the trimmed means of two dependent variables.\\n\"\n    else\n        METHOD=nothing\n    end\n    output = testOutput()\n    output.method = METHOD\n    output.ci = confint\n    output.p = p\n    output.estimate = meandif\n    output.se = se\n    output.statistic = test\n    output.n = n\n    output.df = df\n    output\nend\n\nfunction pbos{S <: Real}(x::AbstractArray{S}; beta::Real=0.2)\n    temp    = sort( abs.( x - median(x) ))\n    nval    = length( x )\n    omhatid::Integer = floor( (1 - beta)*nval )\n    omhatx  = temp[ omhatid ]\n    psi     = ( x - median(x) )./ omhatx\n    i1      = length(psi[ psi .< -1 ])\n    i2      = length(psi[ psi .> 1 ])\n    sx      = 0.0\n    [ sx += psi[i] < -1 ? 0 : [ psi[i] > 1 ? 0 : x[i] ]  for i=1:nval ]\n    return ( sx  + omhatx * (i2 - i1))/(nval - i1 - i2)\nend\n\n\n#Compute the percentage bend correlation between x and y\n#beta is the bending constant for omega sub N.\nfunction pbcor{S <: Real, T <: Real}(x::AbstractArray{S}, y::AbstractArray{T}; beta::Real=0.2)\n    nval = length(x)\n    if length(y) != nval\n        error(\"x and y do not agree in length.\")\n    end\n    temp    = sort( abs.( x - median(x) ))\n    omhatid::Integer = floor( (1 - beta)*nval )\n    omhatx  = temp[ omhatid ]\n    temp    = sort( abs.( y - median(y) ))\n    omhaty  = temp[ omhatid ]\n    a       = (x .- pbos(x, beta=beta) )./omhatx\n    b       = (y .- pbos(y, beta=beta) )./omhaty\n    for i = 1:nval\n        if a[i] < -1\n            a[i] = -1\n        elseif a[i] > 1\n            a[i] = 1\n        end\n        if b[i] < -1\n            b[i] = -1\n        elseif b[i] > 1\n            b[i] = 1\n        end\n    end\n    Pbcor   = sum( a.*b )/sqrt(sum( a.*a ) * sum( b.*b ))\n    test    = Pbcor*sqrt( ( nval - 2 )/( 1 - Pbcor*Pbcor ) )\n    sig     = 2*( 1 - Rmath.pt(abs(test), nval-2))\n\n    METHOD=nothing\n\n    output = testOutput()\n    output.method = METHOD\n    output.p = sig\n    output.estimate = Pbcor\n    output.statistic = test\n    output.n = nval\n    output.df = nval - 2\n    output\nend\n", "meta": {"hexsha": "4f40964e39ffce2ddc5da0eccb221a4ddf4b132c", "size": 24195, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/RobustStats.jl-cf8b7ac2-edfd-5d52-b105-178bb1715a45", "max_stars_repo_head_hexsha": "46eabf13a227b8a7c7165942d747ebd40d527200", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2015-12-06T11:08:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T15:54:25.000Z", "max_issues_repo_path": "src/functions.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/RobustStats.jl-cf8b7ac2-edfd-5d52-b105-178bb1715a45", "max_issues_repo_head_hexsha": "46eabf13a227b8a7c7165942d747ebd40d527200", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2016-06-27T08:18:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:32:59.000Z", "max_forks_repo_path": "src/functions.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/RobustStats.jl-cf8b7ac2-edfd-5d52-b105-178bb1715a45", "max_forks_repo_head_hexsha": "46eabf13a227b8a7c7165942d747ebd40d527200", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-04-25T17:04:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:15:33.000Z", "avg_line_length": 29.2210144928, "max_line_length": 144, "alphanum_fraction": 0.59322174, "num_tokens": 8193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.863391617003942, "lm_q1q2_score": 0.7686725765271016}}
{"text": "using DrWatson\n@quickactivate \"StatReth\"\n\n# %%\n\"\"\"2H1\nPr(twins|speciesA) = 0.1\nPr(twins|speciesB) = 0.2\nPr(speciesA) = Pr(speciesB) = 0.5\nPr(twins) = Pr(twins|speciesA) * Pr(speciesA) + Pr(twins|speciesB) * Pr(speciesB)\n          = 0.1 * 0.5 + 0.2 * 0.5 = 0.15\n\nNow births twins.\n\nBayes:\nPr(species|twins) = Pr(twins|species) * Pr(species) / Pr(twins)\nPr(panda = speciesA|twins) = 0.1 * 0.5 / 0.15 = 1/3\nPr(panda = speciesB|twins) = 0.2 * 0.5 / 0.15 = 2/3\n\n\nPr(twin|panda) = Pr(twins|speciesA) * Pr(panda = speciesA) +\n                 Pr(twins|speciesB) * Pr(panda = speciesB)\n               = 0.1 * 1/3 + 0.2 * 2/3 = 0.167\n\n\"\"\"\n# %%\n\"\"\"2H2\nPr(twins|speciesA) = 0.1\nPr(twins|speciesB) = 0.2\nPr(speciesA) = Pr(speciesB) = 0.5\nPr(twins) = Pr(twins|speciesA) * Pr(speciesA) + Pr(twins|speciesB) * Pr(speciesB)\n          = 0.1 * 0.5 + 0.2 * 0.5 = 0.15\n\nNow births twins.\n\nBayes:\nPr(species|twins) = Pr(twins|species) * Pr(species) / Pr(twins)\nPr(panda = speciesA|twins) = 0.1 * 0.5 / 0.15 = 1/3\n\"\"\"\n# %%\n\"\"\"2H3\nPr(twins|speciesA) = 0.1  |  Pr(singleinfant|speciesA) = 0.9\nPr(twins|speciesB) = 0.2  |  Pr(singleinfant|speciesB) = 0.8\n\nNow:\nPr(speciesA) = 1/3\nPr(speciesB) = 2/3\nPr(twin|panda) = 0.167\n\nPr(singleinfant) = Pr(singleinfant|speciesA) * Pr(speciesA) +\n                   Pr(singleinfant|speciesB) * Pr(speciesB)\n                 = 0.9 * 1/3 + 0.8 * 2/3 = 0.833\n\nNow births single infant.\n\nBayes:\nPr(species|singleinfant) = Pr(singleinfant|species) * Pr(species) / Pr(singleinfant)\nPr(panda = speciesA|singleinfant) = 0.9 * 1/3 / 0.833 = 0.36\n\"\"\"\n# %%\n\"\"\"2H4\nI understood the test like this:\n\n                          panda is:\n                    speciesA    speciesB\ntest    speciesA      0.8         0.35\nsays:   speciesB      0.2         0.65\n\nNow the test comes back as speciesA.\n\nWe would like to know Pr(panda = speciesA | test = speciesA).\n\nBayes:\nPr(test = A | panda = A) = 0.8\nPr(panda = A) = Pr(panda = B) = 0.5\nPr(test = A) = 0.8 * 0.5 + 0.35 * 0.5 = 0.575\nPr(test = B) = 0.2 * 0.5 + 0.65 * 0.5 = 0.425\n\nPr(panda = A | test = A)\n            = Pr(test = A | panda = A) * Pr(panda = A) / Pr(test = A)\n            = 0.8 * 0.5 / 0.575 = 0.696\nPr(panda = B | test = A)\n            = Pr(test = A | panda = B) * Pr(panda = B) / Pr(test = A)\n            = 0.35 * 0.5 / 0.425 = 0.304\n\nThis will be our new prior:\n=> Pr(speciesA) = 0.696\n=> Pr(speciesB) = 0.304\n\n\nNow births twins:\nWe want to know: Pr(speciesA|twins)\n\nPr(twins|speciesA) = 0.1  |  Pr(singleinfant|speciesA) = 0.9\nPr(twins|speciesB) = 0.2  |  Pr(singleinfant|speciesB) = 0.8\n\nBayes:\nPr(speciesA|twins) = Pr(twins|speciesA) * Pr(speciesA) / Pr(twins)\nPr(twins|speciesA) = 0.1\nPr(speciesA) = 0.696\nPr(twins) = 0.1 * 0.696 + 0.2 * 0.304 = 0.130\n=> Pr(speciesA|twins) = 0.1 * 0.696 / 0.130 = 0.535\n=> Pr(speciesB|twins) = 0.2 * 0.304 / 0.130 = 0.468\n(including some rounding errors)\n\nNew priors:\n=> Pr(speciesA) = 0.535\n=> Pr(speciesB) = 0.468\n\n\nNow births twins:\nWe want to know: Pr(speciesA|singleinfant)\n\nBayes:\nPr(speciesA|singleinfant) = Pr(singleinfant|speciesA) * Pr(speciesA) / Pr(singleinfant)\nPr(singleinfant|speciesA) = 0.9\nPr(speciesA) = 0.535\nPr(singleinfant) = 0.9 * 0.535 + 0.8 * 0.468 = 0.856\n=> Pr(speciesA|twins) = 0.9 * 0.535 / 0.856 = 0.563\n=> Pr(speciesB|twins) = 0.8 * 0.468 / 0.856 = 0.437\n\n\"\"\"\n\n\n# %%\nusing Statistics\nusing BenchmarkTools\n\nfunction genetest(p)\n    if p == true  # panda is A\n        return rand() < 0.8\n    else          # panda is B\n        return rand() > 0.65\n    end\nend\n\nfunction twinbirth(p)\n    if p == true  # panda is A\n        return rand() < 0.1\n    else          # panda is B\n        return rand() < 0.2\n    end\nend\n\nfunction singleinfant(p)\n    if p == true  # panda is A\n        return rand() < 0.9\n    else          # panda is B\n        return rand() < 0.8\n    end\nend\n\n\nf(p) = mean(p[@. genetest(p) & twinbirth(p) & singleinfant(p)])\n\nfunction g(p)\n    countA = count(p) do p\n        genetest(p) && twinbirth(p) && singleinfant(p) && p\n    end\n    countB = count(p) do p\n        genetest(p) && twinbirth(p) && singleinfant(p) && !p\n    end\n    countA / (countA + countB)\nend\n\nfunction h(pandasA)\n    countA = 0\n    countB = 0\n    for p in pandasA\n        if genetest(p) && twinbirth(p) && singleinfant(p)\n            if p\n                countA += 1\n            else\n                countB += 1\n            end\n        end\n    end\n    countA / (countA + countB)\nend\n\n\nn = 10000000\npandasA = rand(Bool, n)\n\nf(pandasA)\ng(pandasA)\nh(pandasA)\n", "meta": {"hexsha": "e19837e8601f65f937966526460d400be88b7bba", "size": 4468, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/ch02/2H1-4.jl", "max_stars_repo_name": "karajan9/statisticalrethinking", "max_stars_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-06-03T14:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T16:52:26.000Z", "max_issues_repo_path": "exercises/ch02/2H1-4.jl", "max_issues_repo_name": "karajan9/statisticalrethinking", "max_issues_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-13T05:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T14:05:57.000Z", "max_forks_repo_path": "exercises/ch02/2H1-4.jl", "max_forks_repo_name": "karajan9/statisticalrethinking", "max_forks_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-01T13:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-03T23:40:53.000Z", "avg_line_length": 23.8930481283, "max_line_length": 87, "alphanum_fraction": 0.5666965085, "num_tokens": 1814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896132, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.7686725561376372}}
{"text": "#    Problem :\n#    *********\n#\t The separable extension of Rosenbrock's function.\n#\n#    Origonal SIF Source:problem 21 in\n#    J.J. More', B.S. Garbow and K.E. Hillstrom,\n#    \"Testing Unconstrained Optimization Software\",\n#    ACM Transactions on Mathematical Software, vol. 7(1), pp. 17-41, 1981.\n#\n#    SROSENBR.SIF classification SUR2-AN-V-0\n#\n#    Number of variables is variable \n#\n# Daniel Henderson, 08/2021\n\n\nf = (x) -> begin\n\tfx = 0.0\n\tfor i in firstindex(x):2:lastindex(x)\n\t\tt1     = 1 - x[i]\n\t\tt2     = 10(x[i+1] - x[i]^2)\n\t\tfx    += t1^2 + t2^2\n\tend\n    return fx\nend\n\ng! = (g, x) -> begin\n\tfor i in firstindex(x):2:lastindex(x)\n\t\tt1     = 1 - x[i]\n\t\tt2     = 10(x[i+1] - x[i]^2)\n\t\tg[i+1] = 20t2\n\t\tg[i]   = -2(x[i] * g[i+1] + t1)\n\tend\n    return g\nend\n\nfg! = (g, x) -> begin\n\tfx = 0.0\n\tfor i in firstindex(x):2:lastindex(x)\n\t\tt1     = 1 - x[i]\n\t\tt2     = 10(x[i+1] - x[i]^2)\n\t\tg[i+1] = 20t2\n\t\tg[i]   = -2(x[i] * g[i+1] + t1)\n\t\tfx    += t1^2 + t2^2\n\tend\n    return fx, g\nend\n\ninit = (n::Int=5000) -> begin\n\tmod(n, 2) > 0 && @warn \"SROSENBR: number of variables must be even\" \n\tq = max(1, div(n, 2))\n\tn = 2q\n\n    x0 = [j % 2 == 1 ? 1.2 : 1.0 for j in 1:n]\n    return n, x0\nend\n\nTestSet[\"SROSENBR\"] = UncProgram(\"SROSENBR\",  f, g!, fg!, init)", "meta": {"hexsha": "3027c0e07af3744924f56d57a09040f7bce8dada", "size": 1254, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/programs/SROSENBR.jl", "max_stars_repo_name": "danphenderson/UncNLPrograms.jl", "max_stars_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/programs/SROSENBR.jl", "max_issues_repo_name": "danphenderson/UncNLPrograms.jl", "max_issues_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/programs/SROSENBR.jl", "max_forks_repo_name": "danphenderson/UncNLPrograms.jl", "max_forks_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6206896552, "max_line_length": 75, "alphanum_fraction": 0.5390749601, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7686384365489792}}
{"text": "using FractionalDiffEq, Plots, LinearAlgebra\n\nh = 1e-2; tspan = (0, 30)\nrightfun(x, y) = 172/125*cos(4/5*x)\nmultitermprob = MultiTermsFODEProblem([1, 1/16, 4/5, 3/2, 1/25, 6/5], [3, 2.5, 2, 1, 0.5, 0], rightfun, [1, 4/5, -16/25, 0, 0, 0], tspan)\n\nrealfun(x)=sqrt(2)*sin(4*x/5+π/4)\nsol1 = solve(multitermprob, h, PIEX())\nsol2 = solve(multitermprob, h, PIIMRect())\nsol3 = solve(multitermprob, h, PIIMTrap())\nsol4 = solve(multitermprob, h, PIPECE())\n#=\nplot(sol1)\nplot!(sol2)\nplot!(sol3)\nplot!(sol4)\n=#\n#plot!(collect(0:0.01:30), realfun.(collect(0:0.01:30)))\n\nrealsol = realfun.(collect(0:h:30))\nerr1 = norm(sol1.u-realsol)\nerr2 = norm(sol2.u-realsol)\nerr3 = norm(sol3.u-realsol)\nerr4 = norm(sol4.u-realsol)", "meta": {"hexsha": "f4c72637108d6ba8ac3b095f3f958ede0960f87f", "size": 705, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmarks/fode/multitermsfode.jl", "max_stars_repo_name": "SciFracX/FractionalDiffEq.jl", "max_stars_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-11-05T12:49:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:57:20.000Z", "max_issues_repo_path": "benchmarks/fode/multitermsfode.jl", "max_issues_repo_name": "SciFracX/FractionalDiffEq.jl", "max_issues_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-11-01T22:05:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:57:19.000Z", "max_forks_repo_path": "benchmarks/fode/multitermsfode.jl", "max_forks_repo_name": "SciFracX/FractionalDiffEq.jl", "max_forks_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.375, "max_line_length": 137, "alphanum_fraction": 0.6581560284, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182847, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7685458042105998}}
{"text": "#=\n# Euclidean Distance Matrix Completion\nThis example illustrates how to use Chordal.jl to complete a partially-specified\nEuclidean Distance Matrix (or determine no such completion exists).\n=#\n\n#=\n## Euclidean Distance Matrices\nGiven $N$ vectors $x_1,\\dots,x_n$ in $\\mathbb{R}^n$, the associated Euclidean\nDistance Matrix (EDM) $D \\in \\mathbb{R}^{N \\times N}$ records the squared distance\nbetween each pair $x_i, x_j$. Specifically,\n$$\nD_{ij} = \\|x_i - x_j\\|_2^2.\n$$\n\nGiven a partially-specified EDM $D$ which has a chordal sparsity pattern, we would\nlike to find the missing entries.\n=#\n\nusing Chordal\nusing LinearAlgebra, SparseArrays\n\n\n#=\n## Small Example\nThis small example is taken from Jon Dattorro's [Convex Optimization & Euclidean Distance Geometry](https://ccrma.stanford.edu/~dattorro/EDM.pdf)\neq (1041). First, we construct the partially-specified EDM.\n=#\nD = sparse([\n    0.0 1 5 0;\n    1 0 4 1;\n    5 4 0 1;\n    0 1 1 0\n])\n@show D\n\n## Next, we complete the matrix\nD_complete = sparse(edm_completion(D))\nprintln(\"\\nCompletion:\")\n@show D_complete\n\n\n#=\n## Larger Random Example\n\nFirst, we generate an EDM from 17 vectors in $\\mathbb{R}^3}$.\n=#\nn = 17\nr = 3\nV = randn(n, r)\nVV = V*V'\nD_full = diag(VV)*ones(n)' + ones(n)*diag(VV)' - 2VV;\n\n#=\nNext, we remove entries. and complete the\nThe sparsity pattern is from Figure 4.2 in Lieven Vandenberghe and Martin S. Andersen's\n[Chordal Graphs and Semidefinite Optimization](https://www.seas.ucla.edu/~vandenbe/publications/chordalsdp.pdf).\n=#\nijs = [(3,1), (3,2), (4,1), (4,2), (4,3), (5,1), (5,3), (5,4), (8,7),\n       (9,5), (9,6), (9,7), (9,8), (11,10), (13,10), (13,11), (13,12),\n       (14,10), (14,11), (14,12), (14,13),\n       (15, 1), (15,3), (15,4), (15,5), (15,7), (15,8), (15,9),\n       (16,5), (16,6), (16,9), (16,12), (16,13), (16,14), (16,15),\n       (17,10), (17,11), (17,12), (17,13), (17,14), (17,15), (17,16)]\nappend!(ijs, [(i,i) for i in 1:n])\nII, JJ = Chordal.unzip(ijs)\nsp = sparse(II, JJ, ones(length(II)))\nsp = sp + tril(sp)'\n\n## Remove entries s.t. the remaining entries have a chordal sparsity pattern\nD = sp .* D_full\n\n## Complete the matrix\n@show Chordal.is_edm(edm_completion(D))\n", "meta": {"hexsha": "c073bc67470c81ea73c767e0c82f3cb0c56d74dc", "size": 2164, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/edm.jl", "max_stars_repo_name": "tjdiamandis/Chordal.jl", "max_stars_repo_head_hexsha": "0a2b8764931f07219626eaa4ec8bd87df05e0d25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T23:04:03.000Z", "max_issues_repo_path": "examples/edm.jl", "max_issues_repo_name": "tjdiamandis/ChordalDecomp.jl", "max_issues_repo_head_hexsha": "0a2b8764931f07219626eaa4ec8bd87df05e0d25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-28T02:19:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T17:59:42.000Z", "max_forks_repo_path": "examples/edm.jl", "max_forks_repo_name": "tjdiamandis/ChordalDecomp.jl", "max_forks_repo_head_hexsha": "0a2b8764931f07219626eaa4ec8bd87df05e0d25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8533333333, "max_line_length": 145, "alphanum_fraction": 0.6464879852, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660949832346, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7685457866374118}}
{"text": "#=\nCompute the fixed point of a given operator T, starting from\nspecified initial condition v.\n\n@author : Spencer Lyon <spencer.lyon@nyu.edu>\n\n@date: 2014-07-05\n\nReferences\n----------\n\nhttps://lectures.quantecon.org/jl/optgrowth.html\n=#\n\n\ndoc\"\"\"\nRepeatedly apply a function to search for a fixed point\n\nApproximates ``T^∞ v``, where ``T`` is an operator (function) and ``v`` is an initial\nguess for the fixed point. Will terminate either when `T^{k+1}(v) - T^k v <\nerr_tol` or `max_iter` iterations has been exceeded.\n\nProvided that ``T`` is a contraction mapping or similar,  the return value will\nbe an approximation to the fixed point of ``T``.\n\n##### Arguments\n\n* `T`: A function representing the operator ``T``\n* `v::TV`: The initial condition. An object of type ``TV``\n* `;err_tol(1e-3)`: Stopping tolerance for iterations\n* `;max_iter(50)`: Maximum number of iterations\n* `;verbose(2)`: Level of feedback (0 for no output, 1 for warnings only, 2\n        for warning and convergence messages during iteration)\n* `;print_skip(10)` : if `verbose == 2`, how many iterations to apply between\n        print messages\n\n##### Returns\n---\n\n* '::TV': The fixed point of the operator ``T``. Has type ``TV``\n\n##### Example\n\n```julia\nusing QuantEcon\nT(x, μ) = 4.0 * μ * x * (1.0 - x)\nx_star = compute_fixed_point(x->T(x, 0.3), 0.4)  # (4μ - 1)/(4μ)\n```\n\n\"\"\"\nfunction compute_fixed_point(T::Function, \n                            v::TV; \n                            err_tol=1e-4,\n                            max_iter=100, \n                            verbose=2, \n                            print_skip=10) where TV\n\n    if !(verbose in (0, 1, 2))\n        throw(ArgumentError(\"verbose should be 0, 1 or 2\"))\n    end\n\n    iterate = 0\n    err = err_tol + 1\n    while iterate < max_iter && err > err_tol\n        new_v = T(v)::TV\n        iterate += 1\n        err = Base.maximum(abs, new_v - v)\n        if verbose == 2\n            if iterate % print_skip == 0\n                println(\"Compute iterate $iterate with error $err\")\n            end\n        end\n        v = new_v\n    end\n\n    if verbose >= 1\n        if err > err_tol\n            warn(\"max_iter attained in compute_fixed_point\")\n        elseif verbose == 2\n            println(\"Converged in $iterate steps\")\n        end\n    end\n\n    return v\nend\n", "meta": {"hexsha": "d69fd1061d48ea3fd2701a3743d1340b8a62858e", "size": 2292, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/compute_fp.jl", "max_stars_repo_name": "a-parida12/QuantEcon.jl", "max_stars_repo_head_hexsha": "fc256e1565c457247560255c473cdfaab39e0011", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-27T14:34:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-27T14:34:24.000Z", "max_issues_repo_path": "src/compute_fp.jl", "max_issues_repo_name": "a-parida12/QuantEcon.jl", "max_issues_repo_head_hexsha": "fc256e1565c457247560255c473cdfaab39e0011", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/compute_fp.jl", "max_forks_repo_name": "a-parida12/QuantEcon.jl", "max_forks_repo_head_hexsha": "fc256e1565c457247560255c473cdfaab39e0011", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-25T15:19:11.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-25T15:19:11.000Z", "avg_line_length": 26.6511627907, "max_line_length": 85, "alphanum_fraction": 0.5855148342, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.8757870029950159, "lm_q1q2_score": 0.7684827631003193}}
{"text": "# # Five dim sys\n\n# ## Model\n\nmodule five_dim_sys #jl\n\nusing ReachabilityAnalysis\n\n## system matrix\nD = [-1.0 -4.0  0.0  0.0  0.0;\n      4.0 -1.0  0.0  0.0  0.0;\n      0.0  0.0 -3.0  1.0  0.0;\n      0.0  0.0 -1.0 -3.0  0.0;\n      0.0  0.0  0.0  0.0 -2.0]\nP = [ 0.6 -0.1  0.1  0.7 -0.2;\n     -0.5  0.7 -0.1 -0.8  0.0;\n      0.9 -0.5  0.3 -0.6  0.1;\n      0.5 -0.7  0.5  0.6  0.3;\n      0.8  0.7  0.6 -0.3  0.2]\nA = P * D * inv(P)\n\n## state domain\nX = Universe(5)\n\n## input domain\nU = Ball2(zeros(5), 0.01)\n\nfunction model(X0)\n    S = @system(x' = Ax + u, x ∈ X, u ∈ U)\n    return IVP(S, X0)\nend\n\nend #jl\n\n# ## References\n", "meta": {"hexsha": "6aaacc238804fb07ace09a8caabee7d2a445e071", "size": 620, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/five_dim_sys/five_dim_sys.jl", "max_stars_repo_name": "mforets/ReachabilityLibrary", "max_stars_repo_head_hexsha": "4beac279a071debb0765e415e583d4ab906db762", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-08-16T13:18:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T19:26:31.000Z", "max_issues_repo_path": "src/models/five_dim_sys/five_dim_sys.jl", "max_issues_repo_name": "mforets/ReachabilityLibrary", "max_issues_repo_head_hexsha": "4beac279a071debb0765e415e583d4ab906db762", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44, "max_issues_repo_issues_event_min_datetime": "2020-04-10T15:04:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-27T08:01:45.000Z", "max_forks_repo_path": "src/models/five_dim_sys/five_dim_sys.jl", "max_forks_repo_name": "mforets/ReachabilityLibrary", "max_forks_repo_head_hexsha": "4beac279a071debb0765e415e583d4ab906db762", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.2222222222, "max_line_length": 42, "alphanum_fraction": 0.464516129, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620596782468, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7684738050995122}}
{"text": "export problem2\n\n\"\"\"\n  problem2(N=4e6)\n\n# Problem 2\n## Even Fibonacci numbers\n\nBy considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.\n\"\"\"\nfunction problem2(N=4e6)\n  n = 0\n  f = 0\n  s = 0\n\n  while f < N\n    n += 3\n    s += f\n    f = fib(n)\n  end\n  return s\nend\n\nfunction fib(n::Int)\n  n < 0 && return 0\n  n < 2 && return n\n  a = 1\n  b = 0\n  c = 0\n\n  while n > 2\n    n -= 1\n    c = a\n    a += b\n    b = c\n  end\n\n  return a+b\nend\n", "meta": {"hexsha": "3e3b12e3d592a48910ece3fcb1ea85cdd5b5d948", "size": 503, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problem2.jl", "max_stars_repo_name": "halleysfifthinc/ProjectEuler", "max_stars_repo_head_hexsha": "7134939e154bf52eb48f93f7da664bc50784b2f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problem2.jl", "max_issues_repo_name": "halleysfifthinc/ProjectEuler", "max_issues_repo_head_hexsha": "7134939e154bf52eb48f93f7da664bc50784b2f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problem2.jl", "max_forks_repo_name": "halleysfifthinc/ProjectEuler", "max_forks_repo_head_hexsha": "7134939e154bf52eb48f93f7da664bc50784b2f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.575, "max_line_length": 130, "alphanum_fraction": 0.5626242545, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9481545392102523, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7684592583601315}}
{"text": "function calc_phi(x::Array{Float64,2},xi::Array{Float64,2},n::Int64,nn::Int64,c::Float64,vars::Int64)\r\n  phi=zeros(nn,n)\r\n  for i=1:nn\r\n      for j=1:n\r\n          # 2 r^4\r\n          dr=0\r\n          for k=1:vars\r\n            dr = dr + (xi[i,k] - x[j,k])^2\r\n          end\r\n          # r = (dr)\r\n          # phi[i,j] = -(dr^4)/4/c\r\n\r\n\r\n          # 1 Gaussian\r\n          # phi[i,j] = exp(-sum((xi[i,:] - x[j,:]).^2)/c)\r\n          phi[i,j] = exp(-dr/c)\r\n      end\r\n      # if i in 1:100:nn println(Dates.format(now(), \"HH:MM:SS \"),i,\" of \",nn) end\r\n  end\r\n\r\n\r\n  # xi_all=Array{Float64,3}(undef, nn,1,vars)\r\n  # xi_all[:,1,:]=xi\r\n  # # println(size(xi_all))\r\n  # xi_all=repeat(xi_all,1,n,1)\r\n  # # println(size(xi_all))\r\n\r\n  # x_all=Array{Float64,3}(undef, n,1,vars)\r\n  # x_all[:,1,:]=x\r\n  # # println(size(x_all))\r\n  # x_all=repeat(x_all,1,nn,1)\r\n  # # println(size(x_all))\r\n  # x_all = permutedims(x_all, [2, 1, 3])\r\n  # # println(size(x_all))\r\n\r\n\r\n  # # @time m1=sum((xi_all - x_all).^2,dims=3)\r\n  # # # println(size(m1))\r\n  # phi2=exp.(-sum((xi_all - x_all).^2,dims=3)/c)[:,:,1]\r\n  # # println(size(phi2))\r\n  # # println(mean(abs.(phi-phi2)))\r\n\r\n\r\n  return phi\r\nend\r\n\r\n\r\n\r\n# phi[i,j] = exp(-sqrt(dr)/c)\r\n# phi[i,j] = exp(-r^2)/2 + (r*pi^(1/2)*erf(r))/2;\r\n# phi[i,j] = 2*(1./(1+exp.(-r)))-1;\r\n# phi[i,j] = exp(-r^2/c[i,j])\r\n# phi[i,j] = exp(-dr/c)\r\n# phi[i,j]=tanh.(r^2/c[i,j])\r\n# phi[i,j] = -(r^3)/3\r\n# phi[i,j] = exp(-r/c)\r\n# phi[i,j] =(c^2*exp(-r/c^2))/2 + (c*sqrt(pi)*erf(sqrt(r)/c)*sqrt(r))/2;\r\n# phi[i,j] = -sum((xi[i,:] - x[j,:]).^2)\r\n", "meta": {"hexsha": "3e6bc2576c1674dc350fecad769c8da4a478c280", "size": 1539, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/calc_phi.jl", "max_stars_repo_name": "nbakas/ANNBN.jl", "max_stars_repo_head_hexsha": "17784adbb0fd672c6849f3c377318dfcef607e71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-10-03T09:55:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T15:08:35.000Z", "max_issues_repo_path": "src/calc_phi.jl", "max_issues_repo_name": "nbakas/ANNBN.jl", "max_issues_repo_head_hexsha": "17784adbb0fd672c6849f3c377318dfcef607e71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/calc_phi.jl", "max_forks_repo_name": "nbakas/ANNBN.jl", "max_forks_repo_head_hexsha": "17784adbb0fd672c6849f3c377318dfcef607e71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-01T06:06:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-01T06:06:01.000Z", "avg_line_length": 26.0847457627, "max_line_length": 102, "alphanum_fraction": 0.4717348928, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.768459250253147}}
{"text": "function minimize_molzahn(cliques::AbstractVector, cliquetree::AbstractVector)\n    deltas = [molzahn_heuristic(cliques, edge) for edge in cliquetree]\n    index = argmin(deltas)\n    return cliquetree[index]\nend\n\n\nfunction molzahn_heuristic(cliques::AbstractVector, edge)\n    size_intersect = length(intersect(cliques[edge[1]], cliques[edge[2]]))\n    size_clique1 = length(cliques[edge[1]])\n    size_clique2 = length(cliques[edge[2]])\n    size_fusion = size_clique1 + size_clique2 - size_intersect\n    delta = size_fusion * (2 * size_fusion + 1) -\n            size_clique1 * (2 * size_clique1 + 1) -\n            size_clique2 * (2 * size_clique2 + 1) -\n            size_intersect * (2 * size_intersect + 1)\n    return delta\nend\n\n\nfunction select(cliques::AbstractVector, cliquetree::AbstractVector;\n                selection=minimize_molzahn)\n    return selection(cliques, cliquetree)\nend\n\n\nfunction merge_molzahn(cliques::AbstractVector, cliquetree::AbstractVector;\n                       treshold::Union{Int,Function}=treshold_percent(cliques, 0.1),\n                       selection::Function=minimize_molzahn, kwargs...)\n    edges = Set()\n    if typeof(treshold) <: Int\n        treshold_value = treshold\n        treshold = (x;kwargs...) -> length(x) >= treshold_value\n    end\n    while treshold(cliques; kwargs...)\n        edge = selection(cliques, cliquetree)\n        edges = vcat(edges..., get_added_edges(cliques[edge[1]], cliques[edge[2]])...)\n        cliques, cliquetree = merge_cliques(cliques, cliquetree, edge)\n    end\n    return cliques, cliquetree, edges\nend\n", "meta": {"hexsha": "de668f50787ea820e500ac6856009eaf59793b59", "size": 1569, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Generate/Merge/molzahn.jl", "max_stars_repo_name": "charlyalizadeh/OPFdecgen", "max_stars_repo_head_hexsha": "072216066de28dfb6b59340c9fa279cc33882139", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Generate/Merge/molzahn.jl", "max_issues_repo_name": "charlyalizadeh/OPFdecgen", "max_issues_repo_head_hexsha": "072216066de28dfb6b59340c9fa279cc33882139", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Generate/Merge/molzahn.jl", "max_forks_repo_name": "charlyalizadeh/OPFdecgen", "max_forks_repo_head_hexsha": "072216066de28dfb6b59340c9fa279cc33882139", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3571428571, "max_line_length": 86, "alphanum_fraction": 0.6724028043, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.7684592403850138}}
{"text": "# SVD Algorithms\n# --------------\n\n# Truncated SVD using implicitly restarted Lonczos iterations.\nfunction tsvd(A::Matrix{T}, k::Integer) where T\n    m, n = size(A)\n    F, = svds(A, nsv=k)\n    U, Σ, V = F.U, F.S, F.V\n    @assert size(U, 2) == length(Σ) == size(V, 2) == k\n    return U, Σ, V\nend\n\n# H. Li, G. C. Linderman, et al. \"Algorithm 971: An Implementation of a\n# Randomized Algorithm for Principal Component Analysis\", ACM Transactions on\n# Mathematical Software (TOMS), 2017\n# DOI: https://doi.org/10.1145/3004053\nfunction rsvd(A::Matrix{T}, k::Integer; its=3, l=k+5) where T\n    m, n = size(A)\n    l = min(l, m, n)\n    @assert 0 < k ≤ l ≤ min(m, n)\n    Q::Matrix{T} = rand(eltype(T), n, l) .- T(0.5)\n    Y = A*Q\n    F = lu!(Y)\n    for i in 1:its\n        Y = A'F.L\n        F = lu!(Y)\n        Y = A*F.L\n        if i < its\n            F = lu!(Y)\n        else\n            F = qr!(Y)\n        end\n    end\n    Q = Matrix(F.Q)\n    B = Q'A\n    W, Σ, V = svd(B)\n    U = Q*W\n    return U[:,1:k], Σ[1:k], V[:,1:k]\nend\n", "meta": {"hexsha": "ed6e8081ca8b20fb2fbadf6560b5ed7f269329ef", "size": 1015, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/svd.jl", "max_stars_repo_name": "bicycle1885/CellFishing.jl", "max_stars_repo_head_hexsha": "fd9e437631ec9c6f924c69f9cee15ee58d284206", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2018-07-26T02:14:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-19T11:57:27.000Z", "max_issues_repo_path": "src/svd.jl", "max_issues_repo_name": "cyxss/CellFishing.jl", "max_issues_repo_head_hexsha": "de2a306f80f6ba1bea90cda7b231e20d83681dc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-08-20T06:28:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T21:16:33.000Z", "max_forks_repo_path": "src/svd.jl", "max_forks_repo_name": "cyxss/CellFishing.jl", "max_forks_repo_head_hexsha": "de2a306f80f6ba1bea90cda7b231e20d83681dc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-08-14T12:28:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T19:07:30.000Z", "avg_line_length": 25.375, "max_line_length": 77, "alphanum_fraction": 0.5113300493, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091157, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7684491639385619}}
{"text": "export joLagrangeInterp1D\n\n# 1D Cubic Lagrange Interpolation\n#\n# Parameters:\n#   xin  - input grid\n#   xout - output grid\n#   T    - vector data type\n#\n# Note: the interval [minimum(xout),maximum(xout)] must be contained\n# in the interval [minimum(xin),maximum(xin)]\n\nfunction joLagrangeInterp1D(xin,xout,T)\n    ik = find((xout .>= xin[1]) .& (xout .<= xin[end]))\n    nout = length(xout)\n    nin = length(xin)\n    nk = length(ik)\n    nk > 0 || error(\"The set generated by xout must be contained within the interval [xin[1],xin[end]]\")\n    I = zeros(Int64,4*nk)\n    J = zeros(Int64,4*nk)\n    S = zeros(T,4*nk)\n    a,b,c,d = 1,2,3,4\n    l=1\n    for i = 1:nk        \n        k = ik[i];\n        if xout[k]<xin[b]\n            while (xout[k]<xin[b])&&(b-1>1)\n                b=b-1;\n            end\n            a=b-1;c=b+1;d=c+1;\n        elseif xout[k]>xin[c]\n            while (xout[k]>xin[c])&&(c+1<nin)\n                c=c+1;\n            end\n            a=c-2;b=c-1;d=c+1;\n        end\n        I[l:l+3] = k;\n        J[l]   = a;\n        S[l]   = ((xout[k]-xin[b])*(xout[k]-xin[c])*(xout[k]-xin[d]))/((xin[a]-xin[b])*(xin[a]-xin[c])*(xin[a]-xin[d]));\n\n        J[l+1] = b;\n        S[l+1] = ((xout[k]-xin[a])*(xout[k]-xin[c])*(xout[k]-xin[d]))/((xin[b]-xin[a])*(xin[b]-xin[c])*(xin[b]-xin[d]));\n\n        J[l+2] = c;\n        S[l+2] = ((xout[k]-xin[b])*(xout[k]-xin[a])*(xout[k]-xin[d]))/((xin[c]-xin[b])*(xin[c]-xin[a])*(xin[c]-xin[d]));\n\n        J[l+3] = d;\n        S[l+3] = ((xout[k]-xin[b])*(xout[k]-xin[c])*(xout[k]-xin[a]))/((xin[d]-xin[b])*(xin[d]-xin[c])*(xin[d]-xin[a]));\n        \n        l += 4;\n    end\n\n    return joMatrix(sparse(I[1:l-1],J[1:l-1],S[1:l-1],nout,nin),DDT=T,name=\"joLagrangeInterp1D\")\nend\n", "meta": {"hexsha": "8b6523823624734e14699abe00292de0988811d1", "size": 1705, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Operators/jo_lagrange_interp_1d.jl", "max_stars_repo_name": "slimgroup/WAVEFORM.jl", "max_stars_repo_head_hexsha": "7748a91baadabf7e9a0ea57276cd8e60413980d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2017-05-17T19:08:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T17:08:41.000Z", "max_issues_repo_path": "src/Operators/jo_lagrange_interp_1d.jl", "max_issues_repo_name": "slimgroup/WAVEFORM.jl", "max_issues_repo_head_hexsha": "7748a91baadabf7e9a0ea57276cd8e60413980d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-01T22:32:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-30T19:28:37.000Z", "max_forks_repo_path": "src/Operators/jo_lagrange_interp_1d.jl", "max_forks_repo_name": "slimgroup/WAVEFORM.jl", "max_forks_repo_head_hexsha": "7748a91baadabf7e9a0ea57276cd8e60413980d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-30T10:51:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T17:08:45.000Z", "avg_line_length": 31.0, "max_line_length": 120, "alphanum_fraction": 0.4780058651, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7684491598103259}}
{"text": "# Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten\n# pentagonal numbers are:\n# \n# 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...\n# \n# It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference,\n# 70 − 22 = 48, is not pentagonal.\n# \n# Find the pair of pentagonal numbers, Pj and Pk, for which their sum and\n# difference are pentagonal and D = |Pk − Pj| is minimised; what is the value\n# of D?\n\nusing ProjectEulerSolutions\n\n# Calculate pentagonal numbers, store in set, then check for whether\n# differences and additions are also in the set.  Could probably be faster if\n# searchsorted was used and the minimum bound for j was a function of i.\nfunction p044solution(n::Integer=10)::Integer\n\n    vals = collect(1:n)\n    pentagonals = fld.(vals .* (3 .* vals .- 1), 2)\n    pentagonalset = Set(pentagonals)\n\n    for i in 4:n\n        for j in 3:(i-1)\n            if pentagonals[i] - pentagonals[j] in pentagonalset && pentagonals[i] + pentagonals[j] in pentagonalset\n                return pentagonals[i] -  pentagonals[j]\n            end\n        end\n    end\n\n    return -1\nend\n\np044 = Problems.Problem(p044solution)\n\nProblems.benchmark(p044, 3000)", "meta": {"hexsha": "0c3f0e6b76258bf16d0cdd910cc6e0ce71c09ad5", "size": 1183, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/044.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/044.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/044.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.972972973, "max_line_length": 115, "alphanum_fraction": 0.6644125106, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104868, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7684128809688053}}
{"text": "function rsaencode(clearmsg::AbstractString, nmod::Integer, expub::Integer)\n    bytes = parse(BigInt, \"0x\" * bytes2hex(collect(UInt8, clearmsg)))\n    return powermod(bytes, expub, nmod)\nend\n\nfunction rsadecode(cryptmsg::Integer, nmod::Integer, dsecr::Integer)\n    decoded = powermod(encoded, dsecr, nmod)\n    return join(Char.(hex2bytes(hex(decoded))))\nend\n\nmsg = \"Rosetta Code.\"\nnmod = big\"9516311845790656153499716760847001433441357\"\nexpub = 65537\ndsecr = big\"5617843187844953170308463622230283376298685\"\n\nencoded = rsaencode(msg, nmod, expub)\ndecoded = rsadecode(encoded, nmod, dsecr)\nprintln(\"\\n# $msg\\n -> ENCODED: $encoded\\n -> DECODED: $decoded\")\n", "meta": {"hexsha": "aff7f460cf015166ce9224924583e5d6916af53a", "size": 654, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/rsa-code.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/rsa-code.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/rsa-code.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4210526316, "max_line_length": 75, "alphanum_fraction": 0.74617737, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561685659696, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7684055860242127}}
{"text": "export Toeplitz, embed\n\"\"\"\n[`Toeplitz` matrix](http://en.wikipedia.org/wiki/Toeplitz_matrix)\n\nInput is a vector of odd length.\n\n```julia\njulia> Toeplitz(collect(-4:4))\n5x5 Toeplitz{Int64}:\n 0  -1  -2  -3  -4\n 1   0  -1  -2  -3\n 2   1   0  -1  -2\n 3   2   1   0  -1\n 4   3   2   1   0\n```\n\"\"\"\nstruct Toeplitz{T} <: AbstractArray{T, 2}\n\tc :: Vector{T}\nend\n\ngetindex(T::Toeplitz, i::Int, j::Int) = T.c[i-j+div(length(T.c)+1,2)]\nisassigned(T::Toeplitz, i::Int, j::Int) = isassigned(T.c,i-j+div(length(T.c)+1,2))\n\nsize(T::Toeplitz, r::Int) = (r==1 || r==2) ? 1 + div(length(T.c),2) :\n    throw(ArgumentError(\"Invalid dimension $r\"))\nsize(T::Toeplitz) = size(T,1), size(T,2)\n\n# Fast matrix x vector multiplication via embedding Toeplitz() into Circulant()\nfunction *(A::Toeplitz{T},x::Vector{T}) where T\n    n=length(A.c)\n    k=div(n+1,2)\n    C=Circulant([A.c[k:n];A.c[1:k-1]])\n    (C*[x;zeros(T,k-1)])[1:k]\nend\n\nfunction mul!(y::StridedVector{T},A::Toeplitz{T},x::StridedVector{T}) where T\n    n=length(A.c)\n    k=div(n+1,2)\n    C=Circulant([A.c[k:n];A.c[1:k-1]])\n    xx=[x;zeros(T,k-1)]\n    yy=mul!(similar(xx),C,xx)\n    copyto!(y, 1, yy, 1, length(y))\n    return y\nend\n\nfunction Matrix(To::Toeplitz{T}) where T\n\tn=size(To, 1)\n\tM=Array{T}(undef,n,n)\n\tfor i=1:n\n\t\tM[i:n,i] = To.c[n:2n-i]\n\t\tM[1:i-1,i] = To.c[n-i+1:n-1]\n\tend\n\tM\nend\n\nfunction embed(To::Toeplitz{T}) where T\n    return Circulant([To.c[div(end+1,2):end];To.c[1:div(end-1,2)]])\nend\n", "meta": {"hexsha": "0ecfb4331e2b642690da50a737d600bd2091b00c", "size": 1439, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/toeplitz.jl", "max_stars_repo_name": "devmotion/SpecialMatrices.jl", "max_stars_repo_head_hexsha": "c1d004da20e638cbc1e146dafaaffc978d7ba805", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/toeplitz.jl", "max_issues_repo_name": "devmotion/SpecialMatrices.jl", "max_issues_repo_head_hexsha": "c1d004da20e638cbc1e146dafaaffc978d7ba805", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/toeplitz.jl", "max_forks_repo_name": "devmotion/SpecialMatrices.jl", "max_forks_repo_head_hexsha": "c1d004da20e638cbc1e146dafaaffc978d7ba805", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3898305085, "max_line_length": 82, "alphanum_fraction": 0.5920778318, "num_tokens": 604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.768393857650791}}
{"text": "# In this example, we create piece-wise linear functions that has a single line segment that has a small slope. The interpretation of using such a function as a transport map is to move mass from a large coverage to a concentrated coverage. The intervals in the domain and range that correspond to this segment is the *focus interval*, and is controlled by `range_percentage` and `domain_percentage`. We then fit a logistic-logit function to each of the piece-wise linear functions. The fitted parameters can then be interpolated so that we get a logistic-logit function for any given focus interval.\n\ninclude(\"../src/MonotoneMaps.jl\")\nimport .MonotoneMaps\n#import MonotoneMaps\n\nimport PyPlot # works better in REPL.\n\n#using Plots; pyplot() # easier to work with in .jmd / Weave.jl.\n\nimport Random\nusing LinearAlgebra\n\n\nPyPlot.close(\"all\")\nfig_num = 1\n\nPyPlot.matplotlib[\"rcParams\"][:update]([\"font.size\" => 22, \"font.family\" => \"serif\"])\n\nRandom.seed!(25)\n\n# Get the set of piece-wise linear functions.\np_lb = 0.0\np_ub = 1.0\nrange_percentage = 0.1\nN_itp_samples = 10\ndomain_percentage = 0.7\ninfos, zs, p_range = MonotoneMaps.getendomorphismpiecewiselinear(p_lb, p_ub, range_percentage; N_itp_samples = N_itp_samples, domain_percentage = domain_percentage)\n\n# construct the set of piece-wise functions.\nfs = collect( xx->MonotoneMaps.evalpiecewise2Dlinearfunc(xx, infos[i]) for i = 1:length(infos) )\n\n# visualize.\ndisplay_t = LinRange(0.0, 1.0, 5000)\n\nPyPlot.figure(fig_num)\nfig_num += 1\n\nfor i = length(fs):length(fs)\n    PyPlot.plot(display_t, fs[i].(display_t), label = \"f[$(i)]\")\nend\n\nPyPlot.legend()\nPyPlot.xlabel(\"x\")\nPyPlot.ylabel(\"y\")\nPyPlot.title(\"Piece-wise linear functions, each with a single focus subinterval\")\n\n# display_mat = [ fs[c](display_t[r]) for r = 1:length(display_t), c = 1:length(fs) ]\n# display_labels = [\"$(i)-th function\" for j = 1:1, i = 1:length(fs)]\n#\n# default(titlefont = (20, \"times\"), legendfontsize = 15, guidefont = (18, :black),\n# tickfont = (12, :black))\n#\n# plot_handle = plot(display_t, display_mat,\n# label = display_labels,\n# title = \"Piece-wise linear functions, each with a single focus subinterval\",\n# xlabel = \"x\",\n# ylabel = \"y\",\n# linewidth = 2, legend = :outerright, aspect_ratio=:equal, size = (800,800))\n# display(plot_handle)\n\n\n# fit the compact sigmoids (composite function of applying probit then logistic functions).\np0 = [0.5; 0.0]\np_lb = [0.1; -5.0]\np_ub = [0.6; 5.0]\noptim_algorithm = :LN_BOBYQA # a local derivative-free algorithm. For other algorithms in NLopt, see https://nlopt.readthedocs.io/en/latest/NLopt_Algorithms/\ncostfuncs, minxs, rets = MonotoneMaps.getcompactsigmoidparameters(infos; p0 = p0, p_lb = p_lb, p_ub = p_ub, optim_algorithm = optim_algorithm)\nqs = collect( tt->MonotoneMaps.evalcompositelogisticprobit(tt, minxs[i][1], minxs[i][2]) for i = 1:length(minxs) )\n\n\n## visualize oracle vs. fitted sigmoids.\nPyPlot.figure(fig_num)\nfig_num += 1\n\nfor l = 1:length(qs)\n    PyPlot.plot(display_t, fs[l].(display_t), label = \"f[$(l)]\")\n    PyPlot.plot(display_t, qs[l].(display_t), \"--\", label = \"q[$(l)]\")\nend\n\nPyPlot.legend()\nPyPlot.xlabel(\"x\")\nPyPlot.ylabel(\"\")\nPyPlot.title(\"target vs fit\")\n\n# display_mat = [ fs[c](display_t[r]) for r = 1:length(display_t), c = 1:length(fs) ]\n# display_labels = [\"$(i)-th piece-wise linear\" for j = 1:1, i = 1:length(fs)]\n#\n# display_mat2 = [ qs[c](display_t[r]) for r = 1:length(display_t), c = 1:length(fs) ]\n# display_labels2 = [\"$(i)-th logistic-logit\" for j = 1:1, i = 1:length(qs)]\n#\n# plot_handle2 = plot(display_t, display_mat,\n# label = display_labels,\n# title = \"Piece-wise linear and logistic-logit functions\",\n# xlabel = \"x\",\n# ylabel = \"y\",\n# linewidth = 2, legend = :outerright, aspect_ratio=:equal, size = (800,800))\n#\n# plot!(display_t, display_mat2,\n# label = display_labels2,\n# style = :dash)\n#\n# display(plot_handle2)\n\n# print fit cost.\nfor l = 1:length(costfuncs)\n    println(\"cost of p_star $(l) is \", costfuncs[l](minxs[l]))\nend\n", "meta": {"hexsha": "1de0c55022f8a83f63c425c52a366a0189f031ce", "size": 3963, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/logistic-logit_fit.jl", "max_stars_repo_name": "RoyCCWang/MonotoneMaps.jl", "max_stars_repo_head_hexsha": "dbb247170a0d3a7e0ba58a3cd102243c1bbc5eb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/logistic-logit_fit.jl", "max_issues_repo_name": "RoyCCWang/MonotoneMaps.jl", "max_issues_repo_head_hexsha": "dbb247170a0d3a7e0ba58a3cd102243c1bbc5eb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/logistic-logit_fit.jl", "max_forks_repo_name": "RoyCCWang/MonotoneMaps.jl", "max_forks_repo_head_hexsha": "dbb247170a0d3a7e0ba58a3cd102243c1bbc5eb1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3577981651, "max_line_length": 600, "alphanum_fraction": 0.7110774666, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.768393857099917}}
{"text": "# Parts of this code were taken / derived from Graphs.jl. See LICENSE for\n# licensing details.\n\n\n\"\"\"\n    struct FloydWarshallState{T, U}\n\nAn [`AbstractPathState`](@ref) designed for Floyd-Warshall shortest-paths calculations.\n\"\"\"\nstruct FloydWarshallState{T,U<:Integer} <: AbstractPathState\n    dists::Matrix{T}\n    parents::Matrix{U}\nend\n\n@doc_str \"\"\"\nfloyd_warshall_shortest_paths(g, distmx=weights(g))\nUse the [Floyd-Warshall algorithm](http://en.wikipedia.org/wiki/Floyd–Warshall_algorithm)\nto compute the shortest paths between all pairs of vertices in graph `g` using an\noptional distance matrix `distmx`. Return a [`FloydWarshallState`](@ref) with relevant\ntraversal information.\n\n### Performance\nSpace complexity is on the order of ``\\\\mathcal{O}(|V|^2)``.\n\"\"\"\nfunction floyd_warshall_shortest_paths(\n    g::AbstractGraph,\n    distmx::AbstractMatrix{T} = weights(g)\n) where T\n    U = eltype(g)\n    n_v = nv(g)\n    dists = fill(typemax(T), (Int(n_v), Int(n_v)))\n    parents = zeros(U, (Int(n_v), Int(n_v)))\n\n    # fws = FloydWarshallState(Matrix{T}(), Matrix{Int}())\n    for v in 1:n_v\n        dists[v, v] = zero(T)\n    end\n    undirected = !is_directed(g)\n    for e in edges(g)\n        u = src(e)\n        v = dst(e)\n\n        d = distmx[u, v]\n\n        dists[u, v] = min(d, dists[u, v])\n        parents[u, v] = u\n        if undirected\n            dists[v, u] = min(d, dists[v, u])\n            parents[v, u] = v\n        end\n    end\n    for w in vertices(g), u in vertices(g), v in vertices(g)\n        if dists[u, w] == typemax(T) || dists[w, v] == typemax(T)\n            ans = typemax(T)\n        else\n            ans = dists[u, w] + dists[w, v]\n        end\n        if dists[u, v] > ans\n            dists[u, v] = dists[u, w] + dists[w, v]\n            parents[u, v] = parents[w, v]\n        end\n    end\n    fws = FloydWarshallState(dists, parents)\n    return fws\nend\n\nfunction enumerate_paths(s::FloydWarshallState{T,U}, v::Integer) where T where U<:Integer\n    pathinfo = s.parents[v, :]\n    paths = Vector{Vector{U}}()\n    for i in 1:length(pathinfo)\n        if (i == v) || (s.dists[v, i] == typemax(T))\n            push!(paths, Vector{U}())\n        else\n            path = Vector{U}()\n            currpathindex = i\n            while currpathindex != 0\n                push!(path, currpathindex)\n                currpathindex = pathinfo[currpathindex]\n            end\n            push!(paths, reverse(path))\n        end\n    end\n    return paths\nend\n\nenumerate_paths(s::FloydWarshallState) = [enumerate_paths(s, v) for v in 1:size(s.parents, 1)]\nenumerate_paths(st::FloydWarshallState, s::Integer, d::Integer) = enumerate_paths(st, s)[d]\n", "meta": {"hexsha": "8d735212d3c75d84095fad3a3ea5fbef76e5321e", "size": 2641, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/shortestpaths/floyd-warshall.jl", "max_stars_repo_name": "mschauer/LightGraphs.jl", "max_stars_repo_head_hexsha": "ea21c7046495ca8595eb6b0fd4ed7a621ddd3c5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/shortestpaths/floyd-warshall.jl", "max_issues_repo_name": "mschauer/LightGraphs.jl", "max_issues_repo_head_hexsha": "ea21c7046495ca8595eb6b0fd4ed7a621ddd3c5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/shortestpaths/floyd-warshall.jl", "max_forks_repo_name": "mschauer/LightGraphs.jl", "max_forks_repo_head_hexsha": "ea21c7046495ca8595eb6b0fd4ed7a621ddd3c5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-16T10:27:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-16T10:27:05.000Z", "avg_line_length": 30.0113636364, "max_line_length": 94, "alphanum_fraction": 0.5967436577, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7683938548539082}}
{"text": "using HaloMF\nusing HCubature\nusing Plots\nΔm = 200\nprintln(\"Δm = \", Δm)\nA(Δm) = 1 + 0.24log10(Δm) * exp(-(4 / log10(Δm))^4)\na(Δm) = 0.44log10(Δm) - 0.88\nC(Δm) = 0.019 + 0.107log10(Δm) + 0.19 * exp(-(4 / log10(Δm))^4)\nB, b, c = 0.183, 1.5, 2.4\nδc = 1.686\nbν(lnν) =\n   1 - A(Δm) * exp(0.5 * a(Δm) * lnν) / (exp(0.5 * a(Δm) * lnν) + δc^a(Δm)) +\n   B * exp(0.5 * b * lnν) +\n   C(Δm) * exp(0.5 * c * lnν)\nf0(x) = tinker10MF(x, 0, Δm)\nnorm1, err = hquadrature(f0, -50, 5)\nprintln(\"Normalisation(MF) = \", norm1)\nf1(x) = tinker10MF(x, 0, Δm) * bν(x)\nnorm2, err = hquadrature(f1, -50, 5)\nprintln(\"Normalisation(Bias) = \", norm2)\n# %% Plot b(ν)\nx = -2:0.05:2\nΔm = 200\nplot(\n   log10.(exp.(x)),\n   log10.(bν.(x)),\n   xlim = [-0.5, 0.6],\n   ylim = [-0.5, 1.2],\n   xlabel = \"log10(ν)\",\n   ylabel = \"log10(b)\",\n   ls = :dash,\n)\nΔm = 1600\nplot!(log10.(exp.(x)), log10.(bν.(x)))\n", "meta": {"hexsha": "60a6c1623348920930c74a6c96d09fee6a531092", "size": 862, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/TestHaloBias.jl", "max_stars_repo_name": "komatsu5147/OmegaGrav.jl", "max_stars_repo_head_hexsha": "1a258787fb3ee4e20112722c55548f266a83a73d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-15T20:48:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T20:48:10.000Z", "max_issues_repo_path": "examples/TestHaloBias.jl", "max_issues_repo_name": "komatsu5147/OmegaGrav.jl", "max_issues_repo_head_hexsha": "1a258787fb3ee4e20112722c55548f266a83a73d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/TestHaloBias.jl", "max_forks_repo_name": "komatsu5147/OmegaGrav.jl", "max_forks_repo_head_hexsha": "1a258787fb3ee4e20112722c55548f266a83a73d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6285714286, "max_line_length": 77, "alphanum_fraction": 0.5255220418, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7683929544288621}}
{"text": "negbinmodel_stan = \"data {\n  int<lower=1> N;\n  int<lower=0> y[N];\n}\nparameters {\n  real<lower=0> alpha;\n  real<lower=0> beta;\n}\nmodel {\n  alpha ~ cauchy(0,10);\n  beta ~ cauchy(0,10);\n  for (i in 1:N)\n    y[i] ~ neg_binomial(alpha, beta);\n}\n\"\n\n@model negbinmodel(y) = begin\n  α ~ Cauchy(0,10)\n  β ~ Cauchy(0,10)\n  for i = 1:length(y)\n    y[i] ~ NegativeBinomial(α, β)  # α > 0, 0 < β < 1\n  end\nend\n", "meta": {"hexsha": "9a00f00fe9a947b83938e497867714b49a805ffa", "size": 397, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/stan-models/negative_binomial.model.jl", "max_stars_repo_name": "JuliaTagBot/ContinuousBenchmarks.jl", "max_stars_repo_head_hexsha": "000432d25acef05a11ea51dedfd841c761735e0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/stan-models/negative_binomial.model.jl", "max_issues_repo_name": "JuliaTagBot/ContinuousBenchmarks.jl", "max_issues_repo_head_hexsha": "000432d25acef05a11ea51dedfd841c761735e0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/stan-models/negative_binomial.model.jl", "max_forks_repo_name": "JuliaTagBot/ContinuousBenchmarks.jl", "max_forks_repo_head_hexsha": "000432d25acef05a11ea51dedfd841c761735e0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.5416666667, "max_line_length": 53, "alphanum_fraction": 0.5743073048, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731158685837, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.7683929523717058}}
{"text": "using PyPlot\nusing Printf\n\npi5(x, y) = x > y ? (x-y)^5/120 : zero(x)\nw1 = 1/6\nw2 = 5/6\na = 1/sqrt(5)\n\nK(y) = (1-y)^6/720 - ( w2*pi5(-a,y) + w2*pi5(a,y) + w1*pi5(1,y) )\n\nfigure(1)\ny = range(-1, stop=1, length=201)\nplot(y, K.(y))\ngrid(true)\nxlabel(L\"$y$\")\nylabel(L\"$K(y)$\")\nsavefig(\"quadrature_kernel.pdf\")\n\nE2(n) = 2//(2n+1) - (1+5//5^n)/3\nfor n = 0:3\n    err = E2(n)\n    @printf(\"%6d  %0d / %0d\\n\", n, err.num, err.den)\nend\n", "meta": {"hexsha": "b956cc852e6c73df99ecb94de442503c27093e0e", "size": 424, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chap2/quadrature_kernel.jl", "max_stars_repo_name": "billmclean/ComputationalMathsNotes", "max_stars_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T21:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:30:20.000Z", "max_issues_repo_path": "src/chap2/quadrature_kernel.jl", "max_issues_repo_name": "billmclean/ComputationalMathsNotes", "max_issues_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chap2/quadrature_kernel.jl", "max_forks_repo_name": "billmclean/ComputationalMathsNotes", "max_forks_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.6666666667, "max_line_length": 65, "alphanum_fraction": 0.5283018868, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731094431571, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7683929495537659}}
{"text": "function ylmKCoefficient(l::Integer, m::Integer)\n    k = BigInt(4) # BigInt avoids overflow\n    for i = l-m+1:l+m\n        k *= i\n    end\n\n    return sqrt((2.0 * l + 1) / k / π)\nend\n\n\nfunction ylmCosSinPolynomial(m::Integer, x::Variable, y::Variable)\n    sum = 0.0 * (x + y)\n    for j = 0:m÷2\n        sum += (-1)^j * binomial(m, 2 * j) * (y^(2 * j)) * (x^(m - 2 * j))\n    end\n\n    return sum\nend\n\n\nfunction ylmSinSinPolynomial(m::Integer, x::Variable, y::Variable)\n    sum = 0.0 * (x + y)\n    for j = 0:(m-1)÷2\n        sum += ((-1)^j) * binomial(m, 2 * j + 1) * (y^(2 * j + 1)) * (x^(m - 2 * j - 1))\n    end\n\n    return sum\nend\n\n\n\"\"\"\n    ylm(l, m, x, y, z)\n\nCalculation of the spherical harmonic for a given order (l,m) in Cartesian coordinates\n\n- @arg l: degree of spherical harmonics\n- @arg m: order of spherical harmonics\n- @arg x, y, z: Cartesian coordinates\n- @return: spherical harmonic polynomial\n\n\"\"\"\nfunction ylm(l::Integer, m::Integer, x::Variable, y::Variable, z::Variable)\n    if abs(m) > l\n        throw(\"-l <= m <= l expected, but m = $m and l = $l.\")\n    end\n\n    p = 1.0 * (z^2 - 1)^l + 0.0 * (x + y)\n\n    for i = 1:l+abs(m)\n        c = i <= l ? 1 / (2 * i) : 1.0\n        p = c * differentiate(p, z)\n    end\n\n    if m > 0\n        return sqrt(2) * ylmKCoefficient(l, m) * ylmCosSinPolynomial(m, x, y) * p\n    elseif m < 0\n        return sqrt(2) * ylmKCoefficient(l, abs(m)) * ylmSinSinPolynomial(abs(m), x, y) * p\n    else\n        return ylmKCoefficient(l, 0) * p\n    end\nend\n\n\n\"\"\"\n    rlylm(l, m, x, y, z)\n\nCalculate `r^l * Ylm(x,y,z)``\n\"\"\"\nfunction rlylm(l::Integer, m::Integer, x::Variable, y::Variable, z::Variable)\n    p = ylm(l, m, x, y, z)\n    tout = []\n\n    for t in terms(p)\n        deg = degree(monomial(t))\n        degR = l - deg\n        push!(tout, (x^2 + y^2 + z^2)^Int(degR / 2) * t)\n    end\n\n    return polynomial(tout)\nend\n\n\n\"\"\"\n    eval_spherharmonic(points, L)\n\nEvaluate spherical harmonics basis at given quadrature points\n\"\"\"\nfunction eval_spherharmonic(points::AbstractMatrix{T}, L) where {T<:Real}\n    ne = (L + 1)^2\n    nq = size(points, 1)\n    m = zeros(ne, nq)\n\n    @polyvar x y z\n    if L == 0\n        spe = [ylm(0, 0, x, y, z)]\n    elseif L == 1\n        spe = [\n            ylm(0, 0, x, y, z),\n            ylm(1, -1, x, y, z),\n            ylm(1, 0, x, y, z),\n            ylm(1, 1, x, y, z),\n        ]\n    elseif L == 2\n        spe = [\n            ylm(0, 0, x, y, z),\n            ylm(1, -1, x, y, z),\n            ylm(1, 0, x, y, z),\n            ylm(1, 1, x, y, z),\n            ylm(2, -2, x, y, z),\n            ylm(2, -1, x, y, z),\n            ylm(2, 0, x, y, z),\n            ylm(2, 1, x, y, z),\n            ylm(2, 2, x, y, z),\n        ]\n    end\n\n    for j in axes(m, 2), i in axes(m, 1)\n        m[i, j] = spe[i](x => points[j, 1], y => points[j, 2], z => points[j, 3])\n    end\n\n    return m\nend\n", "meta": {"hexsha": "5a065fcbfc868a5afa0cba2b637f6f321ecd363d", "size": 2835, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Math/sphere_harmonics.jl", "max_stars_repo_name": "vavrines/KitBase.jl", "max_stars_repo_head_hexsha": "c7b835e8151828c4065691c9882e42335a237ec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-12-02T13:59:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T00:49:20.000Z", "max_issues_repo_path": "src/Math/sphere_harmonics.jl", "max_issues_repo_name": "vavrines/KitBase.jl", "max_issues_repo_head_hexsha": "c7b835e8151828c4065691c9882e42335a237ec1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2020-12-02T21:20:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T00:35:04.000Z", "max_forks_repo_path": "src/Math/sphere_harmonics.jl", "max_forks_repo_name": "vavrines/KitBase.jl", "max_forks_repo_head_hexsha": "c7b835e8151828c4065691c9882e42335a237ec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-07T17:11:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T21:13:25.000Z", "avg_line_length": 23.0487804878, "max_line_length": 91, "alphanum_fraction": 0.4846560847, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731083722524, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7683929417667318}}
{"text": "# function to integrate a unit circle to find pi via monte_carlo\nfunction monte_carlo(n::Int64)\n\n    pi_count = 0\n    for i = 1:n\n        point_x = rand()\n        point_y = rand()\n\n        if (point_x^2 + point_y^2 < 1)\n            pi_count += 1\n        end\n    end\n\n    pi_estimate = 4*pi_count/n\n    println(pi - pi_estimate)\nend\n\nmonte_carlo(10000000)\n", "meta": {"hexsha": "18d4d4f38aac976964b0aa1b990dcbe3aa7c976b", "size": 355, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "monte_carlo/monte_carlo.jl", "max_stars_repo_name": "mika314/simuleios", "max_stars_repo_head_hexsha": "0b05660c7df0cd6e31eb5e70864cbedaec29b55a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 197, "max_stars_repo_stars_event_min_datetime": "2015-07-26T02:04:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T11:53:33.000Z", "max_issues_repo_path": "monte_carlo/monte_carlo.jl", "max_issues_repo_name": "shiffman/simuleios", "max_issues_repo_head_hexsha": "57239350d2cbed10893483bda65fa323e5e3a06d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2015-08-04T22:55:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-06T02:33:48.000Z", "max_forks_repo_path": "monte_carlo/monte_carlo.jl", "max_forks_repo_name": "shiffman/simuleios", "max_forks_repo_head_hexsha": "57239350d2cbed10893483bda65fa323e5e3a06d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 55, "max_forks_repo_forks_event_min_datetime": "2015-08-02T21:43:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T18:25:08.000Z", "avg_line_length": 18.6842105263, "max_line_length": 64, "alphanum_fraction": 0.5943661972, "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924777713886, "lm_q2_score": 0.7905303087996142, "lm_q1q2_score": 0.7683895136035179}}
{"text": "module Laplace\n\nusing StaticArrays\nusing LinearAlgebra\nusing ..AeroMDAO: Point2D, Point3D\n\nabstract type AbstractLaplace end\n\n# Performs velocity and potential computations for an object on a grid\ngrid_data(object :: AbstractLaplace, xs) = velocity(object, xs), potential(object, xs)\nvelocity(object :: AbstractLaplace, xs) = map(x -> velocity(object, x...), xs) \npotential(object :: AbstractLaplace, xs) = map(x -> potential(object, x...), xs)\n\n# Performs velocity and potential calculations on a grid\nfunction grid_data(objects :: Vector{<: AbstractLaplace}, xs)\n    vels = foldl((v1, v2) -> [ u .+ v for (u, v) ∈ zip(v1, v2) ], velocity(object, xs) for object ∈ objects)\n    pots = foldl((v1, v2) -> v1 + v2, potential(object, xs) for object ∈ objects)\n    \n    vels, pots\nend\n\n## 2D singularities\n#============================================#\n\nstruct Singularity2D{T <: Real} <: AbstractLaplace\n    strength :: T\n    r \t\t :: Point2D{T}\nend\n\n# Getters\nstrength(s :: Singularity2D) = s.strength\nx(s :: Singularity2D) \t\t = s.r.x\ny(s :: Singularity2D) \t\t = s.r.y\n\nsource_velocity(src :: Singularity2D, x, y) = SVector(strength(src) / (2π) * (x - y(src)) / ((x - y(src))^2 + (y - x(src))^2), str / (2π) * (y - x(src)) / ((x - y(src))^2 + (y - x(src))^2))\nsource_potential(src :: Singularity2D, x, y) = strength(src) / (4π) * log((x - y(src))^2 + (y - x(src))^2)\nsource_stream(src :: Singularity2D, x, y) = strength(src) / (2π) * atan(y - x(src), x - y(src))\n\ndoublet_velocity(dub :: Singularity2D, x, y) = SVector(strength(dub) / (2π) * ((x - y(dub))^2 - (y - x(dub))^2) / ((x - y(dub))^2 + (y - x(dub))^2)^2, - strength(dub) / (2π) * 2 * (x - y(dub)) * (y - x(dub)) / ((x - y(dub))^2 + (y - x(dub))^2)^2)\ndoublet_potential(dub :: Singularity2D, x, y) = -strength(dub) / (2π) * (y - x(dub)) / ((x - y(dub))^2 + (y - x(dub))^2)\ndoublet_stream(dub :: Singularity2D, x, y) = -strength(dub) / (2π) * (y - x(dub)) / ((x - y(dub))^2 + (y - x(dub))^2)\n\nvortex_velocity(vor :: Singularity2D, x, y) = SVector(-strength(vor) / (2π) * (y - x(vor)) / ((x - y(vor))^2 + (y - x(vor))^2), str / (2π) * (x - y(vor)) / ((x - y(vor))^2 + (y - x(vor))^2))\nvortex_potential(vor :: Singularity2D, x, y) = strength(vor) / (2π) * atan(y - x(vor), x - y(vor))\nvortex_stream(vor :: Singularity2D, x, y) = -strength(vor) / (4π) * log((x - y(vor))^2 + (y - x(vor))^2)\n\n\nstruct Uniform2D{T <: Real} <: AbstractLaplace\n    magnitude :: T\n    angle \t  :: T\n    Uniform2D{T}(mag, ang) where T <: Real = new(mag, deg2rad(ang))\nend\n\nmagnitude(uni :: Uniform2D) = uni.magnitude\nangle(uni :: Uniform2D)     = uni.angle\n\nUniform2D(mag :: T, ang :: T) where T <: Real = Uniform2D{T}(mag, ang)\nUniform2D(mag, ang) = Uniform2D(promote(mag, ang)...)\n\nvelocity(uni :: Uniform2D) = let (sa, ca) = sincos(uni.angle); uni.magnitude * SVector(ca, sa) end\npotential(uni :: Uniform2D, x, y) = uni.magnitude * (x * cos(uni.angle) + y * sin(uni.angle))\nstream(uni :: Uniform2D, x, y)    = uni.magnitude * (y * cos(uni.angle) - x * sin(uni.angle))\n\n## 3D singularities\n#============================================#\n\n# struct Singularity3D{T <: Real} <: AbstractLaplace\n# \tstr :: T\n# \tr \t:: Point3D{T}\n# end\n\n# source_velocity(src :: Source2D, x, y, z)\n# source_potential(src :: Source2D, x, y, z) \n# source_stream(src :: Source2D, x, y, z) \n\n## Freestream\n#============================================#\n\nstruct Freestream{T <: Real} <: AbstractLaplace\n    V \t  :: T\n    alpha :: T\n    beta  :: T\n    omega :: SVector{3,T}\n    Freestream{T}(V, α_deg, β_deg, Ω) where T <: Real = new(V, deg2rad(α_deg), deg2rad(β_deg), Ω)\nend\n\n\"\"\"\n    Freestream(V, α, β, Ω)\n    \nA Freestream flow in spherical polar coordinates with magnitude ``V``, angle-of-attack ``α``, side-slip angle ``β``, and a quasi-steady rotation vector ``\\\\Omega``.\n\"\"\"\nFreestream(V, α_deg, β_deg, Ω :: AbstractVector{T}) where T <: Real = Freestream{T}(V, α_deg, β_deg, Ω)\n\n# TODO: ForwardDiff testing\n# Freestream(V :: Real, α_deg, β_deg, Ω :: AbstractVector{<: Real}) = Freestream{Float64}(V, α_deg, β_deg, Ω)\n\n\"\"\"\n    Freestream(U, Ω)\n\nA Freestream flow in Cartesian coordinates with vector ``U`` and quasi-steady rotation vector ``\\\\Omega``.\n\"\"\"\nFreestream(U :: AbstractVector{T}, Ω :: AbstractVector{T}) where T <: Real = \n    let (V, α, β) = cartesian_to_freestream(U); Freestream{T}(V, α, β, Ω) end\n\n\"\"\"\n    freestream_to_cartesian(r, θ, φ)\n\nConvert freestream flow (spherical polar) coordinates to Cartesian coordinates.\n\"\"\"\nfreestream_to_cartesian(r, θ, φ) = r .* SVector(cos(θ) * cos(φ), -sin(φ), sin(θ) * cos(φ))\n\n\"\"\"\n    cartesian_to_freestream(U)\n\nConvert Cartesian coordinates to freestream (spherical polar) flow coordinates.\n\"\"\"\ncartesian_to_freestream(U) = SVector(norm(U), -atand(U[3], U[1]), -atand(U[2], √(U[1]^2 + U[3]^2)))\n\n\"\"\"\n    velocity(freestream :: Freestream)\n\nCompute the velocity of a `Freestream`.\n\"\"\"\nvelocity(freestream :: Freestream) = freestream_to_cartesian(freestream.V, freestream.alpha, freestream.beta)\n\n\"\"\"\n    aircraft_velocity(freestream :: Freestream)\n\nCompute the velocity of Freestream in the aircraft reference frame.\n\"\"\"\naircraft_velocity(freestream :: Freestream) = -velocity(freestream)\n\nend", "meta": {"hexsha": "f03e75d02a99aa3cbbf6bf929a2aba5cdd968c0f", "size": 5154, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Tools/Laplace.jl", "max_stars_repo_name": "GodotMisogi/AeroMDAO.jl", "max_stars_repo_head_hexsha": "e05b3d4589583a3e106c5fc2fde86578483133c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2021-09-23T08:04:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T13:28:01.000Z", "max_issues_repo_path": "src/Tools/Laplace.jl", "max_issues_repo_name": "GodotMisogi/AeroMDAO.jl", "max_issues_repo_head_hexsha": "e05b3d4589583a3e106c5fc2fde86578483133c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-02-08T06:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T06:08:38.000Z", "max_forks_repo_path": "src/Tools/Laplace.jl", "max_forks_repo_name": "GodotMisogi/AeroMDAO", "max_forks_repo_head_hexsha": "e05b3d4589583a3e106c5fc2fde86578483133c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-01-25T08:46:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T08:11:45.000Z", "avg_line_length": 38.7518796992, "max_line_length": 246, "alphanum_fraction": 0.6138921226, "num_tokens": 1757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305638, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7683793541491}}
{"text": "using ModelingToolkit, MethodOfLines, LinearAlgebra, OrdinaryDiffEq\nusing DomainSets\n\n# using Plots\n\n# local sol\nbegin #@testset \"Test 01: Brusselator equation 2D\" begin\n       @parameters x y t\n       @variables u(..) v(..)\n       Dt = Differential(t)\n       Dx = Differential(x)\n       Dy = Differential(y)\n       Dxx = Differential(x)^2\n       Dyy = Differential(y)^2\n\n       ∇²(u) = Dxx(u) + Dyy(u)\n\n       brusselator_f(x, y, t) = (((x-0.3)^2 + (y-0.6)^2) <= 0.1^2) * (t >= 1.1) * 5.\n\n       x_min = y_min = t_min = 0.0\n       x_max = y_max = 1.0\n       t_max = 11.5\n\n       α = 10.\n\n       u0(x,y,t) = 22(y*(1-y))^(3/2)\n       v0(x,y,t) = 27(x*(1-x))^(3/2)\n\n       eq = [Dt(u(x,y,t)) ~ 1. + v(x,y,t)*u(x,y,t)^2 - 4.4*u(x,y,t) + α*∇²(u(x,y,t)) + brusselator_f(x, y, t),\n             Dt(v(x,y,t)) ~ 3.4*u(x,y,t) - v(x,y,t)*u(x,y,t)^2 + α*∇²(v(x,y,t))]\n\n       domains = [x ∈ Interval(x_min, x_max),\n                  y ∈ Interval(y_min, y_max),\n                  t ∈ Interval(t_min, t_max)]\n\n       bcs = [u(x,y,0) ~ u0(x,y,0),\n              u(0,y,t) ~ u(1,y,t),\n              u(x,0,t) ~ u(x,1,t),\n\n              v(x,y,0) ~ v0(x,y,0),\n              v(0,y,t) ~ v(1,y,t),\n              v(x,0,t) ~ v(x,1,t)] \n       \n       @named pdesys = PDESystem(eq,bcs,domains,[x,y,t],[u(x,y,t),v(x,y,t)])\n\n       # Method of lines discretization\n       N = 32\n       \n       dx = 1/N\n       dy = 1/N\n\n       order = 2\n\n       discretization = MOLFiniteDifference([x=>dx, y=>dy], t, approx_order=order)\n\n       #MethodOfLines.generate_code(pdesys, discretization)\n       # Convert the PDE problem into an ODE problem\n       println(\"Discretization:\")\n       @time prob = discretize(pdesys,discretization)\n\n       println(\"Solve:\")\n       @time sol = solve(prob, TRBDF2(),saveat=0.01)\n\n       # Solve reference problem\n       \n       xyd_brusselator = range(0,stop=1,length=N)\n       brusselator_f(x, y, t) = (((x-0.3)^2 + (y-0.6)^2) <= 0.1^2) * (t >= 1.1) * 5.\n       limit(a, N) = a == N+1 ? 1 : a == 0 ? N : a\n       function brusselator_2d_loop(du, u, p, t)\n              A, B, alpha, dx = p\n              alpha = alpha/dx^2\n              @inbounds for I in CartesianIndices((N, N))\n                     i, j = Tuple(I)\n           x, y = xyd_brusselator[I[1]], xyd_brusselator[I[2]]\n           ip1, im1, jp1, jm1 = limit(i+1, N), limit(i-1, N), limit(j+1, N), limit(j-1, N)\n           du[i,j,1] = alpha*(u[im1,j,1] + u[ip1,j,1] + u[i,jp1,1] + u[i,jm1,1] - 4u[i,j,1]) +\n           B + u[i,j,1]^2*u[i,j,2] - (A + 1)*u[i,j,1] + brusselator_f(x, y, t)\n           du[i,j,2] = alpha*(u[im1,j,2] + u[ip1,j,2] + u[i,jp1,2] + u[i,jm1,2] - 4u[i,j,2]) +\n                       A*u[i,j,1] - u[i,j,1]^2*u[i,j,2]\n           end\n       end\n       p = (3.4, 1., 10., step(xyd_brusselator))\n       \n       function init_brusselator_2d(xyd)\n           N = length(xyd)\n           u = zeros(N, N, 2)\n           for I in CartesianIndices((N, N))\n               x = xyd[I[1]]\n               y = xyd[I[2]]\n               u[I,1] = 22*(y*(1-y))^(3/2)\n               u[I,2] = 27*(x*(1-x))^(3/2)\n           end\n           u\n       end\n       u0_manual = init_brusselator_2d(xyd_brusselator)\n       prob = ODEProblem(brusselator_2d_loop,u0_manual,(0.,11.5),p)\n       \n       msol = solve(prob,TRBDF2(),saveat=0.01) # 2.771 s (5452 allocations: 65.73 MiB)\n\n       # get variables for reshape\n       Nx = floor(Int64, (x_max - x_min) / dx) + 1\n       Ny = floor(Int64, (y_max - y_min) / dy) + 1\n\n       @variables u[1:Nx,1:Ny](t)\n       @variables v[1:Nx,1:Ny](t)\n       \n       \n       t = sol[t]\n       @testset \".\" begin\n       for k in div(length(t), 2):length(t)\n              solu = reshape([sol[u[(i-1)*Ny+j]][k] for i in 1:Nx for j in 1:Ny],(Nx,Ny))[2:end,2:end]\n              msolu = msol.u[k][:,:,1]\n              @test solu ≈ msolu rtol = 0.1\n\n              solv = reshape([sol[v[(i-1)*Ny+j]][k] for i in 1:Nx for j in 1:Ny],(Nx,Ny))[2:end,2:end]\n              msolv = msol.u[k][:,:,2]\n              @test solv ≈ msolv rtol = 0.1              \n       end\n       end\n   \n       \n       # Nx = floor(Int64, (x_max - x_min) / dx) + 1\n       # Ny = floor(Int64, (y_max - y_min) / dy) + 1\n\n       #  @variables u[1:Nx,1:Ny](t)\n       #  @variables v[1:Nx,1:Ny](t)\n       #  t = sol[t]\n       #   anim = @animate for k in 1:length(t)\n       #          solu = reshape([sol[u[(i-1)*Ny+j]][k] for i in 1:Nx for j in 1:Ny],(Nx,Ny))\n       #          #solv = reshape([sol[v[(i-1)*Ny+j]][k] for i in 1:Nx for j in 1:Ny],(Nx,Ny))\n       #          heatmap(solu[2:end, 2:end], title=\"$(t[k])\")\n       #   end\n       #   gif(anim, \"plots/Brusselator2Dsol.gif\", fps = 8)\nend", "meta": {"hexsha": "2e08fd8067e91689b428ab55e218bd7fd9a42126", "size": 4631, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/pde_systems/brusselator_eq.jl", "max_stars_repo_name": "pfcrowe/MethodOfLines.jl", "max_stars_repo_head_hexsha": "ab2a6e1c3e5214821770a67ad604e8d326f7c152", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2021-12-15T23:57:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:07:05.000Z", "max_issues_repo_path": "test/pde_systems/brusselator_eq.jl", "max_issues_repo_name": "pfcrowe/MethodOfLines.jl", "max_issues_repo_head_hexsha": "ab2a6e1c3e5214821770a67ad604e8d326f7c152", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47, "max_issues_repo_issues_event_min_datetime": "2021-12-21T01:12:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:48:01.000Z", "max_forks_repo_path": "test/pde_systems/brusselator_eq.jl", "max_forks_repo_name": "pfcrowe/MethodOfLines.jl", "max_forks_repo_head_hexsha": "ab2a6e1c3e5214821770a67ad604e8d326f7c152", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-12-16T13:48:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T13:46:41.000Z", "avg_line_length": 34.5597014925, "max_line_length": 110, "alphanum_fraction": 0.460807601, "num_tokens": 1755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305639, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7683793541491}}
{"text": "using EconPDEs\n\nBase.@kwdef  struct CampbellCochraneModel\n    # consumption process parameters\n    μ::Float64 = 0.0189\n    σ::Float64 = 0.015\n\n    # utility\n    γ::Float64 = 2.0\n    ρ::Float64 = 0.116\n\n    # habit\n    κs::Float64 = 0.138\n    b::Float64 = 0.0\nend\n# I choose persistence so that monthly simulation of the model matches processes in CC (1999)\n# ρ = 12 * (1 - 0.89^(1/12))\n# κs = 12 * (1 - 0.87^(1/12))\n\nfunction initialize_stategrid(m::CampbellCochraneModel; smin = -300.0, n = 1000)\n    μ = m.μ ; σ = m.σ ; γ = m.γ ; ρ = m.ρ ; κs = m.κs ; b = m.b\n    Sbar = σ * sqrt(γ / (κs - b / γ))\n    sbar = log.(Sbar)\n    smax =  sbar + 0.5 * (1 - Sbar^2)\n    # corresponds to Grid 3 in Wachter (2005)\n    shigh = log.(range(0.0, stop = exp(smax), length = div(n, 10)))\n    slow = range(smin, stop = shigh[2], length = n - div(n, 10))\n    OrderedDict(:s => vcat(slow[1:(end-1)], shigh[2:end]))\nend\n\nfunction initialize_y(m::CampbellCochraneModel, stategrid)\n    OrderedDict(:p => ones(length(stategrid[:s])))\nend\n\t\nfunction (m::CampbellCochraneModel)(state::NamedTuple, y::NamedTuple)\n    μ = m.μ ; σ = m.σ ; γ = m.γ ; ρ = m.ρ ; κs = m.κs ; b = m.b\n    s = state.s\n    p, ps, pss = y.p, y.ps, y.pss\n    \n    # drift and volatility of  s and p\n    Sbar = σ * sqrt(γ / (κs - b / γ))\n    sbar = log(Sbar)\n    λ = 1 / Sbar * sqrt(1 - 2 * (s - sbar)) - 1\n    μs = - κs * (s - sbar)\n    σs = λ * σ\n    σp = ps / p * σs\n    μp = ps / p * μs + 0.5 * pss / p * σs^2\n\n    # market price of risk κ\n    κ = γ * (σ + σs)\n\n    # risk free rate  r\n    r = ρ + γ * μ - (γ * κs - b) / 2 + b * (sbar - s)\n\n    # PDE\n    pt = p * (1 / p + μ + μp + σp * σ - r - κ * (σ + σp))\n    return (pt,), (μs, ), (p = p, κ = κ, λ = λ, r = r, σp = σp, μs = μs, σs = σs)\nend\n\n\n# Campbell Cochrane (1999)\nm = CampbellCochraneModel()\nstategrid = initialize_stategrid(m)\ny0 = initialize_y(m, stategrid)\ny, result, distance = pdesolve(m, stategrid, y0)\n\n\n\n# Wachter (2005) calibration\n# m = CampbellCochraneModel(μ = 0.022, σ = 0.0086, γ = 2.0, ρ = 0.073, κs = 0.116, b = 0.011)\n# stategrid = initialize_stategrid(m)\n# y0 = initialize_y(m, stategrid)\n# y, result, distance = pdesolve(m, stategrid, y0)\n\n", "meta": {"hexsha": "ad2e1657cf1e35ff61d4bb5250e486d8cfbbaf53", "size": 2170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/AssetPricing/CampbellCochrane.jl", "max_stars_repo_name": "vr235/EconPDEs.jl", "max_stars_repo_head_hexsha": "045aede7cdcb7b6ae702b152676fb9d5bc85f99f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/AssetPricing/CampbellCochrane.jl", "max_issues_repo_name": "vr235/EconPDEs.jl", "max_issues_repo_head_hexsha": "045aede7cdcb7b6ae702b152676fb9d5bc85f99f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/AssetPricing/CampbellCochrane.jl", "max_forks_repo_name": "vr235/EconPDEs.jl", "max_forks_repo_head_hexsha": "045aede7cdcb7b6ae702b152676fb9d5bc85f99f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9333333333, "max_line_length": 93, "alphanum_fraction": 0.5571428571, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7683793449652259}}
{"text": "abstract type AbstractAcquisition end\n\nsetparams!(a, model) = nothing\nfunction acquisitionfunction(a, model)\n    x -> begin\n        μ, σ² = mean_var(model, x)\n        a.(μ, σ²)\n    end\nend\n\n\"\"\"\nThe probability of improvement measures the probability that a point `x` leads\nto an improvement upon an incumbent target `τ`. For Gaussian distributions it is\ngiven by\n\n    Φ[(μ(x) - τ)/σ(x)]\n\nwhere `Φ` is the standard normal cumulative distribution function and `μ(x)`, `σ(x)`\nare mean and standard deviation of the distribution at point `x`.\n\"\"\"\nmutable struct ProbabilityOfImprovement <: AbstractAcquisition\n    τ::Float64\nend\n@inline function (a::ProbabilityOfImprovement)(μ, σ²)\n    σ² == 0 && return float(μ > a.τ)\n    normal_cdf(μ - a.τ, σ²)\nend\nProbabilityOfImprovement(; τ = -Inf) = ProbabilityOfImprovement(τ)\n\n\"\"\"\nThe expected improvement measures the expected improvement `x - τ` of a point `x`\nupon an incumbent target `τ`. For Gaussian distributions it is given by\n\n    (μ(x) - τ) * ϕ[(μ(x) - τ)/σ(x)] + σ(x) * Φ[(μ(x) - τ)/σ(x)]\n\nwhere `ϕ` is the standard normal distribution function and `Φ` is the standard\nnormal cumulative function, and `μ(x)`, `σ(x)` are mean and standard deviation\nof the distribution at point `x`.\n\"\"\"\nmutable struct ExpectedImprovement <: AbstractAcquisition\n    τ::Float64\nend\nExpectedImprovement(; τ = -Inf) = ExpectedImprovement(τ)\nfunction setparams!(a::Union{ExpectedImprovement,ProbabilityOfImprovement}, model)\n    a.τ = max(maxy(model), a.τ)\nend\n@inline function (a::ExpectedImprovement)(μ, σ²)\n    σ² == 0 && return μ > a.τ ? μ - a.τ : 0.\n    abs(μ - a.τ) * normal_cdf(μ - a.τ, σ²) + √σ² * normal_pdf(μ - a.τ, σ²)\nend\n\nabstract type BetaScaling end\n\"\"\"\nScales `βt` of `UpperConfidenceBound` as\n\n    βt = √(2 * log(t^(D/2 + 2) * π^2/(3δ)))\n\nwhere `t` is the number of observations, `D` is the dimensionality of the input\ndata points and δ is a small constant (default δ = 0.1).\n\nSee Brochu E., Cora V. M., de Freitas N. (2010), \"A Tutorial on Bayesian\nOptimization of Expensive Cost Functions, with Application to Active User\nModeling and Hierarchical Reinforcement Learning\", https://arxiv.org/abs/1012.2599v1\npage 16.\n\"\"\"\nstruct BrochuBetaScaling <: BetaScaling\n    δ::Float64\nend\n\"\"\"\nApplies no scaling to `βt` of `UpperConfidenceBound`.\n\"\"\"\nstruct NoBetaScaling <: BetaScaling end\n\"\"\"\nFor Gaussian distributions the upper confidence bound at `x` is given by\n    μ(x) + βt * σ(x)\n\nwhere `βt` is a fixed parameter in the case of `NoBetaScaling` or an observation\nsize dependent parameter in the case of e.g. `BrochuBetaScaling`.\n\"\"\"\nmutable struct UpperConfidenceBound{S} <: AbstractAcquisition\n    scaling::S\n    βt::Float64\nend\n\"\"\"\n    UpperConfidenceBound(; scaling = BrochuBetaScaling(.1), βt = 1)\n\"\"\"\nUpperConfidenceBound(; scaling = BrochuBetaScaling(.1), βt = 1.) = UpperConfidenceBound(scaling, βt)\nfunction setparams!(a::UpperConfidenceBound{BrochuBetaScaling}, model)\n    D, nobs = dims(model)\n    nobs == 0 && (nobs = 1)\n    a.βt = sqrt(2*log(nobs^(D/2 + 2)*π^2/(3*a.scaling.δ)))\nend\n(a::UpperConfidenceBound)(μ, σ²) = μ + a.βt * √σ²\n\n\"\"\"\nThe acquisition function associated with `ThompsonSamplingSimple` draws\nindependent samples for each input `x` a function value from the model. Together\nwith a gradient-free optimization method this leads to proposal points that\nmight be similarly distributed as the maxima of true Thompson samples from GPs.\nTrue Thompson samples from a GP are simply functions from a GP. Maximizing these\nsamples can be tricky, see e.g. http://hildobijl.com/Downloads/GPRT.pdf\nchapter 6.\n\"\"\"\nstruct ThompsonSamplingSimple <: AbstractAcquisition end\nacquisitionfunction(a::ThompsonSamplingSimple, model) = x -> myrand(model, x)\n\nstruct MaxMean <: AbstractAcquisition end\nacquisitionfunction(a::MaxMean, model) = x -> mean_var(model, x)[1]\n\n\"\"\"\nThe mutual information measures the amount of information gained by querying at\nx. The parameter γ̂ gives a lower bound for the information on f from the queries\n{x}. For a Gaussian this is\n    γ̂ = ∑σ²(x)\nand the mutual information at x is\n    μ(x) + √(α)*(√(σ²(x)+γ̂) - √(γ̂))\n\nwhere `μ(x)`, `σ(x)` are mean and standard deviation\nof the distribution at point `x`.\n\nSee Contal E., Perchet V., Vayatis N. (2014), \"Gaussian Process Optimization\nwith Mutual Information\" http://proceedings.mlr.press/v32/contal14.pdf\n\"\"\"\nmutable struct MutualInformation <: AbstractAcquisition\n    sqrtα::Float64\n    γ̂::Float64\nend\nMutualInformation(; α = 1.0, γ̂ = 0.0) = MutualInformation(sqrt(α), γ̂)\nfunction setparams!(a::MutualInformation, model)\n    D, nobs = dims(model)\n    if iszero(nobs)\n        a.γ̂ = 0.0\n    else\n        last_x = @view model.x[:, end]\n        μ, σ2 = mean_var(model, last_x)\n        a.γ̂ += σ2\n    end\nend\n(a::MutualInformation)(μ, σ²) = μ + a.sqrtα * (sqrt(σ² + a.γ̂) - sqrt(a.γ̂))\n\n# TODO see\n# https://github.com/HildoBijl/GPRT/blob/7166548b8587201fabc671a0647aac2ff96f3555/Chapter6/Chapter6.m#L723\n# and corresponding thesis page 173\n# mutable struct ThompsonSampling{K} <: AbstractAcquisition\n# end\n\n# TODO\n# mutable struct EntropySearch <: AbstractAcquisition\n# end\n\n# TODO\n# mutable struct PredictiveEntropySearch <: AbstractAcquisition\n# end\n\n", "meta": {"hexsha": "029d9ab4e97586ea1bd6b73cb29bc9a859dea758", "size": 5188, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/acquisitionfunctions.jl", "max_stars_repo_name": "SourangshuGhosh/-BayesianOptimization.jl", "max_stars_repo_head_hexsha": "a8a9f322a2820542d0999d0edff513139102c3b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-13T18:06:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-18T14:27:52.000Z", "max_issues_repo_path": "src/acquisitionfunctions.jl", "max_issues_repo_name": "SourangshuGhosh/BayesianOptimization.jl", "max_issues_repo_head_hexsha": "a8a9f322a2820542d0999d0edff513139102c3b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/acquisitionfunctions.jl", "max_forks_repo_name": "SourangshuGhosh/BayesianOptimization.jl", "max_forks_repo_head_hexsha": "a8a9f322a2820542d0999d0edff513139102c3b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4709677419, "max_line_length": 106, "alphanum_fraction": 0.7091364688, "num_tokens": 1555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7683621010721338}}
{"text": "\"\"\"\nRiemann-Liouville sense fractional derivative algorithms, please refer to [Riemann-Liouville derivative](https://en.wikipedia.org/wiki/Fractional_calculus#Riemann%E2%80%93Liouville_fractional_derivative)\n\"\"\"\nabstract type RLDiff <: FracDiffAlg end\n\n#RLDiff_LinearInterp maybe??\n\"\"\"\n# Riemann Liouville sense derivative approximation\n\n    fracdiff(f, α, end_point, h, RLDiffApprox())\n\nUsing Linear interpolation to approximate fractional derivative in Riemann Liouville  fractional derivative sense.\n\n### Example\n\n```julia-repl\njulia> fracdiff(x->x^5, 0.5, 2.5, 0.0001, RLDiffApprox())\n141.59707906952633\n```\n\n!!! warning\n    The RLDiffApprox algorithm only support for 0 < α < 1.\n\"\"\"\nstruct RLDiffApprox <: RLDiff end\n\n\n\"\"\"\n# Riemann Liouville sense derivative using Triangular Strip Matrix to discrete and compute.\n\n    fracdiff(f, α, end_point, h, RLDiffMatrix())\n\nUsing [Triangular Strip Matrix](https://en.wikipedia.org/wiki/Triangle_strip) to approximate fractional derivative.\n\n### Example\n\n```julia-repl\njulia> fracdiff(x->x^5, 0.5, 2.5, 0.0001, RLInt_Matrix())\n```\n\n!!! info\n    Triangular Strip Matrix method returns the derivative in the interval ``[0, T]`` in ```Vector```\n\n```tex\n@article{2009,\ntitle={Matrix approach to discrete fractional calculus II: Partial fractional differential equations},\nDOI={10.1016/j.jcp.2009.01.014},\nauthor={Podlubny, Igor and Chechkin, Aleksei and Skovranek, Tomas and Chen, YangQuan and Vinagre Jara, Blas M.},\n}\n```\n\"\"\"\nstruct RLDiffMatrix <: RLDiff end\n\n\n\"\"\"\n# Riemann Liouville sense linear spline interpolation.\n\n    fracdiff(f, α, end_point, h, RLLinearSplineInterp())\n\nUsing linear spline interpolation method to approximate the Riemann Liouville fractional derivative.\n\"\"\"\nstruct RLLinearSplineInterp <: RLDiff end\n\n\"\"\"\n# Riemann Liouville sense G1 scheme\n\n    fracdiff(f, α, start_point, end_point, h, RLG1())\n\nRemove the limit symbol in the definition of Grunwald-Letnikov fractional derivative, thereby leading to a discretization scheme in form of truncated series.\n\n!!! tip\n        **RLG1** also can be used to compute fractional integral~\n        ``+\\\\alpha`` for fractional derivative and ``-\\\\alpha`` for fractional integral.\n\n```tex\n@inproceedings{Guo2015FractionalPD,\n  title={Fractional Partial Differential Equations and their Numerical Solutions},\n  author={Boling Guo and Xueke Pu and Feng-Hui Huang},\n  year={2015}\n}\n```\n\"\"\"\nstruct RLG1 <: RLDiff end\n\n\"\"\"\n# Riemann Liouville sense D scheme\n\n        fracdiff(f, α, point, h, RLD())\n\n```tex\n@inproceedings{Guo2015FractionalPD,\n  title={Fractional Partial Differential Equations and their Numerical Solutions},\n  author={Boling Guo and Xueke Pu and Feng-Hui Huang},\n  year={2015}\n}\n```\n\"\"\"\nstruct RLD <: RLDiff end\n\n################################################################\n###                    Type definition done                  ###\n################################################################\n\n\nfunction fracdiff(f::FunctionAndNumber, α, end_point, h::Float64, ::RLDiffApprox)\n    #checks(f, α, 0, end_point)\n    typeof(f) <: Number ? (end_point == 0 ? (return 0) : (return f/sqrt(pi*end_point))) : nothing\n    end_point == 0 ? (return 0) : nothing\n\n    summation = 0\n    n = floor(Int, end_point/h)\n\n    @fastmath @inbounds @simd for i ∈ 0:n-1\n        summation += (f(end_point-i*h) - f(end_point-(i+1)*h))*((i+1)^(1-α) - i^(1-α))\n    end\n\n    result = ((1-α)*f(0)/n^α+summation)*end_point^(-α)*n^α/gamma(2-α)\n    return result\nend\n\nfunction fracdiff(f::FunctionAndNumber, α::Float64, end_point::AbstractArray, h::Float64, ::RLDiffApprox)::Vector\n    result = map(x->fracdiff(f, α, x, h, RLDiffApprox()), end_point)\n    return result\nend\n\n\n\n\nfunction fracdiff(f::Union{Function, Number}, α, end_point, h::Float64, ::RLDiffMatrix)\n    N = round(Int, end_point/h+1)\n    @views tspan = collect(0:h:end_point)\n    return B(N, α, h)*f.(tspan)\nend\n\n#Compute the eliminator matrix Sₖ by omiting n-th row\nfunction eliminator(n, row)\n    temp = zeros(n, n) + I\n    return @views temp[Not(row), :]\nend\n\nfunction B(N, p)\n    result = zeros(N, N)\n    temp = omega(N, p)\n\n    @inbounds @simd for i ∈ 1:N\n        @views result[i, 1:i]=reverse(temp[1:i])\n    end\n\n    return result\nend\n# Multiple dispatch for assigning step size *h*.\nfunction B(N, p, h::Float64)\n    result = B(N, p)\n\n    return h^(-p)*result\nend\n\n\n\n\n#=\nNumerical methods for fractional calculus by Li, Changpin\nPage 57\n\nLinear Spline Interpolation\n=#\nfunction fracdiff(f::FunctionAndNumber, α, x, h::Float64, ::RLLinearSplineInterp)\n    typeof(f) <: Number ? (x == 0 ? (return 0) : (return f/sqrt(pi*x))) : nothing\n    x == 0 ? (return 0) : nothing\n    N = round(Int, x/h)\n\n    result = 0\n\n    @fastmath @inbounds @simd for k = 0:(N+1)\n        result += z̄ₘₖ(N, k, α)*f(k*h)\n    end\n\n    return 1/(gamma(4-α)h^α)*result\n\nend\n\nfunction z̄ₘₖ(m, k, α)\n    if k ≤ m-1\n        return c̄ⱼₖ(m-1, k, α)-2*c̄ⱼₖ(m, k, α)+c̄ⱼₖ(m+1, k, α)\n    elseif k == m\n        return -2*c̄ⱼₖ(m, k, α)+c̄ⱼₖ(m+1, k, α)\n    elseif k == m+1\n        return c̄ⱼₖ(m+1, k, α)\n    elseif k > m+1\n        return 0\n    end\nend\n\nfunction c̄ⱼₖ(j, k, α)\n    if k==0\n        return (j-1)^(3-α)-j^(2-α)*(j-3+α)\n    elseif 1 ≤ k ≤ j-1\n        return (j-k+1)^(3-α)-2*(j-k)^(3-α)+(j-k-1)^(3-α)\n    elseif k == j\n        return 1\n    end\nend\n\nfunction fracdiff(f::FunctionAndNumber, α::Float64, end_point::AbstractArray, h::Float64, ::RLLinearSplineInterp)::Vector\n    result = map(x->fracdiff(f, α, x, h, RLLinearSplineInterp()), end_point)\n    return result\nend\n\nfunction fracdiff(f::FunctionAndNumber, α, start_point, end_point, h::Float64, ::RLG1)\n    typeof(f) <: Number ? (end_point == 0 ? (return 0) : (return f/sqrt(pi*end_point))) : nothing\n    end_point == 0 ? (return 0) : nothing\n\n    N = round(Int, (end_point-start_point)/h)\n\n    result = zero(Float64)\n    @fastmath @inbounds @simd for j = 0:N-1\n        result += gamma(j-α)/gamma(j+1)*f(end_point-j*h)\n    end\n\n    return h^(-α)/gamma(-α)*result\nend\n\nfunction fracdiff(f::FunctionAndNumber, α, point, h::Float64, ::RLD)\n    typeof(f) <: Number ? (point == 0 ? (return 0) : (return f/sqrt(pi*point))) : nothing\n    point == 0 ? (return 0) : nothing\n\n    N = round(Int, point/h)\n\n    result = zero(Float64)\n    @fastmath @inbounds @simd for k = 0:N\n        result += ωₖₙ(N, k, α)*f(point-k*h)\n    end\n\n    return point^(-α)/gamma(-α)*result\n\nend\n\nfunction ωₖₙ(n, k, α)\n    temp = 0\n    if k == 0\n        temp = -1\n    elseif 1 ≤ k ≤ n-1\n        temp = 2*k^(1-α)-(k-1)^(1-α)-(k+1)^(1-α)\n    elseif k == n\n        temp = (α-1)*n^(-α)-(n-1)^(1-α)+n^(1-α)\n    end\n    return n^α/(α*(1-α))*temp\nend", "meta": {"hexsha": "a6d8d80a6b075c96ae07a6499f48c47cde92acb4", "size": 6605, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Derivative/RL.jl", "max_stars_repo_name": "SciFracX/FractionalCalculus.jl", "max_stars_repo_head_hexsha": "f570164fdf86314f6c8871d18659bd343046bb04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-11-05T12:53:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T20:58:27.000Z", "max_issues_repo_path": "src/Derivative/RL.jl", "max_issues_repo_name": "SciFracX/FractionalCalculus.jl", "max_issues_repo_head_hexsha": "f570164fdf86314f6c8871d18659bd343046bb04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-11-05T17:20:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T13:20:01.000Z", "max_forks_repo_path": "src/Derivative/RL.jl", "max_forks_repo_name": "SciFracX/FractionalCalculus.jl", "max_forks_repo_head_hexsha": "f570164fdf86314f6c8871d18659bd343046bb04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-10-21T08:58:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T20:40:29.000Z", "avg_line_length": 26.7408906883, "max_line_length": 203, "alphanum_fraction": 0.6342165026, "num_tokens": 2161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.8376199673867853, "lm_q1q2_score": 0.7683510200186885}}
{"text": "\"\"\"\r\n    adaptif(f, a, b; delta=10^-9)\r\n\r\nadalah fungsi yang digunakan untuk mencari nilai integral dari fungsi `f`\r\npada interval `[a,b]` menggunakan aturan kuadratur adaptif.\r\nSecara default toleransi yang digunakan adalah `delta=1e-9`.\r\n\r\n# Examples\r\n```jldoctest\r\njulia> f(x) = 13*(x-x.^2).*exp(-3*x/2);\r\n\r\njulia> sol,err,SRmat = adaptif(f,0,4,delta=0.00001);\r\n\r\njulia> sol\r\n-1.5487882341253174\r\n\r\njulia> err\r\n2.9680861581356417e-6\r\n\r\njulia> SRmat\r\n20×5 Array{Float64,2}:\r\n 0.0     0.0625   0.0228718  1.52153e-8  1.5625e-7\r\n 0.0625  0.125    0.0594869  1.31649e-8  1.5625e-7\r\n 0.125   0.1875   0.0843421  1.13722e-8  1.5625e-7\r\n 0.1875  0.25     0.0996987  9.80639e-9  1.5625e-7\r\n ⋮\r\n 2.5     2.75    -0.2701     7.07089e-8  6.25e-7\r\n 2.75    3.0     -0.234747   5.4474e-8   6.25e-7\r\n 3.0     3.5     -0.363898   1.03699e-6  1.25e-6\r\n 3.5     4.0     -0.243138   4.10779e-7  1.25e-6\r\n```\r\nreturn solusi `sol`, estimasi kesalahan `err`, dan\r\nmatriks `SRmat` yang berisi sub-interval (kolom 1 dan 2), nilai integral\r\npada sub-interval (kolom 3), galat integral numerik (kolom 4), dan toleransi pada\r\nsub-interval (kolom 5).\r\n\r\n\"\"\"\r\nfunction adaptif(f, a, b; delta=10^-9)\r\n  iterating = 0;\r\n  done = 1;\r\n  SRvec = srule(f,a,b,delta);\r\n  SRmat = SRvec;\r\n  m = 1;\r\n  state = iterating;\r\n  while(state==iterating)\r\n    n = m;\r\n    for j = n:-1:1\r\n      p = j;\r\n      SR0vec = SRmat[p,:];\r\n      err = SR0vec[5];\r\n      delta = SR0vec[6];\r\n      if (delta<=err)\r\n        state=done;\r\n        SR1vec=SR0vec;\r\n        SR2vec=SR0vec;\r\n        a = SR0vec[1];\r\n        b = SR0vec[2];\r\n        c =(a+b)/2;\r\n        err=SR0vec[5];\r\n        delta=SR0vec[6];\r\n        delta2=delta/2;\r\n        SR1vec=srule(f,a,c,delta2);\r\n        SR2vec=srule(f,c,b,delta2);\r\n        err = abs(SR0vec[3]-SR1vec[3]-SR2vec[3])/10;\r\n        if err<delta\r\n          SRmat[p,:]=SR0vec;\r\n          SRmat[p,4]=SR1vec[3]+SR2vec[3];\r\n          SRmat[p,5]=err;\r\n        else\r\n          SRmat = [SRmat; zeros(1,6)]\r\n          SRmat[p+1:m+1,:] = SRmat[p:m,:];\r\n          m=m+1;\r\n          SRmat[p,:]=SR1vec;\r\n          SRmat[p+1,:]=SR2vec;\r\n          state=iterating;\r\n        end\r\n      end\r\n    end\r\n  end\r\n  sol = sum(SRmat[:,4]);\r\n  err = sum(abs.(SRmat[:,5]));\r\n  SRmat = SRmat[1:m,[1,2,4,5,6]];\r\n  return sol, err, SRmat\r\nend\r\n\r\nfunction srule(f,a0,b0,delta0)\r\n  h = (b0-a0)/2;\r\n  C = zeros(1,3)\r\n  C = f.([a0 (a0+b0)/2 b0]);\r\n  S = h*(C[1]+4*C[2]+C[3])/3;\r\n  S2= S;\r\n  delta1=delta0;\r\n  err=delta0;\r\n  Z = [a0 b0 S S2 err delta1];\r\n  return Z\r\nend\r\n", "meta": {"hexsha": "613907f6f9d85a10314ccaf4638144973492858d", "size": 2516, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/adaptif.jl", "max_stars_repo_name": "mkhoirun-najiboi/metnum.jl", "max_stars_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/adaptif.jl", "max_issues_repo_name": "mkhoirun-najiboi/metnum.jl", "max_issues_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/adaptif.jl", "max_forks_repo_name": "mkhoirun-najiboi/metnum.jl", "max_forks_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9381443299, "max_line_length": 82, "alphanum_fraction": 0.5373608903, "num_tokens": 1066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679977, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7683510183321248}}
{"text": "#Stationary iterative methods\n#Templates, section 2.2\nexport jacobi, jacobi!, gauss_seidel, gauss_seidel!, sor, sor!, ssor, ssor!\n\njacobi(A::AbstractMatrix, b;\n       tol=size(A,2)^3*eps(typeof(real(b[1]))), maxiter=size(A,2)^2) =\n    jacobi!(zerox(A, b), A, b; tol=tol, maxiter=maxiter)\n\nfunction jacobi!(x, A::AbstractMatrix, b;\n        tol=size(A,2)^3*eps(typeof(real(b[1]))), maxiter=size(A,2)^2)\n\tn = size(A,2)\n    xold = copy(x)\n    z = zero(Amultype(A, x))\n    tol = tol * norm(b)\n\tresnorms = zeros(typeof(real(b[1])), maxiter)\n\tfor iter=1:maxiter\n\t\tfor i=1:n\n\t\t\txi = z\n\t\t\tfor j=[1:i-1;i+1:n]\n\t\t\t\txi += A[i,j]*xold[j]\n\t\t\tend\n\t\t\tA[i,i]==0 && throw(SingularError())\n\t\t\tx[i]=(b[i]-xi)/A[i,i]\n\t\tend\n\t\t#check convergence\n\t\tresnorms[iter] = norm(A*x-b)\n\t\tif resnorms[iter] < tol\n\t\t\tresnorms=resnorms[1:iter]\n\t\t\tbreak\n\t\tend\n\t\tcopy!(xold, x)\n\tend\n\tx, ConvergenceHistory(resnorms[end]<tol, tol, length(resnorms), resnorms)\nend\t\n\ngauss_seidel(A::AbstractMatrix, b;\n        tol=size(A,2)^3*eps(typeof(real(b[1]))), maxiter=size(A,2)^2) =\n    gauss_seidel!(zerox(A, b), A, b; tol=tol, maxiter=maxiter)\n\nfunction gauss_seidel!(x, A::AbstractMatrix, b;\n        tol=size(A,2)^3*eps(typeof(real(b[1]))), maxiter=size(A,2)^2)\n\tn = size(A,2)\n    xold = copy(x)\n    z = zero(Amultype(A, x))\n    tol = tol * norm(b)\n\tresnorms = zeros(typeof(real(b[1])), maxiter)\n\tfor iter=1:maxiter\n\t\tfor i=1:n\n\t\t\tσ=z\n\t\t\tfor j=1:i-1\n\t\t\t\tσ+=A[i,j]*x[j]\n\t\t\tend\n\t\t\tfor j=i+1:n\n\t\t\t\tσ+=A[i,j]*xold[j]\n\t\t\tend\n\t\t\tA[i,i]==0 && throw(SingularError())\n\t\t\tx[i]=(b[i]-σ)/A[i,i]\n\t\tend\n\t\t#check convergence\n\t\tresnorms[iter] = norm(A*x-b)\n\t\tif resnorms[iter] < tol\n\t\t\tresnorms=resnorms[1:iter]\n\t\t\tbreak\n\t\tend\n\t\tcopy!(xold, x)\n\tend\n\tx, ConvergenceHistory(resnorms[end]<tol, tol, length(resnorms), resnorms)\nend\n\n#Successive overrelaxation\nsor(A::AbstractMatrix, b, ω::Real;\n    tol=size(A,2)^3*eps(typeof(real(b[1]))), maxiter=size(A,2)^2) =\n    sor!(zerox(A, b), A, b, ω; tol=tol, maxiter=maxiter)\n\nfunction sor!(x, A::AbstractMatrix, b, ω::Real;\n        tol=size(A,2)^3*eps(typeof(real(b[1]))), maxiter=size(A,2)^2)\n\t0 < ω < 2 || warn(\"ω = $ω lies outside the range 0<ω<2 which is required for convergence\")\n\n\tn = size(A,2)\n    xold = copy(x)\n    z = zero(Amultype(A, x))\n    tol = tol * norm(b)\n\tresnorms = zeros(typeof(real(b[1])), maxiter)\n\tfor iter=1:maxiter\n\t\tfor i=1:n\n\t\t\tσ=z\n\t\t\tfor j=1:i-1\n\t\t\t\tσ+=A[i,j]*x[j]\n\t\t\tend\n\t\t\tfor j=i+1:n\n\t\t\t\tσ+=A[i,j]*xold[j]\n\t\t\tend\n\t\t\tA[i,i]==0 && throw(SingularError())\n\t\t\tσ=(b[i]-σ)/A[i,i]\n\t\t\tx[i]=xold[i]+ω*(σ-xold[i])\n\t\tend\n\t\t#check convergence\n\t\tresnorms[iter] = norm(A*x-b)\n\t\tif resnorms[iter] < tol\n\t\t\tresnorms=resnorms[1:iter]\n\t\t\tbreak\n\t\tend\n\t\tcopy!(xold, x)\n\tend\n\tx, ConvergenceHistory(resnorms[end]<tol, tol, length(resnorms), resnorms)\nend\n\n#Symmetric successive overrelaxation\n#A must be symmetric\nssor(A::AbstractMatrix, b, ω::Real;\n     tol=size(A,2)^3*eps(typeof(real(b[1]))), maxiter=size(A,2)) =\n    ssor!(zerox(A, b), A, b, ω; tol=tol, maxiter=maxiter)\n\nfunction ssor!(x, A::AbstractMatrix, b, ω::Real;\n        tol=size(A,2)^3*eps(typeof(real(b[1]))), maxiter=size(A,2))\n\t0 < ω < 2 || warn(\"ω = $ω lies outside the range 0<ω<2 which is required for convergence\")\n\n\tn = size(A,2)\n    xold = copy(x)\n    z = zero(Amultype(A, x))\n    tol = tol * norm(b)\n\tresnorms = zeros(typeof(real(b[1])), maxiter)\n\tfor iter=1:maxiter\n\t\tfor i=1:n #Do a SOR sweep\n\t\t\tσ=z\n\t\t\tfor j=1:i-1\n\t\t\t\tσ+=A[i,j]*x[j]\n\t\t\tend\n\t\t\tfor j=i+1:n\n\t\t\t\tσ+=A[i,j]*xold[j]\n\t\t\tend\n\t\t\tA[i,i]==0 && throw(SingularError())\n\t\t\tσ=(b[i]-σ)/A[i,i]\n\t\t\tx[i]=xold[i]+ω*(σ-xold[i])\n\t\tend\n\t\tcopy!(xold, x)\n\t\tfor i=n:-1:1 #Do a backward SOR sweep\n\t\t\tσ=z\n\t\t\tfor j=1:i-1\n\t\t\t\tσ+=A[i,j]*xold[j]\n\t\t\tend\n\t\t\tfor j=i+1:n\n\t\t\t\tσ+=A[i,j]*x[j]\n\t\t\tend\n\t\t\tA[i,i]==0 && throw(SingularError())\n\t\t\tσ=(b[i]-σ)/A[i,i] #This line is missing in the Templates reference\n\t\t\tx[i]=xold[i]+ω*(σ-xold[i])\n\t\tend\n\t\t#check convergence\n\t\tresnorms[iter] = norm(A*x-b)\n\t\tif resnorms[iter] < tol\n\t\t\tresnorms=resnorms[1:iter]\n\t\t\tbreak\n\t\tend\n\t\tcopy!(xold, x)\n\tend\n\tx, ConvergenceHistory(resnorms[end]<tol, tol, length(resnorms), resnorms)\nend\n", "meta": {"hexsha": "751fa6ee1202354a492f643b88e7295afc0468d1", "size": 4061, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stationary.jl", "max_stars_repo_name": "zhangwen0411/MyIterativeSolvers.jl", "max_stars_repo_head_hexsha": "846d00bce67d73da0d9bc521732e0348f23fe490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stationary.jl", "max_issues_repo_name": "zhangwen0411/MyIterativeSolvers.jl", "max_issues_repo_head_hexsha": "846d00bce67d73da0d9bc521732e0348f23fe490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stationary.jl", "max_forks_repo_name": "zhangwen0411/MyIterativeSolvers.jl", "max_forks_repo_head_hexsha": "846d00bce67d73da0d9bc521732e0348f23fe490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5408805031, "max_line_length": 91, "alphanum_fraction": 0.601083477, "num_tokens": 1580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7683510163004055}}
{"text": "const fdc1_2 = [0, 1/2]\nconst fdc1_4 = [0, 2/3, -1/12]\nconst fdc1_6 = [0, 3/4, -3/20,1/60 ]\nconst fdc1_8 = [0, 4/5, -1/5 ,4/105, -1/280]\nconst fdc2_2 = [-2, 1]\nconst fdc2_4 = [-5/2,    4/3,-1/12]\nconst fdc2_6 = [-49/18 , 3/2,-3/20, 1/90]\nconst fdc2_8 = [-205/72, 8/5,-1/5,  8/315, -1/560]\nconst fdc1 = [fdc1_2, fdc1_4, fdc1_6, fdc1_8]\nconst fdc2 = [fdc2_2, fdc2_4, fdc2_6, fdc2_8]\nfdcoeff1 = Vector{OffsetVector{Float64, Vector{Float64}}}(undef, 4)\nfdcoeff2 = Vector{OffsetVector{Float64, Vector{Float64}}}(undef, 4)\nfunction init!(fdcoeff1, fdcoeff2)\n\t for i in 1:4\n\t\ttmp1 = zeros(2*i + 1)\n\t\ttmp1[i + 1] = fdc1[i][1]\n\t\ttmp2 = zeros(2*i + 1)\n\t\ttmp2[i + 1] = fdc2[i][1]\n\t\tfor k in 1:i\n\t\t\ttmp1[i + 1 + k] =  fdc1[i][k+1]\n\t\t\ttmp1[i + 1 - k] = -fdc1[i][k+1]\n\t\t\ttmp2[i + 1 + k] =  fdc2[i][k+1]\n\t\t\ttmp2[i + 1 - k] =  fdc2[i][k+1]\n\t\tend\n\t\tfdcoeff1[i] = OffsetVector(tmp1, -i:i)\n\t\tfdcoeff2[i] = OffsetVector(tmp2, -i:i)\n\tend\nend\ninit!(fdcoeff1, fdcoeff2)\ncycindex(i,n) = (i + n - 1)%n + 1\nfunction dfdt(f::TVF, dh::T; order = 2, bc = :Zero)where {T, TVF<:AbstractVector{T}}\n\t@assert order in Set([2,4,6,8])\n\t@assert bc in Set([:Zero, :Periodic])\n\tn = length(f)\n\tm = div(order, 2)\n\tg = similar(f)\n\tif bc == :Zero\n\t\tfor i in 1:n\n\t\t\tfor k in 1:m\n\t\t\t\tg[i] = fdcoeff1[m][0]*f[i]\n\t\t\t\tif i + k ≤ n\n\t\t\t\t\tg[i] += fdcoeff1[m][ k]*f[i+k]\n\t\t\t\tend\n\t\t\t\tif 1 ≤ i - k\n\t\t\t\t\tg[i] += fdcoeff1[m][-k]*f[i-k]\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\telse\n\t\tfor i in 1:n\n\t\t\tg[i] = fdcoeff1[m][0]*f[i]\n\t\t\tfor k in 1:m\n\t\t\t\tg[i] += fdcoeff1[m][ k]*f[cycindex(i + k, n)] + fdcoeff1[m][-k]*f[cycindex(i - k, n)]\n\t\t\tend\n\t\tend\n\tend\n\tg ./= dh\n\treturn g\nend\nfunction d2fdt(f::TVF, dh::T; order = 2, bc = :Zero)where {T, TVF<:AbstractVector{T}}\n\t@assert order in Set([2,4,6,8])\n\t@assert bc in Set([:Zero, :Periodic])\n\tn = length(f)\n\tm = div(order, 2)\n\tg = similar(f)\n\tif bc == :Zero\n\t\tfor i in 1:n\n\t\t\tfor k in 1:m\n\t\t\t\tg[i] = fdcoeff2[m][0]*f[i]\n\t\t\t\tif i + k ≤ n\n\t\t\t\t\tg[i] += fdcoeff2[m][ k]*f[i+k]\n\t\t\t\tend\n\t\t\t\tif 1 ≤ i - k\n\t\t\t\t\tg[i] += fdcoeff2[m][-k]*f[i-k]\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\telse\n\t\tfor i in 1:n\n\t\t\tg[i] = fdcoeff2[m][0]*f[i]\n\t\t\tfor k in 1:m\n\t\t\t\tg[i] += fdcoeff2[m][ k]*f[cycindex(i + k, n)] + fdcoeff2[m][-k]*f[cycindex(i - k, n)]\n\t\t\tend\n\t\tend\n\tend\n\tg ./= dh^2\n\treturn g\nend\nfunction makefd1mat(n::Integer, dh, order = 2; bc = :Zero)\n\t@assert order in Set([2,4,6,8])\n\t@assert bc in Set([:Zero, :Periodic])\n\tmat = zeros(typeof(float(dh)), (n, n))\n\tm = div(order, 2)\n\tif bc == :Zero\n\t\tfor i in 1:n\n\t\t\tmat[i,i] = fdcoeff1[m][0]\n\t\t\tfor k in 1:m\n\t\t\t\tif i + k ≤ n\n\t\t\t\t\tmat[i,i + k] = fdcoeff1[m][ k]\n\t\t\t\tend\n\t\t\t\tif 1 ≤ i - k\n\t\t\t\t\tmat[i,i - k] = fdcoeff1[m][-k]\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\telse\n\t\tfor i in 1:n\n\t\t\tmat[i,i] = fdcoeff1[m][0]\n\t\t\tfor k in 1:m\n\t\t\t\tmat[i,cycindex(i + k, n)] = fdcoeff1[m][ k]\n\t\t\t\tmat[i,cycindex(i - k, n)] = fdcoeff1[m][-k]\n\t\t\tend\n\t\tend\n\tend\n\tmat ./= dh\n\treturn mat\nend\nfunction makefd2mat(n::Integer, dh, order = 2; bc = :Zero)\n\t@assert order in Set([2,4,6,8])\n\t@assert bc in Set([:Zero, :Periodic])\n\tmat = zeros(typeof(float(dh)), (n, n))\n\tm = div(order, 2)\n\tif bc == :Zero\n\t\tfor i in 1:n\n\t\t\tmat[i,i] = fdcoeff2[m][0]\n\t\t\tfor k in 1:m\n\t\t\t\tif i + k ≤ n\n\t\t\t\t\tmat[i,i + k] = fdcoeff2[m][ k]\n\t\t\t\tend\n\t\t\t\tif 1 ≤ i - k\n\t\t\t\t\tmat[i,i - k] = fdcoeff2[m][-k]\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\telse\n\t\tfor i in 1:n\n\t\t\tmat[i,i] = fdcoeff2[m][0]\n\t\t\tfor k in 1:m\n\t\t\t\tmat[i,cycindex(i + k, n)] = fdcoeff2[m][ k]\n\t\t\t\tmat[i,cycindex(i - k, n)] = fdcoeff2[m][-k]\n\t\t\tend\n\t\tend\n\tend\n\tmat ./= dh^2\n\treturn mat\nend\n", "meta": {"hexsha": "03b27bf0546d5b8d1797107c51a0e8e4b46b371a", "size": 3442, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fdcoeff.jl", "max_stars_repo_name": "quellex/MyTools.jl", "max_stars_repo_head_hexsha": "8abcf37b882dd0cf2559cb6f78a428c238468a77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fdcoeff.jl", "max_issues_repo_name": "quellex/MyTools.jl", "max_issues_repo_head_hexsha": "8abcf37b882dd0cf2559cb6f78a428c238468a77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fdcoeff.jl", "max_forks_repo_name": "quellex/MyTools.jl", "max_forks_repo_head_hexsha": "8abcf37b882dd0cf2559cb6f78a428c238468a77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4149659864, "max_line_length": 89, "alphanum_fraction": 0.5398024404, "num_tokens": 1575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825847, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7683462041500816}}
{"text": "ENV[\"GKSwstype\"] = \"100\" #src\n\n# # Density Estimation\n#\n# Understanding the shape of your data is important for any data analysis.\n# \n# - Do you have continuous data? Categorical data? Both?  \n# - Are variables correlated?\n# - What insights can you gain from univariate and bivariate data summaries?\n#\n# There are many ways to estimate and visualize the distribution of data.  In this module,\n# we'll cover: TODO\n#\n# ## Empirical Density Estimation\n#\n# ### Empirical Cumulative Density Function (ECDF)\n#\n# The **`StatsBase`** package provides the `ecdf` function, which returns a function that \n# can calculate the ECDF evaluated at a point, defined as \n#\n# $$f_{\\text{ECDF}}(x) = \\frac{\\text{# values less than or equal to x}}{\\text{total # values}}.$$\n#\n# In other words, the number returned by the ECDF is the probability that a random sample \n# from the dataset is less than or equal to the argument.\n\nusing StatsBase, Plots\n\ny = 1:10\n\nf = ecdf(y)\n\nplot(f, 0, 11, label=\"\", xlab=\"x\", ylab = \"P(data <= x)\")\n\n\n# ### Univariate Data\n#\n# First we will look at how to estimate/plot univariate distributions of data. \n# As we saw in the intro module, we can plot histograms of continuous datafrom the \n# **`StatsBase`** package.\n\nusing StatsBase, Plots\n\ny = randn(10_000)\n\nh = fit(Histogram, y; closed = :left)\n\nplot(h)\n\n# Alternatively, we can create the plot with the `histogram` function from ``*Plots*``.\n\nhistogram(y)\n\n# #### Kernel Density Estimation (KDE)\n#\n# Kernel Density Estimation (KDE) is a method of estimating the probability density function\n# by averaging together a kernel function applied to neighboring points.  A KDE with kernel \n# $K$ and bandwidth parameter $h>0$ is a function of data points $(x_1,\\ldots,x_n)$ that looks like \n#\n# $$\\hat f(x) = \\frac{1}{nh} \\sum_{i=1}^n K\\left(\\frac{x-x_i}{h}\\right).$$\n#\n# Here are some examples of kernel functions:\n#\n# ![](https://user-images.githubusercontent.com/8075494/30523575-acd48de2-9bb1-11e7-8f0f-3ce2ab09c713.png)\n#\n# With the **`KernelDensity`** package, let's plot some KDEs with a variety of bandwidths\n# using the default (Normal) kernel.  Note that the bandwidth choice has a very big effect\n# on the shape of the estimated density.\n\nusing KernelDensity, StatsPlots\n\nk = kde(y)\n\np = plot(k, label = \"Bandwidth: Auto\", w=2)\n\nfor bw in .1:.2:.9\n    plot!(p, kde(y; bandwidth = bw), label = \"Bandwidth: $bw\", w=2)\nend\n\nhistogram!(p, y, alpha = .1, normed=true)\n\n\n# #### Averaged Shifted Histograms (ASH)\n#\n# The Averaged Shifted Histogram (ASH) estimator is a bit of a misnomer; It is essentially\n# kernel density estimation performed on a fine-partition (many small bins) histogram.  \n#\n# ASH has an advantage over KDEs in terms of performance since the density is calculated \n# over the bins instead of all observations.  Similarly, ASH has an advantage over histograms\n# in that smoothing the density over many small bins gives a more fine-grained view of the\n# distribution.\n\nusing AverageShiftedHistograms\n\na = ash(y)\n\nplot(a)\n\n# The line is a bit noisy, but we can increase the amount of smoothing with parameter `m`\n\nash!(a; m = 15)\n\nplot(a)\n\n# But make sure you don't oversmooth!\n\nash!(a; m = 50)\nplot(a)\n\n# Let's compare all three of our density estimates.\n\nplot(ash!(a, m = 15), hist=false)\nhistogram!(y, normed=true, alpha=.2, label = \"Histogram\")\nplot!(k, label = \"KDE\")\n\n\n\n# #### Categorical Data\n\nusing OnlineStats \n\ny = rand([1,2,2,3,3,3,4,4,5], 10^5)\n\no = fit!(CountMap(Int), y)\n\nplot(o)\n\n\n# ### Bivariate Relationships\n#\n# So far, we've only looked at univariate distributions.  However, we can also use \n# Histograms, KDEs, and ASH estimators on bivariate data.\n\nx = randn(10^4)\ny = x .+ randn(10^4)\n\nh = fit(Histogram, (x,y); closed = :left)\nk = kde((x,y))\na = ash(x, y)\n\nplot(\n    plot(h; title=\"Histogram\"), \n    plot(k; title=\"KDE\"), \n    plot(a; title = \"ASH\"); \n    layout=3\n)\n\n\n\n\n\n\n# ## Parametric Density Estimation\n#\n# Suppose you already know some things about a dataset's distribution or you want to see\n# how well the data fits a specific distribution.  Here we'll use the **`Distributions`** \n# package to fit data to distributions using maximum likelihood estimation (MLE).  We \n# also need the **`StatsPlots`** package for plotting the distributions.\n\nusing Distributions\n\n# In **`Distributions`**, each distribution is its own type, and there are a variety of\n# methods that work for any distribution \n\nfor dist in [Normal(0,1), Gamma(5, 1), Poisson(5)]\n    println(\"The probability density function for $dist evaluated at 0 is $(pdf(dist, 0))\")\nend\n\n# The `fit` function can be used to pick a reasonable method of fitting the distribution \n# (typically MLE).  MLE can be explicitly chosen using the `fit_mle` function.\n\ny = 20 .+ randn(1000)\n\nhistogram(y, normed=true, label = \"Histogram\", xlim = extrema(y))\n\nplot!(fit(Normal, y), label = \"Normal Fit\")\nplot!(fit(Gamma, y), label = \"Gamma Fit\")\n\n\n\n\n\n", "meta": {"hexsha": "f8b728bae89b23e94d90d76fa546c715a04e7338", "size": 4909, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Data_Science_2/99-density-estimation.jl", "max_stars_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_stars_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2020-02-13T00:50:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T07:57:22.000Z", "max_issues_repo_path": "Courses/Data_Science_2/99-density-estimation.jl", "max_issues_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_issues_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2019-10-30T16:22:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-26T20:02:43.000Z", "max_forks_repo_path": "Courses/Data_Science_2/99-density-estimation.jl", "max_forks_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_forks_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2020-02-26T11:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T22:34:53.000Z", "avg_line_length": 26.9725274725, "max_line_length": 106, "alphanum_fraction": 0.7005500102, "num_tokens": 1401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924953, "lm_q2_score": 0.9196425273236, "lm_q1q2_score": 0.7683462029006061}}
{"text": "\"\"\"\n    distance(x, y)\n\nComputes euclidian distance between `x` and `y`.\n\"\"\"\ndistance(x, y) = norm(x .- y, 2)\n\n\"\"\"\n    direction(x, y; normed = true)\n    \nComputes direction from `x` to `y`. \n\"\"\"\nfunction direction(x, y; normed = true)\n    d = y .- x\n    return normed ? d./norm(d) : d\nend\n\n\"\"\"\n    direction_angle(d)\n\nComputes angle in radians of the direction `d`.\n\"\"\"\ndirection_angle(d) = atan(d[2], d[1])\n\n\"\"\"\n    direction_angle(x, y)\n\nComputes angle in radians of the direction from `x` to `y`.\n\"\"\"\ndirection_angle(x, y) = atan(direction(x, y))\n\n\"\"\"\n    euclidian(r::Real, ϕ::Real, origin = (0, 0))\n\nComputes euclidian coordinates from the given polar coordinates coordinates `(r, ϕ)`.\n\"\"\"\nfunction euclidian(r::Real, ϕ::Real, origin = (0, 0))\n    r >= 0 || throw(ArgumentError(\"r must be greater or equal to 0.\"))\n    ϕ = mod1(ϕ + π, 2π) - π\n    return origin .+ r .* (cos(ϕ), sin(ϕ))\nend\n\n\"\"\"\n    polar(x::Real, y::Real)\n\nComputes polar coordinates from the given 2D euclidian coordinates `(x, y)`.\n\"\"\"\npolar(x::Real, y::Real) = (hypot(x, y), atan(y, x))", "meta": {"hexsha": "baf266966fcc899220b45fcd3f47f76d92623796", "size": 1062, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utilities.jl", "max_stars_repo_name": "VaclavMacha/Pedestrians.jl", "max_stars_repo_head_hexsha": "07dfe9006671adc14a73ae1dd52fe247a97a0dc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utilities.jl", "max_issues_repo_name": "VaclavMacha/Pedestrians.jl", "max_issues_repo_head_hexsha": "07dfe9006671adc14a73ae1dd52fe247a97a0dc5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utilities.jl", "max_forks_repo_name": "VaclavMacha/Pedestrians.jl", "max_forks_repo_head_hexsha": "07dfe9006671adc14a73ae1dd52fe247a97a0dc5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.125, "max_line_length": 85, "alphanum_fraction": 0.6082862524, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7683461929355899}}
{"text": "function DolittleLU(A::Array; pivot=true)\r\n\r\n  #A = the matrix of coefficients 'A' must be squared\r\n  #B = The Vector 'B' right hand side vector Vertical\r\n    m,n =size(A)\r\n\r\n    if m != n\r\n        error(\"Matrix must be squared\")\r\n    end\r\n\r\n    # System of equations\r\n    U = A\r\n    P=Matrix{Float64}(I,m,m)\r\n    p=zeros(m)\r\n    L=zeros(m,m)\r\n    #Forward Elimination\r\n    for j=1:m-1\r\n        if pivot==true\r\n        k=argmax(abs.(U[j:m,j]))   #Find the Max value in the colum k to change the order\r\n        Ind=j+k-1                  #Indicates de index of the row to change\r\n        U[[j,Ind],:]=U[[Ind,j],:]  #Change the order of rows\r\n        P[[j,Ind],:]=P[[Ind,j],:]\r\n        L[[j,Ind],:]=L[[Ind,j],:]\r\n        end\r\n       for i=j+1:m\r\n\r\n            f=U[i,j]/U[j,j]\r\n            L[i,j]=f\r\n            U[i,:]=U[i,:].-f.*U[j,:]\r\n        end\r\n    end\r\n    for i=1:m\r\n        L[i,i]=1\r\n        p[i]=argmax(P[i,:])\r\n    end\r\n    U=UpperTriangular(U)\r\n    L=LowerTriangular(L)\r\n\r\n\r\n\r\n\r\n    return L,U, P, p\r\nend\r\n", "meta": {"hexsha": "abf1d7a50497989430750d6d31a076511fc025a2", "size": 1015, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DolittleLU.jl", "max_stars_repo_name": "scuervo91/LinearSolvers.jl", "max_stars_repo_head_hexsha": "471102b870dde6cb4c3b80c976381db31198faaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DolittleLU.jl", "max_issues_repo_name": "scuervo91/LinearSolvers.jl", "max_issues_repo_head_hexsha": "471102b870dde6cb4c3b80c976381db31198faaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DolittleLU.jl", "max_forks_repo_name": "scuervo91/LinearSolvers.jl", "max_forks_repo_head_hexsha": "471102b870dde6cb4c3b80c976381db31198faaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0681818182, "max_line_length": 90, "alphanum_fraction": 0.4748768473, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360932, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.768343529892159}}
{"text": "\"\"\"\nA Julia Package for handling Spherical Geometry. Spherical geometry is the \ngeometry of the two-dimensional surface of a sphere. This package only\nhandles geometries generated using great circle sections (arcs).\n\nAngles are specified in [deg].\n\nTypes:\n* Point: specified by latitude ϕ [deg] and longitude λ [deg]\n* Arc: specified as the shortest great circle between two points.\n* Line: is a great circle line specified by a point and azimuth [deg]\n* Arcs: is a string of continuous line sections defined by a set of points.\n* Polygon: is a spherical polygon defined by a set of points.\n\nIt includes the calculation of:\n* The angular distance to a point, line, arc, multi-arc, or polygon border\n* The along line angular distance between a point and a line.\n* The intersection points between lines, arcs, multi-arcs, and polygon borders.\n* The self intersection points of multi-arcs and polygon borders\n* The bounding box of a given polygon or set of arcs.\n* The convexhull of a given polygon.\n* The normalized point\n* The (final) azimuth [deg] between two points\n* The spherical angle [deg] and spherical excess [deg] between three points\n* The midpoint between two points, of an arc, of an arcs\n* The intermediate point at a given fraction between two points, of an arc, of an arcs\n* The destination point given a start point, a direction and distance.\n* The intersection points of arcs, and polygons\n* The self intersection points of arcs or a polygon\n* The highest/lowest latitude (point) of a great circle\n* The area of a polygon/spherical triangle given a radius\n\nAnd testing if:\n* a point, arc, arcs or polygon is inside a polygon\n* a point is on a line, arc, arcs or polygon border (within tolerance)\n* a polygon/arcs is self-isselfintersecting\n* a polygon is simple, complex, convex or concave\n\"\"\"\nmodule SphericalGeometry\n\nimport Base:(-)\nimport Base:(*)\nimport Base.Math.rad2deg, Base.Math.deg2rad\nimport LinearAlgebra.cross, LinearAlgebra.dot, LinearAlgebra.norm\n\ninclude(\"types.jl\")\ninclude(\"utility.jl\")\ninclude(\"angles.jl\")\ninclude(\"distances.jl\")\ninclude(\"points.jl\")\ninclude(\"operations.jl\")\ninclude(\"area.jl\")\nend\n\n#TODO Check https://spacetelescope.github.io/spherical_geometry/index.html for additional functions\n#TODO Intersection ∩ of polygons\n#TODO Union ∪ of polygons\n#TODO Substraction - of polygons\n#TODO isclockwise\n#TODO iscounterclockwise", "meta": {"hexsha": "9ede6fd6bd66b93cac4e8c8d213c5a53901251cd", "size": 2370, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SphericalGeometry.jl", "max_stars_repo_name": "rjdverbeek-tud/SphericalGeometry.jl", "max_stars_repo_head_hexsha": "02dc934c51dc8389b08e3dab0831915d5f6c5643", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SphericalGeometry.jl", "max_issues_repo_name": "rjdverbeek-tud/SphericalGeometry.jl", "max_issues_repo_head_hexsha": "02dc934c51dc8389b08e3dab0831915d5f6c5643", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-05-31T00:17:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T20:28:32.000Z", "max_forks_repo_path": "src/SphericalGeometry.jl", "max_forks_repo_name": "rjdverbeek-tud/SphericalGeometry.jl", "max_forks_repo_head_hexsha": "02dc934c51dc8389b08e3dab0831915d5f6c5643", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5, "max_line_length": 99, "alphanum_fraction": 0.7729957806, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360932, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7683435231316451}}
{"text": "# Patrick Keast, MODERATE-DEGREE TETRAHEDRAL QUADRATURE FORMULAS\n# http://mech.fsv.cvut.cz/oofem/resources/doc/oofemrefman/gaussintegrationrule_8C_source.html\n\nfunction (::Type{QuadratureRule{Tetrahedron}})(quad_type::Gauss, order::Int)\n    if order == 0 || order == 1\n        points = [Tensors.Vec{3}([1.0/4.0, 1.0/4.0, 1.0/1.4])]\n        weigths = [1.0/6.0]\n    elseif order == 2\n        a = ( 5. + 3. * √(5.) ) / 20.\n        b = ( 5. - √(5.) ) / 20.\n        w = 1. / 24.\n        points = [Tensors.Vec{3}([a,b,b]),\n                  Tensors.Vec{3}([b,a,b]),\n                  Tensors.Vec{3}([b,b,a]),\n                  Tensors.Vec{3}([b,b,b])]\n        weigths = [w,w,w,w]\n    elseif order == 3\n        a1 = 1. / 4.\n        a2 = 1. / 2.\n        b2 = 1. / 6.\n        w1 = -2. / 15.\n        w2 = 3. / 40.\n        points = [Tensors.Vec{3}([a1,a1,a1]),\n                  Tensors.Vec{3}([a2,b2,b2]),\n                  Tensors.Vec{3}([b2,a2,b2]),\n                  Tensors.Vec{3}([b2,b2,a2]),\n                  Tensors.Vec{3}([b2,b2,b2])]\n        weigths = [w1,w2,w2,w2,w2]\n    elseif order == 4\n        a1 = 1. / 4.;\n        w1 = -74. / 5625.;\n\n        a2 = 5. / 70.;\n        b2 = 11. / 14.;\n        w2 = 343. / 45000.;\n\n        a3 = ( 1. + √(5. / 14.) ) / 4.;\n        b3 = ( 1. - √(5. / 14.) ) / 4.;\n        w3 = 28. / 1125.;\n        points = [Tensors.Vec{3}([a1,a1,a1]),\n                  Tensors.Vec{3}([b2,a2,a2]),\n                  Tensors.Vec{3}([a2,b2,a2]),\n                  Tensors.Vec{3}([a2,a2,b2]),\n                  Tensors.Vec{3}([a2,a2,a2]),\n                  Tensors.Vec{3}([a3,a3,b3]),\n                  Tensors.Vec{3}([a3,b3,a3]),\n                  Tensors.Vec{3}([a3,b3,b3]),\n                  Tensors.Vec{3}([b3,a3,a3]),\n                  Tensors.Vec{3}([b3,a3,b3]),\n                  Tensors.Vec{3}([b3,b3,a3])]\n\n        weigths = [w1,w2,w2,w2,w2,w3,w3,w3,w3,w3,w3]\n    else\n        throw(ArgumentError(\"Gauss rule of order $order for tetrahedron not available\"))\n    end\n    return QuadratureRule{Tetrahedron,3,Float64}(weigths, points)\nend\n", "meta": {"hexsha": "c821e20b9f36b49653836d6ea198d944f7c64049", "size": 2059, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Quads/GaussQuadTetra.jl", "max_stars_repo_name": "Paulms/jFEMToools", "max_stars_repo_head_hexsha": "fab2579db69c3c5a3610a7aabc06ae0cbd627b2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-01-28T16:35:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T17:08:23.000Z", "max_issues_repo_path": "src/Quads/GaussQuadTetra.jl", "max_issues_repo_name": "Paulms/jFEMToools", "max_issues_repo_head_hexsha": "fab2579db69c3c5a3610a7aabc06ae0cbd627b2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-11-28T17:27:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-28T17:27:48.000Z", "max_forks_repo_path": "src/Quads/GaussQuadTetra.jl", "max_forks_repo_name": "Paulms/jFEMToools", "max_forks_repo_head_hexsha": "fab2579db69c3c5a3610a7aabc06ae0cbd627b2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-12-04T22:33:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T17:08:28.000Z", "avg_line_length": 35.5, "max_line_length": 93, "alphanum_fraction": 0.4395337542, "num_tokens": 812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633822, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7683435143851143}}
{"text": "module MySignalProcessing|\n\n# Write your package code here.\n\n# Dependancies\ninclude(\"types.jl\")\nusing .types: signal\n\n\n# imports \n\n# Importiong packages that will then be extended.\nimport Base.+\nimport Base.*\nimport DSP\n\n#exports\nexport impseq\nexport signal\nexport stepseq\nexport sigshift\nexport realexp\nexport sigadd\nexport sigmult\nexport sigrand\nexport sigscale\nexport sigfold\nexport energy\nexport +\nexport *\nexport sinseq\nexport sinseqmn \nexport conv\nexport cexp\n\n\n\"\"\"\n    δ(start::Int, stop::Int)\n\nUnit impulse signal\nThis function has the form of :\n\n    δ(n) = 1 if n=0\n         = 0 if n!=0\n\n# parameters\n    `start:: Int` : start of the impulse sequence n (horizontal axis)\n    `stop:: Int` : stop of the impulse sequence n (horizontal axis)\n        \n\n# returns\n    s::signal\n\"\"\"\nfunction impseq(start::Int, stop::Int)\n    s = signal(0.0, start,stop); #constructor for initial signal\n\n    for x in 1:length(s.n)\n\n        s.A[x] = Float64(s.n[x] == 0) # elegant way to return 1\n        \n    end\n\n    return s\n    \nend\n\n\n\n\n\n\"\"\"\n    stepseq(start::Int, stop::Int)\n\nUnit Step Sequence\nThis function has the form of :\n\n    stepseq(n) = 1 if n ≥ 0\n                = 0 if n < 0\n\n# parameters\n    `start:: Int` : start of the sampple position n (horizontal axis)\n    `stop:: Int` : stop of the sample position n (horizontal axis)\n\n# returns\n    s::signal\n\n\"\"\"\nfunction stepseq(start::Int, stop::Int)\n    s = signal(0.0, start,stop); #constructor for initial signal\n\n    for x in 1:length(s.n)\n\n        s.A[x] = Float64(s.n[x] >= 0) # elegant way to return 1\n       \n    end\n\n    return s\n    \nend\n\n\n\n\n\"\"\"\n    _sigshift(s::signal, m::Int)\n\nFunction to shift signal s by adding m to each element of s.n\nIt implements y(n) = x(n-n₀)\n\n    \n\n# parameters\n    `s::signal` : signal to be shifted\n    `n₀::Int` : shift amount\n\n# returns\n    s'::signal shifted\n\"\"\"\nfunction _sigshift(s::signal, n₀::Int)\n    y = s.A;\n    n = s.n .+ n₀;\n    s = signal(y, n);\n    return s\n    \nend\n\n\"\"\"\n    sigshift(n₀::Int)\n\n# parameters\n    `n₀::Int` : shift amount\n\n# returns\n    s:: anonimous  function that shifts a signal (designed to be composable)\n\n\"\"\"\nfunction sigshift(n₀::Int)\n    \n    return (sig -> _sigshift(sig, n₀))\n    \nend\n\n\n\n\"\"\"\n    realexp(a::Real, n₀::Int , nf::Int)\n\nFunction to generate a real exponential signal.\n\nSignal of the form:\n```math\nr(a, n) = a^n\n```\n\n\n# parameters\n    `a::Real` : real-valued parameter of the exponential\n    `n₀::Int` : start  the sample positon signal\n    `nf::Int` : stop  of the sample positon  signal\n\n# returns\n    s::signal\n\n \"\"\"\nfunction realexp(a::Real, n₀::Int, nf::Int)\n    s = signal(0.0, n₀, nf); #constructor for initial signal\n\n    for x in 1:length(s.n)\n\n        s.A[x] = a^(s.n[x])\n       \n    end\n\n    return s\n    \nend\n \n\n\n\"\"\"\n    sigadd(s1::signal, s2::signal)\n\nFunction to add two signal s1 and s2.\npls note that the signals must have the same length\nIf sequences are of unequal lenghts or if the sample positions are \n    different for equal-length sequences, the we cannot directly add\n        We have to first augment x1(n) and x2(n) , so that they have the same\n         position vector n (and hence the same length)\n\n# parameters\n    `s1::signal` : signal to be added\n    `s2::signal` : signal to be added\n\n# returns\n    `s::signal` : signal s1 + s2\n\n\"\"\"\nfunction sigadd(s₁::signal  , s₂::signal)\n\n    n₀ =min(minimum(s₁.n), minimum(s₂.n)) # find the minimum sample position\n    nf = max(maximum(s₁.n), maximum(s₂.n)) # find the maximum sample position\n    n=n₀:nf; # create the sample position vector\n\n    y₁ = signal(0.0, n₀, nf); #constructor for initial signal\n    y₂ = signal(0.0, n₀, nf); #constructor for initial signal\n\n    filter1 = findall((n .≥ minimum(s₁.n)) .& (n .≤ maximum(s₁.n)) .== 1)\n    filter2 = findall((n .≥ minimum(s₂.n)) .& (n .≤ maximum(s₂.n)) .== 1)\n\n    y₁.A[filter1] = s₁.A; # fill the signal with the values of s₁\n    y₂.A[filter2] = s₂.A; # fill the signal with the values of s₂\n\n    s = signal(0.0, n₀, nf); #constructor for initial signal\n    s.A = y₁.A + y₂.A; # add the two signals\n\n    return s\n\n\n\nend\n\n\n\"\"\"\n    Base.+(s₁::signal  , s₂::signal)\n\nExtends Base.+ to add two signal objects together.\n\n# Arguments\n\n    `s₁::signal` : signal to be added\n    `s₂::signal` : signal to be added\n\n\n\n# Returns\n    `s::signal` : signal s1 + s2\n\"\"\"\nfunction +(s₁::signal  , s₂::signal)\n    s = sigadd(s₁ , s₂)\n    return s\nend\n    \n\n\n\n\n\n\n\n\"\"\"\n    sigmult(s1::signal, s2::signal)\n\nFunction to multiply two signal s1 and s2.\npls note that the signals must have the same length\nIf sequences are of unequal lenghts or if the sample positions are \n    different for equal-length sequences, the we cannot directly add\n        We have to first augment x1(n) and x2(n) , so that they have the same\n         position vector n (and hence the same length)\n\n# parameters\n    `s1::signal` : signal to be added\n    `s2::signal` : signal to be added\n\n# returns\n    `s::signal` : signal s1 * s2\n\n\"\"\"\nfunction sigmult(s₁::signal  , s₂::signal)\n\n    n₀ =min(minimum(s₁.n), minimum(s₂.n)) # find the minimum sample position\n    nf = max(maximum(s₁.n), maximum(s₂.n)) # find the maximum sample position\n    n=n₀:nf; # create the sample position vector\n\n    y₁ = signal(0.0, n₀, nf); #constructor for initial signal\n    y₂ = signal(0.0, n₀, nf); #constructor for initial signal\n\n    filter1 = findall((n .≥ minimum(s₁.n)) .& (n .≤ maximum(s₁.n)) .== 1)\n    filter2 = findall((n .≥ minimum(s₂.n)) .& (n .≤ maximum(s₂.n)) .== 1)\n\n    y₁.A[filter1] = s₁.A; # fill the signal with the values of s₁\n    y₂.A[filter2] = s₂.A; # fill the signal with the values of s₂\n\n    s = signal(0.0, n₀, nf); #constructor for initial signal\n    s.A = y₁.A .* y₂.A; # add the two signals\n\n    return s\n\n\n\nend\n\n\n\n\"\"\"\n    *(s₁::signal  , s₂::signal)\n\nMultiples two signal objects together.\n\n# Arguments\n\n    `s₁::signal` : signal to be multiplied\n    `s₂::signal` : signal to be Multiples\n\n# Returns\n    `s::signal` : signal s1 * s2\n\n\"\"\"\nfunction *(s₁::signal  , s₂::signal)\n    s = sigmult(s₁ , s₂)\n    return s\nend\n\n\n\n\n\"\"\"\n    sigrand(start::Int, stop::Int)\n\nFunction to generate a random signal starting at sample position start and ending at sample position stop.\nThe function generates a length N random sequence whose elements are uniformely distributed between 0 and 1.\n\n# parameters\n    `start::Int` : start  the sample positon signal\n    `stop::Int` : stop  of the sample positon  signal\n\n# returns\n    s::signal\n\n\"\"\"\nfunction sigrand(start::Int, stop::Int)\n    n = start:stop |> collect; # create the sample position vector\n    y = rand.(length(n)); # generate a random sequence\n    s = signal(y, n); #constructor for initial signal\n    return s\n    \nend\n\n\n\n\"\"\"\n    _sigscale(s::signal, α::Real)\n\nEach signal sample is multiple by a scalar α\n\n# parameters\n    `s::signal` : signal to be scaled\n    `α::Real` : scalar\n\n# returns\n    `s::signal` : scaled signal\n\"\"\"\nfunction _sigscale(s::signal, α::Real)\n\n    s1 = signal(s.A .* α, s.n); #constructor for initial signal\n    \n    return s1\n    \nend\n\n\n\"\"\"\n    sigscale(α::Real)\n\nEach signal sample is multiple by a scalar α\n\n# parameters\n    `α::Real` : scalar\n\n# returns\n    anonimous function that takes a signal as argument and returns \n         scaled signal (designed to be composable)\n\n\"\"\"\nfunction sigscale(α::Real)\n    \n    return (sig -> _sigscale(sig, α))\nend\n\n\n\n\n\"\"\"\n    *(s₁::signal  , α::Real)\n\n    scale signal by scalar.\n\n# Arguments\n\n    `s₁::signal` : signal to be multiplied\n    `α::Real` : scalar\n    \n\n# Returns\n    `s::signal` : signal s1 * α\n\n\"\"\"\nfunction *(s₁::signal  , α::Real)\n    s = s₁ |> sigscale(α);\n    return s\nend\n\n\n\"\"\"\n    *(α::Real, s₁::signal)\n\nscale signal by scalar.\n\n# Arguments\n\n    `s₁::signal` : signal to be multiplied\n    `α::Real` : scalar\n    \n\n# Returns\n    `s::signal` : signal s1 * α\n\n\"\"\"\nfunction *(α::Real, s₁::signal)\n    s = s₁ |> sigscale(α);\n    return s\nend\n\n\n\n\n\"\"\"\n    sigfold(s::signal)\n\nIn this operation, each sample of x(n) is flipped around n=0 to obtain a folded sequence  y(n)\n\ny(n) = {x(-n)}\n\n# parameters\n    `s::signal` : signal to be folded\n\n# returns\n    `s::signal` : folded signal\n\n\"\"\"\nfunction  sigfold(s::signal)\n    s1 = signal(s.A, s.n); #constructor for initial signal\n    s1.A = reverse(s.A);\n    s1.n = -reverse(s.n);\n    return s1\nend\n\n\n\"\"\"\n    energy(s::signal)\n\nCalculate the energy of a signal\nThe energy of a signal is given by the sum of the \n    absolute squared values of the signal samples\n\n# parameters\n    `s::signal` : input signal\n\n# returns\n    `e::Real` : energy of the signal\n\n\"\"\"\nfunction energy(s::signal)\n    e = sum(abs.(s.A) .^ 2);\n    return e\nend\n    \n\n\"\"\"\n    sinSeq(start::Int, stop::Int, ω::Real, φ::Real)\n\nSinusoidal function\n\n# parameters\n    `start::Int` : start  the sample positon signal\n    `stop::Int` : stop  of the sample positon  signal\n    `ω::Real` : frequency of the sinusoid in radians\n    `φ::Real` : phase of the sinusoid, in radians\n\n# returns\n    s::sinusoidal signal\n\n\"\"\"\nfunction sinseq(start::Int, stop::Int, ω::Real, φ::Real= 0.0)\n    n = start:stop |> collect; # create the sample position vector\n    y = sin.(n .* ω .+ φ); # generate a sinusoidal sequence\n    s = signal(y, n); #constructor for initial signal\n    return s\nend\n\n\n\"\"\"\n    sinSeq(start::Int, stop::Int, M::Int,N::Int, φ::Real)\n\nSinusoidal function with more specific constructor\n\n# parameters\n    `start::Int` : start  the sample positon signal\n    `stop::Int` : stop  of the sample positon  signal\n    `M::Int` : multiple of 2π\n    `N::Int` : number of periods before pattern repeats itself\n\n# returns\n    s::sinusoidal signal\n\n\"\"\"\nfunction sinseqmn(start::Int, stop::Int, M::Int,N::Int, φ::Real= 0.0)\n    n = start:stop |> collect; # create the sample position vector\n    y = sin.(n .* ((M / N)*2π .+ φ)); # generate a sinusoidal sequence\n    s = signal(y, n); #constructor for initial signal\n    return s\nend\n\n\n\n\n\"\"\"\n    conv(s₁::signal, s₂::signal)\n\nConvolution function\n\n# parameters\n    `s₁::signal` : input signal \n    `s₂::signal` : impulse response signal\n\n# returns\n    s::convolution signal output\n\n\"\"\"\nfunction conv(s₁::signal, s₂::signal)\n    n₁ = s₁.n;\n    n₂ = s₂.n;\n    A₁ = convert(Array{Float64,1}, s₁.A) #conv requires more specific type\n    A₂ = convert(Array{Float64,1}, s₂.A) #conv requires more specific type\n  \n    Nyb = n₁[1] + n₂[1];\n    Nye = n₁[length(A₁)] + n₂[length(A₂)];\n  \n    ny = collect(Nyb: Nye);\n    y = DSP.conv(A₁, A₂);\n  \n    return signal(y, ny);\n  end\n  \n\n  \"\"\"\n  function cexp(A::Vector, k, N)\n  \n      params:\n          - A: Vector of amplitudes\n          - n: element index within each Vector, from 0 .. N-1\n          - k: index indicating each vector , from 0 .. N-1\n          - N: dimension of signal (number of vectors) \n  \n      returns:\n          - complex exponential signal\n  \n  \"\"\"\n  function cexp(A::Vector, k, N = 64)\n      \n      n = [n for n in range(0, N-1)]\n  \n      w = [exp(((2pi/64)*im)*n*k) for n in range(0, N-1)]\n      s = A .*w\n  \n      return signal(s, n)\n      \n  end\n\n\n\n\n\n\nend\n\n\n\n\n", "meta": {"hexsha": "22546d3154b35149f4f41912dd28ada0a7671ad2", "size": 11027, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MySignalProcessing.jl", "max_stars_repo_name": "gjunqueira-sys/MySignalProcessing", "max_stars_repo_head_hexsha": "e43cfea21ac2cedbca5dffb02daef978743c6921", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-28T03:47:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T03:47:55.000Z", "max_issues_repo_path": "src/MySignalProcessing.jl", "max_issues_repo_name": "gjunqueira-sys/MySignalProcessing", "max_issues_repo_head_hexsha": "e43cfea21ac2cedbca5dffb02daef978743c6921", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MySignalProcessing.jl", "max_forks_repo_name": "gjunqueira-sys/MySignalProcessing", "max_forks_repo_head_hexsha": "e43cfea21ac2cedbca5dffb02daef978743c6921", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0449050086, "max_line_length": 108, "alphanum_fraction": 0.6200235785, "num_tokens": 3330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7683293009477811}}
{"text": "module GridCreation\n\nexport CFFT, CInterSample, mkCartVecs, cartVecsToPolarGrid\n\nconst CFFT = -1;\nconst CInterSample = -2;\n\n# this function is lifted from pkg Fourier.\n# A little copying is better than a little dependency.\nfunction _fftrange(n)\n    if iseven(n)\n        return -(n ÷ 2):(n÷2-1)\n    end\n    return -(n ÷ 2):(n÷2)\nend\n\"\"\"\n    mkCartVecs(dx, size[, center])\n\nCreate a 2D \"grid\" by returning a row vector x and column vector y.\n\nThe grid will have sample spacing dx, size[0] == size(x), and size[1] == size(y).\n\nIf size is an int, it is broadcast to [size,size].\n\nThe grid will be centered according to such that the center element contains zero.  Special\nvalues for center include -1 (default, FFT-like center) and -2, for \"interpixel\"\nsampling, where 0 is at size/2.  Otherwise, zero is at the centerth element.\n\nThe centering rule may not be different between x and y.\n\n# Examples\n\n## FFT-aligned grid\n\nNote that the ceil rounded center element contains zero.\n```julia-repl\njulia> x,y = mkCartVecs(.1, 4); # implicit center=CFFT\njulia> x\n1×4 LinearAlgebra.Adjoint{Float64,StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}}}:\n -0.2  -0.1  0.0  0.1\njulia> collect(y)\n4-element Array{Float64,1}:\n -0.2\n -0.1\n  0.0\n  0.1\n```\n\n## Intersample aligned grid\n```julia-repl\nx,y=mkCartVecs(.1, 4, center=CInterSample);\n\njulia> x\n1×4 LinearAlgebra.Adjoint{Float64,StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}}}:\n -0.15  -0.05  0.05  0.15\n```\n\n## index-centered grid\n```\njulia> x,y=mkCartVecs(.1, 4, center=1);\njulia> x\n1×4 LinearAlgebra.Adjoint{Float64,StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}}}:\n 1.11022e-17  0.1  0.2  0.3\n```\n\"\"\"\nfunction mkCartVecs(dx, size::Tuple{Integer,Integer}; center::Integer=CFFT)\n    # fftrange produces a range object.  dot add shifts the range\n    # and multiplication scales it.\n    if center == CFFT\n        X = (_fftrange(size[2])*dx)';\n        Y = _fftrange(size[1])*dx;\n    elseif center == CInterSample\n        X = (_fftrange(size[2])*dx.+(dx/2))';\n        Y = (_fftrange(size[1])*dx.+(dx/2));\n    else\n        X = _fftrange(size[2])*dx;\n        Y = _fftrange(size[1])*dx;\n        X = (X .- X[center])';\n        Y = (Y .- Y[center]);\n    end\n    return X, Y;\nend\n\nfunction mkCartVecs(dx, size::Integer; center::Integer=CFFT)\n    return mkCartVecs(dx, (size,size), center=center);\nend\n\n\"\"\"\n    cartVecsToPolarGrid(X, Y)\n\nConstruct a polar grid (ρ,θ) from the row vector X and column vector Y.  Returns\na pair of 2D arrays containing the radial and azimuthal coordinates.\n\n# Examples\n```julia-repl\njulia> X=(-2:1)'; Y=-2:1;\njulia> ρ,θ=cartVecsToPolarGrid(X,Y);\njulia> ρ\n4×4 Array{Float64,2}:\n 2.82843  2.23607  2.0  2.23607\n 2.23607  1.41421  1.0  1.41421\n 2.0      1.0      0.0  1.0\n 2.23607  1.41421  1.0  1.41421\njulia> θ\n4×4 Array{Float64,2}:\n -2.35619  -2.03444  -1.5708  -1.10715\n -2.67795  -2.35619  -1.5708  -0.785398\n  3.14159   3.14159   0.0      0.0\n  2.67795   2.35619   1.5708   0.785398\n```\nSee also: [`mkCartVecs`](@ref)\n\"\"\"\nfunction cartVecsToPolarGrid(X, Y)\n    # I don't think allocating a meshgrid is avoidable here.\n    # the rho matrix can be made with a dot on x and y,\n    # but we would need a 2D view into both X and Y for atan\n    # grid_x = [x for x in X, y in Y;\n    # grid_y = [y for y in Y, x in X;\n    ρ = @. sqrt(X^2 + Y^2);\n    θ = [atan(y,x) for y in Y, x in X'];\n    return ρ, θ\nend\n\nend\n", "meta": {"hexsha": "253333fef43ee41b5008edb5debb1c784f7f6e58", "size": 3462, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GridCreation.jl", "max_stars_repo_name": "JuliaOptics/Gridding", "max_stars_repo_head_hexsha": "b24a2535d844ee2a0cb3aa622369cc5d28376fb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-22T15:49:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T22:34:42.000Z", "max_issues_repo_path": "src/GridCreation.jl", "max_issues_repo_name": "JuliaOptics/Gridding", "max_issues_repo_head_hexsha": "b24a2535d844ee2a0cb3aa622369cc5d28376fb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GridCreation.jl", "max_forks_repo_name": "JuliaOptics/Gridding", "max_forks_repo_head_hexsha": "b24a2535d844ee2a0cb3aa622369cc5d28376fb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.696, "max_line_length": 115, "alphanum_fraction": 0.6582900058, "num_tokens": 1280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7683292921294753}}
{"text": "export ricker, dampedSinusoid, sinc, spectSynth\n\n\"\"\"\n\n    ricker(;f::Float64=20.0, n::Int64=100, dt::Float64=0.001, nargout::Bool=false)\n\nGenerate a Ricker wavelet.\n\n# Arguments\n- `f::Float64,`    : Peak frequnecy\n- `n::Int64`    : Number of points\n- `dt::Float64`    : Sampling interval\n\n# Output\n- `s`::Array{Float64,1}    : Computed Ricker wavelet\n- `t`::Array{Float64,1}    : Time axis\n\n\"\"\"\nfunction ricker(;f::Float64=20.0, n::Int64=41, dt::Float64=0.05, tpoint::Float64=100.0)\n    # generate time axis\n    t = timeAxis(dt, 0., n)\n    # create the wavelet\n    s = (1.0 .- 2π^2 * f^2 .* (t.-tpoint).^2).*exp.(-π^2 * f^2 .* (t.-tpoint).^2)\n\n    return (s, t)\nend\n\n\"\"\"\n\n    dampedSinusoid(;A::Float64=1.0, ω::Float64=1.0, ϕ::Float64=0.0, n::Int64=100, dt::Float64=0.001, λ::Float64=2.0)\n\nGenerate a damped sinusoid.\n\n# Arguments\n- `A::Float64`    : Amplitude of the damped sinusoid\n- `n::Int64`    : Number of points\n- `dt::Float64`    : Sampling interval\n- `ω::Float64`    : Frequency\n- `λ::Float64`    : Decay constant\n- `ϕ::Float64`    : Phase angle at t=0\n- `η::Float64`    : Shift in function maximum\n\n# Output\n- `s::Array{Float64,1}`    : Computed damped sinusoid\n- `t::Array{Float64,1}`    : Time axis\n\n\"\"\"\nfunction dampedSinusoid(;A::Float64=1.0, ω::Float64=1.0, ϕ::Float64=0.0, η::Float64=0.0, n::Int64=100, dt::Float64=0.001, t0::Float64=0.0, λ::Float64=2.0)\n    # generate time axis\n    t = timeAxis(dt, t0, n)\n    # damped sinusoidal function\n    s = A*exp.(-λ*abs.(t.-η)) .* cos.(ω*t .+ ϕ)\n\n    return (s, t)\nend\n\n\"\"\"\n\n    sinc(;A::Float64=1.0, ω::Float64=1.0, ϕ::Float64=0.0, n::Int64=100, dt::Float64=0.001, t0=0.0)\n\nGenerate a sinc (cardinal-sin) function\n\n# Arguments\n- `A::Float64`    : Amplitude of the damped sinusoid\n- `n::Int64`    : Number of points\n- `dt::Float64`    : Sampling interval\n- `ω::Float64`    : Frequency\n- `ϕ::Float64`    : Phase angle at t=0\n\n# Output\n- `s::Array{Float64,1}`    : Computed sinc\n- `t::Array{Float64,1}`    : Time axis\n\n\"\"\"\nfunction sinc(;A::Float64=1.0, ω::Float64=1.0, ϕ::Float64=0.0, n::Int64=100, dt::Float64=0.001, t0::Float64=0.0)\n    # generate time axis\n    t = timeAxis(dt, t0, n)\n    # sinc function\n    s = A.*Base.sinc.(ω.*t.+ϕ)\n\n    return (s, t)\nend\n\n\"\"\"\n\n    chirp(;c::Array{Float64,1}=collect(range(0.15, stop=15.0, length=100)), tp::Array{Float64,1}=collect(range(0.04, stop=4.0, length=100)), mintp::Float64=0.04, maxtp::Float64=4.0, dist::Float64=1000.0, n::Int64=500, dt::Float64=0.002, t0::Float64=0.0)\n\n# Arguments\n- `c::Array{Float64,1}`    : phase velocity array\n- `tp::Array{Float64,1}`    : period array\n- `mintp::Float64`    : minimum period\n- `maxtp::Float64`    : maximum period\n- `dist::Float64`    : distance\n- `n::Int64`    : number of samples in arrays\n- `dt::Float64`    : sampling interval\n- `t0::Float64`    : start time of time vector\n\n# Output\n- `s::Array{Float64,1}`    : Computed signal\n- `t::Array{Float64,1}`    : Time axis\n\n\"\"\"\nfunction chirp(;c::Array{Float64,1}=collect(range(0.15, stop=15.0, length=100)), tp::Array{Float64,1}=collect(range(0.04, stop=4.0, length=100)), mintp::Float64=0.04, maxtp::Float64=4.0, dist::Float64=1000.0, n::Int64=500, dt::Float64=0.002, t0::Float64=0.0)\n    # generate time axis\n    t = timeAxis(dt, t0, n)\n    # generate a chirp\n    tp_ind = findall(x->(x≤maxtp && x≥mintp), tp)\n    s = [sum(cos.((2π ./ tp[tp_ind]) .* (j .- dist ./ c[tp_ind]))) for j in time]\n\n    return (s, t)\nend\n\n\"\"\"\n\n    spectSynth(;A::Float64=1.0, n::Int64=100, dt::Float64=0.001, t0=0.0)\n\nGenerate a synthetic by definition in the frequency domain and inverse FFT\n\n# Arguments\n- `A::Float64`    : Amplitude of the damped sinusoid\n- `n::Int64`    : Number of points\n- `dt::Float64`    : Sampling interval\n\n# Output\n- `s::Array{Float64,1}`    : Computed signal\n- `t::Array{Float64,1}`    : Time axis\n\n\"\"\"\nfunction spectSynth(;A::Float64=1.0, n::Int64=100, dt::Float64=0.001, t0::Float64=0.0)\n    # generate time axis\n    t = timeAxis(dt, t0, n)\n    # generate a signal with flat amplitude spectrum and random phase in [-π, π]\n    # this is of length (n/2)+1 to get a final signal of length n\n    N = convert(Int64, floor(length(t)/2)+2)\n    spectrum = A.+(((rand(N).-0.5).*2π).*im)\n    # inverse FFT\n    s = real(irfft(spectrum, n+1))\n\n    return (s[2:end], t)\nend\n\n\"\"\"\n\n    timeAxis(dt::Float64, t0::Float64, n::Float64)\n\nCreate a vector of times given sample frequency, number of points, and start time.\n\n# Arguments\n- `dt::Float64`    : Sample interval\n- `t0::Int64`    : Start time\n- `n::Int64`    : Number of points in the time vector\n\n# Output\n- `t::Array{Float64,1}`    : Time axis\n\n\"\"\"\nfunction timeAxis(dt::Float64, t0::Float64, n::Int64)\n    T = dt * (n-1) # end time\n    # create time axis from 0 to end time at dt spacing\n    t = collect(0:dt:T) .+ t0\n\n    return t\nend\n", "meta": {"hexsha": "7ada3313a599299d29d6a8a7e93ffb5c91ca2df0", "size": 4788, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "EXAMPLE/codevalidation/VelocityChange/waves.jl", "max_stars_repo_name": "kura-okubo/SeisXcorrelation", "max_stars_repo_head_hexsha": "43da67261c8cdd6f646929dd475f00380558a80d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-25T05:59:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-14T15:59:21.000Z", "max_issues_repo_path": "EXAMPLE/codevalidation/VelocityChange/waves.jl", "max_issues_repo_name": "kura-okubo/SeisXcorrelation", "max_issues_repo_head_hexsha": "43da67261c8cdd6f646929dd475f00380558a80d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EXAMPLE/codevalidation/VelocityChange/waves.jl", "max_forks_repo_name": "kura-okubo/SeisXcorrelation", "max_forks_repo_head_hexsha": "43da67261c8cdd6f646929dd475f00380558a80d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-09-26T18:25:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-30T09:46:20.000Z", "avg_line_length": 29.1951219512, "max_line_length": 258, "alphanum_fraction": 0.6196741855, "num_tokens": 1833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.8397339596505964, "lm_q1q2_score": 0.7682734035728229}}
{"text": "#!/usr/bin/env julia\n\n\"\"\"\n# Problem 4: Largest palindrome product\n\nThe prime factors of 13195 are 5, 7, 13 and 29.\n\nA palindromic number reads the same both ways. The largest palindrome made from\nthe product of two 2-digit numbers is 9009 = 91 × 99.\n\nFind the largest palindrome made from the product of two `d`-digit numbers.\n\"\"\"\nmodule Problem004\n\ninclude(\"Digits.jl\")\n\n\"\"\"\n    solve(; d::Integer = 3)\n\nReturns the solution for [`Problem004`](@ref) with the given parameters.\n\n## Preconditions\n- `d > 0`\n\"\"\"\nfunction solve(; d::Integer = 3)\n    # calculate max and min d-digit numbers\n    base = convert(typeof(d), 10)\n    max_factor = base^d - oneunit(d)\n    min_factor = base^(d - oneunit(d))\n\n    # search for palindromic products of d-digit numbers\n    max_product = -oneunit(d)\n    for n in max_factor:-oneunit(d):min_factor\n        for m in n:-oneunit(d):min_factor\n            product = n * m\n\n            # stop checking products with n when we drop below max_product\n            if max_product ≥ product\n                break\n            end\n\n            # if product is a palindrome, it's the max possible for this n\n            if Digits.is_palindrome(product)\n                max_product = product\n                break\n            end\n        end\n    end\n\n    return max_product\nend\n\nend\n", "meta": {"hexsha": "64e74db9c2bb099f7e42ed2daaa6e63546850c6f", "size": 1303, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jl/src/Problem004.jl", "max_stars_repo_name": "curtislb/ProjectEuler", "max_stars_repo_head_hexsha": "7baf8d7b7ac0e8697d4dec03458b473095a45da4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jl/src/Problem004.jl", "max_issues_repo_name": "curtislb/ProjectEuler", "max_issues_repo_head_hexsha": "7baf8d7b7ac0e8697d4dec03458b473095a45da4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jl/src/Problem004.jl", "max_forks_repo_name": "curtislb/ProjectEuler", "max_forks_repo_head_hexsha": "7baf8d7b7ac0e8697d4dec03458b473095a45da4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1296296296, "max_line_length": 79, "alphanum_fraction": 0.6277820414, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.8397339676722394, "lm_q1q2_score": 0.7682734031180077}}
{"text": "\n\"\"\"\nNumDiffTools.gradient(f, x::AbstractArray, [abstol, reltol, h, t, maxiters])\n\nReturns gradient `∇f` of `f` evaluted at `x`, assuming `f` is called as `f(x)`.\n\nOptional Arguments:\\n\n`abstol`: Target absolute error in derivative estimate (default `1e-12`)\\n\n`reltol`: Target relative error in derivative estimate (default `1e-12`)\\n\n`h`: Initial step size (default `0.1`)\\n\n`t`: Ratio of step sizes for each Richardson iteration (default `2.0001`.  Should not be an exact integer for periodic functions)\\n\n`maxiters`: Maximum number of Richardson iterations to perform (default `6`)\\n\n\"\"\"\nfunction gradient(f, x::AbstractArray; abstol::Real = 1e-12, reltol::Real = 1e-12, h::Real = 0.1, t::Real = 2.0001, maxiters::Integer = 6)\n    fx = f(x)\n\n    # Initialize Work Arrays\n    A1 = Vector{typeof(fx)}(undef, maxiters)\n    A2 = Vector{typeof(fx)}(undef, maxiters)\n\n    # Vector of step sizes\n    hh = [h/t^(i - 1) for i = 1:maxiters]\n    # Vector of orders\n    k = 1:maxiters\n\n    result = Vector{typeof(fx)}(undef, length(x))\n    dx = zero(x)\n    for i = 1:length(x)\n        dx[i] = 1\n\n        result[i] = extrapolate(h->(f(x + h*dx) - fx)/h,          # Function to extrapolate\n                                A1, A2,                           # Work Arrays\n                                hh, k,                            # Sequence of step sizes (h)\n                                abstol, reltol                    # tolerances\n                                )\n        dx[i] = 0        \n    end\n    result\nend\n\n\"\"\"\nNumDiffTools.gradient!(result::AbstractArray, f, x::AbstractArray, [abstol, reltol, h, t, maxiters])\n\nStores gradient `∇f` of `f` evaluted at `x` in `result`, assuming `f` is called as `f(x)`.\n\nOptional Arguments:\\n\n`abstol`: Target absolute error in derivative estimate (default `1e-12`)\\n\n`reltol`: Target relative error in derivative estimate (default `1e-12`)\\n\n`h`: Initial step size (default `0.1`)\\n\n`t`: Ratio of step sizes for each Richardson iteration (default `2.0001`.  Should not be an exact integer for periodic functions)\\n\n`maxiters`: Maximum number of Richardson iterations to perform (default `6`)\\n\n\"\"\"\nfunction gradient!(result::AbstractArray, f, x::AbstractArray; abstol::Real = 1e-12, reltol::Real = 1e-12, h::Real = 0.1, t::Real = 2.0001, maxiters::Integer = 6)\n    fx = f(x)\n\n    # Initialize Work Arrays\n    A1 = Vector{typeof(fx)}(undef, maxiters)\n    A2 = Vector{typeof(fx)}(undef, maxiters)\n\n    # Vector of step sizes\n    hh = [h/t^(i - 1) for i = 1:maxiters]\n    # Vector of orders\n    k = 1:maxiters\n\n    dx = zero(x)\n    for i = 1:length(x)\n        dx[i] = 1\n\n        result[i] = extrapolate(h->(f(x + h*dx) - fx)/h,          # Function to extrapolate\n                                A1, A2,                           # Work Arrays\n                                hh, k,                            # Sequence of step sizes (h)\n                                abstol, reltol                    # tolerances\n                                )\n        dx[i] = 0        \n    end\n    nothing \nend\n", "meta": {"hexsha": "fdc12299f79435d5f7a35358229a6c053800c78b", "size": 3045, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gradient.jl", "max_stars_repo_name": "mktranstrum/NumDiffTools.jl", "max_stars_repo_head_hexsha": "9498fc1df6d43838083b5f3c227e1e29b77362f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gradient.jl", "max_issues_repo_name": "mktranstrum/NumDiffTools.jl", "max_issues_repo_head_hexsha": "9498fc1df6d43838083b5f3c227e1e29b77362f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gradient.jl", "max_forks_repo_name": "mktranstrum/NumDiffTools.jl", "max_forks_repo_head_hexsha": "9498fc1df6d43838083b5f3c227e1e29b77362f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0384615385, "max_line_length": 162, "alphanum_fraction": 0.5563218391, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900945711678, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.768273395665295}}
{"text": "export Chebyshev\n\nimmutable Chebyshev <: ParametricFamily\n    n::Int\nend\n\ndomain(::Chebyshev) = -1..1\n\npoints(c::Chebyshev, T = Float64) = cospi.(((c.n:-1:1)-T(0.5))/c.n)\n\ndegf(c::Chebyshev) = c.n\n\n\"Recurrence relation for Chebyshev polynomials.\"\n@inline _chebyshev_recurrence(x, T₋₁, T₋₂) = 2*x*T₋₁ - T₋₂, T₋₁\n\n\"Initialize T₋₁, T₋₂ for the Chebyshev recurrence.\"\n@inline _chebyshev_recurrence_init{T}(x::T) = x, one(T)\n\nmacro _chebyshev_recurrence!(x, T₋₁, T₋₂)\n    T₋₁ = esc(T₋₁)\n    T₋₂ = esc(T₋₂)\n    :(($(T₋₁), $(T₋₂)) = _chebyshev_recurrence($(esc(x)), $(T₋₁), $(T₋₂)))\nend\n\nfunction basis!{T}(c::Chebyshev, x::T, b::AbstractVector{T})\n    @argcheck c.n == length(b)\n    T₋₁, T₋₂ = _chebyshev_recurrence_init(x)\n    for i in 1:c.n\n        if i == 1\n            b[i] = T₋₂\n        else\n            if i > 2\n                @_chebyshev_recurrence! x T₋₁ T₋₂\n            end\n            b[i] = T₋₁\n        end\n    end\n    b\nend\n\n# note: after benchmarking, it was found that this is faster than Clenshaw,\n# and at least as accurate.\nfunction evaluate{T}(c::Chebyshev, θ, x::T)\n    T₋₁, T₋₂ = _chebyshev_recurrence_init(x)\n    value = zero(T)\n    for i in 1:c.n\n        if i == 1\n            value += T₋₂*θ[i]\n        else\n            if i > 2\n                @_chebyshev_recurrence! x T₋₁ T₋₂\n            end\n            value += T₋₁*θ[i]\n        end\n    end\n    value\nend\n\nfunction evaluate{T}(c::Chebyshev, θ, vp::ValuePartial{T})\n    ## if T(x) = 2xT₋₁(x) - T₋₂(x)\n    ## then T′(x) = 2T₋₁(x) + 2xT′₋₁(x) - T′₋₂(x), with T′₂ = 1 and T′₁ = 0\n    x = vp.x\n    value = partial = zero(T)\n    T₋₁ = x\n    T₋₂ = T′₋₁ = one(T)\n    T′₋₂ = zero(T)\n    for i in 1:c.n\n        if i == 1\n            value += T₋₂*θ[i]\n        else\n            if i > 2\n                @_chebyshev_recurrence! x T′₋₁ T′₋₂\n                T′₋₁ += 2*T₋₁\n                @_chebyshev_recurrence! x T₋₁ T₋₂\n            end\n            value += T₋₁*θ[i]\n            partial += T′₋₁*θ[i]\n        end\n    end\n    value, partial\nend\n\nevaluate{T}(c::Chebyshev, θ, x::Partial{T}) = evaluate(c, θ, ValuePartial(x.x))[2]\n\nfunction fit!{T}(c::Chebyshev, ys::AbstractVector{T}, θ::AbstractVector{T})\n    @argcheck c.n == length(ys) == length(θ)\n    x = points(c, T)\n    T₋₂ = ones(T, c.n)\n    T₋₁ = copy(x)\n    for i in 1:c.n\n        if i == 1\n            θ[1] = sum(ys) / c.n\n        else\n            if i > 2\n                for j in 1:c.n\n                    @_chebyshev_recurrence! x[j] T₋₁[j] T₋₂[j]\n                end\n            end\n            θ[i] = dot(T₋₁, ys) *2 / c.n\n        end\n    end\n    θ\nend\n", "meta": {"hexsha": "9a97a28924a0a7132d53d19cb3f68c185cc6a273", "size": 2573, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Chebyshev.jl", "max_stars_repo_name": "JuliaTagBot/ParametricFunctions.jl", "max_stars_repo_head_hexsha": "7ccca90419a332da40b6708be6cdbfbfef42d3ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-03-25T03:13:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T22:28:29.000Z", "max_issues_repo_path": "src/Chebyshev.jl", "max_issues_repo_name": "JuliaTagBot/ParametricFunctions.jl", "max_issues_repo_head_hexsha": "7ccca90419a332da40b6708be6cdbfbfef42d3ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-31T11:46:40.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-31T12:04:16.000Z", "max_forks_repo_path": "src/Chebyshev.jl", "max_forks_repo_name": "JuliaTagBot/ParametricFunctions.jl", "max_forks_repo_head_hexsha": "7ccca90419a332da40b6708be6cdbfbfef42d3ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:48:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:48:50.000Z", "avg_line_length": 24.7403846154, "max_line_length": 82, "alphanum_fraction": 0.4931986009, "num_tokens": 1033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7682601455437639}}
{"text": "\"\"\"\nImplementation of a Rauch-Tung-Striebel smoother based on \nCh.8 of Bayesian Filtering & Smoothing (Särkka, 2014).\n\nAuthor: Wouter Kouw\nLast update: 03-07-2021\n\"\"\"\n\nusing Distributions\nusing Random\n\nfunction fixedinterval_rts_smoother(observations,\n                                    transition_matrix,\n                                    emission_matrix,\n                                    process_noise,\n                                    measurement_noise,\n                                    state0)\n    \"\"\"\n    Fixed-interval Rauch-Tung-Striebel smoother (Th. 8.2)\n\n    This filter is built for a linear Gaussian dynamical system with known\n    transition coefficients, process and measurement noise.\n    \"\"\"\n\n    # Dimensionality\n    Dx = size(process_noise,1)\n    Dy = size(measurement_noise,1)\n\n    # Recast process noise to matrix\n    if Dx == 1\n        if typeof(process_noise) != Array{Float64,2}\n            process_noise = reshape([process_noise], 1, 1)\n        end\n        if typeof(measurement_noise) != Array{Float64,2}\n            measurement_noise = reshape([measurement_noise], 1, 1)\n        end\n    end\n\n    # Time horizon\n    time_horizon = length(observations)\n\n    # Initialize estimate arrays\n    mk = zeros(Dx, time_horizon)\n    Pk = zeros(Dx, Dx, time_horizon)\n\n    # Initial state prior\n    m_0, P_0 = state0\n\n    # Start previous state variable\n    m_kmin = m_0\n    P_kmin = P_0\n\n    \"Forward pass\"\n    for k = 1:time_horizon\n\n        # Forward prediction step\n        m_k_pred = transition_matrix*m_kmin\n        P_k_pred = transition_matrix*P_kmin*transition_matrix' .+ process_noise\n\n        # Forward update step\n        v_k = observations[:,k] .- emission_matrix*m_k_pred\n        S_k = emission_matrix*P_k_pred*emission_matrix' .+ measurement_noise\n        K_k = P_k_pred*emission_matrix'*inv(S_k)\n        m_k = m_k_pred .+ K_k*v_k\n        P_k = P_k_pred .- K_k*S_k*K_k'\n        \n        # Store estimates\n        mk[:,k] = m_k\n        Pk[:,:,k] = P_k\n\n        # Update previous state variable\n        m_kmin = m_k\n        P_kmin = P_k\n\n    end\n\n    # Initialize smoothing estimate arrays\n    msk = zeros(Dx, time_horizon)\n    Psk = zeros(Dx, Dx, time_horizon)\n\n    # Smoothed estimates at time horizon\n    msk[:,time_horizon] = mk[:,time_horizon]\n    Psk[:,:,time_horizon] = Pk[:,:,time_horizon]\n\n    \"Backward pass\"\n    for k = time_horizon-1:-1:1\n        \n        # Backward prediction\n        m_kplus = transition_matrix * mk[:,k]\n        P_kplus = transition_matrix * Pk[:,:,k] * transition_matrix' .+ process_noise\n\n        # Backward update step\n        G_k = Pk[:,:,k]*transition_matrix' * inv(P_kplus)\n        msk[:,k] = mk[:,k] + G_k*(msk[:,k+1] - m_kplus)\n        Psk[:,:,k] = Pk[:,:,k] + G_k*(Psk[:,:,k+1] - P_kplus)*G_k'\n\n    end\n\n    return msk, Psk\nend\n", "meta": {"hexsha": "1dd51309396c42126e19e5182947b0458172e88c", "size": 2806, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "fixedinterval-kalman-smoothers.jl", "max_stars_repo_name": "wmkouw/Bayesian-smoothers", "max_stars_repo_head_hexsha": "e7d211588bef239ea83a17d8da5667a069076f7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fixedinterval-kalman-smoothers.jl", "max_issues_repo_name": "wmkouw/Bayesian-smoothers", "max_issues_repo_head_hexsha": "e7d211588bef239ea83a17d8da5667a069076f7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fixedinterval-kalman-smoothers.jl", "max_forks_repo_name": "wmkouw/Bayesian-smoothers", "max_forks_repo_head_hexsha": "e7d211588bef239ea83a17d8da5667a069076f7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7821782178, "max_line_length": 85, "alphanum_fraction": 0.5915894512, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7682601437560912}}
{"text": "# ---\n# title: 390. Elimination Game\n# id: problem390\n# author: Indigo\n# date: 2021-06-20\n# difficulty: Medium\n# categories: \n# link: <https://leetcode.com/problems/elimination-game/description/>\n# hidden: true\n# ---\n# \n# There is a list of sorted integers from 1 to _n_. Starting from left to right,\n# remove the first number and every other number afterward until you reach the\n# end of the list.\n# \n# Repeat the previous step again, but this time from right to left, remove the\n# right most number and every other number from the remaining numbers.\n# \n# We keep repeating the steps again, alternating left to right and right to\n# left, until a single number remains.\n# \n# Find the last number that remains starting with a list of length _n_.\n# \n# **Example:**\n# \n#     \n#     \n#     Input:\n#     n = 9,\n#     _1_ 2 _3_ 4 _5_ 6 _7_ 8 _9_\n#     2 _4_ 6 _8_\n#     _2_ 6\n#     6\n#     \n#     Output:\n#     6\n#     \n# \n# \n## @lc code=start\nusing LeetCode\n\nlast_remaining(n::Int)::Int = n == 1 ? 1 : 2 * (n ÷ 2 + 1 - last_remaining(n ÷ 2))\n\n## @lc code=end\n", "meta": {"hexsha": "d4ca0133e5d0ed543c20dd0f3918d48996fb3533", "size": 1054, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/390.elimination-game.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/390.elimination-game.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/390.elimination-game.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 22.9130434783, "max_line_length": 82, "alphanum_fraction": 0.6442125237, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7682601435152471}}
{"text": "using SortingAlgorithms\r\n\r\nfunction main(points)\r\n  try\r\n    ch_points = []\r\n    ch_points = convex_hull!(points)\r\n\r\n    output = [[],[],[],[]]\r\n\r\n    for ch_point in ch_points\r\n      push!(output[1], ch_point[1])\r\n      push!(output[2], ch_point[2])\r\n\r\n      deleteat!(points, findfirst(points, ch_point))\r\n    end\r\n    \r\n    for point in points \r\n      push!(output[3], point[1])\r\n      push!(output[4], point[2])\r\n    end\r\n\r\n    return output\r\n  catch e\r\n    if isa(e, MethodError)\r\n      return \"Please provide array of tuples where each element is Int64\"\r\n    else\r\n      return e\r\n    end\r\n  end\r\nend\r\n\r\nfunction convex_hull!(points::Array{Tuple{Int64,Int64},1})\r\n  if size(points, 1) < 3\r\n    return points\r\n  end\r\n\r\n  # Sort all points\r\n  points = sort!(union(points), alg = HeapSort)\r\n\r\n  # Arrays for top and bottom parts of convex hull\r\n  calculated_ch_top = []\r\n  calculated_ch_bottom = []\r\n\r\n  # Build top part of convex hull\r\n  build_convex_hull_part!(calculated_ch_top, points, 1:1:length(points))\r\n\r\n  # Build bottom part of convex hull\r\n  build_convex_hull_part!(calculated_ch_bottom, points, length(points):-1:1)\r\n\r\n  # Remove duplicated points:\r\n  # End of top part == beginning of the bottom part\r\n  pop!(calculated_ch_top)\r\n\r\n  # End of bottom part == beginning of the top part\r\n  pop!(calculated_ch_bottom)\r\n\r\n  # Top + Bottom parts == convex hull\r\n  convex_hull = [calculated_ch_top; calculated_ch_bottom]\r\n\r\n  return convex_hull\r\nend\r\n\r\nfunction counter_clockwise(p1, p2, p3)\r\n  return ((p2[1] - p1[1]) * (p3[2] - p1[2])) - ((p2[2] - p1[2]) * (p3[1] - p1[1]))\r\nend\r\n\r\nfunction generate_points(number_of_points, range_min, range_max)\r\n  points = [(0,0)]\r\n  pop!(points)\r\n  for i = 1:number_of_points\r\n    generated_point = (rand(range_min:range_max), rand(range_min:range_max))\r\n    push!(points, generated_point)\r\n  end\r\n  return points\r\nend  \r\n\r\nfunction build_convex_hull_part!(hull_points, points_to_check, iterator_range)\r\n  for i = iterator_range\r\n    point = points_to_check[i]\r\n\r\n    while length(hull_points) > 1 && counter_clockwise(hull_points[end-1], hull_points[end], point) >= 0\r\n      pop!(hull_points)\r\n    end\r\n\r\n    push!(hull_points, point)\r\n  end\r\nend", "meta": {"hexsha": "4b9278c0d9b0b6b325b5af1144d1b8f7b5440e84", "size": 2194, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "convex_hull.jl", "max_stars_repo_name": "MrShemek/ConvexHullTDD", "max_stars_repo_head_hexsha": "db517d4ecee84b4ef35a8445c07a879eba0b6be6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "convex_hull.jl", "max_issues_repo_name": "MrShemek/ConvexHullTDD", "max_issues_repo_head_hexsha": "db517d4ecee84b4ef35a8445c07a879eba0b6be6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "convex_hull.jl", "max_forks_repo_name": "MrShemek/ConvexHullTDD", "max_forks_repo_head_hexsha": "db517d4ecee84b4ef35a8445c07a879eba0b6be6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2183908046, "max_line_length": 105, "alphanum_fraction": 0.6531449407, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921834855049, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7682601399399016}}
{"text": "# Isomap\n# ------\n# A Global Geometric Framework for Nonlinear Dimensionality Reduction,\n# J. B. Tenenbaum, V. de Silva and J. C. Langford, Science 290 (5500): 2319-2323, 22 December 2000\n\n#### Isomap type\nstruct Isomap{T <: Real} <: AbstractDimensionalityReduction\n    k::Int\n    model::KernelPCA\n    component::AbstractVector{Int}\n\n    Isomap{T}(k::Int, model::KernelPCA) where T = new(k, model)\n    Isomap{T}(k::Int, model::KernelPCA, cc::AbstractVector{Int}) where T = new(k, model, cc)\nend\n\n## properties\noutdim(R::Isomap) = outdim(R.model)\neigvals(R::Isomap) = principalvars(R.model)\nneighbors(R::Isomap) = R.k\nvertices(R::Isomap) = R.component\n\n## show\nsummary(io::IO, R::Isomap) = print(io, \"Isomap(outdim = $(outdim(R)), neighbors = $(neighbors(R)))\")\n\n## interface functions\nfunction fit(::Type{Isomap}, X::AbstractMatrix{T}; k::Int=12, maxoutdim::Int=2) where {T<:Real}\n    # Construct NN graph\n    D, E = find_nn(X, k)\n    G, C = largest_component(SimpleWeightedGraph(adjmat(D,E)))\n\n    # Compute shortest path for every point\n    n = length(C)\n    DD = zeros(T, n, n)\n    for i in 1:n\n        dj = dijkstra_shortest_paths(G, i)\n        DD[i,:] = dj.dists\n    end\n\n    broadcast!(x->-x*x/2, DD, DD)\n    broadcast!((x,y)->(x+y)/2, DD, DD, DD') # remove roundoff error\n    M = fit(KernelPCA, DD, kernel=nothing, maxoutdim=maxoutdim)\n\n    return Isomap{T}(k, M, C)\nend\n\ntransform(R::Isomap) = transform(R.model)\n", "meta": {"hexsha": "44293afc1f9c3aac7567be215d998e2d83bdd537", "size": 1421, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/isomap.jl", "max_stars_repo_name": "yuehhua/ManifoldLearning.jl", "max_stars_repo_head_hexsha": "73c5250dc5a97e806318fceb6d98cb6d2c8c8bfe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/isomap.jl", "max_issues_repo_name": "yuehhua/ManifoldLearning.jl", "max_issues_repo_head_hexsha": "73c5250dc5a97e806318fceb6d98cb6d2c8c8bfe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/isomap.jl", "max_forks_repo_name": "yuehhua/ManifoldLearning.jl", "max_forks_repo_head_hexsha": "73c5250dc5a97e806318fceb6d98cb6d2c8c8bfe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2340425532, "max_line_length": 100, "alphanum_fraction": 0.6509500352, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7682601346973053}}
{"text": "\"\"\"\n# Usage\n\n    solve(prob::FODESystem, h, NonLinearAlg())\n\nNonlinear algorithm for nonlinear fractional differential equations.\n\n### References\n\nDingyu Xue, Northeastern University, China ISBN:9787030543981\n\"\"\"\nstruct NonLinearAlg <: FractionalDiffEqAlgorithm end\n\nfunction solve(prob::FODESystem, h, ::NonLinearAlg, L0=1e10)\n    @unpack f, α, u0, tspan = prob\n    t0 = tspan[1]; T = tspan[2]\n    n = length(u0)\n    m = round(Int, (T-t0)/h)+1\n    g = genfun(1)\n    g = g[:]\n    u0 = u0[:]\n    ha = h.^α\n    z = zeros(n, m)\n    x1 = copy(u0) # Here we pass the value of x0 to x1. Honestly, I kept finding this bug for almost a whole night😅\n\n\n    # All of the min(m, L0+1) is to set the memory effect.\n    SetMemoryEffect = Int64(min(m, L0+1))\n    W = zeros(n, SetMemoryEffect) #Initializing W a n*m matrix\n\n    @fastmath @inbounds @simd for i = 1:n\n        W[i, :] = getvec(α[i], SetMemoryEffect, g)\n    end\n\n    du = zeros(n)\n    @fastmath @inbounds @simd for k = 2:m\n        tk = t0+(k-1)*h\n        L = min(Int64(k-1), Int64(L0))\n        f(du, x1, nothing, tk)\n\n        @fastmath @inbounds @simd for i = 1:n\n            x1[i] = du[i]*ha[i] - W[i, 2:L+1]'*z[i, k-1:-1:k-L] + u0[i]\n        end\n        z[:, k] = x1 - u0\n    end\n\n    result = (z + repeat(u0, 1, m))'\n    \n    return result\nend\n\n\"\"\"\nP-th precision polynomial generate function\n\n```math\ng_p(z)=\\\\sum_{k=1}^p \\\\frac{1}{k}(1-z)^k\n```\n\"\"\"\nfunction genfun(p)\n    a = collect(1:p+1)\n    A = Vandermonde(a)'\n    return (1 .-a')*inv(A')\nend\n\nfunction getvec(α, n, g)\n    p = length(g)-1\n    b = 1 + α\n    g0 = g[1]\n    w = Float64[]\n    push!(w, g[1]^α)\n\n    @fastmath @inbounds @simd for m = 2:p\n        M = m-1\n        dA = b/M\n        temp = (-(g[2:m] .*collect((1-dA):-dA:(1-b))))' *w[M:-1:1]/g0\n        push!(w, temp)\n    end\n\n    @fastmath @inbounds @simd for k = p+1:n\n        M = k-1\n        dA = b/M\n        temp = (-(g[2:(p+1)] .*collect((1-dA):-dA:(1-p*dA))))' *w[M:-1:(k-p)]/g0\n        push!(w, temp)\n    end\n    return w\nend", "meta": {"hexsha": "652fc82907a539ed36e224588fb0ae4b6c9e106e", "size": 1995, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fodesystem/NonLinear.jl", "max_stars_repo_name": "SciFracX/FractionalDiffEq.jl", "max_stars_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-11-05T12:49:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:57:20.000Z", "max_issues_repo_path": "src/fodesystem/NonLinear.jl", "max_issues_repo_name": "SciFracX/FractionalDiffEq.jl", "max_issues_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-11-01T22:05:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:57:19.000Z", "max_forks_repo_path": "src/fodesystem/NonLinear.jl", "max_forks_repo_name": "SciFracX/FractionalDiffEq.jl", "max_forks_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1976744186, "max_line_length": 115, "alphanum_fraction": 0.5368421053, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7682601325483668}}
{"text": "\"\"\"Julia program to implement Exponential Search algorithm.\nExponential Search Algorithm is an optimized Binary Search to search an element in sorted array.\nIt is specifically used when the size of array is infinite.\n\"\"\"\n\nfunction binary_search(arr, low, n, ele)\n    high = n\n    while high >= low\n        mid = low + (high - low) ÷ 2\n        # If the mid element is the required element, return that index\n        if(arr[mid] == ele)\n            return mid\n        # ele is greater than mid element then ele would be present in first half of the array\n        elseif (arr[mid] > ele)\n            high = mid - 1\n        #Else if  ele is smaller than mid element then ele would be present in last half of the array\n        else\n            low = mid + 1\n        end\n    end\n    # If the element is not found return 0\n    return 0\nend\n\n\nfunction exponential_search(arr, n, ele)\n    if(arr[1] == ele)\n        return false\n    end\n    i = 2\n    while( i < n && arr[i] <= ele)\n        i = i * 2\n    end\n    mini = i < (n-1) ? i : (n-1)\n    return binary_search(arr, i÷2, mini, ele )\nend\n\n\nprint(\"How many numbers are present in the array? \")\nn = readline()\nn = parse(Int, n)\nif (n <= 0)\n    println(\"Array is Empty!!!\")\n    exit()\nend\narr = Int[]\nprint(\"Enter the numbers: \")\narr = [parse(Int, num) for num in split(readline())] \nprint(\"Which number do you want to search in the array? \")\nele = readline()\nele = parse(Int, ele)\n# Sort the array in ascending order\narr = sort(arr)\nres = exponential_search(arr, n, ele)\nif (res == 0)\n    print(\"The number $ele is not present in the array\")\nelse\n    print(\"The number $ele is present in the array.\")\nend\n\n\n\n\"\"\"\nTime Complexity - O(log(n)), where 'n' is the size of the array\nSpace Complexity - O(n)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE I\nHow many numbers are present in the array? 5 \nEnter the numbers: 1 2 3 4 5\nWhich number do you want to search in the array? 6\nThe number 6 is not present in the array\n\nSAMPLE II\nHow many numbers are present in the array? 3\nEnter the numbers: 3 1 2\nWhich number do you want to search in the array? 2\nThe number 2 is present in the array.\n\"\"\"\n", "meta": {"hexsha": "0a795cc1a6028c3afcc9a0f818a220f4d1e28656", "size": 2118, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/search/exponential_search.jl", "max_stars_repo_name": "Khushboo85277/NeoAlgo", "max_stars_repo_head_hexsha": "784d7b06c385336425ed951918d1ab37b854d29f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 897, "max_stars_repo_stars_event_min_datetime": "2020-06-25T00:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:49:31.000Z", "max_issues_repo_path": "Julia/search/exponential_search.jl", "max_issues_repo_name": "adarshnjena/NeoAlgo", "max_issues_repo_head_hexsha": "77a92858d2bf970054ef31c2f55a6d79917a786a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5707, "max_issues_repo_issues_event_min_datetime": "2020-06-24T17:53:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T05:03:15.000Z", "max_forks_repo_path": "Julia/search/exponential_search.jl", "max_forks_repo_name": "adarshnjena/NeoAlgo", "max_forks_repo_head_hexsha": "77a92858d2bf970054ef31c2f55a6d79917a786a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1817, "max_forks_repo_forks_event_min_datetime": "2020-06-25T03:51:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:14:07.000Z", "avg_line_length": 26.1481481481, "max_line_length": 101, "alphanum_fraction": 0.6449480642, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7682501592560873}}
{"text": "\"\"\"\nPackage: Smoothers\n\n    sma(x, n, center=false)\n\nSmooth a vector of data using a simple moving average\n\n# Arguments\n- `x`: Vector of data.\n- `n`: Size of the moving average.\n- `center`: returns a vector of the same size of x with missing values on the tails.\n\n# Returns\nVector of moving average values\n\n# Examples\n```julia-repl\njulia> sma(1:5,3)\n3-element Vector{Float64}:\n 2.0\n 3.0\n 4.0\n\njulia> sma(1:5,3,true)\n5-element Vector{Union{Missing, Float64}}:\n  missing\n 2.0\n 3.0\n 4.0\n  missing\n```\n\"\"\"\n@inline function sma(x::AbstractVector{T}, n::Integer, center::Bool=false) where T<:Real\n\n    n == 1 && return x\n    N = length(x)\n    @assert 1 <= n <= N\n    \n    P = Base.promote_op(/, T, T)\n    res = Vector{P}(undef, N-n+1)\n    \n    # initial moving average value\n    res[1] = ma = sum(x[1:n])/n\n    for i in 1:N-n\n        @inbounds res[1+i] = ma += (x[n+i] - x[i]) / P(n)\n    end\n\n    center ? vcat(repeat([missing], n÷2),res,repeat([missing], n-n÷2-1)) : res\n\nend\n", "meta": {"hexsha": "4b16360c523065356f4106e7cb88423251f09c89", "size": 971, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sma.jl", "max_stars_repo_name": "viraltux/Smoothers.jl", "max_stars_repo_head_hexsha": "3dff0ba13001cbc9982700875c9776d2d4a1cd40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2021-09-02T14:40:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T07:40:56.000Z", "max_issues_repo_path": "src/sma.jl", "max_issues_repo_name": "viraltux/Smoothers.jl", "max_issues_repo_head_hexsha": "3dff0ba13001cbc9982700875c9776d2d4a1cd40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-08-15T22:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T04:37:45.000Z", "max_forks_repo_path": "src/sma.jl", "max_forks_repo_name": "viraltux/Smoothers.jl", "max_forks_repo_head_hexsha": "3dff0ba13001cbc9982700875c9776d2d4a1cd40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0392156863, "max_line_length": 88, "alphanum_fraction": 0.6086508754, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7682501571036643}}
{"text": "\"\"\"\n    rv(X, Y)\nCompute the sample RV coefficient between matrices X and Y\n* `X` : Matrix (n obs., p variables).\n* `Y` : Matrix (n obs., q variables).\n\nRV is bounded in [0, 1]. \n\nA dissimilarty measure between `X` and `Y` can be computed\nby d = sqrt(2 * (1 - RV)).\n\n\n## References\n\nEscoufier, Y., 1973. Le Traitement des Variables Vectorielles. Biometrics 29, 751–760. \nhttps://doi.org/10.2307/2529140\n\nJosse, J., Pagès, J., Husson, F., 2008. Testing the significance of the RV coefficient. \nComputational Statistics & Data Analysis 53, 82–91. https://doi.org/10.1016/j.csda.2008.06.012\n\nMayer, C.-D., Lorent, J., Horgan, G.W., 2011. Exploratory Analysis of Multiple Omics \nDatasets Using the Adjusted RV Coefficient. Statistical Applications in Genetics and Molecular\nBiology 10. https://doi.org/10.2202/1544-6115.1540\n\nSmilde, A.K., Kiers, H.A.L., Bijlsma, S., Rubingh, C.M., van Erk, M.J., 2009. \nMatrix correlations for high-dimensional data: the modified RV-coefficient. \nBioinformatics 25, 401–405. https://doi.org/10.1093/bioinformatics/btn634\n\nRobert, P., Escoufier, Y., 1976. A Unifying Tool for Linear Multivariate Statistical Methods: \nThe RV-Coefficient. Journal of the Royal Statistical Society: Series C (Applied Statistics) \n25, 257–265. https://doi.org/10.2307/2347233\n\"\"\" \n\nfunction rv(X, Y; centr = true)\n    X = ensure_mat(X)\n    Y = ensure_mat(Y)\n    if centr\n        X = center(X, mean(X, dims = 1))\n        Y = center(Y, mean(Y, dims = 1))\n    end\n    YtX = Y' * X    \n    XtX = X' * X\n    YtY = Y' * Y\n    A = dot(YtX, YtX)\n    B = dot(XtX, XtX)\n    C = dot(YtY, YtY)\n    rv = A / sqrt(B * C)\nend\n\n", "meta": {"hexsha": "1e9d76df3659cf8ad2f1359aac9fcac9c3bd5781", "size": 1622, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/angles.jl", "max_stars_repo_name": "mlesnoff/Jchemo.jl", "max_stars_repo_head_hexsha": "fea8da15c0458c0e68921cda55a5bf448170eb53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/angles.jl", "max_issues_repo_name": "mlesnoff/Jchemo.jl", "max_issues_repo_head_hexsha": "fea8da15c0458c0e68921cda55a5bf448170eb53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/angles.jl", "max_forks_repo_name": "mlesnoff/Jchemo.jl", "max_forks_repo_head_hexsha": "fea8da15c0458c0e68921cda55a5bf448170eb53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.44, "max_line_length": 94, "alphanum_fraction": 0.6652281134, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7682501518823512}}
{"text": "# This file calculates the field strength at the center of a Faraday cage. Warning, the run-time is long.\n# See /Laplace.jl for a more interactive version.\nusing ApproxFun, SingularIntegralEquations\n\nz_0 = 2.0\nui(x,y) = logabs(complex(x,y)-z_0)\ng1(x,y) = 1/2\n\nfunction electricfield(N,r)\n    # Set the domains.\n    cr = exp(im*2π*[0:N-1]/N)\n    crl = (1-2r)cr\n    crr = (1+2r)cr\n    dom = ∪(Segment.(crl,crr))\n    #dom = ∪(Circle.(cr,ones(length(cr))r))\n    #dom = ∪(Segment.(crl[1:2:end],crr[1:2:end]) ∪ ∪(Circle.(cr[2:2:end],ones(length(cr[2:2:end]))r))\n\n    sp = Space(dom)\n    cwsp = CauchyWeight(sp⊗sp,0)\n    uiΓ,⨍ = Fun(t->ui(real(t),imag(t))+0im,sp),DefiniteLineIntegral(dom)\n\n    G = GreensFun(g1,cwsp;method=:Cholesky)\n\n    ∂u∂n = ⨍[G]\\uiΓ\n\n    us(x,y) = -logkernel(∂u∂n,complex(x,y))/2\n    ut(x,y) = ui(x,y) + us(x,y)\n    h = 1e-5\n    abs((ut(h,0.)-ut(-h,0.))/2h)\nend\n\n\nNNr1,NTr1 = [4:15],[4:15,17:2:20,30:10:80]\nENr1 = Float64[@time electricfield(N,1e-1im) for N in NNr1]\nprintln(\"Done ENr1\")\nETr1 = Float64[@time electricfield(N,1e-1) for N in NTr1]\nprintln(\"Done ETr1\")\n\nNNr2,NTr2 = [[5:10],[15:5:20],[30:10:80]],[[5:10],[15:5:20],[30:10:100]]\nENr2 = Float64[@time electricfield(N,1e-2im) for N in NNr2]\nprintln(\"Done ENr2\")\nETr2 = Float64[@time electricfield(N,1e-2) for N in NTr2]\nprintln(\"Done ETr2\")\n\n#Nr3 = [[5:10],[15:5:20],[30:10:90],[100:50:200]]\n#@time Er3 = Float64[electricfield(N,1e-3) for N in Nr3]\n#@time Er4 = Float64[electricfield(N,1e-4) for N in Nr3]\n", "meta": {"hexsha": "ed52752dac791f5752ee609b55e2388289ea536f", "size": 1482, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/electricfield.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SingularIntegralEquations.jl-e094c991-5a90-5477-8896-c1e4c9552a1a", "max_stars_repo_head_hexsha": "8a0ca7376ecad020ef8f8beca90686311fbb9f84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2016-12-02T13:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T18:31:48.000Z", "max_issues_repo_path": "examples/electricfield.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SingularIntegralEquations.jl-e094c991-5a90-5477-8896-c1e4c9552a1a", "max_issues_repo_head_hexsha": "8a0ca7376ecad020ef8f8beca90686311fbb9f84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2016-12-19T06:02:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:33:33.000Z", "max_forks_repo_path": "examples/electricfield.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SingularIntegralEquations.jl-e094c991-5a90-5477-8896-c1e4c9552a1a", "max_forks_repo_head_hexsha": "8a0ca7376ecad020ef8f8beca90686311fbb9f84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-05-16T06:08:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:20:46.000Z", "avg_line_length": 30.875, "max_line_length": 105, "alphanum_fraction": 0.6234817814, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.7682501510583802}}
{"text": "# ------ Root Finding Methods -----\n\n\n\n\n\"\"\"\n    brent(f, a, b; args=(), atol=2e-12, rtol=4*eps(), maxiter=100)\n\n1D root finding using Brent's method.  Based off the brentq implementation in scipy.\n\n**Arguments**\n- `f`: scalar function, that optionally takes additional arguments\n- `a`::Float, b::Float`: bracketing interval for a root - sign changes sign between: (f(a) * f(b) < 0)\n- `args::Tuple`: tuple of additional arguments to pass to f\n- `atol::Float`: absolute tolerance (positive) for root\n- `rtol::Float`: relative tolerance for root\n- `maxiter::Int`: maximum number of iterations allowed\n\n**Returns**\n- `xstar::Float`: a root of f\n- `info::Tuple`: A named tuple containing:\n    - `iter::Int`: number of iterations\n    - 'fcalls::Int`: number of function calls\n    - 'flag::String`: a convergence/error message.\n\"\"\"\nfunction brent(f, a, b; args=(), atol=2e-12, rtol=4*eps(), maxiter=100)\n\n    xpre = a; xcur = b\n    # xblk = 0.0; fblk = 0.0; spre = 0.0; scur = 0.0\n    error_num = \"INPROGRESS\"\n\n    fpre = f(xpre, args...)\n    fcur = f(xcur, args...)\n    xblk = zero(fpre); fblk = zero(fpre); spre = zero(fpre); scur = zero(fpre)\n    funcalls = 2\n    iterations = 0\n    \n    if fpre*fcur > 0\n        error_num = \"SIGNERR\"\n        return 0.0, (iter=iterations, fcalls=funcalls, flag=error_num)\n    end\n    if fpre == zero(fpre)\n        error_num = \"CONVERGED\"\n        return xpre, (iter=iterations, fcalls=funcalls, flag=error_num)\n    end\n    if fcur == zero(fcur)\n        error_num = \"CONVERGED\"\n        return xcur, (iter=iterations, fcalls=funcalls, flag=error_num)\n    end\n\n    for i = 1:maxiter\n        iterations += 1\n        if fpre*fcur < 0\n            xblk = xpre\n            fblk = fpre\n            spre = scur = xcur - xpre\n        end\n        if abs(fblk) < abs(fcur)\n            xpre = xcur\n            xcur = xblk\n            xblk = xpre\n\n            fpre = fcur\n            fcur = fblk\n            fblk = fpre\n        end\n\n        delta = (atol + rtol*abs(xcur))/2\n        sbis = (xblk - xcur)/2\n        if fcur == zero(fcur) || abs(sbis) < delta\n            error_num = \"CONVERGED\"\n            return xcur, (iter=iterations, fcalls=funcalls, flag=error_num)\n        end\n\n        if abs(spre) > delta && abs(fcur) < abs(fpre)\n            if xpre == xblk\n                # interpolate\n                stry = -fcur*(xcur - xpre)/(fcur - fpre)\n            else\n                # extrapolate\n                dpre = (fpre - fcur)/(xpre - xcur)\n                dblk = (fblk - fcur)/(xblk - xcur)\n                stry = -fcur*(fblk*dblk - fpre*dpre)/(dblk*dpre*(fblk - fpre))\n            end\n            if 2*abs(stry) < min(abs(spre), 3*abs(sbis) - delta)\n                # good short step\n                spre = scur\n                scur = stry\n            else\n                # bisect\n                spre = sbis\n                scur = sbis\n            end\n        else \n            # bisect\n            spre = sbis\n            scur = sbis\n        end\n\n        xpre = xcur; fpre = fcur\n        if abs(scur) > delta\n            xcur += scur\n        else\n            xcur += (sbis > 0 ? delta : -delta)\n        end\n\n        fcur = f(xcur, args...)\n        funcalls += 1\n    end\n    error_num = \"CONVERR\"\n    return xcur, (iter=iterations, fcalls=funcalls, flag=error_num)\nend\n\n# TODO AN: replace w/ newer Brent method and automatic bracketing?\n\n", "meta": {"hexsha": "bcdcdd89487a28e39c8fd7b599e3d51ba45e7d24", "size": 3364, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/roots.jl", "max_stars_repo_name": "dingraha/FLOWMath.jl", "max_stars_repo_head_hexsha": "2837bda3e286772bcaddc781bb0bfe5e5e05e373", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-04-03T23:28:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T14:20:56.000Z", "max_issues_repo_path": "src/roots.jl", "max_issues_repo_name": "dingraha/FLOWMath.jl", "max_issues_repo_head_hexsha": "2837bda3e286772bcaddc781bb0bfe5e5e05e373", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-10-25T17:58:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-05T21:50:19.000Z", "max_forks_repo_path": "src/roots.jl", "max_forks_repo_name": "dingraha/FLOWMath.jl", "max_forks_repo_head_hexsha": "2837bda3e286772bcaddc781bb0bfe5e5e05e373", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-25T17:29:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:42:08.000Z", "avg_line_length": 29.0, "max_line_length": 102, "alphanum_fraction": 0.525862069, "num_tokens": 1024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.768250148905957}}
{"text": "# !INPUT/OUTPUT PARAMETERS:\n#   m : order of derivative (in,integer)\n#   n : number of points (in,integer)\n#   x : abscissa array (in,real(n))\n#   f : function array (in,real(n))\n#   g : (anti-)derivative of f (out,real(n))\n# !DESCRIPTION:\n#   Given function $f$ defined on a set of points $x_i$ then if $m\\ge 0$ this\n#   routine computes the $m$th derivative of $f$ at each point. If $m=-1$ the\n#   anti-derivative of $f$ given by\n#   $$ g(x_i)=\\int_{x_1}^{x_i} f(x)\\,dx $$\n#   is calculated. Both derivatives and integrals are computed by first fitting\n#   the function to a clamped cubic spline.\nfunction fderiv!(m, n, x, f, g)\n\n    @assert n > 0\n\n    # automatic arrays\n    cf = zeros(Float64,3,n)\n\n    # high accuracy integration/differentiation from spline interpolation\n    spline!(n, x, f, cf)\n    if m == -1\n        ss =0.0\n        g[1] = 0.0\n        for i in 1:n-1\n          dx = x[i+1] - x[i]\n          ss = ss + dx*( f[i] + dx*( 0.50*cf[1,i] + dx*( cf[2,i]/3 + dx*0.25*cf[3,i] ) ) )\n          g[i+1] = ss\n        end\n    elseif m == 1\n        for i in 1:n\n            g[i] = cf[1,i]\n        end\n    elseif m == 2\n        for i in 1:n\n            g[i] = 2.0*cf[2,i]\n        end\n    elseif m == 3\n        for i in 1:n\n            g[i] = 6.0*cf[3,i]\n        end\n    else\n        for i in 1:n\n            g[i] = 0.0\n        end\n    end\n    return\nend\n", "meta": {"hexsha": "85859ac7308648ace5005997373500e506de2fc0", "size": 1359, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LAPW/fderiv.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "LAPW/fderiv.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LAPW/fderiv.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 27.18, "max_line_length": 90, "alphanum_fraction": 0.5165562914, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7682495568662698}}
{"text": "# libpurex:\n# Exponential families paramterised by their means\n\ninclude(\"binary_search.jl\");\n\nstruct Gaussian\n    σ2;\nend\n\n# convenience\nGaussian() = Gaussian(1);\n\nstruct Bernoulli\nend\n\nstruct Exponential\nend\n\nstruct Poisson\nend\n\n\n# KL divergence\n\nrel_entr(x, y) = x==0 ? 0. : x*log(x/y);\n\nd(expfam::Gaussian,    μ, λ) = (μ-λ)^2/(2*expfam.σ2);\nd(expfam::Bernoulli,   μ, λ) = rel_entr(μ, λ) + rel_entr(1-μ, 1-λ);\nd(expfam::Exponential, μ, λ) = λ == 0 ? Inf : μ/λ - log(μ/λ) - 1;\nd(expfam::Poisson,     μ, λ) = rel_entr(μ, λ) - μ + λ;\n\n\n# solution for λ in \\min_λ d(μ, λ) - λ x\n# i.e. λ satisfying (λ - μ)ϕ''(λ) == x\n\ninvh(expfam::Gaussian,    μ, x) = μ + x*expfam.σ2;\ninvh(expfam::Bernoulli,   μ, x) = 2μ/(1-x+sqrt((x-1)^2 + 4*x*μ));\ninvh(expfam::Exponential, μ, x) = x > 0 ? Inf : 2μ/(1 + sqrt(1 - 4*x*μ));\ninvh(expfam::Poisson,     μ, x) = μ/(1-x);\n\nsample(rng, expfam::Gaussian,    μ) = μ + sqrt(expfam.σ2)*randn(rng);\nsample(rng, expfam::Bernoulli,   μ) = rand(rng) ≤ μ;\nsample(rng, expfam::Exponential, μ) = randexp(rng)*μ;\n\n# upward and downward confidence intervals\ndup(expfam::Gaussian, μ, v) = μ + sqrt(2*expfam.σ2*v);\nddn(expfam::Gaussian, μ, v) = μ - sqrt(2*expfam.σ2*v);\n\nfunction dup(expfam::Bernoulli, μ, v)\n    μ == 1 ? 1. : binary_search(λ -> d(expfam, μ, λ) - v, μ, 1);\nend\n\nfunction ddn(expfam::Bernoulli, μ, v)\n    μ == 0 ? 0. : binary_search(λ -> v - d(expfam, μ, λ), 0, μ);\nend\n\nfunction dup(expfam::Exponential, μ, v)\n    binary_search(λ -> d(expfam, μ, λ) - v, μ, μ*exp(v+1));\nend\n\nfunction ddn(expfam::Exponential, μ, v)\n    binary_search(λ -> v - d(expfam, μ, λ), 0, μ);\nend\n", "meta": {"hexsha": "10c523efb6b08822495782ca104a68b4495c5a54", "size": 1599, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "expfam.jl", "max_stars_repo_name": "xuedong/LinBAI.jl", "max_stars_repo_head_hexsha": "47da3f6f3adb2cd077ad8696fa72b70de5b7a31b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-21T10:46:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-21T10:46:50.000Z", "max_issues_repo_path": "expfam.jl", "max_issues_repo_name": "xuedong/LinBAI.jl", "max_issues_repo_head_hexsha": "47da3f6f3adb2cd077ad8696fa72b70de5b7a31b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "expfam.jl", "max_forks_repo_name": "xuedong/LinBAI.jl", "max_forks_repo_head_hexsha": "47da3f6f3adb2cd077ad8696fa72b70de5b7a31b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.984375, "max_line_length": 73, "alphanum_fraction": 0.6041275797, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395168021653, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7682495527951797}}
{"text": "\r\nfunction fifth_power_digit_sum(n::Int)\r\n\r\n\ta=Int[];\r\n\r\n\twhile(n>=1)\r\n\t\tpush!(a,n%10);\r\n\t\tn=n-n%10;\r\n\t\tn/=10;\r\n\t\tn=Int(n)\r\n\tend\r\n\tans=0;\r\n\tfor i in a\r\n\t\tans+=i^5\r\n\tend\r\n\treturn ans\r\nend\r\n\r\n\r\nfunction compute()\r\n\tans=0\r\n\tfor i=2:1000000\r\n\t\tif i==fifth_power_digit_sum(i)\r\n\t\t\tans+=i\r\n\t\tend\r\n\tend\r\n\treturn ans\r\nend\r\n\r\nprintln(compute())", "meta": {"hexsha": "12768f2e88ccd80d68654c635139467fadc00cd5", "size": 334, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/p030.jl", "max_stars_repo_name": "tlming16/Projec_Euler", "max_stars_repo_head_hexsha": "797824c5159fae67493de9eba24c22cc7512d95d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-11-14T12:03:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-03T14:33:28.000Z", "max_issues_repo_path": "julia/p030.jl", "max_issues_repo_name": "tlming16/Projec_Euler", "max_issues_repo_head_hexsha": "797824c5159fae67493de9eba24c22cc7512d95d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/p030.jl", "max_forks_repo_name": "tlming16/Projec_Euler", "max_forks_repo_head_hexsha": "797824c5159fae67493de9eba24c22cc7512d95d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-17T14:39:22.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-17T14:39:22.000Z", "avg_line_length": 11.1333333333, "max_line_length": 39, "alphanum_fraction": 0.5718562874, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7682495442178991}}
{"text": "# # Envelopes\n\n\"\"\"\n    struct ConstantProfile\n\nThis is the trivial profile\n```math\nenvelope(z, t) = 1\n```\nwhich gives an infinite duration for the electromagnetic field configuration (we cannot\ncall this a laser pusle since a pulse implicitely has a finite duration).\n\"\"\"\nstruct ConstantProfile <: AbstractTemporalProfile end\n\n@doc \"\"\"\n    GaussProfile{V,T,L}\n\nThis envelope provides a finite duration for the laser pulse and thus can provide a more\nrealistic description of an actual laser pulse.\n```math\nenvelope(z, t) = \\\\exp\\\\left[-\\\\left(\\\\frac{φ}{τ}\\\\right)^2\\\\right],\n```\nwhere\n```math\n\\\\varphi = (t - t_0) - \\\\frac{z - z_0}{c}\\\\,,\n```\nand\n- `c` is the speed of light\n- `τ` is the duration of the pulse (FWHM) and has the default value 18.02fs\n- `t₀` is the origin of the time axis and it is 0 by default\n- `z₀` is the initial position of the intensity peak and has the default value `-4*τ*c`\n\"\"\"\nGaussProfile\n\nstruct GaussProfile{T,IT,L} <: AbstractTemporalProfile\n    inv_τ::IT\n    t₀::T\n    z₀::L\nend\n\nfunction GaussProfile(;τ, t₀=zero(τ), z₀)\n    GaussProfile(inv(τ), t₀, z₀)\nend\n\n@doc \"\"\"\n    Cos²Profile{V,T,L}\n\nThis envelope provides a finite duration for the laser pulse and thus can provide a more\nrealistic description of an actual laser pulse.\n```math\nenvelope(z, t) =\n    \\\\begin{cases}\n    \\\\cos\\\\left[\\\\left(\\\\frac{φ}{τ}\\\\right)\\\\right]^2, & \\\\text{for } |t - t₀| < τ / 2\\\\\\\\\n    0 \\\\,, & \\\\text{otherwise}\n    \\\\end{cases}\n```\nwhere\n```math\n\\\\varphi = (t - t_0) - \\\\frac{z - z_0}{c}\\\\,,\n```\nand\n- `c` is the speed of light\n- `τ` is the duration of the pulse and has the default value 18.02fs\n- `t₀` is the origin of the time axis and it is 0 by default\n- `z₀` is the initial position of the intensity peak and is 0 by default\n\"\"\"\nCos²Profile\n\nstruct Cos²Profile{T,IT,L} <: AbstractTemporalProfile\n    τ::T\n    inv_τ::IT\n    t₀::T\n    z₀::L\nend\n\nfunction Cos²Profile(;τ, t₀=zero(τ), z₀)\n    t₀, τ = promote(t₀, τ)\n    Cos²Profile(τ, inv(τ), t₀, z₀)\nend\n\n@doc \"\"\"\n    QuasiRectangularProfile{V,T,L}\n\nThis envelope produces a pulse with a predominant constant part of width ``Δz``\nwhich could offer better results than the Gaussian profile in the paraxial limit\n(which is considered for the spatial profiles). The shape of the envelope is given by\n```math\nenvelope(z, t) =\n    \\\\begin{cases}\n    \\\\exp\\\\left[-\\\\left(\\\\frac{φ + Δt/2}{τ}\\\\right)^2\\\\right], & \\\\text{for } φ ≤ \\\\frac{Δt}{2}\\\\\\\\\n    1\\\\,, & \\\\text{for } \\\\text{otherwise}\\\\\\\\\n    \\\\exp\\\\left[-\\\\left(\\\\frac{φ - Δt/2}{τ}\\\\right)^2\\\\right], & \\\\ φ > \\\\frac{Δt}{2}\n    \\\\end{cases}\n```\nwhere\n```math\n\\\\varphi = (t - t_0) - \\\\frac{z - z_0}{c}\\\\,,\n```\nand\n- `c` is the speed of light\n- `τ` is the duration of the pulse (FWHM) and has the default value 18.02fs\n- `t₀` is the origin of the time axis and it is 0 by default\n- `z₀` is the initial position of the intensity peak and has the default value `-4*τ*c`\n- `Δt` is the duration of the flat part of the profile and the default value `10*τ`\n\"\"\"\nQuasiRectangularProfile\n\nstruct QuasiRectangularProfile{T,IT,L} <: AbstractTemporalProfile\n    inv_τ::IT\n    t₀::T\n    z₀::L\n    Δt::T\nend\n\nfunction QuasiRectangularProfile(;τ, t₀=zero(τ), z₀, Δt=10τ)\n    τ, t₀, Δt = promote(τ, t₀, Δt)\n    QuasiRectangularProfile(inv(τ), t₀, z₀, Δt)\nend\n\n\"\"\"\n    g(z, t, par)\n\nThe time dependence of the fields defined by this package is given by\n```math\ng(z, t) = \\\\exp(i ω t) envelope(z, t),\n```\nwhere\n- `z` and `t` are the position on the ``Oz`` axis and the time\n- `par` are the laser parameters which pass the corresponding profile to the envelope\nand\n- ``ω`` is the angular frequency of the laser pulse\n- ``envelope(z, t)`` is a function that can be used to control the duration of the pulse\n\"\"\"\nfunction g(z, t, laser; inv_c)\n    profile = laser.profile\n    ω = immutable_cache(laser, :ω)\n\n    exp(im*ω*t) * envelope(profile, z, t; inv_c)\nend\n\n@inline envelope(::ConstantProfile, z, t; inv_c) = 1\n\n@inline function envelope(profile::GaussProfile, z, t; inv_c)\n    @unpack inv_τ, t₀, z₀ = profile\n    φ = (t - t₀) - (z - z₀) * inv_c\n\n    exp(-(φ * inv_τ)^2)\nend\n\n@inline function envelope(profile::Cos²Profile, z, t; inv_c)\n    @unpack inv_τ, τ, t₀, z₀ = profile\n    φ = π*((t - t₀) - (z - z₀) * inv_c)\n\n    if abs(φ) / π < τ / 2\n        cos(-(φ * inv_τ))^2\n    else\n        zero(t * inv_τ)\n    end\nend\n\n@inline function envelope(profile::QuasiRectangularProfile, z, t; inv_c)\n    @unpack inv_τ, t₀, z₀, Δt = profile\n    φ = (t - t₀/2) - (z - z₀/2) * inv_c\n\n    if φ < -Δt/2\n        exp(-((φ + Δt/2) * inv_τ)^2)\n    elseif φ < Δt/2\n        one(φ)\n    else\n        exp(-((φ - Δt/2) * inv_τ)^2)\n    end\nend\n", "meta": {"hexsha": "5410d4a69cd4f118ae774969bff3f4a3eb0ed69e", "size": 4619, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/envelopes.jl", "max_stars_repo_name": "SebastianM-C/LaserTypes.jl", "max_stars_repo_head_hexsha": "f9c4134c936bf9d145233d90989d6f5af9d08dac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-05-15T08:22:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T07:03:37.000Z", "max_issues_repo_path": "src/envelopes.jl", "max_issues_repo_name": "SebastianM-C/LaserTypes.jl", "max_issues_repo_head_hexsha": "f9c4134c936bf9d145233d90989d6f5af9d08dac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2020-05-10T18:22:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T17:06:27.000Z", "max_forks_repo_path": "src/envelopes.jl", "max_forks_repo_name": "SebastianM-C/LaserTypes.jl", "max_forks_repo_head_hexsha": "f9c4134c936bf9d145233d90989d6f5af9d08dac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6994219653, "max_line_length": 99, "alphanum_fraction": 0.6388828751, "num_tokens": 1569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140232, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7682495406802905}}
{"text": "#script for solving the acoustic duct problem\n# -a0(x)*\\Delta u(x,y)+a1(x)*u(x,y)=f(x,y) for (x,y) ∈ Ω:= (0,2)×(0,1)\n# Here a0(x,y)=-1, a1(x,y)=k^2, f(x,y)=0\n# with Neumann boundary conditions ∂u/∂x(x,y)=cos(mπy) for x = 0 and\n# Robin boundary conditions ∂u/∂x(x,y) + iku = 0 for x=2\n\ninclude(\"../src/Solver2D.jl\")\ninclude(\"../src/SplinePlotting.jl\")\n\na0(x,y) = 1\na1(x,y) = -k^2\nf(x,y) = 0\nk = 40\nm = 2\nkx = sqrt(k^2 - (m*π)^2)\nLHS = [im*kx -im*kx; (k-kx)*exp(-2*im*kx) (k+kx)*exp(2*im*kx)]\nRHS = [1, 0]\nA = LHS\\RHS\n\nexact_sol(x,y) = cos(m*π*y)*(A[1]*exp(-im*kx*x)+A[2]*exp(im*kx*x))\nderiv_exact_sol(x,y) = [cos(m*π*y)*(A[1]*(-im)*kx*exp(-im*kx*x)+A[2]*im*kx*exp(im*kx*x)),\n                        -sin(m*π*y)*(m*π)*(A[1]*exp(-im*kx*x)+A[2]*exp(im*kx*x))]\n\n#Define the boundary conditions\nu_bound_left(x,y) = cos(m*π*y)\nu_bound_right(x,y) = 0.\nbound_left = Boundary2D(\"Neumann\", \"Left\", u_bound_left)\nbound_right = Boundary2D(\"Robin\", \"Right\", -im*k, u_bound_right)\nbound_all = [bound_left, bound_right]\n\n#Define the domain geometry\ncornerLowerLeft = [0., 0.]\nlengthx = 2.\nlengthy = 1.\ndegP = [3, 3]\nnumSubdiv = 80\nnrb = nrbsquare(cornerLowerLeft, lengthx, lengthy, degP, numSubdiv)\nIGAmesh = genMesh(nrb)\n#plotBasisParam(IGAmesh)\n\ngauss_rule = [genGaussLegendre(degP[1]+1), genGaussLegendre(degP[2]+1)]\nstiff = assemble_stiff2D(IGAmesh, a0, gauss_rule)\nmass = assemble_mass2D(IGAmesh, a1, gauss_rule)\nrhs = assemble_rhs2D(IGAmesh, f, gauss_rule)\nbcdof_all, elem_all = classifyBoundary2D(IGAmesh)\nlhs = mass + stiff\nlhs, rhs = applyBCnurbs(IGAmesh, bound_all, lhs, rhs, bcdof_all, elem_all, gauss_rule)\n\nprintln(\"Solving linear system\")\n@time sol0 = lhs\\rhs\nprintln(\"Plotting...\")\n@time plotSol(IGAmesh, real(sol0), \"AcousticDuctReal\")\n@time plotSolError(IGAmesh, real(sol0), exact_sol, \"AcousticDuctRealError\")\nprintln(\"Computing error\")\n@time relL2Err, relH1Err = compErrorNorm(IGAmesh, real(sol0), exact_sol, deriv_exact_sol, a0, gauss_rule)\nprintln(\"Relative L2-norm error is $relL2Err\")\nprintln(\"Relative H1-seminorm error is $relH1Err\")\nprint(\"Done!\")\n", "meta": {"hexsha": "a617c9d3ff19e2316f78cf975043efba497047ae", "size": 2058, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/HelmholtzAcousticDuct.jl", "max_stars_repo_name": "canitesc/IGAPack.jl", "max_stars_repo_head_hexsha": "bb2b5e8d01afd9ca8a59055380ca00d2c8f951b1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-07-30T13:49:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T08:18:26.000Z", "max_issues_repo_path": "examples/HelmholtzAcousticDuct.jl", "max_issues_repo_name": "canitesc/IGAPack.jl", "max_issues_repo_head_hexsha": "bb2b5e8d01afd9ca8a59055380ca00d2c8f951b1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/HelmholtzAcousticDuct.jl", "max_forks_repo_name": "canitesc/IGAPack.jl", "max_forks_repo_head_hexsha": "bb2b5e8d01afd9ca8a59055380ca00d2c8f951b1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-30T13:49:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-09T11:32:36.000Z", "avg_line_length": 34.8813559322, "max_line_length": 105, "alphanum_fraction": 0.6763848397, "num_tokens": 812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951570602081, "lm_q2_score": 0.8221891218080991, "lm_q1q2_score": 0.7682495336050734}}
{"text": "\"\"\"\nReturn the Inorder traversal of a complete binary tree with given `height`.\n(Root node will be `0` and placed in the middle of the array\n\"\"\"\nfunction binary_inorder(height::Integer)::Vector{Int}\n    n = (1 << Int(height)) - 1\n    out = Vector{Int}(undef, n)\n\n    s = 2\n    while n >= 1\n        t = s >> 1\n        b, a = n-1, n >> 1\n        for (i, j) in enumerate(a:b)\n            out[i*s - t] = j\n        end\n        n >>= 1\n        s <<= 1\n    end\n\n    return out\nend\n", "meta": {"hexsha": "ed23d366a1fc93953e5b6978efbb7ea24415133e", "size": 474, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/src/Tree/inorder.jl", "max_stars_repo_name": "EQt/graphidx", "max_stars_repo_head_hexsha": "9716488cf29f6235072fc920fa1a473bf88e954f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-04-03T15:18:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T15:22:48.000Z", "max_issues_repo_path": "julia/src/Tree/inorder.jl", "max_issues_repo_name": "EQt/graphidx", "max_issues_repo_head_hexsha": "9716488cf29f6235072fc920fa1a473bf88e954f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/src/Tree/inorder.jl", "max_forks_repo_name": "EQt/graphidx", "max_forks_repo_head_hexsha": "9716488cf29f6235072fc920fa1a473bf88e954f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5454545455, "max_line_length": 75, "alphanum_fraction": 0.5168776371, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7681553218423551}}
{"text": "# There are exactly ten ways of selecting three from five, 12345:\n# \n# 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345\n# \n# In combinatorics, we use the notation, (5 3)=10.\n# \n# In general, (n r)=n!/(r!(n−r)!), where r≤n, n!=n×(n−1)×...×3×2×1, and 0!=10!=1.\n# \n# It is not until n=23 that a value exceeds one-million: (23 10)=1144066.\n#\n# How many, not necessarily distinct, values of (n r) for 1≤n≤100, are greater\n# than one-million?\n\n\nusing ProjectEulerSolutions\n\n# We note that (n r) = (n (n-r)), and that when r = n/2, the value of (n r) is\n# maximal.  Thus we calculate from (n r/2-k) for k until we get a value of more\n# than 1 million.  We save more time by further constraining the range of k\n# values.  This is mostly a book-keeping exercise.\nfunction p053solution(n_max::Integer=3, thresh=1_000)::Integer\n    n_min = 23\n    r = 3\n\n    total = 0\n    for n in n_max:-1:n_min\n        # The value of r where we surpass the threshold will only get larger\n        while binomial(n, r) < thresh\n            r += 1\n        end\n        total += (n - r * 2  + 1)\n    end\n    return total\nend\n\np053 = Problems.Problem(p053solution)\n\nProblems.benchmark(p053, 100, 1_000_000)\n", "meta": {"hexsha": "d9c529a165cccb4053bc762533e630501c47062f", "size": 1179, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/053.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/053.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/053.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2307692308, "max_line_length": 81, "alphanum_fraction": 0.6386768448, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556619, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7681553200768133}}
{"text": "# Legendre-Gauss quadrature weights and nodes\n# This code was originally written for Matlab\n#  by Greg von Winckel - 02/25/2004\n# posted on Mathworks website and licensed under BSD License\n# http://fr.mathworks.com/matlabcentral/fileexchange/4540-legendre-gauss-quadrature-weights-and-nodes\n# \n# \n\nfunction lgwt(N,a,b)\n\n\tN=N-1;\n\tN1=N+1; N2=N+2;\n\txu=linspace(-1,1,N1)';\n\n\ty=(cos((2*(0:N)'+1)*pi/(2*N+2))+(0.27/N1)*sin(pi*xu*N/N2))';\n\n\tL=zeros(N1,N2);\n\n\tLp=zeros(N1,N2);\n\ty0=2;\n\n\twhile maximum(abs(y-y0))>eps()\t\t\t\t\n\t\tL[:,1]=1;\n\t\tLp[:,1]=0;\t\t\n\t\tL[:,2]=y;\n\t\tfor k=2:N1\n\t\t\tL[:,k+1]=( (2*k-1)*y.*L[:,k]-(k-1)*L[:,k-1] )/k;\n\t\tend\t \n\t\tLp=(N2)*( L[:,N1]-y.*L[:,N2] )./(1-y.^2);   \t\t\n\t\ty0=y;\n\t\ty=y0-L[:,N2]./Lp;\t\t\n\tend\n\n\tx=(a*(1-y)+b*(1+y))/2;      \n\n\tw=(b-a)./((1-y.^2).*Lp.^2)*(N2/N1)^2;\n\n\treturn x,w\nend", "meta": {"hexsha": "bdada46e0c0c88673c3fb6ac0a4b691d8831fa7e", "size": 796, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lgwt.jl", "max_stars_repo_name": "flavioluiz/PortHamiltonian", "max_stars_repo_head_hexsha": "8dc9e517292a95b4ae04ab15e8fbde30f0349caf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-08T05:39:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-08T05:39:52.000Z", "max_issues_repo_path": "src/lgwt.jl", "max_issues_repo_name": "flavioluiz/PortHamiltonian", "max_issues_repo_head_hexsha": "8dc9e517292a95b4ae04ab15e8fbde30f0349caf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lgwt.jl", "max_forks_repo_name": "flavioluiz/PortHamiltonian", "max_forks_repo_head_hexsha": "8dc9e517292a95b4ae04ab15e8fbde30f0349caf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4102564103, "max_line_length": 101, "alphanum_fraction": 0.5565326633, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7681553179348166}}
{"text": "using LinearAlgebra\r\n\r\n# coefficients from PD of π functions\r\nπ = [70 -30 0;\r\n     -30 140 -50;\r\n     0 -50 50]\r\n# Force Vector\r\nf = Float64[0 100 60]\r\nF = transpose(f)\r\n\r\n# Displacement vector\r\nu = π\\F\r\nprintln(\"Nodal displacement vector (mm):\")\r\ndisplay(u)", "meta": {"hexsha": "1031899ada2672b14f818b0fb18fd3c5e4cb0037", "size": 258, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "inclass_September9_Potential.jl", "max_stars_repo_name": "UltraHeckerNick/MechanicalPrograms_small", "max_stars_repo_head_hexsha": "1059fb6c0d391be5ef75c4ba165e4f48819bfb2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inclass_September9_Potential.jl", "max_issues_repo_name": "UltraHeckerNick/MechanicalPrograms_small", "max_issues_repo_head_hexsha": "1059fb6c0d391be5ef75c4ba165e4f48819bfb2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inclass_September9_Potential.jl", "max_forks_repo_name": "UltraHeckerNick/MechanicalPrograms_small", "max_forks_repo_head_hexsha": "1059fb6c0d391be5ef75c4ba165e4f48819bfb2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.4285714286, "max_line_length": 43, "alphanum_fraction": 0.6317829457, "num_tokens": 81, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7681553141571393}}
{"text": "# hyperbolic_expansion.jl\n\nmodule hypergeometric_expansion\nexport hypergeom_exp\n\ninclude(\"arb_hypgeom.jl\")\nimport .arb_hypgeom\nusing ArbNumerics\n\nfunction arb_binomial(x, y; prec = 64)\n    setextrabits(0)\n    setprecision(ArbReal, prec)\n    x = ArbReal(\"$x\")\n    y = ArbReal(\"$y\")\n    one = ArbReal(\"1\")\n    ArbNumerics.gamma(x + one) / (ArbNumerics.gamma(y + one) * ArbNumerics.gamma(x - y + one))\nend\n\n\"\"\"\nThis function implements the binomial expansion of the denominator of the integrals:\n\n    ∫_0^1 cosh(zt) / (4a^2/β^2 - t^2)^(n+3/2) dt\n    ∫_0^1 sinh(zt) / (4a^2/β^2 - t^2)^(n+3/2) dt\n\nwhich is:\n\n    ∑_{m=0}^∞ C(-n-3/2, m) (-1)^m (β/2a)^{2n+2m+3} ∫_0^1 cosh(zt) t^{2m} dt\n    ∑_{m=0}^∞ C(-n-3/2, m) (-1)^m (β/2a)^{2n+2m+3} ∫_0^1 sinh(zt) t^{2m} dt.\n\nand also substitutes the integrals for:\n\n    ∫_0^1 cosh(zt) t^{2m} dt = ∑_{t=0}^∞ z^{2t} / ((2t+2m+1)⋅(2t)!)\n    ∫_0^1 sinh(zt) t^{2m} dt = ∑_{t=0}^∞ z^{2t+1} / ((2t+2m+2)⋅(2t+1)!)\n\nby replacing those integrals with one_F_two_fast() from arb_hypgeom.jl. h=0 gives cosh version, h=1 gives sinh version.\n\"\"\"\nfunction hypergeom_exp(z, n, β, a, h; prec = 64)\n# h = 0 gives cosh, h = 1 gives sinh.\n\n    # Initialise precision of ArbReal to prec.\n    p = prec\n    setextrabits(0)\n    setprecision(ArbReal, p)\n\n    z = ArbReal(\"$z\")\n    n = ArbReal(\"$n\")\n    β = ArbReal(\"$β\")\n    a = ArbReal(\"$a\")\n\n    m = ArbReal(\"0\")\n    result = ArbReal(\"0.0\")\n    term = ArbReal(\"1.0\")\n    err = eps(result)  # Machine accuracy of specified precision prec.\n\n    while abs(midpoint(term)) > err * abs(midpoint(result))\n\n        term = ArbReal(β * arb_binomial(-n - 3/2, m; prec = p) * (-1)^m * (β / (2 * a))^(2 * m) * arb_hypgeom.one_f_two_fast(z, m, h; prec = p) / a^(n + 2))\n        result += term\n        # println(\"term: m = \", m, \"\\nterm value: \", ball(ArbReal(term, bits = prec)), \"\\ncumulant result: \", ball(ArbReal(result, bits = prec)), \"\\n\")\n        m += ArbReal(\"1\")\n\n        # Double precision if rounding error in result exceeds accuracy specified by prec.\n        if radius(result) > err * abs(midpoint(result))\n            p *= 2\n            setprecision(ArbReal, p)\n            # println(\"Not precise enough. Error = \", abs(radius(result)/midpoint(result)), \" > \", err, \". Increasing precision to \", p, \" bits.\\n\")\n\n            n = ArbReal(\"$n\")\n            z = ArbReal(\"$z\")\n            β = ArbReal(\"$β\")\n            a = ArbReal(\"$a\")\n\n            m = ArbReal(\"0\")\n            result = ArbReal(\"0.0\")\n            term = ArbReal(\"1.0\")\n        end\n    end\n    # println(\"z: \", ArbReal(z, bits = prec), \". Final result: \", ArbReal(result, bits = prec))\n    ArbReal(result, bits = prec)\nend\n\n# β = ArbReal(\"2.0\")\n# α = ArbReal(\"7.0\")\n# v = ArbReal(\"5.8\")\n# w = ArbReal(\"1.6\")\n# R = ArbReal((v^2 - w^2) / (w^2 * v))\n# a = ArbReal(sqrt(β^2 / 4 + R * β * coth(β * v / 2)))\n# z = ArbReal(\"90.61\")\n# n = ArbReal(\"12.0\")\n# @time c = hypergeom_exp(z, n, β, a, 0; prec = 64)\n# @show(c)\nend # end module\n\n", "meta": {"hexsha": "de973f1bde44a631662d357ee3184a3193420f39", "size": 2949, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "arb/HypergeometricExpansion.jl", "max_stars_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_stars_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-07-26T17:46:18.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-26T17:46:18.000Z", "max_issues_repo_path": "arb/HypergeometricExpansion.jl", "max_issues_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_issues_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arb/HypergeometricExpansion.jl", "max_forks_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_forks_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3723404255, "max_line_length": 156, "alphanum_fraction": 0.5564598169, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7681553055891525}}
{"text": "\"\"\"\n1-D Gradient\n\n    gradient(a::Array, dx::Float64=1)\n    :param f: Vector\n    :param dx: stepsize\n\n    :return g: gradient\n\"\"\"\nfunction gradient(f::Array{Float64, 1}, dx::Float64=1.)\n    n = length(f)\n    g = zeros(n)\n    h = dx*(1:n)\n    # Take forward differences on left and right edges\n    g[1] = (f[2] - f[1])/(h[2]-h[1])\n    g[n] = (f[n] - f[n-1])/(h[end]-h[end-1])\n\n    # Take centered differences on interior points\n    h = h[3:n]-h[1:(n-2)]\n    g[2:(n-1)] = (f[3:n]-f[1:(n-2)])/h[1]\n\n    return g\nend\n\n\n\"\"\"\n2-D Gradient\n\n    gradient2(a::Array, dx::Float64=1, dy::Float=1)\n    :param a: matrix\n    :param dx: stepsize\n    :param dy: stepsize\n\n    :return dxdu: derivatives along x\n    :return dydv: derivatives along y\n\"\"\"\nfunction gradient2(a::Array, dx::Float64=1., dy::Float64=1.)\n    m,n = size(a);\n    dxdu = zeros(m,n);\n    dydv = zeros(m,n);\n\n    for i=1:m\n        dxdu[i,:] = gradient(vec(a[i,:]), dx)\n    end\n\n    for i=1:n\n        dydv[:,i] = gradient(a[:,i], dy)\n    end\n\n    return dxdu, dydv\nend\n\n\n\"\"\"\nCreates Rectangular Grid in 2-D space\n\n    meshgrid(a::LinRange,b::LinRange)\n\"\"\"\nfunction meshgrid(a::LinRange,b::LinRange)\n    grid_a = [i for i in a, j in b]';\n    grid_b = [j for i in a, j in b]';\n\n    return grid_a, grid_b\nend\n\n\n\"\"\"\nLinear interpolation\n\n    approx(xd, yd, xi)\n    :param xd: x samples\n    :param yd: response samples\n    :param xi: new x samples\n\"\"\"\nfunction approx(xd, yd, xi)\n    nd = length(xd);\n    ni = length(xi);\n\n    yi = zeros(ni);\n    for i in 1:ni\n        if (xi[i] <= xd[1])\n            t = (xi[i]-xd[1]) / (xd[2] - xd[1]);\n            yi[i] = (1.0 - t) * yd[1] + t * yd[2];\n        elseif (xd[nd] <= xi[i])\n            t = (xi[i] - xd[nd-1]) / (xd[nd] - xd[nd-1]);\n            yi[i] = (1.0 - t) * yd[nd-1] + t * yd[nd];\n        else\n            for k in 2:nd\n                if (xd[k-1] <= xi[i] && xi[i] <= xd[k])\n                    t = (xi[i] - xd[k-1]) / (xd[k] - xd[k-1]);\n                    yi[i] = (1.0 - t) * yd[k-1] + t * yd[k];\n                    break\n                end\n            end\n        end\n    end\n\n    return yi\nend\n\n\n\"\"\"\nTrapezoidal Integration\n\n    trapz(x, y, dim=1)\n    :param x: vector of time samples\n    :param y: array of response samples\n    :param dim: dimension along which to integrate\n\"\"\"\nfunction trapz(x::Array{Float64, 1}, y::Array{Float64}, dim::Integer=1)\n    perm = [dim:max(ndims(y),dim); 1:dim-1];\n    y = permutedims(y, perm);\n    if ndims(y) == 1\n        m = 1;\n    else\n        m = size(y,1);\n    end\n\n    if m == 1\n        M = length(y);\n        out = sum(diff(x).*(y[1:M-1] + y[2:M])/2.0);\n    else\n        out = transpose(diff(x)) * (reshape(y,Val(2))[1:m-1,:] + reshape(y,Val(2))[2:m,:])/2.0;\n        siz = size(y); siz = collect(siz); siz[1] = 1;\n        out = reshape(out, tuple(siz...));\n        out = permutedims(out, invperm(perm));\n        ind = findall(collect(size(out)).==1);\n        out = dropdims(out,dims=ind[1]);\n        if length(out) == 1;\n            out = out[1];\n        end\n    end\n\n    return out\nend\n\n\n\"\"\"\nCumulative Trapezoidal Integration\n\n    cumtrapz(x, y, dim=1)\n    :param x: vector describing time samples\n    :param y: array describing response\n    :param dim: dimension to integrate over\n\"\"\"\nfunction cumtrapz(x::Array{Float64, 1}, y::Array{Float64}, dim::Integer=1)\n    perm = [dim:max(length(size(y)),dim); 1:dim-1];\n    y = permutedims(y, perm);\n    if ndims(y) == 1\n        n = 1;\n        m = length(y);\n    else\n        m, n = size(y);\n    end\n\n    if n == 1\n        dt = diff(x)/2.0;\n        z = [0; cumsum(dt.*(y[1:(m-1)] + y[2:m]))];\n    else\n        dt = repeat(diff(x)/2.0,1,n);\n        z = [zeros(1,n); cumsum(dt.*(y[1:(m-1), :] + y[2:m, :]),dims=1)];\n        z = permutedims(z, invperm(perm));\n    end\n\n    return z\nend\n\n\n\"\"\"\nCumulative Trapezoidal Integration using midpoint\n\n    cumtrapzmid(x, y, c)\n    :param x: time samples\n    :param y: resposne samples\n    :param c: midpoint\n    :param mid: midpoint location\n\"\"\"\nfunction cumtrapzmid(x, y, c, mid)\n    a = length(x);\n\n    # case < mid\n    fn = zeros(a);\n    tmpx = x[(mid-1):-1:1];\n    tmpy = y[(mid-1):-1:1];\n    tmp = c .+ cumtrapz(tmpx, tmpy);\n    fn[1:(mid-1)] = reverse(tmp);\n\n    # case >= mid\n    fn[mid:a] = c .+ cumtrapz(x[mid:a],y[mid:a]);\n\n    return fn\n\nend\n\n\n\"\"\"\nMultivariate Normal random number generation\n\n    mvnrand(mu, C, n)\n    :param mu: mean vector\n    :param C: covariance matrix\n    :param n: number of samples\n\"\"\"\nfunction mvnrand(mu, C, n)\n    tmp = cholesky(C, :U, Val{true});\n    R = tmp[:U];\n    R = Array(R);\n    R = R[:, tmp.piv];\n    retval = randn(n, size(R,1)) * R;\n    retval += transpose(repeat(mu, 1, n));\n    return transpose(retval)\nend\n\n\n\"\"\"\nLinear interpolation when response contains flat regions\n\n    interp1_flat(x, y, xx)\n    :param x: time samples\n    :param y: response samples\n    :param xx: new time samples\n\"\"\"\nfunction interp1_flat(x,y,xx)\n    flat = find(diff(x).<=0);\n    n = length(flat);\n\n    if n==0\n        tmp = interpolate((x,), y, Gridded(Linear()))\n        yy = tmp[xx];\n    else\n        yy = zeros(size(xx));\n        i1 = 1;\n        if flat[1] == 1\n            i2 = 1;\n            j = xx.==x[i2];\n            yy[j] = minimum(y[i2:i2+1]);\n        else\n            i2 = flat[1];\n            j = (xx.>=x[i1]) & (xx.<=x[i2]);\n            tmp = interpolate((x[i1:i2],), y[i1:i2], Gridded(Linear()))\n            yy[j] = tmp[xx[j]];\n            i1 = copy(i2);\n        end\n        for k = 2:n\n            i2 = flat[k];\n            if i2 > i1+1\n                j = (xx.>=x[i1]) & (xx.<=x[i2]);\n                yi = interpolate((x[i1+1:i2],), y[i1+1:i2], Gridded(Linear()))\n                yy[j] = tmp[xx[j]];\n            end\n            j = xx.==x[i2];\n            yy[j] = minimum(y[i2:i2+1]);\n            i1 = copy(i2);\n        end\n        i2 = length(x);\n        j = (xx.>=x[i1]) & (xx.<=x[i2]);\n        if i1+1 == i2\n            yy[j] = y[i2];\n        else\n            tmp = interpolate((x[i1+1:i2],), y[i1+1:i2], Gridded(Linear()))\n            yy[j] = tmp[xx[j]];\n        end\n    end\n\n    return yy\nend\n\nfunction basis_fourier(f_domain::Vector, numBasis::Int64, fourier_p::Int64)\n    result = Array{Float64}(undef,length(f_domain),2*numBasis)\n    for i in 1:2*numBasis\n        j = ceil(i/2)\n        if ((i % 2) == 1)\n            result[:,i] = sqrt(2) * sin.(2*j*pi*f_domain/fourier_p)\n        end\n        if ((i % 2) == 0)\n            result[:,i] = sqrt(2) * cos.(2*j*pi*f_domain/fourier_p)\n        end\n    end\n\n    out = basis(f_domain,result)\n    return out\nend\n\nfunction f_predictfunction(f::func, at; deriv=0, method=\"linear\")\n    if method==\"linear\"\n        if (deriv==0)\n            result = approx(f.x, f.y, at)\n        end\n        if (deriv == 1)\n            fmod = approx(f.x, f.y, at)\n            diffy1 = [0; diff(fmod)]\n            diffy2 = [diff(fmod); 0]\n            diffx1 = [0; diff(at)]\n            diffx2 = [diff(at); 0]\n\n            result = (diffy2 + diffy1) ./ (diffx2 + diffx1)\n        end\n    else\n        error(\"Method not implemented\")\n    end\n\n    out = func(at, result)\n    return out\nend\n\nfunction f_basistofunction(f_domain, coef, cbasis::basis; coefconst=0)\n    if (size(cbasis.matrix,2)<length(coef))\n        error(\"coefficients exceeds basis functions\")\n    end\n\n    y1 = cbasis.matrix[:,(1:length(coef))] * coef .+ coefconst\n    result = func(cbasis.x, y1)\n    y1 = f_predictfunction(result, f_domain)\n\n    return y1\nend\n", "meta": {"hexsha": "a547db2607d5aafaff4f802a06676eb63abff726", "size": 7425, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/misc_funcs.jl", "max_stars_repo_name": "pnavaro/ElasticFDA.jl", "max_stars_repo_head_hexsha": "0ed8c3f483c3a62f4215a6b65894da34e77eefc1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-02-05T23:39:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-03T06:41:47.000Z", "max_issues_repo_path": "src/misc_funcs.jl", "max_issues_repo_name": "pnavaro/ElasticFDA.jl", "max_issues_repo_head_hexsha": "0ed8c3f483c3a62f4215a6b65894da34e77eefc1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-08-31T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-15T02:18:36.000Z", "max_forks_repo_path": "src/misc_funcs.jl", "max_forks_repo_name": "pnavaro/ElasticFDA.jl", "max_forks_repo_head_hexsha": "0ed8c3f483c3a62f4215a6b65894da34e77eefc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:13:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T17:42:16.000Z", "avg_line_length": 23.4227129338, "max_line_length": 95, "alphanum_fraction": 0.5012794613, "num_tokens": 2497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7681121599468981}}
{"text": "# elastic-net regularization\n\nexport ElasticNet\n\n\"\"\"\n**Elastic-net regularization**\n\n    ElasticNet(μ=1.0, λ=1.0)\n\nReturns the function\n```math\nf(x) = μ\\\\|x\\\\|_1 + (λ/2)\\\\|x\\\\|^2,\n```\nfor nonnegative parameters `μ` and `λ`.\n\"\"\"\nstruct ElasticNet{R <: Real} <: ProximableFunction\n    mu::R\n    lambda::R\n    function ElasticNet{R}(mu::R, lambda::R) where {R <: Real}\n        if lambda < 0 || mu < 0\n            error(\"parameters `μ` and `λ` must be nonnegative\")\n        else\n            new(mu, lambda)\n        end\n    end\nend\n\nis_separable(f::ElasticNet) = true\nis_prox_accurate(f::ElasticNet) = true\nis_convex(f::ElasticNet) = true\n\nElasticNet(mu::R=1.0, lambda::R=1.0) where {R <: Real} = ElasticNet{R}(mu, lambda)\n\nfunction (f::ElasticNet)(x::AbstractArray{R}) where R <: RealOrComplex\n    return f.mu*norm(x,1) + (f.lambda/2)*norm(x,2)^2\nend\n\nfunction prox!(y::AbstractArray{R}, f::ElasticNet{R}, x::AbstractArray{R}, gamma::R=R(1)) where R <: Real\n    sqnorm2x = R(0)\n    norm1x = R(0)\n    gm = gamma*f.mu\n    gl = gamma*f.lambda\n    for i in eachindex(x)\n        y[i] = (x[i] + (x[i] <= -gm ? gm : (x[i] >= gm ? -gm : -x[i])))/(1 + gl)\n        sqnorm2x += abs2(y[i])\n        norm1x += abs(y[i])\n    end\n    return f.mu*norm1x + (f.lambda/2)*sqnorm2x\nend\n\nfunction prox!(y::AbstractArray{R}, f::ElasticNet{R}, x::AbstractArray{R}, gamma::AbstractArray{R}) where R <: Real\n    sqnorm2x = R(0)\n    norm1x = R(0)\n    for i in eachindex(x)\n        gm = gamma[i]*f.mu\n        gl = gamma[i]*f.lambda\n        y[i] = (x[i] + (x[i] <= -gm ? gm : (x[i] >= gm ? -gm : -x[i])))/(1 + gl)\n        sqnorm2x += abs2(y[i])\n        norm1x += abs(y[i])\n    end\n    return f.mu*norm1x + (f.lambda/2)*sqnorm2x\nend\n\nfunction prox!(y::AbstractArray{Complex{R}}, f::ElasticNet{R}, x::AbstractArray{Complex{R}}, gamma::R=R(1)) where R <: Real\n    sqnorm2x = R(0)\n    norm1x = R(0)\n    gm = gamma*f.mu\n    gl = gamma*f.lambda\n    for i in eachindex(x)\n        y[i] = sign(x[i])*max(0, abs(x[i]) - gm)/(1 + gl)\n        sqnorm2x += abs2(y[i])\n        norm1x += abs(y[i])\n    end\n    return f.mu*norm1x + (f.lambda/2)*sqnorm2x\nend\n\nfunction prox!(y::AbstractArray{Complex{R}}, f::ElasticNet{R}, x::AbstractArray{Complex{R}}, gamma::AbstractArray{R}) where R <: Real\n    sqnorm2x = R(0)\n    norm1x = R(0)\n    for i in eachindex(x)\n        gm = gamma[i]*f.mu\n        gl = gamma[i]*f.lambda\n        y[i] = sign(x[i])*max(0, abs(x[i]) - gm)/(1 + gl)\n        sqnorm2x += abs2(y[i])\n        norm1x += abs(y[i])\n    end\n    return f.mu*norm1x + (f.lambda/2)*sqnorm2x\nend\n\nfunction gradient!(y::AbstractArray{T}, f::ElasticNet{R}, x::AbstractArray{T}) where {T <: RealOrComplex, R <: Real}\n    # Gradient of 1 norm\n    y .= f.mu.*sign.(x)\n    # Gradient of 2 norm\n    y .+= f.lambda.*x\n    return f.mu*norm(x,1) + (f.lambda/2)*norm(x,2)^2\nend\n\nfun_name(f::ElasticNet) = \"elastic-net regularization\"\nfun_dom(f::ElasticNet) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::ElasticNet) = \"x ↦ μ||x||_1 + (λ/2)||x||²\"\nfun_params(f::ElasticNet) = \"μ = $(f.mu), λ = $(f.lambda)\"\n\nfunction prox_naive(f::ElasticNet, x::AbstractArray{R}, gamma::Real=1.0) where R <: RealOrComplex\n    uz = max.(0, abs.(x) .- gamma*f.mu)/(1 + f.lambda * gamma)\n    return sign.(x) .* uz, f.mu * norm(uz,1) + (f.lambda/2) * norm(uz)^2\nend\n\nfunction prox_naive(f::ElasticNet, x::AbstractArray{R}, gamma::AbstractArray) where R <: RealOrComplex\n    uz = max.(0, abs.(x) .- gamma.*f.mu)./(1 .+ f.lambda .* gamma)\n    return sign.(x) .* uz, f.mu * norm(uz,1) + (f.lambda/2) * norm(uz)^2\nend\n", "meta": {"hexsha": "5349fae081d0fa987d7a538f5e43e6fd29b2c239", "size": 3540, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/elasticNet.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_stars_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/elasticNet.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_issues_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/elasticNet.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_forks_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6071428571, "max_line_length": 133, "alphanum_fraction": 0.5796610169, "num_tokens": 1286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7681121537394447}}
{"text": "# This is a Julia adaptation of the Matlab code from O. Ledoit and M. Wolf\n# solely used to test our own implementation of their estimator.\n# Their code was released under the BSD-2 license with the copyright notice\n# below.\n# https://www.econ.uzh.ch/en/people/faculty/wolf/publications.html#9\n\n###########################################################################\n# This file is released under the BSD 2-clause license.\n\n# Copyright (c) 2014, Olivier Ledoit and Michael Wolf\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n###########################################################################\n\nusing LinearAlgebra\nusing Statistics\n\n# comments marked with a `#` come from their code\n# comments marked with a `#<#>` are ours\n\nfunction matlab_ledoitwolf_covcor(z)\n    x = copy(z)\n\n    # de-mean returns\n    t, n  = size(x)\n    meanx = mean(x, dims=1)\n    x -= repeat(meanx, outer=(t, 1))\n\n    # compute sample covariance matrix\n    sample = (1/t) * (x'*x)\n\n    # compute prior\n    diagsample = diag(sample)\n    sqrtvar = sqrt.(diagsample)\n\n    sqrtvar_mat = repeat(sqrtvar, outer=(1, n))\n\n    rBar = (sum(sample./(sqrtvar_mat .* sqrtvar_mat'))-n)/(n*(n-1))\n    prior = rBar * sqrtvar_mat .* sqrtvar_mat'\n\n    #<#> replace the diagonal\n    prior -= Diagonal(diag(prior))\n    prior += Diagonal(diagsample)\n\n    #<#> compute optimal shrinkage\n\n    # what we call pi-hat\n    y = x.^2;\n    phiMat = y'*y/t - 2*(x'*x) .* sample/t + sample.^2\n    phi = sum(phiMat)\n\n    # what we call rho-hat\n    term1    = ((x.^3)'*x)/t\n    help     = x'*x/t\n    helpDiag = diag(help)\n    term2    = repeat(helpDiag, outer=(1, n)) .* sample\n    term3    = help .* repeat(diagsample, outer=(1, n))\n    term4    = repeat(diagsample, outer=(1, n)) .* sample\n    thetaMat = term1 - term2 - term3 + term4\n    #<#> remove the diagonal\n    thetaMat -= Diagonal(diag(thetaMat))\n    rho       = sum(diag(phiMat)) + rBar*sum(sqrtvar'./sqrtvar.*thetaMat)\n\n    # what we call gamma hat\n    gamma = sum((sample - prior).^2)\n    kappa = (phi - rho) / gamma\n    shrinkage = max(0, min(1, kappa/t))\n\n    part_results = Dict(\n        \"r̄\" => rBar,\n        \"F\" => prior,\n        \"shrinkage\" => shrinkage,\n        \"kappa\" => kappa,\n        \"gamma\" => gamma,\n        \"lwcov\" => shrinkage*prior + (1-shrinkage)*sample)\n\n    return part_results\nend\n", "meta": {"hexsha": "8541e2bb93c58bb6767beaca513bffc66e8a47ee", "size": 3569, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ref_lw_lshrink.jl", "max_stars_repo_name": "oxinabox/CovarianceEstimation.jl", "max_stars_repo_head_hexsha": "467c3d84d91f8e30969177482966ba96ee9bc3d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2018-11-27T09:45:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T13:04:05.000Z", "max_issues_repo_path": "test/ref_lw_lshrink.jl", "max_issues_repo_name": "oxinabox/CovarianceEstimation.jl", "max_issues_repo_head_hexsha": "467c3d84d91f8e30969177482966ba96ee9bc3d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 71, "max_issues_repo_issues_event_min_datetime": "2018-11-27T03:54:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T10:42:53.000Z", "max_forks_repo_path": "test/ref_lw_lshrink.jl", "max_forks_repo_name": "oxinabox/CovarianceEstimation.jl", "max_forks_repo_head_hexsha": "467c3d84d91f8e30969177482966ba96ee9bc3d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2018-12-17T01:39:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T11:09:24.000Z", "avg_line_length": 35.3366336634, "max_line_length": 75, "alphanum_fraction": 0.6514429812, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7680940519910472}}
{"text": "export Cubic, Spline, npatches, funk\n\n# see http://mathworld.wolfram.com/CubicSpline.html\n\nimport Base: getindex, show\n\n\"\"\"\n`Cubic(a,b,c,d)` is a 3rd degree polynomial `a+bx+cx^2+dx^3`.\nUse `f(x)` to evalue `f` at the value `x`.\n\"\"\"\nstruct Cubic\n    a::Number\n    b::Number\n    c::Number\n    d::Number\nend\n\n(f::Cubic)(x::Number) = f.a + x*(f.b + x*(f.c+x*f.d))\n\n\"\"\"\n`f'` where `f` is a `Cubic` or `Spline` is the derivative\nof `f`.\n\"\"\"\nBase.adjoint(f::Cubic) = Cubic(f.b,2f.c,3f.d,0)\n\nstruct Spline\n    patches::Array{Cubic,1}\n    closed::Bool\nend\n\nis_closed(S::Spline) = S.closed\n\n\nfunction Base.adjoint(S::Spline)\n    plist = adjoint.(S.patches)\n    return Spline(plist,S.closed)\nend\n\n\"\"\"\n`Spline(vals,kind)` returns a cubic spline based on the values in `vals`.\nThe resulting spline `S` will have the property that `S(1)==y[1]`,\n`S(2)==y[2]`, and so on up to `S(n)==y[n]` where `n` is the length of `y`.\n\n+ If `kind` is `:open` then the second derivatives at the end points will be zero. (This is the default.)\n+ If `kind` is `:closed` then we assume that we are interpolating a periodic function where `S(n+1)==S(1)`.\n\"\"\"\nfunction Spline(y::Array{T,1},kind::Symbol=:open)::Spline where T<:Number\n    n = length(y)\n    if kind == :open\n        @assert n>2 \"Open splines must have at least three points\"\n        return open_spline(y)\n    end\n    if kind == :closed\n        @assert n>3 \"Closed splines must have at least four points\"\n        return closed_spline(y)\n    end\n\n    error(\"Spline type must be :open or :closed, not $kind\")\nend\n\nfunction npatches(S::Spline)\n    return length(S.patches)\nend\n\nfunction show(io::IO, S::Spline)\n    adjective = is_closed(S) ? \"Closed\" : \"Open\"\n    print(io, \"$adjective spline with $(npatches(S)) patches\")\nend\n\n\ngetindex(S::Spline, idx::Int) = S.patches[idx]\n\n\"\"\"\n`funk(S)` converts the Spline `S` into a callable function\n(e.g., that can be passed to `plot`).\n\"\"\"\nfunction funk(S)::Function\n    return x -> S(x)\nend\n\nfunction (S::Spline)(x::Real)\n    np = npatches(S)\n\n    if is_closed(S)\n\n        p = Int(floor(x))\n        x = mod(x,np)\n        p = Int(floor(x))\n\n        if p==0\n            p = np\n            x += np\n        end\n        f = S[p]\n        return f(x-p)\n    end\n\n    # open spline\n    p = Int(floor(x))\n    if x < 1\n        p = 1\n    end\n\n    if p > np\n        p = np\n    end\n    f = S[p]\n    return f(x-p)\nend\n\n\nfunction open_spline(y::Array{T,1})::Spline where T<:Number\n    n = length(y)\n    M = zeros(n,n)\n    for i=1:n\n        M[i,i] = 4\n    end\n    M[1,1] = 2\n    M[n,n] = 2\n\n    for i=1:n-1\n        M[i,i+1] = 1\n        M[i+1,i] = 1\n    end\n\n    rhs = zeros(T,n)\n    rhs[1] = 3*(y[2]-y[1])\n    for k=2:n-1\n        rhs[k] = 3*(y[k+1]-y[k-1])\n    end\n    rhs[n] = 3*(y[n]-y[n-1])\n\n    D = M\\rhs\n\n    a = zeros(Number,n-1)\n    b = zeros(Number,n-1)\n    c = zeros(Number,n-1)\n    d = zeros(Number,n-1)\n\n    for j=1:n-1\n        a[j] = y[j]\n        b[j] = D[j]\n        c[j] = 3*(y[j+1]-y[j])-2D[j]-D[j+1]\n        d[j] = 2*(y[j]-y[j+1])+D[j]+D[j+1]\n    end\n    return Spline( [ Cubic(a[i],b[i],c[i],d[i]) for i=1:n-1 ] , false)\nend\n\nfunction closed_spline(y::Array{T,1})::Spline where T <: Number\n    yy = copy(y)\n    n = length(y)\n    prepend!(yy,y[end-3:end])\n    append!(yy,y[1:4])\n\n    S = open_spline(yy)\n\n    plist = S.patches[5:end-3]\n    return Spline(plist,true)\n\nend\n", "meta": {"hexsha": "d8d4658413e5bb956af937dbda27582a9917c2c8", "size": 3339, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cubic.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleDrawing.jl-d78a06e8-ae74-583c-9a07-0d6572347000", "max_stars_repo_head_hexsha": "0b871b42e72e44a9b0a7f924ad146ab242657a7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cubic.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleDrawing.jl-d78a06e8-ae74-583c-9a07-0d6572347000", "max_issues_repo_head_hexsha": "0b871b42e72e44a9b0a7f924ad146ab242657a7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cubic.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleDrawing.jl-d78a06e8-ae74-583c-9a07-0d6572347000", "max_forks_repo_head_hexsha": "0b871b42e72e44a9b0a7f924ad146ab242657a7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7391304348, "max_line_length": 107, "alphanum_fraction": 0.556753519, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7680940489104756}}
{"text": "using DataStructures\n\n# The implementation is referencing the wikipedia page\n# https://en.wikipedia.org/wiki/Matching_pursuit#The_algorithm\n\nconst default_max_iter = 20\nconst default_tolerance = 1e-6\n\n\nfunction SparseArrays.sparsevec(d::DefaultDict, m::Int)\n    SparseArrays.sparsevec(collect(keys(d)), collect(values(d)), m)\nend\n\n\nfunction matching_pursuit_(data::AbstractVector, dictionary::AbstractMatrix,\n                           max_iter::Int, tolerance::Float64)\n    n_atoms = size(dictionary, 2)\n\n    residual = copy(data)\n\n    xdict = DefaultDict{Int, Float64}(0.)\n    for i in 1:max_iter\n        if norm(residual) < tolerance\n            return sparsevec(xdict, n_atoms)\n        end\n\n        # find an atom with maximum inner product\n        products = dictionary' * residual\n        _, maxindex = findmax(abs.(products))\n        maxval = products[maxindex]\n        atom = dictionary[:, maxindex]\n\n        # c is the length of the projection of data onto atom\n        a = maxval / sum(abs2, atom)  # equivalent to maxval / norm(atom)^2\n        residual -= atom * a\n\n        xdict[maxindex] += a\n    end\n    return sparsevec(xdict, n_atoms)\nend\n\n\n\"\"\"\n    matching_pursuit(data::Vector, dictionary::AbstractMatrix;\n                     max_iter::Int = $default_max_iter,\n                     tolerance::Float64 = $default_tolerance)\n\nFind ``x`` such that ``Dx = y`` or ``Dx ≈ y`` where y is `data` and D is `dictionary`.\n```\n# Arguments\n* `max_iter`: Hard limit of iterations\n* `tolerance`: Exit when the norm of the residual < tolerance\n```\n\"\"\"\nfunction matching_pursuit(data::AbstractVector, dictionary::AbstractMatrix;\n                          max_iter::Int = default_max_iter,\n                          tolerance = default_tolerance)\n\n    if tolerance <= 0\n        throw(ArgumentError(\"`tolerance` must be > 0\"))\n    end\n\n    if max_iter <= 0\n        throw(ArgumentError(\"`max_iter` must be > 0\"))\n    end\n\n    if size(data, 1) != size(dictionary, 1)\n        throw(ArgumentError(\n            \"Dimensions must match: `size(data, 1)` and `size(dictionary, 1)`.\"\n        ))\n    end\n\n    matching_pursuit_(data, dictionary, max_iter, tolerance)\nend\n\n\n\"\"\"\n    matching_pursuit(data::AbstractMatrix, dictionary::AbstractMatrix;\n                     max_iter::Int = $default_max_iter,\n                     tolerance::Float64 = $default_tolerance)\n\nFind ``X`` such that ``DX = Y`` or ``DX ≈ Y`` where Y is `data` and D is `dictionary`.\n```\n# Arguments\n* `max_iter`: Hard limit of iterations\n* `tolerance`: Exit when the norm of the residual < tolerance\n```\n\"\"\"\nfunction matching_pursuit(data::AbstractMatrix, dictionary::AbstractMatrix;\n                          max_iter::Int = default_max_iter,\n                          tolerance::Float64 = default_tolerance)\n    K = size(dictionary, 2)\n    N = size(data, 2)\n\n    X = spzeros(K, N)\n\n    for i in 1:N\n        X[:, i] = matching_pursuit(\n            vec(data[:, i]),\n            dictionary,\n            max_iter = max_iter,\n            tolerance = tolerance\n        )\n    end\n    return X\nend\n", "meta": {"hexsha": "9d2dcff5636b351330ba1300332d6a97b183d0eb", "size": 3051, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matching_pursuit.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/KSVD.jl-80e3a25a-59dd-53ce-a95c-a94c81a42368", "max_stars_repo_head_hexsha": "fac7875b0fa77eade1e9322c51c590c4be0bf43c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-09-26T19:42:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T20:30:00.000Z", "max_issues_repo_path": "src/matching_pursuit.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/KSVD.jl-80e3a25a-59dd-53ce-a95c-a94c81a42368", "max_issues_repo_head_hexsha": "fac7875b0fa77eade1e9322c51c590c4be0bf43c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-04-16T06:22:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:26:32.000Z", "max_forks_repo_path": "src/matching_pursuit.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/KSVD.jl-80e3a25a-59dd-53ce-a95c-a94c81a42368", "max_forks_repo_head_hexsha": "fac7875b0fa77eade1e9322c51c590c4be0bf43c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-10-09T07:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-16T06:11:56.000Z", "avg_line_length": 28.5140186916, "max_line_length": 86, "alphanum_fraction": 0.6129137988, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002491, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7680940454375382}}
{"text": "function Newton_Spectral(nlp     :: AbstractNLPModel;\n                         x       :: AbstractVector=copy(nlp.meta.x0),\n                         ϵ       :: Real=√eps(eltype(x)),\n                         #ϵ       :: T = 1e-6,\n                         maxiter :: Int = 200,\n                         Lp      :: Real = 2 # norm Lp \n                         )# where T<:Real\n\n    T = eltype(x)\n    n = nlp.meta.nvar\n    @info log_header([:iter, :f, :dual, :step, :slope], [Int, T, T, T, T],\n                     hdr_override=Dict(:f=>\"f(x)\", :dual=>\"‖∇f‖\", :slope=>\"∇fᵀd\"))\n    f  ::T = obj(nlp,x)\n    ∇f :: Vector{T} = grad(nlp, x)\n    \n    τ₀ = 0.0005\n    τ₁ = 0.999\n\n    iter = 0\n    @info log_row(Any[iter, f, norm(∇f, Lp)])  \n\n    while (norm(∇f, Lp) > ϵ) && (iter <= maxiter)\n        H = Matrix(Symmetric(hess(nlp, x),:L))\n        Δ, O = eigen(H)\n        # Boost negative values of Δ to 1e-8\n        # devise an adaptative value for γ\n        γ = 1e-6\n        D = abs.(Δ) + max.((γ .- abs.(Δ)), 0.0) .*ones(n)\n        \n        d = - O*diagm(1.0 ./ D)*O'*∇f\n\n        #------------------------------------------\n        # Hard coded line search\n        hp0 = ∇f'*d\n        t=1.0\n        # Simple Wolfe forward tracking\n        xt = x + t*d\n        ∇ft = grad(nlp,xt)\n        hp = ∇ft'*d\n        ft = obj(nlp, xt)\n        #  while  ~wolfe & armijo\n        nbW = 0\n        while (hp <= τ₁ * hp0) && (ft <= ( f + τ₀*t*hp0)) && (nbW < 10)\n            t *= 5\n            xt = x + t*d\n            ∇ft = grad(nlp,xt)\n            hp = ∇ft'*d\n            ft = obj(nlp, xt)\n            nbW += 1\n            @debug \"W\", ft\n        end\n        tw = t\n        \n        # Simple Armijo backtracking\n        nbk = 0\n        while (ft > ( f + τ₀*t*hp0)) && (nbk < 20)\n            t *= 0.5\n            xt = x + t*d\n            ft = obj(nlp, xt)\n            nbk += 1\n            @debug \"A\", ft\n        end\n        #------------------------------------------\n        \n        x += t*d\n        f = ft\n        if t!=tw   ∇ft = grad(nlp, xt) end\n        ∇f = ∇ft\n        iter += 1\n        \n        @info log_row(Any[iter, f, norm(∇f, Lp), t, hp0])\n    end\n    if iter > maxiter @warn \"Maximum d'itérations\"\n    end\n    \n    return iter, f, norm(∇f, Lp), x\nend\n", "meta": {"hexsha": "83e15b4880ed69dd1d07893f73e054315bdd1ebb", "size": 2241, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Newton/NewtonSolver.jl", "max_stars_repo_name": "tmigot/LSDescent", "max_stars_repo_head_hexsha": "9a5e6055894abaeb87d8a95c7b10382440311a8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-13T19:17:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T20:07:05.000Z", "max_issues_repo_path": "src/Newton/NewtonSolver.jl", "max_issues_repo_name": "tmigot/LSDescent", "max_issues_repo_head_hexsha": "9a5e6055894abaeb87d8a95c7b10382440311a8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Newton/NewtonSolver.jl", "max_forks_repo_name": "tmigot/LSDescent", "max_forks_repo_head_hexsha": "9a5e6055894abaeb87d8a95c7b10382440311a8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-17T15:21:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T15:21:00.000Z", "avg_line_length": 28.7307692308, "max_line_length": 82, "alphanum_fraction": 0.3659080768, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.768094043897252}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,jl:hydrogen\n#     text_representation:\n#       extension: .jl\n#       format_name: hydrogen\n#       format_version: '1.3'\n#       jupytext_version: 1.10.3\n#   kernelspec:\n#     display_name: Julia 1.6.3\n#     language: julia\n#     name: julia-1.6\n# ---\n\n# %%\nusing LinearAlgebra\nusing Random\nusing Distributions\nusing StatsPlots\n\n# %%\nA = [\n    2 -1\n    -1 2\n]\n\n# %%\ndist = MvNormal(A)\n\n# %%\nA[1,2]/√(A[1,1]*A[2,2])\n\n# %%\nn = 2^10\nXY = rand(dist, n)\nX, Y = XY[1,:], XY[2,:]\n@show cor(X, Y)\n\nscatter(X, Y)\n\n# %%\nfunction sim(A, n, L=10^5)\n    dist = MvNormal(A)\n    R = zeros(L)\n    XY = zeros(2, n)\n    for i in eachindex(R)\n        rand!(dist, XY)\n        R[i] = @views cor(XY[1,:], XY[2,:])\n    end\n    R\nend\n\n# %%\nn = 2^6\nR = sim(A, n)\nZ = atanh.(R)\nr0 = A[1,2]/√(A[1,1]*A[2,2])\nz0 = atanh(r0)\nhistogram(Z; norm=true, alpha=0.3, bin=200)\nplot!(Normal(z0, 1/√(n - 3)))\nplot!(fit_mle(Normal, Z))\n\n# %%\nn = 2^8\nx, y = rand(Uniform(-1, 1), n), rand(Uniform(-1, 1), n)\nX, Y = x, x + y\n@show cor(X, Y)\nscatter(X, Y; label=\"\")\n\n# %%\nfunction sim2(n, L=10^5)\n    R = zeros(L)\n    d = Uniform(-1, 1)\n    x = zeros(n)\n    y = similar(x)\n    Y = similar(x)\n    for i in eachindex(R)\n        rand!(d, x)\n        rand!(d, y)\n        @. Y = x + y\n        R[i] = cor(x, Y)\n    end\n    R\nend\n\n# %%\nn = 2^6\nR = sim2(n)\nZ = atanh.(R)\nr0 = 1/√2\nz0 = atanh(r0)\nhistogram(Z; norm=true, alpha=0.3, bin=200)\nplot!(Normal(z0, 1/√(n - 3)))\nplot!(fit_mle(Normal, Z))\n\n# %%\nn = 2^8\nx, y = rand(Exponential(), n), rand(Exponential(), n)\nX, Y = x, x + y\n@show cor(X, Y)\nscatter(X, Y; label=\"\")\n\n# %%\nfunction sim3(n, L=10^5)\n    R = zeros(L)\n    d = Exponential()\n    x = zeros(n)\n    y = similar(x)\n    Y = similar(x)\n    for i in eachindex(R)\n        rand!(d, x)\n        rand!(d, y)\n        @. Y = x + y\n        R[i] = cor(x, Y)\n    end\n    R\nend\n\n# %%\nn = 2^6\nR = sim3(n)\nZ = atanh.(R)\nr0 = 1/√2\nz0 = atanh(r0)\nhistogram(Z; norm=true, alpha=0.3, bin=200)\nplot!(Normal(z0, 1/√(n - 3)))\nplot!(fit_mle(Normal, Z))\n\n# %%\nfunction simplot(dist, n, L=10^5)\n    Z = zeros(L)\n    x = zeros(n)\n    y = similar(x)\n    Y = similar(x)\n    for i in eachindex(R)\n        rand!(dist, x)\n        rand!(dist, y)\n        @. Y = x + y\n        Z[i] = atanh(cor(x, Y))\n    end\n    r0 = 1/√2\n    z0 = atanh(r0)\n    histogram(Z; norm=true, alpha=0.3, bin=200)\n    plot!(Normal(z0, 1/√(n - 3)))\n    plot!(fit_mle(Normal, Z))\nend\n\n# %%\nsimplot(Normal(), 2^6)\n\n# %%\nsimplot(Uniform(), 2^6)\n\n# %%\nsimplot(Exponential(), 2^6)\n\n# %%\nsimplot(MixtureModel([Normal(), Normal(10, 1)], [0.95, 0.05]), 2^4)\n\n# %%\nsimplot(MixtureModel([Normal(), Normal(10, 1)], [0.95, 0.05]), 2^6)\n\n# %%\n", "meta": {"hexsha": "940ebaf1b2ac63f242d1f4cf877027a019a214af", "size": 2705, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0023/Fisher's Z transform.jl", "max_stars_repo_name": "genkuroki/public", "max_stars_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-06-06T00:33:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T06:56:08.000Z", "max_issues_repo_path": "0023/Fisher's Z transform.jl", "max_issues_repo_name": "genkuroki/public", "max_issues_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0023/Fisher's Z transform.jl", "max_forks_repo_name": "genkuroki/public", "max_forks_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-02T11:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T11:46:05.000Z", "avg_line_length": 16.2951807229, "max_line_length": 67, "alphanum_fraction": 0.5012939002, "num_tokens": 1125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.8688267796346599, "lm_q1q2_score": 0.7680770048843402}}
{"text": "# Some **really cool** maths:\n#\n# $$ \\exp(i\\pi) + 1 \\quad = \\quad 0 $$\n#\n# We can show this with some code:\n\nx = exp(im*π) + 1\n\n# that looks close to zero but\n\nx ≈ 0\n\n# however\n\nabs(x) < eps()\n\n# #### Conclusion\n#\n# The equation is proven thanks to our very rigorous proof.\n", "meta": {"hexsha": "9ee18b571d5ad936547fd39ccc34709d04ce198d", "size": 274, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "_literate/script_ee.jl", "max_stars_repo_name": "mcognetta/franklindocs", "max_stars_repo_head_hexsha": "99f8b177739da2544a4c8ccd8414d1b417e66a0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 657, "max_stars_repo_stars_event_min_datetime": "2020-01-18T00:24:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:14:58.000Z", "max_issues_repo_path": "_literate/script_ee.jl", "max_issues_repo_name": "mcognetta/franklindocs", "max_issues_repo_head_hexsha": "99f8b177739da2544a4c8ccd8414d1b417e66a0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 523, "max_issues_repo_issues_event_min_datetime": "2020-01-17T13:02:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:15:51.000Z", "max_forks_repo_path": "_literate/script_ee.jl", "max_forks_repo_name": "mcognetta/franklindocs", "max_forks_repo_head_hexsha": "99f8b177739da2544a4c8ccd8414d1b417e66a0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 120, "max_forks_repo_forks_event_min_datetime": "2020-02-01T10:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:26:07.000Z", "avg_line_length": 13.7, "max_line_length": 59, "alphanum_fraction": 0.598540146, "num_tokens": 90, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9504109756113862, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7679959553817105}}
{"text": "using SpecialFunctions\n\n# from datetime import date\n# User-provided date:\n#\nstosym = \"wmt\"\nexyear = 2019\nexmonth = 5\nexday = 16\nstopr = 92.68\nstrike = 94\ncallBid = 0.97\ncallAsk = 1.01\nrfir = 0.0225\n#\n#  Initialize key variables below\n#  (This is not actually required. This is your Prof's habit).\n#\ndaystd = 1\ncipd = 0.0\nd1 = 0.0\ndurvol = 0.0\ncumd1 = 0.0\ncumd2 = 0.0\nnewcp = 0.0\ntempcp = 0.0\ntimedecay = 0.0\ntdprice = 0.0\ncallpr = 0.0\n#\n# Calculating strike value (PEG), which is somewhere between BB and BA.\n# PEG coefficient is explained in lecture.\npeg_coef = 0.60\nspread = callAsk - callBid\ncallpr = callBid + (peg_coef*spread)\n# Calculating days to expiry:\ntnow = Dates.today()\nexpiry = Dates.Date(exyear, exmonth, exday)\ndays = Int(expiry - tnow)\n#  Our method for calculating the cumulative standard normal distribution:\nfunction csnd(dval)\n\treturn (1.0 + erf(dval/sqrt(2.0)))/2.0\nend\n#\n#  Below we calculate implied daily volatility using a recursive method to\n#  converge to an answer.  First we make an initializing calculation, then\n#  we converge inside the while loop. The convergence method shown is Prof E's\n#  \"Divide and Conquer\", which is relatively efficient, usually using only 8\n#  (+/- 2) steps. The student should recognize that the cumd1 is the delta.\n#  The implied daily volatility that we are seeking is \"cipd\" below.\n#\ntarget = callpr\nprecision = 1e-4\ncount = 0\nlow = 0.0\nhigh = 1.0\ncipd = (high+low)/2\nd1 = log(stopr/strike)+((rfir/365)+(cipd^2)/2)*days\ndurvol = cipd*sqrt(days)\ncumd1 = csnd(d1/durvol)\ncumd2 = csnd((d1/durvol) - durvol)\ndiscount = exp(-rfir*days/365)\ntempcp = (stopr*cumd1)-(strike*discount*cumd2)\nwhile tempcp<=(target-precision) || tempcp>=(target+precision)\n\tif tempcp >= (target+precision)\n\t\thigh = cipd\n\telse\n\t\tlow = cipd\n    end\n\tcipd = (high+low)/2\n\td1 = log(stopr/strike)+((rfir/365)+(cipd^2)/2)*days\n\tdurvol = cipd*sqrt(days)\n\tcumd1 = csnd(d1/durvol)\n\tcumd2 = csnd((d1/durvol) - durvol)\n\tdiscount = exp(-rfir*days/365)\n\ttempcp = (stopr*cumd1)-(strike*discount*cumd2)\n\tcount +=1\nend\n#\tBelow we calculate one day time decay using our new value for volatility\ndays = days - daystd\nd1 = log(stopr/strike)+((rfir/365)+(cipd^2)/2)*days\ndurvol = cipd*sqrt(days)\ncumd1 = csnd(d1/durvol)\ncumd2 = csnd((d1/durvol) - durvol)\ndiscount = exp(-rfir*days/365)\nnewcp = (stopr*cumd1)-(strike*discount*cumd2)\ntimedecay = callpr - newcp\n\nprintln( \"\")\nprintln( \"Days to expiry: \", days)\nprintln( \"Stock price: \", stopr)\nprintln( \"Strike price: \", strike)\nprintln( \"Call ASK: \", callAsk)\nprintln( \"Call BID: \", callBid)\nprintln( \"Call price (PEG): \", callpr)\nprintln( \"The Delta:\", cumd1)\nprintln( \"One day time decay:\", timedecay)\nprintln( \"The call's implied volatility: \", cipd)\n", "meta": {"hexsha": "6fc5bbdf814bc7e4ab8af78b8bc6aa1ea49772ec", "size": 2717, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "callBSM.jl", "max_stars_repo_name": "JNetForce/ECON136", "max_stars_repo_head_hexsha": "fd8ca7e85f2f9e94b8b76586c7d9e40526dd30d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "callBSM.jl", "max_issues_repo_name": "JNetForce/ECON136", "max_issues_repo_head_hexsha": "fd8ca7e85f2f9e94b8b76586c7d9e40526dd30d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "callBSM.jl", "max_forks_repo_name": "JNetForce/ECON136", "max_forks_repo_head_hexsha": "fd8ca7e85f2f9e94b8b76586c7d9e40526dd30d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4444444444, "max_line_length": 78, "alphanum_fraction": 0.7022451233, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464604, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7679890549894923}}
{"text": "#=\nIn England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation:\n\n1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).\nIt is possible to make £2 in the following way:\n\n1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p\nHow many different ways can £2 be made using any number of coins?\n=#\ncoins = [1,2,5,10,20,50,100,200]\n# Number of ways of making change for n cents\n# using only the first k types of coins\nfunction coin(n,k)\n  if k < 1 || n < 0\n    return 0\n  elseif n == 0\n    return 1\n  end\n  coin(n, k-1)+coin(n-coins[k], k)\nend\n@time println(coin(200,8))\n", "meta": {"hexsha": "86d2e4bd5b651eb5ea05b78a8ccbdd4b4f930fcf", "size": 600, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p31.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p31.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p31.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 27.2727272727, "max_line_length": 111, "alphanum_fraction": 0.65, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7679890539200581}}
{"text": "using OrdinaryDiffEq, Plots\ngr()\n\n#Half-life of Carbon-14 is 5,730 years.\nC₁ = 5.730\n\n#Setup\nu₀ = 1.0\ntspan = (0.0, 1.0)\n\n#Define the problem\nradioactivedecay(u,p,t) = -C₁*u\n\n#Pass to solver\nprob = ODEProblem(radioactivedecay,u₀,tspan)\nsol = solve(prob,Tsit5())\n\n#Plot\nplot(sol,linewidth=2,title =\"Carbon-14 half-life\", xaxis = \"Time in thousands of years\", yaxis = \"Percentage left\", label = \"Numerical Solution\")\nplot!(sol.t, t->exp(-C₁*t),lw=3,ls=:dash,label=\"Analytical Solution\")\n", "meta": {"hexsha": "8f83dabae48e324c19ed5a09ef928fb07fe05734", "size": 485, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "languages/julia/carbon.jl", "max_stars_repo_name": "sergev/vak-opensource", "max_stars_repo_head_hexsha": "e1912b83dabdbfab2baee5e7a9a40c3077349381", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2016-10-29T19:50:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T21:27:43.000Z", "max_issues_repo_path": "languages/julia/carbon.jl", "max_issues_repo_name": "sergev/vak-opensource", "max_issues_repo_head_hexsha": "e1912b83dabdbfab2baee5e7a9a40c3077349381", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "languages/julia/carbon.jl", "max_forks_repo_name": "sergev/vak-opensource", "max_forks_repo_head_hexsha": "e1912b83dabdbfab2baee5e7a9a40c3077349381", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2017-06-19T23:04:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-13T15:00:41.000Z", "avg_line_length": 23.0952380952, "max_line_length": 145, "alphanum_fraction": 0.7010309278, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7679890516957267}}
{"text": "#Create Initially traveling gaussian\nfunction get_gaussian(p::Param , Opp::Opps)\n\n    #Get Variables\n    Nx  = p.xnodes\n    Ny  = p.ynodes\n\n    A0  = p.A0 \n    σ   = p.σ\n    r0  = p.r0\n    ω   = p.ω\n    m   = p.m\n\n    #Get operators\n    x   = Opp.xcoord\n    y   = Opp.ycoord\n\n    Dx  = Opp.Dx\n\n    #Create initial state\n    ψ_matrix = zeros( Nx , Ny )\n    dψ_matrix = zeros( Nx , Ny )\n\n    for i in 1:Nx , j in 1:Ny\n\n        #Radial and angular coordinates\n        r  = sqrt(x[i]^2 + y[j]^2)\n        θ   = atan(y[j] , x[i])\n    \n        ψ_matrix[i,j] = A0*cos( m*θ ) * sin( ω*r ) * exp( - 0.5* ( (r-r0)/ σ)^2 )\n        dψ_matrix[i,j] = A0*cos( m*θ ) * exp( - 0.5* ( (r-r0)/ σ)^2 ) * ( ω*cos(ω*r) - (r-r0)*sin(ω*r)/σ^2  )\n\n    end\n    \n    ψ  = reshape(ψ_matrix , Nx*Ny)\n    dψ = reshape(dψ_matrix , Nx*Ny)\n\n    #Return initial state\n    return ψ , dψ\n\nend", "meta": {"hexsha": "1c780b0028178e6c8932006a7e199b20b69cc124", "size": 855, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sim_utils/initial_conditions.jl", "max_stars_repo_name": "diogoribeiro98/BhAbs-Solver", "max_stars_repo_head_hexsha": "c014326aef6cf25f0a2fb61125cc84cd3955a16e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sim_utils/initial_conditions.jl", "max_issues_repo_name": "diogoribeiro98/BhAbs-Solver", "max_issues_repo_head_hexsha": "c014326aef6cf25f0a2fb61125cc84cd3955a16e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sim_utils/initial_conditions.jl", "max_forks_repo_name": "diogoribeiro98/BhAbs-Solver", "max_forks_repo_head_hexsha": "c014326aef6cf25f0a2fb61125cc84cd3955a16e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8536585366, "max_line_length": 109, "alphanum_fraction": 0.4900584795, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542829224748, "lm_q2_score": 0.8006920068519378, "lm_q1q2_score": 0.7679871676738277}}
{"text": "\"\"\"\n    cartesian_to_lat_lon(x, y, z)\n\nConvert 3D coordinates (x, y, z) from the unit sphere to (lat, lon). Assumes \"lat\" is positive\nwith \"z\", equatorial plane falls at z=0  and \"lon\" is measured anti-clockwise (eastward)\nfrom x-axis (y=0) about z-axis.\n\nThis is a Julia translation of MATLAB code from MITgcm [1].\n\n[1]: http://wwwcvs.mitgcm.org/viewvc/MITgcm/MITgcm_contrib/high_res_cube/matlab-grid-generator/map_xyz2lonlat.m?view=markup\n\"\"\"\ncartesian_to_lat_lon(x, y, z) = cartesian_to_latitude(x, y, z), cartesian_to_longitude(x, y, z)\n\ncartesian_to_latitude(x, y, z) = atand(z, hypot(x, y))\n\ncartesian_to_longitude(x, y, z) = atand(y, x)\n", "meta": {"hexsha": "eb4c22d5bf9739fbfaeb45fab93b69418ad9fd06", "size": 644, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cartesian_to_lat_lon.jl", "max_stars_repo_name": "CliMA/CubedSphere.jl", "max_stars_repo_head_hexsha": "57d0a9bda06173e9c28fd7820daaab4a2367e208", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-02-11T19:50:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-15T03:24:12.000Z", "max_issues_repo_path": "src/cartesian_to_lat_lon.jl", "max_issues_repo_name": "CliMA/CubedSphere.jl", "max_issues_repo_head_hexsha": "57d0a9bda06173e9c28fd7820daaab4a2367e208", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-02-27T01:28:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-11T05:04:32.000Z", "max_forks_repo_path": "src/cartesian_to_lat_lon.jl", "max_forks_repo_name": "CliMA/CubedSphere.jl", "max_forks_repo_head_hexsha": "57d0a9bda06173e9c28fd7820daaab4a2367e208", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8823529412, "max_line_length": 123, "alphanum_fraction": 0.7267080745, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900507, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7679871663278354}}
{"text": "#=\nThe sum of the squares of the first ten natural numbers is,\n\n12 + 22 + ... + 102 = 385\nThe square of the sum of the first ten natural numbers is,\n\n(1 + 2 + ... + 10)2 = 552 = 3025\nHence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.\n\nFind the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.\n=#\n\nfunction sumsquaredifferences()\n  collection = 1:100\n  x = sum(map((x)->x^2, collection))\n  y = sum(collection)^2\n  y - x\nend\n@time println(sumsquaredifferences())\n", "meta": {"hexsha": "16e136616381ee4ad5c01c95efe250b5cfe73b07", "size": 604, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p6.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p6.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p6.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 30.2, "max_line_length": 132, "alphanum_fraction": 0.7069536424, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542794197472, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7679871580266389}}
{"text": "using EconPDEs, Distributions\n\n# Arbitrage With Holding Costs: A Utility-Based Approach (Bruce Tuckman and Jean-Luc Vila)\nBase.@kwdef struct ArbitrageHoldingCosts\n    c::Float64 = 0.06\n    r::Float64 = 0.09\n    ρ::Float64 = 5.42\n    σ::Float64 = 26.72\n    a::Float64 = 26.72\n    T::Float64 = 100\nend\n\nfunction (m::ArbitrageHoldingCosts)(state::NamedTuple, y::NamedTuple, τ::Number)\n    (; c, r, ρ, σ, a, T) = m\n    (; z) = state\n    (; F, Fz_up, Fz_down, Fzz) = y\n    Fz = (z >= 0) ? Fz_up : Fz_down\n    ϕ = z * (1 + z^2)^(-1/2)\n    ϕz = (1 + z^2)^(-3/2)\n    ϕzz = - 3 * z * (1 + z^2)^(-5/2)\n    sτ = c / r * (1 - exp(- r * (T - τ)))\n    μL = ρ * z - 0.5 * σ^2 * ϕzz / ϕz + c / sτ * (ϕ - 1) / ϕz\n    iL = 1 / a * (μL / σ^2 + Fz)\n    μS = ρ * z - 0.5 * σ^2 * ϕzz / ϕz + c / sτ * (ϕ + 1) / ϕz\n    iS = 1 / a * (μS / σ^2 + Fz)\n    μ, i  = 0.0, 0.0\n    if iL > 0\n        i = iL\n        μ = μL\n    elseif iS < 0\n        i = iS\n        μ = μS\n    end\n    Ft = - ((μ + σ^2 * Fz) * a * i - 0.5 * σ^2 * (a * i)^2 - ρ * z * Fz + 0.5 * σ^2 * (Fzz - Fz^2))\n    return (; Ft)\nend\n\nm = ArbitrageHoldingCosts()\nzn = 200\nd = Normal(0, sqrt(m.σ^2 / (2 * m.ρ)))\nstategrid = OrderedDict(:z => range(quantile(d, 0.00001), quantile(d, 0.99999), length = zn))\nyend = OrderedDict(:F => zeros(zn))\nτs = range(0, m.T, length = 100)\nresult = pdesolve(m, stategrid, yend, τs)\nresidual_norm = maximum(result.residual_norm)\n\n### reproduce Fig 2\n#d = Normal(0, sqrt(m.σ^2 / (2 * m.ρ)))\n#zmin = quantile(d, 0.025)\n#zmax = quantile(d, 0.975)\n#idx = (state[:z] .>= zmin) .& (state[:z] .<= zmax)\n#\n#using Plots\n#plot(result[:x][idx, 20], [result[:I_myopic][idx, 2] result[:I][idx, 2]], label = [\"myopic\" \"all\"])\n#plot(result[:x][idx, 20], result[:I][idx, 2])\n#plot!(result[:x][idx, 60], result[:I][idx, 60])\n#plot!(result[:x][idx, 100], result[:I][idx, 100])\n#\n\n", "meta": {"hexsha": "32b6bd6e22354190301a12325b33bf827cffa7e9", "size": 1828, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/AssetPricing/ArbitrageHoldingCosts.jl", "max_stars_repo_name": "matthieugomez/PDEModels.jl", "max_stars_repo_head_hexsha": "ecdefd0b1e52b2ec3bcebb9498d39057c26afd74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2016-10-06T20:37:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T16:25:39.000Z", "max_issues_repo_path": "examples/AssetPricing/ArbitrageHoldingCosts.jl", "max_issues_repo_name": "matthieugomez/PDEModels.jl", "max_issues_repo_head_hexsha": "ecdefd0b1e52b2ec3bcebb9498d39057c26afd74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2018-04-27T17:24:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T01:42:28.000Z", "max_forks_repo_path": "examples/AssetPricing/ArbitrageHoldingCosts.jl", "max_forks_repo_name": "matthieugomez/PDEModels.jl", "max_forks_repo_head_hexsha": "ecdefd0b1e52b2ec3bcebb9498d39057c26afd74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38, "max_forks_repo_forks_event_min_datetime": "2016-11-12T15:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:57:36.000Z", "avg_line_length": 30.4666666667, "max_line_length": 100, "alphanum_fraction": 0.5180525164, "num_tokens": 837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7679553759796103}}
{"text": "# A quadratic segment in 3D space that passes through three points: x⃗₁, x⃗₂, and x⃗₃.\n# The assumed relation of the points may be seen in the diagram below.\n#                 ___x⃗₃___\n#            ____/        \\____\n#        ___/                  \\\n#     __/                       x⃗₂\n#   _/\n#  /\n# x⃗₁\n#\n# NOTE: x⃗₃ is between x⃗₁ and x⃗₂, but not necessarily the midpoint.\n# q(r) = (2r-1)(r-1)x⃗₁ + r(2r-1)x⃗₂ + 4r(1-r)x⃗₃\n# See The Visualization Toolkit: An Object-Oriented Approach to 3D Graphics, 4th Edition\n# Chapter 8, Advanced Data Representation, in the interpolation functions section\nstruct QuadraticSegment_3D{T <: AbstractFloat}\n    points::NTuple{3, Point_3D{T}}\nend\n\n# Constructors\n# -------------------------------------------------------------------------------------------------\nQuadraticSegment_3D(p₁::Point_3D{T},\n                    p₂::Point_3D{T},\n                    p₃::Point_3D{T}) where {T <: AbstractFloat} = QuadraticSegment_3D((p₁, p₂, p₃))\n\n# Methods\n# -------------------------------------------------------------------------------------------------\nfunction (q::QuadraticSegment_3D{T})(r::R) where {T <: AbstractFloat, R <: Real}\n    # See The Visualization Toolkit: An Object-Oriented Approach to 3D Graphics, 4th Edition\n    # Chapter 8, Advanced Data Representation, in the interpolation functions section\n    rₜ = T(r)\n    return (2rₜ-1)*(rₜ-1)*q.points[1] + rₜ*(2rₜ-1)*q.points[2] + 4rₜ*(1-rₜ)*q.points[3]\nend\n\n#function derivative(q::QuadraticSegment_3D{T}, r::R) where {T <: AbstractFloat, R <: Real}\n#    # dq⃗/dr\n#    rₜ = T(r)\n#    return (4rₜ - 3)*q.points[1] + (4rₜ - 1)*q.points[2] + (4 - 8rₜ)*q.points[3]\n#end\n#\n#function arc_length(q::QuadraticSegment_3D{T}; N::Int64=20) where {T <: AbstractFloat}\n#    # Mathematica solution is pages long and can produce NaN results when the segment is\n#    # straight, so numerical integration is used. (Gauss-Legengre quadrature)\n#    #     1                  N\n#    # L = ∫ ||q⃗'(r)||dr  ≈   ∑ wᵢ||q⃗'(rᵢ)||\n#    #     0                 i=1\n#    # The default number of points is N = 20, since the timing difference is very small for\n#    # additional accuracy when compared with N = 15, and small N give poor accuracy.\n#    w, r = gauss_legendre_quadrature(T, N)\n#    return sum(norm.(w .* derivative.(q, r)))\n#end\n#\n#function intersect(l::LineSegment_3D{T}, q::QuadraticSegment_3D{T}) where {T <: AbstractFloat}\n#    # q(r) = (2r-1)(r-1)x⃗₁ + r(2r-1)x⃗₂ + 4r(1-r)x⃗₃\n#    # q(r) = 2r²(x⃗₁ + x⃗₂ - 2x⃗₃) + r(-3x⃗₁ - x⃗₂ + 4x⃗₃) + x⃗₁\n#    # Let D⃗ = 2(x⃗₁ + x⃗₂ - 2x⃗₃), E⃗ = (-3x⃗₁ - x⃗₂ + 4x⃗₃), F⃗ = x₁\n#    # q(r) = r²D⃗ + rE⃗ + F⃗\n#    # l(s) = x⃗₄ + sw⃗\n#    # If D⃗ × w⃗ ≠ 0⃗\n#    #   x⃗₄ + sw⃗ = r²D⃗ + rE⃗ + F⃗\n#    #   sw⃗ = r²D⃗ + rE⃗ + (F⃗ - x⃗₄)\n#    #   0⃗ = r²(D⃗ × w⃗) + r(E⃗ × w⃗) + (F⃗ - x⃗₄) × w⃗\n#    #   Let A⃗ = (D⃗ × w⃗), B⃗ = (E⃗ × w⃗), C⃗ = (F⃗ - x⃗₄) × w⃗\n#    #   0⃗ = r²A⃗ + rB⃗ + C⃗\n#    #   0 = (A⃗ ⋅ A⃗)r² + (B⃗ ⋅ A⃗)r + (C⃗ ⋅ A⃗)\n#    #   A = (A⃗ ⋅ A⃗), B = (B⃗ ⋅ A⃗), C = (C⃗ ⋅ A⃗)\n#    #   0 = Ar² + Br + C\n#    #   r = (-B - √(B²-4AC))/2A, -B + √(B²-4AC))/2A)\n#    #   s = ((q(r) - p₄)⋅w⃗/(w⃗ ⋅ w⃗)\n#    #   r is invalid if:\n#    #     1) A = 0\n#    #     2) B² < 4AC\n#    #     3) r < 0 or 1 < r   (Curve intersects, segment doesn't)\n#    #   s is invalid if:\n#    #     1) s < 0 or 1 < s   (Line intersects, segment doesn't)\n#    # If D⃗ × w⃗ = 0, we need to use line intersection instead.\n#    bool = false\n#    npoints = 0\n#    points = [Point_3D(T, 0), Point_3D(T, 0)]\n#    D⃗ = 2*(q.points[1] + q.points[2] - 2*q.points[3])\n#    E⃗ = 4*q.points[3] - 3*q.points[1] - q.points[2]\n#    w⃗ = l.points[2] - l.points[1]\n#    A⃗ = D⃗ × w⃗\n#    B⃗ = E⃗ × w⃗\n#    C⃗ = (q.points[1] - l.points[1]) × w⃗\n#    A = A⃗ ⋅ A⃗\n#    B = B⃗ ⋅ A⃗\n#    C = C⃗ ⋅ A⃗\n#    if abs(A) < 1.0e-6\n#        # Line intersection\n#        r = (-C⃗ ⋅ B⃗)/(B⃗ ⋅ B⃗)\n#        s = (q(r)- l.points[1]) ⋅ w⃗/(w⃗ ⋅ w⃗)\n#        points[1] = q(r)\n#        if (0 ≤ s ≤ 1) && (0 ≤ r ≤ 1)\n#            bool = true\n#            npoints = 1\n#        end\n#    elseif B^2 ≥ 4A*C\n#        # Quadratic intersection\n#        r₁ = (-B - √(B^2-4A*C))/2A\n#        r₂ = (-B + √(B^2-4A*C))/2A\n#        points[1] = q(r₁)\n#        points[2] = q(r₂)\n#        s₁ = (points[1] - l.points[1]) ⋅ w⃗/(w⃗ ⋅ w⃗)\n#        s₂ = (points[2] - l.points[1]) ⋅ w⃗/(w⃗ ⋅ w⃗)\n#\n#        # Check points to see if they are valid intersections.\n#        # First r,s valid?\n#        if (0 ≤ r₁ ≤ 1) && (0 ≤ s₁ ≤ 1) && (points[1] ≈ l(s₁))\n#            npoints += 1\n#        end\n#        # Second r,s valid?\n#        if (0 ≤ r₂ ≤ 1) && (0 ≤ s₂ ≤ 1) && (points[2] ≈ l(s₂))\n#            npoints += 1\n#            # If only point 2 is valid, return it in index 1 of points\n#            if npoints === 1\n#                points[1] = points[2]\n#            end\n#        end\n#        bool = npoints > 0\n#    end\n#    return bool, npoints, points\n#end\n#intersect(q::QuadraticSegment_3D, l::LineSegment_3D) = intersect(l, q)\n", "meta": {"hexsha": "48c52cbfb072bb81cc9e49fa844cc18b221dcf94", "size": 4967, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unused/QuadraticSegment_3D.jl", "max_stars_repo_name": "KyleVaughn/MOCNeutronTransport", "max_stars_repo_head_hexsha": "6de0f5987c2b37c3c3039d073b63c223ff6cd5f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-11-10T19:36:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T15:34:40.000Z", "max_issues_repo_path": "src/unused/QuadraticSegment_3D.jl", "max_issues_repo_name": "KyleVaughn/MOCNeutronTransport", "max_issues_repo_head_hexsha": "6de0f5987c2b37c3c3039d073b63c223ff6cd5f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2022-01-20T03:03:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T18:29:33.000Z", "max_forks_repo_path": "src/unused/QuadraticSegment_3D.jl", "max_forks_repo_name": "KyleVaughn/MOCNeutronTransport", "max_forks_repo_head_hexsha": "6de0f5987c2b37c3c3039d073b63c223ff6cd5f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0564516129, "max_line_length": 99, "alphanum_fraction": 0.4711093215, "num_tokens": 2260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757596, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7679553755394606}}
{"text": "function combined(op, kernel_function)\n    function combined_kernel_function(u, v, k=nothing)\n        ker = kernel_function(u, v)\n        isnothing(k) ? ker : op.(k, ker)\n    end\nend\n\n# Kernel functions\n\n\"\"\"\n    gaussiankernel(u, v)\n\nCompute the Gaussian kernel, given by the formula\n```\n    κ(x,y) = exp(-‖x-y‖²/2).\n```\n`u` and `v` are matrices, where each column is a datapoint.\n\"\"\"\nfunction gaussiankernel(u, v)\n    uu = sum(abs2, u, dims=1)\n    vv = sum(abs2, v, dims=1)\n    acc = u' * v\n    @. acc = exp(acc - uu' / 2 - vv / 2)\n    return acc\nend\n\nfunction rrule(::typeof(gaussiankernel), u, v)\n    r = gaussiankernel(u, v)\n    # r̄ is short for ∂l / ∂r\n    function gaussiankernel_pullback(r̄)\n        m = r .* r̄ # pullback the exponential\n        ū = v * m'\n        ū .-= sum(m', dims=1) .* u\n        v̄ = u * m\n        v̄ .-= sum(m, dims=1) .* v\n        return NO_FIELDS, ū, v̄\n    end\n    return r, gaussiankernel_pullback\nend\n\n\"\"\"\n    additivegaussiankernel(u, v, k=nothing)\n\nCompute the radial basis function kernel (see [`gaussiankernel`](@ref)) on `u`, `v`.\nIf `k` is not `nothing`, add it to the result.\n\"\"\"\nconst additivegaussiankernel = combined(+, gaussiankernel)\n\n\"\"\"\n    additivegaussiankernel(u, v, k=nothing)\n\nCompute the radial basis function kernel (see [`gaussiankernel`](@ref)) on `u`, `v`.\nIf `k` is not `nothing`, multiply the result by it.\n\"\"\"\nconst multiplicativegaussiankernel = combined(*, gaussiankernel)\n", "meta": {"hexsha": "f7fcf754b2ddfbc0538d8c6706d500152a566828", "size": 1441, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels.jl", "max_stars_repo_name": "Veos-Digital/KernelMachines.jl", "max_stars_repo_head_hexsha": "fcd74ecd11e585adf168d78c62a99e75f9f0dec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels.jl", "max_issues_repo_name": "Veos-Digital/KernelMachines.jl", "max_issues_repo_head_hexsha": "fcd74ecd11e585adf168d78c62a99e75f9f0dec1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels.jl", "max_forks_repo_name": "Veos-Digital/KernelMachines.jl", "max_forks_repo_head_hexsha": "fcd74ecd11e585adf168d78c62a99e75f9f0dec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7321428571, "max_line_length": 84, "alphanum_fraction": 0.6155447606, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.767955371962096}}
{"text": "# See https://en.wikipedia.org/wiki/Fibonacci\n\nfibonacci(n) = ([1 1 ; 1 0] ^ n)[1, 2]\n\nexpressions = [\n    :(fibonacci(0))\n    :(fibonacci(1))\n    :(fibonacci(6))\n    :(fibonacci(91))\n    :(fibonacci(big(283)))\n    :(fibonacci(big(3674)))\n]\n\nfor expr in expressions\n    println(\"[] :julia-answer \\\"\\\"\\\"\", escape_string(string(expr)), \" = \", eval(expr), \"\\\"\\\"\\\".\")\nend\n", "meta": {"hexsha": "011e87fc56442f7ed5c529bc29bfda9a5d0d81df", "size": 368, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "reasoning/julia/fibonacci.jl", "max_stars_repo_name": "pmoura/eye", "max_stars_repo_head_hexsha": "03a4be110f5e9f8f21a6b1ac2756d79cc6518386", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reasoning/julia/fibonacci.jl", "max_issues_repo_name": "pmoura/eye", "max_issues_repo_head_hexsha": "03a4be110f5e9f8f21a6b1ac2756d79cc6518386", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reasoning/julia/fibonacci.jl", "max_forks_repo_name": "pmoura/eye", "max_forks_repo_head_hexsha": "03a4be110f5e9f8f21a6b1ac2756d79cc6518386", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6470588235, "max_line_length": 97, "alphanum_fraction": 0.5625, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7679553708336381}}
{"text": "export lambertW\n\n#\n# The Lambert W function (See reference [4])\n# The following algorithm computes the Lambert-W function to machine accuracy using Halley's method for any x\n# in the domain I=( -1/exp(1), ∞ ). This function can also compute the lambert-W function component-wise for\n# vectors or matrices. The Lambert-W function is used in the module DESincEig to compute the mesh size h.\n# Input: x:: Number, Vector or Matrix\n# Output: lambertW(x)\n#\nfunction lambertW(x::Real)\n    if x < -exp(-one(x))\n        return throw(DomainError())\n    elseif x == -exp(-one(x))\n        return -one(x)    \n    elseif x < 0\n        w0 = e*x/(1+inv(inv(sqrt(2*e*x+2))+inv(e-1)-inv(sqrt(2))))\n    else\n        logx = log(1+x)\n        w0 = logx*(1-log(1+logx)/(2+logx))\n    end\n    expw0 = exp(w0)\n    w1 = w0 - (w0*expw0 - x)/((w0 + 1)*expw0 -\n        (w0 + 2) * (w0*expw0 - x)/(2w0 + 2))\n    while abs(w1/w0 - 1) > 2eps(typeof(x))\n        w0 = w1\n        expw0 = exp(w0)\n        w1 = w0 - (w0*expw0 - x)/((w0 + 1)*expw0 -\n            (w0 + 2) * (w0*expw0 - x)/(2w0 + 2))\n    end\n    return w1\nend\nlambertW(x::Integer) = lambertW(float(x))\n@vectorize_1arg Real lambertW\n", "meta": {"hexsha": "1dd5cf38158a6a36fa7d28e8b45e68e56933ba01", "size": 1157, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lambertW.jl", "max_stars_repo_name": "pjgaudre/DESincEig.jl", "max_stars_repo_head_hexsha": "d6d208514b19d2db2f538df922a048fccec68997", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-11-15T20:20:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-24T21:24:03.000Z", "max_issues_repo_path": "src/lambertW.jl", "max_issues_repo_name": "pjgaudre/DESincEig.jl", "max_issues_repo_head_hexsha": "d6d208514b19d2db2f538df922a048fccec68997", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2015-08-31T21:18:56.000Z", "max_issues_repo_issues_event_max_datetime": "2015-11-15T14:26:37.000Z", "max_forks_repo_path": "src/lambertW.jl", "max_forks_repo_name": "pjgaudre/DESincEig.jl", "max_forks_repo_head_hexsha": "d6d208514b19d2db2f538df922a048fccec68997", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-01-18T21:03:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-24T21:24:13.000Z", "avg_line_length": 33.0571428571, "max_line_length": 109, "alphanum_fraction": 0.5868625756, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7679553697051801}}
{"text": "#\n# this file shows an example of pseudo-spectral discretization for PHS systems for wave equation\n#  three cases are presented. It should be used for verifying the discretization, eigenvalues,\n#  and constraint elimination methods. Three cases are tested:\n#         1) PHS with u = 0 (Neumann-Dirichlet B.C)\n#         2) PHS with y = 0 (Neumann-Dirichlet B.C, but with a constraint)\n#         3) PHS with y = 0 after removing the constraints.\n#\n\n# auxiliary function: used for printing results\n\nfunction print_table(table)\n\tnum_y = size(table,1)\n\tnum_x = size(table,2)\n\tfor i = 1:num_y\n\t\tfor j = 1:num_x\n\t\t\tif j < 3\n\t\t\t\t@printf(\"%.2f\\t\", table[i,j])\n\t\t\telse\n\t\t\t\t@printf(\"%.2e\", table[i,j])\n\t\t\tend\n\t\tend\n\t\t@printf(\"\\n\")\n\tend\nend\n\n# modules:\nusing PortHamiltonian\n#using PyPlot\n\n\nN = 10;\na = 0.;\nb = 1.;\n\n# load the phs discretization structure \n## the Hamiltonian is considered linear with Q = I\nph = discrete_phs(N, a, b); \n\neigval, eigvec = eig(ph);\nnum_freq = frequencies(eigval)\n\nexact_freq = pi/2*collect(1:2:2*N);\nerr = exact_freq - num_freq;\n\n# comparison between numerical and exact results:\ncomp_table = [num_freq exact_freq err./exact_freq];\ncomp_table = comp_table[1:10,:]\n@printf(\"\\nNatural frequencies of the Dirichlet-Neumann B.C. wave equation (with u = 0)\\n\")\n@printf(\"exact\\tnumeric\\terror \\n\")\nprint_table(comp_table)\n@printf(\"\\t From a total %d frequencies, %d are represented with error less than 0.01\\n\", length(err), sum(abs(err) .< 0.01)) \n@printf(\"\\n\\t %d are smaller than %.1e\\n\",sum(abs(err) .< eps()*1e6),eps()*1e6) \n#plot the first five modes\n#plot(ph.disc_data.flow.xi, real(eigvec[1:N,N+2]))\n\n# constrained version\nph_constrained = deepcopy(ph);\nset_constraint!(ph_constrained, ph_constrained.B[:,1], ph_constrained.D[1:1,1:1]);\n\n## eigenvalues of the constrained\neigval, eigvec = eig(ph_constrained)\nnum_freq = frequencies(eigval)\nexact_freq = pi*collect(-0:1:N-1);\nerr = exact_freq - num_freq;\n\n# comparison between numerical and exact results:\ncomp_table = [num_freq exact_freq err./exact_freq]\ncomp_table = comp_table[1:10,:]\n@printf(\"\\nNatural frequencies of the Neumann-Dirichlet B.C. wave equation (with y = 0)\\n\")\n@printf(\"exact\\tnumeric\\terror \\n\")\nprint_table(comp_table)\n@printf(\"\\t\\t From a total %d frequencies, %d are represented with error less than 0.01\\n\", length(err), sum(abs(err) .< 0.01)) \n@printf(\"\\n\\t %d are smaller than %.1e\\n\",sum(abs(err) .< eps()*1e6),eps()*1e6) \n## find an explicit equivalent system\nph_c_elim = constraint_elimination(ph_constrained)\neigval, eigvec = eig(ph_c_elim);\nnum_freq = frequencies(eigval)\n\nexact_freq = pi*collect(0:1:N-1);\nerr = exact_freq - num_freq;\n# comparison between numerical and exact results:\ncomp_table = [num_freq exact_freq err./exact_freq]\ncomp_table = comp_table[1:10,:]\n@printf(\"\\nNatural frequencies of the Neumann-Dirichlet B.C. wave equation (with y=0 after constraint elimination)\\n\")\n@printf(\"exact\\tnumeric\\terror \\n\")\nprint_table(comp_table)\n@printf(\"\\t\\t From a total %d frequencies, %d are represented with error less than 0.01\", length(err), sum(abs(err) .< 0.01)) \n@printf(\"\\n\\t %d are smaller than %.1e\\n\",sum(abs(err) .< eps()*1e6),eps()*1e6) \n", "meta": {"hexsha": "7b70e056956c460b842472fd32c6186b7a383723", "size": 3159, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/wave_equation.jl", "max_stars_repo_name": "flavioluiz/phjulia", "max_stars_repo_head_hexsha": "aee3162f0bec3aed0bed0f6ae4138a7e6a5b5797", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-28T19:34:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-28T19:34:40.000Z", "max_issues_repo_path": "examples/wave_equation.jl", "max_issues_repo_name": "flavioluiz/phjulia", "max_issues_repo_head_hexsha": "aee3162f0bec3aed0bed0f6ae4138a7e6a5b5797", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-10-31T14:12:22.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-31T14:12:22.000Z", "max_forks_repo_path": "examples/wave_equation.jl", "max_forks_repo_name": "flavioluiz/phjulia", "max_forks_repo_head_hexsha": "aee3162f0bec3aed0bed0f6ae4138a7e6a5b5797", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-01T17:15:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:15:30.000Z", "avg_line_length": 35.1, "max_line_length": 128, "alphanum_fraction": 0.7106679329, "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8670357546485407, "lm_q1q2_score": 0.7678741532424515}}
{"text": "\"\"\"\n    InterpolationLineSearch{C, T}\n\n`InterpolationLineSearch` uses quadratic and cubic interpolations to compute the step length\nsatisfying the Armijo sufficient decrease condition.\n\n# Fields\n- `c::C`: the constant for the Armijo condition in the open interval (0, 1)\n- `ϵ::T`: the minimum step length decrease from the initial step length\n\"\"\"\nstruct InterpolationLineSearch{C, T}\n    c::C\n    ϵ::T\n\n    function InterpolationLineSearch(c, ϵ)\n        0 < c < 1 || error(\"`c` must be in the open interval (0, 1)\")\n        return new{typeof(c), typeof(ϵ)}(c, ϵ)\n    end\nend\n\n\"\"\"\n    InterpolationLineSearch(; kwargs...)\n\nInitiate `InterpolationLineSearch`.\n\n# Keywords\n- `c=1e-4`: the constant for the Armijo condition in the open interval (0, 1)\n- `ϵ=1e-6`: the minimum step length decrease from the initial step length\n\"\"\"\nInterpolationLineSearch(; c=1e-4, epsilon=1e-6) = InterpolationLineSearch(c, epsilon)\n\nfunction (ils::InterpolationLineSearch)(f, state, p, α₀::T) where {T}\n    x = state.x\n    ϕ₀ = state.f\n    ∇y = state.∇f\n    dϕ₀ = ∇y⋅p\n    αₖ = α₀\n    c = ils.c\n    ϵ = ils.ϵ\n    ϕ(α) = f(x + α * p)\n    ϕαₖ = ϕ(αₖ)\n    αₖ₊₁ = T(-(dϕ₀ * αₖ^2) / (2 * (ϕαₖ - ϕ₀ - dϕ₀ * αₖ)))\n    while f(x + αₖ₊₁*p) > ϕ₀ + c*αₖ₊₁*dϕ₀\n        ϕαₖ₊₁ = ϕ(αₖ₊₁)\n        a, b = [αₖ^2 -αₖ₊₁^2; -αₖ^3 αₖ₊₁^3] * \n            [ϕαₖ₊₁ - ϕ₀ - dϕ₀*αₖ₊₁; ϕαₖ - ϕ₀ - dϕ₀*αₖ] / \n            (αₖ^2*αₖ₊₁^2*(αₖ₊₁-αₖ))\n        αₖ₊₂ = (-b + sqrt(b^2 - 3a*dϕ₀)) / (3a)\n        αₖ₊₂ = max(min(αₖ₊₂, αₖ₊₁ - ϵ), αₖ₊₁/2)\n        αₖ = αₖ₊₁\n        ϕαₖ = ϕαₖ₊₁\n        αₖ₊₁ = T(αₖ₊₂)\n    end\n    return αₖ₊₁\nend", "meta": {"hexsha": "82e3dfbb0cfecb74f75291c4cac0cc794a9f2d9a", "size": 1578, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/multivariate/line_search/algorithms/interpolation.jl", "max_stars_repo_name": "lhnguyen-vn/Optini.jl", "max_stars_repo_head_hexsha": "81e94ff764daa9819edae4b4b8211726a7de0821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-24T21:26:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T21:26:59.000Z", "max_issues_repo_path": "src/multivariate/line_search/algorithms/interpolation.jl", "max_issues_repo_name": "lhnguyen-vn/Optini.jl", "max_issues_repo_head_hexsha": "81e94ff764daa9819edae4b4b8211726a7de0821", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multivariate/line_search/algorithms/interpolation.jl", "max_forks_repo_name": "lhnguyen-vn/Optini.jl", "max_forks_repo_head_hexsha": "81e94ff764daa9819edae4b4b8211726a7de0821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-18T21:08:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T21:08:54.000Z", "avg_line_length": 28.6909090909, "max_line_length": 92, "alphanum_fraction": 0.5811153359, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7678660762085638}}
{"text": "using ReachabilityAnalysis, SparseArrays, Symbolics\n\nconst var = @variables x[1:9] t\n\nfunction platoon_connected(; deterministic_switching::Bool=true,\n                             c1=5.0)  # clock constraints\n    n = 9 + 1\n\n    # x' = Ax + Bu + c\n    A = Matrix{Float64}(undef, n, n)\n    A[1, :] = [0, 1.0, 0, 0, 0, 0, 0, 0, 0, 0]\n    A[2, :] = [0, 0, -1.0, 0, 0, 0, 0, 0, 0, 0]\n    A[3, :] = [1.6050, 4.8680, -3.5754, -0.8198, 0.4270, -0.0450, -0.1942,  0.3626, -0.0946, 0.]\n    A[4, :] = [0, 0, 0, 0, 1.0, 0, 0, 0, 0, 0,]\n    A[5, :] = [0, 0, 1.0, 0, 0, -1.0, 0, 0, 0, 0]\n    A[6, :] = [0.8718, 3.8140, -0.0754,  1.1936, 3.6258, -3.2396, -0.5950,  0.1294, -0.0796, 0.]\n    A[7, :] = [0, 0, 0, 0, 0, 0, 0, 1.0, 0, 0]\n    A[8, :] = [0, 0, 0, 0, 0, 1.0, 0, 0, -1.0, 0]\n    A[9, :] = [0.7132, 3.5730, -0.0964,  0.8472, 3.2568, -0.0876,  1.2726,  3.0720, -3.1356, 0.]\n    A[10, :] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0]; # t' = 1\n\n    if deterministic_switching\n        invariant = HalfSpace(t <= c1, var)\n    else\n        invariant = Universe(n)\n    end\n\n    # acceleration of the lead vehicle + time\n    B = sparse([2], [1], [1.0], n, 1)\n    U = Hyperrectangle(low=[-9.], high=[1.])\n    c = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0]\n    @system(x' = Ax + Bu + c, x ∈ invariant, u ∈ U)\nend\n\nfunction platoon_disconnected(; deterministic_switching::Bool=true,\n                                c2=5.0)  # clock constraints\n    n = 10 # 9 dimensions + time\n\n    # x' = Ax + Bu + c\n    A = Matrix{Float64}(undef, n, n)\n    A[1, :] = [0, 1.0, 0, 0, 0, 0, 0, 0, 0, 0]\n    A[2, :] = [0, 0, -1.0, 0, 0, 0, 0, 0, 0, 0]\n    A[3, :] = [1.6050, 4.8680, -3.5754, 0, 0, 0, 0, 0, 0, 0]\n    A[4, :] = [0, 0, 0, 0, 1.0, 0, 0, 0, 0, 0,]\n    A[5, :] = [0, 0, 1.0, 0, 0, -1.0, 0, 0, 0, 0]\n    A[6, :] = [0, 0, 0,  1.1936, 3.6258, -3.2396, 0, 0, 0, 0.]\n    A[7, :] = [0, 0, 0, 0, 0, 0, 0, 1.0, 0, 0]\n    A[8, :] = [0, 0, 0, 0, 0, 1.0, 0, 0, -1.0, 0]\n    A[9, :] = [0.7132, 3.5730, -0.0964,  0.8472, 3.2568, -0.0876,  1.2726,  3.0720, -3.1356, 0.]\n    A[10, :] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0]; # t' = 1\n\n    if deterministic_switching\n        invariant = HalfSpace(t <= c2, var)\n    else\n        invariant = Universe(n)\n    end\n\n    # acceleration of the lead vehicle + time\n    B = sparse([2], [1], [1.0], n, 1)\n    U = Hyperrectangle(low=[-9.], high=[1.])\n    c = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0]\n    @system(x' = Ax + Bu + c, x ∈ invariant, u ∈ U)\nend\n\nfunction platoon(; deterministic_switching::Bool=true,\n                   c1=5.0,  # clock constraints\n                   c2=5.0,  # clock constraints\n                   tb=10.0,  # lower bound for loss of communication\n                   tc=20.0, tr=20.0) # upper bound for loss of communication (tc) and reset time (tr)\n\n    # three variables for each vehicle, (ei, d(et)/dt, ai) for\n    # (spacing error, relative velocity, speed), and the last dimension is time\n    n = 9 + 1\n\n    # transition graph\n    automaton = LightAutomaton(2)\n    add_transition!(automaton, 1, 2, 1)\n    add_transition!(automaton, 2, 1, 2)\n\n    # modes\n    mode1 = platoon_connected(deterministic_switching=deterministic_switching, c1=c1)\n    mode2 = platoon_disconnected(deterministic_switching=deterministic_switching, c2=c2)\n    modes = [mode1, mode2]\n\n    # common reset\n    reset = Dict(n => 0.)\n\n    # transition l1 -> l2\n    if deterministic_switching\n        guard = Hyperplane(t == c1, var)\n    else\n        guard = HPolyhedron([tb <= t, t <= tc], var)\n    end\n    t1 = ConstrainedResetMap(n, guard, reset)\n\n    # transition l2 -> l1\n    if deterministic_switching\n        guard = Hyperplane(t == c2, var)\n    else\n        guard = HalfSpace(t <= tr, var)\n    end\n    t2 = ConstrainedResetMap(n, guard, reset)\n    resetmaps = [t1, t2]\n\n    H = HybridSystem(automaton, modes, resetmaps, [AutonomousSwitching()])\n\n    # initial condition is at the orgin in mode 1\n    X0 = BallInf(zeros(n), 0.0)\n    initial_condition = [(1, X0)]\n\n    return IVP(H, initial_condition)\nend\n\nfunction dmin_specification(sol, dmin)\n    return (-ρ(sparsevec([1], [-1.0], 10), sol) > -dmin) &&\n           (-ρ(sparsevec([4], [-1.0], 10), sol) > -dmin) &&\n           (-ρ(sparsevec([7], [-1.0], 10), sol) > -dmin)\nend\n\nprob_PLAD01 = platoon();\n\nconst boxdirs = BoxDirections(10)\nconst octdirs = OctDirections(10);\n\nlength(boxdirs)\n\nalg = BOX(δ=0.01)\nsol_PLAD01_BND42 = solve(prob_PLAD01,\n                         alg=alg,\n                         clustering_method=BoxClustering(1),\n                         intersection_method=TemplateHullIntersection(boxdirs),\n                         intersect_source_invariant=false,\n                         tspan = (0.0 .. 20.0));\n\ndmin_specification(sol_PLAD01_BND42, 42)\n\n-ρ(sparsevec([1], [-1.0], 10), sol_PLAD01_BND42)\n\n-ρ(sparsevec([4], [-1.0], 10), sol_PLAD01_BND42)\n\n-ρ(sparsevec([7], [-1.0], 10), sol_PLAD01_BND42)\n\nusing Plots, LaTeXStrings\n\nplot(sol_PLAD01_BND42, vars=(0, 1), xlab=L\"t\", ylab=L\"x_1\", title=\"PLAD01 - BND42\", lw=0.1)\nplot!(x->x, x->-42., 0., 20., linewidth=2, color=\"red\", linestyle=:dash, leg=nothing)\n\nlength(octdirs)\n\n\nalg = LGG09(δ=0.03, template=octdirs, approx_model=Forward(setops=octdirs));\nsol_PLAD01_BND30 = solve(prob_PLAD01,\n                         alg=alg,\n                         clustering_method=LazyClustering(1),\n                         intersection_method=TemplateHullIntersection(octdirs),\n                         intersect_source_invariant=false,\n                         tspan = (0.0 .. 20.0));\n\ndmin_specification(sol_PLAD01_BND30, 30)\n\n-ρ(sparsevec([1], [-1.0], 10), sol_PLAD01_BND30)\n\n-ρ(sparsevec([4], [-1.0], 10), sol_PLAD01_BND30)\n\n-ρ(sparsevec([7], [-1.0], 10), sol_PLAD01_BND30)\n\nplot(sol_PLAD01_BND30, vars=(0, 1), xlab=L\"t\", ylab=L\"x_1\", title=\"PLAD01 - BND30\", lw=0.1)\nplot!(x->x, x->-30., 0., 20., linewidth=2, color=\"red\", linestyle=:dash, leg=nothing)\n\n", "meta": {"hexsha": "bcc645b0e33fb95328641ac23c60811ef72fa0d8", "size": 5839, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/models/Platoon.jl", "max_stars_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_stars_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2020-03-30T16:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:26:48.000Z", "max_issues_repo_path": "test/models/Platoon.jl", "max_issues_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_issues_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 258, "max_issues_repo_issues_event_min_datetime": "2020-03-30T14:13:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T17:07:04.000Z", "max_forks_repo_path": "test/models/Platoon.jl", "max_forks_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_forks_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-04-23T03:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T23:11:32.000Z", "avg_line_length": 34.3470588235, "max_line_length": 101, "alphanum_fraction": 0.5429011817, "num_tokens": 2420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7678660661755754}}
{"text": "using Plots, LaTeXStrings, Statistics\n\nfunction Deposition(;len, tot_time, time_steps, rate)\n    Time = ceil.(Int, exp.(0:(tot_time)/(time_steps):tot_time))\n    surf = [0 for i=1:len]\n    VarList = [0.0 for i=1:time_steps]\n    for n in 1:time_steps\n        randsurf = rand(1:len,(Time[n+1]-Time[n])*rate)\n        for i in randsurf\n            surf[i] += 1\n        end\n        VarList[n] = std(surf)\n    end\n    return VarList\nend\n\nfunction Linear_fit(;len, tot_time, time_steps, rate)\n    A = [hcat(log.(Time)) reshape(ones(time_steps), time_steps, 1)]\n    b = reshape(log.(meanVar), time_steps, 1)\n    line = (A \\ b)\n    x = 0:tot_time\n    y = x .* line[1] .+ line[2]\n    return x, y, line\nend\n\niternum = 1000\nParameters = Dict(\n                :len => 200,\n                :tot_time => 10,\n                :time_steps => 20,\n                :rate => 10)\nallVar = [[0.0 for i in 1:Parameters[:time_steps]] for j = 1:iternum]\nmeanVar = [0.0 for i in 1:Parameters[:time_steps]]\nvars = [0.0 for i in 1:Parameters[:time_steps]]\nfor i in 1:iternum\n    VarList = Deposition(;Parameters...)\n    allVar[i] = VarList\n    meanVar += VarList\n    print(\"\\r$i\")\nend\nmeanVar /= iternum\nfor i in 1:Parameters[:time_steps]\n    vars[i] = std(log.(hcat(allVar...))[i,:])\nend\n\nTime = ceil.(Int, exp.(0:(Parameters[:tot_time])/(Parameters[:time_steps]):Parameters[:tot_time]))[1:end-1]\nX, Y, Line = Linear_fit(;Parameters...)\n\nscatter(log.(Time),log.(meanVar),\n    xlabel= L\"Log\\ Time\",\n    ylabel= L\"Log\\ W_{(t)}\",\n    title= L\"Log-Log\\ Plot\\ of\\ ~W_{(t)}-Time~, Particles \\ number \\approx e^{%$(Parameters[:tot_time])}\",\n    yerror = vars,\n    label = L\"Data\\ point\")\nplot!(X,Y,c= :black,label = L\"y = %$(round(Line[1],digits= 2))x + %$(round(Line[2],digits= 2))\")\nsavefig(\"C:\\\\Users\\\\Yaghoub\\\\Documents\\\\GitHub\\\\ComputationalPhysics-Fall2021\\\\ProblemSet2\\\\Figs\\\\Q2\\\\RBDW(t).png\")\n", "meta": {"hexsha": "1ebc0cf6f143a0904473734c7b2e37aa48a74ea5", "size": 1864, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSet2/Codes/Q2/Q2-W(t).jl", "max_stars_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_stars_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSet2/Codes/Q2/Q2-W(t).jl", "max_issues_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_issues_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSet2/Codes/Q2/Q2-W(t).jl", "max_forks_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_forks_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-21T11:07:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-21T11:07:08.000Z", "avg_line_length": 32.701754386, "max_line_length": 115, "alphanum_fraction": 0.6019313305, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.767866062603241}}
{"text": "### A Pluto.jl notebook ###\n# v0.10.1\n\nusing Markdown\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 4a816b10-c188-11ea-3935-1fc7371387ac\nusing Plots\n\n# ╔═╡ 62a8f092-c198-11ea-2d26-632729a6bd7f\nusing StatsBase\n\n# ╔═╡ 1c0741f0-c17a-11ea-3c6f-31f0c86dd08d\nmd\"\"\"\n# Random Walk Models\n\"\"\"\n\n# ╔═╡ 58e6d60e-c17c-11ea-145e-ffdc97ab1f3f\nmd\"Short function definition (one-liner):\"\n\n# ╔═╡ a93d6520-c17c-11ea-2cc7-5ff51f20df2b\njump() = rand( (-1, +1) )\n\n# ╔═╡ bfa68c10-c17c-11ea-281c-25e48e4ab81d\nmd\"Exactly the same\"\n\n# ╔═╡ ccef6d10-c17c-11ea-13e5-432b940ba726\nfunction jump_()\n\treturn rand( (-1, +1) )\nend\n\n# ╔═╡ fea8c400-c17c-11ea-35fc-e98ef849c316\njump()\n\n# ╔═╡ 9aff5fa0-c185-11ea-145a-c3230681bd4c\nmd\"It is better to use `tuples` in this case instead of `arrays`, tuples are not mutable and with fixed size\"\n\n# ╔═╡ 0762ce10-c17d-11ea-1f2a-172e4ed0500a\nbegin \n\tlocal t = (-1, +1)\n\ttypeof(t)\nend\n\n# ╔═╡ 212df5a0-c186-11ea-0f5c-83f0dd5a1497\nmd\"Side remark: Simple bernoulli function\"\n\n# ╔═╡ 8ce720ae-c185-11ea-380c-2df4848fb56a\nbernoulli(p) = rand() < p\n\n# ╔═╡ f52fc0a0-c185-11ea-2126-b10b11defe13\nbernoulli(0.25)\n\n# ╔═╡ 891b2f20-c186-11ea-024f-372f0eef600c\nmd\"## Random walks\"\n\n# ╔═╡ 15990630-c186-11ea-2059-e1e301040dae\n[jump() for i ∈ 1:10]\n\n# ╔═╡ 62d228a2-c186-11ea-3ced-1db44003e269\nfunction walk(n)\n\tx = 0\n\t\n\tfor i ∈ 1:n\n\t\tx += jump() #x = x + jump()\n\tend\n\t\n\treturn x\nend\n\n# ╔═╡ 0b66e5a2-c187-11ea-36de-279c4d6aa180\nwalk(10)\n\n# ╔═╡ 432008a0-c187-11ea-3606-159ae4ed8460\nfunction trajectory(n)\n\tx = 0\n\t\n\txs = Int64[x] # inititalize with an initial value and the type of the array\n\t\n\tfor i ∈ 1:n\n\t\tx += jump() # x = x + jump()\n\t\t\n\t\tpush!(xs, x)\n\tend\n\t\n\treturn xs\nend\n\n# ╔═╡ 131fcc00-c18a-11ea-09dc-0906c430d399\nmd\"\"\"steps = $(@bind steps html\"<input type='range' min=5 max=100>\" ) \"\"\"\n\n# ╔═╡ 1afa1280-c18c-11ea-1d1b-7f277d76e68c\nmd\"**$(steps)** steps\"\n\n# ╔═╡ 8cfcb9a2-c187-11ea-1129-ff3d55e25de4\ntrajectories = trajectory(steps)\n\n# ╔═╡ 3b677390-c188-11ea-1079-01f262b1d76f\nmd\"## Plotting\"\n\n# ╔═╡ 643c5510-c188-11ea-2d15-fbf4939ae53c\nbegin \n\tplot(trajectories, m=:o, size=(300, 200))\n\thline!([0], ls=:dash)\nend\n\n# ╔═╡ b417eaf0-c18c-11ea-3ae7-19f88eab6b9f\nbegin\n\tlocal num_walkers = 1000\n\tlocal num_steps = 100\n\t\n\tlocal p = plot(size=(500, 400), leg=false)\n\t\n\tfor i ∈ 1:num_walkers\n\t\ttraj = trajectory(num_steps)\n\t\t\n\t\tplot!(traj)\n\tend\n\t\n\tp\nend\n\n# ╔═╡ eb35c2e0-c18d-11ea-3209-bd013b156820\nmd\"## Precompute the data\"\n\n# ╔═╡ 1ec51ce0-c18f-11ea-2166-6923cbcef091\nn = 20\n\n# ╔═╡ 2c106ee0-c18f-11ea-21dc-db7d6706f5cb\ntraj = trajectory(n)\n\n# ╔═╡ 3ee28c60-c18f-11ea-3297-3d26c8d37627\n@bind traj_steps html\"<input type='range' min=1 max=20>\"\n\n# ╔═╡ 1ac71ed0-c190-11ea-2cfe-4d7cfd514800\nmd\"`traj_steps: ` $(traj_steps)\"\n\n# ╔═╡ 727357e0-c18e-11ea-24f4-81a80c9e5f36\nbegin\n\tplot(traj[1:traj_steps])\n\txlims!(0, length(traj))\n\tylims!(minimum(traj), maximum(traj))\nend\n\n# ╔═╡ 55e2ff60-c191-11ea-1b6b-b9a74d8fab5f\nmd\"## Run N walkers simultaneously\"\n\n# ╔═╡ 60381bd0-c191-11ea-36a6-69333299f23b\nmd\"Rule: NEVER copy and paste (excpet occasionally)\n\nInstead: Automate \"\n\n# ╔═╡ e1c193c0-c191-11ea-0c16-67d6d7611c26\nbegin\n\tlocal n = 20\n\t\n\ttraj_ = [trajectory(n)]\n\t\n\tpush!(traj_, trajectory(n))\nend\n\n# ╔═╡ 6fad5d40-c192-11ea-2573-01f0eb6c17ed\nmd\"`append!` extracts the elements of a vector\"\n\n# ╔═╡ f4e1b4c0-c192-11ea-3782-79f7c856869f\nbegin\n\tlocal v = [1, 2, 3 ,4]\n\t\n\tappend!(v, [5, 6])\nend\n\n# ╔═╡ 0a1011c2-c193-11ea-04a2-e71ff37bf002\nmd\"a vector of vectors using an array comprehension\"\n\n# ╔═╡ d8b930b0-c193-11ea-0d53-63e3111f83a3\nn_ = 20\n\n# ╔═╡ c8dad7c0-c193-11ea-04a6-cf21953820d6\nwalkers = [trajectory(n_) for i ∈ 1:100]\n\n# ╔═╡ 0f2b2db0-c194-11ea-06a1-6b2192a8e677\nmd\"Use `end` to get the last element in a vector\"\n\n# ╔═╡ 61d6a940-c194-11ea-1d9f-4d6550479b45\n[ traj_[end] for traj_ in walkers ] # iterating through walkers, a Vector of Vectors\n\n# ╔═╡ 02bf22b0-c195-11ea-2d1b-ddebd9d7a069\nmd\"Convert Vector of Vectors into a matrix:\"\n\n# ╔═╡ 13a7bfb0-c195-11ea-13d2-41437b78aae1\nhcat(walkers...) # \"splat\" or like the \"spread\" operator in js\n\n# ╔═╡ 188fbdb0-c196-11ea-16c2-0bbd3bd3c5f2\nmd\"a more efficient way:\" \n\n# ╔═╡ b3074f30-c195-11ea-0025-af543bf613be\nwalkers_matrix = reduce(hcat, walkers) \n\n# ╔═╡ 2a00013e-c196-11ea-1d45-3d8ff26e1e53\nmd\"las element of the first row:\"\n\n# ╔═╡ f2221830-c195-11ea-09ff-2fb3e85bde34\nwalkers_matrix[1, end] \n\n# ╔═╡ 5ed8c0a0-c196-11ea-2e0c-370732384c6b\nmd\"last element of the first and second rows:\"\n\n# ╔═╡ 43f2c420-c196-11ea-3bfa-3320a1f4f92e\nwalkers_matrix[1:2, end] \n\n# ╔═╡ 6e5598a0-c196-11ea-11d2-8f08d13fb07f\nmd\"get the last element of all of the rows:\"\n\n# ╔═╡ 8b5d1592-c196-11ea-2a9f-17fbc031a2bd\nwalkers_matrix[1:end, end]\n\n# ╔═╡ 9cbb09a0-c196-11ea-0975-c59ab691f596\nmd\"also:\"\n\n# ╔═╡ a19bf82e-c196-11ea-024c-c7de6f0fbdb2\nfinal_positions = walkers_matrix[:, end]\n\n# ╔═╡ aed262a0-c196-11ea-310c-976af5163b2a\nmd\"## Where are the walkers at last time step?\"\n\n# ╔═╡ e3dc4420-c196-11ea-37be-1388e05cdfc5\nscatter(final_positions)\n\n# ╔═╡ 8e8a1d20-c197-11ea-2241-7fed80778896\nbegin\n\tlocal n = 100\n\t\n\tlocal num_walkers = 10_000\n\t\n\tlocal walkers = [trajectory(n) for i ∈ 1:num_walkers]\n\t\n\tfinal_positions_ = [traj_[end] for traj_ ∈ walkers]\nend\n\n# ╔═╡ a46bcf22-c198-11ea-3496-cfdbdfcac559\nscatter(final_positions_)\n\n# ╔═╡ 527b1810-c198-11ea-3634-5f82562c0394\nimport Pkg; Pkg.add(\"StatsBase\")\n\n# ╔═╡ 76ce6910-c198-11ea-1a99-e33a29b2860f\ncounts = countmap(final_positions_)\n\n# ╔═╡ c6170a90-c198-11ea-19c6-a377288360bd\nscatter(counts)\n\n# ╔═╡ Cell order:\n# ╟─1c0741f0-c17a-11ea-3c6f-31f0c86dd08d\n# ╟─58e6d60e-c17c-11ea-145e-ffdc97ab1f3f\n# ╠═a93d6520-c17c-11ea-2cc7-5ff51f20df2b\n# ╟─bfa68c10-c17c-11ea-281c-25e48e4ab81d\n# ╠═ccef6d10-c17c-11ea-13e5-432b940ba726\n# ╠═fea8c400-c17c-11ea-35fc-e98ef849c316\n# ╟─9aff5fa0-c185-11ea-145a-c3230681bd4c\n# ╠═0762ce10-c17d-11ea-1f2a-172e4ed0500a\n# ╟─212df5a0-c186-11ea-0f5c-83f0dd5a1497\n# ╠═8ce720ae-c185-11ea-380c-2df4848fb56a\n# ╠═f52fc0a0-c185-11ea-2126-b10b11defe13\n# ╟─891b2f20-c186-11ea-024f-372f0eef600c\n# ╠═15990630-c186-11ea-2059-e1e301040dae\n# ╠═62d228a2-c186-11ea-3ced-1db44003e269\n# ╠═0b66e5a2-c187-11ea-36de-279c4d6aa180\n# ╠═432008a0-c187-11ea-3606-159ae4ed8460\n# ╟─131fcc00-c18a-11ea-09dc-0906c430d399\n# ╟─1afa1280-c18c-11ea-1d1b-7f277d76e68c\n# ╠═8cfcb9a2-c187-11ea-1129-ff3d55e25de4\n# ╟─3b677390-c188-11ea-1079-01f262b1d76f\n# ╠═4a816b10-c188-11ea-3935-1fc7371387ac\n# ╠═643c5510-c188-11ea-2d15-fbf4939ae53c\n# ╠═b417eaf0-c18c-11ea-3ae7-19f88eab6b9f\n# ╟─eb35c2e0-c18d-11ea-3209-bd013b156820\n# ╠═1ec51ce0-c18f-11ea-2166-6923cbcef091\n# ╠═2c106ee0-c18f-11ea-21dc-db7d6706f5cb\n# ╟─3ee28c60-c18f-11ea-3297-3d26c8d37627\n# ╟─1ac71ed0-c190-11ea-2cfe-4d7cfd514800\n# ╠═727357e0-c18e-11ea-24f4-81a80c9e5f36\n# ╟─55e2ff60-c191-11ea-1b6b-b9a74d8fab5f\n# ╟─60381bd0-c191-11ea-36a6-69333299f23b\n# ╠═e1c193c0-c191-11ea-0c16-67d6d7611c26\n# ╟─6fad5d40-c192-11ea-2573-01f0eb6c17ed\n# ╠═f4e1b4c0-c192-11ea-3782-79f7c856869f\n# ╟─0a1011c2-c193-11ea-04a2-e71ff37bf002\n# ╠═d8b930b0-c193-11ea-0d53-63e3111f83a3\n# ╠═c8dad7c0-c193-11ea-04a6-cf21953820d6\n# ╟─0f2b2db0-c194-11ea-06a1-6b2192a8e677\n# ╠═61d6a940-c194-11ea-1d9f-4d6550479b45\n# ╟─02bf22b0-c195-11ea-2d1b-ddebd9d7a069\n# ╠═13a7bfb0-c195-11ea-13d2-41437b78aae1\n# ╟─188fbdb0-c196-11ea-16c2-0bbd3bd3c5f2\n# ╠═b3074f30-c195-11ea-0025-af543bf613be\n# ╟─2a00013e-c196-11ea-1d45-3d8ff26e1e53\n# ╠═f2221830-c195-11ea-09ff-2fb3e85bde34\n# ╟─5ed8c0a0-c196-11ea-2e0c-370732384c6b\n# ╠═43f2c420-c196-11ea-3bfa-3320a1f4f92e\n# ╟─6e5598a0-c196-11ea-11d2-8f08d13fb07f\n# ╠═8b5d1592-c196-11ea-2a9f-17fbc031a2bd\n# ╟─9cbb09a0-c196-11ea-0975-c59ab691f596\n# ╠═a19bf82e-c196-11ea-024c-c7de6f0fbdb2\n# ╟─aed262a0-c196-11ea-310c-976af5163b2a\n# ╠═e3dc4420-c196-11ea-37be-1388e05cdfc5\n# ╠═8e8a1d20-c197-11ea-2241-7fed80778896\n# ╠═a46bcf22-c198-11ea-3496-cfdbdfcac559\n# ╠═527b1810-c198-11ea-3634-5f82562c0394\n# ╠═62a8f092-c198-11ea-2d26-632729a6bd7f\n# ╠═76ce6910-c198-11ea-1a99-e33a29b2860f\n# ╠═c6170a90-c198-11ea-19c6-a377288360bd\n", "meta": {"hexsha": "c0506c1aaf836b7e48afd7f97e5749bb955ec25a", "size": 8007, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Random_Walk_Models.jl", "max_stars_repo_name": "elihugarret/my-notebooks", "max_stars_repo_head_hexsha": "b90b275fbc2a7b406daccd954b78f71d64e65f9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-10T19:16:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T20:34:25.000Z", "max_issues_repo_path": "Random_Walk_Models.jl", "max_issues_repo_name": "elihugarret/Computational-Modeling-in-Julia-with-Applications-to-the-COVID-19-Pandemic", "max_issues_repo_head_hexsha": "b90b275fbc2a7b406daccd954b78f71d64e65f9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Random_Walk_Models.jl", "max_forks_repo_name": "elihugarret/Computational-Modeling-in-Julia-with-Applications-to-the-COVID-19-Pandemic", "max_forks_repo_head_hexsha": "b90b275fbc2a7b406daccd954b78f71d64e65f9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2586750789, "max_line_length": 109, "alphanum_fraction": 0.7242412889, "num_tokens": 4280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950907764119, "lm_q2_score": 0.9099070097026719, "lm_q1q2_score": 0.7678660585511298}}
{"text": "# Matern 5/2 ARD covariance Function\n\n@doc \"\"\"\n# Description\nConstructor for the ARD Matern 5/2 kernel (covariance)\n\nk(x,x') = σ²(1+√3*d/L + 5d²/3L²)exp(-√5*d/L), where d = |x-x'| and L = diag(ℓ₁,ℓ₂,...)\n# Arguments:\n* `ll::Vector{Float64}`: Log of the length scale ℓ\n* `lσ::Float64`: Log of the signal standard deviation σ\n\"\"\" ->\ntype Mat52Ard <: StationaryARD\n    ℓ2::Vector{Float64}   # Log of Length scale \n    σ2::Float64           # Log of signal std\n    Mat52Ard(ll::Vector{Float64}, lσ::Float64) = new(exp(2.0*ll), exp(2.0*lσ))\nend\n\nfunction set_params!(mat::Mat52Ard, hyp::Vector{Float64})\n    length(hyp) == num_params(mat) || throw(ArgumentError(\"Mat52 kernel only has $(num_params(mat)) parameters\"))\n    d = length(mat.ℓ2)\n    mat.ℓ2 = exp(2.0*hyp[1:d])\n    mat.σ2 = exp(2.0*hyp[d+1])\nend\n\nget_params(mat::Mat52Ard) = [log(mat.ℓ2)/2.0; log(mat.σ2)/2.0]\nget_param_names(mat::Mat52Ard) = [get_param_names(mat.ℓ2, :ll); :lσ]\nnum_params(mat::Mat52Ard) = length(mat.ℓ2) + 1\n\nmetric(mat::Mat52Ard) = WeightedEuclidean(1.0./(mat.ℓ2))\ncov(mat::Mat52Ard, r::Float64) = mat.σ2*(1+sqrt(5)*r+5/3*r^2)*exp(-sqrt(5)*r)\n\nfunction grad_kern(mat::Mat52Ard, x::Vector{Float64}, y::Vector{Float64})\n    #r = distance(mat,x,y)\n    wdiff = (x-y).^2./mat.ℓ2\n    r = sqrt(sum(wdiff))\n    exp_r = exp(-sqrt(5)*r)\n    \n    g1 = mat.σ2*(5/3)*(1+sqrt(5)*r)*exp_r.*wdiff # dK_d(log ℓ)\n    g2 = 2.0*mat.σ2*(1+sqrt(5)*r+(5/3)*r^2)*exp_r  # dK_d(log σ)\n    \n    return [g1; g2]\nend\n\nfunction grad_stack!(stack::AbstractArray, mat::Mat52Ard, X::Matrix{Float64}, data::StationaryARDData)\n    d = size(X,1)\n    R = distance(mat,X)\n    exp_R = exp(-sqrt(5)*R)\n\n    stack[:,:,d+1] = 2.0*cov(mat, X)\n    part = (5/3) * mat.σ2 .* exp_R .* (1.0 + sqrt(5)*R)\n    broadcast!(*, view(stack, :, :, 1:d), (5/3)*mat.σ2, 1 + sqrt(5)*R, exp_R, data.dist_stack, reshape(1.0./mat.ℓ2, (1,1,d)))\n\n    return stack\nend\n", "meta": {"hexsha": "c178554691de898a95a4638c9abff6411d0708af", "size": 1880, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/mat52_ard.jl", "max_stars_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/mat52_ard.jl", "max_issues_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/mat52_ard.jl", "max_forks_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1818181818, "max_line_length": 125, "alphanum_fraction": 0.6154255319, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.7678491181625714}}
{"text": "\"\"\"\nVAR1SimPs(A,epsilon,T,x0=0.0)\n\nCalculate impulse response function of a VAR(1) system\nx(t) = A * x(t-1) +  epsilon(t), where x(t) is nx1\n\n# Input\n- `A::Matrix`:                  nxn VAR(1) matrix, see above\n- `epsilon::Number or Vector`:  n-vector of shocks in inital period, or Txn matrix with shocks in all periods\n- `T::Number`:                  scalar, last period to calculate for\n- `x0::Number or Vector`:       n-vector with starting values, optional\n\n# Output\n- `xM::Matrix`:               Txn matrix, impulse response function\n\nPaul.Soderlind@unisg.ch, to Julia Nov 2015\n\n\"\"\"\nfunction VAR1SimPs(A,epsilon,T,x0=0.0)\n\n  n = size(A,1)\n\n  isa(x0,Number)         && (x0      = fill(x0,n))           #if scalar\n  isa(epsilon,Number)    && (epsilon = fill(epsilon,n))\n  (length(epsilon) == n) && (epsilon = vcat(vec(epsilon)',zeros(T-1,n)))\n\n  xM      = fill(NaN,(T,n))                        #to put results in\n  xM[1,:] = A*vec(x0) + epsilon[1,:]\n  for t = 2:T                                      #loop over time periods\n    xM[t,:] = A*xM[t-1,:] + epsilon[t,:]\n  end\n\n  return xM\n\nend\n#-----------------------------------------------------------------------\n", "meta": {"hexsha": "2b3a1c5b1f3de786f766e88fe7ad55396d54d136", "size": 1168, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SolvingReModels/jlFiles/VAR1SimPs.jl", "max_stars_repo_name": "PaulSoderlind/PaulSoderlindCode", "max_stars_repo_head_hexsha": "849ab977e410ece42d24ec86a4e043180200c551", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2016-01-15T21:13:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T21:21:18.000Z", "max_issues_repo_path": "SolvingReModels/jlFiles/VAR1SimPs.jl", "max_issues_repo_name": "PaulSoderlind/PaulSoderlindCode", "max_issues_repo_head_hexsha": "849ab977e410ece42d24ec86a4e043180200c551", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-03-05T13:07:59.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-07T11:11:21.000Z", "max_forks_repo_path": "SolvingReModels/jlFiles/VAR1SimPs.jl", "max_forks_repo_name": "PaulSoderlind/PaulSoderlindCode", "max_forks_repo_head_hexsha": "849ab977e410ece42d24ec86a4e043180200c551", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2016-03-05T13:01:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T19:44:57.000Z", "avg_line_length": 31.5675675676, "max_line_length": 109, "alphanum_fraction": 0.5265410959, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7678491162053162}}
{"text": "module TestSystems\n    using ..HomConBase\n\n    export cyclic5, cyclic5Solutions, cyclic7, cyclic7Solutions\n\n    \"\"\"\n        cyclical(iter, n)\n\n    Cycles through an `iter` with n consecutive elements.\n\n    ###Example:\n        cyclical([1, 2, 3, 4], 2) == [[1, 2], [2, 3], [3, 4], [4, 1]]\n    \"\"\"\n    function cyclical(iter, n)\n        m = length(iter)\n        if n == m\n            return [collect(iter)]\n        end\n        values = collect(iter);\n        res = Vector{Vector{eltype(values)}}()\n        for k=0:m-1\n            push!(res, [values[((k + i) % m) + 1] for i=0:n-1])\n        end\n        res\n    end\n\n\n    function monompoly(monomials::Vector{Vector{Int}}, totalvars)\n        exps = zeros(Int, totalvars, length(monomials))\n        for i in eachindex(monomials)\n            for var in monomials[i]\n                exps[var, i] = 1\n            end\n        end\n        coeffs = ones(Int, length(monomials))\n        Poly(exps, coeffs)\n    end\n\n\n    function cyclical_polys(n)\n        F = map(k -> monompoly(cyclical(1:n, k), n), 1:n-1)\n        # now we have to construct x₁x₂x₃...x_n - 1\n        exps = zeros(Int, n, 2)\n        exps[:,1] = 1\n        push!(F, Poly(exps, [1, -1]))\n        PolySystem(F, [Symbol(\"z$i\") for i=1:n])\n    end\n\n    \"\"\"\n        cyclic5()\n\n    Cyclic5 example problem folowing [^1]\n\n    [^1]: A faster way to count the solutions of inhomogeneous systems of algebraic equations,\n    with applications to cyclic n-roots\n    \"\"\"\n    function cyclic5()\n        cyclical_polys(5)\n    end\n\n    \"\"\"\n        cyclic5Solutions()\n\n    Solutions to the Cyclic5 example.\n    \"\"\"\n    function cyclic5Solutions()\n        # (1,w,w^{2k},w^{3k},w^{4k}) with w = exp(2πi/5) permuted cyclical, 1 ≦ k ≦ 4\n        w = exp(2.0*π*im/5.0)\n        classic_sols = vec([ map(i -> w^(i*k), perm) for k in 1:4, perm in cyclical(0:4, 5)])\n\n        #solution of ɛ^2+3ɛ+1=0\n        ɛ = -1.5 - 0.5 * √5.0 + 0*im\n        extended_sols = vec([ rev ? reverse!(w^k * perm) : w^k * perm for perm in cyclical([ɛ, 1/ɛ, 1, 1, 1], 5),\n                                                                            k in 0:4,\n                                                                            rev in [false, true]])\n        vcat(classic_sols, extended_sols)\n    end\n    \"\"\"\n        cyclic7()\n\n    Cyclic7 problem folowing [^1]\n\n    [^1]: A faster way to count the solutions of inhomogeneous systems of algebraic equations,\n    with applications to cyclic n-roots\n    \"\"\"\n    function cyclic7()\n        cyclical_polys(7)\n    end\n\n    \"\"\"\n        cyclic7Solutions()\n\n    Solutions to the Cyclic7 example.\n    \"\"\"\n    function cyclic7Solutions()\n        # (1,w,w^{2k},w^{3k},w^{4k},w^{5k},w^{6k}) with w = exp(2πi/7) permuted cyclical, 1 ≦ k ≦ 6\n        w = exp(2.0*π*im/7.0)\n        classic_sols = vec([ map(i -> w^(i*k), perm) for k in 1:6, perm in cyclical(0:6, 7)])\n\n        #solution of ɛ^2+5ɛ+1=0\n        ɛ = -2.5 - 0.5 * √21.0 + 0*im\n        extended_sols = vec([ rev ? reverse!(w^k * perm) : w^k * perm for perm in cyclical([ɛ, 1/ɛ, 1, 1, 1, 1, 1], 7),\n                                                                            k in 0:6,\n                                                                            rev in [false, true]])\n\n        # index two solutions\n        d = 0.25*im*(√7 + 3*im)\n        index_two = vec([ rev ? reverse!(w^k * perm) : w^k * perm for perm in cyclical([d, conj(d), d, 1, conj(d), 1, 1], 7),\n                                                                            k in 0:6,\n                                                                            rev in [false, true]])\n        index_two_conj = vec([ rev ? reverse!(w^k * perm) : w^k * perm for perm in cyclical([conj(d), d, conj(d), 1, d, 1, 1], 7),\n                                                                            k in 0:6,\n                                                                            rev in [false, true]])\n\n        # index three solutions\n        a = 2.738895317095 + 0im\n        b = 3.436680125767 + 0im\n        c = -0.1298393513967 + 0im\n        sol_1 = [a, b, c, 1, 1/c, 1/b, 1/a]\n        sol_2 = [a*b,c,1/(b*c),1,b*c,1/c, 1/(a*b)]\n        sol_3 = [a*b*c,1/(b*c),b,1,1/b,b*c,1/(a*b*c)]\n\n        perms = [cyclical(sol_1, 7); cyclical(sol_2, 7); cyclical(sol_3, 7)]\n        index_three_first = vec([ rev ? reverse!(w^k * perm) : w^k * perm for perm in perms, k in 0:6, rev in [false, true]])\n\n        a = exp(4.3128389787245im)\n        b = exp(1.356227956787im)\n        c = exp(1.900668281165im)\n        sol_1 = [a, b, c, 1, 1/c, 1/b, 1/a]\n        sol_2 = [a*b,c,1/(b*c),1,b*c,1/c, 1/(a*b)]\n        sol_3 = [a*b*c,1/(b*c),b,1,1/b,b*c,1/(a*b*c)]\n        perms = [cyclical(sol_1, 7); cyclical(sol_2, 7); cyclical(sol_3, 7)]\n        index_three_second = vec([ rev ? reverse!(w^k * perm) : w^k * perm for perm in perms, k in 0:6, rev in [false, true]])\n\n        vcat(classic_sols, extended_sols, index_two, index_two_conj, index_three_first, index_three_second)\n    end\nend\n", "meta": {"hexsha": "910ffea6f11373a882a6eae621fcb26f9a79a597", "size": 4993, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TestSystems/TestSystems.jl", "max_stars_repo_name": "blegat/HomotopyContinuation.jl", "max_stars_repo_head_hexsha": "331282442403125f15f2e022351ebe2d6f8816d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TestSystems/TestSystems.jl", "max_issues_repo_name": "blegat/HomotopyContinuation.jl", "max_issues_repo_head_hexsha": "331282442403125f15f2e022351ebe2d6f8816d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TestSystems/TestSystems.jl", "max_forks_repo_name": "blegat/HomotopyContinuation.jl", "max_forks_repo_head_hexsha": "331282442403125f15f2e022351ebe2d6f8816d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1811594203, "max_line_length": 130, "alphanum_fraction": 0.4722611656, "num_tokens": 1632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7678491089179207}}
{"text": "# Using Convex.jl to test if the probability distributions in Homework problem 1\n# Sets up the optimization problem for the Cut Inflation for the triangle causal\n# model with the distribution:\n#\n# P(a, b, c) = if (a + b + c == 1) => 1/3\n#              else             => 0\n\nusing Convex\nusing GLPK\nusing Inflation\n\n# the probability matrix is set up as\n# P_{A1,B1,C1} = sum_{A2,B2,C2}P     --> 'yxyxyx'\n# P_{A1,B2,C2} = sum_{A2,B1,C1}P     --> 'yxxyxy'\n# P_{A2,B1,C2} = sum_{A1,B2,C1}P     --> 'xyyxxy'\n# P_{A2,B2,C1} = sum_{A1,B1,C2}P     --> 'xyxyyx'\n# P_{A2,B2,C2} = sum_{A1,B1,C1}P     --> 'xyxyxy'\ninfl_strings = [\"yxyxyx\", \"yxxyxy\", \"xyyxxy\", \"xyxyyx\", \"xyxyxy\"]\n\n# creating the M-matrix and b-array to be used in the Convex.jl optimization\nM = get_M_matrix(infl_strings)\nb = get_b_array(infl_strings, pfunc2, spiral)\n\n# the variables that get optimized by Convex.jl\nv = get_v_array_Variable(infl_strings)\n\n# set up the objective and constraints\nobjective   = 0\nconstraints = [v >= 0, M*v == b]\n\n# create the problem and solve\nproblem = Convex.maximize(objective, constraints)\nsolve!(problem, GLPK.Optimizer, verbose=false)\n\n# return the results\nif problem.status == Convex.MathOptInterface.INFEASIBLE\n\tprintln(\"Solution is infeasible.\")\nelse\n\tprintln(problem.optval)\n\tprintln(v.value)\nend\n", "meta": {"hexsha": "053dda142c0e4f28c0b8529c176a5ab27949a401", "size": 1297, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problem4.jl", "max_stars_repo_name": "AlexanderIbrahim1/Inflation", "max_stars_repo_head_hexsha": "b3549ccf2438ce062ccce65f27efbc856d1fae7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problem4.jl", "max_issues_repo_name": "AlexanderIbrahim1/Inflation", "max_issues_repo_head_hexsha": "b3549ccf2438ce062ccce65f27efbc856d1fae7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problem4.jl", "max_forks_repo_name": "AlexanderIbrahim1/Inflation", "max_forks_repo_head_hexsha": "b3549ccf2438ce062ccce65f27efbc856d1fae7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.880952381, "max_line_length": 80, "alphanum_fraction": 0.6815728604, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666346, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7678323512447568}}
{"text": "using Distributions\nfunction discrete_normal(n,mu,sigma,width)\n\n# creates equally spaced approximation to normal distribution\n# n is number of points\n# mu is mean\n# sigma is standard deviation\n# width is the multiple of stand deviation for the width of the grid\n# f is the error in the approximation\n# x gives the location of the points\n# p is probabilities\n\n    x = collect(range(mu-width*sigma,mu+width*sigma,length=n))\n    if n==2\n        p = 0.5.*ones(n)\n    elseif n>2    \n        p  = zeros(n)\n        p[1] = cdf(Normal(mu,sigma), x[1] + 0.5*(x[2]-x[1]))\n        for i = 2:n-1\n            p[i] = cdf(Normal(mu,sigma), x[i] + 0.5*(x[i+1]-x[i])) - cdf(Normal(mu,sigma), x[i] - 0.5*(x[i]-x[i-1]))\n        end\n        p[n] = 1 - sum(p[1:n-1])\n    end\n\n    Ex = x'*p\n    SDx = sqrt((x.^2)'*p .- Ex.^2)\n\n    f = SDx.-sigma\n            \n    return f,x,p\n            \nend", "meta": {"hexsha": "9430d4340a9afc86ec5838eeb3ff19c4a55033d1", "size": 869, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Guides/HA_codes/Julia/discrete_normal.jl", "max_stars_repo_name": "pranjalrawat007/Recursive-Macro", "max_stars_repo_head_hexsha": "6caab42818e32b3a23584dca91837ad50db71616", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2022-01-25T10:14:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T06:38:17.000Z", "max_issues_repo_path": "Guides/HA_codes/Julia/discrete_normal.jl", "max_issues_repo_name": "pranjalrawat007/Recursive-Macro", "max_issues_repo_head_hexsha": "6caab42818e32b3a23584dca91837ad50db71616", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Guides/HA_codes/Julia/discrete_normal.jl", "max_forks_repo_name": "pranjalrawat007/Recursive-Macro", "max_forks_repo_head_hexsha": "6caab42818e32b3a23584dca91837ad50db71616", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-25T05:58:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T09:19:48.000Z", "avg_line_length": 27.15625, "max_line_length": 116, "alphanum_fraction": 0.5673187572, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813551535006, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7678191832729194}}
{"text": "function bin_dist(n, k, p, q)\n    return binomial(n, k) * p^k * q^(n-k)\nend\n\nfunction f(n, k, p, q)\n    mass = 0\n    for i = 0:k\n        mass += bin_dist(n, i, p, q)\n    end\n    return mass\nend\n\nfunction g(n, k, p, q)\n    mass = 0\n    for i = k:n\n        mass += bin_dist(n, i, p, q)\n    end\n    return mass\nend\n\nstr = readline()\nstrvec = split(str, ' ')\nintvec = map(x -> parse(Int64, x), strvec)\na = intvec[1]\nn = intvec[2]\n\np = a / 100\nq = 1 - p\n\nprintln(round(f(n, 2, p, q), 3))\nprintln(round(g(n, 2, p, q), 3))\n", "meta": {"hexsha": "f94c9a81e5d7efd3f79c08eb54c18cc353d43791", "size": 516, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Tutorials/10 Days of Statistics/Day 4/binomial_distribution2.jl", "max_stars_repo_name": "xuedong/hacker-rank", "max_stars_repo_head_hexsha": "ce8a60f80c2c6935b427f9409d7e826ee0d26a89", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-22T17:37:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T17:37:45.000Z", "max_issues_repo_path": "Tutorials/10 Days of Statistics/Day 4/binomial_distribution2.jl", "max_issues_repo_name": "xuedong/hacker-rank", "max_issues_repo_head_hexsha": "ce8a60f80c2c6935b427f9409d7e826ee0d26a89", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tutorials/10 Days of Statistics/Day 4/binomial_distribution2.jl", "max_forks_repo_name": "xuedong/hacker-rank", "max_forks_repo_head_hexsha": "ce8a60f80c2c6935b427f9409d7e826ee0d26a89", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.125, "max_line_length": 42, "alphanum_fraction": 0.519379845, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7678191614655339}}
{"text": "# ---\n# title: 69. Sqrt(x)\n# id: problem69\n# author: Indigo\n# date: 2022-03-03\n# difficulty: Easy\n# categories: Math, Binary Search\n# link: <https://leetcode.com/problems/sqrtx/description/>\n# hidden: true\n# ---\n# \n# Given a non-negative integer `x`, compute and return _the square root of_ `x`.\n# \n# Since the return type is an integer, the decimal digits are **truncated** ,\n# and only **the integer part** of the result is returned.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: x = 4\n#     Output: 2\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: x = 8\n#     Output: 2\n#     Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.\n# \n# \n# \n# **Constraints:**\n# \n#   * `0 <= x <= 231 - 1`\n# \n# \n## @lc code=start\nusing LeetCode\n\nmy_sqrt = isqrt\nfunction mysqrt(x::Int)::Int\n    x < 0 && throw(DomainError(x))\n    left, right = 0, x\n    while left <= right\n        mid = left + ((right - left) >> 1)\n        if mid ^ 2 > x\n            right = mid - 1\n        else\n            left = mid + 1\n        end\n    end\n    right\nend\n\n## @lc code=end\n", "meta": {"hexsha": "006d73343a77e71c47efa40b13e5da1a84fc9231", "size": 1113, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/submited/date-03/69.sqrtx.jl", "max_stars_repo_name": "RexWzh/leetcode_note.jl", "max_stars_repo_head_hexsha": "eae55703e771485d5eff37010f34967694a4158b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/submited/date-03/69.sqrtx.jl", "max_issues_repo_name": "RexWzh/leetcode_note.jl", "max_issues_repo_head_hexsha": "eae55703e771485d5eff37010f34967694a4158b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/submited/date-03/69.sqrtx.jl", "max_forks_repo_name": "RexWzh/leetcode_note.jl", "max_forks_repo_head_hexsha": "eae55703e771485d5eff37010f34967694a4158b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.2459016393, "max_line_length": 110, "alphanum_fraction": 0.5462713387, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7677740484116249}}
{"text": "\r\nmutable struct FixedStepOdeOptions\r\n    step_size::Float64\r\nend\r\nfunction FixedStepOdeOptions(; step_size = 1e-2)\r\n    FixedStepOdeOptions(step_size)\r\nend\r\n\r\n\r\n\r\n\r\nfunction ode_solver_explicit_euler(fcn, time_interval::TimeInterval, initial_values::Vector{T}, options::FixedStepOdeOptions) where {T}\r\n\r\n    step_size = options.step_size\r\n\r\n    t     = time_interval.t_start\r\n    q     = initial_values\r\n\r\n    ode_res = init_ode_result(q)\r\n\r\n    while true\r\n\r\n        dqdt  = fcn(t, q)\r\n        q_new = q + step_size * dqdt\r\n\r\n        t = t + step_size\r\n        q = q_new\r\n\r\n        push!(ode_res, t, q)\r\n\r\n        if t >= time_interval.t_end\r\n            break\r\n        end\r\n\r\n    end\r\n\r\n    return ode_res\r\nend\r\n\r\n\r\nfunction ode_solver_semiimplicit_euler(fcn, time_interval::TimeInterval, initial_values::Vector{T}, options::FixedStepOdeOptions) where {T}\r\n\r\n    step_size = options.step_size\r\n\r\n    t     = time_interval.t_start\r\n    q     = initial_values\r\n\r\n    ode_res = init_ode_result(q)\r\n\r\n    n_dim = length(initial_values)\r\n    id = Matrix{T}( one(T) * I , n_dim, n_dim )\r\n\r\n    while true\r\n\r\n        t_new = t + step_size\r\n        jac = numder.jacobian_fw( q->fcn(t_new, q), q)\r\n\r\n        mat = id - step_size * jac\r\n        dq = step_size .*( mat \\ fcn(t_new, q) )\r\n        \r\n        t = t_new\r\n        q = q + dq\r\n\r\n        push!(ode_res, t, q)\r\n\r\n        if t >= time_interval.t_end\r\n            break\r\n        end\r\n\r\n    end\r\n\r\n    return ode_res\r\n\r\nend\r\n\r\n\r\nfunction ode_solver_implicit_euler(fcn, time_interval::TimeInterval, initial_values::Vector{T}, options::FixedStepOdeOptions) where {T}\r\n\r\n    step_size = options.step_size\r\n\r\n    t     = time_interval.t_start\r\n    q     = initial_values\r\n\r\n    ode_res = init_ode_result(q)\r\n\r\n    n_dim = length(initial_values)\r\n    # id = Matrix{T}( one(T) * I , n_dim, n_dim )\r\n\r\n    while true\r\n\r\n        t_new = t + step_size\r\n        nonlin_fcn(y) = step_size .* fcn(t_new, y) - y + q\r\n\r\n        q_try = q + step_size * fcn(t_new, q)\r\n\r\n        (q_new, nonlineq_iter) = nonlineq.broyden( nonlin_fcn, q_try )\r\n\r\n        t = t_new\r\n        q = q_new\r\n\r\n        push!(ode_res, t, q)\r\n\r\n        if t >= time_interval.t_end\r\n            break\r\n        end\r\n\r\n    end\r\n\r\n    return ode_res\r\n\r\nend\r\n\r\n\r\nfunction ode_solver_rk4(\r\n    fcn,\r\n    time_interval::TimeInterval,\r\n    initial_values::Vector{T},\r\n    options::FixedStepOdeOptions) where {T}\r\n\r\n\r\n\r\nend\r\n", "meta": {"hexsha": "10b9cb42a107bae2e0e7b4cd5d4dbcf87c4d1a36", "size": 2419, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/ode/src/fixed_step_size_solvers.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "__lib__/math/ode/src/fixed_step_size_solvers.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "__lib__/math/ode/src/fixed_step_size_solvers.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6666666667, "max_line_length": 140, "alphanum_fraction": 0.5804051261, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7677740484116249}}
{"text": "# =========================================================================================================================\n# Theoretical error bounds for Carleman linearization\n#\n# References:\n#\n# - [1] Forets, Marcelo, and Amaury Pouly. \"Explicit error bounds for carleman linearization.\"\n#       arXiv preprint arXiv:1711.02552 (2017).\n#\n# - [2] Liu, J. P., Kolden, H. Ø., Krovi, H. K., Loureiro, N. F., Trivisa, K., & Childs,7\n#       A. M. (2021). \"Efficient quantum algorithm for dissipative nonlinear differential equations.\"\n#       Proceedings of the National Academy of Sciences, 118(35). arXiv preprint arXiv:2011.03185.\n#\n# =========================================================================================================================\n\n# --- Error bounds using a priori estimate from [1] ---\n\n# See Theorem 4.2 in [1]. This is a bound based on an a priori estimate\n# of the norm of the exact solution x(t).\n# These bounds use the supremum norm (p = Inf).\nfunction error_bound_apriori(α, F₁, F₂; N)\n    nF₂ = opnorm(F₂, Inf)\n    μF₁ = logarithmic_norm(F₁, Inf)\n\n    β = α * nF₂ / μF₁\n    ε = t -> α * β^N * (exp(μF₁ * t) - 1)^N\n    return ε\nend\n\n# See Theorem 4.2 in [1]\nfunction convergence_radius_apriori(α, F₁, F₂; N)\n    nF₂ = opnorm(F₂, Inf)\n    μF₁ = logarithmic_norm(F₁, Inf)\n\n    if μF₁ < 0\n        return Inf\n    end\n    β = α * F₂ / μF₁\n    T = (1/μF₁) * log(1 + 1/β)\n    return T\nend\n\n# --- Error bounds using power series method from [1] ---\n\n# See Theorem 4.3 in [1], which uses the power series method.\nfunction error_bound_pseries(x₀, F₁, F₂; N)\n    nx₀ = norm(x₀, Inf)\n    nF₁ = opnorm(F₁, Inf)\n    nF₂ = opnorm(F₂, Inf)\n    β₀ = nx₀ * nF₂ / nF₁\n\n    ε = t -> nx₀ * exp(nF₁ * t) / (1 - β₀ * (exp(nF₁ * t) - 1)) * (β₀ * (exp(nF₁ * t) - 1))^N\n    return ε\nend\n\n# See Theorem 4.3 in [1].\nfunction convergence_radius_pseries(x₀, F₁, F₂; N)\n    nx₀ = norm(x₀, Inf)\n    nF₁ = opnorm(F₁, Inf)\n    nF₂ = opnorm(F₂, Inf)\n    β₀ = nx₀ * nF₂ / nF₁\n\n    T = (1/nF₁) * log(1 + 1/β₀)\n    return T\nend\n\n# --- Error bounds using spectral abscissa from [2] ---\n\n# See Definition (2.2) in [2]. These bounds use the spectral norm (p = 2)\nfunction _error_bound_specabs_R(x₀, F₁, F₂; check=true)\n    nx₀ = norm(x₀, 2)\n    nF₂ = opnorm(F₂, 2)\n\n    # compute eigenvalues and sort them by increasing real part\n    λ = eigvals(F₁, sortby=real)\n    λ₁ = last(λ)\n    Re_λ₁ = real(λ₁)\n    if check\n        @assert Re_λ₁ <= 0 \"expected Re(λ₁) ≤ 0, got $Re_λ₁\"\n    end\n    R = nx₀ * nF₂ / abs(Re_λ₁)\n    return (R, Re_λ₁)\nend\n\n# See Lemma 2 in [2]\nfunction error_bound_specabs(x₀, F₁, F₂; N, check=true)\n    (R, Re_λ₁) = _error_bound_specabs_R(x₀, F₁, F₂; check=check)\n    if check\n        @assert R < 1 \"expected R < 1, got R = $R; try scaling the ODE\"\n    end\n\n    nx₀ = norm(x₀, 2)\n    if iszero(Re_λ₁)\n        nF₂ = opnorm(F₂, 2)\n        ε = t -> nx₀ * (nx₀ * nF₂ * t)^N\n    else\n        ε = t -> nx₀ * R^N * (1 - exp(Re_λ₁ * t))^N\n    end\n    return ε\nend\n\n# See Lemma 2 in [2]\nfunction convergence_radius_specabs(x₀, F₁, F₂; check=true)\n    (R, Re_λ₁) = _error_bound_specabs_R(x₀, F₁, F₂; check=check)\n\n    if Re_λ₁ < 0\n        T = Inf\n    elseif iszero(Re_λ₁)\n        nx₀ = norm(x₀, 2)\n        nF₂ = opnorm(F₂, 2)\n        β = nx₀ * nF₂\n        T = 1/β\n    else\n        throw(ArgumentError(\"expected spectral abscissa to be negative or zero, got $Re_λ₁\"))\n    end\n    return T\nend\n", "meta": {"hexsha": "f6b922da6af4b2c65f300c0703df5f84cf1486a9", "size": 3395, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/error_bounds.jl", "max_stars_repo_name": "pogudingleb/CarlemanLinearization.jl", "max_stars_repo_head_hexsha": "461d782c2f42cc5961bede7123ce237f441c1635", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/error_bounds.jl", "max_issues_repo_name": "pogudingleb/CarlemanLinearization.jl", "max_issues_repo_head_hexsha": "461d782c2f42cc5961bede7123ce237f441c1635", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/error_bounds.jl", "max_forks_repo_name": "pogudingleb/CarlemanLinearization.jl", "max_forks_repo_head_hexsha": "461d782c2f42cc5961bede7123ce237f441c1635", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0170940171, "max_line_length": 123, "alphanum_fraction": 0.5531664212, "num_tokens": 1224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8499711832583696, "lm_q1q2_score": 0.7677740457025258}}
{"text": "using LinearAlgebra\nusing ExtendableSparse\n\nmutable struct RadialBasis{F,Q,X,Y,L,U,C,S,D} <: AbstractSurrogate\n    phi::F\n    dim_poly::Q\n    x::X\n    y::Y\n    lb::L\n    ub::U\n    coeff::C\n    scale_factor::S\n    sparse::D\nend\n\nmutable struct RadialFunction{Q,P}\n    q::Q # degree of polynomial\n    phi::P\nend\n\nlinearRadial = RadialFunction(0,z->norm(z))\n\ncubicRadial = RadialFunction(1,z->norm(z)^3)\nmultiquadricRadial = RadialFunction(1,z->sqrt(norm(z)^2+1))\n\nthinplateRadial = RadialFunction(2, z->begin\n    result = norm(z)^2 * log(norm(z))\n    ifelse(iszero(z), zero(result), result)\nend)\n\n\"\"\"\n    RadialBasis(x,y,lb::Number,ub::Number; rad::RadialFunction = linearRadial,scale::Real=1.0)\n\nConstructor for RadialBasis surrogate.\n\"\"\"\nfunction RadialBasis(x, y, lb::Number, ub::Number; rad::RadialFunction=linearRadial, scale_factor::Real=1.0, sparse = false)\n    q = rad.q\n    phi = rad.phi\n    coeff = _calc_coeffs(x, y, lb, ub, phi, q,scale_factor, sparse)\n    return RadialBasis(phi, q, x, y, lb, ub, coeff,scale_factor,sparse)\nend\n\n\"\"\"\nRadialBasis(x,y,lb,ub,rad::RadialFunction, scale_factor::Float = 1.0)\n\nConstructor for RadialBasis surrogate\n\"\"\"\nfunction RadialBasis(x, y, lb, ub; rad::RadialFunction = linearRadial, scale_factor::Real=1.0, sparse = false)\n    q = rad.q\n    phi = rad.phi\n    coeff = _calc_coeffs(x, y, lb, ub, phi, q, scale_factor, sparse)\n    return RadialBasis(phi, q, x, y, lb, ub, coeff,scale_factor, sparse)\nend\n\nfunction _calc_coeffs(x, y, lb, ub, phi, q, scale_factor, sparse)\n    nd = length(first(x))\n    num_poly_terms = binomial(q + nd, q)\n\n    D = _construct_rbf_interp_matrix(x, first(x), lb, ub, phi, q, scale_factor, sparse)\n    Y = _construct_rbf_y_matrix(y, first(y), length(y) + num_poly_terms)\n\n    coeff = D \\ Y\n    return coeff\nend\n\nfunction _construct_rbf_interp_matrix(x, x_el::Number, lb, ub, phi, q, scale_factor, sparse)\n    n = length(x)\n\n    num_poly_terms = binomial(q + 1, q)\n    m = n + num_poly_terms\n\n    if sparse\n        D = ExtendableSparseMatrix{eltype(x_el),Int}(m,m)\n    else\n        D = zeros(eltype(x_el), m, m)\n    end\n    @inbounds for i = 1:n\n        for j = 1:n\n            D[i,j] = phi( (x[i] .- x[j]) ./ scale_factor )\n        end\n        if i <= n\n            for k = 1:num_poly_terms\n                    D[i,n+k] = _scaled_chebyshev(x[i], k-1, lb, ub)\n            end\n        end\n    end\n    D_sym = Symmetric(D, :U)\n    return D_sym\nend\n\nfunction _construct_rbf_interp_matrix(x, x_el, lb, ub, phi, q, scale_factor,sparse)\n    n = length(x)\n    nd = length(x_el)\n\n    num_poly_terms = binomial(q + nd, q)\n    m = n + num_poly_terms\n\n    if sparse\n        D = ExtendableSparseMatrix{eltype(x_el),Int}(m,m)\n    else\n        D = zeros(eltype(x_el), m, m)\n    end\n    @inbounds for i = 1:n\n        for j = 1:n\n            D[i,j] = phi( (x[i] .- x[j]) ./ scale_factor)\n        end\n        if i < n + 1\n            for k = 1:num_poly_terms\n                D[i,n+k] = multivar_poly_basis(x[i], k-1, nd, q)\n            end\n        end\n    end\n    D_sym = Symmetric(D, :U)\n    return D_sym\nend\n\n_construct_rbf_y_matrix(y, y_el::Number, m) = [i <= length(y) ? y[i] : zero(y_el) for i = 1:m]\n_construct_rbf_y_matrix(y, y_el, m) = [i <= length(y) ? y[i][j] : zero(first(y_el)) for i=1:m, j=1:length(y_el)]\n\nusing Zygote: @nograd\n\nfunction _make_combination(n, d, ix)\n    exponents_combinations = [\n        e\n        for e\n        in collect(\n            Iterators.product(\n                Iterators.repeated(0:n, d)...\n            )\n        )[:]\n        if sum(e) <= n\n    ]\n\n    return exponents_combinations[ix + 1]\nend\n# TODO: Is this correct? Do we ever want to differentiate w.r.t n, d, or ix?\n# By using @nograd we force the gradient to be 1 for n, d, ix\n@nograd _make_combination\n\n\"\"\"\n    multivar_poly_basis(x, ix, d, n)\n\nEvaluates in `x` the `ix`-th element of the multivariate polynomial basis of maximum\ndegree `n` and `d` dimensions.\n\nTime complexity: `(n+1)^d.`\n\n# Example\nFor n=2, d=2 the multivariate polynomial basis is\n````\n1,\nx,y\nx^2,y^2,xy\n````\nTherefore the 3rd (ix=3) element is `y` .\nTherefore when x=(13,43) and ix=3 this function will return 43.\n\"\"\"\nmultivar_poly_basis(x, ix, d, n) = prod(\n    a^d\n    for (a, d)\n    in zip(x, _make_combination(n, d, ix))\n)\n\n\"\"\"\nCalculates current estimate of value 'val' with respect to the RadialBasis object.\n\"\"\"\nfunction (rad::RadialBasis)(val)\n    approx = _approx_rbf(val, rad)\n    return _match_container(approx, first(rad.y))\nend\n\nfunction _approx_rbf(val::Number, rad)\n    n = length(rad.x)\n    q = rad.dim_poly\n    num_poly_terms = binomial(q + 1, q)\n    lb = rad.lb\n    ub = rad.ub\n    approx = zero(rad.coeff[1, :])\n    for i = 1:n\n        approx += rad.coeff[i, :] * rad.phi( (val .- rad.x[i]) / rad.scale_factor)\n    end\n    for k = 1:num_poly_terms\n        approx += rad.coeff[n+k, :] * _scaled_chebyshev(val, k-1, lb, ub)\n    end\n    return approx\nend\nfunction _approx_rbf(val, rad)\n    n = length(rad.x)\n    d = length(rad.x[1])\n    q = rad.dim_poly\n    num_poly_terms = binomial(q + d, q)\n    lb = rad.lb\n    ub = rad.ub\n    sum_half_diameter = sum((ub[k]-lb[k])/2 for k = 1:d)\n    mean_half_diameter = sum_half_diameter/d\n    central_point = _center_bounds(first(rad.x), lb, ub)\n\n    approx = zero(rad.coeff[1, :])\n    @views approx += sum( rad.coeff[i, :] * rad.phi( (val .- rad.x[i]) ./rad.scale_factor) for i = 1:n)\n    for k = 1:num_poly_terms\n        @views approx += rad.coeff[n+k, :] .* multivar_poly_basis(val, k-1, d, q)\n    end\n    return approx\nend\n\n_scaled_chebyshev(x, k, lb, ub) = cos(k*acos(-1 + 2*(x-lb)/(ub-lb)))\n_center_bounds(x::Tuple, lb, ub) = ntuple(i -> (ub[i] - lb[i])/2, length(x))\n_center_bounds(x, lb, ub) = (ub .- lb) ./ 2\n\n\"\"\"\n    add_point!(rad::RadialBasis,new_x,new_y)\n\nAdd new samples x and y and update the coefficients. Return the new object radial.\n\"\"\"\nfunction add_point!(rad::RadialBasis,new_x,new_y)\n    if (length(new_x) == 1 && length(new_x[1]) == 1) || ( length(new_x) > 1 && length(new_x[1]) == 1 && length(rad.lb)>1)\n        push!(rad.x,new_x)\n        push!(rad.y,new_y)\n    else\n        append!(rad.x,new_x)\n        append!(rad.y,new_y)\n    end\n    rad.coeff = _calc_coeffs(rad.x,rad.y,rad.lb,rad.ub,rad.phi,rad.dim_poly, rad.scale_factor, rad.sparse)\n    nothing\nend\n", "meta": {"hexsha": "ffed21930a4fca8769437a90737d2416ab71aaf5", "size": 6257, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Radials.jl", "max_stars_repo_name": "fredcallaway/Surrogates.jl", "max_stars_repo_head_hexsha": "413df763b7f6e715306b9308fbf9f9fe7200e2cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-12T15:06:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T15:06:38.000Z", "max_issues_repo_path": "src/Radials.jl", "max_issues_repo_name": "fredcallaway/Surrogates.jl", "max_issues_repo_head_hexsha": "413df763b7f6e715306b9308fbf9f9fe7200e2cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-06-15T04:10:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-15T08:16:09.000Z", "max_forks_repo_path": "src/Radials.jl", "max_forks_repo_name": "MLH-Fellowship/Surrogates.jl", "max_forks_repo_head_hexsha": "faf82d50b4e037d1842056577bf757552258b90c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-14T15:32:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T15:32:55.000Z", "avg_line_length": 27.685840708, "max_line_length": 124, "alphanum_fraction": 0.6140322838, "num_tokens": 2044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7677740432623092}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.0\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 430d5134-92af-11eb-1fcc-d71f5216d62a\n#Set up the working environment\nbegin\n\tusing Pkg\n\tPkg.activate(\"..\")\n\tusing Plots, PlutoUI,LaTeXStrings, DifferentialEquations\nend\n\n# ╔═╡ 5adc7e34-92af-11eb-2cfe-67899a4a0291\nmd\"\"\"\n## Attempting a more realistic model\n\nNext, we'll try to make the model more realistic by including **reinfection**, **vaccination** and **mortalitiy**.\n\n##### Mortality\nWe'll only consider deaths of infected people at a mortality rate $m$: $$I \\xrightarrow{m} D$$\n\n##### Vaccination & Reinfection\nTo account for vaccination, we'll assume that\n1. The rate of infection is different for vaccinated people $V$ and susceptible people $S$, represented by a *vaccination immunity factor*, $i_v < 1$\n\n$$S \\xrightarrow{r_s} I \\xleftarrow{r_s \\cdot i_v} V$$\n\n2. Likewise, susceptible people $S$ and recovered people $R$ become infected at different rates, represented by an *recovered immunity factor*, $i_r < 1$ that lowers the infection risk\n\n$$S \\xrightarrow{r_s} I \\xleftarrow{r_s \\cdot i_r} R$$\n\n3. We assume that recovered people $R$ and susceptible people $S$ are vaccinated at the same rate $v$ \n\n$$S \\xrightarrow{v} V \\xleftarrow{v} R$$\n\nTaken together, this yields the following set of differential equations:\n\n$$\\begin{align}\n\t\\frac{dS}{dt} = -rSI -vS\\\\\n\t\\frac{dV}{dt} = vS + vR - i_v r VI\\\\\n\t\\frac{dD}{dt} = mI\\\\\n\t\\frac{dR}{dt} = aI - i_r rRI - vR\\\\\n\t\\frac{dI}{dt} = rSI + i_r rRI + i_v r VI - mI - aI\n\\end{align}$$\n\n\"\"\"\n\n# ╔═╡ 7a19b238-92af-11eb-30fd-b189d06a0882\nmd\"\"\" ## Simulation\n*Change the sliders to adjust the corresponding values*:\n\n| parameter                   | value                     |\n|-----------------------------|---------------------------|\n| transmission rate $r$       | $(@bind r2 Slider(0:0.005:1, default=0.125, show_value=true)) |\n| recovery rate $a$           | $(@bind a2 Slider(0:0.001:0.25, default=0.1, show_value=true))|\n| rate of vaccination $v$     | $(@bind v2 Slider(0:0.0001:0.01, default=0.0008, show_value=true)) |\n| mortality $m$               | $(@bind m2 Slider(0:0.0001:0.05, default=0.0006, show_value=true)) |\n| % immunity recovered        | $(@bind ir Slider(0:1.0:100.0, default=60, show_value=true)) |\n| % immunity vaccinated       | $(@bind iv Slider(0:1.0:100.0, default=90, show_value=true)) |\n|  $I(0)$                     | $(@bind I02 Slider(0.0001:0.001:0.1, default=0.004, show_value=true)) |\n|  $R(0)$                     | $(@bind R02 Slider(0:0.001:0.1, default=0.055,show_value=true)) |\n| $V(0)$                      | $(@bind V02 Slider(0:0.001:0.1, default=0.048,show_value=true)) |\n| $D(0)$                      | $(@bind D02 Slider(0:0.001:0.1, default=0.001,show_value=true)) |\n| timespan $t_{max}$          | $(@bind tmax2 Slider(10.0:10.0:2000.0, default=100.0,show_value=true)) days | \n| zoom y-axis                 | $(@bind ymax2 Slider(0.001:0.001:1.0, default=1.0,show_value=true)) |\n| Population size             | $(@bind popsize NumberField(500000:10000000000, default=9044650)) |\n\"\"\"\n\n# ╔═╡ 8f867f9a-92af-11eb-3671-43904aa74d8b\nfunction getres(solution, i, t, p)\n\tv = solution(t)[i]*p\n\treturn round(maximum([0.0 v]))\nend\n\n# ╔═╡ 96d8a5c2-92af-11eb-1d3f-9bdd035eafec\n#S, I, R, V, D\nfunction sirvd!(du,u,p,t)\n\tdu[1] = -u[1] * ( p[1] * u[2] + p[3])\n\tdu[2] = u[2] * (p[1] * (u[1] + p[5] * u[4] + p[4] * u[3]) - p[6] - p[2])\n\tdu[3] = p[2] * u[2] - u[3] * ( p[1] * p[4] *  u[2] + p[3])\n\tdu[4] = p[3] * (u[1] + u[3]) - u[4] * u[2] * p[1] * p[5]\n\tdu[5] = p[6] * u[2]\nend\n\n# ╔═╡ 9c0dfe82-92af-11eb-3192-49c2deac6e9b\np2 = [r2, a2, v2, (100 - ir)/100, (100 - iv)/100, m2]\n\n# ╔═╡ a1e4ca5e-92af-11eb-1c40-410a8d3abaca\nu02 = [1-I02-R02-V02-D02, I02, R02, V02, D02]\n\n# ╔═╡ ada6253e-92af-11eb-0e32-d9760ab88271\ntspan2 = (0.0, 2000)\n\n# ╔═╡ b08f47b2-92af-11eb-367b-979567aebb4d\nprob2 = ODEProblem(sirvd!,u02,tspan2,p2)\n\n# ╔═╡ 88b411f0-92af-11eb-2abf-151b2bfb313b\nbegin\n\tsol2 = solve(prob2, dt=1.0, dense = true)\n\tinfected = sol2[2,:]*popsize\n\tdead = infected + sol2[5,:]*popsize\n\trecovered = dead + sol2[3,:]*popsize\n\tvaccinated = recovered + sol2[4,:]*popsize\n\tsusceptible = vaccinated + sol2[1,:]*popsize\n\ticu = infected*0.015\n\ticu_cap = [1000 for t in sol2.t]\n\t\n\t\n\tsim_stackarea = plot(sol2.t, [susceptible, vaccinated, recovered, dead, infected, icu], \n\t\t\t\tfill = true, \n\t\t\t\tcolor = [\"gray89\" \"skyblue3\" \"paleturquoise3\" \"gray39\" \"lightcoral\" \"maroon\"], \n\t\t\t\tfillalpha = 1, \n\t\t\t\tlabel = [\"S(t)\" \"V(t)\" \"R(t)\" \"D(t)\" \"I(t)\" L\"$I(t)_{icu}$\"], \n\t\t\t\txlabel = \"t / days\", \n\t\t\t\ttitle = \"Timecourse (stacked area)\", \n\t\t\t\txlims = (0, tmax2), \n\t\t\t\tylims = (0, ymax2*popsize))\n\t\n\t\n\t\n\tsim_timecourse = plot(sol2,\n\t\t\t\tcolor = [\"gray89\" \"lightcoral\" \"paleturquoise3\" \"skyblue3\" \"gray39\"], \n\t\t\t\tlabel = [\"S(t)\" \"I(t)\" \"R(t)\" \"V(t)\" \"D(t)\"], \n\t\t\t\txlabel = \"t / days\", \n\t\t\t\ttitle = \"Timecourse\", \n\t\t\t\txlims = (0, tmax2), \n\t\t\t\tylims = (0, ymax2))\n\t\n\tsim_rate_tc = plot(0:tmax2, sol2(0:tmax2, Val{1}, idxs=2),\n\t\t\t\tcolor = [\"lightcoral\"],\n\t\t\t\tlabel = [L\"\\frac{dI}{dt}\"],\n\t\t\t\txlabel = \"t / days\", \n\t\t\t\ttitle = \"New Infections\",\n\t\t\t\txlims = (0, tmax2))\n\t\n\ttimecourses = plot(sim_timecourse, sim_rate_tc, layout = (2,1))\n\t\n\tplot(sim_stackarea, timecourses, layout = (1, 2),fontfamily=\"Computer Modern\")\nend\n\n# ╔═╡ 7ec0712a-92af-11eb-2144-15d33af27c3d\nmd\"\"\"\n| t (days) | I(t)                               | R(t)                               | V(t)                               | D(t)                               |\n|----------|------------------------------------|------------------------------------|------------------------------------|------------------------------------|\n| 0        | $(getres(sol2, 2, 0, popsize))     | $(getres(sol2, 3, 0, popsize))     | $(getres(sol2, 4, 0, popsize))     | $(getres(sol2, 5, 0, popsize))     |\n| $tmax2   | $(getres(sol2, 2, tmax2, popsize)) | $(getres(sol2, 3, tmax2, popsize)) | $(getres(sol2, 4, tmax2, popsize)) | $(getres(sol2, 5, tmax2, popsize)) |\n\nBase reprodution rate = $(round((r2*(1-I02-R02-V02-D02)/a2), sigdigits = 3)), \nInfectious period = $(round(1/a2, sigdigits = 3))\n\n\"\"\"\n\n# ╔═╡ 230527fa-92b3-11eb-308f-ffab3777029c\nsol2(0:tmax2, Val{1}, idxs=2)\n\n# ╔═╡ Cell order:\n# ╟─430d5134-92af-11eb-1fcc-d71f5216d62a\n# ╟─5adc7e34-92af-11eb-2cfe-67899a4a0291\n# ╟─7a19b238-92af-11eb-30fd-b189d06a0882\n# ╟─7ec0712a-92af-11eb-2144-15d33af27c3d\n# ╟─88b411f0-92af-11eb-2abf-151b2bfb313b\n# ╟─230527fa-92b3-11eb-308f-ffab3777029c\n# ╟─8f867f9a-92af-11eb-3671-43904aa74d8b\n# ╟─96d8a5c2-92af-11eb-1d3f-9bdd035eafec\n# ╟─9c0dfe82-92af-11eb-3192-49c2deac6e9b\n# ╟─a1e4ca5e-92af-11eb-1c40-410a8d3abaca\n# ╟─ada6253e-92af-11eb-0e32-d9760ab88271\n# ╟─b08f47b2-92af-11eb-367b-979567aebb4d\n", "meta": {"hexsha": "db81845da6ca3f60de0548767e09567f732e0789", "size": 7042, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/04_modelling-sirvd.jl", "max_stars_repo_name": "el-uhu/intro-to-modelling", "max_stars_repo_head_hexsha": "b86d558619c208184fc813e01c39de3d3b2e3f47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/04_modelling-sirvd.jl", "max_issues_repo_name": "el-uhu/intro-to-modelling", "max_issues_repo_head_hexsha": "b86d558619c208184fc813e01c39de3d3b2e3f47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/04_modelling-sirvd.jl", "max_forks_repo_name": "el-uhu/intro-to-modelling", "max_forks_repo_head_hexsha": "b86d558619c208184fc813e01c39de3d3b2e3f47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1222222222, "max_line_length": 195, "alphanum_fraction": 0.5948594149, "num_tokens": 2825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.7677712115367403}}
{"text": "__precompile__()\n\nmodule Napier\n\nexport loge, logn, ln\n\nfunction loge(n::Real, li::Real, ls::Real)\n  if abs(li-ls) <= 0.000001\n    (li+ls)/2.0\n  elseif (exp(li)-n)*(exp((li+ls)/2.0)-n) < 0\n    loge(n,li,(li+ls)/2.0)\n  else\n    loge(n,(li+ls)/2.0,ls)\n  end\nend\n\nfunction logn(n::Real)\n  if n <= 0\n    throw(DomainError())\n  elseif n < 1\n    loge(n, 0, -n-80)\n  elseif n == 1\n    0\n  else\n    loge(n, 0, n)\n  end\nend\n\nconst ln = logn\n\n\nend # module\n", "meta": {"hexsha": "75edee33898db0a8ab88321dbd2e3561007054dd", "size": 447, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Napier.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Napier.jl-aeb4490e-d914-5f40-aac0-ef8e9431dfb2", "max_stars_repo_head_hexsha": "0df79c4abbaad09357468b4da1fae13706f96820", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Napier.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Napier.jl-aeb4490e-d914-5f40-aac0-ef8e9431dfb2", "max_issues_repo_head_hexsha": "0df79c4abbaad09357468b4da1fae13706f96820", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Napier.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Napier.jl-aeb4490e-d914-5f40-aac0-ef8e9431dfb2", "max_forks_repo_head_hexsha": "0df79c4abbaad09357468b4da1fae13706f96820", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.5454545455, "max_line_length": 45, "alphanum_fraction": 0.5637583893, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478306, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7677227253404311}}
{"text": "function VorticityBoundaryConditions!(ω,ψ,Δx,Δy,un,us,ve,vw)\n  ω[:,end] .= 2*((ψ[:,end]  - ψ[:,end-1] )/(Δx^2) .- ve/Δx)\n  ω[:,1] .= 2*((ψ[:,1]  - ψ[:,2]   )/(Δx^2) .- vw/Δx)\n  ω[end,:] .= 2*((ψ[end,:]  - ψ[end-1,:] )/(Δy^2) .+ us/Δy)\n  ω[1,:] .= 2*((ψ[1,:]  - ψ[2,:]   )/(Δy^2) .+ un/Δy)\nend\nfunction GaussSiedel!(ϕ,Ap,An,As,Ae,Aw,Rp,res; λ=1, maxiter = 1000)\n  normRes = 1\n  k = 0\n  Ny,Nx = size(ϕ)\n  while normRes >= 1e-8 && k < maxiter\n    k += 1\n    for i in 2:Ny-1\n      for j in 2:Nx-1\n        ϕP = ϕ[i,j]\n        ϕE = ϕ[i+0,j+1]\n        ϕW = ϕ[i+0,j-1]\n        ϕN = ϕ[i-1,j+0]\n        ϕS = ϕ[i+1,j+0]\n        res[i,j] = Rp[i,j] - (Ap*ϕP\n          + An*ϕN\n          + As*ϕS\n          + Ae*ϕE\n          + Aw*ϕW)\n        Δϕ = res[i,j]/Ap\n        ϕ[i,j] = λ*(ϕ[i,j] + Δϕ) + (1-λ)*ϕ[i,j]\n      end\n    end\n    normRes = norm(res)\n  end\n  return k\nend\nfunction LinearSolve!(A,x,b)\n  # Solves the equation Ax = b assuming zero Dirichlet BCs everywhere\n  Ny,Nx = size(b)\n  Ny,Nx = Ny-2, Nx-2\n  x_int = x[2:end-1,2:end-1]\n  b_int = b[2:end-1,2:end-1]\n  b_vec = reshape(b_int,Ny*Nx)\n  # x_int = A\\b_vec\n  x_vec = reshape(x_int,Ny*Nx)\n  cg!(x_vec,A,b_vec, log = true)\n  x[2:end-1,2:end-1] .= reshape(x_int,(Ny,Nx))\nend\nfunction BuildPoissonMatrix(Ny,Nx,Δx,Δy)\n  # This function returns a (Ny*Nx) × (Ny*Nx) matrix in the form of\n  # a sparse array, corresponding to the discrete 2D Laplacian operator.\n  Ny = Ny-2\n  Nx = Nx-2\n\n  Isx = [1:Ny; 1:Ny-1; 2:Ny]\n  Jsx = [1:Ny; 2:Ny; 1:Ny-1]\n\n  Isy = [1:Nx; 1:Nx-1; 2:Nx]\n  Jsy = [1:Nx; 2:Nx; 1:Nx-1]\n\n  Vsx = [fill(-2,Ny); fill(1, 2Ny-2)]\n  Vsy = [fill(-2,Nx); fill(1, 2Nx-2)]\n  D²x = sparse(Isx, Jsx, Vsx)\n  D²y = sparse(Isy, Jsy, Vsy)\n  # D_xx = 1/(Δx^2) .* kron(sparse(I,Nx,Nx), D²x)\n  # D_yy = 1/(Δy^2) .* kron(D²y, sparse(I,Ny,Ny))\n  D_yy = 1/(Δy^2) .* kron(sparse(I,Nx,Nx), D²x)\n  D_xx = 1/(Δx^2) .* kron(D²y, sparse(I,Ny,Ny))\n  Lap = D_xx + D_yy\nend\nfunction BuildAdvectionDiffusionCoefficients(Re,Δt,Δx,Δy)\n  # Time-derivative\n  ap = 1/Δt\n  # Diffusion\n  ap += 2/(Re*Δx^2) + 2/(Re*Δy^2)\n  an = -1/(Re*Δy^2)\n  aw = -1/(Re*Δx^2)\n  as = -1/(Re*Δy^2)\n  ae = -1/(Re*Δx^2)\n  return ap,an,as,ae,aw\nend\nfunction BuildAdvectionDiffusionRHS!(Rp,ϕ,ψ,Δt,Δx,Δy,Ny,Nx,Re)\n  # Time derivative\n  Rp .= ϕ/Δt\n\n  # Diffusion term (fully implicit)\n\n  # Convection term\n  for i in 2:Ny-1\n    for j in 2:Nx-1\n      ϕE = ϕ[i+0,j+1]; ϕW = ϕ[i+0,j-1]; ϕN = ϕ[i-1,j+0]; ϕS = ϕ[i+1,j+0]\n      ψE = ψ[i+0,j+1]; ψW = ψ[i+0,j-1]; ψN = ψ[i-1,j+0]; ψS = ψ[i+1,j+0]\n\n      u    = (ψN - ψS)/(2Δy); v    = -(ψE - ψW)/(2Δx)\n      ∂ϕ∂y = (ϕN - ϕS)/(2Δy); ∂ϕ∂x = (ϕE - ϕW)/(2Δx)\n\n      Rp[i,j] += - (u*∂ϕ∂x + v*∂ϕ∂y)\n      # Rp[i,j] += (ψE - ψW)/(2Δx) * (ϕN - ϕS)/(2Δy) -\n      #            (ψN - ψS)/(2Δy) * (ϕE - ϕW)/(2Δx)\n    end\n  end\nend\n\nfunction RecordHistory!(ϕ,ϕ_old,ϕ_hist)\n  Δϕ = norm(ϕ - ϕ_old)\n  ϕ_old .= ϕ\n  push!(ϕ_hist,Δϕ)\n  return(Δϕ)\nend\n\n", "meta": {"hexsha": "db8f05ace18798b0d51d1bf17ed16d10f4daf81b", "size": 2867, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "Emadmasroor/SimpleNavierStokes.jl", "max_stars_repo_head_hexsha": "9ded56a19908f5805d67c24c9baa585740d96112", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-30T17:16:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T17:16:24.000Z", "max_issues_repo_path": "src/functions.jl", "max_issues_repo_name": "gsagoo/SimpleNavierStokes.jl", "max_issues_repo_head_hexsha": "9ded56a19908f5805d67c24c9baa585740d96112", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions.jl", "max_forks_repo_name": "gsagoo/SimpleNavierStokes.jl", "max_forks_repo_head_hexsha": "9ded56a19908f5805d67c24c9baa585740d96112", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-30T17:12:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T17:12:59.000Z", "avg_line_length": 26.7943925234, "max_line_length": 72, "alphanum_fraction": 0.5092431113, "num_tokens": 1544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222396, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7677227239338835}}
{"text": "# Linear mean function\n\n@doc \"\"\"\n# Description\nConstructor for the Linear mean function\n\nm(x) = xᵀβ\n# Arguments:\n* `β::Vector{Float64}`: One coefficient for each dimension\n\"\"\" ->\ntype MeanLin <: Mean\n    β::Vector{Float64}\n    dim::Int\n    MeanLin(β::Vector{Float64}) = new(β, length(β))\nend\n    \nmean(mLin::MeanLin,x::Matrix{Float64}) =  x'mLin.β\n\nget_params(mLin::MeanLin) = mLin.β\nget_param_names(::MeanLin) = [:β]\nnum_params(mLin::MeanLin) = mLin.dim\n\nfunction set_params!(mLin::MeanLin, hyp::Vector{Float64})\n    length(hyp) == mLin.dim || throw(ArgumentError(\"Linear mean function only has $(mLin.dim) parameters\"))\n    mLin.β = hyp\nend\n\nfunction grad_mean(mLin::MeanLin, x::Vector{Float64})\n    dM_theta = x\n    return dM_theta\nend\n", "meta": {"hexsha": "923ac3ff4978f0b5eeb635049503792e553c4adf", "size": 739, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/means/mLin.jl", "max_stars_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/means/mLin.jl", "max_issues_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/means/mLin.jl", "max_forks_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.09375, "max_line_length": 107, "alphanum_fraction": 0.6860622463, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158416, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7677227204518353}}
{"text": "module Day25\n\nexport day25\n\nfunction powmod(a::T,n::T,m::T) where T<:Integer\n    q = a\n    product = T(1)\n    while n > T(0)\n        n,r = divrem(n,2)\n        if r == T(1)\n            product = mod(product * q, m)\n        end\n        q = mod(q^2, m)\n    end\n    return product\nend\n\nfunction invmod(a::T,m::T) where T<:Integer\n    t = gcdx(a,m)\n    if t[1] != T(1)\n        return error(\"No inverse exists!\")\n    end\n    return mod(t[2],m)\nend\n\nfunction dlog(g, y, p)\n    q = Int(floor(sqrt(p)))\n    table = Dict{Int,Int}([1 => 0])\n    gq = powmod(g,q,p)\n    current_power = gq\n    for i in 1:div(p,q)\n        table[current_power] = i\n        current_power = mod(current_power*gq, p)\n    end\n    ginv = invmod(g,p)\n    current_key = y\n    for j in 0:q-1\n        if haskey(table, current_key)\n            return table[current_key] * q + j\n        end\n        current_key = mod(current_key*ginv, p)\n    end\nend\n\nfunction day25()\n    card = 10604480\n    door = 4126658\n    p = 20201227\n    g = 7\n\n    b = dlog(g, door, p)\n    powmod(card,b,p)\nend\n\nend\n", "meta": {"hexsha": "033ec7c394cefb838326a101c63ccfb6be884ed8", "size": 1047, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/day25/day25.jl", "max_stars_repo_name": "tgaref/AdventOfCode2020", "max_stars_repo_head_hexsha": "7ec5e29e36e7670e6d4b43eb537fb181ed677256", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/day25/day25.jl", "max_issues_repo_name": "tgaref/AdventOfCode2020", "max_issues_repo_head_hexsha": "7ec5e29e36e7670e6d4b43eb537fb181ed677256", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/day25/day25.jl", "max_forks_repo_name": "tgaref/AdventOfCode2020", "max_forks_repo_head_hexsha": "7ec5e29e36e7670e6d4b43eb537fb181ed677256", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6964285714, "max_line_length": 48, "alphanum_fraction": 0.5339063992, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551505674444, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7676948182742196}}
{"text": "export yin\n\n\"\"\"\n    yin(sig::Vector, sr::Int; w_len::Int = 512, f_step::Int = 256, f0_min = 100, f0_max = 500,\n        harmonic_threshold = 0.1, \n        difference_function::Function = difference_function_original, kwargs...) -> F0s, frame_times\n\nEstimates the fundamental frequency (F0) of the signal `sig` using the YIN algorithm [^1].\nThe signal `sig` is a vector of points uniformly sampled at a rate `sr`.  \n\n\n## Keyword arguments\n* `w_len`: size of the analysis window [samples == number of points]\n* `f_step`: size of the lag between two consecutive frames [samples == number of points]\n* `f0_min`: Minimum fundamental frequency that can be detected [linear frequency]\n* `f0_max`: Maximum fundamental frequency that can be detected [linear frequency]\n* `harmonic_threshold`: Threshold of detection. The algorithm returns the first minimum of\n  the CMNDF function below this threshold.\n* `diffference_function`: The difference function to be used (by default\n  [`differenceFunction_original`](@ref)).\n\n## Description\nThe YIN algorithm [^CheveigneYIN2002] estimates the signal's fundamental frequency `F0` by basically\nlooking for the period `τ0`  which minimizes the signal's autocorrelation. This\nautocorrelation is calculated for signal segments (frames), composed of two windows of\nlength `w_len`. Each window is separated by a distance `τ`, and the idea is that the\ndistance which minimizes the pairwise difference between each window is considered to be the\nfundamental period `τ0` of that frame.\n\nMore precisely, the algorithm first computes the cumulative mean normalized difference\nfunction (MNDF) between two windows of a frame for several candidate periods `τ` ranging\nfrom `τ_min=sr/f0_max` to `τ_max=sr/f0_min`. The MNDF is defined as \n```math\nd_t^\\\\prime(\\\\tau) = \\\\begin{cases}\n        1 & \\\\text{if} ~ \\\\tau=0 \\\\\\\\\n        d_t(\\\\tau)/\\\\left[{(\\\\frac 1 \\\\tau) \\\\sum_{j=1}^{\\\\tau} d_{t}(j)}\\\\right] & \\\\text{otherwise}\n        \\\\end{cases}\n```\nwhere `d_t` is the difference function:\n```math\nd_t(\\\\tau) = \\\\sum_{j=1}^W (x_j - x_{j+\\\\tau})^2\n```\n\nIt then refines the local minima of the MNDF using parabolic (quadratic) interpolation. This\nis done by taking each minima, along with their first neighbor points, and finding the\nminimum of the corresponding interpolated parabola. The MNDF minima are substituted by the\ninterpolation minima. Finally, the algorithm chooses the minimum with the smallest period\nand with a corresponding MNDF below the `harmonic threshold`. If this doesn't exist, it\nchooses the period corresponding to the global minimum. It repeats this for frames starting\nat the first signal point, and separated by a distance `f_step` (frames can overlap), and\nreturns the vector of frequencies `F0=sr/τ0` for each frame, along with the start times of\neach frame.\n\nAs a note, the physical unit of the frequency is 1/[time], where [time] is decided by the\nsampling rate `sr`. If, for instance, the sampling rate is over seconds, then the frequency\nis in Hertz.\n\n[^CheveigneYIN2002]: De Cheveigné, A., & Kawahara, H. (2002). YIN, a fundamental frequency estimator for\nspeech and music. The Journal of the Acoustical Society of America, 111(4), 1917-1930.\n\"\"\"\nfunction yin(sig::Vector, sr::Int; w_len::Int = 512, f_step::Int = 256, f0_min = 100, \n    f0_max = 500, harmonic_threshold = 0.1, \n    difference_function::Function = difference_function_original, kwargs...)\n\n    τ_min = floor(Int64, sr / f0_max)\n    τ_max = floor(Int64, sr / f0_min)\n\n    frame_times = range(1, length(sig) - w_len - τ_max, step=f_step)  # time values for start of  each analysis window\n    # times = frame_times ./ eltype(sig)(sr)  \n\n    F0s = zeros(Float64, length(frame_times))\n\n    for (i, t) in enumerate(frame_times)\n        frame = sig[ (t) : (t + τ_max+ w_len-1) ]\n        df = difference_function(frame, w_len, τ_max)\n        cmdf = cumulative_mean_normalized_difference_function(df)\n        y_refined, τ_refined, τ_indices = refine_local_minima(cmdf)\n        idx_localminimum = absolute_threshold(y_refined, τ_min, τ_max, harmonic_threshold)\n        τ0 = τ_refined[idx_localminimum]\n        F0s[i] = sr / τ0\n\n    end\n    return  F0s, frame_times\nend\n\n\"\"\"\n    difference_function_original(x, W, τmax) -> df\nComputes the difference function of `x`. `W` is the window size, and `τmax` is the maximum\n    period. This corresponds to equation (6) in [^1]:\n```math\nd_t(\\\\tau) = \\\\sum_{j=1}^W (x_j - x_{j+\\\\tau})^2\n```\n\"\"\"\nfunction difference_function_original(x, W, τmax)\n    df = zeros(eltype(x), τmax+1) #df corresponds to τ values from 0 to τ_max\n    for τ in 1:τmax\n        for j in 1:W\n            df[τ+1] += (x[j] - x[j + τ]) ^ 2 \n        end\n    end\n    return df\nend\n\n\"\"\"\nCompute cumulative mean normalized difference function (CMND), starting from the difference\n    function `df`. This corresponds to equation (8) in [1]\n\"\"\"\nfunction cumulative_mean_normalized_difference_function(df)\n    N = length(df)\n    cmndf = df[2:end] .* range(1, N-1, step=1) ./ Float64.(cumsum(df[2:end]))\n    return [1.0; cmndf]\nend\n\n\"\"\"\nReturns the refined local minima of `y`, along with their refined `x` value and the\ncorresponding indices.  For each minimum, by the minimum of the parabola obtained by\ninterpolated the minimum with its first neighbors. Also returns the indices of `y`\n(`x_nominal`) and the value `x` corresponding to each minima.\n\"\"\"\nfunction refine_local_minima(y)\n    x_nominal = 0:length(y)-1 #nominal τ values: 0 to τ_max (cf. difference_function)\n    idxs_local_minima = local_minima(y)\n    if isempty(idxs_local_minima)\n         @warn \"No local minima found for the cumulative mean difference function. Adjusting\n         the values of the minimum and maximum frequencies may fix this.\"\n    end\n    xv, yv = parabolic_interpolation(y, idxs_local_minima) #xv,yv are correction for the local minima\n    y_locmin_refined = yv\n    x_locmin_real= x_nominal[idxs_local_minima] .+ xv\n    x_locmin_nominal = x_nominal[idxs_local_minima]\n    return y_locmin_refined, x_locmin_real, x_locmin_nominal\nend\n\n\"\"\"\nApplies the threshold step described in [^1]. It returns index (period) corresponding to the\nfirst minimum below the `harmonic_threshod`. If that doesn't exist, it regurns the index of the\nglobal minimum.\n\"\"\"\nfunction absolute_threshold(localminima, τ_min, τ_max, harmonic_threshold=0.1)\n    for (idx, localminimum) in enumerate(localminima)\n        if localminimum ≤ harmonic_threshold\n            return idx\n        end\n    end\n    return argmin(localminima)  \nend\n\n\"\"\"\nCalculates the parabolic (quadratic) interpolation for all the indixes of `y` given in\nidxs_interpolate, and returns the coordinates of the respective parabola's minimum.\nAssumes space all adjacent x values of `y` is 1. \n\"\"\"\nfunction parabolic_interpolation(y, idxs_interpolate)\n    #separate x into triplets [x1,x2,x3]. \n    x1 = @view y[idxs_interpolate .- 1]\n    x2 = @view y[idxs_interpolate]\n    x3 = @view y[idxs_interpolate .+ 1]\n    #calculate the vertix coordinates (xv, yv) for each triplet\n    a = @. (x1 - 2x2 + x3)/2 \n    b = @. (x3 - x1) / 2\n    xv = @. -b/2a\n    yv = @. x2 - (b^2 /4a)\n    return xv, yv\nend\n\n\"\"\"\nQuickly written version for finding local minima by comparing first neighbors only.\n#TODO: More detailed implementations available in Peaks.jl or Iamges.jl, maybe this should\nbe replaced by them.\n\"\"\"\nfunction local_minima(x)\n    x1 = @view x[1:end - 2]\n    x2 = @view x[2:end - 1]\n    x3 = @view x[3:end]\n    collect(1:length(x2))[x1 .> x2 .< x3] .+ 1\nend", "meta": {"hexsha": "1a7b29b5e903ac6f6cdf1d6406c59c064c9dd900", "size": 7485, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/period_return/yin.jl", "max_stars_repo_name": "onkyo14taro/ChaosTools.jl", "max_stars_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/period_return/yin.jl", "max_issues_repo_name": "onkyo14taro/ChaosTools.jl", "max_issues_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/period_return/yin.jl", "max_forks_repo_name": "onkyo14taro/ChaosTools.jl", "max_forks_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.5284090909, "max_line_length": 118, "alphanum_fraction": 0.7108884436, "num_tokens": 2121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.8152324983301567, "lm_q1q2_score": 0.7676670689165684}}
{"text": "module SphericalHarmonics_Mod\r\n    using LegendrePolynomials\r\n\r\n    export Calc_SphericalHarmonics\r\n\r\n    function Calc_SphericalHarmonics(l::Int64,m::Int64,n::Int64 = 50)\r\n\r\n        #Create meshgrid\r\n        theta = range(0,pi,length=n)' .* ones(n,1)\r\n        phi = range(0,2*pi,length=n) .* ones(1,n)\r\n\r\n        #Calculate spherical harmonics\r\n        Y = harmonicY(l,m,theta,phi,\"real\")\r\n\r\n        # Transform from spherical to cartesian coordinates\r\n        x,y,z = sph2cart(phi, pi/2 .- theta, abs.(Y))\r\n\r\n        return x,y,z,Y\r\n    end\r\n\r\n    function harmonicY(l::Int64,m::Int64,th::Matrix{Float64},phi::Matrix{Float64},type::String)\r\n        # Calculate the spherical harmonic Ylm\r\n        # Translation of: Javier Montalt Tordera (2022). Spherical Harmonics (https://github.com/jmontalt/harmonicY/releases/tag/v2.0.1), GitHub. Retrieved January 19, 2022. \r\n\r\n        @assert abs(m) <= l \"abs(m) > l!\"\r\n\r\n        isoddm = isodd(m)\r\n        isnegm = m < 0\r\n\r\n        # Quantum mechanical norm, se Wiki. \r\n        # Factorials can overflow Float64 for l > 19, hence \"big\". \r\n        C = (-1)^m*sqrt((2*l+1)/(4*pi)*factorial(big(l-m))/factorial(big(l+m)))\r\n\r\n        C = Float64(C)\r\n\r\n        m = abs(m)\r\n        P = Plm.(cos.(th),l,m)\r\n\r\n        if type==\"real\"\r\n            if isnegm\r\n                E = sin.(m*phi)\r\n            else\r\n                E = cos.(m*phi)\r\n            end\r\n        else\r\n            E = exp.(1im*m*phi)\r\n            if isnegm\r\n                conj!(E)\r\n                if isoddm\r\n                    E = -E\r\n                end\r\n            end\r\n        end\r\n\r\n        # Surface spherical harmonics\r\n        Y = C * P .* E\r\n\r\n        return Y\r\n    end\r\n\r\n    function sph2cart(az::Matrix{Float64},el::Matrix{Float64},r::Matrix{Float64})\r\n        #Spherical to cartesian\r\n\r\n        z = r .* sin.(el)\r\n        rcoselev = r .* cos.(el)\r\n        x = rcoselev .* cos.(az)\r\n        y = rcoselev .* sin.(az)\r\n\r\n        return x,y,z\r\n    end\r\nend", "meta": {"hexsha": "c1a5576fa7c1d2ac7a0db224e41e19a1388b87b7", "size": 1975, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SphericalHarmonics.jl", "max_stars_repo_name": "philipbergander/SphericalHarmonics", "max_stars_repo_head_hexsha": "32c367922554de4ea168643534ffa661bd1bdb5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2022-01-19T20:18:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T22:37:52.000Z", "max_issues_repo_path": "SphericalHarmonics.jl", "max_issues_repo_name": "philipbergander/SphericalHarmonics", "max_issues_repo_head_hexsha": "32c367922554de4ea168643534ffa661bd1bdb5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SphericalHarmonics.jl", "max_forks_repo_name": "philipbergander/SphericalHarmonics", "max_forks_repo_head_hexsha": "32c367922554de4ea168643534ffa661bd1bdb5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8169014085, "max_line_length": 175, "alphanum_fraction": 0.5083544304, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7676670642441988}}
{"text": "using ModelingToolkit\nusing OrdinaryDiffEq\n\n\n\n\"\"\"\nsolves STG calcium model (Liu 1998)\n\nThe log(3000.0/Ca) in the algorithm doesn't play nicely with Zygote. Don't know why. I've maxed it with zero to make it work.\n\nAll neurons have following channels (with some conductances at 0:)\nNaV\nCaT\nCaS\nH\nKd\nLeak\n\"\"\"\n\n\n\nfunction  CalciumNeuron(input)\n    \n    @parameters t\n    D = Differential(t)\n\n\n    @parameters eNa eh eK eleak tauCa gNabar gCaSbar gCaTbar gKabar gKCabar gKdrbar ghbar gleak\n\n    paramvars = [eNa, eh, eK, eleak, tauCa, gNabar, gCaSbar, gCaTbar, gKabar, gKCabar, gKdrbar, ghbar, gleak]\n\n    @variables V(t) Ca(t) mNa(t) hNa(t) mCaS(t) hCaS(t) mCaT(t) hCaT(t) mIh(t) mKa(t) hKa(t) mKCa(t) mKdr(t) \n    statevars = [V, Ca, mNa, hNa, mCaS, hCaS, mCaT, hCaT, mIh, mKa, hKa, mKCa, mKdr]\n    \n    # calcium reversal potential\n    # eCa = (500.0)*(8.6174e-5)*(283.15)*(log(max((3000.0/Ca),1e-5)))\n    eCa = (500.0)*(8.6174e-5)*(283.15)*(log((3000.0/Ca)))\n\n\n\n    # currents\n    INa=  gNabar*mNa^3*hNa*(eNa - V)\n    ICaS= gCaSbar*mCaS^3*hCaS*(eCa - V)\n    ICaT= gCaTbar*mCaT^3*hCaT*(eCa - V)\n    Ih= ghbar*mIh*(eh - V)\n    IKa= gKabar*mKa^3*hKa*(eK - V)\n    IKCa=  gKCabar*mKCa^4*(eK - V)\n    IKdr=  gKdrbar*mKdr^4*(eK - V)\n    Ileak= gleak*(eleak - V)\n\n\n    # calcium\n    Ca_inf = 0.05 + 0.94*(ICaS + ICaT);\n\n    # gating\n    Na_m_inf=  1.0./(1.0+exp((V+25.5)./-5.29));\n    Na_h_inf=  1.0./(1.0+exp((V+48.9)./5.18));\n    Na_tau_m=  1.32 - 1.26./(1+exp((V+120.0)./-25.0));\n    Na_tau_h=  (0.67./(1.0+exp((V+62.9)./-10.0))).*(1.5+1.0./(1.0+exp((V+34.9)./3.6)));\n\n    CaS_m_inf=  1.0./(1.0+exp((V+33.0)./-8.1));\n    CaS_h_inf=  1.0./(1.0+exp((V+60.0)./6.2));\n    CaS_tau_m=  1.4 + 7.0./(exp((V+27.0)./10.0) + exp((V+70.0)./-13.0));\n    CaS_tau_h=  60.0 + 150.0./(exp((V+55.0)./9.0) + exp((V+65.0)./-16.0));\n\n    CaT_m_inf=  1.0./(1.0 + exp((V+27.1)./-7.2));\n    CaT_h_inf=  1.0./(1.0 + exp((V+32.1)./5.5));\n    CaT_tau_m=  21.7 - 21.3./(1.0 + exp((V+68.1)./-20.5));\n    CaT_tau_h=  105.0 - 89.8./(1.0 + exp((V+55.0)./-16.9));\n\n    Ih_m_inf=  1.0./(1.0+exp((V+70.0)./6.0));\n    Ih_tau_m=  (272.0 + 1499.0./(1.0+exp((V+42.2)./-8.73)));\n\n    Ka_m_inf=  1.0./(1.0+exp((V+27.2)./-8.7));\n    Ka_h_inf=  1.0./(1.0+exp((V+56.9)./4.9));\n    Ka_tau_m=  11.6 - 10.4./(1.0+exp((V+32.9)./-15.2));\n    Ka_tau_h=  38.6 - 29.2./(1.0+exp((V+38.9)./-26.5));\n\n    KCa_m_inf=  (Ca./(Ca+3.0))./(1.0+exp((V+28.3)./-12.6));\n    KCa_tau_m=  90.3 - 75.1./(1.0+exp((V+46.0)./-22.7));\n\n    Kdr_m_inf=  1.0./(1.0+exp((V+12.3)./-11.8));\n    Kdr_tau_m=  7.2 - 6.4./(1.0+exp((V+28.3)./-19.2));\n\n    eqs = [ \n    D(V) ~              INa + ICaS + ICaT + Ih + IKa + IKCa + IKdr + Ileak,\n    D(Ca) ~                   (1/tauCa)*(Ca_inf - Ca),\n    D(mNa) ~                   (1/Na_tau_m)*(Na_m_inf - mNa), \n    D(hNa) ~                   (1/Na_tau_h)*(Na_h_inf - hNa), \n    D(mCaS) ~                   (1/CaS_tau_m)*(CaS_m_inf - mCaS), \n    D(hCaS) ~                   (1/CaS_tau_h)*(CaS_h_inf - hCaS), \n    D(mCaT) ~                   (1/CaT_tau_m)*(CaT_m_inf - mCaT), \n    D(hCaT) ~                   (1/CaT_tau_h)*(CaT_h_inf - hCaT), \n    D(mIh) ~                   (1/Ih_tau_m)*(Ih_m_inf - mIh), \n    D(mKa) ~                  (1/Ka_tau_m)*(Ka_m_inf - mKa), \n    D(hKa) ~                   (1/Ka_tau_h)*(Ka_h_inf - hKa), \n    D(mKCa) ~                  (1/KCa_tau_m)*(KCa_m_inf - mKCa), \n    D(mKdr) ~                   (1/Kdr_tau_m)*(Kdr_m_inf - mKdr)\n    ]\n\n    ps = paramvars .=> [50,-20,-80,-50,20,100,3,1.3,5,10,20,0.5,0.01]\n    ics = statevars .=> [-60,0.05,0,0,0,0,0,0,0,0,0,0,0]\n\n    od = ODESystem(eqs, t, statevars, paramvars)\n    tspan = (0.,500.)\n    return od, ics, tspan, ps\nend\n\n\n\n# function predict(p)\n#     return Array(solve(prob, Tsit5(), p=p, saveat=tsteps, sensitivity=BacksolveAdjoint(;autojacvec=true)))        \n# end\n\n\n# function loss(p)\n#     prediction = predict(p)\n#     return sum(abs2, prediction - data)\n# end\n\n", "meta": {"hexsha": "07eee0da262a001578a5a0177e28c6388779e6d4", "size": 3909, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/STG_Liu.jl", "max_stars_repo_name": "Dhruva2/MyModelMenagerie.jl", "max_stars_repo_head_hexsha": "5ec9054142fba29ac668a17506ef3d3fc9fef2d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-10-16T12:58:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-03T15:43:14.000Z", "max_issues_repo_path": "src/models/STG_Liu.jl", "max_issues_repo_name": "Dhruva2/MyModelMenagerie.jl", "max_issues_repo_head_hexsha": "5ec9054142fba29ac668a17506ef3d3fc9fef2d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/STG_Liu.jl", "max_forks_repo_name": "Dhruva2/MyModelMenagerie.jl", "max_forks_repo_head_hexsha": "5ec9054142fba29ac668a17506ef3d3fc9fef2d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.305785124, "max_line_length": 125, "alphanum_fraction": 0.5180353031, "num_tokens": 1801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7676670623532246}}
{"text": "\"\"\" \ndirect product of two or more discrete functions\n\nif we have:\n    ``f_1 : D_1 → R_1``\n    `` …``\n    ``f_k : D_k → R_k``\nthen FunProduct((f1, …, fk)) is F\n    F : D1 × … × Dk → R1 × … × Rk\n\"\"\"\nstruct FunProduct{N, T, D, R} <: CompositeFunction\n    factors :: NTuple{N, T}\n    dom :: D\n    rng :: R\nend\n\nconst FProd = FunProduct\n\ndomain(fp :: FProd) = fp.dom\ncodomain(fp :: FProd) = fp.rng\nfactors(fp :: FProd) = fp.factors\n\n\n# creating functional product from dom and codom\nfunction FProd(dom :: AbstractProduct, codom :: AbstractProduct)\n    fs = Tuple(ResFun(dom[i], codom[i]) for i in 1 : ndims(dom))\n    return FProd(fs, dom, codom)\nend\n\n\n# creating functional product from two tuples\n# of equal length!\n\nfunction FProd(from :: NTuple{N, Int}, to :: NTuple{N, Int}) where N\n    fromto = zip(from, to)\n    funs = tuple(map(ResidueFunction, fromto)...)\n    return FProd(funs)\nend\n\n\n\nfunction FProd(factors)\n    dom = DirectProduct(map(domain, factors))\n    rng = DirectProduct(map(codomain, factors))\n    return FProd(factors, dom, rng)\nend\n\n\nFProd(factors...) = FProd(tuple(factors...))\n\nfunction (fp :: FProd{N, T, D, R})(v) where {N,T,D,R}\n    funs = factors(fp)\n    n = length(v)\n    return NTuple{N}(funs[i](v[i]) for i in 1 : n)\nend\n\nfunction Base.setindex!(fp :: FProd, v :: NTuple, k :: NTuple)\n    fs = factors(fp)\n    for i in 1 : size(fp)\n        fs[i][k[i]] = v[i]\n    end\nend\n(fs :: FProd)(v...) = fs(tuple(v...))", "meta": {"hexsha": "1a2e9abd41481002da801b78120175e0dd2add1e", "size": 1433, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dfuns/fun_product.jl", "max_stars_repo_name": "kirtsar/DiscreteFunctions", "max_stars_repo_head_hexsha": "ff8070b766316f48081611190121e7a97733d4de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dfuns/fun_product.jl", "max_issues_repo_name": "kirtsar/DiscreteFunctions", "max_issues_repo_head_hexsha": "ff8070b766316f48081611190121e7a97733d4de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-01-21T16:48:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-21T16:48:05.000Z", "max_forks_repo_path": "src/dfuns/fun_product.jl", "max_forks_repo_name": "kirtsar/DiscreteFunctions.jl", "max_forks_repo_head_hexsha": "ff8070b766316f48081611190121e7a97733d4de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.746031746, "max_line_length": 68, "alphanum_fraction": 0.6092114445, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541593883189, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7676670623532245}}
{"text": "\"\"\"\n    function expintegrator(A, t::Number, u₀, u₁, …; kwargs...)\n    function expintegrator(A, t::Number, (u₀, u₁, …); kwargs...)\n    function expintegrator(A, t::Number, (u₀, u₁, …), algorithm)\n\nCompute ``y = ϕ₀(t*A)*u₀ + t*ϕ₁(t*A)*u₁ + t^2*ϕ₂(t*A)*u₂ + …``, where `A` is a general linear map, i.e. a `AbstractMatrix` or just a general function or callable object and `u₀`, `u₁` are of any Julia type with vector like behavior. Here, ``ϕ₀(z) = exp(z)`` and ``ϕⱼ₊₁ = (ϕⱼ(z) - 1/j!)/z``. In particular, ``y = x(t)`` represents the solution of the ODE\n``x' = A*x + ∑ⱼ t^j/j! uⱼ₊₁`` with ``x(0) = u₀``.\n\n!!! note\n    When there are only input vectors `u₀` and `u₁`, `t` can equal `Inf`, in which the\n    algorithm tries to evolve all the way to the fixed point `y = - A \\\\ u₁ + P₀ u₀` with\n    `P₀` the projector onto the eigenspace of eigenvalue zero (if any) of `A`. If `A` has\n    any eigenvalues with real part larger than zero, however, the solution to the ODE will\n    diverge, i.e. the fixed point is not stable.\n\n!!! warning\n    The returned solution might be the solution of the ODE integrated up to a smaller time ``t̃ = sign(t) * |t̃|`` with ``|t̃| < |t|``, when the required precision could not be attained. Always check `info.converged > 0` or `info.residual == 0` (see below).\n\n### Arguments:\nThe linear map `A` can be an `AbstractMatrix` (dense or sparse) or a general function or\ncallable object that implements the action of the linear map on a vector. If `A` is an\n`AbstractMatrix`, `x` is expected to be an `AbstractVector`, otherwise `x` can be of any\ntype that behaves as a vector and supports the required methods (see KrylovKit docs).\n\nThe time parameter `t` can be real or complex, and it is better to choose `t` e.g. imaginary\nand `A` hermitian, then to absorb the imaginary unit in an antihermitian `A`. For the\nformer, the Lanczos scheme is used to built a Krylov subspace, in which an approximation to\nthe exponential action of the linear map is obtained. The arguments `u₀`, `u₁`, … can be\nof any type and should be in the domain of `A`.\n\n### Return values:\nThe return value is always of the form `y, info = expintegrator(...)` with\n*   `y`: the result of the computation, i.e.\n    ``y = ϕ₀(t̃*A)*u₀ + t̃*ϕ₁(t̃*A)*u₁ + t̃^2*ϕ₂(t̃*A)*u₂ + …``\n    with ``t̃ = sign(t) * |t̃|`` with ``|t̃| <= |t|``, such that the accumulated error in\n    `y` per unit time is at most equal to the keyword argument `tol`\n*   `info`: an object of type [`ConvergenceInfo`], which has the following fields\n    -   `info.converged::Int`: 0 or 1 if the solution `y` was evolved all the way up to the\n        requested time `t`.\n    -   `info.residual`: there is no residual in the conventional sense, however, this\n        value equals the residual time `t - t̃`, i.e. it is zero if `info.converged == 1`\n    -   `info.normres::Real`: a (rough) estimate of the total error accumulated in the\n        solution, should be smaller than `tol * |t̃|`\n    -   `info.numops::Int`: number of times the linear map was applied, i.e. number of times\n        `f` was called, or a vector was multiplied with `A`\n    -   `info.numiter::Int`: number of times the Krylov subspace was restarted (see below)\n\n### Keyword arguments:\nKeyword arguments and their default values are given by:\n*   `verbosity::Int = 0`: verbosity level, i.e. 0 (no messages), 1 (single message\n    at the end), 2 (information after every iteration), 3 (information per Krylov step)\n*   `krylovdim = 30`: the maximum dimension of the Krylov subspace that will be constructed.\n    Note that the dimension of the vector space is not known or checked, e.g. `x₀` should\n    not necessarily support the `Base.length` function. If you know the actual problem\n    dimension is smaller than the default value, it is useful to reduce the value of\n    `krylovdim`, though in principle this should be detected.\n*   `tol = 1e-12`: the requested accuracy per unit time, i.e. if you want a certain\n    precision `ϵ` on the final result, set `tol = ϵ/abs(t)`. If you work in e.g. single\n    precision (`Float32`), you should definitely change the default value.\n*   `maxiter::Int = 100`: the number of times the Krylov subspace can be rebuilt; see below\n    for further details on the algorithms.\n*   `issymmetric`: if the linear map is symmetric, only meaningful if `T<:Real`\n*   `ishermitian`: if the linear map is hermitian\nThe default value for the last two depends on the method. If an `AbstractMatrix` is used,\n`issymmetric` and `ishermitian` are checked for that matrix, ortherwise the default values\nare `issymmetric = false` and `ishermitian = T <: Real && issymmetric`.\n\n### Algorithm\nThe last method, without keyword arguments and the different vectors `u₀`, `u₁`, … in a\ntuple, is the one that is finally called, and can also be used directly. Here, one\nspecifies the algorithm explicitly as either [`Lanczos`](@ref), for real symmetric or\ncomplex hermitian linear maps, or [`Arnoldi`](@ref), for general linear maps. Note that\nthese names refer to the process for building the Krylov subspace, and that one can still\nuse complex time steps in combination with e.g. a real symmetric map.\n\"\"\"\nfunction expintegrator end\n\nfunction expintegrator(A, t::Number, u₀, us...; kwargs...)\n    alg = eigselector(A, promote_type(typeof(t), eltype(u₀), eltype.(us)...); kwargs...)\n    expintegrator(A, t, (u₀, us...), alg)\nend\n\nfunction expintegrator(A, t::Number, u::Tuple, alg::Union{Lanczos,Arnoldi})\n    length(u) == 1 && return expintegrator(A, t, (u[1], rmul!(similar(u[1]), false)), alg)\n\n    p = length(u) - 1\n\n    # process initial vector and determine result type\n    u₀ = first(u)\n    β₀ = norm(u₀)\n    Au₀ = apply(A, u₀) # used to determine return type\n    numops = 1\n    T = promote_type(promote_type(eltype(Au₀), typeof(β₀), typeof(t)),\n                        promote_type(eltype.(u)...))\n    S = real(T)\n    w₀ = copyto!(similar(u₀, T), u₀)\n\n    # krylovdim and related allocations\n    krylovdim = alg.krylovdim\n    K = krylovdim\n    HH = zeros(T, (krylovdim+p+1, krylovdim+p+1))\n\n    # time step parameters\n    η::S = alg.tol # tol is per unit time\n    totalerr = zero(η)\n    sgn = sign(t)\n    τ::S = abs(t)\n    Δτ::S = one(τ) # don't try any clever initial guesses, rely on correction mechanism\n    τ₀ = zero(τ)\n\n    # safety factors\n    δ::S = 1.2\n    γ::S = 0.8\n\n    # initial vectors\n    w = Vector{typeof(w₀)}(undef, p+1)\n    w[1] = w₀\n    for j = 1:p\n        w[j+1] = apply(A, w[j])\n        numops += 1\n        lfac = 1\n        for l = 0:p-j\n            w[j+1] = axpy!((sgn*τ₀)^l/lfac, u[j+l+1], w[j+1])\n            lfac *= l+1\n        end\n    end\n    v = similar(w₀)\n    β = norm(w[p+1])\n    if β < alg.tol && p == 1\n        if alg.verbosity > 0\n            @info \"\"\"expintegrate finished after 0 iterations, converged to fixed point up to error = $β\"\"\"\n        end\n        return w₀, ConvergenceInfo(1, zero(τ), β, 0, numops)\n    end\n    mul!(v, w[p+1], 1/β)\n\n    # initialize iterator\n    if alg isa Lanczos\n        iter = LanczosIterator(A, w[p+1], alg.orth)\n    else\n        iter = ArnoldiIterator(A, w[p+1], alg.orth)\n    end\n    fact = initialize(iter; verbosity = alg.verbosity - 2)\n    numops += 1\n    sizehint!(fact, krylovdim)\n\n    # start outer iteration loop\n    maxiter = alg.maxiter\n    numiter = 0\n    while true\n        if β < alg.tol && p == 1 # w₀ is fixed point of ODE\n            if alg.verbosity > 0\n                @info \"\"\"expintegrate finished after $numiter iterations, converged to fixed point up to error = $β\"\"\"\n            end\n            return w₀, ConvergenceInfo(1, zero(τ), β, numiter, numops)\n        end\n\n        numiter += 1\n        Δτ = min(Δτ, τ-τ₀)\n\n        # Lanczos or Arnoldi factorization\n        while normres(fact) > eps() && length(fact) < krylovdim\n            fact = expand!(iter, fact; verbosity = alg.verbosity-2)\n            numops += 1\n        end\n        K = fact.k # current Krylov dimension\n        V = basis(fact)\n\n        # Small matrix exponential and error estimation\n        H = fill!(view(HH, 1:K+p+1, 1:K+p+1), zero(T))\n        mul!(view(H, 1:K, 1:K), rayleighquotient(fact), sgn*Δτ)\n        H[1, K+1] = 1\n        for i = 1:p\n            H[K+i, K+i+1] = 1\n        end\n        expH = LinearAlgebra.exp!(H)\n        ϵ = abs(Δτ^p * β * normres(fact) * expH[K,K+p+1])\n        ω = ϵ / (Δτ * η)\n\n        q = K/2\n        while ω > one(ω)\n            ϵ_prev = ϵ\n            Δτ_prev = Δτ\n            Δτ *= (γ/ω)^(1/(q+1))\n            H = fill!(view(HH, 1:K+p+1, 1:K+p+1), zero(T))\n            mul!(view(H, 1:K, 1:K), rayleighquotient(fact), sgn*Δτ)\n            H[1, K+1] = 1\n            for i = 1:p\n                H[K+i, K+i+1] = 1\n            end\n            expH = LinearAlgebra.exp!(H)\n            ϵ = abs(Δτ^p * β * normres(fact) * expH[K,K+p+1])\n            ω = ϵ / (Δτ * η)\n            q = max(zero(q),  log(ϵ / ϵ_prev)/log(Δτ / Δτ_prev)-1)\n        end\n\n        # take time step\n        totalerr += ϵ\n        τ₀ += Δτ\n        jfac = 1\n        for j = 1:p-1\n            w₀ = axpy!((sgn*Δτ)^j/jfac, w[j+1], w₀)\n            jfac *= (j+1)\n        end\n        w[p+1] = mul!(w[p+1], basis(fact), view(expH, 1:K, K+p))\n        # add first correction\n        w[p+1] = axpy!(expH[K,K+p+1], residual(fact), w[p+1])\n        w₀ = axpy!(β*(sgn*Δτ)^p, w[p+1], w₀)\n\n        # increase time step for next iteration:\n        if ω < γ\n            Δτ *= (γ/ω)^(1/(q+1))\n        end\n\n        if alg.verbosity > 1\n            msg = \"expintegrate in iteration $numiter: \"\n            msg *= \"reached time \" * @sprintf(\"%.2e\", τ₀)\n            msg *= \", total error = \" * @sprintf(\"%.4e\", totalerr)\n            @info msg\n        end\n\n        if τ₀ >= τ\n            if alg.verbosity > 0\n                @info \"\"\"expintegrate finished after $numiter iterations: total error = $totalerr\"\"\"\n            end\n            return w₀, ConvergenceInfo(1, zero(τ), totalerr, numiter, numops)\n        elseif numiter == maxiter\n            if alg.verbosity > 0\n                @warn \"\"\"expintegrate finished without convergence after $numiter iterations:\n                total error = $totalerr, residual time = $(τ - τ₀)\"\"\"\n            end\n            return w₀, ConvergenceInfo(0, τ-τ₀, totalerr, numiter, numops)\n        else\n            for j = 1:p\n                w[j+1] = apply(A, w[j])\n                numops += 1\n                lfac = 1\n                for l = 0:p-j\n                    w[j+1] = axpy!((sgn*τ₀)^l/lfac, u[j+l+1], w[j+1])\n                    lfac *= l+1\n                end\n            end\n            β = norm(w[p+1])\n            mul!(v, w[p+1], 1/β)\n            if alg isa Lanczos\n                iter = LanczosIterator(A, w[p+1], alg.orth)\n            else\n                iter = ArnoldiIterator(A, w[p+1], alg.orth)\n            end\n            fact = initialize!(iter, fact; verbosity = alg.verbosity-2)\n            numops += 1\n        end\n    end\nend\n", "meta": {"hexsha": "90cd890a196d9cfa5a6568f2a17996bc502a600c", "size": 10872, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrixfun/expintegrator.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/KrylovKit.jl-0b1a1467-8014-51b9-945f-bf0ae24f4b77", "max_stars_repo_head_hexsha": "f00d56591d0d66e308368338eaff658196247eaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matrixfun/expintegrator.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/KrylovKit.jl-0b1a1467-8014-51b9-945f-bf0ae24f4b77", "max_issues_repo_head_hexsha": "f00d56591d0d66e308368338eaff658196247eaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrixfun/expintegrator.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/KrylovKit.jl-0b1a1467-8014-51b9-945f-bf0ae24f4b77", "max_forks_repo_head_hexsha": "f00d56591d0d66e308368338eaff658196247eaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6352941176, "max_line_length": 353, "alphanum_fraction": 0.5866445916, "num_tokens": 3429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7676670602396448}}
{"text": "export NeedPiecewiseCorrection\n\n\n# Computes samplex of real or complex Haar matrices of size nxn\n#\n# For beta=1,2,4, generates random orthogonal, unitary and symplectic matrices\n# of uniform Haar measure. \n# These matrices are distributed with uniform Haar measure over the\n# classical orthogonal, unitary and symplectic groups O(N), U(N) and\n# Sp(N)~USp(2N) respectively.\n#\n# The last parameter specifies whether or not the piecewise correction\n# is applied to ensure that it truly of Haar measure\n# This addresses an inconsistency in the Householder reflections as\n# implemented in most versions of LAPACK\n# Method 0: No correction\n# Method 1: Multiply rows by uniform random phases\n# Method 2: Multiply rows by phases of diag(R)\n# References:\n#    Edelman and Rao, 2005\n#    Mezzadri, 2006, math-ph/0609050\n#TODO implement O(n^2) method\nfunction rand(W::Haar, n::Integer, doCorrection::Integer)\n    beta = W.beta\n    M=rand(Ginibre(beta,n))\n    q,r=qr(M)\n    if doCorrection==0\n        q\n    elseif doCorrection==1 \n        if beta==1\n            L = sign(rand(n).-0.5)\n        elseif beta==2\n            L = exp(im*rand(n)*2pi)\n        elseif beta==4\n            L = exp(im*rand(2n)*2pi)\n        else\n            error(string(\"beta = \",beta, \" not implemented.\"))\n        end\n        q*diagm(L)\n    elseif doCorrection==2\n        if beta==1\n            L=sign(diag(r))\n        elseif (beta==2 || beta==4)\n            L=diag(r)\n            L=L./abs(L)\n        else\n            error(string(\"beta = \",beta, \" not implemented.\"))\n        end\n        q*diagm(L)\n    end\nend\n\n#By default, always do piecewise correction\n#For most applications where you use the HaarMatrix as a similarity transform\n#it doesn't matter, but better safe than sorry... let the user choose else\nrand(W::Haar,n::Integer) = rand(W,n, 1)\n\n#A utility method to check if the piecewise correction is needed\n#This checks the R part of the QR factorization; if correctly done,\n#the diagonals are all chi variables so are non-negative\nfunction NeedPiecewiseCorrection()\n    n=20\n    R=qr(randn(Ginibre(2,n)))[2]\n    return any([x<0 for x in diag(R)])\nend\n\n\n#TODO maybe, someday\n#Haar measure on U(N) in terms of local coordinates\n#Zyczkowski and Kus, Random unitary matrices, J. Phys. A: Math. Gen. 27,\n#4235–4245 (1994).\n\n", "meta": {"hexsha": "2c7d582386437b66be15ef32e9fca02b0803a0eb", "size": 2291, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HaarMeasure.jl", "max_stars_repo_name": "mschauer/RandomMatrices.jl", "max_stars_repo_head_hexsha": "c9138d4acfcd27c34981401874e1abbe4ec93b73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HaarMeasure.jl", "max_issues_repo_name": "mschauer/RandomMatrices.jl", "max_issues_repo_head_hexsha": "c9138d4acfcd27c34981401874e1abbe4ec93b73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HaarMeasure.jl", "max_forks_repo_name": "mschauer/RandomMatrices.jl", "max_forks_repo_head_hexsha": "c9138d4acfcd27c34981401874e1abbe4ec93b73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3835616438, "max_line_length": 78, "alphanum_fraction": 0.6643387167, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7676538417041349}}
{"text": "module EnsembleAnalysis\n\nusing SciMLBase, Statistics, RecursiveArrayTools\n\n# Getters\nget_timestep(sim,i) = (getindex(sol,i) for sol in sim)\nget_timepoint(sim,t) = (sol(t) for sol in sim)\nfunction componentwise_vectors_timestep(sim,i)\n  arr = [get_timestep(sim,i)...]\n  if typeof(arr[1]) <: AbstractArray\n   return vecarr_to_vectors(VectorOfArray(arr))\n  else\n   return arr\n  end\n end\n function componentwise_vectors_timepoint(sim,t)\n   arr = [get_timepoint(sim,t)...]\n   if typeof(arr[1]) <: AbstractArray\n    return vecarr_to_vectors(VectorOfArray(arr))\n   else\n    return arr\n   end\n  end\n\n# Timestep statistics\ntimestep_mean(sim,i) = componentwise_mean(get_timestep(sim,i))\ntimestep_mean(sim,::Colon) = timeseries_steps_mean(sim)\nfunction timestep_median(sim,i)\n  arr = componentwise_vectors_timestep(sim,i)\n  if typeof(first(arr)) <: AbstractArray\n    return reshape([median(x) for x in arr],size(sim[1][i])...)\n  else\n    return median(arr)\n  end\nend\ntimestep_median(sim,::Colon) = timeseries_steps_median(sim)\nfunction timestep_quantile(sim,q,i)\n  arr = componentwise_vectors_timestep(sim,i)\n  if typeof(first(arr)) <: AbstractArray\n    return reshape([quantile(x,q) for x in arr],size(sim[1][i])...)\n  else\n    return quantile(arr,q)\n  end\nend\ntimestep_quantile(sim,q,::Colon) = timeseries_steps_quantile(sim,q)\ntimestep_meanvar(sim,i) = componentwise_meanvar(get_timestep(sim,i))\ntimestep_meanvar(sim,::Colon) = timeseries_steps_meanvar(sim)\ntimestep_meancov(sim,i,j) = componentwise_meancov(get_timestep(sim,i),get_timestep(sim,j))\ntimestep_meancov(sim,::Colon,::Colon) = timeseries_steps_meancov(sim)\ntimestep_meancor(sim,i,j) = componentwise_meancor(get_timestep(sim,i),get_timestep(sim,j))\ntimestep_meancor(sim,::Colon,::Colon) = timeseries_steps_meancor(sim)\ntimestep_weighted_meancov(sim,W,i,j) = componentwise_weighted_meancov(get_timestep(sim,i),get_timestep(sim,j),W)\ntimestep_weighted_meancov(sim,W,::Colon,::Colon) = timeseries_steps_weighted_meancov(sim,W)\n\nfunction timeseries_steps_mean(sim)\n  DiffEqArray([timestep_mean(sim,i) for i in 1:length(sim[1])],sim[1].t)\nend\nfunction timeseries_steps_median(sim)\n  DiffEqArray([timestep_median(sim,i) for i in 1:length(sim[1])],sim[1].t)\nend\nfunction timeseries_steps_quantile(sim,q)\n  DiffEqArray([timestep_quantile(sim,q,i) for i in 1:length(sim[1])],sim[1].t)\nend\nfunction timeseries_steps_meanvar(sim)\n  m,v = timestep_meanvar(sim,1)\n  means = [m]\n  vars = [v]\n  for i in 2:length(sim[1])\n    m,v = timestep_meanvar(sim,i)\n    push!(means,m)\n    push!(vars,v)\n  end\n  DiffEqArray(means,sim[1].t),DiffEqArray(vars,sim[1].t)\nend\nfunction timeseries_steps_meancov(sim)\n  reshape([timestep_meancov(sim,i,j) for i in 1:length(sim[1]) for j in 1:length(sim[1])],length(sim[1]),length(sim[1]))\nend\nfunction timeseries_steps_meancor(sim)\n  reshape([timestep_meancor(sim,i,j) for i in 1:length(sim[1]) for j in 1:length(sim[1])],length(sim[1]),length(sim[1]))\nend\nfunction timeseries_steps_weighted_meancov(sim,W)\n  reshape([timestep_meancov(sim,W,i,j) for i in 1:length(sim[1]) for j in 1:length(sim[1])],length(sim[1]),length(sim[1]))\nend\n\ntimepoint_mean(sim,t) = componentwise_mean(get_timepoint(sim,t))\nfunction timepoint_median(sim,t)\n  arr = componentwise_vectors_timepoint(sim,t)\n  if typeof(first(arr)) <: AbstractArray\n    return reshape([median(x) for x in arr],size(sim[1][1])...)\n  else\n    return median(arr)\n  end\nend\nfunction timepoint_quantile(sim,q,t)\n  arr = componentwise_vectors_timepoint(sim,t)\n  if typeof(first(arr)) <: AbstractArray\n    return reshape([quantile(x,q) for x in arr],size(sim[1][1])...)\n  else\n    return quantile(arr,q)\n  end\nend\ntimepoint_meanvar(sim,t) = componentwise_meanvar(get_timepoint(sim,t))\ntimepoint_meancov(sim,t1,t2) = componentwise_meancov(get_timepoint(sim,t1),get_timepoint(sim,t2))\ntimepoint_meancor(sim,t1,t2) = componentwise_meancor(get_timepoint(sim,t1),get_timepoint(sim,t2))\ntimepoint_weighted_meancov(sim,W,t1,t2) = componentwise_weighted_meancov(get_timepoint(sim,t1),get_timepoint(sim,t2),W)\n\nfunction EnsembleSummary(sim::SciMLBase.AbstractEnsembleSolution{T,N},\n                         t=sim[1].t;quantiles=[0.05,0.95]) where {T,N}\n  if typeof(sim[1]) <: DESolution\n    m,v = timeseries_point_meanvar(sim,t)\n    qlow = timeseries_point_quantile(sim,quantiles[1],t)\n    qhigh = timeseries_point_quantile(sim,quantiles[2],t)\n  else\n    m,v = timeseries_steps_meanvar(sim)\n    qlow = timeseries_steps_quantile(sim,quantiles[1])\n    qhigh = timeseries_steps_quantile(sim,quantiles[2])\n  end\n\n  trajectories = length(sim)\n  EnsembleSummary{T,N,typeof(t),typeof(m),typeof(v),typeof(qlow),typeof(qhigh)}(t,m,v,qlow,qhigh,trajectories,sim.elapsedTime,sim.converged)\nend\n\nfunction timeseries_point_mean(sim,ts)\n  DiffEqArray([timepoint_mean(sim,t) for t in ts],ts)\nend\nfunction timeseries_point_median(sim,ts)\n  DiffEqArray([timepoint_median(sim,t) for t in ts],ts)\nend\nfunction timeseries_point_quantile(sim,q,ts)\n  DiffEqArray([timepoint_quantile(sim,q,t) for t in ts],ts)\nend\nfunction timeseries_point_meanvar(sim,ts)\n  m,v = timepoint_meanvar(sim,first(ts))\n  means = [m]\n  vars = [v]\n  for t in Iterators.drop(ts,1)\n    m,v = timepoint_meanvar(sim,t)\n    push!(means,m)\n    push!(vars,v)\n  end\n  DiffEqArray(means,ts),DiffEqArray(vars,ts)\nend\nfunction timeseries_point_meancov(sim,ts1,ts2)\n  reshape([timepoint_meancov(sim,t1,t2) for t1 in ts1 for t2 in ts2],length(ts1),length(ts2))\nend\nfunction timeseries_point_meancor(sim,ts1,ts2)\n  reshape([timepoint_meancor(sim,t1,t2) for t1 in ts1 for t2 in ts2],length(ts1),length(ts2))\nend\nfunction timeseries_point_weighted_meancov(sim,W,ts1,ts2)\n  reshape([timepoint_meancov(sim,W,t1,t2) for t1 in ts1 for t2 in ts2],length(ts1),length(ts2))\nend\n\nfunction componentwise_mean(A)\n  x0 = first(A)\n  n = 0\n  mean = zero(x0)\n  for x in A\n    n += 1\n    if typeof(x0) <: AbstractArray && !(typeof(x0) <: SArray)\n      mean .+= x\n    else\n      mean += x\n    end\n  end\n  if typeof(x0) <: AbstractArray && !(typeof(x0) <: SArray)\n    mean ./= n\n  else\n    mean /= n\n  end\n  mean\nend\n\n# Welford algorithm\n# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance\nfunction componentwise_meanvar(A;bessel=true)\n  x0 = first(A)\n  n = 0\n  mean = zero(x0)\n  M2 = zero(x0)\n  delta = zero(x0)\n  delta2 = zero(x0)\n  for x in A\n    n += 1\n    if typeof(x0) <: AbstractArray && !(typeof(x0) <: SArray)\n      delta .= x .- mean\n      mean .+= delta./n\n      delta2 .= x .- mean\n      M2 .+= delta.*delta2\n    else\n      delta = x .- mean\n      mean += delta./n\n      delta2 = x .- mean\n      M2 += delta.*delta2\n    end\n  end\n  if n < 2\n    return NaN\n  else\n    if bessel\n      if typeof(x0) <: AbstractArray && !(typeof(x0) <: SArray)\n        M2 .= M2 ./ (n .- 1)\n      else\n        M2 = M2 ./ (n .- 1)\n      end\n    else\n      if typeof(x0) <: AbstractArray && !(typeof(x0) <: SArray)\n        M2 .= M2 ./ n\n      else\n        M2 = M2 ./ n\n      end\n    end\n    return mean,M2\n  end\nend\n\nfunction componentwise_meancov(A,B;bessel=true)\n  x0 = first(A)\n  y0 = first(B)\n  n = 0\n  meanx = zero(x0)\n  meany = zero(y0)\n  C = zero(x0)\n  dx = zero(x0)\n  for (x,y) in zip(A,B)\n    n += 1\n    if typeof(x0) <: AbstractArray && !(typeof(x0) <: SArray)\n      dx .= x .- meanx\n      meanx .+= dx./n\n      meany .+= (y.-meany)./n\n      C .+= dx .* (y .- meany)\n    else\n      dx = x .- meanx\n      meanx += dx./n\n      meany += (y.-meany)./n\n      C += dx .* (y .- meany)\n    end\n  end\n  if n < 2\n    return NaN\n  else\n    if bessel\n      if typeof(x0) <: AbstractArray && !(typeof(x0) <: SArray)\n        C .= C ./ (n .- 1)\n      else\n        C = C ./ (n .- 1)\n      end\n    else\n      if typeof(x0) <: AbstractArray && !(typeof(x0) <: SArray)\n        C .= C ./ n\n      else\n        C = C ./ n\n      end\n    end\n    return meanx,meany,C\n  end\nend\n\nfunction componentwise_meancor(A,B;bessel=true)\n  mx,my,cov = componentwise_meancov(A,B;bessel=bessel)\n  mx,vx = componentwise_meanvar(A;bessel=bessel)\n  my,vy = componentwise_meanvar(B;bessel=bessel)\n  if typeof(vx) <: AbstractArray\n    vx .= sqrt.(vx)\n    vy .= sqrt.(vy)\n  else\n    vx = sqrt.(vx)\n    vy = sqrt.(vy)\n  end\n  mx,my,cov./(vx.*vy)\nend\n\nfunction componentwise_weighted_meancov(A,B,W;weight_type=:reliability)\n  x0 = first(A)\n  y0 = first(B)\n  w0 = first(W)\n  n = 0\n  meanx = zero(x0)\n  meany = zero(y0)\n  wsum = zero(w0)\n  wsum2 = zero(w0)\n  C = zero(x0)\n  dx = zero(x0)\n  for (x,y,w) in zip(A,B,W)\n    n += 1\n    if typeof(x0) <: AbstractArray && !(typeof(x0) <: SArray)\n      wsum .+= w\n      wsum2 .+= w.*w\n      dx .= x .- meanx\n      meanx .+= (w ./ wsum) .* dx\n      meany .+= (w ./ wsum) .* (y .- meany)\n      C .+= w .* dx .* (y .- meany)\n    else\n      wsum += w\n      wsum2 += w.*w\n      dx = x .- meanx\n      meanx += (w ./ wsum) .* dx\n      meany += (w ./ wsum) .* (y .- meany)\n      C += w .* dx .* (y .- meany)\n    end\n  end\n  if n < 2\n    return NaN\n  else\n    if weight_type == :population\n      if typeof(x0) <: AbstractArray && !(typeof(x0) <: SArray)\n        C .= C ./ wsum\n      else\n        C = C ./ wsum\n      end\n    elseif weight_type == :reliability\n      if typeof(x0) <: AbstractArray && !(typeof(x0) <: SArray)\n        C .= C ./ (wsum .- wsum2 ./ wsum)\n      else\n        C = C ./ (wsum .- wsum2 ./ wsum)\n      end\n    elseif weight_type == :frequency\n      if typeof(x0) <: AbstractArray && !(typeof(x0) <: SArray)\n        C .= C ./ (wsum .- 1)\n      else\n        C = C ./ (wsum .- 1)\n      end\n    else\n      error(\"The weight_type which was chosen is not allowed.\")\n    end\n    return meanx,meany,C\n  end\nend\n\nexport get_timestep, get_timepoint, apply_timestep, apply_timepoint,\n       componentwise_vectors_timestep, componentwise_vectors_timepoint\n\nexport componentwise_mean, componentwise_meanvar\n\nexport timestep_mean, timestep_median, timestep_quantile, timestep_meanvar,\n       timestep_meancov, timestep_meancor, timestep_weighted_meancov\n\nexport timeseries_steps_mean, timeseries_steps_median, timeseries_steps_quantile,\n       timeseries_steps_meanvar, timeseries_steps_meancov,\n       timeseries_steps_meancor, timeseries_steps_weighted_meancov\n\nexport timepoint_mean, timepoint_median, timepoint_quantile,\n       timepoint_meanvar, timepoint_meancov,\n       timepoint_meancor, timepoint_weighted_meancov\n\nexport timeseries_point_mean, timeseries_point_median, timeseries_point_quantile,\n       timeseries_point_meanvar, timeseries_point_meancov,\n       timeseries_point_meancor, timeseries_point_weighted_meancov\n\nend\n", "meta": {"hexsha": "042f2a5404c9d9968b99452eba7cddec0482c14d", "size": 10471, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ensemble/ensemble_analysis.jl", "max_stars_repo_name": "wi11dey/SciMLBase.jl", "max_stars_repo_head_hexsha": "c555eada0f64fe5383f11afcf05a0d11cb4e162a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ensemble/ensemble_analysis.jl", "max_issues_repo_name": "wi11dey/SciMLBase.jl", "max_issues_repo_head_hexsha": "c555eada0f64fe5383f11afcf05a0d11cb4e162a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ensemble/ensemble_analysis.jl", "max_forks_repo_name": "wi11dey/SciMLBase.jl", "max_forks_repo_head_hexsha": "c555eada0f64fe5383f11afcf05a0d11cb4e162a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9171428571, "max_line_length": 140, "alphanum_fraction": 0.6696590584, "num_tokens": 3321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850128595114, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7676538404990045}}
{"text": "\"\"\" \ntupling of two or more discrete functions\nif we have\n    f1 : D → R1\n    f2 : D → R2\n        …\n    fk : D → Rk\nthen FunTupling((f1, …, fk)) is F\n    F : D → R1 × … × Rk\n\"\"\"\nstruct FunTupling{N, T, D, R} <: CompositeFunction\n    factors :: NTuple{N, T}\n    dom :: D\n    rng :: R\nend\n\nconst FTuple = FunTupling\n\n\nfunction FTuple(factors)\n    dom = domain(first(factors))\n    rng = DirectProduct(map(codomain, factors))\n    return FTuple(factors, dom, rng)\nend\n\n\n# creating functional tupling from two tuples\n# not necessarily equal length !\n\nfunction FTuple(from :: NTuple{N, Int}, to :: NTuple{M, Int}) where N where M\n    funs = tuple(map(x -> ExtendedResidueFunction(from, x), to)...)\n    return FTuple(funs)\nend\n\n\n# creating functional product from dom and codom\n\nfunction FTuple(dom :: AbstractProduct, codom :: AbstractProduct)\n    #fromto = zip(from, to)\n    #funs = tuple(map(ResidueFunction, fromto)...)\n    #return FProd(funs)\n    from = size(dom)\n    to = size(codom)\n    return FTuple(from, to)\nend\n\n\nfunction (ft :: FTuple{N, T, D, R})(v) where {N,T,D,R}\n    funs = factors(ft)\n    n = length(funs)\n    return NTuple{N}(funs[i](v) for i in 1 : n)\nend\n\nfunction Base.setindex!(ft :: FTuple, v :: NTuple, k)\n    fs = factors(ft)\n    for (i, val) in enumerate(v)\n        fs[i][k] = val\n    end\nend\n\n(fs :: FTuple)(v...) = fs(tuple(v...))\n\nFTuple(factors...) = FTuple(tuple(factors...))\n", "meta": {"hexsha": "fc6cb847a5700c5ea25f5bfe8476eadbb41921ba", "size": 1399, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dfuns/fun_tupling.jl", "max_stars_repo_name": "kirtsar/DiscreteFunctions", "max_stars_repo_head_hexsha": "ff8070b766316f48081611190121e7a97733d4de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dfuns/fun_tupling.jl", "max_issues_repo_name": "kirtsar/DiscreteFunctions", "max_issues_repo_head_hexsha": "ff8070b766316f48081611190121e7a97733d4de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-01-21T16:48:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-21T16:48:05.000Z", "max_forks_repo_path": "src/dfuns/fun_tupling.jl", "max_forks_repo_name": "kirtsar/DiscreteFunctions.jl", "max_forks_repo_head_hexsha": "ff8070b766316f48081611190121e7a97733d4de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.859375, "max_line_length": 77, "alphanum_fraction": 0.6140100071, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7676538399939384}}
{"text": "module Day12\nexport day12\n\nparseAngle(arg) = div(arg, 90)\n\n# char => (:name, factor, parsefunction)\nconst COMMANDS = Dict('R' => (:rotate, -1, parseAngle),\n                      'L' => (:rotate,  1, parseAngle),\n                      'F' => (:forward, 1, identity),\n                      'N' => (:go, im, identity),\n                      'S' => (:go, -im, identity),\n                      'W' => (:go, -1, identity),\n                      'E' => (:go, 1, identity))\n\nfunction parseLine(line)\n    command = line[1]    \n    arg = parse(Int, line[2:end])\n    name, factor, func = COMMANDS[command]\n    name, factor*func(arg)\nend\n\nfunction readInput(inputfile=\"inputs/input12.txt\")\n    [parseLine(line) for line in eachline(inputfile)]\nend\n\nfunction day12(inputfile=\"inputs/input12.txt\")\n    instructions = readInput(inputfile)\n    (day12Part1(instructions), day12Part2(instructions))\nend\n\nfunction day12Part1(instructions)\n    at = complex(0)\n    facing = complex(1)\n    for (command, value) in instructions\n        if command === :go\n            at += value\n        elseif command === :rotate\n            facing *= (sign(value)*im)^abs(value)\n        elseif command === :forward\n            at += facing*value\n        else\n            error(\"Unknown instruction: $command\")\n        end\n    end\n    abs(real(at)) + abs(imag(at))\nend\n\nfunction day12Part2(instructions)\n    waypoint = 10+1im\n    at = complex(0)\n    for (command, value) in instructions\n        if command === :go\n            waypoint += value\n        elseif command === :rotate\n            waypoint *= (sign(value)*im)^abs(value)\n        elseif command === :forward\n            at += waypoint*value\n        else\n            error(\"Unknown instruction: $command\")\n        end\n    end\n    abs(real(at)) + abs(imag(at))\nend\n\nend #module", "meta": {"hexsha": "71f6f025878e73f717a981746b0ad8e65c8c5948", "size": 1795, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/day12.jl", "max_stars_repo_name": "abraemer/AoC2020.jl", "max_stars_repo_head_hexsha": "e72a617fbd187aa1f9b94a2668c4efda9e8f77c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/day12.jl", "max_issues_repo_name": "abraemer/AoC2020.jl", "max_issues_repo_head_hexsha": "e72a617fbd187aa1f9b94a2668c4efda9e8f77c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/day12.jl", "max_forks_repo_name": "abraemer/AoC2020.jl", "max_forks_repo_head_hexsha": "e72a617fbd187aa1f9b94a2668c4efda9e8f77c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6153846154, "max_line_length": 56, "alphanum_fraction": 0.5493036212, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7676538349208851}}
{"text": "\"\"\"\n**Adadelta constructor**\n\n```julia\n    Adadelta(; ρ::Float64=0.9, ϵ::Float64=1e-8)\n```\n\nAlgorithm :\n\n```math\n\\\\begin{align*}\nE[g^2]_t =& \\\\rho  E[g^2]_{t-1}+(1-\\\\rho)g^2_t\\\\\\\\\n\\\\text{RMS}[g]_t =& \\\\sqrt{E[g^2]_t + \\\\epsilon}\\\\\\\\\n\\\\text{RMS}[\\\\Delta x]_{t-1} =& \\\\sqrt{E[\\\\Delta x^2]_{t-1} + \\\\epsilon}\\\\\\\\\n\\\\Delta x_t =& \\\\text{RMS}[Δx]_{t-1} * g_t / \\\\text{RMS}[g]_t\\\\\\\\\nE[\\\\Delta x^2]_{t} =& \\\\rho E[\\\\Delta x^2]_{t} + (1 - \\\\rho) \\\\Delta x^2_t\\\\\\\\\n\\\\end{align*}\n```\n\n[Algorithm Reference](https://arxiv.org/abs/1212.5701)\n\"\"\"\nmutable struct Adadelta <: Optimizer\n    opt_type::String\n    t::Int64\n    ϵ::Float64\n    ρ::Float64\n    E_g²_t::AbstractArray\n    E_Δx²_t_1::AbstractArray\n    Δx²_t_1::AbstractArray\nend\n\nfunction Adadelta(; ρ::Real=0.9, ϵ::Real=1e-8)\n    @assert ρ > 0.0 \"ρ must be greater than 0\"\n    @assert ϵ > 0.0 \"ϵ must be greater than 0\"\n\n    Adadelta(\"Adadelta\", 0, ϵ, ρ, [], [], [])\nend\n\nparams(opt::Adadelta) = \"ϵ=$(opt.ϵ), ρ=$(opt.ρ)\"\n\nfunction update(opt::Adadelta, g_t::AbstractArray{T}) where {T<:Real}\n    # resize accumulated and squared updates\n    if opt.t == 0\n        opt.E_g²_t = zero(g_t)\n        opt.E_Δx²_t_1  = zero(g_t)\n        opt.Δx²_t_1 = zero(g_t)\n    end\n\n    # accumulate gradient\n    opt.E_g²_t = opt.ρ * opt.E_g²_t + (one(T) - opt.ρ) * (g_t .^ 2)\n\n    # compute update\n    RMS_g_t = sqrt.(opt.E_g²_t .+ opt.ϵ)\n    RMS_Δx_t_1 = sqrt.(opt.E_Δx²_t_1 .+ opt.ϵ)\n    Δx_t = RMS_Δx_t_1 .* g_t ./ RMS_g_t\n\n    # accumulate updates\n    opt.E_Δx²_t_1 = opt.ρ * opt.E_Δx²_t_1 + (one(T) - opt.ρ) * (Δx_t .^ 2)\n\n    return Δx_t\nend\n\n\"\"\"\n\n\"\"\"\n", "meta": {"hexsha": "e14ef8d3d3d5bbe0045eeee81b56d86542461a57", "size": 1580, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/AdaDeltaOptimizer.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_stars_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2017-08-20T00:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T03:09:32.000Z", "max_issues_repo_path": "src/AdaDeltaOptimizer.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_issues_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-11-19T22:38:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-25T20:33:14.000Z", "max_forks_repo_path": "src/AdaDeltaOptimizer.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_forks_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-08-03T16:14:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:48:41.000Z", "avg_line_length": 23.9393939394, "max_line_length": 78, "alphanum_fraction": 0.5753164557, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362849986365571, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7676538308979274}}
{"text": "# adapted from https://github.com/chaaland/EllipseFit.jl by Casey Haaland\n\nusing LinearAlgebra\n\nexport ParametricFormEllipse, ConicFormEllipse, parametric2conic, conic2parametric\n\n\n\nabstract type EllipseForm end\n\nstruct ParametricFormEllipse{T<:Real, U<:Real, V<:Real}\n    axis_lengths::Array{T}\n    center::Array{U}\n    ccw_angle::V\n\n    function ParametricFormEllipse(axis_lengths::Array{T}, center::Array{U}, ccw_angle::V) where {T<:Real, U<:Real, V<:Real}\n        axis_lengths = vec(axis_lengths)\n        center = vec(center)\n\n        if size(center)[1] != 2\n            error(\"Parameter 'center' must be vector of length 2\")\n        elseif size(axis_lengths)[1] != 2\n            error(\"Parameter 'axis_lengths' must be vector of length 2\")\n        elseif sum(axis_lengths .< 0) > 0\n            error(\"Parameter 'axis_lengths' must be nonnegative\")\n        else\n            new{T,U,V}(axis_lengths, center, ccw_angle)\n        end\n    end\nend\n\nfunction parametric2conic(ellipse::ParametricFormEllipse)\n    # inputs\n    a = ellipse.axis_lengths[1] / 2\n    b = ellipse.axis_lengths[2] / 2\n    x₀ = ellipse.center[1]\n    y₀ = ellipse.center[2]\n    θ = deg2rad(ellipse.ccw_angle)\n\n    # outputs\n    A = a^2 * sin(θ)^2 + b^2 * cos(θ)^2\n    B = 2 * (b^2 - a^2) * sin(θ) * cos(θ)\n    C = a^2 * cos(θ)^2 + b^2 * sin(θ)^2\n    D = -2 * A * x₀ - B * y₀\n    E = -B * x₀ - 2 * C * y₀\n    F = A * x₀^2 + B * x₀ * y₀ + C * y₀^2 - a^2 * b^2\n\n    return ConicFormEllipse(A, B, C, D, E, F)\nend\n\nstruct ConicFormEllipse{T<:Real} <: EllipseForm\n    A::T\n    B::T\n    C::T\n    D::T\n    E::T\n    F::T\n    function ConicFormEllipse(A::T, B::T, C::T, D::T, E::T, F::T) where {T<:Real}\n        if B ^2 - 4 * A * C >= 0\n            error(\"Discriminant is non-negative. Input does not denote an ellipse\")\n        end\n        new{T}(A, B, C, D, E, F)\n    end\nend\n\nConicFormEllipse(A::Real, B::Real, C::Real, D::Real, E::Real, F::Real) = ConicFormEllipse(promote(A, B, C, D, E, F)...)\n\n\nfunction conic2parametric(ellipse::ConicFormEllipse)\n    # TODO reference the different equations properly\n\n    # mostly from here: https://en.wikipedia.org/wiki/Ellipse#General_ellipse\n\n    #=\n    Helper for converting from conic form to parametric form of ellipse\n    Given an ellipse in standard conic section form\n            A * x^2 + B * x * y + C * y^2 + D * x + E * y + F = 0\n    convert it to parametric form\n            [x_c y_c] + rot_mat2d(ccw_angle) * [a*cos(theta) b*sin(theta)]\n    Args :\n\n    Returns :\n        axis_lengths : array of the form [2*a 2*b] where a is half the width\n                          and b is half the height (before rotation)\n        center : array of the x and y coordinates of the center of the ellipse\n        ccw_angle : The counter clockwise angle (in degrees) to rotate the ellipse wrt\n                    the positive x-axis\n    =#\n\n    A = ellipse.A; B = ellipse.B; C = ellipse.C; D = ellipse.D; E = ellipse.E; F = ellipse.F\n\n    A_Q = [A B/2 D/2; B/2 C E/2; D/2 E/2 F]\n    Δ = det(A_Q) # -1/4 * (AE² + CD² + FB² -BDE - 4 * ACF)\n\n    A_33 = [A B/2; B/2 C]\n    J = det(A_33) # -1/4 * (B² - 4 * AC)\n\n    I = tr(A_33)\n\n    sq = sqrt((A - C)^2 + B^2)\n\n    #=\n    now write the equations (21) and (22) at http://mathworld.wolfram.com/Ellipse.html\n    in terms of Δ, J, I and sq --> semiaxes a and b\n    =#\n\n    a = sqrt(-2 * Δ * (I + sq)) / (2*J)\n    b = sqrt(-2 * Δ * (I - sq)) / (2*J)\n\n    axis_lengths = [2*a 2*b]\n\n    x₀, y₀ = inv(A_33) * [-D/2; -E/2]\n\n    center = [x₀ y₀]\n\n    # all of the angles are mapped onto [-90,90]\n    # as the system has a period of 180°\n    # i.e. [-280, -100, 80, 260, etc] → 80\n\n    if B == 0\n        if A <= C\n            θ = 0\n        else\n            θ = π/2\n        end\n    else\n        θ = atan(1/B * (C - A - sq))\n    end\n\n    ccw_angle = rad2deg(θ)\n\n\n    return ParametricFormEllipse(axis_lengths, center, ccw_angle)\nend\n", "meta": {"hexsha": "b421fe53566e3a8107401b59f655cfb37d1c5b1d", "size": 3865, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ellipse.jl", "max_stars_repo_name": "razvangheorghe/HexapoleDataFit.jl", "max_stars_repo_head_hexsha": "7586e7465f6c339fcedaf17d55978dcbc23d9aa1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ellipse.jl", "max_issues_repo_name": "razvangheorghe/HexapoleDataFit.jl", "max_issues_repo_head_hexsha": "7586e7465f6c339fcedaf17d55978dcbc23d9aa1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ellipse.jl", "max_forks_repo_name": "razvangheorghe/HexapoleDataFit.jl", "max_forks_repo_head_hexsha": "7586e7465f6c339fcedaf17d55978dcbc23d9aa1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6296296296, "max_line_length": 124, "alphanum_fraction": 0.5686934023, "num_tokens": 1327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979619, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7675265140147497}}
{"text": "# ---\n# title: 313. Super Ugly Number\n# id: problem313\n# author: Indigo\n# date: 2021-06-10\n# difficulty: Medium\n# categories: Math, Heap\n# link: <https://leetcode.com/problems/super-ugly-number/description/>\n# hidden: true\n# ---\n# \n# Write a program to find the `nth` super ugly number.\n# \n# Super ugly numbers are positive numbers whose all prime factors are in the\n# given prime list `primes` of size `k`.\n# \n# **Example:**\n# \n#     \n#     \n#     Input: n = 12, primes = [2,7,13,19]\n#     Output: 32 \n#     Explanation:[1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 \n#                  super ugly numbers given primes = [2,7,13,19] of size 4.\n# \n# **Note:**\n# \n#   * `1` is a super ugly number for any given `primes`.\n#   * The given numbers in `primes` are in ascending order.\n#   * 0 < `k` ≤ 100, 0 < `n` ≤ 106, 0 < `primes[i]` < 1000.\n#   * The nth super ugly number is guaranteed to fit in a 32-bit signed integer.\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction nth_super_ugly_number(n::Int, primes::Vector{Int})\n    dp = fill(1, n)\n    len = length(primes)\n    cur_min = primes[:]\n    ptrs = fill(1, len)\n    \n    @inbounds for i in 2:n\n        minn = minimum(cur_min)\n        dp[i] = minn\n        @simd for pidx in 1:len\n            if minn == cur_min[pidx]\n                ptrs[pidx] += 1\n                cur_min[pidx] = dp[ptrs[pidx]] * primes[pidx]\n            end\n        end\n    end\n    return dp[end]\nend\n## @lc code=end\n", "meta": {"hexsha": "9bb378b00250269e4caae5ee77a8f33e170dc5bc", "size": 1455, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/313.super-ugly-number.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/313.super-ugly-number.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/313.super-ugly-number.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 25.9821428571, "max_line_length": 83, "alphanum_fraction": 0.581443299, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7675265078087417}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Plots\nend;\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.11\"\n\n# ╔═╡ 1aa41898-3afa-11eb-2f49-570853ce6435\nbegin\n\tmu, sig = 2, 3\n\teta = sqrt(3)*sig/pi\n\tn, N = 15, 10^7\n\tdNormal   = Normal(mu, sig)\n\tdLogistic = Logistic(mu, eta)\n\txGrid = -8:0.1:12\n\n\tsNormal   = [var(rand(dNormal,n)) for _ in 1:N]\n\tsLogistic = [var(rand(dLogistic,n)) for _ in 1:N]\nend;\n\n# ╔═╡ 2eb0846a-3b2b-11eb-1154-ff7ca71f3c27\nbegin\n\tp1 = plot(xGrid, pdf.(dNormal,xGrid), c=:blue, label=\"Normal\")\n\tp1 = plot!(xGrid, pdf.(dLogistic,xGrid), c=:red, label=\"Logistic\", \n\t\txlabel=\"x\",ylabel=\"Density\", xlims= (-8,12), ylims=(0,0.16))\n\n\tp2 = stephist(sNormal, bins=200, c=:blue, normed=true, label=\"Normal\")\n\tp2 = stephist!(sLogistic, bins=200, c=:red, normed=true, label=\"Logistic\", \n\t\txlabel=\"Sample Variance\", ylabel=\"Density\", xlims=(0,30), ylims=(0,0.14))\n\n\tplot(p1, p2, size=(800, 400))\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.11\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═1aa41898-3afa-11eb-2f49-570853ce6435\n# ╠═2eb0846a-3b2b-11eb-1154-ff7ca71f3c27\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "5712a7057eadb883be03ec0fc138302281c02fa5", "size": 1473, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/06/listing6.11.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/06/listing6.11.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/06/listing6.11.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 26.7818181818, "max_line_length": 76, "alphanum_fraction": 0.6945010183, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087946129329, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7675265061711594}}
{"text": "#==============================================================================\n    Code for solving the Hamiltonian Jacboi Bellman for\n\t   a problem with non-convexities as in Skiba 1978\n\n\tTranslated Julia code from Matlab code by Ben Moll:\n        http://www.princeton.edu/~moll/HACTproject.htm\n==============================================================================#\n\nusing Plots, SparseArrays, LinearAlgebra\n\n\nγ= 2.0 #gamma parameter for CRRA utility\nρ = 0.05 #the discount rate\nα = 0.3 # the curvature of the production function (cobb-douglas)\nδ = 0.05 # the depreciation rate\nAH = 0.6 #high prodictivity, costs κ\nAL = 0.4 #low prodictivity, free\nκ = 2 #fixed cost\n\nkssH = (α*AH/(ρ+δ))^(1/(1-α))+κ\nk_st = κ./(1-(AL/AH).^(1/α))\n\n\n# create the grid for k\nH = 1000 #number of points on grid\nk_min = 0.001*kssH # min value\nk_max = 1.3*kssH # max value\nk = LinRange(k_min, k_max, H)\ndk = (k_max-k_min)/(H-1)\n\n#Create the production function\nyH = AH*max.(k.-κ,0).^α #high productivity\nyL = AL*k.^α #low prodictivity\ny = max.(yH,yL)\n\nplot(k,y, ylabel=\"\\$f(k)\\$\", xlabel=\"\\$k\\$\",\n\t\txlims=(k_min,k_max), ylims=(0,0.9),legend=false,color=:black)\nplot!(k,yH, line=:dash, color=:red)\nplot!(k,yL, line=:dashdot, color=:orange)\n\n# use Ito's lemma to find the drift and variance of our optimization equation\n\nmaxit = 150 #needed to increase this for same results in julia\nε = 10^(-6)\nΔ = 1000\n# set up all of these empty matrices\ndVf, dVb, dV0, c, If, Ib, I0, V= [zeros(H,1) for i in 1:8]\n\n# Now it's time to solve the model, first put in a guess for the value function\nv0 = (k.^α).^(1-γ)/(1-γ)/ρ\nv=v0\n\ndist = [] # set up empty array for the convergence criteria\n\nfor n = 1:maxit\n    global V=v\n\n    #Now set up the forward difference\n\n    dVf[1:H-1] = (V[2:H] - V[1:H-1])/dk\n    dVf[H] = (y[H]-δ.*k_max).^(-γ) # imposes a constraint\n\n    #backward difference\n    dVb[2:H] = (V[2:H] - V[1:H-1])/dk\n    dVb[1] = (y[1]-δ.*k_min).^(-γ)\n\n    #I_concave = Vab .> Vaf # indicator for whether the value function is concave\n\n    # Consumption and savings functions\n    cf = max.(dVf,10^(-10)).^(-1/γ)\n\tμf = y -δ.*k -cf\n    Hf = cf.^(1-γ)/(1-γ) + dVf.*μf\n\n    # consumption and saving backwards difference\n\n\tcb = max.(dVb,10^(-10)).^(-1/γ)\n\tμb = y -δ.*k -cb\n    Hb = cb.^(1-γ)/(1-γ) + dVb.*μb\n\n    #consumption and derivative of the value function at the steady state\n\n    c0 = y- δ.*k\n    dV0 = max.(c0, 10^(-10)).^(-γ)\n\tH0 = c0.^(1-γ)/(1-γ)\n\n    # Upwind scheme chooses between the forward or backward difference\n\tIeither = (1 .- (μf.>0)) .* (1 .- (μb.<0))\n\tIunique = (μb.<0).*(1 .- (μf.>0)) + (1 .- (μb.<0)).*(μf.>0)\n\tIboth = (μb.<0).*(μf.>0)\n    If= Iunique.*(μf .> 0) + Iboth.*(Hf.>=Hb)  #positive drift → forward difference\n    Ib = Iunique.*(μb .< 0) + Iboth.*(Hb.>=Hf) #negative drift → backward difference\n    I0 = Ieither  #at steady state\n\n    global c = cf.*If + cb.*Ib + c0.*I0\n    u = (c.^(1-γ))/(1-γ)\n\n\t# CONSTRUCT MATRIX\n    global X = -μb.*Ib/dk\n    global Y = - μf.*If/dk  + μb.*Ib/dk\n    global Z = μf.*If/dk\n\n\tglobal A = spdiagm(0=>Y[:], -1=>X[2:end], 1=>Z[1:end-1])\n\n\n  \tB = (1/Δ + ρ)*sparse(I, H, H) - A\n\n  \tu_stacked= reshape(u, H, 1)\n  \tV_stacked = reshape(V,H, 1)\n\n  \tb = u_stacked + (V_stacked/Δ)\n\n  \tV_stacked = B\\b\n\n  \tglobal V = reshape(V_stacked, H, 1)\n\n  \tV_change = V-v\n\n  \tglobal v= V\n\n  \t# need push function to add to an already existing array\n  \tpush!(dist, findmax(abs.(V_change))[1])\n  \tif dist[n].< ε\n      \tprintln(\"Value Function Converged Iteration=\")\n      \tprintln(n)\n      \tbreak\n  \tend\n\nend\n\n# calculate the savings for kk\nkdot = y -δ.*k -c\ndV_upwind = dVf.*If + dVb.*Ib+dV0.*I0\nVerr = c.^(1-γ)/(1-γ) + dV_upwind.*kdot - ρ.*V\n\n#plot for consumption\nplot(k, c, ylabel=\"\\$c(k)\\$\", xlabel=\"\\$k\\$\", label=\"Consumption\")\nplot!(k,y-δ.*k, label=\"Production net of depreciation\", legend=:bottomright)\n\n#plot for savings\nplot(k, kdot, ylabel=\"\\$s(k)\\$\", xlabel=\"\\$k\\$\", legend=false) \nplot!(k,zeros(H,1), line=:dash)\n\n#Plot the value function\nplot(k, V,ylabel=\"\\$V(k)\\$\", xlabel=\"\\$k\\$\", legend=false)\n\n#Plot the error in HJB equation\nplot(k,Verr,ylabel=\"Value Function error\", xlabel=\"\\$k\\$\", legend=false)\n", "meta": {"hexsha": "27db7de45b8dbabab4f82c38c664cb5dfe9f9dc9", "size": 4133, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Moll_Code/Section06-Handling-Non-Convexities-Skiba/HJN_NGM_Skiba.jl", "max_stars_repo_name": "chandlerlester/Radio_Free_Julia", "max_stars_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-02-26T11:52:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T12:41:38.000Z", "max_issues_repo_path": "Moll_Code/Section06-Handling-Non-Convexities-Skiba/HJN_NGM_Skiba.jl", "max_issues_repo_name": "chandlerlester/Radio_Free_Julia", "max_issues_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Moll_Code/Section06-Handling-Non-Convexities-Skiba/HJN_NGM_Skiba.jl", "max_forks_repo_name": "chandlerlester/Radio_Free_Julia", "max_forks_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-11T08:09:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-30T18:54:12.000Z", "avg_line_length": 27.9256756757, "max_line_length": 84, "alphanum_fraction": 0.5872247762, "num_tokens": 1531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129327, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7675265002254489}}
{"text": "#!/usr/bin/julia\n\nusing DataFrames\n\nsrand(46)\n\nSAMPLES = 100\nITERS=200\nITERS_p=200\n\nvalues = readdlm(\"SDvalues.dat\") |> vec\n# A = 5 + randn(10000)\n# B = -5 + randn(10000)\n# values = vcat(A,B)\ninfo(\"Real mean: $(mean(values))\")\n\nfunction bootstrap(array, frac; N=1000)\n    L = length(array)\n    chunksize = floor(Int64,frac*L)\n    0 < chunksize ≤ L || error(\"chunksize = $chunksize ∉ (0,L)\")\n    means = zeros(N)\n    for i ∈ 1:N\n        chunk = rand(array,chunksize)\n        means[i] = mean(chunk)\n    end\n    return mean(means), std(means)\nend\n\nfunction jacknife(array)\n    L = length(array)\n    means = zeros(L)\n    for i ∈ 1:L\n        means[i] = mean(array[j] for j in 1:L if j≠i)\n    end\n    return mean(means), std(means)\nend\n\njdf = DataFrame()\nbdf = DataFrame()\n\n\nfr = 1/e\nfor i in 1:ITERS\n    smallsample = rand(values,SAMPLES)\n    jackμ, jackσ = jacknife(smallsample)\n    bootμ, bootσ = bootstrap(smallsample, fr)\n    jdf = vcat(jdf, DataFrame(i=i,\n                              μ=jackμ,\n                              σ=jackσ))\n    bdf = vcat(bdf, DataFrame(i=i,\n                              fraction=fr,\n                              μ=bootμ,\n                              σ=bootσ))\nend\n\nwritetable(\"data_jack.csv\", jdf)\nwritetable(\"data_boot.csv\", bdf)\n", "meta": {"hexsha": "7befca5f918893e50896176a40e98555b8358626", "size": 1263, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "study_cases/bootstrap/boot.jl", "max_stars_repo_name": "RedPointyJackson/tfg", "max_stars_repo_head_hexsha": "20e25150e749849ef0efea95e2d6d053614cb08d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "study_cases/bootstrap/boot.jl", "max_issues_repo_name": "RedPointyJackson/tfg", "max_issues_repo_head_hexsha": "20e25150e749849ef0efea95e2d6d053614cb08d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "study_cases/bootstrap/boot.jl", "max_forks_repo_name": "RedPointyJackson/tfg", "max_forks_repo_head_hexsha": "20e25150e749849ef0efea95e2d6d053614cb08d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.775862069, "max_line_length": 64, "alphanum_fraction": 0.5526524149, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7675264991924855}}
{"text": "# Linear Interpolation\nfunction (A::LinearInterpolation{<:AbstractVector{<:Number}})(t::Number)\n  idx = findfirst(x->x>=t,A.t)-1\n  idx == 0 ? idx += 1 : nothing\n  θ = (t - A.t[idx])/ (A.t[idx+1] - A.t[idx])\n  (1-θ)*A.u[idx] + θ*A.u[idx+1]\nend\n\nfunction (A::LinearInterpolation{<:AbstractMatrix{<:Number}})(t::Number)\n  idx = findfirst(x->x>=t,A.t)-1\n  idx == 0 ? idx += 1 : nothing\n  θ = (t - A.t[idx])/ (A.t[idx+1] - A.t[idx])\n  (1-θ)*A.u[:,idx] + θ*A.u[:,idx+1]\nend\n\n# Quadratic Interpolation\nfunction (A::QuadraticInterpolation{<:AbstractVector{<:Number}})(t::Number)\n  idx = findfirst(x->x>=t,A.t)-1\n  idx == 0 ? idx += 1 : nothing\n  if idx == length(A.t) - 1\n    i₀ = idx - 1; i₁ = idx; i₂ = i₁ + 1;\n  else\n    i₀ = idx; i₁ = i₀ + 1; i₂ = i₁ + 1;\n  end\n  l₀ = ((t-A.t[i₁])*(t-A.t[i₂]))/((A.t[i₀]-A.t[i₁])*(A.t[i₀]-A.t[i₂]))\n  l₁ = ((t-A.t[i₀])*(t-A.t[i₂]))/((A.t[i₁]-A.t[i₀])*(A.t[i₁]-A.t[i₂]))\n  l₂ = ((t-A.t[i₀])*(t-A.t[i₁]))/((A.t[i₂]-A.t[i₀])*(A.t[i₂]-A.t[i₁]))\n  A.u[i₀]*l₀ + A.u[i₁]*l₁ + A.u[i₂]*l₂\nend\n\nfunction (A::QuadraticInterpolation{<:AbstractMatrix{<:Number}})(t::Number)\n  idx = findfirst(x->x>=t,A.t)-1\n  idx == 0 ? idx += 1 : nothing\n  if idx == length(A.t) - 1\n    i₀ = idx - 1; i₁ = idx; i₂ = i₁ + 1;\n  else\n    i₀ = idx; i₁ = i₀ + 1; i₂ = i₁ + 1;\n  end\n  l₀ = ((t-A.t[i₁])*(t-A.t[i₂]))/((A.t[i₀]-A.t[i₁])*(A.t[i₀]-A.t[i₂]))\n  l₁ = ((t-A.t[i₀])*(t-A.t[i₂]))/((A.t[i₁]-A.t[i₀])*(A.t[i₁]-A.t[i₂]))\n  l₂ = ((t-A.t[i₀])*(t-A.t[i₁]))/((A.t[i₂]-A.t[i₀])*(A.t[i₂]-A.t[i₁]))\n  A.u[:,i₀]*l₀ + A.u[:,i₁]*l₁ + A.u[:,i₂]*l₂\nend\n\n# Lagrange Interpolation\nfunction (A::LagrangeInterpolation{<:AbstractVector{<:Number}})(t::Number)\n  idxs = findRequiredIdxs(A,t)\n  if A.t[idxs[1]] == t\n    return A.u[idxs[1]]\n  end\n  N = zero(A.u[1]); D = zero(A.t[1]); tmp = N\n  for i = 1:length(idxs)\n    mult = one(A.t[1])\n    for j = 1:(i-1)\n      mult *= (A.t[idxs[i]] - A.t[idxs[j]])\n    end\n    for j = (i+1):length(idxs)\n      mult *= (A.t[idxs[i]] - A.t[idxs[j]])\n    end\n    tmp = inv((t - A.t[idxs[i]]) * mult)\n    D += tmp\n    N += (tmp * A.u[idxs[i]])\n  end\n  N/D\nend\n\nfunction (A::LagrangeInterpolation{<:AbstractMatrix{<:Number}})(t::Number)\n  idxs = findRequiredIdxs(A,t)\n  if A.t[idxs[1]] == t\n    return A.u[:,idxs[1]]\n  end\n  N = zero(A.u[:,1]); D = zero(A.t[1]); tmp = D\n  for i = 1:length(idxs)\n    mult = one(A.t[1])\n    for j = 1:(i-1)\n      mult *= (A.t[idxs[i]] - A.t[idxs[j]])\n    end\n    for j = (i+1):length(idxs)\n      mult *= (A.t[idxs[i]] - A.t[idxs[j]])\n    end\n    tmp = inv((t - A.t[idxs[i]]) * mult)\n    D += tmp\n    @. N += (tmp * A.u[:,idxs[i]])\n  end\n  N/D\nend\n\nfunction (A::AkimaInterpolation{<:AbstractVector{<:Number}})(t::Number)\n  i = searchsortedlast(A.t, t)\n  i == 0 && return A.u[1]\n  i == length(A.t) && return A.u[end]\n  wj = t - A.t[i]\n  @evalpoly wj A.u[i] A.b[i] A.c[i] A.d[i]\nend\n\n# ConstantInterpolation Interpolation\nfunction (A::ConstantInterpolation{<:AbstractVector})(t::Number)\n  if A.dir === :left\n    # :left means that value to the left is used for interpolation\n    i = searchsortedlast(A.t, t)\n    return A.u[max(1, i)]\n  else\n    # :right means that value to the right is used for interpolation\n    i = searchsortedfirst(A.t, t)\n    return A.u[min(length(A.t), i)]\n  end\nend\n function (A::ConstantInterpolation{<:AbstractMatrix})(t::Number)\n  if A.dir === :left\n    # :left means that value to the left is used for interpolation\n    i = searchsortedlast(A.t, t)\n    return A.u[:, max(1, i)]\n  else\n    # :right means that value to the right is used for interpolation\n    i = searchsortedfirst(A.t, t)\n    return A.u[:, min(length(A.t), i)]\n  end\nend\n\n# QuadraticSpline Interpolation\nfunction (A::QuadraticSpline{<:AbstractVector{<:Number}})(t::Number)\n  i = findfirst(x->x>=t,A.t)\n  i == 1 ? i += 1 : nothing\n  Cᵢ = A.u[i-1]\n  σ = 1//2 * (A.z[i] - A.z[i-1])/(A.t[i] - A.t[i-1])\n  A.z[i-1] * (t - A.t[i-1]) + σ * (t - A.t[i-1])^2 + Cᵢ\nend\n\n# CubicSpline Interpolation\nfunction (A::CubicSpline{<:AbstractVector{<:Number}})(t::Number)\n  i = findfirst(x->x>=t,A.t)\n  i == nothing ? i = length(A.t) - 1 : i -= 1\n  i == 0 ? i += 1 : nothing\n  I = A.z[i] * (A.t[i+1] - t)^3 / (6A.h[i+1]) + A.z[i+1] * (t - A.t[i])^3 / (6A.h[i+1])\n  C = (A.u[i+1]/A.h[i+1] - A.z[i+1]*A.h[i+1]/6)*(t - A.t[i])\n  D = (A.u[i]/A.h[i+1] - A.z[i]*A.h[i+1]/6)*(A.t[i+1] - t)\n  I + C + D\nend\n\n# BSpline Curve Interpolation\nfunction (A::BSplineInterpolation{<:AbstractVector{<:Number}})(t::Number)\n  # change t into param [0 1]\n  idx = searchsortedlast(A.t,t)\n  idx == length(A.t) ? idx -= 1 : nothing\n  t = A.p[idx] + (t - A.t[idx])/(A.t[idx+1] - A.t[idx]) * (A.p[idx+1] - A.p[idx])\n  n = length(A.t)\n  N = spline_coefficients(n,A.d,A.k,t)\n  ucum = zero(eltype(A.u))\n  for i = 1:n\n    ucum += N[i] * A.c[i]\n  end\n  ucum\nend\n\n# BSpline Curve Approx\nfunction (A::BSplineApprox{<:AbstractVector{<:Number}})(t::Number)\n  # change t into param [0 1]\n  idx = searchsortedlast(A.t,t)\n  idx == length(A.t) ? idx -= 1 : nothing\n  t = A.p[idx] + (t - A.t[idx])/(A.t[idx+1] - A.t[idx]) * (A.p[idx+1] - A.p[idx])\n  n = length(A.t)\n  N = spline_coefficients(A.h,A.d,A.k,t)\n  ucum = zero(eltype(A.u))\n  for i = 1:A.h\n    ucum += N[i] * A.c[i]\n  end\n  ucum\nend\n\n# Curvefit\nfunction (A::CurvefitCache{<:AbstractVector{<:Number}})(t::Union{AbstractVector{<:Number},Number})\n  A.m(t,A.pmin)\nend\n", "meta": {"hexsha": "876d03f2502e004807554070afbdc3458e28e152", "size": 5301, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/interpolation_methods.jl", "max_stars_repo_name": "baggepinnen/DataInterpolations.jl", "max_stars_repo_head_hexsha": "66ea2b0b8e760821dbbc8e5789b075c51600b8ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/interpolation_methods.jl", "max_issues_repo_name": "baggepinnen/DataInterpolations.jl", "max_issues_repo_head_hexsha": "66ea2b0b8e760821dbbc8e5789b075c51600b8ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/interpolation_methods.jl", "max_forks_repo_name": "baggepinnen/DataInterpolations.jl", "max_forks_repo_head_hexsha": "66ea2b0b8e760821dbbc8e5789b075c51600b8ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4655172414, "max_line_length": 98, "alphanum_fraction": 0.5483870968, "num_tokens": 2198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129329, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7675264982435456}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 303488a5-8102-4077-8cad-12655d8c5777\nbegin\n\tusing ScikitLearn\n\tusing Statistics\n\tusing StatsBase: sample\n\tusing DataFrames\n\tusing CSV\n\tusing Bootstrap\nend\n\n# ╔═╡ 6790c593-f5d3-4e45-be83-c974e581bbf2\nmd\"\"\"\n# Bootstrap Notes pt. 2\n\nThis document will work through Jason Brownlee's article [A Gentle Introduction to the Bootstrap Method](https://machinelearningmastery.com/a-gentle-introduction-to-the-bootstrap-method/). This is my second document on this method, so I'll try to be more concise. I'll be translating the python in the article to Julia. \n\nFurther down in this document, I'll work on another of Brownlee's articles, [How to Calculate Bootstrap Confidence Intervals For Machine Learning Results in Python\n](https://machinelearningmastery.com/calculate-bootstrap-confidence-intervals-machine-learning-results-python/).\n\nDate: 2022 April 23\n\"\"\"\n\n# ╔═╡ 8b12df14-0a1f-4fc4-8677-02f26f16e1d6\nmd\"\"\"\n---\nThe bootstrap method is a **resampling technique** used to estimate statistics on a population. It can be used to estimate **summary statistics** on a population such as the mean or standard deviation. It is used to estimate the skill of a model when making predictions on data not in the training set.\n\nThis method provides us confidence intervals which is something cross-validation does not.\n\nThis article will teach us:\n\n - The bootstrap method involves iteratively resampling a dataset with replacement.\n - The bootstrap method has two parameters, the size of the sample and the number of repeats.\n - Scikit-learn provides a resampling funciton. (Note, Julia provides a wrapper for ScikitLearn)\n\"\"\"\n\n# ╔═╡ 1023b0ba-fc8e-4d49-b795-ed3d75004b69\nmd\"\"\"\n## Bootstrap Method\n\nFirst, get one sample from the data set. This is done by choosing a random set of observations to add to the sample. I.e. this is done *without* replacement.\n\nThen, we draw bootstrap samples from this original sample, but this time *with* replacement. We calculate the statistic on each sample, then calculate the mean of those statistics.\n\nHow would we use this method in the case of statistical inference?\n\nFor each bootstrap sample:\n1. Fit a model on this sample\n2. Estimate the skill on the model on the out-of-bag sample\n\nThen calculate the mean of the sample of model skill estimates.\n\n*Note*: The model is evaluated against the samples that weren't selected, *not* against the test dataset, which we can't use until we want to fully evluate the model. The data in the original sample but not the bootstrap sample are called out-of-bag (oob).\n\n*Note*: A useful feature of the bootstrap method is that the resulting sample often forms a normal distribution.\n\n\"\"\"\n\n# ╔═╡ 66d8365c-cb3a-4a85-8da3-00eab0e1d1eb\nmd\"\"\"\n## Example\n\nIn this example, we have a dataset with 6 elements. We will be using the entire dataset to create our EDF, meaning we can sample from the whole thing to create our bootstrap samples. \n\n\"\"\"\n\n# ╔═╡ 1a0f56fa-94a9-420f-b318-b6a0f197b140\ndataset = 0.1:0.1:0.6\n\n# ╔═╡ 8b712ac8-37fe-4c0e-98c1-495f632ed305\nbegin\n\tsampleset = [0.2, 0.1, 0.2, 0.6] # we can have repeats\n\toob    = [0.3, 0.4, 0.5] # everything not in sample\nend\n\n# ╔═╡ ef6a30bf-2f90-486d-879d-a1a089a89c84\n\n\n# ╔═╡ 68ad9943-a5a8-492f-8c5b-93bc7b49d36f\nmd\"\"\"\nNote that above, we have a single sample (that we made by hand instead of actually using random sampling). This would be sufficient for a single iteration of the bootstrap procedure.\n\nThe rest of this iteration would look as follows:\n1. Fit the model on `sample`\n2. Evaluate the model on `oob`\n\n## ScikitLearn\n\nWe can use ScikitLearn's `resample` method to generate the sample for us, but I'm not quite sure how to use the interface so I'll leave this one here.\n\"\"\"\n\n# ╔═╡ 4006c742-dc11-403d-b921-459b64ddd3c2\nmd\"\"\"\n# Bootstrap Confidence Intervals\n\nNow we'll get to the second article, as promised. \n\nStep 1 is to do our bootstrap sampling:\n\n```julia\nB = 1000\nstats = [calculate_stat(sample(data,N,replace=True)) for _ in 1:B]\n```\n\nWe can get an **Empirical Confidence Interval** by simply sorting this list and taking the values at the percentile we are interested in. For intance if we want a 95% confidence interval, we take our interval to be the range starting at the 2.5 percentil and ending at the 97.5 percentile. \n\n```julia\nalpha=0.95\nordered = sort(stats)\nlower = quantile(ordered, (1-alpha)/2)\nupper = quantile9ordered, (alpha+((1-alpha)/2))\n```\n\"\"\"\n\n# ╔═╡ e74d5d8f-7d69-4e32-a036-c711194d216e\nmd\"\"\"\n## Calculate Classification Accuracy Confidence Interval\n\nWe'll read our dataset into a dataframe first.\n\"\"\"\n\n# ╔═╡ 54890bac-8050-4141-8e7e-2fb603bfe3b8\ndata = CSV.read(\"./datasets/pima-indians-diabetes.data.csv\", DataFrame; \n\t\t\t\theader=false)\n\n# ╔═╡ b8ccebb7-b303-4315-94fb-8ff253a90271\nbegin\n\tn_iterations = 1\n\tn_size = trunc(Int64, nrow(data)*0.5)\n\tstats = Array{Int64, n_iterations}\nend\n\n# ╔═╡ bde70fbd-d415-4d6b-b1d0-6eaba93012b9\n#for i in 1:1\n#\ttrain = bootstrap(data, )\n#\ttrain = sample(std, data, BasicSampling(n_size))\n#\t#test = setdiff(data, train)\n#end\n\n# ╔═╡ 0148021c-b8a8-4c47-bcbe-3eae9ef6e75d\nbootstrap(std, data[!, \"Column6\"], BasicSampling(n_iterations))\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nBootstrap = \"e28b5b4c-05e8-5b66-bc03-6f0c0a0a06e0\"\nCSV = \"336ed68f-0bac-5ca0-87d4-7b16caf5d00b\"\nDataFrames = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nScikitLearn = \"3646fa90-6ef7-5e7e-9f22-8aca16db6324\"\nStatistics = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\nStatsBase = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\n\n[compat]\nBootstrap = \"~2.3.3\"\nCSV = \"~0.10.4\"\nDataFrames = \"~1.3.3\"\nScikitLearn = \"~0.6.4\"\nStatsBase = \"~0.33.16\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\njulia_version = \"1.7.1\"\nmanifest_format = \"2.0\"\n\n[[deps.ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[deps.Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[deps.Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[deps.Bootstrap]]\ndeps = [\"DataFrames\", \"Distributions\", \"Random\", \"Statistics\", \"StatsBase\", \"StatsModels\"]\ngit-tree-sha1 = \"fb4bdaa6c24fea362cc54965c3f645f7cfac659f\"\nuuid = \"e28b5b4c-05e8-5b66-bc03-6f0c0a0a06e0\"\nversion = \"2.3.3\"\n\n[[deps.CSV]]\ndeps = [\"CodecZlib\", \"Dates\", \"FilePathsBase\", \"InlineStrings\", \"Mmap\", \"Parsers\", \"PooledArrays\", \"SentinelArrays\", \"Tables\", \"Unicode\", \"WeakRefStrings\"]\ngit-tree-sha1 = \"873fb188a4b9d76549b81465b1f75c82aaf59238\"\nuuid = \"336ed68f-0bac-5ca0-87d4-7b16caf5d00b\"\nversion = \"0.10.4\"\n\n[[deps.ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"9950387274246d08af38f6eef8cb5480862a435f\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.14.0\"\n\n[[deps.ChangesOfVariables]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"bf98fa45a0a4cee295de98d4c1462be26345b9a1\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.2\"\n\n[[deps.CodecZlib]]\ndeps = [\"TranscodingStreams\", \"Zlib_jll\"]\ngit-tree-sha1 = \"ded953804d019afa9a3f98981d99b33e3db7b6da\"\nuuid = \"944b1d66-785c-5afd-91f1-9de20f533193\"\nversion = \"0.7.0\"\n\n[[deps.Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"b153278a25dd42c65abbf4e62344f9d22e59191b\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.43.0\"\n\n[[deps.CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[deps.Conda]]\ndeps = [\"Downloads\", \"JSON\", \"VersionParsing\"]\ngit-tree-sha1 = \"6e47d11ea2776bc5627421d59cdcc1296c058071\"\nuuid = \"8f4d0f93-b110-5947-807f-2305c1781a2d\"\nversion = \"1.7.0\"\n\n[[deps.Crayons]]\ngit-tree-sha1 = \"249fe38abf76d48563e2f4556bebd215aa317e15\"\nuuid = \"a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f\"\nversion = \"4.1.1\"\n\n[[deps.DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[deps.DataFrames]]\ndeps = [\"Compat\", \"DataAPI\", \"Future\", \"InvertedIndices\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"Markdown\", \"Missings\", \"PooledArrays\", \"PrettyTables\", \"Printf\", \"REPL\", \"Reexport\", \"SortingAlgorithms\", \"Statistics\", \"TableTraits\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"6c19003824cbebd804a51211fd3bbd81bf1ecad5\"\nuuid = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nversion = \"1.3.3\"\n\n[[deps.DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"3daef5523dd2e769dad2365274f760ff5f282c7d\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.11\"\n\n[[deps.DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[deps.Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[deps.DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[deps.DensityInterface]]\ndeps = [\"InverseFunctions\", \"Test\"]\ngit-tree-sha1 = \"80c3e8639e3353e5d2912fb3a1916b8455e2494b\"\nuuid = \"b429d917-457f-4dbc-8f4c-0cc954292b1d\"\nversion = \"0.4.0\"\n\n[[deps.Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[deps.Distributions]]\ndeps = [\"ChainRulesCore\", \"DensityInterface\", \"FillArrays\", \"LinearAlgebra\", \"PDMats\", \"Printf\", \"QuadGK\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"Test\"]\ngit-tree-sha1 = \"5a4168170ede913a2cd679e53c2123cb4b889795\"\nuuid = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nversion = \"0.25.53\"\n\n[[deps.DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[deps.Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[deps.FilePathsBase]]\ndeps = [\"Compat\", \"Dates\", \"Mmap\", \"Printf\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"129b104185df66e408edd6625d480b7f9e9823a0\"\nuuid = \"48062228-2e41-5def-b9a4-89aafe57970f\"\nversion = \"0.9.18\"\n\n[[deps.FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"246621d23d1f43e3b9c368bf3b72b2331a27c286\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.13.2\"\n\n[[deps.Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[deps.Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[deps.InlineStrings]]\ndeps = [\"Parsers\"]\ngit-tree-sha1 = \"61feba885fac3a407465726d0c330b3055df897f\"\nuuid = \"842dd82b-1e85-43dc-bf29-5d0ee9dffc48\"\nversion = \"1.1.2\"\n\n[[deps.InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[deps.InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"91b5dcf362c5add98049e6c29ee756910b03051d\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.3\"\n\n[[deps.InvertedIndices]]\ngit-tree-sha1 = \"bee5f1ef5bf65df56bdd2e40447590b272a5471f\"\nuuid = \"41ab1584-1d38-5bbf-9106-f11c6c58b48f\"\nversion = \"1.1.0\"\n\n[[deps.IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[deps.IterTools]]\ngit-tree-sha1 = \"fa6287a4469f5e048d763df38279ee729fbd44e5\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.4.0\"\n\n[[deps.IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[deps.JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"abc9885a7ca2052a736a600f7fa66209f96506e1\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.4.1\"\n\n[[deps.JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"3c837543ddb02250ef42f4738347454f95079d4e\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.3\"\n\n[[deps.LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[deps.LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[deps.LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[deps.LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[deps.Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[deps.LinearAlgebra]]\ndeps = [\"Libdl\", \"libblastrampoline_jll\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[deps.LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"a970d55c2ad8084ca317a4658ba6ce99b7523571\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.12\"\n\n[[deps.Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[deps.MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[deps.Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[deps.MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[deps.Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[deps.Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[deps.MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[deps.NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[deps.OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[deps.OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[deps.OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[deps.OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[deps.PDMats]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"SuiteSparse\"]\ngit-tree-sha1 = \"e8185b83b9fc56eb6456200e873ce598ebc7f262\"\nuuid = \"90014a1f-27ba-587c-ab20-58faa44d9150\"\nversion = \"0.11.7\"\n\n[[deps.Parameters]]\ndeps = [\"OrderedCollections\", \"UnPack\"]\ngit-tree-sha1 = \"34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe\"\nuuid = \"d96e819e-fc66-5662-9728-84c9c7592b0a\"\nversion = \"0.12.3\"\n\n[[deps.Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"3b429f37de37f1fc603cc1de4a799dc7fbe4c0b6\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.3.0\"\n\n[[deps.Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[deps.PooledArrays]]\ndeps = [\"DataAPI\", \"Future\"]\ngit-tree-sha1 = \"28ef6c7ce353f0b35d0df0d5930e0d072c1f5b9b\"\nuuid = \"2dfb63ee-cc39-5dd5-95bd-886bf059d720\"\nversion = \"1.4.1\"\n\n[[deps.Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"47e5f437cc0e7ef2ce8406ce1e7e24d44915f88d\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.3.0\"\n\n[[deps.PrettyTables]]\ndeps = [\"Crayons\", \"Formatting\", \"Markdown\", \"Reexport\", \"Tables\"]\ngit-tree-sha1 = \"dfb54c4e414caa595a1f2ed759b160f5a3ddcba5\"\nuuid = \"08abe8d2-0d0c-5749-adfa-8a2ac140af0d\"\nversion = \"1.3.1\"\n\n[[deps.Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[deps.PyCall]]\ndeps = [\"Conda\", \"Dates\", \"Libdl\", \"LinearAlgebra\", \"MacroTools\", \"Serialization\", \"VersionParsing\"]\ngit-tree-sha1 = \"1fc929f47d7c151c839c5fc1375929766fb8edcc\"\nuuid = \"438e738f-606a-5dbb-bf0a-cddfbfd45ab0\"\nversion = \"1.93.1\"\n\n[[deps.QuadGK]]\ndeps = [\"DataStructures\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"78aadffb3efd2155af139781b8a8df1ef279ea39\"\nuuid = \"1fd47b50-473d-5c70-9696-f719f8f3bcdc\"\nversion = \"2.4.2\"\n\n[[deps.REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[deps.Random]]\ndeps = [\"SHA\", \"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[deps.Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[deps.Rmath]]\ndeps = [\"Random\", \"Rmath_jll\"]\ngit-tree-sha1 = \"bf3188feca147ce108c76ad82c2792c57abe7b1f\"\nuuid = \"79098fc4-a85e-5d69-aa6a-4863f24498fa\"\nversion = \"0.7.0\"\n\n[[deps.Rmath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"68db32dff12bb6127bac73c209881191bf0efbb7\"\nuuid = \"f50d1b31-88e8-58de-be2c-1cc44531875f\"\nversion = \"0.3.0+0\"\n\n[[deps.SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[deps.ScikitLearn]]\ndeps = [\"Compat\", \"Conda\", \"DataFrames\", \"Distributed\", \"IterTools\", \"LinearAlgebra\", \"MacroTools\", \"Parameters\", \"Printf\", \"PyCall\", \"Random\", \"ScikitLearnBase\", \"SparseArrays\", \"StatsBase\", \"VersionParsing\"]\ngit-tree-sha1 = \"ccb822ff4222fcf6ff43bbdbd7b80332690f168e\"\nuuid = \"3646fa90-6ef7-5e7e-9f22-8aca16db6324\"\nversion = \"0.6.4\"\n\n[[deps.ScikitLearnBase]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"7877e55c1523a4b336b433da39c8e8c08d2f221f\"\nuuid = \"6e75b9c4-186b-50bd-896f-2d2496a4843e\"\nversion = \"0.5.0\"\n\n[[deps.SentinelArrays]]\ndeps = [\"Dates\", \"Random\"]\ngit-tree-sha1 = \"6a2f7d70512d205ca8c7ee31bfa9f142fe74310c\"\nuuid = \"91c51154-3ec4-41a3-a24f-3f23e20d615c\"\nversion = \"1.3.12\"\n\n[[deps.Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[deps.SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[deps.ShiftedArrays]]\ngit-tree-sha1 = \"22395afdcf37d6709a5a0766cc4a5ca52cb85ea0\"\nuuid = \"1277b4bf-5013-50f5-be3d-901d8477a67a\"\nversion = \"1.0.0\"\n\n[[deps.Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[deps.SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[deps.SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[deps.SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"5ba658aeecaaf96923dce0da9e703bd1fe7666f9\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"2.1.4\"\n\n[[deps.Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[deps.StatsAPI]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"c82aaa13b44ea00134f8c9c89819477bd3986ecd\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.3.0\"\n\n[[deps.StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"8977b17906b0a1cc74ab2e3a05faa16cf08a8291\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.16\"\n\n[[deps.StatsFuns]]\ndeps = [\"ChainRulesCore\", \"InverseFunctions\", \"IrrationalConstants\", \"LogExpFunctions\", \"Reexport\", \"Rmath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"5950925ff997ed6fb3e985dcce8eb1ba42a0bbe7\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.18\"\n\n[[deps.StatsModels]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"Printf\", \"REPL\", \"ShiftedArrays\", \"SparseArrays\", \"StatsBase\", \"StatsFuns\", \"Tables\"]\ngit-tree-sha1 = \"03c99c7ef267c8526953cafe3c4239656693b8ab\"\nuuid = \"3eaba693-59b7-5ba5-a881-562e759f1c8d\"\nversion = \"0.6.29\"\n\n[[deps.SuiteSparse]]\ndeps = [\"Libdl\", \"LinearAlgebra\", \"Serialization\", \"SparseArrays\"]\nuuid = \"4607b0f0-06f3-5cda-b6b1-a6196a1729e9\"\n\n[[deps.TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[deps.TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[deps.Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"OrderedCollections\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"5ce79ce186cc678bbb5c5681ca3379d1ddae11a1\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.7.0\"\n\n[[deps.Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[deps.Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[deps.TranscodingStreams]]\ndeps = [\"Random\", \"Test\"]\ngit-tree-sha1 = \"216b95ea110b5972db65aa90f88d8d89dcb8851c\"\nuuid = \"3bb67fe8-82b1-5028-8e26-92a6c54297fa\"\nversion = \"0.9.6\"\n\n[[deps.UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[deps.UnPack]]\ngit-tree-sha1 = \"387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b\"\nuuid = \"3a884ed6-31ef-47d7-9d2a-63182c4928ed\"\nversion = \"1.0.2\"\n\n[[deps.Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[deps.VersionParsing]]\ngit-tree-sha1 = \"58d6e80b4ee071f5efd07fda82cb9fbe17200868\"\nuuid = \"81def892-9a0e-5fdd-b105-ffc91e053289\"\nversion = \"1.3.0\"\n\n[[deps.WeakRefStrings]]\ndeps = [\"DataAPI\", \"InlineStrings\", \"Parsers\"]\ngit-tree-sha1 = \"b1be2855ed9ed8eac54e5caff2afcdb442d52c23\"\nuuid = \"ea10d353-3f73-51f8-a26c-33c1cb351aa5\"\nversion = \"1.4.2\"\n\n[[deps.Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[deps.libblastrampoline_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"OpenBLAS_jll\"]\nuuid = \"8e850b90-86db-534c-a0d3-1478176c7d93\"\n\n[[deps.nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[deps.p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╠═303488a5-8102-4077-8cad-12655d8c5777\n# ╟─6790c593-f5d3-4e45-be83-c974e581bbf2\n# ╟─8b12df14-0a1f-4fc4-8677-02f26f16e1d6\n# ╟─1023b0ba-fc8e-4d49-b795-ed3d75004b69\n# ╟─66d8365c-cb3a-4a85-8da3-00eab0e1d1eb\n# ╠═1a0f56fa-94a9-420f-b318-b6a0f197b140\n# ╠═8b712ac8-37fe-4c0e-98c1-495f632ed305\n# ╠═ef6a30bf-2f90-486d-879d-a1a089a89c84\n# ╟─68ad9943-a5a8-492f-8c5b-93bc7b49d36f\n# ╟─4006c742-dc11-403d-b921-459b64ddd3c2\n# ╠═e74d5d8f-7d69-4e32-a036-c711194d216e\n# ╠═54890bac-8050-4141-8e7e-2fb603bfe3b8\n# ╠═b8ccebb7-b303-4315-94fb-8ff253a90271\n# ╠═bde70fbd-d415-4d6b-b1d0-6eaba93012b9\n# ╠═0148021c-b8a8-4c47-bcbe-3eae9ef6e75d\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "2af6c2ca2272087afa45dc6713c963f704450b1d", "size": 22745, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "stats/bootstrap02.jl", "max_stars_repo_name": "plavin/plavin.github.io", "max_stars_repo_head_hexsha": "4afaf1fbe1bd0b8c0cadf5da5618ac776dcb264c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stats/bootstrap02.jl", "max_issues_repo_name": "plavin/plavin.github.io", "max_issues_repo_head_hexsha": "4afaf1fbe1bd0b8c0cadf5da5618ac776dcb264c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stats/bootstrap02.jl", "max_forks_repo_name": "plavin/plavin.github.io", "max_forks_repo_head_hexsha": "4afaf1fbe1bd0b8c0cadf5da5618ac776dcb264c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8210678211, "max_line_length": 320, "alphanum_fraction": 0.7435040668, "num_tokens": 9434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8947894618940992, "lm_q1q2_score": 0.7675218676008219}}
{"text": "#========================================================================================#\n#\tLaboratory 10\n#\n# Working with arrays.\n#\n# Author: Niall Palfreyman, 22/03/2022\n#========================================================================================#\n[\n\tActivity(\n\t\t\"\"\"\n\t\tArrays play a very fundamental role in Julia, so we need to learn how to deal with them\n\t\tefficiently. In this laboratory we learn how to index into arrays in Julia - that is,\n\t\thow to use indices to access and manipulate the entries in an array. We will also look\n\t\tat various ways of applying code to the elements in an array.\n\t\t\n\t\tJulia offers four kinds of indexing: SUBSCRIPTING, LINEAR indexing, MULTIPLE indexing\n\t\tand LOGICAL indexing. All four are extremely useful for scientific programming. To\n\t\tinvestigate these forms of indexing, first create a (4x4) matrix by reshaping a range:\n\n\t\t\tm = reshape(1:16,(4,4))\n\n\t\tFirst notice the order in which Julia has placed the numbers 1:16. Do they run down the\n\t\tcolumns or along the rows?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> occursin(\"col\",lowercase(x))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tSo: SUBSCRIPTING! To access a matrix element with subscripts, we use square brackets\n\t\tenclosing two subscripts i (row) and j (column) like this: m[i,j]. In Julia, the row\n\t\tindex ALWAYS comes before the column index! Display the element m[3,4[] now, then tell\n\t\tme its value:\n\t\t\"\"\",\n\t\t\"Just enter m[3,4] at the Julia prompt\",\n\t\tx -> x==15\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWe have already used the colon operator to create ranges of numbers, for example 1:3 can\n\t\tbe collected into a vector [1,2,3]. We can also use ranges to select regions of an array.\n\t\tUse m[1:3,2:4] to display the top-right (3×3) region of m, then tell me the result\n\t\t(Remember you can use reply(ans) to tell me the result of the previous calculation):\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x == [5 9 13;6 10 14;7 11 15]\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\t1:2:7 creates a range of numbers from 1 to 7 in steps of 2: [1,3,5,7]. Reshape 1:81 into a\n\t\t(9×9) matrix, then extract from it the (3×3) matrix obtained by taking the first, then\n\t\tevery third, row and column of your (9×9) matrix. Then tell me the result:\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x == [1 28 55;4 31 58;7 34 61]\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWe can select a whole row or column by writing \":\". Display and tell me the third row of m:\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x == [3 7 11 15]\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tTo assign values to regions of a matrix, we select the desired matrix range and assign to it\n\t\ta value. However, we should first be aware of something important. Tell me the type of m:\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x <: Base.ReshapedArray\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tNotice that m only LOOKS like an ordinary matrix, but is actually a reshaped range, so Julia\n\t\twill not let us change its value by writing to it. To see this, try out the following:\n\n\t\t\tm[2:3,3:4] .= 1\n\n\t\tThen tell me the name of the function that the error message recommends we use:\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> occursin(\"collect\",lowercase(x))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tLet's take the error message's advice:\n\t\t\n\t\t\tm = collect(m)\n\t\t\tm[2:3,3:4] .= 1\n\n\t\tNow tell me the new value of m:\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x == [1 5 9 13;2 6 1 1;3 7 1 1;4 8 12 16]\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tAnd what is the type of m now?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x <: Matrix\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWhat kind of error do you get if you try to add an element outside the size of the array m:\n\n\t\t\tm[5,1] = 1\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> occursin(\"bounds\",lowercase(x))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tAlthough we can't add elements outside m's bounds, we can extend the size of m by adding\n\t\tnew rows or columns: Blank ' ' adds columns (hcat: horizontal concatenation), and\n\t\tsemicolon ';' adds rows (vcat: vertical concatenation). Tell me the result of this line:\n\n\t\t\tp = ones(4)\n\t\t\tpp = [m p]\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> size(x) == (4,5)\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tAnd what is the result of this line of code?\n\n\t\t\tq = ones(4)'\n\t\t\tqq = [m;q]\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> size(x) == (5,4)\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tOK, now let's look at LINEAR indexing! Internally, Julia represents all arrays as vectors =\n\t\tit simply makes this vector look like a matrix to us. Create the following matrix:\n\n\t\t\tA = [1 2 3;4 5 6]\n\n\t\tIf we just enter A at the Julia prompt, we see a (2×3) matrix, but if you enter A[:], you\n\t\twill see a list of all elements of A in a linear order. Does this order first run down the\n\t\tcolumns or along the rows?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> occursin(\"col\",lowercase(x))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWe can use the linear ordering to index the elements of A. What is the value of A[5]?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==3\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWe can also use linear indexing to change the elements of A. What is the contents of A\n\t\tafter entering this line of code?\n\n\t\t\tA[5] = 99\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> [1 2 99;4 5 6]\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tArrays can have MULTIPLE indices: Vectors have one index and Matrices have two, but we\n\t\tcan have 3, 4, 5, ...! Of course we need to be a bit careful with the size of these arrays:\n\t\tA size (10) Vector contains 10 elements; a size (10,10) Matrix contains 100 elements. How\n\t\tmany elements will there be in a size (10,10,10,10) array?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x == 1e4\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWe can create multiply indexed arrays using zeros(), ones(), rand(), randn() or reshape().\n\t\tA 3-dimensional array might represent 3-dimensional data, such as a chemical concentration\n\t\tat various locations in a cell, or it might represent the time-series of elements of a\n\t\tmatrix A(t). In this case, A[3,5,4] might represent the element [3,5] at time t=4 of the\n\t\ttime-series.\n\n\t\tEnter R = rand(2,3,4); at the Julia prompt, and study the following expressions:\n\n\t\t\tR[1,:,:]\n\t\t\tR[]:,1,:]\n\t\t\tR[]:,:,1]\n\t\t\tsize(R)\n\t\t\n\t\tHow many elements does R contain?\n\t\t\"\"\",\n\t\t\"Use the length function\",\n\t\tx -> x == 24\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tHere is a (4,4) magic square:\n\n\t\t\tA = [1 15 14 4;10 11 8 5;7 6 9 12;16 2 3 13]\n\n\t\tUse Julia's sum() function to find the sum of A's elements along any row, column or\n\t\tdiagonal:\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==34\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWe can generate new magic squares by swapping columns of an existing magic square. Study\n\t\tthe matrix B = A(:,[1,3,2,4]). Is this also a magic square (remember that rows, columns and\n\t\tdiagonals of a magic square must all sum to the same number)? Which substructures of A were\n\t\tpermuted by using the Vector [1,3,2,4] as a permutation index?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> occursin(\"col\",lowercase(x))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tUse a permutation index to swap ROWS 2 and 3 of A, and tell me the result:\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x == [1 15 14 4;7 6 9 12;10 11 8 5;16 2 3 13]\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tLOGICAL indexing uses an array of logical values as an index to another array. For example,\n\t\tsuppose we want to reduce to zero all elements less than 3 in the Vector v = [1,2,3,4,5].\n\t\tOne way would be to access each individual element in v, check whether it is less than 3,\n\t\tand set it to zero. But this would be very inefficient, because accessing each individual\n\t\telement costs time. Instead, we can use LOGICAL indexing to change the entire vector v in\n\t\tone sweep ...\n\n\t\tFirst, create the Vector v. Then tell me the result of entering this line:\n\n\t\t\td = (v .< 3)\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x == [1,1,0,0,0]\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWhat is the type of the elements of d?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x == Bool\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tNotice that d is a Vector of Bools with the same length as v. We can use d to index\n\t\telements of v:\n\n\t\t\tv[d]\n\n\t\tHow many elements of v does d pick out?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x == 2\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tNow enter this line:\n\n\t\t\tv[d] .= 0\n\n\t\tYou will see that this zeros out all elements of v that are less than 3. If you recreate\n\t\tv, you can even condense this entire process into one step:\n\n\t\t\tv = collect(1:5)\n\t\t\tv[v.<3] .= 0\n\n\t\tNow set to zero all numbers in the vector -5:2:5 which are greater than 2, and tell me\n\t\tthe number of non-zero elements in your result:\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x == 4\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tBefore continuing, let's look at several different ways to apply some code to all elements\n\t\tin an array. If the code is just one function, this is easy: we just use the broadcast\n\t\tdot (.):\n\n\t\t\tv = 1:7\n\t\t\tisodd.(v)\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x == isodd.(1:7)\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tIf the code is a little more complicated, we might map() an anonymous function over\n\t\tthe array:\n\n\t\t\tmap( x->(sin(x) >= 0), v)\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x == map( y->(sin(y) >= 0), 1:7)\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tAnd finally, if the code is particularly complicated, we can use a do statement that\n\t\tallows us to define a complicated mapping over all elements of the array:\n\t\t\t\n\t\t\tmap(v) do x\n\t\t\t\tif x < 4\n\t\t\t\t\tisodd(x)\n\t\t\t\telse\n\t\t\t\t\tiseven(x)\n\t\t\t\tend\n\t\t\tend\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x == (map(1:7) do y if y<4 isodd(y) else iseven(y) end end)\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tOK, now the last two activities in this laboratory give you practice in applying indexing,\n\t\tbroadcasting and mapping to problems that often arise in signal-processing. Have fun! :)\n\n\t\tUse logical indexing to generate a list of all odd multiples of 3 in the range 1:50 :\n\t\t\"\"\",\n\t\t\"Use isodd(), rem(), &, and remember to use broadcasts (.) and brackets\",\n\t\tx -> x == [3,9,15,21,27,33,39,45]\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tThis function decides whether or not its argument n is a prime number:\n\n\t\t\tfunction isprime(n::Int)\n\t\t\t\tif n < 2 return false end\n\t\t\t\tif n in 2:3 return true end\n\t\t\t\tfor i in 2:floor(Int,sqrt(n))\n\t\t\t\t\tif rem(n,i) == 0 return false end\n\t\t\t\tend\n\t\t\t\ttrue\n\t\t\tend\n\n\t\tUse the isprime function to generate a list of twenty numbers from 1 to 20, in which\n\t\tall prime numbers AND all multiples of 3 are zeroed out:\n\t\t\"\"\",\n\t\t\"Use rem(), isprime() and |\",\n\t\tx -> x == [1,0,0,4,0,0,0,8,0,10,0,0,0,14,0,16,0,0,0,20]\n\t),\n]", "meta": {"hexsha": "59c8d6b685f0de31410d3d5d6c4269f53f3de27d", "size": 9664, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Labs/INLab010.jl", "max_stars_repo_name": "cspsych/Ingolstadt.jl", "max_stars_repo_head_hexsha": "204cf94397b83994ae70a1ce4984fe648512bb6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Labs/INLab010.jl", "max_issues_repo_name": "cspsych/Ingolstadt.jl", "max_issues_repo_head_hexsha": "204cf94397b83994ae70a1ce4984fe648512bb6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/INLab010.jl", "max_forks_repo_name": "cspsych/Ingolstadt.jl", "max_forks_repo_head_hexsha": "204cf94397b83994ae70a1ce4984fe648512bb6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0930232558, "max_line_length": 94, "alphanum_fraction": 0.6264486755, "num_tokens": 3068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.894789452074398, "lm_q1q2_score": 0.7675218656846007}}
{"text": "# This example came from the R package ggm.\n\nusing StructuralCausalModels\n\nProjDir = @__DIR__\ncd(ProjDir)\n\ndf = DataFrame!(CSV.File(scm_path(\"..\", \"data\", \"marks.csv\")));\n\n#=\nR_dag = \"\n           mechanics vectors algebra statistics analysis\nmechanics          0       0       0          0        0\nvectors            1       0       0          0        0\nalgebra            1       1       0          1        1\nstatistics         0       0       0          0        0\nanalysis           0       0       0          1        0\n\";\n=#\n\nd = from_ggm(\"DAG(\n    mechanics ~ vectors+algebra, \n    vectors ~ algebra, \n    statistics ~ algebra+analysis, \n    analysis ~ algebra)\"\n)\ndisplay(d)\n\n# DAG accepts either an OrderedDict, an adjacency_matrix or a ggm/dagitty string.\n# Below d_string holds a ggm DAG definition.\n\nd_string = \"DAG(\n    mechanics ~ vectors+algebra, \n    vectors ~ algebra, \n    statistics ~ algebra+analysis, \n    analysis ~ algebra)\"\n\ndag = DAG(\"marks\", d_string, df=df);\nshow(dag)\n\nfname = ProjDir * \"/marks.dot\"\nto_graphviz(dag, fname)\nSys.isapple() && run(`open -a GraphViz.app $(fname)`)\n\ndisplay(dag.s); println()\n\nbs = basis_set(dag)\ndisplay(bs); println()\n\nt = shipley_test(dag)\ndisplay(\"shipley_test = $t\"); println()\n\npt = pcor_test(dag, [:analysis, :statistics, :mechanics], 1, 88)\ndisplay(\"pcor_test = $pt\"); println()\n\nf = [:statistics]; s = [:mechanics]; sel = vcat(f, s)\n\ne = d_separation(dag, f, s; c=:algebra)\nprintln(\"d_separation($(dag.name), $f, $s; c=:algebra) = $e\")\n\ne = d_separation(dag, f, s)\nprintln(\"d_separation($(dag.name), $f, $s) = $e\")\n\nprint(\"d_separation($(dag.name), [:statistics], [:mechanics]; c=[:vectors]) = \")\nprintln(d_separation(dag, [:statistics], [:mechanics]; c=[:vectors]))\n\nprint(\"d_separation($(dag.name), [:statistics], [:mechanics]; c=[:analysis, :vectors]) = \")\nprintln(d_separation(dag, [:statistics], [:mechanics]; c=[:analysis, :vectors]))\n\nprint(\"d_separation($(dag.name), [:statistics, :analysis], [:mechanics]; c=[:algebra]) = \")\nprintln(d_separation(dag, [:statistics, :analysis], [:mechanics]; c=[:algebra]))\n\nprint(\"d_separation($(dag.name), [:statistics], [:mechanics, :vectors]; c=[:algebra]) = \")\nprintln(d_separation(dag, [:statistics], [:mechanics, :vectors]; c=[:algebra]))\n\nprint(\"d_separation($(dag.name), [:statistics], [:mechanics, :analysis]; c=[:algebra]) = \")\nprintln(d_separation(dag, [:statistics], [:mechanics, :analysis]; c=[:algebra]))\n\nprint(\"d_separation($(dag.name), [:analysis], [:vectors]) = \")\nprintln(d_separation(dag, [:analysis], [:vectors]))\n\nprint(\"d_separation($(dag.name), [:analysis], [:vectors]; c=[:algebra]) = \")\nprintln(d_separation(dag, [:analysis], [:vectors]; c=[:algebra]))\n\nprint(\"d_separation($(dag.name), [:vectors], [:statistics]; c=[:algebra]) = \")\nprintln(d_separation(dag, [:analysis], [:vectors]; c=[:algebra]))\n\nprint(\"d_separation($(dag.name), [:statistics], [:algebra]; c=[:analysis]) = \")\nprintln(d_separation(dag, [:statistics], [:algebra]; c=[:analysis]))\n\nprint(\"d_separation($(dag.name), [:statistics, :analysis], [:mechanics, :vectors]) = \")\nprintln(d_separation(dag, [:statistics, :analysis], [:mechanics, :vectors]))\n\nprint(\"d_separation($(dag.name), [:statistics, :analysis], [:mechanics, :vectors]; c=[:algebra]) = \")\nprintln(d_separation(dag, [:statistics, :analysis], [:mechanics, :vectors]; c=[:algebra]))\n\nadjustmentsets = adjustment_sets(dag, :statistics, :mechanics)\nprintln(\"\\nAdjustment sets:\")\nadjustmentsets |> display\n\nadjustmentsets = adjustment_sets(dag, :mechanics, :statistics)\nprintln(\"\\nAdjustment sets:\")\nadjustmentsets |> display\n\n#end\n", "meta": {"hexsha": "1cb220b5fdfba1e08c796094ab5764cf733d16d9", "size": 3591, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/marks/marks.jl", "max_stars_repo_name": "yadevi/StructuralCausalModels.jl", "max_stars_repo_head_hexsha": "f02ebbf9fd34a5d20eada979d171372d16555dfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-25T14:22:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-25T14:22:24.000Z", "max_issues_repo_path": "examples/marks/marks.jl", "max_issues_repo_name": "yadevi/StructuralCausalModels.jl", "max_issues_repo_head_hexsha": "f02ebbf9fd34a5d20eada979d171372d16555dfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/marks/marks.jl", "max_forks_repo_name": "yadevi/StructuralCausalModels.jl", "max_forks_repo_head_hexsha": "f02ebbf9fd34a5d20eada979d171372d16555dfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8773584906, "max_line_length": 101, "alphanum_fraction": 0.634642161, "num_tokens": 1065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7675218582640252}}
{"text": "using LinearAlgebra\nusing Statistics\n\n\nmutable struct LinearRegression\n    X\n    Y\n    n_data\n    input_dim\n    w\n    b\nend\n\n\nfunction LinearRegression(X, Y)\n    n_data, input_dim = size(X)\n    return LinearRegression(X, Y, n_data, input_dim, nothing, nothing)\nend\n\n\n# 2. 最小二乗法を用いてモデルパラメーターを最適化\nfunction train!(model::LinearRegression)\n    # 行列Xに「1」の要素を追加\n    ndim = model.n_data\n    Z = hcat(model.X, ones(ndim))\n\n    # 分母の計算\n    ZZ = 1 / ndim * Z' * Z\n\n    # 分子の計算\n    ZY = 1 / ndim * Z' * model.Y\n\n    # パラメーターvの最適化\n    # ZZ * v = ZY を解く\n    v = ZZ \\ ZY\n    model.w = v[1:end-1]\n    model.b = last(v)\n    model\nend\n\n# 3. 予測\n# X: 入力データ(データ数 x 次元数のArray)\npredict(model::LinearRegression, x) = x * model.w .+ model.b\n\n# 4. 平方平均二乗誤差(Root Mean Squared Error)\n# X: 入力データ(データ数 x 次元数のArray)\n# Y: 出力データ(データ数 x 1のArray)\nrmse(model::LinearRegression, x, y) = sqrt.(mean((predict(model, x) - y).^2))\n\n# 5. 決定係数の計算\n# X: 入力データ(データ数 x 次元数のArray)\n# Y: 出力データ(データ数 x 1のArray)\nfunction r2(model::LinearRegression, x, y)\n    sq = sum((predict(model, x) - y).^2)\n    vr = sum((y .- mean(y; dims=1)).^2)\n    return 1 - sq / vr\nend\n\n# L2ノルム正則化最小二乗法を用いてモデルパラメーターを最適化\n# lamb: 正則化の重み係数(実数スカラー)\nfunction train_regularized!(model::LinearRegression, lamb=0.1)\n    # 行列Xに「1」の要素を追加\n    ndim = model.n_data\n    Z = hcat(model.X, ones(ndim))\n\n    # 分母の計算\n    ZZ = 1 / ndim * Z' * Z + lamb * I\n\n    # 分子の計算\n    ZY = 1 / ndim * Z' * model.Y\n\n    # パラメーターvの最適化\n    # ZZ * v = ZY を解く\n    v = ZZ \\ ZY\n    model.w = v[1:end-1]\n    model.b = last(v)\n    model\nend", "meta": {"hexsha": "a35f889a45d09c9ff944959abfbb9813747bded3", "size": 1526, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear_regression.jl", "max_stars_repo_name": "matsueushi/machine-learning-from-scratch-with-julia", "max_stars_repo_head_hexsha": "46ee819a59df9e73bee5ec166d9bf9548ee3a803", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/linear_regression.jl", "max_issues_repo_name": "matsueushi/machine-learning-from-scratch-with-julia", "max_issues_repo_head_hexsha": "46ee819a59df9e73bee5ec166d9bf9548ee3a803", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/linear_regression.jl", "max_forks_repo_name": "matsueushi/machine-learning-from-scratch-with-julia", "max_forks_repo_head_hexsha": "46ee819a59df9e73bee5ec166d9bf9548ee3a803", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5641025641, "max_line_length": 77, "alphanum_fraction": 0.6068152031, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885904, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7674934942266022}}
{"text": "using SemiDiscretizationMethod\n\nfunction createMathieuProblem(δ,ε,b0,a1;T=2π)\n    AMx =  ProportionalMX(t->@SMatrix [0. 1.; -δ-ε*cos(2π/T*t) -a1]);\n    τ1=2π # if function is needed, the use τ1 = t->foo(t)\n    BMx1 = DelayMX(τ1,t->@SMatrix [0. 0.; b0 0.]);\n    cVec = Additive(t->@SVector [0.,sin(4π/T*t)])\n    LDDEProblem(AMx,[BMx1],cVec)\nend;\n\nτmax=2π # the largest τ of the system\nT=2π #Principle period of the system (sin(t)=sin(t+P)) \nmathieu_lddep=createMathieuProblem(3.,2.,-0.15,0.1,T=T); # LDDE problem for Hayes equation\nmethod=SemiDiscretization(1,0.01) # 3rd order semi discretization with Δt=0.1\n# if P = τmax, then n_steps is automatically calculated\nmapping=DiscreteMapping_1step(mathieu_lddep,method,τmax,\n    n_steps=Int((T+100eps(T))÷method.Δt),calculate_additive=true); #The discrete mapping of the system\n\n@show spectralRadiusOfMapping(mapping); # spectral radius ρ of the mapping matrix (ρ>1 unstable, ρ<1 stable)\nfp=fixPointOfMapping(mapping); # stationary solution of the hayes equation (equilibrium position)\n\n\nplot(0.0:method.Δt:P,fp[1:2:end],\n    xlabel=L\"-s\",title=L\"t \\in [nP,(n+1)P],\\quad n \\to \\infty\",guidefontsize=14,linewidth=3,\n    label=L\"x(t-s)\",legendfontsize=11,tickfont = font(10))\n\nplot!(0.0:method.Δt:P,fp[2:2:end],\n    xlabel=L\"-s\",linewidth=3,\n    label=L\"\\dot{x}(t-s)\")\n\nplot!(0.0:method.Δt:P,sin.(2*(0.0:method.Δt:P)),linewidth=3,label=L\"\\sin(2t)\")\n\n\n\n\n\n\n\nusing MDBM\n\nusing Plots\ngr();\nusing LaTeXStrings\n\na1=0.1;\nε=1;\nτmax=2π;\nT=1π;\nmethod=SemiDiscretization(2,T/40);\n\nfoo(δ,b0) = log(spectralRadiusOfMapping(DiscreteMapping_1step(createMathieuProblem(δ,ε,b0,a1,T=T),method,τmax,\n    n_steps=Int((T+100eps(T))÷method.Δt)))); # No additive term calculated\n\naxis=[Axis(-1:0.2:5.,:δ),\n    Axis(-2:0.2:1.5,:b0)]\n\niteration=3;\nstab_border_points=getinterpolatedsolution(solve!(MDBM_Problem(foo,axis),iteration));\n\nscatter(stab_border_points...,xlim=(-1.,5),ylim=(-2.,1.5),\n    label=\"\",title=\"Stability border of the delay Mathieu equation\",xlabel=L\"\\delta\",ylabel=L\"b_0\",\n    guidefontsize=14,tickfont = font(10),markersize=2,markerstrokewidth=0)\n\n\n", "meta": {"hexsha": "4dc31c8151f43cdd474835d6a0f865a50757fc1f", "size": 2091, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/DelayMatheiu.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SemiDiscretizationMethod.jl-a6865705-0aff-55fc-a8e1-34d7b6815716", "max_stars_repo_head_hexsha": "2385af071561ca59510e9864196331e0c70d2d06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/DelayMatheiu.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SemiDiscretizationMethod.jl-a6865705-0aff-55fc-a8e1-34d7b6815716", "max_issues_repo_head_hexsha": "2385af071561ca59510e9864196331e0c70d2d06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-04-02T17:56:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-16T07:35:06.000Z", "max_forks_repo_path": "examples/DelayMatheiu.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SemiDiscretizationMethod.jl-a6865705-0aff-55fc-a8e1-34d7b6815716", "max_forks_repo_head_hexsha": "2385af071561ca59510e9864196331e0c70d2d06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1692307692, "max_line_length": 110, "alphanum_fraction": 0.7044476327, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768635777511, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7674905103804531}}
{"text": "module LogisticRegression2\nusing Revise\nusing Flux\nusing Flux: binarycrossentropy, throttle, @epochs\nusing Flux: Descent, TrackedArray, param, data\nusing Distributions\nusing LinearAlgebra\nusing Random\nusing Plots\nusing Base.Iterators: repeated\n\ntheme(:juno)\n\n# Generate data\nD = 2;   # Data dimension\nn = 100; # Number of observations\nx1 = rand(MvNormal([1., -5.], I), n);\nx2 = rand(MvNormal([-2., -1.5], I), n);\ny1 = repeat([1], n);\ny2 = repeat([0], n);\n\nclassOneColor = :orange\nclassTwoColor = RGBA(0,.2,.7,1);\np = scatter(x1[1, :], x1[2, :], label=\"Class 1\", color=classOneColor)\nscatter!(p, x2[1, :], x2[2, :], label=\"Class 2\", color=classTwoColor)\nX = transpose([x1 x2]);\ny = [y1; y2];\n\n# Create model\nstruct LogisticRegression\n    α :: TrackedArray # bias\n    β :: TrackedArray # weights\n    LogisticRegression(α :: Array, β :: Array) = new(param(α), param(β))\nend\n\nfunction (m :: LogisticRegression)(X)\n    σ.(m.α .+ X*m.β)\nend\n\n\nfunction plot_decision_surface(m, xlim :: Tuple{Int, Int}, ylim :: Tuple{Int, Int})\n    x = xlim[1]:0.5:xlim[2]\n    y = ylim[1]:0.5:ylim[2]\n    f = (x, y) -> (first ∘ data ∘ m)([x y])\n    contour(x, y, f, fill = true, color = :pu_or)\nend\n\n\nfunction plot_fit(m)\n    xlim = ylim = (-8, 8)\n    p = plot_decision_surface(m, xlim, ylim)\n    scatter!(p, x1[1, :], x1[2, :], label=\"Class 1\", color=classOneColor)\n    scatter!(p, x2[1, :], x2[2, :], label=\"Class 2\", color=classTwoColor)\n    p\nend\n\nfunction plot_loss(losses)\n    plot(1:length(losses), losses)\nend\n\n\nfunction create_animation(αs :: Array, βs :: Array)\n    anim = @animate for (α, β) in zip(αs, βs)\n        m = LogisticRegression(α, β)\n        display(plot_fit(m))\n    end\n\n    gif(anim, \"plots/transition.gif\", fps = 60)\nend\n\n\nm = LogisticRegression(rand(1), rand(D, 1)); display(plot_fit(m));\nθ = Flux.params(m.α, m.β);\nnumEpochs = 100;\nloss = (x, y) -> mean(binarycrossentropy.(m(x), y));\n\nlosses, αs, βs = [], [], []\ncb = () -> begin\n    l = Flux.data(loss(X, y));\n    push!(losses, l);\n    push!(αs, Flux.data(m.α));\n    push!(βs, Flux.data(m.β));\nend\n\ndataset = repeated((X, y), numEpochs)\nFlux.train!(loss, θ, dataset, Descent(0.1), cb = cb)\n\nplot_loss(losses)\nplot_fit(m)\n\ncreate_animation(αs, βs)\n\nend\n", "meta": {"hexsha": "d6716429f02209707d730e1eb4f9825f982c0042", "size": 2206, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/log-reg-2.jl", "max_stars_repo_name": "SebastianCallh/julia-baby-steps", "max_stars_repo_head_hexsha": "dd3cae1c92a7e3bb315aa8031591ffa7e4ff4b96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/log-reg-2.jl", "max_issues_repo_name": "SebastianCallh/julia-baby-steps", "max_issues_repo_head_hexsha": "dd3cae1c92a7e3bb315aa8031591ffa7e4ff4b96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/log-reg-2.jl", "max_forks_repo_name": "SebastianCallh/julia-baby-steps", "max_forks_repo_head_hexsha": "dd3cae1c92a7e3bb315aa8031591ffa7e4ff4b96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4680851064, "max_line_length": 83, "alphanum_fraction": 0.6251133273, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653855, "lm_q2_score": 0.8128673087708698, "lm_q1q2_score": 0.7674905022696392}}
{"text": "# Polyharmonic functions used below.\nfunction polyharmonic_phi1(r) return r; end\nfunction polyharmonic_phi2(r) return r>1e-16 ? r^2 * log(r) : r; end\nfunction polyharmonic_phi3(r) return r^3; end\nfunction polyharmonic_phi4(r) return r>1e-16 ? r^4 * log(r) : r^3; end\n\n# Uses polyharmonic interpolation to interpolate at x using values u at centers c.\n# sizes are:\n# x is d x nx\n# c is d x nc\n# u is nc\n# (optional) ord determines the type of basis function. default is 3. 1,2,3,4 are available\nfunction polyharmonic_interp(x, c, u, ord=3)\n    dim = size(x,1);\n    nx = size(x,2); # number of places to evaluate\n    \n    # If no centers are provided, this is meaningless, but return zero.\n    if length(c)==0\n        return zeros(nx);\n    end\n    \n    nc = size(c,2); # number of centers\n    \n    # Constant if only one center is given\n    if nc == 1\n        return u[1] .* ones(nx);\n    end\n    \n    if ord == 1\n        phi = polyharmonic_phi1;\n    elseif ord == 2\n        phi = polyharmonic_phi2;\n    elseif ord == 3\n        phi = polyharmonic_phi3;\n    else\n        phi = polyharmonic_phi4;\n    end\n    \n    # build A matrix\n    A = zeros(nc + dim+1, nc + dim+1);\n    for i=1:nc\n        for j=1:nc\n            A[i,j] = phi(norm(c[:,j] - c[:,i]));\n        end\n    end\n    # build B matrix (within A matrix)\n    A[1:nc, nc+1] .= 1;\n    A[nc+1, 1:nc] .= 1;\n    A[1:nc, (nc+2):(nc+dim+1)] = c';\n    A[(nc+2):(nc+dim+1), 1:nc] = c;\n    \n    # build RHS vector\n    b = vcat(u, zeros(dim+1));\n    \n    wv = A\\b; # coefficients for the polyharmonic\n    \n    sol = zeros(nx);\n    for i=1:nx\n        # evaluate at x[i]\n        sol[i] = wv[nc+1];\n        for k=1:dim\n            sol[i] += wv[nc+k+1] * x[k,i];\n        end\n        for j=1:nc\n            sol[i] += wv[j]*phi(norm(c[:,j] - x[:,i]));\n        end\n    end\n    \n    return sol;\nend", "meta": {"hexsha": "8653691a66b8c9aeaf345838b8418b28c02f36f7", "size": 1832, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polyharmonic_interp.jl", "max_stars_repo_name": "aa25desh/femshop", "max_stars_repo_head_hexsha": "8a75639ea0b7740d378b3f863bd6584f4cdd5ec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-02T17:45:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T20:55:57.000Z", "max_issues_repo_path": "src/polyharmonic_interp.jl", "max_issues_repo_name": "aa25desh/femshop", "max_issues_repo_head_hexsha": "8a75639ea0b7740d378b3f863bd6584f4cdd5ec1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-12-15T16:03:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-24T16:10:55.000Z", "max_forks_repo_path": "src/polyharmonic_interp.jl", "max_forks_repo_name": "aa25desh/femshop", "max_forks_repo_head_hexsha": "8a75639ea0b7740d378b3f863bd6584f4cdd5ec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-10T17:48:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-19T12:12:49.000Z", "avg_line_length": 26.1714285714, "max_line_length": 91, "alphanum_fraction": 0.547489083, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7674566684553652}}
{"text": "#\n# Cubic fit\n#\n\nstruct Cubic\n  a :: Float64\n  b :: Float64\n  c :: Float64\n  d :: Float64\n  R :: Float64\n  x :: Vector{Float64}\n  y :: Vector{Float64}\n  ypred :: Vector{Float64}\n  residues :: Vector{Float64}\nend\n\nfunction fitcubic(X :: AbstractVector, Y :: AbstractVector, options :: Options)\n  X, Y = checkdata(X,Y)\n  @. model(x,p) = p[1]*x^3 + p[2]*x^2 + p[3]*x + p[4]\n  fit = find_best_fit(model, X, Y, 4, options)\n  R = pearson(X,Y,model,fit)\n  x, y, ypred = finexy(X,options.fine,model,fit) \n  return Cubic(fit.param...,R,x,y,ypred,fit.resid)\nend\nfitcubic(X :: AbstractVector, Y :: AbstractVector) = fitcubic(X,Y,Options())\n\nfunction Base.show( io :: IO, fit :: Cubic )\n  println(\"\")\n  println(\" ------------------- Cubic Fit ----------------- \")\n  println(\"\")\n  println(\" Equation: y = ax^3 + bx^2 + cx + d \")\n  println(\"\")\n  println(\" With: a = \", fit.a)\n  println(\"       b = \", fit.b)\n  println(\"       c = \", fit.c)\n  println(\"       d = \", fit.d)\n  println(\"\")\n  println(\" Pearson correlation coefficient, R = \", fit.R)\n  println(\"\")\n  println(\" Predicted Y: ypred = [\",fit.ypred[1],\", \",fit.ypred[2],\"...\")\n  println(\" residues = [\", fit.residues[1],\", \",fit.residues[2],\"...\")\n  println(\"\")\n  println(\" ----------------------------------------------- \")\nend\n\nexport fitcubic\n", "meta": {"hexsha": "7fd5d668b33fd2aa5e1f0db0d953b98f2b3d2441", "size": 1288, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cubic.jl", "max_stars_repo_name": "m3g/EasyF", "max_stars_repo_head_hexsha": "601df86cb3927a195d91558a4027bb5e949771c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-04-07T12:58:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T13:42:50.000Z", "max_issues_repo_path": "src/cubic.jl", "max_issues_repo_name": "m3g/EasyF", "max_issues_repo_head_hexsha": "601df86cb3927a195d91558a4027bb5e949771c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-17T14:34:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-24T14:19:10.000Z", "max_forks_repo_path": "src/cubic.jl", "max_forks_repo_name": "m3g/EasyFit.jl", "max_forks_repo_head_hexsha": "601df86cb3927a195d91558a4027bb5e949771c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-08-19T20:58:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-17T18:43:12.000Z", "avg_line_length": 27.4042553191, "max_line_length": 79, "alphanum_fraction": 0.5458074534, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331958, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7674566659009934}}
{"text": "using Printf\nimport Flux: σ\nusing ModelingToolkit\nusing GalacticOptim\nusing Optim\nusing DiffEqFlux\nusing NeuralPDE\nusing Quadrature, Cubature, Cuba\nusing Plots\n\n@parameters t,x,y\n@variables c(..)\n@derivatives Dt'~t\n@derivatives Dxx''~x\n@derivatives Dyy''~y\n@derivatives Dx'~x\n@derivatives Dy'~y\n\n# Parameters\n\nu = 1.0\nv = 1.0\nv_vector = (u, v)\nR = 0\nD = 0 # 0.1 # diffusion\nt_max = 2.0\nx_min = -1.0\nx_max = 1.0\ny_min = -1.0\ny_max = 1.0\n\n# exp(-(x^2+y^2)/0.1)\n# div(v_vector * c) = dx(uc) + dy(vc)\n# Equations, initial and boundary conditions\neqs = [ Dt(c(t,x,y)) ~ D * (Dxx(c(t,x,y)) + Dyy(c(t,x,y))) - (u*Dx(c(t,x,y)) + v*Dy(c(t,x,y))) + R]\n\nbcs = [ \n        c(0, x, y) ~ exp(-(x^2+y^2)/0.1), #cos(π*x) * cos(π*y) + 1.0,  \n        c(t, x_min, y) ~ c(t, x_max, y),\n        c(t, x, y_min) ~ c(t, x, y_max)\n]\n\n# Space and time domains\ndomains = [t ∈ IntervalDomain(0.0,t_max),\n        x ∈ IntervalDomain(x_min,x_max),\n        y ∈ IntervalDomain(y_min,y_max)\n]\n\n# Discretization\nnx = 32\n# ny = 32\ndx = (x_max-x_min) / (nx - 1)\n# dy = (y_max-y_min) / (ny -1)\ndt = 0.01\n\n# Neural network\ndim = length(domains)\noutput = length(eqs)\nhidden = 32\n\nchain = FastChain( FastDense(dim, hidden, tanh),\n                    FastDense(hidden, hidden, tanh),\n                    FastDense(hidden, 1))\n\n# strategy = GridTraining(dx=[dt,dx,dy])\nstrategy = StochasticTraining(900)\n\ndiscretization = PhysicsInformedNN(chain, strategy=strategy)\n\npde_system = PDESystem(eqs, bcs, domains, [t,x,y], [c])\nprob = discretize(pde_system,discretization)\n\ncb = function (p,l)\n    println(\"Current loss is: $l\")\n    return false\nend\n\nres = GalacticOptim.solve(prob,ADAM();cb=cb,maxiters=100)\n\n\n# Plots\n\nphi = discretization.phi\n\ninitθ = discretization.initθ\n\nacum =  [0;accumulate(+, length.(initθ))]\nsep = [acum[i]+1 : acum[i+1] for i in 1:length(acum)-1]\nminimizers = [res.minimizer[s] for s in sep]\nts,xs,ys = [domain.domain.lower:dx:domain.domain.upper for domain in domains]\n\n# Plot initial condition\nc_predict = reshape([ phi([0, x, y], res.minimizer)[1] for x in xs for y in ys], length(xs), length(ys))\nplot(xs, ys, c_predict)\n\n# Animate\nanim = @animate for (i, t) in enumerate(0:dt:t_max)\n    @info \"Animating frame $i...\"\n    c_predict = reshape([phi([t, x, y], res.minimizer)[1] for x in xs for y in ys], length(xs), length(ys))\n    title = @sprintf(\"Advection-diffusion t = %.3f\", t)\n    heatmap(xs, ys, c_predict, label=\"\", title=title , xlims=(-1, 1), ylims=(-1, 1), color=:thermal, clims=(0, 1))\nend\n\ngif(anim, \"advection_diffusion_2d_pinn.gif\", fps=15)\n\n\n# Plot correct solution\nusing JLD2\nfile = jldopen(\"advection_diffusion/simulation/cosine_advection_diffusion.jld2\")\niterations = parse.(Int, keys(file[\"timeseries/t\"]))\n\nanim = @animate for (i, iter) in enumerate(iterations)\n    @info \"Animating frame $i...\"\n    Hx = file[\"grid/Hx\"]\n    x = file[\"grid/xC\"][1+Hx:end-Hx]\n    t = file[\"timeseries/t/$iter\"]\n    c = file[\"timeseries/c/$iter\"][:]\n    \n    title = @sprintf(\"Advection-diffusion t = %.3f\", t)\n    p = plot(x, c .+ 1, linewidth=2, title=title, label=\"Oceananigans\",\n             xlabel=\"x\", ylabel=\"Tracer\", xlims=(-1, 1), ylims=(0, 2))\n\n    c_predict = reshape([phi([t, x], res.minimizer)[1] for x in xs], length(xs))\n    \n    plot!(p, x, c_predict, linewidth=2, label=\"Neural PDE\")\nend\n\ngif(anim, \"tanh_hidden32_it100_comparison.gif\", fps=15)\n", "meta": {"hexsha": "a7203e3744e5e7031e054df0ec060f66016aa60e", "size": 3345, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NeuralPDEs/2d_advection_diffusion.jl", "max_stars_repo_name": "drozzy/NeuralOceananigans", "max_stars_repo_head_hexsha": "e4cad0a48a95fb8b9360457728f0a9d86b64fdd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NeuralPDEs/2d_advection_diffusion.jl", "max_issues_repo_name": "drozzy/NeuralOceananigans", "max_issues_repo_head_hexsha": "e4cad0a48a95fb8b9360457728f0a9d86b64fdd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NeuralPDEs/2d_advection_diffusion.jl", "max_forks_repo_name": "drozzy/NeuralOceananigans", "max_forks_repo_head_hexsha": "e4cad0a48a95fb8b9360457728f0a9d86b64fdd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-25T23:03:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-25T23:03:26.000Z", "avg_line_length": 25.9302325581, "max_line_length": 114, "alphanum_fraction": 0.6346786248, "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.767456664889298}}
{"text": "# p11.jl - Chebyshev differentation of a smooth function\n\nxx = -1:.01:1; uu = @. exp(xx)*sin(5*xx); clf();\nfor N = [10 20]\n    (D,x) = cheb(N); u = @. exp(x)*sin(5*x);\n    axes([.15,.66-.4*(N==20),.31,.28]);\n    plot(x,u,\".\",markersize=6); grid(true);\n    plot(xx,uu);\n    title(\"u(x),  N=$N\")\n    error = D*u - @. exp(x)*(sin(5*x)+5*cos(5*x));\n    axes([.55,.66-.4*(N==20),.31,.28]);\n    plot(x,error,\".-\",markersize=6); grid(true);\n    title(\"error in u'(x),  N=$N\");\nend\n", "meta": {"hexsha": "8811e78a790dd0f25a132c0ad04f8de64d78d655", "size": 474, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p11.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p11.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p11.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6, "max_line_length": 56, "alphanum_fraction": 0.4978902954, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741295151718, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7674243766828298}}
{"text": "\"\"\"\n    rotation_matrix_zyx(α1, α2, α3)\n\nCalculate the rotation matrix ``R_{ab}`` that transforms a vector in b frame to a frame\n(``v_{a} = R_{ab} v_{b}``) given the rotations (α1, α2, α3) (rad).\n\nFrame b is obtained from frame a performing three intrinsic rotations of magnitude\nα1, α2 and α3 in ZYX order.\n\"\"\"\nfunction rotation_matrix_zyx(α1, α2, α3)\n\n    sα1, cα1 = sin(α1), cos(α1)\n    sα2, cα2 = sin(α2), cos(α2)\n    sα3, cα3 = sin(α3), cos(α3)\n\n    R = @SMatrix [\n        cα2 * cα1   (sα3 * sα2 * cα1 - cα3 * sα1)   (cα3 * sα2 * cα1 + sα3 * sα1)\n        cα2 * sα1   (sα3 * sα2 * sα1 + cα3 * cα1)   (cα3 * sα2 * sα1 - sα3 * cα1)\n        -sα2        sα3 * cα2                       cα3 * cα2\n    ]\n\n    return R\nend\n\n\n\"\"\"\n    rotation_matrix_zyx(q0, q1, q2, q3)\n\nCalculate the rotation matrix ``R_{ab}`` that transforms a vector in b frame to a frame\n(``v_{a} = R_{ab} v_{b}``) given the quaternions ``q_0, q_1, q_2, q_3``.\n\"\"\"\nfunction rotation_matrix_zyx(q0, q1, q2, q3)\n\n    q02, q12, q22, q32 = q0*q0, q1*q1, q2*q2, q3*q3\n\n    R = @SMatrix [\n        (q02+q12-q22-q32)    2*(q1*q2 - q0*q3)    2*(q1*q3 + q0*q2)\n        2*(q1*q2 + q0*q3)    (q02-q12+q22-q32)    2*(q2*q3 - q0*q1)\n        2*(q1*q3 - q0*q2)    2*(q2*q3 + q0*q1)    (q02-q12-q22+q32)\n    ]\n\n    return R\nend\n\n\n\"\"\"\n    quaternions(ψ, θ, ϕ)\n\nCalculate quaternion representation given the Euler angles (ψ, θ, ϕ) (rad).\n\"\"\"\nfunction quaternions(ψ, θ, ϕ)\n\n    s_ψ2, c_ψ2 = sin(ψ/2), cos(ψ/2)\n    s_θ2, c_θ2 = sin(θ/2), cos(θ/2)\n    s_ϕ2, c_ϕ2 = sin(ϕ/2), cos(ϕ/2)\n\n    q0 = c_ψ2*c_θ2*c_ϕ2 + s_ψ2*s_θ2*s_ϕ2\n    q1 = c_ψ2*c_θ2*s_ϕ2 - s_ψ2*s_θ2*c_ϕ2\n    q2 = c_ψ2*s_θ2*c_ϕ2 + s_ψ2*c_θ2*s_ϕ2\n    q3 = s_ψ2*c_θ2*c_ϕ2 - c_ψ2*s_θ2*s_ϕ2\n\n    return @SVector [q0, q1, q2, q3]\nend\n\n\n\"\"\"\n    euler_angles(q0, q1, q2, q3)\n\nCalculate Euler angles (ψ, θ, ϕ) (rad) given the quaternions ``q_0, q_1, q_2, q_3``.\n\"\"\"\nfunction euler_angles(q0, q1, q2, q3)\n\n    ψ = atan(2 * (q1*q2 + q0*q3), q0*q0 + q1*q1 - q2*q2 - q3*q3)\n    θ = asin(-2 * (q1*q3 - q0*q2))\n    ϕ = atan(2 * (q2*q3 + q0*q1), q0*q0 - q1*q1 - q2*q2 + q3*q3)\n\n    return @SVector [mod2pi(ψ), θ, ϕ]\nend\n\n\n\"\"\"\n    body2horizon(x, y, z, ψ, θ, ϕ)\n\nTransform the vector coordintes (x, y, z) given in body axis to local horizon given the\nEuler angles (ψ, θ, ϕ) (rad).\n\"\"\"\nfunction body2horizon(x, y, z, ψ, θ, ϕ)\n    v = @SVector [x, y, z]\n    rv = rotation_matrix_zyx(ψ, θ, ϕ) * v\n    return rv\nend\n\n\n\"\"\"\n    horizon2body(x, y, z, ψ, θ, ϕ)\n\nTransform the vector coordintes (x, y, z) given in local horizon axis to body given the\nEuler angles (ψ, θ, ϕ) (rad).\n\"\"\"\nfunction horizon2body(x, y, z, ψ, θ, ϕ)\n    v = @SVector [x, y, z]\n    rv = transpose(rotation_matrix_zyx(ψ, θ, ϕ)) * v\n    return rv\nend\n\n\n\"\"\"\n    body2horizon(x, y, z, q0, q1, q2, q3)\n\nTransform the vector coordintes (x, y, z) given in body axis to local horizon given the\nquaternions ``q_0, q_1, q_2, q_3``.\n\"\"\"\nfunction body2horizon(x, y, z, q0, q1, q2, q3)\n    v = @SVector [x, y, z]\n    rv = rotation_matrix_zyx(q0, q1, q2, q3) * v\n    return rv\nend\n\n\n\"\"\"\n    horizon2body(x, y, z, q0, q1, q2, q3)\n\nTransform the vector coordintes (x, y, z) given in local horizon axis to body given the\nquaternions ``q_0, q_1, q_2, q_3``.\n\"\"\"\nfunction horizon2body(x, y, z, q0, q1, q2, q3)\n    v = @SVector [x, y, z]\n    rv = transpose(rotation_matrix_zyx(q0, q1, q2, q3)) * v\n    return rv\nend\n\n\n\"\"\"\n    wind2body(x, y, z, α, β)\n\nTransform the vector coordintes (x, y, z) given in wind axis to body given the angle of\nattack (α) and the angle of sideslip (β) (rad).\n\"\"\"\nfunction wind2body(x, y, z, α, β)\n    v = @SVector [x, y, z]\n    rv = transpose(rotation_matrix_zyx(-β, α, 0)) * v\n    return rv\nend\n\n\n\"\"\"\n    body2wind(x, y, z, α, β)\n\nTransform the vector coordintes (x, y, z) given in body axis to wind given the angle of\nattack (α) and the angle of sideslip (β) (rad).\n\"\"\"\nfunction body2wind(x, y, z, α, β)\n    v = @SVector [x, y, z]\n    rv = rotation_matrix_zyx(-β, α, 0) * v\n    return rv\nend\n\n\n\"\"\"\n    wind2horizon(x, y, z, χ, γ, μ)\n\nTransform the vector coordintes (x, y, z) given in wind axis to local horizon given the\nvelocity angles (χ, γ, μ) (rad).\n\"\"\"\nfunction wind2horizon(x, y, z, χ, γ, μ)\n    v = @SVector [x, y, z]\n    rv = rotation_matrix_zyx(χ, γ, μ) * v\n    return rv\nend\n\n\n\"\"\"\n    horizon2wind(x, y, z, χ, γ, μ)\n\nTransform the vector coordintes (x, y, z) given in local horizon axis to wind given the\nvelocity angles (χ, γ, μ) (rad).\n\"\"\"\nfunction horizon2wind(x, y, z, χ, γ, μ)\n    v = @SVector [x, y, z]\n    rv = transpose(rotation_matrix_zyx(χ, γ, μ)) * v\n    return rv\nend\n\n\n\"\"\"\n    ecef2horizon(x, y, z, lat, lon)\n\nTransform the vector coordintes (x, y, z) given in ECEF (Earth Fixed Earth Centered)\ncoordinates to local horizon coordinates using geodetic latitude and longitude (rad).\n\"\"\"\nfunction ecef2horizon(x, y, z, lat, lon)\n    v = @SVector [x, y, z]\n    rv = transpose(rotation_matrix_zyx(lon, -lat - π/2, 0)) * v\nend\n\n\n\"\"\"\n    horizon2ecef(x, y, z, lat, lon)\n\nTransform the vector coordintes (x, y, z) given in local horizon axis to ECEF (Earth Fixed\nEarth Centered) using geodetic latitude and longitude (rad).\n\"\"\"\nfunction horizon2ecef(x, y, z, lat, lon)\n    v = @SVector [x, y, z]\n    rv = rotation_matrix_zyx(lon, -lat - π/2, 0) * v\nend\n", "meta": {"hexsha": "090483ac43b0120dd42c32c833148c16f1d85a18", "size": 5236, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rotations.jl", "max_stars_repo_name": "AlexS12/FlightMechanicsUtils.jl", "max_stars_repo_head_hexsha": "862f3cdac936c65881bc2aa8f1168ead8d5284d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-06-24T17:05:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T16:56:11.000Z", "max_issues_repo_path": "src/rotations.jl", "max_issues_repo_name": "AlexS12/FlightMechanicsUtils.jl", "max_issues_repo_head_hexsha": "862f3cdac936c65881bc2aa8f1168ead8d5284d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-03-13T19:26:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-06T11:41:07.000Z", "max_forks_repo_path": "src/rotations.jl", "max_forks_repo_name": "AlexS12/FlightMechanicsUtils.jl", "max_forks_repo_head_hexsha": "862f3cdac936c65881bc2aa8f1168ead8d5284d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2946859903, "max_line_length": 90, "alphanum_fraction": 0.6012223071, "num_tokens": 2217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7673966882924557}}
{"text": "# chemical problems\n# 22\nfunction haverlys_pooling_problem(x) \n    ## Haverly's Pooling Problem\n    x1 = x[1]; x2 = x[2]; x3 = x[3];\n    x4 = x[4]; x5 = x[5]; x6 = x[6];\n    x7 = x[7]; x8 = x[8]; x9 = x[9];\n    ## objective function\n    f = zeros(2);\n    f[1] = -9*x1-15*x2+6*x3+16*x4;\n    f[2] = 10 .* (x5+x6);\n    ## constraints\n    g = zeros(2);\n    h = zeros(4);\n    g[1] = x9 .* x7+2*x5-2.5*x1;\n    g[2] = x9 .* x8+2*x6-1.5*x2;\n    h[1] = x7+x8-x4-x3;\n    h[2] = x1-x5-x7;\n    h[3] = x2-x6-x8;\n    h[4] = x9 .* x7+x9 .* x8-3 .* x3-x4;\n\n    return f, g, h\nend\n\n# 23\nfunction reactor_network_design(x) \n    ## Reactor Network Design\n    k1 = 0.09755988; k2 = 0.99*k1;\n    k3 = 0.0391908; k4 = 0.9*k3;\n    x1 = x[1]; x2 = x[2]; x3 = x[3];\n    x4 = x[4]; x5 = x[5]; x6 = x[6];\n    ## objective function\n    f = zeros(2);\n    f[1] = -x4;\n    f[2] = x5 .^ (0.5)+x6 .^ (0.5);\n    ## constraints\n    g = zeros(1);\n    h = zeros(4);\n    g[1] = f[2]-4;\n    h[1] = k1 .* x5 .* x2 + x1 -1;\n    h[2] = k3 .* x5 .* x3+x3+x1-1;\n    h[3] = k2 .* x6 .* x2 - x1 + x2;\n    h[4] = k4 .* x6 .* x4 + x2-x1+x4-x3;\n\n    return f, g, h\nend\n\n# 24\nfunction heat_exchanger_network_design(x) \n    ## Heat Exchanger Network Design\n    x1 = x[1]; x2 = x[2]; x3 = x[3]; x4 = x[4]; x5 = x[5];\n    x6 = x[6]; x7 = x[7]; x8 = x[8]; x9 = x[9];\n    ## objective function\n    f = zeros(3);\n    f[1] = 35 .* x1 .^ (0.6)+ 35 .* x2 .^ (0.6);\n    f[2] = 200 .* x1 .* x4-x3;\n    f[3] = 200 .* x2 .* x6-x5;\n    ## constraints\n    g = zeros(1);\n    h = zeros(6);\n    h[1] = x3 - 1e4 .* (x7-100);\n    h[2] = x5 - 1e4 .* (300-x7);\n    h[3] = x3 - 1e4 .* (600-x8);\n    h[4] = x5 - 1e4 .* (900-x9);\n    h[5] = x4 .* log(abs(x8-100)+1e-6)-x4 .* log(abs(600-x7)+1e-6)-x8+x7+500;\n    h[6] = x6 .* log(abs(x9-x7)+1e-6)-x6 .* log(600)-x9+x7+600;\n\n    return f, g, h\nend\n\n", "meta": {"hexsha": "6edfdb7969975f687a988583b18e23fb266571de", "size": 1822, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Multiobjective/RW_MOP_2021/chemical-problems.jl", "max_stars_repo_name": "jmejia8/HardTestProblems.jl", "max_stars_repo_head_hexsha": "cde9e6c654f046fc8b9f01a434f7b213a0fab182", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Multiobjective/RW_MOP_2021/chemical-problems.jl", "max_issues_repo_name": "jmejia8/HardTestProblems.jl", "max_issues_repo_head_hexsha": "cde9e6c654f046fc8b9f01a434f7b213a0fab182", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-08T04:09:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T04:09:36.000Z", "max_forks_repo_path": "src/Multiobjective/RW_MOP_2021/chemical-problems.jl", "max_forks_repo_name": "jmejia8/HardTestProblems.jl", "max_forks_repo_head_hexsha": "cde9e6c654f046fc8b9f01a434f7b213a0fab182", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.661971831, "max_line_length": 77, "alphanum_fraction": 0.4522502744, "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693659780479, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7673966783623004}}
{"text": "module FermiDiracIntegrals\n\nusing Polylogarithms\n\nexport F\n\n\"\"\"\nComplete Fermi-Dirac-integral\n\nArguments:\n* j\n* x\n\nFormula:\n``{F_j(x) = \\\\frac{1}{\\\\Gamma(j+1)} \\\\int_0^{\\\\infty}{\\\\frac{t^j}{\\\\exp(t-x)+1}dt}}``\n\nImplementation:\nUsing the polylogarithm\n\"\"\"\nfunction F(j,x)\n    -polylog(j+1,-exp(x))\nend\n\n\"\"\"\nApproximation of the complete Fermi-Dirac-integral for j = 1/2\n\nChecked for a relative tolerance of 3% in the range x = -100:0.1:100\n\nSpeed: 100 times faster than the polylog version\n\nSource:\nJ. S. Blakemore: Approximations for Fermi-Dirac Integrals. Solid-State Electronics, 25(11):1067-1076, 1982.\n\"\"\"\nfunction F(::Val{1/2},x) \n    if x < 1.3\n        1/(exp(-x)+0.27)\n    else\n        4/3/sqrt(pi)*(x^2+pi^2/6)^(3/4)\n    end\nend\n\nend\n", "meta": {"hexsha": "77913219ff91a024ac2a10668a475e99cd737f7d", "size": 742, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FermiDiracIntegrals.jl", "max_stars_repo_name": "feanor12/FermiDiracIntegral.jl", "max_stars_repo_head_hexsha": "b02a398f028b4d8578d91d9ac228357cd433d60f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FermiDiracIntegrals.jl", "max_issues_repo_name": "feanor12/FermiDiracIntegral.jl", "max_issues_repo_head_hexsha": "b02a398f028b4d8578d91d9ac228357cd433d60f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-22T19:16:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T19:16:59.000Z", "max_forks_repo_path": "src/FermiDiracIntegrals.jl", "max_forks_repo_name": "feanor12/FermiDiracIntegral.jl", "max_forks_repo_head_hexsha": "b02a398f028b4d8578d91d9ac228357cd433d60f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.2558139535, "max_line_length": 107, "alphanum_fraction": 0.6522911051, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7673966772112286}}
{"text": "const DT = Integer\n\nfunction find_amicable(limit::DT)\n  T = typeof(limit)\n  v = Vector{Tuple{Pair{T, Vector{T}}, Pair{T, Vector{T}}}}()\n  t = Set{T}()\n\n  for n ∈ one(T):limit\n    d₁ = divisors(n)\n    p = sum(d₁)\n    d₂ = divisors(p)\n    s = sum(d₂)\n\n    if s == n && d₁ ≠ d₂ && s ∉ t\n      push!(t, s)\n      push!(t, p)\n      push!(v, (n => d₁, p => d₂))\n    end\n  end\n\n  (t, v)\nend\n\n\n# (Set([2924, 5564, 6232, 5020, 220, 284, 1184, 2620, 1210, 6368]),\n#  [(220 => [1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110], 284 => [1, 2, 4, 71, 142]), (1184 => [1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592], 1210 => [1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605]), (2620 => [1, 2, 4, 5, 10, 20, 131, 262, 524, 655, 1310], 2924 => [1, 2, 4, 17, 34, 43, 68, 86, 172, 731, 1462]), (5020 => [1, 2, 4, 5, 10, 20, 251, 502, 1004, 1255, 2510], 5564 => [1, 2, 4, 13, 26, 52, 107, 214, 428, 1391, 2782]), (6232 => [1, 2, 4, 8, 19, 38, 41, 76, 82, 152, 164, 328, 779, 1558, 3116], 6368 => [1, 2, 4, 8, 16, 32, 199, 398, 796, 1592, 3184])])\n#\n# julia> s |> sum\n# 31626\n\nfunction is_amicable(n₁::Any, n₂::Any)\n  throw(ArgumentError(\"n₁ and n₂ should be Integers\"))\nend\n\nfunction is_amicable(n₁::DT, n₂::DT)::Bool\n  d₁ = divisors(n₁)\n  d₂ = divisors(n₂)\n  n₂ == sum(d₁) && n₁ == sum(d₂)\nend\n\nfunction divisors(n::DT)::Vector{<: DT}\n  T = typeof(n)\n  ary::Vector{T} = [one(T), ]\n\n  d = T(2)\n  while d * d ≤ n\n    q, r = divrem(n, d)\n    if r == 0\n      q == d ? push!(ary, d) : push!(ary, d, q)\n    end\n    d += 1\n  end\n\n  return ary |> sort\nend\n", "meta": {"hexsha": "7220beeb641cad8a934c74fcf7af5e1dba3c98c8", "size": 1513, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Amicable_Number/solver.jl", "max_stars_repo_name": "pascal-p/Euler", "max_stars_repo_head_hexsha": "a4cd6048cb0ee288fe9e541271cce28759538218", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Amicable_Number/solver.jl", "max_issues_repo_name": "pascal-p/Euler", "max_issues_repo_head_hexsha": "a4cd6048cb0ee288fe9e541271cce28759538218", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Amicable_Number/solver.jl", "max_forks_repo_name": "pascal-p/Euler", "max_forks_repo_head_hexsha": "a4cd6048cb0ee288fe9e541271cce28759538218", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0178571429, "max_line_length": 557, "alphanum_fraction": 0.5089226702, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480248488136, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7673751305289307}}
{"text": "# # Singular Integrals\n\n# This example shows how to use the `Integration` module for computing\n# quadrature rules for functions with point singularities (such as those\n# appearing in the numerical discretization of boundary integral equations).\n\n# ## Change of variables\n\n# The first set of *tricks* revolve a round a simple change of variables. We\n# focus first on the one-dimensional case, where we wish to integrate \n```math\n    \\int_0^1 f(x) dx,\n```\n# and where the function ``f`` can have an integrable singularity at \n\nusing WaveProp.Geometry\nusing WaveProp.Integration\nusing WaveProp.Integration\nusing QuadGK\n\nf        = (x) -> x==0 ? 0.0 : log(abs(x))*cos(x)\nI,_        = quadgk(f,0,1,rtol=1e-16)\n\nrows = GaussLegendre.([5,10,20,40,80])\ncols = [identity,IMT{1,2}(),Kress{8}(), Window{1,1,7}()]    \nee   = []\nfor qstd in rows\n    for shandler in cols\n        q        = SingularQuadratureRule(qstd,shandler)\n        Is       = integrate(f,q)\n        er       = abs(I-Is)\n        push!(ee,er)\n    end    \nend\n\nusing NamedArrays\nee = reshape(ee,length(cols),length(rows)) |> transpose |> NamedArray\nsetnames!(ee,string.(rows),1)\nsetnames!(ee,string.(cols),2)\nsetdimnames!(ee,[\"Base quadrature\",\"Singularity handler\"])\nshow(ee)\n\n# ## \n# using Plots\n# qstd = GaussLegendre(10)\n# x̂,ŵ  = qstd()\n# cols = [IMT{1,2}(),Kress{8}(), Window{0.5,1,7}()]    \n# fig = plot()\n# for shandler in cols\n#     phi       = shandler.(x̂)\n#     phip      = [jacobian(shandler,x)[1] for x in x̂]\n#     plot!(fig,x̂,f.(phi) .* phip,label=string(shandler),m=:x)\n# end \n# display(fig)   \n\n", "meta": {"hexsha": "73b7e60dad1141789635f7183c42dd7f6285ab28", "size": 1570, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tutorials/singularintegration_tutorial.jl", "max_stars_repo_name": "WaveProp/WaveProp", "max_stars_repo_head_hexsha": "4d589a093d6d590d2f7bf0bfdf2cc8e2da1b1fec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-15T13:46:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T07:16:38.000Z", "max_issues_repo_path": "tutorials/singularintegration_tutorial.jl", "max_issues_repo_name": "WaveProp/WaveProp", "max_issues_repo_head_hexsha": "4d589a093d6d590d2f7bf0bfdf2cc8e2da1b1fec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-06-24T20:14:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-25T11:07:01.000Z", "max_forks_repo_path": "tutorials/singularintegration_tutorial.jl", "max_forks_repo_name": "WaveProp/WaveProp", "max_forks_repo_head_hexsha": "4d589a093d6d590d2f7bf0bfdf2cc8e2da1b1fec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-15T17:31:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T09:43:13.000Z", "avg_line_length": 28.0357142857, "max_line_length": 76, "alphanum_fraction": 0.6388535032, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195635, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7673751305120421}}
{"text": "immutable HessenbergQR{T}\n    cosθ::Vector{T}\n    sinθ::Vector{T}\nend\n\n## QR decomposition on an upper Hessenberg matrix\n## H will be overwritten by Q'HQ=RQ\nfunction hessenqr!{T}(H::Matrix{T})\n    ## Size of matrix\n    n = size(H, 1)\n    if n != size(H, 2)\n        error(\"matrix must be square\")\n    end\n\n    ## Rotation factors\n    ## Each pair (cosθ[i], sinθ[i]) forms a rotation matrix\n    ## Gi = [cosθ[i]  -sinθ[i]]\n    ##      [sinθ[i]   cosθ[i]]\n    cosθ = ones(T, n)\n    sinθ = zeros(T, n)\n\n    for i = 1:(n - 1)\n        ## Make sure H is upper Hessenberg\n        ## Zero the elements below H[i+1, i]\n        H[(i + 2):end, i] = zero(T)\n        ## Calculate cosθ and sinθ\n        x = H[i, i]\n        y = H[i + 1, i]\n        r = hypot(x, y)\n        ## If r is too small, (cosθ, sinθ) stores the original values (1, 0)\n        if r < eps(T)\n            r = zero(T)\n        else\n            cosθ[i] = x / r\n            sinθ[i] = -y / r\n        end\n        ## Apply the rotation on the left H -> Gi * H\n        ## H[i, :]     <- cosθ[i] * H[i, :] - sinθ[i] * H[i +1, :]\n        ## H[i + 1, :] <- sinθ[i] * H[i, :] + cosθ[i] * H[i +1, :]\n        H[i, i] = r\n        H[i + 1, i] = zero(T)\n        c = cosθ[i]\n        s = sinθ[i]\n        for j = (i + 1):n\n            tmp = H[i, j]\n            H[i, j]     = c * tmp - s * H[i + 1, j]\n            H[i + 1, j] = s * tmp + c * H[i + 1, j]\n        end\n    end\n\n    ## Apply the rotations on the right H -> H * Gi'\n    ## H[:, i]     <- cosθ[i] * H[:, i] - sinθ[i] * H[:, i + 1]\n    ## H[:, i + 1] <- sinθ[i] * H[:, i] + cosθ[i] * H[:, i + 1]\n    for i = 1:(n - 1)\n        for j = 1:(i + 1)\n            tmp = H[j, i]\n            H[j, i]     = cosθ[i] * tmp - sinθ[i] * H[j, i + 1]\n            H[j, i + 1] = sinθ[i] * tmp + cosθ[i] * H[j, i + 1]\n        end\n    end\n\n    return HessenbergQR(cosθ, sinθ)\nend\n\n## QR decomposition on a tridiagonal matrix\n## H will be overwritten by Q'HQ=RQ\nfunction tridiagqr!{T}(H::Matrix{T})\n    ## Size of matrix\n    n = size(H, 1)\n    if n != size(H, 2)\n        error(\"matrix must be square\")\n    end\n\n    ## Force H to be tridiagonal\n    maindiag = diag(H)\n    subdiag = diag(H, -1)\n    fill!(H, zero(T))\n    for i = 1:(n - 1)\n        H[i, i] = maindiag[i]\n        H[i + 1, i] = subdiag[i]\n        H[i, i + 1] = subdiag[i]\n    end\n    H[n, n] = maindiag[n]\n\n    ## Rotation factors\n    ## Each pair (cosθ[i], sinθ[i]) forms a rotation matrix\n    ## Gi = [cosθ[i]  -sinθ[i]]\n    ##      [sinθ[i]   cosθ[i]]\n    cosθ = ones(T, n)\n    sinθ = zeros(T, n)\n\n    for i = 1:(n - 1)\n        ## Calculate cosθ and sinθ\n        x = H[i, i]\n        y = H[i + 1, i]\n        r = hypot(x, y)\n        ## If r is too small, (cosθ, sinθ) stores the original values (1, 0)\n        if r < eps(T)\n            r = zero(T)\n        else\n            cosθ[i] = x / r\n            sinθ[i] = -y / r\n        end\n        ## Apply the rotation on the left H -> Gi * H\n        ## Update H[i, i] and H[i + 1, i]\n        H[i, i] = r\n        H[i + 1, i] = zero(T)\n        ## Update H[i, i + 1] and H[i + 1, i + 1]\n        c = cosθ[i]\n        s = sinθ[i]\n        tmp = H[i, i + 1]\n        H[i,     i + 1] = c * tmp - s * H[i + 1, i + 1]\n        H[i + 1, i + 1] = s * tmp + c * H[i + 1, i + 1]\n        ## Update H[i, i + 2] and H[i + 1, i + 2]\n        if i < n - 1\n            H[i,     i + 2] = -s * H[i + 1, i + 2]\n            H[i + 1, i + 2] *= c\n        end\n    end\n\n    ## Apply the rotations on the right H -> H * Gi'\n    ## H[:, i]     <- cosθ[i] * H[:, i] - sinθ[i] * H[:, i + 1]\n    ## H[:, i + 1] <- sinθ[i] * H[:, i] + cosθ[i] * H[:, i + 1]\n    for i = 1:(n - 1)\n        c = cosθ[i]\n        s = sinθ[i]\n\n        tmp = H[i + 1, i]\n        H[i, i]         = c * H[i, i] - s * H[i, i + 1]\n        H[i + 1, i]     = c * tmp     - s * H[i + 1, i + 1]\n        H[i + 1, i + 1] = s * tmp     + c * H[i + 1, i + 1]\n\n        H[i, i + 1] = H[i + 1, i]\n        if i < n - 1\n            H[i, i + 2] = zero(T)\n        end\n    end\n\n    return HessenbergQR(cosθ, sinθ)\nend\n\n## Apply the QR factorization to the right of a matrix A\n## A -> A * Q'\nfunction applyright!{T}(qr::HessenbergQR{T}, A::Matrix{T})\n    cosθ = qr.cosθ\n    sinθ = qr.sinθ\n    n = length(cosθ)\n    ## A[:, i]     <- cosθ[i] * A[:, i] - sinθ[i] * A[:, i + 1]\n    ## A[:, i + 1] <- sinθ[i] * A[:, i] + cosθ[i] * A[:, i + 1]\n    for i = 1:(n - 1)\n        for j = 1:size(A, 1)\n            tmp = A[j, i]\n            A[j, i]     = cosθ[i] * tmp - sinθ[i] * A[j, i + 1]\n            A[j, i + 1] = sinθ[i] * tmp + cosθ[i] * A[j, i + 1]\n        end\n    end\nend\n", "meta": {"hexsha": "0dde4e03a4eef2dd956eeedebc7fbe3852708f73", "size": 4558, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hessenqr.jl", "max_stars_repo_name": "yixuan/Spectra.jl", "max_stars_repo_head_hexsha": "96ff7d180e575c2e0f3b1e41069599265356ee8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hessenqr.jl", "max_issues_repo_name": "yixuan/Spectra.jl", "max_issues_repo_head_hexsha": "96ff7d180e575c2e0f3b1e41069599265356ee8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hessenqr.jl", "max_forks_repo_name": "yixuan/Spectra.jl", "max_forks_repo_head_hexsha": "96ff7d180e575c2e0f3b1e41069599265356ee8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8481012658, "max_line_length": 76, "alphanum_fraction": 0.4014918824, "num_tokens": 1761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7673751249528563}}
{"text": "\"\"\"\r\n    FrankCopula{d,T}\r\n\r\nFields:\r\n  - θ::Real - parameter\r\n\r\nConstructor\r\n\r\n    FrankCopula(d, θ)\r\n\r\nThe [Frank](https://en.wikipedia.org/wiki/Copula_(probability_theory)#Most_important_Archimedean_copulas) copula in dimension ``d`` is parameterized by ``\\\\theta \\\\in [0,\\\\infty)``. It is an Archimedean copula with generator : \r\n\r\n```math\r\n\\\\phi(t) = -\\\\frac{\\\\log\\\\left(1+e^{-t}(e^{-\\\\theta-1})\\\\right)}{\\theta}\r\n```\r\n\"\"\"\r\nstruct FrankCopula{d,T} <: ArchimedeanCopula{d}\r\n    θ::T\r\nend\r\nFrankCopula(d,θ) = θ >= 0 ? FrankCopula{d,typeof(θ)}(θ) : @error \"Theta must be positive\"\r\nϕ(  C::FrankCopula,       t) = -log(1+exp(-t)*(exp(-C.θ)-1))/C.θ\r\nϕ⁻¹(C::FrankCopula,       t) = -log((exp(-t*C.θ)-1)/(exp(-C.θ)-1))\r\n\r\nD₁ = GSL.sf_debye_1 # sadly, this is C code.\r\n# could be replaced by : \r\n# using QuadGK\r\n# D₁(x) = quadgk(t -> t/(exp(t)-1), 0, x)[1]/x\r\n# to make it more general. but once gain, it requires changing the integrator at each evlauation, \r\n# which is problematic. \r\n# Better option is to try to include this function into SpecialFunctions.jl. \r\n\r\n\r\nτ(C::FrankCopula) = 1+4(D₁(C.θ)-1)/C.θ\r\nfunction τ⁻¹(::Type{FrankCopula},τ)\r\n    if τ == zero(τ)\r\n        return τ\r\n    end\r\n    x₀ = (1-τ)/4\r\n    return Roots.fzero(x -> (1-D₁(x))/x - x₀, 10)\r\nend\r\n    \r\n\r\nradial_dist(C::FrankCopula) = Logarithmic(1-exp(-C.θ))\r\n\r\n\r\n", "meta": {"hexsha": "19b76dfdc792b5b8f32556eeb5ef873ea2e09acb", "size": 1333, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ArchimedeanCopulas/FrankCopula.jl", "max_stars_repo_name": "lrnv/Copulas.jl", "max_stars_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2022-02-16T08:18:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:14:07.000Z", "max_issues_repo_path": "src/ArchimedeanCopulas/FrankCopula.jl", "max_issues_repo_name": "lrnv/Copulas.jl", "max_issues_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-19T06:55:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T09:43:03.000Z", "max_forks_repo_path": "src/ArchimedeanCopulas/FrankCopula.jl", "max_forks_repo_name": "lrnv/Copulas.jl", "max_forks_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9782608696, "max_line_length": 228, "alphanum_fraction": 0.6061515379, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881363, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7673751230040924}}
{"text": "using EngEconomics\n\n# Given\ni = 0.1\nxInit = 12500\nyInit = 8900\nxAnnualBenefit = 6800\nyAnnualBenefit = 2000\nxSalvage = 5000\nySalvage = 8900\nxLife = 2\nyLife = 3\n\n# Find: Present Worth Analysis of Both\n\n# Determine the least common multiple of xLife and yLife to figure out how many\n# times we have to repeat the PW Analysis\nyears = 6\nxTimes = years / xLife\nyTimes = years / yLife\n\n# Determine Product X's PW\nxInitPW = -xInit * (1 + presentWorthFactor(i, xLife) + presentWorthFactor(i, 2 * xLife))\nxAnnualBenefitPW = (xAnnualBenefit * seriesPresentAmountFactor(i, xLife)) * (1 + presentWorthFactor(i, xLife) + presentWorthFactor(i, 2 * xLife))\nxSalvagePW = xSalvage * (presentWorthFactor(i, xLife) + presentWorthFactor(i, 2 * xLife) + presentWorthFactor(i, 3 * xLife))\nxPW = xInitPW + xAnnualBenefitPW + xSalvagePW\n\n# Determine Product Y's PW\nyInitPW = -yInit * (1 + presentWorthFactor(i, yLife))\nyAnnualBenefitPW = (yAnnualBenefit * seriesPresentAmountFactor(i, yLife)) * (1 + presentWorthFactor(i, yLife))\nySalvagePW = ySalvage * (presentWorthFactor(i, yLife) + presentWorthFactor(i, 2 * yLife))\nyPW = yInitPW + yAnnualBenefitPW + ySalvagePW\n\n# Determine which product is better by comparing they're present value\nif xPW > yPW\n\tprintln(\"Pick Product X\")\nelse\n\tprintln(\"Pick Product Y\")\nend\n", "meta": {"hexsha": "eac36b3c5be6a07242f44d43dd68522602c29e98", "size": 1289, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps4/p3.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/ps4/p3.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/ps4/p3.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.225, "max_line_length": 145, "alphanum_fraction": 0.7432117921, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877717925422, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7673581159591015}}
{"text": "import Pkg; Pkg.add(Pkg.PackageSpec(url=\"https://github.com/JuliaComputing/JuliaAcademyData.jl\"))\nusing JuliaAcademyData; activate(\"Deep learning with Flux\")\n\n# <br />\n# ## Going deep: Deep neural networks\n#\n# So far, we've learned that if we want to classify more than two fruits, we'll need to go beyond using a single neuron and use *multiple* neurons to get multiple outputs. We can think of stacking these multiple neurons together in a single neural layer.\n#\n# Even so, we found that using a single neural layer was not enough to fully distinguish between bananas, grapes, **and** apples. To do this properly, we'll need to add more complexity to our model. We need not just a neural network, but a *deep neural network*.\n#\n# There is one step remaining to build a deep neural network. We have been saying that a neural network takes in data and then spits out `0` or `1` predictions that together declare what kind of fruit the picture is. However, what if we instead put the output of one neural network layer into another neural network layer?\n#\n# This gets pictured like this below:\n#\n# <img src=\"data/deep-neural-net.png\" alt=\"Drawing\" style=\"width: 375px;\"/>\n#\n# On the left we have 3 data points in blue. Those 3 data points each get fed into 4 neurons in purple. Each of those 4 neurons produces a single output, but those output are each fed into three neurons (the second layer of purple). Each of those 3 neurons spits out a single value, and those values are fed as inputs into the last layer of 6 neurons. The 6 values that those final neurons produce are the output of the neural network. This is a deep neural network.\n\n#-\n\n# ### Why would a deep neural network be better?\n#\n# This is a little perplexing when you first see it. We used neurons to train the model before: why would sticking the output from neurons into other neurons help us fit the data better? The answer can be understood by drawing pictures. Geometrically, the matrix multiplication inside of a layer of neurons is streching and rotating the axis that we can vary:\n\n## using Plots, Random; Random.seed!(0); xs = range(0, stop=10, length=200); ys = randn.() .+ xs .+ 0.5.*xs.^1.5 .+ 6.0.*sin.(clamp.(xs .- 5, 0, Inf)) .+ 4.5.*clamp.(.-abs.(xs .- 2), -2, 0); scatter(xs, ys, label=\"\", ticks = false, title=\"Original data\", ylim=extrema(ys).+[-.5,.5]); savefig(\"data/17-raw.png\"); fit1 = [xs ones(size(xs))] \\ ys; linear1(x) = fit1[1]*x + fit1[2]; plot!(linear1, label=\"Linear transform\", linewidth=4, legend=:topleft); savefig(\"data/17-raw-withfit.png\");\nHTML(\"\"\"<img src=\"https://raw.githubusercontent.com/JuliaComputing/JuliaAcademyData.jl/master/courses/Deep%20learning%20with%20Flux/data/17-raw.png\" onclick=\"this.src='https://raw.githubusercontent.com/JuliaComputing/JuliaAcademyData.jl/master/courses/Deep%20learning%20with%20Flux/data/17-raw-withfit.png'\"/>\"\"\")\n\n# A nonlinear transformation—such as the sigmoid function or a piecewise linear function—then adds a bump to this linearly-transformed data:\n\n## scatter(xs, ys .- linear1.(xs), ticks = false, label = \"\", title=\"data with linear transform\", ylim=extrema(ys).+[-.5,.5]); savefig(\"data/17-linear1.png\"); nonlinearity(x) = clamp.(4.0.*x .- 4.5, -4, 4); plot!(nonlinearity, label = \"nonlinearity\", linewidth=4); savefig(\"data/17-linear1-withfit.png\");\nHTML(\"\"\"<img src=\"https://raw.githubusercontent.com/JuliaComputing/JuliaAcademyData.jl/master/courses/Deep%20learning%20with%20Flux/data/17-linear1.png\" onclick=\"this.src='https://raw.githubusercontent.com/JuliaComputing/JuliaAcademyData.jl/master/courses/Deep%20learning%20with%20Flux/data/17-linear1-withfit.png'\"/>\"\"\")\n\n# Resulting in a bit more of the data accounted for:\n\n## ys2 = ys .- linear1.(xs) .- nonlinearity.(xs); scatter(xs, ys2, ticks = false, label = \"\", title=\"data after first 'layer'\", ylim=extrema(ys).+[-.5,.5]); savefig(\"data/17-nonlinear1.png\"); fit2 = [xs ones(size(xs))] \\ ys2; linear2(x) = fit2[1]*x + fit2[2]; plot!(linear2, label=\"second linear tranform\", linewidth=4); savefig(\"data/17-nonlinear1-withfit.png\");\nHTML(\"\"\"<img src=\"https://raw.githubusercontent.com/JuliaComputing/JuliaAcademyData.jl/master/courses/Deep%20learning%20with%20Flux/data/17-nonlinear1.png\" onclick=\"this.src='https://raw.githubusercontent.com/JuliaComputing/JuliaAcademyData.jl/master/courses/Deep%20learning%20with%20Flux/data/17-nonlinear1-withfit.png'\"/>\"\"\")\n\n# Now let's repeat this process. When we send the data through another layer of neurons, we get another rotation and another \"bump\":\n\n## ys3 = ys2 .- linear2.(xs); scatter(xs .- 4.5, ys3, ticks = false, label = \"\", title=\"data after first layer + second linear transform\", ylim=extrema(ys).+[-.5,.5]); savefig(\"data/17-linear2.png\"); plot!(nonlinearity, label = \"nonlinearity\", linewidth=4); savefig(\"data/17-linear2-withfit.png\");\nHTML(\"\"\"<img src=\"https://raw.githubusercontent.com/JuliaComputing/JuliaAcademyData.jl/master/courses/Deep%20learning%20with%20Flux/data/17-linear2.png\" onclick=\"this.src='https://raw.githubusercontent.com/JuliaComputing/JuliaAcademyData.jl/master/courses/Deep%20learning%20with%20Flux/data/17-linear2-withfit.png'\"/>\"\"\")\n\n#-\n\n## ys4 = ys3 .- nonlinearity.(xs .- 4.5); scatter(xs, ys4, ticks = false, label = \"\", title=\"data after second 'layer'\", ylim=extrema(ys).+[-.5,.5]); savefig(\"data/17-nonlinear2.png\");\nHTML(\"\"\"<img src=\"https://raw.githubusercontent.com/JuliaComputing/JuliaAcademyData.jl/master/courses/Deep%20learning%20with%20Flux/data/17-nonlinear2.png\"/>\"\"\")\n\n#\n# Visually, we see that if we keep doing this process we can make the axis line up with any data. What this means is that **if we have enough layers, then our neural network can approximate any model**.\n#\n# The trade-off is that with more layers we have more parameters, so it may be harder (i.e. computationally intensive) to train the neural network. But we have the guarantee that the model has enough freedom such that there are parameters that will give the correct output.\n#\n# Because this model is so flexible, the problem is reduced to that of learning: do the same gradient descent method on this much larger model (but more efficiently!) and we can make it classify our data correctly. This is the power of deep learning.\n\n#-\n\n# **Important caveat**: The above is a _cartoon_ that loosely describes the concepts behind a deep neural network. In reality, remember that we're not successively fitting \"the best\" linear transformation and then subsequently fitting a nonlinearity; the two are happening simultaneously through gradient descent. This allows the linear transform to — in effect — rotate and stretch the data such that the nonlinearity \"falls\" in the appropriate place to best minimize the loss function.\n\n#-\n\n# # Deep learning with Flux\n\n#-\n\n# Let's load the same datasets from the previous lecture and pre-process them in the same way:\n\nusing CSV, DataFrames, Flux, Plots\napples1 = DataFrame(CSV.File(\"data/Apple_Golden_1.dat\", delim='\\t', allowmissing=:none, normalizenames=true))\napples2 = DataFrame(CSV.File(\"data/Apple_Golden_2.dat\", delim='\\t', allowmissing=:none, normalizenames=true))\napples3 = DataFrame(CSV.File(\"data/Apple_Golden_3.dat\", delim='\\t', allowmissing=:none, normalizenames=true))\napples = vcat(apples1, apples2, apples3)\nbananas = DataFrame(CSV.File(\"data/Banana.dat\", delim='\\t', allowmissing=:none, normalizenames=true))\ngrapes1 = DataFrame(CSV.File(\"data/Grape_White.dat\", delim='\\t', allowmissing=:none, normalizenames=true))\ngrapes2 = DataFrame(CSV.File(\"data/Grape_White_2.dat\", delim='\\t', allowmissing=:none, normalizenames=true))\ngrapes = vcat(grapes1, grapes2)\n## Extract out the features and construct the corresponding labels\nx_apples  = [ [apples[i, :red], apples[i, :blue]] for i in 1:size(apples, 1) ]\nx_bananas  = [ [bananas[i, :red], bananas[i, :blue]] for i in 1:size(bananas, 1) ]\nx_grapes = [ [grapes[i, :red], grapes[i, :blue]] for i in 1:size(grapes, 1) ]\nxs = vcat(x_apples, x_bananas, x_grapes)\nys = vcat(fill(Flux.onehot(1, 1:3), size(x_apples)),\n          fill(Flux.onehot(2, 1:3), size(x_bananas)),\n          fill(Flux.onehot(3, 1:3), size(x_grapes)));\n\n# In the previous lecture, we used a `Dense(2, 3, σ)` as our model. Now we want to construct multiple layers and chain them together:\n\nlayer1 = Dense(2, 4, σ)\nlayer2 = Dense(4, 3, σ)\n\n#-\n\nlayer2(layer1(xs[1]))\n\n#-\n\n#nb ?Chain\n#jl @doc Chain\n\n#-\n\nm = Chain(layer1, layer2)\nm(xs[1])\n\n#-\n\nxs[1] |> layer1 |> layer2\n\n# ### The core algorithm from the last lecture\n\nmodel = Chain(Dense(2, 3, σ)) # Update this!\nL(x,y) = Flux.mse(model(x), y)\nopt = SGD(params(model))\nFlux.train!(L, zip(xs, ys), opt)\n\n#-\n\n## Recall his is how we repeatedly walked down our gradient previously...\nfor _ in 1:1000\n    Flux.train!(L, zip(xs, ys), opt)\nend\n## But our model is now more complicated and this will take more time!\n\n#-\n\ndata = zip(xs, ys)\n@time Flux.train!(L, data, opt)\n@time Flux.train!(L, data, opt)\n\n# ### Improving efficiency by batching\n\nlength(data)\n\n#-\n\nfirst(data)\n\n# Recall our matrix-vector multiplication from the previous lecture:\n\nW = [10 1;\n     20 2;\n     30 3]\nx = [3;\n     2]\nW*x\n\n#-\n\nFlux.batch(xs)\n\n#-\n\nmodel(Flux.batch(xs))\n\n#-\n\ndatabatch = (Flux.batch(xs), Flux.batch(ys))\n@time Flux.train!(L, (databatch,), opt)\n@time Flux.train!(L, (databatch,), opt)\n\n#-\n\nFlux.train!(L, Iterators.repeated(databatch, 10000), opt)\n\n#-\n\nL(databatch[1], databatch[2])\n\n# ### Visualization\n\nusing Plots\nfunction plot_decision_boundaries(model, x_apples, x_bananas, x_grapes)\n    plot()\n\n    contour!(0:0.01:1, 0:0.01:1, (x,y)->model([x,y]).data[1], levels=[0.5, 0.501], color = cgrad([:blue, :blue]), colorbar=:none)\n    contour!(0:0.01:1, 0:0.01:1, (x,y)->model([x,y]).data[2], levels=[0.5,0.501], color = cgrad([:green, :green]), colorbar=:none)\n    contour!(0:0.01:1, 0:0.01:1, (x,y)->model([x,y]).data[3], levels=[0.5,0.501], color = cgrad([:red, :red]), colorbar=:none)\n\n    scatter!(first.(x_apples), last.(x_apples), m=:cross, label=\"apples\", color = :blue)\n    scatter!(first.(x_bananas), last.(x_bananas), m=:circle, label=\"bananas\", color = :green)\n    scatter!(first.(x_grapes), last.(x_grapes), m=:square, label=\"grapes\", color = :red)\nend\nplot_decision_boundaries(model, x_apples, x_bananas, x_grapes)\n\n# ### Further improvements with a better loss function and normalization of outputs\n\nscatter([0],[0], label=\"correct answer\", xlabel=\"model output: [1-x,x]\", ylabel=\"loss against [1, 0]\", legend=:topleft, title=\"Loss function behavior\")\nplot!(x->Flux.mse([1-x, x/2], [1,0]), -1.5, 1.5, label=\"mse\")\n## plot!(x->Flux.crossentropy([1-x, x/2], [1,0]), 0, 1, label=\"crossentropy\")\n\n#-\n\nsum(model(xs[1]))\n\n#-\n\nFlux.mse([0.01,0.98,0.01], [1.0,0,0])\n\n#-\n\nsoftmax([1.0,-3,0])\n\n# ### The new algorithm\n#\n# Use `softmax` as a final normalization and change the loss function to `crossentropy`:\n\nmodel = Chain(Dense(2, 4, σ), Dense(4, 3, identity), softmax)\nL(x,y) = Flux.crossentropy(model(x), y)\nopt = SGD(params(model))\n\n#-\n\nFlux.train!(L, Iterators.repeated(databatch,5000), opt)\n\n#-\n\nplot_decision_boundaries(model, x_apples, x_bananas, x_grapes)\n\n", "meta": {"hexsha": "3a70f854c97926b3ee90b73cea2a9cf47322c062", "size": 11059, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Deep learning with Flux/1700.Introduction-to-deep-learning.jl", "max_stars_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_stars_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2020-02-13T00:50:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T07:57:22.000Z", "max_issues_repo_path": "Courses/Deep learning with Flux/1700.Introduction-to-deep-learning.jl", "max_issues_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_issues_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2019-10-30T16:22:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-26T20:02:43.000Z", "max_forks_repo_path": "Courses/Deep learning with Flux/1700.Introduction-to-deep-learning.jl", "max_forks_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_forks_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2020-02-26T11:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T22:34:53.000Z", "avg_line_length": 50.7293577982, "max_line_length": 487, "alphanum_fraction": 0.7155258161, "num_tokens": 3288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7673517104746778}}
{"text": "# Faster than Polynomials.jl with less memory allocation + single-point type\n# stability; adapted from Octave and\n# https://github.com/JuliaMath/Polynomials.jl/blob/master/src/Polynomials.jl\nfunction poly(x::Array{T,1}) where T <: Number\n  n = length(x)\n  y = zeros(T, n+1)\n  y[1] = one(T)\n  for j = 1:n\n    y[2:j+1] .-= x[j].*y[1:j]\n  end\n  return y\nend\n\nfunction polyval(p::Array{T1,1}, x::T2) where {T1 <: Number, T2 <: Number}\n  y = T2(p[1])\n  for i = 2:lastindex(p)\n    y = p[i] .+ x*y\n  end\n  return y\nend\n\nfunction polyval(p::Array{T1,1}, x::Array{T2,1}) where {T1 <: Number, T2 <: Number}\n  y = ones(T2, length(x)) .* p[1]\n  for i = 2:length(p)\n    broadcast!(*, y, y, x)\n    broadcast!(+, y, y, p[i])\n  end\n  return y\nend\n\nfunction polyfit(x::Array{T1,1}, y::Array{T2,1}, n::Integer=1) where {T1 <: Real, T2 <: Real}\n  nx = length(x)\n  nx == length(y) || error(\"SeisIO.polyfit requires length(t) == length(x)\")\n  -1 < n < nx || throw(DomainError)\n  A = Array{T2, 2}(undef, length(x), n+1)\n  A[:,n+1] .= one(T2)\n  for i = n:-1:1\n      A[:,i] .= A[:,i+1] .* x\n  end\n  return A \\ y\nend\n\n# Convert to Float64 or use improved sum\nfunction linreg(t::Array{Float64,1}, x::AbstractArray{T,1}) where T\n  n = length(t)\n  st = sum(t)\n  sx = sum(x)\n  stt = dot(t,t)\n  stx = dot(t,x)\n  sxx = dot(x,x)\n  d = n*stt - st*st\n  b = (stt*sx - st*stx)/d\n  a = (n*stx - st*sx)/d\n  return T[a,b]\nend\n\n# p = linreg(x, fs)\nfunction linreg(x::AbstractArray{T,1}, dt::Float64) where T\n  n = length(x)\n  t = (1:n)*dt\n  st = sum(t)\n  sx = sum(x)\n  stt = dot(t,t)\n  stx = dot(t,x)\n  sxx = dot(x,x)\n  d = n*stt - st*st\n  b = (stt*sx - st*stx)/d\n  a = (n*stx - st*sx)/d\n  return T[a,b]\nend\n\n#= CHANGELOG for this file\n2019-08-08\n* poly, polyval, and polyfit should now always output powers in descending\norder, i.e., p^n ... p^0\n* BUG fixed: polyval(p::Array{T,1}, x::T) used power ordering of Polynomials.jl;\ncorrected to be consistent with other routines\n* polyfit now allows order n=0 and takes any Integer for n; n=0 returns the mean\n2019-08-19\n* added linreg for low-memory linear regression; identical to SAC detrend\n2019-09-03\n* bug fix for rare situation where float precision led to length(t) != length(x)\n=#\n", "meta": {"hexsha": "941ff679d10d797edb62655987d40d3b7f5360cb", "size": 2196, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CoreUtils/poly.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SeisIO.jl-b372bb87-02dd-52bb-bcf6-c30dd83fd342", "max_stars_repo_head_hexsha": "ae4ddd969c4c42281f36e218d5d3039af6c3146a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2016-05-28T07:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T04:28:21.000Z", "max_issues_repo_path": "src/CoreUtils/poly.jl", "max_issues_repo_name": "tclements/SeisIO.jl", "max_issues_repo_head_hexsha": "2bc58ef028f0b811b02340239c940fdec1288339", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 79, "max_issues_repo_issues_event_min_datetime": "2018-08-11T08:32:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T23:46:41.000Z", "max_forks_repo_path": "src/CoreUtils/poly.jl", "max_forks_repo_name": "tclements/SeisIO.jl", "max_forks_repo_head_hexsha": "2bc58ef028f0b811b02340239c940fdec1288339", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2017-05-08T00:52:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:57:21.000Z", "avg_line_length": 26.1428571429, "max_line_length": 93, "alphanum_fraction": 0.6129326047, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8376199714402813, "lm_q1q2_score": 0.7673517006970257}}
{"text": "#######################\r\n## Prepare libraries ##\r\n#######################\r\n\r\n# export JULIA_NUM_THREADS=4\r\n\r\nBASE_FOLDER = pwd()\r\n(basename(BASE_FOLDER) == \"examples\") && (BASE_FOLDER = dirname(BASE_FOLDER))\r\nusing Pkg\r\nPkg.activate(BASE_FOLDER)\r\n# Install all required packages if not present\r\nisfile(joinpath(BASE_FOLDER,\"Manifest.toml\")) || Pkg.instantiate()\r\n\r\nusing Combinatorics, Distributions, LightGraphs, LinearAlgebra, QuantEcon\r\nusing Roots, SymPy, Manifolds\r\nusing Nash\r\n\r\n## Create game from provided payoff matrices\r\n# Player 1 payoff matrix is\r\n    # 1  0\r\n    # 0  1\r\n# Player 2 payoff matrix is\r\n    # 1  0\r\n    # 1  1\r\ngenerate_game([1 0; 0 1], [1 0; 1 1])\r\n\r\n## Generate random game for 2 players.\r\n# First player has 2 actions and second player has 3 actions\r\n# Payoffs are sampled from standard normal Distributions\r\n\r\nrandom_2players_game(Normal(0,1),2,3)\r\n\r\n## Generate random game for 3 players.\r\n# First player has 2 actions, second player has 3 actions, third player has 3 actions\r\n# Payoffs are sampled from Binomial distribution with 5 trials and p = 0.5\r\n\r\nrandom_nplayers_game(Binomial(5,0.5),[2,3,3])\r\n\r\n## Get payoffs for each player from given mixed strategy profiles\r\n# Player 1 plays first and second action with p = 0.5\r\n# Player 2 plays first action with p = 0.75 and second action with p = 0.25\r\n\r\ngame = random_nplayers_game(Binomial(5,0.5),[2,2]);\r\ns = [[0.5,0.5],[0.75,0.25]]\r\ns[1]'*game[\"player2\"]*s[2]\r\nget_payoff(game,s)\r\n\r\n## Return best reply of first (k = 1) player\r\n# with perturbation epsil=0.5\r\nbest_reply(generate_game([1 0; 0 1], [1 0; 0 1]), [[1.0, 0.], [0, 1]], 1, 0.5)\r\n# no perturbation, with convex hull\r\na2 = best_reply(generate_game(Matrix(I,3,3), Matrix(I,3,3)), [[1/2,1/2,0],[1/3,1/3,1/3]], 1, return_val = \"chull\")\r\n# plot best responses\r\nplot_br(a2)\r\n\r\n# Check if passed strategy is best response for each player and is it a Nash equilibrium\r\nis_nash_q(generate_game([1 0 ; 0 1], [1 0; 0 1]), [[1, 0], [1, 0]])\r\n\r\n# Iteratively find best reply with perturbation (epsil=1/3) and limit of 10 iterations\r\ngame = generate_game(Matrix(I, 3, 3), Matrix(I, 3, 3))\r\ns = [[1/2,1/2, 0], [1/3,1/3,1/3]]\r\ngame_history = iterate_best_reply(game, s, 1/3, 10)\r\n\r\n\r\n# Transform game into Markov Chain\r\ngame = generate_game(Matrix(1I, 3, 3), Matrix(I, 3, 3))\r\ns = [[1, 0, 0],[0, 1, 0]]\r\nmc = game2markov(game, s)\r\nsimulate(mc, 9, init = 3)\r\nsimulate(mc, 9) # random initial condition\r\n\r\nis_irreducible(mc) # can we reach any state from any other state?\r\ncommunication_classes(mc)\r\nperiod(mc)\r\nis_aperiodic(mc)\r\nstationary_distributions(mc)\r\n\r\nplot_markov(10, mc)\r\n\r\n# Generate random symmetric game\r\ngame = random_symmetric_2players_game(Binomial(10,1/2),2)\r\n\r\n# Find necessary values to find symmetric nash equilibrium\r\nx = symbols(\"x\", real=true)\r\nfind_symmetric_nash_equilibrium_2players_game(game, [x, 1-x])\r\n\r\n# Create equations for replicator\r\ncreate_replicator_eqs(game, [x, 1-x])\r\n\r\n# Generate graph of relations that need to hold to make a game symmetric\r\nactions_no_vector = [2, 2, 2];\r\ngraph = create_symmetries_graph(actions_no_vector)\r\n\r\n# Check single relation\r\ncheck_equality_condition(graph,((2,2,1),1), ((2,1,2),1))\r\n\r\n# Find all needed relations\r\nfind_all_equalities(graph)\r\n\r\n# counting vFunction - three players coordination game\r\npay = reshape([1 0 0 0 0 0 0 1], (2,2,2))\r\ng1 = generate_game(pay, pay, pay)\r\nvFunction(g1, [[1, 0], [1, 0], [1, 0]])\r\nvFunction(g1, [[1, 0], [1, 0], [0, 1]])\r\n\r\n# Creates cartersian product of simplices\r\ns1 = [[1, 0], [1, 0], [0, 1]]\r\nv1 = cart_prod_simplices(s1)\r\n\r\ns2 = [[1, 0], [1, 0], [1, 2, 3]]\r\nv2 = cart_prod_simplices(s2)\r\n", "meta": {"hexsha": "d663263358409a28465d24cfb1446b048ad7631b", "size": 3629, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example.jl", "max_stars_repo_name": "KrainskiL/Nash.jl", "max_stars_repo_head_hexsha": "ac6f7efe622b4032c3a6bec2af8ba247040325ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-04-14T11:37:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:58:07.000Z", "max_issues_repo_path": "examples/example.jl", "max_issues_repo_name": "KrainskiL/Nash.jl", "max_issues_repo_head_hexsha": "ac6f7efe622b4032c3a6bec2af8ba247040325ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-03-31T16:04:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-14T07:13:46.000Z", "max_forks_repo_path": "examples/example.jl", "max_forks_repo_name": "KrainskiL/Nash.jl", "max_forks_repo_head_hexsha": "ac6f7efe622b4032c3a6bec2af8ba247040325ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-31T07:26:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T06:04:46.000Z", "avg_line_length": 32.4017857143, "max_line_length": 115, "alphanum_fraction": 0.6740148801, "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7673468957675825}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.20\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 0b868b30-6420-11eb-18f9-1592f7542fe6\nbegin\n    using PlutoUI\n    using Plots\n    using Printf\n\tusing SpecialFunctions\nend\n\n# ╔═╡ 4c4fff40-64c8-11eb-2c45-57f4793ee997\nmd\"_Parabolic Partial Differential Equation, version 1_\"\n\n# ╔═╡ 56d1f810-64c8-11eb-3e0d-81c0bbafdc62\nmd\"\"\"\n## **Parabolic Partial Differential Equation** \n#### **Description:**\nThis notebook computes the Parabolic Partial Differential Equation with 4 different discretization methods (2 explicit - 2 implicit)\n\n\t\tFTCS(Δt,Δy,ν)\n\t\tDuFortFrankel(Δt,Δy,ν)\n\t\tLaasonen(Δt,Δy,ν)\n\t\tCrankNicolson(Δt,Δy,ν)\n\nIf the arguments are missing, it will use the default values.\n    \n\t\tFTCS(Δt=0.002,Δy=0.001,ν=0.000217)\n\t\tDuFortFrankel(Δt=0.002,Δy=0.001,ν=0.000217)\n\t\tLaasonen(Δt=0.002,Δy=0.001,ν=0.000217)\n\t\tCrankNicolson(Δt=0.002,Δy=0.001,ν=0.000217)\n\n#### **Parabolic Partial Differential Equation**\nIn this problem, velocity profile between 2 infinite plates will be investigated. The bottom plates is moving with U₀ and the upper plate is stationary. The equation for the system can be represented by:\n\n$$\\frac{∂u}{∂t}=α\\frac{∂²u}{∂x²}$$\n\nBoundary conditions for the system:\n\n$$u=U₀=1 \\hspace{12pt} y=0$$\n$$u=0    \\hspace{36pt} y=h$$\n\nwhere h is the distance between two plates. In this problem, it is taken as 0.04m. The partial system of equation is solved using following discritizations:\n\n#### **Forward Time Central Space (FTCS) Method**\n\nIt is a first-order in time and second-order in space. The discritization for this partial equation:\n\n$$u_{i}^{n+1}=u_{i}^{n}+d(u_{i+1}^{n}-2u_{i}^{n}+u_{i-1}^{n})$$\n\nwhere\n\n$$d=\\frac{α(Δt)}{Δx^{2}}$$\n\nFor the stability condition:\n\n$$\\frac{α(Δt)}{Δx^{2}}=d\\leqslant0.5$$\n\n#### **DuFort-Frankel Method**\n\nIt is a second-order in time and second-order in space. The discritization for this partial equation:\n\n$$(1+2d)u_{i}^{n+1}=(1-2d)u_{i}^{n-1}+2d(u_{i+1}^{n}+u_{i-1}^{n})$$\n\nwhere\n\n$$d=\\frac{α(Δt)}{Δx^{2}}$$\n\nFor the stability condition:\n\n$$\\frac{α(Δt)}{Δx^{2}}\\leqslant0.5$$\n\nThis method requires 2 sets of initial data so in this notebook, FTCS is used to obtain data set at t=Δt.\n\n#### **Laasonen Method**\n\nIt is a first-order in time and second-order in space. The discritization for this partial equation:\n\n$$du_{i-1}^{n+1}-(1+2d)u_{i}^{n+1}+du_{i+1}^{n+1}=-u_{i}^{n}$$\n\nwhere\n\n$$d=\\frac{α(Δt)}{Δx^{2}}$$\n\nThis method is unconditionally stable.\n\n#### **Crank Nicholson Method**\n\nIt is a second-order in time and second-order in space. The discritization for this partial equation:\n\n$$-\\frac{1}{2}du_{i-1}^{n+1}-(1+d)u_{i}^{n+1}-\\frac{1}{2}du_{i+1}^{n+1}=\\frac{1}{2}du_{i-1}^{n}+(1-d)u_{i}^{n}+\\frac{1}{2}du_{i+1}^{n}$$\n\nwhere\n\n$$d=\\frac{α(Δt)}{Δx^{2}}$$\n\nThis method is unconditionally stable.\n\nDetails of schemes:\nComputational Fluid Dynamics, Volume I, Hoffmann - Chiang\n\n\nFeel free to ask questions!\n\n\n*Furkan Oz*\nfoz@okstate.edu\n\"\"\"\n\n# ╔═╡ 29683fb0-6419-11eb-05d0-2d7392bc8afa\n\"\"\"\nComputes the Forward Time Central Space for the Parabolic Partial Differential Equation\nThis notebook computes the Parabolic Partial Differential Equation\n\t\tFTCS(Δt,Δy,ν)\nIf the arguments are missing, it will use the default values.\n    \n\t\tFTCS(Δt=0.002,Δy=0.001,ν=0.000217)\nFurkan Oz,\nfoz@okstate.edu, \n    \n\"\"\"\nfunction FTCS(Δt=0.002,Δy=0.001,ν=0.000217)\n\t#ν=0.000217 # viscosity [m²/s]\n\th = 0.04 # Distance between 2 plate [m]\n\tT = 1.25 # Total time [s]\n\t#Δt = 0.002 # Time increment\n\tNt = T/Δt+1 # Number of time step\n\tNt = round(Int32,Nt)\n\t\n\t#Δy = 0.001 # Spacing between node points\n\ty = 0:Δy:h # y-coordinates\n\tNx = h/Δy+1 # Number of Node points\n\tNx = round(Int32,Nx)\n\t\n\tU₀ = 1 # Plate speed\n\td = ν*Δt/(Δy)^2\n\t#Initializing\n\tu = zeros(Nx,Nt) \n\t\n\t# Boundary Conditions\n\tu[1,:] = [U₀ for i=1:Nt]\n\tu[Nx,:] = [0 for i=1:Nt]\n\t\n\t# Initial Conditions\n\tu[:,1] = [0 for i=1:Nx]\n\tu[1,1] = U₀\n\tfor ii=1:Nt-1\n\t\tfor i=2:Nx-1\n\t\t\tu[i,ii+1] = u[i,ii]+d*(u[i+1,ii]-2*u[i,ii]+u[i-1,ii])\n\t\tend\n\tend\n\t\n\treturn u,y\n\t\nend\n\n# ╔═╡ 36be1c60-6442-11eb-204a-b37677c1acfd\n\"\"\"\nComputes the DuFort Frankel method for the Parabolic Partial Differential Equation\nThis notebook computes the Parabolic Partial Differential Equation\n\t\tDuFortFrankel(Δt,Δy,ν)\nIf the arguments are missing, it will use the default values.\n    \n\t\tDuFortFrankel(Δt=0.002,Δy=0.001,ν=0.000217)\nFurkan Oz,\nfoz@okstate.edu, \n    \n\"\"\"\nfunction DuFortFrankel(Δt=0.002,Δy=0.001,ν=0.000217)\n\t#ν=0.000217 # viscosity [m²/s]\n\th = 0.04 # Distance between 2 plate [m]\n\tT = 1.25 # Total time [s]\n\t#Δt = 0.002 # Time increment\n\tNt = T/Δt+1 # Number of time step\n\tNt = round(Int32,Nt)\n\t\n\t#Δy = 0.001 # Spacing between node points\n\ty = 0:Δy:h # y-coordinates\n\tNx = h/Δy+1 # Number of Node points\n\tNx = round(Int32,Nx)\n\t\n\tU₀ = 1 # Plate speed\n\td = ν*Δt/(Δy)^2\n\t#Initializing\n\tu = zeros(Nx,Nt) \n\t\n\t# Boundary Conditions\n\tu[1,:] = [U₀ for i=1:Nt]\n\tu[Nx,:] = [0 for i=1:Nt]\n\t\n\t# Initial Conditions\n\tu[:,1] = [0 for i=1:Nx]\n\tu[1,1] = U₀\n\tfor ii=1:1\n\t\tfor i=2:Nx-1\n\t\t\tu[i,ii+1] = u[i,ii]+d*(u[i+1,ii]-2*u[i,ii]+u[i-1,ii])\n\t\tend\n\tend\n\tfor ii=2:Nt-1\n\t\tfor i=2:Nx-1\n\t\t\tu[i,ii+1] = ((1-2*d)*u[i,ii-1]+2*d*(u[i+1,ii]+u[i-1,ii]))/(1+2*d)\n\t\tend\n\tend\n\treturn u,y\n\t\nend\n\n# ╔═╡ 899d6a70-6448-11eb-2870-692c6e93c421\n\"\"\"\nComputes the Laasonen method for the Parabolic Partial Differential Equation\nThis notebook computes the Parabolic Partial Differential Equation\n\t\tLaasonen(Δt,Δy,ν)\nIf the arguments are missing, it will use the default values.\n    \n\t\tLaasonen(Δt=0.002,Δy=0.001,ν=0.000217)\nFurkan Oz,\nfoz@okstate.edu, \n    \n\"\"\"\nfunction Laasonen(Δt=0.002,Δy=0.001,ν=0.000217)\n\t#ν=0.000217 # viscosity [m²/s]\n\th = 0.04 # Distance between 2 plate [m]\n\tT = 1.25 # Total time [s]\n\t#Δt = 0.002 # Time increment\n\tNt = T/Δt+1 # Number of time step\n\tNt = round(Int32,Nt)\n\t\n\t#Δy = 0.001 # Spacing between node points\n\ty = 0:Δy:h # y-coordinates\n\tNx = h/Δy+1 # Number of Node points\n\tNx = round(Int32,Nx)\n\t\n\tU₀ = 1 # Plate speed\n\td = ν*Δt/(Δy)^2\n\t\n\t#Initializing\n\tA = zeros(Nx,Nx)\n\tb = zeros(Nx)\n\tu = zeros(Nx,Nt)\n\t\n\t# Boundary Conditions\n\tA[1,1] = 1\n\tb[1] = U₀\n\tA[Nx,Nx] = 1\n\tb[Nx] = 0\n\t\n\t# Initial Conditions\n\tu[:,1] = [0 for i=1:Nx]\n\tu[1,1] = U₀\n\t\n\tfor ii=2:Nt-1\n\t\t# Boundary Conditions\n\t\tA[1,1] = 1\n\t\tb[1] = U₀\n\t\tA[Nx,Nx] = 1\n\t\tb[Nx] = 0\n\t\tfor i=2:Nx-1\n\t\t\tA[i,i-1] = d\n\t\t\tA[i,i+0] =-1-2*d\n\t\t\tA[i,i+1] = d\n\t\t\tb[i] =-u[i,ii]\n\t\tend\n\t\tulin = A\\b\n\t\tu[1,ii+1] = b[1]\n\t\tu[Nx,ii+1] = b[Nx]\n\t\tu[2:Nx-1,ii+1] = [ulin[i] for i=2:Nx-1]\n\tend\n\treturn u,y\nend\n\n# ╔═╡ 9c410110-644c-11eb-3bd9-93935242ac98\n\"\"\"\nComputes the Crank Nicolson method for the Parabolic Partial Differential Equation\nThis notebook computes the Parabolic Partial Differential Equation\n\t\tCrankNicolson(Δt,Δy,ν)\nIf the arguments are missing, it will use the default values.\n    \n\t\tCrankNicolson(Δt=0.002,Δy=0.001,ν=0.000217)\nFurkan Oz,\nfoz@okstate.edu, \n    \n\"\"\"\nfunction CrankNicolson(Δt=0.002,Δy=0.001,ν=0.000217)\n\t#ν=0.000217 # viscosity [m²/s]\n\th = 0.04 # Distance between 2 plate [m]\n\tT = 1.25 # Total time [s]\n\t#Δt = 0.002 # Time increment\n\tNt = T/Δt+1 # Number of time step\n\tNt = round(Int32,Nt)\n\t\n\t#Δy = 0.001 # Spacing between node points\n\ty = 0:Δy:h # y-coordinates\n\tNx = h/Δy+1 # Number of Node points\n\tNx = round(Int32,Nx)\n\t\n\tU₀ = 1 # Plate speed\n\td = ν*Δt/(Δy)^2\n\t\n\t#Initializing\n\tA = zeros(Nx,Nx)\n\tb = zeros(Nx)\n\tu = zeros(Nx,Nt)\n\t\n\t# Boundary Conditions\n\tA[1,1] = 1\n\tb[1] = U₀\n\tA[Nx,Nx] = 1\n\tb[Nx] = 0\n\t\n\t# Initial Conditions\n\tu[:,1] = [0 for i=1:Nx]\n\tu[1,1] = U₀\n\t\n\tfor ii=3:Nt-1\n\t\t# Boundary Conditions\n\t\tA[1,1] = 1\n\t\tb[1] = U₀\n\t\tA[Nx,Nx] = 1\n\t\tb[Nx] = 0\n\t\tfor i=2:Nx-1\n\t\t\tA[i,i-1] =-0.5*d\n\t\t\tA[i,i+0] = 1+d\n\t\t\tA[i,i+1] =-0.5*d\n\t\t\tb[i] = 0.5*d*u[i+1,ii]+(1-d)*u[i,ii]+0.5*d*u[i-1,ii]\n\t\tend\n\t\tulin = A\\b\n\t\tu[1,ii+1] = b[1]\n\t\tu[Nx,ii+1] = b[Nx]\n\t\tu[2:Nx-1,ii+1] = [ulin[i] for i=2:Nx-1]\n\tend\n\treturn u,y\nend\n\n# ╔═╡ 8939c23e-642a-11eb-2de6-ade5ae2f4b4d\nfunction Analytical(t,Δy=0.001,ν=0.000217)\n\t#ν=0.000217 # viscosity [m²/s]\n\th = 0.04 # Distance between 2 plate [m]\n\ty = 0:Δy:h\n\tNx = h/Δy+1 # Number of Node points\n\tNx = round(Int32,Nx)\n\tU₀ = 1 # Plate speed\n\tη = [y[i]/(2*sqrt(ν*t)) for i=1:Nx]\n\tη₁= h/(2*sqrt(ν*t))\n\tu = [U₀*(erfc(η[i])-erfc(2*η₁-η[i])+erfc(2*η₁+η[i])-erfc(4*η₁-η[i])+erfc(4*η₁+η[i])-erfc(8*η₁-η[i])+erfc(8*η₁+η[i])-erfc(16*η₁-η[i])) for i=1:Nx]\n\treturn u,y\nend\n\n# ╔═╡ 70d8c3ee-641f-11eb-1d57-a943a361c397\nbegin\n\tuFTCS,yFTCS = FTCS()\n\tplot([uFTCS[:,1],uFTCS[:,90],uFTCS[:,180],uFTCS[:,270],uFTCS[:,360],uFTCS[:,450],uFTCS[:,540]],yFTCS,\n\t\t\ttitle = \"FTCS - \\\\Deltat = 0.002 - \\\\Deltay = 0.001\",\n\t\t\tlabel = [\"t=0s\" \"t=0.18s\" \"t=0.36s\" \"t=0.54s\" \"t=0.72s\" \"t=0.90s\" \"t=1.08s\"],\n\t\t\tlegend = :topright,\n\t\t\tylims = (0,0.04),\n\t\t\txlabel = \"U\",\n\t\t\tylabel = \"y\",\n\t\t\tlinewidth = 2,\n\t\t\tlinecolor = :black,\n\t\t\tmarkershape = :auto,\n\t\t\tmarkercolor = :red,\n\t\t\t)\nend\n\n# ╔═╡ 95697270-6427-11eb-02be-bf3b75fbbd33\nbegin\n\tu2,y2 = FTCS(0.005,0.001)\n\t\n\tplot([u2[:,1],u2[:,50],u2[:,100],u2[:,150],u2[:,200]],y2,\n\t\t\ttitle = \"FTCS - \\\\Deltat = 0.005 - \\\\Deltay = 0.001\",\n\t\t\tlabel = [\"t=0s\" \"t=0.25s\" \"t=0.50s\" \"t=0.75s\" \"t=1.00s\"],\n\t\t\tlegend = :topright,\n\t\t\tylims = (0,0.04),\n\t\t\txlabel = \"U\",\n\t\t\tylabel = \"y\",\n\t\t\tlinewidth = 2,\n\t\t\tlinecolor = :black,\n\t\t\tmarkershape = :auto,\n\t\t\tmarkercolor = :red,\n\t\t\t)\nend\n\n# ╔═╡ b1e5b270-643f-11eb-1a37-e3227c598177\nbegin\n\tua1,ya1 = Analytical(0.18,0.001)\n\tuDF,yDF = DuFortFrankel()\n\tuLaasonen,yLaasonen = Laasonen()\n\tuCrankNicolson,yCrankNicolson = CrankNicolson()\n\tplot([ua1-uFTCS[:,90],ua1-uDF[:,90],ua1-uLaasonen[:,90],ua1-uCrankNicolson[:,90]],[ya1],\n\t\t\t\ttitle = \"Error - t = 0.18 - \\\\Deltay = 0.001\",\n\t\t\t\tlabel = [\"FTCS\" \"D/F\" \"Laasonen\" \"CrankNicolson\"],\n\t\t\t\tlegend = :topright,\n\t\t\t\txlims = (-0.005,0.01),\n\t\t\t\tylims = (0,0.04),\n\t\t\t\txlabel = \"U\",\n\t\t\t\tylabel = \"y\",\n\t\t\t\tlinewidth = 2,\n\t\t\t\tlinecolor = :black,\n\t\t\t\tmarkershape = :auto,\n\t\t\t\tmarkercolor = :red,\n\t\t\t\t)\nend\n\n# ╔═╡ 8c11e680-6440-11eb-076a-0b1e169ef37a\nbegin\n\tua2,ya2 = Analytical(1.08,0.001)\n\tplot([ua2-uFTCS[:,540],ua2-uDF[:,540],ua2-uLaasonen[:,540],ua2-uCrankNicolson[:,540]],[ya2],\n\t\t\t\ttitle = \"Error - t = 1.08 -\\\\Deltay = 0.001\",\n\t\t\t\tlabel = [\"FTCS\" \"D/F\" \"Laasonen\" \"CrankNicolson\"],\n\t\t\t\tlegend = :topright,\n\t\t\t\txlims = (-0.0005,0.0015),\n\t\t\t\tylims = (0,0.04),\n\t\t\t\txlabel = \"U\",\n\t\t\t\tylabel = \"y\",\n\t\t\t\tlinewidth = 2,\n\t\t\t\tlinecolor = :black,\n\t\t\t\tmarkershape = :auto,\n\t\t\t\tmarkercolor = :red,\n\t\t\t\t)\nend\n\n# ╔═╡ 33a79720-644e-11eb-0eca-e794b9b87ccf\nbegin\n\tua3,ya3 = Analytical(1.00,0.001)\n\tuLaasonen005,yLaasonen005 = Laasonen(0.005)\n\tuLaasonen01,yLaasonen01 = Laasonen(0.01)\n\tuLaasonen1,yLaasonen1 = Laasonen(0.1)\n\tuLaasonen2,yLaasonen2 = Laasonen(0.2)\n\tplot([ua3-uLaasonen005[:,200],ua3-uLaasonen01[:,100],ua3-uLaasonen1[:,10],ua3-uLaasonen2[:,5]],[ya2],\n\t\t\t\t\ttitle = \"Error - Laasonen - t = 1.00 -\\\\Deltay = 0.001\",\n\t\t\t\t\tlabel = [\"\\\\Deltat=0.005\" \"\\\\Deltat=0.01\" \"\\\\Deltat=0.1\" \"\\\\Deltat=0.2\"],\n\t\t\t\t\tlegend = :topright,\n\t\t\t\t\txlims = (0,0.2),\n\t\t\t\t\tylims = (0,0.04),\n\t\t\t\t\txlabel = \"U\",\n\t\t\t\t\tylabel = \"y\",\n\t\t\t\t\tlinewidth = 2,\n\t\t\t\t\tlinecolor = :black,\n\t\t\t\t\tmarkershape = :auto,\n\t\t\t\t\tmarkercolor = :red,\n\t\t\t\t\t)\nend\n\n# ╔═╡ Cell order:\n# ╟─0b868b30-6420-11eb-18f9-1592f7542fe6\n# ╟─4c4fff40-64c8-11eb-2c45-57f4793ee997\n# ╟─56d1f810-64c8-11eb-3e0d-81c0bbafdc62\n# ╟─29683fb0-6419-11eb-05d0-2d7392bc8afa\n# ╟─36be1c60-6442-11eb-204a-b37677c1acfd\n# ╟─899d6a70-6448-11eb-2870-692c6e93c421\n# ╟─9c410110-644c-11eb-3bd9-93935242ac98\n# ╟─8939c23e-642a-11eb-2de6-ade5ae2f4b4d\n# ╟─70d8c3ee-641f-11eb-1d57-a943a361c397\n# ╟─95697270-6427-11eb-02be-bf3b75fbbd33\n# ╟─b1e5b270-643f-11eb-1a37-e3227c598177\n# ╟─8c11e680-6440-11eb-076a-0b1e169ef37a\n# ╟─33a79720-644e-11eb-0eca-e794b9b87ccf\n", "meta": {"hexsha": "41dc515e6f40d6d4adac72da6576c67674cd274f", "size": 11519, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "003-Parabolic_PDE_4Methods.jl", "max_stars_repo_name": "frkanz/Computational-Aerodynamics-and-Hypersonics-Laboratory", "max_stars_repo_head_hexsha": "79fe89fd978f3653fc335cfd0dcd53e2427bc68e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-03T16:28:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-03T16:28:07.000Z", "max_issues_repo_path": "003-Parabolic_PDE_4Methods.jl", "max_issues_repo_name": "frkanz/Computational-Aerodynamics-and-Hypersonics-Laboratory", "max_issues_repo_head_hexsha": "79fe89fd978f3653fc335cfd0dcd53e2427bc68e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "003-Parabolic_PDE_4Methods.jl", "max_forks_repo_name": "frkanz/Computational-Aerodynamics-and-Hypersonics-Laboratory", "max_forks_repo_head_hexsha": "79fe89fd978f3653fc335cfd0dcd53e2427bc68e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-03T16:28:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T08:42:55.000Z", "avg_line_length": 24.9869848156, "max_line_length": 203, "alphanum_fraction": 0.6346905113, "num_tokens": 5269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8633916047011595, "lm_q1q2_score": 0.7673468758178309}}
{"text": "#=\nRoot finding and ODE solver.\nSee Numerical Recipes 16.1 - 16.2\n=#\n\nfunction fdjac{T<:AbstractFloat}(f::Function, x::Array{T, 1}; epsilon=1e-6)\n    #=\n    Forward difference Jacobian\n    =#\n    n = length(x)\n    y = f(x)\n    jacobian = Array{Float64}(n, n)\n    for i = 1:n\n        temp = x[i]\n        h = abs(x[i]) * epsilon\n        if h == 0.0\n            h = epsilon\n        end # if\n        x[i] = temp + h\n        h = x[i] - temp\n        ystep = f(x)\n        x[i] = temp\n        dy = (ystep - y) ./ h\n        jacobian[1:end, i] = dy\n    end # for\n    return jacobian\nend # fdjac\n\nfunction newton(f, x0; epsilon=1e-2, max_count=1000)\n    #=\n    Multidimensional Newton-Raphson root finding.\n    TODO: figure out scaled stopping critereon\n    =#\n    x = x0\n    count = 1\n    @info(\"newton: Starting Newton method with x0 = \", x0)\n    damping = 0.001\n    while true\n        @info(\"newton: count = \", count)\n        if count > max_count\n            @warn(\"newton: Number of iterations has exceeded \", max_count)\n            break\n        end # if\n        # approximate Jacobian\n        J = fdjac(f, x)\n        # invert for dx\n        invJ = inv(J)\n        dx = -invJ * f(x)\n        frac = dx ./ x\n        @info(\"newton: dx / x = \", frac)\n        # adaptive damping\n        if all(abs(frac) .< 0.1)\n            damping = 1\n        elseif any(abs(frac) .> 1)\n            # restrict to 1% change\n            damping = 0.01 / maximum(abs(frac))\n        else\n            # dampen to move no more than 10% change, and no more than 2\n            damping = minimum([0.1 / maximum(abs(frac)), 2 * damping])\n        end\n        @info(\"newton: damping = \", damping)\n        close_enough = all(abs(frac) .< epsilon)\n        x = x + dx .* damping\n        @info(\"newton: x = \", x)        \n        if close_enough\n            @info(\"newton: Zero-point found at x = \", x)\n            return x\n        end # if\n        count += 1\n    end # while\nend # newton\n\nfunction rkstep{T<:AbstractFloat}(f::Function,\n                                  y::Array{T, 1},\n                                  x::T,\n                                  h::T)\n    k1 = f(x, y)\n    k2 = f(x + h / 2, y + h / 2 .* k1)\n    k3 = f(x + h / 2, y + h / 2 .* k2)\n    k4 = f(x + h, y + h .* k3)\n    dy = h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)\n    return y + dy\nend # rkstep\n\nfunction rk{T<:AbstractFloat}(f::Function,\n                              y0::Array{T, 1},\n                              xrange::Array{T, 1})\n    #=\n    Classic fourth-order Runge-Kutta method\n    f(x, y) = dy / dx\n    Integrate from x0 to xf, y0 = y(x0)\n    =#\n    # @debug(\"rk: starting Runge-Kutta, y0 = \", y0, \", h = \", h)\n    x0 = xrange[1]\n    xf = xrange[end]\n    n = length(xrange)\n    m = length(y0)\n    x = Array{Float64}(n)\n    y = Array{Float64}(n, m)\n    x[1] = x0\n    y[1, 1:end] = y0\n    for (i, xstep) in enumerate(xrange[2:end])\n        j = i + 1\n        h = xstep - x[j - 1]\n        yy = rkstep(f, y[j - 1, 1:end], x[j - 1], h)\n        x[j] = xstep\n        y[j, 1:end] = yy\n    end # while\n    return x, y\nend # rk\n\n# TODO: finish adaptive step size\nfunction rkck{T<:AbstractFloat}(f::Array{Function, 1},\n                                x0::AbstractFloat,\n                                y0::Array{T, 1},\n                                h0::AbstractFloat,\n                                xf::AbstractFloat;\n                                epsilon=1e-3)\n    #=\n    Cash-Karp embedded Runge-Kutta method with adaptive step size.\n    f(x, y) = dy / dx\n    Integrate from x0 to xf, y0 = y(x0)\n    =#\n    # Butcher tableau for Cash-Karp\n    a = [0, 1 / 5, 3 / 10, 3 / 5, 1, 7 / 8]\n    b = zeros(6, 5)\n    b[2, 1] = 1/5\n    b[3, 1:2] = [3 / 40, 9 / 40]\n    b[4, 1:3] = [3 / 10, -9 / 10, 6 / 5]\n    b[5, 1:4] = [-11 / 54, 5 / 2, -70 / 27, 35 / 27]\n    b[6, :] = [1631 / 55296, 175 / 512, 575 / 13824, 44275 / 110592, 253 / 4096]\n    c = [37 / 378, 0, 250 / 621, 125 / 594, 0, 512 / 1771]\n    c_embedded = [2825 / 27648, 0, 18575 / 48384, 13525 / 55296, 277 / 14336, 1 / 4]\n\n    # number of equations\n    m = length(y0)\n    \n    x_list = []\n    y_list = []\n    h_list = []\n    push!(x_list, x0)\n    push!(y_list, y0)\n    push!(h_list, h0)\n    while x_list[end] < xf\n        xx = x_list[end]\n        yy = y_list[end]\n        hh = h_list[end]\n        k = zeros(6, m) # todo, speed up by putting column loop inside\n        k[1, :] = map(g -> hh * g(xx, yy), f)\n        for i = 2:6\n            for j = 1:m\n                k[i, j] = hh * f[j](xx + a[i] * hh, yy + dot(vec(b[i, 1:i - 1]), k[1:i - 1, j]))\n            end # for\n        end # for\n        delta = abs(map(i -> dot(c - c_embedded, k[:, i]), 1:m))\n        delta_target = epsilon * (abs(yy) + abs(vec(k[1, :])))\n        if any(delta .> delta_target)\n            # reject step, try a smaller step size\n            h_list[end] = 0.9 * hh * minimum(delta_target ./ delta) ^ 0.25\n            continue\n        else\n            # accept step\n            push!(h_list, 0.9 * hh * minimum(delta_target ./ delta) ^ 0.2)\n        end # if\n        # println(\"accepted\")\n        x_next = xx + hh\n        y_next = map(i -> yy[i] + dot(c, k[:, i]), 1:m)         \n        push!(x_list, x_next)\n        push!(y_list, y_next)\n    end # while\n    x = Array{Float64}(x_list)\n    h = Array{Float64}(h_list)\n    y = Array{Float64}(length(y_list), length(y_list[1]))\n    for i in 1:length(y_list)\n        y[i, 1:end] = y_list[i]\n    end #for\n    return x, y, h\nend # rkck\n\n", "meta": {"hexsha": "869075517d2c44c0320ad4bbb0c7ccb3258d9132", "size": 5439, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nr.jl", "max_stars_repo_name": "adwasser/StarStruc.jl", "max_stars_repo_head_hexsha": "8b26d86c216d21330d29818eefc1d966367612f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-13T08:01:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-13T08:01:32.000Z", "max_issues_repo_path": "src/nr.jl", "max_issues_repo_name": "adwasser/StarStruc.jl", "max_issues_repo_head_hexsha": "8b26d86c216d21330d29818eefc1d966367612f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nr.jl", "max_forks_repo_name": "adwasser/StarStruc.jl", "max_forks_repo_head_hexsha": "8b26d86c216d21330d29818eefc1d966367612f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2166666667, "max_line_length": 96, "alphanum_fraction": 0.46423975, "num_tokens": 1855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699844, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.7673166843124885}}
{"text": "## This file implements Example H071 using the MathProgBase Interface.\r\n## This is the example code from the MathProgBase test file from https://github.com/JuliaOpt/MathProgBase.jl/blob/master/test/nlp.jl , slightly modified to remove the tests.\r\n## This interface is solver independent, but will use Ipopt as the solver here.\r\n\r\nusing MathProgBase\r\nimport MathProgBase.MathProgSolverInterface   ##In Julia, importing means that the prefix 'MathProgSolverInterface.' must be included before calling any functions within this module\r\nusing Ipopt\r\n\r\ntic()  #Start the clock\r\n\r\n# Here the type represents the complete instance, but it\r\n# could also store instance data.\r\n# The abstract type AbstractNLPEvaluator is used by solvers for accessing the objective function f and constraints g.\r\n# Solvers may query the value, gradients, Hessian-vector products, and the Hessian of the Lagrangian.\r\ntype HS071 <: MathProgSolverInterface.AbstractNLPEvaluator\r\nend\r\n\r\n# hs071\r\n# min x1 * x4 * (x1 + x2 + x3) + x3\r\n# st  x1 * x2 * x3 * x4 >= 25\r\n#     x1^2 + x2^2 + x3^2 + x4^2 = 40\r\n#     1 <= x1, x2, x3, x4 <= 5\r\n# Start at (1,5,5,1)\r\n# End at (1.000..., 4.743..., 3.821..., 1.379...)\r\n\r\n## Initialize must be called before any other methods. The vector requested_features lists features requested by the solver.\r\nfunction MathProgSolverInterface.initialize(d::HS071, requested_features::Vector{Symbol})\r\n    for feat in requested_features\r\n        if !(feat in [:Grad, :Jac, :Hess])\r\n            error(\"Unsupported feature $feat\")\r\n        end\r\n    end\r\nend\r\n\r\n## Returns which features are available for the model HS071\r\nMathProgSolverInterface.features_available(d::HS071) = [:Grad, :Jac, :Hess]\r\n\r\n################################\r\n# Define the Objective Function\r\n################################\r\nMathProgSolverInterface.eval_f(d::HS071, x) = x[1] * x[4] * (x[1] + x[2] + x[3]) + x[3]\r\n\r\n###################\r\n# Constraint set\r\n##################\r\nfunction MathProgSolverInterface.eval_g(d::HS071, g, x)\r\n    g[1] = x[1]   * x[2]   * x[3]   * x[4]\r\n    g[2] = x[1]^2 + x[2]^2 + x[3]^2 + x[4]^2\r\nend\r\n\r\n#####################################\r\n# Gradient of the Objective Function\r\n#####################################\r\nfunction MathProgSolverInterface.eval_grad_f(d::HS071, grad_f, x)\r\n    grad_f[1] = x[1] * x[4] + x[4] * (x[1] + x[2] + x[3])\r\n    grad_f[2] = x[1] * x[4]\r\n    grad_f[3] = x[1] * x[4] + 1\r\n    grad_f[4] = x[1] * (x[1] + x[2] + x[3])\r\nend\r\n\r\n###################################################################################################################################\r\n##These functions collect the sparsity structures of the Jacobian matrix and the Hessian of the Lagrangian (row first then columns)\r\nMathProgSolverInterface.jac_structure(d::HS071) = [1,1,1,1,2,2,2,2],[1,2,3,4,1,2,3,4]\r\n# lower triangle only\r\nMathProgSolverInterface.hesslag_structure(d::HS071) = [1,2,2,3,3,3,4,4,4,4],[1,1,2,1,2,3,1,2,3,4]\r\n\r\n#########################################################################################################################\r\n##OR you could define the values of the non-zero elements. The function below does this for the Jacobian matrix and saves\r\n## them to the matrix J. There is no need to create the matrix J.\r\n####################################################################\r\nfunction MathProgSolverInterface.eval_jac_g(d::HS071, J, x)\r\n    # Constraint (row) 1\r\n    J[1] = x[2]*x[3]*x[4]  # 1,1\r\n    J[2] = x[1]*x[3]*x[4]  # 1,2\r\n    J[3] = x[1]*x[2]*x[4]  # 1,3\r\n    J[4] = x[1]*x[2]*x[3]  # 1,4\r\n    # Constraint (row) 2\r\n    J[5] = 2*x[1]  # 2,1\r\n    J[6] = 2*x[2]  # 2,2\r\n    J[7] = 2*x[3]  # 2,3\r\n    J[8] = 2*x[4]  # 2,4\r\nend\r\n\r\n####################################################################################################\r\n# Similarly for the Hessian -  σ = weight on objective function, μ = multipliers on the constraints\r\n####################################################################################################\r\nfunction MathProgSolverInterface.eval_hesslag(d::HS071, H, x, σ, μ)\r\n    # Again, only lower left triangle (since it is symmetric)\r\n    # Objective\r\n    H[1] = σ * (2*x[4])               # 1,1\r\n    H[2] = σ * (  x[4])               # 2,1\r\n    H[3] = 0                          # 2,2\r\n    H[4] = σ * (  x[4])               # 3,1\r\n    H[5] = 0                          # 3,2\r\n    H[6] = 0                          # 3,3\r\n    H[7] = σ* (2*x[1] + x[2] + x[3])  # 4,1\r\n    H[8] = σ * (  x[1])               # 4,2\r\n    H[9] = σ * (  x[1])               # 4,3\r\n    H[10] = 0                         # 4,4\r\n\r\n    # First constraint\r\n    H[2] += μ[1] * (x[3] * x[4])  # 2,1\r\n    H[4] += μ[1] * (x[2] * x[4])  # 3,1\r\n    H[5] += μ[1] * (x[1] * x[4])  # 3,2\r\n    H[7] += μ[1] * (x[2] * x[3])  # 4,1\r\n    H[8] += μ[1] * (x[1] * x[3])  # 4,2\r\n    H[9] += μ[1] * (x[1] * x[2])  # 4,3\r\n\r\n    # Second constraint\r\n    H[1]  += μ[2] * 2  # 1,1\r\n    H[3]  += μ[2] * 2  # 2,2\r\n    H[6]  += μ[2] * 2  # 3,3\r\n    H[10] += μ[2] * 2  # 4,4\r\n\r\nend\r\n\r\n\r\n# Now put this all together to define and solve the model.\r\n# First, define a model object and the solver to use\r\n    m = MathProgSolverInterface.model(MathProgBase.defaultNLPsolver )\r\n# The vector of lower bounds on the variables\r\n    l = [1,1,1,1]\r\n# The vector of upper bounds on the variables\r\n    u = [5,5,5,5]\r\n# Vector of lower bounds on the constraints\r\n    lb = [25, 40]\r\n# Vector of constraint upper bounds\r\n    ub = [Inf, 40]\r\n# Load the nonlinear programming problem into the model - syntax for loadnonlinearproblem!() is\r\n# loadnonlinearproblem!(m::AbstractMathProgModel, numVar, numConstr, l, u, lb, ub, sense, d::AbstractNLPEvaluator)\r\n    MathProgSolverInterface.loadnonlinearproblem!(m, 4, 2, l, u, lb, ub, :Min, HS071())\r\n## Set the initial values for the optimisation\r\n    MathProgSolverInterface.setwarmstart!(m,[1,5,5,1])\r\n\r\n## Solve the optimisation problem\r\n    MathProgSolverInterface.optimize!(m)\r\n## Let's see the termination status after solving\r\n    stat = MathProgSolverInterface.status(m)\r\n\r\n# Now let's see the solution.\r\n    x = MathProgSolverInterface.getsolution(m)\r\n\r\ntoc()\r\n\r\nprintln(x)\r\n\r\n", "meta": {"hexsha": "c5a5863f81bd943576639380d20293a27880f27b", "size": 6134, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JuMP/ipopt_MathProgBase.jl", "max_stars_repo_name": "floswald/ucl-econ-julia", "max_stars_repo_head_hexsha": "c0b9077382d4245fb1276ae2f517cc9372259c25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-08-18T00:50:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-18T00:50:53.000Z", "max_issues_repo_path": "JuMP/ipopt_MathProgBase.jl", "max_issues_repo_name": "floswald/ucl-econ-julia", "max_issues_repo_head_hexsha": "c0b9077382d4245fb1276ae2f517cc9372259c25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-05-01T13:10:23.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-14T08:44:31.000Z", "max_forks_repo_path": "JuMP/ipopt_MathProgBase.jl", "max_forks_repo_name": "floswald/ucl-econ-julia", "max_forks_repo_head_hexsha": "c0b9077382d4245fb1276ae2f517cc9372259c25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-04-25T11:54:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T01:23:04.000Z", "avg_line_length": 41.7278911565, "max_line_length": 182, "alphanum_fraction": 0.5278774046, "num_tokens": 1945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7673166820292007}}
{"text": "using DataStructures,Distributions,StatsBase,Random,Plots, LaTeXStrings; pyplot()\n\nfunction simMM1Wait(lambda,mu,T)\n    tNextArr = rand(Exponential(1/(lambda)))\n    tNextDep = Inf\n    t = tNextArr\n\n    waitingRoom = Queue{Float64}()\n    serverBusy = false\n    waitTimes = Array{Float64,1}()\n\n    while t<T\n        if t == tNextArr\n            if !serverBusy\n                tNextDep = t + rand(Exponential(1/mu))\n                serverBusy = true\n                push!(waitTimes,0.0)\n            else\n                enqueue!(waitingRoom,t)\n            end\n            tNextArr = t + rand(Exponential(1/(lambda)))\n        else\n            if length(waitingRoom) == 0\n               tNextDep = Inf\n               serverBusy = false\n            else\n               tArr = dequeue!(waitingRoom)\n               waitTime = t - tArr\n               push!(waitTimes, waitTime)\n               tNextDep = t + rand(Exponential(1/mu))\n            end\n        end\n        t = min(tNextArr,tNextDep)\n    end\n\n    return waitTimes\nend\n\nRandom.seed!(1)\nlambda, mu = 0.8, 1.0\nT = 10^3\n\ndata = simMM1Wait(lambda,mu,T)\nempiricalCDF = ecdf(data)\n\nF(x) = 1-(lambda/mu)*MathConstants.e^(-(mu-lambda)x)\nxGrid = 0:0.1:20\n\nplot(xGrid, F.(xGrid),\n\tc=:blue,label=\"Analytic CDF of waiting time\")\nplot!(xGrid, empiricalCDF(xGrid),\n\tc=:red,label=\"ECDF of waiting times\",  \n\txlabel=L\"x\", ylabel=L\"\\Prob(W \\leq x)\", xlims=(0,20),ylims=(0,1),\n\tlegend=:bottomright)", "meta": {"hexsha": "3750b8e97994a0ade100aff60929e324c8e93b73", "size": 1431, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "10_chapter/mm1DESwaitingTimes.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "10_chapter/mm1DESwaitingTimes.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "10_chapter/mm1DESwaitingTimes.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 26.5, "max_line_length": 81, "alphanum_fraction": 0.5632424878, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7673166728779794}}
{"text": "# VWN parameterization of the exchange correlation energy\nfunction excVWN( n::Array{Float64,1} )\n    # Constants\n    X1 = 0.75*(3.0/(2.0*pi))^(2.0/3.0)\n    A = 0.0310907\n    x0 = -0.10498\n    b = 3.72744\n    c = 12.9352\n    Q = sqrt(4*c-b*b)\n    X0 = x0*x0 + b*x0 + c\n    Npoints = size(n)[1]\n    out = zeros(Float64,Npoints)\n    for ip = 1:Npoints\n        rs = (4.0*pi/3.0*n[ip])^(-1.0/3.0) # Added internal conversion to rs\n        x = sqrt(rs)\n        X = x*x + b*x + c    \n        out[ip] = -X1/rs + A*( log(x^2/X) + 2*b/Q*atan(Q/(2*x + b))\n                  -(b*x0)/X0*( log((x-x0)*(x-x0)/X) + 2*(2*x0+b)/Q*atan(Q/(2*x + b)) ))\n    end\n    return out\nend\n\n# d/dn deriv of VWN parameterization of the exchange correlation energy\nfunction excpVWN( n::Array{Float64,1} )\n    # Constants\n    X1 = 0.75*(3.0/(2.0*pi))^(2.0/3.0)\n    A = 0.0310907\n    x0 = -0.10498\n    b = 3.72744\n    c = 12.9352\n    Q = sqrt(4.0*c - b*b)\n    X0 = x0*x0 + b*x0 + c\n    #\n    Npoints = size(n)[1]\n    out = zeros(Float64,Npoints)\n    for ip = 1:Npoints\n        rs = (4.0*pi/3.0*n[ip])^(-1.0/3.0) # Added internal conversion to rs\n        x = sqrt(rs)\n        X = x*x + b*x + c\n        dx = 0.5/x # Chain rule needs dx/drho!\n        out[ip] = dx*( 2.0*X1 / (rs*x)\n                  + A*( 2.0/x - (2*x+b)/X - 4*b/(Q*Q + (2*x+b)*(2*x+b))\n                  - (b*x0)/X0*( 2.0/(x-x0) - (2*x+b)/X - 4*(2*x0+b) /\n                    (Q*Q + (2*x+b) * (2*x+b)) ) ))\n        out[ip] = (-rs/(3*n[ip]))*out[ip] # Added d(rs)/dn from chain rule from rs to n conv\n    end\n    return out\nend\n", "meta": {"hexsha": "d2ab212b043f2959d2412fa600ba84ee2f93050f", "size": 1558, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PW/dft_01/LDA_VWN.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "PW/dft_02/LDA_VWN.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PW/dft_02/LDA_VWN.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 31.7959183673, "max_line_length": 92, "alphanum_fraction": 0.4762516046, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436405, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7672873019718519}}
{"text": "#spherecomponent.jl\n#Algorithm 2.3 of Random Eigenvalues by Alan Edelman\n\n#Experiment:    Random components of a vector on a sphere\n#Plot:          Histogram of a single component\n#Theory:        Beta distribution\n\n## Parameters\nt = 100000      # trials\nn = 12          # dimensions of sphere\ndx = 0.1        # bin size\n\n## Experiment\nv = randn(n, t)\nv = (v[1,:] ./ sqrt(sum(v.^2,1)))'\ngrid, count = hist(v, -1:dx:1)\n\n## Theory\nx = grid\ny = (gamma(n-1)/(2^(n-2)*gamma((n-1)/2)^2))*(1-x.^2).^((n-3)/2)\n\n## Plot\nusing Winston\np = FramedPlot()\nh = Histogram(count/(t*dx), step(grid))\nh.x0 = first(grid)\nadd(p, h)\nadd(p, Curve(x, y, \"color\", \"blue\", \"linewidth\", 2))\nif isinteractive()\n    Winston.display(p)\nelse\n    file(p, \"spherecomponent.png\")\nend\n", "meta": {"hexsha": "14e4c815e74536a4afeb2fe1b36783f842c72a1e", "size": 749, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demos/book/2/spherecomponent.jl", "max_stars_repo_name": "shashi/RandomMatrices.jl", "max_stars_repo_head_hexsha": "603b9e9acd95133839e804d6ef068cdfee4cbbfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2017-09-29T08:46:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T10:05:30.000Z", "max_issues_repo_path": "demos/book/2/spherecomponent.jl", "max_issues_repo_name": "shashi/RandomMatrices.jl", "max_issues_repo_head_hexsha": "603b9e9acd95133839e804d6ef068cdfee4cbbfb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2017-08-18T19:50:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-15T08:08:44.000Z", "max_forks_repo_path": "demos/book/2/spherecomponent.jl", "max_forks_repo_name": "shashi/RandomMatrices.jl", "max_forks_repo_head_hexsha": "603b9e9acd95133839e804d6ef068cdfee4cbbfb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2018-01-05T22:05:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T20:25:41.000Z", "avg_line_length": 22.0294117647, "max_line_length": 63, "alphanum_fraction": 0.611481976, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436405, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7672872929702247}}
{"text": "function fft(a)\n    y1 = Any[]; y2 = Any[]\n    n = length(a)\n    if n ==1 return a end\n    wn(n) = exp(-2*π*im/n)\n    y_even = fft(a[1:2:end])\n    y_odd = fft(a[2:2:end])\n    w = 1\n    for k in 1:Int(n/2)\n        push!(y1, y_even[k] + w*y_odd[k])\n        push!(y2, y_even[k] - w*y_odd[k])\n        w = w*wn(n)\n    end\n    return vcat(y1,y2)\nend\n", "meta": {"hexsha": "0539d7e622a9dbe867348e3ada9ee498c9eec695", "size": 344, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/fast-fourier-transform-4.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/fast-fourier-transform-4.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/fast-fourier-transform-4.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5, "max_line_length": 41, "alphanum_fraction": 0.4738372093, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9674102514755852, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.767258827681805}}
{"text": "struct Grid{FT<:Real}\n\txmin :: FT\n\txmax :: FT\n\tnx   :: Int\n\tδx   :: FT\n\txc   :: Array{FT}\n\txf   :: Array{FT}\n\tymin :: FT\n\tymax :: FT\n\tny   :: Int\n\tδy   :: FT\n\tyc   :: Array{FT}\n\tyf   :: Array{FT}\nend\n\nfunction GenerateGrid(\n\tFT = Float64;\n\tsize, x, y,\n)\n\n\tnx,ny = size\n\txmin,xmax = x\n\tymin,ymax = y\n\n\txv = collect(range(xmin,xmax,length=nx+1)); δx = (xv[end] - xv[1]) / nx\n\txf = xv[2:end]\n\txc = (xv[1:(end-1)] .+ xv[2:end]) / 2\n    yf = collect(range(ymin,ymax,length=ny+1)); δy = (yf[end] - yf[1]) / ny\n\tyc = (yf[1:(end-1)] .+ yf[2:end]) / 2\n\n\treturn Grid{FT}(\n\t\txmin,xmax,nx,δx,xc,xf,\n\t\tymin,ymax,ny,δy,yc,yf\n\t)\n\nend\n\nfunction show(io::IO, g::Grid{FT}) where FT <: Real\n    print(\n\t\tio,\n\t\t\"The Grid{$FT} is defined as follows:\\n\",\n\t\t\"                  domain : x ∈ [$(g.xmin), $(g.xmax)], y ∈ [$(g.ymin), $(g.ymin)]\\n\",\n\t\t\"      resolution (nx,ny) : \", (g.nx,g.ny), '\\n',\n\t\t\"    grid spacing (δx,δy) : \", (g.δx,g.δy), '\\n'\n\t)\nend\n", "meta": {"hexsha": "8253028d27ce894521689eec9f011dab459ed3af", "size": 932, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Grid.jl", "max_stars_repo_name": "natgeo-wong/GillMatsuno.jl", "max_stars_repo_head_hexsha": "b351f6453281af4f9600d36317da0b3ca0db220b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-12-20T18:49:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T09:59:07.000Z", "max_issues_repo_path": "src/Grid.jl", "max_issues_repo_name": "natgeo-wong/GillMatsuno.jl", "max_issues_repo_head_hexsha": "b351f6453281af4f9600d36317da0b3ca0db220b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-12-20T18:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T03:19:20.000Z", "max_forks_repo_path": "src/Grid.jl", "max_forks_repo_name": "natgeo-wong/GillMatsuno.jl", "max_forks_repo_head_hexsha": "b351f6453281af4f9600d36317da0b3ca0db220b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:53:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:53:38.000Z", "avg_line_length": 19.829787234, "max_line_length": 88, "alphanum_fraction": 0.5096566524, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7672452176720788}}
{"text": "#overlap funcs {{{\n## for binary states {{{\nexport overlap, overlapm\n\nfunction overlap{T<:Real}(x::AbstractVector{T},y::AbstractVector{T})\n    return dot(x, y)/length(x)\nend\n\nfunction overlap{T<:Real}(x::AbstractVector{Complex{T}},y::AbstractVector{Complex{T}})\n    rsum = dot(real(x), real(y))\n    isum = dot(imag(x), imag(y))\n    return (rsum+isum)/length(x)*0.5\nend\n\nfunction overlap{T<:Real}(x::AbstractVector{Quaternion{T}},y::AbstractVector{Quaternion{T}})\n    rsum = dot(real(x), real(y))\n    isum = dot(imagi(x), imagi(y))\n    jsum = dot(imagj(x), imagj(y))\n    ksum = dot(imagk(x), imagk(y))\n    return (rsum+isum+jsum+ksum)/length(x)*0.25\nend\n## }}}\n\n## for multi states {{{\nfunction overlapm{T<:Real}(x::AbstractVector{T},y::AbstractVector{T})\n    return sum(x .== y)/length(x)\nend\n\nfunction overlapm{T<:Real}(x::AbstractVector{Complex{T}},y::AbstractVector{Complex{T}})\n    rsum = sum(real(x).== real(y))\n    isum = sum(imag(x).== imag(y))\n    return (rsum+isum)/length(x)*0.5\nend\n\nfunction overlapm{T<:Real}(x::AbstractVector{Quaternion{T}},y::AbstractVector{Quaternion{T}})\n    rsum = sum(real(x).== real(y))\n    isum = sum(imagi(x).== imagi(y))\n    jsum = sum(imagj(x).== imagj(y))\n    ksum = sum(imagk(x).== imagk(y))\n    return (rsum+isum+jsum+ksum)/length(x)*0.25\nend\n## }}}\n", "meta": {"hexsha": "6c6a0e78611c9af0dcf7d4270e2d248e12c02d75", "size": 1293, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/overlap.jl", "max_stars_repo_name": "peakbook/HopfieldNetworks.jl", "max_stars_repo_head_hexsha": "b7bc6d280df9c20e16ba289b0e11998ad16c405c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-02T06:07:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-02T06:07:49.000Z", "max_issues_repo_path": "src/overlap.jl", "max_issues_repo_name": "peakbook/HopfieldNetworks.jl", "max_issues_repo_head_hexsha": "b7bc6d280df9c20e16ba289b0e11998ad16c405c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/overlap.jl", "max_forks_repo_name": "peakbook/HopfieldNetworks.jl", "max_forks_repo_head_hexsha": "b7bc6d280df9c20e16ba289b0e11998ad16c405c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-13T09:44:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T09:44:19.000Z", "avg_line_length": 30.0697674419, "max_line_length": 93, "alphanum_fraction": 0.6380510441, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7672452103428922}}
{"text": "\"\"\"\n    eliminate!(g::SimpleGraph{Int64}, v::Int64, labels)::Nothing\nConnect neighbors of v (in graph g) together if they are not already connected, delete v\nand update the labels array. Labels is pop and element v updated.\n\n# Arguments\n- `g::SimpleGraph{Int64}` the graph to consider.\n- `v::Int64` the vertex to eliminate.\n- `labels::Vector{Int64}` labels to keep track of nodes id in original graph before elimination.\n\n# Return\n- Nothing.\n\"\"\"\nfunction eliminate!(g::SimpleGraph{Int64}, v::Int64, labels::Vector{Int64})::Nothing\n    ns = neighbors(g, v)\n    len = length(ns)\n    for i = 1:(len-1)\n        for j = (i+1):len\n            add_edge!(g, ns[i], ns[j])\n        end\n    end\n    rem_vertex!(g, v)\n    labels[v] = labels[end]\n    pop!(labels)\n    nothing\nend\n\n\"\"\"\n    treewidth_by_elimination!(g::SimpleGraph{Int64}, order::Vector{Int64})\nComputes the treewidth by eliminating in order vertices of the graph and keep track of the max degree.\n\n# Arguments\n- `g::SimpleGraph{Int64}` the graph to consider.\n- `order::Vector{Int64}` the vertex elimination order to perform.\n\n# Return\n- `treewidth::Int64` the max degree of vertices during elimination.\n\"\"\"\nfunction treewidth_by_elimination!(g::SimpleGraph{Int64}, order::Vector{Int64})::Int64\n    treewidth = 0\n    n = nv(g)\n    labels = collect(1:n)\n    for rm_origin_id in order\n        toremove = findfirst(id -> id == rm_origin_id, labels)\n        treewidth = max(treewidth, degree(g, toremove))\n        eliminate!(g, toremove, labels)\n    end\n    return treewidth\nend\n\n\n\"\"\"\n    tree_order!(graph, nodes)\nComputes the optimal elimination order for nodes in a tree. Graph is modified, all its edges are deleted.\n\n# Arguments\n- `graph::SimpleGraph{Int64}` the subtree to consider.\n- `nodes::Vector{Int64}` indices of nodes in the root greaph.\n\n# Return\n- `order::Vector{Int64}` vertex elimination order (indices in the root graph) to get treewidth of 1 in the subtree.\n\"\"\"\nfunction tree_order!(graph::SimpleGraph{Int64}, nodes::Vector{Int64})::Vector{Int64}\n    n = length(nodes)\n    eliminated = 1\n    order = zeros(Int64, n)\n    leafs = filter(node -> length(neighbors(graph, node)) == 1, 1:n)\n\n    # trick to get the last node\n    lastnode = sum(nodes)\n    while eliminated < n\n        parents = unique(map(it -> neighbors(graph, it)[1], leafs))\n        for rm in leafs\n            order[eliminated] = nodes[rm]\n            lastnode -= nodes[rm]\n            if ne(graph) != 0\n                rem_edge!(graph, rm, neighbors(graph, rm)[1])\n            end\n            eliminated += 1\n        end\n        # new leafs are parents with 1 neighbors\n        leafs = filter(\n            node -> length(neighbors(graph, node)) == 1,\n            parents\n        )\n    end\n    # fix last node have no neighbor because all edges are deleted\n    if order[n] == 0\n        order[n] = lastnode\n    end\n    return order\nend\n\n\"\"\"\n    graph_from_gr(filename::String)\n\nRead a graph from the provided gr file.\n\"\"\"\nfunction graph_from_gr(filename::String)::SimpleGraph{Int64}\n    lines = readlines(filename)\n\n    # Create a Graph with the correct number of vertices.\n    num_vertices, num_edges = parse.(Int, split(lines[1], ' ')[3:end])\n    G = SimpleGraph(num_vertices)\n\n    # Add an edge to the graph for every other line in the file.\n    for line in lines[2:end]\n        src, dst = parse.(Int, split(line, ' '))\n        add_edge!(G, src, dst)\n    end\n\n    G\nend\n\n\"\"\"\n    square_lattice_graph(n::Int64)\nReturn a square lattice graph of dimension n. The dimension means\na big square made of n x n squares so (n+1)² nodes in total.\n\n# Example\n\nn = 2 give a graph like this:\n    1 ---- 2 ---- 3\n    |      |      |\n    4 ---- 5 ---- 6\n    |      |      |\n    7 ---- 8 ---- 9\n\n\"\"\"\nfunction square_lattice_graph(n::Int64)::SimpleGraph{Int64}\n    nrow = (n + 1)\n    nvertices =  nrow * nrow\n    g = SimpleGraph{Int64}(nvertices)\n    for i in 1:nvertices\n        if i % nrow != 0\n            add_edge!(g, i, i + 1)\n        end\n        if trunc(i / nrow) < nrow - 1\n            add_edge!(g, i, i + nrow)\n        end\n    end\n    return g\nend\n", "meta": {"hexsha": "c0c4f76757d7ea3f25ea15ce33b7613a3684255b", "size": 4073, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "mroavi/VertexEliminationOrder.jl", "max_stars_repo_head_hexsha": "023c269b6265aafaaf382636f4bd002344069952", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-16T09:30:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T00:14:28.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "mroavi/VertexEliminationOrder.jl", "max_issues_repo_head_hexsha": "023c269b6265aafaaf382636f4bd002344069952", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-08-11T09:04:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-23T17:00:01.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "mroavi/VertexEliminationOrder.jl", "max_forks_repo_head_hexsha": "023c269b6265aafaaf382636f4bd002344069952", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-03T23:54:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:54:33.000Z", "avg_line_length": 28.2847222222, "max_line_length": 115, "alphanum_fraction": 0.6241099926, "num_tokens": 1136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7672088853289715}}
{"text": "# These are the functions that need to be imported so that new methods do not overwrite old ones\r\nimport Base.show\r\nimport Base.one\r\nimport Base.∘\r\nimport Base.inv\r\nimport Base.^\r\nimport Base.:(==)\r\n\r\n\"\"\"\r\n    Permutation(image::Vector{Int64})\r\n    Permutation(xs...::Int64)\r\n\r\nA function ℕ → ℕ which fixes all but finitely many points.\r\n\r\nConstruct a `Permutation` from a vector of integers as the image of the integers `1:length(image)`.\r\n\r\nAlternatively, construct from an arbitrary list of integers.\r\n\r\n# Examples\r\n```julia-repl\r\njulia> Permutation([1,5,3,2,4])\r\n( 2 4 5 )\r\n\r\njulia> Permutation(4,5,2,3,1)\r\n( 1 5 2 3 4 )\r\n```\r\n\"\"\"\r\nstruct Permutation\r\n    image::Vector{Int64}\r\n    # An inner constructor checks that the permutation is valid\r\n    function Permutation(image::Vector{Int64})\r\n        m = maximum([image[image .!= 1:length(image)]..., 1])\r\n        sort(image) == 1:length(image) && return new(image[1:m])\r\n        error(\"not a valid permutation\")\r\n    end\r\nend\r\n\r\nPermutation(imagevals::Int64...) = Permutation([x for x ∈ imagevals])\r\n\r\n\"\"\"\r\n    maxarg(σ::Permutation)\r\n\r\nFind the largest integer which the `Permutation` `σ` does not fix.\r\n\r\nFor the identity `Permutation`, return `1`.\r\n\r\n# Examples\r\n```julia-repl\r\njulia> maxarg(Permutation(1,3,2,4))\r\n3\r\n\r\njulia> maxarg(ι)\r\n1\r\n```\r\n\"\"\"\r\nmaxarg(σ::Permutation) = length(σ.image)\r\n\r\n\"\"\"\r\n    (σ::Permutation)(x::Int64)\r\n\r\nEvaluate the action of the `Permutation` `σ` on `x`.\r\n\r\n# Examples\r\njulia> σ = Permutation(4,5,2,1,3)\r\n( 1 4 )( 2 5 3 )\r\n\r\njulia> σ(5)\r\n3\r\n\"\"\"\r\n(σ::Permutation)(x::Int64) = x ∈ 1:maxarg(σ) ? σ.image[x] : x\r\n\r\n\"\"\"\r\n    orbit(σ::Permutation,x::Int64)\r\n\r\nCompute the orbit of `x` under the repeated action of the `Permutation` `σ`.\r\n\r\n# Examples\r\n```julia-repl\r\njulia> orbit(Permutation(2,3,4,5,1),3)\r\n5-element Vector{Int64}:\r\n 3\r\n 4\r\n 5\r\n 1\r\n 2\r\n```\r\n\"\"\"\r\nfunction orbit(σ::Permutation, x::Int64)\r\n    orb = [x]\r\n    y = σ(x)\r\n    while y != x\r\n        push!(orb,y)\r\n        y = σ(y)\r\n    end\r\n    return orb\r\nend\r\n\r\n\"\"\"\r\n    dcd(σ::Permutation)\r\n\r\nCompute the disjoint cycle decomposition of the `Permutation` `σ`.\r\n\r\nIf an integer is fixed by `σ`, then it is not included in the decomposition.\r\n\r\n# Examples\r\n```julia-repl\r\njulia> dcd(Permutation(4,3,5,1,2))\r\n2-element Vector{Vector{Int64}}:\r\n [1, 4]\r\n [2, 3, 5]\r\n\r\njulia> dcd(Permutation(1,3,2))\r\n1-element Vector{Vector{Int64}}:\r\n [2, 3]\r\n```\r\n\"\"\"\r\nfunction dcd(σ::Permutation)\r\n    decomp = Vector{Int64}[]\r\n    unaccounted = trues(maxarg(σ))\r\n    while any(unaccounted)\r\n        x = findfirst(unaccounted)\r\n        xorbit = orbit(σ,x)\r\n        unaccounted[xorbit] .= false\r\n        length(xorbit) > 1 && push!(decomp,xorbit)\r\n    end\r\n    return decomp\r\nend\r\n\r\nfunction show(io::IO,σ::Permutation)\r\n    toprint = *([ *( \"( \", [\"$y \" for y ∈ x]... , \")\" ) for x ∈ dcd(σ)]..., \"\")\r\n    toprint == \"\" && (toprint = \"ι\")\r\n    print(io, toprint)\r\nend\r\n\r\n\"\"\"\r\n    ι\r\n\r\nThe identity `Permutation`.\r\n\r\n# Examples\r\n```julia-repl\r\njulia> ι.(1:10) == 1:10\r\ntrue\r\n```\r\n\"\"\"\r\nconst ι = Permutation(1)\r\none(::Permutation) = ι\r\none(::Type{Permutation}) = ι\r\n\r\n\"\"\"\r\n    ∘(σ::Permutation)\r\n    ∘(σ::Permutation, τ::Permutation)\r\n    ∘(σs...::Permutation)\r\n\r\nCompose `Permutation`s.\r\n\r\nCompose a single `Permutation` and recieve it back.\r\n\r\n# Examples\r\n```julia-repl\r\njulia> ∘(Permutation(1,2,4,3))\r\n( 3 4 )\r\n\r\njulia> Permutation(5,2,3,1,4) ∘ Permutation(2,1,4,5,3)\r\n( 1 2 5 3 )\r\n```\r\n\"\"\"\r\n∘(σ::Permutation) = σ\r\n∘(σ::Permutation, τ::Permutation) = Permutation([σ(τ(x)) for x ∈ 1:max(maxarg(σ),maxarg(τ))])\r\n∘(σ::Permutation, τ::Permutation, υ::Permutation...) = ∘(σ ∘ τ, υ...)\r\n\r\ninv(σ::Permutation) = Permutation([findfirst(σ.image .== x) for x ∈ 1:maxarg(σ)])\r\n\r\n\"\"\"\r\n    ^(σ::Permutation,n::Int)\r\n\r\nExponentiate a `Permutation` `σ` by an integer `n`.\r\n\r\nIf `n` is negative, compute the inverse and exponentiate by `-n`.\r\n```julia-repl\r\njulia> Permutation(5,4,2,3,1)^5\r\n( 1 5 )( 2 3 4 )\r\n\r\njulia> Permutation(5,4,2,3,1)^-5\r\n( 1 5 )( 2 4 3 )\r\n```\r\n\"\"\"\r\nfunction ^(σ::Permutation,n::Int64)\r\n    n == 0 && return one(Permutation)\r\n    n < 0 && ((n,σ) = (-n,inv(σ)))\r\n    return ∘(fill(σ,n)...)\r\nend\r\n\r\n\"\"\"\r\n    transposition(m::Int64,n::Int64)\r\n\r\nCreate the `Permutation` which is a transposition of `m` and `n`.\r\n\r\nIf `m == n`, the `Permutation` created is the identity.\r\n\r\n# Examples\r\n```julia-repl\r\njulia> transposition(4,5)\r\n( 4 5 )\r\n\r\njulia> transposition(6,6)\r\nι\r\n```\r\n\"\"\"\r\nfunction transposition(m::Int64, n::Int64)\r\n    image = collect(1:max(m,n))\r\n    image[m], image[n] = n, m\r\n    return Permutation(image)\r\nend\r\n\r\n\"\"\"\r\n    symmetricgroup(n::Int64)\r\n\r\nCompute the `Permutation`s which make up the symmetric group of order `factorial(n)`.\r\n\r\n# Examples\r\n```julia-repl\r\njulia> symmetricgroup(5)\r\n120-element Vector{Permutation}:\r\n[...]\r\n```\r\n\"\"\"\r\nfunction symmetricgroup(n::Int64)\r\n    n ≥ 1 || error(\"symmetric group must have a positive parameter\")\r\n    n == 1 && return [ι]\r\n\r\n    permutations = vcat(fill(symmetricgroup(n-1),n)...)\r\n    transpositions = vcat([fill(transposition(i,n),factorial(n-1)) for i ∈ 1:n]...)\r\n    return permutations .∘ transpositions\r\nend\r\n\r\n\"\"\"\r\n    parity(σ::Permutation)\r\n\r\nCompute the parity of the `Permutation` `σ`.\r\n\r\n# Examples\r\n```julia-repl\r\njulia> parity(Permutation(1,2,3,5,4))\r\n-1\r\n\r\njulia> parity(ι)\r\n1\r\n```\r\n\"\"\"\r\nparity(σ::Permutation) = (-1)^sum([iseven(length(x)) for x ∈ dcd(σ)])\r\n\r\n\"\"\"\r\n    alternatinggroup(n::Int64)\r\n\r\nCompute the `Permutation`s which make up the `n`th alternating group.\r\n\r\n# Examples\r\n```julia-repl\r\njulia> alternatinggroup(5)\r\n60-element Vector{Permutation}:\r\n[...]\r\n```\r\n\"\"\"\r\nfunction alternatinggroup(n::Int64)\r\n    Sₙ = symmetricgroup(n)\r\n    return Sₙ[parity.(Sₙ) .== 1]\r\nend\r\n\r\n# Defines equality of permutations, to be used to check ∉\r\n==(σ::Permutation, τ::Permutation) = (σ.image == τ.image)\r\n\r\n\"\"\"\r\n    generate(σs::Permutation...)\r\n\r\nCompute the elements of the group generated by the elements listed.\r\n\r\n# Examples\r\n```julia-repl\r\njulia> generate(Permutation(2,3,4,1))\r\n4-element Vector{Permutation}:\r\n ( 1 2 3 4 )\r\n ( 1 3 )( 2 4 )\r\n ( 1 4 3 2 )\r\n ι\r\n\r\n julia> generate(Permutation(2,3,4,5,1),Permutation(5,4,3,2,1))\r\n 10-element Vector{Permutation}:\r\n  ( 1 2 3 4 5 )\r\n  ( 1 5 )( 2 4 )\r\n  ( 1 3 5 2 4 )\r\n  ( 2 5 )( 3 4 )\r\n  ( 1 5 4 3 2 )\r\n  ( 1 4 )( 2 3 )\r\n  ι\r\n  ( 1 4 2 5 3 )\r\n  ( 1 2 )( 3 5 )\r\n  ( 1 3 )( 4 5 )\r\n```\r\n\"\"\"\r\nfunction generate(σs::Permutation...)\r\n    G = [σs...]\r\n    while true\r\n        newelements = Permutation[]\r\n\r\n        for σ ∈ G, τ ∈ G\r\n            υ = σ ∘ τ\r\n            υ ∉ G && υ ∉ newelements && push!(newelements, υ)\r\n        end\r\n\r\n        if isempty(newelements)\r\n            return G\r\n        else\r\n            G = vcat(G,newelements)\r\n        end\r\n    end\r\nend\r\n", "meta": {"hexsha": "acbbb5edf9814c3f4606241d90168cbc1e13ae6e", "size": 6714, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "casestudies/Permutations/permutations.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "casestudies/Permutations/permutations.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "casestudies/Permutations/permutations.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 21.1132075472, "max_line_length": 100, "alphanum_fraction": 0.5878760798, "num_tokens": 2248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7672088705721946}}
{"text": "\nusing DiffEqBayes, OrdinaryDiffEq, RecursiveArrayTools, Distributions, Plots, StatsPlots, BenchmarkTools, TransformVariables, CmdStan, DynamicHMC\n\n\nfunction pendulum(du,u,p,t)\n    ω,L = p\n    x,y = u\n    du[1] = y\n    du[2] = - ω*y -(9.8/L)*sin(x)\nend\n\nu0 = [1.0,0.1]\ntspan = (0.0,10.0)\nprob1 = ODEProblem(pendulum,u0,tspan,[1.0,2.5])\n\n\nsol = solve(prob1,Tsit5())\nplot(sol)\n\n\nt = collect(range(1,stop=10,length=10))\nrandomized = VectorOfArray([(sol(t[i]) + .01randn(2)) for i in 1:length(t)])\ndata = convert(Array,randomized)\n\n\nscatter!(data')\n\n\npriors = [Uniform(0.1,3.0), Normal(3.0,1.0)]\n\n\nbayesian_result = turing_inference(prob1,Tsit5(),t,data,priors;num_samples=10_000,\n                                   syms = [:omega,:L])\n\n\nplot(bayesian_result)\n\n\nplot(bayesian_result, colordim = :parameter)\n\n\n@btime bayesian_result = turing_inference(prob1,Tsit5(),t,data,priors;syms = [:omega,:L],num_samples=10_000)\n\n\n@btime bayesian_result = stan_inference(prob1,t,data,priors;num_samples=10_000,printsummary=false)\n\n\n@btime bayesian_result = dynamichmc_inference(prob1,Tsit5(),t,data,priors;num_samples = 10_000)\n\n", "meta": {"hexsha": "d3cc3507219741c4b262e86c4efe92a46935de91", "size": 1114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/models/06-pendulum_bayesian_inference.jl", "max_stars_repo_name": "isaacsas/DiffEqTutorials.jl", "max_stars_repo_head_hexsha": "46c1701ef613aacbd678bde7437a3c8de363990d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-05-24T10:30:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T12:13:03.000Z", "max_issues_repo_path": "script/models/06-pendulum_bayesian_inference.jl", "max_issues_repo_name": "LoopGlitch26/SciMLTutorials.jl", "max_issues_repo_head_hexsha": "837d71ad59de12af2fa48babb9e5cd2e280dc71a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-07T21:39:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T03:48:31.000Z", "max_forks_repo_path": "script/models/06-pendulum_bayesian_inference.jl", "max_forks_repo_name": "LoopGlitch26/SciMLTutorials.jl", "max_forks_repo_head_hexsha": "837d71ad59de12af2fa48babb9e5cd2e280dc71a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-24T14:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T14:30:36.000Z", "avg_line_length": 22.28, "max_line_length": 145, "alphanum_fraction": 0.6903052065, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8311430520409024, "lm_q1q2_score": 0.7671775916921036}}
{"text": "#############\n# Rotations #\n#############\n\nexport Rx\n\"\"\"\nRotation matrix, for a rotation about the x-axis.\n\nArguments:\n- `angle::Real`: Counter-clockwise angle of rotation as viewed looking back along the postive direction of the rotation axis.\n- `use_degrees:Bool`: If `true` interpret input as being in degrees.\n\nReturns:\n- `r::Array{<:Real, 2}`: Rotation matrix\n\nReferences:\n1. O. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and Applications_, 2012, p.27.\n\"\"\"\nfunction Rx(angle::Real ; use_degrees::Bool=false)\n    \n    if use_degrees\n        angle *= pi/180.0\n    end\n\n    c = cos(angle)\n    s = sin(angle)\n\n    return [ +1.0  0.0  0.0;\n              0.0 +c   +s;\n              0.0 -s   +c]\nend\n\nexport Ry\n\"\"\"\nRotation matrix, for a rotation about the y-axis.\n\nArguments:\n- `angle::Real`: Counter-clockwise angle of rotation as viewed looking back along the postive direction of the rotation axis.\n- `use_degrees:Bool`: If `true` interpret input as being in degrees.\n\nReturns:\n- `r::Array{<:Real, 2}`: Rotation matrix\n\nReferences:\n1. O. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and Applications_, 2012, p.27.\n\"\"\"\nfunction Ry(angle::Real ; use_degrees::Bool=false)\n    \n    if use_degrees\n        angle *= pi/180.0\n    end\n\n    c = cos(angle)\n    s = sin(angle)\n\n    return [ +c    0.0 -s;\n              0.0 +1.0  0.0;\n             +s    0.0 +c]\nend\n\nexport Rz\n\"\"\"\nRotation matrix, for a rotation about the z-axis.\n\nArguments:\n- `angle::Real`: Counter-clockwise angle of rotation as viewed looking back along the postive direction of the rotation axis.\n- `use_degrees:Bool`: If `true` interpret input as being in degrees.\n\nReturns:\n- `r::Array{<:Real, 2}`: Rotation matrix\n\nReferences:\n1. O. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and Applications_, 2012, p.27.\n\"\"\"\nfunction Rz(angle::Real ; use_degrees::Bool=false)\n    \n    if use_degrees\n        angle *= pi/180.0\n    end\n\n    c = cos(angle)\n    s = sin(angle)\n\n    return [ +c    +s   0.0;\n             -s    +c   0.0;\n              0.0  0.0 +1.0]\nend\n\n###################\n# Data Structures #\n###################\n\n\nexport Quaternion\n\"\"\"\nThe `Quaternion` type defines a _scalar-first_ quaternion for representation\nof attitude.\n\nData members:\n- `q0::Float64`: Scalar part of quaternion\n- `q1::Float64`: First vector component of quaternion\n- `q2::Float64`: Second vector component of quaternion\n- `q3::Float64`: Third vector component of quaternion\n\nReferences:\n1. J. Diebel, _Representing attitude: Euler angles, unit quaternions, and rotation vectors._ Matrix 58(15-16) (2006).\n\"\"\"\nmutable struct Quaternion\n    q0::Float64\n    q1::Float64\n    q2::Float64\n    q3::Float64\n\n    function Quaternion(q0::Real, q1::Real, q2::Real, q3::Real)\n        n = sqrt(q0^2 + q1^2 + q2^2 + q3^2)\n        \n        return new(q0/n, q1/n, q2/n, q3/n)\n    end\nend\n\nexport EulerAngle\n\"\"\"\nThe `EulerAngle` type provides a represenation of EulerAngles for storing attitude\ninformation.\n\nValid sequences are: `121, 123, 131, 132, 212, 213, 231, 232, 312, 313, 321, 323`.\n\nData members:\n- `seq::Integer`: Order of application of angles with respect to body axis.\n- `phi::Float64`: First Euler angle\n- `theta::Float64`: Second Euler angle\n- `psi::Float64`: Third Euler angle\n\nReferences:\n1. J. Diebel, _Representing attitude: Euler angles, unit quaternions, and rotation vectors._ Matrix 58(15-16) (2006).\n\"\"\"\nmutable struct EulerAngle\n    seq::Int\n    phi::Float64\n    theta::Float64\n    psi::Float64\n\n    function EulerAngle(seq::Integer, phi::Real, theta::Real, psi::Real)\n        if !(seq in [121, 123, 131, 132, 212, 213, 231, 232, 312, 313, 321, 323])\n            throw(ArgumentError(\"Invalid EulerAngle sequence: $seq\"))\n        end\n\n        return new(seq, phi, theta, psi)\n    end\nend\n\nexport EulerAxis\n\"\"\"\nThe `EulerAxis` type provides a representation of the Euler angle-and-axis attitude\nrepresentation.\n\nData members:\n- `theta::Float64`: Angle of rotation\n- `vec::Array{Float64, 1}`: Axis of rotation\n\nReferences:\n1. J. Diebel, _Representing attitude: Euler angles, unit quaternions, and rotation vectors._ Matrix 58(15-16) (2006).\n\"\"\"\nmutable struct EulerAxis\n    angle::Float64\n    axis::Array{Float64, 1}\n\n    function EulerAxis(angle::Real, axis::Array{<:Real, 1})\n        if length(axis) != 3\n            throw(ArgumentError(\"Invalid array for EulerAxis initialization. Input size: $(size(axis)), Required size: (3,)\"))\n        end\n\n        return new(angle, axis)\n    end\nend\n\n##############\n# Quaternion #\n##############\n\n# Quaternion Constructors \nfunction Quaternion(vec::Array{<:Real, 1})\n    if length(vec) != 4\n        throw(ArgumentError(\"Invalid array for Quaternion initialization. Input length: $(length(vec)), Required length: 4\"))\n    end\n\n    Quaternion(vec...)\nend\n\nfunction Quaternion(mat::Array{<:Real, 2})\n    if size(mat) == (1,4)\n        # Actually vector initialization. so it and return early\n        return Quaternion(mat...)\n    elseif size(mat) != (3,3)\n        throw(ArgumentError(\"Invalid array for Quaternion initialization. Input size: $(size(mat)), Required size: (3,3)\"))\n    end\n\n    temp = zeros(Float64, 4)\n    temp[1] = 1 + mat[1, 1] + mat[2, 2] + mat[3, 3]\n    temp[2] = 1 + mat[1, 1] - mat[2, 2] - mat[3, 3]\n    temp[3] = 1 - mat[1, 1] + mat[2, 2] - mat[3, 3]\n    temp[4] = 1 - mat[1, 1] - mat[2, 2] + mat[3, 3]\n\n    # Get the maximum value and its index\n    den, ind = findmax(temp)\n    den      = sqrt(den) # Short-cut equivalence to reuse test information\n\n    # Select optimal inverse mapping\n    q0, q1, q2, q3 = 0.0, 0.0, 0.0, 0.0\n    if ind == 1\n        q0 = 0.5 * den\n        q1 = 0.5 * (mat[2, 3] - mat[3, 2]) / den\n        q2 = 0.5 * (mat[3, 1] - mat[1, 3]) / den\n        q3 = 0.5 * (mat[1, 2] - mat[2, 1]) / den\n    elseif ind == 2\n        q0 = 0.5 * (mat[2, 3] - mat[3, 2]) / den\n        q1 = 0.5 * den\n        q2 = 0.5 * (mat[1, 2] + mat[2, 1]) / den\n        q3 = 0.5 * (mat[3, 1] + mat[1, 3]) / den\n    elseif ind == 3\n        q0 = 0.5 * (mat[3, 1] - mat[1, 3]) / den\n        q1 = 0.5 * (mat[1, 2] + mat[2, 1]) / den\n        q2 = 0.5 * den\n        q3 = 0.5 * (mat[2, 3] + mat[3, 2]) / den\n    elseif ind == 4\n        q0 = 0.5 * (mat[1, 2] - mat[2, 1]) / den\n        q1 = 0.5 * (mat[3, 1] + mat[1, 3]) / den\n        q2 = 0.5 * (mat[2, 3] + mat[3, 2]) / den\n        q3 = 0.5 * den\n    end\n\n    return Quaternion(q0, q1, q2, q3)\nend\n\nfunction Quaternion(e::EulerAngle)\n    # Extract Quaternion components\n    q0, q1, q2, q3 = 0.0, 0.0, 0.0, 0.0\n\n    # Compute sine and cosine values for angles\n\n    # Get Quaternion components depending on Euler Angle sequence\n    # reduce number of trig calls\n    c1 = cos(e.phi/2.0)\n    c2 = cos(e.theta/2.0)\n    c3 = cos(e.psi/2.0)\n    s1 = sin(e.phi/2.0)\n    s2 = sin(e.theta/2.0)\n    s3 = sin(e.psi/2.0)\n\n    # Populate the quaternion\n    if e.seq == 121\n        q0 = c1*c2*c3 - s1*c2*s3\n        q1 = c1*c2*s3 + c2*c3*s1\n        q2 = c1*c3*s2 + s1*s2*s3\n        q3 = c1*s2*s3 - s1*c3*s2\n\n    elseif e.seq == 123\n        q0 =  c1*c2*c3 + s1*s2*s3\n        q1 = -c1*s2*s3 + c2*c3*s1\n        q2 =  c1*c3*s2 + s1*c2*s3\n        q3 =  c1*c2*s3 - s1*c3*s2\n\n    elseif e.seq == 131\n        q0 =  c1*c2*c3 - s1*c2*s3\n        q1 =  c1*c2*s3 + c2*c3*s1\n        q2 = -c1*s2*s3 + s1*c3*s2\n        q3 =  c1*c3*s2 + s1*s2*s3\n\n    elseif e.seq == 132\n        q0 =  c1*c2*c3 - s1*s2*s3\n        q1 =  c1*s2*s3 + c2*c3*s1\n        q2 =  c1*c2*s3 + s1*c3*s2\n        q3 =  c1*c3*s2 - s1*c2*s3\n\n    elseif e.seq == 212\n        q0 =  c1*c2*c3 - s1*c2*s3\n        q1 =  c1*c3*s2 + s1*s2*s3\n        q2 =  c1*c2*s3 + c2*c3*s1\n        q3 = -c1*s2*s3 + s1*c3*s2\n\n    elseif e.seq == 213\n        q0 =  c1*c2*c3 - s1*s2*s3\n        q1 =  c1*c3*s2 - s1*c2*s3\n        q2 =  c1*s2*s3 + c2*c3*s1\n        q3 =  c1*c2*s3 + s1*c3*s2\n\n    elseif e.seq == 231\n        q0 =  c1*c2*c3 + s1*s2*s3\n        q1 =  c1*c2*s3 - s1*c3*s2\n        q2 = -c1*s2*s3 + c2*c3*s1\n        q3 =  c1*c3*s2 + s1*c2*s3\n\n    elseif e.seq == 232\n        q0 =  c1*c2*c3 - s1*c2*s3\n        q1 =  c1*s2*s3 - s1*c3*s2\n        q2 =  c1*c2*s3 + c2*c3*s1\n        q3 =  c1*c3*s2 + s1*s2*s3\n\n    elseif e.seq == 312\n        q0 =  c1*c2*c3 + s1*s2*s3\n        q1 =  c1*c3*s2 + s1*c2*s3\n        q2 =  c1*c2*s3 - s1*c3*s2\n        q3 = -c1*s2*s3 + c2*c3*s1\n\n    elseif e.seq == 313\n        q0 =  c1*c2*c3 - s1*c2*s3\n        q1 =  c1*c3*s2 + s1*s2*s3\n        q2 =  c1*s2*s3 - s1*c3*s2\n        q3 =  c1*c2*s3 + c2*c3*s1\n\n    elseif e.seq == 321\n        q0 =  c1*c2*c3 - s1*s2*s3\n        q1 =  c1*c2*s3 + s1*c3*s2\n        q2 =  c1*c3*s2 - s1*c2*s3\n        q3 =  c1*s2*s3 + c2*c3*s1\n\n    elseif e.seq == 323\n        q0 =  c1*c2*c3 - s1*c2*s3\n        q1 = -c1*s2*s3 + s1*c3*s2\n        q2 =  c1*c3*s2 + s1*s2*s3\n        q3 =  c1*c2*s3 + c2*c3*s1\n    else\n        # Should get an invalid sequence, but it is possible if a user\n        # Directly sets the sequence number\n        throw(ArgumentError(\"Invalid EulerAngle sequence: $e.seq\"))\n    end\n\n    return Quaternion(q0, q1, q2, q3)\nend\n\nfunction Quaternion(e::EulerAxis)\n    # Extract Quaternion components\n    q0 = cos(e.angle/2.0)\n    q1 = e.axis[1]*sin(e.angle/2.0)\n    q2 = e.axis[2]*sin(e.angle/2.0)\n    q3 = e.axis[3]*sin(e.angle/2.0)\n\n    return Quaternion(q0, q1, q2, q3)\nend\n\n#########################\n# Quaternion Operations #\n#########################\n\nfunction Base.getindex(q::Quaternion, I::UnitRange{<:Integer})\n    # Allocate vector once\n    vec = as_vector(q)\n\n    # Return selected index or range\n    return [vec[i] for i in I]\nend\n\nfunction Base.getindex(q::Quaternion, I::Integer)\n    if I == 1\n        return q.q0\n    elseif I == 2\n        return q.q1\n    elseif I == 3\n        return q.q2\n    elseif I == 4\n        return q.q3\n    else\n        throw(BoundsError())\n    end\nend\n\nBase.getindex(q::Quaternion, ::Colon) = [q.q0, q.q1, q.q2, q.q3]\n\n# Return quaternion as a vector\nexport as_vector\n\"\"\"\nReturn quaternion as a vector. \n\nEquivalent to q[:]\n\nArguments:\n- `q::Quaternion`: Quaternion\n\nReturns:\n- `vec::Array{Float64, 1}`: Quaternion as a (4,) vector\n\"\"\"\nfunction as_vector(q::Quaternion)\n    return q[:]\nend\n\n# Return quaternion as a matrix\nexport as_matrix\n\"\"\"\nReturn the rotation matrix representation of a Quaternion.\n\nArguments:\n- `q::Quaternion`: Quaternion\n\nReturns:\n- `mat::Array{Float64, 2}`: Rotation Matrix on SO(3).\n\"\"\"\nfunction as_matrix(q::Quaternion)\n    # initialize Empty Matrix\n    mat = zeros(Float64, 3, 3)\n\n    # Construct matrix from Quaternion\n    mat[1, 1] = q.q0*q.q0 + q.q1*q.q1 - q.q2*q.q2 - q.q3*q.q3\n    mat[1, 2] = 2*q.q1*q.q2 + 2*q.q0*q.q3\n    mat[1, 3] = 2*q.q1*q.q3 - 2*q.q0*q.q2\n    mat[2, 1] = 2*q.q1*q.q2 - 2*q.q0*q.q3\n    mat[2, 2] = q.q0*q.q0 - q.q1*q.q1 + q.q2*q.q2 - q.q3*q.q3\n    mat[2, 3] = 2*q.q2*q.q3 + 2*q.q0*q.q1\n    mat[3, 1] = 2*q.q1*q.q3 + 2*q.q0*q.q2\n    mat[3, 2] = 2*q.q2*q.q3 - 2*q.q0*q.q1\n    mat[3, 3] = q.q0*q.q0 - q.q1*q.q1 - q.q2*q.q2 + q.q3*q.q3\n\n    return mat\nend\n\nfunction Base.copy(q::Quaternion)\n    return Quaternion(q.q0, q.q1, q.q2, q.q3)\nend\n\nfunction Base.deepcopy(q::Quaternion)\n    return Quaternion(q.q0, q.q1, q.q2, q.q3)\nend\n\n\"\"\"\nCompute the norm of a Quaternion.\n\nEquivalent to `sqrt(q0^2 + q1^2 + q2^2 + q3^2)`\n\nArguments:\n- `q::Quaternion`: Quaternion\n\nReturns:\n- `q_norm::Float64`: Norm of quaternion.\n\"\"\"\nfunction LinearAlgebra.norm(q::Quaternion)\n    return sqrt(q.q0^2 + q.q1^2 + q.q2^2 + q.q3^2)\nend\n\n\"\"\"\nNormalize a Quaternion in-place.\n\nEquivalent to q=q/norm(q)\n\nArguments:\n- `q::Quaternion`: Quaternion\n\nReturns:\n- `q_norm::Float64`: Norm of quaternion.\n\"\"\"\nfunction LinearAlgebra.normalize(q::Quaternion)\n    # Get Quaternion norm\n    q_norm = norm(q)\n\n    # Normalize q in-place\n    q.q0 = q.q0/q_norm\n    q.q1 = q.q1/q_norm\n    q.q2 = q.q2/q_norm\n    q.q3 = q.q3/q_norm\n\n    # Ensure return value is nothing\n    nothing\nend\n\n\"\"\"\nGet conjugate Quaternion.\n\nArguments:\n- `q::Quaternion`: Input Quaternion\n\nReturns:\n- `q_conj::Quaternion`: Conjugate Quaternion of input\n\"\"\"\nfunction Base.conj(q::Quaternion)\n    return Quaternion(q.q0, -q.q1, -q.q2, -q.q3)\nend\n\n\"\"\"\nGet Quaternion inverse.\n\nArguments:\n- `q::Quaternion`: Input Quaternion\n\nReturns:\n- `q_inv::Quaternion`: Inverse Quaternion of input\n\"\"\"\nfunction Base.inv(q::Quaternion)\n    # Same as Quaternion conjugate since all quaternions are normalized to have\n    # unit norm on construction\n    return conj(q)\nend\n\nfunction Base.:-(q::Quaternion)\n    return Quaternion(-q.q0, -q.q1, -q.q2, -q.q3)\nend\n\nfunction Base.:-(qa::Quaternion, qb::Quaternion)\n    return [qa.q0 - qb.q0\n            qa.q1 - qb.q1\n            qa.q2 - qb.q2\n            qa.q3 - qb.q3]\nend\n\nfunction Base.:+(qa::Quaternion, qb::Quaternion)\n    return [qa.q0 + qb.q0\n            qa.q1 + qb.q1\n            qa.q2 + qb.q2\n            qa.q3 + qb.q3]\nend\n\nfunction Base.:+(q::Quaternion, n::Real)\n    return [q.q0 + n\n            q.q1 + n\n            q.q2 + n\n            q.q3 + n]\nend\n\nfunction Base.:+(n::Real, q::Quaternion)\n    return q+n\nend\n\nfunction Base.:*(qa::Quaternion, qb::Quaternion)\n    # # Quaternion Multiplication\n    # qcos = self.data[0]*other.data[0] - np.dot(self.data[1:4], other.data[1:4])\n    # qvec = self.data[0]*other.data[1:4] + other.data[0]*self.data[1:4] + np.cross(self.data[1:4], other.data[1:4])\n\n    # Quaternion Multiplication\n    qcos = qa.q0*qb.q0 - dot(qa[2:4], qb[2:4])\n    qvec = qa.q0*qb[2:4] + qb.q0*qa[2:4] + cross(qa[2:4], qb[2:4])\n\n    return Quaternion(qcos, qvec...)\nend\n\nfunction Base.:*(q::Quaternion, n::Real)\n    return q[:]*n\nend\n\nfunction Base.:*(n::Real, q::Quaternion)\n    return q*n\nend\n\nexport slerp\n\"\"\"\nPerform spherical linear interpolation (SLERP) on two quaternions. Interpolatles \nfrom quaternion, `q1`, to quaternion, `q2`, at normalized interpolation time, `t`.\n\nInterpolation time must be in the range `[0, 1]` a value of `0` will return `q1`,\nwhile a value of `1` will return `q2`.\n\nArguments:\n- `q1::Quaternion`: Starting Quaternion\n- `q2::Quaternion`: Ending Quaternion\n- `t::Real`: Normalized interpolation time. [0, 1]\n\nReturns:\n- `q:Quaternion`: Quaternion attitude interpolation from q1 toward q2 at time t.\n\"\"\"\nfunction slerp(q0::Quaternion, q1::Quaternion, t::Real)\n    # Check Range on t\n    if t < 0.0 || t > 1.0\n        throw(ArgumentError(\"Invalid interpolation time $t. t must be in the range [0, 1].\"))\n    end\n\n    # Extract vectors and normalize\n    q0 = copy(q0)[:]\n    q1 = copy(q1)[:]\n\n    # Compute cosine of the angle between the two vectors\n    dp = dot(q0, q1)\n\n    # If the dot product is negative, the quaternions have opposite handed-ness \n    # and slerp won't take the shortest path. Fix by reversing one quaternion.\n    if dp < 0.0\n        q1  = -q1\n        dp = -dp\n    end\n\n    # If the inputs are too close we use linear interpolation instead\n    if dp > 0.9995\n        return Quaternion(q0 + (q1 - q0)*t)\n    end\n\n    theta0 = acos(dp) # Angle between input vectors\n    theta  = theta0*t  # Angle between q0 and result quaternion\n\n    s0 = cos(theta) - dp*sin(theta)/sin(theta0)\n    s1 = sin(theta) / sin(theta0)\n\n    return Quaternion((s0 * q0) + (s1 * q1))\nend\n\n##############\n# EulerAngle #\n##############\n\nfunction EulerAngle(seq::Integer, vec::Array{<:Real, 1})\n    if length(vec) != 3\n        throw(ArgumentError(\"Invalid array for EulerAngle initialization. Input length: $(length(vec)), Required length: 3\"))\n    end\n\n    EulerAngle(seq, vec...)\nend\n\nfunction EulerAngle(seq::Integer, mat::Array{<:Real, 2})\n    if size(mat) != (3,3)\n        throw(ArgumentError(\"Invalid array for Quaternion initialization. Input size: $(size(mat)), Required size: (3,3)\"))\n    end\n\n    # Extract elements out of rotation matrix\n    r11 = mat[1, 1]\n    r12 = mat[1, 2]\n    r13 = mat[1, 3]\n    r21 = mat[2, 1]\n    r22 = mat[2, 2]\n    r23 = mat[2, 3]\n    r31 = mat[3, 1]\n    r32 = mat[3, 2]\n    r33 = mat[3, 3]\n\n    # Select euler angle sequence\n    phi, theta, psi = 0.0, 0.0, 0.0\n    if seq == 121\n        phi   = atan(r21, r31)\n        theta = acos(r11)\n        psi   = atan(r12, -r13)\n    elseif seq == 123\n        phi   = atan(r23, r33)\n        theta = -asin(r13)\n        psi   = atan(r12, r11)\n    elseif seq == 131\n        phi   = atan(r31, -r21)\n        theta = acos(r11)\n        psi   = atan(r13, r12)\n    elseif seq == 132\n        phi   = atan(-r32, r22)\n        theta = asin(r12)\n        psi   = atan(-r13, r11)\n    elseif seq == 212\n        phi   = atan(r12, -r32)\n        theta = acos(r22)\n        psi   = atan(r21, r23)\n    elseif seq == 213\n        phi   = atan(-r13, r33)\n        theta = asin(r23)\n        psi   = atan(-r21, r22)\n    elseif seq == 231\n        phi   = atan(r31, r11)\n        theta = -asin(r21)\n        psi   = atan(r23, r22)\n    elseif seq == 232\n        phi   = atan(r32, r12)\n        theta = acos(r22)\n        psi   = atan(r23, -r21)\n    elseif seq == 312\n        phi   = atan(r12, r22)\n        theta = -asin(r32)\n        psi   = atan(r31, r33)\n    elseif seq == 313\n        phi   = atan(r13, r23)\n        theta = acos(r33)\n        psi   = atan(r31, -r32)\n    elseif seq == 321\n        phi   = atan(-r21, r11)\n        theta = asin(r31)\n        psi   = atan(-r32, r33)\n    elseif seq == 323\n        phi   = atan(r23, -r13)\n        theta = acos(r33)\n        psi   = atan(r32, r31)\n    else\n        throw(ArgumentError(\"Invalid EulerAngle sequence: $seq\"))\n    end\n\n    return EulerAngle(seq, phi, theta, psi)\nend\n\nfunction EulerAngle(seq::Integer, q::Quaternion)\n    # Construct angle from Quaternion by going through a rotation matrix\n    return EulerAngle(seq::Integer, as_matrix(q))\nend\n\nfunction EulerAngle(seq::Integer, ea::EulerAxis)\n    # Construct angle from EulerAxis by going through a rotation matrix\n    return EulerAngle(seq::Integer, as_matrix(ea))\nend\n\n# Access Operators\nfunction Base.getindex(e::EulerAngle, I::UnitRange{<:Integer})\n    # Allocate vector once\n    vec = as_vector(e)\n\n    # Return selected index or range\n    return [vec[i] for i in I]\nend\n\nfunction Base.getindex(e::EulerAngle, I::Integer)\n    if I == 1\n        return e.phi\n    elseif I == 2\n        return e.theta\n    elseif I == 3\n        return e.psi\n    else\n        throw(BoundsError())\n    end\nend\n\nBase.getindex(e::EulerAngle, ::Colon) = [e.phi, e.theta, e.psi]\n\n\"\"\"\nReturn Euler angles as a vector.\n\nEquivalent to: `[e.phi, e.theta, e.psi]` for `EulerAngle` `e`\n\nArguments:\n- `e::EulerAngle` Euler Angle\n\nReturns:\n- `evec::Array{Float64, 1}` Euler angles components in vector form.\n\"\"\"\nfunction as_vector(e::EulerAngle)\n    return [e.phi, e.theta, e.psi]\nend\n\nfunction as_matrix(e::EulerAngle)\n    # Get EulerAngle as matrix by going through Quaternions\n    return as_matrix(Quaternion(e))\nend\n\nfunction Base.copy(e::EulerAngle)\n    return EulerAngle(e.seq, e.phi, e.theta, e.psi)\nend\n\nfunction Base.deepcopy(e::EulerAngle)\n    return EulerAngle(e.seq, e.phi, e.theta, e.psi)\nend\n\n#############\n# EulerAxis #\n#############\n\nfunction EulerAxis(angle::Real, v1::Real, v2::Real, v3::Real)\n    return EulerAxis(angle, [v1, v2, v3])\nend\n\nfunction EulerAxis(vec::Array{<:Real, 1})\n    if length(vec) != 4\n        throw(ArgumentError(\"Invalid array for EulerAxis initialization. Input size: $(size(vec)), Required size: (4,)\"))\n    end\n\n    return EulerAxis(vec[1], [vec[2], vec[3], vec[4]])\nend\n\nfunction EulerAxis(mat::Array{<:Real, 2})\n    if size(mat) != (3,3)\n        throw(ArgumentError(\"Invalid array for EulerAxis initialization. Input size: $(size(mat)), Required size: (3,3)\"))\n    end\n\n    return EulerAxis(Quaternion(mat))\nend\n\nfunction EulerAxis(q::Quaternion)\n    # Extract quaternion vector and normalize\n    qv = as_vector(q)\n    q  = qv/norm(qv)\n            \n    # Ensure first element is positive\n    if q[1] < 0\n        q = -q\n    end\n    \n    # Compute Euler Angle\n    angle     = 2*acos(q[1])\n    qvec_norm = norm(q[2:4])\n    vec       = [0.0, 0.0, 0.0]\n\n    if qvec_norm > 1e-15\n        vec = q[2:4]/qvec_norm\n    end\n\n    return EulerAxis(angle, vec)\nend\n\nfunction EulerAxis(e::EulerAngle)\n    # If input is an EulerAngle first compute a quaternion then get the\n    # EulerAxis form\n    EulerAxis(Quaternion(e))\nend\n\n# Access operators\n\nfunction Base.getindex(e::EulerAxis, I::UnitRange{<:Integer})\n    # Allocate vector once\n    vec = as_vector(e)\n\n    # Return selected index or range\n    return [vec[i] for i in I]\nend\n\nfunction Base.getindex(e::EulerAxis, I::Integer)\n    if I == 1\n        return e.angle\n    elseif I == 2\n        return e.axis[1]\n    elseif I == 3\n        return e.axis[2]\n    elseif I == 4\n        return e.axis[3]\n    else\n        throw(BoundsError())\n    end\nend\n\nBase.getindex(e::EulerAxis, ::Colon) = [e.angle, e.axis[1], e.axis[2], e.axis[3]]\n\nfunction as_vector(e::EulerAxis)\n    return e[:]\nend\n\nfunction as_matrix(e::EulerAxis)\n    # Get matrix form from Quaternion for ease\n    return as_matrix(Quaternion(e))\nend\n\nfunction Base.copy(e::EulerAxis)\n    return EulerAxis(e.angle, e.axis)\nend\n\nfunction Base.deepcopy(e::EulerAxis)\n    return EulerAxis(e.angle, e.axis)\nend\n\n####################\n# Type Conversions #\n####################", "meta": {"hexsha": "7c9e39f6502f4cc31bb1bcbde0f698816ce15731", "size": 20993, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/attitude.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SatelliteDynamics.jl-0e7c1a32-1b9f-5532-88a4-e668712d6a4c", "max_stars_repo_head_hexsha": "8afaaf79609b6710fd433bb6d423f1b5af98a386", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-01-02T17:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:40:54.000Z", "max_issues_repo_path": "src/attitude.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SatelliteDynamics.jl-0e7c1a32-1b9f-5532-88a4-e668712d6a4c", "max_issues_repo_head_hexsha": "8afaaf79609b6710fd433bb6d423f1b5af98a386", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-01-14T10:38:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-10T16:07:56.000Z", "max_forks_repo_path": "src/attitude.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SatelliteDynamics.jl-0e7c1a32-1b9f-5532-88a4-e668712d6a4c", "max_forks_repo_head_hexsha": "8afaaf79609b6710fd433bb6d423f1b5af98a386", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-02-08T08:12:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-29T20:48:52.000Z", "avg_line_length": 25.2016806723, "max_line_length": 126, "alphanum_fraction": 0.5898156528, "num_tokens": 7120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.7671775867547563}}
{"text": "\"\"\"\n    sample_entropy(x, m, r, δ)\n\nCompute the Sample Entropy[^1] of `x`.\n\nCompute Sample Entropy with template size `m` and tolerance factor `r`.\nIf timestep `δ` is provided, downsample signal `x` with timestep `δ`.\n\n# Examples\n```julia\njulia> sample_entropy([1, 2, 3, 1, 2, 3], m=2, r=0.2, δ=1)\n0.6931471805599453\n```\n\"\"\"\nfunction sample_entropy(x::AbstractArray, m=2, r=0.2, δ=1)\n    #=\n    x -> normalized signal (1d vector)\n    m -> embedding dimension (must be > length of signal)\n    r -> tolerance factor\n    δ -> delay =#\n    N = length(x)\n    σ = std(x)\n    tolerance = σ * r\n\n    # Create template vectors (of length m + 1)\n    matches = zeros(m + 1, N)\n    for i in 1:m\n        matches[i, 1:(N + 1 - i)] = x[i:end]\n    end\n\n    matches[m + 1, 1:(N + 1 - m - δ)] = x[m + δ:end]\n    matches = matches[:, 1:N + 1 - m - δ]\n\n    # Calculate pairwise distances for templates of length m\n    dist_m = zeros(N - m, N - m)\n    pairwise!(dist_m, Chebyshev(), matches[1:m,:], dims=2)\n    # Extract upper triangle of distance matrix\n    dist_m = dist_m[tril!(trues(size(dist_m)), -1)]\n    # Count pairs of template that are within tolerance\n    B = count(x -> x <= tolerance, dist_m)\n\n    if B == 0\n        return Inf, 0, 0\n    end\n\n    # Repeat for templates m+1\n    dist_m1 = zeros(N - m, N - m)\n    pairwise!(dist_m1, Chebyshev(), matches[1:m + 1,:], dims=2)\n    dist_m1 = dist_m1[tril!(trues(size(dist_m1)), -1)]\n    A = count(x -> x <= tolerance, dist_m1)\n\n    -log(A / B), A, B\n\nend\n\nfunction multiscale_entropy(x::AbstractArray, τ=1, m=2, r=0.2, δ=1)\n\n    if τ == 1\n        sample_entropy(x, m, r, δ)\n    end\n\n    N = length(x)\n    x = x[1:end - (N % τ)]\n    N = length(x)\n    # TODO ordre de dims à vérifier\n    dims = (τ, Int(N / τ))\n    x = reshape(x, dims)\n    x_mse = mean(x, dims=1)\n\n    sample_entropy(x_mse, m, r, δ)\n\nend\n", "meta": {"hexsha": "38a429f5dc13e4785b95db257095d5880891c3d4", "size": 1838, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/entropy/sample_entropy.jl", "max_stars_repo_name": "emilelemoine/epilepsy.jl", "max_stars_repo_head_hexsha": "c525370a60fa73269dec5265efa5c277eb8c05a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/entropy/sample_entropy.jl", "max_issues_repo_name": "emilelemoine/epilepsy.jl", "max_issues_repo_head_hexsha": "c525370a60fa73269dec5265efa5c277eb8c05a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/entropy/sample_entropy.jl", "max_forks_repo_name": "emilelemoine/epilepsy.jl", "max_forks_repo_head_hexsha": "c525370a60fa73269dec5265efa5c277eb8c05a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1780821918, "max_line_length": 71, "alphanum_fraction": 0.5761697497, "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526934, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7671775828940661}}
{"text": "using SparseArrays\r\n\r\nfunction poisson_linear_system(ndofs)\r\n        operator = spdiagm(\r\n                -1 => 1.0 * ones(ndofs - 1),\r\n                0 => -2.0 * ones(ndofs),\r\n                1 => 1.0 * ones(ndofs - 1),\r\n        )\r\n        operator[1,1] = 1.0\r\n        operator[1,2] = 0.0\r\n        operator[ndofs,ndofs-1] = 0.0\r\n        operator[ndofs,ndofs] = 1.0\r\n        return operator\r\nend\r\n\r\nfunction solve_direct(operator, rhs, bcleft, bcright, stepsize)\r\n    numpts = length(rhs)\r\n    copyrhs = copy(rhs)\r\n    copyrhs[1] = bcleft / stepsize^2\r\n    copyrhs[numpts] = bcright / stepsize^2\r\n    sol = stepsize^2 * (operator \\ copyrhs)\r\n    return sol\r\nend\r\n\r\nfunction solve_direct_all_rhs(operator, bcleft, bcright, stepsize)\r\n    ndofs, ndofs = size(operator)\r\n    rhs = diagm(ones(ndofs))[:, 2:ndofs-1]\r\n    rhs[1, :] .= bcleft / stepsize^2\r\n    rhs[ndofs, :] .= bcright / stepsize^2\r\n    sol = stepsize^2 * (operator \\ rhs)\r\n    return sol\r\nend\r\n", "meta": {"hexsha": "91008852742731cd1419f923a1143deacb86ecde", "size": 956, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "poisson_linear_system.jl", "max_stars_repo_name": "ArjunNarayanan/ExploreJacobi", "max_stars_repo_head_hexsha": "cbeeba2a165ecc61ea294c8974929a28edea6481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "poisson_linear_system.jl", "max_issues_repo_name": "ArjunNarayanan/ExploreJacobi", "max_issues_repo_head_hexsha": "cbeeba2a165ecc61ea294c8974929a28edea6481", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "poisson_linear_system.jl", "max_forks_repo_name": "ArjunNarayanan/ExploreJacobi", "max_forks_repo_head_hexsha": "cbeeba2a165ecc61ea294c8974929a28edea6481", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9696969697, "max_line_length": 67, "alphanum_fraction": 0.5638075314, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558356, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7671775753434233}}
{"text": "\"\"\"\n## beam_gm\n\nThis subroutine forms the beam geometric matrix for stability analysis.\n\n### Method\n```julia\nbeam_gm(ell::Float64)\n```\n\n### Arguments\n```julia\n* ell::Float64                   : Element length\n```\n\n### Return value\n```julia\n* gm::::Matrix{Float64}(4,4)     : Geometric matrix for beam element\n```\n\"\"\"\nfunction beam_gm(ell::Float64)\n  #\n  # This subroutine forms the beam geometric matrix for stability analysis.\n  #\n  # Updated gm\n  #\n  gm = zeros(4, 4)\n  gm[1,1] = 1.2/ell\n  gm[1,2] = 0.1\n  gm[2,1] = 0.1\n  gm[1,3] = -1.2/ell\n  gm[3,1] = -1.2/ell\n  gm[1,4] = 0.1\n  gm[4,1] = 0.1\n  gm[2,2] = 2.0*ell/15.0\n  gm[2,3] = -0.1\n  gm[3,2] = -0.1\n  gm[2,4] = -ell/30.0\n  gm[4,2] = -ell/30.0\n  gm[3,3] = 1.2/ell\n  gm[3,4] = -0.1\n  gm[4,3] = -0.1\n  gm[4,4] = 2.0*ell/15.0\n  gm\nend", "meta": {"hexsha": "78f372abde9369298ffcf89e25179ca746922f8a", "size": 786, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PtFEM/Main/beam_gm.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PtFEM.jl-9b64898b-da2a-5774-a656-fd6fb605642c", "max_stars_repo_head_hexsha": "35a9d7c796a92f5d44bd37a2af574fb366fa51ba", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2017-04-16T11:52:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T06:41:59.000Z", "max_issues_repo_path": "src/PtFEM/Main/beam_gm.jl", "max_issues_repo_name": "UnofficialJuliaMirror/PtFEM.jl-9b64898b-da2a-5774-a656-fd6fb605642c", "max_issues_repo_head_hexsha": "35a9d7c796a92f5d44bd37a2af574fb366fa51ba", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2018-07-04T00:14:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:16.000Z", "max_forks_repo_path": "src/PtFEM/Main/beam_gm.jl", "max_forks_repo_name": "UnofficialJuliaMirror/PtFEM.jl-9b64898b-da2a-5774-a656-fd6fb605642c", "max_forks_repo_head_hexsha": "35a9d7c796a92f5d44bd37a2af574fb366fa51ba", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2017-05-28T21:43:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T12:43:12.000Z", "avg_line_length": 17.4666666667, "max_line_length": 75, "alphanum_fraction": 0.5496183206, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7671274137640737}}
{"text": "using splines\n\n\nprintln(\"1D interpolation\")\norders = [100]\nsmin = [0.0]\nsmax = [1.0]\nN_tries = 10\n\nf(x) = sin(x*10)\n# 1d test\na = linspace(0,1,orders[1])\nb = f(a)\nb\ndi = 1\nM = length(a)\n\ncoefs = filter_coeffs(smin,smax,orders,b)\n\n#s = linspace(-0.1,1.1,100000)\ns = linspace(0.01,0.99,100000)\n\ns = copy(s'')\n\ninterp_values = eval_UC_spline(smin,smax,orders,coefs,s)\nval, grad = eval_UC_spline_G(smin,smax,orders,coefs,s)\n\n\n\ninterp_values = eval_UC_spline(smin,smax,orders,coefs,s)\nval, grad = eval_UC_spline_G(smin,smax,orders,coefs,s)\n\n\nfun = interpolant_cspline(smin,smax,orders,b)\nvals = fun(s)\n\nprintln(\"Error: \", maximum(maximum(abs(interp_values - vals )  )))\n\n\ntic()\nfor i = 1:N_tries\n    interp_values = eval_UC_spline(smin,smax,orders,coefs,s)\nend\n\ntrue_values = f(s)\n\nprintln(\"Maximum interpolation error : \", norm(true_values-interp_values,Inf))\ntoc()\n\n\n# Test multi splines:\n\nCC = zeros(2,size(coefs,1))\nCC[1,:] = coefs   # first spline\nCC[2,:] = coefs/2   # second spline\ninterp_multi_values = eval_UC_multi_spline(smin,smax,orders,CC,s)\n\n#using PyPlot\n#plot(s,sol)\n#plot(s,true_values)\n#plot(a,b,\"o\")\n#side effect of pyplot: 0.0 not recognized as a constant\n\n# 2d test\nprintln(\"2D interpolation\")\nsmin = [0.0,0.0]\nsmax = [1.0,1.0]\norders = [10,20]\na1 = linspace(0,1,orders[1])\na2 = linspace(0,1,orders[2])\nb = [sin(i+j) for i=a1, j=a2]\nb = convert(Array{Float64},b)\n#b = reshape(b, orders[1], orders[2])\n#di = [1.0,1.0]\ncoefs = filter_coeffs(smin,smax,orders,b)\n\nforders = [1000,1000]\nN = prod(forders)\nmgrid = [ [x y] for x=linspace(0,1,forders[1]), y=linspace(0,1,forders[2])]\n\nvgrid = vcat(mgrid...)\ninterp_vals = eval_UC_spline(smin,smax,orders,coefs,vgrid)\n\n\ntic()\nfor i = 1:10\ninterp_vals = eval_UC_spline(smin,smax,orders,coefs,vgrid)\nend\ntoc()\ntrue_vals = [sin(x+y) for x=linspace(0,1,forders[1]), y=linspace(0,1,forders[2])]\ntrue_vals = convert(Array{Float64},true_vals[:])\n\nprintln(\"Maximum interpolation error : \", norm(true_vals-interp_vals,Inf))\n\n\n# 3d test\nprintln(\"3D interpolation\")\n\na = [0.0, 0.0, 0.0]\nb = [1.0, 1.0, 1.0]\norders = [20,20,20]\n\na1 = linspace(0,1,orders[1])\na2 = linspace(0,1,orders[2])\na3 = linspace(0,1,orders[3])\n\nmat = [(i+j+k)^2 for i=a1, j=a2, k=a3]\nmat = convert(Array{Float64},mat)\n\n\ncoefs = filter_coeffs(a,b,orders,mat)\n\nforders = [100,100,100]\nN = prod(forders)\n\nmgrid = [ [x y z] for x=linspace(0,1,forders[1]), y=linspace(0,1,forders[2]), z=linspace(0,1,forders[3])]\n\nvgrid = vcat(mgrid...)\ninterp_vals = eval_UC_spline(a,b,orders,coefs,vgrid)\n\n\ntic()\nfor i = 1:10\ninterp_vals = eval_UC_spline(a,b,orders,coefs,vgrid)\nend\ntoc()\ntrue_vals = [(x+y+z)^2 for x=linspace(0,1,forders[1]), y=linspace(0,1,forders[2]),  z=linspace(0,1,forders[3])]\ntrue_vals = convert(Array{Float64},true_vals[:])\n\nprintln(\"Maximum interpolation error : \", norm(true_vals-interp_vals,Inf))\n", "meta": {"hexsha": "e5843abedfc44beb994e7396334bab6aa1ea146d", "size": 2823, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test.jl", "max_stars_repo_name": "JuliaTagBot/splines.jl", "max_stars_repo_head_hexsha": "71b371e396adbcf4998397916eb52342d5397112", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test.jl", "max_issues_repo_name": "JuliaTagBot/splines.jl", "max_issues_repo_head_hexsha": "71b371e396adbcf4998397916eb52342d5397112", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-07-21T06:14:04.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-21T06:14:04.000Z", "max_forks_repo_path": "test/test.jl", "max_forks_repo_name": "JuliaTagBot/splines.jl", "max_forks_repo_head_hexsha": "71b371e396adbcf4998397916eb52342d5397112", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:02:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:02:21.000Z", "avg_line_length": 21.5496183206, "max_line_length": 111, "alphanum_fraction": 0.6836698548, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7671274117574823}}
{"text": "\nusing Jecco\nusing LinearAlgebra\nusing SparseArrays\nusing Plots\n\n#= solving equation\n\n f_xx + f_yy + x y f_xy + x f_x + y f_y + (x^2 + y^2) f\n  + (f_x)^2 + (f_y)^2 + x y f_x f_y = Source(x,y)\n\nfor the source below, the solution should be given by\n\n f = exp(-x^2 - y^2)\n=#\n\nsource(x,y) = exp(-x^2 - y^2) * (-4 + 3 * (x^2 + y^2) + 4 * x^2 * y^2) +\n    4 * exp(-2*x^2 - 2*y^2) * (x^2 + y^2 + x^2 * y^2)\n\nfunction compute_residual!(res::Array, f::Array, x::Vector, y::Vector,\n                           Dxx_op::Jecco.FiniteDiffDeriv, Dyy_op::Jecco.FiniteDiffDeriv,\n                           Dx_op::Jecco.FiniteDiffDeriv, Dy_op::Jecco.FiniteDiffDeriv)\n    Nx = length(x)\n    Ny = length(y)\n\n    f_xx = Dxx_op * f\n    f_yy = Dyy_op * f\n    f_x  = Dx_op  * f\n    f_y  = Dy_op  * f\n    f_xy = Dx_op  * f_y\n\n    for j in 1:Ny, i in 1:Nx\n        x1 = x[i]\n        y1 = y[j]\n\n        res[i,j] = f_xx[i,j] + f_yy[i,j] + x1 * y1 * f_xy[i,j] +\n            x1 * f_x[i,j] + y1 * f_y[i,j] +\n            (x1*x1 + y1*y1) * f[i,j] + f_x[i,j]^2 + f_y[i,j]^2 +\n            x1 * y1 * f_x[i,j] * f_y[i,j] - source(x1,y1)\n    end\n\n    res\nend\n\n\nfunction deriv_operators(hx, hy, Nx::Int, Ny::Int, ord::Int)\n    Dx_op  = CenteredDiff{1}(1, ord, hx, Nx)\n    Dxx_op = CenteredDiff{1}(2, ord, hx, Nx)\n\n    Dy_op  = CenteredDiff{2}(1, ord, hy, Ny)\n    Dyy_op = CenteredDiff{2}(2, ord, hy, Ny)\n\n    Dxx_op, Dyy_op, Dx_op, Dy_op\nend\n\n#=\nuse the Kronecker product (kron) to build the 2-dimensional derivation matrices\nfrom the 1-dimensional ones. see for instance:\n\n  https://en.wikipedia.org/wiki/Kronecker_product\n\n  https://arxiv.org/pdf/1801.01483.pdf (section 5)\n=#\nfunction deriv_matrices(Dxx_op::Jecco.FiniteDiffDeriv, Dyy_op::Jecco.FiniteDiffDeriv,\n                        Dx_op::Jecco.FiniteDiffDeriv, Dy_op::Jecco.FiniteDiffDeriv)\n    Dx  = kron(I(Ny), SparseMatrixCSC(Dx_op))\n    Dxx = kron(I(Ny), SparseMatrixCSC(Dxx_op))\n    Dy  = kron(SparseMatrixCSC(Dy_op), I(Nx))\n    Dyy = kron(SparseMatrixCSC(Dyy_op), I(Nx))\n\n    Dxx, Dyy, Dx * Dy, Dx, Dy\nend\n\n\n# returns axx Dxx + ayy Dyy + axy Dxy + bx Dx + by Dy + cc. note that this\n# function overwrites the input matrices to save memory\nfunction build_jacobian(Dxx::SparseMatrixCSC, Dyy::SparseMatrixCSC, Dxy::SparseMatrixCSC,\n                        Dx::SparseMatrixCSC, Dy::SparseMatrixCSC,\n                        axx::Diagonal, ayy::Diagonal, axy::Diagonal,\n                        bx::Diagonal, by::Diagonal, cc::Diagonal)\n    Dxx_ = similar(Dxx)\n    Dyy_ = similar(Dyy)\n    Dxy_ = similar(Dxy)\n    Dx_  = similar(Dx)\n    Dy_  = similar(Dy)\n\n    mul!(Dxx_, axx, Dxx)\n    mul!(Dyy_, ayy, Dyy)\n    mul!(Dxy_, axy, Dxy)\n    mul!(Dx_, bx, Dx)\n    mul!(Dy_, by, Dy)\n\n    Dxx_ + Dyy_ + Dxy_ + Dx_ + Dy_ + cc\nend\n\n\n\nx_min    = -5.0\nx_max    =  5.0\nx_nodes  =  128\n# x_nodes  =  256\ny_min    = -5.0\ny_max    =  5.0\ny_nodes  =  64\n# y_nodes  =  256\n\nord = 4\n# ord = 2\n\nxcoord  = Cartesian{1}(\"x\", x_min, x_max, x_nodes, endpoint=false)\nycoord  = Cartesian{2}(\"y\", y_min, y_max, y_nodes, endpoint=false)\n\nhx = Jecco.delta(xcoord)\nhy = Jecco.delta(ycoord)\n\nNx = xcoord.nodes\nNy = ycoord.nodes\n\nf_exact = [exp(-xcoord[i]^2 - ycoord[j]^2) for i in 1:Nx, j in 1:Ny]\n\n\nDxx_op, Dyy_op, Dx_op, Dy_op = deriv_operators(hx, hy, Nx, Ny, ord)\nDxx, Dyy, Dxy, Dx, Dy = deriv_matrices(Dxx_op, Dyy_op, Dx_op, Dy_op)\n\n# initial guess\n# fsol   = zeros(Nx,Ny)\nfsol   = copy(f_exact)\n\nres    = zeros(Nx,Ny)\nind2D  = LinearIndices(fsol)\n\nM = Nx * Ny\n\nb_vec   = zeros(M)\naxx     = ones(M)\nayy     = ones(M)\naxy     = zeros(M)\nbx      = zeros(M)\nby      = zeros(M)\ncc      = zeros(M)\nf0      = zeros(M)\n\nitmax   = 8\nepsilon = 1e-12\n\nfor it in 1:itmax\n\n    compute_residual!(res, fsol, xcoord[:], ycoord[:], Dxx_op, Dyy_op, Dx_op, Dy_op)\n    max_res = maximum(abs.(res))\n\n    @show it, max_res\n    if max_res < epsilon\n        break\n    end\n\n    # build (linearized) operator\n    # A = Dxx + Dyy + x y Dxy + (x + 2 f0_x + x y f0_y) Dx + (y + 2 f0_y + x y f0_x) Dy + (x^2 + y^2)\n\n    @inbounds for idx in eachindex(f0)\n        f0[idx] = fsol[idx]\n    end\n    f0_x = Dx * f0\n    f0_y = Dy * f0\n\n    for j in 1:Ny, i in 1:Nx\n        idx = ind2D[i,j]\n\n        x1  = xcoord[i]\n        y1  = ycoord[j]\n\n        axy[idx] = x1 * y1\n        bx[idx]  = x1 + 2 * f0_x[idx] + x1 * y1 * f0_y[idx]\n        by[idx]  = y1 + 2 * f0_y[idx] + x1 * y1 * f0_x[idx]\n        cc[idx]  = x1^2 + y1^2\n\n        b_vec[idx] = -res[idx]\n    end\n\n    A_mat = build_jacobian(Dxx, Dyy, Dxy, Dx, Dy,\n                           Diagonal(axx), Diagonal(ayy), Diagonal(axy),\n                           Diagonal(bx), Diagonal(by), Diagonal(cc))\n\n    A_fact = factorize(A_mat)\n    ldiv!(f0, A_fact, b_vec)\n\n    # update solution\n    @inbounds for idx in eachindex(fsol)\n        fsol[idx] += f0[idx]\n    end\n\nend\n\n\nj_slice = div(Ny,2) + 1\nx = xcoord[:]\n\nplot(x, f_exact[:,j_slice])\nscatter!(x, fsol[:,j_slice])\n", "meta": {"hexsha": "c0c38421bd101bf2673d22a402fb7bf9b9b33272", "size": 4868, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example_2D_PDE_non-lin.jl", "max_stars_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_stars_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-09-08T23:37:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:19:01.000Z", "max_issues_repo_path": "examples/example_2D_PDE_non-lin.jl", "max_issues_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_issues_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-02T17:57:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-02T17:57:23.000Z", "max_forks_repo_path": "examples/example_2D_PDE_non-lin.jl", "max_forks_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_forks_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-02-26T15:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T08:46:55.000Z", "avg_line_length": 24.4623115578, "max_line_length": 101, "alphanum_fraction": 0.5665571076, "num_tokens": 1849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.824461919906883, "lm_q1q2_score": 0.7671273949483066}}
{"text": "## activate package environment\ncd(@__DIR__)\nusing Pkg\nPkg.activate(\"Project.toml\")\n\n## percentage x of Al, wavelengths λ and index of refraction n from publication Aspnes 1986\nx = [0.491 0.590]\nλ = [0.520]\nn = [3.8264 + 0.19880im;\n     3.7477 + 0.15232im]\nN = real(n)\nk = imag(n)\n\n## interpolation of n for wanted x\nx_wanted = [0.509]\nl = length(λ)\nm = length(x_wanted)\nN_wanted = zeros(m,l)\nk_wanted = zeros(m,l)\nfor i = 1:l\n    for j = 0:m-1\n        local coeffs_N = [x[j+1,:] ones(2)]\\N[(1+j*2):(1+j*2)+1,i]\n        local coeffs_k = [x[j+1,:] ones(2)]\\k[(1+j*2):(1+j*2)+1,i]\n        N_wanted[i,j+1] = coeffs_N[1]*x_wanted[j+1] + coeffs_N[2]\n        k_wanted[i,j+1] = coeffs_k[1]*x_wanted[j+1] + coeffs_k[2]\n    end\nend\nN_wanted = round.(N_wanted,sigdigits=4)\nk_wanted = round.(k_wanted,sigdigits=4)\n\n## output solution\nprintln(\"\")\nfor j = 1:m\n    for i = 1:l\n        println(\"n(x = $(x_wanted[j]), λ = $(lambda[i])) = $(N_wanted[i,j]) + $(k_wanted[i,j])i\")\n    end\nend\n", "meta": {"hexsha": "dda9a8ba992d92eef005615f8ac7693729d5ab99", "size": 973, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Code/ior_interp.jl", "max_stars_repo_name": "MaxGrossmann/TRPL", "max_stars_repo_head_hexsha": "b27bc01299502e09b997e52da0842edfb7dd61fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/ior_interp.jl", "max_issues_repo_name": "MaxGrossmann/TRPL", "max_issues_repo_head_hexsha": "b27bc01299502e09b997e52da0842edfb7dd61fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/ior_interp.jl", "max_forks_repo_name": "MaxGrossmann/TRPL", "max_forks_repo_head_hexsha": "b27bc01299502e09b997e52da0842edfb7dd61fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6052631579, "max_line_length": 97, "alphanum_fraction": 0.6032887975, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374122, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7671273945315912}}
{"text": "function square_distance(coords1, coords2)\n    \"\"\"Compute the square distances between coords1 and coords2.\n\n    Note: Depending on the input value and the dtype, negative values may\n    be mixed in the return value.\n\n    Args:\n        coords1: coordinates (N, C)\n        coords2: coordinates (M, C)\n\n    Returns:\n        square distances:\n            square distances between coords1 and coords2 (N, M)\n    \"\"\"\n    dot_product = -2 * coords1 * coords2'\n    column = repeat(sum(coords1 .* coords1, dims=2), 1, size(coords2, 1))\n    row = repeat(sum(coords2 .* coords2, dims=2), 1, size(coords1, 1))'\n    square_dist = column + dot_product + row\n    return square_dist\nend\n\nif abspath(PROGRAM_FILE) == @__FILE__\n    arr1 = reshape(range(0, 23, step=1), 8, 3)\n    arr2 = reshape(range(24, 47, step=1), 8, 3)\n    @time square_distance(arr1, arr2)\n    @time square_distance(arr1, arr2)\nend", "meta": {"hexsha": "35aafc61121601bdcf54fe880bec209839a4293e", "size": 885, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/operator.jl", "max_stars_repo_name": "Obarads/Point_Cloud_Tutorial", "max_stars_repo_head_hexsha": "faf7ae8abf962ecea414cc7557dc35f4fca0e406", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-22T10:32:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-22T10:32:49.000Z", "max_issues_repo_path": "julia/operator.jl", "max_issues_repo_name": "Obarads/Point_Cloud_Tutorial", "max_issues_repo_head_hexsha": "faf7ae8abf962ecea414cc7557dc35f4fca0e406", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-09T14:39:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T14:39:51.000Z", "max_forks_repo_path": "julia/operator.jl", "max_forks_repo_name": "Obarads/Point_Cloud_Tutorial", "max_forks_repo_head_hexsha": "faf7ae8abf962ecea414cc7557dc35f4fca0e406", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7777777778, "max_line_length": 73, "alphanum_fraction": 0.6542372881, "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.8479677660619634, "lm_q1q2_score": 0.7671144911364022}}
{"text": "# Fixed Talbot method\n#\n# Abate, J. and Valkó, P.P.\n# Multi-precision Laplace transform inversion\n# International Journal for Numerical Methods in Engineering, Vol. 60 (Iss. 5-7)  2004  pp 979–993\n\n\"\"\"\n    talbot(func::Function, t::AbstractFloat, M::Integer=talbot_default_num_terms)\n\nEvaluate the inverse Laplace transform of `func` at the point `t`. Use `M` terms in the algorithm.\nFor `typeof(t)` is `Float64`, the default for `M` is `32`. For `BigFloat` the default is `64`.\n\nIf `BigFloat` precision is larger than default, try increasing `M`.\n\n# Example\n\n```jldoctest\njulia> InverseLaplace.talbot(s -> 1 / s^3, 3)\n4.50000000000153\n```\n\n!!! note\n    This function uses the fixed Talbot method. It evaluates `func` for complex arguments.\n\"\"\"\nfunction talbot(func, t, M)\n    bM = convert(typeof(t), M)\n    r = (2 * bM) / (5 * t)\n    term = (1//2) * exp(r * t) * func(r)\n    for i in 1:M-1\n        theta = i * (pi/bM)\n        s = r * theta * (complex(cot(theta), one(theta)))\n        sigma = theta + (theta * cot(theta) - 1) * cot(theta)\n        term += real(exp(t * s) * complex(one(t), sigma) * func(s))\n    end\n    return term * 2 / (5 * t)\nend\n\ntalbot(func, t) = talbot(func, t, talbot_default_num_terms)\nconst talbot_BigFloat_default_num_terms = 64\ntalbot(func, t::BigFloat) = talbot(func, t, talbot_BigFloat_default_num_terms)\ntalbot(func, t::Integer, args...) = talbot(func, BigFloat(t), args...)\n# Hmm, at some point, one of these routines actually gave a Rational result. Don't recall how.\n# But, it can't be talbot.\ntalbot(func, t::Rational, args...) = talbot(func, BigFloat(t), args...)\n\n# Operate on an array of values of t. A single function evaluation\n# f(s) is used for all t\n# This gives more inaccurate results the further values of\n# t are from tmax\n\"\"\"\n    talbotarr(func, ta::AbstractArray, M)\n\nCompute the inverse Laplace transform for each element in `ta`. Each evaluation\nof `func(s)` is used for all elements of `ta`. This may be faster than a\nbroadcast application of `talbot` (i.e. `talbot.(...`) , but is in general, less\naccurate.  `talbotarr` uses the \"fixed\" Talbot method.\n\"\"\"\nfunction talbotarr(func, t::AbstractArray, M)\n    tt = typeof(t[1])\n    bM = convert(tt, M)\n    terms = similar(t)\n    tmax = maximum(t)\n    r = (2 * bM) / (5 * tmax)\n    fr = (1//2) * func(r)\n    terms .= exp.(r .* t) .* fr\n    for i in 1:M-1\n        theta = i * (pi/bM)\n        s = r * theta * (complex(cot(theta), one(theta)))\n        sigma = theta + (theta * cot(theta) - 1) * cot(theta)\n        fs = complex(one(tt), sigma) * func(s)\n        for j in 1:length(terms)\n            terms[j] += real(exp(t[j] * s) * fs)\n        end\n    end\n    terms .= terms .* 2 / (5 * tmax)\n    return terms\nend\n\ntalbotarr(func, t::AbstractArray) = talbotarr(func, t, talbot_default_num_terms)\ntalbotarr(func, t::Vector{BigFloat}) = talbotarr(func, t, talbot_BigFloat_default_num_terms)\n\n#  LocalWords:  talbotarr func talbot\n", "meta": {"hexsha": "48760b934fb1d1bcd09eb7c46347c3b5513bf3df", "size": 2922, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fixed_talbot.jl", "max_stars_repo_name": "jlapeyre/ILT.jl", "max_stars_repo_head_hexsha": "d6ba61e029bd367778293498cdfd266152d014cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2015-08-30T14:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T03:34:32.000Z", "max_issues_repo_path": "src/fixed_talbot.jl", "max_issues_repo_name": "jlapeyre/ILT.jl", "max_issues_repo_head_hexsha": "d6ba61e029bd367778293498cdfd266152d014cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2018-07-13T11:55:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T10:39:29.000Z", "max_forks_repo_path": "src/fixed_talbot.jl", "max_forks_repo_name": "jlapeyre/ILT.jl", "max_forks_repo_head_hexsha": "d6ba61e029bd367778293498cdfd266152d014cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-06-19T12:54:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T16:44:33.000Z", "avg_line_length": 35.2048192771, "max_line_length": 98, "alphanum_fraction": 0.6437371663, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7671144872487923}}
{"text": "# # Unconstrained optimization\n\n#=\nIn this example, we show how to differentiate through the solution of the following unconstrained optimization problem:\n```math\n\\hat{y}(x) = \\min_{y \\in \\mathbb{R}^m} f(x, y)\n```\nThe optimality conditions are given by gradient stationarity:\n```math\nF(x, \\hat{y}(x)) = 0 \\quad \\text{with} \\quad F(x,y) = \\nabla_2 f(x, y) = 0\n```\n\n=#\n\nusing ImplicitDifferentiation\nusing Optim: optimize, minimizer, LBFGS\nusing Zygote\n\nusing ChainRulesTestUtils  #src\nusing Test  #src\n\n# ## Implicit function wrapper\n\n#=\nTo make verification easy, we minimize a quadratic objective\n```math\nf(x, y) = \\lVert y - x \\rVert^2\n```\nIn this case, the optimization algorithm is very simple, but still we can implement it as a black box to show that it doesn't change the result.\n=#\n\nfunction forward(x)\n    f(y) = sum(abs2, y-x)\n    y0 = zero(x)\n    res = optimize(f, y0, LBFGS(); autodiff=:forward)\n    y = minimizer(res)\n    return y\nend;\n\n#=\nOn the other hand, optimality conditions should be provided explicitly whenever possible, so as to avoid nesting automatic differentiation calls.\n=#\n\nconditions(x, y) = 2(y - x);\n\n# We now have all the ingredients to construct our implicit function.\n\nimplicit = ImplicitFunction(forward, conditions);\n\n# ## Testing\n\nx = rand(5)\n\n# Let's start by taking a look at the forward pass, which should be the identity function.\n\nimplicit(x)\n\n# We now check whether the behavior of our `ImplicitFunction` wrapper is coherent with the theoretical derivatives.\n\nZygote.jacobian(implicit, x)[1]\n\n# As expected, we recover the identity matrix as Jacobian.\n\n# The following tests are not included in the docs.  #src\n\n@testset verbose = true \"ChainRules\" begin  #src\n    test_frule(implicit, x; check_inferred=false)  #src\n    test_rrule(implicit, x; check_inferred=false)  #src\nend  #src\n", "meta": {"hexsha": "5896cc43ef763bc5a859d1372319899329ccfd63", "size": 1827, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/1_unconstrained_optimization.jl", "max_stars_repo_name": "gdalle/ImplicitDifferentiation.jl", "max_stars_repo_head_hexsha": "19f68d94c754e2bb2ef370e31b0b6aa2ac1a00f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2022-03-29T14:06:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:10:49.000Z", "max_issues_repo_path": "test/1_unconstrained_optimization.jl", "max_issues_repo_name": "gdalle/ImplicitDifferentiation.jl", "max_issues_repo_head_hexsha": "19f68d94c754e2bb2ef370e31b0b6aa2ac1a00f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2022-03-30T10:29:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T07:23:57.000Z", "max_forks_repo_path": "test/1_unconstrained_optimization.jl", "max_forks_repo_name": "gdalle/ImplicitDifferentiation.jl", "max_forks_repo_head_hexsha": "19f68d94c754e2bb2ef370e31b0b6aa2ac1a00f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1, "max_line_length": 145, "alphanum_fraction": 0.7203065134, "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7671144850689326}}
{"text": "\"\"\"\n    expv(t, A, B; kwargs...)\n\nCompute `exp(t*A) * B` without computing `t * A` or the matrix exponential.\nThis is significantly faster than the matrix exponential when the second dimension of `B` is\nmuch smaller than the first one. The \"time\" `t` may be real or complex.\nThe algorithm is described in [^AlMohyHigham2011].\n\n# Keywords\n\n  - `shift=true`: Expand the Taylor series of `exp(t*A)` about ``A-μI=0`` instead of\n    ``A=0``, where ``μ = \\\\operatorname{tr}(A) / n`` to speed up convergence. See\n    §3.1 of [^AlMohyHigham2011].\n  - `tol`: The tolerance at which to compute the result. Defaults to the tolerance of the\n    eltype of the result.\n\n[^AlMohyHigham2011]: Al-Mohy, Awad H. and Higham, Nicholas J. (2011) Computing the Action of the Matrix\n    Exponential, with an Application to Exponential Integrators. SIAM Journal on Scientific\n    Computing, 33 (2). pp. 488-511. ISSN 1064-8275\n    doi: [10.1137/100788860](https://doi.org/10.1137/100788860)\n    eprint: [eprints.maths.manchester.ac.uk/id/eprint/1591](http://eprints.maths.manchester.ac.uk/id/eprint/1591)\n\"\"\"\nfunction expv(t, A, B; shift=true, tol=eps(float(real(Base.promote_eltype(t, A, B)))))\n    n = LinearAlgebra.checksquare(A)\n    # §3: “Our experience indicates that p_max = 8 and m_max = 55 are appropriate choices.”\n    p_max = 8\n    m_max = 55\n    n0 = size(B, 2)\n    if shift\n        μ = tr(A) / n\n        A -= μ * I\n    else\n        μ = zero(float(eltype(A)))\n    end\n    params = parameters(t, A, n0, m_max, p_max, tol)\n    η = exp(t * μ / params.s)\n    F = one(η) * B\n    for i in 1:(params.s)\n        c1 = _opnormInf(B)\n        for j in 1:(params.m)\n            B = (A * B) * (t / (params.s * j))\n            c2 = _opnormInf(B)\n            F += B\n            c1 + c2 ≤ tol * _opnormInf(F) && break\n            c1 = c2\n        end\n        F *= η\n        B = F\n    end\n    return F\nend\nexpv(t, A::Diagonal, B; kwargs...) = exp.(t .* A.diag) .* B\n", "meta": {"hexsha": "8d257a079b5b2782d304ea0f685fc9c2536d3fb5", "size": 1935, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/expv.jl", "max_stars_repo_name": "sethaxen/ExponentialAction.jl", "max_stars_repo_head_hexsha": "a1e6801c6b0d89798ee86aeeee8a575d6de59f71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-01-30T01:44:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:21:19.000Z", "max_issues_repo_path": "src/expv.jl", "max_issues_repo_name": "sethaxen/ExponentialAction.jl", "max_issues_repo_head_hexsha": "a1e6801c6b0d89798ee86aeeee8a575d6de59f71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-01-31T08:19:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:23:54.000Z", "max_forks_repo_path": "src/expv.jl", "max_forks_repo_name": "sethaxen/ExponentialAction.jl", "max_forks_repo_head_hexsha": "a1e6801c6b0d89798ee86aeeee8a575d6de59f71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5094339623, "max_line_length": 113, "alphanum_fraction": 0.6056847545, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.767114482889073}}
{"text": "\n\"\"\"\n`Energy` - Compute the energy\n\nE = -0.5 * J ∑ xᵢxⱼ\n\nover a periodic N×N square lattice.  Note that this counts each bond twice,\nhence the factor of 0.5\n\n### Fields\n* `x` - State of the lattice\n### Optional Fields\n* 'J=1' - Coupling constant>0\n\"\"\"\nfunction Energy(x::Tx; J::TF=1.0) where {TI<:Integer, Tx<:AbstractArray{TI}, TF<:AbstractFloat}\n    E = 0.0;\n\n    L= size(x)[1];\n    for i in 1:L, j in 1:L\n        # sum of energy contributions\n        k, l = mod1(i+1,L), j;\n        E += - 0.5 * J * x[i,j] * x[k,l];\n\n        k,l = mod1(i-1,L), j;\n        E += - 0.5 * J * x[i,j] * x[k,l];\n\n        k, l = i, mod1(j+1,L);;\n        E += - 0.5 * J * x[i,j] * x[k,l];\n\n        k, l = i, mod1(j-1,L);\n        E += - 0.5 * J * x[i,j] * x[k,l];\n    end\n    return E\nend\n\n\n\"\"\"\n`Magnetization` - Compute the magnetization\n\nM = ∑ xᵢ\n\nover a periodic N×N square lattice.\n\n### Fields\n* `x` - State of the lattice\n\"\"\"\nfunction Magnetization(x::Tx) where {TI<:Integer, Tx<:AbstractArray{TI}}\n    return sum(x)\nend\n\n\n\"\"\"\n`ClusterNeighbors!` - Mark on the cluster map, `c`, where the current cluster\ncontinues.\n\n\n### Fields\n* `c` - Cluster map\n* `x` - State of the lattice\n* `i,j` - Indices of the current site\n* `D` - Direction of the current cluster (+/-1)\n* `id` - Cluster id\n* `L` - Lattice size, L × L\n\"\"\"\nfunction ClusterNeighbors!(c, x, i, j, D, id, L)\n\n    k,l = mod1(i+1,L), j;\n    if (x[k,l] == D && c[k,l]==0)\n        c[k,l] = id;\n        ClusterNeighbors!(c, x, k, l, D, id, L)\n    end\n\n    k,l = mod1(i-1,L), j;\n    if (x[k,l]==D && c[k,l]==0)\n        c[k,l] = id;\n        ClusterNeighbors!(c, x, k, l, D, id, L)\n    end\n\n    k,l = i, mod1(j+1,L);\n    if (x[k,l]==D && c[k,l]==0)\n        c[k,l] = id;\n        ClusterNeighbors!(c, x, k, l, D, id, L)\n    end\n\n    k,l = i, mod1(j-1,L);\n    if (x[k,l]==D && c[k,l]==0)\n        c[k,l] = id;\n        ClusterNeighbors!(c, x, k, l, D, id, L)\n    end\n    c\nend\n\n\n\"\"\"\n`Cluster` - Find all the clusters in the lattice.  Note that the numbering is\narbitrary.\n\n\n### Fields\n* `x` - State of the lattice\n\"\"\"\nfunction Clusters(x::Tx) where {TI<:Integer, Tx<:AbstractArray{TI}}\n    L= size(x)[1];\n    id = 0;\n    c = zeros(Int, L, L);\n\n    for i in 1:L, j in 1:L\n        if(c[i,j]==0)\n            id+=1;\n            c[i,j] = id;\n            D = x[i,j];\n            ClusterNeighbors!(c, x, i, j, D, id, L)\n        end\n    end\n\n    return c\nend\n\n", "meta": {"hexsha": "139bf1b3469120a714e2918e7cf0669b755d1c6f", "size": 2378, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/observables2D.jl", "max_stars_repo_name": "gideonsimpson/Ising2D.jl", "max_stars_repo_head_hexsha": "a8ba0c081d42b27f73803fb3d59d3f91cee53cb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/observables2D.jl", "max_issues_repo_name": "gideonsimpson/Ising2D.jl", "max_issues_repo_head_hexsha": "a8ba0c081d42b27f73803fb3d59d3f91cee53cb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/observables2D.jl", "max_forks_repo_name": "gideonsimpson/Ising2D.jl", "max_forks_repo_head_hexsha": "a8ba0c081d42b27f73803fb3d59d3f91cee53cb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9831932773, "max_line_length": 95, "alphanum_fraction": 0.5008410429, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476385, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7670544570424274}}
{"text": "# This file is a part of Julia. License is MIT: https://julialang.org/license\n\n## number-theoretic functions ##\n\n\"\"\"\n    gcd(x,y)\n\nGreatest common (positive) divisor (or zero if `x` and `y` are both zero).\n\n# Examples\n```jldoctest\njulia> gcd(6,9)\n3\n\njulia> gcd(6,-9)\n3\n```\n\"\"\"\nfunction gcd(a::T, b::T) where T<:Integer\n    while b != 0\n        t = b\n        b = rem(a, b)\n        a = t\n    end\n    checked_abs(a)\nend\n\n# binary GCD (aka Stein's) algorithm\n# about 1.7x (2.1x) faster for random Int64s (Int128s)\nfunction gcd(a::T, b::T) where T<:Union{Int8,UInt8,Int16,UInt16,Int32,UInt32,Int64,UInt64,Int128,UInt128}\n    a == 0 && return abs(b)\n    b == 0 && return abs(a)\n    za = trailing_zeros(a)\n    zb = trailing_zeros(b)\n    k = min(za, zb)\n    u = unsigned(abs(a >> za))\n    v = unsigned(abs(b >> zb))\n    while u != v\n        if u > v\n            u, v = v, u\n        end\n        v -= u\n        v >>= trailing_zeros(v)\n    end\n    r = u << k\n    # T(r) would throw InexactError; we want OverflowError instead\n    r > typemax(T) && __throw_gcd_overflow(a, b)\n    r % T\nend\n@noinline __throw_gcd_overflow(a, b) = throw(OverflowError(\"gcd($a, $b) overflows\"))\n\n\"\"\"\n    lcm(x,y)\n\nLeast common (non-negative) multiple.\n\n# Examples\n```jldoctest\njulia> lcm(2,3)\n6\n\njulia> lcm(-2,3)\n6\n```\n\"\"\"\nfunction lcm(a::T, b::T) where T<:Integer\n    # explicit a==0 test is to handle case of lcm(0,0) correctly\n    if a == 0\n        return a\n    else\n        return checked_abs(a * div(b, gcd(b,a)))\n    end\nend\n\ngcd(a::Integer) = a\nlcm(a::Integer) = a\ngcd(a::Integer, b::Integer) = gcd(promote(a,b)...)\nlcm(a::Integer, b::Integer) = lcm(promote(a,b)...)\ngcd(a::Integer, b::Integer...) = gcd(a, gcd(b...))\nlcm(a::Integer, b::Integer...) = lcm(a, lcm(b...))\n\nlcm(abc::AbstractArray{<:Integer}) = reduce(lcm, abc; init=one(eltype(abc)))\n\nfunction gcd(abc::AbstractArray{<:Integer})\n    a = zero(eltype(abc))\n    for b in abc\n        a = gcd(a,b)\n        if a == 1\n            return a\n        end\n    end\n    return a\nend\n\n# return (gcd(a,b),x,y) such that ax+by == gcd(a,b)\n\"\"\"\n    gcdx(x,y)\n\nComputes the greatest common (positive) divisor of `x` and `y` and their Bézout\ncoefficients, i.e. the integer coefficients `u` and `v` that satisfy\n``ux+vy = d = gcd(x,y)``. ``gcdx(x,y)`` returns ``(d,u,v)``.\n\n# Examples\n```jldoctest\njulia> gcdx(12, 42)\n(6, -3, 1)\n\njulia> gcdx(240, 46)\n(2, -9, 47)\n```\n\n!!! note\n    Bézout coefficients are *not* uniquely defined. `gcdx` returns the minimal\n    Bézout coefficients that are computed by the extended Euclidean algorithm.\n    (Ref: D. Knuth, TAoCP, 2/e, p. 325, Algorithm X.)\n    For signed integers, these coefficients `u` and `v` are minimal in\n    the sense that ``|u| < |y/d|`` and ``|v| < |x/d|``. Furthermore,\n    the signs of `u` and `v` are chosen so that `d` is positive.\n    For unsigned integers, the coefficients `u` and `v` might be near\n    their `typemax`, and the identity then holds only via the unsigned\n    integers' modulo arithmetic.\n\"\"\"\nfunction gcdx(a::T, b::T) where T<:Integer\n    # a0, b0 = a, b\n    s0, s1 = oneunit(T), zero(T)\n    t0, t1 = s1, s0\n    # The loop invariant is: s0*a0 + t0*b0 == a\n    while b != 0\n        q = div(a, b)\n        a, b = b, rem(a, b)\n        s0, s1 = s1, s0 - q*s1\n        t0, t1 = t1, t0 - q*t1\n    end\n    a < 0 ? (-a, -s0, -t0) : (a, s0, t0)\nend\ngcdx(a::Integer, b::Integer) = gcdx(promote(a,b)...)\n\n# multiplicative inverse of n mod m, error if none\n\n\"\"\"\n    invmod(x,m)\n\nTake the inverse of `x` modulo `m`: `y` such that ``x y = 1 \\\\pmod m``,\nwith ``div(x,y) = 0``. This is undefined for ``m = 0``, or if\n``gcd(x,m) \\\\neq 1``.\n\n# Examples\n```jldoctest\njulia> invmod(2,5)\n3\n\njulia> invmod(2,3)\n2\n\njulia> invmod(5,6)\n5\n```\n\"\"\"\nfunction invmod(n::T, m::T) where T<:Integer\n    g, x, y = gcdx(n, m)\n    g != 1 && throw(DomainError((n, m), \"Greatest common divisor is $g.\"))\n    m == 0 && throw(DomainError(m, \"`m` must not be 0.\"))\n    # Note that m might be negative here.\n    # For unsigned T, x might be close to typemax; add m to force a wrap-around.\n    r = mod(x + m, m)\n    # The postcondition is: mod(r * n, m) == mod(T(1), m) && div(r, m) == 0\n    r\nend\ninvmod(n::Integer, m::Integer) = invmod(promote(n,m)...)\n\n# ^ for any x supporting *\nto_power_type(x) = convert(Base._return_type(*, Tuple{typeof(x), typeof(x)}), x)\n@noinline throw_domerr_powbysq(::Any, p) = throw(DomainError(p,\n    string(\"Cannot raise an integer x to a negative power \", p, '.',\n           \"\\nConvert input to float.\")))\n@noinline throw_domerr_powbysq(::Integer, p) = throw(DomainError(p,\n   string(\"Cannot raise an integer x to a negative power \", p, '.',\n          \"\\nMake x a float by adding a zero decimal (e.g., 2.0^$p instead \",\n          \"of 2^$p), or write 1/x^$(-p), float(x)^$p, or (x//1)^$p\")))\n@noinline throw_domerr_powbysq(::AbstractMatrix, p) = throw(DomainError(p,\n   string(\"Cannot raise an integer matrix x to a negative power \", p, '.',\n          \"\\nMake x a float matrix by adding a zero decimal \",\n          \"(e.g., [2.0 1.0;1.0 0.0]^$p instead \",\n          \"of [2 1;1 0]^$p), or write float(x)^$p or Rational.(x)^$p\")))\nfunction power_by_squaring(x_, p::Integer)\n    x = to_power_type(x_)\n    if p == 1\n        return copy(x)\n    elseif p == 0\n        return one(x)\n    elseif p == 2\n        return x*x\n    elseif p < 0\n        isone(x) && return copy(x)\n        isone(-x) && return iseven(p) ? one(x) : copy(x)\n        throw_domerr_powbysq(x, p)\n    end\n    t = trailing_zeros(p) + 1\n    p >>= t\n    while (t -= 1) > 0\n        x *= x\n    end\n    y = x\n    while p > 0\n        t = trailing_zeros(p) + 1\n        p >>= t\n        while (t -= 1) >= 0\n            x *= x\n        end\n        y *= x\n    end\n    return y\nend\npower_by_squaring(x::Bool, p::Unsigned) = ((p==0) | x)\nfunction power_by_squaring(x::Bool, p::Integer)\n    p < 0 && !x && throw_domerr_powbysq(x, p)\n    return (p==0) | x\nend\n\n^(x::T, p::T) where {T<:Integer} = power_by_squaring(x,p)\n^(x::Number, p::Integer)  = power_by_squaring(x,p)\n\n# x^p for any literal integer p is lowered to Base.literal_pow(^, x, Val(p))\n# to enable compile-time optimizations specialized to p.\n# However, we still need a fallback that calls the function ^ which may either\n# mean Base.^ or something else, depending on context.\n# We mark these @inline since if the target is marked @inline,\n# we want to make sure that gets propagated,\n# even if it is over the inlining threshold.\n@inline literal_pow(f, x, ::Val{p}) where {p} = f(x,p)\n\n# Restrict inlining to hardware-supported arithmetic types, which\n# are fast enough to benefit from inlining.\nconst HWReal = Union{Int8,Int16,Int32,Int64,UInt8,UInt16,UInt32,UInt64,Float32,Float64}\nconst HWNumber = Union{HWReal, Complex{<:HWReal}, Rational{<:HWReal}}\n\n# Core.Compiler has complicated logic to inline x^2 and x^3 for\n# numeric types.  In terms of Val we can do it much more simply.\n# (The first argument prevents unexpected behavior if a function ^\n# is defined that is not equal to Base.^)\n@inline literal_pow(::typeof(^), x::HWNumber, ::Val{0}) = one(x)\n@inline literal_pow(::typeof(^), x::HWNumber, ::Val{1}) = x\n@inline literal_pow(::typeof(^), x::HWNumber, ::Val{2}) = x*x\n@inline literal_pow(::typeof(^), x::HWNumber, ::Val{3}) = x*x*x\n\n# don't use the inv(x) transformation here since float^p is slightly more accurate\n@inline literal_pow(::typeof(^), x::AbstractFloat, ::Val{p}) where {p} = x^p\n@inline literal_pow(::typeof(^), x::AbstractFloat, ::Val{-1}) = inv(x)\n\n# for other types, define x^-n as inv(x)^n so that negative literal powers can\n# be computed in a type-stable way even for e.g. integers.\n@inline @generated function literal_pow(f::typeof(^), x, ::Val{p}) where {p}\n    if p < 0\n        :(literal_pow(^, inv(x), $(Val{-p}())))\n    else\n        :(f(x,$p))\n    end\nend\n\n# note: it is tempting to add optimized literal_pow(::typeof(^), x, ::Val{n})\n#       methods here for various n, but this easily leads to method ambiguities\n#       if anyone has defined literal_pow(::typeof(^), x::T, ::Val).\n\n# b^p mod m\n\n\"\"\"\n    powermod(x::Integer, p::Integer, m)\n\nCompute ``x^p \\\\pmod m``.\n\n# Examples\n```jldoctest\njulia> powermod(2, 6, 5)\n4\n\njulia> mod(2^6, 5)\n4\n\njulia> powermod(5, 2, 20)\n5\n\njulia> powermod(5, 2, 19)\n6\n\njulia> powermod(5, 3, 19)\n11\n```\n\"\"\"\nfunction powermod(x::Integer, p::Integer, m::T) where T<:Integer\n    p < 0 && return powermod(invmod(x, m), -p, m)\n    p == 0 && return mod(one(m),m)\n    (m == 1 || m == -1) && return zero(m)\n    b = oftype(m,mod(x,m))  # this also checks for divide by zero\n\n    t = prevpow(2, p)\n    r::T = 1\n    while true\n        if p >= t\n            r = mod(widemul(r,b),m)\n            p -= t\n        end\n        t >>>= 1\n        t <= 0 && break\n        r = mod(widemul(r,r),m)\n    end\n    return r\nend\n\n# optimization: promote the modulus m to BigInt only once (cf. widemul in generic powermod above)\npowermod(x::Integer, p::Integer, m::Union{Int128,UInt128}) = oftype(m, powermod(x, p, big(m)))\n\n_nextpow2(x::Unsigned) = oneunit(x)<<((sizeof(x)<<3)-leading_zeros(x-oneunit(x)))\n_nextpow2(x::Integer) = reinterpret(typeof(x),x < 0 ? -_nextpow2(unsigned(-x)) : _nextpow2(unsigned(x)))\n_prevpow2(x::Unsigned) = one(x) << unsigned((sizeof(x)<<3)-leading_zeros(x)-1)\n_prevpow2(x::Integer) = reinterpret(typeof(x),x < 0 ? -_prevpow2(unsigned(-x)) : _prevpow2(unsigned(x)))\n\n\"\"\"\n    ispow2(n::Integer) -> Bool\n\nTest whether `n` is a power of two.\n\n# Examples\n```jldoctest\njulia> ispow2(4)\ntrue\n\njulia> ispow2(5)\nfalse\n```\n\"\"\"\nispow2(x::Integer) = x > 0 && count_ones(x) == 1\n\n\"\"\"\n    nextpow(a, x)\n\nThe smallest `a^n` not less than `x`, where `n` is a non-negative integer. `a` must be\ngreater than 1, and `x` must be greater than 0.\n\n# Examples\n```jldoctest\njulia> nextpow(2, 7)\n8\n\njulia> nextpow(2, 9)\n16\n\njulia> nextpow(5, 20)\n25\n\njulia> nextpow(4, 16)\n16\n```\n\nSee also [`prevpow`](@ref).\n\"\"\"\nfunction nextpow(a::Real, x::Real)\n    x <= 0 && throw(DomainError(x, \"`x` must be positive.\"))\n    # Special case fast path for x::Integer, a == 2.\n    # This is a very common case. Constant prop will make sure that a call site\n    # specified as `nextpow(2, x)` will get this special case inlined.\n    a == 2 && isa(x, Integer) && return _nextpow2(x)\n    a <= 1 && throw(DomainError(a, \"`a` must be greater than 1.\"))\n    x <= 1 && return one(a)\n    n = ceil(Integer,log(a, x))\n    p = a^(n-1)\n    # guard against roundoff error, e.g., with a=5 and x=125\n    p >= x ? p : a^n\nend\n\n\"\"\"\n    prevpow(a, x)\n\nThe largest `a^n` not greater than `x`, where `n` is a non-negative integer.\n`a` must be greater than 1, and `x` must not be less than 1.\n\n# Examples\n```jldoctest\njulia> prevpow(2, 7)\n4\n\njulia> prevpow(2, 9)\n8\n\njulia> prevpow(5, 20)\n5\n\njulia> prevpow(4, 16)\n16\n```\nSee also [`nextpow`](@ref).\n\"\"\"\nfunction prevpow(a::Real, x::Real)\n    x < 1 && throw(DomainError(x, \"`x` must be ≥ 1.\"))\n    # See comment in nextpos() for a == special case.\n    a == 2 && isa(x, Integer) && return _prevpow2(x)\n    a <= 1 && throw(DomainError(a, \"`a` must be greater than 1.\"))\n    n = floor(Integer,log(a, x))\n    p = a^(n+1)\n    p <= x ? p : a^n\nend\n\n## ndigits (number of digits) in base 10 ##\n\n# decimal digits in an unsigned integer\nconst powers_of_ten = [\n    0x0000000000000001, 0x000000000000000a, 0x0000000000000064, 0x00000000000003e8,\n    0x0000000000002710, 0x00000000000186a0, 0x00000000000f4240, 0x0000000000989680,\n    0x0000000005f5e100, 0x000000003b9aca00, 0x00000002540be400, 0x000000174876e800,\n    0x000000e8d4a51000, 0x000009184e72a000, 0x00005af3107a4000, 0x00038d7ea4c68000,\n    0x002386f26fc10000, 0x016345785d8a0000, 0x0de0b6b3a7640000, 0x8ac7230489e80000,\n]\nfunction bit_ndigits0z(x::Base.BitUnsigned64)\n    lz = (sizeof(x)<<3)-leading_zeros(x)\n    nd = (1233*lz)>>12+1\n    nd -= x < powers_of_ten[nd]\nend\nfunction bit_ndigits0z(x::UInt128)\n    n = 0\n    while x > 0x8ac7230489e80000\n        x = div(x,0x8ac7230489e80000)\n        n += 19\n    end\n    return n + ndigits0z(UInt64(x))\nend\n\nndigits0z(x::BitSigned) = bit_ndigits0z(unsigned(abs(x)))\nndigits0z(x::BitUnsigned) = bit_ndigits0z(x)\nndigits0z(x::Integer) = ndigits0zpb(x, 10)\n\n## ndigits with specified base ##\n\n# The suffix \"nb\" stands for \"negative base\"\nfunction ndigits0znb(x::Integer, b::Integer)\n    d = 0\n    if x isa Unsigned\n        d += (x != 0)::Bool\n        x = -signed(fld(x, -b))\n    end\n    # precondition: b < -1 && !(typeof(x) <: Unsigned)\n    while x != 0\n        x = cld(x,b)\n        d += 1\n    end\n    return d\nend\n\n# do first division before conversion with signed here, which can otherwise overflow\nndigits0znb(x::Bool, b::Integer) = x % Int\n\n# The suffix \"pb\" stands for \"positive base\"\nfunction ndigits0zpb(x::Integer, b::Integer)\n    # precondition: b > 1\n    x == 0 && return 0\n    b = Int(b)\n    x = abs(x)\n    if x isa Base.BitInteger\n        x = unsigned(x)::Unsigned\n        b == 2  && return sizeof(x)<<3 - leading_zeros(x)\n        b == 8  && return (sizeof(x)<<3 - leading_zeros(x) + 2) ÷ 3\n        b == 16 && return sizeof(x)<<1 - leading_zeros(x)>>2\n        b == 10 && return bit_ndigits0z(x)\n    end\n\n    d = 0\n    while x > typemax(Int)\n        x = div(x,b)\n        d += 1\n    end\n    x = div(x,b)\n    d += 1\n\n    m = 1\n    while m <= x\n        m *= b\n        d += 1\n    end\n    return d\nend\n\nndigits0zpb(x::Bool, b::Integer) = x % Int\n\n# The suffix \"0z\" means that the output is 0 on input zero (cf. #16841)\n\"\"\"\n    ndigits0z(n::Integer, b::Integer=10)\n\nReturn 0 if `n == 0`, otherwise compute the number of digits in\ninteger `n` written in base `b` (i.e. equal to `ndigits(n, base=b)`\nin this case).\nThe base `b` must not be in `[-1, 0, 1]`.\n\n# Examples\n```jldoctest\njulia> Base.ndigits0z(0, 16)\n0\n\njulia> Base.ndigits(0, base=16)\n1\n\njulia> Base.ndigits0z(0)\n0\n\njulia> Base.ndigits0z(10, 2)\n4\n\njulia> Base.ndigits0z(10)\n2\n```\n\nSee also [`ndigits`](@ref).\n\"\"\"\nfunction ndigits0z(x::Integer, b::Integer)\n    if b < -1\n        ndigits0znb(x, b)\n    elseif b > 1\n        ndigits0zpb(x, b)\n    else\n        throw(DomainError(b, \"The base must not be in `[-1, 0, 1]`.\"))\n    end\nend\n\n\"\"\"\n    ndigits(n::Integer; base::Integer=10, pad::Integer=1)\n\nCompute the number of digits in integer `n` written in base `base`\n(`base` must not be in `[-1, 0, 1]`), optionally padded with zeros\nto a specified size (the result will never be less than `pad`).\n\n# Examples\n```jldoctest\njulia> ndigits(12345)\n5\n\njulia> ndigits(1022, base=16)\n3\n\njulia> string(1022, base=16)\n\"3fe\"\n\njulia> ndigits(123, pad=5)\n5\n```\n\"\"\"\nndigits(x::Integer; base::Integer=10, pad::Integer=1) = max(pad, ndigits0z(x, base))\n\n## integer to string functions ##\n\nfunction bin(x::Unsigned, pad::Integer, neg::Bool)\n    i = neg + max(pad,sizeof(x)<<3-leading_zeros(x))\n    a = StringVector(i)\n    while i > neg\n        @inbounds a[i] = 48+(x&0x1)\n        x >>= 1\n        i -= 1\n    end\n    if neg; @inbounds a[1]=0x2d; end\n    String(a)\nend\n\nfunction oct(x::Unsigned, pad::Integer, neg::Bool)\n    i = neg + max(pad,div((sizeof(x)<<3)-leading_zeros(x)+2,3))\n    a = StringVector(i)\n    while i > neg\n        @inbounds a[i] = 48+(x&0x7)\n        x >>= 3\n        i -= 1\n    end\n    if neg; @inbounds a[1]=0x2d; end\n    String(a)\nend\n\nfunction dec(x::Unsigned, pad::Integer, neg::Bool)\n    i = neg + ndigits(x, base=10, pad=pad)\n    a = StringVector(i)\n    while i > neg\n        @inbounds a[i] = 48+rem(x,10)\n        x = oftype(x,div(x,10))\n        i -= 1\n    end\n    if neg; @inbounds a[1]=0x2d; end\n    String(a)\nend\n\nfunction hex(x::Unsigned, pad::Integer, neg::Bool)\n    i = neg + max(pad,(sizeof(x)<<1)-(leading_zeros(x)>>2))\n    a = StringVector(i)\n    while i > neg\n        d = x & 0xf\n        @inbounds a[i] = 48+d+39*(d>9)\n        x >>= 4\n        i -= 1\n    end\n    if neg; @inbounds a[1]=0x2d; end\n    String(a)\nend\n\nconst base36digits = ['0':'9';'a':'z']\nconst base62digits = ['0':'9';'A':'Z';'a':'z']\n\nfunction _base(b::Integer, x::Integer, pad::Integer, neg::Bool)\n    (x >= 0) | (b < 0) || throw(DomainError(x, \"For negative `x`, `b` must be negative.\"))\n    2 <= abs(b) <= 62 || throw(DomainError(b, \"base must satisfy 2 ≤ abs(base) ≤ 62\"))\n    digits = abs(b) <= 36 ? base36digits : base62digits\n    i = neg + ndigits(x, base=b, pad=pad)\n    a = StringVector(i)\n    @inbounds while i > neg\n        if b > 0\n            a[i] = digits[1+rem(x,b)]\n            x = div(x,b)\n        else\n            a[i] = digits[1+mod(x,-b)]\n            x = cld(x,b)\n        end\n        i -= 1\n    end\n    if neg; a[1]='-'; end\n    String(a)\nend\n\nsplit_sign(n::Integer) = unsigned(abs(n)), n < 0\nsplit_sign(n::Unsigned) = n, false\n\n\"\"\"\n    string(n::Integer; base::Integer = 10, pad::Integer = 1)\n\nConvert an integer `n` to a string in the given `base`,\noptionally specifying a number of digits to pad to.\n\n```jldoctest\njulia> string(5, base = 13, pad = 4)\n\"0005\"\n\njulia> string(13, base = 5, pad = 4)\n\"0023\"\n```\n\"\"\"\nfunction string(n::Integer; base::Integer = 10, pad::Integer = 1)\n    if base == 2\n        (n_positive, neg) = split_sign(n)\n        bin(n_positive, pad, neg)\n    elseif base == 8\n        (n_positive, neg) = split_sign(n)\n        oct(n_positive, pad, neg)\n    elseif base == 10\n        (n_positive, neg) = split_sign(n)\n        dec(n_positive, pad, neg)\n    elseif base == 16\n        (n_positive, neg) = split_sign(n)\n        hex(n_positive, pad, neg)\n    else\n        _base(base, base > 0 ? unsigned(abs(n)) : convert(Signed, n), pad, (base>0) & (n<0))\n    end\nend\n\nstring(b::Bool) = b ? \"true\" : \"false\"\n\n\"\"\"\n    bitstring(n)\n\nA string giving the literal bit representation of a number.\n\n# Examples\n```jldoctest\njulia> bitstring(4)\n\"0000000000000000000000000000000000000000000000000000000000000100\"\n\njulia> bitstring(2.2)\n\"0100000000000001100110011001100110011001100110011001100110011010\"\n```\n\"\"\"\nfunction bitstring end\n\nbitstring(x::Union{Bool,Int8,UInt8})           = string(reinterpret(UInt8,x), pad = 8, base = 2)\nbitstring(x::Union{Int16,UInt16,Float16})      = string(reinterpret(UInt16,x), pad = 16, base = 2)\nbitstring(x::Union{Char,Int32,UInt32,Float32}) = string(reinterpret(UInt32,x), pad = 32, base = 2)\nbitstring(x::Union{Int64,UInt64,Float64})      = string(reinterpret(UInt64,x), pad = 64, base = 2)\nbitstring(x::Union{Int128,UInt128})            = string(reinterpret(UInt128,x), pad = 128, base = 2)\n\n\"\"\"\n    digits([T<:Integer], n::Integer; base::T = 10, pad::Integer = 1)\n\nReturn an array with element type `T` (default `Int`) of the digits of `n` in the given\nbase, optionally padded with zeros to a specified size. More significant digits are at\nhigher indices, such that `n == sum([digits[k]*base^(k-1) for k=1:length(digits)])`.\n\n# Examples\n```jldoctest\njulia> digits(10, base = 10)\n2-element Array{Int64,1}:\n 0\n 1\n\njulia> digits(10, base = 2)\n4-element Array{Int64,1}:\n 0\n 1\n 0\n 1\n\njulia> digits(10, base = 2, pad = 6)\n6-element Array{Int64,1}:\n 0\n 1\n 0\n 1\n 0\n 0\n```\n\"\"\"\ndigits(n::Integer; base::Integer = 10, pad::Integer = 1) =\n    digits(typeof(base), n, base = base, pad = pad)\n\nfunction digits(T::Type{<:Integer}, n::Integer; base::Integer = 10, pad::Integer = 1)\n    digits!(zeros(T, ndigits(n, base=base, pad=pad)), n, base=base)\nend\n\n\"\"\"\n    hastypemax(T::Type) -> Bool\n\nReturn `true` if and only if `typemax(T)` is defined.\n\"\"\"\nhastypemax(::Base.BitIntegerType) = true\nhastypemax(::Type{T}) where {T} = applicable(typemax, T)\n\n\"\"\"\n    digits!(array, n::Integer; base::Integer = 10)\n\nFills an array of the digits of `n` in the given base. More significant digits are at higher\nindices. If the array length is insufficient, the least significant digits are filled up to\nthe array length. If the array length is excessive, the excess portion is filled with zeros.\n\n# Examples\n```jldoctest\njulia> digits!([2,2,2,2], 10, base = 2)\n4-element Array{Int64,1}:\n 0\n 1\n 0\n 1\n\njulia> digits!([2,2,2,2,2,2], 10, base = 2)\n6-element Array{Int64,1}:\n 0\n 1\n 0\n 1\n 0\n 0\n```\n\"\"\"\nfunction digits!(a::AbstractVector{T}, n::Integer; base::Integer = 10) where T<:Integer\n    2 <= abs(base) || throw(DomainError(base, \"base must be ≥ 2 or ≤ -2\"))\n    hastypemax(T) && abs(base) - 1 > typemax(T) &&\n        throw(ArgumentError(\"type $T too small for base $base\"))\n    isempty(a) && return a\n\n    if base > 0\n        for i in eachindex(a)\n            n, d = divrem(n, base)\n            a[i] = d\n        end\n    else\n        # manually peel one loop iteration for type stability\n        n, d = fldmod(n, -base)\n        a[firstindex(a)] = d\n        n = -signed(n)\n        for i in firstindex(a)+1:lastindex(a)\n            n, d = fldmod(n, -base)\n            a[i] = d\n            n = -n\n        end\n    end\n    return a\nend\n\n\"\"\"\n    isqrt(n::Integer)\n\nInteger square root: the largest integer `m` such that `m*m <= n`.\n\n```jldoctest\njulia> isqrt(5)\n2\n```\n\"\"\"\nisqrt(x::Integer) = oftype(x, trunc(sqrt(x)))\n\nfunction isqrt(x::Union{Int64,UInt64,Int128,UInt128})\n    x==0 && return x\n    s = oftype(x, trunc(sqrt(x)))\n    # fix with a Newton iteration, since conversion to float discards\n    # too many bits.\n    s = (s + div(x,s)) >> 1\n    s*s > x ? s-1 : s\nend\n\n\"\"\"\n    factorial(n::Integer)\n\nFactorial of `n`. If `n` is an [`Integer`](@ref), the factorial is computed as an\ninteger (promoted to at least 64 bits). Note that this may overflow if `n` is not small,\nbut you can use `factorial(big(n))` to compute the result exactly in arbitrary precision.\n\n# Examples\n```jldoctest\njulia> factorial(6)\n720\n\njulia> factorial(21)\nERROR: OverflowError: 21 is too large to look up in the table; consider using `factorial(big(21))` instead\nStacktrace:\n[...]\n\njulia> factorial(big(21))\n51090942171709440000\n```\n\n# See also\n* [`binomial`](@ref)\n\n# External links\n* [Factorial](https://en.wikipedia.org/wiki/Factorial) on Wikipedia.\n\"\"\"\nfunction factorial(n::Integer)\n    n < 0 && throw(DomainError(n, \"`n` must be nonnegative.\"))\n    f::typeof(n*n) = 1\n    for i::typeof(n*n) = 2:n\n        f *= i\n    end\n    return f\nend\n\n\"\"\"\n    binomial(n::Integer, k::Integer)\n\nThe _binomial coefficient_ ``\\\\binom{n}{k}``, being the coefficient of the ``k``th term in\nthe polynomial expansion of ``(1+x)^n``.\n\nIf ``n`` is non-negative, then it is the number of ways to choose `k` out of `n` items:\n```math\n\\\\binom{n}{k} = \\\\frac{n!}{k! (n-k)!}\n```\nwhere ``n!`` is the [`factorial`](@ref) function.\n\nIf ``n`` is negative, then it is defined in terms of the identity\n```math\n\\\\binom{n}{k} = (-1)^k \\\\binom{k-n-1}{k}\n```\n\n# Examples\n```jldoctest\njulia> binomial(5, 3)\n10\n\njulia> factorial(5) ÷ (factorial(5-3) * factorial(3))\n10\n\njulia> binomial(-5, 3)\n-35\n```\n\n# See also\n* [`factorial`](@ref)\n\n# External links\n* [Binomial coeffient](https://en.wikipedia.org/wiki/Binomial_coefficient) on Wikipedia.\n\"\"\"\nfunction binomial(n::T, k::T) where T<:Integer\n    n0, k0 = n, k\n    k < 0 && return zero(T)\n    sgn = one(T)\n    if n < 0\n        n = -n + k -1\n        if isodd(k)\n            sgn = -sgn\n        end\n    end\n    k > n && return zero(T)\n    (k == 0 || k == n) && return sgn\n    k == 1 && return sgn*n\n    if k > (n>>1)\n        k = (n - k)\n    end\n    x::T = nn = n - k + 1\n    nn += 1\n    rr = 2\n    while rr <= k\n        xt = div(widemul(x, nn), rr)\n        x = xt % T\n        x == xt || throw(OverflowError(\"binomial($n0, $k0) overflows\"))\n        rr += 1\n        nn += 1\n    end\n    convert(T, copysign(x, sgn))\nend\n", "meta": {"hexsha": "7ebcc6c57fda123ade37c80e410cc5eccf8433c6", "size": 23215, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "base/intfuncs.jl", "max_stars_repo_name": "EricForgy/julia", "max_stars_repo_head_hexsha": "65df5112babbb26b101da70d430181d94806f94b", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "base/intfuncs.jl", "max_issues_repo_name": "EricForgy/julia", "max_issues_repo_head_hexsha": "65df5112babbb26b101da70d430181d94806f94b", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "base/intfuncs.jl", "max_forks_repo_name": "EricForgy/julia", "max_forks_repo_head_hexsha": "65df5112babbb26b101da70d430181d94806f94b", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.938547486, "max_line_length": 106, "alphanum_fraction": 0.6019814775, "num_tokens": 8023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7670544434968992}}
{"text": "# # Spectrahedron\n#\n# This example shows an optimization problem over the spectraplex:\n# ```math\n# S = \\{X \\in \\mathbb{S}_+^n, Tr(X) = 1\\}\n# ```\n# with $\\mathbb{S}_+^n$ the set of positive semidefinite matrices.\n# Linear optimization with symmetric objective $D$ over the spetraplex consists in computing the\n# leading eigenvector of $D$.\n#\n# The package also exposes `UnitSpectrahedronLMO` which corresponds to the feasible set:\n# ```math\n# S_u = \\{X \\in \\mathbb{S}_+^n, Tr(X) \\leq 1\\}\n# ```\n\nusing FrankWolfe\nusing LinearAlgebra\nusing Random\nusing SparseArrays\n\n# The objective function will be the symmetric squared distance to a set of known or observed entries $Y_{ij}$ of the matrix.\n# ```math\n# f(X) = \\sum_{(i,j) \\in L} 1/2 (X_{ij} - Y_{ij})^2\n# ```\n\n# ## Setting up the input data, objective, and gradient\n\n# Dimension, number of iterations and number of known entries:\nn = 500\nk = 10000\nn_entries = 50\n\nRandom.seed!(41)\n\nconst entry_indices = unique!([minmax(rand(1:n, 2)...) for _ in 1:n_entries])\nconst entry_values = randn(length(entry_indices))\n\nfunction f(X)\n    r = zero(eltype(X))\n    for (idx, (i, j)) in enumerate(entry_indices)\n        r += 1/2 * (X[i,j] - entry_values[idx])^2\n        r += 1/2 * (X[j,i] - entry_values[idx])^2\n    end\n    return r\nend\n\nfunction grad!(storage, X)\n    storage .= 0\n    for (idx, (i, j)) in enumerate(entry_indices)\n        storage[i,j] += (X[i,j] - entry_values[idx])\n        storage[j,i] += (X[j,i] - entry_values[idx])\n    end\nend\n\n# Note that the `ensure_symmetry = false` argument to `SpectraplexLMO`.\n# It skips an additional step making the used direction symmetric.\n# It is not necessary when the gradient is a `LinearAlgebra.Symmetric` (or more rarely a `LinearAlgebra.Diagonal` or `LinearAlgebra.UniformScaling`).\n\nconst lmo = FrankWolfe.SpectraplexLMO(1.0, n, false)\nconst x0 = FrankWolfe.compute_extreme_point(lmo, spzeros(n, n))\n\ntarget_tolerance = 1e-6;\n\n#src the following two lines are used only to precompile the functions\nFrankWolfe.frank_wolfe(f, grad!, lmo, x0, max_iteration=2, line_search=FrankWolfe.MonotonousStepSize()) #src\nFrankWolfe.lazified_conditional_gradient(f, grad!, lmo, x0, max_iteration=2, line_search=FrankWolfe.MonotonousStepSize()) #src\n\n# ## Running standard and lazified Frank-Wolfe\n\nXfinal, Vfinal, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(\n    f,\n    grad!,\n    lmo,\n    x0,\n    max_iteration=k,\n    line_search=FrankWolfe.MonotonousStepSize(),\n    print_iter=k / 10,\n    emphasis=FrankWolfe.memory,\n    verbose=true,\n    trajectory=true,\n    epsilon=target_tolerance,\n)\n\nXfinal, Vfinal, primal, dual_gap, trajectory_lazy = FrankWolfe.lazified_conditional_gradient(\n    f,\n    grad!,\n    lmo,\n    x0,\n    max_iteration=k,\n    line_search=FrankWolfe.MonotonousStepSize(),\n    print_iter=k / 10,\n    emphasis=FrankWolfe.memory,\n    verbose=true,\n    trajectory=true,\n    epsilon=target_tolerance,\n)\n\n# ## Plotting the resulting trajectories\n\ndata = [trajectory, trajectory_lazy]\nlabel = [\"FW\", \"LCG\"]\nFrankWolfe.plot_trajectories(data, label, xscalelog=true)\n", "meta": {"hexsha": "75f3434b47887f288ae21eed243e8ce3a0f8fcce", "size": 3065, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/docs_6_spectrahedron.jl", "max_stars_repo_name": "gdalle/FrankWolfe.jl-2", "max_stars_repo_head_hexsha": "c3b3903c4808e24aa9e0f655aa2f8de0f2c1571c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2021-03-27T15:50:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T15:11:21.000Z", "max_issues_repo_path": "examples/docs_6_spectrahedron.jl", "max_issues_repo_name": "gdalle/FrankWolfe.jl-2", "max_issues_repo_head_hexsha": "c3b3903c4808e24aa9e0f655aa2f8de0f2c1571c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 132, "max_issues_repo_issues_event_min_datetime": "2021-03-29T18:49:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T01:33:22.000Z", "max_forks_repo_path": "docs/src/examples/6_spectrahedron.jl", "max_forks_repo_name": "dviladrich95/FrankWolfe.jl", "max_forks_repo_head_hexsha": "bcb441e52918bd1103f13296082cd7a8bc22607b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-06-02T13:38:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T10:04:42.000Z", "avg_line_length": 29.7572815534, "max_line_length": 149, "alphanum_fraction": 0.7008156607, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7670544394360348}}
{"text": "# Experimental functions for linear extensions\n\nexport linear_extension, linear_extension_empty!, all_linear_extensions, random_linear_extension\n\n\n\"\"\"\n`linear_extension(P)` returns a linear extension of the poset `P`.\n\"\"\"\nfunction linear_extension(P::SimplePoset{T}) where T\n    PP = deepcopy(P)\n    result = linear_extension_empty!(PP)\n    return result\nend\n\n\"\"\"\n`linear_extension_empty!(P)` returns a linear extension of the poset `P`,\nbut also empties the poset `P`. This is a destructive operation.\n\"\"\"\nfunction linear_extension_empty!(PP::SimplePoset{T}) where T\n    result = T[]\n    while card(PP)>0\n        M = minimals(PP)\n        append!(result, M)\n        for x in M\n            delete!(PP,x)\n        end\n    end\n    return result\nend\n\n\n\"\"\"\n`random_linear_extension(P)` generates a linear extension of `P`\nat random. This is slower than `linear_extension(P)` if one just\nwants some linear extension.\n\nNote that linear extensions are not generated uniformly\nat random by this function. Rather we proceed recursively: A\nminimal element `x` of `P` is chosen uniformly at random from among\nall minimal elements, and that becomes the first (lowest) element in\nthe linear extension. Then `x` is deleted and the same process is\nrepeated until all elements have been processed.\n\"\"\"\nfunction random_linear_extension(P::SimplePoset{T}) where T\n    result = T[]\n    PP = deepcopy(P)\n    while card(PP) > 0\n        x = rand(minimals(PP))  # choose a min el't at random\n        push!(result,x)\n        delete!(PP,x)\n    end\n    return result\nend\n\n_LX_table = Dict{SimplePoset, Set}()\nexport clear_LX_table\n\n\"\"\"\n`clear_LX_table()` releases cached results computed by\n`all_linear_extensions`.\n\"\"\"\nfunction clear_LX_table()\n    global _LX_table = Dict{SimplePoset, Set}()\n    nothing\nend\n\n\"\"\"\n`all_linear_extensions(P)` returns the `Set` of all linear extensions\nof `P`. This can take a very long time and eat up a lot of memory\n(which can be freed using `clear_LX_table`).\n\"\"\"\nfunction all_linear_extensions(P::SimplePoset)::Set\n    # see if we already have an answer\n    global _LX_table\n    if haskey(_LX_table,P)\n        return _LX_table[P]\n    end\n\n    T = eltype(P)\n    result::Set = Set{Array{T,1}}()\n    if card(P) == 0\n        return result\n    end\n    if card(P) == 1\n        L = elements(P)\n        push!(result, L)\n        return result\n    end\n\n    M = maximals(P)\n    for x in M\n        PP = deepcopy(P)\n        delete!(PP,x)\n        PP_exts = all_linear_extensions(PP)\n        for L in PP_exts\n            LL = deepcopy(L)\n            append!(LL,[x])\n            push!(result, LL)\n        end\n    end\n    _LX_table[P] = result   # save this answer\n    return result\nend\n", "meta": {"hexsha": "58173a760df7d17f728d157eb629c9fe4fc61ed6", "size": 2679, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear_extensions.jl", "max_stars_repo_name": "scheinerman/SimplePosets.jl", "max_stars_repo_head_hexsha": "deb666893935cac86770122752aa45d6e765d21c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-06-17T16:04:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T17:25:40.000Z", "max_issues_repo_path": "src/linear_extensions.jl", "max_issues_repo_name": "scheinerman/SimplePosets.jl", "max_issues_repo_head_hexsha": "deb666893935cac86770122752aa45d6e765d21c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-07-11T14:03:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-09T20:17:10.000Z", "max_forks_repo_path": "src/linear_extensions.jl", "max_forks_repo_name": "scheinerman/SimplePosets.jl", "max_forks_repo_head_hexsha": "deb666893935cac86770122752aa45d6e765d21c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-10T22:12:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T01:13:09.000Z", "avg_line_length": 25.7596153846, "max_line_length": 96, "alphanum_fraction": 0.6662933931, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.8615382165412809, "lm_q1q2_score": 0.7670225047857128}}
{"text": "\nconst cardpbk = 14012298 # Card's public key\nconst doorpbk = 74241  # Door's public key\n# Puzze input\n\nconst subjectnum = 7\n# Subject number\n\nconst transfnum = 20201227\n# Number used in the operaration that transform a subject number\n\n\n\n# The card transforms the subject number of 7 according to the card's\n# secret loop size. The result is called the card's public key (cardpbk).\n\nfunction findloopzise(pbk)\n    val = 1\n    for i ∈ 1:typemax(Int)\n        # To transform a subject number (subjectnum), start with the value 1.\n        # Then, a number of times called the loop size, perform the following steps:\n\n        val *= subjectnum\n        # 1. Set the value to itself multiplied by the subject number.\n\n        val %= transfnum\n        # 2. Set the value to the remainder after dividing the value\n        # by 20201227 (transfnum)\n\n        if val == pbk\n            # The card transforms the subject number of 7 according to\n            # the card's secret loop size. The result is called the card's public key.\n            # Then when val is equal to out public ket we found our secret loop size\n\n            return i # Secret loop size\n        end\n    end\nend\n\nfunction findencriptkey(cardpbk, doorpbk)\n    cardloopsize = findloopzise(cardpbk)\n    doorloopsize = findloopzise(doorpbk)\n\n    # You can use either device's loop size with the other device's public key\n    # to calculate the encryption key\n\n    subjectnum = doorpbk\n    encriptkey₁ = 1\n    for i ∈ 1:cardloopsize\n        # The card transforms the subject number of the door's public key\n        # according to the card's loop size. The result is the encryption key.\n\n        encriptkey₁ *= subjectnum\n        encriptkey₁ %= transfnum\n    end\n\n    subjectnum = cardpbk\n    encriptkey₂ = 1\n    for i ∈ 1:doorloopsize\n        # Transforming the subject number of cardpbk (the card's public key)\n        # with a loop size of doorloopsize produces the encryption key\n\n        encriptkey₂ *= subjectnum\n        encriptkey₂ %= transfnum\n    end\n    return encriptkey₁, encriptkey₂\nend\n\nfindencriptkey(cardpbk, doorpbk)\n", "meta": {"hexsha": "f456850b7b1f824fbbede733ff3285494ea44ec5", "size": 2086, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day25.jl", "max_stars_repo_name": "fstiffo/aoc-2020-julia", "max_stars_repo_head_hexsha": "73d40e8e5d069d0024a380c504657b3c3fe467b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day25.jl", "max_issues_repo_name": "fstiffo/aoc-2020-julia", "max_issues_repo_head_hexsha": "73d40e8e5d069d0024a380c504657b3c3fe467b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day25.jl", "max_forks_repo_name": "fstiffo/aoc-2020-julia", "max_forks_repo_head_hexsha": "73d40e8e5d069d0024a380c504657b3c3fe467b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8, "max_line_length": 86, "alphanum_fraction": 0.6768935762, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371973, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7670189519268916}}
{"text": "#' ---\r\n#' title: Getting Started with JuMP\r\n#' ---\r\n\r\n#' **Originally Contributed by**: Arpit Bhatia\r\n\r\n#' This tutorial is aimed at providing a quick introduction to writing JuMP code. It assumes familiar with basic optimization and \r\n#' the notion of an [AML](https://en.wikipedia.org/wiki/Algebraic_modeling_language).\r\n\r\n#' ## What is JuMP?\r\n#' JuMP (\"Julia for Mathematical Programming\") is an open-source modeling language that is embedded in Julia. It allows users to \r\n#' users formulate various classes of optimization problems (linear, mixed-integer, quadratic, conic quadratic, semidefinite, \r\n#' and nonlinear) with easy-to-read code. These problems can then be solved using state-of-the-art open-source and commercial solvers.\r\n#' JuMP also makes advanced optimization techniques easily accessible from a high-level language.\r\n\r\n#' ## Installing JuMP\r\n#' JuMP is a package for Julia. From Julia, JuMP is installed by using the built-in package manager.\r\n#+ tangle = false\r\n\r\nimport Pkg\r\nPkg.add(\"JuMP\")\r\n\r\n#' ## A Complete Example\r\n#' Let's try to solve the following linear programming problem by using JuMP and GLPK (a linear and mixed integer programming \r\n#' solver). We will first look at the complete code to solve the problem and then go through it step by step.\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' & \\min & 12x + 20y \\\\\r\n#' & \\;\\;\\text{s.t.} & 6x + 8y \\geq 100 \\\\\r\n#' & & 7x + 12y \\geq 120 \\\\ \r\n#' & & x \\geq 0 \\\\ \r\n#' & & y \\geq 0 \\\\ \r\n#' \\end{align*}\r\n#' $$\r\n\r\nusing JuMP\r\nusing GLPK\r\n\r\nmodel = Model(with_optimizer(GLPK.Optimizer))\r\n@variable(model, x >= 0)\r\n@variable(model, y >= 0)\r\n@constraint(model, 6x + 8y >= 100)\r\n@constraint(model, 7x + 12y >= 120)\r\n@objective(model, Min, 12x + 20y)\r\n\r\noptimize!(model)\r\n\r\n@show value(x);\r\n@show value(y);\r\n@show objective_value(model);\r\n\r\n#' ## Step by Step JuMP Code\r\n#' Once JuMP is installed, to use JuMP in your programs, we just need to write-\r\n\r\nusing JuMP\r\n\r\n#' We also need to include a Julia package which provides an appropriate solver. We want to use GLPK.Optimizer here which is \r\n#' provided by the GLPK.jl package.\r\n\r\nusing GLPK\r\n\r\n#' A model object is a container for variables, constraints, solver options, etc. Models are created with the Model() function. \r\n#' The `with_optimizer` syntax is used to specify the optimizer to be used which is GLPK in this case.\r\n\r\nmodel = Model(with_optimizer(GLPK.Optimizer));\r\n\r\n#' A variable is modelled using `@variable(name of the model object, variable name and bound, variable type)`. The bound can be a\r\n#' lower bound, an upper bound or both. If no variable type is defined, then it is treated as real. \r\n\r\n@variable(model, x >= 0)\r\n@variable(model, y >= 0);\r\n\r\n#' A constraint is modelled using `@constraint(name of the model object, constraint)`.\r\n\r\n@constraint(model, 6x + 8y >= 100)\r\n@constraint(model, 7x + 12y >= 120);\r\n\r\n#' The objective is set in a similar manner using `@objective(name of the model object, Min/Max, function to be optimized)`\r\n\r\n@objective(model, Min, 12x + 20y);\r\n\r\n#' To solve the optimization problem, we call the optimize function.\r\n\r\noptimize!(model)\r\n\r\n#' Let's now check the value of objective and variables.\r\n\r\n@show value(x);\r\n@show value(y);\r\n@show objective_value(model);", "meta": {"hexsha": "cfa197a5a411c53ab503f65167d0f6fa09b5e172", "size": 3232, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/introduction/getting_started_with_JuMP.jl", "max_stars_repo_name": "carlosal1015/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/introduction/getting_started_with_JuMP.jl", "max_issues_repo_name": "carlosal1015/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/introduction/getting_started_with_JuMP.jl", "max_forks_repo_name": "carlosal1015/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5164835165, "max_line_length": 135, "alphanum_fraction": 0.6955445545, "num_tokens": 825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951703918909, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7670189510342886}}
{"text": "\nusing Plots\nusing LinearAlgebra\n\ntheta = [pi/15, -pi/9, -pi/20] \nSigma = diagm([3.0, 1.0, 0.5]) # scale x, then y, then z\n\nRx = [1 0 0; 0 cos(theta[1]) -sin(theta[1]);  0 sin(theta[1]) cos(theta[1])] # rotate about x-axis\nRy = [cos(theta[2]) 0 sin(theta[2]); 0 1 0; -sin(theta[2]) 0 cos(theta[2])] # rotate about y-axis\nRz = [cos(theta[3]) -sin(theta[3]) 0; sin(theta[3]) cos(theta[3]) 0; 0 0 1] # rotate about z-axis\n\nX = Rz*Ry*Rx*Sigma\n\n# Plot sphere\nn = 100\nu = range(0, stop = 2pi, length = n)\nv = range(0, stop = pi, length = n)\n\nx = cos.(u) * sin.(v)'\ny = sin.(u) * sin.(v)'\nz = ones(n) * cos.(v)'\n\np1 = plot(x, y, z, legend = false)\n\nxR = zeros(n, n)\nyR = zeros(n, n)\nzR = zeros(n, n)\n\nfor i = 1:n\n    for j = 1:n\n        vecR = X*[x[i,j]; y[i,j]; z[i,j]]\n        xR[i,j] = vecR[1]\n        yR[i,j] = vecR[2]\n        zR[i,j] = vecR[3]        \n    end\nend\n\np2 = plot(xR, yR, zR, legend = false)", "meta": {"hexsha": "c0ac14560a22bbc4443a1c50510ddf4bc0015d50", "size": 900, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ddsae/CODE/CH01/CH01_SEC03_Rotation.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "ddsae/CODE/CH01/CH01_SEC03_Rotation.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "ddsae/CODE/CH01/CH01_SEC03_Rotation.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 23.6842105263, "max_line_length": 98, "alphanum_fraction": 0.53, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517028006208, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.767018938608592}}
{"text": "using LinearAlgebra\nusing Makie\n\nμ1 = μ2 = 0.0\n\n𝛍 = [\n    μ1\n    μ2\n]\n\nσ11 = σ22 = 1.0\nσ12 = σ21 = 0.0\n\nΣ = [\n    σ11 σ12\n    σ21 σ22\n]\n\nfunction 𝒩(x1, x2; 𝛍 = 𝛍, Σ = Σ)\n    𝐱 = [x1, x2]\n    Λ = inv(Σ)\n    D = length(𝛍)\n    return √(det(Λ)) * exp(-0.5 * (𝐱 .- 𝛍)' * Λ * (𝐱 .- 𝛍)) / √(2π)^D\nend\n\nx1min, x1max = -1.0, 1.0\nx2min, x2max = -1.0, 1.0\nx1 = range(x1min, x1max, length = 50)\nx2 = range(x2min, x2max, length = 50)\nz = 𝒩.(x1', x2)\nwireframe(x1, x2, z, colormap = :Spectral)\n", "meta": {"hexsha": "abf0088f064b5d61d67c71fa5a09034c931d2b46", "size": 480, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "makieExer/multivariateGaussian/multivariate.jl", "max_stars_repo_name": "terasakisatoshi/juliaExer", "max_stars_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-02T01:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-04T12:03:25.000Z", "max_issues_repo_path": "makieExer/multivariateGaussian/multivariate.jl", "max_issues_repo_name": "terasakisatoshi/juliaExer", "max_issues_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "makieExer/multivariateGaussian/multivariate.jl", "max_forks_repo_name": "terasakisatoshi/juliaExer", "max_forks_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.0, "max_line_length": 69, "alphanum_fraction": 0.50625, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399069145609, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.767004069981448}}
{"text": "\n### TRIANGLE\narea(v1::SVector{3,T}, v2::SVector{3,T}, v3::SVector{3,T}) where {T} = norm(vector_area(v1, v2, v3))\ncentroid(v1::SVector{3,T}, v2::SVector{3,T}, v3::SVector{3,T}) where {T} = (v1 + v2 + v3) * Float64(1/3)  # 4 times faster than dividing by 3\nvector_area(v1::SVector{3,T}, v2::SVector{3,T}, v3::SVector{3,T}) where {T} = cross(v2 - v1, v3 - v2) * 0.5\nfunction triangle_area(v123::NTuple{3,SVector{3,T}}, n̂::SVector{3,T}) where {T}\n\tvec_area = vector_area(v123[1], v123[2], v123[3])\n\treturn dot(n̂, vec_area)\nend\ntriangleNormal(v1::SVector{3,T}, v2::SVector{3,T}, v3::SVector{3,T}) where {T} = normalize(vector_area(v1, v2, v3))\n\nfor funName in (:area, :centroid, :triangleNormal, :triangleCross)\n    @eval begin\n        function $funName(sv::SVector{3,SVector{3,T}}) where {T}\n            return $funName(sv[1], sv[2], sv[3])\n        end\n    end\nend\n\n### TETRAHEDRON\nfunction centroid(v1::SVector{3,T}, v2::SVector{3,T}, v3::SVector{3,T}, v4::SVector{3,T}) where {T}\n    return (v1 + v2 + v3 + v4) * 0.25\nend\n\nfunction volume(v1::SVector{3,T}, v2::SVector{3,T}, v3::SVector{3,T}, v4::SVector{3,T}) where {T}\n    # NOTE: This is an algebraic refactorization of a symbolic answer\n    a1, a2, a3 = v1[1], v1[2], v1[3]\n    b1, b2, b3 = v2[1], v2[2], v2[3]\n    c1, c2, c3 = v3[1], v3[2], v3[3]\n    d1, d2, d3 = v4[1], v4[2], v4[3]\n    V =       (b1 - a1) * (c2 * d3 - c3 * d2)\n    V = muladd(b2 - a2,    c3 * d1 - c1 * d3, V)\n    V = muladd(b3 - a3,    c1 * d2 - c2 * d1, V)\n    V = muladd(c1 - d1,    a3 * b2 - a2 * b3, V)\n    V = muladd(c2 - d2,    a1 * b3 - a3 * b1, V)\n    V = muladd(c3 - d3,    a2 * b1 - a1 * b2, V)\n    return V * Float64(1/6)\nend\n\nfor funName in (:centroid, :volume)\n    @eval begin\n        function $funName(sv::SVector{4,SVector{3,T}}) where {T}\n            return $funName(sv[1], sv[2], sv[3], sv[4])\n        end\n    end\nend\n", "meta": {"hexsha": "5baf1fe44361bd90131d7b446552191652b392a0", "size": 1862, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math_kernel/geometry_kernel.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PressureFieldContact.jl-1a2887a7-38b6-5ebe-8978-3a02049ebf6f", "max_stars_repo_head_hexsha": "55d7b6f85771465de112171c609ba529f852ddef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-06-24T23:58:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:36.000Z", "max_issues_repo_path": "src/geometry_kernel.jl", "max_issues_repo_name": "ryanelandt/NumericalTricks.jl", "max_issues_repo_head_hexsha": "20906108074238fb720abdb2831bb6287b6777ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-05-05T02:48:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T16:22:45.000Z", "max_forks_repo_path": "src/geometry_kernel.jl", "max_forks_repo_name": "ryanelandt/NumericalTricks.jl", "max_forks_repo_head_hexsha": "20906108074238fb720abdb2831bb6287b6777ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:29:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T07:51:13.000Z", "avg_line_length": 39.6170212766, "max_line_length": 141, "alphanum_fraction": 0.5708915145, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813394, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7669926862097091}}
{"text": "using Plots\n\n\n\nmax_n = 30\nn_arr = collect(5:max_n)\nprobs = []\nprobs_corner = []\nprobs_line = []\n\nfor n in n_arr\n    N_m = n^2 - 4*(n-1)\n    prob = N_m / n^2 * (N_m-1) / (n^2 - 1)\n    push!(probs, prob)\n\n    # Prob at least one node is a corner node\n    prob_corner = 4/n^2 + (n^2 - 4)/(n^2) * (4/(n^2-1))\n    push!(probs_corner, prob_corner)\n\n    # Prob that users end on same row or column\n    prob_line = 2*(n-1)/(n^2 - 1)\n    push!(probs_line, prob_line)\nend\n\nplot(n_arr, 1 .- probs, label=\"probs not middle\")\nplot!(n_arr, probs_corner, label=\"probs corner\")\nplot!(n_arr, probs_line, label=\"probs line\")\n", "meta": {"hexsha": "0c0af75b7cd6a888df1fd6e9f4ca08a6f67ed751", "size": 607, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scrap/prob_of_userpair_in_middle.jl", "max_stars_repo_name": "FalafelGood/QuNet", "max_stars_repo_head_hexsha": "4be1b0c9b61cccdbc30d25c9cc491854d9626bcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scrap/prob_of_userpair_in_middle.jl", "max_issues_repo_name": "FalafelGood/QuNet", "max_issues_repo_head_hexsha": "4be1b0c9b61cccdbc30d25c9cc491854d9626bcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scrap/prob_of_userpair_in_middle.jl", "max_forks_repo_name": "FalafelGood/QuNet", "max_forks_repo_head_hexsha": "4be1b0c9b61cccdbc30d25c9cc491854d9626bcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6785714286, "max_line_length": 55, "alphanum_fraction": 0.607907743, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813392, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.766992686209709}}
{"text": "# Statistical model for analyzing Radial Velocity observations\r\n# Assumes existance of data in arrays times, obs, sigma_obs\r\n# Assumes existance of functions: loglikelihood(theta), logprior_noise(theta), and is_valid_noise(theta)\r\n\r\nexport logprior_planets, logprior, logtarget, negative_logtarget\r\nexport set_times, set_obs, set_sigma_obs, num_noise_param\r\n\r\n# Observational data to compare model to\r\nglobal times # ::Array{Float64,1}\r\nglobal obs # ::Array{Float64,1}\r\nglobal sigma_obs #::Array{Float64,1}\r\n\r\n# Functions to set global data within module\r\nfunction set_times(t::Array{Float64,1}) global times = t   end\r\nfunction set_obs(o::Array{Float64,1})  global obs = o   end\r\nfunction set_sigma_obs(so::Array{Float64,1}) global sigma_obs = so  end\r\n\r\nfunction is_valid(p::Vector)\r\n   is_valid_noise(p) && is_valid_planets(p)\r\nend\r\n\r\nfunction logprior_period(P::Real)\r\n  const min_period = 1.0\r\n  const max_period = 10000.0\r\n  const norm = -log(max_period/min_period)\r\n  if !(min_period<=P<=max_period)\r\n     return -Inf\r\n  end\r\n  return norm-log(P)\r\nend\r\n\r\nfunction logprior_amplitude(K::Real)\r\n  const min_K = 0.0\r\n  const max_K = 999.0\r\n  const K0 = 1.0\r\n  const norm = -log(K0*log1p(maxK/min_K))\r\n  if !(min_K<=K<=max_K)\r\n     return -Inf\r\n  end\r\n  return norm-log1p(K/K0)\r\nend\r\n\r\nfunction logprior_planets(p::Vector) \r\n  if !is_valid_planets(p) return -Inf end  # prempt model evaluation\r\n  num_pl = num_planets(p)\r\n  logp = zero(eltype(p))\r\n  if num_pl <= 0 return logp end\r\n  if num_param_per_planet == 3\r\n     logp -= num_pl*log(2pi)\r\n  elseif num_param_per_planet == 5\r\n     logp -= 2*num_pl*log(2pi)\r\n  end\r\n  for plid in 1:num_pl\r\n    P::eltype(p) = extract_period(p,plid=plid)\r\n    K::eltype(p) = extract_amplitude(p,plid=plid)\r\n    logp += logprior_period(P) + logprior_amplitude(K)\r\n  end\r\n  return logp::eltype(p)\r\nend\r\n\r\nfunction logprior_offset(C::Real)\r\n  const max_C = 1000.0\r\n  if !(-max_C<=C<=max_C) \r\n     return -Inf\r\n  end\r\n  return -log(2*max_C)\r\nend\r\n\r\nlogprior_offset(p::Vector) = logprior_offset(extract_rvoffset(p))\r\n\r\nfunction logprior(p::Vector) \r\n  logprior_noise(p) + logprior_offset(p) + logprior_planets(p) \r\nend\r\n\r\nfunction logtarget(p::Vector)\r\n  val = logprior(p)\r\n  if val==-Inf\r\n     return val\r\n  end\r\n  val += loglikelihood(p)\r\n  return val\r\nend\r\n\r\nnegative_logtarget(p::Vector) = -logtarget(p)\r\n\r\n\r\n\r\n", "meta": {"hexsha": "cb9a8e487a52bb4aa65ceb9552c8a7bea2d35486", "size": 2348, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stat_model.jl", "max_stars_repo_name": "eford/EPRV3EvidenceChallenge-Ford", "max_stars_repo_head_hexsha": "3db85bd84c1b6aae3a56825b1de94c2b061aa789", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stat_model.jl", "max_issues_repo_name": "eford/EPRV3EvidenceChallenge-Ford", "max_issues_repo_head_hexsha": "3db85bd84c1b6aae3a56825b1de94c2b061aa789", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stat_model.jl", "max_forks_repo_name": "eford/EPRV3EvidenceChallenge-Ford", "max_forks_repo_head_hexsha": "3db85bd84c1b6aae3a56825b1de94c2b061aa789", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6818181818, "max_line_length": 105, "alphanum_fraction": 0.6942078365, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122672782973, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.766992682007705}}
{"text": "using JuMP, Ipopt, Plots, LinearAlgebra, SparseArrays\r\n\r\n#A JuMP model is initialized\r\nmod = Model(optimizer_with_attributes( Ipopt.Optimizer ,  \"max_iter\" => 100,\r\n            \"mumps_mem_percent\" => 500))\r\n\r\n#The parameters of the 1-D rod\r\nL = 0.1                                 #Length of rod\r\nλ = 45.0                                # Conductivity\r\nc = 460.0                               # Specific heat capacitivity\r\nρ = 7800.0                              # Material density\r\nα = λ / (c*ρ)                           # Diffusivity\r\n\r\n#Number of spatial discretization points and length of each\r\nN = 11                                 #Discretization points / nodes\r\nΔx = L / (N-1)                         # Δx = x[i+1] - x[i]\r\n\r\n#Integration from t0 = 0 to tf\r\ntf = 10000.0;                          #Final time\r\nΔt = 10^(-1);                          #Sampling period\r\nk = round(Int,tf / Δt);                #k = number of steps\r\n\r\n#System's matrix: θ' = Aθ + Bu\r\nA = spdiagm(-1 => ones( N-1), 0 => -2*ones(N), 1 => ones(N-1));\r\nA[2,1] = 2.0;\r\nA[end - 1,end] = 2.0;\r\nA = (α/( Δx^2)) * A;\r\n\r\n#input matrix\r\nB = spzeros(N);\r\nB[1] = 1;\r\nB = (2/ (c * ρ * Δx)) * B;\r\n\r\n#output matrix\r\nC = spzeros(1,N)\r\nC[1,end] = 1.0;\r\n\r\n#Initial and reference temperatures in kelvin\r\nθinit = 273.0\r\nθref = 500.0\r\n#bounded input values[u_min,u_max]\r\nu_min = 0.0\r\nu_max = 15000.0\r\n\r\n#Decision variables of the optimization problem\r\n@variable(mod,θ[1:N,1:k]);                              # temperature at x[1:N] at time step k\r\n@variable(mod,u_min <= u[1:k - 1] <= u_max);            # bounded constrained Input u\r\n@variable(mod, y[1:k]);                                 # Output y\r\n#Initial values\r\n@constraint(mod, θ[:,1] .== θinit)\r\n@constraint(mod, y[1] .== θinit)\r\n#System dynamics\r\nfor j in 1:k - 1,i in 1:N\r\n    @constraint(mod,θ[i,j + 1] - (θ[i,j] + Δt * ((A[:,i]' * θ[:,j]) + B[i] * u[j])).== 0.0)\r\nend\r\n\r\nfor j in 1:k - 1\r\n    @constraint(mod,y[j + 1] .== (C * θ[:,j + 1]))\r\nend\r\n#Weighing matrices\r\nQ = C' * C * 1000.0;\r\nR = 0.0001;\r\n\r\n#err = sum(e' Q e)\r\nerr= @NLexpression(mod,(sum(Q[i,i] * (θref - θ[i,j]) ^ 2\r\n                        for j in 1:k-1,i in 1:N)))\r\n#in_err = sum(u'Ru)\r\nin_err = @NLexpression(mod,(sum(R * u[j] ^ 2 for j in 1:k-1)))\r\n\r\nJ = @NLexpression(mod,0.5 * Δt * (err + in_err))\r\n#defining the cost function\r\n@NLobjective(mod, Min, J)\r\n#optimizes the model\r\noptimize!(mod)\r\n\r\n#plotting values\r\nstates_θstart = zeros(k)\r\nstates_θend = zeros(k)\r\ninput_u = zeros(k - 1)\r\nfor i = 1 : k-1\r\n    states_θstart[i] = JuMP.value(θ[1,i])\r\n    states_θend[i] = JuMP.value(θ[end,i])\r\n    input_u[i] = JuMP.value(u[i])\r\nend\r\n\r\nstates_θend[end] = JuMP.value(θ[end,end])\r\nstates_θstart[end] = JuMP.value(θ[1,end])\r\n\r\nplot(states_θstart,label = \"θ1\")\r\nplot!(states_θend,label=\"y = Cθ\")\r\nsavefig(\"lq-optimal_1D_Q1000_R0001_output-bounded.png\")\r\np3 = plot(input_u,label=\"input,Q = 1000,R = 0.001\")\r\nsavefig(\"lq-optimal_1D_Q1000_R0001-input-bounded.png\")\r\n", "meta": {"hexsha": "783e2b52f5778528177dd3cabcec6215a71f9cec", "size": 2955, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lq-OCP_heat_1D.jl", "max_stars_repo_name": "jayborkhatariya17/Optimal-boundary-control-of-the-heat-equation", "max_stars_repo_head_hexsha": "a820be2b0d175f1c4bc7093753f0dd591888f668", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lq-OCP_heat_1D.jl", "max_issues_repo_name": "jayborkhatariya17/Optimal-boundary-control-of-the-heat-equation", "max_issues_repo_head_hexsha": "a820be2b0d175f1c4bc7093753f0dd591888f668", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lq-OCP_heat_1D.jl", "max_forks_repo_name": "jayborkhatariya17/Optimal-boundary-control-of-the-heat-equation", "max_forks_repo_head_hexsha": "a820be2b0d175f1c4bc7093753f0dd591888f668", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-21T10:00:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-17T12:51:52.000Z", "avg_line_length": 31.4361702128, "max_line_length": 95, "alphanum_fraction": 0.5346869712, "num_tokens": 1003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.938124016006303, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7669862572458466}}
{"text": "# Michelle Medina\n# Finite Differencing\n# DATE\n\nexport Params, Params2D\nexport dX, dX_2D, dY_2D, functionOnGrid, Deriv1D, DerivX_2D, DerivY_2D\n\nstruct Params\n#structure contains # of points N and Domain Space L\n    N::Int\n    L::Float64\nend\n\nstruct Params2D\n    #contains number of points Nx and Ny and the length of the \n    #2D grid Lx and Ly\n    Nx::Int\n    Ny::Int\n    Lx::Float64\n    Ly::Float64\nend\n\n# Defining the Grid Space\n\"\"\" computing grid space h \"\"\"\nfunction dX(grid::Params)\n    return (grid.L/(grid.N-1))\nend\n\n\"\"\" computing grid space hx \"\"\"\nfunction dX_2D(grid::Params2D)\n    return (grid.Lx/(grid.Nx-1))\nend\n\n\"\"\" computing grid space hy \"\"\"\nfunction dY_2D(grid::Params2D)\n    #computes grid space hy\n    return (grid.Ly/(grid.Ny-1))\nend\n\n\"\"\" 1D Function is computed on the grid \"\"\"\nfunction functionOnGrid(u::Function, grid::Params)::Array{Float64,1}\n    ux=zeros(grid.N)\n    h=dX(grid)\n    for i in 1:grid.N\n        x=(i-1)*h\n        ux[i]=u(x)\n    end\n    return ux\nend\n\n\"\"\" 2D Function is computed on the grid \"\"\"\nfunction functionOnGrid(u::Function, grid::Params2D)::Array{Float64,2}\n    uxy=zeros(grid.Nx,grid.Ny)\n    hx=dX_2D(grid)\n    hy=dY_2D(grid)\n    for i in 1:grid.Nx, j in 1:grid.Ny\n        x = (i-1)*hx\n        y= (j-1)*hy\n        uxy[i,j]=u(x,y)\n    end\n    return uxy\nend\n\n\"\"\" Derivative of a function is computed on a 1D grid \"\"\"\nfunction Deriv1D(u::Array{Float64,1},grid::Params)::Array{Float64}\n    dudx = zeros(grid.N)\n    h = dX(grid)\n    for i in 1:grid.N\n        if i == 1\n            dudx[i] = (u[i+1] - u[i])/h\n        elseif i == grid.N\n            dudx[i] = (u[i]-u[i-1])/h\n        else\n            dudx[i] = (u[i+1]-u[i-1])/2h\n        end\n    end\n    return dudx\nend\n\nfunction DerivX_2D(u::Array{Float64,2}, grid::Params2D)::Array{Float64}\n    dudx= zeros(grid.Nx,grid.Ny)\n    hx = dX_2D(grid)\n\n    for i in 1:grid.Nx, j in 1:grid.Ny\n        if i==1\n            dudx[i,j] = (u[i+1,j] - u[i,j])/hx\n        elseif i==grid.Nx\n            dudx[i,j] = (u[i,j] - u[i-1,j])/hx\n        else\n            dudx[i,j] = (u[i+1,j]-u[i-1,j])/2hx\n        end\n    end\n    return dudx\nend\n\nfunction DerivY_2D(u::Array{Float64,2},grid::Params2D)::Array{Float64}\n    dudy= zeros(grid.Nx,grid.Ny)\n    hy = dY_2D(grid)\n\n    for i in 1:grid.Nx, j in 1:grid.Ny\n        if j == 1\n            dudy[i,j] = (u[i,j+1] - u[i,j])/hy\n        elseif j== grid.Ny\n            dudy[i,j] = (u[i,j]-u[i,j-1])/hy\n        else\n            dudy[i,j] = (u[i,j+1]-u[i,j-1])/2hy\n        end\n    end\n    return dudy\nend\n\n\n\n\n\n", "meta": {"hexsha": "808d735a125ed2cfbd42e24ee43915dd450002cc", "size": 2525, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FiniteDifferencing.jl", "max_stars_repo_name": "mmedina002/SparseGrids", "max_stars_repo_head_hexsha": "1662ebcb54f0ffbf6ccf3b5084192bd7b9ab5343", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-30T17:55:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-12T16:25:00.000Z", "max_issues_repo_path": "src/FiniteDifferencing.jl", "max_issues_repo_name": "mmedina002/SparseGrids", "max_issues_repo_head_hexsha": "1662ebcb54f0ffbf6ccf3b5084192bd7b9ab5343", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FiniteDifferencing.jl", "max_forks_repo_name": "mmedina002/SparseGrids", "max_forks_repo_head_hexsha": "1662ebcb54f0ffbf6ccf3b5084192bd7b9ab5343", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-07T15:43:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-07T15:43:21.000Z", "avg_line_length": 21.7672413793, "max_line_length": 71, "alphanum_fraction": 0.5659405941, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164656, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7669862530027679}}
{"text": "\nusing CSV, JuMP, MathProgBase, Gurobi, Random, LinearAlgebra, StatsBase, Distributions, Plots, BenchmarkTools, Suppressor\n\n# Formulate optimization problem for Ordinary Least Squares Regression\n\nfunction OrdinaryLeastSquares(x,y)\n#     OLS_model = Model(solver = GurobiSolver(LogFile = append_name,OutputFlag = 0))\n    OLS_model = Model(solver = GurobiSolver(OutputFlag = 0))\n    \n    # Define variables\n    n = size(x,1) # observations\n    p = size(x,2) # features\n    \n    # Define decision variables\n    @variable(OLS_model, β[1:p+1])\n\n    # Define constraints - none\n\n    # Define objective function\n    @objective(OLS_model, Min, sum((y[i] - β[1] - β[2:p+1]' * x[i,:])^2 for i = 1:n))\n#     return(OLS_model)\n    \n    # Run the optimization\n    solve(OLS_model)\n    betas = getvalue(β)\n    objective = getobjectivevalue(OLS_model)\n    return(betas)\nend\n\n# Formulate optimization problem for Least Quantile Squares Regression\n# *********** q: 0, 1, 2, 3, 4\n\nfunction LeastQuantileSquares(x,y,quantile)\n    LQS_model = Model(solver = GurobiSolver(OutputFlag = 0,TimeLimit = 180))\n#     LQS_model = Model(solver = GurobiSolver(OutputFlag = 0))\n    \n    # Define variables\n    M = 10000\n    n = size(x,1) # observations\n    p = size(x,2) # features\n    q = ceil(n*(quantile/4))\n    \n    # Define decision variables\n    @variable(LQS_model, γ)\n    @variable(LQS_model, z[1:n], Bin)\n    @variable(LQS_model, μ[1:n])\n    @variable(LQS_model, β[1:p+1])\n    @variable(LQS_model, r[1:n])\n    @variable(LQS_model, a[1:n])            \n            \n    # Define constraints\n    @constraint(LQS_model, [i=1:n], r[i] == y[i] - β[1] - β[2:p+1]'*x[i,:])\n    @constraint(LQS_model, [i=1:n], γ >= a[i] - μ[i])\n    @constraint(LQS_model, [i=1:n], a[i] >= r[i])\n    @constraint(LQS_model, [i=1:n], a[i] >= -r[i])\n    @constraint(LQS_model, [i=1:n], μ[i] <= M*(1 - z[i]))\n    @constraint(LQS_model, sum(z[i] for i=1:n) == q)\n    @constraint(LQS_model, [i=1:n], μ[i] >= 0)\n    \n     # Define objective function\n    @objective(LQS_model, Min, γ)\n#     return(LQS_model)\n\n    # Run the optimization\n    solve(LQS_model)\n    betas = getvalue(β)\n    qth_residual = getvalue(γ)\n    return(betas,qth_residual)\nend\n\n# Formulate optimization problem for Least Trimmed Squares Regression\n# Note: k is a user specified parameter, k <= (n - p - 1)/2\n\nfunction LeastTrimmedSquares(k,x,y)\n    LTS_model = Model(solver = GurobiSolver(OutputFlag = 0,TimeLimit = 500))\n    \n    # Define variables\n    M = 10000\n    n = size(x,1) # observations\n    p = size(x,2) # features\n    \n    # Define decision variables\n    @variable(LTS_model, z[1:n], Bin)\n    @variable(LTS_model, β[1:p+1])\n    @variable(LTS_model, r[1:n])\n            \n    # Define constraints\n    @constraint(LTS_model, [i=1:n], β[1] + β[2:p+1]'*x[i,:] - y[i] <= r[i] + M*z[i])\n    @constraint(LTS_model, [i=1:n], -β[1] - β[2:p+1]'*x[i,:] + y[i] <= r[i] + M*z[i])\n    @constraint(LTS_model, sum(z[i] for i=1:n) <= k)\n    @constraint(LTS_model, [i=1:n], r[i] >= 0)\n        \n    # Define objective function as QMIP ******** (minimizing over β, z)\n    @objective(LTS_model, Min, sum(r[i]^2 for i=1:n))\n#     return(LTS_model)\n\n    # Run the optimization\n    solve(LTS_model)\n    betas = getvalue(β)\n    outlier_indicators = getvalue(z)\n    return(betas, outlier_indicators)\nend\n\n# Formulate optimization problem for Least Trimmed Squares Regression\n# Note: k is a user specified parameter, k <= (n - p - 1)/2\n\nfunction LeastTrimmedSumResiduals(k,x,y)\n    LTSR_model = Model(solver = GurobiSolver(OutputFlag = 0,TimeLimit = 500))\n    \n    # Define variables\n    M = 10000\n    n = size(x,1) # observations\n    p = size(x,2) # features\n    \n    # Define decision variables\n    @variable(LTSR_model, z[1:n], Bin)\n    @variable(LTSR_model, β[1:p+1])\n    @variable(LTSR_model, r[1:n])\n            \n    # Define constraints\n    @constraint(LTSR_model, [i=1:n], β[1] + β[2:p+1]'*x[i,:] - y[i] <= r[i] + M*z[i])\n    @constraint(LTSR_model, [i=1:n], -β[1] - β[2:p+1]'*x[i,:] + y[i] <= r[i] + M*z[i])\n    @constraint(LTSR_model, sum(z[i] for i=1:n) <= k)\n    @constraint(LTSR_model, [i=1:n], r[i] >= 0)\n        \n    # Define objective function as QMIP ******** (minimizing over β, z)\n    @objective(LTSR_model, Min, sum(r[i] for i=1:n))\n#     return(LTS_model)\n\n    # Run the optimization\n    solve(LTSR_model)\n    betas = getvalue(β)\n    outlier_indicators = getvalue(z)\n    return(betas, outlier_indicators)\nend\n\n# Formulate optimization problem for Least Trimmed Squares Regression\n# Note: k is a user specified parameter, k <= (n - p - 1)/2\n\nfunction BoundedInfluence(α,x,y)\n    BI_model = Model(solver = GurobiSolver(OutputFlag = 0,TimeLimit = 500))\n    \n    # Define variables\n    M = 10000\n    n = size(x,1) # observations\n    p = size(x,2) # features\n    bkdn = ceil((n-p-1)/2)\n    \n    # Define parameters\n    x_int = hcat(ones(n),x)\n    β_ols = (x_int'*x_int)^-1*x_int'*y\n    e_residuals = y-x_int*β_ols\n    σ_squared = e_residuals'*e_residuals/(n-p+1)\n    H = x*(x'*x)^-1*x'\n    h = diag(H)\n    δ = ((e_residuals).^2/(σ_squared*(1 .- h)))*(1/(p+1))*(h./(1 .- h))\n    σ_h = (e_residuals./(1 .- h).^0.5)\n    σ_h_squared = (e_residuals./(1 .- h).^0.5).^2\n#     println(δ)\n    \n    # Define decision variables\n    @variable(BI_model, z[1:n], Bin)\n    @variable(BI_model, β[1:p+1])\n    @variable(BI_model, r[1:n])\n            \n    # Define constraints\n    @constraint(BI_model, [i=1:n], β[1] + β[2:p+1]'*x[i,:] - y[i] <= r[i] + M*z[i])\n    @constraint(BI_model, [i=1:n], -β[1] - β[2:p+1]'*x[i,:] + y[i] <= r[i] + M*z[i])\n    @constraint(BI_model, sum(z[i] for i=1:n) <= bkdn)\n    @constraint(BI_model, [i=1:n], r[i] >= 0)\n        \n    # Define objective function        \n    @objective(BI_model, Min, α*sum(r[i]^2 + z[i]*δ[i]^2 for i=1:n) + (1-α)*sum(z[i] for i=1:n))\n    \n    # Run the optimization\n    solve(BI_model)\n    betas = getvalue(β)\n    outlier_indicators = getvalue(z)\n    return(h, betas, outlier_indicators)\nend\n\nstar_data =  [  1  4.37  5.23   \n                2  4.56  5.74   \n                3  4.26  4.93\n                4  4.56  5.74   \n                5  4.30  5.19   \n                6  4.46  5.46\n                7  3.84  4.65   \n                8  4.57  5.27   \n                9  4.26  5.57\n                10  4.37  5.12  \n                11  3.49  5.73  \n                12  4.43  5.45\n                13  4.48  5.42  \n                14  4.01  4.05  \n                15  4.29  4.26\n                16  4.42  4.58  \n                17  4.23  3.94  \n                18  4.42  4.18\n                19  4.23  4.18  \n                20  3.49  5.89  \n                21  4.29  4.38\n                22  4.29  4.22  \n                23  4.42  4.42  \n                24  4.49  4.85\n                25  4.38  5.02\n                26  4.42  4.66 \n                27  4.29  4.66\n                28  4.38  4.90  \n                29  4.22  4.39  \n                30  3.48  6.05\n                31  4.38  4.42  \n                32  4.56  5.10\n                33  4.45  5.22\n                34  3.49  6.29  \n                35  4.23  4.34  \n                36  4.62  5.62\n                37  4.53  5.10  \n                38  4.45  5.22  \n                39  4.53  5.18\n                40  4.43  5.57  \n                41  4.38  4.62  \n                42  4.45  5.06\n                43  4.50  5.34  \n                44  4.45  5.34  \n                45  4.55  5.54\n                46  4.45  4.98  \n                47  4.42  4.50 ]; \n\nx_star_data = star_data[:,2]\ny_star_data = star_data[:,3];\n\nstar_betas_OLS = OrdinaryLeastSquares(x_star_data,y_star_data)\n\nstar_betas_LQS, star_qth_resid_LQS = LeastQuantileSquares(x_star_data,y_star_data,2)\n\nstar_betas_LTS, star_outlier_indicators_LTS = LeastTrimmedSquares(4,x_star_data,y_star_data)\n\nfindall(x->x==1, star_outlier_indicators_LTS)\n\nstar_betas_LTSR, star_outlier_indicators_LTSR = LeastTrimmedSumResiduals(4,x_star_data,y_star_data)\n\nfindall(x->x==1, star_outlier_indicators_LTSR)\n\nh_star, star_betas_BI, star_outlier_indicators_BI = BoundedInfluence(0.4,x_star_data,y_star_data)\n\nfindall(x->x==1, star_outlier_indicators_BI)\n\n# Plot all the fits\n# gr()\nstar_data_plot = scatter(x_star_data,y_star_data,series_annotations = text.(1:47, :bottom),\n#     title=\"Fitted Regressions on Hertzsprung-Russell Star Data\",\n    label=\"\",\n    legend=:outerbottom,\n    markersize = 2,\n    markercolor = :black,\n    dpi=300,\n    fontfamily=\"Times\",\n    size = (600, 500))\n\nf_ols(x_ols) = star_betas_OLS[1] + x_ols.*star_betas_OLS[2]\nplot!(f_ols, 3.5, 5,label=\"Ordinary Least Squares\")\n\nf_lqs(x_lqs) = star_betas_LQS[1] + x_lqs.*star_betas_LQS[2]\nplot!(f_lqs, 3.5, 5,label=\"Least Median Squares\")\n\nf_lts(x_lts) = star_betas_LTS[1] + x_lts.*star_betas_LTS[2]\nplot!(f_lts, 3.5, 5,label=\"Least Trimmed Squares\")\n\nf_ltsr(x_ltsr) = star_betas_LTSR[1] + x_ltsr.*star_betas_LTSR[2]\nplot!(f_ltsr, 3.5, 5,label=\"Least Trimmed Summed Residuals\")\n\nf_bi(x_bi) = star_betas_BI[1] + x_bi.*star_betas_BI[2]\nplot!(f_bi, 3.5, 5,label=\"Bounded Influence Least Squares\")\n\nsavefig(\"star_data_plot2\")\n\nstar_data_plot2\n\nstack_loss = [ 1  80  27  89  42\n               1  80  27  88  37\n               1  75  25  90  37\n               1  62  24  87  28\n               1  62  22  87  18\n               1  62  23  87  18\n               1  62  24  93  19\n               1  62  24  93  20\n               1  58  23  87  15\n               1  58  18  80  14\n               1  58  18  89  14\n               1  58  17  88  13\n               1  58  18  82  11\n               1  58  19  93  12\n               1  50  18  89   8\n               1  50  18  86   7\n               1  50  19  72   8\n               1  50  19  79   8\n               1  50  20  80   9\n               1  56  20  82  15\n               1  70  20  91  15 ];\n\nx_stack_loss = stack_loss[:,2:4];\n\ny_stack_loss = stack_loss[:,5];\n\nstack_loss_betas_OLS = OrdinaryLeastSquares(x_stack_loss,y_stack_loss)\n\nstack_loss_betas_LQS, stack_loss_qth_resid_LQS = LeastQuantileSquares(x_stack_loss,y_stack_loss,2)\n\nstack_loss_betas_LTS, stack_loss_outlier_indicators_LTS = LeastTrimmedSquares(4,x_stack_loss,y_stack_loss)\n\nindex = findall(x->x==1, stack_loss_outlier_indicators_LTS)\n\nstack_loss_betas_LTSR, stack_loss_outlier_indicators_LTSR = LeastTrimmedSumResiduals(4,x_stack_loss,y_stack_loss)\n\nfindall(x->x==1, stack_loss_outlier_indicators_LTSR)\n\nh_stack_loss, stack_loss_betas_BI, stack_loss_outlier_indicators_BI = BoundedInfluence(0.1,x_stack_loss,y_stack_loss)\n\nfindall(x->x==1, stack_loss_outlier_indicators_BI)\n\nh_stack_loss\n\nfunction standardize(df)\n    n, p = size(df)\n    for j in 1:p\n        mean1 = mean(df[:,j])\n        std1 = std(df[:,j])\n        for i in 1:n\n            df[i,j] = (df[i,j] - mean1)/std1\n        end\n    end\n    return df\nend\n\ndf1 = CSV.read(\"sds0.csv\", header=false);\n\ny1 = df1[:,1]\nX1 = convert(Matrix, df1[:,2:end]);\n\nsize(X1)\n\nt_OLS_df1 = @suppress @benchmark df1_betas_OLS = OrdinaryLeastSquares(X1,y1)\n\ntime(median(t_OLS_df1))/1000000000\n\nt_LQS_df1 = @suppress @benchmark LeastQuantileSquares(X1,y1,2) \n\ntime(median(t_LQS_df1))/1000000000\n\nt_LTS_df1 = @suppress @benchmark df1_LTS_betas, df1_LTS_outlier_indicators = LeastTrimmedSquares(0,X1,y1)\n\ntime(median(t_LTS_df1))/1000000000\n\nt_LTSR_df1 = @suppress @benchmark df1_LTSR_betas, df1_LTSR_outlier_indicators = LeastTrimmedSumResiduals(0,X1,y1)\n\ntime(median(t_LTSR_df1))/1000000000\n\ndf1_betas_OLS = OrdinaryLeastSquares(X1,y1)\n\ndf1_LQS_betas, df1_LQS_qth_resid = LeastQuantileSquares(X1,y1,2)\n\ndf1_LTS_betas, df1_LTS_outlier_indicators = LeastTrimmedSquares(0,X1,y1)\n\ndf1_LTSR_betas, df1_LTSR_outlier_indicators = LeastTrimmedSumResiduals(0,X1,y1)\n\ndf1_BI_betas, df1_BI_outlier_indicators = BoundedInfluence(0.00001,X1,y1)\n\ndf2 = CSV.read(\"sds1.csv\", header=false);\n\ny2 = df2[:,1]\nX2 = convert(Matrix, df2[:,2:end]);\n\nsize(X2)\n\nsum(X2)\n\nmean(X2)\n\nt_OLS_df2 = @suppress @benchmark df2_betas_OLS = OrdinaryLeastSquares(X2,y2)\n\ntime(median(t_OLS_df2))/1000000000\n\nt_LQS_df2 = @suppress @benchmark df2_LQS_betas, df2_LQS_qth_resid = LeastQuantileSquares(X2,y2,2)\n\ntime(median(t_LQS_df2))/1000000000\n\nt_LTS_df2 = @suppress @benchmark df2_LTS_betas, df2_LTS_outlier_indicators = LeastTrimmedSquares(5,X2,y2)\n\ntime(median(t_LTS_df2))/1000000000\n\nt_LTSR_df2 = @suppress @benchmark df2_LTSR_betas, df2_LTSR_outlier_indicators = LeastTrimmedSumResiduals(5,X2,y2)\n\ntime(median(t_LTSR_df2))/1000000000\n\nt_BI_df2 = @suppress @benchmark df2_BI_betas, df2_BI_outlier_indicators = BoundedInfluence(0.4,X2,y2)\n\ntime(median(t_BI_df2))/1000000000\n\ndf2_betas_OLS = OrdinaryLeastSquares(X2,y2)\n\ndf2_LQS_betas, df2_LQS_qth_resid = LeastQuantileSquares(X2,y2,2)\n\ndf2_LTS_betas, df2_LTS_outlier_indicators = LeastTrimmedSquares(5,X2,y2)\n\nfindall(x->x==1, df2_LTS_outlier_indicators)\n\ndf2_LTSR_betas, df2_LTSR_outlier_indicators = LeastTrimmedSumResiduals(5,X2,y2)\n\nfindall(x->x==1, df2_LTSR_outlier_indicators)\n\ndf2_BI_betas, df2_BI_outlier_indicators = BoundedInfluence(0.4,X2,y2)\n\nfindall(x->x==1, df2_BI_outlier_indicators)\n\ndf3 = CSV.read(\"sds2.csv\", header=false);\n\ny3 = df3[:,1]\nX3 = convert(Matrix, df3[:,2:end]);\n\nt_OLS_df3 = @suppress @benchmark df3_betas_OLS = OrdinaryLeastSquares(X3,y3)\n\ntime(median(t_OLS_df3))/1000000000\n\nt_LQS_df3 = @suppress @benchmark df3_LQS_betas, df3_LQS_qth_resid = LeastQuantileSquares(X3,y3,2)\n\ntime(median(t_LQS_df3))/1000000000\n\nt_LTS_df3 = @suppress @benchmark df3_LTS_betas, df3_LTS_outlier_indicators = LeastTrimmedSquares(9,X3,y3)\n\ntime(median(t_LTS_df3))/1000000000\n\nt_LTSR_df3 = @suppress @benchmark df3_LTSR_betas, df3_LTSR_outlier_indicators = LeastTrimmedSumResiduals(9,X3,y3)\n\ntime(median(t_LTSR_df3))/1000000000\n\nt_BI_df3 = @suppress @benchmark df3_BI_betas, df3_BI_outlier_indicators = BoundedInfluence(0.82,X3,y3)\n\ntime(median(t_BI_df3))/1000000000\n\ndf3_betas_OLS = OrdinaryLeastSquares(X3,y3)\n\ndf3_LQS_betas, df3_LQS_qth_resid = LeastQuantileSquares(X3,y3,2)\n\ndf3_LTS_betas, df3_LTS_outlier_indicators = LeastTrimmedSquares(9,X3,y3)\n\nfindall(x->x==1, df3_LTS_outlier_indicators)\n\ndf3_LTSR_betas, df3_LTSR_outlier_indicators = LeastTrimmedSumResiduals(9,X3,y3)\n\nfindall(x->x==1, df3_LTSR_outlier_indicators)\n\ndf3_BI_betas, df3_BI_outlier_indicators = BoundedInfluence(0.82,X3,y3)\n\nfindall(x->x==1, df3_BI_outlier_indicators)\n\ndf4 = CSV.read(\"sds3.csv\", header=false);\n\ny4 = df4[:,1]\nX4 = convert(Matrix, df4[:,2:end]);\n\nsize(X4)\n\nt_OLS_df4 = @suppress @benchmark df4_betas_OLS = OrdinaryLeastSquares(X4,y4)\n\ntime(median(t_OLS_df4))/1000000000\n\nt_LQS_df4 = @suppress @benchmark df4_LQS_betas, df4_LQS_qth_resid = LeastQuantileSquares(X4,y4,2)\n\ntime(median(t_LQS_df4))/1000000000\n\nt_LTS_df4 = @suppress @benchmark df4_LTS_betas, df4_LTS_outlier_indicators = LeastTrimmedSquares(24,X4,y4)\n\ntime(median(t_LTS_df4))/1000000000\n\nt_LTSR_df4 = @suppress @benchmark df4_LTSR_betas, df4_LTSR_outlier_indicators = LeastTrimmedSumResiduals(24,X4,y4)\n\ntime(median(t_LTSR_df4))/1000000000\n\nt_BI_df4 = @suppress @benchmark df4_BI_betas, df4_BI_outlier_indicators = BoundedInfluence(0.85,X4,y4)\n\ntime(median(t_BI_df4))/1000000000\n\ndf4_betas_OLS = OrdinaryLeastSquares(X4,y4)\n\ndf4_LQS_betas, df4_LQS_qth_resid = LeastQuantileSquares(X4,y4,2)\n\ndf4_LTS_betas, df4_LTS_outlier_indicators = LeastTrimmedSquares(24,X4,y4)\n\nfindall(x->x==1, df4_LTS_outlier_indicators)\n\ndf4_LTSR_betas, df4_LTSR_outlier_indicators = LeastTrimmedSumResiduals(24,X4,y4)\n\nfindall(x->x==1, df4_LTSR_outlier_indicators)\n\ndf4_BI_betas, df4_BI_outlier_indicators = BoundedInfluence(0.89,X4,y4)\n\nfindall(x->x==1, df4_BI_outlier_indicators)\n\n# df5 = CSV.read(\"./SyntheticData_&_Scripts/df5.csv\", header=false)\n# y5 = df5[:,1]\n# X5 = convert(Matrix, df5[:,2:end]);\n\n# size(X5)\n\n# t_OLS_df5 = @suppress @benchmark df5_betas_OLS = OrdinaryLeastSquares(X5,y5)\n\n# time(median(t_OLS_df5))/1000000000\n\n# t_LQS_df5 = @suppress @benchmark df5_LQS_betas, df5_LQS_qth_resid = LeastQuantileSquares(X5,y5,2)\n\n# time(median(t_LQS_df2))/1000000000\n\n# t_LTS_df5 = @suppress @benchmark df5_LTS_betas, df5_LTS_outlier_indicators = LeastTrimmedSquares(4,X5,y5)\n\n# time(median(t_LTS_df2))/1000000000\n\n# t_ALTS_df5 = @suppress @benchmark df5_LTSR_betas, df5_LTSR_outlier_indicators = LeastTrimmedSumResiduals(4,X5,y5)\n\n# time(median(t_LTSR_df2))/1000000000\n\n# t_BI_df5 = @suppress @benchmark df5_BI_betas, df5_BI_outlier_indicators = BoundedInfluence(0.1,X5,y5)\n\n# time(median(t_BI_df2))/1000000000\n\n# df5_betas_OLS = OrdinaryLeastSquares(X5,y5)\n\n# df5_LQS_betas, df5_LQS_qth_resid = LeastQuantileSquares(X5,y5,2)\n\n# df5_LTS_betas, df5_LTS_outlier_indicators = LeastTrimmedSquares(5,X5,y5)\n\n# findall(x->x==1, df5_LTS_outlier_indicators)\n\n# df5_LTSR_betas, df5_LTSR_outlier_indicators = LeastTrimmedSumResiduals(5,X5,y5)\n\n# findall(x->x==1, df5_LTSR_outlier_indicators)\n\n# df5_BI_betas, df5_BI_outlier_indicators = BoundedInfluence(0.1,X5,y5)\n\n# findall(x->x==1, df5_BI_outlier_indicators)\n\nfunction standardize(df)\n    n, p = size(df)\n    for j in 1:p\n        mean1 = mean(df[:,j])\n        std1 = std(df[:,j])\n        for i in 1:n\n            df[i,j] = (df[i,j] - mean1)/std1\n        end\n    end\n    return df\nend\n\naq = CSV.read(\"Results/qsar_aquatic_toxicity.csv\", header=false)\n#Convert to matrices\nRandom.seed!(95)\naq = convert(Matrix, aq)\naq = aq[shuffle(1:end), :]\n\nsize(aq)\n\naq = standardize(aq);\n\n# Split into 50%, 25%, and 25%\ntrain_x = aq[1:40, 4:8]\ntrain_y = aq[1:40, 9]\n\nvalid_x = aq[41:60, 4:8]\nvalid_y = aq[41:60, 9]\n\ntest_x = aq[61:80, 4:8]\ntest_y = aq[61:80, 9];\n\nbetas_OLS = OrdinaryLeastSquares(train_x,train_y)\n\nbetas_LQS, LQS_qth_resid = LeastQuantileSquares(train_x,train_y,2)\n\nbetas_LTS, LTS_outlier_indicators = LeastTrimmedSquares(4,train_x,train_y)\n\nbetas_LTSR, LTSR_outlier_indicators = LeastTrimmedSumResiduals(4,train_x,train_y)\n\nbetas_BI, BI_outlier_indicators = BoundedInfluence(0.4,train_x,train_y)\n\nmean((valid_y .- betas_OLS[1] .- valid_x*betas_OLS[2:end]).^2)\nmean((valid_y .- betas_LQS[1] .- valid_x*betas_LQS[2:end]).^2)\nmean((valid_y .- betas_LTS[1] .- valid_x*betas_LTS[2:end]).^2)\nmean((valid_y .- betas_LTSR[1] .- valid_x*betas_LTSR[2:end]).^2)\nmean((valid_y .- betas_BI[1] .- valid_x*betas_BI[2:end]).^2)\n\nfull_x = vcat(train_x, valid_x)\nfull_y = vcat(train_y, valid_y);\n\ntime_OLS = @suppress @benchmark OrdinaryLeastSquares(full_x,full_y)\ntime(median(time_OLS))/1000000000\n\ntime_LQS = @suppress @benchmark betas_LQS, LQS_qth_resid = LeastQuantileSquares(full_x,full_y,2)\ntime(median(time_LQS))/1000000000\n\ntime_LTS = @suppress @benchmark  LeastTrimmedSquares(4,full_x,full_y)\ntime(median(time_LTS))/1000000000\n\ntime_LTSR = @suppress @benchmark LeastTrimmedSumResiduals(4,full_x,full_y)\ntime(median(time_LTSR))/1000000000\n\ntime_BI = @suppress @benchmark BoundedInfluence(0.4,full_x,full_y)\ntime(median(time_BI))/1000000000\n", "meta": {"hexsha": "66a06d349d5afeaf9319f2f02358d2aa1f609126", "size": 18705, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "DEC 9 - FINAL MIO Formulations - OLS, LMS, LTS, LTSR, BILS.jl", "max_stars_repo_name": "azaccor/Outlier_Robust_Regression_Models", "max_stars_repo_head_hexsha": "82c2936040b32639e71546c136030f95cd324e01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DEC 9 - FINAL MIO Formulations - OLS, LMS, LTS, LTSR, BILS.jl", "max_issues_repo_name": "azaccor/Outlier_Robust_Regression_Models", "max_issues_repo_head_hexsha": "82c2936040b32639e71546c136030f95cd324e01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DEC 9 - FINAL MIO Formulations - OLS, LMS, LTS, LTSR, BILS.jl", "max_forks_repo_name": "azaccor/Outlier_Robust_Regression_Models", "max_forks_repo_head_hexsha": "82c2936040b32639e71546c136030f95cd324e01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8154859967, "max_line_length": 121, "alphanum_fraction": 0.6581662657, "num_tokens": 6891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7669862503204513}}
{"text": "# Bertrand Nash example\n# Generates random equilibrium data\nusing Distributions\n\nindxID(ID) = (ID == :1) ? (1, 2) : (2, 1)\n\nfunction bestResponsePrice(thetas, prices, error, pmax, ID)\n\tme, you = indxID(ID)\n\tb = thetas[you]*prices[you] + thetas[3]*error + thetas[4]\n\tp = (-b - sqrt(b^2 - 8 * thetas[me]))/ 4. / thetas[me] \n\n\tassert( p>= 0)\n\treturn min(p, pmax)\nend\n\n#solve for equilibrium prices.  True model is log with a random, firm dependent effect\nfunction solveNashPrices(thetas1::Array{Float64, 1}, thetas2::Array{Float64, 1}, \n\t\t\t\t\t\terrors::Array{Float64, 2}, pmax; MAX_ITERS = 20, TOL=1e-6, trace=false, \n\t\tprices=fill(convert(Float64, pmax / 2), 2))\n\tfor i = 1:MAX_ITERS\n\t\tprices_old = copy(prices)\n\t\tprices[1] = bestResponsePrice(thetas1, prices_old, errors[1], pmax, :1)\n\t\tprices[2] = bestResponsePrice(thetas2, prices_old, errors[2], pmax, :2)\n\t\tdist = norm(prices - prices_old)\n\t\tif trace\n\t\t\tprintln(prices', dist)\n\t\tend\n\t\tif dist < TOL\n\t\t\treturn prices\n\t\tend\n\tend\n\terror(\"Max Iters reached\")\nend\n\nfunction margRev(thetas, prices, error, ID)\n\tme, you = indxID(ID)\n\t1./prices[me] + 2 * thetas[me] * prices[me] + thetas[you] * prices[you] + thetas[3] * error + thetas[4]\nend\n\n", "meta": {"hexsha": "7f6b211e384f4fa4fbaba8f92a5dc3fbfa04520c", "size": 1187, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Demand/BertrandNash2.jl", "max_stars_repo_name": "nlperic/InverseVIs", "max_stars_repo_head_hexsha": "d4a4cba463dd928b2b1e713244b0f7b7c4c30f14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2017-09-09T19:44:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-01T16:13:53.000Z", "max_issues_repo_path": "Demand/BertrandNash2.jl", "max_issues_repo_name": "nlperic/InverseVIs", "max_issues_repo_head_hexsha": "d4a4cba463dd928b2b1e713244b0f7b7c4c30f14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-05-19T17:09:27.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-22T17:27:16.000Z", "max_forks_repo_path": "Demand/BertrandNash2.jl", "max_forks_repo_name": "vgupta1/InverseVIs", "max_forks_repo_head_hexsha": "b3a4b2842126c76617911d8f6dcaf50d14b3962e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-06-11T19:41:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-24T15:04:58.000Z", "avg_line_length": 29.675, "max_line_length": 104, "alphanum_fraction": 0.6722830666, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464115, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7669862502472503}}
{"text": "\n# we write a function that caculates the product of two matrices A and B\nfunction mult(A,B)\n\n\t# we find the sizes of A and B\n\taRows, aCols = size(A)\n\tbRows, bCols = size(B)\n\n\t# we check if the matrix sizes are consistent with multiplication\n\tif aCols != bRows\n\t\terror(\"matrix sizes don't agree\")\n\tend\n\n\t# we initialize C to a zero matrix of the appropriate size\n\tC = zeros(aRows, bCols)\n\n\t# we loop over all pairs of rows and columns\n\tfor i = 1:aRows\n\t\tfor j = 1:bCols\n\t\t\t# and for each pair we store their dot pruduct in C\n\t\t\tfor k = 1:aCols\n\t\t\t\tC[i,j] += A[i,k] * B[k,j];\n\t\t\tend\n\t\tend\n\tend\n\n\t# we return C as the answer\n\treturn C\nend", "meta": {"hexsha": "f6416f0503fa4bdb60be2e2ca14be8ef19998bbf", "size": 636, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1a/Matrix Multiplication/mult.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "1a/Matrix Multiplication/mult.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "1a/Matrix Multiplication/mult.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 21.9310344828, "max_line_length": 72, "alphanum_fraction": 0.6745283019, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7669862474917324}}
{"text": "# ------------------------------------------------------------\n# Truncated cosine and its Fourier transform\n\n# [-1/2,1/2]\nfunction tcos(x)\n\tif 0.0 <= x <= 0.5\n\t\treturn cos(2*pi*x)\n\telse\n\t\treturn 0.0\n\tend\nend\n\nfunction ftcos(xi)\n\tif abs(xi) == 1.0\n\t\treturn 0.25 + 0.0*im\n\telse\n\t\treturn im*xi*( 1 + exp(-pi*xi*im) ) / (2*pi*(1 - xi^2))\n\tend\nend\n\n\n# Overload tcos and ftcos to vector input\n@vectorize_1arg Float64 tcos\n@vectorize_1arg Float64 ftcos\n\n\n# ------------------------------------------------------------\n# Reconstruct truncated cosine in Haar basis\n\nusing GeneralizedSampling\n\nJ = 5\nM = 2^(J+2)\n# Both GeneralizedSampling and Winston (below) have a grid function\nxi = GeneralizedSampling.grid(M, 0.5)\nf = ftcos(xi)\n\nT = Freq2Wave(xi, \"haar\", J)\nwcoef = T \\ f\n\n\n# ------------------------------------------------------------\n# Plot reconstruction\n\nusing IntervalWavelets\nusing Winston\n\nx, yw = weval( real(wcoef), \"haar\", 10 )\n# Waiting for IntervalWavelets to return x on [-0.5, 0.5] instead of [-1,1]\nx -= 0.5\n\nplot(x, yw, x, tcos(x))\n\n", "meta": {"hexsha": "f44038a692ee5f2abd56c8f3328f3f462f158a87", "size": 1044, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/truncated_cosine.jl", "max_stars_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_stars_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/truncated_cosine.jl", "max_issues_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_issues_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/truncated_cosine.jl", "max_forks_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_forks_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3333333333, "max_line_length": 75, "alphanum_fraction": 0.5498084291, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7669862474917324}}
{"text": "#=\nHeru Handika\n18 September 2020\nEuler's number implementation in julia\n=#\n\nusing Printf\n\nfunction calculate_factorial(n)\n    if n == 0 || n == 1\n        return 1\n    else\n        return n * calculate_factorial(n - 1)\n    end\nend\n\nfunction main()\n    euler_number::Float64 = 1.0\n    for i = 1:10\n        euler_number = euler_number + 1.0 / calculate_factorial(i)\n    end\n    @printf(\"Euler number: %.8f\\n\", euler_number)\n\nend\n\nif abspath(PROGRAM_FILE) == @__FILE__\n    main()\nend", "meta": {"hexsha": "8e526af85b5786814fbd1e9ddb951623867cdfea", "size": 480, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "euler-number/julia/euler.jl", "max_stars_repo_name": "hhandika/stats-from-scratch", "max_stars_repo_head_hexsha": "16864dd6f3605c16727480bb1ed2bec197f6d650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "euler-number/julia/euler.jl", "max_issues_repo_name": "hhandika/stats-from-scratch", "max_issues_repo_head_hexsha": "16864dd6f3605c16727480bb1ed2bec197f6d650", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "euler-number/julia/euler.jl", "max_forks_repo_name": "hhandika/stats-from-scratch", "max_forks_repo_head_hexsha": "16864dd6f3605c16727480bb1ed2bec197f6d650", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1428571429, "max_line_length": 66, "alphanum_fraction": 0.64375, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.877476793890012, "lm_q1q2_score": 0.7669824784114142}}
{"text": "using LinearAlgebra\nusing StaticArrays\n\n@inline function get_λ_η(α, β,θ, a)\n    λ = -α * sin(θ)\n    η = (α^2 - a^2)*cos(θ)^2+β^2\n    return λ, η\nend\n\n@inline function get_up_um(λ, η, a)\n    Δ_θ  = 1/2*(1-(η+λ^2)/a^2)\n    up = Δ_θ + √(Δ_θ^2 +η/a^2)\n    um = Δ_θ - √(Δ_θ^2 +η/a^2)\n    return up, um\nend\n\nfunction radialroots(λ::Real, η::Real, a)\n    T = promote_type(typeof(λ), typeof(η))\n    return radialroots(Complex{T}(λ), Complex{T}(η), a)\nend\n\n\n\"\"\"\n    $(SIGNATURES)\nFinds the radial roots using the of the geodesic with\nenergy-scaled angular momentum `λ` and carter constant `η`.\n\"\"\"\n@fastmath function radialroots(λ::Complex, η::Complex, a)\n    A = a^2 - η - λ^2\n    B = 2*(η+(λ-a)^2)\n    C = -a^2 * η\n    P = -A^2 / 12 - C\n    Q = -A/3 * ((A/6)^2-C)-B^2/8\n    H = -9*Q + √(12*P^3 + 81*Q^2)\n    z = √((-2*(3^(1/3)*P)+2^(1/3)*H^(2/3))/(2*6^(2/3)*H^(1/3)) - A/6)\n    discp = -A/2 - z^2 + B/(4*z)\n    dp = sqrt(discp)\n    discm = discp - B/(2*z)\n    dm = sqrt(discm)\n    r1 = -z - dp\n    r2 = -z + dp\n    r3 =  z - dm\n    r4 =  z + dm\n    #roots = SVector(r1,r2,r3,r4)\n    #ind = sortperm(real.(roots))\n    #println(real(λ), \" \", real(η))\n    return r1,r2,r3,r4#Tuple(roots[ind])\nend\n\nfunction get_Λ(β, χ)\n    s,c = sincos(χ)\n    γ = 1/sqrt(1-β^2)\n\n    Λ00 = γ\n    Λ01 = -γ*β*c\n    Λ03 = -γ*β*s\n    Λ11 = (γ-1)*c^2 + 1\n    Λ13 = (γ-1)*s*c\n    Λ33 = (γ-1)*s^2 + 1\n    z = zero(typeof(γ))\n    o =  one(typeof(γ))\n    return @SMatrix[Λ00 Λ01  z  Λ03;\n                    Λ01 Λ11  z  Λ13;\n                    z   z    o  z\n                    Λ03 Λ13  z  Λ33\n                   ]\nend\n", "meta": {"hexsha": "674b62501ced1c906f5575b9dc349f0efd03f124", "size": 1583, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/model_helpers.jl", "max_stars_repo_name": "ptiede/JuKeBOX.jl", "max_stars_repo_head_hexsha": "664db03f8c7e72f9b505d00ed33aae22b2f8ed64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-17T22:40:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T22:40:44.000Z", "max_issues_repo_path": "src/model_helpers.jl", "max_issues_repo_name": "ptiede/JuKeBOX.jl", "max_issues_repo_head_hexsha": "664db03f8c7e72f9b505d00ed33aae22b2f8ed64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/model_helpers.jl", "max_forks_repo_name": "ptiede/JuKeBOX.jl", "max_forks_repo_head_hexsha": "664db03f8c7e72f9b505d00ed33aae22b2f8ed64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2794117647, "max_line_length": 69, "alphanum_fraction": 0.4838913455, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789547, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7669623719517934}}
{"text": "kronprod = kron\n\nkronpow(A::Matrix,n::Integer) = n==1? A : kronprod([A for _ in 1:n]...)\n\nfunction kronsum(terms...)\n    Ms,Ns = zip([size(term) for term in terms]...)\n    Ms == Ns || throw(DimensionMismatch(\"term not square\"))\n    D = [eye(M) for M in Ms]\n    return sum([kronprod(setindex!(copy(D),term,i)...) for (i,term) in enumerate(terms)])\nend\n\n#function kronrepeatedsum(A::Matrix,n::Integer)\n#    B = A\n#    for k=1:n\n#        B = kronsum(B,A)\n#    end\n#    return B\n#end\n", "meta": {"hexsha": "cd4759b4da9b2ff7dd1d583c0c7596e1f32fac38", "size": 480, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fullkronfuns.jl", "max_stars_repo_name": "gajomi/KroneckerMatrices.jl", "max_stars_repo_head_hexsha": "8125f84c62ea3a9e9b27e4aa0ab4701e3ba61477", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fullkronfuns.jl", "max_issues_repo_name": "gajomi/KroneckerMatrices.jl", "max_issues_repo_head_hexsha": "8125f84c62ea3a9e9b27e4aa0ab4701e3ba61477", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fullkronfuns.jl", "max_forks_repo_name": "gajomi/KroneckerMatrices.jl", "max_forks_repo_head_hexsha": "8125f84c62ea3a9e9b27e4aa0ab4701e3ba61477", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2631578947, "max_line_length": 89, "alphanum_fraction": 0.5958333333, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7669623713566648}}
{"text": "# This file is part of the Julia package ModularForms.jl\n#\n# Copyright (c) 2018-2019: Lynn Engelberts and Alexandru Ghitza.\n\n\n#This file contains the functions hecke_operator_on_basis and hecke_operator_on_qexp. \n\n\n\n\"\"\"\n    hecke_operator_on_basis(B, n, k) \n\nCompute the matrix of the Hecke operator T_`n` of weight `k`\nrelative to the given basis `B` of q-expansions for a space of \nmodular forms. \n\n# Arguments\n- `B::Array`: array of q-expansions\n- `n::Integer`: integer >=1 \n- `k::Integer`: weight \n\n# Examples still missing\n\"\"\"\nfunction hecke_operator_on_basis(B::Array{fmpz_rel_series,1}, n::Int, k::Int)\n\n   #error handling\n   if n < 1\n      error(\"n (=$n) must be a positive integer\")\n   end\n   if isa(B, Array) == false\n      error(\"B (=$B) must be an array\")\n   end\n\n   #construct dxd matrix\n   ring = base_ring(B[1])\n   d = length(B)\t\t\t#check if this is always correct\n   S = MatrixSpace(ring, d, d)\n   matrix = S()\n\n   #compute Tn(f) to precision d+1 for each element f of B\n   for j in 1:d\n      f = B[j]\n      T_f = hecke_operator_on_qexp(f, n, k, d+1)\n      #check if cusp form\n      if d == dim_Sk(k)\n         for i in 1:d\n            #Tn for the jth element of B corresponds to the jth row\n            matrix[j,i] = coeff(T_f,i)\n         end\n      else\n         for i in 0:d-1\n            #Tn for the jth element of B corresponds to the jth row\n            matrix[j,i+1] = coeff(T_f,i)\n         end\t\t\n      end\n   end\n\n   return matrix\n\nend\n\n\n\n\"\"\"\n    divisors(n)\n\nReturn an array consisting of all divisors of `n` if n is \nnonzero, raise an error otherwise. \n\"\"\"\nfunction divisors(n::Int)\n\n   #error handling\n   if n == 0\n      error(\"n must be nonzero\")\n   end\n\n   n = abs(n)\n   array = [div for div in 1:n if n%div == 0]\n   return array\n\nend\n\n\n\n\"\"\" \n    hecke_operator_on_qexp(f, n, k, prec=nothing)\n\nCompute the image of the q-expansion `f` of a modular form under\nthe Hecke operator T_`n` of weight `k`. Return a power series to\nprecision `prec`. \n\n# Arguments\n- `f::RelSeriesElem`: q-expansion\n- `n::Integer`: integer >=1 \n- `k::Integer`: weight \n- `prec::Integer=nothing`: precision of the output\n\n# Examples still missing\n\"\"\"\nfunction hecke_operator_on_qexp(f::fmpz_rel_series, n::Int, k::Int, prec::Union{Int, Nothing}=nothing)\n\n   max_prec = Int(ceil(f.prec / Int(n)))\t#check if works also for n nonprime \n   if prec == nothing\n      prec = max_prec\n   elseif prec > max_prec\n      error(\"desired precision is too high given precision of f\")\n   end\n\n   R, q = PowerSeriesRing(base_ring(f), prec, \"q\")\n   T_p = R(0)\t\n\n   l = k-1\n   for m in 0:prec-1\t\t#start with 0 to deal with all modular forms\n      sum = 0\n      array = divisors(gcd(n,m)) \t#check if there is a quicker method\n      for i in 1:length(array)\n         d = array[i]\n         if (m*n)%(d*d) == 0\n            index = (m*n)//(d*d)\n            sum += d^l * coeff(f, Int(index))\n         end\n      end\n      T_p += sum*q^m\n   end\n\t\n   return T_p\n\nend\n", "meta": {"hexsha": "c9485c26e504879e8e330c42b0452cf102df9ea4", "size": 2938, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hecke.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ModularForms.jl-e4207f9d-5a5d-5278-bd5d-cae8f79430d9", "max_stars_repo_head_hexsha": "ae1f6e97b86b1fad1a9b40a4495a5087a68d6de7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-02-01T08:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T19:15:11.000Z", "max_issues_repo_path": "src/hecke.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ModularForms.jl-e4207f9d-5a5d-5278-bd5d-cae8f79430d9", "max_issues_repo_head_hexsha": "ae1f6e97b86b1fad1a9b40a4495a5087a68d6de7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-01-31T23:18:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-31T23:20:16.000Z", "max_forks_repo_path": "src/hecke.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ModularForms.jl-e4207f9d-5a5d-5278-bd5d-cae8f79430d9", "max_forks_repo_head_hexsha": "ae1f6e97b86b1fad1a9b40a4495a5087a68d6de7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-14T02:13:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-14T02:13:07.000Z", "avg_line_length": 22.7751937984, "max_line_length": 102, "alphanum_fraction": 0.6147038802, "num_tokens": 911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7669590212272548}}
{"text": "function laplacian4!(v, u, dx)\n    v[begin] = (u[end] + u[begin+1] - 2u[begin])/dx^2\n    @. @views v[begin+1:end-1] = (u[begin:end-2] + u[begin+2:end] - 2u[begin+1:end-1])/dx^2\n    v[end] = (u[end-1] + u[begin] - 2u[1end])/dx^2\n    return\nend\n\nfunction heateq4(u0, dx, tmax, N=200)\n    t = 0:dx:tmax\n    dt = step(t)\n    u = similar(u0, length(u0), length(t)+1)\n    u[:, 1] = u0\n    v = similar(u0)\n    N = 100\n    for i in 2:length(t)+1\n        @. @views u[:, i] = u[:, i-1]\n        for _ in 1:N\n            @views laplacian4!(v, u[:, i], dx)\n            @. @views u[:, i] += v*dt/N\n        end\n    end\n    t, u\nend\n\nusing StaticArrays\n\nn = 200\nx = range(-π, π; length=n+1)[1:end-1]\ndx = step(x)\nm = 200\nnoise1, noise2 = 0.3randn(m), 0.3randn(m)\nf(x) = SVector{m}((1 .+ noise1)*sin(x) .- (1 .+ noise2)*cos(2x))\nu0 = f.(x);\n\ntmax = 1.0\nt, u = heateq4(u0, dx, tmax);\n\nwrite(\"sol_t.txt\", repr(t))\nwrite(\"sol_u.txt\", repr(u))\n", "meta": {"hexsha": "4a7ac8b3ddbf491dd43ab12381a851ded220be70", "size": 923, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0004/heateq/heateq_calc.jl", "max_stars_repo_name": "genkuroki/public", "max_stars_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-06-06T00:33:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T06:56:08.000Z", "max_issues_repo_path": "0004/heateq/heateq_calc.jl", "max_issues_repo_name": "genkuroki/public", "max_issues_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0004/heateq/heateq_calc.jl", "max_forks_repo_name": "genkuroki/public", "max_forks_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-02T11:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T11:46:05.000Z", "avg_line_length": 23.075, "max_line_length": 91, "alphanum_fraction": 0.5102925244, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7669590170839848}}
{"text": "\"\"\"\n```julia\nlorenz(u0=[0.0, 10.0, 0.0]; σ = 10.0, ρ = 28.0, β = 8/3) -> ds\n```\n```math\n\\\\begin{aligned}\n\\\\dot{X} &= \\\\sigma(Y-X) \\\\\\\\\n\\\\dot{Y} &= -XZ + \\\\rho X -Y \\\\\\\\\n\\\\dot{Z} &= XY - \\\\beta Z\n\\\\end{aligned}\n```\nThe famous three dimensional system due to Lorenz [1], shown to exhibit\nso-called \"deterministic nonperiodic flow\". It was originally invented to study a\nsimplified form of atmospheric convection.\n\nCurrently, it is most famous for its strange attractor (occuring at the default\nparameters), which resembles a butterfly. For the same reason it is\nalso associated with the term \"butterfly effect\" (a term which Lorenz himself disliked)\neven though the effect applies generally to dynamical systems.\nDefault values are the ones used in the original paper.\n\nThe parameter container has the parameters in the same order as stated in this\nfunction's documentation string.\n\n[1] : E. N. Lorenz, J. atmos. Sci. **20**, pp 130 (1963)\n\"\"\"\nfunction lorenz(u0=[0.0, 10.0, 0.0]; σ = 10.0, ρ = 28.0, β = 8/3)\n    return CDS(loop, u0, [σ, ρ, β], loop_jac)\nend\nfunction loop(u, p, t)\n    @inbounds begin\n        σ = p[1]; ρ = p[2]; β = p[3]\n        du1 = σ*(u[2]-u[1])\n        du2 = u[1]*(ρ-u[3]) - u[2]\n        du3 = u[1]*u[2] - β*u[3]\n        return SVector{3}(du1, du2, du3)\n    end\nend\nfunction loop_jac(u, p, t)\n    @inbounds begin\n        σ, ρ, β = p\n        J = @SMatrix [-σ  σ  0;\n        ρ - u[3]  (-1)  (-u[1]);\n        u[2]   u[1]  -β]\n        return J\n    end\nend\n\nfunction lorenz_iip(u0=[0.0, 10.0, 0.0]; σ = 10.0, ρ = 28.0, β = 8/3)\n    return CDS(liip, u0, [σ, ρ, β], liip_jac)\nend\nfunction liip(du, u, p, t)\n    @inbounds begin\n        σ = p[1]; ρ = p[2]; β = p[3]\n        du[1] = σ*(u[2]-u[1])\n        du[2] = u[1]*(ρ-u[3]) - u[2]\n        du[3] = u[1]*u[2] - β*u[3]\n        return nothing\n    end\nend\nfunction liip_jac(J, u, p, t)\n    @inbounds begin\n    σ, ρ, β = p\n    J[1,1] = -σ; J[1, 2] = σ; J[1,3] = 0\n    J[2,1] = ρ - u[3]; J[2,2] = -1; J[2,3] = -u[1]\n    J[3,1] = u[2]; J[3,2] = u[1]; J[3,3] = -β\n    return nothing\n    end\nend\n\n\n\"\"\"\n```julia\nroessler(u0=rand(3); a = 0.2, b = 0.2, c = 5.7)\n```\n```math\n\\\\begin{aligned}\n\\\\dot{x} &= -y-z \\\\\\\\\n\\\\dot{y} &= x+ay \\\\\\\\\n\\\\dot{z} &= b + z(x-c)\n\\\\end{aligned}\n```\nThis three-dimensional continuous system is due to Rössler [1].\nIt is a system that by design behaves similarly\nto the `lorenz` system and displays a (fractal)\nstrange attractor. However, it is easier to analyze qualitatively, as for example\nthe attractor is composed of a single manifold.\nDefault values are the same as the original paper.\n\nThe parameter container has the parameters in the same order as stated in this\nfunction's documentation string.\n\n[1] : O. E. Rössler, Phys. Lett. **57A**, pp 397 (1976)\n\"\"\"\nfunction roessler(u0=rand(3); a = 0.2, b = 0.2, c = 5.7)\n    return CDS(roessler_eom, u0, [a, b, c], roessler_jacob)\nend\nfunction roessler_eom(u, p, t)\n    @inbounds begin\n    a, b, c = p\n    du1 = -u[2]-u[3]\n    du2 = u[1] + a*u[2]\n    du3 = b + u[3]*(u[1] - c)\n    return SVector{3, Float64}(du1, du2, du3)\n    end\nend\nfunction roessler_jacob(u, p, t)\n    a, b, c = p\n    return @SMatrix [0.0 (-1.0) (-1.0);\n                     1.0 a 0.0;\n                     u[3] 0.0 (u[1]-c)]\nend\n\n\"\"\"\n    double_pendulum(u0 = [π/2, 0, 0, rand()];\n                    G=10.0, L1 = 1.0, L2 = 1.0, M1 = 1.0, M2 = 1.0)\nFamous chaotic double pendulum system (also used for our logo!). Keywords\nare gravity (G), lengths of each rod and mass of each ball (all assumed SI units).\n\nThe variables order is [θ1, dθ1/dt, θ2, dθ2/dt].\n\nJacobian is created automatically (thus methods that use the Jacobian will be slower)!\n\n(please contribute the Jacobian and the e.o.m. in LaTeX :smile:)\n\nThe parameter container has the parameters in the same order as stated in this\nfunction's documentation string.\n\"\"\"\nfunction double_pendulum(u0=[π/2, 0, 0, rand()]; G=10.0, L1 = 1.0, L2 = 1.0, M1 = 1.0, M2 = 1.0)\n    return CDS(doublependulum_eom, u0, [G, L1, L2, M1, M2])\nend\n@inbounds function doublependulum_eom(state, p, t)\n    G, L1, L2, M1, M2 = p\n\n    du1 = state[2]\n    del_ = state[3] - state[1]\n    den1 = (M1 + M2)*L1 - M2*L1*cos(del_)*cos(del_)\n    du2 = (M2*L1*state[2]*state[2]*sin(del_)*cos(del_) +\n               M2*G*sin(state[3])*cos(del_) +\n               M2*L2*state[4]*state[4]*sin(del_) -\n               (M1 + M2)*G*sin(state[1]))/den1\n\n    du3 = state[4]\n\n    den2 = (L2/L1)*den1\n    du4 = (-M2*L2*state[4]*state[4]*sin(del_)*cos(del_) +\n               (M1 + M2)*G*sin(state[1])*cos(del_) -\n               (M1 + M2)*L1*state[2]*state[2]*sin(del_) -\n               (M1 + M2)*G*sin(state[3]))/den2\n    return SVector{4}(du1, du2, du3, du4)\nend\n\n\"\"\"\n    henonheiles(u0=[0, -0.25, 0.42081,0])\n```math\n\\\\begin{aligned}\n\\\\dot{x} &= p_x \\\\\\\\\n\\\\dot{y} &= p_y \\\\\\\\\n\\\\dot{p}_x &= -x -2 xy \\\\\\\\\n\\\\dot{p}_y &= -y - (x^2 - y^2)\n\\\\end{aligned}\n```\n\nThe Hénon–Heiles system [1] was introduced as a simplification of the motion\nof a star around a galactic center. It was originally intended to study the\nexistence of a \"third integral of motion\" (which would make this 4D system integrable).\nIn that search, the authors encountered chaos, as the third integral existed\nfor only but a few initial conditions.\n\nThe default initial condition is a typical chaotic orbit.\n\n[1] : Hénon, M. & Heiles, C., The Astronomical Journal **69**, pp 73–79 (1964)\n\"\"\"\nfunction henonheiles(u0=[0, -0.25, 0.42081, 0]#=; conserveE::Bool = true=#)\n\n\n    i = one(eltype(u0))\n    o = zero(eltype(u0))\n    J = zeros(eltype(u0), 4, 4)\n\n    # Vhh(q1, q2) = 1//2 * (q1^2 + q2^2 + 2q1^2 * q2 - 2//3 * q2^3)\n    # Thh(p1, p2) = 1//2 * (p1^2 + p2^2)\n    # Hhh(q1, q2, p1, p2) = Thh(p1, p2) + Vhh(q1, q2)\n    # Hhh(u::AbstractVector) = Hhh(u...)\n    #\n    # E = Hhh(u0)\n    #\n    # ghh! = (resid, u) -> begin\n    #     resid[1] = Hhh(u[1],u[2],u[3],u[4]) - E\n    #     resid[2:4] .= 0\n    # end\n\n    # if conserveE\n    #     cb = ManifoldProjection(ghh!, nlopts=Dict(:ftol=>1e-13), save = false)\n    #     prob = ODEProblem(hheom!, u0, (0., 100.0),  callback=cb)\n    # else\n        # prob = ODEProblem(hheom!, u0, (0., 100.0))\n    # end\n    return CDS(hheom!, u0, nothing, hhjacob!, J)\nend\nfunction hheom!(du, u, p, t)\n    @inbounds begin\n        du[1] = u[3]\n        du[2] = u[4]\n        du[3] = -u[1] - 2u[1]*u[2]\n        du[4] = -u[2] - (u[1]^2 - u[2]^2)\n        return nothing\n    end\nend\nfunction hhjacob!(J, u, p, t)\n    @inbounds begin\n    o = 0.0; i = 1.0\n    J[1,:] .= (o,    o,     i,    o)\n    J[2,:] .= (o,    o,     o,    i)\n    J[3,:] .= (-i - 2*u[2],   -2*u[1],   o,   o)\n    J[4,:] .= (-2*u[1],  -1 + 2*u[2],  o,   o)\n    return nothing\n    end\nend\n\n\n\n\"\"\"\n    lorenz96(N::Int, u0 = rand(M); F=0.01)\n\n```math\n\\\\frac{dx_i}{dt} = (x_{i+1}-x_{i-2})x_{i-1} - x_i + F\n```\n\n`N` is the chain length, `F` the forcing. Jacobian is created automatically.\n(parameter container only contains `F`)\n\"\"\"\nfunction lorenz96(N::Int, u0 = rand(N); F=0.01)\n    @assert N ≥ 4 \"`N` must be at least 4\"\n    lor96 = Lorenz96{N}() # create struct\n    return CDS(lor96, u0, [F])\nend\nstruct Lorenz96{N} end # Structure for size type\nfunction (obj::Lorenz96{N})(dx, x, p, t) where {N}\n    F = p[1]\n    # 3 edge cases\n    @inbounds dx[1] = (x[2] - x[N - 1]) * x[N] - x[1] + F\n    @inbounds dx[2] = (x[3] - x[N]) * x[1] - x[2] + F\n    @inbounds dx[N] = (x[1] - x[N - 2]) * x[N - 1] - x[N] + F\n    # then the general case\n    for n in 3:(N - 1)\n      @inbounds dx[n] = (x[n + 1] - x[n - 2]) * x[n - 1] - x[n] + F\n    end\n    return nothing\nend\n\n\n\n\"\"\"\n    duffing(u0 = [rand(), rand(), 0]; ω = 2.2, f = 27.0, d = 0.2, β = 1)\nThe (forced) duffing oscillator, that satisfies the equation\n```math\n\\\\ddot{x} + d\\\\cdot\\\\dot{x} + β*x + x^3 = f\\\\cos(\\\\omega t)\n```\nwith `f, ω` the forcing strength and frequency and `d` the dampening.\n\nThe parameter container has the parameters in the same order as stated in this\nfunction's documentation string.\n\"\"\"\nfunction duffing(u0 = [rand(), rand()]; ω = 2.2, f = 27.0, d = 0.2, β = 1)\n\n    J = zeros(eltype(u0), 2, 2)\n    J[1,2] = 1\n    return CDS(duffing_eom, u0, [ω, f, d, β], duffing_jacob)\nend\n@inbounds function duffing_eom(x, p, t)\n    ω, f, d, β = p\n    dx1 = x[2]\n    dx2 = f*cos(ω*t) - β*x[1] - x[1]^3 - d * x[2]\n    return SVector{2, Float64}(dx1, dx2)\nend\n@inbounds function duffing_jacob(u, p, t)\n    ω, f, d, β = p\n    return @SMatrix [0 1 ;\n    (-β - 3u[1]^2) -d]\nend\n\n\"\"\"\n    shinriki(u0 = [-2, 0, 0.2]; R1 = 22.0)\nShinriki oscillator with all other parameters (besides `R1`) set to constants.\n*This is a stiff problem, be careful when choosing solvers and tolerances*.\n\"\"\"\nfunction shinriki(u0 = [-2, 0, 0.2]; R1 = 22.0)\n    # # Jacobian caller for Shinriki:\n    # shinriki_eom(::Type{Val{:jac}}, J, u, p, t) = (shi::Shinriki)(t, u, J)\n    return CDS(shinriki_eom, u0, [R1])\nend\nshinriki_voltage(V) = 2.295e-5*(exp(3.0038*V) - exp(-3.0038*V))\nfunction shinriki_eom(u, p, t)\n    R1 = p[1]\n\n    du1 = (1/0.01)*(\n    u[1]*(1/6.9 - 1/R1) - shinriki_voltage(u[1] - u[2]) - (u[1] - u[2])/14.5\n    )\n\n    du2 = (1/0.1)*(\n    shinriki_voltage(u[1] - u[2]) + (u[1] - u[2])/14.5 - u[3]\n    )\n\n    du3 = (1/0.32)*(-u[3]*0.1 + u[2])\n    return SVector{3}(du1, du2, du3)\nend\n\n\"\"\"\n```julia\ngissinger(u0 = 3rand(3); μ = 0.119, ν = 0.1, Γ = 0.9)\n```\n```math\n\\\\begin{aligned}\n\\\\dot{Q} &= \\\\mu Q - VD \\\\\\\\\n\\\\dot{D} &= -\\\\nu D + VQ \\\\\\\\\n\\\\dot{V} &= \\\\Gamma -V + QD\n\\\\end{aligned}\n```\nA continuous system that models chaotic reversals due to Gissinger [1], applied\nto study the reversals of the magnetic field of the Earth.\n\nThe parameter container has the parameters in the same order as stated in this\nfunction's documentation string.\n\n[1] : C. Gissinger, Eur. Phys. J. B **85**, 4, pp 1-12 (2012)\n\"\"\"\nfunction gissinger(u0 = 3rand(3); μ = 0.119, ν = 0.1, Γ = 0.9)\n    return CDS(gissinger_eom, u0, [μ, ν, Γ])\nend\nfunction gissinger_eom(u, p, t)\n    μ, ν, Γ = p\n    du1 = μ*u[1] - u[2]*u[3]\n    du2 = -ν*u[2] + u[1]*u[3]\n    du3 = Γ - u[3] + u[1]*u[2]\n    return SVector{3}(du1, du2, du3)\nend\n\n\"\"\"\n```julia\nrikitake(u0 = [1, 0, 0.6]; μ = 1.0, α = 1.0)\n```\n```math\n\\\\begin{aligned}\n\\\\dot{x} &= -\\\\mu x +yz \\\\\\\\\n\\\\dot{y} &= -\\\\mu y +x(z-\\\\alpha) \\\\\\\\\n\\\\dot{V} &= 1 - xz\n\\\\end{aligned}\n```\nRikitake's dynamo is a system that tries to model the magnetic reversal events\nby means of a double-disk dynamo system.\n\n[1] : T. Rikitake Math. Proc. Camb. Phil. Soc. **54**, pp 89–105, (1958)\n\"\"\"\nfunction rikitake(u0 = [1, 0, 0.6]; μ = 1.0, α = 1.0)\n    return CDS(rikitake_eom, u0, [μ, α])\nend\nfunction rikitake_eom(u, p, t)\n    μ, α = p\n    x,y,z = u\n    xdot = -μ*x + y*z\n    ydot = -μ*y + x*(z - α)\n    zdot = 1 - x*y\n    return SVector{3}(xdot, ydot, zdot)\nend\n\n\n\"\"\"\n```julia\nnosehoover(u0 = [0, 0.1, 0])\n```\n```math\n\\\\begin{aligned}\n\\\\dot{x} &= y \\\\\\\\\n\\\\dot{y} &= yz - x \\\\\\\\\n\\\\dot{V} &= 1 - y^2\n\\\\end{aligned}\n```\nThree dimensional conservative continuous system, taken from the book\n\"Elegant Chaos\" by J. C. Sprott.\n\"\"\"\nnosehoover(u0 = [0, 0.1, 0]) = CDS(nosehoover_eom, u0, nothing)\nfunction nosehoover_eom(u, p, t)\n    x,y,z = u\n    xdot = y\n    ydot = y*z - x\n    zdot  = 1.0 - y*y\n    return SVector{3}(xdot, ydot, zdot)\nend\n\n\"\"\"\n```julia\nlabyrinth(u0 = [1.0, 0, 0])\n```\n```math\n\\\\begin{aligned}\n\\\\dot{x} &= \\\\sin(y) \\\\\\\\\n\\\\dot{y} &= \\\\sin(z) \\\\\\\\\n\\\\dot{V} &= \\\\sin(x)\n\\\\end{aligned}\n```\nThree dimensional conservative continuous system, whose evolution in 3D space looks\nlike a speudo-random walk, the orbit moving around like in a labyrinth.\nTaken from the book \"Elegant Chaos\" by J. C. Sprott.\n\"\"\"\nlabyrinth(u0 = [1.0, 0, 0]) = CDS(labyrinth_eom, u0, nothing)\nfunction labyrinth_eom(u, p, t)\n    x,y,z = u\n    xdot = sin(y)\n    ydot = sin(z)\n    zdot = sin(x)\n    return SVector{3}(xdot, ydot, zdot)\nend\n", "meta": {"hexsha": "35063e948d28e2b7583aa93597e6fcccfa11b318", "size": 11710, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/continuous_famous_systems.jl", "max_stars_repo_name": "JonasIsensee/DynamicalSystemsBase.jl", "max_stars_repo_head_hexsha": "79a6ddfae2b570ced5c5461e2b7dbb28920dcf2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/continuous_famous_systems.jl", "max_issues_repo_name": "JonasIsensee/DynamicalSystemsBase.jl", "max_issues_repo_head_hexsha": "79a6ddfae2b570ced5c5461e2b7dbb28920dcf2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/continuous_famous_systems.jl", "max_forks_repo_name": "JonasIsensee/DynamicalSystemsBase.jl", "max_forks_repo_head_hexsha": "79a6ddfae2b570ced5c5461e2b7dbb28920dcf2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2850241546, "max_line_length": 96, "alphanum_fraction": 0.5633646456, "num_tokens": 4784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7669590129280563}}
{"text": "using Sundials\npyplot(size=(700,700))\n\nProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n\n  ## Define the system residual function.\n  function resrob(tres, y, yp, r)\n      r[1]  = -0.04*y[1] + 1.0e4*y[2]*y[3]\n      r[2]  = -r[1] - 3.0e7*y[2]*y[2] - yp[2]\n      r[1] -=  yp[1]\n      r[3]  =  y[1] + y[2] + y[3] - 1.0\n  end\n\n  #t = [0.0, 4.0 * logspace(-1., 5., 7)]\n  t = [0.0, 0.4, 4.0, 40.0, 400.0, 4000.0, 40000.0, 400000.0]\n  yout, ypout = Sundials.idasol(resrob, [1.0, 0, 0], [-0.04, 0.04, 0.0], t)\n  yout |> display\n  println()\n  ypout |> display\n  println()\n  \n  p1 = plot(t, yout[:,1], color=:darkblue,\n    xlabel=\"x\", ylabel=\"y[1]\",\n    title=\"Example Sundials01A (using Sundials.jl)\"\n  )\n  plot!(t, yout[:,2], color=:red)\n  plot!(t, yout[:,3], color=:green)\n  \n  p2 = plot(t, ypout[:,1], color=:darkred,\n    xlabel=\"x\", ylabel=\"y[2]\"\n  )\n  plot!(t, ypout[:,2], color=:red)\n  plot!(t, ypout[:,3], color=:green)\n  \n  plot(p1, p2, layout=(1, 2))\n  savefig(\"Sundials01B.png\")\n  gui()\n  \n\nend", "meta": {"hexsha": "0eced9dca6d3789edd4f7d2db0cb7aca20a7da33", "size": 989, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch07/IVP/Sundials01B.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "examples/ch07/IVP/Sundials01B.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "examples/ch07/IVP/Sundials01B.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 24.1219512195, "max_line_length": 75, "alphanum_fraction": 0.5348837209, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7669590087721276}}
{"text": "## Example script for testing linear-strength vortex and source panel methods\nusing LinearAlgebra\nusing Base.Iterators\nusing Seaborn\nusing AeroMDAO\n\n## Tests\nwedge_pts    = @. Point2D([0.5, 0.0, -0.5, 0.0, 0.5],\n                          [-0.0, -0.5, 0.0, 0.5, 0.0])\nwedge_panels = @. Panel2D(wedge_pts[1:end-1], wedge_pts[2:end])\nuniform      = Uniform2D(1.0, 0.0)\n\n## Source\nA = source_influence_matrix(wedge_panels)\nb = neumann_boundary_condition(wedge_panels, velocity(uniform))\nσs = A \\ b\n\n##\nsum(σs)\n\n##\nx_domain, y_domain = (-1, 1), (-1, 1)\ngrid_size = 50\nx_dom, y_dom = range(x_domain..., length = grid_size), range(y_domain..., length = grid_size)\ngrid = product(x_dom, y_dom)\nwedge = panel_points(wedge_panels)\n\n##\n#\nsource_vels = [ velocity(uniform) .+ sum(source_velocity.(σs[1:end-1], σs[2:end], wedge_panels, x, y)) for (x, y) in grid ]\n# source_vels = [ sum(source_velocity.(1., 1., wedge_panels, x, y)) for (x, y) in grid ]\nspeeds  = @. sqrt(first(source_vels)^2 + last(source_vels)^2)\n\ncock = plot(first.(wedge), last.(wedge))\nstreamplot(first.(grid)', last.(grid)', first.(source_vels)', last.(source_vels)', color = speeds', density = 2.5)\n\nshow()\n\n\n## Vortex\nA = vortex_influence_matrix(wedge_panels)\nb = neumann_boundary_condition(wedge_panels, velocity(uniform))\nγs = A \\ b\n\n##\nsum(γs)\n\n##\nvortex_vels = [ sum(vortex_velocity(1., 1., panel, x, y) for panel in wedge_panels) for (x, y) in grid ]\n\nvortex_vels = [ velocity(uniform) .+ sum(vortex_velocity.(γs[1:end-1], γs[2:end], wedge_panels, x, y)) for (x, y) in grid ]\n\nspeeds  = @. sqrt(first(vortex_vels)^2 .+ last(vortex_vels)^2)\n\nplot(first.(wedge), last.(wedge))\nstreamplot(first.(grid)', last.(grid)', first.(vortex_vels)', last.(vortex_vels)', color = speeds', density = 2.5)\n\nshow()\n\n##\nvortex_source_vels = [ sum(total_velocity.(σs[1:end-1], σs[2:end], γs[1:end-1], γs[2:end], wedge_panels, x, y)) for (x, y) in grid ]\nspeeds     = @. sqrt(first(vortex_source_vels)^2 + last(vortex_source_vels)^2)\n\nplot(first.(wedge), last.(wedge))\nquiver(first.(grid), last.(grid), first.(vortex_source_vels), last.(vortex_source_vels), speeds)\n\nshow()\n\n", "meta": {"hexsha": "c8ea8f414f4a8729ca453b427e58fe6ed5043e96", "size": 2121, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/2d_panel_methods/all_wedge.jl", "max_stars_repo_name": "HKUST-OCTAD-LAB/AeroMDAO.jl", "max_stars_repo_head_hexsha": "0ca9aa924f088cac59d04958eb5c6704b50feb18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/2d_panel_methods/all_wedge.jl", "max_issues_repo_name": "HKUST-OCTAD-LAB/AeroMDAO.jl", "max_issues_repo_head_hexsha": "0ca9aa924f088cac59d04958eb5c6704b50feb18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/2d_panel_methods/all_wedge.jl", "max_forks_repo_name": "HKUST-OCTAD-LAB/AeroMDAO.jl", "max_forks_repo_head_hexsha": "0ca9aa924f088cac59d04958eb5c6704b50feb18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7391304348, "max_line_length": 132, "alphanum_fraction": 0.6713814239, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7668843787383333}}
{"text": "immutable logNormal <: ContinuousUnivariateDistribution\n    meanlog::Float64\n    sdlog::Float64\n    function logNormal(ml::Real, sdl::Real)\n    \tif sdl > 0.0\n    \t\tnew(float64(ml), float64(sdl))\n    \telse\n    \t\terror(\"sdlog must be positive\")\n    \tend\n\tend\nend\n\nlogNormal(ml::Real) = logNormal(ml, 1.0)\nlogNormal() = logNormal(0.0, 1.0)\n\n@_jl_dist_2p logNormal lnorm\n\nentropy(d::logNormal) = 1.0 / 2.0 + (1.0 / 2.0) *\n                        log(2.0 * pi * d.sdlog^2) + d.meanlog\n\ninsupport(d::logNormal, x::Number) = isreal(x) && isfinite(x) && 0 < x\n\nmean(d::logNormal) = exp(d.meanlog + d.sdlog^2 / 2)\n\nfunction var(d::logNormal)\n\tsigsq = d.sdlog^2\n\treturn (exp(sigsq) - 1) * exp(2d.meanlog + sigsq)\nend\n", "meta": {"hexsha": "f782f0d0690ccee8a9b872c8e3d35f0be90790cf", "size": 707, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/lognormal.jl", "max_stars_repo_name": "mewo2/Distributions.jl", "max_stars_repo_head_hexsha": "00dd06fb13632b9f0259f036bb861e47b7170a76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-16T01:43:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-16T01:43:20.000Z", "max_issues_repo_path": "src/univariate/lognormal.jl", "max_issues_repo_name": "mewo2/Distributions.jl", "max_issues_repo_head_hexsha": "00dd06fb13632b9f0259f036bb861e47b7170a76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/lognormal.jl", "max_forks_repo_name": "mewo2/Distributions.jl", "max_forks_repo_head_hexsha": "00dd06fb13632b9f0259f036bb861e47b7170a76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3793103448, "max_line_length": 70, "alphanum_fraction": 0.6209335219, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7668843778411938}}
{"text": "\"\"\"\n    sun_generators(n)\n\nReturns an array of sparse ``n \\\\times n`` generators of ``SU(N)``\nthat are Hermitian and trless.\n\"\"\"\nfunction sun_generators(n)\n    matrices = [spzeros(ComplexF64, n, n) for i = 1 : n^2-1]\n    i = 1\n\n    # Diagonal matrices\n    for l = 1:n-1\n        for j = 1:l\n            matrices[i][j, j] = sqrt(2/(l*(l+1)))\n        end\n        matrices[i][l+1, l+1] = -sqrt(2*l/(l+1))\n        i += 1\n    end\n\n    # Real matrices\n    for k = 2:n\n        for j = 1:k-1\n            matrices[i][j, k] = matrices[i][k, j] = 1.\n            i += 1\n        end\n    end\n\n    # Imaginary matrices\n    for k = 2:n\n        for j = 1:k-1\n            matrices[i][j, k] -= (matrices[i][k, j] = 1im)\n            i += 1\n        end\n    end\n\n    return matrices\nend\n\n\"\"\"\n    bloch_vector(ρ)\n\nReturns the generalized Bloch vector ``\\\\mathbf{r}`` for the density operator ρ.\n\nIf ρ is a ``N × N`` density operator, ``\\\\mathbf{r}`` will be a ``N^2 - 1``\nvector of real values. We follow the formula\n``ρ = \\\\frac{1}{N} (I + \\\\sqrt{N} \\\\mathbf{r} \\\\cdot \\\\mathbf{λ})``\n\"\"\"\nfunction bloch_vector(ρ)\n   n = size(ρ)[1]\n   λ = sun_generators(n)\n   sqrt(n)/2*real([tr(λ[i] * ρ) for i = 1: length(λ)])\nend\n\n\"\"\"\n    density_operator(r)\n\nReturns the density operator ρ corresponding to the Bloch vector `r`.\n\n`vec` must be a vector of ``N^2-1`` real values. We follow the formula\n``ρ = \\\\frac{1}{N} (I + \\\\sqrt{N} \\\\mathbf{r} \\\\cdot \\\\mathbf{λ})``\n\"\"\"\nfunction density_operator(vec::Array{Float64})\n   n = length(vec)\n   Nq = Int(floor(sqrt(n+1))) # Dimension of the corresponding Hilbert space\n   λ = sun_generators(Nq) # Obtain the generators of the SU(N) Hilbert space\n\n   1/Nq*(I + sqrt(Nq) * sum([vec[i] * λ[i] for i = 1:n]))\nend\n\n# We return im * gen so that the matrix is real (more efficient)\n\n\n\"\"\"\n    igen(H)\n\nReturns ``i G(H)``, where G is defined in Eq. (11) of Joynt et al.\n\"\"\"\nfunction igen(H)\n    n = size(H,1)\n    λ = sun_generators(n)\n    result = spzeros(n^2-1, n^2-1)\n    for i = 1:n^2-1\n        for j = i+1:n^2-1\n            tmp = imag(0.5 * tr(commutator(λ[i],λ[j])*H))\n            if tmp != 0\n                @inbounds result[i,j] = tmp\n                @inbounds result[j,i] = -tmp\n            end\n        end\n    end\n    return result\nend\n\n\"\"\"\n    igen(f, λ, H)\n\nReturns ``i G(H)``, where G is defined in Eq. (11) of Joynt et al., with the\nstructure constants tensor `f` that can be evaluated with `structure_constants(λ)`,\nand the array of SU(N) generators λ (`sun_generators(n)`).\n\nWhen providing `f`, the calculations are much faster (especially if many\ngenerators have to be evaluated).\n\"\"\"\nfunction igen(f, λ, H)\n    n = size(H,1)\n    result = spzeros(n^2-1, n^2-1)\n\n    if eltype(H) <: Real\n        # If the Hamiltonian is real, the imaginary generators do not contribute\n        nimag = Int(floor(n*(n-1)/2))\n        ak = zeros(n^2-1)\n        ak[1:end-nimag] = real([tr(H*lambda) for lambda in λ[1:end-nimag]])\n    else\n        ak = real([tr(H*lambda) for lambda in λ])\n    end\n\n    for i = 1:n^2-1\n        @inbounds result[i, :] .= f[i] * ak\n    end\n    return result\nend\n\n\"\"\"\n    structure_constants(λ)\n\nReturns the totally antisymmetric tensor ``i f_{ijk}`` of the structure constants\nof the list of generators λ, defined as ``f_{ijk} = - 2 i \\\\text{Tr}([λ_i,λ_j]λ_k)``.\n\nNotice that the true definition has a factor ``-i``, which we avoid to store only\na real value.\n\"\"\"\nfunction structure_constants(lambda)::Array{SparseArrays.SparseMatrixCSC{Float64,Int64},3}\n    Nl = length(lambda)\n    f = cat([spzeros(Float64, Nl, Nl) for i = 1:Nl], dims=3)\n    for i = 1:Nl\n        for j = i+1:Nl\n            for k = j+1:Nl\n                tmp::Float64 = 1. / 4. * imag(tr(commutator(lambda[i],lambda[j])*lambda[k]))\n                if tmp != 0\n                    @inbounds begin\n                        f[i][j,k] +=  tmp\n                        f[i][k,j] -=  tmp\n                        f[k][i,j] +=  tmp\n                        f[j][i,k] -=  tmp\n                        f[j][k,i] +=  tmp\n                        f[k][j,i] -=  tmp\n                    end\n                end\n            end\n        end\n    end\n    return f\nend\n", "meta": {"hexsha": "b5cb09c758b2f4b6bd002f696cc1cc0b2a0a4992", "size": 4138, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SpecialUnitary.jl", "max_stars_repo_name": "matteoacrossi/QuasiHamiltonianRTN.jl", "max_stars_repo_head_hexsha": "8005be028134838eda520fe0a8fd7131171f8db7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-22T23:36:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T00:39:43.000Z", "max_issues_repo_path": "src/SpecialUnitary.jl", "max_issues_repo_name": "matteoacrossi/QuasiHamiltonianRTN.jl", "max_issues_repo_head_hexsha": "8005be028134838eda520fe0a8fd7131171f8db7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SpecialUnitary.jl", "max_forks_repo_name": "matteoacrossi/QuasiHamiltonianRTN.jl", "max_forks_repo_head_hexsha": "8005be028134838eda520fe0a8fd7131171f8db7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-10T00:39:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T00:39:48.000Z", "avg_line_length": 26.8701298701, "max_line_length": 92, "alphanum_fraction": 0.5364910585, "num_tokens": 1328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7668843728277281}}
{"text": "\"\"\"\nCalculate the fast Fourier transform of n numbers in x̄.\n(Note that n must be a power of 2 (n = 2ᵏ))\nReturns:\nȳ - A complex array of size n \n\"\"\"\nfunction FFT(n::Integer, x̄::Array{<:Number})\n    # Julia is 1-indexed\n    if n == 1\n        return [x̄[1]]\n    end\n\n    evens = [x̄[Int(2i)] for i = 1:n/2]\n    odds = [x̄[Int(2i-1)] for i = 1:n/2]\n    # Since Julia is 1-indexed, we flip the odds and evens at the recursive step\n    ū = FFT(Int(n/2), odds)\n    v̄ = FFT(Int(n/2), evens)\n    ȳ = zeros(Complex, n)\n    for j = 1:n\n        τ = exp(2π*im*(j-1)/n) \n        ȳ[j] = ū[(j-1)%Int(n/2)+1] + τ * v̄[(j-1)%Int(n/2)+1]\n    end\n    ȳ\nend\n\nn = 4\nx̄ = [1 1 0im 2]\nȳ = FFT(n, x̄)\ndisplay(ȳ)\n", "meta": {"hexsha": "c8b04e2ac1609607b870578849538b94bc125cda", "size": 698, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia_fft.jl", "max_stars_repo_name": "dillondaudert/JuliaFFT", "max_stars_repo_head_hexsha": "eeb80cd0b2208cba70bf024c092228cb898ea015", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia_fft.jl", "max_issues_repo_name": "dillondaudert/JuliaFFT", "max_issues_repo_head_hexsha": "eeb80cd0b2208cba70bf024c092228cb898ea015", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia_fft.jl", "max_forks_repo_name": "dillondaudert/JuliaFFT", "max_forks_repo_head_hexsha": "eeb80cd0b2208cba70bf024c092228cb898ea015", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2666666667, "max_line_length": 80, "alphanum_fraction": 0.5229226361, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7668516467118067}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.5\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ e55010c0-b76d-11eb-2a21-d971845b6910\nbegin\n\tusing Plots,PlutoUI,ForwardDiff\n\tplotlyjs()\nend\n\n# ╔═╡ 1b5d7083-faaf-4cdb-8a7f-3ccbf9af47d9\nf(x) = x^2\n\n# ╔═╡ 8861d281-5968-482d-8c0c-9d5308335411\nmd\"\"\"\nx₀ = $(@bind x₀ Slider(-3:0.1:3,default=0,show_value=true))\n\nΔx = $(@bind Δx Slider(0.01:0.1:1,default=1,show_value=true))\n\"\"\"\n\n# ╔═╡ c10041fe-bbe9-45b5-a405-56cabda81ccf\nbegin\n\tfₓ(x) = ForwardDiff.derivative(f,x)\n\tL(x) = fₓ(x₀)*(x-x₀) + f(x₀) \n\tplot(f,label=\"f(x)\",ylim=[-10,10])\n\t# plot!(fₓ,label=\"f'(x)\")\n\tplot!(L,label=\"L(x)\")\n\tx1 = x₀+Δx \n\tplot!([(x1,L(x1)),(x1,f(x1))],label=\"Δf-df\",with=3)\n\tplot!([(x1,f(x₀)),(x1,L(x1))],width=2,label=false,color=:black)\n\tplot!([(x₀,f(x₀)),(x1,f(x₀))],width=2,label=false,color=:black)\nend\n\n# ╔═╡ Cell order:\n# ╠═e55010c0-b76d-11eb-2a21-d971845b6910\n# ╠═1b5d7083-faaf-4cdb-8a7f-3ccbf9af47d9\n# ╟─8861d281-5968-482d-8c0c-9d5308335411\n# ╟─c10041fe-bbe9-45b5-a405-56cabda81ccf\n", "meta": {"hexsha": "b0ecafc711121d85cb4d9f4096af79793eafc667", "size": 1369, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "cuadernos/linealizacion_y_diferencial.jl", "max_stars_repo_name": "akielbowicz/cbc-analisis-ingenieria", "max_stars_repo_head_hexsha": "b845ef9ab500bb9f2f7ebb62cae1f9d17c1ec428", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cuadernos/linealizacion_y_diferencial.jl", "max_issues_repo_name": "akielbowicz/cbc-analisis-ingenieria", "max_issues_repo_head_hexsha": "b845ef9ab500bb9f2f7ebb62cae1f9d17c1ec428", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cuadernos/linealizacion_y_diferencial.jl", "max_forks_repo_name": "akielbowicz/cbc-analisis-ingenieria", "max_forks_repo_head_hexsha": "b845ef9ab500bb9f2f7ebb62cae1f9d17c1ec428", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-24T15:30:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-24T15:30:30.000Z", "avg_line_length": 27.38, "max_line_length": 195, "alphanum_fraction": 0.6661796932, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.8807970795424088, "lm_q1q2_score": 0.7668195344289239}}
{"text": "using ForwardDiff\nusing LaTeXStrings\nusing StatsPlots\nusing Plots\npyplot()\n\nlet\n\n\"\"\"Function\"\"\"\n\n# Objective\nf(x::Vector) = -(x[1]*x[2] + x[2]*x[3] + x[1]*x[3])\nΩ(x::Vector) = sum((abs.(x) .- 1).^2)\nh(x::Vector) = f(x) + Ω(x)\n\n# Minimization step\nfunction g(x::Vector, i::Integer)\n\n\tif i == 1\n\t\t# Closed-form solution\n\t\tg_i = (1 + abs(x[2] + x[3])/2)*sign(x[2] + x[3])\n\n\telseif i == 2\n\t\t# Closed form solution\n\t\tg_i = (1 + abs(x[1] + x[3])/2)*sign(x[1] + x[3])\n\n\telseif i == 3\n\t\t# Closed form solution\n\t\tg_i = (1 + abs(x[1] + x[2])/2)*sign(x[1] + x[2])\n\tend\n\treturn g_i\nend\n\n\"\"\"Coordinate Descent\"\"\"\n\n# Number of iterations\nK = 2\n\n# Fix step size\nα = 1.0\n\n# Initialize coordinates\nϵ = 1e-3\nx = [-1. - ϵ, 1. + ϵ/2, -1. - ϵ/4]\n\n# Preallocate result array\nglobal xx = zeros(K*3,3)\n\n# Initalize visualization\nscatter([x[1]], [x[2]], [x[3]],\n\t\tcolor=\"red\",\n\t\tmarkerstrokecolor=nothing,\n\t\tlabel=\"x^0\",\n\t\txlims=(-1.5, 1.5),\n\t\tylims=(-1.5, 1.5),\n\t\tzlims=(-1.5, 1.5),\n\t\txlabel=L\"x_1\",\n\t\tylabel=L\"x_2\",\n\t\tzlabel=L\"x_3\")\n\n# Visualize stationary points\nscatter!([+1], [+1], [+1], color=\"green\", label=\"min\", markerstrokecolor=nothing)\nscatter!([-1], [-1], [-1], color=\"green\", label=\"\", markerstrokecolor=nothing)\n\n# Loop over iterations\nanim = @animate for k = 1:K*3\n\n\t# Keep track of x\n\tprintln(x)\n\txx[k, :] = x\n\n\t# Update index\n\ti = (k-1) % 3 + 1\n\tprintln(i)\n\n\t# Update coordinate\n\tx[i] = g(x, i)\n\n\t# Visualization\n\tplot!([xx[k,1], x[1]],\n\t \t  [xx[k,2], x[2]],\n\t\t  [xx[k,3], x[3]],\n\t      color=\"blue\",\n\t \t  label=\"\",\n\t \t  markerstrokecolor=nothing)\nend\n\ngif(anim, \"powells.gif\", fps=2)\n\nend\n", "meta": {"hexsha": "9934306ab94a42a71846881f7f55f53e36958291", "size": 1583, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Powells_example.jl", "max_stars_repo_name": "wmkouw/CD-powells", "max_stars_repo_head_hexsha": "4673cfb8bfffcc9d8142f8753af48a9dfff30a35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Powells_example.jl", "max_issues_repo_name": "wmkouw/CD-powells", "max_issues_repo_head_hexsha": "4673cfb8bfffcc9d8142f8753af48a9dfff30a35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Powells_example.jl", "max_forks_repo_name": "wmkouw/CD-powells", "max_forks_repo_head_hexsha": "4673cfb8bfffcc9d8142f8753af48a9dfff30a35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3956043956, "max_line_length": 81, "alphanum_fraction": 0.572962729, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475810629193, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7668164244219674}}
{"text": "module BuildOverlap\n\nexport buildelecoverlap\n\nusing TypesParticles, TypesBasis\nusing  UtilityFunctions\n\n@doc raw\"\"\"\n                      buildelecoverlap(basis::Basis)\n\nreturns the building of electron overlap integral matrix of expectation values:\n\n     S_{m,n} = langle m | n rangle = int d tau phi_m phi_n \n\nDescription: This function calculates the electron-electron overlap matrix which essential captures\nthe inner product projection of basis function m on n, this is neccessary to track basis-functions that\nare not orthogonal to one another.\n\nNOTES: multiple dispatch only for GaussOrbitals\n\n\"\"\"\nfunction buildelecoverlap(natoms::Int,basisfunc::Array{GaussOrbitals},basis::Basis)\n    numbasisfunc = basis.nbasisfunc; #number of basis functions\n    osize = natoms*basis.nbasisfunc; #overlap size\n    overlap = zeros(Float64,osize,osize); #overlap matrix Ne*Gaussians x Ne*Gaussians\n\n    #flatbasisfunc=vcat(basisfunc...); #Need to improve\n    flatbasisfunc = flattenbasisfunc(natoms,numbasisfunc,basisfunc);\n  \n    for n=1:osize\n        for m=1:osize\n            nbasis = flatbasisfunc[n];\n            mbasis = flatbasisfunc[m];\n            nprims = length(nbasis.alphas);\n            mprims = length(mbasis.alphas);    \n            for np=1:nprims\n                for mp=1:mprims\n                    coefs = nbasis.coefs[np]*mbasis.coefs[mp];\n                    gaussoverlap = getgaussoverlap(np,mp,nbasis,mbasis);\n                    overlap[n,m] += coefs*gaussoverlap;\n                end\n            end # mprims        \n        end \n    end #osize\n\n    return overlap\nend #buildelecoverlap\n\nend #module\n", "meta": {"hexsha": "1874c4272133ad99bd91460570af94095c286676", "size": 1617, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BuildOverlap.jl", "max_stars_repo_name": "JuliaMatSci/LearnHartreeFock.jl", "max_stars_repo_head_hexsha": "ff91cff63d6ae4039b26b864f14fd86743ae6037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-04-26T03:03:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:14:31.000Z", "max_issues_repo_path": "src/BuildOverlap.jl", "max_issues_repo_name": "JuliaMatSci/LearnHatreeFock.jl", "max_issues_repo_head_hexsha": "ff91cff63d6ae4039b26b864f14fd86743ae6037", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BuildOverlap.jl", "max_forks_repo_name": "JuliaMatSci/LearnHatreeFock.jl", "max_forks_repo_head_hexsha": "ff91cff63d6ae4039b26b864f14fd86743ae6037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-24T23:31:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T23:31:50.000Z", "avg_line_length": 32.34, "max_line_length": 103, "alphanum_fraction": 0.6666666667, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993027, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7668164179486039}}
{"text": "\n# DBL_EPSILON - jest to dokładność dla liczb zmiennoprzecinkowych\n# dla Float64 jest to 2.2204460492503131e-16\nDBL_EPSILON = 2.2204460492503131e-16\n\nfunction DIFFSIGN(x::Float64, y::Float64)\n    if (x <=0 && y >= 0) || (x >= 0 && y <= 0)\n        return true\n    else\n        return false\n    end\nend\n\nfunction fun(x::Float64)\n    return 1.0 / (x - 3.0) - 6.0\nend\n\nfunction between(x::Float64, a::Float64, b::Float64)\n    if b > a\n        return (x >= a && x <= b)\n    else\n        return (x >= b && x <= a)\n    end\nend\n\nfunction lfun(b::Float64, a::Float64, fb::Float64, fa::Float64)\n    if fb != fa\n        return b - fb*(b - a) / (fb - fa) # metoda siecznych\n    elseif fa != 0\n        return Inf\n    else\n        return b\n    end\nend\n\nfunction hfun(b::Float64, c::Float64)\n    if c > b\n        return b + abs(b*DBL_EPSILON)\n    else\n        return b - abs(b*DBL_EPSILON)\n    end\nend\n\nfunction mfun(b::Float64, c::Float64)\n    return 0.5*(b + c) # metoda bisekcji\nend\n\nfunction vfun(l::Float64, b::Float64, c::Float64)\n    h = hfun(b, c)\n    m = mfun(b, c)\n    \n    if between(l, h, m) == true\n        return l\n    elseif abs(l - b) <= abs(b*DBL_EPSILON)\n        return h\n    else\n        return m\n    end\nend\n\nfunction DekkerA(x0::Float64, x1::Float64, Eps::Float64)\n    \"\"\"\n    b - ostatnie przyblizenie wyniku\n    c - kontrapunkt b, punkt w którym funkcja f ma przeciwny znak niż w punkcie b\n    a – poprzednia wartość punktu a, używana do wyliczania następnego punktu metodą siecznych\n    \n    Metoda bisekcji z punktów b i c tworzy punkt m pomiędzy nimi na środku przedziału.\n    \n    Wyliczany jest ciąg xi, którego ostatni element oznaczany jest przez x, a poprzedni przez xp.\n    \n    xk - ostatni punkt w ciągu, który ma różny znak niż x.\n    \n    Punkt x wyliczany jest dwoma metodami:\n        - siecznych\n        - bisekcji\n    i wybierany jest ten obliczony z metody siecznych jeśli leży pomiędzy punktem b\n    (ze względów dokładnościowych z pewną poprawką) a punktem m wyliczonym z bisekcji.\n\n    Jeżeli f(x) czy f(xk) leży bliżej zera i jeśli f(x) leży bliżej zera\n    wtedy b ma wartość x, c ma wartość xk, w przeciwnym razie zamiana.\n    \"\"\"\n    fxp = fun(x0)\n    fx = fun(x1)\n    \n    if abs(fx) <= abs(fxp)\n        b = x1\n        a = c = x0\n        fa = fxp\n        fb = fx\n    else\n        b = x0\n        a = c = x1\n        fa = fx\n        fb = fxp\n    end\n    \n    xk = x0\n    fxk = fxp\n    x = x1\n    iter = 1\n    \n    while abs(b - c) > 2*Eps\n        iter = iter + 1\n        lambda = lfun(b, a, fb, fa)\n        xp = x\n        x = vfun(lambda, b, c)\n        fxp = fx\n        fx = fun(x)\n\n        if DIFFSIGN(fxp, fx) == true\n            xk = xp\n            fxk = fxp\n        end\n        \n        if abs(fx) <= abs(fxk)\n            a = b\n            b = x\n            c = xk\n            fa = fb\n            fb = fx\n        else\n            b = xk\n            a = c = x\n            fa = fx\n            fb = fxk\n        end       \n    end\n    println(\"Number of iterations: \", iter)\n    return b\nend\n\nprintln(\"f(x) = 1/(x-3)-6\\n\")\nresult = DekkerA(3.01, 4.0, 1e-12)\nprintln(\"x0 = \", result)\n", "meta": {"hexsha": "246e3616f6cb2e965740069bfb5cbb5887ff70a0", "size": 3113, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Dekker Method A.jl", "max_stars_repo_name": "radoslawczapp/DekkerMethod", "max_stars_repo_head_hexsha": "6aaa0a0337042481e25b755ae03abc4f1a992722", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Dekker Method A.jl", "max_issues_repo_name": "radoslawczapp/DekkerMethod", "max_issues_repo_head_hexsha": "6aaa0a0337042481e25b755ae03abc4f1a992722", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Dekker Method A.jl", "max_forks_repo_name": "radoslawczapp/DekkerMethod", "max_forks_repo_head_hexsha": "6aaa0a0337042481e25b755ae03abc4f1a992722", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0592592593, "max_line_length": 97, "alphanum_fraction": 0.5406360424, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7668164025296792}}
{"text": "using Graphs\nn = 10\nk = 2\nbeta = 0.3\nsvt.S\ng = watts_strogatz_graph(n, k, beta)\nlap = Symmetric(laplacian_matrix(g))\nlaps = Symmetric(laplacian_matrix_sparse(g))\nlapsp = laplacian_matrix_sparse(g)\nfunction algConnectivity(L::Symmetric;vecs=false)\n    # Calculates the algebraic connectivity of graph with laplacian L\n    # Input: L a symmetric laplacian matrix\n    # Output: value of algebraic connectivity λ_2\n    e_vals = eigfact(L,2:2)\n    λ = e_vals.values\n    ν = e_vals.vectors\n    if vecs\n        return λ, ν\n    else\n        return λ\n    end\nend\nfunction algConnectivity(L::SparseMatrixCSC;vecs=false)\n    # Calculates the algebraic connectivity of graph with laplacian L\n    # Input: L a symmetric laplacian matrix\n    s = svds(L)\n    # Output: value of algebraic connectivity λ_2\n    λ = s[2][end-1]\n    ν = s[1][:,end-1]\n    if vecs\n        return λ, ν\n    else\n        return λ\n    end\nend\n@time connectivity = algConnectivity(lapsp,vecs=false)\nprintln(size(lap))\nprintln(typeof(lap))\nplot(g)\nissym(laps)\nlaps.data[3,1] = 90\nlaps.uplo\ns = svds(lapsp)\ns[1]\nsv = svd(full(lapsp))\nsvt = svdfact(full(lapsp))\n", "meta": {"hexsha": "4e71e001f86fa178923eb4941561ef2d0bf2a708", "size": 1117, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "graphTest.jl", "max_stars_repo_name": "bisraelsen/algebraic_connectivity", "max_stars_repo_head_hexsha": "480c85026da5432a5faa96d3e84a9ce8a2e10149", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "graphTest.jl", "max_issues_repo_name": "bisraelsen/algebraic_connectivity", "max_issues_repo_head_hexsha": "480c85026da5432a5faa96d3e84a9ce8a2e10149", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphTest.jl", "max_forks_repo_name": "bisraelsen/algebraic_connectivity", "max_forks_repo_head_hexsha": "480c85026da5432a5faa96d3e84a9ce8a2e10149", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7659574468, "max_line_length": 69, "alphanum_fraction": 0.6830796777, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172688214138, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7667889311155854}}
{"text": "# Code here taken from\n# http://www.visiondummy.com/2014/04/draw-error-ellipse-representing-covariance-matrix/\n\n##########################################################\nfunction plot_ellipse(q::AbstractMvNormal, clr=\"b\", label=\"\"; alpha=1.0)\n##########################################################\n    plot_ellipse(mean(q), cov(q), clr, label; alpha=alpha)\nend\n\n##########################################################\nfunction plot_ellipse(μ, Σ, clr=\"b\", label=\"\"; alpha=1.0)\n##########################################################\n\n    # calculate eigevanlues\n    E = eigvals(Σ)\n    @assert(E[1]<=E[2])\n\n    # calculate eigenvectors, columns are the eigenvectors\n    V = eigvecs(Σ)\n\n    ϕ = atan(V[2,2], V[1,2]) # was atan2\n\n    if(ϕ < 0.0)\n        ϕ = ϕ + 2*pi;\n    end\n\n    chisquare_val = sqrt(2.41) # 70% confidence interval\n    theta_grid    = LinRange(0.0, 2*pi, 500)\n    a = chisquare_val*sqrt(maximum(E))\n    b = chisquare_val*sqrt(minimum(E))\n\n    # the ellipse in x and y coordinates\n    ellipse_x_r  = a*cos.( theta_grid )\n    ellipse_y_r  = b*sin.( theta_grid )\n\n    # Define a rotation matrix\n    R = [ cos.(ϕ) sin.(ϕ); -sin.(ϕ) cos.(ϕ) ];\n\n\n    # let's rotate the ellipse to angle ϕ\n    r_ellipse = [ellipse_x_r ellipse_y_r]  * R\n\n    PyPlot.plot(μ[1], μ[2], \"x\", markersize=12, markeredgewidth=4, color=clr, alpha=alpha)\n    PyPlot.plot(r_ellipse[:,1] .+ μ[1], r_ellipse[:,2] .+ μ[2], clr, linewidth=1, label=label, alpha=alpha)\n\n    # plot ellipse axis (eigenvectors)\n    a_pnts = [vec(LinRange(0.0, a, 500))  vec(LinRange(0.0, a, 500))*0.0    ]*R\n    b_pnts = [vec(LinRange(0.0, b, 500))*0.0      vec(LinRange(0.0, b, 500))]*R\n    PyPlot.plot(a_pnts[:,1] .+ μ[1], a_pnts[:,2] .+ μ[2], @sprintf(\"--%s\",clr), linewidth=2, alpha=alpha)\n    PyPlot.plot(b_pnts[:,1] .+ μ[1], b_pnts[:,2] .+ μ[2], @sprintf(\"--%s\",clr), linewidth=2, alpha=alpha)\n\nend\n", "meta": {"hexsha": "f01c76bf3460e091be6b6bb97859f044842febf3", "size": 1873, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/plot_ellipse.jl", "max_stars_repo_name": "ngiann/MiscUtil.jl", "max_stars_repo_head_hexsha": "62bb259ae41ffa2f2eaf4c55142523238995919e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/plot_ellipse.jl", "max_issues_repo_name": "ngiann/MiscUtil.jl", "max_issues_repo_head_hexsha": "62bb259ae41ffa2f2eaf4c55142523238995919e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-22T10:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T10:56:15.000Z", "max_forks_repo_path": "src/util/plot_ellipse.jl", "max_forks_repo_name": "ngiann/ApproximateVI.jl", "max_forks_repo_head_hexsha": "61b08c374eb419aeb65ccb23706ac8352d0b46df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3396226415, "max_line_length": 107, "alphanum_fraction": 0.5355045382, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875642, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7667889276135437}}
{"text": "# ---\n# title: 295. Find Median from Data Stream\n# id: problem295\n# author: zhwang\n# date: 2022-02-26\n# difficulty: Hard\n# categories: Heap, Design\n# link: <https://leetcode.com/problems/find-median-from-data-stream/description/>\n# hidden: true\n# ---\n# \n# Median is the middle value in an ordered integer list. If the size of the list\n# is even, there is no middle value. So the median is the mean of the two middle\n# value.\n# \n# For example,\n# \n# `[2,3,4]`, the median is `3`\n# \n# `[2,3]`, the median is `(2 + 3) / 2 = 2.5`\n# \n# Design a data structure that supports the following two operations:\n# \n#   * void addNum(int num) - Add a integer number from the data stream to the data structure.\n#   * double findMedian() - Return the median of all elements so far.\n# \n# \n# \n# **Example:**\n# \n#     \n#     \n#     addNum(1)\n#     addNum(2)\n#     findMedian() -> 1.5\n#     addNum(3) \n#     findMedian() -> 2\n#     \n# \n# \n# \n# **Follow up:**\n# \n#   1. If all integer numbers from the stream are between 0 and 100, how would you optimize it?\n#   2. If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?\n# \n# \n## @lc code=start\nusing LeetCode\n\nusing DataStructures\n\nBase.@kwdef struct MedianFinder\n    maxheap::BinaryMaxHeap{Int} = BinaryMaxHeap{Int}()\n    minheap::BinaryMinHeap{Int} = BinaryMinHeap{Int}()\nend\n## function Base.show(io::IO, heap::MedianFinder)\n##     return print(io, \"$(heap.maxheap.valtree):max -- min:$(reverse(heap.minheap.valtree))\")\n## end\n\nfunction add_num!(heap::MedianFinder, num::Int)\n    ## maximal element of maxheap <= minimal element of minheap\n    ## length of maxheap <= length of minheap\n    hi, ha = heap.minheap, heap.maxheap\n    if length(ha) < length(hi)\n        ## e.g. [2]--[4,5] =6> [2]--[4,5,6] => [2,4]--[5,6]\n        push!(hi, num)\n        push!(ha, pop!(hi))\n    else\n        ## e.g. [4]--[5] =2> [2,4]--[5] => [2]--[4,5]\n        push!(ha, num)\n        push!(hi, pop!(ha))\n    end\n    return nothing\nend\n\nfunction find_median(heap::MedianFinder)::Float64\n    hi, ha = heap.minheap, heap.maxheap\n    return length(hi) == length(ha) ? (first(hi) + first(ha)) / 2 : first(hi)\nend\n## @lc code=end\n", "meta": {"hexsha": "773aac77c3e839e08630eca0595eb3c80c06f6cb", "size": 2175, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/295.find-median-from-data-stream.jl", "max_stars_repo_name": "RexWzh/LeetCode.jl", "max_stars_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/295.find-median-from-data-stream.jl", "max_issues_repo_name": "RexWzh/LeetCode.jl", "max_issues_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/295.find-median-from-data-stream.jl", "max_forks_repo_name": "RexWzh/LeetCode.jl", "max_forks_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5243902439, "max_line_length": 102, "alphanum_fraction": 0.6183908046, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7667782052352667}}
{"text": "module Chebyshev\n\nusing FFTW\nusing Future: copy!\n\nimport Base: *, \\\nstruct Transform{T,I}\n    dct!::FFTW.r2rFFTWPlan{T,(3,),true,1}\nend\n\nfunction plan_transform!(x::Vector{T}) where T\n    Transform{T,true}(FFTW.plan_r2r!(x, FFTW.REDFT00))\nend\n\nfunction plan_transform(x::Vector{T}) where T\n    Transform{T,false}(FFTW.plan_r2r!(x, FFTW.REDFT00))\nend\n\n(C::Transform{T,true}  * x::Vector{T}) where T = transform!(x, C.dct!)\n(C::Transform{T,false} * x::Vector{T}) where T = transform(x, C.dct!)\n(C::Transform{T,true}  \\ A::Vector{T}) where T = inv_transform!(A, C.dct!)\n(C::Transform{T,false} \\ A::Vector{T}) where T = inv_transform(A, C.dct!)\n\n\"\"\"\n    Chebyshev.nodes(N, T = Float64)\n\nGives `N` extrema Chebyshev points of type `T` in [-1 ,1].\n\"\"\"\nfunction nodes(N, T = Float64)\n    T[cos(θ) for θ in range(π, 0, length=N)]\nend\n\n\"\"\"\n    Chebyshev.firstkind(C, s[, offset = 0])\n\nEvaluate a Chebyshev series of the first kind.\n\n# Arguments\n\n- `C`: a vector with the coefficients of the series\n- `s`: a scalar or an array of evaluation points ∈ [-1, 1]\n- `offset`: an optional starting index of the series summation\n\"\"\"\nfirstkind(A, ss, offset = 0) = [firstkind(A, s, offset) for s in ss]\nfunction firstkind(A::AbstractArray{C}, s::S, offset = 0)::C where {C,S <: Real}\n    -1 ≤ s ≤ 1 || throw(DomainError(\"s ∉ [-1,1]\"))\n    T₋ = s\n    T  = one(S)\n\n    for i in 1:offset\n        T₋, T = T, 2s*T - T₋\n    end\n\n    N = length(A)\n    f = zero(C)\n    for i in 1+offset:N\n        f += A[i]*T\n        T₋, T = T, 2s*T - T₋\n    end\n    f\nend\n\n\"\"\"\n    Chebyshev.secondkind(C, s[, offset = 0])\n\nEvaluate a Chebyshev series of the second kind.\n\n# Arguments\n\n- `C`: a vector with the coefficients of the series\n- `s`: a scalar or an array of evaluation points ∈ [-1, 1]\n- `offset`: an optional starting index of the series summation\n\"\"\"\nsecondkind(C, ss, offset = 0) = [secondkind(C, s, offset) for s in ss]\nfunction secondkind(A::AbstractArray{C}, s::S, offset = 0)::C where {C,S <: Real}\n    -1 ≤ s ≤ 1 || throw(DomainError(\"s ∉ [-1,1]\"))\n    U₋ = zero(s)\n    U  = one(S)\n\n    for i in 1:offset\n        U₋, U = U, 2s*U - U₋\n    end\n\n    N = length(A)\n    f = zero(C)\n    for i in 1+offset:N\n        f += A[i]*U\n        U₋, U = U, 2s*U - U₋\n    end\n    f\nend\n\n\"\"\"\n    Chebyshev.transform(x[, plan!])\n\nCompute the discrete Chebyshev transform of `x`.\n\n# Arguments\n\n- `x`: samples of a function distributed along [extrema Chebyshev nodes](@ref Chebyshev.nodes)\n- `plan!`: an optional pre-planned in-place DCT-I used to compute the transform\n\"\"\"\nfunction transform(x, plan! = FFTW.plan_r2r!(x, FFTW.REDFT00))\n    C = copy(x)\n    transform!(C, plan!)\nend\n\n\"\"\"\n    Chebyshev.transform!(A,[ x, plan!])\n\nCompute the discrete Chebyshev transform of `x` in-place.\n\n# Arguments\n\n- `A`: the output vector (also the input vector if `x` is omitted)\n- `x`: an optional input vector with samples of a function distributed\n  along [extrema Chebyshev nodes](@ref Chebyshev.nodes)\n- `plan!`: an optional pre-planned in-place DCT-I used to compute the transform\n\"\"\"\nfunction transform!(x, plan! = FFTW.plan_r2r!(x, FFTW.REDFT00))\n    N = length(x)\n    if N != length(plan!)\n        throw(BoundsError(\"`x` must have the same size as the preplanned DCT\"))\n    end\n\n    plan!*x\n\n    s = 1/(N-1)\n\n    @inbounds begin\n        for n in 2:2:N\n            x[n-1] *= s\n            x[n]   *= -s\n        end\n        if isodd(N)\n            x[N] *= s\n        end\n\n        x[1] /= 2\n        x[N] /= 2\n    end\n\n    x\nend\n\nfunction transform!(A::T, x::T, plan! = FFTW.plan_r2r!(x, FFTW.REDFT00)) where T\n    copy!(A, x)\n    transform!(A, plan!)\nend\n\n\"\"\"\n    Chebyshev.inv_transform(A[, plan!])\n\nPerform the inverse Chebyshev transform.\n\nThis is the inverse of [`Chebyshev.transform`](@ref).\n\n# Fields\n\n- `A`: the coefficients of a Chebyshev series\n- `plan!`: an optional pre-planned in-place DCT-I used to compute the transform\n\"\"\"\nfunction inv_transform(A, plan! = FFTW.plan_r2r!(A, FFTW.REDFT00))\n    x = copy(A)\n    inv_transform!(x, plan!)\nend\n\n\"\"\"\n    Chebyshev.inv_transform!(x, [C, plan!)\n\nPerform the inverse Chebyshev transform in place.\n\nThis is the inverse of [`Chebyshev.transform!`](@ref)\n\n# Arguments\n\n- `x`: the output vector to store the reconstructed function with\n  points distributed along extrema Chebyshev nodes (also the input\n  vector if `A` is omitted)\n- `A`: an optional input vector with coefficients of a Chebyshev series\n- `plan!`: an optional pre-planned in-place DCT-I used to compute the transform\n\"\"\"\nfunction inv_transform!(A, plan! = FFTW.plan_r2r!(A, FFTW.REDFT00))\n    N = length(A)\n    if N != length(plan!)\n        throw(BoundsError(\"`A` must have the same size as the preplanned DCT\"))\n    end\n\n    @inbounds begin\n        for n in 2:2:N-2\n            A[n]   *= -0.5\n            A[n+1] *=  0.5\n        end\n        if iseven(N)\n            A[N] *= -1\n        else\n            A[N-1] *= -0.5\n        end\n    end\n\n    plan!*A\nend\n\nfunction inv_transform!(x::T, A::T, plan! = FFTW.plan_r2r!(A, FFTW.REDFT00)) where T\n    copy!(x, A)\n    Chebyshev.inv_transform!(x, plan!)\nend\n\n\n\"\"\"\n    clenshaw_curtis_weights(N)\n\nReturns the `N` weights used in the Clenshaw Curtis quadrature\n\"\"\"\nfunction clenshaw_curtis_weights(N)\n    n = N - 1\n    w = zeros(N)\n\n    # Unlike the documentation, we move the 1/(N-1)\n    # factor inside the r vector.\n    w[1] = 1.0/n\n    for k in 2:2:n\n        w[k+1] = (1.0 + (-1)^k)/(1 - k^2)/n\n    end\n\n    # Scale by S\n    w[1] *= 2; w[N] *= 2\n    # Multiply by D\n    FFTW.r2r!(w, FFTW.REDFT00)\n    # Scale by S⁻¹\n    w[1] /= 2; w[N] /= 2\n\n    return w\nend\n\nend\n", "meta": {"hexsha": "eed06c2d4ac1b1fc8ab718bc2d5d3f632128d1dc", "size": 5569, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/elements/plates/chebyshev.jl", "max_stars_repo_name": "JuliaTagBot/PotentialFlow.jl", "max_stars_repo_head_hexsha": "553d4cd63d19da79bc2b8f83dca0100be5a49d2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/elements/plates/chebyshev.jl", "max_issues_repo_name": "JuliaTagBot/PotentialFlow.jl", "max_issues_repo_head_hexsha": "553d4cd63d19da79bc2b8f83dca0100be5a49d2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/elements/plates/chebyshev.jl", "max_forks_repo_name": "JuliaTagBot/PotentialFlow.jl", "max_forks_repo_head_hexsha": "553d4cd63d19da79bc2b8f83dca0100be5a49d2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4978902954, "max_line_length": 94, "alphanum_fraction": 0.6044173101, "num_tokens": 1858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7667781960124772}}
{"text": "\"\"\"\nCalculate the best-efficiency point (BEP) for the pumps in the water network. The BEP flow,\nhead, and power are added to the pumps' dictionaries.\n\"\"\"\nfunction calc_pump_bep!(data::Dict{String,<:Any})\n    for (pump_id, pump) in data[\"pump\"]\n        q_bep = NaN\n\n        # Calculate best efficiency point efficiencies.\n        if haskey(pump, \"efficiency_curve\")\n            eff_curve_tuples = pump[\"efficiency_curve\"]\n            eff_curve = array_from_tuples(eff_curve_tuples)\n            \n            # fit efficiency curve to determine q_bep and eta_bep\n            A = hcat(eff_curve[:, 1].^2, eff_curve[:, 1])\n            a, b = A \\ eff_curve[:, 2]\n            q_bep, eta_bep = -0.5*b * inv(a), -0.25*b^2 * inv(a)\n        else\n            # presume the single-value for efficiency is at the BEP\n            eta_bep = pump[\"efficiency\"]\n        end\n\n        # Calculate best efficiency point head gains.\n        head_curve_tuples = pump[\"head_curve\"]\n        head_curve = array_from_tuples(head_curve_tuples)\n\n        if isnan(q_bep)\n            # an efficiency curve was not provided, and so we must determine q_bep from the\n            # head curve\n            if size(head_curve)[1] == 1\n                q_bep, g_bep = head_curve[1, 1], head_curve[1, 2]\n            else\n                A = hcat(head_curve[:, 1].^2, ones(size(head_curve, 1)))\n                c, d = A \\ head_curve[:, 2]\n                q_bep, g_bep = sqrt(-0.25 * d * inv(c)), 0.75 * d\n            end    \n        else\n            if size(head_curve)[1] == 1\n                # probably rare that there is an efficiency curve and single-point or no head\n                # curve -- nonetheless, it is a corner case that may be worth investigating\n                # because q_bep would be overdetermined, and the two values may not agree\n                #q_bep_alt = head_curve[1,1]\n                g_bep = head_curve[1, 2]\n            else\n                # we could determine q_bep from the head curve and check wether it agrees\n                # with the value determined from the efficiency curve -- will presume that\n                # the one from the efficiency curve is more accurate\n                A = -inv(3.0) * inv(q_bep^2) * head_curve[:, 1].^2 .+ (4.0 * inv(3.0))\n                g_bep = A \\ head_curve[:, 2]\n            end\n        end\n        \n        # Power at the BEP (1000 and 9.80665 are density and gravity).\n        p_bep = _WM._DENSITY * _WM._GRAVITY * inv(eta_bep) * g_bep * q_bep\n\n        # Add BEP values to the pump dictionary.\n        pump[\"q_bep\"] = q_bep\n        pump[\"g_bep\"] = g_bep\n        pump[\"eta_bep\"] = eta_bep\n        pump[\"p_bep\"] = p_bep\n    end\nend\n", "meta": {"hexsha": "612d92e4ecc2ee90d95e43bf5338171217cf0912", "size": 2667, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/analysis/pump_bep.jl", "max_stars_repo_name": "NREL-SIIP/WaterModelsAnalytics.jl", "max_stars_repo_head_hexsha": "dff18c644546cb0087bf5ca2569845fe7b9a84f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-10-15T15:40:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-19T19:44:03.000Z", "max_issues_repo_path": "src/analysis/pump_bep.jl", "max_issues_repo_name": "NREL-SIIP/WaterModelsAnalytics.jl", "max_issues_repo_head_hexsha": "dff18c644546cb0087bf5ca2569845fe7b9a84f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2020-08-16T23:08:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T18:07:03.000Z", "max_forks_repo_path": "src/analysis/pump_bep.jl", "max_forks_repo_name": "NREL-SIIP/WaterModelsAnalytics.jl", "max_forks_repo_head_hexsha": "dff18c644546cb0087bf5ca2569845fe7b9a84f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-08-16T23:01:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T16:49:06.000Z", "avg_line_length": 42.3333333333, "max_line_length": 93, "alphanum_fraction": 0.5601799775, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474207360067, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7667478020901606}}
{"text": "#=\n---------------------------------------------------------------------\nThis function computes the Metric Terms for General 3D Hexahedral Grids.\n\nThe strategy follows Algorithm 12.4 and 12.5 in F.X. Giraldo's Introduction to Element-based \nGalerkin Methods using Tensor-Product Bases: Analysis, Algorithms, and Applications.\nHere, we use the cross-product metric terms. As an exercise the student may be asked to build the \nCurl-Invariant metric terms.\n\nWritten by F.X. Giraldo on 7/2021\n           Department of Applied Mathematics\n           Naval Postgraduate School\n           Monterey; CA 93943-5216\n---------------------------------------------------------------------\n=#\n\ninclude(\"map_deriv.jl\")\n\nfunction compute_metrics(coord,intma,ψ,dψ,Ne,Np,Nq,DFloat)\n\n    #Initialize Global Arrays\n    ξ_x=zeros(DFloat,Nq,Nq,Nq,Ne)\n    ξ_y=zeros(DFloat,Nq,Nq,Nq,Ne)\n    ξ_z=zeros(DFloat,Nq,Nq,Nq,Ne)\n    η_x=zeros(DFloat,Nq,Nq,Nq,Ne)\n    η_y=zeros(DFloat,Nq,Nq,Nq,Ne)\n    η_z=zeros(DFloat,Nq,Nq,Nq,Ne)\n    ζ_x=zeros(DFloat,Nq,Nq,Nq,Ne)\n    ζ_y=zeros(DFloat,Nq,Nq,Nq,Ne)\n    ζ_z=zeros(DFloat,Nq,Nq,Nq,Ne)\n    jac=zeros(DFloat,Nq,Nq,Nq,Ne)\n\n    #Initialize Local Arrays\n    x=zeros(DFloat,Np,Np,Np)\n    y=zeros(DFloat,Np,Np,Np)\n    z=zeros(DFloat,Np,Np,Np)\n\n    #loop thru the elements\n    for e=1:Ne\n\n        #Store Element Variables\n        for k=1:Np, j=1:Np, i=1:Np\n            I=intma[i,j,k,e]\n            x[i,j,k]=coord[1,I]\n            y[i,j,k]=coord[2,I]\n            z[i,j,k]=coord[3,I]\n        end #j\n\n        #Construct Mapping Derivatives: dx/dξ; dx/dη; dy/dξ; dy/dη\n        (x_ξ,x_η,x_ζ)=map_deriv(ψ,dψ,x,Np,Nq,DFloat)\n        (y_ξ,y_η,y_ζ)=map_deriv(ψ,dψ,y,Np,Nq,DFloat)\n        (z_ξ,z_η,z_ζ)=map_deriv(ψ,dψ,z,Np,Nq,DFloat)\n\n        #Construct Inverse Mapping: dξ/dx; dξ/dy; dη/dx; dη/dy\n        for k=1:Nq, j=1:Nq, i=1:Nq\n            xj = (x_ξ[i,j,k]*y_η[i,j,k]*z_ζ[i,j,k] - x_ξ[i,j,k]*y_ζ[i,j,k]*z_η[i,j,k]) -\n            (y_ξ[i,j,k]*x_η[i,j,k]*z_ζ[i,j,k] - y_ξ[i,j,k]*x_ζ[i,j,k]*z_η[i,j,k]) +\n            (z_ξ[i,j,k]*x_η[i,j,k]*y_ζ[i,j,k] - z_ξ[i,j,k]*x_ζ[i,j,k]*y_η[i,j,k])  \n\n            ξ_x[i,j,k,e]= (y_η[i,j,k]*z_ζ[i,j,k]-y_ζ[i,j,k]*z_η[i,j,k])/xj\n            ξ_y[i,j,k,e]=-(x_η[i,j,k]*z_ζ[i,j,k]-x_ζ[i,j,k]*z_η[i,j,k])/xj\n            ξ_z[i,j,k,e]= (x_η[i,j,k]*y_ζ[i,j,k]-x_ζ[i,j,k]*y_η[i,j,k])/xj\n            η_x[i,j,k,e]=-(y_ξ[i,j,k]*z_ζ[i,j,k]-y_ζ[i,j,k]*z_ξ[i,j,k])/xj\n            η_y[i,j,k,e]= (x_ξ[i,j,k]*z_ζ[i,j,k]-x_ζ[i,j,k]*z_ξ[i,j,k])/xj\n            η_z[i,j,k,e]= -(x_ξ[i,j,k]*y_ζ[i,j,k]-x_ζ[i,j,k]*y_ξ[i,j,k])/xj\n            ζ_x[i,j,k,e]= (y_ξ[i,j,k]*z_η[i,j,k] -y_η[i,j,k]*z_ξ[i,j,k])/xj\n            ζ_y[i,j,k,e]=-(x_ξ[i,j,k]*z_η[i,j,k] -x_η[i,j,k]*z_ξ[i,j,k])/xj\n            ζ_z[i,j,k,e]= (x_ξ[i,j,k]*y_η[i,j,k] -x_η[i,j,k]*y_ξ[i,j,k])/xj   \n            jac[i,j,k,e]=abs(xj)      \n        end #i, j, k\n    end #e\n\n    return (ξ_x,ξ_y,ξ_z,η_x,η_y,η_z,ζ_x,ζ_y,ζ_z,jac)\nend\n", "meta": {"hexsha": "1ec0540b5169d545564910f42a32e2a1f85b4fad", "size": 2900, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Projects/Project_07_3D_Elliptic/For_Students/julia/compute_metrics.jl", "max_stars_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_stars_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-12-28T06:19:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:40:33.000Z", "max_issues_repo_path": "Projects/Project_07_3D_Elliptic/For_Students/julia/compute_metrics.jl", "max_issues_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_issues_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-29T19:12:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-29T21:53:41.000Z", "max_forks_repo_path": "Projects/Project_07_3D_Elliptic/For_Instructors/julia/compute_metrics.jl", "max_forks_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_forks_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:35:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T06:53:34.000Z", "avg_line_length": 38.6666666667, "max_line_length": 98, "alphanum_fraction": 0.5368965517, "num_tokens": 1255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9546474181553805, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7667477977686448}}
{"text": "\"\"\"\nContains functions for generating matrices with correlated or motif structure\n\"\"\"\n\nusing LinearAlgebra\nimport Random.MersenneTwister\n\n#------------------------------------------------------------------------------\n\n\n\"\"\"\n\tgenerate_nv(N::Int64, T::Type; seed=nothing)\n\nReturns a vector with entries i.i.d. on a zero-mean, unit-variance Gaussian\n\"\"\"\nfunction generate_nv(N::Int64, T::Type; seed=nothing)\n\n\t@assert T<:AbstractFloat \"T must be a floating point type\"\n\trng = MersenneTwister(seed)\n\n\treturn randn(rng, T, N)\nend\n\n\n\"\"\"\n\tgenerate_ONB(N::Int64, T::Type; seed=nothing)\n\nReturns a random unitary matrix\n\"\"\"\nfunction generate_ONB(N::Int64, T::Type; seed=nothing)\n\n\t@assert T<:AbstractFloat \"T must be a floating point type\"\n\trng = MersenneTwister(seed)\n\tZ = randn(rng, T, N, N)\n\tF = qr!(Z)\n\n\treturn F.Q * diagm(0 => sign.(diag(F.R)))\nend\n\n\n\n\"\"\"\n\tgenerate_J(N::Int64, eta::T; seed=nothing) where T <: AbstractFloat\n\nReturns a `N x N` Gaussian matrix with correlation between entries opposite the\ndiagonal equal to `eta` and diagonal entries themselves equal to `0`.\n\nEntries of the matrix are scaled `sqrt(N)`.\n\"\"\"\nfunction generate_J(N::Int64, eta::T; seed=nothing) where T <: AbstractFloat\n\n\trng = MersenneTwister(seed)\n\n\tJ = zeros(T, N, N)\n\tM = [convert(T, 1)     convert(T, 0);\n\t\t eta               sqrt(1-eta^2)]\n\tfor j in 1:N-1\n\t\tfor i in j+1:N\n\t\t\t(J[i,j], J[j,i]) = M * randn(rng, T, 2)\n\t\tend\n\tend\n\n\treturn J ./ convert(T, sqrt(N))\nend\n\n\n\n\"\"\"\n\tgenerate_motif_P(N::Int64, kcon::T, kdiv::T, kchn::T; seed=nothing,\n\t\tno_autapses=true) where T <: AbstractFloat\n\nReturns a rank-2 perturbation matrix that introduces converging, diverging, and\nchain motifs when added to a dense random Gaussian matrix.\n\nIn dense Gaussian networks, motifs are interpreted as covariances between\nsynapses that share presynaptic or postsynaptic units. Use care when adding\nperurbations to partially symmetric or antisymmetric matrices, as the final\nsymmetry depends on both the eta and kchn parameters.\n\"\"\"\nfunction generate_motif_P(N::Int64, kcon::T, kdiv::T, kchn::T; seed=nothing,\n\t\tno_autapses=true) where T <: AbstractFloat\n\n\t@assert kchn^2<=kcon*kdiv \"κchn^2 cannot exceed κdiv*κcon\"\n\t@assert kcon>=0 \"Negative κcon is not allowed\"\n\t@assert kdiv>=0 \"Negative κdiv is not allowed\"\n\t@assert kchn>=0 \"Negative κchn is not allowed\"\n\n\trng = MersenneTwister(seed)\n\n\tif kcon == 0\n\t\tM = randn(rng, T, 2, N)\n\t\ta = zeros(N)\n\t\tb = sqrt(kdiv) .* reshape(M[2,:], (1, N))\n\telse\n\t\tM = [sqrt(kcon)          convert(T, 0);\n\t\t\t kchn/sqrt(kcon)     sqrt(max(0, kdiv - kchn^2/kcon))]\n\t\tM *= randn(rng, T, 2, N)\n\t\ta = M[1,:]\n\t\tb = reshape(M[2,:], (1, N))\n\tend\n\n\tP = a .+ b\n\n\tif no_autapses\n\t\tP[diagind(P)] .= 0\n\tend\n\n\treturn P ./ convert(T, sqrt(N))\nend\n\n\n\n\"\"\"\n\tgenerate_outlier_P(N::Int64, re::T, im::T, alpha::T; seed=nothing,\n\t\tno_autapses=true) where T <: AbstractFloat\n\nReturns a rank-2 perturbation matrix that, when added to a random Gaussian\nmatrix, introduces a conjugate pair of outlier eigenvalues with given expected\nreal and imaginary parts.\n\nThe `alpha` parameter controls the strength of the uncorrelated components of\nthe outer product perturbations. This does not affect the expected value of the\nreal and imaginary parts.\n\"\"\"\nfunction generate_outlier_P(N::Int64, re::T, im::T, alpha::T; seed=nothing,\n\t\tno_autapses=true) where T <: AbstractFloat\n\n\t@assert re>0 \"Real part of outliers must be positive\"\n\n\tgamma = 2 * sqrt(1 /(1 + im^2 / re^2))\n\trho = sqrt(2 * re / gamma)\n\n\trng = MersenneTwister(seed)\n\tx1 = randn(rng, T, N)\n\tx2 = randn(rng, T, N)\n\tx3 = randn(rng, T, N)\n\tx4 = randn(rng, T, N)\n\ty1 = randn(rng, T, N)\n\ty2 = randn(rng, T, N)\n\n\tm1 = alpha .* x1 .+ rho .* y1\n\tm2 = alpha .* x2 .+ rho .* y2\n\tn1 = alpha .* x3 .+ rho .* y2 .+ rho * gamma .* y1\n\tn2 = alpha .* x4 .- rho .* y1\n\n\tP = m1 * n1' .+ m2 * n2'\n\n\tif no_autapses\n\t\tP[diagind(P)] .= 0\n\tend\n\n\treturn P ./ N\nend\n", "meta": {"hexsha": "a2d892bab7c68f81e5ab8e10e45a476b1bd8e24b", "size": 3867, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code/processing/31-Aug-21_Lspecs_small_g/random_matrices.jl", "max_stars_repo_name": "mattding20/RateNet-Lyapunov", "max_stars_repo_head_hexsha": "e2de8b6daa3db1e2d14fad9d219560e4f531d67d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/processing/31-Aug-21_Lspecs_small_g/random_matrices.jl", "max_issues_repo_name": "mattding20/RateNet-Lyapunov", "max_issues_repo_head_hexsha": "e2de8b6daa3db1e2d14fad9d219560e4f531d67d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/processing/31-Aug-21_Lspecs_small_g/random_matrices.jl", "max_forks_repo_name": "mattding20/RateNet-Lyapunov", "max_forks_repo_head_hexsha": "e2de8b6daa3db1e2d14fad9d219560e4f531d67d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1103896104, "max_line_length": 79, "alphanum_fraction": 0.6614946987, "num_tokens": 1209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7666621791983127}}
{"text": "struct Rp\n    T::Matrix{Float64}\n    P\nend\n\n\"\"\"\n    rpmat_gauss(p, nlv)\nBuild a gaussian random projection matrix.\n* `p` : Nb. variables (attributes) to project.\n* `nlv` : Nb. final dimensions, i.e. after projection.\n\nThe function returns a random projection matrix P of dimension \n`p` x `nlv` simulated from i.i.d. N(0, 1)/sqrt(`a`).\n\n## References \n\nLi, P., Hastie, T.J., Church, K.W., 2006. Very sparse random projections, \nin: Proceedings of the 12th ACM SIGKDD International Conference on Knowledge \nDiscovery and Data Mining, KDD ’06. Association for Computing Machinery,\nNew York, NY, USA, pp. 287–296. https://doi.org/10.1145/1150402.1150436\n\"\"\" \nfunction rpmat_gauss(p, nlv)\n    randn(p, nlv) / sqrt(nlv)\nend\n\n\n\"\"\"\n    rpmat_li(p, nlv; s = sqrt(p))\nBuild a sparse random projection matrix (Achlioptas 2001, Li et al. 2006).\n* `p` : Nb. variables (attributes) to project.\n* `nlv` : Nb. final dimensions, i.e. after projection.\n* `s` : Coefficient defining the sparsity of the returned matrix \n    (higher is `s`, higher is the sparsity).\n\nThe function returns a random projection matrix P of dimension \n`p` x `nlv` simulated from i.i.d. p_ij = \n* 1 with prob. 1/(2 * `s`)\n* 0 with prob. 1 - 1 / `s`\n* -1 with prob. 1/(2 * `s`)\n\nUsual values for `s` are:\n* sqrt(`p`)       (Li et al. 2006)\n* `p` / log(`p`)  (Li et al. 2006)\n* 1               (Achlioptas 2001)\n* 3               (Achlioptas 2001) \n\n## References \n\nAchlioptas, D., 2001. Database-friendly random projections, \nin: Proceedings of the Twentieth ACM SIGMOD-SIGACT-SIGART Symposium on \nPrinciples of Database Systems, PODS ’01. Association for Computing Machinery, \nNew York, NY, USA, pp. 274–281. https://doi.org/10.1145/375551.375608\n\nLi, P., Hastie, T.J., Church, K.W., 2006. Very sparse random projections, \nin: Proceedings of the 12th ACM SIGKDD International Conference on Knowledge \nDiscovery and Data Mining, KDD ’06. Association for Computing Machinery,\nNew York, NY, USA, pp. 287–296. https://doi.org/10.1145/1150402.1150436\n\"\"\" \nfunction rpmat_li(p, nlv; s = sqrt(p))\n    le = p * nlv\n    k = Int64(round(le / s))\n    z = zeros(le)\n    z[rand(1:le, k)] .= rand([-1. ; 1], k) \n    sparse(reshape(z, p, nlv))\nend\n\n\"\"\"\n    rp(X; nlv, fun = rpmat_li, kwargs ...)\nMake a random projection of matrix X.\n* `X` : X-data to project.\n* `nlv` : Nb. dimensions on which `X` is projected.\n* `fun` : A function of random projection.\n* `kwargs` : Optional arguments of function `fun`.\n\"\"\" \nfunction rp(X; nlv, fun = rpmat_li, kwargs ...)\n    X = ensure_mat(X)\n    P = fun(size(X, 2), nlv; kwargs...)\n    T = X * P\n    Rp(T, P)\nend\n\n\"\"\" \n    transform(object::Rp, X; nlv = nothing)\nCompute \"scores\" T from a random projection model and a matrix X.\n* `object` : The random projection model.\n* `X` : Matrix (m, p) for which LVs are computed.\n* `nlv` : Nb. dimensions to consider. If nothing, it is the maximum nb. dimensions.\n\"\"\" \nfunction transform(object::Rp, X; nlv = nothing)\n    a = size(object.T, 2)\n    isnothing(nlv) ? nlv = a : nlv = min(nlv, a)\n    X * vcol(object.P, 1:nlv)\nend\n\n", "meta": {"hexsha": "73228df239bae73bd655e5f161077ab3f0a1f267", "size": 3052, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rp.jl", "max_stars_repo_name": "mlesnoff/Jchemo.jl", "max_stars_repo_head_hexsha": "fea8da15c0458c0e68921cda55a5bf448170eb53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rp.jl", "max_issues_repo_name": "mlesnoff/Jchemo.jl", "max_issues_repo_head_hexsha": "fea8da15c0458c0e68921cda55a5bf448170eb53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rp.jl", "max_forks_repo_name": "mlesnoff/Jchemo.jl", "max_forks_repo_head_hexsha": "fea8da15c0458c0e68921cda55a5bf448170eb53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1263157895, "max_line_length": 83, "alphanum_fraction": 0.6549803408, "num_tokens": 988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317103, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.766662176519151}}
{"text": "mutable struct Edge\n    rev::Int\n    from::Int\n    to::Int\n    cap::Int\nend\n\nfunction push!(G::Vector{Vector{Edge}}, from, to, cap)\n    fromrev = length(G[from]) + 1\n    torev = length(G[to]) + 1\n    Base.push!(G[from], Edge(torev, from, to, cap))\n    Base.push!(G[to], Edge(fromrev, to, from, 0))\nend\n\nfunction run_flow!(G::Vector{Vector{Edge}}, e::Edge, f)\n    e.cap -= f\n    G[e.to][e.rev].cap += f\n    return G\nend\n\nfunction fodfs(G, v, t, f, seens)\n    v == t && return f\n\n    seens[v] = true\n    for e ∈ G[v]\n        if seens[e.to] || e.cap == 0\n            # Skip\n        else\n            flow = fodfs(G, e.to, t, min(f, e.cap), seens)\n            if flow == 0\n                # Skip\n            else\n                run_flow!(G, e, flow)\n                return flow\n            end\n        end\n    end\n\n    return 0\nend\n\nfunction FordFulkerson(G, s, t)\n    INF = 10^9\n    res = 0\n\n    while true\n        flow = fodfs(G, s, t, INF, falses(length(G)))\n        if flow == 0\n            return res\n        else\n            res += flow\n        end\n    end\n\n    return 0\nend\n\n\nfunction main()\n    N, G, E = parse.(Int, split(readline()))\n    ps = parse.(Int, split(readline())) .+ 1\n\n    H = [Vector{Edge}() for _ = 1:N+1] # Count the super node\n    for _ = 1:E\n        a, b = parse.(Int, split(readline())) .+ 1\n        push!(H, a, b, 1)\n        push!(H, b, a, 1)\n    end\n\n    for p in ps\n        push!(H, p, N+1, 1)\n        push!(H, N+1, p, 1)\n    end\n\n    println(FordFulkerson(H, 1, N+1))\nend\n\nmain()\n", "meta": {"hexsha": "adeeef8c4b91efb0dd4cac5bd45472ce52df08d2", "size": 1507, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/chapter16/nicetak/abc010_4.jl", "max_stars_repo_name": "tokuma09/algorithm_problems", "max_stars_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-07T15:46:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T15:46:58.000Z", "max_issues_repo_path": "problems/chapter16/nicetak/abc010_4.jl", "max_issues_repo_name": "tokuma09/algorithm_problems", "max_issues_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-06-05T14:16:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-10T07:08:28.000Z", "max_forks_repo_path": "problems/chapter16/nicetak/abc010_4.jl", "max_forks_repo_name": "tokuma09/algorithm_problems", "max_forks_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0759493671, "max_line_length": 61, "alphanum_fraction": 0.4764432648, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363299661721, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7666621752389693}}
{"text": "###################################################\n## logarithmic / discrete return transformations ##\n###################################################\n\nfunction disc2log(tn::AbstractTimenum; percent = false)\n    ## discrete net return to logarithmic return\n    if percent\n        rets = log(tn./100 .+ 1).*100\n    else\n        rets = log(tn .+ 1)\n    end\n    return rets\nend\n\nfunction log2disc(tn::AbstractTimenum; percent = false)\n    ## logarithmic return to discrete net return\n    if percent\n        rets = (exp(tn./100) .- 1).*100\n    else\n        rets = exp(tn) .- 1\n    end\n    return rets\nend\n\n###############\n## price2ret ##\n###############\n\n## price2ret for DataArrays\n##-------------------------\n\nfunction price2ret(prices::DataArray; log = true)\n    ## find NAs\n    naInds = find(isna, prices)\n    nNAs = length(naInds)\n\n    ## create price series with NAs replaced by last value\n    pricesNoNA = deepcopy(prices)\n    impute!(pricesNoNA, \"single last\")\n\n    ## calculate returns\n    if log\n        rets = pricesNoNA[2:end] .- pricesNoNA[1:(end-1)]\n    else\n        rets = (pricesNoNA[2:end] .- pricesNoNA[1:(end-1)]) ./\n        pricesNoNA[1:(end-1)] \n    end\n\n    ## fill in NAs again\n    for ii=1:nNAs\n        if naInds[ii] > 1\n            rets[naInds[ii] - 1] = NA\n        end\n    end\n    return rets\nend\n\n## price2ret for TimeData types\n##-----------------------------\n\nfunction price2ret(tn::AbstractTimenum; log = true)\n    ## dealing with NAs through ret2price for DataArrays\n\n    rets = DataFrame()\n    for (nam, col) in eachcol(tn.vals)\n        rets[nam] = price2ret(col, log = log)\n    end\n\n    return TimeData.Timenum(rets, tn.idx[2:end])\nend\n\nfunction price2ret(tm::AbstractTimematr; log = true)\n    ## get discrete net returns from historic prices\n    if log\n        rets = tm[2:end, :] .- tm[1:(end-1), :] # time index of first\n                                        # part is automatically taken! \n    else\n        rets = (tm[2:end, :] .- tm[1:(end-1), :]) ./ tm[1:(end-1), :]\n    end\n    return rets\nend\n\n###############\n## ret2price ##\n###############\n\n## ret2price for DataArrays\n##-------------------------\n\nfunction ret2price(da::DataArray; log = true)\n    ## append 0 or NA and transform returns to prices\n    nObs = size(da, 1)\n    prices = DataArray(eltype(da), nObs+1)\n\n    if isna(da[1])\n        ## find first element\n        indFirstRet = find(x -> !isna(x), da)[1]\n        prices[1:(indFirstRet-1)] = NA\n    else\n        indFirstRet = 1\n    end\n\n    ## different initial value for log / normal prices\n    if log\n        prices[indFirstRet] = 0\n    else\n        prices[indFirstRet] = 1\n    end\n\n    for ii=(indFirstRet+1):(nObs+1)\n        if isna(da[ii-1])\n            prices[ii] = prices[ii-1]\n        else\n            ## different aggregation formulas\n            if log\n                prices[ii] = prices[ii-1] + da[ii-1]\n            else\n                prices[ii] = prices[ii-1] .* (1 .+ da[ii-1])\n            end\n        end\n    end\n\n    ## insert NAs again\n    inds = find(isna(da))\n    for eachNA in inds\n        prices[eachNA + 1] = NA\n    end\n\n    ## again insert initial price in case it was overwritten\n    if log\n        prices[indFirstRet] = 0\n    else\n        prices[indFirstRet] = 1\n    end\n    return prices\nend\n\n## ret2price for TimeData types\n##-----------------------------\n\n\n## ret2price for Timenum\n##----------------------\n\nfunction ret2price(tn::AbstractTimenum; log = true)\n    ## dealing with NAs through ret2price for DataArrays\n\n    prices = DataFrame()\n    for (nam, col) in eachcol(tn.vals)\n        prices[nam] = ret2price(col, log = log)\n    end\n\n    ## get previous day / could be not a business day\n    initDate = TimeData.idx(tn)[1] - Dates.Day(1)\n\n    ## get indices\n    idxs = [initDate; tn.idx]\n\n    return TimeData.Timenum(prices, idxs)\nend\n\n## ret2price for Timematr\n##-----------------------\n\nfunction ret2price(tm::AbstractTimematr; log = true)\n    ## get normed prices from returns\n    (nObs, nVars) = size(tm)\n\n    if log\n        prices = cumsum(tm, 1)\n\n        ## get values of first day\n        initPrices = zeros(1, nVars)\n    else\n        prices = cumprod(tm .+ 1, 1)\n\n        ## get values of first day\n        initPrices = ones(1, nVars)\n    end\n    \n    ## get previous day / could be not a business day\n    initDate = TimeData.idx(tm)[1] - Dates.Day(1)\n\n    ## get first day as Timematr\n    initPricesDf = TimeData.composeDataFrame(initPrices, names(tm)) \n    initPricesTm = TimeData.Timematr(initPricesDf,\n                                     [initDate])\n    \n    return [initPricesTm; prices]\n    \nend\n\n#########################################\n## ret2price with given price metadata ##\n#########################################\n\n## ret2price with prices - Timenum\n##--------------------------------\n\nfunction ret2price(rets::AbstractTimenum,\n                   prices::AbstractTimenum; log = true)\n\n    ## find first prices\n    (nObs, nVars) = size(rets)\n\n    initPrices = DataFrame()\n    for (nam, col) in eachcol(prices.vals)\n        if isna(col[1])\n            ## find first element\n            indFirstPrice = find(x -> !isna(x), col)[1]\n            initPrice = col[indFirstPrice]\n        else\n            initPrice = col[1]\n        end\n        initPrices[nam] = initPrice*ones(nObs+1)\n    end\n\n    ## get normalized prices via DataArrays\n    normedPrices = DataFrame()\n    for (nam, col) in eachcol(rets.vals)\n        normedPrices[nam] = ret2price(col, log = log)\n    end\n    normedPricesIdxs = [prices.idx[1]; rets.idx]\n    normedPricesTn = TimeData.Timenum(normedPrices, normedPricesIdxs)\n\n    ## add / multiply initPrices to each element\n    initPricesTn = TimeData.Timenum(initPrices, normedPricesIdxs)\n    \n    if log\n        newPricesTn = normedPricesTn .+ initPricesTn\n    else\n        newPricesTn = normedPricesTn .* initPricesTn\n    end\n    \n    return newPricesTn\nend\n\n## ret2price with prices - Timematr\n##---------------------------------\n\nfunction ret2price(tm::AbstractTimematr,\n                   prices::AbstractTimenum; log = true)\n\n    normalizedPrices = ret2price(tm, log = log)\n    (nObs, nVars) = size(normalizedPrices)\n\n    ## add initial prices to each element\n    initPricesTm = convert(Timematr, prices[1, :])\n    initPrices = composeDataFrame(repmat(core(initPricesTm), nObs, 1),\n                                  names(normalizedPrices))\n    initPricesTm = Timematr(initPrices, normalizedPrices.idx)\n\n    if log\n        newPrices = normalizedPrices .+ initPricesTm\n    else\n        newPrices = normalizedPrices .* initPricesTm\n    end\n    \n    ## fix first date\n    newPrices.idx[1] = prices.idx[1]\n\n    return newPrices\nend\n\n\n## #####################################\n## ## low-level aggregation functions ##\n## #####################################\n\n## function aggrLog(rets::Array{Float64, 2})\n##     return sum(rets, 1)\n## end\n\n## function aggrLogPercent(rets::Array{Float64, 2})\n##     return aggrLog(rets)\n## end\n\n## function aggrDiscr(rets::Array{Float64, 2})\n##     return prod(rets+1, 1) - 1\n## end\n\n## function aggrDiscrPercent(rets::Array{Float64, 2})\n##     return (prod(rets/100 + 1, 1) - 1)*100\n## end\n\n## #################\n## ## aggregation ##\n## #################\n\n## function getLastPeriodIndices(n, by)\n##     ## get start index\n##     startInd = mod(n, by) + 1\n##     return [(startInd+by-1):by:n]\n## end\n\n## function aggregate(tm::Timematr, by::Integer = 20,\n##                    aggrFunc::Function = aggrLog)\n##     ## aggregate by using most recent observations\n\n##     (nObs, nAss) = size(tm)\n##     vals = core(tm)\n\n##     ## how many aggregations\n##     nAggrRets = div(nObs, by)\n\n##     ## get aggregation intervals and last interval dates\n##     aggrIndices = getLastPeriodIndices(nObs, by)\n##     aggrDates = idx(tm)[aggrIndices]\n\n##     aggrRets = ones(nAggrRets, nAss)\n##     for ii=1:nAggrRets\n##         startInd = aggrIndices[ii]-by+1\n##         aggrRets[ii, :] = aggrFunc(vals[startInd:aggrIndices[ii], :])\n##     end\n\n##     return Timematr(aggrRets, aggrDates)\n## end\n\n## ######################################\n## ## get correlations for frequencies ##\n## ######################################\n\n## ## select pair of assets\n## ## for each frequency\n## ## - get number of possible starting points: remain + by\n## ## - aggregate according to frequency in multiple ways\n## ## - for each aggregation, get correlation\n## ##\n\n\n## function frequCorrPlot(tm::Timematr, ind1::Integer = 1,\n##                        ind2::Integer = 2,\n##                        maxFreq::Integer = 50)\n##     ## select data\n##     data = tm[:, [ind1, ind2]]\n##     nObs = size(data, 1)\n\n##     corrs = Float64[]\n##     frequencies = Float64[]\n##     for frequ=1:maxFreq\n##         ## get number of possible phases\n##         nPhases = mod(nObs, frequ) + frequ\n##         nObsPerPhase = (div(nObs, frequ) - 1)*frequ\n##         ## corrsCurrentFrequ = ones(nPhases)\n\n##         for ii=1:nPhases\n##             ## get current data\n##             corrData = aggregate(data[ii:(ii + nObsPerPhase - 1), :],\n##                                  frequ)\n##             ## corrsCurrentFrequ[ii] = cor(corrData)[1, 2]\n##             corr = cor(corrData)[1, 2]\n##             push!(frequencies, frequ)\n##             push!(corrs, corr)\n##         end\n\n##         ## push!(a, [frequ*ones(nPhases) corrsCurrentFrequ])\n##     end\n\n##     return [frequencies corrs]\n## end\n", "meta": {"hexsha": "d04f49466c64557ec856f2fb8927f3ef1bd881ed", "size": 9393, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/returns.jl", "max_stars_repo_name": "JuliaFinMetriX/Econometrics.jl", "max_stars_repo_head_hexsha": "6647c4a009e2c3074524b7b644ed293f79c0732f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-02-29T01:19:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T12:53:59.000Z", "max_issues_repo_path": "src/returns.jl", "max_issues_repo_name": "jngod2011/Econometrics.jl", "max_issues_repo_head_hexsha": "6647c4a009e2c3074524b7b644ed293f79c0732f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-09-24T08:59:16.000Z", "max_issues_repo_issues_event_max_datetime": "2015-09-24T08:59:16.000Z", "max_forks_repo_path": "src/returns.jl", "max_forks_repo_name": "jngod2011/Econometrics.jl", "max_forks_repo_head_hexsha": "6647c4a009e2c3074524b7b644ed293f79c0732f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-04-27T20:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:49:48.000Z", "avg_line_length": 26.0193905817, "max_line_length": 72, "alphanum_fraction": 0.545193229, "num_tokens": 2609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7666621629814951}}
{"text": "\n#=\n\n=#\n\nusing DataStructures\nusing IterTools\nfunction value_iteration(S,A,P,R,Θ)\nγ = 0.9\nV₀ = DefaultDict{Tuple{Int,Int},Int}(0)\nVk::Array{Any} = [V₀]\nk = 1\nV₁::Dict{Tuple{Int,Int},Float64} = Dict{Tuple{Int,Int},Float64}()\n# update value\nwhile true\n    k = k + 1\n    push!(Vk,Dict{Tuple{Int,Int},Float64}())\n    for s in S\n        Vp = []\n         for a in A\n            #=@show s,a\n            println(broadcast(s′ -> R(s,a,s′),[S...]))\n            println(broadcast(s′ -> P(s′,s,a),[S...]))=#\n            #push!(Vp,sum(broadcast(s′ -> P(s′,s,a)*R(s,a,s′),[S...])))\n            push!(Vp, sum(broadcast(s′ -> P(s′,s,a)*(R(s,a,s′)+γ*Vk[k-1][s′]),[S...])))\n        end\n        #@show Vp\n        Vk[k][s] = maximum(Vp)\n\n    end\n    abs(sum(abs,values(Vk[k])) - sum(abs,values(Vk[k-1]))) < Θ && break;\nend\n@show k\nVk[k]\nend\nActionToVec = Dict(1 => (0,1),2 => (1,0), 3 => (0,-1), 4 => (-1,0))\nfunction P(s′,s,a)\n\n    Action = [0.1, 0.1, 0.1, 0.1]\n    Action[a] = 0.7\n    Vec = map(t -> ActionToVec[t],[1,2,3,4])\n    Near = map(x -> s.+x,Vec)\n    !any([s′] .== Near) && return 0\n\n    Action[findin(Near,[s′])][1]\n\nend\nfunction R(s,a,s′)\n    s == (0,0) && return 10\n    s == (1,1) && return -10\n    0\nend\n", "meta": {"hexsha": "99bd2c66e4bd47ccc8ec257ab466a5bfbe63e71c", "size": 1199, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "main.jl", "max_stars_repo_name": "bollafa/MarkovDecissionProcess", "max_stars_repo_head_hexsha": "757d92102e8a63d21c301419c73a509a1d397095", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.jl", "max_issues_repo_name": "bollafa/MarkovDecissionProcess", "max_issues_repo_head_hexsha": "757d92102e8a63d21c301419c73a509a1d397095", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.jl", "max_forks_repo_name": "bollafa/MarkovDecissionProcess", "max_forks_repo_head_hexsha": "757d92102e8a63d21c301419c73a509a1d397095", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6226415094, "max_line_length": 87, "alphanum_fraction": 0.4854045038, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7666529855000912}}
{"text": "# # Classification of penguin species\n#\n# ## Packages\n\nusing AlgebraOfGraphics\nusing CairoMakie\nusing CalibrationErrors\nusing DataFrames\nusing Distributions\nusing MLJ\nusing MLJNaiveBayesInterface\nusing PalmerPenguins\n\nusing Random\n\n## Plotting settings\nset_aog_theme!()\nCairoMakie.activate!(; type=\"svg\")\n\n# ## Data\n#\n# In this example we study the calibration of different models that classify three penguin\n# species based on measurements of their bill and flipper lengths.\n#\n# We use the [Palmer penguins dataset](https://allisonhorst.github.io/palmerpenguins/) to\n# to train and validate the models.\n\npenguins = dropmissing(DataFrame(PalmerPenguins.load()))\n\npenguins_mapping =\n    data(penguins) * mapping(\n        :bill_length_mm => \"bill length (mm)\", :flipper_length_mm => \"flipper length (mm)\"\n    )\ndraw(penguins_mapping * mapping(; color=:species) * visual(; alpha=0.7))\n\n# We split the data randomly into a training and validation dataset. The training dataset\n# contains around 60% of the samples.\n\nRandom.seed!(1234)\nn = nrow(penguins)\nk = floor(Int, 0.7 * n)\nRandom.seed!(100)\npenguins.train = shuffle!(vcat(trues(k), falses(n - k)))\n\n## Plot the training and validation data\ndataset = :train => renamer(true => \"training\", false => \"validation\") => \"Dataset\"\nplt = penguins_mapping * mapping(; color=:species, col=dataset) * visual(; alpha=0.7)\ndraw(plt; axis=(height=300,))\n\n# ## Fitting normal distributions\n#\n# For each species, we fit independent normal distributions to the observations of the bill\n# and flipper length in the training data, using maximum likelihood estimation.\n\ny, X = unpack(\n    penguins,\n    ==(:species),\n    x -> x === :bill_length_mm || x === :flipper_length_mm;\n    :species => Multiclass,\n    :bill_length_mm => MLJ.Continuous,\n    :flipper_length_mm => MLJ.Continuous,\n)\nmodel = fit!(machine(GaussianNBClassifier(), X, y); rows=penguins.train);\n\n# We plot the estimated normal distributions.\n\n## plot datasets\nfg = draw(plt; axis=(height=300,))\n\n## plot Gaussian distributions\nxgrid = range(extrema(penguins.bill_length_mm)...; length=100)\nygrid = range(extrema(penguins.flipper_length_mm)...; length=100)\nlet f = (x, y, dist) -> pdf(dist, [x, y])\n    for (class, color) in zip(classes(y), Makie.wong_colors())\n        pdfs = f.(xgrid, ygrid', Ref(model.fitresult.gaussians[class]))\n        contour!(fg.figure[1, 1], xgrid, ygrid, pdfs; color=color)\n        contour!(fg.figure[1, 2], xgrid, ygrid, pdfs; color=color)\n    end\nend\n\nfg\n\n# ## Naive Bayes classifier\n#\n# Let us assume that the bill and flipper length are conditionally independent given the\n# penguin species. Then Bayes' theorem implies that\n# ```math\n# \\begin{aligned}\n# \\mathbb{P}(\\mathrm{species} \\,|\\, \\mathrm{bill}, \\mathrm{flipper})\n# &= \\frac{\\mathbb{P}(\\mathrm{species}) \\mathbb{P}(\\mathrm{bill}, \\mathrm{flipper} \\,|\\, \\mathrm{species})}{\\mathbb{P}(\\mathrm{bill}, \\mathrm{flipper})} \\\\\n# &= \\frac{\\mathbb{P}(\\mathrm{species}) \\mathbb{P}(\\mathrm{bill} \\,|\\, \\mathrm{species}) \\mathbb{P}(\\mathrm{flipper} \\,|\\, \\mathrm{species})}{\\mathbb{P}(\\mathrm{bill}, \\mathrm{flipper})}.\n# \\end{aligned}\n# ```\n# This predictive model is known as\n# [naive Bayes classifier](https://en.wikipedia.org/wiki/Naive_Bayes_classifier).\n#\n# In the section above, we estimated $\\mathbb{P}(\\mathrm{species})$,\n# $\\mathbb{P}(\\mathrm{bill} \\,|\\, \\mathrm{species})$, and\n# $\\mathbb{P}(\\mathrm{flipper} \\,|\\, \\mathrm{species})$ for each penguin species from\n# the training data. For the conditional distributions we used a Gaussian approximation.\n\npredictions = MLJ.predict(model)\ntrain_predict = predictions[penguins.train]\nval_predict = predictions[.!penguins.train]\n\n## Plot datasets\nfg = draw(plt; axis=(height=300,))\n\n## Plot predictions\npredictions_grid = reshape(\n    MLJ.predict(model, reduce(hcat, vcat.(xgrid, ygrid'))'), length(xgrid), length(ygrid)\n)\nfor (class, color) in zip(classes(y), Makie.wong_colors())\n    p = pdf.(predictions_grid, class)\n    contour!(fg.figure[1, 1], xgrid, ygrid, p; color=color)\n    contour!(fg.figure[1, 2], xgrid, ygrid, p; color=color)\nend\n\nfg\n\n# ## Evaluation\n#\n# We evaluate the probabilistic predictions of the naive Bayes classifier that we just\n# trained.\n#\n# ### Log-likelihood\n#\n# We compute the average log-likelihood of the validation data. It is equivalent to the\n# negative cross-entropy.\n\nval_y = y[.!penguins.train]\n-mean(cross_entropy(val_predict, val_y))\n\n# ### Brier score\n#\n# The average log-likelihood is also equivalent to the\n# [logarithmic score](https://sites.stat.washington.edu/raftery/Research/PDF/Gneiting2007jasa.pdf).\n# The Brier score is another strictly proper scoring rule that can be used for evaluating\n# probabilistic predictions.\n\nmean(brier_score(val_predict, val_y))\n\n# ### Expected calibration error\n#\n# As all proper scoring rules, the logarithmic and the Brier score can be [decomposed in\n# three terms that quantify the sharpness and calibration of the predictive model and the\n# irreducible uncertainty of the targets that is inherent to the prediction\n# problem](https://doi.org/10.1002/qj.456). The calibration term in this decomposition is\n# the expected calibration error (ECE)\n# ```math\n# \\mathbb{E} d\\big(P_X, \\mathrm{law}(Y \\,|\\, P_X)\\big)\n# ```\n# with respect to the score divergence $d$.\n#\n# Scoring rules, however, include also the sharpness and the uncertainty term. Thus models\n# can trade off calibration for sharpness and therefore scoring rules are not suitable for\n# specifically evaluating calibration of predictive models.\n#\n# The score divergence to the logarithmic and the Brier score are the Kullback-Leibler (KL)\n# divergence\n# ```math\n# d\\big(P_X, \\mathrm{law}(Y \\,|\\, P_X)\\big) = \\sum_{y} \\mathbb{P}(Y = y \\,|\\, P_X)\n# \\log\\big(\\mathbb{P}(Y = y \\,|\\, P_X) / P_X(\\{y\\})\\big)\n# ```\n# and the squared Euclidean distance\n# ```math\n# d\\big(P_X, \\mathrm{law}(Y \\,|\\, P_X)\\big) = \\sum_{y} \\big(P_X - \\mathrm{law}(Y \\,|\\, P_X)\\big)^2(\\{y\\}),\n# ```\n# respectively. The KL divergence is defined only if $\\mathrm{law}(Y \\,|\\, P_X)$ is\n# absolutely continuous with respect to $P_X$, i.e., if $P_X(\\{y\\}) = 0$ implies\n# $\\mathbb{P}(Y = y \\,|\\, P_X) = 0$.\n\n# We estimate the ECE by binning the probability simplex of predictions $P_X$ and computing\n# the weighted average of the distances between the mean prediction and the distribution of\n# targets in each bin.\n#\n# One approach is to use bins of uniform size.\n\nece = ECE(UniformBinning(10), (μ, y) -> kl_divergence(y, μ));\n\n# We have to work with a numerical encoding of the true penguin species and a\n# corresponding vector of predictions. We use [`RowVecs`](https://juliagaussianprocesses.github.io/KernelFunctions.jl/stable/api/#KernelFunctions.RowVecs)\n# to indicate that the rows in the matrix of probabilities returned by `pdf`\n# are the predictions. If we would provide predictions as columns of a matrix, we would have\n# to use [`ColVecs`](https://juliagaussianprocesses.github.io/KernelFunctions.jl/stable/api/#KernelFunctions.ColVecs).\n\nval_yint = map(MLJ.levelcode, val_y)\nval_probs = RowVecs(pdf(val_predict, MLJ.classes(y)));\n\n# We compute the estimate on the validation data:\n\nece(val_probs, val_yint)\n\n# For the squared Euclidean distance we obtain:\n\nece = ECE(UniformBinning(10), SqEuclidean())\nece(val_probs, val_yint)\n\n# Alternatively, one can use a data-dependent binning scheme that tries to split the\n# predictions in a way that minimizes the variance in each bin.\n#\n# With the KL divergence we get:\n\nece = ECE(MedianVarianceBinning(5), (μ, y) -> kl_divergence(y, μ))\nece(val_probs, val_yint)\n\n# For the squared Euclidean distance we obtain:\n\nece = ECE(MedianVarianceBinning(5), SqEuclidean())\nece(val_probs, val_yint)\n\n# We see that the estimates (of the same theoretical quantity!) are highly dependent on the\n# chosen binning scheme.\n\n# ### Kernel calibration error\n#\n# As an alternative to the ECE, we estimate the kernel calibration error (KCE). We keep it\n# simple here, and use the tensor product kernel\n# ```math\n# k\\big((\\mu, y), (\\mu', y')\\big) = \\delta_{y,y'} \\exp{\\bigg(-\\frac{{\\|\\mu - \\mu'\\|}_2^2}{2\\nu^2} \\bigg)}\n# ```\n# with length scale $\\nu > 0$ for predictions $\\mu,\\mu'$ and corresponding targets $y, y'$.\n# For simplicity, we estimate length scale $\\nu$ with the median heuristic.\n\ndistances = pairwise(SqEuclidean(), RowVecs(pdf(train_predict, MLJ.classes(y))))\nν = sqrt(median(distances[i] for i in CartesianIndices(distances) if i[1] < i[2]))\nkernel = with_lengthscale(GaussianKernel(), ν) ⊗ WhiteKernel();\n\n# We obtain the following biased estimate of the squared KCE (SKCE):\n\nskce = BiasedSKCE(kernel)\nskce(val_probs, val_yint)\n\n# Similar to the biased estimates of the ECE, the biased estimates of the SKCE are always\n# non-negative. The unbiased estimates can be negative as well, in particular if the model\n# is (close to being) calibrated:\n\nskce = UnbiasedSKCE(kernel)\nskce(val_probs, val_yint)\n\n# When the datasets are large, the quadratic sample complexity of the standard biased and\n# unbiased estimators of the SKCE can become prohibitive. In these cases, one can resort to\n# an estimator that averages estimates of non-overlapping blocks of samples. This estimator\n# allows to trade off computational cost for increased variance.\n#\n# Here we consider the extreme case of blocks with two samples, which yields an estimator\n# with linear sample complexity:\n\nskce = BlockUnbiasedSKCE(kernel, 2)\nskce(val_probs, val_yint)\n", "meta": {"hexsha": "bbf45103fa8653e624b045f9ef3bf63b5f6ce312", "size": 9413, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/classification/script.jl", "max_stars_repo_name": "devmotion/CalibrationErrors.jl", "max_stars_repo_head_hexsha": "8ba70211e324b874484148fc7c33b5cdb3ba0c83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2019-10-18T10:50:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T22:29:18.000Z", "max_issues_repo_path": "examples/classification/script.jl", "max_issues_repo_name": "devmotion/CalibrationErrors.jl", "max_issues_repo_head_hexsha": "8ba70211e324b874484148fc7c33b5cdb3ba0c83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 91, "max_issues_repo_issues_event_min_datetime": "2019-09-20T14:34:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T15:38:58.000Z", "max_forks_repo_path": "examples/classification/script.jl", "max_forks_repo_name": "devmotion/CalibrationErrors.jl", "max_forks_repo_head_hexsha": "8ba70211e324b874484148fc7c33b5cdb3ba0c83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-18T10:50:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T12:50:24.000Z", "avg_line_length": 37.5019920319, "max_line_length": 187, "alphanum_fraction": 0.721767768, "num_tokens": 2607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374443, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7666529808701631}}
{"text": "# Simple example of a homogeneous heat equation:\n#\n#           y\n#             |\n#             |     u_y = 0\n#          Ly ----------------------------------\n#             |                                |\n#             |                                |\n#             |                                |\n#     u_x = 0 |    u_t - a(u_xx + u_yy) = 0    | u_x = 0\n#             |                                |\n#             |                                |\n#             |                                |\n#           -----------------------------------|-----  x\n#                         u_y = 0              Lx\n#\n# Here, a>0 and the initial data is\n#\n#      u_0(x, y) = 1 + cos(pi x / Lx) cos(pi y / Ly).\n#\n# The exact solution is\n#\n#      u(x, y, t) = 1 + exp(-lambda t) cos(pi x / Lx) cos(pi y / Ly )\n#\n# with\n#\n#      lambda = a pi^2 ( 1 / Lx^2 + 1 / Ly^2 )\n#\nusing PyPlot\nusing FinElt\nusing FinElt.PlanarPoisson\nusing LinearAlgebra: norm\ninclude(\"ode23s.jl\")\n\nconst a = 0.1\nconst Lx = 1.0\nconst Ly = 1.0\nconst lambda = a * pi^2 * ( 1/Lx^2 + 1/Ly^2 )\nconst T = 2.0\n\nfunction exact_u(x, t)\n    return 1 + exp(-lambda * t ) * cos(pi*x[1]/Lx) * cos(pi*x[2]/Ly)\nend\n\nfunction RHS(t, u, S)\n    return -S * u\nend\n\nmaxnorm(x) = norm(x, Inf)\n\nstart = time()\nmesh = read_msh_file(\"../rectangle/rect2.msh\")    \ndof = degrees_of_freedom(mesh, String[])\nM = assembled_matrix(\"Omega\", func_times_func!, 1.0, mesh, dof)\nS = assembled_matrix(\"Omega\", grad_dot_grad!, a, mesh, dof)\nu0 = get_nodal_vals(x->exact_u(x,0.0), mesh)\nt, u = ode23s((t,u)->RHS(t, u, S), u0, [0,T]; \n             reltol=1.0e-5, abstol=1.0e-5, mass=M, norm=maxnorm)\n\nN = length(t)\nerr = zeros(N)\nfor n = 1:N\n    un = get_nodal_vals(x->exact_u(x,t[n]), mesh)\n    err[n] = maxnorm(un-u[n])\nend\n\nfinish = time()\nelapsed = finish - start\n\nfigure(1)\nplot(t, err)\nxlabel(L\"t\")\ntitle(\"Error solving the heat equation\")\ngrid(true)\n", "meta": {"hexsha": "43a9ec036c70b2addc89b58126f8b1e085f4f3cb", "size": 1888, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/heat/homog.jl", "max_stars_repo_name": "billmclean/FinElt.jl", "max_stars_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-07-18T20:04:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:29:09.000Z", "max_issues_repo_path": "examples/heat/homog.jl", "max_issues_repo_name": "billmclean/FinElt.jl", "max_issues_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/heat/homog.jl", "max_forks_repo_name": "billmclean/FinElt.jl", "max_forks_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-06-29T15:15:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T18:01:08.000Z", "avg_line_length": 25.1733333333, "max_line_length": 69, "alphanum_fraction": 0.4454449153, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832974, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7666529798148591}}
{"text": "using Printf\nimport Flux: σ\nusing ModelingToolkit\nusing GalacticOptim\nusing Optim\nusing DiffEqFlux\nusing NeuralPDE\nusing Quadrature, Cubature, Cuba\nusing Plots\n\n@parameters t,x\n@variables c(..)\n@derivatives Dt'~t\n@derivatives Dxx''~x\n@derivatives Dx'~x\n\n# Parameters\n\nv = 1\nR = 0\nD = 0.1 # diffusion\nt_max = 2.0\nx_min = -1.0\nx_max = 1.0\n\n# Equations, initial and boundary conditions\neqs = [ Dt(c(t, x)) ~ D * Dxx(c(t,x)) - Dx(c(t,x)) ]\n\nbcs = [ \n        c(0, x) ~ cos(π*x) + 1.0,  \n        c(t, x_min) ~ c(t, x_max)\n        \n]\n\n# Space and time domains\ndomains = [t ∈ IntervalDomain(0.0,t_max),\n        x ∈ IntervalDomain(x_min,x_max)\n]\n\n# Discretization\nnx = 32\ndx = (x_max-x_min) / (nx - 1)\ndt = 0.01\n\n# Neural network\ndim = length(domains)\noutput = length(eqs)\nhidden = 8\n\nchain = FastChain( FastDense(dim, hidden, σ),\n                    FastDense(hidden, hidden, σ),\n                    FastDense(hidden, 1))\n\nstrategy = GridTraining(dx=[dt,dx])\n\ndiscretization = PhysicsInformedNN(chain, strategy=strategy)\n\npde_system = PDESystem(eqs, bcs, domains, [t,x], [c])\nprob = discretize(pde_system,discretization)\n\ncb = function (p,l)\n    println(\"Current loss is: $l\")\n    return false\nend\n\nres = GalacticOptim.solve(prob,Optim.BFGS();cb=cb,maxiters=1200)\n\n\n# Plots\n\nphi = discretization.phi\n\ninitθ = discretization.initθ\n\nacum =  [0;accumulate(+, length.(initθ))]\nsep = [acum[i]+1 : acum[i+1] for i in 1:length(acum)-1]\nminimizers = [res.minimizer[s] for s in sep]\nts,xs = [domain.domain.lower:dx:domain.domain.upper for domain in domains]\n\nanim = @animate for (i, t) in enumerate(0:dt:t_max)\n    @info \"Animating frame $i...\"\n    c_predict = reshape([phi([t, x], res.minimizer)[1] for x in xs], length(xs))\n    title = @sprintf(\"Advection-diffusion t = %.3f\", t)\n    plot(xs, c_predict, label=\"\", title=title , ylims=(0., 2))\nend\n\ngif(anim, \"advection_diffusion_pinn.gif\", fps=15)\n\nc_predict = reshape([ phi([0, x], res.minimizer)[1] for x in xs], length(xs))\nplot(xs,c_predict)\n\n# Plot correct solution\nusing JLD2\nfile = jldopen(\"advection_diffusion/simulation/cosine_advection_diffusion.jld2\")\niterations = parse.(Int, keys(file[\"timeseries/t\"]))\n\nanim = @animate for (i, iter) in enumerate(iterations)\n    @info \"Animating frame $i...\"\n    Hx = file[\"grid/Hx\"]\n    x = file[\"grid/xC\"][1+Hx:end-Hx]\n    t = file[\"timeseries/t/$iter\"]\n    c = file[\"timeseries/c/$iter\"][:]\n    \n    title = @sprintf(\"Advection-diffusion t = %.3f\", t)\n    p = plot(x, c .+ 1, linewidth=2, title=title, label=\"Oceananigans\",\n             xlabel=\"x\", ylabel=\"Tracer\", xlims=(-1, 1), ylims=(0, 2))\n\n    c_predict = reshape([phi([t, x], res.minimizer)[1] for x in xs], length(xs))\n    \n    plot!(p, x, c_predict, linewidth=2, label=\"Neural PDE\")\nend\n\ngif(anim, \"advection_diffusion_comparison.gif\", fps=15)\n", "meta": {"hexsha": "df99d1efca3e6152e120da96297841bdccb376fb", "size": 2788, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Old Stuff/1_convection_diffusion.jl", "max_stars_repo_name": "drozzy/NeuralOceananigans", "max_stars_repo_head_hexsha": "e4cad0a48a95fb8b9360457728f0a9d86b64fdd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Old Stuff/1_convection_diffusion.jl", "max_issues_repo_name": "drozzy/NeuralOceananigans", "max_issues_repo_head_hexsha": "e4cad0a48a95fb8b9360457728f0a9d86b64fdd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Old Stuff/1_convection_diffusion.jl", "max_forks_repo_name": "drozzy/NeuralOceananigans", "max_forks_repo_head_hexsha": "e4cad0a48a95fb8b9360457728f0a9d86b64fdd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-25T23:03:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-25T23:03:26.000Z", "avg_line_length": 24.4561403509, "max_line_length": 80, "alphanum_fraction": 0.6481348637, "num_tokens": 915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7666529746969252}}
{"text": "module SimpleDrawing\nusing Plots, LinearAlgebra\n\nexport newdraw, draw_circle, draw_arc, draw_segment, draw_point, draw_vector\nexport find_center, non_colinear_check\nexport finish, draw\n\n\"\"\"\n`newdraw()` clears the screen and sets up a blank drawing canvas with\nno axis, grid, or legend, and sets the aspect ratio to 1.\n\"\"\"\nfunction newdraw()\n    plot(aspectratio=1, legend=false, axis=false, grid=false)\nend\n\nfunction draw()\nend\n\n\"\"\"\n`draw_circle(x,y,r)` (or `draw_circle(z,r)`) draws a circle centered\nat `(x,y)` (at `z`) with radius `r`.\n\"\"\"\nfunction draw_circle(x::Real, y::Real, r::Real; opts...)\n    f(t) = r*cos(t) + x\n    g(t) = r*sin(t) + y\n    plot!(f,g,0,2pi;opts...)\nend\n\ndraw_circle(z::Complex, r::Real; opts...) =\n    draw_circle(real(z), imag(z), r; opts...)\n\n\"\"\"\n`draw_circle(a,b,c)` draws a circle through the points given by\nthe three complex arguments.\n\"\"\"\nfunction draw_circle(a::Complex, b::Complex, c::Complex; opts...)\n    z = find_center(a,b,c)\n    r = abs(a-z)\n    x,y = reim(z)\n    draw_circle(x,y,r; opts...)\nend\n\n\n\"\"\"\n`draw_arc(x,y,r,t1,t2)` draws the shorter arc centered at `(x,y)`\nwith radius `r` between angles `t1` and `t2`.\n\"\"\"\nfunction draw_arc(x::Real, y::Real, r::Real, t1::Real, t2::Real; opts...)\n    f(t) = r*cos(t) + x\n    g(t) = r*sin(t) + y\n\n    plot!(f,g,t1,t2;opts...)\nend\n\n\n\n\"\"\"\n`draw_arc(a,b,c)` where the arguments are `Complex`: Draw the\narc from `a` through `b` to `c`.\n\"\"\"\nfunction draw_arc(a::Complex, b::Complex, c::Complex; opts...)\n    m2pi(x::Real) = mod(x,2π)\n\n    z = find_center(a,b,c)\n    x,y = reim(z)\n    r = abs(b-z)\n    ta = m2pi(angle(a-z))\n    tb = m2pi(angle(b-z))\n    tc = m2pi(angle(c-z))\n\n    if ta > tc\n        ta,tc = tc,ta\n    end\n\n\n    if ta<tb<tc\n        return draw_arc(x,y,r,ta,tc; opts...)\n    end\n\n\n    return draw_arc(x,y,r,tc-2pi,ta; opts...)\nend\n\n\n\n\"\"\"\n`draw_segment(x,y,xx,yy)` draws a line segment from `(x,y)` to\n`(xx,yy)`. Also `draw_segment(z,zz)` for `Complex` arguments.\n\"\"\"\nfunction draw_segment(a::Real,b::Real,c::Real,d::Real; opts...)\n    plot!([a,c],[b,d];opts...)\nend\n\nfunction draw_segment(a::Complex, b::Complex; opts...)\n    x,y = reim(a)\n    xx,yy = reim(b)\n    draw_segment(x,y,xx,yy; opts...)\nend\n\n\n\"\"\"\n`draw_point(x,y)` [or `draw_point(z)`] draws a point at coordinates `(x,y)`\n[or complex location `z`].\n\n`draw_point(list)` plots all the points in the one-dimensional `list` of\ncomplex values.\n\"\"\"\nfunction draw_point(x::Real, y::Real; opts...)\n    plot!([x],[y];marker=1,opts...)\nend\n\ndraw_point(z::Complex; opts...) = draw_point(real(z),imag(z); opts...)\n\nfunction draw_point(pts::Array{Complex{T},1};opts...) where T\n    for p in pts\n        draw_point(p;opts...)\n    end\nend\n\n\"\"\"\n`draw_vector` is used to draw vectors (line segments with an arrow at one end).\nThe variations are:\n+ `draw_vector(x,y)` draws a vector from the origin to `(x,y)`.\n+ `draw_vector(x,y,basex,basey)` draws a vector from `(basex,basey)` to\n`(basex+x,basey+y)`.\n+ `draw_vector(z)` draws a vector from the origin to the complex value `z`.\n+ `draw_vector(z,basez)` draws a vector from the complex location `basez` to\n`z+basez`.\n\"\"\"\ndraw_vector(x::Real,y::Real; opts...) = draw_segment(0,0,x,y;arrow=:arrow, opts...)\n\ndraw_vector(z::Complex;opts...) = draw_segment(0+0im, z; arrow=:arrow, opts...)\n\ndraw_vector(x::Real,y::Real,basex::Real,basey::Real; opts...) =\n    draw_segment(basex,basey,basex+x,basey+y; arrow=:arrow, opts...)\n\ndraw_vector(z::Complex, basez::Complex; opts...) =\n    draw_segment(basez, basez+z; arrow=:arrow, opts...)\n\n\n\"\"\"\n`finish()` is used to clean up a drawing after various calls to `draw`.\nIt removes the axes and the grid lines, and sets the aspect ratio to one.\n\"\"\"\nfunction finish()\n    plot!(aspectratio=1, legend=false, axis=false, grid=false)\nend\n\n\n\nexport find_center, non_colinear_check\n\n\"\"\"\n`find_center(a,b,c)`: Given three points in the complex plane,\nfind the point `z` that is equidistant from all three. If the three\npoints are collinear then return `Inf + Inf*im`.\n\"\"\"\nfunction find_center(a::Complex, b::Complex, c::Complex)::Complex\n    if !non_colinear_check(a,b,c)\n        return Inf + im*Inf\n    end\n    A = collect(reim(a))\n    B = collect(reim(b))\n    C = collect(reim(c))\n    AB = 0.5*(A+B)\n    BC = 0.5*(B+C)\n    M = [(A-B)'; (B-C)']\n    rhs = [dot(AB,A-B), dot(BC,B-C)]\n\n    Z = M\\rhs\n    return Z[1] + im*Z[2]\nend\n\n\"\"\"\n`non_colinear_check(a,b,c)`: test if the complex numbers are distinct\nand noncollinear.\n\"\"\"\nfunction non_colinear_check(a::Complex,b::Complex, c::Complex)::Bool\n    if a==b || b==c || a==c\n        return false\n    end\n    z = (b-a)/(c-a)\n    return imag(z) != 0\nend\n\ninclude(\"cubic.jl\")\ninclude(\"curve.jl\")\n\n\nend\n", "meta": {"hexsha": "8ce2e9312bc4a6c5d486884cc695afa15d2c556e", "size": 4663, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SimpleDrawing.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleDrawing.jl-d78a06e8-ae74-583c-9a07-0d6572347000", "max_stars_repo_head_hexsha": "0b871b42e72e44a9b0a7f924ad146ab242657a7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SimpleDrawing.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleDrawing.jl-d78a06e8-ae74-583c-9a07-0d6572347000", "max_issues_repo_head_hexsha": "0b871b42e72e44a9b0a7f924ad146ab242657a7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SimpleDrawing.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleDrawing.jl-d78a06e8-ae74-583c-9a07-0d6572347000", "max_forks_repo_head_hexsha": "0b871b42e72e44a9b0a7f924ad146ab242657a7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4136125654, "max_line_length": 83, "alphanum_fraction": 0.633283294, "num_tokens": 1448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.8221891305219503, "lm_q1q2_score": 0.7666529706342954}}
{"text": "\n\n#provide a pair of points in latitude and longitude, in 'degrees' to get\n#the distance back in Km\nfunction getDistanceFromLatLongInKm(lat1,long1,lat2,long2) \n  RadiusEarth = 6371; # Earth's radius in km\n  dLat = deg2rad(lat2-lat1); # deg2rad, built in fn in Julia\n  dLong = deg2rad(long2-long1); \n  h = sin(dLat/2)*sin(dLat/2) + cos(deg2rad(lat1))*cos(deg2rad(lat2))*sin(dLong/2)*sin(dLong/2)\n  d = RadiusEarth * 2 * atan2(sqrt(h),sqrt(1-h)); # Distance in km\n  return d;\nend\n", "meta": {"hexsha": "8a1f96670b04e200a4f7f7541289f10e39860870", "size": 478, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "getLatLongDist.jl", "max_stars_repo_name": "mantzaris/distLatLong", "max_stars_repo_head_hexsha": "a9e15ddf1969079119e5f97b6c37a98709cc7e80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-21T17:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-21T17:56:14.000Z", "max_issues_repo_path": "getLatLongDist.jl", "max_issues_repo_name": "mantzaris/distLatLong", "max_issues_repo_head_hexsha": "a9e15ddf1969079119e5f97b6c37a98709cc7e80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "getLatLongDist.jl", "max_forks_repo_name": "mantzaris/distLatLong", "max_forks_repo_head_hexsha": "a9e15ddf1969079119e5f97b6c37a98709cc7e80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7692307692, "max_line_length": 95, "alphanum_fraction": 0.7029288703, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.969785412932606, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.7666447810986555}}
{"text": "#\n# Denoise an SPD Example with Cyclic Proximal Point applied to the\n#\n# L2-TV functional with anisotropic TV\n#\n# where the example is the same data as for the corresponding CP algorithm\n#\nusing Manopt\nusing Images, CSV, DataFrames, LinearAlgebra, JLD2\n#\n# Settings\nExportResult = true\nExportOrig = true\nExportResultVideo = false\nExportTable = true\n#\n# Manifold and Data\nf = artificialSPDImage2(32)\npixelM = SymmetricPositiveDefinite(3)\nresultsFolder = \"src/examples/Total_Variation/SPD_TV/\"\nexperimentName = \"ImageCPPA\"\nif !isdir(resultsFolder)\n    mkdir(resultsFolder)\nend\nif ExportOrig\n    renderAsymptote(resultsFolder*experimentName*\"-orig.asy\"; data=f, scaleAxes=(7.5,7.5,7.5))\nend\n#\n# Parameters \nα = 6.\nmaxIterations = 4000\n#\n# Build Problem for L2-TV\nM = Power(pixelM,size(f))\nd = length(size(f))\nrep(d) = (d>1) ? [ones(Int,d)...,d] : d\nfidelity(x) = 1/2*distance(M,x,f)^2\nΛ(x) = forwardLogs(M,x) # on T_xN\nprior(x) = norm(norm.(Ref(pixelM),getValue(repeat(x,rep(d)...)),getValue(Λ(x))),1)\n#\n# Setup and Optimize\ncost(x) =  fidelity(x) + α*prior(x)\nproximalMaps = [(λ,x) -> proxDistance(M,λ,f,x,2), (λ,x) -> proxTV(M,α*λ,x,1)]\nx0 = f\n@time y, yRec = cyclicProximalPoint(M,cost,proximalMaps,x0;\ndebug = [:Iteration,\" | \", DebugProximalParameter(),\" | \", :Change, \" | \", :Cost, \"\\n\",100,:Stop],\nrecord = [:Iteration, :Iterate, :Cost],\nstoppingCriterion = stopAfterIteration(maxIterations)\n)\n#\n# Results\nif ExportResult\n    renderAsymptote(resultsFolder*experimentName*\"-result-$(maxIterations)-α$(replace(string(α), \".\" => \"-\")).asy\"; data=y, render=4, scaleAxes=(7.5,7.5,7.5) )\nend\nif ExportTable\n    A = cat( [ y[1] for y in yRec], [y[3] for y in yRec]; dims=2 )\n    CSV.write(string(resultsFolder*experimentName*\"ResultCost.csv\"),\n    DataFrame(A), writeheader=false);\n    save(resultsFolder*experimentName*\"-CostValue.jld2\",\n    Dict(\"compareCostFunctionValue\" => last(yRec)[3])\n    )\nend", "meta": {"hexsha": "67ee488c5bb269047e307fd414a502fec5cb9be9", "size": 1899, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/examples/Total_Variation/SPDImage_CPPA.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Manopt.jl-0fc0a36d-df90-57f3-8f93-d78a9fc72bb5", "max_stars_repo_head_hexsha": "f97ecec064f282c7ca599c2e5da455f745f761b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/examples/Total_Variation/SPDImage_CPPA.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Manopt.jl-0fc0a36d-df90-57f3-8f93-d78a9fc72bb5", "max_issues_repo_head_hexsha": "f97ecec064f282c7ca599c2e5da455f745f761b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/examples/Total_Variation/SPDImage_CPPA.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Manopt.jl-0fc0a36d-df90-57f3-8f93-d78a9fc72bb5", "max_forks_repo_head_hexsha": "f97ecec064f282c7ca599c2e5da455f745f761b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6290322581, "max_line_length": 159, "alphanum_fraction": 0.6966824645, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.8499711775577735, "lm_q1q2_score": 0.7666065884566549}}
{"text": "## Environment and packages\ncd(@__DIR__)\nusing Pkg; Pkg.activate(\".\"); Pkg.instantiate()\n\nusing OrdinaryDiffEq\nusing ModelingToolkit\nusing DataDrivenDiffEq\nusing LinearAlgebra, Optim\nusing DiffEqFlux, Flux\nusing Plots\ngr()\nusing JLD2, FileIO\nusing Statistics\n# Set a random seed for reproduceable behaviour\nusing Random\nRandom.seed!(1235)\n\n# Create a name for saving ( basically a prefix )\nsvname = \"Scenario_3_\"\n\n## Data Generation\n# Parameters\nD = 0.01f0; #diffusion\nr = 1.0f0; #reaction rate\n\n# Domain\nX = 1.0f0; T = 5f0;\ndx = 0.04f0; dt = T/10;\nx = collect(0:dx:X);\nt = collect(0:dt:T);\nNx = Int64(X/dx+1);\nNt = Int64(T/dt+1);\n\n#initial conditions\nAmp = 1.0f0;\nDelta = 0.5f0;\nrho_ic(Δ) = Amp*(tanh.((x .- (0.5f0 - Δ/2))/(Δ/10)) - tanh.((x .- (0.5f0 + Δ/2))/(Δ/10)))/2\n\n# Reaction term\nreaction(u) = r * u .* (1f0 .- u)\n# Difference Op\nlap = Float32.(diagm(0 => -2.0f0 * ones(Nx), 1=> ones(Nx-1), -1 => ones(Nx-1)) ./ dx^2)\n#Periodic BC\nlap[1,end] = 1.0f0/dx^2\nlap[end,1] = 1.0f0/dx^2\n\nfunction rc_ode(rho, p, t)\n    #finite difference\n    D * lap * rho + reaction.(rho)\nend\n\n# Generate random measurements\nprobpde = ODEProblem(rc_ode, rho_ic(Delta), (0.0f0, T), saveat=dt)\nsolution = solve(probpde, Tsit5());\n\n# Ideal data\nX = Array(solution)\nt = solution.t\n\n# Add noise in terms of the mean\nx̄ = mean(X, dims = 2)\nnoise_magnitude = Float32(2.5e-2)\nXₙ = X .+ (noise_magnitude*x̄) .* randn(eltype(X), size(X))\n\n\n\npl_solution_1 = plot(solution, color = :black, ylabel = \"rho(x,t)\", label = [\"True Data\" [nothing for i in 1:Nx-1]...])\nscatter!(t, transpose(Xₙ), color = :red,label = [\"Noisy Data\" [nothing for i in 1:Nx-1]...], legend =:bottomright)\n# Create dataset plot\npl_contour = contour(t,x,Xₙ, xlabel = \"t\", ylabel = \"x\", fill = (true, :thermal))\npl_initial_data = plot(pl_solution_1, pl_contour, layout = (1,2))\nsavefig(pl_initial_data, joinpath(pwd(), \"plots\",\"$(svname)full_data_$(noise_magnitude).pdf\"))\n\n## Neural Network setup\n## Define the network\n# Gaussian RBF as activation\nrbf(x) = exp.(-(x.^2))\n\n# Create the network to recover the reaction\nrx_nn = FastChain(\n    FastDense(1, 5, rbf),\n    FastDense(5, 5, rbf),\n    FastDense(5, 5, rbf),\n    FastDense(5, 1)\n)\n\n#initialize D0 close to D/dx^2\nD0 = Float32[6.5]\np1s = initial_params(rx_nn)\np2s = zeros(Float32, 4)\np = [p1s;p2s;D0]\n\nfunction nn_ode(u,p,t)\n    # This is the dircetional derivative\n    u_cnn_1   = [p[end-4] * u[end] + p[end-3] * u[1] + p[end-2] * u[2]]\n    u_cnn     = [p[end-4] * u[i-1] + p[end-3] * u[i] + p[end-2] * u[i+1] for i in 2:size(u, 1)-1]\n    u_cnn_end = [p[end-4] * u[end-1] + p[end-3] * u[end] + p[end-2] * u[1]]\n\n    [rx_nn([ui], p[1:length(p1s)])[1] for ui in u] + p[end] * vcat(u_cnn_1, u_cnn, u_cnn_end)\nend\n\nprob_nn = ODEProblem(nn_ode, Xₙ[:, 1], (t[1], t[end]), p)\n\n\n## Necessary functions\n\nfunction predict_pde(θ, X = Xₙ[:, 1], T = t)\n  # No ReverseDiff if using Flux\n  Array(solve(prob_nn, Vern7(),\n        u0 = X, p = θ, tspan = (T[1], T[end]), saveat=T,\n        sensealg=ForwardDiffSensitivity(convert_tspan = false)#, reltol = 1e-4, abstol = 1e-4\n        ))\nend\n\n#match data and force the weights of the CNN to add up to zero\nfunction objective_pde(p)\n    pred = predict_pde(p)\n    sum(abs2, pred .- Xₙ) + abs(sum(p[end-4 : end-2]))\nend\n\n# Container to track the loss\nlosses = Float32[]\n\n# Callback to see the training\ncallback(θ,l) = begin\n    push!(losses, l)\n    if length(losses)%1==0\n        println(\"Current loss after $(length(losses)) iterations: $(losses[end])\")\n    end\n    false\nend\n\n## Train the model\n# First train with ADAM\nres1 = DiffEqFlux.sciml_train(objective_pde, p, ADAM(0.1f0), cb=callback, maxiters = 40)\n# Train with BFGS\nres2 = DiffEqFlux.sciml_train(objective_pde, res1.minimizer, BFGS(initial_stepnorm=0.1f0), cb=callback, maxiters = 10000)\np_trained = res2.minimizer\n\n## Data evaluation -> we subsample here!\ntsample = t[1]:1.0*mean(diff(t)):t[end]\nX̂ = predict_pde(p_trained, Xₙ[:,1], tsample)\n# Trained on noisy data vs real solution\npl_trajectory = plot(tsample, transpose(X̂), xlabel = \"t\", ylabel =\"rho(x,t)\", color = :red,\n label = [\"UDE Approximation\" [nothing for i in 1:25]...])\nscatter!(t, transpose(Xₙ), color = :black, label = [\"Measurements\"  [nothing for i in 1:25]...], legend = :bottomright)\nsavefig(pl_trajectory, joinpath(pwd(), \"plots\", \"$(svname)_trajectory_reconstruction.pdf\"))\n\n\n# Create estimates\nR̂ = similar(X̂)\nR̄ = similar(X̂)\nfor i in 1:size(X̂, 1), j in 1:size(X̂, 2)\n    R̂[i,j] = rx_nn(X̂[i,j], p_trained[1:length(p1s)])[1]\n    R̄[i,j] = reaction(X̂[i,j])\nend\n\npl_reconstruction = plot(tsample, R̂', label = [\"UDE Approximation\" [nothing for i in 1:25]...], color = :red, xlabel = \"t\", ylabel = \"Reaction(x,t)\")\nplot!(tsample, R̄', label = [\"True Reaction\" [nothing for i in 1:25]...], color = :black)\npl_reconstruction_error = plot(tsample, norm.(eachcol(R̂ - R̄)), color = :red, xlabel = \"t\", ylabel = \"L2 Error\")\npl_missing = plot(pl_reconstruction, pl_reconstruction_error, layout = (2,1))\nsavefig(pl_missing, joinpath(pwd(), \"plots\", \"$(svname)_missingterm_reconstruction_and_error.pdf\"))\npl_overall = plot(pl_trajectory, pl_missing)\nsavefig(pl_overall, joinpath(pwd(), \"plots\", \"$(svname)_reconstruction.pdf\"))\n## Symbolic regression via sparse regression / SINDy using DataDrivenDiffEq\n\n# Reshape the reactions\n@variables u[1:1]\nb = Basis(monomial_basis(u, 10), u)\n# We assume (via the modeling) a common mapping of the states\n# via the reaction. In other words a global function. Hence, we can\n# use all measurements as one variable\nXs = Matrix(vcat(eachrow(X̂[1:end, :])...)')\nRs = Matrix(vcat(eachrow(R̂[1:end, :])...)')\n\n# Technically this is cheating until a general DataDrivenProblem is defined properly.\n# we work with the continuous form\nnn_prob = ContinuousDataDrivenProblem(Xs, zeros(Float32, size(Xs, 2)), DX = Rs)\n\nλs = Float32.(exp10.(-3:0.01:5))\nopt = STLSQ(λs)\n\nnn_res = solve(nn_prob, b, opt, maxiters = 1000, progress = true, denoise = true, normalize = false)\n# Print the output\nprintln(nn_res)\nprintln(result(nn_res))\nprintln(parameters(nn_res))\n## Save the results\n\nsave(joinpath(pwd(), \"results\" ,\"$(svname)recovery_$(noise_magnitude).jld2\"),\n    \"solution\", solution, \"X\", Xₙ, \"t\" , t, \"neural_network\" , rx_nn, \"initial_parameters\", p, \"trained_parameters\" , p_trained, # Training\n    \"losses\", losses, \"result\", nn_res,  # Recovery\n    ) # Estimation\n", "meta": {"hexsha": "8945db71b9f2921a8869d551d434dc719f346e73", "size": 6349, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LotkaVolterra/scenario_3.jl", "max_stars_repo_name": "chepyle/universal_differential_equations", "max_stars_repo_head_hexsha": "c10bd27b9a5b158663ca6eeb29dc64e65abb5c74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 173, "max_stars_repo_stars_event_min_datetime": "2020-01-15T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:23:25.000Z", "max_issues_repo_path": "LotkaVolterra/scenario_3.jl", "max_issues_repo_name": "chepyle/universal_differential_equations", "max_issues_repo_head_hexsha": "c10bd27b9a5b158663ca6eeb29dc64e65abb5c74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-01-28T02:37:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T05:47:26.000Z", "max_forks_repo_path": "LotkaVolterra/scenario_3.jl", "max_forks_repo_name": "chepyle/universal_differential_equations", "max_forks_repo_head_hexsha": "c10bd27b9a5b158663ca6eeb29dc64e65abb5c74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2020-01-21T08:13:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:43:29.000Z", "avg_line_length": 32.7268041237, "max_line_length": 150, "alphanum_fraction": 0.6649866121, "num_tokens": 2245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7666065777796884}}
{"text": "\"\"\"\n    GoldenSection <: UnivariateAlgorithm\n\nThe golden section search algorithm optimize a univariate function by iteratively shrinking \nthe initial bracket around the minimum with the golden ratio as an approximation to the \nFibonacci sequence.\n\"\"\"\nstruct GoldenSection <: UnivariateAlgorithm end\n\nfunction _optimize(f, lower::T, upper::T, alg::GoldenSection; \n        reltol, abstol, maxiter) where {T}\n    p = φ - 1\n    x = T(p * lower + (1 - p) * upper)\n    yx = f(x)\n    converged = false\n    iter = 1\n    while true\n        x_tol = reltol * abs(x) + abstol\n        if abs(upper - lower) < 2x_tol\n            converged = true\n            break\n        end\n        iter == maxiter && break\n        iter += 1\n        new_x = T(p * upper + (1 - p) * lower)\n        new_yx = f(new_x)\n        if yx > new_yx\n            lower, x, yx = x, new_x, new_yx\n        else\n            lower, upper = new_x, lower\n        end\n    end\n    return Solution(converged, iter, x, yx)\nend", "meta": {"hexsha": "013b6556d08fa873cc103e3ad3efdc6e1bddcb6c", "size": 974, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/algorithms/golden_section.jl", "max_stars_repo_name": "lhnguyen-vn/Optini.jl", "max_stars_repo_head_hexsha": "81e94ff764daa9819edae4b4b8211726a7de0821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-24T21:26:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T21:26:59.000Z", "max_issues_repo_path": "src/univariate/algorithms/golden_section.jl", "max_issues_repo_name": "lhnguyen-vn/Optini.jl", "max_issues_repo_head_hexsha": "81e94ff764daa9819edae4b4b8211726a7de0821", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/algorithms/golden_section.jl", "max_forks_repo_name": "lhnguyen-vn/Optini.jl", "max_forks_repo_head_hexsha": "81e94ff764daa9819edae4b4b8211726a7de0821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-18T21:08:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T21:08:54.000Z", "avg_line_length": 28.6470588235, "max_line_length": 92, "alphanum_fraction": 0.5872689938, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7666065709243743}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.0\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ c07d1eba-ea4c-4ef3-82cd-7db338e40c34\nusing LinearAlgebra, PlutoUI, Plots\n\n# ╔═╡ a15c0e18-c71c-4e22-9818-50f26b1b6907\nmodule Solution\n\n\tusing LinearAlgebra\n\n\texport solve_quadratic, quadratic_ls, gradient_descent\n\n\n\tabstract type Tracker end\n\n\tstruct NoTrack <: Tracker\n\tend\n\n\tnotrack = NoTrack()\n\n\tstruct PathTrack{T<:Any} <: Tracker\n\t\txsteps::Array{T,1}\n\t\tPathTrack(x::T) where {T} = new{T}(copy(T[x]))\n\tend\n\n\ttrace(::NoTrack, x) = nothing\n\ttrace(tracker::PathTrack, x) = push!(tracker.xsteps, copy(x))\n\n\tnsteps(tracker::PathTrack) = length(tracker.xsteps) - 1\n\n\tfunction getx(tracker::PathTrack)\n\t\tn = length(tracker.xsteps)\n\t\treturn [x[1] for x in tracker.xsteps], [x[2] for x in tracker.xsteps]\n\tend\n\n\t\"\"\"\n\t\tsolve_quadratic(p::Real, q::Real[, r::Real=0.0])\n\n\tFinds the minimizer of an 1-D quadratic system. If the quadratic term `p` is\n\tnegative, the function raises an error.\n\n\tInputs:\n\t\t- `p`, `q`, `r`: the terms of the 1-D quadratic system\n\n\tOutput:\n\t\t- xstar: the minimizer, a number\n\t\"\"\"\n\tfunction solve_quadratic(p::Real, q::Real, r::Real=0.0)\n\t\t@assert p > 0.0\n\t\treturn - q / p\n\tend\n\n\n\t\"\"\"\n\t\tsolve_quadratic(P::AbstractMatrix, q::AbstractVector, r::Real=0)\n\n\tFinds the minimizer of an N-D quadratic system.\n\tP is assumed to be a symmetric positive-definite matrix.\n\n\tInputs:\n\t\t- P, q, r: the terms of the nD quadratic system\n\n\tOutput:\n\t\t- xstar: the minimizer, an (n x 1) vector\n\t\"\"\"\n\tfunction solve_quadratic(P::AbstractMatrix, q::AbstractVector, r::Real=0.0)\n\t\treturn - P \\ q\n\tend\n\n\n\t\"\"\"\n\t\tquadratic_ls(P::AbstractMatrix, q::AbstractVector, Δx::AbstractVector,\n\t\t\t\t\t\t\t\t\t\tx::AbstractVector)\n\n\tFind the exact step size that minimized a quadratic system in\n\ta given point x for a given search direction Dx\n\n\tInputs:\n\t\t- P, q: the terms of the nD quadratic system\n\t\t- x: starting point\n\t\t- Δx: search direction\n\n\tOutput:\n\t\t- t: optimal step size\n\t\"\"\"\n\tfunction quadratic_ls(P::AbstractMatrix, q::AbstractVector, Δx::AbstractVector,\n\t\t\t\t\t\t\t\t\t\tx::AbstractVector)\n\t\tt = solve_quadratic(Δx' * P * Δx, Δx' * P * x + Δx ⋅ q)\n\t\treturn t\n\tend\n\n\t\"\"\"\n\t\tgradient_descent(P::AbstractArray, q::AbstractVector,\n\t\t\t\tx₀::AbstractVector; β::Real=0.0, ϵ::Real=1e-6,\n\t\t\t\ttracker::Tracker=notrack)\n\n\tComputes the minimizes of a quadratic system using gradient descent. Optionally\n\tprovide momentum.\n\n\tInputs:\n\t\t- P, q: the terms of the nD quadratic system\n\t\t- x₀: starting point\n\t\t- ϵ: convergence parameter\n\t\t- β: momentum parameter\n\t\t- track: bool to indicate whether to store the path\n\n\tOutputs:\n\t\t- xstar: the found minimum\n\t\"\"\"\n\tfunction gradient_descent(P::AbstractArray, q::AbstractVector,\n\t\t\t\tx₀::AbstractVector; β::Real=0.0, ϵ::Real=1e-6,\n\t\t\t\ttrack=false)\n\t\t@assert 0 ≤ β < 1\n\t\tx = x₀  # initial value\n\t\tΔx = zero(x)  # pre-allocate a vector for the gradient\n\t\ttrack && (path = [copy(x)])\n\t\twhile true\n\t\t\tΔx .= (1.0 - β) * (- P * x .- q) .+ β *  Δx\n\t\t\tif norm(Δx) < ϵ\n\t\t\t\tbreak\n\t\t\tend\n\t\t\t# determine stepsize using exact line search\n\t\t\tt = quadratic_ls(P, q, Δx, x)\n\t\t\t# perform step\n\t\t\tx .+= t * Δx\n\t\t\ttrack && push!(path, copy(x))\n\t\tend\n\t\tif track\n\t\t\treturn x, path\n\t\telse\n\t\t\treturn x\n\tend\n\tend\n\n\nend\n\n# ╔═╡ 752ced8e-1b80-11ec-298c-050f319f7228\nmd\"\"\"\n# Quadratic optimization\n\n*STMO*\n\n**Michiel Stock**\n\n![](https://github.com/MichielStock/STMO/blob/master/chapters/02.Quadratic/Figures/logo.png?raw=true)\n\"\"\"\n\n# ╔═╡ c7c39058-1035-4b34-8209-cc71837b6b38\nmd\"\"\"\n## Motivation\n\nQuadratic systems are essential! Firstly, we can often closely approximate systems close to their maximum by a quadratic system. Studying the minimization of quadratic systems can teach us about the minimization of general convex functions. Quadratic systems are also crucial in their own right! Many statistical models, graph problems, molecular models, etc. can be formulated as quadratic systems:\n\n- least-square minimization problems\n- inference using multivariate normal distributions\n- molecular modeling using spring-mass systems\n- signal recovery\n\n\"\"\"\n\n# ╔═╡ 0a65fdd9-5579-4a60-a826-d438b6a49caf\nmd\"\"\"\n## Warming up: one-dimensional quadratic systems\n\nIn the scalar case, a quadratic function is given by\n\n$$f(x) = \\frac{1}{2}px^2+qx +r\\,,$$\n\nwith $p>0$ (we will shortly see why).\n\nOur optimization problem is given by:\n\n$$\\min_x\\,\\frac{1}{2}px^2+qx +r\\,.$$\n\nThis can easily be solved by setting the first order derivative equal to zero:\n\n$$\\frac{\\mathrm{d}f(x)}{\\mathrm{d}x} = px + q$$\n\n$$px^\\star+q = 0 \\Leftrightarrow x^\\star=\\frac{-q}{p}\\,.$$\n\nTo show that this is the sole minimizer of $f(x)$, we have to prove that the second-order derivative is positive at this point. This means that at that point, the derivative of the function is increasing: a little to the left the function is increasing, a little to the right and the function is decreasing. We have\n\n$$\\left.\\frac{\\mathrm{d}^2f(x)}{\\mathrm{d}x^2}\\right|_{x^\\star} = p\\,,$$\n\nso if $p>0$ then $x^\\star$ is the minimizer of $f(x)$.\n\n\n**Assignment 1**\n\nComplete the code for solving the 1-D quadratic system. Use it to find the minimum of\n$$4x^2+8x + 2\\,.$$\nCheck the solution graphically.\n\"\"\"\n\n# ╔═╡ e2309eb6-449d-497e-84f9-2e496f29f5a5\n\"\"\"\n    solve_quadratic(p::Real, q::Real, r::Real=0.0)\n\nFinds the minimizer of a 1-D quadratic system,\nraises an error if there is no minimizer (p<0)\n\nInputs:\n    - p, q, r: the coefficients of the 1D quadratic system\n\nOutput:\n    - xstar: the minimizer\n\"\"\"\nfunction solve_quadratic(p::Real, q::Real, r::Real=0.0)\n    @assert missing\n    return missing\nend\n\n# ╔═╡ 0a9c4cc2-375b-4e0e-85ea-bc5992a92d07\nlet\n\tp = missing\n\tq = missing\n\tr = missing\n\t\n\txstar = missing\nend\n\n# ╔═╡ a7f4f2fe-8a4d-4dcf-af55-d87298b5cace\n# make a plot of the quadratic curve and its solution\n\n# ╔═╡ 60e49a4d-a497-4edc-bde1-88161e9edd5b\nmd\"\"\"\n## Towards $n$-dimensional quadratic systems\n\nLet us directly move from the one-dimensional case to the $n$-dimensional case. We will use vector notation:\n\n$$\\mathbf{x} = \\begin{bmatrix}\n       x_1 \\\\ \\vdots \\\\ x_n\n     \\end{bmatrix} \\in \\mathbb{R}^n\\,.$$\n\nA general $n$-dimensional linear system is given by:\n\n$$f(\\mathbf{x}) =\\frac{1}{2} \\mathbf{x}^\\top P \\mathbf{x} + \\mathbf{q}^\\top\\mathbf{x} + r\\,,$$\n\nwith $P$ an $n\\times n$ symmetric matrix, $\\mathbf{q}$ an $n$-dimensional vector and $r$ a scalar. Below, the contours of a two-dimensional example are shown.\n\"\"\"\n\n# ╔═╡ 3850436e-d1d3-463c-8dde-790b40582c4e\nlet\n\tP = [4 1; 1 2]\n\tq = [-1; 1]\n\tr = -10\n\t\n\t# define the function\n\tf_quadr(x) = 0.5x' * P * x + q' * x + r\n\t\n\tcontourf(-10:0.1:10, -10:0.1:10, (x, y)->f_quadr([x, y]), color=:speed)\n\t\n\txlabel!(\"x1\"); ylabel!(\"x2\")\n\t\nend\n\n# ╔═╡ f125cad0-ee03-4474-b535-c1f24c5045a2\nmd\"**Question 1**\n\nWhy is $P$ symmetric?\"\n\n# ╔═╡ ef216f91-4ee1-4b2c-8ebf-d34fb18d3a1a\nmd\"\"\"\nSo we want to solve the problem:\n\n$$\\min_\\mathbf{x}\\,\\frac{1}{2}\\mathbf{x}^\\top P \\mathbf{x} + \\mathbf{q}^\\top\\mathbf{x} + r\\,.$$\n\nThe concept of a derivative is extended towards higher dimensions using the *gradient* operator:\n\n$$\\nabla_\\mathbf{x} = \\begin{bmatrix}\n       \\frac{\\partial \\, }{\\partial x_1} \\\\ \\vdots \\\\ \\frac{\\partial \\, }{\\partial x_n}\n     \\end{bmatrix}\\,,$$\n\nso that the gradient of $f(\\mathbf{x})$ is given by:\n\n$$\\nabla_\\mathbf{x} f(\\mathbf{x}) = \\begin{bmatrix}\n       \\frac{\\partial f(\\mathbf{x}) }{\\partial x_1} \\\\ \\vdots \\\\ \\frac{\\partial f(\\mathbf{x}) }{\\partial x_n}\n     \\end{bmatrix}\\,.$$\n\nFrom now on, we will drop the subscript in the gradient when clear from context. For those not familiar to vector calculus, the most useful rules are given below. Here, $a, b$ and $c$ are scalars, $f$ and $g$ are arbitrary differentiable functions and $\\mathbf{b}$ is a vector.\n\n| rule | example                  |\n| :------------- | :------------- |\n| linearity      | $\\nabla_\\mathbf{x}(a f(\\mathbf{x}) +b g(\\mathbf{x})) = a\\nabla_\\mathbf{x} f(\\mathbf{x}) +b\\nabla_\\mathbf{x} g(\\mathbf{x})$       |\n| product rule | $\\nabla_\\mathbf{x}(f(\\mathbf{x}) g(\\mathbf{x})) = g(\\mathbf{x})\\nabla_\\mathbf{x} f(\\mathbf{x}) + f(\\mathbf{x})\\nabla_\\mathbf{x} g(\\mathbf{x})$|\n|chain rule | $\\nabla_{\\mathbf{x}} f(g(\\mathbf{x})) = \\frac{\\partial f}{\\partial g}\\mid_{g(\\mathbf{x})} \\nabla_\\mathbf{x} f(\\mathbf{x})$|\n| quadratic term | $\\nabla_\\mathbf{x} \\left(\\frac{1}{2}\\mathbf{x}^\\top A\\mathbf{x}\\right)= A\\mathbf{x}$|\n|linear term| $\\nabla_\\mathbf{x} (\\mathbf{b}^\\top\\mathbf{x})=\\mathbf{b}$|\n|constant term |$\\nabla_\\mathbf{x} c = 0$ |\n\"\"\"\n\n# ╔═╡ de7ef8bd-04c1-4c86-80ef-4e1f339f8113\nmd\"The gradient of the quadratic function is\n\t\n$$\\nabla f(\\mathbf{x})=P\\mathbf{x} +\\mathbf{q}\\,.$$\n\nSetting this to zero gives\n\n$$\\mathbf{x}^\\star=-P^{-1}\\mathbf{q}\\,.$$\n\n> *Even though the solution contains the inverse of a matrix, it is seldom a good idea to compute a matrix inverse. Instead, use a solver for the linear system $A\\mathbf{x}=\\mathbf{b}$ (numerically stable).*\n\nHow do we know that $\\mathbf{x}^\\star$ is the minimizer of the quadratic system? For this we have to extend the concept of a second order derivative to $n$ dimensions. We define the *Hessian* as:\n\n$$\\nabla^2 f(\\mathbf{x}) = \\begin{bmatrix}\n\\frac{\\partial^2 f(\\mathbf{x})}{\\partial {x_{1}^2}} & \\frac{\\partial^2 f(\\mathbf{x})}{\\partial x_1 x_2} & \\ldots &  \\frac{\\partial^2 f(\\mathbf{x})}{\\partial x_1 x_n}\\\\\n\\frac{\\partial^2 f(\\mathbf{x})}{\\partial x_1 x_2} & \\frac{\\partial^2 f(\\mathbf{x})}{\\partial {x_2}^2} & \\ldots & \\vdots \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\n\\frac{\\partial^2 f(\\mathbf{x})}{\\partial x_1 x_n} & \\frac{\\partial^2 f(\\mathbf{x})}{\\partial x_2 x_n} & \\ldots & \\frac{\\partial^2 f(\\mathbf{x})}{\\partial x_n^2}\n\\end{bmatrix}\\,.$$\n\nFor the quadratic system, this boils down to\n\n$$\\nabla^2 f(\\mathbf{x}) = P\\,.$$\n\nThe condition for $\\mathbf{x}^\\star$ to be the minimizer of $f(\\mathbf{x})$ is that the Hessian should be *positive-definite* in that point.\n\n> A symmetric $n\\times n$ matrix $A$ is positive-definite (in symbols: $A\\succ0$), if for any vector $\\mathbf{z}\\in\\mathbb{R}^n$:\n> $$\\mathbf{z}^\\top A \\mathbf{z} > 0\\,.$$\n\nA matrix is positive-definite if (and only if) all its eigenvalues as positive. In Julia, we can easily check whether a matrix is positive-define using `isposdef`:\"\n\n# ╔═╡ 8494232c-26ca-4a90-bd35-128a5bde892d\nA = [5 -1; -1 2]\n\n# ╔═╡ 9c47ce39-f015-4d51-afe7-3c6cb946d1f0\nisposdef(A)\n\n# ╔═╡ 5bd99c99-d60b-4998-8381-c516426607f5\nB = [0.5 3; 3 1]\n\n# ╔═╡ 14987a6a-a984-4b04-b951-2db4e79bcac5\nisposdef(B)\n\n# ╔═╡ 00220013-46c0-4269-a85b-125255c52de1\nmd\"\"\"\nHowever, this is an expensive operation (it is based on attempting a Cholesky decomposition), so one should avoid performing unnecessary checks for positive definiteness.\n\nA point $\\mathbf{x}^\\star$ at which the gradient vanishes is a minimizer if and only if\n\n$$\\nabla^2 f(\\mathbf{x})|_{\\mathbf{x}^\\star} \\succ 0\\,.$$\n\nSo, for the quadratic problem, $x^\\star$ is the unique minimizer iff $P\\succ 0$. This means that along every direction $\\mathbf{v}\\in \\mathbb{R}^n$ to project $\\mathbf{x}$, the problem reduces to a one-dimensional quadratic function with a positive second-order constant:\n\n$$x_v = \\mathbf{v}^\\top \\mathbf{x}\\\\\nf'(x_v) = \\frac{1}{2}x_v (\\mathbf{v}^\\top P \\mathbf{v}) x_v + (\\mathbf{v}^\\top \\mathbf{q})x_v + r\\,,$$\n\nwhere $\\mathbf{v}^\\top P \\mathbf{v}>0$ if $P\\succ 0$, which in turn implies that $f'(x_v)$ has a minimizer.\n\nIf $P\\succ 0$, the quadratic system is a *convex* function with a single minimizer. In many problems, $P$ is positive-definite, so there is a well-defined solution. We will develop this further in Chapter 2.\n\"\"\"\n\n# ╔═╡ 16f6f2e8-90d2-499c-a5c8-e69297fb9c42\nmd\"\"\"\n**Assignment 2**\n\nComplete the code for solving the $n$-D quadratic system. Use it to find the minimum of\n\n$$f(\\mathbf{x}) = \\mathbf{x}^\\top\\begin{bmatrix}4 & 1 \\\\ 1 & 2\\end{bmatrix}\\mathbf{x} + \\begin{bmatrix}3 \\\\ 1\\end{bmatrix}^\\top\\mathbf{x} + 12\\,.$$\n\"\"\"\n\n# ╔═╡ 6ff5822a-1c4e-491b-b215-b3a1698e2048\nlet\n\tP = missing\n\tq = missing\n\tr = missing\n\t\n\txstar = missing\nend\n\n# ╔═╡ da307ee7-55ce-4978-a2d6-7cf3e42a9eca\nmd\"\"\"\n\n**Question 2**\n\nConsider $L_2$ regularized ridge regression:\n\n$$\\min_\\mathbf{x}\\, \\frac{1}{2}(\\mathbf{y} - B\\mathbf{x})^\\top(\\mathbf{y} - B\\mathbf{x}) + \\frac{c}{2}\\cdot \\mathbf{x}^\\top\\mathbf{x}\\,,$$\n\nwith $c>0$. Write this in the standard form of a quadratic system and show that it is convex. Give the expression for the minimizer.\n\n## Time and memory complexity of the exact solution\n\nThe exact solution for a convex quadratic system hinges on solving a $n\\times n$ linear system. Conventional solvers for linear systems have a time complexity of $\\mathcal{O}(n^3)$. Solving such systems is doable for problems of moderate size ($n<10000$), but becomes infeasible for large-scale problems (on a standard computer).\n\"\"\"\n\n# ╔═╡ 35dce8ae-f61b-4036-baab-ff14796b30be\nmd\"\"\"\nStoring an $n\\times n$ matrix also has a memory requirement of $\\mathcal{O}(n^2)$. When $n$ is too large, this cannot fit in main memory. In the remainder of this chapter, we will consider the case when $P$ is too large to work with, while matrix-vector products $P\\mathbf{x}$ *can* be computed. Some examples of when such settings occur:\n\n- **low-rank**: $P=B^\\top B$, with $B\\in \\mathbb{R}^{n\\times p}$, with $p\\ll n$.\n- **sparse**: $P$ is a very sparse matrix.\n- **structured**: $P$ has a special structure so that $P\\mathbf{x}$ can be computed on the fly, e.g. $P_{ij}=i^2j^3$.\n- **block**: $P$ is a sparse block matrix (blocks can be loaded and processed independently).\n\"\"\"\n\n# ╔═╡ 2e6ab057-669b-4d6b-bff0-4e34056217a4\nmd\"\"\"## Descent methods\n\nInstead of computing the solution of a convex quadratic system in one step, we will use *descent methods*. Here, a minimizing sequence $\\mathbf{x}^{(k)},\\, k=1,\\dots$, where\n\n$$\\mathbf{x}^{(k+1)} = \\mathbf{x}^{(k)} +t^{(k)}\\Delta \\mathbf{x}^{(k)}\\,,$$\n\nwith $t^{(k)}\\geq 0$ called the *step size* (in machine learning often called *learning rate*) and $\\Delta \\mathbf{x}^{(k)}$ called the *search direction*. Proper descent methods have that\n\n$$f(\\mathbf{x}^{(k+1)}) < f(\\mathbf{x}^{(k)})\\,,$$\n\nexcept when $\\mathbf{x}^{(k)}$ is optimal. For this property to hold, the search direction should satisfy\n\n$$(\\Delta \\mathbf{x}^{(k)})^\\top \\nabla f(\\mathbf{x}) < 0\\,.$$\n\n![Descent and ascent step.](https://github.com/MichielStock/STMO/blob/master/chapters/02.Quadratic/Figures/descent_step.png?raw=true)\n\n\n\"\"\"\n\n# ╔═╡ 42541537-2fc5-41cf-9479-e2325c55d67d\nmd\"\"\"\n### General descent algorithm\n\nBelow is the general pseudocode of a general descent method:\n\n> **given** a starting point $\\mathbf{x}$\n>\n> **repeat**\n>> 1. Determine descent direction $\\Delta \\mathbf{x}$\n>> 2. *Line search*. Choose $t>0$.\n>> 3. *Update*. $\\mathbf{x}:=\\mathbf{x} + t \\Delta \\mathbf{x}$.\n>\n> **until** stopping criterion is reached.\n>\n> **Output**: $\\mathbf{x}$\n\nUsually, the convergence criterion is of the form\n\n$$||\\nabla f(\\mathbf{x})|| < \\nu\\,.$$\n\nThe step size can be chosen in several ways:\n\n- **exact**: $t=\\arg\\min_{s\\geq 0}\\, f(\\mathbf{x}+s\\Delta \\mathbf{x})$.\n- **approximate**: choose a $t$ that only approximately minimizes $f(\\mathbf{x}+s\\Delta \\mathbf{x})$.\n- **decaying**: choose some decaying series, e.g. $t = \\frac{1}{\\alpha+k}$.\n- **constant**: a constant step size (often works fine in practice).\n\n\nFor quadratic systems we can compute the exact step size, as this amounts to a simple one-dimensional quadratic problem:\n\n$$t=\\arg\\min_{s\\geq 0}\\, \\frac{1}{2}(\\mathbf{x}+s\\Delta \\mathbf{x})^\\top P (\\mathbf{x}+s\\Delta \\mathbf{x}) + (\\mathbf{x}+s\\Delta \\mathbf{x})^\\top \\mathbf{q} + r$$\n\n$$=\\arg\\min_{s\\geq 0}\\, \\frac{1}{2}s^2(\\Delta\\mathbf{x})^\\top P \\Delta\\mathbf{x} + s((\\Delta \\mathbf{x})^\\top P\\mathbf{x}+(\\Delta \\mathbf{x})^\\top\\mathbf{q}) +\\text{constant}$$\n\nThis can be solved as:\n\n$$t = \\frac{-(\\Delta\\mathbf{x})^\\top P \\mathbf{x}-(\\Delta\\mathbf{x})^\\top\\mathbf{q}}{(\\Delta\\mathbf{x})^\\top P \\Delta\\mathbf{x}}$$\n\n**Assignment 3**\n\nComplete the code for the exact line search for quadratic systems.\n\"\"\"\n\n# ╔═╡ 7931547d-7e74-45a7-ab83-3212d705dca3\n\"\"\"\n    quadratic_ls(P::AbstractMatrix, q::AbstractVector, Δx::AbstractVector,\n                                    x::AbstractVector)\n\nFind the exact step size that minimized a quadratic system in\na given point x for a given search direction Dx\n\nInputs:\n    - P, q: the terms of the nD quadratic system\n    - x: starting point\n    - Δx: search direction\n\nOutput:\n    - t: optimal step size\n\"\"\"\nfunction quadratic_ls(P::AbstractMatrix, q::AbstractVector, Δx::AbstractVector,\n                                    x::AbstractVector)\n    t = missing  # compute t\n    return t\nend\n\n# ╔═╡ 05236a85-dd10-4c10-ab9a-96cee2390d6d\nmd\"\"\"\n## Gradient descent\n\nA natural choice for the search direction is the negative gradient:\n\n$$\\Delta \\mathbf{x} = - \\nabla f(\\mathbf{x})\\,.$$\n\nRemember, for the quadratic system, the gradient was\n\n$$\\nabla f(\\mathbf{x})=P\\mathbf{x} + \\mathbf{q}\\,,$$\n\nso\n\n$$\\Delta \\mathbf{x} = - P\\mathbf{x} - \\mathbf{q}\\,.$$\n\n### Gradient descent algorithm for quadratic systems\n\n> **given** a starting point $\\mathbf{x}$\n> **repeat**\n>> 1. *Descent direction*. $\\Delta \\mathbf{x} := - P\\mathbf{x} - \\mathbf{q}$\n>> 2. *Line search*. Choose optimal $t>0$.\n>> 3. *Update*. $\\mathbf{x}:=\\mathbf{x} + t \\Delta \\mathbf{x}$.\n> **until** stopping criterion is reached.\n\n**Assignment 4**\n\nComplete the code for the gradient descent algorithm. Solve the previous quadratic system and compare it with the analytic solution. Start at $\\mathbf{x}^{(0)}=[0,0]^\\top$. How many steps do you need for the algorithm to converge? You can access this information from a `Tracker` structure using the function `length`.\n\"\"\"\n\n# ╔═╡ 91e61db9-57b8-4576-9960-bd74984f57b0\n\"\"\"\n    gradient_descent(P::AbstractArray, q::AbstractVector,\n            x₀::AbstractVector; ϵ::Real=1e-6,\n            tracker::Tracker=notrack)\n\nComputes the minimizes of a quadratic system using gradient descent. Optionally\nprovide momentum.\n\nInputs:\n    - P, q: the terms of the nD quadratic system\n    - x₀: starting point\n    - ϵ: convergence parameter\n    - tracker: object of the type `Tracker` to save the steps\n\nOutputs:\n    - xstar: the found minimum\n\"\"\"\nfunction gradient_descent(P::AbstractArray, q::AbstractVector,\n            x₀::AbstractVector; ϵ::Real=1e-4)\n\n    x = x0  # initial value\n    n_steps = 0\n    while true\n        Dx = missing  # compute GD direction\n        if missing\n            break\n        end\n        t = missing  # step size\n        missing  # perform step\n    end\n    return x\n  end\n\n# ╔═╡ 3244fd32-30a3-4e5a-9884-dfb89ce867c7\n# solve the system with gradient descent\n\n# ╔═╡ 4b7fbd19-8b0f-4097-95a4-778c48833dcc\n@bind γ Slider(1:0.1:20, default=10)\n\n# ╔═╡ 8c80e876-55de-414d-81d4-292231b281ad\nmd\"\"\"\n### Illustration\n\nWe illustrate the gradient descent algorithm for the following system:\n\n$$\\min_{x_1,x_2}\\, \\frac{1}{2} (x_1^2 + \\gamma x_2^2)\\,$$\n\nwith $\\gamma$ set to $γ.\n\"\"\"\n\n# ╔═╡ 9359bca7-f702-4b9c-a55d-a2a85bda62b7\nmd\"\"\"\n## Convergence analysis\n\nWe can study the convergence of the gradient descent algorithm by using eigenvalue decomposition. The matrix $P$ can be written as:\n\n$$P = U\\Lambda U^\\top\\,,$$\n\nwith\n\n-  $\\Lambda=\\text{diag}(\\lambda_1,\\ldots,\\lambda_n)$ a matrix with the eigenvalues on the diagonal (sorted from small to large);\n-  $U = [\\mathbf{u}_1, \\ldots, \\mathbf{u}_n]$, a matrix with the corresponding eigenvectors.\n\nNote that because $P\\succ 0$, all eigenvalues are real and positive, and all eigenvectors form a real orthonormal basis.\n\nConsider the following linear transformation:\n\n$$\\mathbf{z}^{(k)}= U^\\top ( \\mathbf{x}^{\\star}-\\mathbf{x}^{(k)})\\,,$$\n\nwhich allows us to rewrite the error in closed-form:\n\n$$f(\\mathbf{x}^{(k)}) - f(\\mathbf{x}^\\star) = \\frac{1}{2}\\sum_{i=1}^n (1-t\\lambda_i)^{2k}\\lambda_i[(\\mathbf{u}_i)^\\top(\\mathbf{x}^{(0)}-\\mathbf{x}^\\star)]^2\\,.$$\n\nHere, we see that:\n\n1. The error decomposes in independent terms in the eigenspace.\n2. The convergence of each term is determined by the *rate*: $|1-t\\lambda_i|$. Convergence occurs as a geometric series.\n3. The total number of steps until convergence is determined by either the smallest and largest eigenvalue.\n4. Optimal value for fixed step size is $t=\\frac{1}{\\lambda_1+\\lambda_n}$.\n\"\"\"\n\n# ╔═╡ ec6ef0e2-3589-4c88-90fa-4083739142ce\nmd\"\"\"\nFurthermore, it can be shown that if we use an exact line search for the step size, the error $f(\\mathbf{x}^{(k)}) - f(\\mathbf{x}^\\star)\\leq \\epsilon$ we need fewer than\n\n$$\\frac{\\log((f(\\mathbf{x}^{(0)}) - f(\\mathbf{x}^\\star))/\\epsilon)}{\\log(1/c)}\\,,$$\n\nwith $c=1-\\frac{\\lambda_1}{\\lambda_n}<1$. The quantity $\\kappa=\\frac{\\lambda_n}{\\lambda_1}$ is called the *condition number* and largely determines the convergence. We observe:\n\n- The quality of the initial guess $f(\\mathbf{x}^{(k)}) - f(\\mathbf{x}^\\star$) has only a logarithmic impact on the number of steps required.\n- Only a few extra steps are needed to decrease $\\epsilon$ with one order of magnitude.\n- If the condition number is large, then $\\log(1/c)\\approx 1/\\kappa$. Large condition numbers require more steps.\n\nBelow, we illustrate this bound for different condition numbers.\n\"\"\"\n\n# ╔═╡ 31937c09-736a-40b6-babe-2d386ddb430e\nmd\"\"\"\n## Gradient descent with momentum\n\n> *While finding the gradient of an objective function is a splendid idea, [descending] the gradient directly may not be.* ~ David J.C. MacKay\n\nEven on simple quadratic problems as discussed here, gradient descent often takes a surprisingly large number of steps to converge. This is because the gradient does not necessarily points in the general direction of the minimum. For convex problems, we are only guaranteed that the gradient points in the half-space of the minimum - a rather weak guarantee! Many improvements in gradient descent have been devised. We will briefly discuss a small modification that can lead to a substantial increase in performance.\n\n\"\"\"\n\n# ╔═╡ e206f6f7-c198-438b-99df-7c2942c4cc15\nmd\"\"\"\n### Steps with memory\n\n$$\\Delta \\mathbf{x}^{(k+1)} = \\beta \\Delta \\mathbf{x}^{(k)} - (1-\\beta)\\nabla f(\\mathbf{x}^{(k)})$$\n\n$$\\mathbf{x}^{(k+1)} = \\mathbf{x}^{(k)} + t^{(k)}\\Delta \\mathbf{x}^{(k+1)}\\,,$$\n\nwith $\\beta\\in[0,1)$ called the *momentum parameter*.\n\n### Gradient descent algorithm with momentum\n\n> **given** a starting point $\\mathbf{x}$,  $\\beta\\in[0,1)$\n> **initialize** $\\Delta \\mathbf{x}= \\mathbf{0}$\n> **repeat**\n>> 1. *Descent direction*. $\\Delta \\mathbf{x} := \\beta \\Delta \\mathbf{x}- (1-\\beta)(P\\mathbf{x}+\\mathbf{q})$\n>> 2. *Line search*. Choose optimal $t>0$.\n>> 3. *Update*. $\\mathbf{x}:=\\mathbf{x} + t \\Delta \\mathbf{x}$.\n> **until** stopping criterion is reached.\n> **Output** $\\mathbf{x}$\n\"\"\"\n\n# ╔═╡ 44c75163-e7b7-4071-8d61-3a609f01ffbd\n@bind β Slider(0:0.05:1, show_value=true, default=0.4)\n\n# ╔═╡ 1619f8f3-e638-4ff4-ade0-764840c11215\nβ\n\n# ╔═╡ 58f001c8-460f-42fd-9f96-c2cc9126873b\nmd\"\"\"\n## Illustration of momentum\n\n**Assignment 5**\n\n1. Complete the code for gradient descent with momentum. Use it find the solution for the above system, also starting at $\\mathbf{x}=[0,0]^\\top$. Set $\\beta=0.1$. Do you see an improvement?\n2. Compare both algorithms for minimizing the following system:\n\n$$f(\\mathbf{x}) = \\frac{1}{2}\\mathbf{x}^\\top\\begin{bmatrix}500 & 2 \\\\ 2 & 1\\end{bmatrix}\\mathbf{x} + \\begin{bmatrix}-40 \\\\100 \\end{bmatrix}^\\top\\mathbf{x} -5\\,,$$\n\nat $\\mathbf{x}_0= [0, 0]^\\top$. Does momentum increase the speed now?\n\"\"\"\n\n# ╔═╡ ae161416-fae9-4d75-81a4-dfacb82db055\n\"\"\"\n    gradient_descent_momentum(P::AbstractArray, q::AbstractVector,\n            x₀::AbstractVector; β::Real=0.0, ϵ::Real=1e-6,\n            tracker::Tracker=notrack)\n\nComputes the minimizes of a quadratic system using gradient descent. Optionally\nprovide momentum.\n\nInputs:\n    - P, q: the terms of the nD quadratic system\n    - x₀: starting point\n    - ϵ: convergence parameter\n    - β: momentum parameter\n    - tracker: object of the type `Tracker` to save the steps\n\nOutputs:\n    - xstar: the found minimum\n\"\"\"\nfunction gradient_descent_momentum(P::AbstractArray, q::AbstractVector,\n            x₀::AbstractVector; β::Real=0.0, ϵ::Real=1e-6)\n    @assert 0 ≤ β < 0\n    x = x₀  # initial value\n    Δx = zero(x)  # pre-allocate a vector for the gradient\n    while true\n        Δx .= missing\n        if missing\n            break\n        end\n        # determine stepsize using exact line search\n        t = quadratic_ls(P, q, Δx, x)\n        # perform step\n        x .+= missing\n    end\n    return x\nend\n\n# ╔═╡ 62524ce5-75f1-4ddb-a69c-a219c1c7c50e\nmd\"\"\"\n## Conjugated gradient descent\n\nConjugated gradient descent is an important method for approximately minimizing quadratic systems. It converges much faster than simple gradient descent and does not have a hyperparameter as with momentum updates.\n\nThe main idea is that in every step the current search direction and all previous search directions are conjugate with respect to $P$, i.e.\n\n$$(\\Delta\\mathbf{x}^{(k)})^\\top  P\\Delta\\mathbf{x}^{(l)}=0 \\quad\\forall  k> l\\,.$$\n\n- The search directions can be computed \\alert{without} storing the previous directions.\n- Solves an $n$-dimensional quadratic system exactly in $n$ steps (provided there are no numerical errors).\n- Convergence is\n\n$$|\\mathbf{e}^{(k)}|_P \\le \\left(\\frac{\\kappa -1}{\\kappa + 1} \\right)^k|\\mathbf{e}^{(0)}|_P\\,$$\n\nwith $|\\mathbf{e}^{(k)}|_P = (\\mathbf{x}^\\star - \\mathbf{x}^{(k)})^\\top P (\\mathbf{x}^\\star - \\mathbf{x}^{(k)})$.\n\nThe interested reader is referred to '[An Introduction to the Conjugate Gradient Method Without the Agonizing Pain](http://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf)' by Jonathan Richard Shewchuk for an in-depth overview.\n\"\"\"\n\n# ╔═╡ 2198ca9d-7522-47e1-925a-14c7fdbc7bc5\nmd\"\"\"\n## Exercise: signal recovery\n\nAs a practical example of minimizing quadratic systems, let us consider a simple signal recovery problem. Consider an $n$-dimensional real vector $\\mathbf{x}=[x_1,\\ldots,x_n]^\\top$. Rather than observing this vector directly, we have $m$ noisy measurements at random indices (indices drawn randomly with replacement from $\\{1,\\ldots,n\\}$): $\\mathcal{O} = \\{(i_j, y_j)\\mid j=1,\\ldots,m\\}$. These measurements are stored in an $m$-dimensional vector $\\mathbf{y}$. Can we recover $\\mathbf{x}$ from $\\mathbf{y}$?\n\"\"\"\n\n# ╔═╡ 28577dc0-0521-4c07-bf9d-338d4b582bf8\nmd\"\"\"\nIf $m<n$, then we do not have a single measurement for every element of $\\mathbf{x}$. Even if $m>n$, it is likely that some elements of $\\mathbf{x}$ are not observed due to chance (for large $n$, if $n=m$, then about 37% of the elements will not be sampled). Recovering $\\mathbf{x}$ from $\\mathbf{y}$ is an impossible assumption if we do not make some assumptions, this seems an impossible problem in general.\n\nIf we assume that the different values of $\\mathbf{x}$ are on a line, then we can make a *smoothness* assumption: elements of $\\mathbf{x}$ for which the indices are close, likely will have similar values. This idea is expressed in the following minimization problem:\n\n$$\\min_\\mathbf{x}\\, \\frac{1}{2}\\sum_{(i_j, y_j)\\in \\mathcal{O}}(y_j-{x}_{i_j})^2 + \\frac{C}{2} \\mathbf{x}^\\top K^{-1}\\mathbf{x}\\,,$$\n\nwith $K^{-1}$ an inverse kernel (or covariance matrix) and $C$ a tuning hyperparameter. The matrix $K^{-1}$ encodes how the different elements of $\\mathbf{x}$ are related, constructing such a matrix is a topic in machine learning (see course Predictive Modelling). For our purposes, we have chosen this matrix as such that elements should have values closes to each other. Hence, the minimization problem has two terms:\n\n- a data-fitting term to make sure that the recovered vector $\\mathbf{x}$ matches the observations,\n- a regularization term to ensure the smoothness of the solution.\n\nThe parameter $C$ determines the trade-off between the two terms. See below for the heatmap of $K$.\n\"\"\"\n\n# ╔═╡ 98e95644-913f-46d9-9deb-d78f7102db3b\nmd\"\"\"\nThe problem can written purely in matrix notation by using the $(m\\times n)$ *bookkeeping matrix* $R$ for which $R_{ij}=1$ if the the $j$-th element of $\\mathbf{y}$ corresponds to the $i$-th element of $\\mathbf{x}$ and $R_{ij}=0$ otherwise. Hence, the compact matrix form is:\n\n$$\\min_\\mathbf{x}\\, \\frac{1}{2}(\\mathbf{y}-R\\mathbf{x})^\\top(\\mathbf{y}-R\\mathbf{x}) + \\frac{C}{2} \\mathbf{x}^\\top K^{-1}\\mathbf{x}\\,.$$\n\"\"\"\n\n# ╔═╡ 7cb64961-d94b-4fe7-913d-50bd094553f2\nmd\"\"\"\n**Assignments**\n\n1. Write the minimization problem in the standard form.\n2. Use the function `generate_noisy_measurements` to generate $m=100$ noisy measurements (standard deviation is 1, default) of a vector with dimensionality $n=1000$. Use the functions `make_connection_matrix` and `make_bookkeeping` to generate the associated matrices $K^{-1}$ and $R$.\n3. Use $C=1$, generate $\\mathbf{x}^\\star$ using the closed-form solution, using gradient descent and gradient descent with momentum. How many steps do the two descent methods need to converge? Use a vector of zeros as the initial point.\n4. Minimize the system for values of $C=1\\times 10^{-2}, 1\\times 10^{-1}, 1, 10, 100$.  Use for momentum $\\beta=0, 0.1, 0.2,\\ldots, 0.9$. Make a table of the number of steps needed to reach convergence for the different values of $C$ and $\\beta$. Make a plot with the different $\\mathbf{x^\\star}$ for different values of $C$. Note that the result should be (nearly) the same whether you use momentum or not, only the number of steps will differ.\n\"\"\"\n\n# ╔═╡ 8e74c0e1-a2de-4a3b-9e9e-41c006ea4c7f\n\n\n# ╔═╡ 3e1f98e8-fea3-40bf-a9dd-9af36afc7877\n\n\n# ╔═╡ 742b079b-092c-4907-9029-2aa6916c8d2e\n\n\n# ╔═╡ 313f361f-a93d-403a-856f-5ffa9c2557c7\nmd\"\"\"\n## References\n\n- Boyd, S. and Vandenberghe, L., '*[Convex Optimization](https://web.stanford.edu/~boyd/cvxbook/bv_cvxbook.pdf)*'. Cambridge University Press (2004)\n- Goh, G. '[*Why Momentum really works*](https://distill.pub/2017/momentum/)' (2017)\n\"\"\"\n\n# ╔═╡ e5864656-9465-49aa-b997-2c237d16f15b\nmd\"Here are some utility functions and the solutions.\"\n\n# ╔═╡ 5beb181b-454c-4314-84e2-ee1d0f220c71\nbegin\n\tmyblue = \"#304da5\"\n\tmygreen = \"#2a9d8f\"\n\tmyyellow = \"#e9c46a\"\n\tmyorange = \"#f4a261\"\n\tmyred = \"#e76f51\"\n\tmyblack = \"#50514F\"\n\n\tmycolors = [myblue, myred, mygreen, myorange, myyellow]\nend;\n\n# ╔═╡ dbe09c4b-7ec2-415d-b1ed-c689dca7e8d1\nlet \n\tsolvetime = Float64[]\n\tinvtime = Float64[]\n\tsizes = [2, 5, 10, 50, 100, 500, 1000, 5000, 10000]\n\n\tP = randn(2, 2)\n\tq = randn(2)\n\n\t# warmup\n\t@elapsed(P \\ q)\n\t@elapsed(inv(P) * q)\n\n\tfor n in sizes\n\t\tP = randn(n, n) |> x -> x' * x + I\n\t\tq = randn(n)\n\t\tpush!(solvetime, @elapsed(P \\ q))\n\t\tpush!(invtime, @elapsed(inv(P) * q))\n\tend\n\n\tplot(sizes, solvetime, color=myblue, label=\"time for solving\", lw=2, xscale=:log10,\n\t\t\t\t\t\t\t\tyscale=:log10)\n\tplot!(sizes, invtime, color=myred, label=\"time for inverting P\", lw=2)\n\txlabel!(\"n\")\n\tylabel!(\"seconds\")\nend\n\n# ╔═╡ 07f1caf6-db49-4d9f-8ff1-d6e8e6f19db7\nlet\n\tP = [1 0; 0 γ]\n\tq = [0, 0]\n\tr = 0\n\tx₀ = [10.0, 1.0]\n\t\n\tf(x1, x2) = [x1, x2] |> x -> x' * P * x / 2 + q' * x + r\n\n\n\txstar, path = Solution.gradient_descent(P, q, copy(x₀), track=true)\n\t\n\tcontourf(-11:0.1:11, -5:0.1:5, f, color=:speed)\n\tplot!(first.(path), last.(path) , color=myorange, label=\"GD\", lw=2) \n\txlabel!(\"x1\"); ylabel!(\"x2\")\nend\n\n# ╔═╡ b3f5a694-dd90-47dd-a2e8-e238f3e8bdc7\nlet\n\tλs = [0.1, 1.5, 1.6, 1.8, 2]\n\n\tx₀ = ones(5)\n\tt = 2 / (maximum(λs) + minimum(λs))\n\t# error xstar = 0, x₀ = 1\n\terrors = [(1.0 - t * λ)^(2k) * λ * x₀ᵢ^2 for k in 0:1000, (λ, x₀ᵢ) in zip(λs, x₀)]\n\tcumerrors = cumsum(errors, dims=2)\n\tplot(cumerrors[:,1], fillrange=0, xscale=:log10, color=myblue, fillcolor=myblue, label=\"lam 1 = $(λs[1])\")\n\tplot!(cumerrors[:,2], fillrange=cumerrors[:,1], color=myred, fillcolor=myred, label=\"lam 2 = $(λs[2])\")\n\tplot!(cumerrors[:,3], fillrange=cumerrors[:,2], color=mygreen, fillcolor=mygreen, label=\"lam 3 = $(λs[3])\")\n\tplot!(cumerrors[:,4], fillrange=cumerrors[:,3], color=myorange, fillcolor=myorange, label=\"lam 4 = $(λs[4])\")\n\tplot!(cumerrors[:,5], fillrange=cumerrors[:,4], color=myyellow, fillcolor=myyellow, label=\"lam 5 = $(λs[5])\")\n\txlabel!(\"k+1\")\n\tylabel!(\"f(x) - f(x*)\")\n\ttitle!(\"Error of gradient descent\\n(cumulative eigencomponents)\")\nend\n\n# ╔═╡ 0170ef68-cf32-46a2-ac39-ff971517dfb4\nlet\n\tλs = [0.1, 1.5, 1.6, 1.8, 2]\n\n\tx₀ = ones(5)\n\tt = 2 / (maximum(λs) + minimum(λs))\n\t# error xstar = 0, x₀ = 1\n\terrors = [(1.0 - t * λ)^(2k) * λ * x₀ᵢ^2 for k in 0:1000, (λ, x₀ᵢ) in zip(λs, x₀)]\n\tcumerrors = cumsum(errors, dims=2)\n\n\n\tplot(errors, ylims=(1e-15,7), lw=2, xscale=:log10, yscale=:log10,\n\t\t\t\t color = [myblue myred myorange mygreen myyellow],\n\t\t\t\t label=[\" lambda  $i = $(λs[i])\" for j in 1:1, i in 1:5])\n\txlabel!(\"k+1\")\n\tylabel!(\"f(x) - f(x*)\")\n\ttitle!(\"Error of gradient descent\\n(individual contributions)\")\nend\n\n# ╔═╡ 41c04f53-091e-4e7f-a920-5df2a3366db6\nlet \n\tκs = [1.1, 2.5, 5, 50, 100]\n\n\tbestt(κ) = 2 / (1 + κ)\n\terrors = [(1 - bestt(κ))^(2k) + (1-bestt(κ) * κ)^(2k) * κ for k in 1:10000, κ in κs]\n\n\tplot(errors, color = reshape(mycolors, 1, :),\n\t\t\tlabels = [\" kappa = $κ\" for i in 1:1, κ in κs],\n\t\t\txscale=:log10, yscale=:log10, ylims=(1e-10, 100), lw=2)\n\n\tκ2c(κ) = 1 - 1 / κ\n\tbounds = [exp(log(1+κ) - k * log(1/κ2c(κ))) for k in 1:10000, κ in κs]\n\n\tplot!(bounds, lw=2, ls=:dash, color = reshape(mycolors, 1, :), label=\"\")\n\tylabel!(\"f(x) - f(x*)\")\n\txlabel!(\"k + 1\")\n\ttitle!(\"Convergence (-) and bound (--) of GD\\n for different condition numbers\")\nend\n\n# ╔═╡ 575f94d7-dadb-4217-8d54-68aa5ee07236\nlet\n\tP = [1 0; 0 γ]\n\tq = [0, 0]\n\tr = 0\n\tx₀ = [10.0, 1.0]\n\t\n\tf(x1, x2) = [x1, x2] |> x -> x' * P * x / 2 + q' * x + r\n\n\t# without momentum\n\txstar, path_gd = Solution.gradient_descent(P, q, copy(x₀), track=true)\n\t# with momentum\n\txstar, path_gdm = Solution.gradient_descent(P, q, copy(x₀); β, track=true)\n\t\n\tcontourf(-11:0.1:11, -5:0.1:5, f, color=:speed)\n\tplot!(first.(path_gd), last.(path_gd) , color=myorange, label=\"GD\", lw=2) \n\tplot!(first.(path_gdm), last.(path_gdm) , color=myblue, label=\"GDM\", lw=2) \n\txlabel!(\"x1\"); ylabel!(\"x2\")\nend\n\n# ╔═╡ f03d9959-321d-4bd6-b062-1bae6fb28d64\nlet\n\tP = [1 0; 0 γ]\n\tq = [0, 0]\n\tr = 0\n\tx₀ = [10.0, 1.0]\n\t\n\tf(x) = x' * P * x / 2 + q' * x + r\n\n\t# without momentum\n\txstar, path_gd = Solution.gradient_descent(P, q, copy(x₀), track=true)\n\t# with momentum\n\txstar, path_gdm = Solution.gradient_descent(P, q, copy(x₀); β, track=true)\n\t\n\tplot(f.(path_gd), label=\"GD\", color=myorange, lw=2, yaxis=:log)\n\tplot!(f.(path_gdm), label=\"GDM\", color=myblue, lw=2)\n\txlabel!(\"iteration + 1\")\n\tylabel!(\"error\")\nend\n\n# ╔═╡ ed98b0d2-2493-4bb7-aceb-eabab7074c9a\n\n\"\"\"Compute a quadratic function.\"\"\"\nfquad(x::Vector, P::Matrix, q::Vector, r::Real=0.0) = 0.5x' * P * x + q' * x + r\n\n# ╔═╡ 5f0cc86d-0566-4269-b7a9-9a76c7ee5da0\n\n\"\"\"Plot a 1-D quadratic function.\"\"\"\nfunction plot_quadratic(p::Real, q::Real, r::Real, (xl, xu), stepsize=0.1; kwargs...)\n    return plot(x -> p*x^2 + q*x+r, xl:stepsize:xu, xlabel=\"\\$x\\$\"; kwargs...)\nend\n\n# ╔═╡ 5fba2a78-1d80-4796-9dac-04c299670231\n\"\"\"Plot a 2-D quadratic function.\"\"\"\nfunction plot_quadratic(P::AbstractMatrix, q::AbstractVector, r::Real,\n                            (x1l, x1u), (x2l, x2u), stepsize=0.1; kwargs...)\n    fun = (x1, x2) -> [x1,x2] |> x -> 0.5x' * P * x + q' * x + r\n    return contour(x1l:stepsize:x1u, x2l:stepsize:x2u, fun, xlabel=\"\\$x_1\\$\",\n                                            ylabel=\"\\$x_2\\$\"; kwargs...)\nend\n\n# ╔═╡ 6590053d-fe91-4401-88e2-03bf29b068ce\n\n\n# ╔═╡ b165fb28-2671-4b0e-8a46-9a008bb6af46\nsignalfun(x, n) = 3sin(x * 2 * pi / n) +\n            2cos(x * 4 * pi / n) +\n            sin(x * 4 * pi / n) + 0.8 * cos(x * 12 * pi / n)\n\n# ╔═╡ c139044f-83f3-4582-b301-e41ded50da4c\n\"\"\"\n    generate_noisy_measurements(m, n; σ=1.0)\n\nGenerate noisy measurements according to some function f\n\nInputs:\n    - m : number of observations\n    - n : dim of x\n    - σ : normally distributed noise (default = 1)\n\nOutput:\n    - y : vector of noisy measurements\n    - ind : vector of indices\n\"\"\"\nfunction generate_noisy_measurements(m, n; σ=1.0)\n    ind = rand(1:n, m)\n    y = signalfun.(ind, n) .+ randn(m) * σ\n    return y, ind\nend\n\n# ╔═╡ 7894fa71-96a6-4f9e-9bd5-e715975b2fb5\nbegin\n\tn, m = 1000, 100\n\ty, ind = generate_noisy_measurements(m, n);\n\tplot(x -> signalfun(x, n), 1:n, label=\" x_i \", color=myblue,\n            xlabel=\" j \", ylabel=\"value\", lw=2)\n\tscatter!(ind, y, color=myorange, label=\" y_j\")\nend\n\n# ╔═╡ 5eafacee-4c7b-4cbd-adbb-631223341785\n\"\"\"\n    make_connection_matrix(n, γ=100)\n\nGenerates the kernel matrix and the inverse kernel matrix\n\nUses γ as a characteristic length scale of the radial basis kernel,\nassumes periodic boundaries.\n\nInputs:\n    - n : number of points\n    - γ : length scale\n\nOutput:\n    - K\n    - Kinv\n\"\"\"\nfunction make_connection_matrix(n, γ=100)\n    # cyclic distance\n    d(i, j) = min((i-j)^2, ((i-n)-j)^2, ((j-n)-i)^2)\n    # distance matrix\n    D = [d(i, j) for i in 1:n, j in 1:n]\n    # kernel matrix\n    K = exp.(-D / γ^2) + 1e-2I\n    return K, inv(K)\nend\n\n\n# ╔═╡ bb203652-f242-4d21-97d6-82419b18daad\nK, Kinv = make_connection_matrix(n)\n\n# ╔═╡ d9630c7b-5840-4a87-bde7-c16629665cb2\nheatmap(log10.(K), title=\"Heatmap of K\")\n\n# ╔═╡ 1fe7b368-ad79-42b8-a682-94b59cb2f0f6\n\"\"\"\n    make_bookkeeping(I, n)\n\nConstructs the bookkeeping matrix R\n\nInputs:\n    - ind : the indices of the measurements\n    - n : dimensionality of signal vector\n\nOutput:\n    - R : m x n bookkeeping matrix\n\"\"\"\nfunction make_bookkeeping(ind, n)\n    m = length(ind)\n    R = zeros(Int, m, n)\n    for (i, j) in enumerate(ind)\n        R[i,j] = 1\n    end\n    return R\nend\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\n\n[compat]\nPlots = \"~1.22.1\"\nPlutoUI = \"~0.7.10\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"f2202b55d816427cd385a9a4f3ffb226bee80f99\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+0\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"9995eb3977fbf67b86d0a0a0508e83017ded03f2\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.14.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"4866e381721b30fac8dda4c8cb1d9db45c8d2994\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.37.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"dba1e8614e98949abfa60480b13653813d8f0157\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+0\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"c2178cfbc0a5a552e16d097fae508f2024de61a3\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.59.0\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"ef49a187604f865f4708c90e3f431890724e9012\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.59.0+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"7bf67e9a481712b3dbe9cb3dac852dc4b1162e02\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+0\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"60ed5f1643927479f845b0135bb369b031b541fa\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.14\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"8a954fed8ac097d5be04921d595f741115c1b2ad\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+0\"\n\n[[HypertextLiteral]]\ngit-tree-sha1 = \"72053798e1be56026b81d4e2682dbe58922e5ec9\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.0\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a4b12a1bd2ebade87891ab7e36fdbce582301a92\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.6\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"761a393aeccd6aa92ec3515e428c26bf99575b3b\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+0\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"5a5bc6bf062f0f95e62d0fe0a2d99699fed82dd9\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.8\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+0\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"438d35d2d95ae2c5e8780b330592b6de8494e779\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.3\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"2537ed3c0ed5e03896927187f5f2ee6a4ab342db\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.0.14\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\"]\ngit-tree-sha1 = \"4c2637482176b1c2fb99af4d83cb2ff0328fc33c\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.22.1\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"HypertextLiteral\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"Suppressor\"]\ngit-tree-sha1 = \"26b4d16873562469a0a1e6ae41d90dec9e51286d\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.10\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"44a75aa7a527910ee3d1751d1f0e4148698add9e\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.2\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"7ad0dfa8d03b7bcf8c597f59f5292801730c55b8\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.4.1\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3240808c6d463ac46f1c1cd7638375cd22abbccb\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.12\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"1958272568dc176a1d881acb797beb909c785510\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.0.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"8cbbc098554648c84f79a463c9ff0fd277144b6c\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.10\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.3\"\n\n[[Suppressor]]\ngit-tree-sha1 = \"a819d77f31f83e5792a76081eee1ea6342ab8787\"\nuuid = \"fd094767-a336-5f1f-9728-57cf17d0bbfb\"\nversion = \"0.2.0\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"1162ce4a6c4b7e31e0e6b14486a6986951c73be9\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.5.2\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\"]\ngit-tree-sha1 = \"2839f1c1296940218e35df0bbb220f2a79686670\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.18.0+4\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─752ced8e-1b80-11ec-298c-050f319f7228\n# ╠═c07d1eba-ea4c-4ef3-82cd-7db338e40c34\n# ╟─c7c39058-1035-4b34-8209-cc71837b6b38\n# ╟─0a65fdd9-5579-4a60-a826-d438b6a49caf\n# ╠═e2309eb6-449d-497e-84f9-2e496f29f5a5\n# ╠═0a9c4cc2-375b-4e0e-85ea-bc5992a92d07\n# ╠═a7f4f2fe-8a4d-4dcf-af55-d87298b5cace\n# ╟─60e49a4d-a497-4edc-bde1-88161e9edd5b\n# ╠═3850436e-d1d3-463c-8dde-790b40582c4e\n# ╟─f125cad0-ee03-4474-b535-c1f24c5045a2\n# ╟─ef216f91-4ee1-4b2c-8ebf-d34fb18d3a1a\n# ╟─de7ef8bd-04c1-4c86-80ef-4e1f339f8113\n# ╠═8494232c-26ca-4a90-bd35-128a5bde892d\n# ╠═9c47ce39-f015-4d51-afe7-3c6cb946d1f0\n# ╠═5bd99c99-d60b-4998-8381-c516426607f5\n# ╠═14987a6a-a984-4b04-b951-2db4e79bcac5\n# ╟─00220013-46c0-4269-a85b-125255c52de1\n# ╟─16f6f2e8-90d2-499c-a5c8-e69297fb9c42\n# ╠═6ff5822a-1c4e-491b-b215-b3a1698e2048\n# ╟─da307ee7-55ce-4978-a2d6-7cf3e42a9eca\n# ╟─dbe09c4b-7ec2-415d-b1ed-c689dca7e8d1\n# ╟─35dce8ae-f61b-4036-baab-ff14796b30be\n# ╟─2e6ab057-669b-4d6b-bff0-4e34056217a4\n# ╟─42541537-2fc5-41cf-9479-e2325c55d67d\n# ╠═7931547d-7e74-45a7-ab83-3212d705dca3\n# ╟─05236a85-dd10-4c10-ab9a-96cee2390d6d\n# ╠═91e61db9-57b8-4576-9960-bd74984f57b0\n# ╠═3244fd32-30a3-4e5a-9884-dfb89ce867c7\n# ╟─8c80e876-55de-414d-81d4-292231b281ad\n# ╟─4b7fbd19-8b0f-4097-95a4-778c48833dcc\n# ╟─07f1caf6-db49-4d9f-8ff1-d6e8e6f19db7\n# ╟─9359bca7-f702-4b9c-a55d-a2a85bda62b7\n# ╟─b3f5a694-dd90-47dd-a2e8-e238f3e8bdc7\n# ╟─0170ef68-cf32-46a2-ac39-ff971517dfb4\n# ╟─ec6ef0e2-3589-4c88-90fa-4083739142ce\n# ╟─41c04f53-091e-4e7f-a920-5df2a3366db6\n# ╟─31937c09-736a-40b6-babe-2d386ddb430e\n# ╟─e206f6f7-c198-438b-99df-7c2942c4cc15\n# ╠═1619f8f3-e638-4ff4-ade0-764840c11215\n# ╟─44c75163-e7b7-4071-8d61-3a609f01ffbd\n# ╟─575f94d7-dadb-4217-8d54-68aa5ee07236\n# ╟─f03d9959-321d-4bd6-b062-1bae6fb28d64\n# ╟─58f001c8-460f-42fd-9f96-c2cc9126873b\n# ╠═ae161416-fae9-4d75-81a4-dfacb82db055\n# ╟─62524ce5-75f1-4ddb-a69c-a219c1c7c50e\n# ╟─2198ca9d-7522-47e1-925a-14c7fdbc7bc5\n# ╠═7894fa71-96a6-4f9e-9bd5-e715975b2fb5\n# ╟─28577dc0-0521-4c07-bf9d-338d4b582bf8\n# ╠═bb203652-f242-4d21-97d6-82419b18daad\n# ╠═d9630c7b-5840-4a87-bde7-c16629665cb2\n# ╠═98e95644-913f-46d9-9deb-d78f7102db3b\n# ╟─7cb64961-d94b-4fe7-913d-50bd094553f2\n# ╠═8e74c0e1-a2de-4a3b-9e9e-41c006ea4c7f\n# ╠═3e1f98e8-fea3-40bf-a9dd-9af36afc7877\n# ╠═742b079b-092c-4907-9029-2aa6916c8d2e\n# ╟─313f361f-a93d-403a-856f-5ffa9c2557c7\n# ╟─e5864656-9465-49aa-b997-2c237d16f15b\n# ╠═5beb181b-454c-4314-84e2-ee1d0f220c71\n# ╠═ed98b0d2-2493-4bb7-aceb-eabab7074c9a\n# ╠═5f0cc86d-0566-4269-b7a9-9a76c7ee5da0\n# ╠═5fba2a78-1d80-4796-9dac-04c299670231\n# ╠═6590053d-fe91-4401-88e2-03bf29b068ce\n# ╠═a15c0e18-c71c-4e22-9818-50f26b1b6907\n# ╠═b165fb28-2671-4b0e-8a46-9a008bb6af46\n# ╠═c139044f-83f3-4582-b301-e41ded50da4c\n# ╠═5eafacee-4c7b-4cbd-adbb-631223341785\n# ╠═1fe7b368-ad79-42b8-a682-94b59cb2f0f6\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "c2ea0a583839e33fc4b85dd358cf104e782693c3", "size": 68612, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapters/02.Quadratic/quadratic.jl", "max_stars_repo_name": "mathematiguy/STMO", "max_stars_repo_head_hexsha": "44a2c8b986632ca943cb6a3b3b09f327235432b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/02.Quadratic/quadratic.jl", "max_issues_repo_name": "mathematiguy/STMO", "max_issues_repo_head_hexsha": "44a2c8b986632ca943cb6a3b3b09f327235432b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/02.Quadratic/quadratic.jl", "max_forks_repo_name": "mathematiguy/STMO", "max_forks_repo_head_hexsha": "44a2c8b986632ca943cb6a3b3b09f327235432b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8461147791, "max_line_length": 516, "alphanum_fraction": 0.6990613887, "num_tokens": 28325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7666065653888927}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.6\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec\nusing Pkg, DrWatson\n\n# ╔═╡ e4eeb13a-1ee4-11eb-0113-91f9a9c3b659\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, DataFrames\n\tRandom.seed!(1)\nend\n\n# ╔═╡ ac3ceabe-1ee4-11eb-3935-313e96aafd62\nmd\"## Listing 2.10\"\n\n# ╔═╡ ce43a8fa-1eee-11eb-326b-e777b76f16c6\nbegin\n\tnumbers = 10:25\n\tN = 10^7\nend;\n\n# ╔═╡ 356e29c2-1eef-11eb-2488-6d87c9d7c26f\nbegin\n\tfirstDigit(x) = Int(floor(x/10))\n\tsecondDigit(x) = x%10\n\n\tnumThirteen, numFirstIsOne, numSecondIsThree = 0, 0, 0\n\n\tfor _ in 1:N\n\t\tX = rand(numbers)\n\t\tglobal numThirteen += X == 13 \n\t\tglobal numFirstIsOne += firstDigit(X) == 1 \n\t\tglobal numSecondIsThree += secondDigit(X) == 3\n\tend\nend\n\n# ╔═╡ 356e6696-1eef-11eb-0386-8fd3dfe0c86e\nprobThirteen, probFirstIsOne, probSecondIsThree =\n    (numThirteen,numFirstIsOne,numSecondIsThree)./N\n\n# ╔═╡ 356ee814-1eef-11eb-3bbe-458402f62f3c\n(\"P(13) = \", round(probThirteen, digits=4),\n\t\"P(1_) = \",round(probFirstIsOne, digits=4),\n    \"P(_3) = \", round(probSecondIsThree, digits=4),\n    \"P(1_)*P(_3) = \",round(probFirstIsOne*probSecondIsThree, digits=4))\n\n# ╔═╡ ea086874-1eeb-11eb-2cb0-4186697d4294\nmd\"## End of listing 2.10\"\n\n# ╔═╡ Cell order:\n# ╟─ac3ceabe-1ee4-11eb-3935-313e96aafd62\n# ╠═de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec\n# ╠═e4eeb13a-1ee4-11eb-0113-91f9a9c3b659\n# ╠═ce43a8fa-1eee-11eb-326b-e777b76f16c6\n# ╠═356e29c2-1eef-11eb-2488-6d87c9d7c26f\n# ╠═356e6696-1eef-11eb-0386-8fd3dfe0c86e\n# ╠═356ee814-1eef-11eb-3bbe-458402f62f3c\n# ╟─ea086874-1eeb-11eb-2cb0-4186697d4294\n", "meta": {"hexsha": "4c4240481738ec6b31067b6a366a193e418193c1", "size": 1593, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/02/listing2.10.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/02/listing2.10.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/02/listing2.10.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.2857142857, "max_line_length": 71, "alphanum_fraction": 0.7206528562, "num_tokens": 795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7665534588636406}}
{"text": "\n\"\"\"\n    PODeigen(X)\n\nUses the eigenvalue method of snapshots to calculate the POD basis of X. Method of\nsnapshots is efficient when number of data points `n` > number of snapshots `m`.\n\"\"\"\nfunction PODeigen(X; subtractmean::Bool = false)\n\n    Xcop = deepcopy(X)\n    PODeigen!(Xcop, subtractmean = subtractmean)\n\nend\n\n\n\"\"\"\n    PODeigen(X,W)\n\nSame as `PODeigen(X)` but uses weights for each data point. The weights are equal to the\ncell volume for a volume mesh.\n\"\"\"\nfunction PODeigen(X,W::AbstractVector; subtractmean::Bool = false)\n\n    Xcop = deepcopy(X)\n    PODeigen!(Xcop,W, subtractmean = subtractmean)\n\nend\n\n\"\"\"\n    PODeigen!(X,W)\n\nSame as `PODeigen!(X)` but uses weights for each data point. The weights are equal to the\ncell volume for a volume mesh.\n\"\"\"\nfunction PODeigen!(X,W::AbstractVector; subtractmean::Bool = false)\n\n    if subtractmean\n        X .-= mean(X,dims=2)\n    end\n\n    # Number of snapshots\n    m = size(X,2)\n\n    # Correlation matrix for method of snapshots\n    C = X'*Diagonal(W)*X\n\n    # Eigen Decomposition\n    E = eigen!(C)\n    eigVals = E.values\n    eigVects = E.vectors\n\n    # Sort the eigen vectors\n    sortInd = sortperm(abs.(eigVals)/m,rev=true)\n    eigVects = eigVects[:,sortInd]\n    eigVals = eigVals[sortInd]\n\n    # Diagonal matrix containing the square roots of the eigenvalues\n    S = sqrt.(abs.(eigVals))\n\n    # Construct the modes and coefficients\n    Φ = X*eigVects*Diagonal(1 ./S)\n    a = Diagonal(S)*eigVects'\n\n    POD = PODBasis(a, Φ)\n\n    return POD, S\n\nend\n\n\n\"\"\"\n    PODeigen!(X)\n\nSame as `PODeigen(X)` but overwrites memory.\n\"\"\"\nfunction PODeigen!(X; subtractmean::Bool = false)\n\n    if subtractmean\n        X .-= mean(X,dims=2)\n    end\n\n    # Number of snapshots\n    m = size(X,2)\n\n    # Correlation matrix for method of snapshots\n    C = X'*X\n\n    # Eigen Decomposition\n    E = eigen!(C)\n    eigVals = E.values\n    eigVects = E.vectors\n\n    # Sort the eigen vectors\n    sortInd = sortperm(abs.(eigVals)/m,rev=true)\n    eigVects = eigVects[:,sortInd]\n    eigVals = eigVals[sortInd]\n\n    # Diagonal matrix containing the square roots of the eigenvalues\n    S = sqrt.(abs.(eigVals))\n\n    # Construct the modes and coefficients\n    Φ = X*eigVects*Diagonal(1 ./S)\n    a = Diagonal(S)*eigVects'\n\n    POD = PODBasis(a, Φ)\n\n    return POD, S\n\nend\n", "meta": {"hexsha": "33bb48a084b595e81566372f831b306926c47de3", "size": 2290, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PODeigen.jl", "max_stars_repo_name": "JuliaDocsForks/ProperOrthogonalDecomposition.jl", "max_stars_repo_head_hexsha": "6b889e1310ca904f43c9940e409d70a266cdd1ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-19T09:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-08T12:23:43.000Z", "max_issues_repo_path": "src/PODeigen.jl", "max_issues_repo_name": "JuliaDocsForks/ProperOrthogonalDecomposition.jl", "max_issues_repo_head_hexsha": "6b889e1310ca904f43c9940e409d70a266cdd1ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-10-17T07:09:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-05T11:00:50.000Z", "max_forks_repo_path": "src/PODeigen.jl", "max_forks_repo_name": "JuliaDocsForks/ProperOrthogonalDecomposition.jl", "max_forks_repo_head_hexsha": "6b889e1310ca904f43c9940e409d70a266cdd1ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-10-17T02:57:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-18T21:53:00.000Z", "avg_line_length": 20.8181818182, "max_line_length": 89, "alphanum_fraction": 0.6532751092, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593496, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7665534538525951}}
{"text": "using PyPlot\n\nx_lines = [-.5, 1.1, 0.6]\ny_lines = [.6, -.3, 1.3]\nplot(x_lines, y_lines)\n\nx_square = [0,1,1,0,0]\ny_square = [0,0,1,1,0]\nplot(x_square, y_square)\n\naxis(\"equal\")\ngrid(true)\nxlabel(\"x-coordinate\")\nylabel(\"y-coordinate\")\ntitle(\"Sample plot of some objects\");\n\nf(x) = sin(3x) + 0.5sin(7x) - 0.1x\nx = range(0, stop=10, length=200)      # Create x-vector, 200 points should make a good plot\n\nplot(x, f.(x))\nplot(x, f.(x .- 3), linewidth=3)\nplot(x, (@. -0.7f(100/(10 + x^2))), color=\"m\", linestyle=\"--\")\nlegend((\"f(x)\", \"f(x-3)\", \"-0.7f(x^2)\"))\ngrid(true);\n\ns = 0:0.001:1\nr = @. .1 + s + 0.1sin(50π*s)\nx = @. r*cos(10π*s)\ny = @. r*sin(10π*s)\nplot(x, y, \"k\")\naxis(\"equal\");\n", "meta": {"hexsha": "54f85b108fc8145dccb9864b298952758d643926", "size": 680, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Plotting/Plotting.jl", "max_stars_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_stars_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "textbook/_build/jupyter_execute/content/Plotting/Plotting.jl", "max_issues_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_issues_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "textbook/_build/jupyter_execute/content/Plotting/Plotting.jl", "max_forks_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_forks_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.25, "max_line_length": 92, "alphanum_fraction": 0.5720588235, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.7665519902426747}}
{"text": "using StaticArrays\n\nconst triangle1an = [\n    SVector{3}([0.333333333333333 0.333333333333333 0.333333333333333])\n]\n\nconst triangle1wn = [\n  1.0,\n]\n\nconst triangle3an = [\n    SVector{3}([0.666666666666667 0.166666666666667 0.166666666666667]),  \n    SVector{3}([0.166666666666667 0.666666666666667 0.166666666666667]),  \n    SVector{3}([0.166666666666667 0.166666666666667 0.666666666666667])\n]\n\nconst triangle3wn = [\n    0.333333333333333,\n    0.333333333333333,\n    0.333333333333333\n]\n\nconst triangle6an = [\n    SVector{3}([0.816847572980459 0.091576213509771 0.091576213509771]),\n    SVector{3}([0.091576213509771 0.816847572980459 0.091576213509771]),\n    SVector{3}([0.091576213509771 0.091576213509771 0.816847572980459]),\n    SVector{3}([0.445948490915965 0.445948490915965 0.108103018168071]),\n    SVector{3}([0.445948490915965 0.108103018168071 0.445948490915965]),\n    SVector{3}([0.108103018168071 0.445948490915965 0.445948490915965])\n]\n\nconst triangle6wn = [\n    0.109951743655322,\n    0.109951743655322,    \n    0.109951743655322,\n    0.223381589678012,\n    0.223381589678012,\n    0.223381589678012\n]\n\n\nconst triangle10an = [\n    SVector{3}([0.3333333333333333 0.3333333333333333 0.333333333333333]), \n    SVector{3}([0.0762564021238483 0.0762564021238483 0.847487195752303]), \n    SVector{3}([0.0762564021238483 0.847487195752303 0.0762564021238483]), \n    SVector{3}([0.847487195752303 0.0762564021238483 0.0762564021238483]), \n    SVector{3}([0.322653005725289 0.0709487609446569 0.606398233330054] ), \n    SVector{3}([0.322653005725289 0.606398233330054 0.0709487609446569] ), \n    SVector{3}([0.0709487609446569 0.322653005725289 0.606398233330054] ), \n    SVector{3}([0.0709487609446569 0.606398233330054 0.322653005725289] ), \n    SVector{3}([0.606398233330054 0.322653005725289 0.0709487609446569] ), \n    SVector{3}([0.606398233330054 0.0709487609446569 0.322653005725289] )\n]\n\n\nconst triangle10wn = [\n    0.19937905503631695,\n    0.06819071348353711,\n    0.06819071348353711,\n    0.06819071348353711,\n    0.09934146741884528,\n    0.09934146741884528,\n    0.09934146741884528,\n    0.09934146741884528,\n    0.09934146741884528,\n    0.09934146741884528\n]\n\n#x = [0.06302787662265326, 0.24063968500834432, 0.4664324392487761, 0.29444203981813605, 0.0443521797062553]\n#w = [0.049548433357090374, 0.1282255662128493, 0.03160255077585674, 0.06197839149376846] \nconst triangle15an = [\n    SVector{3}([0.0630278766226533 0.0630278766226533 0.873944246754694]),\n    SVector{3}([0.0630278766226533 0.873944246754694 0.0630278766226533]),\n    SVector{3}([0.873944246754694 0.0630278766226533 0.0630278766226533]),\n    SVector{3}([0.240639685008344 0.240639685008344 0.518720629983311]  ),\n    SVector{3}([0.240639685008344 0.518720629983311 0.240639685008344]  ),\n    SVector{3}([0.518720629983311 0.240639685008344 0.240639685008344]  ),\n    SVector{3}([0.466432439248776 0.466432439248776 0.0671351215024478] ),\n    SVector{3}([0.466432439248776 0.0671351215024478 0.466432439248776] ),\n    SVector{3}([0.0671351215024478 0.466432439248776 0.466432439248776] ),\n    SVector{3}([0.294442039818136 0.0443521797062553 0.661205780475609] ),\n    SVector{3}([0.294442039818136 0.661205780475609 0.0443521797062553] ),\n    SVector{3}([0.0443521797062553 0.294442039818136 0.661205780475609] ),\n    SVector{3}([0.0443521797062553 0.661205780475609 0.294442039818136] ),\n    SVector{3}([0.661205780475609 0.294442039818136 0.0443521797062553] ),\n    SVector{3}([0.661205780475609 0.0443521797062553 0.294442039818136] )\n]\n\n\nconst triangle15wn = [\n    0.049548433357090374,\n    0.049548433357090374,\n    0.049548433357090374,\n    0.1282255662128493,\n    0.1282255662128493,\n    0.1282255662128493,\n    0.03160255077585674,\n    0.03160255077585674,\n    0.03160255077585674,\n    0.06197839149376846,\n    0.06197839149376846,\n    0.06197839149376846,\n    0.06197839149376846,\n    0.06197839149376846,\n    0.06197839149376846\n]\n\n\n#x = [0.045189009784135412, 0.40360397981780544, 0.48151983478264854, 0.22206316553736064, 0.030424361731352323, 0.1369912012735261, 0.21829007096767486]\n#w = [0.025993571032099375, 0.094080073456857274, 0.051617202570398299, 0.035351705092115611, 0.045469538044873581]\nconst triangle21an = [\n    SVector{3}([0.0451890097841354 0.0451890097841354 0.909621980431729]),\n    SVector{3}([0.0451890097841354 0.909621980431729 0.0451890097841354]),\n    SVector{3}([0.909621980431729 0.0451890097841354 0.0451890097841354]),\n    SVector{3}([0.403603979817805 0.403603979817805 0.192792040364389]  ),\n    SVector{3}([0.403603979817805 0.192792040364389 0.403603979817805]  ),\n    SVector{3}([0.192792040364389 0.403603979817805 0.403603979817805]  ),\n    SVector{3}([0.481519834782649 0.481519834782649 0.0369603304347029] ),\n    SVector{3}([0.481519834782649 0.0369603304347029 0.481519834782649] ),\n    SVector{3}([0.0369603304347029 0.481519834782649 0.481519834782649] ),\n    SVector{3}([0.222063165537361 0.0304243617313523 0.747512472731287] ),\n    SVector{3}([0.222063165537361 0.747512472731287 0.0304243617313523] ),\n    SVector{3}([0.0304243617313523 0.222063165537361 0.747512472731287] ),\n    SVector{3}([0.0304243617313523 0.747512472731287 0.222063165537361] ),\n    SVector{3}([0.747512472731287 0.222063165537361 0.0304243617313523] ),\n    SVector{3}([0.747512472731287 0.0304243617313523 0.222063165537361] ),\n    SVector{3}([0.136991201273526 0.218290070967675 0.644718727758799]  ),\n    SVector{3}([0.136991201273526 0.644718727758799 0.218290070967675]  ),\n    SVector{3}([0.218290070967675 0.136991201273526 0.644718727758799]  ),\n    SVector{3}([0.218290070967675 0.644718727758799 0.136991201273526]  ),\n    SVector{3}([0.644718727758799 0.136991201273526 0.218290070967675]  ),\n    SVector{3}([0.644718727758799 0.218290070967675 0.136991201273526]  )\n]\n\nconst triangle21wn = [\n    0.025993571032099375,\n    0.025993571032099375,\n    0.025993571032099375,\n    0.09408007345685727,\n    0.09408007345685727,\n    0.09408007345685727,\n    0.0516172025703983,\n    0.0516172025703983,\n    0.0516172025703983,\n    0.03535170509211561,\n    0.03535170509211561,\n    0.03535170509211561,\n    0.03535170509211561,\n    0.03535170509211561,\n    0.03535170509211561,\n    0.04546953804487358,\n    0.04546953804487358,\n    0.04546953804487358,\n    0.04546953804487358,\n    0.04546953804487358,\n    0.04546953804487358\n]\n\n#x = [0.032653640853443702, 0.14196281952419448, 0.28318116029651036, 0.02759039318927288, 0.16543435604751824, 0.60187823586421474, 0.026774393775283171, 0.13185966517985423, 0.32750749987987121]\n#w = [ 0.00089863287010520762, 0.013780183679627252, 0.047407203691024753, 0.047279917201778536, 0.024833733334694335, 0.030636740264071611, 0.056812768636667919]\nconst triangle28an = [\n    SVector{3}([0.333333333333333 0.333333333333333 0.333333333333333]    ),\n    SVector{3}([0.0326536408534437 0.0326536408534437 0.934692718293113]),\n    SVector{3}([0.0326536408534437 0.934692718293113 0.0326536408534437]),\n    SVector{3}([0.934692718293113 0.0326536408534437 0.0326536408534437]),\n    SVector{3}([0.141962819524194 0.141962819524194 0.716074360951611]  ),\n    SVector{3}([0.141962819524194 0.716074360951611 0.141962819524194]  ),\n    SVector{3}([0.716074360951611 0.141962819524194 0.141962819524194]  ),\n    SVector{3}([0.283181160296510 0.283181160296510 0.433637679406979]  ),\n    SVector{3}([0.283181160296510 0.433637679406979 0.283181160296510]  ),\n    SVector{3}([0.433637679406979 0.283181160296510 0.283181160296510]  ),\n    SVector{3}([0.0275903931892729 0.165434356047518 0.806975250763209] ),\n    SVector{3}([0.0275903931892729 0.806975250763209 0.165434356047518] ),\n    SVector{3}([0.165434356047518 0.0275903931892729 0.806975250763209] ),\n    SVector{3}([0.165434356047518 0.806975250763209 0.0275903931892729] ),\n    SVector{3}([0.806975250763209 0.0275903931892729 0.165434356047518] ),\n    SVector{3}([0.806975250763209 0.165434356047518 0.0275903931892729] ),\n    SVector{3}([0.601878235864215 0.0267743937752832 0.371347370360502] ),\n    SVector{3}([0.601878235864215 0.371347370360502 0.0267743937752832] ),\n    SVector{3}([0.0267743937752832 0.601878235864215 0.371347370360502] ),\n    SVector{3}([0.0267743937752832 0.371347370360502 0.601878235864215] ),\n    SVector{3}([0.371347370360502 0.601878235864215 0.0267743937752832] ),\n    SVector{3}([0.371347370360502 0.0267743937752832 0.601878235864215] ),\n    SVector{3}([0.131859665179854 0.327507499879871 0.540632834940274]  ),\n    SVector{3}([0.131859665179854 0.540632834940274 0.327507499879871]  ),\n    SVector{3}([0.327507499879871 0.131859665179854 0.540632834940274]  ),\n    SVector{3}([0.327507499879871 0.540632834940274 0.131859665179854]  ),\n    SVector{3}([0.540632834940274 0.131859665179854 0.327507499879871]  ),\n    SVector{3}([0.540632834940274 0.327507499879871 0.131859665179854]  ),\n]\n\nconst triangle28wn = [\n    0.0008986328701052076,\n    0.013780183679627252,\n    0.013780183679627252,\n    0.013780183679627252,\n    0.04740720369102475,\n    0.04740720369102475,\n    0.04740720369102475,\n    0.047279917201778536,\n    0.047279917201778536,\n    0.047279917201778536,\n    0.024833733334694335,\n    0.024833733334694335,\n    0.024833733334694335,\n    0.024833733334694335,\n    0.024833733334694335,\n    0.024833733334694335,\n    0.03063674026407161,\n    0.03063674026407161,\n    0.03063674026407161,\n    0.03063674026407161,\n    0.03063674026407161,\n    0.03063674026407161,\n    0.05681276863666792,\n    0.05681276863666792,\n    0.05681276863666792,\n    0.05681276863666792,\n    0.05681276863666792,\n    0.05681276863666792\n]\n\nconst triangleAn = [\n    triangle1an,\n    triangle3an,\n    triangle6an,\n    triangle10an,\n    triangle15an,\n    triangle21an,\n    triangle28an\n\n]\n\nconst triangleWn = [\n    triangle1wn,\n    triangle3wn,\n    triangle6wn,\n    triangle10wn,\n    triangle15wn,\n    triangle21wn,\n    triangle28wn\n\n]\n\n\n", "meta": {"hexsha": "a935dd6775d6b09fa93ad2cf7004c8eef029b741", "size": 9872, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Quadrature/Triangle.jl", "max_stars_repo_name": "cmuenger/ShunnHamQuadrature.jl", "max_stars_repo_head_hexsha": "5f4af31c3ebbf9e64babae52840d3ad1496ec363", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Quadrature/Triangle.jl", "max_issues_repo_name": "cmuenger/ShunnHamQuadrature.jl", "max_issues_repo_head_hexsha": "5f4af31c3ebbf9e64babae52840d3ad1496ec363", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Quadrature/Triangle.jl", "max_forks_repo_name": "cmuenger/ShunnHamQuadrature.jl", "max_forks_repo_head_hexsha": "5f4af31c3ebbf9e64babae52840d3ad1496ec363", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1300813008, "max_line_length": 196, "alphanum_fraction": 0.7481766613, "num_tokens": 4248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012640659995, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7665519806488376}}
{"text": "module GoldenSectionSearch\n\nexport golden_section_search\n\nBase.@irrational INV_PHI    0.61803398874989484820  (sqrt(big(5)) - 1) / 2\nBase.@irrational INV_PHI_2  0.38196601125010515180  (3 - sqrt(big(5))) / 2\n\nfunction golden_section_search(f, a, b, n, args...)\n    h = b - a\n    c = a + INV_PHI_2 * h\n    d = a + INV_PHI * h\n    yc = f(c, args...)\n    yd = f(d, args...)\n    for i = 1 : n\n        if yc < yd\n            b = d\n            d = c\n            yd = yc\n            h *= INV_PHI\n            c = a + INV_PHI_2 * h\n            yc = f(c, args...)\n        else\n            a = c\n            c = d\n            yc = yd\n            h *= INV_PHI\n            d = a + INV_PHI * h\n            yd = f(d, args...)\n        end\n    end\n    if yc < yd\n        c, yc\n    else\n        d, yd\n    end\nend\n\nend # module GoldenSectionSearch\n", "meta": {"hexsha": "53f7447a925a71793a5b585725a6245b0cdd0ab5", "size": 829, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "legacy/GoldenSectionSearch.jl", "max_stars_repo_name": "dzhang314/RKTK", "max_stars_repo_head_hexsha": "0aa0dfe5980732186573a13d9bcc6d5ba7542549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-07T13:05:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-30T13:26:19.000Z", "max_issues_repo_path": "legacy/GoldenSectionSearch.jl", "max_issues_repo_name": "dzhang314/RKTK", "max_issues_repo_head_hexsha": "0aa0dfe5980732186573a13d9bcc6d5ba7542549", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "legacy/GoldenSectionSearch.jl", "max_forks_repo_name": "dzhang314/RKTK", "max_forks_repo_head_hexsha": "0aa0dfe5980732186573a13d9bcc6d5ba7542549", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-07T13:05:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-07T13:05:36.000Z", "avg_line_length": 21.2564102564, "max_line_length": 74, "alphanum_fraction": 0.4559710495, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96036116089903, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7665475873998823}}
{"text": "######### StanSample Bernoulli example  ###########\n\nusing StanSample\n\nProjDir = @__DIR__\n\nbernoulli_model = \"\ndata {\n  int<lower=1> N;\n  int<lower=0,upper=1> y[N];\n}\nparameters {\n  real<lower=0,upper=1> theta;\n}\nmodel {\n  theta ~ beta(1,1);\n  y ~ bernoulli(theta);\n}\n\";\n\ndata = Dict(\"N\" => 10, \"y\" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1])\n\n# Keep tmpdir across multiple runs to prevent re-compilation\ntmpdir = joinpath(@__DIR__, \"tmp\")\n\nsm = SampleModel(\"kw_bern\", bernoulli_model, tmpdir);\n\nsm |> display\n\nrc = stan_sample(sm; data, num_threads=4, num_cpp_chains=4, num_chains=2, seed=12);\n\nif success(rc)\n  st = read_samples(sm)\n  display(st)\n  println()\n  display(read_samples(sm, :dataframe))\nend\n\n", "meta": {"hexsha": "cff7a31dff06846b9812c118cf6bf5a197d4299d", "size": 697, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/keyword_bernoulli.jl", "max_stars_repo_name": "StanJulia/StanSample", "max_stars_repo_head_hexsha": "33e0dc72948ce92822531187d40175a4880981e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/keyword_bernoulli.jl", "max_issues_repo_name": "StanJulia/StanSample", "max_issues_repo_head_hexsha": "33e0dc72948ce92822531187d40175a4880981e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/keyword_bernoulli.jl", "max_forks_repo_name": "StanJulia/StanSample", "max_forks_repo_head_hexsha": "33e0dc72948ce92822531187d40175a4880981e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8717948718, "max_line_length": 83, "alphanum_fraction": 0.6427546628, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96036116089903, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7665475781790775}}
{"text": "using LinearAlgebra, ForwardDiff\r\n\r\nfunction NewtonProjeto(f, x)\r\n    ∇f(x) = ForwardDiff.gradient(f, x)\r\n    H(x) = ForwardDiff.hessian(f, x)\r\n    m, n = size(H(x))\r\n    η = 1e-2\r\n    Β = 1.0e-3\r\n    num_backtrack = 0\r\n    iter = 0\r\n    while norm(∇f(x)) > 1e-4\r\n        h = H(x)\r\n\r\n        if minimum(diag(h)) > 0     \r\n            ρ = 0.0\r\n        else\r\n            ρ = -minimum(diag(h)) + Β\r\n        end       \r\n\r\n        k = 0  \r\n        while   issuccess(cholesky(h + ρ*I, check=false)) == false\r\n                ρ = max(2ρ, Β)\r\n                k = k+1\r\n        end    \r\n        \r\n        F = cholesky(h + ρ*I)\r\n        J = F.L  \r\n        y = - J \\ ∇f(x)\r\n        M = J'\r\n        d = M \\ y\r\n        \r\n        # Armijo\r\n        α = 1.0\r\n        while f(x + α * d) ≥ f(x) + η * α * dot(d, ∇f(x))\r\n            α = α / 2\r\n            num_backtrack = num_backtrack + 1\r\n            if α < 1e-8\r\n                error(\"Erro no backtracking\")\r\n            end\r\n        end\r\n        x = x + α * d\r\n        \r\n        iter += 1\r\n        if iter > 10000\r\n            error(\"Nao converge\")\r\n        end\r\n    end\r\n    \r\n    return x, iter, num_backtrack\r\nend", "meta": {"hexsha": "0ecc37fd340697d367b440b5d56f26179f5ab9d7", "size": 1151, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NewtonRegularizaçãoProjeto1.jl", "max_stars_repo_name": "FKrukoski/Projeto2Solvers.jl", "max_stars_repo_head_hexsha": "8d48093e9bc1fca9470f568c2415df7bdbaa1672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NewtonRegularizaçãoProjeto1.jl", "max_issues_repo_name": "FKrukoski/Projeto2Solvers.jl", "max_issues_repo_head_hexsha": "8d48093e9bc1fca9470f568c2415df7bdbaa1672", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NewtonRegularizaçãoProjeto1.jl", "max_forks_repo_name": "FKrukoski/Projeto2Solvers.jl", "max_forks_repo_head_hexsha": "8d48093e9bc1fca9470f568c2415df7bdbaa1672", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-21T15:00:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-21T15:00:49.000Z", "avg_line_length": 23.02, "max_line_length": 67, "alphanum_fraction": 0.3735881842, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778024535094, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7664846847613132}}
{"text": "using SymPy, Combinatorics, LinearAlgebra\n\nfunction legendrePolynomials(x::SymPy.Sym,N::Integer)::Array{SymPy.Sym,1}\n    P =  Array{SymPy.Sym}(undef,N+1);\n    for n in 0:N\n        if n == 0\n            p = 1;\n        elseif n == 1\n            p = x;\n        else\n            m = n-1;\n            p = ((2*m+1)*x*P[n] -m*P[n-1])/n;\n        end\n        P[n+1] = p;\n    end\n    return P\nend\n\n\n# Have to make it typed.\nfunction innerProduct(P,Z,rangeZ)\n    intP = zeros(prod(size(P)),1);\n    for k=1:length(P)\n        p = P[k];\n        for i=1:length(Z);\n            z = Z[i];\n            zmin = rangeZ[i,1];\n            zmax = rangeZ[i,2];\n            p = integrate(p,(z,zmin,zmax));\n        end\n        intP[k] = p; #Float64(p);\n    end\n    X = reshape(intP,size(P));\n    return(X);\nend\n\nfunction getBasis(name::String,z::Array{SymPy.Sym,1},N::Integer)::Array{SymPy.Sym,1}\n    nvar = length(z);\n    @vars x\n    if name==\"Legendre\"\n        basis = legendrePolynomials(x,N); # Add other basis functions\n    else\n        error(\"Not implemented\");\n    end\n\n    Phi = [];\n    for n in 0:N\n        for indices in multiexponents(nvar,n)\n            polyBasis = 1;\n            for (i,index) in enumerate(indices)\n                polyBasis = simplify(polyBasis*subs(basis[index+1],x=>z[i]));\n            end\n            push!(Phi,polyBasis);\n        end\n    end\n    return(Phi);\nend\n\nfunction symVec(z::String,nvar::Integer)::Array{SymPy.Sym,1}\n    Z = Array{SymPy.Sym,1}(undef,nvar);\n    for i in 1:nvar\n        Z[i] = symbols(\"$(z)$(i)\",real=true);\n    end\n    return(Z);\nend\n", "meta": {"hexsha": "6c91bdaba78abf76b43c8f866e47f673ca803a1d", "size": 1566, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/PolynomialChaos.jl", "max_stars_repo_name": "uqLab/Polynomial-Chaos", "max_stars_repo_head_hexsha": "1a352175e45a4c4e71bed08de115ddbf31905016", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-22T07:18:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T12:50:11.000Z", "max_issues_repo_path": "julia/PolynomialChaos.jl", "max_issues_repo_name": "uqLab/Polynomial-Chaos", "max_issues_repo_head_hexsha": "1a352175e45a4c4e71bed08de115ddbf31905016", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/PolynomialChaos.jl", "max_forks_repo_name": "uqLab/Polynomial-Chaos", "max_forks_repo_head_hexsha": "1a352175e45a4c4e71bed08de115ddbf31905016", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7272727273, "max_line_length": 84, "alphanum_fraction": 0.5127713921, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778061099871, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7664846831362284}}
{"text": "# ---\n# title: 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K\n# id: problem1414\n# author: Indigo\n# date: 2022-2-18\n# difficulty: Medium\n# categories: Array, Greedy\n# link: <https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/description/>\n# hidden: true\n# ---\n# \n# Given an integer `k`, _return the minimum number of Fibonacci numbers whose\n# sum is equal to_`k`. The same Fibonacci number can be used multiple times.\n# \n# The Fibonacci numbers are defined as:\n# \n#   * `F1 = 1`\n#   * `F2 = 1`\n#   * `Fn = Fn-1 + Fn-2` for `n > 2.`\n# \n# It is guaranteed that for the given constraints we can always find such\n# Fibonacci numbers that sum up to `k`.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: k = 7\n#     Output: 2 \n#     Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... \n#     For k = 7 we can use 2 + 5 = 7.\n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: k = 10\n#     Output: 2 \n#     Explanation: For k = 10 we can use 2 + 8 = 10.\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: k = 19\n#     Output: 3 \n#     Explanation: For k = 19 we can use 1 + 5 + 13 = 19.\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= k <= 10^9`\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction find_min_fibonacci_numbers(k::Int)\n    fibs = [0, 1, 1]\n    while fibs[end] <= k\n        push!(fibs, fibs[end] + fibs[end - 1])\n    end\n    \"\"\"\n    If we need 2 or more fib_i's,\n    we can always use fib_{i+1} and fib_{i-2} to replace them:\n    2fib_i = fib_i + fib_{i-1} + fib_{i-2} = fib_{i+1} + fib_{i-2}.\n\n    So greedy algorithm can be performed.\n    \"\"\"\n    pop!(fibs)\n    res = 0\n    idx = length(fibs) + 1\n    while k != 0\n        idx -= 1\n        k >= fibs[idx] || continue\n        k -= fibs[idx]\n        res += 1\n    end\n    return res\nend\n## @lc code=end\n", "meta": {"hexsha": "51a0a02cc45f798f2933c76fb3bbb193576a4e99", "size": 1838, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/1414.find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k.jl", "max_stars_repo_name": "RexWzh/LeetCode.jl", "max_stars_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/1414.find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k.jl", "max_issues_repo_name": "RexWzh/LeetCode.jl", "max_issues_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/1414.find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k.jl", "max_forks_repo_name": "RexWzh/LeetCode.jl", "max_forks_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1264367816, "max_line_length": 112, "alphanum_fraction": 0.550054407, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8459424450764199, "lm_q1q2_score": 0.7664152481640676}}
{"text": "using Statistics\nusing Plots\n\ninclude(\"ga.jl\")\n\nusing .GA\n\nstr_toint(s) = parse(Int, join(Int.(s)), base=2)\n\nfitness(x::Integer) = 20 * (cos(x/3 + 1)/(x/3 + 1))\nfitness(x::Vector{Bool}) = fitness(str_toint(x))\n\nx = 0:63\ny = fitness.(x)\n\n@show x[argmin(y)]\n@show y[argmin(y)]\n\nff_plt = plot(\n    x,\n    y,\n    label=nothing,\n    title=\"Fitness Function\",\n    size=(1024, 512),\n)\nscatter!(x, y, label=nothing)\nsavefig(ff_plt, \"figs/f_f_fig.png\")\n\nlet quz=\"uniform-1\", n_pop=8, n_genes=ceil(Integer, log2(63)), uniform_p=1.0, n_repeat=100, stop_bybest=true\n    ga01_his = SimpleGA[]\n    ga05_his = SimpleGA[]\n    ga10_his = SimpleGA[]\n    ga50_his = SimpleGA[]\n\n    for i in 1:n_repeat\n        ga01 = SimpleGA(\n            n_pop=n_pop,\n            n_genes=n_genes,\n            fitness=fitness,\n            mutation_p=0.01,\n            uniform_p=uniform_p,\n        )\n        optimize!(ga01, stop_bybest=stop_bybest)\n        push!(ga01_his, ga01)\n\n        ga05 = SimpleGA(\n            n_pop=n_pop,\n            n_genes=n_genes,\n            fitness=fitness,\n            mutation_p=0.05,\n        )\n        optimize!(ga05, stop_bybest=stop_bybest)\n        push!(ga05_his, ga05)\n\n        ga10 = SimpleGA(\n            n_pop=n_pop,\n            n_genes=n_genes,\n            fitness=fitness,\n            mutation_p=0.1,\n        )\n        optimize!(ga10, stop_bybest=stop_bybest)\n        push!(ga10_his, ga10)\n\n        ga50 = SimpleGA(\n            n_pop=n_pop,\n            n_genes=n_genes,\n            fitness=fitness,\n            mutation_p=0.5,\n        )\n        optimize!(ga50, stop_bybest=stop_bybest)\n        push!(ga50_his, ga50)\n    end\n\n    mean_f(his) = mean(fitness.(broadcast(x -> x.best_chro, his)))\n    var_f(his) = var(fitness.(broadcast(x -> x.best_chro, his)))\n\n    mean_i(his) = mean(broadcast(x -> x.iter_n, his))\n    var_i(his) = var(broadcast(x -> x.iter_n, his))\n\n    fgm_c(his) = sum(broadcast(x -> str_toint(x.best_chro) == 5, his))\n\n    mut_plt_gm = plot(\n        [1, 5, 10, 50],\n        fgm_c.([ga01_his, ga05_his, ga10_his, ga50_his]),\n        label=nothing,\n        title=\"Mutation Change - Global Minimum Count\",\n        size=(1024, 512),\n    )\n    savefig(mut_plt_gm, \"figs/$(quz)_mut_gm_fig.png\")\n\n    mut_plt_f_m = plot(\n        [1, 5, 10, 50],\n        mean_f.([ga01_his, ga05_his, ga10_his, ga50_his]),\n        label=nothing,\n        title=\"Mutation Change - Fitness Mean\",\n        size=(1024, 512),\n    )\n    savefig(mut_plt_f_m, \"figs/$(quz)_mut_f_m_fig.png\")\n    mut_plt_f_v = plot(\n        [1, 5, 10, 50],\n        var_f.([ga01_his, ga05_his, ga10_his, ga50_his]),\n        label=nothing,\n        title=\"Mutation Change - Fitness Variance\",\n        size=(1024, 512),\n    )\n    savefig(mut_plt_f_v, \"figs/$(quz)_mut_f_v_fig.png\")\n\n    mut_plt_i_m = plot(\n        [1, 5, 10, 50],\n        mean_i.([ga01_his, ga05_his, ga10_his, ga50_his]),\n        label=nothing,\n        title=\"Mutation Change - N.Iterations Mean\",\n        size=(1024, 512),\n    )\n    savefig(mut_plt_i_m, \"figs/$(quz)_mut_i_m_fig.png\")\n    mut_plt_i_v = plot(\n        [1, 5, 10, 50],\n        var_i.([ga01_his, ga05_his, ga10_his, ga50_his]),\n        label=nothing,\n        title=\"Mutation Change - N.Iterations Variance\",\n        size=(1024, 512),\n    )\n    savefig(mut_plt_i_v, \"figs/$(quz)_mut_i_v_fig.png\")\nend\n\nlet quz=\"uniform-0\", n_pop=8, n_genes=ceil(Integer, log2(63)), uniform_p=0.0, n_repeat=100, stop_bybest=true\n    ga01_his = SimpleGA[]\n    ga05_his = SimpleGA[]\n    ga10_his = SimpleGA[]\n    ga50_his = SimpleGA[]\n\n    for i in 1:n_repeat\n        ga01 = SimpleGA(\n            n_pop=n_pop,\n            n_genes=n_genes,\n            fitness=fitness,\n            mutation_p=0.01,\n            uniform_p=uniform_p,\n        )\n        optimize!(ga01, stop_bybest=stop_bybest)\n        push!(ga01_his, ga01)\n\n        ga05 = SimpleGA(\n            n_pop=n_pop,\n            n_genes=n_genes,\n            fitness=fitness,\n            mutation_p=0.05,\n        )\n        optimize!(ga05, stop_bybest=stop_bybest)\n        push!(ga05_his, ga05)\n\n        ga10 = SimpleGA(\n            n_pop=n_pop,\n            n_genes=n_genes,\n            fitness=fitness,\n            mutation_p=0.1,\n        )\n        optimize!(ga10, stop_bybest=stop_bybest)\n        push!(ga10_his, ga10)\n\n        ga50 = SimpleGA(\n            n_pop=n_pop,\n            n_genes=n_genes,\n            fitness=fitness,\n            mutation_p=0.5,\n        )\n        optimize!(ga50, stop_bybest=stop_bybest)\n        push!(ga50_his, ga50)\n    end\n\n    mean_f(his) = mean(fitness.(broadcast(x -> x.best_chro, his)))\n    var_f(his) = var(fitness.(broadcast(x -> x.best_chro, his)))\n\n    mean_i(his) = mean(broadcast(x -> x.iter_n, his))\n    var_i(his) = var(broadcast(x -> x.iter_n, his))\n\n    fgm_c(his) = sum(broadcast(x -> str_toint(x.best_chro) == 5, his))\n\n    mut_plt_gm = plot(\n        [1, 5, 10, 50],\n        fgm_c.([ga01_his, ga05_his, ga10_his, ga50_his]),\n        label=nothing,\n        title=\"Mutation Change - Global Minimum Count\",\n        size=(1024, 512),\n    )\n    savefig(mut_plt_gm, \"figs/$(quz)_mut_gm_fig.png\")\n\n    mut_plt_f_m = plot(\n        [1, 5, 10, 50],\n        mean_f.([ga01_his, ga05_his, ga10_his, ga50_his]),\n        label=nothing,\n        title=\"Mutation Change - Fitness Mean\",\n        size=(1024, 512),\n    )\n    savefig(mut_plt_f_m, \"figs/$(quz)_mut_f_m_fig.png\")\n    mut_plt_f_v = plot(\n        [1, 5, 10, 50],\n        var_f.([ga01_his, ga05_his, ga10_his, ga50_his]),\n        label=nothing,\n        title=\"Mutation Change - Fitness Variance\",\n        size=(1024, 512),\n    )\n    savefig(mut_plt_f_v, \"figs/$(quz)_mut_f_v_fig.png\")\n\n    mut_plt_i_m = plot(\n        [1, 5, 10, 50],\n        mean_i.([ga01_his, ga05_his, ga10_his, ga50_his]),\n        label=nothing,\n        title=\"Mutation Change - N.Iterations Mean\",\n        size=(1024, 512),\n    )\n    savefig(mut_plt_i_m, \"figs/$(quz)_mut_i_m_fig.png\")\n    mut_plt_i_v = plot(\n        [1, 5, 10, 50],\n        var_i.([ga01_his, ga05_his, ga10_his, ga50_his]),\n        label=nothing,\n        title=\"Mutation Change - N.Iterations Variance\",\n        size=(1024, 512),\n    )\n    savefig(mut_plt_i_v, \"figs/$(quz)_mut_i_v_fig.png\")\nend\n", "meta": {"hexsha": "47de873dfc2bf2820f344f9d33f695f68957d820", "size": 6152, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "main.jl", "max_stars_repo_name": "prbzrg/EC-Class-HW1-GA", "max_stars_repo_head_hexsha": "f797596dc8632680b68170b49bae9ef55c447693", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.jl", "max_issues_repo_name": "prbzrg/EC-Class-HW1-GA", "max_issues_repo_head_hexsha": "f797596dc8632680b68170b49bae9ef55c447693", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.jl", "max_forks_repo_name": "prbzrg/EC-Class-HW1-GA", "max_forks_repo_head_hexsha": "f797596dc8632680b68170b49bae9ef55c447693", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7117117117, "max_line_length": 108, "alphanum_fraction": 0.5658322497, "num_tokens": 2002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7664152376076028}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 3e849bdf-f13a-4ea0-aa54-b6ae89894565\nmd\"\"\"\n# Álgebra lineal básica en Julia\nAutor: Andreas Noack Jensen (MIT) (http://www.econ.ku.dk/phdstudent/noack/)\n(con edición de Jane Herriman)\n\"\"\"\n\n# ╔═╡ a880f5b4-1f0f-4569-a59c-0e87d21cd203\nmd\"\"\"\nJulia's syntax is very similar to other languages but there are some important differences. Define a matrix of random normal variates\n\"\"\"\n\n# ╔═╡ 05eff53f-64c5-4833-9eff-11c7d09b9684\nA = rand(1:4,3,3)\n\n# ╔═╡ 16ca2d04-2f46-4de7-9481-daebf5112c2f\nmd\"\"\"\nDefinir un vector de unos\n\"\"\"\n\n# ╔═╡ 018e028c-43ff-4dbe-bc83-e5f0982d6bb6\nx = fill(1.0, (3))\n\n# ╔═╡ 5cc332db-a229-4182-b860-4d276e3042a9\nmd\"\"\"\nNotamos que $A$ tiene el tipo Array{Int64,2} pero $x$ tiene tipo Array{Int64,1}. Julia define los alias a Vector{Type}=Array{Type,1} y Matrix{Type}=Array{Type,2}.\n\nMuchas de las operaciones básicas son idénticas a otros lenguajes\n\n#### Multiplicación\n\"\"\"\n\n# ╔═╡ 383658c8-9d47-4a1e-ba63-66fa6e7f3311\nb = A*x\n\n# ╔═╡ e2cc7ff7-781c-4102-892c-da24291f0388\nmd\"\"\"\n#### Traspuestas\nComo en otros lenguajes, `A'` es la transpuesta conjugada mientras que `A.'` es sólo la traspuesta\n\"\"\"\n\n# ╔═╡ 5c3d3b48-6b7c-4a3b-a9b6-d83f7bc03168\nAsym = A + A'\n\n# ╔═╡ 88f5c70e-b5b1-4cf0-8f50-d1241f0a769b\nmd\"\"\"\n#### Multiplicación traspuesta\nJulia nos permite escribir esto sin *\n\"\"\"\n\n# ╔═╡ 0691212e-d372-43be-b66e-61f842df09eb\nApd = A'A\n\n# ╔═╡ 1445f674-cfa2-44ab-920f-fe4d85d00c2e\nmd\"\"\"\n#### Resolviendo sistemas lineales\nEl problema $Ax=b$ para $A$ cuadrada se resulve con la función \\.\n\"\"\"\n\n# ╔═╡ c42fc4ae-bf1d-4eb7-9863-a498fb9116b8\nA\\b\n\n# ╔═╡ 462e5a23-f323-4158-bf27-cf36bbc5cec5\nmd\"\"\"\n#### Sistemas sobredeterminados\nCuando nuestra matriz es alta (número de renglones mayores al número de columnas), tenemos un sistema lineal sobredeterminado.\n\n\nEn este caso \\ calcula la de mínimos cuadrados\n\"\"\"\n\n# ╔═╡ 8c87b3e1-b737-4179-9955-defcf0905b1b\nAtall = rand(3, 2)\ndisplay(Atall)\nAtall\\b\n\n# ╔═╡ 7dea4ca8-27e0-429e-bbf3-dccf2ca67df3\nmd\"\"\"\nLa función \\ también sirve ocn problemas deficientes de rango de mínimos cuadrados. En este caso, la solución no es única y Julia regresa el valor con la menor norma.\n\nPara crear un problema de rango deficiente de mínimos cuadrados, vamos a crear una matriz deficiente en rango con columnas linealmente dependientes\n\"\"\"\n\n# ╔═╡ 962df670-f9d1-441d-bf86-f4619f29ab4f\nv = randn(3)\n\n# ╔═╡ 306db6d0-193e-11eb-3bee-cbb7d8c4c5c6\nrankdef = [v v]\n\n# ╔═╡ 92b4cb6a-47c9-459b-8694-aee9158439dd\nrankdef\\b\n\n# ╔═╡ 4c836857-08fc-411a-8b65-6340c6e94c3b\nmd\"\"\"\n#### Sistemas indeterminados\ncuando A es corta (número de columnas mayor al número de renglones), tenemos un sistema indeterminado\n\nEn este caso \\ regresa la solución con la norma mínima\n\"\"\"\n\n# ╔═╡ 0784963e-8842-43f6-af98-781aa7e214b6\nAshort = rand(2, 3)\n\n# ╔═╡ 3346487c-193e-11eb-15dd-4dd8241ac876\ndisplay(Ashort)\n\n# ╔═╡ 3346b974-193e-11eb-2c77-9133e1f9b17b\nAshort\\b[1:2]\n\n# ╔═╡ 86dc3af8-2f80-48a5-b0d3-caeddc5ae8a8\nmd\"\"\"\n### Ejercicios\n\n\n\n```\nA = [\n 1  2  3  4  5  6  7  8  9  10\n 1  2  3  4  5  6  7  8  9  10\n 1  2  3  4  5  6  7  8  9  10\n 1  2  3  4  5  6  7  8  9  10\n 1  2  3  4  5  6  7  8  9  10\n 1  2  3  4  5  6  7  8  9  10\n 1  2  3  4  5  6  7  8  9  10\n 1  2  3  4  5  6  7  8  9  10\n 1  2  3  4  5  6  7  8  9  10\n 1  2  3  4  5  6  7  8  9  10\n ]\n```\n\nQuieres obtener\n\n```\nA = [\n 7  8  9  10  1  2  3  4  5  6\n 7  8  9  10  1  2  3  4  5  6\n 7  8  9  10  1  2  3  4  5  6\n 7  8  9  10  1  2  3  4  5  6\n 7  8  9  10  1  2  3  4  5  6\n 7  8  9  10  1  2  3  4  5  6\n 7  8  9  10  1  2  3  4  5  6\n 7  8  9  10  1  2  3  4  5  6\n 7  8  9  10  1  2  3  4  5  6\n 7  8  9  10  1  2  3  4  5  6\n ]\n```\n\"\"\"\n\n# ╔═╡ f86a1d32-1e1d-461e-ad40-f5b906b04cf9\n\n\n# ╔═╡ 22e5c662-6bf6-48d4-b7f9-93d8ac33ffdd\nmd\"\"\"\n10.2 Toma el producto de un vector `v` con sí mismo.\n\"\"\"\n\n# ╔═╡ 403752d3-4a6b-41bf-b4ed-fd6fe7b9ee95\n\n\n# ╔═╡ 6b98b27f-f671-4c5c-af5e-6d290f0d158b\nmd\"\"\"\n10.3 Toma el producto de un vector `v` con sí mismo.\n\"\"\"\n\n# ╔═╡ fd670b40-f44e-440e-90b0-b27522c7adbd\n\n\n# ╔═╡ Cell order:\n# ╟─3e849bdf-f13a-4ea0-aa54-b6ae89894565\n# ╟─a880f5b4-1f0f-4569-a59c-0e87d21cd203\n# ╠═05eff53f-64c5-4833-9eff-11c7d09b9684\n# ╟─16ca2d04-2f46-4de7-9481-daebf5112c2f\n# ╠═018e028c-43ff-4dbe-bc83-e5f0982d6bb6\n# ╟─5cc332db-a229-4182-b860-4d276e3042a9\n# ╠═383658c8-9d47-4a1e-ba63-66fa6e7f3311\n# ╟─e2cc7ff7-781c-4102-892c-da24291f0388\n# ╠═5c3d3b48-6b7c-4a3b-a9b6-d83f7bc03168\n# ╟─88f5c70e-b5b1-4cf0-8f50-d1241f0a769b\n# ╠═0691212e-d372-43be-b66e-61f842df09eb\n# ╟─1445f674-cfa2-44ab-920f-fe4d85d00c2e\n# ╠═c42fc4ae-bf1d-4eb7-9863-a498fb9116b8\n# ╟─462e5a23-f323-4158-bf27-cf36bbc5cec5\n# ╠═8c87b3e1-b737-4179-9955-defcf0905b1b\n# ╟─7dea4ca8-27e0-429e-bbf3-dccf2ca67df3\n# ╠═962df670-f9d1-441d-bf86-f4619f29ab4f\n# ╠═306db6d0-193e-11eb-3bee-cbb7d8c4c5c6\n# ╠═92b4cb6a-47c9-459b-8694-aee9158439dd\n# ╟─4c836857-08fc-411a-8b65-6340c6e94c3b\n# ╠═0784963e-8842-43f6-af98-781aa7e214b6\n# ╠═3346487c-193e-11eb-15dd-4dd8241ac876\n# ╠═3346b974-193e-11eb-2c77-9133e1f9b17b\n# ╟─86dc3af8-2f80-48a5-b0d3-caeddc5ae8a8\n# ╠═f86a1d32-1e1d-461e-ad40-f5b906b04cf9\n# ╟─22e5c662-6bf6-48d4-b7f9-93d8ac33ffdd\n# ╠═403752d3-4a6b-41bf-b4ed-fd6fe7b9ee95\n# ╟─6b98b27f-f671-4c5c-af5e-6d290f0d158b\n# ╠═fd670b40-f44e-440e-90b0-b27522c7adbd\n", "meta": {"hexsha": "f30892e7fe778bd6c0f71a97a01d6c79d86edd15", "size": 5242, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "es-es/intro-to-julia-ES/plutos/plutos2/10.AlgebraLinealBasica.jl", "max_stars_repo_name": "miguelraz/JuliaTutorials", "max_stars_repo_head_hexsha": "1d427c70c7254844c9734a20e7402e60a000528f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-11-22T00:48:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:10:03.000Z", "max_issues_repo_path": "es-es/intro-to-julia-ES/plutos/plutos2/10.AlgebraLinealBasica.jl", "max_issues_repo_name": "miguelraz/JuliaTutorials", "max_issues_repo_head_hexsha": "1d427c70c7254844c9734a20e7402e60a000528f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "es-es/intro-to-julia-ES/plutos/plutos2/10.AlgebraLinealBasica.jl", "max_forks_repo_name": "miguelraz/JuliaTutorials", "max_forks_repo_head_hexsha": "1d427c70c7254844c9734a20e7402e60a000528f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6960784314, "max_line_length": 166, "alphanum_fraction": 0.6871423121, "num_tokens": 2963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7663912668775013}}
{"text": "# One step of the metropolis algorithm on a Ising's spin graph\nfunction stepmetropolis!(grid::Array{Int, 2}; # Spin grid\n                         h::Float64    = 0.0, # External field\n                         temp::Float64 = 1.0) # Temperature\n\n    # Randomly pick a position within the grid\n    x   = rand(1:size(grid, 1))\n    y   = rand(1:size(grid, 2))\n\n    # Calculate the ΔE for switching the spin\n    m      = nspins(grid, x, y) |> sum\n    eplus  = -m - h\n    ΔE     = -2eplus * grid[x,y]\n\n    # Change spin accordingly\n    if ΔE <= 0 || rand() < exp(-ΔE/temp)\n        grid[x,y] *= -1\n    end\nend\n\n# Several steps of the heat bath algorithm on a Ising's spin graph\nfunction metropolis!(grid::Array{Int, 2};  # Spin grid\n                     h::Float64=0.0,       # External field\n                     temp::Float64=1.0,    # Temperature\n                     iters::Integer=50000, # Number of iterations\n                     plot::Bool=true,      # Plot flag\n                     verbose::Bool=true)   # Verbose flag\n\n    m = Float64[]\n    for i in 1:iters\n        stepmetropolis!(grid, h=h, temp=temp)\n        push!(m, magnetization(grid))\n        # Must find a better way to decide convergence\n    end\n\n    if verbose println(\"(T=$temp) Metropolis ended with magnetization $(m[end]) after $(length(m)) iterations\") end\n    if plot\n        PyPlot.plot(1:length(m), m, \"o\", color=\"blue\")\n        PyPlot.plot(1:length(m), m, \"-\", color=\"blue\")\n        PyPlot.title(\"Metropolis for T=$temp for size $size ($(length(m)) iterations and H=$h)\")\n        PyPlot.xlabel(\"Number of Iterations\")\n        PyPlot.ylabel(\"Magnetization\")\n        PyPlot.ylim(0,1.1)\n        PyPlot.savefig(\"metropolis_T=$temp.png\")\n        PyPlot.close()\n    end\n\n    return m\nend\n", "meta": {"hexsha": "0ec7f712ee4a50840d96013a289cb9f414d8a412", "size": 1755, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/metropolis.jl", "max_stars_repo_name": "000Justin000/IsingLite.jl", "max_stars_repo_head_hexsha": "bc3526d7565a7e62bd64fac075234c33ada6dee0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-07-18T15:54:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T16:15:37.000Z", "max_issues_repo_path": "src/metropolis.jl", "max_issues_repo_name": "000Justin000/IsingLite.jl", "max_issues_repo_head_hexsha": "bc3526d7565a7e62bd64fac075234c33ada6dee0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/metropolis.jl", "max_forks_repo_name": "000Justin000/IsingLite.jl", "max_forks_repo_head_hexsha": "bc3526d7565a7e62bd64fac075234c33ada6dee0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-01T15:51:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T13:05:34.000Z", "avg_line_length": 35.1, "max_line_length": 115, "alphanum_fraction": 0.5612535613, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7663912630697587}}
{"text": "immutable Gamma <: ContinuousUnivariateDistribution\n    shape::Float64\n    scale::Float64\n    function Gamma(sh::Real, sc::Real)\n        sh > zero(sh) && sc > zero(sc) || \n            error(\"Both shape and scale must be positive\")\n        new(float64(sh), float64(sc))\n    end\nend\n\nGamma(sh::Real) = Gamma(sh, 1.0)\nGamma() = Gamma(1.0, 1.0) # Standard exponential distribution\n\nscale(d::Gamma) = d.scale\nrate(d::Gamma) = 1.0 / d.scale\n\n@_jl_dist_2p Gamma gamma\n\nfunction entropy(d::Gamma)\n    x = (1.0 - d.shape) * digamma(d.shape)\n    x + lgamma(d.shape) + log(d.scale) + d.shape\nend\n\ninsupport(::Gamma, x::Real) = zero(x) <= x < Inf\ninsupport(::Type{Gamma}, x::Real) = zero(x) <= x < Inf\n\nkurtosis(d::Gamma) = 6.0 / d.shape\n\nmean(d::Gamma) = d.shape * d.scale\n\nmedian(d::Gamma) = quantile(d, 0.5)\n\nmgf(d::Gamma, t::Real) = (1.0 - t * d.scale)^(-d.shape)\n\ncf(d::Gamma, t::Real) = (1.0 - im * t * d.scale)^(-d.shape)\n\nfunction mode(d::Gamma)\n    d.shape >= 1.0 ? d.scale * (d.shape - 1.0) : error(\"Gamma has no mode when shape < 1.0\")\nend\n\nmodes(d::Gamma) = [mode(d)]\n\n# rand()\n#\n#  A simple method for generating gamma variables - Marsaglia and Tsang (2000)\n#  http://www.cparity.com/projects/AcmClassification/samples/358414.pdf\n#  Page 369\n#  basic simulation loop for pre-computed d and c\nfunction randg2(d::Float64, c::Float64) \n    while true\n        x = v = 0.0\n        while v <= 0.0\n            x = randn()\n            v = 1.0 + c * x\n        end\n        v = v^3\n        U = rand()\n        x2 = x^2\n        if U < 1.0 - 0.331 * x2^2 ||\n           log(U) < 0.5 * x2 + d * (1.0 - v + log(v))\n            return d * v\n        end\n    end\nend\n\n\n# sampling from Gamma(α, 1)\nfunction randg(α::Float64)\n    dpar = (α <= 1.0 ? α + 1.0 : α) - 1.0 / 3.0\n    cpar = 1.0 / sqrt(9.0 * dpar)\n    randg2(dpar, cpar) * (α > 1.0 ? 1.0 : rand()^(1.0 / α))\nend\n\nrand(d::Gamma) = d.scale * randg(d.shape)\n\nfunction rand!(d::Gamma, A::Array{Float64})\n    α = d.shape\n    dpar = (α <= 1.0 ? α + 1.0 : α) - 1.0 / 3.0\n    cpar = 1.0 / sqrt(9.0 * dpar)\n    n = length(A)\n    for i in 1:n\n        A[i] = randg2(dpar, cpar)\n    end\n    if α <= 1.0\n        ainv = 1.0 / α\n        for i in 1:n\n            A[i] *= rand()^ainv\n        end\n    end\n    multiply!(A, d.scale)\nend\n\nskewness(d::Gamma) = 2.0 / sqrt(d.shape)\n\nvar(d::Gamma) = d.shape * d.scale * d.scale\n\n\n## Fit model\n\nimmutable GammaStats\n    sx::Float64      # (weighted) sum of x\n    slogx::Float64   # (weighted) sum of log(x)\n    tw::Float64      # total sample weight\n\n    GammaStats(sx::Real, slogx::Real, tw::Real) = new(float64(sx), float64(slogx), float64(tw))\nend\n\nfunction suffstats(::Type{Gamma}, x::Array)\n    sx = 0.\n    slogx = 0.\n    for xi = x\n        sx += xi\n        slogx += log(xi)\n    end\n    GammaStats(sx, slogx, length(x))\nend\n\nfunction suffstats(::Type{Gamma}, x::Array, w::Array{Float64})\n    n = length(x)\n    if length(w) != n\n        throw(ArgumentError(\"Inconsistent argument dimensions.\"))\n    end\n\n    sx = 0.\n    slogx = 0.\n    tw = 0.\n    for i = 1:n\n        xi = x[i]\n        wi = w[i]\n        sx += wi * xi\n        slogx += wi * log(xi)\n        tw += wi\n    end\n    GammaStats(sx, slogx, tw)\nend\n\nfunction gamma_mle_update(logmx::Float64, mlogx::Float64, a::Float64)\n    ia = 1.0 / a\n    z = ia + (mlogx - logmx + log(a) - digamma(a)) / (abs2(a) * (ia - trigamma(a)))\n    1.0 / z\nend\n\nfunction fit_mle(::Type{Gamma}, ss::GammaStats; \n    alpha0::Float64=NaN, maxiter::Int=1000, tol::Float64=1.0e-16)\n\n    mx = ss.sx / ss.tw\n    logmx = log(mx)\n    mlogx = ss.slogx / ss.tw\n\n    a::Float64 = isnan(alpha0) ? 0.5 / (logmx - mlogx) : alpha0\n    converged = false\n    \n    t = 0\n    while !converged && t < maxiter\n        t += 1\n        a_old = a\n        a = gamma_mle_update(logmx, mlogx, a)\n        converged = abs(a - a_old) <= tol\n    end\n\n    Gamma(a, mx / a)\nend\n\n", "meta": {"hexsha": "42ae0de302103271d3df60352697299343745861", "size": 3845, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/gamma.jl", "max_stars_repo_name": "simonbyrne/Distributions.jl", "max_stars_repo_head_hexsha": "a9bd0e62002a94007ecd590e51cb27af9a346544", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/gamma.jl", "max_issues_repo_name": "simonbyrne/Distributions.jl", "max_issues_repo_head_hexsha": "a9bd0e62002a94007ecd590e51cb27af9a346544", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/gamma.jl", "max_forks_repo_name": "simonbyrne/Distributions.jl", "max_forks_repo_head_hexsha": "a9bd0e62002a94007ecd590e51cb27af9a346544", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4451219512, "max_line_length": 95, "alphanum_fraction": 0.544603381, "num_tokens": 1397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.8333245953120234, "lm_q1q2_score": 0.7663607382901484}}
{"text": "export eikonal_const_vel\n\n\"\"\"\n`eikonal_const_vel(src, z, x, [y, ] velocity)`\n\nCompute traveltime tables between `src` locations and subsurface model locations given by `z`, `x`, and optionally `y`. It assumes `velocity` is constant.\n\nParameters\n----------\n* `src` : `(ns, n)`, `AbstractMatrix{<:Real}`\n\nThe `(z_s, x_s [, x_y])` coordinates for every source. In 2D, `n = 2` and in 3D `n = 3`.\n\n* `z` : `(nz,)`, `AbstractVector{<:Real}`\n\nModel depth `z` coordinates.\n\n* `x` : `(nx,)`, `AbstractVector{<:Real}`\n\nModel horizontal `x` coordinates.\n\n* `y` : `(ny,)`, `AbstractVector{<:Real}`, optional\n\nModel horizontal `y` coordinates.\n\n\n* `velocity` : `Real`\n\nWave speed\n\nReturns\n-------\n\n* `trav` : `(nz, nx, [ny, ] ns)`, `AbstractArray{<:Real, M}`\n\nTraveltime between each src and locations given by `z`, `x` and optionally `y`:\n\n```math\nt(z, x, y, s) = \\\\frac{\\\\sqrt{(z-s_z)^2 + (x-s_x)^2 + (y-s_y)^2}}{v}\n```\n\"\"\"\nfunction eikonal_const_vel(src::AbstractMatrix{<:Real},\n                           z::AbstractVector{<:Real},\n                           x::AbstractVector{<:Real},\n                           velocity::Real)\n    if velocity < 0\n        @warn(\"Velocity cannot not be negative\")\n        throw(DomainError())\n    end\n    size(src, 2) == 2 || throw(DimensionMismatch(\"Second dimension of `src` must match number of model arguments\"))\n\n    ns = size(src, 1)\n    trav = zeros(length(z), length(x), ns)\n    Z = [i for i in z, j in x]\n    X = [j for i in z, j in x]\n    for is in 1:ns\n        src_z, src_x = src[is, :]\n        trav[:,:,is] = @. sqrt.((Z - src_z)^2 + (X - src_x)^2)/velocity\n    end\n    return trav\nend\nfunction eikonal_const_vel(src::AbstractMatrix{<:Real},\n                           z::AbstractVector{<:Real},\n                           x::AbstractVector{<:Real},\n                           y::AbstractVector{<:Real},\n                           velocity::Real)\n    if velocity < 0\n        @warn(\"Velocity cannot not be negative\")\n        throw(DomainError())\n    end\n    size(src, 2) == 3 || throw(DimensionMismatch(\"Second dimension of `src` must match number of model arguments\"))\n\n    ns = size(src, 1)\n    trav = zeros(length(z), length(x), length(y), ns)\n    Z = [i for i in z, j in x, k in y]\n    X = [j for i in z, j in x, k in y]\n    Y = [k for i in z, j in x, k in y]\n    for is in 1:ns\n        src_z, src_x, src_y = src[is, :]\n        trav[:,:,:,is] = @. sqrt((Z - src_z)^2 + (X - src_x)^2 + (Y - src_y)^2)/velocity\n    end\n    return trav\nend\n", "meta": {"hexsha": "712bcbb067cf09fd3753dd1a0056a0bb63cf0269", "size": 2477, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/eikonal.jl", "max_stars_repo_name": "cako/KirchMig.jl", "max_stars_repo_head_hexsha": "6bc65d24cd36ea05a848ddc51093ac07ec5e9035", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-04-04T10:32:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-20T09:52:35.000Z", "max_issues_repo_path": "src/eikonal.jl", "max_issues_repo_name": "cako/KirchMig.jl", "max_issues_repo_head_hexsha": "6bc65d24cd36ea05a848ddc51093ac07ec5e9035", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-08-19T15:26:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T05:26:42.000Z", "max_forks_repo_path": "src/eikonal.jl", "max_forks_repo_name": "cako/KirchMig.jl", "max_forks_repo_head_hexsha": "6bc65d24cd36ea05a848ddc51093ac07ec5e9035", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-04-02T14:11:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T04:29:30.000Z", "avg_line_length": 29.4880952381, "max_line_length": 154, "alphanum_fraction": 0.5510698426, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7663393140032875}}
{"text": "# This file is part of IntegerSequences.\n# Copyright Peter Luschny. License is MIT.\n\n(@__DIR__) ∉ LOAD_PATH && push!(LOAD_PATH, (@__DIR__))\n\nmodule GeneralizedBinomial\nusing Nemo, PrimesIterator, NumberTheory, Products, Triangles\n\nexport ModuleGeneralizedBinomial\nexport Binomial, Pascal, T007318, Multinomial\n\n\"\"\"\n\n P. Luschny, [Generalized Binomial](http://oeis.org/wiki/User:Peter_Luschny/ExtensionsOfTheBinomial), OEIS Wiki.\n\n* Binomial, Pascal, T007318\n\"\"\"\nconst ModuleGeneralizedBinomial = \"\"\n\n\"\"\"\n\nThe classical binomial coefficients defined for ``n≥0`` and ``0≤k≤n`` (a.k.a. Pascal's triangle).\n\"\"\"\nfunction Pascal(n::Int, k::Int)\n\n    (k == 0 || k == n) && return 1\n    if k > div(n, 2)\n        k = n - k\n    end\n\n    nk = n - k\n    factors = fmpz[]\n    rootN = isqrt(n)\n\n    # Make use of Kummer's theorem.\n    for prime ∈ Primes(2, n)\n\n        if prime > nk\n            push!(factors, prime)\n            continue\n        end\n\n        prime > div(n, 2) && continue\n\n        if prime > rootN\n            (n % prime < k % prime) && push!(factors, prime)\n            continue\n        end\n\n        r, N, K, p = 0, n, k, 1\n\n        while N > 0\n            r = N % prime < (K % prime + r) ? 1 : 0\n            if r == 1\n                p *= prime\n            end\n            N = div(N, prime)\n            K = div(K, prime)\n        end\n\n        p > 1 && push!(factors, p)\n    end\n\n    ∏(factors)\nend\n\n\"\"\"\n\nPascal's triangle.\n\"\"\"\nfunction T007318(n::Int)\n    T = zeros(QQ, div(n * (n + 1), 2))\n    j = 1\n    for m ∈ 0:n-1, k ∈ 0:m\n        T[j] = binomial(ZZ(m), ZZ(k))\n        j += 1\n    end\n    T\nend\n\n# See the discussion on\n# [Extensions of the Binomial](http://oeis.org/wiki/User:Peter_Luschny/ExtensionsOfTheBinomial).\n\"\"\"\n\nReturn the extended binomial coefficients defined for all ``n ∈ Z`` and ``k ∈ Z``. Behaves like the binomial function in Maple and Mathematica.\n\n``\\\\binom{n}{k} = \\\\lim \\\\limits_{x \\\\rightarrow 1}(Γ(n + x) / (Γ(k + x) Γ(n - k + x))).``\n\n\"\"\"\nfunction Binomial(n::Int, k::Int)\n    0 ≤ k ≤ n && return binomial(ZZ(n), ZZ(k))\n    k ≤ n < 0 && return binomial(ZZ(-k - 1), ZZ(n - k)) * (-1)^(n - k)\n    n < 0 ≤ k && return binomial(ZZ(-n + k - 1), ZZ(k)) * (-1)^k\n    ZZ(0)\nend\n\n\"\"\"\n\nReturn the multinomial coefficient of a list.\n\"\"\"\nfunction Multinomial(lst::Array{Int})\n    s = 0\n    result = fmpz(1)\n    for c ∈ lst\n        s += c\n        result *= binomial(ZZ(s), ZZ(c))\n    end\n    result\nend\n\n\n#START-TEST-########################################################\n\nusing Test\nfunction test()\n\n    @testset \"Binomial\" begin\n        for n ∈ 0:10, k ∈ 0:n\n            @test Binomial(n, k) == div(factorial(n), (factorial(n - k) * factorial(k)))\n            @test Binomial(n, k) == Pascal(n, k)\n        end\n    end\nend\n\nfunction demo()\n    ShowAsΔ(T007318(8))\n    println()\n\n    for n ∈ -10:10\n        println([Binomial(n, k) for k ∈ -10:10])\n    end\nend\n\n\"\"\"\n\nfor n ∈ 0:10000 Binomial(2*n,n) end\n    0.504729 seconds (10.00 k allocations: 156.266 KiB)\nfor n ∈ -100:100, k ∈ -100:100 Binomial(n,k) end\n    0.008669 seconds (55.55 k allocations: 867.984 KiB)\nfor k ∈ -10000:10000 Binomial(-5,k) end\n    0.005378 seconds (40.00 k allocations: 624.969 KiB)\n\"\"\"\nfunction perf()\n    @time (for n ∈ 0:10000\n        Binomial(2n, n)\n    end)\n    @time (for n ∈ -100:100, k ∈ -100:100\n        Binomial(n, k)\n    end)\n    @time (for k ∈ -10000:10000\n        Binomial(-5, k)\n    end)\nend\n\nfunction main()\n    test()\n    demo()\n    perf()\nend\n\nmain()\n\nend # module\n", "meta": {"hexsha": "284b8c0ebc90008e09eef3572cf7bb866f1c4434", "size": 3478, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GeneralizedBinomial.jl", "max_stars_repo_name": "OpenLibMathSeq/Sequences", "max_stars_repo_head_hexsha": "e53c1f30b7bf81669805f21d408d407b727615b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-06-25T08:54:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T04:52:29.000Z", "max_issues_repo_path": "src/GeneralizedBinomial.jl", "max_issues_repo_name": "OpenLibMathSeq/Sequences", "max_issues_repo_head_hexsha": "e53c1f30b7bf81669805f21d408d407b727615b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-04-30T19:07:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T15:51:34.000Z", "max_forks_repo_path": "src/GeneralizedBinomial.jl", "max_forks_repo_name": "PeterLuschny/IntegerSequences.jl", "max_forks_repo_head_hexsha": "1b9440bc8b86e3ae74fd26ee48fba412befbbdb5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-04-30T17:00:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:32:39.000Z", "avg_line_length": 21.2073170732, "max_line_length": 143, "alphanum_fraction": 0.5416906268, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.8376199714402813, "lm_q1q2_score": 0.7663393137354566}}
{"text": "#!/usr/bin/julia\n\n# Trizen\n# 17 January 2017\n# https://github.com/trizen\n\n# Generates a Mandelbrot-like set.\n\n# See also:\n#   https://en.wikipedia.org/wiki/Mandelbrot_set\n#   https://trizenx.blogspot.ro/2017/01/mandelbrot-set.html\n\nusing Images\n\n@inline function hsv2rgb(h, s, v)\n    c = v * s\n    x = c * (1 - abs(((h/60) % 2) - 1))\n    m = v - c\n\n    if h < 60\n        r,g,b = (c, x, 0)\n    elseif h < 120\n        r,g,b = (x, c, 0)\n    elseif h < 180\n        r,g,b = (0, c, x)\n    elseif h < 240\n        r,g,b = (0, x, c)\n    elseif h < 300\n        r,g,b = (x, 0, c)\n    else\n        r,g,b = (c, 0, x)\n    end\n\n    (r + m), (b + m), (g + m)\nend\n\n#\n## A specific function which maps the value of `c` to some other value.\n#\n@inline function f(c)\n    1/c\nend\n\nfunction mandelbrot()\n\n    w, h = 1000, 1000\n\n    zoom  = 1         # the zoom factor\n    moveX = 0         # the amount of shift on the x axis\n    moveY = 0         # the amount of shift on the y axis\n\n    L = 100           # the maximum value of |z|\n    I = 30            # the maximum number of iterations\n\n    img = zeros(RGB{Float64}, h, w)\n\n    for x in 1:w, y in 1:h\n        c = Complex(\n            (2*x - w) / (w * zoom) + moveX,\n            (2*y - h) / (h * zoom) + moveY\n        )\n        z = c\n        n = 0\n        q = f(c)\n        while (abs(z) < L && (n += 1) < I)\n            z = z^q\n        end\n        v = (I - n) / I\n        r,g,b = hsv2rgb(v*360, 1, v)\n        img[y,x] = RGB{Float64}(r, g, b)\n    end\n\n    println(\"Generating image...\")\n    save(\"mandelbrot_like_set.png\", img)\nend\n\nmandelbrot()\n", "meta": {"hexsha": "30dce02cb02ea935a5cbae8cf7b1ffab3f832bd8", "size": 1576, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Image/mandelbrot_like_set.jl", "max_stars_repo_name": "trizen/julia-scripts", "max_stars_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-03-22T09:38:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T21:38:31.000Z", "max_issues_repo_path": "Image/mandelbrot_like_set.jl", "max_issues_repo_name": "trizen/julia-scripts", "max_issues_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Image/mandelbrot_like_set.jl", "max_forks_repo_name": "trizen/julia-scripts", "max_forks_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2051282051, "max_line_length": 71, "alphanum_fraction": 0.4758883249, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7663393121490137}}
{"text": "\"\"\"\n    vandermonde(elem::AbstractElemShape, N, rst...)\n\nComputes the generalized Vandermonde matrix V of degree N at points (r,s,t).\n\"\"\"\nvandermonde(elem::AbstractElemShape, N, rst...) = first(basis(elem,N,rst...))\nvandermonde(elem::Line, N, r) = first(basis(elem,N,r)) # specialize for 1D\n\n\"\"\"\n    grad_vandermonde(elem::AbstractElemShape, N, rst...)\n\nComputes the generalized Vandermonde derivative matrix V of degree N at points (r,s,t).\n\"\"\"\ngrad_vandermonde(elem::AbstractElemShape, N, rst...) = basis(elem, N, rst...)[2:end]\ngrad_vandermonde(elem::Line, N, r) = last(basis(elem,N,r)) # specialize for 1D\n\n\n\"\"\"\n    nodes(elem::AbstractElemShape,N)\n\nComputes interpolation nodes of degree N. Edge nodes coincide with (N+1)-point Lobatto points.\nDefault routine for elem = Tet(), Pyr(), Tri().\n\nFor Quad(), Hex(), Wedge() elements, nodes(...) returns interpolation points constructed\nusing a tensor product of lower-dimensional nodes. \n\"\"\"\nnodes(elem::AbstractElemShape,N) = build_warped_nodes(elem,N,nodes(Line(),N))\n\n\n\n\"\"\"\n    basis(elem::AbstractElemShape, N, rst...)\n\nComputes orthonormal basis of degree N at tuple of coordinate arrays (r,s,t).\n\"\"\"\nbasis(elem::AbstractElemShape,N,rst...)\n\n\n\"\"\"\n    equi_nodes(elem::AbstractElemShape, N)\n\nCompute equispaced nodes of degree N.\n\"\"\"\nequi_nodes(elem::AbstractElemShape, N)\n\n\"\"\"\n    quad_nodes(elem::AbstractElemShape, N)\n\nCompute quadrature nodes and weights exact for (at least) degree 2N polynomials.\n\"\"\"\nquad_nodes(elem::AbstractElemShape, N)\n\n\n\"\"\"\n    stroud_quad_nodes(elem::AbstractElemShape,N)\n\nReturns Stroud-type quadrature nodes and weights constructed from the tensor product\nof (N+1)-point Gauss-Jacobi rules. Exact for degree 2N polynomials\n\"\"\"\nstroud_quad_nodes(elem::AbstractElemShape,N)\n", "meta": {"hexsha": "5f7d686449a3bba1ee3a37ce2c2b53d0e8b94e6d", "size": 1758, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/common_functions.jl", "max_stars_repo_name": "stevengj/NodesAndModes.jl", "max_stars_repo_head_hexsha": "2c13546a26b23e58164f72aab2e8555b002e79e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2020-08-28T06:59:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T16:38:39.000Z", "max_issues_repo_path": "src/common_functions.jl", "max_issues_repo_name": "stevengj/NodesAndModes.jl", "max_issues_repo_head_hexsha": "2c13546a26b23e58164f72aab2e8555b002e79e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-12-01T07:26:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T18:04:39.000Z", "max_forks_repo_path": "src/common_functions.jl", "max_forks_repo_name": "stevengj/NodesAndModes.jl", "max_forks_repo_head_hexsha": "2c13546a26b23e58164f72aab2e8555b002e79e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-23T16:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T16:50:40.000Z", "avg_line_length": 28.8196721311, "max_line_length": 94, "alphanum_fraction": 0.7258248009, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7663393043748109}}
{"text": "#=\nThis file contains the definition of the generalized dimension and related concepts\nand also uses linear_regions.jl\n=#\nexport generalized_dim\n\n\"\"\"\n    generalized_dim(dataset [, sizes]; q = 1, base = MathConstants.e) -> Δ_q\nReturn the `q` order generalized dimension of the `dataset`, by calculating\nthe [`genentropy`](@ref) for each `ε ∈ sizes`.\n\nThe case of `q = 0` is often called \"capacity\" or \"box-counting\" dimension, while\n`q = 1` is the \"information\" dimension.\n\n## Description\nThe returned dimension is approximated by the\n(inverse) power law exponent of the scaling of the [`genentropy`](@ref) ``H_q``\nversus the box size `ε`, where `ε ∈ sizes`:\n\n```math\nH_q \\\\sim -\\\\Delta_q\\\\log(\\\\varepsilon)\n```\n\nCalling this function performs a lot of automated steps:\n\n  1. A vector of box sizes is decided by calling `sizes = estimate_boxsizes(dataset)`,\n     if `sizes` is not given.\n  2. For each element of `sizes` the appropriate entropy is\n     calculated, through `H = genentropy.(Ref(dataset), sizes; q, base)`.\n     Let `x = -log.(sizes)`.\n  3. The curve `H(x)` is decomposed into linear regions,\n     using [`linear_regions`](@ref)`(x, h)`.\n  4. The biggest linear region is chosen, and a fit for the slope of that\n     region is performed using the function [`linear_region`](@ref),\n     which does a simple linear regression fit using [`linreg`](@ref).\n     This slope is the return value of `generalized_dim`.\n\nBy doing these steps one by one yourself, you can adjust the keyword arguments\ngiven to each of these function calls, refining the accuracy of the result.\n\"\"\"\nfunction generalized_dim(data::AbstractDataset, sizes = estimate_boxsizes(data);\n        base = Base.MathConstants.e, q = 1.0\n    )\n    dd = [genentropy(data, ε; q, base) for ε ∈ sizes]\n    return linear_region(-log.(base, sizes), dd)[2]\nend\n", "meta": {"hexsha": "370c657986f16d441e587403712e675a0c05b4d2", "size": 1827, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dimensions/generalized_dim.jl", "max_stars_repo_name": "onkyo14taro/ChaosTools.jl", "max_stars_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 168, "max_stars_repo_stars_event_min_datetime": "2018-01-07T15:46:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T13:38:24.000Z", "max_issues_repo_path": "src/dimensions/generalized_dim.jl", "max_issues_repo_name": "onkyo14taro/ChaosTools.jl", "max_issues_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 176, "max_issues_repo_issues_event_min_datetime": "2017-12-19T20:26:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:08:23.000Z", "max_forks_repo_path": "src/dimensions/generalized_dim.jl", "max_forks_repo_name": "onkyo14taro/ChaosTools.jl", "max_forks_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2018-01-27T07:59:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T10:08:36.000Z", "avg_line_length": 38.8723404255, "max_line_length": 86, "alphanum_fraction": 0.7049808429, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.766339294924888}}
{"text": "@doc raw\"\"\"\n    LorentzMetric <: Metric\n\nAbstract type for Lorentz metrics, which have a single time dimension. These\nmetrics assume the spacelike convention with the time dimension being last,\ngiving the signature $(++...+-)$.\n\"\"\"\nabstract type LorentzMetric <: Metric end\n\n@doc raw\"\"\"\n    MinkowskiMetric <: LorentzMetric\n\nAs a special metric of signature  $(++...+-)$, i.e. a [`LorentzMetric`](@ref),\nsee [`minkowski_metric`](@ref) for the formula.\n\"\"\"\nstruct MinkowskiMetric <: LorentzMetric end\n\n@doc raw\"\"\"\n    Lorentz{N} = MetricManifold{Euclidean{N,ℝ},LorentzMetric}\n\nThe Lorentz manifold (or Lorentzian) is a pseudo-Riemannian manifold.\n\n# Constructor\n\n    Lorentz(n[, metric=MinkowskiMetric()])\n\nGenerate the Lorentz manifold of dimension `n` with the [`LorentzMetric`](@ref) `m`,\nwhich is by default set to the [`MinkowskiMetric`](@ref).\n\"\"\"\nconst Lorentz = MetricManifold{ℝ,Euclidean{Tuple{N},ℝ},<:LorentzMetric} where {N}\n\nfunction Lorentz(n, m::MT = MinkowskiMetric()) where {MT<:LorentzMetric}\n    return Lorentz{n,typeof(m)}(Euclidean(n), m)\nend\n\nfunction local_metric(\n    ::MetricManifold{ℝ,Euclidean{Tuple{N},ℝ},MinkowskiMetric},\n    p,\n) where {N}\n    return Diagonal([ones(N - 1)..., -1])\nend\n\nfunction inner(::MetricManifold{ℝ,Euclidean{Tuple{N},ℝ},MinkowskiMetric}, p, X, Y) where {N}\n    return minkowski_metric(X, Y)\nend\n@doc raw\"\"\"\n    minkowski_metric(a,b)\n\nCompute the minkowski metric on $\\mathbb R^n$ is given by\n````math\n⟨a,b⟩_{\\mathrm{M}} = -a_{n}b_{n} +\n\\displaystyle\\sum_{k=1}^{n-1} a_kb_k.\n````\n\"\"\"\nminkowski_metric(a, b) = -a[end] * b[end] + sum(a[1:(end - 1)] .* b[1:(end - 1)])\n", "meta": {"hexsha": "7de546a21c60c3351babc7f6c47505895d09b53e", "size": 1616, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/manifolds/Lorentz.jl", "max_stars_repo_name": "stevengj/Manifolds.jl", "max_stars_repo_head_hexsha": "af7f72f29d0f0d1c558d6b1e05c7b22d265362da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/manifolds/Lorentz.jl", "max_issues_repo_name": "stevengj/Manifolds.jl", "max_issues_repo_head_hexsha": "af7f72f29d0f0d1c558d6b1e05c7b22d265362da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/manifolds/Lorentz.jl", "max_forks_repo_name": "stevengj/Manifolds.jl", "max_forks_repo_head_hexsha": "af7f72f29d0f0d1c558d6b1e05c7b22d265362da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8571428571, "max_line_length": 92, "alphanum_fraction": 0.6850247525, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7662882293954199}}
{"text": "#Função de substituição reversa, onde retorna um x que é o o que queremos encontrar de Ax=b\n\n\nfunction sr00(U,b);\n\n\t(m,n) = size(U);\n\tx = zeros(m);\n\n\tx[m] = b[m]/U[m,m];\n\n\tfor i = m-1:-1:1\n\t\tsoma = 0;\n\n\t\tfor j = i+1:n\n\n\t\t\tsoma = soma + U[i,j]*x[j];\n\t\tend\n\t\tx[i] = (b[i] - soma)/U[i,i];\n\tend\n\n\treturn x;\n\t\nend\n\n", "meta": {"hexsha": "1fb277c002071f508d4cfc38c401a426fd6dc950", "size": 310, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/sr00.jl", "max_stars_repo_name": "italonicacio/Algebra_Linear_Computacional_2019.1", "max_stars_repo_head_hexsha": "b7f1540fb16cdbf6db15d88da8c38ba83db866b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-30T02:51:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-30T02:51:30.000Z", "max_issues_repo_path": "julia/sr00.jl", "max_issues_repo_name": "italonicacio/Algebra_Linear_Computacional_2019.1", "max_issues_repo_head_hexsha": "b7f1540fb16cdbf6db15d88da8c38ba83db866b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/sr00.jl", "max_forks_repo_name": "italonicacio/Algebra_Linear_Computacional_2019.1", "max_forks_repo_head_hexsha": "b7f1540fb16cdbf6db15d88da8c38ba83db866b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.4, "max_line_length": 91, "alphanum_fraction": 0.5387096774, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760996, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7662882266049934}}
{"text": "export FFTOp, \\\n\nmutable struct FFTOp{T,F1<:FuncOrNothing,F2<:FuncOrNothing,F3<:FuncOrNothing} <: AbstractLinearOperator{T,F1,F2,F3}\n  nrow   :: Int\n  ncol   :: Int\n  symmetric :: Bool\n  hermitian :: Bool\n  prod   :: F1 # apply the operator to a vector\n  tprod  :: F2 # apply the transpose operator to a vector\n  ctprod :: F3 # apply the transpose conjugate operator to a vector\nend\n\n\"\"\"\n  FFTOp(T::Type, shape::Tuple, shift=true)\n\nreturns an operator which performs an FFT on Arrays of type T\n\n# Arguments:\n* `T::Type`       - type of the array to transform\n* `shape::Tuple`  - size of the array to transform\n* (`shift=true`)  - if true, fftshifts are performed\n\"\"\"\nfunction FFTOp(T::Type, shape::Tuple, shift=true)\n  plan = plan_fft(zeros(T, shape);flags=FFTW.MEASURE)\n  iplan = plan_ifft(zeros(T, shape);flags=FFTW.MEASURE)\n\n  if shift\n    return FFTOp{T,Function, Nothing,Function}(prod(shape), prod(shape), false, false\n              , x->vec(fftshift(plan*fftshift(reshape(x,shape))))/sqrt(prod(shape))\n              , nothing\n              , y->vec(ifftshift(iplan*ifftshift(reshape(y,shape)))) * sqrt(prod(shape)) )\n  else\n    return FFTOp{T,Function, Nothing,Function}(prod(shape), prod(shape), false, false\n            , x->vec(plan*(reshape(x,shape)))/sqrt(prod(shape))\n            , nothing\n            , y->vec(iplan*(reshape(y,shape))) * sqrt(prod(shape)) )\n  end\nend\n\n\\(A::FFTOp, x::Vector) = adjoint(A) * x\n", "meta": {"hexsha": "31dd9dba3b0be209a517fcb5c1fcd3031c468ae9", "size": 1423, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FFTOp.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SparsityOperators.jl-a5ff1dd3-4e0a-50db-9022-6d011c1d5846", "max_stars_repo_head_hexsha": "47c6f244683a9e5213ea669590e23ecbe72abdc1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FFTOp.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SparsityOperators.jl-a5ff1dd3-4e0a-50db-9022-6d011c1d5846", "max_issues_repo_head_hexsha": "47c6f244683a9e5213ea669590e23ecbe72abdc1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FFTOp.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SparsityOperators.jl-a5ff1dd3-4e0a-50db-9022-6d011c1d5846", "max_forks_repo_head_hexsha": "47c6f244683a9e5213ea669590e23ecbe72abdc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7073170732, "max_line_length": 115, "alphanum_fraction": 0.6514406184, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7662882245612755}}
{"text": "@info \"Análise Estrutural\"\n# Matriz de rigidez dos elementos\nk1 = [300  -300\n    -300   300]\n\nk2 = [\n    600  -600\n    -600   600\n]\n\nk3 = [\n    800  -800\n    -800   800\n]\n\nk4 = [\n    500  -500\n    -500   500\n]\n\nk5 = [\n    600  -600\n    -600   600\n]\n\nk6 = [\n    800  -800\n    -800   800\n]\n\n# Vetor de forças aplicadas nos Nós\nf =[0, 500, 500, 600, 1000, 0]\n# Vetor de deslocamentos nodais\nu = [0, 0, 0, 0, 0, 2]\n\n# Nós\nA = 1\nB = 2\nC = 3\nD = 4\nE = 5\nF = 6\n\n# Relacionamento entre elementos e nós\nak1 = [[A,A], [A,B], [B,A], [B,B]]\nak2 = [[B,B], [B,C], [C,B], [C,C]]\nak3 = [[B,B], [B,D], [D,B], [D,D]]\nak4 = [[B,B], [B,E], [E,B], [E,E]]\nak5 = [[D,D], [F,D], [D,F], [F,F]]\nak6 = [[E,E], [E,F], [F,E], [F,F]]\n\n# Matriz de rigidez global\nk = zeros(6, 6)\n\n# Mapeia a matriz de rigidez local com a matriz de rigidez global\nfunction mapear(a, b)\n    l = 1\n    for i in 1:2\n        for j in 1:2\n            k[a[l][1,1],a[l][2,1]] += b[i, j]\n            l+=1\n        end\n    end\nend\n\n# Monta matriz de rigidez global\nmapear(ak1, k1)\nmapear(ak2, k2)\nmapear(ak3, k3)\nmapear(ak4, k4)\nmapear(ak5, k5)\nmapear(ak6, k6)\n\n# Resolve sistema de equações para achar os deslocamentos nodais\n# é retirada da matriz a linha e coluna correspondente ao nó que não tem deslocamento\n@show _k = (k[1:end .!=A, 1:end .!=A])[1:end .!=E, 1:end .!=E] \\ (f[1:end .!=A])[1:end .!=E]\n", "meta": {"hexsha": "3106c255b1f7a497e632276edda4c25f453b80af", "size": 1347, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julialang/tensores.jl", "max_stars_repo_name": "rsd-consultorias/scripts-engenharia", "max_stars_repo_head_hexsha": "cf30e498fb23082d2d931eb4120eef6b5f74b8f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-05T17:03:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-05T17:03:59.000Z", "max_issues_repo_path": "julialang/tensores.jl", "max_issues_repo_name": "rsd-consultorias/scripts-engenharia", "max_issues_repo_head_hexsha": "cf30e498fb23082d2d931eb4120eef6b5f74b8f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julialang/tensores.jl", "max_forks_repo_name": "rsd-consultorias/scripts-engenharia", "max_forks_repo_head_hexsha": "cf30e498fb23082d2d931eb4120eef6b5f74b8f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4935064935, "max_line_length": 92, "alphanum_fraction": 0.5293244246, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7662707876338972}}
{"text": "makepositive(x) = exp(x)\n\ninvmakepositive(y) = log(y)\n\nsigmoid(x) = 1.0 / (exp(-x) + 1.0)\n\ninvsigmoid(y) = - log(1/y -1.0)\n\ntransformbetween(x, lower, upper) = sigmoid(x) * (upper - lower) + lower\n\ninvtransformbetween(y, lower, upper) = invsigmoid((y - lower)/(upper-lower))\n", "meta": {"hexsha": "6dabf530a8a1972a265e1318766f737e5434caef", "size": 275, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transformutil.jl", "max_stars_repo_name": "ngiann/MiscUtil.jl", "max_stars_repo_head_hexsha": "62bb259ae41ffa2f2eaf4c55142523238995919e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/transformutil.jl", "max_issues_repo_name": "ngiann/MiscUtil.jl", "max_issues_repo_head_hexsha": "62bb259ae41ffa2f2eaf4c55142523238995919e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-22T10:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T10:56:15.000Z", "max_forks_repo_path": "src/transformutil.jl", "max_forks_repo_name": "ngiann/MiscUtil.jl", "max_forks_repo_head_hexsha": "62bb259ae41ffa2f2eaf4c55142523238995919e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9166666667, "max_line_length": 76, "alphanum_fraction": 0.6436363636, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.8056321866478978, "lm_q1q2_score": 0.7662707853902602}}
{"text": "# # Section Allocation\n# Suppose you have $n$ students in a class who need to be assigned to $m$\n# discussion sections. Each student needs to be assigned to exactly one section.\n# Each discussion section should have between 6 and 10 students. Suppose an\n# $n \\times m$ preference matrix $P$ is given, where $P_{ij}$ gives student\n# $i$'s ranking for section $j$ (1 would mean it is the student's top choice,\n# 10,000 or a large number would mean the student can not attend that section).\n#\n# The goal will be to get an allocation matrix $X$, where $X_{ij} = 1$ if\n# student $i$ is assigned to section $j$ and $0$ otherwise. \n\nusing Convex, GLPK\naux(str) = joinpath(@__DIR__, \"aux_files\", str) # path to auxiliary files\n\n# Load our preference matrix, `P`\ninclude(aux(\"data.jl\"))\n\nX = Variable(size(P), :Bin)\n\n# We want every student to be assigned to exactly one section. So, every row\n# must have exactly one non-zero entry. In other words, the sum of all the\n# columns for every row is 1. We also want each section to have between 6 and 10\n# students, so the sum of all the rows for every column should be between these.\nconstraints = [sum(X, dims=2) == 1, sum(X, dims=1) <= 10, sum(X, dims=1) >= 6]\n\n# Our objective is simple `sum(X .* P)`, which can be more efficiently\n# represented as `vec(X)' * vec(P)`. Since each entry of `X` is either 0 or 1,\n# this is basically summing up the rankings of students that were assigned to them.\n# If all students got their first choice, this value will be the number of\n# students since the ranking of the first choice is 1.\np = minimize(vec(X)' * vec(P), constraints)\n\nsolve!(p, GLPK.Optimizer)\np.optval\n", "meta": {"hexsha": "b561d90fa5a2db734f57a395cb9023df36313ab6", "size": 1646, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/mixed_integer/section_allocation.jl", "max_stars_repo_name": "JinraeKim/Convex.jl", "max_stars_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 123, "max_stars_repo_stars_event_min_datetime": "2020-06-16T21:56:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:05:39.000Z", "max_issues_repo_path": "docs/examples_literate/mixed_integer/section_allocation.jl", "max_issues_repo_name": "JinraeKim/Convex.jl", "max_issues_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122, "max_issues_repo_issues_event_min_datetime": "2020-06-14T00:19:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T14:02:09.000Z", "max_forks_repo_path": "docs/examples_literate/mixed_integer/section_allocation.jl", "max_forks_repo_name": "JinraeKim/Convex.jl", "max_forks_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2020-08-21T07:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T13:40:50.000Z", "avg_line_length": 47.0285714286, "max_line_length": 83, "alphanum_fraction": 0.7162818955, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7662707831709055}}
{"text": "# Author: Gabrio Rizzuti, rizzuti.gabrio@gatech.edu\n# Date: August, 2020\n# Copyright: Georgia Institute of Technology, 2020\n#\n# Run MALA to sample from Gaussian mixture in 2D\n\n\n## Module loading\n\nusing DrWatson\n@quickactivate \"UncertaintyQuantificationAVP\"\nusing UncertaintyQuantificationAVP\nusing LinearAlgebra, PyPlot, Statistics\nusing Random; Random.seed!(1)\n\n\n## Setting negative log density for Gaussian mixture\n\n# Gaussian modes parameters\nnmodes = 7\nmuComplex = Complex{Float32}.(exp.(1im*2f0*pi*collect(range(0f0, 1f0; length=nmodes+1))))\nmu = [real.(muComplex[1:end-1]) imag.(muComplex[1:end-1])]\nsigma2 = zeros(Float32, nmodes); sigma2 .= Float32(0.025)\n\n# Sampling function\nsample = function sample_gaussmixture(nsamples::Int64) # Direct sampling\n    x = Array{Float32, 2}(undef, (nsamples, 2))\n    for i = 1:nsamples\n        imode = rand(1:nmodes)\n        x[i, :] = mu[imode, :]+sqrt(sigma2[imode])*randn(Float32, 2)\n    end\n    return x\nend\nx = sample(2^10)\nfigure()\nplot(x[:, 1], x[:, 2], \"*\")\ntitle(\"Sample from Gaussian mixture distribution\")\n\n# Negative log density\nfunction negLogDensity_gaussmixture(x::Array{Float32, 2})\n    p = zeros(Float32, size(x, 1))\n    g = zeros(Float32, size(x))\n    for i = 1:nmodes\n        p_i = exp.(-((x[:, 1].-mu[i, 1]).^2+(x[:, 2].-mu[i, 2]).^2)/(2*sigma2[i]))/(nmodes*2f0*pi*sigma2[i])\n        p += p_i\n        g += -p_i.*(x.-mu[i:i, :])/sigma2[i]\n    end\n    return -log.(p), -g./p\nend\nfunction neglogp(x::Array{Float32, 1})\n    f, g = negLogDensity_gaussmixture(reshape(x, 1, 2))\n    return f[1], reshape(g, size(x))\nend\nfunction meshgrid(x, y)\n    X = [i for i in x, j in 1:length(y)]\n    Y = [j for i in 1:length(x), j in y]\n    return X, Y\nend\n\n\n## MALA sampling\n\n# Starting input\nx0 = randn(Float32, 2)\n\n# Parameters\nnsamples = 2^10\nϵ = 0.02f0\nflag_MALA = true\n\n# Run MALA\ntime = @elapsed fval, xLD = langevinSampler(neglogp, nsamples, x0, ϵ; flag_MALA = flag_MALA)\nfigure()\nplot(x[:, 1], x[:, 2], \"r*\")\nplot(xLD[1,:], xLD[2,:], \".\")\ntitle(\"MALA samples\")\n", "meta": {"hexsha": "ac02a570b00bac6b456e1b6a10c51f561015f263", "size": 2014, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "rizzuti2020SEGuqavp/scripts/GaussMixture/LD_gaussmixture.jl", "max_stars_repo_name": "slimgroup/Software.SEG2020", "max_stars_repo_head_hexsha": "e7dd34d803a4936b369b7d49f7a992445121c533", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-04-25T15:00:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T22:29:18.000Z", "max_issues_repo_path": "rizzuti2020SEGuqavp/scripts/GaussMixture/LD_gaussmixture.jl", "max_issues_repo_name": "slimgroup/Software.SEG2020", "max_issues_repo_head_hexsha": "e7dd34d803a4936b369b7d49f7a992445121c533", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rizzuti2020SEGuqavp/scripts/GaussMixture/LD_gaussmixture.jl", "max_forks_repo_name": "slimgroup/Software.SEG2020", "max_forks_repo_head_hexsha": "e7dd34d803a4936b369b7d49f7a992445121c533", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-04-27T09:14:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-06T10:30:24.000Z", "avg_line_length": 26.1558441558, "max_line_length": 108, "alphanum_fraction": 0.6519364449, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809302, "lm_q2_score": 0.865224091265267, "lm_q1q2_score": 0.7662696819066799}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.20\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 1bcf25d8-71c2-11eb-05ca-6fe7c4e1b24f\nbegin\n\tusing Pkg\n\tPkg.activate(\"MLJ_env\", shared=true)\nend\n\n# ╔═╡ 1f7ea604-71c2-11eb-028a-a166f6f4dc5d\nbegin\n\tusing MLJ\n\tusing CSV\n\tusing DataFrames\n\tusing PlutoUI\n\tusing Random\n\tusing Test\n\tusing Printf\nend\n\n# ╔═╡ f377f6d4-71c9-11eb-0249-f3d63e87062b\nbegin \n\tusing LinearAlgebra\n\n\tfunction feature_derivative(errors::Vector{T}, \n\t\t\tfeature::Vector{T}) where {T <: Real}\n    \treturn 2 * dot(feature, errors) # ≡ 2 * feature' * errors\n\tend\nend\n\n# ╔═╡ 9dcffb1c-71c1-11eb-2402-39eaa1f1b5e1\nmd\"\"\"\n## Week 2: Multiple Regression (Gradient Descent)\n\"\"\"\n\n# ╔═╡ c39f9348-71c1-11eb-1691-1d28c6b1d916\nmd\"\"\"\n\nIn this notebook we will cover estimating multiple regression weights via gradient descent, performing the following:\n\n - Add a constant column of 1's to a DataFrame to account for the intercept\n - Write a `predict_output()` function \n - Write a function to compute the derivative of the regression weights with respect to a single feature\n - Write gradient descent function to compute the regression weights given an initial weight vector, step size and tolerance.\n - Use the gradient descent function to estimate regression weights for multiple features\n\"\"\"\n\n# ╔═╡ 3e5d907e-71c2-11eb-2eb3-4375fb21b884\nmd\"\"\"\n### Load in house sales data\n\"\"\"\n\n# ╔═╡ 4c736078-71c2-11eb-225b-816745199225\nsales = CSV.File(\"../../ML_UW_Spec/C02/data/kc_house_test_data.csv\"; \n\theader=true) |> DataFrame;\n\n# ╔═╡ 58e6255a-71c2-11eb-2094-9dbe7fb64151\nfirst(sales, 3)\n\n# ╔═╡ 64c97662-71c2-11eb-2894-2d544642b136\ntypeof(sales.bedrooms)\n\n# ╔═╡ 80fbf0f8-71c2-11eb-265a-fb539d764180\ntypeof(sales.bathrooms)\n\n# ╔═╡ 35b5d05a-71cc-11eb-15a9-852c5a534fab\nmd\"\"\"\n### Convert to Julia Matrix/Vector\n\"\"\"\n\n# ╔═╡ a2928dc6-71c2-11eb-3724-29dc1448a0f3\nmd\"\"\"\nNow we will write a function that will accept a DataFrame, a list of feature names (e.g. [:sqft_living, :bedrooms') and a target feature e.g. (:price) and will return two things:\n\n - A matrix whose columns are the desired features plus a constant column (this is how we create an 'intercept')\n - An array containing the values of the output\n\nWith this in mind, let's write the `get_data` function:\n\n\"\"\"\n\n# ╔═╡ e4da992e-71c2-11eb-36b8-93dd614051c1\nfunction get_data(df, features, output)\n\tdf[:, :constant] .= 1.0 # df.constant = fill(1.0, size(df, 1))\n\tfeatures = [:constant, features...]\n\tX_matrix = convert(Matrix, select(df, features)) # to get a matrix \n\ty = df[!, output]                                # => to get a vector\n\treturn (X_matrix, y)\nend\n\n# ╔═╡ d62e0368-71c2-11eb-16f7-5fda56951d21\nbegin\n\t(ex_features, ex_output) = get_data(sales, [:sqft_living], :price) \n\twith_terminal() do\n\t\tprintln(ex_features[1:5, :], \" / \", typeof(ex_features))\n\t\tprintln(ex_output[1], \" / \", typeof(ex_output))\n\tend\nend\n\n# ╔═╡ 498b3458-71cc-11eb-3b55-8381d58d04bb\nmd\"\"\"\n### Predicting output given regression weights\n\"\"\"\n\n# ╔═╡ daf8aefc-71c7-11eb-04fa-e71d7b2cde21\nmd\"\"\"\nThe predictions from all the observations are just the dot product between the features matrix (on the left) and the weights vector (on the right).\n\nWith this in mind write the following `predict_output` function to compute the predictions given the feature matrix (X) and the weights:\n\"\"\"\n\n# ╔═╡ 02f0c99e-71c5-11eb-1fe1-b3f820998d54\nfunction predict_output(X::Matrix{T}, weights::Vector{T}) where {T <: Real}\n    # assume feature_matrix is a matrix containing the features as columns\n\t# and weights is a corresponding array\n    X * weights\nend\n\n# ╔═╡ 9cd636f2-71c5-11eb-2957-afbaf437aaa5\nbegin\n\tmy_weights = Float64[1., 1.]\n\ttest_predictions = predict_output(ex_features, my_weights)\n\t\n\t@test test_predictions[1] == 1431.0  # should be 1431.0\n\t@test test_predictions[2] == 2951.0  # should be 2951.0\nend\n\n# ╔═╡ 21635b6e-71c8-11eb-2272-edec98c58339\nmd\"\"\"\n### Computing the derivative\n\n\nWe are now going to compute the derivative of the regression cost function. Recall that the cost function is the sum over the data points of the squared difference between an observed output and a predicted output.\n\nSince the derivative of a sum is the sum of the derivatives we can compute the derivative for a single data point and then sum over data points. We can write the squared difference between the observed output and predicted output for a single point as follows:\n\n$$(w[0]\\times[CONST] + w[1]\\times[feature_1] + ... + w[i]\\times[feature_i] + ... +  w[k]\\times[feature_k] - output)^2$$\n\nWhere we have $k$ features and a constant. So the derivative with respect to weight $w[i]$ by the chain rule is:\n\n$$2\\times(w[0]\\times[CONST] + w[1]\\times[feature_1] + ... + w[i]\\times[feature_i] + ... +  w[k]\\times[feature_k] - output)\\times[feature_i]$$\n\nThe term inside the parenthesis is just the error (difference between prediction and output). So we can re-write this as:\n\n$$2\\times error\\times[feature_i]$$\n\nThat is, the derivative for the weight for feature $i$ is:\n  - the sum (over data points) of 2 × the product of the error and the feature itself.   \n    In the case of the constant then this is just twice the sum of the errors!\n\nRecall that twice the sum of the product of two vectors is just:\n  - twice the dot product of the two vectors.  \n    Therefore the derivative for the weight for $feature_i$ is just two times the dot product between the values of $feature_i$ and the current errors. \n\nWith this in mind let's write the following derivative function which computes the derivative of the weight given the value of the feature (over all data points) and the errors (over all data points).\n\n\n`doc ref. https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/`\n\"\"\"\n\n# ╔═╡ 1301a4d2-71ca-11eb-339c-d1f747a3ffe7\nbegin\n\t(nex_features, nex_output) = get_data(sales, [:sqft_living], :price) \n\tya_weights = Float64[0., 0.] # this makes all the predictions 0\n\ttest_preds = predict_output(nex_features, ya_weights) \n\n\t# just like SFrames 2 numpy arrays can be elementwise subtracted with '-': \n\terrors = test_preds .- nex_output # prediction errors in this case is just the -example_output\n\tya_feature = nex_features[:, 1]   # let's compute the derivative with respect to 'constant', the \":\" indicates \"all rows\"\n\tder = feature_derivative(errors, ya_feature)\n\talt_der = -sum(nex_output) * 2\n\n\t@test der == alt_der  # should be the same as derivative\nend\n\n# ╔═╡ 49ce0c84-71cb-11eb-3947-6141a9498ffb\nwith_terminal() do\n\t@printf(\"derivative: %2.5e / alt_derivative: %2.5e\\n\", der, alt_der)\nend\n\n# ╔═╡ 239ff6ca-71cc-11eb-341a-df1453d60a15\nmd\"\"\"\n### Gradient Descent [GD]\n\n\nNow we will write a function that performs a gradient descent. The basic premise is simple. Given a starting point we update the current weights by moving in the negative gradient direction. Recall that the gradient is the direction of increase and therefore the negative gradient is the direction of decrease and we're trying to minimize a cost function.\n\nThe amount by which we move in the negative gradient direction is called the *step size* denoted by η. We stop when we are 'sufficiently close' to the optimum. We define this by requiring that the magnitude (length) of the gradient vector to be smaller than a fixed *tolerance* denoted by ϵ.\n\nWith this in mind, wriet the following gradient descent function below using the derivative function above. For each step in the gradient descent we update the weight for each feature befofe computing our stopping criteria\n\"\"\"\n\n# ╔═╡ 958f81a6-71cc-11eb-13e8-61dddeb014a7\nfunction regression_gradient_descent(f_matrix::Matrix{T}, \n\t\toutput::Vector{T}, init_weights::Vector{T}, η::T, ϵ::T) where {T <: Real}\n    weights = init_weights # make sure it's a vector\n\t\n    while true\n\t\tpreds = predict_output(f_matrix, weights) # compute the predictions \n        errors = preds .- output                  # compute the errors \n        ∇_sum_squares = 0.0                       # init the gradient sum of squares\n        \n\t\t## Update the weights\n        for ix ∈ 1:length(weights) # loop over each weight\n            ## Recall that feature_matrix[:, ix] is the feature column \n\t\t    ## associated with weights[i]\n            deriv_ix = feature_derivative(errors, f_matrix[:, ix]) \n\t\t\t## add squared value of derivative to ∇_sum_squares (convergence)\n            ∇_sum_squares += deriv_ix * deriv_ix \n\t\t\t\n\t\t\t## subtract the step size times the derivative from the CURRENT weight\n            weights[ix] -= η * deriv_ix\n\t\tend\n        ##  compute the square-root of the ∇_sum_squares to get the ∇ magnitude:\n        ∇_magnitude = √(∇_sum_squares)\n        ∇_magnitude < ϵ && break\n\tend    \n    weights\nend\n\n# ╔═╡ 4454239e-71ce-11eb-295e-1755bc0549e6\nmd\"\"\"\n### Running the Gradient Descent as Simple Regression\n\"\"\"\n\n# ╔═╡ 0623d920-71ce-11eb-0936-870685f2e788\nbegin\nfunction train_test_split(df; split=0.8, seed=42, shuffled=true) \n\tRandom.seed!(seed)\n\t(nr, nc) = size(df)\n\tnrp = round(Int, nr * split)\n\trow_ixes = shuffled ? shuffle(1:nr) : collect(1:nr)\n\tdf_train = view(df[row_ixes, :], 1:nrp, 1:nc)\n\tdf_test = view(df[row_ixes, :], nrp+1:nr, 1:nc)\n\t(df_train, df_test)\nend\n\nsales_train, sales_test = train_test_split(sales);\nend\n\n# ╔═╡ 6a1ee460-71ce-11eb-1b49-4de942aefe9d\nbegin\n\t# let's test out the gradient descent\n\ts_features = [:sqft_living]\n\ts_out = :price\n\t(simple_f_matrix, out) = get_data(sales_train, s_features, s_out)\n\n\tinit_weights = [-47000., 1.]\n\tη = 7e-12\n\tϵ = 2.5e7\nend\n\n# ╔═╡ 9883c1ee-71cf-11eb-3b48-a14df232588f\ngd_weights = regression_gradient_descent(simple_f_matrix, Vector{Float64}(out), init_weights, η, ϵ)\n\n# ╔═╡ 06cf79e0-71d0-11eb-3eab-ad040213a64b\nmd\"\"\"\nUse your newly estimated weights and your `predict_output()` function to compute the predictions on all the test data.\n\nyou will need to create a julia array of the test feature_matrix and test output first, as follows:\n\"\"\"\n\n# ╔═╡ 26199ccc-71d0-11eb-0b4e-5f2f8ebc7b76\n(test_s_feature_matrix, test_out) = get_data(sales_test, s_features, s_out);\n\n# ╔═╡ 4be11b60-71d0-11eb-1550-6d2854691b05\nmd\"\"\"\nNow compute your predictions using `test_s_feature_matrix` and the `gd_weights` from above.\n\"\"\"\n\n# ╔═╡ 65c26930-71d0-11eb-248a-3751d927b2f6\nya_preds = predict_output(test_s_feature_matrix, gd_weights)\n\n# ╔═╡ 749979f6-71d0-11eb-0b3a-459257d95ca9\nmd\"\"\"\n**Quiz Question: What is the predicted price for the 1st house in the TEST data set for model 1 (round to nearest dollar)?**\n\n\"\"\"\n\n# ╔═╡ 898fa5b2-71d0-11eb-18c3-ad6d0dbf9bf8\nbegin\n\tpred_price_first_house = ya_preds[1]\n\t\n\twith_terminal() do\n\t\t@printf(\"price: %6.2f / price rounded to nearest dollar: %6.0f\\n\", pred_price_first_house, round(pred_price_first_house))\n\tend\nend\n\n# ╔═╡ 5f0bdea2-71d3-11eb-150c-8722eee3f23a\nmd\"\"\"\nNow that you have the predictions on test data, compute the RSS on the test data set. Save this value for comparison later. Recall that RSS is the sum of the squared errors (difference between prediction and output).\n\"\"\"\n\n# ╔═╡ 6d6eb4b0-71d3-11eb-24f0-f9f796040473\nbegin\n\trss_test = sum((ya_preds - test_out).^2)\n\n\twith_terminal() do\n\t\t@printf(\"rss on test set: %15.2f / in scientific notation: %2.4e\\n\", rss_test, rss_test)\n\tend\nend\n\n# ╔═╡ e13d4ca6-71d0-11eb-1ad7-119b4bf3c830\nmd\"\"\"\n### Running a multiple regression\n\nNow we will use more than one actual feature. Use the following code to produce the weights for a second model with the following parameters:\n\n\"\"\"\n\n# ╔═╡ ec505642-71d0-11eb-2619-0f410fee1f94\nbegin\n\tmr_model_features = [:sqft_living, :sqft_living15] \n\tmr_target = :price\n\t(mr_feature_matrix, mr_output) = get_data(sales_train, mr_model_features,\n\t\t\tmr_target)\n\tmr_init_weights = [-100000., 1., 1.]\n\tηᵣ = 4e-12\n\tϵᵣ = 1e9\nend\n\n# ╔═╡ 59a6c7bc-71d1-11eb-2836-71ec957bd538\nmd\"\"\"\nUse the above parameters to estimate the model weights. Record these values for your quiz.\n\"\"\"\n\n# ╔═╡ 6a907c30-71d1-11eb-3adb-1355e084f741\nweights_mr = regression_gradient_descent(mr_feature_matrix, \n\tVector{Float64}(mr_output), mr_init_weights, ηᵣ, ϵᵣ)\n\n# ╔═╡ c47ea9ec-71d1-11eb-0491-9ba85adf1e0a\nmd\"\"\"\nUse your newly estimated weights and the predict_output function to compute the predictions on the test data.\n\n*Don't forget to create a Julia array for these features from the test set first!*\n\"\"\"\n\n# ╔═╡ da6f7c6a-71d1-11eb-381f-5f75054e14e7\nbegin\n\t(test_mr_features_matrix, test_mr_output) = get_data(sales_test, \n\t\tmr_model_features, mr_target)\n\n\tpreds_mr = predict_output(test_mr_features_matrix, weights_mr)\nend\n\n# ╔═╡ 05450824-71d2-11eb-0a05-2b895313421f\nmd\"\"\"\n**Quiz Question: What is the predicted price for the 1st house in the TEST data set for model 2 (round to nearest dollar)?**\n\n\"\"\"\n\n# ╔═╡ 1706d680-71d2-11eb-3cd6-4d156d964fd7\nbegin\n\tpred_mr_price_first_house = preds_mr[1] \n\n\n\twith_terminal() do\n\t\t@printf(\"price: %6.2f / price rounded to nearest dollar: %6.0f\\n\", pred_mr_price_first_house, round(pred_mr_price_first_house))\n\tend\nend\n\n# ╔═╡ 44c15f32-71d2-11eb-2232-5fd5a07b2bfc\nmd\"\"\"\nWhat is the actual price for the 1st house in the test data set?\n\"\"\"\n\n# ╔═╡ 4eeb7218-71d2-11eb-1fa7-21fec4e8c846\nsales_test[!, :price][1]\n\n# ╔═╡ 84462372-71d2-11eb-1627-1fc0ccb0d650\nmd\"\"\"\n**Quiz Question: Which estimate was closer to the true price for the 1st house on the *test* data set, model 1 or model 2?**\n\n  - [x] Model 1\n  - [ ] Model 2\n\n\"\"\"\n\n# ╔═╡ 8ef08466-71d2-11eb-0cbd-17d088b840e0\nmd\"\"\"\nNow use your predictions and the output to compute the RSS for model 2 on *test* data.\n\"\"\"\n\n# ╔═╡ 9db31f5e-71d2-11eb-1527-29c0a844ce47\nbegin\n\trss_test_mr = sum((preds_mr - test_mr_output).^2)\n\n\twith_terminal() do\n\t\t@printf(\"rss on test set: %15.2f / in scientific notation: %2.4e\\n\", rss_test_mr, rss_test_mr)\n\tend\nend\n\n# ╔═╡ 0d254b32-71d3-11eb-2c92-b1a2d1125c5b\nmd\"\"\"\n**Quiz Question: Which model (1 or 2) has lowest RSS on all of the test data?**\n\n  - [ ] model 1\n  - [x] model 2\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─9dcffb1c-71c1-11eb-2402-39eaa1f1b5e1\n# ╟─c39f9348-71c1-11eb-1691-1d28c6b1d916\n# ╠═1bcf25d8-71c2-11eb-05ca-6fe7c4e1b24f\n# ╠═1f7ea604-71c2-11eb-028a-a166f6f4dc5d\n# ╟─3e5d907e-71c2-11eb-2eb3-4375fb21b884\n# ╠═4c736078-71c2-11eb-225b-816745199225\n# ╠═58e6255a-71c2-11eb-2094-9dbe7fb64151\n# ╠═64c97662-71c2-11eb-2894-2d544642b136\n# ╠═80fbf0f8-71c2-11eb-265a-fb539d764180\n# ╟─35b5d05a-71cc-11eb-15a9-852c5a534fab\n# ╟─a2928dc6-71c2-11eb-3724-29dc1448a0f3\n# ╠═e4da992e-71c2-11eb-36b8-93dd614051c1\n# ╠═d62e0368-71c2-11eb-16f7-5fda56951d21\n# ╟─498b3458-71cc-11eb-3b55-8381d58d04bb\n# ╟─daf8aefc-71c7-11eb-04fa-e71d7b2cde21\n# ╠═02f0c99e-71c5-11eb-1fe1-b3f820998d54\n# ╠═9cd636f2-71c5-11eb-2957-afbaf437aaa5\n# ╟─21635b6e-71c8-11eb-2272-edec98c58339\n# ╠═f377f6d4-71c9-11eb-0249-f3d63e87062b\n# ╠═1301a4d2-71ca-11eb-339c-d1f747a3ffe7\n# ╠═49ce0c84-71cb-11eb-3947-6141a9498ffb\n# ╟─239ff6ca-71cc-11eb-341a-df1453d60a15\n# ╠═958f81a6-71cc-11eb-13e8-61dddeb014a7\n# ╟─4454239e-71ce-11eb-295e-1755bc0549e6\n# ╠═0623d920-71ce-11eb-0936-870685f2e788\n# ╠═6a1ee460-71ce-11eb-1b49-4de942aefe9d\n# ╠═9883c1ee-71cf-11eb-3b48-a14df232588f\n# ╟─06cf79e0-71d0-11eb-3eab-ad040213a64b\n# ╠═26199ccc-71d0-11eb-0b4e-5f2f8ebc7b76\n# ╟─4be11b60-71d0-11eb-1550-6d2854691b05\n# ╠═65c26930-71d0-11eb-248a-3751d927b2f6\n# ╟─749979f6-71d0-11eb-0b3a-459257d95ca9\n# ╠═898fa5b2-71d0-11eb-18c3-ad6d0dbf9bf8\n# ╠═5f0bdea2-71d3-11eb-150c-8722eee3f23a\n# ╠═6d6eb4b0-71d3-11eb-24f0-f9f796040473\n# ╟─e13d4ca6-71d0-11eb-1ad7-119b4bf3c830\n# ╠═ec505642-71d0-11eb-2619-0f410fee1f94\n# ╟─59a6c7bc-71d1-11eb-2836-71ec957bd538\n# ╠═6a907c30-71d1-11eb-3adb-1355e084f741\n# ╟─c47ea9ec-71d1-11eb-0491-9ba85adf1e0a\n# ╠═da6f7c6a-71d1-11eb-381f-5f75054e14e7\n# ╟─05450824-71d2-11eb-0a05-2b895313421f\n# ╠═1706d680-71d2-11eb-3cd6-4d156d964fd7\n# ╟─44c15f32-71d2-11eb-2232-5fd5a07b2bfc\n# ╠═4eeb7218-71d2-11eb-1fa7-21fec4e8c846\n# ╟─84462372-71d2-11eb-1627-1fc0ccb0d650\n# ╟─8ef08466-71d2-11eb-0cbd-17d088b840e0\n# ╠═9db31f5e-71d2-11eb-1527-29c0a844ce47\n# ╟─0d254b32-71d3-11eb-2c92-b1a2d1125c5b\n", "meta": {"hexsha": "ed74a94981086a84f2603f7fbb04b195396002d1", "size": 15765, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "C02/w02/C02w02_nb_pa2.jl", "max_stars_repo_name": "pascal-p/ML_UW_Spec", "max_stars_repo_head_hexsha": "5e19916b62fd776b1412ba31d06b41049a1ec7d8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "C02/w02/C02w02_nb_pa2.jl", "max_issues_repo_name": "pascal-p/ML_UW_Spec", "max_issues_repo_head_hexsha": "5e19916b62fd776b1412ba31d06b41049a1ec7d8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C02/w02/C02w02_nb_pa2.jl", "max_forks_repo_name": "pascal-p/ML_UW_Spec", "max_forks_repo_head_hexsha": "5e19916b62fd776b1412ba31d06b41049a1ec7d8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7246696035, "max_line_length": 355, "alphanum_fraction": 0.7327624485, "num_tokens": 5904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8933094046341532, "lm_q1q2_score": 0.7662523216789183}}
{"text": "# Example from Improved relaxations for the parametric solutionsof ODEs using differential inequalities\r\nid = :ScottA2013b\r\n\r\npL = [1.0; 1.0; 0.001]\r\npU = [1200.0; 1200.0; 100.0]\r\nScottA2013b_x0(p::Vector{T}) where T = [1.53*10^(-4)*one(T); 0.4*one(T); zero(T);\r\n                                        zero(T); 0.0019*one(T); zero(T); zero(T);\r\n                                        zero(T); zero(T); zero(T)]\r\nfunction ScottA2013b_f!(du::Vector{T}, u::Vector{T}, p::Vector{T}, t) where T\r\n\r\n    k = T[53.0*one(T); p[1]; p[2]; p[3]; 1200.0*one(T)]\r\n    K2 = 2081.0\r\n    K3 = 4162.0\r\n\r\n    S = zeros(10,5)\r\n    S[1,1] = -1.0; S[2,1] = -1.0; S[3,1] = 1.0;  S[3,2:3] = -1.0; S[3,5] = -2.0;\r\n    S[4,1] = 1.0; S[5,2] = -1.0;  S[5,3] = -1.0; S[6,2] = 1.0;\r\n    S[7,3] = 1.0; S[7,4] = -1.0;  S[8,4] = 1.0;  S[9,4] = 1.0;  S[10,5] = 1.0\r\n\r\n    r = zeros(T, 5)\r\n    r[1] = k[1]*u[1]*u[2]\r\n    r[2] = k[2]*(u[3]*u[5] - (1.0/K2)*u[6])\r\n    r[3] = k[3]*(u[3]*u[5] - (1.0/K3)*u[7])\r\n    r[4] = k[4]*u[7]\r\n    r[5] = k[5]*u[3]^2\r\n\r\n    du[:] = S*r\r\n    return\r\nend\r\ntspan = (0.0, 2.0)\r\n\r\nprob = ODERelaxProb(ScottA2013b_f!, tspan, ScottA2013b_x0, pL, pU)\r\nurl = \"https://link.springer.com/article/10.1007%2Fs10898-012-9909-0\"\r\nsource = \"ScottA2013b\"\r\ndesc = \"Cyclohexadienyl Radical Oxidation\"\r\n", "meta": {"hexsha": "172b436c248336272be3d7b8625af7a11d39e3c7", "size": 1285, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/library/pODEs/Scott2013b.jl", "max_stars_repo_name": "PSORLab/DynamicBounds.jl", "max_stars_repo_head_hexsha": "a7c258e3e4297442ad425c398705f3163e953331", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-15T17:57:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-15T17:57:30.000Z", "max_issues_repo_path": "src/library/pODEs/Scott2013b.jl", "max_issues_repo_name": "PSORLab/DynamicBounds.jl", "max_issues_repo_head_hexsha": "a7c258e3e4297442ad425c398705f3163e953331", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-09-15T14:31:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T03:48:15.000Z", "max_forks_repo_path": "src/library/pODEs/Scott2013b.jl", "max_forks_repo_name": "PSORLab/DynamicBounds.jl", "max_forks_repo_head_hexsha": "a7c258e3e4297442ad425c398705f3163e953331", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-15T17:57:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T17:57:36.000Z", "avg_line_length": 35.6944444444, "max_line_length": 104, "alphanum_fraction": 0.4856031128, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735663, "lm_q2_score": 0.8577681086260461, "lm_q1q2_score": 0.7662523147763014}}
{"text": "# Load Julia packages (libraries) needed.\n\nusing StatisticalRethinking, CmdStan\n#gr(size=(600,600));\n\nProjDir = rel_path(\"..\", \"scripts\", \"05\")\ncd(ProjDir)\n\n# ### snippet 5.1\n\nwd = CSV.read(rel_path(\"..\", \"data\", \"WaffleDivorce.csv\"), delim=';');\ndf = convert(DataFrame, wd);\ndf[!, :A] = scale(df[!, :MedianAgeMarriage]);\ndf[!, :D] = scale(df[!, :Divorce]);\nfirst(df, 5)\n\n# ### snippet 5.1\n\nstd(df[!, :MedianAgeMarriage])\n\nad = \"\ndata {\n int < lower = 1 > N; // Sample size\n vector[N] D; // Outcome\n vector[N] A; // Predictor\n}\n\nparameters {\n real a; // Intercept\n real bA; // Slope (regression coefficients)\n real < lower = 0 > sigma; // Error SD\n}\n\nmodel {\n  vector[N] mu;\n  a ~ normal(0, 0.2);\n  bA ~ normal(0, 0.5);\n  sigma ~ exponential(1);\n  mu = a + bA * A;\n  D ~ normal(mu , sigma);\n}\n\";\n\n# Define the Stanmodel and set the output format to :mcmcchains.\n\nm5_1s = Stanmodel(name=\"MedianAgeDivorce\", model=ad);\n\n# Input data for cmdstan\n\ndata = Dict(\"N\" => length(df[!, :D]), \"D\" => df[!, :Divorce],\n    \"A\" => df[!, :A]);\n\n# Sample using cmdstan\n\nrc, chn, cnames = stan(m5_1s, data, ProjDir, diagnostics=false,\n  summary=true, CmdStanDir=CMDSTAN_HOME);\n\n# Describe the draws\n\nMCMCChains.describe(chn)\n\n# Plot the density of posterior draws\n\nplot(chn)\n\n# Result rethinking\n\nrethinking = \"\n       mean   sd  5.5% 94.5% n_eff Rhat\na      9.69 0.22  9.34 10.03  2023    1\nbA    -1.04 0.21 -1.37 -0.71  1882    1\nsigma  1.51 0.16  1.29  1.79  1695    1\n\"\n\n# Plot regression line using means and observations\n\nxi = -3.0:0.01:3.0\nrws, vars, chns = size(chn)\nalpha_vals = convert(Vector{Float64}, reshape(chn.value[:, 1, :], (rws*chns)))\nbeta_vals = convert(Vector{Float64}, reshape(chn.value[:, 2, :], (rws*chns)))\nyi = mean(alpha_vals) .+ mean(beta_vals)*xi\n\nscatter(df[!, :A], df[!, :D], color=:darkblue,\n  xlab=\"Standardized median age of marriage\",\n  ylab=\"Standardize divorce rate\")\nplot!(xi, yi, lab=\"Regression line\")\n\n# shade(), abline() and link()\n\nmu = link(xi, chn, [1, 2], mean(xi));\nyl = [minimum(mu[i]) for i in 1:length(xi)];\nyh =  [maximum(mu[i]) for i in 1:length(xi)];\nym =  [mean(mu[i]) for i in 1:length(xi)];\npi = hcat(xi, yl, ym, yh);\npi[1:5,:]\n\nplot!((xi, yl), color=:lightgrey, leg=false)\nplot!((xi, yh), color=:lightgrey, leg=false)\nfor i in 1:length(xi)\n  plot!([xi[i], xi[i]], [yl[i], yh[i]], color=:lightgrey, leg=false)\nend\nscatter!(df[!, :A], df[!, :D], color=:darkblue)\nplot!(xi, yi, lab=\"Regression line\")\n\n# End of `05/m5.1s.jl`\n\n", "meta": {"hexsha": "81689657b58e80300449ff3802b94e8c2c24ead2", "size": 2463, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/05/clip-01-05s.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_stars_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/05/clip-01-05s.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_issues_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/05/clip-01-05s.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_forks_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0186915888, "max_line_length": 78, "alphanum_fraction": 0.6191636216, "num_tokens": 879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7662523099035071}}
{"text": "#\n#  Denoising a cyclic (S1-valued) Signal with first and second order TV.\n#  using the Cyclic Proximal Point Algorithm\n#\n# This example was in a similar form part of the paper\n#\n# > Bergmann, R., Laus, F., Steidl, G., Weinmann, A.:\n# > _Second Order Differences of Cyclic Data and Applications in Variational Denoising_\n# > SIAM J. Imaging Sci., 7(4), 2916–2953, 2014.\n# > doi: [10.1137/140969993](https://dx.doi.org/10.1137/140969993)\n# > arXiv: [1405.5349](https://arxiv.org/abs/1405.5349)\n#\nusing Manopt, Manifolds, Plots\n#\n# Settings\nresults_folder = joinpath(@__DIR__, \"Signal_TV\")\nexperiment_name = \"S1_Signal_TV12_CPPA\"\nexport_orig = true\nexport_result = true\n!isdir(results_folder) && mkdir(results_folder)\n#\n# Parameters\nn = 500\nσ = 0.2\nα = 0.5\nβ = 1.0\n#\n# Coloes\ndata_color = RGBA{Float64}(colorant\"#BBBBBB\")\nresult_color = RGBA{Float64}(colorant\"#EE7733\") # data Color: Tol Vibrant Orange\norig_color = RGBA{Float64}(colorant\"#33BBEE\") # tangent vector: Tol Vibrant Teal\n#\n# Manifolds and Data\nM = Circle()\nN = PowerManifold(M, n)\nf = artificial_S1_signal(n)\nxCompare = f\nfn = exp.(Ref(M), f, random_tangent.(Ref(M), f, Val(:Gaussian), σ))\ndata = fn\nt = range(0.0, 1.0; length=n)\n\nif export_orig\n    scene = scatter(\n        t,\n        f;\n        markersize=2,\n        markercolor=data_color,\n        markerstrokecolor=data_color,\n        lab=\"original\",\n    )\n    scatter!(\n        scene,\n        t,\n        fn;\n        markersize=2,\n        markercolor=orig_color,\n        markerstrokecolor=orig_color,\n        lab=\"noisy\",\n    )\n    yticks!(\n        [-π, -π / 2, 0, π / 2, π],\n        [raw\"$-\\pi$\", raw\"$-\\frac{\\pi}{2}$\", raw\"$0$\", raw\"$\\frac{\\pi}{2}$\", raw\"$\\pi$\"],\n    )\n    png(scene, joinpath(results_folder, experiment_name * \"-original.png\"))\nend\n#\n# Setup and Optimize\nF = (N, x) -> costL2TVTV2(N, data, α, β, x)\nproxes = (\n    (N, λ, x) -> prox_distance(N, λ, data, x, 2),\n    (N, λ, x) -> prox_TV(N, α * λ, x),\n    (N, λ, x) -> prox_TV2(N, β * λ, x),\n)\n\no = cyclic_proximal_point(\n    N,\n    F,\n    proxes,\n    data;\n    λ=i -> π / (2 * i),\n    debug=[\n        :Iteration,\n        \" | \",\n        DebugProximalParameter(),\n        \" | \",\n        :Cost,\n        \" | \",\n        :Change,\n        \"\\n\",\n        1000,\n        :Stop,\n    ],\n    record=[:Iteration, :Cost, :Change, :Iterate],\n    return_options=true,\n)\nfR = get_solver_result(o)\nr = get_record(o)\n#\n# Result\nif export_result\n    scene = scatter(\n        t,\n        f;\n        markersize=2,\n        markercolor=data_color,\n        markerstrokecolor=data_color,\n        lab=\"original\",\n    )\n    scatter!(\n        scene,\n        t,\n        fR;\n        markersize=2,\n        markercolor=result_color,\n        markerstrokecolor=result_color,\n        lab=\"reconstruction\",\n    )\n    yticks!(\n        [-π, -π / 2, 0, π / 2, π],\n        [raw\"$-\\pi$\", raw\"$-\\frac{\\pi}{2}$\", raw\"$0$\", raw\"$\\frac{\\pi}{2}$\", raw\"$\\pi$\"],\n    )\n    png(scene, joinpath(results_folder, experiment_name * \"-result.png\"))\nend\n\nprint(\"MSE (input):  \", 1 / n * distance(N, xCompare, data)^2, \"\\n\")\nprint(\"MSE (result): \", 1 / n * distance(N, xCompare, fR)^2, \"\\n\")\n", "meta": {"hexsha": "8ad25d32f39bbb56d5433ec33cca036b96f656d2", "size": 3115, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/CyclicProximalPoint/S1_Signal_TV12_CPPA.jl", "max_stars_repo_name": "const-ae/Manopt.jl", "max_stars_repo_head_hexsha": "cdaeee451d53d4813d37cf859f2ca6adcad82635", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 141, "max_stars_repo_stars_event_min_datetime": "2020-03-30T08:00:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T09:37:54.000Z", "max_issues_repo_path": "examples/CyclicProximalPoint/S1_Signal_TV12_CPPA.jl", "max_issues_repo_name": "const-ae/Manopt.jl", "max_issues_repo_head_hexsha": "cdaeee451d53d4813d37cf859f2ca6adcad82635", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 90, "max_issues_repo_issues_event_min_datetime": "2020-03-30T08:00:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T08:55:37.000Z", "max_forks_repo_path": "examples/CyclicProximalPoint/S1_Signal_TV12_CPPA.jl", "max_forks_repo_name": "const-ae/Manopt.jl", "max_forks_repo_head_hexsha": "cdaeee451d53d4813d37cf859f2ca6adcad82635", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2020-04-14T11:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T21:36:59.000Z", "avg_line_length": 24.5275590551, "max_line_length": 89, "alphanum_fraction": 0.572070626, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.7662489260716124}}
{"text": "function mutual_information_contingency(probs::AbstractMatrix{Float64}; normalize::Bool=false)\n    ee = entropy(ProbabilityWeights(probs[:]))\n    ex = entropy(ProbabilityWeights(sum(probs, dims=1)[:]))\n    ey = entropy(ProbabilityWeights(sum(probs, dims=2)[:]))\n\n    mi = ex + ey - ee\n    return normalize ? min(mi / min(ex, ey), 1.) : mi\nend\n\n\nfunction mutual_information(\n    x::AbstractVector, y::AbstractVector, ex::Float64, ey::Float64; method=:Naive, adjusted=false, normalize=false)\n\n    # Compute the joint entropy without adjustment nor normalization\n    ee = estimate_joint_entropy(x, y; method=method)\n\n    if adjusted\n        ee_shuffle = estimate_joint_entropy(x, shuffle(y); method=method)\n        mi_shuffle = ex + ey - ee_shuffle\n        mi = ee_shuffle - ee\n        normalize ? mi / (min(ex, ey) - mi_shuffle) : mi\n    else\n        mi = ex + ey - ee\n        normalize ? min(mi / min(ex, ey), 1.) : mi\n    end\nend\n\nfunction mutual_information(\n    x::AbstractVector, y::AbstractVector;\n    method=:Naive, adjusted=false, normalize=false)\n\n    ex = estimate_entropy(x)\n    ey = estimate_entropy(y)\n    mutual_information(\n        x, y, ex, ey; method=method, adjusted=adjusted, normalize=normalize)\nend\n\nfunction mutual_information(data::AbstractMatrix; method::Symbol=:Naive, adjusted::Bool=false, normalize::Bool=false)\n    M = size(data, 2)\n    mi_sym = Array{Float64, 2}(undef, M, M)\n\n    for i =1:M\n        mi_sym[i,i] = estimate_entropy(@view data[:,i]; method=method)\n    end\n\n    for i = 1:M, j=i+1:M\n        ex = mi_sym[i,i]\n        ey = mi_sym[j,j]\n\n        x = @view data[:,i]\n        y = @view data[:,j]\n\n        mi_sym[i, j] = mutual_information(\n            x, y, ex, ey;\n            method=method, adjusted=adjusted, normalize=normalize)\n\n        # Drop null or negative values\n        if mi_sym[i, j] < Base.eps()\n            mi_sym[i, j] = 0.\n        end\n\n        mi_sym[j,i] = mi_sym[i,j]  # tbr\n    end\n    mi_sym\nend\n", "meta": {"hexsha": "d0b9ef86f006567c361b345f4470d04a727b5e95", "size": 1952, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mutual_information.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Discreet.jl-c2843242-4f35-58a6-a2a0-7e7527607317", "max_stars_repo_head_hexsha": "8388e9a19c564eaad84fdc77f959e65123f27566", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mutual_information.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Discreet.jl-c2843242-4f35-58a6-a2a0-7e7527607317", "max_issues_repo_head_hexsha": "8388e9a19c564eaad84fdc77f959e65123f27566", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mutual_information.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Discreet.jl-c2843242-4f35-58a6-a2a0-7e7527607317", "max_forks_repo_head_hexsha": "8388e9a19c564eaad84fdc77f959e65123f27566", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5757575758, "max_line_length": 117, "alphanum_fraction": 0.6229508197, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7662489252015185}}
{"text": "\"\"\"\n    RiemannMatrix\n\nType containing information about the Riemann Matrix, for use in computing the Riemann theta function.\n\"\"\"\nstruct RiemannMatrix\n    τ::Array{<:Number} # matrix in Siegel upper-half space\n    g::Integer # genus\n    X::Array{<:Real} # real part of τ\n    Y::Array{<:Real} # imaginary part of τ\n    T::Array{<:Real} # upper triangular matrix in Cholesky factorization of Y\n    ellipsoid::Array{} # points to sum over for computing theta functions\n\n    \"\"\"\n        RiemannMatrix(τ, siegel=false, ϵ=1.0e-12, nderivs=4)\n\n    Construct a RiemannMatrix type using a matrix τ in the Siegel upper-half space, for use in computing the Riemann theta function.\n\n    # Arguments\n    - `τ::Array{<:Number}`: 2-dimensional array of complex numbers\n    - `siegel::Bool=false`: do a siegel transformation on τ if true, and use the input matrix otherwise\n    - `ϵ::Real=1.0e-12`: absolute error in value of theta function or its derivatives\n    - `nderivs::Integer=4`: highest order of the derivatives of the theta function\n\n    # Examples\n    ```julia\n    julia> RiemannMatrix([1+im -1; -1 1+im], siegel=true, nderivs=2)\n    ```\n    \"\"\"\n    function RiemannMatrix(τ::Array{<:Number}; siegel::Bool=false, ϵ::Real=1.0e-12, nderivs::Integer=4)\n        τ = (siegel ? siegel_transform(τ)[2] : τ);\n        X = real(τ);\n        Y = imag(τ);\n        g = size(Y)[1];\n        T = (g > 1 ? convert(Array{Float64}, cholesky(Symmetric(Y)).U) : sqrt.(Y));\n        ρ = svp(T)[2]*sqrt(π); # length of shortest vector in lattice generated by √π*T\n        radius = [radius_ellipsoid(ϵ, T, Y, ρ, i) for i=0:nderivs]; # radius of ellipsoids for computing theta function, and up to nderivs derivatives.\n        ellipsoid = [ellipsoid_uniform(T, r) for r in radius];\n        new(τ, g, X, Y, T, ellipsoid)\n    end\nend\n\n\n\"\"\"\n    random_siegel(g)\n\nSample a random matrix in the Siegel upper half space with genus g.\n\n# Arguments\n- `g::Integer`: genus.\n\n# Examples\n```julia\njulia> random_siegel(5)\n```\n\"\"\"\nfunction random_siegel(g::Integer)\n    Mx = 2*rand(g, g) - ones(g,g); # entries are random between [-1,1)\n    My = 2*rand(g, g) - ones(g,g); # entries are random between [-1,1)\n    τ = Symmetric((1/2)*(transpose(Mx) + Mx)) + Symmetric(transpose(My)*My)*im; # symmetric real part and psd imaginary part\n    return convert(Array, τ);\nend\n", "meta": {"hexsha": "9093ed6c6adf0fd595644a7f9916f672ab968925", "size": 2320, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/riemann_matrix.jl", "max_stars_repo_name": "vchuravy/Theta.jl", "max_stars_repo_head_hexsha": "c18971456d4aa36bf0f109366ee897e68a413152", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-09-17T23:51:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T17:20:32.000Z", "max_issues_repo_path": "src/riemann_matrix.jl", "max_issues_repo_name": "vchuravy/Theta.jl", "max_issues_repo_head_hexsha": "c18971456d4aa36bf0f109366ee897e68a413152", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-04T16:32:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T08:18:16.000Z", "max_forks_repo_path": "src/riemann_matrix.jl", "max_forks_repo_name": "vchuravy/Theta.jl", "max_forks_repo_head_hexsha": "c18971456d4aa36bf0f109366ee897e68a413152", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T23:19:24.000Z", "avg_line_length": 36.8253968254, "max_line_length": 151, "alphanum_fraction": 0.650862069, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913354875362, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7662479103992483}}
{"text": "export rrefx\n\n\"\"\"\n`rref(A)`  returns the row-reduced echelon form of the exact \nmatrix `A`.\n\"\"\"\nfunction rrefx(A::AbstractMatrix{T}) where {T<:IntegerX}\n    AA = big.(A // 1)\n    return rrefx(AA)\nend\n\nfunction rrefx(A::AbstractMatrix{T}) where {T}\n    AA = copy(A)\n    rrefx!(AA)\n    return AA\nend\n\n\nfunction _pivot!(A::AbstractMatrix{T}, i::Int, j::Int) where {T}\n    r, c = size(A)\n    s = A[i, j]\n    row_scale!(A, i, invx(s))\n\n    for k = 1:r\n        if k != i\n            s = -A[k, j]\n            row_add_mult!(A, i, s, k)\n        end\n    end\nend\n\n\n\nfunction rrefx!(A::AbstractMatrix{T}) where {T}\n    rn, nc = size(A)\n\n    r = 1\n    for j = 1:nc\n        # see if column j's first one is at level r or below\n        col = A[r:end, j]\n        if all(col .== 0)\n            continue\n        end\n        k = findfirst(col .!= 0)\n        row_swap!(A, r, k + r - 1)\n        _pivot!(A, r, j)\n        r += 1\n    end\n\n\nend\n", "meta": {"hexsha": "d180bc8366fcb3048903aba3af84914f484dc393", "size": 920, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rrefx.jl", "max_stars_repo_name": "scheinerman/LinearAlgebraX.jl", "max_stars_repo_head_hexsha": "ccb34ba16fc11eb72b6f3ff624bd02310ff69d8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2020-08-04T09:50:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:10:44.000Z", "max_issues_repo_path": "src/rrefx.jl", "max_issues_repo_name": "scheinerman/LinearAlgebraX.jl", "max_issues_repo_head_hexsha": "ccb34ba16fc11eb72b6f3ff624bd02310ff69d8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-08-04T11:11:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T12:11:30.000Z", "max_forks_repo_path": "src/rrefx.jl", "max_forks_repo_name": "scheinerman/LinearAlgebraX.jl", "max_forks_repo_head_hexsha": "ccb34ba16fc11eb72b6f3ff624bd02310ff69d8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-08-04T09:53:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-25T20:37:06.000Z", "avg_line_length": 17.6923076923, "max_line_length": 64, "alphanum_fraction": 0.5043478261, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7662479014288921}}
{"text": "using JLD2\n@load \"2/data.jld2\" c d A B b D f G g\n\nusing JuMP\nusing Clp\nusing LinearAlgebra\n\np1 = 25\np2 = 100\np3 = 200\nn = 50\nm = 100\n\n# Primal\n\nprimal = Model(Clp.Optimizer)\n\n@variables(primal, begin\n        x[1:n]\n        y[1:m]\n    end\n)\n\n@objective(primal, Min, c'x + d'y)\n\n@constraints(\n\tprimal,\n\tbegin\n        A * x + B * y .== b\n\t\tD * x .<= f\n        G * y .<= g\n    end\n)\n\noptimize!(primal)\n\nx̂ = value.(x)\nŷ = value.(y)\n\n# Dual\n\ndual = Model(Clp.Optimizer)\n\n@variables(dual, begin\n        p[1:p1]\n        q[1:p2] <= 0\n        r[1:p3] <= 0\n    end\n)\n\n@objective(dual, Max, p'b + q'f + r'g)\n\n@constraints(\n\tdual,\n\tbegin\n        p'A + q'D .== c'\n        p'B + r'G .== d'\n    end\n)\n\noptimize!(dual)\n\nprintln(\"primal: \", objective_value(primal))\nprintln(\"dual: \", objective_value(dual))\n@assert objective_value(primal) ≈ objective_value(dual)\n", "meta": {"hexsha": "1534f79e03c8b7f01e845cb7e9c3252408d3328d", "size": 847, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2/3.jl", "max_stars_repo_name": "tansongchen/learn-optimization", "max_stars_repo_head_hexsha": "b44e902c857287ff05da449b9a639dfe534af8ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2/3.jl", "max_issues_repo_name": "tansongchen/learn-optimization", "max_issues_repo_head_hexsha": "b44e902c857287ff05da449b9a639dfe534af8ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2/3.jl", "max_forks_repo_name": "tansongchen/learn-optimization", "max_forks_repo_head_hexsha": "b44e902c857287ff05da449b9a639dfe534af8ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.8333333333, "max_line_length": 55, "alphanum_fraction": 0.5525383707, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7662478972095473}}
{"text": "\"\"\"\n    BlackScholes()\n\n[Black-Scholes model](https://en.wikipedia.org/wiki/Black%E2%80%93Scholes_model).\n\"\"\"\nstruct BlackScholes <: Model end\n\n\"\"\"\n    evaluate(O, BlackScholes())\n\nEvaluate option `O` using `BlackScholes` model.\n\n# Arguments\n- `O::Option`: Option\n\"\"\"\nfunction evaluate(O::EuropeanOption, m::BlackScholes)\n    d1 = (log(O.s / O.k) + (O.r + O.σ * O.σ / 2) * O.t) / (O.σ * √O.t)\n    d2 = d1 - O.σ * √O.t\n\n    if O.call == -1\n        return cdf(Normal(), -d2) * O.k * exp(-O.r * O.t) - cdf(Normal(), -d1) * O.s\n    elseif O.call == 1\n        return O.s * cdf(Normal(), d1) - exp(-O.r * O.t) * O.k * cdf(Normal(), d2)\n    end\nend\n\n\n\"\"\"\n    evaluate(o)\n\nEvaluate option `o` using Back-Scholes model as default valuation model.\n\"\"\"\nevaluate(O::EuropeanOption) = evaluate(O::EuropeanOption, m::BlackScholes)\n", "meta": {"hexsha": "d6604c2cc2dd34749c9bdcc6e106fd9ac71f8bf5", "size": 817, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/black_scholes.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/FinancialDerivatives.jl-43843433-91eb-5384-8a0e-cbb992997742", "max_stars_repo_head_hexsha": "3c46d7973fa3029223c6a28214951a246147cb0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2018-10-29T22:01:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:59:46.000Z", "max_issues_repo_path": "src/models/black_scholes.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/FinancialDerivatives.jl-43843433-91eb-5384-8a0e-cbb992997742", "max_issues_repo_head_hexsha": "3c46d7973fa3029223c6a28214951a246147cb0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-10-25T11:37:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-30T07:12:06.000Z", "max_forks_repo_path": "src/models/black_scholes.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/FinancialDerivatives.jl-43843433-91eb-5384-8a0e-cbb992997742", "max_forks_repo_head_hexsha": "3c46d7973fa3029223c6a28214951a246147cb0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-10-29T14:31:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T16:04:18.000Z", "avg_line_length": 24.0294117647, "max_line_length": 84, "alphanum_fraction": 0.5960832313, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.76623962954686}}
{"text": "function standard_normal_gausshermite(n::Int)\n    ϵᵢ, wᵢ = gausshermite(n) # approximates exp(-x²)\n    ϵᵢ   .*= sqrt(2.)        # Normalize ϵᵢ and wᵢ nodes to approximate standard normal\n    wᵢ   ./= sqrt(π)\n\n    return ϵᵢ, wᵢ\nend\n\n\"\"\"\n```\ngausshermite_expectation(f, μ, σ, n = 10)\ngausshermite_expectation(f, μ, Σ, n = 10)\ngausshermite_expectation(f, μ, Σ, ns)\n```\n\ncalculates the expectation of a function of a Gaussian random variable/vector.\nThe first method evalulates ``\\\\mathbb{E}[f(X)]`` where ``X \\\\sim N(\\\\mu, \\\\sigma)``,\nwhile the other two methods evaluate ``\\\\mathbb{E}[f(X)]`` where\n``X \\\\sim \\\\mathcal{N}(\\\\mu, \\\\Sigma)`` and ``\\\\Sigma`` is diagonal.\nThe latter two methods differ in that the first assumes the same number of\nquadrature points in every dimension while the second does not.\n\n### Inputs\n- `f::Function`: some function of a random variable. If `f(x) = x`, then\n    `gausshermite_expectation(f, μ, σ)` calculates the mean of ``N(\\\\mu, \\\\sigma)``\n    using 10-point Gauss-Hermite quadrature.\n- `μ::Number` or `μ::AbstractVector`: mean of the Gaussian random variable/vector.\n- `σ::Number`: standard deviation of the Gaussian random variable.\n- `Σ::AbstractVector`: diagonal of the variance-covariance matrix of\n     the Gaussian random vector.\n- `n::Int`: number of quadrature points to use\n- `ns::AbstractVector{Int}` or `ns::NTuple{N, Int} where N`: number of quadrature points to use\n    in each dimension of the Gaussian random vector.\n\"\"\"\nfunction gausshermite_expectation(f::Function, μ::Number, σ::Number, n::Int = 10)\n    ϵᵢ, wᵢ = gausshermite(n)\n    ϵᵢ   .*= sqrt(2.)  # Normalize ϵᵢ and wᵢ nodes to approximate standard normal\n    # wᵢ   ./= sqrt(π) # This step done later to reduce number of computations\n\n    if μ ≈ 0.\n        return sum([wᵢ[i] * f(ϵᵢ[i] * σ) for i in 1:n]) / sqrt(π)\n    else\n        return sum([wᵢ[i] * f(ϵᵢ[i] * σ + μ) for i in 1:n]) / sqrt(π)\n    end\n\nend\n\nfunction gausshermite_expectation(f::Function, μ::AbstractVector{S},\n                                  Σ::AbstractVector{<: Number}, n::Int = 10) where {S <: Number}\n\n    d = length(μ)\n    @assert length(Σ) == d \"The length of μ and Σ must be the same.\"\n    ϵ, w = gausshermite(n)\n    ϵ   .*= sqrt(2.)  # Normalize ϵ and w nodes to approximate standard normal\n    # w   ./= sqrt(π) # This step done later to reduce number of computations\n\n    # Evaluate over the tensor grid\n    feval = Array{S}(undef, (n for i in 1:d)...)\n    allCI = CartesianIndices(feval)\n    if all(μ .≈ 0.)\n        @simd for CI in allCI\n            feval[CI] = f([ϵ[i] for i in Tuple(CI)] .* Σ)\n        end\n    else\n        @simd for CI in allCI\n            feval[CI] = f([ϵ[i] for i in Tuple(CI)] .* Σ + μ)\n        end\n    end\n\n    for n_dim in 1:(d - 1)\n        # Iteratively integrate out each dimension, i.e. law of iterated expectations\n        iter = CartesianIndices(tuple(Tuple(1:n for i in 1:(d - n_dim))...,\n                                      Tuple(1:1 for i in 1:n_dim)...)) # Create CartesianIndices for all remaining dimensions\n        # ((1:n for i in 1:(d - n_dim + 1))..., (1 for i in 1:(n_dim - 1))...) creates a Tuple of 1:n for the dimensions\n        # that are not to be integrated out and uses 1s for the remaining dimensions. We want to use each dimension of feval\n        # from 1 to (d - n_dim) (inclusive). So on the first iteration, the tuple should be (1:n, 1:n).\n        # We then assign it to the dimensions of feval from 1 to (d - n_dim - 1) (inclusive) to avoid allocations\n        feval[iter] .= dropdims(sum(mapslices(fᵢ -> fᵢ .* w, (@view feval[((1:n for i in 1:(d - n_dim + 1))...,\n                                                                           (1 for i in 1:(n_dim - 1))...)...]),\n                                              dims = (d - n_dim) + 1), dims = (d - n_dim) + 1), dims = (d - n_dim) + 1)\n    end\n\n    # Handle final integration on its own\n    return sum(w .* (@view feval[:, (1 for i in 1:(d - 1))...])) / π^(d / 2)\nend\n\nfunction gausshermite_expectation(f::Function, μ::AbstractVector{S},\n                                  Σ::AbstractVector{<: Number}, ns::AbstractVector{Int}) where {S <: Number}\n\n    d = length(μ)\n    @assert length(Σ) == d \"The length of μ and Σ must be the same.\"\n    ϵ = Dict{Int, Vector{S}}()\n    w = Dict{Int, Vector{S}}()\n    for i in 1:d\n        ϵ[i], w[i] = gausshermite(ns[i])\n        ϵ[i]     .*= sqrt(2.)  # Normalize ϵ and w nodes to approximate standard normal\n        # w[i]   ./= sqrt(π) # This step done later to reduce number of computations\n    end\n\n    # Evaluate over the tensor grid\n    feval = Array{S}(undef, (n for n in ns)...)\n    allCI = CartesianIndices(feval)\n    if all(μ .≈ 0.)\n        @simd for CI in allCI\n            feval[CI] = f([ϵ[n_dim][gridᵢ] for (n_dim, gridᵢ) in enumerate(Tuple(CI))] .* Σ)\n        end\n    else\n        @simd for CI in allCI\n            feval[CI] = f([ϵ[n_dim][gridᵢ] for (n_dim, gridᵢ) in enumerate(Tuple(CI))] .* Σ + μ)\n        end\n    end\n\n    # Iteratively integrate out each dimension, i.e. law of iterated expectations\n    for n_dim in 1:(d - 1)\n        iter = CartesianIndices(tuple(Tuple(1:ns[i] for i in 1:(d - n_dim))...,\n                                      Tuple(1:1 for i in 1:n_dim)...))\n        feval[iter, 1] .= dropdims(sum(mapslices(fᵢ -> fᵢ .* w[d - n_dim + 1], (@view feval[((1:ns[i] for i in 1:(d - n_dim + 1))...,\n                                                                                             (1 for i in 1:(n_dim - 1))...)...]),\n                                                 dims = (d - n_dim) + 1), dims = (d - n_dim) + 1), dims = (d - n_dim) + 1)\n    end\n\n    # Handle final integration on its own\n    return sum(w[1] .* (@view feval[:, (1 for i in 1:(d - 1))...])) / π^(d / 2)\nend\n\nfunction gausshermite_expectation(f::Function, μ::AbstractVector{S},\n                                  Σ::AbstractVector{<: Number}, ns::NTuple{N, Int}) where {S<: Number, N}\n\n    d = length(μ)\n    @assert length(Σ) == d \"The length of μ and Σ must be the same.\"\n    ϵ = Dict{Int, Vector{S}}()\n    w = Dict{Int, Vector{S}}()\n    for i in 1:d\n        ϵ[i], w[i] = gausshermite(ns[i])\n        ϵ[i]     .*= sqrt(2.)  # Normalize ϵ and w nodes to approximate standard normal\n        # w[i]   ./= sqrt(π) # This step done later to reduce number of computations\n    end\n\n    # Evaluate over the tensor grid\n    feval = Array{S}(undef, (n for n in ns)...)\n    allCI = CartesianIndices(feval)\n    if all(μ .≈ 0.)\n        @simd for CI in allCI\n            feval[CI] = f([ϵ[n_dim][gridᵢ] for (n_dim, gridᵢ) in enumerate(Tuple(CI))] .* Σ)\n        end\n    else\n        @simd for CI in allCI\n            feval[CI] = f([ϵ[n_dim][gridᵢ] for (n_dim, gridᵢ) in enumerate(Tuple(CI))] .* Σ + μ)\n        end\n    end\n\n    # Iteratively integrate out each dimension, i.e. law of iterated expectations\n    for n_dim in 1:(d - 1)\n        iter = CartesianIndices(tuple(Tuple(1:ns[i] for i in 1:(d - n_dim))...,\n                                      Tuple(1:1 for i in 1:n_dim)...))\n        feval[iter, 1] .= dropdims(sum(mapslices(fᵢ -> fᵢ .* w[d - n_dim + 1], (@view feval[((1:ns[i] for i in 1:(d - n_dim + 1))...,\n                                                                                             (1 for i in 1:(n_dim - 1))...)...]),\n                                                 dims = (d - n_dim) + 1), dims = (d - n_dim) + 1), dims = (d - n_dim) + 1)\n    end\n\n    # Handle final integration on its own\n    return sum(w[1] .* (@view feval[:, (1 for i in 1:(d - 1))...])) / π^(d / 2)\nend\n", "meta": {"hexsha": "339d9e371673f67b6dfdad65b620b97cc9dd8f17", "size": 7537, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simulation/gausshermite_expectation.jl", "max_stars_repo_name": "chenwilliam77/RiskAdjustedLinearizations", "max_stars_repo_head_hexsha": "24d95b555882bc5336fe9fb456e9364c6f8f0f3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-08-05T15:42:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T22:08:25.000Z", "max_issues_repo_path": "src/simulation/gausshermite_expectation.jl", "max_issues_repo_name": "chenwilliam77/RiskAdjustedLinearizations.jl", "max_issues_repo_head_hexsha": "24d95b555882bc5336fe9fb456e9364c6f8f0f3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2020-09-17T14:15:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-08T10:46:48.000Z", "max_forks_repo_path": "src/simulation/gausshermite_expectation.jl", "max_forks_repo_name": "chenwilliam77/RiskAdjustedLinearizations", "max_forks_repo_head_hexsha": "24d95b555882bc5336fe9fb456e9364c6f8f0f3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-12-03T14:38:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T23:24:08.000Z", "avg_line_length": 45.9573170732, "max_line_length": 133, "alphanum_fraction": 0.5491574897, "num_tokens": 2420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.76623962954686}}
{"text": "\"\n    Polynomial{T<:Number} <: Function\n\nA Polynomial struct implements the mathematical object P(x) = ∑ cᵢ xⁱ by\nstoring the coefficients cᵢ (i ∈ {0,..., deg(P)}) into a 1-dimensional array of\nnumbers. The **degree** of a polynomial is the highest power of the xᵢ terms.\n\"\nstruct Polynomial{T<:Number} <: Function\n    coeffs::Array{T,1}\n    degree::Int\n\n    function Polynomial{T}(c::Array{T,1}) where {T<:Number}\n        n = length(c) - 1\n        new(c, n)\n    end\n\nend\n\nPolynomial(c::Array{T,1}) where {T<:Number} = Polynomial{T}(c)\n\ndeg(poly::Polynomial{T}) where {T<:Number} = poly.degree\n\nfunction (poly::Polynomial{T})(x::Number, bases=zeros(T, deg(poly), 1)) where {T<:Number}\n    #= Method 1: The first and most straightforward approach:\n    result = 0\n    for (power, c) in enumerate(poly.coeffs)\n        result += c * x^(power - 1)\n    end\n    =#\n\n    #= Method 2: Find the powers and store them for future uses:\n    result = 0\n    power = 1\n    for c in poly.coeffs\n        result += c * power\n        power *= x\n    end\n    =#\n\n    #= Method 3 (Horner): Nest multiplication =#\n    result = poly.coeffs[end]\n    for i = deg(poly):-1:1\n        result *= x - bases[i]\n        result += poly.coeffs[i]\n    end\n\n    result\nend\n\n", "meta": {"hexsha": "459484be3849ec14b44e4f2a62ca1c51fe28df75", "size": 1236, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter-0/01_evaluating_polynomials.jl", "max_stars_repo_name": "kraemerd17/numerical-julia", "max_stars_repo_head_hexsha": "3cfef336ca327ec772ccf4058edacc4e8243f4c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/chapter-0/01_evaluating_polynomials.jl", "max_issues_repo_name": "kraemerd17/numerical-julia", "max_issues_repo_head_hexsha": "3cfef336ca327ec772ccf4058edacc4e8243f4c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chapter-0/01_evaluating_polynomials.jl", "max_forks_repo_name": "kraemerd17/numerical-julia", "max_forks_repo_head_hexsha": "3cfef336ca327ec772ccf4058edacc4e8243f4c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.72, "max_line_length": 89, "alphanum_fraction": 0.604368932, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491797, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7662396287620955}}
{"text": "using Distributions: Normal, Uniform\n\nis_vector(x) = size(x,2) == 1\nnrows(x) = size(x,1)\ndim_error(message:: String) = throw(DimensionMismatch(message)) \n\n\"\"\"Sample(X,Y)\n\nSample holds X array of size n*k (explanatory variables, \nindependent variables, features or regressor) and Y, a n*1 sized \nvector, for observed data (response, dependent variable or regressand).    \n\"\"\"\nstruct Sample\n    X::Array \n    Y::Vector\n    function Sample(X, Y)        \n        nrows(X) == nrows(Y) || dim_error(\"X and Y must have same number of rows\")\n        is_vector(Y) || dim_error(\"Y must be a vector: $Y\")   \n        new(X, Y)\n    end    \nend\n\nfunction add_intercept(X::Array)::Array\n    X0 = ones(nrows(X), 1)\n    return [X0 X]\nend    \n\n# TODO: do not add intercept if it is already there.\nfunction add_intercept(sample::Sample)\n    return Sample(add_intercept(sample.X), sample.Y)\nend\n\nfunction sample_factory(;x_process, y_process, error_process)\n    function sampler(n:: Int)\n        X = x_process(n)\n        Y = vec(y_process(X) + error_process(X))\n        return Sample(X, Y)\n    end\nend\n\nfunction normal_sampler(;a, b, β_0, β, sd_e)\n    k = length(β)\n    du = Uniform(a, b) # this is squares for x only\n    dn = Normal(0, sd_e)\n    sample_factory(x_process = n -> rand(du, n, k),\n                   y_process = X -> β_0 .+ X * β, \n                   error_process = X -> rand(dn, nrows(X), 1)\n                   )\nend", "meta": {"hexsha": "5bfeb6020e8704849835d21b3dc934f531fa9657", "size": 1412, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sample.jl", "max_stars_repo_name": "epogrebnyak/LessOLS.jl", "max_stars_repo_head_hexsha": "4110ae98c702b522f04a238eeaa92c403c3ff66d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-12-25T21:17:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T18:21:15.000Z", "max_issues_repo_path": "src/sample.jl", "max_issues_repo_name": "epogrebnyak/LessOLS.jl", "max_issues_repo_head_hexsha": "4110ae98c702b522f04a238eeaa92c403c3ff66d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sample.jl", "max_forks_repo_name": "epogrebnyak/LessOLS.jl", "max_forks_repo_head_hexsha": "4110ae98c702b522f04a238eeaa92c403c3ff66d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8163265306, "max_line_length": 82, "alphanum_fraction": 0.6182719547, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180243, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7662396275996428}}
{"text": "module AngleBetweenVectors\n\nimport Base: angle\n\nimport LinearAlgebra: norm\n\n\n@inline unitize(p) = p ./ norm(p)\n\n\"\"\"\n    angle(point1::T, point2::T) where {T}\n\nAccurately ascertains the undirected angle (0 <= radians < pi)\nbetween two points given in N-dimensional Cartesian coordinates.\n\nPrefer this to `acos` alternatives\n- more reliably accurate\n- more consistently stable\n\nSuggested when any |coordinate| of either point may be outside 2^±20 or [1/1_000_000, 1_000_000].\nStrongly recommended when any |coordinate| is outside 2^±24 or [1/16_000_000, 16_000_000].\n\nIf one of the points is at the origin, the result is zero.\n\nYou *must* define a tuple constructor `Tuple(x::YourPointType) = ...` if one does not already exist.\n\"\"\"\nfunction angle(point1::A, point2::A) where {N,T<:Real,NT<:NTuple{N,T}, V<:Vector{T}, A<:Union{NT,V}}\n    unitpoint1 = unitize(point1)\n    unitpoint2 = unitize(point2)\n\n    y = unitpoint1 .- unitpoint2\n    x = unitpoint1 .+ unitpoint2\n\n    a = 2 * atan(norm(y) / norm(x))\n\n    !(signbit(a) || signbit(T(pi) - a)) ? a : (signbit(a) ? zero(T) : T(pi))\nend\n\n@inline angle(point1::T, point2::T) where {T} = angle(Tuple(point1), Tuple(point2))\n\nend # AngleBetweenVectors\n", "meta": {"hexsha": "2415a20b4e37ed36457ca7be7c57ad06df3a86de", "size": 1196, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/AngleBetweenVectors.jl", "max_stars_repo_name": "emerali/AngleBetweenVectors.jl", "max_stars_repo_head_hexsha": "675218adacf7aec56ddb538036d0a70053cd83fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2018-07-06T18:19:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T13:10:43.000Z", "max_issues_repo_path": "src/AngleBetweenVectors.jl", "max_issues_repo_name": "emerali/AngleBetweenVectors.jl", "max_issues_repo_head_hexsha": "675218adacf7aec56ddb538036d0a70053cd83fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-07-10T13:50:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-05T10:47:04.000Z", "max_forks_repo_path": "src/AngleBetweenVectors.jl", "max_forks_repo_name": "emerali/AngleBetweenVectors.jl", "max_forks_repo_head_hexsha": "675218adacf7aec56ddb538036d0a70053cd83fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:25:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-01T18:04:14.000Z", "avg_line_length": 28.4761904762, "max_line_length": 100, "alphanum_fraction": 0.6956521739, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7662396255167337}}
{"text": "## Preloads\nmodule DHC_2DUtils\n\n    using FFTW\n    using LinearAlgebra\n    using Statistics\n\n    export fink_filter_bank\n    export fink_filter_list\n    export fink_filter_hash\n    export DHC_compute\n\n\n    function fink_filter_bank(c, L; nx=256, wd=1, pc=1, shift=false)\n        #c     - sets the scale sampling rate (1 is dyadic, 2 is half dyadic)\n        #L     - number of angular bins (usually 8*pc or 16*pc)\n        #wd    - width of the wavelets (default 1, wd=2 for a double covering)\n        #pc    - plane coverage (default 1, full 2pi 2)\n        #shift - shift in θ by 1/2 of the θ spacing\n\n        # -------- set parameters\n        dθ   = pc*π/L\n        wdθ  = wd*dθ\n        θ_sh = shift ? dθ/2 : 0.0\n        dx   = nx/2-1\n        norm = 1.0/sqrt(wd)\n\n        im_scale = convert(Int8,log2(nx))\n        # -------- number of bins in radial direction (size scales)\n        J = (im_scale-2)*c\n\n        # -------- allocate output array of zeros\n        filt      = zeros(nx, nx, J*L+1)\n        psi_index = zeros(Int32, J, L)\n        theta     = zeros(Float64, L)\n        j_value   = zeros(Float64, J)\n\n        # -------- allocate theta and logr arrays\n        θ    = zeros(nx, nx)\n        logr = zeros(nx, nx)\n\n        # -------- loop over l\n        for l = 0:L-1\n            θ_l        = dθ*l+θ_sh\n            theta[l+1] = θ_l\n\n        # -------- allocate anggood BitArray\n            anggood = falses(nx, nx)\n\n        # -------- loop over pixels\n            for x = 1:nx\n                sx = mod(x+dx,nx)-dx -1    # define sx,sy so that no fftshift() needed\n                for y = 1:nx\n                    sy = mod(y+dx,nx)-dx -1\n                    θ_pix  = mod(atan(sy, sx)+π -θ_l, 2*π)\n                    θ_good = abs(θ_pix-π) <= wdθ\n\n                    # If this is a pixel we might use, calculate log2(r)\n                    if θ_good\n                        anggood[y, x] = θ_good\n                        θ[y, x]       = θ_pix\n                        r2            = sx^2 + sy^2\n                        logr[y, x]    = 0.5*log2(max(1,r2))\n                    end\n                end\n            end\n            angmask = findall(anggood)\n        # -------- compute the wavelet in the Fourier domain\n        # -------- the angular factor is the same for all j\n            F_angular = norm .* cos.((θ[angmask].-π).*(L/(2*wd*pc)))\n\n        # -------- loop over j for the radial part\n        #    for (j_ind, j) in enumerate(1/c:1/c:im_scale-2)\n            for j_ind = 1:J\n                j = j_ind/c\n                j_value[j_ind] = j  # store for later\n                jrad  = im_scale-j-1\n                Δj    = abs.(logr[angmask].-jrad)\n                rmask = (Δj .<= 1/c)\n\n        # -------- radial part\n                F_radial = cos.(Δj[rmask] .* (c*π/2))\n                ind      = angmask[rmask]\n        #      Let's have these be (J,L) if you reshape...\n        #        f_ind    = (j_ind-1)*L+l+1\n                f_ind    = j_ind + l*J\n                filt[ind, f_ind] = F_radial .* F_angular[rmask]\n                psi_index[j_ind,l+1] = f_ind\n            end\n        end\n\n        # -------- phi contains power near k=0 not yet accounted for\n        filter_power = (sum(filt.*filt, dims=3))[:,:,1]\n\n        # -------- for plane half-covered (pc=1), add other half-plane\n        if pc == 1\n            filter_power .+= circshift(filter_power[end:-1:1,end:-1:1],(1,1))\n        end\n\n        # -------- compute power required to sum to 1.0\n        i0 = round(Int16,nx/2-2)\n        i1 = round(Int16,nx/2+4)\n        center_power = 1.0 .- fftshift(filter_power)[i0:i1,i0:i1]\n        zind = findall(center_power .< 1E-15)\n        center_power[zind] .= 0.0  # set small numbers to zero\n        phi_cen = zeros(nx, nx)\n        phi_cen[i0:i1,i0:i1] = sqrt.(center_power)\n\n        # -------- before adding ϕ to filter bank, renormalize ψ if pc=1\n        if pc==1 filt .*= sqrt(2.0) end  # double power for half coverage\n\n        # -------- add result to filter array\n        phi_index  = J*L+1\n        filt[:,:,phi_index] .= fftshift(phi_cen)\n\n        # -------- metadata dictionary\n        info=Dict()\n        info[\"npix\"]         = nx\n        info[\"j_value\"]      = j_value\n        info[\"theta_value\"]  = theta\n        info[\"psi_index\"]    = psi_index\n        info[\"phi_index\"]    = phi_index\n        info[\"pc\"]           = pc\n        info[\"wd\"]           = wd\n\n        return filt, info\n    end\n\n\n    ## Make a list of non-zero pixels for the (Fourier plane) filters\n    function fink_filter_list(filt)\n        (ny,nx,Nf) = size(filt)\n\n        # Allocate output arrays\n        filtind = fill(CartesianIndex{2}[], Nf)\n        filtval = fill(Float64[], Nf)\n\n        # Loop over filters and record non-zero values\n        for l=1:Nf\n            f = @view filt[:,:,l]\n            ind = findall(f .> 1E-13)\n            val = f[ind]\n            filtind[l] = ind\n            filtval[l] = val\n        end\n        return [filtind, filtval]\n    end\n\n\n    function fink_filter_hash(c, L; nx=256, wd=1, pc=1, shift=false)\n        # -------- compute the filter bank\n        filt, hash = fink_filter_bank(c, L; nx=nx, wd=wd, pc=pc, shift=shift)\n\n        # -------- list of non-zero pixels\n        flist = fink_filter_list(filt)\n\n        # -------- pack everything you need into the info structure\n        hash[\"filt_index\"] = flist[1]\n        hash[\"filt_value\"] = flist[2]\n        return hash\n    end\n\n\n    function DHC_compute(image::Array{Float64,2}, filter_hash, filter_hash2)\n        # Use 2 threads for FFT\n        FFTW.set_num_threads(2)\n\n        # array sizes\n        (Nx, Ny)  = size(image)\n        (Nf, )    = size(filter_hash[\"filt_index\"])\n\n        # allocate coeff arrays\n        out_coeff = []\n        S0  = zeros(Float64, 2)\n        S1  = zeros(Float64, Nf)\n        S20 = zeros(Float64, Nf, Nf)\n        S12 = zeros(Float64, Nf, Nf)\n        S2  = zeros(Float64, Nf, Nf)  # traditional 2nd order\n\n        # allocate image arrays for internal use\n        im_fdf_0_1 = zeros(Float64,           Nx, Ny, Nf)   # this must be zeroed!\n        im_rd_0_1  = Array{Float64, 3}(undef, Nx, Ny, Nf)\n\n        ## 0th Order\n        S0[1]   = mean(image)\n        norm_im = image.-S0[1]\n        S0[2]   = sum(norm_im .* norm_im)/(Nx*Ny)\n        norm_im ./= sqrt(Nx*Ny*S0[2])\n\n        append!(out_coeff,S0[:])\n\n        ## 1st Order\n        im_fd_0 = fft(norm_im)  # total power=1.0\n\n        # unpack filter_hash\n        f_ind   = filter_hash[\"filt_index\"]  # (J, L) array of filters represented as index value pairs\n        f_val   = filter_hash[\"filt_value\"]\n\n        f_ind2   = filter_hash2[\"filt_index\"]  # (J, L) array of filters represented as index value pairs\n        f_val2   = filter_hash2[\"filt_value\"]\n\n        zarr = zeros(ComplexF64, Nx, Ny)  # temporary array to fill with zvals\n\n        # make a FFTW \"plan\" for an array of the given size and type\n        P   = plan_ifft(im_fd_0)   # P is an operator, P*im is ifft(im)\n\n        ## Main 1st Order and Precompute 2nd Order\n        for f = 1:Nf\n            S1tot = 0.0\n            f_i = f_ind[f]  # CartesianIndex list for filter\n            f_v = f_val[f]  # Values for f_i\n            # for (ind, val) in zip(f_i, f_v)   # this is slower!\n            if length(f_i) > 0\n                for i = 1:length(f_i)\n                    ind       = f_i[i]\n                    zval      = f_v[i] * im_fd_0[ind]\n                    S1tot    += abs2(zval)\n                    zarr[ind] = zval\n                    im_fdf_0_1[ind,f] = abs(zval)\n                end\n                S1[f] = S1tot/(Nx*Ny)  # image power\n                im_rd_0_1[:,:,f] .= abs2.(P*zarr)\n                zarr[f_i] .= 0\n            end\n        end\n        append!(out_coeff, S1[:])\n\n        # we stored the abs()^2, so take sqrt (this is faster to do all at once)\n        im_rd_0_1 .= sqrt.(im_rd_0_1)\n\n        ## 2nd Order\n        #Amat = reshape(im_fdf_0_1, Nx*Ny, Nf)\n        #S12  = Amat' * Amat\n        #Amat = reshape(im_rd_0_1, Nx*Ny, Nf)\n        #S20  = Amat' * Amat\n\n        #append!(out_coeff, S20)\n        #append!(out_coeff, S12)\n\n        ## Traditional second order\n        for f1 = 1:Nf\n            thisim = fft(im_rd_0_1[:,:,f1])  # Could try rfft here\n            # println(\"  f1\",f1,\"  sum(fft):\",sum(abs2.(thisim))/Nx^2, \"  sum(im): \",sum(abs2.(im_rd_0_1[:,:,f1])))\n            # Loop over f2 and do second-order convolution\n            for f2 = 1:Nf\n                f_i = f_ind2[f2]  # CartesianIndex list for filter\n                f_v = f_val2[f2]  # Values for f_i\n                # sum im^2 = sum(|fft|^2/npix)\n                S2[f1,f2] = sum(abs2.(f_v .* thisim[f_i]))/(Nx*Ny)\n            end\n        end\n        append!(out_coeff, S2)\n\n        return out_coeff\n    end\n\nend # of module\n", "meta": {"hexsha": "02c7cc0e23f0d2e31d6fbab9d4c2ea048e25509b", "size": 8739, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scratch_JRY/copy_from_cannon-2021_02_05/DHC_2DUtils.jl", "max_stars_repo_name": "andrew-saydjari/DHC", "max_stars_repo_head_hexsha": "4c544fd2f381f43ee02c6465a563d288b9e5a2a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-02-23T04:59:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T16:52:05.000Z", "max_issues_repo_path": "from_cannon/2021_01_23/DHC_2DUtils.jl", "max_issues_repo_name": "andrew-saydjari/DHC", "max_issues_repo_head_hexsha": "4c544fd2f381f43ee02c6465a563d288b9e5a2a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-02-28T14:00:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-08T15:15:45.000Z", "max_forks_repo_path": "scratch_JRY/copy_from_cannon-2021_02_05/DHC_2DUtils.jl", "max_forks_repo_name": "andrew-saydjari/DHC", "max_forks_repo_head_hexsha": "4c544fd2f381f43ee02c6465a563d288b9e5a2a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8720930233, "max_line_length": 115, "alphanum_fraction": 0.4934202998, "num_tokens": 2630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642554, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7662396199170787}}
{"text": "#=\njinc.jl\n=#\n\nexport jinc\n\nusing SpecialFunctions: besselj1 # grab bessel function\n\n\n\"\"\"\n    jinc(x)\n\nReturn `jinc(x) = J1(pi*x)/(2x)`,\nwhere `J1` is a Bessel function of the first kind.\n\nUnits of `x` are typically cycles/m.\n\nReturn type is `promote_type(typeof(x), Float32)`.\n\"\"\"\nfunction jinc(x::Real)\n    T = promote_type(typeof(x), Float32)\n    if (x == 0) return convert(T, pi/4) end\n    y = abs(x)\n    convert(T, besselj1(pi*y) / (2*y))\nend\n", "meta": {"hexsha": "55232e0d5586ffbaafe8b719a908ca8b720956d4", "size": 448, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utility/jinc.jl", "max_stars_repo_name": "jamesthesnake/MIRT.jl", "max_stars_repo_head_hexsha": "3a4b1e33a35e2ab062f532a22866bfb11f6e5cd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utility/jinc.jl", "max_issues_repo_name": "jamesthesnake/MIRT.jl", "max_issues_repo_head_hexsha": "3a4b1e33a35e2ab062f532a22866bfb11f6e5cd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utility/jinc.jl", "max_forks_repo_name": "jamesthesnake/MIRT.jl", "max_forks_repo_head_hexsha": "3a4b1e33a35e2ab062f532a22866bfb11f6e5cd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.2307692308, "max_line_length": 55, "alphanum_fraction": 0.6383928571, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7662036317954983}}
{"text": "import Base: gcd, lcm\n\n\nfunction gcd(a::SimplePolynomial, b::SimplePolynomial)\n    #try\n    d = integerize(_gcd(a, b))\n    return d\n    # catch\n    #     aa = big(a)\n    #     bb = big(b)\n    #     dd = _gcd(aa,bb)\n    #     d = integerize(dd)\n    #     return d\n    # end\nend\n\nfunction _gcd(a::SimplePolynomial, b::SimplePolynomial)\n\n    if a == 0 && b == 0\n        error(\"The two arguments cannot both be zero\")\n    end\n\n    if a == 0\n        return b\n    end\n\n    if b == 0\n        return a\n    end\n\n    q, r = divrem(a, b)\n    return monic(_gcd(b, monic(r)))\nend\n\n\nfunction lcm(a::SimplePolynomial, b::SimplePolynomial)\n    q, r = divrem(a * b, gcd(a, b))\n    return monic(q)\nend\n", "meta": {"hexsha": "63a88098fea10d2a534d6aca976b2976d073a054", "size": 684, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gcd.jl", "max_stars_repo_name": "scheinerman/SimplePolynomials.jl", "max_stars_repo_head_hexsha": "8de234b81907807859704bff650a5b067e73de2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-13T02:38:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T02:38:17.000Z", "max_issues_repo_path": "src/gcd.jl", "max_issues_repo_name": "scheinerman/SimplePolynomials.jl", "max_issues_repo_head_hexsha": "8de234b81907807859704bff650a5b067e73de2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-08-09T16:40:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-09T16:40:24.000Z", "max_forks_repo_path": "src/gcd.jl", "max_forks_repo_name": "scheinerman/SimplePolynomials.jl", "max_forks_repo_head_hexsha": "8de234b81907807859704bff650a5b067e73de2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-08-09T15:19:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T01:13:08.000Z", "avg_line_length": 17.1, "max_line_length": 55, "alphanum_fraction": 0.5409356725, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7661725853843027}}
{"text": "function cholesky(mat::Matrix)\n    # if the matrix is no a square matrix, return one with zeros\n    if size(mat, 1) != size(mat, 2)\n        return zeros(size(mat, 1), size(mat, 1))\n    end\n    # since verifing that the matrix is positive definite is so\n    # time-consuming, the step is skipped\n    # it's assumed that the matrix has $n$ rows and columns\n    n = size(mat, 1)\n    # $L$ is the matrix to be returned\n    L = zeros(n, n)\n    # the formula is proved by induction, basically\n    for itr1 in 1 : n, itr2 in itr1 : n\n        if itr2 == itr1\n            L[itr2, itr1] = mat[itr2, itr1]\n            for itr3 in 1 : (itr1 - 1)\n                L[itr2, itr1] -= L[itr2, itr3] ^ 2\n            end\n            L[itr2, itr1] = sqrt(L[itr2, itr1])\n        else\n            L[itr2, itr1] = mat[itr2, itr1]\n            for itr3 in 1 : (itr1 - 1)\n                L[itr2, itr1] -= L[itr2, itr3] * L[itr1, itr3]\n            end\n            L[itr2, itr1] /= L[itr1, itr1]\n        end\n    end\n    return L\nend", "meta": {"hexsha": "3ffb6c50aadaf39a3f0e650caa046ca9d1043133", "size": 1003, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear-algebra/cholesky.jl", "max_stars_repo_name": "Shimushushushu/Etude-Rhapsody", "max_stars_repo_head_hexsha": "cdca63ca92a44f0f31e716cf4acd3e0de17c9181", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear-algebra/cholesky.jl", "max_issues_repo_name": "Shimushushushu/Etude-Rhapsody", "max_issues_repo_head_hexsha": "cdca63ca92a44f0f31e716cf4acd3e0de17c9181", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear-algebra/cholesky.jl", "max_forks_repo_name": "Shimushushushu/Etude-Rhapsody", "max_forks_repo_head_hexsha": "cdca63ca92a44f0f31e716cf4acd3e0de17c9181", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5862068966, "max_line_length": 64, "alphanum_fraction": 0.5284147557, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7661725818328277}}
{"text": "using RHEOS\nusing BenchmarkTools\nusing InverseLaplace\nimport MittagLeffler\nusing FunctionWrappers: FunctionWrapper\n\nt=RheoFloat.(0.0:0.001:1.0);\nt0=1.0\n\nprintln(\"=========================\")\nprintln(\"Test on maths functions \")\nprintln(\"=========================\")\n\nprintln()\nprintln(\"Test on the MittalgLeffler function\")\nprintln()\nprintln(\"Version from Julia repo\")\n@btime MittagLeffler.mittleff(0.5, t0)\nprintln(\"Version from RHEOS (should be the same as above)\")\n@btime RHEOS.mittleff(0.5, t0)\n\nprintln()\nprintln()\n\nprintln()\nprintln(\"Test on the inverse Laplace transform\")\nprintln()\ncₐ = 1.0; a=0.5; kᵦ = 2.0; kᵧ=3.0\nprintln(\"Talbot algorithm on FractSLS_Zener creep function\")\nĴ(s) = (1/s)*(cₐ*s^a + kᵦ)/(cₐ*s^a*kᵦ + kᵧ*(cₐ*s^a + kᵦ))\nprint(\"  scalar value: \")\n@btime InverseLaplace.talbot(s->(1/s)*(cₐ*s^a + kᵦ)/(cₐ*s^a*kᵦ + kᵧ*(cₐ*s^a + kᵦ)), t0)\nprint(\"  vector using talbot.: \")\n@btime InverseLaplace.talbot.(s->(1/s)*(cₐ*s^a + kᵦ)/(cₐ*s^a*kᵦ + kᵧ*(cₐ*s^a + kᵦ)), t)\nprint(\"  vector using talbotarr: \")\n@btime InverseLaplace.talbotarr(s -> Ĵ(s), t)\nprintln()\n\nprintln(\"Weeks (80) algorithm on FractSLS_Zener creep function\")\nprint(\"  Initialisation: \")\n@btime InverseLaplace.Weeks(Ĵ,80)\nft = InverseLaplace.Weeks(Ĵ,80)\nprint(\"  Scalar value: \")\n@btime ft(t0)\nprint(\"  Vector values: \")\n@btime ft.(t)\nprintln()\nprintln()\n\nprintln(\"=========================\")\nprintln(\"Test on Moduli functions \")\nprintln(\"=========================\")\n\nprintln()\nprintln(\"Test on the Maxwell model\")\nprintln()\n@btime relaxmod(Maxwell, t0, [2.0,3.0])\n@btime relaxmod(Maxwell, t, [2.0,3.0]);\n\nm = RheoModel(Maxwell,  (η=2.0, k=3.0))\n@btime relaxmod(m, t0)\n@btime relaxmod(m, t);\n\n\nprintln()\nprintln(\"Test on the FractSLS_Zener model relaxation modulus - with mittleff\")\nprintln()\ncₐ = 1.0; a=0.5; kᵦ = 2.0; kᵧ=3.0\nprintln(\"Direct function evaluation\")\n@btime kᵦ*MittagLeffler.mittleff(a, -(kᵦ/cₐ)*t0^a) + kᵧ\n@btime kᵦ.*MittagLeffler.mittleff.(a, -(kᵦ./cₐ).*t.^a) .+ kᵧ;\nprintln(\"From the RheoModelClass\")\n@btime relaxmod(FractSLS_Zener, t0, [1.0,0.5,2.0,3.0])\n@btime relaxmod(FractSLS_Zener, t, [1.0,0.5,2.0,3.0])\nm = RheoModel(FractSLS_Zener,  (cₐ = 1.0, a=0.5, kᵦ = 2.0, kᵧ=3.0))\nprintln(\"From the RheoModel\")\n@btime relaxmod(m, t0)\n@btime relaxmod(m, t)\n\nprintln()\nprintln(\"Test on the FractSLS_Zener model creep compliance - with inverse laplace\")\nprintln()\n\nfwp = ((t,p)->(InverseLaplace.Weeks(s->(1/s)*(p[1]*s^p[2] + p[3])/(p[1]*s^p[2]*p[3] + p[4]*(p[1]*s^p[2] + p[3])),80))(t)) |> FunctionWrapper{RheoFloat,Tuple{RheoFloat,Vector{RheoFloat}}}\nfwpa = ((t,p)->(InverseLaplace.Weeks(s->(1/s)*(p[1]*s^p[2] + p[3])/(p[1]*s^p[2]*p[3] + p[4]*(p[1]*s^p[2] + p[3])),80)).(t)) |> FunctionWrapper{Vector{RheoFloat},Tuple{Vector{RheoFloat},Vector{RheoFloat}}}\nfw = InverseLaplace.Weeks(s->(1/s)*(1.0*s^0.5 + 2.0)/(1.0*s^0.5*2.0 + 3.0*(1.0*s^0.5 + 2.0)),80) |> FunctionWrapper{RheoFloat,Tuple{RheoFloat}}\nfwa = t->fw.(t) |> FunctionWrapper{Vector{RheoFloat},Tuple{Vector{RheoFloat}}}\nprintln()\nprintln(\"function wrappers using Weeks\")\n@btime fwp(t0,[1.0,0.5,2.0,3.0])\n@btime fwpa(t,[1.0,0.5,2.0,3.0])\n@btime fw(t0)\n@btime fwa(t)\n\nprintln()\nprintln(\"From the RheoModelClass\")\n@btime creepcomp(FractSLS_Zener, t0, [1.0,0.5,2.0,3.0])\n@btime creepcomp(FractSLS_Zener, t, [1.0,0.5,2.0,3.0])\nm = RheoModel(FractSLS_Zener,  (cₐ = 1.0, a=0.5, kᵦ = 2.0, kᵧ=3.0))\nprintln(\"From the RheoModel\")\n@btime creepcomp(m, t0)\n@btime creepcomp(m, t)\nnothing\n\n\n\n\n#=\n\nHardware:\nIntel Core i5-7200U Processor (3MB Cache, up to 3.1Ghz)\n8GB LPDDR3 1866\n\n=========================\nTest on maths functions \n=========================\n\nTest on the MittalgLeffler function\n\nVersion from Julia repo\n  57.567 ns (1 allocation: 16 bytes)\nVersion from RHEOS (should be the same as above)\n  58.195 ns (1 allocation: 16 bytes)\n\n\n\nTest on the inverse Laplace transform\n\nTalbot algorithm on FractSLS_Zener creep function\n  scalar value:   21.206 μs (642 allocations: 18.75 KiB)\n  vector using talbot.:   21.383 ms (642143 allocations: 18.33 MiB)\n  vector using talbotarr:   3.418 ms (173413 allocations: 3.61 MiB)\n\nWeeks (80) algorithm on FractSLS_Zener creep function\n  Initialisation:   105.563 μs (2634 allocations: 110.75 KiB)\n  Scalar value:   1.616 μs (1 allocation: 16 bytes)\n  Vector values:   1.596 ms (2 allocations: 8.03 KiB)\n\n\n=========================\nTest on Moduli functions \n=========================\n\nTest on the Maxwell model\n\n  67.185 ns (2 allocations: 112 bytes)\n  7.559 μs (2 allocations: 8.09 KiB)\n  33.592 ns (1 allocation: 16 bytes)\n  8.153 μs (1 allocation: 8.00 KiB)\n\nTest on the FractSLS_Zener model relaxation modulus - with mittleff\n\nDirect function evaluation\n  207.000 ns (7 allocations: 112 bytes)\n  68.707 μs (15 allocations: 8.53 KiB)\nFrom the RheoModelClass\n  166.950 ns (4 allocations: 160 bytes)\n  64.459 μs (2 allocations: 8.11 KiB)\nFrom the RheoModel\n  104.457 ns (1 allocation: 16 bytes)\n  59.557 μs (1 allocation: 8.00 KiB)\n\nTest on the FractSLS_Zener model creep compliance - with inverse laplace\n\n\nfunction wrappers using Weeks\n  62.121 μs (71 allocations: 30.80 KiB)\n  1.660 ms (72 allocations: 38.81 KiB)\n  1.636 μs (1 allocation: 16 bytes)\n  1.610 ms (5 allocations: 8.12 KiB)\n\nFrom the RheoModelClass\n  10.674 μs (101 allocations: 2.64 KiB)\n  10.721 ms (99102 allocations: 2.47 MiB)\nFrom the RheoModel\n  9.535 μs (1 allocation: 16 bytes)\n  9.580 ms (1 allocation: 8.00 KiB)\n\n=#\n", "meta": {"hexsha": "0ade1569b5c6231a39ff89cb698e83ddec04f43e", "size": 5374, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/benchmarks.jl", "max_stars_repo_name": "moustachio-belvedere/RHEOS.jl", "max_stars_repo_head_hexsha": "b0dc226d09b941ae39fe329b566fe2e39fd9a8d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-08-08T16:01:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T11:02:00.000Z", "max_issues_repo_path": "test/benchmarks.jl", "max_issues_repo_name": "rheos-cambridge/RHEOS.jl", "max_issues_repo_head_hexsha": "b0dc226d09b941ae39fe329b566fe2e39fd9a8d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122, "max_issues_repo_issues_event_min_datetime": "2018-08-10T08:55:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-15T22:12:03.000Z", "max_forks_repo_path": "test/benchmarks.jl", "max_forks_repo_name": "rheos-cambridge/RHEOS.jl", "max_forks_repo_head_hexsha": "b0dc226d09b941ae39fe329b566fe2e39fd9a8d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-06-19T12:00:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T12:24:54.000Z", "avg_line_length": 29.8555555556, "max_line_length": 204, "alphanum_fraction": 0.6631931522, "num_tokens": 2144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.7661329216762798}}
{"text": "\nfunction prompt()\n    println(\"Please enter length of short side A if possible, if not leave blank\")\n    a = readline()\n    println(\"Please enter length of short side B if possible, if not leave blank\")\n    b = readline()\n    println(\"Please enter length of Hypotinous C if possible, if not leave blank\")\n    c = readline()\n\n    all_val = a,b,c\n\n    all_val = [all_val[i] == \"\" ?  missing : all_val[i] for i in 1:length(all_val)]\n\n    if sum(x -> ismissing(x), all_val) == 1\n        nothing\n    else\n        println(\"Error: too many or too few missing values.\")\n    end\n\n    all_v = []\n    for i in 1:size(all_val,1)\n        if  ismissing(all_val[i])\n            push!(all_v, missing)\n        else\n            push!(all_v, parse(Float64,all_val[i]) )\n        end\n    end\n\n    return all_v\n\nend\n\nall_v = prompt()\n\nfunction Pythag(inp::Array{Any,1})\n    if ismissing(inp[3])\n        result = sqrt(inp[1]^2 + inp[2]^2)\n    else\n        vals = collect(skipmissing(inp))\n        result = sqrt( vals[2]^2 - vals[1]^2 )\n    end\n    return result\nend\n\nprintln(\"The length of the missing side is: $(Pythag(all_v))\")\n", "meta": {"hexsha": "3696069e4a90dc94ece5505554decc8704c37fce", "size": 1108, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Pythagorean.jl", "max_stars_repo_name": "atott/Pythagoras_Julia", "max_stars_repo_head_hexsha": "14e15aaf62568a5260a47183ea7343138a403991", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Pythagorean.jl", "max_issues_repo_name": "atott/Pythagoras_Julia", "max_issues_repo_head_hexsha": "14e15aaf62568a5260a47183ea7343138a403991", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Pythagorean.jl", "max_forks_repo_name": "atott/Pythagoras_Julia", "max_forks_repo_head_hexsha": "14e15aaf62568a5260a47183ea7343138a403991", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0869565217, "max_line_length": 83, "alphanum_fraction": 0.5965703971, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145365, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7661329182272051}}
{"text": "function mahalanobisSquaredBetweenPairs(pairs::Matrix; covmatrix=nothing)\n    n, p = size(pairs)\n    newmat = zeros(Float64, n, n)\n    if covmatrix === nothing\n        covmatrix = cov(pairs)\n    end\n    try\n        invm = inv(covmatrix)\n        for i in 1:n\n            @inbounds for j in i:n\n                newmat[i, j] = ((pairs[i,:] .- pairs[j,:])' * invm * (pairs[i,:] .- pairs[j,:]))\n                newmat[j, i] = newmat[i,j]\n            end\n        end\n        return newmat\n    catch e\n        @warn e\n        if det(covmatrix) == 0\n            @warn \"singular covariance matrix, mahalanobis distances can not be calculated\"\n        end\n        return zeros(Float64, (n, n))\n    end\nend\n\n\n\"\"\"\n\n    asm2000(setting)\n\nPerform the Setan, Halim and Mohd (2000) algorithm for the given regression setting.\n\n# Arguments\n- `setting::RegressionSetting`: RegressionSetting object with a formula and dataset.\n\n# Examples\n```julia-repl\njulia> reg0001 = createRegressionSetting(@formula(calls ~ year), phones);\njulia> asm2000(reg0001)\nDict{Any,Any} with 1 entry:\n  \"outliers\" => [15, 16, 17, 18, 19, 20]\n```\n\n# References\nSetan, Halim, and Mohd Nor Mohamad. \"Identifying multiple outliers in \nlinear regression: Robust fit and clustering approach.\" (2000).\n\"\"\"\nfunction asm2000(setting::RegressionSetting)\n    X = designMatrix(setting)\n    y = responseVector(setting)\n    return asm2000(X, y)\nend\n\n\nfunction asm2000(X::Array{Float64,2}, y::Array{Float64,1})\n    n, p = size(X)\n    h = floor((n + p - 1) / 2)\n    ltsreg = lts(X, y)\n    \n    betas = ltsreg[\"betas\"]\n    hsubset = ltsreg[\"hsubset\"]\n\n    predicteds = [sum(X[i,:] .* betas) for i in 1:n]\n    resids = y .- predicteds\n    stdres = standardize(ZScoreTransform, resids, dims=1)\n    stdfit = standardize(ZScoreTransform, predicteds, dims=1)\n    pairs = hcat(stdfit, stdres)\n\n    pairs = hcat(resids, predicteds)\n\n    covmatrix = cov(pairs[hsubset, :])\n    mahdist = mahalanobisSquaredBetweenPairs(pairs, covmatrix=covmatrix)\n\n    outlierset = Array{Int,1}()\n\n    hcl = hclust(mahdist, linkage=:single)\n    majonacrit = majona(hcl)\n    clustermappings = cutree(hcl, h=majonacrit)\n    uniquemappings = unique(clustermappings)\n    for clustid in uniquemappings\n        cnt = count(x -> x == clustid, clustermappings)\n        if cnt >= h \n            outlierset = filter(i -> clustermappings[i] != clustid, 1:n)\n        end\n    end\n    \n    result = Dict()\n    result[\"outliers\"] = outlierset\n    return result\nend", "meta": {"hexsha": "25773e6473fe5bb9828c9e8e5dacacaea6d7cdd5", "size": 2465, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/asm2000.jl", "max_stars_repo_name": "akadal/LinRegOutliers", "max_stars_repo_head_hexsha": "86bcb5ffb61ddc40b162b30c782d9f6799de64ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/asm2000.jl", "max_issues_repo_name": "akadal/LinRegOutliers", "max_issues_repo_head_hexsha": "86bcb5ffb61ddc40b162b30c782d9f6799de64ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/asm2000.jl", "max_forks_repo_name": "akadal/LinRegOutliers", "max_forks_repo_head_hexsha": "86bcb5ffb61ddc40b162b30c782d9f6799de64ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6966292135, "max_line_length": 96, "alphanum_fraction": 0.6271805274, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506726044381, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7661329144435687}}
{"text": "# calculate required particle num for kld sampling\n# by wilson-hilferty transformation\n\nmodule ParticleNumWh\n  using Distributions\n\n  function num(epsilon, delta, bin_num)\n    return ceil(quantile(Chisq(bin_num-1), 1-delta)/(2*epsilon))\n  end\n\n  function num_wh(epsilon, delta, bin_num)\n    dof = bin_num - 1\n    z = quantile(Normal(), 1 - delta)\n    return ceil(dof/(2*epsilon)*(1-2/(9*dof)+sqrt(2/(9*dof))*z)^3)\n  end\n\n  function main()\n    bins = [2, 4, 8, 1000, 10000, 100000]\n    for bin in bins\n      println(\"bin:$(bin), ϵ=0.1, δ=0.01, chisq=$(num(0.1, 0.01, bin)), norm=$(num_wh(0.1, 0.01, bin))\")\n      println(\"bin:$(bin), ϵ=0.5, δ=0.01, chisq=$(num(0.5, 0.01, bin)), norm=$(num_wh(0.5, 0.01, bin))\")\n      println(\"bin:$(bin), ϵ=0.5, δ=0.05, chisq=$(num(0.5, 0.05, bin)), norm=$(num_wh(0.5, 0.05, bin))\")\n    end\n  end\nend", "meta": {"hexsha": "e304bbaea4292b9050f99c95e19dd3d692d82485", "size": 833, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/localization/particle_filter/kld_sampling/particle_num_wh.jl", "max_stars_repo_name": "ShisatoYano/JuliaAutonomy", "max_stars_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2021-03-10T12:43:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T16:40:19.000Z", "max_issues_repo_path": "src/localization/particle_filter/kld_sampling/particle_num_wh.jl", "max_issues_repo_name": "ShisatoYano/JuliaAutonomy", "max_issues_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/localization/particle_filter/kld_sampling/particle_num_wh.jl", "max_forks_repo_name": "ShisatoYano/JuliaAutonomy", "max_forks_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-14T02:46:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T09:19:40.000Z", "avg_line_length": 33.32, "max_line_length": 104, "alphanum_fraction": 0.612244898, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067276593032, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7661329114835715}}
{"text": "# mathematical constants related to statistics\n\n@irrational loghalf -0.6931471805599453094 log(big(0.5))\n@irrational logtwo 0.6931471805599453094 log(big(2.))\n@irrational logπ   1.1447298858494001741 log(big(π))\n@irrational log2π  1.8378770664093454836 log(big(2.)*π)\n@irrational log4π  2.5310242469692907930 log(big(4.)*π)\n", "meta": {"hexsha": "a9476cf3707e164f444abe5a9823c76539641b71", "size": 324, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/constants.jl", "max_stars_repo_name": "bdeonovic/LogExpFunctions.jl", "max_stars_repo_head_hexsha": "ef64ba52a4ac20fe29606f62016c63e3fd707184", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/constants.jl", "max_issues_repo_name": "bdeonovic/LogExpFunctions.jl", "max_issues_repo_head_hexsha": "ef64ba52a4ac20fe29606f62016c63e3fd707184", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/constants.jl", "max_forks_repo_name": "bdeonovic/LogExpFunctions.jl", "max_forks_repo_head_hexsha": "ef64ba52a4ac20fe29606f62016c63e3fd707184", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5, "max_line_length": 56, "alphanum_fraction": 0.787037037, "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7661329113290556}}
{"text": "\n\nfunction getCoefficientsSymplecticEulerForward()\n    a = [[0.0 0.0]\n         [1.0 0.0]]\n    b = [1.0, 0.0]\n    c = [0.0, 1.0]\n\n    o = 1\n\n    CoefficientsRK(:symplectic_euler_forward, o, a, b, c)\nend\n\nfunction getCoefficientsSymplecticEulerBackward()\n    a = [[0.0 0.0]\n         [0.0 1.0]]\n    b = [0.0, 1.0]\n    c = [0.0, 1.0]\n\n    o = 1\n\n    CoefficientsRK(:symplectic_euler_backward, o, a, b, c)\nend\n\n\"Tableau for symplectic Euler-A method\"\nfunction getTableauSymplecticEulerA()\n    TableauEPRK(:symplectic_euler_a, 1, getCoefficientsSymplecticEulerForward(), getCoefficientsSymplecticEulerBackward())\nend\n\n\"Tableau for symplectic Euler-B method\"\nfunction getTableauSymplecticEulerB()\n    TableauEPRK(:symplectic_euler_b, 1, getCoefficientsSymplecticEulerBackward(), getCoefficientsSymplecticEulerForward())\nend\n\n\n\"Tableau for Gauss-Lobatto IIIAIIIB method with s=2 stages\"\nfunction getTableauLobattoIIIAIIIB2()\n    TableauEPRK(:lobatto_IIIA_IIIB_2, 2, getCoefficientsLobIIIA2(), getCoefficientsLobIIIB2())\nend\n\n\n\"Tableau for Gauss-Lobatto IIIBIIIA method with s=2 stages\"\nfunction getTableauLobattoIIIBIIIA2()\n    TableauEPRK(:lobatto_IIIB_IIIA_2, 2, getCoefficientsLobIIIB2(), getCoefficientsLobIIIA2())\nend\n\n", "meta": {"hexsha": "c706e0b502eace7a359a8d931b2b6a6f1d6b8399", "size": 1216, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tableaus/tableaus_eprk.jl", "max_stars_repo_name": "krystophny/GeometricIntegrators.jl", "max_stars_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-04T11:52:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T11:52:47.000Z", "max_issues_repo_path": "src/tableaus/tableaus_eprk.jl", "max_issues_repo_name": "krystophny/GeometricIntegrators.jl", "max_issues_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tableaus/tableaus_eprk.jl", "max_forks_repo_name": "krystophny/GeometricIntegrators.jl", "max_forks_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8723404255, "max_line_length": 122, "alphanum_fraction": 0.7368421053, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996141, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7661329062327015}}
{"text": "# Linear fractional transformation \"LFT\"\n\nmodule LinearFractionalTransformations\n\nimport Base.inv, Base.isequal, Base.show, Base.hash\nimport Base.==, Base.*, Base.getindex\nexport LFT, isequal, call\n\n\nconst complex_infinity = Inf + Inf * im\n\n\nstruct LFT\n    M::Array{Complex{Float64},2}\n    function LFT(a, b, c, d)\n        if isinf(a) || isinf(b) || isinf(c) || isinf(d)\n            error(\"Arguments must be finite: \" * string((a, b, c, d)))\n        end\n\n        if a * d - b * c == 0\n            error(\"Singularity detected: \" * string((a, b, c, d)))\n        end\n\n        new([a b; c d])\n    end\nend\n\n\"\"\"\n    LFT\nA linear fractional transformation `f(z)=(a*z+b)/(c*z+d)` where `a,b,c,d` are complex numbers.\n\nConstructors:\n* `LFT(a,b,c,d)`: create the function described above.\n* `LFT()`: create the identity function `f(z) = z`. Equivalent to `LFT(1,0,0,1)`.\n* `LFT(a,b,c)`: create the function with `a ↦ 0`, `b ↦ 1`, and `c ↦ ∞`.\n* `LFT(a,aa,b,bb,c,cc)`: creates the function with `a ↦ aa`, `b ↦ bb`, and `c ↦ cc`.\n\"\"\"\nfunction LFT(M::Array)\n    return LFT(M[1, 1], M[1, 2], M[2, 1], M[2, 2])\nend\n\nfunction LFT()\n    return LFT(1, 0, 0, 1)\nend\n\n# a --> 0, b-->1, and c--> oo\nfunction LFT(a::Number, b::Number, c::Number)\n    if a == b || b == c || a == c\n        error(\"Three arguments must be distinct: \" * string((a, b, c)))\n    end\n\n    if isinf(a)\n        return LFT(0, b - c, 1, -c)\n    end\n\n    if isinf(b)\n        return LFT(1, -a, 1, -c)\n    end\n\n    if isinf(c)\n        return LFT(1, -a, 0, b - a)\n    end\n\n    # if all args are finite\n    aa = (b - c)\n    bb = (-a) * (b - c)\n    cc = (b - a)\n    dd = (-c) * (b - a)\n    return LFT(aa, bb, cc, dd)\nend\n\n# a-->aa, b-->bb, c-->cc\nfunction LFT(a::Number, aa::Number, b::Number, bb::Number, c::Number, cc::Number)\n    f = LFT(a, b, c)\n    g = LFT(aa, bb, cc)\n    return inv(g) * f\nend\n\n\n#### Equality checking ####\n\n# These need to be rewritten\n\nfunction isequal(f::LFT, g::LFT)\n    return f[0] == g[0] && f[1] == g[1] && f[Inf] == g[Inf]\n    # h = f * inv(g)\n    # I = h.M\n    # return I[1,1]==I[2,2] && I[1,2]==I[2,1]==0\nend\n\n==(f::LFT, g::LFT) = isequal(f, g)\n\n# Inverse transformation\nfunction inv(L::LFT)\n    a = L.M[1, 1]\n    b = L.M[1, 2]\n    c = L.M[2, 1]\n    d = L.M[2, 2]\n    return LFT(d, -b, -c, a)\nend\n\n# Composition\n*(A::LFT, B::LFT) = LFT(A.M * B.M)\n\n# Function application\nfunction getindex(A::LFT, x::Number)\n    if isinf(x)\n        a = A.M[1, 1]\n        b = A.M[2, 1]\n        if b == 0\n            return complex_infinity\n        end\n        return a / b\n    end\n    w = A.M * [x + 0im; 1.0 + 0im]\n    if w[2] == 0\n        return complex_infinity\n    end\n    return w[1] / w[2]\nend\n\n# call(A::LFT, x::Number) = A[x]\n\n(A::LFT)(x::Number) = A[x]\n\nfunction show(io::IO, L::LFT)\n    print(\n        io,\n        \"LFT( \",\n        L.M[1, 1],\n        \" , \",\n        L.M[1, 2],\n        \" , \",\n        L.M[2, 1],\n        \" , \",\n        L.M[2, 2],\n        \" )\",\n    )\nend\n\n\nfunction hash(f::LFT, h::UInt64 = UInt64(0))\n    z = 0.0 + 0.0 * im # kludge to make -0.0 and -0.0im into +versions\n    a = f[0] + z\n    b = f[1] + z\n    c = f[Inf] + z\n    return hash(a, hash(b, hash(c, h)))\nend\n\ninclude(\"projection.jl\")\n\nend # end of module \"LFTs\"\n", "meta": {"hexsha": "ab818cee0bff181548b5ba81f68c219dc496ebcc", "size": 3206, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LinearFractionalTransformations.jl", "max_stars_repo_name": "scheinerman/LinearFractionalTransformations.jl", "max_stars_repo_head_hexsha": "01181b1d0adaaf20fdd56865c04cc1eb29c63c0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LinearFractionalTransformations.jl", "max_issues_repo_name": "scheinerman/LinearFractionalTransformations.jl", "max_issues_repo_head_hexsha": "01181b1d0adaaf20fdd56865c04cc1eb29c63c0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LinearFractionalTransformations.jl", "max_forks_repo_name": "scheinerman/LinearFractionalTransformations.jl", "max_forks_repo_head_hexsha": "01181b1d0adaaf20fdd56865c04cc1eb29c63c0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.954248366, "max_line_length": 94, "alphanum_fraction": 0.5, "num_tokens": 1237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7661043760411019}}
{"text": "function factor(n)\n    answer = []\n    hw = []\n    for i in eratosphen(n)\n        if n%i == 0\n            push!(answer,i)\n            push!(hw,1)\n            n = n/i\n            while n%i == 0\n                hw[end] += 1\n                n = n/i\n            end\n        end\n    end\n    return answer,hw         \nend\n\nfunction eratosphen(n)\n    ser = fill(true,n)\n    ser[1] = false\n    k = 2\n    while k !== nothing && k<n \n        ser[k^2:k:end] .= false\n        k=findnext(ser, k+1)\n    end\n    return findall(ser)\nend", "meta": {"hexsha": "ca3327d3be303eef334556de5fb98683aae1672a", "size": 520, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "task_7_6.jl", "max_stars_repo_name": "Litger45/julia-algorithms-2", "max_stars_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "task_7_6.jl", "max_issues_repo_name": "Litger45/julia-algorithms-2", "max_issues_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "task_7_6.jl", "max_forks_repo_name": "Litger45/julia-algorithms-2", "max_forks_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2592592593, "max_line_length": 31, "alphanum_fraction": 0.4153846154, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7661043627650149}}
{"text": "#=\nStarting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:\n\n21 22 23 24 25\n20  7  8  9 10\n19  6  1  2 11\n18  5  4  3 12\n17 16 15 14 13\n\nIt can be verified that the sum of the numbers on the diagonals is 101.\n\nWhat is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?\n=#\n#=\nNotes:\n\n#[1],2,[3],4,[5],6,[7],8,[9],10,11,12,[13],14,15,16,[17],18,19,20,[21],22,23,24,[25]\n#1,3,5,7,9,13,17,21,25,31,37,43,49\n#2, 4, 6\n#3x3, 5x5, 7x7\n=#\nfunction calc()\n  total,start = 1,1\n  step = 2\n  iterations = 3\n  currentsquaresize = 3\n  while currentsquaresize <= 1001\n    start += step\n    for i in start:step:(start+(iterations*step))\n      total += i\n    end\n    start += (iterations*step)\n    currentsquaresize += 2\n    step += 2\n  end\n  total\nend\n@time println(calc())\n", "meta": {"hexsha": "3738bae077bf965caed14916374fa525d0724349", "size": 852, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p28.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p28.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p28.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 21.8461538462, "max_line_length": 113, "alphanum_fraction": 0.6396713615, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678382, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7661043622068144}}
{"text": "using Distributions, Plots; pyplot()\n\nL, K, n  = 500, [450, 400, 250, 100, 50], 30\nhyperDists = [Hypergeometric(k,L-k,n) for k in K]\nxGrid = 0:1:n\npmfs = [ pdf.(dist, xGrid) for dist in hyperDists ]\nlabels = \"Successes = \" .* string.(K)\n\nbar( xGrid, pmfs, \n\talpha=0.8, c=[:orange :purple :green :red :blue ],\n\tlabel=hcat(labels...), ylims=(0,0.25),\n\txlabel=\"x\", ylabel=\"Probability\", legend=:top)", "meta": {"hexsha": "96f76677b579430ed5eec0a69ef8c9a9389c1843", "size": 396, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/hypergeometric.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "3_chapter/hypergeometric.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "3_chapter/hypergeometric.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 33.0, "max_line_length": 51, "alphanum_fraction": 0.6363636364, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7661043603274768}}
{"text": "δ=0.10; ρ=0.15; # Param \nz= ρ + δ +.02     # Need: z > ρ + δ\nI_SS = (z-ρ-δ)/(ρ+δ)\nK_SS = I_SS/δ\n\nif 1==1\n    a_0(s;δ=δ) = δ*s\n    min_s = eps(); max_s = 10.0*K_SS; n_s = 800;\n    min_a = eps(); max_a = K_SS; n_a = 200;\n    \"states:\"\n    states = range(min_s, max_s, length=n_s)\n    ceil_state(s) = states[searchsortedfirst(states, s)]\n    \"actions:\" \n    valid_actions()  = range(min_a, max_a, length=n_a)        # possible actions any state.\n    valid_actions(s) = filter(>=(-(1-δ)*s), valid_actions())  # valid actions @ state=s \n    \"Transition:\" \n    μ(s,a;δ=δ)      = a +(1-δ)*s     \n    \"reward:\" \n    r(s,a;z=z) = z*s -a -0.5*(a^2)\n    \"discount:\"\n    β = 1/(1+ρ);\n    using QuickPOMDPs: QuickMDP           #QuickMDP()\n    using POMDPModelTools: Deterministic\n    m = QuickMDP(\n        states     = states,\n        actions    = valid_actions,\n        transition = (s, a) -> Deterministic( ceil_state( μ(s,a) ) ),\n        reward     = (s, a) -> r(s,a),\n        discount   = β\n    )\n    # DiscreteValueIteration: Both work fast! \n    using DiscreteValueIteration\n    s1 = DiscreteValueIteration.SparseValueIterationSolver()\n    s2 = DiscreteValueIteration.ValueIterationSolver()\n    @time sol1 = solve(s1, m) #\n    @time sol2 = solve(s2, m) #\n    # value(sol1, states[2]), action(sol1, states[2])\n    # value(sol2, states[2]), action(sol2, states[2])\n    value(sol1, states[end])\n\n    using Plots\n    # Value\n    plot(legend=:bottomright, title=\"Value Functions\");\n    #plot!(states[2:end], i->A0 + A1 * i, lab=\"closed form\") \n    plot!(states[2:end], i->value(sol1, i),   lab=\"sol1\")\n    plot!(states[2:end], i->value(sol2, i),   lab=\"sol2\")\n\n    # Simulation\n    Tsim=150; s0=0.5*K_SS; sim1 = []; push!(sim1, s0); \n    for tt in 1:Tsim\n        s = sim1[tt]\n        a = valid_actions()[sol1.policy[searchsortedfirst(states, s)]]\n        sp = μ(s,a) \n        sp = ceil_state(sp)\n        push!(sim1, sp)\n    end \n    \n    plot(legend=:bottomright, title=\"Simulation\");\n    #plot!(simcf,   lab=\"closed form\")\n    plot!(sim1,   lab=\"sol1\")\nend\n", "meta": {"hexsha": "006aa6cbf297bf0006c5fe39095d887986b0f6c3", "size": 2046, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "DiscreteTime_Deterministic_POMDPs.jl", "max_stars_repo_name": "azev77/4Quadrants", "max_stars_repo_head_hexsha": "6a14f29d89c54845fdd4f3469573c35ba6c229cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DiscreteTime_Deterministic_POMDPs.jl", "max_issues_repo_name": "azev77/4Quadrants", "max_issues_repo_head_hexsha": "6a14f29d89c54845fdd4f3469573c35ba6c229cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DiscreteTime_Deterministic_POMDPs.jl", "max_forks_repo_name": "azev77/4Quadrants", "max_forks_repo_head_hexsha": "6a14f29d89c54845fdd4f3469573c35ba6c229cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-31T00:01:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-31T00:01:13.000Z", "avg_line_length": 33.0, "max_line_length": 91, "alphanum_fraction": 0.5630498534, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140232, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.766104359211076}}
{"text": "\"\"\"\n    X = sylvckr(A,B,C)\n\nSolve the continuous Sylvester matrix equation\n\n                AX + XB = C\n\nusing the Kronecker product expansion of equations. `A` and `B` are\nsquare matrices, and `A` and `-B` must not have common eigenvalues.\nThis function is not recommended for large order matrices.\n\"\"\"\nfunction sylvckr(A, B, C)\n    m, n = size(C)\n    [m; n] == LinearAlgebra.checksquare(A, B) ||\n             throw(DimensionMismatch(\"A, B and Q have incompatible dimensions\"))\n    reshape((kron(Array{eltype(A),2}(I, n, n), A) +\n            kron(transpose(B), Array{eltype(B),2}(I, m, m))) \\ (C[:]),m,n)\nend\n\n\"\"\"\n    X = sylvdkr(A,B,C)\n\nSolve the discrete Sylvester matrix equation\n\n                AXB + X = C\n\nusing the Kronecker product expansion of equations. `A` and `B` are\nsquare matrices, and `A` and `-B` must not have common reciprocal eigenvalues.\nThis function is not recommended for large order matrices.\n\"\"\"\nfunction sylvdkr(A, B, C)\n    m, n = size(C)\n    [m; n] == LinearAlgebra.checksquare(A, B) ||\n            throw(DimensionMismatch(\"A, B and C have incompatible dimensions\"))\n    reshape((kron(transpose(B), A) + I) \\ (C[:]), m, n)\nend\n\n\"\"\"\n    X = gsylvkr(A,B,C,D,E)\n\nSolve the generalized Sylvester matrix equation\n\n                AXB + CXD = E\n\nusing the Kronecker product expansion of equations. `A`, `B`, `C` and `D` are\nsquare matrices. The pencils `A-λC` and `D+λB` must be regular and\nmust not have common eigenvalues.\nThis function is not recommended for large order matrices.\n\"\"\"\nfunction gsylvkr(A, B, C, D, E)\n   m, n = size(E)\n   [m; n; m; n] == LinearAlgebra.checksquare(A, B, C, D) ||\n                  throw(DimensionMismatch(\"A, B, C, D and E have incompatible dimensions\"))\n   reshape((kron(transpose(B), A) + kron(transpose(D), C)) \\ (E[:]), m, n)\nend\n\n\"\"\"\n    sylvsyskr(A,B,C,D,E,F) -> (X,Y)\n\nSolve the Sylvester system of matrix equations\n\n                AX + YB = C\n                DX + YE = F\n\nusing the Kronecker product expansion of equations. `(A,D)`, `(B,E)` are\npairs of square matrices of the same size.\nThe pencils `A-λD` and `-B+λE` must be regular and must not have common eigenvalues.\nThis function is not recommended for large order matrices.\n\"\"\"\nfunction sylvsyskr(A, B, C, D, E, F)\n   m, n = size(C)\n   (m == size(F, 1) && n == size(F, 2)) ||\n         throw(DimensionMismatch(\"C and F must have the same dimensions\"))\n   [m; n; m; n] == LinearAlgebra.checksquare(A, B, D, E) ||\n                  throw(DimensionMismatch(\"A, B, C, D, E and F have incompatible dimensions\"))\n   z = [ kron(Array{eltype(A),2}(I, n, n), A) kron(transpose(B), Array{eltype(B),2}(I, m, m)) ;\n         kron(Array{eltype(D),2}(I, n, n), D) kron(transpose(E), Array{eltype(E),2}(I, m, m))] \\ [C[:];F[:]]\n   (reshape(z[1:m * n], m, n), reshape(z[m * n + 1:end], m, n))\nend\n\n\"\"\"\n    dsylvsyskr(A,B,C,D,E,F) -> (X,Y)\n\nSolve the dual Sylvester system of matrix equations\n\n       AX + DY = C\n       XB + YE = F\n\nusing the Kronecker product expansion of equations. `(A,D)`, `(B,E)` are\npairs of square matrices of the same size.\nThe pencils `A-λD` and `-B+λE` must be regular and must not have common eigenvalues.\nThis function is not recommended for large order matrices.\n\"\"\"\nfunction dsylvsyskr(A, B, C, D, E, F)\n   m, n = size(C)\n   (m == size(F, 1) && n == size(F, 2)) ||\n         throw(DimensionMismatch(\"C and F must have the same dimensions\"))\n   [m; n; m; n] == LinearAlgebra.checksquare(A, B, D, E) ||\n                  throw(DimensionMismatch(\"A, B, C, D, E and F have incompatible dimensions\"))\n   z = [ kron(Array{eltype(A),2}(I, n, n), A) kron(Array{eltype(D),2}(I, n, n), D);\n         kron(transpose(B), Array{eltype(B),2}(I, m, m)) kron(transpose(E), Array{eltype(E),2}(I, m, m))] \\ [C[:];F[:]]\n   (reshape(z[1:m * n], m, n), reshape(z[m * n + 1:end], m, n))\nend\n", "meta": {"hexsha": "872855cecfa4854fecff347e3f74a4430e12559d", "size": 3806, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sylvkr.jl", "max_stars_repo_name": "andreasvarga/MatrixEquations", "max_stars_repo_head_hexsha": "60017b9fa7f376d950fac06ea1cea7940fc1ed23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2019-12-02T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T16:21:29.000Z", "max_issues_repo_path": "src/sylvkr.jl", "max_issues_repo_name": "andreasvarga/MatrixEquations", "max_issues_repo_head_hexsha": "60017b9fa7f376d950fac06ea1cea7940fc1ed23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2019-08-07T12:52:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:48:26.000Z", "max_forks_repo_path": "src/sylvkr.jl", "max_forks_repo_name": "andreasvarga/MatrixEquations", "max_forks_repo_head_hexsha": "60017b9fa7f376d950fac06ea1cea7940fc1ed23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-10-06T01:38:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T12:36:04.000Z", "avg_line_length": 36.5961538462, "max_line_length": 119, "alphanum_fraction": 0.6066736731, "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620573763841, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.766069379366479}}
{"text": "# Author: Lukasz Bratos\n\nusing LinearAlgebra\n\nfunction hilb(n::Int)\n    # Function generates the Hilbert matrix  A of size n,\n    #  A (i, j) = 1 / (i + j - 1)\n    # Inputs:\n    #\tn: size of matrix A, n>=1\n    #\n    #\n    # Usage: hilb(10)\n    #\n    # Pawel Zielinski\n    if n < 1\n        error(\"size n should be >= 1\")\n    end\n    return [1 / (i + j - 1) for i in 1:n, j in 1:n]\nend\n    \nfunction matcond(n::Int, c::Float64)\n# Function generates a random square matrix A of size n with\n# a given condition number c.\n# Inputs:\n#\tn: size of matrix A, n>1\n#\tc: condition of matrix A, c>= 1.0\n#\n# Usage: matcond(10, 100.0)\n#\n# Pawel Zielinski\n    if n < 2\n        error(\"size n should be > 1\")\n    end\n    if c < 1.0\n        error(\"condition number  c of a matrix  should be >= 1.0\")\n    end\n    (U, S, V) = svd(rand(n, n))\n    return U * diagm(0 => [LinRange(1.0, c, n);]) * V'\nend\n\nfunction calculate(matrix, x, size)\n    b = matrix * x\n    gauss = matrix \\ b\n    inversion = inv(matrix) * b\n\n    gauss_err = norm(gauss - x) / norm(x)\n    inv_err = norm(inversion - x) / norm(x)\n\n    println(\"$size & $(rank(matrix)) & $(cond(matrix)) & $gauss_err & $inv_err \\\\\\\\ \\\\hline\")\nend\n\nfor i in 1:20\n    matrix = hilb(i)\n    x = ones(Float64, i)\n    calculate(matrix, x, i)\nend\n\nfor i in [5, 10, 20]\n    for j in [1.0, 10.0, 10.0^3, 10.0^7, 10.0^12, 10.0^16]\n        matrix = matcond(i, j)\n        x = ones(Float64, i)\n        calculate(matrix, x, i)\n    end\nend", "meta": {"hexsha": "12da643b7a3c23f58e6ef5e32a17a4b97f5cd1e8", "size": 1454, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "list2/task3.jl", "max_stars_repo_name": "luk9400/on", "max_stars_repo_head_hexsha": "0f35fb60d020c065c96c54893161a3c41ab77acb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "list2/task3.jl", "max_issues_repo_name": "luk9400/on", "max_issues_repo_head_hexsha": "0f35fb60d020c065c96c54893161a3c41ab77acb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "list2/task3.jl", "max_forks_repo_name": "luk9400/on", "max_forks_repo_head_hexsha": "0f35fb60d020c065c96c54893161a3c41ab77acb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.71875, "max_line_length": 93, "alphanum_fraction": 0.5522696011, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7660570278533151}}
{"text": "fix_literal(id) = if id isa Symbol; Meta.quot(id) else id end\n(~)(id) = fix_literal(id)\n\ncommutativity(op) = :( ($op)(a, b) == ($op)(b, a) ) |> Rule\nright_associative(op) = :( ($op)(a, $(op)(b,c)) => ($op)($(op)(a,b), c) ) |> Rule\nleft_associative(op) = :( ($op)($(op)(a,b), c) => ($op)(a, $(op)(b,c)) ) |> Rule\n\nassociativity_left(op) = :( ($op)(a, $(op)(b,c)) => ($op)($(op)(a,b), c) ) |> Rule\nassociativity_right(op) = :(  ($op)($(op)(a,b), c) => ($op)(a, $(op)(b,c)) ) |> Rule\n\nassociativity(op) = [associativity_left(op), associativity_right(op)]\n\nidentity_left(op, id) = let id = ~id; :( ($op)($id, a) => a ) |> Rule end\nidentity_right(op, id) = let id = ~id; :( ($op)(a, $id) => a ) |> Rule end\n\ninverse_left(op, id, invop) = let id = ~id; :( ($op)(($invop)(a), a) => $id ) |> Rule end\ninverse_right(op, id, invop) = let id = ~id; :( ($op)(a, ($invop)(a)) => $id ) |> Rule end\n\n# distributivity of two operations\n# example: `@distrib (⋅) (⊕)`\nfunction distrib_left(outop, inop)\n\t@assert Base.isbinaryoperator(outop)\n\t@assert Base.isbinaryoperator(inop)\n\t:( ($outop)(a, ($inop)(b,c)) == ($inop)(($outop)(a,b),($outop)(a,c)) ) |> Rule\nend\n\nfunction distrib_right(outop, inop)\n\t@assert Base.isbinaryoperator(outop)\n\t@assert Base.isbinaryoperator(inop)\n\t:( ($outop)(($inop)(a,b), c) == ($inop)(($outop)(a,c),($outop)(b,c)) ) |> Rule\nend\n\nfunction monoid(op, id)\n\tlet id = ~id\n\t\t@assert Base.isbinaryoperator(op)\n\t\t[associativity_left(op), associativity_right(op),\n\t\t identity_left(op, id), identity_right(op,id)]\n\tend\nend\nmacro monoid(op, id) monoid(op, id) end\n\n\nfunction commutative_monoid(op, id)\n\tlet id = ~id;\n\t\t@assert Base.isbinaryoperator(op)\n\t\t[commutativity(op), associativity_left(op),\n\t\tassociativity_right(op), identity_left(op, id)]\n\tend\nend\nmacro commutative_monoid(op, id) commutative_monoid(op, id) end\n\n# constructs a semantic theory about a an abelian group\n# The definition of a group does not require that a ⋅ b = b ⋅ a\n# for all elements a and b in G. If this additional condition holds,\n# then the operation is said to be commutative, and the group is called an abelian group.\nfunction commutative_group(op, id, invop)\n\tlet id = ~id;\n\t\t@assert Base.isbinaryoperator(op)\n\t\t# @assert Base.isunaryoperator(invop)\n\t\tcommutative_monoid(op, id) ∪ [inverse_right(op, id, invop)]\n\tend\nend\nabelian_group(op, id, invop) = commutative_group(op, id, invop)\nmacro commutative_group(op, id, invop) commutative_group(op, id, invop) end\nmacro abelian_group(op, id, invop) commutative_group(op, id, invop) end\n\n\n\n\ndistrib(outop, inop) = [\n\tdistrib_left(outop, inop), distrib_right(outop, inop),\n]\n", "meta": {"hexsha": "bbe959327f43133efebb64ec21bcc60f3a79c768", "size": 2606, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Library/algebra.jl", "max_stars_repo_name": "gpeairs/Metatheory.jl", "max_stars_repo_head_hexsha": "782469676fb01db5eb3dc5f385539830b9116bea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Library/algebra.jl", "max_issues_repo_name": "gpeairs/Metatheory.jl", "max_issues_repo_head_hexsha": "782469676fb01db5eb3dc5f385539830b9116bea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Library/algebra.jl", "max_forks_repo_name": "gpeairs/Metatheory.jl", "max_forks_repo_head_hexsha": "782469676fb01db5eb3dc5f385539830b9116bea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.698630137, "max_line_length": 90, "alphanum_fraction": 0.6523407521, "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7660570191939986}}
{"text": "n = 2\nm = 1\n\nA = [1.0 1.0; 0.0 1.0]\nB = [0.0; 1.0]\n\nQ = [1.0 0.0; 0.0 1.0]\nR = [1.0]\n\nx_init = [1.0; 0.0]\n\nnz = 2 * n + m + 2 * n\n\nfunction unpack(z)\n\tx2 = z[1:n]\n\tu1 = z[n .+ (1:m)]\n\tx1 = z[n + m .+ (1:n)]\n\ty2 = z[n + m + n .+ (1:n)]\n\ty1 = z[n + m + n + n .+ (1:n)]\n\n\treturn x2, u1, x1, y2, y1\nend\n\nz0 = rand(nz)\nunpack(z0)\nones(1)' * R * ones(1)\nfunction lagrangian(z, x_init)\n\tx2, u1, x1, y2, y1 = unpack(z)\n\n\tL = 0.0\n\n\t# objective\n\tL += transpose(x2) * Q * x2\n\tL += (transpose(u1) * R * u1)[1]\n\tL += transpose(x1) * Q * x1\n\n\t# constraints\n\tL += transpose(y2) * (A * x1 + B * u1[1] - x2)\n\tL += transpose(y1) * (x_init - x1)\n\n\treturn L\nend\n\n@variables z_sym[1:nz]\n@variables x_sym[1:n]\n\nL = lagrangian(z_sym, x_sym)\nL = simplify.(L)\n\ndL = Symbolics.gradient(L, z_sym)\nddL = Symbolics.hessian(L, z_sym)\nddL_x = Symbolics.jacobian(dL, x_sym)\n\nL_grad = eval(Symbolics.build_function(dL, z_sym, x_sym)[1])\nL_hess = eval(Symbolics.build_function(ddL, z_sym, x_sym)[1])\nLx_hess = eval(Symbolics.build_function(ddL_x, z_sym, x_sym)[1])\n\nfunction solve(z0, x_init)\n\tz = copy(z0)\n\n\t∇L = L_grad(z, x_init)\n\n\tprintln()\n\tfor i = 1:10\n\t\tr_norm = norm(∇L)\n\t\tprintln(\"iter ($i)\")\n\t\tprintln(\"\tgrad norm: $(r_norm)\")\n\t\tr_norm < 1.0e-8 && break\n\n\t\t∇²L = L_hess(z, x_init)\n\n\t\tΔ = ∇²L \\ ∇L\n\n\t\tα = 1.0\n\t\tẑ = z - α * Δ\n\n\t\t∇L̂ = L_grad(ẑ, x_init)\n\n\t\titer = 1\n\t\twhile norm(∇L̂) > norm(∇L)\n\t\t\tα *= 0.5\n\t\t\tẑ = z - α * Δ\n\t\t\t∇L̂ = L_grad(ẑ, x_init)\n\t\t\titer += 1\n\n\t\t\tif iter > 100\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\n\t\tz = ẑ\n\t\t∇L = ∇L̂\n\tend\n\n\treturn z, ∇L, L_hess(z, x_init)\nend\n\nz_sol, ∇L_sol, ∇²L_sol = solve(z0, x_init)\nK_direct = (∇²L_sol \\ Lx_hess(z_sol, x_init))[n .+ (1:m), :]\n\n# LQR solution\nK, P = tvlqr([A], [B], [Q, Q], [R[1,1]])\n\n@assert norm(K_direct - K[1]) < 1.0e-8\n", "meta": {"hexsha": "498858d801606004982eb0c95b3b3ca0acd35bb6", "size": 1747, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/development/direct_lqr_1.jl", "max_stars_repo_name": "thowell/motion_planning", "max_stars_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2021-02-07T10:46:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:30:20.000Z", "max_issues_repo_path": "examples/development/direct_lqr_1.jl", "max_issues_repo_name": "thowell/DirectMotionPlanning", "max_issues_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-10-07T05:36:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-11T17:16:28.000Z", "max_forks_repo_path": "examples/development/direct_lqr_1.jl", "max_forks_repo_name": "thowell/motion_planning", "max_forks_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-01-25T19:23:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T06:43:01.000Z", "avg_line_length": 16.6380952381, "max_line_length": 64, "alphanum_fraction": 0.5472238122, "num_tokens": 822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7660570167996633}}
{"text": "## In this notebook, we'll look at least squares on biometric data\n\n##\nusing Plots\npyplot()\ntheme(:dark)\n##\n# https://vincentarelbundock.github.io/Rdatasets/csv/carData/Davis.csv\nusing CSV\ndf = CSV.read(download(\"https://vincentarelbundock.github.io/Rdatasets/csv/carData/Davis.csv\"))\nX = Float64.([df[:weight] df[:height]])\n# Filter the data\ngoodpts = X[:,1] .<= 115\nXf = X[goodpts,:]\n##\nscatter(Xf[:,1],Xf[:,2],label=\"\",xlabel=\"weight (kg)\", ylabel=\"height (cm)\")\n##\nx = Xf[:,1]\nA = [x ones(length(x))]\nb = Xf[:,2]\nab = A\\b # solve the least squares problem\n\n##\nusing Printf\nscatter(Xf[:,1],Xf[:,2],color=2,size=(300,300), label=\"\")\nplot!(x, x*ab[1] .+ ab[2], label=\"\",color=5)\ntitle!(@sprintf(\"height ≈ %.2f weight + %.2f    \",ab[1],ab[2]))\nxlabel!(\"Weight (kg)\")\nylabel!(\"Height (cm)\")\nsavefig(\"weight-height-fit.pdf\")\n## Show the\n\n## Show the quadratic surface\nquadratic_leastsq(A,b) = x-> (0.5*norm(A*x - b)^2)\nezsurf(x, y, f) = begin\n    X = repeat(x', length(y), 1)\n    Y = repeat(y, 1, length(x))\n    # Evaluate each f(x, y)\n    Z = map((x,y) -> f([x,y]), X, Y)\n    plot(x, y, Z, st=:surface)\nend\nezsurf(-3:0.1:3,-50:0.5:250,\n  quadratic_leastsq(A,b))\n##\nplot!(colorbar=false,size=(300,300),dpi=300)\nanim = @animate for i=1:360\n  plot!(camera=(i,30))\nend\ngif(anim, \"leastsq-quadratic.gif\")\n\n##\n## Show the quadratic surface with alpha-blending\nquadratic_leastsq(A,b) = x-> (0.5*norm(A*x - b)^2)\nezsurf(x, y, f) = begin\n    X = repeat(x', length(y), 1)\n    Y = repeat(y, 1, length(x))\n    # Evaluate each f(x, y)\n    Z = map((x,y) -> f([x,y]), X, Y)\n    plot()\n    plot!(x, y, Z, st=:surface)\nend\nezsurf(-3:0.1:3,-50:0.5:250,\n  quadratic_leastsq(A,b))\n\n##\n## Show k random samples of the quadratic surface\nplotlyjs()\nquadratic_leastsq(A,b) = x-> (0.5*norm(A*x - b)^2)/size(A,1)\nezsurf!(x, y, f) = begin\n    X = repeat(x', length(y), 1)\n    Y = repeat(y, 1, length(x))\n    # Evaluate each f(x, y)\n    Z = map((x,y) -> f([x,y]), X, Y)\n    plot!(x, y, Z, st=:surface, alpha=0.1)\nend\norig = ezsurf(-3:0.25:3,-50:1:250,\n  quadratic_leastsq(A,b))\nnsamp = 25\nk = 25\nfor i=1:k\n  subset = randperm(size(A,1))[1:25] # choose 25 of 200 samples.\n  ezsurf!(-3:0.1:3,-50:0.5:250,\n    quadratic_leastsq(A[subset,:],b[subset,:]))\nend\nplot!() # get the plot to show\n## Show k random samples of the quadratic surface\nusing Random\nusing LinearAlgebra\nplotlyjs()\nquadratic_leastsq(A,b) = x-> (0.5*norm(A*x - b)^2)/size(A,1)\nezsurf!(x, y, f) = begin\n    X = repeat(x', length(y), 1)\n    Y = repeat(y, 1, length(x))\n    # Evaluate each f(x, y)\n    Z = map((x,y) -> f([x,y]), X, Y)\n    plot!(x, y, Z, st=:surface, alpha=0.4)\nend\nplot(framestyle=:none,colorbar=false,size=(300,300),dpi=300)\nnsamp = 10\nk = 25\nfor i=1:k\n  subset = randperm(size(A,1))[1:nsamp] # choose 25 of 200 samples.\n  ezsurf!(-3:0.25:3,-50:2:250,\n    quadratic_leastsq(A[subset,:],b[subset,:]))\nend\nplot!() # get the plot to show\n##\n#plot!(colorbar=false,size=(300,300),dpi=300)\nplot!(colorbar=false,size=(900,900))\nanim = @animate for i=2:2:360\n  plot!(camera=(i,30))\nend\ngif(anim, \"leastsq-quadratic-samples.gif\")\n\n\n## Show the same thing with a log10\nusing Random\nusing LinearAlgebra\nplotlyjs()\nquadratic_leastsq(A,b) = x-> log10(0.5*norm(A*x - b)^2)/size(A,1)\nplot(framestyle=:none,colorbar=false,size=(300,300),dpi=300)\nnsamp = 10\nk = 25\nfor i=1:k\n  subset = randperm(size(A,1))[1:nsamp] # choose 25 of 200 samples.\n  ezsurf!(-3:0.1:3,-50:0.5:250,\n    quadratic_leastsq(A[subset,:],b[subset,:]))\nend\nplot!() # get the plot to show\n##\n#plot!(colorbar=false,size=(300,300),dpi=300)\nplot!(colorbar=false,size=(900,900))\nanim = @animate for i=2:2:360\n  plot!(camera=(i,30))\nend\ngif(anim, \"leastsq-quadratic-samples-log.gif\")\n##\n", "meta": {"hexsha": "53fb5f15f3d8fc3a7b2f49321d2beb98413a6ad4", "size": 3684, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4-unit-3-demos/least-squares-sgd.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "4-unit-3-demos/least-squares-sgd.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4-unit-3-demos/least-squares-sgd.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 26.6956521739, "max_line_length": 95, "alphanum_fraction": 0.6235070575, "num_tokens": 1377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7660570165788391}}
{"text": "# Local Tangent Space Alignment (LTSA)\n# ---------------------------\n# Principal Manifolds and Nonlinear Dimension Reduction via Local Tangent Space Alignment,\n# Zhang, Zhenyue; Hongyuan Zha (2004),  SIAM Journal on Scientific Computing 26 (1): 313–338.\n# doi:10.1137/s1064827502419154.\n\n#### LTSA type\nstruct LTSA{T <: Real} <: AbstractDimensionalityReduction\n    k::Int\n    λ::AbstractVector{T}\n    proj::Projection{T}\n\n    LTSA{T}(k::Int, λ::AbstractVector{T}, proj::Projection{T}) where T = new(k, λ, proj)\nend\n\n## properties\noutdim(R::LTSA) = size(R.proj, 1)\neigvals(R::LTSA) = R.λ\nneighbors(R::LTSA) = R.k\n\n## show\nsummary(io::IO, R::LTSA) = print(io, \"LTSA(outdim = $(outdim(R)), neighbors = $(neighbors(R)))\")\n\n## interface functions\nfunction fit(::Type{LTSA}, X::AbstractMatrix{T}; maxoutdim::Int=2, k::Int=12) where {T<:Real}\n    n = size(X, 2)\n\n    # Construct NN graph\n    D, E = find_nn(X, k)\n    S = ones(k)./sqrt(k)\n    B = spzeros(T, n,n)\n    for i=1:n\n        II = @view E[:,i]\n\n        # re-center points in neighborhood\n        μ = mean(X[:, II], dims=2)\n        δ_x = X[:, II] .- μ\n\n        # Compute orthogonal basis H of θ'\n        θ_t = svd(δ_x).V[:,1:maxoutdim]\n\n        # Construct alignment matrix\n        G = hcat(S, θ_t)\n        B[II, II] .+= diagm(0 => fill(one(T), k)) .- G*transpose(G)\n    end\n\n    # Align global coordinates\n    λ, V = decompose(B, maxoutdim)\n    return LTSA{T}(k, λ, transpose(V))\nend\n\ntransform(R::LTSA) = R.proj\n", "meta": {"hexsha": "37958e56da320219bb202e0550a198f7beacd327", "size": 1464, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ltsa.jl", "max_stars_repo_name": "yuehhua/ManifoldLearning.jl", "max_stars_repo_head_hexsha": "73c5250dc5a97e806318fceb6d98cb6d2c8c8bfe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ltsa.jl", "max_issues_repo_name": "yuehhua/ManifoldLearning.jl", "max_issues_repo_head_hexsha": "73c5250dc5a97e806318fceb6d98cb6d2c8c8bfe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ltsa.jl", "max_forks_repo_name": "yuehhua/ManifoldLearning.jl", "max_forks_repo_head_hexsha": "73c5250dc5a97e806318fceb6d98cb6d2c8c8bfe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6226415094, "max_line_length": 96, "alphanum_fraction": 0.5963114754, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895028, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.7660570113832492}}
{"text": "using LinearAlgebra\r\n\r\nfunction so3ToVec(so3mat)\r\n    if( size(so3mat)!=(3,3) )\r\n        println(\"!Warning! : Input matrix should be 3x3.\")\r\n        return\r\n    end\r\n    if( !((so3mat[1,1]==so3mat[2,2]==so3mat[3,3]==0)) )\r\n        println(\"!Warning! : Diagonals should be zero.\")\r\n        return\r\n    end\r\n    if( so3mat[2,1]!=-so3mat[1,2] ||\r\n        so3mat[3,1]!=-so3mat[1,3] ||\r\n        so3mat[3,2]!=-so3mat[2,3] )\r\n        println(\"!Warning! : Entered matrix isn't a skew symmetric matrix.\")\r\n        return\r\n    end\r\n    ret_vec = [so3mat[3,2];\r\n               so3mat[1,3];\r\n               so3mat[2,1] ]\r\n        return ret_vec\r\nend\r\n\r\nfunction vecToSo3(omg)\r\n    if( size(omg)!=(3,) )\r\n        println(\"!Warning! : Input matrix should be 3x1.\")\r\n        return\r\n    end\r\n\r\n    ret_ss_matrix = [0      -omg[3]   omg[2];\r\n                     omg[3]    0     -omg[1];\r\n                    -omg[2]  omg[1]      0];\r\n    return ret_ss_matrix\r\nend\r\n", "meta": {"hexsha": "8de943b11a147228690738e47c73b8bd06d56464", "size": 950, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HW2_VeysiADIN.jl", "max_stars_repo_name": "veysiadn/AdvancedRoboticsJulia", "max_stars_repo_head_hexsha": "0484999de1908b73fd19c7c78f5c8471a62610ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW2_VeysiADIN.jl", "max_issues_repo_name": "veysiadn/AdvancedRoboticsJulia", "max_issues_repo_head_hexsha": "0484999de1908b73fd19c7c78f5c8471a62610ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW2_VeysiADIN.jl", "max_forks_repo_name": "veysiadn/AdvancedRoboticsJulia", "max_forks_repo_head_hexsha": "0484999de1908b73fd19c7c78f5c8471a62610ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1428571429, "max_line_length": 77, "alphanum_fraction": 0.4873684211, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7660570111624252}}
{"text": "# An example of the Burgers code for the\n# propagation of Burgers equation in time\n# studies the pointwise convergence order of a solution\n# to Burgers equation as a function of resolution\n\nusing Burgers\nusing Printf\nusing PyPlot\ninclude(\"Utils.jl\")\nusing .Utils\n\nfunction convergence_ratio(it::I, sc::SlopeCalc) where {T, I<:Int}\n\t# calculates the pointwise convergence ratio function\n\t# it     : the index for the time at which to slice u(x, t)\n\t#          must satisfy 0 <= t0 <= Ttot\n\t# sc     : the type of slope calculation (linear, minmod, constant)\n\t\n\tTtot     = 2.0   # total duration\n\tNt_b     = 512   # number of time divisions for lowest resolution\n\tNcells_b = 128   # number of position divisions for lowest resolution\n\tNghost   = 2     # padding on position divisions for boundary conditions\n\t\n\tif !(1 <= it <= Nt_b)\n\t\terror(\"The input time index must be between 1 and $Nt_base\")\n\tend\n\t\n\t# The scaling factors\n\tscale1 = 8\n\tscale2 = 2*scale1\n\tscale3 = 2*scale2\n\t\n\t# Creating the Resolution instances\n\tres1 = Resolution{Float64, Int64}(Ttot, scale1*Nt_b, scale1*Ncells_b, Nghost)\n\tres2 = Resolution{Float64, Int64}(Ttot, scale2*Nt_b, scale2*Ncells_b, Nghost)\n\tres3 = Resolution{Float64, Int64}(Ttot, scale3*Nt_b, scale3*Ncells_b, Nghost)\n\t\n\t# Evaluating the solution to Burgers equation at t = t0\n\tufun1 = get_evolved_slice(get_sinewave, res1, scale1*it, sc)\n\tufun2 = get_evolved_slice(get_sinewave, res2, scale2*it, sc)\n\tufun3 = get_evolved_slice(get_sinewave, res3, scale3*it, sc)\n\t\n\t# Calculating the absolute difference between solutions\n\t# of successive resolutions\n\tudiff12 = absolute_difference(ufun1, ufun2, ufun1.xdat)\n\tudiff23 = absolute_difference(ufun2, ufun3, ufun1.xdat)\n\t\n\t# stabilize the solutions, prevents the denominator from being too small\n\teps = 1e-6\n\turatio = (eps + udiff12)/(eps + udiff23)\n\t\n\treturn uratio\nend\n\nfunction plot_convergence(cfun::FunArr{T, U}, imagename::AbstractString) where {T, U}\n\t# plots and saves the binary logarithm of the pointwise convergence function\n\tPyPlot.clf()\n\t\n\txlabel(\"x\")\n\txlim(0, 1)\n\txticks(range(0, 1, length = 10 + 1))\n\n\tylabel(\"C(x)\")\n\tylim(0, 6)\n\tyticks(range(0, 6, length = 6 + 1))\n\n\tplot(cfun.xdat, log.(2, cfun.udat))\n\tsavefig(\"images/\" * imagename * \".png\", dpi = 300)\nend\n\n# collect the command line arguments\n# calculate and plot the convergence ratio\nit, sc, imagename = commandlineparser(true)\nconvergence       = convergence_ratio(it, sc)\nplot_convergence(convergence, imagename)\n", "meta": {"hexsha": "a6395ca931c44acc127efe55c3cd3e04441c8540", "size": 2464, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/convergence.jl", "max_stars_repo_name": "AlexanderIbrahim1/Burgers", "max_stars_repo_head_hexsha": "a6813450ff4f9a341fbc21069e27a2560829348e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/convergence.jl", "max_issues_repo_name": "AlexanderIbrahim1/Burgers", "max_issues_repo_head_hexsha": "a6813450ff4f9a341fbc21069e27a2560829348e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/convergence.jl", "max_forks_repo_name": "AlexanderIbrahim1/Burgers", "max_forks_repo_head_hexsha": "a6813450ff4f9a341fbc21069e27a2560829348e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8533333333, "max_line_length": 85, "alphanum_fraction": 0.7256493506, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.7660089834342281}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 4ea41550-9313-11eb-1cdf-df6c5527f80f\nbegin\n\tusing PlutoUI\n\tPlutoUI.TableOfContents(aside=true)\nend\n\n# ╔═╡ 4c360009-f01e-45bb-b458-29b15f8cac8f\nbegin\n\tusing LinearAlgebra, SpecialMatrices, Statistics\n\timport Random\n\tRandom.seed!(125)\n\tx=rand(-9:9,5)\nend\n\n# ╔═╡ 7d3ed16e-50ea-4ede-b968-e32baa56f76f\nmd\"\"\"\n# Eigenvalue Decomposition - Perturbation Theory\n\n\n__Prerequisites__\n\nThe reader should be familiar with basic linear algebra concepts and facts about eigenvalue decomposition. \n\n__Competences__ \n\nThe reader should be able to understand and check the facts about perturbations of eigenvalues and eigenvectors.\n\n\"\"\"\n\n# ╔═╡ da0d7094-fa3e-4f1e-a6f1-9d1b9316f65a\nmd\"\"\"\n# Norms\n\nIn order to measure changes, we need to define norms. For more details and the proofs of the Facts below, see \n[R. Byers and B. N. Datta, Vector and Matrix Norms, Error Analysis, Efficiency, and Stability, pp. 50.1-50.24](https://www.routledge.com/Handbook-of-Linear-Algebra/Hogben/p/book/9781138199897) and the references therein.\n\n## Definitions\n\n__Norm__ on a vector space $X$ is a real-valued function $\\| \\phantom{x} \\| : X\\to \\mathbb{R}$ with the following properties:\n\n1. __Positive definiteness.__ $\\| x\\|\\geq 0$ and $\\|x\\|=0$ if and only if $x$ is the zero vector.  \n2. __Homogeneity.__ $\\| \\lambda x\\|=|\\lambda| \\|x\\|$  \n3. __Triangle inequality.__ $\\| x+y\\| \\leq \\|x\\|+\\|y\\|$ \n\nCommonly encountered vector norms for $x\\in\\mathbb{C}^n$ are:\n\n* __Hölder norm__ or $p$-__norm__: for $p\\geq 1$, $\\|x\\|_p=\\big(|x_1|^p+|x_2|^p+\\cdots |x_n|^p)^{1/p}$,\n* __Sum norm__ or $1$-__norm__: $\\|x\\|_1=|x_1|+|x_2|+\\cdots |x_n|$,\n* __Euclidean norm__ or $2$-__norm__: $\\|x\\|_2=\\sqrt{|x_1|^2+|x_2|^2+\\cdots |x_n|^2}$,\n* __Sup-norm__ or $\\infty$-__norm__: $\\|x\\|_\\infty = \\max\\limits_{i=1,\\ldots,n} |x_i|$.\n\nVector norm is __absolute__ if $\\||x|\\|=\\|x\\|$.\n\nVector norm is __monotone__ if $|x|\\leq |y|$ implies $\\|x\\|\\leq \\|y\\|$. \n\nFrom every vector norm we can derive a corresponding __induced__ matrix norm (also, __operator norm__ or __natural norm__):\n\n$$\\|A\\| = \\max\\limits_{x\\neq 0} \\frac{\\|Ax\\|}{\\|x\\|}=\\max\\limits_{\\|x\\|=1} \\|Ax\\|.$$\n\nFor matrix $A\\in\\mathbb{C}^{m\\times n}$ we define:\n\n* __Maximum absolute column sum norm__: $\\|A\\|_1=\\max\\limits_{1\\leq j \\leq n} \\sum_{i=1}^m |a_{ij}|$,\n* __Spectral norm__: $\\|A\\|_2=\\sqrt{\\rho(A^*A)}=\\sigma_{\\max}(A)$  (largest singular value of $A$),\n* __Maximum absolute row sum norm__: $\\|A\\|_{\\infty}=\\max\\limits_{1\\leq i \\leq m} \\sum_{j=1}^n |a_{ij}|$,\n* __Euclidean norm__ or __Frobenius norm__: \n$\\|A\\|_F =\\sqrt{\\sum_{i,j} |a_{ij}|^2}=\\sqrt{\\mathop{\\mathrm{tr}}(A^*A)}$.\n\nMatrix norm is __consistent__ if $\\|A\\cdot B\\|\\leq \\|A\\| \\cdot \\| B\\|$, where $A$ and $B$ are compatible for matrix multiplication.\n\nMatrix norm is __absolute__ if $\\||A|\\|=\\|A\\|$.\n\"\"\"\n\n# ╔═╡ f8ba4230-9313-11eb-170c-ab58597826f8\nmd\"\n### Examples\n\"\n\n# ╔═╡ 7bd6f898-b86c-4670-96e8-9016666ee14f\nnorm(x,1), norm(x), norm(x,Inf)\n\n# ╔═╡ 8e1ced3a-d23d-4f5f-8c65-dc13ab392504\nA=rand(-4:4,5,4)\n\n# ╔═╡ d9ef7b4b-4954-464a-96ac-e3f49800e0b7\nnorm(A,1), norm(A), norm(A,2), norm(A,Inf), \nopnorm(A), opnorm(A,1), opnorm(A,Inf)\n\n# ╔═╡ 90fcd9f5-d98c-4db6-bf30-21e377209681\nmd\"\"\"\n## Facts\n\n\n1.  $\\|x\\|_1$, $\\|x\\|_2$, $\\|x\\|_\\infty$ and $\\|x\\|_p$ are absolute and monotone vector norms.\n2. A vector norm is absolute iff it is monotone.\n3. __Convergence.__ $x_k\\to x_*$ iff for any vector norm $\\|x_k-x_*\\|\\to 0$.\n4. Any two vector norms are equivalent in the sense that, for all $x$ and some $\\alpha,\\beta>0$\n\n$$\\alpha \\|x\\|_\\mu \\leq \\|x\\|_\\nu \\leq \\beta \\|x\\|_\\mu.$$ \n\nIn particular:\n\n   *  $\\|x\\|_2 \\leq \\|x\\|_1\\leq \\sqrt{n}\\|x\\|_2$,\n   *  $\\|x\\|_\\infty \\leq \\|x\\|_2\\leq \\sqrt{n}\\|x\\|_\\infty$,\n   *  $\\|x\\|_\\infty \\leq \\|x\\|_1\\leq n\\|x\\|_\\infty$.\n\n5. __Cauchy-Schwartz inequality.__ $|x^*y|\\leq \\|x\\|_2\\|y\\|_2$.\n6. __Hölder inequality.__ If $p,q\\geq 1$ and $\\displaystyle\\frac{1}{p}+\\frac{1}{q}=1$, then \n\n$$|x^*y|\\leq \\|x\\|_p\\|y\\|_q.$$\n\n7.  $\\|A\\|_1$, $\\|A\\|_2$ and $\\|A\\|_\\infty$ are induced by the corresponding vector norms.\n8.  $\\|A\\|_F$ is not an induced norm.\n9.  $\\|A\\|_1$, $\\|A\\|_2$, $\\|A\\|_\\infty$ and $\\|A\\|_F$ are consistent.\n10.  $\\|A\\|_1$, $\\|A\\|_\\infty$ and $\\|A\\|_F$ are absolute. However, $\\||A|\\|_2\\neq \\|A\\|_2$.\n11. Any two matrix norms are equivalent in the sense that, for all $A$ and some $\\alpha,\\beta>0$\n\n$$\\alpha \\|A\\|_\\mu \\leq \\|A\\|_\\nu \\leq \\beta \\|A\\|_\\mu.$$\n\nIn particular:\n   *  $\\frac{1}{\\sqrt{n}}\\|A\\|_\\infty \\leq \\|A\\|_2\\leq \\sqrt{m}\\|A\\|_\\infty$,\n   *  $\\|A\\|_2 \\leq \\|A\\|_F\\leq \\sqrt{n}\\|A\\|_2$,\n   *  $\\frac{1}{\\sqrt{m}}\\|A\\|_1 \\leq \\|A\\|_2\\leq \\sqrt{n}\\|A\\|_1$.\n\n12.  $\\|A\\|_2\\leq \\sqrt{\\|A\\|_1 \\|A\\|_\\infty}$.\n13.  $\\|AB\\|_F\\leq \\|A\\|_F\\|B\\|_2$ and $\\|AB\\|_F\\leq \\|A\\|_2\\|B\\|_F$.\n14. If $A=xy^*$, then $\\|A\\|_2=\\|A\\|_F=\\|x\\|_2\\|y\\|_2$.\n15.  $\\|A^*\\|_2=\\|A\\|_2$ and $\\|A^*\\|_F=\\|A\\|_F$.\n16. For a unitary matrix $U$ of compatible dimension,\n\n$$\\|AU\\|_2=\\|A\\|_2,\\quad \\|AU\\|_F=\\|A\\|_F,\\quad\n\\|UA\\|_2=\\|A\\|_2,\\quad  \\|UA\\|_F=\\|A\\|_F.$$\n\n17. For $A$ square, $\\rho(A)\\leq\\|A\\|$.\n18. For $A$ square, $A^k\\to 0$ iff $>\\rho(A)<1$.\n\"\"\"\n\n# ╔═╡ 8261b5ce-9315-11eb-2378-af63c3eb4c02\nmd\"\n### Random matrix\n\"\n\n# ╔═╡ bb6eee61-c3ee-4b6a-ab44-a638fba776b8\nA\n\n# ╔═╡ 060b8d2f-e6f3-4625-9cf6-d4cc504145fa\n# Absolute norms. Spectral norm is not absolute.\nopnorm(A,1), opnorm(abs.(A),1), norm(A,1), opnorm(A,Inf), opnorm(abs.(A),Inf), norm(A), norm(abs.(A)),  opnorm(A),opnorm(abs.(A))\n\n# ╔═╡ f55a3c60-9315-11eb-027a-dd008031f6f9\nm,n=size(A)\n\n# ╔═╡ c4a1b888-9497-4eb4-aa1c-23671123f426\n# Equivalence of norms\nopnorm(A,Inf)\\ √n,opnorm(A), √m*opnorm(A,Inf)\n\n# ╔═╡ b46cbb6f-36f4-4a66-b970-8fe9b0506b6a\nopnorm(A), norm(A), √n*opnorm(A)\n\n# ╔═╡ 254b2df4-f57e-4284-a735-6fd5d4546c52\nopnorm(A,1)\\ √m,opnorm(A), √n*opnorm(A,1)\n\n# ╔═╡ 09fd0923-1987-4a2e-be28-78451aa2c11a\n# Fact 12\nopnorm(A), √(opnorm(A,1)*opnorm(A,Inf))\n\n# ╔═╡ dcba6892-b90e-41ad-8d58-53e72d40e882\nbegin\n\t# Fact 13\n\tB=rand(n,rand(1:9))\n\tnorm(A*B), norm(A)*opnorm(B), opnorm(A)*norm(B)\nend\n\n# ╔═╡ c765c02e-9316-11eb-146c-ff5d3ba81323\nx\n\n# ╔═╡ d948741f-6748-44d7-ae8c-cf074f7549bd\nbegin\n\t# Fact 14\n\ty=rand(ComplexF64,10)\n\topnorm(x*y'), norm(x*y'), norm(x)*norm(y)\nend\n\n# ╔═╡ ec0746a1-41bd-4d61-9deb-8e227106e592\nbegin\n\t# Fact 15\n\tA₁=rand(-4:4,7,5)+im*rand(-4:4,7,5)\n\topnorm(A₁), opnorm(A₁'), norm(A₁), norm(A₁')\nend\n\n# ╔═╡ d92799f7-1813-450b-8353-9d03078f69f0\n# Unitary invariance - generate random unitary matrix U\nU=qr(rand(ComplexF64,size(A₁)));\n\n# ╔═╡ 0d58d4c4-16c6-4a5b-bdbd-f3f599d0d648\nopnorm(A₁), opnorm(U.Q*A₁), norm(A₁), norm(U.Q*A₁)\n\n# ╔═╡ b1a90c59-8c3e-4530-83ef-6b3e6c6fa687\nbegin\n\t# Spectral radius\n\tA₂=rand(ComplexF64,7,7)\n\tmaximum(abs,eigvals(A₂)), opnorm(A₂,Inf), opnorm(A₂,1), opnorm(A₂), norm(A₂)\nend\n\n# ╔═╡ 31e73f82-93e7-448c-940b-5c9f5e573e5c\nbegin\n\t# Fact 18\n\tB₂=A₂/(maximum(abs,eigvals(A₂))+2)\n\tmaximum(abs,eigvals(B₂)), norm(B₂^100)\nend\n\n# ╔═╡ 909033d9-bb27-4f0e-b07d-574f7fcee700\nmd\"\"\"\n# Errors and condition numbers\n\nWe want to answer the question:\n\n__How much the value of a function changes with respect to the change of its argument?__\n\n## Definitions\n\nFor function $f(x)$ and argument $x$, the __absolute error__ with respect to the __perturbation__ of the argument \n$\\delta x$ is \n\n$$\n\\| f(x+\\delta x)-f(x)\\| = \\frac{\\| f(x+\\delta x)-f(x)\\|}{\\| \\delta x \\|} \\|\\delta x\\| \\equiv \\kappa \\|\\delta x\\|.$$\n\nThe  __condition__ or  __condition number__ $\\kappa$ tells how much does the perturbation of the argument increase. (Its form resembles derivative.)\n\nSimilarly, the __relative error__ with respect to the relative perturbation of the argument is\n\n$$\n\\frac{\\| f(x+\\delta x)-f(x)\\|}{\\| f(x) \\|}= \\frac{\\| f(x+\\delta x)-f(x)\\|\\cdot  \\|x\\| }{\\|\\delta x\\| \\cdot\\| f(x)\\|}\n\\cdot \\frac{\\|\\delta x\\|}{\\|x\\|} \\equiv \\kappa_{rel} \\frac{\\|\\delta x\\|}{\\|x\\|}.$$\n\"\"\"\n\n# ╔═╡ 7ef162c0-5c80-4e96-bcc3-125b302b1d5e\nmd\"\"\"\n# Peturbation bounds\n\n## Definitions\n\nLet $A\\in\\mathbb{C}^{n\\times n}$.\n\nPair $(\\lambda,x)\\in\\mathbb{C}\\times\\mathbb{C}^{n\\times n}$ is an __eigenpair__ of $A$ if $x\\neq 0$ and $Ax=\\lambda x$.\n\nTriplet $(y,\\lambda,x)\\in\\times\\mathbb{C}^{n}\\times\\mathbb{C}\\times\\mathbb{C}^{n}$ is an __eigentriplet__ of $A$ if $x,y\\neq 0$ and $Ax=\\lambda x$ and $y^*A=\\lambda y^*$.\n\n__Eigenvalue matrix__ is a diagonal matrix $\\Lambda=\\mathop{\\mathrm{diag}}(\\lambda_1,\\lambda_2,\\ldots,\\lambda_n)$.\n\nIf all eigenvalues are real, they can be increasingly ordered. $\\Lambda^\\uparrow$ is the eigenvalue matrix of increasingly ordered eigenvalues.\n\n $\\tau$ is a __permutation__ of $\\{1,2,\\ldots,n\\}$.\n\n $\\tilde A=A+\\Delta A$ is a __perturbed matrix__, where $\\Delta A$ is __perturbation__. $(\\tilde \\lambda,\\tilde x)$ are the eigenpairs of $\\tilde A$.\n\n__Condition number__ of a nonsingular matrix $X$ is $\\kappa(X)=\\|X\\| \\|X^{-1}\\|$.\n\nLet $X,Y\\in\\mathbb{C}^{n\\times k}$ with $\\mathop{\\mathrm{rank}}(X)=\\mathop{\\mathrm{rank}}(Y)=k$. The __canonical angles__ between their column spaces, $\\theta_i$, are defined by $\\cos \\theta_i=\\sigma_i$, where $\\sigma_i$ are the singular values of the matrix\n\n$$(Y^*Y)^{-1/2}Y^*X(X^*X)^{-1/2}.$$ \n\nThe __canonical angle matrix__ between $X$ and $Y$ is \n\n$$\\Theta(X,Y)=\\mathop{\\mathrm{diag}}(\\theta_1,\\theta_2,\\ldots,\\theta_k).$$\n    \n\"\"\"\n\n# ╔═╡ 3c8f71a5-0c2f-43a0-bf71-db9df707f84e\nmd\"\"\"\n## Facts\n\nBounds become more strict as matrices have more structure. \nMany bounds have versions in spectral norm and Frobenius norm.\nFor more details and the proofs of the Facts below, see \n[R.-C. Li, Matrix Perturbation Theory, pp 21.1-21.20](https://www.routledge.com/Handbook-of-Linear-Algebra/Hogben/p/book/9781138199897), and the references therein.\n\n1. There exists $\\tau$ such that\n\n$$\\|\\Lambda- \\tilde\\Lambda_\\tau\\|_2\\leq 4(\\|A\\|_2+\\|\\tilde A\\|_2)^{1-1/n}\\|\\Delta A\\|_2^{1/n}.$$\n\n2. __First-order perturbation bounds.__ Let $(y,\\lambda,x)$ be an eigentriplet of a simple $\\lambda$. $\\Delta A$ changes $\\lambda$ to $\\tilde\\lambda=\\lambda+ \\delta\\lambda$, where _(for proof see GVL p. 359)_\n\n$$\\delta\\lambda=\\frac{y^*(\\Delta A)x}{y^*x}+O(\\|\\Delta A\\|_2^2).$$\n\n3. Let $\\mu$ be a semisimple eigenvalue of $A$ with multiplicitiy $k$, and let $X,Y\\in \\mathbb{C}^{n\\times k}$ be the matrices of the corresponding right and left eigenvectors, that is, $AX=\\lambda X$ and $Y^*A=\\lambda Y^*$, such that $Y^*X=I_k$. $\\Delta A$ changes the $k$ copies of $\\mu$ to $\\tilde \\mu=\\mu+\\delta\\mu_i$, where $\\delta\\mu_i$ are the eigenvalues of $Y^*(\\Delta A) X$ up to $O(\\|\\Delta A\\|_2^2)$.\n\n4. Perturbations and the inverse: if $\\|A\\|_p<1$, then $I-A$ is nonsingular and _(for proof see GVL p. 74)_\n\n$$(I-A)^{-1}=\\sum\\limits_{k=0}^\\infty A^k,$$\n\n$$\\|(I-A)^{-1}\\|_p \\leq \\frac{1}{1-\\|A\\|_p},\\qquad \n\\|(I-A)^{-1}-I\\|_p \\leq \\frac{\\|A\\|_p}{1-\\|A\\|_p}.$$\n\n5. __Geršgorin Circle Theorem.__ If $X^{-1} A X=D+F$, where $D=\\mathop{\\mathrm{diag}}(d_1,\\ldots,d_n)$ and $F$ has zero diagonal entries, then _(for proof see GVL p. 357)_\n\n$$\\sigma(A) \\subseteq \\bigcup\\limits_{i=1}^n D_i,$$\n\nwhere \n\n$$D_i=\\big\\{z\\in\\mathbb{C} : |z-d_i| \\leq \\sum\\limits_{j=1}^n |f_{ij}| \\big\\}.$$\n\nMoreover, by continuity, if a connected component of $D$ consists of $k$ circles, it contains $k$ eigenvalues.\n\n6. __Bauer-Fike Theorem.__ If $A$ is diagonalizable and $A=X\\Lambda X^{-1}$ is its eigenvalue decomposition, then _(for proof see GVL p. 357)_\n\n$$\\max_i\\min_j |\\tilde \\lambda_i -\n\\lambda_j|\\leq \\|X^{-1}(\\Delta A)X\\|_p\\leq \\kappa_p(X)\\|\\Delta A\\|_p.$$\n\n7. If $A$ and $\\tilde A$ are diagonalizable, there exists $\\tau$ such that\n\n$$\\|\\Lambda-\\tilde\\Lambda_\\tau\\|_F\\leq \\sqrt{\\kappa_2(X)\\kappa_2(\\tilde X)}\\|\\Delta A\\|_F.$$ \n\nIf $\\Lambda$ and  $\\tilde\\Lambda$ are real, then\n\n$$\\|\\Lambda^\\uparrow-\\tilde\\Lambda^\\uparrow\\|_{2,F} \\leq \\sqrt{\\kappa_2(X)\\kappa_2(\\tilde X)}\\|\\Delta A\\|_{2,F}.$$\n\n8. If $A$ is normal, there exists $\\tau$ such that $\\|\\Lambda-\\tilde\\Lambda_\\tau\\|_F\\leq\\sqrt{n}\\|\\Delta A\\|_F$.\n\n9. __Hoffman-Wielandt Theorem.__ If $A$ and $\\tilde A$ are normal, there exists $\\tau$ such that $\\|\\Lambda-\\tilde\\Lambda_\\tau\\|_F\\leq\\|\\Delta A\\|_F$.\n\n10. If $A$ and $\\tilde A$ are Hermitian, for any unitarily invariant norm $\\|\\Lambda^\\uparrow-\\tilde\\Lambda^\\uparrow\\| \\leq \\|\\Delta A\\|$. In particular,\n\n$$\\begin{aligned}\n\\max_i|\\lambda^\\uparrow_i-\\tilde\\lambda^\\uparrow_i|&\\leq \\|\\Delta A\\|_2,\\\\ \n\\sqrt{\\sum_i(\\lambda^\\uparrow_i-\\tilde\\lambda^\\uparrow_i)^2}&\\leq \\|\\Delta A\\|_F.\n\\end{aligned}$$\n\n11. __Residual bounds.__ Let $A$ be Hermitian. For some $\\tilde\\lambda\\in\\mathbb{R}$ and $\\tilde x\\in\\mathbb{C}^n$ with $\\|\\tilde x\\|_2=1$, define __residual__ $r=A\\tilde x-\\tilde\\lambda\\tilde x$. Then $|\\tilde\\lambda-\\lambda|\\leq \\|r\\|_2$ for some $\\lambda\\in\\sigma(A)$.\n\n12. Let, in addition,  $\\tilde\\lambda=\\tilde x^* A\\tilde x$, let $\\lambda$ be closest to $\\tilde\\lambda$ and $x$ be its unit eigenvector, and let \n\n$$\\eta=\\mathop{\\mathrm{gap}}(\\tilde\\lambda)= \\min_{\\lambda\\neq\\mu\\in\\sigma(A)}|\\tilde\\lambda-\\mu|.$$\n\nIf $\\eta>0$, then\n\n$$|\\tilde\\lambda-\\lambda|\\leq \\frac{\\|r\\|_2^2}{\\eta},\\quad \\sin\\theta(x,\\tilde x)\\leq \\frac{\\|r\\|_2}{\\eta}.$$\n\n13. Let $A$ be Hermitian, $X\\in\\mathbb{C}^{n\\times k}$ have full column rank, and $M\\in\\mathcal{H}_k$ having eigenvalues $\\mu_1\\leq\\mu_2\\leq\\cdots\\leq\\mu_k$. Set $R=AX-XM$. Then there exist $\\lambda_{i_1}\\leq\\lambda_{i_2}\\leq\\cdots\\leq\\lambda_{i_k}\\in\\sigma(A)$ such that\n\n$$\n\\begin{aligned}    \n\\max_{1\\leq j\\leq k} |\\mu_j-\\lambda_{i_j}|& \\leq \\frac{\\|R\\|_2}{\\sigma_{\\min}(X)},\\\\\n\\sqrt{\\sum_{j=1}^k (\\mu_j-\\lambda_{i_j})^2}&\\leq \\frac{\\|R\\|_F}{\\sigma_{\\min}(X)}.\n\\end{aligned}$$\n\n(The indices $i_j$ need not be the same in the above formulae.)\n\n14. If, additionally, $X^*X=I$ and $M=X^*AX$, and if all but $k$ of $A$'s eigenvalues differ from every one of $M$'s eigenvalues by at least $\\eta>0$, then\n\n$$\\sqrt{\\sum_{j=1}^k (\\mu_j-\\lambda_{i_j})^2}\\leq \\frac{\\|R\\|_F^2}{\\eta\\sqrt{1-\\|R\\|_F^2/\\eta^2}}.$$\n\n15. Let $A=\\begin{bmatrix} M & E^* \\\\ E & H \\end{bmatrix}$ and $\\tilde A=\\begin{bmatrix} M & 0 \\\\ 0 & H \\end{bmatrix}$ be Hermitian, and set $\\eta=\\min |\\mu-\\nu|$ over all $\\mu\\in\\sigma(M)$ and $\\nu\\in\\sigma(H)$. Then\n\n$$\\max |\\lambda_j^\\uparrow -\\tilde\\lambda_j^\\uparrow| \\leq \\frac{2\\|E\\|_2^2}{\\eta+\\sqrt{\\eta^2+4\\|E\\|_2^2}}.$$\n\n16. Let \n\n$$\\begin{bmatrix} X_1^*\\\\ X_2^* \\end{bmatrix} A \\begin{bmatrix} X_1 & X_2 \\end{bmatrix}=\n\\begin{bmatrix} A_1 &  \\\\ & A_2 \\end{bmatrix}, \\quad \\begin{bmatrix} X_1 & X_2 \\end{bmatrix} \\quad \\textrm{unitary},\n\\quad X_1\\in\\mathbb{C}^{n\\times k}.$$\n\nLet $Q\\in\\mathbb{C}^{n\\times k}$ have orthonormal columns and for a Hermitian $k\\times k$ matrix $M$ set\n$R=AQ-QM$. Let $\\eta=\\min|\\mu-\\nu|$ over all $\\mu\\in\\sigma(M)$ and $\\nu\\in\\sigma(A_2)$. If $\\eta > 0$, then\n\n$$\\|\\sin\\Theta(X_1,Q)\\|_F\\leq \\frac{\\|R\\|_F}{\\eta}.$$\n\"\"\"\n\n# ╔═╡ 98fade4c-cdcb-495e-9328-96e86ca8e90e\nmd\"\"\"\n## Examples \n\n### Nondiagonalizable matrix\n\"\"\"\n\n# ╔═╡ 8f064645-cf1f-4226-add4-53bc72665bf6\nA₃=[-3 7 -1; 6 8 -2; 72 -28 19]\n\n# ╔═╡ 568366c7-3eee-4948-a096-7bf87537412d\n# (Right) eigenvectors\nX₃=eigen(A₃)\n\n# ╔═╡ fe46c02b-74bd-4303-8314-3b6e96b9e51a\ncond(X₃.vectors)\n\n# ╔═╡ c48aa813-8012-409f-9b08-ce9805da9cb3\n# Left eigenvectors\nY₃=eigen(Matrix(A₃'))\n\n# ╔═╡ f0bcadb5-882c-4e46-9079-b36097650435\ncond(Y₃.vectors)\n\n# ╔═╡ 21b412f3-f460-4f60-8b31-85c839566d62\nbegin\n\t# Try k=2,3\n\tk=1\n\tY₃.vectors[:,k]'*A₃-Y₃.values[k]*Y₃.vectors[:,k]'\nend\n\n# ╔═╡ 6654b8d5-0c31-4a44-a16a-3f71e714ce31\nbegin\n\tΔA₃=rand(3,3)/20\n\tB₃=A₃+ΔA₃\nend\n\n# ╔═╡ 3fbcbecd-6e69-49d0-94bf-06a4f6704858\nnorm(ΔA₃)\n\n# ╔═╡ 210137a6-1b7b-4741-84d2-9d72e18cd999\nZ₃=eigen(B₃)\n\n# ╔═╡ e946019f-5e75-4195-8991-da371300e9a2\nbegin\n\t# Fact 2\n\tl=1\n\tZ₃.values[l]-X₃.values[l], Y₃.vectors[:,l]'*ΔA₃*X₃.vectors[:,l] /(Y₃.vectors[:,l]⋅X₃.vectors[:,l])\nend\n\n# ╔═╡ 4723a4f9-af98-4f2d-8628-0ffc58488e62\nmd\"\"\"\n### Jordan form\n\"\"\"\n\n# ╔═╡ f3d63eb6-0174-458c-aeef-46ed6d62db7f\nbegin\n\tn₄=6\n\tc=0.5\n\tJ=Bidiagonal(c*ones(n₄),ones(n₄-1),'U')\nend\n\n# ╔═╡ b9770791-4fa6-4d3f-9688-ac79b7ae7f22\n# Accurately defined eigenvalues\nλ₄=eigvals(J)\n\n# ╔═╡ 8112bf44-3146-4b9f-953a-54de6f4c8c5b\n# Only one eigenvector\neigvecs(J)\n\n# ╔═╡ 6b26afc1-e427-496e-b9a5-4618551aeede\nbegin\n\tx₄=eigvecs(J)[:,1]\n\ty₄=eigvecs(J')[:,1]\nend\n\n# ╔═╡ b2a07659-cb08-4c53-99ac-32f817485062\ny₄'*J-0.5*y₄'\n\n# ╔═╡ 989b7c60-c673-4b77-ada8-909db2904fa2\n# Just one perturbed element in the lower left corner\nΔJ=√eps()*[zeros(n₄-1);1]*Matrix(I,1,n₄)\n\n# ╔═╡ 1da2bfee-6792-4aed-8798-91cc058cd540\nμ₄=eigvals(J+ΔJ)\n\n# ╔═╡ a6769e47-59f7-430c-9c20-a121a98f19bf\n# Fact 2\nmaximum(abs,λ₄-μ₄)\n\n# ╔═╡ fab42c40-7d01-4787-a491-3d37cae1768d\ny₄'*ΔJ*x₄/(y₄⋅x₄)\n\n# ╔═╡ 2f783e6e-5b29-477f-8b45-00461013c66f\nmd\"\"\"\nHowever, since $J+\\Delta J$ is diagonalizable, we can apply Bauer-Fike theorem to it: \n\"\"\"\n\n# ╔═╡ 9385e7e0-17d6-4840-98a2-fa69d53ebea3\nY₄=eigvecs(J+ΔJ)\n\n# ╔═╡ 18e6478b-bb8e-482c-bd02-0c85bca6fc7f\ncond(Y₄)\n\n# ╔═╡ ae524f6a-3e64-49ea-92e3-671559f85a5f\nopnorm(inv(Y₄)*ΔJ*Y₄), cond(Y₄)*opnorm(ΔJ)\n\n# ╔═╡ 9c0c9fcf-9581-479f-8ec5-d885dd3e6665\nmd\"\"\"\n### Normal matrix\n\"\"\"\n\n# ╔═╡ 300e0ddd-3ab0-4803-9528-665e754e54ca\nbegin\n\tn₅=5\n\tC=Circulant(rand(-5:5,n₅))\nend\n\n# ╔═╡ fdecade7-4d5c-460f-a566-d52868c75ec0\neigvals(Matrix(C))\n\n# ╔═╡ 01250371-f8ab-4a0a-b283-ffbcffdc2929\nΔC=randn(n₅,n₅)*0.0001\n\n# ╔═╡ 0787f637-44bf-4c5c-b8d2-92df842a91b5\nopnorm(ΔC), eigvals(C+ΔC)\n\n# ╔═╡ 5645f7ea-50e5-43f7-afc3-1c46fbdd7c5b\nmd\"\"\"\n### Hermitian matrix\n\"\"\"\n\n# ╔═╡ 51cd2fc5-e295-4b76-9fd1-fdd2b92ce05a\nbegin\n\t# Random matrix with strong column scaling\n\tm₆=10\n\tn₆=6\n\tD₆=Diagonal(exp.(10*randn(n₆)))\n\tA₆=cor(randn(m₆,n₆)*D₆)\nend\n\n# ╔═╡ bc5a0ee0-931f-11eb-204c-b9e03584c787\nD₆\n\n# ╔═╡ 1eb12479-0662-410b-9569-c4e8939a291f\nΔA₆=cor(rand(m₆,n₆)*D₆)*1e-5\n\n# ╔═╡ 821f6b8b-0e12-404b-b1dc-57d809ebf79b\nbegin\n\tλ₆,U₆=eigen(A₆) \n\tμ₆=eigvals(A₆+ΔA₆)\n\t[λ₆ μ₆]\nend\n\n# ╔═╡ ac3d3677-1160-4a79-a25f-8faa7fd89940\nnorm(ΔA₆)\n\n# ╔═╡ f4051f63-a0d3-4b43-8c61-2bbd08338a72\n# ?round\n\n# ╔═╡ 612870ba-75df-4729-a16e-432f70707fb4\nbegin\n\t# Residual bounds - how close is μ, y to λ[2],X[:,2]\n\tk₆=3\n\tζ₆=round(λ₆[k₆],sigdigits=2)\n\ty₆=round.(U₆[:,k₆],sigdigits=2)\n\tnormalize!(y₆)\nend\n\n# ╔═╡ 3ba55b4b-5445-48a3-b327-b7d3af28397a\nζ₆\n\n# ╔═╡ 6f3da676-c953-4d23-8b9a-bb62b8b8ac94\n# Fact 9\nr₆=A₆*y₆-ζ₆*y₆\n\n# ╔═╡ 886ce4f8-73a0-4b57-8d5e-082bcfc1f9aa\nminimum(abs,ζ₆.-λ₆), norm(r₆)\n\n# ╔═╡ 82a4adaa-3663-4200-9f15-d09fd4cd0259\nbegin\n\t# Fact 10 - μ is Rayleigh quotient\n\tξ₆=y₆⋅(A₆*y₆)\n\tρ₆=A₆*y₆-ξ₆*y₆\nend\n\n# ╔═╡ b1025690-4244-4933-9693-9bbd3ad8aedb\nη₆=min(abs(ξ₆-λ₆[k₆-1]),abs(ξ₆-λ₆[k₆+1]))\n\n# ╔═╡ 5e69cab3-712c-4754-b6b1-579bc3c8e114\nξ₆-λ₆[k₆], norm(ρ₆)^2/η₆\n\n# ╔═╡ 3792c478-fbaa-4683-849a-ca0d0cb751f3\nbegin\n\t# Eigenvector bound\n\t# cos(θ)\n\tcosθ=dot(y₆,U₆[:,k₆])\n\t# sin(θ)\n\tsinθ=sqrt(1-cosθ^2)\n\tsinθ,norm(ρ₆)/η₆\nend\n\n# ╔═╡ 0dd080f1-575d-43e0-9285-20279f390d2f\nbegin\n\t# Residual bounds - Fact 13\n\tQ₆=round.(U₆[:,1:3],sigdigits=2)\n\t# Orthogonalize\n\tF=qr(Q₆)\n\tX=Matrix(F.Q)\n\t# Make sure M₆ is hermitian\n\tM₆=Hermitian(X'*A₆*X)\n\tμₘ=eigvals(M₆)\n\tR₆=A₆*X-X*M₆\nend\n\n# ╔═╡ ea07eea3-bab7-4add-90cc-43acd7c2ec89\nλ₆\n\n# ╔═╡ 53f2860a-db33-49cd-b95e-3086f76c2592\nμₘ\n\n# ╔═╡ 8cdffcc2-c8c1-410e-95db-6327931782a1\nM₆\n\n# ╔═╡ 0e871e72-47ee-4492-9f73-fcfd2ef1aada\n# The entries of μ are not ordered - which algorithm was called?\nissymmetric(M₆)\n\n# ╔═╡ 108f73bc-b1cf-47ed-80f0-281cb5ebd048\nηₘ=λ₆[4]-λ₆[3]\n\n# ╔═╡ dbc219f9-9fcf-4aac-b7d5-feb8fcafe3e9\nnorm(λ₆[1:3]-μₘ), norm(R₆)^2/ηₘ\n\n# ╔═╡ 7cae5501-8a51-4874-8b23-5825f79624e3\nA₆\n\n# ╔═╡ 7cb49041-f326-4b2c-90f8-99c4d58178eb\nbegin\n\t# Fact 15\n\tM₇=A₆[1:3,1:3]\n\tH=A₆[4:6,4:6]\n\tE=A₆[4:6,1:3]\n\t# Block-diagonal matrix\n\tB₇=cat(M₇,H,dims=(1,2))\nend\n\n# ╔═╡ 75c00141-e691-4f9c-8b7a-ed262b88a62d\nbegin\n\tη₇=minimum(abs,eigvals(M₇)-eigvals(H))\n\tμ₇=eigvals(B₇)\n\t[λ₆ μ₇]\nend\n\n# ╔═╡ 433a0652-912f-4f59-8494-4d0381e22115\n2*norm(E)^2/(η₇+√(η₇^2+4*norm(E)^2))\n\n# ╔═╡ ad6ca597-65b2-4403-a6aa-1394399c3ed8\nbegin\n\t# Eigenspace bounds - Fact 16\n\tB₆=A₆+ΔA₆\n\tμ,V=eigen(B₆)\nend\n\n# ╔═╡ 4727c0ba-124e-41a4-861a-57eb5a6d849d\nbegin\n\t# sin(Θ(U[:,1:3],V[:,1:3]))\n\tX₆=U₆[:,1:3]\n\tQ=V[:,1:3]\n\tcosθ₆=svdvals(√(Q'*Q)*Q'*X₆*√(X₆'*X₆))\n\tsinθ₆=sqrt.(1 .-cosθ₆.^2)\nend\n\n# ╔═╡ dd00cbef-e1f6-43bc-95b0-1b6694c23583\n# Bound\nM₈=Q'*A₆*Q\n\n# ╔═╡ 99f44a10-b3e1-442c-a042-b2f0afad1797\nR₈=A₆*Q-Q*M₈\n\n# ╔═╡ b6f8f48e-2e80-4999-95a9-701d491411bd\neigvals(M₈), λ₆\n\n# ╔═╡ 7a6554bb-0518-4068-9784-678f846d3b3f\nbegin\n\tη₈=abs(eigvals(M₈)[3]-λ₆[4])\n\tnorm(sinθ₆), norm(R₈)/η₈\nend\n\n# ╔═╡ Cell order:\n# ╟─4ea41550-9313-11eb-1cdf-df6c5527f80f\n# ╟─7d3ed16e-50ea-4ede-b968-e32baa56f76f\n# ╟─da0d7094-fa3e-4f1e-a6f1-9d1b9316f65a\n# ╟─f8ba4230-9313-11eb-170c-ab58597826f8\n# ╠═4c360009-f01e-45bb-b458-29b15f8cac8f\n# ╠═7bd6f898-b86c-4670-96e8-9016666ee14f\n# ╠═8e1ced3a-d23d-4f5f-8c65-dc13ab392504\n# ╠═d9ef7b4b-4954-464a-96ac-e3f49800e0b7\n# ╟─90fcd9f5-d98c-4db6-bf30-21e377209681\n# ╟─8261b5ce-9315-11eb-2378-af63c3eb4c02\n# ╠═bb6eee61-c3ee-4b6a-ab44-a638fba776b8\n# ╠═060b8d2f-e6f3-4625-9cf6-d4cc504145fa\n# ╠═f55a3c60-9315-11eb-027a-dd008031f6f9\n# ╠═c4a1b888-9497-4eb4-aa1c-23671123f426\n# ╠═b46cbb6f-36f4-4a66-b970-8fe9b0506b6a\n# ╠═254b2df4-f57e-4284-a735-6fd5d4546c52\n# ╠═09fd0923-1987-4a2e-be28-78451aa2c11a\n# ╠═dcba6892-b90e-41ad-8d58-53e72d40e882\n# ╠═c765c02e-9316-11eb-146c-ff5d3ba81323\n# ╠═d948741f-6748-44d7-ae8c-cf074f7549bd\n# ╠═ec0746a1-41bd-4d61-9deb-8e227106e592\n# ╠═d92799f7-1813-450b-8353-9d03078f69f0\n# ╠═0d58d4c4-16c6-4a5b-bdbd-f3f599d0d648\n# ╠═b1a90c59-8c3e-4530-83ef-6b3e6c6fa687\n# ╠═31e73f82-93e7-448c-940b-5c9f5e573e5c\n# ╟─909033d9-bb27-4f0e-b07d-574f7fcee700\n# ╟─7ef162c0-5c80-4e96-bcc3-125b302b1d5e\n# ╟─3c8f71a5-0c2f-43a0-bf71-db9df707f84e\n# ╟─98fade4c-cdcb-495e-9328-96e86ca8e90e\n# ╠═8f064645-cf1f-4226-add4-53bc72665bf6\n# ╠═568366c7-3eee-4948-a096-7bf87537412d\n# ╠═fe46c02b-74bd-4303-8314-3b6e96b9e51a\n# ╠═c48aa813-8012-409f-9b08-ce9805da9cb3\n# ╠═f0bcadb5-882c-4e46-9079-b36097650435\n# ╠═21b412f3-f460-4f60-8b31-85c839566d62\n# ╠═6654b8d5-0c31-4a44-a16a-3f71e714ce31\n# ╠═3fbcbecd-6e69-49d0-94bf-06a4f6704858\n# ╠═210137a6-1b7b-4741-84d2-9d72e18cd999\n# ╟─e946019f-5e75-4195-8991-da371300e9a2\n# ╟─4723a4f9-af98-4f2d-8628-0ffc58488e62\n# ╠═f3d63eb6-0174-458c-aeef-46ed6d62db7f\n# ╠═b9770791-4fa6-4d3f-9688-ac79b7ae7f22\n# ╠═8112bf44-3146-4b9f-953a-54de6f4c8c5b\n# ╠═6b26afc1-e427-496e-b9a5-4618551aeede\n# ╠═b2a07659-cb08-4c53-99ac-32f817485062\n# ╠═989b7c60-c673-4b77-ada8-909db2904fa2\n# ╠═1da2bfee-6792-4aed-8798-91cc058cd540\n# ╠═a6769e47-59f7-430c-9c20-a121a98f19bf\n# ╠═fab42c40-7d01-4787-a491-3d37cae1768d\n# ╟─2f783e6e-5b29-477f-8b45-00461013c66f\n# ╠═9385e7e0-17d6-4840-98a2-fa69d53ebea3\n# ╠═18e6478b-bb8e-482c-bd02-0c85bca6fc7f\n# ╠═ae524f6a-3e64-49ea-92e3-671559f85a5f\n# ╟─9c0c9fcf-9581-479f-8ec5-d885dd3e6665\n# ╠═300e0ddd-3ab0-4803-9528-665e754e54ca\n# ╠═fdecade7-4d5c-460f-a566-d52868c75ec0\n# ╠═01250371-f8ab-4a0a-b283-ffbcffdc2929\n# ╠═0787f637-44bf-4c5c-b8d2-92df842a91b5\n# ╟─5645f7ea-50e5-43f7-afc3-1c46fbdd7c5b\n# ╠═51cd2fc5-e295-4b76-9fd1-fdd2b92ce05a\n# ╠═bc5a0ee0-931f-11eb-204c-b9e03584c787\n# ╠═1eb12479-0662-410b-9569-c4e8939a291f\n# ╠═821f6b8b-0e12-404b-b1dc-57d809ebf79b\n# ╠═ac3d3677-1160-4a79-a25f-8faa7fd89940\n# ╠═f4051f63-a0d3-4b43-8c61-2bbd08338a72\n# ╠═612870ba-75df-4729-a16e-432f70707fb4\n# ╠═3ba55b4b-5445-48a3-b327-b7d3af28397a\n# ╠═6f3da676-c953-4d23-8b9a-bb62b8b8ac94\n# ╠═886ce4f8-73a0-4b57-8d5e-082bcfc1f9aa\n# ╠═82a4adaa-3663-4200-9f15-d09fd4cd0259\n# ╠═b1025690-4244-4933-9693-9bbd3ad8aedb\n# ╠═5e69cab3-712c-4754-b6b1-579bc3c8e114\n# ╠═3792c478-fbaa-4683-849a-ca0d0cb751f3\n# ╠═0dd080f1-575d-43e0-9285-20279f390d2f\n# ╠═ea07eea3-bab7-4add-90cc-43acd7c2ec89\n# ╠═53f2860a-db33-49cd-b95e-3086f76c2592\n# ╠═8cdffcc2-c8c1-410e-95db-6327931782a1\n# ╠═0e871e72-47ee-4492-9f73-fcfd2ef1aada\n# ╠═108f73bc-b1cf-47ed-80f0-281cb5ebd048\n# ╠═dbc219f9-9fcf-4aac-b7d5-feb8fcafe3e9\n# ╠═7cae5501-8a51-4874-8b23-5825f79624e3\n# ╠═7cb49041-f326-4b2c-90f8-99c4d58178eb\n# ╠═75c00141-e691-4f9c-8b7a-ed262b88a62d\n# ╠═433a0652-912f-4f59-8494-4d0381e22115\n# ╠═ad6ca597-65b2-4403-a6aa-1394399c3ed8\n# ╠═4727c0ba-124e-41a4-861a-57eb5a6d849d\n# ╠═dd00cbef-e1f6-43bc-95b0-1b6694c23583\n# ╠═99f44a10-b3e1-442c-a042-b2f0afad1797\n# ╠═b6f8f48e-2e80-4999-95a9-701d491411bd\n# ╠═7a6554bb-0518-4068-9784-678f846d3b3f\n", "meta": {"hexsha": "1ce246a88da1f4ccb92d2cbf95ab08cba3f4d849", "size": 23863, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Module B - Eigenvalue and Singular Value Decompositions/L3b Eigenvalue Decomposition - Perturbation Theory.jl", "max_stars_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_stars_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2016-06-10T09:40:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:00:08.000Z", "max_issues_repo_path": "src/Module B - Eigenvalue and Singular Value Decompositions/L3b Eigenvalue Decomposition - Perturbation Theory.jl", "max_issues_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_issues_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Module B - Eigenvalue and Singular Value Decompositions/L3b Eigenvalue Decomposition - Perturbation Theory.jl", "max_forks_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_forks_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2016-06-21T14:20:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T17:03:59.000Z", "avg_line_length": 31.6485411141, "max_line_length": 412, "alphanum_fraction": 0.6755646817, "num_tokens": 12270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.863391624034103, "lm_q1q2_score": 0.766005017594905}}
{"text": "# Ilija Spasić PR 34-2020\n\n\"\"\"\n    generateArray(a,b,n=30)\n\nFunkcija za generisanje zadatog niza brojeva iz opsega **[1 ... 100]**,\nsa najmanje 30 elementa. Gde parametar **a** predstavlja početak opsega, parametar **b** kraj\nopsega, dok je parametar **n** opcioni parametar za broj elemenata generisanog niza.\n\"\"\"\nfunction generateArray(a::Int64, b::Int64, n::Int64=30)::Array{Int64}\n    if a < 1 || b > 100\n        error(\"Neispravan opseg funkcije. Za vise informacija upisite ?generateArray\")\n    end\n    X = [ ]\n    for _ in 1:n\n        push!(X, Int64(rand(a:b)))\n    end\n    return X\nend\n\n\"\"\"\n\n    bucketSort(X::Array, smer::String)\n\nFunkcija sortiranja niza primenom Bucket Sort algoritma. Gde smer uzima vrednosti\n**\"o\"** za sortiranje u opadajućem poretku i \n**\"r\"** za sortiranje u rastućem poretku\n\"\"\"\nfunction bucketSort(X::Array{Int64},smer::String=\"r\")\n    if smer != \"r\" && smer != \"o\"\n        error(\"Pogrešan parametar funkcije! Proverite ? bucketSort\")\n    end\n    rez = [ ]\n    M = maximum(X)\n    n = M/length(X)\n    buckets = [ ]\n    for _ in 1:length(X)\n        push!(buckets,[ ])\n    end\n    for i in 1:length(X)\n        j = Int64(floor((X[i]/n)))\n        j = j == 0 ? 1 : j\n        if j != length(X)\n            push!(buckets[j],X[i])\n        else\n            push!(buckets[length(X)-1],X[i])\n        end\n    end\n    for i in 1:length(X)\n        insertSortBucket(buckets[i],smer)\n    end\n    if smer == \"o\"\n        for i in 1:length(X)\n            rez = vcat(buckets[i],rez)\n        end\n    else\n        for i in 1:length(X)\n            rez = vcat(rez,buckets[i])\n        end\n    end\n    return rez\nend\n\n\"\"\"\n\n    insertSortBucket(x::Array)\n\nPomoćna funkcija za sortiranja podeljenih delova (bucket-a) kod\nBucket Sort algoritma koja koristi Insertion Sort algoritam.\n\"\"\"\nfunction insertSortBucket(x,smer)\n    for j in 2:length(x)\n        key = x[j]\n        i = j-1\n        while i>0 && (smer == \"o\" ? x[i] < key : x[i] > key)\n            x[i+1] = x[i]\n            i = i-1\n        end\n        x[i+1] = key\n    end\nend\n\n\n", "meta": {"hexsha": "347ea07823a9235459799b49ac370e0d6e86546f", "size": 2039, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Projekat/bucketSort.jl", "max_stars_repo_name": "pikacxe/Julia_Projects", "max_stars_repo_head_hexsha": "422c8d3cbea2282ccb9c5b3fc222241de21ff3ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Projekat/bucketSort.jl", "max_issues_repo_name": "pikacxe/Julia_Projects", "max_issues_repo_head_hexsha": "422c8d3cbea2282ccb9c5b3fc222241de21ff3ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Projekat/bucketSort.jl", "max_forks_repo_name": "pikacxe/Julia_Projects", "max_forks_repo_head_hexsha": "422c8d3cbea2282ccb9c5b3fc222241de21ff3ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2738095238, "max_line_length": 93, "alphanum_fraction": 0.5689063266, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8633916082162402, "lm_q1q2_score": 0.7660049984112731}}
{"text": "# lasso.jl - Lasso solvers based on FISTA and ADMM using ProximalOperators\n#\n#   minimize 0.5*||A*x - b||^2 + lam*||x||_1\n#\n\nusing LinearAlgebra\nusing Random\nusing ProximalOperators\n\nRandom.seed!(0)\n\n# Define solvers\n\nfunction lasso_fista(A, b, lam, x; tol=1e-3, maxit=50000)\n  x_prev = copy(x)\n  g = NormL1(lam)\n  gam = 1.0/norm(A)^2\n  for it = 1:maxit\n    # extrapolation step\n    x_extr = x + (it-2)/(it+1)*(x - x_prev)\n    # compute least-squares residual\n    res = A*x_extr - b\n    # compute gradient (forward) step\n    y = x_extr - gam*(A'*res)\n    # store current iterate\n    x_prev .= x\n    # compute proximal (backward) step\n    prox!(x, g, y, gam)\n    # stopping criterion\n    if norm(x_extr-x, Inf)/gam <= tol*(1+norm(x, Inf))\n      break\n    end\n  end\n  return x\nend\n\nfunction lasso_admm(A, b, lam, x; tol=1e-8, maxit=50000)\n  u = zero(x)\n  z = copy(x)\n  f = LeastSquares(A, b)\n  g = NormL1(lam)\n  gam = 100.0/norm(A)^2\n  for it = 1:maxit\n    # perform f-update step\n    prox!(x, f, z - u, gam)\n    # perform g-update step\n    prox!(z, g, x + u, gam)\n    # stopping criterion\n    if norm(x-z, Inf) <= tol*(1+norm(u, Inf))\n      break\n    end\n    # dual update\n    u .+= x - z\n  end\n  return z\nend\n\n# Generate random problem\n\nprintln(\"Generating random lasso problem\")\n\nm, n, k, sig = 500, 2500, 100, 1e-3\nA = randn(m, n)\nx_true = [randn(k)..., zeros(n-k)...]\nb = A*x_true + sig*randn(m)\nlam = 0.1*norm(A'*b, Inf)\n\n# Call solvers\n\nprintln(\"Calling solvers\")\n\nx_fista = lasso_fista(A, b, lam, zeros(n))\nprintln(\"FISTA\")\nprintln(\"      nnz(x)    = $(norm(x_fista, 0))\")\nprintln(\"      obj value = $(0.5*norm(A*x_fista-b)^2 + lam*norm(x_fista, 1))\")\n\nx_admm = lasso_admm(A, b, lam, zeros(n))\nprintln(\"ADMM\")\nprintln(\"      nnz(x)    = $(norm(x_admm, 0))\")\nprintln(\"      obj value = $(0.5*norm(A*x_admm-b)^2 + lam*norm(x_admm, 1))\")\n\n@test x_fista ≈ x_admm rtol=1e-3\n", "meta": {"hexsha": "a287784d2ede48ff1ee39f0a7cfd479f1e3e4e14", "size": 1875, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demos/lasso.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_stars_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2016-10-29T12:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:11:52.000Z", "max_issues_repo_path": "demos/lasso.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_issues_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2016-10-26T16:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T20:38:48.000Z", "max_forks_repo_path": "demos/lasso.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_forks_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T10:40:24.000Z", "avg_line_length": 22.5903614458, "max_line_length": 78, "alphanum_fraction": 0.5984, "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7659830661341301}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Statistics\n\tusing Random, Distributions, Plots\n\tRandom.seed!(0)\nend;\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.15\"\n\n# ╔═╡ 1aa41898-3afa-11eb-2f49-570853ce6435\nbegin\n\tmu, sig = 50, 5\n\tdist = Normal(mu, sig)\n\talpha = 0.01\n\tnMax = 40\n\n\tobservations = rand(dist,1)\n\tpiLarray, piUarray = [], []\nend;\n\n# ╔═╡ 0e5aed16-3b2f-11eb-2f7c-01f450cc5336\nfor _ in 2:nMax\n    xNew = rand(dist)\n    push!(observations,xNew)\n\n    xbar, sd = mean(observations), std(observations)\n    n = length(observations)\n    tVal = quantile(TDist(n-1),1-alpha/2)\n    delta = tVal * sd * sqrt(1+1/n)\n    piL, piU = xbar - delta, xbar + delta\n    \n    push!(piLarray,piL); push!(piUarray,piU)\nend\n\n# ╔═╡ 0e5b22c2-3b2f-11eb-2895-7d6e7267e6b6\nbegin\n\tscatter(1:nMax, observations, \n\t\tc=:blue, msw=0, label=\"Observations\")\n\tplot!(2:nMax, piUarray, \n\t\tc=:red, shape=:xcross, msw=0, label=\"Prediction Interval\")\n\tplot!(2:nMax, piLarray, \n\t\tc=:red, shape=:xcross, msw=0, label=\"\", \n\t\tylims=(0,100), xlabel=\"Number of observations\", ylabel=\"Value\")\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.15\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═1aa41898-3afa-11eb-2f49-570853ce6435\n# ╠═0e5aed16-3b2f-11eb-2f7c-01f450cc5336\n# ╠═0e5b22c2-3b2f-11eb-2895-7d6e7267e6b6\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "f191746ba9b7ed57f54f710bd3d9fd680556b41c", "size": 1655, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/06/listing6.15.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/06/listing6.15.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/06/listing6.15.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 24.3382352941, "max_line_length": 65, "alphanum_fraction": 0.6966767372, "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7659830617695897}}
{"text": "#Week 6\n#A\neq1=@equ δ=4m*M/(m+M)^2 #maximum fraction of energy transferable\neq2=@equ Te-Tgas=2qe*E^2/(3δ*me*vm^2) #∝p^-2, steady state\n\n#B\nb1=@equ d*Ṅ=Ṅ*α*d*x\nb2=@equ Ṅ=Ṅ0*exp(α*x)\nb3=@equ i=Ṅ0*e*exp(α*d) # =i0*exp(α*d) #current leaving the anode #should e be qe?\nb4=@equ i=i0*exp(α*d)/(1-γ*(exp(α*d)-1)) #sum of avalances\nb5=@equ γ*exp(α*d)=γ+1 #1-γ*(exp(α*d)-1)=0 #breakdown criterion\n\n#C\nc1=@equ α=A*p*exp(-B*p/E)\nc1b=@equ α=1/λ*exp(-ϵi/(e*E*λ))\nc1c=@equ α=A*p*exp(-B*p*d/V)\nc2=@equ E=V/d #for parallel plates\nc3=@equ VB=B*p*d/(log(A*p*d)-log(log(1+1/γ))) #breakdown voltage\nc3b=@equ VB=B*p*d/(log(C*p*d))\nc3c=@equ C=A/log(1+1/γ)\nc4=@equ Der(nj,t)+Dot(∇,Γj)=Sj\nc5=@equ Sj=ne*α*ue\nc6=@equ E=-∇V\nc7=@equ ∇^2*V=0\n#boundary conditions\nc8=@equ n*Γi_anode=0 #ions\nc9=@equ n*Γe_cathode=-γse*n*Γi_cathode\n\n#D\nd1=@equ Γi=ni*c̄i/4 #ion thermal flux\nd1b=@equ c̄i=sqrt(8*e*Ti/(pi*mi))\nd2=@equ Γe=ne*c̄e/4 #electron thermal flux\nd2b=@equ c̄e=sqrt(8*e*Te/(pi*me))\n\n#E\ne1=@equ 1/2*M*u^2+e*V=1/2*M*us^2\ne2=@equ ni*u=ns*us\ne3=@equ ni=ns*(1-2*e*V/(M*us^2))^(-0.5) #ion density in sheath\ne4=@equ ne=ns*exp(V/Te) #electron density in sheath\ne5=@equ Der(Der(V,x),x)=-(ni-ne)*e/ϵ0 #Poisson's euqation in sheath\ne6=@equ ub=sqrt(e*Te/M)#≤us #Bohm's criterion\ne7=@equ ns*uB=0.61n0*sqrt(e*Te/M) #ion flux to a wall\ne8=@equ e*ns*ub*A=0.61*e*A*n0*sqrt(e*Te/M) #ion current to a probe area A\ne9=@equ Vs=Te/2*log(M/(2*pi*m))#~4.7Te for argon #sheath voltage drop\ne10=@equ ϵi=e*Te/2*log(M/2.3m)#~5.2e*Te #Ion energy to a wall\n\n\n#Week 7\n#B\nb1=@equ ΔEf=ΔEα+ΔEn\nb2=@equ RDT*ΔEf=nD*nT*σDT*v*ΔEf\t#fusion power density, depends on v\nb3=@equ nD*nT*σv*ΔEf=1/4*n^2*σv*ΔEf #whole plasma, avg σv\nb4=@equ Pb/volume=A*n^2*Zeff*sqrt(Te) #Bremsstrahlung\nb4b=@equ A=5e-37 #Wm^-3\nb4c=@equ Zeff=nj*Zj^2/n #sum over j\nb5=@equ Pdl/volume=3n*T/τE #losses\nb6=@equ Q=Pf/Pin\nb7=@equ fα=Pα/(Pα+Pin)\nb8=@equ QE=(Pout_E-Pin_E)/Pin_E #conversion efficiency\nb8b=@equ Pin_E=Pin/ηe\nb8c=@equ Pout_E=ηt*(Pf+Pin)\n\n#C\nc1=@equ El=1/((ϵl*ϵth)^3*ϵc^4)*(n0/n)^2\t#driver energy\n\n#D\nd1=@equ thickness=1/(number_density*cross_section)\t#required wall thickness\nd2=@equ I=I0*exp(-x/λtot)\n\n#E\ne1=@equ Γr=D*Der(n,r)\n", "meta": {"hexsha": "3ee372e93fd897f3f4260998505c4ef8917479c7", "size": 2147, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "formularies/plasma.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Equations.jl-3a41ca7c-167c-5dd3-b068-80165705c037", "max_stars_repo_head_hexsha": "23b0a37f01006f8b370ac242f9915866e72af205", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-04-15T13:19:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:04:25.000Z", "max_issues_repo_path": "formularies/plasma.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Equations.jl-3a41ca7c-167c-5dd3-b068-80165705c037", "max_issues_repo_head_hexsha": "23b0a37f01006f8b370ac242f9915866e72af205", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2015-04-18T11:47:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:30:40.000Z", "max_forks_repo_path": "formularies/plasma.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Equations.jl-3a41ca7c-167c-5dd3-b068-80165705c037", "max_forks_repo_head_hexsha": "23b0a37f01006f8b370ac242f9915866e72af205", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-06-01T06:36:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:16:08.000Z", "avg_line_length": 29.8194444444, "max_line_length": 83, "alphanum_fraction": 0.650675361, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.8418256393148981, "lm_q1q2_score": 0.7659830491317341}}
{"text": "################################################################################\n## Linear Regression\n##   y ~ N(b0 + b1 * x, s2)\n##   b0, b1 ~ N(0, 1000)\n##   s2 ~ invgamma(0.001, 0.001)\n################################################################################\n\nusing Mamba\n\n## Data\ndata = Dict(\n  :x => [1, 2, 3, 4, 5],\n  :y => [1, 3, 3, 3, 5]\n)\n\n## Log-transformed Posterior(b0, b1, log(s2)) + Constant\nlogf = function(x::DenseVector)\n   b0 = x[1]\n   b1 = x[2]\n   logs2 = x[3]\n   r = data[:y] - b0 - b1 * data[:x]\n   (-0.5 * length(data[:y]) - 0.001) * logs2 -\n     (0.5 * dot(r, r) + 0.001) / exp(logs2) -\n     0.5 * b0^2 / 1000 - 0.5 * b1^2 / 1000\nend\n\n## MCMC Simulation with Slice Sampling\n## With multivariate (1) and univariate (2) updating\nn = 5000\nsim1 = Chains(n, 3, names = [\"b0\", \"b1\", \"s2\"])\nsim2 = Chains(n, 3, names = [\"b0\", \"b1\", \"s2\"])\nwidth = [1.0, 1.0, 2.0]\ntheta1 = SliceUnivariate([0.0, 0.0, 0.0], width, logf)\ntheta2 = SliceMultivariate([0.0, 0.0, 0.0], width, logf)\nfor i in 1:n\n  sample!(theta1)\n  sample!(theta2)\n  sim1[i, :, 1] = [theta1[1:2]; exp(theta1[3])]\n  sim2[i, :, 1] = [theta2[1:2]; exp(theta2[3])]\nend\ndescribe(sim1)\ndescribe(sim2)\n", "meta": {"hexsha": "940b144abd69237630b198907442ae5d3b7b6676", "size": 1177, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "doc/samplers/slice.jl", "max_stars_repo_name": "JuliaPackageMirrors/Mamba.jl", "max_stars_repo_head_hexsha": "61d716958902077d0c9e7030ae490153ac515ae1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/samplers/slice.jl", "max_issues_repo_name": "JuliaPackageMirrors/Mamba.jl", "max_issues_repo_head_hexsha": "61d716958902077d0c9e7030ae490153ac515ae1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/samplers/slice.jl", "max_forks_repo_name": "JuliaPackageMirrors/Mamba.jl", "max_forks_repo_head_hexsha": "61d716958902077d0c9e7030ae490153ac515ae1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-15T05:12:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-15T05:12:54.000Z", "avg_line_length": 27.3720930233, "max_line_length": 80, "alphanum_fraction": 0.4723874257, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7659830424593023}}
{"text": "# Hessian Eigenmaps (HLLE)\n# ---------------------------\n# Hessian eigenmaps: Locally linear embedding techniques for high-dimensional data,\n# D. Donoho and C. Grimes, Proc Natl Acad Sci U S A. 2003 May 13; 100(10): 5591–5596\n\nimport Combinatorics: combinations\n\n\"\"\"\n    HLLE{NN <: AbstractNearestNeighbors, T <: Real} <: AbstractDimensionalityReduction\n\nThe `HLLE` type represents a Hessian eigenmaps model constructed for `T` type data with a help of the `NN` nearest neighbor algorithm.\n\"\"\"\nstruct HLLE{NN <: AbstractNearestNeighbors, T <: Real} <: AbstractDimensionalityReduction\n    λ::AbstractVector{T}\n    proj::Projection{T}\n    nearestneighbors::NN\n    component::AbstractVector{Int}\nend\n\n## properties\noutdim(R::HLLE) = size(R.proj, 1)\neigvals(R::HLLE) = R.λ\nneighbors(R::HLLE) = R.nearestneighbors.k\nvertices(R::HLLE) = R.component\n\n## show\nsummary(io::IO, R::HLLE) = print(io, \"Hessian Eigenmaps(outdim = $(outdim(R)), neighbors = $(neighbors(R)))\")\n\n## interface functions\n\"\"\"\n    fit(HLLE, data; k=12, maxoutdim=2, nntype=BruteForce)\n\nFit a Hessian eigenmaps model to `data`.\n\n# Arguments\n* `data`: a matrix of observations. Each column of `data` is an observation.\n\n# Keyword arguments\n* `k`: a number of nearest neighbors for construction of local subspace representation\n* `maxoutdim`: a dimension of the reduced space.\n* `nntype`: a nearest neighbor construction class (derived from `AbstractNearestNeighbors`)\n\n# Examples\n```julia\nM = fit(HLLE, rand(3,100)) # construct Hessian eigenmaps model\nR = transform(M)          # perform dimensionality reduction\n```\n\"\"\"\nfunction fit(::Type{HLLE}, X::AbstractMatrix{T};\n             k::Int=12, maxoutdim::Int=2, nntype=BruteForce) where {T<:Real}\n    # Construct NN graph\n    NN = fit(nntype, X, k)\n    D, E = knn(NN, X)\n    G, C = largest_component(SimpleWeightedGraph(adjmat(D,E)))\n    XX = @view X[:, C]\n    n = length(C)\n\n    # Obtain tangent coordinates and develop Hessian estimator\n    hs = (maxoutdim*(maxoutdim+1)) >> 1\n    W = spzeros(T, hs*n, n)\n    for i=1:n\n        II = @view E[:,C[i]]\n        # re-center points in neighborhood\n        VX = view(XX, :, II)\n        μ = mean(VX, dims=2)\n        N = VX .- μ\n        # calculate tangent coordinates\n        tc = svd(N).V[:,1:maxoutdim]\n\n        # Develop Hessian estimator\n        Yi = [ones(T, k) tc zeros(T, k, hs)]\n        for ii=1:maxoutdim\n            Yi[:,maxoutdim+ii+1] = tc[:,ii].^2\n        end\n        yi = 2*(1+maxoutdim)\n        for (ii,jj) in combinations(1:maxoutdim, 2)\n            Yi[:, yi] = tc[:, ii] .* tc[:, jj]\n            yi += 1\n        end\n        F = qr(Yi)\n        H = transpose(F.Q[:,(end-(hs-1)):end])\n        W[(1:hs).+(i-1)*hs, II] = H\n    end\n\n    # decomposition\n    λ, V = decompose(transpose(W)*W, maxoutdim)\n    return HLLE{nntype, T}(λ, transpose(V) .* convert(T, sqrt(n)), NN, C)\nend\n\n\"\"\"\n    transform(R::LLE)\n\nTransforms the data fitted to the Hessian eigenmaps model `R` into a reduced space representation.\n\"\"\"\ntransform(R::HLLE) = R.proj\n", "meta": {"hexsha": "0e85e20b24bf5f7bb436cee5c53a980f33c41a0b", "size": 3003, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hlle.jl", "max_stars_repo_name": "yha/ManifoldLearning.jl", "max_stars_repo_head_hexsha": "29a97cce829f0ab8fb172ac27ddfcfff446596a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71, "max_stars_repo_stars_event_min_datetime": "2015-03-15T17:34:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T19:17:06.000Z", "max_issues_repo_path": "src/hlle.jl", "max_issues_repo_name": "yha/ManifoldLearning.jl", "max_issues_repo_head_hexsha": "29a97cce829f0ab8fb172ac27ddfcfff446596a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2015-02-13T17:18:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T21:36:26.000Z", "max_forks_repo_path": "src/hlle.jl", "max_forks_repo_name": "yha/ManifoldLearning.jl", "max_forks_repo_head_hexsha": "29a97cce829f0ab8fb172ac27ddfcfff446596a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2015-06-17T17:56:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T21:45:13.000Z", "avg_line_length": 31.28125, "max_line_length": 134, "alphanum_fraction": 0.6287046287, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342049451596, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7659693568310114}}
{"text": "\"\"\"\n    dirVector{FT}\nStruct for spherical coordinate directions in θ (elevation angle) and ϕ (azimuth angle)\n# Fields\n$(DocStringExtensions.FIELDS)\n\"\"\"\nstruct dirVector{FT}\n    θ::FT\n    ϕ::FT\nend\n\n\"\"\"\n    dirVector_μ{FT}\nStruct for spherical coordinate directions in θ (elevation angle) and ϕ (azimuth angle)\"\n# Fields\n$(DocStringExtensions.FIELDS)\n\"\"\"\nstruct dirVector_μ{FT}\n    μ::FT\n    ϕ::FT\nend \n\n# Define dot product for the directional vector in spherical coordinates:\nLinearAlgebra.dot(Ω₁::dirVector, Ω₂::dirVector) = cos(Ω₁.θ) * cos(Ω₂.θ) + sin(Ω₁.θ) * sin(Ω₂.θ) * cos(Ω₂.ϕ - Ω₁.ϕ)\n\n# Define dot product for the directional vector in spherical coordinates:\nLinearAlgebra.dot(Ω₁::dirVector_μ, Ω₂::dirVector_μ) = Ω₁.μ * Ω₂.μ + sqrt(1-Ω₁.μ^2)  * sqrt(1-Ω₂.μ^2) * cos(Ω₂.ϕ - Ω₁.ϕ)\n", "meta": {"hexsha": "5a2ad282dbc43aea172b9f72dcb516ce25fac806", "size": 788, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/types/angle_types.jl", "max_stars_repo_name": "RemoteSensingTools/CanopyOptics.jl", "max_stars_repo_head_hexsha": "ba8b699526036e34a2c6d169850fb313aa6b5f65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/types/angle_types.jl", "max_issues_repo_name": "RemoteSensingTools/CanopyOptics.jl", "max_issues_repo_head_hexsha": "ba8b699526036e34a2c6d169850fb313aa6b5f65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/types/angle_types.jl", "max_forks_repo_name": "RemoteSensingTools/CanopyOptics.jl", "max_forks_repo_head_hexsha": "ba8b699526036e34a2c6d169850fb313aa6b5f65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1428571429, "max_line_length": 119, "alphanum_fraction": 0.6979695431, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633822, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7659693564310479}}
{"text": "#\n#   Kepler.jl\n#\n#   Solves Kepler's problem for TwoBody orbits.\n#\n\n\"\"\"\nSolves Kepler's Problem for `orbit` and `Δtᵢ`.\n\"\"\"\nfunction kepler(r::AbstractVector, v::AbstractVector, μ::Number, Δt::Number = period(semimajor_axis(r,v,μ), μ); tol=1e-6, max_iter=100) \n\n    e, a, i, Ω, ω, ν = keplerian(r, v, μ)\n    T = period(a, μ)\n    conic_section = conic(e)\n\n    # Guess χ₀\n    if conic_section == Hyperbolic\n        χ₀ = sign(Δt) * √(-a) * log(ℯ, (-2 * μ / a * Δt) / (r ⋅ v + (sign(Δt) * √(-μ * a) * (1 - norm(r) / a))))\n    elseif conic_section == Parabolic\n        χ₀ = √(a) * tan(ν / 2)\n    else\n        Δt = mod(Δt, T)\n        χ₀ = √(μ) * Δt / a\n    end\n\n    # Iteratively solve for χ\n    # TODO: Compare loop vs. recursion performance here.\n    # There shouldn't be too large of a difference, since this tends\n    # to converge with only a few iterations.\n    χₙ, rₙ, ψ, C₂, C₃ = χₖ(χ₀, Δt, r, v, a, μ, tol=tol, max_iter=max_iter)\n\n    # Convert to a Orbit\n    f = 1 - χₙ^2 / norm(r) * C₂\n    ḟ = √(μ) / (norm(r) * rₙ) * χₙ * (ψ * C₃ - 1)\n    g = Δt - (χₙ^3 / √(μ)) * C₃\n    ġ = 1 - (χₙ^2 / rₙ) * C₂\n\n    return ((f * r) .+ (g * v), (ḟ * r) .+ (ġ * v))\nend\n\n\nfunction χₖ(χₙ, Δt, rᵢ₀, vᵢ₀, a, μ; iter=1, tol=1e-14, max_iter=100)\n    \n    r₀ = norm(rᵢ₀)\n    ψ = upreferred(χₙ^2 / a)\n\n    if ψ > tol\n        C₂ = (1 - cos(√(ψ))) /  ψ\n        C₃ = (√(ψ) - sin(√(ψ))) / √(ψ^3)\n    elseif ψ < -tol\n        C₂ = (1 - cosh(√(-ψ))) / ψ\n        C₃ = (sinh(√(-ψ)) - √(-ψ)) / √((-ψ)^3)\n    else\n        C₂ = 1.0 / 2.0\n        C₃ = 1.0 / 6.0\n    end\n\n    r = χₙ^2 * C₂ + (rᵢ₀ ⋅ vᵢ₀) * χₙ / √(μ) * (1 - ψ*C₃) + r₀ * (1 - ψ * C₂)\n    χₙ₊₁ = χₙ + ((√(μ) * Δt - χₙ^3 * C₃ - (rᵢ₀ ⋅ vᵢ₀) / √(μ) * χₙ^2 * C₂ - r₀ * χₙ * (1 - ψ * C₃)) / r)\n\n    if iter > max_iter\n        @error \"Failed to converge!\"\n        return χₙ, r, ψ, C₂, C₃\n    elseif abs(χₙ₊₁ - χₙ) < oneunit(χₙ) * tol\n        return  χₙ, r, ψ, C₂, C₃\n    else\n        return χₖ(χₙ₊₁, Δt, rᵢ₀, vᵢ₀, a, μ; iter=iter+1, tol=tol, max_iter=max_iter)\n    end\n    \nend", "meta": {"hexsha": "488f3cfd7cd044872e14a1c7a768aba11b7e7232", "size": 2007, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Calculations/R2BP/Kepler.jl", "max_stars_repo_name": "cadojo/SimpleAstrodynamics.jl", "max_stars_repo_head_hexsha": "0d1f704c0e85f687d5e92d34637ccc046570ef8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-05-25T00:32:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T23:31:08.000Z", "max_issues_repo_path": "src/Calculations/R2BP/Kepler.jl", "max_issues_repo_name": "cadojo/UnitfulAstrodynamics.jl", "max_issues_repo_head_hexsha": "c24888c1500450ea420169af4ca54dbd5bc99092", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2020-10-11T16:07:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-10T12:28:56.000Z", "max_forks_repo_path": "src/Calculations/R2BP/Kepler.jl", "max_forks_repo_name": "cadojo/UnitfulAstrodynamics.jl", "max_forks_repo_head_hexsha": "c24888c1500450ea420169af4ca54dbd5bc99092", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-28T12:13:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-28T12:13:09.000Z", "avg_line_length": 28.6714285714, "max_line_length": 136, "alphanum_fraction": 0.4778276034, "num_tokens": 1019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7659693558410714}}
{"text": "#=\r\nRegularisation of network.\r\nContains L1 and L2 regularisation as well as sparsity constraint for sparse\r\nencoder.\r\n=#\r\n\r\n\r\n################################################################################\r\n#\r\n# L1\r\n#\r\n################################################################################\r\n\r\n########################################\r\n# L1 Cost                                ∈ ℝ\r\n########################################\r\n\r\n# For each layer weight matrix\r\n# Jℓ₁ = λ ∑||Wᵢⱼ||    ∀ Wᵢⱼ\r\nfunction ℓ1_reg_cost(net)\r\n    Jᵣ = zero(net.dtype)\r\n    for ℓ in net.layers[2:end]\r\n\r\n        # No parameters in pooling layers\r\n        typeof(ℓ) <: PoolLayer && continue\r\n\r\n        # ∑||Wᵢⱼ||\r\n        Jᵣ += sumabs(ℓ.W)\r\n    end\r\n\r\n    # λ ∑||Wᵢⱼ||\r\n    Jᵣ *= net.λ\r\nend\r\n\r\n########################################\r\n# L1 Gradient                            ∈ ℝ^ num_feats\r\n########################################\r\n\r\n#=\r\nNote that an option to make the L1 gradient numerically stable is to make the\r\nfunction √(x²+ϵ). This would make the function smooth around x=0.\r\n=#\r\n# ∂Jℓ₂/∂Wᵢⱼ = λ sign(Wᵢⱼ)    ∀ Wᵢⱼ\r\n# Added to the gradient in-place\r\nfunction ℓ1_reg_grad!(net)\r\n    for ℓ in net.layers[2:end]\r\n\r\n        # No parameters in pooling layers\r\n        typeof(ℓ) <: PoolLayer && continue\r\n\r\n        # ∇W := λ sign(W) + ∇W\r\n        BLAS.axpy!(net.λ, sign(ℓ.W), ℓ.∇W)\r\n    end\r\nend\r\n\r\n\r\n################################################################################\r\n#\r\n# L2 (Weight Decay)\r\n#\r\n################################################################################\r\n\r\n########################################\r\n# L2 Cost                                ∈ ℝ\r\n########################################\r\n\r\n# Jℓ₂ = (λ/2) ∑||Wᵢⱼ||²    ∀ Wᵢⱼ\r\nfunction ℓ2_reg_cost(net)\r\n    Jᵣ = zero(net.dtype)\r\n    for ℓ in net.layers[2:end]\r\n\r\n        # No parameters in pooling layers\r\n        typeof(ℓ) <: PoolLayer && continue\r\n\r\n        # ∑||Wᵢⱼ||²\r\n        Jᵣ += sumabs2(ℓ.W)\r\n    end\r\n\r\n    # (λ/2) ∑||Wᵢⱼ||²\r\n    Jᵣ *= net.λ * net.dtype(0.5)\r\nend\r\n\r\n########################################\r\n# L2 Gradient                            ∈ ℝ^ num_feats\r\n########################################\r\n\r\n# ∂Jℓ₂/∂Wᵢⱼ = λ Wᵢⱼ    ∀ Wᵢⱼ\r\n# Added to the gradient in-place\r\nfunction ℓ2_reg_grad!(net)\r\n    for ℓ in net.layers[2:end]\r\n\r\n        # No parameters in pooling layers\r\n        typeof(ℓ) <: PoolLayer && continue\r\n\r\n        # ∇W := λ W + ∇W\r\n        BLAS.axpy!(net.λ, ℓ.W, ℓ.∇W)\r\n    end\r\nend\r\n\r\n\r\n################################################################################\r\n#\r\n# L1 and L2 Dictionaries (for user selections through api)\r\n#\r\n################################################################################\r\n\r\nreg_cost_dict = Dict{Symbol, Function}(:L1 => ℓ1_reg_cost, :L2 => ℓ2_reg_cost)\r\nreg_grad_dict = Dict{Symbol, Function}(:L1 => ℓ1_reg_grad!, :L2 => ℓ2_reg_grad!)\r\n\r\n\r\n\r\n################################################################################\r\n#\r\n# Sparsity (KL Divergence of Bernoulli means)\r\n#\r\n################################################################################\r\n\r\n########################################\r\n# KL Divergence                          ∈ ℝ\r\n########################################\r\n\r\n# Sum of KL Divergences between a Bernoulli random variable with mean p and a\r\n# vector of Bernoulli random variables with mean p̂\r\nfunction kl_div_sum{F<:AbstractFloat}(p̂::Vector{F}, p::F)\r\n    s = F(0)\r\n    for j in eachindex(p̂)\r\n        @inbounds s += (p * log(p / p̂[j]) +\r\n                        (F(1) - p) * log((F(1) - p) / (F(1) - p̂[j])))\r\n    end\r\n    return s\r\nend\r\n\r\n# Sparsity cost function for the net\r\nfunction sparse_cost(net)\r\n    J = zero(net.dtype)\r\n    for ℓ in net.layers[2:end-1]\r\n\r\n        # Only for sparse encoder layers\r\n        !(typeof(ℓ) <: SparseEncoderLayer) && continue\r\n\r\n        # β ∑ˢ KL(p || p̂)\r\n        J += ℓ.β * kl_div_sum(ℓ.p̂, ℓ.p)\r\n    end\r\n    return J\r\nend\r\n\r\n########################################\r\n# Sparsity Gradient                      ∈ ℝ^ num_feats\r\n########################################\r\n\r\nfunction delta_sparse!{F<:AbstractFloat}(Δ::Array{F}, spgrad::Vector{F},\r\n                                         p̂::Vector{F}, p::F, β::F, m::F)\r\n    for j in eachindex(p̂)\r\n        @inbounds spgrad[j] = (- p / p̂[j] + (F(1) - p) / (F(1) - p̂[j])) * β / m\r\n    end\r\n    broadcast!(+, Δ, spgrad, Δ)\r\nend\r\n", "meta": {"hexsha": "e54370661fd7ed677c0d9d24a8fb525c3dfb78d6", "size": 4394, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/regularisation.jl", "max_stars_repo_name": "Wedg/Alice.jl", "max_stars_repo_head_hexsha": "48884d8dfaca3f987e69423dfc63e1f0881c7dc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/regularisation.jl", "max_issues_repo_name": "Wedg/Alice.jl", "max_issues_repo_head_hexsha": "48884d8dfaca3f987e69423dfc63e1f0881c7dc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/regularisation.jl", "max_forks_repo_name": "Wedg/Alice.jl", "max_forks_repo_head_hexsha": "48884d8dfaca3f987e69423dfc63e1f0881c7dc7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8101265823, "max_line_length": 82, "alphanum_fraction": 0.3830223031, "num_tokens": 1180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342049451595, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7659693522812749}}
{"text": "import PolynomialApproximations: Remez\nusing SpecialFunctions: erfcx\nusing PyPlot\n\nT = Float64\n\nfunction g(y::T) where T <: AbstractFloat\n    if -one(T) ≤ y ≤ -one(T) + eps(T)\n        return one(T)\n    elseif one(T) - eps(T) ≤ y ≤ one(T)\n        return zero(T)\n    else\n        x = (1+y) / (1-y)\n        return erfcx(x)\n    end\nend\n\nfunction erfcx_approx(x)\n    if x < one(T)\n        y = (x-1) / (x+1)\n    else\n        rx = 1 / x\n        y = (1-rx) / (1+rx)\n    end\n    return g_approx(y)\nend\n\nn = 15\niterations = 6\nclamp = :both\nddp, pt, zmax, zmin = Remez.minimax(T, g, n, iterations, clamp)\n\ng_approx(y) = Remez.Newton_poly(ddp, pt, y)\n\nfigure(1)\ny = range(-one(T), one(T), length=201)\n\nplot(y, g.(y))\ngrid(true)\nxlabel(L\"$y$\")\nylabel(L\"$g(y)$\")\n\nfigure(2)\nplot(y, g.(y)-g_approx.(y))\ngrid(true)\nxlabel(L\"$y$\")\nylabel(L\"error in $g$\")\n\nfigure(3)\nx = Float64[ 10 * (n/400)^2 for n = 0:400 ]\nplot(x, erfcx_approx.(x) - erfcx.(x))\ngrid(true)\nxlabel(L\"$x$\")\nylabel(\"error in erfcx\")\n", "meta": {"hexsha": "157f2af248b98d3f31bc8685ad4bef4fb731bc77", "size": 982, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/clamp_erfcx_Remez.jl", "max_stars_repo_name": "billmclean/MittagLefflerFunctions.jl", "max_stars_repo_head_hexsha": "5244e7fce7efeee160edfc76eb7cab5e7624ae8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/clamp_erfcx_Remez.jl", "max_issues_repo_name": "billmclean/MittagLefflerFunctions.jl", "max_issues_repo_head_hexsha": "5244e7fce7efeee160edfc76eb7cab5e7624ae8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/clamp_erfcx_Remez.jl", "max_forks_repo_name": "billmclean/MittagLefflerFunctions.jl", "max_forks_repo_head_hexsha": "5244e7fce7efeee160edfc76eb7cab5e7624ae8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8545454545, "max_line_length": 63, "alphanum_fraction": 0.5723014257, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.8104789178257653, "lm_q1q2_score": 0.7658982938060439}}
{"text": "function compute_angle(origin,point)\r\n\r\n    degree = atan((origin[2] - point[2]),(point[1] - origin[1])) * (180/pi)\r\n    if degree > 90\r\n        degree = 450 - degree\r\n    else\r\n        degree = 90 - degree\r\n    end\r\n    return degree\r\nend\r\n\r\nfunction compute_distance(origin,point)\r\n    distance = sqrt((origin[1] - point[1])^2 + (origin[2] - point[2])^2)\r\n    return distance\r\nend\r\n\r\nf = open(\"day10.txt\");\r\nast_list = []\r\nfor (y, line) in enumerate(readlines(f))\r\n    for (x, value) in enumerate(line)\r\n        if value == '#'\r\n            push!(ast_list,[x-1,y-1])\r\n        end\r\n\r\n    end\r\nend\r\ndetected = -1\r\nstation = -1\r\nfor ast in ast_list\r\n    detected_angles = Set()\r\n    for other in ast_list\r\n        if ast != other\r\n            push!(detected_angles,compute_angle(ast,other))\r\n        end\r\n    end\r\n    if length(detected_angles) > detected\r\n        global detected\r\n        global station\r\n        detected = length(detected_angles)\r\n        station = ast\r\n    end\r\nend\r\n\r\nprintln(detected)\r\nprintln(station)\r\n\r\nfilter!(x->x!=station,ast_list)\r\n\r\nangle_dict = Dict()\r\nfor ast in ast_list\r\n    angle = compute_angle(station,ast)\r\n\r\n    if haskey(angle_dict, angle) == false\r\n        push!(angle_dict,angle=>[ast])\r\n    else\r\n        value = angle_dict[angle]\r\n        append!(value,[ast])\r\n    end\r\nend\r\niter = 0\r\nfor angle in sort([i for i in keys(angle_dict)],by=abs)\r\n    remove = typemax(Float64)\r\n    vaporized = nothing\r\n    for i in angle_dict[angle]\r\n        dist = compute_distance(station,i)\r\n        if dist < remove\r\n            remove = dist\r\n            vaporized = i\r\n        end\r\n    end\r\n    global iter\r\n    iter += 1\r\n    if iter == 200\r\n        solution = vaporized[1]*100 + vaporized[2]\r\n        println(\"Vaporize $vaporized, solution is $solution\")\r\n        break\r\n    end\r\nend\r\n", "meta": {"hexsha": "d339223c6774d962c42d800697754f88627d35f2", "size": 1815, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day10.jl", "max_stars_repo_name": "TseIvan/AdventOfCode2019", "max_stars_repo_head_hexsha": "e1749eeed59f9509311c76046c4fe852a9211ef1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day10.jl", "max_issues_repo_name": "TseIvan/AdventOfCode2019", "max_issues_repo_head_hexsha": "e1749eeed59f9509311c76046c4fe852a9211ef1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day10.jl", "max_forks_repo_name": "TseIvan/AdventOfCode2019", "max_forks_repo_head_hexsha": "e1749eeed59f9509311c76046c4fe852a9211ef1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9746835443, "max_line_length": 76, "alphanum_fraction": 0.5730027548, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083137, "lm_q2_score": 0.8104789040926007, "lm_q1q2_score": 0.7658982758061726}}
{"text": "cd(@__DIR__)\nusing DifferentialEvolutionMCMC, Random, KernelDensity, Distributions\ninclude(\"KDE.jl\")\n\nfunction loglike(data, μ, σ)\n    simdata = rand(Normal(μ, σ), 10_000)\n    kd = kernel(simdata)\n    dist = InterpKDE(kd)\n    like = max.(1e-10, pdf(dist, data))\n    return sum(log.(like))\nend\n\n# returns prior log likelihood\nfunction prior_loglike(μ, σ)\n    LL = 0.0\n    LL += logpdf(Normal(0, 1), μ)\n    LL += logpdf(truncated(Cauchy(0, 1), 0, Inf), σ)\n    return LL\nend\n\n# function for initial values\nfunction sample_prior()\n    μ = rand(Normal(0, 1))\n    σ = rand(truncated(Cauchy(0, 1), 0, Inf))\n    return [μ,σ]\nend\n\n# parameter names\nnames = (:μ,:σ)\n# parameter bounds\nbounds = ((-Inf,Inf),(0.0,Inf))\n\ndata = rand(Normal(0.0, 1.0), 50)\n\n\n# model object\nmodel = DEModel(; \n    sample_prior, \n    prior_loglike, \n    loglike, \n    data,\n    names\n)\n\n# DEMCMC sampler object\nde = DE(;sample_prior, bounds, burnin = 1000, Np = 6)\n# number of interations per particle\nn_iter = 2000\nchains = sample(model, de, MCMCThreads(), n_iter, progress=true)", "meta": {"hexsha": "8157ad664c2157dbade025013ac5abcfb105b083", "size": 1047, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/KDE_Example.jl", "max_stars_repo_name": "itsdfish/DifferentialEvolutionMCMC.jl", "max_stars_repo_head_hexsha": "3974509006e3df0eef74cf82be71586f2045d421", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-06-22T07:03:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T06:47:34.000Z", "max_issues_repo_path": "Examples/KDE_Example.jl", "max_issues_repo_name": "itsdfish/DifferentialEvolutionMCMC.jl", "max_issues_repo_head_hexsha": "3974509006e3df0eef74cf82be71586f2045d421", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 40, "max_issues_repo_issues_event_min_datetime": "2020-05-28T11:51:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T11:59:22.000Z", "max_forks_repo_path": "Examples/KDE_Example.jl", "max_forks_repo_name": "itsdfish/DifferentialEvolutionMCMC.jl", "max_forks_repo_head_hexsha": "3974509006e3df0eef74cf82be71586f2045d421", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3673469388, "max_line_length": 69, "alphanum_fraction": 0.6523400191, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100817, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7658982754580824}}
{"text": "\nusing Flux, StochasticDiffEq\nusing NeuralPDE\nusing Plots\nusing CUDA\n\n\nfunction phi(xi)\n    y = Float64[]\n    K = 100\n    for x in eachcol(xi)\n        val = max(K - maximum(x) , 0.00)\n        y = push!(y , val)\n    end\n    y = reshape(y , 1 , size(y)[1] )\n    return y\nend\n\n\nd = 1\nr = 0.04\nsigma = 0.2\nxspan = (80.00 , 115.0)\ntspan = (0.0 , 1.0)\nσ(du , u , p , t) = du .= sigma.*u\nμ(du , u , p , t) = du .= r.*u\nprob = KolmogorovPDEProblem(μ , σ , phi , xspan , tspan, d)\n\n\nsdealg = EM()\nensemblealg = EnsembleThreads()\ndt = 0.01\ndx = 0.01\ntrajectories = 100000\n\n\nm = Chain(Dense(d, 64, elu),Dense(64, 128, elu),Dense(128 , 16 , elu) , Dense(16 , 1))\nuse_gpu = false\nif CUDA.functional() == true\n  m = fmap(CUDA.cu , m)\n  use_gpu = true\nend\nopt = Flux.ADAM(0.0005)\n\n\n@time sol = solve(prob, NeuralPDE.NNKolmogorov(m, opt, sdealg, ensemblealg), verbose = true, dt = dt,\n            dx = dx , trajectories = trajectories , abstol=1e-6, maxiters = 1000 , use_gpu = use_gpu)\n\n\nmonte_carlo_sol = []\nx_out = collect(85:2.00:110.00)\nfor x in x_out\n  u₀= [x]\n  g_val(du , u , p , t) = du .= 0.2.*u\n  f_val(du , u , p , t) = du .= 0.04.*u\n  dt = 0.01\n  tspan = (0.0,1.0)\n  prob = SDEProblem(f_val,g_val,u₀,tspan)\n  output_func(sol,i) = (sol[end],false)\n  ensembleprob_val = EnsembleProblem(prob , output_func = output_func )\n  sim_val = solve(ensembleprob_val, EM(), EnsembleThreads() , dt=0.01, trajectories=100000,adaptive=false)\n  s = reduce(hcat , sim_val.u)\n  mean_phi = sum(phi(s))/length(phi(s))\n  global monte_carlo_sol = push!(monte_carlo_sol , mean_phi)\nend\n\n\nx_model = reshape(x_out, 1 , size(x_out)[1])\nif use_gpu == true\n  m = fmap(cpu , m)\nend\ny_out = m(x_model)\ny_out = reshape(y_out , 13 , 1)\n\n\nplot(x_out , y_out , lw = 3 ,  xaxis=\"Initial Stock Price\", yaxis=\"Payoff\" , label = \"NNKolmogorov\")\nplot!(x_out , monte_carlo_sol , lw = 3 ,  xaxis=\"Initial Stock Price\", yaxis=\"Payoff\" ,label = \"Monte Carlo Solutions\")\n\n\nusing SciMLTutorials\nSciMLTutorials.tutorial_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])\n\n", "meta": {"hexsha": "223278598e31685448faef7947b16e38cf312350", "size": 2017, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/advanced/03-kolmogorov_equations.jl", "max_stars_repo_name": "SciML/SciMLTutorialsOutput", "max_stars_repo_head_hexsha": "f66779faa9eb1dc131c1adfe8099f26f09afc458", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-05-24T10:30:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T12:13:03.000Z", "max_issues_repo_path": "script/advanced/03-kolmogorov_equations.jl", "max_issues_repo_name": "SciML/SciMLTutorialsOutput", "max_issues_repo_head_hexsha": "f66779faa9eb1dc131c1adfe8099f26f09afc458", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-07T21:39:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T03:48:31.000Z", "max_forks_repo_path": "script/advanced/03-kolmogorov_equations.jl", "max_forks_repo_name": "SciML/SciMLTutorialsOutput", "max_forks_repo_head_hexsha": "f66779faa9eb1dc131c1adfe8099f26f09afc458", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-24T14:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T14:30:36.000Z", "avg_line_length": 24.3012048193, "max_line_length": 119, "alphanum_fraction": 0.6341100645, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8221891370573386, "lm_q1q2_score": 0.7658383532410098}}
{"text": "export cohens_d\n\n\"\"\"\n    cohens_d(μ1, μ2, s)\n    cohens_d(n1, μ1, s1, n2, μ2, s2)\n    cohens_d(A::Array, B::Array)\n\nEffect size according to Cohen's d for means `μ1` and `μ2`, number of samples `n1` and `n2`, and standard deviations `s1` and `s2` for respectively group 1 and 2.\n\"\"\"\ncohens_d(μ1, μ2, s) = (μ1 - μ2) / s\ns_pooled(n1, s1, n2, s2) = sqrt(\n    ( (n1 - 1) * s1^2 + (n2 - 1) * s2^2 ) /\n    ( n1 + n2 - 2)\n)\ns_pooled(A::Array, B::Array) = s_pooled(length(A), std(A), length(B), std(B))\ncohens_d(A::Array, B::Array) = cohens_d(mean(A), mean(B), s_pooled(A, B))\ncohens_d(n1, μ1, s1, n2, μ2, s2) = cohens_d(μ1, μ2, s_pooled(n1, s1, n2, s2))\n\n\"\"\"\n    accuracy(trues, preds)::Number\n\nThe number of correct predictions in `pred` (by comparing `true` to `prediction`) divided by the total number of predictions.\n\"\"\"\naccuracy(trues, preds)::Number = count(trues .== preds) / length(preds)\n", "meta": {"hexsha": "019caf48a3e2e6599b0e20be748ad555b9c64820", "size": 890, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stats.jl", "max_stars_repo_name": "rikhuijzer/Codex.jl", "max_stars_repo_head_hexsha": "c7e14b2731f5350ffcc11ed5a8a362a7fd672b1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stats.jl", "max_issues_repo_name": "rikhuijzer/Codex.jl", "max_issues_repo_head_hexsha": "c7e14b2731f5350ffcc11ed5a8a362a7fd672b1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-01-12T08:51:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-17T12:53:35.000Z", "max_forks_repo_path": "src/stats.jl", "max_forks_repo_name": "rikhuijzer/Codex.jl", "max_forks_repo_head_hexsha": "c7e14b2731f5350ffcc11ed5a8a362a7fd672b1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6, "max_line_length": 162, "alphanum_fraction": 0.6269662921, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.765838352311264}}
{"text": "export WLS, RandomCascade\nusing Wavelets, Statistics\n\n\"\"\"\n    WLS(shufflemethod::Surrogate = IAAFT();\n        f::Union{Nothing, Function} = Statistics.cor,\n        rescale::Bool = true,\n        wt::Wavelets.WT.OrthoWaveletClass = Wavelets.WT.Daubechies{16}())\n\nA wavelet surrogate generated by the following procedure:\n\n1. Compute the wavelet transform of the signal. This results in a set of \n    detail coefficients over a set of dyadic scales. As in Keylock (2006), \n    we here use the maximal overlap discrete wavelet transform, or MODWT,\n    so that the number of coefficients at each scale are the same.\n2. Shuffle the detail coefficients at each dyadic scale using the \n    provided `shufflemethod`. See \"Shuffling methods\" below for alternatives.\n3. Apply the inverse wavelet transform to the shuffled detail coefficients \n    to obtain a surrogate time series.\n\n## Shuffling methods\n\nYou may choose to use any surrogate from this package to perform the \nrandomization of the detail coefficients at each dyadic scale.\n\nThe following methods have been discussed in the literature (more may exist): \n\n- Random permutations of wavelet coefficients within each scale (Breakspear et al., 2003). To get this behaviour, use `WLS(x, RandomShuffle(), rescale = false, f = nothing)`.\n- Cyclic rotation of wavelet coefficients within each scale (Breakspear et al., 2003).  To get this behaviour, use `WLS(x, Circshift(1:length(x)), rescale = false, f = nothing)`.\n- Block resampling of wavelet coefficients within each scale (Breakspear et al., 2003). To get this behaviour, use `WLS(x, BlockShuffle(nblocks, randomize = true), rescale = false, f = nothing)`.\n- IAAFT resampling of wavelet coefficients within each scale (Keylock, 2006). To get this behaviour, use `WLS(x, IAAFT(), rescale = true, f = Statistics.cor)`.\n    This method preserves the local mean and variance structure of the signal, but \n    randomises nonlinear properties of the signal (i.e. Hurst exponents)[^Keylock2006]. \n    These surrogates can therefore be used to test for changes in nonlinear properties \n    of the original signal. In contrast to IAAFT surrogates, the IAAFT-wavelet surrogates \n    also preserves nonstationarity. Using other `shufflemethod`s does not necessarily\n    preserve nonstationarity. To deal with nonstationary signals, Keylock (2006) recommends \n    using a wavelet with a high number of vanishing moments. Thus, our default is to\n    use a Daubechies wavelet with 16 vanishing moments. *Note: The iterative procedure after \n    the rank ordering step (step [v] in [^Keylock2006]) is not performed in \n    this implementation.*\n\nThe default method and parameters replicate the behaviour of Keylock (2006)'s IAAFT \nwavelet surrogates.\n\n## Error minimization \n\nFor the [`IAAFT`](@ref) approach introduced in Keylock (2006), detail coefficients \nat each level are circularly rotated to minimize an error function. The methods \nintroduced in Breakspear et al. (2003) do not apply this error minimization.\n\nIn our implementation, you can turn this option on/off using the `f` parameter of \nthe `WLS` constructor. If `f = nothing` turns off error minization. If `f` is set \nto a two-argument function that computes some statistic, for example \n`f = Statistics.cor`, then detail coefficients at each scale are circularly \nrotated until that function is maximized (and hence the \"error\" minimized). \nIf you want to *minimize* some error function, then instead provide an appropriate \ntransform of your function. For example, if using the root mean squared deviation,\ndefine `rmsd_inv(x, y) = 1 - StatsBase.rmsd(x, y)` and set `f = rmsd_inv`.\n\n## Rescaling \n\nIf `rescale == true`, then surrogate values are mapped onto the \nvalues of the original time series, as in the [`AAFT`](@ref) algorithm.\nIf `rescale == false`, surrogate values are not constrained to the \noriginal time series values. If [`AAFT`](@ref) or [`IAAFT`](@ref) shuffling \nis used, `rescale` should be set to `true`. For other methods, it does not \nnecessarily need to be.\n\n[^Breakspear2003]: Breakspear, M., Brammer, M., & Robinson, P. A. (2003). Construction of multivariate surrogate sets from nonlinear data using the wavelet transform. Physica D: Nonlinear Phenomena, 182(1-2), 1-22.\n[^Keylock2006]: C.J. Keylock (2006). \"Constrained surrogate time series with preservation of the mean and variance structure\". Phys. Rev. E. 73: 036707. doi:10.1103/PhysRevE.73.036707.\n\"\"\"\nstruct WLS{WT <: Wavelets.WT.OrthoWaveletClass, S <: Surrogate, E <: Union{Nothing, Function}} <: Surrogate\n    shufflemethod::Surrogate # should preserve values of the original series\n    rescale::Bool\n    f::E\n    wt::WT\n\n    function WLS(method::S = IAAFT(); rescale::Bool = true, wt::WT = Wavelets.WT.Daubechies{16}(), f::E = Statistics.cor) where {S <: Surrogate, WT <: Wavelets.WT.OrthoWaveletClass, E <: Union{Nothing, Function}}\n        new{WT, S, E}(method, rescale, f, wt)\n    end\nend\n\n# Initialize without error minimization.\nfunction get_init_noerrorminimize(x, method, rng = Random.default_rng())\n    wl = wavelet(method.wt)\n    L = length(x)\n    x_sorted = sort(x)\n\n    # Wavelet coefficients (step [i] in Keylock)\n    W = modwt(x, wl)\n    T = eltype(W)\n    R = zeros(size(W))\n\n    Nscales = ndyadicscales(L)\n\n    # Will contain surrogate realizations of the wavelet coefficients \n    # at each scale (step [ii] in Keylock). \n    sW = zeros(T, size(W))\n\n    # Surrogate generators for each set of coefficients\n    sgs = [surrogenerator(W[:, i], method.shufflemethod, rng) for i = 1:Nscales]\n\n    init = (\n        wl = wl, \n        W = W, \n        Nscales = Nscales, \n        sW = sW, \n        sgs = sgs,\n        x_sorted = x_sorted,\n        R = R,\n    )\n\n    return init\nend\n\n# Initialize error minimization, as in Keylock (2006).\nfunction get_init_errorminimize(x, method::WLS, rng = Random.default_rng())\n    wl = wavelet(method.wt)\n    L = length(x)\n    x_sorted = sort(x)\n\n    # Wavelet coefficients (step [i] in Keylock)\n    W = modwt(x, wl)\n    T = eltype(W)\n    Nscales = ndyadicscales(L)\n\n    # Will contain surrogate realizations of the wavelet coefficients \n    # at each scale (step [ii] in Keylock). \n    sW = zeros(T, size(W))\n\n    # We will also need a matrix to store the mirror images of the \n    # surrogates (last part of step [ii])\n    sWmirr = zeros(T, size(W))\n\n    # Surrogate generators for each set of coefficients\n    sgs = [surrogenerator(W[:, i], method.shufflemethod, rng) for i = 1:Nscales]\n\n    # Temporary array for the circular shift error minimizing step \n    circshifted_s = zeros(T, size(W))\n    circshifted_smirr = zeros(T, size(W))\n    R = zeros(size(W))\n\n    s = similar(x)\n\n    init = (wl = wl, W = W, Nscales = Nscales, L = L, \n            sW = sW, sgs = sgs, sWmirr = sWmirr, \n            circshifted_s = circshifted_s,\n            circshifted_smirr = circshifted_smirr,\n            x_sorted = x_sorted, R = R,\n    )\n\n    return init\nend\n\nfunction surrogenerator(x::AbstractVector{T}, method::WLS, rng = Random.default_rng()) where T\n    init = isnothing(method.f) ? \n        get_init_noerrorminimize(x, method, rng) : \n        get_init_errorminimize(x, method, rng)\n\n    s = similar(x)\n\n    return SurrogateGenerator(method, x, s, init, rng)\nend\n\nfunction (sg::SurrogateGenerator{<:WLS})()\n    if isnothing(sg.method.f)\n        wls_noerrorminimize(sg)\n    else\n        wls_errorminimize(sg)\n    end\nend\n\nfunction wls_noerrorminimize(sg::SurrogateGenerator{<:WLS}) \n    s = sg.s\n\n    fds = (:wl, :W, :Nscales, :sW, :sgs, :x_sorted, :R)\n    wl, W, Nscales, sW, sgs, x_sorted, R = getfield.(Ref(sg.init), fds)\n\n    for λ in 1:Nscales\n        sW[:, λ] .= sgs[λ]()\n    end\n\n    s .= imodwt(sW, wl)\n\n    if sg.method.rescale\n        s[sortperm(s)] .= x_sorted\n    end\n\n    return s\nend\n\nfunction wls_errorminimize(sg::SurrogateGenerator{<:WLS})\n    s = sg.s\n\n    # Error minimization function (if we reached this function, \n    # f is never `Nothing`), so we can use it safely.\n    f = sg.method.f \n\n    fds = (:wl, :W, :Nscales, :L, :sW, :sgs, :sWmirr, \n        :circshifted_s, :circshifted_smirr,\n        :x_sorted, :R)\n\n    wl, W, Nscales, L, sW, sgs, sWmirr, \n        circshifted_s, circshifted_smirr,\n        x_sorted, R = getfield.(Ref(sg.init), fds)\n\n    # Create surrogate versions of detail coefficients at each dyadic scale [first part of step (ii) in Keylock]   \n    for λ in 1:Nscales\n        sW[:, λ] .= sgs[λ]()\n    end\n\n    # Mirror the surrogate coefficients [last part of step (ii) in Keylock]   \n    sWmirr .= reverse(sW, dims = 1)\n\n    # In the original paper, surrogates and mirror images are matched to original \n    # detail coefficients in a circular manner until some error criterion is \n    # minimized. Then, the surrogate or its mirror image, depending on which provides \n    # the best fit to the original coefficients, is chosen as the representative\n    # for a particular dyadic scale. Here, we instead use maximal correlation as \n    # the criterion for matching.\n    optimal_shifts = zeros(Int, Nscales)\n    optimal_shifts_mirr = zeros(Int, Nscales)\n    maxcorrs = zeros(Nscales)\n    maxcorrs_mirr = zeros(Nscales)\n\n    for i in 0:L-1\n        circshift!(circshifted_s, sW, (i, 0))\n        circshift!(circshifted_smirr, sWmirr, (i, 0))\n\n        for λ in 1:Nscales\n            origW = W[:, λ]\n            c = f(origW, circshifted_s[:, λ])\n            if c > maxcorrs[λ]\n                maxcorrs[λ] = c\n                optimal_shifts[λ] = i\n            end\n\n            c_mirr = f(origW, circshifted_smirr[:, λ])\n            if c_mirr > maxcorrs_mirr[λ]\n                maxcorrs_mirr[λ] = c_mirr\n                optimal_shifts_mirr[λ] = i\n            end\n        end\n    end\n\n    # Decide which coefficients are retained (either surrogate or mirror surrogate coefficients)\n    for λ in 1:Nscales\n        if maxcorrs[λ] >= maxcorrs_mirr[λ]\n            R[:, λ] .= circshift(sW[:, λ], optimal_shifts[λ])\n        else \n            R[:, λ] .= circshift(sWmirr[:, λ], optimal_shifts_mirr[λ])\n        end\n    end\n\n    s .= imodwt(R, wl)\n\n    if sg.method.rescale\n        s[sortperm(s)] .= x_sorted\n    end\n\n    return s\nend\n\n\"\"\"\n    RandomCascade(paddingmode::String = \"zeros\")\n\nA random cascade multifractal wavelet surrogate (Paluš, 2008)[^Paluš2008].\n\nIf the input signal length is not a power of 2, the signal must be \npadded before the surrogate is constructed. `paddingmode` determines \nhow the signal is padded. Currently supported padding modes: `\"zeros\"`.\nThe final surrogate (constructed from the padded signal) is subset\nto match the length of the original signal.\n\nRandom cascade surrogate preserve multifractal properties of the input \ntime series, that is, interactions among dyadic scales and nonlinear \ndependencies[^Paluš2008].\n\n[^Paluš2008]: Paluš, Milan (2008). Bootstrapping Multifractals: Surrogate Data from Random Cascades on Wavelet Dyadic Trees. Physical Review Letters, 101(13), 134101–. doi:10.1103/PhysRevLett.101.134101\n\"\"\"\nstruct RandomCascade{WT <: Wavelets.WT.OrthoWaveletClass} <: Surrogate\n    wt::WT\n    paddingmode::String\n\n    function RandomCascade(; wt::WT = Wavelets.WT.Daubechies{16}(), paddingmode::String = \"zeros\") where {WT <: Wavelets.WT.OrthoWaveletClass}\n        new{WT}(wt, paddingmode)\n    end\nend\n\nfunction surrogenerator(x::AbstractVector{T}, method::RandomCascade, rng = Random.default_rng()) where T\n    nlevels = ndyadicscales(length(x))\n    mode = method.paddingmode\n\n    # Pad input so that input to discrete wavelet transform has length which is a power of 2\n    x̃ = zeros(2^(nlevels + 1))\n    if mode == \"zeros\"\n        copyto!(x̃, x)\n    else\n        throw(ArgumentError(\"\"\"`paddingmode` must be one of [\"zeros\"]\"\"\"))\n    end\n\n    wl = wavelet(method.wt)\n\n    # Wavelet coefficients (step [i] in Keylock)\n    c = dwt(x̃, wl, nlevels)\n\n    # Surrogate coefficients will be partly identical to original coefficients, \n    # so we simply copy them and replace the necessary coefficients later.\n    cₛ = copy(c)\n\n    # Multiplication factors and index vectors can be pre-allocated for\n    # levels 2:nlevels-1; they are overwritten for each new surrogate.\n    Ms = [zeros(dyadicdetailn(j-1)) for j = 2:nlevels-1]\n    ixs = [zeros(Int, dyadicdetailn(j-1)) for j = 2:nlevels-1]\n\n    init = (\n        wl = wl,\n        c = c, \n        cₛ = cₛ,\n        nlevels = nlevels,\n        s̃ = similar(x̃),\n        Ms = Ms,\n        ixs = ixs,\n    )\n\n    return SurrogateGenerator(method, x, similar(x), init, rng)\nend\n\nfunction (sg::SurrogateGenerator{<:RandomCascade})()\n    s, rng = sg.s, sg.rng\n    c, cₛ, s̃, wl, nlevels, Ms, ixs = \n        sg.init.c, sg.init.cₛ, sg.init.s̃, sg.init.wl, sg.init.nlevels, sg.init.Ms, sg.init.ixs\n\n    cₛ[dyadicdetailrange(0)] = @view c[dyadicdetailrange(0)]\n    cₛ[dyadicdetailrange(1)] = @view c[dyadicdetailrange(1)]\n\n    for (l, j) = enumerate(2:nlevels-1)\n        cⱼ₋₁ = @view c[dyadicdetailrange(j - 1)]\n        cⱼ = @view c[dyadicdetailrange(j)]\n\n        M = Ms[l]\n        ct = 1\n        @inbounds for k = 1:length(cⱼ₋₁)\n            if k % 2 == 0\n                M[ct] = cⱼ[2*k] / cⱼ₋₁[k]\n            else \n                M[ct] = cⱼ[2*(k+1)] / cⱼ₋₁[k+1]\n            end\n            ct += 1\n        end\n\n        shuffle!(rng, M)\n        new_coeffs!(M, cⱼ₋₁)\n        ix = ixs[l]\n        sortperm!(ix, M)\n        cₛ[dyadicdetailrange(j-1)] .= @view cⱼ₋₁[ix]\n    end\n    s̃ .= idwt(cₛ, wl, nlevels)\n\n    # Surrogate length must match length of original signal.\n    s .= @view s̃[1:length(s)]\n    return s\nend\n\nfunction new_coeffs!(M, cⱼ₋₁)\n    @inbounds for k = 1:length(cⱼ₋₁)\n        M[k] = M[k] * cⱼ₋₁[k]\n    end\nend\n", "meta": {"hexsha": "c80320367c9927e3b513229f4f69e4809f5af303", "size": 13615, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/methods/wavelet_based.jl", "max_stars_repo_name": "kahaaga/TimeseriesSurrogates.jl", "max_stars_repo_head_hexsha": "d96f32cc4501b3e2b4a07c54af23b75a1e6d6033", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-09-08T02:48:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-22T20:40:48.000Z", "max_issues_repo_path": "src/methods/wavelet_based.jl", "max_issues_repo_name": "kahaaga/TimeseriesSurrogates.jl", "max_issues_repo_head_hexsha": "d96f32cc4501b3e2b4a07c54af23b75a1e6d6033", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2018-05-15T14:44:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-06T13:11:31.000Z", "max_forks_repo_path": "src/methods/wavelet_based.jl", "max_forks_repo_name": "kahaaga/TimeseriesSurrogates.jl", "max_forks_repo_head_hexsha": "d96f32cc4501b3e2b4a07c54af23b75a1e6d6033", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-12-23T10:00:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:03:07.000Z", "avg_line_length": 36.6981132075, "max_line_length": 214, "alphanum_fraction": 0.663312523, "num_tokens": 4000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7658383513815177}}
{"text": "raw\"\"\"\nComputes Cholesky decomposition of a Hermitian positive-definite matrix A, i.e.,\n\n$$\nA = L L^*\n$$\n\nwhere $L$ is a lower triangular matrix with real and positive diagonal entries, and $L^*$ denotes\nthe conjugate transpose of $L$.\n\"\"\"\nmodule CholeskyDecomposition\n\nusing LinearAlgebra\n\nexport\n    cholesky_outer_product_decompose,\n    cholesky_banachiewicz_decompose,\n    cholesky_crout_decompose\n\nfunction get_n(A::Matrix)::Int\n    (n_r, n_c) = size(A)\n    @assert n_r == n_c \"Input matrix is not square\"\n    n_r\nend\n\n\"\"\"\nThe Cholesky (outer-product) algorithm\n\n<https://en.wikipedia.org/wiki/Cholesky_decomposition#The_Cholesky_algorithm>\n\"\"\"\nfunction cholesky_outer_product_decompose(A::Matrix{T})::LowerTriangular{T} where T<:Number\n    n = get_n(A)\n\n    # Some edge case values:\n    #\n    #     A_1 = A\n    #     A_{n + 1} = I(n)\n    #     I_i ∈ ℜ_{i ^ 2}\n    #     I_0 = ∅\n    #     L_0 = I(n)\n    #     B_0 = A\n    #     B_i ∈ ℂ_{(n - i) ^ 2}\n    #     B_n = ∅\n\n    A_i = copy(A)\n    A = nothing  # prevents accidental assignment\n    L_0 = T.(I(n)) |> Matrix |> LowerTriangular\n    L = copy(L_0)  # The product of L1...Ln\n    for i in 1:n\n        # Makes aliases (no need for `A_ii`)\n        b_i = @view A_i[(i + 1):end, i]\n        b_i_H = @view A_i[i, (i + 1):end]\n        B_i = @view A_i[(i + 1):end, (i + 1):end]\n\n        L_i = copy(L_0)\n        sqrtAii = sqrt(A_i[i, i])\n        L_i[i, i] = sqrtAii\n        L_i[(i + 1):end, i] = b_i / sqrtAii\n\n        L *= L_i\n\n        # Mind the order\n        B_i .-= b_i * transpose(b_i_H) / A_i[i, i]  # Ugly, can't do `b_i * b_i_H`\n        b_i .= 0.0\n        b_i_H .= 0.0\n        A_i[i, i] = 1.0\n    end\n    L\nend\n\n\"\"\"\nThe Cholesky-Banachiewicz algorithm\n\n<https://en.wikipedia.org/wiki/Cholesky_decomposition#The_Cholesky–Banachiewicz_and_Cholesky–Crout_algorithms>\n\"\"\"\nfunction cholesky_banachiewicz_decompose(A::Matrix{T})::LowerTriangular{T} where T<:Number\n    n = get_n(A)\n    # To write the in-place version, just set `L = A` and do symmetric updating.\n    L = zeros(T, n, n) |> LowerTriangular\n\n    # Note that as $A$ is positive-definite, **not positive semi-definite**, $L_{ii}$ will never be\n    # zero, so there is no need to check.\n    #\n    # Also, do NOT use `dot` to compute `L[r, c]`!\n\n    for r in 1:n\n        for c in 1:(r - 1)\n            L[r, c] = (\n                A[r, c] - sum((@view L[r, 1:(c - 1)]) .* conj.(@view L[c, 1:(c - 1)]))\n            ) / L[c, c]\n        end\n        l = @view L[r, 1:(r - 1)]\n        L[r, r] = sqrt(A[r, r] - l ⋅ l)\n    end\n    L\nend\n\n\"\"\"\nThe Cholesky-Crout algorithm\n\nIt is similar to the Cholesky-Banachiewicz algorithm, but processes column by column instead of row\nby row.\n\"\"\"\nfunction cholesky_crout_decompose(A::Matrix{T})::LowerTriangular{T} where T<:Number\n    n = get_n(A)\n    L = zeros(T, n, n) |> LowerTriangular\n    # Deliberately write the index as `:` rather than `1:(c - 1)`\n    for c in 1:n\n        l = @view L[c, :]\n        L[c, c] = sqrt(A[c, c] - l ⋅ l)\n        for r in (c + 1):n\n            L[r, c] = (A[r, c] - sum((@view L[r, :]) .* conj.(@view L[c, :]))) / L[c, c]\n        end\n     end\n     L\nend\n\nend  # module\n", "meta": {"hexsha": "f8c426a573514174b3edf2d6134131f2e9324968", "size": 3142, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CholeskyDecomposition/src/CholeskyDecomposition.jl", "max_stars_repo_name": "gyk/TrivialSolutions", "max_stars_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T05:51:37.000Z", "max_issues_repo_path": "CholeskyDecomposition/src/CholeskyDecomposition.jl", "max_issues_repo_name": "gyk/TrivialSolutions", "max_issues_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CholeskyDecomposition/src/CholeskyDecomposition.jl", "max_forks_repo_name": "gyk/TrivialSolutions", "max_forks_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4033613445, "max_line_length": 110, "alphanum_fraction": 0.5652450668, "num_tokens": 1107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7658383451243843}}
{"text": "plan_clenshawcurtis(μ) = length(μ) > 1 ? FFTW.plan_r2r!(μ, FFTW.REDFT00) : ones(μ)'\n\n\"\"\"\nCompute nodes of the Clenshaw—Curtis quadrature rule.\n\"\"\"\nclenshawcurtisnodes(::Type{T}, N::Int) where T = T[cospi(k/(N-one(T))) for k=0:N-1]\n\n\"\"\"\nCompute weights of the Clenshaw—Curtis quadrature rule with modified Chebyshev moments of the first kind ``\\\\mu``.\n\"\"\"\nclenshawcurtisweights(μ::Vector) = clenshawcurtisweights!(copy(μ))\nclenshawcurtisweights!(μ::Vector) = clenshawcurtisweights!(μ, plan_clenshawcurtis(μ))\nfunction clenshawcurtisweights!(μ::Vector{T}, plan) where T\n    N = length(μ)\n    rmul!(μ, inv(N-one(T)))\n    plan*μ\n    μ[1] *= half(T); μ[N] *= half(T)\n    return μ\nend\n\n\n\n# Chebyshev-T coefficients to values at Clenshaw-Curtis nodes\n\napplyTN_plan(x) = length(x) > 1 ? FFTW.plan_r2r!(x, FFTW.REDFT00) : fill!(similar(x),1)'\n\napplyTN!(x::Vector{T}) where {T<:AbstractFloat} = applyTN!(x,applyTN_plan(x))\n\nfunction applyTN!(x::Vector{T},plan) where T<:AbstractFloat\n    x[1] *= 2; x[end] *=2\n    plan*x\n    rmul!(x,half(T))\nend\napplyTN(x::Vector{T},plan) where {T<:AbstractFloat} = applyTN!(copy(x),plan)\napplyTN(x::Vector{T}) where {T<:AbstractFloat} = applyTN!(copy(x))\n\n# Values at Clenshaw-Curtis nodes to Chebyshev-T coefficients\n\napplyTNinv_plan(x) = length(x) > 1 ? FFTW.plan_r2r!(x, FFTW.REDFT00) : ones(x)'\n\napplyTNinv!(x::Vector{T}) where {T<:AbstractFloat} = applyTNinv!(x,applyTNinv_plan(x))\n\nfunction applyTNinv!(x::Vector{T},plan) where T<:AbstractFloat\n    plan*x\n    x[1] /= 2;x[end] /= 2\n    rmul!(x,inv(length(x)-one(T)))\nend\napplyTNinv(x::Vector{T},plan) where {T<:AbstractFloat} = applyTNinv!(copy(x),plan)\napplyTNinv(x::Vector{T}) where {T<:AbstractFloat} = applyTNinv!(copy(x))\n\n# sin(nθ) coefficients to values at Clenshaw-Curtis nodes except ±1\n\napplyUN_plan(x) = length(x) > 0 ? FFTW.plan_r2r!(x, FFTW.RODFT00) : fill!(similar(x),1)'\n\napplyUN!(x::AbstractVector{T}) where {T<:AbstractFloat} = applyUN!(x,applyUN_plan(x))\n\nfunction applyUN!(x::AbstractVector{T},plan) where T<:AbstractFloat\n    plan*x\n    rmul!(x,half(T))\nend\napplyUN(x::AbstractVector{T},plan) where {T<:AbstractFloat} = applyUN!(copy(x),plan)\napplyUN(x::AbstractVector{T}) where {T<:AbstractFloat} = applyUN!(copy(x))\n", "meta": {"hexsha": "c1510be90e0b4547650b9be922d874d4e0f39c2c", "size": 2219, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/clenshawcurtis.jl", "max_stars_repo_name": "putianyi889/FastTransforms.jl", "max_stars_repo_head_hexsha": "491716260d0b8de4aa3b9bab15c98a8f8ce59970", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-04-25T21:42:35.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-25T21:42:35.000Z", "max_issues_repo_path": "src/clenshawcurtis.jl", "max_issues_repo_name": "putianyi889/FastTransforms.jl", "max_issues_repo_head_hexsha": "491716260d0b8de4aa3b9bab15c98a8f8ce59970", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/clenshawcurtis.jl", "max_forks_repo_name": "putianyi889/FastTransforms.jl", "max_forks_repo_head_hexsha": "491716260d0b8de4aa3b9bab15c98a8f8ce59970", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2222222222, "max_line_length": 114, "alphanum_fraction": 0.6890491212, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8221891218080991, "lm_q1q2_score": 0.765838343729765}}
{"text": "# This implements src/snes/examples/tutorials/ex2.c from PETSc using the PETSc.jl package, using SNES\n#\n# This solves the equations sequentially\n# \n# Newton method to solve u'' + u^{2} = f, sequentially.\n\nusing PETSc, MPI, LinearAlgebra, SparseArrays, UnicodePlots\n\nif ~MPI.Initialized()\n    MPI.Init()\nend\n\npetsclib = PETSc.petsclibs[1]\nPETSc.initialize(petsclib)\n\n\"\"\"    \n    Computes initial guess \n\"\"\"\nfunction FormInitialGuess!(x)\n    for i=1:length(x)\n        x[i] = 0.50;\n    end\nend\n\n\"\"\" \n    Computes rhs forcing function \n\"\"\" \nfunction SetInitialArrays(n)\n    h =  1.0/(n-1.0)\n    F = zeros(n);\n    xp = 0.0;\n    for i=1:n \n        v    = 6.0*xp + (xp+1.e-12)^6.0; \n        F[i] = v;\n        xp   = xp+h;\n    end\n\n    return F\nend\n\n\"\"\"\n    Computes the residual f, given solution vector x\n\"\"\"\nfunction FormResidual!(cf,cx, args...)\n    if typeof(cx) <: Ptr{Nothing}\n        # When this routine is called from PETSc, cx is a pointer to a global vector\n        # That's why we have to transfer it first to \n        x   =   PETSc.unsafe_localarray(PETSc.scalartype(petsclib),cx)\n    else\n        x   = cx;\n    end\n    if typeof(cf) <: Ptr{Nothing}\n        f   =   PETSc.unsafe_localarray(PETSc.scalartype(petsclib),cf)\n    else\n        f   = cf;\n    end\n    n       =   length(x);\n    xp      =   LinRange(0.0,1.0, n);\n    F       =   6.0.*xp .+ (xp .+1.e-12).^6.0;      # define source term function\n    \n    dx      =   1.0/(n-1.0);\n    f[1]    =   x[1] - 0.0;\n    for i=2:n-1\n        f[i] = (x[i-1] - 2.0*x[i] + x[i+1])/dx^2 + x[i]*x[i] - F[i]\n    end\n    f[n]    =   x[n] - 1.0;\n    Base.finalize(x)\n    Base.finalize(f)\n\nend\n\n\n\"\"\"\n    Computes the jacobian, given solution vector x\n\"\"\"\nfunction FormJacobian!(cx, args...)\n\n    if typeof(cx) <: Ptr{Nothing}\n        x   =   PETSc.unsafe_localarray(PETSc.scalartype(petsclib),cx)\n    else\n        x   =   cx;\n    end\n\n    J   =   args[1];        # preconditioner = args[2], in case we want it to be different from J\n    n   =   length(x);\n    dx  =   1.0/(n-1.0);\n    \n    # interior points (hand-coded jacobian)\n    for i=2:n-1\n        J[i,i-1] = 1.0/dx^2;\n        J[i,i  ] = -2.0/dx^2 + 2.0*x[i];\n        J[i,i+1] = 1.0/dx^2;\n    end\n\n    # boundary points\n    J[1,1] = 1.0;\n    J[n,n] = 1.0;\n  \n    if typeof(J) <: PETSc.AbstractMat\n        PETSc.assemble(J);  # finalize assembly\n    \n    end\n\n    Base.finalize(x)\nend\n\n\n# ==========================================\n# Main code \n\n\n# Compute initial solution\nn   =   21;\nF   =   SetInitialArrays(n);\nx   =   zeros(n);\n\nFormInitialGuess!(x);\n\n# Compute initial jacobian using a julia structure to obtain the nonzero structure\n# Note that we can also obtain this structure in a different manner\nJstruct  = zeros(n,n);\nFormJacobian!(x, Jstruct);                              # jacobian in julia form\nJsp      =   sparse(Float64.(abs.(Jstruct) .> 0))       # sparse julia, with 1.0 in nonzero spots\nPJ       =   PETSc.MatSeqAIJ(Jsp);                      # transfer to \n\n# Setup snes\nx_s = PETSc.VecSeq(x);                  # solution vector\nres = PETSc.VecSeq(F);     # residual vector\n\nS = PETSc.SNES{Float64}(PETSc.petsclibs[1],MPI.COMM_WORLD; \n        snes_rtol=1e-12, \n        snes_monitor=false,\n        snes_converged_reason=false);\nPETSc.setfunction!(S, FormResidual!, res)\nPETSc.setjacobian!(S, FormJacobian!, PJ, PJ)\n\n# solve\nPETSc.solve!(x_s, S);\n\n# Extract & plot solution\nx_sol = x_s.array;                  # convert solution to julia format\nFormResidual!(res.array,x_sol)      # just for checking, compute residual\n\n@show norm(res.array)\n\nPETSc.finalize(petsclib)\n\n# plot solution in REPL\nlineplot(LinRange(0,1,n),x_sol,xlabel=\"width\",ylabel=\"solution\")\n", "meta": {"hexsha": "ee105c57ff8d01e1b552a8516c7e5dea82fc63a1", "size": 3678, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/SNES_ex2.jl", "max_stars_repo_name": "xj361685640/PETSc.jl", "max_stars_repo_head_hexsha": "eb034ed60ae6d2c9bc1554fb3deda36cec3fc398", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 87, "max_stars_repo_stars_event_min_datetime": "2015-10-19T06:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T07:17:42.000Z", "max_issues_repo_path": "examples/SNES_ex2.jl", "max_issues_repo_name": "xj361685640/PETSc.jl", "max_issues_repo_head_hexsha": "eb034ed60ae6d2c9bc1554fb3deda36cec3fc398", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 118, "max_issues_repo_issues_event_min_datetime": "2015-10-13T01:42:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-07T22:13:21.000Z", "max_forks_repo_path": "examples/SNES_ex2.jl", "max_forks_repo_name": "xj361685640/PETSc.jl", "max_forks_repo_head_hexsha": "eb034ed60ae6d2c9bc1554fb3deda36cec3fc398", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2015-10-24T18:21:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:20:35.000Z", "avg_line_length": 24.52, "max_line_length": 101, "alphanum_fraction": 0.5701468189, "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.7658065893455639}}
{"text": "export angular_distance, along_line_angular_distance, angular_length\n# export angular_distance, distance, along_line_angular_distance, angular_length\n# \"\"\"\n#     Radius Earth [m]\n#\n# Source: en.wikipedia.org/wiki/Earth_radius\n# \"\"\"\n# const Rₑ_m = 6371008.7714\n\n\"\"\"\n    angular_distance(point₁::Point, point₂::Point)\n\nReturn the `angular_distance` [deg] of the great circle line between the\npositions `point₁` [deg] and `point₂` [deg] on a unit sphere.\n\nSource: www.movable-type.co.uk/scripts/latlong.html\n\"\"\"\nfunction angular_distance(point₁::Point, point₂::Point)\n    Δpos = point₂ - point₁\n    a = sind(Δpos.ϕ/2.0)^2 + cosd(point₁.ϕ)*cosd(point₂.ϕ)*sind(Δpos.λ/2.0)^2\n    c = 2.0 * atand(√a, √(1.0 - a))\n    return c\nend\n\n\"\"\"\n    angular_length(arc::Arc)\n\nReturn the `angular_length` [deg] of the great circle line section on a\nunit sphere.\n\"\"\"\nangular_length(arc::Arc) =\nangular_distance(arc.point₁, arc.point₂)\n\n\"\"\"\n    angular_length(points::Vector{Points{Float64}})\n\nReturn the `angular_length` [deg] along the subsequent points on a unit sphere.\n\"\"\"\nfunction angular_length(points::Vector{Point{Float64}})\n    point₁ = points[1]\n    dist_deg = 0.0\n    for point₂ in points[2:end]\n        dist_deg += angular_distance(point₁, point₂)\n        point₁ = point₂\n    end\n    return dist_deg\nend\n\n\"\"\"\n    angular_length(arcs::Arcs)\n\nReturn the `angular_length` [deg] along the arcs on a unit sphere.\n\"\"\"\nangular_length(arcs::Arcs) = angular_length(arcs.points)\n\n\"\"\"\n    angular_length(polygon::Polygon)\n\nReturn the `angular_length` [deg] (e.g. circumference) along the polygon on a unit\nsphere.\n\"\"\"\nangular_length(polygon::Polygon) = angular_length(polygon.points)\n\n# \"\"\"\n#     distance(angular_distance::Float64, radius::Float64=Rₑ_m)\n#\n# Convert the `angular_distance` [deg] into a distance on a sphere of given radius\n#  [m]. The default radius is the radius of the Earth.\n# \"\"\"\n# function distance(angular_distance::Float64, radius::Float64=Rₑ_m)\n#     return deg2rad(angular_distance) * radius\n# end\n\n\"\"\"\n    angular_distance(point₃::Point, point₁::Point, azimuth₁₂::Float64)\n\nReturn the `angular_distance` [deg] from point₃ [deg] to the closest point on a\ngreat circle line starting in `point₁` [deg] with `azimuth₁₂` [deg] from\n`point₁` to `point₂`. It is assumed that the great circle line does not stop in\n`point₂`, but continuous around the unit sphere. A positive value indicates\nbeing right of the line, and negative being left of the line.\n\nSource: www.movable-type.co.uk/scripts/latlong.html\n\"\"\"\nfunction angular_distance(point₃::Point, point₁::Point, azimuth₁₂::Float64)\n    angular_distance₁₃ = angular_distance(point₁, point₃)\n    azimuth₁₃ = azimuth(point₁, point₃)\n    return angular_distance(angular_distance₁₃, azimuth₁₃, azimuth₁₂)\nend\n\n\"\"\"\n    angular_distance(point₃::Point, line₁::Line)\n\nReturn the `angular_distance` [deg] from point₃ [deg] to the closest point on a\ngreat circle line starting in `point₁` [deg] with `azimuth₁₂` [deg]. A positive\nvalue indicates being right of the line, and negative being left of the line.\n\nSource: www.movable-type.co.uk/scripts/latlong.html\n\"\"\"\nangular_distance(point₃::Point, line₁::Line) = angular_distance(point₃,\nline₁.point, line₁.azimuth)\n\n\"\"\"\n    angular_distance(angular_distance₁₃::Float64, azimuth₁₃::Float64,\n    azimuth₁₂::Float64)\n\nReturn the `angular_distance` [deg] from point₃ [deg] to the closest point on a\ngreat circle line starting in `point₁` [deg] with `azimuth₁₂` [deg]. For the\ncalculation we need the `angular_distance₁₃` and `azimuth₁₃` between `point₁`\nand `point₃` [deg], and the `azimuth₁₂` from `point₁` to `point₂` along the\ngreat circle line. It is assumed that the great circle line does not stop in\n`point₂`, but continuous around the unit sphere.\n\nSource: www.movable-type.co.uk/scripts/latlong.html\n\"\"\"\nfunction angular_distance(angular_distance₁₃::Float64, azimuth₁₃::Float64,\nazimuth₁₂::Float64)\n    return asind(sind(angular_distance₁₃) * sind(azimuth₁₃ - azimuth₁₂))\nend\n\n\"\"\"\n    angular_distance(point₃::Point, point₁::Point, point₂::Point)\n\nReturn the `angular_distance` [deg] from point₃ [deg] to the closest point on a\ngreat circle line section starting in `point₁` [deg] and ending in `point₂` [deg].\nThe great circle line section does not continue around the unit sphere.\n\nThe `angular_distance` does not change sign when being left or right of the arc.\n\"\"\"\nfunction angular_distance(point₃::Point, point₁::Point, point₂::Point, tolerance::Float64=tolerance_deg)\n    angular_distance₁₂ = angular_distance(point₁, point₂)\n    angular_distance₁₃ = angular_distance(point₁, point₃)\n    angular_distance₂₃ = angular_distance(point₂, point₃)\n    azimuth₁₂ = azimuth(point₁, point₂)\n    angular_distance_line3 = angular_distance(point₃, point₁, azimuth₁₂)\n    # along_line_angular_dist = along_line_angular_distance(angular_distance₁₃,\n    # angular_distance_line3)\n    along_line_pnt_3a = along_line_point(point₃, Line(point₁, azimuth₁₂))\n    if abs(angular_distance(along_line_pnt_3a, point₁) +\n        angular_distance(along_line_pnt_3a, point₂) -\n        angular_distance₁₂) < tolerance\n        return abs(angular_distance_line3)\n    else\n        return min(angular_distance₁₃, angular_distance₂₃)\n    end\nend\n\n\"\"\"\n    angular_distance(point₃::Point, points::Vector{Points{T}}) where T<:Float64\n\nReturn the `angular_distance` [deg] from point₃ [deg] to the closest point on a\nan set of points representing an set of arcs.\n\nThe `angular_distance` does not change sign when being left or right of the arc.\n\"\"\"\nfunction angular_distance(point₃::Point, points::Vector{Point{T}}) where\n    T<:Float64\n    point₁ = points[1]\n    point₂ = points[2]\n    min_dist = angular_distance(point₃, point₁, point₂)\n    point₁ = point₂\n    for point₂ in points[2:end]\n        min_dist = min(min_dist, angular_distance(point₃, point₁, point₂))\n        point₁ = point₂\n    end\n    return min_dist\nend\n\n\"\"\"\n    angular_distance(point₃::Point, arcs::Arcs)\n\nReturn the `angular_distance` [deg] from point₃ [deg] to the closest point on a\nan `arcs`.\n\nThe `angular_distance` does not change sign when being left or right of the arc.\n\"\"\"\nangular_distance(point₃::Point, arcs::Arcs) = angular_distance(point₃, arcs.points)\n\n\"\"\"\n    angular_distance(point₃::Point, polygon::Polygon)\n\nReturn the `angular_distance` [deg] from point₃ [deg] to the closest point on\nthe border of a `polygon`.\n\nThe `angular_distance` does not change sign when being left or right of the arc.\n\"\"\"\nangular_distance(point₃::Point, polygon::Polygon) = angular_distance(point₃,\npolygon.points)\n\n\"\"\"\n    angular_distance(point₃::Point, arc₁₂::Arc)\n\nReturn the `angular_distance` [deg] from point₃ [deg] to the closest point on a\ngreat circle line section starting in `point₁` [deg] and ending in `point₂` [deg].\nThe great circle line section does not continue around the unit sphere.\n\"\"\"\nangular_distance(point₃::Point, arc₁₂::Arc) = angular_distance(point₃, arc₁₂.point₁, arc₁₂.point₂)\n\n\"\"\"\n    along_line_angular_distance(angular_distance₁₃::Float64,\n    angular_distance_line3::Float64)\n\nThe `along_line_angular_distance` from the start `point₁` [deg] to the closest\npoint on the great circle line to `point₃`. As input we need the\n`angular_distance₁₃` [deg] between `point₁` and `point₃` [deg] and the closest\ndistance `angular_distance_line3` [deg] between the great circle line and\n`point3` [deg]. The distance is non-directional.\n\nSource: www.movable-type.co.uk/scripts/latlong.html\n\"\"\"\nfunction along_line_angular_distance(angular_distance₁₃::Float64,\nangular_distance_line3::Float64)\n    return acosd(cosd(angular_distance₁₃) / cosd(angular_distance_line3))\nend\n\n\"\"\"\n    along_line_angular_distance(point₃::Point, line₁::Line)\n\nThe `along_line_angular_distance` from the start `point₁` [deg] to the closest\npoint on the great circle line `line₁` to `point₃`. The distance is\nnon-directional.\n\nSource: www.movable-type.co.uk/scripts/latlong.html\n\"\"\"\nfunction along_line_angular_distance(point₃::Point, line₁::Line)\n    angular_distance₁₃ = angular_distance(line₁.point, point₃)\n    angular_distance_line3 = angular_distance(point₃::Point, line₁::Line)\n    return along_line_angular_distance(angular_distance₁₃,\n    angular_distance_line3)\nend\n", "meta": {"hexsha": "f27325b5587e9e5a4d9552985c72663f8b04d0ea", "size": 8203, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances.jl", "max_stars_repo_name": "rjdverbeek-tud/SphericalGeometry.jl", "max_stars_repo_head_hexsha": "02dc934c51dc8389b08e3dab0831915d5f6c5643", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distances.jl", "max_issues_repo_name": "rjdverbeek-tud/SphericalGeometry.jl", "max_issues_repo_head_hexsha": "02dc934c51dc8389b08e3dab0831915d5f6c5643", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-05-31T00:17:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T20:28:32.000Z", "max_forks_repo_path": "src/distances.jl", "max_forks_repo_name": "rjdverbeek-tud/SphericalGeometry.jl", "max_forks_repo_head_hexsha": "02dc934c51dc8389b08e3dab0831915d5f6c5643", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5108225108, "max_line_length": 104, "alphanum_fraction": 0.7483847373, "num_tokens": 2270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7657862254533159}}
{"text": "export Spindle\n\n\"\"\"\n`Spindle()` returns the Moser spindle graph. This is a seven-vertex\nunit distance graph with chromatic number equal to 4.\n\"\"\"\nfunction Spindle()\n    G = IntGraph(7)\n    edges = [\n        1 2\n        1 3\n        2 3\n        2 4\n        3 4\n        1 5\n        1 6\n        5 6\n        5 7\n        6 7\n        4 7 ]\n    add_edges!(G,edges)\n\n    d = Dict{Int,Vector}()\n    a = sqrt(3)/2\n\n    pts = [ 0 1/2 -1/2 0 ; 0 a a 2a ]\n\n    theta = acos(5/6)/2\n    R = [ cos(theta) -sin(theta); sin(theta) cos(theta) ]\n\n    p1 = R*pts\n    for k=1:4\n        d[k] = p1[:,k]\n    end\n\n    p2 = R'*pts\n    for k=5:7\n        d[k] = p2[:,k-3]\n    end\n    embed(G,d)\n    SimpleGraphs.name(G,\"Moser Spindle\")\n    return G\nend\n", "meta": {"hexsha": "f859409d0fe050d14d35b9b2dd554d9b90851212", "size": 723, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/embedding/embedded-graphs.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_stars_repo_head_hexsha": "7faccfcd99dcafb6d8cce600dac01c3722b299f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/embedding/embedded-graphs.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_issues_repo_head_hexsha": "7faccfcd99dcafb6d8cce600dac01c3722b299f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/embedding/embedded-graphs.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_forks_repo_head_hexsha": "7faccfcd99dcafb6d8cce600dac01c3722b299f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.4318181818, "max_line_length": 67, "alphanum_fraction": 0.4744121715, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.765786222089493}}
{"text": "\"\"\"\n    isinside(chart, point) -> Bool\n\nReturns true is the given point is in the image of the given chart, false otherwise.\n\"\"\"\nfunction isinside(cell, point)\n\n  u = carttobary(cell, point)\n  T = eltype(u)\n\n  tol = eps(T) * 1e3\n  w = one(T)\n  for i in 1:dimension(cell)\n    0+tol < u[i] < 1-tol || return false\n    w -= u[i]\n  end\n\n  0+tol < w < 1-tol || return false\n  return true\n\nend\n\n\n\"\"\"\n\tisinclosure(simplex, point) -> Bool\n\nDetermine whether point is in the closure of simplex. False positives are possible for points just outside of the simplex.\n\"\"\"\nfunction isinclosure(cell, point)\n\n  u = carttobary(cell, point)\n  T = eltype(u)\n  dim = dimension(cell)\n  udim = length(point)\n\n  tol = eps(T) * 1e3\n  w = one(T)\n  for i in 1:dim\n    0-tol < u[i] < 1+tol || return false\n    w -= u[i]\n  end\n\n  0-tol < w < 1+tol || return false\n\n  # finally, check that the point indeed is in the plane of the cell\n  A = zeros(T, udim, dim+1)\n  origin = cell[dim+1]\n  for i in 1:dim\n      for j in 1:udim\n          A[j,i] = cell[i][j] - origin[j]\n      end\n  end\n  for j in 1:udim; A[j,end] = point[j] - origin[j]; end\n  rank(A) == dim+1 && return false\n\n  return true\n\nend\n", "meta": {"hexsha": "28b2f2292bea270045a77295fe1de3b0e5b404f5", "size": 1166, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/isinside.jl", "max_stars_repo_name": "shakisparki/CompScienceMeshes", "max_stars_repo_head_hexsha": "5246a76e8e6493b6b28552f248e4eb53de6197ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/isinside.jl", "max_issues_repo_name": "shakisparki/CompScienceMeshes", "max_issues_repo_head_hexsha": "5246a76e8e6493b6b28552f248e4eb53de6197ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/isinside.jl", "max_forks_repo_name": "shakisparki/CompScienceMeshes", "max_forks_repo_head_hexsha": "5246a76e8e6493b6b28552f248e4eb53de6197ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7627118644, "max_line_length": 122, "alphanum_fraction": 0.6106346484, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561136, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7657862159528426}}
{"text": "const GraphMatrix = Union{Matrix, BitMatrix}\r\n\r\nfunction clique_size(seq::Union{Vector{Bool}, BitArray}, A::GraphMatrix)\r\n  set = find(seq)\r\n  clique = true\r\n  for i in set, j in set\r\n    if (i != j) && !(A[i,j] > 0)\r\n      clique = false\r\n      break\r\n    end\r\n  end\r\n  return clique*length(set)\r\nend\r\n\r\nfunction clique_loss(seq::Union{Vector{Bool}, BitArray}, A::GraphMatrix, kappa::Float)  \r\n  set = find(seq)\r\n  clique = true\r\n  edges = Float(0)\r\n  n = length(set)  \r\n  for i in set, j in set\r\n    if i != j\r\n      aij = (A[i,j] > 0)\r\n      edges += aij \r\n      clique = clique && aij\r\n    end\r\n  end\r\n\r\n  return (Float(1) - Float(edges)/Float(max(n*(n-1+kappa), 1)), Float(-n*clique))\r\nend\r\n\r\nfunction clique_loss(seq::Vector{Int}, A::GraphMatrix, kappa::Float)\r\n  n = size(A, 1)\r\n  if length(seq) < n\r\n    idx = falses(n)\r\n    idx[seq] = true\r\n  else\r\n    idx = seq .> 1\r\n  end\r\n  return clique_loss(idx, A, kappa)\r\nend\r\n\r\n\"\"\"\r\n### Clique finding using the cakewalk method\r\nMinimize the soft-clique-loss function with cakewalk. Usage: \\n\r\n`opt_seq, opt_val = clique_cw(A, kappa)` \\n\r\nwhere `kappa` is a size booster parameter beteen 0.0 and 1.0. \r\nFor details about the loss, kappa, and the reasoning behind them see our paper.\\n\\n\r\n\r\nWhen `opt_seq[i]` is 2, it means vertex `i` is selected, and 1 means it is not. \\n\r\n`opt_val` is a tuple of two floats. The first is the value being optimized, i.e., \r\nthe soft-clique-loss, and the second is the actual loss that we are interested in, \r\nthe negative clique size. \r\n\"\"\"\r\nclique_cw(A::GraphMatrix, args...; kwargs...) = cakewalk(clique_loss, 2, size(A, 1), A, args...; kwargs...)\r\n\r\ninc_clique_size(ind, A::GraphMatrix) = maximum(map(v -> (w = copy(ind); w[v] = true; clique_size(w, A)), 1:size(A,1)))\r\n\r\n\"\"\"\r\n### Validate that a clique is locally maximal\r\nFirst, find some clique, \\n\r\n`opt_seq, opt_val = clique_cw(A, kappa)` \\n\r\nThen, validate the clique is locally maximal, \\n\r\n`is_local_max_clique(opt_seq .== 2, A)`\\n\r\nThe returned value is binary.\r\n\"\"\"\r\nis_local_max_clique(ind, A::GraphMatrix) = (cs = clique_size(ind,A); (cs > 0) && (cs >= inc_clique_size(ind, A)))\r\n", "meta": {"hexsha": "2ac79d708f461c37f89d1481bfc19e831a069324", "size": 2130, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/clique.jl", "max_stars_repo_name": "uripatish/Combo.jl", "max_stars_repo_head_hexsha": "3944755da0aab4bb11d8212df0e455187b98edf8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2018-08-10T10:29:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:25:56.000Z", "max_issues_repo_path": "src/clique.jl", "max_issues_repo_name": "uripatish/Combo.jl", "max_issues_repo_head_hexsha": "3944755da0aab4bb11d8212df0e455187b98edf8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/clique.jl", "max_forks_repo_name": "uripatish/Combo.jl", "max_forks_repo_head_hexsha": "3944755da0aab4bb11d8212df0e455187b98edf8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7910447761, "max_line_length": 119, "alphanum_fraction": 0.6370892019, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561136, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7657862119980232}}
{"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    signarea(A, B, C)\n\nCompute signed area of triangle formed\nby points `A`, `B` and `C`.\n\"\"\"\nfunction signarea(A::Point{2}, B::Point{2}, C::Point{2})\n  ((B - A) × (C - A)) / 2\nend\n\n\"\"\"\n    sideof(point, segment)\n\nDetermines on which side of the oriented `segment`\nthe `point` lies. Possible results are `:LEFT`,\n`:RIGHT` or `:ON` the segment.\n\"\"\"\nfunction sideof(p::Point{2,T}, s::Segment{2,T}) where {T}\n  a, b = vertices(s)\n  area = signarea(p, a, b)\n  ifelse(area > atol(T), :LEFT, ifelse(area < -atol(T), :RIGHT, :ON))\nend\n\n\"\"\"\n    sideof(point, chain)\n\nDetermines on which side of the closed `chain` the\n`point` lies. Possible results are `:INSIDE` or\n`:OUTSIDE` the chain.\n\"\"\"\nfunction sideof(p::Point{2,T}, c::Chain{2,T}) where {T}\n  w = windingnumber(p, c)\n  ifelse(isapprox(w, zero(T), atol=atol(T)), :OUTSIDE, :INSIDE)\nend\n\n\"\"\"\n    mahalanobis(radii, angles, convention)\n\nReturn the Mahalanobis distance corresponding to an ellipsoid\nwith `radii` rotated by given `angles` according to given `convention`.\n\n- For 2D ellipses, there are two radii and one rotation angle.\n- For 3D ellipsoids, there are three radii and three rotation angles.\n\nThe list of available conventions can be found with:\n\n```julia\njulia> subtypes(RotationConvention)\n```\n\"\"\"\nfunction mahalanobis(radii, angles, convention)\n  ndims, nangles = length(radii), length(angles)\n  valid = (ndims == 3 && nangles == 3) || (ndims == 2 && nangles == 1)\n  @assert valid \"invalid number of radii/angles\"\n\n  # invert radii if necessary\n  invert = mainaxis(convention) == :Y\n  ranges = invert ? [radii[i] for i in reverse(1:ndims,1,2)] : vec(radii)\n\n  # scaling matrix\n  λ = one(eltype(ranges)) ./ ranges.^2\n  Λ = Diagonal(SVector{ndims}(λ))\n\n  # rotation matrix\n  R = rotmat(angles, convention)\n\n  # ellipsoid metric\n  W = Symmetric(R'*Λ*R)\n  Mahalanobis(W)\nend", "meta": {"hexsha": "f0de2c05e551fc11de021e5b4339a62400cea086", "size": 2042, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "thchr/Meshes.jl", "max_stars_repo_head_hexsha": "72f34bd4c5f709d2a172e076d20117d8cd21a1ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "thchr/Meshes.jl", "max_issues_repo_head_hexsha": "72f34bd4c5f709d2a172e076d20117d8cd21a1ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "thchr/Meshes.jl", "max_forks_repo_head_hexsha": "72f34bd4c5f709d2a172e076d20117d8cd21a1ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5945945946, "max_line_length": 73, "alphanum_fraction": 0.6258570029, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7657862097251156}}
{"text": "# This file is part of the TaylorSeries.jl Julia package, MIT license\n#\n# Luis Benet & David P. Sanders\n# UNAM\n#\n# MIT Expat license\n#\n\n## Differentiating ##\n\"\"\"\n    derivative(a)\n\nReturn the `Taylor1` polynomial of the differential of `a::Taylor1`.\nThe last coefficient is set to zero.\n\nThe function `differentiate` is an exact synonym of `derivative`.\n\"\"\"\nfunction derivative(a::Taylor1)\n    res = zero(a)\n    @inbounds for ord in eachindex(a)\n        derivative!(res, a, ord)\n        # ord == a.order-1 && break\n    end\n    return res\nend\n\n\"\"\"\n    differentiate\n\nAn exact synonym of [`derivative`](@ref).\n\"\"\"\nconst differentiate = derivative\n\n\"\"\"\n    derivative!(res, a) --> nothing\n\nIn-place version of `derivative`. Compute the `Taylor1` polynomial of the\ndifferential of `a::Taylor1` and save it into `res`. The last coefficient is\nset to zero.\n\"\"\"\nfunction derivative!(res::Taylor1, a::Taylor1)\n    @inbounds for ord in eachindex(a)\n        derivative!(res, a, ord)\n        # ord == a.order-1 && break\n    end\n    res[a.order] = zero(a[0])\n    nothing\nend\n\n\"\"\"\n    derivative!(p, a, k) --> nothing\n\nUpdate in-place the `k-th` expansion coefficient `p[k]` of `p = derivative(a)`\nfor both `p` and `a` `Taylor1`.\n\nThe coefficients are given by\n\n```math\np_k = (k+1)a_{k+1}.\n```\n\n\"\"\"\nderivative!(p::Taylor1, a::Taylor1, k::Int) = k < a.order ? p[k] = (k+1)*a[k+1] : nothing\n\n\n\"\"\"\n    derivative(a, n)\n\nCompute recursively the `Taylor1` polynomial of the n-th derivative of\n`a::Taylor1`.\n\"\"\"\nfunction derivative(a::Taylor1{T}, n::Int) where {T<:Number}\n    @assert a.order ≥ n ≥ 0\n    if n==0\n        return a\n    else\n        res = deepcopy(a)\n        for i in 1:n\n            derivative!(res, res)\n        end\n        return res\n    end\nend\n\n\"\"\"\n    derivative(n, a)\n\nReturn the value of the `n`-th derivative of the polynomial `a`.\n\"\"\"\nfunction derivative(n::Int, a::Taylor1{T}) where {T<:Number}\n    @assert a.order ≥ n ≥ 0\n    factorial( widen(n) ) * a[n] :: T\nend\n\n## Integrating ##\n\"\"\"\n    integrate(a, [x])\n\nReturn the integral of `a::Taylor1`. The constant of integration\n(0-th order coefficient) is set to `x`, which is zero if ommitted.\n\"\"\"\nfunction integrate(a::Taylor1{T}, x::S) where {T<:Number,S<:Number}\n    order = get_order(a)\n    aa = a[0]/1 + zero(x)\n    R = typeof(aa)\n    coeffs = Array{typeof(aa)}(undef, order+1)\n    fill!(coeffs, zero(aa))\n    @inbounds for i = 1:order\n        coeffs[i+1] = a[i-1] / i\n    end\n    @inbounds coeffs[1] = convert(R, x)\n    return Taylor1(coeffs, a.order)\nend\nintegrate(a::Taylor1{T}) where {T<:Number} = integrate(a, zero(a[0]))\n\n\n\n## Differentiation ##\n\"\"\"\n    derivative(a, r)\n\nPartial differentiation of `a::HomogeneousPolynomial` series with respect\nto the `r`-th variable.\n\"\"\"\nfunction derivative(a::HomogeneousPolynomial, r::Int)\n    @assert 1 ≤ r ≤ get_numvars()\n    # @show zero(a[1]) zero(eltype(a))\n    T = eltype(a)\n    a.order == 0 && return HomogeneousPolynomial(zero(a[1]), 0)\n    @inbounds num_coeffs = size_table[a.order]\n    coeffs = zeros(T,num_coeffs)\n    @inbounds posTb = pos_table[a.order]\n    @inbounds num_coeffs = size_table[a.order+1]\n\n    @inbounds for i = 1:num_coeffs\n        iind = coeff_table[a.order+1][i]\n        n = iind[r]\n        n == 0 && continue\n        iind[r] -= 1\n        kdic = in_base(get_order(),iind)\n        pos = posTb[kdic]\n        coeffs[pos] = n * a[i]\n        iind[r] += 1\n    end\n\n    return HomogeneousPolynomial{T}(coeffs, a.order-1)\nend\nderivative(a::HomogeneousPolynomial, s::Symbol) = derivative(a, lookupvar(s))\n\n\"\"\"\n    derivative(a, r)\n\nPartial differentiation of `a::TaylorN` series with respect\nto the `r`-th variable. The `r`-th variable may be also\nspecified through its symbol.\n\"\"\"\nfunction derivative(a::TaylorN, r=1::Int)\n    T = eltype(a)\n    coeffs = Array{HomogeneousPolynomial{T}}(undef, a.order)\n\n    @inbounds for ord = 1:a.order\n        coeffs[ord] = derivative( a[ord], r)\n    end\n    return TaylorN{T}( coeffs, a.order )\nend\nderivative(a::TaylorN, s::Symbol) = derivative(a, lookupvar(s))\n\n\"\"\"\n    derivative(a::TaylorN{T}, ntup::NTuple{N,Int})\n\nReturn a `TaylorN` with the partial derivative of `a` defined\nby `ntup::NTuple{N,Int}`, where the first entry is the number\nof derivatives with respect to the first variable, the second is\nthe number of derivatives with respect to the second, and so on.\n\"\"\"\nfunction derivative(a::TaylorN, ntup::NTuple{N,Int}) where {N}\n\n    @assert N == get_numvars() && all(ntup .>= 0)\n\n    sum(ntup) > a.order && return zero(a)\n    sum(ntup) == 0 && return copy(a)\n\n    aa = copy(a)\n    for nvar in 1:get_numvars()\n        for numder in 1:ntup[nvar]\n            aa = derivative(aa, nvar)\n        end\n    end\n\n    return aa\nend\n\n\"\"\"\n    derivative(ntup::NTuple{N,Int}, a::TaylorN{T})\n\nReturns the value of the coefficient of `a` specified by\n`ntup::NTuple{N,Int}`, multiplied by the corresponding\nfactorials.\n\"\"\"\nfunction derivative(ntup::NTuple{N,Int}, a::TaylorN) where {N}\n\n    @assert N == get_numvars() && all(ntup .>= 0)\n\n    c = getcoeff(a, [ntup...])\n    for ind = 1:get_numvars()\n        c *= factorial(ntup[ind])\n    end\n\n    return c\nend\n\n\n## Gradient, jacobian and hessian\n\"\"\"\n```\n    gradient(f)\n    ∇(f)\n```\n\nCompute the gradient of the polynomial `f::TaylorN`.\n\"\"\"\nfunction gradient(f::TaylorN)\n    T = eltype(f)\n    numVars = get_numvars()\n    grad = Array{TaylorN{T}}(undef, numVars)\n    @inbounds for nv = 1:numVars\n        grad[nv] = derivative(f, nv)\n    end\n    return grad\nend\nconst ∇ = TaylorSeries.gradient\n\n\"\"\"\n```\n    jacobian(vf)\n    jacobian(vf, [vals])\n```\n\nCompute the jacobian matrix of `vf`, a vector of `TaylorN` polynomials,\nevaluated at the vector `vals`. If `vals` is ommited, it is evaluated at zero.\n\"\"\"\nfunction jacobian(vf::Array{TaylorN{T},1}) where {T<:Number}\n    numVars = get_numvars()\n    @assert length(vf) == numVars\n    jac = Array{T}(undef, numVars, numVars)\n\n    @inbounds for comp = 1:numVars\n        jac[:,comp] = vf[comp][1][1:end]\n    end\n\n    return transpose(jac)\nend\nfunction jacobian(vf::Array{TaylorN{T},1}, vals::Array{S,1}) where {T<:Number,S<:Number}\n    R = promote_type(T,S)\n    numVars = get_numvars()\n    @assert length(vf) == numVars == length(vals)\n    jac = Array{R}(undef, numVars, numVars)\n\n    for comp = 1:numVars\n        @inbounds grad = gradient( vf[comp] )\n        @inbounds for nv = 1:numVars\n            jac[nv,comp] = evaluate(grad[nv], vals)\n        end\n    end\n\n    return transpose(jac)\nend\n\nfunction jacobian(vf::Array{Taylor1{TaylorN{T}},1}) where {T<:Number}\n    vv = convert(Array{TaylorN{Taylor1{T}},1}, vf)\n    jacobian(vv)\nend\n\n\"\"\"\n```\n    jacobian!(jac, vf)\n    jacobian!(jac, vf, [vals])\n```\n\nCompute the jacobian matrix of `vf`, a vector of `TaylorN` polynomials\nevaluated at the vector `vals`, and write results to `jac`. If `vals` is ommited,\nit is evaluated at zero.\n\"\"\"\nfunction jacobian!(jac::Array{T,2}, vf::Array{TaylorN{T},1}) where {T<:Number}\n    numVars = get_numvars()\n    @assert length(vf) == numVars\n    @assert (numVars, numVars) == size(jac)\n    for comp2 = 1:numVars\n        for comp1 = 1:numVars\n            @inbounds jac[comp1,comp2] = vf[comp1][1][comp2]\n        end\n    end\n    nothing\nend\nfunction jacobian!(jac::Array{T,2}, vf::Array{TaylorN{T},1},\n        vals::Array{T,1}) where {T<:Number}\n\n    numVars = get_numvars()\n    @assert length(vf) == numVars == length(vals)\n    @assert (numVars, numVars) == size(jac)\n    for comp = 1:numVars\n        @inbounds for nv = 1:numVars\n            jac[nv,comp] = evaluate(derivative(vf[nv], comp), vals)\n        end\n    end\n    nothing\nend\n\n\n\"\"\"\n```\n    hessian(f)\n    hessian(f, [vals])\n```\n\nReturn the hessian matrix (jacobian of the gradient) of `f::TaylorN`,\nevaluated at the vector `vals`. If `vals` is ommited, it is evaluated at\nzero.\n\"\"\"\nhessian(f::TaylorN{T}, vals::Array{S,1}) where {T<:Number,S<:Number} =\n    (R = promote_type(T,S); jacobian( gradient(f), vals::Array{R,1}) )\n\nhessian(f::TaylorN{T}) where {T<:Number} = hessian( f, zeros(T, get_numvars()) )\n\n\"\"\"\n```\n    hessian!(hes, f)\n    hessian!(hes, f, [vals])\n```\n\nReturn the hessian matrix (jacobian of the gradient) of `f::TaylorN`,\nevaluated at the vector `vals`, and write results to `hes`. If `vals` is\nommited, it is evaluated at zero.\n\"\"\"\nhessian!(hes::Array{T,2}, f::TaylorN{T}, vals::Array{T,1}) where {T<:Number} =\n    jacobian!(hes, gradient(f), vals)\n\nhessian!(hes::Array{T,2}, f::TaylorN{T}) where {T<:Number} =\n    jacobian!(hes, gradient(f))\n\n\n##Integration\n\"\"\"\n    integrate(a, r)\n\nIntegrate the `a::HomogeneousPolynomial` with respect to the `r`-th\nvariable. The returned `HomogeneousPolynomial` has no added constant of\nintegration. If the order of a corresponds to `get_order()`, a zero\n`HomogeneousPolynomial` of 0-th order is returned.\n\n\"\"\"\nfunction integrate(a::HomogeneousPolynomial, r::Int)\n    @assert 1 ≤ r ≤ get_numvars()\n\n    order_max = get_order()\n    a.order == order_max && return HomogeneousPolynomial(zero(a[1]/1), 0)\n\n    @inbounds posTb = pos_table[a.order+2]\n    @inbounds num_coeffs = size_table[a.order+1]\n\n    T = promote_type(eltype(a), eltype(a[1]/1))\n    coeffs = zeros(T, size_table[a.order+2])\n\n    @inbounds for i = 1:num_coeffs\n        iind = coeff_table[a.order+1][i]\n        n = iind[r]\n        n == order_max && continue\n        iind[r] += 1\n        kdic = in_base(get_order(), iind)\n        pos = posTb[kdic]\n        coeffs[pos] = a[i] / (n+1)\n        iind[r] -= 1\n    end\n\n    return HomogeneousPolynomial(coeffs, a.order+1)\nend\nintegrate(a::HomogeneousPolynomial, s::Symbol) = integrate(a, lookupvar(s))\n\n\n\"\"\"\n    integrate(a, r, [x0])\n\nIntegrate the `a::TaylorN` series with respect to the `r`-th variable,\nwhere `x0` the integration constant and must be independent\nof the `r`-th variable; if `x0` is ommitted, it is taken as zero.\n\"\"\"\nfunction integrate(a::TaylorN, r::Int)\n    T = promote_type(eltype(a), eltype(a[0]/1))\n    order_max = min(get_order(), a.order+1)\n    coeffs = zeros(HomogeneousPolynomial{T}, order_max)\n\n    @inbounds for ord = 0:order_max-1\n        coeffs[ord+1] = integrate( a[ord], r)\n    end\n\n    return TaylorN(coeffs)\nend\nfunction integrate(a::TaylorN, r::Int, x0::TaylorN)\n    # Check constant of integration is independent of re\n    @assert derivative(x0, r) == 0.0 \"\"\"\n    The integration constant ($x0) must be independent of the\n    $(_params_TaylorN_.variable_names[r]) variable\"\"\"\n\n    res = integrate(a, r)\n    return x0+res\nend\nintegrate(a::TaylorN, r::Int, x0) =\n    integrate(a,r,TaylorN(HomogeneousPolynomial([convert(eltype(a),x0)], 0)))\n\nintegrate(a::TaylorN, s::Symbol) = integrate(a, lookupvar(s))\nintegrate(a::TaylorN, s::Symbol, x0::TaylorN) = integrate(a, lookupvar(s), x0)\nintegrate(a::TaylorN, s::Symbol, x0) = integrate(a, lookupvar(s), x0)\n", "meta": {"hexsha": "b08e2916d1faad89e9c4fd00fd0f449ff6f261f8", "size": 10739, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/calculus.jl", "max_stars_repo_name": "PerezHz/TaylorSeries.jl", "max_stars_repo_head_hexsha": "dfb3f159def4fee8fbcbee29f8626c9c0bcac4be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/calculus.jl", "max_issues_repo_name": "PerezHz/TaylorSeries.jl", "max_issues_repo_head_hexsha": "dfb3f159def4fee8fbcbee29f8626c9c0bcac4be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/calculus.jl", "max_forks_repo_name": "PerezHz/TaylorSeries.jl", "max_forks_repo_head_hexsha": "dfb3f159def4fee8fbcbee29f8626c9c0bcac4be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0024213075, "max_line_length": 89, "alphanum_fraction": 0.6337647826, "num_tokens": 3284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7656996586029192}}
{"text": "# Load Julia packages (libraries) needed  for the snippets in chapter 0\n\nusing StatisticalRethinking\nimport LogDensityProblems: logdensity, logdensity_and_gradient\nimport StatisticalRethinking: HMC2, generate_n_samples\n\n# CmdStan uses a tmp directory to store the output of cmdstan\n\nProjDir = @__DIR__\ncd(ProjDir)\n\n# ### snippet 9.3\n\n# Construct the logdensity problem\n\nstruct clip_9_3_model{TY <: AbstractVector, TX <: AbstractVector}\n    \"Observations.\"\n    y::TY\n    \"Covariate\"\n    x::TX\nend\n\n# Make the type callable with the parameters *as a single argument*.\n\nfunction (problem:: clip_9_3_model)(θ)\n    @unpack y, x, = problem    # extract the data\n    @unpack muy, mux = θ     # works on the named tuple too\n    ll = 0.0\n    ll += loglikelihood(Normal(mux, 1), x)\n    ll += loglikelihood(Normal(muy, 1), y)\n    ll += logpdf(Normal(0, 1), mux) \n    ll += logpdf(Normal(0, 1), muy)\n    ll\nend\n\n# Instantiate the model with data and inits.\n\nRandom.seed!(1234591)\n\nN = 100\nx = rand(Normal(0, 1), N)\ny = rand(Normal(0, 1), N)\n \np = clip_9_3_model(y, x)\nθ = (muy = 0.0, mux=0.0)\np(θ)\n\n# Write a function to return properly dimensioned transformation.\n\nproblem_transformation(p::clip_9_3_model) =\n    as((muy = asℝ, mux = asℝ))\n\n# Wrap the problem with a transformation, then use Flux for the gradient.\n\nP = TransformedLogDensity(problem_transformation(p), p)\n∇P = ADgradient(:ForwardDiff, P);\n\n# Tune and sample.\n\nchain, NUTS_tuned = NUTS_init_tune_mcmc(∇P, 1000);\n\n# We use the transformation to obtain the posterior from the chain.\n\nposterior = TransformVariables.transform.(Ref(problem_transformation(p)), get_position.(chain));\n\n# Extract the posterior means,\n\n[mean(first, posterior), mean(last, posterior)]\n\n# Draw 200 samples:\n\nfunction draw_n_samples(model, grad;\n  epsilon = 0.03, # Step size\n  L = 11, # No of leapfrog steps\n  n_samples = 1000, # No of samples\n  q = [-0.1, 0.2]) # Initial position\n  \n  samples = zeros(n_samples, 2)\n  for i in 1:n_samples\n    q, ptraj, qtraj, accept, dH = HMC(model, grad, 0.03, 11, q)\n    samples[i, :] = q\n  end\n  \n  samples\n  \nend\n\nsamples = draw_n_samples(p, ∇P; n_samples=200);\nmean(samples, dims=1)\n    \n# End of `09/clip-03.jl`\n", "meta": {"hexsha": "c1c9c1ffc0e15768731b1ca663ba10afa74ddab5", "size": 2182, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/09/clip-03d1.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_stars_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/09/clip-03d1.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_issues_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/09/clip-03d1.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_forks_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7173913043, "max_line_length": 96, "alphanum_fraction": 0.6911090742, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066391, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.765699652567293}}
{"text": "using ITensors\nusing Zygote\n\ns = siteind(\"Qubit\")\n\nf(x) = op(\"Ry\", s; θ=x)[1, 1]\n\nx = 0.2\n@show f(x), cos(x / 2)\n@show f'(x), -sin(x / 2) / 2\n\n# Simple gate optimization\nψ0 = state(s, \"0\")\nψp = state(s, \"+\")\n\nfunction loss(x)\n  U = op(\"Ry\", s; θ=x)\n  Uψ0 = replaceprime(U * ψ0, 1 => 0)\n  return -(dag(ψp) * Uψ0)[]\nend\n\n# Extremely simple gradient descent implementation,\n# where gradients are computing with automatic differentiation\n# using Zygote.\nfunction gradient_descent(f, x0; γ, nsteps, grad_tol)\n  @show γ, nsteps\n  x = x0\n  f_x = f(x)\n  ∇f_x = f'(x)\n  step = 0\n  @show step, x, f_x, ∇f_x\n  for step in 1:nsteps\n    x -= γ * ∇f_x\n    f_x = f(x)\n    ∇f_x = f'(x)\n    @show step, x, f_x, ∇f_x\n    if norm(∇f_x) ≤ grad_tol\n      break\n    end\n  end\n  return x, f_x, ∇f_x\nend\n\nx0 = 0\nγ = 2.0 # Learning rate\nnsteps = 30 # Number of steps of gradient descent\ngrad_tol = 1e-4 # Stop if gradient falls below this value\nx, loss_x, ∇loss_x = gradient_descent(loss, x0; γ=γ, nsteps=nsteps, grad_tol=grad_tol)\n\n@show x0, loss(x0)\n@show x, loss(x)\n@show π / 2, loss(π / 2)\n", "meta": {"hexsha": "10a3cde7b95d2ce4fc4e0aa5230fc3902cc49e9b", "size": 1069, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/autodiff/circuit_optimization/op.jl", "max_stars_repo_name": "nticea/ITensors.jl", "max_stars_repo_head_hexsha": "e3694cc50e4b6387222832f23d81996990244782", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-27T08:13:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T19:19:37.000Z", "max_issues_repo_path": "examples/autodiff/circuit_optimization/op.jl", "max_issues_repo_name": "nticea/ITensors.jl", "max_issues_repo_head_hexsha": "e3694cc50e4b6387222832f23d81996990244782", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/autodiff/circuit_optimization/op.jl", "max_forks_repo_name": "nticea/ITensors.jl", "max_forks_repo_head_hexsha": "e3694cc50e4b6387222832f23d81996990244782", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-27T08:14:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-27T08:14:00.000Z", "avg_line_length": 20.1698113208, "max_line_length": 86, "alphanum_fraction": 0.6127221703, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7656763461052596}}
{"text": "using LinearAlgebra\n\n\"\"\"\nPerforms a random hill climb solution for a discretized search space.\n\n    Args:\n      fn (Function): Objective function\n      x0 (Array{Any}): Starting point\n      h (Float64, optional): Discretization\n      max_failed (Int64, optional): Max number of failed moves before exiting.\n        Defaults to the dimensionality of the design space.\n      verbose (Bool, optional): Optionally print results\n\n    Returns:\n      tuple: (x, fx, f_calls) where x is the minimizer, fx is the minimum, and\n      f_calls is the number of function calls made.\n\"\"\"\nfunction random_hill(fn::Function, x0::Array{Float64};\n                     h=.1, max_failed=nothing, verbose=false)\n    x = copy(x0)\n    fx = fn(x)\n    n = length(x)\n    failed = 0\n    f_calls = 1\n\n    # use an I matrix to randomly determine direction\n    e_hat = Matrix(1I, n, n)\n\n    if isnothing(max_failed)\n        max_failed = n\n    end\n\n    while failed < max_failed\n        d = e_hat[:, rand(1:n)] # randomly choose basis vec\n        d *= rand([-1, 1]) # randomly choose pos/neg\n        \n        xnew = x + h*d\n        fnew = fn(xnew)\n        f_calls += 1\n\n        if fnew < fx\n            fx = fnew\n            x = xnew\n            failed = 0\n        else\n            failed += 1\n        end\n    end\n\n    if verbose\n        println(\"Iterations: $(f_calls)\\nx*: $(x)\\nf*: $(fx)\\n\")\n    end\n\n    return x, fx, f_calls\nend\n", "meta": {"hexsha": "d5bed948a049d4697212ec75e1dd03f00948cef6", "size": 1402, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/random_hill.jl", "max_stars_repo_name": "camirmas/DesignAutomation", "max_stars_repo_head_hexsha": "66bb5acb6589cb35635e8a203fd7eb62ce649e3e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-02T17:21:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T17:21:37.000Z", "max_issues_repo_path": "src/random_hill.jl", "max_issues_repo_name": "camirmas/DesignAutomation", "max_issues_repo_head_hexsha": "66bb5acb6589cb35635e8a203fd7eb62ce649e3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/random_hill.jl", "max_forks_repo_name": "camirmas/DesignAutomation", "max_forks_repo_head_hexsha": "66bb5acb6589cb35635e8a203fd7eb62ce649e3e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0357142857, "max_line_length": 78, "alphanum_fraction": 0.577746077, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7656763376451147}}
{"text": "# Functions for STaylor1\r\n@generated function exp(a::STaylor1{N,T}) where {N, T <: Number}\r\n    ex_calc = quote end\r\n    append!(ex_calc.args, Any[nothing for i in 1:N])\r\n    syms = Symbol[Symbol(\"c$i\") for i in 1:N]\r\n\r\n    sym = syms[1]\r\n    ex_line = :($(syms[1]) = exp(a[0]))\r\n    ex_calc.args[1] = ex_line\r\n\r\n    for k in 1:(N-1)\r\n        kT = convert(T,k)\r\n        sym = syms[k+1]\r\n        ex_line = :($kT * a[$k] * $(syms[1]))\r\n        @inbounds for i = 1:k-1\r\n            ex_line = :($ex_line + $(kT-i) * a[$(k-i)] * $(syms[i+1]))\r\n        end\r\n        ex_line = :(($ex_line)/$kT)\r\n        ex_line = :($sym = $ex_line)\r\n        ex_calc.args[k+1] = ex_line\r\n    end\r\n\r\n    exout = :(($(syms[1]),))\r\n    for i = 2:N\r\n        push!(exout.args, syms[i])\r\n    end\r\n    return quote\r\n               Base.@_inline_meta\r\n               $ex_calc\r\n               return STaylor1{N,T}($exout)\r\n            end\r\nend\r\n\r\n@generated function log(a::STaylor1{N,T}) where {N, T <: Number}\r\n    ex_calc = quote end\r\n    append!(ex_calc.args, Any[nothing for i in 1:N])\r\n    syms = Symbol[Symbol(\"c$i\") for i in 1:N]\r\n\r\n    (N >= 1) && (ex_calc.args[1] = :($(syms[1]) = log(constant_term(a))))\r\n    (N >= 2) && (ex_calc.args[2] = :($(syms[2]) = a[1]/constant_term(a)))\r\n\r\n    for k in 2:(N-1)\r\n        ex_line = :($(k-1)*a[1]*$(syms[k]))\r\n        @inbounds for i = 2:k-1\r\n            ex_line = :($ex_line + $(k-i)*a[$i] * $(syms[k+1-i]))\r\n        end\r\n        ex_line = :((a[$k] - ($ex_line)/$(convert(T,k)))/constant_term(a))\r\n        ex_line = :($(syms[k+1]) = $ex_line)\r\n        ex_calc.args[k+1] = ex_line\r\n    end\r\n\r\n    exout = :(($(syms[1]),))\r\n    for i = 2:N\r\n        push!(exout.args, syms[i])\r\n    end\r\n\r\n    return quote\r\n               Base.@_inline_meta\r\n               iszero(constant_term(a)) && throw(ArgumentError(\"\"\"\r\n                       The 0-th order `STaylor1` coefficient must be non-zero\r\n                       in order to expand `log` around 0.\r\n                       \"\"\"))\r\n               $ex_calc\r\n               return STaylor1{N,T}($exout)\r\n            end\r\nend\r\n\r\nsin(a::STaylor1{N,T}) where {N, T <: Number} = sincos(a)[1]\r\ncos(a::STaylor1{N,T}) where {N, T <: Number} = sincos(a)[2]\r\n@generated function sincos(a::STaylor1{N,T}) where {N, T <: Number}\r\n\r\n    ex_calc = quote end\r\n    append!(ex_calc.args, Any[nothing for i in 1:(2*N)])\r\n\r\n    syms_s = Symbol[Symbol(\"c$i\") for i in 1:N]\r\n    syms_c = Symbol[Symbol(\"c2$i\") for i in 1:N]\r\n\r\n    ex_line_s = :($(syms_s[1]) = sin(a[0]))\r\n    ex_line_c = :($(syms_c[1]) = cos(a[0]))\r\n    ex_calc.args[1] = ex_line_s\r\n    ex_calc.args[2] = ex_line_c\r\n\r\n    for k = 1:(N - 1)\r\n        ex_line_s = :(a[1]*$(syms_c[k]))\r\n        ex_line_c = :(-a[1]*$(syms_s[k]))\r\n        for i = 2:k\r\n            ex_line_s = :($ex_line_s + $i*a[$i]*$(syms_c[(k - i + 1)]))\r\n            ex_line_c = :($ex_line_c - $i*a[$i]*$(syms_s[(k - i + 1)]))\r\n        end\r\n        ex_line_s = :($(syms_s[k + 1]) = ($ex_line_s)/$k)\r\n        ex_line_c = :($(syms_c[k + 1]) = ($ex_line_c)/$k)\r\n        ex_calc.args[2*k + 1] = ex_line_s\r\n        ex_calc.args[2*k + 2] = ex_line_c\r\n    end\r\n\r\n    exout_s = :(($(syms_s[1]),))\r\n    for i = 2:N\r\n        push!(exout_s.args, syms_s[i])\r\n    end\r\n\r\n    exout_c = :(($(syms_c[1]),))\r\n    for i = 2:N\r\n        push!(exout_c.args, syms_c[i])\r\n    end\r\n\r\n    return quote\r\n               Base.@_inline_meta\r\n               $ex_calc\r\n               return STaylor1{N,T}($exout_s), STaylor1{N,T}($exout_c)\r\n            end\r\nend\r\n\r\n# Functions for STaylor1\r\n#=\r\n@generated function tan(a::STaylor1{N,T}) where {N, T <: Number}\r\n\r\n    ex_calc = quote end\r\n    append!(ex_calc.args, Any[nothing for i in 1:(4*N)])\r\n    syms = Symbol[Symbol(\"c$i\") for i in 1:N]\r\n    syms2 = Symbol[Symbol(\"c2$i\") for i in 1:N]\r\n\r\n    for i = 1:N\r\n        ex_calc.args[i] = :($(syms2[i]) = 0.0)\r\n    end\r\n\r\n    ex_line_c = :($(syms[1]) = tan(a[0]))\r\n    ex_line_c2 = :($(syms2[1]) = ($(syms[1]))^2)\r\n    ex_calc.args[N + 1] = ex_line_c\r\n    ex_calc.args[N + 2] = ex_line_c2\r\n\r\n    for k = 1:(N - 1)\r\n\r\n        kodd = k%2\r\n        kend = div(k - 2 + kodd, 2)\r\n        kdiv2 = div(k, 2)\r\n\r\n        ex_line_c = :($(k-1)*a[$(k-1)]*$(syms2[2]))\r\n        for i = 1:(k - 1)\r\n            q = k - i\r\n            ex_line_c = :($ex_line_c + ($q)*a[$q]*$(syms2[i + 1]))\r\n        end\r\n        ex_line_c = :(a[$k] + ($ex_line_c)/$k)\r\n        ex_line_c = :($(syms[k + 1]) = $ex_line_c)\r\n        ex_calc.args[(3*k-2) + N + 2] = ex_line_c\r\n\r\n        ex_line_c2 = :(a[0]*a[$k])\r\n        for i = 1:kend\r\n            ex_line_c2 = :($ex_line_c2 + a[$i]*a[$k - $i])\r\n        end\r\n        ex_line_c2 = :(2*$ex_line_c2)\r\n\r\n        if kodd != 1\r\n            ex_line_c2 = :($ex_line_c2 + a[$kdiv2]^2)\r\n        end\r\n\r\n        ex_line_c2 = :($(syms2[k + 1]) = $ex_line_c2)\r\n        ex_calc.args[(3*k-1) + 2 + N] = ex_line_c2\r\n        blar = k + 1\r\n        blar_str = \"c$(blar) \"\r\n        ex_calc.args[3*k + N + 2] = :(println($blar_str*string($(syms[k + 1]))))\r\n    end\r\n\r\n    exout = :(($(syms[1]),))\r\n    for i = 2:N\r\n        push!(exout.args, syms[i])\r\n    end\r\n\r\n    return quote\r\n               Base.@_inline_meta\r\n               $ex_calc\r\n               return STaylor1{N,T}($exout)\r\n            end\r\nend\r\n=#\r\n\r\n# Functions for STaylor1\r\n#=\r\n@generated function asin(a::STaylor1{N,T}) where {N, T <: Number}\r\n    ex_calc = quote end\r\n    append!(ex_calc.args, Any[nothing for i in 1:N])\r\n    syms = Symbol[Symbol(\"c$i\") for i in 1:N]\r\n\r\n    sym = syms[1]\r\n    ex_line = :($(sym) = asin(a[0]))\r\n    ex_calc.args[1] = ex_line\r\n\r\n    #=\r\n    for k in 1:(N-1)\r\n        kT = convert(T,k)\r\n        sym = syms[k+1]\r\n        ex_line = :($kT * a[$k] * $(syms[1]))\r\n        @inbounds for i = 1:k-1\r\n            ex_line = :($ex_line + $(kT-i) * a[$(k-i)] * $(syms[i+1]))\r\n        end\r\n        ex_line = :(($ex_line)/$kT)\r\n        ex_line = :($sym = $ex_line)\r\n        ex_calc.args[k+1] = ex_line\r\n    end\r\n    =#\r\n\r\n    exout = :(($(syms[1]),))\r\n    for i = 2:N\r\n        push!(exout.args, syms[i])\r\n    end\r\n    return quote\r\n               Base.@_inline_meta\r\n               $ex_calc\r\n               return STaylor1{N,T}($exout)\r\n            end\r\nend\r\n=#\r\n\r\n# Functions for STaylor1\r\n#=\r\n@generated function acos(a::STaylor1{N,T}) where {N, T <: Number}\r\n    ex_calc = quote end\r\n    append!(ex_calc.args, Any[nothing for i in 1:N])\r\n    syms = Symbol[Symbol(\"c$i\") for i in 1:N]\r\n\r\n    sym = syms[1]\r\n    ex_line = :($(sym) = acos(a[0]))\r\n    ex_calc.args[1] = ex_line\r\n\r\n    #=\r\n    for k in 1:(N-1)\r\n        kT = convert(T,k)\r\n        sym = syms[k+1]\r\n        ex_line = :($kT * a[$k] * $(syms[1]))\r\n        @inbounds for i = 1:k-1\r\n            ex_line = :($ex_line + $(kT-i) * a[$(k-i)] * $(syms[i+1]))\r\n        end\r\n        ex_line = :(($ex_line)/$kT)\r\n        ex_line = :($sym = $ex_line)\r\n        ex_calc.args[k+1] = ex_line\r\n    end\r\n    =#\r\n\r\n    exout = :(($(syms[1]),))\r\n    for i = 2:N\r\n        push!(exout.args, syms[i])\r\n    end\r\n    return quote\r\n               Base.@_inline_meta\r\n               $ex_calc\r\n               return STaylor1{N,T}($exout)\r\n            end\r\nend\r\n=#\r\n\r\n# Functions for STaylor1\r\n#=\r\n@generated function atan(a::STaylor1{N,T}) where {N, T <: Number}\r\n    ex_calc = quote end\r\n    append!(ex_calc.args, Any[nothing for i in 1:N])\r\n    syms = Symbol[Symbol(\"c$i\") for i in 1:N]\r\n\r\n    sym = syms[1]\r\n    ex_line = :($(sym) = atan(a[0]))\r\n    ex_calc.args[1] = ex_line\r\n\r\n    #=\r\n    for k in 1:(N-1)\r\n        kT = convert(T,k)\r\n        sym = syms[k+1]\r\n        ex_line = :($kT * a[$k] * $(syms[1]))\r\n        @inbounds for i = 1:k-1\r\n            ex_line = :($ex_line + $(kT-i) * a[$(k-i)] * $(syms[i+1]))\r\n        end\r\n        ex_line = :(($ex_line)/$kT)\r\n        ex_line = :($sym = $ex_line)\r\n        ex_calc.args[k+1] = ex_line\r\n    end\r\n    =#\r\n\r\n    exout = :(($(syms[1]),))\r\n    for i = 2:N\r\n        push!(exout.args, syms[i])\r\n    end\r\n    return quote\r\n               Base.@_inline_meta\r\n               $ex_calc\r\n               return STaylor1{N,T}($exout)\r\n            end\r\nend\r\n=#\r\n\r\nsinh(a::STaylor1{N,T}) where {N, T <: Number} = sinhcosh(a)[1]\r\ncosh(a::STaylor1{N,T}) where {N, T <: Number} = sinhcosh(a)[2]\r\n@generated function sinhcosh(a::STaylor1{N,T}) where {N, T <: Number}\r\n\r\n    ex_calc = quote end\r\n    append!(ex_calc.args, Any[nothing for i in 1:(2*N)])\r\n\r\n    syms_s = Symbol[Symbol(\"c$i\") for i in 1:N]\r\n    syms_c = Symbol[Symbol(\"c2$i\") for i in 1:N]\r\n\r\n    ex_line_s = :($(syms_s[1]) = sinh(a[0]))\r\n    ex_line_c = :($(syms_c[1]) = cosh(a[0]))\r\n    ex_calc.args[1] = ex_line_s\r\n    ex_calc.args[2] = ex_line_c\r\n\r\n    for k = 1:(N - 1)\r\n        ex_line_s = :(a[1]*$(syms_c[k]))\r\n        ex_line_c = :(a[1]*$(syms_s[k]))\r\n        for i = 2:k\r\n            ex_line_s = :($ex_line_s + $i*a[$i]*$(syms_c[(k - i + 1)]))\r\n            ex_line_c = :($ex_line_c + $i*a[$i]*$(syms_s[(k - i + 1)]))\r\n        end\r\n        ex_line_s = :($(syms_s[k + 1]) = ($ex_line_s)/$k)\r\n        ex_line_c = :($(syms_c[k + 1]) = ($ex_line_c)/$k)\r\n        ex_calc.args[2*k + 1] = ex_line_s\r\n        ex_calc.args[2*k + 2] = ex_line_c\r\n    end\r\n\r\n    exout_s = :(($(syms_s[1]),))\r\n    for i = 2:N\r\n        push!(exout_s.args, syms_s[i])\r\n    end\r\n\r\n    exout_c = :(($(syms_c[1]),))\r\n    for i = 2:N\r\n        push!(exout_c.args, syms_c[i])\r\n    end\r\n\r\n    return quote\r\n               Base.@_inline_meta\r\n               $ex_calc\r\n               return STaylor1{N,T}($exout_s), STaylor1{N,T}($exout_c)\r\n            end\r\nend\r\n\r\n# Functions for STaylor1\r\n@generated function tanh(a::STaylor1{N,T}) where {N, T <: Number}\r\n\r\n    ex_calc = quote end\r\n    append!(ex_calc.args, Any[nothing for i in 1:(2*N)])\r\n    syms = Symbol[Symbol(\"c$i\") for i in 1:N]\r\n    syms2 = Symbol[Symbol(\"c2$i\") for i in 1:N]\r\n\r\n    ex_line_c = :($(syms[1]) = tanh(a[0]))\r\n    ex_line_c2 = :($(syms2[1]) = ($(syms[1]))^2)\r\n    ex_calc.args[1] = ex_line_c\r\n    ex_calc.args[2] = ex_line_c2\r\n\r\n    for k = 1:(N - 1)\r\n\r\n        kodd = k%2\r\n        kend = div(k - 2 + kodd, 2)\r\n        kdiv2 = div(k, 2)\r\n\r\n        ex_line_c = :($k*a[$k]*$(syms2[1]))\r\n        for i = 1:(k - 1)\r\n            q = k - i\r\n            ex_line_c = :($ex_line_c + ($q)*a[$q]*$(syms2[i+1]))\r\n        end\r\n        ex_line_c = :(a[$k] - $ex_line_c/$k)\r\n        ex_line_c = :($(syms[k + 1]) = $ex_line_c)\r\n        ex_calc.args[2*k + 1] = ex_line_c\r\n\r\n        ex_line_c2 = :(a[1]*a[$k])\r\n        @inbounds for i = 1:kend\r\n            ex_line_c2 = :($ex_line_c2 + a[$i + 1]*a[$k - $i])\r\n        end\r\n        ex_line_c2 = :(2*$ex_line_c2)\r\n\r\n        if kodd != 1\r\n            ex_line_c2 = :($ex_line_c2 + a[$kdiv2 + 1]^2)\r\n        end\r\n\r\n        ex_line_c2 = :($(syms2[k + 1]) = $ex_line_c2)\r\n        ex_calc.args[2*k + 2] = ex_line_c2\r\n    end\r\n\r\n    exout = :(($(syms[1]),))\r\n    for i = 2:N\r\n        push!(exout.args, syms[i])\r\n    end\r\n\r\n    return quote\r\n               Base.@_inline_meta\r\n               $ex_calc\r\n               return STaylor1{N,T}($exout)\r\n            end\r\nend\r\n", "meta": {"hexsha": "9a2d3853996063da8eeea3c4ca37887ffadaa8df", "size": 10978, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "mewilhel/StaticTaylorSeries.jl", "max_stars_repo_head_hexsha": "962b75010152ce076e8f5831279edc783a5a8361", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions.jl", "max_issues_repo_name": "mewilhel/StaticTaylorSeries.jl", "max_issues_repo_head_hexsha": "962b75010152ce076e8f5831279edc783a5a8361", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions.jl", "max_forks_repo_name": "mewilhel/StaticTaylorSeries.jl", "max_forks_repo_head_hexsha": "962b75010152ce076e8f5831279edc783a5a8361", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5142857143, "max_line_length": 81, "alphanum_fraction": 0.4661140463, "num_tokens": 3868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7656763329698191}}
{"text": "# p24.jl - pseudospectra of Davies's complex harmonic oscillator\n#         (For finer, slower plot, change 0:2 to 0:.5.)\n\n# Eigenvalues:\nN = 70; (D,x) = cheb(N); x = x[2:N];\nL = 6; x = L*x; D = D/L;                   # rescale to [-L,L]\nA = -D^2; A = A[2:N,2:N] + (1+3im)*diagm(x.^2);\nlambda = eigvals(A);\nclf(); plot(real(lambda),imag(lambda),\"k.\",markersize=6);\naxis([0,50,0,40])\n\n# Pseudospectra:\nx = 0:1:50; y = 0:1:40;  zz = x' .+ 1im*y;\nI = eye(N-1);\nminsvd(z) = minimum(svdvals(z*I-A));\nsigmin = [ minsvd(x[i]+1im*y[j]) for i=eachindex(x), j=eachindex(y) ];\ncontour(x,y,sigmin',levels=10.0.^(-4:.5:-.5));\n", "meta": {"hexsha": "d81fd6155ca914f8678856538e5979e122c54579", "size": 612, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p24.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p24.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p24.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0, "max_line_length": 70, "alphanum_fraction": 0.5555555556, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750466836961, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7656455337260634}}
{"text": "function initial_velocity(N::Int64;T=298.15,R=8.3145,m=1.0)\n  vel = [ [0.,0.] for i in 1:N]\n \n  for i in 1:N\n    angle = 2*pi*rand()\n    px = rand()\n    py = rand()\n    vel[i][1] = sqrt(-(2*R*T/m)*log(1-px)) * angle       # velocity in the x axis \n    vel[i][2] = sqrt(-(2*R*T/m)*log(1-py)) * angle       # velocity in the y axis\n  end\n\n  return vel\nend\n\nfunction norm(x::Vector{Float64})\n  s = 0.\n  for i in 1:length(x)  \n    s = s + x[i]^2\n  end\n  sqrt(s)  \nend\n\nfunction normVEL(x)\n  s = zeros(length(x))\n  for i in 1:length(x)\n    s[i] = norm(x[i])        \n  end \n  return s\nend\n\nexport initial_velocity, norm, normVEL\n\n\n# p(v)dv\np(v;m=1.,R=8.3145,T=298.15) = m/(R*T) * v * exp(-m*v^2/(2R*T)) \n\n# probability v < x\npv(x;m = 1., T = 298.15, R = 8.3145) = -exp(-m*x^2/(2*R*T)) + 1\n\n\n\n\n\n", "meta": {"hexsha": "a9bd66b444fd496d0e3cc3f15dc8f18233012738", "size": 788, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/initial_velocity.jl", "max_stars_repo_name": "viniciuspiccoli/simulationQP934", "max_stars_repo_head_hexsha": "1187384bddb098dba854d01db66d82891f6d6dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/initial_velocity.jl", "max_issues_repo_name": "viniciuspiccoli/simulationQP934", "max_issues_repo_head_hexsha": "1187384bddb098dba854d01db66d82891f6d6dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/initial_velocity.jl", "max_forks_repo_name": "viniciuspiccoli/simulationQP934", "max_forks_repo_head_hexsha": "1187384bddb098dba854d01db66d82891f6d6dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.9090909091, "max_line_length": 82, "alphanum_fraction": 0.5291878173, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666346, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7655475700984363}}
{"text": "module BVP1D\n\nusing LinearAlgebra\nusing OffsetArrays\n\nexport solve_bvp\n\nfunction solve_bvp(L, f, γ0, γL, P) \n    Δx = L / P\n    c = 1 / Δx^2\n    dv = fill(2c, P-1)\n    ev = fill(-c, P-1)\n    A = SymTridiagonal(dv, ev)\n    x_ = range(0; length=P+1, stop=L)\n    x = OffsetArray(x_, 0:P)\n    b = f.(x[1:P-1])\n    b[1]   += c * γ0\n    b[P-1] += c * γL\n    U = OffsetArray{Float64}(undef, 0:P)\n    U[0] = γ0\n    U[1:P-1] = A \\ b\n    U[P] = γL\n    return U, x\nend\n\nend # module BVP1D\n\n", "meta": {"hexsha": "e02f428f1d4cb2fffc7f78f57794a23863fc4656", "size": 479, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chap1/BVP1D.jl", "max_stars_repo_name": "billmclean/ComputationalMathsNotes", "max_stars_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T21:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:30:20.000Z", "max_issues_repo_path": "src/chap1/BVP1D.jl", "max_issues_repo_name": "billmclean/ComputationalMathsNotes", "max_issues_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chap1/BVP1D.jl", "max_forks_repo_name": "billmclean/ComputationalMathsNotes", "max_forks_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1071428571, "max_line_length": 40, "alphanum_fraction": 0.5240083507, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812336438725, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7655347300052139}}
{"text": "\n\n\n\"\"\"\n    B_SplineFFT{T, order} <: AbstractInterpolation{T, CircEdge, order}\n    B_SplineFFT( order::Int, n::Int, T::DataType=Float64)\n\nType containing spline coefficients for b-spline interpolation based on fft, using the fact that b-spline matrix is a circulant matrix\n\n# Type parameters\n- `T` : the type of data that is interpolate\n- `order::Int`: order of lagrange interpolation\n\n# Implementation :\n- `c_fft::Vector{Complex{T}}` : fft transform of coefficients\n- `parfft::PrepareFftBig` : fft precomputed data\n- `tabfct::Vector{Polynomial{T}}` : function table for interpolation\n\n# Arguments : \n- `n` : size of the matrix\n- `order` : the order of interpolation\n- `[T::DataType=Float64]` : The type values to interpolate \n\n\"\"\"\nstruct B_SplineFFT{T,order} <: B_Spline{T,CircEdge,order}\n    c_fft::Vector{Complex{T}}\n    parfft::PrepareFftBig\n    tabfct::Vector{Polynomial{T}}\n    function B_SplineFFT(order::Int, n::Int, T::DataType = Float64)\n        bspline = getbspline(order, 0)\n        tabfct_rat = map(x -> bspline[order-x](Polynomial([order - x, 1])), 0:order)\n        kl, ku = get_kl_ku(order)\n        c = zeros(T, n)\n        parfft = PrepareFftBig(n, T)\n        tab_coef = convert.(T, bspline.(1:order))\n        dec = n - kl - 1\n        for i = 1:order\n            c[(dec+i)%n+1] = tab_coef[i]\n        end\n        c_fft = fftgen(parfft, c)\n        return new{T,order}(c_fft, parfft, convert.(Polynomial{T}, tabfct_rat))\n    end\n    B_SplineFFT(o::Int, n::Int, _::T) where {T} = B_SplineFFT(o, n, T)\nend\nfunction sol(bsp::B_SplineFFT{T}, b::AbstractVector{T}) where {T}\n    return real(ifftgen(bsp.parfft, fftgen(bsp.parfft, b) ./ bsp.c_fft))\nend\nfunction sol!(Y::AbstractVector{T}, bsp::B_SplineFFT{T}, b::AbstractVector{T}) where {T}\n    Y .= real(ifftgen(bsp.parfft, fftgen(bsp.parfft, b) ./ bsp.c_fft))\nend\n\n", "meta": {"hexsha": "4cbd98da0899e2a336ba139ddb7e9536ac4707a7", "size": 1823, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bsplinefft.jl", "max_stars_repo_name": "JuliaVlasov/SemiLagrangian.jl", "max_stars_repo_head_hexsha": "f1a5c87eb434eca778f00dbdd660227fc4a47eae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-04T09:18:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T09:18:10.000Z", "max_issues_repo_path": "src/bsplinefft.jl", "max_issues_repo_name": "JuliaVlasov/SemiLagrangian.jl", "max_issues_repo_head_hexsha": "f1a5c87eb434eca778f00dbdd660227fc4a47eae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-12-18T08:28:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:02:12.000Z", "max_forks_repo_path": "src/bsplinefft.jl", "max_forks_repo_name": "JuliaVlasov/SemiLagrangian.jl", "max_forks_repo_head_hexsha": "f1a5c87eb434eca778f00dbdd660227fc4a47eae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0576923077, "max_line_length": 134, "alphanum_fraction": 0.6566099835, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7655235408667663}}
{"text": "\"\"\"\n`poro_elasticity_model(;\n    n = 980,\n    rho = 1e-3,\n    alpha = 0.79,\n    M = 1/7.80e3,\n    kappanu = 633.33,\n    eta = 1e-4,\n    force_download = false\n  )`\n\nThis function returns a port-Hamiltonian model of linear poroelasticity in a\nbounded Lipschitz domain as described in\n    Altmann, Mehrmann, Unger: Port-Hamiltonian Formulations of Poroelastic\n    Network Models\n# Arguments\n- `n`: System dimension (can only be either: 320, 980, or 1805). Default = 980.\n- `rho`: density. Default = `1e-3`.\n- `alpha`: Biot-Willis fluid-solid coupling coefficient. Default = 0.79.\n- `bm`: Biot-Modulus. Default = `1/7.8e3`.\n- `kappanu`: Quotient kappa/Nu, where kappa denotes the permeability and nu denotes the fluid viscosity. Default = 633.33.\n- `eta`: artificial damping coefficient. Default = `1e-4`.\n\"\"\"\nfunction poro_elasticity_model(;\n    n = 980,\n    rho = 1e-3,\n    alpha = 0.79,\n    bm = 1/7.80e3,\n    kappanu = 633.33,\n    eta = 1e-4,\n    force_download = false\n  )\n  Y, D, M, K, Bp, Bf, A = load_poro_raw_data(\n    n=n,\n    force_download = force_download\n  )\n  Y = rho*sparse(Y)\n  D = alpha*sparse(D)\n  M = 1/bm .* sparse(M)\n  K = kappanu*sparse(K)\n  A = sparse(A)\n  Bp = Bp'\n  Bf = Bf'\n  n = size(A, 1);\n  m = size(M, 1);\n  E = [Y spzeros(n,n+m); spzeros(n,n) A spzeros(n,m); spzeros(m,n+n) M];\n  J = [spzeros(n,n) -A D';A spzeros(n,n+m); -D spzeros(m,n+m)];\n  R = [spzeros(n,2*n+m); spzeros(n,2*n+m); spzeros(m,2*n) K] + eta*I\n  B = [zeros(n,1); Bf; Bp];\n  return E, J, R, B\nend\n\nfunction load_poro_raw_data(;\n    n = 980,\n    force_download = false\n  )\n  filename = \"poro-n$n.mat\"\n  url = \"https://zenodo.org/record/5702554/files/poro-n$n.mat?download=1\"\n  if n == 980\n    md5_hash = hex(0x2961a189be7049ffe2d476b18cb1f678)\n  elseif n == 320\n    md5_hash = hex(0x97afe8c34f0e9a56bbe86d0a51b7b626)\n  elseif n == 1805\n    md5_hash = hex(0xc61f6687da9cd26cbf2d880d7d3a9ac9)\n  else\n    throw(ArgumentError(\"Model size is either 320, 980, or 1805\"))\n  end\n  download_system_data_if_required(\n    filename,\n    url,\n    md5_hash,\n    force_download = force_download\n  )\n  dd = loadMAT(get_filepath(filename))\n  return dd[\"Y\"], dd[\"D\"], dd[\"M\"], dd[\"K\"], dd[\"Bp\"], dd[\"Bf\"], dd[\"A\"]\nend\n\nexport poro_elasticity_model\n", "meta": {"hexsha": "dd2a8a63e809c5f611a0d97b9ebf2de792c23be6", "size": 2224, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PoroModel.jl", "max_stars_repo_name": "Algopaul/PortHamiltonianBenchmarkSystems", "max_stars_repo_head_hexsha": "d37bd1ef6b02e1d98bc1905a16e41a915dd212e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-03T14:56:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T10:55:04.000Z", "max_issues_repo_path": "src/PoroModel.jl", "max_issues_repo_name": "Algopaul/PortHamiltonianBenchmarkSystems", "max_issues_repo_head_hexsha": "d37bd1ef6b02e1d98bc1905a16e41a915dd212e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-15T14:52:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-15T14:52:34.000Z", "max_forks_repo_path": "src/PoroModel.jl", "max_forks_repo_name": "Algopaul/PortHamiltonianBenchmarkSystems", "max_forks_repo_head_hexsha": "d37bd1ef6b02e1d98bc1905a16e41a915dd212e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1518987342, "max_line_length": 122, "alphanum_fraction": 0.6398381295, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7655235373679774}}
{"text": "\"\"\"\nN: universe dimension\nD: manifold dimension\nT: coordinate type\n\"\"\"\nstruct RectangleChart{N,D,T}\n  origin::SVector{N,T}\n  tangents::SVector{D,SVector{N,T}}\n  normal::SVector{N,T}\nend\n\nfunction RectangleChart(o, tgs)\n  n = tgs[1] × tgs[2]\n  n = normalize(n)\n  RectangleChart(o, tgs, n)\nend\n\nstruct RectangleNBD{N,D,T}\n  chart::RectangleChart{N,D,T}\n  parm::SVector{D,T}\n  cart::SVector{N,T}\nend\n\ncartesian(nbd::RectangleNBD) = nbd.cart\n\nfunction neighborhood(rect::RectangleChart{3,2}, uv)\n  o = rect.origin\n  t1, t2 = rect.tangents\n  u1, u2 = uv\n  cart = o + u1*t1 + u2*t2\n  RectangleNBD(rect, SVector(uv), cart)\nend\n\ngetindex(nbd::RectangleNBD, i) = nbd.cart[i]\nnormal(nbd::RectangleNBD) = nbd.chart.normal\n\nfunction quadpoints(chart::RectangleChart{3,2}, rule)\n\n  T = eltype(chart.origin)\n\n  o = chart.origin\n  t1 = chart.tangents[1]\n  t2 = chart.tangents[2]\n  j = norm(t1 × t2)\n  Q, P = rule\n  U1, W1 = legendre(Q, zero(T), one(T))\n  U2, W2 = legendre(P, zero(T), one(T))\n\n  #pts = [o + u1 * t1 + u2 * t2 for u1 in U1 for u2 in U2]\n  pts = [neighborhood(chart, (u1,u2)) for u1 in U1 for u2 in U2]\n  wts = [j*w1*w2 for w1 in W1 for w2 in W2]\n\n  collect(zip(pts,wts))\nend\n", "meta": {"hexsha": "4106bc2ed1cbbac08eb5522ef82f6e90d43d3056", "size": 1176, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rectangle.jl", "max_stars_repo_name": "sbadrian/CompScienceMeshes.jl", "max_stars_repo_head_hexsha": "27c6737d2a39bca7e97aa204f4595ef007defe9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2018-05-30T20:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:10:58.000Z", "max_issues_repo_path": "src/rectangle.jl", "max_issues_repo_name": "sbadrian/CompScienceMeshes.jl", "max_issues_repo_head_hexsha": "27c6737d2a39bca7e97aa204f4595ef007defe9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2017-04-11T14:45:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T14:06:03.000Z", "max_forks_repo_path": "src/rectangle.jl", "max_forks_repo_name": "sbadrian/CompScienceMeshes.jl", "max_forks_repo_head_hexsha": "27c6737d2a39bca7e97aa204f4595ef007defe9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2017-03-29T17:00:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T11:45:35.000Z", "avg_line_length": 21.3818181818, "max_line_length": 64, "alphanum_fraction": 0.6556122449, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222396, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7655235338691883}}
{"text": "\n# ------------------------------------------------------------------------------------------\n# # Julia 中的线性代数\n# > Based on work by Andreas Noack Jensen (MIT) (http://www.econ.ku.dk/phdstudent/noack/)\n# > with edits from Jane Herriman\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## 基础线性代数操作\n# 定义一个随机矩阵\n# ------------------------------------------------------------------------------------------\n\nA = rand(1:4,3,3)\n\n# ------------------------------------------------------------------------------------------\n# 定义一个元素全为 1 的向量\n# ------------------------------------------------------------------------------------------\n\nx = fill(1.0, (3,)) # = fill(1.0, 3)\n\n# ------------------------------------------------------------------------------------------\n# 注意 $A$ 的类型为 `Array{Int64,2}`，而 $x$ 的类型为 `Array{Float64,1}`。\n#\n# Julia 定义向量 `Vector{Type}` 的别名为 `Array{Type,1}`，矩阵`Matrix{Type}` 的别名为 `Array{Type,2}`。\n#\n# 许多线性代数的基础操作和其他语言一样\n#\n# ### 乘法\n# ------------------------------------------------------------------------------------------\n\nb = A*x\n\n# ------------------------------------------------------------------------------------------\n# ### 转置\n# 就像在其他语言中 `A'` 表示对 `A` 进行共轭转置\n# ------------------------------------------------------------------------------------------\n\nA'\n\n# ------------------------------------------------------------------------------------------\n# 我们还可以通过 `transpose` 函数获得转置矩阵\n# ------------------------------------------------------------------------------------------\n\ntranspose(A)\n\n# ------------------------------------------------------------------------------------------\n# ### 转置的乘法\n# Julia 中某些情况下可以省略 `*` 号\n# ------------------------------------------------------------------------------------------\n\nA'A\n\n# ------------------------------------------------------------------------------------------\n# ### 解线性方程组\n# 用方阵 $A$ 表示的线性方程组 $Ax=b$ 可以用左除运算符（函数）`\\` 求解\n# ------------------------------------------------------------------------------------------\n\nA\\b\n\n# ------------------------------------------------------------------------------------------\n# 超定线性方程组（overdetermined linear system）的情况下 `A\\b` 给出*最小二乘解（least squares solution）*\n# ------------------------------------------------------------------------------------------\n\nAtall = rand(3, 2)\n\nAtall\\b\n\n# ------------------------------------------------------------------------------------------\n# 缺秩最小二乘问题（a rank-deficient least squares problem）情况下，会给出*极小范数最小二乘解（minimum norm least\n# squares solution）*\n# ------------------------------------------------------------------------------------------\n\nv = rand(3)\nrankdef = hcat(v, v)\n\nrankdef\\b\n\n# ------------------------------------------------------------------------------------------\n# 欠定问题（an underdetermined solution）下，会给出 最小范数解（minimum norm solution）\n# ------------------------------------------------------------------------------------------\n\nbshort = rand(2)\nAshort = rand(2, 3)\n\nAshort\\bshort\n\n# ------------------------------------------------------------------------------------------\n# ## `LinearAlgebra` 包\n#\n# 如上所示，Julia默认自带了很多线性代数操作，而标准库 `LinearAlgebra` 提供了更多的相关名词和函数。\n# 特别是它提供了因子分解和一些结构化矩阵类型。\n# 和其他包一样，可以通过 `using LinearAlgebra` 引入这些额外的特征。\n# ------------------------------------------------------------------------------------------\n\nusing LinearAlgebra\n\n# ------------------------------------------------------------------------------------------\n# ## 练习\n#\n# ### 10.1\n# 计算向量 `v` 和它自己的内积，并赋值给 `dot_v`。\n# ------------------------------------------------------------------------------------------\n\nv = [1,2,3]\n\n# 在此作答\ndot_v = v\n\n@assert dot_v == 14\n\n# ------------------------------------------------------------------------------------------\n# ### 10.2\n# 计算向量 v 和它自己的外积(Outer product)，并赋值给 `outer_v`。\n#\n# 提示：外积是一种克罗内克积(Kronecker product)\n#\n# 计算叉积(cross product)，赋值给 `cross_v`\n# ------------------------------------------------------------------------------------------\n\n# 在此作答\nouter_v = v\ncross_v = v\n\n@assert outer_v == [1 2 3\n                    2 4 6\n                    3 6 9]\n\n@assert cross_v == [0, 0, 0]\n\n# ------------------------------------------------------------------------------------------\n# 请在完成练习运行 `@assert` 块以检测结果是否正确，若无报错即为正确。\n# ------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "9c01888c54b8888ae95595c6b3d2164250750afa", "size": 4427, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/zh-cn/intro-to-julia-ZH/11.基本线性代数.jl", "max_stars_repo_name": "NahsiN/JuliaTutorials", "max_stars_repo_head_hexsha": "6d61077a0f6565e19305cddab0adde79d232e147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 535, "max_stars_repo_stars_event_min_datetime": "2020-07-15T14:56:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T12:50:32.000Z", "max_issues_repo_path": ".nbexports/zh-cn/intro-to-julia-ZH/11.基本线性代数.jl", "max_issues_repo_name": "NahsiN/JuliaTutorials", "max_issues_repo_head_hexsha": "6d61077a0f6565e19305cddab0adde79d232e147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2018-02-25T22:53:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-14T02:15:50.000Z", "max_forks_repo_path": ".nbexports/zh-cn/intro-to-julia-ZH/11.基本线性代数.jl", "max_forks_repo_name": "NahsiN/JuliaTutorials", "max_forks_repo_head_hexsha": "6d61077a0f6565e19305cddab0adde79d232e147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 394, "max_forks_repo_forks_event_min_datetime": "2020-07-14T23:22:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:12:57.000Z", "avg_line_length": 33.2857142857, "max_line_length": 92, "alphanum_fraction": 0.2374068218, "num_tokens": 1023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075711974104, "lm_q2_score": 0.7956581024858785, "lm_q1q2_score": 0.7655086844862289}}
{"text": "module GMMbox\n\nusing Distances\nusing Distributions\nusing Clustering\nimport Base.rand\nimport Base.rand!\n\nexport gaussian, logprob!, logprob, gmm, rand, rand!\n\nmutable struct gaussian{T<:AbstractFloat}\n  ndim::Int64\n  mean::AbstractArray{T,2}\n  cov::AbstractArray{T,2}\nend\n\ngaussian(ndim::Integer) = gaussian(ndim,zeros(ndim,1),eye(ndim))\ngaussian(data::Matrix{T} where T<:AbstractFloat)  = gaussian(size(data,1),mean(data,2),cov(data,2))\n\nmutable struct gmm{T<:AbstractFloat}\n  nmix::Int64\n  wts::AbstractArray{T,2}\n  mix::AbstractArray{gaussian{T}}\nend\n\nfunction gmm(nmix::Integer, data::Matrix{T} where T <: AbstractFloat; method = \"rand\")\n  if(method==\"rand\")\n    ndim = size(data,1);\n    dcov = cov(data,2);\n    dmvn = MvNormal(vec(mean(data,2)),dcov);\n    mix = Array{gaussian{eltype(data)}}(nmix);\n    for i=1:nmix\n      mixmean = convert(Array{eltype(data)},rand(dmvn));\n      mix[i] = gaussian(ndim,reshape(mixmean,ndim,1),dcov);\n    end\n  elseif(method==\"kmeans\")\n    km = kmeans(data,nmix);\n    mix = Array{gaussian{eltype(data)}}(nmix);\n    dcov = cov(data,2);\n    for i=1:nmix\n      mix[i] = gaussian(data[:,find(km.assignments.==i)]);\n      mix[i].cov = dcov;\n    end\n  end\n\n  return gmm(nmix,convert(Array{eltype(data)},(1/nmix)*ones(nmix,1)),mix);\nend\n\nrand!(g::gaussian{T},data::Matrix{T}) where T <: AbstractFloat = rand!(MvNormal(vec(g.mean),g.cov),data);\nrand(g::gaussian{T},nvec::Integer) where T <: AbstractFloat = rand(MvNormal(vec(g.mean),g.cov),nvec);\n\nfunction rand!(gm::gmm{T},data::Matrix{T}) where T <: AbstractFloat\n  ftype = eltype(data);\n  nvec = size(data,2);\n  pmix = rand(ftype,nvec);\n  nvecmix = zeros(Int64,gm.nmix);\n  thr = zeros(ftype,1);\n  for i=1:gm.nmix\n    nvecmix[i] = sum((pmix.>=thr).&(pmix.<thr+gm.wts[i]))\n    thr += gm.wts[i];\n  end\n  if(sum(nvecmix)<nvec)\n    nvecmix[end] += nvec-sum(nvecmix);\n    println(\"sum of number of samples per mixture not equal to requested number of samples\");\n  end\n  sindx = 1;\n  eindx = 0;\n  for i=1:gm.nmix\n    eindx += nvecmix[i];\n    data[:,sindx:eindx] = rand(gm.mix[i],nvecmix[i]);\n    sindx += nvecmix[i];\n  end\n  return nothing\nend\n\nfunction rand(gm::gmm{T},nvec::Integer) where T <: AbstractFloat\n  ftype = eltype(gm.wts);\n  pmix = rand(ftype,nvec);\n  nvecmix = zeros(Int64,gm.nmix);\n  thr = zeros(ftype,1);\n  for i=1:gm.nmix\n    nvecmix[i] = sum((pmix.>=thr).&(pmix.<thr+gm.wts[i]))\n    thr += gm.wts[i];\n  end\n  if(sum(nvecmix)<nvec)\n    nvecmix[end] += nvec-sum(nvecmix);\n    println(\"sum of number of samples per mixture not equal to requested number of samples\");\n  end\n  data = zeros(ftype,gm.mix[1].ndim,sum(nvec));\n  sindx = 1;\n  eindx = 0;\n  for i=1:gm.nmix\n    eindx += nvecmix[i];\n    data[:,sindx:eindx] = rand(gm.mix[i],nvecmix[i]);\n    sindx += nvecmix[i];\n  end\n  return data\nend\n\n\nlogprob!(p::Array{T},g::gaussian{T},data::Matrix{T}) where T <: AbstractFloat = logpdf!(p,MvNormal(vec(g.mean),g.cov),data)\nlogprob(g::gaussian{T},data::Matrix{T}) where T <: AbstractFloat = logpdf(MvNormal(vec(g.mean),g.cov),data)\n\nfunction logprob!(p::Array{T},gm::gmm{T},data::Matrix{T}) where T <: AbstractFloat\n  mixprob = zeros(eltype(data),size(data,2),gm.nmix);\n  for i=1:gm.nmix\n    mixprob[:,i] = logprob(gm.mix[i],data);\n  end\n  maxprob = maximum(mixprob,2);\n  broadcast!(-,mixprob,mixprob,maxprob);\n  p .= vec(log.((exp.(mixprob))*gm.wts) .+ maxprob);\n  return nothing\nend\n\nfunction logprob(gm::gmm{T},data::Matrix{T}) where T <: AbstractFloat\n  mixprob = zeros(eltype(data),size(data,2),gm.nmix);\n  for i=1:gm.nmix\n    mixprob[:,i] = logprob(gm.mix[i],data);\n  end\n  maxprob = maximum(mixprob,2);\n  broadcast!(-,mixprob,mixprob,maxprob);\n  return vec(log.((exp.(mixprob))*gm.wts) .+ maxprob);\nend\n\n\n\n#=\nfunction logprob!(p::Matrix{T},g::gaussian{T},data::Matrix{T}) where T <: AbstractFloat\n  logpdf!(reshape(p,length(p)),MvNormal(vec(g.mean),g.cov),data);\n  reshape(p,length(p),1);\nend\n=#\n\n#=\n#logpdf and logpdf! using Distributions.jl is faster than this version which uses Distances.jl for Float32 - not using this version for CPU code\nfunction logprob!(p::Matrix{T},g::gaussian{T},data::Matrix{T}) where T <: AbstractFloat\n  ndim = size(data,1);\n  icov = inv(g.cov);\n  lconst = ndim*log(2*pi) + log(det(g.cov));\n  pairwise!(p,SqMahalanobis(icov),data,g.mean);\n  p .+= lconst;\n  p .*= -0.5;\n  return nothing\nend\n\nfunction logprob(g::gaussian{T},data::Matrix{T}) where T <: AbstractFloat\n  p = zeros(eltype(data),size(data,2),1);\n  ndim = size(data,1);\n  icov = inv(g.cov);\n  lconst = ndim*log(2*pi) + log(det(g.cov));\n  pairwise!(p,SqMahalanobis(icov),data,g.mean);\n  p .+= lconst;\n  p .*= -0.5;\n  return p\nend\n=#\n\n\nend\n", "meta": {"hexsha": "f9c9d74d14a0ddd47786ed93150127d910e3cee0", "size": 4620, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "GMMbox.jl", "max_stars_repo_name": "vidhyasaharan/julia_code", "max_stars_repo_head_hexsha": "473e5d85a0884fb0cd7c2bf00e33f7c4d9c1a2e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GMMbox.jl", "max_issues_repo_name": "vidhyasaharan/julia_code", "max_issues_repo_head_hexsha": "473e5d85a0884fb0cd7c2bf00e33f7c4d9c1a2e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GMMbox.jl", "max_forks_repo_name": "vidhyasaharan/julia_code", "max_forks_repo_head_hexsha": "473e5d85a0884fb0cd7c2bf00e33f7c4d9c1a2e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.875, "max_line_length": 144, "alphanum_fraction": 0.6543290043, "num_tokens": 1581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8740772286044095, "lm_q1q2_score": 0.7655054608398786}}
{"text": "# Some global variables that will stay constant\nα = 0.013\nα_q = (1-(1-α)^3)\nb_param = 0.0124\nd_param = 0.00822\nβ = 0.98\nγ = 1.0\nσ = 2.0\n\n# The default wage distribution: a discretized log normal\nlog_wage_mean, wage_grid_size, max_wage = 20, 200, 170\nw_vec = linspace(1e-3, max_wage, wage_grid_size + 1)\nlogw_dist = Normal(log(log_wage_mean), 1)\ncdf_logw = cdf.(logw_dist, log.(w_vec))\npdf_logw = cdf_logw[2:end] - cdf_logw[1:end-1]\np_vec = pdf_logw ./ sum(pdf_logw)\nw_vec = (w_vec[1:end-1] + w_vec[2:end]) / 2\n\n\"\"\"\nCompute the reservation wage, job finding rate and value functions of the\nworkers given c and τ.\n\n\"\"\"\nfunction compute_optimal_quantities(c::AbstractFloat, τ::AbstractFloat)\n    mcm = McCallModel(α_q,\n                      β,\n                      γ,\n                      c-τ,                # post-tax compensation\n                      σ,\n                      collect(w_vec-τ),  # post-tax wages\n                      p_vec)\n\n\n    w_bar, V, U = compute_reservation_wage(mcm, return_values=true)\n    λ = γ * sum(p_vec[w_vec - τ .> w_bar])\n\n    return w_bar, λ, V, U\nend\n\n\"\"\"\nCompute the steady state unemployment rate given c and tau using optimal\nquantities from the McCall model and computing corresponding steady state\nquantities\n\n\"\"\"\nfunction compute_steady_state_quantities(c::AbstractFloat, τ::AbstractFloat)\n    w_bar, λ_param, V, U = compute_optimal_quantities(c, τ)\n\n    # Compute steady state employment and unemployment rates\n    lm = LakeModel(λ=λ_param, α=α_q, b=b_param, d=d_param)\n    x = rate_steady_state(lm)\n    u_rate, e_rate = x\n\n    # Compute steady state welfare\n    w = sum(V .* p_vec .* (w_vec - τ .> w_bar)) / sum(p_vec .* (w_vec - τ .> w_bar))\n    welfare = e_rate .* w + u_rate .* U\n\n    return u_rate, e_rate, welfare\nend\n\n\"\"\"\nFind tax level that will induce a balanced budget.\n\n\"\"\"\nfunction find_balanced_budget_tax(c::Real)\n    function steady_state_budget(t::Real)\n      u_rate, e_rate, w = compute_steady_state_quantities(c, t)\n      return t - u_rate * c\n    end\n\n    τ = brent(steady_state_budget, 0.0, 0.9 * c)\n\n    return τ\nend\n\n# Levels of unemployment insurance we wish to study\nNc = 60\nc_vec = linspace(5.0, 140.0, Nc)\n\ntax_vec = Vector{Float64}(Nc)\nunempl_vec = Vector{Float64}(Nc)\nempl_vec = Vector{Float64}(Nc)\nwelfare_vec = Vector{Float64}(Nc)\n\nfor i = 1:Nc\n    t = find_balanced_budget_tax(c_vec[i])\n    u_rate, e_rate, welfare = compute_steady_state_quantities(c_vec[i], t)\n    tax_vec[i] = t\n    unempl_vec[i] = u_rate\n    empl_vec[i] = e_rate\n    welfare_vec[i] = welfare\nend\n\nfig, axes = subplots(2, 2, figsize=(15, 10))\n\nplots = [unempl_vec, empl_vec, tax_vec, welfare_vec]\ntitles = [\"Unemployment\", \"Employment\", \"Tax\", \"Welfare\"]\n\nfor (ax, plot, title) in zip(axes, plots, titles)\n    ax[:plot](c_vec, plot, \"b-\", lw=2, alpha=0.7)\n    ax[:set](title=title)\nend\n\nfig[:tight_layout]()\n", "meta": {"hexsha": "c98b014a4999a56daa41f7ebc95fa4ba51c425e0", "size": 2852, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lake_model/lake_fiscal_policy.jl", "max_stars_repo_name": "chenwang/QuantEcon.lectures.code", "max_stars_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lake_model/lake_fiscal_policy.jl", "max_issues_repo_name": "chenwang/QuantEcon.lectures.code", "max_issues_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lake_model/lake_fiscal_policy.jl", "max_forks_repo_name": "chenwang/QuantEcon.lectures.code", "max_forks_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-30T13:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-30T13:08:09.000Z", "avg_line_length": 27.1619047619, "max_line_length": 84, "alphanum_fraction": 0.6553295933, "num_tokens": 893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7654827302111962}}
{"text": "using FastGaussQuadrature\ninclude(\"chebyshev.jl\")\ninclude(\"pgrid.jl\")\n\nidx(ki, xi, order) = (ki - 1) * order + xi\n\nstruct CompositeGrid\n    grid::Vector{Float64} # panel x finegrid\n    wgrid::Vector{Float64}\n    panel::Vector{Float64}\n    x::Vector{Float64}\n    w::Vector{Float64}\n    # xp::Matrix{Float64} # the fine grid\n    # wp::Matrix{Float64} # the weight of the fine grid\n    Np::Int  # number of panel - 1\n    order::Int  # number of fine grid\n    type::Symbol\n    function CompositeGrid(panel, order, type::Symbol)\n        if type == :cheb\n            x, w = barychebinit(order)\n        elseif type == :gaussian\n            x, w = gausslegendre(order)\n        else\n            throw(\"not implemented!\")\n        end\n\n        # println(\"Quadrature type : \", type)\n        # println(\"Quadrature points : \", x)\n        # println(\"Quadrature weights: \", w)\n\n        Np = length(panel) - 1\n\n        grid = zeros(Float64, Np * order)\n        wgrid = zeros(Float64, Np * order)\n        # xp = zeros(Float64, (Np, order))\n        # wp = zeros(Float64, (Np, order))\n\n        for p in 1:Np\n            a, b = panel[p], panel[p + 1]\n            for xi in 1:order\n                index = idx(p, xi, order)\n                grid[index] = (a + b) / 2 + (b - a) / 2 * x[xi]\n                wgrid[index] = (b - a) / 2 * w[xi]\n            end\n        end\n\n        return new(grid, wgrid, panel, x, w, Np, order, type)\n    end\nend\n\nfunction KPanel(Nk, kF, maxK, minK)\n    panel = Grid.boseKUL(0.5 * kF, maxK, minK, Nk, 1).grid\n    panel[1] = 0.0  # the kgrid start with 0.0\n    return panel\nend\n\nfunction QPanel(Nk, kF, maxK, minK, k)\n    panel = pGrid(k, kF, maxK, minK, [Nk,Nk,Nk,Nk]).grid\n\n    # panel = Grid.boseKUL(0.5 * kF, maxK, minK, Nk, 1).grid\n    # panel[1] = 0.0  # the kgrid start with 0.0\n\n    return panel\nend\n\n\"\"\"\ninterpolate!(f, k::CompositeGrid, grid)\n\nmap f array in the grid k to a new grid \n\n# Arguments\n- f::Vector{Float64}: vector of data.\n- k::CompositeGrid: the grid object that f is defined on\n- grid::Vector{Float64}: new grid points \n\"\"\"\nfunction interpolate(f, k::CompositeGrid, grid)\n    @assert k.type == :cheb\n    order = k.order\n    ff = zeros(eltype(f), length(grid))\n    kpidx = 1 # panel index of the kgrid\n    head, tail = idx(kpidx, 1, order), idx(kpidx, order, order) \n    # extract all x in the kpidx-th k panel\n    fx = @view f[head:tail] # all F in the same kpidx-th K panel\n    x = @view k.grid[head:tail]\n    w = @view k.wgrid[head:tail]\n\n    for (qi, q) in enumerate(grid)\n        # for a given q, one needs to find the k panel to do interpolation\n        if q > k.panel[kpidx + 1]\n            # if q is too large, move k panel to the next\n            # println(\"before $q, $kpidx, $(k.panel[kpidx]) -> $(k.panel[kpidx + 1])\")\n            while q > kgrid.panel[kpidx + 1]\n                kpidx += 1\n            end\n            # println(\"after $q, $kpidx, $(k.panel[kpidx]) -> $(k.panel[kpidx + 1])\")\n            head, tail = idx(kpidx, 1, order), idx(kpidx, order, order) \n            fx = @view f[head:tail] # all F in the same kpidx-th K panel\n            x = @view k.grid[head:tail]\n            w = @view k.wgrid[head:tail]\n            @assert kpidx <= k.Np\n        end\n        ff[qi] = barycheb(order, q, fx, w, x) # the interpolation is independent with the panel length\n        # @assert k.panel[kpidx - 1][order] <= q <= k.panel[pidx + 1][1] \"$q for kpidx=$kpidx with $x\"\n    end\n    return ff\nend\n\nif abspath(PROGRAM_FILE) == @__FILE__\n    grid=CompositeGrid([0.0, 1.0, 2.0], 4, :cheb)\n    println(grid.grid)\nend\n", "meta": {"hexsha": "680b358d4ecf162a91f69018d19faecb049a7707", "size": 3556, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/old/old_com_grid.jl", "max_stars_repo_name": "quantumstatistics/CompositeGrids.jl", "max_stars_repo_head_hexsha": "6bf230eb4267749adbcfb1a80ddffd6899e7317d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-21T03:44:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T22:58:02.000Z", "max_issues_repo_path": "src/old/old_com_grid.jl", "max_issues_repo_name": "quantumstatistics/CompositeGrids.jl", "max_issues_repo_head_hexsha": "6bf230eb4267749adbcfb1a80ddffd6899e7317d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2021-08-16T19:16:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T01:55:31.000Z", "max_forks_repo_path": "src/old/old_com_grid.jl", "max_forks_repo_name": "quantumstatistics/CompositeGrids.jl", "max_forks_repo_head_hexsha": "6bf230eb4267749adbcfb1a80ddffd6899e7317d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-22T21:04:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T21:04:22.000Z", "avg_line_length": 31.75, "max_line_length": 102, "alphanum_fraction": 0.5624296963, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7654827264778856}}
{"text": "# ----------\r\n# Vector Calculus Module, Only work on peroideric boundary!\r\n# ----------\r\n\r\nfunction Curl(B1::Array,B2::Array,B3::Array;\r\n              Lx = 2π, Ly = Lx, Lz = Lx,T = Float32)\r\n    nx,ny,nz = size(B1);\r\n    grid = ThreeDGrid(nx, Lx, ny, Ly, nz, Lz, T = T);\r\n    cB1,cB2,cB3 = Curl(B1,B2,B3,grid;Lx = Lx, Ly = Ly, Lz = Lz,T = T)\r\n    return cB1,cB2,cB3;\r\nend\r\n\r\nfunction Curl(B1::Array,B2::Array,B3::Array,grid;\r\n              Lx = 2π, Ly = Lx, Lz = Lx,T = Float32)\r\n    #funtion of computing ∇×Vector using the fourier method\r\n    # fft(∇×Vector) -> im * k × V\r\n    #| i j k  |\r\n    #| x y z  |\r\n    #|B1 B2 B3|\r\n    #\r\n    nx,ny,nz = size(B1);\r\n    B1h = zeros(Complex{T},(div(nx,2)+1,ny,nz));\r\n    B2h = zeros(Complex{T},(div(nx,2)+1,ny,nz));\r\n    B3h = zeros(Complex{T},(div(nx,2)+1,ny,nz));\r\n    cBxh = copy(B1h); \r\n    cByh = copy(B2h);\r\n    cBzh = copy(B3h);\r\n    mul!(B1h, grid.rfftplan, B1); \r\n    mul!(B2h, grid.rfftplan, B2); \r\n    mul!(B3h, grid.rfftplan, B3);\r\n        \r\n    for k in 1:nz, j in 1:ny,i in 1:div(nx,2)+1 \r\n       x,y,z = grid.kr[i],grid.l[j],grid.m[k]; \r\n       cBxh[i,j,k] = im*(y*B3h[i,j,k] - z*B2h[i,j,k]);\r\n       cByh[i,j,k] = im*(z*B1h[i,j,k] - x*B3h[i,j,k]);\r\n       cBzh[i,j,k] = im*(x*B2h[i,j,k] - y*B1h[i,j,k]);\r\n    end\r\n    \r\n    cB1,cB2,cB3 = zeros(T,size(B1)),zeros(T,size(B1)),zeros(T,size(B1));\r\n    ldiv!(cB1, grid.rfftplan, deepcopy(cBxh));  \r\n    ldiv!(cB2, grid.rfftplan, deepcopy(cByh));\r\n    ldiv!(cB3, grid.rfftplan, deepcopy(cBzh));\r\n    return cB1,cB2,cB3\r\nend\r\n\r\nfunction Div(B1::Array,B2::Array,B3::Array;\r\n             Lx = 2π, Ly = Lx, Lz = Lx,T = Float32)\r\n    nx,ny,nz = size(B1);\r\n    grid = ThreeDGrid(nx, Lx, ny, Ly, nz, Lz, T = T);\r\n    cB1 = Div(B1,B2,B3,grid;Lx = Lx, Ly = Ly, Lz = Lz,T = T);\r\n\r\n    return cB1\r\nend\r\n\r\nfunction Div(B1::Array,B2::Array,B3::Array,grid;\r\n             Lx = 2π, Ly = Lx, Lz = Lx,T = Float32)\r\n    #funtion of computing ∇̇ ⋅ Vector using the fourier method\r\n    # fft(∇·Vector) -> im * k ⋅ V\r\n    # = im* x*B1 + y*B2 + z*B3\r\n    nx,ny,nz = size(B1);\r\n    B1h = zeros(Complex{T},(div(nx,2)+1,ny,nz));\r\n    B2h = zeros(Complex{T},(div(nx,2)+1,ny,nz));\r\n    B3h = zeros(Complex{T},(div(nx,2)+1,ny,nz));\r\n    Dot = copy(B1h);\r\n    mul!(B1h, grid.rfftplan, B1); \r\n    mul!(B2h, grid.rfftplan, B2); \r\n    mul!(B3h, grid.rfftplan, B3);\r\n        \r\n    for k in 1:nz, j in 1:ny,i in 1:div(nx,2)+1 \r\n       x,y,z = grid.kr[i],grid.l[j],grid.m[k]; \r\n       Dot[i,j,k] = x*B1h[i,j,k] + y*B2h[i,j,k] + z*B3h[i,j,k];\r\n    end\r\n    \r\n    cB1 = zeros(T,size(B1))\r\n    ldiv!(cB1, grid.rfftplan, deepcopy(Dot));  \r\n\r\n    return cB1\r\nend\r\n\r\nfunction LaplaceSolver(B::Array; Lx=2π, Ly = Lx, Lz = Lz, T = Float32)\r\n    nx,ny,nz = size(B);\r\n    grid = ThreeDGrid(nx, Lx, ny, Ly, nz, Lz, T = T);\r\n    Φ   = LaplaceSolver(B,grid; Lx=2π, Ly = Lx, Lz = Lz, T = Float32);\r\n    return Φ\r\nend\r\n\r\nfunction LaplaceSolver(B::Array,grid; Lx=2π, Ly = Lx, Lz = Lz, T = Float32)\r\n    #=\r\n    funtion of computing ΔΦ = B using the fourier method, must be peroidic condition\r\n    Considering in k-space, k² Φ' = B', we would get Φ = F(B'/k²)\r\n    =#\r\n    nx,ny,nz = size(B);\r\n    Φ    = zeros(T,nx,ny,nz);\r\n    Bh   = zeros(ComplexF32,(div(nx,2)+1,ny,nz));\r\n    mul!(Bh, grid.rfftplan, B); \r\n    for k in 1:nz, j in 1:ny, i in 1:div(nx,2)+1\r\n       x,y,z = grid.kr[i],grid.l[j],grid.m[k]; \r\n       k² = x^2 + y^2 + z^2;\r\n       Bh[i,j,k] = Bh[i,j,k]/k²;\r\n       if k² == 0; Bh[i,j,k] = 0; end \r\n    end\r\n    ldiv!(Φ, grid.rfftplan, deepcopy(Bh));\r\n    return Φ;\r\nend\r\n\r\nfunction Crossproduct(A1,A2,A3,B1,B2,B3)\r\n    C1 = @.  (A2*B3 - A3*B2);\r\n    C2 = @. -(A1*B3 - A3*B1); \r\n    C3 = @.  (A1*B2 - A2*B1);\r\n    return C1,C2,C3\r\nend\r\n\r\nfunction Dotproduct(A1,A2,A3,B1,B2,B3)\r\n    return A1.*B1 + A2.*B2 + A3.*B3 \r\nend\r\n", "meta": {"hexsha": "512730dc953610e0eec0088ebddc921aa23f46cd", "size": 3785, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/VectorCalculus.jl", "max_stars_repo_name": "MHDFlows/MHDFlows", "max_stars_repo_head_hexsha": "0861ca1aae752b5b3f6478ce71d0cb3ad106632e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-28T05:55:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T03:48:38.000Z", "max_issues_repo_path": "src/utils/VectorCalculus.jl", "max_issues_repo_name": "MHDFlows/MHDFlows", "max_issues_repo_head_hexsha": "0861ca1aae752b5b3f6478ce71d0cb3ad106632e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/VectorCalculus.jl", "max_forks_repo_name": "MHDFlows/MHDFlows", "max_forks_repo_head_hexsha": "0861ca1aae752b5b3f6478ce71d0cb3ad106632e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6293103448, "max_line_length": 85, "alphanum_fraction": 0.5154557464, "num_tokens": 1592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.765482724397034}}
{"text": "export ShepardInterpolator, RBFInterpolator\nexport multiquadratic, invmultiquadratic, gaussian\n\nusing LinearAlgebra: Symmetric\n\n#-------------------------------------------------------------------------------\n\nfunction distance(a, b, n::Int)\n    r = 0.0\n    for i = 1:n\n        @inbounds d = a[i] - b[i]\n        r += d*d\n    end\n    sqrt(r)\nend\n\nfunction checkcoords(X, y)\n    @assert size(X)[2] > 1 \"Generally it doesn't make sense to apply scattered interpolation methods in one dimension. Consider using a 1D interpolator.\"\n    p = size(X)[1]\n    n = length(y)\n    @assert p == n \"number of points in X ($p) does not match number of values in y ($n)\"\nend\n\nfunction checkdims(x, N::Int)\n    n = length(x)\n    @assert n == N \"Number of interpolation coordinates ($n) does not match number of interpolator dimensions ($N)\"\nend\n\nstruct ScatteredPoints{T}\n    #number of dimensions\n    N::Int64\n    #number of points\n    p::Int64\n    #table of points, p x N\n    X::Array{T,2}\n    #vector of values\n    y::Vector{T}\nend\n\nfunction ScatteredPoints(X, y)\n    checkcoords(X, y)\n    N = size(X)[2]\n    p = size(X)[1]\n    ScatteredPoints(N, p, X, y)\nend\n\n#-------------------------------------------------------------------------------\n\n\"\"\"\n    multiquadratic(r, ϵ)\n\n``\\\\sqrt{1 + (r/ϵ)^2}``\n\"\"\"\nmultiquadratic(r, ϵ) = sqrt(1 + (r/ϵ)^2)\n\n\"\"\"\n    invmultiquadratic(r, ϵ)\n\n``\\\\frac{1}{\\\\sqrt{1 + (r/ϵ)^2}}``\n\"\"\"\ninvmultiquadratic(r, ϵ) = 1/multiquadratic(r, ϵ)\n\n\"\"\"\n    gaussian(r, ϵ)\n\n``e^{-r^2/ϵ^2}``\n\"\"\"\ngaussian(r, ϵ) = exp(-r^2/ϵ^2)\n\nstruct RBFInterpolator{T,F}\n    #interpolation points\n    S::ScatteredPoints{T}\n    #radial basis function\n    rbf::F\n    #distance scale factor\n    ϵ::T\n    #function weights\n    w::Vector{T}\nend\n\n\"\"\"\n    RBFInterpolator(X, y, ϵ, rbf=invmultiquadratic)\n\nConstruct a radial basis function (RBF) interpolator for an n-dimensional set of points with coordinates `X` and values `y`. `X` must be an p × N array, where p is the number of points and N is the number of dimensions. `y` must be a length p vector. The value of `ϵ` scales the radial basis function of choice, `f`, which is [`invmultiquadratic`](@ref) by default. Any function in the form ``ϕ(r,ϵ)`` can be passed to the `rbf` argument, where \\$r\\$ is the distance between points and ``ϵ`` is a scaling factor.\n\"\"\"\nfunction RBFInterpolator(X::AbstractMatrix,\n                         y::AbstractVector,\n                         ϵ,\n                         rbf::F=multiquadratic) where {F}\n    S = ScatteredPoints(X, y)\n    #matrix of basis function evaluations\n    A = ones(eltype(y), S.p, S.p)\n    for i = 1:S.p\n        a = view(S.X,i,:)\n        for j = i+1:S.p\n            b = view(S.X,j,:)\n            r = distance(a, b, S.N)\n            A[i,j] = rbf(r, ϵ)\n        end\n    end\n    #solve for weights\n    w = Symmetric(A)\\S.y\n    #construct\n    RBFInterpolator(S, rbf, convert(eltype(y), ϵ), w)\nend\n\nfunction RBF(Φ::RBFInterpolator, x)\n    checkdims(x, Φ.S.N)\n    y = 0.0\n    for i = 1:Φ.S.p\n        #distance\n        r = distance(x, view(Φ.S.X,i,:), Φ.S.N)\n        #weighted evaluation\n        @inbounds y += Φ.w[i]*Φ.rbf(r, Φ.ϵ)\n    end\n    return y\nend\n\nfunction (Φ::RBFInterpolator)(x::Union{AbstractVector,Tuple})\n    RBF(Φ, x)\nend\n\nfunction (Φ::RBFInterpolator)(x::Number...)\n    RBF(Φ, collect(Float64, x))\nend\n\n#-------------------------------------------------------------------------------\n\nstruct ShepardInterpolator{T}\n    #interpolation points\n    S::ScatteredPoints{T}\n    #power-law exponent\n    a::Float64\nend\n\n\"\"\"\n    ShepardInterpolator(X, y, a=3)\n\nConstruct a `ShepardInterpolator` for an n-dimensional set of points with coordinates `X` and values `y`. `X` must be an p × N array, where p is the number of points and N is the number of dimensions. `y` must be a length p vector. The value of `a` defines the distance weighting function ``r^{-a}``.\n\"\"\"\nfunction ShepardInterpolator(X::AbstractMatrix,\n                             y::AbstractVector,\n                             a::Real=3.0)\n    ShepardInterpolator(ScatteredPoints(X, y), a)\nend\n\nfunction shepard(Φ::ShepardInterpolator, x)\n    checkdims(x, Φ.S.N)\n    n = 0.0\n    d = 0.0\n    for i = 1:Φ.S.p\n        #distance\n        r = distance(x, view(Φ.S.X,i,:), Φ.S.N)\n        #evaluate weighting function\n        f = 1.0/r^Φ.a\n        #weigted and unweighted contribution to numertor and denominator\n        @inbounds n += Φ.S.y[i]*f\n        d += f\n    end\n    return n/d\nend\n\n(Φ::ShepardInterpolator)(x::Union{AbstractVector,Tuple}) = shepard(Φ, x)\n\n(Φ::ShepardInterpolator)(x::Number...) = shepard(Φ, x)\n", "meta": {"hexsha": "ec60057c22b00b61e941bdbc3ccb95bb2d59dd98", "size": 4567, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scattered.jl", "max_stars_repo_name": "wordsworthgroup/BasicInterpolators.jl", "max_stars_repo_head_hexsha": "1a43e6e657377ee9de53c721cf58141363036e78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-03T14:12:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-05T02:27:30.000Z", "max_issues_repo_path": "src/scattered.jl", "max_issues_repo_name": "markmbaum/BasicInterpolators.jl", "max_issues_repo_head_hexsha": "6986d0418913b39207ccc7825a7f00822e434ef4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-16T15:16:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T15:05:48.000Z", "max_forks_repo_path": "src/scattered.jl", "max_forks_repo_name": "wordsworthgroup/BasicInterpolators.jl", "max_forks_repo_head_hexsha": "1a43e6e657377ee9de53c721cf58141363036e78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5120481928, "max_line_length": 512, "alphanum_fraction": 0.5756514123, "num_tokens": 1364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701655, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7654827237697232}}
{"text": "using LinearAlgebra\nusing FinEtools\nusing PGFPlotsX\n\nobjects = []\n\nE = 200*phun(\"GPa\");\nnu = 0.3;\nG = E/2/(1+nu)\na = 1.0*phun(\"m\");\nt = a/5\nD = E*t^3/12/(1-nu^2)\nP = 1.0\na = 1.0\nr = collect(t/100000:t/10000:t)\nw_b = @. P/16/pi/D * (2*r^2 * log(r/a) + (3+nu)/(1+nu)*(a^2 - r^2))\nw_s = @. -P/4/pi/G/t * log(r/a) \nmax_w_b = maximum(w_b)\n\n@pgf p = PGFPlotsX.Plot(\n{\ncolor = \"black\",\nline_width  = 0.7, \nstyle = \"solid\"\n},\nCoordinates([v for v in  zip(r./t, w_b./max_w_b)])\n)\npush!(objects, p)\npush!(objects, LegendEntry(\"Bending only\"))\n\n\n@pgf p = PGFPlotsX.Plot(\n{\ncolor = \"red\",\nline_width  = 0.7, \nstyle = \"solid\"\n},\nCoordinates([v for v in  zip(r./t, (w_b+w_s)./max_w_b)])\n)\npush!(objects, p)\npush!(objects, LegendEntry(\"Bending plus shear\"))\n\n\n\n@pgf ax = Axis(\n    {\n        xlabel = \"Normalized Distance [ND]\",\n        ylabel = \"Normalized Displacement [ND]\",\n        # xmin = range[1],\n        # xmax = range[2],\n        xmode = \"linear\", \n        ymode = \"linear\",\n        yminorgrids = \"true\",\n        grid = \"both\",\n        legend_style = {\n            at = Coordinate(0.5, 1.05),\n            anchor = \"south\",\n            legend_columns = -1\n        },\n    },\n    objects...\n)\n\ndisplay(ax)\npgfsave(\"deflections.pdf\", ax)\n", "meta": {"hexsha": "37c1f64da4a4675ffd372827aa164e38d6163e04", "size": 1228, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/shear_defl.jl", "max_stars_repo_name": "PetrKryslUCSD/TestT3FF.jl", "max_stars_repo_head_hexsha": "819519b164de714bb6b649ca82b92658bca79f02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T17:58:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T17:58:23.000Z", "max_issues_repo_path": "test/shear_defl.jl", "max_issues_repo_name": "PetrKryslUCSD/TestT3FF.jl", "max_issues_repo_head_hexsha": "819519b164de714bb6b649ca82b92658bca79f02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/shear_defl.jl", "max_forks_repo_name": "PetrKryslUCSD/TestT3FF.jl", "max_forks_repo_head_hexsha": "819519b164de714bb6b649ca82b92658bca79f02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6060606061, "max_line_length": 67, "alphanum_fraction": 0.5415309446, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7654827216888715}}
{"text": "function max_divisor(number::Integer) ::Integer\n    return Integer(floor(sqrt(number)))\nend\n\nfunction is_prime(number::Integer) ::Bool\n    max::Integer = max_divisor(number)\n    # False if any number evenly divides it.\n    for x=2:max\n        if number % x == 0\n            return false\n        end\n    end\n    # true otherwise.\n    return true\nend\n\nfunction next_prime(number::Integer) ::Integer\n    to_check = number\n    while true\n        to_check += 1\n        if is_prime(to_check)\n            return to_check\n        end\n    end\nend\n   \nfunction first_n_primes(number::Integer) ::Vector{<:Integer}\n    last::Integer = 0\n    primes = Vector{Integer}()\n    for n=1:number\n        last = next_prime(last)\n        push!(primes, last)\n    end\n    return primes\nend\n\nfunction first_n_twin_primes(number::Integer) ::Vector{<:Integer}\n    last::Integer = 0\n    primes = Vector{Integer}()\n    for n=3:number\n        while true\n            last = next_prime(last)\n            if is_prime(last + 2)\n                push!(primes, last)\n                push!(primes, last+2)\n                last += 2\n                break\n            end\n        end\n    end\n    return primes\nend\n\nsum(x^2 for x in first_n_twin_primes(10000))", "meta": {"hexsha": "f55e6a74a0872fb4c2a2bc5e39600788c58d16ae", "size": 1218, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "itsnotwhathappenstoyoubuthowyoureacttoitthatmatters/first_n_primes.jl", "max_stars_repo_name": "CrosleyZack/crosleyzack.github.io", "max_stars_repo_head_hexsha": "8386c9eda6dfec33b9a074965fa368fcd76b54b1", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "itsnotwhathappenstoyoubuthowyoureacttoitthatmatters/first_n_primes.jl", "max_issues_repo_name": "CrosleyZack/crosleyzack.github.io", "max_issues_repo_head_hexsha": "8386c9eda6dfec33b9a074965fa368fcd76b54b1", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "itsnotwhathappenstoyoubuthowyoureacttoitthatmatters/first_n_primes.jl", "max_forks_repo_name": "CrosleyZack/crosleyzack.github.io", "max_forks_repo_head_hexsha": "8386c9eda6dfec33b9a074965fa368fcd76b54b1", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5555555556, "max_line_length": 65, "alphanum_fraction": 0.5812807882, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452771, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.7654466323092082}}
{"text": "#\n# NBody calculations\n#\n\n\"\"\"\nReturns total energy for `NBodySystem`.\n\"\"\"\nfunction system_energy(sys::NBodySystem)\n\n    E = 0.0u\"J\"\n    for i = 1:length(sys.body)\n\n        E += sys.body[i].m * dot(sys.body[i].v̅, sys.body[i].v̅)\n        for j = 1:length(sys.body)\n\n            if i ≠ j\n                E -= 6.6743e-11u\"m^3/(kg*s^2)\" * (sys.body[i].m * sys.body[j].m) / \n                                  norm(sys.body[j].r̅ .- sys.body[i].r̅)\n\n            end\n        end\n    end\n\n    return E\n\nend\n\n\"\"\"\nReturns total angular momentum for `NBodySystem`.\n\"\"\"\nfunction system_angular_momentum(sys::NBodySystem)\n\n    H = reduce(+, [sys.body[i].m * cross(sys.body[i].r̅, sys.body[i].v̅) for i ∈ 1:length(sys.body)])\n\nend", "meta": {"hexsha": "d853b64dae18910c7de232112424deec3993ff49", "size": 716, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "deprecated/GeneralAstrodynamics_v0.8/NBody/NBodyCalculations.jl", "max_stars_repo_name": "pbouffard/GeneralAstrodynamics.jl", "max_stars_repo_head_hexsha": "80f175a5b3c6dac2140e645b016d39f131ecea05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deprecated/GeneralAstrodynamics_v0.8/NBody/NBodyCalculations.jl", "max_issues_repo_name": "pbouffard/GeneralAstrodynamics.jl", "max_issues_repo_head_hexsha": "80f175a5b3c6dac2140e645b016d39f131ecea05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deprecated/GeneralAstrodynamics_v0.8/NBody/NBodyCalculations.jl", "max_forks_repo_name": "pbouffard/GeneralAstrodynamics.jl", "max_forks_repo_head_hexsha": "80f175a5b3c6dac2140e645b016d39f131ecea05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4571428571, "max_line_length": 101, "alphanum_fraction": 0.532122905, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813488829418, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.765446624750105}}
{"text": "#=\nWe shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.\n\nWhat is the largest n-digit pandigital prime that exists?\n=#\ninclude(\"projecteulerutils.jl\")\nusing Combinatorics\nusing Primes\n\nfunction calc()\n  largestpandigitalprime = 1\n  for n in 2:9\n    digit_arr = [i for i in 1:n]\n    for permutation in permutations(digit_arr)\n      x = nd(permutation)\n      if isprime(x) && x > largestpandigitalprime\n        largestpandigitalprime = x\n      end\n    end\n  end\n  largestpandigitalprime\nend\n@time println(calc())\n", "meta": {"hexsha": "4422116b05c25de546f60d383e0b45bff35846f0", "size": 623, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p41.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p41.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p41.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 25.9583333333, "max_line_length": 165, "alphanum_fraction": 0.7174959872, "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7654398978033845}}
{"text": "# # Ice Flow over a Bumpy Bed \n\n# This is the first two dimensional example: flow down a plane with bumps on different length scales.\n# This example is similar in spirit to Experiment A in the Ice Sheet Model Intercomparison Exercise - Higher Order Model (ISMIP-HOM): doi: 10.5194/tc-2-95-2008\n# This example demonstrates: How to use WAVI.jl in plan view (two horizontal spatial dimensions) with arbitrary bed shapes, and how to interact with Grid objects.\n\n# ## Install dependencies\n#\n# First let's make sure we have all required packages installed.\n\n# using Pkg\n# Pkg.add(\"https://github.com/RJArthern/WAVI.jl\"), Pkg.add(Plots)\nusing WAVI, Plots\n\n# ## Basal Topography\n#\n# Following ISMIP-HOM, let's take a bed with a series of sinusoidal oscillations with an amplitude of 500m:\n# $$\n# z_b(x,y) = -x \\tan \\alpha + 500 \\sin (\\omega x) \\sin(\\omega y)\n# $$\n# Here $L$ is the lengthscale of the domain, $\\alpha$ is the net slope of the plane, and $\\omega = 2\\pi / L$ is the frequency of the bumps. \n# Let's define this bed as a function and take a look at it:\n\nz_b(x,y; α, ω) = -x * tand(α) + 500sin(ω*x)*sin(ω*y);\n\n# It's useful to define our model grid here. We can do this for an arbitary domain length L.\ngrid(; L, nx = 80,ny = 80) = Grid(nx = nx, ny = ny, dx = L/nx, dy = L/ny, y0 = 0.0, x0 = 0.0);\n\n# The final two arguments simply set the origin of the co-ordinate system. This grid has 80 grid points in each direction by default\n\n# Let's choose a domain of 80km with 80 grid points\nL = 80000.;\ngrid80 = grid(L = L);\n\n# This grid object contains information about the location of grid points. We use this to construct and array defining the bed:\nz_b80 = z_b.(grid80.xxh,grid80.yyh; α = 0.5, ω = 2π/L );\nplt = Plots.heatmap(grid80.xxh[:,1]/1e3, grid80.yyh[1,:]/1e3, z_b80, \n                        xlabel = \"x (km)\", \n                        ylabel = \"y (km)\",\n                        colorbar_title = \"bed depth (m)\")\nplot!(size = (800,400))\n#display(plt)\n\n\n# ## Model Instantiation and Initial Conditions\n# In the ISMIP-HOM comparison, the main test is velocity along the line $y = L/4$, for various different values of $L$.\n# Before we do that, lets look at the velocity for the example we started above with $L = 80$km. \n\n# To begin, we create an `InitialConditions` object to prescribe the ice thickness of 1000m everywhere\ninitial_conditions = InitialConditions(initial_thickness = 1000. .* ones(grid80.nx, grid80.ny));\n\n# Now we can build our model\nmodel80 = Model(grid = grid80, \n            bed_elevation = z_b80,\n            initial_conditions = initial_conditions);\n    \n# ## Determining the velocity \n# To bring the velocity in line with the ice thickness, we have to use the `update_state!` function\nupdate_state!(model80);\n\n# Let's have a look at the velocity component in the x-direction\nPlots.heatmap(model80.grid.xxh[:,1]/1e3, model80.grid.yyh[1,:]/1e3, model80.fields.gh.u', \n                        xlabel = \"x (km)\", \n                        ylabel = \"y (km)\",\n                        colorbar_title = \"ice velocity in x-direction (m/yr)\")\nplot!(size = (1000,550))\n\n# ## Different Lengthscales\n# Now let's look at how the velocity along a flowline changes with L.\nL_values =  [160, 80, 40, 20, 10, 5]*1.0e3;\n\n# We loop over these values and store the info: \nU_flowline = zeros(80, length(L_values));\ngrid_flowline = zeros(80, length(L_values));\nfor (count,L) in enumerate(L_values) ;\n    gridL = grid(L = L);\n    z_bL = z_b.(gridL.xxh,gridL.yyh; α = 0.5, ω = 2π/L );\n    initial_conditions = InitialConditions(initial_thickness = 1000. .* ones(80, 80));\n    model = Model(grid = gridL, \n                bed_elevation = z_bL,\n                initial_conditions = initial_conditions);\n    update_state!(model);\n    grid_flowline[:, count] .= model.grid.xxh[:, round(Int, gridL.nx/4)];\n    U_flowline[:,count] .= model.fields.gh.u[:, round(Int, gridL.nx/4)];\nend\n\n#And make the plot in a single command\nplot(grid_flowline/1e3,\n    U_flowline, \n    layout = (2,3), \n    framestyle = :box, \n    xlabel = \"x (km)\", \n    ylabel = \"horizontal velocity (m/yr)\",\n    label = :none,\n    title =  [\"160km\" \"80km\" \"40km\" \"20km\" \"10km\" \"5km\"])\nplot!(size = (1000,550))", "meta": {"hexsha": "5636d086d4a35cf9c2bb6f4464a5c2c64963f8e8", "size": 4179, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/bumpy_bed.jl", "max_stars_repo_name": "JimCircadian/WAVI.jl", "max_stars_repo_head_hexsha": "16ea6bf6631ca35769dff87f944fb1827dab808b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2022-02-25T12:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T18:31:01.000Z", "max_issues_repo_path": "examples/bumpy_bed.jl", "max_issues_repo_name": "JimCircadian/WAVI.jl", "max_issues_repo_head_hexsha": "16ea6bf6631ca35769dff87f944fb1827dab808b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-02-03T16:13:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T09:26:21.000Z", "max_forks_repo_path": "examples/bumpy_bed.jl", "max_forks_repo_name": "JimCircadian/WAVI.jl", "max_forks_repo_head_hexsha": "16ea6bf6631ca35769dff87f944fb1827dab808b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-05T14:37:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T14:37:59.000Z", "avg_line_length": 43.53125, "max_line_length": 162, "alphanum_fraction": 0.6602057909, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7654398969999383}}
{"text": "export\n    istriangular,\n    nthtriangular, ntriangular,\n    alltriangular, sometriangular, exacttriangular,\n    primitive_pythagorean_triples\n\nistriangular(n::Integer) = isperfectsquare(8*n + 1)\n\nnthtriangular(n::Integer) = (n * (n+1)) ÷ 2\nntriangular(n::Int, T::Type = Int) = collect(exacttriangular(n, T))\n\nalltriangular(T::Type = Int) = TriangularIterator{T}()\nsometriangular(xmax::T) where {T<:Integer} = @pipe alltriangular(T) |> takewhile(x -> x <= xmax, _)\nexacttriangular(n::Int, T::Type = Int) = @pipe alltriangular(T) |> take(_, n)\n\nstruct TriangularIterator{T<:Integer}\nend\n\nBase.start(::TriangularIterator{T}) where {T<:Integer} = zero(T), one(T)\nBase.next(::TriangularIterator{T}, state) where {T<:Integer} = begin\n    s, n = state\n    s += n\n    s, (s, n + 1)\nend\nBase.done(::TriangularIterator, _) = false\n\nBase.eltype(it::TriangularIterator) = Base.eltype(typeof(it))\nBase.eltype(::Type{TriangularIterator{T}}) where {T<:Integer} = T\n\nBase.iteratorsize(::TriangularIterator) = Base.IsInfinite()\n\n\n\nprimitive_pythagorean_triples(T::Type = Int) = PrimitivePythagoreanTripleIterator{T}()\nprimitive_pythagorean_triples(maxperimeter::T) where {T} = PrimitivePythagoreanTriplePerimeterIterator{T}(maxperimeter)\n\n\nabstract type PrimitivePythagoreanTripleIteratorBase{T<:Integer} end\n\nstruct PrimitivePythagoreanTripleIterator{T<:Integer} <: PrimitivePythagoreanTripleIteratorBase{T}\nend\n\nstruct PrimitivePythagoreanTriplePerimeterIterator{T<:Integer} <: PrimitivePythagoreanTripleIteratorBase{T}\n    maximum::T\nend\n\n\nBase.start(::PrimitivePythagoreanTripleIterator{T}) where {T} = begin\n    q = List{Array{T,1}}()\n    n = push!(q, [3,4,5])\n    q, n\nend\nBase.start(it::PrimitivePythagoreanTriplePerimeterIterator{T}) where {T} = begin\n    q = List{Array{T,1}}()\n    n = it.maximum >= 12 ? push!(q, [3,4,5]) : q.node\n    q, n\nend\n\nBase.next(::PrimitivePythagoreanTripleIterator, state) = begin\n    q, n = state\n    n.data, (q, next!(q, n))\nend\nBase.next(it::PrimitivePythagoreanTriplePerimeterIterator, state) = begin\n    q, n = state\n    n.data, (q, next!(q, n, it.maximum))\nend\n\nBase.done(::PrimitivePythagoreanTripleIteratorBase, state) = begin\n    q, n = state\n    iseol(q, n)\nend\n\nBase.eltype(it::PrimitivePythagoreanTripleIteratorBase) = Base.eltype(typeof(it))\nBase.eltype(::Type{PrimitivePythagoreanTripleIterator{T}}) where {T} = Array{T,1}\nBase.eltype(::Type{PrimitivePythagoreanTriplePerimeterIterator{T}}) where {T} = Array{T,1}\n\nBase.iteratorsize(::PrimitivePythagoreanTripleIterator) = Base.IsInfinite()\nBase.iteratorsize(::PrimitivePythagoreanTriplePerimeterIterator) = Base.SizeUnknown()\n\n\niseol(q::List{T}, n::ListNode{T}) where {T} = n == q.node\n\nnext!(q::List{T}, n::ListNode{T}) where {T} = begin\n    n = n.next\n    iseol(q, n) || return n\n\n    x, y, z = calculate(shift!(q)...)\n    n = push!(q, x)\n    push!(q, y)\n    push!(q, z)\n    n\nend\n\nnext!(q::List{T}, n::ListNode{T}, maxsum) where {T} = begin\n    n = n.next\n    iseol(q, n) || return n\n\n    while iseol(q, n) && !isempty(q)\n        x, y, z = calculate(shift!(q)...)\n        sum(x) <= maxsum && (nx = push!(q, x); n = nx)\n        sum(y) <= maxsum && (ny = push!(q, y); n = iseol(q, n) ? ny : n)\n        sum(z) <= maxsum && (nz = push!(q, z); n = iseol(q, n) ? nz : n)\n    end\n    n\nend\n\ncalculate(a, b, c) = begin\n    x = [ a - 2b + 2c,  2a - b + 2c,  2a - 2b + 3c] # const U = [ 1  2  2, -2 -1 -2, 2 2 3], [a b c] * U\n    y = [ a + 2b + 2c,  2a + b + 2c,  2a + 2b + 3c] # const A = [ 1  2  2,  2  1  2, 2 2 3], [a b c] * A\n    z = [-a + 2b + 2c, -2a + b + 2c, -2a + 2b + 3c] # const D = [-1 -2 -2,  2  1  2, 2 2 3], [a b c] * D\n    x, y, z\nend\n", "meta": {"hexsha": "24a2f1566ad87586b6f887e04adfe4a2633457b8", "size": 3631, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Math/NumberTheory/triangle.jl", "max_stars_repo_name": "Samayel/Brainstorm.jl", "max_stars_repo_head_hexsha": "9d83bb0a104973e498ba4ca84b0a27ede6c053ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-12-22T17:56:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T21:13:36.000Z", "max_issues_repo_path": "src/Math/NumberTheory/triangle.jl", "max_issues_repo_name": "Samayel/Brainstorm.jl", "max_issues_repo_head_hexsha": "9d83bb0a104973e498ba4ca84b0a27ede6c053ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/NumberTheory/triangle.jl", "max_forks_repo_name": "Samayel/Brainstorm.jl", "max_forks_repo_head_hexsha": "9d83bb0a104973e498ba4ca84b0a27ede6c053ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1327433628, "max_line_length": 119, "alphanum_fraction": 0.6461030019, "num_tokens": 1268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630935, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7654398956689596}}
{"text": "#The \"1/e^2 beamwidth\" seems to have inconsistent definitions,\n#either meaning the half-width or the full width of the beam\n#Here \"beamwidth\" will refer to the full width, and \"sigma\" will\n#refer to the halfwidth\n#Sigma is the width of a gaussian defined as y = e^-(2x^2/sigma^2)\n#(this parameterization of the Gaussian is common for optics but not universal. The other\n#common convention has a 2 in the denominator of the exponent rather thatn the numerator.\n#This is the convention in statistics and thus is how variance and std are defined.  So if we want\n#an r.m.s. value we should use this latter convention)\n#By the former convention \"sigma\" is the distance from the origin at which the gaussian\n#decays to 1/e^2 of its maximum value, i.e. the halfwidth.\n#sigma_statistics = std = sigma_optics/2\n#sigma_optics = 2*std\n\n\n#gaussian approximation to airy disk\n#taken from paraxial approximations derived in:\n#Gaussian approximations of fluorescence microscope point-spread function models\n#Bo Zhang, Josiane Zerubia, and Jean-Christophe Olivo-Marin\n#1 April 2007 Vol. 46, No. 10 APPLIED OPTICS\n#Note that the authors derive the below expression for \"sigma\"\n#but their definition of sigma differs from ours; they use the statistical convention\n#(see comments at top of this file) instead of 1/e^2 convention\n#their r.h.s. is    e^-(x^2/2*sigma^2)\n#...while ours is   e^-(2x^2/sigma^2)\n#thus our axial sigma is twice theirs\napprox_sigma_axial(lambda, NA, n) = 4*sqrt(6)*n/(2*pi/lambda*NA^2)\napprox_sigma_axial(lambda, f, unfocused_sigma, n) = approx_sigma_axial(lambda, lens_na(unfocused_sigma, f), n)\n\napprox_sigma_lateral(lambda, NA) = sqrt(2)*lambda / (pi*NA)\napprox_sigma_lateral(lambda, f, unfocused_sigma) = approx_sigma_lateral(lambda, lens_na(unfocused_sigma, f))\nfocused_beamwidth(lambda, f, unfocused_beamwidth) = 2*approx_sigma_lateral(lambda, f, unfocused_beamwidth/2)\n\n#assuming a lens has a big enough aperture to accept\n#a collimated input of specified halfwidth and also\n#that the medium is the same before and after focusing\n#what is the NA of the system?\nlens_na(unfocused_sigma, f) = unfocused_sigma/f\n\n#Halfwidth of the Gaussian approximation of the axial PSF of a light sheet imaging system,\n#considering both the PSF of the imaging lens and the sheet thickness\nlightsheet_axial_combined_psf(det_sigma, sheet_sigma) =\n    sqrt((det_sigma^2*sheet_sigma^2)/(det_sigma^2 + sheet_sigma^2))\n\nrayleigh_length(lambda, focused_sigma) = pi*focused_sigma^2 / lambda\nrayleigh_length(lambda, f, unfocused_sigma, n) =\n    rayleigh_length(lambda, approx_sigma_lateral(lambda, f, unfocused_sigma, n))\n\n#sigma of a focused beam as a function of displacement from the beam waist\ndisplaced_sigma(lambda, focused_sigma, displacement) = sqrt(focused_sigma^2*(1+(lambda*displacement/(pi*focused_sigma^2))^2))\n\n#This doesn't match the calculation on the OpenSPIM website.  Seems theirs is incorrect.\nfwhm_stats(std) = 2*sqrt(2*log(2)) * std\nfwhm_optics(sigma) = fwhm_stats(sigma/2)\n\n#Currently aren't using these\nabbe_lat(lambda, NA) = lambda/(2*NA)\nabbe_ax(lambda, NA) = 2*lambda/(NA^2)\n", "meta": {"hexsha": "89802d39e64742d10d72eae08f8c4734ded9484d", "size": 3088, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/optics.jl", "max_stars_repo_name": "HolyLab/ExtractPSF", "max_stars_repo_head_hexsha": "b562a720ebcad4a62d76ff97c6e79e4a2833bced", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-01T19:16:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-01T19:16:17.000Z", "max_issues_repo_path": "src/optics.jl", "max_issues_repo_name": "HolyLab/ExtractPSF.jl", "max_issues_repo_head_hexsha": "b562a720ebcad4a62d76ff97c6e79e4a2833bced", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-09-04T18:14:38.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T19:15:05.000Z", "max_forks_repo_path": "src/optics.jl", "max_forks_repo_name": "HolyLab/ExtractPSF", "max_forks_repo_head_hexsha": "b562a720ebcad4a62d76ff97c6e79e4a2833bced", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.3389830508, "max_line_length": 125, "alphanum_fraction": 0.7755829016, "num_tokens": 851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541528387691, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7654398855486626}}
{"text": "using MPFR_wrap\n\nconst atol = BigFloat(\"1e-100000\")\nconst prec = 333_000\nconst π_MPFR = BigFloat(π, prec)\n\n\nfunction brent_salamin()\n    old_prec = precision(BigFloat)\n    setprecision(BigFloat, prec)\n    a_prev, b_prev = big(1.0), 1 / sqrt(big(2.0))\n    s_prev, π_prev = big(1.0) / 2, big(4.0)\n    π_next = BigFloat()\n    k, p2 = 1, big(2)\n    while true\n        a_next = (a_prev + b_prev) / 2\n        b_next = sqrt(a_prev * b_prev)\n        c_next = (a_next - b_next) * (a_next + b_next)\n        s_next = s_prev - p2 * c_next\n        π_next = 2a_next^2 / s_next\n        #println(\"$k -> $pn\")\n        δπ = π_next - π_prev\n        abs(δπ) ≤ atol && break\n        a_prev, b_prev, s_prev, π_prev = a_next, b_next, s_next, π_next\n        k += 1\n        p2 *= 2\n    end\n    setprecision(BigFloat, old_prec)\n    @assert isapprox(π_next, π_MPFR, atol=atol)\n    (k, π_next)\nend\n\n\nfunction inplace_brent_salamin()\n    a_prev = BigFloat(1, precision=prec)\n    b_prev = BigFloat(2, precision=prec)\n    rec_sqrt!(b_prev, b_prev)\n    s_prev = BigFloat(0.5, precision=prec)\n    π_prev = BigFloat(4, precision=prec)\n    a_next = BigFloat(precision=prec)\n    b_next = BigFloat(precision=prec)\n    c_next = BigFloat(precision=prec)\n    s_next = BigFloat(precision=prec)\n    π_next = BigFloat(precision=prec)\n    δπ = BigFloat(precision=prec)\n    k = Int32(1)\n    while true\n        add!(a_next, a_prev, b_prev)\n        div_2!(a_next, a_next, Int32(1))\n\n        mul!(b_next, a_prev, b_prev)\n        sqrt!(b_next, b_next)\n\n        sub!(c_next, a_prev, a_next)\n        sqr!(c_next, c_next)\n\n        mul_2!(c_next, c_next, k)\n        sub!(s_next, s_prev, c_next)\n\n        sqr!(π_next, a_next)\n        mul_2!(π_next, π_next, Int32(1))\n        div!(π_next, π_next, s_next)\n\n        sub!(δπ, π_next, π_prev)\n        abs(δπ) ≤ atol && break\n\n        a_prev, a_next = a_next, a_prev\n        b_prev, b_next = b_next, b_prev\n        s_prev, s_next = s_next, s_prev\n        π_prev, π_next = π_next, π_prev\n\n        k += Int32(1)\n    end\n    @assert isapprox(π_next, π_MPFR, atol=atol)\n    (k, π_next)\nend\n\n\nfunction inplace_borwein_cubic()\n    a_prev = BigFloat(1, precision=prec)\n    div!(a_prev, a_prev, Int32(3))\n    s_prev = BigFloat(3, precision=prec)\n    sqrt!(s_prev, s_prev)\n    sub!(s_prev, s_prev, Int32(1))\n    div_2!(s_prev, s_prev, Int32(1))\n    r_next = BigFloat(precision=prec)\n    s_next = BigFloat(precision=prec)\n    rsq_next = BigFloat(precision=prec)\n    a_next = BigFloat(precision=prec)\n    tmp = BigFloat(precision=prec)\n    π_prev = BigFloat(0, precision=prec)\n    π_next = BigFloat(precision=prec)\n    δπ = BigFloat(precision=prec)\n    k = Int32(0)\n    while true\n        pow!(r_next, s_prev, Int32(3))\n        sub!(r_next, Int32(1), r_next)\n        cbrt!(r_next, r_next)\n        mul_2!(r_next, r_next, Int32(1))\n        add!(r_next, r_next, Int32(1))\n        div!(r_next, Int32(3), r_next)\n\n        sub!(s_next, r_next, Int32(1))\n        div_2!(s_next, s_next, Int32(1))\n\n        sqr!(rsq_next, r_next)\n        sub!(tmp, rsq_next, Int32(1))\n        mul!(tmp, tmp, Int32(3)^k)\n        mul!(a_next, rsq_next, a_prev)\n        sub!(a_next, a_next, tmp)\n\n        div!(π_next, Int32(1), a_next)\n        sub!(δπ, π_next, π_prev)\n        abs(δπ) ≤ atol && break\n\n        a_prev, a_next = a_next, a_prev\n        s_prev, s_next = s_next, s_prev\n        π_prev, π_next = π_next, π_prev\n\n        k += Int32(1)\n    end\n    @assert isapprox(π_next, π_MPFR, atol=atol)\n    (k, π_next)\nend\n", "meta": {"hexsha": "c410711ff50ba8879d1051e3f4081a0199753252", "size": 3471, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/pi_iterative.jl", "max_stars_repo_name": "mzaffalon/MPFR_wrap.jl", "max_stars_repo_head_hexsha": "f7231fa2a93636e85961b848cfa42172d8b931ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T22:22:35.000Z", "max_issues_repo_path": "examples/pi_iterative.jl", "max_issues_repo_name": "mzaffalon/MPFR_wrap.jl", "max_issues_repo_head_hexsha": "f7231fa2a93636e85961b848cfa42172d8b931ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/pi_iterative.jl", "max_forks_repo_name": "mzaffalon/MPFR_wrap.jl", "max_forks_repo_head_hexsha": "f7231fa2a93636e85961b848cfa42172d8b931ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.768, "max_line_length": 71, "alphanum_fraction": 0.596946125, "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761565, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7654398804763671}}
{"text": "include(\"./Legendre_polynomials.jl\")\n\nfunction Spherical_harmonics_a!(x::Float64, lmax::Int64;\n                                Yₗ = nothing, Pₗ = nothing) \n    #### Returns an array of size lmax_half. Each cell contains one (even axisymmetric) spherical harmonic at point cos(θ) = x ####\n    #### The \"a\" in the name is here to outline that this function only gives the \"a\"xisymmetric harmonics (i.e. m = 0).         ####\n    # getting the constants we will need\n    lmax_half = div(lmax, 2)\n\n    # let's preallocate the arrays that haven't been given\n    if isnothing(Yₗ)\n        Yₗ = zeros(lmax_half) # WIll hold the spherical harmonics\n    end\n    if isnothing(Pₗ)\n        Pₗ = zeros(lmax_half) # WIll hold the Legendre polynomials\n    end\n\n    # let's comptute the (even) Legendre polynomials at point x\n    Legendre_polynomials!(x, lmax, Pₗ = Pₗ)\n\n    # let's compute the spherical harmonics\n    for l_half = 1:lmax_half\n        l = 2 * l_half\n        Yₗ[l_half] = Pₗ[l_half] * sqrt((2 * l + 1) / (4 * π)) # Yₗ₀ = Pₗ₀ * sqrt((2 l + 1) / 4 π)\n    end\n\n    return(Yₗ)\nend\n\nfunction Spherical_harmonics!(θ::Float64, ϕ::Float64, lmax::Int64; \n                                Yₗₘ = nothing, Pₗₘ = nothing) \n    #### Returns an array of size lmax_half * (2 lmax + 1). Each cell contains one (even) spherical harmonic at point (θ, ϕ) ####\n    #### This function has no \"a\" in its title because it returns ALL the spherical harmonics (i.e. m = 0 and m != 0)        ####\n    # getting the constants we will need\n    lmax_half = div(lmax, 2)\n\n    # let's preallocate the arrays that haven't been given\n    if isnothing(Yₗₘ)\n        Yₗₘ = zeros(2 * lmax + 1, lmax_half) # Will hold the spherical harmonics\n    end\n    if isnothing(Pₗₘ)\n        Pₗₘ = zeros(lmax + 1, lmax_half) # Will hold the normalized associated Legendre polynomials\n    end\n\n    # Let's compute the normalzed associated Legendre polynomials\n    Normalized_associated_Legendre_polynomials!(cos(θ), lmax, P = Pₗₘ)\n\n    # Let's compute the spherical harmonics\n    for l_half = 1:lmax_half\n        l = 2 * l_half\n\n        for m = 0:l\n            # The passage from Pₗₘ to Yₗₘ is not the same if m is positive, null or negative. \n            # Cf Wikipedia : https://en.wikipedia.org/wiki/Spherical_harmonics#Real_form\n            if (m != 0)\n                Yₗₘ[lmax + 1 - m, l_half] = (-1)^(m) * sqrt(2) * Pₗₘ[m + 1, l_half] * sin(m * ϕ)\n                Yₗₘ[lmax + 1 + m, l_half] = (-1)^(m) * sqrt(2) * Pₗₘ[m + 1, l_half] * cos(m * ϕ)\n            else\n                Yₗₘ[lmax + 1, l_half] = Pₗₘ[1, l_half]\n            end\n        end\n    end\n\n    return(Yₗₘ)\nend", "meta": {"hexsha": "f92b2d01e19790b086b89b7c430d94f56a7f542e", "size": 2624, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Code/Spherical_harmonics.jl", "max_stars_repo_name": "NathanMagnan/VRROOMe", "max_stars_repo_head_hexsha": "9047b050687598c99d818b1498c8deae835be756", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/Spherical_harmonics.jl", "max_issues_repo_name": "NathanMagnan/VRROOMe", "max_issues_repo_head_hexsha": "9047b050687598c99d818b1498c8deae835be756", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Spherical_harmonics.jl", "max_forks_repo_name": "NathanMagnan/VRROOMe", "max_forks_repo_head_hexsha": "9047b050687598c99d818b1498c8deae835be756", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3692307692, "max_line_length": 133, "alphanum_fraction": 0.5983231707, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.765437715810546}}
{"text": "# Common functions compatible for use with physical vectors\n\nfunction dot_product(A::AbstractArray{T1,N},B::AbstractArray{T2,N}) where {T1<:Number,T2<:Number,N}\n    \n    size(A) === size(B) || throw(ArgumentError(\"Vectors must have the same shape\"))\n    u = zeros(promote_type(T1,T2),size(A)[1:end-1]...)\n    dot_product!(u,A,B)\n    return u\nend\n\nfunction dot_product!(u::AbstractArray{T1,N}, A::AbstractArray{T2,N2},B::AbstractArray{T3,N2}) where {T1<:Number,T2<:Number,T3<:Number,N,N2}\n    \n    (size(A) === size(B)) || throw(ArgumentError(\"Vectors must have the same shape\"))\n    (N === N2-1) || throw(ArgumentError(\"Output should be scalar matrix, one dimension less than input\"))\n    \n    T = promote_type(T1,T2,T3)\n    @turbo for I in CartesianIndices(u)\n        x_temp = zero(T)\n        for i in 1:N\n            x_temp += A[I,i]*B[I,i]\n        end\n        u[I] = x_temp\n    end\n    return u\nend\n\nfunction cross_product(A::AbstractArray{T1,4},B::AbstractArray{T2,4}) where {T1<:Number,T2<:Number}\n    \n    size(A) === size(B) || throw(ArgumentError(\"Vectors must have the same shape\"))\n    s = size(A)\n    u = zeros(promote_type(T1,T2),s...)\n    cross_product!(u,A,B)\n    return u\nend\n\nfunction cross_product!(u::AbstractArray{T1,4},A::AbstractArray{T2,4},B::AbstractArray{T3,4}) where {T1<:Number,T2<:Number,T3<:Number}\n    \n    (size(A) === size(B) && size(A) === size(u))|| throw(ArgumentError(\"Vectors must have the same shape\"))\n    s = size(u)\n\n    @turbo for r in 1:s[3], q in 1:s[2], p in 1:s[1]\n        u[p,q,r,1] = A[p,q,r,2]*B[p,q,r,3] - A[p,q,r,3]*B[p,q,r,2]\n        u[p,q,r,2] = A[p,q,r,3]*B[p,q,r,1] - A[p,q,r,1]*B[p,q,r,3]\n        u[p,q,r,3] = A[p,q,r,1]*B[p,q,r,2] - A[p,q,r,2]*B[p,q,r,1]\n    end\nend\n\nfunction square_norm(A::AbstractArray{T,N}) where {T<:Number,N}\n    u = zeros(T,size(A)[1:end-1]...)\n    square_norm!(u,A)\n    return u\nend\n\nfunction square_norm!(u::AbstractArray{T1,N1},A::AbstractArray{T2,N2}) where {T1<:Number,T2<:Number,N1,N2}\n    dot_product!(u,A,A)\n    @. u = u^0.5\nend", "meta": {"hexsha": "a669d19204f917067bf95a5bf551cd83f8a07f33", "size": 2016, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/derivative_operators/vector_algebraic_operations.jl", "max_stars_repo_name": "QiyaoWei/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "4b1882556fb5c2bcb2994543452e765761d33de7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 194, "max_stars_repo_stars_event_min_datetime": "2020-04-03T15:12:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T03:25:55.000Z", "max_issues_repo_path": "src/derivative_operators/vector_algebraic_operations.jl", "max_issues_repo_name": "QiyaoWei/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "4b1882556fb5c2bcb2994543452e765761d33de7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 181, "max_issues_repo_issues_event_min_datetime": "2020-04-01T17:55:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T11:16:19.000Z", "max_forks_repo_path": "src/derivative_operators/vector_algebraic_operations.jl", "max_forks_repo_name": "QiyaoWei/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "4b1882556fb5c2bcb2994543452e765761d33de7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 48, "max_forks_repo_forks_event_min_datetime": "2020-04-10T04:44:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:56:09.000Z", "avg_line_length": 35.3684210526, "max_line_length": 140, "alphanum_fraction": 0.6071428571, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7654377092780431}}
{"text": "# ## GPU Computing\n\n# https://github.com/JuliaGPU\n\nusing Plots, BenchmarkTools, FFTW, LinearAlgebra\n\n# ### Advection equation for a rotation in two dimensional domain\n#md #\n#md # ```math\n#md #  \\\\frac{d f}{dt} +  (y \\\\frac{d f}{dx} - x \\\\frac{d f}{dy}) = 0\n#md # ```\n#md #\n#md # ``x \\in [-π, π], y \\in [-π, π] `` and  `` t \\in [0, 200π] ``\n\n#md # ---\n\nstruct Mesh\n    \n    nx   :: Int64\n    ny   :: Int64\n    x    :: Vector{Float64}\n    y    :: Vector{Float64}\n    kx   :: Vector{Float64}\n    ky   :: Vector{Float64}\n    \n    function Mesh( xmin, xmax, nx, ymin, ymax, ny)\n        ## periodic boundary condition, we remove the end point.\n        x = range(xmin, stop=xmax, length=nx+1)[1:end-1]  \n        y = range(ymin, stop=ymax, length=ny+1)[1:end-1]  \n        kx  = 2π ./ (xmax-xmin) .* [0:nx÷2-1;nx÷2-nx:-1]\n        ky  = 2π ./ (ymax-ymin) .* [0:ny÷2-1;ny÷2-ny:-1]\n        new( nx, ny, x, y, kx, ky)\n    end\nend\n\n#md # ---\n\nfunction exact(time, mesh :: Mesh; shift=1.0)\n   \n    f = zeros(Float64,(mesh.nx, mesh.ny))\n    for (i, x) in enumerate(mesh.x), (j, y) in enumerate(mesh.y)\n        xn = cos(time)*x - sin(time)*y\n        yn = sin(time)*x + cos(time)*y\n        f[i,j] = exp(-(xn-shift)*(xn-shift)/0.1)*exp(-(yn-shift)*(yn-shift)/0.1)\n    end\n\n    f\nend\n\n#md # ---\n\nfunction animation( tf, nt)\n    \n    mesh = Mesh( -π, π, 64, -π, π, 64)\n    dt = tf / nt\n    t = 0\n    anim = @animate for n=1:nt\n       \n       f = exact(t, mesh)\n       t += dt\n       p = contour(mesh.x, mesh.y, f, axis=[], framestyle=:none)\n       plot!(p[1]; clims=(0.,1.), aspect_ratio=:equal, colorbar=false, show=false)\n       plot!(sqrt(2) .* cos.(-pi:0.1:pi+0.1), \n             sqrt(2) .* sin.(-pi:0.1:pi+0.1), label=\"\", show=false)\n       xlims!(-π,π)\n       ylims!(-π,π)\n        \n    end\n\n    anim\n    \nend\n\n#md # ---\n\nanim = animation( 2π, 100)\n#md gif(anim, \"rotation2d.gif\", fps = 20)\n#md nothing # hide\n\n#md # ![](rotation2d.gif)\n\n#md # ---\n\nfunction rotation_on_cpu( mesh :: Mesh, nt :: Int64, tf :: Float64) \n    \n    dt = tf / nt\n    \n    f   = zeros(ComplexF64,(mesh.nx,mesh.ny))\n    f  .= exact( 0.0, mesh )\n    \n    exky = exp.( 1im*tan(dt/2) .* mesh.x  .* mesh.ky')\n    ekxy = exp.(-1im*sin(dt)   .* mesh.y' .* mesh.kx )\n    \n    for n = 1:nt\n        \n        fft!(f, 2)\n        f .= exky .* f \n        ifft!(f,2)\n        \n        fft!(f, 1)  \n        f .= ekxy .* f\n        ifft!(f, 1)\n        \n        fft!(f, 2)\n        f .= exky .* f\n        ifft!(f, 2)\n        \n    end\n    \n    real(f)\n    \nend\n\n#md # ---\n\nmesh = Mesh( -π, π, 1024, -π, π, 1024)\nnt, tf = 100, 20.\nrotation_on_cpu(mesh, 1, 0.1) # trigger building\netime = @time norm( rotation_on_cpu(mesh, nt, tf) .- exact( tf, mesh))\nprintln(etime)\n\n@test true #src\n\n#md # ---\n\nusing Pkg \n\nGPU_ENABLED = haskey(Pkg.installed(), \"CUDAdrv\")\n\nif GPU_ENABLED\n\n    using CUDAdrv, CuArrays, CuArrays.CUFFT\n    \n    println(CUDAdrv.name(CuDevice(0)))\n\nend\n\n#md # ---\n    \nif GPU_ENABLED\n\n    function rotation_on_gpu( mesh :: Mesh, nt :: Int64, tf :: Float64)\n        \n        dt  = tf / nt\n        f   = zeros(ComplexF64,(mesh.nx, mesh.ny))\n        f  .= exact( 0.0, mesh)\n        \n        d_f    = CuArray(f) # allocate f on GPU\n        \n        p_x    = plan_fft!(d_f,  [1]) # Create fft plans on GPU\n        pinv_x = plan_ifft!(d_f, [1])\n        p_y    = plan_fft!(d_f,  [2])\n        pinv_y = plan_ifft!(d_f, [2])  \n        \n        d_exky = CuArray(exp.( 1im*tan(dt/2) .* mesh.x  .* mesh.ky'))\n        d_ekxy = CuArray(exp.(-1im*sin(dt)   .* mesh.y' .* mesh.kx ))\n        \n        for n = 1:nt\n            \n            p_y * d_f\n            d_f .*= d_exky \n            pinv_y * d_f\n            \n            p_x * d_f\n            d_f .*= d_ekxy \n            pinv_x * d_f\n            \n            p_y * d_f\n            d_f .*= d_exky \n            pinv_y * d_f\n            \n        end\n        \n        f .= collect(d_f) # Transfer f from GPU to CPU\n        real(f)\n        \n    end\n\nend\n\n#md # ---\n\nif GPU_ENABLED\n\n    nt, tf = 100, 20.\n    rotation_on_gpu(mesh, 1, 0.1)\n    etime = @time norm( rotation_on_gpu(mesh, nt, tf) .- exact( tf, mesh))\n    println(etime)\n    @test true #src\n\nend\n\n#md # Next: [Metaprogrammimg and Particle Group](/Numkin2019/04/build/index.html)\n", "meta": {"hexsha": "d24ccbf9201fdd6aca9a3a670b7ec34ce1e01be4", "size": 4223, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/03.RotationGPU.jl", "max_stars_repo_name": "JuliaVlasov/Numkin2019", "max_stars_repo_head_hexsha": "8720a3c7d3fe0102a5232139ca97bc4ec4b5ea00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-25T01:19:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-25T01:19:30.000Z", "max_issues_repo_path": "src/03.RotationGPU.jl", "max_issues_repo_name": "JuliaVlasov/Numkin2019", "max_issues_repo_head_hexsha": "8720a3c7d3fe0102a5232139ca97bc4ec4b5ea00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/03.RotationGPU.jl", "max_forks_repo_name": "JuliaVlasov/Numkin2019", "max_forks_repo_head_hexsha": "8720a3c7d3fe0102a5232139ca97bc4ec4b5ea00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7680412371, "max_line_length": 82, "alphanum_fraction": 0.4861472887, "num_tokens": 1487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7654377078018597}}
{"text": "\"\"\"\n\nThe chemostat steady state impose a contraint over the exchanges:\n\n``intake <= c/ξ``\n    \nwhere ``c`` is the concentration of the metabolite in the medium and ``ξ`` is the cell-specific dilution rate.\nTogether with the thermodinamic bound we have\n\nstst_bound(c, ξ, b) = sign(b) * min(c/ ξ, abs(b))\n\n\"\"\"\nstst_bound(c, ξ, b) = sign(b) * min(c/ ξ, abs(b))", "meta": {"hexsha": "da26d2b3deab2ee89d950d107f386d3d6bd797e1", "size": 357, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SteadyState/stst_bound.jl", "max_stars_repo_name": "josePereiro/Chemostat", "max_stars_repo_head_hexsha": "83961584c686ca5a6c8818380d29317a77a42c00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SteadyState/stst_bound.jl", "max_issues_repo_name": "josePereiro/Chemostat", "max_issues_repo_head_hexsha": "83961584c686ca5a6c8818380d29317a77a42c00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SteadyState/stst_bound.jl", "max_forks_repo_name": "josePereiro/Chemostat", "max_forks_repo_head_hexsha": "83961584c686ca5a6c8818380d29317a77a42c00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4615384615, "max_line_length": 110, "alphanum_fraction": 0.6694677871, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7654377054306419}}
{"text": "\"\"\"\n    function latticeCompactHexagonal(box,r)\n\nMake a lattice with compact hexagonal structure in box with spheres of radius r.\n\n# Returns\n[posX,posY,posZ] Where pos are arrays with the positions of the cells for each component.\n\"\"\"\nfunction compactHexagonal(box::Array{Array{Float64,1},1},r::Number)\n\n    d = length(box)\n    if !(d in [1,2,3])\n        error(\"Incompatible number of dimensions \", d)\n    end\n\n    #Make first dimension\n    lineX = Array(box[1][1]:2*r:box[1][2])\n\n    #Make second dimension\n    if d > 1\n        lineY = fill(box[2][1]+r,length(lineX))\n        nY = ceil(Int,(box[2][2]-box[2][1])/(4*sin(pi/3)*r))\n        areaX = Float64[]\n        areaY = Float64[]\n        dx = 2*r*cos(pi/3)\n        dy = 2*r*sin(pi/3)\n        for i in 0:nY-1\n            append!(areaX,lineX)\n            append!(areaX,lineX.+dx)\n\n            append!(areaY,lineY.+dy*2*i)\n            append!(areaY,lineY.+dy*2*i.+dy)\n        end\n    end\n\n    #Make third dimension\n    if d == 3\n        areaZ = fill(box[2][1]+r,length(areaX))\n        nZ = ceil(Int,(box[3][2]-box[3][1])/(4*sin(pi/3)*r))\n        volumeX = Float64[]\n        volumeY = Float64[]\n        volumeZ = Float64[]\n        dy = 2*r/2/cos(pi/6)\n        dz = 2*sqrt(2/3)*r\n        for i in 0:nZ-1\n            append!(volumeX,areaX)\n            append!(volumeX,areaX)\n\n            append!(volumeY,areaY)\n            append!(volumeY,areaY.+dy)\n\n            append!(volumeZ,areaZ.+dz*2*i)\n            append!(volumeZ,areaZ.+dz*2*i.+dz)\n        end    \n    end\n\n    #Return\n    if d == 1\n        return lineX\n    elseif d == 2\n        return areaX, areaY\n    else\n        return volumeX, volumeY, volumeZ\n    end\n\nend\n\n", "meta": {"hexsha": "7721b8cfb3574ad2ff7ca28416f4b4c61ee8fe33", "size": 1669, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/community/constructors/latices/hexagonal.jl", "max_stars_repo_name": "gatocor/embryogenesisJulia", "max_stars_repo_head_hexsha": "826348fcbe781f87c89a924da217f803d7ca4ebf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/community/constructors/latices/hexagonal.jl", "max_issues_repo_name": "gatocor/embryogenesisJulia", "max_issues_repo_head_hexsha": "826348fcbe781f87c89a924da217f803d7ca4ebf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/community/constructors/latices/hexagonal.jl", "max_forks_repo_name": "gatocor/embryogenesisJulia", "max_forks_repo_head_hexsha": "826348fcbe781f87c89a924da217f803d7ca4ebf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5441176471, "max_line_length": 89, "alphanum_fraction": 0.5374475734, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7654377032715285}}
{"text": "using OrdinaryDiffEq, PoissonRandom\r\n\r\nfunction rate_to_proportion(r::Float64,t::Float64)\r\n    1-exp(-r*t)\r\nend;\r\n\r\nfunction sir_abm!(du,u,p,t)\r\n    (β,c,γ,δt) = p\r\n    N = length(u)\r\n    # Initialize du to u\r\n    for i in 1:N\r\n        du[i] = u[i]\r\n    end\r\n    for i in 1:N # loop through agents\r\n        # If recovered\r\n        if u[i]==Recovered\r\n            continue\r\n        # If susceptible\r\n        elseif u[i]==Susceptible\r\n            ncontacts = pois_rand(c*δt)\r\n            while ncontacts > 0\r\n                j = rand(1:N)\r\n                if j==i\r\n                    continue\r\n                end\r\n                a = u[j]\r\n                if a==Infected && rand() < β\r\n                    du[i] = Infected\r\n                    break\r\n                end\r\n                ncontacts -= 1\r\n            end\r\n        # If infected\r\n        else u[i]==Infected\r\n            if rand() < γ\r\n                du[i] = Recovered\r\n            end\r\n        end\r\n    end\r\n    nothing\r\nend\r\n\r\nδt = 0.1\r\nnsteps = 400\r\ntf = nsteps*δt\r\ntspan = (0.0,nsteps)\r\nt = 0:δt:tf;\r\nβ = 0.05\r\nc = 10.0\r\nγ = rate_to_proportion(0.25,δt)\r\np = [β,c,γ,δt]\r\n\r\n@enum InfectionStatus Susceptible Infected Recovered\r\nBase.zero(::Type{<:InfectionStatus}) = Susceptible\r\n\r\nN = 1000\r\nI0 = 10\r\nu0 = Array{InfectionStatus}(undef,N);\r\nfor i in 1:N\r\n    if i <= I0\r\n        s = Infected\r\n    else\r\n        s = Susceptible\r\n    end\r\n    u0[i] = s\r\nend\r\n\r\nprob_map = DiscreteProblem(sir_abm!,u0,tspan,p)\r\nsol_map = solve(prob_map,FunctionMap())\r\n", "meta": {"hexsha": "a8dc6461ea5e0447765222202515f3ece81f3ea2", "size": 1515, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/interface/enums.jl", "max_stars_repo_name": "contradict/OrdinaryDiffEq.jl", "max_stars_repo_head_hexsha": "784c2e6cc1073e3664aa9e052cee0d22f1a06e8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-26T20:43:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T20:43:50.000Z", "max_issues_repo_path": "test/interface/enums.jl", "max_issues_repo_name": "contradict/OrdinaryDiffEq.jl", "max_issues_repo_head_hexsha": "784c2e6cc1073e3664aa9e052cee0d22f1a06e8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/interface/enums.jl", "max_forks_repo_name": "contradict/OrdinaryDiffEq.jl", "max_forks_repo_head_hexsha": "784c2e6cc1073e3664aa9e052cee0d22f1a06e8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6428571429, "max_line_length": 53, "alphanum_fraction": 0.4798679868, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7654243621370331}}
{"text": "# Code for Video 1.5: \r\n\r\nfunction sum(x, y, z)\r\n  return x + y + z\r\nend\r\n\r\nshow(sum(2, 3, 4)) # 9\r\nshow(sum(2.1, 3.2, 4.3)) # 9.600000000000001\r\nshow(sum(true, false, true)) # 2\r\n\r\ntypeof(sum) # Function\r\n\r\nfunction sum_prod(x, y)\r\n    x + y, x * y\r\nend\r\n\r\n# sum(\"Iris\", 7, true)\r\n# ERROR: MethodError: `+` has no method matching +(::ASCIIString, ::Int64)\r\n\r\nfunction sum(x:: Int64, y::Int64, z::Int64)\r\n    return x + y + z\r\nend\r\n\r\nfunction sump(x:: Int64, y::Int64, z::Int64)\r\n    p::Int64 = x * y * z\r\n    return x + y + z + p\r\nend\r\n\r\n sum(x, y, z) = x + y + z\r\n\r\nfunction sumvar(args...)\r\n    sum = 0\r\n    for n in args\r\n        sum += n\r\n    end\r\n    return sum\r\nend\r\n\r\nsumvar(2,3,4,100,-9) # 100\r\nsumvar(2,3,4) # 9\r\nsumvar() # 0\r\n\r\nfunction sum(n1, n2, n3=5; n4=-9)\r\n    return n1 + n2 + n3 + n4\r\nend\r\n\r\nsum(2, 3) # 1 (= 2 + 3 + 5 -9)\r\nsum(2, 3, 4) # 0  (= 2 + 3 + 4 -9)\r\nsum(2, 3, 4, n4=100) # 109 (= 2 + 3 + 4 + 100)\r\n\r\n(x, y, z) -> x + y + z\r\n# (anonymous function)\r\n\r\narr = rand(100)\r\n# 100-element Array{Float64,1}:\r\n#  0.0552819\r\n#  0.319113\r\n#  0.488649\r\n#  ...\r\n\r\narr2 = map(x -> x^2, arr)\r\n# 100-element Array{Float64,1}:\r\n#  0.00305609\r\n#  0.101833\r\n#  0.238778\r\n\r\narr2 = [x^2 for x in arr]\r\n# 100-element Array{Any,1}:\r\n#  0.00305609\r\n#  0.101833\r\n#  0.238778\r\n\r\nisodd(n) = (n % 2 != 0)\r\n\r\nfilter(isodd, round(Int64, rand(100) * 100))\r\n# 50-element Array{Int64,1}:\r\n#  57\r\n#  99\r\n#  23\r\n\r\nfilter(n -> n %2 != 0, round(Int64, rand(100) * 100))\r\n\r\nmap(collect(1:100)) do x\r\n        7x^2 - 3.14x + sin(x) + 4\r\nend\r\n# 100-element Array{Float64,1}:\r\n#      8.70147\r\n#     26.6293\r\n#     57.7211\r\n#    102.683\r\n# ...", "meta": {"hexsha": "61cdb6b9b827d3ac870e1f62222bad269d3b7ddd", "size": 1628, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Section 1/1_5.jl", "max_stars_repo_name": "lytemar/Julia-for-Data-Science-Video", "max_stars_repo_head_hexsha": "e7cb2427b10979d4be0f1e00be1cc1090f4da736", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-09-01T15:05:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T14:09:53.000Z", "max_issues_repo_path": "Section 1/1_5.jl", "max_issues_repo_name": "lytemar/Julia-for-Data-Science-Video", "max_issues_repo_head_hexsha": "e7cb2427b10979d4be0f1e00be1cc1090f4da736", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Section 1/1_5.jl", "max_forks_repo_name": "lytemar/Julia-for-Data-Science-Video", "max_forks_repo_head_hexsha": "e7cb2427b10979d4be0f1e00be1cc1090f4da736", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-09-01T15:05:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-08T15:00:22.000Z", "avg_line_length": 17.8901098901, "max_line_length": 75, "alphanum_fraction": 0.515970516, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7654243570410472}}
{"text": "\n\"\"\"\nGenerate a Ricker Wavelet. Reference:\nFrequencies of the Ricker wavelet, Yanghua Wang, GEOPHYSICS, VOL. 80, NO. 2\nBandwidth is roughly 1.2 * fpeak for ricker\n\n# Keyword Arguments\n\n* `fqdom::Float64`: dominant frequency \n* `tgrid`: time-domain grid\n* `tpeak::Float64=tgrid[1]+1.5/fqdom`: the peak of the ricker in time (has a default)\n* `tpeak_rand_flag` : randomly place peak of ricker\n\"\"\"\nfunction ricker(fqdom::Float64,\n\t\ttgrid::StepRangeLen;\n\t\ttpeak::Float64=tgrid[1]+1.5/fqdom, # using approximate half width of ricker\n\t\tattrib::AbstractString=\"\",\n\t\ttrim_tol::Float64=0.0,\n\t\tmaxamp::Float64=1.0,\n\t\ttpeak_rand_flag=false,\n\t\tmaxamp_rand_flag=false,\n\t\tphase_rand_flag=false,\n\t\t)\n\t(tpeak < tgrid[1]+1.5/fqdom) && error(\"cannot output Ricker for given tgrid and tpeak\")\n\t(tpeak > tgrid[end]-1.5/fqdom) && error(\"cannot output Ricker for given tgrid and tpeak\")\n\n\tif(tpeak_rand_flag)\n\t\ttpeak=rand(Uniform(tgrid[1]+1.5/fqdom,tgrid[end]-1.5/fqdom))\n\tend\n\tif(maxamp_rand_flag)\n\t\tmaxamp=rand(Uniform(-1,1))\n\tend\n\tisapprox(fqdom,0.0) && error(\"dominant frequency cannot be zero\")\n\n\t#! some constants\n\tpf = (π*π)*(fqdom^2.0)\n\tnt = length(tgrid)\n\tδt = step(tgrid)\n\n\t# a vector is odd number of samples (nt + 1 corresponds to time zero)\n\twav = zero(tgrid);\n\t# k = (1 - 2* pf * t^2) * Exp[-pf *t^2]\n\t# Simplify[D[k,t]]\n\t# FortranForm[Simplify[D[k,t]]]\n\tif(occursin(\"[DIFF]\",attrib))\n\t\t\t# ricker after a time derivative\n\t\t\tfor it = 1:nt\n\t\t\t\ttsquare = (tgrid[it]-tpeak) * (tgrid[it]-tpeak)\n\t\t\t\tt       = -1.0 * (tgrid[it]-tpeak)\n\t\t\t\twav[it] = (2.0 * pf * t * (-3.0 + 2.0 * pf * tsquare)) * exp(-1.0 * pf * tsquare)\n\t\t\tend\n\telse\n\t#! ricker wavelet\n\t\tfor it = 1:nt\n\t\t\ttsquare = (tgrid[it]-tpeak) * (tgrid[it]-tpeak)\n\t\t\twav[it] = (1.0 - 2.0 * pf * tsquare) * exp(-1.0e0 * pf * tsquare) * maxamp\n\t\tend\n\tend\n\n\tisapprox(maximum(abs.(wav)),0.0) && warn(\"wavelet is zeros\")\n\n\t# apply random phase to the ricker wavelet\n\tif(phase_rand_flag)\n\t\twav=apply_rand_phase(wav)\n\tend\n\n\tif(trim_tol != 0.0)\n\t\treturn wav[abs(wav).>=trim_tol]\n\telse\n\t\treturn wav\n\tend\nend\n\n\n\"\"\"\normbsy wavelet\n\n\n* `tperc::Float64=0.0` : the wavelet is tapered in time using this percentage value\n\"\"\"\nfunction  ormsby(\n\t\tfqdom,\n\t\ttgrid::StepRangeLen;\n\t\tfracbandwidth::Float64=1.2, # using same value as Ricker\n\t\tf1::Float64=fqdom-fracbandwidth*0.5*fqdom,\n\t\tf4::Float64=fqdom+fracbandwidth*0.5*fqdom,\n\t\tf2::Float64=0.25*f4+0.75*f1,\n\t\tf3::Float64=0.25*f1+0.75*f4,\n\t\ttpeak::Float64=tgrid[1]+1.5/(0.25*(f1+f4)), # using approximate half width \n\t\ttrim_tol::Float64=0.0,\n\t\ttperc::Float64=0.0,\n\t\ttpeak_rand_flag=false,\n\t\tmaxamp_rand_flag=false,\n\t\tphase_rand_flag=false,\n\t\t)\n\n\t# some constants\n\tA43 = (pi*f4)^2 / (pi*f4 - pi*f3);\n\tA34 = (pi*f3)^2 / (pi*f4 - pi*f3);\n\tA21 = (pi*f2)^2 / (pi*f2 - pi*f1);\n\tA12 = (pi*f1)^2 / (pi*f2 - pi*f1);\n\n\twav = zeros(length(tgrid));\n\n\tif(tpeak_rand_flag)\n\t\ttpeak=rand(Uniform(tgrid[1]+1.5/(0.25*(f1+f4)),tgrid[end]-1.5/(0.25*(f1+f4))))\n\tend\n\n\t# ormsby wavelet\n\tfor it = 1: length(tgrid)\n\t\tt = tgrid[it]-tpeak\n\t\tS4 = (sinc(pi*f4*t))^2\n\t\tS3 = (sinc(pi*f3*t))^2\n\t\tS2 = (sinc(pi*f2*t))^2\n\t\tS1 = (sinc(pi*f1*t))^2\n\n\t\twav[it] =  ((A43 * S4 - A34 * S3) - (A21 * S2 - A12 * S1))\n\tend\n\n\tisapprox(maximum(abs.(wav)),0.0) && warn(\"wavelet is zeros\")\n\n\t# normalize\n\twav /= maximum(abs.(wav));\n\n\tif(maxamp_rand_flag)\n\t\twav *= rand(Uniform(-1,1))\n\tend\n\n\n\n\t# apply random phase to the ricker wavelet\n\tif(phase_rand_flag)\n\t\twav=apply_rand_phase(wav)\n\tend\n\n\tif(trim_tol != 0.0)\n\t\twav = wav[abs(wav).>=trim_tol]\n\tend\n\n\twav = wav .* Utils.taper(ones(length(wav)),tperc)\n\treturn wav\n\nend\n\n\nfunction apply_rand_phase(wav)\n\tnt=length(wav)\n\tW=FFTW.rfft(wav);\n\tθ=rand(Uniform(-Float64(pi),Float64(pi)))\n\tfor i in eachindex(W)\n\t\tW[i]=W[i]*complex(cos(θ),sin(θ))\n\tend\n\twav=FFTW.irfft(W,nt)\nend\n\n\"\"\"\nReturn a ricker wavelet for a given input `Medium`.\n\n# Arguments\n* `mod::Medium` : Medium\n* `nλ::Int64=10` : number of wavelengths (P-wave) in the medium\n* `tmaxfrac::Float64=1.0` : by default the maximum modelling time is computed using the average velocity and the diagonal distance of the medium, \nuse this fraction to increase of reduce the maximum time\n\n# Keyword Arguments\n* all the keywords arguments of the `ricker` method can be used.\n\"\"\"\nfunction ricker(mod::Medium, nλ::Int=10, tmaxfrac::Real=1.0, epsilon=inv(sqrt(ndims(mod))); args... )\n\t@assert(!iszero(mod))\n\tfqdom, tgrid = get_fqdom_tgrid(mod, nλ, tmaxfrac, epsilon)\n\twav=ricker(fqdom, tgrid; args...)\n\treturn wav, tgrid\nend\n\n\"\"\"\nSame as ricker, but return ormsby...\n\"\"\"\nfunction ormsby(mod::Medium, nλ::Int=10, tmaxfrac::Real=1.0, epsilon=inv(sqrt(ndims(mod))); args... )\n\t@assert(!iszero(mod))\n\tfqdom, tgrid = get_fqdom_tgrid(mod, nλ, tmaxfrac, epsilon)\n\twav=ormsby(fqdom, tgrid; args...)\n\treturn wav, tgrid\nend\n\n\"\"\"\nReturn dominant source frequency, and its temporal grid for a finite-difference simulation, for given number of wavelengths `nλ` in the medium.\nThe model has `nλ` wavelengths, and the maximum modeling time is determined by `tmaxfrac`.\n`epsilon` is Courant number.\n\"\"\"\nfunction get_fqdom_tgrid( mod::Medium, nλ::Int, tmaxfrac::Real, epsilon)\n\n\t# maximum distance (diagnol) the wave travels\n\td = sqrt(sum([(m[1]-m[end])^2 for m in mod.mgrid]))\n\n\t# dominant wavelength using mod dimensions\n\tλdom=d*inv(real(nλ))\n\n\t# average P velocity\n\tvavg=mod.ref[:vp]\n\n\tfqdom = vavg/λdom\n\n\t# use two-way maximum distance to get tmax\n\ttmax=2.0*d*inv(vavg)*tmaxfrac\n\n\t# choose sampling interval to obey max freq of source wavelet\n\tδmin = minimum(step.(mod.mgrid))\n\tvmax=try\n\t\tsqrt(mod.bounds[:vp][2]^2 + mod.bounds[:vs][2]^2) # see Virieux (1986)\n\tcatch\n\t\tmod.bounds[:vp][2]\n\tend\n\tδt=epsilon*δmin/vmax\n\n\t# check if δt is reasonable\n\t#(δt > 0.1/fqdom) : error(\"decrease spatial sampling or nλ\")\n\n\ttgrid=range(0.0, stop=tmax, step=δt)\n\n\treturn fqdom, tgrid\nend\n\n\n", "meta": {"hexsha": "7cb9fd9ea11a7b52e93343f507b32900cf3dc883", "size": 5778, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/srcwav/wavelets.jl", "max_stars_repo_name": "ayushinav/GeoPhyInv.jl", "max_stars_repo_head_hexsha": "b0ce642161cb5300e2e7a5bd737b58fe37ddbfeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-01-05T04:30:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-26T18:32:37.000Z", "max_issues_repo_path": "src/srcwav/wavelets.jl", "max_issues_repo_name": "ayushinav/GeoPhyInv.jl", "max_issues_repo_head_hexsha": "b0ce642161cb5300e2e7a5bd737b58fe37ddbfeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-11-14T19:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-16T19:55:36.000Z", "max_forks_repo_path": "src/srcwav/wavelets.jl", "max_forks_repo_name": "ayushinav/GeoPhyInv.jl", "max_forks_repo_head_hexsha": "b0ce642161cb5300e2e7a5bd737b58fe37ddbfeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-08-15T14:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T21:18:19.000Z", "avg_line_length": 25.7946428571, "max_line_length": 146, "alphanum_fraction": 0.6720318449, "num_tokens": 2074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7654243558877333}}
{"text": "\"\"\"\n     fdhinfminus(sys,freq) -> (β, ind, fr)\n\nCompute for a stable descriptor system `sys = (A-λE,B,C,D)` the `H∞-` index `β` of its\ntransfer function matrix `G(λ)`. If `freq = missing` (default), then `β` is the \nminimum `H∞-norm` of the columns of `G`, `ind` is the index of the minimum-norm column and `fr` is \nthe frequency where the minimum `H∞-norm` of the columns is achieved. If `freq` is a real value or \na real vector of frequency values, then `β` is the minimum of the 2-norms of the columns of the \nfrequency responses of `G` evaluated for all values contained in `freq`, `ind` is the index of column \nfor which the minimum is achieved and `fr` is the corresponding frequency. \n\"\"\"\nfunction fdhinfminus(sys::DescriptorStateSpace{T}, freq::Union{AbstractVector{<:Real},Real,Missing} = missing) where T\n   p, m = size(sys)\n\n   m == 0 && (return T[], Int[], T[])\n   \n   isstable(sys) || error(\"the system is unstable\")\n   β = Inf; ind = 0; f = -1;\n   if ismissing(freq) \n      # evaluate β as the minimum of H-infinity norms of the columns of G\n      for j = 1:m\n         temp, fr = ghinfnorm(sys[:,j])\n         β <= temp || (β = temp; ind = j; f = fr)\n      end\n   else\n      # evaluate β as the minimum of the norms of columns of the frequency \n      # responses of G evaluated over all frequencies contained in FREQ \n      if !isa(freq, Vector) \n         # use evalfr if only one frequency is present\n         H = evalfr(sys; fval = freq) \n         for j = 1:m\n             temp = norm(view(H,:,j))\n             β <= temp || (β = temp; ind = j)\n         end\n         f = freq\n      else\n         T1 = T <: BlasFloat ? T : promote_type(Float64,T) \n         ONE = one(T1)\n         a, e, b, c, d = dssdata(T1,sys)\n         Ts = abs(sys.Ts)\n         disc = !iszero(Ts)\n         sw = disc ? im*Ts : im\n         desc = !(e == I)\n         # Determine the complex Hessenberg-form system to be used for efficient\n         # frequency response computation.\n         ac, ec, bc, cc, dc = chess(a, e, b, c, d)\n         H = similar(dc, eltype(dc), p, m)\n         bct = similar(bc) \n         for i = 1:length(freq)\n             if isinf(freq[i])\n                # exceptional call to evalfr\n                H = evalfr(sys, fval=Inf)\n             else\n                copyto!(H, dc)\n                copyto!(bct, bc)\n                w = disc ? -exp(sw*freq[i]) : -sw*freq[i]\n                desc ? ldiv!(UpperHessenberg(ac+w*ec),bct) : ldiv!(ac,bct,shift = w)\n                mul!(H, cc, bct, -ONE, ONE)\n             end\n             for j = 1:m\n                 temp = norm(view(H,:,j))\n                 β <= temp || (β = temp; ind = j; f = freq[i])\n             end\n         end\n      end\n   end\n   return β, ind, f\nend\n\"\"\"\n     fdhinfmax(sys,freq) -> (γ, ind, fr)\n\nCompute for a descriptor system `sys = (A-λE,B,C,D)`, `γ` - the maximum norm of the columns of its\ntransfer function matrix `G(λ)`. If `freq = missing` (default), then `γ` is the \nmaximum `H∞-norm` of the columns of `G`, `ind` is the index of the maximum-norm column and `fr` is \nthe frequency where the maximum `H∞-norm` of the columns is achieved. If `freq` is a real value or \na real vector of frequency values, then `γ` is the maximum of the 2-norms of the columns of the \nfrequency responses of `G` evaluated for all values contained in `freq`, `ind` is the index of column \nfor which the maximum is achieved and `fr` is the corresponding frequency. \n\"\"\"\nfunction fdhinfmax(sys::DescriptorStateSpace{T}, freq::Union{AbstractVector{<:Real},Real,Missing} = missing) where T\n   p, m = size(sys)\n\n   m == 0 && (return T[], Int[], T[])\n   \n   γ = 0; ind = 0; f = -1;\n   if ismissing(freq) \n      # evaluate γ as the maximum of H-infinity norms of the columns of G\n      for j = 1:m\n         temp, fr = ghinfnorm(sys[:,j])\n         γ >= temp || (γ = temp; ind = j; f = fr)\n      end\n   else\n      # evaluate γ as the maximum of the norms of columns of the frequency \n      # responses of G evaluated over all frequencies contained in FREQ \n      if !isa(freq, Vector) \n         # use evalfr if only one frequency is present\n         H = evalfr(sys; fval = freq) \n         for j = 1:m\n             temp = norm(view(H,:,j))\n             γ >= temp || (γ = temp; ind = j)\n         end\n         f = freq\n      else\n         T1 = T <: BlasFloat ? T : promote_type(Float64,T) \n         ONE = one(T1)\n         a, e, b, c, d = dssdata(T1,sys)\n         Ts = abs(sys.Ts)\n         disc = !iszero(Ts)\n         sw = disc ? im*Ts : im\n         desc = !(e == I)\n         # Determine the complex Hessenberg-form system to be used for efficient\n         # frequency response computation.\n         ac, ec, bc, cc, dc = chess(a, e, b, c, d)\n         H = similar(dc, eltype(dc), p, m)\n         bct = similar(bc) \n         for i = 1:length(freq)\n             if isinf(freq[i])\n                # exceptional call to evalfr\n                H = evalfr(sys, fval=Inf)\n             else\n                copyto!(H, dc)\n                copyto!(bct, bc)\n                w = disc ? -exp(sw*freq[i]) : -sw*freq[i]\n                desc ? ldiv!(UpperHessenberg(ac+w*ec),bct) : ldiv!(ac,bct,shift = w)\n                mul!(H, cc, bct, -ONE, ONE)\n             end\n             for j = 1:m\n                 temp = norm(view(H,:,j))\n                 γ >= temp || (γ = temp; ind = j; f = freq[i])\n             end\n         end\n      end\n   end\n   return γ, ind, f\nend\nfunction binmat2dec(S::Union{BitArray,VecOrMat{<:Number}})\n# Convert a binary matrix with zero/non-zero elements to an equivalent decimal number integer vector\n   len = size(S,2)\n   n = Int.(S[:,1] .!= 0)\n   for i = 2:len\n       n .= 2*n .+ Int.(S[:,i] .!= 0)\n   end\n   return n\nend\nfunction dec2binmat(n::Union{Int,Vector{Int}}, numbits::Int = 1)\n# Convert a decimal non-negative integer or integer vector with decimal non-negative values \n# to their binary matrix representation with `numbits` bits.\n   minimum(n) < 0 && error(\"only non-negative values allowed\")\n   maxn = maximum(n)\n   len = maxn == 0 ? max(1,numbits) : max(Int(floor(log2(maxn)+1)),numbits) \n   ns = size(n,1)\n   v = isa(n,Int) ? string.([n], base = 2, pad = len) : string.(n, base = 2, pad = len) \n   S = falses(ns,len)  \n   for i = 1:ns\n       for j = 1:len\n           S[i,j] = parse(Int,v[i][j]) == 1\n       end\n   end\n   return S\nend\n\"\"\"\n    S = fditspec_(sysrf::DescriptorStateSpace; FDfreq = missing, block = false, poleshift = false, \n                 FDtol, FDStol, atol = 0, atol1 = atol, atol2 = atol, rtol, fast = true) \n\nCompute the weak or strong binary structure matrix `S` of the transfer function matrix of a \nlinear time-invariant system `sysrf` \n(typically representing the transfer channel from the fault inputs to residuals).\n`sysrf` has a descriptor system realization of the form `sysrf = (Af-lambda*Ef,Bf,Cf,Df)` \nwith a  `q x mf` transfer function matrix `Rf(λ)`. \nFor the description of keyword parameters see the documentation of [`fditspec`](@ref). \n\"\"\"\nfunction fditspec_(sysrf::DescriptorStateSpace{T}; FDfreq::Union{AbstractVector{<:Real},Real,Missing} = missing, \n                  block::Bool = false, poleshift::Bool = false, FDtol::Real = 0., FDStol::Real = 0., \n                  atol::Real = zero(float(real(T))), atol1::Real = atol, atol2::Real = atol, \n                  rtol::Real =  (size(sysrf.A,1)+1)*eps(float(one(real(T))))*iszero(max(atol1,atol2)), fast::Bool = true) where T\n   p, mf = size(sysrf) \n   n = order(sysrf)\n   q = block ? 1 : p  # number of rows of S\n   Sstrong = !ismissing(FDfreq)\n   if Sstrong\n      isa(FDfreq,Vector) || (FDfreq = [FDfreq]) \n      lfreq = length(FDfreq);\n      w = im*FDfreq;                   # w = j*freq\n      Ts = abs(sysrf.Ts);\n      Ts > 0 && ( w = exp(Ts*w))     # w = exp(j*Ts*freq)\n      S = falses(q,mf,lfreq)\n   else\n      S = falses(q,mf)\n   end   \n   a, e, b, c, d = dssdata(sysrf)\n   standard = isequal(e,I)\n   if n == 0\n      S1 =  abs.(d) .> (FDtol <= 0 ? 0.0001*max(1., norm(d,1)) : FDtol) \n      S = block ? maximum(S1, dims=1) : S1\n      return Sstrong ? repeat(S,1,1,lfreq) : S\n   end\n   if Sstrong\n      #FDStol <= 0. && (FDStol = 0.0001*max(1., norm(a,1), norm(b,1), norm(c,Inf), norm(d,1), standard ? 0 : norm(e,1))) \n      FDStol <= 0. && (FDStol = eps(max(1., norm(a,1), norm(b,1), norm(c,Inf), norm(d,1), standard ? 0 : norm(e,1)))) \n      S = trues(q, mf, lfreq)\n      p1, n1 = size(c,1), size(c,2)\n      # employ structural analysis to compute weak/strong structure matrix  \n      ispole = false\n      for k = 1:lfreq\n         # check if freq(k) is a pole \n         ispole = isinf(FDfreq[k]) ? (e == I ? false : rank(e) < n1) : rank(a-w[k]*e) < n1 \n         ispole || break\n      end\n      ispole && !poleshift && error(\"sysf has poles in Ω\")\n      if block\n         ispole && (f = rand(T,n1,p1); mul!(a,f,c,1,1); mul!(b,f,d,1,1) ) \n         for j = 1:mf \n             # elliminate uncontrollable and unobservable eigenvalues for the j-th column of B\n             a1, e1, b1, c1, d1 = lsminreal(a, e, view(b,:,j), c, view(d,:,j); noseig = false, atol1, atol2, rtol, fast)\n             for k = 1:lfreq\n                # check if freq(k) is a zero of the j-th column \n                s = isinf(FDfreq[k]) ? svdvals!([e1 b1; c1 d1]) : svdvals!([a1-w[k]*e1 b1; c1 d1])\n                S[1, j, k] = (s[end] > FDStol)\n            end\n         end\n      else\n         for i = 1:p \n             # elliminate unobservable eigenvalues for the i-th row of C\n             a1, e1, b1, c1, d1 = lsminreal(a, e, b, view(c,i:i,:), view(d,i:i,:); contr = false, noseig = false, atol1, atol2, rtol, fast)\n             n1 = size(a1,1)\n             ispole && (f1 = rand(T,n1,1); mul!(a1,f1,c1,1,1); mul!(b1,f1,d1,1,1) ) \n             for j = 1:mf \n                 # elliminate uncontrollable and non-dynamic eigenvalues for the j-th column of B\n                 a2, e2, b2, c2, d2 = lsminreal(a1, e1, view(b1,:,j:j), c1, view(d1,:,j:j); obs = false, noseig = true, atol1, atol2, rtol, fast)\n                 for k = 1:lfreq\n                    # check if freq(k) is a zero of the (i,j)-th element \n                    s = isinf(FDfreq[k]) ? svdvals!([e2 b2; c2 d2]) : svdvals!([a2-w[k]*e2 b2; c2 d2])\n                    S[i,j,k] = s[end] > FDStol\n                 end\n             end\n         end\n      end\n   else\n      FDtol <= 0. && (FDtol = 0.0001*max(1., norm(b,1), norm(d,1)))\n      standard && all(abs.(d) .> FDtol) && (return trues(q,mf))\n      S = falses(q, mf)\n      if block\n         for j = 1:mf\n             # compute minimal realization of the j-th column of Rf\n             _, _, b1, _, d1 = lsminreal(a, e, view(b,:,j:j), c, view(d,:,j:j); atol1, atol2, rtol, fast)\n             S[1,j] |=  (any(abs.(view(d1,:,1)) .> FDtol) || any(abs.(view(b1,:,1)) .> FDtol))\n         end\n      else\n         for j = 1:mf \n             # elliminate uncontrollable eigenvalues for the j-th column of B\n             a1, e1, b1, c1, d1 = lsminreal(a, e, view(b,:,j), c, view(d,:,j); obs = false, noseig = false, atol1, atol2, rtol, fast)\n             for i = 1:p \n                # elliminate unobservable and non-dynamic eigenvalues for the (i,j)-th element\n                _, _, b2, _, d2 = lsminreal(a1, e1, b1, view(c1,i:i,:),view(d1,i:i,:); contr = false, noseig = true, atol1, atol2, rtol, fast)\n                S[i,j] |=  (abs(d2[1,1]) > FDtol || any(abs.(view(b2,:,1)) .> FDtol))\n             end\n         end\n      end\n   end\n   return S\nend\n\"\"\"\n     fdisspec_(sysrf::DescriptorStateSpace, freq; block = false, stabilize = false, FDGainTol = 0.01, \n                     atol, atol1, atol2, atol3, rtol, fast = true) -> (S, gains)\n\nCompute the strong binary structure matrix `S` of the transfer function matrix of a \nlinear time-invariant system `sysrf` \n(typically representing the transfer channel from the fault inputs to residuals).\n`sysrf` has a descriptor system realization of the form `sysrf = (Af-lambda*Ef,Bf,Cf,Df)` \nwith a  `q x mf` transfer function matrix `Rf(λ)`. \nFor the description of keyword parameters see the documentation of [`fdisspec`](@ref). \n\"\"\"\nfunction fdisspec_(sysrf::DescriptorStateSpace{T}, freq::Union{AbstractVector{<:Real},Real} = 0; stabilize::Bool = false, FDGainTol::Real = 0.01, block::Bool = false, \n                   atol::Real = zero(float(real(T))), atol1::Real = atol, atol2::Real = atol, atol3::Real = atol, \n                   rtol::Real =  ((max(size(sysrf.A)...))+1)*eps(float(one(real(T))))*iszero(max(atol1,atol2)), fast::Bool = true) where T\n   p, mf = size(sysrf) \n   isa(freq,Vector) || (freq = [freq]) \n   lfreq = length(freq);\n   w = im*freq;                   # w = j*freq\n   Ts = abs(sysrf.Ts);\n   Ts > 0 && ( w = exp(Ts*w))     # w = exp(j*Ts*freq)\n\n   ispole = false\n   n = size(sysrf.A,1)\n   for k = 1:lfreq\n      # check if freq(k) is a pole \n      ispole = isinf(freq[k]) ? (sysrf.E == I ? false : rank(sysrf.E) < n) : rank(sysrf.A-w[k]*sysrf.E) < n \n      ispole || break\n   end\n   ispole && !stabilize && error(\"sysf has poles in Ω\")\n   if block\n      stabilize && (sysrf = glcf(sysrf; atol1, atol2, atol3, rtol)[1])\n      # gs = evalfr(sysrf, w[1]; atol1, atol2, rtol, fast) \n      # any(isinf.(gs)) && error(\"fdisspec:pole - the frequency $(w[1]) is a system pole\")\n      smat = falses(1, mf, lfreq)\n      gains = zeros(T, 1, mf, lfreq)\n      for i = 1:lfreq\n          gs = evalfr(sysrf, w[i]; atol1, atol2, rtol, fast) \n         any(isinf.(gs)) && error(\"fdisspec_:pole - the frequency $(w[i]) is a system pole\")\n          for j = 1:mf \n              gsj = norm(view(gs,:,j))\n              gains[1,j,i] = gsj\n              smat[1,j,i] = (gsj .> FDGainTol)\n          end\n      end\n   else\n      smat = falses(p, mf, lfreq)\n      gains = zeros(T, p, mf, lfreq)\n      for k = 1:p\n         t = gir(sysrf[k,:]; contr = false, atol1, atol2, rtol)\n         stabilize && (t = glcf(t; atol1, atol2, atol3, rtol)[1])\n         for i = 1:lfreq\n            #  gs = stabilize ? abs.(evalfr(glcf(t; atol1, atol2, atol3, rtol)[1], w[i]; atol1, atol2, rtol, fast)) :\n            #                   abs.(evalfr(t, w[i]; atol1, atol2, rtol, fast))\n             gs = abs.(evalfr(t, w[i]; atol1, atol2, rtol, fast))\n             any(isinf.(gs)) && error(\"fdisspec_:pole - the frequency $(w[i]) is a system pole\")\n             gains[k,:,i] = gs\n             smat[k,:,i] = (gs .> FDGainTol)\n         end\n      end\n   end\n   return smat, gains\nend\n\"\"\"\n     fdiscond_(sysrf::DescriptorStateSpace, freq) -> (scond, β, γ)\n\nCompute for a stable descriptor system `sysrf = (A-λE,B,C,D)` with the transfer function matrix `Rf(λ)`, \n`β` - the H∞- index of `Rf(λ)`, `γ` - the maximum of the columns norms of `Rf(λ)` and \n`scond` - the column-gains sensitivity condition evaluated as `scond := β/γ`. \nIf `freq` is a vector of real frequency values, then `β` and `γ`\nare evaluated over the frequencies contained in `freq`. \n\"\"\"\nfunction fdiscond_(sysrf::DescriptorStateSpace{T}, freq::Union{AbstractVector{<:Real},Real,Missing} = missing) where T\n   p, m = size(sysrf)\n\n   m == 0 && (return T[], T[], T[])\n\n   isstable(sysrf) || error(\"the system is unstable\")\n\n   β = Inf\n   γ = 0 \n   if ismissing(freq) \n      # evaluate β and γ as the minimum and maximum of H-infinity norms of the columns of G\n      for j = 1:m\n         temp = ghinfnorm(sysrf[:,j])[1]\n         γ >= temp || (γ = temp)\n         β <= temp || (β = temp)\n      end\n   else\n      # evaluate β and γ as the minimum and maximum of the norms of columns of the frequency \n      # responses of G evaluated over all frequencies contained in FREQ \n      if !isa(freq, Vector) \n         # use evalfr if only one frequency is present\n         H = evalfr(sysrf; fval = freq) \n         for j = 1:m\n             temp = norm(view(H,:,j))\n             γ >= temp || (γ = temp)\n             β <= temp || (β = temp)\n         end\n      else\n         T1 = T <: BlasFloat ? T : promote_type(Float64,T) \n         ONE = one(T1)\n         a, e, b, c, d = dssdata(T1,sysrf)\n         Ts = abs(sysrf.Ts)\n         disc = !iszero(Ts)\n         sw = disc ? im*Ts : im\n         desc = !(e == I)\n         # Determine the complex Hessenberg-form system to be used for efficient\n         # frequency response computation.\n         ac, ec, bc, cc, dc = chess(a, e, b, c, d)\n         H = similar(dc, eltype(dc), p, m)\n         bct = similar(bc) \n         for i = 1:length(freq)\n             if isinf(freq[i])\n                # exceptional call to evalfr\n                H = evalfr(sys, fval=Inf)\n             else\n                copyto!(H, dc)\n                copyto!(bct, bc)\n                w = disc ? -exp(sw*freq[i]) : -sw*freq[i]\n                desc ? ldiv!(UpperHessenberg(ac+w*ec),bct) : ldiv!(ac,bct,shift = w)\n                mul!(H, cc, bct, -ONE, ONE)\n             end\n             for j = 1:m\n                 temp = norm(view(H,:,j))\n                 γ >= temp || (γ = temp)\n                 β <= temp || (β = temp)\n             end\n         end\n      end\n   end\n   return β/γ, β, γ\nend\n", "meta": {"hexsha": "730d6d136892017d3c26d1677627808c78568cca", "size": 16928, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FDIutils.jl", "max_stars_repo_name": "andreasvarga/FaultDetectionTools", "max_stars_repo_head_hexsha": "854dcc0a05a89d893b6857bafa9c25b02007ae55", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-09T05:17:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T14:43:29.000Z", "max_issues_repo_path": "src/FDIutils.jl", "max_issues_repo_name": "andreasvarga/FaultDetectionTools", "max_issues_repo_head_hexsha": "854dcc0a05a89d893b6857bafa9c25b02007ae55", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-27T13:29:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T20:29:23.000Z", "max_forks_repo_path": "src/FDIutils.jl", "max_forks_repo_name": "andreasvarga/FaultDetectionTools", "max_forks_repo_head_hexsha": "854dcc0a05a89d893b6857bafa9c25b02007ae55", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9644670051, "max_line_length": 167, "alphanum_fraction": 0.5401701323, "num_tokens": 5354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7653945079532588}}
{"text": "\"\"\"\nThe inverse logit function, which is also the CDF of the Logistic(0, 1)\ndistribution. Note that this function will generate an exact value of 0 when\nz <= -710 and will generate an exact value of 1 when z >= 37. This introduces\nnumeric problems if you provide inputs outside of that range.\n\"\"\"\n@inline invlogit(z::Real) = 1 / (1 + exp(-z))\n\n\"\"\"\nThe logit function, which is also the quantile function of the Logistic(0, 1)\ndistribution.\n\"\"\"\n@inline logit(p::Real) = log(p / (1 - p))\n", "meta": {"hexsha": "60f698e82deb731ff024726c03f8da5c3b6b9306", "size": 486, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/links.jl", "max_stars_repo_name": "johnmyleswhite/IntertemporalChoiceHeuristics.jl", "max_stars_repo_head_hexsha": "6562fb1740a5e7af67b3a427a32acfd473a7e53f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-02T21:33:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-02T21:33:51.000Z", "max_issues_repo_path": "src/links.jl", "max_issues_repo_name": "johnmyleswhite/IntertemporalChoiceHeuristics.jl", "max_issues_repo_head_hexsha": "6562fb1740a5e7af67b3a427a32acfd473a7e53f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/links.jl", "max_forks_repo_name": "johnmyleswhite/IntertemporalChoiceHeuristics.jl", "max_forks_repo_head_hexsha": "6562fb1740a5e7af67b3a427a32acfd473a7e53f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7142857143, "max_line_length": 77, "alphanum_fraction": 0.70781893, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7653945078415679}}
{"text": "# Bifurcation diagram for 1D climate model\nusing DrWatson\n@quickactivate \"NonlinearDynamicsTextbook\"\ninclude(srcdir(\"style.jl\"))\nusing DynamicalSystems, PyPlot\n\ninclude(srcdir(\"simple_continuation.jl\"))\n\nusing ForwardDiff, PyPlot\nαtan(T) = 0.5 - 0.2*tanh((T-263)/4)\ndTdt(T, ε = 0.65, α=αtan, s= 1.0) = s*(1 - α(T)) - 1.6e-10 * ε * T^4\ndTdt(T; ε = 0.65, α=αtan, s = 1.0) = dTdt(T, ε, α, s)\nd²Tdt²(T, ε) = ForwardDiff.derivative(T -> dTdt(T, ε), T)\nclimate_f(u, p, t) = SVector(dTdt(u[1], p))\nclimate_J(u, p, t) = SMatrix{1,1}(d²Tdt²(u[1], p))\n\nu0 = SVector(225.0)\np0 = 0.9\nds = ContinuousDynamicalSystem(climate_f, u0, p0, climate_J)\n\nf, J = bifurcation_rule_form(ds)\n\npmin = 0.3\npmax = 1\n\ndp0 = 0.05\ndx0 = SVector(0.1)\n\nxs, ps, stability = continuation(f, J, u0, p0;\n    pmin, pmax, dp0, dx0, N = 1500\n)\n\nxs = [x[1] for x in xs]\n\n\n# %% make figure\nstable1 = findfirst(!, stability)\nunstable1 = findlast(!, stability)\n\nfig = figure(figsize = (figx/2, figy))\nax = gca()\n\nplot(ps[1:stable1], xs[1:stable1]; c = \"C2\", ls = \"solid\", label=\"stable\")\nplot(ps[stable1+1:unstable1], xs[stable1+1:unstable1]; c = \"C2\", ls = \"dashed\", label=\"unstable\")\nplot(ps[unstable1+1:end], xs[unstable1+1:end]; c = \"C2\", ls = \"solid\")\n\n# scatter bifurcation points\nax.plot([ps[stable1], ps[unstable1]], [xs[stable1], xs[unstable1]], ls = \"None\",\n\t\tmarker=\"o\", ms = 12, color = \"k\", mew = 1, mec = \"k\",\n        fillstyle = \"top\", markerfacecoloralt= \"w\"\n)\n\n# plot arrows\n_a = 300\narrow1ε = ps[_a:stable1] .- 0.03\narrow1T = xs[_a:stable1] .- 5\nplot(arrow1ε, arrow1T; color = \"C1\", lw = 4.0)\narrow(arrow1ε[end], arrow1T[end], 0, 50; \nwidth = 0.004, head_length = 5.0, color = \"C1\", zorder = 99)\n\n_b = 200\narrow2ε = ps[unstable1:unstable1+_b] .+ 0.03\narrow2T = xs[unstable1:unstable1+_b] .+ 5\n\nplot(arrow2ε, arrow2T; color = \"C0\", lw = 4.0)\narrow(arrow2ε[1], arrow2T[1], 0, -50; \nwidth = 0.004, head_length = 5.0, color = \"C0\", zorder = 99)\n\n# scatter(ps[stability], xs[stability]; c = \"C3\", legend = \"stable\")\n# scatter(ps[stability], xs[stability]; c = \"C3\", legend = \"stable\")\nlegend()\nxticks(0.3:0.2:0.9)\nyticks(200:50:350)\nylabel(\"\\$T^*\\$\", labelpad = -20)\nxlabel(\"\\$\\\\varepsilon\\$\"; labelpad=-20)\n# yticks(230:50:310)\n# ylim(210, 320)\n# ax.xaxis.set_label_coords(0.4, -0.025)\nfig.tight_layout(pad=0.3)\nwsave(plotsdir(\"4\", \"bif_example\"), fig)", "meta": {"hexsha": "a5428d638aac7807a6c1179ab5c2e3ef73bd0094", "size": 2322, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "figure_generation/4/4.1.jl", "max_stars_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_stars_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 88, "max_stars_repo_stars_event_min_datetime": "2021-07-18T20:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T09:23:53.000Z", "max_issues_repo_path": "figure_generation/4/4.1.jl", "max_issues_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_issues_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figure_generation/4/4.1.jl", "max_forks_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_forks_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-07-28T18:49:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:45:11.000Z", "avg_line_length": 29.025, "max_line_length": 97, "alphanum_fraction": 0.6391042205, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7653945059279834}}
{"text": "# MaxPlus Semiring Implementation\n# MaxPlus is over real numbers with max as addition and + as multiplication\n# The zero element is -inf and the one element is 0\n\nstruct MaxPlusSemiringElement{T<:Real} <: AbstractSemiringElement{T}\n    val::T\nend\n\n# interface methods\nval(x::MaxPlusSemiringElement) = x.val\n+(l::MaxPlusSemiringElement, r::MaxPlusSemiringElement) = MaxPlusSemiringElement(max(l.val, r.val))\n*(l::MaxPlusSemiringElement, r::MaxPlusSemiringElement) = MaxPlusSemiringElement(l.val+r.val)\nzero(::Type{MaxPlusSemiringElement{T}}) where T = MaxPlusSemiringElement(-Inf)\none(::Type{MaxPlusSemiringElement{T}}) where T = MaxPlusSemiringElement{T}(0)\n\niscommutative(::Type{<:MaxPlusSemiringElement}) = true\nisidempotent(::Type{<:MaxPlusSemiringElement}) = true\nisstar(::Type{<:MaxPlusSemiringElement}) = true\n\n# MinPlus Semiring Implementation\n# MinPlus is over real numbers with min as addition and + as multiplication\n# The zero element is +inf and the one element is 0\n\nstruct MinPlusSemiringElement{T<:Real} <: AbstractSemiringElement{T}\n    val::T\nend\n\n# interface methods\nval(x::MinPlusSemiringElement) = x.val\n+(l::MinPlusSemiringElement, r::MinPlusSemiringElement) = MinPlusSemiringElement(min(l.val, r.val))\n*(l::MinPlusSemiringElement, r::MinPlusSemiringElement) = MinPlusSemiringElement(l.val+r.val)\nzero(::Type{MinPlusSemiringElement{T}}) where T = MinPlusSemiringElement(Inf)\none(::Type{MinPlusSemiringElement{T}}) where T = MinPlusSemiringElement{T}(0)\n\niscommutative(::Type{<:MinPlusSemiringElement}) = true\nisidempotent(::Type{<:MinPlusSemiringElement}) = true\nisstar(::Type{<:MinPlusSemiringElement}) = true\n\n\n# Real (or Probabilistic) Semiring Implementation\n# The Real Semiring is over real numbers with + as addition and * as multiplication\n# The zero element is 0 and the one element is 1\n\nstruct RealSemiringElement{T<:Real} <: AbstractSemiringElement{T}\n    val::T\nend\n\n# interface methods\nval(x::RealSemiringElement) = x.val\n+(l::RealSemiringElement, r::RealSemiringElement) = RealSemiringElement(l.val+r.val)\n*(l::RealSemiringElement, r::RealSemiringElement) = RealSemiringElement(l.val*r.val)\nzero(::Type{RealSemiringElement{T}}) where T = RealSemiringElement(0)\none(::Type{RealSemiringElement{T}}) where T = RealSemiringElement(1)\n\niscommutative(::Type{<:RealSemiringElement}) = true\nisstar(::Type{<:RealSemiringElement}) = true\n\n# optional methods\n-(x::RealSemiringElement) = RealSemiringElement(-x.val)\n/(l::RealSemiringElement, r::RealSemiringElement) = RealSemiringElement(l.val/r.val)\nfunction star(x::RealSemiringElement)\n    0 <= x.val < 1 ? RealSemiringElement(1/(1-x.val)) : throw(DomainError(\"$x must be within [0, 1)\"))\nend\n\nfor op in (:conj,) # required for matrix inversion?\n    @eval begin\n        $op(x::RealSemiringElement) = RealSemiringElement($op(x.val))\n    end\nend\n\n# Boolean Semiring Implementation\n# The Boolean Semiring is over {True, False} with OR as addition and AND as multiplication\n# The zero element is False and the one element is True\n\nstruct BooleanSemiringElement{Bool} <: AbstractSemiringElement{Bool}\n    val::Bool\nend\n\n# interface methods\nval(x::BooleanSemiringElement) = x.val\n+(l::BooleanSemiringElement, r::BooleanSemiringElement) = BooleanSemiringElement(l.val | r.val)\n*(l::BooleanSemiringElement, r::BooleanSemiringElement) = BooleanSemiringElement(l.val & r.val)\nzero(::Type{BooleanSemiringElement{T}}) where T = BooleanSemiringElement{T}(false)\none(::Type{BooleanSemiringElement{T}}) where T = BooleanSemiringElement{T}(true)\n\niscommutative(::Type{<:BooleanSemiringElement}) = true\nisidempotent(::Type{<:BooleanSemiringElement}) = true\nisstar(::Type{<:BooleanSemiringElement}) = true\n\n#optional methods\nstar(x::R) where R<:BooleanSemiringElement = one(R)\n", "meta": {"hexsha": "34e20eccb43a24d69e19ad818310aee77b3f0603", "size": 3735, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/implementations.jl", "max_stars_repo_name": "mcognetta/Semirings.jl", "max_stars_repo_head_hexsha": "d5605585e43d17021926a067767bebc0c1bda526", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-03T01:59:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T10:10:23.000Z", "max_issues_repo_path": "src/implementations.jl", "max_issues_repo_name": "mcognetta/Semirings.jl", "max_issues_repo_head_hexsha": "d5605585e43d17021926a067767bebc0c1bda526", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/implementations.jl", "max_forks_repo_name": "mcognetta/Semirings.jl", "max_forks_repo_head_hexsha": "d5605585e43d17021926a067767bebc0c1bda526", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.597826087, "max_line_length": 102, "alphanum_fraction": 0.7665327979, "num_tokens": 1065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990283, "lm_q2_score": 0.8354835432479663, "lm_q1q2_score": 0.7653945040516293}}
{"text": "### A Pluto.jl notebook ###\n# v0.11.14\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ eb68872e-01ee-11eb-22e4-b1f20b71faff\nbegin\n\timport Pkg\n\tPkg.activate(mktempdir())\n\tPkg.add(\"Combinatorics\")\n\tusing Combinatorics\nend\n\t\n\n# ╔═╡ 9a4603ea-01f2-11eb-00f0-591422bc7142\nmd\" Given 20 people, what is the probability that,\namong the 12 months in the year, there are 4\nmonths containing exactly 2 birthdays and 4 containing exactly 3 birthdays?\n\n(For simplicity, assume that it is equally like that a birthday falls in one of the 12 months.) \n(from A First Course in Probablity - Sheldon Ross)\n\n\n\"\n\n# ╔═╡ 0cfeea3c-01ee-11eb-26f1-f1815eccdd10\nmd\"Create twenty birthday months\"\n\n# ╔═╡ 015393e0-01ee-11eb-2feb-d7db4236368a\nmonths = rand(1:12,20)\n\n# ╔═╡ 1a6a603e-01ee-11eb-39f6-efc09168a3ba\ncounts =  [sum(months.==i) for i=1:12]\n\n# ╔═╡ 67c25428-0251-11eb-04b0-cb201bbefa6b\nsum(counts)\n\n# ╔═╡ 6f1890a6-01ee-11eb-1524-1da938de93f3\nsum(counts.==2),sum(counts.==3)\n\n# ╔═╡ af424780-01ee-11eb-3d5f-4f4ba6a372b4\nsum(counts.==2)==4 & sum(counts.==3)==4\n\n# ╔═╡ d8b5158e-01ee-11eb-393f-0d51ea1fc19b\nfunction birthday_problem(n)\n  success = 0\n  for t=1:n\n     months = rand(1:12,20)\n     counts = [sum(months.==i) for i=1:12]\n     success += sum(counts.==2) == 4  &&  sum(counts.==3)==4\n   end\n   success/n\nend\n\n# ╔═╡ dea5c880-01ee-11eb-066d-8105b2196548\nbirthday_problem(20_000_000)\n\n# ╔═╡ d74e2646-01f2-11eb-2b25-158bf9419ecd\n@elapsed birthday_problem(20_000_000)\n\n# ╔═╡ 006a84ee-01ef-11eb-2db7-5792cb4d0198\nmultinomial(4,4,4) * multinomial(2,2,2,2,3,3,3,3) / 12.0^20\n\n# ╔═╡ Cell order:\n# ╟─9a4603ea-01f2-11eb-00f0-591422bc7142\n# ╟─0cfeea3c-01ee-11eb-26f1-f1815eccdd10\n# ╠═015393e0-01ee-11eb-2feb-d7db4236368a\n# ╠═1a6a603e-01ee-11eb-39f6-efc09168a3ba\n# ╠═67c25428-0251-11eb-04b0-cb201bbefa6b\n# ╠═6f1890a6-01ee-11eb-1524-1da938de93f3\n# ╠═af424780-01ee-11eb-3d5f-4f4ba6a372b4\n# ╠═d8b5158e-01ee-11eb-393f-0d51ea1fc19b\n# ╠═dea5c880-01ee-11eb-066d-8105b2196548\n# ╠═d74e2646-01f2-11eb-2b25-158bf9419ecd\n# ╠═eb68872e-01ee-11eb-22e4-b1f20b71faff\n# ╠═006a84ee-01ef-11eb-2db7-5792cb4d0198\n", "meta": {"hexsha": "67cc589e0b229eaf3d63fa9e9f9f08701c65a718", "size": 2058, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_notebooks/week5/birthday-problem.jl", "max_stars_repo_name": "mathijsvdv/ComputationalThinking", "max_stars_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lecture_notebooks/week5/birthday-problem.jl", "max_issues_repo_name": "mathijsvdv/ComputationalThinking", "max_issues_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecture_notebooks/week5/birthday-problem.jl", "max_forks_repo_name": "mathijsvdv/ComputationalThinking", "max_forks_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3846153846, "max_line_length": 96, "alphanum_fraction": 0.7244897959, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7653945003733816}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.18\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ d80342ae-522b-11eb-19c0-cf931fb4ae81\nusing Statistics\n\n# ╔═╡ 9c2ef32a-522d-11eb-29e6-29da29e4dec7\nusing Plots\n\n# ╔═╡ 88b47ee6-522d-11eb-1a98-ed4dd43dfd11\nBase.@kwdef mutable struct SampleAvg\n    t::Int = 0\n    avg::Float64 = 0.0\nend\n\n# ╔═╡ 8c94a810-522d-11eb-2024-01ca19bc1984\nfunction (s::SampleAvg)(x)\n    s.t += 1\n    s.avg += (x - s.avg) / s.t\n    s.avg\nend\n\n# ╔═╡ 8fde026e-522d-11eb-2aa1-f3e28c238ea6\nfunction run_once(b)\n    rms = Float64[]\n    distribution = randn(b)\n    expectation = mean(distribution)\n    sample_avg = SampleAvg()\n    \n    for i in 1:2*b\n        avg = sample_avg(distribution[rand(1:b)])\n        push!(rms, abs(avg - expectation))\n    end\n    rms\nend\n\n# ╔═╡ 969b48aa-522d-11eb-2039-61916ddf87d4\nbegin\n\tn_runs = 1000\n\tp = plot(legend=:topright)\n\n\tfor b in [2, 10, 100, 1000]\n\t\trms = mean(run_once(b) for _ in 1:n_runs)\n\t\txs = (1:2*b) ./ b\n\t\tplot!(p, xs, rms, label=\"b=$b\")\n\tend\n\n\tp\nend\n\n# ╔═╡ Cell order:\n# ╠═d80342ae-522b-11eb-19c0-cf931fb4ae81\n# ╠═88b47ee6-522d-11eb-1a98-ed4dd43dfd11\n# ╠═8c94a810-522d-11eb-2024-01ca19bc1984\n# ╠═8fde026e-522d-11eb-2aa1-f3e28c238ea6\n# ╠═9c2ef32a-522d-11eb-29e6-29da29e4dec7\n# ╠═969b48aa-522d-11eb-2039-61916ddf87d4\n", "meta": {"hexsha": "51aa730869c1787341de131d251fd49b3fd69560", "size": 1262, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/Chapter08_Expectation_VS_Sample.jl", "max_stars_repo_name": "xiruizhao/ReinforcementLearningAnIntroduction.jl", "max_stars_repo_head_hexsha": "21f5c2886b254a725a5cec0227721684807acc1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-08T12:50:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-08T12:50:53.000Z", "max_issues_repo_path": "notebooks/Chapter08_Expectation_VS_Sample.jl", "max_issues_repo_name": "xiruizhao/ReinforcementLearningAnIntroduction.jl", "max_issues_repo_head_hexsha": "21f5c2886b254a725a5cec0227721684807acc1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Chapter08_Expectation_VS_Sample.jl", "max_forks_repo_name": "xiruizhao/ReinforcementLearningAnIntroduction.jl", "max_forks_repo_head_hexsha": "21f5c2886b254a725a5cec0227721684807acc1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6885245902, "max_line_length": 49, "alphanum_fraction": 0.6640253566, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7653944946326283}}
{"text": "# # Surface-grid operations\n\n#md # ```@meta\n#md # CurrentModule = ImmersedLayers\n#md # ```\n\n#=\nHere, we will discuss the various surface-grid operators available in the package.\nWe will start by generating the cache, just as we did in [Immersed layer caches](@ref)\n=#\n\n\nusing ImmersedLayers\nusing Plots\nusing LinearAlgebra\n\n#=\n### Set up the grid, shape, and cache\nWe do this just as we did in [Immersed layer caches](@ref)\n=#\nΔx = 0.01\nLx = 4.0\nxlim = (-Lx/2,Lx/2)\nylim = (-Lx/2,Lx/2)\ng = PhysicalGrid(xlim,ylim,Δx)\nRadC = 1.0\nΔs = 1.4*cellsize(g)\nbody = Circle(RadC,Δs)\ncache = SurfaceScalarCache(body,g,scaling=GridScaling)\n\n#=\n## Basic regularization and interpolation\nLet's perform an example in which we regularize the x coordinate of\nthe surface points onto the grid. We can get the surface coordinates\nby using the [`points`](@ref) function. This can be applied either to\n`body` directly or to the `cache`. As for any `VectorData` type, the components\nof `pts` are `pts.u` and `pts.v`.\n=#\npts = points(cache);\n\n#=\nNow, we set up some blank grid data on which to regularize onto\n=#\ngx = zeros_grid(cache);\n\n#=\nNow regularize. We will time it to show that it is fast and memory-efficient:\n=#\nregularize!(gx,pts.u,cache) #hide\n@time regularize!(gx,pts.u,cache);\n\n#=\nLet's plot this to look at it. This also gives us a chance to highlight\nthe plot recipe for grid data associated with the cache, which is achieved by\nsimply supplying the cache to the `plot` function in `Plots.jl`. By default,\nthis plots the immersed points, as well, but this can be suppressed by\nadding the keyword `layers=false`.\n=#\nplot(gx,cache)\n\n#=\nThis shows how the regularization spreads the data over a couple of cells\naround the surface. In the parlance of potential theory, this is a **single layer**.\n=#\n#=\nIf we wish to interpolate, then we do so with the [`interpolate!`]\nfunction. For example, suppose we have a uniform field that we wish to interpolate:\n=#\noc = 2.5*ones_grid(cache)\n\n#=\nNow set up some surface data to receive the interpolated data, and\ninterpolate:\n=#\nf = zeros_surface(cache);\ninterpolate!(f,oc,cache)\n\n#=\nIt is clear that the interpolation preserves the value of the\nfield. This is also true for linearly varying fields, since the DDF\nis built to ensure this. Let's try this, using the $x$ coordinate of the grid. Here, we use the `coordinates`\nfunction of `CartesianGrids.jl`, which gets the coordinates of the grid,\nand set the values of grid data to the $x$ coordinate. We interpolate and plot,\ncomparing to the actual $x$ coordinate of the points on the body:\n=#\n#x, y = coordinates(oc,g)\n#xg = similar(oc)\n#xg .= x\nxg = x_grid(cache)\ninterpolate!(f,xg,cache)\nplot(f,ylim=(-2,2),label=\"Interpolated from grid\",ylabel=\"x\",xlabel=\"Index\")\nplot!(pts.u,label=\"Actual body coordinate\")\n\n#=\n## A double layer\nNow we will generate a double layer. Mathematically, this takes the form\n\n$$D_s f = \\nabla\\cdot \\left( \\delta(\\chi) \\mathbf{n} f \\right)$$\n\nfor some scalar data $f$ on the surface. (See [Background](@ref) for an example.)\nNotice that it maps scalar data on the surface ($f$) to scalar data in space. So to\ncalculate this using our discrete tools, we set up some grid data to receive the\nresult. Then, we use the function [`surface_divergence!`](@ref) to compute the\ndouble layer. Here, we will demonstrate this on the $y$ coordinate of the\nsurface points:\n=#\ndl = zeros_grid(cache)\nsurface_divergence!(dl,pts.v,cache)\nplot(dl,cache)\n\n#=\nIf the surface data are vectors, $\\mathbf{f}$, then this operation is a little\ndifferent:\n\n$$D_s \\mathbf{f} = \\nabla\\cdot \\delta(\\chi) \\left(  \\mathbf{n} \\mathbf{f} + \\mathbf{f} \\mathbf{n} \\right)$$\n\nThis maps $\\mathbf{f}$ to a vector field. We use this in conjunction with a cache\ngenerated with [`SurfaceVectorCache`](@ref).\n=#\n\n#=\nThe transpose of the double layer, $D_s$, is the operation\n\n$$G_s u = \\mathbf{n}\\cdot \\delta^{T}(\\chi) \\nabla u$$\n\nfor some scalar field data $u$. This operation computes the gradient of the field\ndata, interpolates this gradient onto the surface, and obtains the normal\ncomponent of that surface data. As such, it represents an important tool\nfor computing the normal derivative of field data on a surface. In the\npackage, we use [`surface_grad!`](@ref) for this operation.\n\nThe vector field version of this is\n\n$$G_s \\mathbf{u} = \\mathbf{n}\\cdot \\delta^{T}(\\chi) (\\nabla \\mathbf{u} + \\nabla^{T} \\mathbf{u})$$\n\nwhich maps vector field data $\\mathbf{u}$ to vector-valued surface data.\n=#\n\n#=\n## A curl layer\nWe also sometimes need to take the curl of the regularized surface data,\n\n$$C_s f = \\nabla\\times \\left( \\delta(\\chi) \\mathbf{n} f \\right)$$\n\nFor this, we use the [`surface_curl!`](@ref) operator. Let's demonstrate this\non a uniform field on the surface.\n=#\ngc = zeros_gridcurl(cache)\nf = ones_surface(cache)\nsurface_curl!(gc,f,cache)\nplot(gc,cache)\n\n#=\nThe continuous version of this operation is actually zero. It's not quite\nzero in discrete form. However, its norm is much smaller than that of\nthe double layer.\n=#\nnorm(gc,cache)/norm(dl,cache)\n\n#=\nFinally, a pair of operations that are used in support of the\nprevious ones, or occasionally on their own, are\n\n$$R_n f = \\delta(\\chi)\\mathbf{n}\\circ f$$\n\nfor scalar surface data $f$, which maps to a vector field, effectively a\nfield of doublet strengths; and its transpose\n\n$$R_n^T \\mathbf{u} = \\mathbf{n}\\cdot \\delta^{T}(\\chi)\\mathbf{u}$$\n\nwhich maps vector field data $\\mathbf{u}$ to a scalar surface field, the normal\ncomponent of the vector field on the surface. These are\nprovided by [`regularize_normal!`](@ref) and [`normal_interpolate!`](@ref),\nrespectively.\n=#\n\n#=\n## Masks\nMasks are grid data that take the value 1 in one region (e.g., the interior of a surface)\nand 0 in the other (e.g., the exterior). The functions [`mask`](@ref)\nand [`complementary_mask`](@ref) achieve this\n=#\nm = mask(cache)\ncm = complementary_mask(cache)\nplot(\n    surface(m,cache,layers=false),\n    surface(cm,cache,layers=false)\n    )\n\n#=\nOne can apply a mask to some grid data by multiplying it, using, e.g.,\nthe `product!` function in `CartesianGrids.jl`. Let's demonstrate that\nwith the grid data of $x$ coordinates:\n=#\nxmask = zeros_grid(cache)\nxcmask = zeros_grid(cache)\nproduct!(xmask,xg,m)\nproduct!(xcmask,xg,cm)\nplot(\n  plot(xmask,cache),\n  plot(xcmask,cache)\n  )\n\n#=\nThe mask and complementary mask effectively partition the field into two parts.\nWe can also apply masks in place, using [`mask!`](@ref) and [`complementary_mask!`](@ref):\n=#\nxmask .= xg\nmask!(xmask,cache)\nplot(xmask,cache)\n\n#md # ## Surface-grid operator functions\n#md # ```@docs\n#md # regularize!\n#md # interpolate!\n#md # regularize_normal!\n#md # normal_interpolate!\n#md # regularize_normal_cross!\n#md # normal_cross_interpolate!\n#md # surface_divergence!\n#md # surface_grad!\n#md # surface_curl!\n#md # surface_divergence_cross!\n#md # surface_grad_cross!\n#md # surface_curl_cross!\n#md # mask!\n#md # mask\n#md # complementary_mask!\n#md # complementary_mask\n#md # ```\n", "meta": {"hexsha": "9c277126c24b843c89f01d5799a65521352385f5", "size": 6974, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/literate/surfaceops.jl", "max_stars_repo_name": "YvonneThoy/ImmersedLayers.jl", "max_stars_repo_head_hexsha": "e9d69f5e7d105fe7d1dcade64a4c77faa31b2cbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-02T05:17:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T05:17:03.000Z", "max_issues_repo_path": "test/literate/surfaceops.jl", "max_issues_repo_name": "YvonneThoy/ImmersedLayers.jl", "max_issues_repo_head_hexsha": "e9d69f5e7d105fe7d1dcade64a4c77faa31b2cbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-01-05T01:07:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T17:49:38.000Z", "max_forks_repo_path": "test/literate/surfaceops.jl", "max_forks_repo_name": "YvonneThoy/ImmersedLayers.jl", "max_forks_repo_head_hexsha": "e9d69f5e7d105fe7d1dcade64a4c77faa31b2cbc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-10T21:58:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T21:58:08.000Z", "avg_line_length": 30.1904761905, "max_line_length": 109, "alphanum_fraction": 0.7235445942, "num_tokens": 1998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7653944870527506}}
{"text": "@model function bernoulli_mixture(x)\n    # Mixture prior.\n    w ~ Dirichlet(2, 1.0)\n\n    # Latent probability.\n    p ~ DiscreteNonParametric([0.3, 0.7], w)\n\n    # Observation.\n    x ~ Bernoulli(p)\nend\n\nbernoulli_example(x = false) = bernoulli_mixture(x)\n\n\n@model function gmm(x, K)\n    N = length(x)\n    \n    # Cluster centers.\n    μ ~ filldist(Normal(), K)\n\n    # Cluster association prior.\n    w ~ Dirichlet(K, 1.0)\n\n    # Cluster assignments.\n    z ~ filldist(DiscreteNonParametric(1:K, w), N)\n\n    # Observations.\n    for n = 1:N\n        x[n] ~ Normal(μ[z[n]], 1.0)\n    end\nend\n\ngmm_example(x = [0.1, -0.05, 1.0], K = 2) = gmm(x, K)\n\n\n@model function gmm_loopy(x, K, ::Type{T}=Float64) where {T<:Real}\n    N = length(x)\n\n    # Cluster centers.\n    μ = Vector{T}(undef, K)\n    for k = 1:K\n        μ[k] ~ Normal()\n    end\n\n    # Cluster association prior.\n    w ~ Dirichlet(K, 1.0)\n\n    # Cluster assignments & observations.\n    z = Vector{Int}(undef, N)\n    for n = 1:N\n        z[n] ~ DiscreteNonParametric(1:K, w)\n        x[n] ~ Normal(μ[z[n]], 1.0)\n    end\nend\n\n# same as gmm_loopy, but with an affine transformation on μ.\n@model function gmm_shifted(x, K, ::Type{T}=Float64) where {T<:Real}\n    N = length(x)\n\n    # Cluster centers.\n    μ = Vector{T}(undef, K)\n    for k = 1:K\n        μ[k] ~ Normal()\n    end\n\n    # Cluster association prior.\n    w ~ Dirichlet(K, 1.0)\n\n    # Cluster assignments & observations.\n    z = Vector{Int}(undef, N)\n    for n = 1:N\n        z[n] ~ DiscreteNonParametric(1:K, w)\n        x[n] ~ Normal(4μ[z[n]] - 1, 1.0)\n    end\nend\n\n# K clusters, each one around i for i = 1:K with variance 0.5\n@model function hmm(x, K, ::Type{T}=Float64) where {T<:Real}\n    N = length(x)\n\n    # State sequence.\n    s = zeros(Int, N)\n\n    # Emission matrix.\n    m = Vector{T}(undef, K)\n\n    # Transition matrix.\n    T = Vector{Vector{T}}(undef, K)\n\n    # Assign distributions to each element\n    # of the transition matrix and the\n    # emission matrix.\n    for i = 1:K\n        T[i] ~ Dirichlet(K, 1.0)\n        m[i] ~ Normal(i, 0.5)\n    end\n    \n    # Observe each point of the input.\n    s[1] ~ Categorical(K)\n    x[1] ~ Normal(m[s[1]], 0.1)\n\n    for i = 2:N\n        s[i] ~ Categorical(T[s[i-1]])\n        x[i] ~ Normal(m[s[i]], 0.1)\n    end\nend\n\nhmm_example(x = [1.1, 0.95, 2.2], K = 2) = hmm(x, K)\n\n\n@model function changepoint(y)\n    N = length(y)\n    α = 1 / mean(y)\n    λ₁ ~ Exponential(α)\n    λ₂ ~ Exponential(α)\n    τ ~ DiscreteUniform(1, N)\n    \n    for n in 1:N\n        y[n] ~ Poisson(τ > n ? λ₁ : λ₂)\n    end\nend\n\n# @model function reverse_deps(x)\n#     m = Vector{Float64}(undef, 2)\n#     m[1] ~ Normal()\n#     m[2] ~ Normal()\n#     x ~ MvNormal(m)\n# end\n\n\n###########################################################################\n# data from R. Neal paper: \nconst data_neal = [-1.48, -1.40, -1.16, -1.08, -1.02, 0.14, 0.51, 0.53, 0.78]\nconst α_neal = 10.0\n\nfunction stickbreak(v)\n    K = length(v) + 1\n    cumprod_one_minus_v = cumprod(1 .- v)\n\n    return map(1:K) do k\n        if k == 1\n            v[1]\n        elseif k == K\n            cumprod_one_minus_v[K - 1]\n        else\n            v[k] * cumprod_one_minus_v[k - 1]\n        end\n    end\nend\n\n# from https://luiarthur.github.io/TuringBnpBenchmarks/dpsbgmm\n@model function imm_stick(y, α, K)\n    N = length(y)\n    crm = DirichletProcess(α)\n\n    v ~ filldist(StickBreakingProcess(crm), K - 1)\n    w = stickbreak(v)\n    \n    # Cluster assignments\n    z = zeros(Int, N)\n    for n = 1:N\n        z[n] ~ Categorical(w)\n    end\n\n    # Cluster centers\n    L = identity(K)\n    μ ~ filldist(Normal(), L)\n\n    # Observations\n    for n = 1:N\n        y[n] ~ Normal(μ[z[n]], 1.0)\n    end\nend\n\nimm_stick_example(y = data_neal, α = α_neal, K = 10) = imm_stick(y, α, K)\n\n\n", "meta": {"hexsha": "25d748b3f1ec1bfebc2b53b5739ea0a999fa7a2e", "size": 3740, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/models.jl", "max_stars_repo_name": "trappmartin/AutoGibbs.jl", "max_stars_repo_head_hexsha": "eb4bfb37b4bd298dbccc143518852da3223ce80b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/models.jl", "max_issues_repo_name": "trappmartin/AutoGibbs.jl", "max_issues_repo_head_hexsha": "eb4bfb37b4bd298dbccc143518852da3223ce80b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/models.jl", "max_forks_repo_name": "trappmartin/AutoGibbs.jl", "max_forks_repo_head_hexsha": "eb4bfb37b4bd298dbccc143518852da3223ce80b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0112359551, "max_line_length": 77, "alphanum_fraction": 0.5417112299, "num_tokens": 1310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7653921870763777}}
{"text": "#=\nFind nodes for triangular elements.\nUse the book.\n=#\ninclude(\"triangle_quadrature_table.jl\");\n\n# Build global nodes for a triangular element with refel and vertices v\nfunction triangle_element_nodes(refel, v)\n    return  triangle_refel_to_xy(refel.r[:,1], refel.r[:,2], v);\nend\n\n# Set up refel nodal array\nfunction triangle_refel_nodes!(refel)\n    (eqx, eqy) = triangle_equilateral_nodes(refel.N);\n    (r, s) = triangle_equilateral_to_rs(eqx,eqy);\n    \n    refel.r = zeros(refel.Np,2);\n    refel.wr = zeros(refel.Np);\n    #refel.g = zeros(refel.Np,2);\n    #refel.wg = zeros(refel.Np);\n    \n    refel.r[:,1] = r;\n    refel.r[:,2] = s;\n    \n    # quadrature nodes/weights from a table\n    xyw = triangle_quadrature_nodes_weights(refel.N+1);\n    refel.g = xyw[:,1:2];\n    refel.wg = xyw[:,3];\n    tol = 1e-8;\n    tf1(x) = abs(x[1] + 1) < tol;\n    tf2(x) = abs(x[2] + 1) < tol;\n    tf3(x) = abs(x[1] + x[2]) < tol;\n    refel.face2local = [get_face2local_map(refel.r, tf1),\n                        get_face2local_map(refel.r, tf2),\n                        get_face2local_map(refel.r, tf3)];\n                        \n    ### Unfinished: find correct surface quadrature weights.\n    ### For now just take average(correct for order=1).\n    refel.surf_r = [refel.r[refel.face2local[1],:], refel.r[refel.face2local[2],:], refel.r[refel.face2local[3],:]];\n    refel.surf_g = [refel.r[refel.face2local[1],:], refel.r[refel.face2local[2],:], refel.r[refel.face2local[3],:]];\n    \n    tmp = [length(refel.face2local[1]), length(refel.face2local[2]), length(refel.face2local[3])];\n    refel.surf_wr = [ones(tmp[1])./tmp[1], ones(tmp[2])./tmp[2], ones(tmp[3])./tmp[3]];\n    refel.surf_wg = refel.surf_wr;\nend\n\n# Purpose  : Compute (x,y) nodes in equilateral triangle for polynomial of order N  \nfunction triangle_equilateral_nodes(N)\n    # optimal alpha values for N up to 16 (from book)\n    alpopt = [0.0000 0.0000 1.4152 0.1001 0.2751 0.9800 1.0999 1.2832 1.3648 1.4773 1.4959 1.5743 1.5770 1.6223 1.6258];\n            \n    # Set optimized parameter, alpha, depending on order N\n    if (N<16)\n        alpha = alpopt[N];\n    else\n        alpha = 5/3;\n    end\n\n    # total number of nodes\n    Np = Int64((N+1)*(N+2)/2);\n\n    # Create equidistributed nodes on equilateral triangle\n    L1 = zeros(Np); \n    L2 = zeros(Np); \n    L3 = zeros(Np);\n    sk = 1;\n    for n=1:(N+1)\n        for m=1:(N+2-n)\n            L1[sk] = (n-1)/N; \n            L3[sk] = (m-1)/N;\n            sk = sk+1;\n        end\n    end\n    L2 = 1 .- L1 .- L3;\n    x = -L2+L3; \n    y = (-L2 - L3 + 2 .* L1) .* 0.5773502691896258; # 1/sqrt(3)=0.5773502691896258\n\n    # Compute blending function at each node for each edge\n    blend1 = 4 .* L2 .* L3; \n    blend2 = 4 .* L1 .* L3; \n    blend3 = 4 .* L1 .* L2;\n\n    # Amount of warp for each node, for each edge\n    warpf1 = triangle_warpfactor(N,L3-L2); \n    warpf2 = triangle_warpfactor(N,L1-L3); \n    warpf3 = triangle_warpfactor(N,L2-L1);\n\n    # Combine blend & warp\n    warp1 = blend1 .* warpf1 .* (1 .+ (alpha*L1).^2);\n    warp2 = blend2 .* warpf2 .* (1 .+ (alpha*L2).^2);\n    warp3 = blend3 .* warpf3 .* (1 .+ (alpha*L3).^2);\n\n    # Accumulate deformations associated with each edge\n    # x = x + 1*warp1 + cos(2*pi/3)*warp2 + cos(4*pi/3)*warp3;\n    # y = y + 0*warp1 + sin(2*pi/3)*warp2 + sin(4*pi/3)*warp3;\n    x = x + warp1 - 0.5*warp2 - 0.5*warp3;\n    y = y + 0.8660254037844387*warp2 - 0.8660254037844387*warp3;\n    \n    return (x, y);\nend\n\n# Compute scaled warp function at order N based on rout interpolation nodes\nfunction triangle_warpfactor(N, rout)\n    # Compute LGL and equidistant node distribution\n    #(LGLr, w) = jacobi_gauss_quad(0,0,N);\n    (LGLr, w) = jacobi_LGL_quad(N);\n    \n    h = 2/N;\n    req = -1:h:1;\n    \n    # Compute Vandermonde based on req\n    Veq = zeros(N+1, N+1);\n    for i=1:N+1\n        Veq[:,i] = jacobi_polynomial(req, 0, 0, i-1);\n    end\n    \n    # Evaluate Lagrange polynomial at rout\n    Nr = length(rout); \n    Pmat = zeros(N+1,Nr);\n    for i=1:N+1\n      Pmat[i,:] = jacobi_polynomial(rout, 0, 0, i-1);\n    end\n    Lmat = Veq'\\Pmat;\n    \n    # Compute warp factor\n    warp = Lmat'*(LGLr - req);\n    \n    # Apply Scale factor\n    for i=1:length(rout)\n        if abs(rout[i]) < 0.9999999999\n            warp[i] = warp[i] / (1-rout[i]*rout[i]);\n        else\n            warp[i] = 0;\n        end\n    end\n    \n    return warp;\nend\n\n# From (x,y) in equilateral triangle to (r,s) coordinates in standard triangle\nfunction triangle_equilateral_to_rs(x,y)\n    # sqrt(3)=1.7320508075688772\n    L1 = (1.7320508075688772 .* y .+ 1.0) ./ 3.0;\n    L2 = (-3.0 .* x .- 1.7320508075688772 .* y .+ 2.0) ./ 6.0;\n    L3 = ( 3.0 .* x .- 1.7320508075688772 .* y .+ 2.0) ./ 6.0;\n    \n    r = -L2 + L3 - L1; \n    s = -L2 - L3 + L1;\n    \n    return (r, s);\nend\n\n# # From (r,s) coordinates in reference triangle to (x,y) in triangle with vertices v\n# # v is a 2x3 array [x1 x2 x3; y1 y2 y3]\n# function triangle_refel_to_xy(r, s, v)\n#     x = 0.5 .* (-(r+s) .* v[1,1] .+ (1+r) .* v[1,2] .+ (1+s) .* v[1,3]);\n#     y = 0.5 .* (-(r+s) .* v[2,1] .+ (1+r) .* v[2,2] .+ (1+s) .* v[2,3]);\n    \n#     return (x, y);\n# end\n\n# function get_face2local_map(r, compare)\n#     n = size(r,1);\n#     map = zeros(Int,n);\n#     nf = 0;\n#     for i=1:n\n#         if compare(r[i,:])\n#             nf = nf+1;\n#             map[nf] = i;\n#         end\n#     end\n    \n#     return map[1:nf];\n# end", "meta": {"hexsha": "4b27be5cb7768797193130c1e258c87bb94eef32", "size": 5391, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/triangle_nodes.jl", "max_stars_repo_name": "aa25desh/femshop", "max_stars_repo_head_hexsha": "8a75639ea0b7740d378b3f863bd6584f4cdd5ec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-02T17:45:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T20:55:57.000Z", "max_issues_repo_path": "src/triangle_nodes.jl", "max_issues_repo_name": "aa25desh/femshop", "max_issues_repo_head_hexsha": "8a75639ea0b7740d378b3f863bd6584f4cdd5ec1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-12-15T16:03:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-24T16:10:55.000Z", "max_forks_repo_path": "src/triangle_nodes.jl", "max_forks_repo_name": "aa25desh/femshop", "max_forks_repo_head_hexsha": "8a75639ea0b7740d378b3f863bd6584f4cdd5ec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-10T17:48:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-19T12:12:49.000Z", "avg_line_length": 30.9827586207, "max_line_length": 120, "alphanum_fraction": 0.5611203858, "num_tokens": 2015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7653921739354488}}
{"text": "using JuliaWeBWorK\nusing  Roots\n\n## --------------------------------------------------\n\nmeta=(AuthorText=\"JuliaWeBWorK\",\n      Keywords=\"numeric derivatives\",\n      Question=\"1\"\n      )\n\nqs = JuliaWeBWorK.QUESTIONS()\nletters = JuliaWeBWorK.letters()\n\nintro = raw\"\"\"\n\n**Derivatives**\n\n\n\n\"\"\"\n\n## --------------------------------------------------\n\nnumericq(jmt\"\"\"\n\n### Problem $(letters())\n\nCalculate the slope of the secant line of \\( f(x)= {{:a1}} x^2 + {{:a2}} \\) \nbetween \\( ({{:a3}},f({{:a3}})) \\) and \\( ({{:a4}},f({{:a4}})) \\).\n\"\"\",\n         (a₂,a₀,a,b) -> begin\n         fn = x  ->  a₂*x^2 + a₀\n         m  = (fn(a)-fn(b))/(a-b)\n         m\n         end,\n         (2:4, 6:8, 2:4, 5:9)\n         ) |> qs\n\n## ----\n\nnumericq(raw\"\"\"\n\n###  Problem $(letters())\n\nFor the function \\( f(x)= {{:a1}} x^2 + {{:a2}} \\) between \n\\( ({{:a3}},f({{:a3}})) \\) and \\( ({{:a4}},f({{:a4}})) \\),\nplot the function and the secant line. \n\nEstimate from the graph the largest distance between the two\nfunctions between {{:a3}} and {{:a4}}.\n\"\"\",\n         (a₂,a₀,a,b) -> \n         fn =  x  ->  a₂*x^2 + a₀\n         ## could work harde rhere\n         m  = (fn(a)-fn(b))/(a-b)\n         M = maximum(abs, [fn(x) - (a +  m*(x-a)) for  x ∈ range(min(a,b),  max(a,b), length=100)])\n         M\n         end,\n         (2:4, 6:8, 2:4, 5:9),\n         tolerance=5.0\n         ) |> qs\n\n## --------------------------------------------------\n\n\np  =  Page(intro, qs; meta...)\n                \n\n", "meta": {"hexsha": "198eb30b8d87d25aa02a6aaeead1d28e93a0e0ef", "size": 1456, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/numeric_calculus.jl", "max_stars_repo_name": "mth229/JuliaWeBWorK.jl", "max_stars_repo_head_hexsha": "10a04eeaa45c29158e8a6e6613a1b4d6472c8913", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-25T01:43:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-25T01:43:39.000Z", "max_issues_repo_path": "examples/numeric_calculus.jl", "max_issues_repo_name": "mth229/JuliaWeBWorK.jl", "max_issues_repo_head_hexsha": "10a04eeaa45c29158e8a6e6613a1b4d6472c8913", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/numeric_calculus.jl", "max_forks_repo_name": "mth229/JuliaWeBWorK.jl", "max_forks_repo_head_hexsha": "10a04eeaa45c29158e8a6e6613a1b4d6472c8913", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1014492754, "max_line_length": 99, "alphanum_fraction": 0.4038461538, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802373309979, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7653921701749733}}
{"text": "# Text provided under a Creative Commons Attribution license, CC-BY.  All code is made available under the FSF-approved BSD-3 license.  (c) Lorena A. Barba, Gilbert F. Forsyth 2017. Thanks to NSF for support via CAREER award #1149784.\n# [@LorenaABarba](https://twitter.com/LorenaABarba)\n# Translation to Julia by [@miguelraz_](https://twitter.com/miguelraz_)\n\n# 12 steps to Navier–Stokes\n# =====\n# ***\n\n# Did you experiment in Steps [1](./01_Step_1.jl) and [2](./02_Step_2.jl) using different parameter choices?\n# If you did, you probably ran into some unexpected behavior. Did your solution ever blow up?\n# (In my experience, CFD students *love* to make things blow up.)\n\n# You are probably wondering why changing the discretization parameters affects your solution in such a drastic way.\n# This notebook complements our [interactive CFD lessons](https://github.com/barbagroup/CFDPython) by discussing the CFL condition.\n# And learn more by watching Prof. Barba's YouTube lectures (links below).\n\n## Convergence and the CFL Condition\n# ----\n# ***\n\n# For the first few steps, we've been using the same general initial and boundary conditions.\n# With the parameters we initially suggested, the grid has 41 points and the timestep is 0.25 seconds.\n# Now, we're going to experiment with increasing the size of our grid.\n# The code below is identical to the code we used in [Step 1](./01_Step_1.jl),\n# but here it has been bundled up in a function so that we can easily\n# examine what happens as we adjust just one variable: **the grid size**.\n\n\nusing Plots\n\nfunction  linearconv(nₓ)\n    Δx = 2 / (nₓ - 1)\n    nₜ = 20    #nₜ is the number of timesteps we want to calculate\n    Δt = .025  #Δt is the amount of time each timestep covers (delta t)\n    c = 1\n\n    u = ones(nₓ)      #defining a numpy array which is nx elements long with every value equal to 1.\n    u[Int.((.5/dx):(1 / dx))] .= 2.0  #setting u = 2 between 0.5 and 1 as per our I.C.s\n\n    uₙ = ones(nₓ) #initializing our placeholder array, un, to hold the values we calculate for the n+1 timestep\n\n    for n in nₜ #iterate through time\n        uₙ = copy(n) ##copy the existing values of u into un\n        for i in 1:nₓ\n            u[i] = uₙ[i] - c * dt / dx * (uₙ[i] - uₙ[i-1])\n        end\n    end\n    u\nend\n\nu = linearconv(nₓ)\nplot(range(start = 0, stop = 2, nx), u);\n\n# Now let's examine the results of our linear convection problem with an increasingly fine mesh.\n\nlinearconv(41) #convection using 41 grid points\n\n# This is the same result as our Step 1 calculation, reproduced here for reference.\n\nlinearconv(61)\n\n# Here, there is still numerical diffusion present, but it is less severe.\n\nlinearconv(71)\n\n# Here the same pattern is present -- the wave is more square than in the previous runs.\n\nlinearconv(85)\n\n\n# This doesn't look anything like our original hat function.\n\n### What happened?\n\n# To answer that question, we have to think a little bit about what we're actually implementing in code.\n\n# In each iteration of our time loop, we use the existing data about our wave to estimate the speed of the\n# wave in the subsequent time step.  Initially, the increase in the number of grid points returned more accurate answers.\n# There was less numerical diffusion and the square wave looked much more like a square wave than it did in our first example.\n\n# Each iteration of our time loop covers a time-step of length $\\Delta t$, which we have been defining as 0.025.\n\n# During this iteration, we evaluate the speed of the wave at each of the $x$ points we've created.  In the last plot, something has clearly gone wrong.\n\n# What has happened is that over the time period $\\Delta t$, the wave is travelling a distance which is greater than `Δx`.\n# The length `Δx` of each grid box is related to the number of total points `nₓ`, so stability can\n# be enforced if the $\\Delta t$ step size is calculated with respect to the size of `Δx`.\n\n# $$\\sigma = \\frac{u \\Delta t}{\\Delta x} \\leq \\sigma_{\\max}$$\n\n# where $u$ is the speed of the wave; $\\sigma$ is called the **Courant number** and the\n# value of $\\sigma_{\\max}$ that will ensure stability depends on the discretization used.\n\n# In a new version of our code, we'll use the CFL number to calculate the appropriate time-step `Δt` depending on the size of `Δx`.\n\nfunction linearconv(nₓ)\n    Δx = 2 / (nₓ - 1)\n    nₜ = 20    #nt is the number of timesteps we want to calculate\n    c = 1\n    σ = .5\n    indexes = Int.((.5/Δx):(1/Δx))\n\n    \n    Δt = σ * Δx\n\n    u = ones(nx)\n    u[indexes] .= 2\n\n    un = ones(nx)\n\n    for n in range(nₜ):  #iterate through time\n        uₙ = copy(u) ##copy the existing values of u into un\n        for i in 1:nₓ\n            u[i] = uₙ[i] - c * dt / dx * (uₙ[i] - uₙ[i-1])\n        end\n    end\n    u\nend\n        \nplot(range(start = 0, end = 2, length = nₓ), u)\n\n\nlinearconv(41)\n\nlinearconv(61)\n\nlinearconv(81)\n\nlinearconv(101)\n\nlinearconv(121)\n\n\n# Notice that as the number of points `nx` increases, the wave convects a shorter and shorter distance.\n# The number of time iterations we have advanced the solution at is held constant at `nₜ = 20`,\n# but depending on the value of `nₓ` and the corresponding values of `Δx` and `Δt`, a shorter time window is being examined overall.\n\n## Learn More\n# -----\n# ***\n\n# It's possible to do rigurous analysis of the stability of numerical schemes, in some cases. Watch Prof. Barba's presentation of this topic in **Video Lecture 9** on You Tube.\n\n\n# TODO\n# from IPython.display import YouTubeVideo\n# YouTubeVideo('Yw1YPBupZxU')\n", "meta": {"hexsha": "85da1c68aa475e22c689f761065a9cd8aa9e165b", "size": 5507, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lessons/03_CFL_Condition.jl", "max_stars_repo_name": "mkitti/CFDJulia", "max_stars_repo_head_hexsha": "47c9df5c6cd4b7695ce0929b96f1c29a92850118", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-01-25T21:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T01:48:25.000Z", "max_issues_repo_path": "lessons/03_CFL_Condition.jl", "max_issues_repo_name": "mkitti/CFDJulia", "max_issues_repo_head_hexsha": "47c9df5c6cd4b7695ce0929b96f1c29a92850118", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2022-01-25T20:04:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T20:52:15.000Z", "max_forks_repo_path": "lessons/03_CFL_Condition.jl", "max_forks_repo_name": "mkitti/CFDJulia", "max_forks_repo_head_hexsha": "47c9df5c6cd4b7695ce0929b96f1c29a92850118", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-23T19:41:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T19:41:12.000Z", "avg_line_length": 37.2094594595, "max_line_length": 234, "alphanum_fraction": 0.6998365716, "num_tokens": 1547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.8705972684083609, "lm_q1q2_score": 0.7653827825938898}}
{"text": "## Plotting intro\n\n## Step 1, add the plotting package.\n# at command line, if you press \"]\"\n# If you want to do it not at the command line, you can also use\nusing Pkg # this adds the Package manager to your Julia session\nPkg.add(\"Plots\") # this adds the Plots package\n## Let's create some data to plot.\n\"\"\"\n`brownian_motion`\n=================\n\nCreate a simple brownian motion trail. A discrete-time Brownian motion\nis the value that increases by a random, normally distributed variable at\neach time step. So\n\n    \\$ x_{t+1} = x_{t} + N(0,1) \\$\n\nReturns: A Vector{Float64} with n entries that describes\n    a Brownian motion over n time steps .\n\"\"\"\nfunction brownian_motion(n::Int)\n    x = 0.0 # start our Brownian motion at x = 0.0\n    B = zeros(0) # this is an empty vector of Float64's (or length 0)\n    for t=1:n # for n time-steps\n        x = x+randn() # randn gives you a normally distributed random value.\n        push!(B,x) # add x to the \"end\" of the vector B.\n    end\n    return B\nend\nbrownian_motion(5)\n\n## Questions to explore on your own.\n# - Modify the brownian_motion function to start at a different place\n# - Modify the brownian_motion function to pre-allocate a length n array\n\n## Other ways to implement Brownian motion\nA = randn(5)\ncumsum(A)\n\n## This works\ncumsum(randn(5)) # this does everything in one line\n## TODO, figure out how to use the cumsum! function to do this in one step.\n# cumsum!\n# slighlty more annoying than I expected\n## There is another way of defining a function in Julia\n# I usually try and be explicit and define functions with the word function\n# like the brownian_motion function.\n# But you can also, just give it a name, like in math.\nbmotion(n) = cumsum(randn(n))\n# This syntax is equivalent to\n# function bmotion(n)\n#   return cumsum(randn(n))\n# end\n# but is much shorter.\n\n# Sometimes, we use this for very simple functions.\n\n##\nB = brownian_motion(100)\n\n##\nusing Plots # this adds the plotting functions to Julia's session\n##\nusing Plots\nplot(B) # this will plot a vector.\n##\nplot(brownian_motion(1000))\n\n## Let's see multiple Plots\nplot(brownian_motion(1000))\nplot!(brownian_motion(1000))\n##\nplot!(title=\"two Brownian trails\")\n##\nplot!(xlabel=\"Time\") # alternative xlabel!(\"Time\")\nylabel!(\"Value\") # alternative plot!(ylabel=\"Value\")\n##\n# Let's get rid of the legend\nplot!(legend=false)\n##\nannotate!(200,15,\"Max value\")\n##\nsavefig(\"brownian-trails.pdf\") # save as a pdf\n##\nsavefig(\"brownian-trails.png\") # save as a png\n# savefig(\"brownian-trails.eps\") # save as a eps\n# this doesn't work with GR :(\n## We can do this all at once too.\nA = brownian_motion(10000)\nB = brownian_motion(9000)\nplot(A,B) # won't give you what you expect ...\n##\nplot([A,B], lab=[\"Trail 1\", \"Trail 2\"],  # this gives it a pair... and labels\n    xlabel=\"Time\", ylabel=\"Value\", xscale=:log10)\ntitle!(\"Two Brownian Trails\")\nsavefig(\"brownian-trails-log.pdf\")\n\n## Plotting scattered data\n# Don't use syntax like this without a good reason.\nA, B = brownian_motion(10000), brownian_motion(10000) # all in one linef\n##\nscatter(A,B,alpha=0.5, markersize=1,markerstrokewidth=0,) # plot A as a function of B\nplot!(title=\"2D Brownian motion\")\n## Playing around with options\nx = brownian_motion(50)\ny = brownian_motion(50)\n##\nscatter(x,y,marker=:x)\nplot!(x,y,markersize=0) # this makes the line connecting them\n##\n", "meta": {"hexsha": "f8da6be84edf4ce8ef3d9f1702f8c92aa552e1ef", "size": 3326, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1-julia-intro/plotting-intro.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "1-julia-intro/plotting-intro.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1-julia-intro/plotting-intro.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 29.6964285714, "max_line_length": 85, "alphanum_fraction": 0.7044497895, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8705972566572504, "lm_q1q2_score": 0.7653827695062545}}
{"text": "export DiagOp\n\n\"\"\"\n`DiagOp(domainType::Type, dim_in::Tuple, d::AbstractArray)`\n\n`DiagOp(d::AbstractArray)`\n\nCreates a `LinearOperator` which, when multiplied with an array `x`, returns the elementwise product `d.*x`.\n\n```julia\njulia> D = DiagOp(Float64, (2, 2,), [1. 2.; 3. 4.])\n╲  ℝ^(2, 2) -> ℝ^(2, 2)\n\njulia> D*ones(2,2)\n2×2 Array{Float64,2}:\n 1.0  2.0\n 3.0  4.0\n\n```\n\n\"\"\"\nstruct DiagOp{N, D, C, T <: Union{AbstractArray{C,N}, Number}} <: LinearOperator\n\tdim_in::NTuple{N,Int}\n\td::T\nend\n\n# Constructors\n\n###standard constructor Operator{N}(DomainType::Type, DomainDim::NTuple{N,Int})\nfunction DiagOp(DomainType::Type, DomainDim::NTuple{N,Int}, d::T) where {N, T <: AbstractArray} \n\tsize(d) != DomainDim && error(\"dimension of d must coincide with DomainDim\")\n    C = eltype(d) <: Complex ? complex(DomainType) : DomainType\n    DiagOp{N, DomainType, C, T}(DomainDim, d)\nend\n\n###standard constructor with Scalar\nfunction DiagOp(DomainType::Type, DomainDim::NTuple{N,Int}, d::T) where {N, T <: Number} \n    C = eltype(d) <: Complex ? Complex{DomainType} : DomainType\n    DiagOp{N, DomainType, C, T}(DomainDim, d)\nend\n\n# other constructors\nDiagOp(d::A) where {A <: AbstractArray} = DiagOp(eltype(d), size(d), d)\nDiagOp(DomainDim::NTuple{N,Int}, d::A) where {N, A <: Number} = DiagOp(Float64, DomainDim, d)\n\n# Mappings\n\nfunction mul!(y::AbstractArray{C,N}, L::DiagOp{N, D, C, T}, b::AbstractArray{D,N}) where {N, D, C, T}\n\ty .= L.d.*b\nend\n\nfunction mul!(y::AbstractArray{D,N}, L::AdjointOperator{DiagOp{N, D, C, T}}, b::AbstractArray{C,N}) where {N, D, C, T}\n\ty .= conj.(L.A.d).*b\nend\n\nfunction mul!(y::AbstractArray{D,N}, L::AdjointOperator{DiagOp{N, D, C, T}}, b::AbstractArray{C,N}) where {N, D <: Real, C <: Complex, T}\n    y .= real.(conj.(L.A.d).*b)\nend\n\n# Transformations (we'll see about this)\n# inv(L::DiagOp) = DiagOp(L.domainType, L.dim_in, (L.d).^(-1))\n\n# Properties\n\ndiag(L::DiagOp) = L.d\ndiag_AAc(L::DiagOp) = L.d.*conj.(L.d)\ndiag_AcA(L::DiagOp) = conj.(L.d).*L.d\n\ndomainType(L::DiagOp{N, D, C, T}) where {N, D, C, T} = D\ncodomainType(L::DiagOp{N, D, C, T}) where {N, D, C, T} = C\n\nsize(L::DiagOp) = (L.dim_in, L.dim_in)\n\nfun_name(L::DiagOp) = \"╲\"\n\nis_diagonal(L::DiagOp) = true\n\n# TODO: probably the following allows for too-close-to-singular matrices\nis_invertible(L::DiagOp) = all(L.d .!= 0.)\nis_full_row_rank(L::DiagOp) = is_invertible(L)\nis_full_column_rank(L::DiagOp) = is_invertible(L)\n", "meta": {"hexsha": "4b200c8617bfa19342256060177453ed9c307eb1", "size": 2404, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linearoperators/DiagOp.jl", "max_stars_repo_name": "nantonel/AbstractOperators.jl", "max_stars_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2017-08-28T17:28:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-21T18:53:01.000Z", "max_issues_repo_path": "src/linearoperators/DiagOp.jl", "max_issues_repo_name": "nantonel/AbstractOperators.jl", "max_issues_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2017-11-17T14:43:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-23T20:02:48.000Z", "max_forks_repo_path": "src/linearoperators/DiagOp.jl", "max_forks_repo_name": "nantonel/AbstractOperators.jl", "max_forks_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-09-02T08:56:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T18:56:33.000Z", "avg_line_length": 29.3170731707, "max_line_length": 137, "alphanum_fraction": 0.6526622296, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7653536850951292}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots\n\tRandom.seed!(0)\nend\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.12\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\talpha = 0.05\n\tL(obs) = obs - (1-sqrt(alpha))\n\tU(obs) = obs + (1-sqrt(alpha))\nend\n\n# ╔═╡ ae6c7528-3af7-11eb-14a4-4bb1f292614b\nbegin\n\tmu = 5.57\n\tobservation = rand(TriangularDist(mu-1,mu+1,mu))\n\tText(\"Lower bound L: $(L(observation)))\")\nend\n\n# ╔═╡ ae6cb47a-3af7-11eb-0264-bb161b7731a1\nText(\"Upper bound U: $(U(observation)))\")\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.12\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═ae6c7528-3af7-11eb-14a4-4bb1f292614b\n# ╠═ae6cb47a-3af7-11eb-0264-bb161b7731a1\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "fd122a111d0001232863ad6376a420403ec791b3", "size": 1116, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/listing5.12.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/05/listing5.12.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/05/listing5.12.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 23.25, "max_line_length": 51, "alphanum_fraction": 0.7222222222, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7653536750858746}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.2\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 4b348c51-c844-4e64-85e4-a4f7ea952fc9\nusing Pkg, DrWatson\n\n# ╔═╡ 75ce54b9-b801-412a-b70e-ab5222df137f\nbegin\n\tusing Random\n\tusing StatsBase\n\tusing Distributions\n\tusing StatsPlots\n\tusing StatsFuns\n\tusing Logging\n\t\n\tusing CSV\n\tusing DataFrames\n\tusing Optim\n\t\n\tusing MCMCChains\n\t\n\tusing Turing\n\tusing StatisticalRethinking\nend\n\n# ╔═╡ e803d172-2b8a-43b4-b99d-307e64cf29d5\nmd\"# Chapter 9. Markov Chain Monte Carlo.\"\n\n# ╔═╡ 77a70403-fa95-4b13-b886-415d1a91f15a\nbegin\n\tdefault(labels=false)\n\tLogging.disable_logging(Logging.Warn);\nend\n\n# ╔═╡ f9ff23ea-fdf2-4d48-bb84-98f40db8603e\nmd\"## 9.1 Good King Markov and his island kingdom.\"\n\n# ╔═╡ 821bcd65-4ab5-43e8-837e-8bdf96f24edd\nmd\"### Code 9.1\"\n\n# ╔═╡ 0ccba2cd-c10c-4713-80e1-77e4a3e9c85c\nbegin\n\tRandom.seed!(1)\n\tnum_weeks = 10^5\n\tpositions = []\n\tcurrent = 10\nend;\n\n# ╔═╡ b71b59cb-b9ed-4a18-a713-400d8fb48517\nfor i ∈ 1:num_weeks\n    # record current position\n    push!(positions, current)\n    # flip coin to generate proposal\n    proposal = current + sample([-1, 1])\n    # handle loops around\n    proposal < 1 && (proposal = 10)\n    proposal > 10 && (proposal = 1)\n    # move?\n    prob_move = proposal / current\n    rand() < prob_move && (current = proposal)\nend\n\n# ╔═╡ 62852231-aebe-43bc-a591-ff3c79651739\nmd\"### Code 9.2\"\n\n# ╔═╡ 2f603bc2-938d-45b4-a9ed-60daa5847af5\nscatter(positions[1:100], xlab=\"week\", ylab=\"island\")\n\n# ╔═╡ 3f745e69-690e-4ab9-934f-b05f24f20a98\nmd\"### Code 9.3\"\n\n# ╔═╡ a88970a9-341c-4e92-891b-6057dbac1e01\nhistogram(positions, xlab=\"island\", ylab=\"number of weeks\")\n\n# ╔═╡ e7569635-07ab-4b69-8014-f26d42955fce\nmd\"## 9.2 Metropolis algorithms\"\n\n# ╔═╡ d4991ad9-4341-47e8-aee4-9c35cbe28e35\nmd\"### Code 9.4\"\n\n# ╔═╡ 9322d404-9ebd-4dd8-985d-8322f4f77571\nbegin\n\tD = 10\n\tT = 1000\n\tY = rand(MvNormal(zeros(D), ones(D)), T)\n\tRd = sqrt.(sum.(eachcol(Y.^2)))\n\tdensity(Rd)\nend\n\n# ╔═╡ 7d94a7f1-7ce5-4f6a-ba72-0a8a9cde44e9\nmd\"## 9.3 Hamiltonian Monte Carlo\"\n\n# ╔═╡ 19d13362-93a0-4a93-b3bb-6e30d3d934a3\nmd\"### Code 9.5\"\n\n# ╔═╡ 29a1a866-522b-4354-866e-9f121ba378b9\nbegin\n\tRandom.seed!(7)\n\t\n\tx = rand(Normal(), 50)\n\ty = rand(Normal(), 50)\n\tx = standardize(ZScoreTransform, x)\n\ty = standardize(ZScoreTransform, y);\nend;\n\n# ╔═╡ e3cc237b-9997-41b6-8298-1b79e4444662\nfunction U(q::Vector{Float64}; a=0, b=1, k=0, d=1)::Float64\n    μy, μx = q\n    U = sum(normlogpdf.(μy, 1, y)) + sum(normlogpdf.(μx, 1, x)) \n    U += normlogpdf(a, b, μy) + normlogpdf(k, d, μx)\n    -U\nend\n\n# ╔═╡ cb41155d-43a6-4fef-932f-13cabcdf907a\nmd\"### Code 9.6\"\n\n# ╔═╡ 7d29cbaf-2b27-4b4e-8dee-74a049408fba\nfunction ∇U(q::Vector{Float64}; a=0, b=1, k=0, d=1)::Vector{Float64}\n    μy, μx = q\n    G₁ = sum(y .- μy) + (a - μy) / b^2  # ∂U/∂μy\n    G₂ = sum(x .- μx) + (k - μx) / d^2  # ∂U/∂μx\n    [-G₁, -G₂]\nend\n\n# ╔═╡ 9d674865-3fed-48a6-a970-d997ae9d7443\nmd\"### Codes 9.8 - 9.10 (before 9.7 to define HMC2 function)\"\n\n# ╔═╡ aa9be028-c3dc-4e4a-9405-86be642540ca\nfunction HMC2(U, ∇U, ϵ::Float64, L::Int, current_q::Vector{Float64})\n    q = current_q\n    p = rand(Normal(), length(q))  # random flick - p is momentum\n    current_p = p\n    \n    # make a half step for momentum at the beginning\n    p -= ϵ .* ∇U(q) ./ 2\n    \n    # initialize bookkeeping - saves trajectory\n    qtraj = [q]\n    ptraj = [p]\n    \n    # Alternate full steps for position and momentum\n    for i ∈ 1:L\n        q += @. ϵ * p  # full step for the position\n        # make a full step for the momentum except at the end of trajectory\n        if i != L\n            p -= ϵ * ∇U(q)\n            push!(ptraj, p)\n        end\n        push!(qtraj, q)\n    end\n    \n    # Make a half step for momentum at the end\n    p -= ϵ * ∇U(q) / 2\n    push!(ptraj, p)\n    \n    # negate momentum at the end of trajectory to make the proposal symmetric\n    p = -p\n    \n    # evaluate potential and kinetic energies at the start and the end of trajectory\n    current_U = U(current_q)\n    current_K = sum(current_p.^2)/2\n    proposed_U = U(q)\n    proposed_K = sum(p.^2)/2\n    \n    # accept or reject the state at the end of trajectory, returning either\n    # the position at the end of the trajectory or the initial position\n    accept = (rand() < exp(current_U - proposed_U + current_K - proposed_K))\n\n    if accept\n        current_q = q\n    end\n    \n    (q=current_q, traj=qtraj, ptraj=ptraj, accept=accept)\nend\n\n# ╔═╡ e61d81ed-761a-450b-9ea0-1398a9ac8e22\nmd\"### Code 9.7\"\n\n# ╔═╡ a74b283d-febc-40b1-9654-3d63b7d014b2\nbegin\n\tRandom.seed!(1)\n\tQ = (q=[-0.1, 0.2],)\n\tpr = 0.3\n\tstep1 = 0.03\n\tL = 11\n\tn_samples = 4\n\tp = scatter([Q.q[1]], [Q.q[2]], xlab=\"μx\", ylab=\"μy\")\n\n\n\tfor i ∈ 1:n_samples\n\t    Q = HMC2(U, ∇U, step1, L, Q.q)\n\t    if n_samples < 10 \n\t        cx, cy = [], []\n\t        for j ∈ 1:L\n\t            K0 = sum(Q.ptraj[j].^2)/2\n\t            plot!(\n\t                [Q.traj[j][1], Q.traj[j+1][1]],\n\t                [Q.traj[j][2], Q.traj[j+1][2]],\n\t                lw=1+2*K0,\n\t                c=:black,\n\t                alpha=0.5\n\t            )\n\t            push!(cx, Q.traj[j+1][1])\n\t            push!(cy, Q.traj[j+1][2])\n\t        end\n\t        scatter!(cx, cy, c=:white, ms=3)\n\t    end\n\t    scatter!([Q.q[1]], [Q.q[2]], shape=(Q.accept ? :circle : :rect), c=:blue)\n\tend\n\tp\nend\n\n# ╔═╡ 4dc8aa1b-7544-4a80-9109-a2c9040d9321\nmd\"## 9.4 Easy HMC: ulam\"\n\n# ╔═╡ e6a3d465-57d2-40aa-b71d-8cca5db234d9\nmd\"### Code 9.11\"\n\n# ╔═╡ ff957f53-dbc7-4885-9797-61d10b8dac15\nbegin\n\td = CSV.read(sr_datadir(\"rugged.csv\"), DataFrame)\n\tdd = d[completecases(d, :rgdppc_2000),:]\n\tdd[:,:log_gdp] = log.(dd.rgdppc_2000);\n\tdd[:,:log_gdp_std] = dd.log_gdp / mean(dd.log_gdp)\n\tdd[:,:rugged_std] = dd.rugged / maximum(dd.rugged)\n\tdd[:,:cid] = @. ifelse(dd.cont_africa == 1, 1, 2);\nend;\n\n# ╔═╡ 06d5c8b7-7a87-4ddb-9c30-d6d623a71814\nmd\"### Code 9.12\"\n\n# ╔═╡ e29edd1a-890d-4e21-a221-d4311bd845d3\nr̄ = mean(dd.rugged_std);\n\n# ╔═╡ 200f0e88-b30f-4aac-a733-a25f5a52c5d8\n@model function model_m8_3(rugged_std, cid,  log_gdp_std)\n    σ ~ Exponential()\n    a ~ MvNormal([1, 1], 0.1)\n    b ~ MvNormal([0, 0], 0.3)\n    μ = @. a[cid] + b[cid] * (rugged_std - r̄)\n    log_gdp_std ~ MvNormal(μ, σ)\nend\n\n# ╔═╡ fbcda425-2e88-4a49-b24b-17894231642e\nbegin\n\tm8_3 = optimize(model_m8_3(dd.rugged_std, dd.cid,  dd.log_gdp_std), MAP())\n\tm8_3_df = DataFrame(sample(m8_3, 1000))\n\tPRECIS(m8_3_df)\nend\n\n# ╔═╡ f67d530a-e56d-408c-8f21-d4e37e8dab42\nmd\"### Code 9.13\"\n\n# ╔═╡ 60a185df-0656-4a46-b301-388407073ab6\nmd\"#### For Turing this is not needed\"\n\n# ╔═╡ 9d6afd05-6570-44e0-8b49-5e4bc7e8a76f\nbegin\n\tdat_slim = dd[!,[:log_gdp_std, :rugged_std, :cid]]\n\tdescribe(dat_slim)\nend\n\n# ╔═╡ cfe67e9f-41bb-419f-96ba-282926de31a2\nmd\"### Code 9.14\"\n\n# ╔═╡ 8409b9f4-7fa5-4f38-9b38-ae34e4c60e83\n@model function model_m9_1(rugged_std, cid,  log_gdp_std)\n    σ ~ Exponential()\n    a ~ MvNormal([1, 1], 0.1)\n    b ~ MvNormal([0, 0], 0.3)\n    μ = @. a[cid] + b[cid] * (rugged_std - r̄)\n    log_gdp_std ~ MvNormal(μ, σ)\nend\n\n# ╔═╡ 4e94cf59-81eb-4b99-b048-502f54faee15\nmd\"#### One chain will be produced by default\"\n\n# ╔═╡ 76782d05-9e32-424c-a206-8081e0fdd146\nm9_1 = sample(model_m8_3(dd.rugged_std, dd.cid,  dd.log_gdp_std), NUTS(), 1000);\n\n# ╔═╡ e8dd780e-b94d-413c-9b0b-0476817b2094\nmd\"### Code 9.15\"\n\n# ╔═╡ b80e5ff3-445a-465c-9665-697f5b0b897e\nPRECIS(DataFrame(m9_1))\n\n# ╔═╡ b6057787-3948-482c-be7e-69c4231386b6\nmd\"### Code 9.16\"\n\n# ╔═╡ d438bddd-9138-410e-ab98-40f7c90e780f\nmd\"#### For this to use multiple cores, julia has to be started with `--threads 4` parameter, otherwise chains will be sampled sequentially\"\n\n# ╔═╡ 3f4a3b7c-2db7-4d7b-800a-c14968a02855\nm9_1_4 = sample(model_m8_3(dd.rugged_std, dd.cid,  dd.log_gdp_std), NUTS(),\n\tMCMCThreads(), 1000, 4);\n\n# ╔═╡ 2d2aa3ef-8fb7-4c69-8869-42e1939dc950\nmd\"### Code 9.17\"\n\n# ╔═╡ 61b5e6a8-3baa-4101-9a21-5d49af43bfe7\nmd\"#### This shows combined chains statistics. To get information about individual chains, use `m9_1[:,:,1]`\"\n\n# ╔═╡ 35f25d1e-234b-481f-9303-3c5973ab1228\nm9_1\n\n# ╔═╡ 4e20ad94-3011-4b89-b29e-8a793e733e03\nmd\"### Code 9.18\"\n\n# ╔═╡ ed026592-6cb3-40a3-9f0a-565e14038114\nPRECIS(DataFrame(m9_1[:,:,1]))\n\n# ╔═╡ b25c0b7a-4469-4945-be28-bfb2c22103ca\nmd\"### Code 9.19\"\n\n# ╔═╡ 8a0295cc-4f0c-475a-a8c6-ccf2b99ed00f\n@df DataFrame(m9_1) corrplot(cols(1:5), seriestype=:scatter, ms=0.2, size=(950, 800), bins=30, grid=false)\n\n# ╔═╡ 580db5a8-550a-42d1-9aef-c95f4099a3fa\nmd\"### Code 9.20\"\n\n# ╔═╡ 0bd7dbfe-0689-40d4-8fd0-1fd372b2edc2\ntraceplot(m9_1)\n\n# ╔═╡ 534f0c53-da8b-4da5-81d4-c0ab3ceb270b\nmd\"### Code 9.21\"\n\n# ╔═╡ a28ee7bb-d9d7-43ea-833f-6460a2cf7579\nhistogram(m9_1)\n\n# ╔═╡ 4535c71f-be7c-41e8-940b-57289c83e509\nmd\"## 9.5 Care and feeding of your Markov chain.\"\n\n# ╔═╡ f39cd55f-ed8f-487e-885e-f1e16b78d9dd\nmd\"### Codes 9.22 - 9.23\"\n\n# ╔═╡ cd971faa-315a-4cea-a11a-0cb28f3e3997\nlet\n\t# To make it diverting with Turing, it was needed to increase exp() argument.\n\tRandom.seed!(1)\n\ty = [-1., 1.]\n\n\t@model function model_m9_2(y)\n\t    α ~ Normal(0, 1000)\n\t    σ ~ Exponential(1/0.0001)\n\t    y ~ Normal(α, σ)\n\tend\n\n\tglobal m9_2 = sample(model_m9_2(y), NUTS(), 1000)\n\tm9_2_df = DataFrame(m9_2)\n\tPRECIS(m9_2_df)\nend\n\n# ╔═╡ a9febef3-06d0-4552-8590-2f165ce36547\nmd\"### Code 9.23\"\n\n# ╔═╡ 7b2588d2-d86d-44fb-9895-d6452875bc47\nplot(\n    traceplot(m9_2),\n    histogram(m9_2),\n    size=(900, 500)\n)\n\n# ╔═╡ cc97f4d9-ad00-4d2c-b520-2071b9cf86f6\nmd\"### Code 9.24\"\n\n# ╔═╡ 631bb03b-00a5-466a-be0d-36f86a9721aa\nRandom.seed!(2)\n\n# ╔═╡ 95dc66d6-660a-4b0c-b89d-487a22dfec82\n@model function model_m9_3(y)\n    α ~ Normal(1, 10)\n    σ ~ Exponential(1)\n    y ~ Normal(α, σ)\nend\n\n# ╔═╡ c5570bf1-c04d-41e3-b8ae-6e6dac45cb70\nbegin\n\tm9_3 = sample(model_m9_3(y), NUTS(), 1000)\n\tm9_3_df = DataFrame(m9_3)\n\tPRECIS(m9_3_df)\nend\n\n# ╔═╡ 8f945f6c-2561-433b-aedb-3448d2c4b419\ness_rhat(m9_3)\n\n# ╔═╡ ecd23fa3-fdd2-4ffb-a0e9-ad1feee04d22\nmd\"### Code 9.25 - 9.26\"\n\n# ╔═╡ f10e310f-165b-4b4b-b3e0-66af6430ba4f\nlet\n\tRandom.seed!(41)\n\ty = rand(Normal(), 100)\n\n\tRandom.seed!(384)\n\n\t@model function model_m9_4(y)\n\t    a1 ~ Normal(0, 1000)\n\t    a2 ~ Normal(0, 1000)\n\t    σ ~ Exponential(1)\n\t    μ = a1 + a2\n\t    y ~ Normal(μ, σ)\n\tend\n\n\tglobal m9_4 = sample(model_m9_4(y), NUTS(), 1000)\n\tm9_4_df = DataFrame(m9_4)\n\tPRECIS(m9_4_df)\n\nend\n\n# ╔═╡ 4c09eda3-8f4c-4fa2-91ea-99b92cfbb422\ness_rhat(m9_4)\n\n# ╔═╡ 1f2c5378-bbcd-4fb7-9130-9c6cebb4c6d4\nplot(m9_4)\n\n# ╔═╡ 517d31ba-5843-40a7-ad06-96e7a8ea8845\nmd\"### Code 9.27\"\n\n# ╔═╡ 1cc0a6c1-3fcf-4df3-a8d9-ba3454c0a37b\nRandom.seed!(384)\n\n# ╔═╡ 9a76593b-c9a9-45cc-aca5-9877432baffd\n@model function model_m9_5(y)\n    a1 ~ Normal(0, 10)\n    a2 ~ Normal(0, 10)\n    σ ~ Exponential(1)\n    μ = a1 + a2\n    y ~ Normal(μ, σ)\nend\n\n# ╔═╡ 6a7ea8be-bea2-41c4-89ab-9a6bbcfba116\nbegin\n\tm9_5 = sample(model_m9_5(y), NUTS(), 1000)\n\tm9_5_df = DataFrame(m9_5)\n\tPRECIS(m9_5_df)\nend\n\n# ╔═╡ 942e3f19-a5c1-430e-a3be-097c53bc7394\ness_rhat(m9_5)\n\n# ╔═╡ 6caa4b75-9ac1-496b-a4b2-38b72b203e59\nplot(m9_5)\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nCSV = \"336ed68f-0bac-5ca0-87d4-7b16caf5d00b\"\nDataFrames = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nDistributions = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nDrWatson = \"634d3b9d-ee7a-5ddf-bec9-22491ea816e1\"\nLogging = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\nMCMCChains = \"c7f686f2-ff18-58e9-bc7b-31028e88f75d\"\nOptim = \"429524aa-4258-5aef-a3af-852621145aeb\"\nPkg = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\nRandom = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\nStatisticalRethinking = \"2d09df54-9d0f-5258-8220-54c2a3d4fbee\"\nStatsBase = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nStatsFuns = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nStatsPlots = \"f3b207a7-027a-5e70-b257-86293d7955fd\"\nTuring = \"fce5fe82-541a-59a6-adf8-730c64b5f9a0\"\n\n[compat]\nCSV = \"~0.9.11\"\nDataFrames = \"~1.2.2\"\nDistributions = \"~0.25.34\"\nDrWatson = \"~2.7.5\"\nMCMCChains = \"~5.0.1\"\nOptim = \"~1.5.0\"\nStatisticalRethinking = \"~4.4.3\"\nStatsBase = \"~0.33.13\"\nStatsFuns = \"~0.9.14\"\nStatsPlots = \"~0.14.29\"\nTuring = \"~0.19.0\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[ANSIColoredPrinters]]\ngit-tree-sha1 = \"574baf8110975760d391c710b6341da1afa48d8c\"\nuuid = \"a4c015fc-c6ff-483c-b24f-f7ea428134e9\"\nversion = \"0.0.1\"\n\n[[AbstractFFTs]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"485ee0867925449198280d4af84bdb46a2a404d0\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"1.0.1\"\n\n[[AbstractMCMC]]\ndeps = [\"BangBang\", \"ConsoleProgressMonitor\", \"Distributed\", \"Logging\", \"LoggingExtras\", \"ProgressLogging\", \"Random\", \"StatsBase\", \"TerminalLoggers\", \"Transducers\"]\ngit-tree-sha1 = \"db0a7ff3fbd987055c43b4e12d2fa30aaae8749c\"\nuuid = \"80f14c24-f653-4e6a-9b94-39d6b0f70001\"\nversion = \"3.2.1\"\n\n[[AbstractPPL]]\ndeps = [\"AbstractMCMC\"]\ngit-tree-sha1 = \"15f34cc635546ac072d03fc2cc10083adb4df680\"\nuuid = \"7a57a42e-76ec-4ea3-a279-07e840d6d9cf\"\nversion = \"0.2.0\"\n\n[[AbstractTrees]]\ngit-tree-sha1 = \"03e0550477d86222521d254b741d470ba17ea0b5\"\nuuid = \"1520ce14-60c1-5f80-bbc7-55ef81b5835c\"\nversion = \"0.3.4\"\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[AdvancedHMC]]\ndeps = [\"AbstractMCMC\", \"ArgCheck\", \"DocStringExtensions\", \"InplaceOps\", \"LinearAlgebra\", \"ProgressMeter\", \"Random\", \"Requires\", \"Setfield\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"UnPack\"]\ngit-tree-sha1 = \"0a655e9a59ee1c8bafc3af18e96d90f980b08600\"\nuuid = \"0bf59076-c3b1-5ca4-86bd-e02cd72cde3d\"\nversion = \"0.3.2\"\n\n[[AdvancedMH]]\ndeps = [\"AbstractMCMC\", \"Distributions\", \"Random\", \"Requires\"]\ngit-tree-sha1 = \"8ad8bfddf8bb627d689ecb91599c349cbf15e971\"\nuuid = \"5b7e9947-ddc0-4b3f-9b55-0d8042f74170\"\nversion = \"0.6.6\"\n\n[[AdvancedPS]]\ndeps = [\"AbstractMCMC\", \"Distributions\", \"Libtask\", \"Random\", \"StatsFuns\"]\ngit-tree-sha1 = \"06da6c283cf17cf0f97ed2c07c29b6333ee83dc9\"\nuuid = \"576499cb-2369-40b2-a588-c64705576edc\"\nversion = \"0.2.4\"\n\n[[AdvancedVI]]\ndeps = [\"Bijectors\", \"Distributions\", \"DistributionsAD\", \"DocStringExtensions\", \"ForwardDiff\", \"LinearAlgebra\", \"ProgressMeter\", \"Random\", \"Requires\", \"StatsBase\", \"StatsFuns\", \"Tracker\"]\ngit-tree-sha1 = \"130d6b17a3a9d420d9a6b37412cae03ffd6a64ff\"\nuuid = \"b5ca4192-6429-45e5-a2d9-87aec30a685c\"\nversion = \"0.1.3\"\n\n[[ArgCheck]]\ngit-tree-sha1 = \"dedbbb2ddb876f899585c4ec4433265e3017215a\"\nuuid = \"dce04be8-c92d-5529-be00-80e4d2c0e197\"\nversion = \"2.1.0\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Arpack]]\ndeps = [\"Arpack_jll\", \"Libdl\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"2ff92b71ba1747c5fdd541f8fc87736d82f40ec9\"\nuuid = \"7d9fca2a-8960-54d3-9f78-7d1dccf2cb97\"\nversion = \"0.4.0\"\n\n[[Arpack_jll]]\ndeps = [\"Libdl\", \"OpenBLAS_jll\", \"Pkg\"]\ngit-tree-sha1 = \"e214a9b9bd1b4e1b4f15b22c0994862b66af7ff7\"\nuuid = \"68821587-b530-5797-8361-c406ea357684\"\nversion = \"3.5.0+3\"\n\n[[ArrayInterface]]\ndeps = [\"Compat\", \"IfElse\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"Static\"]\ngit-tree-sha1 = \"265b06e2b1f6a216e0e8f183d28e4d354eab3220\"\nuuid = \"4fba245c-0d91-5ea0-9b3e-6abc04ee57a9\"\nversion = \"3.2.1\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[AxisAlgorithms]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"66771c8d21c8ff5e3a93379480a2307ac36863f7\"\nuuid = \"13072b0f-2c55-5437-9ae7-d433b7a33950\"\nversion = \"1.0.1\"\n\n[[AxisArrays]]\ndeps = [\"Dates\", \"IntervalSets\", \"IterTools\", \"RangeArrays\"]\ngit-tree-sha1 = \"d127d5e4d86c7680b20c35d40b503c74b9a39b5e\"\nuuid = \"39de3d68-74b9-583c-8d2d-e117c070f3a9\"\nversion = \"0.4.4\"\n\n[[AxisKeys]]\ndeps = [\"AbstractFFTs\", \"CovarianceEstimation\", \"IntervalSets\", \"InvertedIndices\", \"LazyStack\", \"LinearAlgebra\", \"NamedDims\", \"OffsetArrays\", \"Statistics\", \"StatsBase\", \"Tables\"]\ngit-tree-sha1 = \"7bf355be5615178fdac1252a16e247eca6ee166f\"\nuuid = \"94b1ba4f-4ee9-5380-92f1-94cde586c3c5\"\nversion = \"0.1.22\"\n\n[[BangBang]]\ndeps = [\"Compat\", \"ConstructionBase\", \"Future\", \"InitialValues\", \"LinearAlgebra\", \"Requires\", \"Setfield\", \"Tables\", \"ZygoteRules\"]\ngit-tree-sha1 = \"0ad226aa72d8671f20d0316e03028f0ba1624307\"\nuuid = \"198e06fe-97b7-11e9-32a5-e1d131e6ad66\"\nversion = \"0.3.32\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Baselet]]\ngit-tree-sha1 = \"aebf55e6d7795e02ca500a689d326ac979aaf89e\"\nuuid = \"9718e550-a3fa-408a-8086-8db961cd8217\"\nversion = \"0.1.1\"\n\n[[Bijectors]]\ndeps = [\"ArgCheck\", \"ChainRulesCore\", \"Compat\", \"Distributions\", \"Functors\", \"IrrationalConstants\", \"LinearAlgebra\", \"LogExpFunctions\", \"MappedArrays\", \"Random\", \"Reexport\", \"Requires\", \"Roots\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"369af32fcb9be65d496dc43ad0bb713705d4e859\"\nuuid = \"76274a88-744f-5084-9051-94815aaf08c4\"\nversion = \"0.9.11\"\n\n[[BitTwiddlingConvenienceFunctions]]\ndeps = [\"Static\"]\ngit-tree-sha1 = \"bc1317f71de8dce26ea67fcdf7eccc0d0693b75b\"\nuuid = \"62783981-4cbd-42fc-bca8-16325de8dc4b\"\nversion = \"0.1.1\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[CPUSummary]]\ndeps = [\"Hwloc\", \"IfElse\", \"Static\"]\ngit-tree-sha1 = \"87b0c9c6ee0124d6c1f4ce8cb035dcaf9f90b803\"\nuuid = \"2a0fbf3d-bb9c-48f3-b0a9-814d99fd7ab9\"\nversion = \"0.1.6\"\n\n[[CSV]]\ndeps = [\"CodecZlib\", \"Dates\", \"FilePathsBase\", \"InlineStrings\", \"Mmap\", \"Parsers\", \"PooledArrays\", \"SentinelArrays\", \"Tables\", \"Unicode\", \"WeakRefStrings\"]\ngit-tree-sha1 = \"49f14b6c56a2da47608fe30aed711b5882264d7a\"\nuuid = \"336ed68f-0bac-5ca0-87d4-7b16caf5d00b\"\nversion = \"0.9.11\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"f2202b55d816427cd385a9a4f3ffb226bee80f99\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+0\"\n\n[[ChainRules]]\ndeps = [\"ChainRulesCore\", \"Compat\", \"LinearAlgebra\", \"Random\", \"RealDot\", \"Statistics\"]\ngit-tree-sha1 = \"65a0826ac25869556070076459925d1700316aab\"\nuuid = \"082447d4-558c-5d27-93f4-14fc19e9eca2\"\nversion = \"1.14.0\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"f885e7e7c124f8c92650d61b9477b9ac2ee607dd\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.11.1\"\n\n[[ChangesOfVariables]]\ndeps = [\"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"9a1d594397670492219635b35a3d830b04730d62\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.1\"\n\n[[Clustering]]\ndeps = [\"Distances\", \"LinearAlgebra\", \"NearestNeighbors\", \"Printf\", \"SparseArrays\", \"Statistics\", \"StatsBase\"]\ngit-tree-sha1 = \"75479b7df4167267d75294d14b58244695beb2ac\"\nuuid = \"aaaa29a8-35af-508c-8bc3-b662a17a0fe5\"\nversion = \"0.14.2\"\n\n[[CodecZlib]]\ndeps = [\"TranscodingStreams\", \"Zlib_jll\"]\ngit-tree-sha1 = \"ded953804d019afa9a3f98981d99b33e3db7b6da\"\nuuid = \"944b1d66-785c-5afd-91f1-9de20f533193\"\nversion = \"0.7.0\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"a851fec56cb73cfdf43762999ec72eff5b86882a\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.15.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Combinatorics]]\ngit-tree-sha1 = \"08c8b6831dc00bfea825826be0bc8336fc369860\"\nuuid = \"861a8166-3701-5b0c-9a16-15d98fcdc6aa\"\nversion = \"1.0.2\"\n\n[[CommonSolve]]\ngit-tree-sha1 = \"68a0743f578349ada8bc911a5cbd5a2ef6ed6d1f\"\nuuid = \"38540f10-b2f7-11e9-35d8-d573e4eb0ff2\"\nversion = \"0.2.0\"\n\n[[CommonSubexpressions]]\ndeps = [\"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"7b8a93dba8af7e3b42fecabf646260105ac373f7\"\nuuid = \"bbf7d656-a473-5ed7-a52c-81e309532950\"\nversion = \"0.3.0\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"dce3e3fea680869eaa0b774b2e8343e9ff442313\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.40.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[CompositionsBase]]\ngit-tree-sha1 = \"455419f7e328a1a2493cabc6428d79e951349769\"\nuuid = \"a33af91c-f02d-484b-be07-31d278c5ca2b\"\nversion = \"0.1.1\"\n\n[[ConsoleProgressMonitor]]\ndeps = [\"Logging\", \"ProgressMeter\"]\ngit-tree-sha1 = \"3ab7b2136722890b9af903859afcf457fa3059e8\"\nuuid = \"88cd18e8-d9cc-4ea6-8889-5259c0d15c8b\"\nversion = \"0.1.2\"\n\n[[ConstructionBase]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"f74e9d5388b8620b4cee35d4c5a618dd4dc547f4\"\nuuid = \"187b0558-2788-49d3-abe0-74a17ed4e7c9\"\nversion = \"1.3.0\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[CovarianceEstimation]]\ndeps = [\"LinearAlgebra\", \"Statistics\", \"StatsBase\"]\ngit-tree-sha1 = \"bc3930158d2be029e90b7c40d1371c4f54fa04db\"\nuuid = \"587fd27a-f159-11e8-2dae-1979310e6154\"\nversion = \"0.2.6\"\n\n[[Crayons]]\ngit-tree-sha1 = \"3f71217b538d7aaee0b69ab47d9b7724ca8afa0d\"\nuuid = \"a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f\"\nversion = \"4.0.4\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataFrames]]\ndeps = [\"Compat\", \"DataAPI\", \"Future\", \"InvertedIndices\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"Markdown\", \"Missings\", \"PooledArrays\", \"PrettyTables\", \"Printf\", \"REPL\", \"Reexport\", \"SortingAlgorithms\", \"Statistics\", \"TableTraits\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"d785f42445b63fc86caa08bb9a9351008be9b765\"\nuuid = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nversion = \"1.2.2\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[DataValues]]\ndeps = [\"DataValueInterfaces\", \"Dates\"]\ngit-tree-sha1 = \"d88a19299eba280a6d062e135a43f00323ae70bf\"\nuuid = \"e7dc6d0d-1eca-5fa6-8ad6-5aecde8b7ea5\"\nversion = \"0.4.13\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DefineSingletons]]\ngit-tree-sha1 = \"77b4ca280084423b728662fe040e5ff8819347c5\"\nuuid = \"244e2a9f-e319-4986-a169-4d1fe445cd52\"\nversion = \"0.1.1\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[DensityInterface]]\ndeps = [\"InverseFunctions\", \"Test\"]\ngit-tree-sha1 = \"80c3e8639e3353e5d2912fb3a1916b8455e2494b\"\nuuid = \"b429d917-457f-4dbc-8f4c-0cc954292b1d\"\nversion = \"0.4.0\"\n\n[[DiffResults]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"c18e98cba888c6c25d1c3b048e4b3380ca956805\"\nuuid = \"163ba53b-c6d8-5494-b064-1a9d43ac40c5\"\nversion = \"1.0.3\"\n\n[[DiffRules]]\ndeps = [\"LogExpFunctions\", \"NaNMath\", \"Random\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"d8f468c5cd4d94e86816603f7d18ece910b4aaf1\"\nuuid = \"b552c78f-8df3-52c6-915a-8e097449b14b\"\nversion = \"1.5.0\"\n\n[[Distances]]\ndeps = [\"LinearAlgebra\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"837c83e5574582e07662bbbba733964ff7c26b9d\"\nuuid = \"b4f34e82-e78d-54a5-968a-f98e89d6e8f7\"\nversion = \"0.10.6\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Distributions]]\ndeps = [\"ChainRulesCore\", \"DensityInterface\", \"FillArrays\", \"LinearAlgebra\", \"PDMats\", \"Printf\", \"QuadGK\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"Test\"]\ngit-tree-sha1 = \"7f3bec11f4bcd01bc1f507ebce5eadf1b0a78f47\"\nuuid = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nversion = \"0.25.34\"\n\n[[DistributionsAD]]\ndeps = [\"Adapt\", \"ChainRules\", \"ChainRulesCore\", \"Compat\", \"DiffRules\", \"Distributions\", \"FillArrays\", \"LinearAlgebra\", \"NaNMath\", \"PDMats\", \"Random\", \"Requires\", \"SpecialFunctions\", \"StaticArrays\", \"StatsBase\", \"StatsFuns\", \"ZygoteRules\"]\ngit-tree-sha1 = \"55c82c84759cff92189c9ad07e7bd0a0df63e900\"\nuuid = \"ced4e74d-a319-5a8a-b0ac-84af2272839c\"\nversion = \"0.6.34\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[Documenter]]\ndeps = [\"ANSIColoredPrinters\", \"Base64\", \"Dates\", \"DocStringExtensions\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"LibGit2\", \"Logging\", \"Markdown\", \"REPL\", \"Test\", \"Unicode\"]\ngit-tree-sha1 = \"f425293f7e0acaf9144de6d731772de156676233\"\nuuid = \"e30172f5-a6a5-5a46-863b-614d45cd2de4\"\nversion = \"0.27.10\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[DrWatson]]\ndeps = [\"Dates\", \"FileIO\", \"JLD2\", \"LibGit2\", \"MacroTools\", \"Pkg\", \"Random\", \"Requires\", \"Scratch\", \"UnPack\"]\ngit-tree-sha1 = \"dfc6c06fa560e6a7658245bacd90fc6a3a6c1cce\"\nuuid = \"634d3b9d-ee7a-5ddf-bec9-22491ea816e1\"\nversion = \"2.7.5\"\n\n[[DynamicPPL]]\ndeps = [\"AbstractMCMC\", \"AbstractPPL\", \"BangBang\", \"Bijectors\", \"ChainRulesCore\", \"Distributions\", \"MacroTools\", \"Random\", \"ZygoteRules\"]\ngit-tree-sha1 = \"532397f64ad49472fb60e328369ecd5dedeff02f\"\nuuid = \"366bfd00-2699-11ea-058f-f148b4cae6d8\"\nversion = \"0.15.1\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[EllipsisNotation]]\ndeps = [\"ArrayInterface\"]\ngit-tree-sha1 = \"3fe985505b4b667e1ae303c9ca64d181f09d5c05\"\nuuid = \"da5c29d0-fa7d-589e-88eb-ea29b0a81949\"\nversion = \"1.1.3\"\n\n[[EllipticalSliceSampling]]\ndeps = [\"AbstractMCMC\", \"ArrayInterface\", \"Distributions\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"254182080498cce7ae4bc863d23bf27c632688f7\"\nuuid = \"cad2338a-1db2-11e9-3401-43bc07c9ede2\"\nversion = \"0.4.4\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FFTW]]\ndeps = [\"AbstractFFTs\", \"FFTW_jll\", \"LinearAlgebra\", \"MKL_jll\", \"Preferences\", \"Reexport\"]\ngit-tree-sha1 = \"463cb335fa22c4ebacfd1faba5fde14edb80d96c\"\nuuid = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nversion = \"1.4.5\"\n\n[[FFTW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea\"\nuuid = \"f5851436-0d7a-5f13-b9de-f02708fd171a\"\nversion = \"3.3.10+0\"\n\n[[FileIO]]\ndeps = [\"Pkg\", \"Requires\", \"UUIDs\"]\ngit-tree-sha1 = \"2db648b6712831ecb333eae76dbfd1c156ca13bb\"\nuuid = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nversion = \"1.11.2\"\n\n[[FilePathsBase]]\ndeps = [\"Compat\", \"Dates\", \"Mmap\", \"Printf\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"04d13bfa8ef11720c24e4d840c0033d145537df7\"\nuuid = \"48062228-2e41-5def-b9a4-89aafe57970f\"\nversion = \"0.9.17\"\n\n[[FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"8756f9935b7ccc9064c6eef0bff0ad643df733a3\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.12.7\"\n\n[[FiniteDiff]]\ndeps = [\"ArrayInterface\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"StaticArrays\"]\ngit-tree-sha1 = \"8b3c09b56acaf3c0e581c66638b85c8650ee9dca\"\nuuid = \"6a86dc24-6348-571c-b903-95158fe2bd41\"\nversion = \"2.8.1\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[ForwardDiff]]\ndeps = [\"CommonSubexpressions\", \"DiffResults\", \"DiffRules\", \"LinearAlgebra\", \"LogExpFunctions\", \"NaNMath\", \"Preferences\", \"Printf\", \"Random\", \"SpecialFunctions\", \"StaticArrays\"]\ngit-tree-sha1 = \"6406b5112809c08b1baa5703ad274e1dded0652f\"\nuuid = \"f6369f11-7733-5829-9624-2563aa707210\"\nversion = \"0.10.23\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[Functors]]\ngit-tree-sha1 = \"e4768c3b7f597d5a352afa09874d16e3c3f6ead2\"\nuuid = \"d9f16b24-f501-4c13-a1f2-28368ffc5196\"\nversion = \"0.2.7\"\n\n[[Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"0c603255764a1fa0b61752d2bec14cfbd18f7fe8\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+1\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"30f2b340c2fff8410d89bfcdc9c0a6dd661ac5f7\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.62.1\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"fd75fa3a2080109a2c0ec9864a6e14c60cca3866\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.62.0+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"7bf67e9a481712b3dbe9cb3dac852dc4b1162e02\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+0\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"0fa77022fe4b511826b39c894c90daf5fce3334a\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.17\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"8a954fed8ac097d5be04921d595f741115c1b2ad\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+0\"\n\n[[HostCPUFeatures]]\ndeps = [\"BitTwiddlingConvenienceFunctions\", \"IfElse\", \"Libdl\", \"Static\"]\ngit-tree-sha1 = \"8f0dc80088981ab55702b04bba38097a44a1a3a9\"\nuuid = \"3e5b6fbb-0976-4d2c-9146-d79de83f2fb0\"\nversion = \"0.1.5\"\n\n[[Hwloc]]\ndeps = [\"Hwloc_jll\"]\ngit-tree-sha1 = \"92d99146066c5c6888d5a3abc871e6a214388b91\"\nuuid = \"0e44f5e4-bd66-52a0-8798-143a42290a1d\"\nversion = \"2.0.0\"\n\n[[Hwloc_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3395d4d4aeb3c9d31f5929d32760d8baeee88aaf\"\nuuid = \"e33a78d0-f292-5ffc-b300-72abe9b543c8\"\nversion = \"2.5.0+0\"\n\n[[IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[IfElse]]\ngit-tree-sha1 = \"debdd00ffef04665ccbb3e150747a77560e8fad1\"\nuuid = \"615f187c-cbe4-4ef1-ba3b-2fcf58d6d173\"\nversion = \"0.1.1\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[InitialValues]]\ngit-tree-sha1 = \"7f6a4508b4a6f46db5ccd9799a3fc71ef5cad6e6\"\nuuid = \"22cec73e-a1b8-11e9-2c92-598750a2cf9c\"\nversion = \"0.2.11\"\n\n[[InlineStrings]]\ndeps = [\"Parsers\"]\ngit-tree-sha1 = \"19cb49649f8c41de7fea32d089d37de917b553da\"\nuuid = \"842dd82b-1e85-43dc-bf29-5d0ee9dffc48\"\nversion = \"1.0.1\"\n\n[[InplaceOps]]\ndeps = [\"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"50b41d59e7164ab6fda65e71049fee9d890731ff\"\nuuid = \"505f98c9-085e-5b2c-8e89-488be7bf1f34\"\nversion = \"0.3.0\"\n\n[[IntelOpenMP_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d979e54b71da82f3a65b62553da4fc3d18c9004c\"\nuuid = \"1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0\"\nversion = \"2018.0.3+2\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[Interpolations]]\ndeps = [\"AxisAlgorithms\", \"ChainRulesCore\", \"LinearAlgebra\", \"OffsetArrays\", \"Random\", \"Ratios\", \"Requires\", \"SharedArrays\", \"SparseArrays\", \"StaticArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"61aa005707ea2cebf47c8d780da8dc9bc4e0c512\"\nuuid = \"a98d9a8b-a2ab-59e6-89dd-64a1c18fca59\"\nversion = \"0.13.4\"\n\n[[IntervalSets]]\ndeps = [\"Dates\", \"EllipsisNotation\", \"Statistics\"]\ngit-tree-sha1 = \"3cc368af3f110a767ac786560045dceddfc16758\"\nuuid = \"8197267c-284f-5f27-9208-e0e47529a953\"\nversion = \"0.5.3\"\n\n[[InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.2\"\n\n[[InvertedIndices]]\ngit-tree-sha1 = \"bee5f1ef5bf65df56bdd2e40447590b272a5471f\"\nuuid = \"41ab1584-1d38-5bbf-9106-f11c6c58b48f\"\nversion = \"1.1.0\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLD2]]\ndeps = [\"DataStructures\", \"FileIO\", \"MacroTools\", \"Mmap\", \"Pkg\", \"Printf\", \"Reexport\", \"TranscodingStreams\", \"UUIDs\"]\ngit-tree-sha1 = \"46b7834ec8165c541b0b5d1c8ba63ec940723ffb\"\nuuid = \"033835bb-8acc-5ee8-8aae-3f567f8a3819\"\nversion = \"0.4.15\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[KernelDensity]]\ndeps = [\"Distributions\", \"DocStringExtensions\", \"FFTW\", \"Interpolations\", \"StatsBase\"]\ngit-tree-sha1 = \"591e8dc09ad18386189610acafb970032c519707\"\nuuid = \"5ab0869b-81aa-558d-bb23-cbf5423bbe9b\"\nversion = \"0.6.3\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"f2355693d6778a178ade15952b7ac47a4ff97996\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.3.0\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a8f4f279b6fa3c3c4f1adadd78a621b13a506bce\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.9\"\n\n[[LayoutPointers]]\ndeps = [\"ArrayInterface\", \"LinearAlgebra\", \"ManualMemory\", \"SIMDTypes\", \"Static\"]\ngit-tree-sha1 = \"83b56449c39342a47f3fcdb3bc782bd6d66e1d97\"\nuuid = \"10f19ff3-798f-405d-979b-55457f8fc047\"\nversion = \"0.1.4\"\n\n[[LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[LazyStack]]\ndeps = [\"LinearAlgebra\", \"NamedDims\", \"OffsetArrays\", \"Test\", \"ZygoteRules\"]\ngit-tree-sha1 = \"a8bf67afad3f1ee59d367267adb7c44ccac7fdee\"\nuuid = \"1fad7336-0346-5a1a-a56f-a06ba010965b\"\nversion = \"0.0.7\"\n\n[[LeftChildRightSiblingTrees]]\ndeps = [\"AbstractTrees\"]\ngit-tree-sha1 = \"71be1eb5ad19cb4f61fa8c73395c0338fd092ae0\"\nuuid = \"1d6d02ad-be62-4b6b-8a6d-2f90e265016e\"\nversion = \"0.1.2\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"0b4a5d71f3e5200a7dff793393e09dfc2d874290\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+1\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtask]]\ndeps = [\"Libtask_jll\", \"LinearAlgebra\", \"Statistics\"]\ngit-tree-sha1 = \"90c6ed7f9ac449cddacd80d5c1fca59c97d203e7\"\nuuid = \"6f1fad26-d15e-5dc8-ae53-837a1d7b8c9f\"\nversion = \"0.5.3\"\n\n[[Libtask_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"901fc8752bbc527a6006a951716d661baa9d54e9\"\nuuid = \"3ae2931a-708c-5973-9c38-ccf7496fb450\"\nversion = \"0.4.3+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LineSearches]]\ndeps = [\"LinearAlgebra\", \"NLSolversBase\", \"NaNMath\", \"Parameters\", \"Printf\"]\ngit-tree-sha1 = \"f27132e551e959b3667d8c93eae90973225032dd\"\nuuid = \"d3d80556-e9d4-5f37-9878-2ab0fcc64255\"\nversion = \"7.1.1\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"be9eef9f9d78cecb6f262f3c10da151a6c5ab827\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.5\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[LoggingExtras]]\ndeps = [\"Dates\", \"Logging\"]\ngit-tree-sha1 = \"dfeda1c1130990428720de0024d4516b1902ce98\"\nuuid = \"e6f89c97-d47a-5376-807f-9c37f3926c36\"\nversion = \"0.4.7\"\n\n[[MCMCChains]]\ndeps = [\"AbstractMCMC\", \"AxisArrays\", \"Compat\", \"Dates\", \"Distributions\", \"Formatting\", \"IteratorInterfaceExtensions\", \"KernelDensity\", \"LinearAlgebra\", \"MCMCDiagnosticTools\", \"MLJModelInterface\", \"NaturalSort\", \"OrderedCollections\", \"PrettyTables\", \"Random\", \"RecipesBase\", \"Serialization\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"TableTraits\", \"Tables\"]\ngit-tree-sha1 = \"04c3fd6da28ebd305120ffb05f0a3b8f9baced0a\"\nuuid = \"c7f686f2-ff18-58e9-bc7b-31028e88f75d\"\nversion = \"5.0.1\"\n\n[[MCMCDiagnosticTools]]\ndeps = [\"AbstractFFTs\", \"DataAPI\", \"Distributions\", \"LinearAlgebra\", \"MLJModelInterface\", \"Random\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"Tables\"]\ngit-tree-sha1 = \"6aba85ab1ac0515a1d14330bf347a8634ea5776c\"\nuuid = \"be115224-59cd-429b-ad48-344e309966f0\"\nversion = \"0.1.2\"\n\n[[MKL_jll]]\ndeps = [\"Artifacts\", \"IntelOpenMP_jll\", \"JLLWrappers\", \"LazyArtifacts\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"5455aef09b40e5020e1520f551fa3135040d4ed0\"\nuuid = \"856f044c-d86e-5d09-b602-aeab76dc8ba7\"\nversion = \"2021.1.1+2\"\n\n[[MLJModelInterface]]\ndeps = [\"Random\", \"ScientificTypesBase\", \"StatisticalTraits\"]\ngit-tree-sha1 = \"0174e9d180b0cae1f8fe7976350ad52f0e70e0d8\"\nuuid = \"e80e1ace-859a-464e-9ed9-23947d8ae3ea\"\nversion = \"1.3.3\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[ManualMemory]]\ngit-tree-sha1 = \"9cb207b18148b2199db259adfa923b45593fe08e\"\nuuid = \"d125e4d3-2237-4719-b19c-fa641b8a4667\"\nversion = \"0.1.6\"\n\n[[MappedArrays]]\ngit-tree-sha1 = \"e8b359ef06ec72e8c030463fe02efe5527ee5142\"\nuuid = \"dbb5928d-eab1-5f90-85c2-b9b0edb7c900\"\nversion = \"0.4.1\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[MicroCollections]]\ndeps = [\"BangBang\", \"Setfield\"]\ngit-tree-sha1 = \"4f65bdbbe93475f6ff9ea6969b21532f88d359be\"\nuuid = \"128add7d-3638-4c79-886c-908ea0c25c34\"\nversion = \"0.1.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MonteCarloMeasurements]]\ndeps = [\"Distributed\", \"Distributions\", \"LinearAlgebra\", \"MacroTools\", \"Random\", \"RecipesBase\", \"Requires\", \"SLEEFPirates\", \"StaticArrays\", \"Statistics\", \"StatsBase\", \"Test\"]\ngit-tree-sha1 = \"d9dc441d5a0393ee80aea49d0fb13281d7cc7c91\"\nuuid = \"0987c9cc-fe09-11e8-30f0-b96dd679fdca\"\nversion = \"1.0.3\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[MultivariateStats]]\ndeps = [\"Arpack\", \"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsBase\"]\ngit-tree-sha1 = \"8d958ff1854b166003238fe191ec34b9d592860a\"\nuuid = \"6f286f6a-111f-5878-ab1e-185364afe411\"\nversion = \"0.8.0\"\n\n[[NLSolversBase]]\ndeps = [\"DiffResults\", \"Distributed\", \"FiniteDiff\", \"ForwardDiff\"]\ngit-tree-sha1 = \"50310f934e55e5ca3912fb941dec199b49ca9b68\"\nuuid = \"d41bc354-129a-5804-8e4c-c37616107c6c\"\nversion = \"7.8.2\"\n\n[[NNlib]]\ndeps = [\"Adapt\", \"ChainRulesCore\", \"Compat\", \"LinearAlgebra\", \"Pkg\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"2eb305b13eaed91d7da14269bf17ce6664bfee3d\"\nuuid = \"872c559c-99b0-510c-b3b7-b6c96a88d5cd\"\nversion = \"0.7.31\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[NamedArrays]]\ndeps = [\"Combinatorics\", \"DataStructures\", \"DelimitedFiles\", \"InvertedIndices\", \"LinearAlgebra\", \"Random\", \"Requires\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"2fd5787125d1a93fbe30961bd841707b8a80d75b\"\nuuid = \"86f7a689-2022-50b4-a561-43c23ac3c673\"\nversion = \"0.9.6\"\n\n[[NamedDims]]\ndeps = [\"AbstractFFTs\", \"ChainRulesCore\", \"CovarianceEstimation\", \"LinearAlgebra\", \"Pkg\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"4f34e3ff2fa7f2a1c03fb2c4fdd637380d760bbc\"\nuuid = \"356022a1-0364-5f58-8944-0da4b18d706f\"\nversion = \"0.2.42\"\n\n[[NamedTupleTools]]\ngit-tree-sha1 = \"63831dcea5e11db1c0925efe5ef5fc01d528c522\"\nuuid = \"d9ec5142-1e00-5aa0-9d6a-321866360f50\"\nversion = \"0.13.7\"\n\n[[NaturalSort]]\ngit-tree-sha1 = \"eda490d06b9f7c00752ee81cfa451efe55521e21\"\nuuid = \"c020b1a1-e9b0-503a-9c33-f039bfc54a85\"\nversion = \"1.0.0\"\n\n[[NearestNeighbors]]\ndeps = [\"Distances\", \"StaticArrays\"]\ngit-tree-sha1 = \"16baacfdc8758bc374882566c9187e785e85c2f0\"\nuuid = \"b8a86587-4115-5ab1-83bc-aa920d37bbce\"\nversion = \"0.4.9\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Observables]]\ngit-tree-sha1 = \"fe29afdef3d0c4a8286128d4e45cc50621b1e43d\"\nuuid = \"510215fc-4207-5dde-b226-833fc4488ee2\"\nversion = \"0.4.0\"\n\n[[OffsetArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"043017e0bdeff61cfbb7afeb558ab29536bbb5ed\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.8\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+0\"\n\n[[OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Optim]]\ndeps = [\"Compat\", \"FillArrays\", \"ForwardDiff\", \"LineSearches\", \"LinearAlgebra\", \"NLSolversBase\", \"NaNMath\", \"Parameters\", \"PositiveFactorizations\", \"Printf\", \"SparseArrays\", \"StatsBase\"]\ngit-tree-sha1 = \"35d435b512fbab1d1a29138b5229279925eba369\"\nuuid = \"429524aa-4258-5aef-a3af-852621145aeb\"\nversion = \"1.5.0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[PDMats]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"SuiteSparse\"]\ngit-tree-sha1 = \"ee26b350276c51697c9c2d88a072b339f9f03d73\"\nuuid = \"90014a1f-27ba-587c-ab20-58faa44d9150\"\nversion = \"0.11.5\"\n\n[[Parameters]]\ndeps = [\"OrderedCollections\", \"UnPack\"]\ngit-tree-sha1 = \"34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe\"\nuuid = \"d96e819e-fc66-5662-9728-84c9c7592b0a\"\nversion = \"0.12.3\"\n\n[[ParetoSmooth]]\ndeps = [\"AxisKeys\", \"InteractiveUtils\", \"LinearAlgebra\", \"LogExpFunctions\", \"MCMCDiagnosticTools\", \"NamedDims\", \"PrettyTables\", \"Printf\", \"Random\", \"Requires\", \"Statistics\", \"StatsBase\", \"Tullio\"]\ngit-tree-sha1 = \"c6e1c653d65d9b411f93d173678e82cf086d92e6\"\nuuid = \"a68b5a21-f429-434e-8bfa-46b447300aac\"\nversion = \"0.7.0\"\n\n[[ParetoSmoothedImportanceSampling]]\ndeps = [\"CSV\", \"DataFrames\", \"Distributions\", \"JSON\", \"Printf\", \"Random\", \"StanSample\", \"Statistics\", \"StatsFuns\", \"StatsPlots\", \"Test\"]\ngit-tree-sha1 = \"c272a5d52dc5947a84b22b1b6655284d2fb45c8a\"\nuuid = \"98f080ec-61e2-11eb-1c7b-31ea1097256f\"\nversion = \"1.1.0\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"ae4bbcadb2906ccc085cf52ac286dc1377dceccc\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.1.2\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"b084324b4af5a438cd63619fd006614b3b20b87b\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.0.15\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\", \"UnicodeFun\"]\ngit-tree-sha1 = \"d73736030a094e8d24fdf3629ae980217bf1d59d\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.24.3\"\n\n[[PooledArrays]]\ndeps = [\"DataAPI\", \"Future\"]\ngit-tree-sha1 = \"db3a23166af8aebf4db5ef87ac5b00d36eb771e2\"\nuuid = \"2dfb63ee-cc39-5dd5-95bd-886bf059d720\"\nversion = \"1.4.0\"\n\n[[PositiveFactorizations]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"17275485f373e6673f7e7f97051f703ed5b15b20\"\nuuid = \"85a6dd25-e78a-55b7-8502-1745935b8125\"\nversion = \"0.2.4\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[PrettyTables]]\ndeps = [\"Crayons\", \"Formatting\", \"Markdown\", \"Reexport\", \"Tables\"]\ngit-tree-sha1 = \"d940010be611ee9d67064fe559edbb305f8cc0eb\"\nuuid = \"08abe8d2-0d0c-5749-adfa-8a2ac140af0d\"\nversion = \"1.2.3\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[ProgressLogging]]\ndeps = [\"Logging\", \"SHA\", \"UUIDs\"]\ngit-tree-sha1 = \"80d919dee55b9c50e8d9e2da5eeafff3fe58b539\"\nuuid = \"33c8b6b6-d38a-422a-b730-caa89a2f386c\"\nversion = \"0.1.4\"\n\n[[ProgressMeter]]\ndeps = [\"Distributed\", \"Printf\"]\ngit-tree-sha1 = \"afadeba63d90ff223a6a48d2009434ecee2ec9e8\"\nuuid = \"92933f4c-e287-5a05-a399-4b506db050ca\"\nversion = \"1.7.1\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[QuadGK]]\ndeps = [\"DataStructures\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"78aadffb3efd2155af139781b8a8df1ef279ea39\"\nuuid = \"1fd47b50-473d-5c70-9696-f719f8f3bcdc\"\nversion = \"2.4.2\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RangeArrays]]\ngit-tree-sha1 = \"b9039e93773ddcfc828f12aadf7115b4b4d225f5\"\nuuid = \"b3c3ace0-ae52-54e7-9d0b-2c1406fd6b9d\"\nversion = \"0.3.2\"\n\n[[Ratios]]\ndeps = [\"Requires\"]\ngit-tree-sha1 = \"01d341f502250e81f6fec0afe662aa861392a3aa\"\nuuid = \"c84ed2f1-dad5-54f0-aa8e-dbefe2724439\"\nversion = \"0.4.2\"\n\n[[RealDot]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"9f0a1b71baaf7650f4fa8a1d168c7fb6ee41f0c9\"\nuuid = \"c1ae055f-0cd5-4b69-90a6-9a35b1a98df9\"\nversion = \"0.1.0\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.2.1\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"7ad0dfa8d03b7bcf8c597f59f5292801730c55b8\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.4.1\"\n\n[[RecursiveArrayTools]]\ndeps = [\"ArrayInterface\", \"ChainRulesCore\", \"DocStringExtensions\", \"FillArrays\", \"LinearAlgebra\", \"RecipesBase\", \"Requires\", \"StaticArrays\", \"Statistics\", \"ZygoteRules\"]\ngit-tree-sha1 = \"c944fa4adbb47be43376359811c0a14757bdc8a8\"\nuuid = \"731186ca-8d62-57ce-b412-fbd966d074cd\"\nversion = \"2.20.0\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[Rmath]]\ndeps = [\"Random\", \"Rmath_jll\"]\ngit-tree-sha1 = \"bf3188feca147ce108c76ad82c2792c57abe7b1f\"\nuuid = \"79098fc4-a85e-5d69-aa6a-4863f24498fa\"\nversion = \"0.7.0\"\n\n[[Rmath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"68db32dff12bb6127bac73c209881191bf0efbb7\"\nuuid = \"f50d1b31-88e8-58de-be2c-1cc44531875f\"\nversion = \"0.3.0+0\"\n\n[[Roots]]\ndeps = [\"CommonSolve\", \"Printf\", \"Setfield\"]\ngit-tree-sha1 = \"51ee572776905ee34c0568f5efe035d44bf59f74\"\nuuid = \"f2b01f46-fcfa-551c-844a-d8ac1e96c665\"\nversion = \"1.3.11\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[SIMDTypes]]\ngit-tree-sha1 = \"330289636fb8107c5f32088d2741e9fd7a061a5c\"\nuuid = \"94e857df-77ce-4151-89e5-788b33177be4\"\nversion = \"0.1.0\"\n\n[[SLEEFPirates]]\ndeps = [\"IfElse\", \"Static\", \"VectorizationBase\"]\ngit-tree-sha1 = \"1410aad1c6b35862573c01b96cd1f6dbe3979994\"\nuuid = \"476501e8-09a2-5ece-8869-fb82de89a1fa\"\nversion = \"0.6.28\"\n\n[[SciMLBase]]\ndeps = [\"ArrayInterface\", \"CommonSolve\", \"ConstructionBase\", \"Distributed\", \"DocStringExtensions\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"Logging\", \"RecipesBase\", \"RecursiveArrayTools\", \"StaticArrays\", \"Statistics\", \"Tables\", \"TreeViews\"]\ngit-tree-sha1 = \"b3d23aa4e5f621b574b3b0d41c62c8624d27192a\"\nuuid = \"0bca4576-84f4-4d90-8ffe-ffa030f20462\"\nversion = \"1.19.5\"\n\n[[ScientificTypesBase]]\ngit-tree-sha1 = \"185e373beaf6b381c1e7151ce2c2a722351d6637\"\nuuid = \"30f210dd-8aff-4c5f-94ba-8e64358c1161\"\nversion = \"2.3.0\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[SentinelArrays]]\ndeps = [\"Dates\", \"Random\"]\ngit-tree-sha1 = \"f45b34656397a1f6e729901dc9ef679610bd12b5\"\nuuid = \"91c51154-3ec4-41a3-a24f-3f23e20d615c\"\nversion = \"1.3.8\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[Setfield]]\ndeps = [\"ConstructionBase\", \"Future\", \"MacroTools\", \"Requires\"]\ngit-tree-sha1 = \"def0718ddbabeb5476e51e5a43609bee889f285d\"\nuuid = \"efcf1570-3423-57d1-acb7-fd33fddbac46\"\nversion = \"0.8.0\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"f0bccf98e16759818ffc5d97ac3ebf87eb950150\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.8.1\"\n\n[[SplittablesBase]]\ndeps = [\"Setfield\", \"Test\"]\ngit-tree-sha1 = \"39c9f91521de844bad65049efd4f9223e7ed43f9\"\nuuid = \"171d559e-b47b-412a-8079-5efa626c420e\"\nversion = \"0.1.14\"\n\n[[StanBase]]\ndeps = [\"CSV\", \"DataFrames\", \"DelimitedFiles\", \"Distributed\", \"DocStringExtensions\", \"Documenter\", \"Parameters\", \"Random\", \"StanDump\", \"Unicode\"]\ngit-tree-sha1 = \"3d50110ed8c3b5ee768d29600837be594bee7bca\"\nuuid = \"d0ee94f6-a23d-54aa-bbe9-7f572d6da7f5\"\nversion = \"2.6.0\"\n\n[[StanDump]]\ndeps = [\"ArgCheck\", \"DocStringExtensions\"]\ngit-tree-sha1 = \"bfaebe19ada44a52a6c797d48473f1bb22fd0853\"\nuuid = \"9713c8f3-0168-54b5-986e-22c526958f39\"\nversion = \"0.2.0\"\n\n[[StanSample]]\ndeps = [\"CSV\", \"DelimitedFiles\", \"Distributed\", \"DocStringExtensions\", \"MonteCarloMeasurements\", \"NamedTupleTools\", \"OrderedCollections\", \"Random\", \"Requires\", \"StanBase\", \"TableOperations\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"737094d47efd6c3f4f6ac606367dda490d4c0a9c\"\nuuid = \"c1514b29-d3a0-5178-b312-660c88baa699\"\nversion = \"4.4.1\"\n\n[[Static]]\ndeps = [\"IfElse\"]\ngit-tree-sha1 = \"e7bc80dc93f50857a5d1e3c8121495852f407e6a\"\nuuid = \"aedffcd0-7271-4cad-89d0-dc628f76c6d3\"\nversion = \"0.4.0\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3c76dde64d03699e074ac02eb2e8ba8254d428da\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.13\"\n\n[[StatisticalRethinking]]\ndeps = [\"AxisKeys\", \"CSV\", \"DataFrames\", \"Dates\", \"Distributions\", \"DocStringExtensions\", \"Documenter\", \"Formatting\", \"KernelDensity\", \"LinearAlgebra\", \"MCMCChains\", \"MonteCarloMeasurements\", \"NamedArrays\", \"NamedTupleTools\", \"Optim\", \"OrderedCollections\", \"Parameters\", \"ParetoSmooth\", \"ParetoSmoothedImportanceSampling\", \"PrettyTables\", \"Random\", \"Reexport\", \"Requires\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"StructuralCausalModels\", \"Tables\", \"Test\", \"Unicode\"]\ngit-tree-sha1 = \"89dd34c569b411ee10c81855844893639c73fef5\"\nuuid = \"2d09df54-9d0f-5258-8220-54c2a3d4fbee\"\nversion = \"4.4.3\"\n\n[[StatisticalTraits]]\ndeps = [\"ScientificTypesBase\"]\ngit-tree-sha1 = \"730732cae4d3135e2f2182bd47f8d8b795ea4439\"\nuuid = \"64bff920-2084-43da-a3e6-9bb72801c0c9\"\nversion = \"2.1.0\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"0f2aa8e32d511f758a2ce49208181f7733a0936a\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.1.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"2bb0cb32026a66037360606510fca5984ccc6b75\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.13\"\n\n[[StatsFuns]]\ndeps = [\"ChainRulesCore\", \"InverseFunctions\", \"IrrationalConstants\", \"LogExpFunctions\", \"Reexport\", \"Rmath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"bedb3e17cc1d94ce0e6e66d3afa47157978ba404\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.14\"\n\n[[StatsPlots]]\ndeps = [\"Clustering\", \"DataStructures\", \"DataValues\", \"Distributions\", \"Interpolations\", \"KernelDensity\", \"LinearAlgebra\", \"MultivariateStats\", \"Observables\", \"Plots\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"StatsBase\", \"TableOperations\", \"Tables\", \"Widgets\"]\ngit-tree-sha1 = \"d6956cefe3766a8eb5caae9226118bb0ac61c8ac\"\nuuid = \"f3b207a7-027a-5e70-b257-86293d7955fd\"\nversion = \"0.14.29\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.3\"\n\n[[StructuralCausalModels]]\ndeps = [\"CSV\", \"Combinatorics\", \"DataFrames\", \"DataStructures\", \"Distributions\", \"DocStringExtensions\", \"LinearAlgebra\", \"NamedArrays\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"2ff1d30658057a17f3fca1ef501d8911ae66566e\"\nuuid = \"a41e6734-49ce-4065-8b83-aff084c01dfd\"\nversion = \"1.1.0\"\n\n[[SuiteSparse]]\ndeps = [\"Libdl\", \"LinearAlgebra\", \"Serialization\", \"SparseArrays\"]\nuuid = \"4607b0f0-06f3-5cda-b6b1-a6196a1729e9\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableOperations]]\ndeps = [\"SentinelArrays\", \"Tables\", \"Test\"]\ngit-tree-sha1 = \"e383c87cf2a1dc41fa30c093b2a19877c83e1bc1\"\nuuid = \"ab02a1b2-a7df-11e8-156e-fb1833f50b87\"\nversion = \"1.2.0\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"fed34d0e71b91734bf0a7e10eb1bb05296ddbcd0\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.6.0\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[TerminalLoggers]]\ndeps = [\"LeftChildRightSiblingTrees\", \"Logging\", \"Markdown\", \"Printf\", \"ProgressLogging\", \"UUIDs\"]\ngit-tree-sha1 = \"62846a48a6cd70e63aa29944b8c4ef704360d72f\"\nuuid = \"5d786b92-1e48-4d6f-9151-6b4477ca9bed\"\nversion = \"0.1.5\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[Tracker]]\ndeps = [\"Adapt\", \"DiffRules\", \"ForwardDiff\", \"LinearAlgebra\", \"MacroTools\", \"NNlib\", \"NaNMath\", \"Printf\", \"Random\", \"Requires\", \"SpecialFunctions\", \"Statistics\"]\ngit-tree-sha1 = \"bf4adf36062afc921f251af4db58f06235504eff\"\nuuid = \"9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c\"\nversion = \"0.2.16\"\n\n[[TranscodingStreams]]\ndeps = [\"Random\", \"Test\"]\ngit-tree-sha1 = \"216b95ea110b5972db65aa90f88d8d89dcb8851c\"\nuuid = \"3bb67fe8-82b1-5028-8e26-92a6c54297fa\"\nversion = \"0.9.6\"\n\n[[Transducers]]\ndeps = [\"Adapt\", \"ArgCheck\", \"BangBang\", \"Baselet\", \"CompositionsBase\", \"DefineSingletons\", \"Distributed\", \"InitialValues\", \"Logging\", \"Markdown\", \"MicroCollections\", \"Requires\", \"Setfield\", \"SplittablesBase\", \"Tables\"]\ngit-tree-sha1 = \"bccb153150744d476a6a8d4facf5299325d5a442\"\nuuid = \"28d57a85-8fef-5791-bfe6-a80928e7c999\"\nversion = \"0.4.67\"\n\n[[TreeViews]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d0d7a3fe2f30d6a7f833a5f19f7c7a5b396eae6\"\nuuid = \"a2a6695c-b41b-5b7d-aed9-dbfdeacea5d7\"\nversion = \"0.3.0\"\n\n[[Tullio]]\ndeps = [\"ChainRulesCore\", \"DiffRules\", \"LinearAlgebra\", \"Requires\"]\ngit-tree-sha1 = \"0288b7a395fc412952baf756fac94e4f28bfec65\"\nuuid = \"bc48ee85-29a4-5162-ae0b-a64e1601d4bc\"\nversion = \"0.3.2\"\n\n[[Turing]]\ndeps = [\"AbstractMCMC\", \"AdvancedHMC\", \"AdvancedMH\", \"AdvancedPS\", \"AdvancedVI\", \"BangBang\", \"Bijectors\", \"DataStructures\", \"Distributions\", \"DistributionsAD\", \"DocStringExtensions\", \"DynamicPPL\", \"EllipticalSliceSampling\", \"ForwardDiff\", \"Libtask\", \"LinearAlgebra\", \"MCMCChains\", \"NamedArrays\", \"Printf\", \"Random\", \"Reexport\", \"Requires\", \"SciMLBase\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"Tracker\", \"ZygoteRules\"]\ngit-tree-sha1 = \"c40eac01a46b8efc8af9481982a618d6e54b506d\"\nuuid = \"fce5fe82-541a-59a6-adf8-730c64b5f9a0\"\nversion = \"0.19.0\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[UnPack]]\ngit-tree-sha1 = \"387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b\"\nuuid = \"3a884ed6-31ef-47d7-9d2a-63182c4928ed\"\nversion = \"1.0.2\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[UnicodeFun]]\ndeps = [\"REPL\"]\ngit-tree-sha1 = \"53915e50200959667e78a92a418594b428dffddf\"\nuuid = \"1cfade01-22cf-5700-b092-accc4b62d6e1\"\nversion = \"0.4.1\"\n\n[[VectorizationBase]]\ndeps = [\"ArrayInterface\", \"CPUSummary\", \"HostCPUFeatures\", \"Hwloc\", \"IfElse\", \"LayoutPointers\", \"Libdl\", \"LinearAlgebra\", \"SIMDTypes\", \"Static\"]\ngit-tree-sha1 = \"17e5847bb36730d90801170ecd0ce4041a3dde86\"\nuuid = \"3d5dd08c-fd9d-11e8-17fa-ed2836048c2f\"\nversion = \"0.21.22\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"66d72dc6fcc86352f01676e8f0f698562e60510f\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.23.0+0\"\n\n[[WeakRefStrings]]\ndeps = [\"DataAPI\", \"InlineStrings\", \"Parsers\"]\ngit-tree-sha1 = \"c69f9da3ff2f4f02e811c3323c22e5dfcb584cfa\"\nuuid = \"ea10d353-3f73-51f8-a26c-33c1cb351aa5\"\nversion = \"1.4.1\"\n\n[[Widgets]]\ndeps = [\"Colors\", \"Dates\", \"Observables\", \"OrderedCollections\"]\ngit-tree-sha1 = \"80661f59d28714632132c73779f8becc19a113f2\"\nuuid = \"cc8bc4a8-27d6-5769-a93b-9d913e69aa62\"\nversion = \"0.6.4\"\n\n[[WoodburyMatrices]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"de67fa59e33ad156a590055375a30b23c40299d3\"\nuuid = \"efce3f68-66dc-5838-9240-27a6d6f5f9b6\"\nversion = \"0.5.5\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[ZygoteRules]]\ndeps = [\"MacroTools\"]\ngit-tree-sha1 = \"8c1a8e4dfacb1fd631745552c8db35d0deb09ea0\"\nuuid = \"700de1a5-db45-46bc-99cf-38207098b444\"\nversion = \"0.2.2\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─e803d172-2b8a-43b4-b99d-307e64cf29d5\n# ╠═4b348c51-c844-4e64-85e4-a4f7ea952fc9\n# ╠═75ce54b9-b801-412a-b70e-ab5222df137f\n# ╠═77a70403-fa95-4b13-b886-415d1a91f15a\n# ╟─f9ff23ea-fdf2-4d48-bb84-98f40db8603e\n# ╟─821bcd65-4ab5-43e8-837e-8bdf96f24edd\n# ╠═0ccba2cd-c10c-4713-80e1-77e4a3e9c85c\n# ╠═b71b59cb-b9ed-4a18-a713-400d8fb48517\n# ╟─62852231-aebe-43bc-a591-ff3c79651739\n# ╠═2f603bc2-938d-45b4-a9ed-60daa5847af5\n# ╟─3f745e69-690e-4ab9-934f-b05f24f20a98\n# ╠═a88970a9-341c-4e92-891b-6057dbac1e01\n# ╟─e7569635-07ab-4b69-8014-f26d42955fce\n# ╟─d4991ad9-4341-47e8-aee4-9c35cbe28e35\n# ╠═9322d404-9ebd-4dd8-985d-8322f4f77571\n# ╟─7d94a7f1-7ce5-4f6a-ba72-0a8a9cde44e9\n# ╟─19d13362-93a0-4a93-b3bb-6e30d3d934a3\n# ╠═29a1a866-522b-4354-866e-9f121ba378b9\n# ╠═e3cc237b-9997-41b6-8298-1b79e4444662\n# ╟─cb41155d-43a6-4fef-932f-13cabcdf907a\n# ╠═7d29cbaf-2b27-4b4e-8dee-74a049408fba\n# ╟─9d674865-3fed-48a6-a970-d997ae9d7443\n# ╠═aa9be028-c3dc-4e4a-9405-86be642540ca\n# ╟─e61d81ed-761a-450b-9ea0-1398a9ac8e22\n# ╠═a74b283d-febc-40b1-9654-3d63b7d014b2\n# ╟─4dc8aa1b-7544-4a80-9109-a2c9040d9321\n# ╟─e6a3d465-57d2-40aa-b71d-8cca5db234d9\n# ╠═ff957f53-dbc7-4885-9797-61d10b8dac15\n# ╟─06d5c8b7-7a87-4ddb-9c30-d6d623a71814\n# ╠═e29edd1a-890d-4e21-a221-d4311bd845d3\n# ╠═200f0e88-b30f-4aac-a733-a25f5a52c5d8\n# ╠═fbcda425-2e88-4a49-b24b-17894231642e\n# ╟─f67d530a-e56d-408c-8f21-d4e37e8dab42\n# ╟─60a185df-0656-4a46-b301-388407073ab6\n# ╠═9d6afd05-6570-44e0-8b49-5e4bc7e8a76f\n# ╟─cfe67e9f-41bb-419f-96ba-282926de31a2\n# ╠═8409b9f4-7fa5-4f38-9b38-ae34e4c60e83\n# ╟─4e94cf59-81eb-4b99-b048-502f54faee15\n# ╠═76782d05-9e32-424c-a206-8081e0fdd146\n# ╟─e8dd780e-b94d-413c-9b0b-0476817b2094\n# ╠═b80e5ff3-445a-465c-9665-697f5b0b897e\n# ╟─b6057787-3948-482c-be7e-69c4231386b6\n# ╟─d438bddd-9138-410e-ab98-40f7c90e780f\n# ╠═3f4a3b7c-2db7-4d7b-800a-c14968a02855\n# ╟─2d2aa3ef-8fb7-4c69-8869-42e1939dc950\n# ╟─61b5e6a8-3baa-4101-9a21-5d49af43bfe7\n# ╠═35f25d1e-234b-481f-9303-3c5973ab1228\n# ╟─4e20ad94-3011-4b89-b29e-8a793e733e03\n# ╠═ed026592-6cb3-40a3-9f0a-565e14038114\n# ╟─b25c0b7a-4469-4945-be28-bfb2c22103ca\n# ╠═8a0295cc-4f0c-475a-a8c6-ccf2b99ed00f\n# ╟─580db5a8-550a-42d1-9aef-c95f4099a3fa\n# ╠═0bd7dbfe-0689-40d4-8fd0-1fd372b2edc2\n# ╟─534f0c53-da8b-4da5-81d4-c0ab3ceb270b\n# ╠═a28ee7bb-d9d7-43ea-833f-6460a2cf7579\n# ╟─4535c71f-be7c-41e8-940b-57289c83e509\n# ╟─f39cd55f-ed8f-487e-885e-f1e16b78d9dd\n# ╠═cd971faa-315a-4cea-a11a-0cb28f3e3997\n# ╟─a9febef3-06d0-4552-8590-2f165ce36547\n# ╠═7b2588d2-d86d-44fb-9895-d6452875bc47\n# ╟─cc97f4d9-ad00-4d2c-b520-2071b9cf86f6\n# ╠═631bb03b-00a5-466a-be0d-36f86a9721aa\n# ╠═95dc66d6-660a-4b0c-b89d-487a22dfec82\n# ╠═c5570bf1-c04d-41e3-b8ae-6e6dac45cb70\n# ╠═8f945f6c-2561-433b-aedb-3448d2c4b419\n# ╟─ecd23fa3-fdd2-4ffb-a0e9-ad1feee04d22\n# ╠═f10e310f-165b-4b4b-b3e0-66af6430ba4f\n# ╠═4c09eda3-8f4c-4fa2-91ea-99b92cfbb422\n# ╠═1f2c5378-bbcd-4fb7-9130-9c6cebb4c6d4\n# ╟─517d31ba-5843-40a7-ad06-96e7a8ea8845\n# ╠═1cc0a6c1-3fcf-4df3-a8d9-ba3454c0a37b\n# ╠═9a76593b-c9a9-45cc-aca5-9877432baffd\n# ╠═6a7ea8be-bea2-41c4-89ab-9a6bbcfba116\n# ╠═942e3f19-a5c1-430e-a3be-097c53bc7394\n# ╠═6caa4b75-9ac1-496b-a4b2-38b72b203e59\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "d5bd71b511f18df0da22a1e90fd11ee9dc2fd118", "size": 75933, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/09/Chapter_09.jl", "max_stars_repo_name": "SimonAB/StatisticalRethinkingTuring.jl", "max_stars_repo_head_hexsha": "fe8bc9430ef7bed17f532d9b70a5f6a85910266f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/09/Chapter_09.jl", "max_issues_repo_name": "SimonAB/StatisticalRethinkingTuring.jl", "max_issues_repo_head_hexsha": "fe8bc9430ef7bed17f532d9b70a5f6a85910266f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/09/Chapter_09.jl", "max_forks_repo_name": "SimonAB/StatisticalRethinkingTuring.jl", "max_forks_repo_head_hexsha": "fe8bc9430ef7bed17f532d9b70a5f6a85910266f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4801587302, "max_line_length": 467, "alphanum_fraction": 0.7286423558, "num_tokens": 35003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220291, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7653536686839264}}
{"text": "module SimpleLife\nexport life_step, life_step!, random_life\n\n\"\"\"\n`_get(A,i,j,wrap=fasle)` returns `A[i,j]` or `0` if subscripts are out of bounds.\nWith `wrap==true` then the indices are taken modulo the number of rows/columns\nas appropriate.\n\"\"\"\nfunction _get(A::Matrix{T}, i::Int, j::Int, wrap::Bool=false)::T where T<:Number\n    r,c = size(A)\n    if (1<=i<=r) && (1<=j<=c)\n        return @inbounds A[i,j]\n    end\n\n    if !wrap\n        return zero(T)\n    end\n\n    i = mod(i,r)\n    j = mod(j,c)\n    if i==0\n        i=r\n    end\n    if j==0\n        j=c\n    end\n    return @inbounds A[i,j]\nend\n\n\n\"\"\"\n`_neighbor_count(A,i,j,wrap=false)` counts how many neighbors of entry `i,j`\nof matrix `A` are nonzero.\n\"\"\"\nfunction _neighbor_count(A::Matrix{Int},i::Int,j::Int,wrap::Bool=false)::Int\n    return sum(_get(A,p,q,wrap) for p=i-1:i+1 for q=j-1:j+1 if (p,q) != (i,j))\nend\n\n\"\"\"\n`_new_entry(A,i,j)` computes the new entry in cell `i,j`\nif the current state is given by matrix `A`.\n\"\"\"\nfunction _new_entry(A::Matrix{Int},i::Int,j::Int,wrap::Bool=false)\n    nc = _neighbor_count(A,i,j,wrap)\n    if A[i,j]==0\n        if nc==3\n            return 1\n        else\n            return 0\n        end\n    end\n    # so A[i,j] is 1\n    if nc==2 || nc==3\n        return 1\n    else\n        return 0\n    end\nend\n\n\"\"\"\n`life_step(A,wrap=false)` gives the next generation after state `A`\nin Conway's *Game of Life*. With `wrap==true` treats the board toroidally.\n\"\"\"\nfunction life_step(A::Matrix{Int},wrap::Bool=false)::Matrix{Int}\n    r,c = size(A)\n    B = zeros(Int,r,c)\n    for i=1:r\n        for j=1:c\n            @inbounds B[i,j] = _new_entry(A,i,j,wrap)\n        end\n    end\n    return B\nend\n\n\"\"\"\n`life_step!(A,wrap=false)` overwrites `A` with `life_step(A,wrap)`.\nThis function returns `true` if there has been a change to `A`;\notherwise, returns `false` if there was no change.\n\"\"\"\nfunction life_step!(A::Matrix{Int}, wrap::Bool=false)\n    r,c = size(A)\n    B = life_step(A,wrap)\n    change = A!=B\n    for i=1:r\n        for j=1:c\n            @inbounds A[i,j] = B[i,j]\n        end\n    end\n    return change\nend\n\n\n\"\"\"\n`random_life(r,c,p=0.5)` creates a random `r`-by-`c` instance of a life board\nwith density `p`.\n\n`random_life(n,p=0.5)` is equivalent to `random_life(n,n,p)`.\n\"\"\"\nfunction random_life(r::Int, c::Int, p::AbstractFloat=0.5)\n    M = rand(r,c) .< p\n    return Int.(M)\nend\n\nrandom_life(n::Int,p::AbstractFloat=0.5) = random_life(n,n,p)\n\n\"\"\"\n`_life_check(A)` determines if the integer matrix `A` only contains\nzeros and ones.\n\"\"\"\nfunction _life_check(A::Matrix{Int})\n    return 0 <= minimum(A) <= maximum(A) <= 1\nend\n\ninclude(\"visualize.jl\")\n\nend  # module SimpleLife\n", "meta": {"hexsha": "c7d0c777e15c07d3f1a6bc2c7598ef8620031fa8", "size": 2656, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SimpleLife.jl", "max_stars_repo_name": "scheinerman/SimpleLife.jl", "max_stars_repo_head_hexsha": "e9000cae1f24a58b390b014ada0ec69e28a5e576", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-24T16:29:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T22:44:45.000Z", "max_issues_repo_path": "src/SimpleLife.jl", "max_issues_repo_name": "scheinerman/SimpleLife.jl", "max_issues_repo_head_hexsha": "e9000cae1f24a58b390b014ada0ec69e28a5e576", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SimpleLife.jl", "max_forks_repo_name": "scheinerman/SimpleLife.jl", "max_forks_repo_head_hexsha": "e9000cae1f24a58b390b014ada0ec69e28a5e576", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:13:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T01:13:21.000Z", "avg_line_length": 22.7008547009, "max_line_length": 81, "alphanum_fraction": 0.6012801205, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7653204851686022}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction aitoff(l::T, b::T) where {T<:AbstractFloat}\n    l = rem(l, T(360), RoundNearest)\n    alpha2 = deg2rad(l/2)\n    delta = deg2rad(b)\n    r2 = sqrt(T(2))\n    f = 2*r2/pi\n    sin_alpha2, cos_alpha2 = sincos(alpha2)\n    sin_delta, cos_delta = sincos(delta)\n    denom = sqrt(1 + cos_delta * cos_alpha2)\n    return rad2deg(cos_delta * sin_alpha2 * 2 * r2 / denom / f),\n           rad2deg(sin_delta * r2 / denom / f)\nend\n\n\"\"\"\n    aitoff(l, b) -> x, y\n\n### Purpose ###\n\nConvert longitude `l` and latitude `b` to `(x, y)` using an Aitoff projection.\n\n### Explanation ###\n\nThis function can be used to create an all-sky map in Galactic coordinates with\nan equal-area Aitoff projection.  Output map coordinates are zero longitude\ncentered.\n\n### Arguments ###\n\n* `l`: longitude, scalar or vector, in degrees.\n* `b`: latitude, number of elements as `l`, in degrees.\n\nCoordinates can be given also as a 2-tuple `(l, b)`.\n\n### Output ###\n\n2-tuple `(x, y)`.\n\n* `x`: x coordinate, same number of elements as `l`.  `x` is normalized to be in\n  \\$[-180, 180]\\$.\n* `y`: y coordinate, same number of elements as `l`.  `y` is normalized to be in\n  \\$[-90, 90]\\$.\n\n### Example ###\n\nGet \\$(x ,y)\\$ Aitoff coordinates of Sirius, whose Galactic coordinates are\n\\$(227.23, -8.890)\\$.\n\n```jldoctest\njulia> using AstroLib\n\njulia> x, y = aitoff(227.23, -8.890)\n(-137.92196683723276, -11.772527357473054)\n```\n\n### Notes ###\n\nSee AIPS memo No. 46\n(ftp://ftp.aoc.nrao.edu/pub/software/aips/TEXT/PUBL/AIPSMEMO46.PS), page 4, for\ndetails of the algorithm.  This version of `aitoff` assumes the projection is\ncentered at b=0 degrees.\n\nCode of this function is based on IDL Astronomy User's Library.\n\"\"\"\naitoff(l::Real, b::Real) = aitoff(promote(float(l), float(b))...)\n\naitoff(lb::Tuple{Real, Real}) = aitoff(lb...)\n\nfunction aitoff(l::AbstractArray{L}, b::AbstractArray{B}) where {L<:Real,B<:Real}\n    @assert length(l) == length(b)\n    typel = float(L)\n    x = similar(l, typel)\n    y = similar(b, typel)\n    for i in eachindex(l)\n        x[i], y[i] = aitoff(l[i], b[i])\n    end\n    return x, y\nend\n", "meta": {"hexsha": "b9fb3801bb44f394023e1c9e5bb0dc2f6d36ca57", "size": 2171, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/aitoff.jl", "max_stars_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_stars_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2016-09-11T14:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T20:45:36.000Z", "max_issues_repo_path": "src/aitoff.jl", "max_issues_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_issues_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 64, "max_issues_repo_issues_event_min_datetime": "2017-01-19T21:03:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:27:46.000Z", "max_forks_repo_path": "src/aitoff.jl", "max_forks_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_forks_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:11:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:55:21.000Z", "avg_line_length": 26.8024691358, "max_line_length": 81, "alphanum_fraction": 0.6421004146, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.765313708643985}}
{"text": "export quadraticFieldmap, stairsFieldmap, polarFieldmap\n\n\"\"\"\n    quadraticFieldmap(Nx::Int64, Ny::Int64, maxOffresonance::Float64=125.0)\n\nComputes a parabolic fieldmap.\n\"\"\"\nfunction quadraticFieldmap(Nx::Int64, Ny::Int64, maxOffresonance::Float64=125.0)\n  xx = range(-1, stop=1, length=Nx)\n  yy = range(-1, stop=1, length=Ny)\n  fieldmap = zeros(Nx,Ny, 1)\n  for nx=1:Nx\n    for ny=1:Ny\n      fieldmap[nx,ny,1] = maxOffresonance*(xx[nx]^2 + yy[ny]^2) - maxOffresonance\n    end\n  end\n  return fieldmap\nend\n\n\"\"\"\nComputes a polaroid fieldmap.\n\"\"\"\nfunction polarFieldmap(Nx::Int64, Ny::Int64,\n                        maxOffresonance::Float64=125.0;\n                        xCenter::Int64=0,\n                        yCenter::Int64=0\n                       )\n  fieldmap = zeros(Nx,Ny,1)\n  xx = range(-1, stop=1, length=Nx)\n  yy = range(-1, stop=1, length=Ny)\n  for nx=1:Nx\n    for ny=1:Ny\n      fieldmap[nx,ny,1] = maxOffresonance*sqrt(xx[nx]^2 + yy[ny]^2)- maxOffresonance\n    end\n  end\n  return fieldmap\nend\n\n\n\"\"\"\nComputes a fieldmap consisting of stairs, which has discrete linear\nascending/descending values\n\"\"\"\nfunction stairsFieldmap(Nx::Int64, Ny::Int64;\n                        numStairs::Int64=8,\n                        minOffresonance::Float64=-125.0,\n                        maxOffresonance::Float64=125.0,\n                        ascending=true)\n  # Input check for the number of stairs\n  if numStairs < 2 || numStairs > (Nx > Ny ? Ny : Nx)\n    error(\"Number of stairs not used correctly\")\n  end\n  # Allocating output\n  fieldmap = zeros(Nx,Ny)\n  # Determine the height and width of the stairs (e.g for NxN -> deltaX = deltaY)\n  deltaX = Int64(floor((Nx / (numStairs*2) )))\n  deltaY = Int64(floor((Ny / (numStairs*2) )))\n\n  if ascending == true\n    scaling = range(minOffresonance,stop=maxOffresonance,length=numStairs)\n  else\n    scaling = -range(minOffresonance,stop=maxOffresonance,length=numStairs)\n  end\n\n  # Filling (Quarter) Matrix for constructing the stairs\n  partialFieldMap = zeros(Int64(floor((Nx/2))),Int64(floor((Ny/2))))\n\n  for i=1:numStairs\n    partialFieldMap[(i-1)*deltaX+1 : end     , (i-1)*deltaY+1 : i*deltaY  ] .= -1 * scaling[i]\n    partialFieldMap[(i-1)*deltaX+1 : i*deltaX, (i-1)*deltaY+1 : end ]       .= -1 * scaling[i]\n  end\n\n  # Correction if numOfStairs is not divisible by 4 fill the lower right corner of\n  # the upper left (quarter) partial matrix\n  if numStairs % 4 != 0\n    partialFieldMap[numStairs*deltaX:end , numStairs*deltaY:end] .= -1 * scaling[numStairs]\n  end\n\n  # If width or height is not divisible by two the middle row or column(or both)\n  # must be filled manually\n  partSizeX , partSizeY = size(partialFieldMap)\n  xRemainder, yRemainder = Nx%2, Ny%2\n\n  # Rotating and mirroring the filled quarter of the matrix to complete the stairs\n  fieldmap[1:partSizeX                , 1: partSizeY]                 = partialFieldMap\n  fieldmap[1:partSizeX                , partSizeY+1+yRemainder : end] = partialFieldMap[:,end:-1:1]\n  fieldmap[partSizeX+1+xRemainder:end , 1: partSizeY]                 = partialFieldMap[end:-1:1,:]\n  fieldmap[partSizeX+1+xRemainder:end , partSizeY+1+yRemainder : end] = rot180(partialFieldMap)\n\n  # Filling the row or column,needed when number of rows/columns is odd\n  if xRemainder != 0 && yRemainder != 0\n    midXIndx, midYIndx  = Int64(ceil(Nx/2)), Int64(ceil(Ny/2))\n    fieldmap[midXIndx,: ] = fieldmap[midXIndx-1,:]\n    fieldmap[:,midYIndx ] = fieldmap[:,midYIndx-1]\n  elseif xRemainder != 0\n    midXIndx = Int64(ceil(Nx/2))\n    fieldmap[midXIndx,: ] = fieldmap[midXIndx-1,:]\n  elseif yRemainder != 0\n    midYIndx = Int64(ceil(Ny/2))\n    fieldmap[:,midYIndx ] = fieldmap[:,midYIndx-1]\n  end\n\n  return reshape(fieldmap,Nx,Ny,1)\nend\n", "meta": {"hexsha": "f20a670566677ce28094f67aab9ae17eb0c74a83", "size": 3713, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Simulation/Fieldmap.jl", "max_stars_repo_name": "UnofficialJuliaMirror/MRIReco.jl-bdf86e05-2d2b-5731-a332-f3fe1f9e047f", "max_stars_repo_head_hexsha": "f8ce9fcd09d81c166bae1359884489e7b0da0954", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2019-04-22T20:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T10:49:45.000Z", "max_issues_repo_path": "src/Simulation/Fieldmap.jl", "max_issues_repo_name": "UnofficialJuliaMirror/MRIReco.jl-bdf86e05-2d2b-5731-a332-f3fe1f9e047f", "max_issues_repo_head_hexsha": "f8ce9fcd09d81c166bae1359884489e7b0da0954", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 49, "max_issues_repo_issues_event_min_datetime": "2018-11-03T09:34:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T15:13:07.000Z", "max_forks_repo_path": "src/Simulation/Fieldmap.jl", "max_forks_repo_name": "UnofficialJuliaMirror/MRIReco.jl-bdf86e05-2d2b-5731-a332-f3fe1f9e047f", "max_forks_repo_head_hexsha": "f8ce9fcd09d81c166bae1359884489e7b0da0954", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2019-04-23T21:34:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T08:34:17.000Z", "avg_line_length": 35.3619047619, "max_line_length": 99, "alphanum_fraction": 0.6466469162, "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7653137056505095}}
{"text": "function r2cf(n1::Integer, n2::Integer)\n    ret = Int[]\n    while n2 != 0\n        n1, (t1, n2) = n2, divrem(n1, n2)\n        push!(ret, t1)\n    end\n    ret\nend\nr2cf(r::Rational) = r2cf(numerator(r), denominator(r))\n\nfunction r2cf(n1, n2, maxiter=20)\n    ret = Int[]\n    while n2 != 0 && maxiter > 0\n        n1, (t1, n2) = n2, divrem(n1, n2)\n        push!(ret, t1)\n        maxiter -= 1\n    end\n    ret\nend\n\nmutable struct NG\n    a1::Int\n    a::Int\n    b1::Int\n    b::Int\nend\n\nfunction ingress(ng, n)\n    ng.a, ng.a1= ng.a1, ng.a + ng.a1 * n\n    ng.b, ng.b1 = ng.b1, ng.b + ng.b1 * n\nend\n\nneedterm(ng) = ng.b == 0 || ng.b1 == 0 || !(ng.a // ng.b == ng.a1 // ng.b1)\n\nfunction egress(ng)\n    n = ng.a // ng.b\n    ng.a, ng.b = ng.b, ng.a - ng.b * n\n    ng.a1, ng.b1 = ng.b1, ng.a1 - ng.b1 * n\n    r2cf(n)\nend\n\negress_done(ng) = (if needterm(ng) ng.a, ng.b = ng.a1, ng.b1 end; egress(ng))\n\ndone(ng) = ng.b == 0 && ng.b1 == 0\n\nfunction testng()\n    data = [[\"[1;5,2] + 1/2\",      [2,1,0,2], [13,11]],\n        [\"[3;7] + 1/2\",        [2,1,0,2], [22, 7]],\n        [\"[3;7] divided by 4\", [1,0,0,4], [22, 7]],\n        [\"[1;1] divided by sqrt(2)\", [0,1,1,0], [1,sqrt(2)]]]\n\n    for d in data\n        str, ng, r = d[1], NG(d[2]...), d[3]\n        print(rpad(str, 25), \"->\")\n        for n in r2cf(r...)\n            if !needterm(ng)\n                print(\" $(egress(ng))\")\n            end\n            ingress(ng, n)\n        end\n        while true\n            print(\" $(egress_done(ng))\")\n            if done(ng)\n                println()\n                break\n            end\n        end\n    end\nend\n\ntestng()\n", "meta": {"hexsha": "6e43c11493525e69b1fa2cf3f82bcd4bfe58fa02", "size": 1592, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n-.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n-.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n-.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1111111111, "max_line_length": 77, "alphanum_fraction": 0.4478643216, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.765313703681633}}
{"text": "#Code written by Scott Hanna 6/27/2019\r\n#Last Update: 8/14/2019\r\n#Contact: shanna7@jhu.edu\r\n#\r\n#The Modulus type is here defined as the residue class of a modulo n where\r\n#[a] = a + nZ := {a +nz | z ∈ Z}\r\n#the quotient set with respect to Rn, is often denoted by Z/nZ.\r\n#Thus, Z/nZ := {[0], [1], . . . , [n − 1]}.\r\n#\r\n#The set of all classes modulo n is a field only in the case that n is prime.\r\n#i.e. it only guarantees an inverse element if n is prime.  If n is not prime\r\n#it is possible that a particular value, a,has an inverse (that is a*a^-1 = 1),\r\n#but the set is still not considered a field.\r\nmodule ModulusN\r\n\r\nusing LinearAlgebra, Random\r\nimport Base: convert,promote_rule,+,-,*,/,zero,one,abs,abs2,^,<,<=,>,>=,==,isequal,inv,isnan\r\nimport LinearAlgebra: conj\r\nimport Random: rand\r\n\r\nexport getVal,getMod,Modulus,hasInverse\r\n\r\nstruct Modulus{N} <: Number\r\n    val::Real\r\n    function Modulus{N}(val) where N\r\n        @assert N isa Real\r\n        @assert N != 0\r\n        new{N}(mod(val,N))\r\n    end\r\n    Modulus{N}(x::Modulus{N}) where N = Modulus{N}(x.val)\r\nend\r\n\r\nconvert(::Modulus{N}, x::M) where {N,M<:Real} = Modulus{N}(x)\r\npromote_rule(::Type{Modulus{N}}, ::Type{M}) where {N,M<:Real} = Modulus{N}\r\npromote_rule(::Type{M}, ::Type{Modulus{N}}) where {N,M<:Real} = Modulus{N}\r\n\r\ngetVal(x::Modulus{N}) where N = return x.val\r\ngetMod(x::Modulus{N}) where N = return N\r\n\r\n+(x::Modulus{N},y::Modulus{N}) where N = Modulus{N}(x.val + y.val)\r\n-(x::Modulus{N},y::Modulus{N}) where N = Modulus{N}(x.val - y.val)\r\n*(x::Modulus{N},y::Modulus{N}) where N = Modulus{N}(x.val * y.val)\r\n/(x::Modulus{N},y::Modulus{N}) where N = inv(y) * x\r\n-(x::Modulus{N}) where N = Modulus{N}(-x.val)\r\nzero(x::Modulus{N}) where N = Modulus{N}(0)\r\none(x::Modulus{N}) where N = Modulus{N}(1)\r\nabs(x::Modulus{N}) where N = Modulus{N}(abs(x.val))\r\n^(x::Modulus{N}, y::Int) where N = Modulus{N}(x.val^y)\r\nabs2(x::Modulus{N}) where N = abs(x)^2\r\n\r\n<(x::Modulus{N}, y::Modulus{N}) where N = x.val < y.val\r\n<=(x::Modulus{N}, y::Modulus{N}) where N = x.val <= y.val\r\n>(x::Modulus{N}, y::Modulus{N}) where N = x.val > y.val\r\n>=(x::Modulus{N}, y::Modulus{N}) where N = x.val >= y.val\r\n==(x::Modulus{N}, y::Modulus{M}) where {N,M} = x.val == y.val && N==M\r\nisequal(x::Modulus{N}, y::Modulus{M}) where {N,M} = x.val == y.val && N==M\r\n\r\nisnan(x::Modulus{N}) where N = isnan(x.val)\r\nconj(x::Modulus{N}) where N = abs(x)\r\n\r\nfunction inv(x::Modulus{N}) where N\r\n    divs,v = gcdx(x.val,N)\r\n    if divs != 1 || N == 1\r\n        error(\"No Inverse Exists\")\r\n    end\r\n    return Modulus{N}(v)\r\nend\r\n\r\nfunction hasInverse(x::Modulus{N}) where N\r\n    return gcd(x.val,N)==1 && N != 1\r\nend\r\n\r\nrand(rng::AbstractRNG, ::Random.SamplerType{Modulus{N}}) where N = Modulus{N}(rand(rng,Int))\r\n\r\nend #end module ModulusN\r\n", "meta": {"hexsha": "0a30caa29504c222714a42e6a0fd15ada07a368d", "size": 2776, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ModulusN.jl", "max_stars_repo_name": "sphanna/ModulusN", "max_stars_repo_head_hexsha": "1e8144109e4a22e1ba65eb8ac4fe4363953e4774", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ModulusN.jl", "max_issues_repo_name": "sphanna/ModulusN", "max_issues_repo_head_hexsha": "1e8144109e4a22e1ba65eb8ac4fe4363953e4774", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ModulusN.jl", "max_forks_repo_name": "sphanna/ModulusN", "max_forks_repo_head_hexsha": "1e8144109e4a22e1ba65eb8ac4fe4363953e4774", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5263157895, "max_line_length": 93, "alphanum_fraction": 0.6102305476, "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7653137015956717}}
{"text": "module Radon\n\nexport radon\nexport backprojection, backprojection_anim\nexport iradon, fitered_backprojection, SART\n\n\"\"\"\n    radon(f::Matrix{T}; θ=Vector(0:(π/180):π-π/180)::Vector{T}, in_circle=true) where {T<:Real}\n\nreturn Radon transform of `f`.\n\n# Keyword arguments\n\n- `f`: 2-dimension array.(phantom image)\n- `θ`: projection angle.(radian)\n- `in_circle`: \n\"\"\"\nfunction radon(f::Matrix{T}; θ=Vector(0:(π/180):π-π/180)::Vector{T}, in_circle=true) where {T<:Real}\n    ℛf = zeros(maximum(size(f)), length(θ))\n    \n    slim, θlim = size(ℛf)\n    ylim, xlim = size(f)\n\n    if in_circle == true\n        L = ylim\n    else\n        L = round(Int64, hypot(xlim, ylim))\n    end\n    \n    cos_ = cos.(θ)\n    sin_ = sin.(θ)\n\n    s = LinRange(-L/2, L/2, slim)\n    t = LinRange(-L/2, L/2, L)\n    \n    for sᵢ ∈ 1:slim, θᵢ ∈ 1:θlim\n        for l ∈ 1:L\n            x = round(Int64, xlim/2 + s[sᵢ]*cos_[θᵢ] + t[l]*sin_[θᵢ])\n            y = round(Int64, ylim/2 - t[l]*cos_[θᵢ] + s[sᵢ]*sin_[θᵢ])\n            if 1 ≤ x ≤ xlim && 1 ≤ y ≤ ylim\n                ℛf[sᵢ, θᵢ] += f[end-y+1, x]\n            end\n        end\n    end\n    \n    return ℛf\nend\n\n\"\"\"\n    backprojection(ℛf)(f::Matrix{T}, θ::Vector{T}) where {T<:Real}\n\nreturn [back projection](https://freshrimpsushi.github.io/posts/back-projection-dual-transform-of-radon-transform/) of `ℛf`\n\n# Keyword arguments\n\n- `ℛf`: 2d array w.r.t. Radon transform of 'f'\n- `θ`: projection angle(radian)\n\"\"\"\nfunction backprojection(ℛf, θ = 0:π/180:π-π/180)\n    slim, θlim = size(ℛf)\n    reconstructed_image = zeros(slim, slim)\n    \n    ylim, xlim = size(reconstructed_image)\n    L = round(Int64, hypot(xlim, ylim))\n    \n    x= range(-xlim/2+1, xlim/2, xlim)\n    y= range(ylim/2, -ylim/2+1, ylim)\n\n    X = x'.*ones(xlim)\n    Y = ones(ylim)'.*y\n\n    s = range(-L/2, L/2, length=slim)\n\n    for (value, angle) ∈ zip(eachcol(ℛf), θ)\n        S = X.*cos(angle) + Y.*sin(angle)\n        interpolation = LinearInterpolation(s, value, extrapolation_bc=Line())\n        reconstructed_image .+= interpolation.(S)\n    end\n    return reconstructed_image\nend\n\n\"\"\"\n    backprojection_anim(f::Matrix{T}, θ::Vector{T}) where {T<:Real}\n\nreturn animation for calculation backprojection of ℛf\n\n# Keyword arguments\n\n- `ℛf`: 2d array w.r.t. Radon transform of 'f'\n- `θ`: projection angle(radian)\n\"\"\"\nfunction backprojection_anim(ℛf)\n    slim, θlim = size(ℛf)\n    reconstructed_image = zeros(slim, slim)\n\n    slim, θlim= size(ℛf)\n    ylim, xlim = size(reconstructed_image)\n    L = round(Int64, hypot(xlim, ylim))\n\n    x= range(-xlim/2+1, xlim/2, xlim)\n    y= range(ylim/2, -ylim/2+1, ylim)\n\n    X = x'.*ones(xlim)\n    Y = ones(ylim)'.*y\n\n    θ = 0 : π/θlim : π-π/θlim\n    s = range(-L/2, L/2, length=slim)\n\n    anim = Animation()\n    for (value, angle) ∈ zip(eachcol(ℛf), θ)\n        S = X.*cos(angle) + Y.*sin(angle)\n        interpolation = LinearInterpolation(s, value, extrapolation_bc=Line())\n        reconstructed_image .+= interpolation.(S)\n        frame(anim, heatmap(reverse(reconstructed_image, dims=1)))\n    end\n    for _ ∈ 1:80\n        frame(anim, heatmap(reverse(reconstructed_image, dims=1)))\n    end\n    return anim\nend\n\n\"\"\"\n    iradon(ℛf, method=\"fbp\")\n\nreturn Radon transform of `f`\n\n# Keyword arguments\n\n- `f`: phantom\n- `θ`: projection angle\n\"\"\"\nfunction iradon(ℛf, method=\"fbp\")\n    \n    if method == \"fbp\"\n        reconstructed_f = fitered_backprojection(ℛf)\n    end\n\n    return reconstructed_f\nend\n\n\"\"\"\n    fitered_backprojection(ℛff::Matrix{T}, θ::Vector{T}) where {T<:Real}\nreturn f\n\n# Keyword arguments\n\n- `ℛf`: 2d array w.r.t. Radon transform of `f`\n- `θ`: projection angle\n\"\"\"\nfunction fitered_backprojection(ℛf)\n    N = size(ℛf)[1]\n    \n    ℱℛf = fft(ℛf, [1])\n    \n    fourier_filter = abs.(fftfreq(N))    \n    filterd_ℱℛf = ℱℛf .* fourier_filter\n\n    ℱ⁻¹_filterd_ℱℛf = real.(ifft(filterd_ℱℛf, [1]))\n\n    reconstructed_f = (π/360)*backprojection(ℱ⁻¹_filterd_ℱℛf)\n    return reconstructed_f\nend\n\n\"\"\"\n    SART(ℛf)\nreturn Radon transform of `f`\n\n# Keyword arguments\n\n- `ℛf`: 2d array w.r.t. Radon transform of 'f'\n- `θ`: projection angle\n\"\"\"\nfunction SART(ℛf)\nend\n\nend # module", "meta": {"hexsha": "651938c13e63dc4224745280a7c15023d2f286ea", "size": 4090, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Radon.jl", "max_stars_repo_name": "physimatics/Tomography.jl", "max_stars_repo_head_hexsha": "97bbddeb5b74026f64751b2948d292d339df021e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-20T08:03:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T06:55:22.000Z", "max_issues_repo_path": "src/Radon.jl", "max_issues_repo_name": "physimatics/Tomography.jl", "max_issues_repo_head_hexsha": "97bbddeb5b74026f64751b2948d292d339df021e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Radon.jl", "max_forks_repo_name": "physimatics/Tomography.jl", "max_forks_repo_head_hexsha": "97bbddeb5b74026f64751b2948d292d339df021e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-11T04:26:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T04:26:55.000Z", "avg_line_length": 23.2386363636, "max_line_length": 123, "alphanum_fraction": 0.6100244499, "num_tokens": 1435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7653136981262565}}
{"text": "# Helper function for the PCA demo\n\nmutable struct pPCAParams\n    W::Matrix{Float64}\n    m::Vector{Float64}\n    v::Float64\nend\n\nfunction readDataSet(filename)\n    f = open(filename);\n    data = nothing\n    for line in eachline(f)\n        row = map((s) -> parse(Int, s), split(replace(line, \"  \" => \" \"), \" \"))\n        data = (data == nothing) ? row' : vcat(data, row')\n    end\n    close(f)\n\n    return data\nend\n\nfunction pPCA(X::Matrix, M::Int64)\n    # Implement probabilistic PCA using the EM algorithm\n    # X collects the data points on its columns\n    # X may contain missing values, indicated by NaN\n\n    # Probabilistic model:\n    # x[n] = W*z[n] + m + ε, where W is a matrix, m is a vector and ε is a noise term\n    # z[n] ~ N(0,I), where I is the identity matrix\n    # ε ~ N(0, v*I), where v is a scalar\n    N = size(X, 2); D = size(X, 1)\n    missing_values = isnan.(X)\n    has_missing_values = sum(missing_values) > 0\n    # Find row means of X, ignoring missing values\n    if has_missing_values\n        X[findall(missing_values)] .= 0\n        m = ( sum(X, dims=2) ./ (N*ones(D) - sum(missing_values,dims=2)) )[:,1] # [:,1] makes sure this is a vector\n        X[findall(missing_values)] .= NaN\n        observed_d = [findall(.!missing_values[:,n]) for n=1:N] # observed dimensions for every data vector\n        observed_n = [findall(.!missing_values[d,:]) for d=1:D] # observed value indexes per dimension\n        x_observed = [X[observed_d[n],n] for n=1:N]  # data vectors without the missing data\n    else    \n        m = (sum(X, dims=2) ./ N)[:,1] # [:,1] makes sure this is a vector\n        _X = X .- m # shift data to be zero-mean\n    end \n    # Initialize variables\n    θ = pPCAParams(Matrix{Float64}(undef,D,M), m, 1.0) # θ holds the parameters\n    Mz = randn(M,N)              # Mz[:,n] = MEAN[z[n]]\n    Σz = [zeros(M,M) for n=1:N]  # Σz[n] = COV[z[n]]\n\n    function eStep!(Mz, Σz)\n        # Update Mz and Σz\n        W = θ.W; v = θ.v\n\n        if has_missing_values\n            for n=1:N\n                _W = W[observed_d[n],:]\n                _x = x_observed[n] - θ.m[observed_d[n]]\n                M_inv = inv(_W'*_W + v*Matrix{Float64}(I, M, M))\n                Σz[n] = v * M_inv\n                Mz[:,n] = M_inv * _W' * _x\n            end\n        else\n          \n            M_inv = inv(W'*W + v*Matrix{Float64}(I, M, M))\n            Mz[:] = M_inv * W' * _X\n            Σz[1] = v * M_inv # COV[z[n]] is equal for all n. We only update the one for n=1\n        end\n    end\n\n    function mStep!(θ)\n        # Update W, m, v\n        if has_missing_values\n            m = zero(θ.m)\n            for n=1:N\n                m[observed_d[n]] += x_observed[n] .- (θ.W[observed_d[n],:] * Mz[:,n])[:,1]\n            end\n            m = m ./ (N .- sum(missing_values, dims=2)[:,1])\n            θ.m = m\n\n            for d=1:D\n                A = inv(Mz[:,observed_n[d]]*Mz[:,observed_n[d]]' + sum(Σz[observed_n[d]]))\n                b = zeros(M)\n                for n in observed_n[d]\n                    b += Mz[:,n]*(X[d,n] .- m[d])\n                end\n                θ.W[d,:] = ( A * b )'\n            end\n            W = θ.W\n\n            θ.v = 0.0\n            for n=1:N\n                for d in observed_d[n]\n                    θ.v +=  (X[d,n] .- (W[d,:]'*Mz[:,n])[1] - m[d])^2 + (W[d,:]' * Σz[n] * W[d,:])[1]\n                end\n            end\n            θ.v = θ.v / (N*D-sum(missing_values))\n\n        else\n            # no need to update m\n            W = _X * Mz' * inv(Mz*Mz' + N*Σz[1])\n            θ.W = W\n            θ.v = sum((_X - W*Mz).^2)/(N*D) + tr(W*Σz[1]*W')/D\n        end\n    end\n\n    for i=1:30 # Here should be a decent convergence check, but hey, this also works...\n        mStep!(θ)\n        eStep!(Mz, Σz)\n    end\n\n    return (θ, Mz) # Mz is actually redundant, but we return it for convenient plotting\nend\n", "meta": {"hexsha": "6e1491e0c407d585a63cc2a05a8c166570d29d3d", "size": 3832, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lessons/notebooks/scripts/pca_demo_helpers.jl", "max_stars_repo_name": "Yikeru/BMLIP", "max_stars_repo_head_hexsha": "296f5330210d387809b2c3ce7a6847f2bd69b24c", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-09-14T17:34:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T18:29:11.000Z", "max_issues_repo_path": "lessons/notebooks/scripts/pca_demo_helpers.jl", "max_issues_repo_name": "Yikeru/BMLIP", "max_issues_repo_head_hexsha": "296f5330210d387809b2c3ce7a6847f2bd69b24c", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2015-08-18T11:30:12.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-03T15:17:33.000Z", "max_forks_repo_path": "lessons/notebooks/scripts/pca_demo_helpers.jl", "max_forks_repo_name": "Yikeru/BMLIP", "max_forks_repo_head_hexsha": "296f5330210d387809b2c3ce7a6847f2bd69b24c", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-03-18T14:05:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T14:35:32.000Z", "avg_line_length": 33.9115044248, "max_line_length": 115, "alphanum_fraction": 0.4926931106, "num_tokens": 1254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258009, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7653136943549205}}
{"text": "# function ⋃(Sets...)\n#     return reduce(∪, Sets)\n# end\nconst ⋃ = union\n\nfunction ∂(Simplex)\n    # if !(Simplex |> issorted) @warn \"Simplex $Simplex is not sorted\" end\n    faces = [setdiff(Simplex, v) for v in reverse(Simplex)]\n    return faces\nend\n\nfunction faces(Simplex::Set)\n    return Set([setdiff(Simplex, v) for v in Simplex])\nend\nfaces(Set([3,5,3,2]))\n∂([1,2,3])\n∂([1,3,2])", "meta": {"hexsha": "b1da1d387f9880c2f5dcf409bf95e5719a419fb9", "size": 382, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/complices/chaincomplex.jl", "max_stars_repo_name": "KNU-MATH-AI/TopologicalDataAnalysis.jl", "max_stars_repo_head_hexsha": "bcc6d282d35f3cc6579d2382afa9ba6e6c25bda1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/complices/chaincomplex.jl", "max_issues_repo_name": "KNU-MATH-AI/TopologicalDataAnalysis.jl", "max_issues_repo_head_hexsha": "bcc6d282d35f3cc6579d2382afa9ba6e6c25bda1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-03T19:17:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T19:17:28.000Z", "max_forks_repo_path": "src/complices/chaincomplex.jl", "max_forks_repo_name": "KNU-MATH-AI/TopologicalDataAnalysis.jl", "max_forks_repo_head_hexsha": "bcc6d282d35f3cc6579d2382afa9ba6e6c25bda1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4705882353, "max_line_length": 74, "alphanum_fraction": 0.6282722513, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.765313693954334}}
{"text": "\"\"\"\n    function discrete_gamma_rates(α::T, β::S,k::Int64, method::Symbol=:mean; sig::Int64=1)::Array{Float64} where {T<:Real, S<:Real}\n\nThis function calculates the rates of the discretized gamma distribution.\nIt returns a vector of either the mean or the median weights in each category,\nsuch that each category is of equal proportion.\n\nSee: Yang, 1994, Maximum likelihood phylogenetic estimation from DNA sequences\nwith variable rates over sites: Approximate methods. (https://doi.org/10.1007/BF00160154)\n\"\"\"\nfunction discrete_gamma_rates(α::T, β::S,k::Int64, method::Symbol=:mean; sig::Int64=1)::Array{Float64} where {T<:Real, S<:Real}\n    meanvals = Array{Float64, 1}(undef, k)\n    factor::Float64 = α/β*k\n\n    if method==:median\n        meanvals .= median_boundaries(α, β, k)\n        t = sum(meanvals)\n        meanvals .*= (factor / t)\n    else\n        meanvals .= mean_boundaries(α, β, k)\n        @inbounds @simd for i in 1:k-1\n            meanvals[i] = gamma_inc(α+1,meanvals[i]*β, sig)[1]\n        end\n        meanvals[k] = 1.0\n        @inbounds for i in k:-1:2\n            meanvals[i] -= meanvals[i-1]\n            meanvals[i] *= factor\n        end\n        meanvals[1] *= factor\n    end\n    meanvals\nend\n\n#### helper functions for boundaries of rate categories ####\n\nfunction mean_boundaries(α::T, β::S, k::Int64)::Array{Float64} where {T<:Real, S<:Real}\n    ch = Chisq((2*α)/(2*β))\n    boundaries = Array{Float64, 1}(undef, k)\n    for i in 1:k-1\n        boundaries[i] = quantile(ch, i/k)/(2*β)\n    end\n    boundaries\nend\n\nfunction median_boundaries(α::T, β::S, k::Int64)::Array{Float64} where {T<:Real, S<:Real}\n    ch = Chisq((2*α)/(2*β))\n    boundaries = Array{Float64, 1}(undef, k)\n    for i in 1:k\n        boundaries[i] = quantile(ch, ((i-1)*2+1)/(2*k))\n    end\n    return boundaries\nend\n", "meta": {"hexsha": "83fb81c7e02c1e4759ea68643328f0412284ff9a", "size": 1801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Likelihood/Rates.jl", "max_stars_repo_name": "Asaber5492/MCPhylo.jl", "max_stars_repo_head_hexsha": "91a38a42917d41169932b1099ae56c1402ae734e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Likelihood/Rates.jl", "max_issues_repo_name": "Asaber5492/MCPhylo.jl", "max_issues_repo_head_hexsha": "91a38a42917d41169932b1099ae56c1402ae734e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Likelihood/Rates.jl", "max_forks_repo_name": "Asaber5492/MCPhylo.jl", "max_forks_repo_head_hexsha": "91a38a42917d41169932b1099ae56c1402ae734e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9811320755, "max_line_length": 131, "alphanum_fraction": 0.6268739589, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.8198933271118222, "lm_q1q2_score": 0.7653136917653435}}
{"text": "\"\"\"\n    analytic_histogram(d::Distributions.UnivariateDistribution, G::LinRange; normalize=true)\n\nCompute the probability mass of `d` in equally-sized intervals with midpoints given by `G`.\n\nIf `normalize`, then the probabilities are re-scaled such that their sum is 1.\n\"\"\"\nfunction analytic_histogram(d::Distributions.UnivariateDistribution,\n                            G::LinRange;\n                            normalize=true)\n    cdf(x) = Distributions.cdf(d, x)\n\n    mps = get_midpoints(G)\n    hist = zeros(length(G))\n    for i in eachindex(hist)\n        hist[i] = cdf(mps[i + 1]) - cdf(mps[i])\n    end\n\n    if normalize\n        s = sum(hist)\n        hist .= hist ./ s\n    end\n\n    return hist\nend\n\n# aux for analytic_histogram\nfunction get_midpoints(G::LinRange)\n    half_step = step(G) / 2\n    return LinRange(first(G) - half_step,\n                    last(G) + half_step,\n                    length(G) + 1)\nend\n", "meta": {"hexsha": "b9302c931ca6585e6577c84d294d993f8dd7f3ec", "size": 917, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/statistics.jl", "max_stars_repo_name": "ruairidhs/RSUtils.jl", "max_stars_repo_head_hexsha": "485567ac2f9604249d5e121936733219438e251e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/statistics.jl", "max_issues_repo_name": "ruairidhs/RSUtils.jl", "max_issues_repo_head_hexsha": "485567ac2f9604249d5e121936733219438e251e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/statistics.jl", "max_forks_repo_name": "ruairidhs/RSUtils.jl", "max_forks_repo_head_hexsha": "485567ac2f9604249d5e121936733219438e251e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9705882353, "max_line_length": 92, "alphanum_fraction": 0.6074154853, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7653079393441072}}
{"text": "using Base: front, tail\n\n\"\"\"\n    ⊗(t1::Tensor{T}, t2::Tensor{S}) where {T,S} -> Tensor{promote_type(T, S)}\n\nComputes the outer product of the tensors `t1` and `t2`, also referred to as the tensor\nproduct of `t1` and `t2`.\nArguments can be of arbitrary size and dimension.\n\n# Arguments\n- `t1::Tensor{T}`: the first factor\n- `t2::Tensor{S}`: the second factor\n\n# Returns\n- `Tensor{promote_type(T, S)}`: the outer product of `t1` and `t2`\n\"\"\"\nfunction ⊗(t1::Tensor{T}, t2::Tensor{S}) where {T,S}\n    res = Array{promote_type(T, S)}(undef, size(t1)..., size(t2)...)\n\n    j, k = 1, 1\n    for i in eachindex(res)\n        @inbounds res[i] = t1.data[j] * t2.data[k]\n        j = j % length(t1) + 1\n        k += j == 1 ? 1 : 0\n    end\n\n    return Tensor(res)\nend\n\n\"\"\"\n    ⊗(ts...) -> Tensor{promote_type(eltype.(ts)...)}\n\nComputes the outer product of an arbitrary number of tensors `ts...`. The empty outer\nproduct is defined as `Tensor(1)` (i.e., the neutral element of the outer product).\nArguments can be of arbitrary size and dimension.\n\n# Arguments\n- `ts...`: the (possibly empty) list of tensors to be multiplied\n\n# Returns\n- `Tensor{promote_type(eltype.(ts)...)}`: the outer product of the tensors `ts...`\n\"\"\"\n⊗(ts...) = reduce(⊗, ts; init=Tensor(1))\n\n\"\"\"\n    ⋅(t1::Tensor{T}, t2::Tensor{S}) where {T,S} -> Tensor{promote_type(T, S)}\n\nComputes the inner product of the tensors `t1` and `t2`, also referred to as the scalar\nproduct of `t1` and `t2`.\nArguments need to be of non-zero dimension and the last dimension of `t1` needs to match the\nfirst dimension of `t2`.\n\n# Arguments\n- `t1::Tensor{T}`: the first factor\n- `t2::Tensor{S}`: the second factor\n\n# Returns\n- `Tensor{promote_type(T, S)}`: the inner product of `t1` and `t2`\n\n# Throws\n- `ArgumentError`: if either `t1` or `t2` is 0-dimensional\n- `DimensionMismatch`: if the last dimension of `t1` does not match the first dimension of\n    `t2`\n\"\"\"\nfunction ⋅(t1::Tensor{T}, t2::Tensor{S}) where {T,S}\n    @argcheck ndims(t1) > 0\n    @argcheck ndims(t2) > 0\n    @argcheck last(size(t1)) == first(size(t2)) DimensionMismatch\n\n    return pushover(conj(t1), t2, ndims(t1), 1)\nend\n\n\"\"\"\n    contract(t::Tensor, d1::Integer, d2::Integer) -> Tensor\n\nComputes the contraction of the tensor `t` along the dimensions `d1` and `d2`.\n`d1` and `d2` need to be distinct, valid indices for the dimensions of `t`. Additionally,\nthe `d1`-th dimension of `t` has to match its `d2`-th dimension.\n\n# Arguments\n- `t::Tensor`: the tensor to be contracted\n- `d1::Integer`: the first contraction dimension\n- `d2::Integer`: the second contraction dimension\n\n# Returns\n- `Tensor`: the contracted tensor\n\n# Throws\n- `ArgumentError`: if `d1` and `d2` are not distinct\n- `BoundsError`: if `d1` and `d2` do not index valid dimensions of `t`\n- `DimensionMismatch`: if the `d1`-th dimension does not match the `d2`-th dimension of `t`\n\"\"\"\nfunction contract(t::Tensor, d1::Integer, d2::Integer)\n    @argcheck d1 != d2\n    @argcheck 1 <= d1 <= ndims(t) BoundsError(size(t), d1)\n    @argcheck 1 <= d2 <= ndims(t) BoundsError(size(t), d2)\n    @argcheck size(t, d1) == size(t, d2) DimensionMismatch\n\n    # allow more efficient access of the needed (column-major) array elements\n    a = permutedims(t.data, (d1, d2, Tuple(k for k in 1:ndims(t) if k != d1 && k != d2)...))\n\n    res = Array{eltype(t)}(undef, size(a)[3:ndims(a)])\n    inds = CartesianIndices(res)\n\n    # NOTE: replacing the cartesian indexing by on-the-fly linear indexing hurts performance\n    for i in eachindex(res)\n        @inbounds res[i] = sum(a[j, j, inds[i]] for j in axes(a, 1))\n    end\n\n    return Tensor(res)\nend\n\n\"\"\"\n    trace(t::Tensor{T,2}) where {T} -> Tensor{T,0}\n\nComputes the contraction of the tensor `t` along its two dimensions, equivalent to the trace\nof the underlying matrix of `t`.\nThe two dimensions `t` need to match, i.e., `t` needs to be a 'square' tensor.\n\n# Arguments\n- `t::Tensor{T,2}`: the tensor to be contracted\n\n# Returns\n- `Tensor{T,0}`: the contracted scalar tensor\n\n# Throws\n- `DimensionMismatch`: if the first and the second dimension of `t` do not match\n\"\"\"\ntrace(t::Tensor{T,2}) where {T} = contract(t, 1, 2)\n\n\"\"\"\n    pushover(t1::Tensor{T}, t2::Tensor{S}, d1::Integer, d2::Integer) where {T,S} -> Tensor{promote_type(T, S)}\n\nComputes the 'Überschiebung' of the tensors `t1` and `t2` along the dimensions `d1` and `d2`\nrespectively.\n`d1` and `d2` need to be valid indices for the dimensions of `t1` and `t2` respectively.\nAdditionally, the `d1`-th dimension of `t1` has to match the `d2`-th dimension of `t2`.\n\n# Arguments\n- `t1::Tensor{T}`: the first tensor to push over\n- `t2::Tensor{S}`: the second tensor to push over\n- `d1::Integer`: the first push-over dimension\n- `d2::Integer`: the second push-over dimension\n\n# Returns\n- `Tensor{promote_type(T, S)}`: the push-over tensor\n\n# Throws\n- `BoundsError`: if `d1` and `d2` do not index valid dimensions of `t1` and `t2`\n    respectively\n- `DimensionMismatch`: if the `d1`-th dimension of `t1` does not match the `d2`-th dimension\n    of `t2`\n\"\"\"\nfunction pushover(t1::Tensor{T}, t2::Tensor{S}, d1::Integer, d2::Integer) where {T,S}\n    @argcheck 1 <= d1 <= ndims(t1) BoundsError(size(t1), d1)\n    @argcheck 1 <= d2 <= ndims(t2) BoundsError(size(t2), d2)\n    @argcheck size(t1, d1) == size(t2, d2) DimensionMismatch\n\n    # allow more efficient access of the needed (column-major) array elements\n    a1 = permutedims(t1.data, (d1, Tuple(k for k in 1:ndims(t1) if k != d1)...))\n    a2 = permutedims(t2.data, (d2, Tuple(k for k in 1:ndims(t2) if k != d2)...))\n\n    res = Array{promote_type(T, S)}(\n        undef, size(a1)[2:ndims(a1)]..., size(a2)[2:ndims(a2)]...\n    )\n\n    # NOTE: improved indexing, but still not great, more optimization?\n    j, k = 1, 1\n    for i in eachindex(res)\n        @inbounds res[i] = sum(a1[j:(j + size(a1, 1) - 1)] .* a2[k:(k + size(a1, 1) - 1)])\n        j = (j + size(a1, 1)) % length(t1)\n        k += j == 1 ? size(a1, 1) : 0\n    end\n\n    return Tensor(res)\nend\n\n# TODO: Implement epsilon tensor\n# TODO: Implement delta tensor\n# TODO: Think about sparse tensors for efficiency?\n# TODO: Implement cross product (how?)\n# TODO: Add examples to all relevant docstrings\n# TODO: Maybe rename actual implementations of ⊗ and ⋅ to outer and inner and alias symbols\n", "meta": {"hexsha": "bac4f61b8d264bf4f404078982fe33106c2da432", "size": 6258, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algebra.jl", "max_stars_repo_name": "icetube23/TensorCalculus", "max_stars_repo_head_hexsha": "ffa2e2ac9b43365c7e1e5f1e7201ae3301282555", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algebra.jl", "max_issues_repo_name": "icetube23/TensorCalculus", "max_issues_repo_head_hexsha": "ffa2e2ac9b43365c7e1e5f1e7201ae3301282555", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-21T21:09:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T21:14:19.000Z", "max_forks_repo_path": "src/algebra.jl", "max_forks_repo_name": "icetube23/TensorCalculus", "max_forks_repo_head_hexsha": "ffa2e2ac9b43365c7e1e5f1e7201ae3301282555", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0108695652, "max_line_length": 110, "alphanum_fraction": 0.6538830297, "num_tokens": 2024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7653079263406831}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,jl:hydrogen\n#     text_representation:\n#       extension: .jl\n#       format_name: hydrogen\n#       format_version: '1.3'\n#       jupytext_version: 1.11.2\n#   kernelspec:\n#     display_name: Julia 1.6.3\n#     language: julia\n#     name: julia-1.6\n# ---\n\n# %%\nusing Distributions\nusing HypothesisTests\nusing StatsPlots\ndefault(size=(500, 300))\n\nfunction pval_t(null, X)\n    μ = mean(null)\n    n = length(X)\n    T = (mean(X) - μ)/√(var(X)/n)\n    2ccdf(TDist(n-1), abs(T))\nend\n\nfunction pval_wilcoxon(null, X)\n    m = quantile(null, 0.5) # median of null\n    W = HypothesisTests.SignedRankTest(X .- m)\n    pvalue(W)\nend\n\nfunction plot_pvals(;\n        pval = pval_wilcoxon,\n        null = Gamma(4, 1),\n        n = 100,\n        L = 10^6\n    )\n    PVal = similar(zeros(), L)\n    for i in 1:L\n        X = rand(null, n)\n        PVal[i] = pval(null, X)\n    end\n    realalpha = mean(PVal .< 0.05)\n    histogram(PVal; norm=true, alpha=0.3, bin=0.001:0.025:1.001, label=\"\")\n    plot!(; xtick=0:0.05:1, xrotation=90, bottom_margin=3Plots.mm)\n    title!(\"\"\"\n        pval = $pval,  n = $n\n        null = $null\n        P(p-value < 0.05) = $realalpha,  niters = $L\"\"\",\n        titlefontsize=8)\nend\n\nfunction plot_both(;\n        null = Gamma(4, 1),\n        n = 100,\n        L = 10^6\n    )\n    P = plot_pvals(; pval = pval_t, null, n, L)\n    Q = plot_pvals(; pval = pval_wilcoxon, null, n, L)\n    plot(P, Q; size=(500, 600), layout=(2, 1), tickfontsize=8)\nend\n\n# %%\nplot(Gamma(4, 1); label=\"Gamma(4, 1)\")\n\n# %%\nplot_both(; null = Gamma(4, 1), n = 30)\n\n# %%\nplot_both(; null = Gamma(4, 1), n = 100)\n\n# %%\nplot_both(null = Gamma(4, 1), n = 300, L=10^5)\n\n# %%\nplot_both(; null = Gamma(4, 1), n = 1000, L=10^5)\n\n# %%\nplot(Gamma(10, 1); label=\"Gamma(10, 1)\")\n\n# %%\nplot_both(; null = Gamma(10, 1))\n\n# %%\nplot(Gamma(20, 1); label=\"Gamma(20, 1)\")\n\n# %%\nplot_both(; null = Gamma(20, 1))\n\n# %%\nplot(Gamma(50, 1), 20, 80; label=\"Gamma(50, 1)\")\n\n# %%\nplot_both(; null = Gamma(50, 1), n = 30)\n\n# %%\nplot_both(; null = Gamma(50, 1), n = 100)\n\n# %%\nplot_both(; null=Gamma(50, 1), n = 300, L=10^5)\n\n# %%\nplot_both(; null=Gamma(50, 1), n = 1000, L=10^5)\n\n# %%\nplot(Uniform(-1, 1), -3, 3; label=\"Uniform(-1, 1)\")\n\n# %%\nplot_both(; null = Uniform(-1, 1))\n\n# %%\nnull = TDist(3)\nplot(null, -8, 8; label=\"TDist(3)\")\nplot!(Normal(mean(null), std(null)), -8, 8; label=\"normal approx.\", ls=:dash)\n\n# %%\nplot_both(; null)\n\n# %%\nnull = MixtureModel([Normal(), Normal(10, 1)], [0.95, 0.05])\nplot(null, -5, 15; label=\"\", title=\"$null\", titlefontsize=8) |> display\nplot_both(; null, n = 30)\n\n# %%\nplot_both(; null, n = 100)\n\n# %%\nplot_both(; null, n = 300, L = 10^5)\n\n# %%\nplot_both(; null, n = 1000, L = 10^5)\n\n# %%\nnull = Exponential()\nplot(null; label=\"\", title=\"$null\", titlefontsize=8) |> display\nplot_both(; null, n = 30)\n\n# %%\nplot_both(; null, n = 100)\n\n# %%\n", "meta": {"hexsha": "3800b41b45823f1afa38cac7d83be83f1a26f9e4", "size": 2895, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0022/Wilcoxon test vs. t-test for asymmetric null.jl", "max_stars_repo_name": "genkuroki/public", "max_stars_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-06-06T00:33:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T06:56:08.000Z", "max_issues_repo_path": "0022/Wilcoxon test vs. t-test for asymmetric null.jl", "max_issues_repo_name": "genkuroki/public", "max_issues_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0022/Wilcoxon test vs. t-test for asymmetric null.jl", "max_forks_repo_name": "genkuroki/public", "max_forks_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-02T11:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T11:46:05.000Z", "avg_line_length": 19.8287671233, "max_line_length": 77, "alphanum_fraction": 0.5499136442, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.8688267796346598, "lm_q1q2_score": 0.7652600778967223}}
{"text": "\"\"\"\r\nPermTrack(args...)\r\n\r\nReturn Wyllie and Rose permeability correlation using either Timur or Morris coeficients as well as fluid type, oil or gas\r\n``K=Cperm*\\frac { { Phie }^{ Dperm } }{ { Sw }^{ Eperm } } ``\r\n\r\n## coeficients\r\n### Timur\r\nDperm=4.4\r\nEperm=2.0\r\n\r\nFor Oil\r\n Cperm=3400\r\n\r\nFor Gas\r\nCperm=340\r\n\r\n### Morris\r\nDperm=6.0\r\nEperm=2.0\r\n\r\nFor Oil\r\n Cperm=65000\r\n\r\nFor Gas\r\nCperm=6500\r\n\r\n## Example\r\n\r\n```julia\r\nk=PermWR(0.18,0.3;Fluid=\"Oil\",Author=\"Timur\")\r\n```\r\n\"\"\"\r\n\r\nfunction PermWR(Phie,Swir;Fluid=\"Oil\",Author=\"Timur\")\r\n    #https://www.spec2000.net/15-permwyllie.htm\r\n\r\n    if (Author==\"Timur\")\r\n        Dperm=4.4\r\n        Eperm=2.0\r\n\r\n        if (Fluid==\"Oil\")\r\n         Cperm=3400\r\n        elseif (Fluid==\"Gas\")\r\n            Cperm=340\r\n        end\r\n\r\n    elseif (Author==\"Morris\")\r\n        Dperm=6.0\r\n        Eperm=2.0\r\n           if (Fluid==\"Oil\")\r\n         Cperm=65000\r\n         elseif (Fluid==\"Gas\")\r\n            Cperm=6500\r\n        end\r\n\r\n        end\r\n\r\n    k=Cperm .* (Phie .^ Dperm) ./ (Swir .^ Eperm)\r\nend\r\n", "meta": {"hexsha": "9e092ba077714c78c71d86246e47333514588f04", "size": 1032, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PermWR.jl", "max_stars_repo_name": "scuervo91/WellLogs.jl", "max_stars_repo_head_hexsha": "bc691fdd0500414b4f78172f905ca81930364f8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-05-23T12:19:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T21:34:04.000Z", "max_issues_repo_path": "src/PermWR.jl", "max_issues_repo_name": "scuervo91/WellLogs.jl", "max_issues_repo_head_hexsha": "bc691fdd0500414b4f78172f905ca81930364f8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-21T23:04:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-25T15:37:20.000Z", "max_forks_repo_path": "src/PermWR.jl", "max_forks_repo_name": "scuervo91/WellLogs.jl", "max_forks_repo_head_hexsha": "bc691fdd0500414b4f78172f905ca81930364f8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-06-21T22:50:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T18:28:16.000Z", "avg_line_length": 16.9180327869, "max_line_length": 123, "alphanum_fraction": 0.5310077519, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7652354276188087}}
{"text": "using JuMP\nusing Cbc\nusing ChooseOptimizer\nusing DiscreteFunctions\nusing LinearAlgebra\nimport Base.sqrt\n\n\"\"\"\n`sqrt(g::DiscreteFunction)` returns a function `f` such that\n`f*f==g` or throws an error if no such function exists.\nThis method uses integer linear programming.\n\"\"\"\nfunction sqrt(g::DiscreteFunction)::DiscreteFunction\n    err_msg = \"This function does not have a square root.\"\n    n = length(g)\n    B = Matrix(g)\n\n    if !quick_sqrt_test(g)\n        error(err_msg)\n    end\n    \n    # options = Dict()\n    # options[:logLevel] = 0\n\n    MOD = Model(get_solver())\n\n    @variable(MOD, a[1:n,1:n], Bin)  # entry in A matrix\n    @variable(MOD, w[1:n,1:n,1:n], Bin) # w[i,j,k] is a[i,j]*a[j,k]\n\n    # this ensures w[i,j,k] is 0 if either a[i,j] or a[j,k] are\n    for i=1:n\n        for j=1:n\n            for k=1:n\n                @constraint(MOD, a[i,j]>=w[i,j,k])\n                @constraint(MOD, a[j,k]>=w[i,j,k])\n            end\n        end\n    end\n\n    # this ensures that the A matrix represents a function\n    for i=1:n\n        @constraint(MOD, sum(a[i,j] for j=1:n) == 1)\n    end\n\n    # this ensures that A^2 == B\n    for i=1:n\n        for k=1:n\n            @constraint(MOD, sum(w[i,j,k] for j=1:n) == B[i,k])\n        end\n    end\n\n    # Turns out, we don't need to maximize the w's to get this to work!\n    # @objective(MOD, Max, sum(w[i,j,k] for i=1:n for j=1:n for k=1:n))\n\n    # try to solve\n    optimize!(MOD)\n    status = Int(termination_status(MOD))\n    if status != 1   # if status isn't 1, the IP is not feasible, no sqrt\n        error(err_msg)\n    end\n\n    # build the sqrt function from the A matrix\n    A = Int.(value.(a))\n    f = DiscreteFunction(n)\n    for i=1:n\n        for j=1:n\n            if A[i,j]==1\n                f[i] = j\n            end\n        end\n    end\n    return f\nend\n\n\n\"\"\"\n`has_sqrt(f::DiscreteFunction)` checks if there is a function `g`\nsuch that `g*g==f`. Returns `true` if so and `false` otherwise.\n\"\"\"\nfunction has_sqrt(f::DiscreteFunction)::Bool\n    try\n        g = sqrt(f)\n        return true\n    catch\n        return false\n    end\nend\n\n\"\"\"\n`quick_sqrt_test(f::DiscreteFunction)` is a quick check of a necessary\ncondition for `f` to have a square root. If this returns `false` then `f`\ndoes *not* have a square root. If it returns `true`, it might.\n\"\"\"\nfunction quick_sqrt_test(f::DiscreteFunction)::Bool\n    evals = reduced_eigvals(f)\n    d = real(prod(evals))\n    return d > 0.5\nend\n\nfunction reduced_eigvals(A::Array{T,2}) where T\n    elist = eigvals(A)\n    return filter(x -> abs(x)>1e-7, elist)\nend\n\n\"\"\"\n`reduced_eigvals(f::DiscreteFunction)` returns the nonzero eigenvalues of\n`f`'s matrix.\n\"\"\"\nfunction reduced_eigvals(f::DiscreteFunction)\n    return reduced_eigvals(Matrix(f))\nend\n", "meta": {"hexsha": "f6cd020e4e393099adb8b1e11a6f04b9860d70ca", "size": 2734, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/opt_sqrt.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/DiscreteFunctions.jl-b53ab163-7315-5a32-b7e7-8af45be20176", "max_stars_repo_head_hexsha": "99612254ef1a3b895b7329493aea9a81ea667c42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-09T19:15:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T19:15:23.000Z", "max_issues_repo_path": "src/opt_sqrt.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/DiscreteFunctions.jl-b53ab163-7315-5a32-b7e7-8af45be20176", "max_issues_repo_head_hexsha": "99612254ef1a3b895b7329493aea9a81ea667c42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/opt_sqrt.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/DiscreteFunctions.jl-b53ab163-7315-5a32-b7e7-8af45be20176", "max_forks_repo_head_hexsha": "99612254ef1a3b895b7329493aea9a81ea667c42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:13:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:27:36.000Z", "avg_line_length": 24.4107142857, "max_line_length": 73, "alphanum_fraction": 0.6020482809, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7652354263457176}}
{"text": "@doc raw\"\"\"\n    PowerKernel([γ=1])\n\nThe Power Kernel is a negative definite kernel given by:\n```\n    κ(x,y) = ‖x-y‖²ᵞ   γ ∈ (0,1]\n```\nwhere `γ` is a shape parameter of the Euclidean distance.\n\n# Examples\n\n```jldoctest; setup = :(using MLKernels)\njulia> PowerKernel()\nPowerKernel{Float64}(1.0)\n\njulia> PowerKernel(0.5f0)\nPowerKernel{Float32}(0.5)\n```\n\"\"\"\nstruct PowerKernel{T<:AbstractFloat} <: NegativeDefiniteKernel{T}\n    γ::T\n    function PowerKernel{T}(γ::Real=T(1)) where {T<:AbstractFloat}\n        @check_args(PowerKernel, γ, one(T) >= γ > zero(T), \"γ ∈ (0,1]\")\n        new{T}(γ)\n    end\nend\nPowerKernel(γ::T=1.0) where {T<:Real} = PowerKernel{promote_float(T)}(γ)\n\n@inline basefunction(::PowerKernel) = SquaredEuclidean()\n\n@inline kappa(κ::PowerKernel{T}, d²::T) where {T} = d²^κ.γ\n\nfunction convert(::Type{K}, κ::PowerKernel) where {K>:PowerKernel{T}} where T\n    return PowerKernel{T}(κ.γ)\nend", "meta": {"hexsha": "f37a9b30ac5fe9197eb2d9258f400b57ec2376aa", "size": 902, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernelfunctions/negativedefinite/power.jl", "max_stars_repo_name": "trthatcher/Kernels.jl", "max_stars_repo_head_hexsha": "c95971efc89b76f05e39cbdf5213507fe4351d63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85, "max_stars_repo_stars_event_min_datetime": "2015-04-21T16:40:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T00:25:21.000Z", "max_issues_repo_path": "src/kernelfunctions/negativedefinite/power.jl", "max_issues_repo_name": "trthatcher/Kernels.jl", "max_issues_repo_head_hexsha": "c95971efc89b76f05e39cbdf5213507fe4351d63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 81, "max_issues_repo_issues_event_min_datetime": "2015-04-22T16:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-03T14:32:44.000Z", "max_forks_repo_path": "src/kernelfunctions/negativedefinite/power.jl", "max_forks_repo_name": "trthatcher/Kernels.jl", "max_forks_repo_head_hexsha": "c95971efc89b76f05e39cbdf5213507fe4351d63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2015-04-22T15:59:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-21T19:02:01.000Z", "avg_line_length": 25.7714285714, "max_line_length": 77, "alphanum_fraction": 0.6563192905, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.7652354211355405}}
{"text": "\"\"\"\nCompute Kummer's confluent hypergeometric function `M(a, b, z) = ₁F₁(a; b; z)`.\n\"\"\"\nfunction _₁F₁(a, b, z)\n    if real(z) ≥ 0\n        return _₁F₁maclaurin(a, b, z)\n    else\n        return exp(z)*_₁F₁(b-a, b, -z)\n    end\nend\n\n\"\"\"\nCompute Kummer's confluent hypergeometric function `M(a, b, z) = ₁F₁(a; b; z)`.\n\"\"\"\nconst M = _₁F₁\n\n\"\"\"\nCompute Tricomi's confluent hypergeometric function `U(a, b, z) ∼ z⁻ᵃ ₂F₀([a, a-b+1]; []; -z⁻¹)`.\n\"\"\"\nfunction U(a, b, z)\n    return z^-a*pFq([a, a-b+1], typeof(z)[], -inv(z))\nend\n", "meta": {"hexsha": "d12c890f9348e735df60224c72df4fe02a1ad44e", "size": 517, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/confluent.jl", "max_stars_repo_name": "rashidrafeek/HypergeometricFunctions.jl", "max_stars_repo_head_hexsha": "2b47e2f3cdad38d54154fc06e35bfb25ac16f7a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2018-11-12T20:05:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-08T18:26:38.000Z", "max_issues_repo_path": "src/confluent.jl", "max_issues_repo_name": "rashidrafeek/HypergeometricFunctions.jl", "max_issues_repo_head_hexsha": "2b47e2f3cdad38d54154fc06e35bfb25ac16f7a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2018-11-02T20:00:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T18:03:45.000Z", "max_forks_repo_path": "src/confluent.jl", "max_forks_repo_name": "rashidrafeek/HypergeometricFunctions.jl", "max_forks_repo_head_hexsha": "2b47e2f3cdad38d54154fc06e35bfb25ac16f7a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:51:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:51:30.000Z", "avg_line_length": 22.4782608696, "max_line_length": 97, "alphanum_fraction": 0.5705996132, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9744347860767304, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7652319941253971}}
{"text": "using JuMP\nusing Cbc\nm = Model(Cbc.Optimizer)\n\nPROFIT = [15 12 16 18 9 11]\nCOSTS = [38 33 39 45 23 27]\nLIMIT = 100\n\n@variable(m, projects[1:6] ≥ 0, Int)\n@objective(m, Max, sum(PROFIT * projects))\n@constraint(m, sum(COSTS * projects) ≤ LIMIT)\n@constraint(m, projects[1] + projects[2] ≤ 1) # can only choose one of 1 or 2\n@constraint(m, projects[3] + projects[4] ≤ 1) # can only choose one of 3 or 4\n@constraint(m, projects[3] + projects[4] ≤ projects[1] + projects[2]) # we can do 3 or 4 only if we do 1 or 2\n@constraint(m, projects .≤ ones(size(projects))) # can do every project at most once\nprint(m)\noptimize!(m) \nstatus = termination_status(m)\nprintln(\"Solution status: \", status)\nprintln(\"Objective value: \", objective_value(m))\nprintln(\"Projects chores: \", value.(projects))", "meta": {"hexsha": "b418211b55b9e1b9917e7e17439e563d74f8e84e", "size": 779, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week6/example2.jl", "max_stars_repo_name": "InzamamRahaman/COMP6925-2021", "max_stars_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-23T23:33:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T01:47:28.000Z", "max_issues_repo_path": "week6/example2.jl", "max_issues_repo_name": "InzamamRahaman/COMP6925-2021", "max_issues_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week6/example2.jl", "max_forks_repo_name": "InzamamRahaman/COMP6925-2021", "max_forks_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0952380952, "max_line_length": 109, "alphanum_fraction": 0.6906290116, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.967899289579129, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7651537314428345}}
{"text": "using LinearAlgebra\nfunction Newton(f, f_prime; x_0, tolerance=1.0E-10, maxiter=10000)\n    x_old = x_0\n    normdiff = Inf\n    iter = 1\n    while normdiff > tolerance && iter <= maxiter\n        x_new = x_old - (f(x_old) / f_prime(x_old))\n        normdiff = norm(x_new - x_old)\n        x_old = x_new\n        iter = iter + 1\n    end\n    return (value=x_old, normdiff=normdiff, iter=iter)\nend\n\nf(x) = (x - 1)^3\nf_prime(x) = 3 * (x - 1)^2\ng(x) = x^2 + 3 * x - 10\ng_prime(x) = 2 * x + 3\nsol_f = Newton(f, f_prime, x_0 = 0)\nsol_g = Newton(g, g_prime, x_0 = 0)\nsol_f, sol_g", "meta": {"hexsha": "f82d1b0bc8064952146e1efdbbcb02b52a6a076d", "size": 565, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Problem Sets/Newton.jl", "max_stars_repo_name": "jeff72216/ECON622_exercise", "max_stars_repo_head_hexsha": "300d9c917f6feb456302b57f554739d8ef98c759", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Problem Sets/Newton.jl", "max_issues_repo_name": "jeff72216/ECON622_exercise", "max_issues_repo_head_hexsha": "300d9c917f6feb456302b57f554739d8ef98c759", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Problem Sets/Newton.jl", "max_forks_repo_name": "jeff72216/ECON622_exercise", "max_forks_repo_head_hexsha": "300d9c917f6feb456302b57f554739d8ef98c759", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9047619048, "max_line_length": 66, "alphanum_fraction": 0.589380531, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992895791291, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.7651537266662223}}
{"text": "\"\"\"\n    internal_rate_of_return(cashflows::vector)\n    internal_rate_of_return(cashflows::Vector, timepoints::Vector)\n    \nCalculate the internal_rate_of_return with given timepoints. If no timepoints given, will assume that a series of equally spaced cashflows, assuming the first cashflow occurring at time zero. \n\nWill try to return a root within the range [-2,2]. If the fast solver does not find one matching this condition, then a more robust search will be performed over the [.99,2] range.\n\nThe solution returned will be in the range [-2,2], but may not be the one nearest zero. For a slightly slower, but more robust version, call `ActuaryUtilities.irr_robust(cashflows,timepoints)` directly.\n\n# Example\n```julia-repl\njulia> internal_rate_of_return([-100,110],[0,1]) # e.g. cashflows at time 0 and 1\n0.10000000001652906\njulia> internal_rate_of_return([-100,110]) # implied the same as above\n0.10000000001652906\n```\n\n\"\"\"\nfunction internal_rate_of_return(cashflows)\n    \n\n    return internal_rate_of_return(cashflows, 0:length(cashflows)-1)\n    \nend\n\nfunction internal_rate_of_return(cashflows,times)\n    # first try to quickly solve with newton's method, otherwise \n    # revert to a more robust method\n    lower,upper = -2.,2.\n    \n    v = try \n        irr_newton(cashflows,times)\n    catch e\n        if isa(e,Roots.ConvergenceFailed) || sprint(showerror, e) ==\"No convergence\"\n            return irr_robust(cashflows,times)\n        else\n            throw(e)\n        end\n    end\n    \n    if v <= upper && v >= lower\n        return v\n    else\n        return irr_robust(cashflows,times)\n    end\nend\n\nirr_robust(cashflows) = irr_robust(cashflows,0:length(cashflows)-1)\n\nfunction irr_robust(cashflows, times)\n    f(i) =  sum(cf / (1+i)^t for (cf,t) in zip(cashflows,times))\n    # lower bound at -.99 because otherwise we can start taking the root of a negative number\n    # when a time is fractional. \n    roots = Roots.find_zeros(f, -0.99, 2)\n    \n    # short circuit and return nothing if no roots found\n    isempty(roots) && return nothing\n    # find and return the one nearest zero\n    min_i = argmin(roots)\n    return roots[min_i]\n\nend\n\nirr_newton(cashflows) = irr_newton(cashflows,0:length(cashflows)-1)\n\nfunction irr_newton(cashflows, times)\n    # use newton's method with hand-coded derivative\n    f(r) =  sum(cf * exp(-r*t) for (cf,t) in zip(cashflows,times))\n    f′(r) = sum(-t*cf * exp(-r*t) for (cf,t) in zip(cashflows,times) if t > 0)\n    # r = Roots.solve(Roots.ZeroProblem((f,f′), 0.0), Roots.Newton())\n    r = Roots.newton(x->(f(x),f(x)/f′(x)),0.0)\n    return exp(r)-1\n\nend\n\n\"\"\"\n    irr()\n\n    An alias for `internal_rate_of_return`.\n\"\"\"\nirr = internal_rate_of_return\n\n\"\"\"\n    present_value(interest, cashflows::Vector, timepoints)\n    present_value(interest, cashflows::Vector)\n\nDiscount the `cashflows` vector at the given `interest_interestrate`,  with the cashflows occurring\nat the times specified in `timepoints`. If no `timepoints` given, assumes that cashflows happen at times 1,2,...,n.\n\nThe `interest` can be an `InterestCurve`, a single scalar, or a vector wrapped in an `InterestCurve`. \n\n# Examples\n```julia-repl\njulia> present_value(0.1, [10,20],[0,1])\n28.18181818181818\njulia> present_value(Yields.Forward([0.1,0.2]), [10,20],[0,1])\n28.18181818181818 # same as above, because first cashflow is at time zero\n```\n\nExample on how to use real dates using the [DayCounts.jl](https://github.com/JuliaFinance/DayCounts.jl) package\n```jldoctest\n\nusing DayCounts \ndates = Date(2012,12,31):Year(1):Date(2013,12,31)\ntimes = map(d -> yearfrac(dates[1], d, DayCounts.Actual365Fixed()),dates) # [0.0,1.0]\npresent_value(0.1, [10,20],times)\n\n# output\n28.18181818181818\n\n```\n\n\"\"\"\nfunction present_value(yc::T, cashflows, timepoints) where {T <: Yields.AbstractYield}\n    sum(discount(yc,t) * cf for (t,cf) in zip(timepoints, cashflows))\nend\n\nfunction present_value(yc::T, cashflows) where {T <: Yields.AbstractYield}\n    present_value(yc,cashflows,1:length(cashflows))\nend\n\nfunction present_value(i, x)\n    \n    v = 1.0\n    v_factor = 1/(1+i)\n    pv = 0.0\n\n    for (t,cf) in zip(1:length(x),x)\n        v *= v_factor\n        pv += v * cf\n    end\n    return pv \nend\n\nfunction present_value(i, v, times)\n    return present_value(Yields.Constant(i), v, times)\nend\n\n# Interest Given is an array, assume forwards.\nfunction present_value(i::AbstractArray, v)\n    yc = Yields.Forward(i)\n    return sum(discount(yc, t) * cf for (t,cf) in zip(1:length(v),v))\nend\n\n# Interest Given is an array, assume forwards.\nfunction present_value(i::AbstractArray, v, times)\n    yc = Yields.Forward(i, times)\n    return sum(discount(yc, t) * cf for (cf, t) in zip(v,times))\nend\n\n\"\"\"\n    pv()\n\n    An alias for `present_value`.\n\"\"\"\npv = present_value\n\n\n\"\"\"\n    present_value(interest, cashflows::Vector, timepoints)\n    present_value(interest, cashflows::Vector)\n\nEfficiently calculate a vector representing the present value of the given cashflows at each period prior to the given timepoint.\n\n# Examples\n```julia-repl\njulia> present_values(0.00, [1,1,1])\n[3,2,1]\n\njulia> present_values(Yields.Forward([0.1,0.2]), [10,20],[0,1])\n2-element Vector{Float64}:\n 28.18181818181818\n 18.18181818181818\n```\n\n\"\"\"\nfunction present_values(interest, cashflows)\n    pvs = Vector{Float64}(undef,length(cashflows))\n    pvs[end] = Yields.discount(interest, lastindex(cashflows) - 1, lastindex(cashflows)) * cashflows[end]\n    for (t, cf) in Iterators.reverse(enumerate(cashflows[1:end - 1]))\n        pvs[t] = Yields.discount(interest, t - 1, t) * (cf + pvs[t + 1])\n    end\n\n    return pvs\nend\n\n\nfunction present_values(interest,cashflows,times)\n    present_values_accumulator(interest,cashflows,times)\nend\n\nfunction present_values_accumulator(interest,cashflows,times,pvs=[0.0])\n    from_time = length(times) == 1 ? 0. : times[end-1]\n    pv = discount(interest,from_time,last(times)) *(first(pvs) + last(cashflows))\n    pvs = pushfirst!(pvs,pv)\n\n    if length(cashflows) > 1\n\n        new_cfs = @view cashflows[1:end-1]\n        new_times = @view times[1:end-1]\n        return present_values_accumulator(interest,new_cfs,new_times,pvs)\n    else\n        # last discount and return\n        return pvs[1:end-1] # end-1 get rid of trailing 0.0\n    end\nend\n\n# if given a vector of rates, assume that it should be a forward discount yield\nfunction present_values(y::Vector{T}, cfs, times) where {T <: Real}\n    return present_values(Yields.Forward(y), cfs, times)\nend\n\n\n\"\"\"\n    price(...)\n\nThe absolute value of the `present_value(...)`. \n\n# Extended help\n\nUsing `price` can be helpful if the directionality of the value doesn't matter. For example, in the common usage, duration is more interested in the change in price than present value, so `price` is used there.\n\"\"\"\nprice(x1,x2) = present_value(x1, x2) |> abs\nprice(x1,x2,x3) = present_value(x1, x2, x3) |> abs\n\n\"\"\"\n    breakeven(yield, cashflows::Vector)\n    breakeven(yield, cashflows::Vector,times::Vector)\n\nCalculate the time when the accumulated cashflows breakeven given the yield.\n\nAssumptions:\n\n- cashflows occur at the end of the period\n- cashflows evenly spaced with the first one occuring at time zero if `times` not given\n\nReturns `nothing` if cashflow stream never breaks even.\n\n```jldoctest\njulia> breakeven(0.10, [-10,1,2,3,4,8])\n5\n\njulia> breakeven(0.10, [-10,15,2,3,4,8])\n1\n\njulia> breakeven(0.10, [-10,-15,2,3,4,8]) # returns the `nothing` value\n\n\n```\n\"\"\"\nfunction breakeven(y::T, cashflows::Vector, timepoints::Vector) where {T <: Yields.AbstractYield}\n    accum = zero(eltype(cashflows))\n    last_neg = nothing\n\n    accum += cashflows[1]\n    if accum >= 0 && isnothing(last_neg)\n        last_neg = timepoints[1]\n    end\n\n    for i in 2:length(cashflows)\n        # accumulate the flow from each timepoint to the next\n        accum *= Yields.accumulation(y, timepoints[i - 1], timepoints[i])\n        accum += cashflows[i]\n\n        if accum >= 0 && isnothing(last_neg)\n            last_neg = timepoints[i]\n        elseif accum < 0\n            last_neg = nothing\n        end\n    end\n\n    return last_neg\n\nend\n\nfunction breakeven(y::T, cfs, times) where {T <: Real}\n    return breakeven(Yields.Constant(y), cfs, times)\nend\n\nfunction breakeven(y::Vector{T}, cfs, times) where {T <: Real}\n    return breakeven(Yields.Forward(y), cfs, times)\nend\n\nfunction breakeven(i, cashflows::Vector)\n    return breakeven(i, cashflows, [t for t in 0:length(cashflows) - 1])\nend\n\nabstract type Duration end\n\nstruct Macaulay <: Duration end\nstruct Modified <: Duration end\nstruct DV01 <: Duration end\n\n\"\"\" \n    duration(Macaulay(),interest_rate,cfs,times)\n    duration(Modified(),interest_rate,cfs,times)\n    duration(::DV01,interest_rate,cfs,times)\n    duration(interest_rate,cfs,times)             # Modified Duration\n    duration(interest_rate,valuation_function)    # modified Duration\n\nCalculates the Macaulay, Modified, or DV01 duration. `times` may be ommitted and the valuation will assume evenly spaced cashflows starting at the end of the first period.\n- `interest_rate` should be a fixed effective yield (e.g. `0.05`).\n\n\nWhen not given `Modified()` or `Macaulay()` as an argument, will default to `Modified()`.\n\n# Examples\n\nUsing vectors of cashflows and times\n```julia-repl\njulia> times = 1:5\njulia> cfs = [0,0,0,0,100]\njulia> duration(0.03,cfs,times)\n4.854368932038834\njulia> duration(Macaulay(),0.03,cfs,times)\n5.0\njulia> duration(Modified(),0.03,cfs,times)\n4.854368932038835\njulia> convexity(0.03,cfs,times)\n28.277877274012614\n\n```\n\nUsing any given value function: \n\n```julia-repl\njulia> lump_sum_value(amount,years,i) = amount / (1 + i ) ^ years\njulia> my_lump_sum_value(i) = lump_sum_value(100,5,i)\njulia> duration(0.03,my_lump_sum_value)\n4.854368932038835\njulia> convexity(0.03,my_lump_sum_value)\n28.277877274012617\n\n```\n\"\"\"\nfunction duration(::Macaulay, yield, cfs, times)\n    return sum(times .* price.(yield, vec(cfs), times) / price(yield, vec(cfs), times))\nend\n\nfunction duration(::Modified, yield, cfs, times)\n    D(i) = price(i, vec(cfs), times)\n    return duration(yield, D)\nend\n\nfunction duration(yield, valuation_function)\n    D(i) = log(valuation_function(i + yield))\n    δV =  - ForwardDiff.derivative(D, 0.0)\nend\n\nfunction duration(yield::Y, valuation_function) where {Y <: Yields.AbstractYield}\n    D(i) = log(valuation_function(i + yield))\n    δV =  - ForwardDiff.derivative(D, 0.0)\nend\n\nfunction duration(yield, cfs, times)\n    return duration(Modified(), yield, vec(cfs), times)\nend\nfunction duration(yield::Y, cfs::A) where {Y <: Yields.AbstractYield,A <: AbstractArray}\n    times = 1:length(cfs)\n    return duration(Modified(), yield, vec(cfs), times)\nend\n\nfunction duration(yield::R, cfs) where {R <: Real}\n    return duration(Yields.Constant(yield), cfs)\nend\n\nfunction duration(::DV01, yield, cfs, times)\n    return duration(DV01(), yield, i -> price(i, vec(cfs), times))\nend\nfunction duration(d::Duration, yield, cfs)\n    times = 1:length(cfs)\n    return duration(d, yield, vec(cfs), times)\nend\n\nfunction duration(::DV01, yield, valuation_function)\n    return duration(yield, valuation_function) * valuation_function(yield) / 100\nend\n\n\"\"\" \n    convexity(yield,cfs,times)\n    convexity(yield,valuation_function)\n\nCalculates the convexity.\n    - `yield` should be a fixed effective yield (e.g. `0.05`).\n    - `times` may be omitted and it will assume `cfs` are evenly spaced beginning at the end of the first period.\n\n# Examples\n\nUsing vectors of cashflows and times\n```julia-repl\njulia> times = 1:5\njulia> cfs = [0,0,0,0,100]\njulia> duration(0.03,cfs,times)\n4.854368932038834\njulia> duration(Macaulay(),0.03,cfs,times)\n5.0\njulia> duration(Modified(),0.03,cfs,times)\n4.854368932038835\njulia> convexity(0.03,cfs,times)\n28.277877274012614\n\n```\n\nUsing any given value function: \n\n```julia-repl\njulia> lump_sum_value(amount,years,i) = amount / (1 + i ) ^ years\njulia> my_lump_sum_value(i) = lump_sum_value(100,5,i)\njulia> duration(0.03,my_lump_sum_value)\n4.854368932038835\njulia> convexity(0.03,my_lump_sum_value)\n28.277877274012617\n\n```\n\n\"\"\"\nfunction convexity(yield, cfs, times)\n    return convexity(yield, i -> price(i, vec(cfs), times))\nend\n\nfunction convexity(yield, cfs::A) where {A <: AbstractArray}\n    times = 1:length(cfs)\n    return convexity(yield, i -> price(i, vec(cfs), times))\nend\n\nfunction convexity(yield, valuation_function)\n    v(x) = abs(valuation_function(yield + x[1]))\n    ∂²P = ForwardDiff.hessian(v, [0.0])\n    return ∂²P[1] / v([0.0])  \nend\n", "meta": {"hexsha": "401f1fefe2bc6568432c77d49fd6e3279b8e871b", "size": 12426, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/financial_math.jl", "max_stars_repo_name": "JuliaActuary/ActuaryUtilities.jl", "max_stars_repo_head_hexsha": "1e574ad70769a539ea62d846f03b84c92e2f1ae8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-04-03T02:41:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T12:09:21.000Z", "max_issues_repo_path": "src/financial_math.jl", "max_issues_repo_name": "JuliaActuary/ActuaryUtilities.jl", "max_issues_repo_head_hexsha": "1e574ad70769a539ea62d846f03b84c92e2f1ae8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 58, "max_issues_repo_issues_event_min_datetime": "2020-04-03T20:37:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T10:00:24.000Z", "max_forks_repo_path": "src/financial_math.jl", "max_forks_repo_name": "JuliaActuary/ActuaryUtilities.jl", "max_forks_repo_head_hexsha": "1e574ad70769a539ea62d846f03b84c92e2f1ae8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-06T17:20:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T20:38:39.000Z", "avg_line_length": 28.7638888889, "max_line_length": 210, "alphanum_fraction": 0.69716723, "num_tokens": 3742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.765148548505599}}
{"text": "\"\"\"\n    ConjugateGradients(d,operators,parameters;<keyword arguments>)\nConjugate Gradients following Algorithm 2 from Scales, 1987.\nThe user provides an array of linear operators. Verify that linear operator(s) pass the dot product.\nSee also: [`DotTest`](@ref)\n\n# Arguments\n- `Niter=10` : Number of iterations\n- `mu=0`\n- `tol=1.0e-15`\n\n\"\"\"\nfunction ConjugateGradients(d,operators,parameters;Niter=10,mu=0,tol=1.0e-15)\n\n    cost = Float64[]\n    r = copy(d)\n    g = LinearOperator(r,operators,parameters,adj=true)\n    m = zero(g)\n    s = copy(g)\n    gamma = InnerProduct(g,g)\n    gamma00 = gamma\n    cost0 = InnerProduct(r,r)\n    push!(cost,1.0)\n    for iter = 1 : Niter\n\tt = LinearOperator(s,operators,parameters,adj=false)\n\tdelta = InnerProduct(t,t) + mu*InnerProduct(s,s)\n\tif delta <= tol\n#\t    println(\"delta reached tolerance, ending at iteration \",iter)\n\t    break;\n\tend\n\talpha = gamma/delta\n\tm = m + alpha*s\n\tr = r - alpha*t\n\tg = LinearOperator(r,operators,parameters,adj=true)\n\tg = g - mu*m\n\tgamma0 = copy(gamma)\n\tgamma = InnerProduct(g,g)\n        cost1 = InnerProduct(r,r) + mu*InnerProduct(m,m)\n        push!(cost,cost1/cost0)\n\tbeta = gamma/gamma0\n\ts = beta*s + g\n\tif (sqrt(gamma) <= sqrt(gamma00) * tol)\n\t    println(\"tolerance reached, ending at iteration \",iter)\n\t    break;\n\tend\n    end\n\n    return m, cost\nend\n", "meta": {"hexsha": "e9a4945af976eca320f2bc1e871b5ceab908bebc", "size": 1323, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Tools/ConjugateGradients.jl", "max_stars_repo_name": "JuliaTagBot/SeisReconstruction.jl", "max_stars_repo_head_hexsha": "ef0789f00aa7d71dc2b4c92c572c7ecc6c37cac7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-13T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T11:11:49.000Z", "max_issues_repo_path": "src/Tools/ConjugateGradients.jl", "max_issues_repo_name": "JuliaTagBot/SeisReconstruction.jl", "max_issues_repo_head_hexsha": "ef0789f00aa7d71dc2b4c92c572c7ecc6c37cac7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-11-18T21:58:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T22:19:13.000Z", "max_forks_repo_path": "src/Tools/ConjugateGradients.jl", "max_forks_repo_name": "JuliaTagBot/SeisReconstruction.jl", "max_forks_repo_head_hexsha": "ef0789f00aa7d71dc2b4c92c572c7ecc6c37cac7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-01-22T20:39:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T22:47:02.000Z", "avg_line_length": 26.46, "max_line_length": 100, "alphanum_fraction": 0.6666666667, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7651485456434115}}
{"text": "# The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.\n#\n# Find the sum of all numbers, less than one million, which are palindromic in\n# base 10 and base 2.\n#\n# (Please note that the palindromic number, in either base, may not include\n# leading zeros.)\n\nusing ProjectEulerSolutions\n\n# Simple using Julia's builtin bitstring and parse functions (with BigInt).\nfunction p036solution(n::Integer=10)::Integer\n    sums = 0\n    for i in 1:n\n        if ispalindrome_integer(i) && ispalindrome(parse(BigInt, bitstring(i)))\n            sums += i\n        end\n    end\n    return sums\nend\n\np036 = Problems.Problem(p036solution)\n\nProblems.benchmark(p036, 1_000_000)\n", "meta": {"hexsha": "df5c2a8476f76299861542e18961ce8a39bd7aec", "size": 679, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/036.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/036.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/036.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.16, "max_line_length": 79, "alphanum_fraction": 0.7113402062, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7651485450491181}}
{"text": "\"\"\"\n    Haversine(radius=6_371_000)\n\nThe haversine distance between two locations on a sphere of given `radius`, whose\ndefault value is 6,371,000, i.e., the Earth's (volumetric) mean radius in meters; cf.\n[NASA's Earth Fact Sheet](https://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html).\n\nLocations are described with longitude and latitude in degrees.\nThe computed distance has the unit of the radius.\n\"\"\"\nstruct Haversine{T<:Number} <: Metric\n    radius::T\nend\nHaversine{T}() where {T<:Number} = Haversine(T(6_371_000))\nHaversine() = Haversine{Int}()\n\nfunction (dist::Haversine)(x, y)\n    length(x) == length(y) == 2 || haversine_error(dist)\n\n    λ₁, φ₁ = x\n    λ₂, φ₂ = y\n\n    Δλ = λ₂ - λ₁  # longitudes\n    Δφ = φ₂ - φ₁  # latitudes\n\n    # haversine formula\n    a = sind(Δφ/2)^2 + cosd(φ₁)*cosd(φ₂)*sind(Δλ/2)^2\n\n    # distance on the sphere\n    2 * (dist.radius * asin( min(√a, one(a)) )) # take care of floating point errors\nend\n\nhaversine(x, y, radius::Number=6_371_000) = Haversine(radius)(x, y)\n\n@noinline haversine_error(dist) = throw(ArgumentError(\"expected both inputs to have length 2 in $dist distance\"))\n\nresult_type(::Haversine{T1}, ::Type{T2}, ::Type{T3}) where {T1<:Number,T2<:Number,T3<:Number} =\n    float(promote_type(T1, T2, T3))\n\n\"\"\"\n    SphericalAngle()\n\nThe spherical angle distance between two locations on a sphere.\n\nLocations are described with two angles, longitude and latitude, in radians.\nThe distance is computed with the haversine formula and also has units of radians.\n\"\"\"\nstruct SphericalAngle <: Metric end\n\nfunction (dist::SphericalAngle)(x, y)\n    length(x) == length(y) == 2 || haversine_error(dist)\n\n    λ₁, φ₁ = x\n    λ₂, φ₂ = y\n\n    Δλ = λ₂ - λ₁  # longitudes\n    Δφ = φ₂ - φ₁  # latitudes\n\n    # haversine formula\n    a = sin(Δφ/2)^2 + cos(φ₁)*cos(φ₂)*sin(Δλ/2)^2\n\n    # distance on the sphere\n    2 * asin( min(√a, one(a)) ) # take care of floating point errors\nend\n\nconst spherical_angle = SphericalAngle()\n\nresult_type(::SphericalAngle, ::Type{T1}, ::Type{T2}) where {T1<:Number,T2<:Number} = float(promote_type(T1, T2))\n", "meta": {"hexsha": "2f22f169994e1a86b532d9bfad4c7e2b6090377a", "size": 2076, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/haversine.jl", "max_stars_repo_name": "JackDunnNZ/Distances.jl", "max_stars_repo_head_hexsha": "5f9be3719759043d3ab279b866377c8367f4527e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-08T03:30:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T03:30:58.000Z", "max_issues_repo_path": "src/haversine.jl", "max_issues_repo_name": "JackDunnNZ/Distances.jl", "max_issues_repo_head_hexsha": "5f9be3719759043d3ab279b866377c8367f4527e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/haversine.jl", "max_forks_repo_name": "JackDunnNZ/Distances.jl", "max_forks_repo_head_hexsha": "5f9be3719759043d3ab279b866377c8367f4527e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0869565217, "max_line_length": 113, "alphanum_fraction": 0.6777456647, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7651485438161219}}
{"text": "module EOQ\n\nusing DecFP\nexport @d128_str, @d32_str, @d64_str, @d_str, Dec128, Dec32, Dec64, DecFP, exponent10, ldexp10, sigexp\n\"\"\"\nSimple EOQ model with required arguments:\n    - demand (constant per unit time), order (set up) cost, holding (carrying) cost\n    - holding cost can be calculated as (unit cost)*(holding rate)\nOptional arguments:\n    - time units ---> Tuple ---> default is ('m' for months, 12) => 1 year\n    - lead time (default is 0)\n\"\"\"\nfunction eoq_execute(;demand::Signed, c::Union{Signed,AbstractFloat}, ct::Union{Signed,AbstractFloat}, \n    ce::Union{Signed,AbstractFloat}, time_units::Tuple{String,Signed}, lead_time::Signed)\n    # Basic Output\n    Q = sqrt(2*ct*demand/ce)\n    T_raw = Q/demand\n    T = Dec64(T_raw*time_units[2])\n    N = 1/T_raw\n    \n    # Inventory Position\n    # ROP_IP = demand*lead_time/time_units[2]\n\n    # Costs (not accounting for pipeline inventory cost, i.e. for lead_time > 0)\n    OrderingCost = ct*N\n    HoldingCost = ce*(Q/2)\n    TRC() = OrderingCost + HoldingCost\n    TC() = TRC() + c*demand\n\n    # Inventory Policy\n    policy() = Dict(\"Q\"=>Q, \"T\"=>T, \"N\"=>N, \"TRC\"=>TRC(), \"TC\"=>TC())\n\n    function policy_for(s::String, value::Union{Signed, AbstractFloat})\n        if s == \"Q\"\n            Q_for = value\n            T_raw_for = value/demand\n            T_for = T_raw_for*time_units[2]\n            N_for = 1/T_raw_for\n        elseif s == \"T\"\n            T_for = value\n            N_for = time_units[2]/value\n            Q_for = demand/N_for\n        else\n            return \"Invalid input\"\n        end\n        OrderingCost_for = ct*N_for\n        HoldingCost_for = ce*(Q_for/2)\n        TRC_for() = OrderingCost_for + HoldingCost_for\n        TC_for() = TRC_for() + c*demand\n        return Dict(\"Q*\"=>Q_for, \"T\"=>T_for, \"N\"=>N_for, \"TRC\"=>TRC_for(), \"TC\" => TC_for(), \"ΔTC\"=> TC_for()/TC())\n    end\n\n    # [Required] Returning a function with \"public\" elements\n    ()->(Q, T_raw, T, N,\n    OrderingCost, HoldingCost, TRC, TC,\n    policy, policy_for)\nend\n\n\"\"\"\nIntermediary function to simplify input for eoq_execute()\n\"\"\"\nfunction eoq(;demand, c=0, ct, ce, time_units=(\"m\",12), lead_time=0)\n    d = Dict(:demand=>demand, :c=>c, :ct=>ct, :ce=>ce, :time_units=>time_units, :lead_time=>lead_time)\n    return eoq_execute(;d...)\nend\n\nend # Module EOQ", "meta": {"hexsha": "5affcfcb519840517fb16446c8b7da34c0b34bce", "size": 2292, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/EOQ.jl", "max_stars_repo_name": "Jorbnc/SupplyChainModels.jl", "max_stars_repo_head_hexsha": "4d5913feca1d1a2f2028dcc99b7c37685953b4ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/EOQ.jl", "max_issues_repo_name": "Jorbnc/SupplyChainModels.jl", "max_issues_repo_head_hexsha": "4d5913feca1d1a2f2028dcc99b7c37685953b4ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/EOQ.jl", "max_forks_repo_name": "Jorbnc/SupplyChainModels.jl", "max_forks_repo_head_hexsha": "4d5913feca1d1a2f2028dcc99b7c37685953b4ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2089552239, "max_line_length": 115, "alphanum_fraction": 0.6143106457, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.76514853773996}}
{"text": "ACTIVATIONS = [\n    :line, :σ, :sigmoid, :hardσ, :hardsigmoid, :hardtanh, :relu,\n    :leakyrelu, :relu6, :rrelu, :prelu, :elu, :gelu, :swish, :selu,\n    :celu, :softplus, :softsign, :logσ, :logcosh,\n    :mish, :tanhshrink, :softshrink, :trelu, :lisht,\n    :gaussian, :GCU, :SQU, :NCU, :SSU, :DSU\n]\nfor f in ACTIVATIONS\n    @eval export $(f)\nend\n\n\"\"\"\n    line(x)\nLinear function. This is the expression:\n```math\nline(x) = x\n```\n\"\"\"\nline(x) = x\n\n@doc raw\"\"\"\n    σ(x)\nStandard sigmoid activation function. Also, this function can be called with `σ`. This is the expression:\n```math\n\\sigma(x) = \\frac{1}{1+e^{-x}}\n```\n\"\"\"\nfunction sigmoid(x)\n    t = exp(-abs(x))\n    return (x>=0) ? inv(1 + t) : t / (t + 1)\nend\nconst σ = sigmoid\n\n@doc raw\"\"\"\n    hardsigmoid(x) = max(0, min(1, (x + 2.5) / 6))\nPiecewise linear approximation of sigmoid. Also, this function can be called with `hardσ`. This is the expression:\n```math\nhardsigmoid(x) = \\left\\{\n\\begin{array}{ll}\n1 & (x \\geq \\frac{1}{4}) \\\\\n\\frac{1}{5} x & (- \\frac{1}{4} \\lt x \\lt \\frac{1}{4}) \\\\\n0 & (x \\leq - \\frac{1}{4})\n\\end{array}\n\\right.\n```\n\"\"\"\nhardsigmoid(x) = max(0, min(1, (x + 2.5) / 6))\nconst hardσ = hardsigmoid\n\n@doc raw\"\"\"\n    lisht(x)\nThis is the expression:\n```math\nlisht(x) = x\\tanh(x)\n```\n\"\"\"\nlisht(x) = x*tanh(x)\n\n@doc raw\"\"\"\n    relu(x) = max(0, x)\n`relu` is `Rectified Linear Unit`. This is the expression:\n```math\nrelu(x) = \\left\\{\n\\begin{array}{ll}\nx & (x \\geq 0) \\\\\n0 & (x \\lt 0)\n\\end{array}\n\\right.\n```\n\"\"\"\nrelu(x) = max(0, x)\n\n@doc raw\"\"\"\n    leakyrelu(x; α=0.01) = (x>0) ? x : α*x\nLeaky Rectified Linear Unit. This is the expression:\n```math\nleakyrelu(x) = \\left\\{\n\\begin{array}{ll}\n\\alpha x & (x \\lt 0) \\\\\nx & (x \\geq 0)\n\\end{array}\n\\right.\n```\n\"\"\"\nleakyrelu(x; α=0.01f0) = max(x, α*x)\n\n@doc raw\"\"\"\n    rrelu(min, max)\nRandomized Rectified Linear Unit. The expression is the as [`leakyrelu`](@ref), but `α` is a random number between `min` and `max`.\nAlso, since this function is defined as a structure, use it as follows:\n```\nDense(10=>5, rrelu(0.001, 0.1))\n```\n\"\"\"\nstruct rrelu\n    α::Union{Float64, Float32}\n    function rrelu(min::Float64, max::Float64)\n        new(round(rand()*(max-min+1))+min)\n    end\nend\n\n(rrelu::rrelu)(x) = max(x, rrelu.α*x)\n\n@doc raw\"\"\"\n    prelu(; α=0.01)\nParametric Ractified LinearUnit. The expression is the as [`leakyrelu`](@ref), but `α` is determined by learning. Also, when using this function, use [`Denseσ`](@ref) instead of [`Dense`](@ref).\n\"\"\"\nstruct prelu\n    α::Union{Float64, Float32}\n    prelu(; α=0.01) = new(α)\nend\n\n(prelu::prelu)(x) = max(x, prelu.α*x)\n\n@doc raw\"\"\"\n    relu6(x)\nRelu function with an upper limit of 6. This is the expression:\n```math\nrelu6(x) = \\left\\{\n\\begin{array}{ll}\n6 & (x \\gt 6) \\\\\nx & (x \\geq 0) \\\\\n0 & (x \\lt 0)\n\\end{array}\n\\right.\n```\n\"\"\"\nrelu6(x) = min(6, max(0, x))\n\n@doc raw\"\"\"\n    elu(x, α=1)\nExponential Linear Unit activation function. You can also specify the coefficient explicitly, e.g. elu(x, 1). This is the expression:\n```math\nelu(x, α) = \\left\\{\n\\begin{array}{ll}\nx & (x \\geq 0) \\\\\n\\alpha(e^x-1) & (x \\lt 0)\n\\end{array}\n\\right.\n```\n\"\"\"\nelu(x; α=1) = (x<0) ? (exp(x)-1)α : x\n\n@doc raw\"\"\"\n    celu(x; α=1)\nContinuously Differentiable Exponential Linear Unit. This is the expression:\n```math\n\\alpha = 1 \\\\\ncelu(x) = \\left\\{\n\\begin{array}{ll}\nx & (x \\geq 0) \\\\\n\\alpha(e^\\frac{x}{\\alpha}-1) & (x \\lt 0)\n\\end{array}\n\\right.\n```\n\"\"\"\ncelu(x; α=1) = (x>=0) ? x : α*(exp(x/α)-1)\n\n@doc raw\"\"\"\n    gelu(x)\nGaussian Error Linear Unit. This is the expression(``\\phi`` is a distribution function of standard normal distribution.):\n```math\ngelu(x) = x\\phi(x)\n```\nHowever, in the implementation, it is calculated with the following expression.\n```math\n\\sigma(x) = \\frac{1}{1+e^{-x}} \\\\\ngelu(x) = x\\sigma(1.702x)\n```\n\"\"\"\ngelu(x) = σ(1.702*x)x\n\n@doc raw\"\"\"\n    selu(x)\nScaled exponential linear units. This is the expression\n```math\n\\lambda = 1.0507009873554804934193349852946 \\\\\n\\alpha = 1.6732632423543772848170429916717 \\\\\nselu(x) = \\lambda \\left\\{\n\\begin{array}{ll}\nx & (x \\geq 0) \\\\\n\\alpha(e^x-1) & (x \\lt 0)\n\\end{array}\n\\right.\n```\n\"\"\"\nfunction selu(x)\n    λ = oftype(float(x), selu_λ)\n    α = oftype(float(x), selu_α)\n    return ((x > 0) ? x : (exp(x)-1)α)*λ\nend\n\nconst selu_λ = 1.0507009873554804934193349852946\nconst selu_α = 1.6732632423543772848170429916717\n\n@doc raw\"\"\"\n    trelu(x; θ=1)\nThreshold gated Rectified Linear Unit. This is the expression:\n```math\n\\theta = 1 \\\\\ntrelu(x) = \\left\\{\n\\begin{array}{ll}\nx & (x \\gt 0) \\\\\n0 & (x \\leq 0)\n\\end{array}\n\\right.\n```\n\"\"\"\ntrelu(x; θ=1) = (x<=θ) ? 0 : x\n\n@doc raw\"\"\"\n    logσ(x)\nlogarithmic sigmoid function. This is the expression:\n```math\n\\sigma(x) = \\frac{1}{1+e^{-x}} \\\\\nlogsigmoid(x) = \\log(\\sigma(x))\n```\n\"\"\"\nlogsigmoid(x) = log(σ(x))\nconst logσ = logsigmoid\n\n@doc raw\"\"\"\n    logcosh(x)\nLog-Cosh function. This is the expression:\n```math\nlogcosh(x) = \\log(\\cosh(x))\n```\n\"\"\"\nlogcosh(x) = log(cosh(x))\n\n@doc raw\"\"\"\n    hardtanh(x)\nLinear tanh function. This is the expression:\n```math\nhardtanh(x) = \\left\\{\n\\begin{array}{ll}\n1 & (x \\geq 1) \\\\\nx & (-1 \\lt x \\lt 1) \\\\\n-1 & (x \\leq -1)\n\\end{array}\n\\right.\n```\n\"\"\"\nhardtanh(x) = min(1, max(-1, x))\n\n@doc raw\"\"\"\n    tanhshrink(x)\nShrink tanh function. This is the expression:\n```math\ntanhshrink(x) = 1-\\tanh(x)\n```\n\"\"\"\ntanhshrink(x) = 1-tanh(x)\n\n@doc raw\"\"\"\n    softshrink(x; λ=0.5)\nThis is the expression:\n```math\n\\lambda=0.5 \\\\\nsoftshrink(x) = \\left\\{\n\\begin{array}{ll}\nx-\\lambda & (x \\gt \\lambda) \\\\\n0 & (-\\lambda \\leq x \\leq \\lambda) \\\\\nx+\\lambda & (x \\lt -\\lambda) \\\\\n\\end{array}\n\\right.\n```\n\"\"\"\nsoftshrink(x; λ=0.5) = min(x+λ, max(x-λ, 0))\n\n@doc raw\"\"\"\n    softsign(x) = x / (1+abs(x))\nThe softsign activation function. This is the expression:\n```math\nsoftsign(x) = \\frac{x}{1+|x|}\n```\n\"\"\"\nsoftsign(x) = x / (1 + abs(x))\n\n@doc raw\"\"\"\n    softplus(x) = log(1 + exp(x))\nthe softplus activation function. This is the expression:\n```math\nsoftplus(x) = \\ln(1+e^x)\n```\n\"\"\"\nsoftplus(x) = log(1 + exp(x))\n\n@doc raw\"\"\"\n    mish(x) = x * tanh(softplus(x))\nThe mish function. This is the expression:\n```math\nsoftplus(x) = \\ln(1+e^x) \\\\\nmish(x) = x\\tanh(softplus(x))\n```\n\"\"\"\nmish(x) = x * tanh(softplus(x))\n\n@doc raw\"\"\"\n    swish(x; β=1)\nThe swish function. This is the expression:\n```math\n\\sigma(x) = \\frac{1}{1+e^{-x}} \\\\\nswish(x) = x\\sigma(\\beta x)\n```\n\"\"\"\nswish(x; β=1) = x * σ(β*x)\n\n@doc raw\"\"\"\n    gaussian(x)\nThe Gauss Function. This is the expression:\n```math\nGaussian(x) = e^{-x^{2}}\n```\n\"\"\"\ngaussian(x) = exp(-x^2)\n\n@doc raw\"\"\"\n    GCU(x)\nGrowing Cosine Unit. This is the expression:\n```math\nGCU(x) = x\\cos(x)\n```\n\"\"\"\nGCU(x) = x*cos(x)\n\n@doc raw\"\"\"\n    SQU(x)\nShifted Quadratic Unit. SQU is a biologically inspired activation that enables single neurons to learn the XOR function. This is the expression:\n```math\nSQU(x) = x^{2}+x\n```\n\"\"\"\nSQU(x) = x^2+x\n\n@doc raw\"\"\"\n    NCU(x)\nNon-Monotonic Cubic Unit. This is the expression:\n```math\nNCU(x) = x-x^{3}\n```\n\"\"\"\nNCU(x) = x-x^3\n\n@doc raw\"\"\"\n    SSU(x)\nShifted Sinc Unit. This is the expression:\n```math\nSSU(x) = \\pi sinc(x - \\pi)\n```\n\"\"\"\nSSU(x) = pi*sinc(x-pi)\n\n@doc raw\"\"\"\n    DSU(x)\nDecaying Sine Unit. This is the expression:\n```math\nDSU(x) = \\frac{\\pi}{2}(sinc(x-\\pi)-sinc(x+\\pi))\n```\n\"\"\"\nDSU(x) = (pi/2)*(sinc(x-pi)-sinc(x+pi))", "meta": {"hexsha": "264800134743b11054e1f9d00727e4013eddc232", "size": 7232, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NeuralNetwork/activations.jl", "max_stars_repo_name": "simonp0420/HorseML.jl", "max_stars_repo_head_hexsha": "ccdf43e2854fba367ba73ee70e81a3b90dc9bc6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-12-16T22:10:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T07:09:36.000Z", "max_issues_repo_path": "src/NeuralNetwork/activations.jl", "max_issues_repo_name": "simonp0420/HorseML.jl", "max_issues_repo_head_hexsha": "ccdf43e2854fba367ba73ee70e81a3b90dc9bc6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-12-12T14:13:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T14:00:10.000Z", "max_forks_repo_path": "src/NeuralNetwork/activations.jl", "max_forks_repo_name": "simonp0420/HorseML.jl", "max_forks_repo_head_hexsha": "ccdf43e2854fba367ba73ee70e81a3b90dc9bc6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-28T21:15:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T21:15:30.000Z", "avg_line_length": 20.0332409972, "max_line_length": 194, "alphanum_fraction": 0.5955475664, "num_tokens": 2739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7651429958126094}}
{"text": "# Natural Round\nround2(x; digits = 0) = sign(x) * floor( abs(x) * 10.0^digits + 0.5 ) / (10.0^digits)\n\n# Cumulative distribution function\nfunction CDF(x, F::EG)\n    if x < minimum(F.table.scale) return 0 end\n    if x > maximum(F.table.scale) return 1 end\n    F.table.cumprob[F.table.scale .== x][1]\nend\n\n# Percentile rank function\nfunction PRF(x, F::EG)\n    if x < (minimum(F.table.scale) - F.interval/2.0) return 0.0 end\n    if x ≥ (maximum(F.table.scale) + F.interval/2.0) return 100.0 end\n    x′ = round2(x)\n    Fx1 = CDF(x′-F.interval, F)\n    Fx = CDF(x′, F)\n    P = 100*(Fx1+(x-x′+F.interval/2.0)*(Fx-Fx1))[1]\n    return P\nend\n\n# Percentile Function\nfunction p_search_descend(P, F::EG, offset)\n    x = nothing;iter = length(F.table.scale)\n    while x === nothing\n        iter -= 1\n        x =  100CDF(F.table.scale[iter], F) > P ? nothing : F.table.scale[iter+offset]\n    end\n    return x\nend\nfunction p_search_ascend(P, F::EG, offset)\n    x = nothing;iter = 0\n    while x === nothing\n        iter += 1\n        x = 100CDF(F.table.scale[iter], F) < P ? nothing : iter == 1 ? 0.0 : F.table.scale[iter+offset]\n    end\n    return x\nend\n\n# The inverse of the percentile rank function (Percentile function)\nfunction PFu(P, F::EG)\n    if P ≥ 100.0 return (maximum(F.table.scale) + .5) end\n    xu = P > 50.0 ? p_search_descend(P, F, 1) : p_search_ascend(P, F, 0)\n    x = (P/100 - CDF(xu-F.interval, F)) / (CDF(xu, F) - CDF(xu-F.interval, F))\n    return isinf(x) || isnan(x) ? xu -F.interval/2.0 : x + xu -F.interval/2.0\nend\nfunction PFl(P, F::EG)\n    if P ≤ 0.0 return -.5 end\n    xl = P > 50.0 ? p_search_descend(P, F, 0) : p_search_ascend(P, F, -1)\n    x = (P/100 - CDF(xl, F)) / (CDF(xl+F.interval, F) - CDF(xl, F))\n    return isinf(x) || isnan(x) ? xl + F.interval/2.0 : x + xl + F.interval/2.0\nend\n\n# equipercentile equating\nmutable struct SGEquateResult <: SGEquateMethod\n    method\n    table\n    estimates\n    data\nend\n\"\"\"\n    Equipercentile(X::EG, Y::EG; case = :middle)\n\nEquipercentile Equating under equivalent (single) group design. The smoothed frequency can be used.\nA table returned by the function contains 2 columns. The first one stands for the base scale score in the test X.\nThe second one is equated score from test Y, which is equipercentile score on the base scale.\n\n`case` represents which equating case use. Pass to the symbols below.\n\n- `:upper` Calculating scores correspond to arbitrary percentile P, use the smallest integer score with a cumulative percent that is greater than P.\n- `:lower` (default) Contrary to above case, use the largest integer score with a cumulative percent that is less than P\n- `:both` (Not for practice) Show both case of upper and lower.\n- `:middle` Use midpoint case upper between lower.\n\nIn my example cases, it seems that equate package in R uses `lower` case to equate.\n\"\"\"\nfunction Equipercentile(X::EG, Y::EG; case = :lower)\n    scaleX = X.table.scale\n    eYxu = zeros(Float64, length(scaleX))\n    eYxl = zeros(Float64, length(scaleX))\n    for (i,v) in enumerate(scaleX)\n        P = PRF(v, X)\n        eYxu[i] = PFu(P, Y)\n        eYxl[i] = PFl(P, Y)\n    end\n    if case == :upper\n        eYx = eYxu\n    elseif case == :lower\n        eYx = eYxl\n    elseif case == :both\n        eYx = string.(eYxu, \"_\", eYxl)\n    elseif case == :middle\n        eYx = (eYxu .+ eYxl) ./ 2.0\n    end\n    tbl = DataFrame(scaleX = scaleX, eYx = eYx)\n    return SGEquateResult(\n        Symbol(\"Equipercentile($(case))\"),\n        tbl, \n        nothing, \n        (X = X, Y = Y)\n    )\nend\n# linear equating\n\"\"\"\n    Linear(X::EG, Y::EG)\n\nLinear equating under the equivalent group desing.\nThis method, equate to match first 2 moments, is so simple to comprehend the equating result.\n\"\"\"\nfunction Linear(X::EG, Y::EG)\n    μX = mean(X.raw); σX = std(X.raw)\n    μY = mean(Y.raw); σY = std(Y.raw)\n    slope = σY/σX; intercept = μY - slope*μX\n    lYx = @. X.table.scale * slope + intercept\n    tbl = DataFrame(scaleX = X.table.scale, lYx = lYx)\n    return SGEquateResult(\n        :Linear,\n        tbl, \n        (slope = slope, intercept = intercept), \n        (X = X, Y = Y)\n    )\nend\n\n# mean equating\n\"\"\"\n    Mean(X::EG, Y::EG)\n\nMean equating under the equivalent group desing.\nThis method, equate to match only first moments = mean, is so simple to comprehend the equating result.\n\"\"\"\nfunction Mean(X::EG, Y::EG)\n    μX = mean(X.raw)\n    μY = mean(Y.raw)\n    slope = 1.0; intercept = μY - μX\n    lYx = @. X.table.scale * slope + intercept\n    tbl = DataFrame(scaleX = X.table.scale, lYx = lYx)\n    return SGEquateResult(\n        :Mean, \n        tbl, \n        (slope = slope, intercept = intercept), \n        (X = X, Y = Y)\n    )\nend\n", "meta": {"hexsha": "06aa34df59381f8327fa3eb9fcbca50f56ef2968", "size": 4660, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SGdesign.jl", "max_stars_repo_name": "takuizum/Equate.jl", "max_stars_repo_head_hexsha": "8ba0055ef69fc086fd4b39cff545a623d5a793fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-10T14:48:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-10T14:48:51.000Z", "max_issues_repo_path": "src/SGdesign.jl", "max_issues_repo_name": "takuizum/Equate.jl", "max_issues_repo_head_hexsha": "8ba0055ef69fc086fd4b39cff545a623d5a793fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-01-06T00:14:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T19:11:22.000Z", "max_forks_repo_path": "src/SGdesign.jl", "max_forks_repo_name": "takuizum/Equate.jl", "max_forks_repo_head_hexsha": "8ba0055ef69fc086fd4b39cff545a623d5a793fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3611111111, "max_line_length": 148, "alphanum_fraction": 0.6227467811, "num_tokens": 1507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7651429885974298}}
{"text": "@doc raw\"\"\"\n    LocalLevel(y::Vector{Fl}) where Fl\n\nThe local level model is defined by:\n```math\n\\begin{gather*}\n    \\begin{aligned}\n        y_{t} &=  \\mu_{t} + \\varepsilon_{t} \\quad \\varepsilon_{t} \\sim \\mathcal{N}(0, \\sigma^2_{\\varepsilon})\\\\\n        \\mu_{t+1} &= \\mu_{t} + \\eta_{t} \\quad \\eta_{t} \\sim \\mathcal{N}(0, \\sigma^2_{\\eta})\\\\\n    \\end{aligned}\n\\end{gather*}\n```\n\n# Example\n```jldoctest\njulia> model = LocalLevel(rand(100))\nLocalLevel model\n```\n\nSee more on [Nile river annual flow](@ref)\n\n# References\n * Durbin, James, & Siem Jan Koopman. (2012). \"Time Series Analysis by State Space Methods: Second Edition.\" Oxford University Press. pp. 9\n\"\"\"\nmutable struct LocalLevel <: StateSpaceModel\n    hyperparameters::HyperParameters\n    system::LinearUnivariateTimeInvariant\n    results::Results\n\n    function LocalLevel(y::Vector{Fl}) where Fl\n\n        # Define system matrices\n        Z = ones(Fl, 1)\n        T = ones(Fl, 1, 1)\n        R = ones(Fl, 1, 1)\n        d = zero(Fl)\n        c = zeros(Fl, 1)\n        H = one(Fl)\n        Q = ones(Fl, 1, 1)\n\n        system = LinearUnivariateTimeInvariant{Fl}(y, Z, T, R, d, c, H, Q)\n\n        # Define hyperparameters names\n        names = [\"sigma2_ε\", \"sigma2_η\"]\n        hyperparameters = HyperParameters{Fl}(names)\n\n        return new(hyperparameters, system, Results{Fl}())\n    end\nend\n\n# Obligatory methods\nfunction default_filter(model::LocalLevel)\n    Fl = typeof_model_elements(model)\n    a1 = zero(Fl)\n    P1 = Fl(1e6)\n    steadystate_tol = Fl(1e-5)\n    return ScalarKalmanFilter(a1, P1, 1, steadystate_tol)\nend\n\nfunction initial_hyperparameters!(model::LocalLevel)\n    Fl = typeof_model_elements(model)\n    observed_variance = var(model.system.y[findall(!isnan, model.system.y)])\n    initial_hyperparameters = Dict{String,Fl}(\n        \"sigma2_ε\" => observed_variance, \"sigma2_η\" => observed_variance\n    )\n    set_initial_hyperparameters!(model, initial_hyperparameters)\n    return model\nend\n\nfunction constrain_hyperparameters!(model::LocalLevel)\n    constrain_variance!(model, \"sigma2_ε\")\n    constrain_variance!(model, \"sigma2_η\")\n    return model\nend\n\nfunction unconstrain_hyperparameters!(model::LocalLevel)\n    unconstrain_variance!(model, \"sigma2_ε\")\n    unconstrain_variance!(model, \"sigma2_η\")\n    return model\nend\n\nfunction fill_model_system!(model::LocalLevel)\n    model.system.H = get_constrained_value(model, \"sigma2_ε\")\n    model.system.Q[1] = get_constrained_value(model, \"sigma2_η\")\n    return model\nend\n\nfunction reinstantiate(::LocalLevel, y::Vector{Fl}) where Fl\n    return LocalLevel(y)\nend\n\nhas_exogenous(::LocalLevel) = false\n", "meta": {"hexsha": "91398c2da78b4dc9a757a00742079d8b367bc3f6", "size": 2608, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/locallevel.jl", "max_stars_repo_name": "pkofod/StateSpaceModels.jl", "max_stars_repo_head_hexsha": "2921e9fd8c30ede584f6606a068700e0027f207b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/models/locallevel.jl", "max_issues_repo_name": "pkofod/StateSpaceModels.jl", "max_issues_repo_head_hexsha": "2921e9fd8c30ede584f6606a068700e0027f207b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/locallevel.jl", "max_forks_repo_name": "pkofod/StateSpaceModels.jl", "max_forks_repo_head_hexsha": "2921e9fd8c30ede584f6606a068700e0027f207b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0430107527, "max_line_length": 139, "alphanum_fraction": 0.6763803681, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7651429872333219}}
{"text": "using OrdinaryDiffEq, PyPlot, LinearAlgebra\n\nconst tol = 1e-8\n\nfunction compute_max_lyapunov_exponent(rhs_fn, x0, params, δ0, Δt, N)\n    # solve the reference trajectory\n    problem = ODEProblem(rhs_fn, x0, (0, N*Δt), params)\n    solver = AutoTsit5(Rosenbrock23())\n    ref_sol = solve(problem, solver, reltol=tol, abstol=tol, dense=true)\n    # neighboring trajectory\n    du = ref_sol.u[2] - ref_sol.u[1] # vector along trajectory\n    v = rand(size(du, 1))\n    pert = v - dot(du, v) / dot(du, du) * du # vector orthogonal to trajectory\n    pert *= δ0 / norm(pert) # make pertubation small\n    x_test = x0 + pert\n    # result\n    s = 0.0\n    for i in 1:N\n        t = i*Δt\n        # advance neighboring trajectory\n        p = ODEProblem(rhs_fn, x_test, ((i - 1)*Δt, t), params)\n        neighboring_sol = solve(p, solver,  reltol=tol, abstol=tol, dense=true)\n        # compute seperation\n        δ = norm(neighboring_sol(t) - ref_sol(t))\n        # update result\n        s += log(δ / δ0)\n        # rescale the neighboring trajectory\n        x_ref = ref_sol(t)\n        x_test = x_ref + δ0 / δ * (x_test - x_ref)\n    end\n    # result\n    return s / (Δt * N)\nend\n\nfunction lorentz_rhs(du, u, p, t)\n    β, σ, ρ = p\n    x, y, z = u\n    du[1] = σ * (y - x)\n    du[2] = - x * z - ρ * x - y\n    du[3] = x * y - β * z\nend\n\nβ = 8 / 3.\nσ = 10.0\nρ_range = 20:0.1:100\nλs = [compute_max_lyapunov_exponent(lorentz_rhs, [1.0, 1.0, 1.0],\n           [β, σ, ρ], 1e-5, 0.001, 20)\n     for ρ = ρ_range]\nplot(ρ_range, λs)\nxlabel(\"\\$\\\\rho\\$\")\nylabel(\"\\$\\\\lambda_1\\$\")\n", "meta": {"hexsha": "7473e91b1b6bf73a7f7950ecf0a68f492988acb4", "size": 1540, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "max_lyapunov_exponent.jl", "max_stars_repo_name": "cosmo-jana/numerics-physics-stuff", "max_stars_repo_head_hexsha": "f5fb35c00c84ca713877e20c1d8186e76883cd28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "max_lyapunov_exponent.jl", "max_issues_repo_name": "cosmo-jana/numerics-physics-stuff", "max_issues_repo_head_hexsha": "f5fb35c00c84ca713877e20c1d8186e76883cd28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "max_lyapunov_exponent.jl", "max_forks_repo_name": "cosmo-jana/numerics-physics-stuff", "max_forks_repo_head_hexsha": "f5fb35c00c84ca713877e20c1d8186e76883cd28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6153846154, "max_line_length": 79, "alphanum_fraction": 0.5785714286, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7651429868424888}}
{"text": "export first_permuted_prime\nexport isprime\nexport sieve_eratosthenes\n\n\"\"\"\nCreates permutations of numbers and returns when the first prime value is reached.\n\"\"\"\nfunction first_permuted_prime(elementlist::Array, multiplier::Array, k::Integer=1)\n    if k == length(elementlist)\n        if elementlist[end] % 2 == 1\n            val = sum(elementlist .* multiplier)\n            if isprime(val)\n                return val\n            else\n                return -1\n            end\n        else\n            return -1\n        end\n    else\n        for i in k:length(elementlist)\n            elementlist[k], elementlist[i] = elementlist[i], elementlist[k]\n            v = first_permuted_prime(elementlist, multiplier, k + 1)\n            if v > 0\n                return v\n            end\n            elementlist[k], elementlist[i] = elementlist[i], elementlist[k]\n        end\n    end\n    return -1\nend\n\n\"\"\"\nReasonably fast test for primality.\n\"\"\"\nfunction isprime(n)\n    if n == 2 || n == 3\n        return true\n    end\n    if n < 2 || n % 2 == 0\n        return false\n    end\n    if n < 9\n        return true\n    end\n    if n % 3 == 0\n        return false\n    end\n    r = typeof(n)(floor(sqrt(n)))\n    f = 5\n    while f <= r\n        if n % f == 0\n            return false\n        end\n        if n % (f + 2) == 0\n            return false\n        end\n        f += 6\n    end\n    return true\nend\n\n\"\"\"\nImplements the Sieve of Eratosthenes to return all prime numbers up \"n\".\nhttps://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\n\"\"\"\nfunction sieve_eratosthenes(n::Integer=500, nstart::Integer=2)::Array{Integer}\n    primes = trues(n)\n    primes[1] = false\n\n    for i in 2:floor(Integer, sqrt(n))\n        if primes[i]\n            @inbounds primes[(i+i):i:n] .= false\n        end\n    end\n    primes[1:nstart-1] .= false\n    return findall(primes)\nend\n", "meta": {"hexsha": "941c02aa825d1f6e156fe81f3b80a0256b1f5c26", "size": 1831, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/prime.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/prime.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/prime.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1772151899, "max_line_length": 82, "alphanum_fraction": 0.5516111415, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7651429864516556}}
{"text": "# This file contains functions to calculate polygon centroid and mean center\n\n\"\"\"\n    meancenter(P)\nCalculate the mean center of a polygon or vector of polygons ``P``.\n\"\"\"\nfunction meancenter end\n\nfunction meancenter(P::Union{AbstractPolygon,AbstractMultiPolygon})::Tuple{Float64, Float64}\n    xy = _getpointsPoligon(P)\n\n    cx = mean(xy[1])\n    cy = mean(xy[2])\n\n    return cx, cy\nend\n\nfunction meancenter(P::Vector{T} where T <:Union{Missing,AbstractPolygon,AbstractMultiPolygon})::Tuple{Vector{Float64}, Vector{Float64}}\n    cxy = meancenter.(P)\n\n    cx = first.(cxy)\n    cy = last.(cxy)\n\n    return cx, cy\nend\n\n\"\"\"\n    centroid(P)\nCalculate the centroid of a polygon or vector of polygons ``P``.\n\"\"\"\nfunction centroid end\n\nfunction centroid(P::Union{AbstractPolygon,AbstractMultiPolygon})::Tuple{Float64, Float64}\n    xy = _getpointsPoligon(P)\n\n    xo = xy[1]\n    yo = xy[2]\n\n    # Formula: https://en.wikipedia.org/wiki/Centroid#Of_a_polygon\n\n    # If the last point is not equal to the first point, add a new point similar to the first point.\n    if (xo[end] != xo[1]) | (yo[end] != yo[1])\n        x = copy(xo)\n        y = copy(yo)\n        \n        push!(x, x[1])\n        push!(y, y[1])    \n    else\n        x = xo\n        y = yo\n    end\n\n    # Loop to calculate elements of A and centroids\n    n = length(x)\n    A = 0\n    xprodsum = 0\n    yprodsum = 0\n\n    for i in 1:n-1\n        xycross = x[i] * y[i + 1] - x[i + 1] * y[i]\n        xprod = (x[i] + x[i + 1]) * xycross\n        yprod = (y[i] + y[i + 1]) * xycross\n\n        A += xycross\n        xprodsum += xprod\n        yprodsum += yprod\n    end\n    A = A / 2\n\n    # Centroids\n    cx = 1 / (6 * A) * xprodsum\n    cy = 1 / (6 * A) * yprodsum\n\n    return cx, cy\nend\n\nfunction centroid(P::Vector{T} where T <:Union{Missing,AbstractPolygon,AbstractMultiPolygon})::Tuple{Vector{Float64}, Vector{Float64}}\n    cxy = centroid.(P)\n\n    cx = first.(cxy)\n    cy = last.(cxy)\n\n    return cx, cy\nend\n", "meta": {"hexsha": "459bdf4812137d5442fc9bc5ca3ac0757ee84c2d", "size": 1943, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sweights/centroid.jl", "max_stars_repo_name": "javierbarbero/SpatialDependence.jl", "max_stars_repo_head_hexsha": "fa6f94e0afd6aab4214709e73ba08289c6b95fbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-07-03T21:57:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T20:12:18.000Z", "max_issues_repo_path": "src/sweights/centroid.jl", "max_issues_repo_name": "javierbarbero/SpatialDependence.jl", "max_issues_repo_head_hexsha": "fa6f94e0afd6aab4214709e73ba08289c6b95fbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-03T20:56:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-15T20:16:18.000Z", "max_forks_repo_path": "src/sweights/centroid.jl", "max_forks_repo_name": "javierbarbero/SpatialDependence.jl", "max_forks_repo_head_hexsha": "fa6f94e0afd6aab4214709e73ba08289c6b95fbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-12T12:22:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-12T12:22:23.000Z", "avg_line_length": 22.8588235294, "max_line_length": 136, "alphanum_fraction": 0.5985589295, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.765142983332607}}
{"text": "include(\"05_one_site_operator_custom.jl\")\n\nprintln(\"\n#######################################################\n# Tutorial 6                                          #\n#                                                     #\n# 2-site state                                        #\n#######################################################\n\")\n\ni1 = Index(2, \"S=1/2\")\ni2 = Index(2, \"S=1/2\")\n\n@show i1 ≠ i2\n\n# Uninitialized ITensor\nZpZm = ITensor(i1, i2)\n\n# State |Z+⟩₁|Z-⟩₂ ≡ |Z+Z-⟩\nZpZm[i1 => 1, i2 => 2] = 1\n\n# Order doesn't matter!\nZpZm[i2 => 2, i1 => 1] = 1\n\n# Or construct from single site basis states:\n# State |Z+⟩₁\nZp1 = state(\"Z+\", i1)\n# State |Z+⟩₂\nZp2 = state(\"Z+\", i2)\n\n# State |Z-⟩₁\nZm1 = state(\"Z-\", i1)\n# State |Z-⟩₂\nZm2 = state(\"Z-\", i2)\n\n# State |Z+Z-⟩ = |Z+⟩₁|Z-⟩₂\nZpZm = Zp1 * Zm2\n\n# State |Z+Z-⟩ = |Z-⟩₂|Z+⟩₁ = |Z+⟩₁|Z-⟩₂\n# Order doesn't matter!\nZpZm = Zm2 * Zp1\n\n# State |Z-Z+⟩\nZmZp = Zm1 * Zp2\n\n# State |Z+Z+⟩\nZpZp = Zp1 * Zp2\n\nXp1 = state(\"X+\", i1)\nXp2 = state(\"X+\", i2)\n\nXm1 = state(\"X-\", i1)\nXm2 = state(\"X-\", i2)\n\n# State |Z-⟩|Z-⟩\nZmZm = Zm1 * Zm2\n\n# Cat state (|Z+⟩|Z-⟩ + |Z-⟩|Z+⟩) / √2\n\n# With element setting:\nCat = ITensor(i1, i2)\nCat[i1 => 1, i2 => 2] = 1 / √2\nCat[i1 => 2, i2 => 1] = 1 / √2\n\n# Or build from single site basis states:\nCat = (Zp1 * Zm2 + Zm1 * Zp2) / √(2)\n@show (dag(Cat) * Cat)[]\n@show inner(Cat, Cat)\n@show norm(Cat)\n\nentanglement_entropy(s) = sum(sn -> iszero(sn) ? zero(sn) : -sn^2 * log(sn^2), s)\n\n# Compact syntax for matrix decompositions like SVD,\n# which reveal the rank/entanglement:\n_, S, _ = svd(ZmZp, i1)\ns = diag(S)\n@show s\n@show entanglement_entropy(s)\n\n_, S, _ = svd(Cat, i1)\ns = diag(S)\n@show s\n@show entanglement_entropy(s)\n", "meta": {"hexsha": "686b8ca3856ab73ae9d3ab7798d852a8e15c5999", "size": 1681, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tutorials/06_two_site_state.jl", "max_stars_repo_name": "mtfishman/ITensorTutorials.jl", "max_stars_repo_head_hexsha": "dcbc1988299e6a7f3b612faeb31563da38ece3be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-11T10:42:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T01:03:58.000Z", "max_issues_repo_path": "tutorials/06_two_site_state.jl", "max_issues_repo_name": "mtfishman/ITensorTutorials.jl", "max_issues_repo_head_hexsha": "dcbc1988299e6a7f3b612faeb31563da38ece3be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/06_two_site_state.jl", "max_forks_repo_name": "mtfishman/ITensorTutorials.jl", "max_forks_repo_head_hexsha": "dcbc1988299e6a7f3b612faeb31563da38ece3be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0119047619, "max_line_length": 81, "alphanum_fraction": 0.4848304581, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.8670357649558006, "lm_q1q2_score": 0.7650965175288458}}
{"text": "\"This code defines some simple finite difference approximations, applies them to\napproximate u'(x), and compares the result to the exact solution.\"\n\n# run file by typing \"include(\"fd_simple.jl\")\", copying and pasting into the REPL, or\n# selecting code and pressing Ctrl/Command-Enter\n\nDfwd(u,x,h) = (u(x+h) - u(x))/h\nDback(u,x,h) = (u(x) - u(x-h))/(h)\nD2(u,x,h) = (u(x+h) - u(x-h))/(2*h)\n\nu(x) = sin(1+pi*x)\ndudx(x) = pi*cos(1+pi*x)\n\nx̄ = .5\nh = .001\n@show Dfwd(u,x̄,h) - dudx(x̄)\n@show Dback(u,x̄,h) - dudx(x̄)\n@show D2(u,x̄,h) - dudx(x̄)\n", "meta": {"hexsha": "e84052268f4e33f098bb98e5d69402f2baa95f95", "size": 540, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week1/fd_simple.jl", "max_stars_repo_name": "jlchan/caam452_s21", "max_stars_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:38:43.000Z", "max_issues_repo_path": "week1/fd_simple.jl", "max_issues_repo_name": "jlchan/caam452_s21", "max_issues_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week1/fd_simple.jl", "max_forks_repo_name": "jlchan/caam452_s21", "max_forks_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4210526316, "max_line_length": 85, "alphanum_fraction": 0.6259259259, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9585377284730286, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.76509215003504}}
{"text": "#___  ____       ___ _____   _   _       _ _\r\n#|  \\/  | |     |_  /  __ \\ | | | |     (_| |\r\n#| .  . | |       | | /  \\/ | | | |_ __  _| |_ ___\r\n#| |\\/| | |       | | |     | | | | '_ \\| | __/ _ \\\r\n#| |  | | |___/\\__/ | \\__/\\ | |_| | | | | | || (_) |\r\n#_______\\_____\\____/ \\____/  _____|_|___|_____\\_____ _____ _____\r\n#| ___ \\        (_)         | | \\ \\ / / / __  |  _  / __  |  _  |\r\n#| |_/ _ __ ___  _  ___  ___| |_ \\ V /  `' / /| |/' `' / /| |/' |\r\n#|  __| '__/ _ \\| |/ _ \\/ __| __|/   \\    / / |  /| | / / |  /| |\r\n#| |  | | | (_) | |  __| (__| |_/ /^\\ \\ ./ /__\\ |_/ ./ /__\\ |_/ /\r\n#\\_|  |_|  \\___/| |\\___|\\___|\\__\\/   \\/ \\_____/\\___/\\_____/\\___/\r\n#              _/ |\r\n#             |__/\r\n#\r\n# This code is part of the proposal of the team \"MLJC UniTo\" - University of Turin\r\n# for \"ProjectX 2020\" Climate Change for AI.\r\n# The code is licensed under MIT 3.0\r\n# Please read readme or comments for credits and further information.\r\n\r\n# Compiler: Julia 1.5.3\r\n#= Short description of this file: LOTKA-VOLTERRA EQUATIONS.\r\n\r\nNumerical approach using DifferentialEquations.jl and Neural ODE layer approach\r\nusing DiffEqFlux.jl based on Chris Rackauckas' paper \" DiffEqFlux.jl -\r\nA Julia Library for Neural Differential Equations\"\r\n(https://arxiv.org/abs/1902.02376 )\r\n=#\r\n\r\nusing Flux, DiffEqFlux, DifferentialEquations, Plots\r\n\r\n#= To solve the equations numerically, we first define a problem type by giving\r\nthe equation, the initial condition, and timespan to solve over.\r\n=#\r\nfunction lotka_volterra(du,u,p,t) #Define equations\r\n  x, y = u\r\n  α, β, δ, γ = p\r\n  du[1] = dx = α*x - β*x*y\r\n  du[2] = dy = -δ*y + γ*x*y\r\nend\r\nu0 = [1.0,1.0] #initial condition\r\ntspan = (0.0,10.0) #timespan\r\np = [1.5,1.0,3.0,1.0] #parameters\r\nprob = ODEProblem(lotka_volterra,u0,tspan,p)\r\n\r\n#= Solve the ODE problem using 5th order Tsitouras method (Tsit5) and plot the\r\nsolution.\r\n=#\r\nsol = solve(prob,Tsit5())\r\nplot(sol)\r\n\r\n# Data generation from the above ODE solution\r\nsol = solve(prob,Tsit5(),saveat=0.1)\r\nA = sol[1,:] # length 101 vector\r\nt = 0:0.1:10.0\r\nscatter!(t,A) #plot (t,A) over the ODE's solution\r\n\r\n#= Build a neural network with the function as our single layer,\r\nand define a loss function as the squared distance of the above generated data\r\nfrom 1.\r\n =#\r\n\r\np = param([2.2, 1.0, 2.0, 0.4]) # Initial Parameter Vector\r\nfunction predict_rd() # Our 1-layer neural network\r\n  diffeq_rd(p,prob,Tsit5(),saveat=0.1)[1,:]\r\nend\r\nloss_rd() = sum(abs2,x-1 for x in predict_rd()) # loss function\r\n\r\n#= 100 epoch neural network training to minimize loss function and thus get the\r\noptimized parameters.\r\n=#\r\n\r\ndata = Iterators.repeated((), 100)\r\nopt = ADAM(0.1)\r\ncb = function () #callback function to observe training\r\n  display(loss_rd())\r\n  # using `remake` to re-create our `prob` with current parameters `p`\r\n  display(plot(solve(remake(prob,p=Flux.data(p)),Tsit5(),saveat=0.1),ylim=(0,6)))\r\nend\r\n# Display the ODE with the initial parameter values.\r\ncb()\r\n\r\nFlux.train!(loss_rd, [p], data, opt, cb = cb)\r\n\r\n#= Flux trains the neural network, finding its parameters (p) that minimize the\r\ncost function: the forward pass of the neural network includes solving an ODE.\r\n=#\r\n", "meta": {"hexsha": "7ecf9da37b77553a4789317dbb4496c24ec8e118", "size": 3166, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Model_Selection/DiffEqFlux/ODE Lotka-Volterra DiffEqFlux.jl", "max_stars_repo_name": "MachineLearningJournalClub/MLJC-UniTo-ProjectX-2020-public", "max_stars_repo_head_hexsha": "49cf39583b3713a7d56e3819825969a904cbca71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2020-11-30T21:49:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T23:09:46.000Z", "max_issues_repo_path": "Model_Selection/DiffEqFlux/ODE Lotka-Volterra DiffEqFlux.jl", "max_issues_repo_name": "MachineLearningJournalClub/MLJC-UniTo-ProjectX-2020-public", "max_issues_repo_head_hexsha": "49cf39583b3713a7d56e3819825969a904cbca71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-30T20:10:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-30T20:10:15.000Z", "max_forks_repo_path": "Model_Selection/DiffEqFlux/ODE Lotka-Volterra DiffEqFlux.jl", "max_forks_repo_name": "MachineLearningJournalClub/MLJC-UniTo-ProjectX-2020-public", "max_forks_repo_head_hexsha": "49cf39583b3713a7d56e3819825969a904cbca71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-12-21T22:39:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T09:30:17.000Z", "avg_line_length": 36.3908045977, "max_line_length": 83, "alphanum_fraction": 0.6013897663, "num_tokens": 1039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377261041522, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7650921458434098}}
{"text": "function solve_ode(u0, tspan, p, time_interval=1)\n        function SIR(du,u,p,t)\n                du[1]=-p[1]*u[1]*u[2]/(u[1]+u[2]+u[3])\n                du[2]=p[1]*u[1]*u[2]/(u[1]+u[2]+u[3]) - p[2]*u[2]\n                du[3] = p[2]*u[2]\n        end\n        problem = ODEProblem(SIR, u0, tspan,p)\n        sol=solve(problem, saveat=time_interval)\n        return sol\nend\n\nfunction solve_ode_seasonal_forcing(u0, tspan, p,time_interval=1)\n        function SIR_forcing(du,u,p,t)\n                L, beta0, beta1, theta, gamma = p\n                # 17 weeks (~ 4 months) seasonal?\n                beta_t = beta0*(1 + beta1*cos( (2*pi*t - theta)/26 ) ) \n                # du[1]=(Ntot-u[1]-u[2])/L - beta_t*u[2]*u[1]/Ntot\n                # du[2]=beta_t*u[1]*u[2]/Ntot - u[2]/D\n                du[1] =  -beta_t*u[2]*u[1]/(u[1]+u[2]+u[3]) + u[3]/L\n                du[2] = beta_t*u[1]*u[2]/(u[1]+u[2]+u[3]) - gamma*u[2]\n                du[3] = gamma*u[2]\n               \n        end\n        problem = ODEProblem(SIR_forcing, u0, tspan,p)\n        sol=solve(problem, saveat=time_interval)\n        return sol\nend\n\nfunction solve_seir(u0, tspan, p, time_interval=1)\n        function SEIR(du,u,p,t)\n                du[1]=p[1]*(u[1]+u[2]+u[3]) - p[1]*u[1] - p[2]*u[1]*u[3]/(u[1]+u[2]+u[3]+u[4])\n                du[2]=p[2]*u[1]*u[3]/(u[1]+u[2]+u[3]+u[4]) - (p[1] + p[3])*u[2]\n                du[3] = p[3]*u[2] - (p[4]+p[1])*u[3]\n                du[4] = p[4]*u[3] - p[1]*u[4]\n        end\n        problem = ODEProblem(SEIR, u0, tspan,p)\n        sol=solve(problem, saveat=time_interval)\n        return sol\nend", "meta": {"hexsha": "b37d6929ee45e877716be6e2674ef0e4979526d6", "size": 1586, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sir_ode.jl", "max_stars_repo_name": "tyhlee/UBC440540_Project", "max_stars_repo_head_hexsha": "dc359b5a4037ca59b2212adfc5b4f0a088a58a84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sir_ode.jl", "max_issues_repo_name": "tyhlee/UBC440540_Project", "max_issues_repo_head_hexsha": "dc359b5a4037ca59b2212adfc5b4f0a088a58a84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sir_ode.jl", "max_forks_repo_name": "tyhlee/UBC440540_Project", "max_forks_repo_head_hexsha": "dc359b5a4037ca59b2212adfc5b4f0a088a58a84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6666666667, "max_line_length": 94, "alphanum_fraction": 0.4590163934, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574668, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7650921440779699}}
{"text": "using Statistics\nusing LinearAlgebra\nusing Polynomials: Poly\nimport PyPlot; const plt = PyPlot\n\nfunction leastsquares(x, y, Ω; order::Integer = 1)\n    X = ones((length(x), order+1))\n    for n in 1:order\n        X[:, n+1] = x.^n\n    end\n\n    if ndims(Ω) == 1\n        Ω = diagm(0 => Ω)\n    end\n\n    w = inv(Ω)  # Weights defined as 1/σ²\n    Xᵀ = transpose(X)\n    kω = inv(Xᵀ*w*X)*Xᵀ*w\n    coeffs = kω*y\n    Σ = kω*Ω*kω'\n    coeffs, Σ\nend\n\nfunction leastsquares(x, y; order::Integer = 1)\n    X = ones((length(x), order+1))\n    for n in 1:order\n        X[:, n+1] = x.^n\n    end\n\n    Xᵀ = transpose(X)\n    inv(Xᵀ*X)*Xᵀ*y\nend\n\nfunction plotresiduals(x, y, coefficients; ax=nothing)\n    if ax ≡ nothing\n        fig, ax = plt.subplots(ncols=2)\n    end\n    p = Poly(coefficients)\n    ŷ = p.(y)\n    xrange = range(minimum(x), maximum(x), length=100)\n    ŷrange = p.(xrange)\n\n    ê = ŷ - y\n    ax[1].scatter(x, y)\n    ax[1].scatter(x, ŷ)\n    ax[1].plot(xrange, ŷrange, \"--\")\n    ax[1].set_title(\"Fit\")\n    ax[2].scatter(x, ê)\n    ax[2].set_title(\"Residuals\")\n    return ax\nend\n", "meta": {"hexsha": "08ff4f02a3f0be21e4807ca3b469eaa494700677", "size": 1073, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/regression.jl", "max_stars_repo_name": "Caronthir/JSort", "max_stars_repo_head_hexsha": "0ffae10599eaa56943f494ffb2e0a613e19414f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/regression.jl", "max_issues_repo_name": "Caronthir/JSort", "max_issues_repo_head_hexsha": "0ffae10599eaa56943f494ffb2e0a613e19414f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/regression.jl", "max_forks_repo_name": "Caronthir/JSort", "max_forks_repo_head_hexsha": "0ffae10599eaa56943f494ffb2e0a613e19414f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6346153846, "max_line_length": 54, "alphanum_fraction": 0.5563839702, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7650842178374043}}
{"text": "using Polynomials\nusing Plots\ninclude(\"funkcje.jl\")\nreturn\n\nprec = 0.01\nidealne = [(cos(t), sin(t)) for t in -pi:0.001:pi]\nreturn\n\nfunction makeSpline(coordinates)\n    function CalculateCs()\n        μ = [NaN64 for k in 1:n]\n        α = vcat([0.], [3. * (A[k+1] - A[k])/h[k] - 3. * (A[k] - A[k-1])/h[k-1] for k in 2:n])\n\n        C = [0. for k in 1:nPlus1]\n        l = [0. for k in 1:nPlus1]\n        z = [0. for k in 1:nPlus1]\n\n        l[1] = 1.\n        μ[1] = 0.\n        z[1] = 0.\n\n        for k in 2:n\n            l[k] = 2 * (xs[k+1] - xs[k-1]) - h[k-1] * μ[k-1]\n            μ[k] = h[k] / l[k]\n            z[k] = (α[k] - h[k-1]*z[k-1]) / l[k]\n        end\n\n        l[nPlus1] = 1.\n        z[nPlus1] = 0.\n        C[nPlus1] = 0.\n\n        for k in n:(-1):1\n            C[k] = z[k] - μ[k]*C[k+1]\n        end\n        return C\n    end\n    nPlus1 = length(coordinates)\n    n = nPlus1 - 1\n    # x1 x2 ... xk+1\n    xs = map(pair->pair[1], coordinates)\n    # y1 y2 ... yk+1\n    # ys = map(pair->pair[2], coordinates)\n    A = map(pair->pair[2], coordinates)\n\n    h = [xs[k+1] - xs[k] for k in 1:n]\n    C = CalculateCs()\n\n    B = [(A[k+1] - A[k]) / h[k] - h[k]*(C[k+1] + 2. * C[k]) / 3. for k in 1:n]\n    D = [(C[k+1] - C[k]) / (3. * h[k]) for k in 1:n]\n\n    outputSet = [Poly(NaN) for k in 1:n]\n    intervals = myzip(xs,xs[2:end])\n\n    for k in 1:n\n        xk = xs[k]\n        polynom = A[k] + B[k]*poly([xk]) + C[k]*(poly([xk])^2) + D[k]*(poly([xk]) ^ 3)\n        outputSet[k] = polynom\n    end\n    return myzip(outputSet, intervals)\nend\n\nfunction calculateSpline(splajn)\n#     prec = 0.01\n    coors = []\n    angles = []\n\n    for i in 1:length(splajn)\n        xk = splajn[i][2][1]\n        xkPlus1 = splajn[i][2][2]\n        wielomian = splajn[i][1]\n        przedzial = [x for x in xk:prec:(xkPlus1-prec)]\n\n        coors = vcat(coors, map(wielomian, przedzial))\n        angles = vcat(angles, przedzial)\n    end\n\n    return angles, coors\nend\n\nfunction circle(n, r = 1)\n    ps = [t for t in -pi:2*pi/n:pi]\n    xs = r * cos.(ps)\n    ys = r * sin.(ps)\n\n    xspline = makeSpline(myzip(ps, xs))\n    yspline = makeSpline(myzip(ps, ys))\n\n\n    angles, xvalues = calculateSpline(xspline)\n    angles, yvalues = calculateSpline(yspline) #jak zrobi się na odwrót kolejności to wychodzą ładne rysunki błędów\n\n    xerrors = abs.(cos.(angles) - xvalues)\n    yerrors = abs.(sin.(angles) - yvalues)\n\n    errors = sqrt.([x^2 for x in xerrors] + [y^2 for y in yerrors])\n\n    return [(angles, errors), (xvalues, yvalues), (xs, ys)]\nend\n\nfunction plotCircle(c, n)\n    plot!(c[2], lab = \"n = \" * string(n), linestyle = :dash)\n#     scatter!(c[3], lab = \"Zadane punkty\")\nend\n\nfunction mainCircle(ns :: Array{Int})\n\n    Plots.plot(size = (600*1.1, 600))\n\n    title!(\"Splajn\")\n\n    xlabel!(\"Os x\")\n    ylabel!(\"Os y\")\n\n\n    plot!(idealne, lab = \"idealne kolo\", color = :black)\n    cns = [(circle(n), n) for n in ns]\n    for cn in cns\n        plotCircle(cn[1], cn[2])\n    end\n\n    savefig(\"splajn\")\nend\nfunction mainCircle(n :: Int)\n\n    Plots.plot(size = (600*1.1, 600))\n\n    title!(\"Splajn\")\n\n    xlabel!(\"Os x\")\n    ylabel!(\"Os y\")\n\n    plot!(idealne, lab = \"idealne kolo\", color = :black)\n    c = circle(n)\n    plotCircle(c, n)\n\n    savefig(\"splajn\")\nend\n\n\nfunction plotError(c, n)\n    plot!(c[1], lab = \"n = \" * string(n))\nend\nfunction mainError(ns :: Array{Int})\n    Plots.plot(size = (600*1.1, 600))\n\n    title!(\"Splajn Bledy\")\n\n    xlabel!(\"Os x\")\n    ylabel!(\"Os y\")\n\n    cns = [(circle(n), n) for n in ns]\n    for cn in cns\n        plotError(cn[1], cn[2])\n    end\n\n    savefig(\"splajnbledy\")\nend\nfunction mainError(n :: Int)\n\n    Plots.plot(size = (600*1.1, 600))\n\n    title!(\"Splajn Blad\")\n\n    xlabel!(\"Os x\")\n    ylabel!(\"Os y\")\n\n    c = circle(n)\n    plotError(c, n)\n\n    savefig(\"splajnblad\")\nend\n\nfunction helix(n, p, r = 1)\n    ps = [t for t in -pi:pi/n:pi]\n    xs = r * cos.(ps)\n    ys = r * sin.(ps)\n\n    xspline = makeSpline(myzip(ps, xs))\n    yspline = makeSpline(myzip(ps, ys))\n\n    angles, xvalues = calculateSpline(xspline)\n    angles, yvalues = calculateSpline(yspline)\n\n    pts = [p*t for t in angles]\n\n    Plots.plot(size = (600*1.1, 600), leg = false)\n    plot!(pts, xvalues, yvalues)\n    plot!(xvalues, pts, yvalues)\n    plot!(xvalues, yvalues, pts)\n    title!(\"Helisa Splajn\")\n    xlabel!(\"Os x\")\n    ylabel!(\"Os y\")\nend\n\nfunction B(t)\n    c = (4/3)*(sqrt(2) - 1)\n\n    P0 = [0,1]\n    P1 = [c,1]\n    P2 = [1,c]\n    P3 = [1,0]\n\n    return (1-t)^3*P0 + 3*(1-t)^2*t*P1 + 3*(1-t)*t^2*P2 + t^3*P3\nend\n\nfunction circle()\n    n = 1000\n    prec = 1/n\n    ts = [t for t in 0:prec:1]\n\n    xvalues, yvalues = myunzip([B(t) for t in ts])\n\n    angles = [t for t in 0:pi/(2*n+1):pi/2]\n\n    xerrors = abs.(sin.(angles) - xvalues)\n    yerrors = abs.(cos.(angles) - yvalues)\n\n    errors = sqrt.([x^2 for x in xerrors] + [y^2 for y in yerrors])\n\n    xvs = vcat(xvalues, yvalues, -xvalues, -yvalues) #cosinus\n    yvs = vcat(-yvalues, xvalues, yvalues, -xvalues) #sinus\n\n    xvalues = xvs\n    yvalues = yvs\n\n    return [(angles, errors), (xvalues, yvalues)]\nend\n\nfunction silnia(k)::BigInt\n    if k == 0\n        return 1\n    else\n        return k * silnia(k-1)\n    end\nend\n\nfunction ilorazysilni(k)::Tuple{Array{BigFloat,1}, Array{BigFloat,1}}\n    xis = [BigFloat(1.) for i in 0:k]\n    yis = [BigFloat(1.) for i in 0:k]\n    xis[1] = yis[1] = BigFloat(1.)\n    for j in 2:k\n        i = j - 1\n        xis[j] = BigFloat(xis[i] * BigFloat(k+i-1) * BigFloat(k - i) / BigFloat(i))\n        yis[j] = xis[j] * (k+i) / (k-i)\n    end\n    yis[k+1] = yis[k] * 2\n    return xis, yis\nend\n\nfunction Hk(k, α, facts, e, f)\n    suma = .0\n    for i in 0:e\n        hi = f(pi*(k+i)/2 + α) / (2*α)^(k+i+1)\n        fact = facts[i+1]\n        suma += (hi*fact)\n    end\n    return suma / silnia(k)\nend\n\nfunction Xk(k, α)\n    return Hk(k, α, ilorazysilni(k)[1], k-1, cos)\nend\nfunction Yk(k, α)\n    return Hk(k, α, ilorazysilni(k)[2], k, sin)\nend\n\nfunction Hn(t, n, α, Hks, c1, c2)\n    suma = .0\n    c = t^2 - α^2\n    for k in 1:n\n        suma += Hks[k]*c^k\n    end\n    suma *= c1\n    suma += c2\n    return suma\nend\n\nfunction Xn(t, n, α, Xks)\n    return Hn(t, n, α, Xks, 2*α, cos(α))\nend\nfunction Yn(t, n, α, Xks)\n    return Hn(t, n, α, Xks, 2*t, t*sin(α)/α)\nend\n\n\nfunction arc(n, α, r)\n    Xks = [Xk(k, α) for k in 1:n]\n    Yks = [Yk(k, α) for k in 1:n]\n\n    angles = [t for t in -α:prec:α]\n\n    xvalues = r * [Xn(t, n, α, Xks) for t in angles]\n    yvalues = r * [Yn(t, n, α, Yks) for t in angles]\n\n    xerrors = abs.(r * cos.(angles) - xvalues)\n    yerrors = abs.(r * sin.(angles) - yvalues)\n\n    angles = convert.(Float64, round.(angles; digits = 10))\n    xvalues = convert.(Float64, round.(xvalues; digits = 10))\n    yvalues = convert.(Float64, round.(yvalues; digits = 10))\n    xerrors = convert.(Float64, round.(xerrors; digits = 10))\n    yerrors = convert.(Float64, round.(yerrors; digits = 10))\n\n    errors = sqrt.([x^2 for x in xerrors] + [y^2 for y in yerrors])\n\n    return [(angles,errors), (xvalues, yvalues)]\nend\nfunction circle(n, α = pi, r = 1)\n    a = arc(n, α, r)\n    angles, errors = a[1]\n    xvalues, yvalues = a[2]\n\n    if α == pi\n        xpoints = [cos(pi), cos(-pi)]\n        ypoints = [sin(pi), sin(-pi)]\n        return [(angles, errors), (xvalues, yvalues), (xpoints, ypoints)]\n    end\n    if α == pi/2\n        xvalues = vcat(xvalues, reverse(-xvalues))\n        yvalues = vcat(yvalues, reverse(yvalues))\n\n        xpoints = [cos(pi/2), cos(-pi/2)]\n        ypoints = [sin(pi/2), sin(-pi/2)]\n        return [(angles, errors), (xvalues, yvalues), (xpoints, ypoints)]\n    end\n    if α == pi/4\n        xvs = vcat(reverse(xvalues), reverse(yvalues), -xvalues, yvalues)\n        yvs = vcat(reverse(yvalues), reverse(-xvalues), yvalues, xvalues)\n        xvalues = xvs\n        yvalues = yvs\n\n        xpoints = [cos(pi/4), cos(3*pi/4), cos(5*pi/4), cos(7*pi/4)]\n        ypoints = [sin(pi/4), sin(3*pi/4), sin(5*pi/4), sin(7*pi/4)]\n\n        return [(angles, errors), (xvalues, yvalues), (xpoints, ypoints)]\n    end\nend\n\nfunction helix(n, p, α = pi, r = 1)\n    Xks = [Xk(k, α) for k in 1:n]\n    Yks = [Yk(k, α) for k in 1:n]\n\n    angles = [t for t in -α:prec:α]\n\n    xvalues = r * [Xn(t, n, α, Xks) for t in angles]\n    yvalues = r * [Yn(t, n, α, Yks) for t in angles]\n    zvalues = [p * t for t in angles]\n\n    return [xvalues, yvalues, zvalues]\nend\n", "meta": {"hexsha": "dd4a492f60dc91504ee6d2a32fa85baf97491136", "size": 8296, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "II rok/I semestr/ANM/Pracownia 3/prog/program.jl", "max_stars_repo_name": "antonitomaszewski/Studia", "max_stars_repo_head_hexsha": "ff2fa59e25cf3f5c86b59de9994b80a502ec1e7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "II rok/I semestr/ANM/Pracownia 3/prog/program.jl", "max_issues_repo_name": "antonitomaszewski/Studia", "max_issues_repo_head_hexsha": "ff2fa59e25cf3f5c86b59de9994b80a502ec1e7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "II rok/I semestr/ANM/Pracownia 3/prog/program.jl", "max_forks_repo_name": "antonitomaszewski/Studia", "max_forks_repo_head_hexsha": "ff2fa59e25cf3f5c86b59de9994b80a502ec1e7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5681818182, "max_line_length": 115, "alphanum_fraction": 0.5348360656, "num_tokens": 3148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693716759488, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7650842080639937}}
{"text": "export  KalmanFilter,\n        kalmanfilter,\n        kalmansmoother\n\nstruct KalmanFilter\n    means::Matrix{Float}\n    covs::Array{Float,3}\n    # Storage for recycling in kalman smoother\n    means_::Matrix{Float}\n    covs_::Array{Float,3}\nend\n\nstruct KalmanSmoother\n    means::Matrix{Float}\n    covs::Array{Float,3}\nend\n\nfunction kalmanfilter(lg::LinearGaussian, observations::Matrix{Float},\n                      mu0::Vector{Float}, C0::Matrix{Float}\n                      )::KalmanFilter\n    @assert issymmetric(C0) && isposdef(C0) \"Cov mat must be sym + pos def\"\n\n    nsteps = size(observations, 2)\n\n    kf_means = zeros(lg.dimx, nsteps)\n    kf_covs  = zeros(lg.dimx, lg.dimx, nsteps)\n\n    kf_means[:,1]  = mu0\n    kf_covs[:,:,1] = C0\n\n    kf_means_ = copy(kf_means)\n    kf_covs_  = copy(kf_covs)\n\n    for k = 2:nsteps\n        # intermediate (k|k-1)\n        mu_ = lg.A * kf_means[:,k-1]\n        C_  = lg.A * kf_covs[:,:,k-1] * lg.A' + lg.Q\n        G_  = (C_ * lg.B') / (lg.R + lg.B*C_*lg.B')\n        # update (k|k)\n        kf_means[:,k]  = mu_ + G_*(observations[:,k]-lg.B*mu_)\n        kf_covs[:,:,k] = (eye(lg.dimx) - G_*lg.B)*C_\n        # storage for smoothing\n        kf_means_[:,k]  = mu_\n        kf_covs_[:,:,k] = C_\n    end\n    KalmanFilter(kf_means, kf_covs, kf_means_, kf_covs_)\nend\n\n\"\"\"\n    kalmansmoother(lg, observations, kf)\n\nTwo-filter smoother in linear gaussian case (everything is tractable).\n\"\"\"\nfunction kalmansmoother(lg::LinearGaussian, observations::Matrix{Float},\n                        kf::KalmanFilter)::KalmanSmoother\n    ks_means = similar(kf.means)\n    ks_covs  = similar(kf.covs)\n    # Nsteps\n    K = size(observations,2)\n    # Pre-computations\n    iQA, iRB = lg.Q\\lg.A, lg.R\\lg.B\n    Pbi      = lg.B'*iRB\n    Pbi_K    = copy(Pbi)\n    c        = iRB'*observations[:,K]\n    # Initialisation\n    ks_covs[:,:,K] = inv( inv(kf.covs_[:,:,K]) + Pbi_K )\n    ks_means[:,K]  = ks_covs[:,:,K]*( kf.covs_[:,:,K]\\kf.means_[:,K] + c )\n    # main loop\n    for k = (K-1):-1:1\n        # Kalman Smoother with 2 Filter Smoother update\n        G   = (eye(lg.dimx) + lg.Q*Pbi)\\lg.A\n        Pbi = Pbi_K+iQA'*(lg.A-G)\n        c   = iRB'*observations[:,k] + G'*c\n        #\n        ks_covs[:,:,k] = inv( inv(kf.covs_[:,:,k]) + Pbi )\n        ks_means[:,k]  = ks_covs[:,:,k]*( kf.covs_[:,:,k]\\kf.means_[:,k] + c )\n    end\n    KalmanSmoother(ks_means, ks_covs)\nend\n", "meta": {"hexsha": "62ff6d6e698614b4f6d1da328ed2a3adb4dd42fb", "size": 2368, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kalman.jl", "max_stars_repo_name": "shug3502/SMC.jl", "max_stars_repo_head_hexsha": "af264c90faafbdc628de20f82bdbc72e8eee0f7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-08-09T16:01:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T01:40:09.000Z", "max_issues_repo_path": "src/kalman.jl", "max_issues_repo_name": "shug3502/SMC.jl", "max_issues_repo_head_hexsha": "af264c90faafbdc628de20f82bdbc72e8eee0f7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-06-27T22:38:29.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-14T03:13:10.000Z", "max_forks_repo_path": "src/kalman.jl", "max_forks_repo_name": "shug3502/SMC.jl", "max_forks_repo_head_hexsha": "af264c90faafbdc628de20f82bdbc72e8eee0f7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-08T08:09:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-08T08:09:44.000Z", "avg_line_length": 29.6, "max_line_length": 78, "alphanum_fraction": 0.5646114865, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.949669363129097, "lm_q2_score": 0.8056321819811829, "lm_q1q2_score": 0.7650842011783747}}
{"text": "\"\"\"\n    loglik(η, x)\n\nCompute the simple (linear) birth and death process log-likelihood where\n``η = (λ, μ)^{\\\\prime}``, `λ` is the birth rate, `μ` is the death rate, and `x`\nis the observed sample.\n\nDefine `i` as the size of the population at time 0 and `j` as the population\nsize at time `t`. Let ``α = (μ e^{(λ - μ) t} - μ) / (λ e^{(λ - μ) t} - μ)`` and\n``β = (λ e^{(λ - μ) t} - λ) / (λ e^{(λ - μ) t} - μ)``. Transition probability\n`p(j | i, t, λ, μ)` is equal to (Bailey, 1964):\n``\\\\sum_{h = 0}^{\\\\min(i, j)} \\\\binom{i}{h} \\\\binom{i + j - h - 1}{i - 1}\nα^{i - h} β^{j - h} (1 - α - β)^{h}``.\n\nSuppose to observe the process at time points `t[0], t[1], ..., t[s], ..., t[S]`\nwith `t[S] <= T`, at which the population size is\n`n[0], n[1], ..., n[s], ..., n[S]`. By the Markov property, log-likelihood is\n``l(λ, μ | x) = \\\\log p(n[S] | n[S], T - t[S], λ, μ) +\n\\\\sum_{s = 1}^{S} \\\\log p(n[s] | n[s - 1], t[s] - t[s - 1], λ, μ)``.\nIf we observe `M` independent processes with same parameters `(λ, μ)`, then\n``l(λ, μ | x[1], ..., x[M]) = \\\\sum_{m = 1}^{M} l(λ, μ | x[m]).``\n\nIf the process is observed continously over time period `[0, T]`, log-likelihood\nsimplifies to (Darwin, 1956, Equation (24)):\n``l(λ, μ | x) = B \\\\log λ + D \\\\log μ - (λ + μ) X + \\\\sum_{s=0}^{S - 1} n[s]``.\n`B` and `D` are the total number of births and deaths observed in `[0, T]`\nrespectively. `X` is defined as ``n[0] (t[1] - t[0]) + n[1] (t[2] - t[1]) + ...\n+ n[S - 1] (t[S] - t[S-1]) + n[S] (T - t[S])``.\n\n# References:\n\nBailey, N. T. J. (1964). The elements of stochastic processes with applications\nto the natural sciences. Wiley, New York, NY, USA. ISBN 0-471-04165-3.\n\nDarwin, J. H. (1956). The behaviour of an estimator for a simple birth and death\nprocess. Biometrika, 43(1/2), 23-31. https://doi.org/10.2307/2333575\n\"\"\"\nfunction loglik(\n  η::Vector{F},\n  x::ObservationContinuousTime\n)::F where {\n  F <: AbstractFloat\n}\n  x.tot_births * log(η[1]) +\n  x.tot_deaths * log(η[2]) -\n  (η[1] + η[2]) * x.integrated_jump +\n  x.sum_log_n\nend\n\nfunction loglik(\n  η::Vector{F},\n  x::Vector{ObservationContinuousTime}\n)::F where {\n  F <: AbstractFloat\n}\n  mapreduce(y -> loglik(η, y), +, x)\nend\n\nfunction loglik(\n  η::Vector{F},\n  x::ObservationDiscreteTimeEven\n) where {\n  F <: AbstractFloat\n}\n  l = zeros(F, x.n)\n\n  for i = 1:x.n\n    itr = zip(x.state[1:(end - 1), i], x.state[2:end, i])\n    l[i] = mapreduce(y -> trans_prob(y..., x.u, η), +, itr)\n  end\n\n  sum(l)\nend\n\nfunction loglik(\n  η::Vector{F},\n  x::ObservationDiscreteTimeUneven\n) where {\n  F <: AbstractFloat\n}\n  itr = zip(x.state[1:(end - 1), i], x.state[2:end, i], x.waiting_time)\n  mapreduce(y -> trans_prob(y..., η), +, itr)\nend\n\nfunction loglik(\n  η::Vector{F},\n  x::Vector{ObservationDiscreteTimeUneven}\n)::F where {\n  F <: AbstractFloat\n}\n  mapreduce(y -> loglik(η, y), +, x)\nend\n", "meta": {"hexsha": "34fb8de47d650e79ebbe04aa488139ac200c1cc9", "size": 2821, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simple/log_likelihood.jl", "max_stars_repo_name": "mauricelanghinrichs/SimpleBirthDeathProcess.jl", "max_stars_repo_head_hexsha": "7756b2489099a329466a81310eb8e173717e2c0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simple/log_likelihood.jl", "max_issues_repo_name": "mauricelanghinrichs/SimpleBirthDeathProcess.jl", "max_issues_repo_head_hexsha": "7756b2489099a329466a81310eb8e173717e2c0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simple/log_likelihood.jl", "max_forks_repo_name": "mauricelanghinrichs/SimpleBirthDeathProcess.jl", "max_forks_repo_head_hexsha": "7756b2489099a329466a81310eb8e173717e2c0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-11T15:30:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T15:30:13.000Z", "avg_line_length": 30.3333333333, "max_line_length": 80, "alphanum_fraction": 0.5760368664, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741214369554, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.765082580157681}}
{"text": "module CF\n\nimport ..d\n\n#cross entropy cost function\n\nlogloss{F <: AbstractFloat}(x::F) = -log(x)\ndlogloss{F <: AbstractFloat}(x::F) = -one(F)/x\n\nd(::typeof(logloss)) = dlogloss\n\ncrossentropy{F <: AbstractFloat}(expected::Bool, result::F) = (expected) * logloss(result) + (!expected) * logloss(one(F)-result)\ncrossentropy{F <: AbstractFloat}(expected::Array{Bool}, result::Array{F}) = sum(crossentropy.(expected, result))\n\ndcrossentropy{F <: AbstractFloat}(expected::Bool, result::F) = (expected) * d(logloss)(result) - (!expected) * d(logloss)(one(F) - result)\ndcrossentropy{F <: AbstractFloat}(expected::Array{Bool}, result::Array{F}) = dcrossentropy.(expected, result)\n\nd(::typeof(crossentropy)) = dcrossentropy\n\n#mean square cost function\n\nmeansquare{F <: AbstractFloat}(result::F, expected::F) = sqr(expected - result)\ndmeansquare{F <: AbstractFloat}(result::F, expected::F) = F(2.0) * (result + expected)\n\nd(::typeof(meansquare)) = dmeansquare\nend\n", "meta": {"hexsha": "adb477a84d0da3f3444c130606b69ced428dffae", "size": 953, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/costfunctions.jl", "max_stars_repo_name": "interplanetary-robot/GenML", "max_stars_repo_head_hexsha": "f99015ab404250861334e75445b3a701293349e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/costfunctions.jl", "max_issues_repo_name": "interplanetary-robot/GenML", "max_issues_repo_head_hexsha": "f99015ab404250861334e75445b3a701293349e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/costfunctions.jl", "max_forks_repo_name": "interplanetary-robot/GenML", "max_forks_repo_head_hexsha": "f99015ab404250861334e75445b3a701293349e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2962962963, "max_line_length": 138, "alphanum_fraction": 0.7019937041, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296943, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7650825778325374}}
{"text": "using MultivariateOrthogonalPolynomials, FastTransforms, BlockBandedMatrices, Plots, LinearAlgebra, StaticArrays\npyplot()\n\n\n####\n# Solving\n#\n#   (Δ + k^2*I) * u = f\n#\n# in a unit disk |𝐱| ≤ 1, \n# using orthogonal polynomials (in x and y) in a disk\n# with the weight (1-|𝐱|^2) = (1-x^2-y^2)\n####\n\nZ = Zernike(1)\nW = Weighted(Z) # w*Z\nxy = axes(Z, 1);\nx, y = first.(xy), last.(xy);\nΔ = Z \\ (Laplacian(xy) * W)\nS = Z \\ W # identity\n\n\nk = 20\nL = Δ + k^2 * S # discretisation of Helmholtz\nf = @.(cos(x * exp(y)))\n\nu = W * (L \\ (Z \\ f))\ncontourf(u)\n\n\n# One can also fix the discretisation size\n\nN = 20\nZₙ = Z[:,Block.(1:N)]\nWₙ = W[:,Block.(1:N)]\nLₙ = L[Block.(1:N),Block.(1:N)]\n\nu = Wₙ * (Lₙ \\ (Zₙ \\ f))\ncontourf(u)\n\n\n# We can also do eigenvalues of the Laplacian\nN = 20\nΔₙ = Δ[Block.(1:N),Block.(1:N)]\nSₙ = S[Block.(1:N),Block.(1:N)]\n\nλ,Q = eigen(Symmetric(Matrix(Δₙ)), Symmetric(Matrix(Sₙ)))\n\ncontourf(Wₙ * Q[:,end-10])", "meta": {"hexsha": "a8b37461c8abc2b4f2d0a01af7eed24174372810", "size": 915, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/diskhelmholtz.jl", "max_stars_repo_name": "ApproxFun/Geometries.jl", "max_stars_repo_head_hexsha": "63dc3861b95821ee0cfd071f0cce83050278d8e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/diskhelmholtz.jl", "max_issues_repo_name": "ApproxFun/Geometries.jl", "max_issues_repo_head_hexsha": "63dc3861b95821ee0cfd071f0cce83050278d8e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/diskhelmholtz.jl", "max_forks_repo_name": "ApproxFun/Geometries.jl", "max_forks_repo_head_hexsha": "63dc3861b95821ee0cfd071f0cce83050278d8e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6734693878, "max_line_length": 112, "alphanum_fraction": 0.5901639344, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224333, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.7650825777513343}}
{"text": "using ApproxFun\n\n # Semicircle law\nx=Fun(identity,-2..2)\nw=sqrt(4-x^2)/(2π)\n\nlanczos(w,5)\n\n\n# Marchenco–Pastur law\n\nr = .5\nlmax = (1+sqrt(r))^2\nlmin = (1-sqrt(r))^2\n\nx= Fun(identity,lmin..lmax)\n\nw=sqrt((lmax-x)*(x-lmin))/(π*x)\n\nlanczos(w,5)\n\n\n# Wachter law\n\na = 5; b= 10;\nc = sqrt(a/(a+b)*(1-1/(a+b)))\nd = sqrt(1/(a+b)*(1-a/(a+b)))\n\nlmax = (c+d)^2\nlmin = (c-d)^2\n\nx = Fun(identity,lmin..lmax)\n\nw = (a+b)*sqrt((x-lmin).*(lmax-x))/(2π*x*(1-x))\n\nlanczos(w,5)\n", "meta": {"hexsha": "cf41dc498a11ce041ab83b7cfcf9f9b5083ea8e2", "size": 456, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Extras/Lanczos.jl", "max_stars_repo_name": "putianyi889/ApproxFunExamples", "max_stars_repo_head_hexsha": "b519a2b2a197607561028fea53a327493bfb344e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2018-06-01T04:19:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T10:15:11.000Z", "max_issues_repo_path": "Extras/Lanczos.jl", "max_issues_repo_name": "putianyi889/ApproxFunExamples", "max_issues_repo_head_hexsha": "b519a2b2a197607561028fea53a327493bfb344e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-03-27T09:32:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-30T08:52:42.000Z", "max_forks_repo_path": "Extras/Lanczos.jl", "max_forks_repo_name": "putianyi889/ApproxFunExamples", "max_forks_repo_head_hexsha": "b519a2b2a197607561028fea53a327493bfb344e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-07-25T00:08:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T12:38:42.000Z", "avg_line_length": 12.3243243243, "max_line_length": 47, "alphanum_fraction": 0.5526315789, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338068793907, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7650521642576793}}
{"text": "#=\nComparing two numbers written in index form like 211 and 37 is not difficult, as any calculator would confirm that 211 = 2048 < 37 = 2187.\n\nHowever, confirming that 632382518061 > 519432525806 would be much more difficult, as both numbers contain over three million digits.\n\nUsing base_exp.txt (right click and 'Save Link/Target As...'), a 22K text file containing one thousand lines with a base/exponent pair on each line, determine which line number has the greatest numerical value.\n\nNOTE: The first two lines in the file represent the numbers in the example given above.\n=#\nusing DelimitedFiles\nfunction calc()\n  combined = readdlm(dirname(@__FILE__()) * \"/../Resources/p99.txt\", ',', Int64)\n  bases = vec(combined[1:1000])\n  exponents = vec(combined[1001:2000])\n  max, line = 0,0\n  for i in 1:1000\n    result = exponents[i]*log10(bases[i])\n    if result > max\n      max, line = result, i\n    end\n  end\n  line\nend\n@time println(calc())\n", "meta": {"hexsha": "b8877109e91b5f7fcce80bf32c19d69e6996ddbb", "size": 943, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p99.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p99.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p99.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 37.72, "max_line_length": 210, "alphanum_fraction": 0.7253446448, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7650126724406642}}
{"text": "abstract type AbstractQGramDistance <: StringSemiMetric end\n\n\"\"\"\n\tQGram(q::Int)\n\nCreates a QGram distance.\n\nThe distance corresponds to\n\n``||v(s1, q) - v(s2, q)||``\n\nwhere ``v(s, q)`` denotes the vector on the space of q-grams of length q, \nthat contains the number of times a q-gram appears for the string s\n\"\"\"\nstruct QGram <: AbstractQGramDistance\n\tq::Int\nend\neval_start(::QGram) = 0\n@inline function eval_op(::QGram, c::Integer, n1::Integer, n2::Integer)\n\tc + abs(n1 - n2)\nend\neval_end(::QGram, c::Integer) = c\n\n\"\"\"\n\tCosine(q::Int)\n\nCreates a Cosine distance.\n\nThe distance corresponds to\n\n`` 1 - v(s1, q).v(s2, q)  / ||v(s1, q)|| * ||v(s2, q)||``\n\nwhere ``v(s, q)`` denotes the vector on the space of q-grams of length q, \nthat contains the  number of times a q-gram appears for the string s\n\"\"\"\nstruct Cosine <: AbstractQGramDistance\n\tq::Int\nend\neval_start(::Cosine) = (0, 0, 0)\n@inline function eval_op(::Cosine, c::NTuple{3, <:Integer}, n1::Integer, n2::Integer)\n\t(c[1] + n1^2, c[2] + n2^2, c[3] + n1 * n2)\nend\neval_end(::Cosine, c::NTuple{3, <:Integer}) = 1 - c[3] / sqrt(c[1] * c[2])\n\n\"\"\"\n\tJaccard(q::Int)\n\nCreates a Jaccard distance.\n\nThe distance corresponds to \n\n``1 - |Q(s1, q) ∩ Q(s2, q)| / |Q(s1, q) ∪ Q(s2, q))|``\n\nwhere ``Q(s, q)``  denotes the set of q-grams of length n for the string s\n\"\"\"\nstruct Jaccard <: AbstractQGramDistance\n\tq::Int\nend\neval_start(::Jaccard) = (0, 0, 0)\n@inline function eval_op(::Jaccard, c::NTuple{3, <:Integer}, n1::Integer, n2::Integer)\n\t(c[1] + (n1 > 0), c[2] + (n2 > 0), c[3] + (n1 > 0) * (n2 > 0))\nend\neval_end(::Jaccard, c::NTuple{3, <:Integer}) = 1 - c[3] / (c[1] + c[2] - c[3])\n\n\"\"\"\n\tSorensenDice(q::Int)\n\nCreates a SorensenDice distance.\n\nThe distance corresponds to  \n\n``1 - 2 * |Q(s1, q) ∩ Q(s2, q)|  / (|Q(s1, q)| + |Q(s2, q))|)``\n\nwhere ``Q(s, q)``  denotes the set of q-grams of length n for the string s\n\"\"\"\nstruct SorensenDice <: AbstractQGramDistance\n\tq::Int\nend\neval_start(::SorensenDice) = (0, 0, 0)\n@inline function eval_op(::SorensenDice, c::NTuple{3, <:Integer}, n1::Integer, n2::Integer)\n\t(c[1] + (n1 > 0), c[2] + (n2 > 0), c[3] + (n1 > 0) * (n2 > 0))\nend\neval_end(::SorensenDice, c::NTuple{3, <:Integer}) = 1 - 2 * c[3] / (c[1] + c[2])\n\n\"\"\"\n\tOverlap(q::Int)\n\nCreates a Overlap distance.\n\nThe distance corresponds to  \n\n``1 - |Q(s1, q) ∩ Q(s2, q)|  / min(|Q(s1, q)|, |Q(s2, q)|)``\n\nwhere ``Q(s, q)``  denotes the set of q-grams of length n for the string s\n\"\"\"\nstruct Overlap <: AbstractQGramDistance\n\tq::Int\nend\neval_start(::Overlap) = (0, 0, 0)\n@inline function eval_op(::Overlap, c::NTuple{3, <:Integer}, n1::Integer, n2::Integer)\n\t(c[1] + (n1 > 0), c[2] + (n2 > 0), c[3] + (n1 > 0) * (n2 > 0))\nend\neval_end(::Overlap, c::NTuple{3, <:Integer}) = 1 - c[3] / min(c[1], c[2])\n\n\"\"\"\n\tNMD(q::Int)\n\tNMD(q::Int)\n\nCreates a NMD (Normalized Multiset Distance) as introduced by Besiris and\nZigouris 2013. The goal with this distance is to behave similarly to a normalized\ncompression distance without having to do any actual compression (and thus being\nfaster to compute).\n\nThe distance corresponds to\n\n``(sum(max.(m(s1), m(s2)) - min(M(s1), M(s2))) / max(M(s1), M(s2))``\n\nwhere ``m(s)`` is the vector of q-gram counts for string ``s`` and ``M(s)`` is the\nsum of those counts.\n\nFor details see:\nhttps://www.sciencedirect.com/science/article/pii/S1047320313001417\n\"\"\"\nstruct NMD <: AbstractQGramDistance\n\tq::Int\nend\neval_start(::NMD) = (0, 0, 0)\n@inline function eval_op(::NMD, c::NTuple{3, <:Integer}, n1::Integer, n2::Integer)\n\t(c[1] + n1, c[2] + n2, c[3] + max(n1, n2))\nend\neval_end(::NMD, c::NTuple{3, <:Integer}) = (c[3] - min(c[1], c[2])) / max(c[1], c[2])\n\n\"\"\"\n\tMorisitaOverlap(q::Int)\n\nCreates a MorisitaOverlap distance, a general, statistical measure of\ndispersion which can also be used on dictionaries such as created\nfrom q-grams. See https://en.wikipedia.org/wiki/Morisita%27s_overlap_index\nThis is more fine-grained than many of the other QGramDistances since\nit is based on the counts per q-gram rather than only which q-grams are\nin the strings.\n\nThe distance corresponds to\n\n``(2 * sum(m(s1) .* m(s2)) / (sum(m(s1).^2)*M(s2)/M(s1) + sum(m(s2).^2)*M(s1)/M(s2))``\n\nwhere ``m(s)`` is the vector of q-gram counts for string ``s`` and ``M(s)`` is the\nsum of those counts.\n\"\"\"\nstruct MorisitaOverlap <: AbstractQGramDistance\n\tq::Int\nend\neval_start(::MorisitaOverlap) = (0, 0, 0, 0, 0)\n@inline function eval_op(::MorisitaOverlap, c::NTuple{5, <:Integer}, n1::Integer, n2::Integer)\n\t(c[1] + n1, c[2] + n2, c[3] + n1^2, c[4] + n2^2, c[5] + n1 * n2)\nend\neval_end(::MorisitaOverlap, c::NTuple{5, <:Integer}) = 1 - 2 * c[5] / (c[3] * c[2] / c[1] + c[4] * c[1] / c[2])\n\n#==========================================================================\nQGramIterator\n==========================================================================#\n@doc \"\"\"\nReturn an iterator corresponding to the the q-gram of an iterator. \nWhen the iterator is a String, qgrams are SubStrings.\n\n### Arguments\n* `s` iterator\n* `q::Integer`: length of q-gram\n\n## Examples\n```julia\nfor x in qgrams(\"hello\", 2)\n\tprintln(x)\nend\n```\n\"\"\" \nqgrams\n\nstruct QGramIterator{S <: Union{AbstractString, AbstractVector}}\n\ts::S   # Collection\n\tq::Int # Length of Qgram\n\tfunction QGramIterator{S}(s, q) where {S <: Union{AbstractString, AbstractVector}}\n\t\tq > 0 || throw(ArgumentError(\"The qgram length must be higher than zero\"))\n\t\tnew(s, q)\n\tend\nend\nfunction QGramIterator(s::Union{AbstractString, AbstractVector}, q::Integer)\n\tQGramIterator{typeof(s)}(s, q)\nend\nBase.length(qgram::QGramIterator) = max(length(qgram.s) - qgram.q + 1, 0)\n\n# q-grams of AbstractString\nfunction Base.iterate(qgram::QGramIterator{<: AbstractString}, \n\tstate = (1, nextind(qgram.s, 0, qgram.q)))\n\tistart, iend = state\n\tiend > ncodeunits(qgram.s) && return nothing\n\telement = SubString(qgram.s, istart, iend)\n\tnextstate = nextind(qgram.s, istart), nextind(qgram.s, iend)\n\telement, nextstate\nend\nBase.eltype(qgram::QGramIterator{SubString{S}}) where {S} = SubString{S}\nBase.eltype(qgram::QGramIterator{S}) where {S <: AbstractString} = SubString{S}\nqgrams(s::AbstractString, q::Integer) = QGramIterator(s, q)\n\n# q-grams of General Iterators\nfunction Base.iterate(qgram::QGramIterator{<: AbstractVector}, state = firstindex(qgram.s))\n\tstate + qgram.q - 1 > lastindex(qgram.s) && return nothing\n\tview(qgram.s, state:(state + qgram.q - 1)), state + 1\nend\nBase.eltype(qgram::QGramIterator{<: AbstractVector}) = typeof(first(qgram))\nqgrams(s::AbstractVector, q::Integer) = QGramIterator(s, q)\nqgrams(s, q::Integer) = QGramIterator(collect(s), q)\n\n#==========================================================================\nCompute QGramDistances on general iterators\n==========================================================================#\n# For two iterators s1 and s2, that define a length and eltype method,\n# this returns an iterator that,\n# for each element in s1 ∪ s2, returns (numbers of times it appears in s1, numbers of times it appears in s2)\nfunction _count(qgrams1, qgrams2)\n\tK = promote_type(eltype(qgrams1), eltype(qgrams2))\n\td = Dict{K, Tuple{Int, Int}}()\n\tsizehint!(d, length(qgrams1) + length(qgrams2))\n\t# I use a faster way to change a dictionary key\n\t# see setindex! in https://github.com/JuliaLang/julia/blob/master/base/dict.jl#L380\n\tfor x1 in qgrams1\n\t\tindex = Base.ht_keyindex2!(d, x1)\n\t\tif index > 0\n\t\t\td.age += 1\n\t\t\t@inbounds d.keys[index] = x1\n\t\t\t@inbounds d.vals[index] = (d.vals[index][1] + 1, 0)\n\t\telse\n\t\t\t@inbounds Base._setindex!(d, (1, 0), x1, -index)\n\t\tend\n\tend\n\tfor x2 in qgrams2\n\t\tindex = Base.ht_keyindex2!(d, x2)\n\t\tif index > 0\n\t\t\td.age += 1\n\t\t\t@inbounds d.keys[index] = x2\n\t\t\t@inbounds d.vals[index] = (d.vals[index][1], d.vals[index][2] + 1)\n\t\telse\n\t\t\t@inbounds Base._setindex!(d, (0, 1), x2, -index)\n\t\tend\n\tend\n\treturn values(d)\nend\n\nfunction (dist::AbstractQGramDistance)(s1, s2)\n\t(s1 === missing) | (s2 === missing) && return missing\n\tc = eval_start(dist)\n\tfor (n1, n2) in _count(qgrams(s1, dist.q), qgrams(s2, dist.q))\n\t\tc = eval_op(dist, c, n1, n2)\n\tend\n\teval_end(dist, c)\nend\n\n#==========================================================================\nCompute QGramDistances on QGramDicts, iterators that store a dictionary associating qgrams to the number of their occurences\n==========================================================================#\n\n\"\"\"\n\tQGramDict(s, q::Integer = 2)\n\nAn iterator with a pre-computed dictionary of its qgrams. This enables faster calculation of QGram \ndistances.\n\nNote that the qgram length must correspond with the q length used\nin the distance.\n\n## Examples\n```julia\nstr1, str2 = \"my string\", \"another string\"\nqd1 = QGramDict(str1, 2)\nqd2 = QGramDict(str2, 2)\nevaluate(Overlap(2), qd1, qd2)\n```\n\"\"\"\nstruct QGramDict{S, K}\n\ts::S\n\tq::Int\n\tcounts::Dict{K, Int}\nend\nBase.length(s::QGramDict) = length(s.s)\nBase.iterate(s::QGramDict, args...) = iterate(s.s, args...)\n\nfunction QGramDict(s, q::Integer = 2)\n\t(s isa QGramDict) && (s.q == q) && return s\n\tqgs = qgrams(s, q)\n\tcountpairs = countdict(qgs)\n\tQGramDict{typeof(s), eltype(qgs)}(s, q, countpairs)\nend\n\n# Turn a sequence of qgrams to a count dict for them, i.e. map each\n# qgram to the number of times it has been seen.\nfunction countdict(qgrams)\n\td = Dict{eltype(qgrams), Int}()\n\tfor qg in qgrams\n\t\tindex = Base.ht_keyindex2!(d, qg)\n\t\tif index > 0\n\t\t\td.age += 1\n\t\t\t@inbounds d.keys[index] = qg\n\t\t\t@inbounds d.vals[index] = d.vals[index][1] + 1\n\t\telse\n\t\t\t@inbounds Base._setindex!(d, 1, qg, -index)\n\t\tend\n\tend\n\treturn d\nend\n\nfunction (dist::AbstractQGramDistance)(qc1::QGramDict, qc2::QGramDict)\n\tdist.q == qc1.q == qc2.q || throw(ArgumentError(\"The distance and the QGramDict must have the same qgram length\"))\n\td1, d2 = qc1.counts, qc2.counts\n\tc = eval_start(dist)\n\tfor (s1, n1) in d1\n\t\tindex = Base.ht_keyindex2!(d2, s1)\n\t\tif index <= 0\n\t\t\tc = eval_op(dist, c, n1, 0)\n\t\telse\n\t\t\tc = eval_op(dist, c, n1, d2.vals[index])\n\t\tend\n\tend\n\tfor (s2, n2) in d2\n\t\tindex = Base.ht_keyindex2!(d1, s2)\n\t\tif index <= 0\n\t\t\tc = eval_op(dist, c, 0, n2)\n\t\tend\n\tend\n\teval_end(dist, c)\nend\n\n#==========================================================================\nCompute QGramDistances on QGramSortedVectors, iterators that store a sorted vector associating qgrams to the number of their occurences\nNote that QGramSortedVectors require qgrams to have a natural order\n==========================================================================#\n\n\"\"\"\n\tQGramSortedVector(s, q::Integer = 2)\n\nAn iterator with a pre-computed sorted vector of its qgrams. This enables faster calculation of QGram \ndistances.\n\nSince qgrams are sorted in lexicographic order QGram distances can be \ncalculated even faster than when using a QGramDict. However, the \nsorting means that updating the counts after creation is less \nefficient. However, for most use cases QGramSortedVector is preferred\nover a QgramDict.\n\nNote that the qgram length must correspond with the q length used\nin the distance.\n\n## Examples\n```julia\nstr1, str2 = \"my string\", \"another string\"\nqs1 = QGramSortedVector(str1, 2)\nqs2 = QGramSortedVector(str2, 2)\nevaluate(Jaccard(2), qs1, qs2)\n```\n\"\"\"\nstruct QGramSortedVector{S, K}\n\ts::S\n\tq::Int\n\tcounts::Vector{Pair{K, Int}}\nend\nBase.length(s::QGramSortedVector) = length(s.s)\nBase.iterate(s::QGramSortedVector, args...) = iterate(s.s, args...)\n\nfunction QGramSortedVector(s, q::Integer = 2)\n\t(s isa QGramSortedVector) && (s.q == q) && return s\n\tqgs = qgrams(s, q)\n\t# todo: maybe more efficient to create sorteddict directly\n\tcountpairs = collect(countdict(qgs))\n\tsort!(countpairs, by = first)\n\tQGramSortedVector{typeof(s), eltype(qgs)}(s, q, countpairs)\nend\n\nfunction (dist::AbstractQGramDistance)(qc1::QGramSortedVector, qc2::QGramSortedVector)\n\tdist.q == qc1.q == qc2.q || throw(ArgumentError(\"The distance and the QGramSortedVectors must have the same qgram length\"))\n\td1, d2 = qc1.counts, qc2.counts\n\tc = eval_start(dist)\n\ti1 = i2 = 1\n\twhile true\n\t\t# length can be zero\n\t\tif i2 > length(d2)\n\t\t\tfor i in i1:length(d1)\n\t\t\t\t@inbounds c = eval_op(dist, c, d1[i][2], 0)\n\t\t\tend\n\t\tbreak\n\t\telseif i1 > length(d1)\n\t\t\tfor i in i2:length(d2)\n\t\t\t\t@inbounds c = eval_op(dist, c, 0, d2[i][2])\n\t\t\tend\n\t\tbreak\n\t\tend\n\t\t@inbounds s1, n1 = d1[i1]\n\t\t@inbounds s2, n2 = d2[i2]\n\t\tcmpval = Base.cmp(s1, s2)\n\t\tif cmpval == -1 # s1 < s2\n\t\t\tc = eval_op(dist, c, n1, 0)\n\t\t\ti1 += 1\n\t\telseif cmpval == 1 # s1 > s2\n\t\t\tc = eval_op(dist, c, 0, n2)\n\t\t\ti2 += 1\n\t\telse # s1 == s2\n\t\t\tc = eval_op(dist, c, n1, n2)\n\t\t\ti1 += 1\n\t\t\ti2 += 1\n\t\tend\n\tend\n\teval_end(dist, c)\nend\n", "meta": {"hexsha": "01838ac7828cffe42ba09b0b4a35c3c5e11cb7ab", "size": 12448, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances/qgram.jl", "max_stars_repo_name": "ararslan/StringDistances.jl", "max_stars_repo_head_hexsha": "71b4e42ead8d133394c75c224022458bf3b83552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 108, "max_stars_repo_stars_event_min_datetime": "2015-10-23T20:55:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T05:36:14.000Z", "max_issues_repo_path": "src/distances/qgram.jl", "max_issues_repo_name": "ararslan/StringDistances.jl", "max_issues_repo_head_hexsha": "71b4e42ead8d133394c75c224022458bf3b83552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 54, "max_issues_repo_issues_event_min_datetime": "2016-04-27T21:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T19:56:47.000Z", "max_forks_repo_path": "src/distances/qgram.jl", "max_forks_repo_name": "ararslan/StringDistances.jl", "max_forks_repo_head_hexsha": "71b4e42ead8d133394c75c224022458bf3b83552", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2015-10-30T15:19:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T17:49:23.000Z", "avg_line_length": 30.213592233, "max_line_length": 135, "alphanum_fraction": 0.6376124679, "num_tokens": 4191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7650126721795987}}
{"text": "using Distributions, PlotRecipes, Statistics\r\n\r\n# Order of variables in function does not matter (since cor(y,x) = cor(x,y))\r\nfunction correlation_ttest(y,x; h0=0.0)\r\n    n = length(y)\r\n    v = n - 2\r\n    X = [ones(n) x]\r\n    b = inv(X'X)*X'y\r\n    res = y .- X*b\r\n    s2 = sum(res.^2)/v\r\n    vb = s2.*inv(transpose(X)*X)\r\n    seb = sqrt(vb[2,2])\r\n#    that = abs(b[2]/seb)\r\n    ts = (seb*std(x)/std(y)).*rand(TDist(v),1000000) .+ (b[2]*std(x)/std(y))\r\n    that = abs(mean(ts) - h0)/std(ts)\r\n    todds = (1.0 + (that^2)/v)^(0.5*(v+1))\r\n    pval = 2.0*minimum([cdf(TDist(v),that) (1.0 - cdf(TDist(v),that))])\r\n\tps = [0.005; 0.025; 0.5; 0.95; 0.975]\r\n\tq = quantile(ts,[0.005,0.025,0.5,0.95,0.975])\r\n\tqs = [ps q]\r\n\tplt = plot(ts,st=:density, label=\"posterior\", fill=(0,0.4,:blue),alpha=0.4, title=\"Posterior for Correlation Coefficient\")\r\n\tvline!([cor(y,x) h0],linecolor = [:green :black],label=[\"mean\" \"H0\"])\r\n\treturn todds, pval, qs, plt\r\nend\r\n\r\n\r\n# Example of use (vary coefficient on x to increase/reduce correlation)\r\n#n = 50\r\n#x = randn(n)\r\n#y = 1.0 .+ 1.0.*x .+ randn(50)\r\n#cor(x,y)\r\n# cor(x,y) = bhat*sd(x)/sd(y)\r\n\r\n#results = correlation_ttest(x,y, h0=0.5)\r\n#results[1]\r\n#results[2]\r\n#results[3]\r\n#results[4]\r\n# savefig(\"trash.png\")\r\n", "meta": {"hexsha": "bf21ae8992825ed98080ecbab096d1045ad13a93", "size": 1239, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "correlation_coefficient_v2.jl", "max_stars_repo_name": "tszanalytics/BayesTesting.jl", "max_stars_repo_head_hexsha": "d44f1b752be0932afa51860b2eee83681e41f59d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-10T07:29:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T22:09:46.000Z", "max_issues_repo_path": "correlation_coefficient_v2.jl", "max_issues_repo_name": "tszanalytics/BayesTesting.jl", "max_issues_repo_head_hexsha": "d44f1b752be0932afa51860b2eee83681e41f59d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2018-09-10T06:26:40.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-13T09:57:50.000Z", "max_forks_repo_path": "correlation_coefficient_v2.jl", "max_forks_repo_name": "tszanalytics/BayesTesting.jl", "max_forks_repo_head_hexsha": "d44f1b752be0932afa51860b2eee83681e41f59d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-31T02:03:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-15T08:11:03.000Z", "avg_line_length": 30.975, "max_line_length": 124, "alphanum_fraction": 0.5714285714, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7650126681256613}}
{"text": "\"\"\"\r\n    GumbelCopula{d,T}\r\n\r\nFields:\r\n  - θ::Real - parameter\r\n\r\nConstructor\r\n\r\n    GumbelCopula(d, θ)\r\n\r\nThe [Gumbel](https://en.wikipedia.org/wiki/Copula_(probability_theory)#Most_important_Archimedean_copulas) copula in dimension ``d`` is parameterized by ``\\\\theta \\\\in [1,\\\\infty)``. It is an Archimedean copula with generator : \r\n\r\n```math\r\n\\\\phi(t) = \\\\exp{-t^{\\\\frac{1}{θ}}}\r\n```\r\n\"\"\"\r\nstruct GumbelCopula{d,T} <: ArchimedeanCopula{d}\r\n    θ::T\r\nend\r\nGumbelCopula(d,θ) = θ >= 1 ? GumbelCopula{d,typeof(θ)}(θ) : @error \"Theta must be greater than 1.\"\r\nϕ(  C::GumbelCopula,       t) = exp(-t^(1/C.θ))\r\nϕ⁻¹(C::GumbelCopula,       t) = (-log(t))^C.θ\r\nτ(C::GumbelCopula) = (C.θ-1)/C.θ\r\nτ⁻¹(::Type{GumbelCopula},τ) =1/(1-τ) \r\n\r\nfunction radial_dist(C::GumbelCopula)\r\n    α = 1/C.θ\r\n    β = 1\r\n    γ = cos(π/(2C.θ))^C.θ\r\n    δ = C.θ == 1 ? 1 : 0\r\n    AlphaStable([α,β,γ,δ]...) # for the type promotion...\r\nend\r\n\r\n\r\n# S(α, β, γ , δ) denotes a stable distribution in\r\n# 1-parametrization [16, p. 8] with characteristic exponent α ∈ (0, 2], skewness β ∈ [−1, 1], scale\r\n# γ ∈ [0,∞), and location δ ∈ R", "meta": {"hexsha": "645c5001b08e668b6687c18d754df4482decce53", "size": 1100, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ArchimedeanCopulas/GumbelCopula.jl", "max_stars_repo_name": "lrnv/Copulas.jl", "max_stars_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2022-02-16T08:18:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:14:07.000Z", "max_issues_repo_path": "src/ArchimedeanCopulas/GumbelCopula.jl", "max_issues_repo_name": "lrnv/Copulas.jl", "max_issues_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-19T06:55:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T09:43:03.000Z", "max_forks_repo_path": "src/ArchimedeanCopulas/GumbelCopula.jl", "max_forks_repo_name": "lrnv/Copulas.jl", "max_forks_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7297297297, "max_line_length": 229, "alphanum_fraction": 0.59, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7650126629277066}}
{"text": "using ControlSystems, OrdinaryDiffEq, NLopt, BlackBoxOptim, ForwardDiff\np0          = [0.2,0.8,1] # Initial guess\nK(kp,ki,kd) = pid(kp=kp, ki=ki, kd=kd)\nK(p)        = K(p...)\n\n# Define process model\nζ  = 0.1\nω  = 1.; ω² = ω^2\nP  = tf(ω²,[1, 2ζ*ω, ω²])*tf(1,[1,1])\n\nΩ  = exp10.(LinRange(-1,2,150))  # Frequency vector to eval constraints\nh  = 0.1 # Sample time for time-domain evaluation\nTf = 60.  # Time horizon\nt  = 0:h:Tf-h\n\nMs = 1.4 # Maximum allowed magnitude of sensitivity function\nMt = 1.4 # Maximum allowed magnitude of complimentary sensitivity function\n\np  = copy(p0)\n\nfunction timedomain(p)\n    C     = K(p[1], p[2], p[3])\n    S     = 1/(1+P*C) # Sensitivity fun\n    PS    = ss(P*S)   # TF from load disturbance to output\n    s     = Simulator(PS, (t,x) -> [1]) # Sim. unit step load disturbance\n    ty    = eltype(p) # So that all inputs to solve have same numerical type (ForwardDiff.Dual)\n    x0    = zeros(PS.nx) .|> ty\n    tspan = (ty(0.),ty(Tf))\n    sol   = solve(s, x0, tspan, Tsit5())\n    y     = PS.C*sol(t) # y = C*x\n    C,y\nend\n\nfunction freqdomain(p)\n    C     = K(p[1], p[2], p[3])\n    S     = 1/(1+P*C) # Sensitivity fun\n    T     = tf(1.) - S# Comp. Sensitivity fun\n    Sw    = vec(bode(S,Ω)[1]) # Freq. domain constraints\n    Tw    = vec(bode(T,Ω)[1]) # Freq. domain constraints\n    Sw,Tw\nend\n\n# Evaluates and plots candidate controller\nfunction evalsol(p::Vector)\n    C,y = timedomain(p)\n    Sw,Tw = freqdomain(p)\n    plot(t,y', layout=2, show=false)\n    plot!(Ω, [Sw Tw] , lab=[\"Sw\" \"Tw\"], subplot=2, xscale=:log10, yscale=:log10, show=false)\n    plot!([Ω[1],Ω[end]], [Ms,Ms], c = :black, l=:dash, subplot=2, show=false, lab=\"Ms\")\n    plot!([Ω[1],Ω[end]], [Mt,Mt], c = :purple, l=:dash, subplot=2, lab=\"Mt\")\n    gui()\n    false\nend\nevalsol(res::BlackBoxOptim.OptimizationResults) = evalsol(best_candidate(res))\n\n\nfunction constraintfun(p)\n    Sw,Tw = freqdomain(p)\n    [maximum(Sw)-Ms; maximum(Tw)-Mt]\nend\n\n\nfunction costfun(p)\n    C,y = timedomain(p)\n    mean(abs,y) # ~ Integrated absolute error IAE\nend\n\n\nfunction runopt(p, costfun, constraintfun;\n    f_tol = 1e-5,\n    x_tol = 1e-3,\n    c_tol = 1e-8,\n    f_cfg = ForwardDiff.GradientConfig(costfun, p),\n    g_cfg = ForwardDiff.JacobianConfig(constraintfun, p),\n    lb = zeros(length(p)))\n\n    c1 = constraintfun(p)\n    np = length(p)\n    nc = length(c1)\n\n    function f(p::Vector, grad::Vector)\n        if length(grad) > 0\n            grad .= ForwardDiff.gradient(costfun,p,f_cfg)\n        end\n        costfun(p)\n    end\n\n    function c(result, p::Vector, grad)\n        if length(grad) > 0\n            grad .= ForwardDiff.jacobian(constraintfun,p,g_cfg)'\n        end\n        result .= constraintfun(p)\n    end\n\n    opt = Opt(:LD_SLSQP, np)\n    lower_bounds!(opt, lb)\n    xtol_rel!(opt, x_tol)\n    ftol_rel!(opt, f_tol)\n\n    min_objective!(opt, f)\n    inequality_constraint!(opt, c, c_tol*ones(nc))\n    minf,minx,ret = NLopt.optimize(opt, p)\nend\n\nf_cfg = ForwardDiff.GradientConfig(costfun, p)\ng_cfg = ForwardDiff.JacobianConfig(constraintfun, p)\n@time minf,minx,ret = runopt(1p0, costfun, constraintfun, x_tol=1e-6, c_tol=1e-12, f_cfg=f_cfg, g_cfg=g_cfg)\nevalsol(minx)\n\n# # Optimize costfun using derivative-free method\n# res1 = compare_optimizers(costfun; SearchRange = (0.,2.), NumDimensions = length(p0), MaxTime = 20.0)\n# res2 = bboptimize(costfun, NumDimensions = length(p0), MaxTime = 20.0)\n# evalsol(res2)\n# p = best_candidate(res2)\n", "meta": {"hexsha": "3b3f9247e3b0d2edc07b6002a452c001a842e98b", "size": 3422, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/autodiff.jl", "max_stars_repo_name": "tfoliva/ControlSystems.jl", "max_stars_repo_head_hexsha": "69f58c3bef1e0d179ffb2b2b1df17a6ddbdbb06b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-01T18:34:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T18:34:02.000Z", "max_issues_repo_path": "example/autodiff.jl", "max_issues_repo_name": "tfoliva/ControlSystems.jl", "max_issues_repo_head_hexsha": "69f58c3bef1e0d179ffb2b2b1df17a6ddbdbb06b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-16T22:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-17T07:52:59.000Z", "max_forks_repo_path": "example/autodiff.jl", "max_forks_repo_name": "olof3/ControlSystems.jl", "max_forks_repo_head_hexsha": "c680b682eee08438b55c3451000894bdf00674ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7565217391, "max_line_length": 108, "alphanum_fraction": 0.6209818819, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7650126552613075}}
{"text": "using DifferentialEquations, Plots\n\n𝞪 = 1\nu0 = 1/2\nf(t,u) = 𝞪*u\ntspan = (0.0, 1.0)\n\nprob = ODEProblem(f, u0, tspan)\n\nsol1 = solve(prob, Euler(), dt=1/2^1)\nsol2 = solve(prob, Euler(), dt=1/2^2)\nsol3 = solve(prob, Euler(), dt=1/2^4)\n\n#[t+2u for (t,u) in zip(sol1.t,sol.u)]\n\nx = 0.0:0.05:1.0\np = plot(x, sol1(x))\nplot!(p, x, sol2(x))\nplot!(p, x, sol3(x))\n\ngui()", "meta": {"hexsha": "aebb4751d752cd776ec13a1658c76dcfa93ddb23", "size": 358, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch07/DiffEq/ODE/Ex01/simpleODE.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "examples/ch07/DiffEq/ODE/Ex01/simpleODE.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "examples/ch07/DiffEq/ODE/Ex01/simpleODE.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 17.0476190476, "max_line_length": 38, "alphanum_fraction": 0.5810055866, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090322, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7650126532343389}}
{"text": "\"\"\" Julia Program to implement the Cutting a Rod problem\n  \nWe are given a rod of length 'n' and the cost of the rod of different length from\n1 to n. We need to find the maximum sell price that can be obtained by cutting the rod\nat any lengths.\n \nThis problem can be solved by using Dynamic Programming\n\"\"\"\n\n# Build a dp Table in Botom-Up manner, such that the n'th element stores\n# the maximum price obtained by a rod of length 'n'\nfunction max_sell_price(m, cost)\n    dp = zeros(Int, n + 1)\n    for i in 1:n\n        curr_max = -1\n        for j in 0:(i - 1)\n            # Maximum Price obtained by cutting a rod of length zero is zero\n            if ((i - j - 1) == 0)\n                curr_max = max(curr_max, cost[j + 1])\n            else\n                curr_max = max(curr_max, cost[j + 1] + dp[i - j - 1])\n            end\n        end\n        #  Stores the maximum cost obtainable for a rod of length i\n        dp[i] = curr_max\n    end\n    return dp[n]\nend\n\nprint(\"What is the length of the rod? \")\nn = readline()\nn = parse(Int, n)\nif (n <= 0)\n    println(\"The given rod length is Invalid!!!\")\n    exit()\nend\ncost = Int[]\nprint(\"Enter the cost of the rod for length 1 to $n :  \")\ncost = [parse(Int, num) for num in split(readline())]\nmax_price = max_sell_price(n, cost)\nprint(\"The maximized sell price of the: $max_price\")\n\n\n\"\"\"\nTime Complexity- O(n^2), where 'n' is the length of the rod\nSpace Complexity- O(n)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE 1\n\nWhat is the length of the rod? 5\nEnter the cost of the rod for length 1 to 5: 2 5 7 8 10\nThe maximized sell price of the: 12 \n\nSAMPLE 2\n\nWhat is the length of the rod? -3\nThe given rod length is Invalid!!!\n\n\"\"\"\n", "meta": {"hexsha": "e3a8cca9e178d86f0091d03061fa3f1cd5c40339", "size": 1663, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/dp/cutting_a_rod.jl", "max_stars_repo_name": "TechSpiritSS/NeoAlgo", "max_stars_repo_head_hexsha": "08f559b56081a191db6c6b1339ef37311da9e986", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 897, "max_stars_repo_stars_event_min_datetime": "2020-06-25T00:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:49:31.000Z", "max_issues_repo_path": "Julia/dp/cutting_a_rod.jl", "max_issues_repo_name": "AnshikaAgrawal5501/NeoAlgo", "max_issues_repo_head_hexsha": "d66d0915d8392c2573ba05d5528e00af52b0b996", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5707, "max_issues_repo_issues_event_min_datetime": "2020-06-24T17:53:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T05:03:15.000Z", "max_forks_repo_path": "Julia/dp/cutting_a_rod.jl", "max_forks_repo_name": "AnshikaAgrawal5501/NeoAlgo", "max_forks_repo_head_hexsha": "d66d0915d8392c2573ba05d5528e00af52b0b996", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1817, "max_forks_repo_forks_event_min_datetime": "2020-06-25T03:51:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:14:07.000Z", "avg_line_length": 26.8225806452, "max_line_length": 86, "alphanum_fraction": 0.6361996392, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7649670819417012}}
{"text": "using StatisticalRethinking, CmdStan\n#gr(size=(600,600));\n\nProjDir = rel_path(\"..\", \"scripts\", \"04\")\ncd(ProjDir)\n\nhowell1 = CSV.read(rel_path(\"..\", \"data\", \"Howell1.csv\"), delim=';')\ndf = convert(DataFrame, howell1);\n\ndf2 = filter(row -> row[:age] >= 18, df);\n\nfirst(df2, 5)\n\nstruct Post\n  mu::Float64\n  sigma::Float64\n  ll:: Float64\n  prod::Float64\n  prob::Float64\nend\n\nmu_list = repeat(range(140, 160, length=200), 200);\nsigma_list = repeat(range(4, 9, length=200), inner=200);\n\nll = zeros(40000);\nfor i in 1:40000\n    d1 = Normal(mu_list[i], sigma_list[i])\n    ll[i] = sum(log.(pdf.(d1, df2[:height])))\nend\n\nd2 = Normal(178.0, 20.0)\nd3 = Uniform(0, 50)\nprod = ll + log.(pdf.(d2, mu_list)) + log.(pdf.(d3, sigma_list))\nprob = exp.(prod .- maximum(prod))\npost = DataFrame(mu=mu_list, sigma=sigma_list, ll=ll, prod=prod, prob=prob)\nfirst(post, 10)\n\nsamples = post[sample(1:size(post, 1), Weights(post[:prob]), 10000, replace=true), :]\n\ndensity(samples[:mu])\n\ndensity(samples[:sigma])\n\n#hpd(samples[:mu])\n\n#hpd(samples[:sigma])\n\n# This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl\n\n", "meta": {"hexsha": "8b846c997d55e04c9c1d467c24156222e259d7b3", "size": 1117, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapters/04/clip-14-20.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_stars_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/04/clip-14-20.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_issues_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/04/clip-14-20.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_forks_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.34, "max_line_length": 87, "alphanum_fraction": 0.6615935542, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7649670662977005}}
{"text": "# Linear Discriminant Analysis\n\n#### Type to represent a linear discriminant functional\n\nabstract type Discriminant{T} end\n\nstruct LinearDiscriminant{T<:Real} <: Discriminant{T}\n    w::Vector{T}\n    b::T\nend\n\nlength(f::LinearDiscriminant) = length(f.w)\n\nevaluate(f::LinearDiscriminant, x::AbstractVector) = dot(f.w, x) + f.b\n\nfunction evaluate(f::LinearDiscriminant, X::AbstractMatrix)\n    R = transpose(X) * f.w\n    if f.b != 0\n        broadcast!(+, R, R, f.b)\n    end\n    return R\nend\n\npredict(f::Discriminant, x::AbstractVector) = evaluate(f, x) > 0\n\npredict(f::Discriminant, X::AbstractMatrix) = (Y = evaluate(f, X); Bool[y > 0 for y in Y])\n\n\n#### function to solve linear discriminant\n\nfunction ldacov(C::DenseMatrix{T},\n                μp::DenseVector{T},\n                μn::DenseVector{T}) where T<:Real\n\n    w = cholesky(C) \\ (μp - μn)\n    ap = w ⋅ μp\n    an = w ⋅ μn\n    c = 2 / (ap - an)\n    LinearDiscriminant(rmul!(w, c), 1 - c * ap)\nend\n\nldacov(Cp::DenseMatrix{T},\n       Cn::DenseMatrix{T},\n       μp::DenseVector{T},\n       μn::DenseVector{T}) where T<:Real = ldacov(Cp + Cn, μp, μn)\n\n#### interface functions\n\nfunction fit(::Type{LinearDiscriminant}, Xp::DenseMatrix{T}, Xn::DenseMatrix{T};\n             covestimator::CovarianceEstimator = SimpleCovariance()) where T<:Real\n    μp = vec(mean(Xp, dims=2))\n    μn = vec(mean(Xn, dims=2))\n    Zp = Xp .- μp\n    Zn = Xn .- μn\n    Cp = calcscattermat(covestimator, Zp)\n    Cn = calcscattermat(covestimator, Zn)\n    ldacov(Cp, Cn, μp, μn)\nend\n\n\n#### Multiclass LDA Stats\n\nmutable struct MulticlassLDAStats{T<:Real, M<:AbstractMatrix{T}, N<:AbstractMatrix{T}}\n    dim::Int              # sample dimensions\n    nclasses::Int         # number of classes\n    cweights::Vector{T}   # class weights\n    tweight::T            # total sample weight\n    mean::Vector{T}       # overall sample mean\n    cmeans::Matrix{T}     # class-specific means\n    Sw::M                 # within-class scatter matrix\n    Sb::N                 # between-class scatter matrix\nend\n\nmean(S::MulticlassLDAStats) = S.mean\nclassweights(S::MulticlassLDAStats) = S.cweights\nclassmeans(S::MulticlassLDAStats) = S.cmeans\n\nwithclass_scatter(S::MulticlassLDAStats) = S.Sw\nbetweenclass_scatter(S::MulticlassLDAStats) = S.Sb\n\nfunction MulticlassLDAStats(cweights::Vector{T},\n                            mean::Vector{T},\n                            cmeans::Matrix{T},\n                            Sw::AbstractMatrix{T},\n                            Sb::AbstractMatrix{T}) where T<:Real\n    d, nc = size(cmeans)\n    length(mean) == d || throw(DimensionMismatch(\"Incorrect length of mean\"))\n    length(cweights) == nc || throw(DimensionMismatch(\"Incorrect length of cweights\"))\n    tw = sum(cweights)\n    size(Sw) == (d, d) || throw(DimensionMismatch(\"Incorrect size of Sw\"))\n    size(Sb) == (d, d) || throw(DimensionMismatch(\"Incorrect size of Sb\"))\n    MulticlassLDAStats(d, nc, cweights, tw, mean, cmeans, Sw, Sb)\nend\n\nfunction multiclass_lda_stats(nc::Int, X::AbstractMatrix{T}, y::AbstractVector{Int};\n                              covestimator_within::CovarianceEstimator=SimpleCovariance(),\n                              covestimator_between::CovarianceEstimator=SimpleCovariance()) where T<:Real\n    # check sizes\n    d = size(X, 1)\n    n = size(X, 2)\n    n ≥ nc || throw(ArgumentError(\"The number of samples is less than the number of classes\"))\n    length(y) == n || throw(DimensionMismatch(\"Inconsistent array sizes.\"))\n\n    # compute class-specific weights and means\n    cmeans, cweights, Z = center(X, y, nc)\n\n    Sw = calcscattermat(covestimator_within, Z)\n\n    # compute between-class scattering\n    mean = cmeans * (cweights ./ T(n))\n    U = rmul!(cmeans .- mean, Diagonal(sqrt.(cweights)))\n    Sb = calcscattermat(covestimator_between, U)\n\n    return MulticlassLDAStats(Vector{T}(cweights), mean, cmeans, Sw, Sb)\nend\n\n\n#### Multiclass LDA\n\nmutable struct MulticlassLDA{T<:Real}\n    proj::Matrix{T}\n    pmeans::Matrix{T}\n    stats::MulticlassLDAStats{T}\nend\n\nindim(M::MulticlassLDA) = size(M.proj, 1)\noutdim(M::MulticlassLDA) = size(M.proj, 2)\n\nprojection(M::MulticlassLDA) = M.proj\n\nmean(M::MulticlassLDA) = mean(M.stats)\nclassmeans(M::MulticlassLDA) = classmeans(M.stats)\nclassweights(M::MulticlassLDA) = classweights(M.stats)\n\nwithclass_scatter(M::MulticlassLDA) = withclass_scatter(M.stats)\nbetweenclass_scatter(M::MulticlassLDA) = betweenclass_scatter(M.stats)\n\ntransform(M::MulticlassLDA, x::AbstractVecOrMat{<:Real}) = M.proj'x\n\nfunction fit(::Type{MulticlassLDA}, nc::Int, X::DenseMatrix{T}, y::AbstractVector{Int};\n             method::Symbol=:gevd,\n             outdim::Int=min(size(X,1), nc-1),\n             regcoef::T=T(1.0e-6),\n             covestimator_within::CovarianceEstimator=SimpleCovariance(),\n             covestimator_between::CovarianceEstimator=SimpleCovariance()) where T<:Real\n\n    multiclass_lda(multiclass_lda_stats(nc, X, y;\n                                        covestimator_within=covestimator_within,\n                                        covestimator_between=covestimator_between);\n                   method=method,\n                   regcoef=regcoef,\n                   outdim=outdim)\nend\n\nfunction multiclass_lda(S::MulticlassLDAStats{T};\n                        method::Symbol=:gevd,\n                        outdim::Int=min(size(X,1), S.nclasses-1),\n                        regcoef::T=T(1.0e-6)) where T<:Real\n\n    P = mclda_solve(S.Sb, S.Sw, method, outdim, regcoef)\n    MulticlassLDA(P, P'S.cmeans, S)\nend\n\nmclda_solve(Sb::AbstractMatrix{T}, Sw::AbstractMatrix{T}, method::Symbol, p::Int, regcoef::T) where T<:Real =\n    mclda_solve!(copy(Sb), copy(Sw), method, p, regcoef)\n\nfunction mclda_solve!(Sb::AbstractMatrix{T},\n                      Sw::AbstractMatrix{T},\n                      method::Symbol, p::Int, regcoef::T) where T<:Real\n\n    p <= size(Sb, 1) || throw(ArgumentError(\"p cannot exceed sample dimension.\"))\n\n    if method == :gevd\n        regularize_symmat!(Sw, regcoef)\n        E = eigen!(Symmetric(Sb), Symmetric(Sw))\n        ord = sortperm(E.values; rev=true)\n        P = E.vectors[:, ord[1:p]]\n\n    elseif method == :whiten\n        W = _lda_whitening!(Sw, regcoef)\n        wSb = transpose(W) * (Sb * W)\n        Eb = eigen!(Symmetric(wSb))\n        ord = sortperm(Eb.values; rev=true)\n        P = W * Eb.vectors[:, ord[1:p]]\n\n    else\n        throw(ArgumentError(\"Invalid method name $(method)\"))\n    end\n    return P::Matrix{T}\nend\n\nfunction _lda_whitening!(C::AbstractMatrix{T}, regcoef::T) where T<:Real\n    n = size(C,1)\n    E = eigen!(Symmetric(C))\n    v = E.values\n    a = regcoef * maximum(v)\n    for i = 1:n\n        @inbounds v[i] = 1.0 / sqrt(v[i] + a)\n    end\n    return rmul!(E.vectors,  Diagonal(v))\nend\n\n#### SubspaceLDA\n\n# When the dimensionality is much higher than the number of samples,\n# it makes more sense to perform LDA on the space spanned by the\n# within-group scatter.\n\nstruct SubspaceLDA{T<:Real}\n    projw::Matrix{T}\n    projLDA::Matrix{T}\n    λ::Vector{T}\n    cmeans::Matrix{T}\n    cweights::Vector{Int}\nend\n\nindim(M::SubspaceLDA) = size(M.projw,1)\noutdim(M::SubspaceLDA) = size(M.projLDA, 2)\n\nprojection(M::SubspaceLDA) = M.projw * M.projLDA\n\nmean(M::SubspaceLDA) = vec(sum(M.cmeans * Diagonal(M.cweights / sum(M.cweights)), dims=2))\nclassmeans(M::SubspaceLDA) = M.cmeans\nclassweights(M::SubspaceLDA) = M.cweights\n\ntransform(M::SubspaceLDA, x) = M.projLDA' * (M.projw' * x)\n\nfit(::Type{F}, X::AbstractMatrix{T}, nc::Int, label::AbstractVector{Int}) where {T<:Real, F<:SubspaceLDA} =\n    fit(F, X, label, nc)\n\nfunction fit(::Type{F}, X::AbstractMatrix{T},\n             label::AbstractVector{Int},\n             nc=maximum(label);\n             normalize::Bool=false) where {T<:Real, F<:SubspaceLDA}\n    d, n = size(X, 1), size(X, 2)\n    n ≥ nc || throw(ArgumentError(\"The number of samples is less than the number of classes\"))\n    length(label) == n || throw(DimensionMismatch(\"Inconsistent array sizes.\"))\n    # Compute centroids, class weights, and deviation from centroids\n    # Note Sb = Hb*Hb', Sw = Hw*Hw'\n    cmeans, cweights, Hw = center(X, label, nc)\n    dmeans = cmeans .- (normalize ? mean(cmeans, dims=2) : cmeans * (cweights / T(n)))\n    Hb = normalize ? dmeans : dmeans * Diagonal(convert(Vector{T}, sqrt.(cweights)))\n    if normalize\n        Hw /= T(sqrt(n))\n    end\n    # Project to the subspace spanned by the within-class scatter\n    # (essentially, PCA before LDA)\n    Uw, Σw, _ = svd(Hw, full=false)\n    keep = Σw .> sqrt(eps(T)) * maximum(Σw)\n    projw = Uw[:,keep]\n    pHb = projw' * Hb\n    pHw = projw' * Hw\n    λ, G = lda_gsvd(pHb, pHw, cweights)\n    SubspaceLDA(projw, G, λ, cmeans, cweights)\nend\n\n# Reference: Howland & Park (2006), \"Generalizing discriminant analysis\n# using the generalized singular value decomposition\", IEEE\n# Trans. Patt. Anal. & Mach. Int., 26: 995-1006.\nfunction lda_gsvd(Hb::AbstractMatrix{T}, Hw::AbstractMatrix{T}, cweights::AbstractVector{Int}) where T<:Real\n    nc = length(cweights)\n    K = vcat(Hb', Hw')\n    P, R, Q = svd(K, full=false)\n    keep = R .> sqrt(eps(T))*maximum(R)\n    R = R[keep]\n    Pk = P[1:nc, keep]\n    U, ΣA, W = svd(Pk)\n    ncnz = sum(cweights .> 0)\n    G = Q[:,keep]*(Diagonal(1 ./ R) * W[:,1:ncnz-1])\n    # Normalize\n    Gw = G' * Hw\n    nrm = Gw * Gw'\n    G = G ./ reshape(sqrt.(diag(nrm)), 1, ncnz-1)\n    # Also get the eigenvalues\n    Gw = G' * Hw\n    Gb = G' * Hb\n    λ = diag(Gb * Gb')./diag(Gw * Gw')\n    λ, G\nend\n\nfunction center(X::AbstractMatrix{T}, label::AbstractVector{Int}, nc=maximum(label)) where T<:Real\n    d, n = size(X,1), size(X,2)\n    # Calculate the class weights and means\n    cmeans = zeros(T, d, nc)\n    cweights = zeros(Int, nc)\n    for j = 1:n\n        k = label[j]\n        for i = 1:d\n            cmeans[i,k] += X[i,j]\n        end\n        cweights[k] += 1\n    end\n    for j = 1:nc\n        cw = cweights[j]\n        cw == 0 && continue\n        for i = 1:d\n            cmeans[i,j] /= cw\n        end\n    end\n    # Compute differences from the means\n    dX = Matrix{T}(undef, d, n)\n    for j = 1:n\n        k = label[j]\n        for i = 1:d\n            dX[i,j] = X[i,j] - cmeans[i,k]\n        end\n    end\n    cmeans, cweights, dX\nend\n", "meta": {"hexsha": "46601146e7066e9e13ac6a3d7911f9a3e6ee1e6d", "size": 10150, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lda.jl", "max_stars_repo_name": "yingqiuz/MultivariateStats.jl", "max_stars_repo_head_hexsha": "b84cbc94c04057297acc42168a58b599a984f87d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lda.jl", "max_issues_repo_name": "yingqiuz/MultivariateStats.jl", "max_issues_repo_head_hexsha": "b84cbc94c04057297acc42168a58b599a984f87d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lda.jl", "max_forks_repo_name": "yingqiuz/MultivariateStats.jl", "max_forks_repo_head_hexsha": "b84cbc94c04057297acc42168a58b599a984f87d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7419354839, "max_line_length": 109, "alphanum_fraction": 0.6104433498, "num_tokens": 3140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7649670606577362}}
{"text": "function Laplacian{T<:AbstractFloat}(nz::Int,nx::Int,dz::T,dx::T)\n\n# This function computes the 2D Laplacian operator/matrix that acts on a\n# vectorized 2D field. The vectorization is assumed to be done using column\n# major order.\n#\n# INPUTS:     nz        - Number of grid points in the z-direction\n#             nx        - Number of grid points in the x-direction\n#             dz        - Grid spacing in z-direction\n#             dx        - Grid spacing in x-direction\n#\n# OUTPUTS:    L         - 2D Laplace operator\n\n    Dzz = (1/dz^2)*spdiagm((ones(nz-1),-2*ones(nz),ones(nz-1)),(-1,0,1))\n    Dxx = (1/dx^2)*spdiagm((ones(nx-1),-2*ones(nx),ones(nx-1)),(-1,0,1))\n\n    Mzz = kron(speye(nx),Dzz)\n    Mxx = kron(Dxx,speye(nz))\n\n    L = Mzz + Mxx\n\n    return L\n\nend", "meta": {"hexsha": "5b85896d02bb9a2f44e0cab54d508dd39b373138", "size": 768, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Operators/Laplacian.jl", "max_stars_repo_name": "lsafron/AcousticFWI.jl", "max_stars_repo_head_hexsha": "7ba478407b76faf7eef0c784289281ec7997e0d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-13T01:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-13T01:24:30.000Z", "max_issues_repo_path": "src/Operators/Laplacian.jl", "max_issues_repo_name": "lsafron/AcousticFWI.jl", "max_issues_repo_head_hexsha": "7ba478407b76faf7eef0c784289281ec7997e0d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Operators/Laplacian.jl", "max_forks_repo_name": "lsafron/AcousticFWI.jl", "max_forks_repo_head_hexsha": "7ba478407b76faf7eef0c784289281ec7997e0d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0, "max_line_length": 75, "alphanum_fraction": 0.5924479167, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.76491639570892}}
{"text": "function crra_utility(;\n    β = 0.9,\n    σ = 2.0,\n    γ = 2.0,\n    Π = 0.5 * ones(2, 2),\n    G = [0.1, 0.2],\n    Θ = ones(Float64, 2),\n    transfers = false\n    )\n    function U(c, n)\n        if σ == 1.0\n            U = log(c)\n        else\n            U = (c.^(1.0 - σ) - 1.0) / (1.0 - σ)\n        end\n        return U - n.^(1 + γ) / (1 + γ)\n    end\n    # Derivatives of utility function\n    Uc(c,n) =  c.^(-σ)\n    Ucc(c,n) = -σ * c.^(-σ - 1.0)\n    Un(c,n) = -n.^γ\n    Unn(c,n) = -γ * n.^(γ - 1.0)\n    n_less_than_one = false\n    return Model(β, Π, G, Θ, transfers,\n                 U, Uc, Ucc, Un, Unn, n_less_than_one)\nend", "meta": {"hexsha": "bf1910ee9efaebb9869b85cc101e132f77698191", "size": 623, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "opt_tax_recur/crra_utility.jl", "max_stars_repo_name": "QuantEcon/QuantEcon.lectures.code", "max_stars_repo_head_hexsha": "d61ac7bc54529dd5c77470c17539eb2418b047c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2017-05-09T10:45:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:33:27.000Z", "max_issues_repo_path": "opt_tax_recur/crra_utility.jl", "max_issues_repo_name": "QuantEcon/QuantEcon.lectures.code", "max_issues_repo_head_hexsha": "d61ac7bc54529dd5c77470c17539eb2418b047c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2017-06-30T01:52:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-01T20:09:47.000Z", "max_forks_repo_path": "opt_tax_recur/crra_utility.jl", "max_forks_repo_name": "QuantEcon/QuantEcon.lectures.code", "max_forks_repo_head_hexsha": "d61ac7bc54529dd5c77470c17539eb2418b047c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 117, "max_forks_repo_forks_event_min_datetime": "2017-04-25T16:09:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T02:30:29.000Z", "avg_line_length": 23.9615384615, "max_line_length": 54, "alphanum_fraction": 0.4109149278, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191309994468, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7649163921839961}}
{"text": "function modalparam_test()\n\t# State space model for testing modalparam \n\t# and modalparami\n\t# \n\t# javier.cara@upm.es\n\n\tM = [35.0 0.0;0.0 17.5] # mass matrix\n\tK = [12250.0 -3500.0;-3500.0 3500.0] # stiffness matrix\n\tg = [0.02;0.02] # damping ratios\n\t\n\t# teorethical eigenvalues and eigenvectors\n\tW2,V = eig(K,M)\n\tW = sqrt(W2)\n\t\n\t# damping matrix\n\tMm = V'*M*V\n\tGm = 2*Mm*diagm(W)*diagm(g)\n\tG = inv(V')*Gm*inv(V) # damping matrix\n\t\n\t# state-space matrices\n\tMinv = [ 1/M[1,1] 0.0;0.0 1/M[2,2] ]\n\tAc = [zeros(2,2) eye(2,2);-Minv*K -Minv*G] # continuous A matrix\n\tdt = 0.02 # time step\n\tA = expm(Ac*dt) # discrete A matrix\n\tC = [-Minv*K -Minv*G] # discrete C matrix\n\tBc = [zeros(2,2);Minv]\n\tB = (A - eye(4))*inv(Ac)*Bc\n\t\n\t# eigenvectors with max. component = 1\n\tV1 = zeros(2,2)\n\tfor j in 1:2\n\t\tmaxval = V[1,j]\n\t\tif abs(V[2,j]) > abs(maxval)\n\t\t\tmaxval = V[2,j]\n\t\tend\n\t\tV1[:,j] = V[:,j]/maxval\n\tend\t\n\t# updated mass masses\n\tMm1 = V1'*M*V1\n\tmm1 = diag(Mm1)\n\t\n\tssm = Dict(\"M\"=>M,\"K\"=>K,\"G\"=>G,\"wm\"=>W,\"zm\"=>g,\"Vm\"=>V1,\"mm\"=>mm1,\n\t\t\t\t\t\t\t\"dt\"=>dt,\"A\"=>A,\"B\"=>B,\"C\"=>C)\n\t\n\treturn ssm\n\t\nend\n\n", "meta": {"hexsha": "d76ddae37f16fb809d929d5f05daf71f29972c7a", "size": 1078, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/modalparam_test.jl", "max_stars_repo_name": "javiercara/ModalSSM.jl", "max_stars_repo_head_hexsha": "eb1c5200c34f3f5662ccf11f618df209e4b91111", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/modalparam_test.jl", "max_issues_repo_name": "javiercara/ModalSSM.jl", "max_issues_repo_head_hexsha": "eb1c5200c34f3f5662ccf11f618df209e4b91111", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/modalparam_test.jl", "max_forks_repo_name": "javiercara/ModalSSM.jl", "max_forks_repo_head_hexsha": "eb1c5200c34f3f5662ccf11f618df209e4b91111", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0, "max_line_length": 68, "alphanum_fraction": 0.5779220779, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8080672227971212, "lm_q1q2_score": 0.7649137460498382}}
{"text": "#= \nExample 3:  \n  Fit the following analytical model with 3 parameters:\n  (p1  +  p2 * x  +  p3 * x^2)  *  cos(x)\n\nA `FuncWrap` component is used to wrap a common Julia function\n=#\nusing Random, DataFitting\n\n# Define the analytic model function\nf(x, p1, p2, p3) = @. (p1  +  p2 * x  +  p3 * x^2)  *  cos(x)\n\n# \"True\" parameter values:\nparams = [1, 2, 3];\n\n# \"True\" physical quantities\nx = 0:0.1:15\ny = f(x, params...);\n\n# Add some noise to simulate a measurement process\nnoise = 0.1 .* y\ny .+= noise .* randn(length(x));\n\n# Wrap empirical measures and uncertainties in a `Measure` object\ndata = Measures(y, noise)\n\n# Prepare the model with a `FuncWrap` component.  Provide the guess\n# values with the `params` vector.\nmodel = Model(Domain(x), :comp1 => DataFitting.FuncWrap(f, params...))\n\n# Fit the model to empirical data\nresult = fit!(model, data)\n\n# Print best fit parameters\nfor i in 1:length(result[:comp1].p)\n    println(\"p[$i] = \", result[:comp1].p[i].val, \" ± \", result[:comp1].p[i].unc)\nend\n\n# Plot data and best fit model\nusing Gnuplot\n@gp    x data.val data.unc \"w yerr\" :-\n@gp :- x model[1] \"w line\"\n", "meta": {"hexsha": "ff0a70e50aa9cf64a7e7da477eae1ba862c62f3f", "size": 1114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/03_funcwrap.jl", "max_stars_repo_name": "gcalderone/ModelFit.jl", "max_stars_repo_head_hexsha": "7a3b0c7eeb4e1bc1b0239074680a659bd3ee71b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2018-09-04T06:57:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-07T01:01:56.000Z", "max_issues_repo_path": "examples/03_funcwrap.jl", "max_issues_repo_name": "gcalderone/ModelFit.jl", "max_issues_repo_head_hexsha": "7a3b0c7eeb4e1bc1b0239074680a659bd3ee71b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-16T16:29:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-16T16:29:07.000Z", "max_forks_repo_path": "examples/03_funcwrap.jl", "max_forks_repo_name": "gcalderone/ModelFit.jl", "max_forks_repo_head_hexsha": "7a3b0c7eeb4e1bc1b0239074680a659bd3ee71b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-08-06T05:20:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-04T05:57:12.000Z", "avg_line_length": 25.9069767442, "max_line_length": 80, "alphanum_fraction": 0.6490125673, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7649137423976584}}
{"text": "# p32.jl - solve u_xx = exp(4x), u(-1)=0, u(1)=1 (compare p13.jl)\n\nN = 16;\n(D,x) = cheb(N);\nD2 = D^2;\nD2 = D2[2:N,2:N];                   # boundary conditions\nf = exp(4*x[2:N]);\nu = D2\\f;                           # Poisson eq. solved here\nu = [0;u;0] + (x+1)/2;\nclf();\nplot(x,u,\".\",markersize=10);\nxx = -1:.01:1;\nuu = polyval(polyfit(x,u),xx);\nplot(xx,uu); grid(true);\nexact = @. (exp(4*xx) - sinh(4)*xx - cosh(4))/16 + (xx+1)/2;\ntitle(\"max err = $(signif(norm(uu-exact,Inf),4))\",fontsize=12);\n", "meta": {"hexsha": "57b7504705d9a6f1d88824e5ddb411f25ccb3e00", "size": 496, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p32.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p32.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p32.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1764705882, "max_line_length": 65, "alphanum_fraction": 0.502016129, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966717067252, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7649137304890339}}
{"text": "################################################################################\n# 3-D model\n\n\"\"\"\n    dett(::Type{DeforModelRed3D},  C::FMat{T}) where {T}\n\nCompute the determinant of a general square matrix.\n\"\"\"\nfunction dett(::Type{DeforModelRed3D},  C::FMat{T}) where {T}\n\treturn (C[1,1] * C[2,2] * C[3,3] + \n\t\tC[1,2] * C[2,3] * C[3,1] + \n\t\tC[1,3] * C[2,1] * C[3,2] - \n\t\tC[1,3] * C[2,2] * C[3,1] - \n\t\tC[1,2] * C[2,1] * C[3,3] - \n\t\tC[1,1] * C[2,3] * C[3,2])\nend\n\n\"\"\"\n    strainvdet(::Type{DeforModelRed3D},  Cv::FVec{T}) where {T}\n\nCompute the determinant of a symmetric strain-like square matrix represented\nas a vector. Remember that the shear strain components are twice the entries\nof the matrix representation.\n\"\"\"\nfunction strainvdet(::Type{DeforModelRed3D},  Cv::FVec{T}) where {T}\n\treturn (Cv[1] * Cv[2] * Cv[3] + \n\t\tCv[4]/2 * Cv[6]/2 * Cv[5]/2 + \n\t\tCv[5]/2 * Cv[4]/2 * Cv[6]/2 -  \n\t\tCv[5]/2 * Cv[2] * Cv[5]/2 - \n\t\tCv[4]/2 * Cv[4]/2 * Cv[3] - \n\t\tCv[1] * Cv[6]/2 * Cv[6]/2)\nend\n\n\"\"\"\n    strainvtr(::Type{DeforModelRed3D},  Cv::FVec{T}) where {T}\n\nCompute the trace of a symmetric strain-like square matrix represented as a\nvector.\n\"\"\"\nfunction strainvtr(::Type{DeforModelRed3D},  Cv::FVec{T}) where {T}\n\treturn (Cv[1] + Cv[2] + Cv[3])\nend\n\n\"\"\"\n    strainttov!(::Type{DeforModelRed3D}, v::FVec{T}, t::FMat{T}) where {T}\n\nConvert a symmetric matrix of 3x3 strain components  into a 6-component vector.\n\"\"\"\nfunction strainttov!(::Type{DeforModelRed3D}, v::FVec{T}, t::FMat{T}) where {T}\n\tv[1] = t[1,1];\n\tv[2] = t[2,2];\n\tv[3] = t[3,3];\n\tv[4] = t[1,2] + t[2,1];\n\tv[5] = t[1,3] + t[3,1];\n\tv[6] = t[3,2] + t[2,3];\n\treturn v\nend\n\n\"\"\"\n    strainvtot!(::Type{DeforModelRed3D}, t::FMat{T}, v::FVec{T}) where {T}\n\nConvert a strain 3-vector to a  matrix of 2x2 strain components (symmetric tensor).\n\"\"\"\nfunction strainvtot!(::Type{DeforModelRed3D}, t::FMat{T}, v::FVec{T}) where {T}\n\tt[1,1] = v[1];\n\tt[2,2] = v[2];\n\tt[3,3] = v[3];\n\tt[1,2] = v[4]/2.;\n\tt[2,1] = v[4]/2.;\n\tt[1,3] = v[5]/2.;\n\tt[3,1] = v[5]/2.;\n\tt[3,2] = v[6]/2.;\n\tt[2,3] = v[6]/2.;\n    return t\nend\n\n\"\"\"\n    stressttov!(::Type{DeforModelRed3D}, v::FVec{T}, t::FMat{T}) where {T}\n\nConvert a symmetric matrix of 3x3 stress components to a 6-component vector.\n\"\"\"\nfunction stressttov!(::Type{DeforModelRed3D}, v::FVec{T}, t::FMat{T}) where {T}\n\tv[1] = t[1,1];\n\tv[2] = t[2,2];\n\tv[3] = t[3,3];\n\tv[4] = 1/2.0*(t[1,2] + t[2,1]);\n\tv[5] = 1/2.0*(t[1,3] + t[3,1]);\n\tv[6] = 1/2.0*(t[3,2] + t[2,3]);\n\treturn v\nend\n\n\"\"\"\n    stressvtot!(::Type{DeforModelRed3D}, t::FMat{T}, v::FVec{T}) where {T}\n\nConvert a 6-vector to a  matrix of 3x3 stress components (symmetric tensor).\n\"\"\"\nfunction stressvtot!(::Type{DeforModelRed3D}, t::FMat{T}, v::FVec{T}) where {T}\n\tt[1,1] = v[1];\n\tt[2,2] = v[2];\n\tt[3,3] = v[3];\n\tt[1,2] = v[4];\n\tt[2,1] = v[4];\n\tt[1,3] = v[5];\n\tt[3,1] = v[5];\n\tt[3,2] = v[6];\n\tt[2,3] = v[6];\n\treturn t\nend\n\n################################################################################\n# 2-D plane strain model\n\n\"\"\"\n    dett(::Type{DeforModelRed2DStrain},  C::FMat{T}) where {T}\n\nCompute the determinant of a general square matrix.\n\"\"\"\nfunction dett(::Type{DeforModelRed2DStrain},  C::FMat{T}) where {T}\n\treturn (C[1,1] * C[2,2] - C[1,2] * C[2,1])\nend\n\n\"\"\"\n    strainvdet(::Type{DeforModelRed2DStrain},  Cv::FVec{T}) where {T}\n\nCompute the determinant of a symmetric strain-like square matrix represented\nas a vector. Remember that the shear strain components are twice the entries\nof the matrix representation.\n\"\"\"\nfunction strainvdet(::Type{DeforModelRed2DStrain},  Cv::FVec{T}) where {T}\n\treturn (Cv[1] * Cv[2] - Cv[3]/2 * Cv[3]/2)\nend\n\n\"\"\"\n    strainvtr(::Type{DeforModelRed2DStrain},  Cv::FVec{T}) where {T}\n\nCompute the trace of a symmetric strain-like square matrix represented as a\nvector.\n\"\"\"\nfunction strainvtr(::Type{DeforModelRed2DStrain},  Cv::FVec{T}) where {T}\n\treturn (Cv[1] + Cv[2])\nend\n\n\"\"\"\n    strainttov!(::Type{DeforModelRed2DStrain}, v::FVec{T}, t::FMat{T}) where {T}\n\nConvert a symmetric matrix of 2x2 strain components  into a 3-component vector.\n\"\"\"\nfunction strainttov!(::Type{DeforModelRed2DStrain}, v::FVec{T}, t::FMat{T}) where {T}\n    v[1] = t[1,1];\n    v[2] = t[2,2];\n    v[3] = t[1,2] + t[2,1];\n    return v\nend\n\n\"\"\"\n    strainvtot!(::Type{DeforModelRed2DStrain}, t::FMat{T}, v::FVec{T}) where {T}\n\nConvert a strain 3-vector to a  matrix of 2x2 strain components (symmetric tensor).\n\"\"\"\nfunction strainvtot!(::Type{DeforModelRed2DStrain}, t::FMat{T}, v::FVec{T}) where {T}\n    t[1,1] = v[1];\n    t[2,2] = v[2];\n    t[1,2] = v[3]/2.;\n    t[2,1] = v[3]/2.;\n    return t\nend\n\n\"\"\"\n    stressttov!(::Type{DeforModelRed2DStrain}, v::FVec{T}, t::FMat{T}) where {T}\n\nConvert a symmetric matrix of 2x2 stress components to a 3-component vector.\n\"\"\"\nfunction stressttov!(::Type{DeforModelRed2DStrain}, v::FVec{T}, t::FMat{T}) where {T}\n\tv[1] = t[1,1];\n\tv[2] = t[2,2];\n\tv[3] = 0.5*(t[1,2] + t[2,1]);\n\treturn v\nend\n\n\"\"\"\n    stressvtot!(::Type{DeforModelRed2DStrain}, t::FMat{T}, v::FVec{T}) where {T}\n\nConvert a vector to a  matrix of 2x2 stress components (symmetric tensor).\n\nIf `v` has 4 entries, also the `t[3,3]` matrix entry is set.\n\nThe stress vector components need to be ordered as:\n    sigmax, sigmay, tauxy, sigmaz,\nwhich is the ordering used for the plane-strain model reduction.\n\"\"\"\nfunction stressvtot!(::Type{DeforModelRed2DStrain}, t::FMat{T}, v::FVec{T}) where {T}\n    t[1,1] = v[1];\n    t[2,2] = v[2];\n    t[1,2] = v[3];\n    t[2,1] = v[3];\n    (length(v) == 4)  && (t[3,3] = v[4]);\n    return t\nend\n\n\n################################################################################\n# 2-D plane stress model\n\n\"\"\"\n    stressttov!(::Type{DeforModelRed2DStress}, v::FVec{T}, t::FMat{T}) where {T}\n\nConvert a symmetric matrix of 2x2 stress components to a 3-component vector.\n\"\"\"\nfunction stressttov!(::Type{DeforModelRed2DStress}, v::FVec{T}, t::FMat{T}) where {T}\n\tv[1] = t[1,1];\n\tv[2] = t[2,2];\n\tv[3] = 0.5*(t[1,2] + t[2,1]);\n\treturn v\nend\n\n\"\"\"\n    stressvtot!(::Type{DeforModelRed2DStress}, t::FMat{T}, v::FVec{T}) where {T}\n\nConvert a 3-vector to a  matrix of 2x2 stress components (symmetric tensor).\n\"\"\"\nfunction stressvtot!(::Type{DeforModelRed2DStress}, t::FMat{T}, v::FVec{T}) where {T}\n    t[1,1] = v[1];\n    t[2,2] = v[2];\n    t[1,2] = v[3];\n    t[2,1] = v[3];\n    return t\nend\n\n################################################################################\n# 2-D axially symmetric stress model\n\n\"\"\"\n    stressvtot!(::Type{DeforModelRed2DAxisymm}, t::FMat{T}, v::FVec{T}) where {T}\n\nConvert a 4-vector to a  matrix of 3x3 stress components (tensor).\n\nConvert a 4-vector to a *symmetric* matrix of 3x3 stress components (tensor).\n\nThe stress vector components need to be ordered as:\n    sigmax, sigmay, sigmaz, tauxy.\n\"\"\"\nfunction stressvtot!(::Type{DeforModelRed2DAxisymm}, t::FMat{T}, v::FVec{T}) where {T}\n    t[1,1] = v[1];\n    t[2,2] = v[2];\n    t[1,2] = v[4];\n    t[2,1] = v[4];\n    t[3,3] = v[3];\n    return t\nend", "meta": {"hexsha": "61c632b38decb4e07212ddfee066fd6099ae8bfa", "size": 6922, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/genconv.jl", "max_stars_repo_name": "PetrKryslUCSD/FinEtoolsDeforLinear.jl", "max_stars_repo_head_hexsha": "2be05b98954d75fc7980ef3c82b0babf748fa18d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-11-02T17:38:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T15:59:05.000Z", "max_issues_repo_path": "src/genconv.jl", "max_issues_repo_name": "PetrKryslUCSD/FinEtoolsDeforLinear.jl", "max_issues_repo_head_hexsha": "2be05b98954d75fc7980ef3c82b0babf748fa18d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-04-17T17:03:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-06T00:24:42.000Z", "max_forks_repo_path": "src/genconv.jl", "max_forks_repo_name": "PetrKryslUCSD/FinEtoolsDeforLinear.jl", "max_forks_repo_head_hexsha": "2be05b98954d75fc7980ef3c82b0babf748fa18d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-09T23:43:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-09T23:43:17.000Z", "avg_line_length": 27.7991967871, "max_line_length": 86, "alphanum_fraction": 0.5775787345, "num_tokens": 2724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7649137246491844}}
{"text": "\n# Used \"Conjugate Bayesian analysis of the Gaussian distribution\" by Murphy as\n# a reference.  Note that there were some typos in that document so the code\n# here may not correspond exactly.\n\nimmutable NormalWishart <: Distribution\n    dim::Int\n    zeromean::Bool\n    mu::Vector{Float64}\n    kappa::Float64\n    Tchol::Cholesky{Float64}  # Precision matrix (well, sqrt of one)\n    nu::Float64\n\n    function NormalWishart(mu::Vector{Float64}, kappa::Real,\n                                  Tchol::Cholesky{Float64}, nu::Real)\n        # Probably should put some error checking in here\n        d = length(mu)\n        zmean::Bool = true\n        for i = 1:d\n            if mu[i] != 0.\n                zmean = false\n                break\n            end\n        end\n        new(d, zmean, mu, float64(kappa), Tchol, float64(nu))\n    end\nend\n\nfunction NormalWishart(mu::Vector{Float64}, kappa::Real,\n                       T::Matrix{Float64}, nu::Real)\n    NormalWishart(mu, kappa, cholfact(T), nu)\n    \nend\n\nfunction insupport(::Type{NormalWishart}, x::Vector{Float64}, Lam::Matrix{Float64})\n    return (all(isfinite(x)) &&\n           size(Lam, 1) == size(Lam, 2) &&\n           isApproxSymmmetric(Lam) &&\n           size(Lam, 1) == length(x) &&\n           hasCholesky(Lam))\nend\n\npdf(nw::NormalWishart, x::Vector{Float64}, Lam::Matrix{Float64}) =\n        exp(logpdf(nw, x, Lam))\n\nfunction logpdf(nw::NormalWishart, x::Vector{Float64}, Lam::Matrix{Float64})\n    if !insupport(NormalWishart, x, Lam)\n        return -Inf\n    else\n        p = length(x)\n\n        nu = nw.nu\n        kappa = nw.kappa\n        mu = nw.mu\n        Tchol = nw.Tchol\n        hnu = 0.5 * nu\n        hp = 0.5 * p\n    \n        # Normalization\n        logp::Float64 = hp*(log(kappa) - float64(log2π))\n        logp -= hnu * logdet(Tchol)\n        logp -= hnu * p * log(2.)\n        logp -= lpgamma(p, hnu)\n\n        # Wishart (MvNormal contributes 0.5 as well)\n        logp += (hnu - hp) * logdet(Lam)\n        logp -= 0.5 * trace(Tchol \\ Lam)\n        \n        # Normal\n        z = nw.zeromean ? x : x - mu\n        logp -= 0.5 * kappa * dot(z, Lam * z)\n\n        return logp\n\n    end\nend\n\nfunction rand(nw::NormalWishart)\n    Lam = rand(Wishart(nw.nu, nw.Tchol))\n    mu = rand(MvNormal(nw.mu, inv(Lam) ./ nw.kappa))\n    return (mu, Lam)\nend\n\n", "meta": {"hexsha": "7ac23f0ed49ac9239f1ff4345e76c2bbec0eced4", "size": 2295, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/conjugates/normalwishart.jl", "max_stars_repo_name": "davidanthoff/Distributions.jl", "max_stars_repo_head_hexsha": "75a04ebc12f3643392d33240a4029d458f86e7f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-08-08T03:44:46.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-08T03:44:46.000Z", "max_issues_repo_path": "src/conjugates/normalwishart.jl", "max_issues_repo_name": "davidanthoff/Distributions.jl", "max_issues_repo_head_hexsha": "75a04ebc12f3643392d33240a4029d458f86e7f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/conjugates/normalwishart.jl", "max_forks_repo_name": "davidanthoff/Distributions.jl", "max_forks_repo_head_hexsha": "75a04ebc12f3643392d33240a4029d458f86e7f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3214285714, "max_line_length": 83, "alphanum_fraction": 0.5572984749, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299591537478, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7648985253852831}}
{"text": "# # POVM simulation\n# This notebook shows how we can check how much depolarizing noise a qubit positive operator-valued measure (POVM) can take before it becomes simulable by projective measurements. The general method is described in [arXiv:1609.06139](https://arxiv.org/abs/1609.06139). The question of simulability by projective measurements boils down to an SDP problem. Eq. (8) from the paper defines the noisy POVM that we obtain subjecting a POVM $\\mathbf{M}$ to a depolarizing channel $\\Phi_t$:\n#\n# $$\n# \\left[\\Phi_t\\left(\\mathbf{M}\\right)\\right]_i := t M_i + (1-t)\\frac{\\mathrm{tr}(M_i)}{d} \\mathbb{1}.\n# $$\n#\n# If this visibility $t\\in[0,1]$ is one, the POVM $\\mathbf{M}$ is simulable.\n#\n# We will use Convex.jl to solve the SDP problem.\n\nusing Convex, SCS, LinearAlgebra\nif VERSION < v\"1.2.0-DEV.0\"\n    (I::UniformScaling)(n::Integer) = Diagonal(fill(I.λ, n))\n     LinearAlgebra.diagm(v::AbstractVector) = diagm(0 => v)\nend\n\n# For the qubit case, a four outcome qubit POVM $\\mathbf{M} \\in\\mathcal{P}(2,4)$ is simulable if and only if \n#\n# $M_{1}=N_{12}^{+}+N_{13}^{+}+N_{14}^{+},$\n#\n# $M_{2}=N_{12}^{-}+N_{23}^{+}+N_{24}^{+},$\n#\n# $M_{3}=N_{13}^{-}+N_{23}^{-}+N_{34}^{+},$\n#\n# $M_{4}=N_{14}^{-}+N_{24}^{-}+N_{34}^{-},$\n#\n# where Hermitian operators $N_{ij}^{\\pm}$ satisfy $N_{ij}^{\\pm}\\geq0$ and $N_{ij}^{+}+N_{ij}^{-}=p_{ij}\\mathbb{1}$, where $i<j$ , $i,j=1,2,3,4$ and $p_{ij}\\geq0$ as well as $\\sum_{i<j}p_{ij}=1$, that is, the $p_{ij}$ values form a probability vector. This forms an SDP feasibility problem, which we can rephrase as an optimization problem by adding depolarizing noise to the left-hand side of the above equations and maximizing the visibility $t$:\n#\n# $\\max_{t\\in[0,1]} t$\n#\n# such that\n#\n# $t\\,M_{1}+(1-t)\\,\\mathrm{tr}(M_{1})\\frac{\\mathbb{1}}{2}=N_{12}^{+}+N_{13}^{+}+N_{14}^{+},$\n#\n# $t\\,M_{2}+(1-t)\\,\\mathrm{tr}(M_{2})\\frac{\\mathbb{1}}{2}=N_{12}^{-}+N_{23}^{+}+N_{24}^{+},$\n#\n# $t\\,M_{3}+(1-t)\\,\\mathrm{tr}(M_{3})\\frac{\\mathbb{1}}{2}=N_{13}^{-}+N_{23}^{-}+N_{34}^{+},$\n#\n# $t\\,M_{4}+(1-t)\\,\\mathrm{tr}(M_{4})\\frac{\\mathbb{1}}{2}=N_{14}^{-}+N_{24}^{-}+N_{34}^{-}$.\n#\n# We organize these constraints in a function that takes a four-output qubit POVM as its argument:\n\nfunction get_visibility(K)\n    noise = real([tr(K[i])*I(2)/2 for i=1:size(K, 1)])\n    P = [[ComplexVariable(2, 2) for i=1:2] for j=1:6]\n    q = Variable(6, Positive())\n    t = Variable(1, Positive())\n    constraints = [P[i][j] in :SDP for i=1:6 for j=1:2]\n    constraints += sum(q)==1\n    constraints += t<=1\n    constraints += [P[i][1]+P[i][2] == q[i]*I(2) for i=1:6]\n    constraints += t*K[1] + (1-t)*noise[1] == P[1][1] + P[2][1] + P[3][1]\n    constraints += t*K[2] + (1-t)*noise[2] == P[1][2] + P[4][1] + P[5][1]\n    constraints += t*K[3] + (1-t)*noise[3] == P[2][2] + P[4][2] + P[6][1]\n    constraints += t*K[4] + (1-t)*noise[4] == P[3][2] + P[5][2] + P[6][2]\n    p = maximize(t, constraints)\n    solve!(p, SCS.Optimizer(verbose=0))\n    return p.optval\nend\n\n# We check this function using the tetrahedron measurement (see Appendix B in [arXiv:quant-ph/0702021](https://arxiv.org/abs/quant-ph/0702021)). This measurement is non-simulable, so we expect a value below one.\n\nfunction dp(v)\n    I(2) + v[1]*[0 1; 1 0] + v[2]*[0 -im; im 0] + v[3]*[1 0; 0 -1]\nend\nb = [ 1  1  1; \n     -1 -1  1; \n     -1  1 -1;  \n      1 -1 -1]/sqrt(3)\nM = [dp(b[i, :]) for i=1:size(b,1)]/4;\nget_visibility(M)\n\n# This value matches the one [we obtained](https://github.com/peterwittek/ipython-notebooks/blob/master/Simulating_POVMs.ipynb) using [PICOS](http://picos.zib.de/).\n", "meta": {"hexsha": "bc044d479b7cd6cb35472b1c7ad0a537567ad41b", "size": 3559, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/optimization_with_complex_variables/povm_simulation.jl", "max_stars_repo_name": "danspielman/Convex.jl", "max_stars_repo_head_hexsha": "fb7098c983553458a2e636e105f1fed97c72a7f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/examples_literate/optimization_with_complex_variables/povm_simulation.jl", "max_issues_repo_name": "danspielman/Convex.jl", "max_issues_repo_head_hexsha": "fb7098c983553458a2e636e105f1fed97c72a7f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/examples_literate/optimization_with_complex_variables/povm_simulation.jl", "max_forks_repo_name": "danspielman/Convex.jl", "max_forks_repo_head_hexsha": "fb7098c983553458a2e636e105f1fed97c72a7f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.4533333333, "max_line_length": 482, "alphanum_fraction": 0.6043832537, "num_tokens": 1438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7648985217057264}}
{"text": "\n\"\"\"\n    gpdfitnew(x)\n\nEstimate the paramaters for the Generalized Pareto Distribution (GPD). Returns empirical Bayes estimate for the parameters of the two-parameter generalized Parato distribution given the data.\n\n# Arguments\n* `x::AbstractArray`: One dimensional data array.\n\n# Returns\n* `k::Float64, sigma::Float64`: Estimated parameter values.\n\n# Notes\n* This function returns a negative of Zhang and Stephens's k, because it is more common parameterization.\n\"\"\"\nfunction gpdfitnew(x::AbstractArray)\n    if ndims(x) != 1 || length(x) <= 1\n        throw(DimensionMismatch())\n    end\n    sort!(x)\n\n    n = length(x)\n    m = 80 + trunc(Int, sqrt(n))\n    prior = 3\n    \n    bs = collect(1:m) .- 0.5  \n    bs .= (1 .- sqrt.(m ./ bs)) ./ prior ./ x[trunc(Int64, n/4 + 0.5)] .+ 1 / x[end]\n\n    ks = mean(log1p.(-bs .* x'), dims=2)[:,1]\n    L = n * (log.(bs ./ -ks) .- ks .- 1)\n    w = similar(L)\n    w .= (1 ./ sum(exp.(L .- L'), dims=1)')[:,1]\n\n    # remove negligible weights\n    dii = w .>= (10 * eps(Float64))\n    if ~all(dii)\n        w = w[dii]\n        bs = bs[dii]\n    end\n    # normalise w\n    w ./= sum(w)\n    # posterior mean for b\n    b = sum(bs .* w)\n    # Estimate for k, note that we return a negative of Zhang and\n    # Stephens's k, because it is more common parameterisation.\n    k = mean(log1p.(-b .* x))\n    # estimate for sigma\n    sigma = -k / b\n\n    return k, sigma\n\nend\n", "meta": {"hexsha": "70298a61382039de39c38419f83131a2b20d9d63", "size": 1390, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gpdfitnew.jl", "max_stars_repo_name": "devmotion/StatsModelComparisons.jl", "max_stars_repo_head_hexsha": "07896872c4140710b9ab91631a08aabb15106077", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gpdfitnew.jl", "max_issues_repo_name": "devmotion/StatsModelComparisons.jl", "max_issues_repo_head_hexsha": "07896872c4140710b9ab91631a08aabb15106077", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gpdfitnew.jl", "max_forks_repo_name": "devmotion/StatsModelComparisons.jl", "max_forks_repo_head_hexsha": "07896872c4140710b9ab91631a08aabb15106077", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2264150943, "max_line_length": 191, "alphanum_fraction": 0.5877697842, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.764898520271965}}
{"text": "abstract type ClusterModel end\n\n\"\"\"\n    TotalClusterSS( Clustered::ClusterModel )\n\nReturns a scalar of the total sum of squares for a ClusterModel object.\n\"\"\"\nfunction TotalClusterSS( Clustered::ClusterModel )\n    GrandMean = StatsBase.mean( Clustered.X , dims = 1 )\n    return sum((Clustered.X .- GrandMean).^ 2)\nend\n\n\"\"\"\n    WithinClusterSS( Clustered::ClusterModel )\n\nReturns a scalar of the within cluter sum of squares for a ClusterModel object.\n\"\"\"\nfunction WithinClusterSS( Clustered::ClusterModel )\n    Clusters = unique( Clustered.Assignments )\n    WithinSS = zeros( size(Clustered.X) )\n    for cluster in Clusters\n        ElementsInCluster = vec(Clustered.Assignments .== cluster)\n        samples = Clustered.X[ ElementsInCluster, : ]\n        clusterMean = StatsBase.mean( samples , dims = 1 )\n        WithinSS[ElementsInCluster,:] = (samples .- clusterMean) .^ 2\n    end\n    return sum( WithinSS )\nend\n\n\"\"\"\n    BetweenClusterSS( Clustered::ClusterModel )\n\nReturns a scalar of the between cluster sum of squares for a ClusterModel object.\n\"\"\"\nfunction BetweenClusterSS( Clustered::ClusterModel )\n    Clusters = unique( Clustered.Assignments )\n    GrandMean = StatsBase.mean( Clustered.X , dims = 1 )\n    BetweenSS = 0.0\n    for cluster in Clusters\n        ElementsInCluster = vec(Clustered.Assignments .== cluster)\n        samples = Clustered.X[ ElementsInCluster, : ]\n        clusterMean = StatsBase.mean( samples , dims = 1 )\n        BetweenSS += size(samples)[1] * sum( ( clusterMean .- GrandMean ) .^ 2)\n    end\n    return BetweenSS\nend\n\nstruct KMeansClustering <: ClusterModel\n    X\n    Centroids\n    Assignments\nend\n\n\"\"\"\n    KMeans( X, Clusters; tolerance = 1e-8, maxiters = 200 )\n\nReturns a ClusterModel object after finding clusterings for data in `X` via MacQueens K-Means algorithm. `Clusters` is the K parameter, or the # of clusters.\n\nMacQueen, J. B. (1967). Some Methods for classification and Analysis of Multivariate Observations. Proceedings of 5th Berkeley Symposium on Mathematical Statistics and Probability. 1. University of California Press. pp. 281–297.\n\"\"\"\nfunction KMeans( X, Clusters; tolerance = 1e-8, maxiters = 200 )\n    (Xrows, Xcols) = size( X )\n    ResultVector = zeros( Xrows )\n    #1) Initialize K-Means centroids: Randomly select C samples\n    rndsmpl = collect( StatsBase.sample( collect(1 : Xrows), Clusters, replace = false ) )\n    Centroids = X[ rndsmpl, :]\n    newCentroid = zeros( Clusters, Xcols )\n    #2) finding which many points are nearest to our centroid\n    #3) Calculate the mean value of each dimension to make a new centroid and repeat.\n    for iter in 1 : maxiters\n        DistsToCentroids = SquareEuclideanDistance( X, Centroids )\n        ResultVector = last.(Tuple.(argmin( DistsToCentroids, dims = 2 )))\n\n        for cluster in 1:Clusters\n            Assigned = (ResultVector .== cluster)[:,1]\n            newCentroid[ cluster, : ] = StatsBase.mean( X[ Assigned, : ], dims = 1 )\n        end\n        ToleranceCheck = ( 1.0 / Clusters ) * sum( ( Centroids .- newCentroid ) .^ 2)\n        if ToleranceCheck <= tolerance ; break; end\n        Centroids = newCentroid\n    end\n    return KMeansClustering( X, Centroids, ResultVector )\nend\n", "meta": {"hexsha": "88ef6bb72b9b05bff8b672d4d02795fd9d2e4100", "size": 3195, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Clustering.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/ChemometricsTools.jl-a9718f02-dbee-5ae5-ad0e-dfbd07fa387b", "max_stars_repo_head_hexsha": "4db6d13fba2ed249f62b973cf282951d1479854d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 52, "max_stars_repo_stars_event_min_datetime": "2019-03-04T10:09:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T02:59:13.000Z", "max_issues_repo_path": "src/Clustering.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/ChemometricsTools.jl-a9718f02-dbee-5ae5-ad0e-dfbd07fa387b", "max_issues_repo_head_hexsha": "4db6d13fba2ed249f62b973cf282951d1479854d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 39, "max_issues_repo_issues_event_min_datetime": "2019-03-03T16:46:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T11:54:29.000Z", "max_forks_repo_path": "src/Clustering.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/ChemometricsTools.jl-a9718f02-dbee-5ae5-ad0e-dfbd07fa387b", "max_forks_repo_head_hexsha": "4db6d13fba2ed249f62b973cf282951d1479854d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2019-04-17T00:28:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T18:16:59.000Z", "avg_line_length": 38.0357142857, "max_line_length": 228, "alphanum_fraction": 0.6866979656, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.764898520001287}}
{"text": "\"\"\"\n    angleofrefraction(n1, n2, β)\n\nCompute the angle of refraction.\n\n# Arguments\n* `n1`: refractive index of the medium in which the wave is propagating towards the interface\n* `n2`: refractive index of the other medium\n* `β`:  incident or reflected angle\n\"\"\"\nfunction angleofrefraction(n1, n2, β)\n    asin(n1 / n2 * sin(β))\nend\n\n\"\"\"\n    fresnel_x(n1, n2, β)\n\nCompute the diagonal elements \\$L_{xx}\\$ of the fresnel factor.\n\n# Arguments\n* `n1`: refractive index of the medium in which the wave is propagating towards the interface\n* `n2`: refractive index of the other medium\n* `β`:  incident or reflected angle\n\nhttps://doi.org/10.1103/PhysRevB.59.1263\n\"\"\"\nfunction fresnel_x(n1, n2, β)\n    γ = angleofrefraction(n1, n2, β)\n    2n1 * cos(γ) / (n1 * cos(γ) + n2 * cos(β))\nend\n\n\"\"\"\n    fresnel_y(n1, n2, β)\n\nCompute the diagonal elements \\$L_{yy}\\$ of the fresnel factor.\n\n# Arguments\n* `n1`: refractive index of the medium in which the wave is propagating towards the interface\n* `n2`: refractive index of the other medium\n* `β`:  incident or reflected angle\n\nhttps://doi.org/10.1103/PhysRevB.59.1263\n\"\"\"\nfunction fresnel_y(n1, n2, β)\n    γ = angleofrefraction(n1, n2, β)\n    2n1 * cos(β) / (n1 * cos(β) + n2 * cos(γ))\nend\n\n\"\"\"\n    fresnel_z(n1, n2, n′, β)\n\nCompute the diagonal elements \\$L_{yy}\\$ of the fresnel factor.\n\n# Arguments\n* `n1`: refractive index of the medium in which the wave is propagating towards the interface\n* `n2`: refractive index of the other medium\n* `n′`: refractive index of the interface\n* `β`:  incident or reflected angle\n\nhttps://doi.org/10.1103/PhysRevB.59.1263\n\"\"\"\nfunction fresnel_z(n1, n2, n′, β)\n    γ = angleofrefraction(n1, n2, β)\n    2n2 * cos(β) / (n1 * cos(γ) + n2 * cos(β)) * (n1 / n′)^2\nend\n\n\"\"\"\n    ninterface(n2)\n\nCalculate the index of refraction of the interfacial layer according to\n\n``\\\\left(\\\\frac{1}{n^\\\\prime}\\\\right)^2 = \\\\frac{4n_2^2 + 2}{n_2^2(n_2 ^2+5)}``.\n\n# Arguments\n* `n2`: refractive index of the medium in which the wave is **not** propagating towards the interface\n\nhttps://doi.org/10.1103/PhysRevB.59.1263\n\"\"\"\nfunction ninterface(n2)\n    1 / sqrt((4 * n2^2 + 2) / (n2^2 * (n2^2 + 5)))\nend\n", "meta": {"hexsha": "00ad0a5a9e32adf13fab428cf3e60ad2f5943b15", "size": 2156, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fresnel.jl", "max_stars_repo_name": "MLackner/SFGAnalysis.jl", "max_stars_repo_head_hexsha": "8d095b56fdab061df73941eece5156b2efc98796", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-26T16:03:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T16:03:59.000Z", "max_issues_repo_path": "src/fresnel.jl", "max_issues_repo_name": "MLackner/SFGAnalysis.jl", "max_issues_repo_head_hexsha": "8d095b56fdab061df73941eece5156b2efc98796", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-06-11T14:14:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T00:38:31.000Z", "max_forks_repo_path": "src/fresnel.jl", "max_forks_repo_name": "MLackner/SFGAnalysis.jl", "max_forks_repo_head_hexsha": "8d095b56fdab061df73941eece5156b2efc98796", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2926829268, "max_line_length": 101, "alphanum_fraction": 0.6697588126, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229961215457, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7648985191892524}}
{"text": "function gradexpr(ex::SymbolicVariable, wrt::SymbolicVariable)\n    return ex == wrt ? 1 : 0\nend\n\ngradexpr(ex::Number, wrt::SymbolicVariable) = 0\n\nfunction gradexpr(ex::Expr, wrt::Any)\n    if ex.head != :call\n        error(\"Unrecognized expression $ex\")\n    end\n    simplify(\n        gradexpr(\n            SymbolParameter(ex.args[1]),\n            ex.args[2:end],\n            wrt\n        )\n    )\nend\n\nfunction gradexpr{T}(x::SymbolParameter{T}, args::Any, wrt::Any)\n    error(\n        @sprintf(\n            \"Derivative of function %s not supported\",\n            string(T)\n        )\n    )\nend\n\n# The Power Rule\nfunction gradexpr(::SymbolParameter{:^}, args::Any, wrt::Any)\n    x, y = args[1], args[2]\n    xp, yp = gradexpr(x, wrt), gradexpr(y, wrt)\n    if xp == 0 && yp == 0\n        return 0\n    elseif yp == 0\n        return :($y * $xp * ($x^($y - 1)))\n    else\n        return :($x^$y * ($xp * $y / $x + $yp * log($x))) \n    end\nend\n\nfunction gradexpr(::SymbolParameter{:+}, args::Any, wrt::Any)\n    termdiffs = {:+}\n    for y in args\n        x = gradexpr(y, wrt)\n        if x != 0\n            push!(termdiffs, x)\n        end\n    end\n    n = length(termdiffs)\n    if n == 1\n        return 0\n    elseif n == 2\n        return termdiffs[2]\n    else\n        return Expr(:call, termdiffs...)\n    end\nend\n\nfunction gradexpr(::SymbolParameter{:-}, args::Any, wrt::Any)\n    termdiffs = {:-}\n    # first term is special, can't be dropped\n    term1 = gradexpr(args[1], wrt)\n    push!(termdiffs, term1)\n    for y in args[2:end]\n        x = gradexpr(y, wrt)\n        if x != 0\n            push!(termdiffs, x)\n        end\n    end\n    n = length(termdiffs)\n    if term1 != 0 && n == 2 && length(args) >= 2\n        # if all of the terms but the first disappeared, we return the first\n        return term1\n    elseif term1 == 0 && n == 2\n        return 0\n    else\n        return Expr(:call, termdiffs...)\n    end\nend\n\n# The Product Rule\n# d/dx (f * g) = (d/dx f) * g + f * (d/dx g)\n# d/dx (f * g * h) = (d/dx f) * g * h + f * (d/dx g) * h + ...\nfunction gradexpr(::SymbolParameter{:*}, args::Any, wrt::Any)\n    n = length(args)\n    resargs = Array(Any, n)\n    for i in 1:n\n       newargs = Array(Any, n)\n       for j in 1:n\n           if j == i\n               newargs[j] = gradexpr(args[j], wrt)\n           else\n               newargs[j] = args[j]\n           end\n       end\n       resargs[i] = Expr(:call, :*, newargs...)\n    end\n    return Expr(:call, :+, resargs...)\nend\n\n# The Quotient Rule\n# d/dx (f / g) = ((d/dx f) * g - f * (d/dx g)) / g^2\nfunction gradexpr(::SymbolParameter{:/}, args::Any, wrt::Any)\n    x, y = args[1], args[2]\n    xp, yp = gradexpr(x, wrt), gradexpr(y, wrt)\n    if xp == 0 && yp == 0\n        return 0\n    elseif xp == 0\n        return :(-$yp * $x / $y^2)\n    elseif yp == 0\n        return :($xp / $y)\n    else\n        return :(($xp * $y - $x * $yp) / $y^2)\n    end\nend\n\n# This table is used in other packages, and if someone changes it they should\n# notify the following packages:\n# * https://github.com/scidom/DualNumbers.jl\nderivative_rules = [\n    ( :sqrt,        :(  xp / 2 / sqrt(x)                         ))\n    ( :cbrt,        :(  xp / 3 / cbrt(x)^2                       ))\n    ( :square,      :(  xp * 2 * x                               ))\n    ( :log,         :(  xp / x                                   ))\n    ( :log10,       :(  xp / x / log(10)                         ))\n    ( :log2,        :(  xp / x / log(2)                          ))\n    ( :log1p,       :(  xp / (x + 1)                             ))\n    ( :exp,         :(  xp * exp(x)                              ))\n    ( :exp2,        :(  xp * log(2) * exp2(x)                    ))\n    ( :expm1,       :(  xp * exp(x)                              ))\n    ( :sin,         :(  xp * cos(x)                              ))\n    ( :cos,         :( -xp * sin(x)                              ))\n    ( :tan,         :(  xp * (1 + tan(x)^2)                      ))\n    ( :sec,         :(  xp * sec(x) * tan(x)                     ))\n    ( :csc,         :( -xp * csc(x) * cot(x)                     ))\n    ( :cot,         :( -xp * (1 + cot(x)^2)                      ))\n    ( :sind,        :(  xp * pi / 180 * cosd(x)                  ))\n    ( :cosd,        :( -xp * pi / 180 * sind(x)                  ))\n    ( :tand,        :(  xp * pi / 180 * (1 + tand(x)^2)          ))\n    ( :secd,        :(  xp * pi / 180 * secd(x) * tand(x)        ))\n    ( :cscd,        :( -xp * pi / 180 * cscd(x) * cotd(x)        ))\n    ( :cotd,        :( -xp * pi / 180 * (1 + cotd(x)^2)          ))\n    ( :asin,        :(  xp / sqrt(1 - x^2)                       ))\n    ( :acos,        :( -xp / sqrt(1 - x^2)                       ))\n    ( :atan,        :(  xp / (1 + x^2)                           ))\n    ( :asec,        :(  xp / abs(x) / sqrt(x^2 - 1)              ))\n    ( :acsc,        :( -xp / abs(x) / sqrt(x^2 - 1)              ))\n    ( :acot,        :( -xp / (1 + x^2)                           ))\n    ( :asind,       :(  xp * 180 / pi / sqrt(1 - x^2)            ))\n    ( :acosd,       :( -xp * 180 / pi / sqrt(1 - x^2)            ))\n    ( :atand,       :(  xp * 180 / pi / (1 + x^2)                ))\n    ( :asecd,       :(  xp * 180 / pi / abs(x) / sqrt(x^2 - 1)   ))\n    ( :acscd,       :( -xp * 180 / pi / abs(x) / sqrt(x^2 - 1)   ))\n    ( :acotd,       :( -xp * 180 / pi / (1 + x^2)                ))\n    ( :sinh,        :(  xp * cosh(x)                             ))\n    ( :cosh,        :(  xp * sinh(x)                             ))\n    ( :tanh,        :(  xp * sech(x)^2                           ))\n    ( :sech,        :( -xp * tanh(x) * sech(x)                   ))\n    ( :csch,        :( -xp * coth(x) * csch(x)                   ))\n    ( :coth,        :( -xp * csch(x)^2                           ))\n    ( :asinh,       :(  xp / sqrt(x^2 + 1)                       ))\n    ( :acosh,       :(  xp / sqrt(x^2 - 1)                       ))\n    ( :atanh,       :(  xp / (1 - x^2)                           ))\n    ( :asech,       :( -xp / x / sqrt(1 - x^2)                   ))\n    ( :acsch,       :( -xp / abs(x) / sqrt(1 + x^2)              ))\n    ( :acoth,       :(  xp / (1 - x^2)                           ))\n    ( :erf,         :(  xp * 2 * exp(-square(x)) / sqrt(pi)      ))\n    ( :erfc,        :( -xp * 2 * exp(-square(x)) / sqrt(pi)      ))\n    ( :erfi,        :(  xp * 2 * exp(square(x)) / sqrt(pi)       ))\n    ( :gamma,       :(  xp * digamma(x) * gamma(x)               ))\n    ( :lgamma,      :(  xp * digamma(x)                          ))\n    # note: only covers the 1-arg version of :airy\n    ( :airy,        :(  xp * airyprime(x)                        ))\n    ( :airyprime,   :(  xp * airy(2, x)                          ))\n    ( :airyai,      :(  xp * airyaiprime(x)                      ))\n    ( :airybi,      :(  xp * airybiprime(x)                      ))\n    ( :airyaiprime, :(  xp * x * airyai(x)                       ))\n    ( :airybiprime, :(  xp * x * airybi(x)                       ))\n    ( :besselj0,    :( -xp * besselj1(x)                         ))\n    ( :besselj1,    :(  xp * (besselj0(x) - besselj(2, x)) / 2   ))\n    ( :bessely0,    :( -xp * bessely1(x)                         ))\n    ( :bessely1,    :(  xp * (bessely0(x) - bessely(2, x)) / 2   ))\n    ## ( :erfcx,   :(  xp * (2 * x * erfcx(x) - 2 / sqrt(pi))   ))  # uncertain\n    ## ( :dawson,  :(  xp * (1 - 2x * dawson(x))                ))  # uncertain\n]\n\nfor (funsym, exp) in derivative_rules \n    @eval function gradexpr(\n        ::SymbolParameter{$(Meta.quot(funsym))},\n        args::Any,\n        wrt::Any\n    )\n        x = args[1]\n        xp = gradexpr(x, wrt)\n        if xp != 0\n            return @sexpr($exp)\n        else\n            return 0\n        end\n    end\nend\n\nderivative_rules_bessel = [\n    ( :besselj,    :(  xp * (besselj(nu - 1, x) - besselj(nu + 1, x)) / 2   ))\n    ( :besseli,    :(  xp * (besseli(nu - 1, x) + besseli(nu + 1, x)) / 2   ))\n    ( :bessely,    :(  xp * (bessely(nu - 1, x) - bessely(nu + 1, x)) / 2   ))\n    ( :besselk,    :( -xp * (besselk(nu - 1, x) + besselk(nu + 1, x)) / 2   ))\n    ( :hankelh1,   :(  xp * (hankelh1(nu - 1, x) - hankelh1(nu + 1, x)) / 2 ))\n    ( :hankelh2,   :(  xp * (hankelh2(nu - 1, x) - hankelh2(nu + 1, x)) / 2 ))\n]\n\n# 2-argument bessel functions\nfor (funsym, exp) in derivative_rules_bessel \n    @eval function gradexpr(\n        ::SymbolParameter{$(Meta.quot(funsym))},\n        args::Any,\n        wrt::Any\n    )\n        nu, x = args[1], args[2]\n        xp = gradexpr(x, wrt)\n        if xp != 0\n            return @sexpr($exp)\n        else\n            return 0\n        end\n    end\nend\n\n### Other functions from julia/base/math.jl we might want to define\n### derivatives for. Some have two arguments.\n\n## atan2\n## hypot \n## beta, lbeta, eta, zeta, digamma\n\nfunction gradexpr(ex::Expr, targets::Vector{Symbol})\n    n = length(targets)\n    exprs = Array(Any, n)\n    for i in 1:n\n        exprs[i] = gradexpr(ex, targets[i])\n    end\n    return exprs\nend\n", "meta": {"hexsha": "610b760be426c4aa6bfaefabbedc5217be4dfde4", "size": 8973, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/symbolic/gradexpr.jl", "max_stars_repo_name": "johnmyleswhite/Calculus2.jl", "max_stars_repo_head_hexsha": "57f56fed859ceb6c87455249f22a0a2eb85029a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-08-25T19:12:38.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-25T19:12:38.000Z", "max_issues_repo_path": "src/symbolic/gradexpr.jl", "max_issues_repo_name": "johnmyleswhite/Calculus2.jl", "max_issues_repo_head_hexsha": "57f56fed859ceb6c87455249f22a0a2eb85029a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/symbolic/gradexpr.jl", "max_forks_repo_name": "johnmyleswhite/Calculus2.jl", "max_forks_repo_head_hexsha": "57f56fed859ceb6c87455249f22a0a2eb85029a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-01T12:21:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:21:27.000Z", "avg_line_length": 36.6244897959, "max_line_length": 79, "alphanum_fraction": 0.3820349939, "num_tokens": 2987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7648985129128512}}
{"text": "using Distributions, Plots, LaTeXStrings; pyplot()\n\nalphas = [0.5, 1.5, 1]\nlam = 2\n\nlambda(dist::Weibull) = shape(dist)*scale(dist)^(-shape(dist))\ntheta(lam,alpha) = (alpha/lam)^(1/alpha)\n\ndists = [Weibull.(a,theta(lam,a)) for a in alphas]\n\nhA(dist,x) = pdf(dist,x)/ccdf(dist,x)\nhB(dist,x) = lambda(dist)*x^(shape(dist)-1)\n\nxGrid = 0.01:0.01:10\nhazardsA = [hA.(d,xGrid) for d in dists]\nhazardsB = [hB.(d,xGrid) for d in dists]\n\nprintln(\"Maximum difference between two implementations of hazard: \", \n    maximum(maximum.(hazardsA-hazardsB)))\n\nCl = [:blue :red :green]\nLb = [L\"\\lambda=\" * string(lambda(d)) * \",   \" * L\"\\alpha =\" * string(shape(d)) \n        for d in dists]\n\nplot(xGrid, hazardsA, c=Cl, label=reshape(Lb, 1,:), xlabel=\"x\",\n\tylabel=\"Instantaneous failure rate\", xlims=(0,10), ylims=(0,10))", "meta": {"hexsha": "108863a080ca2019337d211e435a2ca3d64fbadf", "size": 802, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/weibullHazard.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "3_chapter/weibullHazard.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "3_chapter/weibullHazard.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 30.8461538462, "max_line_length": 80, "alphanum_fraction": 0.6483790524, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7648985126421731}}
{"text": "using SchumakerSpline\ntol = 10*eps()\n\nx = [1,2,3,4,5,6,7,8,9,10,11,12]\ny = log.(x) + sqrt.(x)\n\ntypeof(x) == Vector{Int}\n\nspline = Schumaker(x,y)\nfor i in 1:length(x)\n    abs(evaluate(spline, x[i]) - y[2]) < tol\nend\n# Evaluation with a Float64.\nevaluate(spline, 11.5)\n\n# Testing second derivatives\nxArray = range(1, stop=6, length=1000)\nsecond_derivatives = evaluate.(spline, xArray,2)\nmaximum(second_derivatives) < tol\n\n# Testing Integrals\nanalytic_integral(lhs,rhs) = rhs*log(rhs) - rhs + (2/3) * rhs^(3/2) - ( lhs*log(lhs) - lhs + (2/3) * lhs^(3/2) )\nlhs = 2.0\nrhs = 2.5\nnumerical_integral = evaluate_integral(spline, lhs,rhs)\nabs(analytic_integral(lhs,rhs) - numerical_integral) < 0.01\n\nlhs = 2.1\nrhs = 2.11\nnumerical_integral = evaluate_integral(spline, lhs,rhs)\nabs(analytic_integral(lhs,rhs) - numerical_integral) < 0.01\n\n\nlhs = 1\nrhs = 4\nnumerical_integral = evaluate_integral(spline, lhs,rhs)\nabs(analytic_integral(lhs,rhs) - numerical_integral) < 0.1\n", "meta": {"hexsha": "4fccad81ba71ca4eb3a688fccaf2445539d535ab", "size": 960, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Test_with_Ints.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SchumakerSpline.jl-65e68595-3a03-5ff5-a6a2-f05fa774f32e", "max_stars_repo_head_hexsha": "d9ec5723ab4896e96c83ad4cf47e16b7c82731c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-04-12T00:50:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T18:31:02.000Z", "max_issues_repo_path": "test/Test_with_Ints.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SchumakerSpline.jl-65e68595-3a03-5ff5-a6a2-f05fa774f32e", "max_issues_repo_head_hexsha": "d9ec5723ab4896e96c83ad4cf47e16b7c82731c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-10-14T12:39:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T23:53:29.000Z", "max_forks_repo_path": "test/Test_with_Ints.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SchumakerSpline.jl-65e68595-3a03-5ff5-a6a2-f05fa774f32e", "max_forks_repo_head_hexsha": "d9ec5723ab4896e96c83ad4cf47e16b7c82731c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-08-10T06:39:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:21:27.000Z", "avg_line_length": 25.2631578947, "max_line_length": 112, "alphanum_fraction": 0.7, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069105, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7648985106670555}}
{"text": "# Minimally adapted from https://github.com/scipy/scipy/blob/b5d8bab88af61d61de09641243848df63380a67f/scipy/special/_spherical_bessel.pxd#L74\nfunction sphericalbesselj(n::Integer, x::T) where {T<:AbstractFloat}\n    isnan(x) && return x\n    n < 0 && throw(DomainError(n, \"n must be non-negative\"))\n    isinf(x) && return zero(T)\n    iszero(x) && return iszero(n) ? one(T) : zero(T)\n\n    if n > 0 && n ≥ x\n        # We don't use SpecialFunctions.sphericalbesselj directly because it errors out on large x\n        return T(SpecialFunctions.sphericalbesselj(n, x))\n    else\n        return _sphericalbesselj(n, x)\n    end\nend\n\nfunction _sphericalbesselj(n::Integer, x::T) where {T<:AbstractFloat}\n    invx = inv(x)\n    s0 = sin(x) * invx\n    iszero(n) && return s0\n\n    s1 = (s0 - cos(x)) * invx\n    isone(n) && return s1\n\n    sn = zero(T)\n    for idx in 2:n\n        sn = (2idx - 1) * invx * s1 - s0\n        s0 = s1\n        s1 = sn\n    end\n    return sn\nend\n\n# Adapted from https://github.com/numpy/numpy/blob/4adc87dff15a247e417d50f10cc4def8e1c17a03/numpy/polynomial/legendre.py#L832-L914\nfunction legval(x, c::AbstractVector)\n    nd = length(c)\n    nd ≥ 2 || return last(c)\n\n    c0, c1 = @inbounds c[nd - 1], c[nd]\n    @inbounds for j in (nd - 2):-1:1\n        k = j / (j + 1)\n        c0, c1 = c[j] - c1 * k, c0 + c1 * x * (k + 1)\n    end\n    return c0 + c1 * x\nend\n\n# Adapted from https://github.com/numpy/numpy/blob/4adc87dff15a247e417d50f10cc4def8e1c17a03/numpy/polynomial/legendre.py#L1126-L1176\n\"\"\"\nlegvander(x, deg)\n\nPseudo-Vandermonde matrix of degree `deg`.\n\"\"\"\nfunction legvander(x::AbstractVector{T}, deg::Integer) where {T}\n    deg ≥ 0 || throw(DomainError(deg, \"degree needs to be non-negative\"))\n\n    vsize = (length(x), deg + 1)\n    v = Matrix{T}(undef, vsize...)\n\n    # Use forward recursion to generate the entries. This is not as accurate\n    # as reverse recursion in this application but it is more efficient.\n    @inbounds begin\n        v[:, 1] .= one(T)\n        if deg > 0\n            v[:, 2] .= x\n            for i in 2:deg\n                invi = inv(i)\n                @views @. v[:, i + 1] = v[:, i] * x * (2 - invi) - v[:, i - 1] * (1 - invi)\n            end\n        end\n    end\n\n    return v\nend\n\n# Adapted from https://github.com/numpy/numpy/blob/4adc87dff15a247e417d50f10cc4def8e1c17a03/numpy/polynomial/legendre.py#L612-L701\n\"\"\"\n    legder\n\"\"\"\nfunction legder(c::AbstractMatrix{T}) where {T}\n    c = copy(c)\n    n, m = size(c)\n    n -= 1\n    der = Matrix{T}(undef, n, m)\n    @views @inbounds for j in n:-1:2\n        @. der[j, :] = (2j - 1) * c[j + 1, :]\n        @. c[j - 1, :] += c[j + 1, :]\n    end\n    @views @inbounds @. der[1, :] = c[2, :]\n    return der\nend\n", "meta": {"hexsha": "bfd82a105935930c812e41e41f54055c460c03ef", "size": 2688, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/_specfuncs.jl", "max_stars_repo_name": "SpM-lab/SparseIR.jl", "max_stars_repo_head_hexsha": "02b377297b99df67138c74a6ac1de8266d58c003", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-18T16:36:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:47:20.000Z", "max_issues_repo_path": "src/_specfuncs.jl", "max_issues_repo_name": "SpM-lab/SparseIR.jl", "max_issues_repo_head_hexsha": "02b377297b99df67138c74a6ac1de8266d58c003", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2022-01-18T13:39:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T00:28:25.000Z", "max_forks_repo_path": "src/_specfuncs.jl", "max_forks_repo_name": "SpM-lab/SparseIR.jl", "max_forks_repo_head_hexsha": "02b377297b99df67138c74a6ac1de8266d58c003", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8666666667, "max_line_length": 141, "alphanum_fraction": 0.5911458333, "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7648985101256994}}
{"text": "\"\"\"\nAXLeastSquares(y, X)\n\nAn Ordinary Least Squares implementation.\n\"\"\"\n\nstruct AXLeastSquares <: AXEstimator\n    β::Array{Float64} # Coefficient\n    y::Matrix{Float64} # Response\n    X::Matrix{Float64} # Covariates\n\n    # Constructor Function\n    function AXLeastSquares(y::Matrix{Float64}, X::Matrix{Float64})\n        β = inv(X' * X) * (X' * y)\n        new(β, y, X)\n    end\nend #AXLeastSquares\n\n# Methods ======================================================================\n\"\"\"\ninfer(fit::AXLeastSquares; heteroskedastic, print_df)\n\nA method to calculate standard errors of an AXLeastSquares object.\n\"\"\"\nfunction infer(fit::AXLeastSquares; heteroskedastic::Bool=false, print_df::Bool=true)\n    # Retrieve necessary parameters\n    N = length(fit.y)\n    K = size(fit.X, 2) # number of covariates\n\n    # Calculate the variance-covariance matrix\n    resid  = fit.y - predict(fit)\n    XX     = fit.X' * fit.X\n    residX = fit.X .* resid\n    if heteroskedastic\n        vcv = inv(XX) * (residX' * residX) * inv(XX) .* (N / (N-K))\n    else\n        # homoskedasticity\n        vcv = inv(XX) .* (resid' * resid) ./ (N-K)\n    end\n\n    se = sqrt.(diag(vcv))\n    t_stat = fit.β ./ se\n    p_val = 2 * cdf.(Normal(), -abs.(t_stat))\n    r2 = 1 - sum(resid.^2)/sum((fit.y.-mean(fit.y)).^2)\n\n    # Print estimates\n    if print_df\n        out_df = DataFrame(hcat(fit.β, se, t_stat, p_val, r2), :auto)\n        rename!(out_df, [\"coef\", \"se\", \"t-stat\", \"p-val\", \"R-sqaure\"])\n        display(out_df)\n    end\n\n    # Organize and return output\n    output = (β = fit.β, se = se, t = t_stat, p = p_val, r = r2)\n    return output\nend #infer.AXLeastSquares\n", "meta": {"hexsha": "5b9e5e8de0dbd7cbb1d2ddd8c393db652a57b9d0", "size": 1631, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FUN/AXLeastSquares.jl", "max_stars_repo_name": "ningyin-xu/AXMethods.jl", "max_stars_repo_head_hexsha": "f20ce0923f8cb9c51b725feac1ce7d7a0ecddad9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FUN/AXLeastSquares.jl", "max_issues_repo_name": "ningyin-xu/AXMethods.jl", "max_issues_repo_head_hexsha": "f20ce0923f8cb9c51b725feac1ce7d7a0ecddad9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FUN/AXLeastSquares.jl", "max_forks_repo_name": "ningyin-xu/AXMethods.jl", "max_forks_repo_head_hexsha": "f20ce0923f8cb9c51b725feac1ce7d7a0ecddad9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6140350877, "max_line_length": 85, "alphanum_fraction": 0.5818516248, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7648978483490213}}
{"text": "\"\"\"\n    idct2!(x, fft_type::FFTType = Radix2Type())\n\nInverse discrete cosine transform of type II.\n\nX = IDCT2(Y) inverts the DCT2 transform, returning the\noriginal vector if Y was obtained using Y = DCT2(X). It is based on\nthe staggered-grid definition\n                          N\n   X(j) = 2/N*( Y(1)/2 +  ∑ Y(k) cos (π*(k-1)*(j-1/2)/N) )\n                         k=2\n\nX = IDCT2(Y,N) pads or truncates the vector Y to length N\nbefore transforming.\n\nIf Y is a matrix, the IDCT2 operation is applied to\neach column.\n\n                          N\n   X(j) = 2/N*( Y(1)/2 +  ∑ Y(k) cos (π*(k-1)*(j-1/2)/N) )\n                         k=2\n\"\"\"\nfunction idct2!(x, fft_type=Radix2Type())\n    x .= idct2(x, fft_type)\nend\nfunction idct2(a, fft_type::FFTType=Radix2Type())\n    FT = eltype(a)\n    if min(size(a)...)==1\n        if size(a,2)>1\n            do_trans = true;\n        else\n            do_trans = false;\n        end\n        a = a[:];\n    else\n        do_trans = false;\n    end\n    n = size(a,1);\n    m = size(a,2);\n    # Pad or truncate a if necessary\n    if size(a,1)<n\n      aa = zeros(n,m);\n      aa[1:size(a,1),:] .= a;\n    else\n      aa = a[1:n,:];\n    end\n    y = Array{Complex{FT},2}(undef, 2*n, m)\n    fill!(y, 0)\n    y[1:n,:] .= aa;\n    i = Complex(0,1);\n    e = 0.5 * exp.(-i*FT(0.5) * π * (0:n-1) ./ n);\n    for l = 1:m\n        y[1:n,l] .= y[1:n,l] .* e;\n    end\n    y[n+2:2*n,:] .= reverse(conj.(y[2:n,:]); dims=1);\n    yy = fft(y, 1);\n    b = (2/n) * yy[1:n,:];\n    if isreal(a)\n        b = real.(b)\n    end\n    if do_trans\n        b = b'\n    end\n    return b\nend\n", "meta": {"hexsha": "4174bff78b52a6d6c2fd7f142459ecee10254cb0", "size": 1573, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FFTs/idct.jl", "max_stars_repo_name": "charleskawczynski/MOONS.jl", "max_stars_repo_head_hexsha": "a88311ce88b665289e9780a65dceef76529f2d94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-26T22:31:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T22:31:50.000Z", "max_issues_repo_path": "src/FFTs/idct.jl", "max_issues_repo_name": "charleskawczynski/MOONS.jl", "max_issues_repo_head_hexsha": "a88311ce88b665289e9780a65dceef76529f2d94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2020-12-30T19:19:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-28T15:26:15.000Z", "max_forks_repo_path": "src/FFTs/idct.jl", "max_forks_repo_name": "charleskawczynski/MOONS.jl", "max_forks_repo_head_hexsha": "a88311ce88b665289e9780a65dceef76529f2d94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8333333333, "max_line_length": 67, "alphanum_fraction": 0.4780673872, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7648978416981649}}
{"text": "#=\n   From Allen Downey\n   https://twitter.com/AllenDowney/status/1063460117029535746\n   \"\"\"\n   Today's Bayesian problem of the week: Suppose we visit a wild animal preserve where we\n   know that the only animals are lions and tigers and bears, but we don't know how\n   many of each there are.\n\n   During the tour, we see 3 lions, 2 tigers, and 1 bear. Assuming that every animal had an equal\n   chance to appear in our sample, estimate the prevalence of each species.\n\n   What is the probability that the next animal we see is a bear?\n   \"\"\"\n\n   Also see: https://towardsdatascience.com/estimating-probabilities-with-bayesian-modeling-in-python-7144be007815\n    From https://towardsdatascience.com/estimating-probabilities-with-bayesian-modeling-in-python-7144be007815\n    \"\"\"\n    Species: lions    Prevalence: 44.44%.\n    Species: tigers   Prevalence: 33.33%.\n    Species: bears    Prevalence: 22.22%.\n    \"\"\"\n\n   Distributions of variable animal7\n   lion       =>    4526  (0.452600)\n   tiger      =>    3251  (0.325100)\n   bear       =>    2223  (0.222300)\n\n   Cf ~/blog/lions_tigers_and_bears.blog\n      ~/webppl/lions_tigers_and_bears.wppl\n\n\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n\n@model function lions_tigers_and_bears()\n    lion = 1\n    tiger = 2\n    bear = 3\n\n    # Prior\n    # probLion  ~ Beta(1,1)\n    # probTiger ~ Beta(1,1)\n    # probBear  ~ Beta(1,1)\n\n    # The Dirichlet distribution ensures that the sum of probabilities is 1\n    # i.e. we don't have to ensure this via some specific constraint.\n    v = [3, 2, 1] # We saw three lions, two tigers, and one bear\n    # v = [2,2,2]\n    x ~ Dirichlet(v)\n\n    # The probabilities to calculate (\"aliased\" for simplicity)\n    probLion  ~ Dirac(x[1])\n    probTiger ~ Dirac(x[2])\n    probBear  ~ Dirac(x[3])\n\n    n = 7\n    o = tzeros(n)\n    for i in 1:n\n        o[i] ~ Categorical([probLion,probTiger,probBear])\n    end\n\n    # It shouldn't matter in what order we see the different animals.\n    true ~ Dirac(o[1] == lion)\n    true ~ Dirac(o[2] == lion)\n    true ~ Dirac(o[3] == lion)\n    true ~ Dirac(o[4] == tiger)\n    true ~ Dirac(o[5] == tiger)\n    true ~ Dirac(o[6] == bear)\n\n    animal7 ~ Dirac(o[7])\n    \n    # probbear7 ~ Dirac(o[7] == bear)\n    # problion7 ~ Dirac(o[7] == lion)\n    # probtiger7 ~ Dirac(o[7] == tiger)\n\nend\n\n\nmodel = lions_tigers_and_bears()\nnum_chns = 4\n\n# chns = sample(model, Prior(), 10_000)\n\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(15), 10_000)\n# chns = sample(model, SMC(1000), 10_000)\n# chns = sample(model, IS(), 10_000)\n\n#\ndisplay(chns)\n\nshow_var_dist_pct(chns,:animal7,[\"lion\",\"tiger\",\"bear\"])\n", "meta": {"hexsha": "6b522819226df4302f1cdc736b362a0016e0f9f2", "size": 2634, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/lions_tigers_and_bears.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/lions_tigers_and_bears.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/lions_tigers_and_bears.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 27.4375, "max_line_length": 114, "alphanum_fraction": 0.6454062263, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7648978378121928}}
{"text": "123 == 123\n\n123 == 100 + 23\n\n123 == -123\n\ntypeof(true)\n\ntypeof(false)\n\ntypeof(45 == 45)\n\n23 ≤ -5\n\n4 ≠ 44\n\n1.0 == 1\n\n1.000000000001 == 1\n\n3 < 4 && -15 > -10\n\n3 < 4 || -15 > -10\n\n!(-4 ≥ 4) && (1 > 2 || 1 < 2)\n\n1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5\n\nx = -2.3\n-3 ≤ x ≤ 4\n\n# Examples of if-else statements\n\nfunction check_x(x)\n    if 0 ≤ x ≤ 10\n        println(\"x is between 0 and 10\")\n    elseif !(x < 0)\n        println(\"x is not between 0 and 10, and x is not negative (meaning x > 10)\")\n    else\n        println(\"x is not between 0 and 10, and x is not not negative (meaning x is negative)\")\n    end\nend\n\n\ncheck_x(π)\n\ncheck_x(10.000001)\n\ncheck_x(2^63)        # trick question - causes Int64 overflow\n\nx = -3\nif x ≥ 0 && sqrt(x) < 10\n    # do something\nelse\n    println(\"Sorry, need a non-negative number with square root strictly less than 10\")\nend\n\n\nfunction fibonacci(n)\n    # First special cases\n    if n == 0\n        return 0\n    elseif n == 1\n        return 1\n    else\n        # General case n ≥ 2 - initialize and iterate\n        Fkold = 0\n        Fk = 1\n        for k = 2:n\n            Fknew = Fk + Fkold\n            # Swap previous values\n            Fkold = Fk\n            Fk = Fknew\n        end\n        return Fk\n    end\nend\n\nfibonacci(10)\n\nfibonacci(1000)   # Again be careful with overflow of Int64, but this one is OK\n\nfunction PE1(n)\n    s = 0\n    for i = 1:n-1\n        if i % 3 == 0 || i % 5 == 0\n            s += i\n        end\n    end\n    s\nend\n\nPE1(10)\n\nPE1(1000)\n", "meta": {"hexsha": "b641d2ab8865f7fb759dc5b6490a260134b4190c", "size": 1485, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Introduction/Conditionals.jl", "max_stars_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_stars_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "textbook/_build/jupyter_execute/content/Introduction/Conditionals.jl", "max_issues_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_issues_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "textbook/_build/jupyter_execute/content/Introduction/Conditionals.jl", "max_forks_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_forks_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.46875, "max_line_length": 95, "alphanum_fraction": 0.5212121212, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.8652240791017535, "lm_q1q2_score": 0.7648920655083183}}
{"text": "using Plots\nusing LinearAlgebra\n\n\"\nThis code shows how errors for different finite difference methods converge as h->0.\n\"\n\n# define forward, centered differences, D3 = some other difference approx\nD1(u,x,h) = (u(x+h) - u(x))/h\nD2(u,x,h) = (u(x+h) - u(x-h))/(2*h)\nD3(u,x,h) = (u(x-2*h) - 6*u(x-h) + 3*u(x) + 2*u(x+h))/(6*h)\n\ninclude(\"fdcoeffV.jl\")\nx = -2:2\na = fdcoeffV(1,x[3],x) # 1 = order of derivative, x̄, stencil points x\nD4(u,x,h,c) = dot(c,(u(x-2*h),u(x-h),u(x),u(x+h),u(x+2*h)))/h\n\n# function, exact derivative\nu(x) = x^2 + sin(1+pi*x)\ndudx(x) = 2*x + pi*cos(1+pi*x)\nx = 0.0 # point at which we approximate the derivative\n\n# measure how error changes as h decreases\nhvec = 2.0 .^(-(0:8))\nerr = (zeros(size(hvec)),zeros(size(hvec)),zeros(size(hvec)),zeros(size(hvec)))\nfor (i,h) in enumerate(hvec)\n    err[1][i] = abs(dudx(x) - D1(u,x,h))\n    err[2][i] = abs(dudx(x) - D2(u,x,h))\n    err[3][i] = abs(dudx(x) - D3(u,x,h))\n    err[4][i] = abs(dudx(x) - D4(u,x,h,a))\nend\n\nplot(xaxis=:log,yaxis=:log,legend=:bottomright)\nlabels = (\"Forward diff\",\"Centered diff\",\"Some other 4-point diff\",\"5-point centered diff\")\nfor i = 1:4\n    plot!(hvec,err[i],marker=:dot,label=labels[i])\n    plot!(hvec,hvec.^i,linestyle=:dash,label=\"Order $(i)\")\nend\ndisplay(plot!())\n", "meta": {"hexsha": "cd7e07a0f75ef09febbc3249b78fd1189f97175d", "size": 1259, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week1/fd_convergence.jl", "max_stars_repo_name": "jlchan/caam452_s21", "max_stars_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:38:43.000Z", "max_issues_repo_path": "week1/fd_convergence.jl", "max_issues_repo_name": "jlchan/caam452_s21", "max_issues_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week1/fd_convergence.jl", "max_forks_repo_name": "jlchan/caam452_s21", "max_forks_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.475, "max_line_length": 91, "alphanum_fraction": 0.6131850675, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7647996639802339}}
{"text": "using Plots\ngr(titlefontsize=12,size=(500,300),transpose=true,colorbar=false)\n\nusing FourierGPE\n# Units\n# this example works in oscillator units\n\n## Initialize simulation\n\nL = (40.0,40.0)\nN = (256,256)\nsim = Sim(L,N)\n@unpack_Sim sim\n\n## simulation parameters\nμ = 15.0\n\n\n# potential\nimport FourierGPE.V\nV(x,y,t) = 0.5*(x^2 + y^2)\n\n# TF state\nψtf(x,y,μ,g) = sqrt(μ/g)*sqrt(max(1.0-V(x,y,0.0)/μ,0.0)+im*0.0)\n\n# make initial state\nx,y = X\nψi = ψtf.(x,y',μ,g)\nϕi = kspace(ψi,sim)\n\n@pack_Sim! sim\n\n## evolve\nsol = runsim(sim)\n\n## pull out the ground state\nϕg = sol[end]\nψg = xspace(ϕg,sim)\nshowpsi(x,y,ψg)\n\nR(w) = sqrt(2*μ/w^2)\nR(1)\nplot(x, abs2.(ψtf.(x,0.,μ,g)))\nplot!(x, abs2.(ψg[:,128]))\n\n## free expansion\nV(x,y,t) = 0.0\n\n# sim parameters\nγ = 0.0\ntf = 10.0\nt = LinRange(ti,tf,Nt)\nϕi = ϕg\n\nsime = Sim(L,N)\n@pack! sime = tf,t,γ,ϕi\n\n## evolve\nsole = runsim(sime)\n\nϕf = sole[end]\nψf = xspace(ϕf,sime)\nshowpsi(x,y,ψf)\n\nanim = @animate for i=1:Nt-6\n    ψ = xspace(sole[i],sime)\n    showpsi(x,y,ψ)\nend\n\ngif(anim,\"./examples/expand.gif\",fps=30)\n", "meta": {"hexsha": "29655ce5d0c4b07d9353db8c69e8b28f302624e8", "size": 1035, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/2dexpansion.jl", "max_stars_repo_name": "srivatsabprasad/FourierGPE.jl", "max_stars_repo_head_hexsha": "fec6571760f75a1fe135b8ac8548061b09aac626", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-20T15:53:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T15:53:01.000Z", "max_issues_repo_path": "examples/2dexpansion.jl", "max_issues_repo_name": "srivatsabprasad/FourierGPE.jl", "max_issues_repo_head_hexsha": "fec6571760f75a1fe135b8ac8548061b09aac626", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-12-11T04:59:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T06:31:28.000Z", "max_forks_repo_path": "examples/2dexpansion.jl", "max_forks_repo_name": "srivatsabprasad/FourierGPE.jl", "max_forks_repo_head_hexsha": "fec6571760f75a1fe135b8ac8548061b09aac626", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-21T00:16:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T00:16:14.000Z", "avg_line_length": 14.5774647887, "max_line_length": 65, "alphanum_fraction": 0.6280193237, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7647996543113661}}
{"text": "\"\"\"\n    first_po(n::Int64, k::Int64) -> po_idx::Vector{Int64}\n\nNotation-Generator: Calculate the first generator matrix in PO notation (padding ones indices) by n and k.\n\"\"\"\nfunction first_po(n::Int64, k::Int64)::Vector{Int64}\n    return collect(1:(n-k))\nend\n\n\n\"\"\"\n    next_po(current_po::Vector{Int64}, n::Int64, i=0) -> next::Vector{Int64}\n\nNotation-Generator: Calculates the next generator matrix in PO notation (padding ones indices) in relation to a given generator matrix in PO notation.\n\"\"\"\nfunction next_po(current_po::Vector{Int64}, n::Int64, i=0)::Vector{Int64}\n    if i > size(current_po,1)\n        println(\"Error: i=$i\")\n        return nothing\n    end\n    next = copy(current_po)\n    if current_po[end-i] + 1 > n - i\n        return next_po(current_po, n, i+1)\n    else\n        next[end-i] += 1\n        for j in (size(next,1) - i + 1):size(next,1)\n           next[j] = next[j-1] +1\n        end\n        return next\n    end\nend\n\n\n\"\"\"\n    construct_generators(n::Int64, k::Int64, prnt = false) -> Ω::Int64, all_pos, all_generating_matrices\n\nMatrix- and Notation-Generator: Calculate all generating matrices (including PO notations) and the number of generating matrices Ω.\n\"\"\"\nfunction construct_generators(n::Int64, k::Int64, prnt = false)\n    # calculate number of possible generating matrices\n    Ω = binomial(n,k)\n    println(\"There are Ω = ($n choose $k) = $Ω  possible basic permutations.\")\n\n    # Generate all possible padding ones positions first    \n    # number of padding ones\n    num_pos = n - k\n    # save first PO\n    all_pos = []\n    push!(all_pos, first_po(n,k))\n    # save first PO as matrix\n    all_generating_matrices = SparseMatrixCSC{ℤ₂, Int64}[]\n    push!(all_generating_matrices, po2matrix(all_pos[1],n))\n\n    if prnt\n        println(\n            \"1:\\t \", all_pos[1],\n            \"\\t↔ AI:\\t \", po2ai(all_pos[1],n), \n            \"\\tA² Test: \", multiplyZ2(all_generating_matrices[1],all_generating_matrices[1]) == id(n), \n            \": \", all_generating_matrices[1], \"\\n\\n\")\n    end\n\n    # construct all other generating matrices\n    for i in 2:Ω\n        next = next_po(all_pos[end],n)\n        push!(all_pos, next)\n        push!(all_generating_matrices, po2matrix(all_pos[end],n))\n        if prnt\n            println(\n                \"$i:\\t\", next, \n                \"\\t↔ AI:\\t \", po2ai(all_pos[end],n), \n                \"\\tA² Test: \", multiplyZ2(all_generating_matrices[end],all_generating_matrices[end]) == id(n), \n                \": \", all_generating_matrices[end], \"\\n\\n\")\n        end\n    end\n    \n    # return all necessary variables\n    return Ω, all_pos, all_generating_matrices\nend", "meta": {"hexsha": "0e98952d33aebe541693d983bcce14563dde361d", "size": 2618, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/generators.jl", "max_stars_repo_name": "Fhoeddinghaus/AntiIdClosedGroup.jl", "max_stars_repo_head_hexsha": "47576926259d8fc27128fab8b9c0b03d70b653c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/generators.jl", "max_issues_repo_name": "Fhoeddinghaus/AntiIdClosedGroup.jl", "max_issues_repo_head_hexsha": "47576926259d8fc27128fab8b9c0b03d70b653c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/generators.jl", "max_forks_repo_name": "Fhoeddinghaus/AntiIdClosedGroup.jl", "max_forks_repo_head_hexsha": "47576926259d8fc27128fab8b9c0b03d70b653c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5641025641, "max_line_length": 150, "alphanum_fraction": 0.6218487395, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.7647940191780046}}
{"text": "# # Lasso, Ridge and Elastic Net Regressions\n#\n# This notebook presents a simple implementation of Lasso and elastic net regressions.\n\n#-\n\n# ## Load Packages and Extra Functions\n\nusing DelimitedFiles, LinearAlgebra, Statistics, Plots, Convex, SCS\n\nimport MathOptInterface\nconst MOI = MathOptInterface\n\n# # Loading Data\n#\n# We use the diabetes data from Efron et al, downloaded from https://web.stanford.edu/~hastie/StatLearnSparsity_files/DATA/diabetes.html and then converted from a tab to a comma delimited file.\n#\n# All data series are standardised (see below) to have zero means and unit standard deviation, which improves the numerical stability. (Efron et al do not standardise the scale of the response variable.)\n\n(x,header) = readdlm(\"aux_files/diabetes.csv\",',',header=true)\n#display(header)\n#display(x)\n\nx = (x .- mean(x,dims=1))./std(x,dims=1)          #standardise\n\n(Y,X) = (x[:,end],x[:,1:end-1]);                  #to get traditional names\nxNames = header[1:end-1];\n\n# # Lasso, Ridge and Elastic Net Regressions\n#\n# (a)  The regression is $Y = Xb + u$,\n# where $Y$ and $u$ are $T \\times 1$, $X$ is $T \\times K$, and $b$ is the $K$-vector of regression coefficients.\n#\n# (b) We want to minimize $(Y-Xb)'(Y-Xb) + \\gamma \\sum |b_i| + \\lambda \\sum b_i^2$.\n#\n# (c) We can equally well minimise $b'Qb - 2c'b + \\gamma \\sum |b_i| + \\lambda \\sum b_i^2$,\n# where $Q = X'X$ and $c=X'Y$\n#\n# (d) Lasso: $\\gamma>0,\\lambda=0$; Ridge: $\\gamma=0,\\lambda>0$; elastic net: $\\gamma>0,\\lambda>0$.\n\n\"\"\"\n    LassoEN(Y,X,γ,λ)\n\nDo Lasso (set γ>0,λ=0), ridge (set γ=0,λ>0) or elastic net regression (set γ>0,λ>0).\n\n\n## Input\n- `Y::Vector`:     T-vector with the response (dependent) variable\n- `Y::VecOrMat`:   TxK matrix of covariates (regressors)\n- `γ::Number`:     penalty on sum(abs.(b))\n- `λ::Number`:     penalty on sum(b.^2)\n\n\"\"\"\nfunction LassoEN(Y,X,γ,λ=0.0)\n\n    K = size(X,2)\n\n    b_ls = X\\Y                    #LS estimate of weights, no restrictions\n\n    Q  = X'X\n    c  = X'Y                      #c'b = Y'X*b\n\n    b  = Variable(K)              #define variables to optimize over\n    L1 = quadform(b,Q)            #b'Q*b\n    L2 = dot(c,b)                 #c'b\n    L3 = norm(b,1)                #sum(|b|)\n    L4 = sumsquares(b)            #sum(b^2)\n\n    Sol = minimize(L1-2*L2+γ*L3+λ*L4)      #u'u + γ*sum(|b|) + λsum(b^2), where u = Y-Xb\n    solve!(Sol,()->SCS.Optimizer(verbose = false))\n    Sol.status == MOI.OPTIMAL ? b_i = vec(evaluate(b)) : b_i = NaN\n\n    return b_i, b_ls\n\nend\n\n# The next cell makes a Lasso regression for a single value of γ.\n\n\nK = size(X,2)\nγ = 100\n\n(b,b_ls) = LassoEN(Y,X,γ)\n\nprintln(\"OLS and Lasso coeffs (with γ=$γ)\")\ndisplay([[\"\" \"OLS\" \"Lasso\"];xNames b_ls b])\n\n# # Redo the Lasso Regression with Different Gamma Values\n#\n#\n# We now loop over $\\gamma$ values.\n#\n# Remark: it would be quicker to put this loop inside the `LassoEN()` function so as to not recreate `L1`-`L4`.\n\nnγ = 101\nγM = range(0; stop=600, length=nγ)             #different γ values\n\nbLasso   = fill(NaN,size(X,2),nγ)       #results for γM[i] are in bLasso[:,i]\nfor i = 1:nγ\n    bLasso[:,i], = LassoEN(Y,X,γM[i])\nend\n\n#-\n\nplot(log.(γM),bLasso',\n     title = \"Lasso regression coefficients\",\n     xlabel = \"log(γ)\",\n     label = permutedims(xNames),\n     size = (600,400))\n\n# # Ridge Regression\n#\n# We use the same function to do a ridge regression. Alternatively, do `b = inv(X'X + λ*I)*X'Y`.\n\nnλ = 101\nλM = range(0; stop=3000, length=nλ)\n\nbRidge  = fill(NaN,size(X,2),nλ)\nfor i = 1:nλ\n    bRidge[:,i], = LassoEN(Y,X,0,λM[i])\nend\n\n#-\n\nplot(log.(λM),bRidge',\n     title = \"Ridge regression coefficients\",\n     xlabel = \"log(λ)\",\n     label = permutedims(xNames),\n     size = (600,400))\n\n# # Elastic Net Regression\n\nλ = 200\nprintln(\"redo the Lasso regression, but with λ=$λ: an elastic net regression\")\n\nbEN   = fill(NaN,size(X,2),nγ)\nfor i = 1:nγ\n    bEN[:,i], = LassoEN(Y,X,γM[i],λ)\nend\n\n#-\n\nplot(log.(γM),bEN',\n     title = \"Elastic Net regression coefficients\",\n     xlabel = \"log(γ)\",\n     label = permutedims(xNames),\n     size = (600,400))\n#-\n", "meta": {"hexsha": "bea5a050e83f869799584ed79711b358c0684eae", "size": 4047, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/general_examples/lasso_regression.jl", "max_stars_repo_name": "JinraeKim/Convex.jl", "max_stars_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 123, "max_stars_repo_stars_event_min_datetime": "2020-06-16T21:56:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:05:39.000Z", "max_issues_repo_path": "docs/examples_literate/general_examples/lasso_regression.jl", "max_issues_repo_name": "JinraeKim/Convex.jl", "max_issues_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122, "max_issues_repo_issues_event_min_datetime": "2020-06-14T00:19:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T14:02:09.000Z", "max_forks_repo_path": "docs/examples_literate/general_examples/lasso_regression.jl", "max_forks_repo_name": "JinraeKim/Convex.jl", "max_forks_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2020-08-21T07:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T13:40:50.000Z", "avg_line_length": 27.1610738255, "max_line_length": 203, "alphanum_fraction": 0.6120583148, "num_tokens": 1359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.7647940073676531}}
{"text": "#=\n  Port of WebPPL code from https://github.com/probmods/ppaml2016/blob/gh-pages/chapters/5-election.md\n  \"\"\"\n  Basic model\n  Learning a state-wide preference from poll data\n  \"\"\"\n\n  Clinton: 1 Trump: 2\n  Distributions of variable (num:0)\n  2.00000 =>    8750  (0.875000)\n  1.00000 =>    1250  (0.125000)\n\n  According to the WebPPL model, the probability that Clinton wins (won) is 0.12207\n=#\n\nusing Turing\ninclude(\"jl_utils.jl\")\n\n@model function sampleElection()\n    function trueStatePref()\n        pref ~ Beta(1,1)\n        counts = Dict(:trump=>304, :clinton=>276)\n        total = sum(values(counts))\n        c ~ Binomial(total, pref)\n        true ~ Dirac(c == counts[:clinton])\n        return pref\n    end\n    clinton = 0\n    trump = 1\n    pref = trueStatePref()\n    turnout = 2400000\n    clintonVotes ~ Binomial(turnout,pref)\n    trumpVotes ~ Dirac(turnout - clintonVotes)\n    winner ~ Dirac(clintonVotes > trumpVotes ? clinton : trump)\n\n    clintonWins ~ Dirac(winner == clinton)\n    trumpWins ~ Dirac(winner == trump)    \n    return winner\nend\n\nmodel = sampleElection()\n\n# chns = sample(model, MH(), 10_000)\n# chns = sample(model, PG(15), 10_000)\n# chns = sample(model, IS(), 10_000)\nchns = sample(model, SMC(), 10_000)\n# chns = sample(model, SMC(), MCMCThreads(), 10_000, 4)\n\ndisplay(chns)\n\nchns_params = Turing.MCMCChains.get_sections(chns, :parameters)\ngenq = generated_quantities(model, chns_params)\nprintln(\"Clinton: 0 Trump: 1\")\nshow_var_dist_pct(genq)\n", "meta": {"hexsha": "bfd695d66dc8520811ed35b1d3a1dad8da5ea13b", "size": 1467, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/bda_presidential_election.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/bda_presidential_election.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/bda_presidential_election.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 26.6727272727, "max_line_length": 101, "alphanum_fraction": 0.6673483299, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240211961401, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7647891853319501}}
{"text": "# # Hovercraft Path Planning\n# In this case study, we seek to determine an optimal control policy for the\n# trajectory of a hovercraft that travels to a set of dynamic waypoints while\n# trying to minimize the thrust input. \n\n# ## Formulation\n\n# The corresponding dynamic optimization problem is expressed:\n# ```math\n# \\begin{aligned}\n# \t&&\\underset{x(t), v(t), u(t)}{\\text{min}} &&& \\int_{t \\in T} |u(t)|_2^2 dt  \\\\\n# \t&&\\text{s.t.} &&& v(0) = v0\\\\\n# \t&&&&& \\frac{dx}{dt} = v(t), && t \\in T\\\\\n#     &&&&& \\frac{dv}{dt} = u(t), && t \\in T\\\\\n#     &&&&& x(t_i) = xw_i, && i \\in I\n# \\end{aligned}\n# ```\n# where ``x(t)`` is the Cartesian position, ``v(t)`` is the velocity, ``u(t)`` is\n# the thrust input, ``xw_i, \\ i \\in I,`` are the waypoints, and ``T`` is the time\n# horizon.\n\n# ## Model Definition\n\n# Let's implement this in `InfiniteOpt` and first import the packages we need:\nusing InfiniteOpt, Ipopt\n\n# Next we'll specify our waypoint data:\nxw = [1 4 6 1; 1 3 0 1] # positions\ntw = [0, 25, 50, 60];    # times\n\n# We initialize the infinite model and opt to use the Ipopt solver:\nm = InfiniteModel(optimizer_with_attributes(Ipopt.Optimizer, \"print_level\" => 0));\n\n# Let's specify our infinite parameter which is time ``t \\in [0, 60]``:\n@infinite_parameter(m, t in [0, 60], num_supports = 61)\n\n# Now let's specify the decision variables:\n@variables(m, begin\n    ## state variables\n    x[1:2], Infinite(t)\n    v[1:2], Infinite(t)\n    ## control variables\n    u[1:2], Infinite(t), (start = 0)\nend)\n\n# Specify the objective:\n@objective(m, Min, ∫(u[1]^2 + u[2]^2, t))\n\n# Set the initial conditions with respect to the velocity:\n@constraint(m, [i = 1:2], v[i] == 0, DomainRestrictions(t => 0))\n\n# Define the point physics ODEs which serve as our system model:\n@constraint(m, [i = 1:2], ∂(x[i], t) == v[i])\n@constraint(m, [i = 1:2], ∂(v[i], t) == u[i])\n\n# Ensure we hit all the waypoints:\n@constraint(m, [i = 1:2, j = eachindex(tw)], x[i] == xw[i, j], DomainRestrictions(t => tw[j]))\n\n# ## Problem Solution\n\n# Optimize the model:\noptimize!(m)\n\n# Extract the results:\nx_opt = value.(x);\n\n# Plot the results:\nusing Plots\nscatter(xw[1,:], xw[2,:], label = \"Waypoints\", background_color = :transparent)\nplot!(x_opt[1], x_opt[2], label = \"Trajectory\")\nxlabel!(\"x_1\")\nylabel!(\"x_2\")\n\n# That's it, now we have our optimal trajectory!\n\n# ### Maintenance Tests\n# These are here to ensure this example stays up to date. \nusing Test\n@test termination_status(m) == MOI.LOCALLY_SOLVED\n@test has_values(m)\n@test x_opt isa Vector{<:Vector{<:Real}}\n", "meta": {"hexsha": "54c751572c2c0944ca6d9356a25727d325bee567", "size": 2528, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/Optimal Control/hovercraft.jl", "max_stars_repo_name": "azev77/InfiniteOpt.jl", "max_stars_repo_head_hexsha": "db734856e6d89fd105f7bdb4fb5b8e16a72bd7fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/src/examples/Optimal Control/hovercraft.jl", "max_issues_repo_name": "azev77/InfiniteOpt.jl", "max_issues_repo_head_hexsha": "db734856e6d89fd105f7bdb4fb5b8e16a72bd7fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/src/examples/Optimal Control/hovercraft.jl", "max_forks_repo_name": "azev77/InfiniteOpt.jl", "max_forks_repo_head_hexsha": "db734856e6d89fd105f7bdb4fb5b8e16a72bd7fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8292682927, "max_line_length": 94, "alphanum_fraction": 0.6408227848, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7647891817963742}}
{"text": "# Functions\r\n\r\n# Point\r\n#rand(rng::Random.AbstractRNG, ::Random.SamplerType{Point{T, N}}) where N where T = Point{T, N}(NTuple{N, T}(rand(rng, T, N)))\r\ndistance(p1::Point{T, N}, p2::Point{T, N}) where N where T = sqrt(sum((p1.coordinates .- p2.coordinates).^2))\r\n\r\nfunction area(arr::Array{Point{T, 2}, 1}) where T\r\n    length(arr) <= 2 && error(\"Area for two points cannot be computed!\")\r\n    area = 0.0\r\n    x = 2\r\n    y = 3\r\n    flag = false\r\n    while(x <= length(arr) && y <= length(arr))\r\n        a = distance(arr[1], arr[x])\r\n        b = distance(arr[x], arr[y])\r\n        c = distance(arr[1], arr[y])\r\n        s = (a + b + c)/2.0\r\n        area += sqrt(s*(s - a)*(s - b)*(s - c))\r\n        if flag == false\r\n            flag = true\r\n            x = y + 1\r\n        else\r\n            flag = false\r\n            y = x + 1\r\n        end\r\n    end\r\n    return area\r\nend\r\n\r\nfunction convexHull(points::Array{Point{T,2},1}) where T\r\n    if length(points) < 3\r\n        error(\"Minimum three points required\")\r\n    end\r\n    n = length(points)\r\n    function orientation(p::Point{T, 2}, q::Point{T, 2}, r::Point{T, 2}) where T <: Real\r\n        v = (q.coordinates[2] - p.coordinates[2])*(r.coordinates[1] - q.coordinates[1])- (q.coordinates[1] - p.coordinates[1])*(r.coordinates[2] - q.coordinates[2])\r\n        if v == 0 return 0 end\r\n        return v > 0 ? 1 : 2\r\n    end\r\n    hull = Array{Point{T, 2}, 1}(undef, 0)\r\n    l = 1\r\n    for i in 2:n\r\n        if points[i].coordinates[1] < points[l].coordinates[1]\r\n            l = i\r\n        end\r\n    end\r\n    p = l - 1\r\n    q = -1\r\n    while true\r\n        push!(hull, points[p + 1])\r\n        q = (p + 1) % n\r\n        for i in 0:(n - 1)\r\n            if(orientation(points[p + 1], points[i + 1], points[q+1]) == 2)\r\n                q = i\r\n            end\r\n        end\r\n        p = q\r\n        if p == l - 1\r\n            break\r\n        end\r\n    end\r\n    return hull\r\nend\r\n# Line\r\nfunction distance(p::Point{T, N}, l::Line{T, N}) where N where T\r\n    t = dot(p.coordinates .- l.p.coordinates, l.v)/dot(l.v, l.v)\r\n    return norm(p.coordinates .- l.p.coordinates .- t*l.v)\r\nend\r\ndistance(l::Line{T, N}, p::Point{T, N}) where N where T = distance(p::Point{T, N}, l::Line{T, N})\r\n\r\nfunction distance(l1::Line{T, N}, l2::Line{T, N}; err = 1e-10) where N where T\r\n    if norm(l1.v .- l2.v) ≦ err\r\n        return distance(l1.p, l2)\r\n    else\r\n        return zero(T)\r\n    end\r\nend\r\n\r\n# Plane\r\n\r\nfunction distance(p::Point{T, N}, q::Plane{T, N}) where N where T\r\n    x = distance(p, q.p)\r\n    y = distance(p, q.n)\r\n    return sqrt(x^2 - y^2)\r\nend\r\n\r\nfunction boundingbox(a::Array{Point{T, N}, 1}) where N where T\r\n    mn = Array{T,1}(undef, N)\r\n    mn .= typemax(T)\r\n    mx = Array{T,1}(undef, N)\r\n    mx .= typemin(T)\r\n    for i in 1:N, j in 1:length(a)\r\n        mn[i] = min(mn[i], a[j].coordinates[i])\r\n        mx[i] = max(mx[i], a[j].coordinates[i])\r\n    end\r\n    return (Point{T, N}(mn), Point{T, N}(mx))\r\nend\r\n", "meta": {"hexsha": "cb78c5c78a0585731fe0c327c43a8d6c8e6c85a7", "size": 2938, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "Ellipse0934/Example.jl", "max_stars_repo_head_hexsha": "332483de38043a5eef558a4e74c42c288e6a4cf6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions.jl", "max_issues_repo_name": "Ellipse0934/Example.jl", "max_issues_repo_head_hexsha": "332483de38043a5eef558a4e74c42c288e6a4cf6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions.jl", "max_forks_repo_name": "Ellipse0934/Example.jl", "max_forks_repo_head_hexsha": "332483de38043a5eef558a4e74c42c288e6a4cf6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9795918367, "max_line_length": 165, "alphanum_fraction": 0.5054458816, "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763572, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7647891817963741}}
{"text": "ProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n\nA = Float64[\n  1/2 1/3 1/4 1/5 1/6;\n  1/3 1/4 1/5 1/6 1/7;\n  1/4 1/5 1/6 1/7 1/8;\n  1/5 1/6 1/7 1/8 1/9;\n  1/6 1/7 1/8 1/9 1/10;\n]\nb = ones(5)\n\n(Al, Au, Ap) = lu(A)\n\n@show y = Al \\ b[Ap]\nprintln()\n\n@show x = Au \\ y\nprintln()\n\n@show As = sparse(A)\nprintln()\n\n@show As\\b\nprintln()\n\n@show F = lu(As)\nprintln()\n\n@show F.L * F.U == F.Rs .* A[F.p, :]\nprintln()\n\n@show F.L*F.U\nprintln()\n\n@show sparse(F.Rs.* A[F.p, F.q])\nprintln()\n\n@show lu(A)\nprintln()\n\nend", "meta": {"hexsha": "53dc7f8ddb098a9162a85e63b7d9b61983caccdd", "size": 496, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_sparse_02.jl", "max_stars_repo_name": "goedman/CSoM.jl", "max_stars_repo_head_hexsha": "4eecc92f3bbe17572b009325f40e9383ede6bb13", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2017-04-16T11:52:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T06:41:59.000Z", "max_issues_repo_path": "test/test_sparse_02.jl", "max_issues_repo_name": "goedman/CSoM.jl", "max_issues_repo_head_hexsha": "4eecc92f3bbe17572b009325f40e9383ede6bb13", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2018-07-04T00:14:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:16.000Z", "max_forks_repo_path": "test/test_sparse_02.jl", "max_forks_repo_name": "goedman/CSoM.jl", "max_forks_repo_head_hexsha": "4eecc92f3bbe17572b009325f40e9383ede6bb13", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2017-05-28T21:43:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T12:43:12.000Z", "avg_line_length": 11.8095238095, "max_line_length": 36, "alphanum_fraction": 0.5383064516, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7647891803860661}}
{"text": "\"\"\"\nPolynomial smoothing with the Savitzky Golay filters. Adapted for julia >= 1.0.\nSources: https://github.com/BBN-Q/Qlab.jl/blob/master/src/SavitskyGolay.jl\n         https://gist.github.com/lnacquaroli/c97fbc9a15488607e236b3472bcdf097\nRequires LinearAlgebra and DSP modules loaded.\n\"\"\"\n\n# TODO: could probably improve performance with some @inbounds sprinkling\nfunction savitzkyGolay(x::AbstractVector, windowSize::Int, polyOrder::Int; deriv::Int=0)\n\n  isodd(windowSize) || throw(\"Window size must be an odd integer.\")\n  polyOrder < windowSize || throw(\"Polynomial order must me less than window size.\")\n\n  halfWindow = Int( ceil((windowSize-1)/2) )\n\n  # Setup the S matrix of basis vectors\n  S = zeros.(windowSize, polyOrder+1)\n  for ct = 0:polyOrder\n    S[:,ct+1] = (-halfWindow:halfWindow).^(ct)\n  end\n\n  ## Compute the filter coefficients for all orders\n\n  # From the scipy code it seems pinv(S) and taking rows should be enough\n  G = S * pinv(S' * S)\n\n  # Slice out the derivative order we want\n  filterCoeffs = G[:, deriv+1] * factorial(deriv)\n\n  # Pad the signal with the endpoints and convolve with filter\n  paddedX = vcat(x[1]*ones(halfWindow), x, x[end]*ones(halfWindow))\n  y = conv(filterCoeffs[end:-1:1], paddedX)\n\n  # Return the valid midsection\n  return y[2*halfWindow+1:end-2*halfWindow]\n\nend", "meta": {"hexsha": "02a735e68df04c510d4eb8cf6edb30cf189741bf", "size": 1309, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/savgol.jl", "max_stars_repo_name": "matthijscox/BrainFlowML.jl", "max_stars_repo_head_hexsha": "8e33b0ede382f242dcaacdd10e9e3cd28bd5f308", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-01-18T21:40:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T15:50:38.000Z", "max_issues_repo_path": "src/savgol.jl", "max_issues_repo_name": "matthijscox/BrainFlowML.jl", "max_issues_repo_head_hexsha": "8e33b0ede382f242dcaacdd10e9e3cd28bd5f308", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/savgol.jl", "max_forks_repo_name": "matthijscox/BrainFlowML.jl", "max_forks_repo_head_hexsha": "8e33b0ede382f242dcaacdd10e9e3cd28bd5f308", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3783783784, "max_line_length": 88, "alphanum_fraction": 0.7219251337, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7647891803860661}}
{"text": "using Random, Plots, StatsPlots, Distributions, DataFrames, Optim\n# Bayesian Inference for Bernoulli parameter (inference success probability)\n# Define HPD (highest posterior density) interval\n# HPD are difficult to calculate and not be used nowadays. \n# Maybe this? https://github.com/tpapp/HighestDensityRegions.jl\n\"\"\"\nHPD interval for beta dist\nOptim.jl\nhttp://julianlsolvers.github.io/Optim.jl/v0.9.3/user/tipsandtricks/#dealing-with-constant-parameters\n    \n    Inputs\n    ------\n    ci0:  initial value for calculating HPD interval numerically\n    α:    parameter 1 of Beta dist\n    β:    parameter 2 of Beta dist\n    prob: probabilty of HPD interval\n    \n    Outputs\n    -------\n    HPD interval\n\n\"\"\"\nfunction beta_hpdi(ci0, α, β, prob)\n    \"\"\"\n    Continuous equation for HPD interval\n    \n        Inputs\n        ------\n        v: HPD interval (2-element Vector)\n        a: parameter 1 of Beta dist\n        b: parameter 2 of Beta dist\n        p: probabilty of HPD interval\n        \n        Outputs\n        -------\n        HPD interval condition equations (2-element Vector)\n\n    \"\"\"\n    function hpdi_conditions(v, a, b, p)\n        # HPD interval probability = p\n        eq1 = cdf(Beta(a, b), v[2]) - cdf(Beta(a, b), v[1]) - p\n        # p(lower|D) = p(upper|D)\n        eq2 = pdf(Beta(a, b), v[2]) - pdf(Beta(a, b), v[1])\n        return [eq1, eq2]\n    end\n    return nothing\nend\n\nfunction hpdi_conditions(v, a, b, p)\n    # HPD interval probability = p\n    eq1 = cdf(Beta(a, b), v[2]) - cdf(Beta(a, b), v[1]) - p\n    # p(lower|D) = p(upper|D)\n    eq2 = pdf(Beta(a, b), v[2]) - pdf(Beta(a, b), v[1])\n    return [eq1, eq2]\nend\n\nfunction hpdi_conditions(v)\n    # HPD interval probability = p\n    eq1 = cdf(Beta(14, 38), v[2]) - cdf(Beta(14, 38), v[1]) - 0.95\n    # p(lower|D) = p(upper|D)\n    eq2 = pdf(Beta(14, 38), v[2]) - pdf(Beta(14, 38), v[1])\n    return [eq1, eq2]\nend\n\n\n# Optimization\nhpdi_conditions([0.17, 0.41])\nOptim.optimize(hpdi_conditions, [0.17, 0.41])\nhpdi_conditions([0, 0])\nOptim.optimize(hpdi_conditions, [0, 0])\nNLsolve.nlsolve(hpdi_conditions)\n\n# Define calculation of posterior for Bernoulli parameter\n\"\"\"\nPosterior Distribution (Beta dist) for Bernoulli parameter π\n\n    Inputs\n    ------\n    data: data (0 or 1)\n    a0: parameter 1 of prior (Beta dist)\n    b0: parameter 2 of prior (Beta dist)\n    prob: credible interval probability (0 < prob < 1)\n\n    Outputs\n    -------\n    results: posterior summary stats table (DataFrames)\n    a: parameter 1 of posterior (Beta dist)\n    b: parameter 2 of posterior (Beta dist)\n\n\"\"\"\nfunction bernoulli_stats(data, a0, b0, prob)\n    # posterior\n    n = size(data)[1]\n    sum_data = sum(data)\n    a = sum_data + a0\n    b = n - sum_data + b0\n    d_posterior = Beta(a, b)\n    # mean\n    mean_π = mean(d_posterior)\n    # median\n    median_π = median(d_posterior)\n    # mode\n    mode_π = mode(d_posterior)\n    # Analytic Mode for Beta Dist\n    # (a - 1.0) / (a + b - 2.0)\n    # std\n    sd_π = std(d_posterior)\n    # credible interval\n    # ci upper boud\n    ci_π_upper = quantile(d_posterior, prob - (1-prob)/2)\n    # ci lower boud\n    ci_π_lower = quantile(d_posterior, (1-prob)/2)\n    ci_π = [ci_π_lower, ci_π_upper]\n\n    posterior_stats = reshape([mean_π, median_π, mode_π, sd_π, ci_π], 1, 5)\n    stats_string = [\"Mean\", \"Median\", \"Mode\", \"SD\", \"CI\"]\n    results = DataFrame(posterior_stats, stats_string)\n    return results, a, b\nend\n\n# Generate moc data from Bernoulli\np = 0.25\nn = 50\nRandom.seed!(99)\ndata = rand(Bernoulli(p), n)\n\n# Set prior\na0 = 1.0\nb0 = 1.0\n\n# Calculate posterior statistics\nprob = 0.95\nresults, a, b = bernoulli_stats(data, a0, b0, prob)\nprint(results)\n\n# Visualize Posterior\nplot(Beta(a0, b0), xlims=(0, 1), ylims=(0, 7), xlabel=\"Success Probability q\", ylabel=\"Probability Density\", label=\"prior: Beta(1, 1)\", linestyle=:dash)\nplot!(Beta(a, b), label=\"posterior: Beta($a, $b)\", linestyle=:solid)\n\n# Plot posterior by different prior\nRandom.seed!(99)\ndata = rand(Bernoulli(p), 250) # more data\nvalue_size = [10, 50, 250]\nvalue_a0 = [1.0, 6.0]\nvalue_b0 = [1.0, 4.0]\nstyles = [:dot, :dashdot, :dash, :solid]\n\nl = @layout [grid(1, 2)]\nplots = []\nfor index = 1:2\n    style_index = 1\n    a0_i = value_a0[index]\n    b0_i = value_b0[index]\n    pl = plot(Beta(a0_i, b0_i), linestyle=styles[style_index], label=\"prior: Beta($a0_i, $b0_i)\", color=\"cornflower blue\",\n             xlims=(0, 1), ylims=(0, 15.5), xlabel=\"Success Probability q\", ylabel=\"Probability Density\")\n    for n_j in value_size\n        style_index += 1\n        sum_data = sum(data[1:n_j])\n        a_j = sum_data + a0_i\n        b_j = n_j - sum_data + b0_i\n        plot!(Beta(a_j, b_j), linestyle=styles[style_index], label=\"posterior: Beta($a_j, $b_j)\", color=\"cornflower blue\")\n    end\n    push!(plots, pl)\nend\nplot(plots..., layout=l)\n\n# Animation\n# https://stackoverflow.com/questions/55794068/animating-subplots-using-plots-jl-efficiently\nRandom.seed!(99)\ndata = rand(Bernoulli(p), 250) # more data\nvalue_size = Vector(1:1:100)\nvalue_a0 = [1.0, 6.0]\nvalue_b0 = [1.0, 4.0]\n\ngr(fmt = :png)\nanim = @animate for n_j in value_size\n    sum_data = sum(data[1:n_j])\n    a_j_1 = sum_data + value_a0[1]\n    b_j_1 = n_j - sum_data + value_b0[1]\n    # all_p[1][1][:z] = Beta(a_j, b_j)\n    p1 = plot(Beta(a_j_1, b_j_1), color=\"cornflower blue\", label=\"posterior: Beta($a_j_1, $b_j_1)\", xlims=(0, 1), ylims=(0, 15.5), xlabel=\"Success Probability q\", ylabel=\"Probability Density\", title=\"n=$n_j\")\n    a0_1 = value_a0[1]\n    b0_1 = value_b0[1]\n    plot!(Beta(a0_1, b0_1), linestyle=:dot, label=\"prior: Beta($a0_1, $b0_1)\")\n\n    a_j_2 = sum_data + value_a0[2]\n    b_j_2 = n_j - sum_data + value_b0[2]\n    # all_p[2][1][:z] = Beta(a_j, b_j)\n    p2 = plot(Beta(a_j_2, b_j_2), color=\"cornflower blue\", label=\"posterior: Beta($a_j_2, $b_j_2)\", xlims=(0, 1), ylims=(0, 15.5), xlabel=\"Success Probability q\", ylabel=\"Probability Density\", title=\"n=$n_j\")\n    a0_2 = value_a0[2]\n    b0_2 = value_b0[2]\n    plot!(Beta(a0_2, b0_2), linestyle=:dot, label=\"prior: Beta($a0_2, $b0_2)\")\n\n    layout = @layout [grid(1, 2)]\n    plot(p1, p2; layout)\nend\ngif(anim, \"posterior.gif\", fps=10)", "meta": {"hexsha": "c928be3a28efc6f100ff4d687b91c00e1398184b", "size": 6107, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jlbayes_conjugate_bernoulli.jl", "max_stars_repo_name": "hessihan/julia_bayes_intro", "max_stars_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jlbayes_conjugate_bernoulli.jl", "max_issues_repo_name": "hessihan/julia_bayes_intro", "max_issues_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jlbayes_conjugate_bernoulli.jl", "max_forks_repo_name": "hessihan/julia_bayes_intro", "max_forks_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0, "max_line_length": 208, "alphanum_fraction": 0.6310790896, "num_tokens": 2104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240211961401, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7647891748036691}}
{"text": "\"\"\"\r\n    AMHCopula{d,T}\r\n\r\nFields:\r\n  - θ::Real - parameter\r\n\r\nConstructor\r\n\r\n    AMHCopula(d, θ)\r\n\r\nThe [AMH](https://en.wikipedia.org/wiki/Copula_(probability_theory)#Most_important_Archimedean_copulas) copula in dimension ``d`` is parameterized by ``\\\\theta \\\\in [0,1)``. It is an Archimedean copula with generator : \r\n\r\n```math\r\n\\\\phi(t) = 1 - \\\\frac{1-\\\\theta}{e^{-t}-\\\\theta}\r\n```\r\n\"\"\"\r\nstruct AMHCopula{d,T} <: ArchimedeanCopula{d}\r\n    θ::T\r\nend\r\nAMHCopula(d,θ) = (0 <= θ <= 1) ? AMHCopula{d,typeof(θ)}(θ) : @error \"Theta must be between 0 and 1\"\r\nϕ(  C::AMHCopula,t) = (1-C.θ)/(exp(t)-C.θ)\r\nϕ⁻¹(  C::AMHCopula,t) = log(C.θ + (1-C.θ)/t)\r\n\r\nτ(C::AMHCopula) = 1 - 2(C.θ+(1-C.θ)^2*log(1-C.θ))/(3C.θ^2) # no closed form inverse...\r\nfunction τ⁻¹(::Type{AMHCopula},τ)\r\n    if τ == zero(τ)\r\n        return τ\r\n    end\r\n    if τ > 1/3\r\n        @warn \"AMHCopula cannot handle kendall tau's greater than 1/3. We capped it to 1/3.\"\r\n        return 1\r\n    end\r\n    return Roots.fzero(θ -> 1 - 2(θ+(1-θ)^2*log(1-θ))/(3θ^2) - τ,0.5)\r\nend\r\n\r\n\r\nradial_dist(C::AMHCopula) = 1 + Distributions.Geometric(1-C.θ)\r\n\r\n\r\n", "meta": {"hexsha": "07bbbfdc274d394ee11c60b71cb5d1437eb0e892", "size": 1104, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ArchimedeanCopulas/AMHCopula.jl", "max_stars_repo_name": "lrnv/Copulas.jl", "max_stars_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2022-02-16T08:18:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:14:07.000Z", "max_issues_repo_path": "src/ArchimedeanCopulas/AMHCopula.jl", "max_issues_repo_name": "lrnv/Copulas.jl", "max_issues_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-19T06:55:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T09:43:03.000Z", "max_forks_repo_path": "src/ArchimedeanCopulas/AMHCopula.jl", "max_forks_repo_name": "lrnv/Copulas.jl", "max_forks_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6, "max_line_length": 220, "alphanum_fraction": 0.5815217391, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7647891740690979}}
{"text": "(@__DIR__) ∉ LOAD_PATH && push!(LOAD_PATH, (@__DIR__))\n\nmodule SequencesDemo\n\nusing IntegerSequences\n\nprintln(\"\\nProduct 1*2*3\")\np = ∏([1, 2, 3])\nprintln(p)\n\nprintln(\"\\nList of first 10000 Kolakoski numbers (timing):\")\n@time KolakoskiList(10000)\n\nprintln(\"\\nList of first 10000 partition numbers (timing):\")\n@time PartitionNumberList(10000)\n\nprintln(\"\\nList of first 10000 Clausen numbers (timing):\")\n@time ClausenNumberList(10000)\n\nprintln(\"\\nList of first 10000 Ramanujan tau numbers (timing):\")\n@time RamanujanTauList(10000)\n\nprintln(\"\\nRamanujan tau of n = 10000:\")\nr = RamanujanTau(10000)\nprintln(r)\n\nprintln(\"\\nAll partitions of 1, 2, 3, 4 and 5.\")\nfor n in 1:5 Partition(n); println() end\n\nprintln(\"\\nNumber of points in square lattice on the\ncircle of radius √n.\")\nSeqShow(L004018(12))\n\nprintln(\"\\nThe product of the prime numbers dividing n.\")\nprintln(typeof([Radical(n) for n in 0:9]))\nSeqShow([Radical(n) for n in 0:9])\n\nprintln(\"\\nOr:\")\nA = ZArray(9, Radical)\nSeqShow(A)\n\nprintln(\"\\n=============\")\n\nprintln(\"\\nThe exponential transform of Pascal's triangle.\")\nT = T055883(8)\nShowAsΔ(T)\n\nprintln(\"\\nThe row sums of the triangle above.\")\nPrintln(RowSums(T))\n\nprintln(\"\\nThe factorial of 100.\")\nf = F!(100)\nprintln(f)\n\nprintln(\"\\nThe rising factorial ↑(20, 80).\") # (a.k.a. Pochhammer)\nrf = 20 ↑ 80\nprintln(rf)\n\nprintln(\"\\nThe falling factorial ↓(80, 60).\")\nff = 80 ↓ 60\nprintln(ff)\n\nprintln(\"\\nThe number of divisors of n = 25920.\")\nt = τ(25920)\nprintln(t)\n\nprintln(\"\\nThe sum of divisors of n = 25920.\")\ns = σ(25920)\nprintln(s)\n\nprintln(\"\\nNumber of acyclic orientations of the\nTurán graph T(2n, n) for n = 20.\")\ng = V033815(20)\nprintln(g)\n\nprintln(\"\\nThe binomial function defined for all fmpz.\nThe same way as Maple and Mathematica compute the binomial.\nFirst the familiar Pascal case:\")\nfor n in 0:8\n    for k in 0:n print(lpad(Binomial(n, k), 4)) end\n    println()\nend\n\nprintln(\"\\nAn extended region on the 2-dim lattice:\")\nfor n in -5:5\n    for k in -5:5\n        print(lpad(Binomial(n, k), 5))\n    end\n    println()\nend\n\nprintln(\"\\nKnuth, Graham and Patashnik write in\nConcrete Mathematics: Hear us, O mathematicians\nof the world! Let us not wait any longer! We can\nmake many formulas clearer by defining a new notation\nnow! Let us agree to write m ⊥ n, and to say m is\nprime to n, if m and n are relatively prime.\\n\")\nfor n in 1:6\n    for m in 1:6 print(⊥(m, n), \" \" ) end\n    println()\nend\n\nprintln(\"\\nUsing conversion to integer this can also be written as:\\n\")\nfor n in 1:6\n    for m in 1:6 print(Int(⊥(m, n)), \" \" ) end\n    println()\nend\n\n# Generating the OLMS logo.\n# ⍊(n, k) means k is strong prime to n.\n# n is strong prime to k iff n is prime to k and n does not divide k-1.\n# Insert the line sum(L) == n - 5 && println(n) if you want to see why this\n# triangle is called the Save-Prime-Triangle.\n\nprintln(\"\\nThe Save-Prime-Triangle, the logo of the OLMS\n(open library of mathematical sequences).\\n\")\nfor n in 5:23\n    T = [k for k in 1:n if ⍊(n, k)]\n    L = [Int(k ∈ T) for k in 3:(n - 2)]\n    println(L)\nend\n\nprintln(\"\\n... have fun with Sequences!\")\n\nend # module\n", "meta": {"hexsha": "bb0d3ce1eb55fa75b5c98af176ea860cf5cb9885", "size": 3093, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demos/SequencesDemo.jl", "max_stars_repo_name": "OpenLibMathSeq/Sequences", "max_stars_repo_head_hexsha": "e53c1f30b7bf81669805f21d408d407b727615b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-06-25T08:54:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T04:52:29.000Z", "max_issues_repo_path": "demos/SequencesDemo.jl", "max_issues_repo_name": "OpenLibMathSeq/Sequences", "max_issues_repo_head_hexsha": "e53c1f30b7bf81669805f21d408d407b727615b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-04-30T19:07:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T15:51:34.000Z", "max_forks_repo_path": "demos/SequencesDemo.jl", "max_forks_repo_name": "PeterLuschny/IntegerSequences.jl", "max_forks_repo_head_hexsha": "1b9440bc8b86e3ae74fd26ee48fba412befbbdb5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-04-30T17:00:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:32:39.000Z", "avg_line_length": 24.5476190476, "max_line_length": 75, "alphanum_fraction": 0.6805690268, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.7647372527072483}}
{"text": "function HPDE_∂F∂x(func_F,u,Δx,dim)\n    Uₓᴸ, Uₓᴿ = GeneralFluxLimiter(u,Δx)\n    n = size(u,dim)\n    ∂f∂x = copy(u)\n\n    for i=1:n\n        A⁺ , A⁻ = LRJacobian(func_F,u[:,i])\n        ∂f∂x[:,i] = (A⁻ * Uₓᴸ[:,i] .+ A⁺ * Uₓᴿ[:,i])\n    end\n    return ∂f∂x\nend\n\nfunction HPDE_∂u∂t(prob::HPDEProblem,u)\n\n    ∂F∂x = HPDE_∂F∂x(prob.func_F,u,prob.Grid.Δx,2)\n\n    # future extentions\n    #∂F∂x = HPDE_∂F∂x(prob.func_F,u,prob.Grid.Δx,1)\n    #∂G∂y = HPDE_∂F∂x(prob.func_G,u,prob.Grid.Δy,2)\n    #∂H∂z = HPDE_∂F∂x(prob.func_H,u,prob.Grid.Δz,3)\n    #S = prob.func_S(u)\n\n    ∂G∂y = 0\n    ∂H∂z = 0\n    #S = func_S(u)\n    S = 0\n\n    ∂u∂t = S .- (∂F∂x .+ ∂G∂y .+ ∂H∂z)\n\n    return ∂u∂t\nend\n\n\nfunction LRJacobian(func_F,u)\n    A = ForwardDiff.jacobian(func_F, u)\n    #A = (abs.(A) .> 1e-10) .* A\n    #println(A)\n    Λ = diagm(eigvals(A))\n    Λ⁺ = 0.5 .* (Λ .+ abs.(Λ))\n    Λ⁻ = 0.5 .* (Λ .- abs.(Λ))\n    P = eigvecs(A)\n    P⁻¹ = inv(P)\n    A⁺ = P * Λ⁺ * P⁻¹\n    A⁻ = P * Λ⁻ * P⁻¹\n    return A⁺, A⁻\nend\n\nfunction GeneralFluxLimiter(u,Δx)\n    ϵ = 1.0e-8\n    ∂u∂x(U⁺,U⁻) = (U⁺ .- U⁻) ./ Δx\n    func_Ψ(r) = 0\n    #func_Ψ(r) = κ_Scheme_new(r,1)\n    func_Ψ(r) = SuperBee(r)\n    #func_Ψ(r) = Koren(r)\n    #func_Ψ(r) = 0\n    func_r(Uₓ₁,Uₓ₂) = (Uₓ₁ .+ ϵ) ./ (Uₓ₂ .+ ϵ)\n    func_U(Δxᵢ,r,uₓ) = (Δxᵢ / 2) .* func_Ψ(r) .* (uₓ .+ ϵ)\n    Uᵢ₋₂ = [u[:,1] u[:,1] u[:,1:end-2]]\n    Uᵢ₋₁ = [u[:,1] u[:,1:end-1]]\n    Uᵢ   = copy(u)\n    Uᵢ₊₁ = [u[:,2:end] u[:,end]]\n    Uᵢ₊₂ = [u[:,3:end] u[:,end] u[:,end]]\n\n    Uₓi₊¾ = ∂u∂x(Uᵢ₊₂,Uᵢ₊₁)\n    Uₓi₊½ = ∂u∂x(Uᵢ₊₁,Uᵢ)\n    Uₓi₋½ = ∂u∂x(Uᵢ,Uᵢ₋₁)\n    Uₓi₋¾ = ∂u∂x(Uᵢ₋₁,Uᵢ₋₂)\n\n    Uᴸi₊½ = Uᵢ₊₁ .- func_U(Δx,func_r(Uₓi₊½,Uₓi₊¾),Uₓi₊¾)\n    Uᴸi₋½ = Uᵢ   .- func_U(Δx,func_r(Uₓi₋½,Uₓi₊½),Uₓi₊½)\n    Uᴿi₊½ = Uᵢ   .+ func_U(Δx,func_r(Uₓi₊½,Uₓi₋½),Uₓi₋½)\n    Uᴿi₋½ = Uᵢ₋₁ .+ func_U(Δx,func_r(Uₓi₋½,Uₓi₋¾),Uₓi₋¾)\n\n    Uₓᴸ = (Uᴸi₊½ .- Uᴸi₋½) ./ Δx\n    Uₓᴿ = (Uᴿi₊½ .- Uᴿi₋½) ./ Δx\n    #return Uᴿi₊½, Uᴿi₋½, Uᴸi₊½ , Uᴸi₋½\n    #return Uₓi₊¾, Uₓi₊½, Uₓi₋½, Uₓi₋¾\n    return Uₓᴸ, Uₓᴿ\nend\n\n\n\n\n\n################## METHODS ####################\n\nfunction Koren(r)\n    return max.(0,min.(2 .* r,min.(1/3 .+ 2 /3 .* r,2)))\nend\n\nfunction UpWind_FO(r)\n    return 0\nend\n\nfunction UpWind_SO(r)\n    return κ_Scheme_new(r,-1)\nend\n\nfunction SCD(r)\n    return κ_Scheme_new(r,1)\nend\n\nfunction UpWind_Q(r)\n    return κ_Scheme_new(r,0.5)\nend\n\nfunction UpWind_C(r)\n    return κ_Scheme_new(r,1/3.0)\nend\n\nfunction SuperBee(r)\n    return max.(0,min.(r,1))\nend\n", "meta": {"hexsha": "370bec7978bed77ed527f92f7dc90ae4c1cc5abe", "size": 2424, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FVMPDE_methods.jl", "max_stars_repo_name": "CyanRaptor/TEMPsolver_PDE.jl", "max_stars_repo_head_hexsha": "e904651c75f2c132fcb2a3e9962dbd8185a6c00d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FVMPDE_methods.jl", "max_issues_repo_name": "CyanRaptor/TEMPsolver_PDE.jl", "max_issues_repo_head_hexsha": "e904651c75f2c132fcb2a3e9962dbd8185a6c00d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FVMPDE_methods.jl", "max_forks_repo_name": "CyanRaptor/TEMPsolver_PDE.jl", "max_forks_repo_head_hexsha": "e904651c75f2c132fcb2a3e9962dbd8185a6c00d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2631578947, "max_line_length": 58, "alphanum_fraction": 0.5041254125, "num_tokens": 1457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897558991953, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7647372519242406}}
{"text": "# Converts an FFT into a gammatonegram. Based on the gammatonegram/fft2gammatonemx MATLAB \n# functions by Dan Ellis.\n# D. P. W. Ellis (2009). \"Gammatone-like spectrograms\", web resource.\n# http://www.ee.columbia.edu/~dpwe/resources/matlab/gammatonegram/\n\ntype Gammatonegram{T, F<:Real} <: DSP.Periodograms.TFR{T}\n\tamplitude::Matrix{T}\n\tfrequencies::Vector{F}\n\ttime::FloatRange{Float64}\nend\n\nfunction gammatonegram(x,sr::Integer,twin::Real,thop::Real,N::Integer,fmin,fmax,width)\n\tnfft = int(2^(ceil(log(2*twin*sr)/log(2))))\n    nhop = iround(thop*sr)\n    nwin = iround(twin*sr)\n    (W,F) = fft2gammatonemx(nfft, sr, N, width, fmin, fmax)\n    # perform FFT and weighting in amplitude domain\n\tS = stft(x, nwin, nwin-nhop; nfft=nfft, fs=sr, window=hanning)\n\tY = 1/nfft*W*abs(S)\n\tGammatonegram(Y, vec(F), ((0:size(Y,2)-1)*(nhop)+nwin/2)/sr)\nend\n\nfunction fft2gammatonemx(nfft::Integer, sr::Integer, N::Integer, width, fmin, fmax)\n\t# Allocating matrix to store the filterbank weights\n\tW = zeros(N, int(nfft/2+1));\n\t# Gammatone filterbank constants\n\tEarQ = 9.26449\n\tminBW = 24.7\n\torder = 1\n\n\tcfreqs = -(EarQ*minBW) + exp((1:N)'*(-log(fmax + EarQ*minBW) + log(fmin + EarQ*minBW))/N) * (fmax + EarQ*minBW);\n\tcfreqs = fliplr(cfreqs)\n\tGTord = 4\n\tucirc = exp(im*2*pi*[0:(nfft/2)]/nfft)\n\tfor k=1:N\n\t    cf = cfreqs[k];\n\t    ERB = width*((cf/EarQ).^order + minBW^order).^(1/order);\n\t    B = 1.019*2*pi*ERB;\n\t    r = exp(-B/sr);\n\t    theta = 2*pi*cf/sr;\n\t    pole = r*exp(im*theta);\n\t    T = 1/sr;\n\t    \n\t\tA11 = -(2*T*cos(2*cf*pi*T)./exp(B*T) + 2*sqrt(3+2^1.5)*T*sin(2*\n\t                                                      cf*pi*T)./exp(B*T))/2; \n\t    A12 = -(2*T*cos(2*cf*pi*T)./exp(B*T) - 2*sqrt(3+2^1.5)*T*sin(2*\n\t                                                      cf*pi*T)./exp(B*T))/2;\n\t    A13 = -(2*T*cos(2*cf*pi*T)./exp(B*T) + 2*sqrt(3-2^1.5)*T*sin(2*\n\t                                                      cf*pi*T)./exp(B*T))/2; \n\t    A14 = -(2*T*cos(2*cf*pi*T)./exp(B*T) - 2*sqrt(3-2^1.5)*T*sin(2*\n\t                                                      cf*pi*T)./exp(B*T))/2; \n\t    zros = -[A11 A12 A13 A14]/T;\n    \n\t    gain =  abs((-2*exp(4*im*cf*pi*T)*T + \n\t                2*exp(-(B*T) + 2*im*cf*pi*T).*T.* \n\t                (cos(2*cf*pi*T) - sqrt(3 - 2^(3/2))* \n\t                 sin(2*cf*pi*T))) .* \n\t               (-2*exp(4*im*cf*pi*T)*T + \n\t                2*exp(-(B*T) + 2*im*cf*pi*T).*T.* \n\t                (cos(2*cf*pi*T) + sqrt(3 - 2^(3/2)) * \n\t                 sin(2*cf*pi*T))).* \n\t               (-2*exp(4*im*cf*pi*T)*T + \n\t                2*exp(-(B*T) + 2*im*cf*pi*T).*T.* \n\t                (cos(2*cf*pi*T) - \n\t                 sqrt(3 + 2^(3/2))*sin(2*cf*pi*T))) .* \n\t               (-2*exp(4*im*cf*pi*T)*T + 2*exp(-(B*T) + 2*im*cf*pi*T).*T.* \n\t                (cos(2*cf*pi*T) + sqrt(3 + 2^(3/2))*sin(2*cf*pi*T))) ./ \n\t               (-2 ./ exp(2*B*T) - 2*exp(4*im*cf*pi*T) +  \n\t                2*(1 + exp(4*im*cf*pi*T))./exp(B*T)).^4);\n\t    W[k,:] = ((T^4)/gain) *\n\t        abs(ucirc-zros[1]).*abs(ucirc-zros[2]) .*\n\t        abs(ucirc-zros[3]).*abs(ucirc-zros[4]) .*\n\t        (abs((pole-ucirc).*(pole'-ucirc)).^-GTord);\n\tend\n\tW, cfreqs\t\nend\n", "meta": {"hexsha": "bf649ef514dcda6d2a221bb63a4258c025d83dd4", "size": 3158, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Gammatonegram.jl", "max_stars_repo_name": "JuliaPackageMirrors/AuditoryFilters.jl", "max_stars_repo_head_hexsha": "b9d203e983351d24340e780c5788fee57bca585b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Gammatonegram.jl", "max_issues_repo_name": "JuliaPackageMirrors/AuditoryFilters.jl", "max_issues_repo_head_hexsha": "b9d203e983351d24340e780c5788fee57bca585b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Gammatonegram.jl", "max_forks_repo_name": "JuliaPackageMirrors/AuditoryFilters.jl", "max_forks_repo_head_hexsha": "b9d203e983351d24340e780c5788fee57bca585b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.012987013, "max_line_length": 113, "alphanum_fraction": 0.4844838505, "num_tokens": 1217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587142, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7647372465264104}}
{"text": "#!/usr/bin/julia\n\n# Trizen\n# 28 August 2020\n# https://github.com/trizen\n\n# Generate all the positive divisors of n.\n\nusing Primes\n\nfunction divisors(n)\n\n    d = Int64[1]\n\n    for (p,e) in factor(n)\n        t = Int64[]\n        r = 1\n\n        for i in 1:e\n            r *= p\n            for u in d\n                push!(t, u*r)\n            end\n        end\n\n        append!(d, t)\n    end\n\n    return sort(d)\nend\n\nprintln(divisors(5040))\n", "meta": {"hexsha": "1c955e8109cc7961b137669400b8c33489de3423", "size": 434, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Math/divisors.jl", "max_stars_repo_name": "trizen/julia-scripts", "max_stars_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-03-22T09:38:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T21:38:31.000Z", "max_issues_repo_path": "Math/divisors.jl", "max_issues_repo_name": "trizen/julia-scripts", "max_issues_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/divisors.jl", "max_forks_repo_name": "trizen/julia-scripts", "max_forks_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.1515151515, "max_line_length": 42, "alphanum_fraction": 0.4907834101, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7647372399124559}}
{"text": "function kernel(x::REALMAT, x₀::REALMAT, kernel_struct::Kernel)\n    @assert size(x, 2) == size(x₀, 2) \"The number of columns of x and x₀ do not match.\"\n    # Dispatch to kernel\n    K = kernel_calculation(x, x₀, kernel_struct::Kernel)\n    return K\nend\nkernel(x::REALMAT, kernel_struct::Kernel) = kernel(x, x, kernel_struct)\n\n# Linear\nfunction kernel_calculation(x, x₀, k::Linear)\n    K = [dot(x[i1, :], x[i2, :]) for i1 in 1:size(x, 1), i2 in 1:size(x₀, 1)]\n    return K * k.σ\nend\n\n# Radial Basis Function (Squared Exponential)\nfunction kernel_calculation(x, x₀, k::RBF)\n    K = zeros(size(x, 1), size(x₀, 1))\n    for i1 in 1:size(x, 1)\n        for i2 in 1:size(x₀, 1)\n            K[i1, i2] = k.σ * exp(-sum((x[i1, :] .- x₀[i2, :]).^2)/(2*k.l^2))\n        end\n    end\n    return K\nend\n\n# Rational Quadratic\nfunction kernel_calculation(x, x₀, k::RationalQuadratic)\n    K = zeros(size(x, 1), size(x₀, 1))\n    for i1 in 1:size(x, 1)\n        for i2 in 1:size(x₀, 1)\n            K[i1, i2] = k.σ * (1.0 + sum((x[i1, :] .- x₀[i2, :])^2)/(2 * k.a * k.l^2))^-k.a\n        end\n    end\n    return K\nend\n\n# Periodic\nfunction kernel_calculation(x, x₀, k::Periodic)\n    K = zeros(size(x, 1), size(x₀, 1))\n    for i1 in 1:size(x, 1)\n        for i2 in 1:size(x₀, 1)\n            K[i1, i2] = k.σ * exp(-2 * sin(sum(abs.(x[i1, :] .- x₀[i2, :])))^2/k.l^2)\n        end\n    end\n    return K\nend\n\n# Locally Periodic\nfunction kernel_calculation(x, x₀, k::LocallyPeriodic)\n    K = zeros(size(x, 1), size(x₀, 1))\n    for i1 in 1:size(x, 1)\n        for i2 in 1:size(x₀, 1)\n            K[i1, i2] = k.σ * exp(-2 * sin(sum(abs.(x[i1, :] .- x₀[i2, :])))^2/k.l^2) * exp(-sum((x[i1, :] .- x[i2, :].^2)/(2*k.l^2)))\n        end\n    end\n    return K\nend", "meta": {"hexsha": "929ef123a98b9098193ca2c955af65810aff4d98", "size": 1714, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels.jl", "max_stars_repo_name": "madskoefoed/RecursiveLeastSquares.jl", "max_stars_repo_head_hexsha": "2bca940810cadeaac961ab54c1c619c387dd8c70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels.jl", "max_issues_repo_name": "madskoefoed/RecursiveLeastSquares.jl", "max_issues_repo_head_hexsha": "2bca940810cadeaac961ab54c1c619c387dd8c70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels.jl", "max_forks_repo_name": "madskoefoed/RecursiveLeastSquares.jl", "max_forks_repo_head_hexsha": "2bca940810cadeaac961ab54c1c619c387dd8c70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0701754386, "max_line_length": 134, "alphanum_fraction": 0.5507584597, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7647372385629985}}
{"text": "function evalPsiFromRectangleCoil(r0,z0,dr,dz,Ic,quadRule_r,quadRule_z, xr,xz; derivative=0)\n\t\n\tsurf=dr*dz\n\tjc=Ic/surf\n\n\t#define quadrature points and weigths in the rectangle\n\txgr=r0 .+ quadRule_r.x *0.5 *dr\t\n\txgz=z0 .+ quadRule_z.x *0.5 *dz\t\n\n\txgr_rep=repeat(xgr,size(xgz,1))\n\txgz_rep=reshape(repeat(xgz,1,size(xgr,1))',size(xgr,1)*size(xgz,1))\n\t\n\twgr=quadRule_r.w *0.5 *dr\t\n\twgz=quadRule_z.w *0.5 *dz\t\n\n\twgr_rep=repeat(wgr,size(wgz,1))\n\twgz_rep=reshape(repeat(wgz,1,size(wgr,1))',size(wgr,1)*size(wgz,1))\n\n\t#\n\tG = @.Green(xr,xz,xgr_rep,xgz_rep, derivative=derivative)\n\tG_PXPG = getindex.(G,:G_xy)\n\n\tval=wgr_rep.*wgz_rep.*G_PXPG*jc\n\tval=sum(val)\t\n\n\tif(derivative==0)\n\t\treturn (psi=val,)\n\tend\n\tif(derivative>0)\n\t\tdxrG = getindex.(G,:dxrG_xy)\n\t\tdxzG = getindex.(G,:dxzG_xy)\n\n\t\tdxrval=wgr_rep.*wgz_rep.*dxrG*jc\n\t\tdxzval=wgr_rep.*wgz_rep.*dxzG*jc\n\t\n\t\tdxrval=sum(dxrval)\t\n\t\tdxzval=sum(dxzval)\t\n\t\t\n\t\treturn (psi=val, dxrpsi=dxrval, dxzpsi=dxzval)\n\n\tend\n\nend\n\nfunction assemblyRhsRectangleCoil(r0,z0,dr,dz,Ic,quadRule_r, quadRule_z, BEMesh, quadRule)\n\n\t# dimension\n\tn=size(BEMesh.edges,1)\n\n\t#\n\trhs=zeros(n)\n\n\t#quadrature rule on BEMesh\n\txGauss=quadRule.x\n\twGauss=quadRule.w\n\tnQuad=size(quadRule.w,1)\n\n\t#in order to remap the quadrature we need the midpoints and length of edges\n\te=collect(1:n)\n\tedgeToNode=BEMesh.edges\n\th=BEMesh.length\n\n    P=0.5*(BEMesh.coordinates[edgeToNode[:,1],:]+BEMesh.coordinates[edgeToNode[:,2],:])\n\t#@show P\n\t\n\t#quadrature points on all edges\n\tPG=zeros(size(P,1),2,nQuad)\n\tfor i in 1:nQuad\n\t\tPG[:,:,i]=P + xGauss[i]*0.5*(BEMesh.coordinates[edgeToNode[:,2],:]-BEMesh.coordinates[edgeToNode[:,1],:])\n\n\t\tevalC=@.evalPsiFromRectangleCoil((r0,),(z0,),(dr,),(dz,),(Ic,),(quadRule_r,),(quadRule_z,), PG[:,1,i], PG[:,2,i])\n\t\t\n\t\tpsiC = getindex.(evalC,:psi)\n\n\t\trhs=rhs+0.5*wGauss[i]*h.*psiC\n\tend\n\n\treturn rhs\n\nend\n", "meta": {"hexsha": "691e67ea8c0ed31bcfe98041c7cc0ee7881f77d8", "size": 1827, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rectangleCoil.jl", "max_stars_repo_name": "blaise-faugeras/VacBEM.jl", "max_stars_repo_head_hexsha": "afa3c3e26b482a2749806a756f62e17a52f520dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rectangleCoil.jl", "max_issues_repo_name": "blaise-faugeras/VacBEM.jl", "max_issues_repo_head_hexsha": "afa3c3e26b482a2749806a756f62e17a52f520dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rectangleCoil.jl", "max_forks_repo_name": "blaise-faugeras/VacBEM.jl", "max_forks_repo_head_hexsha": "afa3c3e26b482a2749806a756f62e17a52f520dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5555555556, "max_line_length": 115, "alphanum_fraction": 0.6896551724, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7647372347311834}}
{"text": "\"\"\"\n    randBall(nDims, nPts)\n\nDraw nPts random points uniformely distributed in an nDims-dimensional ball.\n\n# Implementation\nSamples uniformely in a unit cube, then throws away unnecessary points.\nEfficient only for low number of dimensions (nDims=1,2,3).\n\n# Examples\n```julia-repl\njulia> using FPRS; using Plots;\njulia> x = randBall(2,50);\njulia> figure(); scatter(x[1,:], x[2,:]);\n```\n\"\"\"\nfunction randBall(nDims::Integer, nPts::Integer)\n\n    res = zeros(nDims, nPts)\n    numInBall = 0\n    \n    while numInBall < nPts\n        newPoint = 2.0 * rand(nDims) .- 1.0\n        if norm(newPoint) <= 1\n            numInBall += 1\n            res[1:end, numInBall] = newPoint\n        end\n    end\n    \n    return res\nend\n\n\n\"\"\"\n    randRotationMatrix(deflection=1.0; randSeed)\n\nReturn a random rotation matrix in 3d.\n\nSources:\n-http://blog.lostinmyterminal.com/python/2015/05/12/random-rotation-matrix.html\n-http://www.realtimerendering.com/resources/GraphicsGems/gemsiii/rand_rotation.c\n\n# Arguments\n- `deflection`: number between 0 and 1 controls the size of the perturbation. \n                For 0, no rotation; for 1, competely random rotation. \n                Small deflection => small perturbation.\n\n# Examples\n```julia-repl\njulia> mx = randRotationMatrix();\n```\n\"\"\"\nfunction randRotationMatrix(deflection=1.0)\n    # Random.seed!(seedVal) # do not reseed rng\n    \n    theta = 2.0*deflection* pi * rand() # Rotation about the pole (Z)\n    phi = 2.0* pi * rand() # For direction of pole deflection\n    z = 2.0*deflection * rand() # For magnitude of pole deflection\n    \n    # Compute a vector V used for distributing points over the sphere\n    # via the reflection I - V Transpose(V).  This formulation of V\n    # will guarantee that if x[1] and x[2] are uniformly distributed,\n    # the reflected points will be uniform on the sphere.  Note that V\n    # has length sqrt(2) to eliminate the 2 in the Householder matrix.\n    \n    r =  sqrt(z)\n    Vx = sin(phi) * r\n    Vy = cos(phi) * r\n    Vz = sqrt(2.0 - z)\n\n    # Compute the row vector S = Transpose(V) * R, where R is a simple\n    # rotation by theta about the z-axis.  No need to compute Sz since\n    # it's just Vz.\n\n    st = sin(theta)\n    ct = cos(theta)\n    Sx = Vx * ct - Vy * st\n    Sy = Vx * st + Vy * ct\n    \n    # Construct the rotation matrix  ( V Transpose(V) - I ) R, which\n    # is equivalent to V S - R.\n\n    M = zeros(3,3)\n    M[1,1] = Vx * Sx - ct;\n    M[1,2] = Vx * Sy - st;\n    M[1,3] = Vx * Vz;\n\n    M[2,1] = Vy * Sx + st;\n    M[2,2] = Vy * Sy - ct;\n    M[2,3] = Vy * Vz;\n\n    M[3,1] = Vz * Sx;\n    M[3,2] = Vz * Sy;\n    M[3,3] = 1.0 - z;   # This equals Vz * Vz - 1.0\n\n    return M\nend\n", "meta": {"hexsha": "69a3d801f748c66c4180331f203733e5c1603c06", "size": 2657, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utilities.jl", "max_stars_repo_name": "tsipenyuk/FPRS", "max_stars_repo_head_hexsha": "9cbf7f835ffaed78deb8dd1ca42b5f3bc461c2b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utilities.jl", "max_issues_repo_name": "tsipenyuk/FPRS", "max_issues_repo_head_hexsha": "9cbf7f835ffaed78deb8dd1ca42b5f3bc461c2b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utilities.jl", "max_forks_repo_name": "tsipenyuk/FPRS", "max_forks_repo_head_hexsha": "9cbf7f835ffaed78deb8dd1ca42b5f3bc461c2b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.112244898, "max_line_length": 80, "alphanum_fraction": 0.6157320286, "num_tokens": 846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465044347828, "lm_q2_score": 0.8175744850834649, "lm_q1q2_score": 0.7647154367378863}}
{"text": "# ffr, 19 April 2016\n\n# for the moment, I decided to not include L, because it can\n# be calculated from A and B\nstruct LF1dGrid\n    N::Int64\n    A::Float64\n    B::Float64\n    h::Float64\n    grid::Array{Float64,1}\n    D1jl::Array{Float64,2}\n    D2jl::Array{Float64,2}\nend\n\n# Periodic LF\nfunction init_LF1d_p( N::Int64, A::Float64, B::Float64, verbose=false )\n    # Check argument\n    if N % 2 == 0\n        error(\"N must be an odd number\\n\")\n    end\n    L = (B - A)\n    h = L/N\n    grid = zeros(Float64,N)\n    for i = 1:N\n        grid[i] = A + 0.5*(B-A)*(2*i-1)/N\n    end\n    D1jl = zeros(Float64,N,N)\n    D2jl = zeros(Float64,N,N)\n    #\n    # Diagonal elements\n    #\n    Nprimed = (N-1)/2\n    for j = 1:N\n        # the diagonal elements of D1jl are already zero\n        D2jl[j,j] = -(2.0*pi/L)^2 * Nprimed * (Nprimed+1)/3.\n    end\n    #\n    # Off diagonal elements\n    #\n    for j = 1 : N\n        for l = j+1 : N\n            #\n            nn = j - l\n            #\n            tt1 = pi/L * (-1.0)^nn\n            tt2 = sin(pi*nn/N)\n            #\n            tt3 = (2.0*pi/L)^2 * (-1.0)^nn * cos(pi*nn/N)\n            tt4 = 2.0*sin(pi*nn/N)^2\n            #\n            D1jl[j,l] =  tt1/tt2\n            D1jl[l,j] = -tt1/tt2\n            #\n            D2jl[j,l] = -tt3/tt4\n            D2jl[l,j] = -tt3/tt4\n        end\n    end\n    #\n    LF = LF1dGrid( N, A, B, h, grid, D1jl, D2jl )\n    if verbose\n        @printf(\"Allocated: periodic 1d LBF grid: N, h = %d , %f\\n\", N, h)\n    end\n    #\n    return LF\nend # function init_LF1d_p\n\n\n# cluster Lagrange function\nfunction init_LF1d_c( N::Int64, A::Float64, B::Float64, verbose=false )\n    L = B - A\n    h = L/(N + 1.)\n    #\n    grid = zeros(Float64,N)\n    for i = 1:N\n        grid[i] = A + i*(B-A)/(N+1)\n    end\n    #\n    D1jl = zeros(Float64,N,N)  # XXX this is not yet used\n    D2jl = zeros(Float64,N,N)\n    #\n    # Diagonal part\n    #\n    pre = -pi^2/(2.0*L^2)\n    for i = 1:N\n        t1 = ( 2.0*(N+1)^2 + 1 )/3.0\n        t2 = sin( i*pi/(N+1) )^2\n        D2jl[i,i] = pre*( t1 - 1.0/t2 )\n    end\n    #\n    # Off-diagonal\n    #\n    for l = 1 : N\n        for j = l+1 : N\n            nnm = l - j\n            nnp = l + j\n            pre = -pi^2 / (2*L^2) * (-1.0)^nnm\n            t1 = sin( pi*nnm/2.0/(N+1) )^2\n            t2 = sin( pi*nnp/2.0/(N+1) )^2\n            #\n            D2jl[l,j] = pre*( 1.0/t1 - 1.0/t2 )\n            D2jl[j,l] = pre*( 1.0/t1 - 1.0/t2 )  # XXX is it faster to just recalculate?\n        end\n    end\n    LF = LF1dGrid( N, A, B, h, grid, D1jl, D2jl )\n    if verbose\n        @printf(\"Allocated: cluster 1d LBF grid: N, h = %5d , %10.5f\\n\", N, h)\n    end\n    return LF\nend\n\n\n# Lagrange-sinc function\nfunction init_LF1d_sinc( N::Int64, h::Float64, verbose=false )\n    # Choice for A and B\n    A = -(N-1)*h/2.0\n    B =  (N-1)*h/2.0\n    #\n    grid = zeros(Float64,N)\n    for i = 1:N\n        grid[i] = A + (i-1)*h\n    end\n    #\n    D1jl = zeros(Float64,N,N)  # XXX this is not yet used\n    D2jl = zeros(Float64,N,N)\n    #\n    # Diagonal part\n    #\n    for i = 1:N\n        D2jl[i,i] = -pi^2 / 3.0 / h^2\n    end\n    #\n    # Off-diagonal\n    #\n    for j = 1 : N\n        for i = j+1 : N\n            D2jl[i,j] = -2.0*(-1.0)^(i-j)/( grid[i] - grid[j] )^2\n            D2jl[j,i] = D2jl[i,j]  # XXX is it faster to just recalculate?\n        end\n    end\n    LF = LF1dGrid( N, A, B, h, grid, D1jl, D2jl )\n    if verbose\n        @printf(\"Allocated: 1d Lagrange-sinc grid: N, h = %5d , %10.5f\\n\", N,  h)\n    end\n    return LF\nend\n", "meta": {"hexsha": "eed1543856de7cd2a15731d10ee511e4505e20cb", "size": 3469, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LF/LF_common/m_LF1d.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "LF/LF_common/m_LF1d.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LF/LF_common/m_LF1d.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 23.7602739726, "max_line_length": 88, "alphanum_fraction": 0.4641106947, "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7647154331061246}}
{"text": "\"\"\"\n    Step{T, S<:Integer}(start, decay, step_sizes)\n    Step(;λ, γ, step_sizes)\n\nA step schedule decays exponentially by `γ` every step\nin `step_sizes`.\nThe output conforms to\n```text\nλ * γ^{i - 1}\n```\nwhere `sum(step_sizes[1:(i - 1)]) < t <= sum(step_sizes[1:i])`\n\n# Arguments:\n- `start`/`λ`: the starting value\n- `decay`/`γ`: the decay rate\n- `step_sizes::Union{<:Integer, <:Vector}`: the step sizes\n\"\"\"\nstruct Step{T, S<:Integer}\n    start::T\n    decay::T\n    step_sizes::Vector{S}\nend\nStep(λ, γ, step_size::Integer) = Step(λ, γ, [step_size])\nStep(;λ, γ, step_sizes) = Step(λ, γ, step_sizes)\n\nfunction (schedule::Step)(t)\n    i = findlast(x -> t > x, cumsum(schedule.step_sizes))\n    i = isnothing(i) ? 0 :\n            (i >= length(schedule.step_sizes)) ? length(schedule.step_sizes) - 1 : i\n\n    return schedule.start * schedule.decay^i\nend\n\nBase.eltype(::Type{<:Step{T}}) where T = T\nBase.IteratorSize(::Type{<:Step}) = Base.IsInfinite()\n\nfunction Base.iterate(schedule::Step, state = (1, 1, 1))\n    t, i, t0 = state\n    if (i < length(schedule.step_sizes)) && (t >= t0 + schedule.step_sizes[i])\n        # move onto next step range\n        i += 1\n        t0 = t\n    end\n\n    return schedule.start * schedule.decay^(i - 1), (t + 1, i, t0)\nend\n\nBase.axes(::Step) = (OneToInf(),)\n\n\n\"\"\"\n    Exp{T}(start, decay)\n    Exp(;λ, γ)\n\nA exponential decay schedule at rate `γ`.\nThe output conforms to\n```text\nλ * γ^{t - 1}\n```\n\n# Arguments:\n- `start`/`λ`: the base value\n- `decay`/`γ`: the decay rate\n\"\"\"\nstruct Exp{T}\n    start::T\n    decay::T\nend\nExp(;λ, γ) = Exp(λ, γ)\n\n(schedule::Exp)(t) = schedule.start * schedule.decay^(t - 1)\n\nBase.eltype(::Type{<:Exp{T}}) where T = T\nBase.IteratorSize(::Type{<:Exp}) = Base.IsInfinite()\n\nBase.iterate(schedule::Exp, t = 1) = schedule(t), t + 1\n\nBase.axes(::Exp) = (OneToInf(),)\n\n\"\"\"\n    Poly{T, S<:Integer}(start, degree, max_iter)\n    Poly(;λ, p, max_iter)\n\nA polynomial schedule decays with degree `p`.\nThe output conforms to\n```text\nλ / (1 - (t - 1) / max_iter)^p\n```\n\n# Arguments\n- `start`/`λ`: the base value\n- `degree`/`p::Integer`: the degree of the polynomial\n- `max_iter::Integer`: the total number of iterations\n\"\"\"\nstruct Poly{T, S<:Integer}\n    start::T\n    degree::S\n    max_iter::S\nend\nPoly(;λ, p, max_iter) = Poly(λ, p, max_iter)\n\nfunction (schedule::Poly)(t)\n    (t <= length(schedule)) || throw(BoundsError(\"Cannot index Poly for t > max_iter\"))\n    return schedule.start * (1 - (t - 1) / schedule.max_iter)^schedule.degree\nend\n\nBase.eltype(::Type{<:Poly{T}}) where T = T\nBase.IteratorSize(::Type{<:Poly}) = Base.HasLength()\nBase.length(schedule::Poly) = schedule.max_iter\n\nBase.iterate(schedule::Poly, t = 1) = schedule(t), t + 1\n\nBase.axes(schedule::Poly) = 1:length(schedule)\n\n\n\"\"\"\n    Inv{T, S<:Integer}(start, decay, degree)\n    Inv(;λ, γ, p)\n\nA decay schedule that inversely decays with rate `γ`.\nThe output conforms to\n```text\nλ / (1 + (t - 1) * γ)^p\n```\n\n# Arguments\n- `start`/`λ`: the base value\n- `decay`/`γ`: the decay rate\n- `degree`/`p::Integer`: the degree of decay\n\"\"\"\nstruct Inv{T<:Number, S<:Integer}\n    start::T\n    decay::T\n    degree::S\nend\nInv(;λ, γ, p) = Inv(λ, γ, p)\n\n(schedule::Inv)(t) = schedule.start / (1 + (t - 1) * schedule.decay)^schedule.degree\n\nBase.eltype(::Type{<:Inv{T}}) where T = T\nBase.IteratorSize(::Type{<:Inv}) = Base.IsInfinite()\n\nBase.iterate(schedule::Inv, t = 1) = schedule(t), t + 1\n\nBase.axes(::Inv) = (OneToInf(),)", "meta": {"hexsha": "c5b7ed86f1b68166c9aa47628f8690cc70c43ea1", "size": 3418, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/decay.jl", "max_stars_repo_name": "darsnack/ParameterSchedulers.jl", "max_stars_repo_head_hexsha": "83cb8f794b0926eb50c91f07db9391d321d4189f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2020-12-30T08:08:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T05:08:52.000Z", "max_issues_repo_path": "src/decay.jl", "max_issues_repo_name": "darsnack/ParameterSchedulers.jl", "max_issues_repo_head_hexsha": "83cb8f794b0926eb50c91f07db9391d321d4189f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-12-28T17:37:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T03:47:46.000Z", "max_forks_repo_path": "src/decay.jl", "max_forks_repo_name": "darsnack/ParameterSchedulers.jl", "max_forks_repo_head_hexsha": "83cb8f794b0926eb50c91f07db9391d321d4189f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-12-28T15:35:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-13T13:13:04.000Z", "avg_line_length": 23.5724137931, "max_line_length": 87, "alphanum_fraction": 0.617612639, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346504434783, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7647154263440574}}
{"text": "\nusing DifferentialEquations\nfunction f(du,u,p,t)\n    du[1] = -u[1]\nend\nu0 = [10.0]\nconst V = 1\nprob = ODEProblem(f,u0,(0.0,10.0))\n\n\nsol = solve(prob,Tsit5())\nusing Plots; gr()\nplot(sol)\n\n\ncondition(u,t,integrator) = t==4 && u[1]/V<4\naffect!(integrator) = integrator.u[1] += 10\ncb = DiscreteCallback(condition,affect!)\n\n\nsol = solve(prob,Tsit5(),tstops=[4.0],callback=cb)\nusing Plots; gr()\nplot(sol)\n\n\nprintln(sol(4.00000))\nprintln(sol(4.000000000001))\n\n\nfunction f(du,u,p,t)\n    du[1] = -u[1]/6\nend\nu0 = [10.0]\nconst V = 1\nprob = ODEProblem(f,u0,(0.0,10.0))\n\n\nsol = solve(prob,Tsit5())\nusing Plots; gr()\nplot(sol)\n\n\nsol = solve(prob,Tsit5(),tstops=[4.0],callback=cb)\nusing Plots; gr()\nplot(sol)\n\n\nusing SciMLTutorials\nSciMLTutorials.tutorial_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])\n\n", "meta": {"hexsha": "83e7a49db3a73543530240be2664072379d21a96", "size": 790, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/models/02-conditional_dosing.jl", "max_stars_repo_name": "SciML/SciMLTutorialsOutput", "max_stars_repo_head_hexsha": "f66779faa9eb1dc131c1adfe8099f26f09afc458", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-05-24T10:30:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T12:13:03.000Z", "max_issues_repo_path": "script/models/02-conditional_dosing.jl", "max_issues_repo_name": "SciML/SciMLTutorialsOutput", "max_issues_repo_head_hexsha": "f66779faa9eb1dc131c1adfe8099f26f09afc458", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-07T21:39:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T03:48:31.000Z", "max_forks_repo_path": "script/models/02-conditional_dosing.jl", "max_forks_repo_name": "SciML/SciMLTutorialsOutput", "max_forks_repo_head_hexsha": "f66779faa9eb1dc131c1adfe8099f26f09afc458", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-24T14:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T14:30:36.000Z", "avg_line_length": 15.4901960784, "max_line_length": 69, "alphanum_fraction": 0.6658227848, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465044347828, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7647154221865257}}
{"text": "module Operators\n\nexport grad,lapq,bclap,bcdiv,adv,cgsolv\n\nusing LinearAlgebra\nusing SparseArrays\n\nfunction grad(velovec,p,u,v,pvec,nx,ny,dx,dy)\n\n    G = spzeros(length(velovec),length(pvec))\n\n    for i = 1:nx\n        for j = 1:ny\n\n            if i != nx\n\n                G[u[j,i],p[j,i+1]] =    1/dx\n                G[u[j,i],p[j,i]]   = -1/dx\n\n            end\n\n            if j != ny\n\n                G[v[j,i],p[j+1,i]] =    1/dy\n                G[v[j,i],p[j,i]]   = -1/dy\n\n            end\n        end\n    end\n\n    return G\nend\n\nfunction lapq(velovec,p,u,v,nx,ny,dx,dy)\n\n    cuti = (nx-1)*ny\n\nL = spzeros(length(velovec),length(velovec))\n\n    for i = 1:nx-1\n        for j = 1:ny\n\n\n        if i != 1 && j != 1 && i != nx-1 && j != ny\n\n\n            L[u[j,i],u[j,i+1]] =    1/dx/dx\n            L[u[j,i],u[j,i]] =     -2/dx/dx\n            L[u[j,i],u[j,i-1]] =    1/dx/dx\n\n            L[u[j,i],u[j+1,i]] =    1/dy/dy\n            L[u[j,i],u[j,i]] +=     -2/dy/dy\n            L[u[j,i],u[j-1,i]] =    1/dy/dy\n        end\n\n\n        # left\n        if i == 1 && j != 1 && j != ny\n\n            L[u[j,i],u[j,i+1]] =    1/dx/dx\n            L[u[j,i],u[j,i]] =     -2/dx/dx\n#             L[u[j,i],u[j,i-1]] =    1/dx/dx\n\n            L[u[j,i],u[j+1,i]] =    1/dy/dy\n            L[u[j,i],u[j,i]] +=     -2/dy/dy\n            L[u[j,i],u[j-1,i]] =    1/dy/dy\n        end\n\n        if i == nx-1 && j != 1 && j != ny\n\n#             L[u[j,i],u[j,i+1]] =    1/dx/dx\n            L[u[j,i],u[j,i]] =     -2/dx/dx\n            L[u[j,i],u[j,i-1]] =    1/dx/dx\n\n            L[u[j,i],u[j+1,i]] =    1/dy/dy\n            L[u[j,i],u[j,i]] +=     -2/dy/dy\n            L[u[j,i],u[j-1,i]] =    1/dy/dy\n        end\n\n        if i != 1 && j == 1 && i != nx-1\n\n            L[u[j,i],u[j,i+1]] =    1/dx/dx\n            L[u[j,i],u[j,i]] =     -2/dx/dx\n            L[u[j,i],u[j,i-1]] =    1/dx/dx\n\n            L[u[j,i],u[j+1,i]] =    1/dy/dy\n            L[u[j,i],u[j,i]] +=     -3/dy/dy\n#             L[u[j,i],u[j-1,i]] =    1/dy/dy\n        end\n\n        if i != 1 && j == ny && i != nx-1\n\n            L[u[j,i],u[j,i+1]] =    1/dx/dx\n            L[u[j,i],u[j,i]] =     -2/dx/dx\n            L[u[j,i],u[j,i-1]] =    1/dx/dx\n\n#             L[u[j,i],u[j+1,i]] =    1/dy/dy\n            L[u[j,i],u[j,i]] +=     -3/dy/dy\n            L[u[j,i],u[j-1,i]] =    1/dy/dy\n        end\n\n            # four corners\n        if (j == 1 && i == 1)\n\n            L[u[j,i],u[j,i+1]] =    1/dx/dx\n            L[u[j,i],u[j,i]] =     -2/dx/dx\n#             L[u[j,i],u[j,i-1]] =    1/dx/dx\n\n            L[u[j,i],u[j+1,i]] =    1/dy/dy\n            L[u[j,i],u[j,i]] +=     -3/dy/dy\n#             L[u[j,i],u[j-1,i]] =    1/dy/dy\n\n        end\n\n        if (j == 1 && i == nx-1)\n\n#             L[u[j,i],u[j,i+1]] =    1/dx/dx\n            L[u[j,i],u[j,i]] =     -2/dx/dx\n            L[u[j,i],u[j,i-1]] =    1/dx/dx\n\n            L[u[j,i],u[j+1,i]] =    1/dy/dy\n            L[u[j,i],u[j,i]] +=     -3/dy/dy\n#             L[u[j,i],u[j-1,i]] =    1/dy/dy\n\n        end\n\n        if (j == ny && i == 1)\n\n            L[u[j,i],u[j,i+1]] =    1/dx/dx\n            L[u[j,i],u[j,i]] =     -2/dx/dx\n#             L[u[j,i],u[j,i-1]] =    1/dx/dx\n\n#             L[u[j,i],u[j+1,i]] =    1/dy/dy\n            L[u[j,i],u[j,i]] +=     -3/dy/dy\n            L[u[j,i],u[j-1,i]] =    1/dy/dy\n\n        end\n\n        if (j == ny && i == nx-1)\n\n#             L[u[j,i],u[j,i+1]] =    1/dx/dx\n            L[u[j,i],u[j,i]] =     -2/dx/dx\n            L[u[j,i],u[j,i-1]] =    1/dx/dx\n\n#             L[u[j,i],u[j+1,i]] =    1/dy/dy\n            L[u[j,i],u[j,i]] +=     -3/dy/dy\n            L[u[j,i],u[j-1,i]] =    1/dy/dy\n\n        end\n    end\nend\n\n    for i = 1:nx\n        for j = 1:ny-1\n\n        if i != 1 && j != 1 && i != nx && j != ny-1\n\n            L[v[j,i],v[j,i+1]] =    1/dx/dx\n            L[v[j,i],v[j,i]] =     -2/dx/dx\n            L[v[j,i],v[j,i-1]] =    1/dx/dx\n\n            L[v[j,i],v[j+1,i]] =    1/dy/dy\n            L[v[j,i],v[j,i]] +=     -2/dy/dy\n            L[v[j,i],v[j-1,i]] =    1/dy/dy\n        end\n\n\n        if i == 1 && j != 1 && j != ny-1\n\n            L[v[j,i],v[j,i+1]] =    1/dx/dx\n            L[v[j,i],v[j,i]] =     -3/dx/dx\n#             L[v[j,i],v[j,i-1]] =    1/dx/dx\n\n            L[v[j,i],v[j+1,i]] =    1/dy/dy\n            L[v[j,i],v[j,i]] +=     -2/dy/dy\n            L[v[j,i],v[j-1,i]] =    1/dy/dy\n        end\n\n        if i == nx && j != 1 && j != ny-1\n\n#             L[v[j,i],v[j,i+1]] =    1/dx/dx\n            L[v[j,i],v[j,i]] =     -3/dx/dx\n            L[v[j,i],v[j,i-1]] =    1/dx/dx\n\n            L[v[j,i],v[j+1,i]] =    1/dy/dy\n            L[v[j,i],v[j,i]] +=     -2/dy/dy\n            L[v[j,i],v[j-1,i]] =    1/dy/dy\n        end\n\n        if i != 1 && j == 1 && i != nx\n\n            L[v[j,i],v[j,i+1]] =    1/dx/dx\n            L[v[j,i],v[j,i]] =     -2/dx/dx\n            L[v[j,i],v[j,i-1]] =    1/dx/dx\n\n            L[v[j,i],v[j+1,i]] =    1/dy/dy\n            L[v[j,i],v[j,i]] +=     -2/dy/dy\n#             L[u[j,i],u[j-1,i]] =    1/dy/dy\n        end\n\n        if i != 1 && j == ny-1 && i != nx\n\n            L[v[j,i],v[j,i+1]] =    1/dx/dx\n            L[v[j,i],v[j,i]] =     -2/dx/dx\n            L[v[j,i],v[j,i-1]] =    1/dx/dx\n\n#             L[u[j,i],u[j+1,i]] =    1/dy/dy\n            L[v[j,i],v[j,i]] +=     -2/dy/dy\n            L[v[j,i],v[j-1,i]] =    1/dy/dy\n        end\n\n            # four corners\n        if (j == 1 && i == 1)\n\n            L[v[j,i],v[j,i+1]] =    1/dx/dx\n            L[v[j,i],v[j,i]] =     -3/dx/dx\n#             L[u[j,i],u[j,i-1]] =    1/dx/dx\n\n            L[v[j,i],v[j+1,i]] =    1/dy/dy\n            L[v[j,i],v[j,i]] +=     -2/dy/dy\n#             L[u[j,i],u[j-1,i]] =    1/dy/dy\n\n        end\n\n        if (j == 1 && i == nx)\n\n#             L[u[j,i],u[j,i+1]] =    1/dx/dx\n            L[v[j,i],v[j,i]] =     -3/dx/dx\n            L[v[j,i],v[j,i-1]] =    1/dx/dx\n\n            L[v[j,i],v[j+1,i]] =    1/dy/dy\n            L[v[j,i],v[j,i]] +=     -2/dy/dy\n#             L[u[j,i],u[j-1,i]] =    1/dy/dy\n\n        end\n\n        if (j == ny-1 && i == 1)\n\n            L[v[j,i],v[j,i+1]] =    1/dx/dx\n            L[v[j,i],v[j,i]] =     -3/dx/dx\n#             L[u[j,i],u[j,i-1]] =    1/dx/dx\n\n#             L[u[j,i],u[j+1,i]] =    1/dy/dy\n            L[v[j,i],v[j,i]] +=     -2/dy/dy\n            L[v[j,i],v[j-1,i]] =    1/dy/dy\n\n        end\n\n        if (j == ny-1 && i == nx)\n\n#             L[u[j,i],u[j,i+1]] =    1/dx/dx\n            L[v[j,i],v[j,i]] =     -3/dx/dx\n            L[v[j,i],v[j,i-1]] =    1/dx/dx\n\n#             L[u[j,i],u[j+1,i]] =    1/dy/dy\n            L[v[j,i],v[j,i]] +=     -2/dy/dy\n            L[v[j,i],v[j-1,i]] =    1/dy/dy\n\n        end\n    end\nend\n\n    return L\nend\n\nfunction bclap(velovec,u_up,u_bottom,u_left,u_right,v_up,v_bottom,v_left,v_right,p,u,v,nx,ny,dx,dy)\n\n    cuti = (nx-1)*ny\n\n    bcL = spzeros(length(velovec))\n\n    bcL_u_left = deepcopy(u_left)\n    bcL_u_right = deepcopy(u_right)\n\n    bcL_v_up = deepcopy(v_up)\n    bcL_v_bottom = deepcopy(v_bottom)\n\n    bcL_u_up = deepcopy(u_up)\n    bcL_u_bottom = deepcopy(u_bottom)\n    bcL_v_left = deepcopy(v_left)\n    bcL_v_right = deepcopy(v_right)\n\n#     # extrapolation\n#     for i = 1:length(bcL_u_up)\n#         bcL_u_up[i] = 2*u_up[i] - velovec[u[end,i]]\n#         bcL_u_bottom[i] = 2*u_bottom[i] - velovec[u[1,i]]\n#     end\n\n#     for j = 1:length(bcL_v_left)\n#         bcL_v_left[j] = 2*v_left[j] - velovec[v[j,1]]\n#         bcL_v_right[j] = 2*v_right[j] - velovec[v[j,end]]\n#     end\n\n    # u B.C.\n    for i = 1:length(bcL_u_up)\n\n        bcL[u[end,i]] += bcL_u_up[i]*2   /dy/dy\n        bcL[u[1,i]]   += bcL_u_bottom[i]    *(2)/dy/dy\n\n    end\n\n    for j = 1:length(bcL_u_left)\n\n        bcL[u[j,end]] += bcL_u_right[j]*1   /dx/dx\n        bcL[u[j,1]]   += bcL_u_left[j]    *(1)/dx/dx\n\n    end\n\n    # v B.C.\n    for i = 1:length(bcL_v_up)\n\n        bcL[v[end,i]] += bcL_v_up[i]*1   /dy/dy\n        bcL[v[1,i]]   += bcL_v_bottom[i]    *(1)/dy/dy\n\n    end\n\n    for j = 1:length(bcL_v_left)\n\n        bcL[v[j,end]] += bcL_v_right[j]*2   /dx/dx\n        bcL[v[j,1]]   += bcL_v_left[j]    *(2)/dx/dx\n\n    end\n\n    return bcL\nend\n\nfunction bcdiv(Dbc_up,Dbc_bottom,Dbc_left,Dbc_right,pvec,p,uy,vx,dx,dy)\n\n    Dbc = spzeros(length(pvec))\n\n\n    for j = 1:length(uy)\n\n        Dbc[p[j,end]] += Dbc_right[j]*1   /dx\n        Dbc[p[j,1]]   += Dbc_left[j]    *(-1)/dx\n\n    end\n\n    for i = 1:length(vx)\n\n        Dbc[p[end,i]] += Dbc_up[i]*1   /dy\n        Dbc[p[1,i]]   += Dbc_bottom[i]    *(-1)/dy\n\n    end\n\n    return deepcopy(Dbc)\nend\n\nfunction adv(velovec,bcu_up,bcu_bottom,bcu_left,bcu_right,bcv_up,bcv_bottom,bcv_left,bcv_right,p,u,v,nx,ny,dx,dy)\n    q = deepcopy(0*velovec)\n\n\n    for i = 1:nx-1\n        for j = 1:ny\n\n            if i != 1 && j != 1 && i != nx-1 && j != ny\n\n            u_right = 0.5*(velovec[u[j,i]] + velovec[u[j,i+1]])\n            u_left  = 0.5*(velovec[u[j,i-1]] + velovec[u[j,i]])\n\n            u_up     = 0.5*(velovec[u[j,i]] + velovec[u[j+1,i]])\n            u_bottom = 0.5*(velovec[u[j-1,i]] + velovec[u[j,i]])\n            v_up     = 0.5*(velovec[v[j,i]] + velovec[v[j,i+1]])\n            v_bottom = 0.5*(velovec[v[j-1,i]] + velovec[v[j-1,i+1]])\n\n\n            q[u[j,i]] = (u_right*u_right - u_left*u_left)/dx + (u_up*v_up - u_bottom*v_bottom)/dy\n\n            end\n\n    if i == 1 && j != 1 && j != ny\n\n\n            u_right = 0.5*(velovec[u[j,i]] + velovec[u[j,i+1]])\n            u_left  = 0.5*(bcu_left[j] + velovec[u[j,i]])\n\n            u_up     = 0.5*(velovec[u[j,i]] + velovec[u[j+1,i]])\n            u_bottom = 0.5*(velovec[u[j-1,i]] + velovec[u[j,i]])\n            v_up     = 0.5*(velovec[v[j,i]] + velovec[v[j,i+1]])\n            v_bottom = 0.5*(velovec[v[j-1,i]] + velovec[v[j-1,i+1]])\n\n\n            q[u[j,i]] = (u_right*u_right - u_left*u_left)/dx + (u_up*v_up - u_bottom*v_bottom)/dy\n\n    end\n\n    if i == nx-1 && j != 1 && j != ny\n\n\n            u_right = 0.5*(velovec[u[j,i]] + bcu_right[j])\n            u_left  = 0.5*(velovec[u[j,i-1]] + velovec[u[j,i]])\n\n            u_up     = 0.5*(velovec[u[j,i]] + velovec[u[j+1,i]])\n            u_bottom = 0.5*(velovec[u[j-1,i]] + velovec[u[j,i]])\n            v_up     = 0.5*(velovec[v[j,i]] + velovec[v[j,i+1]])\n            v_bottom = 0.5*(velovec[v[j-1,i]] + velovec[v[j-1,i+1]])\n\n\n            q[u[j,i]] = (u_right*u_right - u_left*u_left)/dx + (u_up*v_up - u_bottom*v_bottom)/dy\n\n    end\n\n        if j == 1 && i != 1 && i != nx-1\n\n\n            u_right = 0.5*(velovec[u[j,i]] + velovec[u[j,i+1]])\n            u_left  = 0.5*(velovec[u[j,i-1]] + velovec[u[j,i]])\n\n            u_up     = 0.5*(velovec[u[j,i]] + velovec[u[j+1,i]])\n            u_bottom = bcu_bottom[i]\n            v_up     = 0.5*(velovec[v[j,i]] + velovec[v[j,i+1]])\n            v_bottom = 0.5*(bcv_bottom[i] + bcv_bottom[i+1])\n\n\n            q[u[j,i]] = (u_right*u_right - u_left*u_left)/dx + (u_up*v_up - u_bottom*v_bottom)/dy\n\n        end\n\n            if j == ny && i != 1 && i != nx-1\n\n\n            u_right = 0.5*(velovec[u[j,i]] + velovec[u[j,i+1]])\n            u_left  = 0.5*(velovec[u[j,i-1]] + velovec[u[j,i]])\n\n            u_up     = bcu_up[i]\n            u_bottom = 0.5*(velovec[u[j-1,i]] + velovec[u[j,i]])\n            v_up     = 0.5*(bcv_up[i] + bcv_up[i+1])\n            v_bottom = 0.5*(velovec[v[j-1,i]] + velovec[v[j-1,i+1]])\n\n\n            q[u[j,i]] = (u_right*u_right - u_left*u_left)/dx + (u_up*v_up - u_bottom*v_bottom)/dy\n\n        end\n\n            # four corners\n            if j == 1 && i == 1\n\n\n            u_right = 0.5*(velovec[u[j,i]] + velovec[u[j,i+1]])\n            u_left  = 0.5*(bcu_left[j] + velovec[u[j,i]])\n\n            u_up     = 0.5*(velovec[u[j,i]] + velovec[u[j+1,i]])\n            u_bottom = bcu_bottom[i]\n            v_up     = 0.5*(velovec[v[j,i]] + velovec[v[j,i+1]])\n            v_bottom = 0.5*(bcv_bottom[i] + bcv_bottom[i+1])\n\n\n            q[u[j,i]] = (u_right*u_right - u_left*u_left)/dx + (u_up*v_up - u_bottom*v_bottom)/dy\n\n            end\n\n            if j == 1 && i == nx-1\n\n            u_right = 0.5*(velovec[u[j,i]] + bcu_right[j])\n            u_left  = 0.5*(velovec[u[j,i-1]] + velovec[u[j,i]])\n\n            u_up     = 0.5*(velovec[u[j,i]] + velovec[u[j+1,i]])\n            u_bottom = bcu_bottom[i]\n            v_up     = 0.5*(velovec[v[j,i]] + velovec[v[j,i+1]])\n            v_bottom = 0.5*(bcv_bottom[i] + bcv_bottom[i+1])\n\n\n            q[u[j,i]] = (u_right*u_right - u_left*u_left)/dx + (u_up*v_up - u_bottom*v_bottom)/dy\n\n            end\n\n            if j == ny && i == 1\n\n            u_right = 0.5*(velovec[u[j,i]] + velovec[u[j,i+1]])\n            u_left  = 0.5*(bcu_left[j] + velovec[u[j,i]])\n\n            u_up     = bcu_up[i]\n            u_bottom = 0.5*(velovec[u[j-1,i]] + velovec[u[j,i]])\n            v_up     = 0.5*(bcv_up[i] + bcv_up[i+1])\n            v_bottom = 0.5*(velovec[v[j-1,i]] + velovec[v[j-1,i+1]])\n\n\n            q[u[j,i]] = (u_right*u_right - u_left*u_left)/dx + (u_up*v_up - u_bottom*v_bottom)/dy\n\n            end\n\n            if j == ny && i == nx-1\n\n            u_right = 0.5*(velovec[u[j,i]] + bcu_right[j])\n            u_left  = 0.5*(velovec[u[j,i-1]] + velovec[u[j,i]])\n\n            u_up     = bcu_up[i]\n            u_bottom = 0.5*(velovec[u[j-1,i]] + velovec[u[j,i]])\n            v_up     = 0.5*(bcv_up[i] + bcv_up[i+1])\n            v_bottom = 0.5*(velovec[v[j-1,i]] + velovec[v[j-1,i+1]])\n\n\n            q[u[j,i]] = (u_right*u_right - u_left*u_left)/dx + (u_up*v_up - u_bottom*v_bottom)/dy\n\n            end\n\n    end\nend\n\n\n    for i = 1:nx\n        for j = 1:ny-1\n\n\n            if i != 1 && j != 1 && i != nx && j != ny-1\n\n                v_up     = 0.5*(velovec[v[j,i]] + velovec[v[j+1,i]])\n                v_bottom = 0.5*(velovec[v[j,i]] + velovec[v[j-1,i]])\n\n                v_right     = 0.5*(velovec[v[j,i]] + velovec[v[j,i+1]])\n                v_left      = 0.5*(velovec[v[j,i]] + velovec[v[j,i-1]])\n                u_right     = 0.5*(velovec[u[j,i]] + velovec[u[j+1,i]])\n                u_left      = 0.5*(velovec[u[j,i-1]] + velovec[u[j+1,i-1]])\n\n            q[v[j,i]] = (u_right*v_right - u_left*v_left)/dx + (v_up*v_up - v_bottom*v_bottom)/dy\n\n\n            end\n\n\n            if i == 1 && j != 1 && j != ny-1\n\n\n                v_up     = 0.5*(velovec[v[j,i]] + velovec[v[j+1,i]])\n                v_bottom = 0.5*(velovec[v[j,i]] + velovec[v[j-1,i]])\n\n                v_right     = 0.5*(velovec[v[j,i]] + velovec[v[j,i+1]])\n                v_left      = bcv_left[j]\n                u_right     = 0.5*(velovec[u[j,i]] + velovec[u[j+1,i]])\n                u_left      = 0.5*(bcu_left[j] + bcu_left[j+1])\n\n\n            q[v[j,i]] = (u_right*v_right - u_left*v_left)/dx + (v_up*v_up - v_bottom*v_bottom)/dy\n\n            end\n\n    if i == nx && j != 1 && j != ny-1\n\n\n                v_up     = 0.5*(velovec[v[j,i]] + velovec[v[j+1,i]])\n                v_bottom = 0.5*(velovec[v[j,i]] + velovec[v[j-1,i]])\n\n                v_right     = bcv_right[j]\n                v_left      = 0.5*(velovec[v[j,i]] + velovec[v[j,i-1]])\n                u_right     = 0.5*(bcu_right[j] + bcu_right[j+1])\n                u_left      = 0.5*(velovec[u[j,i-1]] + velovec[u[j+1,i-1]])\n\n            q[v[j,i]] = (u_right*v_right - u_left*v_left)/dx + (v_up*v_up - v_bottom*v_bottom)/dy\n\n    end\n\n        if j == 1 && i != 1 && i != nx\n\n\n                v_up     = 0.5*(velovec[v[j,i]] + velovec[v[j+1,i]])\n                v_bottom = 0.5*(velovec[v[j,i]] + bcv_bottom[i])\n\n                v_right     = 0.5*(velovec[v[j,i]] + velovec[v[j,i+1]])\n                v_left      = 0.5*(velovec[v[j,i]] + velovec[v[j,i-1]])\n                u_right     = 0.5*(velovec[u[j,i]] + velovec[u[j+1,i]])\n                u_left      = 0.5*(velovec[u[j,i-1]] + velovec[u[j+1,i-1]])\n\n            q[v[j,i]] = (u_right*v_right - u_left*v_left)/dx + (v_up*v_up - v_bottom*v_bottom)/dy\n\n        end\n\n            if j == ny-1 && i != 1 && i != nx\n\n\n                v_up     =  0.5*(velovec[v[j,i]] + bcv_up[i])\n                v_bottom = 0.5*(velovec[v[j,i]] + velovec[v[j-1,i]])\n\n                v_right     = 0.5*(velovec[v[j,i]] + velovec[v[j,i+1]])\n                v_left      = 0.5*(velovec[v[j,i]] + velovec[v[j,i-1]])\n                u_right     = 0.5*(velovec[u[j,i]] + velovec[u[j+1,i]])\n                u_left      = 0.5*(velovec[u[j,i-1]] + velovec[u[j+1,i-1]])\n\n            q[v[j,i]] = (u_right*v_right - u_left*v_left)/dx + (v_up*v_up - v_bottom*v_bottom)/dy\n\n        end\n\n        # four corners\n\n            if i == 1 && j == 1\n\n\n                v_up     = 0.5*(velovec[v[j,i]] + velovec[v[j+1,i]])\n                v_bottom = 0.5*(velovec[v[j,i]] + bcv_bottom[i])\n\n                v_right     = 0.5*(velovec[v[j,i]] + velovec[v[j,i+1]])\n                v_left      = bcv_left[j]\n                u_right     = 0.5*(velovec[u[j,i]] + velovec[u[j+1,i]])\n                u_left      = 0.5*(bcu_left[j] + bcu_left[j+1])\n\n\n            q[v[j,i]] = (u_right*v_right - u_left*v_left)/dx + (v_up*v_up - v_bottom*v_bottom)/dy\n\n            end\n\n            if i == 1 && j == ny-1\n\n\n                v_up     =  0.5*(velovec[v[j,i]] + bcv_up[i])\n                v_bottom = 0.5*(velovec[v[j,i]] + velovec[v[j-1,i]])\n\n                v_right     = 0.5*(velovec[v[j,i]] + velovec[v[j,i+1]])\n                v_left      = bcv_left[j]\n                u_right     = 0.5*(velovec[u[j,i]] + velovec[u[j+1,i]])\n                u_left      = 0.5*(bcu_left[j] + bcu_left[j+1])\n\n\n            q[v[j,i]] = (u_right*v_right - u_left*v_left)/dx + (v_up*v_up - v_bottom*v_bottom)/dy\n\n            end\n\n            if i == nx && j == 1\n\n\n                v_up     = 0.5*(velovec[v[j,i]] + velovec[v[j+1,i]])\n                v_bottom = 0.5*(velovec[v[j,i]] + bcv_bottom[i])\n\n                v_right     = bcv_right[j]\n                v_left      = 0.5*(velovec[v[j,i]] + velovec[v[j,i-1]])\n                u_right     = 0.5*(bcu_right[j] + bcu_right[j+1])\n                u_left      = 0.5*(velovec[u[j,i-1]] + velovec[u[j+1,i-1]])\n\n\n            q[v[j,i]] = (u_right*v_right - u_left*v_left)/dx + (v_up*v_up - v_bottom*v_bottom)/dy\n\n            end\n\n            if i == nx && j == ny-1\n\n\n                v_up     =  0.5*(velovec[v[j,i]] + bcv_up[i])\n                v_bottom = 0.5*(velovec[v[j,i]] + velovec[v[j-1,i]])\n\n                v_right     = bcv_right[j]\n                v_left      = 0.5*(velovec[v[j,i]] + velovec[v[j,i-1]])\n                u_right     = 0.5*(bcu_right[j] + bcu_right[j+1])\n                u_left      = 0.5*(velovec[u[j,i-1]] + velovec[u[j+1,i-1]])\n\n\n            q[v[j,i]] = (u_right*v_right - u_left*v_left)/dx + (v_up*v_up - v_bottom*v_bottom)/dy\n\n            end\n\n        end\n    end\n\n\n    return -q\nend\n\nfunction cgsolv(A,b,x,imax,ϵ)\n    i=0\n    r=b-A*x\n    d=deepcopy(r)\n    δnew = r'*r\n\n    # added by myself\n    r0 = b\n    δ0 = r0'*r0\n\n    while i<imax && δnew > ϵ^2 * δ0\n        q = A*d\n        α = δnew/(d'*q)\n        x = x + α*d\n        if mod(i,50) == 0\n            r=b-A*x\n        else\n            r=r-α*q\n        end\n\n        δold = deepcopy(δnew)\n        δnew = r'*r\n        β = δnew/δold\n        d = r + β*d\n\n        i+=1\n    end\n\n    x = x .- x[1]\n\n    return i,x\nend\n\n\nend\n", "meta": {"hexsha": "2b24e134809e47f2fbe3cfb99ba3fd444fe5e842", "size": 18950, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "midterm/Operators.jl", "max_stars_repo_name": "liyuxuan48/MAE250H", "max_stars_repo_head_hexsha": "7ea98451772ee8a199ba9f5ac0c01a1b9e256c30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "midterm/Operators.jl", "max_issues_repo_name": "liyuxuan48/MAE250H", "max_issues_repo_head_hexsha": "7ea98451772ee8a199ba9f5ac0c01a1b9e256c30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "midterm/Operators.jl", "max_forks_repo_name": "liyuxuan48/MAE250H", "max_forks_repo_head_hexsha": "7ea98451772ee8a199ba9f5ac0c01a1b9e256c30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4637681159, "max_line_length": 113, "alphanum_fraction": 0.4001055409, "num_tokens": 7421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828602, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7645929019552642}}
{"text": "export R_coeff, Q_coeff, impedanceM1\r\ninclude(\"constant.jl\")\r\n#using .constant\r\n\r\n# plan-wave reflection coefficient\r\n\"\"\"\r\n\r\n    R_coeff(Zc)\r\n\r\nCalculate plan-wave reflection coefficient\r\n\r\n# Arguments\r\n- `Zc`: complex number, ground characteristic impedance\r\n\r\n# Output\r\n- `𝛹`: deg, grazing angle\r\n- `R_mag`: coefficient magnitude\r\n- `R_phase`: deg, phase\r\n\r\n# Example\r\n```julia-repl\r\njulia> Zc = 10 + 10im\r\njulia> 𝛹, R_mag, R_phase = R_coeff(Zc)\r\n```\r\n\r\n\"\"\"\r\nfunction R_coeff(Zc;len::Int64=1000)\r\n    𝛹 = range(0.0,π/2, length = len)\r\n    R_coeff = ( sin.(𝛹) .- 1/Zc ) ./ ( sin.(𝛹) .+ 1/Zc )\r\n    THETA = Float32.(𝛹*180/π)\r\n    RMAG = Float32.(abs.(R_coeff))\r\n    RPHASE = Float32.(angle.(R_coeff)*180/π)\r\n    return THETA, RMAG, RPHASE\r\nend\r\n\r\n\r\n#@btime R_coeff(Zc)\r\n#𝛹, R_mag, R_phase =   R_coeff(Zc)\r\n#plot(𝛹,R_phase)\r\n\r\n# spherical-wave reflection coefficient\r\n\"\"\"\r\n\r\n\r\n    Q_coeff(Zc,R2,f)\r\n\r\nCalculate spherical-wave reflection coefficient\r\n\r\n# Arguments:\r\n\r\n- `Zc`: complex number, characteristic impedance\r\n- `R2`: m, length of reflection ray path\r\n- `f`: Hz, frequency\r\n\r\n# Outputs:\r\n- `𝛹`: deg, grazing angle\r\n- `Q_mag`: coefficient magnitude\r\n- `Q_phase`: deg, phase\r\n\r\n# Example:\r\n```julia-repl\r\njulia> Zc = 10 + 10im\r\njulia> 𝛹, Q_mag, Q_phase = R_coeff(Zc)\r\n```\r\n\r\n\"\"\"\r\nfunction Q_coeff(Zc,R2,f,len=100)\r\n    λ = c0/f\r\n    k = 2*π/λ\r\n    𝛹 = range(0,π/2, length = len)\r\n\r\n    Q_coeff = randn(ComplexF64, (length(𝛹), 1))\r\n    for i=1:length(𝛹)\r\n        d = sqrt(1im*k*R2/2) * (1/Zc + sin(𝛹[i]))\r\n        Fd = 1 + 1im*sqrt(π)*d*erfcx(-1im*(d))\r\n        Q_coeff[i] = (Zc*sin(𝛹[i]) - 1 + 2*Fd) / (Zc*sin(𝛹[i]) + 1)\r\n    end\r\n\r\n    return Float32.(𝛹*180/π), Float32.(abs.(Q_coeff[:,1])), Float32.(angle.(Q_coeff[:,1])*180/π)\r\n\r\nend\r\n", "meta": {"hexsha": "e8d6cc60e688b096adb2aaf47670e5c00356258d", "size": 1743, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/impcoeff.jl", "max_stars_repo_name": "ducphucnguyen/FreeRay.jl", "max_stars_repo_head_hexsha": "f6138cce8c33b833529af8d5b4fe7f5013f600b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-02T01:13:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T04:32:39.000Z", "max_issues_repo_path": "src/impcoeff.jl", "max_issues_repo_name": "ducphucnguyen/FreeRay.jl", "max_issues_repo_head_hexsha": "f6138cce8c33b833529af8d5b4fe7f5013f600b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/impcoeff.jl", "max_forks_repo_name": "ducphucnguyen/FreeRay.jl", "max_forks_repo_head_hexsha": "f6138cce8c33b833529af8d5b4fe7f5013f600b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.256097561, "max_line_length": 97, "alphanum_fraction": 0.5960986804, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7645757388345934}}
{"text": "\"\"\"\n    detrend(signal::Vector{<:Real}; p::Int = 1, coefs::Union{Vector{<:Real}, Nothing, Real} = nothing, return_coefs::Bool = false)\n\nDetrend a signal by removing polynomial trend of order p using build in least squares.\nChoose p = 0 to remove only mean or input coefficients from previous detrending to detrend by those.\n\n# Args:\n\n*   signal::Vector: Data Vector containing te signal\n*   p::Int: order of polynomial\n*   coefs::Union{Vector{<:Real}, Nothing, Real}: Coefficients to do the same detrending on different signal\n*   return_coefs::Bool: if true returns coefficients detrended by\n\n# Return:\n\n* newSignal: The detrended sigal\n\n    Or if return_coefs = true:\n\n* (newSignal, coefs): The detrended signal and the estimated coefficients from order 0 to  p\n\n# Examples\n\n```julia\njulia> signal = sin.([1:100;]) + 0.03 .* [1:100;]\njulia> detrend(signal)\nVector{Float}\n```\n\n\"\"\"\nfunction detrend(signal::Vector{<:Real}; p::Int = 1, coefs::Union{Vector{<:Real}, Nothing, Real} = nothing, return_coefs::Bool = false)\n    p >= 0 || throw(DomainError(\"Order p hast to be positive or zero, is: $p\"))\n    # Build up regression matrix x\n    x = ones(length(signal))\n    xt = cumsum(x)\n    for i in 1:p\n      x = hcat(x, xt .^ i)\n    end\n    # If no coefs given estimate them\n    if coefs === nothing\n        coefs = x \\ signal\n    else\n        length(coefs) == p+1 || throw(DomainError(\"p is $p, but length of coefs is $(length(coefs))\"))\n    end        \n    trend = x * coefs\n    \n    if return_coefs\n        return (signal .- trend), coefs\n    else\n        return signal .- trend\n    end\nend\n\n\"\"\"\n    theilSenEstimator(x, y)\n\nCalculate the Teil Sen Estimator (median of all slopes m = (yⱼ - yᵢ)/(xⱼ - xᵢ )). Stable up to ~27% outliers\n\n# Args:\n\n* 'x::Vector': Data Vector containing x values\n* 'y::Vector': Data Vector containing y values\n\n# Return:\n\n* '(m, b)::Tuple': m represents slope, b the intersect\n\n# Examples\n\n```julia\njulia> theilSenEstimator(1:10, 1:10)\n(1.0,0.0)\n```\n\n\"\"\"\nfunction theilSenEstimator(x::Vector{<:Real}, y::Vector{<:Real})\n    len = length(y)\n    len == length(x) || throw(DomainError(\"Input Vectors have to be of same length\"))   \n    indices = 1:len\n    m = Vector{Float64}(undef, len - 1)\n    for ii = 1:len-1\n        indices = mod.(indices, len) .+ 1\n        m[ii] = median((y - y[indices]) ./ (x - x[indices]))\n    end\n    m = median(m)\n    b = median(y .- m*x)\n    return (m, b)\nend\n\n\"\"\"\n    arDecomposition(x::AbstractVector, p::Union{Int, UnitRange{Int}}; nfreq::Int = 124, sf::Real = 1, verbose::Bool = false)\n\nPerform a decomosition of the AR spectrum of signal `x` with order `p`. Returns the complex spectra associated to each AR-pole (nfreq x p) and the respectie center frequencies (p) and a frequency vector (nfreq)\n\n# Arguments\n\n* x: Signal to be decomposed\n* p: order of the AR process, if a UnitRange is given, the optimal order will be chosen through AIC\n\n# Keywords\n\n* nfreq: resolution of the analysed spectra, defaults to 256\n* sf: sampling frequency in Hz, defaults to 1\n* verbose: print some information oder selection, defaults to false\n\"\"\"\nfunction arDecomposition(x::AbstractVector, p::Union{Int, UnitRange{Int}}; nfreq::Int = 124, sf::Real = 1, verbose::Bool = false)\n    minimum(p) > 0 || throw(DomainError(\"Order p has to be positive\"))\n    if typeof(p) != Int \n        aicValues = map(order-> length(x) * log(lpc(x, order)[2]) + 2order, p)\n        p = p[findmin(aicValues)[2]]      \n        verbose && @info \"Order was choosen as p: $p by AIC\" \n    end\n\n    # estimate AR coefs\n    arcoefs, γ = lpc(x, p)\n    arPoly = Polynomial(reverse([1; arcoefs]))\n    poles = Polynomials.roots(arPoly)\n\n\n    z2f(z) = abs(real((2π*im)^-1 * log(z)))\n    centerFrequencies = z2f.(poles) .* sf\n\n    f = range(0, 0.5, length = nfreq)\n    f2z(f) = exp(2π*im * f)\n    z = f2z.(f)\n\n    S = zeros(Complex, length(f), p)\n    γk(k) = 2γ / (poles[k] * prod(poles[k] .- poles[1:end .!= k]) * prod(poles[k]^-1 .- poles)) \n    for k in 1:p\n        Sk(z) = ((γk(k) * poles[k]) / (z^-1 - poles[k]) + γk(k) + (γk(k) * poles[k]) / (z - poles[k])) \n        S[:, k] = Sk.(z)\n    end\n\n    return S, centerFrequencies, f .* sf\nend\n\n\"\"\"\n    getSpectralComponent(S::AbstractMatrix, centerFrequencies::AbstractVector, frange::Tuple{<:Real, <:Real} = (0.0, Inf))\n\nExtract the spectral components of a decomposed AR spectrum `S`, where the center frequencies fall in `frange`. See also `arDecomposition`.\n\n\"\"\"\nfunction getSpectralComponent(S::AbstractMatrix, centerFrequencies::AbstractVector, frange::Tuple{<:Real, <:Real} = (0.0, Inf))\n    frange[1] < frange[2] || throw(DomainError(\"fmin needs to be < fmax\"))\n    return vec(sum((real.(S[:, findall(f -> frange[1] <= f <= frange[2], centerFrequencies)])), dims = 2))\nend", "meta": {"hexsha": "973ab4edc211ae10c7ac55ab120008db26ec95c7", "size": 4738, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Utilities/util.jl", "max_stars_repo_name": "mapi1/Cardio.jl", "max_stars_repo_head_hexsha": "91afd96217c29c2486914d72b15627a663f7c1d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-24T19:32:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-24T19:32:09.000Z", "max_issues_repo_path": "src/Utilities/util.jl", "max_issues_repo_name": "mapi1/Cardio.jl", "max_issues_repo_head_hexsha": "91afd96217c29c2486914d72b15627a663f7c1d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utilities/util.jl", "max_forks_repo_name": "mapi1/Cardio.jl", "max_forks_repo_head_hexsha": "91afd96217c29c2486914d72b15627a663f7c1d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-17T13:22:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T13:22:45.000Z", "avg_line_length": 32.4520547945, "max_line_length": 210, "alphanum_fraction": 0.6361333896, "num_tokens": 1491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7645757335244576}}
{"text": "using QuasiGeostrophy, Plots, FFTW, BenchmarkTools\nusing LinearAlgebra\nimport Plots: plot\nimport QuasiGeostrophy: compute\n\n\n##\nΩxy = S¹(0,2π) × S¹(0,2π)\nNx = 2^8; Ny = 2^8;\nfourier_grid = create_grid((Nx, Ny), Ωxy)\nx, y = fourier_grid.grid\nfourier_transform = Transform(fourier_grid)\n\nnames = (\"ϕ1\", \"ϕ2\", \"ϕ3\", \"ϕ4\")\ncreate_fields(names = names, \n              grid = fourier_grid,\n              transform = fourier_transform)\nf1 = @. sin(x) + 0im * y\nf2 = @. sin(y) + 0im * x\nf3 = @. sin(x) * sin(y) # product\nf4 = @. sin(x) + sin(y) # sum\nf1 = fourier_transform.forward * f1\nf2 = fourier_transform.forward * f2\nf3 = fourier_transform.forward * f3\nf4 = fourier_transform.forward * f4\nϕ1.data .= f1\nϕ2.data .= f2\nϕ3.data .= f3\nϕ4.data .= f4\n## Check Algebra\nnorm((ϕ1 * ϕ2 - ϕ3).data)/norm((ϕ3).data)\n\nf_ϕ1 = Field(ϕ1, BasicMetaData(\"ϕ1\"))\nf_ϕ2 = Field(ϕ2, BasicMetaData(\"ϕ2\"))\ntt =  2 * f_ϕ1 + f_ϕ2 * f_ϕ1 + 2 + tanh(f_ϕ1) + 2*2\ncompute(a::FourierField) = a\ncompute(tt)\nevaluate(tt)\n\n## Check Calculus\nkx, ky = fourier_grid.wavenumbers\n∂x = FourierOperator(im .* kx, FourierOperatorMetaData(\"∂x\"))\n∂y = FourierOperator(im .* ky, FourierOperatorMetaData(\"∂y\"))\n\n∂x(ϕ)\n\n∂x(ϕ) + 1 + (∂x^2 + ∂y^2)(ϕ)\n##\ndmd = DerivativeMetaData(FourierOperator(im .* kx, FourierOperatorMetaData(\"∂x\")), \"x\")\n∂x = Operator(nothing, dmd)\n∂x(f_ϕ1)\ndmd = DerivativeMetaData(FourierOperator(im .* ky, FourierOperatorMetaData(\"∂y\")), \"y\")\n∂y = Operator(nothing, dmd)\n∂ʸϕ1 = ∂y(f_ϕ2) * ∂x(f_ϕ1)\nevaluate(∂ʸϕ1)\ntmp = compute(∂ʸϕ1)\np1 = plot(tmp)\n\n\na1 = compute(∂x)^2\na2 = compute(∂x^2)\nnorm(a1.op - a2.op)\n\nΔ1 = compute(∂x)^2 + compute(∂y)^2\nΔ2 = compute(∂x^2+∂y^2)\nnorm(Δ1.op - Δ2.op)\n", "meta": {"hexsha": "6e41aee42e3797f8360e997e085c12d3147dd00c", "size": 1659, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "trial_zone/fourier_fields.jl", "max_stars_repo_name": "upiterbarg/QuasiGeostrophy", "max_stars_repo_head_hexsha": "ba0be019c933916ffc379141c36e83adb10c1c59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-16T15:35:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-01T21:10:48.000Z", "max_issues_repo_path": "trial_zone/fourier_fields.jl", "max_issues_repo_name": "upiterbarg/QuasiGeostrophy", "max_issues_repo_head_hexsha": "ba0be019c933916ffc379141c36e83adb10c1c59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-19T13:39:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-19T13:39:29.000Z", "max_forks_repo_path": "trial_zone/fourier_fields.jl", "max_forks_repo_name": "upiterbarg/QuasiGeostrophy", "max_forks_repo_head_hexsha": "ba0be019c933916ffc379141c36e83adb10c1c59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-09T16:24:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-09T16:24:16.000Z", "avg_line_length": 24.7611940299, "max_line_length": 87, "alphanum_fraction": 0.6467751658, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7645757321452281}}
{"text": "\"\"\"\n    Hypergeometric(s, f, n)\n\nA *Hypergeometric distribution* describes the number of successes in `n` draws without replacement from a finite population containing `s` successes and `f` failures.\n\n```math\nP(X = k) = {{{s \\\\choose k} {f \\\\choose {n-k}}}\\\\over {s+f \\\\choose n}}, \\\\quad \\\\text{for } k = \\\\max(0, n - f), \\\\ldots, \\\\min(n, s).\n```\n\n```julia\nHypergeometric(s, f, n)  # Hypergeometric distribution for a population with\n                         # s successes and f failures, and a sequence of n trials.\n\nparams(d)       # Get the parameters, i.e. (s, f, n)\n```\n\nExternal links\n\n* [Hypergeometric distribution on Wikipedia](http://en.wikipedia.org/wiki/Hypergeometric_distribution)\n\n\"\"\"\nstruct Hypergeometric <: DiscreteUnivariateDistribution\n    ns::Int     # number of successes in population\n    nf::Int     # number of failures in population\n    n::Int      # sample size\n\n    function Hypergeometric(ns::Real, nf::Real, n::Real)\n        @check_args(Hypergeometric, ns >= zero(ns) && nf >= zero(nf))\n        @check_args(Hypergeometric, zero(n) <= n <= ns + nf)\n        new(ns, nf, n)\n    end\nend\n\n@distr_support Hypergeometric max(d.n - d.nf, 0) min(d.ns, d.n)\n\n\n### Parameters\n\nparams(d::Hypergeometric) = (d.ns, d.nf, d.n)\n\n\n### Statistics\n\nmean(d::Hypergeometric) = d.n * d.ns / (d.ns + d.nf)\n\nfunction var(d::Hypergeometric)\n    N = d.ns + d.nf\n    p = d.ns / N\n    d.n * p * (1.0 - p) * (N - d.n) / (N - 1.0)\nend\nmode(d::Hypergeometric) = floor(Int, (d.n + 1) * (d.ns + 1) / (d.ns + d.nf + 2))\n\nfunction modes(d::Hypergeometric)\n    if (d.ns == d.nf) && mod(d.n, 2) == 1\n        [(d.n-1)/2, (d.n+1)/2]\n    else\n        [mode(d)]\n    end\nend\n\nskewness(d::Hypergeometric) = (d.nf-d.ns)*sqrt(d.ns+d.nf-1)*(d.ns+d.nf-2*d.n)/sqrt(d.n*d.ns*d.nf*(d.ns+d.nf-d.n))/(d.ns+d.nf-2)\nfunction kurtosis(d::Hypergeometric)\n    N = d.ns + d.nf\n    a = (N-1) * N^2 * (N * (N+1) - 6*d.ns * (N-d.ns) - 6*d.n*(N-d.n)) + 6*d.n*d.ns*(d.nf)*(N-d.n)*(5*N-6)\n    b = (d.n*d.ns*(N-d.ns) * (N-d.n)*(N-2)*(N-3))\n    a/b\nend\n\n\n### Evaluation & Sampling\n\n@_delegate_statsfuns Hypergeometric hyper ns nf n\n\nrand(d::Hypergeometric) = convert(Int, StatsFuns.RFunctions.hyperrand(d.ns, d.nf, d.n))\n\nstruct RecursiveHypergeomProbEvaluator <: RecursiveProbabilityEvaluator\n    ns::Float64\n    nf::Float64\n    n::Float64\nend\n\nRecursiveHypergeomProbEvaluator(d::Hypergeometric) = RecursiveHypergeomProbEvaluator(d.ns, d.nf, d.n)\n\nnextpdf(s::RecursiveHypergeomProbEvaluator, p::Float64, x::Integer) =\n    ((s.ns - x + 1) / x) * ((s.n - x + 1) / (s.nf - s.n + x)) * p\n\nBase.broadcast!(::typeof(pdf), r::AbstractArray, d::Hypergeometric, rgn::UnitRange) =\n    _pdf!(r, d, rgn, RecursiveHypergeomProbEvaluator(d))\n\nfunction Base.broadcast(::typeof(pdf), d::Hypergeometric, X::UnitRange)\n    r = similar(Array{promote_type(partype(d), eltype(X))}, indices(X))\n    r .= pdf.(d,X)\nend\n", "meta": {"hexsha": "708ddbedc3caa065309147d48b3cbafa093f80bc", "size": 2863, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/discrete/hypergeometric.jl", "max_stars_repo_name": "ludkinm/Distributions.jl", "max_stars_repo_head_hexsha": "7ec5b512139e8fb0a46b7a283d42d95a7b540bd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/discrete/hypergeometric.jl", "max_issues_repo_name": "ludkinm/Distributions.jl", "max_issues_repo_head_hexsha": "7ec5b512139e8fb0a46b7a283d42d95a7b540bd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/discrete/hypergeometric.jl", "max_forks_repo_name": "ludkinm/Distributions.jl", "max_forks_repo_head_hexsha": "7ec5b512139e8fb0a46b7a283d42d95a7b540bd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4574468085, "max_line_length": 166, "alphanum_fraction": 0.6150890674, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7645757262144045}}
{"text": "using LinearAlgebra\nusing Plots\n\n# generate the data for the example\nfunction generateSamples(n, k, mu::Float64)\n  # generate theta\n  theta = rand(Float64, k)\n  @. theta = (theta -0.5) * 10\n  \n  # generate y with noise\n  y = Vector{Float64}(undef, n+k -1)\n  for j in 1:n\n    y[j] = 1 * (rand(Float64) -0.5)\n  end\n  for j in n+1:n+k-1\n    y[j] = 0\n  end\n  \n  # generate X, update y\n  supportPoints = rand(Float64, n)\n  @. supportPoints = (supportPoints - 0.5)\n  supportPoints = sort(supportPoints)\n  X = Matrix{Float64}(undef, k, n+k-1)\n  \n  for j in 1:n\n    X[1,j] = 1\n    y[j] = theta[1]\n    for i in 2:k\n      X[i,j] = X[i-1, j] * supportPoints[j]\n      y[j] += X[i,j] * theta[i]\n    end\n  end\n  \n  # identidy matrix multiplied with vector of weights, first row \n  for j in n+1:n+k-1\n    X[1,j] = 0\n    for i in 1:k\n      if (j - n + 1 == i) \n        X[i,j] = sqrt(mu * (j-n))\n      end\n    end\n  end\n  \n  return X, y, theta\nend\n\nfunction evalPolynomial(grid, coeff)\n  k = length(coeff)\n  len = length(grid)\n  f = zeros(Float64, len)\n  for i in 1:k\n    for j in 1:len\n      f[j] *= grid[j]\n      f[j] += coeff[k + 1 - i]\n    end\n  end\n  return f\nend\n\nfunction plotAll(X::Matrix{Float64}, y::Vector{Float64}, theta::Vector{Float64}, n, k)\n  x = Vector{Float64}(undef, n)\n  val = Vector{Float64}(undef, n)\n  for j in 1:n\n    x[j] = X[2,j]\n    val[j] = y[j]\n  end\n  plot(x, val ,label=\"\", seriestype=:scatter) #xlims=[x[1], x[n]]\n  \n  grid = collect(range(x[1], step=0.01, stop=x[n]))\n  f = evalPolynomial(grid, theta)\n  plot!(grid, f, label=\"theta\")\n  \n  theta2 = X' \\ y # solve in least squares sense\n  f2 = evalPolynomial(grid, theta2)\n  plot!(grid, f2, label=\"regression theta\")\nend\n\nfunction wrap(n, k, mu::Float64)\n  X, y, theta = generateSamples(n, k, mu)\n  plotAll(X, y, theta, n, k)\nend\n", "meta": {"hexsha": "4ae55e39ee0df423a4afb4a59c400eb14d44b991", "size": 1795, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/plot.jl", "max_stars_repo_name": "Mathemalsky/BenignOverfitting", "max_stars_repo_head_hexsha": "f3bd4f5d9455f4402440bd5abbc813c152aa866b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/plot.jl", "max_issues_repo_name": "Mathemalsky/BenignOverfitting", "max_issues_repo_head_hexsha": "f3bd4f5d9455f4402440bd5abbc813c152aa866b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/plot.jl", "max_forks_repo_name": "Mathemalsky/BenignOverfitting", "max_forks_repo_head_hexsha": "f3bd4f5d9455f4402440bd5abbc813c152aa866b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8902439024, "max_line_length": 86, "alphanum_fraction": 0.5816155989, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475794701961, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7645633188649861}}
{"text": "using SymEngine\nusing HCubature\nusing LinearAlgebra\n\nfunction L₂(X;x=symbols(\"x\"),y=symbols(\"y\"))\n    res=Matrix{SymEngine.Basic}(undef,3,size(X,2))\n    for i in 1:size(X,2)\n        res[1,i]=diff(X[1,i],x)\n        res[2,i]=diff(X[2,i],y)\n        res[3,i]=diff(X[1,i],y)+diff(X[2,i],x)\n    end\n    return res\nend\n\nx,y=symbols(\"x,y\")\nxᵢ=symbols(\"x₁ x₂ x₃\")\nyᵢ=symbols(\"y₁ y₂ y₃\")\n#T9G9\nA=symbols(\"A\")\n\n# aᵢ=[y[j]-y[m] for (j,m) in zip([2,3,1],[3,1,2])]\n# bᵢ=[y[j]-y[m] for (j,m) in zip([2,3,1],[3,1,2])]\n# cᵢ=[-x[j]+x[m] for (j,m) in zip([2,3,1],[3,1,2])]\naᵢ=symbols(\"a₁ a₂ a₃\")\nbᵢ=symbols(\"b₁ b₂ b₃\")\ncᵢ=symbols(\"c₁ c₂ c₃\")\nLᵢ=1/2/A .*(aᵢ .+bᵢ .*x .+cᵢ .*y)\nNᵤᵨᵢ=[0.5*Lᵢ[i]*(bᵢ[m]*Lᵢ[j]-bᵢ[j]*Lᵢ[m]) for (i,j,m) in zip([1,2,3],[2,3,1],[3,1,2])]\nNᵥᵨᵢ=[0.5*Lᵢ[i]*(cᵢ[m]*Lᵢ[j]-cᵢ[j]*Lᵢ[m]) for (i,j,m) in zip([1,2,3],[2,3,1],[3,1,2])]\n\nNᵢ=Array{Basic}(undef,2,9)\nfor i in 1:3\n    Nᵢ[:,3i-2:3i]=[Lᵢ[i] 0 Nᵤᵨᵢ[i];\n                   0 Lᵢ[i] Nᵥᵨᵢ[i]]\nend\nB=L₂(Nᵢ)\nD₀=E₀/(1-ν₀^2)\nD=D₀*[1 ν₀ 0;\n      ν₀ 1 0;\n      0  0 (1-ν₀)/2]\n\nK=transpose(B)*D*B\nopen(\"./k_GT9.jl\",\"w+\") do f\n    for i in 1:size(K,1)\n        for j in 1:size(K,2)\n            write(f,\"K[\"*string(i)*\",\"*string(j)*\"]=\"*string(K[i,j])*\"\\n\")\n        end\n    end\nend\n", "meta": {"hexsha": "5a6546773d9a94c31cf5b3a8e79ec0558e1ab963", "size": 1223, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/meta/GT9.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Mozi.jl-938b0b66-b18d-59c3-b436-87bb841ccf42", "max_stars_repo_head_hexsha": "392c31542dc2c8cc95ea87e06c258be2f4d0de37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/meta/GT9.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Mozi.jl-938b0b66-b18d-59c3-b436-87bb841ccf42", "max_issues_repo_head_hexsha": "392c31542dc2c8cc95ea87e06c258be2f4d0de37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/meta/GT9.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Mozi.jl-938b0b66-b18d-59c3-b436-87bb841ccf42", "max_forks_repo_head_hexsha": "392c31542dc2c8cc95ea87e06c258be2f4d0de37", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.46, "max_line_length": 86, "alphanum_fraction": 0.5102207686, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.8104789109591831, "lm_q1q2_score": 0.7645633175741173}}
{"text": "\"random number between a and b\"\nfunction randin(a::Real, b::Real)\n    -Inf < a ≤ b < Inf || DomainError()\n    a + (b - a) * rand()\nend\n\n\n\"\"\"\nWeighted random integer.\nGiven weights = (w1, w2, ...), returns a random integer i with probability proportional to w_i.\nThe weights should be 0 ≤ w_i < ∞, and do not need to sum to 1.\n\"\"\"\nfunction wrand(weights)\n    wr = rand() * sum(w for w in weights)\n    for (i,w) in enumerate(weights)\n        @assert 0 ≤ w < Inf\n        wr -= w\n        if wr ≤ 0\n            return i\n        end\n    end\nend\n\n\n\n\"\"\"\nReturns a random vector x = (x1, x2, ..., xn), such that\nxi ≥ 0 and sum(xi) = 1\n\"\"\"\nfunction randsimplex(n::Int) \n    # https://cs.stackexchange.com/questions/3227/uniform-sampling-from-a-simplex\n    @assert n > 0\n    diff(sort([0; rand(n - 1); 1]))\nend\n\n\n\"\"\"\nReturns a random vector x = x0 * v[0] + x1 * v[1] + ... + xn * v[n]\nwhere xi ≥ 0 and sum(xi) = 1\n\"\"\"\nfunction randsimplex(V::Vector{Vector{Float64}})\n    @assert allsame(length.(V))\n    X = randsimplex(length(V))\n    sum(x*v for (x,v) in zip(X,V))\nend\n", "meta": {"hexsha": "6c74a031701e3d6833b9f20a33e9243d4f9faeae", "size": 1058, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rand.jl", "max_stars_repo_name": "cossio/Utils.jl", "max_stars_repo_head_hexsha": "64342af48986ec78e3a7a622c6aee84ba98f6b1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rand.jl", "max_issues_repo_name": "cossio/Utils.jl", "max_issues_repo_head_hexsha": "64342af48986ec78e3a7a622c6aee84ba98f6b1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rand.jl", "max_forks_repo_name": "cossio/Utils.jl", "max_forks_repo_head_hexsha": "64342af48986ec78e3a7a622c6aee84ba98f6b1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0, "max_line_length": 95, "alphanum_fraction": 0.5850661626, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065792, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.7645633037738775}}
{"text": "#Implements Future Value calculation as per Excel\n#Type = 1 means payment at start of period\nfunction FV(Rate=0,Nper=0,Pmt=0,Pv=0,Type=0)\n    Fv = (-1*Pv*(1 + Rate)^Nper - Pmt*(1 + Rate*Type)*(((1 + Rate)^Nper - 1)/Rate))\n\tround(Fv, 2)\nend\n\n#######################################\n\n#Implements Present Value calculation as per Excel\n#Type = 1 means payment at start of period\nfunction PV(Rate=0,Nper=0,Pmt=0,Fv=0,Type=0)\n    Pv = (-1*Fv - Pmt*(1 + Rate*Type)*(((1 + Rate)^Nper - 1)/Rate))/(1 + Rate)^Nper\n\tround(Pv, 2)\nend\n\n#######################################\n\n#Implements Payment calculation as per Excel\n#Type = 1 means payment at start of period\nfunction PMT(Rate=0,Nper=0,Pv=0,Fv=0,Type=0)\n    Pmt = (-1*Fv - Pv*(1 + Rate)^Nper)/((1 + Rate*Type)*((1 + Rate)^Nper - 1)/Rate)\n\tround(Pmt, 2)\nend\n\n#######################################\n\n#Implements Effective Annual Rate calculation as per Excel\nfunction EFFECT(Nominal_rate,Npery)\n\tEffect = ((1 + Nominal_rate/Npery)^Npery - 1)\n\tround(Effect, 6)\nend\n\n#######################################\n\n#Implements Net Present Value calculation as per Excel\n#Add the option of adding inital payment\nfunction NPV(Rate,Cash_Flow,InitialPayment=0)\n\tnpv=0\n\tfor i in 1:length(Cash_Flow)\n\t\tnpv += Cash_Flow[i] / (1+Rate)^i\n\tend\n\tnpv += InitialPayment\n\tround(npv, 2)\nend\n\n#######################################\n\n#Implements Internal Rate of Return calculation as per Excel\nfunction IRR(Cash_Flow,Guess=0.1)\n\tconst limit=0.0000001\n\tinitial=Cash_Flow[1]\n\tvalues=Cash_Flow[2:length(Cash_Flow)]\n\t\n\trate=Guess*1.01\n\toldRate=Guess\n\t\n\twhile (abs((rate-oldRate)/rate) > limit)\n\t\tnewRate=rate-NPV(rate,values,initial)*((rate-oldRate)/(NPV(rate,values,initial)-NPV(oldRate,values,initial)))\n\t\toldRate=rate\n\t\trate=newRate\n\tend\n\t\n\tround(rate,6)\nend\n", "meta": {"hexsha": "32f02838d80e851e12ef8ce7c90898b705bfc473", "size": 1777, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Finance.jl", "max_stars_repo_name": "arnaudamiel/Finance", "max_stars_repo_head_hexsha": "7023a99a2d3947f0b929542a2fce70d95817dea0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-06-01T18:23:59.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-01T18:23:59.000Z", "max_issues_repo_path": "Finance.jl", "max_issues_repo_name": "arnaudamiel/Finance", "max_issues_repo_head_hexsha": "7023a99a2d3947f0b929542a2fce70d95817dea0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Finance.jl", "max_forks_repo_name": "arnaudamiel/Finance", "max_forks_repo_head_hexsha": "7023a99a2d3947f0b929542a2fce70d95817dea0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9242424242, "max_line_length": 111, "alphanum_fraction": 0.6240855374, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7645122616795347}}
{"text": "module HHChannels\n\nexport Stim, run_hh\n\nusing Sundials\nusing SIUnits.ShortUnits\n\nimmutable HHParam\n    c_m       # membrane spacific capacitance\n    gnabar    # Na channel cross-membrane conductivity\n    gkbar     # K channel cross-membrane conductivity\n    gl        # Leak conductivity\n    ena       # Na channel reversal potential\n    ek        # K channel reversal potential\n    el        # Leak reversal potential\n    q10       # temperature dependent rate coefficient\n              # (= 3^((T-T₀)/10K) with T₀ = 6.3 °C)\n\n    # constructor with default values, corresponding\n    # to a resting potential of -65 mV and temperature 6.3 °C\n    HHParam(;\n        # default values from HH paper\n\n        # For reversal potentials we use those computed using\n        # the Nernst equation with the following values:\n        #       R   8.3144598\n        #       F   96485.33289\n        #       nao 140   mM\n        #       nai  10   mM\n        #       ko    2.5 mM\n        #       ki   64.4 nM\n        # We don't use the default values for ena and ek taken\n        # from the HH paper:\n        #   ena    = 115.0mV + -65.0mV,\n        #   ek     = -12.0mV + -65.0mV,\n        ena    =  63.55148117386mV,\n        ek     = -74.17164678272mV,\n\n        c_m    = 0.01F*m^-2,\n        gnabar = .12S*cm^-2,\n        gkbar  = .036S*cm^-2,\n        gl     = .0003S*cm^-2,\n        el     = -54.3mV,\n        q10    = 1\n    ) = new(c_m, gnabar, gkbar, gl, ena, ek, el, q10)\n\nend\n\nimmutable Stim\n    t0        # start time of stimulus\n    t1        # stop time of stimulus\n    i_e       # stimulus current density\n\n    Stim() = new(0s, 0s, 0A/m^2)\n    Stim(t0, t1, i_e) = new(t0, t1, i_e)\nend\n\nvtrap(x,y) = x/(exp(x/y) - 1.0)\n\n# \"m\" sodium activation system\nfunction m_lims(v, q10)\n    alpha = .1mV^-1 * vtrap(-(v+40mV),10mV)\n    beta =  4 * exp(-(v+65mV)/18mV)\n    sum = alpha + beta\n    mtau = 1ms / (q10*sum)\n    minf = alpha/sum\n    return mtau, minf\nend\n\n# \"h\" sodium inactivation system\nfunction h_lims(v, q10)\n    alpha = 0.07*exp(-(v+65mV)/20mV)\n    beta = 1 / (exp(-(v+35mV)/10mV) + 1)\n    sum = alpha + beta\n    htau = 1ms / (q10*sum)\n    hinf = alpha/sum\n    return htau, hinf\nend\n\n# \"n\" potassium activation system\nfunction n_lims(v, q10)\n    alpha = .01mV^-1 * vtrap(-(v+55mV),10mV)\n    beta = .125*exp(-(v+65mV)/80mV)\n    sum = alpha + beta\n    ntau = 1ms / (q10*sum)\n    ninf = alpha/sum\n    return ntau, ninf\nend\n\n# Choose initial conditions for the system such that the gating variables\n# are at steady state for the user-specified voltage v\nfunction initial_conditions(v, q10)\n    mtau, minf = m_lims(v, q10)\n    htau, hinf = h_lims(v, q10)\n    ntau, ninf = n_lims(v, q10)\n\n    return (v, minf, hinf, ninf)\nend\n\n# Given time t and state (v, m, h, n),\n# return (vdot, mdot, hdot, ndot)\nfunction f(t, state; p=HHParam(), stim=Stim())\n    v, m, h, n = state\n\n    # calculate current density due to ion channels\n    gna = p.gnabar*m*m*m*h\n    gk = p.gkbar*n*n*n*n\n\n\n    ina = gna*(v - p.ena)\n    ik = gk*(v - p.ek)\n    il = p.gl*(v - p.el)\n\n    itot = ik + ina + il\n\n    # calculate current density due to stimulus\n    if t>=stim.t0 && t<stim.t1\n        itot -= stim.i_e\n    end\n        \n    # calculate the voltage dependent rates for the gating variables\n    mtau, minf = m_lims(v, p.q10)\n    htau, hinf = h_lims(v, p.q10)\n    ntau, ninf = n_lims(v, p.q10)\n\n    return (-itot/p.c_m, (minf-m)/mtau, (hinf-h)/htau, (ninf-n)/ntau)\nend\n\nfunction run_hh(t_end; v0=-65mV, stim=Stim(), param=HHParam(), sample_dt=0.01ms)\n    v_scale = 1V\n    t_scale = 1s\n\n    v0, m0, h0, n0 = initial_conditions(v0, param.q10)\n    y0 = [ v0/v_scale, m0, h0, n0 ]\n\n    samples = collect(0s: sample_dt: t_end)\n\n    fbis(t, y, ydot) = begin\n        vdot, mdot, hdot, ndot =\n            f(t*t_scale, (y[1]*v_scale, y[2], y[3], y[4]), stim=stim, p=param)\n\n        ydot[1], ydot[2], ydot[3], ydot[4] =\n            vdot*t_scale/v_scale, mdot*t_scale, hdot*t_scale, ndot*t_scale\n\n        return Sundials.CV_SUCCESS\n    end\n\n    # Ideally would run with vector absolute tolerance to account for v_scale,\n    # but this would prevent us using the nice cvode wrapper.\n\n    res = Sundials.cvode(fbis, y0, map(t->t/t_scale, samples), abstol=1e-6, reltol=5e-10)\n\n    # Use map here because of issues with type deduction with arrays and SIUnits.\n    return samples, map(v->v*v_scale, res[:, 1])\nend\n\nend # module HHChannels\n", "meta": {"hexsha": "910a402cb8201c8355723a77236045dbad1cf03f", "size": 4383, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "validation/ref/numeric/HHChannels.jl", "max_stars_repo_name": "kabicm/arbor", "max_stars_repo_head_hexsha": "cfab5fd6a2e6a211c097659c96dcc098ee806e68", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "validation/ref/numeric/HHChannels.jl", "max_issues_repo_name": "kabicm/arbor", "max_issues_repo_head_hexsha": "cfab5fd6a2e6a211c097659c96dcc098ee806e68", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "validation/ref/numeric/HHChannels.jl", "max_forks_repo_name": "kabicm/arbor", "max_forks_repo_head_hexsha": "cfab5fd6a2e6a211c097659c96dcc098ee806e68", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7405063291, "max_line_length": 89, "alphanum_fraction": 0.5836185261, "num_tokens": 1537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7645122616795346}}
{"text": "using LinearAlgebra: Diagonal\n\n# Loss function should return a pair of (e, ∂e/∂ŷ).\nexport\n    mse,\n    softmax, log_softmax,\n    logit_cross_entropy,\n    logit_binary_cross_entropy\n\n\n\"Mean squared error loss\"\n@inline mse(ŷ, y) = (0.5 * sum((y - ŷ) .^ 2), ŷ - y)\n\n#=====\n\n**Softmax** turns (multinomial) logit into probability:\n\n    softmax(x)_i = exp(x_i) / Σ exp(x_i)\n\n**Cross entropy** evaluates the expected coding length of data following distribution p when a wrong\ndistribution q is assumed:\n\n    H(p, q) = -E_p[log(q)]\n            = -Σ p log(q)\n            = H(p) + D_KL(p || q)\n            = -Σ p log(p) + Σ p log(p/q)\n\n**Binary cross entropy** is the special case of cross entropy for 2-class classification. It is\napplied on a single sigmoid output rather than a vector of size 2 as in the softmax case.\n\nTo mitigate numerical instabilities, computing by a composed function (prefixed with \"logit_\") is\nusually preferred:\n\n    logit_cross_entropy(ŷ, y) := cross_entropy(softmax(ŷ), y)\n    logit_binary_cross_entropy(ŷ, y) := binary_cross_entropy(logistic(ŷ), y)\n\nSoftmax is invariant under translation by the same value in each coordinate. The standard logistic\nfunction is a special case of softmax where one variable is fixed at 0.\n\n=====#\n\n\nfunction softmax(x::AbstractMatrix{Float64})::Matrix{Float64}\n    max_x = maximum(x, dims=1)\n    exp_x = exp.(x .- max_x)\n    exp_x ./ sum(exp_x, dims=1)\nend\n\nfunction log_softmax(x::AbstractMatrix{Float64})::Matrix{Float64}\n    x_ = x .- maximum(x, dims=1)\n    x_ .- log.(sum(exp.(x_), dims=1))\nend\n\n#=\n\nDerivation:\n\n    p_i = softmax(y)_i  ⟹\n    ∂p_i/∂y_j = [i = j] p_i - p_i p_j\n\n    ∂e/∂y_j = Σ_i ∂e/∂p_i ⋅ ∂p_i/∂y_j\n\nOr in the form of matrix calculus,\n\n    ∂e/∂y = ∂e/∂p ⋅ ∂p/∂y\n\nAnd\n\n    e = -sum(y .* log(p)) / n  ⟹\n    ∂e/∂p = -y / n * (1/p)\n\nAlso note that $∂p/∂y ∈ ℜ_{d × d}$, so if mini-batch is used it is impossible to be expressed in\nmatrix form. We directly write `∂e/∂p ⋅ ∂p/∂y` of one sample as\n\n      (∂e/∂p) ⋅ (diag(p) - p ⋅ p')\n    = ∇p .* p - sum(∇p .* p) * p    # a ℜ_d vector\n\nThe mini-batch case can be written as\n\n    ... = ∇p .* p - sum(∇p .* p, dims=1) .* p    # a ℜ_{d × n} matrix\n\n=#\nfunction logit_cross_entropy(\n    ŷ::AbstractMatrix{Float64},\n    y::AbstractMatrix{Float64},\n)::Tuple{Float64, Matrix{Float64}}\n    n_batches = size(ŷ, 2)\n    log_p = log_softmax(ŷ)\n    e = -sum(y .* log_p) / n_batches\n\n    p = softmax(ŷ)\n    ∇p = @. -y / n_batches * inv(p)\n    t = ∇p .* p\n    ∇y = t - sum(t, dims=1) .* p\n\n    (e, ∇y)\nend\n\n#=\n    logit_binary_cross_entropy(ŷ, 0)\n        = -log(1 - logistic(ŷ))\n        = -log(1 / (1 + exp(ŷ)))\n        = -(0 - log(1 + exp(ŷ)))\n        = -(ŷ - log(1 + exp(ŷ))) + ŷ\n        = -log_logistic(ŷ) + ŷ\n=#\nfunction logit_binary_cross_entropy(\n    ŷ::AbstractMatrix{Float64},\n    y::AbstractMatrix{Bool},\n)::Tuple{Float64, Matrix{Float64}}\n    @assert size(ŷ, 1) == 1\n    t = -log_logistic.(ŷ)\n    ny = .!y\n    t[ny] .+= ŷ[ny]\n    e = sum(t) / size(ŷ, 2)\n\n    ∂t_over_∂y = -∇log_logistic.(ŷ, -t)\n    ∂t_over_∂y[ny] .+= 1.0\n    ∇y = ∂t_over_∂y\n\n    (e, ∇y)\nend\n\n\n#=\n\nAddendum\n--------\n\nThe derivation of the gradient of softmax + cross-entropy can be found in:\n\n- https://stats.stackexchange.com/questions/235528/backpropagation-with-softmax-cross-entropy\n- https://charlee.li/how-to-compute-the-derivative-of-softmax-and-cross-entropy/\n- http://denizyuret.github.io/Knet.jl/stable/softmax/#Softmax-1\n\nCopy the LaTeX here:\n\n$$\n\\begin{aligned}\n\\frac{\\partial}{\\partial z_k}\\text{CE} &= \\frac{\\partial}{\\partial z_k}\\sum_{j=1}^n\n\\big(- y_j \\log \\sigma(z_j) \\big) \\\\  &= -\\sum_{j=1}^n y_j \\frac{\\partial}{\\partial z_k} \\log\n\\sigma(z_j) && \\cdots \\text{addition rule, } -y_j \\text{ is constant}\\\\  &= -\\sum_{j=1}^n y_j\n\\frac{1}{\\sigma(z_j)} \\cdot \\frac{\\partial}{\\partial z_k} \\sigma(z_j) && \\cdots \\text{chain rule}\\\\\n&= -y_k \\cdot \\frac{\\sigma(z_k)(1-\\sigma(k))}{\\sigma(z_k)} –  \\sum_{j \\neq k} y_j \\cdot\n\\frac{-\\sigma(z_j)\\sigma(z_k)}{\\sigma(z_j)} && \\cdots \\text{consier both }j = k \\text{ and } j \\neq\nk \\\\  &= -y_k \\cdot (1-\\sigma(z_k)) + \\sum_{j \\neq k} y_j \\sigma(z_k) \\\\  &= -y_k + y_k \\sigma(z_k)\n+  \\sum_{j \\neq k} y_j \\sigma(z_k) \\\\  &= -y_k + \\sigma(z_k) \\sum_j y_j.\n\\end{aligned}\n$$\n\n=#\n", "meta": {"hexsha": "c8513e758f779f698eeb4bb8e73206aa692c1f1f", "size": 4231, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "MultilayerPerceptron/src/loss.jl", "max_stars_repo_name": "gyk/TrivialSolutions", "max_stars_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T05:51:37.000Z", "max_issues_repo_path": "MultilayerPerceptron/src/loss.jl", "max_issues_repo_name": "gyk/TrivialSolutions", "max_issues_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MultilayerPerceptron/src/loss.jl", "max_forks_repo_name": "gyk/TrivialSolutions", "max_forks_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8355263158, "max_line_length": 100, "alphanum_fraction": 0.6026943985, "num_tokens": 1587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7645122519333475}}
{"text": "##################################################\n# Helper functions\n##################################################\n\n\"\"\"\n    spline_catmullrom(u, y0, y1, y2, y3)\n\nSmooth interpolation between `y1, y2`, using the Catmull-Rom spline.\nThe function uses `y0` and `y3` to ensure that the derivative at `y1`\nand `y2` is continuous.  `u` is a parameter between `0` and `1`.\n\n\"\"\"\nspline_catmullrom(u, y0, y1, y2, y3) = y1 + 0.5u*(-y0 + y2 + u*(2y0 - 5y1 + 4y2 - y3 + u*(-y0 + 3y1 - 3y2 + y3)))\n\n_orbitalrank(orbital_symbol) =\n    startswith(string(orbital_symbol), \"s\") ? 1 :\n    startswith(string(orbital_symbol), \"p\") ? 2 :\n    startswith(string(orbital_symbol), \"d\") ? 3 :\n    startswith(string(orbital_symbol), \"f\") ? 4 :\n    error(\"invalid orbital symbol: $orbital_symbol\")\n\n##################################################\n", "meta": {"hexsha": "e8e14ebdeb5cb6190223c4c8bd7315daf28ef89e", "size": 828, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/util.jl", "max_stars_repo_name": "NanoJulia/SlaterKoster.jl", "max_stars_repo_head_hexsha": "57b1420b041021518c2043867ac6482fd3b81354", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-10-11T10:55:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-07T14:42:45.000Z", "max_issues_repo_path": "src/util.jl", "max_issues_repo_name": "dalum/SlaterKoster.jl", "max_issues_repo_head_hexsha": "57b1420b041021518c2043867ac6482fd3b81354", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util.jl", "max_forks_repo_name": "dalum/SlaterKoster.jl", "max_forks_repo_head_hexsha": "57b1420b041021518c2043867ac6482fd3b81354", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0, "max_line_length": 113, "alphanum_fraction": 0.5301932367, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7645122462907538}}
{"text": "\n\nfunction LinearRegression(\n    x :: AbstractArray{T, 1},\n    y :: AbstractArray{T, 1};\n    order :: Integer = 1,\n) where T <: AbstractFloat \n\n    if order < 0\n        throw(ErrorException(\"Parameter order must be non-negative.\"))\n    end\n\n    N = length(x)\n\n    bases = order + 1\n\n\n    ϕ = zeros(N, bases)\n\n    for i = 1:bases\n\n        if i == 1\n            ϕ[:, 1] .= 1.0\n        else\n            ϕ[:, i] .= x.^(i-1)\n        end\n\n    end\n\n    # ϕ β = y => β = ϕ \\ y\n\n    return ϕ \\ y\n\nend\n\nfunction detrend(\n    x :: AbstractArray{T, 1},\n    y :: AbstractArray{T, 1};\n    order :: Integer = 1,\n) where T <: AbstractFloat\n\n    if order < 0\n        throw(ErrorException(\"Parameter order must be non-negative.\"))\n    end\n    \n    bases = order + 1\n\n    β = LinearRegression(x, y; order=order)\n    \n    result = copy(y)\n    total_mean = 0.0\n    for i = 1:bases\n        result .-= β[i] * x.^(i-1)\n        total_mean += β[i]/ i * (x[end]^i - x[1]^i) \n    end\n\n    result .+= total_mean / (x[end] - x[1])\n\n    return result\n\nend\n", "meta": {"hexsha": "69da383bec0e836a5b0ca9dc0999d63a7e09e780", "size": 1025, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/old/diagnose_scripts/analysis/LinearRegression.jl", "max_stars_repo_name": "meteorologytoday/CESM-diagnostic", "max_stars_repo_head_hexsha": "ed9cbc3ffeb2ebebe7d7a2453a52111a51b1660f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/old/diagnose_scripts/analysis/LinearRegression.jl", "max_issues_repo_name": "meteorologytoday/CESM-diagnostic", "max_issues_repo_head_hexsha": "ed9cbc3ffeb2ebebe7d7a2453a52111a51b1660f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/old/diagnose_scripts/analysis/LinearRegression.jl", "max_forks_repo_name": "meteorologytoday/CESM-diagnostic", "max_forks_repo_head_hexsha": "ed9cbc3ffeb2ebebe7d7a2453a52111a51b1660f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.5322580645, "max_line_length": 70, "alphanum_fraction": 0.5024390244, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632247867715, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7645116088335774}}
{"text": "# Contains various membership function types\n# ------------------------------------------\n\n\"\"\"\t Membership function type\n\"\"\"\nabstract type MF end\n\n\n\"\"\"\t Triangular membership function type\n\n\t TriangularMF(l_vertex, center, r_vertex)\n\n\t Properties\n\t ----------\n\t `l_vertex`, `center` and `r_vertex` are the vertices of the triangle, in order\n\n\t `eval` function returns membership value at a point\n\t `mean_at` function returns mean value at line clipped by given firing strength\n\"\"\"\nmutable struct TriangularMF<:MF\n\n\tl_vertex::Real\n\tcenter::Real\n\tr_vertex::Real\n\n\teval::Function\n\tmean_at::Function\n\tget_n::Function\n\tcut::Function\n\n\tfunction TriangularMF(l_vertex::Real, center::Real, r_vertex::Real)\n\n\t\tif l_vertex <= center <= r_vertex\n\n\t\t\tthis = new()\n\n\t\t\tthis.l_vertex = l_vertex\n\t\t\tthis.center = center\n\t\t\tthis.r_vertex = r_vertex\n\n\t\t\tfunction inv(α)\n\t\t\t\tx1 = (this.center - this.l_vertex) * α + this.l_vertex\n\t\t\t\tx2 = (this.center - this.r_vertex) * α + this.r_vertex\n\t\t\t\treturn x1, x2\n\t\t\tend\n\t\t\tthis.eval = function eval(x)\n\t\t\t\tmaximum([minimum([((x - this.l_vertex) / (this.center - this.l_vertex)), ((this.r_vertex - x) / (this.r_vertex - this.center))]), 0])\n\t\t\tend\n\n\t\t\tthis.mean_at = function mean_at(firing_strength)\n\n\t\t\t\tif firing_strength != 1\n\t\t\t\t\tp1 = (this.center - this.l_vertex) * firing_strength + this.l_vertex\n\t\t\t\t\tp2 = (this.center - this.r_vertex) * firing_strength + this.r_vertex\n\t\t\t\t\t(p1 + p2) / 2\n\t\t\t\telseif firing_strength == 1\n\t\t\t\t\treturn this.center\n\t\t\t\tend\n\n\t\t\tend\n\n\t\t\tthis.n_opt = function get_n(tol)\n\t\t\t\treturn 0\n\t\t\tend\n\n\t\t\tthis.cut = function cut(α)\n\t\t\t\tx1, x2 = inv(α)\n\t\t\t\treturn CutMF(x1, x2, α, this)\n\t\t\tend\n\n\t\t\tthis\n\n\t\telse\n\n\t\t\terror(\"invalid vertices\")\n\n\t\tend\n\n\tend\n\nend\n\n\n\"\"\"\n Gaussian membership function type\n\n\tGaussianMF(center, sigma)\n\n\t Properties\n\t ----------\n\t `center` is the center of the distribution\n\t `sigma` determines width of the distribution\n\n\t `eval` function returns membership value at a point\n\t `mean_at` function returns mean value at line clipped by given firing strength\n\n\"\"\"\nmutable struct GaussianMF<:MF\n\n\tcenter::Real\n\tsigma::Real\n\n\teval::Function\n\tmean_at::Function\n\tget_n::Function\n\tcut::Function\n\n\tfunction GaussianMF(center::Real, sigma::Real)\n\n\t\tthis = new()\n\n\t\tthis.center = center\n\t\tthis.sigma = sigma\n\n\t\tfunction inv(α)\n\t\t\tx1 = this.center - this.sigma*sqrt(-2*log(α))\n\t\t\tx2 = this.center + this.sigma*sqrt(-2*log(α))\n\t\t\treturn x1, x2\n\t\tend\n\n\t\tthis.eval = function eval(x)\n\t\t\texp( - 0.5 * ((x - this.center) / this.sigma) ^ 2)\n\t\tend\n\n\t\tthis.mean_at = function mean_at(firing_strength)\n\t\t\tthis.center\n\t\tend\n\n\t\tthis.get_n = function get_n(tol)\n\t\t\tl, u = inv(0.01)\n\t\t\tc = this.center\n\t\t\ts = this.sigma\n\t\t\tsdiff(x) = this.eval(x)*(c^2 - 2*c*x - s^2 + x^2)/s^4\n\t\t\txs = collect(l:(u-l)/100:u)\n\t\t\tys = sdiff.(xs)\n\t\t\tym = maximum(abs.(ys))\n\t\t\tsqrt((u - l)^3*ym/(12*tol))\n\t\tend\n\n\t\tthis.cut = function cut(α)\n\t\t\tx1, x2 = inv(α)\n\t\t\treturn CutMF(x1, x2, α, this)\n\t\tend\n\n\t\tthis\n\n\tend\n\nend\n\n\"\"\"\n\t Generalised Bell membership function type\n\n\tBellMF(a, b, c)\n\n\t Properties\n\t ----------\n\t `a`, `b` and `c` the usual bell parameters with `c` being the center\n\n\t `eval` function returns membership value at a point\n\t `mean_at` function returns mean value at line clipped by given firing strength\n\n\"\"\"\nmutable struct BellMF<:MF\n\n\ta::Real\n\tb::Real\n\tc::Real\n\n\teval::Function\n\tmean_at::Function\n\tget_n::Function\n\tcut::Function\n\n\tfunction BellMF(a::Real, b::Real, c::Real)\n\n\t\tthis = new()\n\n\t\tthis.a = a\n\t\tthis.b = b\n\t\tthis.c = c\n\n\t\tfunction inv(α)\n\t\t\tx1 = this.c - this.a*((1-α)/α)^(1/(2*b))\n\t\t\tx2 = this.c + this.a*((1-α)/α)^(1/(2*b))\n\t\t\treturn x1, x2\n\t\tend\n\t\tthis.eval = function eval(x)\n\t\t\t1 / (1 + abs((x - this.c) / this.a) ^ (2 * this.b))\n\t\tend\n\n\t\tthis.mean_at = function mean_at(firing_strength)\n\t\t\tthis.c\n\t\tend\n\n\t\tthis.get_n = function get_n(tol)\n\t\t\tl, u = inv(α)\n\t\t\treturn (u-l)^3/(12*tol)\n\t\tend\n\t\tthis.cut = function cut(α)\n\t\t\tx1, x2 = inv(α)\n\t\t\treturn CutMF(x1, x2, α, this)\n\t\tend\n\n\t\tthis\n\n\tend\n\nend\n\n\"\"\"\n\t Trapezoidal membership function type\n\n\tTrapezoidalMF(l_bottom_vertex, l_top_vertex, r_top_vertex, r_bottom_vertex)\n\n\t Properties\n\t ----------\n\t `l_bottom_vertex`, `l_top_vertex`, `r_top_vertex` and `r_bottom_vertex` are the vertices of the trapezoid, in order\n\n\t `eval` function returns membership value at a point\n\t `mean_at` function returns mean value at line clipped by given firing strength\n\n\"\"\"\nmutable struct TrapezoidalMF<:MF\n\n\tl_bottom_vertex::Real\n\tl_top_vertex::Real\n\tr_top_vertex::Real\n\tr_bottom_vertex::Real\n\n\teval::Function\n\tmean_at::Function\n\tget_n::Function\n\tcut::Function\n\n\tfunction TrapezoidalMF(l_bottom_vertex::Real, l_top_vertex::Real, r_top_vertex::Real, r_bottom_vertex::Real)\n\n\t\tif l_bottom_vertex <= l_top_vertex <= r_top_vertex <= r_bottom_vertex\n\n\t\t\tthis = new()\n\n\t\t\tthis.l_bottom_vertex = l_bottom_vertex\n\t\t\tthis.l_top_vertex = l_top_vertex\n\t\t\tthis.r_top_vertex = r_top_vertex\n\t\t\tthis.r_bottom_vertex = r_bottom_vertex\n\n\t\t\tfunction inv(α)\n\t\t\t\tx1 = (this.l_top_vertex - this.l_bottom_vertex) * α + this.l_bottom_vertex\n\t\t\t\tx2 = (this.r_top_vertex - this.r_bottom_vertex) * α + this.r_bottom_vertex\n\t\t\t\treturn x1, x2\n\t\t\tend\n\n\t\t\tthis.eval = function eval(x)\n\t\t\t\tmaximum([minimum([((x - this.l_bottom_vertex) / (this.l_top_vertex - this.l_bottom_vertex)), 1, ((this.r_bottom_vertex - x) / (this.r_bottom_vertex - this.r_top_vertex))]), 0])\n\t\t\tend\n\n\t\t\tthis.mean_at = function mean_at(firing_strength)\n\t\t\t\tp1 = (this.l_top_vertex - this.l_bottom_vertex) * firing_strength + this.l_bottom_vertex\n\t\t\t\tp2 = (this.r_top_vertex - this.r_bottom_vertex) * firing_strength + this.r_bottom_vertex\n\t\t\t\t(p1 + p2) / 2\n\t\t\tend\n\n\t\t\tthis.get_n = function get_n(tol)\n\t\t\t\treturn 0\n\t\t\tend\n\n\t\t\tthis.cut = function cut(α)\n\t\t\t\tx1, x2 = inv(α)\n\t\t\t\treturn CutMF(x1, x2, α, this)\n\t\t\tend\n\n\t\t\tthis\n\n\t\telse\n\n\t\t\terror(\"invalid vertices\")\n\n\t\tend\n\n\tend\n\nend\n\n\"\"\"\n\t Sigmoid membership function type\n\n\tSigmoidMF(a, c, limit)\n\n\t Properties\n\t ----------\n\t `a` controls slope\n\t `c` is the crossover point\n\t `limit` sets the extreme limit\n\n\t `eval` function returns membership value at a point\n\t `mean_at` function returns mean value at line clipped by given firing strength\n\n\"\"\"\nmutable struct SigmoidMF<:MF\n\n\ta::Real\n\tc::Real\n\tlimit::Real\n\n\teval::Function\n\tmean_at::Function\n\tget_n::Function\n\tcut::Function\n\n\tfunction SigmoidMF(a::Real, c::Real, limit::Real)\n\n\t\tif (a > 0 && limit > c) || (a < 0 && limit < c)\n\n\t\t\tthis = new()\n\n\t\t\tthis.a = a\n\t\t\tthis.c = c\n\t\t\tthis.limit = limit\n\n\t\t\tfunction inv(α)\n\t\t\t\treturn this.c - (1/this.a)*log((1-α)/α)\n\t\t\tend\n\n\t\t\tthis.eval = function eval(x)\n\t\t\t\t1 / (1 + exp(-this.a * (x - this.c)))\n\t\t\tend\n\n\t\t\tthis.mean_at = function mean_at(firing_strength)\n\n\t\t\t\tif firing_strength == 1\n\t\t\t\t\tp_firing_strength = 0.999\n\t\t\t\telseif firing_strength == 0\n\t\t\t\t\tp_firing_strength = 0.001\n\t\t\t\telse\n\t\t\t\t\tp_firing_strength = firing_strength\n\t\t\t\tend\n\n\t\t\t\tp1 = -log((1 / p_firing_strength) - 1) / this.a + this.c\n\t\t\t\tp2 = this.limit\n\t\t\t\t(p1 + p2) / 2\n\n\t\t\tend\n\n\t\t\tthis.get_n = function get_n(tol)\n\t\t\t\ta = this.a\n\t\t\t\tc = this.c\n\t\t\t\tif a > 0\n\t\t\t\t\tu = this.limit\n\t\t\t\t\tl = inv(0.01)\n\t\t\t\telse\n\t\t\t\t\tl = this.limit\n\t\t\t\t\tu = inv(0.01)\n\t\t\t\tend\n\t\t\t\taux1(x) = exp(-a*(x-c))\n\t\t\t\taux2(x) = 2*a^2*(aux1(x))^2/(aux1(x) + 1)^3\n\t\t\t\tsdiff(x) = aux2(x) - a^2*aux1(x)/(aux1(x) + 1)^2\n\t\t\t\txs = collect(l:(u-l)/100:u)\n\t\t\t\tys = sdiff.(xs)\n\t\t\t\tym = maximum(abs.(ys))\n\t\t\t\tsqrt((u - l)^3*ym/(12*tol))\n\t\t\tend\n\n\t\t\tthis.cut = function cut(α)\n\t\t\t\tx = inv(α)\n\t\t\t\tif this.a > 0\n\t\t\t\t\tx1 = x\n\t\t\t\t\tx2 = this.limit\n\t\t\t\telse\n\t\t\t\t\tx1 = this.limit\n\t\t\t\t\tx2 = x\n\t\t\t\tend\n\t\t\t\treturn CutMF(x1, x2, α, this)\n\t\t\tend\n\n\t\t\tthis\n\n\t\telse\n\n\t\t\terror(\"invalid parameters\")\n\n\t\tend\n\n\tend\nend\n\n\"\"\"\n\tCut MF\n\n\tCutMF(a, b, c)\n\n\t Properties\n\t ----------\n\t `a`, `b` and `c` the usual bell parameters with `c` being the center\n\n\t `eval` function returns membership value at a point\n\t `mean_at` function returns mean value at line clipped by given firing strength\n\n\"\"\"\nmutable struct CutMF<:MF\n\n\tx1::Real\n\tx2::Real\n\tα::Real\n\ttoCutMF::MF\n\n\teval::Function\n\tmean_at::Function\n\tget_n::Function\n\tcut::Function\n\n\tfunction CutMF(x1::Real, x2::Real, α::Real, toCutMF::MF)\n\n\t\tthis = new()\n\n\t\tthis.x1 = x1\n\t\tthis.x2 = x2\n\t\tthis.α = α\n\t\tthis.toCutMF = toCutMF\n\n\t\tthis.eval = function eval(x)\n\t\t\tif x1 <= x <= x2\n\t\t\t\treturn this.α\n\t\t\telse\n\t\t\t\treturn this.toCutMF.eval(x)\n\t\t\tend\n\t\tend\n\n\t\tthis.mean_at = function mean_at(firing_strength)\n\t\t\tif firing_strength >= α\n\t\t\t\treturn this.toCutMF.mean_at(α)\n\t\t\telse\n\t\t\t\treturn this.toCutMF.mean_at(firing_strength)\n\t\t\tend\n\t\tend\n\n\t\tthis.get_n = function get_n(tol)\n\t\t\treturn this.toCutMF.get_n(tol)\n\t\tend\n\n\t\tthis.cut = function cut(α)\n\t\t\tif α >= this.α\n\t\t\t\treturn this\n\t\t\telse\n\t\t\t\treturn this.toCutMF.cut(α)\n\t\t\tend\n\t\tend\n\n\t\tthis\n\n\tend\n\nend\n", "meta": {"hexsha": "3efb7152d43f95a309daa772dbec896e09d6ec7b", "size": 8669, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MF.jl", "max_stars_repo_name": "juanscr/Fuzzy.jl", "max_stars_repo_head_hexsha": "b8553c79ff60592a5e5058d4bc1ae60724d237eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-03T17:29:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T17:29:10.000Z", "max_issues_repo_path": "src/MF.jl", "max_issues_repo_name": "juanscr/Fuzzy.jl", "max_issues_repo_head_hexsha": "b8553c79ff60592a5e5058d4bc1ae60724d237eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MF.jl", "max_forks_repo_name": "juanscr/Fuzzy.jl", "max_forks_repo_head_hexsha": "b8553c79ff60592a5e5058d4bc1ae60724d237eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1368653422, "max_line_length": 180, "alphanum_fraction": 0.6426346753, "num_tokens": 2711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632234212403, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7645116054945527}}
{"text": "using LinearAlgebra\r\nusing JuMP, Clp\r\ninclude(\"ontoSimplex.jl\")\r\n\r\n\r\nfunction distFunction(states1::Vector{Float64}, states2::Vector{Float64})::Array{Float64,2}\r\n    n1= length(states1); n2= length(states2)\r\n    dMatrix= Array{Float64}(undef, (n1,n2))\r\n    for i= 1:n1, j= 1:n2\r\n\t\tdMatrix[i,j]= abs(states2[j]- states1[i])\r\n    end\r\n    return dMatrix\r\nend\r\n\r\n\r\n#\tcomputes the Wasserstein distance\r\nfunction Wasserstein(p1::Vector{Float64}, p2::Vector{Float64}, distMatrix::Array{Float64,2}, rWasserstein::Float64=1.)\r\n\tontoSimplex!(p1); ontoSimplex!(p2)\r\n    n1= length(p1);   n2= length(p2)\r\n\r\n    A= kron(ones(n2)', Matrix{Float64}(I, n1, n1))\r\n    B= kron(Matrix{Float64}(I, n2, n2), ones(n1)')\r\n\r\n\tmodel = Model(Clp.Optimizer)\r\n\t@variable(model, x[i=1:n1*n2] >= 0)\r\n\t@objective(model, Min, vec(distMatrix.^rWasserstein)' * x)\r\n\t@constraint(model, [A;B] * x .== [p1;p2])\r\n\toptimize!(model)\r\n    return (distance= (objective_value(model))^(1/ rWasserstein), π= reshape(value.(x), (n1, n2)))\r\nend\r\n\r\n\r\n#\tSinkhorn-Knopp iteration algorithm\r\nfunction Sinkhorn(p1::Vector{Float64}, p2::Vector{Float64}, distMatrix::Array{Float64,2}, rWasserstein::Float64= 1., λ::Float64= 1.)\r\n\tontoSimplex!(p1); ontoSimplex!(p2); count= 0\r\n\tβr= Array{Float64}(undef, length(p1));\r\n\tγc= ones(size(p2))\t\t# guess a starting value\r\n\tdistMatrix.^= rWasserstein; K= exp.(-λ * distMatrix)\r\n\twhile count < 1000\t\t# Sinkhorn iteration\r\n\t\tγc= γc./ (p2'*γc)\t\t# rescale\r\n\t\tβr= p1./ (K* γc)\t\t# vector operation\r\n\t\tγc= p2./ (K'* βr)\t\t# vector operation\r\n\t\tcount += 1\t\t\t\t# iteration count\r\n\tend\r\n#\tprintln(\"r=\", βr, p1'*βr); println(\"c=\", γc, p2'*γc)\r\n\tπ= Diagonal(βr)*K*Diagonal(γc)\r\n\treturn (distance= (sum(π.* distMatrix)) ^(1/rWasserstein), π= π)\r\nend\r\n\r\n\r\n# #\tSinkhorn-Knopp algorithm\r\n# function Sinkhorn(p1::Vector{Float64}, p2::Vector{Float64}, distMatrix::Array{Float64,2}, rWasserstein::Float64= 1., λ::Float64= 1.)\r\n# \tontoSimplex!(p1); ontoSimplex!(p2)\r\n# \tπ= exp.(-λ * (distMatrix.^ rWasserstein))\r\n# \tfor i= 1:100\r\n# \t\tπ.*= (p2'./ sum(π, dims=1)) # scale to sum of column= 1\r\n# \t\tπ.*= (p1 ./ sum(π, dims=2)) # scale to sum of lines= 1\r\n# \tend\r\n# \treturn (distance= sum(π.* distMatrix)^(1/ rWasserstein), π= π)\r\n# end", "meta": {"hexsha": "af44c0fa933327d2f4625778f3ac43196f6fbcdd", "size": 2197, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Wasserstein.jl", "max_stars_repo_name": "aloispichler/ScenTrees.jl", "max_stars_repo_head_hexsha": "c619f385636cab3050362eefc1ec522c9fed40fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-03T01:09:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T01:09:51.000Z", "max_issues_repo_path": "src/Wasserstein.jl", "max_issues_repo_name": "rubsc/ScenTrees.jl", "max_issues_repo_head_hexsha": "e13e7b06f29a387e1f2afcd0f3575b77ef6132bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Wasserstein.jl", "max_forks_repo_name": "rubsc/ScenTrees.jl", "max_forks_repo_head_hexsha": "e13e7b06f29a387e1f2afcd0f3575b77ef6132bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-10-05T12:55:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T07:51:52.000Z", "avg_line_length": 36.6166666667, "max_line_length": 135, "alphanum_fraction": 0.6417842513, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172688214137, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7644782920143836}}
{"text": "using Random, LinearAlgebra, Plots; pyplot()\nRandom.seed!()\n\nN = 10^5\ndata     = [[rand(),rand()] for _ in 1:N]\nindata   = filter((x)-> (norm(x) <= 1), data)\noutdata  = filter((x)-> (norm(x) > 1), data)\npiApprox = 4*length(indata)/N\nprintln(\"Pi Estimate: \", piApprox)\n\nscatter(first.(indata),last.(indata), c=:blue, ms=1, msw=0)\nscatter!(first.(outdata),last.(outdata), c=:red, ms=1, msw=0,\n\txlims=(0,1), ylims=(0,1), legend=:none, ratio=:equal)", "meta": {"hexsha": "9a18541444f0cdb365c31b65935794c799ba221d", "size": 445, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1_chapter/piEstimate.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "1_chapter/piEstimate.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "1_chapter/piEstimate.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 34.2307692308, "max_line_length": 61, "alphanum_fraction": 0.6247191011, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172615983309, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7644782861952355}}
{"text": "## Definition of Link types and methods for link, invlink and μη, the derivative of μ w.r.t. η\n\nabstract Link\n\nimmutable IdentityLink <: Link end\nimmutable InverseLink <: Link end\nimmutable LogLink <: Link end\nimmutable LogitLink <: Link end\n\nlink(::IdentityLink,μ) = μ\ninvlink(::IdentityLink,η) = η\nμη(::IdentityLink,η) = one(η)\n\nlink(::LogitLink,μ) = log(μ/(one(μ)-μ))\ninvlink(::LogitLink,η) = inv(one(η) + exp(-η))\nμη(::LogitLink,η) = (ee = exp(-η); ee/abs2(one(η)+ee))\n\nlink(::LogLink,μ) = log(μ)\ninvlink(::LogLink,η) = exp(η)\nμη(::LogLink,η) = exp(η)\n\nlink(::InverseLink,μ) = inv(μ)\ninvlink(::InverseLink,η) = inv(η)\nμη(::InverseLink,η) = -inv(abs2(η))\n\n", "meta": {"hexsha": "cc0016c9bbe3b3aea209761d0bc5813b755bde78", "size": 659, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/link.jl", "max_stars_repo_name": "JuliaTagBot/ParallelGLM.jl", "max_stars_repo_head_hexsha": "ccb49bf0866c21ec6f5a4b10d94f4dfedea75426", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-02-15T00:26:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-24T21:06:01.000Z", "max_issues_repo_path": "src/link.jl", "max_issues_repo_name": "JuliaTagBot/ParallelGLM.jl", "max_issues_repo_head_hexsha": "ccb49bf0866c21ec6f5a4b10d94f4dfedea75426", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/link.jl", "max_forks_repo_name": "JuliaTagBot/ParallelGLM.jl", "max_forks_repo_head_hexsha": "ccb49bf0866c21ec6f5a4b10d94f4dfedea75426", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-08-29T00:11:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:18:54.000Z", "avg_line_length": 25.3461538462, "max_line_length": 94, "alphanum_fraction": 0.6646433991, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7644782850314057}}
{"text": "using ApproxFun, Test\n    import ApproxFun: Block, BlockBandedMatrix\n\n## PDEs\n\n\nS = JacobiWeight(1.,1.,Jacobi(1.,1.))^2\nΔ = Laplacian(S)\n\nf = Fun((x,y)->sin(π*x)*sin(π*y),S)\n\nQR1=qr(Δ)\n    ApproxFun.resizedata!(QR1,:,400)\n    \\(QR1,f; tolerance=1E-10)\nQR1=qr(Δ)\n    @time Δ[Block.(1:40), Block.(1:40)]\n    @time ApproxFun.resizedata!(QR1,:,400)\n    @time \\(QR1,f; tolerance=1E-10)\nprintln(\"Laplace Dirichlet: should be ~0.015, 0.015, 0.001\")\n\nd=ChebyshevInterval()^2\nA=[Dirichlet(d); Laplacian(d)]\nf=Fun((x,y)->real(exp(x+im*y)),∂(d))\n\nQR=qr(A)\n    ApproxFun.resizedata!(QR,:,150)\n    \\(QR,[f; 0.];tolerance=1E-10)\n\nQR=qr(A)\n    @time ApproxFun.resizedata!(QR,:,150)\n    @time u=\\(QR,[f; 0.];tolerance=1E-10)\n\nprintln(\"Laplace: should be ~0.06, 0.001\")\n\n\n\nd=ChebyshevInterval()^2\nu = [Neumann(d); Laplacian(d)+100I] \\ [[[1,1],[1,1]],0]\n@time u = [Neumann(d); Laplacian(d)+100I] \\ [[[1,1],[1,1]],0]\nprintln(\"Neumann Helmholtz: should be ~0.032\")\n\n# dx=Interval(0.,1.);dt=Interval(0.0,0.54)\n# d=dx*dt\n#\n# x,y=Fun(d)\n# V=x^2\n#\n# Dt=Derivative(d,[0,1]);Dx=Derivative(d,[1,0])\n#\n# ϵ=0.1\n#\n# u0=Fun(x->exp(-25*(x-.5)^2)*exp(-1.0im/(5*ϵ)*log(2cosh(5*(x-.5)))),dx)\n# L=1im*ϵ*Dt+.5*ϵ^2*Dx^2-V⊗1\n#\n# PO=discretize([timedirichlet(d);L],50)\n# @time PO=discretize([timedirichlet(d);L],50)\n# u=PO\\u0\n# @time    u=PO\\u0\n#\n# println(\"Schrodinger: should be ~0.013,0.015\")\n", "meta": {"hexsha": "309cfa2cb73dea2b16813dcf2f80b841509e4533", "size": 1356, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/SpeedPDETest.jl", "max_stars_repo_name": "jw3126/ApproxFun.jl", "max_stars_repo_head_hexsha": "e244b8c3481467c3f38b56bf5170c89104194b47", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/SpeedPDETest.jl", "max_issues_repo_name": "jw3126/ApproxFun.jl", "max_issues_repo_head_hexsha": "e244b8c3481467c3f38b56bf5170c89104194b47", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/SpeedPDETest.jl", "max_forks_repo_name": "jw3126/ApproxFun.jl", "max_forks_repo_head_hexsha": "e244b8c3481467c3f38b56bf5170c89104194b47", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2295081967, "max_line_length": 72, "alphanum_fraction": 0.6017699115, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7644108732735163}}
{"text": "using NBInclude\n\n\n@nbinclude(\"Time Evolution(QOptics).ipynb\")\n\nusing ITensors\nusing PyPlot\n\n  N = 10\n  cutoff = 1E-8\n  tau = 0.05\n  ttotal = 1.5*4\n\nfunction TEvolHeis(N, cutoff,tau, ttotal)\n\n  # Compute the number of steps to do\n  Nsteps = Int(ttotal/tau)\n\n  # Make an array of 'site' indices\n  s = siteinds(\"S=1/2\",N)\n\n  # Make gates (1,2),(2,3),(3,4),...\n  gates = ITensor[]\n  for j=1:N-1\n    s1 = s[j]\n    s2 = s[j+1]\n    hj =       op(\"Sz\",s1) * op(\"Sz\",s2) +\n               op(\"Sx\",s1) * op(\"Sx\",s2) +\n               op(\"Sy\",s1) * op(\"Sy\",s2)\n    Gj = exp(-1.0im * tau/2 * hj)\n    push!(gates,Gj)\n  end\n  # Include gates in reverse order too\n  # (N,N-1),(N-1,N-2),...\n  append!(gates,reverse(gates))\n\n  c = div(N,2) # center site\n\n  # Initialize psi to be a product state (alternating up and down)\n  psi = productMPS(s, n -> n!=c ? \"Up\" : \"Dn\")\n\n  Szc=[]\n  Szc2=[]\n  # Compute and print initial <Sz> value on site c\n  t = 0.0\n  Sz  = ITensors.expect(psi,\"Sz\";site_range=c:c)\n  Sz2 = ITensors.expect(psi,\"Sz\";site_range=c+1:c+1)\n  println(\"$t $Sz $Sz2\")\n  append!(Szc,Sz)\n  append!(Szc2,Sz2)\n\n  # Do the time evolution by applying the gates\n  # for Nsteps steps and printing <Sz> on site c\n  for step=1:Nsteps\n    psi = apply(gates, psi; cutoff=cutoff)\n    t += tau\n    Sz  = ITensors.expect(psi,\"Sz\";site_range=c:c)\n    Sz2 = ITensors.expect(psi,\"Sz\";site_range=c+1:c+1)\n    println(\"$t $Sz $Sz2\")\n    append!(Szc,Sz)\n    append!(Szc2,Sz2)\n  end\n  times = 0:tau:ttotal\n  return Szc, Szc2, times\nend\n\n\n#Clear demostration of time-evolution\nSzc1=TEvolHeis(10, 1E-8, 0.05, 1.5*4)[1];\nSzc2=TEvolHeis(10, 1E-8, 0.05, 1.5*4)[2];\ntimess=TEvolHeis(10, 1E-8, 0.05, 1.5*4)[3];\n#Data of longer time-step\nSzc1t=TEvolHeis(10, 1E-8, 0.05, 1.5*8)[1];\nSzc2t=TEvolHeis(10, 1E-8, 0.05, 1.5*8)[2];\ntimesst=TEvolHeis(10, 1E-8, 0.05, 1.5*8)[3];\n#Data of bigger cut-off\nSzc1f=TEvolHeis(10, 1E-4, 0.05, 1.5*4)[1];\nSzc2f=TEvolHeis(10, 1E-4, 0.05, 1.5*4)[2];\ntimessf=TEvolHeis(10, 1E-4, 0.05, 1.5*4)[3];\n\n#Plotting both QOptics and ITensors data of time-evolution \n\nPyPlot.plot(timess, Szc1)\nPyPlot.plot(timess, Szc2)\nPyPlot.plot(tout, m5z,linestyle = \":\",linewidth = 5)\nPyPlot.plot(tout, m6z,linestyle = \":\",linewidth = 5)\nlegend([\"m5z(ITensors)\", \"m6z(ITensors)\",\"m5z(QOptics)\",\"m6z(QOptics)\"])\nxlabel(\"Time\")\nylabel(L\"$\\langle S^{Z} \\rangle$\") \n\nsavefig( \"time-evolution.pdf\", bbox_inches = \"tight\", pad_inches = 0.1 )\n\n#Plot of longer Time-step  \nPyPlot.plot(timesst, Szc1t)\nPyPlot.plot(timesst, Szc2t)\ntitle(\"Longer Time Scale\")\nxlabel(\"Time\")\nylabel(L\"$\\langle  S^{Z}  \\rangle$\") \nlegend([\"m5z(ITensors)\",\"m6z(ITensors)\"])\nsavefig( \"Longer Time Scale.pdf\", bbox_inches = \"tight\", pad_inches = 0.1 )\n\n#Plot of bigger cut-off\nPyPlot.plot(timessf, Szc1f)\nPyPlot.plot(timessf, Szc2f)\ntitle(L\"Cut-Off($10^{-4}$)\")\nxlabel(\"Time\")\nylabel(L\"$\\langle S^{Z} \\rangle$\") \nlegend([\"m5z(ITensors)\",\"m6z(ITensors)\"])\nsavefig( \"smallercut-off.pdf\", bbox_inches = \"tight\", pad_inches = 0.1 )\n\n\n", "meta": {"hexsha": "b0bb9b88220c693d22f953db2079217f9b757f4f", "size": 2963, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "TensorNetworks/Time Evolution(QO and ITensors).jl", "max_stars_repo_name": "BlackBodyRadiation/JupyterTNN", "max_stars_repo_head_hexsha": "9f3c207fdff32ce68e791a8cedab9da7cbe37fee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TensorNetworks/Time Evolution(QO and ITensors).jl", "max_issues_repo_name": "BlackBodyRadiation/JupyterTNN", "max_issues_repo_head_hexsha": "9f3c207fdff32ce68e791a8cedab9da7cbe37fee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TensorNetworks/Time Evolution(QO and ITensors).jl", "max_forks_repo_name": "BlackBodyRadiation/JupyterTNN", "max_forks_repo_head_hexsha": "9f3c207fdff32ce68e791a8cedab9da7cbe37fee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4553571429, "max_line_length": 75, "alphanum_fraction": 0.6290921363, "num_tokens": 1227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7644108694326825}}
{"text": "series = \"\n73167176531330624919225119674426574742355349194934\n96983520312774506326239578318016984801869478851843\n85861560789112949495459501737958331952853208805511\n12540698747158523863050715693290963295227443043557\n66896648950445244523161731856403098711121722383113\n62229893423380308135336276614282806444486645238749\n30358907296290491560440772390713810515859307960866\n70172427121883998797908792274921901699720888093776\n65727333001053367881220235421809751254540594752243\n52584907711670556013604839586446706324415722155397\n53697817977846174064955149290862569321978468622482\n83972241375657056057490261407972968652414535100474\n82166370484403199890008895243450658541227588666881\n16427171479924442928230863465674813919123162824586\n17866458359124566529476545682848912883142607690042\n24219022671055626321111109370544217506941658960408\n07198403850962455444362981230987879927244284909188\n84580156166097919133875499200524063689912560717606\n05886116467109405077541002256983155200055935729725\n71636269561882670428252483600823257530420752963450\n\"\n\nseries = filter(x -> !isspace(x), series)\nmax = 0\nbiglist=[]\nfor i = 1:length(series)-13\n    rolling = series[i:i+13]\n    products = 1\n    for i in rolling\n        products *= parse(Int,i)\n    end\n    if products > max\n        global max = products\n        global biglist = rolling\n    end\nend\nprintln(max)\nprintln(\"List = $biglist\")\n", "meta": {"hexsha": "ecadfaf03252de0de10511f8e0419f3124d3b821", "size": 1368, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "008.jl", "max_stars_repo_name": "Moelf/EulerProject.jl", "max_stars_repo_head_hexsha": "02e0f6e6e34c20b261ac720133eabc8597a03b11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "008.jl", "max_issues_repo_name": "Moelf/EulerProject.jl", "max_issues_repo_head_hexsha": "02e0f6e6e34c20b261ac720133eabc8597a03b11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "008.jl", "max_forks_repo_name": "Moelf/EulerProject.jl", "max_forks_repo_head_hexsha": "02e0f6e6e34c20b261ac720133eabc8597a03b11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:07:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:07:42.000Z", "avg_line_length": 34.2, "max_line_length": 50, "alphanum_fraction": 0.8815789474, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.8333246035907932, "lm_q1q2_score": 0.7644108676362654}}
{"text": "export SpHTypes\n\"\"\"\n    const SpHTypes = Union{Float64,Complex{Float64}}\n\nThe types supported by FastSphericalHarmonics (the same types as for\nFastTransforms).\n\"\"\"\nconst SpHTypes = Union{Float64,Complex{Float64}}\n\nexport sph_points\n\"\"\"\n    Θ, Φ = sph_points(N::Integer)\n    Θ::Vector{Float64}\n    Φ::Vector{Float64}\n\nCalculate the locations of points on the sphere when using `N` points\nin the θ (latitudinal) direction.\n\nIt is `length(Θ) = N` and `length(Φ) = M` where `M = 2N-1`.\n\"\"\"\nfunction sph_points(N::Int)\n    @assert N > 0\n    M = 2 * N - 1\n    return π / N * (0.5:(N - 0.5)), 2π / M * (0:(M - 1))\nend\nsph_points(N::Integer) = sph_points(Int(N))\n\nexport sph_lmax\n\"\"\"\n    lmax = sph_lmax(N::Integer)\n    lmax::Int\n\nCalculate the maximum `l` mode that can be represented with `N`\npoints. It is `lmax = N - 1`.\n\"\"\"\nfunction sph_lmax(N::Int)\n    @assert N > 0\n    return N - 1\nend\nsph_lmax(N::Integer) = sph_lmax(Int(N))\n", "meta": {"hexsha": "7d5e41bbef0c692f0b0c7fe7943fe62cc89e5eba", "size": 926, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/points.jl", "max_stars_repo_name": "eschnett/FastSphericalHarmonics.jl", "max_stars_repo_head_hexsha": "5f53677ac2703cd0e30ec7457f1c36dd62ba36da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-03-10T17:20:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T08:50:11.000Z", "max_issues_repo_path": "src/points.jl", "max_issues_repo_name": "eschnett/FastSphericalHarmonics.jl", "max_issues_repo_head_hexsha": "5f53677ac2703cd0e30ec7457f1c36dd62ba36da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-26T09:45:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-29T02:31:55.000Z", "max_forks_repo_path": "src/points.jl", "max_forks_repo_name": "eschnett/FastSphericalHarmonics.jl", "max_forks_repo_head_hexsha": "5f53677ac2703cd0e30ec7457f1c36dd62ba36da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-20T15:30:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-20T15:30:44.000Z", "avg_line_length": 22.5853658537, "max_line_length": 69, "alphanum_fraction": 0.651187905, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7644108675633249}}
{"text": "## Exercise 5-4\n## If you are given three sticks, you may or may not be able to arrange them in a triangle. For example, if one of the sticks is 12 inches long and the other two are one inch long, you will not be able to get the short sticks to meet in the middle. For any three lengths, there is a simple test to see if it is possible to form a triangle:\n\n## TIP\n## If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle. Otherwise, you can. (If the sum of two lengths equals the third, they form what is called a “degenerate” triangle.)\n\n## 1. Write a function named istriangle that takes three integers as arguments, and that prints either “Yes” or “No”, depending on whether you can or cannot form a triangle from sticks with the given lengths.\nprintln(\"Ans 1: \")\n\nfunction istriangle(a, b, c)\n   return (((a + b) > c) && ((b + c) > a) && ((c + a) > b)) ? \"Yes\" : \"No\"\nend\n\nprintln(istriangle(13, 1, 1))\nprintln(istriangle(4, 3, 5))\n\n## 2. Write a function that prompts the user to input three stick lengths, converts them to integers, and uses istriangle to check whether sticks with the given lengths can form a triangle.\nprintln(\"Ans 2: \")\n\nfunction check_is_triangle()\n    print(\"Enter the first side: \")\n    a = parse(Int64, readline())\n    print(\"Enter the second side: \")\n    b = parse(Int64, readline())\n    print(\"Enter the third side: \")\n    c = parse(Int64, readline())\n\n    println(istriangle(a, b, c))\nend\n\ncheck_is_triangle()\n\nprintln(\"End.\")\n", "meta": {"hexsha": "3b3acfbca2604f1f56f9ad229b97ffcd35a2065b", "size": 1508, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter5/ex4.jl", "max_stars_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_stars_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-13T14:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T14:11:30.000Z", "max_issues_repo_path": "Chapter5/ex4.jl", "max_issues_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_issues_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter5/ex4.jl", "max_forks_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_forks_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3529411765, "max_line_length": 339, "alphanum_fraction": 0.7022546419, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7644108656939669}}
{"text": "export simple_psf\nexport jinc_psf\n\n\n # shift frequency to center if `shift=true` \n # and `norm` the sum to 1\nfunction shift_and_norm(psf, shift, norm)\n    if norm\n        psf ./= sum(psf)\n    end\n\n    if shift\n        psf = fftshift(psf)\n    end\n    return psf\nend\n\n\n\"\"\"\n    simple_psf(psf_size, radius; shift=false)\n\nGeneration of an approximate 2D PSF.\n`psf_size` is the output size of the PSF. The PSF will be centered\naround the point [1, 1],\n`radius` indicates the pupil diameter in pixel from which the PSF is generated.\n\n# Examples\n```julia-repl\njulia> simple_psf([5, 5], 2)\n5×5 Array{Float64,2}:\n 0.36       0.104721    0.0152786    0.0152786    0.104721\n 0.104721   0.0304627   0.00444444   0.00444444   0.0304627\n 0.0152786  0.00444444  0.000648436  0.000648436  0.00444444\n 0.0152786  0.00444444  0.000648436  0.000648436  0.00444444\n 0.104721   0.0304627   0.00444444   0.00444444   0.0304627\n```\n\"\"\"\nfunction simple_psf(psf_size, radius; shift=false)\n    mask = rr(psf_size) .<= radius\n    mask_ft = fft(mask)\n    psf = abs2.(mask_ft)\n    return shift_and_norm(psf, shift, true) \nend\n\n\n\"\"\"\n    jinc_psf(psf_size, L, radius[, f]; λ=550e-9, shift=false)\n\nGenerate the normalized, incoherent 2D jinc PSF of a circular aperture.\n`psf_size` is output array shape. `L` is the width of the array\nexpressed in meter. `radius` is the aperture radius in meter.\nKeyword arguments `λ` and `f=100e-3` represent wavelength and focal\nlength of the lens respectively.\n\nReference: Mertz, J. (2019). Introduction to Optical Microscopy (2nd ed.).\n\"\"\"\nfunction jinc_psf(psf_size, L, radius, f=100e-3; λ=550e-9, shift=false)\n    κ = calc_κ(λ) \n    Δk⊥ = 2 * κ * radius / f\n    # create real output psf\n    \n    psf = zeros(Float64, psf_size)\n    # calculate each point\n    for (j, x) in enumerate(fftpos(L, psf_size[2]))\n        for (i, y) in enumerate(fftpos(L, psf_size[1]))\n            r = sqrt(x^2 + y^2)\n            psf[i, j] = jinc(π * Δk⊥ * r).^2\n        end\n    end\n    # shift center to top left corner\n    psf = ifftshift(psf)\n    return shift_and_norm(psf, shift, true) \nend\n", "meta": {"hexsha": "015035c62140cc66368720b360e7cf468e31ac85", "size": 2078, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/psf.jl", "max_stars_repo_name": "JuliaPhysics/PhysicalOptics", "max_stars_repo_head_hexsha": "47efb1d816756fe7ea57b01061776cad8dbe47c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2020-11-04T11:52:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T10:13:22.000Z", "max_issues_repo_path": "src/psf.jl", "max_issues_repo_name": "JuliaPhysics/PhysicalOptics", "max_issues_repo_head_hexsha": "47efb1d816756fe7ea57b01061776cad8dbe47c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-01-06T12:58:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T13:48:37.000Z", "max_forks_repo_path": "src/psf.jl", "max_forks_repo_name": "JuliaPhysics/PhysicalOptics", "max_forks_repo_head_hexsha": "47efb1d816756fe7ea57b01061776cad8dbe47c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-05T09:40:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T23:19:30.000Z", "avg_line_length": 28.0810810811, "max_line_length": 79, "alphanum_fraction": 0.6612127045, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7644108580998289}}
{"text": "@doc raw\"\"\"\n# Hermite's Interpolating Polynomials\n\nImplements a two point Hermite inter-/extrapolation function which passes\nthrough the function and its first derivative for the interval ``[0,1]``.\nThe polynomial is determined by four constraint equations, matching the\nfunction and its derivative at the points ``0`` and ``1``.\n\nCall with one of the following methods\n```julia\n_hermite_extrapolation!(t₀, t₁, x₀, x₁, ẋ₀, ẋ₁, t, x)\n_hermite_extrapolation!(t₀, t₁, x₀, x₁, ẋ₀, ẋ₁, t, x, ẋ)\n_hermite_extrapolation!(v, t₀, t₁, x₀, x₁, t, x)\n_hermite_extrapolation!(v, t₀, t₁, x₀, x₁, t, x, ẋ)\n```\n\nwhere\n\n* `t₀`: first  sample time $t_0$\n* `t₁`: second sample time $t_1$\n* `x₀`: first  solution value $x_0 = x(t_0)$\n* `x₁`: second solution value $x_1 = x(t_1)$\n* `ẋ₀`: first  vector field value $ẋ_0 = v(t_0, x(t_0))$\n* `ẋ₁`: second vector field value $ẋ_1 = v(t_1, x(t_1))$\n* `v`:  function to compute vector field with signature `v(t,x,ẋ)`\n* `t`:  time $t$ to extrapolate\n* `x`:  extrapolated solution value $x(t)$\n* `v`:  extrapolated vector field value $ẋ(t)$\n\n\n#### Derivation\n\nThe interpolation works as follows:\nStart by defining the 3rd degree polynomial and its derivative by\n```math\n\\begin{aligned}\ng(x) &= a_0 + a_1 x + a_2 x^2 + a_3 x^3 , \\\\\ng'(x) &= a_1 + 2 a_2 x + 3 a_3 x^2 ,\n\\end{aligned}\n```\nand apply the constraints\n```math\n\\begin{aligned}\ng(0) &= f_0 & & \\Rightarrow & a_0 &= f_0 , \\\\\ng(1) &= f_1 & & \\Rightarrow & a_0 + a_1 + a_2 + a_3 &= f_1 , \\\\\ng'(0) &= f'_0 & & \\Rightarrow & a_1 &= f'_0 , \\\\\ng'(1) &= f'_1 & & \\Rightarrow & a_1 + 2 a_2 + 3 a_3 &= f'_1 . \\\\\n\\end{aligned}\n```\nSolving for ``a_0, a_1, a_2, a_3`` leads to\n```math\n\\begin{aligned}\na_0 &= f_0 , &\na_1 &= f'_0 , &\na_2 &= - 3 f_0 + 3 f_1 - 2 f'_0 - f'_1 , &\na_3 &= 2 f_0 - 2 f_1 + f'_0 + f'_1 ,\n\\end{aligned}\n```\nso that the polynomial ``g(x)`` reads\n```math\ng(x) = f_0 + f'_0 x + (- 3 f_0 + 3 f_1 - 2 f'_0 - f'_1) x^2 + (2 f_0 - 2 f_1 + f'_0 + f'_1) x^3 .\n```\nThe function and derivative values can be factored out, so that ``g(x)`` can be rewritten as\n```math\ng(x) = f_0 (1 - 3 x^2 + 2 x^3) + f_1 (3 x^2 - 2 x^3) + f'_0 (x - 2 x^2 + x^3) + f'_1 (- x^2 + x^3) ,\n```\nor in generic form as\n```math\ng(x) = f_0 a_0(x) + f_1 a_1(x) + f'_0 b_0(x) + f'_1 b_1(x) ,\n```\nwith basis functions\n```math\n\\begin{aligned}\na_0 (x) &= 1 - 3 x^2 + 2 x^3 , &\nb_0 (x) &= x - 2 x^2 + x^3 , \\\\\na_1 (x) &= 3 x^2 - 2 x^3 , &\nb_1 (x) &= - x^2 + x^3 .\n\\end{aligned}\n```\nThe derivative ``g'(x)`` accordingly reads\n```math\ng'(x) = f_0 a'_0(x) + f_1 a'_1(x) + f'_0 b'_0(x) + f'_1 b'_1(x) ,\n```\nwith\n```math\n\\begin{aligned}\na'_0 (x) &= - 6 x + 6 x^2 , &\nb'_0 (x) &= 1 - 4 x + 3 x^2 , \\\\\na'_1 (x) &= 6 x - 6 x^2 , &\nb'_1 (x) &= - 2 x + 3 x^2 .\n\\end{aligned}\n```\nThe basis functions ``a_0``and ``a_1`` are associated with the function\nvalues at ``x_0`` and ``x_1``, respectively, while the basis functions\n``b_0`` and ``b_1`` are associated with the derivative values at\n``x_0`` and ``x_1``.\nThe basis functions satisfy the following relations,\n```math\n\\begin{aligned}\na_i (x_j) &= \\delta_{ij} , &\nb_i (x_j) &= 0 , &\na'_i (x_j) &= 0 , &\nb'_i (x_j) &= \\delta_{ij} , &\ni,j &= 0, 1 ,\n\\end{aligned}\n```\nwhere ``\\delta_{ij}`` denotes the Kronecker-delta, so that\n```math\n\\begin{aligned}\ng(0) &= f_0 , &\ng(1) &= f_1 , &\ng'(0) &= f'_0 , &\ng'(1) &= f'_1 .\n\\end{aligned}\n```\n\"\"\"\nfunction _hermite_extrapolation! end\n\n\nfunction _hermite_extrapolation!(t₀::TT, t₁::TT, x₀::AbstractArray{DT}, x₁::AbstractArray{DT}, ẋ₀::AbstractArray{DT}, ẋ₁::AbstractArray{DT}, t::TT, x::AbstractArray{DT}) where {DT,TT}\n    local a₀::TT\n    local a₁::TT\n    local b₀::TT\n    local b₁::TT\n    local Δt = t₁ - t₀\n    local s = (t - t₀) / Δt\n\n    # Interpolate x at t\n    if t == t₀\n        x .= x₀\n    elseif t == t₁\n        x .= x₁\n    else\n        a₁ = 3s^2 - 2s^3\n        a₀ = 1 - a₁\n        b₁ = s^2*(s-1)\n        b₀ = s*(1-s)+b₁\n        x .= a₀ .* x₀ .+ a₁ .* x₁ .+ b₀ .* Δt .* ẋ₀ .+ b₁ .* Δt .* ẋ₁\n    end\n\n    return x\nend\n\nfunction _hermite_extrapolation!(t₀::TT, t₁::TT, x₀::AbstractArray{DT}, x₁::AbstractArray{DT}, ẋ₀::AbstractArray{DT}, ẋ₁::AbstractArray{DT}, t::TT, x::AbstractArray{DT}, ẋ::AbstractArray{DT}) where {DT,TT}\n    local a₀::TT\n    local a₁::TT\n    local b₀::TT\n    local b₁::TT\n    local Δt = t₁ - t₀\n    local s = (t - t₀) / Δt\n\n    _hermite_extrapolation!(t₀, t₁, x₀, x₁, ẋ₀, ẋ₁, t, x)\n\n    # Interpolate ẋ at t\n    if t == t₀\n        ẋ .= ẋ₀\n    elseif t == t₁\n        ẋ .= ẋ₁\n    else\n        a₁ = (6s - 6s^2) / Δt\n        a₀ = - a₁\n        b₁ = s*(3s-2)\n        b₀ = 1-2s+b₁\n        ẋ .= a₀ .* x₀ .+ a₁ .* x₁ .+ b₀ .* ẋ₀ .+ b₁ .* ẋ₁\n    end\n\n    return (x, ẋ)\nend\n\nfunction _get_velocities(v::Function, t₀::TT, t₁::TT, x₀::AbstractArray{DT}, x₁::AbstractArray{DT}) where {DT,TT}\n    ẋ₀ = zero(x₀)\n    ẋ₁ = zero(x₁)\n    v(t₀, x₀, ẋ₀)\n    v(t₁, x₁, ẋ₁)\n    return (ẋ₀, ẋ₁)\nend\n\nfunction _hermite_extrapolation!(v::Function, t₀::TT, t₁::TT, x₀::AbstractArray{DT}, x₁::AbstractArray{DT}, t::TT, x::AbstractArray{DT}) where {DT,TT}\n    _hermite_extrapolation!(t₀, t₁, x₀, x₁, _get_velocities(v, t₀, t₁, x₀, x₁)..., t, x)\nend\n\nfunction _hermite_extrapolation!(v::Function, t₀::TT, t₁::TT, x₀::AbstractArray{DT}, x₁::AbstractArray{DT}, t::TT, x::AbstractArray{DT}, ẋ::AbstractArray{DT}) where {DT,TT}\n    _hermite_extrapolation!(t₀, t₁, x₀, x₁, _get_velocities(v, t₀, t₁, x₀, x₁)..., t, x, ẋ)\nend\n\n\n\nstruct HermiteExtrapolation{T} <: Extrapolation\n    t₀::T\n    t₁::T\n    Δt::T\n\n    function HermiteExtrapolation{T}(t₀, t₁) where {T}\n        new(t₀, t₁, t₁-t₀)\n    end\nend\n\nfunction HermiteExtrapolation(t₀::T, t₁::T) where {T}\n    HermiteExtrapolation{T}(t₀, t₁)\nend\n\n\nfunction GeometricBase.evaluate!(int::HermiteExtrapolation{TT}, x₀::AbstractArray{DT}, x₁::AbstractArray{DT}, ẋ₀::AbstractArray{DT}, ẋ₁::AbstractArray{DT}, t::TT, x::AbstractArray{DT}) where {DT,TT}\n    _hermite_extrapolation!(int.t₀, int.t₁, x₀, x₁, ẋ₀, ẋ₁, t, x)\nend\n\nfunction GeometricBase.evaluate!(int::HermiteExtrapolation{TT}, x₀::AbstractArray{DT}, x₁::AbstractArray{DT}, ẋ₀::AbstractArray{DT}, ẋ₁::AbstractArray{DT}, t::TT, x::AbstractArray{DT}, ẋ::AbstractArray{DT}) where {DT,TT}\n    _hermite_extrapolation!(int.t₀, int.t₁, x₀, x₁, ẋ₀, ẋ₁, t, x, ẋ)\nend\n", "meta": {"hexsha": "ab708aaab65603d82974178bdd0ee84527f57e70", "size": 6229, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/integrators/extrapolation/hermite.jl", "max_stars_repo_name": "JuliaGNI/GeometricIntegrators.jl", "max_stars_repo_head_hexsha": "bf1ca810d75e43c1d89e4981beea35451858155a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-12-29T10:41:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T11:48:39.000Z", "max_issues_repo_path": "src/integrators/extrapolation/hermite.jl", "max_issues_repo_name": "JuliaGNI/GeometricIntegrators.jl", "max_issues_repo_head_hexsha": "bf1ca810d75e43c1d89e4981beea35451858155a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2020-11-16T16:45:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T17:51:11.000Z", "max_forks_repo_path": "src/integrators/extrapolation/hermite.jl", "max_forks_repo_name": "michakraus/GeometricIntegrators.jl", "max_forks_repo_head_hexsha": "fcca462f25a1f9d5ff0954d5d71ef7cd1389ab3e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-05T12:54:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T18:19:13.000Z", "avg_line_length": 29.6619047619, "max_line_length": 223, "alphanum_fraction": 0.5898218013, "num_tokens": 2693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7644108580998289}}
{"text": "### Activation functions.\n\nfunction activation_function_selector(activation::ASCIIString)\n\tif activation == \"exponential\"\n\t\treturn activation, exponential_activation!, exponential_backward!\n\telseif activation == \"leaky_rectified_linear\"\n\t\treturn activation, leaky_rectified_linear_activation!, leaky_rectified_linear_backward!\n\telseif activation == \"rectified_linear\"\n\t\treturn activation, rectified_linear_activation!, rectified_linear_backward!\n\telseif activation == \"sigmoid\"\n\t\treturn activation, sigmoid_activation!, sigmoid_backward!\n\telseif activation == \"softmax\"\n\t\treturn activation, softmax_activation!, softmax_backward!\n\telseif activation == \"softplus\"\n\t\treturn activation, softplus_activation!, softplus_backward!\n\telseif activation == \"tanh\"\n\t\treturn activation, tanh_activation!, tanh_backward!\n\t# Else default to linear activations.\n\telse\n\t\treturn \"linear\", linear_activation!, linear_backward!\n\tend\nend\n\n### Exponential activations.\n\nfunction exponential_activation!{T<:FloatingPoint}(NET::Vector{T}, ACT::Vector{T})\n\t@inbounds begin\n\t\tfor i = 1:length(NET)\n\t\t\tACT[i] = exp(NET[i])\n\t\tend\n\tend\nend\n\nfunction exponential_backward!{T<:FloatingPoint}(NET::Vector{T}, ACT::Vector{T}, DELTAS_ABOVE::Vector{T}, DE_DNET::Vector{T})\n\t@inbounds begin\n\t\tfor o = 1:length(NET)\n\t\t\tDE_DNET[o] = DELTAS_ABOVE[o] * ACT[o]\n\t\tend\n\tend\nend\n\n### Linear activations.\n\nfunction linear_activation!{T<:FloatingPoint}(NET::Vector{T}, ACT::Vector{T})\n\t@inbounds begin\n\t\tfor i = 1:length(NET)\n\t\t\tACT[i] = NET[i]\n\t\tend\n\tend\nend\n\nfunction linear_backward!{T<:FloatingPoint}(NET::Vector{T}, ACT::Vector{T}, DELTAS_ABOVE::Vector{T}, DE_DNET::Vector{T})\n\t@inbounds begin\n\t\tfor o = 1:length(NET)\n\t\t\tDE_DNET[o] = DELTAS_ABOVE[o]\n\t\tend\n\tend\nend\n\n### Leaky rectified linear activations.\n\nfunction leaky_rectified_linear_activation!{T<:FloatingPoint}(NET::Vector{T}, ACT::Vector{T})\n\t@inbounds begin\n\t\tfor i = 1:length(NET)\n\t\t\tif NET[i] > 0.0\n\t\t\t\tACT[i] = NET[i]\n\t\t\telse\n\t\t\t\tACT[i] = 0.01 * NET[i]\n\t\t\tend\n\t\tend\n\tend\nend\n\nfunction leaky_rectified_linear_backward!{T<:FloatingPoint}(NET::Vector{T}, ACT::Vector{T}, DELTAS_ABOVE::Vector{T}, DE_DNET::Vector{T})\n\t@inbounds begin\n\t\tfor o = 1:length(NET)\n\t\t\tif NET[o] > 0.0\n\t\t\t\tDE_DNET[o] = DELTAS_ABOVE[o]\n\t\t\telse\n\t\t\t\tDE_DNET[o] = DELTAS_ABOVE[o] * 0.01\n\t\t\tend\n\t\tend\n\tend\nend\n\n### Rectified linear activations.\n\nfunction rectified_linear_activation!{T<:FloatingPoint}(NET::Vector{T}, ACT::Vector{T})\n\t@inbounds begin\n\t\tfor i = 1:length(NET)\n\t\t\tif NET[i] > 0.0\n\t\t\t\tACT[i] = NET[i]\n\t\t\telse\n\t\t\t\tACT[i] = 0.0\n\t\t\tend\n\t\tend\n\tend\nend\n\nfunction rectified_linear_backward!{T<:FloatingPoint}(NET::Vector{T}, ACT::Vector{T}, DELTAS_ABOVE::Vector{T}, DE_DNET::Vector{T})\n\t@inbounds begin\n\t\tfor o = 1:length(NET)\n\t\t\tif NET[o] > 0.0\n\t\t\t\tDE_DNET[o] = DELTAS_ABOVE[o]\n\t\t\telse\n\t\t\t\tDE_DNET[o] = 0.0\n\t\t\tend\n\t\tend\n\tend\nend\n\n### Sigmoid activations.\n\nfunction sigmoid_activation!{T<:FloatingPoint}(NET::Vector{T}, ACT::Vector{T})\n\t@inbounds begin\n\t\tfor i = 1:length(NET)\n\t\t\tACT[i] = 1.0 / (1.0 + exp(-NET[i]))\n\t\tend\n\tend\nend\n\nfunction sigmoid_backward!{T<:FloatingPoint}(NET::Vector{T}, ACT::Vector{T}, DELTAS_ABOVE::Vector{T}, DE_DNET::Vector{T})\n\t@inbounds begin\n\t\tfor o = 1:length(NET)\n\t\t\tDE_DNET[o] = DELTAS_ABOVE[o] * ACT[o] * (1.0 - ACT[o])\n\t\tend\n\tend\nend\n\n### Softmax activations.\n\nfunction softmax_activation!{T<:FloatingPoint}(NET::Vector{T}, ACT::Vector{T})\n\t@inbounds begin\n\t\tfor j = 1:size(NET, 2)\n\t\t\t# Get maximum net value (for numerical stability).\n\t\t\tmaxnet::T = -Inf\n\t\t\tfor i = 1:length(NET)\n\t\t\t\tif NET[i] > maxnet\n\t\t\t\t\tmaxnet = NET[i]\n\t\t\t\tend\n\t\t\tend\n\t\t\t# Get sum of exponentials.\n\t\t\texpsum::T = 0.0\n\t\t\tfor i = 1:length(NET)\n\t\t\t\tACT[i] = exp(NET[i] - maxnet)\n\t\t\t\texpsum += ACT[i]\n\t\t\tend\n\t\t\t# Set activations.\n\t\t\tfor i = 1:length(NET)\n\t\t\t\tACT[i] ./= expsum\n\t\t\tend\n\t\tend\n\tend\nend\n\nfunction softmax_backward!{T<:FloatingPoint}(NET::Vector{T}, ACT::Vector{T}, DELTAS_ABOVE::Vector{T}, DE_DNET::Vector{T})\n\t@inbounds begin\n\t\tno = length(NET)\n\t\tfor o = 1:no\n\t\t\tDE_DNET[o] = 0.0\n\t\t\tfor oo = 1:no\n\t\t\t\tif o == oo\n\t\t\t\t\tDE_DNET[o] += DELTAS_ABOVE[oo] * ACT[o] * (1.0 - ACT[o])\n\t\t\t\telse\n\t\t\t\t\tDE_DNET[o] -= DELTAS_ABOVE[oo] * ACT[o] * ACT[oo]\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\nend\n\n### Softplus activations.\n\nfunction softplus_activation!{T<:FloatingPoint}(NET::Vector{T}, ACT::Vector{T})\n\t@inbounds begin\n\t\tfor i = 1:length(NET)\n\t\t\tACT[i] = log(1.0 + exp(NET[i]))\n\t\tend\n\tend\nend\n\nfunction softplus_backward!{T<:FloatingPoint}(NET::Vector{T}, ACT::Vector{T}, DELTAS_ABOVE::Vector{T}, DE_DNET::Vector{T})\n\t@inbounds begin\n\t\tfor o = 1:length(NET)\n\t\t\texpx = exp(NET[o])\n\t\t\tDE_DNET[o] = DELTAS_ABOVE[o] * expx / (1.0 + expx)\n\t\tend\n\tend\nend\n\n### Tanh activations.\n\nfunction tanh_activation!{T<:FloatingPoint}(NET::Vector{T}, ACT::Vector{T})\n\t@inbounds begin\n\t\tfor i = 1:length(NET)\n\t\t\tACT[i] = tanh(NET[i])\n\t\tend\n\tend\nend\n\nfunction tanh_backward!{T<:FloatingPoint}(NET::Vector{T}, ACT::Vector{T}, DELTAS_ABOVE::Vector{T}, DE_DNET::Vector{T})\n\t@inbounds begin\n\t\tfor o = 1:length(NET)\n\t\t\tDE_DNET[o] = DELTAS_ABOVE[o] * (1.0 - ACT[o] * ACT[o])\n\t\tend\n\tend\nend\n", "meta": {"hexsha": "601407fe6522cc274e6e45ccbe9bebdaab55910d", "size": 5049, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/activation_functions.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/StackedNets.jl-cde04a67-da5f-5e53-93c0-2a9e1e7feaac", "max_stars_repo_head_hexsha": "c18da9d82faa41042a7e4425438a249e5e57691f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/activation_functions.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/StackedNets.jl-cde04a67-da5f-5e53-93c0-2a9e1e7feaac", "max_issues_repo_head_hexsha": "c18da9d82faa41042a7e4425438a249e5e57691f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/activation_functions.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/StackedNets.jl-cde04a67-da5f-5e53-93c0-2a9e1e7feaac", "max_forks_repo_head_hexsha": "c18da9d82faa41042a7e4425438a249e5e57691f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2740384615, "max_line_length": 136, "alphanum_fraction": 0.679342444, "num_tokens": 1673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7643846917926276}}
{"text": "\"\"\"\n    LogNumber{S,L}\n\nRepresent a real or complex number in terms of its sign and logarithm.\n\nThis is a hack around the limitation that standard floating-point\ntypes link the bitcount of the exponent to that of the mantissa, which\nmakes it impossible to represent very large or small values without\nsimultaneously increasing the precision of the representation. The\ndrawback of this hack is that values x close to 1 have a larger relative\naccuracy than values far away from 1 since\n\n    1 - exp(l*(1±ε)) / exp(l) == 1 - exp(±l*ε) ≈ ∓l*ε.\n\nIt remains to be seen whether this has any practical relevance.\n\nA better workaround would be to create a floating-point type with\narbitrary exponent and mantissa.\n\"\"\"\nstruct LogNumber{S,L} <: Number\n    sign::S\n    logabs::L\nend\n\nLogNumber(x::Number) where {S,L} = LogNumber(sign(x),logabs(x))\nLogNumber{S,L}(x::Number) where {S,L} = LogNumber{S,L}(sign(x),logabs(x))\nBase.AbstractFloat(x::LogNumber) = x.sign*exp(x.logabs)\n\nBase.sign(x::LogNumber) = x.sign\n\n\"\"\"\n    logabs(x) -> log(abs(x))\n\"\"\"\nlogabs(x::Number) = log(abs2(x))/2\nlogabs(x::LogNumber) = x.logabs\n\nBase.promote_rule(::Type{LogNumber{S,L}}, ::Type{T}) where {S,L,T<:Number} =\n    LogNumber{promote_type(S,typeof(sign(one(T)))), promote_type(L,typeof(logabs(one(T))))}\n\nBase.:*(x::LogNumber,y::LogNumber) = LogNumber(x.sign * y.sign, x.logabs + y.logabs)\nBase.:/(x::LogNumber,y::LogNumber) = LogNumber(x.sign * conj(y.sign), x.logabs - y.logabs)\n", "meta": {"hexsha": "7dc26b6a88bf43abaf05b9e066d9b45fbe08b3ec", "size": 1452, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LogNumbers.jl", "max_stars_repo_name": "ettersi/ApproxTools.jl", "max_stars_repo_head_hexsha": "5a14019a3ed7a545c3446a7dd03b4584adf6ff46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LogNumbers.jl", "max_issues_repo_name": "ettersi/ApproxTools.jl", "max_issues_repo_head_hexsha": "5a14019a3ed7a545c3446a7dd03b4584adf6ff46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-03-16T15:54:22.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-09T16:37:30.000Z", "max_forks_repo_path": "src/LogNumbers.jl", "max_forks_repo_name": "ettersi/ApproxTools.jl", "max_forks_repo_head_hexsha": "5a14019a3ed7a545c3446a7dd03b4584adf6ff46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5714285714, "max_line_length": 91, "alphanum_fraction": 0.7079889807, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7643846861062769}}
{"text": "module _SlopEn\nexport SlopEn\nusing GroupSlices\n    \"\"\"\n        Slop = SlopEn(Sig) \n\n    Returns the slope entropy (`Slop`) estimates for embedding dimensions\n    [2, ..., m] of the data sequence (`Sig`) using the default parameters:\n    embedding dimension = 2, time delay = 1, \n    angular thresholds = [5 45],  logarithm = base 2 \n\n        Slop = SlopEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, Lvls::AbstractArray{T,1} where T<:Real=[5, 45], Logx::Real=2, Norm::Bool=true)\n\n    Returns the slope entropy (`Slop`) estimate of the data sequence (`Sig`)  \n    using the specified 'keyword' arguments:\n\n    # Arguments:\n    `m`     - Embedding Dimension, an integer > 1   \t\\n\n              SlopEn returns estimates for each dimension [2,...,m]\n    `tau`   - Time Delay, a positive integer    \\n\n    `Lvls`  - Angular thresolds, a vector of monotonically increasing   \n              values in the range [0 90] degrees.\\n\n    `Logx`  - Logarithm base, a positive scalar (enter 0 for natural log)   \\n\n    `Norm`  - Normalisation of SlopEn value, a boolean operator: \\n\n              [false]  no normalisation\n              [true]   normalises w.r.t. the number of patterns found (default)\n\n    # See also `PhasEn`, `GridEn`, `MSEn`, `CoSiEn`, `SampEn`, `ApEn`\n\n    # References:\n        [1] David Cuesta-Frau,\n            \"Slope Entropy: A New Time Series Complexity Estimator Based on\n            Both Symbolic Patterns and Amplitude Information.\" \n            Entropy \n            21.12 (2019): 1167.\n\n    \"\"\"\n    function SlopEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1,\n         Lvls::AbstractArray{T,1} where T<:Real=[5, 45], Logx::Real=2, Norm::Bool=true)\n        \n    Logx == 0 ? Logx = exp(1) : nothing\n    (size(Sig,1) >10) ? nothing :  error(\"Sig:   must be a numeric vector\")\n    (m > 1) ? nothing :  error(\"m:     must be an integer > 1\")\n    (tau>0) ? nothing :  error(\"tau:   must be an integer > 0\")\n    (length(Lvls)>1 && all(diff(Lvls).>0) && all(0 .< Lvls .< 90)) ? nothing :\n        error(\"Lvls:    must be a vector of 2 or more monotonically increasing\n                        values in the range [0 90] degrees\")\n    (Logx>0) ? nothing : error(\"Logx:  must be a positive number > 0\")\n\n    m = m-1;\n    Tx = atand.(Sig[1+tau:end] .- Sig[1:end-tau])\n    N = size(Tx,1)\n    Sx = zeros(Int,N,m)\n    Symbx = zeros(Int,size(Tx));\n    Slop = zeros(m)\n    sort!(Lvls)\n\n    for q = 2:length(Lvls)\n        Symbx[(Tx.<= Lvls[q]) .& (Tx .> Lvls[q-1])] .= q-1\n        Symbx[(Tx.>=-Lvls[q]) .& (Tx .<-Lvls[q-1])] .= -(q-1)\n        \n        if q == length(Lvls)\n            Symbx[Tx.> Lvls[q]] .= q\n            Symbx[Tx.<-Lvls[q]] .= -q\n        end\n    end\n\n    for k = 1:m\n        Sx[1:N-k+1,k] = Symbx[k:N]\n        Locs = groupslices(Sx[1:N-k+1,1:k])\n        p = []\n        [push!(p, sum(Locs.==n)) for n in unique(Locs)]\n            \n        Norm ? p ./=(N-k+1) : p./= length(p)\n\n        if Norm && round(sum(p)) != 1\n            @warn(\"Potential Error: Some permutations not accounted for!\")\n            print(round(sum(p)))\n        end\n        \n        Slop[k] = -sum(p.*log.(Logx, p))\n    end\n\n    return Slop\n    end\n\nend\n\"\"\"\nCopyright 2021 Matthew W. Flood, EntropyHub\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nFor Terms of Use see https://github.com/MattWillFlood/EntropyHub\n\n\"\"\"", "meta": {"hexsha": "aba52ccf56b6eaeb04af8fe762e4948589fd7a6a", "size": 3814, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/_SlopEn.jl", "max_stars_repo_name": "MattWillFlood/EntropyHub.jl", "max_stars_repo_head_hexsha": "d681c7fad3dbddaa708391b0afef1495c7dde20d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-06-19T19:20:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T16:13:41.000Z", "max_issues_repo_path": "src/_SlopEn.jl", "max_issues_repo_name": "MattWillFlood/EntropyHub.jl", "max_issues_repo_head_hexsha": "d681c7fad3dbddaa708391b0afef1495c7dde20d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-06-16T21:57:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T01:10:46.000Z", "max_forks_repo_path": "src/_SlopEn.jl", "max_forks_repo_name": "MattWillFlood/EntropyHub.jl", "max_forks_repo_head_hexsha": "d681c7fad3dbddaa708391b0afef1495c7dde20d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-15T05:41:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T05:41:21.000Z", "avg_line_length": 36.3238095238, "max_line_length": 161, "alphanum_fraction": 0.5894074463, "num_tokens": 1173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7643846857827017}}
{"text": "# ---\n# title: 878. Nth Magical Number\n# id: problem878\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Hard\n# categories: Math, Binary Search\n# link: <https://leetcode.com/problems/nth-magical-number/description/>\n# hidden: true\n# ---\n# \n# A positive integer is _magical_  if it is divisible by either A or B.\n# \n# Return the N-th magical number.  Since the answer may be very large, **return\n# it modulo**`10^9 + 7`.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: N = 1, A = 2, B = 3\n#     Output: 2\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: N = 4, A = 2, B = 3\n#     Output: 6\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: N = 5, A = 2, B = 4\n#     Output: 10\n#     \n# \n# **Example 4:**\n# \n#     \n#     \n#     Input: N = 3, A = 6, B = 4\n#     Output: 8\n#     \n# \n# \n# \n# **Note:**\n# \n#   1. `1 <= N <= 10^9`\n#   2. `2 <= A <= 40000`\n#   3. `2 <= B <= 40000`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "5e9469e55b1eecb081f12102b8a35c7ac1aabe8a", "size": 979, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/878.nth-magical-number.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/unresolved/878.nth-magical-number.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/unresolved/878.nth-magical-number.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 15.0615384615, "max_line_length": 79, "alphanum_fraction": 0.480081716, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7643846839088232}}
{"text": "\n# Single pendulums shall be solved numerically.\n#\nusing OrdinaryDiffEq, Elliptic, Printf, DiffEqPhysics, Statistics\n\nsol2q(sol) = [sol.u[i][j] for i in 1:length(sol.u), j in 1:length(sol.u[1])÷2]\nsol2p(sol) = [sol.u[i][j] for i in 1:length(sol.u), j in length(sol.u[1])÷2+1:length(sol.u[1])]\nsol2tqp(sol) = (sol.t, sol2q(sol), sol2p(sol))\n\n# The exact solutions of single pendulums can be expressed by the Jacobian elliptic functions.\n#\nsn(u, k) = Jacobi.sn(u, k^2) # the Jacobian sn function\n\n# Use PyPlot.\n#\nusing PyPlot\n\ncolorlist = [\n    \"#1f77b4\", \"#ff7f0e\", \"#2ca02c\", \"#d62728\", \"#9467bd\",\n    \"#8c564b\", \"#e377c2\", \"#7f7f7f\", \"#bcbd22\", \"#17becf\",\n]\ncc(k) = colorlist[mod1(k, length(colorlist))]\n\n# plot the sulution of a Hamiltonian problem\n#\nfunction plotsol(sol::ODESolution)\n    local t, q, p\n    t, q, p = sol2tqp(sol)\n    local d = size(q)[2]\n    for j in 1:d\n        j_str = d > 1 ? \"[$j]\" : \"\"\n        plot(t, q[:,j], color=cc(2j-1), label=\"q$(j_str)\", lw=1)\n        plot(t, p[:,j], color=cc(2j),   label=\"p$(j_str)\", lw=1, ls=\"--\")\n    end\n    grid(ls=\":\")\n    xlabel(\"t\")\n    legend()\nend\n\n# plot the solution of a Hamiltonian problem on the 2D phase space\n#\nfunction plotsol2(sol::ODESolution)\n    local t, q, p\n    t, q, p = sol2tqp(sol)\n    local d = size(q)[2]\n    for j in 1:d\n        j_str = d > 1 ? \"[$j]\" : \"\"\n        plot(q[:,j], p[:,j], color=cc(j), label=\"(q$(j_str),p$(j_str))\", lw=1)\n    end\n    grid(ls=\":\")\n    xlabel(\"q\")\n    ylabel(\"p\")\n    legend()\nend\n\n# plot the energy of a Hamiltonian problem\n#\nfunction plotenergy(H, sol::ODESolution)\n    local t, q, p\n    t, q, p = sol2tqp(sol)\n    local energy = [H(q[i,:], p[i,:], nothing) for i in 1:size(q)[1]]\n    plot(t, energy, label=\"energy\", color=\"red\", lw=1)\n    grid(ls=\":\")\n    xlabel(\"t\")\n    legend()\n    local stdenergy_str = @sprintf(\"%.3e\", std(energy))\n    title(\"                    std(energy) = $stdenergy_str\", fontsize=10)\nend\n\n# plot the numerical and exact solutions of a single pendulum\n#\n# Warning: Assume q(0) = 0, p(0) = 2k.   (for the sake of laziness)\n#\nfunction plotcomparison(k, sol::ODESolution)\n    local t, q, p\n    t, q, p = sol2tqp(sol)\n    local y = sin.(q/2)\n    local y_exact = k*sn.(t, k) # the exact solution\n\n    plot(t, y,       label=\"numerical\", lw=1)\n    plot(t, y_exact, label=\"exact\",     lw=1, ls=\"--\")\n    grid(ls=\":\")\n    xlabel(\"t\")\n    ylabel(\"y = sin(q(t)/2)\")\n    legend()\n    local error_str = @sprintf(\"%.3e\", maximum(abs.(y - y_exact)))\n    title(\"maximum(abs(numerical - exact)) = $error_str\", fontsize=10)\nend\n\n# plot solution and energy\n#\nfunction plotsolenergy(H, integrator, Δt, sol::ODESolution)\n    local integrator_str = replace(\"$integrator\", r\"^[^.]*\\.\" => \"\")\n\n    figure(figsize=(10,8))\n\n    subplot2grid((21,20), ( 1, 0), rowspan=10, colspan=10)\n    plotsol(sol)\n\n    subplot2grid((21,20), ( 1,10), rowspan=10, colspan=10)\n    plotsol2(sol)\n\n    subplot2grid((21,20), (11, 0), rowspan=10, colspan=10)\n    plotenergy(H, sol)\n\n    suptitle(\"=====    $integrator_str,   Δt = $Δt    =====\")\nend\n\n# Solve a single pendulum\n#\nfunction singlependulum(k, integrator, Δt; t0 = 0.0, t1 = 100.0)\n    local H(p,q,params) = p[1]^2/2 - cos(q[1]) + 1\n    local q0 = [0.0]\n    local p0 = [2k]\n    local prob = HamiltonianProblem(H, p0, q0, (t0, t1))\n\n    local integrator_str = replace(\"$integrator\", r\"^[^.]*\\.\" => \"\")\n    @printf(\"%-25s\", \"$integrator_str:\")\n    sol = solve(prob, integrator, dt=Δt)\n    @time local sol = solve(prob, integrator, dt=Δt)\n\n    sleep(0.1)\n    figure(figsize=(10,8))\n\n    subplot2grid((21,20), ( 1, 0), rowspan=10, colspan=10)\n    plotsol(sol)\n\n    subplot2grid((21,20), ( 1,10), rowspan=10, colspan=10)\n    plotsol2(sol)\n\n    subplot2grid((21,20), (11, 0), rowspan=10, colspan=10)\n    plotenergy(H, sol)\n\n    subplot2grid((21,20), (11,10), rowspan=10, colspan=10)\n    plotcomparison(k, sol)\n\n    suptitle(\"=====    $integrator_str,   Δt = $Δt    =====\")\nend\n\n\n# Single pendulum\n\nk = rand()\nintegrator = VelocityVerlet()\nΔt = 0.1\nsinglependulum(k, integrator, Δt, t0=-20.0, t1=20.0)\n\n\n# Two single pendulums\n\nH(q,p,param) = sum(p.^2/2 .- cos.(q) .+ 1)\nq0 = pi*rand(2)\np0 = zeros(2)\nt0, t1 = -20.0, 20.0\nprob = HamiltonianProblem(H, q0, p0, (t0, t1))\n\nintegrator = VelocityVerlet()\nΔt = 0.1\nsol = solve(prob, integrator, dt=Δt)\n@time sol = solve(prob, integrator, dt=Δt)\n\nsleep(0.1)\nplotsolenergy(H, integrator, Δt, sol)\n\n\nSymplecticIntegrators = [\n    SymplecticEuler(),\n    VelocityVerlet(),\n    VerletLeapfrog(),\n    PseudoVerletLeapfrog(),\n    McAte2(),\n    Ruth3(),\n    McAte3(),\n    CandyRoz4(),\n    McAte4(),\n    CalvoSanz4(),\n    McAte42(),\n    McAte5(),\n    Yoshida6(),\n    KahanLi6(),\n    McAte8(),\n    KahanLi8(),\n    SofSpa10(),\n]\n\nk = 0.999\nΔt = 0.1\nfor integrator in SymplecticIntegrators\n    singlependulum(k, integrator, Δt)\nend\n\n\nk = 0.999\nΔt = 0.01\nfor integrator in SymplecticIntegrators[1:4]\n    singlependulum(k, integrator, Δt)\nend\n\n\nk = 0.999\nΔt = 0.001\nsinglependulum(k, SymplecticEuler(), Δt)\n\n\nk = 0.999\nΔt = 0.0001\nsinglependulum(k, SymplecticEuler(), Δt)\n\n\nusing DiffEqBenchmarks\nDiffEqBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])\n\n", "meta": {"hexsha": "ef271cae7d23eb6412cb9062cfafcbf5196d9047", "size": 5143, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/DynamicalODE/single_pendulums.jl", "max_stars_repo_name": "jamesjscully/DiffEqBenchmarks.jl", "max_stars_repo_head_hexsha": "4a47f59717f3166864fa4f1b96a0faa5a0db7764", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-23T11:26:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T11:46:34.000Z", "max_issues_repo_path": "script/DynamicalODE/single_pendulums.jl", "max_issues_repo_name": "jamesjscully/DiffEqBenchmarks.jl", "max_issues_repo_head_hexsha": "4a47f59717f3166864fa4f1b96a0faa5a0db7764", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-12T12:07:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-23T10:04:12.000Z", "max_forks_repo_path": "script/DynamicalODE/single_pendulums.jl", "max_forks_repo_name": "jamesjscully/DiffEqBenchmarks.jl", "max_forks_repo_head_hexsha": "4a47f59717f3166864fa4f1b96a0faa5a0db7764", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-12T00:28:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T00:28:16.000Z", "avg_line_length": 24.1455399061, "max_line_length": 95, "alphanum_fraction": 0.6013999611, "num_tokens": 1854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7643846802904961}}
{"text": "using Distributions\n\nf(x) = x^2 - 5 * x + 6\n\nfunction get_best_solution(soln)\n    best = soln[1]\n    for s in soln\n        if f(s) < f(best)\n            best = s\n        end\n    end\n    return best\nend\n\n\nfunction flower_pollination_algorithm(f;total_flowers=25,λ = 1.5,γ = 0.1,p = 0.8, MaxGenerations = 10)\n    flowers = rand(Float64, total_flowers)\n    L = Levy()\n\n    global_best = get_best_solution(flowers)\n    print(\"Start Global best:\", global_best)\n    println(\"Out of answers:\", flowers)\n    println(\"Best answer so far:\", global_best)\n\n    t = 1\n    while t < MaxGenerations\n        for i = 1:total_flowers\n            new_value = nothing\n            if rand() < p\n                new_value = flowers[i] + γ * rand(L) * (global_best - flowers[i])\n            else\n                xj = rand(1:total_flowers)\n                xk = rand(1:total_flowers)\n                new_value = flowers[i] + rand() * (xj - xk)\n            end\n            if f(new_value) < f(flowers[i])\n                flowers[i] = new_value\n            end\n        end\n        global_best = get_best_solution(flowers)\n        println(\"Global Best so far: \", global_best)\n        t = t + 1\n    end\n    return global_best\nend\n\nglobal_minimum=flower_pollination_algorithm(f,total_flowers=25,λ = 1.5,γ = 0.1,p = 0.8)\n\nprintln(\"Final Global Minimum: \", global_minimum)\n", "meta": {"hexsha": "8d127d3449af8db675af9cd24a5f37df120d538b", "size": 1341, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FPA.jl", "max_stars_repo_name": "amir1m/bio-inspired", "max_stars_repo_head_hexsha": "ca965bf83bcc5a1935d80bcc7cb9b68a85ab115b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FPA.jl", "max_issues_repo_name": "amir1m/bio-inspired", "max_issues_repo_head_hexsha": "ca965bf83bcc5a1935d80bcc7cb9b68a85ab115b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FPA.jl", "max_forks_repo_name": "amir1m/bio-inspired", "max_forks_repo_head_hexsha": "ca965bf83bcc5a1935d80bcc7cb9b68a85ab115b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.82, "max_line_length": 102, "alphanum_fraction": 0.5704697987, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7643846802257811}}
{"text": "function stable_principal_component_pursuit(M, sigma;\n    threshold = 1e-6, solver_output=0)\n    \"\"\"\n    This function solves the stable principal component pursuit problem.\n\n    :param M: An arbitrary n-by-n matrix.\n    :param sigma: A parameter that controls the tradeoff between nuclear norm\n                  term and the L1 norm term in the objective function\n    :param threshold: Singular values in the output low rank matrix below\n                      threshold are set to 0. Entries in the output sparse\n                      matrix below threshold are set to 0 (Float64).\n    :param solver_output: Solver_output param to be passed to SCS (Int64).\n\n    :return: This function returns two values. The first value is a tuple of 2\n             n-by-n arrays that correspond to the solution of stable PCP (the\n             first element in the tuple is the matrix X and the second element\n             is the matrix Y). The second value is the optimal objective value\n             of the optimization problem (Float64).\n    \"\"\"\n    n = size(M)[1]\n    mu = (2 * n) ^ 0.5 * sigma\n\n    # Build stable PCP formulation using JuMP\n    m = Model(SCS.Optimizer)\n    set_optimizer_attribute(m, \"verbose\", solver_output)\n\n    @variable(m, L[i=1:n, j=1:n])\n    @variable(m, W_1[i=1:n, j=1:n])\n    @variable(m, W_2[i=1:n, j=1:n])\n    @variable(m, S[i=1:n, j=1:n])\n    @variable(m, S_abs[i=1:n, j=1:n])\n    @variable(m, error[i=1:n, j=1:n])\n\n    @constraint(m, [W_1 L; L' W_2] in PSDCone())\n    @constraint(m, [i=1:n, j=1:n], S_abs[i, j] >= S[i, j])\n    @constraint(m, [i=1:n, j=1:n], S_abs[i, j] >= -S[i, j])\n\n    @constraint(m, [i=1:n, j=1:n], (M[i, j] - L[i, j] - S[i, j])^2 <= error[i, j])\n\n    @objective(m, Min, 0.5 * sum(W_1[i, i] for i=1:n) +\n        0.5 * sum(W_2[i, i] for i=1:n) +\n        n^(-0.5) * sum(S_abs[i, j] for i=1:n, j=1:n) +\n        sum(error[i, j] for i=1:n, j=1:n)/(2*mu))\n\n    # Solve stable PCP\n    optimize!(m)\n\n    L_opt = value.(L)\n    S_opt = value.(S)\n\n    L_svd = svd(L_opt)\n    L_U = L_svd.U\n    L_S = L_svd.S\n    L_Vt = L_svd.Vt\n\n    for i = 1:n\n        if abs(L_S[i]) < threshold\n            L_S[i] = 0\n        end\n    end\n\n    L_opt = L_U * Diagonal(L_S) * L_Vt\n\n    for i = 1:n\n        for j = 1:n\n            if abs(S_opt[i, j]) < threshold\n                S_opt[i, j] = 0\n            end\n        end\n    end\n\n    return (L_opt, S_opt), objective_value(m)\n\nend;\n", "meta": {"hexsha": "548bdaea676cc3ce1f3516d395694c4859d57c04", "size": 2393, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SPCP.jl", "max_stars_repo_name": "NicholasJohnson2020/SparseLowRankSoftware", "max_stars_repo_head_hexsha": "824c9db34b3f3299ae1ffe195b29bf72f603a80c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-03T15:42:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T15:42:59.000Z", "max_issues_repo_path": "src/SPCP.jl", "max_issues_repo_name": "NicholasJohnson2020/SparseLowRankSoftware", "max_issues_repo_head_hexsha": "824c9db34b3f3299ae1ffe195b29bf72f603a80c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SPCP.jl", "max_forks_repo_name": "NicholasJohnson2020/SparseLowRankSoftware", "max_forks_repo_head_hexsha": "824c9db34b3f3299ae1ffe195b29bf72f603a80c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9066666667, "max_line_length": 82, "alphanum_fraction": 0.5666527372, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900945711678, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7643846763485936}}
{"text": "﻿using Unitful, UnitfulAstro\n\nimport PhysicalConstants.CODATA2018: g_n\n\nimport ..SfUnits: Angle, to_angle, Acceleration\n\nexport kinetic_energy, distance, duration, acceleration, projectile_displacement, projectile_velocity, \n\tprojectile_flight_time, projectile_apex, projectile_range, projectile_angle, projectile_angle_planetary\n\t\n# TODO: rename these when the underlying compilation issues have been resolved\nexport projectile_range_planetary\n# TODO: better names?\nexport projectile_peak_displacement_planetary\n\n\"\"\"\n\tkinetic_energy(m::Unitful.Mass, v::Unitful.Velocity)\n\t\nCompute the kinetic energy of a body with mass `m` travelling at velocity `v`.\n\nNo relativistic corrections are applied. Use `relativistic_kinetic_energy` if those are required.\n\"\"\"\nkinetic_energy(m::Unitful.Mass, v::Unitful.Velocity) = 0.5m*v^2 |> u\"J\"\n\n\"\"\"\n    distance(a::Unitful.Acceleration, t::Unitful.Time, initial_v::Unitful.Velocity = 0u\"m/s\")\n\t\nCompute the distance travelled in time `t` by a body with initial velocity `initial_v` and uniform acceleration `a`.\n\"\"\"\ndistance(a::Unitful.Acceleration, t::Unitful.Time, initial_v::Unitful.Velocity = 0u\"m/s\") = t*initial_v + a*t^2 / 2\n\n\"\"\"\n    duration(a::Unitful.Acceleration, d::Unitful.Length, initial_v::Unitful.Velocity = 0u\"m/s\")\n\t\nCompute the time taken for a body with initial velocity `initial_v` and uniform acceleration `a` to travel a distance of `d`.\n\"\"\"\nfunction duration(a::Unitful.Acceleration, d::Unitful.Length, initial_v::Unitful.Velocity = 0u\"m/s\")\n    if d < 0u\"m\"\n\t\tthrow(DomainError(d, \"Negative distances not allowed.\"))\n\tend\n\n\tif initial_v == 0u\"m/s\"\n\t\treturn sqrt(2d / a)\n\telseif a == 0u\"m/s^2\"\n\t\tif initial_v < 0u\"m/s\"\n\t\t\tthrow(DomainError(d, \"Negative initial velocities not allowed with zero acceleration.\"))\n\t\tend\n\t\n\t\treturn d / initial_v\n\tend\n\n    # at^2 + 2v_0t - 2d = 0\n    # ax^2 + bx + c\n\n    b = 2 * initial_v\n    c = -2d\n\n    discr = b^2 - 4*a*c\n\n    t1 = (-b + sqrt(discr))/(2a)\n    t2 = (-b - sqrt(discr))/(2a)\n\n    # the negative results aren't wrong, per se, but as the parameters are\n    # vector quantities the negative results aren't particularly interesting.    \n\n    if t1 < 0u\"s\"\n        return t2\n    elseif t2 < 0u\"s\"\n        return t1\n    else\n        return min(t1, t2)\n    end\nend\n\n\"\"\"\n    acceleration(d::Unitful.Length, v_final::Unitful.Velocity, v_initial::Unitful.Velocity = 0u\"m/s\")\n\t\nGiven a distance `d`, initial velocity `v_initial and desired velocity `v_final` compute the required uniform acceleration\n\"\"\"\nacceleration(d::Unitful.Length, v_final::Unitful.Velocity, v_initial::Unitful.Velocity = 0u\"m/s\") = (v_final^2 - v_initial^2) / 2d\n\n\"\"\"\n    projectile_displacement(v_0::Unitful.Velocity, θ::Angle, t::Unitful.Time; g::Acceleration = g_n)\n\t\nHorizontal and vertical displacement at time `t` of a projectile with initial velocity `v_0` and launch angle `θ` in a unitform gravitational acceleration `g`.\n\"\"\"\nprojectile_displacement(v_0::Unitful.Velocity, θ::Angle, t::Unitful.Time; g::Acceleration = g_n) =\n    [ v_0 * t * cos(θ), v_0 * t * sin(θ) - 0.5g * t^2 ]\n\n\"\"\"\n    projectile_displacement(v_0::Unitful.Velocity, t::Unitful.Time; g::Acceleration = g_n)\n\t\nVertical displacement at time `t` of a projectile launched vertically with initial velocity `v_0` in a unitform gravitational acceleration `g`.\n\"\"\"\nprojectile_displacement(v_0::Unitful.Velocity, t::Unitful.Time; g::Acceleration = g_n) = projectile_displacement(v_0, 90u\"°\", t, g = g)[2]\n\n\"\"\"\n    projectile_velocity(v_0::Unitful.Velocity, θ::Angle, t::Unitful.Time; g::Acceleration = g_n)\n\t\nHorizontal and vertical velocity at time `t` of a projectile with initial velocity `v_0` and launch angle `θ` in a unitform gravitational acceleration `g`.\n\"\"\"\nprojectile_velocity(v_0::Unitful.Velocity, θ::Angle, t::Unitful.Time; g::Acceleration = g_n) =\n    [ v_0 * cos(θ), v_0 * sin(θ) - g * t ]\n\n\"\"\"\n    projectile_velocity(v_0::Unitful.Velocity, t::Unitful.Time; g::Acceleration = g_n)\n\t\nVelocity at time `t` of a projectile launched vertically with initial velocity `v_0` in a unitform gravitational acceleration `g`.\n\"\"\"\nprojectile_velocity(v_0::Unitful.Velocity, t::Unitful.Time; g::Acceleration = g_n) = projectile_velocity(v_0, 90u\"°\", g, t)[2]\n\n\"\"\"\n    projectile_flight_time(v_0::Unitful.Velocity, θ::Angle = 90u\"°\"; g::Acceleration = g_n)\n\t\nCompute total flight time for a projectile launched at angle `θ` with initial velocity `v_0` in a uniform gravitation acceleration `g`.\n\nFlight is considered to be complete when vertical displacement returns to zero.\n\"\"\"\nprojectile_flight_time(v_0::Unitful.Velocity, θ::Angle = 90u\"°\"; g::Acceleration = g_n) = 2v_0 * sin(θ) / g |> u\"s\"\n\n\"\"\"\n    projectile_apex(v_0::Unitful.Velocity, θ::Angle = 90u\"°\"; g::Acceleration = g_n)\n\t\nHorizontal and vertical displacement of a projectile launched at angle `θ` with initial velocity `v_0` in a uniform gravitation acceleration `g` at the apex of its trajectory.\n\nDefault launch angle is 90° for maximum height.\n\"\"\"\nprojectile_apex(v_0::Unitful.Velocity, θ::Angle = 90u\"°\"; g::Acceleration = g_n) = [ v_0^2 * sin(2θ) / 2g,  v_0^2 * sin(θ)^2 / 2g ]\n\n\"\"\"\n    projectile_range(v_0::Unitful.Velocity, θ::Angle = 45u\"°\"; g::Acceleration = g_n)\n\t\nCompute range of a projectile launched at angle `θ` with initial velocity `v_0` in a uniform gravitation acceleration `g`.\n\nDefault launch angle is 45° for maximum range.\n\"\"\"\nprojectile_range(v_0::Unitful.Velocity, θ::Angle = 45u\"°\"; g::Acceleration = g_n) = (v_0^2 * sin(2θ)) / g\n\n\"\"\"\n    projectile_range(v_0::Unitful.Velocity, y_0::Unitful.Length, θ::Angle = 45u\"°\"; g::Acceleration = g_n)\n\t\nCompute range of a projectile launched from altitude `y_0` at angle `θ` with initial velocity `v_0` in a uniform gravitation acceleration `g`.\n\nRange is reached when vertical displacement is zero. Default launch angle is 45° for maximum range.\n\"\"\"\nprojectile_range(v_0::Unitful.Velocity, y_0::Unitful.Length, θ::Angle = 45u\"°\"; g::Acceleration = g_n) =\n\t(v_0 * cos(θ) / g) * (v_0 * sin(θ) + sqrt((v_0 * sin(θ))^2 + 2g * y_0))\n\t\n\"\"\"\n    projectile_range_planetary(v_0::Unitful.Velocity, r_planet::Unitful.Length = 1u\"Rearth\", θ::Angle = 45u\"°\"; g::Acceleration = g_n)\n\t\nCompute range of a projectile launched from altitude `y_0` at angle `θ` with initial velocity `v_0` on a spherical planet with radius `r_planet` and surface gravity `g`.\n\nNOTE: this should be called `projectile_range`, but weird internal compiler errors prevent that with this version of Julia (1.5.3).\n\"\"\"\nfunction projectile_range_planetary(v_0::Unitful.Velocity, θ::Angle = 45u\"°\", r_planet::Unitful.Length = 1u\"Rearth\"; g::Acceleration = g_n)\n\tv_rat2 = (v_0 / sqrt(r_planet * g))^2\n\t\n\tif v_rat2 > 1\n\t\tthrow(DomainError(\"Initial velocity exceeds orbital velocity; Range undefined\"))\n\tend\n\t\n\ta = v_0^2 * sin(2θ) / g\n\tb = sqrt(1 - (2 - v_rat2) * v_rat2 * cos(θ)^2)\n\t\n\treturn a / b |> u\"m\"\nend\n\nfunction projectile_peak_displacement_planetary(v_0::Unitful.Velocity, θ::Angle = 45u\"°\", r_planet::Unitful.Length = 1u\"Rearth\"; g::Acceleration = g_n)\n\tv_rat2 = (v_0 / sqrt(r_planet * g))^2\n\t\n\tif v_rat2 > 1\n\t\tthrow(DomainError(\"Initial velocity exceeds orbital velocity; Range undefined\"))\n\tend\n\t\n\ta = v_0^2 * sin(θ) / g\n\tb = 1 - v_rat2 + sqrt(1 - (2 - v_rat2) * v_rat2 * cos(θ)^2)\n\t\n\treturn a / b |> u\"m\"\nend\n\t\n\"\"\"\n    projectile_angle(v_0::Unitful.Velocity, d::Unitful.Length; g::Acceleration = g_n)\n\t\nCompute the possible launch angles for a projectile to reach a horizontal range of `d` given initial velocity `v_0` in a uniform gravitation acceleration `g`.\n\nThe shallow angle is the first result, the steep angle the second. A domain error is raised if the target is out of range.\n\"\"\"\nfunction projectile_angle(v_0::Unitful.Velocity, d::Unitful.Length; g::Acceleration = g_n)\n\tk = (g * d) / v_0^2\n\t\n\tif (k > 1)\n\t\tthrow(DomainError(\"Target out of range; no solutions\"))\n\tend\n\t\n\treturn ( 0.5asin(k) * 1u\"rad\" |> u\"°\", 45u\"°\" + (0.5acos(k) * 1u\"rad\" |> u\"°\") )\nend\n\t\n\"\"\"\n    projectile_angle(v_0::Unitful.Velocity, d::Unitful.Length, y::Unitful.Length; g::Acceleration = g_n)\n\t\nCompute the possible launch angles for a projectile to reach a horizontal range of `d` and altitude of `y` relative to the starting point given initial velocity `v_0` in a uniform gravitation acceleration `g`.\n\nThe shallow angle is the first result, the steep angle the second. A domain error is raised if the target is out of range.\n\"\"\"\nfunction projectile_angle(v_0::Unitful.Velocity, d::Unitful.Length, y::Unitful.Length; g::Acceleration = g_n)\n\tdet = v_0^4 - g * (g * d^2 + 2y * v_0^2)\n\t\n\tif (ustrip(det) < 0)\n\t\tthrow(DomainError(\"Target out of range; no solutions\"))\n\tend\n\t\n\ta = atan((v_0^2 + sqrt(det)) / (g * d)) * 1u\"rad\" |> u\"°\"\n\tb = atan((v_0^2 - sqrt(det)) / (g * d)) * 1u\"rad\" |> u\"°\"\n\t\n\tif a < b\n\t\treturn (a, b)\n\telse\n\t\treturn (b, a)\n\tend\nend\n\n\"\"\"\n    projectile_optimum_angle(v_0::Unitful.Velocity, r_planet::Unitful.Length = 1u\"Rearth\"; g::Acceleration = g_n)\n\"\"\"\nfunction projectile_optimum_angle(v_0::Unitful.Velocity, r_planet::Unitful.Length = 1u\"Rearth\"; g::Acceleration = g_n)\n\tv_rat2 = (v_0 / sqrt(r_planet * g))^2\n\t\n\tif v_rat2 > 0\n\t\tthrow(DomainError(\"Initial velocity exceeds orbital velocity; optimum angle undefined\"))\n\tend\n\t\n\treturn 0.5acos(v_rat2 / (2 - v_rat2)) * u\"rad\" |> u\"°\"\nend\n", "meta": {"hexsha": "dceec9ebf535c6b17bf114154c26e024069189da", "size": 9236, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kinematics.jl", "max_stars_repo_name": "icantbelieveitsnotphysics/SfPhysics", "max_stars_repo_head_hexsha": "c2bfd4733335ccc0b5605aff61e73efde3bffdd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kinematics.jl", "max_issues_repo_name": "icantbelieveitsnotphysics/SfPhysics", "max_issues_repo_head_hexsha": "c2bfd4733335ccc0b5605aff61e73efde3bffdd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-02-15T13:57:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-15T14:01:45.000Z", "max_forks_repo_path": "src/kinematics.jl", "max_forks_repo_name": "icantbelieveitsnotphysics/SfPhysics", "max_forks_repo_head_hexsha": "c2bfd4733335ccc0b5605aff61e73efde3bffdd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4700854701, "max_line_length": 209, "alphanum_fraction": 0.7038761369, "num_tokens": 2843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.7643846746041452}}
{"text": "function eller(n)\n    result = 1\n    answer,hw  = factor(n)\n    for i in 1:length(answer)\n        if hw[i] == 1\n            result *= answer[i]-1\n        else\n            result *= (answer[i]^hw[i] - answer[i]^(hw[i]-1))\n        end\n    end\n    return result\nend\n\nfunction factor(n)\n    answer = []\n    hw = []\n    for i in eratosphen(n)\n        if n%i==0\n            push!(answer,i)\n            push!(hw,1)\n            n=n/i\n            while n%i==0\n                hw[end]+=1\n                n=n/i\n            end\n        end\n    end\n    return answer,hw         \nend\n\nfunction eratosphen(n)\n    ser = fill(true,n)\n    ser[1] = false\n    k = 2\n    while k !== nothing && k<n \n        ser[k^2:k:end] .= false\n        k=findnext(ser, k+1)\n    end\n    return findall(ser)\nend", "meta": {"hexsha": "efc11b9af39dbd8f9ef9e57ac5466d9b413f3237", "size": 774, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "task_7_7.jl", "max_stars_repo_name": "Litger45/julia-algorithms-2", "max_stars_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "task_7_7.jl", "max_issues_repo_name": "Litger45/julia-algorithms-2", "max_issues_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "task_7_7.jl", "max_forks_repo_name": "Litger45/julia-algorithms-2", "max_forks_repo_head_hexsha": "ff8f650b314cc920e0d35238509a0838d4b0a5ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.35, "max_line_length": 61, "alphanum_fraction": 0.4431524548, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.963779943094681, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7643796061437232}}
{"text": "using Optim, Plots\n# method for contour\nrosenbrock(x1,x2) = (1.0 - x1)^2 + 100.0 * (x2 - x1^2)^2\n# method for optim\nrosenbrock(θ) = (1.0 - θ[1])^2 + 100.0 * (θ[2] - θ[1]^2)^2\nθ = zeros(2)\nb1 = range(0.0,stop=1.5,length=100) \nb2 = range(0.0,stop=1.5,length=100)\ncontour(b1,b2,(b1,b2)->rosenbrock(b1,b2),fill=true, c=:viridis)\nθs = zeros(100,2)\nfor i = 1:100\n    #global θ = optimize(rosenbrock, θ, GradientDescent(), Optim.Options(iterations=1)).minimizer\n    global θ = optimize(rosenbrock, θ, Newton(), Optim.Options(iterations=1)).minimizer\n    θs[i,:] = θ'\n    display(scatter!(θs[1:i,1], θs[1:i,2], legend=false))\n    sleep(0.1)\nend\nθs\n\n\n", "meta": {"hexsha": "2cff8bbce1a4075e35d18cee4b333af82addadf0", "size": 642, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/NonlinearOptimization/RosenbrockTrace.jl", "max_stars_repo_name": "Hiroakiyusheng/Econometrics", "max_stars_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "Examples/NonlinearOptimization/RosenbrockTrace.jl", "max_issues_repo_name": "Hiroakiyusheng/Econometrics", "max_issues_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "Examples/NonlinearOptimization/RosenbrockTrace.jl", "max_forks_repo_name": "Hiroakiyusheng/Econometrics", "max_forks_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 30.5714285714, "max_line_length": 97, "alphanum_fraction": 0.6339563863, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474233166328, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7643785566711387}}
{"text": "# Magnetic field topology in fusion research.\n\nusing Elliptic, SpecialFunctions\n\n\"\"\"\n    getB_bottle(x, y, z, distance, a, b, I1, I2) -> Vector{Float}\n\nGet magnetic field from a magnetic bottle.\nReference: https://en.wikipedia.org/wiki/Magnetic_mirror#Magnetic_bottles\n\n# Arguments\n- `x,y,z::Float`: location in [m].\n- `distance::Float`: distance between solenoids in [m].\n- `a::Float`: radius of each side coil in [m].\n- `b::Float`: radius of central coil in [m].\n- `I1::Float`: current in the solenoid times number of windings in side coils.\n- `I2::Float`: current in the central solenoid times number of windings in the\ncentral loop.\n\"\"\"\nfunction getB_bottle(x, y, z, distance, a, b, I1, I2)\n\n   r = √(x^2 + y^2) # distance from z-axis\n\n   # 1st loop\n   z₁ = z + 0.5*distance\n   k = √(4*r*a / (z₁^2 + (a + r)^2) )\n   K, E = ellipke(k)\n   Bz1 = μ₀*I1 / (2π*√(z₁^2+(a+r)^2)) * ((a^2-z₁^2-r^2)/(z₁^2+(r-a)^2)*E + K)\n   Br1 = μ₀*z₁*I1/(2π*r*√(z₁^2+(a+r)^2))*((z₁^2+r^2+a^2)/(z₁^2+(r-a)^2)*E - K)\n   Bx1 = Br1 * x / r\n   By1 = Br1 * y / r\n\n   # 2nd loop\n   z₂ = z - 0.5*distance\n   k = √(4*r*a / (z₂^2 + (a + r)^2) )\n   K, E = ellipke(k)\n   Bz2 = μ₀*I1 / (2π*√(z₂^2+(a+r)^2)) * ((a^2-z₂^2-r^2)/(z₂^2+(r-a)^2)*E + K)\n   Br2 = μ₀*z₂*I1/(2π*r*√(z₂^2+(a+r)^2))*((z₂^2+r^2+a^2)/(z₂^2+(r-a)^2)*E - K)\n   Bx2 = Br2 * x / r\n   By2 = Br2 * y / r\n\n   # central loop\n   z₃ = z\n   k = √(4*r*b / (z₃^2 + (b+r)^2) )\n   K, E = ellipke(k)\n   Bz3 = μ₀*I2 / (2π*√(z₃^2+(b+r)^2)) * ((b^2-z₃^2-r^2)/(z₃^2+(r-b)^2)*E + K)\n   Br3 = μ₀*z₃*I2/(2π*r*√(z₃^2+(b+r)^2))*((z₃^2+r^2+b^2)/(z₃^2+(r-b)^2)*E - K)\n   Bx3 = Br3 * x / r\n   By3 = Br3 * y / r\n\n   # total magnetic field\n   if x == 0.0 && y == 0.0\n      Bx = 0.0\n      By = 0.0\n      Bz = Bz1 + Bz2 + Bz3\n   else\n      Bx = Bx1 + Bx2 + Bx3\n      By = By1 + By2 + By3\n      Bz = Bz1 + Bz2 + Bz3\n   end\n   [Bx, By, Bz]\nend\n\n\"\"\"\n    getB_tokamak(x, y, z, a, b, ICoils, IPlasma)\n\nGet the magnetic field from a Tokamak topology consists of 16 coils.\nOriginal: https://github.com/BoschSamuel/Simulation-of-a-Tokamak-Fusion-Reactor/blob/master/Simulation2.m\n# Arguments\n- `x,y,z::Float`: location in [m].\n- `a::Float`: radius of each coil in [m].\n- `b::Float`: radius of central region in [m].\n- `ICoil::Float`: current in the coil times number of windings.\n- `IPlasma::Float`: current of the plasma?\n\"\"\"\nfunction getB_tokamak(x, y, z, a, b, ICoils, IPlasma)\n\n   a *= 2\n\n   Bx, By, Bz = 0.0, 0.0, 0.0\n\n   # magnetic field of the coils\n   for i = 0:15\n      θ = π/16 + i*π/8 # angle between the i-th coil and the x-axis\n\n      if abs(sin(θ)) > 0.01\n         r1_ = x/(cos(θ)-sin(θ)*tan(atan(y, x) - θ)) - a - b\n         r1 = √(r1_^2 + z^2)\n         z1 = ((b + a)*cos(θ) + r1_*cos(θ) - x) / sin(θ)\n      else\n         r1_ = x - b - a\n         r1 = √(r1_^2 + z^2)\n         z1 = y\n      end\n\n      k = √(4r1*a / (z1^2 + (a + r1)^2))\n\n      K, E = ellipke(k)\n      # Bz1_ is the magnetic field in the coil frame\n      Bz1_ = μ₀*ICoils/(2π*√(z1^2+(a+r1)^2))*((a^2-z1^2-r1^2)/(z1^2+(r1-a)^2)*E+K)\n      # Br1_ is the magnetic field in the coil frame\n      Br1_ = μ₀*z1*ICoils/(2π*r1*√(z1^2+(a+r1)^2))*((z1^2+r1^2+a^2)/(z1^2+(r1-a)^2)*E-K)\n      # normal coordinates\n      Bx1 = -sin(θ)*Bz1_ + Br1_*r1_/r1*cos(θ)\n      By1 = cos(θ)*Bz1_ + sin(θ)*Br1_*r1_/r1\n      Bz1 = Br1_ * z / r1\n\n      # add the field of a single coil to the total field\n      Bx += Bx1\n      By += By1\n      Bz += Bz1\n\n      if abs(Bx) < 5e-12\n         Bx = 0.0\n      end\n      if abs(By) < 5e-12\n         By = 0.0\n      end\n      if abs(Bz) < 5e-12\n         Bz = 0.0\n      end\n   end\n\n   # magnetic field of the plasma current\n   σ = a/3 # parameter of the Gauss curve\n   ϕ = atan(y, x)\n   # distance to centre of plasma ring\n   distance = √( z^2 + (x - (a + b)*cos(ϕ))^2 + (y - (a + b)*sin(ϕ))^2 )\n   I2_r_plasma = IPlasma * erf(distance/(σ*√2))\n\n   r = hypot(x, y)\n   k = √(4r*(a+b)/(z^2+((a+b)+r)^2))\n   K, E = ellipke(k)\n   Bz_plasma = μ₀*I2_r_plasma/(2π*√(z^2+((a+b)+r)^2))*(((a+b)^2-z^2-r^2)/(z^2+(r-(a+b))^2)*E+K)\n   Br_plasma = μ₀*z*I2_r_plasma/(2π*r*√(z^2+(b+r)^2))*((z^2+r^2+(a+b)^2)/(z^2+(r-(a+b))^2)*E-K)\n   Bx_plasma = Br_plasma*x/r\n   By_plasma = Br_plasma*y/r\n\n   if distance > 0.0001\n      Bx += Bx_plasma\n      By += By_plasma\n      Bz += Bz_plasma\n   end\n   [Bx, By, Bz]\nend", "meta": {"hexsha": "2e78c82fe2624c96f94173892cbdf674b45a2c50", "size": 4276, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utility/confinement.jl", "max_stars_repo_name": "henry2004y/TestParticle.jl", "max_stars_repo_head_hexsha": "d2967fd847dcaafd4249526e598324c8b317bf90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-13T21:54:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T21:54:01.000Z", "max_issues_repo_path": "src/utility/confinement.jl", "max_issues_repo_name": "henry2004y/TestParticle.jl", "max_issues_repo_head_hexsha": "d2967fd847dcaafd4249526e598324c8b317bf90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2021-02-08T00:59:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T21:02:21.000Z", "max_forks_repo_path": "src/utility/confinement.jl", "max_forks_repo_name": "henry2004y/TestParticle.jl", "max_forks_repo_head_hexsha": "d2967fd847dcaafd4249526e598324c8b317bf90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4896551724, "max_line_length": 105, "alphanum_fraction": 0.5226847521, "num_tokens": 1960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474168650673, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7643785469651346}}
{"text": "function rouwenhorst(n, mu, sigma, rho)\n    \n    # grid\n    width = sqrt((n-1) * sigma^2 / ( 1 - rho^2))\n    grid = vcat(range( mu-width, mu + width, length=n))\n    \n    # transition matrix\n    p0 = (1 + rho) / 2\n    trans = [p0 1-p0; 1-p0 p0]\n    \n    if n > 2\n        for i = 1:n-2\n            cstr_temp = zeros(length(trans[:,1]), 1)\n            trans = p0 .* [trans cstr_temp; cstr_temp' 0] + (1 - p0 ) .* [cstr_temp trans; cstr_temp' 0]  + (1 - p0 ) .*  [ cstr_temp' 0; trans cstr_temp] + p0 .* [ cstr_temp' 0; cstr_temp trans]\n        end\n        trans = trans ./ sum(trans,dims=2)\n    end\n    \n    # ergodic distribution\n    dist = ones(1,n)./n\n    for i = 1:100\n        dist = dist*(trans^i)\n    end\n    dist = vcat(dist...)\n    \n    return grid, trans, dist\nend\n    ", "meta": {"hexsha": "30b840970271c564596909d942699602189f1c69", "size": 775, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Guides/HA_codes/Julia/rouwenhorst.jl", "max_stars_repo_name": "pranjalrawat007/Recursive-Macro", "max_stars_repo_head_hexsha": "6caab42818e32b3a23584dca91837ad50db71616", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2022-01-25T10:14:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T06:38:17.000Z", "max_issues_repo_path": "Guides/HA_codes/Julia/rouwenhorst.jl", "max_issues_repo_name": "pranjalrawat007/Recursive-Macro", "max_issues_repo_head_hexsha": "6caab42818e32b3a23584dca91837ad50db71616", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Guides/HA_codes/Julia/rouwenhorst.jl", "max_forks_repo_name": "pranjalrawat007/Recursive-Macro", "max_forks_repo_head_hexsha": "6caab42818e32b3a23584dca91837ad50db71616", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-25T05:58:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T09:19:48.000Z", "avg_line_length": 27.6785714286, "max_line_length": 195, "alphanum_fraction": 0.5096774194, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474155747541, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7643785459319912}}
{"text": "\"\"\"\n    UCB1 Implementation\n    Based on: Figure-1, Auer, P., Bianchi, N. C., & Fischer, P. (2002). Finite time analysis of the multiarmed bandit problem. Machine Learning, 47, 235–256.\n\"\"\"\n\ntype UCB1 <: BanditAlgorithmBase\n    noOfArms::Int64\n    noOfSteps::Int64\n    lastPlayedArm::Int64\n\n    c::Float64\n\n    cummReward::Vector{Float64}\n    count::Vector{Int64}\n    ucbIndices::Vector{Float64}\n\n    function UCB1( noOfArms::Int, c::Real = √2 )\n        new( noOfArms,\n             0,\n             0,\n             c,\n             zeros(Float64,noOfArms),\n             zeros(Int64,noOfArms),\n             zeros(Float64,noOfArms)\n        )\n    end\nend\n\nfunction get_arm_index( agent::UCB1 )\n    if any(agent.count.==0)\n        agent.lastPlayedArm =  rand( find(agent.count.==0) )\n    else\n        agent.lastPlayedArm = findmax(agent.ucbIndices)[2]\n    end\n\n    return agent.lastPlayedArm\nend\n\nfunction update_reward!( agent::UCB1, r::Real )\n\n    # Update cummulative reward\n    agent.cummReward[agent.lastPlayedArm] += r\n\n    # Update play count for arm\n    agent.count[agent.lastPlayedArm] += 1\n\n    # Update number of steps played\n    agent.noOfSteps += 1\n\n    # Update UCB indices\n    agent.ucbIndices = agent.cummReward./agent.count +\n                        agent.c * sqrt.(log(agent.noOfSteps)./agent.count)\n\n    nothing\nend\n\nfunction reset!( agent::UCB1 )\n    agent.noOfSteps     = 0\n    agent.lastPlayedArm = 0\n\n    agent.cummReward    = zeros( Float64, agent.noOfArms )\n    agent.count         = zeros( Int64, agent.noOfArms )\n    agent.ucbIndices    = zeros( Float64, agent.noOfArms )\n\n    nothing\nend\n\nfunction info_str( agent::UCB1, latex::Bool )\n    if agent.c == √2\n        return @sprintf( \"UCB1\" )\n    else\n        return @sprintf( \"UCB1 (c=%3.2f)\", agent.c )\n    end\nend\n\n# \"\"\"\n#     UCB2 Implementation\n#     Based on: Figure-2, Auer, P., Bianchi, N. C., & Fischer, P. (2002). Finite time analysis of the multiarmed bandit problem. Machine Learning, 47, 235–256.\n# \"\"\"\n# type UCB2 <: BanditAlgorithmBase\n#     noOfArms::Int64\n#     noOfSteps::Int64\n#     lastPlayedArm::Int64\n#     α::Float64\n#\n#     cummReward::Vector{Float64}\n#     count::Vector{Int64}\n#\n#     function UCB2( noOfArms::Int, α::Float64 )\n#         new( noOfArms,\n#              0,\n#              0,\n#              α,\n#              zeros(Float64,noOfArms),\n#              zeros(Int64,noOfArms)\n#         )\n#     end\n# end\n\n# function getArmIndex( agent::UCB2 )\n#\n# end\n#\n# function updateReward( agent::UCB2, r::Float64 )\n#\n# end\n\n\n\"\"\"\n    UCB-Normal Implementation\n    Based on: Figure-4, Auer, P., Bianchi, N. C., & Fischer, P. (2002). Finite time analysis of the multiarmed bandit problem. Machine Learning, 47, 235–256.\n\"\"\"\n\ntype UCBNormal <: BanditAlgorithmBase\n    noOfArms::Int64\n    noOfSteps::Int64\n    lastPlayedArm::Int64\n\n    cummReward::Vector{Float64}\n    count::Vector{Int64}\n    cummSqReward::Vector{Float64}\n    ucbIndices::Vector{Float64}\n\n    function UCBNormal( noOfArms::Int )\n        new( noOfArms,\n             0,\n             0,\n             zeros(Float64,noOfArms),\n             zeros(Int64,noOfArms),\n             zeros(Float64,noOfArms),\n             zeros(Float64,noOfArms)\n        )\n    end\nend\n\nfunction get_arm_index( agent::UCBNormal )\n    tmp_lb      = ceil( 8 * log(agent.noOfSteps) )  # Quantity for comparison\n    tmp_lbArms  = find( agent.count .< tmp_lb )     # Find index of under played arms\n    if( size(tmp_lbArms,1) > 0 )    # if any machine is played less than ceil(8 log n), play that arm\n        agent.lastPlayedArm = rand( tmp_lbArms )    # Randomly play one of those arms\n    else    # else play arm with highest UCB index\n        agent.lastPlayedArm = findmax(agent.ucbIndices)[2]\n    end\n    return agent.lastPlayedArm\nend\n\nfunction update_reward!( agent::UCBNormal, r::Real )\n    # Update cummulative reward\n    agent.cummReward[agent.lastPlayedArm] += r\n    # Update squared cummulative reward\n    agent.cummSqReward[agent.lastPlayedArm] += (r^2)\n    # Update count for last played arm\n    agent.count[agent.lastPlayedArm] += 1\n    # Update number of steps\n    agent.noOfSteps += 1\n    # Update UCB indices\n    agent.ucbIndices    = agent.cummReward ./ agent.count +\n                            sqrt.(16 *\n                                (agent.cummSqReward-((agent.cummReward).^2)./agent.count) ./ (agent.count-1) *\n                                log(agent.noOfSteps-1)./agent.count )\n\n    nothing\nend\n\nfunction reset!( agent::UCBNormal )\n    agent.noOfSteps     = 0\n    agent.lastPlayedArm = 0\n\n    agent.cummReward    = zeros( Float64, agent.noOfArms )\n    agent.count         = zeros( Int64, agent.noOfArms )\n    agent.cummSqReward  = zeros( Float64, agent.noOfArms )\n    agent.ucbIndices    = zeros( Float64, agent.noOfArms )\n\n    nothing\nend\n\nfunction info_str( agent::UCBNormal, latex::Bool )\n    return @sprintf( \"UCB Normal\" )\nend\n\n\"\"\"\n    Discounted UCB\n    Based on: Moulines, E., & Paristech, T. (2008). On Upper-Confidence Bound Policies for Non-Stationary Bandit Problems. arXiv Preprint, (2008), 1–24.\n\"\"\"\n\ntype DUCB <: BanditAlgorithmBase\n    noOfArms::Int64\n    noOfSteps::Int64\n    lastPlayedArm::Int64\n\n    γ::Float64                      # Discouting factor\n    ξ::Float64                      # Confidence Scale Parameter\n    cummReward::Vector{Float64}     # Cummulattive Reward from each arm\n    discCumReward::Vector{Float64}  # Discounted reward\n    count::Vector{Int64}            # Count of how many time an arm is pulled\n    discCount::Vector{Float64}      # Discounted Count\n    indices::Vector{Float64}        # Calculated Indices\n\n    function DUCB( noOfArms::Int, γ::Float64, ξ::Float64 = 0.5 )\n        new( noOfArms,\n             0,\n             0,\n             γ,\n             ξ,\n             zeros(Float64,noOfArms),\n             zeros(Float64,noOfArms),\n             zeros(Int64,noOfArms),\n             zeros(Float64,noOfArms),\n             zeros(Float64,noOfArms)\n        )\n    end\nend\n\nfunction get_arm_index( agent::DUCB )\n    if any(agent.count.==0)\n        agent.lastPlayedArm =  rand( find(agent.count.==0) )\n    else\n        agent.lastPlayedArm = findmax(agent.indices)[2]\n    end\n\n    return agent.lastPlayedArm\nend\n\nfunction update_reward!( agent::DUCB, r::Real )\n    # Update cummulative reward\n    agent.cummReward[agent.lastPlayedArm] += r\n    # Update play count for arm\n    agent.count[agent.lastPlayedArm] += 1\n    # Update number of steps played\n    agent.noOfSteps += 1\n    # Update discounted cummulative reward\n    agent.discCumReward *= agent.γ                  # Discount for all arms\n    agent.discCumReward[agent.lastPlayedArm] += r   # Update reward to last played arm\n    # Update discounted count\n    agent.discCount *= agent.γ\n    agent.discCount[agent.lastPlayedArm] += 1\n    # Update UCB indices\n    agent.indices   = agent.discCumReward./agent.discCount +\n                        2*sqrt.(agent.ξ*log(sum(agent.discCount))./agent.discCount)\n\n    nothing\nend\n\nfunction reset!( agent::DUCB )\n    agent.noOfSteps     = 0;\n    agent.lastPlayedArm = 0;\n\n    agent.cummReward    = zeros( Float64, agent.noOfArms );\n    agent.discCumReward = zeros( Float64, agent.noOfArms );\n    agent.count         = zeros( Int64, agent.noOfArms );\n    agent.discCount     = zeros( Float64, agent.noOfArms );\n    agent.indices       = zeros( Float64, agent.noOfArms );\n\n    nothing\nend\n\nfunction info_str( agent::DUCB, latex::Bool )\n    if latex\n        return @sprintf( \"Discounted-UCB\\$(\\\\gamma = %4.3f,\\\\xi = %4.3f)\\$\", agent.γ, agent.ξ );\n    else\n        return @sprintf( \"Discounted-UCB(γ = %4.3f, ξ = %4.3f)\", agent.γ, agent.ξ );\n    end\nend\n\n\"\"\"\n    Sliding Window UCB\n    Based on: Moulines, E., & Paristech, T. (2008). On Upper-Confidence Bound Policies for Non-Stationary Bandit Problems. arXiv Preprint, (2008), 1–24.\n\"\"\"\n\ntype SWUCB <: BanditAlgorithmBase\n    noOfArms::Int64\n    noOfSteps::Int64\n    lastPlayedArm::Int64\n\n    τ::Int64                        # Window Length\n    ξ::Float64                      # Confidence Scale Parameter\n    cummReward::Vector{Float64}     # Cummulative Reward from each arm\n    count::Vector{Int64}            # Count of how many time an arm is pulled\n    swCount::Vector{Int64}          # Count of how many times an arm is picked in this sliding Window\n    armsInWindow::Vector{Int64}     # Vector of Arms picked in window\n    rewardsInWindow::Vector{Float64}# Vector of Rewards corresponding to arms picked in this window\n    swCumRew::Vector{Float64}       # Cummulative reward of arms in this window\n    indices::Vector{Float64}        # Calculated Indices\n\n    function SWUCB( noOfArms::Int, τ::Int64, ξ::Float64 = 2.0 )\n        new( noOfArms,\n             0,\n             0,\n             τ,\n             ξ,\n             zeros(Float64,noOfArms),\n             zeros(Int64,noOfArms),\n             zeros(Int64,noOfArms),\n             Vector{Int64}(),\n             Vector{Float64}(),\n             zeros(Float64,noOfArms),\n             zeros(Float64,noOfArms)\n        )\n    end\nend\n\nfunction get_arm_index( agent::SWUCB )\n    if any(agent.swCount.==0)\n        agent.lastPlayedArm =  rand( find(agent.swCount.==0) )\n    else\n        agent.lastPlayedArm = findmax(agent.indices)[2]\n    end\n    return agent.lastPlayedArm\nend\n\nfunction update_reward!( agent::SWUCB, r::Real )\n    # Update cummulative reward\n    agent.cummReward[agent.lastPlayedArm] += r\n    # Update play count for arm\n    agent.count[agent.lastPlayedArm] += 1\n    # Update number of steps played\n    agent.noOfSteps += 1\n\n    # For sliding window\n    push!( agent.armsInWindow, agent.lastPlayedArm )\n    push!( agent.rewardsInWindow, r )\n    agent.swCount[agent.lastPlayedArm]  += 1\n    agent.swCumRew[agent.lastPlayedArm] += r\n    if length(agent.armsInWindow) > agent.τ\n        _arm    = shift!( agent.armsInWindow )\n        _r      = shift!( agent.rewardsInWindow )\n        agent.swCount[_arm]     -= 1\n        agent.swCumRew[_arm]    -= _r\n    end\n\n    # Sanity check\n    assert( length(agent.armsInWindow) == length(agent.rewardsInWindow) <= agent.τ )\n\n    # Update UCB indices\n    agent.indices = agent.swCumRew./agent.swCount +\n                        sqrt.(agent.ξ*log(min(agent.noOfSteps,agent.τ))./agent.swCount)\n\n    nothing\nend\n\nfunction reset!( agent::SWUCB )\n    agent.noOfSteps         = 0\n    agent.lastPlayedArm     = 0\n    agent.cummReward        = zeros(Float64,agent.noOfArms)\n    agent.count             = zeros(Int64,agent.noOfArms)\n    agent.swCount           = zeros(Int64,agent.noOfArms)\n    agent.armsInWindow      = Vector{Int64}()\n    agent.rewardsInWindow   = Vector{Int64}()\n    agent.indices           = zeros(Float64,agent.noOfArms)\n\n    nothing\nend\n\nfunction info_str( agent::SWUCB, latex::Bool )\n    if latex\n        return @sprintf( \"SW-UCB\\$(\\\\tau = %3.2f,\\\\xi = %3.2f)\\$\", agent.τ, agent.ξ );\n    else\n        return @sprintf( \"SW-UCB(τ = %3.2f, ξ = %3.2f)\", agent.τ, agent.ξ );\n    end\nend\n\n\n\"\"\"\n    UCB-V: Variance Aware UCB Implementation\n    Based on: Audibert, J. Y., Munos, R., & Szepesvári, C. (2009). Exploration-exploitation tradeoff using variance estimates in multi-armed bandits. Theoretical Computer Science, 410(19), 1876–1902. http://doi.org/10.1016/j.tcs.2009.01.016\n\"\"\"\n\ntype UCBV <: BanditAlgorithmBase\n    noOfArms::Int64\n    noOfSteps::Int64\n    lastPlayedArm::Int64\n\n    # Parameters\n    ζ::Float64\n    c::Float64\n    b::Float64\n\n    empiricalMean::Vector{Float64}\n    empiricalVariance::Vector{Float64}\n    count::Vector{Int64}\n    ucbIndices::Vector{Float64}\n\n    function UCBV( noOfArms::Int; ζ::Real = 1.0, c::Real = 1/3, b::Real = 1.0 )\n        new( noOfArms,\n             0,\n             0,\n             ζ,\n             c,\n             b,\n             zeros(Float64,noOfArms),\n             zeros(Float64,noOfArms),\n             zeros(Int64,noOfArms),\n             zeros(Float64,noOfArms)\n        )\n    end\nend\n\nfunction get_arm_index( agent::UCBV )\n    if any(agent.count.==0)\n        agent.lastPlayedArm =  rand( find(agent.count.==0) )\n    else\n        agent.lastPlayedArm = findmax(agent.ucbIndices)[2]\n    end\n\n    return agent.lastPlayedArm\nend\n\nfunction update_reward!( agent::UCBV, r::Real )\n\n    # Save old mean\n    μ = agent.empiricalMean[agent.lastPlayedArm]\n\n    # Update cummulative reward\n    agent.empiricalMean[agent.lastPlayedArm] = (agent.empiricalMean[agent.lastPlayedArm]*agent.count[agent.lastPlayedArm]+r) /\n                                                    (agent.count[agent.lastPlayedArm]+1)\n    # Update empirical Variance : Based on (30) in http://mathworld.wolfram.com/SampleVarianceComputation.html\n    if agent.count[agent.lastPlayedArm] != 0\n        agent.empiricalVariance[agent.lastPlayedArm] = (agent.count[agent.lastPlayedArm]-1)/agent.count[agent.lastPlayedArm] *\n                                                            agent.empiricalVariance[agent.lastPlayedArm] +\n                                                        1/(agent.count[agent.lastPlayedArm]+1) * (r-μ)^2\n    end\n\n    # Update play count for arm\n    agent.count[agent.lastPlayedArm] += 1\n\n    # Update number of steps played\n    agent.noOfSteps += 1\n\n    # Update UCB indices\n    agent.ucbIndices = agent.empiricalMean +\n                        sqrt.(2*agent.ζ*log(agent.noOfSteps)*agent.empiricalVariance./agent.count) +\n                            3*agent.c*agent.b*log(agent.noOfSteps)./agent.count\n    nothing\nend\n\nfunction reset!( agent::UCBV )\n    agent.noOfSteps     = 0\n    agent.lastPlayedArm = 0\n\n    agent.empiricalMean     = zeros( Float64, agent.noOfArms )\n    agent.empiricalVariance = zeros( Float64, agent.noOfArms )\n    agent.count             = zeros( Int64, agent.noOfArms )\n    agent.ucbIndices        = zeros( Float64, agent.noOfArms )\n\n    nothing\nend\n\nfunction info_str( agent::UCBV, latex::Bool )\n    if latex\n        return @sprintf( \"UCB-V(\\$\\\\zeta=%3.2f,c=%3.2f,b=%3.2f\\$)\", agent.ζ, agent.c, agent.b )\n    else\n        return @sprintf( \"UCB-V(ζ=%3.2f,c=%3.2f,b=%3.2f)\", agent.ζ, agent.c, agent.b )\n    end\nend\n\n\n\n\"\"\"\n    Bayes-UCB Implementation\n    Based on: Kaufmann, E., Cappé, O., & Garivier, A. (2012). On Bayesian upper confidence bounds for bandit problems. International Conference on Artificial Intelligence and Statistics, 592–600.\n    Using 1 - 1/t as quantile\n\"\"\"\ntype BayesUCB <: BanditAlgorithmBase\n    noOfArms::Int64\n    noOfSteps::Int64\n    lastPlayedArm::Int64\n\n    count::Vector{Int64}\n    α0::Vector{Int64}\n    β0::Vector{Int64}\n    cummSuccess::Vector{Int64}\n    cummFailure::Vector{Int64}\n\n    samplingDist::Vector{Distributions.Beta}\n\n    function BayesUCB( noOfArms::Integer )\n        new( noOfArms,\n             0,\n             0,\n             zeros(Int64,noOfArms),\n             ones(Int64,noOfArms),\n             ones(Int64,noOfArms),\n             zeros(Float64,noOfArms),\n             zeros(Float64,noOfArms),\n             fill(Distributions.Beta(1,1),noOfArms)\n        )\n    end\n\n    function BayesUCB( armParams::Array{Tuple{Int64,Int64},1} )\n        _noOfArms   = length( armParams )\n        _priorDist  = [ Distributions.Beta(armParams[idx][1],armParams[idx][2]) for idx=1:_noOfArms ]\n        new( _noOfArms,\n             0,\n             0,\n             zeros(Int64,noOfArms),\n             [ armParams[idx][1] for idx=1:_noOfArms ],\n             [ armParams[idx][2] for idx=1:_noOfArms ],\n             zeros(Float64,_noOfArms),\n             zeros(Float64,_noOfArms),\n             _priorDist\n        )\n    end\nend\n\nfunction get_arm_index( agent::BayesUCB )\n    if any(agent.count.==0)\n        agent.lastPlayedArm =  rand( find(agent.count.==0) )\n    else\n        agent.lastPlayedArm = findmax(  map(dist->quantile(dist,1-1/agent.noOfSteps),agent.samplingDist) )[2]\n    end\n    return agent.lastPlayedArm\nend\n\nfunction update_reward!( agent::BayesUCB, r::Int64 )\n    # Update S and F\n    agent.cummSuccess[agent.lastPlayedArm] += (r==0?0:1)\n    agent.cummFailure[agent.lastPlayedArm] += (r==0?1:0)\n\n    # Update Distributions\n    agent.samplingDist[agent.lastPlayedArm] = Distributions.Beta(\n                                                agent.cummSuccess[agent.lastPlayedArm]+agent.α0[agent.lastPlayedArm],\n                                                agent.cummFailure[agent.lastPlayedArm]+agent.β0[agent.lastPlayedArm]\n                                            )\n\n    # Update play count for arm\n    agent.count[agent.lastPlayedArm] += 1\n\n    # Update time steps\n    agent.noOfSteps += 1\n\n    nothing\nend\n\nfunction reset!( agent::BayesUCB )\n    agent.noOfSteps     = 0\n    agent.lastPlayedArm = 0\n\n    agent.count         = zeros( Int64, agent.noOfArms )\n    agent.cummSuccess   = zeros( Float64, agent.noOfArms )\n    agent.cummFailure   = zeros( Float64, agent.noOfArms )\n    agent.samplingDist  = fill( Distributions.Beta(1,1), agent.noOfArms )\n\n    nothing\nend\n\nfunction info_str( agent::BayesUCB, latex::Bool )\n    return @sprintf( \"Bayes UCB\" )\nend\n\n\"\"\"\n    KL-UCB Implementation\n    Based on: Garivier, A., & Cappe, O. (2011). The KL-UCB Algorithm for Bounded Stochastic Bandits and Beyond. In CoLT (Vol. 24).\n\"\"\"\ntype KLUCB <: BanditAlgorithmBase\n    noOfArms::Int64\n    noOfSteps::Int64\n    lastPlayedArm::Int64\n\n    cummReward::Vector{Float64}\n    count::Vector{Int64}\n    ucbIndices::Vector{Float64}\n\n    function KLUCB( noOfArms::Int )\n        new( noOfArms,\n             0,\n             0,\n             zeros(Float64,noOfArms),\n             zeros(Int64,noOfArms),\n             zeros(Float64,noOfArms)\n        )\n    end\nend\n\nfunction get_arm_index( agent::KLUCB )\n    if any(agent.count.==0)\n        agent.lastPlayedArm =  rand( find(agent.count.==0) )\n    else\n        agent.lastPlayedArm = findmax(agent.ucbIndices)[2]\n    end\n\n    return agent.lastPlayedArm\nend\n\nfunction update_reward!( agent::KLUCB, r::Real )\n\n    # Update cummulative reward\n    agent.cummReward[agent.lastPlayedArm] += r\n\n    # Update play count for arm\n    agent.count[agent.lastPlayedArm] += 1\n\n    # Update number of steps played\n    agent.noOfSteps += 1\n\n    # Update UCB indices\n    agent.ucbIndices = find_q.( agent.cummReward, agent.count, agent.noOfSteps )\n\n    nothing\nend\n\nfunction reset!( agent::KLUCB )\n    agent.noOfSteps     = 0\n    agent.lastPlayedArm = 0\n\n    agent.cummReward    = zeros( Float64, agent.noOfArms )\n    agent.count         = zeros( Int64, agent.noOfArms )\n    agent.ucbIndices    = zeros( Float64, agent.noOfArms )\n\n    nothing\nend\n\nfunction info_str( agent::KLUCB, latex::Bool )\n    return @sprintf( \"KL-UCB\" )\nend\n\n# Utility functions\nfunction kl_div( p::Float64, q::Float64 )\n    if p==q\n        return 0.00\n    elseif p == 0.0\n        return -log(1-q)\n    elseif p == 1.0\n        return -log(q)\n    else\n        return p*log(p/q) + (1-p)*log((1-p)/(1-q))\n    end\nend\n\nfunction kl_div( X1::Distributions.Bernoulli, X2::Distributions.Bernoulli )\n   kl_div( X1.p, X2.p )\nend\n\nfunction find_q( sa, na, t; ϵ = 1e-5 )\n    lQ = sa/na\n    uQ = min( 1, sa/na+√(log(t)/na/2))      # Applying Pinkser's Inequality\n    q̄ = 1.0\n    q  = (lQ+uQ)/2\n    while abs(q̄-q) > ϵ\n        q̄  = q\n        # print( @sprintf( \"lQ = %f, q = %f, uQ = %f\", lQ, q, uQ ) )\n        klDiv = kl_div( sa/na, q )\n        # println( @sprintf( \"    kl = %f, d = %f\", klDiv, log(t)/na ))\n        if klDiv < (log(t)/na)\n            lQ = q\n        else\n            uQ = q\n        end\n        q  = (lQ+uQ)/2\n    end\n    return lQ\nend\n\n\"\"\"\n    M-UCB\n    Based on: Cao, Y., Zheng, W., Kveton, B., & Xie, Y. (2018). Nearly Optimal Adaptive Procedure for Piecewise-Stationary Bandit: a Change-Point Detection Approach. Retrieved from http://arxiv.org/abs/1802.03692\n\"\"\"\n\ntype MUCB <: BanditAlgorithmBase\n    noOfArms::Int64\n    noOfSteps::Int64\n    lastPlayedArm::Int64\n\n    # Algorithm params\n    w::Int              # Test window length - Should be a even number\n    b::Float64          # Test threshold\n    γ::Float64          # Expoloration parameter\n\n    # Internal\n    τ::Int              # Last detected change point\n    _ucb::UCB1          # UCB agent to run\n    rew::Vector{Vector{Float64}}    # Past rewards from each arm\n\n    function MUCB( noOfArms::Int, w::Int, b::Float64, γ::Float64 )\n        new(\n            noOfArms,\n            0,\n            0,\n            w,\n            b,\n            γ,\n            0,\n            UCB1(noOfArms),\n            [ Vector{Float64}() for k = 1:noOfArms ]\n        )\n    end\nend\n\nfunction get_arm_index( agent::MUCB )\n    A = (agent.noOfSteps-agent.τ) % floor(agent.noOfArms/agent.γ)\n    if A < agent.noOfArms   # Uniform Exploration\n        agent.lastPlayedArm = A+1\n        agent._ucb.lastPlayedArm = agent.lastPlayedArm\n    else\n        agent.lastPlayedArm = get_arm_index( agent._ucb )\n    end\n    return agent.lastPlayedArm\nend\n\nfunction update_reward!( agent::MUCB, r::Real )\n    agent.noOfSteps += 1\n    push!( agent.rew[agent.lastPlayedArm], r )\n    update_reward!( agent._ucb, r )\n    if length(agent.rew[agent.lastPlayedArm]) > agent.w # If the window length is reached\n        # Then discard the oldest reward\n        shift!( agent.rew[agent.lastPlayedArm] )\n        # Also do the test\n        if mucb_cd( agent.rew[agent.lastPlayedArm], agent.b )   # If test detects a change\n            # Reset UCB1\n            reset!( agent._ucb )\n            # Update last detection point\n            agent.τ = agent.noOfSteps\n            agent.rew = [ Vector{Float64}() for k = 1:agent.noOfArms ]\n        end\n    end\n    nothing\nend\n\nfunction reset!( agent::MUCB )\n    agent.noOfSteps     = 0\n    agent.lastPlayedArm = 0\n    agent.τ             = 0\n    agent.rew           = [ Vector{Float64}() for k = 1:agent.noOfArms ]\n\n    reset!( agent._ucb )    # Reset internal UCB1 agent also\nend\n\nfunction info_str( agent::MUCB, latex::Bool )\n    if latex\n        return @sprintf( \"M-UCB( w = %d, b = %4.3f, \\$\\\\gamma\\$ = %4.3f )\", agent.w, agent.b, agent.γ )\n    else\n        return @sprintf( \"M-UCB( w = %d, b = %4.3f, γ = %4.3f )\", agent.w, agent.b, agent.γ )\n    end\nend\n\n#=\n    Change Detection algorithm for M-UCB\n        b - detection threshold\n        rew - list of rewards; must be of length 'w' an even number\n=#\nfunction mucb_cd( rew::Vector{Float64}, b::Float64 )\n    l = length( rew )\n    assert( l%2 == 0 )\n    return abs( sum(rew[1:Int(l/2)])-sum(rew[Int(l/2)+1:end]) ) > b\nend\n", "meta": {"hexsha": "b88efb66651fc1b5c5d8f16f95b067fc5e4e15da", "size": 22248, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Algorithms/UCB.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/MAB.jl-96e1709c-041e-5d42-98d9-815bb6f3efac", "max_stars_repo_head_hexsha": "6acf2b1b13c49a35b0b4be085dec3d5443cadd5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-02-18T22:33:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T05:58:49.000Z", "max_issues_repo_path": "src/Algorithms/UCB.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/MAB.jl-96e1709c-041e-5d42-98d9-815bb6f3efac", "max_issues_repo_head_hexsha": "6acf2b1b13c49a35b0b4be085dec3d5443cadd5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-04-25T01:20:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:29:59.000Z", "max_forks_repo_path": "src/Algorithms/UCB.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/MAB.jl-96e1709c-041e-5d42-98d9-815bb6f3efac", "max_forks_repo_head_hexsha": "6acf2b1b13c49a35b0b4be085dec3d5443cadd5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:19:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T07:34:42.000Z", "avg_line_length": 29.8630872483, "max_line_length": 240, "alphanum_fraction": 0.6035149227, "num_tokens": 6596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7643545055485139}}
{"text": "## Bisection methods to find a root.\n\n\"\"\"\n    bisection(f,l,r)\n\nFind the root of a function via a bisection approach. This is a\n  pedagogical implementation that can be improved.\n  ## Add link to \"julia bisection floating point\"\n\"\"\"\nfunction bisection(f::Function, l::Real, r::Real)\n  if r < l\n    l,r = r,l\n  end\n  fl = f(l)\n  fr = f(r)\n  if fl*fr == 0\n    al = abs(fl)\n    ar = abs(fr)\n    if al < ar\n      return l\n    else\n      return r\n    end\n  end\n\n  @assert(fl*fr < 0) # make sure the signs are different\n  while r-l >= max(min(eps(l),eps(r)),eps(1.0)) # while there is still floating point space left.\n    m = l/2 + r/2\n    fm = f(m)\n        @show l, m, r, fl, fm, fr\n    if abs(fm) <= eps(1.0)\n      return m\n    elseif sign(fl) == sign(fm)\n      l = m\n      fl = fm\n    else\n      @assert(fm*fl <= 0)\n      r = m\n      frm = fm\n    end\n  end\n  return l\nend\nl = bisection(x -> x-5, 0.0, 12.0)\n##\nl = bisection(x -> x-5, 0.0, 10.0)\n", "meta": {"hexsha": "07efc2b9f3e5ac7bbba6800f08c8982ee2d8dd72", "size": 942, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "6-unit-5-demos/bisection.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "6-unit-5-demos/bisection.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "6-unit-5-demos/bisection.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 20.0425531915, "max_line_length": 97, "alphanum_fraction": 0.5477707006, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.764354501887502}}
{"text": "# complexspace.jl\n#\n# Defines the immutable ComplexSpace for a standard complex vector space C^n and is\n# characterized by its dimension and whether or not it is the dual space. Tensors with\n# ComplexSpace as index spaces make a distinction between covariant and contravariant indices.\n\n# ComplexSpace:\n#---------------\nimmutable ComplexSpace <: EuclideanSpace{ℂ}\n  d::Int\n  dual::Bool\nend\nComplexSpace(d::Int) = ComplexSpace(d, false)\n^(::Type{ℂ},d::Int) = ComplexSpace(d)\n\n# Corresponding methods:\ndim(V::ComplexSpace) = V.d\ndual(V::ComplexSpace) = ComplexSpace(V.d, !V.dual)\ncnumber(V::ComplexSpace) = ComplexSpace(1, V.dual)\ncnumber(::Type{ComplexSpace}) = ComplexSpace(1)\niscnumber(V::ComplexSpace) = dim(V)==1\n\n# Show methods\nBase.show(io::IO, V::ComplexSpace) = print(io, V.dual ? \"ℂ^$(V.d)*\" : \"ℂ^$(V.d)\")\n\n# direct sum of ComplexSpaces\ndirectsum(V1::ComplexSpace, V2::ComplexSpace) = (V1.dual==V2.dual ? ComplexSpace(V1.d+V2.d, V1.dual) : throw(SpaceError(\"Direct sum of a vector space and its dual do not exist\")))\n\n# fusing and splitting ComplexSpaces\nfuse(V1::ComplexSpace,V2::ComplexSpace,V::ComplexSpace) = dim(V1)*dim(V2)==dim(V)\n\n# # basis and basisvector\n# typealias ComplexBasisVector BasisVector{ComplexSpace,Int} # use integer from 1 to dim as identifier\n# typealias ComplexBasis Basis{ComplexSpace}\n#\n# Base.length(B::ComplexBasis) = dim(space(B))\n# Base.start(B::ComplexBasis) = 1\n# Base.next(B::ComplexBasis, state::Int) = (EuclideanBasisVector(space(B),state),state+1)\n# Base.done(B::ComplexBasis, state::Int) = state>length(B)\n#\n# Base.to_index(b::ComplexBasisVector) = b.identifier\n", "meta": {"hexsha": "bae9235e4eb0a0c2f86134ae9bd9ca6fb43fa71d", "size": 1608, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spaces/complexspace.jl", "max_stars_repo_name": "amilsted/TensorToolbox.jl", "max_stars_repo_head_hexsha": "d491b3d2cabb7cc584b324435a61f409714daf20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-26T20:33:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T20:33:51.000Z", "max_issues_repo_path": "src/spaces/complexspace.jl", "max_issues_repo_name": "amilsted/TensorToolbox.jl", "max_issues_repo_head_hexsha": "d491b3d2cabb7cc584b324435a61f409714daf20", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spaces/complexspace.jl", "max_forks_repo_name": "amilsted/TensorToolbox.jl", "max_forks_repo_head_hexsha": "d491b3d2cabb7cc584b324435a61f409714daf20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-07-06T23:58:07.000Z", "max_forks_repo_forks_event_max_datetime": "2016-07-06T23:58:07.000Z", "avg_line_length": 38.2857142857, "max_line_length": 179, "alphanum_fraction": 0.7276119403, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7643544980410183}}
{"text": "\"\"\"\n    X = sylvc(A,B,C)\n\nSolve the continuous Sylvester matrix equation\n\n                AX + XB = C\n\nusing the Bartels-Stewart Schur form based approach. `A` and `B` are\nsquare matrices, and `A` and `-B` must not have common eigenvalues.\n\nThe following particular cases are also adressed:\n\n    X = sylvc(α*I,B,C)  or  X = sylvc(α,B,C)\n\nSolve the matrix equation `X(αI+B)  = C`.\n\n    X = sylvc(A,β*I,C)  or  X = sylvc(A,β,C)\n\nSolve the matrix equation `(A+βI)X = C`.\n\n    X = sylvc(α*I,β*I,C)  or  sylvc(α,β,C)\n\nSolve the matrix equation `(α+β)X = C`.\n\n    x = sylvc(α,β,γ)\n\nSolve the equation `(α+β)x = γ`.\n\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2×2 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2×2 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2×2 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> X = sylvc(A, B, C)\n2×2 Array{Float64,2}:\n -4.46667   1.93333\n  3.73333  -1.8\n\njulia> A*X + X*B - C\n2×2 Array{Float64,2}:\n  2.66454e-15  1.77636e-15\n -3.77476e-15  4.44089e-16\n```\n\"\"\"\nfunction sylvc(A::AbstractMatrix,B::AbstractMatrix,C::AbstractMatrix)\n   \"\"\"\n   Reference:\n   R. H. Bartels and G. W. Stewart. Algorithm 432: Solution of the matrix equation AX+XB=C.\n   Comm. ACM, 15:820–826, 1972.\n   \"\"\"\n\n   m, n = size(C);\n   [m; n] == LinearAlgebra.checksquare(A,B) || throw(DimensionMismatch(\"A, B and C have incompatible dimensions\"))\n\n   T2 = promote_type(eltype(A), eltype(B), eltype(C))\n   T2 <: BlasFloat || (T2 = promote_type(Float64,T2))\n   eltype(A) == T2 || (A = convert(Matrix{T2},A))\n   eltype(B) == T2 || (B = convert(Matrix{T2},B))\n   eltype(C) == T2 || (C = convert(Matrix{T2},C))\n\n   adjA = isa(A,Adjoint)\n   adjB = isa(B,Adjoint)\n   if adjA\n      RA, QA = schur(A.parent)\n   else\n      RA, QA = schur(A)\n   end\n   if adjB\n      RB, QB = schur(B.parent)\n   else\n      RB, QB = schur(B)\n   end\n\n   Y = QA' * C * QB\n\n   sylvcs!(RA, RB, Y, adjA = adjA, adjB = adjB)\n\n   mul!(Y, QA, Y*QB')\n\n   return Y\nend\n# solve X(B+α) = C or (α+β)X = C\nsylvc(A::Union{Real,Complex,UniformScaling},B::Union{AbstractMatrix,UniformScaling},C::AbstractMatrix) = C/(A*I+B)\n# solve (A+β)X = C\nsylvc(A::AbstractMatrix,B::Union{Real,Complex,UniformScaling},C::AbstractMatrix) = (A+B*I)\\C\n# solve (α+β)X = C\nsylvc(A::Union{Real,Complex},B::Union{Real,Complex},C::AbstractMatrix) = A+B == 0 ? throw(SingularException(1)) : C/(A+B)\n# solve (α+β)x = γ\nsylvc(A::Union{Real,Complex}, B::Union{Real,Complex}, C::Union{Real,Complex}) = A+B == 0 ? throw(SingularException(1)) : C/(A+B)\n\"\"\"\n    X = sylvd(A,B,C)\n\nSolve the discrete Sylvester matrix equation\n\n                AXB + X = C\n\nusing an extension of the Bartels-Stewart Schur form based approach.\n`A` and `B` are square matrices, and `A` and `-B` must not have\ncommon reciprocal eigenvalues.\n\nThe following particular cases are also adressed:\n\n    X = sylvd(α*I,B,C)  or  X = sylvd(α,B,C)\n\nSolve the matrix equation `X(αB+I)  = C`.\n\n    X = sylvd(A,β*I,C)   or  X = sylvd(A,β,C)\n\nSolve the matrix equation `(βA+I)X = C`.\n\n    X = sylvd(α*I,β*I,C)  or  X = sylvd(α,β,C)\n\nSolve the matrix equation `(αβ+1)X = C`.\n\n    x = sylvd(α,β,γ)\n\nSolve the equation `(αβ+1)x = γ`.\n\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2×2 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2×2 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2×2 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> X = sylvd(A, B, C)\n2×2 Array{Float64,2}:\n -2.46667  -2.73333\n  2.4       1.86667\n\njulia> A*X*B + X - C\n2×2 Array{Float64,2}:\n  8.88178e-16   8.88178e-16\n -3.9968e-15   -5.55112e-15\n```\n\"\"\"\nfunction sylvd(A::AbstractMatrix,B::AbstractMatrix,C::AbstractMatrix)\n   \"\"\"\n   Reference:\n   R. H. Bartels and G. W. Stewart. Algorithm 432: Solution of the matrix equation AX+XB=C.\n   Comm. ACM, 15:820–826, 1972.\n   \"\"\"\n\n   m, n = size(C);\n   [m; n] == LinearAlgebra.checksquare(A,B) || throw(DimensionMismatch(\"A, B and C have incompatible dimensions\"))\n   T2 = promote_type(eltype(A), eltype(B), eltype(C))\n   T2 <: BlasFloat || (T2 = promote_type(Float64,T2))\n   eltype(A) == T2 || (A = convert(Matrix{T2},A))\n   eltype(B) == T2 || (B = convert(Matrix{T2},B))\n   eltype(C) == T2 || (C = convert(Matrix{T2},C))\n\n   adjA = isa(A,Adjoint)\n   adjB = isa(B,Adjoint)\n   if adjA\n      RA, QA = schur(A.parent)\n   else\n      RA, QA = schur(A)\n   end\n   if adjB\n      RB, QB = schur(B.parent)\n   else\n      RB, QB = schur(B)\n   end\n\n   Y = QA' * C * QB\n\n   sylvds!(RA, RB, Y, adjA = adjA, adjB = adjB)\n\n   mul!(Y, QA, Y*QB')\n\n   return Y\nend\n# solve X(αB+I) = C or X(αβ+1) = C\nsylvd(A::Union{Real,Complex,UniformScaling},B::Union{AbstractMatrix,UniformScaling},C::AbstractMatrix) = C/(A*B+I)\n# solve (Aβ+I)X = C\nsylvd(A::AbstractMatrix,B::Union{Real,Complex,UniformScaling},C::AbstractMatrix) = (A*B+I)\\C\n# solve (αβ+1)X = C\nsylvd(A::Union{Real,Complex},B::Union{Real,Complex},C::AbstractMatrix) = A*B+1 == 0 ? throw(SingularException(1)) : C/(A*B+1)\n# solve (αβ+1)x = γ\nsylvd(A::Union{Real,Complex}, B::Union{Real,Complex}, C::Union{Real,Complex}) = A*B+1 == 0 ? throw(SingularException(1)) : C/(A*B+one(C))\n\"\"\"\n    X = gsylv(A,B,C,D,E)\n\nSolve the generalized Sylvester matrix equation\n\n              AXB + CXD = E\n\nusing a generalized Schur form based approach. `A`, `B`, `C` and `D` are\nsquare matrices. The pencils `A-λC` and `D+λB` must be regular and\nmust not have common eigenvalues.\n\nThe following particular cases are also adressed:\n\n    X = gsylv(A,B,E)\n\nSolve the generalized Sylvester matrix equation `AXB  = E`.\n\n    X = gsylv(A,B,γ*I,E)  or  X = gsylv(A,B,γ,E)\n\nSolve the generalized Sylvester matrix equation `AXB +γX = E`.\n\n    X = gsylv(A,B,γ*I,D,E)  or  X = gsylv(A,B,γ,D,E)\n\nSolve the generalized Sylvester matrix equation `AXB +γXD = E`.\n\n    X = gsylv(A,B,C,δ*I,E)  or  X = gsylv(A,B,C,δ,E)\n\nSolve the generalized Sylvester matrix equation `AXB +CXδ = E`.\n\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2×2 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2×2 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2×2 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> D = [1. -2.; -2. -1.]\n2×2 Array{Float64,2}:\n  1.0  -2.0\n -2.0  -1.0\n\njulia> E = [1. -1.; -2. 2.]\n2×2 Array{Float64,2}:\n  1.0  -1.0\n -2.0   2.0\n\njulia> X = gsylv(A, B, C, D, E)\n2×2 Array{Float64,2}:\n -0.52094   -0.0275792\n -0.168539   0.314607\n\njulia> A*X*B + C*X*D - E\n2×2 Array{Float64,2}:\n 4.44089e-16  8.88178e-16\n 6.66134e-16  0.0\n```\n\"\"\"\nfunction gsylv(A::AbstractMatrix,B::AbstractMatrix,C::AbstractMatrix,D::AbstractMatrix,E::AbstractMatrix)\n\n    m, n = size(E);\n    [m; n; m; n] == LinearAlgebra.checksquare(A,B,C,D) ||\n       throw(DimensionMismatch(\"A, B, C, D and E have incompatible dimensions\"))\n    T2 = promote_type(eltype(A), eltype(B), eltype(C), eltype(D), eltype(E))\n    T2 <: BlasFloat || (T2 = promote_type(Float64,T2))\n    eltype(A) == T2 || (A = convert(Matrix{T2},A))\n    eltype(B) == T2 || (B = convert(Matrix{T2},B))\n    eltype(C) == T2 || (C = convert(Matrix{T2},C))\n    eltype(D) == T2 || (D = convert(Matrix{T2},D))\n    eltype(E) == T2 || (E = convert(Matrix{T2},E))\n\n    adjA = isa(A,Adjoint)\n    adjB = isa(B,Adjoint)\n    adjC = isa(C,Adjoint)\n    adjD = isa(D,Adjoint)\n    adjAC = adjA && adjC\n    adjBD = adjB && adjD\n\n    if adjAC\n       AS, CS, Z1, Q1 = schur(A.parent,C.parent)\n    else\n       adjA && (A = copy(A))\n       adjC && (C = copy(C))\n       AS, CS, Q1, Z1 = schur(A,C)\n    end\n    if adjBD\n       BS, DS, Z2, Q2 = schur(B.parent,D.parent)\n    else\n       adjB && (B = copy(B))\n       adjD && (D = copy(D))\n       BS, DS, Q2, Z2 = schur(B,D)\n    end\n\n    Y = Q1' * E *Z2\n\n    gsylvs!(AS, BS, CS, DS, Y, adjAC = adjAC, adjBD = adjBD)\n\n    mul!(Y, Z1, Y*Q2')\n\n   return Y\nend\n# solve AXB = C\ngsylv(A::Union{AbstractMatrix,UniformScaling,Real,Complex},B::Union{AbstractMatrix,UniformScaling,Real,Complex},E::AbstractMatrix) = (A\\E)/B\n# solve AXB+γX = E\ngsylv(A::AbstractMatrix,B::AbstractMatrix,C::Union{UniformScaling,Real,Complex},E::AbstractMatrix) =\nsize(A,1) == size(A,2) && size(B,1) == size(B,2) ? gsylv(A,B,Matrix{eltype(C)}(C*I,size(A)),Matrix{eltype(C)}(I,size(B)),E) :\nthrow(DimensionMismatch(\"A and B must be square matrices\"))\n# solve AXB+γXδ = E\ngsylv(A::AbstractMatrix,B::AbstractMatrix,C::Union{UniformScaling,Real,Complex},D::Union{UniformScaling,Real,Complex},E::AbstractMatrix) = gsylv(A,B,C*D,E)\n# solve AXB+γXD = E\ngsylv(A::AbstractMatrix,B::AbstractMatrix,C::Union{UniformScaling,Real,Complex},D::AbstractMatrix,E::AbstractMatrix) =\nsize(A,1) == size(A,2) ? gsylv(A,B,Matrix{eltype(C)}(C*I,size(A)),D,E) :\nthrow(DimensionMismatch(\"A must be a square matrix\"))\n# solve AXB+CXδ = E\ngsylv(A::AbstractMatrix,B::AbstractMatrix,C::AbstractMatrix,D::Union{UniformScaling,Real,Complex},E::AbstractMatrix) =\nsize(B,1) == size(B,2) ? gsylv(A,B,C,Matrix{eltype(D)}(D*I,size(B)),E) :\nthrow(DimensionMismatch(\"B must be a square matrix\"))\n\n\"\"\"\n    (X,Y) = sylvsys(A,B,C,D,E,F)\n\nSolve the Sylvester system of matrix equations\n\n                AX + YB = C\n                DX + YE = F,\n\nwhere `(A,D)`, `(B,E)` are pairs of square matrices of the same size.\nThe pencils `A-λD` and `-B+λE` must be regular and must not have common eigenvalues.\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2×2 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2×2 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2×2 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> D = [1. -2.; -2. -1.]\n2×2 Array{Float64,2}:\n  1.0  -2.0\n -2.0  -1.0\n\njulia> E = [1. -1.; -2. 2.]\n2×2 Array{Float64,2}:\n  1.0  -1.0\n -2.0   2.0\n\njulia> F = [1. -1.; -2. 2.]\n2×2 Array{Float64,2}:\n  1.0  -1.0\n -2.0   2.0\n\njulia> X, Y = sylvsys(A, B, C, D, E, F);\n\njulia> X\n2×2 Array{Float64,2}:\n  1.388  -1.388\n -0.892   0.892\n\njulia> Y\n2×2 Array{Float64,2}:\n -1.788  0.192\n  0.236  0.176\n\njulia> A*X + Y*B - C\n2×2 Array{Float64,2}:\n  6.66134e-16  2.22045e-15\n -3.10862e-15  2.66454e-15\n\njulia> D*X + Y*E - F\n2×2 Array{Float64,2}:\n  1.33227e-15  -2.22045e-15\n -4.44089e-16   4.44089e-16\n```\n\"\"\"\nfunction sylvsys(A::AbstractMatrix,B::AbstractMatrix,C::AbstractMatrix,D::AbstractMatrix,E::AbstractMatrix,F::AbstractMatrix)\n\n    m, n = size(C);\n    (m == size(F,1) && n == size(F,2)) ||\n      throw(DimensionMismatch(\"C and F must have the same dimensions\"))\n    [m; n; m; n] == LinearAlgebra.checksquare(A,B,D,E) ||\n       throw(DimensionMismatch(\"A, B, C, D, E and F have incompatible dimensions\"))\n    T2 = promote_type(eltype(A), eltype(B), eltype(C), eltype(D), eltype(E), eltype(F))\n    T2 <: BlasFloat || (T2 = promote_type(Float64,T2))\n    eltype(A) == T2 || (A = convert(Matrix{T2},A))\n    eltype(B) == T2 || (B = convert(Matrix{T2},B))\n    eltype(C) == T2 || (C = convert(Matrix{T2},C))\n    eltype(D) == T2 || (D = convert(Matrix{T2},D))\n    eltype(E) == T2 || (E = convert(Matrix{T2},E))\n    eltype(F) == T2 || (F = convert(Matrix{T2},F))\n\n    isa(A,Adjoint) && (A = copy(A))\n    isa(B,Adjoint) && (B = copy(B))\n    isa(D,Adjoint) && (D = copy(D))\n    isa(E,Adjoint) && (E = copy(E))\n\n    AS, DS, Q1, Z1 = schur(A,D)\n    BS, ES, Q2, Z2 = schur(B,E)\n\n    CS = adjoint(Q1) * (C*Z2)\n    FS = adjoint(Q1) * (F*Z2)\n\n    X, Y, scale =  tgsyl!('N',AS,BS,CS,DS,ES,FS)\n\n    (rmul!(Z1*(X * adjoint(Z2)), inv(scale)), rmul!(Q1*(Y * adjoint(Q2)), inv(-scale)) )\nend\n\"\"\"\n    (X,Y) = dsylvsys(A,B,C,D,E,F)\n\nSolve the dual Sylvester system of matrix equations\n\n       AX + DY = C\n       XB + YE = F ,\n\nwhere `(A,D)`, `(B,E)` are pairs of square matrices of the same size.\nThe pencils `A-λD` and `-B+λE` must be regular and must not have common eigenvalues.\n\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2×2 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2×2 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2×2 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> D = [1. -2.; -2. -1.]\n2×2 Array{Float64,2}:\n  1.0  -2.0\n -2.0  -1.0\n\njulia> E = [1. -1.; -2. 2.]\n2×2 Array{Float64,2}:\n  1.0  -1.0\n -2.0   2.0\n\njulia> F = [1. -1.; -2. 2.]\n2×2 Array{Float64,2}:\n  1.0  -1.0\n -2.0   2.0\n\njulia> X, Y = dsylvsys(A, B, C, D, E, F);\n\njulia> X\n2×2 Array{Float64,2}:\n  2.472  -1.648\n -1.848   1.232\n\njulia> Y\n2×2 Array{Float64,2}:\n -0.496  -0.336\n  0.264   0.824\n\njulia> A*X + D*Y - C\n2×2 Array{Float64,2}:\n  4.44089e-16  0.0\n -3.55271e-15  1.55431e-15\n\njulia> X*B + Y*E - F\n2×2 Array{Float64,2}:\n -8.88178e-16   0.0\n  8.88178e-16  -4.44089e-16\n```\n\"\"\"\nfunction dsylvsys(A::AbstractMatrix,B::AbstractMatrix,C::AbstractMatrix,D::AbstractMatrix,E::AbstractMatrix,F::AbstractMatrix)\n\n    m, n = size(C);\n    (m == size(F,1) && n == size(F,2)) ||\n      throw(DimensionMismatch(\"C and F must have the same dimensions\"))\n    [m; n; m; n] == LinearAlgebra.checksquare(A,B,D,E) ||\n       throw(DimensionMismatch(\"A, B, C, D, E and F have incompatible dimensions\"))\n\n    T2 = promote_type(eltype(A), eltype(B), eltype(C), eltype(D), eltype(E), eltype(F))\n    T2 <: BlasFloat || (T2 = promote_type(Float64,T2))\n    eltype(A) == T2 || (A = convert(Matrix{T2},A))\n    eltype(B) == T2 || (B = convert(Matrix{T2},B))\n    eltype(C) == T2 || (C = convert(Matrix{T2},C))\n    eltype(D) == T2 || (D = convert(Matrix{T2},D))\n    eltype(E) == T2 || (E = convert(Matrix{T2},E))\n    eltype(F) == T2 || (F = convert(Matrix{T2},F))\n    realcase = T2 <: AbstractFloat\n    transsylv = isa(A,Adjoint) && isa(B,Adjoint) && isa(D,Adjoint) && isa(E,Adjoint)\n    realcase ? trans = 'T' : trans = 'C'\n    if transsylv\n       AS, DS, Q1, Z1 = schur(A.parent,D.parent)\n       BS, ES, Q2, Z2 = schur(B.parent,E.parent)\n       CS = adjoint(Z1) * (C*Z2)\n       FS = adjoint(Q1) * (F*Q2)\n       X, Y, scale =  tgsyl!(trans,AS,BS,CS,DS,ES,-FS)\n       (rmul!(Q1*(X * adjoint(Z2)), inv(scale)), rmul!(Q1*(Y * adjoint(Z2)), inv(scale)) )\n    else\n       AS, DS, Q1, Z1 = schur(copy(A'),copy(D'))\n       BS, ES, Q2, Z2 = schur(copy(B'),copy(E'))\n       CS = adjoint(Z1) * (C*Z2)\n       FS = adjoint(Q1) * (F*Q2)\n\n       X, Y, scale =  tgsyl!(trans,AS,BS,CS,DS,ES,-FS)\n\n       (rmul!(Q1*(X * adjoint(Z2)), inv(scale)), rmul!(Q1*(Y * adjoint(Z2)), inv(scale)) )\n    end\nend\n\"\"\"\n    sylvcs!(A,B,C; adjA = false, adjB = false)\n\nSolve the continuous Sylvester matrix equation\n\n                op(A)X + Xop(B) =  C,\n\nwhere `op(A) = A` or `op(A) = A'` if `adjA = false` or `adjA = true`, respectively,\nand `op(B) = B` or `op(B) = B'` if `adjB = false` or `adjB = true`, respectively.\n`A` and `B` are square matrices in Schur forms, and `A` and `-B` must not have\ncommon eigenvalues. `C` contains on output the solution `X`.\n\"\"\"\nfunction sylvcs!(A::AbstractMatrix{T1}, B::AbstractMatrix{T1}, C::AbstractMatrix{T1}; adjA::Bool = false, adjB::Bool = false) where  T1<:BlasFloat\n   \"\"\"\n   This is a wrapper to the LAPACK.trsylv! function, based on the Bartels-Stewart Schur form based approach.\n   Reference:\n   R. H. Bartels and G. W. Stewart. Algorithm 432: Solution of the matrix equation AX+XB=C.\n   Comm. ACM, 15:820–826, 1972.\n   \"\"\"\n   try\n      trans = T1 <: Complex ? 'C' : 'T'\n      C, scale = LAPACK.trsyl!(adjA ? trans : 'N', adjB ? trans : 'N', A, B, C)\n      rmul!(C, inv(scale))\n      return C[:,:]\n   catch err\n      findfirst(\"LAPACKException(1)\",string(err)) === nothing ? rethrow() :\n               throw(\"ME:SingularException: A has eigenvalue(s) α and B has eigenvalues(s) β such that α+β = 0\")\n   end\nend\nfunction sylvd2!(adjA::Bool, adjB::Bool, C::AbstractMatrix{T}, na::Int, nb::Int, A::AbstractMatrix{T}, B::AbstractMatrix{T}, Xw::AbstractMatrix{T}) where {T <:BlasReal}\n   # speed and reduced allocation oriented implementation of a solver for 1x1 and 2x2 Sylvester equations \n   # encountered in solving discrete Lyapunov equations: \n   # A*X*B + X = C   if adjA = false and adjB = false -> R = kron(B',A) + I \n   # A'*X*B + X = C  if adjA = true  and adjB = false -> R = kron(B',A') + I \n   # A*X*B' + X = C  if adjA = false and adjB = true  -> R = kron(B,A) + I\n   # A'*X*B' + X = C if adjA = true  and adjB = true  -> R = kron(B,A') + I\n   ONE = one(T)\n   if na == 1 && nb == 1\n      temp = A[1,1]*B[1,1] + ONE\n      rmul!(C,inv(temp))\n      any(!isfinite, C) && throw(\"ME:SingularException: A has eigenvalue(s) α and B has eigenvalues(s) β such that αβ = -1\")\n      return C\n   end\n   n = na*nb\n   i1 = 1:n\n   R = view(Xw, i1, i1)\n   Y = reshape(C, n)\n   if adjA && !adjB\n      if na == 1\n         # R12 =\n         # [ a11*b11+1      a11*b21]\n         # [     a11*b12  a11*b22+1]\n         # @inbounds R = [ A[1,1]*B[1,1]+ONE      A[1,1]*B[2,1];\n         #                 A[1,1]*B[1,2]  A[1,1]*B[2,2]+ONE]\n         @inbounds  R[1,1] = A[1,1]*B[1,1]+ONE\n         @inbounds  R[1,2] = A[1,1]*B[2,1]\n         @inbounds  R[2,1] = A[1,1]*B[1,2]\n         @inbounds  R[2,2] = A[1,1]*B[2,2]+ONE\n         # @inbounds  Y[1] = C[1,1]\n         # @inbounds  Y[2] = C[1,2]\n      else\n         if nb == 1\n            # R21 =\n            # [ a11*b11+1      a21*b11]\n            # [     a12*b11  a22*b11+1]\n            # @inbounds R = [ A[1,1]*B[1,1]+ONE      A[2,1]*B[1,1];\n            #                 A[1,2]*B[1,1]  A[2,2]*B[1,1]+ONE ]\n            @inbounds  R[1,1] = A[1,1]*B[1,1]+ONE\n            @inbounds  R[1,2] = A[2,1]*B[1,1]\n            @inbounds  R[2,1] = A[1,2]*B[1,1]\n            @inbounds  R[2,2] = A[2,2]*B[1,1]+ONE\n            # @inbounds  Y[1] = C[1,1]\n            # @inbounds  Y[2] = C[2,1]\n         else\n            # R =\n            # [ a11*b11+1      a21*b11      a11*b21      a21*b21]\n            # [     a12*b11  a22*b11+1      a12*b21      a22*b21]\n            # [     a11*b12      a21*b12  a11*b22+1      a21*b22]\n            # [     a12*b12      a22*b12      a12*b22  a22*b22+1]\n            # @inbounds R = [ A[1,1]*B[1,1]+ONE      A[2,1]*B[1,1]      A[1,1]*B[2,1]      A[2,1]*B[2,1];\n            # A[1,2]*B[1,1]  A[2,2]*B[1,1]+ONE      A[1,2]*B[2,1]      A[2,2]*B[2,1];\n            # A[1,1]*B[1,2]      A[2,1]*B[1,2]  A[1,1]*B[2,2]+ONE      A[2,1]*B[2,2];\n            # A[1,2]*B[1,2]      A[2,2]*B[1,2]      A[1,2]*B[2,2]  A[2,2]*B[2,2]+ONE]\n            @inbounds  R[1,1] = A[1,1]*B[1,1]+ONE\n            @inbounds  R[1,2] = A[2,1]*B[1,1]\n            @inbounds  R[1,3] = A[1,1]*B[2,1]\n            @inbounds  R[1,4] = A[2,1]*B[2,1]\n            @inbounds  R[2,1] = A[1,2]*B[1,1]\n            @inbounds  R[2,2] = A[2,2]*B[1,1]+ONE\n            @inbounds  R[2,3] = A[1,2]*B[2,1]\n            @inbounds  R[2,4] = A[2,2]*B[2,1]\n            @inbounds  R[3,1] = A[1,1]*B[1,2]\n            @inbounds  R[3,2] = A[2,1]*B[1,2]\n            @inbounds  R[3,3] = A[1,1]*B[2,2]+ONE\n            @inbounds  R[3,4] = A[2,1]*B[2,2]\n            @inbounds  R[4,1] = A[1,2]*B[1,2]\n            @inbounds  R[4,2] = A[2,2]*B[1,2]\n            @inbounds  R[4,3] = A[1,2]*B[2,2]\n            @inbounds  R[4,4] = A[2,2]*B[2,2]+ONE\n            # @inbounds  Y[1] = C[1,1]\n            # @inbounds  Y[2] = C[2,1]\n            # @inbounds  Y[3] = C[1,2]\n            # @inbounds  Y[4] = C[2,2]\n         end\n      end\n      #R = kron(transpose(B),A) + I\n   elseif !adjA && adjB\n      if na == 1\n         # R12 =\n         # [ a11*b11+1      a11*b12]\n         # [     a11*b21  a11*b22+1]\n         # @inbounds R = [ A[1,1]*B[1,1]+ONE      A[1,1]*B[1,2];\n         #                 A[1,1]*B[2,1]  A[1,1]*B[2,2]+ONE]\n         @inbounds  R[1,1] = A[1,1]*B[1,1]+ONE\n         @inbounds  R[1,2] = A[1,1]*B[1,2]\n         @inbounds  R[2,1] = A[1,1]*B[2,1]\n         @inbounds  R[2,2] = A[1,1]*B[2,2]+ONE\n         # @inbounds  Y[1] = C[1,1]\n         # @inbounds  Y[2] = C[1,2]\n      else\n         if nb == 1\n            # R21 =\n            #    [ a11*b11+1      a12*b11]\n            #    [     a21*b11  a22*b11+1]\n            # @inbounds R = [ A[1,1]*B[1,1]+ONE      A[1,2]*B[1,1];\n            #                 A[2,1]*B[1,1]  A[2,2]*B[1,1]+ONE]\n            @inbounds  R[1,1] = A[1,1]*B[1,1]+ONE\n            @inbounds  R[1,2] = A[1,2]*B[1,1]\n            @inbounds  R[2,1] = A[2,1]*B[1,1]\n            @inbounds  R[2,2] = A[2,2]*B[1,1]+ONE\n            # @inbounds  Y[1] = C[1,1]\n            # @inbounds  Y[2] = C[2,1]\n         else\n            # R =\n            # [ a11*b11+1      a12*b11      a11*b12      a12*b12]\n            # [     a21*b11  a22*b11+1      a21*b12      a22*b12]\n            # [     a11*b21      a12*b21  a11*b22+1      a12*b22]\n            # [     a21*b21      a22*b21      a21*b22  a22*b22+1]\n            # @inbounds R = [ A[1,1]*B[1,1]+ONE      A[1,2]*B[1,1]      A[1,1]*B[1,2]      A[1,2]*B[1,2];\n            # A[2,1]*B[1,1]  A[2,2]*B[1,1]+ONE      A[2,1]*B[1,2]      A[2,2]*B[1,2];\n            # A[1,1]*B[2,1]      A[1,2]*B[2,1]  A[1,1]*B[2,2]+ONE      A[1,2]*B[2,2];\n            # A[2,1]*B[2,1]      A[2,2]*B[2,1]      A[2,1]*B[2,2]  A[2,2]*B[2,2]+ONE]\n            @inbounds  R[1,1] = A[1,1]*B[1,1]+ONE\n            @inbounds  R[1,2] = A[1,2]*B[1,1]\n            @inbounds  R[1,3] = A[1,1]*B[1,2]\n            @inbounds  R[1,4] = A[1,2]*B[1,2]\n            @inbounds  R[2,1] = A[2,1]*B[1,1]\n            @inbounds  R[2,2] = A[2,2]*B[1,1]+ONE\n            @inbounds  R[2,3] = A[2,1]*B[1,2]\n            @inbounds  R[2,4] = A[2,2]*B[1,2]\n            @inbounds  R[3,1] = A[1,1]*B[2,1]\n            @inbounds  R[3,2] = A[1,2]*B[2,1]\n            @inbounds  R[3,3] = A[1,1]*B[2,2]+ONE\n            @inbounds  R[3,4] = A[1,2]*B[2,2]\n            @inbounds  R[4,1] = A[2,1]*B[2,1]\n            @inbounds  R[4,2] = A[2,2]*B[2,1]\n            @inbounds  R[4,3] = A[2,1]*B[2,2]\n            @inbounds  R[4,4] = A[2,2]*B[2,2]+ONE\n            # @inbounds  Y[1] = C[1,1]\n            # @inbounds  Y[2] = C[2,1]\n            # @inbounds  Y[3] = C[1,2]\n            # @inbounds  Y[4] = C[2,2]\n         end\n      end\n      #R = kron(transpose(B),transpose(A)) + I\n   elseif !adjA && !adjB\n      if na == 1\n         # R12 =\n         # [ a11*b11 + 1,     a11*b21]\n         # [     a11*b12, a11*b22 + 1]\n         # @inbounds R = [ A[1,1]*B[1,1]+ONE      A[1,1]*B[2,1];\n         #                 A[1,1]*B[1,2]  A[1,1]*B[2,2]+ONE]\n         @inbounds  R[1,1] = A[1,1]*B[1,1]+ONE\n         @inbounds  R[1,2] = A[1,1]*B[2,1]\n         @inbounds  R[2,1] = A[1,1]*B[1,2]\n         @inbounds  R[2,2] = A[1,1]*B[2,2]+ONE\n         # @inbounds  Y[1] = C[1,1]\n         # @inbounds  Y[2] = C[1,2]\n      else\n         if nb == 1\n            # R21 =\n            # [ a11*b11 + 1,     a12*b11]\n            # [     a21*b11, a22*b11 + 1]\n            # @inbounds R = [ A[1,1]*B[1,1]+ONE      A[1,2]*B[1,1];\n            #                 A[2,1]*B[1,1]  A[2,2]*B[1,1]+ONE]\n            @inbounds  R[1,1] = A[1,1]*B[1,1]+ONE\n            @inbounds  R[1,2] = A[1,2]*B[1,1]\n            @inbounds  R[2,1] = A[2,1]*B[1,1]\n            @inbounds  R[2,2] = A[2,2]*B[1,1]+ONE\n            # @inbounds  Y[1] = C[1,1]\n            # @inbounds  Y[2] = C[2,1]\n         else\n            # R =\n            # [ a11*b11 + 1,     a12*b11,     a11*b21,     a12*b21]\n            # [     a21*b11, a22*b11 + 1,     a21*b21,     a22*b21]\n            # [     a11*b12,     a12*b12, a11*b22 + 1,     a12*b22]\n            # [     a21*b12,     a22*b12,     a21*b22, a22*b22 + 1]\n            # @inbounds R = [ A[1,1]*B[1,1]+ONE      A[1,2]*B[1,1]      A[1,1]*B[2,1]      A[1,2]*B[2,1];\n            # A[2,1]*B[1,1]  A[2,2]*B[1,1]+ONE      A[2,1]*B[2,1]      A[2,2]*B[2,1];\n            # A[1,1]*B[1,2]      A[1,2]*B[1,2]  A[1,1]*B[2,2]+ONE      A[1,2]*B[2,2];\n            # A[2,1]*B[1,2]      A[2,2]*B[1,2]      A[2,1]*B[2,2]  A[2,2]*B[2,2]+ONE]\n            @inbounds  R[1,1] = A[1,1]*B[1,1]+ONE\n            @inbounds  R[1,2] = A[1,2]*B[1,1]\n            @inbounds  R[1,3] = A[1,1]*B[2,1]\n            @inbounds  R[1,4] = A[1,2]*B[2,1]\n            @inbounds  R[2,1] = A[2,1]*B[1,1]\n            @inbounds  R[2,2] = A[2,2]*B[1,1]+ONE\n            @inbounds  R[2,3] = A[2,1]*B[2,1]\n            @inbounds  R[2,4] = A[2,2]*B[2,1]\n            @inbounds  R[3,1] = A[1,1]*B[1,2]\n            @inbounds  R[3,2] = A[1,2]*B[1,2]\n            @inbounds  R[3,3] = A[1,1]*B[2,2]+ONE\n            @inbounds  R[3,4] = A[1,2]*B[2,2]\n            @inbounds  R[4,1] = A[2,1]*B[1,2]\n            @inbounds  R[4,2] = A[2,2]*B[1,2]\n            @inbounds  R[4,3] = A[2,1]*B[2,2]\n            @inbounds  R[4,4] = A[2,2]*B[2,2]+ONE\n            # @inbounds  Y[1] = C[1,1]\n            # @inbounds  Y[2] = C[2,1]\n            # @inbounds  Y[3] = C[1,2]\n            # @inbounds  Y[4] = C[2,2]\n         end\n      end\n      #R = kron(B,A) + I\n   else\n      if na == 1\n         # R12 =\n         # [ a11*b11 + 1,     a11*b12]\n         # [     a11*b21, a11*b22 + 1]\n         # @inbounds R = [ A[1,1]*B[1,1]+ONE      A[1,1]*B[1,2];\n         #                 A[1,1]*B[2,1]  A[1,1]*B[2,2]+ONE]\n         @inbounds  R[1,1] = A[1,1]*B[1,1]+ONE\n         @inbounds  R[1,2] = A[1,1]*B[1,2]\n         @inbounds  R[2,1] = A[1,1]*B[2,1]\n         @inbounds  R[2,2] = A[1,1]*B[2,2]+ONE\n         # @inbounds  Y[1] = C[1,1]\n         # @inbounds  Y[2] = C[1,2]\n      else\n         if nb == 1\n            # R21 =\n            # [ a11*b11 + 1,     a21*b11]\n            # [     a12*b11, a22*b11 + 1]\n            # @inbounds R = [ A[1,1]*B[1,1]+ONE      A[2,1]*B[1,1];\n            #                 A[1,2]*B[1,1]  A[2,2]*B[1,1]+ONE]\n            @inbounds  R[1,1] = A[1,1]*B[1,1]+ONE\n            @inbounds  R[1,2] = A[2,1]*B[1,1]\n            @inbounds  R[2,1] = A[1,2]*B[1,1]\n            @inbounds  R[2,2] = A[2,2]*B[1,1]+ONE\n            # @inbounds  Y[1] = C[1,1]\n            # @inbounds  Y[2] = C[2,1]\n         else\n            # R =\n            # [ a11*b11 + 1,     a21*b11,     a11*b12,     a21*b12]\n            # [     a12*b11, a22*b11 + 1,     a12*b12,     a22*b12]\n            # [     a11*b21,     a21*b21, a11*b22 + 1,     a21*b22]\n            # [     a12*b21,     a22*b21,     a12*b22, a22*b22 + 1]\n            # @inbounds R = [ A[1,1]*B[1,1]+ONE      A[2,1]*B[1,1]      A[1,1]*B[1,2]      A[2,1]*B[1,2];\n            # A[1,2]*B[1,1]  A[2,2]*B[1,1]+ONE      A[1,2]*B[1,2]      A[2,2]*B[1,2];\n            # A[1,1]*B[2,1]      A[2,1]*B[2,1]  A[1,1]*B[2,2]+ONE      A[2,1]*B[2,2];\n            # A[1,2]*B[2,1]      A[2,2]*B[2,1]      A[1,2]*B[2,2]  A[2,2]*B[2,2]+ONE]\n            @inbounds  R[1,1] = A[1,1]*B[1,1]+ONE\n            @inbounds  R[1,2] = A[2,1]*B[1,1]\n            @inbounds  R[1,3] = A[1,1]*B[1,2]\n            @inbounds  R[1,4] = A[2,1]*B[1,2]\n            @inbounds  R[2,1] = A[1,2]*B[1,1]\n            @inbounds  R[2,2] = A[2,2]*B[1,1]+ONE\n            @inbounds  R[2,3] = A[1,2]*B[1,2]\n            @inbounds  R[2,4] = A[2,2]*B[1,2]\n            @inbounds  R[3,1] = A[1,1]*B[2,1]\n            @inbounds  R[3,2] = A[2,1]*B[2,1]\n            @inbounds  R[3,3] = A[1,1]*B[2,2]+ONE\n            @inbounds  R[3,4] = A[2,1]*B[2,2]\n            @inbounds  R[4,1] = A[1,2]*B[2,1]\n            @inbounds  R[4,2] = A[2,2]*B[2,1]\n            @inbounds  R[4,3] = A[1,2]*B[2,2]\n            @inbounds  R[4,4] = A[2,2]*B[2,2]+ONE\n            # @inbounds  Y[1] = C[1,1]\n            # @inbounds  Y[2] = C[2,1]\n            # @inbounds  Y[3] = C[1,2]\n            # @inbounds  Y[4] = C[2,2]\n         end\n         #R = kron(B,transpose(A)) + I\n      end\n   end\n   luslv!(R,Y) && throw(\"ME:SingularException: A has eigenvalue(s) α and B has eingenvalu(s) β such that αβ = -1\")\n   #C[:,:] = Y\n   return C\nend\n\"\"\"\n    sylvds!(A,B,C; adjA = false, adjB = false)\n\nSolve the discrete Sylvester matrix equation\n\n                op(A)Xop(B) + X =  C,\n\nwhere `op(A) = A` or `op(A) = A'` if `adjA = false` or `adjA = true`, respectively,\nand `op(B) = B` or `op(B) = B'` if `adjB = false` or `adjB = true`, respectively.\n`A` and `B` are square matrices in Schur forms, and `A` and `-B` must not have\ncommon reciprocal eigenvalues. `C` contains on output the solution `X`.\n\"\"\"\nfunction sylvds!(A::AbstractMatrix{T1}, B::AbstractMatrix{T1}, C::AbstractMatrix{T1}, W::AbstractMatrix{T1} = similar(A,size(A,1),2); adjA::Bool = false, adjB::Bool = false) where  T1<:BlasReal\n   \"\"\"\n   An extension of the Bartels-Stewart Schur form based approach is employed.\n\n   Reference:\n   R. H. Bartels and G. W. Stewart. Algorithm 432: Solution of the matrix equation AX+XB=C.\n   Comm. ACM, 15:820–826, 1972.\n   \"\"\"\n   m, n = LinearAlgebra.checksquare(A,B)\n   (size(C,1) == m && size(C,2) == n ) || throw(DimensionMismatch(\"C must be an $m x $n matrix\"))\n   (m, 2) == size(W) || throw(DimensionMismatch(\"W must be an $m x 2 matrix\"))\n   ONE = one(T1)\n\n   # determine the structure of the real Schur form of A\n   ba, pa = sfstruct(A)\n   bb, pb = sfstruct(B)\n   \n   G = Matrix{T1}(undef,2,2)\n   WA = Matrix{T1}(undef,2,2)\n\n   Xw = Matrix{T1}(undef,4,4)\n   if !adjA && !adjB\n      # \"\"\"\n      # The (K,L)th block of X is determined starting from\n      # bottom-left corner column by column by\n\n      #            A(K,K)*X(K,L)*B(L,L) + X(K,L) = C(K,L) - R(K,L)\n\n      # where\n      #                        M\n      #            R(K,L) = { SUM [A(K,J)*X(J,L)] } * B(L,L) +\n      #                      J=K+1\n      #                        M             L-1\n      #                       SUM { A(K,J) * SUM [X(J,I)*B(I,L)] }.\n      #                       J=K            I=1\n      # \"\"\"\n      j = 1\n      for ll = 1:pb\n          dl = bb[ll]\n          dll = 1:dl\n          il1 = 1:j-1\n          j1 = j+dl-1\n          l = j:j1\n          i = m\n          for kk = pa:-1:1\n              dk = ba[kk]\n              dkk = 1:dk\n              i1 = i-dk+1\n              k = i1:i\n              Ckl = view(C,k,l)\n              y = view(G,1:dk,1:dl)\n              copyto!(y,Ckl)\n              if kk < pa\n                 ir = i+1:m\n                 W1 = view(WA,dkk,dll)\n                 mul!(W1,view(A,k,ir),view(C,ir,l))\n                 mul!(y,W1,view(B,l,l),-ONE,ONE)\n              end\n              if ll > 1\n                 ic = i1:m\n                 mul!(view(W,k,dll),view(C,k,il1),view(B,il1,l))\n                 mul!(y,view(A,k,ic),view(W,ic,dll),-ONE,ONE)\n              end\n              sylvd2!(adjA,adjB,y,dk,dl,view(A,k,k),view(B,l,l),Xw)  \n              copyto!(Ckl,y)\n           i -= dk\n          end\n          j += dl\n      end\n   elseif !adjA && adjB\n         # \"\"\"\n         # The (K,L)th block of X is determined starting from\n         # bottom-right corner column by column by\n\n         #             A(K,K)*X(K,L)*B(L,L)' + X(K,L) = C(K,L) - R(K,L)\n\n         # where\n         #                        M\n         #            R(K,L) = { SUM [A(K,J)*X(J,L)] } * B(L,L)' +\n         #                      J=K+1\n         #                        M              N\n         #                       SUM { A(K,J) * SUM [X(J,I)*B(L,I)'] }.\n         #                       J=K           I=L+1\n         # \"\"\"\n         j = n\n         for ll = pb:-1:1\n             dl = bb[ll]\n             dll = 1:dl\n             il1 = j+1:n\n             l = j-dl+1:j\n             i = m\n             for kk = pa:-1:1\n                 dk = ba[kk]\n                 dkk = 1:dk\n                 i1 = i-dk+1\n                 k = i1:i\n                 Ckl = view(C,k,l)\n                 y = view(G,1:dk,1:dl)\n                 copyto!(y,Ckl)\n                 if kk < pa\n                    ir = i+1:m\n                    W1 = view(WA,dkk,dll)\n                    mul!(W1,view(A,k,ir),view(C,ir,l))\n                    mul!(y,W1,adjoint(view(B,l,l)),-ONE,ONE)\n                 end\n                 if ll < pb\n                    ic = i1:m\n                    mul!(view(W,k,dll),view(C,k,il1),adjoint(view(B,l,il1)))\n                    mul!(y,view(A,k,ic),view(W,ic,dll),-ONE,ONE)\n                 end\n                 sylvd2!(adjA,adjB,y,dk,dl,view(A,k,k),view(B,l,l),Xw)  \n                 copyto!(Ckl,y)\n                 i -= dk\n             end\n             j -= dl\n         end\n   elseif adjA && !adjB\n      # \"\"\"\n      # The (K,L)th block of X is determined starting from the\n      # upper-left corner column by column by\n\n      # A(K,K)'*X(K,L)*B(L,L) + X(K,L) = C(K,L) - R(K,L),\n\n      # where\n      #                       K-1\n      #            R(K,L) = { SUM [A(J,K)'*X(J,L)] } * B(L,L) +\n      #                       J=1\n      #                        K              L-1\n      #                       SUM A(J,K)' * { SUM [X(J,I)*B(I,L)] }.\n      #                       J=1             I=1\n      # \"\"\"\n      j = 1\n      for ll = 1:pb\n          dl = bb[ll]\n          dll = 1:dl\n          il1 = 1:j-1\n          j1 = j+dl-1\n          l = j:j1\n          i = 1\n          for kk = 1:pa\n              dk = ba[kk]\n              dkk = 1:dk\n              i1 = i+dk-1\n              k = i:i1\n              Ckl = view(C,k,l)\n              y = view(G,1:dk,1:dl)\n              copyto!(y,Ckl)\n              if kk > 1\n                 ir = 1:i-1\n                 W1 = view(WA,dkk,dll)\n                 mul!(W1,adjoint(view(A,ir,k)),view(C,ir,l))\n                 mul!(y,W1,view(B,l,l),-ONE,ONE)\n              end\n              if ll > 1\n                 ic = 1:i1\n                 mul!(view(W,k,dll),view(C,k,il1),view(B,il1,l))\n                 mul!(y,adjoint(view(A,ic,k)),view(W,ic,dll),-ONE,ONE)\n              end\n              sylvd2!(adjA,adjB,y,dk,dl,view(A,k,k),view(B,l,l),Xw)  \n              copyto!(Ckl,y)\n           i += dk\n          end\n          j += dl\n      end\n   elseif adjA && adjB\n      # \"\"\"\n      # The (K,L)th block of X is determined starting from the\n      # lower-left corner column by column by\n\n      #            A(K,K)'*X(K,L)*B(L,L)' + X(K,L) = C(K,L) - R(K,L)\n\n      # where\n      #                       K-1\n      #            R(K,L) = { SUM [A(J,K)'*X(J,L)] } * B(L,L)' +\n      #                       J=1\n      #                        K               N\n      #                       SUM A(J,K)' * { SUM [X(J,I)*B(L,I)'] }.\n      #                       J=1            I=L+1\n      # \"\"\"\n      j = n\n      for ll = pb:-1:1\n          dl = bb[ll]\n          dll = 1:dl\n          il1 = j+1:n\n          l = j-dl+1:j\n          i = 1\n          for kk = 1:pa\n              dk = ba[kk]\n              dkk = 1:dk\n              i1 = i+dk-1\n              k = i:i1\n              Ckl = view(C,k,l)\n              y = view(G,1:dk,1:dl)\n              copyto!(y,Ckl)\n              if kk > 1\n                 ir = 1:i-1\n                 W1 = view(WA,dkk,dll)\n                 mul!(W1,adjoint(view(A,ir,k)),view(C,ir,l))\n                 mul!(y,W1,adjoint(view(B,l,l)),-ONE,ONE)\n              end\n              if ll < pb\n                 ic = 1:i1\n                 mul!(view(W,k,dll),view(C,k,il1),adjoint(view(B,l,il1)))\n                 mul!(y,adjoint(view(A,ic,k)),view(W,ic,dll),-ONE,ONE)\n              end\n              sylvd2!(adjA,adjB,y,dk,dl,view(A,k,k),view(B,l,l),Xw)  \n              copyto!(Ckl,y)\n           i += dk\n          end\n          j -= dl\n      end\n   end\n   return C\nend\nfunction sylvds!(A::AbstractMatrix{T1}, B::AbstractMatrix{T1}, C::AbstractMatrix{T1}, W::AbstractVector{T1} = similar(A,size(A,1)); adjA::Bool = false, adjB::Bool = false) where  T1<:BlasComplex\n   \"\"\"\n   An extension of the Bartels-Stewart Schur form based approach is employed.\n\n   Reference:\n   R. H. Bartels and G. W. Stewart. Algorithm 432: Solution of the matrix equation AX+XB=C.\n   Comm. ACM, 15:820–826, 1972.\n   \"\"\"\n   m, n = LinearAlgebra.checksquare(A,B)\n   (size(C,1) == m && size(C,2) == n ) || throw(DimensionMismatch(\"C must be an $m x $n matrix\"))\n  \n   ONE = one(T1)\n   ZERO = zero(T1)\n   if !adjA && !adjB\n      # \"\"\"\n      # The (K,L)th element of X is determined starting from\n      # bottom-left corner column by column by\n\n      #            A(K,K)*X(K,L)*B(L,L) + X(K,L) = C(K,L) - R(K,L)\n\n      # where\n      #                        M\n      #            R(K,L) = { SUM [A(K,J)*X(J,L)] } * B(L,L) +\n      #                      J=K+1\n      #                        M             L-1\n      #                       SUM { A(K,J) * SUM [X(J,I)*B(I,L)] }.\n      #                       J=K            I=1\n      # \"\"\"\n      for l = 1:n\n          il1 = 1:l-1\n          for k = m:-1:1\n              y = C[k,l]\n              if k < m\n                 ta = ZERO\n                 for ir = k+1:m\n                     ta += A[k,ir]*C[ir,l]\n                 end\n                 y -= ta*B[l,l]\n              end\n              if l > 1\n                 tz = ZERO\n                 for ir = il1\n                     tz += C[k,ir]*B[ir,l]\n                 end\n                 W[k] = tz\n                 for ic = k:m\n                     y -= A[k,ic]*W[ic]\n                 end\n              end\n              C[k,l] = y/(B[l,l]*A[k,k]+ONE)\n              isfinite(C[k,l]) || throw(\"ME:SingularException: A and -B have common or close reciprocal eigenvalues\")\n             end\n      end\n   elseif !adjA && adjB\n         # \"\"\"\n         # The (K,L)th element of X is determined starting from\n         # bottom-right corner column by column by\n\n         #          A(K,K)*X(K,L)*B(L,L)' + X(K,L) = C(K,L) - R(K,L)\n\n         # where\n         #                        M\n         #            R(K,L) = { SUM [A(K,J)*X(J,L)] } * B(L,L)' +\n         #                      J=K+1\n         #                        M              N\n         #                       SUM { A(K,J) * SUM [X(J,I)*B(L,I)'] }.\n         #                       J=K           I=L+1\n         # \"\"\"\n         for l = n:-1:1\n             il1 = l+1:n\n             for k = m:-1:1\n                 y = C[k,l]\n                 if k < m\n                    ta = ZERO\n                    for ir = k+1:m\n                       ta += A[k,ir]*C[ir,l]\n                    end\n                    y -= ta*B[l,l]'\n                 end\n                 if l < n\n                    tz = ZERO\n                    for ir = il1\n                        tz += C[k,ir]*B[l,ir]'\n                    end\n                    W[k] = tz\n                    for ic = k:m\n                        y -= A[k,ic]*W[ic]\n                    end\n                 end\n                 C[k,l] = y/(B[l,l]'*A[k,k]+ONE)\n                 isfinite(C[k,l]) || throw(\"ME:SingularException: A and -B have common or close reciprocal eigenvalues\")\n             end\n         end\n   elseif adjA && !adjB\n      # \"\"\"\n      # The (K,L)th element of X is determined starting from the\n      # upper-left corner column by column by\n\n      #          A(K,K)'*X(K,L)*B(L,L) + X(K,L) = C(K,L) - R(K,L),\n\n      # where\n      #                       K-1\n      #            R(K,L) = { SUM [A(J,K)'*X(J,L)] } * B(L,L) +\n      #                       J=1\n      #                        K              L-1\n      #                       SUM A(J,K)' * { SUM [X(J,I)*B(I,L)] }.\n      #                       J=1             I=1\n      # \"\"\"\n      for l = 1:n\n          il1 = 1:l-1\n          for k = 1:m\n              y = C[k,l]\n              if k > 1\n                 ta = ZERO\n                 for ir = 1:k-1\n                     ta += A[ir,k]'*C[ir,l]\n                 end\n                 y -= ta*B[l,l]\n              end\n              if l > 1\n                 ic = 1:m\n                 tz = ZERO\n                 for ir = il1\n                     tz += C[k,ir]*B[ir,l]\n                 end\n                 W[k] = tz\n                 for ic = 1:m\n                     y -= A[ic,k]'*W[ic]\n                 end\n              end\n              C[k,l] = y/(B[l,l]*A[k,k]'+ONE)\n              isfinite(C[k,l]) || throw(\"ME:SingularException: A and -B have common or close reciprocal eigenvalues\")\n         end\n      end\n   elseif adjA && adjB\n      # \"\"\"\n      # The (K,L)th element of X is determined starting from the\n      # upper-right corner column by column by\n\n      #         A(K,K)'*X(K,L)*B(L,L)' + X(K,L) = C(K,L) - R(K,L)\n\n      # where\n      #                       K-1\n      #            R(K,L) = { SUM [A(J,K)'*X(J,L)] } * B(L,L)' +\n      #                       J=1\n      #                        K               N\n      #                       SUM A(J,K)' * { SUM [X(J,I)*B(L,I)'] }.\n      #                       J=1            I=L+1\n      # \"\"\"\n      for l = n:-1:1\n          il1 = l+1:n\n          for k = 1:m\n              y = C[k,l]\n              if k > 1\n                 ta = ZERO\n                 for ir = 1:k-1\n                     ta += A[ir,k]'*C[ir,l]\n                 end\n                 y -= ta*B[l,l]'\n              end\n              if l < n\n                 ic = 1:m\n                 tz = ZERO\n                 for ir = il1\n                     tz += C[k,ir]*B[l,ir]'\n                 end\n                 W[k] = tz\n                 for ic = 1:m\n                     y -= A[ic,k]'*W[ic]\n                 end\n              end\n              C[k,l] = y/(B[l,l]'*A[k,k]'+ONE)\n              isfinite(C[k,l]) || throw(\"ME:SingularException: A and -B have common or close reciprocal eigenvalues\")\n          end\n      end\n   end\n   return C\nend\n\"\"\"\n    X = gsylvs!(A,B,C,D,E; adjAC=false, adjBD=false, CASchur = false, DBSchur = false)\n\nSolve the generalized Sylvester matrix equation\n\n                op1(A)Xop2(B) + op1(C)Xop2(D) = E,\n\nwhere `A`, `B`, `C` and `D` are square matrices, and\n\n`op1(A) = A` and `op1(C) = C` if `adjAC = false`;\n\n`op1(A) = A'` and `op1(C) = C'` if `adjAC = true`;\n\n`op2(B) = B` and `op2(D) = D` if `adjBD = false`;\n\n`op2(B) = B'` and `op2(D) = D'` if `adjBD = true`.\n\nThe matrix pair `(A,C)` is in a generalized real or complex Schur form.\nThe matrix pair `(B,D)` is in a generalized real or complex Schur form if `DBSchur = false`\nor the matrix pair `(D,B)` is in a generalized real or complex Schur form if `DBSchur = true`.\nThe pencils `A-λC` and `D+λB` must be regular and must not have common eigenvalues.\n\"\"\"\nfunction gsylvs!(A::AbstractMatrix{T1}, B::AbstractMatrix{T1}, C::AbstractMatrix{T1}, D::AbstractMatrix{T1}, E::AbstractMatrix{T1}, \n                 WB::AbstractMatrix{T1} = similar(A,size(A,1),2), WD::AbstractMatrix{T1} = similar(A,size(A,1),2); \n                 adjAC::Bool = false, adjBD::Bool = false, CASchur::Bool = false, DBSchur::Bool = false) where T1<:BlasReal\n   \"\"\"\n   An extension proposed in [1] of the Bartels-Stewart Schur form based approach [2] is employed.\n\n   References:\n   [1] K.-W. E. Chu. The solution of the matrix equation AXB – CXD = E and\n       (YA – DZ, YC– BZ) = (E, F). Lin. Alg. Appl., 93:93-105, 1987.\n   [2] R. H. Bartels and G. W. Stewart. Algorithm 432: Solution of the matrix equation AX+XB=C.\n       Comm. ACM, 15:820–826, 1972.\n   \"\"\"\n   m, n = size(E);\n   [m; n; m; n] == LinearAlgebra.checksquare(A,B,C,D) ||\n      throw(DimensionMismatch(\"A, B, C, D and E have incompatible dimensions\"))\n\n   (m, 2) == size(WB) || throw(DimensionMismatch(\"WB must be an $m x 2 matrix\"))\n   (m, 2) == size(WD) || throw(DimensionMismatch(\"WD must be an $m x 2 matrix\"))\n   \n   ONE = one(T1)\n\n   # determine the structure of the generalized real Schur form of (A,C)\n   CASchur ? ((ba, pa) = sfstruct(C)) : ((ba, pa) = sfstruct(A))\n   DBSchur ? ((bb, pb) = sfstruct(D)) : ((bb, pb) = sfstruct(B))\n\n   # WB = zeros(T1,m,2)\n   # WD = zeros(T1,m,2)\n   Xw = Matrix{T1}(undef,4,4)\n   if !adjAC && !adjBD\n      # \"\"\"\n      # The (K,L)th block of X is determined starting from\n      # bottom-left corner column by column by\n\n      #       A(K,K)*X(K,L)*B(L,L) + C(K,K)*X(K,L)*D(L,L) = E(K,L) - R(K,L)\n\n      # where\n      #                        M\n      #            R(K,L) = { SUM [A(K,J)*X(J,L)] } * B(L,L) +\n      #                      J=K+1\n      #                        M             L-1\n      #                       SUM { A(K,J) * SUM [X(J,I)*B(I,L)] } +\n      #                       J=K            I=1\n\n      #                        M\n      #                     { SUM [C(K,J)*X(J,L)] } * D(L,L) +\n      #                      J=K+1\n      #                        M             L-1\n      #                       SUM { C(K,J) * SUM [X(J,I)*D(I,L)] }.\n      #                       J=K            I=1\n      # \"\"\"\n      j = 1\n      for ll = 1:pb\n          dl = bb[ll]\n          dll = 1:dl\n          il1 = 1:j-1\n          j1 = j+dl-1\n          l = j:j1\n          i = m\n          for kk = pa:-1:1\n              dk = ba[kk]\n              dkk = 1:dk\n              i1 = i-dk+1\n              k = i1:i\n              y = view(E,k,l)\n              W1 = view(Xw,dkk,dll)\n              if kk < pa\n                 ir = i+1:m\n                 #W1 = A[k,ir]*E[ir,l]\n                 mul!(W1,view(A,k,ir),view(E,ir,l))\n                 #y -= W1*B[l,l]\n                 mul!(y,W1,view(B,l,l),-ONE,ONE)\n                 #W1 = C[k,ir]*E[ir,l]\n                 mul!(W1,view(C,k,ir),view(E,ir,l))\n                 #y -= W1*D[l,l]\n                 mul!(y,W1,view(D,l,l),-ONE,ONE)\n              end\n              if ll > 1\n                 ic = i1:m\n                 # WB[k,dll] = E[k,il1]*B[il1,l]\n                 mul!(view(WB,k,dll),view(E,k,il1),view(B,il1,l))\n                 # WD[k,dll] = E[k,il1]*D[il1,l]\n                 mul!(view(WD,k,dll),view(E,k,il1),view(D,il1,l))\n                 # y -= (A[k,ic]*WB[ic,dll] + C[k,ic]*WD[ic,dll])\n                 mul!(y,view(A,k,ic),view(WB,ic,dll),-ONE,ONE)\n                 mul!(y,view(C,k,ic),view(WD,ic,dll),-ONE,ONE)\n              end\n              gsylv2!(adjAC,adjBD,y,dk,dl,view(A,k,k),view(B,l,l),view(C,k,k),view(D,l,l),Xw) \n              i -= dk\n          end\n          j += dl\n      end\n   elseif !adjAC && adjBD\n         # \"\"\"\n         #  The (K,L)th block of X is determined starting from\n         #  bottom-right corner column by column by\n\n         #       A(K,K)*X(K,L)*B(L,L)' + C(K,K)*X(K,L)*D(L,L)' = E(K,L) - R(K,L)\n\n         #  where\n         #                        M\n         #            R(K,L) = { SUM [A(K,J)*X(J,L)] } * B(L,L)' +\n         #                      J=K+1\n         #                        M              N\n         #                       SUM { A(K,J) * SUM [X(J,I)*B(L,I)'] } +\n         #                       J=K           I=L+1\n\n         #                       M\n         #                    { SUM [C(K,J)*X(J,L)] } * D(L,L)' +\n         #                     J=K+1\n         #                       M              N\n         #                      SUM { C(K,J) * SUM [X(J,I)*D(L,I)'] }.\n         #                      J=K           I=L+1\n         # \"\"\"\n         j = n\n         for ll = pb:-1:1\n             dl = bb[ll]\n             dll = 1:dl\n             il1 = j+1:n\n             l = j-dl+1:j\n             i = m\n             for kk = pa:-1:1\n                 dk = ba[kk]\n                 dkk = 1:dk\n                 i1 = i-dk+1\n                 k = i1:i\n                 y = view(E,k,l)\n                 W1 = view(Xw,dkk,dll)\n                 if kk < pa\n                    ir = i+1:m\n                    #W1 = A[k,ir]*E[ir,l]\n                    mul!(W1,view(A,k,ir),view(E,ir,l))\n                    #y -= W1*B[l,l]'\n                    mul!(y,W1,transpose(view(B,l,l)),-ONE,ONE)\n                    #W2 = C[k,ir]*E[ir,l]\n                    mul!(W1,view(C,k,ir),view(E,ir,l))\n                    # y -= W1*D[l,l]'\n                    mul!(y,W1,transpose(view(D,l,l)),-ONE,ONE)\n                  end\n                 if ll < pb\n                    ic = i1:m\n                    #WB[k,dll] = E[k,il1]*B[l,il1]'\n                    mul!(view(WB,k,dll),view(E,k,il1),transpose(view(B,l,il1)))\n                    #WD[k,dll] = E[k,il1]*D[l,il1]'\n                    mul!(view(WD,k,dll),view(E,k,il1),transpose(view(D,l,il1)))\n                    #y -= (A[k,ic]*WB[ic,dll]+C[k,ic]*WD[ic,dll])\n                    mul!(y,view(A,k,ic),view(WB,ic,dll),-ONE,ONE)\n                    mul!(y,view(C,k,ic),view(WD,ic,dll),-ONE,ONE)\n                 end\n                 gsylv2!(adjAC,adjBD,y,dk,dl,view(A,k,k),view(B,l,l),view(C,k,k),view(D,l,l),Xw) \n                 i -= dk\n             end\n             j -= dl\n         end\n   elseif adjAC && !adjBD\n      # \"\"\"\n      # The (K,L)th block of X is determined starting from the\n      # upper-left corner column by column by\n\n      # A(K,K)'*X(K,L)*B(L,L) + C(K,K)'*X(K,L)*D(L,L) = E(K,L) - R(K,L),\n\n      # where\n      #                       K-1\n      #            R(K,L) = { SUM [A(J,K)'*X(J,L)] } * B(L,L) +\n      #                       J=1\n      #                        K              L-1\n      #                       SUM A(J,K)' * { SUM [X(J,I)*B(I,L)] } +\n      #                       J=1             I=1\n\n      #                       K-1\n      #                     { SUM [C(J,K)'*X(J,L)] } * D(L,L) +\n      #                       J=1\n      #                        K              L-1\n      #                       SUM C(J,K)' * { SUM [X(J,I)*D(I,L)] }.\n      #                       J=1             I=1\n      # \"\"\"\n      j = 1\n      for ll = 1:pb\n          dl = bb[ll]\n          dll = 1:dl\n          il1 = 1:j-1\n          j1 = j+dl-1\n          l = j:j1\n          i = 1\n          for kk = 1:pa\n              dk = ba[kk]\n              dkk = 1:dk\n              i1 = i+dk-1\n              k = i:i1\n              y = view(E,k,l)\n              W1 = view(Xw,dkk,dll)\n              if kk > 1\n                 ir = 1:i-1\n                 # W1 = A[ir,k]'*E[ir,l]\n                 mul!(W1,transpose(view(A,ir,k)),view(E,ir,l))\n                 #y -= W1*B[l,l]\n                 mul!(y,W1,view(B,l,l),-ONE,ONE)\n                 mul!(W1,transpose(view(C,ir,k)),view(E,ir,l))\n                 #y -= W1*D[l,l]\n                 mul!(y,W1,view(D,l,l),-ONE,ONE)\n              end\n              if ll > 1\n                 ic = 1:i1\n                 #WB[k,dll] = E[k,il1]*B[il1,l]\n                 mul!(view(WB,k,dll),view(E,k,il1),view(B,il1,l))\n                 #y -= A[ic,k]'*WB[ic,dll]\n                 mul!(y,transpose(view(A,ic,k)),view(WB,ic,dll),-ONE,ONE)\n                 #WD[k,dll] = E[k,il1]*D[il1,l]\n                 mul!(view(WD,k,dll),view(E,k,il1),view(D,il1,l))\n                 #y -= C[ic,k]'*WD[ic,dll]\n                 mul!(y,transpose(view(C,ic,k)),view(WD,ic,dll),-ONE,ONE)\n              end\n              gsylv2!(adjAC,adjBD,y,dk,dl,view(A,k,k),view(B,l,l),view(C,k,k),view(D,l,l),Xw) \n              i += dk\n          end\n          j += dl\n      end\n   elseif adjAC && adjBD\n      # \"\"\"\n      # The (K,L)th block of X is determined starting from\n      # upper-right corner column by column by\n\n      #            A(K,K)'*X(K,L)*B(L,L)' + C(K,K)'*X(K,L)*D(L,L)' = E(K,L) - R(K,L)\n\n      # where\n      #                       K-1\n      #            R(K,L) = { SUM [A(J,K)'*X(J,L)] } * B(L,L)' +\n      #                       J=1\n      #                        K               N\n      #                       SUM A(J,K)' * { SUM [X(J,I)*B(L,I)'] }+\n      #                       J=1            I=L+1\n\n      #                       K-1\n      #                     { SUM [C(J,K)'*X(J,L)] } * D(L,L)' +\n      #                       J=1\n      #                        K               N\n      #                       SUM C(J,K)' * { SUM [X(J,I)*D(L,I)'] }.\n      #                       J=1            I=L+1\n      # \"\"\"\n      j = n\n      for ll = pb:-1:1\n          dl = bb[ll]\n          dll = 1:dl\n          il1 = j+1:n\n          l = j-dl+1:j\n          i = 1\n          for kk = 1:pa\n              dk = ba[kk]\n              dkk = 1:dk\n              i1 = i+dk-1\n              k = i:i1\n              y = view(E,k,l)\n              W1 = view(Xw,dkk,dll)\n              if kk > 1\n                 ir = 1:i-1\n                 #W1 = A[ir,k]'*E[ir,l]\n                 mul!(W1,transpose(view(A,ir,k)),view(E,ir,l))\n                 #y -= W1*B[l,l]'\n                 mul!(y,W1,transpose(view(B,l,l)),-ONE,ONE)\n                 #   W2 = C[ir,k]'*E[ir,l]\n               #   y -= W2*D[l,l]'\n                 mul!(W1,transpose(view(C,ir,k)),view(E,ir,l))\n                 #y -= W1*D[l,l]'\n                 mul!(y,W1,transpose(view(D,l,l)),-ONE,ONE)\n               end\n              if ll < pb\n                 ic = 1:i1\n                 #WB[k,dll] = E[k,il1]*B[l,il1]'\n                 mul!(view(WB,k,dll),view(E,k,il1),transpose(view(B,l,il1)))\n                 #WD[k,dll] = E[k,il1]*D[l,il1]'\n                 mul!(view(WD,k,dll),view(E,k,il1),transpose(view(D,l,il1)))\n                 #y -= (A[ic,k]'*WB[ic,dll] + C[ic,k]'*WD[ic,dll])\n                 mul!(y,transpose(view(A,ic,k)),view(WB,ic,dll),-ONE,ONE)\n                 mul!(y,transpose(view(C,ic,k)),view(WD,ic,dll),-ONE,ONE)\n              end\n              gsylv2!(adjAC,adjBD,y,dk,dl,view(A,k,k),view(B,l,l),view(C,k,k),view(D,l,l),Xw) \n              i += dk\n          end\n          j -= dl\n      end\n   end\n   return E\nend\n@inline function gsylv2!(adjAC::Bool,adjBD::Bool,E::StridedMatrix{T},na::Int,nb::Int,A::AbstractMatrix{T},B::AbstractMatrix{T},C::AbstractMatrix{T},D::AbstractMatrix{T},Xw::StridedMatrix{T}) where T <:BlasReal\n   # speed and reduced allocation oriented implementation of a solver for 1x1 and 2x2 generalized Sylvester equations: \n   #      A*X*B + C*X*D = E     if adjAC = false and adjBD = false -> R = kron(B',A)  + kron(D',C) \n   #      A'*X*B + C'*X*D = E   if adjAC = true and adjBD = false  -> R = kron(B',A') + kron(D',C')\n   #      A*X*B' + C*X*D' = E   if adjAC = false and adjBD = true  -> R = kron(B,A)   + kron(D,C)\n   #      A'*X*B' + C'*X*D' = E if adjAC = true and adjBD = true   -> R = kron(B,A')  + kron(D,C')\n   if na == 1 && nb == 1\n      temp = A[1,1]*B[1,1] + C[1,1]*D[1,1]\n      rmul!(E,inv(temp))\n      any(!isfinite, E) &&  throw(\"ME:SingularException: `A-λC` and `D+λB` have common eigenvalues\")\n      return E\n   end\n   n = na*nb\n   i1 = 1:n\n   R = view(Xw,i1,i1)\n   Y = reshape(E, n)\n   if !adjAC && !adjBD\n      if na == 1\n         # R12 =\n         # [ a11*b11 + c11*d11, a11*b21 + c11*d21]\n         # [ a11*b12 + c11*d12, a11*b22 + c11*d22]\n         # @inbounds R = [ A[1,1]*B[1,1]+C[1,1]*D[1,1]      A[1,1]*B[2,1]+C[1,1]*D[2,1];\n         #                 A[1,1]*B[1,2]+C[1,1]*D[1,2]  A[1,1]*B[2,2]+C[1,1]*D[2,2]]\n         @inbounds  R[1,1] = A[1,1]*B[1,1]+C[1,1]*D[1,1]\n         @inbounds  R[1,2] = A[1,1]*B[2,1]+C[1,1]*D[2,1]\n         @inbounds  R[2,1] = A[1,1]*B[1,2]+C[1,1]*D[1,2]\n         @inbounds  R[2,2] = A[1,1]*B[2,2]+C[1,1]*D[2,2]\n         # @inbounds  Y[1] = E[1,1]\n         # @inbounds  Y[2] = E[1,2]\n      else\n         if nb == 1\n            # R21 =\n            # [ a11*b11 + c11*d11, a12*b11 + c12*d11]\n            # [ a21*b11 + c21*d11, a22*b11 + c22*d11]\n            # @inbounds R = [ A[1,1]*B[1,1]+C[1,1]*D[1,1]      A[1,2]*B[1,1]+C[1,2]*D[1,1];\n            #                 A[2,1]*B[1,1]+C[2,1]*D[1,1]  A[2,2]*B[1,1]+C[2,2]*D[1,1] ]\n            @inbounds  R[1,1] = A[1,1]*B[1,1]+C[1,1]*D[1,1]\n            @inbounds  R[1,2] = A[1,2]*B[1,1]+C[1,2]*D[1,1]\n            @inbounds  R[2,1] = A[2,1]*B[1,1]+C[2,1]*D[1,1]\n            @inbounds  R[2,2] = A[2,2]*B[1,1]+C[2,2]*D[1,1]\n            # @inbounds  Y[1] = E[1,1]\n            # @inbounds  Y[2] = E[2,1]\n         else\n            # R =\n            # [ a11*b11 + c11*d11, a12*b11 + c12*d11, a11*b21 + c11*d21, a12*b21 + c12*d21]\n            # [ a21*b11 + c21*d11, a22*b11 + c22*d11, a21*b21 + c21*d21, a22*b21 + c22*d21]\n            # [ a11*b12 + c11*d12, a12*b12 + c12*d12, a11*b22 + c11*d22, a12*b22 + c12*d22]\n            # [ a21*b12 + c21*d12, a22*b12 + c22*d12, a21*b22 + c21*d22, a22*b22 + c22*d22]\n            # (iszero(C[2,1]) && iszero(D[2,1]) && iszero(C[1,2]) && iszero(D[1,2])) ?\n            # (@inbounds R = [ A[1,1]*B[1,1]+C[1,1]*D[1,1]      A[1,2]*B[1,1]      A[1,1]*B[2,1]      A[1,2]*B[2,1];\n            # A[2,1]*B[1,1]  A[2,2]*B[1,1]+C[2,2]*D[1,1]      A[2,1]*B[2,1]      A[2,2]*B[2,1];\n            # A[1,1]*B[1,2]      A[1,2]*B[1,2]  A[1,1]*B[2,2]+C[1,1]*D[2,2]      A[1,2]*B[2,2];\n            # A[2,1]*B[1,2]      A[2,2]*B[1,2]      A[2,1]*B[2,2]  A[2,2]*B[2,2]+C[2,2]*D[2,2]]) :\n            # (@inbounds R = [ A[1,1]*B[1,1]+C[1,1]*D[1,1]      A[1,2]*B[1,1]+C[1,2]*D[1,1]      A[1,1]*B[2,1]+C[1,1]*D[2,1]      A[1,2]*B[2,1]+C[1,2]*D[2,1];\n            # A[2,1]*B[1,1]+C[2,1]*D[1,1]  A[2,2]*B[1,1]+C[2,2]*D[1,1]      A[2,1]*B[2,1]+C[2,1]*D[2,1]      A[2,2]*B[2,1]+C[2,2]*D[2,1];\n            # A[1,1]*B[1,2]+C[1,1]*D[1,2]      A[1,2]*B[1,2]+C[1,2]*D[1,2]  A[1,1]*B[2,2]+C[1,1]*D[2,2]      A[1,2]*B[2,2]+C[1,2]*D[2,2];\n            # A[2,1]*B[1,2]+C[2,1]*D[1,2]      A[2,2]*B[1,2]+C[2,2]*D[1,2]      A[2,1]*B[2,2]+C[2,1]*D[2,2]  A[2,2]*B[2,2]+C[2,2]*D[2,2]])\n            @inbounds  R[1,1] = A[1,1]*B[1,1]+C[1,1]*D[1,1]\n            @inbounds  R[1,2] = A[1,2]*B[1,1]+C[1,2]*D[1,1]\n            @inbounds  R[1,3] = A[1,1]*B[2,1]+C[1,1]*D[2,1]\n            @inbounds  R[1,4] = A[1,2]*B[2,1]+C[1,2]*D[2,1]\n            @inbounds  R[2,1] = A[2,1]*B[1,1]+C[2,1]*D[1,1]\n            @inbounds  R[2,2] = A[2,2]*B[1,1]+C[2,2]*D[1,1]\n            @inbounds  R[2,3] = A[2,1]*B[2,1]+C[2,1]*D[2,1]\n            @inbounds  R[2,4] = A[2,2]*B[2,1]+C[2,2]*D[2,1]\n            @inbounds  R[3,1] = A[1,1]*B[1,2]+C[1,1]*D[1,2]\n            @inbounds  R[3,2] = A[1,2]*B[1,2]+C[1,2]*D[1,2]\n            @inbounds  R[3,3] = A[1,1]*B[2,2]+C[1,1]*D[2,2]\n            @inbounds  R[3,4] = A[1,2]*B[2,2]+C[1,2]*D[2,2]\n            @inbounds  R[4,1] = A[2,1]*B[1,2]+C[2,1]*D[1,2]\n            @inbounds  R[4,2] = A[2,2]*B[1,2]+C[2,2]*D[1,2]\n            @inbounds  R[4,3] = A[2,1]*B[2,2]+C[2,1]*D[2,2]\n            @inbounds  R[4,4] = A[2,2]*B[2,2]+C[2,2]*D[2,2]\n            # @inbounds  Y[1] = E[1,1]\n            # @inbounds  Y[2] = E[2,1]\n            # @inbounds  Y[3] = E[1,2]\n            # @inbounds  Y[4] = E[2,2]\n         end\n      end\n      #R = kron(transpose(B),A) + kron(transpose(D),C)\n   elseif adjAC && !adjBD\n      if na == 1\n         # R12 =\n         # [ a11*b11 + c11*d11, a11*b21 + c11*d21]\n         # [ a11*b12 + c11*d12, a11*b22 + c11*d22]\n         # @inbounds R = [ A[1,1]*B[1,1]+C[1,1]*D[1,1]      A[1,1]*B[2,1]+C[1,1]*D[2,1];\n         #                 A[1,1]*B[1,2]+C[1,1]*D[1,2]  A[1,1]*B[2,2]+C[1,1]*D[2,2]]\n         @inbounds  R[1,1] = A[1,1]*B[1,1]+C[1,1]*D[1,1]\n         @inbounds  R[1,2] = A[1,1]*B[2,1]+C[1,1]*D[2,1]\n         @inbounds  R[2,1] = A[1,1]*B[1,2]+C[1,1]*D[1,2]\n         @inbounds  R[2,2] = A[1,1]*B[2,2]+C[1,1]*D[2,2]\n         # @inbounds  Y[1] = E[1,1]\n         # @inbounds  Y[2] = E[1,2]\n      else\n         if nb == 1\n            # R21 =\n            # [ a11*b11 + c11*d11, a21*b11 + c21*d11]\n            # [ a12*b11 + c12*d11, a22*b11 + c22*d11]\n            # @inbounds R = [ A[1,1]*B[1,1]+C[1,1]*D[1,1]      A[2,1]*B[1,1]+C[2,1]*D[1,1];\n            #                 A[1,2]*B[1,1]+C[1,2]*D[1,1]  A[2,2]*B[1,1]+C[2,2]*D[1,1] ]\n            @inbounds  R[1,1] = A[1,1]*B[1,1]+C[1,1]*D[1,1]\n            @inbounds  R[1,2] = A[2,1]*B[1,1]+C[2,1]*D[1,1]\n            @inbounds  R[2,1] = A[1,2]*B[1,1]+C[1,2]*D[1,1]\n            @inbounds  R[2,2] = A[2,2]*B[1,1]+C[2,2]*D[1,1]\n            # @inbounds  Y[1] = E[1,1]\n            # @inbounds  Y[2] = E[2,1]\n         else\n            # R =\n            # [ a11*b11 + c11*d11, a21*b11 + c21*d11, a11*b21 + c11*d21, a21*b21 + c21*d21]\n            # [ a12*b11 + c12*d11, a22*b11 + c22*d11, a12*b21 + c12*d21, a22*b21 + c22*d21]\n            # [ a11*b12 + c11*d12, a21*b12 + c21*d12, a11*b22 + c11*d22, a21*b22 + c21*d22]\n            # [ a12*b12 + c12*d12, a22*b12 + c22*d12, a12*b22 + c12*d22, a22*b22 + c22*d22]\n            # (iszero(C[2,1]) && iszero(D[2,1]) && iszero(C[1,2]) && iszero(D[1,2])) ?\n            # (@inbounds R = [ A[1,1]*B[1,1]+C[1,1]*D[1,1]      A[2,1]*B[1,1]      A[1,1]*B[2,1]      A[2,1]*B[2,1];\n            # A[1,2]*B[1,1]  A[2,2]*B[1,1]+C[2,2]*D[1,1]      A[1,2]*B[2,1]      A[2,2]*B[2,1];\n            # A[1,1]*B[1,2]      A[2,1]*B[1,2]  A[1,1]*B[2,2]+C[1,1]*D[2,2]      A[2,1]*B[2,2];\n            # A[1,2]*B[1,2]      A[2,2]*B[1,2]      A[1,2]*B[2,2]  A[2,2]*B[2,2]+C[2,2]*D[2,2]]) :\n            # (@inbounds R = [ A[1,1]*B[1,1]+C[1,1]*D[1,1]      A[2,1]*B[1,1]+C[2,1]*D[1,1]      A[1,1]*B[2,1]+C[1,1]*D[2,1]      A[2,1]*B[2,1]+C[2,1]*D[2,1];\n            # A[1,2]*B[1,1]+C[1,2]*D[1,1]  A[2,2]*B[1,1]+C[2,2]*D[1,1]      A[1,2]*B[2,1]+C[1,2]*D[2,1]      A[2,2]*B[2,1]+C[2,2]*D[2,1];\n            # A[1,1]*B[1,2]+C[1,1]*D[1,2]      A[2,1]*B[1,2]+C[2,1]*D[1,2]  A[1,1]*B[2,2]+C[1,1]*D[2,2]      A[2,1]*B[2,2]+C[2,1]*D[2,2];\n            # A[1,2]*B[1,2]+C[1,2]*D[1,2]      A[2,2]*B[1,2]+C[2,2]*D[1,2]      A[1,2]*B[2,2]+C[1,2]*D[2,2]  A[2,2]*B[2,2]+C[2,2]*D[2,2]])\n            @inbounds  R[1,1] = A[1,1]*B[1,1]+C[1,1]*D[1,1]\n            @inbounds  R[1,2] = A[2,1]*B[1,1]+C[2,1]*D[1,1]\n            @inbounds  R[1,3] = A[1,1]*B[2,1]+C[1,1]*D[2,1]\n            @inbounds  R[1,4] = A[2,1]*B[2,1]+C[2,1]*D[2,1]\n            @inbounds  R[2,1] = A[1,2]*B[1,1]+C[1,2]*D[1,1]\n            @inbounds  R[2,2] = A[2,2]*B[1,1]+C[2,2]*D[1,1]\n            @inbounds  R[2,3] = A[1,2]*B[2,1]+C[1,2]*D[2,1]\n            @inbounds  R[2,4] = A[2,2]*B[2,1]+C[2,2]*D[2,1]\n            @inbounds  R[3,1] = A[1,1]*B[1,2]+C[1,1]*D[1,2]\n            @inbounds  R[3,2] = A[2,1]*B[1,2]+C[2,1]*D[1,2]\n            @inbounds  R[3,3] = A[1,1]*B[2,2]+C[1,1]*D[2,2]\n            @inbounds  R[3,4] = A[2,1]*B[2,2]+C[2,1]*D[2,2]\n            @inbounds  R[4,1] = A[1,2]*B[1,2]+C[1,2]*D[1,2]\n            @inbounds  R[4,2] = A[2,2]*B[1,2]+C[2,2]*D[1,2]\n            @inbounds  R[4,3] = A[1,2]*B[2,2]+C[1,2]*D[2,2]\n            @inbounds  R[4,4] = A[2,2]*B[2,2]+C[2,2]*D[2,2]\n            # @inbounds  Y[1] = E[1,1]\n            # @inbounds  Y[2] = E[2,1]\n            # @inbounds  Y[3] = E[1,2]\n            # @inbounds  Y[4] = E[2,2]\n         end\n      end\n      #R = kron(transpose(B),transpose(A)) + kron(transpose(D),transpose(C))\n   elseif !adjAC && adjBD\n      if na == 1\n         # R12 =\n         # [ a11*b11 + c11*d11, a11*b12 + c11*d12]\n         # [ a11*b21 + c11*d21, a11*b22 + c11*d22]\n         # @inbounds R = [ A[1,1]*B[1,1]+C[1,1]*D[1,1]      A[1,1]*B[1,2]+C[1,1]*D[1,2];\n         #                 A[1,1]*B[2,1]+C[1,1]*D[2,1]  A[1,1]*B[2,2]+C[1,1]*D[2,2]]\n         @inbounds  R[1,1] = A[1,1]*B[1,1]+C[1,1]*D[1,1]\n         @inbounds  R[1,2] = A[1,1]*B[1,2]+C[1,1]*D[1,2]\n         @inbounds  R[2,1] = A[1,1]*B[2,1]+C[1,1]*D[2,1]\n         @inbounds  R[2,2] = A[1,1]*B[2,2]+C[1,1]*D[2,2]\n         # @inbounds  Y[1] = E[1,1]\n         # @inbounds  Y[2] = E[1,2]\n      else\n         if nb == 1\n            # R21 =\n            # [ a11*b11 + c11*d11, a12*b11 + c12*d11]\n            # [ a21*b11 + c21*d11, a22*b11 + c22*d11]\n            # @inbounds R = [ A[1,1]*B[1,1]+C[1,1]*D[1,1]      A[1,2]*B[1,1]+C[1,2]*D[1,1];\n            #                 A[2,1]*B[1,1]+C[2,1]*D[1,1]  A[2,2]*B[1,1]+C[2,2]*D[1,1] ]\n            @inbounds  R[1,1] = A[1,1]*B[1,1]+C[1,1]*D[1,1]\n            @inbounds  R[1,2] = A[1,2]*B[1,1]+C[1,2]*D[1,1]\n            @inbounds  R[2,1] = A[2,1]*B[1,1]+C[2,1]*D[1,1]\n            @inbounds  R[2,2] = A[2,2]*B[1,1]+C[2,2]*D[1,1]\n            # @inbounds  Y[1] = E[1,1]\n            # @inbounds  Y[2] = E[2,1]\n         else\n            # R =\n            # [ a11*b11 + c11*d11, a12*b11 + c12*d11, a11*b12 + c11*d12, a12*b12 + c12*d12]\n            # [ a21*b11 + c21*d11, a22*b11 + c22*d11, a21*b12 + c21*d12, a22*b12 + c22*d12]\n            # [ a11*b21 + c11*d21, a12*b21 + c12*d21, a11*b22 + c11*d22, a12*b22 + c12*d22]\n            # [ a21*b21 + c21*d21, a22*b21 + c22*d21, a21*b22 + c21*d22, a22*b22 + c22*d22]\n            # (iszero(C[2,1]) && iszero(D[2,1]) && iszero(C[1,2]) && iszero(D[1,2])) ?\n            # (@inbounds R = [ A[1,1]*B[1,1]+C[1,1]*D[1,1]      A[1,2]*B[1,1]      A[1,1]*B[1,2]      A[1,2]*B[1,2];\n            # A[2,1]*B[1,1]  A[2,2]*B[1,1]+C[2,2]*D[1,1]      A[2,1]*B[1,2]      A[2,2]*B[1,2];\n            # A[1,1]*B[2,1]      A[1,2]*B[2,1]  A[1,1]*B[2,2]+C[1,1]*D[2,2]      A[1,2]*B[2,2]+C[1,2]*D[2,2];\n            # A[2,1]*B[2,1]      A[2,2]*B[2,1]      A[2,1]*B[2,2]  A[2,2]*B[2,2]+C[2,2]*D[2,2]]) :\n            # (@inbounds R = [ A[1,1]*B[1,1]+C[1,1]*D[1,1]      A[1,2]*B[1,1]+C[1,2]*D[1,1]      A[1,1]*B[1,2]+C[1,1]*D[1,2]      A[1,2]*B[1,2]+C[1,2]*D[1,2];\n            # A[2,1]*B[1,1]+C[2,1]*D[1,1]  A[2,2]*B[1,1]+C[2,2]*D[1,1]      A[2,1]*B[1,2]+C[2,1]*D[1,2]      A[2,2]*B[1,2]+C[2,2]*D[1,2];\n            # A[1,1]*B[2,1]+C[1,1]*D[2,1]      A[1,2]*B[2,1]+C[1,2]*D[2,1]  A[1,1]*B[2,2]+C[1,1]*D[2,2]      A[1,2]*B[2,2]+C[1,2]*D[2,2];\n            # A[2,1]*B[2,1]+C[2,1]*D[2,1]      A[2,2]*B[2,1]+C[2,2]*D[2,1]      A[2,1]*B[2,2]+C[2,1]*D[2,2]  A[2,2]*B[2,2]+C[2,2]*D[2,2]])\n            @inbounds  R[1,1] = A[1,1]*B[1,1]+C[1,1]*D[1,1]\n            @inbounds  R[1,2] = A[1,2]*B[1,1]+C[1,2]*D[1,1]\n            @inbounds  R[1,3] = A[1,1]*B[1,2]+C[1,1]*D[1,2]\n            @inbounds  R[1,4] = A[1,2]*B[1,2]+C[1,2]*D[1,2]\n            @inbounds  R[2,1] = A[2,1]*B[1,1]+C[2,1]*D[1,1]\n            @inbounds  R[2,2] = A[2,2]*B[1,1]+C[2,2]*D[1,1]\n            @inbounds  R[2,3] = A[2,1]*B[1,2]+C[2,1]*D[1,2]\n            @inbounds  R[2,4] = A[2,2]*B[1,2]+C[2,2]*D[1,2]\n            @inbounds  R[3,1] = A[1,1]*B[2,1]+C[1,1]*D[2,1]\n            @inbounds  R[3,2] = A[1,2]*B[2,1]+C[1,2]*D[2,1]\n            @inbounds  R[3,3] = A[1,1]*B[2,2]+C[1,1]*D[2,2]\n            @inbounds  R[3,4] = A[1,2]*B[2,2]+C[1,2]*D[2,2]\n            @inbounds  R[4,1] = A[2,1]*B[2,1]+C[2,1]*D[2,1]\n            @inbounds  R[4,2] = A[2,2]*B[2,1]+C[2,2]*D[2,1]\n            @inbounds  R[4,3] = A[2,1]*B[2,2]+C[2,1]*D[2,2]\n            @inbounds  R[4,4] = A[2,2]*B[2,2]+C[2,2]*D[2,2]\n            # @inbounds  Y[1] = E[1,1]\n            # @inbounds  Y[2] = E[2,1]\n            # @inbounds  Y[3] = E[1,2]\n            # @inbounds  Y[4] = E[2,2]\n         end\n      end\n      #R = kron(B,A) + kron(D,C)\n   else\n      if na == 1\n         # R12 =\n         # [ a11*b11 + c11*d11, a11*b12 + c11*d12]\n         # [ a11*b21 + c11*d21, a11*b22 + c11*d22]\n         # @inbounds R = [ A[1,1]*B[1,1]+C[1,1]*D[1,1]      A[1,1]*B[1,2]+C[1,1]*D[1,2];\n         #                 A[1,1]*B[2,1]+C[1,1]*D[2,1]  A[1,1]*B[2,2]+C[1,1]*D[2,2]]\n         @inbounds  R[1,1] = A[1,1]*B[1,1]+C[1,1]*D[1,1]\n         @inbounds  R[1,2] = A[1,1]*B[1,2]+C[1,1]*D[1,2]\n         @inbounds  R[2,1] = A[1,1]*B[2,1]+C[1,1]*D[2,1]\n         @inbounds  R[2,2] = A[1,1]*B[2,2]+C[1,1]*D[2,2]\n         # @inbounds  Y[1] = E[1,1]\n         # @inbounds  Y[2] = E[1,2]\n      else\n         if nb == 1\n            # R21 =\n            # [ a11*b11 + c11*d11, a21*b11 + c21*d11]\n            # [ a12*b11 + c12*d11, a22*b11 + c22*d11]\n            # @inbounds R = [ A[1,1]*B[1,1]+C[1,1]*D[1,1]      A[2,1]*B[1,1]+C[2,1]*D[1,1];\n            #                 A[1,2]*B[1,1]+C[1,2]*D[1,1]  A[2,2]*B[1,1]+C[2,2]*D[1,1] ]\n            @inbounds  R[1,1] = A[1,1]*B[1,1]+C[1,1]*D[1,1]\n            @inbounds  R[1,2] = A[2,1]*B[1,1]+C[2,1]*D[1,1]\n            @inbounds  R[2,1] = A[1,2]*B[1,1]+C[1,2]*D[1,1]\n            @inbounds  R[2,2] = A[2,2]*B[1,1]+C[2,2]*D[1,1]\n            # @inbounds  Y[1] = E[1,1]\n            # @inbounds  Y[2] = E[2,1]\n         else\n            # R =\n            # [ a11*b11 + c11*d11, a21*b11 + c21*d11, a11*b12 + c11*d12, a21*b12 + c21*d12]\n            # [ a12*b11 + c12*d11, a22*b11 + c22*d11, a12*b12 + c12*d12, a22*b12 + c22*d12]\n            # [ a11*b21 + c11*d21, a21*b21 + c21*d21, a11*b22 + c11*d22, a21*b22 + c21*d22]\n            # [ a12*b21 + c12*d21, a22*b21 + c22*d21, a12*b22 + c12*d22, a22*b22 + c22*d22]\n            # (iszero(C[2,1]) && iszero(D[2,1]) && iszero(C[1,2]) && iszero(D[1,2])) ?\n            # (@inbounds R = [ A[1,1]*B[1,1]+C[1,1]*D[1,1]      A[2,1]*B[1,1]      A[1,1]*B[1,2]      A[2,1]*B[1,2];\n            # A[1,2]*B[1,1]  A[2,2]*B[1,1]+C[2,2]*D[1,1]      A[1,2]*B[1,2]      A[2,2]*B[1,2];\n            # A[1,1]*B[2,1]      A[2,1]*B[2,1]  A[1,1]*B[2,2]+C[1,1]*D[2,2]      A[2,1]*B[2,2];\n            # A[1,2]*B[2,1]      A[2,2]*B[2,1]      A[1,2]*B[2,2]  A[2,2]*B[2,2]+C[2,2]*D[2,2]]) :\n            # (@inbounds R = [ A[1,1]*B[1,1]+C[1,1]*D[1,1]      A[2,1]*B[1,1]+C[2,1]*D[1,1]      A[1,1]*B[1,2]+C[1,1]*D[1,2]      A[2,1]*B[1,2]+C[2,1]*D[1,2];\n            # A[1,2]*B[1,1]+C[1,2]*D[1,1]  A[2,2]*B[1,1]+C[2,2]*D[1,1]      A[1,2]*B[1,2]+C[1,2]*D[1,2]      A[2,2]*B[1,2]+C[2,2]*D[1,2];\n            # A[1,1]*B[2,1]+C[1,1]*D[2,1]      A[2,1]*B[2,1]+C[2,1]*D[2,1]  A[1,1]*B[2,2]+C[1,1]*D[2,2]      A[2,1]*B[2,2]+C[2,1]*D[2,2];\n            # A[1,2]*B[2,1]+C[1,2]*D[2,1]      A[2,2]*B[2,1]+C[2,2]*D[2,1]      A[1,2]*B[2,2]+C[1,2]*D[2,2]  A[2,2]*B[2,2]+C[2,2]*D[2,2]])\n            @inbounds  R[1,1] = A[1,1]*B[1,1]+C[1,1]*D[1,1]\n            @inbounds  R[1,2] = A[2,1]*B[1,1]+C[2,1]*D[1,1]\n            @inbounds  R[1,3] = A[1,1]*B[1,2]+C[1,1]*D[1,2]\n            @inbounds  R[1,4] = A[2,1]*B[1,2]+C[2,1]*D[1,2]\n            @inbounds  R[2,1] = A[1,2]*B[1,1]+C[1,2]*D[1,1]\n            @inbounds  R[2,2] = A[2,2]*B[1,1]+C[2,2]*D[1,1]\n            @inbounds  R[2,3] = A[1,2]*B[1,2]+C[1,2]*D[1,2]\n            @inbounds  R[2,4] = A[2,2]*B[1,2]+C[2,2]*D[1,2]\n            @inbounds  R[3,1] = A[1,1]*B[2,1]+C[1,1]*D[2,1]\n            @inbounds  R[3,2] = A[2,1]*B[2,1]+C[2,1]*D[2,1]\n            @inbounds  R[3,3] = A[1,1]*B[2,2]+C[1,1]*D[2,2]\n            @inbounds  R[3,4] = A[2,1]*B[2,2]+C[2,1]*D[2,2]\n            @inbounds  R[4,1] = A[1,2]*B[2,1]+C[1,2]*D[2,1]\n            @inbounds  R[4,2] = A[2,2]*B[2,1]+C[2,2]*D[2,1]\n            @inbounds  R[4,3] = A[1,2]*B[2,2]+C[1,2]*D[2,2]\n            @inbounds  R[4,4] = A[2,2]*B[2,2]+C[2,2]*D[2,2]\n            # @inbounds  Y[1] = E[1,1]\n            # @inbounds  Y[2] = E[2,1]\n            # @inbounds  Y[3] = E[1,2]\n            # @inbounds  Y[4] = E[2,2]\n         end\n      end\n      #R = kron(B,transpose(A)) + kron(D,transpose(C))\n   end\n   luslv!(R,Y) && throw(\"ME:SingularException: A has eigenvalue(s) α and B has eingenvalu(s) β such that αβ = -1\")\n   # E[:,:] = Y\n   return E\nend\n\nfunction gsylvs!(A::AbstractMatrix{T1}, B::AbstractMatrix{T1}, C::AbstractMatrix{T1}, D::AbstractMatrix{T1}, E::AbstractMatrix{T1}, \n                 WB::AbstractVector{T1} = similar(A,size(A,1)), WD::AbstractVector{T1} = similar(A,size(A,1)); \n                 adjAC::Bool = false, adjBD::Bool = false, CASchur::Bool = false, DBSchur::Bool = false) where T1<:BlasComplex\n   \"\"\"\n   An extension proposed in [1] of the Bartels-Stewart Schur form based approach [2] is employed.\n\n   References:\n   [1] K.-W. E. Chu. The solution of the matrix equation AXB – CXD = E and\n       (YA – DZ, YC– BZ) = (E, F). Lin. Alg. Appl., 93:93-105, 1987.\n   [2] R. H. Bartels and G. W. Stewart. Algorithm 432: Solution of the matrix equation AX+XB=C.\n       Comm. ACM, 15:820–826, 1972.\n   \"\"\"\n   m, n = size(E);\n   [m; n; m; n] == LinearAlgebra.checksquare(A,B,C,D) ||\n      throw(DimensionMismatch(\"A, B, C, D and E have incompatible dimensions\"))\n   m == length(WB) || throw(DimensionMismatch(\"WB must be an $m - dimensional vector\"))\n   m == length(WD) || throw(DimensionMismatch(\"WD must be an $m - dimensional vector\"))\n\n   WB = zeros(T1,m)\n   WD = zeros(T1,m)\n   ZERO = zero(T1)\n   if !adjAC && !adjBD\n      # \"\"\"\n      # The (K,L)th element of X is determined starting from\n      # bottom-left corner column by column by\n\n      #       A(K,K)*X(K,L)*B(L,L) +C(K,K)*X(K,L)*D(L,L) = E(K,L) - R(K,L)\n\n      # where\n      #                        M\n      #            R(K,L) = { SUM [A(K,J)*X(J,L)] } * B(L,L) +\n      #                      J=K+1\n      #                        M             L-1\n      #                       SUM { A(K,J) * SUM [X(J,I)*B(I,L)] } +\n      #                       J=K            I=1\n\n      #                       M\n      #                    { SUM [C(K,J)*X(J,L)] } * D(L,L) +\n      #                     J=K+1\n      #                       M             L-1\n      #                      SUM { C(K,J) * SUM [X(J,I)*D(I,L)] } +\n      #                      J=K            I=1\n      # \"\"\"\n      for l = 1:n\n          il1 = 1:l-1\n          for k = m:-1:1\n              y = E[k,l]\n              if k < m\n                 ta = ZERO\n                 tc = ZERO\n                 for ir = k+1:m\n                     ta += A[k,ir]*E[ir,l]\n                     tc += C[k,ir]*E[ir,l]\n                 end\n                 y -= (ta*B[l,l]+tc*D[l,l])\n              end\n              if l > 1\n                 ta = ZERO\n                 tc = ZERO\n                 for ir = il1\n                     ta += E[k,ir]*B[ir,l]\n                     tc += E[k,ir]*D[ir,l]\n                 end\n                 WB[k] = ta\n                 WD[k] = tc\n                 for ic = k:m\n                     y -= (A[k,ic]*WB[ic]+C[k,ic]*WD[ic])\n                 end\n              end\n              E[k,l] = y/(B[l,l]*A[k,k]+D[l,l]*C[k,k])\n              isfinite(E[k,l]) || throw(\"ME:SingularException: A-λC and D+λB have common or close eigenvalues\")\n          end\n      end\n   elseif !adjAC && adjBD\n         # \"\"\"\n         #  The (K,L)th element of X is determined starting from\n         #  bottom-right corner column by column by\n\n         #       A(K,K)*X(K,L)*B(L,L)' + C(K,K)*X(K,L)*D(L,L)' = E(K,L) - R(K,L)\n\n         #  where\n         #                        M\n         #            R(K,L) = { SUM [A(K,J)*X(J,L)] } * B(L,L)' +\n         #                      J=K+1\n         #                        M              N\n         #                       SUM { A(K,J) * SUM [X(J,I)*B(L,I)'] } +\n         #                       J=K           I=L+1\n\n         #                       M\n         #                    { SUM [C(K,J)*X(J,L)] } * D(L,L)' +\n         #                     J=K+1\n         #                       M              N\n         #                      SUM { C(K,J) * SUM [X(J,I)*D(L,I)'] }.\n         #                      J=K           I=L+1\n         # \"\"\"\n         for l = n:-1:1\n             il1 = l+1:n\n             for k = m:-1:1\n                 y = E[k,l]\n                 if k < m\n                    ta = ZERO\n                    tc = ZERO\n                    for ir = k+1:m\n                        ta += A[k,ir]*E[ir,l]\n                        tc += C[k,ir]*E[ir,l]\n                    end\n                    y -= (ta*B[l,l]'+tc*D[l,l]')\n                 end\n                 if l < n\n                    ta = ZERO\n                    tc = ZERO\n                    for ir = il1\n                        ta += E[k,ir]*B[l,ir]'\n                        tc += E[k,ir]*D[l,ir]'\n                    end\n                    WB[k] = ta\n                    WD[k] = tc\n                    for ic = k:m\n                        y -= (A[k,ic]*WB[ic]+C[k,ic]*WD[ic])\n                    end\n                 end\n                 E[k,l] = y/(B[l,l]'*A[k,k]+D[l,l]'*C[k,k])\n                 isfinite(E[k,l]) || throw(\"ME:SingularException: A-λC and D'+λB' have common or close eigenvalues\")\n             end\n         end\n   elseif adjAC && !adjBD\n      # \"\"\"\n      # The (K,L)th element of X is determined starting from the\n      # upper-left corner column by column by\n\n      # A(K,K)'*X(K,L)*B(L,L) + C(K,K)'*X(K,L)*D(L,L) = E(K,L) - R(K,L),\n\n      # where\n      #                       K-1\n      #            R(K,L) = { SUM [A(J,K)'*X(J,L)] } * B(L,L) +\n      #                       J=1\n      #                        K              L-1\n      #                       SUM A(J,K)' * { SUM [X(J,I)*B(I,L)] } +\n      #                       J=1             I=1\n\n      #                       K-1\n      #                     { SUM [C(J,K)'*X(J,L)] } * D(L,L) +\n      #                       J=1\n      #                        K              L-1\n      #                       SUM C(J,K)' * { SUM [X(J,I)*D(I,L)] }.\n      #                       J=1             I=1\n      # \"\"\"\n      for l = 1:n\n          il1 = 1:l-1\n          for k = 1:m\n              y = E[k,l]\n              if k > 1\n                 ta = ZERO\n                 tc = ZERO\n                 for ir = 1:k-1\n                     ta += A[ir,k]'*E[ir,l]\n                     tc += C[ir,k]'*E[ir,l]\n                 end\n                 y -= (ta*B[l,l]+tc*D[l,l])\n              end\n              if l > 1\n                 ta = ZERO\n                 tc = ZERO\n                 for ir = il1\n                     ta += E[k,ir]*B[ir,l]\n                     tc += E[k,ir]*D[ir,l]\n                 end\n                 WB[k] = ta\n                 WD[k] = tc\n                 for ic = 1:m\n                     y -= (A[ic,k]'*WB[ic]+C[ic,k]'*WD[ic])\n                 end\n              end\n              E[k,l] = y/(B[l,l]*A[k,k]'+D[l,l]*C[k,k]')\n              isfinite(E[k,l]) || throw(\"ME:SingularException: A'-λC' and D+λB have common or close eigenvalues\")\n          end\n      end\n   elseif adjAC && adjBD\n      # \"\"\"\n      # The (K,L)th element of X is determined starting from\n      # upper-rght corner column by column by\n\n      #       A(K,K)'*X(K,L)*B(L,L)' + C(K,K)'*X(K,L)*D(L,L)' = E(K,L) - R(K,L)\n\n      # where\n      #                       K-1\n      #            R(K,L) = { SUM [A(J,K)'*X(J,L)] } * B(L,L)' +\n      #                       J=1\n      #                        K               N\n      #                       SUM A(J,K)' * { SUM [X(J,I)*B(L,I)'] }+\n      #                       J=1            I=L+1\n\n      #                       K-1\n      #                     { SUM [C(J,K)'*X(J,L)] } * D(L,L)' +\n      #                       J=1\n      #                        K               N\n      #                       SUM C(J,K)' * { SUM [X(J,I)*D(L,I)'] }.\n      #                       J=1            I=L+1\n      # \"\"\"\n      for l = n:-1:1\n          il1 = l+1:n\n          for k = 1:m\n              y = E[k,l]\n              if k > 1\n                 ta = ZERO\n                 tc = ZERO\n                 for ir = 1:k-1\n                     ta += A[ir,k]'*E[ir,l]\n                     tc += C[ir,k]'*E[ir,l]\n                 end\n                 y -= (ta*B[l,l]'+tc*D[l,l]')\n               end\n               if l < n\n                 ic = 1:m\n                 ta = ZERO\n                 tc = ZERO\n                 for ir = il1\n                     ta += E[k,ir]*B[l,ir]'\n                     tc += E[k,ir]*D[l,ir]'\n                 end\n                 WB[k] = ta\n                 WD[k] = tc\n                 for ic = 1:m\n                     y -= (A[ic,k]'*WB[ic]+C[ic,k]'*WD[ic])\n                 end\n               end\n              E[k,l] = y/(B[l,l]'*A[k,k]'+D[l,l]'*C[k,k]')\n              isfinite(E[k,l]) || throw(\"ME:SingularException: A'-λC' and D'+λB' have common or close eigenvalues\")\n          end\n      end\n   end\n   return E\nend\n\"\"\"\n    (X,Y) = sylvsyss!(A,B,C,D,E,F)\n\nSolve the Sylvester system of matrix equations\n\n                AX + YB = C\n                DX + YE = F,\n\nwhere `(A,D)`, `(B,E)` are pairs of square matrices of the same size in generalized Schur forms.\nThe pencils `A-λD` and `-B+λE` must be regular and must not have common eigenvalues. The computed\nsolution `(X,Y)` is contained in `(C,F)`.\n\n_Note:_ This is an enhanced interface to the `LAPACK.tgsyl!` function to also cover the case when\n`A`, `B`, `D` and `E` are real matrices and `C` and `F` are complex matrices.\n\"\"\"\nfunction sylvsyss!(A::T1, B::T1, C::T1, D::T1, E::T1, F::T1) where {T<:BlasFloat,T1<:Matrix{T}}\n   \"\"\"\n   This is a wrapper to the LAPACK.tgsyl! function with `trans = 'N'`.\n   \"\"\"\n   C, F, scale =  tgsyl!('N',A,B,C,D,E,F)\n   return rmul!(C,inv(scale)), rmul!(F,inv(-scale))\nend\n\"\"\"\n    (X,Y) = dsylvsyss!(A,B,C,D,E,F)\n\nSolve the dual Sylvester system of matrix equations\n\n    A'X + D'Y = C\n    XB' + YE' = F,\n\nwhere `(A,D)`, `(B,E)` are pairs of square matrices of the same size in generalized Schur forms.\nThe pencils `A-λD` and `-B+λE` must be regular and must not have common eigenvalues. The computed\nsolution `(X,Y)` is contained in `(C,F)`.\n\"\"\"\nfunction dsylvsyss!(A::T1, B::T1, C::T1, D::T1, E::T1, F::T1) where {T<:BlasFloat,T1<:Matrix{T}}\n   \"\"\"\n   This is an interface to the LAPACK.tgsyl! function with `trans = 'T' or `trans = 'C'`.\n   \"\"\"\n   # MF = -F\n   # E, F, scale =  tgsyl!(T <: Complex ? 'C' : 'T', A, B, C, D, E, MF)\n   # F = MF\n   # return rmul!(C[:,:],inv(scale)), rmul!(F[:,:],inv(scale))\n   F = -F\n   C, F, scale =  tgsyl!(T <: Complex ? 'C' : 'T', A, B, C, D, E, F)\n   return rmul!(C[:,:],inv(scale)), rmul!(F[:,:],inv(scale))\nend\n", "meta": {"hexsha": "c8a001d5d8e6f4d33ae06010f57487abe04bc4b5", "size": 79517, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sylvester.jl", "max_stars_repo_name": "andreasvarga/MatrixEquations.jl", "max_stars_repo_head_hexsha": "116c9c76136dfe4b3d45d0c8344c9a47957f09ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2019-12-02T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T16:21:29.000Z", "max_issues_repo_path": "src/sylvester.jl", "max_issues_repo_name": "andreasvarga/MatrixEquations.jl", "max_issues_repo_head_hexsha": "116c9c76136dfe4b3d45d0c8344c9a47957f09ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2019-08-07T12:52:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:48:26.000Z", "max_forks_repo_path": "src/sylvester.jl", "max_forks_repo_name": "andreasvarga/MatrixEquations.jl", "max_forks_repo_head_hexsha": "116c9c76136dfe4b3d45d0c8344c9a47957f09ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-10-06T01:38:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T12:36:04.000Z", "avg_line_length": 38.1926032661, "max_line_length": 209, "alphanum_fraction": 0.407623527, "num_tokens": 32282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7643544926422357}}
{"text": "module KuboOscillatorProblem\n\n    using GeometricIntegrators.Equations\n\n    export kubo_oscillator_sde_1, kubo_oscillator_psde_1, kubo_oscillator_spsde_1\n    export kubo_oscillator_sde_2, kubo_oscillator_psde_2, kubo_oscillator_spsde_2\n    export kubo_oscillator_sde_3, kubo_oscillator_psde_3, kubo_oscillator_spsde_3\n\n    q_init_A=[0.5, 0.0]\n    q_init_B=[0.5 0.0 -0.5; 0.0 0.5 0.0]\n\n    const noise_intensity = 0.1\n\n    const Δt = 0.01\n    const nt = 10\n\n\n    function kubo_oscillator_sde_v(t, q, v_out)\n        v_out[1]=  q[2]\n        v_out[2]= -q[1]\n    end\n\n\n    function kubo_oscillator_sde_B(t, q, B_out::AbstractVector, ν=noise_intensity)\n        B_out[1] = +ν*q[2]\n        B_out[2] = -ν*q[1]\n    end\n\n    function kubo_oscillator_sde_B(t, q, B_out::AbstractMatrix, col=1, ν=noise_intensity)\n        B_out[1,col] = +ν*q[2]\n        B_out[2,col] = -ν*q[1]\n    end\n\n\n    function kubo_oscillator_sde_1(q₀=q_init_A)\n        # q_init_A - single deterministic initial condition\n        # Generating 3 sample paths\n        # 1-dimensional noise\n        SDE(1, 3, kubo_oscillator_sde_v, kubo_oscillator_sde_B, q₀)\n    end\n\n    function kubo_oscillator_sde_2(q₀=q_init_B)\n        # q_init_B - interpreted as three random initial conditions\n        # The 3 columns correspond to 3 sample paths\n        # 1-dimensional noise\n        SDE(1, 1, kubo_oscillator_sde_v, kubo_oscillator_sde_B, q₀)\n    end\n\n    function kubo_oscillator_sde_3(q₀=q_init_A)\n        # q_init_A - interpreted as one random initial conditions with one sample path\n        # 1-dimensional noise\n        SDE(1, 1, kubo_oscillator_sde_v, kubo_oscillator_sde_B, q₀)\n    end\n\n\n    # PSDE\n\n    q_init_C=[0.5]\n    p_init_C=[0.0]\n\n    q_init_D=[0.5 0.0 -0.5]\n    p_init_D=[0.0 0.5 0.0]\n\n\n    function kubo_oscillator_psde_v(t, q, p, v_out)\n        v_out[1] =  p[1]\n    end\n\n    function kubo_oscillator_psde_f(t, q, p, f_out)\n        f_out[1] = -q[1]\n    end\n\n    function kubo_oscillator_psde_B(t, q, p, B_out, ν=noise_intensity)\n        B_out[1,1] = +ν*p[1]\n    end\n\n    function kubo_oscillator_psde_G(t, q, p, G_out, ν=noise_intensity)\n        G_out[1,1] = -ν*q[1]\n    end\n\n\n    function kubo_oscillator_psde_1(q₀=q_init_C, p₀=p_init_C)\n        # q_init_C - single deterministic initial condition\n        # Generating 3 sample paths\n        # 1-dimensional noise\n        PSDE(1, 3, kubo_oscillator_psde_v, kubo_oscillator_psde_f, kubo_oscillator_psde_B, kubo_oscillator_psde_G, q₀, p₀)\n    end\n\n    function kubo_oscillator_psde_2(q₀=q_init_D, p₀=p_init_D)\n        # q_init_D - interpreted as a single random initial condition\n        # The 3 columns correspond to 3 sample paths\n        # 1-dimensional noise\n        PSDE(1, 1, kubo_oscillator_psde_v, kubo_oscillator_psde_f, kubo_oscillator_psde_B, kubo_oscillator_psde_G, q₀, p₀)\n    end\n\n    function kubo_oscillator_psde_3(q₀=q_init_C, p₀=p_init_C)\n        # q_init_C - interpreted as a single random initial condition with one sample path\n        # 1-dimensional noise\n        PSDE(1, 1, kubo_oscillator_psde_v, kubo_oscillator_psde_f, kubo_oscillator_psde_B, kubo_oscillator_psde_G, q₀, p₀)\n    end\n\n\n    # SPSDE\n\n    function kubo_oscillator_spsde_v(t, q, p, v_out)\n        v_out[1] =  p[1]\n    end\n\n    function kubo_oscillator_spsde_f1(t, q, p, f_out)\n        f_out[1] = -q[1]\n    end\n\n    function kubo_oscillator_spsde_f2(t, q, p, f_out)\n        f_out[1] = 0\n    end\n\n    function kubo_oscillator_spsde_B(t, q, p, B_out, ν=noise_intensity)\n        B_out[1,1] = +ν*p[1]\n    end\n\n    function kubo_oscillator_spsde_G1(t, q, p, G_out, ν=noise_intensity)\n        G_out[1,1] = -ν*q[1]\n    end\n\n    function kubo_oscillator_spsde_G2(t, q, p, G_out, ν=noise_intensity)\n        G_out[1,1] = 0\n    end\n\n\n    function kubo_oscillator_spsde_1(q₀=q_init_C, p₀=p_init_C)\n        # q_init_C - single deterministic initial condition\n        # Generating 3 sample paths\n        # 1-dimensional noise\n        SPSDE(1, 3, kubo_oscillator_spsde_v, kubo_oscillator_spsde_f1, kubo_oscillator_spsde_f2, kubo_oscillator_spsde_B, kubo_oscillator_spsde_G1, kubo_oscillator_spsde_G2, q₀, p₀)\n    end\n\n    function kubo_oscillator_spsde_2(q₀=q_init_D, p₀=p_init_D)\n        # q_init_D - interpreted as a single random initial condition\n        # The 3 columns correspond to 3 sample paths\n        # 1-dimensional noise\n        SPSDE(1, 1, kubo_oscillator_spsde_v, kubo_oscillator_spsde_f1, kubo_oscillator_spsde_f2, kubo_oscillator_spsde_B, kubo_oscillator_spsde_G1, kubo_oscillator_spsde_G2, q₀, p₀)\n    end\n\n    function kubo_oscillator_spsde_3(q₀=q_init_C, p₀=p_init_C)\n        # q_init_C - interpreted as a single random initial condition with one sample path\n        # 1-dimensional noise\n        SPSDE(1, 1, kubo_oscillator_spsde_v, kubo_oscillator_spsde_f1, kubo_oscillator_spsde_f2, kubo_oscillator_spsde_B, kubo_oscillator_spsde_G1, kubo_oscillator_spsde_G2, q₀, p₀)\n    end\n\nend\n", "meta": {"hexsha": "b0c8c19066f45d0e0a1685b54c2dd474f01a9e93", "size": 4889, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/kubo_oscillator.jl", "max_stars_repo_name": "TomaszTyranowski/GeometricIntegrators.jl", "max_stars_repo_head_hexsha": "8f514c18548754186d14ae2ef49ae956561ca529", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-04T11:52:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T11:52:47.000Z", "max_issues_repo_path": "src/problems/kubo_oscillator.jl", "max_issues_repo_name": "TomaszTyranowski/GeometricIntegrators.jl", "max_issues_repo_head_hexsha": "8f514c18548754186d14ae2ef49ae956561ca529", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/kubo_oscillator.jl", "max_forks_repo_name": "TomaszTyranowski/GeometricIntegrators.jl", "max_forks_repo_head_hexsha": "8f514c18548754186d14ae2ef49ae956561ca529", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3774834437, "max_line_length": 181, "alphanum_fraction": 0.6919615463, "num_tokens": 1750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7643544887957521}}
{"text": "function ldlt!(a::Matrix{Float64}, d = Vector{Float64}; small=1.0e-10)\n  n = size(a, 1)\n  for k in 1:n-1\n    d[1] = a[1,1]\n    if abs(a[k,k]) > small\n      for i in k+1:n\n        x = a[i,k] / a[k,k]\n        for j = k+1:n\n          a[i,j] -= a[k,j] * x\n        end\n        d[i] = a[i,i]\n      end\n    else\n      println(\"Zero pivot found in row $k\")\n    end\n  end\nend\n\nfunction ldlt(a::Matrix{Float64}, d = Vector{Float64}; small=1.0e-10)\n  at = deepcopy(a)\n  dt = deepcopy(d)\n  n = size(at, 1)\n  for k in 1:n-1\n    dt[1] = at[1,1]\n    if abs(at[k,k]) > small\n      for i in k+1:n\n        x = at[i,k] / at[k,k]\n        for j = k+1:n\n          at[i,j] -= at[k,j] * x\n        end\n        dt[i] = at[i,i]\n      end\n    else\n      println(\"Zero pivot found in row $k\")\n    end\n  end\n  (at, dt)\nend\n\nexport\n  ldlt!,\n  ldlt\n", "meta": {"hexsha": "0507afd645ba39fd5faeeb0f00dceb38c39e48b0", "size": 817, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nmlib/ldlt.jl", "max_stars_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_stars_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "src/nmlib/ldlt.jl", "max_issues_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "src/nmlib/ldlt.jl", "max_forks_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 19.0, "max_line_length": 70, "alphanum_fraction": 0.4651162791, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682086, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7643544832114979}}
{"text": "export proxL21!, normL21\n\n\n\"\"\"\n    proxL21!(x::Vector{T},λ::Float64; sparseTrafo::Trafo=nothing, slices::Int64=1, kargs...)\n\ngroup-soft-thresholding for l1/l2-regularization.\n\n# Arguments:\n* `x::Array{T}`                 - Vector to apply proximal map to\n* `λ::Float64`                  - regularization paramter\n* `sparseTrafo::Trafo=nothing`  - sparsifying transform to apply\n* `slices::Int64=1`             - number of elements per group\n\"\"\"\nfunction proxL21!(x::Vector{T},λ::Float64; sparseTrafo::Trafo=nothing, slices::Int64=1, kargs...) where T\n  if sparseTrafo != nothing\n    z = sparseTrafo*x\n  else\n    z = x\n  end\n  if λ != 0\n    proxL21!(z, λ, slices)\n  end\n  if sparseTrafo != nothing\n    x[:] = adjoint(sparseTrafo)*z\n  else\n    x[:] = z\n  end\n  return x\nend\n\nfunction proxL21!(x::Vector{T}, λ::Float64, slices::Int64) where T\n  sliceLength = div(length(x),slices)\n  groupNorm = [norm(x[i:sliceLength:end]) for i=1:sliceLength]\n  x[:] = [ x[i]*max( (groupNorm[mod1(i,sliceLength)]-λ)/groupNorm[mod1(i,sliceLength)],0 ) for i=1:length(x)]\nend\n\n\"\"\"\n    normL21(x::Vector{T}, λ::Float64; sparseTrafo::Trafo=nothing, slices::Int64=1, kargs...) where T\n\nreturn the value of the L21-regularization term.\nArguments are the same as in `proxL21!`\n\"\"\"\nfunction normL21(x::Vector{T}, λ::Float64; sparseTrafo::Trafo=nothing, slices::Int64=1, kargs...) where T\n  if sparseTrafo != nothing\n    z = sparseTrafo*x\n  else\n    z = x\n  end\n  sliceLength = div(length(z),slices)\n  groupNorm = [norm(z[i:sliceLength:end]) for i=1:sliceLength]\n  return λ*norm(groupNorm,1)\nend\n", "meta": {"hexsha": "6feb440900d2d56f7ae8c501820a58d90a5b30cb", "size": 1568, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/proximalMaps/ProxL21.jl", "max_stars_repo_name": "alexjaffray/RegularizedLeastSquares.jl", "max_stars_repo_head_hexsha": "2a8fcba5cc270c5683415efa2d2190bb39f19424", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-06-21T03:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T02:40:40.000Z", "max_issues_repo_path": "src/proximalMaps/ProxL21.jl", "max_issues_repo_name": "alexjaffray/RegularizedLeastSquares.jl", "max_issues_repo_head_hexsha": "2a8fcba5cc270c5683415efa2d2190bb39f19424", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2018-10-28T12:32:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T18:56:24.000Z", "max_forks_repo_path": "src/proximalMaps/ProxL21.jl", "max_forks_repo_name": "alexjaffray/RegularizedLeastSquares.jl", "max_forks_repo_head_hexsha": "2a8fcba5cc270c5683415efa2d2190bb39f19424", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-08-13T08:02:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T23:01:39.000Z", "avg_line_length": 29.037037037, "max_line_length": 109, "alphanum_fraction": 0.6568877551, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7642747489756749}}
{"text": "# Let d(n) be defined as the sum of proper divisors of n (numbers less than n\n# which divide evenly into n).  If d(a) = b and d(b) = a, where a ≠ b, then a\n# and b are an amicable pair and each of a and b are called amicable numbers.\n#\n# For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44,\n# 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4,\n# 71 and 142; so d(284) = 220.\n#\n# Evaluate the sum of all the amicable numbers under 10000.\n\nusing ProjectEulerSolutions\n\n# Actually build up an array of factors, testing for amicable numbers smaller\n# than the current index.  Building up is done with a double loop, adding like\n# below.\n#\n# 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16\n#    1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1\n#             2     2     2     2     2     2     2\n#                   3        3        3        3\n#                         4           4           4\n#                               5              5\n#                                     6\n#                                           7\n#                                                 8\nfunction p021solution_incremental(n::Integer=10)::Integer\n    amicable_numbers = Array{Integer, 1}()\n\n    factor_sums = ones(Integer, n)\n    for i = 2:n\n        for j = 2*i:i:n\n            factor_sums[j] += i\n        end\n        x = factor_sums[i]\n        if x < i && i == factor_sums[x]\n            push!(amicable_numbers, x)\n            push!(amicable_numbers, i)\n        end\n    end\n    return sum(amicable_numbers)\nend\n\n# Repeatedly uses factors function and cache values so you don't\n# recalculate.  Store in a set so you get unique values.\nfunction p021solution_factors(n::Integer=10)::Integer\n    factor_sums = zeros(Integer, 5*n) # Initialize to some large size\n\n    amicable_numbers = Set{Integer}()\n\n    for i in 2:n\n        s1 = factor_sums[i]\n        if s1 == 0\n            s1 = sum(factors(i))\n            factor_sums[i] = s1\n        end\n        s2 = factor_sums[s1]\n        if s2 == 0\n            s2 = sum(factors(s1))\n            factor_sums[s1] = s2\n        end\n        if s2 == i && s1 != s2\n            push!(amicable_numbers, s1)\n            push!(amicable_numbers, s2)\n        end\n    end\n    return sum(amicable_numbers)\nend\n\np021 = Problems.Problem(Dict(\"Incremental\" => p021solution_incremental,\n                             \"Factors\" => p021solution_factors))\n\nProblems.benchmark(p021, 10_000)", "meta": {"hexsha": "25f3bd7e9ff970c20c6e4a4991a9ecc24b107ca6", "size": 2444, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/021.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/021.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/021.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9444444444, "max_line_length": 78, "alphanum_fraction": 0.5315057283, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8376199572530449, "lm_q1q2_score": 0.7642747457126507}}
{"text": "#=\n# The BUGS Book\n# Example 2.1.2, page 17:\n# For\n#   Y ~ Binomial(0.5, 8)\n# we want to know Pr(Y <= 2)\n#\n\n  See ~/jags/bugs_book_2_1_2.jags\n       Mean     SD Naive SE Time-series SE\n  P2 0.1442 0.3513 0.001434       0.001434\n  Y  4.0025 1.4177 0.005788       0.005839\n\n  ~/webppl/bugs_book_2_1_2.wppl\n\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n@model function bugs_book_2_1_2()\n\n    y ~ Binomial(8,0.5)\n    p2 ~ y <= 2 ? flip(1.0) : flip(0.0);\n\n    return y, p2\n\nend\n\n\nmodel = bugs_book_2_1_2()\n\nnum_chains = 4\n# chains = sample(model, Prior(), MCMCThreads(), 10_000, num_chains)\n\n# chains = sample(model, MH(), MCMCThreads(), 40_000, num_chains)\n\n# chains = sample(model, PG(15), MCMCThreads(), 10_000, num_chains)\n\nchains = sample(model, SMC(1000), MCMCThreads(), 10_000, num_chains)\n\n# chains = sample(model, IS(), MCMCThreads(), 10_000, num_chains)\n\ndisplay(chains)\n# display(plot(chains))\n\ngen = generated_quantities(model, chains)\nshow_var_dist_pct(gen, 120)\n", "meta": {"hexsha": "83055ec03b86a3b7fc9e4b89c30ab28212d9844f", "size": 991, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/bugs_book_2_1_2.jl", "max_stars_repo_name": "Wikunia/hakank", "max_stars_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/turing/bugs_book_2_1_2.jl", "max_issues_repo_name": "Wikunia/hakank", "max_issues_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/turing/bugs_book_2_1_2.jl", "max_forks_repo_name": "Wikunia/hakank", "max_forks_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2244897959, "max_line_length": 68, "alphanum_fraction": 0.6649848638, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7642747392937511}}
{"text": "@doc raw\"\"\"\nThe Cauchy or Paul wavelet.\n\nIn contrast to the `MorletWavelet`, the Cauchy or Paul wavelet is a proper wavelet with a\nsimilar good localization in time and scale.\n\nThere are different definitions of the Cauchy wavelet around. Here one is implemented where\nthe center frequency is always 1 irrespective of the value of α:\n```math\n g(t) = h(t) = \\left(1-i\\,\\frac{2\\pi\\,t}{\\alpha}\\right)^{-(1+\\alpha)}\\,,\n```\nand its reproducing kernel\n```math\n P_{g,h}(b, a) = \\Gamma(2\\alpha+1)\\,a^{\\alpha+1}\\,\\left(1+a-\\frac{i\\,b}{a}\\right)^{-(2\\alpha+1)}\\,.\n```\n\"\"\"\nstruct CauchyWavelet <: GenericContinuousWavelet\n    α::Float64;\n    norm::Float64;\n    ϵ::Float64\n\n    @doc raw\"\"\"\n        CauchyWavelet(α::Real; ϵ::Real=1e-2)\n\n    Constructs a new Cauchy wavelet, whith the given α specifying the time-frequency resolution.\n    The optional keyword arguent ϵ specifies the cutoff at which the kernel evaluation gets\n    truncated. It is defined as the fraction of total power loss of the mother wavelet. Smaller\n    values of ϵ will increase the precision of the wavelet transform on the cost of longer kernels\n    leading to slower convolutions.\n    \"\"\"\n    function CauchyWavelet(α::Real; ϵ::Real=1e-2)\n        norm = exp(-2*log(2π) - logabsgamma(2α+1)[1]/2 + logabsgamma(α+1)[1]\n          + (2α+2)*log(2)/2 + log(α));\n        new(α, norm, ϵ);\n    end\nend\n\nfunction eval_analysis(wav::CauchyWavelet, t::Float64)\n    (1 - 2im*π*t/wav.α)^(-1-wav.α);\nend\n\neval_synthesis(wav::CauchyWavelet, t::Float64) = wav.norm * eval_analysis(wav, t);\n\nfunction eval_repkern(wav::CauchyWavelet, a::Float64, b::Float64)\n    c = wav.α*log(a) + logabsgamma(2*wav.α-1)[1] - (1+2*wav.α)*log(2π);\n    exp(c) * (1+a-2im*π*b/wav.α)^(-1-2*wav.α);\nend\n\nfunction cutoff_time(wav::CauchyWavelet)\n    wav.α*sqrt(wav.ϵ^(-2/(wav.α+1))-1)/(2π);\nend;\n\nfunction cutoff_freq(wav::CauchyWavelet)\n    1 + 1/( wav.α^2 * (wav.ϵ^(-2 / (wav.α + 1)) - 1) / ((2π)^2) );\nend;\n", "meta": {"hexsha": "866a924ccbd843ecc630c7f7ca31b1fa44dc604d", "size": 1931, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cauchy.jl", "max_stars_repo_name": "hmatuschek/ContinuousWavelet.jl", "max_stars_repo_head_hexsha": "23c49cdafee0ae21aeba2755924d6ef59b4e5637", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cauchy.jl", "max_issues_repo_name": "hmatuschek/ContinuousWavelet.jl", "max_issues_repo_head_hexsha": "23c49cdafee0ae21aeba2755924d6ef59b4e5637", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cauchy.jl", "max_forks_repo_name": "hmatuschek/ContinuousWavelet.jl", "max_forks_repo_head_hexsha": "23c49cdafee0ae21aeba2755924d6ef59b4e5637", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4821428571, "max_line_length": 99, "alphanum_fraction": 0.6592439151, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361533336451, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7642747372992952}}
{"text": "function dbeta(p::Real, a::Real, b::Real)\n    any((a, b) .<= 0) ? (return NaN) : nothing\n    !(0 <= p <= 1) ? (return 0.0) : nothing\n    return gamma(a + b)/gamma(a)/gamma(b)*(1 - p)^(b - 1)*p^(a - 1)\nend\nfunction pbeta(p::Real, a::Real, b::Real)\n    any((a, b) .<= 0) ? (return NaN) : nothing\n    p <= 0  ? (return 0.0) : nothing\n    p >= 1  ? (return 1.0) : nothing\n    return beta_inc(a, b, p, 1 - p)[1]\nend\n\ngauss_legendre = function(low, high, order::Integer)\n    pivots, weights = gauss(order)\n    a, b = (high - low)/2, (high + low)/2\n    scaled_pivots  = a .* pivots .+ b\n    scaled_weights = a .* weights\n    return(scaled_pivots, scaled_weights)\nend\n\n# precompute\ngl_25_pivots, gl_25_weights = gauss_legendre(-1, 1, 25)\ngauss_legendre_25 = function(low, high)\n    pivots, weights = gl_25_pivots, gl_25_weights\n    a, b = (high - low)/2, (high + low)/2\n    scaled_pivots  = a .* pivots .+ b\n    scaled_weights = a .* weights\n    return(scaled_pivots, scaled_weights)\nend\n\nfunction one_stage_sample_size(p0::Real, α::Real, p1::Real, β::Real)\n    z_1_α   = Distributions.quantile(Distributions.Normal(), 1 - α)\n    z_1_β   = Distributions.quantile(Distributions.Normal(), 1 - β)\n    napprox = p1*(1 - p1)*( (z_1_α + z_1_β) / (p1 - p0) )^2\n    return Int(ceil(napprox))\nend\n", "meta": {"hexsha": "81c37f1d07492285afb033baff8d316f31e3800d", "size": 1280, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/util.jl", "max_stars_repo_name": "JuliaTagBot/bad.jl", "max_stars_repo_head_hexsha": "7cccc038b65e4d6e923221064c20b361466e21cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/util.jl", "max_issues_repo_name": "JuliaTagBot/bad.jl", "max_issues_repo_head_hexsha": "7cccc038b65e4d6e923221064c20b361466e21cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-12-10T17:25:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-06T10:33:25.000Z", "max_forks_repo_path": "src/util.jl", "max_forks_repo_name": "JuliaTagBot/bad.jl", "max_forks_repo_head_hexsha": "7cccc038b65e4d6e923221064c20b361466e21cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:43:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:43:02.000Z", "avg_line_length": 34.5945945946, "max_line_length": 68, "alphanum_fraction": 0.6140625, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7642710072273983}}
{"text": "#=\nProblem 101\n=#\n\nfunction u_gen(k::Array, n)\n    sum = 0\n    for i = length(k):-1:1\n        sum = k[i] + sum * n\n    end\n    return sum\nend\n\nN = 11\n\n# first 11 terms\nu_n = Vector{Float64}(N)\nfor i=1:N\n    u_n[i] = u_gen([1 -1 1 -1 1 -1 1 -1 1 -1 1], i)\nend\n\n# Matrix of coefficients\nA = Array{Float64}(N,N)\nfor i=1:N, j=1:N\n    A[i,j] = i^(j-1)\nend\n\nsum = 0\nfor i=1:N-1\n    coeff = Array{Int64}(round(inv(A[1:i, 1:i]) * u_n[1:i]))\n    FIT = u_gen(coeff, i+1)\n    @show coeff\n    @show FIT\n    sum += FIT\nend\n\nprintln(\"Sum of FITs is $(sum)\")\n\n# Alternatively u_n = A*[1 -1 1 -1 1 -1 1 -1 1 -1 1]'\n", "meta": {"hexsha": "6435a55af825f0b2c382ab9cb32446f877282106", "size": 599, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problem-101.jl", "max_stars_repo_name": "mebrunet/project-euler", "max_stars_repo_head_hexsha": "95140634b82c568af468e6c065a3be823b4935c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problem-101.jl", "max_issues_repo_name": "mebrunet/project-euler", "max_issues_repo_head_hexsha": "95140634b82c568af468e6c065a3be823b4935c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem-101.jl", "max_forks_repo_name": "mebrunet/project-euler", "max_forks_repo_head_hexsha": "95140634b82c568af468e6c065a3be823b4935c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.358974359, "max_line_length": 60, "alphanum_fraction": 0.5325542571, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801267121407, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7642709901258052}}
{"text": "#=\n\n  Euler #16 in Julia.\n\n  Problem 16\n  \"\"\"\n  2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.\n\n  What is the sum of the digits of the number 2^1000?\n  \"\"\"\n\n  This Julia program was created by Hakan Kjellerstrand, hakank@gmail.com\n  See also my Julia page: http://www.hakank.org/julia/\n\n=#\n\ninclude(\"Euler.jl\")\n\n# 0.00027433s\nfunction euler16a()\n    # return split(string(BigInt(2)^1000),\"\").|>(i->parse(Int,i))|>sum\n    return digits(BigInt(2)^1000)|>sum\nend\n\nrun_euler(euler16a);\n", "meta": {"hexsha": "95a275f3ab299cad2f83fcdf1d43ae9d99e65bce", "size": 501, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/euler16.jl", "max_stars_repo_name": "Wikunia/hakank", "max_stars_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/euler16.jl", "max_issues_repo_name": "Wikunia/hakank", "max_issues_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/euler16.jl", "max_forks_repo_name": "Wikunia/hakank", "max_forks_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 19.2692307692, "max_line_length": 73, "alphanum_fraction": 0.6487025948, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7642272575140103}}
{"text": "# Euler's Totient function, φ(n) [sometimes called the phi function], is used\n# to determine the number of numbers less than n which are relatively prime to\n# n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively\n# prime to nine, φ(9)=6.\n# \n# n   Relatively Prime  φ(n)   n/φ(n)\n# --------------------------------------\n# 2   1                 1      2\n# 3   1,2               2      1.5\n# 4   1,3               2      2\n# 5   1,2,3,4           4      1.25\n# 6   1,5               2      3\n# 7   1,2,3,4,5,6       6      1.1666...\n# 8   1,3,5,7           4      2\n# 9   1,2,4,5,7,8       6      1.5\n# 10  1,3,7,9           4      2.5\n#\n# It can be seen that n=6 produces a maximum n / φ(n) for n ≤ 10.\n#\n# Find the value of n ≤ 1,000,000 for which n / φ(n) is a maximum.\n\n\nusing ProjectEulerSolutions\n\n# Brute force solution, considering every value less than n.\nfunction p069solution_bruteforce(n::Integer=1_000)::Integer\n\n    max_val = 0.0\n    max_index = 0\n    for i in 2:n\n        test_val = i / totient(i)\n        if max_val < test_val\n            max_val = test_val\n            max_index = i\n        end\n    end\n\n    return max_index\nend\n\n# Only consider values that are likely candidates, which are primodial numbers.\n# Primodial numbers are the product of consecutive primes starting at 2, so\n# 2, 6, 30, 210, etc.  We only consider primordial numbers up to that who's\n# product more than n since they have maximal n / φ(n) values.\nfunction p069solution_factors(n::Integer=1_000)::Integer\n\n    primes = sieve_eratosthenes(30)\n    index = 2\n    p = primes[1]\n    while p * primes[index] < n\n        p *= primes[index]\n        index += 1\n    end\n    return p\nend\n\n\np069 = Problems.Problem(Dict(\"Brute force\" => p069solution_bruteforce,\n                             \"Factors\" => p069solution_factors))\n\nProblems.benchmark(p069, 1_000_000)\n", "meta": {"hexsha": "d4d7eed478f94b3d33f1a5231d9dda7731837b7c", "size": 1869, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/069.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/069.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/069.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1451612903, "max_line_length": 80, "alphanum_fraction": 0.5730337079, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7642272569836543}}
{"text": "@doc raw\"\"\"\n    Otsu <: AbstractImageBinarizationAlgorithm\n    Otsu()\n\n    binarize([T,] img, f::Otsu)\n    binarize!([out,] img, f::Otsu)\n\nUnder the assumption that the image histogram is bimodal the binarization\nthreshold is set so that the resultant between-class variance is maximal.\n\n# Output\n\nReturn the binarized image as an `Array{Gray{T}}` of size `size(img)`. If\n`T` is not specified, it is inferred from `out` and `img`.\n\n# Details\n\nLet ``f_i`` ``(i=1 \\ldots I)`` denote the number of observations in the\n``i``th bin of the image histogram. Then the probability that an observation\nbelongs to the ``i``th bin is given by  ``p_i = \\frac{f_i}{N}`` (``i = 1,\n\\ldots, I``), where ``N = \\sum_{i=1}^{I}f_i``.\n\nThe choice of a threshold ``T`` partitions the data into two categories, ``C_0``\nand ``C_1``. Let\n```math\nP_0(T) = \\sum_{i = 1}^T p_i \\quad \\text{and} \\quad P_1(T) = \\sum_{i = T+1}^I p_i\n```\ndenote the cumulative probabilities,\n```math\n\\mu_0(T) = \\sum_{i = 1}^T i \\frac{p_i}{P_0(T)} \\quad \\text{and} \\quad \\mu_1(T) = \\sum_{i = T+1}^I i \\frac{p_i}{P_1(T)}\n```\ndenote the means, and\n```math\n\\sigma_0^2(T) = \\sum_{i = 1}^T (i-\\mu_0(T))^2 \\frac{p_i}{P_0(T)} \\quad \\text{and} \\quad \\sigma_1^2(T) = \\sum_{i = T+1}^I (i-\\mu_1(T))^2 \\frac{p_i}{P_1(T)}\n```\ndenote the variances of categories ``C_0`` and ``C_1``, respectively.\nFurthermore, let\n```math\n\\mu = P_0(T)\\mu_0(T) + P_1(T)\\mu_1(T),\n```\nrepresent the overall mean,\n```math\n\\sigma_b^2(T) = P_0(T)(\\mu_0(T) - \\mu)^2 + P_1(T)(\\mu_1(T) - \\mu)^2,\n```\nthe between-category variance, and\n```math\n\\sigma_w^2(T) = P_0(T) \\sigma_0^2(T) +  P_1(T)\\sigma_1^2(T)\n```\nthe within-category variance, respectively.\n\nFinding the discrete value ``T`` which maximises the function ``\\sigma_b^2(T)``\nproduces the sought-after threshold value (i.e. the bin which determines the\nthreshold). As it turns out, that threshold value is equal to the threshold\ndecided by minimizing the within-category variances criterion ``\\sigma_w^2(T)``.\nFurthermore, that threshold is also the same as the threshold calculated by\nmaximizing the ratio of between-category variance to within-category variance.\n\n# Arguments\n\nThe function argument is described in more detail below.\n\n##  `img::AbstractArray`\n\nThe image that needs to be binarized.  The image is automatically converted\nto `Gray` in order to construct the requisite graylevel histogram.\n\n\n# Example\n\nBinarize the \"cameraman\" image in the `TestImages` package.\n\n```julia\nusing TestImages, ImageBinarization\n\nimg = testimage(\"cameraman\")\nimg_binary = binarize(img, Otsu())\n```\n\n# Reference\n\n1. Nobuyuki Otsu (1979). “A threshold selection method from gray-level histograms”. *IEEE Trans. Sys., Man., Cyber.* 9 (1): 62–66. [doi:10.1109/TSMC.1979.4310076](http://dx.doi.org/doi:10.1109/TSMC.1979.4310076)\n\"\"\"\nstruct Otsu <: AbstractImageBinarizationAlgorithm end\n\nfunction (f::Otsu)(out::GenericGrayImage, img::GenericGrayImage)\n    edges, counts = build_histogram(img,  256)\n    t = find_threshold(HistogramThresholding.Otsu(), counts[1:end], edges)\n    @simd for i in CartesianIndices(img)\n        out[i] = img[i] < t ? 0 : 1\n    end\n    out\nend\n\n(f::Otsu)(out::GenericGrayImage, img::AbstractArray{<:Color3}) =\n    f(out, of_eltype(Gray, img))\n", "meta": {"hexsha": "7e0bc0ef10c55205f10ede302d64e1ad966cff3c", "size": 3227, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algorithms/otsu.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ImageBinarization.jl-cbc4b850-ae4b-5111-9e64-df94c024a13d", "max_stars_repo_head_hexsha": "e6b3b13279196544e815c821e45e2bef37c18376", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algorithms/otsu.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ImageBinarization.jl-cbc4b850-ae4b-5111-9e64-df94c024a13d", "max_issues_repo_head_hexsha": "e6b3b13279196544e815c821e45e2bef37c18376", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithms/otsu.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ImageBinarization.jl-cbc4b850-ae4b-5111-9e64-df94c024a13d", "max_forks_repo_head_hexsha": "e6b3b13279196544e815c821e45e2bef37c18376", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-13T20:29:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-13T20:29:41.000Z", "avg_line_length": 33.6145833333, "max_line_length": 211, "alphanum_fraction": 0.6867059188, "num_tokens": 1082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.764227251210329}}
{"text": "using Plots\nplotlyjs()\n\n# Rossler space equation\nfunction rossler(t::Float64, x::Vector{Float64}, dx::Vector{Float64},\n                 a::Float64, b::Float64, c::Float64)\n    dx[1] = -x[2] - x[3]\n    dx[2] = x[1] + a*x[2]\n    dx[3] = b + x[3]*(x[1]-c)\n    return dx\nend\n\n\"\"\"\n    rk4(f, x0, time_span[, h, args])\n\n4-th order Runge-Kutta. ``f`` is a handler to the\nspace state funtion, ``x0`` is a vector of initial\nconditions, ``time_span`` is a tuple containing\nthe start and end simulation times and ``h`` is the\nintegration interval.\n\nThe function ``f`` is called as:\n\n    dx = f(t, x, args...)\n\"\"\"\nfunction rk4(f::Function, x0::Vector{Float64}, time_span; h=(time_span[2]-time_span[1])/1e4, args=())\n    t = time_span[1]:h:time_span[2]\n    N = length(t)\n    n = length(x0)\n    # Allocate buffers\n    x = Vector{Vector{Float64}}(N)\n    for i = 1:N\n        x[i] = Vector{Float64}(n)\n    end\n    xd = Vector{Float64}(n)\n    x_aux = Vector{Float64}(n)\n    # Simulate\n    copy!(x[1], x0)\n    @inbounds for i = 1:N-1\n        copy!(x[i+1], x[i])\n        # 1-st evaluation\n        f(t[i], x[i], xd, args...)\n        Base.LinAlg.axpy!(h/6, xd, x[i+1])\n        # 2-nd evaluation\n        copy!(x_aux, x[i])\n        Base.LinAlg.axpy!(h/2, xd, x_aux)\n        f(t[i]+h/2, x_aux, xd, args...)\n        Base.LinAlg.axpy!(h/6, xd, x[i+1])\n        # 3-rd evaluation\n        copy!(x_aux, x[i])\n        Base.LinAlg.axpy!(h/2, xd, x_aux)\n        f(t[i]+h/2, x_aux, xd, args...)\n        Base.LinAlg.axpy!(h/6, xd, x[i+1])\n        # 4-th evaluation\n        copy!(x_aux, x[i])\n        Base.LinAlg.axpy!(h, xd, x_aux)\n        f(t[i]+h, x_aux, xd, args...)\n        Base.LinAlg.axpy!(h/6, xd, x[i+1])\n    end\n    return x\nend\n\n# Simulate Rossler\ntime_span = (0, 1000)\nx0 = [1.0, 1.0, 2.0]\nargs = (0.2, 0.2, 5.7)\n\n@time x = rk4(rossler, x0, time_span, h=0.01, args=args)\n\nx = hcat(x...)'\n\nplot(x)\n\nplot(x[:, 1], x[:,2], x[:, 3])\n", "meta": {"hexsha": "03a47901573eff3e4a9b9d74d4ca2a279c967ebf", "size": 1904, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "rossler_v2.jl", "max_stars_repo_name": "MACSIN-UFMG/julia-rossler-example", "max_stars_repo_head_hexsha": "c214bb28a584ad98c2380e01817eb5452093dc44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rossler_v2.jl", "max_issues_repo_name": "MACSIN-UFMG/julia-rossler-example", "max_issues_repo_head_hexsha": "c214bb28a584ad98c2380e01817eb5452093dc44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rossler_v2.jl", "max_forks_repo_name": "MACSIN-UFMG/julia-rossler-example", "max_forks_repo_head_hexsha": "c214bb28a584ad98c2380e01817eb5452093dc44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3866666667, "max_line_length": 101, "alphanum_fraction": 0.5388655462, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7642272414896288}}
{"text": "\"\"\"\n    smooth(z,sdim)\n\nSmoothen field `z` with a circular kernel of radius `sdim` using convolution\n\"\"\"\n\tfunction smooth(zi,sdim)\n\n        (nsx,nsy)=size(zi);\n        #sdim=div(div(ns,nas),2);\n\n        mask=zeros(nsx,nsy);\n        nsx2=div(nsx,2)\n        nsy2=div(nsy,2)\n\n        for i=1:nsx\n           for j=1:nsy\n               kx=i-1;\n               ky=j-1;\n               if(i>nsx2+1)\n                  kx=i-nsx-1 ;\n               end\n               if(j>nsy2+1)\n                  ky=j-nsy-1 ;\n               end\n               r2=kx*kx+ky*ky;\n               if(r2<=sdim*sdim)\n                  mask[i,j]=1.0;\n                end\n           end\n        end \n        zf=real(ifft(fft(mask).*fft(zi)))/sum(mask)\n        return zf\n   end\n", "meta": {"hexsha": "836eb1d54d3925b4b31c5a59ad7a7c43ae945552", "size": 740, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rf/smooth.jl", "max_stars_repo_name": "UnofficialJuliaMirror/RainFARM.jl-e9a4e08f-a0a3-5224-a821-6d0231c12d6b", "max_stars_repo_head_hexsha": "740f4edff721692e13168b132503aa62d5fea574", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rf/smooth.jl", "max_issues_repo_name": "UnofficialJuliaMirror/RainFARM.jl-e9a4e08f-a0a3-5224-a821-6d0231c12d6b", "max_issues_repo_head_hexsha": "740f4edff721692e13168b132503aa62d5fea574", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rf/smooth.jl", "max_forks_repo_name": "UnofficialJuliaMirror/RainFARM.jl-e9a4e08f-a0a3-5224-a821-6d0231c12d6b", "max_forks_repo_head_hexsha": "740f4edff721692e13168b132503aa62d5fea574", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7647058824, "max_line_length": 76, "alphanum_fraction": 0.4, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7642167926547622}}
{"text": "mutable struct EmpiricalBayesianRegressor\n    _alpha::Float64\n    _beta::Float64\n    _w_mean::AbstractArray{Float64,1}\n    _w_precision::AbstractArray{Float64,2}\n    _n_features::Int64\n    function EmpiricalBayesianRegressor(alpha::Float64, beta::Float64, n_features)\n        new(\n            alpha,\n            beta,\n            zeros(n_features) * 1.0,\n            zeros(n_features, n_features) * 1.0,\n            n_features,\n        )\n    end\nend\n\nfunction fitting(\n    regressor::EmpiricalBayesianRegressor,\n    Phi::AbstractArray{Float64,2},\n    t::AbstractArray{Float64,1},\n    max_iter::Int64 = 100,\n)\n    # Phi is the design matrix  [phi(x_1), phi(x_2), ,,, phi(x_N)]^T of size (n_samples, n_features)\n    n_features = size(Phi)[2]\n    n_samples = size(Phi)[1]\n    @assert n_samples == size(t)[1]\n\n    alpha = regressor._alpha\n    beta = regressor._beta\n    M = transpose(Phi) * Phi\n    eigenvalues = eigvals(M)\n    @assert n_features == size(eigenvalues)[1]\n\n    E = Matrix(I, n_features, n_features)\n    w_mean = zeros(n_features)\n    w_precision = zeros(n_features, n_features)\n    for i = 1:max_iter\n        params = [alpha beta]\n        w_precision = alpha * E + beta * M\n        w_mean = beta * inv(w_precision) * transpose(Phi) * t\n        gamma = sum(eigenvalues ./ (eigenvalues .+ alpha))\n\n        alpha = gamma / norm(w_mean)^2\n        beta = (n_samples - gamma) / sum((Phi * w_mean - t) .^ 2)\n        if isapprox(params, [alpha beta])\n            break\n        end\n    end\n\n    # update\n    regressor._alpha = alpha\n    regressor._beta = beta\n    regressor._w_mean = w_mean\n    regressor._w_precision = w_precision\nend\n\nfunction log_evidence(\n    regressor::EmpiricalBayesianRegressor,\n    Phi::AbstractArray{Float64,2},\n    t::AbstractArray{Float64,1},\n)\n    # Phi is the design matrix [phi(x_1), phi(x_2), ,,, phi(x_N)]^T of size (n_samples, n_features)\n    n_features = size(Phi)[2]\n    n_samples = size(Phi)[1]\n    M = n_features\n    N = n_samples\n    @assert n_samples == size(t)[1]\n\n    alpha = regressor._alpha\n    beta = regressor._beta\n    E = Matrix(I, n_features, n_features)\n    A = alpha * E + beta * transpose(Phi) * Phi\n    w = regressor._w_mean\n    Ew = beta / 2.0 * sum((t - Phi * w) .^ 2) + alpha / 2.0 * (transpose(w) * w)\n\n    return M / 2.0 * log(alpha) + N / 2.0 * log(beta) - Ew - log(det(A)) / 2.0 -\n           N / 2.0 * log(2 * pi)\nend\n\nfunction predict(\n    regressor::EmpiricalBayesianRegressor,\n    Phi::AbstractArray{Float64,2},\n    return_std::Bool = true,\n)\n    # Phi is the design matrix [phi(x_1), phi(x_2), ,,, phi(x_N)]^T of size (n_samples, n_features)\n    N = size(Phi)[1]\n    w_mean = regressor._w_mean\n    w_cov = inv(regressor._w_precision)\n\n    y = Phi * w_mean\n\n    if return_std == true\n        y_vars =\n            1.0 / regressor._beta .+ [transpose(Phi[i, :]) * w_cov * Phi[i, :] for i = 1:N]\n        y_std = sqrt.(y_vars)\n\n        return y, y_std\n    end\n\n    return y\nend\n", "meta": {"hexsha": "42c9bc5b299f41b7a2d013c087696f85cfdf5239", "size": 2939, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear/empirical_bayesian_regressor.jl", "max_stars_repo_name": "soblin/prml-julia", "max_stars_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-10T21:46:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:40:22.000Z", "max_issues_repo_path": "src/linear/empirical_bayesian_regressor.jl", "max_issues_repo_name": "soblin/prml-julia", "max_issues_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/linear/empirical_bayesian_regressor.jl", "max_forks_repo_name": "soblin/prml-julia", "max_forks_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5339805825, "max_line_length": 100, "alphanum_fraction": 0.6063286832, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7642167910462303}}
{"text": "# generic solve_hjb( ) Implicit method. \r\n# TODO: ns states/nc controls \r\n# TODO: add uncertainty, nx shocks...\r\n\r\nusing LinearAlgebra, SparseArrays, Plots\r\n\r\n# NGM ###############################\r\nif 1==1 \r\n    σ= 2.0; ρ = 0.05; δ = 0.05; A = 1.0; α= 0.3; \r\n\r\n    # Closed form. Doesn't work.\r\n    # σ= 4.0;  δ = 0.05; A = 1.0; α= 0.3; \r\n    # ρ = δ*(α*σ - 1) # restriction for closed form \r\n    # FOC(v;σ=σ) = abs(v)^(-1.0/σ)                  # FOC, u'^-1()\r\n\r\n    r(c; σ=σ)  = (c^(1-σ))/(1-σ)             # return fcn.      make it r(s,c)\r\n    μ(s,c; α=α,δ=δ,A=A) = A*(s^α) - δ*s -c;  # Transition fcn.  ṡ=μ(s,c)\r\n\r\n    dr(c;σ=σ) = c^(-σ)                       # derivative of return fcn.\r\n    FOC(v;σ=σ) = v^(-1.0/σ)                  # FOC, u'^-1()\r\n\r\n    μ_inv(s,ṡ; α=α,δ=δ,A=A) = A*(s^α) - δ*s -ṡ; # Inv Trans c=μ(s,ṡ), solve ṡ=μ(s,c) for c\r\n    # con0(s;α=α,δ=δ,A=A)     = A*(s^α) - δ*s      # solve: ṡ=μ(s,c) for c(s) if ṡ=0. \r\n    # μ_inv(s,0) = con0(s)\r\n\r\n    s_ss = (α*A/(ρ+δ))^(1/(1-α))\r\n    s_min = 0.001*s_ss\r\n    s_max = 2.000*s_ss\r\n    H = 10_000;\r\n    s = LinRange(s_min, s_max, H)\r\n    s = convert(Array, s)\r\n    ds = (s_max-s_min)/(H-1)\r\nend \r\n\r\n# con-sav ###############################\r\nif 1==1 \r\n    a_bar = -0.02;\r\n    #a_bar = 0.1;\r\n    σ= 2.0; ρ = 0.05; A=0.045; w = 0.1;\r\n    r(c;σ=σ)  = (c^(1-σ))/(1-σ)            # return fcn.\r\n    μ(s,c; w=w,A=A) = w + A*s - c;         # Transition fcn.  ṡ=μ(s,c)\r\n\r\n    dr(c;σ=σ) = c^(-σ)                     # deriv return fcn.\r\n    FOC(v;σ=σ) = v^(-1.0/σ)                # FOC, u'^-1()\r\n\r\n    μ_inv(s,ṡ; w=w,A=A) = w + A*s -ṡ;  # Inv Trans c=μ(s,ṡ), solve ṡ=μ(s,c) for c\r\n    # μ_inv(s,0) = con0(s)\r\n    #con0(s;α=α,δ=δ,A=A) = w + A*s          # solve: ṡ=μ(s,c) for c(s) if ṡ=0. \r\n\r\n    s_min = a_bar\r\n    μ_inv(s_min,0) > 0 \r\n    \r\n    s_max = 1.0\r\n    H = 10_000;\r\n    s = LinRange(s_min, s_max, H)\r\n    s = convert(Array, s)\r\n    ds = (s_max-s_min)/(H-1)\r\nend \r\n\r\n##################################\r\nΔ = 1_000\r\nmaxit = 10_000\r\nε = 10e-6\r\ndVf, dVb     = [zeros(H,1) for i in 1:2]\r\ndV_Upwind, c = [zeros(H,1) for i in 1:2]\r\nv0 = @. r(μ_inv(s,0))/ρ #initial guess for V\r\nv = v0\r\ndist=[]\r\n\r\nfor n=1:maxit\r\n    #println(n)\r\n\tV=v\r\n    dV = (V[2:H]-V[1:H-1])/ds\r\n\r\n    # forward difference\r\n\tdVf[1:H-1] = dV\r\n\tdVf[H]     = dr(μ_inv(s_max,0))      # u'(c(s_max)) state constraint, for stability\r\n    #dVf[H]= 0;\r\n\r\n\t# backward difference\r\n\tdVb[2:H] = dV\r\n\tdVb[1]   = dr(μ_inv(s_min,0))        # state constraint, for stability\r\n    #dVb[1] = (A*s_min)^(-σ)\r\n\r\n\r\n\tI_concave = dVb .> dVf\r\n    # scatter(I_concave) #1 everywhere EXCEPT @ last point H. \r\n\r\n    # consumption and savings with forward difference\r\n    cf  = FOC.(dVf)\r\n    μ_f = μ.(s, cf)\r\n\r\n    # consumption and savings with backward difference\r\n    cb  = FOC.(dVb)\r\n    μ_b = μ.(s, cb)\r\n\r\n    # c if k̇=0 & V = u'(c)\r\n\tc0  = μ_inv.(s,0)   # con0.(s) \r\n    dV0 = dr.(c0)\r\n\r\n    # Now to make a choice between forward and backward difference\r\n    If = μ_f .> 0\r\n    Ib = μ_b .< 0\r\n    I0 = (1.0 .- If - Ib)\r\n\r\n    dV_Upwind= dVf.*If + dVb.*Ib + dV0.*I0   \r\n    c = FOC.(dV_Upwind)                       \r\n    u = r.(c)\r\n\r\n    # plot(dVf, lab=\"dVf\") \r\n    # plot!(dVb, lab=\"dVb\")\r\n    # plot!(dV0, lab=\"dV0\")\r\n    # plot!(dV_Upwind, lab=\"dV_Upwind\")\r\n\r\n    # plot(cf, lab=\"dVf\") \r\n    # plot!(cb, lab=\"dVb\")\r\n    # plot!(c0, lab=\"dV0\")\r\n    # plot!(c, lab=\"dV_Upwind\")\r\n\r\n    # plot(μ_f, lab=\"dVf\") \r\n    # plot!(μ_b, lab=\"dVb\")\r\n    # plot!(zero(μ_f), lab=\"dV0\")\r\n\r\n    # create the transition matrix\r\n    X = -min.(μ_b,0)/ds\r\n    Y = -max.(μ_f,0)/ds + min.(μ_b,0)/ds\r\n    Z = max.(μ_f,0)/ds\r\n\r\n    a1 = sparse(Diagonal((Y[:])))\r\n    a2 = [zeros(1,H); sparse(Diagonal((X[2:H]))) zeros(H-1,1)]\r\n    a3 = [zeros(H-1,1) sparse(Diagonal((Z[1:H-1]))); zeros(1,H)]\r\n    AA = a1 + a2 + a3\r\n\r\n    B = (ρ + 1/Δ)*sparse(I,H,H) - AA\r\n    b = u + V./Δ\r\n\r\n    # Solve: B V = b \r\n    # => (ρ + 1/Δ)*sparse(I,H,H)*V - AA*V = u + V./Δ\r\n    # => (ρ + 1/Δ)*V = u + V./Δ +  AA*V\r\n    # => (ρ)*V + V./Δ = u + V./Δ +  AA*V\r\n    # => (ρ)*V = u  +  AA*V\r\n\r\n    V = B \\ b\r\n    V_change = V-v\r\n    v = V \r\n\r\n\tpush!(dist,findmax(abs.(V_change))[1])\r\n    println(n, \" \", dist[n])\r\n\tif dist[n] .< ε\r\n\t\tprintln(\"Value Function Converged Iteration=\")\r\n\t\tprintln(n)\r\n\t\tbreak\r\n\tend\r\nend\r\n\r\ns_dot = μ.(s,c)\r\nv_err = r.(c) + dV_Upwind.*s_dot - ρ.*v # approx @ borrowing constraint\r\n# TODO: SIMULATE!\r\n\r\nplot(dist, \r\n\t\txlabel=\"Iteration\", ylabel=\"||V^{n+1} - V^n||\",\r\n\t\t#ylims=(-0.001,0.030),\r\n\t\tlegend=false, title=\"\")\r\n#png(\"Convergence\")\r\n\r\nplot(s, v_err, \r\n\t\txlabel=\"s\", ylabel=\"Error in the HJB equation\",\r\n\t\txlims=(s_min,s_max),\r\n\t\tlegend=false, title=\"\")\r\n#png(\"HJB_error\")\r\n\r\nplot(s, v, \r\n\t\txlabel=\"k\", ylabel=\"V(k)\",\r\n\t\txlims=(s_min,s_max),\r\n\t\tlegend=false, title=\"\")\r\n#png(\"Value_function_vs_k\")\r\n\r\nplot(s, c, \r\n\t\txlabel=\"k\", ylabel=\"c(k)\",\r\n\t\txlims=(s_min,s_max),\r\n\t\tlegend=false, title=\"\")\r\n#png(\"c(k)_vs_k\")\r\n\r\nplot(s, s_dot, \r\n\t\txlabel=\"k\", ylabel=\"s(k)\",\r\n\t\txlims=(s_min,s_max), title=\"\", label=\"s(k)\", legend=false)\r\nplot!(s, zeros(H,1), label=\"\", line=:dash)\r\n#png(\"stateconstraint\")\r\n\r\n# Simulate. \r\n# s_0 = 0.10;\r\n# c_0 # = interpolate(s_0, (s,c(s)))\r\n# sp = μ(s_0, c)\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Special case of NGM has closed-form sol. Compare!\r\nσ= 4.0;  δ = 0.05; A = 1.0; α= 0.3; \r\nρ = δ*(α*σ - 1) # restriction for closed form \r\n\r\n# Policy: c = (1-s)(k^α)\r\ncp(s) = (1-((α*δ)/(ρ+δ)))*s^α\r\ns_d(s) = (s^α) - δ*s - cp(s)\r\nplot(s, cp)\r\nplot!(s, s_d)\r\n\r\n#\r\ns_ss = (α*A/(ρ+δ))^(1/(1-α))\r\nz_ss = (s_ss)^(1-α)\r\nc_ss = (s_ss)^(α)  - δ*s_ss\r\n\r\ns_0 = 5;\r\nz_0 = (s_0)^(1-α)\r\n\r\nλ=(1-α)*δ\r\nz(t) = z_ss + exp(-λ*t)*(z_0 - z_ss)\r\nkk(t) = z(t)^(1/(1-α))\r\ncc(t) = (1-((α*δ)/(ρ+δ)))*kk(t)^α\r\n\r\nt_sim = 0.01:0.01:100\r\nplot(legend=:topleft)\r\nplot!(t_sim, z, lab=\"z\")\r\nplot!(t_sim, kk, lab=\"k\")\r\nplot!(t_sim, cc, lab=\"c\")\r\nplot!([z_ss s_ss c_ss],  seriestype = :hline, lab=\"\", color=\"grey\")\r\n\r\n", "meta": {"hexsha": "5e0f8a4fe673b1ad9cd5c0bc8dedbef29e27fa1b", "size": 5883, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Generic_1_state_deterministic.jl", "max_stars_repo_name": "azev77/Solve_Generic_HJB_KFE", "max_stars_repo_head_hexsha": "3f43d5843e146c2a5d313e389edf80f99a98b426", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-08-02T00:16:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T05:11:39.000Z", "max_issues_repo_path": "Generic_1_state_deterministic.jl", "max_issues_repo_name": "azev77/Solve_Generic_HJB_KFE", "max_issues_repo_head_hexsha": "3f43d5843e146c2a5d313e389edf80f99a98b426", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Generic_1_state_deterministic.jl", "max_forks_repo_name": "azev77/Solve_Generic_HJB_KFE", "max_forks_repo_head_hexsha": "3f43d5843e146c2a5d313e389edf80f99a98b426", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-26T12:39:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-26T12:39:36.000Z", "avg_line_length": 25.5782608696, "max_line_length": 95, "alphanum_fraction": 0.4698283189, "num_tokens": 2503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7642167811365151}}
{"text": "export lorenz63, lorenz96\n\n\"\"\" \n\n    lorenz63(du, u, p, t)\n\nLorenz-63 dynamical model ``u = [x, y, z]`` and ``p = [\\\\sigma, \\\\rho, \\\\mu]``:\n```math\n\\\\frac{dx}{dt} = σ(y-x) \\\\\\\\\n\\\\frac{dy}{dt} = x(ρ-z) - y \\\\\\\\\n\\\\frac{dz}{dt} = xy - βz \\\\\\\\\n```\n\n- [Example Catalog](@ref)\n- [Lorenz system on wikipedia](https://en.wikipedia.org/wiki/Lorenz_system)\n\"\"\"\nfunction lorenz63(du, u, p, t)\n\n    du[1] = p[1] * (u[2] - u[1])\n    du[2] = u[1] * (p[2] - u[3]) - u[2]\n    du[3] = u[1] * u[2] - p[3] * u[3]\n\nend\n\n\"\"\"\n    lorenz96(S, t, F, J)\n\nLorenz-96 dynamical model. For ``i=1,...,N``:\n\n```math\n\\\\frac{dx_i}{dt} = (x_{i+1}-x_{i-2})x_{i-1} - x_i + F\n```\n\nwhere it is assumed that ``x_{-1}=x_{N-1},x_0=x_N`` and ``x_{N+1}=x_1``. \nHere ``x_i`` is the state of the system and ``F`` is a forcing constant. \n\n- [Lorenz 96 model on wikipedia](https://en.wikipedia.org/wiki/Lorenz_96_model)\n\"\"\"\nfunction lorenz96(dx, x, p, t)\n    F = p[1]\n    N = Int64(p[2])\n    # 3 edge cases\n    dx[1] = (x[2] - x[N-1]) * x[N] - x[1] + F\n    dx[2] = (x[3] - x[N]) * x[1] - x[2] + F\n    dx[N] = (x[1] - x[N-2]) * x[N-1] - x[N] + F\n    # then the general case\n    for n = 3:(N-1)\n        dx[n] = (x[n+1] - x[n-2]) * x[n-1] - x[n] + F\n    end\nend\n", "meta": {"hexsha": "42074f2d6379ab4fcf67b009f479c5cb8cf8e8f3", "size": 1212, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models.jl", "max_stars_repo_name": "pnavaro/AnalogDataAssimilation.jl", "max_stars_repo_head_hexsha": "aed4be59c5e7e25f81546c8b8f7ad84a770a1265", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2022-01-05T21:17:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T21:18:17.000Z", "max_issues_repo_path": "src/models.jl", "max_issues_repo_name": "pnavaro/AnalogDataAssimilation.jl", "max_issues_repo_head_hexsha": "aed4be59c5e7e25f81546c8b8f7ad84a770a1265", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models.jl", "max_forks_repo_name": "pnavaro/AnalogDataAssimilation.jl", "max_forks_repo_head_hexsha": "aed4be59c5e7e25f81546c8b8f7ad84a770a1265", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7647058824, "max_line_length": 79, "alphanum_fraction": 0.4925742574, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7642167796977158}}
{"text": "using Plots\nusing BenchmarkTools\n\nfunction vfsolve(vnew, kgrid, tolerance, imax)\n    α = 0.37\n    δ = 0.1\n    β = 0.95\n    σ = 1.5\n\n    v = vnew .+ 2*tolerance\n    cartesianindex = Array{CartesianIndex{2}, length(v)}\n    i = 1\n    \n    c = kgrid.^α + (1-δ)*kgrid .- kgrid'\n    c[c .< 0] .= 0\n    u = (c .^ (1-σ) .- 1) ./ (1-σ)\n    u[kgrid.^α + (1-δ)*kgrid .- kgrid' .< 0] .= -Inf\n\n    while maximum(abs.(v - vnew)) > tolerance && i <= imax\n        v = vnew;\n        \n        (vnew, cartesianindex) = findmax(u .+ β*v', dims = 2);\n        i += 1;\n    end\n    kprimeindex = getindex.(cartesianindex, 2)\n    return (v = vnew, kprime = kgrid[kprimeindex], kprimeindex = kprimeindex)\nend\n\n\nkupper = 5\nklower = 0.05\nn = 1000\nkgrid = collect(range(klower, stop = kupper, length = n))\n(v, kprime, kprimeindex) = vfsolve(zeros(n), kgrid, 0.001, 1000);\n\nplot(kgrid, kprime, label = \"k'\")\n\n\nfunction policy(x)\n    e=getindex(findall(kgrid .== x),1)\n    return kprime[e]  \nend \n\nT = 100\nkpath = zeros(T)\nk = kgrid[92]\nfor i in 1:T\n    k = policy(k)\n    kpath[i] = k\nend \ntime = collect(range(1, T, length = T))\nplot(time, kpath, label = \"kpath\")\n\n\n\n# Check k bounds, stepsize, tolerance, imax\nfindall(kprime .== maximum(kgrid))\nany(kprime .== minimum(kgrid))\n\n\n\n\nfunction vfsolve1(vnew, kgrid, imax)\n    α = 1.5\n    δ = 0.1\n    β = 0.95\n    σ = 1.5\n\n    cartesianindex = Array{CartesianIndex{2}, length(v)}\n    i = 1\n    \n    c = kgrid.^α + (1-δ)*kgrid .- kgrid'\n    c[c .< 0] .= 0\n    u = (c .^ (1-σ) .- 1) ./ (1-σ)\n    u[kgrid.^α + (1-δ)*kgrid .- kgrid' .< 0] .= -Inf\n\n    while i <= imax\n\n        (vnew, cartesianindex) = findmax(u .+ β*vnew', dims = 2);\n        i += 1;\n\n    end\n    kprimeindex = getindex.(cartesianindex, 2)\n    return (v = vnew, kprime = kgrid[kprimeindex], kprimeindex = kprimeindex)\nend\n\n(v1, kprime1, kprimeindex1) = vfsolve1(zeros(n), kgrid, 1);\n(v5, kprime5, kprimeindex5) = vfsolve1(zeros(n), kgrid, 5);\n(v10, kprime10, kprimeindex10) = vfsolve1(zeros(n), kgrid, 10);\nscatter(kgrid, v1, label = \"v1\")\nscatter(kgrid, v5, label = \"v5\")\nscatter(kgrid, v10, label = \"v10\")\n\n\n\nfunction vfsolve2(vnew, kgrid, tolerance, imax)\n    α = 1.5\n    δ = 0.1\n    β = 0.95\n    σ = 0.5\n\n    v = vnew .+ 2*tolerance\n    cartesianindex = Array{CartesianIndex{2}, length(v)}\n    i = 1\n    \n    c = kgrid.^α + (1-δ)*kgrid .- kgrid'\n    c[c .< 0] .= 0\n    u = (c .^ (1-σ) .- 1) ./ (1-σ)\n    u[kgrid.^α + (1-δ)*kgrid .- kgrid' .< 0] .= -Inf\n\n    while maximum(abs.(v - vnew)) > tolerance && i <= imax\n        v = vnew;\n        \n        (vnew, cartesianindex) = findmax(u .+ β*v', dims = 2);\n        i += 1;\n    end\n    kprimeindex = getindex.(cartesianindex, 2)\n    return (v = vnew, kprime = kgrid[kprimeindex], kprimeindex = kprimeindex)\nend\n\n(v, kprime, kprimeindex) = vfsolve2(zeros(n), kgrid, 0.001, 1000);\nscatter(kgrid, v, label = \"v\")\nscatter(kgrid, kprime, label = \"k'\")", "meta": {"hexsha": "a9123e3363cb29bbff90c01141f42dd8ac6518ee", "size": 2873, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Dynamic Programming/DM.jl", "max_stars_repo_name": "paradoxuu/AS-1", "max_stars_repo_head_hexsha": "3d7b03e5806dca30dcd19a7a6acdea9c994bbde7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Dynamic Programming/DM.jl", "max_issues_repo_name": "paradoxuu/AS-1", "max_issues_repo_head_hexsha": "3d7b03e5806dca30dcd19a7a6acdea9c994bbde7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Dynamic Programming/DM.jl", "max_forks_repo_name": "paradoxuu/AS-1", "max_forks_repo_head_hexsha": "3d7b03e5806dca30dcd19a7a6acdea9c994bbde7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3577235772, "max_line_length": 77, "alphanum_fraction": 0.5596937, "num_tokens": 1135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.764216779358251}}
{"text": "\r\n\"\"\"tests if point p1 and p2 are on the same side of line ab\"\"\"\r\nfunction same_side(p1::Vector{U},p2::Vector{U}, a::Vector{U}, b::Vector{U}) where U <: AbstractFloat\r\n    cp1 = cross(b-a, p1-a)\r\n    cp2 = cross(b-a, p2-a)\r\n    dot(cp1, cp2) >= 0\r\nend\r\n\r\n\"\"\" tests if a point p is Left|On|Right of an infinite line ab\r\n- >0 for p left of the line ab\r\n- =0 for p on the line\r\n- <0 for p right of the line\r\n\"\"\"\r\nfunction is_left(p::Vector{U}, a::Vector{U}, b::Vector{U}) where U <: Real\r\n    (b[1]-a[1])*(p[2]-a[2]) - (p[1]-a[1])*(b[2]-a[2])\r\nend\r\n\r\n\"\"\"calculates 2D convec hull for set of points\r\nreturns points which determine the hull and its indices in the input list\r\n\r\nbased on Andrew's Monotone Chain Algorithm (Andrew, 1979), explained here:\r\nhttp://geomalgorithms.com/a10-_hull-1.html\"\"\"\r\nfunction get_hull(P::Vector{Vector{T}}) where T <: Real\r\n    np = length(P)\r\n    # sort indices, first by x then y\r\n    pm = zeros(T,(np, 3))\r\n    [pm[i,:] = [P[i][1], P[i][2], i] for i in 1:np] # to 2d array\r\n    pm = sortrows(pm, by=x->(x[1],x[2]))\r\n    P = [pm[i,1:2] for i in 1:np]\r\n    idx = Int[pm[i,3] for i in 1:np]\r\n    # get indices of points with 1st x min or max and 2nd y min or max\r\n    min_min = 1 # min x, min y\r\n    i = 0 ## initiate so it is known outside loop, arghh...\r\n    for i in 2:np\r\n        P[i][1] != P[1][1] && break\r\n    end\r\n    min_max = i-1\r\n    for i in np-1:-1:1\r\n        P[i][1] != P[np][1] && break\r\n    end\r\n    max_min = i+1\r\n    max_max = np\r\n    # initiate convex hull stack with point indices\r\n    stack = Int[]\r\n\r\n    ## LOWER HULL\r\n    push!(stack, min_min)\r\n    top = 1 # no. of points in stack\r\n    for i in 2:max_min-1 # loop through points with increasing x sequence\r\n        is_left(P[i], P[min_min], P[max_min]) >= 0 && continue # ignore P[i] above or on the lower line\r\n        while top >= 2 # at least two points in stack\r\n            is_left(P[i], P[stack[top-1]], P[stack[top]]) > 0 && break # P[i] in hull\r\n            pop!(stack)\r\n            top -= 1\r\n        end\r\n        push!(stack, i)\r\n        top += 1\r\n    end\r\n    push!(stack, max_min)\r\n    top += 1\r\n\r\n    ## UPPER HULL\r\n    # if  distinct xmax points push max_min point onto stack\r\n    if max_max != max_min\r\n        push!(stack, max_max)\r\n        top += 1\r\n    end\r\n    bot = top # bottom point of upper hull\r\n    for i in np-1:-1:2 # loop through points with decreasing x sequence\r\n        is_left(P[i], P[max_max], P[min_max]) >= 0 && continue # ignore P[i] below or on the upper line\r\n        while bot > top # at least two points in upper stack\r\n            is_left(P[i], P[stack[top-1]], P[stack[top]]) > 0 && break # P[i] in hull\r\n            pop!(stack)\r\n            top -= 1\r\n        end\r\n        push!(stack, i)\r\n        top += 1\r\n    end\r\n    push!(stack, min_max)\r\n    top += 1\r\n\r\n    # return points of hull and indices\r\n    P[stack], idx[stack]\r\nend\r\n\r\n\"\"\"calculates bbox coordinates for set of points\r\nreturns the list with coordinates the indices of the points which determine the bbox\"\"\"\r\nfunction get_bbox(P::Vector{Vector{T}}) where T <: Real\r\n    @assert length(P) >= 2\r\n    xmin, xmax, ymin, ymax = Inf, -Inf, Inf, -Inf\r\n    xmini, xmaxi, ymini, ymaxi = 0, 0, 0, 0  # declare indices of points that make up bbox\r\n    i = 0\r\n    @inbounds for p in P\r\n        addp = false\r\n        i += i  # index of point in vector P\r\n        if p[1] < xmin\r\n            xmin = p[1]\r\n            xmini = i\r\n        end\r\n        if p[1] > xmax\r\n            xmax = p[1]\r\n            xmaxi = i\r\n        end\r\n        if p[2] < ymin\r\n            ymin = p[2]\r\n            ymini = i\r\n        end\r\n        if p[2] > ymax\r\n            ymax = p[2]\r\n            ymaxi = p\r\n        end\r\n    end\r\n\r\n    # return bbox and indices that make up bbox\r\n    [xmin,xmax,ymin,ymax], [xmini, xmaxi, ymini, ymaxi]\r\nend\r\n\r\nfunction triangle_area(a::Vector{U}, b::Vector{U}, c::Vector{U}) where U <: AbstractFloat\r\n    abs(a[1]*(b[2]-c[2]) + b[1]*(c[2]-a[2]) + c[1]*(a[2]-b[2])) / 2.\r\nend\r\n\r\n\"\"\"check if point p [x,y] in triangle made out of points a,b,c\"\"\"\r\nfunction in_triangle(p::Vector{U}, a::Vector{U},b::Vector{U},c::Vector{U}) where U <: AbstractFloat\r\n    p,a,b,c = [[x[1],x[2],0.] for x in [p,a,b,c]]\r\n    same_side(p,a, b,c) && same_side(p,b, a,c) && same_side(p,c, a,b)\r\nend\r\n\r\n\"\"\"check if point (x,y) in traingle made out of points vector\"\"\"\r\nfunction in_triangle(x::AbstractFloat, y::AbstractFloat, points::Vector{Vector{U}}) where U <: AbstractFloat\r\n    length(points)\r\n    npoints != 3 && warn(\"more than three points in list, check based on first three points only\")\r\n    a,b,c = points[1], points[2], points[3]\r\n    xypoint_in_triangle([x, y], a, b,c)\r\nend\r\n\r\n\"\"\"check if point (x,y) in bbox\"\"\"\r\nfunction in_bbox(x::AbstractFloat, y::AbstractFloat, points::Vector{Vector{U}}) where U <: AbstractFloat\r\n    xmin,xmax,ymin,ymax = get_bbox(points)[1]\r\n    xmin <= x <= xmax && ymin <= y <= ymax\r\nend\r\n\r\n\r\n\"\"\"check if point in hull of all points based on hull computation\"\"\"\r\nfunction in_hull(x::Real, y::Real, points::Vector{Vector{U}}) where U <: Real\r\n    npoints = length(points)\r\n    @assert npoints >= 3 [\"point vector should contain at least three points\"]\r\n    push!(points, [x,y])\r\n    p_hull, idx_hull = get_hull(points)\r\n    !in(npoints+1, idx_hull)\r\nend\r\n", "meta": {"hexsha": "ca5fa8823a7fcafd9389902021abc273a3c95a8a", "size": 5272, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "modules/GridOperations/src/utils.jl", "max_stars_repo_name": "Deltares/als2dtm", "max_stars_repo_head_hexsha": "a1e70318b2dbb359150b69ab1a55ac3834be57a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-06-04T05:21:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T06:46:30.000Z", "max_issues_repo_path": "modules/GridOperations/src/utils.jl", "max_issues_repo_name": "Deltares/als2dtm", "max_issues_repo_head_hexsha": "a1e70318b2dbb359150b69ab1a55ac3834be57a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/GridOperations/src/utils.jl", "max_forks_repo_name": "Deltares/als2dtm", "max_forks_repo_head_hexsha": "a1e70318b2dbb359150b69ab1a55ac3834be57a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9139072848, "max_line_length": 109, "alphanum_fraction": 0.5669575114, "num_tokens": 1671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7641758055817454}}
{"text": "export Companion\n\nimmutable Companion{T} <: AbstractArray{T, 2}\n    c :: Vector{T}\nend\n#From polynomial\n\nusing Polynomials\n#Generate companion matrix from a polynomial\n\nfunction Companion(P::Poly)\n   n = length(P)\n   c = Array(Number,n-1)\n   d=P.a[n]\n   for i=1:n-1\n       c[i]=P.a[i]/d\n   end\n   Companion(c)   \nend\n\n#Basic property computations\nsize(C::Companion, r::Int) = (r==1 || r==2) ? length(C.c) : \n    throw(ArgumentError(\"Companion is of rank 2\"))\n\nfunction size(C::Companion)\n    n = length(C.c)\n    n, n\nend\n\n#XXX Inefficient but works\ngetindex(C::Companion, i, j) = getindex(full(C), i, j)\nisassigned(C::Companion, i, j) = isassigned(full(C), i, j)\n\nfunction full{T}(C::Companion{T})\n    M = zeros(T, size(C)...)\n    M[:,end]=-C.c\n    for i=1:size(C,1)-1\n    \tM[i+1, i] = one(T)\n\tend\n    M\nend\n\n#Linear algebra stuff\nfunction A_mul_B!{T}(C::Companion{T}, b::Vector{T})\n\tx = b[end]\n\ty = -C.c[1]*x\n\tb[2:end] = b[1:end-1]-C.c[2:end]*x\n\tb[1] = y\n    b\nend\n*{T}(C::Companion{T}, b::Vector{T}) = A_mul_B!(C, copy(b))\n\nfunction A_mul_B!{T}(A::Matrix{T}, C::Companion{T})\n\tv = Array(T, size(A,1))\n\tfor i=1:size(A,1)\n\t\tv[i] =(A[i,:]*-C.c)[1]\n\tend\n\tfor i=1:size(A,1), j=1:size(A,2)-1\n\t\tA[i,j] = A[i,j+1]\n\tend\n\tA[:,end] = v\n\tA\nend\n*{T}(A::Matrix{T}, C::Companion{T}) = A_mul_B!(copy(A), C)\n\nfunction inv{T}(C::Companion{T})\n\tM = zeros(T, size(C)...)\n    for i=1:size(C,1)-1\n    \tM[i, i+1] = one(T)\n\tend\n\td = M[end, 1] = -one(T)/C.c[1]\n\tM[1:end-1, 1] = d*C.c[2:end]\n    M\nend\n", "meta": {"hexsha": "866b23cdfadfe0bc87723434bc6ec331f208cd8b", "size": 1478, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/companion.jl", "max_stars_repo_name": "JuliaPackageMirrors/SpecialMatrices.jl", "max_stars_repo_head_hexsha": "726b43fd2a968ef340ed89234f3ef3439f64fdb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/companion.jl", "max_issues_repo_name": "JuliaPackageMirrors/SpecialMatrices.jl", "max_issues_repo_head_hexsha": "726b43fd2a968ef340ed89234f3ef3439f64fdb6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/companion.jl", "max_forks_repo_name": "JuliaPackageMirrors/SpecialMatrices.jl", "max_forks_repo_head_hexsha": "726b43fd2a968ef340ed89234f3ef3439f64fdb6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7066666667, "max_line_length": 60, "alphanum_fraction": 0.5737483085, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7641758047461212}}
{"text": "\"\"\"\n    mat_C1(q,N)\n\nGenerate the matrix corresponding to even, π-periodic solutions to the\nangular Mathieu equation.\n\n* `q`: real parameter of Mathieu’s equation\n* `N`: truncated matrix dimension (matrix is N×N)\n\"\"\"\nmat_C1(q::Number,N::Integer) = mat_C1(blasfloat(q),N)\nfunction mat_C1(q::T,N::Integer) where T<:BlasReal\n    dd = [T(2k)^2 for k = 0:N-1]\n    du = fill(q,N-1)\n    du[1] *= √2\n    return SymTridiagonal(dd,du)\nend\n\n\"\"\"\n    mat_C2(q,N)\n\nGenerate the matrix corresponding to even, 2π-periodic (π-antiperiodic)\nsolutions to the angular Mathieu equation.\n\n* `q`: real parameter of Mathieu’s equation\n* `N`: truncated matrix dimension (matrix is N×N)\n\"\"\"\nmat_C2(q::Number,N::Integer) = mat_C2(blasfloat(q),N)\nfunction mat_C2(q::T,N::Integer) where T<:BlasReal\n    dd = [T(2k+1)^2 for k = 0:N-1]\n    dd[1] += q\n    du = fill(q,N-1)\n    return SymTridiagonal(dd,du)\nend\n\n\"\"\"\n    mat_C3(q,N)\n\nGenerate the matrix corresponding to odd, 2π-periodic (π-antiperiodic)\nsolutions to the angular Mathieu equation.\n\n* `q`: real parameter of Mathieu’s equation\n* `N`: truncated matrix dimension (matrix is N×N)\n\"\"\"\nmat_C3(q::Number,N::Integer) = mat_C3(blasfloat(q),N)\nfunction mat_C3(q::T,N::Integer) where T<:BlasReal\n    dd = [T(2k+1)^2 for k = 0:N-1]\n    dd[1] -= q\n    du = fill(q,N-1)\n    return SymTridiagonal(dd,du)\nend\n\n\"\"\"\n    mat_C4(q,N)\n\nGenerate the matrix corresponding to odd, π-periodic solutions to the\nangular Mathieu equation.\n\n* `q`: real parameter of Mathieu’s equation\n* `N`: truncated matrix dimension (matrix is N×N)\n\"\"\"\nmat_C4(q::Number,N::Integer) = mat_C4(blasfloat(q),N)\nfunction mat_C4(q::T,N::Integer) where T<:BlasReal\n    dd = [T(2k+2)^2 for k = 0:N-1]\n    du = fill(q,N-1)\n    return SymTridiagonal(dd,du)\nend\n", "meta": {"hexsha": "2fc9eb7a7ef8f22e1b6f45253420a4fa609ee6ce", "size": 1741, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/integerorder_mat.jl", "max_stars_repo_name": "jebej/Mathieu.jl", "max_stars_repo_head_hexsha": "613825b54e108c7da209c82eb43349d76aec3257", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-08-05T13:47:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-09T23:19:28.000Z", "max_issues_repo_path": "src/integerorder_mat.jl", "max_issues_repo_name": "jebej/Mathieu.jl", "max_issues_repo_head_hexsha": "613825b54e108c7da209c82eb43349d76aec3257", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-12-12T19:32:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-12T19:32:52.000Z", "max_forks_repo_path": "src/integerorder_mat.jl", "max_forks_repo_name": "jebej/Mathieu.jl", "max_forks_repo_head_hexsha": "613825b54e108c7da209c82eb43349d76aec3257", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9850746269, "max_line_length": 71, "alphanum_fraction": 0.6691556577, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305638, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7641757998609942}}
{"text": "@parallel function diffusion3D_step!(T2, T, Ci, lam, dt, dx, dy, dz)\n    @inn(T2) = @inn(T) + dt*(lam*@inn(Ci)*(@d2_xi(T)/dx^2 + @d2_yi(T)/dy^2 + @d2_zi(T)/dz^2));\n    return\nend\n\nfunction diffusion3D()\n# Physics\nlam        = 1.0;                                        # Thermal conductivity\ncp_min     = 1.0;                                        # Minimal heat capacity\nlx, ly, lz = 10.0, 10.0, 10.0;                           # Length of computational domain in dimension x, y and z\n\n# Numerics\nnx, ny, nz = 8, 8, 8;                              # Number of gridpoints in dimensions x, y and z\nnt         = 3;                                          # Number of time steps\ndx         = lx/(nx-1);                                  # Space step in x-dimension\ndy         = ly/(ny-1);                                  # Space step in y-dimension\ndz         = lz/(nz-1);                                  # Space step in z-dimension\n\n# Array initializations\nT   = @zeros(nx, ny, nz);\nT2  = @zeros(nx, ny, nz);\nCi  = @zeros(nx, ny, nz);\n\n# Initial conditions (heat capacity and temperature with two Gaussian anomalies each)\nCi .= 1.0./( cp_min .+ Data.Array([5*exp(-(((ix-1)*dx-lx/1.5))^2-(((iy-1)*dy-ly/2))^2-(((iz-1)*dz-lz/1.5))^2) +\n                                   5*exp(-(((ix-1)*dx-lx/3.0))^2-(((iy-1)*dy-ly/2))^2-(((iz-1)*dz-lz/1.5))^2) for ix=1:size(T,1), iy=1:size(T,2), iz=1:size(T,3)]) )\nT  .= Data.Array([100*exp(-(((ix-1)*dx-lx/2)/2)^2-(((iy-1)*dy-ly/2)/2)^2-(((iz-1)*dz-lz/3.0)/2)^2) +\n                   50*exp(-(((ix-1)*dx-lx/2)/2)^2-(((iy-1)*dy-ly/2)/2)^2-(((iz-1)*dz-lz/1.5)/2)^2) for ix=1:size(T,1), iy=1:size(T,2), iz=1:size(T,3)])\nT2 .= T;                                                 # Assign also T2 to get correct boundary conditions.\n\n# Time loop\ndt = min(dx^2,dy^2,dz^2)*cp_min/lam/8.1;                 # Time step for the 3D Heat diffusion\nfor it = 1:nt\n    @parallel diffusion3D_step!(T2, T, Ci, lam, dt, dx, dy, dz);\n    T, T2 = T2, T;\nend\n\nreturn true\nend\n", "meta": {"hexsha": "ab82547eea3dd1b3d1857f924894380ff38dab16", "size": 1991, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_projects/shared/diffusion3D.jl", "max_stars_repo_name": "albert-de-montserrat/ParallelStencil.jl", "max_stars_repo_head_hexsha": "63f9416eee94d050a67fa9065820ae26bef60728", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 171, "max_stars_repo_stars_event_min_datetime": "2020-12-22T09:39:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T21:57:03.000Z", "max_issues_repo_path": "test/test_projects/shared/diffusion3D.jl", "max_issues_repo_name": "boriskaus/ParallelStencil.jl", "max_issues_repo_head_hexsha": "a790e954e99f5b558a8022bf850e685f780cbd18", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2021-01-18T15:26:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:33:34.000Z", "max_forks_repo_path": "test/test_projects/shared/diffusion3D.jl", "max_forks_repo_name": "boriskaus/ParallelStencil.jl", "max_forks_repo_head_hexsha": "a790e954e99f5b558a8022bf850e685f780cbd18", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2020-12-23T20:37:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T19:41:52.000Z", "avg_line_length": 49.775, "max_line_length": 164, "alphanum_fraction": 0.4671019588, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.764175798254055}}
{"text": "import Random: GLOBAL_RNG\n\n\"\"\"Random number generator for Float32 in [0,1) that samples from \n42*2^23 float32s in [0,1) compared to 2^23 for rand(Float32).\"\"\" \nfunction randfloat(rng::Random.AbstractRNG,::Type{Float32})\n    # create exponent bits in 0000_0000 to 0111_1110\n    # at following chances\n    # e=01111110 at 50.0% for [0.5,1.0)\n    # e=01111101 at 25.0% for [0.25,0.5)\n    # e=01111100 at 12.5% for [0.125,0.25)\n    # ...\n    ui = rand(rng,UInt64)\n\n    # count leading zeros of random UInt64\n    # 0 leading zeros at 50% chance\n    # 1 leading zero at 25% chance\n    # 2 leading zeros at 12.5% chance etc.\n    # then convert leading zeros to exponent bits of Float32\n    lz = leading_zeros(ui)\n    e = ((126 - lz) % UInt32) << 23\n\n    # for 64 leading zeros the smallest float32 that can be created is 2.7105054f-20\n    # use last 23 bits for signficand, only when they are not part of the leading zeros\n    # to sample from all floats in 2.7105054f-20 to prevfloat(1f0)\n    ui = lz > 40 ? rand(rng,UInt64) : ui\n\n    # combine exponent and signficand\n    return reinterpret(Float32,e | ((ui % UInt32) & 0x007f_ffff))\nend\n\n\"\"\"Random number generator for Float64 in [0,1) that samples from \n64*2^52 floats compared to 2^52 for rand(Float64).\"\"\" \nfunction randfloat(rng::Random.AbstractRNG,::Type{Float64})\n    # create exponent bits in 000_0000_0000 to 011_1111_1110\n    # at following chances\n    # e=01111111110 at 50.0% for [0.5,1.0)\n    # e=01111111101 at 25.0% for [0.25,0.5)\n    # e=01111111100 at 12.5% for [0.125,0.25)\n    # ...\n    ui = rand(rng,UInt64)\n\n    # count leading zeros of random UInt64 in several steps\n    # 0 leading zeros at 50% chance\n    # 1 leading zero at 25% chance\n    # 2 leading zeros at 12.5% chance etc.\n    # then convert leading zeros to exponent bits of Float64\n    lz = leading_zeros(ui)\n    e = ((1022 - lz) % UInt64) << 52\n\n    # for 64 leading zeros the smallest float64 that\n    # can be created is 2.710505431213761e-20\n\n    # draw another UInt64 for significant bits in case the leading\n    # zeros reach into the bits that would be used for the significand\n    # (in which case the first signifcant bits would always be zero)\n    ui = lz > 11 ? rand(rng,UInt64) : ui\n    \n    # combine exponent and significand (sign always 0)\n    return reinterpret(Float64,e | (ui & 0x000f_ffff_ffff_ffff))\nend\n\n\"\"\"Random number generator for Float16 in [0,1) that samples from \nall 15360 float16s in that range.\"\"\" \nfunction randfloat(rng::Random.AbstractRNG,::Type{Float16})\n    # create exponent bits in 00000 to 01110\n    # at following chances\n    # e=01110 at 50.0% for [0.5,1.0)\n    # e=01101 at 25.0% for [0.25,0.5)\n    # e=01100 at 12.5% for [0.125,0.25)\n    # ...\n    ui = rand(rng,UInt32) | 0x0002_0000\n    # set 15th bit to 1 to have at most 14 leading zeros.\n\n    # count leading zeros of random UInt64 in several steps\n    # 0 leading zeros at 50% chance\n    # 1 leading zero at 25% chance\n    # 2 leading zeros at 12.5% chance etc.\n    # then convert leading zeros to exponent bits of Float16\n    lz = leading_zeros(ui)\n    e = ((14 - lz) % UInt32) << 10\n    \n    # combine exponent and significand (sign always 0)\n    return reinterpret(Float16,(e | (ui & 0x0000_03ff)) % UInt16)\nend\n\n# use stdlib default RNG as a default here too\nrandfloat(::Type{T}=Float64) where {T<:Base.IEEEFloat} = randfloat(GLOBAL_RNG,T)\nrandfloat(rng::Random.AbstractRNG) = randfloat(rng,Float64)\n\n# randfloat for arrays - in-place\nfunction randfloat!(rng::Random.AbstractRNG, A::AbstractArray{T}) where T\n    for i in eachindex(A)\n        @inbounds A[i] = randfloat(rng, T)\n    end\n    A\nend\n\n# randfloat for arrays with memory allocation\nrandfloat(rng::Random.AbstractRNG, ::Type{T}, dims::Integer...) where {T<:Base.IEEEFloat} = randfloat!(rng, Array{T}(undef,dims))\nrandfloat(rng::Random.AbstractRNG,            dims::Integer...)                           = randfloat!(rng, Array{Float64}(undef,dims))\nrandfloat(::Type{T}, dims::Integer...) where {T<:Base.IEEEFloat} = randfloat!(GLOBAL_RNG, Array{T}(undef,dims))\nrandfloat(           dims::Integer...)                           = randfloat!(GLOBAL_RNG, Array{Float64}(undef,dims))", "meta": {"hexsha": "383d9c4ed27ae4a4a79b194daa9737e35cb8f824", "size": 4167, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/randfloat.jl", "max_stars_repo_name": "DhairyaLGandhi/RandomNumbers.jl", "max_stars_repo_head_hexsha": "8a3d9dd0b713abde9c3b7a7987c684888103d887", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2017-02-19T21:32:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T22:21:47.000Z", "max_issues_repo_path": "src/randfloat.jl", "max_issues_repo_name": "DhairyaLGandhi/RandomNumbers.jl", "max_issues_repo_head_hexsha": "8a3d9dd0b713abde9c3b7a7987c684888103d887", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2017-02-17T23:28:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-13T15:04:15.000Z", "max_forks_repo_path": "src/randfloat.jl", "max_forks_repo_name": "DhairyaLGandhi/RandomNumbers.jl", "max_forks_repo_head_hexsha": "8a3d9dd0b713abde9c3b7a7987c684888103d887", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2017-02-17T21:13:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-25T13:49:12.000Z", "avg_line_length": 40.8529411765, "max_line_length": 135, "alphanum_fraction": 0.6657067435, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7641757902193588}}
{"text": "# This file is part of GenericSchur.jl, released under the MIT \"Expat\" license\n\n# The method in this file is derived from LAPACK's zlacon.\n# LAPACK is released under a BSD license, and is\n# Copyright:\n# Univ. of Tennessee\n# Univ. of California Berkeley\n# Univ. of Colorado Denver\n# NAG Ltd.\n\n\n# Hager's one-norm estimator, with modifications by N.J. Higham\n\"\"\"\n    norm1est!(applyA!,applyAH!,y::Vector) => γ\n\nEstimate the 1-norm of a linear operator `A` expressed as functions which\napply `A` and `adjoint(A)` to a vector such as `y`.\n\ncf. N.J. Higham, SIAM J. Sci. Stat. Comp. 11, 804 (1990)\n\"\"\"\nfunction norm1est!(applyA!, applyAH!, y::AbstractVector{Ty}; maxiter=5) where Ty\n    n = length(y)\n    x = fill(one(Ty)/n,n)\n    y .= zero(Ty)\n    applyA!(x)\n    (n == 1) && return abs(x[1])\n    γ = norm(x,1)\n    tiny = safemin(real(Ty))\n    for i=1:n\n        absxi = abs(x[i])\n        if absxi > tiny\n            x[i] /= absxi\n        else\n            x[i] = one(Ty)\n        end\n    end\n    applyAH!(x)\n    ax0,j0 = _findamax(x)\n    for iter = 1:maxiter\n        x .= zero(Ty)\n        x[j0] = one(Ty)\n        applyA!(x)\n        y .= x\n        oldγ = γ\n        γ = norm(y,1)\n        if γ <= oldγ\n            break\n        end\n        for i=1:n\n            absxi = abs(x[i])\n            if absxi > tiny\n                x[i] /= absxi\n            else\n                x[i] = one(Ty)\n            end\n        end\n        applyAH!(x)\n        jlast = j0\n        ax0, j0 = _findamax(x)\n        if abs(x[jlast]) == ax0\n            break\n        end\n    end\n    # alternative estimate for tricky cases (see Higham 1990)\n    v = x # reuse workspace\n    isign = 1\n    for i in 1:n\n        v[i] = isign * (1+(i-1)/(n-1))\n        isign = -isign\n    end\n    applyA!(v)\n    t = 2*norm(v,1) / (3*n)\n    return max(t,γ)\nend\n\nfunction _findamax(x::AbstractVector{T}) where T\n    ax0 = abs(x[1])\n    i0 = 1\n    for i=2:length(x)\n        ax = abs(x[i])\n        if ax > ax0\n            ax0 = ax\n            i0 = i\n        end\n    end\n    return ax0,i0\nend\n\nfunction _findamax(x::AbstractVector{T}) where T <: Complex\n    ax0 = abs2(x[1])\n    i0 = 1\n    for i=2:length(x)\n        ax = abs2(x[i])\n        if ax > ax0\n            ax0 = ax\n            i0 = i\n        end\n    end\n    return sqrt(ax0),i0\nend\n", "meta": {"hexsha": "bbe2963808608d243f76edcac885139b29226d89", "size": 2277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/norm1est.jl", "max_stars_repo_name": "thorek1/GenericSchur.jl", "max_stars_repo_head_hexsha": "77b4925be2e97b4852f1d569491c08a3090afe52", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-11-04T21:02:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T13:21:37.000Z", "max_issues_repo_path": "src/norm1est.jl", "max_issues_repo_name": "thorek1/GenericSchur.jl", "max_issues_repo_head_hexsha": "77b4925be2e97b4852f1d569491c08a3090afe52", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-04-24T17:33:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T02:05:29.000Z", "max_forks_repo_path": "src/norm1est.jl", "max_forks_repo_name": "thorek1/GenericSchur.jl", "max_forks_repo_head_hexsha": "77b4925be2e97b4852f1d569491c08a3090afe52", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-09-24T10:04:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:47:12.000Z", "avg_line_length": 22.5445544554, "max_line_length": 80, "alphanum_fraction": 0.5063680281, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.8459424431344438, "lm_q1q2_score": 0.7641349124928292}}
{"text": "using Revise\nusing Basins\nusing Plots\nusing DynamicalSystems\nusing DifferentialEquations\n\n#\n#\n# ω=1.\n# F = 0.2\n# ds =Systems.duffing([0.1, 0.25]; ω = ω, f = F, d = 0.15, β = -1)\n# integ_df  = integrator(ds; alg=Tsit5(),  reltol=1e-8, save_everystep=false)\n# xg = range(-2.2,2.2,length=150)\n# yg = range(-2.2,2.2,length=150)\n#\n# @time bsn = Basins.basins_map2D(xg, yg, integ_df; T=2*pi/ω)\n#\n# sa,sb = compute_saddle(integ_df, bsn, [1], [2]; N=1000)\n\n# plot(xg,yg,bsn.basin', seriestype=:heatmap)\n# s = Dataset(sa)\n# plot!(s[:,1],s[:,2],seriestype=:scatter)\n\n# io = open(\"myfile.txt\", \"w\");\n# for v in s\n#     write(io, string(v[1], \" \", v[2], \"; \\n\"));\n# end\n# close(io);\n\n\n\n\n# Forced pendulum\n\n# Equations of motion:\nfunction forced_pendulum!(du, u, p, t)\n    d = p[1]; F = p[2]; omega = p[3]\n    du[1] = u[2]\n    du[2] = -d*u[2] - sin(u[1])+ F*cos(omega*t)\nend\n\n# We have to define a callback to wrap the phase in [-π,π]\nfunction affect!(integrator)\n    if integrator.u[1] < 0\n        integrator.u[1] += 2*π\n    else\n        integrator.u[1] -= 2*π\n    end\nend\n\ncondition(u,t,integrator) = (integrator.u[1] < -π  || integrator.u[1] > π)\n\ncb = DiscreteCallback(condition,affect!)\n\n#d, F ,w\nF = 1.66\nω = 1.\nd=0.2\np=[d, F, ω]\n#p=[0.15, 0.2, 0.1]\ndf = ODEProblem(forced_pendulum!,rand(2),(0.0,20.0), p)\ninteg_df  = init(df, alg=AutoTsit5(Rosenbrock23()); reltol=1e-9, abstol=1e-9, save_everystep=false, callback=cb)\n\nxres=200\nyres=200\n\n# range for forced pend\nxg = range(-pi,pi,length=xres)\nyg = range(-2.,4.,length=yres)\n\n# compute basin\n@time bsn = Basins.basins_map2D(xg, yg, integ_df; T=2*pi/ω)\n\nNa = length(unique(bsn.basin))\n\nsa,sb = compute_saddle(integ_df, bsn, [1], [2,3]; N=1000)\n\nplot(xg,yg,bsn.basin', seriestype=:heatmap)\ns = Dataset(sa)\nplot!(s[:,1],s[:,2],seriestype=:scatter, markercolor=:blue)\n", "meta": {"hexsha": "43ebd21ab9bdcd10f7a99a092c06fa25bc35cee6", "size": 1807, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/examples/tst_duffing_straddle.jl", "max_stars_repo_name": "awage/Basins.jl", "max_stars_repo_head_hexsha": "765a232b0568a257a845ee95a14c0cf2776046a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-27T14:46:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T08:39:36.000Z", "max_issues_repo_path": "src/examples/tst_duffing_straddle.jl", "max_issues_repo_name": "awage/Basins.jl", "max_issues_repo_head_hexsha": "765a232b0568a257a845ee95a14c0cf2776046a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-12T15:47:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-14T13:47:35.000Z", "max_forks_repo_path": "src/examples/tst_duffing_straddle.jl", "max_forks_repo_name": "awage/Basins.jl", "max_forks_repo_head_hexsha": "765a232b0568a257a845ee95a14c0cf2776046a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3086419753, "max_line_length": 112, "alphanum_fraction": 0.6209186497, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7641349067821966}}
{"text": "#=\njinc.jl\n=#\n\nexport jinc\n\nusing SpecialFunctions: besselj1\n\n\n\"\"\"\n    jinc(x)\n\nReturn `jinc(x) = J1(π*x)/(2x)`,\nwhere `J1` is a Bessel function of the first kind.\n\nThe argument `x` must be unitless.\n\nReturn type is `promote_type(typeof(x), Float32)`.\n\"\"\"\nfunction jinc(x::X) where {X <: Real}\n    T = promote_type(X, Float32)\n    if (x == 0) return convert(T, π/4) end\n    y = abs(x)\n    convert(T, besselj1(π*y) / (2*y))\nend\n", "meta": {"hexsha": "d0cf6eaba0fcc0523f5a089cff4e91eb5c7ae4e9", "size": 427, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/jinc.jl", "max_stars_repo_name": "EricCheek3731/ImagePhantoms.jl", "max_stars_repo_head_hexsha": "e9d32d41553d634334c939a34d0fd1174ebd4e0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-08-21T07:57:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T21:25:31.000Z", "max_issues_repo_path": "src/jinc.jl", "max_issues_repo_name": "EricCheek3731/ImagePhantoms.jl", "max_issues_repo_head_hexsha": "e9d32d41553d634334c939a34d0fd1174ebd4e0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2021-07-16T16:10:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T16:42:07.000Z", "max_forks_repo_path": "src/jinc.jl", "max_forks_repo_name": "EricCheek3731/ImagePhantoms.jl", "max_forks_repo_head_hexsha": "e9d32d41553d634334c939a34d0fd1174ebd4e0d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-01T01:39:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T01:39:08.000Z", "avg_line_length": 16.4230769231, "max_line_length": 50, "alphanum_fraction": 0.6206088993, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7641349010333215}}
{"text": "# https://adventofcode.com/2020/day/13\n\nexample = \"\n939\n7,13,x,x,59,x,31,19\n\"\n\nfunction read_input(string)\n    earliest_timestamp, bus_numbers = split(string, '\\n', keepempty=false)\n    earliest_timestamp = parse(Int, earliest_timestamp)\n    bus_numbers = map(x -> tryparse(Int, x), split(bus_numbers, ','))\n    return earliest_timestamp, bus_numbers\nend\n\n@assert read_input(example) == (939, [7, 13, nothing, nothing, 59, nothing, 31, 19])\n\nfunction closest_arrival(bus_number, timestamp)\n    divisor, reminder = divrem(timestamp, bus_number)\n    if reminder == 0\n        return 0\n    else\n        return bus_number * (divisor + 1) - timestamp\n    end\nend\n\nfunction part1(input)\n    earliest_timestamp, bus_numbers = read_input(input)\n    bus_numbers = convert(Vector{Int}, filter(x -> !isnothing(x), bus_numbers))\n    closest_arrivals = closest_arrival.(bus_numbers, earliest_timestamp)\n    i = argmin(closest_arrivals)\n    return closest_arrivals[i] * bus_numbers[i]\nend\n\n@assert part1(example) == 295\n\n\"\"\"\nSolve Chinese reminder theorem problem using the inverse modulo algorithm\n\nSee:\n* https://en.wikipedia.org/wiki/Chinese_remainder_theorem\n* https://www.geeksforgeeks.org/chinese-remainder-theorem-set-2-implementation/\n* https://rosettacode.org/wiki/Chinese_remainder_theorem\n\"\"\"\nfunction chinese_reminder(modulus, reminder)\n    N = prod(modulus)\n    Ni = div.(N, modulus)\n    i = invmod.(Ni, modulus)\n    return mod(sum(reminder .* Ni .* i), N)\nend\n\n@assert chinese_reminder([3, 4, 5], [2, 3, 1]) == 11\n\nfunction part2(input)\n    _, bus_numbers = read_input(input)\n\n    nonmissing = map(x -> !isnothing(x), bus_numbers)\n    indexes = collect(0:(length(bus_numbers) - 1))\n    indexes = indexes[nonmissing]\n    bus_numbers = bus_numbers[nonmissing]\n    reminders = maximum(indexes) .- indexes\n\n    return chinese_reminder(bus_numbers, reminders) - maximum(reminders)\nend\n\n@assert part2(example) == 1068781\n@assert part2(\"0\\n17,x,13,19\") == 3417\n@assert part2(\"0\\n67,7,59,61\") == 754018\n@assert part2(\"0\\n67,x,7,59,61\") == 779210\n@assert part2(\"0\\n67,7,x,59,61\") == 1261476\n@assert part2(\"0\\n1789,37,47,1889\") == 1202161486\n\ntest = read(\"data/day-13.txt\", String)\nprintln(\"Part 1: $(result1 = part1(test))\")\nprintln(\"Part 2: $(result2 = part2(test))\")\n\n@assert result1 == 4207\n@assert result2 == 725850285300475\n", "meta": {"hexsha": "ed0de44e69f2d7aba9608fd71923676b61089651", "size": 2319, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2020/day-13.jl", "max_stars_repo_name": "twolodzko/advent-of-code", "max_stars_repo_head_hexsha": "8d0e41b20aa9007cad4d99aa5043648e0807d565", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2020/day-13.jl", "max_issues_repo_name": "twolodzko/advent-of-code", "max_issues_repo_head_hexsha": "8d0e41b20aa9007cad4d99aa5043648e0807d565", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/day-13.jl", "max_forks_repo_name": "twolodzko/advent-of-code", "max_forks_repo_head_hexsha": "8d0e41b20aa9007cad4d99aa5043648e0807d565", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7307692308, "max_line_length": 84, "alphanum_fraction": 0.7028891764, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7641348997272502}}
{"text": "# Symmetric Toeplitz solver\nfunction durbin!{T<:BlasReal}(r::AbstractVector{T}, y::AbstractVector{T})\n    n = length(r)\n    n <= length(y) || throw(DimensionMismatch(\"Auxiliary vector cannot be shorter than data vector\"))\n    y[1] = -r[1]\n    β = one(T)\n    α = -r[1]\n    for k = 1:n-1\n        β *= one(T) - α*α\n        α = -r[k+1]\n        for j = 1:k\n            α -= r[k-j+1]*y[j]\n        end\n        α /= β\n        for j = 1:div(k,2)\n            tmp = y[j]\n            y[j] += α*y[k-j+1]\n            y[k-j+1] += α*tmp\n        end\n        if isodd(k) y[div(k,2)+1] *= one(T) + α end\n        y[k+1] = α\n    end\n    return y\nend\ndurbin{T<:BlasReal}(r::AbstractVector{T}) = durbin!(r, zeros(T, length(r)))\n\nfunction levinson!{T<:BlasReal}(r::AbstractVector{T}, b::AbstractVector{T}, x::AbstractVector{T})\n    n = length(b)\n    n == length(r) || throw(DimensionMismatch(\"Vectors must have same length\"))\n    n <= length(x) || throw(DimensionMismatch(\"Auxiliary vector cannot be shorter than data vector\"))\n    x[1] = b[1]\n    b[1] = -r[2]/r[1]\n    β = one(T)\n    α = -r[2]/r[1]\n    for k = 1:n-1\n        β *= one(T) - α*α\n        μ = b[k+1]\n        for j = 2:k+1\n            μ -= r[j]/r[1]*x[k-j+2]\n        end\n        μ /= β\n        for j = 1:k\n            x[j] += μ*b[k-j+1]\n        end\n        x[k+1] = μ\n        if k < n - 1\n            α = -r[k+2]\n            for j = 2:k+1\n                α -= r[j]*b[k-j+2]\n            end\n            α /= β*r[1]\n            for j = 1:div(k,2)\n                tmp = b[j]\n                b[j] += α*b[k-j+1]\n                b[k-j+1] += α*tmp\n            end\n            if isodd(k) b[div(k,2)+1] *= one(T) + α end\n            b[k+1] = α\n        end\n    end\n    for i = 1:n\n        x[i] /= r[1]\n    end\n    return x\nend\nlevinson{T<:BlasReal}(r::AbstractVector{T}, b::AbstractVector{T}) = levinson!(r, copy(b), zeros(T, length(b)))\n", "meta": {"hexsha": "8e90364addf5e8a6ab5ae59b6b8763915fd03890", "size": 1867, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/toeplitzsolvers.jl", "max_stars_repo_name": "wildart/StatsBase.jl", "max_stars_repo_head_hexsha": "3885542a93d2de71a1102da030c798cd51749481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-12T03:24:25.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-12T03:24:25.000Z", "max_issues_repo_path": "src/toeplitzsolvers.jl", "max_issues_repo_name": "wildart/StatsBase.jl", "max_issues_repo_head_hexsha": "3885542a93d2de71a1102da030c798cd51749481", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/toeplitzsolvers.jl", "max_forks_repo_name": "wildart/StatsBase.jl", "max_forks_repo_head_hexsha": "3885542a93d2de71a1102da030c798cd51749481", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8656716418, "max_line_length": 110, "alphanum_fraction": 0.4370648099, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7641348936067552}}
{"text": "# Functions to create standard graph matrices\n#import Base.eigvals\nexport adjacency, char_poly, laplace, incidence, dist_matrix, eigvals\nusing SparseArrays\n# Adjaceny Matrix\n\n\"\"\"\n`adjacency(G)` returns the adjacency matrix of `G`.\n\nNote: If the vertices can be sorted by `sort`, then the first row of\nthe adjacency matrix corresponds to the first vertex (in order) in `G`\nand so forth. However, if the vertices are not sortable in this way,\nthe mapping between vertices and rows/columns of the matrix is\nunpredictable.\n\"\"\"\nfunction adjacency(G::SimpleGraph)\n    n = NV(G)\n    A = zeros(Int,(n,n))\n\n    # create a table from V to 1:n\n    d = vertex2idx(G)\n\n    for e in G.E\n        i = d[e[1]]\n        j = d[e[2]]\n        A[i,j]=1\n        A[j,i]=1\n    end\n\n    return A\nend\n\n# Laplace matrix\n\n\"\"\"\n`laplace(G)` returns the Laplacian matrix of `G`. This is the\nadjacency matrix minus the (diagonal) degree matrix. See `adjacency`\nto understand how vertices correspond to rows/columns of the resulting\nmatrix.\n\"\"\"\nfunction laplace(G::SimpleGraph)\n    A = adjacency(G)\n    d = collect(sum(A,dims=1))[:]\n    # D = diagm(d) # deprecated version\n    D = Matrix(Diagonal(d))\n    L = D-A\n    return L\nend\n\n# incidence matrix\n\"\"\"\n\n`incidence(G)` returns the vertex-edge incidence matrix of `G`.\n\nNotes:\n\n* The result is a sparse matrix. Wrap in `full` to convert to nonsparse.\n\n* Each column of the matrix has exactly one `+1` and one `-1`. If `G`\nis undirected and an unsigned incidence matrix is desired, use\n`incidence(G,false)`.\n\"\"\"\nfunction incidence(G::SimpleGraph, signed::Bool = true)\n    n = NV(G)\n    m = NE(G)\n    M = spzeros(Int,n,m)\n    d = vertex2idx(G)\n    E = elist(G)\n    a = 1\n    b = signed ? -1 : 1\n\n    idx = 0\n    for e in E\n        i = d[e[1]]\n        j = d[e[2]]\n        idx += 1\n        M[i,idx] = a\n        M[j,idx] = b\n    end\n\n    return M\nend\n\n# Create the n-by-n distance matrix\n\"\"\"\n`dist_matrix(G)` returns a matrix whose `i,j`-entry is the distance\nfrom the `i`th vertex to the `j`th vertex. If there is no `i,j`-path,\nthat entry is `-1`.\n\"\"\"\nfunction dist_matrix(G::AbstractSimpleGraph)\n    if cache_check(G,:dist_matrix)\n      return cache_recall(G,:dist_matrix)\n    end\n    vtcs = vlist(G)\n    n = length(vtcs)\n    dd = dist(G)\n\n    A = zeros(Int,n,n)\n\n    for i = 1:n\n        u = vtcs[i]\n        for j = 1:n\n            v = vtcs[j]\n            A[i,j] = dd[(u,v)]\n        end\n    end\n    cache_save(G,:dist_matrix,A)\n    return A\nend\n\n\"\"\"\n`char_poly(G)` returns the characteristic polynomial of\n`adjacency(G)`. Use `char_poly(G,function)` for other\npossible integer matrix functions such as `laplace`.\n\"\"\"\nfunction char_poly(G::AbstractSimpleGraph, func::Function=adjacency)\n    if cache_check(G,:char_poly) && func==adjacency\n      return cache_recall(G,:char_poly)\n    end\n    evs = eigvals(G,func)\n    P = poly(evs)\n    cs = round.(Int,real(coeffs(P)))\n    P =  Poly(cs)\n    if func==adjacency\n        cache_save(G,:char_poly,P)\n    end\n    return P\nend\n\n\n\"\"\"\n`eigvals(G)` for a `SimpleGraph` returns the eigenvalues of `G`'s\nadjacency matrix. More generally, `eigvals(G,mat)` returns the eigenvalues\nof `mat(G)` where `mat` is a matrix-valued function of `G`. In particular,\none can use `mat(G,laplace)` to find the eigenvalues of `G`'s Laplacian.\n\"\"\"\nfunction LinearAlgebra.eigvals(G::SimpleGraph, mat::Function = adjacency)\n    return eigvals(mat(G))\nend\n", "meta": {"hexsha": "2544315205fcb5a1a919c05d514837018365a9b6", "size": 3385, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simple_matrices.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_stars_repo_head_hexsha": "7faccfcd99dcafb6d8cce600dac01c3722b299f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simple_matrices.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_issues_repo_head_hexsha": "7faccfcd99dcafb6d8cce600dac01c3722b299f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simple_matrices.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_forks_repo_head_hexsha": "7faccfcd99dcafb6d8cce600dac01c3722b299f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1785714286, "max_line_length": 74, "alphanum_fraction": 0.6416543575, "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7640798281456515}}
{"text": "\nusing LinearAlgebra\ninclude(\"approx_inequality.jl\")\n# export ProximableFunction\nexport prox, prox!\n\n# abstract type ProximableFunction end\nexport IndNonnegativeBallL2\n\nstruct IndNonnegativeBallL2{R <: Real} \n    r::R\n    function IndNonnegativeBallL2{R}(r::R) where {R <: Real}\n        if r <= 0\n            error(\"parameter r must be positive\")\n        else\n            new(r)\n        end\n    end\nend\n\nis_convex(f::IndNonnegativeBallL2) = true\nis_set(f::IndNonnegativeBallL2) = true\n\nIndNonnegativeBallL2(r::R=1.0) where {R <: Real} = IndNonnegativeBallL2{R}(r)\n\nfunction (f::IndNonnegativeBallL2)(x::AbstractArray{T}) where {R <: Real, T <: RealOrComplex{R}}\n    if isapprox_le(norm(x), f.r, atol=eps(R), rtol=sqrt(eps(R)))\n        for k in eachindex(x)\n            if x[k] < 0\n                return R(Inf)\n            end\n        end\n        return R(0)\n    end\n    return R(Inf)\nend\n\nfunction prox!(y::AbstractArray{T}, f::IndNonnegativeBallL2, x::AbstractArray{T}, gamma::R=R(1)) where {R <: Real, T <: RealOrComplex{R}}\n    for k in eachindex(x)\n        if x[k] < 0\n            y[k] = R(0)\n        else\n            y[k] = x[k]\n        end\n    end\n    \n    scal = f.r/norm(y)\n    if scal > 1\n        return R(0)\n    end\n    for k in eachindex(y)\n        y[k] = scal*y[k]\n    end\n    return R(0)\nend\n\nfunction prox(f::IndNonnegativeBallL2, x::AbstractArray{T}, gamma::R=R(1)) where {R <: Real, T <: RealOrComplex{R}}\n    y = copy(x)\n    for k in eachindex(x)\n        if x[k] < 0\n            y[k] = R(0)\n        else\n            y[k] = x[k]\n        end\n    end\n    \n    scal = f.r/norm(y)\n    if scal > 1\n        return y, R(0)\n    end\n    for k in eachindex(y)\n        y[k] = scal*y[k]\n    end\n    return y, R(0)\nend\n\nfun_name(f::IndNonnegativeBallL2) = \"indicator of an L2 norm ball and nonnegative orthant\"\nfun_dom(f::IndNonnegativeBallL2) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::IndNonnegativeBallL2) = \"x ↦ 0 if ||x|| ⩽ r & all(0 ⩽ x), +∞ otherwise\"\nfun_params(f::IndNonnegativeBallL2) = \"r = $(f.r)\"\n\nfunction prox_naive(f::IndNonnegativeBallL2, x::AbstractArray{T}, gamma::R=R(1)) where {R <: Real, T <: RealOrComplex{R}}\n    y = copy(x)\n    for k in eachindex(x)\n        if x[k] < 0\n            y[k] = R(0)\n        end\n    end\n    \n    normx = norm(y)\n    if normx > f.r\n        y = (f.r/normx)*y\n    end\n    return y, R(0)\nend\n", "meta": {"hexsha": "c6bafd40c7d451e912e13f6a67e48a1371ac6929", "size": 2361, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utilities/indNonnegativeBallL2.jl", "max_stars_repo_name": "pourya-b/CIAOAlgorithms.jl", "max_stars_repo_head_hexsha": "f01d44b3553c841cf55814cfa2329e4b7bce1258", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utilities/indNonnegativeBallL2.jl", "max_issues_repo_name": "pourya-b/CIAOAlgorithms.jl", "max_issues_repo_head_hexsha": "f01d44b3553c841cf55814cfa2329e4b7bce1258", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utilities/indNonnegativeBallL2.jl", "max_forks_repo_name": "pourya-b/CIAOAlgorithms.jl", "max_forks_repo_head_hexsha": "f01d44b3553c841cf55814cfa2329e4b7bce1258", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.59375, "max_line_length": 137, "alphanum_fraction": 0.5679796696, "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7640798263209142}}
{"text": "#=\nThe cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3).\nIn fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.\n\nFind the smallest cube for which exactly five permutations of its digits are cube.\n=#\ninclude(\"projecteulerutils.jl\")\n\nfunction largest_permutation(i)\n  nd(reverse(sort(reverse(digits(i)))))\nend\n\nfunction calc()\n  i, max_permutations = 1, 5\n  hash = Dict{Int64, Array{Int64}}()  #largest_permutation => [smallest_cube, count]\n  while true\n    current_cube = i ^ 3\n    largest = largest_permutation(current_cube)\n    v = get(hash, largest, [current_cube, 0])\n    count = v[2] + 1\n    hash[largest] = [v[1], count]\n    if count == max_permutations\n      return v[1]\n    end\n    i = i + 1\n  end\nend\n@time println(calc())\n", "meta": {"hexsha": "0d0fe4321c3f2c009e83fcce2ff877c7b69f9daf", "size": 844, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p62.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p62.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p62.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 29.1034482759, "max_line_length": 110, "alphanum_fraction": 0.6954976303, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099069987088004, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7640798197126917}}
{"text": "#\n# Denoise an SPD Example with Cyclic Proximal Point to minimize the\n#\n# L2-TV functional with anisotropic TV\n#\n# where the example is the same data and cost as for SPD_Image_CP_vs_CPPA\n#\n# This example and its data is used for comparison in Section 6.2 of\n#\n# > R. Bergmann, R. Herzog, M. Silva Louzeiro, D. Tenbrinck, J. Vidal Núñez:\n# > _Fenchel Duality Theory and a Primal-Dual Algorithm on Riemannian Manifolds_,\n# > arXiv: [1908.02022](https://arxiv.org/abs/1908.02022)\n#\nusing Manopt, Manifolds\nusing Images, CSV, DataFrames, LinearAlgebra, JLD2\n#\n# Settings\nexperiment_name = \"SPD_Image_CPPA\"\nexport_orig = true # export and render input image\nexport_result = true # export resulting image\nexport_table = true # export a table of data recorded through the iterations\nexport_function_value = true # export the final cost function value for ChambollePock\nasy_render_detail = 4 # resolution in asymptote, a high resolution is e.g. 4\nresults_folder = joinpath(@__DIR__, \"Image_TV\")\n!isdir(results_folder) && mkdir(results_folder)\n\n#\n# Algorithm Parameters\nα = 6.0\nmaxIterations = 4000\n\n#\n# Manifold and Data\nf = artificial_SPD_image2(32)\npixelM = SymmetricPositiveDefinite(3)\nif export_orig\n    orig_filename = joinpath(results_folder, experiment_name * \"-orig.asy\")\n    asymptote_export_SPD(orig_filename; data=f, scaleAxes=(7.5, 7.5, 7.5))\n    render_asymptote(orig_filename; render=asy_render_detail)\nend\n\n#\n# Build Problem for L2-TV & proximal maps\nM = PowerManifold(pixelM, NestedPowerRepresentation(), size(f)...)\nd = length(size(f))\nrep(d) = (d > 1) ? [ones(Int, d)..., d] : d\nfidelity(x) = 1 / 2 * distance(M, x, f)^2\nΛ(x) = forward_logs(M, x) # on T_xN\nprior(x) = norm(norm.(Ref(pixelM), repeat(x, rep(d)...), Λ(x)), 1)\ncost(x) = (1 / α) * fidelity(x) + prior(x)\nproxes = ((λ, x) -> prox_distance(M, λ, f, x, 2), (λ, x) -> prox_TV(M, α * λ, x, 1))\n\nx0 = f\n@time o = cyclic_proximal_point(\n    M,\n    cost,\n    proxes,\n    x0;\n    λ=i -> 4 / i,\n    stopping_criterion=StopAfterIteration(maxIterations),\n    debug=[\n        :Iteration,\n        \" | \",\n        DebugProximalParameter(),\n        \" | \",\n        :Change,\n        \" | \",\n        :Cost,\n        \"\\n\",\n        100,\n        :Stop,\n    ],\n    record=[:Iteration, :Iterate, :Cost],\n    return_options=true,\n)\ny = get_solver_result(o)\nyRec = get_record(o)\n#\n# Results\nif export_result\n    result_filename = joinpath(results_folder, experiment_name * \"-result.asy\")\n    asymptote_export_SPD(result_filename; data=y, scaleAxes=(7.5, 7.5, 7.5))\n    render_asymptote(result_filename; render=asy_render_detail)\nend\nif export_table\n    A = cat([y[1] for y in yRec], [y[3] for y in yRec]; dims=2)\n    table_filename = joinpath(results_folder, experiment_name * \"-recorded-cost.csv\")\n    CSV.write(table_filename, DataFrame(A); writeheader=false)\nend\nif export_function_value\n    fctval_filename = joinpath(results_folder, experiment_name * \"-cost.jld2\")\n    values = Dict(\"cost_function_value\" => last(yRec)[3], \"iterations\" => length(yRec) - 1)\n    save(fctval_filename, values)\nend\n", "meta": {"hexsha": "3adea42a3592d62772ac807e2a1530bb51e4ccd0", "size": 3044, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/CyclicProximalPoint/SPD_Image_CPPA.jl", "max_stars_repo_name": "JuliaTagBot/Manopt.jl", "max_stars_repo_head_hexsha": "940068f79cb1fd82141f0706cfe6c7525aca12b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/CyclicProximalPoint/SPD_Image_CPPA.jl", "max_issues_repo_name": "JuliaTagBot/Manopt.jl", "max_issues_repo_head_hexsha": "940068f79cb1fd82141f0706cfe6c7525aca12b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/CyclicProximalPoint/SPD_Image_CPPA.jl", "max_forks_repo_name": "JuliaTagBot/Manopt.jl", "max_forks_repo_head_hexsha": "940068f79cb1fd82141f0706cfe6c7525aca12b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0421052632, "max_line_length": 91, "alphanum_fraction": 0.688239159, "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7640798165168217}}
{"text": "\n\"\"\"\nProblem 1: \n\nGiven a path given by an input array of commands (direction + integer), \ncompute the final position relative to the start.\n\nProblem 2: \nSame, but changing slightly the rules.\n\n\"\"\"\n\nusing DelimitedFiles\n\n# Read input\nfunction readInput() :: Array{Tuple{String,Int}}\n  data = readdlm(\"./inputs/day2.txt\", ' ', String)\n  data = map(x -> (x[1],parse(Int,x[2])), data[i,:] for i in 1:size(data)[1] )\n  return data\nend\n\n# Converts direction from string to cartesian index.\nfunction toIndex(s::String)\n  if s == \"up\"\n    return CartesianIndex(0,-1)\n  elseif s == \"down\"\n    return CartesianIndex(0,1)\n  elseif s == \"forward\"\n    return CartesianIndex(1,0)\n  else \n    return CartesianIndex(-1,0)\n  end\nend\n\n# Follows a path given by an array of steps (distance + direction). Return final position.\nfunction followPath(path:: Array{Tuple{String,Int}}) :: CartesianIndex{2}\n  pos = CartesianIndex(0,0)\n  for step in path\n    pos += step[2] * toIndex(step[1])\n  end\n  return pos\nend\n\n# Modified version for the second part of the problem. \nfunction followPath2(path:: Array{Tuple{String,Int}}) :: CartesianIndex{2}\n  aim = 0\n  pos = CartesianIndex(0,0)\n  for step in path\n    dir = toIndex(step[1])\n    aim += step[2] * dir[2]\n    pos += CartesianIndex(step[2] * dir[1] ,aim * step[2] * dir[1])\n  end\n  return pos\nend\n\n\npath = readInput()\n\npos = followPath(path)\nprintln(\"Problem 1:\")\nprintln(pos[1]*pos[2])\n\npos = followPath2(path)\nprintln(\"Problem 2:\")\nprintln(pos[1]*pos[2])\n", "meta": {"hexsha": "6d182460a75b9188191540ba548ce4331fbc0b30", "size": 1486, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/day02.jl", "max_stars_repo_name": "JordiManyer/advent-of-code-2021", "max_stars_repo_head_hexsha": "552a888a92263e3374a7f97df61eda02ef95f337", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/day02.jl", "max_issues_repo_name": "JordiManyer/advent-of-code-2021", "max_issues_repo_head_hexsha": "552a888a92263e3374a7f97df61eda02ef95f337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/day02.jl", "max_forks_repo_name": "JordiManyer/advent-of-code-2021", "max_forks_repo_head_hexsha": "552a888a92263e3374a7f97df61eda02ef95f337", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5151515152, "max_line_length": 90, "alphanum_fraction": 0.6729475101, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894576856559, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7640721341143771}}
{"text": "include(\"CG_Convergence_Utilities.jl\")\n\n# ==============================================================================\n# Exact Arithematic error bound.\n# ==============================================================================\n\n\nfunction PerformCGFor(A, b, immitate_exact=true)\n    cgm = ConjGradModified(A, b)\n    if !immitate_exact \n        TurnOffReorthgonalize(cgm)\n    end\n    ResidualNorm = GetResidualNorm(cgm)\n    ResidualNorms = Vector{Float64}()\n    Guesses = Vector{Vector{Float64}}()\n    push!(ResidualNorms, ResidualNorm)\n    while ResidualNorm > 1e-10\n        ResidualNorm = cgm()\n        push!(ResidualNorms, ResidualNorm)\n        push!(Guesses, cgm.x)\n    end\n    return ResidualNorms, Guesses\nend\n\n\n\nfunction Run1()\n    \nreturn end\n    \n\nN = 512\nA = GetUniformPSDMatrix(N)\nb = rand(N)\nResidualNorms, Guesses = PerformCGFor(A, b)\nResidualEnergy = ResRelEnergyNorm(A, b,Guesses)\nk = length(ResidualNorms)\nErrorsBound = [TheoreticalErrorBound(A, idx) for idx in 1: k]\n\nfig1 = plot(log10.(ResidualEnergy), label=\"Relative Energy (exact)\", legend=:bottomleft)\nplot!(fig1, log10.(ErrorsBound), label=\"Theoretical Error Bound\")\ndisplay(fig1)\nSaveFigToCurrentScriptDir(fig1, \"fig1.png\")\n\n# ==============================================================================\n# Floating Points Error Bound.\n# ==============================================================================\n\nA = GetUniformPSDMatrix(N)\nb = rand(N)\nResidualNorms, Guesses = PerformCGFor(A, b, false)\nResidualEnergy = ResRelEnergyNorm(A, b,Guesses)\nk = length(ResidualNorms)\nErrorsBound = [TheoreticalErrorBound(A, idx) for idx in 1: k]\n\nfig2 = plot(log10.(ResidualEnergy), label=\"Relative Energy (floats)\", legend=:bottomleft)\nplot!(fig2, log10.(ErrorsBound), label=\"Theoretical Error Bound(exact)\")\ndisplay(fig2)\nSaveFigToCurrentScriptDir(fig2, \"fig2.png\")\n", "meta": {"hexsha": "1ae77b642c8789b062f4ad0947e8ac9be0e6b933", "size": 1847, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "numerical_experiments/CG_Convergence (Abandoned)/CGConvergence.jl", "max_stars_repo_name": "iluvjava/Subspace_Projection_Method", "max_stars_repo_head_hexsha": "0728d708b18a2f0bca763c1061eb729eb0b79c3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numerical_experiments/CG_Convergence (Abandoned)/CGConvergence.jl", "max_issues_repo_name": "iluvjava/Subspace_Projection_Method", "max_issues_repo_head_hexsha": "0728d708b18a2f0bca763c1061eb729eb0b79c3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical_experiments/CG_Convergence (Abandoned)/CGConvergence.jl", "max_forks_repo_name": "iluvjava/Subspace_Projection_Method", "max_forks_repo_head_hexsha": "0728d708b18a2f0bca763c1061eb729eb0b79c3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7833333333, "max_line_length": 89, "alphanum_fraction": 0.5988088793, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7640721289261893}}
{"text": "\n# ints_trap = map(hs) do h\n#     x = y1:h:y2\n#     -(g(x[1]) + g(x[end]))*h/2.0 + sum(g.(x)*h)\n# end\n\nfunction integration_scheme(x::AbstractVector{T}; scheme::Symbol = :trapezoidal, kws...) where T<:AbstractFloat\n    if length(collect(x)) == 1\n        return [0.]\n    end\n\n    if scheme == :trapezoidal\n        trap_scheme(x; kws...)\n    elseif scheme == :simpson\n        simpson_scheme(x; kws...)\n    else\n        @warn(\"Integration scheme $scheme unknown, will use trapezoidal\")\n        trap_scheme(x; kws...)\n    end\nend\n\nfunction trap_scheme(x::AbstractVector{T}; x0::T = first(x), xn::T = last(x)) where T<:AbstractFloat\n\n    inds = axes(x,1)\n\n    h = (x[inds[2]]-x[inds[1]])\n    σs = similar(x)\n    σs .= h\n\n    σs[inds[1]] -= h/T(2)\n\n    σs[end] -= h/T(2)\n    # accounts for the ends\n    σs[inds[1]] +=   (x[inds[1]] - x0)*(x[inds[2]] - x0 + h)/(2.0h)\n    σs[inds[2]] +=  -(x0 - x[inds[1]])^T(2)/(T(2)*h)\n    σs[end] +=  (xn - x[end])*(xn - x[end-1] + h)/(2h)\n    σs[end-1] += - (xn - x[end])^T(2)/(T(2)*h)\n\n    return σs\nend\n\nfunction simpson_scheme(x::AbstractVector{T}; x0::T = first(x), xn::T = last(x)) where T<:AbstractFloat\n    inds = axes(x,1)\n\n    if iseven(length(inds))\n        @warn(\"Simpson's integration scheme is designed for an odd number of mesh points\")\n    end\n\n    h = (x[inds[2]]-x[inds[1]])\n    σs = similar(x).*zero(T)\n    for j in 1:length(inds)\n        σs[inds[j]] = iseven(j) ? 4.0 : 2.0\n    end\n    σs = σs.*(h/3.0)\n\n    # accounts for the ends\n    σs[inds[1]] = h/3.0\n    σs[inds[1]] +=  (x[inds[1]] - x0)*(x[inds[2]] - x0 + h)/(2.0h)\n    σs[inds[2]] +=  - (x0-x[inds[1]])^2.0/(2.0h)\n    σs[inds[end]] = h/3.0\n    σs[inds[end]] +=  (xn-x[inds[end]])*(xn - x[inds[end-1]] + h)/(2h)\n    σs[inds[end-1]] += - (xn-x[inds[end]])^2.0/(2h)\n\n    return σs\nend\n", "meta": {"hexsha": "eef1fedf808fee6ff9e29eadf1a29b07a98d4cf4", "size": 1789, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/average_waves/numerical_integration.jl", "max_stars_repo_name": "UnofficialJuliaMirror/EffectiveWaves.jl-37e8709b-1ed2-53db-b26a-3571262b3cb4", "max_stars_repo_head_hexsha": "ec9829c42554ae993fe52f93a05c00b4c86105be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/average_waves/numerical_integration.jl", "max_issues_repo_name": "UnofficialJuliaMirror/EffectiveWaves.jl-37e8709b-1ed2-53db-b26a-3571262b3cb4", "max_issues_repo_head_hexsha": "ec9829c42554ae993fe52f93a05c00b4c86105be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/average_waves/numerical_integration.jl", "max_forks_repo_name": "UnofficialJuliaMirror/EffectiveWaves.jl-37e8709b-1ed2-53db-b26a-3571262b3cb4", "max_forks_repo_head_hexsha": "ec9829c42554ae993fe52f93a05c00b4c86105be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1060606061, "max_line_length": 111, "alphanum_fraction": 0.5265511459, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7640721281937125}}
{"text": "###########\n# This gives an example of Gauss–Seidel\n#\n###########\n\nusing BlockBandedMatrices, BandedMatrices, ArrayLayouts, FillArrays, LazyBandedMatrices, LazyArrays\n\n\nfunction finitedifference_2d(n)\n    h = 1/n\n    D² = BandedMatrix(0 => Fill(-2,n), 1 => Fill(1,n-1), -1 => Fill(1,n-1))/h^2\n    D_xx = BandedBlockBandedMatrix(Kron(D², Eye(n)))\n    D_yy = BandedBlockBandedMatrix(Kron(Eye(n), D²))\n    D_xx + D_yy\nend\n\nfunction _gaussseidel(L, U, b, x=copy(b), y=copy(b), M=5)\n    for _=1:M\n        @view(y[1:end-1]) .= Mul(U , @view(x[2:end]))\n        y[end] = 0\n        x .= b .- y\n        x .= Ldiv(L, x)\n    end\n    x\nend\n\n\n\nfunction _gaussseidel2(L, U, b, x=copy(b), y=copy(b), M=5)\n    for _=1:M\n        mul!(@view(y[1:end-1]) , U , @view(x[2:end]))\n        y[end] = 0\n        y .= b .- y\n        x .= L\\ y\n    end\n    x\nend\n\nfunction gaussseidel(A, b, M)\n    n = Int(sqrt(length(b)))\n    L = LowerTriangular(A)\n    U = BandedBlockBandedMatrix(UpperTriangular(@view(A[1:end-1,2:end])), ([fill(n,n-1); n-1], [n-1; fill(n,n-1)]),\n                                            (0,1), (0,1))\n    x = copy(b)\n    _gaussseidel(L,U, b, x, copy(x), M) # 1.6s\n    x\nend\n\nn = 1000;\n    Δt = (1/n^2)/4; @time Δ = finitedifference_2d(n);\n    @time A = I - Δt*Δ  # 1m x 1m discretization\n    b = randn(n^2)\n    L = LowerTriangular(A)\n    @time U = BandedBlockBandedMatrix(UpperTriangular(@view(A[1:end-1,2:end])), ([fill(n,n-1); n-1], [n-1; fill(n,n-1)]),\n                                            (0,1), (0,1))\n    x = copy(b)\n    y = copy(x)\n    @time _gaussseidel(L,U, b, x, y, 20) # 0.4s\n\n    @time L̃ = sparse(BandedBlockBandedMatrix(L))\n    @time Ũ = sparse(U)\n    x = copy(b)\n    y = copy(x)\n    @time _gaussseidel2(L̃,Ũ, b, x, y, 20)\n\nÃ = sparse(A)\n@time qr(Ã);\n@time Ã \\b ;\n\nA = randn(n,n)\n\nn = 1000;\n    As = [randn(2k+1,k) for k=1:n];\n\n    @time for A in As\n        qr(A)\n    end\nn = 1000;\n    # As = [randn(2k+1,k) for k=1:n];\n\n    @time for A in As\n        lu(A)\n    end\n\n", "meta": {"hexsha": "18d1bdbafb09dfeb72533aeb401d52582a81d9e9", "size": 1979, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/finitedifference_2d.jl", "max_stars_repo_name": "JuliaMatrices/BlockBandedMatrices.jl", "max_stars_repo_head_hexsha": "1af0411eba0c4e152f826ece7d1b44e95af5e30a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2017-12-08T18:35:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T06:20:13.000Z", "max_issues_repo_path": "examples/finitedifference_2d.jl", "max_issues_repo_name": "JuliaMatrices/BlockBandedMatrices.jl", "max_issues_repo_head_hexsha": "1af0411eba0c4e152f826ece7d1b44e95af5e30a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 89, "max_issues_repo_issues_event_min_datetime": "2018-01-31T10:28:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:19:46.000Z", "max_forks_repo_path": "examples/finitedifference_2d.jl", "max_forks_repo_name": "JuliaMatrices/BlockBandedMatrices.jl", "max_forks_repo_head_hexsha": "1af0411eba0c4e152f826ece7d1b44e95af5e30a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2018-02-19T10:15:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T09:31:23.000Z", "avg_line_length": 23.2823529412, "max_line_length": 121, "alphanum_fraction": 0.5098534613, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642554, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7640446971229913}}
{"text": "\"\"\"\n    explicit midpoint integrator\n\"\"\"\nfunction midpoint(model, x, u, w, h)\n    x + h * f(model, x + 0.5 * h * f(model, x, u, w), u, w)\nend\n\n\"\"\"\n    implicit midpoint integrator\n\"\"\"\nfunction midpoint_implicit(model, x⁺, x, u, w, h)\n    x⁺ - (x + h * f(model, 0.5 * (x + x⁺), u, w))\nend\n\n\"\"\"\n    explicit RK3 integrator\n\"\"\"\nfunction rk3(model, z, u, w, h)\n    k1 = k2 = k3 = zero(z)\n    k1 = h * f(model, z, u, w)\n    k2 = h * f(model, z + 0.5 * k1, u, w)\n    k3 = h * f(model, z - k1 + 2.0 * k2, u, w)\n    z + (k1 + 4.0 * k2 + k3) / 6.0\nend\n\n\"\"\"\n    discrete explicit dynamics\n\"\"\"\nfunction fd(model, x, u, w, h, t)\n    midpoint(model, x, u, w, h)\nend\n\n\"\"\"\n    discrete implicit dynamics\n\"\"\"\nfunction fd(model, x⁺, x, u, w, h, t)\n    midpoint_implicit(model, x⁺, x, u, w, h)\nend\n", "meta": {"hexsha": "80bc4f9b89f79d68ad6ae99e49fc5aec605d9a0a", "size": 780, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/integration.jl", "max_stars_repo_name": "zacmanchester/DirectMotionPlanning", "max_stars_repo_head_hexsha": "fd8ef76ab5023d6ac175a72f9e870f986e1a67d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-18T16:01:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:36:10.000Z", "max_issues_repo_path": "src/integration.jl", "max_issues_repo_name": "zacmanchester/DirectMotionPlanning", "max_issues_repo_head_hexsha": "fd8ef76ab5023d6ac175a72f9e870f986e1a67d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/integration.jl", "max_forks_repo_name": "zacmanchester/DirectMotionPlanning", "max_forks_repo_head_hexsha": "fd8ef76ab5023d6ac175a72f9e870f986e1a67d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0, "max_line_length": 59, "alphanum_fraction": 0.5217948718, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7640446928338029}}
{"text": "module SimplePCHIP\n#\n# Simple PCHIP implementation following Fritsch and Carlson, SIAM J. NUMER. ANAL. 17 (1980) 238-246.\n# Derivative calculated in a fashion similar to SciPy's PchipInterpolate\n#\n\nexport interpolate\n\n\nstruct _pchip\n    N :: Int\n    xs :: Vector{Float64}\n    ys :: Vector{Float64}\n    ds :: Vector{Float64}\nend\n\nϕ(t) = 3t^2 - 2t^3\nψ(t) = t^3 - t^2\n\nfunction _interp(pchip :: _pchip, x :: Number)\n    i = _pchip_index(pchip, x)\n    x1, x2 = pchip.xs[i:i+1]\n    y1, y2 = pchip.ys[i:i+1]\n    d1, d2 = pchip.ds[i:i+1]\n    h = x2 - x1\n\n    (y1 * ϕ((x2-x)/h)\n     + y2 * ϕ((x-x1)/h)\n     - d1*h * ψ((x2-x)/h)\n     + d2*h * ψ((x-x1)/h))\nend\n\nfunction _pchip_index(pchip :: _pchip, x)\n    N = pchip.N\n    if N < 200  # Approximate performance cross-over on my old intel i7-3517U\n        i = _pchip_index_linear_search(pchip, x)\n    else\n        i = _pchip_index_bisectional_search(pchip, x)\n    end\n    if i == N\n        # Treat right endpoint as part of rightmost interval\n        @assert (x ≈ pchip.xs[N])\n        i = N-1\n    end\n    i\nend\n\nfunction _pchip_index_linear_search(pchip :: _pchip, x)\n    xmin = pchip.xs[1]\n    @assert (x >= xmin)\n\n    i = 1\n    N = pchip.N\n    while i < N  &&  x >= pchip.xs[i+1]\n        i = i + 1\n    end\n    i\nend\n\nfunction _pchip_index_bisectional_search(pchip :: _pchip, x)\n    N = pchip.N\n    imin, imax = 1, N\n    xmin = pchip.xs[imin]\n    xmax = pchip.xs[imax]\n    @assert (x >= xmin && x <= xmax)\n\n    i = imin + div(imax - imin + 1, 2)\n    while imin < imax\n        if x < pchip.xs[i]\n            imax = i - 1\n        elseif x >= pchip.xs[i+1]\n            imin = i + 1\n        else\n            break\n        end\n        i = imin + div(imax - imin + 1, 2)\n    end\n    i\nend\n\n\n\"Similar to how SciPy's PCHIP does it\"\nfunction _initial_ds_scipy(xs, ys)\n    h(i) = xs[i+1]-xs[i]\n    Δ(i) = (ys[i+1]-ys[i]) / h(i)\n\n    N = length(xs)\n    ds = similar(xs)\n    if N == 2\n        ds[:] .= Δ(1)\n    else\n        Δl = Δ(1)\n        hl = h(1)\n        for i ∈ 2:N-1\n            Δr = Δ(i)\n            hr = h(i)\n            if sign(Δl) != sign(Δr) || Δl ≈ 0.0 || Δr ≈ 0.0\n                ds[i] = 0.0\n            else\n                wl = 2hl + hr\n                wr = hl + 2hr\n                ds[i] = (wl + wr) / (wl/Δl + wr/Δr)\n            end\n            Δl = Δr\n            hl = hr\n        end\n        ds[1] = _edge_derivative(h(1), h(2), Δ(1), Δ(2))\n        ds[N] = _edge_derivative(h(N-1), h(N-2), Δ(N-1), Δ(N-2))\n    end\n    ds\nend\n\nfunction _edge_derivative(h1, h2, Δ1, Δ2)\n    d = ((2h1 + h2)*Δ1 - h2*Δ2) / (h1 + h2)\n    if sign(d) != sign(Δ1)\n        d = 0.0\n    elseif sign(Δ1) != sign(Δ2)  &&  abs(d) > abs(3Δ1)\n        d = 3Δ1\n    end\n    d\nend\n\nfunction interpolate(xs, ys)\n    xs_ = [x for x ∈ xs]\n    ys_ = [y for y ∈ ys]\n    _assert_xs_ys(xs_, ys_)\n    ds = _initial_ds_scipy(xs_, ys_)\n    pchip = _pchip(length(xs_), xs_, ys_, ds)\n\n    x -> _interp(pchip, x)\nend\n\nfunction _assert_xs_ys(xs, ys)\n    N = length(xs)\n    @assert (N > 1)\n    @assert (N == length(ys))\n    assert_monotonic_increase(xs)\nend\n\nfunction assert_monotonic_increase(xs)\n    foldl((a,b) -> (@assert (a < b); b), xs)\nend\n\nend  # module\n", "meta": {"hexsha": "c99fa546f7bbaa712beac5760ab4f6c984f35ddd", "size": 3158, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SimplePCHIP.jl", "max_stars_repo_name": "genkuroki/SimplePCHIP", "max_stars_repo_head_hexsha": "7a2dab706140cf3061e3dc12b303c0ae1d9ca922", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SimplePCHIP.jl", "max_issues_repo_name": "genkuroki/SimplePCHIP", "max_issues_repo_head_hexsha": "7a2dab706140cf3061e3dc12b303c0ae1d9ca922", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SimplePCHIP.jl", "max_forks_repo_name": "genkuroki/SimplePCHIP", "max_forks_repo_head_hexsha": "7a2dab706140cf3061e3dc12b303c0ae1d9ca922", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7793103448, "max_line_length": 100, "alphanum_fraction": 0.5107663078, "num_tokens": 1207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7640446885446142}}
{"text": "using QuadGK\nusing FastClosures\n\"\"\"\n\tWharmonicR(t, tf, coeffs)\nHarmonic correction Hamiltonian in the rotating frame.\n\"\"\"\nfunction WharmonicR(t, tf, coeffs)\n\tε1, ε2, Δ = coeffs[1], coeffs[2], coeffs[3]\n\tcos2t, sin2t = cos(2*t), sin(2*t)\n\tg = (ε1*cos2t + ε2*sin2t)*(1 - cos(2*pi*t/tf))\n\tW = zeros(Float64, 3)\n\tW[1] = g*cos2t\n\tW[2] = g*sin2t\n\tW[3] = Δ/2\n\treturn W\nend\n\"\"\"\n\tWharmonicI(t, tf, coeffs)\nHarmonic correction Hamiltonian in the interaction picture.\n\"\"\"\nfunction WharmonicI(t, tf, coeffs)\n\tε1, ε2, Δ = coeffs[1], coeffs[2], coeffs[3]\n\tcos2t, sin2t = cos(2*t), sin(2*t)\n\tg = (ε1*cos2t + ε2*sin2t)*(1 - cos(2*pi*t/tf))\n\tΛt = Λ(t,tf)\n\tcosh2Λ, sinh2Λ = cosh(2*Λt), sinh(2*Λt)\n\tW = zeros(Float64, 3)\n\tW[1] = g*cos2t*cosh2Λ + (Δ/2 + g)*sinh2Λ\n\tW[2] = g*sin2t\n\tW[3] = g*cos2t*sinh2Λ + (Δ/2 + g)*cosh2Λ\n\treturn W\nend\n\"\"\"\n\tcorrection_matrix(tf)\nCorrection matrix for the harmonic correction.\n\"\"\"\nfunction correction_matrix(tf)\n\tM = zeros(Float64, 3, 3)\n\th(t) = 1 - cos(2*pi*t/tf)\n\n\tfunc11 = @closure t-> h(t)*((1 + cos(4*t))*cosh(2*Λ(t,tf))\n\t\t\t\t\t\t\t\t+ 2*cos(2*t)*sinh(2*Λ(t,tf)))/2\n\tM[1, 1], err = quadgk(func11, 0.0, tf, rtol=1e-10, atol=1e-14)\n\tfunc12 = @closure t-> h(t)*(sin(4*t)*cosh(2*Λ(t,tf))\n\t\t\t\t\t\t\t\t+ 2*sin(2*t)*sinh(2*Λ(t,tf)))/2\n\tM[1, 2], err = quadgk(func12, 0.0, tf, rtol=1e-10, atol=1e-14)\n\tfunc13 = @closure t-> sinh(2*Λ(t,tf))/2\n\tM[1, 3], err = quadgk(func13, 0.0, tf, rtol=1e-10, atol=1e-14)\n\tfunc21 = t-> h(t)*sin(4*t)/2\n\tM[2, 1], err = quadgk(func21, 0.0, tf, rtol=1e-10, atol=1e-14)\n\tfunc22 = t-> h(t)*(1 - cos(4*t))/2\n\tM[2, 2], err = quadgk(func22, 0.0, tf, rtol=1e-10, atol=1e-14)\n\tfunc31 = @closure t-> h(t)*((1 + cos(4*t))*sinh(2.0*Λ(t,tf))\n\t\t\t\t\t\t\t\t+ 2.0*cos(2*t)*cosh(2.0*Λ(t,tf)))/2\n\tM[3, 1], err = quadgk(func31, 0.0, tf, rtol=1e-10, atol=1e-14)\n\tfunc32 = @closure t-> h(t)*(sin(4*t)*sinh(2.0*Λ(t,tf))\n\t\t\t\t\t\t\t\t+ 2.0*sin(2*t)*cosh(2.0*Λ(t,tf)))/2\n\tM[3, 2], err = quadgk(func32, 0.0, tf, rtol=1e-10, atol=1e-14)\n\tfunc33 = @closure t-> cosh(2*Λ(t,tf))/2\n\tM[3, 3], err = quadgk(func33, 0.0, tf, rtol=1e-10, atol=1e-14)\n\n\treturn M\nend\n\"\"\"\n\tcoefficients_W(Omega, M)\nCalculate the coefficients of the harmonic correction.\n\"\"\"\nfunction coefficients_W(Omega, M)\n\tih_vec = Omega\n\tcoeffs = inv(M)*ih_vec\n\treturn coeffs\nend\n\"\"\"\n\tget_coeffs(M, coeffs, order, tf)\nCalculate the coefficients of the Harmonic correction.\n\"\"\"\nfunction get_coeffs(M, coeffs, order, tf)\n\tA = @closure (t-> -V_I(t, tf) .- WharmonicI(t, tf, coeffs))\n\n    Ndims = 3\n    Omegaf = solveOmega(tf, order, A, comm!, Ndims)\n\n    vec = sum(Omegaf, dims=2)\n    coeffs = coefficients_W(vec, M)\n    return coeffs\nend\n\"\"\"\n\tget_coeffs(M, order, tf)\nCalculate the coefficients of the Harmonic correction.\n\"\"\"\nfunction get_coeffs(M, order, tf)\n    coeffs = zeros(3)\n    for k = 1: order\n\t\tcoeffs2 = get_coeffs(M, coeffs, order, tf)\n        coeffs = coeffs .+ coeffs2\n    end\n    return coeffs\nend\n", "meta": {"hexsha": "436aacc80f0f795d8475db4375643d8753dac87d", "size": 2868, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PDC/HarmonicCorrectionBoson.jl", "max_stars_repo_name": "thalesfr/MagnusCorrection", "max_stars_repo_head_hexsha": "c0b5107e321a7e94661ed900ba7075eee438d01e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-06T14:45:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-06T14:45:42.000Z", "max_issues_repo_path": "PDC/HarmonicCorrectionBoson.jl", "max_issues_repo_name": "thalesfr/MagnusCorrection", "max_issues_repo_head_hexsha": "c0b5107e321a7e94661ed900ba7075eee438d01e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PDC/HarmonicCorrectionBoson.jl", "max_forks_repo_name": "thalesfr/MagnusCorrection", "max_forks_repo_head_hexsha": "c0b5107e321a7e94661ed900ba7075eee438d01e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-06T14:45:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-06T14:45:55.000Z", "avg_line_length": 28.9696969697, "max_line_length": 63, "alphanum_fraction": 0.6147140865, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491797, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7640446808860416}}
{"text": "######### Stan program example  ###########\n\nusing Mamba, Stan\n\nProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n\n  bernoullimodel = \"\n  data { \n    int<lower=1> N; \n    int<lower=0,upper=1> y[N];\n  } \n  parameters {\n    real<lower=0,upper=1> theta;\n  } \n  model {\n    theta ~ beta(1,1);\n    y ~ bernoulli(theta);\n  }\n  \"\n\n  bernoullidata = [\n    Dict(\"N\" => 1, \"y\" => [0]),\n    Dict(\"N\" => 1, \"y\" => [0]),\n    Dict(\"N\" => 1, \"y\" => [0]),\n    Dict(\"N\" => 1, \"y\" => [0]),\n  ]\n\n  monitor = [\"theta\", \"lp__\", \"accept_stat__\"]\n\n  global stanmodel, rc, sim1, sim\n  stanmodel = Stanmodel(num_samples=1200, thin=2, name=\"bernoulli\", model=bernoullimodel);\n\n  println(\"\\nStanmodel that will be used:\")\n  stanmodel |> display\n  println()\n  println(\"Input observed data dictionary:\")\n  bernoullidata |> display\n  println()\n\n  rc, sim1 = stan(stanmodel, bernoullidata, ProjDir, diagnostics=false, CmdStanDir=CMDSTAN_HOME);\n\n  if rc == 0\n    ## Subset Sampler Output to variables suitable for describe().\n    sim = sim1[1:size(sim1, 1), monitor, 1:size(sim1, 3)]\n    describe(sim)\n    println()\n\n    ## Brooks, Gelman and Rubin Convergence Diagnostic\n    try\n      gelmandiag(sim, mpsrf=true, transform=true) |> display\n    catch e\n      #println(e)\n      gelmandiag(sim, mpsrf=false, transform=true) |> display\n    end\n    println()\n\n    ## Geweke Convergence Diagnostic\n    gewekediag(sim) |> display\n\n    ## Highest Posterior Density Intervals\n    hpd(sim) |> display\n\n    ## Cross-Correlations\n    cor(sim) |> display\n\n    ## Lag-Autocorrelations\n    autocor(sim) |> display\n\n    ## Deviance Information Criterion\n    #dic(sim) |> display\n\n    ## Plotting\n    p = plot(sim, [:trace, :mean, :density, :autocor], legend=true);\n    draw(p, ncol=4, filename=\"$(stanmodel.name)-summaryplot\", fmt=:svg)\n    draw(p, ncol=4, filename=\"$(stanmodel.name)-summaryplot\", fmt=:pdf)\n\n  \t# Pairwise contour plots\n  \tsimmod = ModelChains(sim,Mamba.Model())\n  \tp = plot(simmod, :contour)\n  \tdraw(p, nrow=2, ncol=2, filename=\"$(stanmodel.name)-contourplot.svg\")\n  \tdraw(p, nrow=2, ncol=2, filename=\"$(stanmodel.name)-contourplot.pdf\", fmt=:pdf)\n\n  end # rc == 0\nend # cd\n", "meta": {"hexsha": "67082e0de8956c13f17d5890cf837325e004d530", "size": 2140, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/Mamba/BernoulliScalar/bernoulliscalar.jl", "max_stars_repo_name": "fpmenninger/Stan.jl", "max_stars_repo_head_hexsha": "671e03a6e40748b070db206b0d8e907dbf90b86b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Examples/Mamba/BernoulliScalar/bernoulliscalar.jl", "max_issues_repo_name": "fpmenninger/Stan.jl", "max_issues_repo_head_hexsha": "671e03a6e40748b070db206b0d8e907dbf90b86b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/Mamba/BernoulliScalar/bernoulliscalar.jl", "max_forks_repo_name": "fpmenninger/Stan.jl", "max_forks_repo_head_hexsha": "671e03a6e40748b070db206b0d8e907dbf90b86b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8837209302, "max_line_length": 97, "alphanum_fraction": 0.6168224299, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.764033731039687}}
{"text": "#! /usr/bin/julia\n\n# Rosetta Code, Permutation test\n\ndelta_mean{T<:Real}(a::Array{T,1}, b::Array{T,1}) = mean(a) - mean(b)\n\nfunction bifurcate{T<:Integer}(a::AbstractVector, sel::Array{T,1})\n    x = a[sel]\n    asel = trues(length(a))\n    asel[sel] = false\n    y = a[asel]\n    return (x, y)\nend\n\nfunction perm_sig_test{T<:Real}(treat::Array{T,1}, control::Array{T,1})\n    base_effect = delta_mean(treat, control)\n    pool = [treat, control]\n    tlen = length(treat)\n    plen = length(pool)\n    better = 0\n    worse = 0\n    for s in combinations(1:plen, tlen)\n        (t, c) = bifurcate(pool, s)\n        if base_effect < delta_mean(t, c)\n            better += 1\n        else\n            worse += 1\n        end\n    end\n    return (better, worse)\nend\n    \ntreat = [85, 88, 75, 66, 25, 29, 83, 39, 97]\ncontrol = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]\n\n(better, worse) = perm_sig_test(treat, control)\n\ntot = better + worse\n\nprintln(\"Permutation test using the following data:\")\nprintln(\"Treated:  \", treat)\nprintln(\"Control:  \", control)\n\nprintln()\nprintln(\"There are \", tot, \" different permuted groups of these data.\")\nprint(@sprintf(\"%8d, %5.2f%% \", better, 100better/tot))\nprintln(\"showed better than actual results.\")\nprint(@sprintf(\"%8d, %5.2f%% \", worse, 100worse/tot))\nprintln(\"showed equalivalent or worse results.\")\n", "meta": {"hexsha": "997cabae8669294b2c75f4ec9af8ac6b00e26c70", "size": 1322, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/completed/permutation_test.jl", "max_stars_repo_name": "MichaeLeroy/rosetta-code", "max_stars_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/completed/permutation_test.jl", "max_issues_repo_name": "MichaeLeroy/rosetta-code", "max_issues_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/completed/permutation_test.jl", "max_forks_repo_name": "MichaeLeroy/rosetta-code", "max_forks_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.44, "max_line_length": 71, "alphanum_fraction": 0.6180030257, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8596637487122112, "lm_q1q2_score": 0.7640337211805873}}
{"text": "@inline permute(i, N) = isodd(i) ? floor(Int, i/2) + 1 : N - floor(Int, (i-1)/2)\n\n@inline unpermute(i, N) = i <= ceil(N/2) ? 2i-1 : 2(N-i+1)\n\nfunction dct_makhoul_1d(A::CuArray)\n    B = similar(A)\n    N = length(A)\n\n    for k in 1:N\n        B[permute(k, N)] = A[k]\n    end\n\n    B = CUDA.CUFFT.fft(B)\n\n    for k in 1:N\n        B[k] = 2 * ω(4N, k-1) * B[k]\n    end\n\n    return real(B)\nend\n\nfunction idct_makhoul_1d(A::CuArray)\n    B = similar(A, complex(eltype(A)))\n    N = length(A)\n\n    B[1] = 1/2 * ω(4N, 0) * A[1]\n    for k in 2:N\n        B[k] = ω(4N, 1-k) * A[k]\n    end\n\n    B = CUDA.CUFFT.ifft(B)\n\n    C = similar(A)\n    for k in 1:N\n        C[unpermute(k, N)] = real(B[k])\n    end\n\n    return C\nend\n\nfunction dct_makhoul_2d(A::CuArray)\n    Nx, Ny = size(A)\n\n    # DCT along dimension 1\n\n    B = similar(A)\n\n    for j in 1:Ny, i in 1:Nx\n        B[permute(i, Nx), j] = A[i, j]\n    end\n\n    B = CUDA.CUFFT.fft(B, 1)\n\n    for j in 1:Ny, i in 1:Nx\n        B[i, j] = 2 * ω(4Nx, i-1) * B[i, j]\n    end\n\n    B = real(B)\n\n    # DCT along dimension 2\n\n    C = similar(A)\n\n    for j in 1:Ny, i in 1:Nx\n        C[i, permute(j, Ny)] = B[i, j]\n    end\n\n    C = CUDA.CUFFT.fft(C, 2)\n\n    for j in 1:Ny, i in 1:Nx\n        C[i, j] = 2 * ω(4Ny, j-1) * C[i, j]\n    end\n\n    return real(C)\nend\n\nfunction idct_makhoul_2d(A::CuArray)\n    Nx, Ny = size(A)\n\n    # IDCT along dimension 1\n\n    B = similar(A, complex(eltype(A)))\n\n    for j in 1:Ny\n        B[1, j] = 1/2 * ω(4Nx, 0) * A[1, j]\n    end\n\n    for j in 1:Ny, i in 2:Nx\n        B[i, j] = ω(4Nx, 1-i) * A[i, j]\n    end\n\n    B = CUDA.CUFFT.ifft(B, 1)\n\n    C = similar(A)\n    for j in 1:Ny, i in 1:Nx\n        C[unpermute(i, Nx), j] = real(B[i, j])\n    end\n\n    # IDCT along dimension 2\n\n    D = similar(A, complex(eltype(A)))\n\n    for i in 1:Nx\n        D[i, 1] = 1/2 * ω(4Ny, 0) * C[i, 1]\n    end\n\n    for j in 2:Ny, i in 1:Nx\n        D[i, j] = ω(4Ny, 1-j) * C[i, j]\n    end\n\n    D = CUDA.CUFFT.ifft(D, 2)\n\n    E = similar(A)\n    for j in 1:Ny, i in 1:Nx\n        E[i, unpermute(j, Ny)] = real(D[i, j])\n    end\n\n    return E\nend", "meta": {"hexsha": "742966851816631aec8b9b22b736ccdaff76c154", "size": 2064, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dct_makhoul.jl", "max_stars_repo_name": "ali-ramadhan/TransformPlayground.jl", "max_stars_repo_head_hexsha": "b5ffff2d00622fb4a0e165657792829381a266c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-11-14T08:02:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T16:42:19.000Z", "max_issues_repo_path": "src/dct_makhoul.jl", "max_issues_repo_name": "ali-ramadhan/TransformPlayground.jl", "max_issues_repo_head_hexsha": "b5ffff2d00622fb4a0e165657792829381a266c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dct_makhoul.jl", "max_forks_repo_name": "ali-ramadhan/TransformPlayground.jl", "max_forks_repo_head_hexsha": "b5ffff2d00622fb4a0e165657792829381a266c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3445378151, "max_line_length": 80, "alphanum_fraction": 0.480620155, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7640248485395739}}
{"text": "#=\nPolynomial operations made over unsigned integers in extension fields GF(2^m).\n\nAuthor: Ivan A. Moreno Soto\nLast updated: 2019/July/08\n=#\n\nmodule Polynomials\n\nexport\n    PolynomialConstants,\n    monomial,\n    evaluate!,\n    addRing!,\n    multiplyRing!,\n    divRing!,\n    modRing!,\n    makePolynomialMonic!,\n    inverseRing!,\n    isPolynomialIrreducible!,\n    randomPoly,\n    splitPolynomial!\n\ninclude(\"./ExtensionField.jl\")\nusing .ExtensionField\n\nPolynomialConstants = Dict(\n    '0' => Array{UInt32, 1}([0]),\n    '1' => Array{UInt32, 1}([1]),\n    'x' => Array{UInt32, 1}([0, 1])\n)\n\n\"\"\"\n    monomial(degree)\n\nReturns a monomial of the given degree.\n\"\"\"\nfunction monomial(degree)\n    monomial = Array{UInt32, 1}([0 for _ in 0:degree])\n    monomial[end] = 1\n    return monomial\nend\n\n\"\"\"\n    evaluate!(x, p, g)\n\nEvaluates p(x) modulo g(x).\n\"\"\"\nfunction evaluate!(x, p, g)\n    y = UInt32(0)\n\n    for i in length(p):-1:1\n        y = add(modulo(multiply(x, y), g), p[i])\n    end\n\n    return y\nend\n\n\"\"\"\n    reducePolynomialArray!(p)\n\nTakes a polynomial p and returns an array without unnecessary zero\ncoefficients.\n\"\"\"\nfunction reducePolynomialArray!(p)\n    if length(p) == 1\n        return p\n    elseif !any(x -> x > 0, p)\n        return [p[1]]\n    else\n        return p[1:findlast(x -> x > 0, p)]\n    end\nend\n\n\"\"\"\n    addRing!(a, b)\n\nAdds two polynomials with coefficients in GF(2^m).\n\"\"\"\nfunction addRing!(a, b)\n    if length(a) >= length(b)\n        longPolynomial = a\n        shortPolynomial = b\n    else\n        longPolynomial = b\n        shortPolynomial = a\n    end\n\n    total = Array{UInt32, 1}([coeff for coeff in longPolynomial])\n\n    for i in 1:length(shortPolynomial)\n        total[i] = add(shortPolynomial[i], longPolynomial[i])\n    end\n\n    return reducePolynomialArray!(total)\nend\n\n\"\"\"\n    multiplyRing!(a, b, m)\n\nMultiplies two polynomials with coefficients in GF(2^m).\n\"\"\"\nfunction multiplyRing!(a, b, m)\n    product = Array{UInt32, 1}([0 for _ in 1:(length(a) + length(b) - 1)])\n\n    for i in 1:length(a)\n        for j in 1:length(b)\n            term = modulo(multiply(a[i], b[j]), primitivePolynomials[m])\n            product[i+j - 1] = add(product[i+j - 1], term)\n        end\n    end\n\n    return reducePolynomialArray!(product)\nend\n\n\"\"\"\n    polynomialLongDivision!(a, b, m)\n\nReturns the quotient and the modulo of a/b with coefficients\nin GF(2^m).\n\"\"\"\nfunction polynomialLongDivision!(a, b, m)\n    if a == b\n        return Array{UInt32, 1}([1]), Array{UInt32, 1}([0])\n    elseif length(a) < length(b) #a < b\n        return Array{UInt32, 1}([0]), a\n    end\n\n    quotient = Array{UInt32, 1}([])\n    remainder = a\n    for i in (length(a) - length(b)):-1:0\n        if length(remainder) >= length(b) + i\n            step = Array{UInt32, 1}([0 for _ in 0:i])\n            step[end] = modulo(multiply(inverse(b[end], primitivePolynomials[m]), remainder[end]), primitivePolynomials[m])\n\n            partial = multiplyRing!(b, step, m)\n\n            remainder = addRing!(remainder, partial)\n            push!(quotient, step[end])\n        else\n            push!(quotient, 0)\n        end\n    end\n\n    reverse!(quotient) # push! adds the coefficients in reverse order.\n\n    return reducePolynomialArray!(quotient), reducePolynomialArray!(remainder)\nend\n\n\"\"\"\n    divRing!(a, b, m)\n\nReturns the quotient of a/b with coefficients in GF(2^m).\n\"\"\"\nfunction divRing!(a, b, m)\n    quotient, _ = polynomialLongDivision!(a, b, m)\n    return quotient\nend\n\n\"\"\"\n    modRing!(a, b, m)\n\nReturns the remainder of a/b with coefficients in GF(2^m).\n\"\"\"\nfunction modRing!(a, b, m)\n    _, remainder = polynomialLongDivision!(a, b, m)\n    return remainder\nend\n\n\"\"\"\n    makePolynomialMonic!(p, m)\n\nReturns p as a monic polynomial by dividing p by the inverse of its leading\ncoefficient.\n\"\"\"\nfunction makePolynomialMonic!(p, m)\n    return multiplyRing!([inverse(p[end], primitivePolynomials[m])], p, m)\nend\n\n\"\"\"\n    ringgcs!(a, b, m)\n\nComputes the GCD of a and b with coefficients in GF(2^m).\n\"\"\"\nfunction ringgcd!(a, b, m)\n    while b != PolynomialConstants['0']\n        t = copy(b)\n        b = modRing!(a, b, m)\n        a = t\n    end\n\n    return makePolynomialMonic!(a, m)\nend\n\n\"\"\"\n    inverseRing!(a, g, m)\n\nComputes the inverse of a mod g with coefficients in GF(2^m). Throws\nan exception if the inverse doesn't exist.\n\"\"\"\nfunction inverseRing!(a, g, m)\n    # Extended euclidean algorithm.\n    r = copy(a)\n    R = copy(g)\n    s = Array{UInt32, 1}([1])\n    S = Array{UInt32, 1}([0])\n    t = Array{UInt32, 1}([0])\n    T = Array{UInt32, 1}([1])\n\n    while R != Array{UInt32, 1}([0])\n        q = divRing!(r, R, m)\n\n        x = R; R = addRing!(r, multiplyRing!(q, R, m)); r = x\n        x = S; S = addRing!(s, multiplyRing!(q, S, m)); s = x\n        x = T; T = addRing!(t, multiplyRing!(q, T, m)); t = x\n    end\n\n    c = inverse(r[end], primitivePolynomials[m])\n\n    if makePolynomialMonic!(r, m) != PolynomialConstants['1']\n        error(\"The element doesn't have an inverse.\")\n    end\n\n    return multiplyRing!([c], s, m)\nend\n\n\"\"\"\n    isPolynomialIrreducible!(polynomial, n, m)\n\nChecks if the given polynomial has at least one root in GF(2^m). Returns\ntrue if it doesn't have roots, false otherwise.\n\"\"\"\nfunction isPolynomialIrreducible!(polynomial, n, m)\n    for i in 0:(2^m - 1)\n        if evaluate!(UInt32(i), polynomial, primitivePolynomials[m]) == 0\n            return false\n        end\n    end\n\n    return true\nend\n\n\"\"\"\n    getRandomCoefficients(t, m)\n\nReturns a random sequence of elements from GF(2^m)\nto serve as the coefficients of polynomial of degree t.\n\"\"\"\nfunction getRandomCoefficients(t, m)\n    polynomial = [UInt32(0) for _ in 1:(t + 1)]\n    polynomial[end] = UInt32(1) # Making the polynomial monic.\n    # Adding random coefficients to the polynomial.\n    for i in 1:t\n        if rand() >= 0.5\n            polynomial[i] = UInt32(rand(1:(2^m - 1)))\n        end\n    end\n\n    return polynomial\nend\n\n\"\"\"\n    randomPoly(t::Int, m::Int)\n\nReturns a random monic irreducible polynomial of degree t\nover the extension field GF(2^m).\n\"\"\"\nfunction randomPoly(t::Int, m::Int)\n    polynomial = getRandomCoefficients(t, m)\n\n    while !isPolynomialIrreducible!(polynomial, t, m)\n        polynomial = getRandomCoefficients(t, m)\n    end\n\n    return polynomial\nend\n\n\"\"\"\n    splitPolynomial!(p, m)\n\nSplits the polynomial p into even and odd terms in GF(2^m).\n\"\"\"\nfunction splitPolynomial!(p, m)\n    even = [squareroot(coeff, m) for coeff in p[1:2:end]]\n    odd = [squareroot(coeff, m) for coeff in p[2:2:end]]\n    return even, odd\nend\n\nend # Module Polynomials\n", "meta": {"hexsha": "30c0ceb035b5c3ed94bf5bf3697e802d6dc8fd65", "size": 6538, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "source/Polynomials.jl", "max_stars_repo_name": "rexemin/McEliece", "max_stars_repo_head_hexsha": "db8a2193acc74350df0d43700f6f636df8b57c3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-08-12T20:35:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T20:30:06.000Z", "max_issues_repo_path": "source/Polynomials.jl", "max_issues_repo_name": "rexemin/McEliece", "max_issues_repo_head_hexsha": "db8a2193acc74350df0d43700f6f636df8b57c3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Polynomials.jl", "max_forks_repo_name": "rexemin/McEliece", "max_forks_repo_head_hexsha": "db8a2193acc74350df0d43700f6f636df8b57c3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5448275862, "max_line_length": 123, "alphanum_fraction": 0.6183848272, "num_tokens": 1944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133430934989, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7640248339392016}}
{"text": "#== # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n#\n# Description\n#\n#   Functions to convert anomalies related to the orbit.\n#\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n#\n# References\n#\n#   [1] Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications.\n#       Microcosm Press, Hawthorn, CA, USA.\n#\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ==#\n\nexport M_to_E, M_to_f\nexport E_to_f, E_to_M\nexport f_to_E, f_to_M\n\n################################################################################\n#                              From Mean Anomaly\n################################################################################\n\n\"\"\"\n    M_to_E(e::Number, M::Number, tol::Number = 1e-10)\n\nCompute the eccentric anomaly (0,2π) \\\\[rad] given the eccentricity `e` and the\nmean anomaly `M` [rad]. This function uses the Newton-Raphson algorithm and the\ntolerance to accept the solution is `tol`.\n\n\"\"\"\n@inline function M_to_E(e::Number, M::Number, tol::Number = 1e-10)\n    # Compute the eccentric anomaly using the Newton-Raphson method.\n    # ==============================================================\n\n    # Make sure that M is in the interval [0,2π].\n    M = mod(M,2π)\n\n    # Initial guess.\n    #\n    # See [1, p. 75].\n    E = (M > π) ? M - e : M + e\n\n    sin_E, cos_E = sincos(E)\n\n    # Newton-Raphson iterations.\n    while ( abs(E - e*sin_E - M) > tol )\n        E = E - (E - e*sin_E - M)/(1-e*cos_E)\n\n        sin_E, cos_E = sincos(E)\n    end\n\n    # Return the eccentric anomaly in the interval [0, 2π].\n    mod(E, 2π)\nend\n\n\"\"\"\n    M_to_f(e::Number, M::Number, tol::Number = 1e-10)\n\nCompute the true anomaly (0,2π) \\\\[rad] given the eccentricity `e` and the mean\nanomaly `M` [rad]. This function uses the Newton-Raphson algorithm and the\ntolerance to accept the solution is `tol`.\n\n\"\"\"\n@inline function M_to_f(e::Number, M::Number, tol::Number = 1e-10)\n    # Compute the eccentric anomaly.\n    E = M_to_E(e, M, tol)\n\n    # Compute the true anomaly in the interval [0,2π].\n    E_to_f(e,E)\nend\n\n################################################################################\n#                            From Eccentric Anomaly\n################################################################################\n\n\"\"\"\n    E_to_f(e::Number, E::Number)\n\nCompute the true anomaly (0,2π) \\\\[rad] given the eccentricity `e` and the\neccentric anomaly `E` [rad].\n\n\"\"\"\n@inline function E_to_f(e::Number, E::Number)\n    sin_Eo2, cos_Eo2 = sincos(E/2)\n\n    # Compute the true anomaly in the interval [0, 2*π].\n    mod( 2atan(sqrt(1+e)*sin_Eo2, sqrt(1-e)*cos_Eo2) , 2π )\nend\n\n\"\"\"\n    E_to_M(e::Number, E::Number)\n\nCompute the mean anomaly (0,2π) \\\\[rad] given the eccentricity `e` and the\neccentric anomaly `E` [rad].\n\n\"\"\"\nE_to_M(e::Number, E::Number) = mod(E - e*sin(E), 2π)\n\n################################################################################\n#                              From True Anomaly\n################################################################################\n\n\"\"\"\n    f_to_E(e::Number,f::Number)\n\nCompute the eccentric anomaly (0,2π) \\\\[rad] given the eccentricity `e` and\nthe true anomaly `f` [rad].\n\n\"\"\"\n@inline function f_to_E(e::Number, f::Number)\n    sin_fo2, cos_fo2 = sincos(f/2)\n\n    mod( 2atan(sqrt(1-e)*sin_fo2, sqrt(1+e)*cos_fo2), 2π )\nend\n\n\"\"\"\n    f_to_E(orb::Orbit)\n\nCompute the eccentric anomaly (0,2π) \\\\[rad] given the orbit `orb` (see\n`Orbit`).\n\n\"\"\"\nf_to_E(orb::Orbit) = f_to_E(orb.e, orb.f)\n\n\"\"\"\n    f_to_M(e::Number, f::Number)\n\nCompute the mean anomaly (0,2π) \\\\[rad] given the eccentricity `e` and the\ntrue anomaly `f` [rad].\n\n\"\"\"\n@inline function f_to_M(e::Number, f::Number)\n    # Compute the eccentric anomaly.\n    E = f_to_E(e, f)\n\n    # Compute the true anomaly in the interval [0, 2π].\n    E_to_M(e,E)\nend\n\n\"\"\"\n    f_to_M(orb::Orbit)\n\nCompute the mean anomaly (0,2π) \\\\[rad] given the orbit `orb` (see `Orbit`).\n\n\"\"\"\nf_to_M(orb::Orbit) = f_to_M(orb.e, orb.f)\n", "meta": {"hexsha": "df91cb7558cf604657b1d55506f8eca358ea82b2", "size": 4009, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/orbit/anomalies.jl", "max_stars_repo_name": "ThatcherC/SatelliteToolbox.jl", "max_stars_repo_head_hexsha": "a30a74f96a8dfb77aba0869aeabe21c69cd83f36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/orbit/anomalies.jl", "max_issues_repo_name": "ThatcherC/SatelliteToolbox.jl", "max_issues_repo_head_hexsha": "a30a74f96a8dfb77aba0869aeabe21c69cd83f36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/orbit/anomalies.jl", "max_forks_repo_name": "ThatcherC/SatelliteToolbox.jl", "max_forks_repo_head_hexsha": "a30a74f96a8dfb77aba0869aeabe21c69cd83f36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0878378378, "max_line_length": 80, "alphanum_fraction": 0.4991269643, "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7639989547976007}}
{"text": "export\n    scale2log,\n    normlog,\n    sph2cart,\n    cart2sph,\n    mod_angle,\n    mod_angle_deg,\n    mod_angle_rad\n\n\n# operation\nscale2log(x) = 20log10(x)\nnormlog(vec) = vec .- maximum(vec)\nsph2cart(θ, ϕ, r) = begin\n    (\n        x=r * sin(θ)cos(ϕ),\n        y=r * sin(θ)sin(ϕ),\n        z=r * cos(θ)\n    )\nend\ncart2sph(x, y, z) = begin\n    # XXX r are not calcuated, may cause problem\n    r = sqrt(x^2 + y^2 + z^2)\n    θ = acos(z / r)\n    ϕ = atan(y, x)\n    (\n        θ=θ,\n        ϕ=ϕ,\n        r=r\n    )\nend\n# convert to domain θ ∈[0°, 180°], ϕ∈ [-180°, 180°]\n# bad implementation\nfunction mod_angle(θ, ϕ)\n    sign = x -> x >= 0 ? 1 : -1\n    item1 = -sign.(mod2pi.(θ) .- π)\n    θ_ = mod1.(θ .* item1, π)\n    θ_[θ.==0] .= 0\n    ϕ_ = item1 .* ϕ .|> mod2pi\n    (θ_, ϕ_)\nend\nfunction mod_angle(θ::Number, ϕ)\n    sign = x -> x >= 0 ? 1 : -1\n    item1 = -sign(mod2pi(θ) - π)\n    θ_ = (θ==0 ?  0.0 : mod1(θ * item1, π))\n    ϕ_ = (item1 .* ϕ) .|> mod2pi\n    (θ_, ϕ_)\nend\n\n# convert to domain θ ∈[0°, 180°], ϕ∈ [-180°, 180°]\nfunction mod_angle_deg(θ::Number, ϕ)\n    θ_res = 0.\n    ϕ_res = 0.\n    invert_ϕ = false\n    # in domain\n    if θ >= 0 && θ <= 180\n        θ_res = θ\n    elseif θ < 0 && θ >= -180\n        invert_ϕ = true \n        θ_res = -θ\n    else\n        throw(\"θ = $(θ) is out of range [-180,180]\")\n    end\n\n    if ϕ >=-180 && ϕ <= 180\n        ϕ_res = ϕ\n    elseif ϕ > 180 && ϕ <=360\n        ϕ_res = ϕ - 360\n    else\n        throw(\"ϕ = $(ϕ) is out of range [-180,360]\")\n    end\n\n    if invert_ϕ\n        if ϕ_res <= 0\n            ϕ_res += 180\n        else\n            ϕ_res -= 180\n        end\n    end\n    θ_res, ϕ_res\nend\n\n# not test\nfunction mod_angle_rad(θ::Number, ϕ)\n    θ_res = 0.\n    ϕ_res = 0.\n    invert_ϕ = false\n    # in domain\n    if θ >= 0 && θ <= pi\n        θ_res = θ\n    elseif θ < 0 && θ >= -pi\n        invert_ϕ = true \n        θ_res = -θ\n    else\n        throw(\"θ = $(θ) is out of range [-pi, pi]\")\n    end\n\n    if ϕ >=-pi && ϕ <= pi\n        ϕ_res = ϕ\n    elseif ϕ > pi && ϕ <=2pi\n        ϕ_res = ϕ - 2pi\n    else\n        throw(\"ϕ = $(ϕ) is out of range [-pi, 2pi]\")\n    end\n\n    if invert_ϕ\n        if ϕ_res <= 0\n            ϕ_res += pi\n        else\n            ϕ_res -= pi\n        end\n    end\n    θ_res, ϕ_res\nend", "meta": {"hexsha": "85ce508650fcc68f2e6b270809d93eba6ab7f9be", "size": 2230, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "ChansonLeung/Antenna.jl", "max_stars_repo_head_hexsha": "a9507607ac705c666a7106d66f7013fe9915bb92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-25T08:59:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:35:59.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "ChansonLeung/Antenna.jl", "max_issues_repo_head_hexsha": "a9507607ac705c666a7106d66f7013fe9915bb92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "ChansonLeung/Antenna.jl", "max_forks_repo_head_hexsha": "a9507607ac705c666a7106d66f7013fe9915bb92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5614035088, "max_line_length": 52, "alphanum_fraction": 0.4596412556, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7639989493703853}}
{"text": "module HWunconstrained\n\n\t# imports: which packages are we going to use in this module?\n\tusing Distributions, Optim, Plots, DataFrames\n\tusing Random\n\tusing Statistics\n\tusing LinearAlgebra\n\n\n    export maximize_like_grad, makeData, loglik, grad!, maximize_like, plotLike, plotGrad\n\n\n\n\t# methods/functions\n\t# -----------------\n\n\t# data creator\n\t# should/could return a dict with beta,numobs,X,y,norm)\n\t# true coeff vector, number of obs, data matrix X, response vector y, and a type of parametric distribution for G.\n\tfunction makeData(n=10_000)\n\t           beta = [ 1; 1.5; -0.5 ]\n\t           Random.seed!(54321)\n\t           numobs = n\n\t           X = randn(numobs,3)    # n,k\n\t           epsilon = randn(numobs)\n\t           Y = X * beta + epsilon\n\t           y = 1.0 * (Y .> 0)\n\t           norm = Normal(0,1)    # create a normal distribution object with mean 0 and variance 1\n\t           return Dict(\"beta\"=>beta,\"n\"=>numobs,\"X\"=>X,\"y\"=>y,\"dist\"=>norm)\n\t       end\n\n\tfunction loglik(betas::Vector, d::Dict)\n\t\tlh = log.(cdf.(d[\"dist\"],d[\"X\"]*betas) .^ d[\"y\"] .* (1 .- cdf.(d[\"dist\"],d[\"X\"]*betas)) .^ (1 .- d[\"y\"]))\n\t\treturn (-1) * sum(lh) / d[\"n\"]\n\tend\n\n\t# gradient of the likelihood at x\n\tfunction grad!(storage::Vector,betas::Vector,d)\n\n\t\tfor j=1:3\n\t\t\ttemp = zeros(length(d[\"y\"]))\n \t\t\tfor i=1:d[\"n\"]\n\t\t\t\ttemp[i] = (d[\"y\"][i] - cdf.(d[\"dist\"], d[\"X\"][i,:]' * betas)) * d[\"X\"][i,j]\n\t\t\tend\n\t\t\tstorage[j] = sum(temp)\n\t\tend\n\tend\n\n\n\t# hessian of the likelihood at x\n\tfunction hessian!(storage::Matrix,betas::Vector,d)\n\n\t\t#call the gradient we just made\n\n\t\t# Compute the hessian\n\t\t.*(storage, storage')\n\t\t#change it to matrix\n\n\n\n\n\n\n\n\tend\n\n\n\n\tfunction info_mat(betas::Vector,d)\n\n\tend\n\n\n\tfunction inv_Info(betas::Vector,d)\n\n\tend\n\n\n\n\t\"\"\"\n\tinverse of observed information matrix\n\t\"\"\"\n\tfunction inv_observedInfo(betas::Vector,d)\n\n\n\n\n\tend\n\n\t\"\"\"\n\tstandard errors\n\t\"\"\"\n\tfunction se(betas::Vector,d::Dict)\n\n\tend\n\n\t# function that maximizes the log likelihood without the gradient\n\t# with a call to `optimize` and returns the result\n\n# Check i( is intentional that the maximization is not so good)\n\tfunction maximize_like(x0=[0.8, 1.0, -1.0],meth=NelderMead())\n\t\tmaximum_like(betas) = loglik(betas, makeData())\n\t\t#maximum_like(betas) = (-1) * sum(log.(cdf.(makeData()[\"dist\"], (makeData()[\"X\"] * betas)) ^makeData()[\"y\"]) .+\n\t\t#\t\t(log.(1 .- cdf.(makeData()[\"dist\"], (makeData()[\"X\"] * betas)) ^(1 .- makeData()[\"y\"]))))\n\t\tnm = optimize(maximum_like, x0, meth)\n\t\treturn(nm)\n\tend\n\n\n\n\tfunction maximize_like_helpNM(x0=[ 1; 1.5; -0.5 ],meth=NelderMead())\n\n\n\n\tend\n\n\n\n\t# function that maximizes the log likelihood with the gradient\n\t# with a call to `optimize` and returns the result\n\tfunction maximize_like_grad(x0=[0.8,1.0,-0.1],meth=BFGS())\n\n\tend\n\n\n\tfunction maximize_like_grad_hess(x0=[0.8,1.0,-0.1],meth=Newton())\n\n\n\n\n\n\tend\n\n\tfunction maximize_like_grad_se(x0=[0.8,1.0,-0.1],meth=BFGS())\n\n\n\n\n\n\tend\n\n\n\t# visual diagnostics\n\t# ------------------\n\n\t# function that plots the likelihood\n\t# we are looking for a figure with 3 subplots, where each subplot\n\t# varies one of the parameters, holding the others fixed at the true value\n\t# we want to see whether there is a global minimum of the likelihood at the the true value\n\tfunction plotLike()\n\n\t\t# You want to call the loglik function for different vectors of beta and keep loglik in mind\n\t\t# increments = 0.01\n\t\ttotest_values = collect(-3.0:0.01:3.0)\n\t\t#for the first element\n\t\tj = zeros(length(totest_values))\n\n\t\td = makeData()\n\t\tb1 = d[\"beta\"][1]\n\t\tb2 = d[\"beta\"][2]\n\t\tb3 = d[\"beta\"][3]\n\t\tfor i=1:length(totest_values)\n\t\t\tbetas_calc = [totest_values[i], b2, b3]\n\t\t\tj[i] = loglik(betas_calc, d)\n\t\tend\n\t\tp1 = plot(totest_values, j,\n\t\t\tlab=\"B2 = 1.5 ; B3 = -0.5\",\n\t\t\txlabel = \"B1\")\n\n\t\t#for the second element\n\t\tj = zeros(length(totest_values))\n\t\tfor i=1:length(totest_values)\n\t\t\tj[i] = loglik([makeData()[\"beta\"][1], totest_values[i], makeData()[\"beta\"][3]],\n\t\t\t\t\tmakeData())\n\t\tend\n\t\tp2 = plot(totest_values, j,\n\t\t\tlab=\"B1 = 1.0 ; B3 = -0.5\",\n\t\t\txlabel = \"B2\", ylabel = \"Log Likelihood function\")\n\n\n\t\t#for the second element\n\t\tj = zeros(length(totest_values))\n\t\tfor i=1:length(totest_values)\n\t\t\tj[i] = loglik([makeData()[\"beta\"][1], makeData()[\"beta\"][2], totest_values[i]],\n\t\t\t\t\tmakeData())\n\t\tend\n\t\tp3 = plot(totest_values, j,\n\t\t\tlab=\"B1 = 1.0 ; B2 = 1.5\",\n\t\t\txlabel = \"B3\")\n\n\t\t# Plot final graph\n\t\tl = @layout [a; b; c]\n\t\treturn(plot(p1, p2, p3, layout = l))\n\tend\n\n\n\n\n\n\tfunction plotGrad()\n\t\t\t# You want to call the loglik function for different vectors of beta and keep loglik in mind\n\t\t\t# increments = 0.01\n\t\t\ttotest_values = collect(-2.0:0.01:2.0)\n\n# Element 1\n\t\t# reinitialize storage to true values\n\t\t\tbetas = makeData()[\"beta\"]\n\t\t\tstorage = zeros(3)\n\t\t\tj = zeros(length(totest_values))\n\t\t# run the function grad!() to get the gradient & extract the coef of interest\n\t\t\tfor i=1:length(totest_values)\n\t\t\t\tgrad!(storage, [totest_values[i], betas[2], betas[3]], makeData())\n\t\t\t\tj[i] = storage[1]\n\t\t\tend\n\t\t\tp1 = plot(totest_values, j,\n\t\t\t\tlab=\"B2 = 1.5 ; B3 = -0.5\",\n\t\t\t\txlabel = \"B1\")\n\n# Element 2\n\t\t\tbetas = makeData()[\"beta\"]\n\t\t\tstorage = zeros(3)\n\t\t\tj = zeros(length(totest_values))\n\t\t\tfor i=1:length(totest_values)\n\t\t\t\tgrad!(storage, [betas[1], totest_values[i], betas[3]], makeData())\n\t\t\t\tj[i] = storage[2]\n\t\t\tend\n\t\t\tp2 = plot(totest_values, j,\n\t\t\t\tlab=\"B1 = 1.0 ; B3 = -0.5\",\n\t\t\t\txlabel = \"B2\", ylabel = \"Log likelihood gradient\")\n\n# Element 3\n\t\t\tbetas = makeData()[\"beta\"]\n\t\t\tstorage = zeros(3)\n\t\t\tj = zeros(length(totest_values))\n\t\t\tfor i=1:length(totest_values)\n\t\t\t\tgrad!(storage, [betas[1], betas[2], totest_values[i]], makeData())\n\t\t\t\tj[i] = storage[3]\n\t\t\tend\n\t\t\tp3 = plot(totest_values, j,\n\t\t\t\tlab=\"B1 = 1.0 ; B2 = 1.5\",\n\t\t\t\txlabel = \"B3\")\n\t\t\t\tl = @layout [a; b; c]\n\t\t\treturn(plot(p1, p2, p3, layout = l))\n\t\tend\n\n\n\n\n\tfunction saveplots()\n\t\tp1 = plotLike()\n\t\tsavefig(p1,joinpath(dirname(@__FILE__),\"..\",\"likelihood.png\"))\n\t\tp2 = plotGrad()\n\t\tsavefig(p2,joinpath(dirname(@__FILE__),\"..\",\"gradient.png\"))\n\t\t@info(\"saved both plots.\")\n\tend\n\nend\n", "meta": {"hexsha": "8f1be331c669636546ce70fe543e5c3d32d8c04d", "size": 5987, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HWunconstrained.jl", "max_stars_repo_name": "jeannesorin/HWunconstrained.jl", "max_stars_repo_head_hexsha": "0806ee96f74c989d44e81b7d78559095cd092c43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HWunconstrained.jl", "max_issues_repo_name": "jeannesorin/HWunconstrained.jl", "max_issues_repo_head_hexsha": "0806ee96f74c989d44e81b7d78559095cd092c43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HWunconstrained.jl", "max_forks_repo_name": "jeannesorin/HWunconstrained.jl", "max_forks_repo_head_hexsha": "0806ee96f74c989d44e81b7d78559095cd092c43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2054263566, "max_line_length": 115, "alphanum_fraction": 0.6228495073, "num_tokens": 1974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7639989471520064}}
{"text": "line(x0, x1, x) = x0 + (x1-x0)*x\n\nfunction array2dist(xs :: AbstractArray{<:AbstractFloat})\n    len = length(xs)\n    @assert mod(len, 3) |> iszero\n\n    nmodes = len÷3\n    μs = xs[begin:nmodes]\n    σs = xs[nmodes+1:2nmodes]\n    ws = xs[2nmodes+1:end]\n    ws = ws ./ sum(ws)\n\n    return truncated(MixtureModel(Normal, zip(μs, σs) |> collect, ws), 0, Inf)\nend\n\nfunction target_function(image  :: AbstractArray{Bool},\n                         ncloud :: Integer,\n                         cutoff :: Integer)\n    cf = corrfn(image, cutoff)\n    p  = porosity(image)\n    s  = size(image)\n\n    return xs -> -likelihood(cf, s, p, array2dist(xs); ncloud = ncloud)\nend\n\n\"\"\"\n~~~~\nsandcorn_parameters(image; nmodes     = 1,\n                           ncloud     = 100,\n                           cutoff     = 100,\n                           iterations = 15,\n                           μ_bounds   = (0.0,  40.0),\n                           σ_bounds   = (1e-3, 10.0),\n                           w_bounds   = (0.05, 1.0))\n~~~~\n\nFind a distribution of radii in an image which consists of partially\noverlapping grains (like an slice of a sandstone). `nmodes` is an\nassumed number of modes in the distribution. The resulting\ndistribution can be constructed as\n`Truncated(MixtureModel(Normal, sandcorn_parameters(…)), 0, Inf)`.\n\"\"\"\nfunction sandcorn_parameters(image      :: AbstractArray{Bool};\n                             nmodes     :: Integer = 1,\n                             ncloud     :: Integer = 100,\n                             cutoff     :: Integer = 100,\n                             iterations :: Integer = 15,\n                             μ_bounds = (0.0,  40.0),\n                             σ_bounds = (1e-3, 10.0),\n                             w_bounds = (0.05, 1.0))\n    μ_lo, μ_hi = μ_bounds\n    σ_lo, σ_hi = σ_bounds\n    w_lo, w_hi = w_bounds\n\n    μ_lower = fill(μ_lo, nmodes)\n    σ_lower = fill(σ_lo, nmodes)\n    w_lower = fill(w_lo, nmodes)\n    μ_upper = fill(μ_hi, nmodes)\n    σ_upper = fill(σ_hi, nmodes)\n    w_upper = fill(w_hi, nmodes)\n\n    lower = vcat(μ_lower, σ_lower, w_lower)\n    upper = vcat(μ_upper, σ_upper, w_upper)\n    start = line.(lower, upper, rand(Float64, 3nmodes))\n\n    opt = optimize(target_function(image, ncloud, cutoff), start,\n                   ParticleSwarm(lower = lower, upper = upper),\n                   Optim.Options(show_trace = true,\n                                 show_every = 1,\n                                 iterations = iterations))\n    return opt |> Optim.minimizer |> array2dist\nend\n", "meta": {"hexsha": "bc04dbb343e89081ece45592544cac2faea91741", "size": 2529, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/optimize.jl", "max_stars_repo_name": "shamazmazum/Sandcorn.jl", "max_stars_repo_head_hexsha": "4256577eb51b7b1949aba259f875dd5c25abcca9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/optimize.jl", "max_issues_repo_name": "shamazmazum/Sandcorn.jl", "max_issues_repo_head_hexsha": "4256577eb51b7b1949aba259f875dd5c25abcca9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimize.jl", "max_forks_repo_name": "shamazmazum/Sandcorn.jl", "max_forks_repo_head_hexsha": "4256577eb51b7b1949aba259f875dd5c25abcca9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6438356164, "max_line_length": 78, "alphanum_fraction": 0.5195729537, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7639989395064122}}
{"text": "# Numerical_Integration.jl\r\n# Date: 28.06.2019. Created by Joshua Simon. \r\n\r\n# Define some functions you want to integrate\r\n\r\nfunction com_simpson(f, a, b, n)\r\n    # Composite Simpson's rule\r\n    # Integration of function f over interval [a,b] where n is\r\n    # the number of subintervals. Accuracy only depends on the \r\n    # number of subintervals.\r\n    \r\n    sum = 0\r\n\r\n    if(a > b)\r\n        println(\"ERROR: Lower interval bound a has to be smaller than upper bound b.\")\r\n        return 0\r\n    end\r\n\r\n    # Step length h\r\n    h = (b - a) / n\r\n\r\n    # Calculate integral value with composite simpson's rule\r\n    for k = 1:n\r\n\r\n        x_k = a + k * h\r\n\t\tx_k1 = a + (k - 1) * h\r\n\t\t\r\n\t\tsimpson = h/6 * ( f(x_k1) + f(x_k) + 4* f((x_k1 + x_k)/2) )\r\n\t\t\r\n        sum += simpson\r\n    end\r\n\r\n    return sum\r\n\r\nend\r\n\r\nintegral_k_1 = com_simpson(sin, 0.0, pi*2.0, 100000)\r\n\r\nprintln(integral_k_1)", "meta": {"hexsha": "78185bbd8ba0f1ff011ef02cbd6897de6504db49", "size": 889, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia.jl", "max_stars_repo_name": "SV-97/Numeric-Integration", "max_stars_repo_head_hexsha": "13099425112f2cb3b860787471218fcdbf773dac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-06-28T13:54:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-13T03:20:28.000Z", "max_issues_repo_path": "Julia.jl", "max_issues_repo_name": "SV-97/Numeric-Integration", "max_issues_repo_head_hexsha": "13099425112f2cb3b860787471218fcdbf773dac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia.jl", "max_forks_repo_name": "SV-97/Numeric-Integration", "max_forks_repo_head_hexsha": "13099425112f2cb3b860787471218fcdbf773dac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7948717949, "max_line_length": 87, "alphanum_fraction": 0.581552306, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7639989330887378}}
{"text": "# Simulate a Thomas cluster point process on a rectangle\n# Author: H. Paul Keeler, 2019.\n# Website: hpaulkeeler.com\n# Repository: github.com/hpaulkeeler/posts\n# For more details, see the post:\n# hpaulkeeler.com/testing-the-julia-language-with-point-process-simulations/\n\n#Note: Need the .+ for adding a scalar to an array\n#Also need . for sqrt, exp, cos, sin etc and assinging scalars to arrays\n#Best to use vectors instead of 1-D matrices eg x=rand(n),  NOT x=rand(n,1).\n\nusing Distributions #for random simulations\nusing Plots #for plotting\n\n#Simulation window parameters\nxMin=-.5;\nxMax=.5;\nyMin=-.5;\nyMax=.5;\n\n#Parameters for the parent and daughter point processes\nlambdaParent=10;#density of parent Poisson point process\nlambdaDaughter=10;#mean number of points in each cluster\nsigma=0.05; #sigma for normal variables (ie random locations) of daughters\n\n#Extended simulation windows parameters\nrExt=7*sigma; #extension parameter\n#for rExt, use factor of deviation sigma eg 6 or 7\nxMinExt=xMin-rExt;\nxMaxExt=xMax+rExt;\nyMinExt=yMin-rExt;\nyMaxExt=yMax+rExt;\n#rectangle dimensions\nxDeltaExt=xMaxExt-xMinExt;\nyDeltaExt=yMaxExt-yMinExt;\nareaTotalExt=xDeltaExt*yDeltaExt; #area of extended rectangle\n\n#Simulate Poisson point process\nnumbPointsParent=rand(Poisson(areaTotalExt*lambdaParent)); #Poisson number of points\n\n#x and y coordinates of Poisson points for the parent\nxxParent=xMinExt.+xDeltaExt*rand(numbPointsParent);\nyyParent=yMinExt.+yDeltaExt*rand(numbPointsParent);\n\n#Simulate Poisson point process for the daughters (ie final poiint process)\nnumbPointsDaughter=rand(Poisson(lambdaDaughter),numbPointsParent);\nnumbPoints=sum(numbPointsDaughter); #total number of points\n\n#Generate the (relative) locations in Cartesian coordinates by\n#simulating independent normal variables\nxx0=rand(Normal(0,sigma),numbPoints);\nyy0=rand(Normal(0,sigma),numbPoints);\n\n#replicate parent points (ie centres of disks/clusters)\nxx=vcat(fill.(xxParent, numbPointsDaughter)...);\nyy=vcat(fill.(yyParent, numbPointsDaughter)...);\n\n#Shift centre of disk to (xx0,yy0)\nxx=xx.+xx0;\nyy=yy.+yy0;\n\n#thin points if outside the simulation window\nbooleInside=((xx.>=xMin).&(xx.<=xMax).&(yy.>=yMin).&(yy.<=yMax));\n#retain points inside simulation window\nxx=xx[booleInside];\nyy=yy[booleInside];\n\n#Plotting\nplot1=scatter(xx,yy,xlabel =\"x\",ylabel =\"y\", leg=false);\ndisplay(plot1);\n", "meta": {"hexsha": "307dd4541670698dfbcb6ccf92fb483f9efc9065", "size": 2353, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "TestingJulia/ThomasClusterRectangle.jl", "max_stars_repo_name": "hpkeeler/posts", "max_stars_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2020-05-14T12:14:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:22:09.000Z", "max_issues_repo_path": "TestingJulia/ThomasClusterRectangle.jl", "max_issues_repo_name": "hpkeeler/posts", "max_issues_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TestingJulia/ThomasClusterRectangle.jl", "max_forks_repo_name": "hpkeeler/posts", "max_forks_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-10-26T01:22:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T17:33:40.000Z", "avg_line_length": 33.1408450704, "max_line_length": 84, "alphanum_fraction": 0.7807054824, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.763937636738313}}
{"text": "\n# Cross-correlation and convolution\nfunction FFTConvolution( image::Array{<:Real,N}, kernel::Array{<:Real,N}; typ=Float32 ) where {N}\n\treturn FFTConvolution!( image, kernel, zeros( typ, size(image).+size(kernel).-1) ); \nend\n\nfunction FFTConvolution!( image::Array{<:Real,N}, kernel::Array{<:Real,N}, conv::Array{T,N} ) where {T,N}\n\n\t@assert all( size(conv) .== size(image) .+ size(kernel) .- 1 ); \n\t\n\tpaddedkernel = zeros( Complex{T}, size(image) .+ size(kernel) .- 1 );\n\tpaddedkernel[ 1:size(kernel,1), 1:size(kernel,2), 1:size(kernel,3) ] .= convert.( Complex{T}, kernel )\n\n\tpaddedimage  = zeros( Complex{T}, size(image) .+ size(kernel) .- 1 );\n\tpaddedimage[ 1:size(image,1), 1:size(image,2), 1:size(image,3) ] .= convert.( Complex{T}, image )\n\n\tFFTW.fft!( paddedimage  );\n\tFFTW.fft!( paddedkernel );\n\n\t@inbounds @simd for idx in 1:length(paddedimage)\n\t\tpaddedimage[idx] = paddedimage[idx] * paddedkernel[idx]\n\tend\n\n\tFFTW.ifft!( paddedimage ); \n\n\t@inbounds @simd for idx in 1:length(paddedimage)\n\t\tconv[idx] = real( paddedimage[idx] )\n\tend\n\n\treturn conv\nend\n\n\nfunction FFTConvolution_crop( image::Array{<:Real,N}, kernel::Array{<:Real,N}; typ=Float32 ) where {N}\n\treturn FFTConvolution_crop!( image, kernel, zeros( typ, size(image) ) ); \nend\n\nfunction FFTConvolution_crop!( image::Array{<:Real,N}, kernel::Array{<:Real,N}, conv::Array{T,N} ) where {T,N}\n\n\t@assert all( size(conv) .== size(image) ); \n\t\n\tpaddedkernel = zeros( Complex{T}, size(image) .+ size(kernel) .- 1 );\n\tpaddedkernel[ 1:size(kernel,1), 1:size(kernel,2), 1:size(kernel,3) ] .= convert.( Complex{T}, kernel )\n\n\tpaddedimage  = zeros( Complex{T}, size(image) .+ size(kernel) .- 1 );\n\tpaddedimage[ 1:size(image,1), 1:size(image,2), 1:size(image,3) ] .= convert.( Complex{T}, image )\n\n\tFFTW.fft!( paddedimage  );\n\tFFTW.fft!( paddedkernel );\n\n\t@inbounds @simd for idx in 1:length(paddedimage)\n\t\tpaddedimage[idx] = paddedimage[idx] * paddedkernel[idx]\n\tend\n\n\tFFTW.ifft!( paddedimage ); \n\n\toffs = div.( size( kernel ), 2 ); \n\tzoff = ( N == 2 ) ? 0 : offs[3]; \n\n\n\tfor zet in 1+zoff:size(image,3)+zoff, col in 1+offs[2]:size(image,2)+offs[2]\n\t\t@simd for row in 1+offs[1]:size(image,1)+offs[1]\n\t\t\tconv[row-offs[1],col-offs[2],zet-zoff] = real( paddedimage[row,col,zet] )\n\tend end\n\n\treturn conv\nend\n\nfunction FFTConvolution_b( image::Array{T1,2}, kernel::Array{T2,2}; typ=Float32 ) where {T1<:Real,T2<:Real}\n\n\tpaddedkernel = zeros( typ, size(image) .+ size(kernel) .- 1 );\n\tpaddedkernel[ 1:size(kernel,1), 1:size(kernel,2) ] .= convert.( typ, kernel )\n\n\tpaddedimage  = zeros( typ, size(image) .+ size(kernel) .- 1 );\n\tpaddedimage[ 1:size(image,1), 1:size(image,2) ] .= convert.( typ, image )\n\n\tFf = FFTW.fft( paddedimage  );\n\tFg = FFTW.fft( paddedkernel );\n\n\tFcorr =  Ff .* Fg;\n\n\treturn real.( FFTW.bfft( Fcorr ) )\nend\n\n\nfunction paddedConvolution( image::Array{T1,2}, kernel::Array{T2,2}; typ=Float32 ) where {T1<:Real,T2<:Real}\n\n\tN1, N2 = size( image  );\n\tM1, M2 = size( kernel );\n\n\tpaddedImage = similar(image, N1+2*M1-2, N2+2*M2-2);\n\tpaddedImage[ M1:(M1+N1-1), M2:(M2+N2-1) ] .= image;\n\n\tcorrmatrix = zeros( typ, N1 + M1 - 1, N2 + M2 - 1 )\n\n\tfor col in 1:( N2 + M2 - 1)\n\t\tfor row in 1:( N1 + M1 - 1 )\n\t\t\tcorrmatrix[ row, col ] = sum( paddedImage[ row:row+M1-1, col:col+M2-1 ] .* kernel )\n\t\tend\n\tend\n\treturn corrmatrix\nend", "meta": {"hexsha": "6085095e2410a82413285407878eeb92e746eb09", "size": 3285, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FFTconvolutions.jl", "max_stars_repo_name": "BrucePBon/ImageAnalysis", "max_stars_repo_head_hexsha": "7d1be7ca49ce1d45ec5b29bdbd0200ada404cef4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FFTconvolutions.jl", "max_issues_repo_name": "BrucePBon/ImageAnalysis", "max_issues_repo_head_hexsha": "7d1be7ca49ce1d45ec5b29bdbd0200ada404cef4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FFTconvolutions.jl", "max_forks_repo_name": "BrucePBon/ImageAnalysis", "max_forks_repo_head_hexsha": "7d1be7ca49ce1d45ec5b29bdbd0200ada404cef4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2058823529, "max_line_length": 110, "alphanum_fraction": 0.6480974125, "num_tokens": 1139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.76393763524468}}
{"text": "# Naive Bayes Module\n\nmodule NB\nexport NaiveBayes, train, predict\n\n\"\"\"\nData structure for Naive Bayes\\\\\n`pY` is probability for each target\\\\\n`mean` is the corresponding mean of Xi for each taregt\\\\\n`var` is the corresponding variance of Xi for each target\n\"\"\"\nmutable struct NaiveBayes\n    n_features::Integer\n    pY::Dict{Number,AbstractFloat}\n    mean::Dict{Number,Array{AbstractFloat}}\n    var::Dict{Number,Array{AbstractFloat}}\nend\n\n\"\"\"\nTraining function for Naive Bayes\\\\\n`X_data` has shape (M,N)\\\\\n`Y_data` has shape (M,)\\\\\nReturns the computed data structure `NaiveBayes`\n\"\"\"\nfunction train(X_data::Array{T} where T<:Number, Y_data::Array{K} where K<:Number)::NaiveBayes\n    @assert ndims(X_data) == ndims(Y_data) + 1\n    @assert size(X_data)[1] == size(Y_data)[1]\n    n_features = size(X_data)[2]\n    # compute probability of Y\n    pY = Dict{Number,AbstractFloat}()\n    for Y_val in Y_data\n        if haskey(pY, Y_val)\n            pY[Y_val] += 1.0\n        else\n            pY[Y_val] = 1.0\n        end\n    end\n    for Y_val in keys(pY)\n        pY[Y_val] /= size(Y_data)[1]\n    end\n    # compute Xi mean and var for each Y\n    mean = Dict{Number,Array{AbstractFloat}}()\n    var = Dict{Number,Array{AbstractFloat}}()\n    for Y_val in keys(pY)\n        X_part = X_data[Y_data .== Y_val, :]\n        mean[Y_val] = vec(sum(X_part, dims=1) ./ size(X_part)[1])\n        var[Y_val] = vec(sum((X_part .- reshape(mean[Y_val], 1, :)).^2, dims=1) ./ size(X_part)[1])\n    end\n    return NaiveBayes(n_features, pY, mean, var)\nend\n\n\"\"\"\nVectorized gaussian function\\\\\nReturns the product of P(xi|y)\n\"\"\"\nfunction gaussian(X_vec::Array, mean::Array, var::Array)::AbstractFloat\n    @assert ndims(X_vec) == ndims(mean) == ndims(var) == 1\n    @assert length(X_vec) == length(mean) == length(var)\n    left = 1.0 ./ sqrt.((2.0 * pi) .* var)\n    right = exp.(-(X_vec .- mean).^2 ./ (2.0 .* var))\n    p = left .* right\n    return prod(p)\nend\n\n\"\"\"\nPredict function for Naive Bayes\\\\\n`X_data` has ndims of 1 or 2\n\"\"\"\nfunction predict(X_data::Array{T} where T<:Number, data::NaiveBayes)::Array\n    if ndims(X_data) == 1\n        X_data = reshape(X_data, 1, :)\n    end\n    @assert ndims(X_data) == 2\n    @assert size(X_data)[2] == data.n_features\n    prediction = Array{Number}(undef, size(X_data)[1])\n    for i in 1:size(X_data)[1]\n        X_vec = X_data[i, :]\n        Y_dict = Dict{Number,AbstractFloat}()\n        for Y_val in keys(data.pY)\n            Y_dict[Y_val] = data.pY[Y_val] * gaussian(X_vec, data.mean[Y_val], data.var[Y_val])\n        end\n        prediction[i] = sort(collect(Y_dict), by=m->m[2], rev=true)[1][1]\n    end\n    return prediction\nend\n\nend", "meta": {"hexsha": "529d96988bb2c96f3cb734018c4c1c2e935ccc6e", "size": 2638, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Naive_Bayes/script.jl", "max_stars_repo_name": "teamclouday/JuliaLearn", "max_stars_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Naive_Bayes/script.jl", "max_issues_repo_name": "teamclouday/JuliaLearn", "max_issues_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Naive_Bayes/script.jl", "max_forks_repo_name": "teamclouday/JuliaLearn", "max_forks_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3218390805, "max_line_length": 99, "alphanum_fraction": 0.6277482942, "num_tokens": 826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7639376293423213}}
{"text": "function initial_velocity(data, np)\n    constante = -2*data.R*data.T/data.m\n    p=[rand() for i in 1:np]\n    vmod =  [sqrt(constante * log(1-p[i])) for i in 1:np]\n    angle = [2*pi*rand() for i in 1:np]   \nreturn [ [vmod[i]*cos(angle[i]), vmod[i]*sin(angle[i])] for i in 1:np ], vmod\nend\n\n\n\n\n    ", "meta": {"hexsha": "ac074e98483b0b0ff55ecd441d9f60a9cc7e6773", "size": 296, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/velocidades.jl", "max_stars_repo_name": "ljduarte/Simulacoes.jl", "max_stars_repo_head_hexsha": "c6581596f0abc79b342d6c2a2cfcfe5ef8353d0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/velocidades.jl", "max_issues_repo_name": "ljduarte/Simulacoes.jl", "max_issues_repo_head_hexsha": "c6581596f0abc79b342d6c2a2cfcfe5ef8353d0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/velocidades.jl", "max_forks_repo_name": "ljduarte/Simulacoes.jl", "max_forks_repo_head_hexsha": "c6581596f0abc79b342d6c2a2cfcfe5ef8353d0d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6666666667, "max_line_length": 77, "alphanum_fraction": 0.5810810811, "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9511422255326288, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7639325054346913}}
{"text": "# p17.jl - Helmholtz eq. u_xx + u_yy + (k^2)u = f\n#         on [-1,1]x[-1,1]    (compare p16.jl)\n\n# Set up spectral grid and tensor product Helmholtz operator:\nN = 24; (D,x) = cheb(N); y = x;\nxx = x[2:N]; yy = y[2:N];\nf = @. exp(-10*((yy-1)^2+(xx'-.5)^2));\nD2 = D^2; D2 = D2[2:N,2:N]; I = eye(N-1);\nk = 9;\nL = kron(I,D2) + kron(D2,I) + k^2*eye((N-1)^2);\n\n# Solve for u, reshape to 2D grid, and plot:\nu = L\\f[:];\nuu = zeros(N+1,N+1); uu[N:-1:2,N:-1:2] = reshape(u,N-1,N-1);\nxxx = yyy = -1:.0333:1;\ns = Spline2D(x[end:-1:1],y[end:-1:1],uu);\nuuu = evalgrid(s,xxx,yyy);\nfigure(1); clf(); surf(xxx,yyy,uuu,rstride=1,cstride=1);\nxlabel(\"x\"); ylabel(\"y\"); zlabel(\"u\"); view(-37.5,30);\nvalue = signif(uu[Int(N/2+1),Int(N/2+1)],10);\ntext3D(.2,1,.022,\"u(0,0) = $value\");\nfigure(2); clf(); contour(xxx,yyy,uuu,10); axis(\"square\");\n", "meta": {"hexsha": "1567f9a5248ad156772c3ae681ef9421871887d6", "size": 820, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p17.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p17.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p17.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.652173913, "max_line_length": 61, "alphanum_fraction": 0.5451219512, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7639324998729753}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots, LaTeXStrings\n\tRandom.seed!(1)\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.21\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\tcUnif = Uniform(0,2π)\n\txGrid, N = 0:0.1:2π, 10^6\nend\n\n# ╔═╡ 287be85a-2165-11eb-2609-eba593feae95\nbegin\n\tstephist( rand(N)*2π, bins=xGrid, \n\t\tnormed=:true, c=:blue, \n\t\tlabel=\"MC Estimate\")\n\tplot!( xGrid, pdf.(cUnif,xGrid), \n\t\tc=:red,ylims=(0,0.2),label=\"PDF\", ylabel=\"Density\",xticks=([0:π/2:2π;],\n\t\t[\"0\", L\"\\dfrac{\\pi}{2}\", L\"\\pi\", L\"\\dfrac{3\\pi}{2}\", L\"2\\pi\"]))\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.21\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═287be85a-2165-11eb-2609-eba593feae95\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "00e221648b3d43b4136098a13825d1b3b0a42733", "size": 1156, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.21.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.21.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.21.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.1304347826, "max_line_length": 73, "alphanum_fraction": 0.7006920415, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8774767746654976, "lm_q1q2_score": 0.7639288772233744}}
{"text": "using ModelingToolkit, DiffEqOperators, LinearAlgebra, OrdinaryDiffEq\nusing ModelingToolkit: operation, istree, arguments\n\n# Define some variables\n@parameters t x\n@variables u(..) v(..)\nDt = Differential(t)\nDx = Differential(x)\nDxx = Differential(x)^2\neqs  = [Dt(u(t,x)) ~ Dxx(u(t,x)), \n        Dt(v(t,x)) ~ Dxx(v(t,x))]\nbcs = [u(0,x) ~ - x * (x-1) * sin(x),\n       v(0,x) ~ - x * (x-1) * sin(x),\n       u(t,0) ~ 0.0, u(t,1) ~ 0.0,\n       v(t,0) ~ 0.0, v(t,1) ~ 0.0]\n\ndomains = [t ∈ IntervalDomain(0.0,1.0),\n           x ∈ IntervalDomain(0.0,1.0)]\n\npdesys = PDESystem(eqs,bcs,domains,[t,x],[u(t,x),v(t,x)])\ndiscretization = MOLFiniteDifference([x=>0.1],t;grid_align=edge_align)\nprob = discretize(pdesys,discretization) # This gives an ODEProblem since it's time-dependent\nsol = solve(prob,Tsit5())\n\n@parameters t x y\n@variables u(..)\nDxx = Differential(x)^2\nDyy = Differential(y)^2\nDt = Differential(t)\nt_min= 0.\nt_max = 2.0\nx_min = 0.\nx_max = 2.\ny_min = 0.\ny_max = 2.\n\n# 3D PDE\neq  = Dt(u(t,x,y)) ~ Dxx(u(t,x,y)) + Dyy(u(t,x,y))\n\nanalytic_sol_func(t,x,y) = exp(x+y)*cos(x+y+4t)\n# Initial and boundary conditions\nbcs = [u(t_min,x,y) ~ analytic_sol_func(t_min,x,y),\n       u(t,x_min,y) ~ analytic_sol_func(t,x_min,y),\n       u(t,x_max,y) ~ analytic_sol_func(t,x_max,y),\n       u(t,x,y_min) ~ analytic_sol_func(t,x,y_min),\n       u(t,x,y_max) ~ analytic_sol_func(t,x,y_max)]\n\n# Space and time domains\ndomains = [t ∈ IntervalDomain(t_min,t_max),\n           x ∈ IntervalDomain(x_min,x_max),\n           y ∈ IntervalDomain(y_min,y_max)]\npdesys = PDESystem([eq],bcs,domains,[t,x,y],[u(t,x,y)])\n\n# Method of lines discretization\ndx = 0.1; dy = 0.2\ndiscretization = MOLFiniteDifference([x=>dx,y=>dy],t)\nprob = ModelingToolkit.discretize(pdesys,discretization)\nsol = solve(prob,Tsit5())\n\n# Diffusion in a sphere\n@parameters t r\n@variables u(..)\nDt = Differential(t)\nDr = Differential(r)\nDrr = Dr^2\neq  = Dt(u(t,r)) ~ (1/r^2 * Dr(r^2 * Dr(u(t,r))))\nbcs = [u(0,r) ~ - r * (r-1) * sin(r),\n       Dr(u(t,0)) ~ 0.0, u(t,1) ~ sin(1)]\n\ndomains = [t ∈ IntervalDomain(0.0,1.0),\n           r ∈ IntervalDomain(0.0,1.0)]\n\npdesys = PDESystem(eq,bcs,domains,[t,r],[u(t,r)])\ndiscretization = MOLFiniteDifference([r=>0.1],t)\nprob = discretize(pdesys,discretization) # This gives an ODEProblem since it's time-dependent\nsol = solve(prob,Tsit5())\n", "meta": {"hexsha": "cc966e8ae15b9360bda74f4680a22a1b726d0b80", "size": 2319, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/MOL/MOLtest.jl", "max_stars_repo_name": "JordiBolibar/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "4913718c9ff2c0fe1613b7274e63e7bf048221d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/MOL/MOLtest.jl", "max_issues_repo_name": "JordiBolibar/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "4913718c9ff2c0fe1613b7274e63e7bf048221d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/MOL/MOLtest.jl", "max_forks_repo_name": "JordiBolibar/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "4913718c9ff2c0fe1613b7274e63e7bf048221d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1168831169, "max_line_length": 93, "alphanum_fraction": 0.6287192755, "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7638818235872948}}
{"text": "precision(proposal, goldstandard) =\n    num_common_cons(proposal, goldstandard) / num_cons(proposal)\nrecall(proposal, goldstandard) =\n    num_common_cons(proposal, goldstandard) / num_cons(goldstandard)\nf1_measure(proposal, goldstandard) =\n    2 * precision(proposal, goldstandard) * recall(proposal, goldstandard) /\n       (precision(proposal, goldstandard) + recall(proposal, goldstandard))\n\n\"number of constituents of tree\"\nfunction num_cons(tree::Tree)\n    M = boolean_dependency_matrix(tree)\n    count(x->x, M)\nend\n\n\"number of common constituents\"\nfunction num_common_cons(tree1::Tree, tree2::Tree)\n    A = boolean_dependency_matrix(tree1)\n    B = boolean_dependency_matrix(tree2)\n    sum(a && b for (a,b) in zip(A,B))\nend\n\n\"number of crossed bracket pairs\"\nfunction num_crossed_brackets(tree1, tree2)\n    num_cons(tree1) - num_common_cons(tree1, tree2)\nend\n\n# t1 = tree(\"[0maj[0maj[0maj][1maj]][0maj[7maj][0maj]]]\")\n# t2 = tree(\"[0maj[1maj[2min][1maj]][0maj[7maj][0maj]]]\")\n# t3 = tree(\"[0maj[0maj][0maj[0maj][0maj[7maj][0maj]]]]\")\n#\n# num_crossed_brackets(t1, t3)\n", "meta": {"hexsha": "284797db66f2428899cd32ddc86e951946d97113", "size": 1071, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GeneralizedChartparsing/src/tools/tree_evaluation.jl", "max_stars_repo_name": "yblainm/FragmentGrammar.jl", "max_stars_repo_head_hexsha": "3ae13bffd2d11824e0f32091cce20f44e871547a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-03-27T16:51:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-24T00:20:58.000Z", "max_issues_repo_path": "src/GeneralizedChartparsing/src/tools/tree_evaluation.jl", "max_issues_repo_name": "yblainm/FragmentGrammar.jl", "max_issues_repo_head_hexsha": "3ae13bffd2d11824e0f32091cce20f44e871547a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GeneralizedChartparsing/src/tools/tree_evaluation.jl", "max_forks_repo_name": "yblainm/FragmentGrammar.jl", "max_forks_repo_head_hexsha": "3ae13bffd2d11824e0f32091cce20f44e871547a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.46875, "max_line_length": 76, "alphanum_fraction": 0.7226890756, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7638818110316464}}
{"text": "# p15.jl - solve eigenvalue BVP u_xx = lambda*u, u(-1)=u(1)=0\n\nN = 36; (D,x) = cheb(N); D2 = D^2; D2 = D2[2:N,2:N];\n(lam,V) = eig(D2);\nii = sortperm(-lam);          # sort eigenvalues and -vectors\nlam = lam[ii]; V = V[:,ii]; clf();\nfor j = 5:5:30                  # plot 6 eigenvectors\n    u = [0;V[:,j];0]; subplot(7,1,j/5)\n    plot(x,u,\".\",markersize=6); grid(true);\n    xx = -1:.01:1; uu = polyval(polyfit(x,u),xx);\n    plot(xx,uu); axis(\"off\");\n    text(-.4,.1,\"eig $j = $(lam[j]*4/pi^2) π^2/4\");\n    text(.7,.1,\"$(signif(4*N/(pi*j),2))  ppw\");\nend\n", "meta": {"hexsha": "6d9802b485ba299daafcb5d61b4baa72369c419c", "size": 553, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p15.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p15.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p15.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8666666667, "max_line_length": 61, "alphanum_fraction": 0.4972875226, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545274901875, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7638638096867909}}
{"text": "N=10000000\ncnt=0\nfor i = 1:N\n    x=rand()\n    y=rand()\n    if x^2+y^2<1.0\n        cnt+=1\n    end\nend\n\n@printf \"Estimate of PI for %d trials is %8.5f\\n\" N 4.0*(cnt / N)", "meta": {"hexsha": "8e1382ecaf55d8aac0fccb94b9e8afdb303132e1", "size": 167, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "masteringJulia/monte.jl", "max_stars_repo_name": "terasakisatoshi/juliaExer", "max_stars_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-02T01:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-04T12:03:25.000Z", "max_issues_repo_path": "masteringJulia/monte.jl", "max_issues_repo_name": "terasakisatoshi/juliaExer", "max_issues_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "masteringJulia/monte.jl", "max_forks_repo_name": "terasakisatoshi/juliaExer", "max_forks_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.1818181818, "max_line_length": 65, "alphanum_fraction": 0.5269461078, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9481545289551958, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7638637998051316}}
{"text": "using Plots\nusing Formatting\n\nfunction logistic(r,x)\n    r*x*(1.0-x)\nend\n\nfunction logisticmap(;x0=0.2,r=4,n=10)\n    results = [(x0,logistic(r,x0))];\n    for i in 1:(n-1)\n      xold = results[end][2]\n      xnew = logistic(r,xold)\n      append!(results,[(xold,xold)])\n      append!(results,[(xold,xnew)])\n  end\n  results\nend\n\nfunction vary(dname;x0_vals=[],r_vals=[], nvals=[])\n if !isdir(dname)\n  mkdir(dname)\n end\n fno = 1\n for x0 in x0_vals\n  for r in r_vals\n      for n in nvals\n          fname = format(dname*\"/frame{:05d}.png\",fno)\n          fno = fno + 1\n          simres = logisticmap(x0=x0, r=r, n=n)\n          xvals = [x for (x, y) in simres]\n          yvals = [y for (x, y) in simres]\n          plot(xvals,yvals,legend=false,xaxis=false,yaxis=false,xlim=(0,1),ylim=(0,1));\n          savefig(fname)\n        end\n    end\nend\nend\n\n\n# name/number each iteration then plot 1, 1+2, 1+2+3 ...\n\n\n# To make frames varying r, specify x0_vals as an array with a single value\n# along with whatever values of r you want to loop through\nvary(\"frames_r\";x0_vals=[0.5],r_vals=0:0.1:5, n=[100])\n\n# To make frames varying x0, specify r_vals as an array with a single value\n# along with whatever values of x0 you want to loop through\nvary(\"frames_x0\";x0_vals=0:0.05:1,r_vals=[4.0], n=[100])\n\nvary(\"frames_n\";x0_vals=[0.2],r_vals=[4], nvals = 1:500)\n\nr_vals = 4.1\nvary(\"loop3\";x0_vals=[(r_vals+sqrt(r_vals-4)*sqrt(r_vals))/(2*r_vals)],r_vals=[4], nvals=1:10)\n\nvary(\"loop2\";x0_vals=[(r_vals-sqrt(r_vals-4)*sqrt(r_vals))/(2*r_vals)],r_vals=[4], nvals=1:10)\n\nffmpeg -i frame%05d.png -vf \"fps=12,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse\" -loop 0 output.gif\n", "meta": {"hexsha": "06b26133f092557f4ab7520c1feb78ee4f847d4f", "size": 1651, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code/week_two-graph_animation/new_graphs/single_iteration_graph.jl", "max_stars_repo_name": "lwlss/MacPherson_2020", "max_stars_repo_head_hexsha": "cf4a3903d234a31ae3a445bb016fe744c381ed65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/week_two-graph_animation/new_graphs/single_iteration_graph.jl", "max_issues_repo_name": "lwlss/MacPherson_2020", "max_issues_repo_head_hexsha": "cf4a3903d234a31ae3a445bb016fe744c381ed65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/week_two-graph_animation/new_graphs/single_iteration_graph.jl", "max_forks_repo_name": "lwlss/MacPherson_2020", "max_forks_repo_head_hexsha": "cf4a3903d234a31ae3a445bb016fe744c381ed65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9830508475, "max_line_length": 105, "alphanum_fraction": 0.633555421, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7637986998064249}}
{"text": "# # Control\n\n#-\n\n# A simple control problem on a system usually involves a variable $x(t)$\n# that denotes the state of the system over time, and a variable $u(t)$ that\n# denotes the input into the system over time. Linear constraints are used to\n# capture the evolution of the system over time:\n#\n# $$\n# x(t) = Ax(t - 1) + Bu(t), \\ \\text{for} \\ t = 1,\\ldots, T,\n# $$\n#\n# where the numerical matrices $A$ and $B$ are called the dynamics and input matrices,\n# respectively.\n#\n# The goal of the control problem is to find a sequence of inputs\n# $u(t)$ that will allow the state $x(t)$ to achieve specified values\n# at certain times. For example, we can specify initial and final states of the system:\n#\n# $$\n# \\begin{aligned}\n#   x(0) &= x_i \\\\\n#   x(T) &= x_f\n# \\end{aligned}\n# $$\n#\n# Additional states between the initial and final states can also be specified. These\n# are known as waypoint constraints. Often, the input and state of the system will\n# have physical meaning, so we often want to find a sequence inputs that also\n# minimizes a least squares objective like the following:\n#\n# $$\n#   \\sum_{t = 0}^T \\|Fx(t)\\|^2_2 + \\sum_{t = 1}^T\\|Gu(t)\\|^2_2,\n# $$\n#\n# where $F$ and $G$ are numerical matrices.\n#\n# We'll now apply the basic format of the control problem to an example of controlling\n# the motion of an object in a fluid over $T$ intervals, each of $h$ seconds.\n# The state of the system at time interval $t$ will be given by the position and the velocity of the\n# object, denoted $p(t)$ and $v(t)$, while the input will be forces\n# applied to the object, denoted by $f(t)$.\n# By the basic laws of physics, the relationship between force, velocity, and position\n# must satisfy:\n#\n# $$\n#   \\begin{aligned}\n#     p(t+1) &= p(t) + h v(t) \\\\\n#     v(t+1) &= v(t) + h a(t)\n#   \\end{aligned}.\n# $$\n#\n# Here, $a(t)$ denotes the acceleration at time $t$, for which we we use\n# $a(t) = f(t) / m + g - d v(t)$,\n# where $m$, $d$, $g$ are constants for the mass of the object, the drag\n# coefficient of the fluid, and the acceleration from gravity, respectively.\n#\n# Additionally, we have our initial/final position/velocity conditions:\n#\n# $$\n#   \\begin{aligned}\n#     p(1) &= p_i\\\\\n#     v(1) &= v_i\\\\\n#     p(T+1) &= p_f\\\\\n#     v(T+1) &= 0\n#   \\end{aligned}\n# $$\n#\n# One reasonable objective to minimize would be\n#\n# $$\n#   \\text{objective} = \\mu \\sum_{t = 1}^{T+1} (v(t))^2 + \\sum_{t = 1}^T (f(t))^2\n# $$\n#\n# We would like to keep both the forces small to perhaps save fuel, and keep\n# the velocities small for safety concerns.\n# Here $\\mu$ serves as a parameter to control which part of the objective we\n# deem more important, keeping the velocity small or keeping the force small.\n#\n# The following code builds and solves our control example:\n\nusing Convex, SCS, Plots\n\n## Some constraints on our motion\n## The object should start from the origin, and end at rest\ninitial_velocity = [-20; 100]\nfinal_position = [100; 100]\n\nT = 100 # The number of timesteps\nh = 0.1 # The time between time intervals\nmass = 1 # Mass of object\ndrag = 0.1 # Drag on object\ng = [0, -9.8] # Gravity on object\n\n## Declare the variables we need\nposition = Variable(2, T)\nvelocity = Variable(2, T)\nforce = Variable(2, T - 1)\n\n## Create a problem instance\nmu = 1\n\n## Add constraints on our variables\nconstraints = Constraint[\n    position[:, i+1] == position[:, i] + h * velocity[:, i] for i in 1:T-1\n]\n\nfor i in 1:T-1\n    acceleration = force[:, i] / mass + g - drag * velocity[:, i]\n    push!(constraints, velocity[:, i+1] == velocity[:, i] + h * acceleration)\nend\n\n## Add position constraints\npush!(constraints, position[:, 1] == 0)\npush!(constraints, position[:, T] == final_position)\n\n## Add velocity constraints\npush!(constraints, velocity[:, 1] == initial_velocity)\npush!(constraints, velocity[:, T] == 0)\n\n## Solve the problem\nproblem = minimize(sumsquares(force), constraints)\nsolve!(problem, SCS.Optimizer; silent_solver = true)\n\n# We can plot the trajectory taken by the object.\n\npos = evaluate(position)\nplot([pos[1, 1]], [pos[2, 1]], st = :scatter, label = \"initial point\")\nplot!([pos[1, T]], [pos[2, T]], st = :scatter, label = \"final point\")\nplot!(pos[1, :], pos[2, :], label = \"trajectory\")\n\n# We can also see how the magnitude of the force changes over time.\n\nplot(vec(sum(evaluate(force) .^ 2, dims = 1)), label = \"force (magnitude)\")\n", "meta": {"hexsha": "9fe0644fdf121959dd8edd7faf78f0b6ac775bec", "size": 4335, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/general_examples/control.jl", "max_stars_repo_name": "baggepinnen/Convex.jl", "max_stars_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 327, "max_stars_repo_stars_event_min_datetime": "2015-01-22T01:00:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T16:42:11.000Z", "max_issues_repo_path": "docs/examples_literate/general_examples/control.jl", "max_issues_repo_name": "baggepinnen/Convex.jl", "max_issues_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 275, "max_issues_repo_issues_event_min_datetime": "2015-01-12T19:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-05T19:05:45.000Z", "max_forks_repo_path": "docs/examples_literate/general_examples/control.jl", "max_forks_repo_name": "baggepinnen/Convex.jl", "max_forks_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 121, "max_forks_repo_forks_event_min_datetime": "2015-01-23T21:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T13:58:39.000Z", "avg_line_length": 31.875, "max_line_length": 100, "alphanum_fraction": 0.6629757785, "num_tokens": 1279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7637986965154961}}
{"text": "using SummationByParts\ninclude(\"nodecalc3.jl\")\n\nfunction nodecalc(sbp::TriSBP, isDG::Bool)\n  vtx = [0.0 0; 1 0; 0 1]  # why is this 0 to 1 but the other method is -1 to 1\n  r1 = vtx[1, :]\n  r2 = vtx[2, :]\n  r3 = vtx[3, :]\n\n  T = zeros(2,2)\n  T[:, 1] = r2 - r1\n  T[:, 2] = r3 - r1\n\n\n  if isDG\n    coords = SummationByParts.SymCubatures.calcnodes(sbp.cub, vtx)\n  else\n    coords = calcnodes(sbp, vtx)\n  end\n\n  xi = zeros(coords)\n\n  for i=1:size(coords,2)\n    xi[:, i] = T\\(coords[:, i] - r1)\n  end\n\n  return xi, coords\nend\n\nfunction nodecalc(sbp::TetSBP, isDG::Bool)\n\n  vtx = [-1.0 -1.0 -1.0\n        1.0 -1.0 -1.0\n       -1.0 1.0 -1.0\n       -1.0 -1.0 1.0]\n\n  r1 = vtx[1, :]\n  r2 = vtx[2, :]\n  r3 = vtx[3, :]\n  r4 = vtx[4, :]\n  T = zeros(3,3)\n  T[:, 1] = r2 - r1\n  T[:, 2] = r3 - r1\n  T[:, 3] = r4 - r1\n\n\n  if isDG\n    coords = SummationByParts.SymCubatures.calcnodes(sbp.cub, vtx)\n  else\n    coords = calcnodes(sbp, vtx)\n  end\n\n  xi = zeros(coords)\n\n  for i=1:size(coords,2)\n    xi[:, i] = T\\(coords[:, i] - r1)\n  end\n\n  return xi, coords\nend\n\n\nfunction minNodeDist(sbp, isDG::Bool)\n# get the minimum distance between nodes on a reference element of degree p\n\n    xi, coords = nodecalc(sbp, isDG)\n    min_dist = typemax(Float64)\n#    println(\"coords = \", coords)\n    for i=1:size(coords, 2)\n      for j=(i+1):size(coords, 2)\n\t# calculate distance between node i and node j\n\tdist_j = norm(coords[:, i] - coords[:, j])\n\n\tif dist_j < min_dist\n\t  min_dist = dist_j\n\tend\n\n      end  # end loop j\n    end  # end loop i\n\n#    println(\"for p=$p elements, min node distance = \", min_dist)\n  \n  return min_dist\nend\n\n# sbp = TriSBP{Float64}(degree=1, reorder=false, internal=false)\n# sbp = getTriSBPWithDiagE(degree=4)\n# xi, coords = nodecalc(sbp, true)\n# printCaseStatement(xi)\n# printBaryCoords(xi, coords)\n# writedlm(\"coordsout.dat\", coords, ' ')\n#minNodeDist(2)\n", "meta": {"hexsha": "d2ab19f809109b354e16a49b18ea67273521c06a", "size": 1854, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nodecalc.jl", "max_stars_repo_name": "OptimalDesignLab/PumiInterface.jl", "max_stars_repo_head_hexsha": "ca2cfe4cdb35958921ffc3748387772db4406901", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-07-10T18:10:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-30T06:16:59.000Z", "max_issues_repo_path": "src/nodecalc.jl", "max_issues_repo_name": "OptimalDesignLab/PumiInterface.jl", "max_issues_repo_head_hexsha": "ca2cfe4cdb35958921ffc3748387772db4406901", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2015-09-30T16:29:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-04T21:47:17.000Z", "max_forks_repo_path": "src/nodecalc.jl", "max_forks_repo_name": "OptimalDesignLab/PumiInterface.jl", "max_forks_repo_head_hexsha": "ca2cfe4cdb35958921ffc3748387772db4406901", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.935483871, "max_line_length": 79, "alphanum_fraction": 0.5965480043, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7637021609223256}}
{"text": "# Methods from Moukalled et al. FVM - OpenFOAM, Matlab\n\nmutable struct Cell\n    faceIndices::Vector{Int64}\n    pointIndices::Vector{Int64}\nend\n\n######################### Mesh/Cell Geometry ###########################\nfunction triangleCentroid(points)\n    center = [ 0.0, 0.0, 0.0 ]\n    nPts = size(points, 1)\n    for pt in 1:nPts\n        center = center .+ points[pt]\n    end\n    center /= nPts\n\n    return center\nend\n\n#Alternate name for same function\ngeometricCenter = triangleCentroid\n\nfunction triangleArea(points::Array{Array{Float64, 1}})\n    side1 = points[2] .- points[1]\n    side2 = points[3] .- points[1]\n    fAVec = cross(side1, side2) ./ 2\n    return fAVec\nend\n\n#=\n    Calculates face area vector and centroid from the points that make up the face\n    Points must be ordered sequentially\n\n    How it works:\n        1. Splits face into subtriangles\n        2. Area and centroid is computed for each subtriangle\n        3. Areas vectors are summed and returned\n        4. The centroid returned is obtained from an area-weighted of sum of the subtriangle centroids\n=#\nfunction faceAreaCentroid(points::Array{Array{Float64, 1}})\n    gC = geometricCenter(points)\n    nPts = size(points, 1)\n\n    fAVec = [ 0.0, 0.0, 0.0 ]\n    centroid = [ 0.0, 0.0, 0.0 ]\n\n    for i in 1:nPts\n        if i < nPts\n            subTriPts = [ gC, points[i], points[i+1] ]\n        else\n            subTriPts = [ gC, points[i], points[1] ]\n        end\n\n        triCentroid = triangleCentroid(subTriPts)\n        subFAVec = triangleArea(subTriPts)\n\n        fAVec += subFAVec\n        centroid += triCentroid .* mag(subFAVec)\n    end\n\n    centroid /= mag(fAVec)\n\n    return fAVec, centroid\nend\n\n#=\n    Calculates cell volume (scalar) and centroid (vector) from the points and face area vectors (fAVecs) that make up the cell\n        fAVecs can be computed using the faceAreaCentroids function\n\n    How it works:\n        1. Splits cell into polygonal pyramids, each incorporating a single face and the geometric center of the cell\n        2. Computes volume and centroid of each sub-pyramid\n        3. Resulting volume is sum of sub-pyramid volumes, centroid is the volume-weighted sum of sub-pyramid centroids\n=#\nfunction cellVolCentroid(points, fAVecs, faceCentroids)\n    gC = geometricCenter(points)\n    nFaces = size(fAVecs,1)\n\n    vol = 0.0\n    centroid = [ 0.0, 0.0, 0.0 ]\n\n    for f in 1:nFaces\n        cellCenterVec = faceCentroids[f] .- gC\n        subPyrVol = abs(sum(fAVecs[f] .* cellCenterVec) / 3)\n        subPyrCentroid = 0.75.*faceCentroids[f] .+ 0.25.*gC\n\n        vol += subPyrVol\n        centroid += subPyrCentroid .* subPyrVol\n    end\n\n    centroid /= vol\n\n    return vol, centroid\nend\n\n# For each face, calculates the vectors from its owner and neighbour cell centers to its own center\nfunction cellCentroidToFaceVec(faceCentroids::Array{Array{Float64, 1}}, cellCentroids::Array{Array{Float64, 1}})\n    #TODO: Understand ordering to make sure we're accepting faces in the order we need to pass them back in??\n    nFaces = size(faceCentroids, 1)\n\n    cellToFaceVec = zeros(nFaces, 3)\n\n    for f in 1:nFaces\n        cellToFaceVec[f,:] = faceCentroids[f] - cellCentroids\n    end\n\n    return cellToFaceVec\nend\n\n######################### Utility Functions ###########################\n# Returns basic info about the mesh: nCells, nFaces, nBoundaries, nBdryFaces\nfunction unstructuredMeshInfo(mesh::Mesh)\n    nCells = size(mesh.cells, 1)\n    nFaces = size(mesh.faces, 1)\n    nBoundaries = size(mesh.boundaryFaces, 1)\n\n    # Count boundary faces\n    nBdryFaces = 0\n    for bdry in 1:nBoundaries\n        nBdryFaces += size(mesh.boundaryFaces[bdry], 1)\n    end\n\n    return nCells, nFaces, nBoundaries, nBdryFaces\nend\n\n# Checks whether a string represents a number (using a regular expression)\nfunction isNumber(str)\n    re = r\"^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$\"\n    return occursin(re, str)\nend\n\n######################### Parse OpenFOAM Meshes ###########################\n#=\n    In the points, faces, owner, and neighbour files, the beginning of useful information in the file looks like this:\n\n        ...\n        object      faces;\n        }\n        // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //\n\n\n        5135\n        (\n        4(79 1516 1380 37)\n        4(1381 1422 1249 39)\n        ...\n\n    The 5135 indicates how many lines of information follow it.\n    This function would return 5135, and the line number of the first piece of information in the file ((line number of 5135) + 2)\n=#\nfunction OFFile_FindNItems(fileLines)\n    nLines = size(fileLines, 1)\n    lineCounter = 1\n    itemCount = 0\n    startLine = 0\n    for line in fileLines\n        if isNumber(strip(line))\n            itemCount = parse(Int64, line)\n            startLine = lineCounter+2\n            break\n        end\n        lineCounter += 1\n    end\n    return startLine, itemCount\nend\n\n#=\n    Takes the file path to an OpenFOAM mesh 'points' file, returns a 2D array of point coordinates:\n            X   Y   Z\n        P1  x1  y1  z1\n        P2  x2  y2  z2\n        ...\n=#\nfunction readOFPointsFile(filePath)\n    f = open(filePath)\n    pointsLines = readlines(f)\n    startLine, pCount = OFFile_FindNItems(pointsLines)\n\n    points = zeros(pCount, 3)\n    for line in startLine:(startLine+pCount-1)\n        pLine = pointsLines[line]\n\n        bracketsRemoved = pLine[2:end-1]\n        coords = split(bracketsRemoved)\n        for d in 1:3\n            points[line+1-startLine, d] = parse(Float64, coords[d])\n        end\n    end\n\n    return points\nend\n\n#=\n    Takes the file path to an OpenFOAM mesh 'faces' file, returns a 1D array of 1D arrays.\n    Each entry in the upper level array represents a single face\n    Each face-array contains the indices of the points that make up that face\n    Note that all indices from the file are incremented by 1, to switch from OpenFOAM's 0-based indexing to Julia's 1-based indexing\n\n    Example return value:\n        [ [face1_pt1Index, face1_pt2Index, face1_pt3Index], [face2_pt1Index, face2_pt2Index, face2_pt3Index, face2_pt4Index], ... ]\n=#\nfunction readOFFacesFile(filePath)\n    f = open(filePath)\n    facesLines = readlines(f)\n    startLine, fCount = OFFile_FindNItems(facesLines)\n\n    faces = []\n    for line in startLine:(startLine+fCount-1)\n        fLine = facesLines[line]\n        facePts = []\n\n        bracketIndex = findfirst(\"(\", fLine)[1]\n        bracketsRemoved = fLine[bracketIndex+1:end-1]\n        ptNumbers = split(bracketsRemoved)\n        nPts = length(ptNumbers)\n        for p in 1:nPts\n            # Add one to convert to 1-based indexing\n            push!(facePts, parse(Int64, ptNumbers[p])+1)\n        end\n        push!(faces, facePts)\n    end\n\n    return faces\nend\n\n#=\n    Takes the file path to an OpenFOAM 'owner' file, returns a 1D array of owner cell indices\n    Example return value:\n        [ face1_ownerCellIndex, face2_ownerCellIndex, ...  ]\n=#\nfunction readOFOwnerFile(filePath)\n    f = open(filePath)\n    ownerLines = readlines(f)\n    startLine, oCount = OFFile_FindNItems(ownerLines)\n\n    faceOwnerCells = zeros(Int64, oCount)\n    for line in startLine:(startLine+oCount-1)\n        # Add one to convert to 1-based indexing\n        faceOwnerCells[line-startLine+1] = parse(Int64, ownerLines[line])+1\n    end\n\n    return faceOwnerCells\nend\n\n#=\n    Takes the file path to an OpenFOAM 'neighbour' file, returns a 1D array of neighbour cell indices\n    Note that all indices from the file are incremented by 1, to switch from OpenFOAM's 0-based indexing to Julia's 1-based indexing\n\n    Example return value:\n        [ face1_neighbourCellIndex, face2_neighbourCellIndex, ...  ]\n=#\nfunction readOFNeighbourFile(filePath)\n    f = open(filePath)\n    neighbourLines = readlines(f)\n    startLine, nCount = OFFile_FindNItems(neighbourLines)\n\n    faceNeighbourCells = zeros(Int64, nCount)\n    for line in startLine:(startLine+nCount-1)\n        # Add one to convert to 1-based indexing\n        faceNeighbourCells[line-startLine+1] = parse(Int64, neighbourLines[line])+1\n    end\n\n    return faceNeighbourCells\nend\n\n#=\n    Returns index of first line containing str\n    Otherwise returns -1\n=#\nfunction findInLines(str, lines, startLine)\n    nLines = size(lines, 1)\n    for i in startLine:nLines\n        if occursin(str, lines[i])\n            return i\n        end\n    end\n    return -1\nend\n\n#=\n    Takes the file path to an OpenFOAM 'boundary' file, returns 3 arrays:\n    boundaryNames:          Array of boundary names (strings)\n    boundaryNumFaces:       Array containing the number of faces in each boundary\n    boundaryStartFaces:     Array containing the index of the first face in the boundary (boundaries always occupy a continuous sequence of face indices, and are usually numbered last)\n=#\nfunction readOFBoundaryFile(filePath)\n    f = open(filePath)\n    bLines = readlines(f)\n    startLine, bCount = OFFile_FindNItems(bLines)\n    nLines = size(bLines, 1)\n\n    boundaryNames = Array{String, 1}(undef, bCount)\n    boundaryStartFaces = Array{Int64, 1}(undef, bCount)\n    boundaryNumFaces = Array{Int64, 1}(undef, bCount)\n    for i in 1:bCount\n        bNameLine = findInLines(\"{\", bLines, startLine)-1\n        boundaryNames[i] = strip(bLines[bNameLine])\n\n        bNFacesLine = findInLines(\"nFaces\", bLines, startLine)\n        boundaryNumFaces[i] = parse(Int64, split(bLines[bNFacesLine])[2][1:end-1])\n\n        bStartFaceLine = findInLines(\"startFace\", bLines, startLine)\n        boundaryStartFaces[i] = parse(Int64, split(bLines[bStartFaceLine])[2][1:end-1])+1\n\n        startLine = findInLines(\"}\", bLines, startLine)+1\n    end\n\n    return boundaryNames, boundaryNumFaces, boundaryStartFaces\nend\n\n#=\n    Input: Path to an OpenFOAM mesh FOLDER.\n    Output: Calls readOFPoints/Faces/Owner/NeighbourFile and returns all of their results (reads all OpenFOAM's mesh file data into arrays)\n=#\nfunction readOpenFOAMMesh(polyMeshPath)\n    println(\"Reading mesh: $polyMeshPath\")\n    pointsFilePath = \"$polyMeshPath/points\"\n    points = readOFPointsFile(pointsFilePath)\n    facesFilePath = \"$polyMeshPath/faces\"\n    faces = readOFFacesFile(facesFilePath)\n    ownerFilePath = \"$polyMeshPath/owner\"\n    owner = readOFOwnerFile(ownerFilePath)\n    neighbourFilePath = \"$polyMeshPath/neighbour\"\n    neighbour = readOFNeighbourFile(neighbourFilePath)\n    boundaryFilePath = \"$polyMeshPath/boundary\"\n    boundaryNames, boundaryNumFaces, boundaryStartFaces = readOFBoundaryFile(boundaryFilePath)\n\n    return points, faces, owner, neighbour, boundaryNames, boundaryNumFaces, boundaryStartFaces\nend\n\n#=\n    Function used to find all the points in each cell.\n    Not required for CFD, which is face-based, but required for cell-based .vtk file output.\n\n    Input: Path to an OpenFOAM mesh FOLDER.\n    Returns:\n        points:         Array of points obtained from readOFPoints()\n        cellPtIndices:  Array of arrays, where each subarrary represents a cell, and each entry in a cell's array is the index of one of its points\n=#\nfunction OpenFOAMMesh_findCellPts(polyMeshPath)\n    pointLocations, pointIndicesByFace, faceOwnerCellIndices, faceNeighborCellIndices, boundaryNames, boundaryNumFaces, boundaryStartFaces = readOpenFOAMMesh(polyMeshPath)\n    nCells = maximum(faceOwnerCellIndices)\n    nFaces = size(pointIndicesByFace, 1)\n    nBoundaries = size(boundaryNames, 1)\n\n    # Output\n    cells = Array{Cell, 1}(undef, nCells)\n    for i in eachindex(cells)\n        cells[i] = Cell(Vector{Int64}(undef, 0), Vector{Int64}(undef, 0))\n    end\n\n    ### Populate the cells array ###\n    function addCellFaceIndices(adjacentCellList)\n        nFaces = length(adjacentCellList)\n        for f in 1:nFaces\n            ownerCellIndex = adjacentCellList[f]\n            push!(cells[ownerCellIndex].faceIndices, f)\n        end\n    end\n\n    # Start by a just adding face indices, want to order the points appropriately before adding them\n    addCellFaceIndices(faceOwnerCellIndices)\n    addCellFaceIndices(faceNeighborCellIndices)\n\n    function addAllNewPoints!(cell::Cell, faceIndex)\n        for pointIndex in pointIndicesByFace[faceIndex]\n            if !any(x->x==pointIndex, cell.pointIndices)\n                push!(cell.pointIndices, pointIndex)\n            end\n        end\n    end\n\n    function disjoint(f1Points, f2Points)\n        allPoints = vcat(f1Points, f2Points)\n        pointSet = Set(allPoints)\n        return length(allPoints) == length(pointSet)\n    end\n\n    function intersection(points1, points2)\n        return intersect(Set(points1), Set(points2))\n    end\n\n    function index(element, array)\n        for i in eachindex(array)\n            if element == array[i]\n                return i\n            end\n        end\n        return -1\n    end            \n\n    function addEdges!(cellPoints, facePoints, endFacePoints, endFacePointsSet, unusedFaces, pointOffset=4)\n        oppositeFaceIndex = -1\n        for i in 1:length(unusedFaces)\n            fi = unusedFaces[i]\n            fiPoints = pointIndicesByFace[fi]\n            commonPoints = intersection(fiPoints, facePoints)\n\n            if length(commonPoints) == 2\n                # These two points form an edge connecting faces one and two\n                points = collect(commonPoints)\n\n                if points[1] in endFacePointsSet\n                    p1 = points[1]\n                    p2 = points[2]\n                else\n                    p1 = points[2]\n                    p2 = points[1]\n                end\n\n                position = index(p1, endFacePoints) # Find position over the point on the face one side\n                if position == -1\n                    throw(ErrorException(\"Point $p1 not found in $endFacePoints\"))\n                end\n                cellPoints[ position + pointOffset ] = p2 # The point on the face two side goes in the matching spot\n            else\n                oppositeFaceIndex = i # This is the face opposite to the one containing facePoints\n            end\n        end\n        return oppositeFaceIndex\n    end\n\n    function populatePointIndices_Tet!(cell::Cell)\n        # For a tetrahedron, the order of points is unimportant\n        # And all points from an arbitrary face\n        addAllNewPoints!(cell, cell.faceIndices[1])\n\n        # Choose another face, it will contain the fourth point we need to complete the tetrahedron\n        addAllNewPoints!(cell, cell.faceIndices[2])\n    end\n\n    function populatePointIndices_Pyramid!(cell::Cell)\n        # Pyramids need to have the points that make up their square base ordered 1-4, with the tip of the pyramid coming last\n        # Find the quad face\n        for faceIndex in cell.faceIndices\n            if length(pointIndicesByFace[faceIndex]) == 4\n                addAllNewPoints!(cell, faceIndex)\n\n                # There is only one square face, and all other faces contain the pyramid tip\n                # Find any other face and add its points to make the pyramid tip the final point\n                if faceIndex != cell.faceIndices[1]\n                    addAllNewPoints!(cell, cell.faceIndices[1])\n                else\n                    addAllNewPoints!(cell, cell.faceIndices[2])\n                end\n\n                # All done\n                break\n            end\n        end\n    end\n\n    function populatePointIndices_Wedge!(cell::Cell)\n        # Wedges need the triangular faces numbered 1-3 and 4-6 respectively, where 1 is aligned with 4, 2 with 5, and 3 with 6\n        # Using similar strategy it to that used for hex cells: Identify two end faces, then use the faces that connect them to ensure their points are aligned\n        \n        # First identify the two triangular faces, keep track of one and get rid of the other\n        unusedFaces = deepcopy(cell.faceIndices)\n        t1 = -1 # Triangular face one, we will base the ordering off this one\n\n        for j in 1:2\n            for i in eachindex(unusedFaces)\n                faceIndex = unusedFaces[i]\n                \n                if length(pointIndicesByFace[faceIndex]) == 3\n                    # Found a triangular face\n                    if t1 == -1\n                        t1 = faceIndex\n                    end\n                    deleteat!(unusedFaces, i)\n                    break\n                end\n            end\n        end\n\n        if length(unusedFaces) != 3\n            throw(ErrorException(\"Expected three quadrilateral faces remaining after removal of two triangular end faces, got $(length(unusedFaces))\"))\n        end\n\n        t1Points = pointIndicesByFace[t1]\n        t1PointsSet = Set(t1Points)\n        cell.pointIndices = vcat(t1Points, [0, 0, 0]) # Still have to determine proper ordering of points in the other triangular end face, 0's will be replaced below\n\n        # Now all the remaining faces (3) will be quadrilaterals connecting the two triangular end faces\n        q1 = pop!(unusedFaces) # Select one at random\n        q1Points = pointIndicesByFace[q1] \n        addEdges!(cell.pointIndices, q1Points, t1Points, t1PointsSet, unusedFaces, 3) # Use it to populate 2/3 of the unknown points\n\n        q2 = pop!(unusedFaces) # Select another at random\n        q2Points = pointIndicesByFace[q2]\n        addEdges!(cell.pointIndices, q2Points, t1Points, t1PointsSet, unusedFaces, 3) # Use it to populate the last unknown point\n    end\n\n    function populatePointIndices_Hex!(cell::Cell)\n        # Need to order point such that the points that make up a single quadrilateral face are ordered 1-4\n            # The face opposite to it must have its points ordered 5-8, with point 1 connected to/aligned with point 5, 2 with 6, etc...\n            # We will accomplish this by first picking a starting face at random, this face's points will be numbered 1-4\n            # Then we will identify its opposite face and remove it\n            # Then all the remaining faces form the connections between the first face we picked and its opposite Face\n            # Pairs of these faces will contain 0 or 2 points in common\n                # When zero, they are opposite each other\n                # When two, they are adjacent and the two points they have in common form an edge connecting the two end faces\n                    # This indicates that these two points should be aligned, and is used to properly order the remaining points\n\n        # Start by choosing an arbitrary face\n        unusedFaces = deepcopy(cell.faceIndices)\n        f1 = pop!(unusedFaces)\n        f1Points = pointIndicesByFace[f1]\n        f1PointsSet = Set(f1Points)\n\n        # Find the opposite face (no points in common) and remove it\n        for i in 1:length(unusedFaces)\n            fi = unusedFaces[i]\n            fiPoints = pointIndicesByFace[fi]\n\n            if disjoint(f1Points, fiPoints)\n                deleteat!(unusedFaces, i)\n                break\n            end\n        end\n\n        ### Now find the correct orientation\n            # Point f1_i needs to be aligned (spatially) with Point f2_i\n            # We can check for this by using one of the other faces as a guide, since it forms part of the connection between f1 and f2\n        cell.pointIndices = vcat(f1Points, [0, 0, 0, 0])\n\n        # Pick an arbitrary other face\n        f3 = pop!(unusedFaces)\n        f3Points = pointIndicesByFace[f3]\n        lastFace = addEdges!(cell.pointIndices, f3Points, f1Points, f1PointsSet, unusedFaces)\n        \n        # Add points from the edges of the face opposite f3\n        lastFacePoints = pointIndicesByFace[unusedFaces[lastFace]]\n        deleteat!(unusedFaces, lastFace)        \n        noResult = addEdges!(cell.pointIndices, lastFacePoints, f1Points, f1PointsSet, unusedFaces)\n\n        if noResult != -1\n            throw(ErrorException(\"Failure to appropriately order hexahedral cell points for writing to .vtk\"))\n        end\n    end\n\n    # Now use the face indices to gather and order each cell's points appropriately\n        # Correct point ordering is important for .vtk output: (See figure 2) https://vtk.org/wp-content/uploads/2015/04/file-formats.pdf\n    for cell in cells\n        nFaces = length(cell.faceIndices)\n        if nFaces == 4\n            populatePointIndices_Tet!(cell)\n        elseif nFaces == 5\n            quadFaceCount = 0\n\n            for f in cell.faceIndices\n                if length(pointIndicesByFace[f]) == 4\n                    quadFaceCount += 1\n                end\n            end\n\n            if quadFaceCount == 1\n                populatePointIndices_Pyramid!(cell)\n            elseif quadFaceCount == 3\n                populatePointIndices_Wedge!(cell)\n            else\n                throw(ErrorException(\"Unrecognized cell type, cell: $cell. Expecting only hex, tet, wedge, or pyramid cells for vtk output.\"))\n            end\n        elseif nFaces == 6\n            populatePointIndices_Hex!(cell)\n        end\n    end\n\n    return pointLocations, cells\nend\n\n#=\n    Reads an OpenFOAM mesh and returns a Mesh object suitable for calculations in FvCFD.jl.\n\n    Mesh defined in dataStructures.jl, documented in dataStructureDefintions.md\n=#\nfunction OpenFOAMMesh(polyMeshPath)\n    points, OFfaces, owner, neighbour, boundaryNames, boundaryNumFaces, boundaryStartFaces = readOpenFOAMMesh(polyMeshPath)\n    nCells = maximum(owner)\n    nFaces = size(OFfaces, 1)\n    nBoundaries = size(boundaryNames, 1)\n\n    cells = Array{Array{Int64, 1}, 1}(undef, nCells)                # Indices of faces that make up a cell\n    cVols = zeros(nCells)                                           # Cell Volumes\n    cCenters = Array{Array{Float64, 1}, 1}(undef, nCells)           # Cell Centroids\n    cellSizes = Matrix{Float64}(undef, nCells, 3)                   # Cell sizes (x,y,z) direction\n\n    faces = Array{Array{Int64, 1}, 1}(undef, nFaces)                # Indices of cells adjacent to each face always owner first, then neighbour\n    fAVecs = Array{Array{Float64, 1}, 1}(undef, nFaces)             # Face Area Vectors\n    fCenters = Array{Array{Float64, 1}, 1}(undef, nFaces)           # Face Centroids\n    boundaryFaces = Array{Array{Int64, 1}, 1}(undef, nBoundaries)   # Indices of faces that make up each boundary\n\n    # Calculate face area vectors and face centroids from list of points in each face\n    for f in 1:nFaces\n        fPts = [ points[pt,:] for pt in OFfaces[f] ]\n        fAVecs[f], fCenters[f] = faceAreaCentroid(fPts)\n    end\n    #fAVecs and fCenters now complete\n\n    # Build 'cells' and 'faces' arrays from info from 'owner' file\n    nOwners = size(owner, 1)\n    for f in 1:nOwners\n        ownerCell = owner[f]\n        if isassigned(cells, ownerCell)\n            push!(cells[ownerCell], f)\n        else\n            cells[ownerCell] = [f,]\n        end\n\n        faces[f] = [ownerCell, -1]\n    end\n\n    # Finish building 'cells' and 'faces' arrays, adding info from 'neighbour' file\n    nNeighbours = size(neighbour, 1)\n    for f in 1:nNeighbours\n        neighbourCell = neighbour[f]\n        if isassigned(cells, neighbourCell)\n            push!(cells[neighbourCell], f)\n        else\n            cells[neighbourCell] = [f,]\n        end\n\n        faces[f][2] = neighbourCell\n    end\n    # fAVecs, fCenters, faces, cells now complete\n\n    # For each cell, use the face area vectors and face centroids for all of its faces, to calculate it's volume and centroid location\n    for c in 1:nCells\n        pts = []\n        for f in cells[c]\n            for pt in OFfaces[f]\n                if !(points[pt,:] in pts)\n                    push!(pts, points[pt,:])\n                end\n            end\n        end\n        fCs = [ fCenters[f] for f in cells[c] ]\n        cell_fAVecs = [ fAVecs[f] for f in cells[c] ]\n\n        cVols[c], cCenters[c] = cellVolCentroid(pts, cell_fAVecs, fCs)\n    end\n    # fAVecs, fCenters, faces, cells, cVols, cCenters now complete\n\n    # Create boundaryFaces array\n    for b in 1:nBoundaries\n        startF = boundaryStartFaces[b]\n        endF = startF + boundaryNumFaces[b] - 1\n        boundaryFaces[b] = Array(startF:endF)\n    end\n\n    # Compute cell sizes in the x, y, z directions\n    # In the past, cell sizes were used for a shitty CFL calculation, may be able to get rid of them now\n    maxCoords = [ -1000000.0, -1000000.0, -1000000.0 ]\n    minCoords = [ 1000000.0, 1000000.0, 1000000.0 ]\n    for c in 1:nCells\n        fill!(maxCoords, -10000000)\n        fill!(minCoords, 10000000)\n\n        pts = Vector{Vector{Float64}}()\n\n        # Add points\n        for f in cells[c]\n            for pt in OFfaces[f]\n                if !any(x->x==pt, pts)\n                    push!(pts, points[pt, :])\n                end\n            end\n        end\n\n        for pt in pts\n            for d in 1:3\n                maxCoords[d] = max(maxCoords[d], pt[d])\n                minCoords[d] = min(minCoords[d], pt[d])\n            end\n        end\n\n        for d in 1:3\n            cellSizes[c,d] = maxCoords[d] - minCoords[d]\n        end\n    end\n\n    return Mesh(cells, cVols, cCenters, cellSizes, faces, fAVecs, fCenters, boundaryFaces)\nend\n", "meta": {"hexsha": "122a4ce99e29443a78e5f4438dc400f5677892cd", "size": 24864, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mesh.jl", "max_stars_repo_name": "henrystoldt/fvCFD", "max_stars_repo_head_hexsha": "07afc193631af9c9d445df30a3528cd13cef580e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2021-03-18T05:40:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T21:15:01.000Z", "max_issues_repo_path": "src/mesh.jl", "max_issues_repo_name": "GodotMisogi/FvCFD.jl", "max_issues_repo_head_hexsha": "07afc193631af9c9d445df30a3528cd13cef580e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mesh.jl", "max_forks_repo_name": "GodotMisogi/FvCFD.jl", "max_forks_repo_head_hexsha": "07afc193631af9c9d445df30a3528cd13cef580e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-07-27T15:16:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T02:09:33.000Z", "avg_line_length": 36.350877193, "max_line_length": 184, "alphanum_fraction": 0.6338481338, "num_tokens": 6463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7636999041660034}}
{"text": "\"\"\"\n    Cylinder(x, y, zmin, zmax, radius)\n\nCreate a `Cylinder` that can be used for spatial lookup.\n\nSee also `AbstractRegion`\n\"\"\"\nstruct Cylinder{T <: Real} <: AbstractRegion{T}\n    x::T\n    y::T\n    zmin::T\n    zmax::T\n    radius::T\nend\n\n\"\"\"\n    volume(cylinder::Cylinder)\n\nReturns the volume of the `cylinder`.\n\"\"\"\n@inline function volume(cylinder::Cylinder)\n    π * cylinder.radius * cylinder.radius * (cylinder.zmax - cylinder.zmin)\nend\n\nfunction boundingbox(cylinder::Cylinder{T}) where T\n    xmin = cylinder.x - cylinder.radius\n    xmax = cylinder.x + cylinder.radius\n    ymin = cylinder.y - cylinder.radius\n    ymax = cylinder.y + cylinder.radius\n    return BoundingBox{T}(xmin, ymin, cylinder.zmin, xmax, ymax, cylinder.zmax)\nend\n\nfunction in(p::StaticVector{3, <:Real}, cylinder::Cylinder)\n    r² = cylinder.radius * cylinder.radius\n    Δx = p[1] - cylinder.x\n    Δy = p[2] - cylinder.y\n    return Δx*Δx + Δy*Δy <= r² && p[3] >= cylinder.zmin && p[3] <= cylinder.zmax\nend", "meta": {"hexsha": "556a628eb85ad30fffed9d22378d97bc8ba7ee97", "size": 982, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Cylinder.jl", "max_stars_repo_name": "greghislop/RoamesGeometry.jl", "max_stars_repo_head_hexsha": "cea24fff1dcc8222a79fbffd2c0171ad006776c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-02-09T04:45:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T16:43:30.000Z", "max_issues_repo_path": "src/Cylinder.jl", "max_issues_repo_name": "greghislop/RoamesGeometry.jl", "max_issues_repo_head_hexsha": "cea24fff1dcc8222a79fbffd2c0171ad006776c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-12-07T03:32:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T22:12:57.000Z", "max_forks_repo_path": "src/Cylinder.jl", "max_forks_repo_name": "FugroRoames/RoamesGeometry.jl", "max_forks_repo_head_hexsha": "f50c95447b26e3c7a6bb96e5d54edd8c31fb4427", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-02-13T11:59:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-08T20:55:17.000Z", "avg_line_length": 25.8421052632, "max_line_length": 80, "alphanum_fraction": 0.6598778004, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462514578343, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7636999022071984}}
{"text": "#\n# asian-option.jl\n#\nfunction run-asian(N = 100000, PutCall = 'C';) \n# European Asian option.  \n# Uses geometric or arithmetic average.\n# Euler and Milstein discretization for Black-Scholes.\n# Option features.\n  println(\"Setting option parameters\");\n  S0  = 100;      # Spot price\n  K   = 100;      # Strike price\n  r   = 0.05;     # Risk free rate\n  q   = 0.0;      # Dividend yield\n  v   = 0.2;      # Volatility\n  tma = 0.25;     # Time to maturity\n\n  Averaging = 'A';  # 'A'rithmetic or 'G'eometric\n  OptType = (PutCall == 'C' ? \"CALL\" : \"PUT\");\n  println(\"Option type is $OptType\");\n# Simulation settings.\n  println(\"Setting simulation parameters\");\n  T = 100;         # Number of time steps\n  dt = tma/T;      # Time increment\n\n# Initialize the terminal stock price matrices\n# for the Euler and Milstein discretization schemes.\n S = zeros(Float64,N,T);\n  for n=1:N\n    \tS[n,1] = S0;\n  end\n\n# Simulate the stock price under the Euler and Milstein schemes.\n# Take average of terminal stock price.\n  println(\"Looping $N times.\");\n  A = zeros(Float64,N);\n  for n=1:N\n    \tfor t=2:T\n      \t\tdW = (randn(1)[1])*sqrt(dt);\n     \t\t z0 = (r - q - 0.5*v*v)*S[n,t-1]*dt;\n     \t\t z1 = v*S[n,t-1]*dW;\n      \t\tz2 = 0.5*v*v*S[n,t-1]*dW*dW;\n      \t\tS[n,t] = S[n,t-1] + z0 + z1 + z2;\n   \t end\n   \t if cmp(Averaging,'A') == 0\n      \t\tA[n] = mean(S[n,:]);\n   \t elseif cmp(Averaging,'G') == 0\n      \t\tA[n] = exp(mean(log(S[n,:])));\n   \t end\n  end\n\n# Define the payoff\n  P = zeros(Float64,N);\n  if cmp(PutCall,'C') == 0\n    \tfor n = 1:N\n      \t\tP[n] = max(A[n] - K, 0);\n  \t  end\n  elseif cmp(PutCall,'P') == 0\n    \tfor n = 1:N\n     \t\t P[n] = max(K - A[n], 0);\n   \t end\n  end\n# Calculate the price of the Asian option\n AsianPrice = exp(-r*tma)*mean(P);\n @printf \"Price: %10.4f\\n\" AsianPrice;\nend\n\nrun-asian()\n\n", "meta": {"hexsha": "9b3bf4c7df970ef7c3161de839db80628a6e9071", "size": 1794, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Module 3/Chapter01/asian-option.jl", "max_stars_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_stars_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2017-02-12T15:36:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T03:30:39.000Z", "max_issues_repo_path": "Module 3/Chapter01/asian-option.jl", "max_issues_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_issues_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Module 3/Chapter01/asian-option.jl", "max_forks_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_forks_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-02-10T16:19:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T11:46:44.000Z", "avg_line_length": 26.0, "max_line_length": 64, "alphanum_fraction": 0.5646599777, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705932, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7636998995770691}}
{"text": "@doc raw\"\"\"\n    ℛ(z::Number, tableau::AbstractButcherTableau) :: Number\n    ℛ(z::Number, solver::AbstractRungeKuttaSolver) :: Number\n\nreturns the stability function of an [`AbstractRungeKuttaSolver`](@ref):\n```math\n    R(z) = \\frac{\\det(I - z(A - \\mathbb{1}b^\\intercal))}{\\det(I - zA)}.\n```\n\"\"\"\nfunction ℛ(z::Number, tableau::AbstractButcherTableau)\n    @↓ A, b, s = tableau\n    e = ones(s)\n    return det(I - z * (A - e * b')) / det(I - z * A)\nend\nℛ(z::Number, solver::AbstractRungeKuttaSolver) = ℛ(z, solver.tableau)\n\n\"\"\"\n    ℛ(Z::AbstractMatrix, tableau::AbstractButcherTableau) :: AbstractMatrix\n    ℛ(Z::AbstractMatrix, solver::AbstractRungeKuttaSolver) :: AbstractMatrix\n\nreturns the stability function of an [`AbstractRungeKuttaSolver`](@ref).\n\"\"\"\nfunction ℛ(Z::AbstractMatrix, tableau::AbstractButcherTableau)\n    @↓ A, b, s = tableau\n    e = ones(s)\n    tmp = kron(e, Z)\n    tmp = (I - kron(A, Z)) \\ tmp\n    tmp = kron(b', Matrix(1.0I, size(Z)...)) * tmp\n    return I + tmp\nend\nℛ(Z::AbstractMatrix, solver::AbstractRungeKuttaSolver) = ℛ(Z, solver.tableau)\n", "meta": {"hexsha": "fa267a4c9438ecd27ccb978eb11d98c870c51612", "size": 1065, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stability.jl", "max_stars_repo_name": "antonuccig/RungeKutta.jl", "max_stars_repo_head_hexsha": "7476b73367240e17776dc56613bb6ce69f9448bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-30T17:45:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T17:45:14.000Z", "max_issues_repo_path": "src/stability.jl", "max_issues_repo_name": "antonuccig/RungeKutta.jl", "max_issues_repo_head_hexsha": "7476b73367240e17776dc56613bb6ce69f9448bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stability.jl", "max_forks_repo_name": "antonuccig/RungeKutta.jl", "max_forks_repo_head_hexsha": "7476b73367240e17776dc56613bb6ce69f9448bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.28125, "max_line_length": 77, "alphanum_fraction": 0.6507042254, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7636998948973227}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, DataFrames, Plots\n\tRandom.seed!(0)\nend;\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.14\"\n\n# ╔═╡ 1aa41898-3afa-11eb-2f49-570853ce6435\nbegin\n\tlambda = 0.1\n\tdist = Exponential(1/lambda)\n\tactualMedian = median(dist)\n\n\tM = 10^3\n\tN = 10^4\n\tnRange = 2:2:10\n\talpha = 0.05\nend\n\n# ╔═╡ fba0be84-3b2f-11eb-1e0f-5f8a1f264dba\nbegin\n\tdf = DataFrame()\n\tfor n in nRange\n\t\tcoverageCount = 0\n\t\tfor _ in 1:M\n\t\t\tsampleData = rand(dist, n)\n\t\t\tbootstrapSampleMeans = [median(rand(sampleData, n)) for _ in 1:N]\n\t\t\tL = quantile(bootstrapSampleMeans, alpha/2)\n\t\t\tU = quantile(bootstrapSampleMeans, 1-alpha/2)\n\t\t\tcoverageCount += L < actualMedian && actualMedian < U\n\t\tend\n\t\tappend!(df, DataFrame(:n => n, :coverage => coverageCount/M))\n\tend\n\tdf\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.14\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═1aa41898-3afa-11eb-2f49-570853ce6435\n# ╠═fba0be84-3b2f-11eb-1e0f-5f8a1f264dba\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "b0ae4868706473b714d8fa4a83f617a69f1930de", "size": 1346, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/06/listing6.14.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/06/listing6.14.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/06/listing6.14.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 22.813559322, "max_line_length": 68, "alphanum_fraction": 0.7161961367, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7636659994549742}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.21\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ bca1c92c-8561-11eb-0420-6f0123bacb7f\nbegin\n\t# dependencies\n\tusing Plots\n\tusing LightGraphs, SimpleWeightedGraphs, LinearAlgebra, Random\n\timport StatsBase:sample\nend\n\n# ╔═╡ 774fa124-8560-11eb-2317-53b0d106b67a\nmd\"\"\"\n# Local Search\n\"\"\"\n\n# ╔═╡ 2b5e6876-8561-11eb-0685-dfe1cca39c45\nmd\"\"\"\n## Simulated annealing\nSimulated annealing is similar to hill climbing, but it allows downhill moves. There are several aspects to consider. \n* What is considered a neighbor? And how to chose them?\n* How to evaluate the energy (i.e. the fitness)?\n* How to let the temperature evolve. Several options exist here:\n    - exponential decrease: $T = T_0(1-\\alpha)^k$, where $\\alpha$ is the ‘cooling rate’ and $k$ is the iteration\n    - fast decrease: $T = T_0/k$\n    - boltzmann decrease: $T = T_0/log(k)$   \n\"\"\"\n\n# ╔═╡ 4e190a2e-8561-11eb-3759-795e3bb4d8d2\nmd\"\"\"\nTo illustrate the principle, let's try to find the maximum of \n\\\\[ f(x) = -\\dfrac{1}{4}x^4 +  \\dfrac{7}{3} x^3 - 7x^2 + 8x \\\\]\nin the interval $[0, 5]$. You can observe that there is a global maximum in $x=4$, however, there is a local maximum in $x=1$.\n\"\"\"\n\n# ╔═╡ b49f0528-8561-11eb-36a7-fd42574edc81\nbegin\n\tf = x-> -1/4*x^4 + 7/3 *x^3 - 7*x^2 + 8*x\n\tx = range(0,5, length=100);\n\tplot(x,f.(x),label=\"\",size=(300,200))\nend\n\n# ╔═╡ d5019d8a-8561-11eb-2a43-a9ce616532f5\nbegin\n\t\"\"\"\n\tEvaluate the fitness of a specific point\n\t\"\"\"\n\tfunction fitness(x::Float64,f::Function)\n\t\treturn f(x)\n\tend\n\n\t\"\"\"\n\tDetermine successors for a given location (with a fixed step size)\n\tYou could include automatic step size modification if you want.\n\t\"\"\"\n\tfunction successors(x::Float64; step=0.1)\n\t\treturn x .+ step*[-1; 1]\n\tend\n\n\t\"\"\"\n\tmapping of time to temperature. You might make this a wrapper function for\n\tdifferent cooling schemes. Currently only has exponential cooling.\n\t\"\"\"\n\tfunction scheduletemp(t::Int64;T0::Float64=273.0, α::Float64=0.005)\n\t\treturn T0*(1-α)^t\n\tend\n\n\t\"\"\"\n\t\tsimulated_annealing(args; kwargs)\n\t\n\tSimulated annealing implementation for a 1D problem.\n\n\tSince this is stochastic (sort of a random walk), it will not always reach the optimal value, therefore, one typically runs several iterations and the best one is retained.\n\t\n\tThe probabiliy of accepting a value that lead to a decrease in energy is given by exp(ΔE/T), which is between 0 (temp = 0) and one (ΔE for any T ≠ 0).\n\n\tIn the literature you might also find  1/(1 + exp(ΔE/T)) ∈ [1/2, 1] as a treshold.\n\t\n\targuments:\n\t- x0: starting point\n\tkeywords:\n\t- tmax: maximum iterations\n\t- T0: initial temperature\n\t- α: cooling rate\n\t- fitness: fitness function\n\t- optimfun: the function we want to optimize\n\t\"\"\"\n\tfunction simulated_annealing(x0; \n\t\t\t\ttmax=1000, T0::Float64=273.0, α::Float64=0.005,\n\t\t\t\tfitness::Function=fitness, optimfun::Function=f) \n\t\tcurrent = x0\n\t\tnext = x0\n\t\tT = T0\n\t\tbest = x0\n\t\tfor t = 1:tmax\n\t\t\tT = scheduletemp(t,T0=T0,α=α)\n\t\t\tif T == 0\n\t\t\t\treturn current\n\t\t\telse\n\t\t\t\tnext = rand(successors(current))\n\t\t\t\tΔE = fitness(next, optimfun) - fitness(current, optimfun)\n\t\t\t\tif ΔE > 0 \n\t\t\t\t\tcurrent = next\n\t\t\t\telse\n\t\t\t\t\tif rand() < exp(ΔE/T)\n\t\t\t\t\t\tcurrent = next\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tif fitness(current, optimfun) > fitness(best, optimfun)\n\t\t\t\t\tbest = current\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\treturn best\n\tend\n\t\n\t\"\"\"\n\t\tSAsearch\n\t\n\tWrapper function for multiple SA iterations. Returns the best n found value for N runs of simulated annealing.\n\t\"\"\"\n\tfunction SAsearch(x0, n::Int64=1, N::Int64=10;kwargs...)\n\t\treturn sort!([simulated_annealing(x0; kwargs...) for _ in 1:N], \n\t\t\t\t\t by=x->kwargs[:fitness](x,kwargs[:optimfun]),\n\t\t\t\t\t rev=true)[1:n]\n\tend\nend\n\n# ╔═╡ 9c2e2032-8568-11eb-103f-fdc57c11ab1f\nmd\"\"\"\n### Solving the TSP problem with simulated annealing\nUse simulated annealing to solve the travelling saleman problem again. You will need to think in particalar about:\n* an appropriate inital solution (e.g. a tour by using a nearest neigbor approach or purely random)\n* generating appropriate neigbors (e.g. by flipping a subpart of a tour)\n\"\"\"\n\n# ╔═╡ c84f6af2-8568-11eb-06c4-53f7664294ac\nbegin\n\t\"\"\"\n\t\tplotgraph(g::SimpleWeightedGraph, d::Dict,draw_MST::Bool=true,wf::Real=5)\n\n\tVisualize the network with its edges and their weights\n\n\tparameters:\n\t\t- g : SimpleWeightedGraph\n\t\t- d : Dict\n\t\t\tdictionary that links a node to a coordinate pair\n\t\t- draw_MST : Bool\n\t\t\tif true, also draws the MST on the figure\n\t\t- wf : Real\n\t\t\tmultiplication factor for the edge weigth to obtain a nicer visualisation\n\t\"\"\"\n\tfunction plotgraph(g::SimpleWeightedGraph, d::Dict;wf::Real=5,draw_MST::Bool=true)\n\t\tp = plot(legend=:bottomright)\n\t\tfor e in edges(g)\n\t\t\tplot!([d[e.src][1], d[e.dst][1]],[d[e.src][2], d[e.dst][2]], \n\t\t\t\tmarkershape=:circle, linewidth=e.weight*wf, color=:black, markeralpha = 0.5,\n\t\t\t\tlinealpha=0.2, label=\"\", markercolor=:black, markersize=5)\n\t\tend\n\t\tplot!([],[],markershape=:circle, color=:black,\n\t\t\t\tlinealpha=0.2, label=\"Full network\", markercolor=:black, markersize=5, markeralpha = 0.5)\n\t\tif draw_MST\n\t\t\tMST = prim_mst(g, weights(g))\n\t\t\tfor e in MST\n\t\t\t\tplot!([d[e.src][1], d[e.dst][1]],[d[e.src][2], d[e.dst][2]], \n\t\t\t\t\t\tmarkershape=:circle, linewidth=weights(g)[e.src,e.dst]*wf, color=:red,\n\t\t\t\t\t\tlinealpha=0.8, label=\"\", linestyle=:solid, markeralpha = 0)\n\n\t\t\tend\n\t\t\tplot!([],[],linealpha=0.8, label=\"MST\", color=:red, linestyle=:solid)\n\t\tend\n\t\txlims!(0,1)\n\t\tylims!(0,1)\n\t\tplot!(legend=:best)\n\t\treturn p\n\tend\n\n\t\"\"\"\n\t\tplotsol(fp::Array{Int64,1}, nodedict::Dict)\n\n\tFunction that plots the final TSP solution\n\t\"\"\"\n\tfunction plotsol(fp::Array{Int64,1}, nodedict::Dict)\n\t\tp = plot()\n\t\tfor i in 1:length(fp)-1\n\t\t\tx = [nodedict[fp[i]][1]; nodedict[fp[i+1]][1]]\n\t\t\ty = [nodedict[fp[i]][2]; nodedict[fp[i+1]][2]]\n\t\t\tplot!(x,y,color=:blue,label=\"\", marker=:circle)\n\t\tend\n\t\t# close loop\n\t\tx = [nodedict[fp[1]][1]; nodedict[fp[end]][1]]\n\t\ty = [nodedict[fp[1]][2]; nodedict[fp[end]][2]]\n\t\tplot!(x,y,color=:red,label=\"\", marker=:circle)\n\t\txlims!(0,1)\n\t\tylims!(0,1)\n\t\treturn p\n\tend\n\t\n\t\"plot functions\"\nend\n\n# ╔═╡ 46e468e0-8569-11eb-0a30-d11e814ccf7e\nbegin\n\t\"\"\"\n\t\tproblemgenerator(n::Int)\n\n\tgenerate n points in the unit square\n\t\"\"\"\n\tfunction problemgenerator(n::Int)\n\t\treturn [(rand(), rand()) for _ in 1:n]\n\tend\n\n\t\"\"\"\n\t\tdistancematrix(x::Array{Tuple{Float64,Float64},1}, p::Real=1)\n\n\tGenerate distancematrix between all points.\n\n\tx is an array [n x 1] and p is the L_p-norm you want to use for the distancematrix\n\t\"\"\"\n\tfunction distancematrix(x::Array{Tuple{Float64,Float64},1}, p::Real=1)\n\t\tn = length(x)\n\t\tA = zeros(n,n)\n\t\tfor (i,j) in collect(Base.Iterators.product(1:n, 1:n))\n\t\t\tA[i,j] = norm(x[i] .- x[j], p)\n\t\tend\n\t\treturn A\n\tend\nend\n\n# ╔═╡ 7c5282fa-8569-11eb-0dcf-abc7b3b795ef\nbegin\n\tN = problemgenerator(15) # nodes\n\tnodedict = Dict( i => N[i] for i in 1:length(N)) # nodes dict\n\tA = distancematrix(N,2) # distance matrix using manhattan norm\n\tG = SimpleWeightedGraph(A) # graph\n\tp = plotgraph(G,nodedict;draw_MST=false) # layout of the current graph\nend\n\n# ╔═╡ eb27eada-8569-11eb-0739-7717087a5240\nbegin\n\t\"\"\"\n\t\tfinit(A::Array{Float64,2})\n\t\n\tGenerate an initial distribution based and a random order\n\t\"\"\"\n\tfunction finit(A::Array{Float64,2})\n\t\treturn shuffle(1:size(A,1))\n\tend\n\t\n\tfinit(A)\nend\n\n# ╔═╡ 1692c654-856a-11eb-1b02-77b0ab027c29\nbegin\n\t\"\"\"\n\t\tfitness(T::Array{Int64,1},A::Array{Float64,2})\n\t\n\tGiven a tour, compute the tour distance based on the distance matrix\n\t\"\"\"\n\tfunction fitness(T::Array{Int64,1},A::Array{Float64,2})\n\t\treturn -sum([A[T[i],T[i+1]] for i in 1:length(T)-1]) - A[T[1],T[end]] \n\tend\n\t\n\tfitness(finit(A),A)\nend\n\n# ╔═╡ 3c58cc1a-856a-11eb-17bd-a31c244f6229\nbegin\n\t\"\"\"\n\tDetermine successors for a given tour (simple random permutation of partial tour)\n\t\"\"\"\n\tfunction successors(T::Array{Int64,1}; nsuc::Int64=5)\n\t\tres = Array{Array{Int64,1},1}()\n\t\tfor _ in 1:nsuc\n\t\t\ti,j = sample(1:length(T),2,replace=false,ordered=true)\n\t\t\tcand = copy(T)\n\t\t\tcand[i:j] = shuffle(T[i:j])\n\t\t\tpush!(res, cand)\n\t\tend\n\n\t\treturn res\n\tend\n\tsuccessors(finit(A))\nend\n\n# ╔═╡ 7ab96168-856c-11eb-166a-b7531078ac90\nbegin\n\t\"\"\"\n\t\tsimulated_annealing(args; kwargs...)\n\t\n\tSimulated annealing implementation for TSP\n\n\tSince this is stochastic (sort of a random walk), it will not always reach the optimal value, therefore, one typically runs several iterations and the best one is retained.\n\n\tThe probabiliy of accepting a value that lead to a decrease in energy is given by exp(ΔE/T). In the literature you might also find  1/(1 + exp(ΔE/T)) ∈ [1/2, 1] as a treshold.\n\t\"\"\"\n\tfunction simulated_annealing(A::Array{Float64,2}, init::Array{Int64,1}; \n\t\t\t\t\t\t\t\ttmax=1000, T0::Float64=273.0, α::Float64=0.005,\n\t\t\t\t\t\t\t\tfitness::Function=fitness,nsuc::Int64=10, kwargs...)\n\t\tcurrent = init\n\t\tnext = init\n\t\tT = T0\n\t\tbest = init\n\t\tfor t = 1:tmax\n\t\t\tT = scheduletemp(t,T0=T0)\n\t\t\tif T == 0\n\t\t\t\treturn current\n\t\t\telse\n\t\t\t\tnext = rand(successors(current, nsuc=nsuc))\n\t\t\t\tΔE = fitness(next, A) - fitness(current, A)\n\t\t\t\tif ΔE > 0 \n\t\t\t\t\tcurrent = next\n\t\t\t\telse\n\t\t\t\t\tif rand() < exp(ΔE/T)\n\t\t\t\t\t\tcurrent = next\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tif fitness(current, A) > fitness(best, A)\n\t\t\t\t\tbest = current\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\treturn best\n\tend\n\t\n\t\"\"\"\n\twrapper function for multiple SA iterations\n\n\tReturns the best n found value for N runs of simulated annealing.\n\t\"\"\"\n\tfunction SAsearch(A::Array{Float64,2}, n::Int64=1, N::Int64=10;kwargs...)\n\t\tsort!([simulated_annealing(A, finit(A); kwargs...) for _ in 1:N], \n\t\t\t\tby=x->kwargs[:fitness](x,A),rev=false)[1:n]\n\tend\n\t\n\n\tsimulated_annealing(A, finit(A))\nend\n\n# ╔═╡ 934aa9e4-856e-11eb-1924-fd1df8fd3fe2\nmd\"\"\"\n## Genetic algorithms\na genetic algorithm (GA) is inspired by the process of natural selection. In order to implement this you need the following items:\n* an initial population (e.g. random)\n* a fitness function that allows you to rank the population members\n* a selection method (e.g. roulette based proportions, ‘elite selection’)\n* a cross-over method (cutting; 50/50 per gene etc.)\n* mutation rate and method\n* \\\\(\\dots\\\\)\n\"\"\"\n\n# ╔═╡ 8753fd9a-856f-11eb-2d91-13657e302031\nmd\"\"\"\n### Toy example\nLet's try write a message by using a genetic algorithm. E.g \"172 Pol evolved!\" starting from a random set of characters (a-zA-Z0-9. !)\n\"\"\"\n\n# ╔═╡ 48c05e06-8570-11eb-0367-1f3db0aa20d0\nbegin\n\tchars = vcat(65:90,97:122, 48:57,[Int(' ');Int('.'); Int('!')])\n\tconst genes = [Char(i) for i = chars]\n\tconst pop_size = 100\n\tconst goal = collect(\"172 Pol evolved!\");\nend\n\n# ╔═╡ 6faf987e-8570-11eb-1861-7de0f661bd63\nbegin\n\tfunction fitness(p::Array{Char,1}; goal=goal)\n\t\tsum(p.==goal)\n\tend\n\n\ttestcase = rand(genes,length(goal))\n\ttestcase, fitness(testcase)\nend\n\n# ╔═╡ 728b94da-8566-11eb-1b02-e94c64424845\nbegin\n\toptions = Dict(\t:tmax=>1000, :T0=>273.0, :α=>0.005, \n               \t\t:fitness=>fitness, :optimfun=>f)\n\tx0 = 0.0;\n\tsimulated_annealing(x0; options...)\nend\n\n# ╔═╡ a72d7c3c-8569-11eb-36a3-cb68ab2622cf\nlet\n\tn = 10;\n\tres = SAsearch(x0,n;options...)\nend\n\n# ╔═╡ 0ce6432c-8567-11eb-1465-432d66051360\nbegin\n\tn = 10;\n\tres = SAsearch(x0,n;options...)\n\tplot(x,f.(x),label=\"\")\n\tscatter!([x0],[f.(x0)],label=\"start\",marker=(:circle, :green),size=(300,200), legend=:bottom)\n\tscatter!([res],[f.(res)],label=\"optimal values\",marker=(:circle, :red),size=(300,200), legend=:bottom)\nend\n\n# ╔═╡ ef64ca86-856c-11eb-0cd0-178565e85576\nlet\n\toptions = Dict(:tmax=>1000, :T0=>273.0, :α=>0.005, :fitness=>fitness)\n\t@show res = SAsearch(A; options...)[1];\n\tinit = finit(A)\n\tprintln(\"Cost of a random trip: $(-fitness(init,A))\")\n\tprintln(\"Cost of a optimised trip: $(-fitness(res,A))\")\n\tplotsol(res, nodedict)\n\ttitle!(\"TSP solution using simulated annealing\")\nend\n\n# ╔═╡ 57726a64-856d-11eb-2b37-877202c47ede\nlet\n\t# Larger example\n\tn = 50 # number of nodes\n\tN = problemgenerator(n) # nodes\n\toptions = Dict(:tmax=>1000, :T0=>273.0, :α=>0.005, :fitness=>fitness)\n\tnodedict = Dict( i => N[i] for i in 1:length(N)) # nodes dict\n\tA = distancematrix(N,2) # distance matrix using manhattan norm\n\tinit = finit(A)\n\t\n\t@time res = SAsearch(A; options...)[1]\n\tprintln(\"Cost of a random trip: $(-fitness(init,A))\")\n\tprintln(\"Cost of a optimised trip: $(-fitness(res,A))\")\n\tplotsol(res, nodedict)\nend\n\n# ╔═╡ d70478c8-856d-11eb-3f27-0b565955b6ed\nlet\n\t# trajectory cost distribution\n\tres = Array{Float64,1}()\n\tfor _ in 1:50\n\t\tpush!(res, -fitness(SAsearch(A;options...)[1], A))\n\tend\n\thistogram(res, normalize=:pdf, alpha=0.5,label=\"PDF optimised tour cost\")\n\tscatter!([-fitness(finit(A),A)],[0],label=\"initial non-optimised cost\")\n\txlabel!(\"Tour cost\")\n\tylabel!(\"PDF\")\n\ttitle!(\"Histogram for tour cost ($(size(A,1)) cities)\")\nend\n\n# ╔═╡ 9cc2fa40-8570-11eb-2eba-c15433dcb90e\nbegin\n\t\"\"\"\n\t\tmate(p1,p2; pmut, genes)\n\t\n\tmating function to obtain children. includes both crossover and mutation.\n\t\"\"\"\n\tfunction mate(p1::Array{Char,1}, p2::Array{Char,1}; pmut=0.1, genes=genes)\n\t\tchild = typeof(p1)() # empty child\n\t\t# walk over genome sequence \n\t\tfor i in 1:length(p1)\n\t\t\tp = rand()\n\t\t\tif p < (1-pmut)/2\n\t\t\t\t# parent 1 wins\n\t\t\t\tpush!(child, p1[i])\n\t\t\telseif p < 1-pmut\n\t\t\t\t# parent 2 wins\n\t\t\t\tpush!(child, p2[i])\n\t\t\telse\n\t\t\t\t# mutation\n\t\t\t\tpush!(child, rand(genes))\n\t\t\tend\n\t\tend\n\t\treturn child\n\tend\n\t\n\t# demo\n\tp1 = ['a';'b';'c']\n\tp2 = ['d';'e';'f']\n\tmate(p1,p2, pmut=1)\nend\n\n# ╔═╡ 47153f8e-8572-11eb-1310-c932bd478721\nmd\"\"\"\n### Some ideas for crossover:\nBelow you can find some algorithms that have proven to work quite well for this type of application. Both of these are described and an example and an implementation is provided. You are also invited to come up with a method yourself if you think you have a good idea.\n\n#### The partially mapped crossover \nAfter choosing two random cut points on parents to build offspring, the portion between cut points, one parent’s string is mapped onto the other parent’s string and the remaining information is exchanged.\n\nE.g. for parents $P_1$ and $P_2$ with cutting positions $c_1$ and $c_2$:\n* ``P_1 = [3, 4, 8 | 2, 7, 1 | 6, 5 ]``\n* ``P_` = [4, 2, 5 | 1, 6, 8 | 3, 7 ]``\nWe get the following mappings:\n* ``m_{1 \\rightarrow 2}: \\{2 \\rightarrow 1, 7 \\rightarrow 6, 1 \\rightarrow 8\\}``\n* ``m_{2 \\rightarrow 1}: \\{1 \\rightarrow 2, 6 \\rightarrow 7, 8 \\rightarrow 1\\}``\nwhich leads to the following initial offspring:\n* ``O_1 = [0, 0, 0 | 1, 6, 8 | 0, 0 ] ``\n* ``O_2 = [0, 0, 0 | 2, 7, 1 | 0, 0 ] ``\nwe then add the non-conflicting values (i.e. the values not already present the offspring due do the crossover) from the original parents:\n* ``O_1 = [3, 4, 0 | 1, 6, 8 | 0, 5 ]``\n* ``O_2 = [4, 0, 5 | 2, 7, 1 | 3, 0 ] ``\nFor the remaining values, we (recursively) make use of the mappings using $m_{2 \\rightarrow 1}$ for $P_1$ and $m_{1 \\rightarrow 2}$ for $P_2$. This finally leads to the following offspring:\n* ``O_1 = [3, 4, 2 | 1, 6, 8 | 7, 5 ] ``\n* ``O_2 = [4, 8, 5 | 2, 7, 1 | 3, 6 ] ``\n\n\n#### The cycle crossover \nThe Cycle Crossover operator identifies a number of so-called cycles between two parent chromosomes. To form Child 1, cycle 1 is copied from parent 1, cycle 2 from parent 2, cycle 3 again from parent 1, and so on. An example might help to better understand the principle of a cycle. E.g.\n* ``P_1 = [1,2,3,4,5,6,7,8] ``\n* ``P_2 = [8,5,2,1,3,6,4,7] ``\nFor the first cycle, we start at index 1 in $P_1$. Following the links from $P_1$ to $P_2$ we find the following mappings:\n* ``1 \\rightarrow 8`` with index 8\n* ``8 \\rightarrow 7`` with index 7\n* ``7 \\rightarrow 4`` with index 4\n* ``4 \\rightarrow 1`` with index 1\nafter this last mapping, we are back at the starting point, so our first cycle is complete and is $\\{1,4,7,8 \\}$.\n\nThe second cycle will start at the first index that is not yet present in a cycle. In this case the index is equal to 2. Following the links from $P_1$ to $P_2$ we find the following mappings\n* ``2 \\rightarrow 5`` with index 2\n* ``5 \\rightarrow 3`` with index 5\n* ``3 \\rightarrow 2`` with index 3\n\nSo our second cycle is equal to $\\{2,3,5\\}$.\n\nThe third an final cycle is equal to the only remaining part, i.e. $\\{6 \\}$\n\nWe have now determined all cycles. The children aren obtained as follows:\n* ``O_1[1,4,7,8] =  P_1[1,4,7,8] ``\n* ``O_1[2,3,5] = P_2[2,3,5] ``\n* ``O_1[6]  = P_1[6] ``\n\nThis leads to $O_1 = [1,5,2,4,3,6,7,8]$. In a similar fashion, but inverting the role of $P_1$ and $P_2$ one finds $O_2 = [8,2,3,1,5,6,4,7]$.\n\nA downside of this type of crossover is that it can sometimes lead to the offspring being identical to the parents. You can verify this for $[3,4,8,2,7,1,6,5]$ & $[4,2,5,1,6,8,3,7]$.\n\n#### Your own method\nCome up with something that seems adequate...\n\n\"\"\"\n\n# ╔═╡ 1f5d255c-8576-11eb-1463-89f94258168d\nbegin\n\t\"\"\"\n\t\tmate(p1,p2;method=partialcrossover, kwargs...) \n\n\tFunction that handles the crossover for two different tours. The method keyword argument can be any of the functions you define as long as 1. the function exists 2. the function works in a similar way as the other ones (i.e. return two children from two parents.)\n\n\tAdditional options for your own crossover implementation can be passed via the kwargs. You should document the options for each algorithm sperately.\n\n\t\"\"\"\n\tfunction mate(p1::Array{Int64,1},p2::Array{Int64,1}; method::Function=partialcrossover, kwargs...) \n\t\t\treturn method(p1,p2; kwargs...)\n\tend\n\n\t\"\"\"\n\t\tpartialcrossover(p1, p2; kwargs...)\n\n\tImplementation of the partial crossover function for TSP routing problems.\n\t\"\"\"\n\tfunction partialcrossover(p1::Array{Int64,1},p2::Array{Int64,1}; kwargs...)\n\t\t\"\"\"\n\t\t\tdeconflicter!(O::Array{Int64,1}, mapping::Dict)\n\n\t\tFunction that deals with the conflicts after the initial assignments.\n\t\t\"\"\"\n\t\tfunction deconflicter(O::Array{Int64,1},p::Array{Int64,1}, mapping::Dict)\n\t\t\tfor i in 1:length(O)\n\t\t\t\tif O[i] == 0\n\t\t\t\t\tcand = p[i]\n\t\t\t\t\twhile cand in O\n\t\t\t\t\t\tcand = mapping[cand]\n\t\t\t\t\tend\n\t\t\t\t\tO[i] = cand\n\t\t\t\tend\n\t\t\tend\n\t\t\treturn O\n\t\tend\n\n\t\t# choose cut points\n\t\tc1, c2 = sort(sample(1:length(p1),2, replace=false))\n\t\t# initiate offspring\n\t\tO1, O2 = [zeros(Int64,length(p1)) for _ in 1:2]\n\t\t# determine mapping \n\t\tmap12 = Dict(p1[i]=> p2[i] for i in c1:c2)\n\t\tmap21 = Dict(value => key for (key, value) in map12)\n\t\t# set offspring initial values\n\t\tO1[c1:c2] = p2[c1:c2]\n\t\tO2[c1:c2] = p1[c1:c2]\n\t\t# fill non-conflicting positions\n\t\tfor i in setdiff(1:length(p1),c1:c2)\n\t\t\tO1[i] = p1[i] in O1 ? 0 : p1[i]\n\t\t\tO2[i] = p2[i] in O2 ? 0 : p2[i]\n\t\tend\n\t\t# fill conflicting positions using the mapping\n\t\tO1, O2 = deconflicter(O1, p1, map21), deconflicter(O2, p2, map12)\n\n\t\treturn O1, O2\n\tend\n\n\t\"\"\"\n\t\tcyclecrossover(p1, p2)\n\n\tImplementation of the cycle crossover function for TSP routing problems.\n\t\"\"\"\n\tfunction cyclecrossover(p1::Array{Int64,1},p2::Array{Int64,1})\n\t\t# initiate children\n\t\to1=zeros(Int64,length(p1))\n\t\to2=zeros(Int64,length(p2))\n\n\t\t# Pt. 1 - find all cycles\n\n\t\t# make hashtable: value => index\n\t\th1 = Dict{Int64, Int64}(p1[i]=>i for i in 1:length(p1))\n\t\th2 = Dict{Int64, Int64}(p2[i]=>i for i in 1:length(p2))\n\t\t# make hashtable to track usage in a cycle: index => bool\n\t\tu1 = Dict{Int64, Bool}(i=>false for i in 1:length(p1))\n\t\t# loop over parent creating cycles on the go\n\t\t# a cycle is stored in a Set because this is hashable. This is (much) faster than an array for ∉ check\n\t\t# the values stores in the cycles are the indices to be used\n\t\tcycles = Array{Set{Int64},1}()\n\t\tfor i in 1:length(p1)      \n\t\t\tif !u1[h1[p1[i]]] # if not used yet, start a new cycle\n\t\t\t\tcycle = Set{Int64}()\n\t\t\t\tnext = h1[p1[i]] # add initial values\n\t\t\t\twhile next ∉ cycle\n\t\t\t\t\tpush!(cycle, next)  # update cycle\n\t\t\t\t\tu1[next] = true     # update tracking\n\t\t\t\t\tnext = h1[p2[next]] # next location\n\t\t\t\tend\n\t\t\t\tpush!(cycles, cycle)\n\t\t\telse\n\t\t\t\tcontinue\n\t\t\tend    \n\t\tend\n\n\t\t# Pt. 2 - make children from cycles\n\t\tfor i in 1:length(cycles)\n\t\t\tinds = collect(cycles[i])\n\t\t\tif isodd(i)\n\t\t\t\to1[inds] = p1[inds]\n\t\t\t\to2[inds] = p2[inds]\n\t\t\telse\n\t\t\t\to1[inds] = p2[inds]\n\t\t\t\to2[inds] = p1[inds]\n\t\t\tend\n\t\tend\n\t\treturn o1, o2\n\tend\n\n\n\t\"\"\"\n\t\tmycrossover(p1, p2; myoption::Float64=0.5, kwargs...)\n\n\tYour own method that takes predefined options and also accepts others.\n\t\"\"\"\n\tfunction mycrossover(p1::Array{Int64,1},p2::Array{Int64,1}; myoption::Float64=0.5, kwargs...)\n\t\terror(\"Function <mycrossover> not defined yet... Get creative!\")\n\tend\nend\n\n# ╔═╡ fd95d464-8570-11eb-1a38-879d8079d127\nbegin\n\tfunction textga(;goal::Array{Char,1}=goal, popsize::Int64=pop_size, \n                \t ngen::Int64=500, next::Float64=0.4, pmut=0.1, kwargs...)\n\t\t# initiate population\n\t\tpopulation = [rand(genes, length(goal)) for _ in 1:popsize]\n\t\tgen = 0\n\t\tfor _ in 1:ngen\n\t\t\t# sort by fitness\n\t\t\tsort!(population; by=x->fitness(x), rev=true)\n\t\t\tif population[1] == goal\n\t\t\t\tbreak\n\t\t\tend\n\t\t\tgen += 1\n\t\t\t# select adequate parents\n\t\t\tgoodparents = population[1: round(Int,popsize*next)]\n\t\t\t# make children\n\t\t\tnew_generation = typeof(population)()\n\t\t\tfor _ in 1:popsize\n\t\t\t\tpush!(new_generation, mate(rand(goodparents), rand(goodparents),\n\t\t\t\t\t\t\t\t\t\t\tpmut=pmut ))\n\t\t\tend\n\t\t\tpopulation = new_generation\n\t\tend\n\t\t@info \"stopped after $(gen) generations\"\n\n\t\treturn (gen, prod(population[1]), fitness(population[1])/fitness(goal))\n\tend\n\n\ttextga(ngen=500, popsize=100, pmut=0.1)\nend\n\n# ╔═╡ 7c4ef658-8576-11eb-3f6d-d3587a1af7e8\nbegin\n\tlet\n\t\t# small demo matching the explanation of the algorithm above. \n\t\t# Matches the detailed example if you force c1, c2 = 4, 6 in the partialcrossover algorithm\n\t\tp1 = [3,4,8,2,7,1,6,5]\n\t\tp2 = [4,2,5,1,6,8,3,7]\n\t\t@time mate(p1,p2)\n\tend\n\n\tlet\n\t\t# Longer route does not necessarily imply greater time for offspring generation\n\t\t# with the partial crossover algorithm (why could that be?)\n\t\t@info \"100 items\"\n\t\tN = 100\n\t\tp1 = collect(1:N)\n\t\tp2 = sample(p1,N,replace=false)\n\t\t@time mate(p1,p2);\n\tend\n\n\tlet\n\t\t# demo from the method description\n\t\tp1 = [1,2,3,4,5,6,7,8]\n\t\tp2 = [8,5,2,1,3,6,4,7]\n\t\t@time res = mate(p1,p2, method=cyclecrossover)\n\t\t@assert res ==  ([1,5,2,4,3,6,7,8],  [8,2,3,1,5,6,4,7])\n\tend\n\n\tlet\n\t\t# demo for children equal to parents\n\t\tp1 = [3,4,8,2,7,1,6,5]\n\t\tp2 = [4,2,5,1,6,8,3,7]\n\t\t@time res = mate(p1,p2, method=cyclecrossover)\n\t\t@assert res == (p1 ,p2)\n\tend\n\n\tlet\n\t\t# Longer routes scales nicely for cyclecrossover as well (≈10x longer route and only ≈2x slower)\n\t\tN = 100\n\t\tp1 = collect(1:N)\n\t\tp2 = sample(p1,N,replace=false)\n\t\t@time res = mate(p1,p2, method=cyclecrossover);\n\tend\nend\n\n# ╔═╡ 8b77cf1c-8571-11eb-2ea7-531abac106cc\nmd\"\"\"\n### Genetic algorithm - TSP\nNow that you are familiar with a genetic algorithm, let's try to solve the TSP problem again, but this time, using a genetic algorithm.\n\nWe should think about:\n* representation\n* an initial configuration\n* a fitness function \n* a selection method (e.g. roulette based proportions, ‘elite selection’ etc.)\n* cross-over method: (what is the difference with the text application?)\n* mutation rate and method (is this required? why (not)?)\n* when do you stop making new generations?\n* \\\\( \\dots \\\\)\n\n\nTasks:\n* Come up with your own suggestions for cross-over/mutation\n* Implement the genetic algorithm to solve the TSP\n* Compare the performance of the tree cross-over algorithms to deal with eachother. Give that there is some randomness involved, a statistical approached might be more appropriate. Since the initial population will most likely be chosen at random, you should impose the random seed to make sure you have the same starting point for the comparisons.\n* Compare the scalability with what you know from previous practical sessions (tree search etc.) What is better and what is worse?\n\"\"\"\n\n# ╔═╡ 712cb76c-8576-11eb-37c3-87beed1c3fa1\nbegin\n\tfunction TSP_ga(d::Array{Float64,2}; \n\t\t\t\t\tpopsize::Int64=30, ngen::Int64=500, next::Float64=0.4,\n\t\t\t\t\tmethod::Function=partialcrossover, kwargs...)\n\t\t# initiate population\n\t\tn = size(d,1)\n\t\tpopulation = [sample(1:n,n,replace=false) for _ in 1:popsize]\n\t\tgen = 0\n\t\t# go over the generations\n\t\tfor _ in 1:ngen\n\t\t\t# sort by fitness\n\t\t\tsort!(population; by=x->fitness(x,d), rev=true)\n\t\t\t#@show \"current tour cost: $(fitness(population[1],d))\"\n\t\t\t# include a stopcondition?\n\t\t\tgen += 1\n\t\t\t# select adequate parents\n\t\t\tgoodparents = population[1: round(Int,popsize*next)]\n\t\t\t# make children\n\t\t\tnew_generation = typeof(population)()\n\t\t\tfor _ in 1:2:popsize\n\t\t\t\tp1,p2 = rand(goodparents,2)\n\t\t\t\toffspring = mate(p1,p2;method=method, kwargs...) \n\t\t\t\tappend!(new_generation, offspring)\n\t\t\tend\n\t\t\tpopulation = new_generation\n\t\tend\n\n\t\treturn (gen, population[1], fitness(population[1],d))\n\tend\nend\n\n# ╔═╡ fa780328-8576-11eb-3a16-b7109ffbad63\nlet\n\tn = 50 # number of nodes\n\tN = problemgenerator(n) # nodes\n\tnodedict = Dict( i => N[i] for i in 1:length(N)) # nodes dict\n\tA = distancematrix(N,1) # distance matrix using manhattan norm\n\t@info fitness(finit(A), A)\n\tG = SimpleWeightedGraph(A) # graph\n\t@time begin\n    \tD = Dict()\n    \tmethods = [cyclecrossover, partialcrossover]\n\t\tfor method in methods\n\t\t\tres = []\n\t\t\tfor _ in 1:100\n\t\t\t\t(_, tour, cost) = TSP_ga(A, ngen=20, popsize=n,method=method)\n\t\t\t\tpush!(res,(tour,cost))\n\t\t\tend\n\t\t\tD[method] = [x[2] for x in res]\n\t\tend\n\tend\n\t\n\t# illustration\n\thistogram()\n\tfor (key, val) in D\n\t\thistogram!(-val, label=string(key), normalize=:pdf, alpha=0.5)\n\tend\n\tscatter!([-fitness(finit(A),A)],[0],label=\"initial non-optimised cost\")\n\txlabel!(\"Tour cost\")\n\tylabel!(\"PDF\")\n\ttitle!(\"Histogram for tour cost ($(size(A,1)) cities)\")\nend\n\n# ╔═╡ 1a79eb5a-8577-11eb-168e-8fa9230f26fb\n\n\n# ╔═╡ Cell order:\n# ╟─774fa124-8560-11eb-2317-53b0d106b67a\n# ╠═bca1c92c-8561-11eb-0420-6f0123bacb7f\n# ╠═2b5e6876-8561-11eb-0685-dfe1cca39c45\n# ╠═4e190a2e-8561-11eb-3759-795e3bb4d8d2\n# ╠═b49f0528-8561-11eb-36a7-fd42574edc81\n# ╠═d5019d8a-8561-11eb-2a43-a9ce616532f5\n# ╠═728b94da-8566-11eb-1b02-e94c64424845\n# ╠═a72d7c3c-8569-11eb-36a3-cb68ab2622cf\n# ╠═0ce6432c-8567-11eb-1465-432d66051360\n# ╟─9c2e2032-8568-11eb-103f-fdc57c11ab1f\n# ╟─c84f6af2-8568-11eb-06c4-53f7664294ac\n# ╠═46e468e0-8569-11eb-0a30-d11e814ccf7e\n# ╠═7c5282fa-8569-11eb-0dcf-abc7b3b795ef\n# ╠═eb27eada-8569-11eb-0739-7717087a5240\n# ╠═1692c654-856a-11eb-1b02-77b0ab027c29\n# ╠═3c58cc1a-856a-11eb-17bd-a31c244f6229\n# ╠═7ab96168-856c-11eb-166a-b7531078ac90\n# ╠═ef64ca86-856c-11eb-0cd0-178565e85576\n# ╠═57726a64-856d-11eb-2b37-877202c47ede\n# ╠═d70478c8-856d-11eb-3f27-0b565955b6ed\n# ╟─934aa9e4-856e-11eb-1924-fd1df8fd3fe2\n# ╟─8753fd9a-856f-11eb-2d91-13657e302031\n# ╠═48c05e06-8570-11eb-0367-1f3db0aa20d0\n# ╠═6faf987e-8570-11eb-1861-7de0f661bd63\n# ╠═9cc2fa40-8570-11eb-2eba-c15433dcb90e\n# ╠═fd95d464-8570-11eb-1a38-879d8079d127\n# ╟─47153f8e-8572-11eb-1310-c932bd478721\n# ╠═1f5d255c-8576-11eb-1463-89f94258168d\n# ╠═7c4ef658-8576-11eb-3f6d-d3587a1af7e8\n# ╟─8b77cf1c-8571-11eb-2ea7-531abac106cc\n# ╠═712cb76c-8576-11eb-37c3-87beed1c3fa1\n# ╠═fa780328-8576-11eb-3a16-b7109ffbad63\n# ╠═1a79eb5a-8577-11eb-168e-8fa9230f26fb\n", "meta": {"hexsha": "ece304bed580bf7bb683f6c015816878dcc1aa21", "size": 26535, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PS/PS05 - Local Search.jl", "max_stars_repo_name": "B4rtDC/DS425-PS", "max_stars_repo_head_hexsha": "585f1c69d4abb9801feb9e281d0b1a04b89b7761", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-07T21:55:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T14:29:23.000Z", "max_issues_repo_path": "PS/PS05 - Local Search.jl", "max_issues_repo_name": "Goodwill-Khoa/DS425-PS", "max_issues_repo_head_hexsha": "585f1c69d4abb9801feb9e281d0b1a04b89b7761", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PS/PS05 - Local Search.jl", "max_forks_repo_name": "Goodwill-Khoa/DS425-PS", "max_forks_repo_head_hexsha": "585f1c69d4abb9801feb9e281d0b1a04b89b7761", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-07-07T21:55:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T13:52:37.000Z", "avg_line_length": 31.0350877193, "max_line_length": 348, "alphanum_fraction": 0.6766157905, "num_tokens": 9657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.8577681104440171, "lm_q1q2_score": 0.7636659985767074}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.11\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 8dbcf370-1dec-11eb-0a2d-e967ec1f2fde\nmd\" ### Nomenclatura\"\n\n# ╔═╡ c4a8db60-1dec-11eb-0c39-73a8aac79092\nmd\"Seja $X$ uma matriz com dimensões $n x m$ com $n$ linhas e $m$ colunas que contém nossos exemplos. $x_i^{(j)}$ corresponde ao elemento de $X$ em que $i$ é uma linha da matriz (exemplo) e $j$ uma coluna da matriz (atributo), cujo acesso na linguagem representamos por x[i,j]. Para pegarmos um vetor linha desta matriz (exemplo) representamos formalmente por $X_i$ e na linguagem por x[i,:].\"\n\n# ╔═╡ cd532e00-1dec-11eb-06d9-9b7c76e9c1ba\nmd\"Seja $\\theta$ um vetor linha com $m$ elementos tal que $m$ corresponde ao número de atributos mais um. $\\theta = [\\theta^{(0)},\\theta^{(1)}, ...,\\theta^{(m)}]$ em que cada elemento corresponde ao j-ésimo parâmetro associado ao j-ésimo atributo. Na nossa linguagem acessamos um elemento por $\\theta[i]$ e o vetor por $\\theta$\"\n\n# ╔═╡ dc365e10-1dec-11eb-0e4f-95624ee468ea\nmd\"Seja $y$ nosso vetor alvo em que representamos o i-ésimo elemento por $y_i$. Na nossa linguagem representamos por $y[i]$.\"\n\n# ╔═╡ 571a5ea0-1dee-11eb-0eaf-bf746a6faa86\nmd\"### Algumas libs importantes usadas neste experimento\"\n\n# ╔═╡ 317bbe60-1ded-11eb-2faa-c3e47c0df176\nbegin \n   import Statistics: mean,std\n   import BenchmarkTools: @benchmark, @btime\n   import StaticArrays: @SMatrix\n   import Plots: plot,plot!,scatter,scatter!\t\n   import StatsBase: zscore\t\n   μ = mean\t\nend\n\n# ╔═╡ f9af3a70-1dec-11eb-34f0-91b7fc591b87\nmd\" ### Hipótese e modelo linear\"\n\n# ╔═╡ 78d2c0e0-1f98-11eb-06bc-b51c3b4b9f35\nmd\"A seguir descrevemos a hipótese que consiste da aplicação de um modelo (conjunto de parâmetros) em um exemplo. Note que a hipótese sempre se refere à aplicação de um único exemplo e não ao conjunto de dados todo. \"\n\n# ╔═╡ 2e7709e0-1ded-11eb-2abd-d770bf1afe8a\nmd\"$H_{\\theta}(X_i) = \\sum_{j}^{m}{x_{i}^{(j)} \\theta^{(j)}} = X_i\\theta^{T}$\"\n\n# ╔═╡ b05f9930-1f97-11eb-0083-07ebd21313e0\nmd\"Exemplificando o produto de vetores, nossa hipótese faria o seguinte cálculo para um exemplo $X_i = \\begin{bmatrix} 1 & 500 \\end{bmatrix}$ e um vetor de parâmetros $\\theta^T = \\begin{bmatrix}\n    0.5 \\\\\n    1.0\n\\end{bmatrix}$:\"\n\n# ╔═╡ cbf998e0-1f96-11eb-0a8b-a3bf631bfe02\nmd\"e.g. $H_{\\theta}(X_i) = \\begin{bmatrix}\n    1 & 500 \n  \\end{bmatrix}\\begin{bmatrix}\n    0.5 \\\\\n    1.0\n\\end{bmatrix} = 500.5$\"\n\n# ╔═╡ 4cc76c80-1f98-11eb-0c70-29aec0b92ac4\nmd\"Note que o resultado é um escalar, pois estamos estimando um valor contínuo (problema de regressão).\"\n\n# ╔═╡ c0b094a0-1f98-11eb-2efb-07f680447b12\nmd\"### Implementação a hipótese\"\n\n# ╔═╡ be0deb50-1ded-11eb-06bb-33e94217e815\nH(χ,θ) = χ*Θ'\n\n# ╔═╡ 2f5a6500-1ded-11eb-11dd-bd88bf102b98\nmd\" ### Função de custo\"\n\n# ╔═╡ 30972ac0-1ded-11eb-1007-1d3833dfc264\n\nmd\"$J(\\theta)= \\frac{1}{2n}\\sum_{i=1}^{n}{(H_{\\theta}(X_i) - y_i)²}$\"\n\n\n# ╔═╡ bba6d590-1e1d-11eb-2df6-67bd6c5d4777\nmd\" A seguir estou calculando a função de custo sem loop, apenas por matrizes.Desta maneira, geramos em uma multiplicação de matrizes, um vetor de predições com a mesma dimensão da saída. Após isto, subtraímos elemento a elemento. Após isto, elevamos cada elemento ao quadrado e depois tiramos uma média. Explicado na aula anterior.\"\n\n# ╔═╡ 9837a3d0-1ded-11eb-3c49-17a45387e46e\nJ(Θ,χ,γ) = .5μ((χ*Θ' .- γ).^2)\n\n# ╔═╡ 2ebaad22-1dee-11eb-2fb1-f51c49ec13fb\nmd\"### Gradiente descendente\"\n\n# ╔═╡ d1cf31b0-1e17-11eb-22d1-916c9a331700\nmd\"A seguir, mostramos o cálculo do gradiente. Como podemos notar, o expoente 2 desce e é eliminado pela constante 2 do denominador. Adicionalemente, vemos que é uma subtração do gradiente, pois estamos minimizando a função de custo. Por isto, estamos caminhando no sentido contrário ao do gradiente. É importante também ressaltar que o viés já está embutido na matriz $X$ na forma de uma coluna com valores 1. Desta forma, o cálculo do gradiente é o mesmo para o parâmetro do viés ($θ^{(0)}$) e os demais.\" \n\n# ╔═╡ cbf654c0-1dfa-11eb-0994-85a67ded79b0\nmd\"$θ^{(j)} = θ^{(j)} - α \\frac{1}{n} \\sum_{i=1}^{n}{(H_θ(X_i) - y_i)x_{i}^{(j)}}$\"\n\n# ╔═╡ 46484b80-1e1d-11eb-2bdc-e50b24f6b530\nmd\"Entretanto, podemos condensar esta fórmula usando notação de vetores e matrizes. Lembrando que $\\theta$ é um vetor agora e os cálculos são feitos simultaneamente para cada eleemnto deste. Podemos observar que o índice da coluna some, pois são processadas automaticamente. A seguir, veja a fórmula:\"\n\n# ╔═╡ f1089b10-1e1d-11eb-120e-cdbd993d72dc\nmd\"$θ = θ - α \\frac{1}{n} \\sum_{i=1}^{n}{(H_θ(X_i) - y_i) \\circ X_{i}}$\"\n\n# ╔═╡ 79bc38d0-1e1f-11eb-066c-2929340c479e\nmd\"Cabe observar que $\\circ$ é o produto de hadamard.\"\n\n# ╔═╡ f5d33090-1e1f-11eb-3f25-d10f2616803d\nmd\"### Algoritmo \"\n\n# ╔═╡ 7a22eab0-1def-11eb-2672-495fb9cf19f8\nfunction train(θ,χ,γ;verbose=false,α = 1e-3,ϵ=1e-5,τ=1e3)\n\t\n\te₂  = J(θ,χ,γ) \n\te₁  = e₂ + .1\n\t#Δ₁,Δ₂ = e₁ - e₂ + 2ϵ,e₁ - e₂\n\t💻 = [[e₂ θ]]\n\ti   = 1\n\twhile e₂ < e₁ && e₂ > ϵ && i < τ    \n\t#while Δ₁ > Δ₂  && e₂ > ϵ && i < τ     \n\t\t\n\t\t∇     = μ((χ*θ' .- γ).* χ,dims=1)\n\t\tθ    -= α .* ∇\n\t\t\n\t\te₁,e₂ = e₂,J(θ,χ,γ)\n\t\t#Δ₁,Δ₂ = Δ₂,e₁ - e₂\n\t\tverbose && if (i%10==0) append!(💻,[[e₂ θ]]) end\n\t\t\n\t\ti += 1\n\tend\n\tθ,vcat(💻...)\nend\t\n\n# ╔═╡ 1f0e51f0-1df4-11eb-0feb-b53552fa63c9\nmd\"### Testes de unitários\"\n\n# ╔═╡ 58dd7720-1e09-11eb-1904-af5f9991ece5\nmd\" Sempre que for desenvolver suas funções, realize uma bateria de testes para cada uma antes mesmo de executar todo o seu programa. Isso vai lhe poupar muito tempo para uma futura depuração de código. Assim, para cada função, faça pelo menos um teste. Elabore casos bons de entrada para suas funções de forma que cubra bem o espaço de possibilidades. Seus casos devem ser bem simples para que num futuro, se der erro, você consiga rapidamente resolver.\"\n\n# ╔═╡ 259ac040-1e39-11eb-3670-f5c5519a1978\nmd\"### Padronizando os Dados \"\n\n# ╔═╡ 246cc792-1e39-11eb-3c20-f1623d8ea737\nmd\"O objetivo de padronizar os dados é acelerar a convergência do método. Aqui utilizaremos a padronização zscore. Entretanto, para amostras pequenas, a padronização não funciona muito bem.\"\n\n# ╔═╡ c467ca00-1e08-11eb-3d41-75a38532652b\nmd\"### Verificando a curva de erro\"\n\n# ╔═╡ d1a88a00-1f8f-11eb-36b7-f39dabee0657\nmd\"### Veificando o comportamento dos parâmetros\"\n\n# ╔═╡ b405694e-1f8f-11eb-0fad-5d0c3527d206\nmd\"### Verificando o modelo\"\n\n# ╔═╡ d497051e-1f94-11eb-2ccb-a7d3e52570d1\nmd\"Como podemos observar, o gradiente jogou o θ₁ para zero (viés, responsável pela translação) e ajustou o θ₂ (responsável pela rotação). Cabe ressaltar que estamos trabalhando com os dados padronizados. É possível, no entanto, despadronizar e obter predições no campo dos números originais.\"\n\n# ╔═╡ 37c52e40-1e48-11eb-1e13-7ba1bebfabc4\nmd\"### Depuração \"\n\n# ╔═╡ 44997b82-1e48-11eb-1821-f7f3aecd8093\nmd\" Costumo colocar alguma variáveis soltas para que eu veja se está tudo correto. \"\n\n# ╔═╡ a419b220-1e4b-11eb-1299-295bf39df3f4\nmd\"### Solução direta por álgebra linear\"\n\n# ╔═╡ a39cb9f0-1e4b-11eb-296e-bf19e5438416\ntrain(X,Y) = inv(X'X)X'Y\n\n# ╔═╡ 628624c0-1dfa-11eb-2afb-137bf77669e1\nbegin\n\tΘ1 = [0. 4.] \n\tχ =  [1 50.;1 60.;1 100.; 1 200.]\n\tγ =  [200  ;   240  ;   400; 800]\n\t@assert J(Θ1,χ,γ) == 0.0\n\t@assert train(Θ1,χ,γ)[1] == [0. 4.] # iniciando com a solução, o θ deve continuar igual\nend\t\n\n# ╔═╡ 4c632fee-1e39-11eb-00c6-c3f2a0774005\nbegin \n\tχₚ = hcat(ones((4,1)), zscore(χ[:,2:end])) # padronizamos só o que não é viés\n\tγₚ = zscore(γ)\nend\t\n\n# ╔═╡ d8ab5330-1e47-11eb-06b3-af3d2ee97c7b\nχₚ\n\n# ╔═╡ 86be2920-1e48-11eb-10f1-6740a2459951\nγₚ\n\n# ╔═╡ 74604cb2-1e05-11eb-19ef-09fd04dc52e3\n(θᵏ,r) = train([4 5],χₚ,γₚ,verbose=true,α = 1e-3,ϵ=1e-5,τ=1e5);\n\n# ╔═╡ b7913600-1e0c-11eb-362e-0b4b9ef9d1aa\nplot(1:length(r[:,1]),r[:,1],xlabel=\"iterações\",ylabel=\"J(θ)\",title=\"Análise de erros\",label=\"Erro\")\n\n# ╔═╡ fa0bd460-1e23-11eb-131f-f31bec373c07\nbegin\n\tp = plot(1:length(r[:,2]),r[:,2],xlabel=\"iterações\",ylabel=\"θ₁,θ₂\",title=\"Análise de parâmetros\",label=\"θ₁\")\n\tplot!(p,1:length(r[:,3]),r[:,3],xlabel=\"iterações\",label=\"θ₂\")\nend\t\n\n# ╔═╡ cc73d620-1f8f-11eb-357d-b19b50c19280\nbegin\n\tf(x) = θᵏ[1] + θᵏ[2]*x # o mesmo que H(X) lá do início\n\tplot(χₚ[:,2],f,xlabel=\"m² (padronizado)\",ylabel=\"Preço (padronizado)\",title=\"Análise do da predição do modelo\",label=\"θ₁ + θ₂x\")\n\tscatter!(χₚ[:,2],γₚ,label=\"Dados Coletados\")\nend\t\n\n# ╔═╡ 41505b10-1e34-11eb-06db-750eb3ab11cf\nr[end,:]\n\n# ╔═╡ 29b04780-1e44-11eb-3bcf-8b5f121d157f\nJ(θᵏ,χₚ,γₚ)\n\n# ╔═╡ d0de29e0-1e36-11eb-398c-5f0b55ea281e\nθᵏ\n\n# ╔═╡ 70775a70-1e4c-11eb-3cec-11fd54e9b637\ntrain(χₚ,γₚ) \n\n# ╔═╡ Cell order:\n# ╟─8dbcf370-1dec-11eb-0a2d-e967ec1f2fde\n# ╟─c4a8db60-1dec-11eb-0c39-73a8aac79092\n# ╟─cd532e00-1dec-11eb-06d9-9b7c76e9c1ba\n# ╟─dc365e10-1dec-11eb-0e4f-95624ee468ea\n# ╟─571a5ea0-1dee-11eb-0eaf-bf746a6faa86\n# ╠═317bbe60-1ded-11eb-2faa-c3e47c0df176\n# ╟─f9af3a70-1dec-11eb-34f0-91b7fc591b87\n# ╟─78d2c0e0-1f98-11eb-06bc-b51c3b4b9f35\n# ╟─2e7709e0-1ded-11eb-2abd-d770bf1afe8a\n# ╟─b05f9930-1f97-11eb-0083-07ebd21313e0\n# ╟─cbf998e0-1f96-11eb-0a8b-a3bf631bfe02\n# ╟─4cc76c80-1f98-11eb-0c70-29aec0b92ac4\n# ╟─c0b094a0-1f98-11eb-2efb-07f680447b12\n# ╠═be0deb50-1ded-11eb-06bb-33e94217e815\n# ╟─2f5a6500-1ded-11eb-11dd-bd88bf102b98\n# ╟─30972ac0-1ded-11eb-1007-1d3833dfc264\n# ╟─bba6d590-1e1d-11eb-2df6-67bd6c5d4777\n# ╠═9837a3d0-1ded-11eb-3c49-17a45387e46e\n# ╟─2ebaad22-1dee-11eb-2fb1-f51c49ec13fb\n# ╟─d1cf31b0-1e17-11eb-22d1-916c9a331700\n# ╟─cbf654c0-1dfa-11eb-0994-85a67ded79b0\n# ╟─46484b80-1e1d-11eb-2bdc-e50b24f6b530\n# ╟─f1089b10-1e1d-11eb-120e-cdbd993d72dc\n# ╟─79bc38d0-1e1f-11eb-066c-2929340c479e\n# ╟─f5d33090-1e1f-11eb-3f25-d10f2616803d\n# ╠═7a22eab0-1def-11eb-2672-495fb9cf19f8\n# ╟─1f0e51f0-1df4-11eb-0feb-b53552fa63c9\n# ╟─58dd7720-1e09-11eb-1904-af5f9991ece5\n# ╠═628624c0-1dfa-11eb-2afb-137bf77669e1\n# ╟─259ac040-1e39-11eb-3670-f5c5519a1978\n# ╟─246cc792-1e39-11eb-3c20-f1623d8ea737\n# ╠═4c632fee-1e39-11eb-00c6-c3f2a0774005\n# ╟─c467ca00-1e08-11eb-3d41-75a38532652b\n# ╠═74604cb2-1e05-11eb-19ef-09fd04dc52e3\n# ╟─b7913600-1e0c-11eb-362e-0b4b9ef9d1aa\n# ╟─d1a88a00-1f8f-11eb-36b7-f39dabee0657\n# ╠═fa0bd460-1e23-11eb-131f-f31bec373c07\n# ╟─b405694e-1f8f-11eb-0fad-5d0c3527d206\n# ╟─d497051e-1f94-11eb-2ccb-a7d3e52570d1\n# ╠═cc73d620-1f8f-11eb-357d-b19b50c19280\n# ╟─37c52e40-1e48-11eb-1e13-7ba1bebfabc4\n# ╟─44997b82-1e48-11eb-1821-f7f3aecd8093\n# ╠═41505b10-1e34-11eb-06db-750eb3ab11cf\n# ╠═29b04780-1e44-11eb-3bcf-8b5f121d157f\n# ╠═d0de29e0-1e36-11eb-398c-5f0b55ea281e\n# ╠═d8ab5330-1e47-11eb-06b3-af3d2ee97c7b\n# ╠═86be2920-1e48-11eb-10f1-6740a2459951\n# ╟─a419b220-1e4b-11eb-1299-295bf39df3f4\n# ╠═a39cb9f0-1e4b-11eb-296e-bf19e5438416\n# ╠═70775a70-1e4c-11eb-3cec-11fd54e9b637\n", "meta": {"hexsha": "906c0c2ac320fd195c3adb592d4994c9a794da6c", "size": 10516, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "reg_linear.jl", "max_stars_repo_name": "lalvim/machinelearning", "max_stars_repo_head_hexsha": "495afd09a639baca85763ceb82c39595733b86c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reg_linear.jl", "max_issues_repo_name": "lalvim/machinelearning", "max_issues_repo_head_hexsha": "495afd09a639baca85763ceb82c39595733b86c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reg_linear.jl", "max_forks_repo_name": "lalvim/machinelearning", "max_forks_repo_head_hexsha": "495afd09a639baca85763ceb82c39595733b86c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2911877395, "max_line_length": 508, "alphanum_fraction": 0.7163370103, "num_tokens": 5230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896132, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7636659853524652}}
{"text": "function arnoldi(a::AbstractArray{T,2},b::AbstractArray{T,1},m::S = length(b)) where {T <: AbstractFloat, S <: Integer} # Exact\n\n    n = length(b)\n    if m > n\n        error(\"'m' must be no larger than the length of 'b' \")\n    end\n\n    q = zeros(n,m)\n    h = zeros(m+1,m)\n\n    β = norm(b)\n    qk = copy(b)\n\n    @views for k = 1:m\n        q[:,k] .= qk/β\n        qk .= a*q[:,k]\n        for j = 1:k\n            h[j,k] = qk'q[:,j]\n            qk .-= h[j,k]*q[:,j]\n        end\n        β = norm(qk)\n        h[k+1,k] = β\n        if β < eps(T)\n            return q[:,1:k], h[1:k,1:k], k\n        end\n    end\n\n    return q, h[1:m,1:m], m\n\nend\n\nfunction arnoldi(f::Function,x::Array{T,1},r::Array{T,1},m::S=length(x)) where {T <: AbstractFloat, S <: Integer} #Exact\n\n    n = length(x)\n    if m > n\n        error(\"'m' must be no larger than the length of 'b' \")\n    end\n\n    q = zeros(n,m)\n    h = zeros(m+1,m)\n\n    β = norm(r)\n    qk = copy(r)\n\n    @views for k = 1:m\n        q[:,k] = qk/β\n        jacvec!(qk,f,x,q[:,k])\n        for j = 1:k\n            h[j,k] = qk'q[:,j]\n            qk -= h[j,k]*q[:,j]\n        end\n        β = norm(qk)\n        h[k+1,k] = β\n        if β < eps(T)\n            return q[:,1:k], h[1:k,1:k], k\n        end\n    end\n\n    return q, h[1:m,:], m\n\nend\n\nfunction arnoldi(a::AbstractArray{T,2},b::AbstractArray{T,1},tol::T,m::S=length(b)) where {T <: AbstractFloat, S <: Integer} #Inexact\n\n    n = length(b)\n    if m > n\n        error(\"'m' must be no larger than the length of 'b' \")\n    end\n\n    q = zeros(n,m)\n    h = zeros(m+1,m)\n\n    β = norm(b)\n    qk = copy(b)\n\n    @views for k = 1:m\n        q[:,k] .= qk/β\n        qk .= a*q[:,k]\n        for j = 1:k\n            h[j,k] = qk'q[:,j]\n            qk .-= h[j,k]*q[:,j]\n        end\n        β = norm(qk)\n        h[k+1,k] = β\n        if β < tol\n            return q[1:n,1:k], h[1:k,1:k], k\n        end\n    end\n\n    return q[1:n,1:m], h[1:m,1:m], m\n\nend\n\nfunction arnoldi(f::Function,x::Array{T,1},r::Array{T,1},tol::T,m::S=length(x)) where {T <: AbstractFloat, S <: Integer} # Inexact\n\n    n = length(x)\n    if m > n\n        error(\"'m' must be no larger than the length of 'b' \")\n    end\n\n    q = zeros(n,m)\n    h = zeros(m+1,m)\n\n    β = norm(r)\n    qk = copy(r)\n\n    @views for k = 1:m\n        q[:,k] = qk/β\n        jacvec!(qk,f,x,q[:,k])\n        for j = 1:k\n            h[j,k] = qk'q[:,j]\n            qk -= h[j,k]*q[:,j]\n        end\n        β = norm(qk)\n        h[k+1,k] = β\n        if β < tol\n            return q[1:n,1:k], h[1:k,1:k], k\n        end\n    end\n\n    return q[1:n,1:m], h[1:m,1:m], m\n\nend\n\nfunction arnoldi_inplace(f::Function,x::Array{T,1},r::Array{T,1},tol::T,m::S=length(x)) where {T <: AbstractFloat, S <: Integer} # Inexact\n\n    n = length(x)\n    if m > n\n        error(\"'m' must be no larger than the length of 'b' \")\n    end\n\n    q = zeros(n,m)\n    h = zeros(m+1,m)\n\n    β = norm(r)\n    qk = copy(r)\n\n    @views for k = 1:m\n        q[:,k] = qk/β\n        jacvec_inplace!(qk,f,x,q[:,k])\n        for j = 1:k\n            h[j,k] = qk'q[:,j]\n            qk -= h[j,k]*q[:,j]\n        end\n        β = norm(qk)\n        h[k+1,k] = β\n        if β < tol\n            return q[1:n,1:k], h[1:k,1:k], k\n        end\n    end\n\n    return q[1:n,1:m], h[1:m,1:m], m\n\nend", "meta": {"hexsha": "3a0422ee750d4c5daeaabe67b34a9c092592fcc1", "size": 3229, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/arnoldi.jl", "max_stars_repo_name": "RJDennis/NLboxsolve.jl", "max_stars_repo_head_hexsha": "ab03fb574e873d7851aa3979c8e7955b146addcc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-14T00:17:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T00:17:33.000Z", "max_issues_repo_path": "src/arnoldi.jl", "max_issues_repo_name": "RJDennis/NLboxsolve.jl", "max_issues_repo_head_hexsha": "ab03fb574e873d7851aa3979c8e7955b146addcc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-11-26T18:47:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T02:06:29.000Z", "max_forks_repo_path": "src/arnoldi.jl", "max_forks_repo_name": "RJDennis/NLboxsolve.jl", "max_forks_repo_head_hexsha": "ab03fb574e873d7851aa3979c8e7955b146addcc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9675324675, "max_line_length": 138, "alphanum_fraction": 0.4310932177, "num_tokens": 1207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8577680977182187, "lm_q1q2_score": 0.7636659847502066}}
{"text": "using StatisticalRethinking\n\nn_samples = 10000\na3d = ones(n_samples,1,1)\nw = 6; l = 3; n = w +l\np = [0.5]\nfor i in 2:n_samples\n  p_new = rand(Normal(p[i-1], 0.1), 1)[1]\n  if  p_new < 0\n    p_new = abs(p_new)\n  end\n  if p_new > 1\n    p_new = 2 - p_new\n  end\n  q0 = pdf(Binomial(n, p[i-1]), w)\n  q1 = pdf(Binomial(n, p_new), w)\n  append!(p, [rand(Uniform(0, 1), 1)[1] < q1/q0 ? p_new : p[i-1]])\nend\n\na3d[:, 1, 1] = p\nchns = MCMCChains.Chains(a3d, [\"toss\"])\n\nMCMCChains.describe(chns)\n\nplot(chns)\n\nw = 6; n = 9; x = 0:0.01:1\ndensity(chns, lab=\"Samples\")\nplot!( x, pdf.(Beta( w+1 , n-w+1 ) , x ), lab=\"Conjugate solution\")\n\n# This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl\n\n", "meta": {"hexsha": "1d73fed4d71df80c98e08daf1a22536f6b151348", "size": 709, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapters/02/clip-08.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_stars_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/02/clip-08.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_issues_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/02/clip-08.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_forks_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4848484848, "max_line_length": 87, "alphanum_fraction": 0.605077574, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.890294223211224, "lm_q2_score": 0.8577680977182186, "lm_q1q2_score": 0.7636659822534106}}
{"text": "# ---\n# title: 888. Fair Candy Swap\n# id: problem888\n# author: Indigo\n# date: 2021-02-01\n# difficulty: Easy\n# categories: Array\n# link: <https://leetcode.com/problems/fair-candy-swap/description/>\n# hidden: true\n# ---\n# \n# Alice and Bob have candy bars of different sizes: `A[i]` is the size of the\n# `i`-th bar of candy that Alice has, and `B[j]` is the size of the `j`-th bar\n# of candy that Bob has.\n# \n# Since they are friends, they would like to exchange one candy bar each so that\n# after the exchange, they both have the same total amount of candy.  ( _The\n# total amount of candy  a person has is the sum of the sizes of candy bars they\n# have._)\n# \n# Return an integer array `ans` where `ans[0]` is the size of the candy bar that\n# Alice must exchange, and `ans[1]` is the size of the candy bar that Bob must\n# exchange.\n# \n# If there are multiple answers, you may return any one of them.  It is\n# guaranteed an answer exists.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: A = [1,1], B = [2,2]\n#     Output: [1,2]\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: A = [1,2], B = [2,3]\n#     Output: [1,2]\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: A = [2], B = [1,3]\n#     Output: [2,3]\n#     \n# \n# **Example 4:**\n# \n#     \n#     \n#     Input: A = [1,2,5], B = [2,4]\n#     Output: [5,4]\n#     \n# \n# \n# \n# **Note:**\n# \n#   * `1 <= A.length <= 10000`\n#   * `1 <= B.length <= 10000`\n#   * `1 <= A[i] <= 100000`\n#   * `1 <= B[i] <= 100000`\n#   * It is guaranteed that Alice and Bob have different total amounts of candy.\n#   * It is guaranteed there exists an answer.\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction fair_candy_swap(A::Vector{Int}, B::Vector{Int})\n    set_a, set_b = Set(A), Set(B)\n    dif = (sum(A) - sum(B)) ÷ 2\n    for num_a in set_a\n        ((num_a - dif) in set_b) && return [num_a, num_a - dif]\n    end\nend\n## @lc code=end\n", "meta": {"hexsha": "81bc98c8874e29d84e3b03ea13395584035d2090", "size": 1882, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/888.fair-candy-swap.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/888.fair-candy-swap.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/888.fair-candy-swap.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 22.1411764706, "max_line_length": 80, "alphanum_fraction": 0.5674814028, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.8577681049901036, "lm_q1q2_score": 0.7636659812371397}}
{"text": "\"\"\"\n2-D Gradient\n\n    gradient2(a::Array, dx::Float64=1, dy::Float=1)\n    :param a: matrix\n    :param dx: stepsize\n    :param dy: stepsize\n\n    :return dxdu: derivatives along x\n    :return dydv: derivatives along y\n\"\"\"\nfunction gradient2(a::Array, dx::Float64=1., dy::Float64=1.)\n    m,n = size(a);\n    dxdu = zeros(m,n);\n    dydv = zeros(m,n);\n\n    for i=1:m\n        dxdu[i,:] = gradient(vec(a[i,:]), dx)\n    end\n\n    for i=1:n\n        dydv[:,i] = gradient(a[:,i], dy)\n    end\n\n    return dxdu, dydv\nend\n\n\n\"\"\"\nCreates Rectangular Grid in 2-D space\n\n    meshgrid(a::LinSpace,b::LinSpace)\n\"\"\"\nfunction meshgrid(a::LinSpace,b::LinSpace)\n    grid_a = [i for i in a, j in b]';\n    grid_b = [j for i in a, j in b]';\n\n    return grid_a, grid_b\nend\n\n\n\"\"\"\nLinear interpolation\n\n    approx(xd, yd, xi)\n    :param xd: x samples\n    :param yd: response samples\n    :param xi: new x samples\n\"\"\"\nfunction approx(xd, yd, xi)\n    nd = length(xd);\n    ni = length(xi);\n\n    yi = zeros(ni);\n    for i in 1:ni\n        if (xi[i] <= xd[1])\n            t = (xi[i]-xd[1]) / (xd[2] - xd[1]);\n            yi[i] = (1.0 - t) * yd[1] + t * yd[2];\n        elseif (xd[nd] <= xi[i])\n            t = (xi[i] - xd[nd-1]) / (xd[nd] - xd[nd-1]);\n            yi[i] = (1.0 - t) * yd[nd-1] + t * yd[nd];\n        else\n            for k in 2:nd\n                if (xd[k-1] <= xi[i] && xi[i] <= xd[k])\n                    t = (xi[i] - xd[k-1]) / (xd[k] - xd[k-1]);\n                    yi[i] = (1.0 - t) * yd[k-1] + t * yd[k];\n                    break\n                end\n            end\n        end\n    end\n\n    return yi\nend\n\n\n\"\"\"\nTrapezoidal Integration\n\n    trapz(x, y, dim=1)\n    :param x: vector of time samples\n    :param y: array of response samples\n    :param dim: dimension along which to integrate\n\"\"\"\nfunction trapz(x::Array{Float64, 1}, y::Array{Float64}, dim::Integer=1)\n    perm = [dim:max(ndims(y),dim); 1:dim-1];\n    y = permutedims(y, perm);\n    if ndims(y) == 1\n        m = 1;\n    else\n        m = size(y,1);\n    end\n\n    if m == 1\n        M = length(y);\n        out = sum(diff(x).*(y[1:M-1] + y[2:M])/2.);\n    else\n        out = diff(x).' * (y[1:m-1,:] + y[2:m,:])/2.;\n        siz = size(y); siz = collect(siz); siz[1] = 1;\n        out = reshape(out, tuple(siz...));\n        out = ipermutedims(out, perm);\n        ind = find(collect(size(out)).==1);\n        out = squeeze(out,ind[1]);\n        if length(out) == 1;\n            out = out[1];\n        end\n    end\n\n    return out\nend\n\n\n\"\"\"\nCumulative Trapezoidal Integration\n\n    cumtrapz(x, y, dim=1)\n    :param x: vector describing time samples\n    :param y: array describing response\n    :param dim: dimension to integrate over\n\"\"\"\nfunction cumtrapz(x::Array{Float64, 1}, y::Array{Float64}, dim::Integer=1)\n    perm = [dim:max(length(size(y)),dim); 1:dim-1];\n    y = permutedims(y, perm);\n    if ndims(y) == 1\n        n = 1;\n        m = length(y);\n    else\n        m, n = size(y);\n    end\n\n    if n == 1\n        dt = diff(x)/2.0;\n        z = [0; cumsum(dt.*(y[1:(m-1)] + y[2:m]))];\n    else\n        dt = repmat(diff(x)/2.0,1,n);\n        z = [zeros(1,n); cumsum(dt.*(y[1:(m-1), :] + y[2:m, :]),1)];\n        z = ipermutedims(z, perm);\n    end\n\n    return z\nend\n\n\n\"\"\"\nCumulative Trapezoidal Integration using midpoint\n\n    cumtrapzmid(x, y, c)\n    :param x: time samples\n    :param y: resposne samples\n    :param c: midpoint\n\"\"\"\nfunction cumtrapzmid(x, y, c)\n    a = length(x);\n    mid = round(Integer, a/2);\n\n    # case < mid\n    fn = zeros(a);\n    tmpx = x[(mid-1):-1:1];\n    tmpy = y[(mid-1):-1:1];\n    tmp = c + cumtrapz(tmpx, tmpy);\n    fn[1:(mid-1)] = reverse(tmp);\n\n    # case >= mid\n    fn[mid:a] = c + cumtrapz(x[mid:a],y[mid:a]);\n\n    return fn\n\nend\n\n\n\"\"\"\nMultivariate Normal random number generation\n\n    mvnrand(mu, C, n)\n    :param mu: mean vector\n    :param C: covariance matrix\n    :param n: number of samples\n\"\"\"\nfunction mvnrand(mu, C, n)\n    tmp = cholfact(C, :U, Val{true});\n    R = tmp[:U];\n    R = Array(R);\n    R = R[:, tmp.piv];\n    retval = randn(n, size(R,1)) * R;\n    retval += transpose(repmat(mu, 1, n));\n    return transpose(retval)\nend\n\n\n\"\"\"\nLinear interpolation when response contains flat regions\n\n    interp1_flat(x, y, xx)\n    :param x: time samples\n    :param y: response samples\n    :param xx: new time samples\n\"\"\"\nfunction interp1_flat(x,y,xx)\n    flat = find(diff(x).<=0);\n    n = length(flat);\n\n    if n==0\n        tmp = interpolate((x,), y, Gridded(Linear()))\n        yy = tmp[xx];\n    else\n        yy = zeros(size(xx));\n        i1 = 1;\n        if flat[1] == 1\n            i2 = 1;\n            j = xx.==x[i2];\n            yy[j] = minimum(y[i2:i2+1]);\n        else\n            i2 = flat[1];\n            j = (xx.>=x[i1]) & (xx.<=x[i2]);\n            tmp = interpolate((x[i1:i2],), y[i1:i2], Gridded(Linear()))\n            yy[j] = tmp[xx[j]];\n            i1 = copy(i2);\n        end\n        for k = 2:n\n            i2 = flat[k];\n            if i2 > i1+1\n                j = (xx.>=x[i1]) & (xx.<=x[i2]);\n                yi = interpolate((x[i1+1:i2],), y[i1+1:i2], Gridded(Linear()))\n                yy[j] = tmp[xx[j]];\n            end\n            j = xx.==x[i2];\n            yy[j] = minimum(y[i2:i2+1]);\n            i1 = copy(i2);\n        end\n        i2 = length(x);\n        j = (xx.>=x[i1]) & (xx.<=x[i2]);\n        if i1+1 == i2\n            yy[j] = y[i2];\n        else\n            tmp = interpolate((x[i1+1:i2],), y[i1+1:i2], Gridded(Linear()))\n            yy[j] = tmp[xx[j]];\n        end\n    end\n\n    return yy\nend\n", "meta": {"hexsha": "0043e0f1d9c09af3ba591a5408fd161343b3f286", "size": 5476, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/misc_funcs.jl", "max_stars_repo_name": "JuliaPackageMirrors/ElasticFDA.jl", "max_stars_repo_head_hexsha": "fe9852231d04672c0792f2ca7adf754da0874f0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/misc_funcs.jl", "max_issues_repo_name": "JuliaPackageMirrors/ElasticFDA.jl", "max_issues_repo_head_hexsha": "fe9852231d04672c0792f2ca7adf754da0874f0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/misc_funcs.jl", "max_forks_repo_name": "JuliaPackageMirrors/ElasticFDA.jl", "max_forks_repo_head_hexsha": "fe9852231d04672c0792f2ca7adf754da0874f0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6280991736, "max_line_length": 78, "alphanum_fraction": 0.480642805, "num_tokens": 1850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7636202308779791}}
{"text": "ENV[\"GKSwstype\"] = \"100\" #src\n\n# # Generalized Linear Models\n#\n# Generalized Linear Models (GLMs) are a family of statistical models where the prediction\n# is based on a function of a linear predictor $x_^T\\beta$ where $x$ is a vector of features\n# and $\\beta$ is the parameter vector.  \n#\n# One of the big assumptions of GLMs is that there is a strictly increasing *link function*\n# $g$ that \"links\" the mean of the distribution $E(Y|X) = \\mu$ to the linear predictor \n# $x^T\\beta$.  In other words, our prediction of $y$ given $x$ is $g^{-1}(x^T\\beta)$.\n\n\n\n\n# The two most common GLMs are linear and logistic regression.\n\n# The GLM package\n#\n# \n\n# ## Linear Regression\n\n\n# ## Logistic Regression\n", "meta": {"hexsha": "915454112f2cf3bfcd791108ef32d29cbbc7adc6", "size": 698, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Data_Science_2/99-glms.jl", "max_stars_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_stars_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2020-02-13T00:50:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T07:57:22.000Z", "max_issues_repo_path": "Courses/Data_Science_2/99-glms.jl", "max_issues_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_issues_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2019-10-30T16:22:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-26T20:02:43.000Z", "max_forks_repo_path": "Courses/Data_Science_2/99-glms.jl", "max_forks_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_forks_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2020-02-26T11:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T22:34:53.000Z", "avg_line_length": 26.8461538462, "max_line_length": 92, "alphanum_fraction": 0.6991404011, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7636202286142703}}
{"text": "\"\"\"\nshoot(phi,xspan,lval,lder,rval,rder,init)\n\nUse the shooting method to solve a two-point boundary value problem. The ODE is\nu'' = `phi`(x,u,u') for x in `xspan`. Specify a function value or derivative at\nthe left endpoint using `lval` and `lder`, respectively, and similarly for the\nright endpoint  using `rval` and `rder`. (Use an empty array to denote an\nunknown quantity.) The value `init` is an initial guess for whichever value is\nmissing at the left endpoint.\n\nReturn vectors for the nodes, the values of u, and the values of u'.\n    \"\"\"\nfunction shoot(phi,xspan,lval,lder,rval,rder,init)\n\n    # Tolerances for IVP solver and rootfinder.\n    ivp_opt = 1e-6\n    optim_opt = 1e-5\n\n    # Evaluate the difference between computed and target values at x=b.\n    function objective(s)\n        # Combine s with the known left endpoint value.\n        v_init = isempty(lder) ?  [ lval; s[1] ]  :  [ s[1]; lder ]\n\n        # ODE posed as a first-order equation in 2 variables.\n        function shootivp(v,p,x)\n            [ v[2]; phi(x,v[1],v[2]) ]\n        end\n\n        IVP = ODEProblem(shootivp,v_init,xspan)\n        sol = solve(IVP,abstol=ivp_opt,reltol=ivp_opt)\n        x = sol.t;  v = sol;\n\n        return isempty(rder) ? v[1,end] - rval  :  v[2,end] - rder\n    end\n\n    # Find the unknown quantity at x=a by rootfinding.\n    x = [];  v = [];   # the values will be overwritten\n    s = nlsolve(objective,[init],xtol=optim_opt).zero\n\n    # Don't need to solve the IVP again. It was done within the\n    # objective function already.\n    u = v[1,:]            # solution\n    dudx = v[2,:]         # derivative\n\n    return x,u,dudx\nend\n\n\"\"\"\n    diffmat2(n,xspan)\n\nCompute 2nd-order-accurate differentiation matrices on `n`+1 points in the\ninterval `xspan`. Return a vector of nodes, and the matrices for the first\nand second derivatives.\n\"\"\"\nfunction diffmat2(n,xspan)\n    a,b = xspan\n    h = (b-a)/n\n    x = [ a + i*h for i=0:n ]   # nodes\n\n    # Define most of Dx by its diagonals.\n    dp = fill(0.5/h,n)        # superdiagonal\n    dm = fill(-0.5/h,n)       # subdiagonal\n    Dx = diagm(-1=>dm,1=>dp)\n\n    # Fix first and last rows.\n    Dx[1,1:3] = [-1.5,2,-0.5]/h\n    Dx[n+1,n-1:n+1] = [0.5,-2,1.5]/h\n\n    # Define most of Dxx by its diagonals.\n    d0 =  fill(-2/h^2,n+1)    # main diagonal\n    dp =  ones(n)/h^2         # superdiagonal and subdiagonal\n    Dxx = diagm(-1=>dp,0=>d0,1=>dp)\n\n    # Fix first and last rows.\n    Dxx[1,1:4] = [2,-5,4,-1]/h^2\n    Dxx[n+1,n-2:n+1] = [-1,4,-5,2]/h^2\n\n    return x,Dx,Dxx\nend\n\n\"\"\"\n    diffcheb(n,xspan)\n\nCompute Chebyshev differentiation matrices on `n`+1 points in the\ninterval `xspan`. Return a vector of nodes, and the matrices for the first\nand second derivatives.\n\"\"\"\nfunction diffcheb(n,xspan)\n    x = [ -cos( k*pi/n ) for k=0:n ]    # nodes in [-1,1]\n    Dx = zeros(n+1,n+1)\n    c = [2; ones(n-1); 2];    # endpoint factors\n\n    # Off-diagonal entries\n    Dx = [ (-1)^(i+j)*c[i+1]/(c[j+1]*(x[i+1]-x[j+1])) for i=0:n, j=0:n ]\n\n    # Diagonal entries\n    Dx[isinf.(Dx)] .= 0              # fix divisions by zero on diagonal\n    s = sum(Dx,dims=2)\n    Dx -= diagm(0=>s[:,1])           # \"negative sum trick\"\n\n    # Transplant to [a,b]\n    a,b = xspan\n    x = @. a + (b-a)*(x+1)/2\n    Dx = 2*Dx/(b-a)\n\n    # Second derivative\n    Dxx = Dx^2\n\n    return x,Dx,Dxx\nend\n\n\"\"\"\n     bvplin(p,q,r,xspan,lval,rval,n)\n\nUse finite differences to solve a linear bopundary value problem. The ODE is\nu''+`p`(x)u'+`q`(x)u = `r`(x) on the interval `xspan`, with endpoint function\nvalues given as `lval` and `rval`. There will be `n`+1 equally spaced nodes,\nincluding the endpoints.\n\nReturn vectors of the nodes and the solution values.\n\"\"\"\nfunction bvplin(p,q,r,xspan,lval,rval,n)\n    x,Dx,Dxx = diffmat2(n,xspan)\n\n    P = diagm(0=>p.(x))\n    Q = diagm(0=>q.(x))\n    L = Dxx + P*Dx + Q     # ODE expressed at the nodes\n\n    # Replace first and last rows using boundary conditions.\n    I = Diagonal(ones(n+1))\n    A = [ I[[1],:]; L[2:n,:]; I[[n+1],:] ]\n    b = [ lval; r.(x[2:n]); rval ]\n\n    # Solve the system.\n    u = A\\b\n\n    return x,u\nend\n\n\"\"\"\n    bvp(phi,xspan,lval,lder,rval,rder,init)\n\nUse finite differences to solve a two-point boundary value problem. The ODE is\nu'' = `phi`(x,u,u') for x in `xspan`. Specify a function value or derivative at\nthe left endpoint using `lval` and `lder`, respectively, and similarly for the\nright endpoint  using `rval` and `rder`. (Use an empty array to denote an\nunknown quantity.) The value `init` is an initial guess for whichever value is\nmissing at the left endpoint.\n\nReturn vectors for the nodes and the values of u.\n\"\"\"\nfunction bvp(phi,xspan,lval,lder,rval,rder,init)\n    n = length(init) - 1\n    x,Dx,Dxx = diffmat2(n,xspan)\n    h = x[2]-x[1]\n\n    function residual(u)\n        # Compute the difference between u'' and phi(x,u,u') at the\n        # interior nodes and appends the error at the boundaries.\n        dudx = Dx*u                   # discrete u'\n        d2udx2 = Dxx*u                # discrete u''\n        f = d2udx2 - phi.(x,u,dudx)\n\n        # Replace first and last values by boundary conditions.\n        f[1] = isempty(lder) ? (u[1] - lval)/h^2 : (dudx[1] - lder)/h\n        f[n+1] = isempty(rder) ? (u[n+1] - rval)/h^2 : (dudx[n+1] - rder)/h\n        return f\n    end\n\n    u = levenberg(residual,init)\n    return x,u[:,end]\nend\n\n\"\"\"\n    fem(c,s,f,a,b,n)\n\nUse a piecewise linear finite element method to solve a two-point boundary\nvalue problem. The ODE is (`c`(x)u')' + `s`(x)u = `f`(x) on the interval\n[`a`,`b`], and the boundary values are zero. The discretization uses `n` equal\nsubintervals.\n\nReturn vectors for the nodes and the values of u.\n\"\"\"\nfunction fem(c,s,f,a,b,n)\n    # Define the grid.\n    h = (b-a)/n\n    x = @. a + h*(0:n)\n\n    # Templates for the subinterval matrix and vector contributions.\n    Ke = [1 -1; -1 1]\n    Me = (1/6)*[2 1; 1 2]\n    fe = (1/2)*[1; 1]\n\n    # Evaluate coefficent functions and find average values.\n    cval = c.(x);   cbar = (cval[1:n]+cval[2:n+1]) / 2;\n    sval = s.(x);   sbar = (sval[1:n]+sval[2:n+1]) / 2;\n    fval = f.(x);   fbar = (fval[1:n]+fval[2:n+1]) / 2;\n\n    # Assemble global system, one interval at a time.\n    K = zeros(n-1,n-1);  M = zeros(n-1,n-1);  f = zeros(n-1);\n    K[1,1] = cbar[1]/h;  M[1,1] = sbar[1]*h/3;  f[1] = fbar[1]*h/2;\n    K[n-1,n-1] = cbar[n]/h;  M[n-1,n-1] = sbar[n]*h/3;  f[n-1] = fbar[n]*h/2;\n    for k = 2:n-1\n      K[k-1:k,k-1:k] += (cbar[k]/h) * Ke\n      M[k-1:k,k-1:k] += (sbar[k]*h) * Me\n      f[k-1:k] += (fbar[k]*h) * fe\n    end\n\n    # Solve system for the interior values.\n    u = (K+M) \\ f\n    u = [0; u; 0]      # put the boundary values into the result\n\n    return x,u\nend\n", "meta": {"hexsha": "2b027deed470a6ef1d93c3ccfd106e6420fcf4df", "size": 6656, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/functions/chapter10.jl", "max_stars_repo_name": "snowdj/fnc-extras", "max_stars_repo_head_hexsha": "ef51fada748de1326a4ce645fbcb0c2499cb2b8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 109, "max_stars_repo_stars_event_min_datetime": "2018-04-21T09:02:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T19:03:54.000Z", "max_issues_repo_path": "julia/functions/chapter10.jl", "max_issues_repo_name": "snowdj/fnc-extras", "max_issues_repo_head_hexsha": "ef51fada748de1326a4ce645fbcb0c2499cb2b8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-12-04T22:17:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T21:04:47.000Z", "max_forks_repo_path": "julia/functions/chapter10.jl", "max_forks_repo_name": "snowdj/fnc-extras", "max_forks_repo_head_hexsha": "ef51fada748de1326a4ce645fbcb0c2499cb2b8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2017-04-02T17:21:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T17:19:57.000Z", "avg_line_length": 30.9581395349, "max_line_length": 79, "alphanum_fraction": 0.5892427885, "num_tokens": 2315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7636202256881328}}
{"text": "println(5 + π)\n\nprintln(typeof(π)) # Echo the type of pi\nprintln(typeof(100)) # Echo the type of 100\nprintln(typeof(6.0000)) # Echo the type of 6.0000\n\nprintln(Sys.WORD_SIZE) # This variable indicated whether the target system is 32-bit arch or 64-bit arch\n\n# %% typeof\nhexX = 0x1\nprintln(\"typeof(hexX) ~~> \", typeof(hexX))\n\nhexX = 0x123\nprintln(\"typeof(hexX) ~~> \", typeof(hexX))\n\nhexX = 0x123456789\nprintln(\"typeof(hexX) ~~> \", typeof(hexX))\n\nx = 0b10\nprintln(\"typeof(x) ~~> \", typeof(x))\n\ny = 0o010\nprintln(\"typeof(y) ~~> \", typeof(y))\n\nfor T in [Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UInt128]\n    println(\"* $(lpad(T,7)): [$(typemin(T)),$(typemax(T))]\")\nend\n# %% End\n\n# %% Overflow behavior\nx = typemax(Int64)\nprintln(\"x ~~> \", x)\nx = x + 1\nprintln(\"x ~~> \", x)\n# x + 1 == typemax(Int64)\nprintln(x + 1 == typemax(Int64))\n# %% End\n\n# %% Overflow resolution\nprintln(10^19)\nprintln(big(10)^19)\n# %% End\n\n# %% Float\nmyFloat = 1.777\nprintln(\"typeof(myFLoat) ~~> \", typeof(myFloat))\nprintln(\"typeof(Float32(myFloat)) ~~> \", typeof(Float32(myFloat)))\n# %% End\n\n# %% Positive and Negetive zero\nprintln(\"0.0 == -0.0 ~~> \", 0.0 == -0.0)\nprintln(\"bitstring(0.0) ~~> \", bitstring(0.0))\nprintln(\"bitstring(-0.0) ~~> \", bitstring(-0.0))\n# %% End\n\n# %% Arbitrary Precision Arithmetic\nprintln(\"BigInt(typemax(Int64)) + 1 ~~> \", BigInt(typemax(Int64)) + 1)\nprintln((big\"123456789012345678901234567890\" + 1))\nprintln(typeof(big\"123456789012345678901234567890\" + 1))\nparse(BigInt, \"123456789012345678901234567890\")\nprintln(string(big\"2\"^200, base = 16))\n# %% End\n\n# %% Numeric Literal Coefficients\nx = 3\nprintln(\"x ~~> \", x)\ny = 2(x - 1)^2 - 3(x - 1) + 1\nprintln(\"y ~~> \", y)\nprintln(\"√16 ~~> \", √16)\n# %% End\n", "meta": {"hexsha": "c041cfac22177b84350cbbdab20cde610e85fc21", "size": 1723, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/julia-documentation/_2-integers-and-floats/main.jl", "max_stars_repo_name": "iktefish/_s", "max_stars_repo_head_hexsha": "0e7866191cb679e2c5fead9f46a2ec84da205cbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/julia-documentation/_2-integers-and-floats/main.jl", "max_issues_repo_name": "iktefish/_s", "max_issues_repo_head_hexsha": "0e7866191cb679e2c5fead9f46a2ec84da205cbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/julia-documentation/_2-integers-and-floats/main.jl", "max_forks_repo_name": "iktefish/_s", "max_forks_repo_head_hexsha": "0e7866191cb679e2c5fead9f46a2ec84da205cbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2676056338, "max_line_length": 104, "alphanum_fraction": 0.6320371445, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.9005297781091839, "lm_q1q2_score": 0.7636202242155202}}
{"text": "using Distributions, Random, Plots; pyplot()\nRandom.seed!(4)\n\nfunction simulateMM1DoobGillespie(lambda,mu,Q0,T)\n    t, Q = 0.0 , Q0\n    tValues, qValues = [0.0], [Q0]\n    while t<T\n        if Q == 0\n            t += rand(Exponential(1/lambda))\n            Q = 1\n        else\n            t += rand(Exponential(1/(lambda+mu)))\n            Q += 2(rand() < lambda/(lambda+mu)) -1\n        end\n        push!(tValues,t)\n        push!(qValues,Q)\n    end\n    return [tValues, qValues]\nend\n\nfunction stichSteps(epochs,q)\n    n = length(epochs)\n    newEpochs  = [ epochs[1] ]\n    newQ = [ q[1] ]\n    for i in 2:n\n        push!(newEpochs,epochs[i])\n        push!(newQ,q[i-1])\n        push!(newEpochs,epochs[i])\n        push!(newQ,q[i])\n    end\n    return [newEpochs, newQ]\nend\n\nlambda, mu = 0.7, 1.0\nTplot, Testimation = 200, 10^7\nQ0 = 20\n\neL,qL = simulateMM1DoobGillespie(lambda, mu ,Q0, Testimation)\nmeanQueueLength = (eL[2:end]-eL[1:end-1])'*qL[1:end-1]/last(eL)\nrho = lambda/mu\nprintln(\"Estimated mean queue length: \", meanQueueLength )\nprintln(\"Theoretical mean queue length: \", rho/(1-rho) )\n\nepochs, qValues = simulateMM1DoobGillespie(lambda, mu, Q0,Tplot)\nepochsForPlot, qForPlot = stichSteps(epochs,qValues)\nplot(epochsForPlot,qForPlot, \n\tc=:blue, xlims=(0,Tplot), ylims=(0,25), xlabel=\"Time\",\n\tylabel=\"Customers in queue\", legend=:none)", "meta": {"hexsha": "8e5c3d22bb9d63e178a7d79804f1544364f405de", "size": 1334, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "10_chapter/mm1Gillespie.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "10_chapter/mm1Gillespie.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "10_chapter/mm1Gillespie.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 27.7916666667, "max_line_length": 64, "alphanum_fraction": 0.6131934033, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7636202212893833}}
{"text": "## exponential.jl : implementation of exponential covariance function\n\n## Exponential ##\nstruct Exponential{T} <: IsotropicCovarianceStructure{T}\n    λ::T\n    σ::T\n    p::T\n\n    function Exponential{T}(λ::T, σ::T, p::T) where T\n        λ > 0 || throw(DomainError(λ, \"correlation length λ of exponential covariance cannot be negative or zero\"))\n        σ > 0 || throw(DomainError(σ, \"marginal standard deviation σ of exponential covariance cannot be negative or zero\"))\n        p >= 1 || throw(DomainError(p, \"in p-norm, p must be greater than or equal to 1\"))\n        isinf(p) && throw(DomainError(p, \"in p-norm, p cannot be infinity\"))\n\n        new{T}(λ, σ, p)\n    end\nend\n\n\"\"\"\n    Exponential(λ, [σ = 1], [p = 2])\n\nExponential covariance structure with correlation length `λ`, (optional) marginal standard deviation `σ` and (optional) `p`-norm defined as\n\n``C(x, y) = σ \\\\exp\\\\left(-\\\\displaystyle\\\\frac{ρ}{λ}\\\\right)``\n\nwith ``ρ = ||x - y||_p``.\n\n# Examples\n```jldoctest\njulia> Exponential(0.1)\nexponential (λ=0.1, σ=1.0, p=2.0)\n\njulia> Exponential(1.0, σ=2)\nexponential (λ=1.0, σ=2.0, p=2.0)\n\n```\nSee also: [`Linear`](@ref), [`Spherical`](@ref), [`Whittle`](@ref), [`Gaussian`](@ref), [`SquaredExponential`](@ref), [`Matern`](@ref)\n\"\"\"\nExponential(λ::Real; σ::Real=1.0, p::Real=2) = Exponential{promote_type(typeof(λ),typeof(σ),typeof(p))}(promote(λ, σ, p)...)\n\n# evaluate exponential covariance\napply(e::Exponential, x::Real) = exp(-x / e.λ)\n\n# short name\nshortname(::Exponential) = \"exponential\"\n", "meta": {"hexsha": "191807aba765834397295896dfd257d683a30242", "size": 1502, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/covariance_functions/exponential.jl", "max_stars_repo_name": "Philippe1123/GaussianRandomFields.jl", "max_stars_repo_head_hexsha": "86ae443ae46d27a45d4afcdceb453c48cbfd9807", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2018-02-01T10:43:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:29:00.000Z", "max_issues_repo_path": "src/covariance_functions/exponential.jl", "max_issues_repo_name": "Philippe1123/GaussianRandomFields.jl", "max_issues_repo_head_hexsha": "86ae443ae46d27a45d4afcdceb453c48cbfd9807", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2018-01-17T18:32:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T07:14:13.000Z", "max_forks_repo_path": "src/covariance_functions/exponential.jl", "max_forks_repo_name": "Philippe1123/GaussianRandomFields.jl", "max_forks_repo_head_hexsha": "86ae443ae46d27a45d4afcdceb453c48cbfd9807", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-08-01T17:13:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T11:19:26.000Z", "avg_line_length": 32.652173913, "max_line_length": 139, "alphanum_fraction": 0.6418109188, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529778109184, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7636202121058794}}
{"text": "module FiniteDifferenceDerivatives\n\nusing ArrayViews\n\ninclude(\"specialized.jl\")\n\nexport fdd!, fdd, fddmatrix, fddat\n\n\n# returns a sparse matrix D such that D*u is a der-derivative of specified order\nfunction fddmatrix{T<:Number}(x::AbstractVector{T},der::Int,order::Int)\n    npts = length(x)\n    m = zeros(T,npts,npts)\n    f = eye(T,npts)\n    for i = 1:npts\n        m[:,i]=fdd(f[:,i],x,der,order)\n    end\n    return sparse(m)\nend\n\n\n# compute the der-derivative using order-point scheme\nfunction fdd!{T<:Number}(df::AbstractVector{T},f::AbstractVector{T},x::AbstractVector{T},der::Int,order::Int)\n    npts = length(x)\n    if order < der\n        error(\"Order can not be smaller than der\")\n    elseif npts < order\n        error(\"Number of mesh points shouldn't be smaller than order\")\n    end\n\n    # specialized implementation for lower orders\n    if der == 1 && order == 3\n        fdd13!(df,f,x)\n    elseif der == 2 && order == 3\n        fdd23!(df,f,x)\n    elseif der == 1\n        fdd1n!(df,f,x,order)\n    else\n        # proceed with general implementation\n\n        c = Array(T,order,der+1)\n\n        for N = 1:npts\n            # N1 is the leftmost point of the stencil\n            N1    = min(max(1,N-div(order-1,2)),npts-order+1)\n            df[N] = fddcore(f,x,der,x[N],N1,order,c)\n        end\n    end\n\nend\n\n\nfunction fdd{T<:Number}(f::AbstractVector{T},x::AbstractVector{T},der::Int,order::Int)\n    df = Array(T,length(f))\n    fdd!(df,f,x,der,order)\n    return df\nend\n\n\nfunction fddcore{T<:Number}(f::AbstractVector{T},\n                            x::AbstractVector{T},\n                            der::Int,\n                            x0::Real,\n                            N1::Int,\n                            order::Int,\n                            c::Matrix{T})\n\n    generatec!(c,x0,x,N1)\n\n    dfN = zero(T)\n    @simd for j = 1:order\n        @inbounds dfN += c[j,der+1]*f[N1-1+j]\n    end\n    return dfN\nend\n\nfunction fddat{T<:Number}(f::AbstractVector{T},\n                          x::AbstractVector{T},\n                          der::Int,\n                          x0::Real)\n\n    if length(f) != length(x)\n        error(\"x and f must have the same size\")\n    end\n\n    N1 = 1\n    order = length(x)\n    c = Array(T,order,der+1)\n    return fddcore(f,x,der,x0,N1,order,c)\nend\n\n\n# generate the coefficients c\nfunction generatec!{T}(c::Matrix{T},x0::Real,x::AbstractVector{T},N1::Int)\n    order = size(c,1)\n    der   = size(c,2)-1\n\n    if N1 < 1 || N1+order-1 > length(x)\n        error(\"N1=$N1 and order=$order are out of bounds\")\n    end\n\n    c1 = one(T)\n    @inbounds c4 = x[N1] - x0\n    c[:] = zero(T)\n    c[1] = one(T)\n    for i=1:order-1\n        mn = min(i,der)\n        c2 = one(T)\n        c5 = c4\n        @inbounds c4 = x[i+N1] - x0\n        j = 0\n        while j <= i-1\n            @inbounds c3 = x[i+N1] - x[j+N1]\n            c2 = c2*c3\n            if j == i-1\n                s = mn\n                while s >= 1\n                    @inbounds c[i+1,s+1] = c1*(s*c[i,s] - c5*c[i,s+1])/c2\n                    s-=1\n                end\n                @inbounds c[i+1,1] = -c1*c5*c[i,1]/c2\n            end\n            s = mn\n            while s >= 1\n                @inbounds c[j+1,s+1] = (c4*c[j+1,s+1] - s*c[j+1,s])/c3\n                s-=1\n            end\n            @inbounds c[j+1,1] = c4*c[j+1,1]/c3\n            j+=1\n        end\n        c1 = c2\n    end\nend\n\n\nend # module\n", "meta": {"hexsha": "20d0d48cef7fb95f3b53ce12ab648d16e73acfe8", "size": 3380, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FiniteDifferenceDerivatives.jl", "max_stars_repo_name": "pwl/FiniteDifferenceDerivatives.jl", "max_stars_repo_head_hexsha": "a17000f3f00064506a3d505db25c681cee71b6d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FiniteDifferenceDerivatives.jl", "max_issues_repo_name": "pwl/FiniteDifferenceDerivatives.jl", "max_issues_repo_head_hexsha": "a17000f3f00064506a3d505db25c681cee71b6d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FiniteDifferenceDerivatives.jl", "max_forks_repo_name": "pwl/FiniteDifferenceDerivatives.jl", "max_forks_repo_head_hexsha": "a17000f3f00064506a3d505db25c681cee71b6d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6715328467, "max_line_length": 109, "alphanum_fraction": 0.4934911243, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947179030094, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7636192550698664}}
{"text": "\"\"\"\n`solve(P::Problem, O::Options=DefaultOptions)::Tuple{Vector, Vector}`\n\nSolve the problem `P` using options `O`.\n\nSee `Problem` and `Options` for more info about how to state a problem and change the\ndefault options.\n\"\"\"\nfunction solve(P::Problem, O::Options=DefaultOptions)::Tuple{Vector, Vector}\n\n    # Unpack the data structures\n    @unpack α, β, γ, δ, p, q, a, b, A, y₀, z₀ = P\n    @unpack n = O\n\n    # Compute the step\n    h = (b - a) / n\n\n    # Prepare the result arrays\n    y = Vector{Float64}(undef, n+1); z = copy(y)\n\n    # Put the boundary values first\n    y[1] = y₀\n    z[1] = z₀\n\n    # Compute the rest\n    for i in 1:n\n        x = a + i * h\n        yᵢ₊₁(x, zᵢ₊₁) = (y[i] + h * (β(A) * zᵢ₊₁ + p(x, zᵢ₊₁))) / (1 - h * α(A))\n        z[i+1] = find_zero(\n            (zᵢ₊₁) -> -zᵢ₊₁ + z[i] + h * (γ(A) * yᵢ₊₁(x, zᵢ₊₁) + δ(A) * zᵢ₊₁ + q(x, zᵢ₊₁)),\n            z[i],\n        )\n        y[i+1] = yᵢ₊₁(x, z[i+1])\n    end\n\n    return y, z\n\nend\n", "meta": {"hexsha": "56fb40635868a39463663653ccd3b1eb9aeff4cb", "size": 949, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "A2/src/Internal/Functions/solve.jl", "max_stars_repo_name": "paveloom-p/P12", "max_stars_repo_head_hexsha": "8dfa2a5662fc1fbcb683615eafda28ec22821f56", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A2/src/Internal/Functions/solve.jl", "max_issues_repo_name": "paveloom-p/P12", "max_issues_repo_head_hexsha": "8dfa2a5662fc1fbcb683615eafda28ec22821f56", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A2/src/Internal/Functions/solve.jl", "max_forks_repo_name": "paveloom-p/P12", "max_forks_repo_head_hexsha": "8dfa2a5662fc1fbcb683615eafda28ec22821f56", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3333333333, "max_line_length": 91, "alphanum_fraction": 0.5142255005, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7636192497430948}}
{"text": "struct Point2D{T<:Real}\n    x::T\n    y::T\nend\n\nstruct Point3D{T<:Real}\n    x::T\n    y::T\n    z::T\nend\n\n\"\"\"\n    euclidean2DRounded(i1::Int,i2::Int, map::Dict{Int, Point2D})\n\nTakes in a map of indexes to points and two indexes\nReturns the euclidean distance on the xy-plane between the two points rounded to the nearest integer\n\n# Arguments\n- `i1::Int`: an index of a point in the map\n- `i2::Int`: another index of a point in the map\n- `map::Dict{Int, Point2D}`: the map of indexes to points\n\"\"\"\nfunction euclidean2DRounded(i1::Int,i2::Int, map::Dict{Int, Point2D})\n    return euclidean2DRounded(map[i1],map[i2])\nend\n\n\"\"\"\n    euclidean2DRounded(p1::Point2D,p2::Point2D)\n\nTakes in a map of indexes to points and two indexes\nReturns the euclidean distance on the xy-plane between the two points rounded to the nearest integer\n\n# Arguments\n- `p1::Point2D`: a point to compare\n- `p2::Point2D`: another point to compare\n\"\"\"\nfunction euclidean2DRounded(p1::Point2D,p2::Point2D)\n    return round(sqrt(((p1.x - p2.x)^2)+((p1.y - p2.y)^2)))\nend\n\n\"\"\"\n    euclidean2D(i1::Int,i2::Int, map::Dict{Int, Point2D})\n\nTakes in a map of indexes to points and two indexes\nReturns the euclidean distance on the xy-plane between the two points\n\n# Arguments\n- `i1::Int`: an index of a point in the map\n- `i2::Int`: another index of a point in the map\n- `map::Dict{Int, Point2D}`: the map of indexes to points\n\"\"\"\nfunction euclidean2D(i1::Int,i2::Int, map::Dict{Int, Point2D})\n    return euclidean2D(map[i1],map[i2])\nend\n\n\"\"\"\n    euclidean2D(p1::Point2D,p2::Point2D)\n\nTakes in a map of indexes to points and two indexes\nReturns the euclidean distance on the xy-plane between the two points\n\n# Arguments\n- `p1::Point2D`: a point to compare\n- `p2::Point2D`: another point to compare\n\"\"\"\nfunction euclidean2D(p1::Point2D,p2::Point2D)\n    return sqrt(((p1.x - p2.x)^2)+((p1.y - p2.y)^2))\nend\n\n\"\"\"\n    euclidean3DRounded(i1::Int,i2::Int, map::Dict{Int, Point3D})\n\nTakes in a map of indexes to points and two indexes\nReturns the euclidean distance on the xyz-plane between the two points rounded to the nearest integer\n\n# Arguments\n- `i1::Int`: an index of a point in the map\n- `i2::Int`: another index of a point in the map\n- `map::Dict{Int, Point3D}`: the map of indexes to points\n\"\"\"\nfunction euclidean3DRounded(i1::Int,i2::Int, map::Dict{Int, Point3D})\n    return euclidean3DRounded(map[i1],map[i2])\nend\n\n\"\"\"\n    euclidean3DRounded(p1::Point3D,p2::Point3D)\n\nTakes in a map of indexes to points and two indexes\nReturns the euclidean distance on the xyz-plane between the two points rounded to the nearest integer\n\n# Arguments\n- `p1::Point3D`: a point to compare\n- `p2::Point3D`: another point to compare\n\"\"\"\nfunction euclidean3DRounded(p1::Point3D,p2::Point3D)\n    return round(sqrt(((p1.x - p2.x)^2)+((p1.y - p2.y)^2)+((p1.z - p2.z)^2)))\nend\n\n\"\"\"\n    euclidean3D(i1::Int,i2::Int, map::Dict{Int, Point3D})\n\nTakes in a map of indexes to points and two indexes\nReturns the euclidean distance on the xyz-plane between the two points\n\n# Arguments\n- `i1::Int`: an index of a point in the map\n- `i2::Int`: another index of a point in the map\n- `map::Dict{Int, Point3D}`: the map of indexes to points\n\"\"\"\nfunction euclidean3D(i1::Int,i2::Int, map::Dict{Int, Point3D})\n    return euclidean3D(map[i1],map[i2])\nend\n\n\"\"\"\n    euclidean3D(p1::Point3D,p2::Point3D)\n\nTakes in a map of indexes to points and two indexes\nReturns the euclidean distance on the xyz-plane between the two points\n\n# Arguments\n- `p1::Point3D`: a point to compare\n- `p2::Point3D`: another point to compare\n\"\"\"\nfunction euclidean3D(p1::Point3D,p2::Point3D)\n    return sqrt(((p1.x - p2.x)^2)+((p1.y - p2.y)^2)+((p1.z - p2.z)^2))\nend\n", "meta": {"hexsha": "13365a3d57c61b5814e581b802d62b5f26fe4694", "size": 3662, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/model/geometry/euclideanGeometry.jl", "max_stars_repo_name": "IsaacRudich/PnB_SOP", "max_stars_repo_head_hexsha": "4d28dc183bcb1427e68ed8d9d8f0030d195c10c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/model/geometry/euclideanGeometry.jl", "max_issues_repo_name": "IsaacRudich/PnB_SOP", "max_issues_repo_head_hexsha": "4d28dc183bcb1427e68ed8d9d8f0030d195c10c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/model/geometry/euclideanGeometry.jl", "max_forks_repo_name": "IsaacRudich/PnB_SOP", "max_forks_repo_head_hexsha": "4d28dc183bcb1427e68ed8d9d8f0030d195c10c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8346456693, "max_line_length": 101, "alphanum_fraction": 0.7007099945, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065459, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7636192456947727}}
{"text": "export prime_plane\n\n\n\"\"\"\n`prime_plane(n)` returns a finite projective plane of order `n` provided\n`n` is prime.\n\"\"\"\nfunction prime_plane(p::Int)\n    @assert isprime(p) \"$p is not prime\"\n    alist = [ [a,b,1] for a=0:p-1 for b=0:p-1 ]\n    blist = [ [a,1,0] for a=0:p-1 ]\n    clist = [ [1,0,0] ]\n\n    list = [alist; blist; clist ]\n\n    n = length(list)\n\n    A = zeros(Int,n,n)\n    for i=1:n\n        for j=1:n\n            d = list[i]' * list[j]\n            A[i,j] = mod(d[1],p) == 0\n        end\n    end\n    return A\nend\n", "meta": {"hexsha": "82f9838fc52b2b961f54d595a1e63e79493e27c5", "size": 517, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/prime_plane.jl", "max_stars_repo_name": "scheinerman/BalancedIncompleteBlockDesigns.jl", "max_stars_repo_head_hexsha": "7e68d67c62ad35763c2092d042b472ed418042ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/prime_plane.jl", "max_issues_repo_name": "scheinerman/BalancedIncompleteBlockDesigns.jl", "max_issues_repo_head_hexsha": "7e68d67c62ad35763c2092d042b472ed418042ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/prime_plane.jl", "max_forks_repo_name": "scheinerman/BalancedIncompleteBlockDesigns.jl", "max_forks_repo_head_hexsha": "7e68d67c62ad35763c2092d042b472ed418042ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:13:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T01:13:16.000Z", "avg_line_length": 19.1481481481, "max_line_length": 72, "alphanum_fraction": 0.5125725338, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9566342049451596, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7635727689281707}}
{"text": "\n# Lets check normalization\nusing GeometryTypes\nusing Makie\nusing Colors\nusing JuliennedArrays\n\nexport spherical_plot, complex_spherical_plot\n\nfunction sampleSphere(n::Int)\n    map(normalize, Slices(randn(3,n),1))\nend\n\nfunction complexImage(vals::Array{Complex{Float64}}) \n    max = maximum(abs.(vals))\n    map(x -> HSV(angle(x)*360/(2π),(abs(x)/max)^.5,1),vals) \nend\n\n\nfunction spherical_plot(fun::Function, n::Int)\n    # n sets the resolution\n    θ = [0;(0.5:n-0.5)/n;1]\n    φ = [(0:2n-2)*2/(2n-1);2]\n    x = [cospi(φ)*sinpi(θ) for θ in θ, φ in φ]\n    y = [sinpi(φ)*sinpi(θ) for θ in θ, φ in φ]\n    z = [cospi(θ) for θ in θ, φ in φ]\n    vals = map(((x,y,z) -> fun( [x,y,z])), x,y,z);\n    s = Makie.surface(x, y, z, color = complexImage(vals))\nend\n\nfunction comptosphere(z::Complex)\n    # solve for the \n    x = real(z)\n    y = imag(z)\n    t = 2/(1+abs(z)^2)\n    [t*x,t*y,1-t]\nend\n\nfunction complex_spherical_plot(fun::Function, n::Int)\n    # plots a function of the complex plane on the riemann sphere\n    function spheretocomp(r::Array)\n        # solve for the complex plane point\n        x = r[1]\n        y = r[2]\n        t = 1-r[3]\n        z = (x + im*y)/t\n    end\n    spherical_plot((x->fun(spheretocomp(x))), n)\nend\n", "meta": {"hexsha": "4a04d2703212c6c5af772a92d0ae79bc4ed3ad32", "size": 1223, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SphericalPlotting.jl", "max_stars_repo_name": "chelate/SphericalLearning.jl", "max_stars_repo_head_hexsha": "c4d8c0918d60c87a67843b3444bac88a53649b4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SphericalPlotting.jl", "max_issues_repo_name": "chelate/SphericalLearning.jl", "max_issues_repo_head_hexsha": "c4d8c0918d60c87a67843b3444bac88a53649b4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SphericalPlotting.jl", "max_forks_repo_name": "chelate/SphericalLearning.jl", "max_forks_repo_head_hexsha": "c4d8c0918d60c87a67843b3444bac88a53649b4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.46, "max_line_length": 65, "alphanum_fraction": 0.6042518397, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342024724487, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7635727646582303}}
{"text": "# # Implement your own numerical methods to solve\n#\n# $$\n# y'(t) = 1 - y(t),  t \\in [0,5],  y(0) = 0.\n# $$\n\n# --\n\n# ## Explicit Euler\n\n\neuler(f, t, y, h) = t + h, y + h * f(t, y)\n\n# ## Runge-Kutta 2nd order\n\nrk2(f, t, y, h) = begin\n    ỹ = y + h / 2 * f(t, y)\n    t + h, y + h * f(t + h / 2, ỹ)\nend\n\n# ---\n\n# ## Runge-Kutta 4th order\n\nfunction rk4(f, t, y, dt)\n\n    y₁ = dt * f(t, y)\n    y₂ = dt * f(t + dt / 2, y + y₁ / 2)\n    y₃ = dt * f(t + dt / 2, y + y₂ / 2)\n    y₄ = dt * f(t + dt, y + y₃)\n\n    t + dt, y + (y₁ + 2 * y₂ + 2 * y₃ + y₄) / 6\n\nend\n\n# ---\n\n# ## Solve function\n\nfunction dsolve(f, method, t₀, y₀, h, nsteps)\n\n    t = zeros(Float64, nsteps)\n    y = similar(t)\n\n    t[1] = t₀\n    y[1] = y₀\n\n    for i = 2:nsteps\n        t[i], y[i] = method(f, t[i-1], y[i-1], h)\n    end\n\n    t, y\n\nend\n\n# ---\n\n# ## Plot solutions\n\nusing Plots\n\nnsteps, tfinal = 7, 5.0\nt₀, x₀ = 0.0, 0.0\ndt = tfinal / (nsteps - 1)\nf(t, x) = 1 - x\n\nt, y_euler = dsolve(f, euler, t₀, x₀, dt, nsteps)\n\nt, y_rk2 = dsolve(f, rk2, t₀, x₀, dt, nsteps)\n\nt, y_rk4 = dsolve(f, rk4, t₀, x₀, dt, nsteps)\n\n# ---\n\nplot(t, y_euler; marker = :o, label = \"Euler\")\nplot!(t, y_rk2; marker = :d, label = \"RK2\")\nplot!(t, y_rk4; marker = :p, label = \"RK4\")\nplot!(t -> 1 - exp(-t); line = 3, label = \"true solution\")\nsavefig(\"dsolve.png\") #hide\n# ![dsolve](dsolve.png)\n\n# ---\n\n# ## DifferentialEquations.jl\n\nusing DifferentialEquations\n\nf(y, p, t) = 1.0 - y\ny₀, t = 0.0, (0.0, 5.0)\n\nprob = ODEProblem(f, y₀, t)\n\nsol_euler = solve(prob, Euler(), dt = 1.0)\nsol = solve(prob)\n\n# ---\n\nplot(sol_euler, label = \"Euler\")\nplot!(sol, label = \"default\")\nplot!(1:0.1:5, t -> 1.0 - exp(-t), lw = 3, ls = :dash, label = \"True Solution!\")\n\nsavefig(\"diffeq.png\"); nothing #hide\n\n# ![diffeq](diffeq.png)\n\n# ---\n\n# `sol.t` is the array of time points that the solution was saved at\n\nsol.t\n\n# `sol.u` is the array of solution values\n\nsol.u\n\n# ---\n\nfunction lorenz(du, u, p, t)\n    du[1] = 10.0 * (u[2] - u[1])\n    du[2] = u[1] * (28.0 - u[3]) - u[2]\n    du[3] = u[1] * u[2] - (8 / 3) * u[3]\nend\n\nu0 = [1.0; 0.0; 0.0]\ntspan = (0.0, 100.0)\nprob = ODEProblem(lorenz, u0, tspan)\n\nsol = solve(prob)\n\n# ---\n\nplot(sol, vars = (1, 2, 3))\n\nsavefig(\"lorenz.png\"); nothing #hide\n\n# ![lorenz](lorenz.png)\n\n# ---\n\nusing ParameterizedFunctions\n\nlotka_volterra = @ode_def begin\n  d🐁 = α*🐁  - β*🐁*🐈\n  d🐈 = -γ*🐈 + δ*🐁*🐈\nend α β γ δ\n\nu0 = [1.0, 1.0] # Initial condition\n\ntspan = (0.0, 10.0) # Simulation interval \ntsteps = 0.0:0.1:10.0 # intermediary points\n\np = [1.5, 1.0, 3.0, 1.0] # equation parameters: p = [α, β, δ, γ]\n\nprob = ODEProblem(lotka_volterra, u0, tspan, p)\nsol = solve(prob)\n\n# ---\n\n# # Type-Dispatch Programming\n#\n# - Centered around implementing the generic template of the algorithm not around building representations of data.\n# - The data type choose how to efficiently implement the algorithm.\n# - With this feature share and reuse code is very easy\n#\n# [JuliaCon 2019 | The Unreasonable Effectiveness of Multiple Dispatch | Stefan Karpinski](https://youtu.be/kc9HwsxE1OY)\n\n# ---\n\n# Simple gravity pendulum\n\nusing DifferentialEquations, Plots\n\ng = 9.79 # Gravitational constants\nL = 1.00 # Length of the pendulum\n\n#Initial Conditions\nu₀ = [0, π / 60] # Initial speed and initial angle\ntspan = (0.0, 6.3) # time domain\n\n#Define the problem\nfunction simplependulum(du, u, p, t)\n    θ = u[1]\n    dθ = u[2]\n    du[1] = dθ\n    du[2] = -(g/L)*θ\nend\n\nprob = ODEProblem(simplependulum, u₀, tspan)\nsol = solve(prob, Tsit5(), reltol = 1e-6)\n\n\n# ---\n\n# Analytic and computed solution\nu = u₀[2] .* cos.(sqrt(g / L) .* sol.t)\n\nscatter(sol.t, getindex.(sol.u, 2), label = \"Numerical\")\nplot!(sol.t, u, label = \"Analytic\")\nsavefig(\"pendulum1.svg\"); nothing # hide\n\n# ![](pendulum1.svg)\n\n# ---\n\n# [Numbers with Uncertainties](http://tutorials.juliadiffeq.org/html/type_handling/02-uncertainties.html)\n\nusing Measurements\n\ng = 9.79 ± 0.02; # Gravitational constants\nL = 1.00 ± 0.01; # Length of the pendulum\n\n#Initial Conditions\nu₀ = [0 ± 0, π / 60 ± 0.01] # Initial speed and initial angle\n\n#Define the problem\nfunction simplependulum(du, u, p, t)\n    θ = u[1]\n    dθ = u[2]\n    du[1] = dθ\n    du[2] = -(g/L)*θ\nend\n\n#Pass to solvers\nprob = ODEProblem(simplependulum, u₀, tspan)\nsol = solve(prob, Tsit5(), reltol = 1e-6);\nnothing # hide\n\n#md # ---\n\n# Analytic solution\nu = u₀[2] .* cos.(sqrt(g / L) .* sol.t)\n\nplot(sol.t, getindex.(sol.u, 2), label = \"Numerical\")\nplot!(sol.t, u, label = \"Analytic\")\nsavefig(\"pendulum2.svg\"); nothing # hide\n\n# ![](pendulum2.svg)\n\n# ---\n", "meta": {"hexsha": "08eef0baee462d515a8d0701a12a5bc4410150c8", "size": 4495, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/02.RungeKuttaMethods.jl", "max_stars_repo_name": "pnavaro/JuliaSMAI2021", "max_stars_repo_head_hexsha": "1ba72998ada9b8fee19f0547def441df0c51a119", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/02.RungeKuttaMethods.jl", "max_issues_repo_name": "pnavaro/JuliaSMAI2021", "max_issues_repo_head_hexsha": "1ba72998ada9b8fee19f0547def441df0c51a119", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/02.RungeKuttaMethods.jl", "max_forks_repo_name": "pnavaro/JuliaSMAI2021", "max_forks_repo_head_hexsha": "1ba72998ada9b8fee19f0547def441df0c51a119", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7291666667, "max_line_length": 120, "alphanum_fraction": 0.583759733, "num_tokens": 1822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201266, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7635638665798671}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 94f8e29e-ef91-11eb-1ae9-29bc46fa505a\nbegin\n\tusing Pkg\n    Pkg.activate(joinpath(Pkg.devdir(), \"MLCourse\"))\n\tusing Plots, DataFrames, Random, CSV, MLJ, MLJLinearModels\nend\n\n# ╔═╡ 12d5824c-0873-49a8-a5d8-f93c73b633ae\nusing PlutoUI; PlutoUI.TableOfContents()\n\n# ╔═╡ 20c5c7bc-664f-4c04-8215-8f3a9a2095c9\nbegin\n    using MLCourse\n    MLCourse.list_notebooks(@__FILE__)\nend\n\n# ╔═╡ 8217895b-b120-4b08-b18f-d921dfdddf10\nmd\"# Linear Regression\n\n## Wind speed prediction with one predictor\n\"\n\n# ╔═╡ 9f84bcc5-e5ab-4935-9076-c19e9bd668e8\nweather = CSV.read(joinpath(@__DIR__, \"..\", \"data\", \"weather2015-2018.csv\"), DataFrame);\n\n# ╔═╡ 34e527f2-ef80-4cb6-be3a-bee055eca125\nbegin\n    training_set1 = (X = (LUZ_pressure = weather.LUZ_pressure[1:end-5],),\n                     y = weather.LUZ_wind_peak[6:end])\n    m1 = machine(LinearRegressor(), training_set1.X, training_set1.y) |> fit!\nend;\n\n# ╔═╡ 006fc1eb-50d5-4206-8c87-53e873f158f4\nbegin\n    scatter(training_set1.X.LUZ_pressure[1:10:end],\n            training_set1.y[1:10:end], label = \"data\")\n    plot!(fitted_linear_func(m1), label = \"linear fit\", w = 3)\nend\n\n# ╔═╡ e4712ebe-f395-418b-abcc-e10ada4b05c2\nmd\"Let us inspect the results.\nFirst we look at the fitted parameters.\nWe find that there is a negative correlation between the pressure in Luzern\nand the wind speed 5 hours later in Luzern.\n\"\n\n# ╔═╡ 8c9ae8f7-81b2-4d60-a8eb-ded5364fe0cc\nfitted_params(m1)\n\n# ╔═╡ f4f890b6-0ad4-4155-9321-15d673e15489\nmd\"Next we predict the mean for different pressure values the distribution of\n    wind speeds. In the probabilistic interpretation of supervised learning,\n    standard linear regression finds conditional normal distributions with\n    input-dependent mean ``\\mu = \\hat y = \\theta_0 + \\theta_1 x`` and\n    constant standard deviation σ.\n\"\n\n# ╔═╡ 9b62c374-c26e-4990-8ffc-790928e62e88\npredict(m1, (LUZ_pressure = [930., 960., 990.],))\n\n# ╔═╡ 7923a0a8-3033-4dde-91e8-22bf540c9866\nmd\"We use the root-mean-squared-error (`rmse`) = ``\\sqrt{\\frac1n\\sum_{i=1}^n(y_i - \\hat y_i)^2}`` to evaluate our training error. To compute the test error, we use hourly data from 2019 to 2020.\n\"\n\n# ╔═╡ 57f352dc-55ee-4e14-b68d-698938a97d92\nrmse(predict(m1, training_set1.X), training_set1.y)\n\n# ╔═╡ b0de002f-3f39-4378-8d68-5c4606e488b7\nbegin\n    weather_test = CSV.read(joinpath(@__DIR__, \"..\", \"data\", \"weather2019-2020.csv\"), DataFrame);\n    test_set1 = (X = (LUZ_pressure = weather_test.LUZ_pressure[1:end-5],),\n                     y = weather_test.LUZ_wind_peak[6:end])\nend\n\n# ╔═╡ ce536f60-68b3-4901-bd6a-c96378054b12\nrmse(predict(m1, test_set1.X), test_set1.y)\n\n# ╔═╡ c65b81bd-395f-4461-a73b-3535903cb2d7\nmd\"## Multiple Linear Regression\n\nIn multiple linear regression there are multiple predictors ``x_1, x_2, \\ldots, x_p``\nand the response is ``\\hat y = \\beta_0 + \\beta_1 x_1 + \\beta_2 x_2 + \\cdots + \\beta_p x_p\n`` (we use here ``\\beta`` instead of ``\\theta`` for the parameters).\nWith ``p = 2`` predictors we can visualize linear regression as the plane\nthat is closest to the data. Use the sliders below to get a feeling for the\nparameters. You can also change the viewing angle by clicking and dragging in\nthe figure.\"\n\n# ╔═╡ 51c9ea74-3110-4536-a4af-7cc73b45a4a6\nmd\"β₀ = $(@bind β₀ Slider(-1:.02:1, default = .4, show_value = true))\n\nβ₁ = $(@bind β₁ Slider(-1:.02:1, default = .2, show_value = true))\n\nβ₂ = $(@bind β₂ Slider(-1:.02:1, default = -.6, show_value = true))\n\"\n\n# ╔═╡ 0f544053-1b7a-48d6-b18b-72092b124305\nbegin\n    Random.seed!(3)\n\tX = DataFrame(X1 = randn(20), X2 = randn(20))\n    f0(X1, X2, β₀, β₁, β₂) = β₀ + β₁ * X1 + β₂ * X2\n    f0(β₀, β₁, β₂) = (X1, X2) -> f0(X1, X2, β₀, β₁, β₂)\n\tdata_generator(X1, X2; β₀, β₁, β₂, σ = 0.8) = f0(X1, X2, β₀, β₁, β₂) + σ * randn()\n\ty = data_generator.(X.X1, X.X2, β₀ = .4, β₁ = .5, β₂ = -.6)\nend;\n\n\n# ╔═╡ d541a8cd-5aa4-4c2d-bfdf-5e6297bb65a8\nbegin\n    plotly()\n    p1 = scatter3d(X.X1, X.X2, y, markersize = 1,\n                   xlims = (-3, 3), xlabel = \"X1\",\n                   ylims = (-3, 3), ylabel = \"X2\",\n                   zlims = (-4, 4), zlabel = \"y\", label = \"data\")\n    wireframe!(-3:.1:3, -3:.1:3, f0(β₀, β₁, β₂),\n               label = \"function\", title = \"data & function\", color = :green)\n    plot_residuals!(X.X1, X.X2, y, f0(β₀, β₁, β₂))\n    p2 = contour(-1:.1:1, -1:.1:1, (β₀, β₁) -> mean((β₀ .+ β₁ .* X.X1 .+ β₂ .* X.X2 .- y).^2), levels = 100, ylabel = \"β₁\", cbar = false, title = \"loss\")\n    scatter!([β₀], [β₁], label = nothing)\n    p3 = contour(-1:.1:1, -1:.1:1, (β₀, β₂) -> mean((β₀ .+ β₁ .* X.X1 .+ β₂ .* X.X2 .- y).^2), levels = 100, xlabel = \"β₀\", ylabel = \"β₂\")\n    scatter!([β₀], [β₂], label = \"current loss\")\n    plot(p1, plot(p2, p3, layout = (2, 1)), layout = (1, 2),\n         size = (700, 400), legend = false)\nend\n\n# ╔═╡ da6462d8-3343-41d8-82dd-48770176d4ba\nmd\"## Wind speed prediction with multiple predictors\"\n\n# ╔═╡ 753ec309-1363-485d-a2bd-b9fa100d9058\nm2 = machine(LinearRegressor(), select(weather[1:end-5,:], Not([:LUZ_wind_peak, :time])),\n             weather.LUZ_wind_peak[6:end]) |> fit!;\n\n# ╔═╡ 618ef3c7-0fda-4970-88e8-1dac195545de\nsort!(DataFrame(predictor = names(select(weather, Not([:LUZ_wind_peak, :time]))),\n                value = fitted_params(m2).coefs), :value)\n\n# ╔═╡ 2d25fbb6-dc9b-40ad-bdce-4c952cdad077\nrmse(predict(m2, select(weather[1:end-5,:], Not([:LUZ_wind_peak, :time]))),\n     weather.LUZ_wind_peak[6:end])\n\n# ╔═╡ c9f10ace-3299-45fb-b98d-023a35dd405a\nrmse(predict(m2, select(weather_test[1:end-5,:], Not([:LUZ_wind_peak, :time]))),\n     weather_test.LUZ_wind_peak[6:end])\n\n# ╔═╡ 99a371b2-5158-4c42-8f50-329352b6c1f2\nmd\"# Error Decomposition\n\n\"\n\n# ╔═╡ f10b7cad-eda3-4ec9-99ee-d43ed013a057\nbegin\n    f(x) = sin(2x) + 2*(x - .5)^3 - .5x\n    conditional_generator(x; n = 50) = f.(x) .+ .2*randn(n)\nend;\n\n# ╔═╡ 05354df5-a803-422f-87a3-1c56a34e8a48\nf̂(x) = 0.1 + x\n\n# ╔═╡ 9e61b4c3-1a9f-41a7-9882-25ed797a7b8d\nexpected_error(f, x) = mean((conditional_generator(x, n = 10^6) .- f(x)).^2);\n\n# ╔═╡ c6a59b85-d031-4ad4-9e24-691494d08cde\nexpected_error(f̂, .1)\n\n# ╔═╡ e50b8196-e804-473a-b3b5-e22fdb9d2f45\n(f(.1) - f̂(.1))^2\n\n# ╔═╡ f413ea94-36ca-4afc-8ca8-9a7e88101980\nexpected_error(f, .1)\n\n# ╔═╡ dbf7fc72-bfd0-4c57-a1a9-fb5881e16e7e\nlet x = rand(100), grid = 0:.05:1\n    gr()\n    p1 = scatter(x, vcat(conditional_generator.(x, n = 1)...), label = \"samples\")\n    plot!(f, label = \"f\")\n    plot!(f̂, label = \"f̂\")\n    p2 = plot(grid, expected_error.(f̂, grid), label = \"expected error f̂\", w = 3)\n    plot!(grid, (f.(grid) .- f̂.(grid)).^2, label = \"reducible error\", w = 3)\n    hline!([.2^2], label = \"irreducible error\", ylims = (0, .15), w = 3, xlabel = \"x\")\n    plot(p1, p2, layout = (2, 1), legend = :right, ylabel = \"y\")\nend\n\n# ╔═╡ ad5b293d-c0f4-4693-84f4-88308639a501\nmd\"# Logistic Regression\n\n## Preparing the spam data\n\nThe text in our spam data set is already preprocessed. But we do not yet have\na format similar to our weather prediction data set with a fixed number ``p`` of\npredictors for each email. In this section we create a very simple feature\nrepresentation of our emails:\n1. We create a lexicon of words that are neither very frequent nor very rare.\n2. For each email we count how often every word in this lexicon appears.\n3. Our feature matrix will consist of ``n`` rows (one for each email) and ``p``\n    predictors (one for each word in the lexicon) with ``x_{ij}`` measuring how\n    often word ``j`` appears in document ``i``, normalized by the number of\n    lexicon words in each email (such that the elements in every row sum to 1).\n\"\n\n# ╔═╡ 210b977d-7136-407f-a1c9-eeea869d0312\nbegin\n    spamdata = CSV.read(joinpath(@__DIR__, \"..\", \"data\", \"spam.csv\"), DataFrame)\n    dropmissing!(spamdata) # remove entries without any text (missing values).\nend\n\n# ╔═╡ 72969aca-b203-4d83-8923-74e523aa1c01\nimport TextAnalysis: Corpus, StringDocument, DocumentTermMatrix, lexicon,\n                     update_lexicon!, tf\n\n# ╔═╡ 4cbb3057-01f4-4e80-9029-4e80d6c9e5e6\nmd\"In the next cell we create the full lexicon of words appearing in the first\n2000 emails. Each lexicon entry is of the form `\\\"word\\\" => count`.\"\n\n# ╔═╡ c50c529f-d393-4854-b5ed-91e90d557d12\nbegin\n    crps = Corpus(StringDocument.(spamdata.text[1:2000]))\n    update_lexicon!(crps)\n    lexicon(crps)\nend\n\n# ╔═╡ 72b50cee-d436-42ce-add9-07b0c012cb31\nmd\"Now we select only those words of the full lexicon that appear at least 100\ntimes and at most 10^3 times. These numbers are pulled out of thin air (like\nall the design choses of this very crude feature engineering).\n\"\n\n# ╔═╡ bf4110a9-31a4-48a3-bd6d-85c404d0e72d\nbegin\n    small_lex = Dict(k => lexicon(crps)[k]\n                     for k in findall(x -> 100 <= last(x) <= 10^3, lexicon(crps)))\n    m = DocumentTermMatrix(crps, small_lex)\nend\n\n# ╔═╡ 534681d5-71d8-402a-b455-f491cfbb353e\nbegin\n    spam_or_ham = coerce(String.(spamdata.label[1:2000]), Binary)\n    normalized_word_counts = float.(DataFrame(tf(m), :auto))\nend\n\n# ╔═╡ ec1c2ea5-29ce-4371-be49-08798305ff50\nMarkdown.parse(\"Here we go: now we have a matrix of size\n $(join(size(normalized_word_counts), \" x \")) as input and a vector of binary label as\n output. We will be able to use this as input in multiple logistic regression.\n For future usage we save this preprocessed representation of the spam data to\n a file.\")\n\n# ╔═╡ 681cb7b9-f041-4aea-907e-4d85135c005a\nCSV.write(joinpath(dirname(pathof(MLCourse)), \"..\", \"data\", \"spam_preprocessed.csv\"),\n          [normalized_word_counts DataFrame(spam_or_ham = spam_or_ham)])\n\n# ╔═╡ f7117513-283f-4e32-a2a1-3594c794c94d\nmd\"## Multiple Logistic Regression\n\nIn the top row of the figure below we see in two different ways (once as a 3D\nplot and once as a contour plot) the probability of class A for the selected\nparameter values. The bottom row shows samples (large points, red = class A)\nobtained with this probability distribution and predictions (small points)\nat decision threshold 0.5.\nPlay with the parameters to get a feeling for how they affect the probability\nand the samples.\n\nθ₀ = $(@bind θ₀ Slider(-3:3, default = 0, show_value = true))\n\nθ₁ = $(@bind θ₁ Slider(-8:8, default = 3, show_value = true))\n\nθ₂ = $(@bind θ₂ Slider(-8:8, default = 0, show_value = true))\n\"\n\n# ╔═╡ fd4165dc-c3e3-4c4c-9605-167b5b4416da\nmd\"## Confusion Matrix, ROC and AUC\"\n\n# ╔═╡ 7738c156-8e1b-4723-9818-fba364822171\nmd\"s = $(@bind s Slider(-4:.1:4, default = 0, show_value = true))\n\nseed = $(@bind seed Slider(1:100, show_value = true))\n\nthreshold = $(@bind threshold Slider(.01:.01:.99, default = 0.5, show_value = true))\n\"\n\n# ╔═╡ 0fcfd7d2-6ea3-4c75-bad3-7d0fdd6fde11\nbegin\n    logistic(x) = 1/(1 + exp(-x))\n    logodds(p) = log(p/(1-p))\n    function error_rates(x, y, t)\n        P = sum(y)\n        N = length(y) - P\n        pos_pred = y[(logistic.(x) .> t)]\n        TP = sum(pos_pred)\n        FP = sum(1 .- pos_pred)\n        FP/N, TP/P\n    end\nend;\n\n# ╔═╡ 4f89ceab-297f-4c2c-9029-8d2d7fad084f\nlet f(x1, x2) = logistic(θ₀ + θ₁ * x1 + θ₂ * x2)\n    p1 = wireframe(-3:.1:3, -3:.1:3, f, zlims = (0, 1))\n    p2 = contour(-3:.1:3, -3:.1:3, f, contour_labels = true, levels = 20, cbar = false)\n\tplotly()\n    samples = (X1 = 6 * rand(200) .- 3, X2 = 6 * rand(200) .- 3)\n    labels = f.(samples.X1, samples.X2) .> rand(200)\n    xgrid = MLCourse.grid(-3:.2:3, -3:.2:3, names = (:X1, :X2))\n    scatter(xgrid.X1, xgrid.X2, color = (f.(xgrid.X1, xgrid.X2) .> .5) .+ 1,\n            markersize = 2, markerstrokewidth = 0, label = nothing)\n    p3 = scatter!(samples.X1, samples.X2, color = labels .+ 1, xlabel = \"X1\")\n    plot(p1, p2, plot(), p3, layout = (2, 2), size = (700, 600),\n         ylabel = \"X2\", legend = false)\nend\n\n\n# ╔═╡ 285c6bfc-5f29-46e0-a2c1-8abbec74501b\nbegin\n    Random.seed!(seed)\n    auc_samples_x = 2 * randn(200)\nend;\n\n# ╔═╡ c98524b5-d6b3-469c-82a1-7d231cc792d6\nbegin\n    auc_samples_y = logistic.(2.0^s * auc_samples_x) .> rand(200)\n    auc = [error_rates(2.0^s * auc_samples_x, auc_samples_y, t)\n           for t in .01:.01:.99]\n    push!(auc, (0., 0.))\n    prepend!(auc, [(1., 1.)])\nend;\n\n# ╔═╡ 3336ab15-9e9b-44af-a7d5-1d6472241e62\nlet\n    gr()\n    p1 = scatter(auc_samples_x, auc_samples_y, markershape = :vline, label = nothing, color = :black)\n    plot!(x -> logistic(2.0^s * x), color = :blue, label = nothing, xlims = (-8, 8))\n    vline!([1/(2.0^s) * logodds(threshold)], w = 3, color = :red,\n           label = nothing, xlabel = \"x\", ylabel = \"y\")\n    p2 = plot(first.(auc), last.(auc), title = \"ROC\", label = nothing)\n    fp, tp = auc[floor(Int, threshold * 100)]\n    scatter!([fp], [tp], color = :red, xlims = (-.01, 1.01), ylims = (-.01, 1.01),\n            labels = nothing, ylabel = \"true positive rate\",\n            xlabel = \"false positive rate\")\n    plot(p1, p2, size = (700, 400))\nend\n\n\n# ╔═╡ 62ad57e5-1366-4635-859b-ccdab2efd3b8\nmd\"## Multiple Logistic Regression on the spam data\"\n\n# ╔═╡ 29e1d9ff-4375-455a-a69b-8dd0c2cac57d\nm3 = fit!(machine(LogisticClassifier(penalty = :none),\n                  normalized_word_counts,\n                  spam_or_ham));\n\n# ╔═╡ 1d1a24c6-c166-49a2-aa21-7acf50b55a66\npredict(m3, normalized_word_counts)\n\n# ╔═╡ 32bafa9e-a35e-4f54-9857-d269b47f95c3\nconfusion_matrix(predict_mode(m3, normalized_word_counts), spam_or_ham)\n\n# ╔═╡ 4e4f4adf-364f-49b9-9391-5050a4c1286a\nmd\"With our simple features, logistic regression can classify the training data\nalmost always correctly. Let us see how well this works for test data.\n\"\n\n# ╔═╡ 50c035e6-b892-4157-a52f-824578366977\nbegin\n    test_crps = Corpus(StringDocument.(spamdata.text[2001:4000]))\n    test_input = float.(DataFrame(tf(DocumentTermMatrix(test_crps, small_lex)), :auto))\n    test_labels = coerce(String.(spamdata.label[2001:4000]), Binary)\n    confusion_matrix(predict_mode(m3, test_input), test_labels)\nend\n\n# ╔═╡ 21b66582-3fda-401c-9421-73ae2f455a75\npredict_mode(m3, normalized_word_counts)\n\n# ╔═╡ ba4b5683-5932-415e-8772-8b3eef5eb63d\nmd\"We save also the test data for future usage.\"\n\n# ╔═╡ a30578dd-aecb-46eb-b947-f009282cf2fc\nmd\"Let us evaluate the fit in terms of commonly used losses for binary classification.\"\n\n# ╔═╡ 8ed39cdc-e99e-48ff-9973-66df41aa0f78\nfunction losses(machine, input, response)\n    (loglikelihood = -sum(log_loss(predict(machine, input), response)),\n     misclassification_rate = mean(predict_mode(machine, input) .!= response),\n     accuracy = accuracy(predict_mode(machine, input), response),\n     auc = MLJ.auc(predict(machine, input), response)\n\t)\nend;\n\n# ╔═╡ dd463687-b73d-4e70-b2cf-97a56a0ad409\nlosses(m3, normalized_word_counts, spam_or_ham)\n\n# ╔═╡ 57dcadc0-2da2-4521-aeaf-6fd01f4bd82b\nspam_or_ham\n\n# ╔═╡ 935adbcd-48ab-4a6f-907c-b04137ca3abe\nlosses(m3, test_input, test_labels)\n\n# ╔═╡ 8b0451bf-59b0-4e71-be84-549e23b5bfe7\nmd\"\"\"# Exercises\n\n## Conceptual\n\n1. Suppose we have a data set with three predictors, ``X_1`` = Final Grade, ``X_2`` = IQ, ``X_3`` = Level (1 for College and 0 for High School).  The response is starting salary after graduation (in thousands of dollars). Suppose we use least squares to fit the model, and get ``\\hat\\beta_0 = 25, \\hat\\beta_1 = 2, \\hat\\beta_2 = 0.07, \\hat\\beta_3 = 15``.\n   - Which answer is correct, and why?\n      - For a fixed value of IQ and Final Grade, high school graduates earn more, on average, than college graduates.\n      - For a fixed value of IQ and Final Grade, college graduates earn more, on average, than high school graduates.\n   - Predict the salary of a college graduate with IQ of 110 and a Final Grade of 4.0.\n2. Suppose we collect data for a group of students in a machine learning class with variables ``X_1 =`` hours studied, ``X_2 =`` grade in statistics class, and ``Y =`` receive a 6 in the machine learning class. We fit a logistic regression and produce estimated coefficients, ``\\hat{\\beta}_0 = -6``, ``\\hat{\\beta}_1 = 0.025``, ``\\hat{\\beta}_2 = 1``.\n   - Estimate the probability that a student who studies for 75 hours and had a 4 in the statistics class gets a 6 in the machine learning class.\n   - How many hours would the above student need to study to have a 50% chance of getting an 6 in the machine learning class?\n3. In this exercise we will derive the loss function implicitly defined by maximum likelihood estimation of the parameters in a classification setting with multiple classes. Remember that the input ``f(x)`` of the softmax function ``s`` is a vector-valued function. Here we assume a linear function ``f`` and write the ``i``th component of this function as ``f_i(x) = \\theta_{i0} + \\theta_{i1}x_1 + \\cdots + \\theta_{ip}x_p``. Note that each component ``i`` has now its own parameters ``\\theta_{i0}`` to ``\\theta_{ip}``. Using matrix multiplication we can also write ``f(x) = \\theta x`` where ``\\theta = \\left(\\begin{array}{ccc}\\theta_{10} & \\cdots & \\theta_{1p}\\\\\\vdots & \\ddots & \\cdots\\\\\\theta_{K0} & \\cdots & \\theta_{Kp}\\end{array}\\right)`` is a ``K\\times(p+1)`` dimensional matrix and ``x = (1, x_1, x_2, \\ldots, x_p)`` is a column vector of length ``p+1``.\n    - Write the log-likelihood function for a classification problem with ``K`` classes. *Hint*: to simplify the notation we can use the convention ``s_y(f(x)) = P(y|x)`` to write the conditional probability of class ``y`` given input ``x``. This convention makes sense when the classes are identified by the integers ``1, 2, \\ldots, K``; in this case ``s_y(f(x))`` is the ``y``th component of ``s(f(x))``. Otherwise we would could specify a mapping from classes ``C_1, C_2, \\ldots, C_K`` to the integers ``1, 2, \\ldots, K`` for this convention to make sense.\n    - Assume now ``K = 3`` and ``p = 2``. Explicitly write the loss function for the training set ``\\mathcal D = ((x_1 = (0, 0), y_1 = C), (x_2 = (3, 0), y_2 = A), (x_3 = (0, 2), y_3 = B))``.\n    - Assume ``K = 2`` and ``p = 1`` and set ``\\theta_{20} = 0`` and ``\\theta_{21} = 0``. Show that we recover standard logistic regression in this case. *Hint*: show that ``s_1(f(x)) = \\sigma(f_1(x))`` and ``s_2(f(x)) = 1 - \\sigma(f_1(x))``, where ``s`` is the softmax function and ``\\sigma(x) = 1/(1 + e^{-x})`` is the logistic function.\n    - Show that one can always set ``\\theta_{K0}, \\theta_{K1}, \\ldots, \\theta_{Kp}`` to zero. *Hint* Show that the softmax function with the transformed parameters ``\\tilde\\theta_{ij}=\\theta_{ij} - \\theta_{Kj}`` has the same value as the softmax function in the original parameters.\n\n## Applied\n1. In the multiple linear regression of the weather data set above we used all\n   available predictors. We do not know if all of them are relevant. In this exercise our aim is to find models with fewer predictors and quantify the loss in prediction accuracy.\n    - Systematically search for the model with at most 2 predictors that has the lowest test rmse. *Hint* write a function `train_and_evaluate` that takes the training and the test data as input as well as an array of two predictors; remember that `data[:, [\\\"A\\\", \\\"B\\\"]]` returns a sub-dataframe with columns \\\"A\\\" and \\\"B\\\". This function should fit a `LinearRegressor` on the training set with those two predictors and return the test rmse for the two predictors. To get a list of all pairs of predictors you can use something like `predictors = setdiff(names(train), [\"time\", \"LUZ_wind_peak\"]); predictor_pairs = [[p1, p2] for p1 in predictors, p2 in predictors if p1 != p2 && p1 > p2]`\n    - How much higher is the test error compared to the fit with all available predictors?\n    - How many models did you have to fit to find your result above?\n    - How many models would you have to fit to find the best model with at most 5 predictors? *Hint* the function `binomial` may be useful.\n2. In this exercise we perform linear classification of the MNIST handwritten digits\n   dataset.\n   - Load the MNIST data set with `using OpenML; mnist = OpenML.load(554) |> DataFrame; dropmissing!(mnist);`\n   - Usually the first 60'000 images are taken as training set, but for this exercise I recommend to use fewer rows, e.g. the first 5000.\n   - Scale the input values to the interval [0, 1) with `mnist[:, 1:784] ./= 255`\n   - Fit a `MLJLinearModels.MultinomialClassifier(penalty = :none)` to the data. Be patient! This can take a few minutes.\n   - Compute the misclassification rate and the confusion matrix on the training set.\n   - Use as test data rows 60001 to 70000 and compute the misclassification rate\n     and the confusion matrix on this test set.\n   - Plot some of the wrongly classified training and test images.\n     Are they also difficult for you to classify?\n\"\"\"\n\n# ╔═╡ 7f08fcaa-000d-422d-80b4-e58a2f489d74\nMLCourse.footer()\n\n# ╔═╡ Cell order:\n# ╟─12d5824c-0873-49a8-a5d8-f93c73b633ae\n# ╠═94f8e29e-ef91-11eb-1ae9-29bc46fa505a\n# ╟─8217895b-b120-4b08-b18f-d921dfdddf10\n# ╠═9f84bcc5-e5ab-4935-9076-c19e9bd668e8\n# ╠═34e527f2-ef80-4cb6-be3a-bee055eca125\n# ╠═006fc1eb-50d5-4206-8c87-53e873f158f4\n# ╟─e4712ebe-f395-418b-abcc-e10ada4b05c2\n# ╠═8c9ae8f7-81b2-4d60-a8eb-ded5364fe0cc\n# ╟─f4f890b6-0ad4-4155-9321-15d673e15489\n# ╠═9b62c374-c26e-4990-8ffc-790928e62e88\n# ╟─7923a0a8-3033-4dde-91e8-22bf540c9866\n# ╠═57f352dc-55ee-4e14-b68d-698938a97d92\n# ╠═b0de002f-3f39-4378-8d68-5c4606e488b7\n# ╠═ce536f60-68b3-4901-bd6a-c96378054b12\n# ╟─c65b81bd-395f-4461-a73b-3535903cb2d7\n# ╟─51c9ea74-3110-4536-a4af-7cc73b45a4a6\n# ╟─d541a8cd-5aa4-4c2d-bfdf-5e6297bb65a8\n# ╟─0f544053-1b7a-48d6-b18b-72092b124305\n# ╟─da6462d8-3343-41d8-82dd-48770176d4ba\n# ╠═753ec309-1363-485d-a2bd-b9fa100d9058\n# ╠═618ef3c7-0fda-4970-88e8-1dac195545de\n# ╠═2d25fbb6-dc9b-40ad-bdce-4c952cdad077\n# ╠═c9f10ace-3299-45fb-b98d-023a35dd405a\n# ╟─99a371b2-5158-4c42-8f50-329352b6c1f2\n# ╠═f10b7cad-eda3-4ec9-99ee-d43ed013a057\n# ╠═05354df5-a803-422f-87a3-1c56a34e8a48\n# ╠═9e61b4c3-1a9f-41a7-9882-25ed797a7b8d\n# ╠═c6a59b85-d031-4ad4-9e24-691494d08cde\n# ╠═e50b8196-e804-473a-b3b5-e22fdb9d2f45\n# ╠═f413ea94-36ca-4afc-8ca8-9a7e88101980\n# ╟─dbf7fc72-bfd0-4c57-a1a9-fb5881e16e7e\n# ╟─ad5b293d-c0f4-4693-84f4-88308639a501\n# ╠═210b977d-7136-407f-a1c9-eeea869d0312\n# ╠═72969aca-b203-4d83-8923-74e523aa1c01\n# ╟─4cbb3057-01f4-4e80-9029-4e80d6c9e5e6\n# ╠═c50c529f-d393-4854-b5ed-91e90d557d12\n# ╟─72b50cee-d436-42ce-add9-07b0c012cb31\n# ╠═bf4110a9-31a4-48a3-bd6d-85c404d0e72d\n# ╠═534681d5-71d8-402a-b455-f491cfbb353e\n# ╟─ec1c2ea5-29ce-4371-be49-08798305ff50\n# ╠═681cb7b9-f041-4aea-907e-4d85135c005a\n# ╟─f7117513-283f-4e32-a2a1-3594c794c94d\n# ╟─4f89ceab-297f-4c2c-9029-8d2d7fad084f\n# ╟─fd4165dc-c3e3-4c4c-9605-167b5b4416da\n# ╟─7738c156-8e1b-4723-9818-fba364822171\n# ╠═0fcfd7d2-6ea3-4c75-bad3-7d0fdd6fde11\n# ╟─3336ab15-9e9b-44af-a7d5-1d6472241e62\n# ╟─285c6bfc-5f29-46e0-a2c1-8abbec74501b\n# ╟─c98524b5-d6b3-469c-82a1-7d231cc792d6\n# ╟─62ad57e5-1366-4635-859b-ccdab2efd3b8\n# ╠═29e1d9ff-4375-455a-a69b-8dd0c2cac57d\n# ╠═1d1a24c6-c166-49a2-aa21-7acf50b55a66\n# ╠═32bafa9e-a35e-4f54-9857-d269b47f95c3\n# ╟─4e4f4adf-364f-49b9-9391-5050a4c1286a\n# ╠═50c035e6-b892-4157-a52f-824578366977\n# ╠═21b66582-3fda-401c-9421-73ae2f455a75\n# ╟─ba4b5683-5932-415e-8772-8b3eef5eb63d\n# ╟─a30578dd-aecb-46eb-b947-f009282cf2fc\n# ╠═8ed39cdc-e99e-48ff-9973-66df41aa0f78\n# ╠═dd463687-b73d-4e70-b2cf-97a56a0ad409\n# ╠═57dcadc0-2da2-4521-aeaf-6fd01f4bd82b\n# ╠═935adbcd-48ab-4a6f-907c-b04137ca3abe\n# ╟─8b0451bf-59b0-4e71-be84-549e23b5bfe7\n# ╟─20c5c7bc-664f-4c04-8215-8f3a9a2095c9\n# ╟─7f08fcaa-000d-422d-80b4-e58a2f489d74\n", "meta": {"hexsha": "f3ef373c4d4a14eb94095fe13a9bfcded869992b", "size": 23579, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/generalized_linear_regression.jl", "max_stars_repo_name": "jbrea/MLCourse", "max_stars_repo_head_hexsha": "68b120f3be86a8f6140b272ceecc1d5746fabc6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2021-09-02T07:40:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T01:08:27.000Z", "max_issues_repo_path": "notebooks/generalized_linear_regression.jl", "max_issues_repo_name": "davibarreira/MLCourse", "max_issues_repo_head_hexsha": "68b120f3be86a8f6140b272ceecc1d5746fabc6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-04T12:54:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T12:54:30.000Z", "max_forks_repo_path": "notebooks/generalized_linear_regression.jl", "max_forks_repo_name": "davibarreira/MLCourse", "max_forks_repo_head_hexsha": "68b120f3be86a8f6140b272ceecc1d5746fabc6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-09-29T22:20:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T20:49:25.000Z", "avg_line_length": 45.5193050193, "max_line_length": 861, "alphanum_fraction": 0.688366767, "num_tokens": 9194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8652240791017535, "lm_q1q2_score": 0.763497846152524}}
{"text": "# Classical Multidimensional Scaling\n\n## convert Gram matrix to Distance matrix\n\nfunction gram2dmat!{DT}(D::AbstractMatrix{DT}, G::AbstractMatrix)\n    # argument checking\n    m = size(G, 1)\n    n = size(G, 2)\n    m == n || error(\"D should be a square matrix.\")\n    size(D) == (m, n) ||\n        throw(DimensionMismatch(\"Sizes of D and G do not match.\"))\n\n    # implementation\n    for j = 1:n\n        for i = 1:j-1\n            @inbounds D[i,j] = D[j,i]\n        end\n        D[j,j] = zero(DT)\n        for i = j+1:n\n            @inbounds D[i,j] = sqrt(G[i,i] + G[j,j] - 2 * G[i,j])\n        end\n    end\n    return D\nend\n\ngram2dmat{T<:Real}(G::AbstractMatrix{T}) = gram2dmat!(similar(G, Base.momenttype(T)), G)\n\n## convert Distance matrix to Gram matrix\n\nfunction dmat2gram!{GT}(G::AbstractMatrix{GT}, D::AbstractMatrix)\n    # argument checking\n    n = Compat.LinAlg.checksquare(D)\n    size(G) == (n, n) ||\n        throw(DimensionMismatch(\"Sizes of G and D do not match.\"))\n\n    # implementation\n    u = zeros(GT, n)\n    s = 0.0\n    for j = 1:n\n        s += (u[j] = sum(abs2, view(D,:,j)) / n)\n    end\n    s /= n\n\n    for j = 1:n\n        for i = 1:j-1\n            @inbounds G[i,j] = G[j,i]\n        end\n        for i = j:n\n            @inbounds G[i,j] = (u[i] + u[j] - abs2(D[i,j]) - s) / 2\n        end\n    end\n    return G\nend\n\ndmat2gram{T<:Real}(D::AbstractMatrix{T}) = dmat2gram!(similar(D, Base.momenttype(T)), D)\n\n## classical MDS\n\nfunction classical_mds{T<:Real}(D::AbstractMatrix{T}, p::Int;\n        dowarn::Bool=true)\n\n    n = size(D, 1)\n    m = min(p, n) #Actual number of eigenpairs wanted\n\n    G = dmat2gram(D)\n\n    #Get m largest eigenpairs\n    E = eigfact!(Symmetric(G))\n\n    #Sometimes dmat2gram produces a negative definite matrix, and the sign just\n    #needs to be flipped. The heuristic to check for this robustly is to check\n    #if there is a negative eigenvalue of magnitude larger than the largest\n    #positive eigenvalue, and flip the sign of eigenvalues if necessary.\n\n    mineig, maxeig = extrema(E[:values])\n    if mineig < 0 && abs(mineig) > abs(maxeig)\n        #do flip\n        ord = sortperm(E.values)\n        v = -E[:values][ord[1:m]]\n    else\n        ord = sortperm(E.values; rev=true)\n        v = E[:values][ord[1:m]]\n    end\n\n    for i = 1:m\n        if v[i] > 0\n            v[i] = √v[i]\n        else #Keeping all remaining eigenpairs would not change solution (if 0)\n             #or make the answer _worse_ (if <0).\n             #The least squares solution would want to throw all these away.\n            dowarn && warn(\"Gramian has only $(i-1) positive eigenvalue(s)\")\n            m = i-1\n            ord = ord[1:m]\n            v = v[1:m]\n            break\n        end\n    end\n\n    #Check if the last considered eigenvalue is degenerate\n    if m>0\n        nevalsmore = sum(abs.(E[:values][ord[m+1:end]] .- v[m]^2) .< n*eps())\n        nevals = sum(abs.(E[:values] .- v[m]^2) .< n*eps())\n        if nevalsmore > 1\n            dowarn && warn(\"The last eigenpair is degenerate with $(nevals-1) others; $nevalsmore were ignored. Answer is not unique\")\n        end\n    end\n    U = E[:vectors][:, ord[1:m]]\n    scale!(U, v)\n\n    #Add trailing zero coordinates if dimension of embedding space (p) exceeds\n    #number of eigenpairs used (m)\n    if m < p\n        U = [U zeros(n, p-m)]\n    end\n\n    U' #Return each coordinate in a column\nend\n\n", "meta": {"hexsha": "3ea9c5ec827a1e7c9a350dd65636d100e7a11275", "size": 3360, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cmds.jl", "max_stars_repo_name": "ianshmean/MultivariateStats.jl", "max_stars_repo_head_hexsha": "a65917fcba5f95b208be19204f23cdc08bc05f16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cmds.jl", "max_issues_repo_name": "ianshmean/MultivariateStats.jl", "max_issues_repo_head_hexsha": "a65917fcba5f95b208be19204f23cdc08bc05f16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cmds.jl", "max_forks_repo_name": "ianshmean/MultivariateStats.jl", "max_forks_repo_head_hexsha": "a65917fcba5f95b208be19204f23cdc08bc05f16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-10T13:12:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-10T13:12:34.000Z", "avg_line_length": 28.2352941176, "max_line_length": 134, "alphanum_fraction": 0.5645833333, "num_tokens": 1045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7634301622096169}}
{"text": "#' ## Functions\r\n#'\r\n#'\r\n#' In the last notebook, we talked about modeling data with functions. A **function** is one of the most fundamental concepts in computing (and also in mathematics).\r\n#'\r\n#' A function is a piece of a program that receives **input arguments**, processes them by doing certain calculations on them, and returns **outputs**.\r\n#'\r\n#' For example, we might have a function `g` that takes a number as an input and returns the square of that number as an output. How can we define this function `g` on a computer? Julia gives us a few different ways to do this.\r\n#' ### Defining functions\r\n#' Firstly, we could write `g` as follows:\r\n\r\n#+ results=\"hidden\"\r\ng(x) = x^2\r\n#+\r\n#'\r\ng(2), g(3.5) # This is a tuple.\r\n#'\r\ng(3.0)\r\n#' Alternatively, we could declare this function using the `function` and `end` keywords:\r\n#+ results=\"hidden\"\r\nfunction g1(x)\r\n    x^2\r\nend\r\n#+\r\ng1(2), g1(3.5)\r\n#' The third way we could have declared this function is as an \"anonymous\" or\r\n#' \"lambda\" function. \"Anonymous\" functions are functions that truly don't need\r\n#' names! For example, we could have declared a function that squares its input\r\n#' as\r\n(x->x^2)(2)\r\n#' Now that we've done that, we can't access the function `x -> x^2` again\r\n#' because we have no name to call! That seems a little silly, doesn't it?\r\n#'\r\n#' Actually, there are times where functions without names are especially\r\n#' handy.  Most commonly they're used arguments to \"higher-order\" functions:\r\n#' these are functions which take _other functions_ as arguments. For example:\r\nmap(sqrt, [1, 2, 3])\r\n#'\r\nmap(x->x^2, [1, 2, 3])\r\n#' Of course, you can also assign anonymous function a name, but in general\r\n#' it's better style to use the non-anonymous equivalents above if you actually\r\n#' want to use a name.\r\ng2 = x -> x^2\r\ng2(3.5), g2(\"I ♡ Julia \") # Use \\heartsuit + TAB to get the ♡ character\r\n\r\n#' ## An important sigmoidal function\r\n#' A particular function that is used a lot in machine learning is a so-called\r\n#' \"sigmoidal\" function (meaning a function that is S-shaped, i.e. the graph\r\n#' of the function looks like an `S`).\r\n#'\r\n#' $$\\sigma(x) = \\frac{1}{1 + e^{-x}}$$\r\n#'\r\n#' The sigmoid function that we will use is given the name $\\sigma$, and is\r\n#' defined by the following mathematical expression:\r\n#'\r\n#' $$\\sigma(x) := \\frac{1}{1 + \\exp(-x)}$$\r\n\r\n#' #### Exercise 1\r\n#'\r\n#' Use the first syntax given above to define the function `σ` in Julia.\r\n#' Note that Julia actually allows us to use the symbol σ as a variable name!\r\n#' To do so, type `\\sigma<TAB>` in the code cell.\r\n\r\n#' #### Solution\r\n# Short form\r\nσ(x) = 1/(1 + exp(-x))\r\nσ(1)\r\n#+ results=\"hidden\"\r\n# Long form\r\nfunction sigma(x)\r\n    1/(1 + exp(-x))\r\nend\r\n#+\r\nsigma(1)\r\n\r\n\r\n#' ## Plotting functions\r\n\r\n#' Let's draw the function σ to see what it looks like. Throughout this course,\r\n#' we'll use the Julia package `Plots.jl` for all of the graphics. This package\r\n#' provides a flexible syntax for plotting, in which options to change\r\n#' attributes like the width of the lines used in the figure are given as named\r\n#' keyword arguments.\r\n#'\r\n#' In addition, it allows us to use different \"backends\", which are the other\r\n#' libraries that actually carry out the plotting following the instructions\r\n#' from `Plots.jl`.\r\nusing Plots\r\n#gr()\r\n# plotly interferes mathjax, tpl file needs to be fixed\r\n# see templates/julia_html.tpl\r\nplotly()\r\n\r\npl = plot(sigma, -5, 5, legend=(0.1,0.9), label=\"σ\")\r\n# add horizontal lines at 0 and 1, with dashed style and linewidth 3\r\nhline!(pl, [0,1], ls=:dash, lw=3, label=false)\r\n# add a vertical line at 0\r\nvline!(pl, [0], ls=:dash, lw=3, label=false)\r\n\r\n#' We can think of $\\sigma$ as a smooth version of a step or threshold function\r\n#' (often called a \"Heaviside\" function). To see this, let's modify the\r\n#' steepness of the jump in $\\sigma$ and compare it to the Heaviside function;\r\n#' we'll see how all this works in more detail later:\r\n#+ results=\"hidden\"\r\nfunction heaviside(x)\r\n    x < 0 ? 0.0 : 1.0\r\nend\r\n#+\r\n\r\n#' Try manipulating the value of `w` between 0 to :\r\nw = 10.0\r\nplot(x->sigma(w*x), -5, 5, label=\"σ\", lw=2, legend=(0.1,0.9))\r\nplot!(heaviside, ls=:dash, label=\"step\")\r\n# This particular function takes any real number as input, and gives an output\r\n# between $0$ and $1$. It is continuous and smooth.\r\n#' Try a smaller $w$.\r\nw = 1.0\r\nplot(x->sigma(w*x), -5, 5, label=\"σ\", lw=2, legend=(0.1,0.9))\r\nplot!(heaviside, ls=:dash, label=\"step\")\r\n#' #### Exercise 2\r\n#' Declare the sigmoid function above as an anonymous function with a different\r\n#' name.\r\nσx = x -> 1/(1+exp(-x))\r\nσx(1)\r\n#' ### Mutating functions: `...!`\r\n#' To generate our plot of σ above, we used some functions that end with `!`.\r\n#'  What does a `!` at the end of a function name mean in Julia?\r\n#'\r\n#' Functions that change or modify their inputs are called\r\n#' **mutating functions**. But wait, don't all functions do that?\r\n#' No, actually. Functions typically take *inputs* and use those *inputs* to\r\n#' generate *outputs*, but the inputs themselves usually don't actually get\r\n#' changed by a function. For example, copy and execute the following code:\r\nv1 = [9, 4, 7, 11]\r\nv2 = sort(v1)\r\n#' `v2` is a sorted version of `v1`, but after calling `sort`, `v1` is still\r\n#' unsorted.\r\nv1\r\n#+ results=\"hidden\"\r\nsort!(v1)\r\n#' Look at the values in `v1` now!\r\nv1\r\n#' This time, the original vector itself was changed (mutated), and is now\r\n#' sorted. Unlike `sort`, `sort!` is a mutating function. Did the `!` make\r\n#' `sort!` mutating? Well, no, not really. In Julia, `!` indicates mutating\r\n#' functions by convention. When the author of `sort!` wrote `sort!`, they added\r\n#' a `!` to let you to know that `sort!` is mutating, but the `!` isn't what\r\n#' makes a function mutating or non-mutating in the first place.\r\n\r\n#' #### Exercise\r\n#' Some of our plotting commands end with `!`. Copy and execute the following code:\r\nr = -5:0.1:5\r\ng(x) = x^2\r\nh(x) = x^3\r\nplot(r, g, label=\"g\")\r\nplot!(r, h, label=\"h\")\r\n#' Then change the code slightly to remove the `!` after `plot!(r, h)`.\r\n#' How does this change your output? What do you think it means to add `!`\r\n#' after plotting commands?\r\n#' #### Solution\r\nr = -5:0.1:5\r\ng(x) = x^2\r\nh(x) = x^3\r\np1 = plot(r, g, label=\"g\")\r\n#'\r\np2 = plot(r, h, label=\"h\")\r\n#' ```julia\r\n#' plot(r, g)\r\n#' plot!(r, h)\r\n#' ```\r\n#' creates an overlay of `g` and `h`, whereas\r\n#'\r\n#' ```julia\r\n#' plot(r, g)\r\n#' plot(r, h)\r\n#' ```\r\n#'\r\n#' creates one plot for `g` and one for `h`.\r\n#'\r\n#' When we add a `!` after a plotting command, we are mutating or updating an\r\n#' *existing* plot.\r\n\r\n#' ## Pointwise application of functions, `f.(x, y)` and `x .+ y` - broadcasting\r\n#' We saw in a previous notebook that we needed to add `.` after the names of\r\n#' some functions, as in\r\n#'\r\n#' ```julia\r\n#' green_amount = mean(Float64.(green.(apple)))\r\n#' ```\r\n#'\r\n#' What are those extra `.`s really doing?\r\n#'\r\n#' When we add a `.` after a function's name, we are telling Julia that we want\r\n#' to \"**broadcast**\" that function over the inputs passed to the function.\r\n#' This means that we want to apply that function *element-wise* over the\r\n#' inputs; in other words, it will apply the function to each element of the\r\n#' input, and return an array with the newly-calculated values.\r\n\r\n#' For example, copy and execute the following code:\r\ng.(r)\r\n#' Since the function `g` squares it's input, this squares all the elements of\r\n#' the range `r`.\r\n#' What happens if instead we just call `g` on `r` via\r\n# g(r)\r\n\r\n#' You should see an error message after calling `g(r)`, which says that Julia\r\n#' cannot multiply two vectors. When we call `g(r)`, we ask Julia to multiply\r\n#' `r` by `r`. When we call `g.(r)`, we ask Julia to multiply *each element*\r\n#' in `r` by itself.\r\n\r\n#' Try this and see what happens.\r\nx = [1 2 3; 4 5 6]\r\nf(t) = sqrt(t) + 5\r\nf.(x)\r\n\r\n#' #### Exercise 3\r\n#'\r\n#' Copy and execute the following code to get the type of the object\r\n#' `numbers = [1, 2, \"three\", 4.0]`:\r\n#+ results=\"hidden\"\r\nnumbers = [1, 2, \"three\", 4.0]\r\n#' What is the type of `numbers`?\r\ntypeof(numbers)\r\n#' Its type is `Array{Any,1}`. This means that `numbers` is a\r\n#' 1-dimensional array that has elements of abstract type `Any`. We can think\r\n#' of the `Any` type as a classification that includes *all* concrete types,\r\n#' for example, `Float64`, `Int32`, `Bool`, `String`, `Char`, etc.\r\n\r\n#' #### Exercise 4\r\n#'\r\n#' Broadcast `typeof` over `numbers` to see what the types of the elements\r\n#' stored inside `numbers` are.\r\ntypeof.(numbers)\r\n\r\n#' Note: Alternatively, we could have looked at the `typeof` each element in\r\n#' the array `numbers` using a `for` loop:\r\nfor n in numbers\r\n    println(typeof(n))\r\nend\r\n\r\n#' #### Exercise 5\r\n#'\r\n#' Write a `for` loop that applies `g` to each of the elements of `r` and\r\n#' prints the results. Verify that the numbers printed by this `for` loop are\r\n#' equal to the entries of the output of `g.(r)`.\r\nr = -5:0.1:5\r\nfor x in r\r\n    #println(g(x)) # uncomment to print\r\nend\r\n\r\n#' We can check this via\r\nbroadcasted_g = g.(r)\r\nfor (x, bg) = zip(r, broadcasted_g)\r\n    # println(g(x) == bg) # uncomment to print\r\nend\r\n\r\n#' A better way\r\nanswers_match = true\r\nfor (x, bg) = zip(r, broadcasted_g)\r\n    if (g(x) != bg)\r\n        answers_match = false\r\n    end\r\nend\r\nanswers_match ? println(\"Our `for` loop worked!\") : println(\"Our `for` loop does not work\")\r\n\r\n#' #### Exercise 6\r\n#'\r\n#' Define a range `xs` between -5 and 5 with steps of 0.5.\r\n#' Apply the $\\sigma$ function pointwise to this range and define `ys` as the\r\n#' result.\r\n#' What does the result look like? Plot these as points and join them with\r\n#' lines.\r\n#'\r\n#' Make the plot interactive where you can vary the step size. Fix the range of\r\n#' the plot in the `x` and `y` directions using the functions `xlims!` and\r\n#' `ylims!`.\r\n#'\r\n#' Learn about plot optinos by `plotattr(:Series)` and `plotattr(\"markershape\")`\r\nxs = -5:0.5:5\r\nys = sigma.(xs)\r\npl = plot(xs, ys; legend=(0.1,0.9), markershape=:circle)\r\n\r\n#' Try manipulating `stepsize` between 0 and 1:\r\nstepsize = 0.5\r\nxs = -5.0:stepsize:5.0\r\nys = σ.(xs)\r\n\r\nscatter(xs, ys)\r\nplot!(xs, ys)\r\n\r\nxlims!(-5, 5)\r\nylims!(0, 1)\r\n", "meta": {"hexsha": "91850de7b0d48af2c7568872719423b3192e295e", "size": 10167, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JuliaAcademy/FundMachLearn/ch0300quiz.jl", "max_stars_repo_name": "ykyang/org.allnix.julia", "max_stars_repo_head_hexsha": "58933a5848dec81c53d591b4163e9a70df62ddd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JuliaAcademy/FundMachLearn/ch0300quiz.jl", "max_issues_repo_name": "ykyang/org.allnix.julia", "max_issues_repo_head_hexsha": "58933a5848dec81c53d591b4163e9a70df62ddd8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JuliaAcademy/FundMachLearn/ch0300quiz.jl", "max_forks_repo_name": "ykyang/org.allnix.julia", "max_forks_repo_head_hexsha": "58933a5848dec81c53d591b4163e9a70df62ddd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6996587031, "max_line_length": 228, "alphanum_fraction": 0.6513229074, "num_tokens": 2954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7634301608273096}}
{"text": "# private helper for union\nfunction _union(A::Multiset{S}, B::Multiset{S}) where {S}\n    M = Multiset{S}()\n    for (x, v) in A.data\n        M[x] = max(v, B[x])\n    end\n    for (y, w) in B.data\n        M[y] = max(A[y], w)\n    end\n    return M\nend\n\nfunction type_convert(T, A::Multiset)\n    M = Multiset{T}()\n    for (x, v) in A.data\n        xx = convert(T, x)\n        M[xx] = v\n    end\n    return M\nend\n\n\n\"\"\"\n`union(A,B)` for multisets creates a new multiset in which the\nmultiplicity of `x` is `max(A[x],B[x])`. This may be invoked as \n`A ∪ B`.\n\"\"\"\nfunction union(A::Multiset{S}, B::Multiset{T}) where {S,T}\n    if S == T\n        return _union(A, B)\n    end\n    ST = typejoin(S, T)\n    AA = type_convert(ST, A)\n    BB = type_convert(ST, B)\n    return _union(AA, BB)\nend\n\n\n\"\"\"\n`A+B` for multisets is the disjoint union, i.e., a new multiset in which the\nmultiplicity of `x` is `A[x]+B[x]`. \n\"\"\"\nfunction (+)(A::Multiset{S}, B::Multiset{T}) where {S,T}\n    ST = typejoin(S, T)\n    M = Multiset{ST}()\n    for (x, v) in A.data\n        push!(M, x, v)\n    end\n    for (x, v) in B.data\n        push!(M, x, v)\n    end\n    return M\nend\n\n# private helper for A-B\nfunction _minus(A::Multiset{S}, B::Multiset{S}) where {S}\n    M = Multiset{S}()\n    for (x, v) in A.data\n        M.data[x] = max(v - B[x], 0)\n    end\n    return M\nend\n\n\"\"\"\n`A-B` for multisets is the multiset difference, i.e., a new multiset\nin which the multiplicity of `x` is `A[x]-B[x]` unless this goes\nbelow `0`, in which case the multiplicity is 0.\n\"\"\"\nfunction (-)(A::Multiset{S}, B::Multiset{T}) where {S,T}\n    if S == T\n        return _minus(A, B)\n    end\n    ST = typejoin(S, T)\n    AA = type_convert(ST, A)\n    BB = type_convert(ST, B)\n    return _minus(AA, BB)\nend\n\n\n\n# private helper for intersect\nfunction _intersect(A::Multiset{S}, B::Multiset{S}) where {S}\n    M = Multiset{S}()\n    for (x, v) in A.data\n        push!(M, x, min(v, B[x]))\n    end\n    return M\nend\n\n\"\"\"\n`intersect(A,B)` for multisets creates a new multiset in which the\nmultiplicity of `x` is `min(A[x],B[x])`.\nThis may be abbreviated `A ∩ B`.\n\"\"\"\nfunction intersect(A::Multiset{S}, B::Multiset{T}) where {S,T}\n    if S == T\n        return _intersect(A, B)\n    end\n    ST = typejoin(S, T)\n    AA = type_convert(ST, A)\n    BB = type_convert(ST, B)\n    return _intersect(AA, BB)\nend\n\n\n\"\"\"\n`A*B` for the Cartesian product of multisets `A` and `B`.\n\"\"\"\nfunction (*)(A::Multiset{S}, B::Multiset{T}) where {S,T}\n    ST = Tuple{S,T}\n    M = Multiset{ST}()\n    for (a, v) in A.data\n        for (b, w) in B.data\n            M.data[(a, b)] = v * w\n        end\n    end\n    return M\nend\n\n\"\"\"\n`n*A` is the scalar multiple of a multiset in which the multiplicity of\n`x` is `n*A[x]`. Of course, we require `n >= 0`.\n\"\"\"\nfunction (*)(n::Int, A::Multiset{T}) where {T}\n    @assert n >= 0 \"Scalar multiplication of a multiset must be by a nonnegative integer\"\n    M = Multiset{T}()\n    for (x, v) in A.data\n        M.data[x] = n * v\n    end\n    return M\nend\n\n# private helper for issubset\nfunction _sub(A::Multiset{S}, B::Multiset{S}) where {S}\n    for (x, v) in A.data\n        if v > B[x]\n            return false\n        end\n    end\n    return true\nend\n\nfunction issubset(A::Multiset{S}, B::Multiset{T}) where {S,T}\n    if S == T\n        return _sub(A, B)\n    end\n    ST = typejoin(S, T)\n    AA = type_convert(ST, A)\n    BB = type_convert(ST, B)\n    return _sub(AA, BB)\nend\n\n\n(==)(A::Multiset, B::Multiset) = (length(A) == length(B)) && issubset(A, B)\n\n\n## mixing Multisets with other AbstractSets and the like\n\n\nunion(A::Multiset, B::T) where {T} = union(A, Multiset(B))\nunion(B::Set, A::Multiset) = union(A, Multiset(B))\nunion(B::BitSet, A::Multiset) = union(A, Multiset(B))\n\nintersect(A::Multiset, B::T) where {T} = intersect(A, Multiset(B))\nintersect(B::Set, A::Multiset) = intersect(A, Multiset(B))\nintersect(B::BitSet, A::Multiset) = intersect(A, Multiset(B))\n\n(+)(A::Multiset, B::T) where {T} = A + Multiset(B)\n(+)(B::T, A::Multiset) where {T} = A + Multiset(B)\n\n(-)(A::Multiset, B::T) where {T} = A - Multiset(B)\n(-)(B::T, A::Multiset) where {T} = Multiset(B) - A\n\n(*)(A::Multiset, B::T) where {T} = A * Multiset(B)\n(*)(A::T, B::Multiset) where {T} = Multiset(A) * B\n", "meta": {"hexsha": "fa51e1e0c5a8630f2ff5d0ed8d67186369adaae9", "size": 4193, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operations.jl", "max_stars_repo_name": "scheinerman/Multiset.jl", "max_stars_repo_head_hexsha": "fe08c9c214b1053b8326e79cf3ad3ae006fcbdf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-10-05T12:04:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:51:24.000Z", "max_issues_repo_path": "src/operations.jl", "max_issues_repo_name": "scheinerman/Multiset.jl", "max_issues_repo_head_hexsha": "fe08c9c214b1053b8326e79cf3ad3ae006fcbdf0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-03-22T13:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T12:58:31.000Z", "max_forks_repo_path": "src/operations.jl", "max_forks_repo_name": "scheinerman/Multiset.jl", "max_forks_repo_head_hexsha": "fe08c9c214b1053b8326e79cf3ad3ae006fcbdf0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-09-16T11:06:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T21:34:28.000Z", "avg_line_length": 23.8238636364, "max_line_length": 89, "alphanum_fraction": 0.5738134987, "num_tokens": 1441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7634301560949878}}
{"text": "using OrdinaryDiffEq, DiffEqSensitivity, DiffEqFlux, Flux\nusing ComponentArrays, LinearAlgebra, GalacticOptim, Test\n\nconst nknots = 10\nconst h = 1.0/(nknots+1)\nx = range(0, step=h, length=nknots)\nu0 = sin.(π*x)\n\n@inline function f(du,u,p,t)\n  du .= zero(eltype(u))\n  u₃ = @view u[3:end]\n  u₂ = @view u[2:end-1]\n  u₁ = @view u[1:end-2]\n  @. du[2:end-1] = p.k*((u₃ - 2*u₂ + u₁)/(h^2.0))\n  nothing\nend\n\np_true = ComponentArray(k=0.42)\njac_proto = Tridiagonal(similar(u0,nknots-1), similar(u0), similar(u0, nknots-1))\nprob = ODEProblem(ODEFunction(f,jac_prototype=jac_proto), u0, (0.0,1.0), p_true)\n@time sol_true = solve(prob, Rodas4P(), saveat=0.1)\n\nfunction loss(prob0, p)\n  prob = remake(prob0, p=p)\n  sol = solve(prob, Rodas4P(autodiff=false), saveat=0.1, sensealg=ForwardDiffSensitivity())\n  sum((sol .- sol_true).^2)\nend\n\np0 = ComponentArray(k=1.0)\nres = DiffEqFlux.sciml_train(p -> loss(prob,p), p0, ADAM(0.01), GalacticOptim.AutoZygote(), maxiters=100)\n@test res.u.k ≈ 0.42461977305259074 rtol=1e-1\n", "meta": {"hexsha": "9b248950a872a891a56fbc8d0190f49834596d87", "size": 1004, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/downstream/forwarddiffsensitivity_sparsity_components.jl", "max_stars_repo_name": "stjordanis/DiffEqSensitivity.jl", "max_stars_repo_head_hexsha": "8f8753b9fda0300b76a68a22b7f86ee0b7eda635", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 136, "max_stars_repo_stars_event_min_datetime": "2020-04-06T13:59:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T10:57:27.000Z", "max_issues_repo_path": "test/downstream/forwarddiffsensitivity_sparsity_components.jl", "max_issues_repo_name": "stjordanis/DiffEqSensitivity.jl", "max_issues_repo_head_hexsha": "8f8753b9fda0300b76a68a22b7f86ee0b7eda635", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 212, "max_issues_repo_issues_event_min_datetime": "2020-03-26T16:26:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T11:16:41.000Z", "max_forks_repo_path": "test/downstream/forwarddiffsensitivity_sparsity_components.jl", "max_forks_repo_name": "stjordanis/DiffEqSensitivity.jl", "max_forks_repo_head_hexsha": "8f8753b9fda0300b76a68a22b7f86ee0b7eda635", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2020-04-24T15:53:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T03:53:22.000Z", "avg_line_length": 31.375, "max_line_length": 105, "alphanum_fraction": 0.687250996, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7634301533303733}}
{"text": "\n#Constants and setup\nusing OrdinaryDiffEq\ninitial = [0.01, 0.01, 0.01, 0.01]\ntspan = (0.,100.)\n\n#Define the problem\nfunction double_pendulum_hamiltonian(udot,u,p,t)\n    α  = u[1]\n    lα = u[2]\n    β  = u[3]\n    lβ = u[4]\n    udot .=\n    [2(lα-(1+cos(β))lβ)/(3-cos(2β)),\n    -2sin(α) - sin(α+β),\n    2(-(1+cos(β))lα + (3+2cos(β))lβ)/(3-cos(2β)),\n    -sin(α+β) - 2sin(β)*(((lα-lβ)lβ)/(3-cos(2β))) + 2sin(2β)*((lα^2 - 2(1+cos(β))lα*lβ + (3+2cos(β))lβ^2)/(3-cos(2β))^2)]\nend\n\n#Pass to solvers\npoincare = ODEProblem(double_pendulum_hamiltonian, initial, tspan)\n\n\nsol = solve(poincare, Tsit5())\n\n\nusing Plots; gr()\nplot(sol, vars=[(0,3),(0,4)], leg=false, plotdensity=10000)\n\n\nplot(sol, vars=(3,4), leg=false)\n\n\nf = (t) -> sol(t,idxs=4)\n\n\nusing Optim\nopt = optimize(f,18.0,22.0)\n\n\nprintln(opt.minimizer)\nprintln(opt.minimum)\n\n\nf = (t) -> -sol(first(t),idxs=4)\nopt2 = optimize(f,0.0,22.0)\n\n\nplot(sol, vars=(0,4), plotdensity=10000)\nscatter!([opt.minimizer],[opt.minimum],label=\"Local Min\")\nscatter!([opt2.minimizer],[-opt2.minimum],label=\"Local Max\")\n\n\nf = (t) -> -sol(first(t),idxs=4)\nopt = optimize(f,[20.0],BFGS())\n\n\nimport NLopt, ForwardDiff\n\ncount = 0 # keep track of # function evaluations\n\nfunction g(t::Vector, grad::Vector)\n  if length(grad) > 0\n    #use ForwardDiff for the gradients\n    grad[1] = ForwardDiff.derivative((t)->sol(first(t),idxs=4),t)\n  end\n  sol(first(t),idxs=4)\nend\nopt = NLopt.Opt(:GN_ORIG_DIRECT_L, 1)\nNLopt.lower_bounds!(opt, [0.0])\nNLopt.upper_bounds!(opt, [40.0])\nNLopt.xtol_rel!(opt,1e-8)\nNLopt.min_objective!(opt, g)\n(minf,minx,ret) = NLopt.optimize(opt,[20.0])\nprintln(minf,\" \",minx,\" \",ret)\nNLopt.max_objective!(opt, g)\n(maxf,maxx,ret) = NLopt.optimize(opt,[20.0])\nprintln(maxf,\" \",maxx,\" \",ret)\n\n\nplot(sol, vars=(0,4), plotdensity=10000)\nscatter!([minx],[minf],label=\"Global Min\")\nscatter!([maxx],[maxf],label=\"Global Max\")\n\n\nusing DiffEqTutorials\nDiffEqTutorials.tutorial_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])\n\n", "meta": {"hexsha": "212157a712f052a1a96618deda0e9629e56fa1db", "size": 1951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_extras/03-ode_minmax.jl", "max_stars_repo_name": "isaacsas/DiffEqTutorials.jl", "max_stars_repo_head_hexsha": "46c1701ef613aacbd678bde7437a3c8de363990d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-18T06:27:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-18T06:27:54.000Z", "max_issues_repo_path": "script/ode_extras/03-ode_minmax.jl", "max_issues_repo_name": "isaacsas/DiffEqTutorials.jl", "max_issues_repo_head_hexsha": "46c1701ef613aacbd678bde7437a3c8de363990d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/ode_extras/03-ode_minmax.jl", "max_forks_repo_name": "isaacsas/DiffEqTutorials.jl", "max_forks_repo_head_hexsha": "46c1701ef613aacbd678bde7437a3c8de363990d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9213483146, "max_line_length": 121, "alphanum_fraction": 0.6442849821, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7634301464286612}}
{"text": "\"\"\"\nType representing any object drawable on image\n\"\"\"\nabstract type Drawable end\n\n\"\"\"\n    p = Point(x,y)\n    p = Point(c)\n\nA `Drawable` point on the image\n\"\"\"\nstruct Point <: Drawable\n    x::Int\n    y::Int\nend\n\nabstract type Line <: Drawable end\nabstract type Circle <: Drawable end\n\n\n\"\"\"\n    line = LineTwoPoints(p1, p2)\n\nA `Drawable` infinite length line passing through the two points\n`p1` and `p2`.\n\"\"\"\nstruct LineTwoPoints <: Line\n    p1::Point\n    p2::Point\nend\n\n\"\"\"\n    line = LineNormal(ρ, θ)\n\nA `Drawable` infinte length line having perpendicular length `ρ` from\norigin and angle `θ` between the perpendicular and x-axis\n\n\"\"\"\nstruct LineNormal{T<:Real, U<:Real} <: Line\n    ρ::T\n    θ::U\nend\n\n\"\"\"\n    circle = CircleThreePoints(p1, p2, p3)\n\nA `Drawable` circle passing through points `p1`, `p2` and `p3`\n\"\"\"\nstruct CircleThreePoints <: Circle\n    p1::Point\n    p2::Point\n    p3::Point\nend\n\n\"\"\"\n    circle = CirclePointRadius(center, ρ)\n\nA `Drawable` circle having center `center` and radius `ρ`\n\"\"\"\nstruct CirclePointRadius{T<:Real} <: Circle\n    center::Point\n    ρ::T\nend\n\n\"\"\"\n    ls = LineSegment(p1, p2)\n\nA `Drawable` finite length line between `p1` and `p2`\n\"\"\"\nstruct LineSegment <: Drawable\n    p1::Point\n    p2::Point\nend\n\n\"\"\"\n    path = Path([point])\n\nA `Drawable` sequence of line segments connecting consecutive pairs\nof points in `[point]`.\n!!! note\n    This will create a non-closed path. For a closed path, see `Polygon`\n\"\"\"\nstruct Path <: Drawable\n    vertices::Vector{Point}\nend\n\n\"\"\"\n    ellipse = Ellipse(center, ρx, ρy)\n\nA `Drawable` ellipse with center `center` and parameters `ρx` and `ρy`\n\n\"\"\"\nstruct Ellipse{T<:Real, U<:Real} <: Drawable\n    center::Point\n    ρx::T\n    ρy::U\nend\n\n\"\"\"\n    polygon = Polygon([vertex])\n\nA `Drawable` polygon i.e. a closed path created by joining the\nconsecutive points in `[vertex]` along with the first and last point.\n!!! note\n    This will create a closed path. For a non-closed path, see `Path`\n\"\"\"\nstruct Polygon <: Drawable\n    vertices::Vector{Point}\nend\n\n\"\"\"\n    rp = RegularPolygon(center, side_count, side_length, θ)\n\nA `Drawable` regular polygon.\n\n#Arguments\n* `center::Point` : the center of the polygon\n* `side_count::Int` : number of sides of the polygon\n* `side_length::Real` : length of each side\n* `θ::Real` : orientation of the polygon w.r.t x-axis (in radians)\n\n\"\"\"\nstruct RegularPolygon{T<:Real, U<:Real} <: Drawable\n    center::Point\n    side_count::Int\n    side_length::T\n    θ::U\nend\n\n\"\"\"\n    cross = Cross(c, range::UnitRange{Int})\nA `Drawable` cross passing through the point `c` with arms ranging across `range`.\n\"\"\"\nstruct Cross <: Drawable\n    c::Point\n    range::UnitRange{Int}\nend\n\n\"\"\"\n    img = draw!(img, drawable, color)\n    img = draw!(img, drawable)\n\nDraws `drawable` on `img` using color `color` which\ndefaults to `oneunit(eltype(img))`\n\"\"\"\ndraw!(img::AbstractArray{T,2}, object::Drawable) where {T<:Colorant} = draw!(img, object, oneunit(T))\n\n\n\"\"\"\n    img = draw!(img, [drawable], [color])\n    img = draw!(img, [drawable] ,color)\n    img = draw!(img, [drawable])\n\nDraws all objects in `[drawable]` in the given order on `img` using\ncorresponding colors from `[color]` which defaults to `oneunit(eltype(img))`\nIf only a single color `color` is specified then all objects will be\ncolored with that color.\n\"\"\"\nfunction draw!(img::AbstractArray{T,2}, objects::AbstractVector{U}, colors::AbstractVector{V}) where {T<:Colorant, U<:Drawable, V<:Colorant}\n    colors = copy(colors)\n    while length(colors) < length(objects)\n        push!(colors, oneunit(T))\n    end\n    foreach((object, color) -> draw!(img, object, color), objects, colors)\n    img\nend\n\ndraw!(img::AbstractArray{T,2}, objects::AbstractVector{U}, color::T = oneunit(T)) where {T<:Colorant, U<:Drawable} =\n    draw!(img, objects, [color for i in 1:length(objects)])\n\n\"\"\"\n    img_new = draw(img, drawable, color)\n    img_new = draw(img, [drawable], [color])\n\nDraws the `drawable` object on a copy of image `img` using color\n`color`. Can also draw multiple `Drawable` objects when passed\nas a `AbstractVector{Drawable}` with corresponding colors in `[color]`\n\"\"\"\ndraw(img::AbstractArray{T,2}, args...) where {T<:Colorant} = draw!(copy(img), args...)\n\nPoint(τ::Tuple{Int, Int}) = Point(τ...)\nPoint(p::CartesianIndex) = Point(p[2], p[1])\n\nfunction draw!(img::AbstractArray{T,2}, point::Point, color::T) where T<:Colorant\n    drawifinbounds!(img, point, color)\nend\n\n\"\"\"\n\n    img_new = drawifinbounds!(img, y, x, color)\n    img_new = drawifinbounds!(img, Point, color)\n    img_new = drawifinbounds!(img, CartesianIndex, color)\n\nDraws a single point after checkbounds() for coordinate in the image.\nColor Defaults to oneunit(T)\n\n\"\"\"\n\ndrawifinbounds!(img::AbstractArray{T,2}, p::Point, color::T = oneunit(T)) where {T<:Colorant} = drawifinbounds!(img, p.y, p.x, color)\ndrawifinbounds!(img::AbstractArray{T,2}, p::CartesianIndex{2}, color::T = oneunit(T)) where {T<:Colorant} = drawifinbounds!(img, Point(p), color)\n\nfunction drawifinbounds!(img::AbstractArray{T,2}, y::Int, x::Int, color::T) where {T<:Colorant}\n    if checkbounds(Bool, img, y, x) img[y, x] = color end\n    img\nend\n", "meta": {"hexsha": "4fa1ff6750c4fbbcbcd827dfb8466ffce4b60709", "size": 5132, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/core.jl", "max_stars_repo_name": "JuliaTagBot/ImageDraw.jl", "max_stars_repo_head_hexsha": "551501f91f8c4910cb599b95c2e740bfc68a2f95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core.jl", "max_issues_repo_name": "JuliaTagBot/ImageDraw.jl", "max_issues_repo_head_hexsha": "551501f91f8c4910cb599b95c2e740bfc68a2f95", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core.jl", "max_forks_repo_name": "JuliaTagBot/ImageDraw.jl", "max_forks_repo_head_hexsha": "551501f91f8c4910cb599b95c2e740bfc68a2f95", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9126213592, "max_line_length": 145, "alphanum_fraction": 0.6703039751, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7634166711223667}}
{"text": "\"\"\"\n    r = gnrank(sys, fastrank = true, atol = 0, atol1 = atol, atol2 = atol, rtol = n*ϵ )\n\nCompute the normal rank `r` of the transfer function matrix `G(λ)` of the descriptor system `sys = (A-λE,B,C,D)`. \n\nThe normal rank of `G(λ)` is evaluated as `r = k - n`, where `k` is the normal rank of\nthe system matrix pencil \n\n              | A-λE | B | \n      S(λ) := |------|---|\n              |  C   | D |  \n\nand `n` is the order of the system `sys` (i.e., the size of `A`). \n\nIf `fastrank = true`, the normal rank of `S(λ)` is evaluated by counting the singular values of `S(γ)` greater than `max(max(atol1,atol2), rtol*σ₁)`, \nwhere `σ₁` is the largest singular value of `S(γ)` and `γ` is a randomly generated value. \nIf `fastrank = false`, the rank is evaluated as `nr + ni + nf + nl`, where `nr` and `nl` are the sums of right and left Kronecker indices, \nrespectively, while `ni` and `nf` are the number of infinite and finite eigenvalues, respectively. The sums `nr+ni` and  \n`nf+nl` are determined from an appropriate Kronecker-like form of the pencil `S(λ)`, exhibiting the spliting of the right and left structures.\n\nThe keyword arguments `atol1`, `atol2`, and `rtol`, specify, respectively, \nthe absolute tolerance for the nonzero elements of `A`, `B`, `C`, `D`,  \nthe absolute tolerance for the nonzero elements of `E`,  \nand the relative tolerance for the nonzero elements of `A`, `B`, `C`, `D` and `E`.  \nThe default relative tolerance is `n*ϵ`, where `ϵ` is the working machine epsilon. \nThe keyword argument `atol` can be used to simultaneously set `atol1 = atol` and `atol2 = atol`. \n\"\"\"\nfunction gnrank(sys::DescriptorStateSpace; fastrank = true, atol::Real = 0, atol1::Real = atol, atol2::Real = atol, \n                rtol::Real = (max(sys.nx,sys.nu,sys.ny)*eps(real(float(one(eltype(sys.A))))))*iszero(min(atol1,atol2))) \n    sys.nx == 0 && (return rank(sys.D; atol = atol1, rtol))             \n    return max(0,sprank(dssdata(sys)..., atol1 = atol1, atol2 = atol2, rtol = rtol, fastrank = fastrank) - sys.nx)\nend\n\"\"\"\n    val = gzero(sys; fast = false, atol = 0, atol1 = atol, atol2 = atol, rtol = n*ϵ) \n\nReturn for the descriptor system `sys = (A-λE,B,C,D)` the complex vector `val` containing the \nfinite and infinite Smith zeros of the system matrix pencil  \n\n               | A-λE | B | \n       S(λ) := |------|---| .\n               |  C   | D |  \n\nThe values in `val` are called the _invariant zeros_ of the pencil `S(λ)` and are the _transmission zeros_ of the \ntransfer function matrix of `sys` if `A-λE` is _regular_ and the descriptor system realization \n`sys = (A-λE,B,C,D)` is _irreducible_.  \n\nThe computation of the zeros is performed by reducing the pencil `S(λ)` to an appropriate Kronecker-like form  \nusing orthonal similarity transformations and involves rank decisions based on rank revealing QR-decompositions with column pivoting, \nif `fast = true`, or, the more reliable, SVD-decompositions, if `fast = false`. \n\nThe keyword arguements `atol1`, `atol2`  and `rtol` specify the absolute tolerance for the nonzero\nelements of `A`, `B`, `C` and `D`, the absolute tolerance for the nonzero elements of `E`, \nand the relative tolerance for the nonzero elements of `A`, `E`, `B`, `C` and `D`, respectively. \nThe default relative tolerance is `n*ϵ`, where `n` is the size of `A`, and `ϵ` is the \nworking machine epsilon. \nThe keyword argument `atol` can be used to simultaneously set `atol1 = atol` and `atol2 = atol`. \n\"\"\"\nfunction gzero(SYS::DescriptorStateSpace;fast = false, atol::Real = 0, atol1::Real = atol, atol2::Real = atol, \n    rtol::Real = SYS.nx*eps(real(float(one(real(eltype(SYS.A)))))*iszero(min(atol1,atol2))) ) \n    # pzeros([SYS.A SYS.B; SYS.C SYS.D], [SYS.E zeros(SYS.nx,SYS.nu); zeros(SYS.ny,SYS.nx+SYS.nu)]; fast = fast, atol1 = atol1,\n    # atol2 = atol2, rtol = rtol )[1]\n    return spzeros(dssdata(SYS)...; fast = fast, atol1 = atol1, atol2 = atol2, rtol = rtol)[1]\nend\n\"\"\"\n    val = gpole(sys; fast = false, atol = 0, atol1 = atol, atol2 = atol, rtol = n*ϵ) \n\nReturn for the descriptor system `sys = (A-λE,B,C,D)` the complex vector `val` containing \nthe finite and infinite zeros of the system pole pencil `P(λ) := A-λE`. \nThe values in `val` are the poles of the transfer function matrix of `sys`, if `A-λE` is _regular_ and the \ndescriptor system realization `sys = (A-λE,B,C,D)` is _irreducible_. \nIf the pencil `A-λE` is singular, `val` also contains `NaN` elements,\nwhose number is the rank deficiency of the pencil  `A-λE`.\n\nFor `E` nonsingular, `val` contains the generalized eigenvalues of the pair `(A,E)`. \nFor `E` singular, `val` contains the zeros of `P(λ)`, which are computed \nby reducing the pencil `P(λ)` to an appropriate Kronecker-like form  \nusing orthonal similarity transformations and involves rank decisions based on rank revealing QR-decompositions with column pivoting, \nif `fast = true`, or, the more reliable, SVD-decompositions, if `fast = false`. \n\nThe regularity of `A-λE` is implicitly checked. If `check_reg = true`, an error message is issued if the pencil   \n`A-λE` is singular. If `check_reg = false` and the pencil `A-λE` is singular, then `n-r` poles are set to `NaN`, where\n`n` is the system order and `r` is the normal rank of `A-λE`. \n\nThe keyword arguements `atol1`, `atol2`  and `rtol` specify the absolute tolerance for the nonzero\nelements of `A`, the absolute tolerance for the nonzero elements of `E`, \nand the relative tolerance for the nonzero elements of `A` and `E`, respectively. \nThe default relative tolerance is `n*ϵ`, where `ϵ` is the working machine epsilon. \nThe keyword argument `atol` can be used to simultaneously set `atol1 = atol` and `atol2 = atol`. \n\"\"\"\nfunction gpole(SYS::DescriptorStateSpace{T}; fast = false, atol::Real = 0, atol1::Real = atol, atol2::Real = atol, \n               rtol::Real = SYS.nx*eps(real(float(one(T))))*iszero(min(atol1,atol2)), check_reg = false ) where T\n    T <: BlasFloat ? T1 = T : T1 = promote_type(Float64,T)\n    A = copy_oftype(SYS.A,T1)\n    if SYS.E == I\n       return isschur(A) ? ordeigvals(A) : MatrixPencils.eigvalsnosort(A)\n    else\n       E = copy_oftype(SYS.E,T1)\n       if norm(E,Inf) > atol2 \n          epsm = eps(float(one(real(T1))))\n          isschur(A,E) && rcond(UpperTriangular(E)) >= SYS.nx*epsm && (return ordeigvals(A,E)[1])\n          istriu(E) && rcond(UpperTriangular(E)) >= SYS.nx*epsm && (return MatrixPencils.eigvalsnosort(A,E))\n          rcond(E) >= SYS.nx*epsm && (return MatrixPencils.eigvalsnosort(A,E))\n       end\n       # singular E\n       poles, nip, krinfo = pzeros(A, E; fast = fast, atol1 = atol1, atol2 = atol2, rtol = rtol )\n       check_reg && (SYS.nx == krinfo.nrank || error(\"the system has a singular pole pencil\"))\n       return [poles;NaN*ones(SYS.nx-krinfo.nrank)]\n    end\nend\n\"\"\"\n    gzeroinfo(sys; smarg, fast = false, atol = 0, atol1 = atol, atol2 = atol, \n              rtol = n*ϵ, offset = sqrt(ϵ)) -> (val, info) \n\nReturn for the descriptor system `sys = (A-λE,B,C,D)` the complex vector `val` containing \nthe finite and infinite Smith zeros of the system matrix pencil `S(λ)` \n\n              | A-λE | B | \n       S(λ) = |------|---| \n              |  C   | D |  \n\nand the named tuple `info` containing information on the Kronecker structure of the pencil `S(λ)`. \nThe values in `val` are called the _invariant zeros_ of the pencil `S(λ)` and are the _transmission zeros_ of the \ntransfer function matrix of `sys` if `A-λE` is _regular_ and the descriptor system realization \n`sys = (A-λE,B,C,D)` is _irreducible_. \n\nFor stability analysis purposes, a stability margin `smarg` can be specified for the finite zeros,\nin conjunction with a stability domain boundary offset `β` to numerically assess the  finite zeros \nwhich belong to the boundary of the stability domain as follows: \nin the continuous-time case, these are the finite zeros having real parts in the interval\n`[smarg-β, smarg+β]`, while in the discrete-time case, these are the finite zeros having moduli in the interva\n`[smarg-β, smarg+β]`. The default value of the stability margin `smarg` is `0` for a continuous-time system and \n`1` for a discrete-time system. \nThe default value used for `β` is `sqrt(ϵ)`, where `ϵ` is the working machine precision. \n\nThe named tuple `info` contains the following information:\n\n`info.nfz` is the number of finite eigenvalues of the pencil `S(λ)` (also the number of finite zeros of `sys`);\n\n`info.niev` is the number of infinite eigenvalues of the pencil `S(λ)`;\n\n`info.nisev` is the number of  _simple_ infinite eigenvalues of the pencil `S(λ)`; \n\n`info.niz` is the number of infinite zeros of the system `sys`;\n\n`info.nfsz` is the number of finite stable zeros, i.e., the finite zeros\nhaving real parts or moduli less than `smarg-β` for a continuous- or discrete-time system, respectively;\n\n`info.nfsbz` is the number of finite zeros on the boundary of the \n          stability domain, i.e., the finite zeros\n          having real parts or moduli in the interval `[smarg-β, smarg+β]` for a continuous- or discrete-time system, respectively;\n\n`info.nfuz` is the number of finite unstable zeros, i.e., the finite zeros\nhaving real parts or moduli greater than `smarg+β` for a continuous- or discrete-time system, respectively;\n\n`info.nrank` is the normal rank of the pencil `S(λ)`;\n\n`info.miev` is an integer vector, which contains the multiplicities \n          of the infinite eigenvalues of the pencil `S(λ)`  \n           (also the dimensions of the elementary infinite blocks in the\n          Kronecker form of `S(λ)`);\n\n`info.miz` is an integer vector, which contains the information on the  \n           multiplicities of the infinite zeros of `S(λ)` as follows: \n           `S(λ)` has `info.mip[i]` infinite zeros of multiplicity `i`, and \n             is empty if `S(λ)` has no infinite zeros;\n\n`info.rki` is an integer vector, which contains the _right Kronecker indices_ \n         of the pencil `S(λ)` (empty for a regular pencil);\n\n`info.lki` is an integer vector, which contains the _left Kronecker indices_ \n        of the pencil `S(λ)` (empty for a regular pencil);\n\n`info.regular` is set to `true`,  if the pencil `S(λ)` is regular and set to  \n`false`, if the pencil `S(λ)` is singular;\n\n`info.stable` is set to `true`, if the pencil `S(λ)` has only stable  \n                finite zeros and all its infinite zeros are\n                 simple and  is set to `false` otherwise.\n\n_Note:_ The finite zeros and the finite eigenvalues of the pencil\n`S(λ)` are the same, but the multiplicities of infinite eigenvalues \n   are in excess with one to the multiplicities of infinite zeros. \n\nThe computation of the zeros is performed by reducing the pencil `S(λ)` to an appropriate Kronecker-like form  \nusing orthonal similarity transformations and involves rank decisions based on rank revealing QR-decompositions with column pivoting, \nif `fast = true`, or, the more reliable, SVD-decompositions, if `fast = false`. \n\nThe keyword arguements `atol1`, `atol2`  and `rtol` specify the absolute tolerance for the nonzero\nelements of `A`, `B`, `C` and `D`, the absolute tolerance for the nonzero elements of `E`, \nand the relative tolerance for the nonzero elements of `A`, `E`, `B`, `C` and `D`, respectively. \nThe default relative tolerance is `n*ϵ`, where `n` is the size of `A` and `ϵ` is the \nworking machine epsilon. \nThe keyword argument `atol` can be used to simultaneously set `atol1 = atol` and `atol2 = atol`. \n\"\"\"\nfunction gzeroinfo(SYS::DescriptorStateSpace{T}; smarg::Real = SYS.Ts == 0 ? 0 : 1, fast = false, \n                   atol::Real = zero(float(real(T))), atol1::Real = atol, atol2::Real = atol, \n                   rtol::Real = SYS.nx*eps(real(float(one(T))))*iszero(min(atol1,atol2)), \n                   offset::Real = sqrt(eps(float(real(T)))) ) where T\n    val, miz, krinfo = spzeros(dssdata(SYS)...; fast = fast, atol1 = atol1, atol2 = atol2, rtol = rtol)\n    nfsz, nfsbz, nfuz = eigvals_info(val[isfinite.(val)], smarg, SYS.Ts != 0, offset)\n    niev = sum(krinfo.id)\n    nisev = niev == 0 ? 0 : krinfo.id[1]\n    niz = sum(miz)\n    nfz = krinfo.nf\n    return val, (nfz = nfz, niev = niev, nisev = nisev, niz = niz, nfsz = nfsz, nfsbz = nfsbz, \n                 nfuz = nfuz, nrank = krinfo.nrank, miev = krinfo.id, miz = miz, \n                 rki = krinfo.rki, lki = krinfo.lki, regular = (sum(krinfo.rki) == 0 && sum(krinfo.lki) == 0),  \n                 stable = (niz == 0 && nfsz == nfz))\nend\n\"\"\"\n    gpoleinfo(sys; smarg, fast = false, atol = 0, atol1 = atol, atol2 = atol, \n              rtol = n*ϵ, offset = sqrt(ϵ)) -> (val, info) \n\nReturn for the descriptor system `sys = (A-λE,B,C,D)` the complex vector `val` containing \nthe finite and infinite zeros of the system pole pencil `P(λ) := A-λE` and the named tuple `info` containing information on \nthe eigenvalue structure of the pole pencil `P(λ)`. The values in `val` are the _poles_ of the \ntransfer function matrix of `sys`, if `A-λE` is _regular_ and the \ndescriptor system realization `sys = (A-λE,B,C,D)` is _irreducible_. \nIf the pencil `A-λE` is singular, `val` also contains `NaN` elements,\nwhose number is the rank deficiency of the pencil  `A-λE`.\n\nFor stability analysis purposes, a stability margin `smarg` can be specified for the finite eigenvalues,\nin conjunction with a stability domain boundary offset `β` to numerically assess the  finite eigenvalues \nwhich belong to the boundary of the stability domain as follows: \nin the continuous-time case, these are the finite eigenvalues having real parts in the interval\n`[smarg-β, smarg+β]`, while in the discrete-time case, these are the finite eigenvalues having moduli in the interval\n`[smarg-β, smarg+β]`. The default value of the stability margin `smarg` is `0` for a continuous-time system and \n`1` for a discrete-time system. \nThe default value used for `β` is `sqrt(ϵ)`, where `ϵ` is the working machine precision. \n\nThe named tuple `info` contains the following information:\n\n`info.nfev` is the number of finite eigenvalues of the pencil `A-λE` (also the number of finite poles of `sys`);\n\n`info.niev` is the number of infinite eigenvalues of the pencil `A-λE`;\n\n`info.nisev` is the number of _simple_ infinite eigenvalues of the pencil `A-λE` (also known as non-dynamic modes); \n\n`info.nip` is the number of infinite poles of the system `sys`;\n\n`info.nfsev` is the number of finite stable eigenvalues, i.e., the finite eigenvalues\nhaving real parts or moduli less than `smarg-β` for a continuous- or discrete-time system, respectively;\n\n`info.nfsbev` is the number of finite eigenvalues on the boundary of the \n          stability domain, i.e., the finite eigenvalues\n          having real parts or moduli in the interval `[smarg-β, smarg+β]` for a continuous- or discrete-time system, respectively;\n\n`info.nfuev` is the number of finite unstable eigenvalues, i.e., the finite eigenvalues\nhaving real parts or moduli greater than `smarg+β` for a continuous- or discrete-time system, respectively;\n\n`info.nhev` is the number of _hidden_ eigenvalues set to `NaN`\n         (can be nonzero only if the pencil `A-λE` is singular);  \n\n`info.nrank` is the normal rank of the pencil `A-λE`;\n\n`info.miev` is an integer vector, which contains the multiplicities \n          of the infinite eigenvalues of the pencil `A-λE` as follows:\n          the `i`-th element `info.miev[i]` is the order of an infinite elementary divisor \n          (i.e., the multiplicity of an infinite eigenvalue) and \n          the number of infinite poles is the sum of the components of `info.miev`;  \n\n`info.mip` is an integer vector, which contains the information on the  \n           multiplicities of the infinite zeros of `A-λE` as follows: \n           the `i`-th element `info.mip[i]` is equal to `k-1`, where `k` is the order of an infinite elementary \n             divisor with `k > 0` and the number of infinite poles is the sum of the components of `info.mip`; \n\n`info.rki` is an integer vector, which contains the _right Kronecker indices_ \n           of the pencil `A-λE` (empty for a regular pencil);\n\n`info.lki` is an integer vector, which contains the _left Kronecker indices_\n           of the pencil `A-λE` (empty for a regular pencil);\n\n`info.regular` is set to `true`,  if the pencil `A-λE` is regular and set to  \n`false`, if the pencil `A-λE` is singular;\n\n`info.proper` is set to `true`, if the pencil `A-λE` is regular and all its infinite \n                 eigenvalues are simple (has only non-dynamic modes), or \n                 is set to `false`, if the pencil `A-λE` is singular or has higher order infinite eigenvalues;\n\n`info.stable` is set to `true`, if the pencil `A-λE` is regular, has only stable  \n                finite eigenvalues and all its infinite eigenvalues are\n                 simple (has only non-dynamic modes), and  is set to `false` otherwise.\n\n_Note:_ The finite poles and the finite eigenvalues of the pencil `P(λ)` are the same, \nbut the multiplicities of infinite eigenvalues of `P(λ)` are in excess with one to the multiplicities of infinite poles.\n\nFor the reduction of the pencil `P(λ)` to an appropriate Kronecker-like form  \northonal similarity transformations are performed, which involve rank decisions based on rank revealing QR-decompositions with column pivoting, \nif `fast = true`, or, the more reliable, SVD-decompositions, if `fast = false`. \n\nThe keyword arguements `atol1`, `atol2`  and `rtol` specify the absolute tolerance for the nonzero\nelements of `A`, the absolute tolerance for the nonzero elements of `E`, \nand the relative tolerance for the nonzero elements of `A` and `E`, respectively. \nThe default relative tolerance is `n*ϵ`, where `n` is the size of `P(λ)`, and `ϵ` is the \nworking machine epsilon. \nThe keyword argument `atol` can be used to simultaneously set `atol1 = atol` and `atol2 = atol`. \n\"\"\"\nfunction gpoleinfo(SYS::DescriptorStateSpace{T}; smarg::Real = SYS.Ts == 0 ? 0 : 1, fast = false, \n                   atol::Real = zero(float(real(T))), atol1::Real = atol, atol2::Real = atol, \n                   rtol::Real = SYS.nx*eps(real(float(one(T))))*iszero(min(atol1,atol2)), \n                   offset::Real = sqrt(eps(float(real(T))))) where T\n    disc = (SYS.Ts != 0)\n    n = SYS.nx\n    T <: BlasFloat ? T1 = T : T1 = promote_type(Float64,T)\n    A = copy_oftype(SYS.A,T1)\n    if SYS.E == I\n       isschur(A) ? val = ordeigvals(A) : val = MatrixPencils.eigvalsnosort(A)\n       nfsev, nfsbev, nfuev = eigvals_info(val, smarg, disc, offset)\n       return val, (nfev = n, niev = 0, nisev = 0, nip = 0, nfsev = nfsev, nfsbev = nfsbev, \n                     nfuev = nfuev, nhev = 0, nrank = n, miev = Int[], mip = Int[], \n                     rki = Int[], lki = Int[], regular = true, proper = true, stable = (nfsev == n))\n    else\n       krinfo = nothing\n       E = copy_oftype(SYS.E,T1)\n       if norm(E,Inf) > atol2 \n          epsm = eps(float(one(real(T))))\n          if isschur(A,E) && rcond(UpperTriangular(E)) >= n*epsm\n             val = ordeigvals(A,E)[1]\n          elseif istriu(E) && rcond(UpperTriangular(E)) >= n*epsm  \n             val = MatrixPencils.eigvalsnosort(A,E)\n          elseif rcond(E) >= n*epsm \n             val = MatrixPencils.eigvalsnosort(A,E)\n          else\n             # singular E\n             val, mip, krinfo = pzeros(A, E; fast = fast, atol1 = atol1, atol2 = atol2, rtol = rtol )\n          end\n       else\n          val, mip, krinfo = pzeros(A, E; fast = fast, atol1 = atol1, atol2 = atol2, rtol = rtol )\n       end\n       nfsev, nfsbev, nfuev = eigvals_info(val[isfinite.(val)], smarg, disc, offset)\n       isnothing(krinfo) && \n           (return val, (nfev = n, niev = 0, nisev = 0, nip = 0, nfsev = nfsev, nfsbev = nfsbev, \n                        nfuev = nfuev, nhev = 0, nrank = n, miev = Int[], mip = Int[], \n                        rki = Int[], lki = Int[], regular = true, proper = true, stable = (nfsev == n)))\n       nhev = n - krinfo.nrank \n       nhev > 0 && (@warn \"The system has a singular pole pencil\")\n       val = [val;NaN*ones(nhev)]\n       niev = sum(krinfo.id)\n       nip = sum(mip)\n       nfev = n-niev\n       return val, (nfev = nfev, niev = niev, nisev = count(krinfo.id .== 1), nip = nip, nfsev = nfsev, nfsbev = nfsbev, \n                    nfuev = nfuev, nhev = nhev, nrank = krinfo.nrank, miev = krinfo.id, mip = mip, \n                    rki = krinfo.rki, lki = krinfo.lki, regular = (nhev == 0), proper = (nip == 0), \n                    stable = (nip == 0 && nfsev == nfev))\n    end\nend\nfunction eigvals_info(val::AbstractVector, smarg::Real, disc::Bool, offset::Real)\n    if disc\n       nf = count(abs.(val) .< smarg-offset)\n       nu = count(abs.(val) .> smarg+offset)\n    else\n       nf = count(real.(val) .< smarg-offset)\n       nu = count(real.(val) .> smarg+offset)\n    end\n    return nf, length(val)-nf-nu, nu\nend\n\"\"\"\n    isregular(sys; atol = 0, atol1 = atol, atol2 = atol, rtol = n*ϵ)\n\nReturn `true` if the descriptor system `sys = (A-λE,B,C,D)` has a regular pole pencil `A-λE` and `false` otherwise.  \n\nTo test whether the pencil `A-λE` is regular (i.e., `det(A-λE) ̸≡ 0`),  \nthe underlying computational procedure reduces the pencil `A-λE` to an appropriate Kronecker-like form, \nwhich provides information on the rank of `A-λE`. \n\nThe keyword arguements `atol1`, `atol2` and `rtol` specify the absolute tolerance for the nonzero\nelements of `A`, the absolute tolerance for the nonzero elements of `E`, and the relative tolerance \nfor the nonzero elements of `A` and `E`, respectively. \nThe default relative tolerance is `n*ϵ`, where `n` is the size of  `A`, and `ϵ` is the \nworking machine epsilon. \nThe keyword argument `atol` can be used to simultaneously set `atol1 = atol` and `atol2 = atol`. \n\"\"\"\nfunction isregular(SYS::DescriptorStateSpace{T}; atol::Real = zero(float(real(T))), atol1::Real = atol, atol2::Real = atol, \n    rtol::Real = SYS.nx*eps(real(float(one(T))))*iszero(min(atol1,atol2))) where T\n    SYS.E == I && (return true)\n    epsm = eps(float(one(real(T))))\n    istriu(SYS.E) && rcond(UpperTriangular(SYS.E)) > SYS.nx*epsm && (return true)\n    rcond(SYS.E) > SYS.nx*epsm && (return true)\n    return MatrixPencils.isregular(SYS.A, SYS.E, atol1 = atol1, atol2 = atol2, rtol = rtol )\nend\n\"\"\"\n    isproper(sys; atol = 0, atol1 = atol, atol2 = atol, rtol = = n*ϵ, fast = true)\n\nReturn `true` if the transfer function matrix `G(λ)` of the descriptor system `sys = (A-λE,B,C,D)` is proper\nand `false` otherwise.  \n\nFor a descriptor system realization `sys = (A-λE,B,C,D)` without uncontrollable and unobservable infinite eigenvalues,\nit is checked that the pencil `A-λE` has no infinite eigenvalues or, if infinite eigenvalues exist,\nall infinite eigenvalues are simple. If the original descriptor realization has uncontrollable or\nunobservable infinite eigenvalues, these are elliminated using orthogonal pencil reduction algorithms. \n\nThe keyword arguments `atol1`, `atol2`, and `rtol`, specify, respectively, \nthe absolute tolerance for the nonzero elements of `A`, `B`, `C`, `D`,  \nthe absolute tolerance for the nonzero elements of `E`,  \nand the relative tolerance for the nonzero elements of `A`, `B`, `C`, `D` and `E`.  \nThe default relative tolerance is `n*ϵ`, where `n` is the order of `A` and `ϵ` is the working machine epsilon. \nThe keyword argument `atol` can be used to simultaneously set `atol1 = atol` and `atol2 = atol`. \n\"\"\"\nfunction isproper(SYS::DescriptorStateSpace{T}; fast::Bool = true, atol::Real = zero(float(real(T))), atol1::Real = atol, atol2::Real = atol, \n    rtol::Real = SYS.nx*eps(real(float(one(T))))*iszero(min(atol1,atol2))) where T\n    (SYS.E == I || SYS.nx == 0)   && (return true)\n    epsm = eps(float(one(real(T))))\n    istriu(SYS.E) && rcond(UpperTriangular(SYS.E)) > SYS.nx*epsm && \n                     (return true)\n    rcond(SYS.E) > SYS.nx*epsm && (return true)\n    # check regularity for singular E\n    MatrixPencils.isregular(SYS.A, SYS.E, atol1 = atol1, atol2 = atol2, rtol = rtol ) || (return false)   \n    # compute a realizations without uncontrollable and unobservable infinite eigenvalues\n    A, E, = lsminreal2(SYS.A, SYS.E, SYS.B, SYS.C, SYS.D; \n             fast = fast, atol1 = atol1, atol2 = atol2, rtol = rtol, infinite = true, \n             contr = true, obs = true, noseig = false) \n    krinfo = pkstruct(A, E; fast = fast, atol1 = atol1, atol2 = atol2, rtol = rtol )\n    return (isempty(krinfo.id) || maximum(krinfo.id) == 1) \nend\n\"\"\"\n    isstable(sys[, smarg]; fast = true, atol = 0, atol1 = atol, atol2 = atol, rtol = n*ϵ, offset = sqrt(ϵ))\n\nReturn `true` if the descriptor system `sys = (A-λE,B,C,D)` has only stable poles and `false` otherwise.  \n\nIt is checked that the pole pencil `P(λ) := A-λE` has no infinite eigenvalues or, if infinite eigenvalues exist,\nall infinite eigenvalues are simple, and additionally the real parts of all finite eigenvalues  are\nless than `smarg-β` for a continuous-time system or \nhave moduli less than `smarg-β` for a discrete-time system, where `smarg` is the stability margin and \n`β` is the stability domain boundary offset. \nThe default value of the stability margin `smarg` is `0` for a continuous-time system and \n`1` for a discrete-time system.\nThe offset  `β` to be used to numerically assess the stability of eigenvalues \ncan be specified via the keyword parameter `offset = β`. \nThe default value used for `β` is `sqrt(ϵ)`, where `ϵ` is the working machine precision. \n\nFor `E` singular, the computation of the poles is performed by reducing the pencil `P(λ)` to an appropriate Kronecker-like form  \nusing orthonal similarity transformations and involves rank decisions based on rank revealing QR-decompositions with column pivoting, \nif `fast = true`, or, the more reliable, SVD-decompositions, if `fast = false`. \n\nThe keyword arguments `atol1`, `atol2`, and `rtol`, specify, respectively, \nthe absolute tolerance for the nonzero elements of `A`, `B`, `C`, `D`,  \nthe absolute tolerance for the nonzero elements of `E`,  \nand the relative tolerance for the nonzero elements of `A`, `B`, `C`, `D` and `E`.  \nThe default relative tolerance is `n*ϵ`, where `n` is the order of `A` and `ϵ` is the working machine epsilon. \nThe keyword argument `atol` can be used to simultaneously set `atol1 = atol` and `atol2 = atol`. \n\"\"\"\nfunction isstable(SYS::DescriptorStateSpace{T}, smarg::Real = SYS.Ts == 0 ? 0 : 1; \n                  fast = false, atol::Real = 0, atol1::Real = atol, atol2::Real = atol, \n                  rtol::Real = SYS.nx*eps(real(float(one(T))))*iszero(min(atol1,atol2)), \n                  offset::Real = sqrt(eps(float(real(T))))) where T\n    disc = (SYS.Ts != 0)\n    β = abs(offset); \n    if SYS.E == I\n       isschur(SYS.A) ? poles = ordeigvals(SYS.A) : poles = eigvals(SYS.A)\n    else\n       poles = gpole(SYS; fast = fast, atol1 = atol1, atol2 = atol2, rtol = rtol)\n       (any(isinf.(poles)) || any(isnan.(poles)))  && (return false)\n    end\n    return disc ? all(abs.(poles) .< smarg-β) : all(real.(poles) .< smarg-β)\nend\n\"\"\"\n    ghanorm(sys, fast = true, atol = 0, atol1 = atol, atol2 = atol, rtol = n*ϵ) -> (hanorm, hs)\n\nCompute for a proper and stable descriptor system `sys = (A-λE,B,C,D)` with the transfer function\nmatrix `G(λ)`, the Hankel norm `hanorm =` ``\\\\small ||G(\\\\lambda)||_H`` and the vector of Hankel singular values `hs` of the system.\n\nFor a proper system with `E` singular, the uncontrollable infinite eigenvalues of the pair `(A,E)` and\nthe non-dynamic modes are elliminated using minimal realization techniques.\nThe rank determinations in the performed reductions\nare based on rank revealing QR-decompositions with column pivoting \nif `fast = true` or the more reliable SVD-decompositions if `fast = false`. \n\n   The keyword arguments `atol1`, `atol2`, and `rtol`, specify, respectively, \nthe absolute tolerance for the nonzero elements of `A`, `B`, `C`, `D`,  \nthe absolute tolerance for the nonzero elements of `E`,  \nand the relative tolerance for the nonzero elements of `A`, `B`, `C`, `D` and `E`.  \nThe default relative tolerance is `n*ϵ`, where `ϵ` is the working machine epsilon \nand `n` is the order of the system `sys`. The keyword argument `atol` can be used \nto simultaneously set `atol1 = atol` and `atol2 = atol`. \n\"\"\"   \nfunction ghanorm(sys::DescriptorStateSpace{T}; fast::Bool = true, \n                 atol::Real = zero(float(real(T))), atol1::Real = atol, atol2::Real = atol, \n                 rtol::Real = sys.nx*eps(real(float(one(T))))*iszero(min(atol1,atol2)))  where T \n    \n    T1 = T <: BlasFloat ? T : promote_type(Float64,T) \n    n = size(sys.A,1)  \n\n    n == 0 && (return zero(real(T1)), zeros(real(T1),0))\n\n    s2eps = sqrt(eps(real(T1)))       \n    disc = !iszero(sys.Ts)\n    \n    \n    if  sys.E == I\n        # for a non-dynamic system, we set the Hankel norm to zero,\n        # but the Hankel singular values are empty\n        size(sys.A,1) == 0 && (return zero(real(T1)), zeros(real(T1),0))\n        # reduce the system to Schur coordinate form\n        SF = schur(sys.A)\n        # check stability\n        ((disc && maximum(abs.(SF.values)) >= 1-s2eps) || (!disc && maximum(real(SF.values)) >= -s2eps)) &&\n              error(\"The system sys is unstable\")\n        S = plyaps(SF.T, SF.Z'*sys.B; disc = disc)\n        R = plyaps(SF.T', (sys.C*SF.Z)'; disc = disc)\n        hs = svdvals(R*S)\n     else\n        # eliminate non-dynamic modes if possible\n        if rcond(sys.E) < n*eps(float(real(T1)))\n           # sys = gss2ss(sys,s2eps,'triu');\n           sys = gminreal(sys, fast = fast, atol1 = atol1, atol2 = atol2, rtol = rtol);\n           rcond(sys.E) < n*eps(float(real(T1))) && error(\"The system SYS is not proper\")\n        end\n        # for a non-dynamic system, we set the Hankel norm to zero,\n        # but the Hankel singular values are empty\n        size(sys.A,1) == 0 && (return zero(real(T1)), zeros(real(T1),0))\n        # reduce the system to generalized Schur coordinate form\n        SF = schur(sys.A,sys.E)\n        ((disc && maximum(abs.(SF.values)) >= 1-s2eps) || (!disc && maximum(real(SF.values)) >= -s2eps)) &&\n              error(\"The system sys is unstable\") \n        S = plyaps(SF.S, SF.T, SF.Q'*sys.B; disc = disc)\n        R = plyaps(SF.S', SF.T', (sys.C*SF.Z)'; disc = disc)\n        hs = svdvals(R*UpperTriangular(SF.T)*S)\n    end\n\n    return hs[1], hs\n    # end GHANORM\nend\n\"\"\"\n    gh2norm(sys, fast = true, offset = sqrt(ϵ), atol = 0, atol1 = atol, atol2 = atol, atolinf = atol, rtol = n*ϵ) \n\nCompute for a descriptor system `sys = (A-λE,B,C,D)` the `H2` norm of its transfer function  matrix `G(λ)`.\nThe `H2` norm is infinite, if `sys` has unstable poles, or, for a continuous-time, the system has nonzero gain at infinity.\nTo check the stability, the eigenvalues of the _pole pencil_ `A-λE` must have real parts less \nthan `-β` for a continuous-time system or \nhave moduli less than `1-β` for a discrete-time system, where `β` is the stability domain boundary offset.\nThe offset  `β` to be used can be specified via the keyword parameter `offset = β`. \nThe default value used for `β` is `sqrt(ϵ)`, where `ϵ` is the working machine precision. \n\nFor a continuous-time system `sys` with `E` singular, a reduced order realization is determined first, without \nuncontrollable and unobservable nonzero finite and infinite eigenvalues of the corresponding pole pencil. \nThe rank determinations in the performed reductions\nare based on rank revealing QR-decompositions with column pivoting \nif `fast = true` or the more reliable SVD-decompositions if `fast = false`.   \n\nThe keyword arguments `atol1`, `atol2`, and `rtol`, specify, respectively, \nthe absolute tolerance for the nonzero elements of `A`, `B`, `C`, `D`,  \nthe absolute tolerance for the nonzero elements of `E`,  \nand the relative tolerance for the nonzero elements of `A`, `B`, `C`, `D` and `E`.  \nThe keyword argument `atolinf` is the absolute tolerance for the gain of `G(λ)` at `λ = ∞`. \nThe used default value is `atolinf = 0`. \nThe default relative tolerance is `n*ϵ`, where `ϵ` is the working machine epsilon \nand `n` is the order of the system `sys`. The keyword argument `atol` can be used \nto simultaneously set `atol1 = atol` and `atol2 = atol`.  \n\"\"\"   \nfunction gh2norm(sys::DescriptorStateSpace{T}; fast::Bool = true, offset::Real = sqrt(eps(float(real(T)))), \n                 atol::Real = zero(float(real(T))), atol1::Real = atol, atol2::Real = atol, atolinf::Real = atol, \n                 rtol::Real = sys.nx*eps(real(float(one(T))))*iszero(min(atol1,atol2)))  where T \n    return gl2norm(sys; h2norm = true, fast = fast, offset = offset, atol1 = atol1, atol2 = atol2, atolinf = atolinf, rtol = rtol)\n    \nend\n\"\"\"\n    gl2norm(sys, h2norm = false, fast = true, offset = sqrt(ϵ), atol = 0, atol1 = atol, atol2 = atol, atol3 = atol, atolinf = atol, rtol = n*ϵ) \n\nCompute for a descriptor system `sys = (A-λE,B,C,D)` the `L2` norm of its transfer function  matrix `G(λ)`.\nThe `L2` norm is infinite if the _pole pencil_ `A-λE` has\nzeros (i.e., poles) on the stability domain boundary, i.e., on the extended imaginary axis, in the continuous-time case, \nor on the unit circle, in the discrete-time case. \nThe `L2` norm is also infinite for a continuous-time system having a gain at infinity greater than `atolinf`. \n\nTo check the lack of poles on the stability domain boundary, the eigenvalues of the pencil `A-λE` \nmust not have real parts in the interval `[-β,β]` for a continuous-time system or \nmust not have moduli in the interval `[1-β,1+β]` for a discrete-time system, where `β` is the stability domain boundary offset.  \nThe offset  `β` to be used can be specified via the keyword parameter `offset = β`. \nThe default value used for `β` is `sqrt(ϵ)`, where `ϵ` is the working machine precision. \n\nIf `h2norm = true`, the `H2` norm is computed. \nThe `H2` norm is infinite if the _pole pencil_ `A-λE` has unstable zeros (i.e., unstable poles), or\nfor a continuous-time system having a gain at infinity greater than `atolinf`.  \nTo check the stability, the eigenvalues of the pencil `A-λE` must have real parts less than `-β` for a continuous-time system or \nhave moduli less than `1-β` for a discrete-time system. \n\nFor a continuous-time system `sys` with `E` singular, a reduced order realization is determined first, without \nuncontrollable and unobservable nonzero finite and infinite eigenvalues of the corresponding pole pencil. \nThe rank determinations in the performed reductions\nare based on rank revealing QR-decompositions with column pivoting \nif `fast = true` or the more reliable SVD-decompositions if `fast = false`.   \n\nThe keyword arguments `atol1`, `atol2`, and `rtol`, specify, respectively, \nthe absolute tolerance for the nonzero elements of `A`, `B`, `C`, `D`,  \nthe absolute tolerance for the nonzero elements of `E`,  \nand the relative tolerance for the nonzero elements of `A`, `B`, `C`, `D` and `E`.  \nThe keyword argument `atol3` specifies the absolute tolerance for the nonzero elements of `B`\nand is only used if `h2norm = false` for controllability tests of unstable eigenvalues. \nThe keyword argument `atolinf` is the absolute tolerance for the gain of `G(λ)` at  `λ = ∞`. \nThe used default value is `atolinf = 0`. \nThe default relative tolerance is `n*ϵ`, where `ϵ` is the working machine epsilon \nand `n` is the order of the system `sys`. The keyword argument `atol` can be used \nto simultaneously set `atol1 = atol`, `atol2 = atol` and `atol3 = atol`. \n\"\"\"   \nfunction gl2norm(sys::DescriptorStateSpace{T}; h2norm::Bool = false, fast::Bool = true, \n                 offset::Real = sqrt(eps(float(real(T)))), atol::Real = zero(float(real(T))), atol1::Real = atol, atol2::Real = atol, atol3::Real = atol, \n                 atolinf::Real = atol, rtol::Real = sys.nx*eps(real(float(one(T))))*iszero(min(atol1,atol2)))  where T \n    \n    T1 = T <: BlasFloat ? T : promote_type(Float64,T) \n    disc = !iszero(sys.Ts)\n       \n    if  sys.E == I\n        # quick return for a non-dynamic system or continuous-time system with nonzero D\n        size(sys.A,1) == 0 && (return disc ? norm(sys.D) : (norm(sys.D,Inf) <= atolinf ? zero(real(T1)) : Inf))\n        disc || norm(sys.D,Inf) <= atolinf || (return Inf)\n        if h2norm\n            # compute the H2-norm\n            # reduce the system to Schur coordinate form\n            SF = schur(sys.A)\n            # check stability\n            ((disc && maximum(abs.(SF.values)) >= 1-offset) || (!disc && maximum(real(SF.values)) >= -offset)) && (return Inf)\n            R = plyaps(SF.T', (sys.C*SF.Z)'; disc = disc)\n            return disc ? norm([R*(SF.Z'*sys.B); sys.D]) : norm(R*(SF.Z'*sys.B))\n        else\n            # compute the L2-norm\n            try\n              sys = grcfid(sys, offset = offset, atol1 = atol1, atol3 = atol3, rtol = rtol)[1]\n              R = plyaps(sys.A', sys.C'; disc = disc)\n              return disc ? norm([R*sys.B; sys.D]) : norm(R*sys.B)\n            catch\n              return Inf\n            end\n        end\n     else\n        n = sys.nx\n        # eliminate uncontrollable and unobservable infinite eigenvalues and non-dynamic modes if possible\n        if rcond(sys.E) < n*eps(float(real(T1)))\n           sys = gir(sys, finite = false, noseig = true, fast = fast, atol1 = atol1, atol2 = atol2, rtol = rtol)\n           # check properness for a continuous-time system\n           disc || rcond(sys.E) >= n*eps(float(real(T1))) || (return Inf)\n        end\n        size(sys.A,1) == 0 && (return disc ? norm(sys.D) : (norm(sys.D,Inf) <= atolinf ? zero(real(T1)) : Inf))\n        disc || norm(sys.D) <= atolinf || (return Inf)\n        if h2norm\n            # compute the H2-norm\n            # reduce the system to generalized Schur coordinate form\n            SF = schur(sys.A,sys.E)\n            # check stability\n            ((disc && maximum(abs.(SF.values)) >= 1-offset) || (!disc && maximum(real(SF.values)) >= -offset)) && (return Inf)\n            R = plyaps(SF.S', SF.T', (sys.C*SF.Z)'; disc = disc)\n            return disc ? norm([R*(SF.Q'*sys.B); sys.D]) : norm(R*(SF.Q'*sys.B))\n        else\n            # compute the L2-norm\n            try\n              sys = glcfid(sys, offset = offset, mininf = true, atol1 = atol1, atol2 = atol2, atol3 = atol3, rtol = rtol)[1]\n              R = plyaps(sys.A', sys.E', sys.C'; disc = disc)\n              return disc ? norm([R*sys.B; sys.D]) : norm(R*sys.B)\n            catch\n              return Inf\n            end\n        end\n    end\n\n    # end GL2NORM\nend\n\"\"\"\n    ghinfnorm(sys, rtolinf = 0.001, fast = true, offset = sqrt(ϵ), atol = 0, atol1 = atol, atol2 = atol, rtol = n*ϵ) -> (hinfnorm, fpeak)\n\nCompute for a descriptor system `sys = (A-λE,B,C,D)` with the transfer function  matrix `G(λ)` \nthe `H∞` norm `hinfnorm` (i.e.,  the peak gain of `G(λ)`) and \nthe corresponding peak frequency `fpeak`, where the peak gain is achieved. \nThe `H∞` norm is infinite if the _pole pencil_ `A-λE` has unstable zeros (i.e., `sys` has unstable poles). \nTo check the stability, the eigenvalues of the pencil `A-λE` must have real parts less than `-β` for a continuous-time system or \nhave moduli less than `1-β` for a discrete-time system, where `β` is the stability domain boundary offset.\nThe offset  `β` to be used can be specified via the keyword parameter `offset = β`. \nThe default value used for `β` is `sqrt(ϵ)`, where `ϵ` is the working machine precision. \n\nThe keyword argument `rtolinf` specifies the relative accuracy for the computed infinity norm. \nThe  default value used for `rtolinf` is `0.001`.\n\nFor a continuous-time system `sys` with `E` singular, a reduced order realization is determined first, without \nuncontrollable and unobservable nonzero finite and infinite eigenvalues of the corresponding pole pencil. \nThe rank determinations in the performed reductions\nare based on rank revealing QR-decompositions with column pivoting \nif `fast = true` or the more reliable SVD-decompositions if `fast = false`.   \n\nThe keyword arguments `atol1`, `atol2`, and `rtol`, specify, respectively, the absolute tolerance for the \nnonzero elements of matrices `A`, `B`, `C`, `D`, the absolute tolerance for the nonzero elements of `E`,  \nand the relative tolerance for the nonzero elements of `A`, `B`, `C`, `D` and `E`. \nThe default relative tolerance is `n*ϵ`, where `ϵ` is the working machine epsilon  \nand `n` is the order of the system `sys`. \nThe keyword argument `atol` can be used to simultaneously set `atol1 = atol` and `atol2 = atol`. \n\"\"\"   \nfunction ghinfnorm(sys::DescriptorStateSpace{T}; rtolinf::Real = float(real(T))(0.001), fast::Bool = true, offset::Real = sqrt(eps(float(real(T)))), \n                   atol::Real = zero(float(real(T))), atol1::Real = atol, atol2::Real = atol,  \n                   rtol::Real = (size(sys.A,1)*eps(real(float(one(T)))))*iszero(min(atol1,atol2)))  where T \n    return glinfnorm(sys; hinfnorm = true, rtolinf = rtolinf, fast = fast, offset = offset, atol1 = atol1, atol2 = atol2, rtol = rtol)\n\nend\n\"\"\"\n    glinfnorm(sys, hinfnorm = false, rtolinf = 0.001, fast = true, offset = sqrt(ϵ), atol = 0, atol1 = atol, atol2 = atol, rtol = n*ϵ) -> (linfnorm, fpeak)\n\nCompute for a descriptor system `sys = (A-λE,B,C,D)` with the transfer function  matrix `G(λ)` \nthe `L∞` norm `linfnorm` (i.e.,  the peak gain of `G(λ)`) and \nthe corresponding peak frequency `fpeak`, where the peak gain is achieved. \nThe `L∞` norm is infinite if the _pole pencil_ `A-λE` has\nzeros (i.e., poles) on the stability domain boundary, i.e., on the extended imaginary axis, in the continuous-time case, \nor on the unit circle, in the discrete-time case.  \nTo check the lack of poles on the stability domain boundary, the eigenvalues of the pencil `A-λE` \nmust not have real parts in the interval `[-β,β]` for a continuous-time system or \nmust not have moduli within the interval `[1-β,1+β]` for a discrete-time system, where `β` is the stability domain boundary offset.  \nThe offset  `β` to be used can be specified via the keyword parameter `offset = β`. \nThe default value used for `β` is `sqrt(ϵ)`, where `ϵ` is the working machine precision. \n\nThe keyword argument `rtolinf` specifies the relative accuracy for the computed infinity norm. \nThe  default value used for `rtolinf` is `0.001`.\n\nIf `hinfnorm = true`, the `H∞` norm is computed. In this case, the stability of the zeros of `A-λE` is additionally checked and \nthe `H∞` norm is infinite for an unstable system.\nTo check the stability, the eigenvalues of the pencil `A-λE` must have real parts less than `-β` for a continuous-time system or \nhave moduli less than `1-β` for a discrete-time system.\n\nFor a continuous-time system `sys` with `E` singular, a reduced order realization is determined first, without \nuncontrollable and unobservable nonzero finite and infinite eigenvalues of the corresponding pole pencil. \nThe rank determinations in the performed reductions\nare based on rank revealing QR-decompositions with column pivoting \nif `fast = true` or the more reliable SVD-decompositions if `fast = false`.   \n\nThe keyword arguments `atol1`, `atol2`, and `rtol`, specify, respectively, the absolute tolerance for the \nnonzero elements of matrices `A`, `B`, `C`, `D`, the absolute tolerance for the nonzero elements of `E`,  \nand the relative tolerance for the nonzero elements of `A`, `B`, `C`, `D` and `E`. \nThe default relative tolerance is `n*ϵ`, where `ϵ` is the working machine epsilon  \nand `n` is the order of the system `sys`. \nThe keyword argument `atol` can be used to simultaneously set `atol1 = atol` and `atol2 = atol`. \n\"\"\"   \nfunction glinfnorm(sys::DescriptorStateSpace{T}; hinfnorm::Bool = false, rtolinf::Real = float(real(T))(0.001), fast::Bool = true, \n                   offset::Real = sqrt(eps(float(real(T)))), atol::Real = zero(float(real(T))), atol1::Real = atol, atol2::Real = atol,  \n                   rtol::Real = sys.nx*eps(real(float(one(T))))*iszero(min(atol1,atol2)))  where T \n    \n    T1 = T <: BlasFloat ? T : promote_type(Float64,T) \n    ZERO = real(T1)(0)\n\n    # detect zero case\n    # iszero(sys, atol1 = atol1, atol2 = atol2, rtol = rtol) && (return ZERO, ZERO)\n\n    # quick exit for zero dimensions  \n    (sys.nu == 0 || sys.ny == 0) && (return ZERO, ZERO)\n\n    # quick exit in constant case  \n    sys.nx == 0 && (return opnorm(sys.D), ZERO)\n\n    β = abs(offset)\n    Ts = abs(sys.Ts)\n    disc = !iszero(Ts)\n    complx = T1 <: Complex\n\n    # eliminate simple infinite eigenvalues in the continuous-time case with singular E\n    if disc || sys.E == I || rcond(sys.E) >= sys.nx*eps(float(real(T1)))\n       A, E, B, C, D = dssdata(T1,sys)\n    else\n       A, E, B, C, D = dssdata(gir(sys, fast = fast, finite = false, noseig = true, atol1 = atol1, atol2 = atol2, rtol = rtol))\n    end\n\n    n = size(A,1)\n\n    # quick exit in constant case  \n    n == 0 && (return opnorm(D), real(T1)(0))\n\n\n    # check properness in continuous-time case\n    disc || E == I || rcond(E) >= n*eps(float(real(T1))) || (return Inf, Inf)\n    \n    # check for poles on the boundary of the stability domain\n    E == I ? ft = eigvals(A) : ft = eigvals(A,E); ft = ft[isfinite.(ft)]\n    if disc\n        hinfnorm && any(abs.(ft) .> 1-β) && (return Inf, NaN)\n        for i = 1:length(ft)\n            abs(ft[i]) >= 1-β && abs(ft[i]) <= 1+β && (return Inf, complx ? imag(log(complex(ft[i]))/Ts) : abs(log(complex(ft[i]))/Ts))\n        end\n    else\n        hinfnorm && any(real.(ft) .> -β) && (return Inf, NaN)\n        for i = 1:length(ft)\n            real(ft[i]) >= -β && real(ft[i]) <= β && (return Inf, complx ? imag(ft[i]) : abs(imag(ft[i])))\n        end\n    end\n    \n    # compute L∞-norm according to system type\n    disc ? (return norminfd(A, E, B, C, D, ft, Ts, rtolinf)) : \n           (return norminfc(A, E, B, C, D, ft, rtolinf))\n    # end GLINFNORM\nend\nfunction norminfc(a, e, b, c, d, ft0, tol)\n\n   T = eltype(a)\n   TR = real(T)\n   ny, nu = size(d)\n   min(ny, nu) == 0 && (return TR(0), TR(0))\n   \n   # Continuous-time L∞ norm computation\n   # It is assumed that A-λE has no eigenvalues on the extended imaginary axis\n\n   # Tolerance for jw-axis mode detection\n   compl = T <: Complex\n   epsm = eps(TR)\n   toljw1 = 100 * epsm;       # for simple roots\n   toljw2 = 10 * sqrt(epsm);  # for double root\n   \n   # Problem dimensions\n   nx = size(a,1)\n   desc = e != I\n   # reduce to complex Hessenberg form\n   ac, ec, bc, cc, dc = chess(a, e, b, c, d)\n    \n   # Build a new vector TESTFRQ of test frequencies containing the peaking\n   # frequency for each mode (or an approximation thereof for non-resonant modes).\n   # Add frequency w = 0 and set GMIN = || D || and FPEAK to infinity\n   # ar2 = abs.(real(ft0));  # magnitudes of real parts of test frequencies\n   w0 = abs.(ft0);         # fundamental frequencies\n    \n   #  ikeep = (imag.(ft0) .>= 0) .& ( w0 .> 0)\n   #  offset2 = max.(0.25,max.(1 .- 2 .*(ar2[ikeep]./w0[ikeep]).^2))\n   #  temp = w0[ikeep].*sqrt.(offset2)\n   #  compl ? testfrq = [-temp; [0]; temp] : testfrq = [[0]; temp]\n   compl ? testfrq = [-w0; [0]; w0] : testfrq = [[0]; w0]\n   \n   gmin = opnorm(d)\n   fpeak = Inf\n\n   # Compute lower estimate GMIN as max. gain over the selected frequencies\n   for i = 1:length(testfrq)\n      w = testfrq[i];\n      bct = copy(bc)\n      desc ? ldiv!(UpperHessenberg(ac-(im*w)*ec),bct) : ldiv!(ac,bct,shift = -im*w)\n      gw = opnorm(dc-cc*bct)\n      gw > gmin && (gmin = gw;  fpeak = w)\n   end\n   gmin == 0 && (return TR(0), TR(0))\n \n   # modified gamma iterations (Bruinsma-Steinbuch algorithm) start:\n   iter = 1;\n   while iter < 30\n      # Test if G = (1+TOL)*GMIN qualifies as upper bound\n      g = (1+tol) * gmin;\n      # Compute finite eigenvalues of Hamiltonian pencil \n      # deflate nu+ny simple infinite eigenvalues\n      h1 = [g*I d; d' g*I; zeros(T,nx,ny) b ; c' zeros(T,nx,nu)]\n      h2 = [c zeros(T,ny,nx) ; zeros(T,nu,nx) -b'; a zeros(T,nx,nx) ; zeros(T,nx,nx) -a']\n      j2 = [zeros(T,ny+nu,2*nx); e zeros(T,nx,nx) ; zeros(T,nx,nx) e']\n      _, tau = LinearAlgebra.LAPACK.geqrf!(h1)\n      compl ? tran = 'C' : tran = 'T'\n      LinearAlgebra.LAPACK.ormqr!('L',tran,h1,tau,h2)\n      LinearAlgebra.LAPACK.ormqr!('L',tran,h1,tau,j2)\n      i2 = ny+nu+1:ny+nu+2*nx\n      heigs = eigvals!(view(h2,i2,:),view(j2,i2,:))\n \n      mag = abs.(heigs);\n      # Detect jw-axis modes.  Test is based on a round-off level of\n      # eps*rho(H) resulting in worst-case\n      # perturbations of order sqrt(eps*rho(H)) on the real part\n      # of poles of multiplicity two (typical as g->norm(sys,inf))\n      #jweig = heigs(abs(real(heigs)) < toljw2*(1 .+ mag)+toljw1*max(mag));\n      jweig = heigs[abs.(real(heigs)) .< toljw2*(1 .+ mag) .+ toljw1*mag];\n   \n      # Compute frequencies where gain G is attained and\n      # generate new test frequencies\n      ws = imag(jweig);\n      #ws = unique(max.(epsm,ws[ws.> 0]))\n      compl ? ws = unique(sort(ws)) : ws = unique(sort(max.(epsm,ws[ws.> 0])))\n      lws0 = length(ws);\n      if lws0 == 0\n         # No jw-axis eigenvalues for G = GMIN*(1+TOL): we're done\n         return gmin, fpeak\n      else\n         lws0 == 1 && (ws = [ws;ws]) # correct pairing\n         lws = length(ws);\n      end\n            \n      # Form the vector of mid-points and compute\n      # gain at new test frequencies\n      gmin0 = gmin;   # save current lower bound\n      #ws = sqrt.(ws[1:lws-1].*ws[2:lws])\n      #ws = (ws[1:lws-1].+ ws[2:lws])/2\n      # Compute lower estimate GMIN as max. gain over the selected frequencies\n      for i = 1:lws-1\n          w = (ws[i]+ws[i+1])/2\n          bct = copy(bc)\n          desc ? ldiv!(UpperHessenberg(ac-(im*w)*ec),bct) : ldiv!(ac,bct,shift = -im*w)\n          gw = opnorm(dc-cc*bct)\n          gw > gmin && (gmin = gw;  fpeak = w)\n      end\n \n      # If lower bound has not improved, exit (safeguard against undetected\n      # jw-axis modes of Hamiltonian matrix)\n      (lws0 < 2 || gmin < gmin0*(1+tol/10)) && (return gmin, fpeak)\n      iter += 1\n   end #while  \nend  \nfunction norminfd(a, e, b, c, d, ft0, Ts, tol)\n\n   T = eltype(a)\n   TR = real(T)\n   ny, nu = size(d)\n   min(ny, nu) == 0 && (return TR(0), TR(0))\n\n   # Discrete-time L∞ norm computation\n   # It is assumed that A-λE has no eigenvalues on the unit circle\n\n   # Tolerance for detection of unit circle modes\n   compl = T <: Complex\n   epsm = eps(TR)\n   toluc1 = 100 * epsm       # for simple roots\n   toluc2 = 10 * sqrt(epsm)  # for double root\n   \n   # Problem dimensions\n   nx = size(a,1);\n   ny, nu = size(d)\n   desc = e != I\n   # reduce to complex Hessenberg form\n   ac, ec, bc, cc, dc = chess(a, e, b, c, d)\n   \n   # Build a new vector TESTFRQ of test frequencies containing the peaking\n   # frequency for each mode (or an approximation thereof for non-resonant modes).\n   sr = log.(complex(ft0[(ft0 .!= 0) .& (abs.(ft0) .<= pi/Ts)]));   # equivalent jw-axis modes\n   #sr = ft0[(ft0 .!= 0) .& (abs.(ft0) .<= pi/Ts)];   # equivalent jw-axis modes\n   # asr2 = abs.(real(sr))   # magnitude of real parts\n   w0 = abs.(sr);           # fundamental frequencies\n\n   # ikeep = (imag.(sr) .>= 0) .& ( w0 .> 0)\n   # testfrq = w0[ikeep].*sqrt.(max.(0.25,1 .- 2 .*(asr2[ikeep]./w0[ikeep]).^2))\n   compl ? testfrq = [-w0; [0]; w0] : testfrq = [[0]; w0]\n   \n   # Back to unit circle, and add z = exp(0) and z = exp(pi)\n   testz = [exp.(im*testfrq); [-1] ]\n  \n   gmin = 0\n   fpeak = 0\n   \n   # Compute lower estimate GMIN as max. gain over the selected frequencies\n   for i = 1:length(testz)\n      z = testz[i]\n      bct = copy(bc)\n      desc ? ldiv!(UpperHessenberg(ac-z*ec),bct) : ldiv!(ac,bct,shift = -z)\n      gw = opnorm(dc-cc*bct)\n      gw > gmin && (gmin = gw;  compl ? fpeak = angle(z) : fpeak = abs(angle(z)))\n   end\n   gmin == 0 && (return TR(0), TR(0))\n\n   # Modified gamma iterations (Bruinsma-Steinbuch algorithm) starts:\n   iter = 1;\n   while iter < 30\n      # Test if G = (1+TOL)*GMIN qualifies as upper bound\n      g = (1+tol) * gmin;\n      # Compute the finite eigenvalues of the symplectic pencil\n      # deflate nu+ny simple infinite eigenvalues\n      h1 = [a zeros(T,nx,nx+ny) b; zeros(T,nx,nx) e' zeros(nx,ny+nu)]\n      h2 = [c zeros(T,ny,nx) g*I d; zeros(T,nu,nx) b' d' g*I]\n      j1 = [e zeros(T,nx,nx+ny+nu); zeros(T,nx,nx) a' c' zeros(T,nx,nu) ]\n      _, tau = LinearAlgebra.LAPACK.gerqf!(h2)\n      compl ? tran = 'C' : tran = 'T'\n      LinearAlgebra.LAPACK.ormrq!('R',tran,h2,tau,h1)\n      LinearAlgebra.LAPACK.ormrq!('R',tran,h2,tau,j1)\n      i1 = 1:(2*nx)\n      heigs = eigvals!(view(h1,:,i1),view(j1,:,i1))\n      heigs =  heigs[abs.(heigs) .< 1/toluc2]\n\n      # Detect unit-circle eigenvalues\n      mag = abs.(heigs)\n      uceig = heigs[abs.(1 .- mag) .< toluc2 .+ toluc1*mag]\n   \n      # Compute frequencies where gain G is attained and\n      # generate new test frequencies\n      ang = sort(angle.(uceig));\n      ang = compl ? unique(ang) : unique(max.(epsm,ang[ang .> 0]))\n      lan0 = length(ang);\n      if lan0 == 0\n         # No unit-circle eigenvalues for G = GMIN*(1+TOL): we're done\n         return gmin, fpeak/Ts\n       else\n         lan0 == 1 && (ang = [ang;ang])   # correct pairing\n         lan = length(ang)\n      end\n   \n      # Form the vector of mid-points and compute\n      # gain at new test frequencies\n      gmin0 = gmin;   # save current lower bound\n      #testz = exp.(im*((ang[1:lan-1]+ang[2:lan])/2))\n      # Compute lower estimate GMIN as max. gain over the selected frequencies\n      for i = 1:lan-1\n         #z = testz[i]\n         z = exp(im*((ang[i]+ang[i+1])/2))\n         bct = copy(bc)\n         desc ? ldiv!(UpperHessenberg(ac-z*ec),bct) : ldiv!(ac,bct,shift = -z)\n         gw = opnorm(dc-cc*bct)\n         gw > gmin && (gmin = gw;  compl ? fpeak = angle(z) : fpeak = abs(angle(z)))\n      end\n    \n      # If lower bound has not improved, exit (safeguard against undetected\n      # unit-circle eigenvalues).\n      (lan0 < 2 || gmin < gmin0*(1+tol/10)) && (return gmin, fpeak/Ts)\n      iter += 1\n   end\nend  \n \n\"\"\"   \n    gnugap(sys1, sys2; freq = ω, rtolinf = 0.00001, fast = true, offset = sqrt(ϵ), \n           atol = 0, atol1 = atol, atol2 = atol, rtol = n*ϵ) -> (nugapdist, fpeak)\n\nCompute the ν-gap distance `nugapdist` between two descriptor systems `sys1 = (A1-λE1,B1,C1,D1)` and \n`sys2 = (A2-λE2,B2,C2,D2)` and the corresponding frequency `fpeak` (in rad/TimeUnit), where the ν-gap \ndistance achieves its peak value. \n\nIf `freq = missing`, the resulting `nugapdist` satisfies `0 <= nugapdist <= 1`. \nThe value `nugapdist = 1` results, if the winding number is different of zero in which case `fpeak = []`. \n\nIf `freq = ω`, where `ω` is a given vector of real frequency values, the resulting `nugapdist` is a vector \nof pointwise ν-gap distances of the dimension of `ω`, whose components satisfies `0 <= maximum(nugapdist) <= 1`. \nIn this case, `fpeak` is the frequency for which the pointwise distance achieves its peak value. \nAll components of `nugapdist` are set to 1 if the winding number is different of zero in which case `fpeak = []`.\n\nThe stability boundary offset,  `β`, to be used to assess the finite zeros which belong to the\nboundary of the stability domain can be specified via the keyword parameter `offset = β`.\nAccordingly, for a continuous-time system, these are the finite zeros having \nreal parts within the interval `[-β,β]`, while for a discrete-time system, \nthese are the finite zeros having moduli within the interval `[1-β,1+β]`. \nThe default value used for `β` is `sqrt(ϵ)`, where `ϵ` is the working machine precision. \n\nPencil reduction algorithms are employed to compute range and coimage spaces \nwhich perform rank decisions based on rank \nrevealing QR-decompositions with column pivoting \nif `fast = true` or the more reliable SVD-decompositions if `fast = false`.\n\nThe keyword arguments `atol1`, `atol2` and `rtol`, specify, respectively, \nthe absolute tolerance for the nonzero elements of `A1`, `A2`, `B1`, `B2`, `C1`, `C2`, `D1` and `D2`,\nthe absolute tolerance for the nonzero elements of `E1` and `E2`,   \nand the relative tolerance for the nonzero elements of all above matrices.  \nThe default relative tolerance is `n*ϵ`, where `ϵ` is the working machine epsilon \nand `n` is the maximum of the orders of the systems `sys1` and `sys2`. \nThe keyword argument `atol` can be used to simultaneously set `atol1 = atol`, `atol2 = atol`. \n\nThe keyword argument `rtolinf` specifies the relative accuracy to be used \nto compute the ν-gap as the infinity norm of the relevant system according to [1]. \nThe default value used for `rtolinf` is `0.00001`.\n   \n_Method:_ The evaluation of ν-gap uses the definition proposed in [1],\nextended to generalized LTI (descriptor) systems. The computation of winding number\nis based on enhancements covering zeros on the boundary of the \nstability domain and infinite zeros.\n\n_References:_\n\n[1] G. Vinnicombe. Uncertainty and feedback: H∞ loop-shaping and the ν-gap metric. \n    Imperial College Press, London, 2001. \n\"\"\"   \nfunction gnugap(sys1::DescriptorStateSpace{T1},sys2::DescriptorStateSpace{T2}; freq::Union{AbstractVector{<:Real},Real,Missing} = missing,\n         fast::Bool = true, offset::Real = sqrt(eps(float(real(T1)))), rtolinf::Real = float(real(T1))(0.00001), \n         atol::Real = zero(real(T1)), atol1::Real = atol, atol2::Real = atol,  \n         rtol::Real = max(sys1.nx,sys2.nx)*eps(real(float(one(T1))))*iszero(min(atol1,atol2)))  where {T1,T2} \n   T = promote_type(T1,T2)\n   T <: BlasFloat || (T = promote_type(T,Float64))  \n   ONE = one(real(T))\n   \n   Ts = promote_Ts(sys1.Ts,sys2.Ts)\n   disc = (Ts != 0)\n   \n   ismissing(freq) ? nf = 0 : nf = length(freq)\n   \n   p, m = size(sys1)\n   (p,m) == size(sys2) || error(\"The systems sys1 and sys2 must have the same number of inputs and outputs\")\n      \n   # compute the normalized coprime factorizations R1 = [N1;M1] and R2 = [N2;M2] \n   R1 = grange([sys1;I], zeros = \"none\", inner = true, atol1 = atol1, atol2 = atol2, rtol = rtol, \n               offset = offset, fast = fast)[1]; \n   R2 = grange([sys2;I], zeros = \"none\", inner = true, atol1 = atol1, atol2 = atol2, rtol = rtol, \n                offset = offset, fast = fast)[1]; \n   \n   # check conditions on det(N2'*N1+M2'*M1) = det(R2'*R1)\n   syst = gir(R2'*R1, atol1 = atol1, atol2 = atol2, rtol = rtol, fast = fast);  \n   infoz = gzeroinfo(syst, offset = offset, atol1 = atol1, atol2 = atol2, rtol = rtol, fast = fast)[2];\n   # check invertibility and presence of zeros on the boundary of stability domain\n   if infoz.nrank != order(syst)+m || infoz.nfsbz > 0\n      return nf == 0 ? ONE : ones(nf), Float64[]\n   end\n   \n   # evaluate winding number \n   infop = gpoleinfo(syst,offset = offset, atol1 = atol1, atol2 = atol2, rtol = rtol, fast = fast)[2];\n   wno = infoz.nfuz - infop.nfuev + infoz.niz - infop.nip\n   # check condition on winding number \n   if wno != 0\n      # nonzero winding number\n      return nf == 0 ? ONE : ones(nf), Float64[]\n   end\n   \n   # compute the normalized left coprime factorization L1 = [ N1t M1t]\n   L1 = gcrange([sys1 I], zeros = \"none\", coinner = true, atol1 = atol1, atol2 = atol2, rtol = rtol, \n                offset = offset, fast = fast)[1]; \n   # compute the underlying system to compute the nu-gap distance \n   # using the definition of Vinnicombe\n   syst = L1*[zeros(T,m,p) -I; I zeros(T,p,m)]*R2\n   if ismissing(freq)\n      # compute the ν-gap using the definition of Vinnicombe\n      nugapdist, fpeak = ghinfnorm(syst; rtolinf = rtolinf, fast = fast, offset = offset, \n                                  atol1 = atol1, atol2 = atol2, rtol = rtol) \n   else \n      H = freqresp(syst,freq); nugapdist = zeros(nf)\n      tmax = opnorm(H[:,:,1]); fpeak = freq[1]\n      nugapdist[1] = tmax\n      for i = 2:nf\n          temp = opnorm(H[:,:,i])\n          nugapdist[i] = temp;\n          if tmax < temp\n             tmax = temp; fpeak = freq[i]\n          end\n      end          \n   end\n   return nugapdist, fpeak \nend\n   \n   ", "meta": {"hexsha": "028a3bb3087bdad798937df67ca36695945b2205", "size": 59744, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/analysis.jl", "max_stars_repo_name": "andreasvarga/DescriptorSystems.jl", "max_stars_repo_head_hexsha": "2745eda6a24a2334d82a81fb9c4247438cf4473d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-10-06T23:28:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T02:26:16.000Z", "max_issues_repo_path": "src/analysis.jl", "max_issues_repo_name": "andreasvarga/DescriptorSystems.jl", "max_issues_repo_head_hexsha": "2745eda6a24a2334d82a81fb9c4247438cf4473d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-01-21T13:10:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T15:48:54.000Z", "max_forks_repo_path": "src/analysis.jl", "max_forks_repo_name": "andreasvarga/DescriptorSystems.jl", "max_forks_repo_head_hexsha": "2745eda6a24a2334d82a81fb9c4247438cf4473d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-26T04:53:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T13:15:48.000Z", "avg_line_length": 53.9205776173, "max_line_length": 155, "alphanum_fraction": 0.647328602, "num_tokens": 17955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7634166654215966}}
{"text": "using LinearAlgebra\n\nexport translate, scale, rotate\n\nimport Base: position\n\n\"\"\"\n    translate(v::Vec2D) -> Matrix\nCreates a 3x3 matrix that would translate points\nin the `v` direction.\n\"\"\"\nfunction translate(v::Union{Vec2D, Point})\n    A = zeros(3, 3) + I\n\tA[1, 3] = v.x\n\tA[2, 3] = v.y\n\t\n    A\nend\n\n\n\"\"\"\n    scale(x, y) -> Matrix\nCreate 3x3 matrix for scaling in object. If you multiply\nthis with a collection of points making up a shape, it\nhas the effect of scaling that shape.\n\"\"\"\nfunction scale(x::Number, y::Number)\n    A = zeros(3, 3)\n    A[1, 1] = x\n    A[2, 2] = y\n    A[3, 3] = 0.0 \n    A\nend\n\n\"\"\"\n    rotate(angle) -> Matrix\nCreate a 3x3 matrix that can be used to rotate a shape\nmade up of multiple points along its axis. Each point\nwill have to be a column in matrix.\n\"\"\"\nfunction rotate(angle::Number)\n    A = zeros(3, 3) + I\n    sine   = sin(angle)\n    cosine = cos(angle)\n    \n\tA[1, 1] = cosine\n\tA[1, 2] = -sine\n\tA[2, 1] = sine\n\tA[2, 2] = cosine\n    \n    A     \nend\n", "meta": {"hexsha": "1c566b859231008bb6cdea186b0933ebb81e1b1b", "size": 982, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geometry/transform.jl", "max_stars_repo_name": "ordovician/BitBlit2D.jl", "max_stars_repo_head_hexsha": "cb2402a5a7fd9110331507cbf72855c9a7cf6a4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-22T19:50:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-22T19:50:14.000Z", "max_issues_repo_path": "src/geometry/transform.jl", "max_issues_repo_name": "ordovician/BitBlit2D.jl", "max_issues_repo_head_hexsha": "cb2402a5a7fd9110331507cbf72855c9a7cf6a4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geometry/transform.jl", "max_forks_repo_name": "ordovician/BitBlit2D.jl", "max_forks_repo_head_hexsha": "cb2402a5a7fd9110331507cbf72855c9a7cf6a4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5283018868, "max_line_length": 56, "alphanum_fraction": 0.616089613, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561676667174, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.7633920058327491}}
{"text": "function score(x, y)\n\tdistance = sqrt(x^2 + y^2)\n\tinner_radius = 1\n\tmiddle_radius = 5\n\touter_radius = 10\n\tif distance <= inner_radius\n\t\treturn 10\n\telseif distance <= middle_radius\n\t\treturn 5\n\telseif distance <= outer_radius\n\t\treturn 1\n\telse\n\t\treturn 0\n    end\nend\n", "meta": {"hexsha": "6a0e155f46b01f70afd3e1588df9131b88fa383c", "size": 264, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/darts/darts.jl", "max_stars_repo_name": "tamireinhorn/exercism", "max_stars_repo_head_hexsha": "3ca78b262ad590b67c75c5d1cd83db02bc2d1e6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/darts/darts.jl", "max_issues_repo_name": "tamireinhorn/exercism", "max_issues_repo_head_hexsha": "3ca78b262ad590b67c75c5d1cd83db02bc2d1e6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-12-18T16:31:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-18T16:33:33.000Z", "max_forks_repo_path": "julia/darts/darts.jl", "max_forks_repo_name": "tamireinhorn/Exercism", "max_forks_repo_head_hexsha": "3a3d5744e88ab4457df4e6ac20d772d8c50c43da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.5, "max_line_length": 33, "alphanum_fraction": 0.7045454545, "num_tokens": 83, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561721629776, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.7633920045507464}}
{"text": "# # Foundations of Bilevel Programming: Example 5\n# This example is from the book _Foundations of Bilevel Programming_ by Stephan\n# Dempe, Chapter 8.1, Page 255. [url](https://www.springer.com/gp/book/9781402006319)\n\n# Here, only the second level is described\n\n# Model of the problem\n# First level\n# ```math\n# \\min 0,\\\\\n# ```\n# Second level\n# ```math\n# \\min x,\\\\\n# \\notag s.t.\\\\\n# x+y \\leq 2,\\\\\n# x-y \\leq 2,\\\\\n# -4x+5y \\leq 10,\\\\\n# -4x-5y \\leq 10,\\\\\n# ```\n\n\nusing BilevelJuMP\nusing Ipopt\nusing JuMP\nusing Test\n\nmodel = BilevelModel(Ipopt.Optimizer, mode = BilevelJuMP.ProductMode(1e-9))\n\n# Global variables\natol = 1e-3\n\n# First we need to create all of the variables in the upper and lower problems:\n\n# Upper level variables\n@variable(Upper(model), y, start = 0)\n\n#Lower level variables\n@variable(Lower(model), x, start = 0)\n\n# Then we can add the objective and constraints of the upper problem:\n\n# Upper level objecive function\n@objective(Upper(model), Min, 0 * y + 0)\n\n\n# Followed by the objective and constraints of the lower problem:\n\n# Lower objective function\n@objective(Lower(model), Min, x)\n\n# Lower constraints\n@constraint(Lower(model), x + y <= 2)\n@constraint(Lower(model), x - y <= 2)\n@constraint(Lower(model), -4x + 5y <= 10)\n@constraint(Lower(model), -4x - 5y <= 10)\n\n# Initial Starting conditions  #src\n\n# Now we can solve the problem and verify the solution again that reported by\n# Dempe.\n\noptimize!(model)\nprimal_status(model)\ntermination_status(model)\n", "meta": {"hexsha": "73e266d32774e172f3a3a2b1f5346a9d2ed47e0a", "size": 1471, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/FOBP_example5.jl", "max_stars_repo_name": "NLaws/BilevelJuMP.jl", "max_stars_repo_head_hexsha": "e8d0020b0634fcd49d795a042b29e13d4751b60d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 58, "max_stars_repo_stars_event_min_datetime": "2019-11-11T02:06:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:10:36.000Z", "max_issues_repo_path": "docs/src/examples/FOBP_example5.jl", "max_issues_repo_name": "NLaws/BilevelJuMP.jl", "max_issues_repo_head_hexsha": "e8d0020b0634fcd49d795a042b29e13d4751b60d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 146, "max_issues_repo_issues_event_min_datetime": "2019-11-08T22:26:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T00:41:16.000Z", "max_forks_repo_path": "docs/src/examples/FOBP_example5.jl", "max_forks_repo_name": "NLaws/BilevelJuMP.jl", "max_forks_repo_head_hexsha": "e8d0020b0634fcd49d795a042b29e13d4751b60d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2019-12-02T03:41:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-02T01:37:55.000Z", "avg_line_length": 22.2878787879, "max_line_length": 85, "alphanum_fraction": 0.7029231815, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7633884657075515}}
{"text": "const woods = let res_init=zeros(7), jac_init=zeros(7,4), x_init=[-3.0, -1.0, -3.0, -1.0]\n\n    function res(x, r)\n        r[1] = 10.0 * (x[2] - x[1]^2 )\n        r[2] = 1.0 - x[1]\n        r[3] = sqrt(90.0) * (x[4] - x[3]^2 )\n        r[4] = 1.0 - x[3]\n        r[5] = sqrt(9.9) * (x[2] + x[4] - 2.0)\n        t = sqrt(0.2)\n        r[6] = t * (x[2] - 1.0)\n        r[7] = t * (x[4] - 1.0)\n        return r\n    end\n\n    function jac(x, jac)\n        jac[:] .= 0.0\n        jac[1, 1] = -20x[1]\n        jac[1, 2] = 10.0\n        jac[2, 1] = -1.0\n        jac[3, 4] = sqrt(90.0)\n        jac[3, 3] = -2x[3] * jac[3, 4]\n        jac[4, 3] = -1.0\n        jac[5, 2] = sqrt(9.9)\n        jac[5, 4] = jac[5, 2]\n        jac[6, 2] = sqrt(0.2)\n        jac[7, 4] = jac[6, 2]\n        return jac\n    end\n\n    f(;scale=1, verbose=false, print_steps=false) = testone(\"woods\", res, jac,\n                                                   res_init, jac_init, x_init;\n                                                   scale=scale, verbose=verbose,\n                                                   print_steps=print_steps)\nend\n", "meta": {"hexsha": "c5e12328f7ca07fe365b4284ddd43a8ac5f35853", "size": 1096, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/optests/woods.jl", "max_stars_repo_name": "macd/NL2sol.jl", "max_stars_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-01-19T21:59:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T00:42:56.000Z", "max_issues_repo_path": "test/optests/woods.jl", "max_issues_repo_name": "macd/NL2sol.jl", "max_issues_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/optests/woods.jl", "max_forks_repo_name": "macd/NL2sol.jl", "max_forks_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3142857143, "max_line_length": 89, "alphanum_fraction": 0.3686131387, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.763388461799754}}
{"text": "\"\"\"\n    mcse(x::AbstractVector{<:Real}; method::Symbol=:imse, kwargs...)\n\nCompute the Monte Carlo standard error (MCSE) of samples `x`.\nThe optional argument `method` describes how the errors are estimated. Possible options are:\n\n- `:bm` for batch means [^Glynn1991]\n- `:imse` initial monotone sequence estimator [^Geyer1992]\n- `:ipse` initial positive sequence estimator [^Geyer1992]\n\n[^Glynn1991]: Glynn, P. W., & Whitt, W. (1991). Estimating the asymptotic variance with batch means. Operations Research Letters, 10(8), 431-435.\n\n[^Geyer1992]: Geyer, C. J. (1992). Practical Markov Chain Monte Carlo. Statistical Science, 473-483.\n\"\"\"\nfunction mcse(x::AbstractVector{<:Real}; method::Symbol=:imse, kwargs...)\n    return if method === :bm\n        mcse_bm(x; kwargs...)\n    elseif method === :imse\n        mcse_imse(x)\n    elseif method === :ipse\n        mcse_ipse(x)\n    else\n        throw(ArgumentError(\"unsupported MCSE method $method\"))\n    end\nend\n\nfunction mcse_bm(x::AbstractVector{<:Real}; size::Int=floor(Int, sqrt(length(x))))\n    n = length(x)\n    m = min(div(n, 2), size)\n    m == size || @warn \"batch size was reduced to $m\"\n    mcse = StatsBase.sem(Statistics.mean(@view(x[(i + 1):(i + m)])) for i in 0:m:(n - m))\n    return mcse\nend\n\nfunction mcse_imse(x::AbstractVector{<:Real})\n    n = length(x)\n    lags = [0, 1]\n    ghat = StatsBase.autocov(x, lags)\n    Ghat = sum(ghat)\n    @inbounds value = Ghat + ghat[2]\n    @inbounds for i in 2:2:(n - 2)\n        lags[1] = i\n        lags[2] = i + 1\n        StatsBase.autocov!(ghat, x, lags)\n        Ghat = min(Ghat, sum(ghat))\n        Ghat > 0 || break\n        value += 2 * Ghat\n    end\n\n    mcse = sqrt(value / n)\n\n    return mcse\nend\n\nfunction mcse_ipse(x::AbstractVector{<:Real})\n    n = length(x)\n    lags = [0, 1]\n    ghat = StatsBase.autocov(x, lags)\n    @inbounds value = ghat[1] + 2 * ghat[2]\n    @inbounds for i in 2:2:(n - 2)\n        lags[1] = i\n        lags[2] = i + 1\n        StatsBase.autocov!(ghat, x, lags)\n        Ghat = sum(ghat)\n        Ghat > 0 || break\n        value += 2 * Ghat\n    end\n\n    mcse = sqrt(value / n)\n\n    return mcse\nend\n", "meta": {"hexsha": "063ab8b4c77e1193dc0baab4fad01ddd1d50756e", "size": 2114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mcse.jl", "max_stars_repo_name": "rikhuijzer/InferenceDiagnostics.jl", "max_stars_repo_head_hexsha": "13ae88c7ff481d9831b3b09cbe0052658caf4a60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-05-18T09:19:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-04T21:10:32.000Z", "max_issues_repo_path": "src/mcse.jl", "max_issues_repo_name": "rikhuijzer/InferenceDiagnostics.jl", "max_issues_repo_head_hexsha": "13ae88c7ff481d9831b3b09cbe0052658caf4a60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2021-05-18T12:31:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-07T01:07:04.000Z", "max_forks_repo_path": "src/mcse.jl", "max_forks_repo_name": "rikhuijzer/InferenceDiagnostics.jl", "max_forks_repo_head_hexsha": "13ae88c7ff481d9831b3b09cbe0052658caf4a60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-06-21T19:26:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-04T18:49:03.000Z", "avg_line_length": 28.9589041096, "max_line_length": 145, "alphanum_fraction": 0.6021759697, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.763388461799754}}
{"text": "function normAm(A,m)::Real\n    #NORMAM   Estimate of 1-norm of power of matrix.\n    #   NORMAM(A,m) estimates norm(A^m,1).\n    #   If A has nonnegative elements the estimate is exact.\n    #   [C,MV] = NORMAM(A,m) returns the estimate C and the number MV of\n    #   matrix-vector products computed involving A or A^*.\n\n    #   Reference: A. H. Al-Mohy and N. J. Higham, A New Scaling and Squaring\n    #   Algorithm for the Matrix Exponential, SIAM J. Matrix Anal. Appl. 31(3):\n    #   970-989, 2009.\n\n    #   Awad H. Al-Mohy and Nicholas J. Higham, September 7, 2010.\n\n    t = 2; # Number of columns used by NORMEST1.\n\n    n = size(A, 1);\n    if hasmethod(opnorm, Tuple{typeof(A), typeof(1)})\n        if eltype(A) <: Real\n            if sum(A .< 0) == 0 # for positive matrices only\n                e = ones(n,1)\n                f = similar(e)\n                for j=1:m\n                    mul!(f, A, e)\n                    copyto!(e, f)\n                end\n                return norm(e, Inf)\n            end\n        end\n    end\n    return norm1est(A, m, t)\nend\n", "meta": {"hexsha": "926260f4fc6c5438652d50702b8ae48bd8cb47f7", "size": 1062, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/normAm.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ExpmV.jl-a3781d3e-2c8e-5597-8496-846d69e16182", "max_stars_repo_head_hexsha": "2d5b2b489a4c69847f7ca7bb7c3d86deba1c0bb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-05-15T15:08:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T00:40:20.000Z", "max_issues_repo_path": "src/normAm.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ExpmV.jl-a3781d3e-2c8e-5597-8496-846d69e16182", "max_issues_repo_head_hexsha": "2d5b2b489a4c69847f7ca7bb7c3d86deba1c0bb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-07-17T05:55:13.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-20T21:38:45.000Z", "max_forks_repo_path": "src/normAm.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ExpmV.jl-a3781d3e-2c8e-5597-8496-846d69e16182", "max_forks_repo_head_hexsha": "2d5b2b489a4c69847f7ca7bb7c3d86deba1c0bb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-07-17T02:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T00:40:22.000Z", "avg_line_length": 33.1875, "max_line_length": 79, "alphanum_fraction": 0.5338983051, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7633616993491544}}
{"text": "## discretize!\n\n\"\"\"\n    discretize!(a::AbstractArray{<:Real}, n::Integer=30)\n\nSort `a`, divide its values into (roughly) `n` groups corresponding to\nequal-length intervals, and replace each value in a group by the `mean`\nof this group. This can be useful to transform samples from a continuous\ndistribution in order to plot an histogram.\n\n# Examples\n```julia-repl\njulia> pmf(discretize!(randn(1000), 10))\npmf for [-3.2977741401356235, -2.804784333001702, -2.804784333001702, -2.804784333001702, -2.0873488466856744, -2.0873488466856744, -2.0873488466856744, -2.0873488466856744, -2.0873488466856744, -2.0873488466856744  …  2.0792314833569865, 2.0792314833569865, 2.0792314833569865, 2.0792314833569865, 2.0792314833569865, 2.9112746357518313, 2.9112746357518313, 2.9112746357518313, 2.9112746357518313, 2.9112746357518313] with support of length 10:\n  -3.29777  => 0.001\n  -2.80478  => 0.003\n  -2.08735  => 0.026\n  -1.36503  => 0.104\n  -0.679956 => 0.237\n  0.0211377 => 0.273\n  0.748744  => 0.232\n  1.46951   => 0.101\n  2.07923   => 0.018\n  2.91127   => 0.005\n```\n\"\"\"\nfunction discretize!(a::AbstractArray{<:Real}, n::Integer=30)\n    require_one_based_indexing(a)\n    length(a) < 2n && return a\n    n = min(n, length(a) ÷ 2)\n    sort!(a)\n    w = (a[end] - a[1]) / n\n    i = 1\n    for x in LinRange(a[1], a[end], n)\n        j = searchsortedlast(a, x)\n        y = mean(view(a, i:j))\n        a[i:j] .= y\n        i = j+1\n    end\n    a\nend\n", "meta": {"hexsha": "5b2b3b5686c79026d63f4cc030d9469a6f7b3833", "size": 1436, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/util.jl", "max_stars_repo_name": "rfourquet/DistributionsLite.jl", "max_stars_repo_head_hexsha": "494f825e0dc4ef69cf9ea51b73bbe5b93474b3aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-24T00:08:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T00:08:03.000Z", "max_issues_repo_path": "src/util.jl", "max_issues_repo_name": "JuliaRandom/RandomMonad.jl", "max_issues_repo_head_hexsha": "494f825e0dc4ef69cf9ea51b73bbe5b93474b3aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util.jl", "max_forks_repo_name": "JuliaRandom/RandomMonad.jl", "max_forks_repo_head_hexsha": "494f825e0dc4ef69cf9ea51b73bbe5b93474b3aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1904761905, "max_line_length": 445, "alphanum_fraction": 0.6608635097, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.763361693550074}}
{"text": "function DE_mutation(population, i::Int, F::Float64, strategy::Symbol=:rand1, best_ind=0)\n\n    N = length(population)\n    # select participats\n    r1 = rand(1:N)\n    while r1 == i\n        r1 = rand(1:N)\n    end\n\n    r2 = rand(1:N)\n    while r2 == i || r1 == r2\n        r2 = rand(1:N)\n    end\n\n    r3 = rand(1:N)\n    while r3 == i || r3 == r1 || r3 == r2\n        r3 = rand(1:N)\n    end\n\n    x = population[i].x\n    a = population[r1].x\n    b = population[r2].x\n    c = population[r3].x\n\n    # strategy is selected here\n    if strategy == :rand1\n        # DE/rand/1\n        u = a + F * (b - c)\n    elseif strategy == :best1\n        # DE/best/1\n        xBest = population[argbest(population)].x\n        u = xBest + F * (b - c)\n    elseif strategy == :rand2\n        # DE/rand/2\n\n        r4 = rand(1:N)\n        while r4 == i || r4 == r1 || r4 == r2 || r4 == r3\n            r4 = rand(1:N)\n        end\n\n        r5 = rand(1:N)\n        while r5 == i || r5 == r1 || r5 == r2 || r5 == r3 || r5 == r4\n            r5 = rand(1:N)\n        end\n\n        d = population[r4].x\n        ee = population[r5].x\n\n        u = ee + F * (a - b + c - d)\n    elseif strategy == :randToBest1\n        # DE/rand-to-best/1\n        xBest = population[argbest(population)].x\n        u = x + F * (xBest - x + a - b)\n    elseif strategy == :best2\n        # DE/best/2\n        r4 = rand(1:N)\n        best_ind = argbest(population)\n        xBest = population[best_ind].x\n        while r4 == i || r4 == r1 || r4 == r2 || r4 == r3 || r4 == best_ind\n            r4 = rand(1:N)\n        end\n        d = population[r4].x\n        u = xBest + F * (a - b + c - d)\n    else\n        error(\"Unknown strategy \" * string(strategy))\n    end\n\n    return u\nend\n\nfunction DE_crossover(x, u, CR)\n    D = length(x)\n    # binomial crossover\n    v = zeros(D)\n    j_rand = rand(1:D)\n\n    # binomial crossover\n    for j = 1:D\n        if rand() < CR || j == j_rand\n            v[j] = u[j]\n        else\n            v[j] = x[j]\n        end\n    end\n\n    return v\nend\n\n", "meta": {"hexsha": "6f857340c8f7783b6488b5d4503e8bb9467f6ef0", "size": 2000, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algorithms/DE/crossover_mutation.jl", "max_stars_repo_name": "pitmonticone/Metaheuristics.jl", "max_stars_repo_head_hexsha": "d429ff51cc921e7166d44e1c15d69f9041b8a0cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algorithms/DE/crossover_mutation.jl", "max_issues_repo_name": "pitmonticone/Metaheuristics.jl", "max_issues_repo_head_hexsha": "d429ff51cc921e7166d44e1c15d69f9041b8a0cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithms/DE/crossover_mutation.jl", "max_forks_repo_name": "pitmonticone/Metaheuristics.jl", "max_forks_repo_head_hexsha": "d429ff51cc921e7166d44e1c15d69f9041b8a0cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4719101124, "max_line_length": 89, "alphanum_fraction": 0.4645, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7633616932726213}}
{"text": "using NNlib: logsoftmax, logσ\n\n# Cost functions\n\nmse(ŷ, y) = sum((ŷ .- y).^2)/length(y)\n\nfunction crossentropy(ŷ::AbstractVecOrMat, y::AbstractVecOrMat; weight = 1)\n  @fix -sum(y .* log.(ŷ) .* weight) / size(y, 2)\nend\n\n@deprecate logloss(x, y) crossentropy(x, y)\n\nfunction logitcrossentropy(logŷ::AbstractVecOrMat, y::AbstractVecOrMat; weight = 1)\n  return -sum(y .* logsoftmax(logŷ) .* weight) / size(y, 2)\nend\n\n\"\"\"\n    binarycrossentropy(ŷ, y)\n\nReturn `-y*log(ŷ) - (1-y)*log(1-ŷ)`.\n\n    julia> binarycrossentropy.(σ.([-1.1491, 0.8619, 0.3127]), [1, 1, 0.])\n    3-element Array{Float64,1}:\n    1.4244\n    0.352317\n    0.86167\n\"\"\"\nbinarycrossentropy(ŷ, y) = -y*log(ŷ) - (1 - y)*log(1 - ŷ)\n\n\"\"\"\n    logitbinarycrossentropy(logŷ, y)\n\n`logitbinarycrossentropy(logŷ, y)` is mathematically equivalent to `binarycrossentropy(σ(logŷ), y)`\nbut it is more numerically stable.\n\n    julia> logitbinarycrossentropy.([-1.1491, 0.8619, 0.3127], [1, 1, 0.])\n    3-element Array{Float64,1}:\n     1.4244\n     0.352317\n     0.86167\n\"\"\"\nlogitbinarycrossentropy(logŷ, y) = (1 - y)*logŷ - logσ(logŷ)\n\n\"\"\"\n    normalise(x::AbstractVecOrMat)\n\nNormalise each column of `x` to mean 0 and standard deviation 1.\n\"\"\"\nfunction normalise(x::AbstractVecOrMat)\n  μ′ = mean(x, 1)\n  σ′ = std(x, 1, mean = μ′)\n  return (x .- μ′) ./ σ′\nend\n", "meta": {"hexsha": "ccd4fe4c8d3d55a3fcd190153f320f3640cba670", "size": 1317, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/layers/stateless.jl", "max_stars_repo_name": "hellcoderz/Flux.jl", "max_stars_repo_head_hexsha": "aea1e73cdede14a579670a59859d7f2654824e8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/layers/stateless.jl", "max_issues_repo_name": "hellcoderz/Flux.jl", "max_issues_repo_head_hexsha": "aea1e73cdede14a579670a59859d7f2654824e8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/layers/stateless.jl", "max_forks_repo_name": "hellcoderz/Flux.jl", "max_forks_repo_head_hexsha": "aea1e73cdede14a579670a59859d7f2654824e8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3888888889, "max_line_length": 99, "alphanum_fraction": 0.6347760061, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620468, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.7633616801730259}}
{"text": "function ahp_RI(n::Int64)::Float64\n    # First index is n = 3\n    # RI[3] = 0.58\n    # RI[4] = 0.90\n    ris = [0.58, 0.90, 1.12, 1.24, 1.32,\n          1.41, 1.45, 1.49, 1.51, 1.53,\n          1.56, 1.57, 1.59]\n    if n < 3 \n        return 0\n    elseif n <= 15\n        return ris[n - 2]\n    else\n        return ris |> last\n    end\n\nend\n\n\nfunction ahp_consistency(comparisonMatrix::DataFrame)::AHPConsistencyResult\n  \n    n, m = size(comparisonMatrix)\n  \n    csums = colsums(comparisonMatrix)\n    normalizedComparisonMatrix = zeros(Float64, n, n)\n\n    for i in 1:n\n        for j in 1:n\n            normalizedComparisonMatrix[i, j] = comparisonMatrix[i, j] / csums[j]\n        end\n    end\n\n    priority_vector = rowmeans(normalizedComparisonMatrix)\n    mcomparisonMatrix = convert(Array{Float64,2}, comparisonMatrix)\n\n    consistency_vector = mcomparisonMatrix * priority_vector\n\n    pc_matrix = consistency_vector ./ priority_vector\n\n    lambda_max = sum(pc_matrix) / n\n\n    CI  = (lambda_max - n) / (n - 1)\n    ri  = ahp_RI(n)\n    CR  = CI / ri\n\n    isConsistent = (CR < 0.1)\n\n    result = AHPConsistencyResult(\n        comparisonMatrix,\n        makeDecisionMatrix(normalizedComparisonMatrix),\n        consistency_vector,\n        priority_vector,\n        pc_matrix,\n        lambda_max,\n        CI,\n        ri,\n        CR,\n        isConsistent\n    )\n\n    return result\n\nend\n\n\n\n\nfunction ahp(comparisonMatrixList::Array{DataFrame,1}, criteriaComparisonMatrix::DataFrame)::AHPResult\n    \n    result_list = map(ahp_consistency, comparisonMatrixList)\n\n    n = length(result_list)\n\n    ncriteria, _ = size(criteriaComparisonMatrix)\n\n    ncandidates, _ = size(comparisonMatrixList[1])\n\n    decision_matrix = zeros(Float64, ncandidates, ncriteria)\n\n    @inbounds for i in 1:n\n        decision_matrix[:,i] = result_list[i].priority\n    end\n\n    criteria_consistency = ahp_consistency(criteriaComparisonMatrix)\n\n    weights = criteria_consistency.priority\n\n    decision_matrix_df = makeDecisionMatrix(decision_matrix)\n    ordering_result =  decision_matrix * weights\n    \n    bestIndex = sortperm(ordering_result) |> last\n\n    result = AHPResult(\n        comparisonMatrixList,\n        criteriaComparisonMatrix,\n        criteria_consistency,\n        decision_matrix_df,\n        ordering_result,\n        weights,\n        bestIndex\n    )\n\n    return result\nend\n\n", "meta": {"hexsha": "956e62acc9d6a685e92ed68a5b7b96f4a6740361", "size": 2346, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ahp.jl", "max_stars_repo_name": "ersagunkuruca/JMcDM", "max_stars_repo_head_hexsha": "d7caeb1b039e022ca0959355fba00465795a2d70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ahp.jl", "max_issues_repo_name": "ersagunkuruca/JMcDM", "max_issues_repo_head_hexsha": "d7caeb1b039e022ca0959355fba00465795a2d70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ahp.jl", "max_forks_repo_name": "ersagunkuruca/JMcDM", "max_forks_repo_head_hexsha": "d7caeb1b039e022ca0959355fba00465795a2d70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3428571429, "max_line_length": 102, "alphanum_fraction": 0.6427962489, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159683, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7633451992257216}}
{"text": "#######################################################\n# Constrained to unconstrained distribution bijectors #\n#######################################################\nstruct TruncatedBijector{T} <: Bijector{0}\n    lb::T\n    ub::T\nend\n\nfunction (b::TruncatedBijector)(x::Real)\n    a, b = b.lb, b.ub\n    lowerbounded, upperbounded = isfinite(a), isfinite(b)\n    if lowerbounded && upperbounded\n        return StatsFuns.logit((x - a) / (b - a))\n    elseif lowerbounded\n        return log(x - a)\n    elseif upperbounded\n        return log(b - x)\n    else\n        return x\n    end \nend\n\nfunction (b::TruncatedBijector)(x::AbstractVector{<:Real})\n    a, b = b.lb, b.ub\n    lowerbounded, upperbounded = isfinite(a), isfinite(b)\n    if lowerbounded && upperbounded\n        return @. StatsFuns.logit((x - a) / (b - a))\n    elseif lowerbounded\n        return log.(x - a)\n    elseif upperbounded\n        return log.(b - x)\n    else\n        return x\n    end\nend\n\nfunction (ib::Inversed{<:TruncatedBijector})(y::Real)\n    a, b = ib.orig.lb, ib.orig.ub\n    lowerbounded, upperbounded = isfinite(a), isfinite(b)\n    if lowerbounded && upperbounded\n        return (b - a) * StatsFuns.logistic(y) + a\n    elseif lowerbounded\n        return exp(y) + a\n    elseif upperbounded\n        return b - exp(y)\n    else\n        return y\n    end\nend\n\nfunction (ib::Inversed{<:TruncatedBijector})(y::AbstractVector{<:Real})\n    a, b = ib.orig.lb, ib.orig.ub\n    lowerbounded, upperbounded = isfinite(a), isfinite(b)\n    if lowerbounded && upperbounded\n        return @. (b - a) * StatsFuns.logistic(y) + a\n    elseif lowerbounded\n        return @. exp(y) + a\n    elseif upperbounded\n        return @. b - exp(y)\n    else\n        return y\n    end\nend\n\nfunction logabsdetjac(b::TruncatedBijector, x::Real)\n    a, b = b.lb, b.ub\n    lowerbounded, upperbounded = isfinite(a), isfinite(b)\n    if lowerbounded && upperbounded\n        return - log((x - a) * (b - x) / (b - a))\n    elseif lowerbounded\n        return - log(x - a)\n    elseif upperbounded\n        return - log(b - x)\n    else\n        return zero(x)\n    end\nend\n\nfunction logabsdetjac(b::TruncatedBijector, x::AbstractVector{<:Real})\n    a, b = b.lb, b.ub\n    lowerbounded, upperbounded = isfinite(a), isfinite(b)\n    if lowerbounded && upperbounded\n        return @. - log((x - a) * (b - x) / (b - a))\n    elseif lowerbounded\n        return @. - log(x - a)\n    elseif upperbounded\n        return @. - log(b - x)\n    else\n        return zero(x)\n    end\nend\n\n", "meta": {"hexsha": "9cfb0a60a53290ef5b88e23d397f292b6af02f89", "size": 2486, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bijectors/truncated.jl", "max_stars_repo_name": "devmotion/Bijectors.jl", "max_stars_repo_head_hexsha": "dc736c86cbf397acb78e57d6cc4e00dc6aafff16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bijectors/truncated.jl", "max_issues_repo_name": "devmotion/Bijectors.jl", "max_issues_repo_head_hexsha": "dc736c86cbf397acb78e57d6cc4e00dc6aafff16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bijectors/truncated.jl", "max_forks_repo_name": "devmotion/Bijectors.jl", "max_forks_repo_head_hexsha": "dc736c86cbf397acb78e57d6cc4e00dc6aafff16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7311827957, "max_line_length": 71, "alphanum_fraction": 0.5732099759, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109728022221, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.763345198080196}}
{"text": "function gausschebyshev(n::Int, kind::Int=1)\n    # GAUSS-CHEBYSHEV NODES AND WEIGHTS.\n\n    # Use known explicit formulas. Complexity O(n).\n    if kind == 1\n        # Gauss-ChebyshevT quadrature, i.e., w(x) = 1/sqrt(1-x^2)\n        [cos((2 * k - 1) * π / (2 * n)) for k = n:-1:1], fill(π / n, n)\n    elseif kind == 2\n        # Gauss-ChebyshevU quadrature, i.e., w(x) = sqrt(1-x^2)\n        ([cos(k * π / (n + 1)) for k = n:-1:1],\n         [π/(n + 1) * sin(k / (n + 1) * π)^2 for k = n:-1:1])\n    elseif kind == 3\n        # Gauss-ChebyshevV quadrature, i.e., w(x) = sqrt((1+x)/(1-x))\n        ([cos((k - .5) * π / (n + .5)) for k = n:-1:1],\n         [2π / (n + .5) * cos((k - .5) * π / (2 * (n + .5)))^2 for k = n:-1:1])\n    elseif kind == 4\n        # Gauss-ChebyshevW quadrature, i.e., w(x) = sqrt((1-x)/(1+x))\n        ([cos(k * π / (n + .5)) for k = n:-1:1],\n         [2π / (n + .5) * sin(k * π / (2 * (n + .5)))^2 for k = n:-1:1])\n    else\n        throw(ArgumentError(\"Chebyshev kind should be 1, 2, 3, or 4\"))\n    end\nend\n", "meta": {"hexsha": "04eb848de1171288611b5a8e1a43e8148d5194ce", "size": 1021, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gausschebyshev.jl", "max_stars_repo_name": "MikaelSlevinsky/FastGaussQuadrature.jl", "max_stars_repo_head_hexsha": "d1f1c6a089096eafc830e0ea8e34fb234a097347", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-07-31T23:02:17.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-31T23:02:17.000Z", "max_issues_repo_path": "src/gausschebyshev.jl", "max_issues_repo_name": "JuliaPackageMirrors/FastGaussQuadrature.jl", "max_issues_repo_head_hexsha": "ada3e7d2c56cebded0a99744f607845974454c74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gausschebyshev.jl", "max_forks_repo_name": "JuliaPackageMirrors/FastGaussQuadrature.jl", "max_forks_repo_head_hexsha": "ada3e7d2c56cebded0a99744f607845974454c74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.5416666667, "max_line_length": 79, "alphanum_fraction": 0.4564152791, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068041, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7633451947306298}}
{"text": "\"\"\"\nShapey value using Harsanyi dividends\n\"\"\"\nfunction fₛⁱ(G::Game, i::Int)\n    ∑(Δₕ(G, T) / length(T) for T in subsets(G.N) if i ∈ T)\nend\n\n\"\"\"\nShapey value using permutations\n\"\"\"\nfunction fₛ(G::SimpleGame)\n    N = length(G.N)\n    Nσ = factorial(N)\n\n    shapley = zeros(N)\n\n    for n in 1:Nσ\n        σ = nthperm(G.N, n)\n        \n        for (i, s) in enumerate(σ)\n            shapley[s] += G.v(σ[1:i]) - G.v(σ[1:i - 1])\n        end\n        \n    end\n\n    return shapley ./ Nσ\nend\nfₛ(G::GraphGame) = fₛ(graphtoMyerson(G))\n\n\"\"\"\nMyerson solution, it is equivalent to the Shapley value of the Myerson game.\n\"\"\"\nμ(G::SimpleGame, L::Array{NTuple{2,Int}}) = fₛ(GraphGame(G.N, G.v, L))", "meta": {"hexsha": "9ccce1365069f8bd4a9e9797b1f6f68a0febb349", "size": 676, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solutions/shapley.jl", "max_stars_repo_name": "NoFishLikeIan/CoordinationGames.jl", "max_stars_repo_head_hexsha": "fa1939552482c785af3cbe3e3a80dd714180d115", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-03-20T18:53:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T22:40:56.000Z", "max_issues_repo_path": "src/solutions/shapley.jl", "max_issues_repo_name": "NoFishLikeIan/CoordinationGames.jl", "max_issues_repo_head_hexsha": "fa1939552482c785af3cbe3e3a80dd714180d115", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-23T16:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T10:15:39.000Z", "max_forks_repo_path": "src/solutions/shapley.jl", "max_forks_repo_name": "NoFishLikeIan/CoordinationGames.jl", "max_forks_repo_head_hexsha": "fa1939552482c785af3cbe3e3a80dd714180d115", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-26T18:15:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T18:15:24.000Z", "avg_line_length": 20.4848484848, "max_line_length": 76, "alphanum_fraction": 0.5680473373, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109756113862, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7633451936199085}}
{"text": "\"\"\" Computes divided differences of tabulated data n points x and \n    for each of the n points, up to m derivatives  dy\n\"\"\"\nfunction DividedDifference2(x,dy)  # generate array of divided differences\n    n, m = size(dy)                # n data points, m derivatives (0 to m-1)\n    dd = zeros(typeof(x[1]),n*m,n*m)               # matrix of divided differences\n    z = zeros(typeof(x[1]),n*m) \n    k=1;\n    for i = 1:n                    # n data points\n        for j = 1:m                # m derivatives (0 to m-1) at each point\n            k = (i-1)*m + j        # row index\n            z[k] = x[i]      \n            dd[k,1] = dy[i,1]      # 0th divided difference in first column\n            for l = 2:k            # column index for the remaining columns\n                if dd[k,l-1] == dd[k-1,l-1]  # left and top-left neighbors are repeated\n                    if l<=m\n                        dd[k,l] = dy[i,l] / factorial(l-1)\n                    else dd[k,l] = big(0.0)\n                    end\n                else                       \n                    dd[k,l] = (dd[k,l-1] - dd[k-1,l-1]) / (z[k]-z[k-l+1])\n                end\n            end\n        end\n    end\n    return dd\nend\n\n", "meta": {"hexsha": "98f512874ad444faa26174803644a11352df1bb7", "size": 1194, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Local/DividedDifference2.jl", "max_stars_repo_name": "tmigot/OneDmin.jl", "max_stars_repo_head_hexsha": "b7e32ed1de5aae153907279171d71851751c7d6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-03T15:40:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T15:40:55.000Z", "max_issues_repo_path": "src/Local/DividedDifference2.jl", "max_issues_repo_name": "tmigot/OneDmin.jl", "max_issues_repo_head_hexsha": "b7e32ed1de5aae153907279171d71851751c7d6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-02T15:20:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-02T15:20:22.000Z", "max_forks_repo_path": "src/Local/DividedDifference2.jl", "max_forks_repo_name": "tmigot/OneDmin.jl", "max_forks_repo_head_hexsha": "b7e32ed1de5aae153907279171d71851751c7d6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-03T22:58:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-05T08:35:46.000Z", "avg_line_length": 41.1724137931, "max_line_length": 87, "alphanum_fraction": 0.445561139, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7633451925265892}}
{"text": "\"\"\"\nOLSFn\n\nRun the (first-stage) time-series regressions for the asset pricing model to obtain the alpha and betas for each test assets\n\nINPUT\n`Y': T x N matrix of dependent varaible\n`X': T x (K + 1) matrix with K explanatory variables and one intercept term\n`cov_method': method for calculating the variance-covariance matrix of the error terms:\n            - time iid: error terms are iid across time but cross-sectionally correlated\n            - iid: error terms are iiid both across time and assets\n            - NW: Newey-West covariance matrix with m lags\n            - HH: Hansen-Hodrick covariane matrix with m lags\n`m': number of lags for the Newey-West or Hansen-Hodrick covariance matrix\n\n\nOUTPUT\n`alpha': N x 1 vector of alphas of the test assets\n`beta': N x K matrix of the betas of the test assets. There are N test assets and K factors\n`resid': T x N matrix of the pricing errors\n`cov_resid': N x N matrix of covariance matrix of the pricing errors\n\"\"\"\n\n\nfunction OLSFn(Y, X, cov_method = \"time iid\", m = 0)\n    beta = (X' * X) \\ (X' * Y); # (K+1) x N\n    resid = Y - X * beta;\n    alpha = beta[1, :]; # alphas N x 1\n    beta = beta[2:end, :]'; # betas N x K\n\n    # Method of estimating the covariance matrix of residuals for OLS\n    if cov_method == \"time iid\" # iid across time but cross-sectionally correlated\n        cov_resid = cov(resid);\n    elseif cov_method == \"iid\" # iid\n        cov_resid = cov(resid);\n        cov_resid = diagm(diag(cov_resid));\n    elseif cov_method == \"NW\" # Newey-West\n        cov_resid = cov(resid);\n        for i = 1:m\n            w = 1 - i / (m + 1);\n            cov_resid = cov_resid + 2 * w * (1 / (T - 1 - i)) * resid[1:end - i, :]' * resid[1 + i:end, :];\n        end\n    elseif cov_method == \"HH\" # Hansen-Hodrick\n        cov_resid = cov(resid)\n        for i = 1:m\n            cov_resid = cov_resid + (2 / (T - 1 - i)) * resid[1:end - i, :]' * resid[1 + i:end, :];\n        end\n    end\n\n    return (alpha, beta, resid, cov_resid)\nend\n", "meta": {"hexsha": "2307985e9357df401f2b1e6d2c6fd7b80596681e", "size": 1988, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/OLSFn.jl", "max_stars_repo_name": "yingxiangli/Linear-Factor-Model-and-Random-Walk-Tests", "max_stars_repo_head_hexsha": "0d844c9e8b383b7239727379e11d7149144cfd63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-13T12:56:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-13T12:56:24.000Z", "max_issues_repo_path": "src/OLSFn.jl", "max_issues_repo_name": "yingxiangli/Linear-Factor-Model-and-Random-Walk-Tests", "max_issues_repo_head_hexsha": "0d844c9e8b383b7239727379e11d7149144cfd63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OLSFn.jl", "max_forks_repo_name": "yingxiangli/Linear-Factor-Model-and-Random-Walk-Tests", "max_forks_repo_head_hexsha": "0d844c9e8b383b7239727379e11d7149144cfd63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2307692308, "max_line_length": 124, "alphanum_fraction": 0.620221328, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787997, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7633276391021204}}
{"text": "using LinearAlgebra, Statistics, StatsBase, Plots; pyplot()\n\nn, N = 5, 10^6\nP = diagm(-1 => fill(1/3,n-1),\n           0 => fill(1/3,n),\n           1 => fill(1/3,n-1))\nP[1,n], P[n,1] = 1/3, 1/3\n\nA = UpperTriangular(ones(n,n))\nC = P*A\n\nfunction f1(x,u)\n    for xNew in 1:n\n        if u <= C[x+1,xNew]\n            return xNew-1\n        end\n    end\nend\n\nf2(x,xi) = mod(x + xi , n)\n\nfunction countTau(f,rnd)\n    t = 0\n    visits = fill(false,n)\n    state = 0\n    while sum(visits) < n\n        state = f(state,rnd())\n        visits[state+1] |= true\n        t += 1\n    end\n    return t-1\nend\n\ndata1 = [countTau(f1,rand) for _ in 1:N]\ndata2 = [countTau(f2,()->rand([-1,0,1]) ) for _ in 1:N]\nest1, est2 = mean(data1), mean(data2)\nc1, c2 = counts(data1)/N,counts(data2)/N\nprintln(\"Estimated mean value of tau using f1: \",est1)\nprintln(\"Estimated mean value of tau using f2: \",est2)\nprintln(\"\\nThe matrix P:\", P)\nscatter(4:33,c1[1:30], \n\tc=:blue, ms=5, msw=0, \n\tlabel=\"Transition probability matrix\")\nscatter!(4:33,c2[1:30], \n\tc=:red, ms=5, msw=0, shape=:cross, \n\tlabel=\"Stochastic recursive formula\", xlabel=\"Time\", ylabel=\"Probability\")", "meta": {"hexsha": "253bea293c367d0fcf0af68480ae9e7d9778da9d", "size": 1127, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "10_chapter/simpleMarkov.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "10_chapter/simpleMarkov.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "10_chapter/simpleMarkov.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 24.5, "max_line_length": 75, "alphanum_fraction": 0.5820763088, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7633276305651223}}
{"text": "export iCycle, iPath, iGrid, iKnight, iCube, iShift\n\n\"\"\"\n`iCycle(n::Int, simple::Bool=true)` creates an implicit graph that is\na cycle graph with `n` vertices `1` through `n`. When `simple`\nis `true`, the graph is undirected; when `false` it's a directed \ncycle `1 → 2 → 3 → ⋯ → n → 1`. \n\"\"\"\nfunction iCycle(n::Int, simple::Bool = true)::ImplicitGraph{Int}\n    if n < 3\n        error(\"Number of vertices must be at least 3\")\n    end\n\n    function N(v::Int)\n        a = mod1(v + 1, n)\n        b = mod1(v - 1, n)\n        if simple\n            return [b, a]\n        end\n        return [a]\n    end\n\n    has_vertex(v::Int) = 1 <= v <= n\n\n    return ImplicitGraph{Int}(has_vertex, N)\nend\n\n\"\"\"\n`iPath(simple::Bool=true)` creates an implicit graph that is \na path graph on the integers. If `simple` is `true` vertex `v` is \nhas an edge to `v-1` and `v+1`; otherwise, `v` has an edge only to \n`v+1`.\n\"\"\"\nfunction iPath(simple::Bool = true)::ImplicitGraph{Int}\n    yes(v::Int)::Bool = true\n\n    function N(v::Int)::Vector{Int}\n        if simple\n            return [v - 1, v + 1]\n        else\n            return [v + 1]\n        end\n    end\n    return ImplicitGraph{Int}(yes, N)\nend\n\n\n\"\"\"\n`iGrid()` returns an infinite two-dimensional grid graph. Vertices are \nof type `Tuple{Int,Int}`.\n\"\"\"\nfunction iGrid()::ImplicitGraph{Tuple{Int,Int}}\n    yes(v::Tuple{Int,Int})::Bool = true\n    function N(v::Tuple{Int,Int})::Vector{Tuple{Int,Int}}\n        a, b = v\n        return [(a, b - 1), (a, b + 1), (a - 1, b), (a + 1, b)]\n    end\n    return ImplicitGraph{Tuple{Int,Int}}(yes, N)\nend\n\n\"\"\"\n`iKnight()` returns the Knight's move graph on an infinite \nchessboard.\n\"\"\"\nfunction iKnight()::ImplicitGraph{Tuple{Int,Int}}\n    yes(v::Tuple{Int,Int})::Bool = true\n    function N(v::Tuple{Int,Int})::Vector{Tuple{Int,Int}}\n        a, b = v\n        neigh = [\n            (a + 1, b + 2),\n            (a + 1, b - 2),\n            (a + 2, b + 1),\n            (a + 2, b - 1),\n            (a - 1, b + 2),\n            (a - 1, b - 2),\n            (a - 2, b + 1),\n            (a - 2, b - 1),\n        ]\n        return neigh\n    end\n    return ImplicitGraph{Tuple{Int,Int}}(yes, N)\nend\n\n\"\"\"\n`iCube(d::Int)` creates an (implict) `d`-dimensional cube graph.\n\"\"\"\nfunction iCube(d::Int)::ImplicitGraph{String}\n    if d < 1\n        error(\"Dimension must be positive\")\n    end\n\n    function dvec_check(s::String)::Bool\n        if length(s) != d\n            return false\n        end\n        for i = 1:d\n            if s[i] ∉ \"01\"\n                return false\n            end\n        end\n        return true\n    end\n\n    function N(v::String)\n        result = Vector{String}(undef, d)\n        for i = 1:d\n            head = v[1:i-1]\n            c = v[i] == '0' ? \"1\" : \"0\"\n            tail = v[i+1:end]\n            result[i] = head * c * tail\n        end\n        return result\n    end\n\n    return ImplicitGraph{String}(dvec_check, N)\nend\n\n\n\nusing IterTools\n\"\"\"\n`iShift(alphabet,n)` creates an implicit shift digraph whose vertices \nare `n`-tuples of elements of `alphabet`.\n\"\"\"\nfunction iShift(alphabet, n::Int)::ImplicitGraph\n    elts = collect(distinct(alphabet))\n    T = eltype(elts)\n\n    function has_vertex(v)::Bool\n        for i = 1:n\n            if v[i] ∉ elts\n                return false\n            end\n        end\n        return true\n    end\n\n    function N(v)\n        base = v[2:end]\n        result = [(base..., j) for j in elts]\n        return result\n    end\n\n    return ImplicitGraph{NTuple{n,T}}(has_vertex, N)\nend\n", "meta": {"hexsha": "4e1cb29d47b0a307ee9ca43e102252d6be711e21", "size": 3483, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/iGraphs.jl", "max_stars_repo_name": "scheinerman/ImplicitGraphs.jl", "max_stars_repo_head_hexsha": "0cc9c163b88c13c99c1c636589dd1209e63310e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-02-03T22:09:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T00:31:06.000Z", "max_issues_repo_path": "src/iGraphs.jl", "max_issues_repo_name": "scheinerman/ImplicitGraphs.jl", "max_issues_repo_head_hexsha": "0cc9c163b88c13c99c1c636589dd1209e63310e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/iGraphs.jl", "max_forks_repo_name": "scheinerman/ImplicitGraphs.jl", "max_forks_repo_head_hexsha": "0cc9c163b88c13c99c1c636589dd1209e63310e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8561643836, "max_line_length": 71, "alphanum_fraction": 0.5311513063, "num_tokens": 1091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7633276285426184}}
{"text": "### wiener-time-series.jl\n#\n# Copyright (C) 2016 Mosè Giordano.\n#\n# Maintainer: Mosè Giordano <mose AT gnu DOT org>\n# Keywords: deconvolution, signal processing\n#\n# This file is a part of Deconvolution.jl.\n#\n# License is MIT \"Expat\".\n#\n### Commentary:\n#\n# This file produces an example image used in Deconvolution.jl documentation.\n#\n### Code:\n\nusing Random\n\nRandom.seed!(7)\n\nusing LombScargle, Deconvolution, Plots, Statistics, FFTW\nt = range(0, stop=10, length=1000) # observation times\nx = sinpi.(t) .* cos.(5t) - 1.5cospi.(t) .* sin.(2t) # the original signal\n\n# Gaussian blurring kernel\nkernel = exp.( - 10 .* (t .- 5).^2)  \nkernel ./= sum(kernel) # normalize kernel to sum of 1\nkernel = ifftshift(kernel) # move center to index pos 1\n\nn = rand(length(x)) # noise to be added\nnoise = 3 .* (n .- mean(n))\ny = x + noise # observed noisy signal\n# blurred and noise signal\ny_blurred = real(ifft(fft(kernel) .* fft(x))) + noise\n\n\n# Lomb-Scargle periodogram\np = lombscargle(t, y, maximum_frequency=2, samples_per_peak=10)\nplot(freqpower(p)...)\n\nm1 = LombScargle.model(t, y, findmaxfreq(p, [0, 0.5])[1]) # first model\nm2 = LombScargle.model(t, y, findmaxfreq(p, [0.5, 1])[1]) # second model\nm3 = LombScargle.model(t, y, findmaxfreq(p, [1, 1.5])[1]) # third model\n\nsignal = m1 + m2 + m3\npolished = wiener(y, signal, noise)\ndeblurred = wiener(y_blurred, signal, noise, kernel)\n\n# Plots \nplot(t, x, size=(900, 600), label=\"Original signal\", linewidth=2)\nplot!(t, y, label=\"Observed signal\")\nsavefig(\"time-series-observed.png\")\n\nplot(t, x, size=(900, 600), label=\"Original signal\", linewidth=2)\nplot!(t, y_blurred, label=\"Blurred signal\")\nsavefig(\"time-series-observed-blurred.png\")\n\nplot(t, x, size=(900, 600), label=\"Original signal\", linewidth=2)\nplot!(t, polished, label=\"Recovered with Wiener\")\nplot!(t, signal, label=\"Lomb–Scargle model\")\nsavefig(\"time-series-recovered.png\")\n\nplot(t, x, size=(900, 600), label=\"Original signal\", linewidth=2)\nplot!(t, deblurred, label=\"Deblurred with Wiener\")\nplot!(t, signal, label=\"Lomb–Scargle model\")\nsavefig(\"time-series-deblurred.png\")\n", "meta": {"hexsha": "8fe89c8546b74b952165bb74187a36626bb8f9cc", "size": 2076, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/wiener/time-series.jl", "max_stars_repo_name": "giordano/Deconvolution.jl", "max_stars_repo_head_hexsha": "4edc2adf4f468a2c400cfd318014ef736eb9c481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2016-09-09T15:13:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T11:31:10.000Z", "max_issues_repo_path": "doc/src/wiener/time-series.jl", "max_issues_repo_name": "roflmaostc/Deconvolution.jl", "max_issues_repo_head_hexsha": "e63127a84c43d6d29314154ca4e46b7b16da600a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2017-05-17T00:45:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-18T16:38:36.000Z", "max_forks_repo_path": "doc/src/wiener/time-series.jl", "max_forks_repo_name": "roflmaostc/Deconvolution.jl", "max_forks_repo_head_hexsha": "e63127a84c43d6d29314154ca4e46b7b16da600a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2016-09-24T04:34:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T03:28:43.000Z", "avg_line_length": 30.5294117647, "max_line_length": 77, "alphanum_fraction": 0.6926782274, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7633276253384726}}
{"text": "#== # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n#\n# Description\n#\n#   Functions to convert anomalies related to the orbit.\n#\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n#\n# References\n#\n#   [1] Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications.\n#       Microcosm Press, Hawthorn, CA, USA.\n#\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ==#\n\nexport M_to_E, M_to_f\nexport E_to_f, E_to_M\nexport f_to_E, f_to_M\n\n################################################################################\n#                              From Mean Anomaly\n################################################################################\n\n\"\"\"\n    M_to_E(e::T1, M::T2; kwargs...) where {T1, T2}\n\nCompute the eccentric anomaly (0,2π) \\\\[rad] given the eccentricity `e` and the\nmean anomaly `M` [rad].\n\nThis function uses the Newton-Raphson algorithm to solve the Kepler's equation.\n\n# Keywords\n\n- `tol::Union{Nothing, Number}`: Tolerance to accept the solution from\n    Newton-Raphson algorithm. If `tol` is `nothing`, then it will be\n    `eps(T)`, where `T` is a floating-point type obtained from the promotion of\n    `T1` and `T2`. (**Default** = `nothing`)\n- `max_iterations::Number`: Maximum number of iterations allowed for the\n    Newton-Raphson algorithm. If it is lower than 1, then it is set to 10.\n    (**Default** = 10)\n\"\"\"\n@inline function M_to_E(\n    e::T1,\n    M::T2;\n    max_iterations::Integer = 10,\n    tol::Union{Nothing, Number} = nothing\n) where {T1, T2}\n    T = float(promote_type(T1, T2))\n\n    # Compute the eccentric anomaly using the Newton-Raphson method.\n    # ==============================================================\n\n    # Make sure that M is in the interval [0,2π].\n    M = mod(M, T(2π))\n\n    # Initial guess.\n    #\n    # See [1, p. 75].\n    E = (M > π) ? M - e : M + e\n\n    sin_E, cos_E = sincos(E)\n\n    # Check the tolerance.\n    if tol === nothing\n        δ = eps(T)\n    else\n        δ = T(tol)\n    end\n\n    # Check the maximum number of iterations.\n    if max_iterations < 1\n        max_iterations = 10\n    end\n\n    # Newton-Raphson iterations.\n    for i in 1:max_iterations\n        abs(E - e*sin_E - M) ≤ δ && break\n        E = E - (E - e * sin_E - M) / (1 - e * cos_E)\n        sin_E, cos_E = sincos(E)\n    end\n\n    # Return the eccentric anomaly in the interval [0, 2π].\n    return mod(E, T(2π))\nend\n\n\"\"\"\n    M_to_f(e::T1, M::T2; kwargs...) where {T1, T2}\n\nCompute the true anomaly (0,2π) \\\\[rad] given the eccentricity `e` and the mean\nanomaly `M` [rad].\n\nThis function uses the Newton-Raphson algorithm to solve the Kepler's equation.\n\n# Keywords\n\n- `tol::Union{Nothing, Number}`: Tolerance to accept the solution from\n    Newton-Raphson algorithm. If `tol` is `nothing`, then it will be\n    `eps(T)`, where `T` is a floating-point type obtained from the promotion of\n    `T1` and `T2`. (**Default** = `nothing`)\n- `max_iterations::Number`: Maximum number of iterations allowed for the\n    Newton-Raphson algorithm. If it is lower than 1, then it is set to 10.\n    (**Default** = 10)\n\"\"\"\n@inline function M_to_f(e::T1, M::T2; kwargs...) where {T1, T2}\n    # Compute the eccentric anomaly.\n    E = M_to_E(e, M; kwargs...)\n\n    # Compute the true anomaly in the interval [0,2π].\n    return E_to_f(e, E)\nend\n\n################################################################################\n#                            From Eccentric Anomaly\n################################################################################\n\n\"\"\"\n    E_to_f(e::T1, E::T2) where {T1, T2}\n\nCompute the true anomaly (0,2π) \\\\[rad] given the eccentricity `e` and the\neccentric anomaly `E` [rad].\n\"\"\"\n@inline function E_to_f(e::T1, E::T2) where {T1, T2}\n    T = float(promote_type(T1, T2))\n\n    sin_Eo2, cos_Eo2 = sincos(E / 2)\n\n    # Compute the true anomaly in the interval [0, 2*π].\n    return mod(2atan(sqrt(1 + e) * sin_Eo2, sqrt(1 - e) * cos_Eo2), T(2π))\nend\n\n\"\"\"\n    E_to_M(e::T1, E::T2) where {T1, T2}\n\nCompute the mean anomaly (0,2π) \\\\[rad] given the eccentricity `e` and the\neccentric anomaly `E` [rad].\n\"\"\"\n@inline function E_to_M(e::T1, E::T2) where {T1, T2}\n    T = float(promote_type(T1, T2))\n    return mod(E - e * sin(E), T(2π))\nend\n\n################################################################################\n#                              From True Anomaly\n################################################################################\n\n\"\"\"\n    f_to_E(e::T1, f::T2) where {T1, T2}\n\nCompute the eccentric anomaly (0,2π) \\\\[rad] given the eccentricity `e` and\nthe true anomaly `f` [rad].\n\"\"\"\n@inline function f_to_E(e::T1, f::T2) where {T1, T2}\n    T = float(promote_type(T1, T2))\n    sin_fo2, cos_fo2 = sincos(f / 2)\n    return mod(2atan(sqrt(1 - e) * sin_fo2, sqrt(1 + e) * cos_fo2), T(2π) )\nend\n\n\"\"\"\n    f_to_M(e::T1, f::T2) where {T1, T2}\n\nCompute the mean anomaly (0,2π) \\\\[rad] given the eccentricity `e` and the\ntrue anomaly `f` [rad].\n\"\"\"\n@inline function f_to_M(e::T1, f::T2) where {T1, T2}\n    # Compute the eccentric anomaly.\n    E = f_to_E(e, f)\n\n    # Compute the true anomaly in the interval [0, 2π].\n    return E_to_M(e, E)\nend\n", "meta": {"hexsha": "dbecb1388e10f03439611347af1094709b7da6f6", "size": 5180, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/orbit/anomalies.jl", "max_stars_repo_name": "yashi/SatelliteToolbox.jl", "max_stars_repo_head_hexsha": "3a2bea103083f7fcf5729bcd1446cb23c7f23cd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 157, "max_stars_repo_stars_event_min_datetime": "2018-06-19T21:11:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:24:41.000Z", "max_issues_repo_path": "src/orbit/anomalies.jl", "max_issues_repo_name": "yashi/SatelliteToolbox.jl", "max_issues_repo_head_hexsha": "3a2bea103083f7fcf5729bcd1446cb23c7f23cd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 71, "max_issues_repo_issues_event_min_datetime": "2018-06-18T20:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T21:33:20.000Z", "max_forks_repo_path": "src/orbit/anomalies.jl", "max_forks_repo_name": "SatelliteToolbox/SatelliteToolbox.jl", "max_forks_repo_head_hexsha": "a1ad4b4331fda1ddfb78993e05fe947514cf483a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2018-10-02T02:42:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T20:36:51.000Z", "avg_line_length": 30.2923976608, "max_line_length": 80, "alphanum_fraction": 0.5223938224, "num_tokens": 1569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362858, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7633276200587217}}
{"text": "# One dimensional wave equation\nusing ConservationLawsDiffEq\nusing OrdinaryDiffEq\nconst CL = ConservationLawsDiffEq\n\nconst CFL = 0.45\nconst Tend = 1.0\nconst cc = 1.0\n\nJf(u::AbstractVector) = [0.0 cc;cc 0.0]\nf(u::AbstractVector) = [0.0 cc;cc 0.0]*u\nf0(x) = [sin(4*π*x),0.0]\n\nNflux(ϕl::AbstractVector, ϕr::AbstractVector) = 0.5*(f(ϕl)+f(ϕr))\nexact_sol(x, t::Float64) = [0.5*(sin(4*π*(-t+x))+sin(4*π*(t+x))),\n0.5*(sin(4*π*(-t+x))-sin(4*π*(t+x)))]\n\n# Now discretizate the domain\nmesh = Uniform1DFVMesh(50, [-1.0, 1.0])\n\nfunction get_problem(alg, mesh)\n  #Compute discrete initial data\n  u0 = getInitialState(mesh,f0,use_threads = true)\n\n  # Now get a explicit semidiscretization (discrete in space) du_h(t)/dt = f_h(u_h(t))\n  f_h = getSemiDiscretization(f,alg,mesh,[Periodic()]; Df = Jf, use_threads = false,numvars = 2)\n\n  #Setup ODE problem for a time interval = [0.0,1.0]\n  ode_prob = ODEProblem(f_h,u0,(0.0,Tend))\n\n  #Setup callback in order to fix CFL constant value\n  cb = getCFLCallback(f_h, CFL)\n\n  #Estimate an initial dt\n  dt = update_dt!(u0, f_h, CFL)\n  return ode_prob, cb, dt\nend\n\node_prob, cb, dt = get_problem(FVSKTScheme(), mesh)\nsol = solve(ode_prob,SSPRK22(); dt = dt, callback = cb)\n\node_prob, cb, dt = get_problem(FVTecnoScheme(Nflux;order=3), mesh)\nsol2 = solve(ode_prob,SSPRK22(); dt = dt, callback = cb)\n\node_prob, cb, dt = get_problem(FVCompWENOScheme(), mesh)\nsol3 = solve(ode_prob,SSPRK22(); dt = dt, callback = cb)\n\node_prob, cb, dt = get_problem(FVCompMWENOScheme(), mesh)\nsol4 = solve(ode_prob,SSPRK22(); dt = dt, callback = cb)\n\node_prob, cb, dt = get_problem(FVSpecMWENOScheme(), mesh)\nsol5 = solve(ode_prob,SSPRK22(); dt = dt, callback = cb)\n\n#Estimate errors\nu1_h = fv_solution(sol, mesh; vars = 2)\nu2_h = fv_solution(sol2, mesh; vars = 2)\nu3_h = fv_solution(sol3, mesh; vars = 2)\nu4_h = fv_solution(sol4, mesh; vars = 2)\nu5_h = fv_solution(sol5, mesh; vars = 2)\nget_L1_error(exact_sol,u1_h)\nget_L1_error(exact_sol,u2_h)\nget_L1_error(exact_sol,u3_h)\nget_L1_error(exact_sol,u4_h)\nget_L1_error(exact_sol,u5_h)\n\n#Plot\nusing Plots\nplot(u1_h, vars=1, lab=\"KT y\",line = (:dot,2))\nplot!(u2_h, vars=1,lab=\"Tecno y\",line=(:dot,3))\nplot!(u3_h, vars=1,lab=\"Comp WENO y\",line=(:dot,3))\nplot!(u4_h, vars=1,lab=\"Comp MWENO y\",line=(:dot,3))\nplot!(u5_h, vars=1,lab=\"Spec MWENO y\",line=(:dot,3))\nplot!(CL.cell_centers(mesh), [exact_sol(x,Tend)[1] for x in CL.cell_centers(mesh)],lab=\"Ref y\")\n", "meta": {"hexsha": "4adc0435b9972c7ab73bca21c780a09d3b93019c", "size": 2405, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/2_WaveEq1D.jl", "max_stars_repo_name": "Paulms/ConservationLawsDiffEq.jl", "max_stars_repo_head_hexsha": "9b7e5f13865a65a0d77614eae508044d0528c9a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-07-10T00:00:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T15:45:29.000Z", "max_issues_repo_path": "examples/2_WaveEq1D.jl", "max_issues_repo_name": "jamesamiller/ConservationLawsDiffEq.jl", "max_issues_repo_head_hexsha": "9b7e5f13865a65a0d77614eae508044d0528c9a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2018-06-01T15:01:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T08:08:21.000Z", "max_forks_repo_path": "examples/2_WaveEq1D.jl", "max_forks_repo_name": "jamesamiller/ConservationLawsDiffEq.jl", "max_forks_repo_head_hexsha": "9b7e5f13865a65a0d77614eae508044d0528c9a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-08-02T13:11:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T22:21:30.000Z", "avg_line_length": 32.5, "max_line_length": 96, "alphanum_fraction": 0.6943866944, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850128595114, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7632899659794856}}
{"text": "\"\"\"\nFeatures extraction from returns proposed by Betina and al.\n\"\"\"\n#KLT stands for the long-term period\n#KST stands for the short-term period\n#ϱ is the number of standard deviations above the means\nfunction feature_indexes_sgns(asset_rtn_sgn, kst, klt, kmom, ϱ=2)\n    #current time\n    t = size(asset_rtn_sgn, 1)\n    # sig_1 and sig_2 are\n    # short-term and long-term simple moving averages\n    sig_1 = (1 / kst) * sum(asset_rtn_sgn[t - d] for d in 0:(kst - 1))\n    sig_2 = (1 / klt) * sum(asset_rtn_sgn[t - d] for d in 0:(klt - 1))\n\n    # sig_3 and sig_4 are exponential moving average (short and long)\n    sig_3 =\n        (1.0 / sum(exp(-d / kst) for d in 1:kst)) *\n        sum(exp(-d / kst) * asset_rtn_sgn[t - d] for d in 0:(kst - 1))\n    sig_4 =\n        (1.0 / sum(exp(-d / klt) for d in 1:klt)) *\n        sum(exp(-d / klt) * asset_rtn_sgn[t - d] for d in 0:(klt - 1))\n    # RSI\n    R_pos = 0\n    R_neg = 0\n    num_pos = 0\n    num_neg = 0\n    for i in (t - kmom + 1):t\n        if (asset_rtn_sgn[i] > 0)\n            R_pos = R_pos + asset_rtn_sgn[i]\n            num_pos = num_pos + 1\n        else\n            R_neg = R_neg + asset_rtn_sgn[i]\n            num_neg = num_neg + 1\n        end\n    end\n    med_pos = R_pos / num_pos\n    if num_neg == 0\n        med_neg = 1\n    else\n        med_neg = abs(R_neg / num_neg)\n    end\n    sig_5 = med_pos / med_neg\n    # estimated shor-t and long-t standard deviations\n    σ_st_6 = sqrt((1.0 / kst) * sum((asset_rtn_sgn[t - d] - sig_1)^2 for d in 0:(kst - 1)))\n    σ_lt_7 = sqrt((1.0 / klt) * sum((asset_rtn_sgn[t - d] - sig_2)^2 for d in 0:(klt - 1)))\n    # sig_6 and sig_7 are\n\n    if sig_1 <= 0\n        sig_6 = sig_1 - ϱ * σ_st_6\n    else\n        sig_6 = sig_1 + ϱ * σ_st_6\n    end\n    if sig_2 <= 0\n        sig_7 = sig_2 - ϱ * σ_lt_7\n    else\n        sig_7 = sig_2 + ϱ * σ_lt_7\n    end\n    σ_st_8 = sqrt((1.0 / kst) * sum((asset_rtn_sgn[t - d] - sig_3)^2 for d in 0:(kst - 1)))\n    σ_lt_9 = sqrt((1.0 / klt) * sum((asset_rtn_sgn[t - d] - sig_4)^2 for d in 0:(klt - 1)))\n    if sig_3 <= 0\n        sig_8 = sig_3 - ϱ * σ_st_8\n    else\n        sig_8 = sig_3 + ϱ * σ_st_8\n    end\n    if sig_4 <= 0\n        sig_9 = sig_4 - ϱ * σ_lt_9\n    else\n        sig_9 = sig_4 + ϱ * σ_lt_9\n    end\n\n    return [sig_1; sig_2; sig_3; sig_4; sig_5; sig_6; sig_7; sig_8; sig_9]\nend\n\n\"\"\"\nMixed signals predictor proposed by Betina and al. Univariate\n\"\"\"\nfunction mixed_signals_predict_return(asset_rtn_sgn, num_t, kst_a, klt_a, kmom, ϱ=2)\n    numD = size(asset_rtn_sgn, 1)\n    num_train = min(numD - 1, num_t)\n\n    ## optimize features weights (least squares based on past returns)\n    # signal features extraction train (from klt+1 to klt+num_train)\n    #kst = max(min(numD-num_train-10,kst_a),0)\n    #klt = max(min(numD-num_train-10,klt_a),0)\n    sig_features = zeros(num_train, 9) #each line is the i-element's featurs\n    for i in 1:num_train\n        #kst = max(min(numD-i-2,kst_a),0)\n        klt = max(min(numD - i - 2, klt_a), 0)\n        kst = Int64(floor(klt / 2.0))\n        sig_features[num_train + 1 - i, :] = feature_indexes_sgns(\n            asset_rtn_sgn[1:(numD - i)], kst, klt, kmom\n        )\n    end\n    # optimize weights (least squares - pseudo inverse)\n    try\n        weights_opt = \\(\n            sig_features'sig_features,\n            sig_features'asset_rtn_sgn[(numD - num_train + 1):numD],\n        )\n    catch\n        weights_opt = pinv(sig_features, 1E-07) * asset_rtn_sgn[(numD - num_train + 1):numD]\n    end\n    #  normalize features weights\n    weights_opt = weights_opt ./ sum(weights_opt)\n    ## extract features current return\n    kst = min(numD, kst_a)\n    klt = min(numD, klt_a)\n    features = feature_indexes_sgns(asset_rtn_sgn[1:numD], kst, klt, kmom)\n    ## extrapolate return\n\n    return (features'weights_opt)[1]\nend\n", "meta": {"hexsha": "9e57ab476562b806de8f7e3ec46af5db7e66b799", "size": 3777, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/forecasts.jl", "max_stars_repo_name": "Ianlmgoddard/PortfolioOpt.jl", "max_stars_repo_head_hexsha": "378d815f6105edc2b7fff4b7a5a5dabebb8183dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/forecasts.jl", "max_issues_repo_name": "Ianlmgoddard/PortfolioOpt.jl", "max_issues_repo_head_hexsha": "378d815f6105edc2b7fff4b7a5a5dabebb8183dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/forecasts.jl", "max_forks_repo_name": "Ianlmgoddard/PortfolioOpt.jl", "max_forks_repo_head_hexsha": "378d815f6105edc2b7fff4b7a5a5dabebb8183dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4247787611, "max_line_length": 92, "alphanum_fraction": 0.5917394758, "num_tokens": 1385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037732, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7632899630807324}}
{"text": "using LinearAlgebra\n\nusing GLMakie; GLMakie.activate!()\nusing AbstractPlotting\n\nusing Delaunay\nusing DEC2D\n\n# convert vector of vectors into a matrix\nvv2m(vv) = reduce(vcat, transpose.(vv))\n\n# Simples case\nbegin\n    vertices = vcat([[0, 0]], [[cos(2π * i / 6), sin(2π * i / 6)] for i = 1:6])\n    edges = [\n        [1, 2],\n        [1, 3],\n        [1, 4],\n        [1, 5],\n        [1, 6],\n        [1, 7],\n        [2, 3],\n        [3, 4],\n        [4, 5],\n        [5, 6],\n        [6, 7],\n        [7, 2],\n    ]\n    triangles = [[1, 2, 3], [1, 3, 4], [1, 4, 5], [1, 5, 6], [1, 6, 7], [1, 7, 2]]\n\n    # return the mesh and the indices of the interior vertices\n    vint, mesh = DECMesh(vertices, edges, triangles)\n    vext = setdiff(1:length(vertices), vint)\n\n    # d₀ = boundary1(mesh)\n    # d₁ = boundary2d(mesh)\n    # *₁ = hodgestar1(mesh)\n    # *₂ = hodgestar2(mesh)\n    # Δ = *₂ * d₁ * *₁ * d₀\n    Δ = laplacian(mesh) # calculate the laplacian operator\n\n    b = [-1 - 10 * sum(Δ[i, vext]) for i = 1:length(vint)]\n\n    # numerical solution\n    zf = Δ[vint, vint] \\ b\n\n    x = vv2m(vertices)[:, 1]\n    y = vv2m(vertices)[:, 2]\n    zn = similar(vertices, Float64)\n    zn[vint] = zf\n    zn[vext] .= 10\n\n    # exact solution\n    f(x, y) = (1 - x^2 - y^2) / 4 + 10\n    z = [f(v...) for v in vertices]\n\n    println(\n        \"La norma de la diferencia entre la solución numérica y la exacta es \",\n        norm(zn - z),\n    )\n\n    #   ____  _       _   _   _\n    #  |  _ \\| | ___ | |_| |_(_)_ __   __ _\n    #  | |_) | |/ _ \\| __| __| | '_ \\ / _` |\n    #  |  __/| | (_) | |_| |_| | | | | (_| |\n    #  |_|   |_|\\___/ \\__|\\__|_|_| |_|\\__, |\n    #                                 |___/\n\n    # plot numerical solution\n    scene = Scene()\n    mesh!(\n        scene,\n        hcat(x, y, zn),\n        vv2m(mesh.tri.triangles),\n        color = zn,\n        scale_plot = false,\n    )\n    xlims!(scene, -1, 1)\n    ylims!(scene, -1, 1)\n    zlims!(scene, 10, 10.25)\n    wireframe!(scene[end][1], color = (:black, 0.6), linewidth = 2)\n    display(scene)\n    sleep(5.0)\nend\n\n# Caso medio\nbegin\n    # we get the vertices of a more fine mesh\n    vertices = [\n        [cos(2π * i / (50 * r + 1)), sin(2π * i / (50 * r + 1))] .* r for r = 0:0.1:1\n        for i = 1:round(Int, 50 * r + 1, RoundDown)\n    ]\n\n    # get thetriangulation using Delaunay algorithm\n    meshd = delaunay(vv2m(vertices))\n    triangles = [meshd.simplices[i, :] for i = 1:size(meshd.simplices, 1)]\n    edges = reduce(\n        union,\n        [[sort([t[1], t[2]]), sort([t[2], t[3]]), sort([t[3], t[1]])] for t in triangles],\n    )\n\n    vint, mesh = DECMesh(vertices, edges, triangles)\n    vext = setdiff(1:length(vertices), vint)\n\n    Δ = laplacian(mesh)\n\n    b = [-1 - 10 * sum(Δ[i, vext]) for i = 1:length(vint)]\n    zf = Δ[vint, vint] \\ b\n\n    x = vv2m(vertices)[:, 1]\n    y = vv2m(vertices)[:, 2]\n    zn = similar(vertices, Float64)\n    zn[vint] = zf\n    zn[vext] .= 10\n\n    f(x, y) = (1 - x^2 - y^2) / 4 + 10\n    z = [f(v...) for v in vertices]\n\n    println(\n        \"La norma de la diferencia entre la solución numérica y la exacta es \",\n        norm(zn - z),\n    )\n\n    scene = Scene()\n    mesh!(\n        scene,\n        hcat(x, y, zn),\n        vv2m(mesh.tri.triangles),\n        color = zn,\n        scale_plot = false,\n    )\n    xlims!(scene, -1, 1)\n    ylims!(scene, -1, 1)\n    zlims!(scene, 10, 10.25)\n    wireframe!(scene[end][1], color = (:black, 0.6), linewidth = 2)\n    display(scene)\n    sleep(5.0)\nend\n\n# Caso denso\nbegin\n    # we get the vertices of a more fine mesh\n    vertices = [\n        [cos(2π * i / (200 * r + 1)), sin(2π * i / (200 * r + 1))] .* r for r = 0:0.025:1 for i = 1:round(Int, 200 * r + 1, RoundDown)\n    ]\n\n    # get thetriangulation using Delaunay algorithm\n    meshd = delaunay(vv2m(vertices))\n    triangles = [meshd.simplices[i, :] for i = 1:size(meshd.simplices, 1)]\n    edges = reduce(\n        union,\n        [[sort([t[1], t[2]]), sort([t[2], t[3]]), sort([t[3], t[1]])] for t in triangles],\n    )\n\n    vint, mesh = DECMesh(vertices, edges, triangles)\n    vext = setdiff(1:length(vertices), vint)\n\n    Δ = laplacian(mesh)\n\n    b = [-1 - 10 * sum(Δ[i, vext]) for i = 1:length(vint)]\n    zf = Δ[vint, vint] \\ b\n\n    x = vv2m(vertices)[:, 1]\n    y = vv2m(vertices)[:, 2]\n    zn = similar(vertices, Float64)\n    zn[vint] = zf\n    zn[vext] .= 10\n\n    f(x, y) = (1 - x^2 - y^2) / 4 + 10\n    z = [f(v...) for v in vertices]\n\n    println(\n        \"La norma de la diferencia entre la solución numérica y la exacta es \",\n        norm(zn - z),\n    )\n\n    scene = Scene()\n    mesh!(\n        scene,\n        hcat(x, y, zn),\n        vv2m(mesh.tri.triangles),\n        color = zn,\n        scale_plot = false,\n    )\n    xlims!(scene, -1, 1)\n    ylims!(scene, -1, 1)\n    zlims!(scene, 10, 10.25)\n    wireframe!(scene[end][1], color = (:black, 0.6), linewidth = 2)\n    display(scene)\nend\n", "meta": {"hexsha": "da9ac3ecd15419921c078db3acb02bbd90e17b26", "size": 4842, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/diffeq.jl", "max_stars_repo_name": "Suavesito-Olimpiada/DEC2D.jl", "max_stars_repo_head_hexsha": "526132942bd52cd03e352bf1de85d3e130d74200", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-11T08:10:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-11T08:10:44.000Z", "max_issues_repo_path": "examples/diffeq.jl", "max_issues_repo_name": "Suavesito-Olimpiada/DEC2D.jl", "max_issues_repo_head_hexsha": "526132942bd52cd03e352bf1de85d3e130d74200", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/diffeq.jl", "max_forks_repo_name": "Suavesito-Olimpiada/DEC2D.jl", "max_forks_repo_head_hexsha": "526132942bd52cd03e352bf1de85d3e130d74200", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3507853403, "max_line_length": 134, "alphanum_fraction": 0.5008261049, "num_tokens": 1776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7632899532252417}}
{"text": "using PyCall\n@pyimport matplotlib.pyplot as plt\n\nusing Gen\n\n#import Gen: Distribution, logpdf\n\n# Example from Section 4 of Reversible jump Markov chain Monte Carlo\n# computation and Bayesian model determination \n\n########################\n# custom distributions #\n########################\n\n# minimum of k draws from uniform_continuous(lower, upper)\n\n# we can sequentially sample the order statistics of a collection of K uniform\n# continuous samples on the interval [a, b], by:\n# x1 ~ min_uniform_continuous(a, b, K)\n# x2 | x1 ~ min_uniform_continuous(x1, b, K-1)\n# ..\n# xK | x1 .. x_{K-1} ~ min_uniform_continuous(x_{K-1}, b, 1)\n\nstruct MinUniformContinuous <: Distribution{Float64} end\nconst min_uniform_continuous = MinUniformContinuous()\n\nfunction Gen.logpdf(::MinUniformContinuous, x::Float64, lower::T, upper::U, k::Int) where {T<:Real,U<:Real}\n    if x > lower && x < upper\n        (k-1) * log(upper - x) + log(k) - k * log(upper - lower)\n    else\n        -Inf\n    end\nend\n\nfunction Gen.random(::MinUniformContinuous, lower::T, upper::U, k::Int) where {T<:Real,U<:Real}\n    # inverse CDF method\n    p = rand()\n    upper - (upper - lower) * (1. - p)^(1. / k)\nend\n\n\n# piecewise homogenous Poisson process \n\n# n intervals - n + 1 bounds\n# (b_1, b_2]\n# (b_2, b_3]\n# ..\n# (b_n, b_{n+1}]\n\nfunction compute_total(bounds, rates)\n    num_intervals = length(rates)\n    if length(bounds) != num_intervals + 1\n        error(\"Number of bounds does not match number of rates\")\n    end\n    total = 0.\n    bounds_ascending = true\n    for i=1:num_intervals\n        lower = bounds[i]\n        upper = bounds[i+1]\n        rate = rates[i]\n        len = upper - lower\n        if len <= 0\n            bounds_ascending = false\n        end\n        total += len * rate\n    end\n    (total, bounds_ascending)\nend\n\nstruct PiecewiseHomogenousPoissonProcess <: Distribution{Vector{Float64}} end\nconst piecewise_poisson_process = PiecewiseHomogenousPoissonProcess()\n\nfunction Gen.logpdf(::PiecewiseHomogenousPoissonProcess, x::Vector{Float64}, bounds::Vector{Float64}, rates::Vector{Float64})\n    cur = 1\n    upper = bounds[cur+1]\n    lpdf = 0.\n    for xi in sort(x)\n        if xi < bounds[1] || xi > bounds[end]\n            error(\"x ($xi) lies outside of interval\")\n        end\n        while xi > upper \n            cur += 1\n            upper = bounds[cur+1]\n        end\n        lpdf += log(rates[cur])\n    end\n    (total, bounds_ascending) = compute_total(bounds, rates)\n    if bounds_ascending\n        lpdf - total\n    else\n        -Inf\n    end\nend\n\nfunction Gen.random(::PiecewiseHomogenousPoissonProcess, bounds::Vector{Float64}, rates::Vector{Float64})\n    x = Vector{Float64}()\n    num_intervals = length(rates)\n    for i=1:num_intervals\n        lower = bounds[i]\n        upper = bounds[i+1]\n        rate = (upper - lower) * rates[i]\n        n = random(poisson, rate)\n        for j=1:n\n            push!(x, random(uniform_continuous, lower, upper))\n        end\n    end\n    x\nend\n\n\n#########\n# model #\n#########\n\n@gen function model(T::Float64)\n\n    # prior on number of change points\n    k = @addr(poisson(3.), \"k\")\n\n    # prior on the location of (sorted) change points\n    change_pts = Vector{Float64}(undef, k)\n    lower = 0.\n    for i=1:k\n        cp = @addr(min_uniform_continuous(lower, T, k-i+1), \"cp$i\")\n        change_pts[i] = cp\n        lower = cp\n    end\n\n    # k + 1 rate values\n    # h$i is the rate for cp$(i-1) to cp$i where cp0 := 0 and where cp$(k+1) := T\n    alpha = 1.\n    beta = 200.\n    rates = Float64[@addr(Gen.gamma(alpha, 1. / beta), \"h$i\") for i=1:k+1]\n\n    # poisson process\n    bounds = vcat([0.], change_pts, [T])\n    @addr(piecewise_poisson_process(bounds, rates), \"points\")\nend\n\nfunction render(trace; ymax=0.02)\n    T = get_call_record(trace).args[1]\n    assignment = get_assignment(trace)\n    k = assignment[\"k\"]\n    bounds = vcat([0.], sort([assignment[\"cp$i\"] for i=1:k]), [T])\n    rates = [assignment[\"h$i\"] for i=1:k+1]\n    for i=1:length(rates)\n        lower = bounds[i]\n        upper = bounds[i+1]\n        rate = rates[i]\n        plt.plot([lower, upper], [rate, rate], color=\"black\", linewidth=2)\n    end\n    points = assignment[\"points\"]\n    plt.scatter(points, -rand(length(points)) * (ymax/5.), color=\"black\", s=5)\n    ax = plt.gca()\n    xlim = [0., T]\n    plt.plot(xlim, [0., 0.], \"--\")\n    ax[:set_xlim](xlim)\n    ax[:set_ylim](-ymax/5., ymax)\nend\n\nfunction show_prior_samples()\n    plt.figure(figsize=(16,16))\n    T = 40000.\n    for i=1:16\n        plt.subplot(4, 4, i)\n        trace = simulate(model, (T,))\n        render(trace; ymax=0.015)\n    end\n    plt.tight_layout(pad=0)\n    plt.savefig(\"prior_samples.pdf\")\nend\n\n#############################\n# height and position moves #\n#############################\n\n@gen function height_proposal(prev, i::Int)\n    prev_assignment = get_assignment(prev)\n    height = prev_assignment[\"h$i\"]\n    @addr(uniform_continuous(height/2., height*2.), \"h$i\")\nend\n\n@gen function position_proposal(prev, i::Int)\n    prev_assignment = get_assignment(prev)\n    k = prev_assignment[\"k\"]\n    lower = (i == 1) ? 0. : prev_assignment[\"cp$(i-1)\"]\n    upper = (i == k) ? T : prev_assignment[\"cp$(i+1)\"]\n    @addr(uniform_continuous(lower, upper), \"cp$i\")\nend\n\nfunction height_move(trace)\n    k = get_assignment(trace)[\"k\"]\n    i = random(uniform_discrete, 1, k+1)\n    mh(model, height_proposal, (i,), trace)\nend\n\nfunction position_move(trace)\n    k = get_assignment(trace)[\"k\"]\n    i = random(uniform_discrete, 1, k)\n    mh(model, position_proposal, (i,), trace)\nend\n\n\n######################\n# birth / death move #\n######################\n\n# insert a new change point at i, where 1 <= i <= k+1\n# the current change point at i, and all after, will be shifted right\n# the new change point will be placed between cp$(i-1) and the current cp$i\n@gen function birth_proposal(prev, T, i::Int)\n    prev_assignment = get_assignment(prev)\n    k = prev_assignment[\"k\"]\n    lower = (i == 1) ? 0. : prev_assignment[\"cp$(i-1)\"]\n    upper = (i == k+1) ? T : prev_assignment[\"cp$i\"]\n    @addr(uniform_continuous(lower, upper), \"new-cp\")\n    @addr(uniform_continuous(0., 1.), \"u\")\nend\n\n@gen function death_proposal(prev) end\n\nfunction birth_move_new_heights(cur_height, new_cp, prev_cp, next_cp, u)\n    d_prev = new_cp - prev_cp\n    d_next = next_cp - new_cp\n    @assert d_prev > 0\n    @assert d_next > 0\n    d_total = d_prev + d_next\n    log_cur_height = log(cur_height)\n    log_ratio = log(1 - u) - log(u)\n    new_h_prev = exp(log_cur_height - (d_prev / d_total) * log_ratio)\n    new_h_next = exp(log_cur_height + (d_next / d_total) * log_ratio)\n    @assert new_h_prev > 0.\n    @assert new_h_next > 0.\n    (new_h_prev, new_h_next)\nend\n\nconst MODEL = :model\nconst PROPOSAL = :proposal\n\n@inj function birth_injection(T, i::Int)\n\n    # increment k\n    k = @read(MODEL => \"k\")\n    @write(k+1, MODEL => \"k\")\n\n    # changepoints\n    for j=1:i-1\n        @copy(MODEL => \"cp$j\", MODEL => \"cp$j\")\n    end\n    @copy(PROPOSAL => \"new-cp\", MODEL => \"cp$i\")\n    for j=i:k\n        @copy(MODEL => \"cp$j\", MODEL => \"cp$(j+1)\")\n    end\n\n    # compute new heights\n    cur_height = @read(MODEL => \"h$i\")\n    prev_cp = (i == 1) ? 0. : @read(MODEL => \"cp$(i-1)\")\n    next_cp = (i == k+1) ? T : @read(MODEL => \"cp$i\")\n    new_cp = @read(PROPOSAL => \"new-cp\")\n    u = @read(PROPOSAL => \"u\")\n    (new_h_prev, new_h_next) = birth_move_new_heights(cur_height, new_cp, prev_cp, next_cp, u)\n\n    # heights\n    for j=1:i-1\n        @copy(MODEL => \"h$j\", MODEL => \"h$j\")\n    end\n    @write(new_h_prev, MODEL => \"h$i\")\n    @write(new_h_next, MODEL => \"h$(i+1)\")\n    for j=i+1:k+1\n        @copy(MODEL => \"h$j\", MODEL => \"h$(j+1)\")\n    end\n\n    @copy(MODEL => \"points\", MODEL => \"points\")\nend\n\nfunction death_move_u_new_height(prev_height, next_height, cur_cp, prev_cp, next_cp)\n    d_prev = cur_cp - prev_cp\n    d_next = next_cp - cur_cp\n    @assert d_prev > 0\n    @assert d_next > 0\n    d_total = d_prev + d_next\n    log_prev_height = log(prev_height)\n    log_next_height = log(next_height)\n    new_height = exp((d_prev / d_total) * log_prev_height + (d_next / d_total) * log_next_height)\n    u = prev_height / (prev_height + next_height)\n    @assert new_height > 0.\n    (new_height, u)\nend\n\n@inj function death_injection(T, i::Int)\n\n    # decrement k\n    k = @read(MODEL => \"k\")\n    @assert k > 0\n    @write(k-1, MODEL => \"k\")\n\n    # change points\n    for j=1:i-1\n        @copy(MODEL => \"cp$j\", MODEL => \"cp$j\")\n    end\n    for j=i+1:k\n        @copy(MODEL => \"cp$j\", MODEL => \"cp$(j-1)\")\n    end\n\n    # compute new height\n    cur_cp = @read(MODEL => \"cp$i\")\n    prev_cp = (i == 1) ? 0. : @read(MODEL => \"cp$(i-1)\")\n    next_cp = (i == k) ? T : @read(MODEL => \"cp$(i+1)\")\n    prev_height = @read(MODEL => \"h$i\")\n    next_height = @read(MODEL => \"h$(i+1)\")\n    (new_height, u) = death_move_u_new_height(prev_height, next_height, cur_cp, prev_cp, next_cp)\n\n    # heights\n    for j=1:i-1\n        @copy(MODEL => \"h$j\", MODEL => \"h$j\")\n    end\n    @write(new_height, MODEL => \"h$i\")\n    for j=i+2:k+1\n        @copy(MODEL => \"h$j\", MODEL => \"h$(j-1)\")\n    end\n\n    @copy(MODEL => \"points\", MODEL => \"points\")\n\n    @copy(MODEL => \"cp$i\", PROPOSAL => \"new-cp\")\n    @write(u, PROPOSAL => \"u\")\nend\n\nfunction birth_move(trace)\n    # if k > 0, then prob_b = 0.25 and prob_d = 0.25\n    # the probability that the one we introduce will get deleted, given that\n    # we choose a death move, is: 1/(k+1); which is also the probability that\n    # we choose the i that we choose here\n    k = get_assignment(trace)[\"k\"]\n    i = random(uniform_discrete, 1, k+1)\n    # prob_b = 1, but prob_d = 0.25, so we correct by -log(4)\n    correction = (new_trace) -> (k == 0 ? -log(4) : 0)\n    T = get_call_record(trace).args[1]\n    rjmcmc(model,\n        birth_proposal, (T, i),\n        death_proposal, (),\n        birth_injection, (T, i),\n        trace, correction)\nend\n\nfunction death_move(trace)\n    k = get_assignment(trace)[\"k\"]\n    @assert k > 0\n    i = random(uniform_discrete, 1, k)\n    correction = (new_trace) -> (k == 0 ? log(4) : 0)\n    T = get_call_record(trace).args[1]\n    rjmcmc(model,\n        death_proposal, (),\n        birth_proposal, (T, i),\n        death_injection, (T, i),\n        trace, correction)\nend\n\n##########################\n# Generic MCMC inference #\n##########################\n\nfunction resimulation_mh(selection, trace)\n    model_args = get_call_record(trace).args\n    (new_trace, weight) = regenerate(model, model_args, NoChange(), trace, selection)\n    if log(rand()) < weight\n        # accept\n        return new_trace\n    else\n        # reject\n        return trace\n    end\nend\n\nk_selection = DynamicAddressSet()\npush_leaf_node!(k_selection, \"k\")\n\nfunction generic_mcmc_step(trace)\n    k = get_assignment(trace)[\"k\"]\n    if k > 0\n        prob_h = 1./3\n        prob_p = 1./3\n        prob_change_k = 1./3\n    else\n        prob_h = 0.\n        prob_p = 0.\n        prob_change_k = 1\n    end\n    move_type = random(categorical, [prob_h, prob_p, prob_change_k])\n    if move_type == 1\n        height_move(trace)\n    elseif move_type == 2\n        position_move(trace)\n    else\n        resimulation_mh(k_selection, trace)\n    end\nend\n\n\n#########################\n# RJMCMC MCMC inference #\n#########################0\n\nfunction mcmc_step(trace)\n    k = get_assignment(trace)[\"k\"]\n    if k > 0\n        prob_h = 0.25\n        prob_p = 0.25\n        prob_b = 0.25\n        prob_d = 0.25\n    else\n        prob_h = 0.\n        prob_p = 0.\n        prob_b = 1.\n        prob_d = 0.\n    end\n    move_type = random(categorical, [prob_h, prob_p, prob_b, prob_d])\n    if move_type == 1\n        height_move(trace)\n    elseif move_type == 2\n        position_move(trace)\n    elseif move_type == 3\n        birth_move(trace)\n    elseif move_type == 4\n        death_move(trace)\n    else\n        error(\"Unknown move type $move_type\")\n    end\nend\n\nfunction do_mcmc(T, num_steps::Int)\n    (trace, _) = generate(model, (T,), observations)\n    for iter=1:num_steps\n        if iter % 1000 == 0\n            println(\"iter $iter of $num_steps, k: $(get_assignment(trace)[\"k\"])\")\n        end\n        #trace = mcmc_step(trace)\n        trace = generic_mcmc_step(trace)\n    end\n    trace\nend\n\n\n########################\n# inference experiment #\n########################\n\nGen.load_generated_functions()\n\nimport Random\nRandom.seed!(1)\n\n# load data set\nimport CSV\nfunction load_data_set()\n    df = CSV.read(\"coal.csv\")\n    dates = df[1]\n    dates = dates .- minimum(dates)\n    dates * 365.25 # convert years to days\nend\n\nconst points = load_data_set()\nconst T = maximum(points)\nconst observations = DynamicAssignment()\nobservations[\"points\"] = points\n\nfunction show_posterior_samples()\n    plt.figure(figsize=(16,16))\n    for i=1:16\n        println(\"replicate $i\")\n        tic()\n        plt.subplot(4, 4, i)\n        trace = do_mcmc(T, 5000)#10000)\n        toc()\n        render(trace; ymax=0.015)\n    end\n    plt.tight_layout(pad=0)\n    plt.savefig(\"posterior_samples.pdf\")\nend\n\nfunction get_rate_vector(trace, test_points)\n    assignment = get_assignment(trace)\n    k = assignment[\"k\"]\n    cps = [assignment[\"cp$i\"] for i=1:k]\n    hs = [assignment[\"h$i\"] for i=1:k+1]\n    rate = Vector{Float64}()\n    cur_h_idx = 1\n    cur_h = hs[cur_h_idx]\n    next_cp_idx = 1\n    upper = (next_cp_idx == k + 1) ? T : cps[next_cp_idx]\n    for x in test_points\n        while x > upper\n            next_cp_idx += 1\n            upper = (next_cp_idx == k + 1) ? T : cps[next_cp_idx]\n            cur_h_idx += 1\n            cur_h = hs[cur_h_idx]\n        end\n        push!(rate, cur_h)\n    end\n    rate\nend\n\n# compute posterior mean rate curve\n\nfunction plot_posterior_mean_rate()\n    test_points = collect(1.0:10.0:T)\n    rates = Vector{Vector{Float64}}()\n    num_samples = 0\n    num_steps = 5000 # 20000\n    for reps=1:10\n        (trace, _) = generate(model, (T,), observations)\n        for iter=1:num_steps\n            if iter % 1000 == 0\n                println(\"iter $iter of $num_steps, k: $(get_assignment(trace)[\"k\"])\")\n            end\n            trace = mcmc_step(trace)\n            if iter > 4000\n                num_samples += 1\n                rate_vector = get_rate_vector(trace, test_points)\n                @assert length(rate_vector) == length(test_points)\n                push!(rates, rate_vector)\n            end\n        end\n    end\n    posterior_mean_rate = zeros(length(test_points))\n    for rate in rates\n        posterior_mean_rate += rate / Float64(num_samples)\n    end\n    ymax = 0.010\n    plt.figure()\n    plt.plot(test_points, posterior_mean_rate, color=\"black\")\n    plt.scatter(points, -rand(length(points)) * (ymax/6.), color=\"black\", s=5)\n    ax = plt.gca()\n    xlim = [0., T]\n    plt.plot(xlim, [0., 0.], \"--\")\n    ax[:set_xlim](xlim)\n    ax[:set_ylim](-ymax/5., ymax)\n    plt.savefig(\"posterior_mean_rate.pdf\")\nend\n\nfunction plot_trace_plot()\n    # show the number of clusters\n    (trace, _) = generate(model, (T,), observations)\n    num_clusters_vec = Int[]\n    burn_in = 20000\n    for iter=1:burn_in + 5000\n        (trace, accept) = mcmc_step(trace)\n        if iter > burn_in\n            push!(num_clusters_vec, get_assignment(trace)[\"k\"])\n        end\n    end\n    plt.figure()\n    plt.plot(num_clusters_vec)\n    ax = plt.gca()\n    plt.savefig(\"trace_plot_rjmcmc.pdf\")\nend\n\nfunction plot_trace_plot()\n    plt.figure(figsize=(8, 4))\n\n    # generic\n    (trace, _) = generate(model, (T,), observations)\n    num_clusters_vec = Int[]\n    burn_in = 20000\n    for iter=1:burn_in + 5000\n        trace = generic_mcmc_step(trace)\n        if iter > burn_in\n            push!(num_clusters_vec, get_assignment(trace)[\"k\"])\n        end\n    end\n    plt.subplot(2, 1, 1)\n    plt.plot(num_clusters_vec, \"r\")\n\n    # reversible jump\n    (trace, _) = generate(model, (T,), observations)\n    height1 = Float64[]\n    num_clusters_vec = Int[]\n    burn_in = 20000\n    for iter=1:burn_in + 5000\n        trace = mcmc_step(trace)\n        if iter > burn_in\n            push!(num_clusters_vec, get_assignment(trace)[\"k\"])\n        end\n    end\n    plt.subplot(2, 1, 2)\n    plt.plot(num_clusters_vec, \"b\")\n\n    ax = plt.gca()\n    plt.savefig(\"trace_plot.pdf\")\nend\n\n\n\nprintln(\"showing prior samples...\")\nshow_prior_samples()\n\nprintln(\"showing posterior samples...\")\nshow_posterior_samples()\n\nprintln(\"estimating posterior mean rate...\")\nplot_posterior_mean_rate()\n\nprintln(\"making trace plot...\")\nplot_trace_plot()\n", "meta": {"hexsha": "39e34be8dd99bb4e1c3099543c3ad60cb01153d2", "size": 16342, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/coal/coal.jl", "max_stars_repo_name": "BoltzmannBrain/Gen", "max_stars_repo_head_hexsha": "a9ab5b41cd5974aa40c38ffdcb9ecabd224f42b9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/coal/coal.jl", "max_issues_repo_name": "BoltzmannBrain/Gen", "max_issues_repo_head_hexsha": "a9ab5b41cd5974aa40c38ffdcb9ecabd224f42b9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/coal/coal.jl", "max_forks_repo_name": "BoltzmannBrain/Gen", "max_forks_repo_head_hexsha": "a9ab5b41cd5974aa40c38ffdcb9ecabd224f42b9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0562913907, "max_line_length": 125, "alphanum_fraction": 0.5920327989, "num_tokens": 4827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362849986365571, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.763289943876829}}
{"text": "\"\"\"\n\tMMCK(μ, λ, c, k)\n\nTạo mô hình M/M/c/k\n\"\"\"\nstruct MMCK{T} <:AbstractMMCK\n\tλ::T\n\tμ::T\n\tc::Union{T, Integer}\n\tk::Union{T, Integer}\n\tr::Union{T, Real}\n\tρ::Union{T, Real}\n\tfunction MMCK(λ, μ, c, k)\n\t\tT = Union{typeof(μ), typeof(λ)}\n\t\tnew{T}(λ, μ, c,\tk, λ/μ,\tλ/μ/c)\n\tend\nend\n\nfunction pn(m::MMCK, n::Integer)\n\tr = m.r\n\tk = m.k\n\tc = m.c\n\tif n == 0\n\t\t1 / (\n\t\t     sum(r^i / factorial(i) for i = 0:c-1) +\n\t\t     sum(r^i / (c^(i-c) * factorial(c)) for i = c:k)\n\t\t     )\n\telseif n < c\n\t\tpn(m, 0) * r^n / factorial(n)\n\telseif n <= k\n\t\tpn(m, 0) * r^n / (c^(n-c) * factorial(c))\n\telse 0\n\tend\nend\n\nfunction L(m::MMCK)\n\tsum(i * pn(m, i) for i=0:m.k)\nend\n\nfunction Lq(m::MMCK)\n\tsum((i - m.c) * pn(m, i) for i=m.c:m.k)\nend\n\nfunction W(m::MMCK)\n\tL(m) / λe(m)\nend\n\nfunction Wq(m::MMCK)\n\tLq(m) / λe(m)\nend\n", "meta": {"hexsha": "a0d7cbd375db24e1102deca41636311c3a29104c", "size": 790, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mmck.jl", "max_stars_repo_name": "ndgnuh/MarkovAndQueueModels.jl", "max_stars_repo_head_hexsha": "30d0c3ecb9da61a466b95b791e8dbefc854ed38f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mmck.jl", "max_issues_repo_name": "ndgnuh/MarkovAndQueueModels.jl", "max_issues_repo_head_hexsha": "30d0c3ecb9da61a466b95b791e8dbefc854ed38f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mmck.jl", "max_forks_repo_name": "ndgnuh/MarkovAndQueueModels.jl", "max_forks_repo_head_hexsha": "30d0c3ecb9da61a466b95b791e8dbefc854ed38f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.4901960784, "max_line_length": 54, "alphanum_fraction": 0.5215189873, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750466836961, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7632797034104029}}
{"text": "# This file is a part of Julia. License is MIT: http://julialang.org/license\n\n# https://github.com/JuliaLang/julia/issues/4707\n\n#----------------- Get the A matrix\nfunction getDivGrad(n1,n2,n3)\n        D1 = kron(speye(n3),kron(speye(n2),ddx(n1)))\n        D2 = kron(speye(n3),kron(ddx(n2),speye(n1)))\n        D3 = kron(ddx(n3),kron(speye(n2),speye(n1)))\n\n        # DIV from faces to cell-centers\n        Div = [D1 D2 D3]\n        return Div*Div';\nend\n\n#----------------- 1D finite difference on staggered grid\nfunction ddx(n)\n    return spdiags(ones(n)*[-1 1],[0,1],n,n+1)\nend\n\n#------------- Build a diagonal matrix\nfunction spdiags(B,d,m,n)\n    d = d[:]\n    p = length(d)\n\n    len = zeros(Int, p+1, 1)\n    for k = 1:p\n        len[k+1] = len[k] + length(max(1,1-d[k]):min(m,n-d[k]))\n    end\n\n    a = zeros(Int, len[p+1], 3)\n    for k = 1:p\n        # Append new d[k]-th diagonal to compact form\n        i = max(1,1-d[k]):min(m,n-d[k])\n        a[(len[k]+1):len[k+1],:] = [i i+d[k] B[i+(m>=n)*d[k],k]]\n    end\n\n    return sparse(a[:,1],a[:,2],a[:,3],m,n)\nend\n", "meta": {"hexsha": "09a76bac03aa45103fe9588565add0efab71b2c6", "size": 1055, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmarks/kernel/getdivgrad.jl", "max_stars_repo_name": "JuliaTagBot/Perftests.jl", "max_stars_repo_head_hexsha": "90cab79cad1f7e5ec476132860c5da2abcec548e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-10-02T14:25:00.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-02T14:25:00.000Z", "max_issues_repo_path": "benchmarks/kernel/getdivgrad.jl", "max_issues_repo_name": "JuliaTagBot/Perftests.jl", "max_issues_repo_head_hexsha": "90cab79cad1f7e5ec476132860c5da2abcec548e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/kernel/getdivgrad.jl", "max_forks_repo_name": "JuliaTagBot/Perftests.jl", "max_forks_repo_head_hexsha": "90cab79cad1f7e5ec476132860c5da2abcec548e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:56:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:21:43.000Z", "avg_line_length": 26.375, "max_line_length": 76, "alphanum_fraction": 0.5308056872, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750360641185, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7632796903736317}}
{"text": "export Zernike,\n       zernike_norm,\n       zernike_nm_to_fringe,\n       zernike_nm_to_ansi_j,\n       zernike_ansi_j_to_nm,\n       zernike_noll_to_nm,\n       zernike_fringe_to_nm,\n       zernike_zero_separation\n\n\"\"\"\n    Zernike([T, ]n, m, norm=true)\n\nZernike polynomial of orders `n` and `m`. If `norm` is true the output will be normalized. The output type can be specified with `T`, which will default to `Float64`.\n\n# Examples\n\n```jldoctest\njulia> z = Zernike(10, 3)\nZernike{Float64}(n=10, m=3)\n\njulia> z(0.8, 0.2)\n-1.6860955965619917\n\njulia> Zernike(BigFloat, 10, 3)(0.8, 0.2)\n-1.68609559656199170518675600760616362094879150390625\n```\n\"\"\"\nstruct Zernike{T<:AbstractFloat,F1,F2}\n    n::Int\n    m::Int\n    basis::F1\n    trig_func::F2\n    Zernike{T}(n, m, basis, trig_func) where {T} = new{T,typeof(basis),typeof(trig_func)}(n, m, basis, trig_func)\nend\n\nfunction Zernike(T, n, m, norm::Bool=true)\n    norm_val = norm ? zernike_norm(n, m) : 1.0\n    trig_func = m < 0 ? sin : cos\n    basis = x -> norm_val * jacobi((n - m) ÷ 2, 0, abs(m), x)\n    Zernike{T}(n, m, basis, trig_func)\nend\n\nZernike(n, m, norm::Bool=true) = Zernike(Float64, n, m, norm)\n\nfunction Base.show(io::IO, z::Zernike{T}) where T\n    print(io, \"Zernike{$T}(n=$(z.n), m=$(z.m))\")\nend\n\nfunction (z::Zernike{T})(ρ, θ) where T\n    x = ρ^2 - 1\n    return T(ρ^abs(z.m) * z.basis(x) * z.trig_func(z.m * θ))\nend\n    \n\n\n\"\"\"\n    kronecker(i,j)\n\n1 if i==j, else 0; mathematical kronecker function\n\"\"\"\nkronecker(i, j) = Int(i == j)\n\n\"\"\"\n    zernike_norm(n, m)\n\nNorm of Zernike polynomial of radial order n, azimuthal order m.\n\nThe norm is the average squared distance to zero.  By multiplying a zernike\nvalue by the norm, the term is given unit stdev or RMS.\n\"\"\"\nfunction zernike_norm(n, m)\n    num = √(2 * (n+1)) / (1 + kronecker(m, 0))\nend\n\n\"\"\"\n    zernike_nm_to_fringe(n, m)\n\nMap (n,m) ANSI indices to a single fringe index.\n\"\"\"\nfunction zernike_nm_to_fringe(n, m)\n    term1 = (1 + (n + abs(m))/2)^2\n    term2 = 2*abs(m)\n    term3 = (1 + sign(m)) / 2\n    return int(term2 - term2 - term3) + 1\nend\n\n\"\"\"\n    zernike_nm_to_ansi_j(n, m)\n\nMap (n,m) ANSI indices to a single ANSI j index.\n\nSee also:\n    - [`zernike_ansi_j_to_nm`](@ref) (reciprocal of this function)\n\"\"\"\nfunction zernike_nm_to_ansi_j(n, m)\n    return int((n * (n + 2) + m) / 2)\nend\n\n\"\"\"\n    zernike_ansi_to_ansi_j(n, m)\n\nMap (n,m) ANSI indices to a single ANSI j index.\n\nSee also:\n    - [`zernike_nm_to_ansi_j`](@ref) (reciprocal of this function)\n\"\"\"\nfunction zernike_ansi_j_to_nm(j)\n    n = int(ceil((-3 + √(9 + 8j))/2))\n    m = 2j - n * (n + 2)\n    return n, m\nend\n\n\"\"\"\n    zernike_noll_to_nm(j)\n\nMap j Noll index to ANSI (n,m) indices.\n\"\"\"\nfunction zernike_noll_to_nm(j)\n    n = int(ceil((-1 + √(1 + 8j))/2) - 1)\n    if n == 0\n        m = 0\n    else\n        nseries = int((n+1) * (n+2) / 2)\n        residual = j - nseries - 1\n\n        if isodd(j)\n            sign = -1\n        else\n            sign = 1\n        end\n\n        if isodd(n)\n            ms = [1,1]\n        else\n            ms = [0]\n        end\n\n        for i=0:n÷2\n            push!(ms, ms[end]+2)\n            push!(ms, ms[end])\n        end\n\n        m = ms[residual] * sign\n    end\n    return n, m\nend\n\n\"\"\"\n    zernike_fringe_to_nm(j)\n\nMap j Fringe index to ANSI (n,m) indices.\n\"\"\"\nfunction zernike_fringe_to_nm(j)\n    m_n = 2 * ceil(√j - 1)\n    g_s = (m_n / 2)^2 + 1\n    n = m_n / 2 + floor((j-g_s)/2)\n    m = m_n - n * (1 - mod(j-g_s, 2) * 2)\n    return int(n), int(m)\nend\n\n\"\"\"\n    zernike_zero_separation(n)\n\nMinimum zero separation of Zernike polynomial of radial order n.  Useful for\ncomputing sample count requirements.\n\"\"\"\nfunction zernike_zero_separation(n)\n    return 1 / n^2\nend\n\n\"\"\"\n    zernike(n, m, ρ, θ[; norm])\n\nZernike polynomial of radial order n and azimuthal order m, evaluated at the\npoint (ρ, θ).  No normalization is required of (ρ, θ), though the polynomials\nare orthogonal only over the unit disk.\n\nnorm is a boolean flag indicating whether the result should be orthonormalized\n(scaled to unit RMS) or not.\n\"\"\"\nfunction zernike(n, m, ρ, θ; norm::Bool=true)\n    x = ρ^2 - 1\n    n_j = (n - m) / 2\n    am = abs(m)\n    # α=0, β=|m|\n    # there is a second syntax where you have x reversed, 1 - ρ^2,\n    # in which ase you swap α and β.  It makes absolutely no difference\n    out = jacobi(n_j, 0, am, x)\n    if m != 0\n        if sign(m) == -1\n            f = sin\n        else\n            f = cos\n        end\n        out *= (ρ^am * f(m*θ))\n    end\n\tif norm\n\t\tout *= zernike_norm(n,m)\n\tend\n    return out\nend\n", "meta": {"hexsha": "58ce6cddffe26ad089dcca635e2b07476eb3cb1c", "size": 4511, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/zernike.jl", "max_stars_repo_name": "mileslucas/OpticsPolynomials.jl", "max_stars_repo_head_hexsha": "ca8ec35c627a6c1d1c2b8a792460900b600e584e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/zernike.jl", "max_issues_repo_name": "mileslucas/OpticsPolynomials.jl", "max_issues_repo_head_hexsha": "ca8ec35c627a6c1d1c2b8a792460900b600e584e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/zernike.jl", "max_forks_repo_name": "mileslucas/OpticsPolynomials.jl", "max_forks_repo_head_hexsha": "ca8ec35c627a6c1d1c2b8a792460900b600e584e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3316831683, "max_line_length": 166, "alphanum_fraction": 0.5932165817, "num_tokens": 1622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7632783002513962}}
{"text": "using DataFrames, GLM, Distributions, LinearAlgebra, Random\nusing Plots, LaTeXStrings;pyplot()\nRandom.seed!(0)\n\nbeta0, beta1 = 2.0, 1.5\nsigma = 2.5\nn, N = 10, 10^4\nalpha = 0.05\n\nfunction coefEst()\n    xVals = collect(1:n)\n    yVals = beta0 .+ beta1*xVals + rand(Normal(0,sigma),n)\n    data = DataFrame([xVals,yVals],[:X,:Y])\n    model = lm(@formula(Y ~ X), data)\n    coef(model)\nend\n\nests = [coefEst() for _ in 1:N]\n\nxBar = mean(1:n)\nsXX = sum([(x - xBar)^2 for x in 1:n])\nsx2 = sum([x^2 for x in 1:n])\nvar0 = sigma^2 * sx2/(n*sXX)\nvar1 = sigma^2/sXX\ncv = -sigma^2*xBar/sXX\n\nmu = [beta0, beta1]\nSigma = [var0 cv; cv var1]\n\nA = cholesky(Sigma).L\nAi = inv(A)\n\nr = quantile(Rayleigh(),1-alpha)\nisInEllipse(x) = norm(Ai*(x-mu)) <= r\nestIn = isInEllipse.(ests)\n\nprintln(\"Proportion of points inside ellipse: \", sum(estIn)/N)\n\nscatter(first.(ests[estIn]),last.(ests[estIn]),c=:green, ms=2, msw=0)\nscatter!(first.(ests[.!estIn]),last.(ests[.!estIn]),c=:blue, ms=2, msw=0)\n\nellipsePts = [r*A*[cos(t),sin(t)] + mu  for t in 0:0.01:2pi]\nscatter!([beta0],[beta1],c=:red, ms=5, msw = 0)\nplot!(first.(ellipsePts),last.(ellipsePts), \n\tc=:red, lw=2, legend=:none, \n\txlabel=L\"\\hat{\\beta}_0\", ylabel=L\"\\hat{\\beta}_1\")", "meta": {"hexsha": "6ee62bc7b898b4f53cded663ad69a6e796240791", "size": 1200, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "8_chapter/distRegEstimators.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "8_chapter/distRegEstimators.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "8_chapter/distRegEstimators.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 26.0869565217, "max_line_length": 73, "alphanum_fraction": 0.6316666667, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.7632782962164171}}
{"text": "#Runs a simple Metropolis-Hastings (ie MCMC) algoritm to simulate an\n#exponential distribution, which has the probability density\n#p(x)=exp(-x/m^2), where m>0.\n#\n#Author: H. Paul Keeler, 2019.\n# Website: hpaulkeeler.com\n# Repository: github.com/hpaulkeeler/posts\n\n#Note: Need the .+ for adding a scalar to an array\n#Also need . for sqrt, exp, cos, sin etc and assinging scalars to arrays\n\n#clearconsole(); #for clearing Julia REPL console\n\nusing Distributions #for random simulations\nusing PyPlot #for plotting\nusing StatsBase #for histograms etc\nusing Random\nusing LinearAlgebra\nPyPlot.close(\"all\");  # close all PyPlot figures\n\n#set random seed for reproducibility\n#Random.seed!(1234)\n\nnumbSim=10^4; #number of random variables simulated\nnumbSteps=25; #number of steps for the Markov process\nnumbBins=50; #number of bins for histogram\n\nsigma=1; #standard deviation for normal random steps\nm=2; #parameter (ie mean) for distribution to be simulated\n\nfunction fun_p(x)\n    return ((exp.(-x./m)./m).*(x.>0));\nend\n\nxRand=rand(numbSim); #random intial values\nprobCurrent=fun_p(xRand); #current transition probabilities\n\nfor jj=1:numbSteps\n    zRand= xRand.+sigma.*rand(Normal(),numbSim);#take a (normally distributed) random step\n    #zRand= xRand +2*sigma*(rand(size(xRand))-0.5);#take a (uniformly distributed) random step\n    probProposal=fun_p(zRand); #proposed probability\n\n    #acceptance rejection step\n    booleAccept=rand(numbSim) .< probProposal./probCurrent;\n    #update state of random walk/Markov chain\n    xRand[booleAccept]=zRand[booleAccept];\n    #update transition probabilities\n    probCurrent[booleAccept]=probProposal[booleAccept];\n\nend\n\n#histogram section: empirical probability density\nhistX=fit(Histogram, xRand,nbins=numbBins); #find histogram data\nhistX=normalize(histX,mode=:pdf); #normalize histogram\nbinEdges=histX.edges; #retrieve bin edges\nxValues=(binEdges[1][2:end]+binEdges[1][1:end-1])./2; #mid-points of bins\npdfEmp=(histX.weights)\n#analytic solution of probability density\npdfExact=fun_p(xValues);\n\n# Plotting\nPyPlot.plot(xValues, pdfExact)\nPyPlot.scatter(xValues, pdfEmp, marker=\"x\", c=\"r\");\nPyPlot.grid(true);\nPyPlot.xlabel(\"x\");\nPyPlot.ylabel(\"p(x)\");\nPyPlot.show();\n", "meta": {"hexsha": "2434e5f04fc47237294f8b1163bff7c19319b07b", "size": 2203, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "MCMC/MCMC_1D.jl", "max_stars_repo_name": "hpkeeler/posts", "max_stars_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2020-05-14T12:14:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:22:09.000Z", "max_issues_repo_path": "MCMC/MCMC_1D.jl", "max_issues_repo_name": "hpkeeler/posts", "max_issues_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MCMC/MCMC_1D.jl", "max_forks_repo_name": "hpkeeler/posts", "max_forks_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-10-26T01:22:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T17:33:40.000Z", "avg_line_length": 32.3970588235, "max_line_length": 94, "alphanum_fraction": 0.7557875624, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7632782930440595}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.5\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ f6d978ea-b349-11eb-309e-f5a517efc907\nbegin \n\tusing LinearAlgebra \n\tusing Plots \n\tusing QuadGK\nend\n\n# ╔═╡ 99268461-9e3f-4685-b530-e24febfb539e\n#= \nIDEA OF MULTIGRID : \n\t\t\n\tG is a mesh of a 1D domain. \n\tG1 is another, but coarser. \n\tG1's operator has higher frequency eigenvalues as opposed to  G. \n\tUse G1 to weed out these values. \n\tUse smoothers alternatively. \n=# \n\n# ╔═╡ b422b21d-b9d3-4aad-b29b-d0669331abc8\n \nbegin\n\te = 5; #  Tune e for different basis functions \n\tN = 10;\n\tNi = 100; \n\txmin = 0;\n\txmax = 1; \n\tx = LinRange(xmin,xmax,N);\n\txi = LinRange(x[e-1],x[e+1],Ni);\n\th = x[2] - x[1]; \nend\n\n# ╔═╡ b11596d4-ee5d-41ec-af8f-96734ba2f579\n# This shows a heirarchy of grids\t\ngrid1 = plot(x,zeros(length(x)),marker=\"*\")\n\n# ╔═╡ c1463b68-12e6-4e8c-9902-c2cc7e6caa91\nbegin\n\t# Plot the basis functions \n\ty = zeros(length(xi)); \n\tfor i = 1:length(xi);  \n\t\tif(xi[i]>=xi[1] && xi[i]<=x[e])\n\t\t\ty[i] = 1/h * (xi[i]-x[e-1]);\t\n\t\telseif (xi[i]>x[e] && xi[i]<x[e+1]) \n\t\t\ty[i] = 1/h * (x[e+1]-xi[i]);\n\t\tend\n\tend\n\tplot!(xi,y,title=\"Linear Basis Functions\");\nend\n\n# ╔═╡ d5da54e6-0a4f-4f43-a7ab-8791574b32c6\n# Now we use the linear basis functions and obtain an approximation of the Laplacian operator. \n\nbegin \n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\tfunction θ(x,i,N)\n\t\tn = length(x); \n\t\ty = zeros(n); \n\t\tif i==1 \n\t\t\tfor k=1:N \n\t\t\t\tif x[k]<= x[i+1] \n\t\t\t\t\ty[k] = (N-1)*(x[i+1]-x[k]);\n\t\t\t\tend\n\t\t\tend\n\t\telseif i==N \n\t\t\tfor l = 1:N \n\t\t\t\tif x[l] >= x[i-1] \n\t\t\t\t\ty[l] = (N-1) * (x[l]-x[i]);\n\t\t\t\tend\n\t\t\tend\n\t\telse \n\t\t\tfor j=2:n-1 \n\t\t\t\tif(x[j]>=x[i-1] && x[j]<=x[i])\n\t\t\t\t\ty[j] = (N-1) * (x[j]-x[i-1]);\n\t\t\t\telseif(x[j]>=x[i] && x[j]<=x[i+1])\n\t\t\t\t\ty[j] = (N-1) * (x[i+1]-x[j]); \n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\treturn y;\n\tend\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\tfunction θ_scalar(x,i,xi,N)\n\t\t\tif(x>=xi[i-1] && x<=xi[i])\n\t\t\t\ty = (N-1) * (x-xi[i-1]);\n\t\t\telseif(x>=xi[i] && x<=xi[i+1])\n\t\t\t\ty = (N-1) * (xi[i+1]-x); \n\t\t\telse\n\t\t\t\ty=0;\n\t\t\tend\n\t\treturn y;\n\tend\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\tfunction stiffness_matrix(n)\n\t\tmd = 2.0*ones(n-2);\n\t\tld = -1.0*ones(n-3); \n\t\tud = -1.0*ones(n-3);\n\t\treturn (n-1)*Tridiagonal(ld,md,ud); \n\tend\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\tfunction intergrate(x,i,N) \n\t\tdomain = LinRange(0,1,N+2);\n\t\treturn sin(pi*x) * θ_scalar(x,i,domain,N);  \n\tend\n\t\n\tfunction compute_rhs(n)\n\t\tn = n-2; \n\t\tintegral = zeros(n);\t\n\t\tfor i=1:length(integral)  \n\t\tintegral[i] = 1.5*quadgk(q->intergrate(q,i+1,n),0,1,rtol=1e-8)[1];\n\t\tend\n\t\treturn integral; \n\tend\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nend\n\n# ╔═╡ a5f1a911-3f71-4630-a872-99514d52e5f3\nbegin\n\tnk = 12;\n\ta = LinRange(xmin,xmax,nk); \n\tz = θ(a,3,nk);\n\tplot(a,z)\nend\n\n# ╔═╡ feba23c9-1b66-400e-9ffb-0dc5fc65896f\nbegin\n\t# Get the stiffness matrix and the RHS : The RHS is evaluated and plotted. \n\tn = 7;\n\ttest_A = stiffness_matrix(n)\n\ttest_b = compute_rhs(n);\n\tplot(test_b)\n\t#test_A\n\t#test_b\nend\n\n# ╔═╡ b8b7b670-6039-4bd9-9f95-8652f6e03528\nmd\"\"\"\n\t\n\t#NESTED MULTIGRID\n\n\tStart on a coarse grid h_0 \n\n\tIterate using a smoother and remove one range of high frequencies. \n\n\tInterpolate solution to a finer grid - h_1\n\t\n\tStart step 1 with a smaller time step h_1. \n\"\"\"\n\n# ╔═╡ a217bef6-3c9f-4d12-8b3f-eb937987c709\n# Description\n\nmd\"\"\"\n\nTo implement a nested multigrid method. \n\nWe would need access to a smoother. The kind of smoother to choose depends on the nature of the matrix A that we solve. \n\nFor the finite element approximation of the poisson equation we have a matrix A that is not diagonally dominant. \n\nSo solve the problem we need a method for which convergence could be proven. \n\nIn comes the Gauss Seidel method. \n\n\"\"\"\n\n# ╔═╡ f2a7eb59-3617-47fe-be19-f6873d0f3c56\nfunction gauss_seidel_relaxation(A,b,x0,max_iterations)\n\tx = x0; \n\tres = b - A*x; \n\tfor iter = 1:max_iterations \n\t\tfor i = 1:length(x)\n\t\t\tx[i] = (1/A[i,i])*(b[i] - dot(A[i,:],x) + A[i,i]*x[i]);\n\t\tend\n\t\tres = b - A*x; \n\tend \n\treturn x\nend\n\n# ╔═╡ abf72f94-406b-41a6-bbdd-fa3ac2919531\n# To perform a nested iteration \nbegin \n\tn_nodes = 7;\n\tA = stiffness_matrix(n_nodes);\n\tb = compute_rhs(n_nodes);\n\tx0 = zeros(n_nodes-2); \n\t\n\ty_appx = gauss_seidel_relaxation(A,b,x0,10); \n\ty_appx = vcat(0,y_appx,0);\n\tprintln(y_appx)\n\t\n\tx_nodes = LinRange(0,1,100); \n\ty_actual = zeros(length(x_nodes)); \n\tfor i=1:length(x_nodes)\n\t\ty_actual[i] = 1/pi^2 * sin(pi*x_nodes[i]);\n\tend\n\tplot(x_nodes,y_actual,label=\"Actual Solution\");\n\tplot!(LinRange(0,1,length(y_appx)),y_appx,label=\"Approximate solution\");\nend\n\n# ╔═╡ Cell order:\n# ╠═f6d978ea-b349-11eb-309e-f5a517efc907\n# ╠═99268461-9e3f-4685-b530-e24febfb539e\n# ╠═b422b21d-b9d3-4aad-b29b-d0669331abc8\n# ╠═b11596d4-ee5d-41ec-af8f-96734ba2f579\n# ╠═c1463b68-12e6-4e8c-9902-c2cc7e6caa91\n# ╠═d5da54e6-0a4f-4f43-a7ab-8791574b32c6\n# ╠═a5f1a911-3f71-4630-a872-99514d52e5f3\n# ╠═feba23c9-1b66-400e-9ffb-0dc5fc65896f\n# ╟─b8b7b670-6039-4bd9-9f95-8652f6e03528\n# ╟─a217bef6-3c9f-4d12-8b3f-eb937987c709\n# ╠═f2a7eb59-3617-47fe-be19-f6873d0f3c56\n# ╠═abf72f94-406b-41a6-bbdd-fa3ac2919531\n", "meta": {"hexsha": "587cd388b86e8ebb11e506d636da23fb6504b44e", "size": 5175, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Nested_grid.jl", "max_stars_repo_name": "dynamic-queries/Smoothers-Multigrids-and-all-that", "max_stars_repo_head_hexsha": "0964dcee0df44b4d9b1364a57a983756e56a8a78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Nested_grid.jl", "max_issues_repo_name": "dynamic-queries/Smoothers-Multigrids-and-all-that", "max_issues_repo_head_hexsha": "0964dcee0df44b4d9b1364a57a983756e56a8a78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nested_grid.jl", "max_forks_repo_name": "dynamic-queries/Smoothers-Multigrids-and-all-that", "max_forks_repo_head_hexsha": "0964dcee0df44b4d9b1364a57a983756e56a8a78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6301369863, "max_line_length": 120, "alphanum_fraction": 0.5953623188, "num_tokens": 2115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7632575085770802}}
{"text": "# Some built-in functions\nprintln(\"println is a function\")\nprintln(\"parse(Int64, \\\"123\\\"): $(parse(Int64, \"123\"))\")\nprintln(\"parse(Float64, \\\"123.456\\\"): $(parse(Float64, \"123.456\"))\")\nprintln(\"trunc(Int64, 3.67123): $(trunc(Int64, 3.67123))\")\nprintln(\"trunc(Int64, -3.67123): $(trunc(Int64, -3.67123))\")\nprintln(\"Other examples: \", float(32), \"\\t\", string(32), \"\\t\", string(123.456))\nprintln(\"Natural log and base, log(exp(1)): $(log(exp(1)))\")\nprintln(\"Other log bases, log2(10), log10(10): $(log2(10)), $(log10(10))\")\nprintln(\"Trigonometry, sin(pi), cos(pi), tan(pi): $(sin(pi)), $(cos(pi)), $(tan(pi))\")\nprintln(\"sqrt(2) = $(sqrt(2))\")\n\n# Defning functions\nfunction printlines()\n    println(\"This is the first line.\")\n    println(\"This is the second line.\")\nend\n\n# printlines()\n\nfunction printmorelines()\n    printlines()\n    printlines()\nend\n\n# printmorelines()\n\nfunction printargument(arg)\n    println(arg)\nend\n\nprintargument(123)\nprintargument(\"123456\")\nprintargument(cos(pi/2))\n\n# Locality of variables and parameters\nfunction sumthree(a, b, c)\n    a = a + b\n    total = a\n    total += c\n    return total\nend\nd, e, f = 1, 2, 3\nprintln(\"sumthree(d, e, f): $(sumthree(d, e, f))\")\nprintln(\"d, e, f: $d, $e, $f\")\n# These lines will cause an error:\n# println(a, b, c)\n# println(total)\n\n# Example of void function that returns nothing:\nprintln(printlines())\n\n# Example of a docstring\n\"\"\"\npolyline(t, n, len, angle)\n\nDraws n line segments with the given length and\nangle (in degrees) between them.  t is a turtle.\n\"\"\"\nfunction polyline(t, n, len, angle)\nend\n\n# Example of including errors\nfunction fact(n)\n    if !(n isa Int64)\n        error(\"Factorial is only defined for integers.\")\n    elseif n < 0\n        error(\"Factorial is not defined for negative integers.\")\n    elseif n == 0\n        return 1\n    else\n        return n * fact(n-1)\n    end\nend\n\n# println(fact(1.5))\n# println(fact(-1))\n\n# Shorthand notation for function definition\nfunction func_ex(a=1, b=2)\n    return a + 2b\nend\n\n# The above function definition is equivalent to the following:\nfunc(a, b) = a + 2b\nfunc(a) = func(a, 2)\nfunc() = func(1, 2)\nprintln(\"func(7, 5): $(func(7, 5))\")\nprintln(\"func(2): $(func(2))\")\nprintln(\"func(): $(func())\")", "meta": {"hexsha": "a24bb3398e10e85ba00b8c602eae854b132ef675", "size": 2212, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "EnzioKam/learning_julia", "max_stars_repo_head_hexsha": "a673e2d721d734333c79bcc4cf04f678ed378bdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions.jl", "max_issues_repo_name": "EnzioKam/learning_julia", "max_issues_repo_head_hexsha": "a673e2d721d734333c79bcc4cf04f678ed378bdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions.jl", "max_forks_repo_name": "EnzioKam/learning_julia", "max_forks_repo_head_hexsha": "a673e2d721d734333c79bcc4cf04f678ed378bdb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5777777778, "max_line_length": 86, "alphanum_fraction": 0.6428571429, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7632575077555886}}
{"text": "# p13.jl - solve linear BVP u_xx = exp(4x), u(-1)=u(1)=0\n\nN = 16;\n(D,x) = cheb(N);\nD2 = D^2;\nD2 = D2[2:N,2:N];                   # boundary conditions\nf = @. exp(4*x[2:N]);\nu = D2\\f;                           # Poisson eq. solved here\nu = [0;u;0];\nclf(); axes([.1,.4,.8,.5]);\nplot(x,u,\".\",markersize=6);\nxx = -1:.01:1;\nuu = polyval(polyfit(x,u),xx);      # interpolate grid data\nplot(xx,uu);\ngrid(true);\nexact = @. ( exp(4*xx) - sinh(4)*xx - cosh(4) )/16;\ntitle(\"max err = $(signif(norm(uu-exact,Inf),4))\",fontsize=12);\n", "meta": {"hexsha": "9ff27647dd7b42c395a0b717aca2db1de6aa2f88", "size": 520, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p13.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p13.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p13.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8888888889, "max_line_length": 63, "alphanum_fraction": 0.5076923077, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810451666346, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7632406718486809}}
{"text": "# This file calculates scattering from the gravity Helmholtz equation via the adaptive spectral method.\n# Δu + (E+x_2)u = 0,\n# u|Γ = 0,\n# u^i = Φ(⋅,⋅,E)|Γ\n# u = u^i + u^s.\n# The normal derivative ∂u/∂n of the entire wave is calculated on the sound-soft boundaries.\n# The scattered wave is calculated by convolving ∂u/∂n with the fundamental solution.\n# Then, the total wave is obtained by summing the incident and the scattered waves.\n\nusing ApproxFun, SingularIntegralEquations\ninclude(\"Scatteraux.jl\")\n\nE = 20.\nω = 2π\nui = (x,y) ->  lhelmfs(complex(x,y),-5.0im,E)\n\n# The gravity Helmholtz Green's function.\ng3 = (x,y) ->  lhelmfs(x,y,E)\nr = (x,y) ->  lhelm_riemann(x,y,E)\n\n\ndom = ∪(Segment.([-10.0-3.0im,5.0,-2+5im],[-5.0+0.0im,10.0-3im,2+5im]))\nsp = Space(dom)\ncwsp = CauchyWeight(sp⊗sp,0)\nuiΓ,⨍ = Fun(t->ui(real(t),imag(t)),sp),DefiniteLineIntegral(dom)\n\n@time G = GreensFun(g3,cwsp;method=:unsplit)\n\n@time ∂u∂n = ⨍[G]\\uiΓ\nprintln(\"The length of ∂u∂n is: \",ncoefficients(∂u∂n))\nus = (x,y) ->  -linesum(g3,∂u∂n,complex(x,y))\n", "meta": {"hexsha": "0bf35d30f15827095de0ed1fbe00b2ce2ce54982", "size": 1028, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/GravityHelmholtz.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SingularIntegralEquations.jl-e094c991-5a90-5477-8896-c1e4c9552a1a", "max_stars_repo_head_hexsha": "8a0ca7376ecad020ef8f8beca90686311fbb9f84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2016-12-02T13:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T18:31:48.000Z", "max_issues_repo_path": "examples/GravityHelmholtz.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SingularIntegralEquations.jl-e094c991-5a90-5477-8896-c1e4c9552a1a", "max_issues_repo_head_hexsha": "8a0ca7376ecad020ef8f8beca90686311fbb9f84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2016-12-19T06:02:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:33:33.000Z", "max_forks_repo_path": "examples/GravityHelmholtz.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SingularIntegralEquations.jl-e094c991-5a90-5477-8896-c1e4c9552a1a", "max_forks_repo_head_hexsha": "8a0ca7376ecad020ef8f8beca90686311fbb9f84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-05-16T06:08:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:20:46.000Z", "avg_line_length": 32.125, "max_line_length": 103, "alphanum_fraction": 0.6682879377, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666345, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7632406674275238}}
{"text": "# Local Tangent Space Alignment (LTSA)\n# ---------------------------\n# Principal Manifolds and Nonlinear Dimension Reduction via Local Tangent Space Alignment,\n# Zhang, Zhenyue; Hongyuan Zha (2004),  SIAM Journal on Scientific Computing 26 (1): 313–338.\n# doi:10.1137/s1064827502419154.\n\n\"\"\"\n    LTSA{NN <: AbstractNearestNeighbors, T <: Real} <: AbstractDimensionalityReduction\n\nThe `LTSA` type represents a local tangent space alignment model constructed for `T` type data with a help of the `NN` nearest neighbor algorithm.\n\"\"\"\nstruct LTSA{NN <: AbstractNearestNeighbors, T <: Real} <: AbstractDimensionalityReduction\n    λ::AbstractVector{T}\n    proj::Projection{T}\n    nearestneighbors::NN\n    component::AbstractVector{Int}\nend\n\n## properties\noutdim(R::LTSA) = size(R.proj, 1)\neigvals(R::LTSA) = R.λ\nneighbors(R::LTSA) = R.nearestneighbors.k\nvertices(R::LTSA) = R.component\n\n## show\nsummary(io::IO, R::LTSA) = print(io, \"LTSA(outdim = $(outdim(R)), neighbors = $(neighbors(R)))\")\n\n## interface functions\n\"\"\"\n    fit(LTSA, data; k=12, maxoutdim=2, nntype=BruteForce)\n\nFit a local tangent space alignment model to `data`.\n\n# Arguments\n* `data`: a matrix of observations. Each column of `data` is an observation.\n\n# Keyword arguments\n* `k`: a number of nearest neighbors for construction of local subspace representation\n* `maxoutdim`: a dimension of the reduced space.\n* `nntype`: a nearest neighbor construction class (derived from `AbstractNearestNeighbors`)\n\n# Examples\n```julia\nM = fit(LTSA, rand(3,100)) # construct LTSA model\nR = transform(M)           # perform dimensionality reduction\n```\n\"\"\"\nfunction fit(::Type{LTSA}, X::AbstractMatrix{T};\n        k::Int=12, maxoutdim::Int=2, ɛ::Real=1.0, nntype=BruteForce) where {T<:Real}\n    # Construct NN graph\n    NN = fit(nntype, X, k)\n    D, E = knn(NN, X)\n    G, C = largest_component(SimpleWeightedGraph(adjmat(D,E)))\n    XX = @view X[:, C]\n    n = length(C)\n\n    S = ones(k)./sqrt(k)\n    B = spzeros(T, n,n)\n    for i=1:n\n        II = @view E[:,i]\n        VX = view(XX, :, II)\n\n        # re-center points in neighborhood\n        μ = mean(VX, dims=2)\n        δ_x = VX .- μ\n\n        # Compute orthogonal basis H of θ'\n        θ_t = svd(δ_x).V[:,1:maxoutdim]\n\n        # Construct alignment matrix\n        G = hcat(S, θ_t)\n        B[II, II] .+= Diagonal(fill(one(T), k)) .- G*transpose(G)\n    end\n\n    # Align global coordinates\n    λ, V = decompose(B, maxoutdim)\n    return LTSA{nntype, T}(λ, transpose(V), NN, C)\nend\n\n\"\"\"\n    transform(R::LTSA)\n\nTransforms the data fitted to the local tangent space alignment model `R` into a reduced space representation.\n\"\"\"\ntransform(R::LTSA) = R.proj\n", "meta": {"hexsha": "ef32f960a55f1f459302c0a095f3afdda27ff84c", "size": 2647, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ltsa.jl", "max_stars_repo_name": "yha/ManifoldLearning.jl", "max_stars_repo_head_hexsha": "29a97cce829f0ab8fb172ac27ddfcfff446596a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71, "max_stars_repo_stars_event_min_datetime": "2015-03-15T17:34:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T19:17:06.000Z", "max_issues_repo_path": "src/ltsa.jl", "max_issues_repo_name": "yha/ManifoldLearning.jl", "max_issues_repo_head_hexsha": "29a97cce829f0ab8fb172ac27ddfcfff446596a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2015-02-13T17:18:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T21:36:26.000Z", "max_forks_repo_path": "src/ltsa.jl", "max_forks_repo_name": "yha/ManifoldLearning.jl", "max_forks_repo_head_hexsha": "29a97cce829f0ab8fb172ac27ddfcfff446596a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2015-06-17T17:56:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T21:45:13.000Z", "avg_line_length": 30.7790697674, "max_line_length": 146, "alphanum_fraction": 0.6565923687, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810525948928, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7632406645696534}}
{"text": "\"\"\"\n    swapping_even_odd_bits(n::Int64))\n\nFor a given integer value, all odd bits will be swapped with even bits.\n\n\n# Arguments\n- `n::Int64`: Integer value of the number, which has to be swapped.\n\n\n# Examples\n```julia-repl\njulia> import ClassicAlgorithmsCollections\njulia> ClassicAlgorithmsCollections.function swapping_even_odd_bits(23)\n43\n```\n\n\n# Notes\n---\nThe definition of the even and odd bits:\n```julia-repl\neven_bits = n & 0xAAAAAAAA\nodd_bits = n & 0x55555555\n```\n\"\"\"\nfunction swapping_even_odd_bits(n::Int64)\n    # Defining even and odd bits\n    even_bits = n & 0xAAAAAAAA\n    odd_bits = n & 0x55555555\n\n    # Shifting the even and odd bits\n    even_bits >>= 1\n    odd_bits <<= 1\n    return (even_bits | odd_bits)\nend\n", "meta": {"hexsha": "ff7ff1f921f8b36b2cf2f64864c0c287e234e36d", "size": 727, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BitManipulation/SwappingBits.jl", "max_stars_repo_name": "Anselmoo/ClassicAlgorithmsCollections", "max_stars_repo_head_hexsha": "9f802c4f317492e19b0b8bb6d9020d8450e00772", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BitManipulation/SwappingBits.jl", "max_issues_repo_name": "Anselmoo/ClassicAlgorithmsCollections", "max_issues_repo_head_hexsha": "9f802c4f317492e19b0b8bb6d9020d8450e00772", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2020-09-03T06:47:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-20T06:58:58.000Z", "max_forks_repo_path": "src/BitManipulation/SwappingBits.jl", "max_forks_repo_name": "Anselmoo/ClassicAlgorithmsCollections", "max_forks_repo_head_hexsha": "9f802c4f317492e19b0b8bb6d9020d8450e00772", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6486486486, "max_line_length": 71, "alphanum_fraction": 0.7097661623, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797148356994, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7632223248709105}}
{"text": "module Percolation\n\nexport clustgyration, hklabel, hkmaxclust!, genclust, clustfractal\n\nusing DataStructures\n\n\"\"\"\nFinds the radius of gyration for the largest closed cluster in the percolation grid\n\nPercolation is assumed to occur from top to bottom. Uses the Hoshen-Kopelman algorithm.\n\n# Argument\n\n`grid::Matrix{Bool}`: Represents the grid cells; True if porous (part of the path;\n    can pass through) and False if blocked (can't pass through; no path passes through)\n\n# Returns\n\nThe gyration radius of the largest closed cluster (the largest cluster that doesn't connect\nthe top and bottom of the grid)\n\"\"\"\nfunction clustgyration(grid::BitMatrix)\n    labels, list, clusters = hklabel(grid)\n    if length(clusters) == 0\n        return 0\n    end\n\n    maxlabel = hkmaxclust!(labels, list, clusters)\n    if maxlabel == 0\n        return 0\n    end\n\n    maxclust = Tuple.(findall(x -> x != 0 && hkfind(list, x) == maxlabel, labels))\n    mass = length(maxclust)\n    if mass == 0\n        return 0\n    end\n\n    centerofmass = reduce(.+, maxclust) ./ mass\n    return √(sum(pos -> reduce(.+, (pos .- centerofmass).^2),\n        maxclust) / mass)\nend\n\n\"\"\"\nUses the Hoshen-Kopelman algorithm to label the grid\n\nreturns the labels, label mapping list, and cluster lengths\n\"\"\"\n@inline function hklabel(grid::BitMatrix)\n    height, width = size(grid)\n    labels = zeros(Integer, height, width)\n    list = Vector{Integer}()\n    clusters = Vector{Integer}()\n\n    # first row, special case because of top boundary\n    hkfirstrow!(grid, labels, list, clusters)\n\n    for row in 2:height\n        # first column, special case because of left boundary\n        if grid[row, 1]\n            hkfirstcol!(labels, list, clusters, row)\n        end\n\n        # \"middle\" points, with appropriate neighbors\n        for col in 2:width\n            if grid[row, col]\n                hkiter!(labels, list, clusters, row, col)\n            end\n        end\n    end\n\n    return labels, list, clusters\nend\n\n\"\"\"\nHelper function for `hkpercolate`; Adds new label.\n\"\"\"\n@inline function hknew!(labels::Matrix{<:Integer}, list::Vector{<:Integer},\n        clusters::Vector{<:Integer}, row::Integer, col::Integer)\n    labels[row, col] = length(list) + 1\n    push!(list, labels[row, col])\n    push!(clusters, 0)\nend\n\n\"\"\"\nHelper function for `hkpercolate`; Applies the Hoshen-Kopelman algorithm to the first row.\n\"\"\"\n@inline function hkfirstrow!(grid::BitMatrix, labels::Matrix{<:Integer},\n        list::Vector{<:Integer}, clusters::Vector{<:Integer})\n    width = size(labels)[2]\n    if grid[1, 1]\n        hknew!(labels, list, clusters, 1, 1)\n        clusters[labels[1, 1]] += 1\n    end\n    for col in 2:width\n        if grid[1, col]\n            if labels[1, col - 1] != 0\n                labels[1, col] = hkfind!(list, labels[1, col - 1])\n            else\n                hknew!(labels, list, clusters, 1, col)\n            end\n            clusters[labels[1, col]] += 1\n        end\n    end\nend\n\n\"\"\"\nHelper function for `hkpercolate`; Applies the Hoshen-Kopelman algorithm to the first column.\n\"\"\"\n@inline function hkfirstcol!(labels::Matrix{<:Integer}, list::Vector{<:Integer},\n        clusters::Vector{<:Integer}, row::Integer)\n    if labels[row - 1, 1] != 0\n        labels[row, 1] = hkfind!(list, labels[row - 1, 1])\n    else\n        hknew!(labels, list, clusters, row, 1)\n    end\n    clusters[labels[row, 1]] += 1\nend\n\n\"\"\"\nHelper function for `hkpercolate`; Applies one iteration of the Hoshen-Kopelman algorithm.\n\"\"\"\n@inline function hkiter!(labels::Matrix{<:Integer}, list::Vector{<:Integer},\n        clusters::Vector{<:Integer}, row::Integer, col::Integer)\n    above, left = labels[row - 1, col], labels[row, col - 1]\n    if above == 0\n        if left == 0\n            hknew!(labels, list, clusters, row, col)\n        else\n            labels[row, col] = hkfind!(list, left)\n        end\n    elseif left == 0\n        labels[row, col] = hkfind!(list, above)\n\n    else\n        labels[row, col] = hkunion!(list, clusters, above, left)\n    end\n    clusters[labels[row, col]] += 1\nend\n\n\"\"\"\nUnion function of the union-find algorithm used by the Hoshen-Kopelman algorithm\n\"\"\"\n@inline function hkunion!(list::Vector{<:Integer}, clusters::Vector{<:Integer},\n        x::Integer, y::Integer)\n    root = hkfind!(list, x)\n    dest = hkfind!(list, y)\n    if dest != root\n        list[dest] = root\n        clusters[root] += clusters[dest]\n        clusters[dest] = 0\n    end\n    return root\nend\n\n\"\"\"\nFind function of the union-find algorithm used by the Hoshen-Kopelman algorithm\n\"\"\"\n@inline function hkfind!(list::Vector{<:Integer}, x::Integer)\n    y = x;\n    while list[y] != y\n        y = list[y];\n    end\n    while list[x] != x\n        z = list[x];\n        list[x] = y;\n        x = z;\n    end\n    return y;\nend\n\n\"\"\"\nSame as hkfind!, but doesn't update labels\n\"\"\"\n@inline function hkfind(list::Vector{<:Integer}, x::Integer)\n    while x != list[x]\n        x = list[x];\n    end\n    return x\nend\n\n\"\"\"\nFinds the label of the largest closed cluster (a.k.a. finite cluster).\n\nAlso, sets the size of open clusters (a.k.a. infinite cluster) to zero, hence the !\n\"\"\"\n@inline function hkmaxclust!(labels::Matrix{Integer}, list::Vector{Integer},\n        clusters::Vector{Integer})\n    for root in labels[1, :]\n        if root > 0\n            for dest in labels[end, :]\n                if dest > 0\n                    toplabel = hkfind(list, root)\n                    bottomlabel = hkfind(list, dest)\n                    if toplabel == bottomlabel\n                        clusters[toplabel] = 0\n                    end\n                end\n            end\n        end\n    end\n\n    if maximum(clusters) > 0\n        return argmax(clusters)\n    else\n        return 0\n    end\nend\n\n\"\"\"\nUses a depth-first search algorithm to generate a cluster with the given site probability\n\n# Arguments\n\n- `probability`: the probability a site is generated when growing the cluster\n- `maxsize::Integer` (optional, defaults to 10000): the maximum size of the cluster\n    (breaks the loop after the cluster is grown to this size)\n\n# Returns\n\nan integer matrix (8-bit) with 0 where no site exists, 1 where a cell is generated, and 2\nwhere the growth is stopped\n\"\"\"\nfunction genclust(probability::Float64; maxsize::Integer=10000, crop::Bool=true)\n    cluster = zeros(Int8, maxsize, maxsize)\n    # create \"fences\" to stop the cluster form reaching the bounds of the matrix\n    cluster[1, :] .= 2\n    cluster[:, 1] .= 2\n    cluster[end, :] .= 2\n    cluster[:, end] .= 2\n\n    stack = Stack{Tuple{Integer, Integer}}()\n    seed = (maxsize÷2, maxsize÷2)\n    push!(stack, seed)\n    cluster[seed...] = 1\n\n    clustdfs!(stack, cluster, probability, maxsize)\n\n    if crop\n        return cropclust!(cluster)\n    else\n        return cluster\n    end\nend\n\n\"\"\"\nThe depth-first search algorithm used for `genclust`\n\"\"\"\n@inline function clustdfs!(stack::Stack, cluster::Matrix{<:Integer},\n        probability::Float64, maxsize::Integer)\n    size = 1\n    while !isempty(stack) && size < maxsize\n        site = pop!(stack)\n        for step in ((-1, 0), (0, -1), (0, 1), (1, 0))\n            neighbor = site .+ step\n            if cluster[neighbor...] == 0\n                if rand() <= probability\n                    cluster[neighbor...] = 1\n                    push!(stack, neighbor)\n                    size += 1\n                else\n                    cluster[neighbor...] = 2\n                end\n            end\n        end\n    end\nend\n\n\"\"\"\nfinds the mass and radius of gyration of the cluster from the output of `genclust`\n\"\"\"\nfunction clustfractal(cluster::Matrix{Int8})\n    clust = Tuple.(findall(x -> x == 1, cluster))\n    mass = length(clust)\n    if mass == 0\n        return 0\n    end\n\n    centerofmass = reduce(.+, clust) ./ mass\n    return mass, √(sum(pos -> reduce(.+, (pos .- centerofmass).^2), clust) / mass)\nend\n\n\"\"\"\ncrop the `genclust` function output to remove excess zeros\n\"\"\"\n@inline function cropclust!(cluster::Matrix{<:Integer})\n    height, width = size(cluster)\n    top = bottom = height ÷ 2\n    left = right = width ÷ 2\n\n    while 1 in cluster[top + 1, 2:end-1] || 2 in cluster[top + 1, 2:end-1]\n        top += 1\n    end\n    while 1 in cluster[bottom - 1, 2:end-1] || 2 in cluster[bottom - 1, 2:end-1]\n        bottom -= 1\n    end\n    while 1 in cluster[2:end-1, left - 1] || 2 in cluster[2:end-1, left - 1]\n        left -= 1\n    end\n    while 1 in cluster[2:end-1, right + 1] || 2 in cluster[2:end-1, right + 1]\n        right += 1\n    end\n\n    return cluster[bottom:top, left:right]\nend\n\nend\n", "meta": {"hexsha": "182a125fabd75ce533413b88733c8e5bec00cc23", "size": 8503, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ps4-percolation-random-walk/p1-3-percolation/Percolation.jl", "max_stars_repo_name": "slhshamloo/comp-phys", "max_stars_repo_head_hexsha": "04d6759e0eb9d7e16e2781417d389bc15e22b01b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ps4-percolation-random-walk/p1-3-percolation/Percolation.jl", "max_issues_repo_name": "slhshamloo/comp-phys", "max_issues_repo_head_hexsha": "04d6759e0eb9d7e16e2781417d389bc15e22b01b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ps4-percolation-random-walk/p1-3-percolation/Percolation.jl", "max_forks_repo_name": "slhshamloo/comp-phys", "max_forks_repo_head_hexsha": "04d6759e0eb9d7e16e2781417d389bc15e22b01b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6071428571, "max_line_length": 93, "alphanum_fraction": 0.6009643655, "num_tokens": 2401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7632223152901388}}
{"text": "\"\"\"\n    ExactReach\n\nExactReach performs exact reachability analysis to compute the output reachable set for a network.\n\n# Problem requirement\n1. Network: any depth, ReLU activation\n2. Input: HPolytope\n3. Output: HPolytope\n\n# Return\n`ReachabilityResult`\n\n# Method\nExact reachability analysis.\n\n# Property\nSound and complete.\n\n# Reference\n[W. Xiang, H.-D. Tran, and T. T. Johnson,\n\"Reachable Set Computation and Safety Verification for Neural Networks with ReLU Activations,\"\n*ArXiv Preprint ArXiv:1712.08163*, 2017.](https://arxiv.org/abs/1712.08163)\n\"\"\"\nstruct ExactReach end\n\nfunction solve(solver::ExactReach, problem::Problem)\n    reach = forward_network(solver, problem.network, problem.input)\n    return check_inclusion(reach, problem.output)\nend\n\nfunction forward_layer(solver::ExactReach, layer::Layer, input::Vector{HPolytope})\n    output = Vector{HPolytope}(undef, 0)\n    for i in 1:length(input)\n        input[i] = linear_transformation(layer, input[i])\n        append!(output, forward_partition(layer.activation, input[i]))\n    end\n    return output\nend\n\nfunction forward_layer(solver::ExactReach, layer::Layer, input::HPolytope)\n    input = linear_transformation(layer, input)\n    return forward_partition(layer.activation, input)\nend\n\nfunction forward_partition(act::ReLU, input::HPolytope)\n    n = dim(input)\n    output = Vector{HPolytope}(undef, 0)\n    C, d = tosimplehrep(input)\n    dh = [d; zeros(n)]\n    for h in 0:2^n-1\n        P = getP(h, n)\n        Ch = [C; I - 2P]\n        input_h = HPolytope(Ch, dh)\n        if !isempty(input_h)\n            push!(output, linear_transformation(Matrix(P), input_h))\n        end\n    end\n    return output\nend\n\nfunction getP(h::Int64, n::Int64)\n    str = string(h-1, pad = n, base = 2)\n    vec = Vector{Int64}(undef, n)\n    for i in 1:n\n        vec[i] = ifelse(str[i] == '1', 1, 0)\n    end\n    return Diagonal(vec)\nend", "meta": {"hexsha": "d789ceedfa2318928ba33d5abbbbe168120a9929", "size": 1871, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/reachability/exactReach.jl", "max_stars_repo_name": "awesome-archive/NeuralVerification.jl", "max_stars_repo_head_hexsha": "ea68308ca1594787f508cde583e1e34b4b3a25db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-02T00:36:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-02T00:36:58.000Z", "max_issues_repo_path": "src/reachability/exactReach.jl", "max_issues_repo_name": "awesome-archive/NeuralVerification.jl", "max_issues_repo_head_hexsha": "ea68308ca1594787f508cde583e1e34b4b3a25db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/reachability/exactReach.jl", "max_forks_repo_name": "awesome-archive/NeuralVerification.jl", "max_forks_repo_head_hexsha": "ea68308ca1594787f508cde583e1e34b4b3a25db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-02T00:41:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-02T00:41:32.000Z", "avg_line_length": 27.115942029, "max_line_length": 98, "alphanum_fraction": 0.6867985035, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7632223151165823}}
{"text": "# Axis-aligned multivariate normal (i.e., independent entries, i.e., diagonal covariance matrix) using conjugate prior.\r\nmodule MVNaaC\r\n\r\nmodule MVNaaCmodel # submodule for component family definitions\r\nexport Theta, Data, log_marginal, new_theta, Theta_clear!, Theta_adjoin!, Theta_remove!,\r\n       Hyperparameters, construct_hyperparameters, update_hyperparameters!\r\n\r\nconst Data = Array{Float64,1}\r\n\r\ntype Theta\r\n    n::Int64                 # number of data points assigned to this cluster\r\n    sum_x::Array{Float64,1}  # sum of the data points x assigned to this cluster\r\n    sum_xx::Array{Float64,1} # sum of x.*x for the data points assigned to this cluster\r\n    Theta(d) = (p=new(); p.n=0; p.sum_x=zeros(d); p.sum_xx=zeros(d); p)\r\nend\r\n\r\nnew_theta(H) = Theta(H.d)\r\n\r\nTheta_clear!(p) = (p.sum_x[:] = 0.; p.sum_xx[:] = 0.; p.n = 0)\r\n\r\nTheta_adjoin!(p,x) = (for i=1:length(x); p.sum_x[i] += x[i]; p.sum_xx[i] += x[i]*x[i]; end; p.n += 1)\r\nTheta_remove!(p,x) = (for i=1:length(x); p.sum_x[i] -= x[i]; p.sum_xx[i] -= x[i]*x[i]; end; p.n -= 1)\r\n\r\n# In each dimension independently,\r\n# X_1,...,X_n ~ Normal(mu,1/lambda) with Normal(mu|m,1/(c*lambda))Gamma(lambda|a,b) prior on mean=mu, precision=lambda.\r\nfunction log_marginal(p,H)\r\n    n = p.n\r\n    LB = 0.0\r\n    # For each dimension\r\n    for i = 1:H.d\r\n        ## update to b\r\n        t1 = H.b + 0.5 * p.sum_xx[i] * H.alpha_wt ###\r\n        t2 = 0.5 * p.sum_x[i]*p.sum_x[i] / n * H.alpha_wt\r\n        t3 = 0.5 * H.c * n * H.alpha_wt * (p.sum_x[i]/n - H.m)^2 / (H.c + n * H.alpha_wt)\r\n        #LB += log(H.b + 0.5 * p.sum_xx[i] - 0.5 * p.sum_x[i]*p.sum_x[i] / n + \\\r\n        #          0.5 * H.c * n * (p.sum_x[i]/n - H.m)^2/(H.c + n))\r\n        LB += log(t1 - t2 + t3)\r\n    end\r\n\r\n    # update to a\r\n    aa = H.a + 0.5 * n * H.alpha_wt ##\r\n    # log term w/ update to c\r\n    cc = 0.5 * log(H.c + n * H.alpha_wt) ##\r\n\r\n    term = H.d * (H.constant - 0.5*n*log(2*pi)*H.alpha_wt - cc + H.log_Ga[p.n]) - aa * LB\r\n    #return H.d * (H.constant - 0.5*n*log(2*pi) - 0.5*log(H.c+n) + H.log_Ga[n]) - (H.a+0.5*n) * LB\r\n    return term\r\nend\r\n\r\nfunction log_marginal(x,p,H)\r\n    Theta_adjoin!(p,x)\r\n    result = log_marginal(p,H)\r\n    Theta_remove!(p,x)\r\n    return result\r\nend\r\n\r\ntype Hyperparameters\r\n    d::Int64    # dimension\r\n    m::Float64  # prior mean of mu's\r\n    c::Float64  # prior precision multiplier for mu's\r\n    a::Float64  # prior shape of lambda's\r\n    b::Float64  # prior rate of lambda's\r\n    constant::Float64\r\n    log_Ga::Array{Float64,1}\r\n    alpha_wt::Float64 # alpha weight (not technically a hyperparameter)\r\nend\r\n\r\nfunction construct_hyperparameters(options)\r\n    x = options.x\r\n    n = length(x)\r\n    d = length(x[1])\r\n    mu = mean(x)\r\n    v = mean([xi.*xi for xi in x]) - mu.*mu  # sample variance\r\n    @assert(all(abs.(mu) .< 1e-10) && all(abs.(v - 1.0) .< 1e-10), \"Data must be normalized to zero mean, unit variance.\")\r\n    m = 0.0\r\n    c = 1.0\r\n    a = 1.0\r\n    b = 1.0\r\n\r\n    # specify the weight\r\n    alpha_eval = eval(parse(options.alpha_wt_str))\r\n    alpha_wt_fn(n) = Base.invokelatest(alpha_eval, n)\r\n    alpha_wt = alpha_wt_fn(options.n)\r\n\r\n    log_Ga = lgamma.(a+0.5*(1:n+1) * alpha_wt)\r\n\r\n    # normalizing constant of the log Normal-gamma pdf involving hyperparams\r\n    constant = 0.5*log(c) + a*log(b) - lgamma(a)\r\n\r\n    return Hyperparameters(d,m,c,a,b,constant,log_Ga, alpha_wt)\r\nend\r\n\r\nfunction update_hyperparameters!(H,theta,list,t,x,z)\r\n    #error(\"update_hyperparameters is not yet implemented.\")\r\nend\r\n\r\nend # module MVNaaCmodel\r\nusing .MVNaaCmodel\r\n\r\n# Include generic code\r\ninclude(\"generic.jl\")\r\n\r\n# Include core sampler code\r\ninclude(\"coreConjugate.jl\")\r\n\r\nend # module MVNaaC\r\n\r\n\r\n\r\n", "meta": {"hexsha": "0965c0015807f3daccdac3f8f5b6aee9c713ede7", "size": 3679, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MVNaaC.jl", "max_stars_repo_name": "dicai/BayesianMixtures.jl", "max_stars_repo_head_hexsha": "4b71c07b79908891f74aed76f57d4493290c9e63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MVNaaC.jl", "max_issues_repo_name": "dicai/BayesianMixtures.jl", "max_issues_repo_head_hexsha": "4b71c07b79908891f74aed76f57d4493290c9e63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MVNaaC.jl", "max_forks_repo_name": "dicai/BayesianMixtures.jl", "max_forks_repo_head_hexsha": "4b71c07b79908891f74aed76f57d4493290c9e63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4454545455, "max_line_length": 123, "alphanum_fraction": 0.6004349008, "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7632223117702319}}
{"text": "amaxmin(x::T, y::T) where {T} = ifelse( abs(x) < abs(y), (y,x), (x,y) )\nfunction amaxmin(x::T, y::T, z::T) where {T}\n     y, z = amaxmin(y, z)\n     x, z = amaxmin(x, z)\n     x, y = amaxmin(x, y)\n     return x, y, z\nend\nfunction amaxmin(a::T, b::T, c::T, d::T) where {T}\n    a, b = amaxmin(a, b)\n    c, d = amaxmin(c, d)\n    a, c = amaxmin(a, c)\n    b, d = amaxmin(b, d)\n    b, c = amaxmin(b, c)\n     \n    return a, b, c, d\nend\n\n\"\"\"\n    two_sum(a, b)\n\nComputes `hi = fl(a+b)` and `lo = err(a+b)`.\n\"\"\"\n@inline function two_sum(a::T, b::T) where {T<:Real}\n    hi = a + b\n    v  = hi - a\n    lo = (a - (hi - v)) + (b - v)\n    return hi, lo\nend\n\n\"\"\"\n    one_sum(a, b)\n\nComputes `fl(a+b)`.\n\"\"\"\n@inline function one_sum(a::T, b::T) where {T<:Real}\n    return a + b\nend\n\n\"\"\"\n   three_sum(a, b, c)\n    \nComputes `hi = fl(a+b+c)` and `md = err(a+b+c), lo = err(md)`.\n\"\"\"\nfunction three_sum(a::T, b::T, c::T) where {T}\n    hi, md, lo = amaxmin(a, b, c) \n    md, lo = two_hilo_sum(md, lo)\n    hi, md = two_hilo_sum(hi, md)\n    md, lo = two_hilo_sum(md, lo)\n    return hi, md, lo\nend\n\n\"\"\"\n    two_sum(a, b, c)\n    \nComputes `hi = fl(a+b+c)` and `lo = err(a+b+c)`.\n\"\"\"\n@inline function two_sum(a::T, b::T, c::T) where {T}\n    hi, md, lo = amaxmin(a, b, c) \n    md, lo = two_hilo_sum(md, lo)\n    hi, md = two_hilo_sum(hi, md)\n    md += lo\n    return hi, md\nend\n\n\"\"\"\n    one_sum(a, b, c)\n    \nComputes `fl(a+b+c)`\n\"\"\"\n@inline function one_sum(a::T,b::T,c::T) where {T}\n    md, lo = two_sum(b, c) \n    hi, md = two_sum(a, md)\n    md, lo = two_sum(md, lo)\n    hi, md = two_hilo_sum(hi, md)\n    md = md + lo\n    hi = hi + md\n    return hi\nend\n\n\"\"\"\n    four_sum(a, b, c, d)\n    \nComputes `hi = fl(a+b+c+d)` and `hm = err(a+b+c+d), ml = err(hm), lo = err(ml)`.\n\"\"\"\nfunction four_sum(a::T,b::T,c::T,d::T) where {T}\n    t0, t1 = two_sum(a,  b)\n    t2, t3 = two_sum(c,  d)\n    hi, t4 = two_sum(t0, t2)\n    t5, lo = two_sum(t1, t3)\n    hm, ml = two_sum(t4, t5)\n    ml, lo = two_hilo_sum(ml, lo)\n    hm, ml = two_hilo_sum(hm, ml)\n    hi, hm = two_hilo_sum(hi,hm)\n    return hi, hm, ml, lo\nend\n\n\n\"\"\"\n    three_sum(a, b, c, d)\n    \nComputes `hi = fl(a+b+c+d)` and `md = err(a+b+c+d), lo = err(md)`.\n\"\"\"\nfunction three_sum(a::T,b::T,c::T,d::T) where {T}\n    t0, t1 = two_sum(a,  b)\n    t2, t3 = two_sum(c,  d)\n    hi, t4 = two_sum(t0, t2)\n    t5, t6 = two_sum(t1, t3)\n    md, lo = two_sum(t4, t5)\n    lo = lo + t6\n    md, lo = two_hilo_sum(md, lo)\n    hi, md = two_hilo_sum(hi, md)\n    return hi, md, lo\nend\n\n\"\"\"\n    two_sum(a, b, c, d)\n    \nComputes `hi = fl(a+b+c+d)` and `lo = err(a+b+c+d)`.\n\"\"\"\nfunction two_sum(a::T,b::T,c::T,d::T) where {T}\n    t0, t1 = two_sum(a,  b)\n    t2, t3 = two_sum(c,  d)\n    hi, t4 = two_sum(t0, t2)\n    t5, t6 = two_sum(t1, t3)\n    lo, t7 = two_sum(t4, t5)\n    t7 = t7 + t6\n    lo, t7 = two_hilo_sum(lo, t7)\n    hi, lo = two_hilo_sum(hi, lo)\n    return hi, lo\nend\n\n\"\"\"\n    one_sum(a, b, c, d)\n    \nComputes `fl(a+b+c+d)`.\n\"\"\"\nfunction one_sum(a::T,b::T,c::T,d::T) where {T}\n    t0, t1 = two_sum(a,  b)\n    t2, t3 = two_sum(c,  d)\n    hi, t4 = two_sum(t0, t2)\n    t5, t6 = two_sum(t1, t3)\n    lo, t7 = two_sum(t4, t5)\n    t7 = t7 + t6\n    lo, t7 = two_hilo_sum(lo, t7)\n    hi = hi + lo\n    return hi\nend\n\n\n\nfunction vec_sum(x0::T, x1::T, x2::T, x3::T) where {T}\n    s3 = x3\n    s2, e3 = two_sum(x2, s3)\n    s1, e2 = two_sum(x1, s2)\n    s0, e1 = two_sum(x0, s1)\n    return s0,e1,e2,e3\nend\n\nfunction vsum_errbranch(x::NTuple{4,T}) where {T}\n    y = zeros(T, 4)\n    r = zeros(T, 4)\n    e = zeros(T, 4)\n    j = 1\n    e[1] = x[1]\n    for i = 1:2\n        r[i], t = two_sum(e[i], x[i+1])\n        if t !== zero(T)\n            y[j] = r[i]\n            e[i+1] = t\n            j += 1\n        else    \n            e[i+1] = r[i]\n        end    \n    end\n    y[j], y[j+1] = two_sum(e[3], x[4])\n    return y\nend\n\nfunction foursum(x1::T, x2::T, x3::T, x4::T) where {T}\n    a1, a2 = two_sum(x1, x2)\n    b1, b2 = two_sum(x3, x4)\n    c1, c2 = two_sum(a1, b1)\n    d1, d2 = two_sum(a2, b2)\n    e1to4 = vec_sum(c1,c2,d1,d2)\n    y = vsum_errbranch(e1to4)\n    return (y...,)\nend\n\n\"\"\"\n    five_sum(a, b, c, d, e)\n    \nComputes `s = fl(a+b+c+d+e)` and \n    `e1 = err(a+b+c+d), e2 = err(e1), e3 = err(e2), e4 = err(e3)`.\n\"\"\"\nfunction five_sum(v::T, w::T, x::T, y::T, z::T) where {T}\n    t0, t4 = two_sum(y, z)\n    t0, t3 = two_sum(x, t0)\n    t0, t2 = two_sum(w, t0)\n    a, t1  = two_sum(v, t0)\n    t0, t3 = two_sum(t3, t4)\n    t0, t2 = two_sum(t2, t0)\n    b, t1  = two_sum(t1, t0)\n    t0, t2 = two_sum(t2, t3)\n    c, t1  = two_sum(t1, t0)\n    d, e   = two_sum(t1, t2)\n    return a, b, c, d, e\nend\n\n\"\"\"\n    two_diff(a, b)\n\nComputes `s = fl(a-b)` and `e = err(a-b)`.\n\"\"\"\n@inline function two_diff(a::T, b::T) where {T}\n    hi = a - b\n    v  = hi - a\n    lo = (a - (hi - v)) - (b + v)\n    return hi, lo\nend\n\n\"\"\"\n    three_diff(a, b, c)\n    \nComputes `s = fl(a-b-c)` and `e1 = err(a-b-c), e2 = err(e1)`.\n\"\"\"\nfunction three_diff(a::T,b::T,c::T) where {T}\n    s, t = two_diff(-b, c)\n    x, u = two_sum(a, s)\n    y, z = two_sum(u, t)\n    x, y = two_hilo_sum(x, y)\n    return x, y, z\nend\n\n\"\"\"\n    four_diff(a, b, c, d)\n    \nComputes `hi = fl(a-b-c-d)` and `hm = err(a-b-c-d), ml = err(hm), lo = err(ml)`.\n\"\"\"\nfunction four_diff(a::T,b::T,c::T,d::T) where {T}\n    t0, t1 = two_diff(a ,  b)\n    t0, t2 = two_diff(t0,  c)\n    hi, t3 = two_diff(t0,  d)\n    t0, t1 = two_sum(t1, t2)\n    hm, t2 = two_sum(t0, t3) # here, t0 >= t3\n    ml, lo = two_sum(t1, t2)\n    return hi, hm, ml, lo\nend\n\n\"\"\"\n    two_square(a)\n\nComputes `hi = fl(a*a)` and `lo = fl(err(a*a))`.\n\"\"\"\n@inline function two_square(a::T) where {T}\n    hi = a * a\n    lo = fma(a, a, -hi)\n    hi, lo\nend\n\n\"\"\"\n    two_prod(a, b)\n\nComputes `hi = fl(a*b)` and `lo = fl(err(a*b))`.\n\"\"\"\n@inline function two_prod(a::T, b::T) where {T}\n    hi = a * b\n    lo = fma(a, b, -hi)\n    hi, lo\nend\n\n@inline max_min(a,b) = abs(a) < abs(b) ? (b,a) : (a,b)\n\n\"\"\"\n    three_prod(a, b, c)\n    \nComputes `hi = fl(a*b*c)` and `md = err(a*b*c), lo = err(md)`.\n\"\"\"\nfunction three_prod(a::T, b::T, c::T) where {T}\n    a, b = max_min(a,b)\n    a, c = max_min(a,c)\n    b, c = max_min(b,c)\n    abhi, ablo = two_prod(a, b)\n    hi, abhiclo = two_prod(abhi, c)\n    ablochi, abloclo = two_prod(ablo, c)\n    md, lo, tmp  = three_sum(ablochi, abhiclo, abloclo)\n    hi, md = two_sum(hi, md)\n    return hi, md, lo\nend\n\n\n\n#=\n   three_fma algorithm from\n   Sylvie Boldo and Jean-Michel Muller\n   Some Functions Computable with a Fused-mac\n=#\n\n\"\"\"\n   three_fma(a, b, c)\n\nComputes `hi = fl(fma(a,b,c))` and `md = fl(err(fma(a,b,c))), lo = fl(err(md))`.\n\"\"\"\nfunction three_fma(a::T, b::T, c::T) where {T}\n    hi = fma(a, b, c) \n    hi0, lo0 = two_prod(a, b)\n    hi1, lo1 = two_sum(c, lo0)\n    hi2, lo2 = two_sum(hi0, hi1)\n    y = ((hi2 - hi) + lo2)\n    md, lo = two_hilo_sum(y, lo1)\n    return hi, md, lo\nend\n\n\"\"\"\n   two_fma(a, b, c)\n\nComputes `hi = fl(fma(a,b,c))` and `lo = fl(err(fma(a,b,c)))`.\n\"\"\"\nfunction two_fma(a::T, b::T, c::T) where {T}\n    hi = fma(a, b, c) \n    hi0, lo0 = two_prod(a, b)\n    hi1, lo1 = two_sum(c, lo0)\n    hi2, lo2 = two_sum(hi0, hi1)\n    lo = ((hi2 - hi) + lo2) + lo1\n    return hi, lo\nend\n\n\"\"\"\n   two_muladd(a, b, c)\n\nComputes `hi = fl(muladd(a,b,c))` and `lo = fl(err(muladd(a,b,c)))`.\n\"\"\"\nfunction two_muladd(a::T, b::T, c::T) where {T}\n    hi = fma(a, b, c)\n    lo = fma(a, b, c-hi)\n    return hi, lo\nend    \n\n# with arguments sorted by magnitude\n\n\"\"\"\n    two_hilo_sum(a, b)\n\n*unchecked* requirement `|a| ≥ |b|`\n\nComputes `hi = fl(a+b)` and `lo = err(a+b)`.\n\"\"\"\n@inline function two_hilo_sum(a::T, b::T) where {T}\n    hi = a + b\n    lo = b - (hi - a)\n    return hi, lo\nend\n\n\"\"\"\n    two_lohi_sum(a, b)\n\n*unchecked* requirement `|b| ≥ |a|`\n\nComputes `hi = fl(a+b)` and `lo = err(a+b)`.\n\"\"\"\n@inline function two_lohi_sum(a::T, b::T) where {T}\n    hi = b + a\n    lo = a - (hi - b)\n    return hi, lo\nend\n\n\"\"\"\n    two_hilo_diff(a, b)\n    \n*unchecked* requirement `|a| ≥ |b|`\n\nComputes `hi = fl(a-b)` and `lo = err(a-b)`.\n\"\"\"\n@inline function two_hilo_diff(a::T, b::T) where {T}\n    hi = a - b\n    lo = (a - hi) - b\n    hi, lo\nend\n\n\"\"\"\n    two_lohi_diff(a, b)\n    \n*unchecked* requirement `|b| ≥ |a|`\n\nComputes `hi = fl(a-b)` and `lo = err(a-b)`.\n\"\"\"\n@inline function two_lohi_diff(a::T, b::T) where {T}\n    hi = b - a\n    lo = (b - hi) - a\n    hi, lo\nend\n\n\"\"\"\n    two_hilo_sum(a, b, c)\n    \n*unchecked* requirement `|a| ≥ |b| ≥ |c|`\n\nComputes `hi = fl(a+b+c)` and `lo = err(a+b+c)`.\n\"\"\"\nfunction two_hilo_sum(a::T, b::T, c::T) where {T}\n    lo, t = two_hilo_sum(b, c)\n    hi, lo = two_sum(a, lo)\n    lo += t\n    hi, lo = two_hilo_sum(hi, lo)\n    return hi, lo\nend\n\n\"\"\"\n    three_hilo_sum(a, b, c)\n    \n*unchecked* requirement `|a| ≥ |b| ≥ |c|`\n\nComputes `x = fl(a+b+c)` and `y = err(a+b+c), z = err(y)`.\n\"\"\"\nfunction three_hilo_sum(a::T, b::T, c::T) where {T}\n    md, lo = two_hilo_sum(b, c)\n    hi, md = two_sum(a, md)\n    md, lo = two_hilo_sum(md, lo)\n    hi, md = two_hilo_sum(hi, md)\n    return hi,md,lo\nend\n\n\"\"\"\n    three_lohi_sum(a, b, c)\n    \n*unchecked* requirement `|c| ≥ |b| ≥ |a|`\n\nComputes `x = fl(a+b+c)` and `y = err(a+b+c), z = err(y)`.\n\"\"\"\nfunction three_lohi_sum(a::T,b::T,c::T) where {T}\n    md, lo = two_lohi_sum(a, b)\n    hi, md = two_sum(c, md)\n    md, lo = two_lohi_sum(lo, md)\n    hi, md = two_lohi_sum(md, hi)\n    return hi,md,lo\nend\n\n\"\"\"\n    three_hilo_diff(a, b, c)\n    \n*unchecked* requirement `|a| ≥ |b| ≥ |c|`\n\nComputes `x = fl(a-b-c)` and `y = err(a-b-c), z = err(y)`.\n\"\"\"\nfunction three_hilo_diff(a::T,b::T,c::T) where {T}\n    md, lo = two_hilo_sum(-b, -c)\n    hi, md = two_sum(a, md)\n    md, lo = two_hilo_sum(md, lo)\n    hi, md = two_hilo_sum(hi, md)\n    return hi,md,lo \nend\n\n\"\"\"\n    three_lohi_diff(a, b, c)\n    \n*unchecked* requirement `|c| ≥ |b| ≥ |a|`\n\nComputes `x = fl(a-b-c)` and `y = err(a-b-c), z = err(y)`.\n\"\"\"\nfunction three_lohi_diff(c::T,b::T,a::T) where {T}\n    three_lohi_sum(c, -b, -a)\nend\n\n\"\"\"\n    four_hilo_sum(a, b, c, d)\n    \n*unchecked* requirement `|a| ≥ |b| ≥ |c| ≥ |d|`\n\nComputes `hi = fl(a+b+c+d)` and `hm = err(a+b+c+d), ml = err(hm), lo = err(ml)`.\n\"\"\"\nfunction four_hilo_sum(a::T,b::T,c::T,d::T) where {T}\n    t0, t1 = two_hilo_sum(a ,  b)\n    t0, t2 = two_hilo_sum(t0,  c)\n    hi, t3 = two_hilo_sum(t0,  d)\n    t0, t1 = two_hilo_sum(t1, t2)\n    hm, t2 = two_hilo_sum(t0, t3) # here, t0 >= t3\n    ml, lo = two_hilo_sum(t1, t2)\n    return hi, hm, ml, lo\nend\n\n\"\"\"\n    four_lohi_sum(a, b, c, d)\n    \n*unchecked* requirement `|d| ≥ |c| ≥ |b| ≥ |a|`\n\nComputes `hi = fl(a+b+c+d)` and `hm = err(a+b+c+d), ml = err(hm), lo = err(ml)`.\n\"\"\"\nfunction four_lohi_sum(d::T,c::T,b::T,a::T) where {T}\n    t0, t1 = two_hilo_sum(a ,  b)\n    t0, t2 = two_hilo_sum(t0,  c)\n    hi, t3 = two_hilo_sum(t0,  d)\n    t0, t1 = two_hilo_sum(t1, t2)\n    hm, t2 = two_hilo_sum(t0, t3)\n    ml, lo = two_hilo_sum(t1, t2)\n    return hi, hm, ml, lo\nend\n\n\"\"\"\n    four_hilo_diff(a, b, c, d)\n    \n*unchecked* requirement `|a| ≥ |b| ≥ |c| ≥ |d|`\n\nComputes `hi = fl(a-b-c-d)` and `hm = err(a-b-c-d), ml = err(hm), lo = err(ml)`.\n\"\"\"\nfunction four_hilo_diff(a::T,b::T,c::T,d::T) where {T}\n    t0, t1 = two_hilo_diff(a,  b)\n    t0, t2 = two_hilo_diff(t0,  c)\n    hi, t3 = two_hilo_diff(t0,  d)\n    t0, t1 = two_hilo_sum(t1, t2)\n    hm, t2 = two_hilo_sum(t0, t3) # here, t0 >= t3\n    ml, lo = two_hilo_sum(t1, t2)\n    return hi, hm, ml, lo\nend\n\n\"\"\"\n    four_hilo_diff(a, b, c, d)\n    \n*unchecked* requirement `|d| ≥ |c| ≥ |b| ≥ |a|`\n\nComputes `hi = fl(a-b-c-d)` and `hm = err(a-b-c-d), ml = err(hm), lo = err(ml)`.\n\"\"\"\nfunction four_lohi_diff(d::T,c::T,b::T,a::T) where {T}\n    t0, t1 = two_hilo_diff(a,  b)\n    t0, t2 = two_hilo_diff(t0,  c)\n    hi, t3 = two_hilo_diff(t0,  d)\n    t0, t1 = two_hilo_sum(t1, t2)\n    hm, t2 = two_hilo_sum(t0, t3) # here, t0 >= t3\n    ml, lo = two_hilo_sum(t1, t2)\n    return hi, hm, ml, lo\nend\n", "meta": {"hexsha": "8afad97c9f2ce8b12277c2ece8d23fd4c3daf860", "size": 11752, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/errorfree_all.jl", "max_stars_repo_name": "JeffreySarnoff/ErrorfreeArithmetic.jl", "max_stars_repo_head_hexsha": "01fc651ef75ebbdf2d6c4959f32a88779f6bebbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-08-07T17:03:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T11:37:33.000Z", "max_issues_repo_path": "src/errorfree_all.jl", "max_issues_repo_name": "JeffreySarnoff/ErrorfreeArithmetic.jl", "max_issues_repo_head_hexsha": "01fc651ef75ebbdf2d6c4959f32a88779f6bebbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2017-04-07T15:19:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-15T03:34:13.000Z", "max_forks_repo_path": "src/errorfree_all.jl", "max_forks_repo_name": "JeffreySarnoff/ErrorfreeArithmetic.jl", "max_forks_repo_head_hexsha": "01fc651ef75ebbdf2d6c4959f32a88779f6bebbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2017-04-10T00:18:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:54:51.000Z", "avg_line_length": 22.1735849057, "max_line_length": 80, "alphanum_fraction": 0.5175289312, "num_tokens": 4920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7631908341188467}}
{"text": "\nfunction checkSVDDone(S::Vector,\n                      thresh::Float64)\n  N = length(S)\n  (N <= 1 || thresh < 0.0) && return (true,1)\n  S1t = S[1]*thresh\n  start = 2\n  while start <= N\n    (S[start] < S1t) && break\n    start += 1\n  end\n  if start >= N\n    return (true,N)\n  end\n  return (false,start)\nend\n\nfunction svd_recursive(M::AbstractMatrix;\n                      thresh::Float64=1E-3,\n                      north_pass::Int=2)\n  Mr,Mc = size(M)\n\n  if Mr > Mc\n    V,S,U = svd_recursive(transpose(M))\n    conj!(U)\n    conj!(V)\n    return U,S,V\n  end\n\n  #rho = BLAS.gemm('N','T',-1.0,M,M) #negative to sort eigenvalues greatest to smallest\n  rho = -M*M' #negative to sort eigenvalues in decreasing order\n  D,U = eigen(Hermitian(rho),1:size(rho,1))\n\n  Nd = length(D)\n\n  V = M'*U\n\n  V,R = qr_positive(V)\n  for n=1:Nd\n    D[n] = R[n,n]\n  end\n\n  (done,start) = checkSVDDone(D,thresh)\n\n  done && return U,D,V\n\n  u = view(U,:,start:Nd)\n  v = view(V,:,start:Nd)\n\n  b = u'*(M*v)\n  bu,bd,bv = svd_recursive(b,\n                          thresh=thresh,\n                          north_pass=north_pass)\n\n  u .= u*bu\n  v .= v*bv\n  view(D,start:Nd) .= bd\n  \n  return U,D,V\nend\n\n# TODO: maybe move to another location?\n# Include options for other svd algorithms\nfunction polar(M::AbstractMatrix)\n  U,S,V = svd(M) # calls LinearAlgebra.svd(_)\n  return U*V', V*Diagonal(S)*V'\nend\n\n", "meta": {"hexsha": "21594332bec36c98ed421d1b8364a14ee97c51ca", "size": 1368, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "NDTensors/src/svd.jl", "max_stars_repo_name": "emstoudenmire/ITensors.jl", "max_stars_repo_head_hexsha": "794a94e9c1fb7654b3cdebcc6a51464d01715f3a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-10T06:23:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T06:23:09.000Z", "max_issues_repo_path": "NDTensors/src/svd.jl", "max_issues_repo_name": "emstoudenmire/ITensors.jl", "max_issues_repo_head_hexsha": "794a94e9c1fb7654b3cdebcc6a51464d01715f3a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NDTensors/src/svd.jl", "max_forks_repo_name": "emstoudenmire/ITensors.jl", "max_forks_repo_head_hexsha": "794a94e9c1fb7654b3cdebcc6a51464d01715f3a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-19T18:26:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-19T18:26:33.000Z", "avg_line_length": 19.8260869565, "max_line_length": 87, "alphanum_fraction": 0.5606725146, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7631908249987647}}
{"text": "# 'cstrt_bwinja_ngon' provides the vertices coordinates (a,b) of a small\r\n# n-gon for n = 2m and m >= 3\r\nfunction cstrt_bwinja_ngon(n)\r\nif mod(n,2) == 0 && n>=6\r\n    # initialization\r\n    v(u) = (pi/2-u)/(n/2-1);\r\n    d(u) = asin(sin(u)+sin(u+3*v(u)/2)/(2*cos(v(u)/2)))-u-v(u);\r\n    A(u) = sin(u)+sin(2*v(u))-sin(v(u)+d(u))+\r\n    (n/2-3)*(sin(v(u))-tan(v(u)/2))+(cos(v(u)-d(u))-cos(2*v(u))-1/2)*tan(v(u)/2);\r\n    F(u) = -A(u);\r\n    res = optimize(F,pi/(2*n-2),pi/n);\r\n    u0 = Optim.minimizer(res);\r\n    v0 = (pi/2-u0)/(n/2-1);\r\n    d0 = asin(sin(u0)+sin(u0+3*v0/2)/(2*cos(v0/2)))-u0-v0;\r\n    x = zeros(Int(n/2));\r\n    x[1] = u0;\r\n    x[2] = v0+d0;\r\n    x[3] = v0-d0;\r\n    if n >= 8\r\n        x[4:end] .= v0;\r\n    end\r\n    # construction\r\n    a = zeros(n-1); b = zeros(n-1);\r\n    a[Int(n/2-1)] = sin(x[1]); a[Int(n/2+1)] = -a[Int(n/2-1)];\r\n    b[Int(n/2-1)] = cos(x[1]); b[Int(n/2+1)] = b[Int(n/2-1)];\r\n    for i = 2:Int(n/2-1)\r\n        a[Int(mod(i*(n-1)/2-mod(i,2)/2,n))] = a[Int(mod((i-1)*(n-1)/2-mod(i-1,2)/2,n))]-(-1)^i*sin(sum(x[1:i]));\r\n        a[Int(n-mod(i*(n-1)/2-mod(i,2)/2,n))] = -a[Int(mod(i*(n-1)/2-mod(i,2)/2,n))];\r\n        b[Int(mod(i*(n-1)/2-mod(i,2)/2,n))] = b[Int(mod((i-1)*(n-1)/2-mod(i-1,2)/2,n))]-(-1)^i*cos(sum(x[1:i]));\r\n        b[Int(n-mod(i*(n-1)/2-mod(i,2)/2,n))] = b[Int(mod(i*(n-1)/2-mod(i,2)/2,n))];\r\n    end\r\n    a[Int(n/2)] = 0; b[Int(n/2)] = 1;\r\n    return(a,b)\r\nend\r\nend", "meta": {"hexsha": "3488754490412ee7ac2f44d5c54e8d11dd3b4dd3", "size": 1402, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "cstrt_ngon/cstrt_bwinja_ngon.jl", "max_stars_repo_name": "cbingane/optigon", "max_stars_repo_head_hexsha": "f585de7a2b01ff1e7a15c566596a7ba8f77f782a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cstrt_ngon/cstrt_bwinja_ngon.jl", "max_issues_repo_name": "cbingane/optigon", "max_issues_repo_head_hexsha": "f585de7a2b01ff1e7a15c566596a7ba8f77f782a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cstrt_ngon/cstrt_bwinja_ngon.jl", "max_forks_repo_name": "cbingane/optigon", "max_forks_repo_head_hexsha": "f585de7a2b01ff1e7a15c566596a7ba8f77f782a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0571428571, "max_line_length": 113, "alphanum_fraction": 0.4507845934, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688146, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7631630753954229}}
{"text": "\"\"\"\n    QR()\nFinds a vector vanishing 'gamma' such that all of its entries sum to 1.\n\nInput arguments\n---------------\ngamma::Array{Float64, 2}    This matrix verifies properties necessary for QR() to work. We know that the rank of 'Gamma' n-1 (otherwise we wouldn't reach this function).\ntolerance::Float64          Same as always.\n\nReturns\n-------\nlambda::Vec{Float64}        A vector vanishing 'gamma'. lambda is a column vector containing the components of a vector generating Nul(M) with all the components summing up to 1.\n\"\"\"\nfunction QR(Gamma, tolerance)\n   # We know that rank(Gamma)=n-1\n   #and rank(Gamma0)=n\n   # In addition all columns of M are non vanishing\n   ## Outcome\n   # lambda is a column vector containing the components of a vector generating\n   # Nul(M) with all the components summing up to 1\n   ##\n\n   n = size(Gamma, 2)\n   m = size(Gamma, 1) # m>=n-1\n   if m == 1\n      #then n<=2 but n=1 is excluded since it corresponds to a 1-vertex boundary, thus n=2 and Gamma=[a b]\n      #also notice that since Gamma0=[[a b];[1 1]] has full rank it is ruled\n      #out that a=b\n      lambda = [Gamma[2]; -Gamma[1]] / (Gamma[2] - Gamma[1])\n   else\n\n      # M=Q*R\n      #Q is an orthogonal matrix of dimension m x m\n      qr_decomposition = qr(Gamma).R # access the second element of the tuple\n      # R is an upper triangular matrix of dimension m x n\n      R = triu(qr_decomposition)\n\n      # diagonal is a column vector with dimension either n-1 (if m=n-1) or n (if m>=n)\n      # Set entries that are too small relative to `tolerance` to zero.\n      diagonal = heaviside(tolerance .- abs.(diag(R)))\n      index = round.(Int, transpose(collect(1:min(m, n))) * diagonal)[1]\n\n      if index == 0\n         # the first n-1 columns are linearly independent\n         index = n - 1\n      else\n         #the index-th entry in diag(R) is zero\n         index = index - 1\n      end\n\n      lambda = zeros(n, 1)\n      lambda[1:index] = - R[1:index, 1:index] \\ R[1:index, index + 1] # A\\b means inv(A)*b\n      lambda[index + 1] = 1\n      lambda = lambda / (ones(1, n) * lambda)\n   end\n   lambda = lambda .* heaviside(abs.(lambda) .- tolerance)\n\n   return(lambda)\nend\n", "meta": {"hexsha": "087f3003e090c2667e2a278587a053283e521525", "size": 2169, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/QR.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Simplices.jl-d5428e67-3037-59ba-9ab1-57a04f0a3b6a", "max_stars_repo_head_hexsha": "c5651f0aa8e45bd196fc6816e3e47f01d2f1764b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-08T00:07:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T00:07:46.000Z", "max_issues_repo_path": "src/QR.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Simplices.jl-d5428e67-3037-59ba-9ab1-57a04f0a3b6a", "max_issues_repo_head_hexsha": "c5651f0aa8e45bd196fc6816e3e47f01d2f1764b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2018-04-04T02:26:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-29T15:46:04.000Z", "max_forks_repo_path": "src/QR.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Simplices.jl-d5428e67-3037-59ba-9ab1-57a04f0a3b6a", "max_forks_repo_head_hexsha": "c5651f0aa8e45bd196fc6816e3e47f01d2f1764b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-12-11T08:36:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:03:05.000Z", "avg_line_length": 36.15, "max_line_length": 178, "alphanum_fraction": 0.6279391425, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368929, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7631492165955633}}
{"text": "# https://mrandri19.github.io/2020/09/28/bayesian-linear-regression-with-conjugate-priors.html\n# https://qiita.com/haru1843/items/3956dab2fd0d448cd02b\n# https://discourse.julialang.org/t/solving-ax-b-for-large-matrix-dimesnions-efficiently-in-julia/51504\n# https://stackoverflow.com/questions/57270276/identity-matrix-in-julia\n\n# bayesian inferense (using conjugate prior analyticaly) of coefficients and variance in error term for linear regression model\n\nusing Random, Plots, StatsPlots, Distributions, LinearAlgebra, DataFrames, Printf, LaTeXStrings\n\n\"\"\"\nConjugate Priors for linear regression model (β|σ^2 ~ MvNormal, σ^2 ~ InverseGamma)\n\n    Inputs\n    ------\n    y:    data, independent variable (n vector)\n    X:    data, dependent variables (n * k matrix)\n    β0:   mean of conditional prior (multivariate normal β0|σ^2 ~ MvNormal) for coefficients\n    A0:   precision matrix (inverse of Σ) of conditional prior for coefficients\n    ν0:   shape parameter of prior for variance of error term\n    λ0:   scale parameter of prior for variance of error term\n    prob: credible interval probability (0 < prob < 1)\n\n    Outputs\n    -------\n    results: posterior summary stats table (DataFrames)\n    marginal_posterior_β: vector of marginal posterior for each coefficients (single β|D ~ TDist)\n    posterior_σ2: posterior for variance of error term (σ^2|D ~ InverseGamma)\n\"\"\"\nfunction regression_stats(y, X, β0, A0, ν0, λ0, prob)\n    XX = X' * X\n    Xy = X' * y\n    # @time XX \\ Xy # fast and efficient\n    # @time inv(XX) * Xy\n    β_ols = XX \\ Xy # OLS estimator\n    A_star = XX + A0\n    β_star = A_star \\ (Xy + A0 * β0)\n    C_star = inv(inv(XX) + inv(A0))\n    ν_star = size(y)[1] + ν0\n    ssr = sum((y - X * β_ols).^2) # SSR sum of squared residual 残差二乗和\n    # @time (β0 - β_ols)' * C_star * (β0 - β_ols)\n    # @time dot(β0 - β_ols, C_star, β0 - β_ols) # faster\n    λ_star = ssr + dot(β0 - β_ols, C_star, β0 - β_ols) + λ0\n    H_star = (λ_star / ν_star) * inv(A_star)\n    h_star = diag(sqrt(H_star))\n\n    marginal_posterior_β = LocationScale.(β_star, h_star, TDist(ν_star)) # broadcasting through coefficients\n    sd_β = std.(marginal_posterior_β)\n    ci_β_upper = quantile.(marginal_posterior_β, prob - (1-prob)/2)\n    ci_β_lower = quantile.(marginal_posterior_β, (1-prob)/2)\n    # ci_β = [ci_β_lower, ci_β_upper]\n    stats_β = [β_star β_star β_star sd_β ci_β_lower ci_β_upper]\n\n    posterior_σ2 = InverseGamma(ν_star/2, λ_star/2)\n    mean_σ2 = mean(posterior_σ2)\n    median_σ2 = median(posterior_σ2)\n    mode_σ2 = mode(posterior_σ2)\n    sd_σ2 = std(posterior_σ2)\n    ci_σ2_upper = quantile(posterior_σ2, prob - (1-prob)/2)\n    ci_σ2_lower = quantile(posterior_σ2, (1-prob)/2)\n    # ci_σ2 = [ci_σ2_lower, ci_σ2_upper]\n    stats_σ2 = [mean_σ2 median_σ2 mode_σ2 sd_σ2 ci_σ2_lower ci_σ2_upper]\n    stats = [stats_β; stats_σ2]\n    stats_string = [\"Mean\", \"Median\", \"Mode\", \"SD\", @sprintf(\"CI(%d)_Lower\", prob*100), @sprintf(\"CI(%d)_Upper\", prob*100)]\n    results = DataFrame(stats, stats_string)\n    return results, marginal_posterior_β, posterior_σ2, β_ols\nend\n\n# Generate moc data\nn = 50\ndim = 1\nRandom.seed!(99)\nu = rand(Normal(0, 0.7), n) # true value σ^2 = 0.49\nx = rand(Uniform(-sqrt(3.0), sqrt(3.0)), n, dim) # x generated from Uniform[-√3, √3]\nX = [ones(n) x] # dependent variable matrix with ones\nβ = Vector(1:1:dim+1) # true coefficients\ny = X*β + u # true data generating process\n\n\n# set prior\nk = size(X, 2)\nβ0 = zeros(k)\nτ0 = 0.2 # no ridge penalty ... τ0 = Inf ?\n\n# τ0 = 0.001\n# τ0 = 0.01\n# τ0 = 0.1\n# τ0 = 1\n# τ0 = 10\n# τ0 = 100\n# τ0 = 1000\n\nA0 = τ0 * I # Identity matrix\nν0 = 5.0\nλ0 = 7.0\nH0 = (λ0 / ν0) * inv(A0) # scale matrix for marginal prior of multivariate coefficient (mv Tdist)\nh0 = diag(sqrt(Matrix(H0, k, k))) # scale params for marginal prior of single coefficient (T dist) H0の対角成分\nmarginal_prior_β = LocationScale.(β0, h0, TDist(ν0)) # broadcasting through coefficients\nprior_σ2 = InverseGamma(ν0/2, λ0/2)\n\n# calculate posterior\nprob = 0.95\nresults, marginal_posterior_β, posterior_σ2, β_ols = regression_stats(y, X, β0, A0, ν0, λ0, prob)\nprint(\"$results\\n\")\n\n# Visualize Posterior\nplots = []\n\nfor i = 1:k\n    label_prior = @sprintf(\"marginal prior: T(ν=%.1f, μ=%.1f, σ^2=%.1f)\", params(params(marginal_prior_β[i])[3])[1], params(marginal_prior_β[i])[1], params(marginal_prior_β[i])[2])\n    p = plot(marginal_prior_β[i], linestyle=:dash, label=label_prior, xlims=(0.0, 3.0), ylims=(0.0, 4.0), xlabel=@sprintf(\"β%d\", i), ylabel=\"Probability Density\")\n    label_posterior = @sprintf(\"marginal posterior: T(ν=%.1f, μ=%.1f, σ^2=%.1f)\", params(params(marginal_posterior_β[i])[3])[1], params(marginal_posterior_β[i])[1], params(marginal_posterior_β[i])[2])\n    plot!(marginal_posterior_β[i], linestyle=:solid, label=label_posterior)\n    push!(plots, p)\nend\n\nlabel_prior = @sprintf(\"prior: InverseGamma(α=%.1f, θ=%.1f)\", params(prior_σ2)[1], params(prior_σ2)[2])\np = plot(prior_σ2, linestyle=:dash, label=label_prior, xlims=(0.0, 3.0), ylims=(0.0, 4.0), xlabel=L\"\\sigma^2\", ylabel=\"Probability Density\")\nlabel_posterior = @sprintf(\"prior: InverseGamma(α=%.1f, θ=%.1f)\", params(posterior_σ2)[1], params(posterior_σ2)[2])\nplot!(posterior_σ2, linestyle=:solid, label=label_posterior)\npush!(plots, p)\n\nplot(plots..., layout=(1, k+1))\n\n# plot ols\nscatter(x, y, label=\"data\")\n# scatter(x, y, xlims=(-0.1, 0.1), ylims=(0.9, 1.5))\nplot!(x, X * β, label=(@sprintf(\"True: y = %.d + %.dx\", β[1], β[2])))\nplot!(x, X * β_ols, label=(@sprintf(\"OLS: y = %.5f + %.5fx\", β_ols[1], β_ols[2])))\nβ_star = results[:, \"Mean\"][1:k]\nplot!(x, X * β_star, label=(@sprintf(\"Bayes: y = %.5f + %.5fx (τ0=%.2f, Ridge)\", β_star[1], β_star[2], τ0)))\n\n# significance test on coefficients H0: βj = 0, H1: βj ≠ 0\n# evaluate with SDDR\n\"\"\"\ncalculate SDDR (compare density of posterior and prior on particular value)\n# https://docs.julialang.org/en/v1/manual/methods/\n# https://stackoverflow.com/questions/61088294/declaring-the-name-of-argument-when-invoking-a-function\n\n    Inputs\n    ------\n    β_h0: test value, (default is 0)\n    posterior\n    prior\n\n    Output\n    ------\n    sddr\n\"\"\"\nfunction sddr(posterior, prior, ;null_hypothesis::Float64=0.0)\n    return pdf(posterior, null_hypothesis) / pdf(prior, null_hypothesis)\nend\n\nprint(log10.(sddr.(marginal_posterior_β, marginal_prior_β, null_hypothesis=0.0)))", "meta": {"hexsha": "98418f7c557e6f3b09e7d2e219f4ce5e3741f34f", "size": 6296, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jlbayes_conjugate_regression.jl", "max_stars_repo_name": "hessihan/julia_bayes_intro", "max_stars_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jlbayes_conjugate_regression.jl", "max_issues_repo_name": "hessihan/julia_bayes_intro", "max_issues_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jlbayes_conjugate_regression.jl", "max_forks_repo_name": "hessihan/julia_bayes_intro", "max_forks_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1503267974, "max_line_length": 200, "alphanum_fraction": 0.6786848793, "num_tokens": 2229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258009, "lm_q2_score": 0.8175744828610096, "lm_q1q2_score": 0.7631492095859264}}
{"text": "# probit\n# https://stats.stackexchange.com/questions/155239/marginal-effects-from-bayesian-probit\n\nusing Turing\nusing Distributions\nusing Random\nusing LinearAlgebra\nusing StatsPlots\nusing MCMCChains\nusing DataFrames\nusing Printf\n# using Plots # reesport\n# using Statistics # reesport\n\nusing StatsFuns: normcdf, norminvcdf, normpdf\n\n# cdf of normal distribution # Φ(x'β)\nplot(normcdf.(Vector(-10:0.1:10)))\n# probit function, inverse-cdf of normal distribution # Φ^{-1}(y)\nplot(norminvcdf.(Vector(0:0.01:1)))\n\n# geberate moc data from logit model\nn = 1_000\nnum_var = 2\nRandom.seed!(99)\nX = rand(Uniform(-sqrt(3.0), 2.0*sqrt(3.0)), n, num_var) # case-specific variables Z_i Matrix\nX = [ones(n) X]\nβ = Vector([0.0, 0.5, -0.5]) # true coefficients\n# V = X * β # representative utility, # utility (latent variable) y_star = U = Xβ + ϵ = V + ϵ\np = normcdf.(X * β) # probability (する確率)\ny = rand.(Bernoulli.(p)) # observable choice 0 or 1\n\n# set prior, β ~ MvNormal(β0, A0), no σ²\nn, k = size(X)\nβ0 = zeros(k)\nA0 = 0.01 * I\n\n@model function probit_model(X, y)\n    # Set the priors only for β.\n    β ~ MvNormal(β0, inv(A0))\n\n    # Write the likelihood, can't vectorize? no multivariate distribution\n    n = size(X, 1)\n    for i = 1:n\n        y[i] ~ Bernoulli(normcdf(X[i, :]' * β))\n    end\nend\n\n# Draw random number from posterior.\nmodel = probit_model(X, y)\n\nn_draws = 5_000\n# n_chains = 4\nn_chains = 1\nn_tune = 1_000\nchn = sample(model, NUTS(), MCMCThreads(), n_draws, n_chains)\n# chn = sample(model, NUTS(), MCMCThreads(), n_draws, n_chains)[n_tune:n_draws, :, :]\nβ_chn = chn[n_tune+1:n_draws, :, :] # delete initial and exclude odd (hamiltonian bluh bluh) chain \nβ_chn = group(β_chn, :β)\n\nsummarize(β_chn)\nquantile(β_chn)\nplot(β_chn)\n\n# Marginal Effect\n\"\"\"\nMarginal Effect of probit regression for continuous variable\n\n∂Pr(Y=1|X)/∂X_j = ∂Pr(Φ(Xβ))/∂X_j \n                = ϕ(Xβ)β_j, where ϕ() is standard normal pdf\n\nThe marginal effect on X_j depends on β_j, X_j and other β and X. Therefore, \n\n    β_chn:          random drawed β\n    β_interest:     variables of interest, :Symbol\n                    one of a symbol in `chain` argument.\n    x:              independent variable vector to calculate marginal \n                    effect (individual, at mean, etc...). \n    Output\n    ------\n    dydxs:   marginal effects regarding to each random drawed β, ((n_draws - n_tune) * n_chains) matrix\n\"\"\"\nfunction marginal_effect_probit(β_chn, β_interest, x)\n    β_rand = get_params(β_chn).β # get random value\n    β_rand_interest = β_chn[β_interest].data\n    dydxs = []\n    for which_chain = chains(β_chn)\n        β_rand_single_chain = reduce(hcat, [β_rand[j].data[:, which_chain] for j=1:length(β_rand)])\n        β_rand_interest_single_chain = β_rand_interest[:, which_chain]\n        dydx = normpdf.(β_rand_single_chain * x) .* β_rand_interest_single_chain\n        push!(dydxs, dydx)\n    end\n    dydxs = reduce(hcat, dydxs)\n    return dydxs\nend\n\nrand_margins = marginal_effect_probit(β_chn, Symbol(\"β[2]\"), X[100, :])\ndensity(rand_margins)\n\n\"\"\"\nAverage Marginal Effect of all sample.\n\"\"\"\nfunction marginal_effect_probit_mae(β_chn, β_interest, X)\n    # https://discourse.julialang.org/t/converting-a-matrix-into-an-array-of-arrays/17038/7\n    # https://discourse.julialang.org/t/how-to-broadcast-over-only-certain-function-arguments/19274\n    return mean(marginal_effect_probit.((β_chn,), (β_interest,), [r for r in eachrow(X)]))\nend\n\nrand_mae = marginal_effect_probit_mae(β_chn, Symbol(\"β[2]\"), X)\ndensity(rand_mae)\n\n# Plot Marginal Effect regarding to different value of X_j in interest\n\"\"\"\nMargins plot\n\nPlot Marginal Effect regarding to different value of X_j in interest\n# https://docs.julialang.org/en/v1/manual/functions/#Optional-Arguments\n# https://docs.julialang.org/en/v1/manual/functions/#Keyword-Arguments\n\"\"\"\nfunction plot_marginal_effect(β_chn::Chains, β_interest::Symbol, x_interest_theoritical::Vector; at_mean::Bool=false, ci_p::Float64=0.95)\n    interest_dim = findall(x -> x == β_interest, names(β_chn))\n    other_dim = findall(x -> x != β_interest, names(β_chn))\n    x_interest = X[:, interest_dim]\n    # https://stackoverflow.com/questions/37661221/julia-select-all-but-one-element-in-array-matrix\n    x_other = X[:, 1:end .!= interest_dim]\n    # x_interest_theoritical = Vector(minimum(x_interest):step:maximum(x_interest))\n\n    if at_mean\n        # at mean other x\n        X_theoritical_atmean = Matrix{Float64}(undef, size(x_interest_theoritical, 1), length(names(β_chn)))\n        X_theoritical_atmean[:, interest_dim] = x_interest_theoritical\n        for other in other_dim\n            X_theoritical_atmean[:, other] .= mean(X, dims=1)[other]\n        end\n        rand_margins = marginal_effect_probit.((β_chn,), (β_interest,), [r for r in eachrow(X_theoritical_atmean)])\n        ylabel = @sprintf(\"Marginal Effect at Means, CI(%d)\", ci_p*100)\n    else\n        # Average other x\n        X_theoritical_ames = []\n        for x in x_interest_theoritical\n            X_theoritical_ame = copy(X)\n            X_theoritical_ame[:, interest_dim] .= x\n            push!(X_theoritical_ames, X_theoritical_ame)\n        end\n        rand_margins = marginal_effect_probit_mae.((β_chn,), (β_interest,), X_theoritical_ames)\n        ylabel = @sprintf(\"Average Marginal Effect, CI(%d)\", ci_p*100)\n    end\n\n    # margins plot\n    # https://discourse.julialang.org/t/asymmetric-error-bars-and-box-plots-in-julia/73647/2\n    rand_margins_median = median.(rand_margins)\n    ci_lower = quantile.(rand_margins, (1-ci_p)/2)\n    ci_upper = quantile.(rand_margins, ci_p-(1-ci_p)/2)\n    plot(x_interest_theoritical, rand_margins_median, color=\"black\", xlabel=@sprintf(\"%s's x\", β_interest), ylabel=ylabel,  legend=false)\n    display(scatter!(x_interest_theoritical, rand_margins_median, yerror=(ci_lower, ci_upper), color=\"cornflowerblue\"))\n\n    return rand_margins\nend\n\nx_hypo = Vector(-2.0:0.5:3.5)\n\nplot_marginal_effect(β_chn, Symbol(\"β[2]\"), x_hypo, at_mean=false)\nplot_marginal_effect(β_chn, Symbol(\"β[2]\"), x_hypo, at_mean=true)\nplot_marginal_effect(β_chn, Symbol(\"β[2]\"), x_hypo, at_mean=true, ci_p=0.5)\n\nplot_marginal_effect(β_chn, Symbol(\"β[3]\"), x_hypo, at_mean=false)\nplot_marginal_effect(β_chn, Symbol(\"β[3]\"), x_hypo, at_mean=true)", "meta": {"hexsha": "22f3ce947e26d69d8465d1ce6cbe0711457d6d74", "size": 6230, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jlbayes_mcmc_probit.jl", "max_stars_repo_name": "hessihan/julia_bayes_intro", "max_stars_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jlbayes_mcmc_probit.jl", "max_issues_repo_name": "hessihan/julia_bayes_intro", "max_issues_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jlbayes_mcmc_probit.jl", "max_forks_repo_name": "hessihan/julia_bayes_intro", "max_forks_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3053892216, "max_line_length": 137, "alphanum_fraction": 0.6940609952, "num_tokens": 1939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.763149206950934}}
{"text": "#=\nIf p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.\n\n{20,48,52}, {24,45,51}, {30,40,50}\n\nFor which value of p ≤ 1000, is the number of solutions maximised?\n=#\nfunction calc()\n  dict = Dict{Float64, Set}()\n\n  for i in 1:1000, j in 1:1000\n    k = i^2+j^2\n    key = i + j + sqrt(k)\n    if sqrt(k) != floor(sqrt(k)) || key > 1000\n      continue\n    end\n\n    if haskey(dict, key) == false\n      dict[key] = Set()\n    else\n      push!(dict[key], sort!([i, j, sqrt(k)]))\n    end\n  end\n\n  (maxkey, maxcount) = 0,0\n  for key in keys(dict)\n    count = length(dict[key])\n    if count > maxcount\n      maxcount, maxkey = count, key\n    end\n  end\n  Int64(maxkey)\nend\n@time println(calc())\n", "meta": {"hexsha": "f73c297ac814682a474f994553c80b0ffcacf73d", "size": 759, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p39.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p39.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p39.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 21.6857142857, "max_line_length": 131, "alphanum_fraction": 0.5955204216, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308036221031, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7631492024088611}}
{"text": "\nusing Distributions: Normal\n\n\"\"\"\n    MomentumHarmonicWigner(ω, β)\n\nWigner distribution in a 1D harmonic potential for the momentum\n\"\"\"\nfunction MomentumHarmonicWigner(ω, β)\n    σ = sqrt(Q(ω, β) / β)\n    Normal(0, σ)\nend\n\n\"\"\"\n    PositionHarmonicWigner(ω, β)\n\nWigner distribution in a 1D harmonic potential for the position\n\"\"\"\nfunction PositionHarmonicWigner(ω, β, m; centre=0)\n    σ = sqrt(Q(ω, β) / β / m) / ω  \n    Normal(centre, σ)\nend\n\n\"\"\"\n    VelocityHarmonicWigner(ω, β, m)\n\nWigner distribution in a 1D harmonic potential for the velocity\n\"\"\"\nfunction VelocityHarmonicWigner(ω, β, m)\n    σ = sqrt(Q(ω, β) / β) / m\n    Normal(0, σ)\nend\n\n\"Quantum corrector for the Wigner distribution\"\nfunction Q(ω, β)\n    halfβħω = β*ω/2\n    return halfβħω / tanh(halfβħω)\nend\n", "meta": {"hexsha": "6d1bcf4ab19b88a16b97432f8dc12af8f1271a7e", "size": 768, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NonadiabaticDistributions/harmonic_wigner.jl", "max_stars_repo_name": "NQCD/NonadiabaticMolecularDynamics.jl", "max_stars_repo_head_hexsha": "491937e0878f15881201e7d637235a5e7f6feb6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-23T04:13:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T04:13:13.000Z", "max_issues_repo_path": "src/NonadiabaticDistributions/harmonic_wigner.jl", "max_issues_repo_name": "NQCD/NonadiabaticMolecularDynamics.jl", "max_issues_repo_head_hexsha": "491937e0878f15881201e7d637235a5e7f6feb6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2021-08-18T11:59:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T14:32:58.000Z", "max_forks_repo_path": "src/NonadiabaticDistributions/harmonic_wigner.jl", "max_forks_repo_name": "NQCD/NonadiabaticMolecularDynamics.jl", "max_forks_repo_head_hexsha": "491937e0878f15881201e7d637235a5e7f6feb6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6923076923, "max_line_length": 63, "alphanum_fraction": 0.6770833333, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430803622103, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7631491941108279}}
{"text": "using LinearAlgebra, ForwardDiff\nusing Convex, SCS, ECOS\n\n\"\"\"\n\tprojection onto second-order cone\n\"\"\"\nfunction Πsoc(v, s)\n\tif norm(v) <= -s\n\t\t# @warn \"below cone\"\n\t\treturn zero(v), 0.0\n\telseif norm(v) <= s\n\t\t# @warn \"in cone\"\n\t\treturn v, s\n\telseif norm(v) > abs(s)\n\t\t# @warn \"outside cone\"\n\t\ta = 0.5 * (1.0 + s / norm(v))\n\t\treturn a * v, a * norm(v)\n\telse\n\t\t@warn \"soc projection error\"\n\t\treturn zero(v), 0.0\n\tend\nend\n\nfunction projection_difference(v, s)\n\tvcat(Πsoc(v, s)...) - [v; s]\nend\n\n# projection_difference(ones(2), 1.0)\n\n\"\"\"\n min v'b\n st norm(b) <= y\n\"\"\"\n\n# parameters\nv = [1.0; 1.0e-1]\nψ = norm(v)\ny = 1.0\n\n\"Convex.jl\"\nb = Variable(2)\nprob = minimize(v' * b)\nprob.constraints += norm(b) <= y\n@time solve!(prob, ECOS.Optimizer)\n\n@show prob.status\n@show b.value\n@show prob.constraints[1].dual\nprob.optval\n\nfunction lagrangian(v, y, b, ψ)\n\tv' * b + ψ' * projection_difference(b, y) + 0.5 * projection_difference(b, y)' * projection_difference(b, y)\nend\n\nfunction r(z, θ)\n\tb = z[1:2]\n\tψ = z[3:5]\n\ty = θ[1]\n\tv = θ[2:3]\n\n\tlb(w) = lagrangian(v, y, w, ψ)\n\t# lψ(w) = lagrangian(v, y, b, w)\n\n\t# return ForwardDiff.gradient(lb, b)\n\treturn [ForwardDiff.gradient(lb, b);\n\t\t\tprojection_difference(b, y)]\n\nend\n\nθ = [y; v]\nrz(x) = r(x, θ)\n\nsol = levenberg_marquardt(rz, ones(5))\nrθ(x) = r(sol, x)\n\ndrdz = ForwardDiff.jacobian(rz, sol)\ndrdθ = ForwardDiff.jacobian(rθ, θ)\n\n# norm(drdz - drz(z, θ))\n# norm(drdθ - drθ(z, θ))\nrank(drdz)\n# eigen(drdz).values\n#\n# rank(drz(z, θ))\n# eigen(drz(z, θ)).values\n\nx1 = (-drdz \\ drdθ)[1:2,:]\nx3 = (-(drdz' * drdz) \\ (drdz' * drdθ))[1:2,:]\n\nρ = 1.0e-8\nx2 = (-(drdz' * drdz + ρ * I) \\ (drdz' * drdθ))[1:2,:]\nx4 = (-drdz' * ((drdz * drdz' + ρ * I) \\ drdθ))[1:2,:]\n\n# x2 = (-drz(z,θ) \\ drθ(z,θ))[1:2,:]\n# x4 = (-(drz(z,θ)' * drz(z,θ)) \\ (drz(z, θ)' * drθ(z, θ)))[1:2, :]\n#\n", "meta": {"hexsha": "9e745bda60f8a1650a4feba5e9d31981d22b19ea", "size": 1797, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/development/projection_socp.jl", "max_stars_repo_name": "jmichaux/motion_planning", "max_stars_repo_head_hexsha": "9a36f394261ff11ca8325d8a5e9d8a79f18b2744", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2021-02-07T10:46:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:30:20.000Z", "max_issues_repo_path": "examples/development/projection_socp.jl", "max_issues_repo_name": "jmichaux/motion_planning", "max_issues_repo_head_hexsha": "9a36f394261ff11ca8325d8a5e9d8a79f18b2744", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-10-07T05:36:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-11T17:16:28.000Z", "max_forks_repo_path": "examples/development/projection_socp.jl", "max_forks_repo_name": "thowell/motion_planning", "max_forks_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-01-25T19:23:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T06:43:01.000Z", "avg_line_length": 18.5257731959, "max_line_length": 109, "alphanum_fraction": 0.5776293823, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210671, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7630873711807814}}
{"text": "doc\"\"\"\n    Gamma(α,θ)\n\nThe *Gamma distribution* with shape parameter `α` and scale `θ` has probability density\nfunction\n\n$f(x; \\alpha, \\beta) = \\frac{x^{\\alpha-1} e^{-x/\\beta}}{\\Gamma(\\alpha) \\beta^\\alpha},\n\\quad x > 0$\n\n```julia\nGamma()          # Gamma distribution with unit shape and unit scale, i.e. Gamma(1.0, 1.0)\nGamma(a)         # Gamma distribution with shape a and unit scale, i.e. Gamma(a, 1.0)\nGamma(a, b)      # Gamma distribution with shape a and scale b\n\nparams(d)        # Get the parameters, i.e. (a, b)\nshape(d)         # Get the shape parameter, i.e. a\nscale(d)         # Get the scale parameter, i.e. b\n```\n\nExternal links\n\n* [Gamma distribution on Wikipedia](http://en.wikipedia.org/wiki/Gamma_distribution)\n\n\"\"\"\nimmutable Gamma <: ContinuousUnivariateDistribution\n    α::Float64\n    θ::Float64\n\n    function Gamma(α::Real, θ::Real)\n        @check_args(Gamma, α > zero(α) && θ > zero(θ))\n        new(α, θ)\n    end\n    function Gamma(α::Real)\n        @check_args(Gamma, α > zero(α))\n        new(α, 1.0)\n    end\n    Gamma() = new(1.0, 1.0)\nend\n\n@distr_support Gamma 0.0 Inf\n\n\n#### Parameters\n\nshape(d::Gamma) = d.α\nscale(d::Gamma) = d.θ\nrate(d::Gamma) = 1.0 / d.θ\n\nparams(d::Gamma) = (d.α, d.θ)\n\n\n#### Statistics\n\nmean(d::Gamma) = d.α * d.θ\n\nvar(d::Gamma) = d.α * d.θ^2\n\nskewness(d::Gamma) = 2.0 / sqrt(d.α)\n\nkurtosis(d::Gamma) = 6.0 / d.α\n\nfunction mode(d::Gamma)\n    (α, θ) = params(d)\n    α >= 1.0 ? θ * (α - 1.0) : error(\"Gamma has no mode when shape < 1.0\")\nend\n\nfunction entropy(d::Gamma)\n    (α, θ) = params(d)\n    α + lgamma(α) + (1.0 - α) * digamma(α) + log(θ)\nend\n\nmgf(d::Gamma, t::Real) = (1.0 - t * d.θ)^(-d.α)\n\ncf(d::Gamma, t::Real) = (1.0 - im * t * d.θ)^(-d.α)\n\n\n#### Evaluation & Sampling\n\n@_delegate_statsfuns Gamma gamma α θ\n\ngradlogpdf(d::Gamma, x::Float64) =\n    insupport(Gamma, x) ? (d.α - 1.0) / x - 1.0 / d.θ : 0.0\n\nrand(d::Gamma) = StatsFuns.Rmath.gammarand(d.α, d.θ)\n\n\n#### Fit model\n\nimmutable GammaStats <: SufficientStats\n    sx::Float64      # (weighted) sum of x\n    slogx::Float64   # (weighted) sum of log(x)\n    tw::Float64      # total sample weight\n\n    GammaStats(sx::Real, slogx::Real, tw::Real) = new(sx, slogx, tw)\nend\n\nfunction suffstats{T<:Real}(::Type{Gamma}, x::AbstractArray{T})\n    sx = 0.\n    slogx = 0.\n    for xi = x\n        sx += xi\n        slogx += log(xi)\n    end\n    GammaStats(sx, slogx, length(x))\nend\n\nfunction suffstats{T<:Real}(::Type{Gamma}, x::AbstractArray{T}, w::AbstractArray{Float64})\n    n = length(x)\n    if length(w) != n\n        throw(ArgumentError(\"Inconsistent argument dimensions.\"))\n    end\n\n    sx = 0.\n    slogx = 0.\n    tw = 0.\n    for i = 1:n\n        @inbounds xi = x[i]\n        @inbounds wi = w[i]\n        sx += wi * xi\n        slogx += wi * log(xi)\n        tw += wi\n    end\n    GammaStats(sx, slogx, tw)\nend\n\nfunction gamma_mle_update(logmx::Float64, mlogx::Float64, a::Float64)\n    ia = 1.0 / a\n    z = ia + (mlogx - logmx + log(a) - digamma(a)) / (abs2(a) * (ia - trigamma(a)))\n    1.0 / z\nend\n\nfunction fit_mle(::Type{Gamma}, ss::GammaStats;\n    alpha0::Float64=NaN, maxiter::Int=1000, tol::Float64=1.0e-16)\n\n    mx = ss.sx / ss.tw\n    logmx = log(mx)\n    mlogx = ss.slogx / ss.tw\n\n    a::Float64 = isnan(alpha0) ? 0.5 / (logmx - mlogx) : alpha0\n    converged = false\n\n    t = 0\n    while !converged && t < maxiter\n        t += 1\n        a_old = a\n        a = gamma_mle_update(logmx, mlogx, a)\n        converged = abs(a - a_old) <= tol\n    end\n\n    Gamma(a, mx / a)\nend\n", "meta": {"hexsha": "f1d32718e37b27f1804a45b7f79558042b642277", "size": 3471, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/gamma.jl", "max_stars_repo_name": "ericproffitt/Distributions.jl", "max_stars_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/gamma.jl", "max_issues_repo_name": "ericproffitt/Distributions.jl", "max_issues_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/gamma.jl", "max_forks_repo_name": "ericproffitt/Distributions.jl", "max_forks_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8355263158, "max_line_length": 90, "alphanum_fraction": 0.572457505, "num_tokens": 1249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7630873692103408}}
{"text": "\"\"\"\n    X = sylvc(A,B,C)\n\nSolve the continuous Sylvester matrix equation\n\n                AX + XB = C\n\nusing the Bartels-Stewart Schur form based approach. `A` and `B` are\nsquare matrices, and `A` and `-B` must not have common eigenvalues.\n\nThe following particular cases are also adressed:\n\n    X = sylvc(α*I,B,C)  or  X = sylvc(α,B,C)\n\nSolve the matrix equation `X(αI+B)  = C`.\n\n    X = sylvc(A,β*I,C)  or  X = sylvc(A,β,C)\n\nSolve the matrix equation `(A+βI)X = C`.\n\n    X = sylvc(α*I,β*I,C)  or  sylvc(α,β,C)\n\nSolve the matrix equation `(α+β)X = C`.\n\n    x = sylvc(α,β,γ)\n\nSolve the equation `(α+β)x = γ`.\n\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2×2 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2×2 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2×2 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> X = sylvc(A, B, C)\n2×2 Array{Float64,2}:\n -4.46667   1.93333\n  3.73333  -1.8\n\njulia> A*X + X*B - C\n2×2 Array{Float64,2}:\n  2.66454e-15  1.77636e-15\n -3.77476e-15  4.44089e-16\n```\n\"\"\"\nfunction sylvc(A::AbstractMatrix,B::AbstractMatrix,C::AbstractMatrix)\n   \"\"\"\n   Reference:\n   R. H. Bartels and G. W. Stewart. Algorithm 432: Solution of the matrix equation AX+XB=C.\n   Comm. ACM, 15:820–826, 1972.\n   \"\"\"\n\n   m, n = size(C);\n   [m; n] == LinearAlgebra.checksquare(A,B) || throw(DimensionMismatch(\"A, B and C have incompatible dimensions\"))\n \n   T2 = promote_type(eltype(A), eltype(B), eltype(C))\n   T2 <: BlasFloat || (T2 = promote_type(Float64,T2))\n   eltype(A) == T2 || (A = convert(Matrix{T2},A))\n   eltype(B) == T2 || (B = convert(Matrix{T2},B))\n   eltype(C) == T2 || (C = convert(Matrix{T2},C))\n \n   adjA = isa(A,Adjoint)\n   adjB = isa(B,Adjoint)\n   if adjA\n      RA, QA = schur(A.parent)\n   else\n      RA, QA = schur(A)\n   end\n   if adjB\n      RB, QB = schur(B.parent)\n   else\n      RB, QB = schur(B)\n   end\n\n   realcase = eltype(A) <: AbstractFloat\n   if adjA\n      RA, QA = schur(A.parent)\n   else\n      RA, QA = schur(A)\n   end\n   if adjB\n      RB, QB = schur(B.parent)\n   else\n      RB, QB = schur(B)\n   end\n   D = adjoint(QA) * (C*QB)\n   Y = sylvcs!(RA, RB, D, adjA = adjA, adjB = adjB)\n   QA*(Y * adjoint(QB))\nend\n# solve X(B+α) = C or (α+β)X = C\nsylvc(A::Union{Real,Complex,UniformScaling},B::Union{AbstractMatrix,UniformScaling},C::AbstractMatrix) = C/(A*I+B)\n# solve (A+β)X = C\nsylvc(A::AbstractMatrix,B::Union{Real,Complex,UniformScaling},C::AbstractMatrix) = (A+B*I)\\C\n# solve (α+β)X = C\nsylvc(A::Union{Real,Complex},B::Union{Real,Complex},C::AbstractMatrix) = A+B == 0 ? throw(SingularException(1)) : C/(A+B)\n# solve (α+β)x = γ\nsylvc(A::Union{Real,Complex}, B::Union{Real,Complex}, C::Union{Real,Complex}) = A+B == 0 ? throw(SingularException(1)) : C/(A+B)\n\"\"\"\n    X = sylvd(A,B,C)\n\nSolve the discrete Sylvester matrix equation\n\n                AXB + X = C\n\nusing an extension of the Bartels-Stewart Schur form based approach.\n`A` and `B` are square matrices, and `A` and `-B` must not have\ncommon reciprocal eigenvalues.\n\nThe following particular cases are also adressed:\n\n    X = sylvd(α*I,B,C)  or  X = sylvd(α,B,C)\n\nSolve the matrix equation `X(αB+I)  = C`.\n\n    X = sylvd(A,β*I,C)   or  X = sylvd(A,β,C)\n\nSolve the matrix equation `(βA+I)X = C`.\n\n    X = sylvd(α*I,β*I,C)  or  X = sylvd(α,β,C)\n\nSolve the matrix equation `(αβ+1)X = C`.\n\n    x = sylvd(α,β,γ)\n\nSolve the equation `(αβ+1)x = γ`.\n\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2×2 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2×2 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2×2 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n   \njulia> X = sylvd(A, B, C)\n2×2 Array{Float64,2}:\n -2.46667  -2.73333\n  2.4       1.86667\n\njulia> A*X*B + X - C\n2×2 Array{Float64,2}:\n  8.88178e-16   8.88178e-16\n -3.9968e-15   -5.55112e-15\n```\n\"\"\"\nfunction sylvd(A::AbstractMatrix,B::AbstractMatrix,C::AbstractMatrix)\n   \"\"\"\n   Reference:\n   R. H. Bartels and G. W. Stewart. Algorithm 432: Solution of the matrix equation AX+XB=C.\n   Comm. ACM, 15:820–826, 1972.\n   \"\"\"\n\n   m, n = size(C);\n   [m; n] == LinearAlgebra.checksquare(A,B) || throw(DimensionMismatch(\"A, B and C have incompatible dimensions\"))\n   T2 = promote_type(eltype(A), eltype(B), eltype(C))\n   T2 <: BlasFloat || (T2 = promote_type(Float64,T2))\n   eltype(A) == T2 || (A = convert(Matrix{T2},A))\n   eltype(B) == T2 || (B = convert(Matrix{T2},B))\n   eltype(C) == T2 || (C = convert(Matrix{T2},C))\n\n   adjA = isa(A,Adjoint)\n   adjB = isa(B,Adjoint)\n   if adjA\n      RA, QA = schur(A.parent)\n   else\n      RA, QA = schur(A)\n   end\n   if adjB\n      RB, QB = schur(B.parent)\n   else\n      RB, QB = schur(B)\n   end\n   D = adjoint(QA) * (C*QB)\n   Y = sylvds!(RA, RB, D, adjA = adjA, adjB = adjB)\n   QA*(Y * adjoint(QB))\nend\n# solve X(αB+I) = C or X(αβ+1) = C\nsylvd(A::Union{Real,Complex,UniformScaling},B::Union{AbstractMatrix,UniformScaling},C::AbstractMatrix) = C/(A*B+I)\n# solve (Aβ+I)X = C\nsylvd(A::AbstractMatrix,B::Union{Real,Complex,UniformScaling},C::AbstractMatrix) = (A*B+I)\\C\n# solve (αβ+1)X = C\nsylvd(A::Union{Real,Complex},B::Union{Real,Complex},C::AbstractMatrix) = A*B+1 == 0 ? throw(SingularException(1)) : C/(A*B+1)\n# solve (αβ+1)x = γ\nsylvd(A::Union{Real,Complex}, B::Union{Real,Complex}, C::Union{Real,Complex}) = A*B+1 == 0 ? throw(SingularException(1)) : C/(A*B+one(C))\n\"\"\"\n    X = gsylv(A,B,C,D,E)\n\nSolve the generalized Sylvester matrix equation\n\n              AXB + CXD = E\n\nusing a generalized Schur form based approach. `A`, `B`, `C` and `D` are\nsquare matrices. The pencils `A-λC` and `D+λB` must be regular and\nmust not have common eigenvalues.\n\nThe following particular cases are also adressed:\n\n    X = gsylv(A,B,E)\n\nSolve the generalized Sylvester matrix equation `AXB  = E`.\n\n    X = gsylv(A,B,γ*I,E)  or  X = gsylv(A,B,γ,E)\n\nSolve the generalized Sylvester matrix equation `AXB +γX = E`.\n\n    X = gsylv(A,B,γ*I,D,E)  or  X = gsylv(A,B,γ,D,E)\n\nSolve the generalized Sylvester matrix equation `AXB +γXD = E`.\n\n    X = gsylv(A,B,C,δ*I,E)  or  X = gsylv(A,B,C,δ,E)\n\nSolve the generalized Sylvester matrix equation `AXB +CXδ = E`.\n\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2×2 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2×2 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2×2 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> D = [1. -2.; -2. -1.]\n2×2 Array{Float64,2}:\n  1.0  -2.0\n -2.0  -1.0\n\njulia> E = [1. -1.; -2. 2.]\n2×2 Array{Float64,2}:\n  1.0  -1.0\n -2.0   2.0\n\njulia> X = gsylv(A, B, C, D, E)\n2×2 Array{Float64,2}:\n -0.52094   -0.0275792\n -0.168539   0.314607\n \njulia> A*X*B + C*X*D - E\n2×2 Array{Float64,2}:\n 4.44089e-16  8.88178e-16\n 6.66134e-16  0.0\n```\n\"\"\"\nfunction gsylv(A::AbstractMatrix,B::AbstractMatrix,C::AbstractMatrix,D::AbstractMatrix,E::AbstractMatrix)\n\n    m, n = size(E);\n    [m; n; m; n] == LinearAlgebra.checksquare(A,B,C,D) ||\n       throw(DimensionMismatch(\"A, B, C, D and E have incompatible dimensions\"))\n    T2 = promote_type(eltype(A), eltype(B), eltype(C), eltype(D), eltype(E))\n    T2 <: BlasFloat || (T2 = promote_type(Float64,T2))\n    eltype(A) == T2 || (A = convert(Matrix{T2},A))\n    eltype(B) == T2 || (B = convert(Matrix{T2},B))\n    eltype(C) == T2 || (C = convert(Matrix{T2},C))\n    eltype(D) == T2 || (D = convert(Matrix{T2},D))\n    eltype(E) == T2 || (E = convert(Matrix{T2},E))\n\n    adjA = isa(A,Adjoint)\n    adjB = isa(B,Adjoint)\n    adjC = isa(C,Adjoint)\n    adjD = isa(D,Adjoint)\n    adjAC = adjA && adjC\n    adjBD = adjB && adjD\n\n    if adjAC\n       AS, CS, Z1, Q1 = schur(A.parent,C.parent)\n    else\n       if adjA\n          A = copy(A)\n       end\n       if adjC\n          C = copy(C)\n       end\n       AS, CS, Q1, Z1 = schur(A,C)\n    end\n    if adjBD\n       BS, DS, Z2, Q2 = schur(B.parent,D.parent)\n    else\n      if adjB\n          B = copy(B)\n      end\n      if adjD\n          D = copy(D)\n      end\n       BS, DS, Q2, Z2 = schur(B,D)\n    end\n    Y = adjoint(Q1) * (E*Z2)\n    gsylvs!(AS, BS, CS, DS, Y, adjAC = adjAC, adjBD = adjBD)\n    Z1*(Y * adjoint(Q2))\nend\n# solve AXB = C\ngsylv(A::Union{AbstractMatrix,UniformScaling,Real,Complex},B::Union{AbstractMatrix,UniformScaling,Real,Complex},E::AbstractMatrix) = (A\\E)/B\n# solve AXB+γX = E\ngsylv(A::AbstractMatrix,B::AbstractMatrix,C::Union{UniformScaling,Real,Complex},E::AbstractMatrix) =\nsize(A,1) == size(A,2) && size(B,1) == size(B,2) ? gsylv(A,B,Matrix{eltype(C)}(C*I,size(A)),Matrix{eltype(C)}(I,size(B)),E) :\nthrow(DimensionMismatch(\"A and B must be square matrices\"))\n# solve AXB+γXδ = E\ngsylv(A::AbstractMatrix,B::AbstractMatrix,C::Union{UniformScaling,Real,Complex},D::Union{UniformScaling,Real,Complex},E::AbstractMatrix) = gsylv(A,B,C*D,E)\n# solve AXB+γXD = E\ngsylv(A::AbstractMatrix,B::AbstractMatrix,C::Union{UniformScaling,Real,Complex},D::AbstractMatrix,E::AbstractMatrix) =\nsize(A,1) == size(A,2) ? gsylv(A,B,Matrix{eltype(C)}(C*I,size(A)),D,E) :\nthrow(DimensionMismatch(\"A must be a square matrix\"))\n# solve AXB+CXδ = E\ngsylv(A::AbstractMatrix,B::AbstractMatrix,C::AbstractMatrix,D::Union{UniformScaling,Real,Complex},E::AbstractMatrix) =\nsize(B,1) == size(B,2) ? gsylv(A,B,C,Matrix{eltype(D)}(D*I,size(B)),E) :\nthrow(DimensionMismatch(\"B must be a square matrix\"))\n\n\"\"\"\n    (X,Y) = sylvsys(A,B,C,D,E,F)\n\nSolve the Sylvester system of matrix equations\n\n                AX + YB = C\n                DX + YE = F,\n\nwhere `(A,D)`, `(B,E)` are pairs of square matrices of the same size.\nThe pencils `A-λD` and `-B+λE` must be regular and must not have common eigenvalues.\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2×2 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2×2 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2×2 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> D = [1. -2.; -2. -1.]\n2×2 Array{Float64,2}:\n  1.0  -2.0\n -2.0  -1.0\n\njulia> E = [1. -1.; -2. 2.]\n2×2 Array{Float64,2}:\n  1.0  -1.0\n -2.0   2.0\n\njulia> F = [1. -1.; -2. 2.]\n2×2 Array{Float64,2}:\n  1.0  -1.0\n -2.0   2.0\n\njulia> X, Y = sylvsys(A, B, C, D, E, F);\n\njulia> X\n2×2 Array{Float64,2}:\n  1.388  -1.388\n -0.892   0.892\n\njulia> Y\n2×2 Array{Float64,2}:\n -1.788  0.192\n  0.236  0.176\n\njulia> A*X + Y*B - C\n2×2 Array{Float64,2}:\n  6.66134e-16  2.22045e-15\n -3.10862e-15  2.66454e-15\n\njulia> D*X + Y*E - F\n2×2 Array{Float64,2}:\n  1.33227e-15  -2.22045e-15\n -4.44089e-16   4.44089e-16\n```\n\"\"\"\nfunction sylvsys(A::AbstractMatrix,B::AbstractMatrix,C::AbstractMatrix,D::AbstractMatrix,E::AbstractMatrix,F::AbstractMatrix)\n\n    m, n = size(C);\n    (m == size(F,1) && n == size(F,2)) ||\n      throw(DimensionMismatch(\"C and F must have the same dimensions\"))\n    [m; n; m; n] == LinearAlgebra.checksquare(A,B,D,E) ||\n       throw(DimensionMismatch(\"A, B, C, D, E and F have incompatible dimensions\"))\n    T2 = promote_type(eltype(A), eltype(B), eltype(C), eltype(D), eltype(E), eltype(F))\n    T2 <: BlasFloat || (T2 = promote_type(Float64,T2))\n    eltype(A) == T2 || (A = convert(Matrix{T2},A))\n    eltype(B) == T2 || (B = convert(Matrix{T2},B))\n    eltype(C) == T2 || (C = convert(Matrix{T2},C))\n    eltype(D) == T2 || (D = convert(Matrix{T2},D))\n    eltype(E) == T2 || (E = convert(Matrix{T2},E))\n    eltype(F) == T2 || (F = convert(Matrix{T2},F))\n\n    if isa(A,Adjoint)\n      A = copy(A)\n    end\n    if isa(B,Adjoint)\n      B = copy(B)\n    end\n    if isa(D,Adjoint)\n      D = copy(D)\n    end\n    if isa(E,Adjoint)\n      E = copy(E)\n    end\n    AS, DS, Q1, Z1 = schur(A,D)\n    BS, ES, Q2, Z2 = schur(B,E)\n\n    CS = adjoint(Q1) * (C*Z2)\n    FS = adjoint(Q1) * (F*Z2)\n\n    X, Y, scale =  tgsyl!('N',AS,BS,CS,DS,ES,FS)\n\n    (rmul!(Z1*(X * adjoint(Z2)), inv(scale)), rmul!(Q1*(Y * adjoint(Q2)), inv(-scale)) )\nend\n\"\"\"\n    (X,Y) = dsylvsys(A,B,C,D,E,F)\n\nSolve the dual Sylvester system of matrix equations\n\n       AX + DY = C\n       XB + YE = F ,\n\nwhere `(A,D)`, `(B,E)` are pairs of square matrices of the same size.\nThe pencils `A-λD` and `-B+λE` must be regular and must not have common eigenvalues.\n\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2×2 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2×2 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2×2 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> D = [1. -2.; -2. -1.]\n2×2 Array{Float64,2}:\n  1.0  -2.0\n -2.0  -1.0\n\njulia> E = [1. -1.; -2. 2.]\n2×2 Array{Float64,2}:\n  1.0  -1.0\n -2.0   2.0\n\njulia> F = [1. -1.; -2. 2.]\n2×2 Array{Float64,2}:\n  1.0  -1.0\n -2.0   2.0\n\njulia> X, Y = dsylvsys(A, B, C, D, E, F);\n\njulia> X\n2×2 Array{Float64,2}:\n  2.472  -1.648\n -1.848   1.232\n\njulia> Y\n2×2 Array{Float64,2}:\n -0.496  -0.336\n  0.264   0.824\n\njulia> A*X + D*Y - C\n2×2 Array{Float64,2}:\n  4.44089e-16  0.0\n -3.55271e-15  1.55431e-15\n \njulia> X*B + Y*E - F\n2×2 Array{Float64,2}:\n -8.88178e-16   0.0\n  8.88178e-16  -4.44089e-16\n```\n\"\"\"\nfunction dsylvsys(A::AbstractMatrix,B::AbstractMatrix,C::AbstractMatrix,D::AbstractMatrix,E::AbstractMatrix,F::AbstractMatrix)\n\n    m, n = size(C);\n    (m == size(F,1) && n == size(F,2)) ||\n      throw(DimensionMismatch(\"C and F must have the same dimensions\"))\n    [m; n; m; n] == LinearAlgebra.checksquare(A,B,D,E) ||\n       throw(DimensionMismatch(\"A, B, C, D, E and F have incompatible dimensions\"))\n\n    T2 = promote_type(eltype(A), eltype(B), eltype(C), eltype(D), eltype(E), eltype(F))\n    T2 <: BlasFloat || (T2 = promote_type(Float64,T2))\n    eltype(A) == T2 || (A = convert(Matrix{T2},A))\n    eltype(B) == T2 || (B = convert(Matrix{T2},B))\n    eltype(C) == T2 || (C = convert(Matrix{T2},C))\n    eltype(D) == T2 || (D = convert(Matrix{T2},D))\n    eltype(E) == T2 || (E = convert(Matrix{T2},E))\n    eltype(F) == T2 || (F = convert(Matrix{T2},F))\n    realcase = T2 <: AbstractFloat\n    transsylv = isa(A,Adjoint) && isa(B,Adjoint) && isa(D,Adjoint) && isa(E,Adjoint)\n    realcase ? trans = 'T' : trans = 'C'\n    if transsylv\n       AS, DS, Q1, Z1 = schur(A.parent,D.parent)\n       BS, ES, Q2, Z2 = schur(B.parent,E.parent)\n       CS = adjoint(Z1) * (C*Z2)\n       FS = adjoint(Q1) * (F*Q2)\n       X, Y, scale =  tgsyl!(trans,AS,BS,CS,DS,ES,-FS)\n       (rmul!(Q1*(X * adjoint(Z2)), inv(scale)), rmul!(Q1*(Y * adjoint(Z2)), inv(scale)) )\n    else\n       AS, DS, Q1, Z1 = schur(copy(A'),copy(D'))\n       BS, ES, Q2, Z2 = schur(copy(B'),copy(E'))\n       CS = adjoint(Z1) * (C*Z2)\n       FS = adjoint(Q1) * (F*Q2)\n\n       X, Y, scale =  tgsyl!(trans,AS,BS,CS,DS,ES,-FS)\n\n       (rmul!(Q1*(X * adjoint(Z2)), inv(scale)), rmul!(Q1*(Y * adjoint(Z2)), inv(scale)) )\n    end\nend\n\"\"\"\n    sylvcs!(A,B,C; adjA = false, adjB = false)\n\nSolve the continuous Sylvester matrix equation\n\n                op(A)X + Xop(B) =  C,\n\nwhere `op(A) = A` or `op(A) = A'` if `adjA = false` or `adjA = true`, respectively,\nand `op(B) = B` or `op(B) = B'` if `adjB = false` or `adjB = true`, respectively.\n`A` and `B` are square matrices in Schur forms, and `A` and `-B` must not have\ncommon eigenvalues. `C` contains on output the solution `X`.\n\n_Note:_ This is an enhanced interface to `LAPACK.trsyl!` also covering the case when\n`A` and `B` are real matrices and `C` is a complex matrix. \n\"\"\"\nfunction sylvcs!(A::T1, B::T1, C::Union{T1,T2}; adjA = false, adjB = false) where \n     {T1<:Union{Matrix{Float32},Matrix{Float64}}, T2<:Union{Matrix{Complex{Float64}},Matrix{Complex{Float32}}} }\n   \"\"\"\n   This is a wrapper to the LAPACK.trsylv! function for real matrices A and B, \n   based on the Bartels-Stewart Schur form based approach.\n   For a complex C, two calls of trsyl! are performed (for the real and imaginary parts). \n   Reference:\n   R. H. Bartels and G. W. Stewart. Algorithm 432: Solution of the matrix equation AX+XB=C.\n   Comm. ACM, 15:820–826, 1972.\n   \"\"\"\n   T = eltype(A)\n   TC = eltype(C)\n   TR = real(TC)\n   T == TR || error(\"TypeError: for real part of C expected Type{$T}, got Type{$TR}\")\n    cmplx = TC <: Complex \n   adjA ? TA = 'T' : TA = 'N'\n   adjB ? TB = 'T' : TB = 'N'\n   if cmplx\n      YR = real(C)\n      YR, scale = LAPACK.trsyl!(TA, TB, A, B, YR)\n      rmul!(YR, inv(scale))\n      YI = imag(C)\n      YI, scale = LAPACK.trsyl!(TA, TB, A, B, YI)\n      rmul!(YI, inv(scale)) \n      C[:,:] = YR + im*YI\n      return C\n   else\n      C, scale = LAPACK.trsyl!(TA, TB, A, B, C)\n      rmul!(C, inv(scale))\n      return C\n   end\nend\nfunction sylvcs!(A::T, B::T, C::T; adjA = false, adjB = false) where  {T<:Union{Matrix{Complex{Float64}},Matrix{Complex{Float32}}}}\n   \"\"\"\n   This is a wrapper to the LAPACK.trsylv! function, based on the Bartels-Stewart Schur form based approach.\n   Reference:\n   R. H. Bartels and G. W. Stewart. Algorithm 432: Solution of the matrix equation AX+XB=C.\n   Comm. ACM, 15:820–826, 1972.\n   \"\"\"\n   adjA ? TA = 'C' : TA = 'N'\n   adjB ? TB = 'C' : TB = 'N'\n   C, scale = LAPACK.trsyl!(TA, TB, A, B, C)\n   rmul!(C, inv(scale))\nend\n\"\"\"\n    sylvds!(A,B,C; adjA = false, adjB = false)\n\nSolve the discrete Sylvester matrix equation\n\n                op(A)Xop(B) + X =  C,\n\nwhere `op(A) = A` or `op(A) = A'` if `adjA = false` or `adjA = true`, respectively,\nand `op(B) = B` or `op(B) = B'` if `adjB = false` or `adjB = true`, respectively.\n`A` and `B` are square matrices in Schur forms, and `A` and `-B` must not have\ncommon reciprocal eigenvalues. `C` contains on output the solution `X`.\n\"\"\"\nfunction sylvds!(A::T1, B::T1, C::Union{T1,T2}; adjA = false, adjB = false) where \n   {T1<:Union{Matrix{Float32},Matrix{Float64}}, T2<:Union{Matrix{Complex{Float64}},Matrix{Complex{Float32}}} }\n#function sylvds!(A::T, B::T, C::T; adjA = false, adjB = false) where  {T<:Union{Array{Float64,2},Array{Float32,2}}}\n   \"\"\"\n   An extension of the Bartels-Stewart Schur form based approach is employed.\n\n   Reference:\n   R. H. Bartels and G. W. Stewart. Algorithm 432: Solution of the matrix equation AX+XB=C.\n   Comm. ACM, 15:820–826, 1972.\n   \"\"\"\n   m, n = LinearAlgebra.checksquare(A,B)\n   (size(C,1) == m && size(C,2) == n ) || throw(DimensionMismatch(\"C must be an $m x $n matrix\"))\n   \n   T = eltype(A)\n   TC = eltype(C)\n   TR = real(TC)\n   T == TR || error(\"TypeError: for real part of C expected Type{$T}, got Type{$TR}\")\n \n   # determine the structure of the real Schur form of A\n   ba = fill(1,m,1)\n   pa = 1\n   if m > 1\n      d = [diag(A,-1);zeros(1)]\n      i = 1\n      pa = 0\n      while i <= m\n         pa += 1\n         if d[i] != 0\n            ba[pa] = 2\n            i += 1\n         end\n         i += 1\n      end\n   end\n   # determine the structure of the real Schur form of B\n   bb = fill(1,n,1)\n   pb = 1\n   if n > 1\n      d = [diag(B,-1);zeros(1)]\n      i = 1\n      pb = 0\n      while i <= n\n         pb += 1\n         if d[i] != 0\n            bb[pb] = 2\n            i += 1\n         end\n         i += 1\n      end\n   end\n\n   W = fill(zero(eltype(C)),m,2)\n   if !adjA && !adjB\n      \"\"\"\n      The (K,L)th block of X is determined starting from\n      bottom-left corner column by column by\n\n                 A(K,K)*X(K,L)*B(L,L) + X(K,L) = C(K,L) - R(K,L)\n\n      where\n                             M\n                 R(K,L) = { SUM [A(K,J)*X(J,L)] } * B(L,L) +\n                           J=K+1\n                             M             L-1\n                            SUM { A(K,J) * SUM [X(J,I)*B(I,L)] }.\n                            J=K            I=1\n      \"\"\"\n      j = 1\n      for ll = 1:pb\n          dl = bb[ll]\n          dll = 1:dl\n          il1 = 1:j-1\n          j1 = j+dl-1\n          l = j:j1\n          i = m\n          for kk = pa:-1:1\n              dk = ba[kk]\n              dkk = 1:dk\n              i1 = i-dk+1\n              k = i1:i\n              y = C[k,l]\n              if kk < pa\n                 ir = i+1:m\n                 W1 = A[k,ir]*C[ir,l]\n                 y -= W1*B[l,l]\n              end\n              if ll > 1\n                 ic = i1:m\n                 W[k,dll] = C[k,il1]*B[il1,l]\n                 y -= A[k,ic]*W[ic,dll]\n              end\n              Z = (kron(transpose(B[l,l]),A[k,k])+I)\\(y[:])\n              isfinite(maximum(abs.(Z))) ? C[k,l] = Z : throw(\"SingularException: A and -B have common or close reciprocal eigenvalues\")\n              i -= dk\n          end\n          j += dl\n      end\n   elseif !adjA && adjB\n         \"\"\"\n         The (K,L)th block of X is determined starting from\n         bottom-right corner column by column by\n\n                     A(K,K)*X(K,L)*B(L,L)' + X(K,L) = C(K,L) - R(K,L)\n\n         where\n                                M\n                    R(K,L) = { SUM [A(K,J)*X(J,L)] } * B(L,L)' +\n                              J=K+1\n                                M              N\n                               SUM { A(K,J) * SUM [X(J,I)*B(L,I)'] }.\n                               J=K           I=L+1\n         \"\"\"\n         j = n\n         for ll = pb:-1:1\n             dl = bb[ll]\n             dll = 1:dl\n             il1 = j+1:n\n             l = j-dl+1:j\n             i = m\n             for kk = pa:-1:1\n                 dk = ba[kk]\n                 dkk = 1:dk\n                 i1 = i-dk+1\n                 k = i1:i\n                 y = C[k,l]\n                 if kk < pa\n                    ir = i+1:m\n                    W1 = A[k,ir]*C[ir,l]\n                    y -= W1*B[l,l]'\n                 end\n                 if ll < pb\n                    ic = i1:m\n                    W[k,dll] = C[k,il1]*B[l,il1]'\n                    y -= A[k,ic]*W[ic,dll]\n                 end\n                 Z = (kron(B[l,l],A[k,k])+I)\\(y[:])\n                 isfinite(maximum(abs.(Z))) ? C[k,l] = Z : throw(\"SingularException: A and -B have common or close reciprocal eigenvalues\")\n                 i -= dk\n             end\n             j -= dl\n         end\n   elseif adjA && !adjB\n      \"\"\"\n      The (K,L)th block of X is determined starting from the\n      upper-left corner column by column by\n\n      A(K,K)'*X(K,L)*B(L,L) + X(K,L) = C(K,L) - R(K,L),\n\n      where\n                            K-1\n                 R(K,L) = { SUM [A(J,K)'*X(J,L)] } * B(L,L) +\n                            J=1\n                             K              L-1\n                            SUM A(J,K)' * { SUM [X(J,I)*B(I,L)] }.\n                            J=1             I=1\n      \"\"\"\n      j = 1\n      for ll = 1:pb\n          dl = bb[ll]\n          dll = 1:dl\n          il1 = 1:j-1\n          j1 = j+dl-1\n          l = j:j1\n          i = 1\n          for kk = 1:pa\n              dk = ba[kk]\n              dkk = 1:dk\n              i1 = i+dk-1\n              k = i:i1\n              y = C[k,l]\n              if kk > 1\n                 ir = 1:i-1\n                 W1 = A[ir,k]'*C[ir,l]\n                 y -= W1*B[l,l]\n              end\n              if ll > 1\n                 ic = 1:i1\n                 W[k,dll] = C[k,il1]*B[il1,l]\n                 y -= A[ic,k]'*W[ic,dll]\n              end\n              Z = (kron(transpose(B[l,l]),transpose(A[k,k]))+I)\\(y[:])\n              isfinite(maximum(abs.(Z))) ? C[k,l] = Z : throw(\"SingularException: A and -B have common or close reciprocal eigenvalues\")\n              i += dk\n          end\n          j += dl\n      end\n   elseif adjA && adjB\n      \"\"\"\n      The (K,L)th block of X is determined starting from the\n      lower-left corner column by column by\n\n                 A(K,K)'*X(K,L)*B(L,L)' + X(K,L) = C(K,L) - R(K,L)\n\n      where\n                            K-1\n                 R(K,L) = { SUM [A(J,K)'*X(J,L)] } * B(L,L)' +\n                            J=1\n                             K               N\n                            SUM A(J,K)' * { SUM [X(J,I)*B(L,I)'] }.\n                            J=1            I=L+1\n      \"\"\"\n      j = n\n      for ll = pb:-1:1\n          dl = bb[ll]\n          dll = 1:dl\n          il1 = j+1:n\n          l = j-dl+1:j\n          i = 1\n          for kk = 1:pa\n              dk = ba[kk]\n              dkk = 1:dk\n              i1 = i+dk-1\n              k = i:i1\n              y = C[k,l]\n              if kk > 1\n                 ir = 1:i-1\n                 W1 = A[ir,k]'*C[ir,l]\n                 y -= W1*B[l,l]'\n              end\n              if ll < pb\n                 ic = 1:i1\n                 W[k,dll] = C[k,il1]*B[l,il1]'\n                 y -= A[ic,k]'*W[ic,dll]\n              end\n              Z = (kron(B[l,l],transpose(A[k,k]))+I)\\(y[:])\n              isfinite(maximum(abs.(Z))) ? C[k,l] = Z : throw(\"SingularException: A and -B have common or close reciprocal eigenvalues\")\n              i += dk\n          end\n          j -= dl\n      end\n   end\n   return C\nend\nfunction sylvds!(A::T, B::T, C::T; adjA = false, adjB = false) where {T<:Union{Matrix{Complex{Float64}},Matrix{Complex{Float32}}}}\n   \"\"\"\n   An extension of the Bartels-Stewart Schur form based approach is employed.\n\n   Reference:\n   R. H. Bartels and G. W. Stewart. Algorithm 432: Solution of the matrix equation AX+XB=C.\n   Comm. ACM, 15:820–826, 1972.\n   \"\"\"\n   m, n = LinearAlgebra.checksquare(A,B)\n   (size(C,1) == m && size(C,2) == n ) || throw(DimensionMismatch(\"C must be an $m x $n matrix\"))\n  \n   W = fill(zero(eltype(C)),m,1)\n   if !adjA && !adjB\n      \"\"\"\n      The (K,L)th element of X is determined starting from\n      bottom-left corner column by column by\n\n                 A(K,K)*X(K,L)*B(L,L) + X(K,L) = C(K,L) - R(K,L)\n\n      where\n                             M\n                 R(K,L) = { SUM [A(K,J)*X(J,L)] } * B(L,L) +\n                           J=K+1\n                             M             L-1\n                            SUM { A(K,J) * SUM [X(J,I)*B(I,L)] }.\n                            J=K            I=1\n      \"\"\"\n      for l = 1:n\n          il1 = 1:l-1\n          ll = l:l\n          for k = m:-1:1\n              y = C[k,l]\n              kk = k:k\n              if k < m\n                 ir = k+1:m\n                 W1 = A[kk,ir]*C[ir,ll]\n                 y -= W1[1]*B[l,l]\n              end\n              if l > 1\n                 ic = k:m\n                 Z = C[kk,il1]*B[il1,ll]\n                 W[k,1] = Z[1]\n                 TA = A[kk,ic]*W[ic,1]\n                 y -= TA[1]\n              end\n              Z = y/(B[l,l]*A[k,k]+I)\n              isfinite(Z) ? C[k,l] = Z : throw(\"SingularException: A and -B have common or close reciprocal eigenvalues\")\n             end\n      end\n   elseif !adjA && adjB\n         \"\"\"\n         The (K,L)th element of X is determined starting from\n         bottom-right corner column by column by\n\n                  A(K,K)*X(K,L)*B(L,L)' + X(K,L) = C(K,L) - R(K,L)\n\n         where\n                                M\n                    R(K,L) = { SUM [A(K,J)*X(J,L)] } * B(L,L)' +\n                              J=K+1\n                                M              N\n                               SUM { A(K,J) * SUM [X(J,I)*B(L,I)'] }.\n                               J=K           I=L+1\n         \"\"\"\n         for l = n:-1:1\n             ll = l:l\n             il1 = l+1:n\n             for k = m:-1:1\n                 kk = k:k\n                 y = C[k,l]\n                 if k < m\n                    ir = k+1:m\n                    W1 = A[kk,ir]*C[ir,ll]\n                    y -= W1[1]*B[l,l]'\n                 end\n                 if l < n\n                    ic = k:m\n                    Z = C[kk,il1]*B[ll,il1]'\n                    W[k,1] = Z[1]\n                    TA = A[kk,ic]*W[ic,1]\n                    y -= TA[1]\n                 end\n                 Z = y/(B[l,l]'*A[k,k]+I)\n                 isfinite(Z) ? C[k,l] = Z : throw(\"SingularException: A and -B have common or close reciprocal eigenvalues\")\n             end\n         end\n   elseif adjA && !adjB\n      \"\"\"\n      The (K,L)th element of X is determined starting from the\n      upper-left corner column by column by\n\n               A(K,K)'*X(K,L)*B(L,L) + X(K,L) = C(K,L) - R(K,L),\n\n      where\n                            K-1\n                 R(K,L) = { SUM [A(J,K)'*X(J,L)] } * B(L,L) +\n                            J=1\n                             K              L-1\n                            SUM A(J,K)' * { SUM [X(J,I)*B(I,L)] }.\n                            J=1             I=1\n      \"\"\"\n      for l = 1:n\n          ll = l:l\n          il1 = 1:l-1\n          for k = 1:m\n              kk = k:k\n              y = C[k,l]\n              if k > 1\n                 ir = 1:k-1\n                 W1 = A[ir,kk]'*C[ir,ll]\n                 y -= W1[1]*B[l,l]\n              end\n              if l > 1\n                 ic = 1:m\n                 Z = C[kk,il1]*B[il1,ll]\n                 W[k,1] = Z[1]\n                 TA = A[ic,kk]'*W[ic,1]\n                 y -= TA[1]\n              end\n              Z = y/(B[l,l]*A[k,k]'+I)\n              isfinite(Z) ? C[k,l] = Z : throw(\"SingularException: A and -B have common or close reciprocal eigenvalues\")\n          end\n      end\n   elseif adjA && adjB\n      \"\"\"\n      The (K,L)th element of X is determined starting from the\n      upper-right corner column by column by\n\n              A(K,K)'*X(K,L)*B(L,L)' + X(K,L) = C(K,L) - R(K,L)\n\n      where\n                            K-1\n                 R(K,L) = { SUM [A(J,K)'*X(J,L)] } * B(L,L)' +\n                            J=1\n                             K               N\n                            SUM A(J,K)' * { SUM [X(J,I)*B(L,I)'] }.\n                            J=1            I=L+1\n      \"\"\"\n      for l = n:-1:1\n          ll = l:l\n          il1 = l+1:n\n          for k = 1:m\n              kk = k:k\n              y = C[k,l]\n              if k > 1\n                 ir = 1:k-1\n                 W1 = A[ir,kk]'*C[ir,ll]\n                 y -= W1[1]*B[l,l]'\n              end\n              if l < n\n                 ic = 1:m\n                 Z = C[kk,il1]*B[ll,il1]'\n                 W[k,1] = Z[1]\n                 TA = A[ic,kk]'*W[ic,1]\n                 y -= TA[1]\n              end\n              Z = y/(B[l,l]'*A[k,k]'+I)\n              isfinite(Z) ? C[k,l] = Z : throw(\"SingularException: A and -B have common or close reciprocal eigenvalues\")\n          end\n      end\n   end\n   return C\nend\n\"\"\"\n    X = gsylvs!(A,B,C,D,E; adjAC=false, adjBD=false, DBSchur = false)\n\nSolve the generalized Sylvester matrix equation\n\n                op1(A)Xop2(B) + op1(C)Xop2(D) = E,\n\nwhere `A`, `B`, `C` and `D` are square matrices, and\n\n`op1(A) = A` and `op1(C) = C` if `adjAC = false`;\n\n`op1(A) = A'` and `op1(C) = C'` if `adjAC = true`;\n\n`op2(B) = B` and `op2(D) = D` if `adjBD = false`;\n\n`op2(B) = B'` and `op2(D) = D'` if `adjBD = true`.\n\nThe matrix pair `(A,C)` is in a generalized real or complex Schur form.\nThe matrix pair `(B,D)` is in a generalized real or complex Schur form if `DBSchur = false`\nor the matrix pair `(D,B)` is in a generalized real or complex Schur form if `DBSchur = true`.\nThe pencils `A-λC` and `D+λB` must be regular and must not have common eigenvalues.\n\"\"\"\nfunction gsylvs!(A::T1, B::T1, C::T1, D::T1, E::Union{T1,T2}; adjAC = false, adjBD = false, CASchur = false, DBSchur = false) where \n   {T1<:Union{Matrix{Float32},Matrix{Float64}}, T2<:Union{Matrix{Complex{Float64}},Matrix{Complex{Float32}}} }\n   \"\"\"\n   An extension proposed in [1] of the Bartels-Stewart Schur form based approach [2] is employed.\n\n   References:\n   [1] K.-W. E. Chu. The solution of the matrix equation AXB – CXD = E and\n       (YA – DZ, YC– BZ) = (E, F). Lin. Alg. Appl., 93:93-105, 1987.\n   [2] R. H. Bartels and G. W. Stewart. Algorithm 432: Solution of the matrix equation AX+XB=C.\n       Comm. ACM, 15:820–826, 1972.\n   \"\"\"\n   m, n = size(E);\n   [m; n; m; n] == LinearAlgebra.checksquare(A,B,C,D) || \n      throw(DimensionMismatch(\"A, B, C, D and E have incompatible dimensions\"))\n \n   T = eltype(A)\n   TE = eltype(E)\n   TR = real(TE)\n   T == TR || error(\"TypeError: for real part of E expected Type{$T}, got Type{$TR}\")\n\n   # determine the structure of the generalized real Schur form of (A,C)\n   ba = fill(1,m,1)\n   pa = 1\n   if m > 1\n      CASchur ? d = [diag(C,-1);zeros(1)] : d = [diag(A,-1);zeros(1)]\n      i = 1\n      pa = 0\n      while i <= m\n         pa += 1\n         if d[i] != 0\n            ba[pa] = 2\n            i += 1\n         end\n         i += 1\n      end\n   end\n   # determine the structure of the generalized real Schur form of (B,D)\n   bb = fill(1,n,1)\n   pb = 1\n   if n > 1\n      DBSchur ? d = [diag(D,-1);zeros(1)] : d = [diag(B,-1);zeros(1)]\n      i = 1\n      pb = 0\n      while i <= n\n         pb += 1\n         if d[i] != 0\n            bb[pb] = 2\n            i += 1\n         end\n         i += 1\n      end\n   end\n\n   WB = fill(zero(eltype(E)),m,2)\n   WD = fill(zero(eltype(E)),m,2)\n   if !adjAC && !adjBD\n      \"\"\"\n      The (K,L)th block of X is determined starting from\n      bottom-left corner column by column by\n\n            A(K,K)*X(K,L)*B(L,L) + C(K,K)*X(K,L)*D(L,L) = E(K,L) - R(K,L)\n\n      where\n                             M\n                 R(K,L) = { SUM [A(K,J)*X(J,L)] } * B(L,L) +\n                           J=K+1\n                             M             L-1\n                            SUM { A(K,J) * SUM [X(J,I)*B(I,L)] } +\n                            J=K            I=1\n\n                             M\n                          { SUM [C(K,J)*X(J,L)] } * D(L,L) +\n                           J=K+1\n                             M             L-1\n                            SUM { C(K,J) * SUM [X(J,I)*D(I,L)] }.\n                            J=K            I=1\n      \"\"\"\n      j = 1\n      for ll = 1:pb\n          dl = bb[ll]\n          dll = 1:dl\n          il1 = 1:j-1\n          j1 = j+dl-1\n          l = j:j1\n          i = m\n          for kk = pa:-1:1\n              dk = ba[kk]\n              dkk = 1:dk\n              i1 = i-dk+1\n              k = i1:i\n              y = E[k,l]\n              if kk < pa\n                 ir = i+1:m\n                 W1 = A[k,ir]*E[ir,l]\n                 y -= W1*B[l,l]\n                 W1 = C[k,ir]*E[ir,l]\n                 y -= W1*D[l,l]\n              end\n              if ll > 1\n                 ic = i1:m\n                 WB[k,dll] = E[k,il1]*B[il1,l]\n                 WD[k,dll] = E[k,il1]*D[il1,l]\n                 y -= (A[k,ic]*WB[ic,dll] + C[k,ic]*WD[ic,dll])\n              end\n              Z = (kron(transpose(B[l,l]),A[k,k])+kron(transpose(D[l,l]),C[k,k]))\\(y[:])\n              isfinite(maximum(abs.(Z))) ? E[k,l] = Z : throw(\"SingularException: A-λC and D+λB have common or close eigenvalues\")\n              i -= dk\n          end\n          j += dl\n      end\n   elseif !adjAC && adjBD\n         \"\"\"\n          The (K,L)th block of X is determined starting from\n          bottom-right corner column by column by\n\n               A(K,K)*X(K,L)*B(L,L)' + C(K,K)*X(K,L)*D(L,L)' = E(K,L) - R(K,L)\n\n          where\n                                M\n                    R(K,L) = { SUM [A(K,J)*X(J,L)] } * B(L,L)' +\n                              J=K+1\n                                M              N\n                               SUM { A(K,J) * SUM [X(J,I)*B(L,I)'] } +\n                               J=K           I=L+1\n\n                               M\n                            { SUM [C(K,J)*X(J,L)] } * D(L,L)' +\n                             J=K+1\n                               M              N\n                              SUM { C(K,J) * SUM [X(J,I)*D(L,I)'] }.\n                              J=K           I=L+1\n         \"\"\"\n         j = n\n         for ll = pb:-1:1\n             dl = bb[ll]\n             dll = 1:dl\n             il1 = j+1:n\n             l = j-dl+1:j\n             i = m\n             for kk = pa:-1:1\n                 dk = ba[kk]\n                 dkk = 1:dk\n                 i1 = i-dk+1\n                 k = i1:i\n                 y = E[k,l]\n                 if kk < pa\n                    ir = i+1:m\n                    W1 = A[k,ir]*E[ir,l]\n                    y -= W1*B[l,l]'\n                    W2 = C[k,ir]*E[ir,l]\n                    y -= W2*D[l,l]'\n                 end\n                 if ll < pb\n                    ic = i1:m\n                    WB[k,dll] = E[k,il1]*B[l,il1]'\n                    WD[k,dll] = E[k,il1]*D[l,il1]'\n                    y -= (A[k,ic]*WB[ic,dll]+C[k,ic]*WD[ic,dll])\n                 end\n                 Z = (kron(B[l,l],A[k,k])+kron(D[l,l],C[k,k]))\\(y[:])\n                 isfinite(maximum(abs.(Z))) ? E[k,l] = Z : throw(\"SingularException: A-λC and D+λB have common or close eigenvalues\")\n                 i -= dk\n             end\n             j -= dl\n         end\n   elseif adjAC && !adjBD\n      \"\"\"\n      The (K,L)th block of X is determined starting from the\n      upper-left corner column by column by\n\n      A(K,K)'*X(K,L)*B(L,L) + C(K,K)'*X(K,L)*D(L,L) = E(K,L) - R(K,L),\n\n      where\n                            K-1\n                 R(K,L) = { SUM [A(J,K)'*X(J,L)] } * B(L,L) +\n                            J=1\n                             K              L-1\n                            SUM A(J,K)' * { SUM [X(J,I)*B(I,L)] } +\n                            J=1             I=1\n\n                            K-1\n                          { SUM [C(J,K)'*X(J,L)] } * D(L,L) +\n                            J=1\n                             K              L-1\n                            SUM C(J,K)' * { SUM [X(J,I)*D(I,L)] }.\n                            J=1             I=1\n      \"\"\"\n      j = 1\n      for ll = 1:pb\n          dl = bb[ll]\n          dll = 1:dl\n          il1 = 1:j-1\n          j1 = j+dl-1\n          l = j:j1\n          i = 1\n          for kk = 1:pa\n              dk = ba[kk]\n              dkk = 1:dk\n              i1 = i+dk-1\n              k = i:i1\n              y = E[k,l]\n              if kk > 1\n                 ir = 1:i-1\n                 W1 = A[ir,k]'*E[ir,l]\n                 y -= W1*B[l,l]\n                 W2 = C[ir,k]'*E[ir,l]\n                 y -= W2*D[l,l]\n              end\n              if ll > 1\n                 ic = 1:i1\n                 WB[k,dll] = E[k,il1]*B[il1,l]\n                 y -= A[ic,k]'*WB[ic,dll]\n                 WD[k,dll] = E[k,il1]*D[il1,l]\n                 y -= C[ic,k]'*WD[ic,dll]\n              end\n              Z = (kron(transpose(B[l,l]),transpose(A[k,k]))+kron(transpose(D[l,l]),transpose(C[k,k])))\\(y[:])\n              isfinite(maximum(abs.(Z))) ? E[k,l] = Z : throw(\"SingularException: A-λC and D+λB have common or close eigenvalues\")\n              i += dk\n          end\n          j += dl\n      end\n   elseif adjAC && adjBD\n      \"\"\"\n      The (K,L)th block of X is determined starting from\n      upper-rght corner column by column by\n\n                 A(K,K)'*X(K,L)*B(L,L)' + C(K,K)'*X(K,L)*D(L,L)' = E(K,L) - R(K,L)\n\n      where\n                            K-1\n                 R(K,L) = { SUM [A(J,K)'*X(J,L)] } * B(L,L)' +\n                            J=1\n                             K               N\n                            SUM A(J,K)' * { SUM [X(J,I)*B(L,I)'] }+\n                            J=1            I=L+1\n\n                            K-1\n                          { SUM [C(J,K)'*X(J,L)] } * D(L,L)' +\n                            J=1\n                             K               N\n                            SUM C(J,K)' * { SUM [X(J,I)*D(L,I)'] }.\n                            J=1            I=L+1\n      \"\"\"\n      j = n\n      for ll = pb:-1:1\n          dl = bb[ll]\n          dll = 1:dl\n          il1 = j+1:n\n          l = j-dl+1:j\n          i = 1\n          for kk = 1:pa\n              dk = ba[kk]\n              dkk = 1:dk\n              i1 = i+dk-1\n              k = i:i1\n              y = E[k,l]\n              if kk > 1\n                 ir = 1:i-1\n                 W1 = A[ir,k]'*E[ir,l]\n                 y -= W1*B[l,l]'\n                 W2 = C[ir,k]'*E[ir,l]\n                 y -= W2*D[l,l]'\n              end\n              if ll < pb\n                 ic = 1:i1\n                 WB[k,dll] = E[k,il1]*B[l,il1]'\n                 WD[k,dll] = E[k,il1]*D[l,il1]'\n                 y -= (A[ic,k]'*WB[ic,dll] + C[ic,k]'*WD[ic,dll])\n              end\n              Z = (kron(B[l,l],transpose(A[k,k]))+kron(D[l,l],transpose(C[k,k])))\\(y[:])\n              isfinite(maximum(abs.(Z))) ? E[k,l] = Z : throw(\"SingularException: A-λC and D+λB have common or close eigenvalues\")\n              i += dk\n          end\n          j -= dl\n      end\n   end\n   return E\nend\nfunction gsylvs!(A::T, B::T, C::T, D::T, E::T; adjAC = false, adjBD = false, CASchur = false, DBSchur = false) where {T<:Union{Array{Complex{Float64},2},Array{Complex{Float32},2}}}\n   \"\"\"\n   An extension proposed in [1] of the Bartels-Stewart Schur form based approach [2] is employed.\n\n   References:\n   [1] K.-W. E. Chu. The solution of the matrix equation AXB – CXD = E and\n       (YA – DZ, YC– BZ) = (E, F). Lin. Alg. Appl., 93:93-105, 1987.\n   [2] R. H. Bartels and G. W. Stewart. Algorithm 432: Solution of the matrix equation AX+XB=C.\n       Comm. ACM, 15:820–826, 1972.\n   \"\"\"\n   m, n = size(E);\n   [m; n; m; n] == LinearAlgebra.checksquare(A,B,C,D) ||\n      throw(DimensionMismatch(\"A, B, C, D and E have incompatible dimensions\"))\n\n   WB = fill(zero(eltype(E)),m,1)\n   WD = fill(zero(eltype(E)),m,1)\n   if !adjAC && !adjBD\n      \"\"\"\n      The (K,L)th element of X is determined starting from\n      bottom-left corner column by column by\n\n            A(K,K)*X(K,L)*B(L,L) +C(K,K)*X(K,L)*D(L,L) = E(K,L) - R(K,L)\n\n      where\n                             M\n                 R(K,L) = { SUM [A(K,J)*X(J,L)] } * B(L,L) +\n                           J=K+1\n                             M             L-1\n                            SUM { A(K,J) * SUM [X(J,I)*B(I,L)] } +\n                            J=K            I=1\n\n                            M\n                         { SUM [C(K,J)*X(J,L)] } * D(L,L) +\n                          J=K+1\n                            M             L-1\n                           SUM { C(K,J) * SUM [X(J,I)*D(I,L)] } +\n                           J=K            I=1\n      \"\"\"\n      for l = 1:n\n          il1 = 1:l-1\n          ll = l:l\n          for k = m:-1:1\n              y = E[k,l]\n              kk = k:k\n              if k < m\n                 ir = k+1:m\n                 W1 = A[kk,ir]*E[ir,ll]\n                 W2 = C[kk,ir]*E[ir,ll]\n                 y -= (W1[1]*B[l,l]+W2[1]*D[l,l])\n              end\n              if l > 1\n                 ic = k:m\n                 ZB = E[kk,il1]*B[il1,ll]\n                 ZD = E[kk,il1]*D[il1,ll]\n                 WB[k,1] = ZB[1]\n                 WD[k,1] = ZD[1]\n                 TB = A[kk,ic]*WB[ic,1]\n                 TD = C[kk,ic]*WD[ic,1]\n                 y -= (TB[1]+TD[1])\n              end\n              Z = y/(B[l,l]*A[k,k]+D[l,l]*C[k,k])\n              isfinite(Z) ? E[k,l] = Z : throw(\"SingularException: A-λC and D+λB have common or close eigenvalues\")\n          end\n      end\n   elseif !adjAC && adjBD\n         \"\"\"\n          The (K,L)th element of X is determined starting from\n          bottom-right corner column by column by\n\n               A(K,K)*X(K,L)*B(L,L)' + C(K,K)*X(K,L)*D(L,L)' = E(K,L) - R(K,L)\n\n          where\n                                M\n                    R(K,L) = { SUM [A(K,J)*X(J,L)] } * B(L,L)' +\n                              J=K+1\n                                M              N\n                               SUM { A(K,J) * SUM [X(J,I)*B(L,I)'] } +\n                               J=K           I=L+1\n\n                               M\n                            { SUM [C(K,J)*X(J,L)] } * D(L,L)' +\n                             J=K+1\n                               M              N\n                              SUM { C(K,J) * SUM [X(J,I)*D(L,I)'] }.\n                              J=K           I=L+1\n         \"\"\"\n         for l = n:-1:1\n             ll = l:l\n             il1 = l+1:n\n             for k = m:-1:1\n                 kk = k:k\n                 y = E[k,l]\n                 if k < m\n                    ir = k+1:m\n                    W1 = A[kk,ir]*E[ir,ll]\n                    W2 = C[kk,ir]*E[ir,ll]\n                    y -= (W1[1]*B[l,l]'+W2[1]*D[l,l]')\n                 end\n                 if l < n\n                    ic = k:m\n                    ZB = E[kk,il1]*B[ll,il1]'\n                    ZD = E[kk,il1]*D[ll,il1]'\n                    WB[k,1] = ZB[1]\n                    WD[k,1] = ZD[1]\n                    TB = A[kk,ic]*WB[ic,1]\n                    TD = C[kk,ic]*WD[ic,1]\n                    y -= (TB[1]+TD[1])\n                 end\n                 Z = y/(B[l,l]'*A[k,k]+D[l,l]'*C[k,k])\n                 isfinite(Z) ? E[k,l] = Z : throw(\"SingularException: A-λC and D+λB have common or close eigenvalues\")\n             end\n         end\n   elseif adjAC && !adjBD\n      \"\"\"\n      The (K,L)th element of X is determined starting from the\n      upper-left corner column by column by\n\n      A(K,K)'*X(K,L)*B(L,L) + C(K,K)'*X(K,L)*D(L,L) = E(K,L) - R(K,L),\n\n      where\n                            K-1\n                 R(K,L) = { SUM [A(J,K)'*X(J,L)] } * B(L,L) +\n                            J=1\n                             K              L-1\n                            SUM A(J,K)' * { SUM [X(J,I)*B(I,L)] } +\n                            J=1             I=1\n\n                            K-1\n                          { SUM [C(J,K)'*X(J,L)] } * D(L,L) +\n                            J=1\n                             K              L-1\n                            SUM C(J,K)' * { SUM [X(J,I)*D(I,L)] }.\n                            J=1             I=1\n      \"\"\"\n      for l = 1:n\n          ll = l:l\n          il1 = 1:l-1\n          for k = 1:m\n              kk = k:k\n              y = E[k,l]\n              if k > 1\n                 ir = 1:k-1\n                 W1 = A[ir,kk]'*E[ir,ll]\n                 W2 = C[ir,kk]'*E[ir,ll]\n                 y -= (W1[1]*B[l,l] + W2[1]*D[l,l])\n              end\n              if l > 1\n                 ic = 1:m\n                 ZB = E[kk,il1]*B[il1,ll]\n                 ZD = E[kk,il1]*D[il1,ll]\n                 WB[k,1] = ZB[1]\n                 WD[k,1] = ZD[1]\n                 TB = A[ic,kk]'*WB[ic,1]\n                 TD = C[ic,kk]'*WD[ic,1]\n                 y -= (TB[1]+TD[1])\n              end\n              Z = y/(B[l,l]*A[k,k]'+D[l,l]*C[k,k]')\n              isfinite(Z) ? E[k,l] = Z : throw(\"SingularException: A-λC and D+λB have common or close eigenvalues\")\n          end\n      end\n   elseif adjAC && adjBD\n      \"\"\"\n      The (K,L)th element of X is determined starting from\n      upper-rght corner column by column by\n\n            A(K,K)'*X(K,L)*B(L,L)' + C(K,K)'*X(K,L)*D(L,L)' = E(K,L) - R(K,L)\n\n      where\n                            K-1\n                 R(K,L) = { SUM [A(J,K)'*X(J,L)] } * B(L,L)' +\n                            J=1\n                             K               N\n                            SUM A(J,K)' * { SUM [X(J,I)*B(L,I)'] }+\n                            J=1            I=L+1\n\n                            K-1\n                          { SUM [C(J,K)'*X(J,L)] } * D(L,L)' +\n                            J=1\n                             K               N\n                            SUM C(J,K)' * { SUM [X(J,I)*D(L,I)'] }.\n                            J=1            I=L+1\n      \"\"\"\n      for l = n:-1:1\n          ll = l:l\n          il1 = l+1:n\n          for k = 1:m\n              kk = k:k\n              y = E[k,l]\n              if k > 1\n                 ir = 1:k-1\n                 W1 = A[ir,kk]'*E[ir,ll]\n                 W2 = C[ir,kk]'*E[ir,ll]\n                 y -= (W1[1]*B[l,l]'+W2[1]*D[l,l]')\n              end\n              if l < n\n                 ic = 1:m\n                 ZB = E[kk,il1]*B[ll,il1]'\n                 ZD = E[kk,il1]*D[ll,il1]'\n                 WB[k,1] = ZB[1]\n                 WD[k,1] = ZD[1]\n                 TB = A[ic,kk]'*WB[ic,1]\n                 TD = C[ic,kk]'*WD[ic,1]\n                 y -= (TB[1]+TD[1])\n              end\n              Z = y/(B[l,l]'*A[k,k]'+D[l,l]'*C[k,k]')\n              isfinite(Z) ? E[k,l] = Z : throw(\"SingularException: A-λC and D+λB have common or close eigenvalues\")\n          end\n      end\n   end\n   return E\nend\n\"\"\"\n    (X,Y) = sylvsyss!(A,B,C,D,E,F)\n\nSolve the Sylvester system of matrix equations\n\n                AX + YB = C\n                DX + YE = F,\n\nwhere `(A,D)`, `(B,E)` are pairs of square matrices of the same size in generalized Schur forms.\nThe pencils `A-λD` and `-B+λE` must be regular and must not have common eigenvalues. The computed\nsolution `(X,Y)` is contained in `(C,F)`.\n\n_Note:_ This is an enhanced interface to the `LAPACK.tgsyl!` function to also cover the case when\n`A`, `B`, `D` and `E` are real matrices and `C` and `F` are complex matrices.\n\"\"\"\nfunction sylvsyss!(A::T, B::T, C::T, D::T, E::T, F::T) where {T<:Union{Array{Complex{Float64},2},Array{Complex{Float32},2}}}\n   \"\"\"\n   This is a wrapper to the complex LAPACK.tgsyl! function with `trans = 'N'`.\n   \"\"\"\n   C, F, scale =  tgsyl!('N',A,B,C,D,E,F)\n   return rmul!(C,inv(scale)), rmul!(F,inv(-scale))\nend\nfunction sylvsyss!(A::T1, B::T1, C::Union{T1,T2}, D::T1, E::T1, F::Union{T1,T2}) where \n   {T1<:Union{Matrix{Float32},Matrix{Float64}}, T2<:Union{Matrix{Complex{Float64}},Matrix{Complex{Float32}}} }\n   \"\"\"\n   This is an enhanced interface to the real LAPACK.tgsyl! function with `trans = 'N'`. \n   For a complex pair (C,F), two calls of tgsyl! are performed (for the real and imaginary parts). \n   \"\"\"\n   T = eltype(A)\n   TC = promote_type(eltype(C),eltype(F))\n   TR = real(TC)\n   T == TR || error(\"TypeError: for real parts of (C,F) expected Type{$T}, got Type{$TR}\")\n   cmplx = TC <: Complex \n   if cmplx\n      XR = real(C)\n      XI = imag(C)\n      YR = real(F)\n      YI = imag(F)\n      XR, YR, scale =  tgsyl!('N',A,B,XR,D,E,YR)\n      rmul!(XR,inv(scale)) \n      rmul!(YR,inv(-scale))\n      XI, YI, scale =  tgsyl!('N',A,B,XI,D,E,YI)\n      rmul!(XI,inv(scale)) \n      rmul!(YI,inv(-scale))\n      C = XR+im*XI\n      F = YR+im*YI\n      return C[:,:], F[:,:]\n   else\n      C, F, scale =  tgsyl!('N',A,B,C,D,E,F)\n      return rmul!(C,inv(scale)), rmul!(F,inv(-scale))\n   end\nend\n\"\"\"\n    (X,Y) = dsylvsyss!(A,B,C,D,E,F)\n\nSolve the dual Sylvester system of matrix equations\n\n\n    A'X + D'Y = C\n    XB' + YE' = F,\n\nwhere `(A,D)`, `(B,E)` are pairs of square matrices of the same size in generalized Schur forms.\nThe pencils `A-λD` and `-B+λE` must be regular and must not have common eigenvalues. The computed\nsolution `(X,Y)` is contained in `(C,F)`.\n\n_Note:_ This is an enhanced interface to the `LAPACK.tgsyl!` function to also cover the case when\n`A`, `B`, `D` and `E` are real matrices and `C` and `F` are complex matrices.\n\"\"\"\nfunction dsylvsyss!(A::T, B::T, C::T, D::T, E::T, F::T) where {T<:Union{Array{Complex{Float64},2},Array{Complex{Float32},2}}}\n   \"\"\"\n   This is an interface to the complex LAPACK.tgsyl! function with `trans = 'C'`. \n   \"\"\"\n   MF = -F\n   E, F, scale =  tgsyl!('C',A,B,C,D,E,MF)\n   F = MF\n   return rmul!(C[:,:],inv(scale)), rmul!(F[:,:],inv(scale))\nend\nfunction dsylvsyss!(A::T1, B::T1, C::Union{T1,T2}, D::T1, E::T1, F::Union{T1,T2}) where \n   {T1<:Union{Matrix{Float32},Matrix{Float64}}, T2<:Union{Matrix{Complex{Float64}},Matrix{Complex{Float32}}} }\n   \"\"\"\n   This is an interface to the real LAPACK.tgsyl! function with `trans = 'T'`. \n   For a complex pair (C,F), two calls of tgsyl! are performed (for the real and imaginary parts). \n   \"\"\"\n   T = eltype(A)\n   TC = promote_type(eltype(C),eltype(F))\n   TR = real(TC)\n   T == TR || error(\"TypeError: for real parts of (C,F) expected Type{$T}, got Type{$TR}\")\n   cmplx = TC <: Complex \n   if cmplx\n      XR = real(C)\n      XI = imag(C)\n      YR = -real(F)\n      YI = -imag(F)\n      XR, YR, scale =  tgsyl!('T',A,B,XR,D,E,YR)\n      rmul!(XR,inv(scale)) \n      rmul!(YR,inv(scale))\n      XI, YI, scale =  tgsyl!('T',A,B,XI,D,E,YI)\n      rmul!(XI,inv(scale)) \n      rmul!(YI,inv(scale))\n      C = XR+im*XI\n      F = YR+im*YI\n      return C[:,:], F[:,:]\n   else\n      MF = -F\n      C, MF, scale =  tgsyl!('T',A,B,C,D,E,MF)\n      F = MF\n      return rmul!(C[:,:],inv(scale)), rmul!(F[:,:],inv(scale))\n   end\nend\n\n", "meta": {"hexsha": "123ad37f6ac6717173e031bf23939fe282a6d86d", "size": 51328, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sylvester.jl", "max_stars_repo_name": "JuliaTagBot/MatrixEquations.jl", "max_stars_repo_head_hexsha": "bfb0adadada58bf169f896ad91e32a23eeb9044c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sylvester.jl", "max_issues_repo_name": "JuliaTagBot/MatrixEquations.jl", "max_issues_repo_head_hexsha": "bfb0adadada58bf169f896ad91e32a23eeb9044c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sylvester.jl", "max_forks_repo_name": "JuliaTagBot/MatrixEquations.jl", "max_forks_repo_head_hexsha": "bfb0adadada58bf169f896ad91e32a23eeb9044c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5282555283, "max_line_length": 180, "alphanum_fraction": 0.4355517456, "num_tokens": 17571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8267118004748678, "lm_q1q2_score": 0.7630873641798772}}
{"text": "\"\"\"\n    step_size(::ForwardMode, x::AbstractFloat)\n\n# Description\n\nDetermine the step-size to use for forward-mode finite differences.\n\n# Arguments\n\n* `::ForwardMode`: An instance of the `ForwardMode` type.\n* `x::AbstractFloat`: A point at which the derivative of a function will be\n    approximated. Its type must implement `eps`.\n\n# Returns\n\n* `ϵ::Real`: The step-size to use for finite differences at `x`.\n\n# References\n\nSee Section 5.7 of Numerical Recipes in C for the mathematical justification\nfor working with `sqrt(eps(typeof(x)))`.\n\n# Examples\n\n```julia\nimport FiniteDiff: step_size, ForwardMode\nϵ = step_size(ForwardMode(), 0.0)\n```\n\"\"\"\n@inline function step_size(::ForwardMode, x::AbstractFloat)::Real\n    return sqrt(eps(typeof(x))) * max(one(typeof(x)), abs(x))\nend\n\n\"\"\"\n    step_size(::BackwardMode, x::AbstractFloat)\n\n# Description\n\nDetermine the step-size to use for backward-mode finite differences.\n\n# Arguments\n\n* `::BackwardMode`: An instance of the `BackwardMode` type.\n* `x::AbstractFloat`: A point at which the derivative of a function will be\n    approximated. Its type must implement `eps`.\n\n# Returns\n\n* `ϵ::Real`: The step-size to use for finite differences at `x`.\n\n# References\n\nSee Section 5.7 of Numerical Recipes in C for the mathematical justification\nfor working with `sqrt(eps(typeof(x)))`.\n\n# Examples\n\n```julia\nimport FiniteDiff: step_size, BackwardMode\nϵ = step_size(BackwardMode(), 0.0)\n```\n\"\"\"\n@inline function step_size(::BackwardMode, x::AbstractFloat)::Real\n    return sqrt(eps(typeof(x))) * max(one(typeof(x)), abs(x))\nend\n\n\"\"\"\n    step_size(::CentralMode, x::AbstractFloat)\n\n# Description\n\nDetermine the step-size to use for central-mode finite differences.\n\n# Arguments\n\n* `::CentralMode`: An instance of the `CentralMode` type.\n* `x::AbstractFloat`: A point at which the derivative of a function will be\n    approximated. Its type must implement `eps`.\n\n# Returns\n\n* `ϵ::Real`: The step-size to use for finite differences at `x`.\n\n# References\n\nSee Section 5.7 of Numerical Recipes in C for the mathematical justification\nfor working with `cbrt(eps(typeof(x)))`.\n\n# Examples\n\n```julia\nimport FiniteDiff: step_size, CentralMode\nϵ = step_size(CentralMode(), 0.0)\n```\n\"\"\"\n@inline function step_size(::CentralMode, x::AbstractFloat)::Real\n    return cbrt(eps(typeof(x))) * max(one(typeof(x)), abs(x))\nend\n\n\"\"\"\n    step_size(::ComplexMode, x::AbstractFloat)\n\n# Description\n\nDetermine the step-size to use for complex-mode finite differences.\n\n# Arguments\n\n* `::ComplexMode`: An instance of the `ComplexMode` type.\n* `x::AbstractFloat`: A point at which the derivative of a function will be\n    approximated. Its type must implement `eps`.\n\n# Returns\n\n* `ϵ::Real`: The step-size to use for finite differences at `x`.\n\n# References\n\nSee \"The Complex-Step Derivative Approximation\" by Martins, Sturdza and Alonso\n(2003) for the mathematical justification for working with `eps(x)`.\n\n# Examples\n\n```julia\nimport FiniteDiff: step_size, ComplexMode\nϵ = step_size(ComplexMode(), 0.0)\n```\n\"\"\"\n@inline function step_size(::ComplexMode, x::AbstractFloat)::Real\n    return eps(typeof(x))\nend\n\n\"\"\"\n    step_size(::HessianMode, x::AbstractFloat)\n\n# Description\n\nDetermine the step-size to use for finite differences of hessians.\n\n# Arguments\n\n* `::HessianMode`: An instance of the `HessianMode` type.\n* `x::AbstractFloat`: A point at which the derivative of a function will be\n    approximated. Its type must implement `eps`.\n\n# Returns\n\n* `ϵ::Real`: The step-size to use for finite differences at `x`.\n\n# References\n\nSee Section 5.7 of Numerical Recipes in C for the mathematical justification\nfor working with `eps(x)^(1 // 4)`.\n\n# Examples\n\n```julia\nimport FiniteDiff: step_size, HessianMode\nϵ = step_size(HessianMode(), 0.0)\n```\n\"\"\"\n@inline function step_size(::HessianMode, x::AbstractFloat)::Real\n    return eps(typeof(x))^(1 // 4) * max(one(typeof(x)), abs(x))\nend\n", "meta": {"hexsha": "07bdd3e0b3479b1ef8c4cc36bbf9384f4d557f5a", "size": 3902, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/step_size.jl", "max_stars_repo_name": "johnmyleswhite/FiniteDiff.jl", "max_stars_repo_head_hexsha": "d9c3da50b0c214b7be008b60cb04d6701548ff92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-01-19T14:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-27T06:04:07.000Z", "max_issues_repo_path": "src/step_size.jl", "max_issues_repo_name": "johnmyleswhite/FiniteDiff.jl", "max_issues_repo_head_hexsha": "d9c3da50b0c214b7be008b60cb04d6701548ff92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-08-17T22:35:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-22T16:09:43.000Z", "max_forks_repo_path": "src/step_size.jl", "max_forks_repo_name": "johnmyleswhite/FiniteDiff.jl", "max_forks_repo_head_hexsha": "d9c3da50b0c214b7be008b60cb04d6701548ff92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-16T20:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T22:51:01.000Z", "avg_line_length": 23.6484848485, "max_line_length": 78, "alphanum_fraction": 0.7178370067, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7630873622094364}}
{"text": "\n\"\"\"\n    evalcompositelogisticprobit(x::T, a, b)::T where T <: Real\n\nevaluates the map from (0,1) to (0,1).\nreturns 1/(1 + exp(-a*(log(x/(1-x))-b)))\n\n\n    evalcompositelogisticprobit(x::T, a, b, lb, ub)::T where T <: Real\nevaluates the map from (lb, ub) to (lb, ub), by mapping (lb,ub) to (0,1), run evalcompositelogisticprobit(), then map (0,1) to (lb,ub).\n\"\"\"\nfunction evalcompositelogisticprobit(x::T, a, b)::T where T <: Real\n\n    return 1/(1 + exp(-a*(log(x/(1-x))-b)))\nend\n\nfunction evalcompositelogisticprobit(x_inp::T, a, b, lb, ub)::T where T <: Real\n\n    x = convertcompactdomain(x_inp, lb, ub, zero(T), one(T))\n    y = evalcompositelogisticprobit(x, a, b)\n    y_out = convertcompactdomain(y, zero(T), one(T), lb, ub)\n\n    return y_out\nend\n\nfunction evalinversecompositelogisticprobit(y::T, a, b)::T where T <: Real\n    return exp(b)/(exp(b) + (-1 + 1/y)^(1/a))\nend\n\nfunction evalinversecompositelogisticprobit(y_inp::T, a, b, lb, ub)::T where T <: Real\n\n    y = convertcompactdomain(y_inp, lb, ub, zero(T), one(T))\n    x = evalinversecompositelogisticprobit(y, a, b)\n    x_out = convertcompactdomain(x, zero(T), one(T), lb, ub)\n\n    return x_out\nend\n\nfunction eval1Dnumericalinverse(f::Function,\n    y::T,\n    x0::T,\n    a::T,\n    b::T,\n    max_iters::Int) where T <: Real\n\n    @assert a < b\n\n    obj_func = xx->((f(xx[1])-y)^2)::T\n\n    op = Optim.Options( iterations = max_iters,\n                         store_trace = false,\n                         show_trace = false)\n\n    results = Optim.optimize(   obj_func,\n                                [x0],\n                                Optim.NewtonTrustRegion(),\n                                op)\n\n    x_star = results.minimizer\n    x_out = clamp(x_star[1], a, b)\n\n    return x_out, results\nend\n", "meta": {"hexsha": "98f049da752dad3ec63b4777623854c58ad6cd0a", "size": 1757, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/endomorphisms/composite_sigmoid.jl", "max_stars_repo_name": "RoyCCWang/MonotoneMaps.jl", "max_stars_repo_head_hexsha": "dbb247170a0d3a7e0ba58a3cd102243c1bbc5eb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/endomorphisms/composite_sigmoid.jl", "max_issues_repo_name": "RoyCCWang/MonotoneMaps.jl", "max_issues_repo_head_hexsha": "dbb247170a0d3a7e0ba58a3cd102243c1bbc5eb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/endomorphisms/composite_sigmoid.jl", "max_forks_repo_name": "RoyCCWang/MonotoneMaps.jl", "max_forks_repo_head_hexsha": "dbb247170a0d3a7e0ba58a3cd102243c1bbc5eb1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.453125, "max_line_length": 135, "alphanum_fraction": 0.5839499146, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.763087357607911}}
{"text": "# Support Vector Machines Module\nmodule SVM\nexport WeightsLinearSVM, train_linear\nexport WeightsSVM, train\nexport cost, predict, predict_proba\n\nimport Random\nimport Statistics\n\ninclude(\"../tools.jl\")\nimport .JuTools\n\n\"\"\"\nThe weight data struct for training linear SVM\n\"\"\"\nmutable struct WeightsLinearSVM\n    C::AbstractFloat\n    w::Array{T} where T<:AbstractFloat\n    b::AbstractFloat\nend\n\n\"\"\"\nCost function for linear SVM\\\\\nIf `X_data` has shape (M,N)\\\\\n`Y_data` has shape (M,)\\\\\n`weights.w` has shape (N,)\\\\\nReturns the computed loss\n\"\"\"\nfunction cost(X_data::Array{T} where T<:Number, Y_data::Array{T} where T<:Number, weights::WeightsLinearSVM)::AbstractFloat\n    @assert ndims(Y_data) == ndims(weights.w) == 1\n    @assert size(X_data) == (size(Y_data)[1], size(weights.w)[1])\n    loss_w = 0.5 * (weights.w' * weights.w)\n    loss_inner = 1.0 .- Y_data .* vec(X_data * weights.w .+ weights.b)\n    loss_inner .= map(m->max(0.0,m), loss_inner)\n    loss = loss_w + weights.C * sum(loss_inner) / size(X_data)[1]\n    return loss\nend\n\n\"\"\"\nLearning function for linear SVM, using Gradient Descent\\\\\nIf `X_data` has shape (M,N)\\\\\n`Y_data` has shape (M,)\\\\\n`weights.w` has shape (N,)\\\\\nUpdate the weights in place\n\"\"\"\nfunction learn!(X_data::Array{T} where T<:Number, Y_data::Array{T} where T<:Number, weights::WeightsLinearSVM, momentum::WeightsLinearSVM, alpha::AbstractFloat)\n    @assert ndims(Y_data) == ndims(weights.w) == 1\n    @assert size(X_data) == (size(Y_data)[1], size(weights.w)[1])\n    # compute deciding feature\n    decide = (Y_data .* (X_data * weights.w .+ weights.b)) .< 1 # (? < 1) will be 1, otherwise 0\n    # update w\n    gradient_w = weights.w .+ (weights.C / size(X_data)[1]) .* vec(-(Y_data .* decide)' * X_data)\n    gradient_w .= gradient_w .* alpha\n    momentum.w .= gradient_w .+ (0.9 .* momentum.w)\n    weights.w .= weights.w .- momentum.w\n    # update b\n    gradient_b = (weights.C / size(X_data)[1]) * sum(-(Y_data .* decide))\n    gradient_b *= alpha\n    momentum.b = gradient_b + (0.9 * momentum.b)\n    weights.b = weights.b - momentum.b\n    return nothing\nend\n\n\"\"\"\nPrediction function for linear SVM\\\\\nIf `X_data` has shape (M,N)\\\\\n`weights.w` has shape (N,)\\\\\nReturns the actual computed values\n\"\"\"\nfunction predict_proba(X_predict::Array{T} where T<:Number, weights::WeightsLinearSVM)::Array\n    @assert 1 <= ndims(X_predict) <= 2\n    if ndims(X_predict) == 1\n        X_predict = reshape(X_predict, (1, size(X_predict)[1]))\n    end\n    @assert size(X_predict)[2] == size(weights.w)[1]\n    prediction = vec(X_predict * weights.w .+ weights.b)\n    return prediction\nend\n\n\"\"\"\nPrediction function for linear SVM\\\\\nIf `X_data` has shape (M,N)\\\\\n`weights.w` has shape (N,)\\\\\nReturns the converted predictions, in {-1, 1}\n\"\"\"\nfunction predict(X_predict::Array{T} where T<:Number, weights::WeightsLinearSVM)::Array\n    @assert 1 <= ndims(X_predict) <= 2\n    if ndims(X_predict) == 1\n        X_predict = reshape(X_predict, (1, size(X_predict)[1]))\n    end\n    @assert size(X_predict)[2] == size(weights.w)[1]\n    prediction = vec(X_predict * weights.w .+ weights.b)\n    prediction .= map(m -> m >= 0 ? 1.0 : -1.0, prediction)\n    return prediction\nend\n\n\"\"\"\nTraining function for linear SVM\\\\\nIf `X_data` has shape (M,N)\\\\\n`Y_data` has shape (M,)\\\\\n`C` is the constraint for SVM decision margin\\\\\n`max_iter` should be >= 0\n------\nReturns trained weights as `WeightsLinearSVM` object\n\n------\nSet `early_stop` to `false`, to force run maximum iteractions\\\\\nSet `random_weights` to `false` to initialize weights of 0.0\n\"\"\"\nfunction train_linear(X_data::Array{T} where T<:Number, Y_data::Array{T} where T<:Number, C::AbstractFloat;\n        learning_rate::AbstractFloat=0.1, max_iter::Integer=1000, verbose::Bool=false, random_weights::Bool=true)::WeightsLinearSVM\n    @assert ndims(X_data) == ndims(Y_data) + 1 == 2\n    @assert size(X_data)[1] == size(Y_data)[1]\n    @assert max_iter >= 0\n    X_data = Float64.(X_data)\n    Y_data = Float64.(Y_data)\n    # is it better to use zero weights than normal weights ?\n    weights = nothing\n    if random_weights\n        weights = WeightsLinearSVM(C, Random.randn(size(X_data)[2]), Random.randn())\n    else\n        weights = WeightsLinearSVM(C, zeros(size(X_data)[2]), 0.0)\n    end\n    momentum = WeightsLinearSVM(C, zeros(size(X_data)[2]), 0.0)\n    best_weights = WeightsLinearSVM(C, copy(weights.w), weights.b)\n    best_cost = nothing\n    for i in 1:max_iter\n        JuTools.shuffle_data!(X_data, Y_data)\n        learn!(X_data, Y_data, weights, momentum, learning_rate)\n        new_cost = cost(X_data, Y_data, weights)\n        if verbose\n            acc = JuTools.compute_accuracy(predict(X_data, weights), Y_data)\n            println(\"Iter: $i\")\n            println(\"Cost = $new_cost\")\n            println(\"Accuracy = $acc\")\n            println()\n        end\n        if best_cost === nothing\n            best_cost = new_cost\n        else\n            if new_cost <= best_cost\n                best_cost = min(new_cost, best_cost)\n                best_weights.w = copy(weights.w)\n                best_weights.b = weights.b\n            end\n        end\n    end\n    return best_weights\nend\n\n\n\"\"\"\nThe weight data struct for training common SVM (with kernels)\n\"\"\"\nmutable struct WeightsSVM\n    C::AbstractFloat                # constraint\n    b::AbstractFloat                # threshold\n    gamma::AbstractFloat            # parameter used for polynomial, rbf, and sigmoid kernels\n    r::AbstractFloat                # parameter used for polynomial, and sigmoid kernels\n    d::AbstractFloat                # parameter used for polynomial kernel\n    tol_alpha::AbstractFloat        # tolerance for alpha\n    tol_error::AbstractFloat        # tolerance for error\n    alpha::Array{T} where T<:Number # alpha array\n    error::Array{T} where T<:Number # array for error cache\n    kernel::String                  # kernel function name\nend\n\n\"\"\"\nKernel Function (linear)\n\"\"\"\nfunction kernel_linear(X1::Array{T} where T<:Number, X2::Array{T} where T<:Number)::Array\n    @assert ndims(X1) == ndims(X2) == 2\n    @assert size(X1)[2] == size(X2)[2]\n    result = X1 * X2'\n    return result\nend\n\"\"\"\nKernel Function (polynomial)\\\\\n`d` is `degree` parameter in training function\\\\\n`r` is `coef` parameter in training function\\\\\n`gamma` is computed from `gamma` parameter in training function\n\"\"\"\nfunction kernel_polynomial(X1::Array{T} where T<:Number, X2::Array{T} where T<:Number;\n        d::AbstractFloat=1.0, r::AbstractFloat=0.0, gamma::AbstractFloat=1.0)::Array\n    @assert ndims(X1) == ndims(X2) == 2\n    @assert size(X1)[2] == size(X2)[2]\n    result = (gamma .* (X1 * X2') .+ r) .^ d\n    return result\nend\n\"\"\"\nKernel Function (rbf)\\\\\n`gamma` is computed from `gamma` parameter in training function\n\"\"\"\nfunction kernel_rbf(X1::Array{T} where T<:Number, X2::Array{T} where T<:Number; gamma::AbstractFloat=1.0)::Array\n    @assert ndims(X1) == ndims(X2) == 2\n    @assert size(X1)[2] == size(X2)[2]\n    result = (sum(X1 .^ 2, dims=2) * ones(size(X2)[1])') .+ (ones(size(X1)[1]) * sum(X2 .^ 2, dims=2)') .- 2.0 .* (X1 * X2')\n    result .= broadcast(m->max(0.0, m), result) # ignore very small negative outputs, due to precision\n    result .= sqrt.(result)\n    result .= (-gamma) .* result\n    result .= exp.(result)\n    return result\nend\n\"\"\"\nKernel Function (sigmoid)\\\\\n`r` is `coef` parameter in training function\\\\\n`gamma` is computed from `gamma` parameter in training function\n\"\"\"\nfunction kernel_sigmoid(X1::Array{T} where T<:Number, X2::Array{T} where T<:Number; gamma::AbstractFloat=1.0, r::AbstractFloat=0.0)::Array\n    @assert ndims(X1) == ndims(X2) == 2\n    @assert size(X1)[2] == size(X2)[2]\n    result = gamma .* (X1 * X2') .+ r\n    result .= tanh.(result)\n    return result\nend\n\n\"\"\"\nCost function for SVM\\\\\nIf `X_data` has shape (M,N)\\\\\n`weights.alpha` has shape (M,)\\\\\nReturns the computed cost\\\\\n__Note__:\\\\\nCost is the opposite of objective value\n\"\"\"\nfunction cost(X_data::Array{T} where T<:Number, weights::WeightsSVM)::AbstractFloat\n    @assert ndims(X_data) == ndims(weights.alpha) + 1 == 2\n    @assert size(X_data)[1] == size(weights.alpha)[1]\n    result = nothing\n    if weights.kernel == \"linear\"\n        result = kernel_linear(X_data, X_data)\n    elseif weights.kernel == \"polynomial\"\n        result = kernel_polynomial(X_data, X_data, d=weights.d, r=weights.r, gamma=weights.gamma)\n    elseif weights.kernel == \"rbf\"\n        result = kernel_rbf(X_data, X_data, gamma=weights.gamma)\n    elseif weights.kernel == \"sigmoid\"\n        result = kernel_sigmoid(X_data, X_data, gamma=weights.gamma, r=weights.r)\n    else\n        throw(ArgumentError(\"Error: kernel function $weights.kernel is not recognized\"))\n    end\n    result = 0.5 * (weights.alpha' * result * weights.alpha) - sum(weights.alpha)\n    return result\nend\n\n\"\"\"\nStep function for learning SVM\\\\\nIf `X_data` has shape (M,N)\\\\\n`Y_data` has shape (M,)\\\\\n`weights.alpha` has shape (M,)\\\\\n`weights.error` has shape (M,)\\\\\n`id1` and `id2` are index in `weights.alpha`\\\\\nTries to update `weights.alpha` in place\\\\\nReturns `1` if step further, else `0`\n\"\"\"\nfunction learn_step!(X_data::Array{T} where T<:Number, Y_data::Array{T} where T<:Number,\n        weights::WeightsSVM, id1::Integer, id2::Integer)::Integer\n    @assert ndims(X_data) == ndims(Y_data) + 1 == 2\n    @assert size(X_data)[1] == size(Y_data)[1]\n    @assert size(X_data)[1] == size(weights.alpha)[1]\n    @assert size(weights.error) == size(weights.alpha)\n    @assert id1 >= 1\n    @assert id2 >= 1\n    # if choosing same alpha, skip\n    if id1 == id2\n        return 0\n    end\n    # prepare data\n    alpha1 = weights.alpha[id1]\n    alpha2 = weights.alpha[id2]\n    Y1 = Y_data[id1]\n    Y2 = Y_data[id2]\n    error1 = weights.error[id1]\n    error2 = weights.error[id2]\n    # compute L & H\n    L = nothing\n    H = nothing\n    if Y1 != Y2\n        L = max(0.0, alpha2 - alpha1)\n        H = min(weights.C, weights.C + alpha2 - alpha1)\n    else\n        L = max(0.0, alpha1 + alpha2 - weights.C)\n        H = min(weights.C, alpha1 + alpha2)\n    end\n    if L == H\n        return 0\n    end\n    # compute kernel results and 2nd derivative eta\n    k11 = nothing\n    k12 = nothing\n    k22 = nothing\n    n_features = size(X_data)[2]\n    X_id1 = reshape(X_data[id1, :], (1, n_features))\n    X_id2 = reshape(X_data[id2, :], (1, n_features))\n    if weights.kernel == \"linear\"\n        k11 = kernel_linear(X_id1, X_id1)[1]\n        k12 = kernel_linear(X_id1, X_id2)[1]\n        k22 = kernel_linear(X_id2, X_id2)[1]\n    elseif weights.kernel == \"polynomial\"\n        k11 = kernel_polynomial(X_id1, X_id1, d=weights.d, r=weights.r, gamma=weights.gamma)[1]\n        k12 = kernel_polynomial(X_id1, X_id2, d=weights.d, r=weights.r, gamma=weights.gamma)[1]\n        k22 = kernel_polynomial(X_id2, X_id2, d=weights.d, r=weights.r, gamma=weights.gamma)[1]\n    elseif weights.kernel == \"rbf\"\n        k11 = kernel_rbf(X_id1, X_id1, gamma=weights.gamma)[1]\n        k12 = kernel_rbf(X_id1, X_id2, gamma=weights.gamma)[1]\n        k22 = kernel_rbf(X_id2, X_id2, gamma=weights.gamma)[1]\n    elseif weights.kernel == \"sigmoid\"\n        k11 = kernel_sigmoid(X_id1, X_id1, gamma=weights.gamma, r=weights.r)[1]\n        k12 = kernel_sigmoid(X_id1, X_id2, gamma=weights.gamma, r=weights.r)[1]\n        k22 = kernel_sigmoid(X_id2, X_id2, gamma=weights.gamma, r=weights.r)[1]\n    else\n        throw(ArgumentError(\"Error: kernel function $weights.kernel is not recognized\"))\n    end\n    eta = 2.0 * k12 - k11 - k22\n    # compute new alpha2 (a2)\n    a2 = nothing\n    if eta < 0.0\n        a2 = alpha2 - Y2 * (error1 - error2) / eta\n        a2 = min(a2, H)\n        a2 = max(a2, L)\n    else\n        c1 = eta / 2.0\n        c2 = Y2 * (error1 - error2) - eta * alpha2\n        Lobj = c1 * L * L + c2 * L\n        Hobj = c1 * H * H + c2 * H\n        if Lobj > (Hobj + weights.tol_alpha)\n            a2 = L\n        elseif Lobj < (Hobj - weights.tol_alpha)\n            a2 = H\n        else\n            a2 = alpha2\n        end\n    end\n    # push to 0 or C\n    if a2 < 1e-8\n        a2 = 0.0\n    elseif a2 > (weights.C - 1e-8)\n        a2 = weights.C\n    end\n    # skip if cannot be optimized\n    if abs(a2 - alpha2) < weights.tol_alpha * (a2 + alpha2 + weights.tol_alpha)\n        return 0\n    end\n    # compute new alpha1 (a1)\n    a1 = alpha1 + (Y1 * Y2) * (alpha2 - a2)\n    if a1 < 0.0\n        a2 += (Y1 * Y2) * a1\n        a1 = 0.0\n    elseif a1 > weights.C\n        a2 += (Y1 * Y2) * (a1 - weights.C)\n        a1 = weights.C\n    end\n    # update threshold\n    b1 = error1 + Y1 * (a1 - alpha1) * k11 + Y2 * (a2 - alpha2) * k12 + weights.b\n    b2 = error2 + Y1 * (a1 - alpha1) * k12 + Y2 * (a2 - alpha2) * k22 + weights.b\n    b_new = nothing\n    if 0 < a1 < weights.C\n        b_new = b1\n    elseif 0 < a2 < weights.C\n        b_new = b2\n    else\n        b_new = (b1 + b2) * 0.5\n    end\n    # update error cache\n    non_optimized_ids = [i for i in 1:size(X_data)[1] if (0 < weights.alpha[i] < weights.C)]\n    kerr1 = nothing\n    kerr2 = nothing\n    if weights.kernel == \"linear\"\n        kerr1 = vec(kernel_linear(X_id1, X_data[non_optimized_ids, :]))\n        kerr2 = vec(kernel_linear(X_id2, X_data[non_optimized_ids, :]))\n    elseif weights.kernel == \"polynomial\"\n        kerr1 = vec(kernel_polynomial(X_id1, X_data[non_optimized_ids, :], d=weights.d, r=weights.r, gamma=weights.gamma))\n        kerr2 = vec(kernel_polynomial(X_id2, X_data[non_optimized_ids, :], d=weights.d, r=weights.r, gamma=weights.gamma))\n    elseif weights.kernel == \"rbf\"\n        kerr1 = vec(kernel_rbf(X_id1, X_data[non_optimized_ids, :], gamma=weights.gamma))\n        kerr2 = vec(kernel_rbf(X_id2, X_data[non_optimized_ids, :], gamma=weights.gamma))\n    elseif weights.kernel == \"sigmoid\"\n        kerr1 = vec(kernel_sigmoid(X_id1, X_data[non_optimized_ids, :], gamma=weights.gamma, r=weights.r))\n        kerr2 = vec(kernel_sigmoid(X_id2, X_data[non_optimized_ids, :], gamma=weights.gamma, r=weights.r))\n    end\n    weights.error[non_optimized_ids] .= weights.error[non_optimized_ids] .+\n        ((Y1*(a1-alpha1)) .* kerr1) .+ ((Y2*(a2-alpha2)) .* kerr2) .- (b_new - weights.b)\n    weights.error[id1] = 0.0\n    weights.error[id2] = 0.0\n    # update alpha and b\n    weights.b = b_new\n    weights.alpha[id1] = a1\n    weights.alpha[id2] = a2\n    return 1\nend\n\n\"\"\"\nLearning function for SVM, using SMO\\\\\nIf `X_data` has shape (M,N)\\\\\n`Y_data` has shape (M,)\\\\\n`weights.alpha` has shape (M,)\\\\\nTries to update `weights.alpha` with step function\\\\\nReturns `1` if step further, else `0`\n\"\"\"\nfunction learn!(X_data::Array{T} where T<:Number, Y_data::Array{T} where T<:Number,\n        weights::WeightsSVM, id::Integer; verbose::Bool=false)::Integer\n    @assert ndims(X_data) == ndims(Y_data) + 1 == 2\n    @assert size(X_data)[1] == size(Y_data)[1]\n    @assert size(X_data)[1] == size(weights.alpha)[1]\n    @assert size(weights.error) == size(weights.alpha)\n    @assert id >= 1\n    Y = Y_data[id]\n    alpha = weights.alpha[id]\n    error = weights.error[id]\n    r = error * Y\n    if ((r < -weights.tol_error) && (alpha < weights.C)) || ((r > weights.tol_error) && (alpha > 0))\n        alpha_target = [i for (i, m) in enumerate(weights.alpha) if (0.0 < m < weights.C)]\n        # try argmax E1 - E2\n        if verbose\n            println(\"Trying argmax(abs(E1 - E2))\")\n        end\n        new_id = 0\n        tmax = 0\n        for i in alpha_target\n            tmp = abs(error - weights.error[i])\n            if(tmp > tmax)\n                tmax = tmp\n                new_id = i\n            end\n        end\n        if new_id >= 1\n            step = learn_step!(X_data, Y_data, weights, new_id, id)\n            if step > 0\n                return step\n            end\n        end\n        # loop non-bound alphas, randomly\n        if verbose\n            println(\"Trying random non-bound alphas\")\n        end\n        for new_id in alpha_target[Random.randperm(length(alpha_target))]\n            step = learn_step!(X_data, Y_data, weights, new_id, id)\n            if step > 0\n                return step\n            end\n        end\n        # else loop all alphas, randomly\n        if verbose\n            println(\"Trying random remaining alphas\")\n        end\n        for new_id in Random.randperm(length(weights.alpha))\n            if new_id in alpha_target\n                continue # skip the alpha ids that already looked at\n            end\n            step = learn_step!(X_data, Y_data, weights, new_id, id)\n            if step > 0\n                return step\n            end\n        end\n    end\n    return 0\nend\n\n\"\"\"\nPrediction function for SVM\\\\\nIf `X_data` has shape (M,N)\\\\\n`Y_data` has shape (M,)\\\\\n`weights.alpha` has shape (M,)\\\\\n`X_predict` has shape (k,N)\\\\\nReturns the actual predictions\n\"\"\"\nfunction predict_proba(X_predict::Array{T} where T<:Number, X_data::Array{T} where T<:Number,\n        Y_data::Array{T} where T<:Number, weights::WeightsSVM)::Array\n    if ndims(X_predict) == 1\n        X_predict = reshape(X_predict, (1, size(X_predict)[1]))\n    end\n    @assert ndims(X_predict) == ndims(X_data) == ndims(Y_data) + 1 == 2\n    @assert size(X_predict)[2] == size(X_data)[2]\n    result = nothing\n    if weights.kernel == \"linear\"\n        result = kernel_linear(X_data, X_predict)\n    elseif weights.kernel == \"polynomial\"\n        result = kernel_polynomial(X_data, X_predict, d=weights.d, r=weights.r, gamma=weights.gamma)\n    elseif weights.kernel == \"rbf\"\n        result = kernel_rbf(X_data, X_predict, gamma=weights.gamma)\n    elseif weights.kernel == \"sigmoid\"\n        result = kernel_sigmoid(X_data, X_predict, gamma=weights.gamma, r=weights.r)\n    else\n        throw(ArgumentError(\"Error: kernel function $weights.kernel is not recognized\"))\n    end\n    prediction = vec((weights.alpha .* Y_data)' * result)\n    return prediction\nend\n\n\"\"\"\nPrediction function for SVM\\\\\nIf `X_data` has shape (M,N)\\\\\n`Y_data` has shape (M,)\\\\\n`weights.alpha` has shape (M,)\\\\\n`X_predict` has shape (k,N)\\\\\nReturns the converted predictions, in {-1, 1}\n\"\"\"\nfunction predict(X_predict::Array{T} where T<:Number, X_data::Array{T} where T<:Number,\n        Y_data::Array{T} where T<:Number, weights::WeightsSVM)::Array\n    if ndims(X_predict) == 1\n        X_predict = reshape(X_predict, (1, size(X_predict)[1]))\n    end\n    @assert ndims(X_predict) == ndims(X_data) == ndims(Y_data) + 1 == 2\n    @assert size(X_predict)[2] == size(X_data)[2]\n    result = nothing\n    if weights.kernel == \"linear\"\n        result = kernel_linear(X_data, X_predict)\n    elseif weights.kernel == \"polynomial\"\n        result = kernel_polynomial(X_data, X_predict, d=weights.d, r=weights.r, gamma=weights.gamma)\n    elseif weights.kernel == \"rbf\"\n        result = kernel_rbf(X_data, X_predict, gamma=weights.gamma)\n    elseif weights.kernel == \"sigmoid\"\n        result = kernel_sigmoid(X_data, X_predict, gamma=weights.gamma, r=weights.r)\n    else\n        throw(ArgumentError(\"Error: kernel function $weights.kernel is not recognized\"))\n    end\n    prediction = vec((weights.alpha .* Y_data)' * result)\n    prediction .= map(m -> m >= 0 ? 1.0 : -1.0, prediction)\n    return prediction\nend\n\n\"\"\"\nTraining function for linear SVM\\\\\nIf `X_data` has shape (M,N)\\\\\n`Y_data` has shape (M,)\\\\\n`C` is the constraint for SVM decision margin\\\\\n`tol_alpha` sets tolerance for alpha array\\\\\n`tol_error` sets tolerance for error cache\\\\\n`kernel` selects a kernel function, possible values are:\n* \"rbf\"\n* \"linear\"\n* \"sigmoid\"\n* \"polynomial\"\n\n`gamma` selects a way to compute gamma, possible values are:\n* \"scale\"\n* \"auto\"\n\n`degree` defines the degree in `polynomial` kernel function\\\\\n`coef` defines the `r` in `polynomial` and `sigmoid` kernel functions\n------\nReturns trained alphas as `WeightsSVM` object\n\"\"\"\nfunction train(X_data::Array{T} where T<:Number, Y_data::Array{T} where T<:Number, C::AbstractFloat;\n        tol_alpha::AbstractFloat=0.01, tol_error::AbstractFloat=0.01, kernel::String=\"rbf\", gamma::String=\"scale\",\n        degree::AbstractFloat=1.0, coef::AbstractFloat=0.0, verbose::Bool=false)::WeightsSVM\n    @assert ndims(X_data) == ndims(Y_data) + 1 == 2\n    @assert size(X_data)[1] == size(Y_data)[1]\n    X_data = Float64.(X_data)\n    Y_data = Float64.(Y_data)\n    # gamma is computed the same way sklearn does\n    gamma_num = nothing\n    if gamma == \"scale\"\n        gamma_num = 1.0 / (size(X_data)[2] * Statistics.var(X_data))\n    elseif gamma == \"auto\"\n        gamma_num = 1.0 / size(X_data)[2]\n    else\n        throw(ArgumentError(\"Error: gamma $gamma is not recognized, possible values are 'scale' and 'auto'\"))\n    end\n    weights = WeightsSVM(C, 0.0, gamma_num, coef, degree, tol_alpha, tol_error, Float64.(zeros(size(X_data)[1])), -copy(Y_data), kernel)\n    num_changed = 0\n    examine_all = true\n    total_steps = 0\n    while (num_changed > 0) || examine_all\n        num_changed = 0\n        if examine_all\n            if verbose\n                println(\"Scanning all training data\")\n            end\n            for i in 1:size(X_data)[1]\n                step = learn!(X_data, Y_data, weights, i, verbose=verbose)\n                num_changed += step\n                if step > 0 && verbose\n                    obj = -cost(X_data, weights)\n                    println(\"1 step further, objective = $obj\")\n                end\n            end\n        else\n            if verbose\n                println(\"Scanning data whose alpha is not at limit\")\n            end\n            alpha_target = [i for (i, m) in enumerate(weights.alpha) if (m != 0.0 && m != weights.C)]\n            for i in alpha_target\n                step = learn!(X_data, Y_data, weights, i, verbose=verbose)\n                num_changed += step\n                if step > 0 && verbose\n                    obj = -cost(X_data, weights)\n                    println(\"1 step further, objective = $obj\")\n                end\n            end\n        end\n        if examine_all\n            examine_all = false\n        elseif num_changed <= 0\n            examine_all = true\n        end\n        total_steps += num_changed\n    end\n    if verbose\n        println(\"Training Complete\\nTotal steps: $total_steps\")\n    end\n    return weights\nend\n\nend", "meta": {"hexsha": "f0cb2c3af00dc86e8368d63c59efaf47b17e62ce", "size": 22033, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Support_Vector_Machines/script.jl", "max_stars_repo_name": "teamclouday/JuliaLearn", "max_stars_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Support_Vector_Machines/script.jl", "max_issues_repo_name": "teamclouday/JuliaLearn", "max_issues_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Support_Vector_Machines/script.jl", "max_forks_repo_name": "teamclouday/JuliaLearn", "max_forks_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5389718076, "max_line_length": 160, "alphanum_fraction": 0.6191621658, "num_tokens": 6455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526934, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7630873543276734}}
{"text": "using Primes\n\nfunction ulamspiral(ord::Int)\n    # Possible directions\n    dirs = [[0, 1], [-1, 0], [0, -1], [1, 0]]\n    # fdir = [\"→\", \"↑\", \"←\", \"↓\"] # for debug pourpose\n    cur = maxsteps = 1  # starting direction & starting max steps\n    steps = n = 0       # starting steps     & starting number in cell\n    pos = [ord ÷ 2 + 1, isodd(ord) ? ord ÷ 2 + 1 : ord ÷ 2] # starting position\n    M = Matrix{Bool}(ord, ord) # result matrix\n    while n < ord ^ 2  # main loop (stop when the matrix is filled)\n        n += 1\n        M[pos[1], pos[2]] = isprime(n)\n        steps += 1\n        # Debug print\n        # @printf(\"M[%i, %i] = %5s (%2i), step %i/%i, nxt %s\\n\", pos[1], pos[2], isprime(n), n, steps, maxsteps, fdir[cur])\n        pos  .+= dirs[cur] # increment position\n        if steps == maxsteps # if reached max number of steps in that direction...\n            steps = 0        # ...reset steps\n            if iseven(cur) maxsteps += 1 end # if the current direction is even increase the number of steps\n            cur  += 1        # change direction\n            if cur > 4 cur -= 4 end # correct overflow\n        end\n    end\n    return M\nend\n\nmprint(m::Matrix) = for i in 1:size(m, 1) println(join(el ? \" ∙ \" : \"   \" for el in m[i, :]), '\\n') end\n\nM = ulamspiral(9)\nmprint(M)\n", "meta": {"hexsha": "0785612d83fa4adcd7d6b863fe72e5c42026b77b", "size": 1282, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/ulam-spiral--for-primes-.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/ulam-spiral--for-primes-.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/ulam-spiral--for-primes-.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0625, "max_line_length": 123, "alphanum_fraction": 0.5343213729, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558356, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7630873525774473}}
{"text": "##### ----- Power Law ----- #####\n# Calculate probability density for a residence time τ given α of power law, \n# minimum and maximum residence times τ₋ and τ₊\nfunction E_powerLaw(τ, (q, α, τ₋, τ₊, k)) # Note - destructured arguments so that all pdfs have τ as first argument and p as second\n    if(τ < τ₋)\n        0\n    elseif(τ > τ₊)\n        0\n    else\n        ((τ^(-α) - τ₊^(-α))*(-α+1.0)/(τ₊^(-α+1.0)-τ₋^(-α+1.0)-τ₊^(-α)*(τ₊ - τ₋)*(1.0-α)))\n    end\n    # else\n    #     (α-1)*τ₋^(α-1)*τ^(-α)\n    # end\nend\n\n# Calculate rate of hyporheic exchange [T^-1] given a ratio of hyporheic volume to channel volume (V_frac) \n# and parameters describing the pdf of the residence time distribution \nfunction qCalc_powerLaw(α, τ₋, τ₊, V_frac)\n    V_frac/quadgk(τ -> (τ₊^(-α+1) - τ^(-α+1)- (τ₊^(-α)*(τ₊-τ)*(-α+1)))/(τ₊^(-α+1) - τ₋^(-α+1)- (τ₊^(-α)*(τ₊-τ₋)*(-α+1))), τ₋, τ₊)[1]\n    # V_frac/quadgk(τ -> (-τ^(-α+1))/(- τ₋^(-α+1)), τ₋, Inf)[1]\nend\n\n##### ----- Exponential ----- #####\n\n\n\n", "meta": {"hexsha": "3d9c5979f3d0bee5908adda6a99c3a24554e4855", "size": 975, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/residenceTimeDistributions.jl", "max_stars_repo_name": "elizabethjmohr/hyporheic-biogeochemistry", "max_stars_repo_head_hexsha": "b7daee2f127ef63ba5823b96d2817903c7bd630e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/residenceTimeDistributions.jl", "max_issues_repo_name": "elizabethjmohr/hyporheic-biogeochemistry", "max_issues_repo_head_hexsha": "b7daee2f127ef63ba5823b96d2817903c7bd630e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/residenceTimeDistributions.jl", "max_forks_repo_name": "elizabethjmohr/hyporheic-biogeochemistry", "max_forks_repo_head_hexsha": "b7daee2f127ef63ba5823b96d2817903c7bd630e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8214285714, "max_line_length": 132, "alphanum_fraction": 0.5230769231, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813463747181, "lm_q2_score": 0.798186784940666, "lm_q1q2_score": 0.7630516773260855}}
{"text": "module CYCLOPS_v6_2a_CircularStats_U\n\nexport Circular_Mean\nexport Fischer_Circular_CorrelationMeasures\nexport Jammalamadka_Circular_CorrelationMeasures\nexport Circular_Error\nexport Circular_Error_List\n\nusing MultivariateStats\nusing StatsBase\n\n############################################################\nfunction Circular_Mean(phases::Array{Float64,1})\n  sinterm=sum(sin.(phases))\n  costerm=sum(cos.(phases))\n  atan2(sinterm,costerm)\nend \n\n\n############################################################\nfunction Fischer_Circular_Correlations(rphases,sphases)\n\tn1=length(rphases)\n\tn2=length(sphases)\n\n\tnum=n1\n\n\trphases=mod.(rphases+2*pi,2*pi)\n\tsphases=mod.(sphases+2*pi,2*pi)\n\n\tnumtot=0.\n\td1tot=0.\n\td2tot=0.\n\tfor i in 1:num\n\t\tfor j in (i+1):num\n\t\t\tnumeratorterm=sin(sphases[i]-sphases[j])*sin(rphases[i]-rphases[j])\n\t\t\tdenomterm1=(sin(sphases[i]-sphases[j]))^2\n\t\t\tdenomterm2=(sin(rphases[i]-rphases[j]))^2\n\t\t\tnumtot=numtot+numeratorterm\n\t\t\td1tot=d1tot+denomterm1\n\t\t\td2tot=d2tot+denomterm2\n\t\tend\n\tend\n\tfischercor=numtot/(sqrt(d1tot)*sqrt(d2tot))\n\tfischercor\nend\n############################################################\nfunction Jammalamadka_Circular_Correlations(rphases,sphases)\n\tnumtot=0.\n\td1tot=0.\n\td2tot=0.\n\t\n\trbar=mod.(2*pi+Circular_Mean(rphases),2*pi)\n\tsbar=mod.(2*pi+Circular_Mean(sphases),2*pi)\n\n\tnumtot=sum(sin.(rphases-rbar) .* sin.(sphases-sbar))\n\td1tot=sqrt(sum( sin.(rphases-rbar) .^ 2))\n\td2tot=sqrt(sum( sin.(sphases-sbar) .^ 2))\n\tJammalamadka=numtot/(d1tot*d2tot)\n\tJammalamadka\nend\n\n############################################################\nfunction Circular_Rank_Phases(rphases)\n\tnumber=length(rphases)\n\trphases=mod.(rphases+2*pi,2*pi)\n\trranks=tiedrank(rphases)\n\trrankphases=rranks*2*pi/number\n\trrankphases\nend\n\n############################################################\nfunction Jammalamadka_Rank_Circular_Correlations(rphases,sphases)\n\n\trphases=Circular_Rank_Phases(rphases)\n\tsphases=Circular_Rank_Phases(sphases)\n\n\tr_minus_s_bar=mod(atan2(sum(sin.(rphases-sphases)),sum(cos.(rphases-sphases))),2*pi)\n\tr_plus_s_bar=mod(atan2(sum(sin.(rphases+sphases)),sum(cos.(rphases+sphases))),2*pi)\n\n\tNtot=length(rphases)\n\n\tterm1=cos.(rphases-sphases-r_minus_s_bar)\n\tterm2=cos.(rphases+sphases-r_plus_s_bar)\n\t\n\tJammalamadka=1/Ntot*(sum(term1))-1/Ntot*(sum(term2))\n\tJammalamadka\nend\n############################################################\n##########################################################\n\nfunction FindComponentAngles(angle_sum,angle_diff)\n    rang=(angle_sum + angle_diff)/2\n    sang=(angle_sum - angle_diff)/2\n\t[rang,sang]    \nend\n##########################################################\nfunction Jammalamadka_Uniform_Circular_Correlations(rphases,sphases)\n# This is a modification of he Jammalamadka Circular Correlation\n# Described in Topics in Circular Statistics\n# It is required beacuse the circular average is not well defined with circular uniform data\n# This measure should only be used when 1 or both of the data sets being compared are uniform\n\n\trphases=mod.(rphases,2*pi)\n\tsphases=mod.(sphases,2*pi)\n\n\tr_minus_s_bar=mod(atan2(sum(sin.(rphases-sphases)),sum(cos.(rphases-sphases))),2*pi)\n\tr_plus_s_bar=mod(atan2(sum(sin.(rphases+sphases)),sum(cos.(rphases+sphases))),2*pi)\n\n\tbars=FindComponentAngles(r_plus_s_bar,r_minus_s_bar)\n\trbar=bars[1]\n\tsbar=bars[2]\n\n\tnumtot=sum(sin.(rphases-rbar) .* sin.(sphases-sbar))\n\td1tot=sqrt(sum( sin.(rphases-rbar) .^ 2))\n\td2tot=sqrt(sum( sin.(sphases-sbar) .^ 2))\n\n\tJammalamadka=numtot/(d1tot*d2tot)\n\tJammalamadka\nend\n\n\n\n############################################################\n\nfunction Fischer_Circular_CorrelationMeasures(rphases,sphases)\n\t\n\trrankphases=Circular_Rank_Phases(rphases)\n\tsrankphases=Circular_Rank_Phases(sphases)\n\n\tF =Fischer_Circular_Correlations(rphases,sphases)\n\n\tFR =Fischer_Circular_Correlations(rrankphases,srankphases)\n\n\t[F,FR]\nend\n\n############################################################\n\nfunction Jammalamadka_Circular_CorrelationMeasures(rphases,sphases)\n\t\n\tJ =Jammalamadka_Circular_Correlations(rphases,sphases)\n\n\tJU =Jammalamadka_Uniform_Circular_Correlations(rphases,sphases)\n\n\tJR =Jammalamadka_Rank_Circular_Correlations(rphases,sphases)\n\n\t[J, JU, JR]\nend\n############################################################\n\n\nfunction Circular_Error(truth,estimate)\n\ttruth=mod(2*pi+truth,2*pi)\n\testimate=mod(2*pi+estimate,2*pi)\n\n\tdiff1=mod((truth-estimate),2*pi)\n\tdiff2=diff1-(2*pi)\n\n\tif (abs(diff1)<=abs(diff2)) \n\t\tdiff=diff1\n\tend\n\t\n\tif (abs(diff2)<abs(diff1))\n\t\tdiff=diff2\n\tend\n\t\t\n\te=diff\n\te\nend\n############################################################\n\nfunction Circular_Error_List(true_list,estimate_list)\n\tn1=length(true_list)\n\tn2=length(estimate_list)\n\tif (n1 != n2) print(\"Error Warning\") end\n\n\terror_list=zeros(n1)\n\tfor count in 1:n1\n\t\terror_list[count]=Circular_Error(true_list[count],estimate_list[count])\n\tend\n\terror_list\nend\n\n############################################################\nend\n", "meta": {"hexsha": "9a446d1778bc6a295678c672b72485cd989116ea", "size": 4912, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PNAS_CYCLOPS_PROGRAM_SCRIPTS_REVISION_UPLOAD/CYCLOPS_v6_2a_CircularStats_U.jl", "max_stars_repo_name": "AdithyaVenkateshMohan/CYCLOPS", "max_stars_repo_head_hexsha": "0e3dabe6fe0890c6e591334ccdcd5c4bfb54252e", "max_stars_repo_licenses": ["W3C"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-05-17T08:35:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-12T12:19:31.000Z", "max_issues_repo_path": "PNAS_CYCLOPS_PROGRAM_SCRIPTS_REVISION_UPLOAD/CYCLOPS_v6_2a_CircularStats_U.jl", "max_issues_repo_name": "AdithyaVenkateshMohan/CYCLOPS", "max_issues_repo_head_hexsha": "0e3dabe6fe0890c6e591334ccdcd5c4bfb54252e", "max_issues_repo_licenses": ["W3C"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-07-10T05:37:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-11T20:18:01.000Z", "max_forks_repo_path": "PNAS_CYCLOPS_PROGRAM_SCRIPTS_REVISION_UPLOAD/CYCLOPS_v6_2a_CircularStats_U.jl", "max_forks_repo_name": "AdithyaVenkateshMohan/CYCLOPS", "max_forks_repo_head_hexsha": "0e3dabe6fe0890c6e591334ccdcd5c4bfb54252e", "max_forks_repo_licenses": ["W3C"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2017-04-26T12:10:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T16:28:55.000Z", "avg_line_length": 26.4086021505, "max_line_length": 93, "alphanum_fraction": 0.6490228013, "num_tokens": 1456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7630516760324128}}
{"text": "\n\"\"\"\n    gen_qary!(matrix::Matrix{T},k::Int,q::Int) where {T}\n\n...Maybe this should not try to operate in place...\n\"\"\"\nfunction gen_qary!(matrix::Matrix{T},k::Int,q) where {T}\n    d,n = size(matrix)\n    d==n || error(\"n!=d\")\n\n    matrix[1:d-k,1:d-k] = Matrix{T}(I,d-k,d-k)\n    matrix[d-k+1:d,1:d-k] = rand(T(0):q-1,k,d-k)\n    matrix[1:d-k,d-k+1:d] = zeros(T,k,d-k)\n    matrix[d-k+1:d,d-k+1:d] = q*Matrix{T}(I,k,k)\nend\n\n\"\"\"\n    b= gen_qary_b(T, d::Int,k::Int,b::Int)\n\nGenerate a q-ary lattice given an element type `T`, dimension `d`, parameter\n`k`, and bit-depth `b`. Specifically, find a `d` by `d` matrix which has the\nblock structure `[I zeros(T,k,d-k); H q*I]]`, where the `k` by `d-k` matrix\nH is sampled from `0:q-1` and q is sampled uniformly from `1:big(2)^b-1`\n\nThese bases correspond to the SIS/LWE q-ary lattices; see D. Micciancio and\nO. Regev. Post-Quantum Cryptography. Chapter of Lattice-based Cryptography,\n147-191 (2009) and latticegen in https://github.com/fplll/fplll\n\n# Examples\n```\njulia> b=gen_qary_b(Int64,2,1,6)\n2×2 Matrix{Int64}:\n 1   0\n 7  32\n\n```\n\"\"\"\nfunction gen_qary_b(T, d::Int,k::Int,b::Int)\n    if T!=BigInt && big(2)^b-1>typemax(T)\n        error(\"Type $(T) can only handle b=$(log2(typemax(T)+1)) \"*\n              \"bits, and you're asking for $b. Try again with \"*\n              \"a different type or smaller bit depth b.\")\n    end\n    q = T(rand(1:big(2)^b-1))\n    matrix = Matrix{T}(undef,d,d)\n    gen_qary!(matrix,k,q)\n    return matrix\nend\n", "meta": {"hexsha": "faada619945e827171a96585c2a6a0bd451276a8", "size": 1476, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/latticegen.jl", "max_stars_repo_name": "GiggleLiu/LLLplus.jl", "max_stars_repo_head_hexsha": "01fbfa2ec47cbee224cf6827e90a1c2f208ba9ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 51, "max_stars_repo_stars_event_min_datetime": "2015-04-18T03:08:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T00:41:23.000Z", "max_issues_repo_path": "src/latticegen.jl", "max_issues_repo_name": "GiggleLiu/LLLplus.jl", "max_issues_repo_head_hexsha": "01fbfa2ec47cbee224cf6827e90a1c2f208ba9ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2015-06-24T00:47:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T08:55:28.000Z", "max_forks_repo_path": "src/latticegen.jl", "max_forks_repo_name": "GiggleLiu/LLLplus.jl", "max_forks_repo_head_hexsha": "01fbfa2ec47cbee224cf6827e90a1c2f208ba9ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-04-29T18:00:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T00:42:59.000Z", "avg_line_length": 30.1224489796, "max_line_length": 76, "alphanum_fraction": 0.6131436314, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8499711794579722, "lm_q1q2_score": 0.76301512389998}}
{"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ f1d0ed8f-bfd3-4210-84fd-f189bba6ebf9\nbegin\n\tusing PlutoUI\n\tPlutoUI.TableOfContents(title = \"Contents\")\nend\n\n# ╔═╡ 08eadc12-f8e9-11eb-1094-b7adc6936aa1\nmd\"\"\"\n# Permutations\n\"\"\"\n\n# ╔═╡ c4d2ff29-2579-4079-a6cb-29015ef5ecd2\nmd\"\"\"\n## Objectives\n- _**Create a custom type**_ to represent a permutation\n- _**Utilise multiple dispatch to create new methods for inbuilt functions**_ with `Permutation` objects as arguments\n- Generate the elements of groups from generators in `Permutation` form\n\"\"\"\n\n# ╔═╡ db919e43-6dc8-4e53-8081-d9312446117a\nmd\"\"\"\n## What is multiple dispatch?\nMultiple dispatch is a feature central to the design of Julia with incredibly powerful consequences. In a most basic sense, it allows for the same function name to be used for multiple different operations, such as `-` being used for unary minus (``x \\to -x``) as well as for subtraction. More generally, if the types of the inputs are specified differently for different declarations of the function, the function can act differently depending on the inputs that it gets. An example of this inbuilt into Julia is `a * b`, which multiplies `a` and `b` if they are numbers, and concatenates `a` and `b` if they are strings:\n\"\"\"\n\n# ╔═╡ 524dee4b-6687-44de-af79-b99d3724f9ac\n3 * 4\n\n# ╔═╡ a16202d3-406a-4b43-807e-b60c673d4132\n\"3\" * \"4\"\n\n# ╔═╡ 41fc4769-5b67-4503-b1d1-2854a0d9c3a2\nmd\"\"\"\nThese, or similar examples, are duplicated notation common to most programming languages, but what Julia allows that others don't is for your own custom functions to utilise multiple dispatch as well. For example, say that I want to check if an input is four or not, but I don't mind if the input is a number or a string. To do this, I follow the argument with double colons and the type to determine when this method will run (here `Number` is an abstract type, which cannot itself be the type of an object, but encompasses all numeric types into one keyword). Note that such notation of arguments can still be used for functions with only a single methods, where it can be helpful for debugging purposes.\n\"\"\"\n\n# ╔═╡ acf690f4-b65b-4576-9145-1e894d5342f2\nisfour(x::String) = (lowercase(x) ∈ [\"4\", \"four\"])\n\n# ╔═╡ 9f193c51-b6ea-477f-ab0e-1bc5a4be4b86\nmd\"\"\"\n`isfour` is now defined for a `Number` and a `String` input, but not currently for anything else. If I decide that nothing else can be considered as four, then I can create a third method using the keyword `Any` (the abstract type representing all possible types) which will deal with everything else:\n\"\"\"\n\n# ╔═╡ 29b729bb-cd1a-4ee1-ae2e-26b55ce744a4\nisfour(x::Any) = false\n\n# ╔═╡ 740f8275-ee0c-4aa2-b0c1-76d46fad3ecd\nmd\"\"\"\nOf course, an input like `4` is also of type `Any`, but Julia's type system recognises that `Number` is more restrictive and so is of higher precedence, hence any `Number` input to `isfour` triggers the specialised method for that type.\n\nMore of the power of multiple dispatch is illustrated later in this case study.\n\"\"\"\n\n# ╔═╡ 73d93917-b72e-468b-970c-f34ec6d51de4\nmd\"\"\"\n## Creating the `Permutation` type\n\n### Declaring `Permutation` as a new type\nI begin by declaring a new type with the keyword `struct`. The most basic syntax to do this is:\n```julia\nstruct Permutation\n    image::Vector{Int64}\nend\n```\n\nalthough I will want more functionality than this. The new type has a single field `image` which is a vector of integers, representing the images of ``1, 2, \\dots n`` under the permutation (where ``n`` is the maximum integer permuted). For example, the permutation ``(123)(45)`` has image ``(2, 3, 1, 5, 4)^T``, and can be created as an object by the syntax:\n```julia\nσ = Permutation([2,3,1,5,4])\n```\n\nIts field will also be accessible through dot notation by:\n```julia\nσ.image\n```\n\"\"\"\n\n# ╔═╡ c18ae801-b186-44cf-9e42-83188c4781aa\nmd\"\"\"\nThere are currently some issues with the new type, primarily that at the moment any vector of integers could be the image of a `Permutation`, so I need to be able to check that an image is valid, i.e.\n- The image contains all of the integers ``1, 2, ..., n`` for some ``n`` exactly once\n- The image contains nothing else\n\nI will also impose an additional condition, which is that the largest integer `n` must not be fixed, since there is no point in storing it. However, this can be amended within the code, rather than rejecting such an image vector.\n\nThe way to impose these conditions is to use an inner constructor, which is a method within the `struct` block.\n```julia\nstruct Permutation\n    image::Vector{Int64}\n\n\tfunction Permutation(image::Vector{Int64})\n\t\t# Inner constructor code\n\tend\nend\n```\n\nTo check that the vector `image` contains the right elements, I sort it and compare it to the vector `1:n`, where `n` is the length of `image`.\n```julia\nsort(image) == 1:length(image)\n```\n\nThen, I find the integers which aren't fixed by using Boolean indexing, which is indexing an array with an array of `true`s and `false`s of the same size, and taking the elements which correspond to `true`. The maximum of them is then found, with `1` added to the list since `maximum` cannot find the maximum element of an empty vector.\n```julia\nm = maximum([image[image .!= 1:length(image)]..., 1])\n```\n\nNow, I can make use of the inner constructor specific keyword `new` to construct the permutation, by ordering the arguments as they would be if I were calling the `Permutation` function. With an error message if the conditions are not met by `image`, this completes my inner constructor\n```julia\nfunction Permutation(image::Vector{Int64})\n    sortedimage = sort(image)\n \tm = maximum([image[image .!= 1:length(image)]..., 1])\n    sortedimage == 1:last(sortedimage) && return new(image[1:m])\n    error(\"not a valid permutation\")\nend\n```\n\"\"\"\n\n# ╔═╡ 99fe42de-2afa-409f-9416-5c7671e4d0f4\nmd\"\"\"\nOne last thing I want to adjust before I am done with the `Permutation` type is to be able to construct a permutation by just giving it a list of integers and not having to wrap them up in vector form myself. This I do by utilising multiple dispatch, with an outer constructor, which is simply a new method with different inputs to construct a `Permutation` object.\n```julia\nPermutation(imagevals::Int64...) = Permutation([x for x ∈ imagevals])\n```\n\nPutting this all together, I get (including some code from later sections, due to the reactivity of the Pluto notebook in which this is written):\n\"\"\"\n\n# ╔═╡ b9c535e5-3317-4291-9925-696bc6cb0252\nbegin\n\tstruct Permutation\n    \timage::Vector{Int64}\n\t\t\n\t    function Permutation(image::Vector{Int64})\n    \t    sortedimage = sort(image)\n        \tm = maximum([image[image .!= 1:length(image)]..., 1])\n\t        sortedimage == 1:last(sortedimage) && return new(image[1:m])\n    \t    error(\"not a valid permutation\")\n\t    end\n\tend\n\n\tPermutation(imagevals::Int64...) = Permutation([x for x ∈ imagevals])\n\t\n\t# See section Evaluating a Permutation as a function below\n\tmaxarg(σ::Permutation) = length(σ.image)\n\t(σ::Permutation)(x::Int64) = x ∈ 1:maxarg(σ) ? σ.image[x] : x\n\t\n\t# See section Generating groups with Permutations\n\timport Base.:(==)\n\t==(σ::Permutation, τ::Permutation) = (σ.image == τ.image)\n\t\n\tnothing\nend\n\n# ╔═╡ 1d56249e-d86a-4d1e-b7d2-6d63a621bfa8\nisfour(x::Number) = (x == 4)\n\n# ╔═╡ 9ab255ff-b40a-4f16-bed8-fe14e4495502\nisfour(4.0)\n\n# ╔═╡ 98750bd0-84bd-4cb1-900b-9ee26142e4ec\nisfour(\"Twelve\")\n\n# ╔═╡ 4e4508db-47c0-462f-9cec-93e52bbffd7c\nisfour([4])\n\n# ╔═╡ de16f61d-853a-43ed-adf0-fb77ea3c8f4a\nσ = Permutation(4,5,1,3,2); σ.image\n\n# ╔═╡ 322f2dbc-f8f4-4f62-a9bb-ea6b00a333ae\nmd\"\"\"\n### Evaluating a `Permutation` as a function\nI now have a `Permutation` object, but it doesn't do anything yet. The next step is to be able to use a Permutation object as the function that it represents, i.e. evaluate it at an integer. I can do this by defining a function with its name as a `Permutation` parameter:\n```julia\n(σ::Permutation)(x::Int64) = σ.image[x]\n```\n\nHowever this will give an error for any integer not between `1` and the maximum unfixed integer (`m` in the inner constructor), since no such index exists. Instead, I want it to fix all other integers, which will make composing permutations later much easier, so I amend the code, defining a new function `maxarg` to go with it:\n```julia\nmaxarg(σ::Permutation) = length(σ.image)\n(σ::Permutation)(x::Int64) = x ∈ 1:maxarg(σ) ? σ.image[x] : x\n```\n\nThis is included in the block above with the constructors. I can test the result of this on the sample permutation `σ` defined above\n\"\"\"\n\n# ╔═╡ ff8ab6b4-34de-44eb-b98a-2f5e0f1c48fc\nσ(4)\n\n# ╔═╡ 5ce89616-326b-4404-9f2f-707c91835fa3\nmaxarg(σ)\n\n# ╔═╡ 9617f0f2-1b45-418f-8818-26df1abde6cb\nmd\"\"\"\n### Creating a custom display format for a `Permutation` object\nAt the moment, whenever a `Permutation` object is returned, it displays in the default form for a new `struct`, which is the name of the type followed by a list of its fields (in this case `σ` would look like `Permutation([4, 5, 1, 3, 2])`). This isn’t very useful, so be more understandable (and more in keeping with standard mathematical notation), I want to customise this displayed form, which I can do with multiple dispatch by adding a method to the function `show` specifically for the `Permutation` type.\n\nThe format that I want to display the permutation in is as its disjoint cycle decomposition. This will first require a function to calculate the orbit generated by acting repeatedly on a given element:\n\"\"\"\n\n# ╔═╡ ee9d45f3-0a25-47f6-8445-8ba733c3a8f6\nfunction orbit(σ::Permutation, x::Int64)\n    orb = [x]\n    y = σ(x)\n    while y != x\n        push!(orb,y)\n        y = σ(y)\n    end\n    return orb\nend\n\n# ╔═╡ b119e9f0-b8ba-42a3-a76c-82ed2dc170a4\nmd\"\"\"\nTo calculate the disjoint cycle decomposition, I build up the output as follows:\n- I start out with an empty `Vector{Vector{Int64}}` (that is, a vector whose elements are vectors of integers)\n```julia\ndecomp = Vector{Int64}[]\n```\n\n- A vector `unaccounted` tracks which values in the range `1:maxarg(σ)` are yet to be added to the decomposition. I will iterate until this vector is entirely false\n```julia\nunaccounted = trues(maxarg(σ))\n\nwhile any(unaccounted)\n    # code to iterate\nend\n```\n\n- Inside the loop, I will look for the first value which is unaccounted for in the decomposition so far, calculate its orbit, and then update `unaccounted` accordingly\n```julia\nx = findfirst(unaccounted)\nxorbit = orbit(σ,x)\nunaccounted[xorbit] .= false\n```\n\n- Then, if the orbit is non-trivial, I add it to the decomposition\n```julia\nlength(xorbit) > 1 && push!(decomp,xorbit)\n```\n\nThis results in `decomp` being a list of cycles exactly determining the disjoint cycle decomposition.\n\"\"\"\n\n# ╔═╡ e4ce9583-5c18-4df7-a5fb-a46670fe40af\nfunction dcd(σ::Permutation)\n    decomp = Vector{Int64}[]\n    unaccounted = trues(maxarg(σ))\n    while any(unaccounted)\n        x = findfirst(unaccounted)\n        xorbit = orbit(σ,x)\n        unaccounted[xorbit] .= false\n        length(xorbit) > 1 && push!(decomp,xorbit)\n    end\n    return decomp\nend\n\n# ╔═╡ b2ac585a-d84a-4d19-afe5-ad6d288e847f\nmd\"\"\"\nI then need to consider how to build up the string from this decomposition\n- Each cycle from the decomposition will be expressed as an open parenthesis, followed by the list of integers in order, separated by spaces, and then closed with another parenthesis. To do this, I list out strings that I can then concatenate with `*`.\n```julia\n*( \"( \", [\"$y \" for y ∈ x]... , \")\" )\n```\n\n- This needs to be repeated for all of the cycles in the decomposition, with an additional empty string added in case the disjoint cycle decomposition is empty.\n```julia\ntoprint = *([ *( \"( \", [\"$y \" for y ∈ x]... , \")\" ) for x ∈ dcd(σ)]..., \"\")\n```\n\n- Finally, if (and only if) the permutation is the identity permutation, then the string will be empty at this point. Instead, I want to use the symbol `ι`.\n```julia\ntoprint == \"\" && (toprint = \"ι\")\n```\n\nIn order to write my new method for `show`, I first need to `import` it, ensuring that I do not overwrite the inbuilt methods that it has. Then, I construct my function, mirroring the syntax used for `show` in the source code as it is good practice.\n\"\"\"\n\n# ╔═╡ 7a96d2c8-aa9c-405f-b34f-1f3c7c53b6c6\nbegin\n\timport Base.show\n\t\n\tfunction show(io::IO,σ::Permutation)\n\t    toprint = *([ *( \"( \", [\"$y \" for y ∈ x]... , \")\" ) for x ∈ dcd(σ)]..., \"\")\n    \ttoprint == \"\" && (toprint = \"ι\")\n\t    print(io, toprint)\n\tend\nend\n\n# ╔═╡ 12346644-107b-4c43-aaca-3e404fecc8b3\nmd\"\"\"\nPermutations now have a much more aesthetic and useful display style:\n\"\"\"\n\n# ╔═╡ 0afa030a-58ad-44f6-a10f-0ae3baabe6f8\nσ\n\n# ╔═╡ 1e8659dc-27d5-429d-8431-d5cfa9006411\nmd\"\"\"\n### Adding `Permutation` arithmetic\nI now want to add some arithmetic for combining `Permutation` objects, starting with a shortcut for the identity. This will be represented by the constant `ι` (mirroring the way it is displayed by `show`), and is given by:\n\"\"\"\n\n# ╔═╡ 068a9d15-ce46-4aa5-9c13-3f79e70b0eda\nconst ι = Permutation(1)\n\n# ╔═╡ b3151f52-6dd7-4f63-a158-becb5d1aec2e\nmd\"\"\"\nThen, I add two methods to the inbuilt function one allowing it to be obtained either by passing a permutation, or the `Permutation` type. For these functions, the input variables are not given names, only their types specified, since the type is the only relevant property about the input, as needed for multiple dispatch.\n\"\"\"\n\n# ╔═╡ d614739d-b22f-4991-9722-e8371732bf4b\nbegin\n\timport Base.one\n\tone(::Permutation) = ι\n\tone(::Type{Permutation}) = ι\nend\n\n# ╔═╡ 363481da-d185-4846-82ab-c227e9f668f8\nmd\"\"\"\nNext, I want to be able to compose permutations, for which I will write new `Permutation`-specific methods for the inbuilt operator `∘`. In order for an arbitrary number of permutations to be composable, I use an inductive definition which mirrors the definition of composition of functions [from the Julia source code](https://github.com/JuliaLang/julia/blob/master/base/operators.jl#L1096), that is:\n```julia\n∘(f) = f\n∘(f, g) = ComposedFunction(f, g)\n∘(f, g, h...) = ∘(f ∘ g, h...)\n```\n\nHence, my methods for `∘` are:\n\"\"\"\n\n# ╔═╡ 8f925ec6-7cd8-49fe-a467-807711b3425b\nbegin\n\timport Base.∘\n\t∘(σ::Permutation) = σ\n\t∘(σ::Permutation, τ::Permutation) =\n        Permutation([σ(τ(x)) for x ∈ 1:max(maxarg(σ),maxarg(τ))])\n\t∘(σ::Permutation, τ::Permutation, υ::Permutation...) = ∘(σ ∘ τ, υ...)\nend\n\n# ╔═╡ 4552e49c-af66-4fd3-a827-28284215f4f9\nmd\"\"\"\nThirdly, I want an inverse function to be able to find the inverse of a permutation. To do this, I need to find the index of each of `1:maxarg(σ)` in the image vector and let that be the image of the new permutation, which is done by:\n\"\"\"\n\n# ╔═╡ 0e710b07-b5db-4ea7-986b-8eb7fc0946b1\nbegin\n\timport Base.inv\n\tinv(σ::Permutation) = Permutation([findfirst(σ.image .== x) for x ∈ 1:maxarg(σ)])\nend\n\n# ╔═╡ 7c082457-980c-4961-bb10-d91b7248d0f6\nmd\"\"\"\nFinally, I want to be able to exponentiate by any integer (including zero and negative integers), which can be done using some logic combined with the three operations above:\n\"\"\"\n\n# ╔═╡ 59075aa4-dd35-47af-b4d1-40e89b2e599f\nbegin\n\timport Base.^\n\n\tfunction ^(σ::Permutation,n::Int64)\n\t    n == 0 && return one(Permutation)\n\t    n < 0 && ((n,σ) = (-n,inv(σ)))\n\t    return ∘(fill(σ,n)...)\n\tend\nend\n\n# ╔═╡ 764fb693-f4ac-4327-93a3-2171621ad039\nmd\"\"\"\nI can now test these out:\n\"\"\"\n\n# ╔═╡ 75e5491a-6536-44b0-a5b9-10cf7f9e5c66\nι\n\n# ╔═╡ 9d43f21c-c60a-4bf8-b1a0-bf3b56b3a97b\nσ\n\n# ╔═╡ b421f174-d554-47a8-a72d-4d5f3ec6ba2e\nτ = Permutation(4,5,2,3,1)\n\n# ╔═╡ ff82e088-aa60-49fe-bb12-fe39b0430d51\nσ ∘ τ\n\n# ╔═╡ 7c0c4e99-ebff-409b-87f3-919a6870cccc\nσ^-1\n\n# ╔═╡ 029a0c9f-5d32-409d-b6ad-9e0d4e19e854\nτ^5\n\n# ╔═╡ c75f7100-778e-44c6-9d43-675d11175673\nmd\"\"\"\n## Generating groups with `Permutation` objects\n\n### Constructing symmetric and alternating groups\nThe first groups that I would like to be able to list the elements of are symmetric or alternating groups. Before this however, I will define two more functions which will be useful to me in their construction.\n\nFirst, I would like a way to quickly construct a transposition:\n\"\"\"\n\n# ╔═╡ 0598e94b-a043-4106-bb7b-d032eb67be0b\nfunction transposition(m::Int64, n::Int64)\n    image = collect(1:max(m,n))\n    image[m], image[n] = n, m\n    return Permutation(image)\nend\n\n# ╔═╡ 00a61c28-230d-41b0-81ac-e2f0869d6640\ntransposition(3,4)\n\n# ╔═╡ 32b52a58-6086-4c2f-a833-e1a7efb69d29\ntransposition(3,3)\n\n# ╔═╡ 84bd5d92-00eb-4e66-a1c5-c86626b8f7d2\nmd\"\"\"\nNote that `transposition(m,m)` returns the identity, which turns out to be exactly what I want.\n\nTo find the alternating group, I will need to consider the parity of elements. The easiest way to find the parity of a permutation is to consider it as a product of cycles and consider their parities. I already have such a decomposition, given by `dcd`, so using the `iseven` function, and `sum` to count the number of `true` elements of an array, I can write such a function:\n\"\"\"\n\n# ╔═╡ 1b10a694-a310-4a4e-9831-654e3e9691d1\nparity(σ::Permutation) = (-1)^sum([iseven(length(x)) for x ∈ dcd(σ)])\n\n# ╔═╡ 9812e6fb-9308-4c27-9d57-9fbf71474343\nparity(ι)\n\n# ╔═╡ d69ce761-f489-4728-a19d-783b84b436a5\nparity(σ)\n\n# ╔═╡ a6be1358-652d-4084-9c8e-f3089fb99169\nparity(τ)\n\n# ╔═╡ 41cf3bc2-c70c-4053-bed0-74a11f8a5ad5\nmd\"\"\"\nNow, I have all the tools to create the `n`th symmetric group as a vector of `Permutation` objects, which I will do recursively using the inductive formula:\n```math\nS_1 = \\{ \\iota \\}, \\qquad S_n = \\{ \\sigma \\circ (m n) : \\sigma \\in S_{n-1}, m \\in \\{ 1, 2, \\dots, n \\} \\}\n```\nwhere as in the `transposition` function above, ``(n n) = \\iota``.\n\n- First, I will check that `n` is positive to avoid non-terminating loops (and also because the group doesn’t make sense otherwise)\n```julia\nn ≥ 1 || error(\"symmetric group must have a positive parameter\")\n```\n\n- Then, I implement the base case of the trivial group when `n == 1`:\n```julia\nn == 1 && return [ι]\n```\n\n- For the recursive step, I copy `symmetricgroup(n-1)` into a vector `n` times, and then set up the corresponding vector of transpositions that I will multiply each by, using array filling and concatenation. Then, I compose the two elementwise:\n```julia\npermutations = vcat(fill(symmetricgroup(n-1),n)...)\ntranspositions = vcat([fill(transposition(i,n),factorial(n-1)) for i ∈ 1:n]...)\nreturn permutations .∘ transpositions\n```\n\nThe entire function is:\n\"\"\"\n\n# ╔═╡ c70a297d-adb7-4f70-b6bb-949a3d49d3c0\nfunction symmetricgroup(n::Int64)\n    n ≥ 1 || error(\"symmetric group must have a positive parameter\")\n    n == 1 && return [ι]\n\n    permutations = vcat(fill(symmetricgroup(n-1),n)...)\n    transpositions = vcat([fill(transposition(i,n),factorial(n-1)) for i ∈ 1:n]...)\n    return permutations .∘ transpositions\nend\n\n# ╔═╡ eb5640fa-0814-497c-b157-da718df1c129\nmd\"\"\"\nNow, finding the `n`th alternating group is as simple as finding the `n`th symmetric group and taking the even permutations:\n\"\"\"\n\n# ╔═╡ d546b70a-eeaa-45db-8b65-d36cb13b67f6\nfunction alternatinggroup(n::Int64)\n    Sₙ = symmetricgroup(n)\n    return Sₙ[parity.(Sₙ) .== 1]\nend\n\n# ╔═╡ 5dea6f25-65fe-4304-a7e7-2d4b830f4724\nsymmetricgroup(5)\n\n# ╔═╡ 13cacc56-7fcc-4a71-9cc5-be298295939b\nalternatinggroup(5)\n\n# ╔═╡ 46eeeed1-a8e4-49cc-8d97-6ddfb1fa2b1e\nmd\"\"\"\n### Generating arbitrary finite groups\nInstead of just symmetric and alternating groups, I would like to be able to generate a group given a list of `Permutation` objects as generators. By Cayley's theorem, this suffices to construct any finite group, assuming that you can find an appropriate list of generators. This will require one final use of multiple dispatch, which will be for me to define equality of permutations:\n```julia\nimport Base.:(==)\n==(σ::Permutation, τ::Permutation) = (σ.image == τ.image)\n```\n\nThis snippet of code is included in the block with the definition of the `Permutation` type at the end of the section [Declaring `Permutation` as a new type](#73d93917-b72e-468b-970c-f34ec6d51de4), since otherwise the import of `==` here conflicts with its use in the definition of `Permutation` in the Pluto notebook format.\n\nI can now write a function to generate a group from a list of generators. This I will do by repeatedly checking closure under multiplication, which is not a particularly clever or efficient algorithm, but it will work which is all I am looking for in this case.\n\"\"\"\n\n# ╔═╡ 3e8b7d82-1d63-4aec-8ed6-0b1f11c5cb33\nfunction generate(σs::Permutation...)\n    G = [σs...]\n    while true\n        newelements = Permutation[]\n\n        for σ ∈ G, τ ∈ G\n            υ = σ ∘ τ\n            υ ∉ G && υ ∉ newelements && push!(newelements, υ)\n        end\n\n        if isempty(newelements)\n            return G\n        else\n            G = vcat(G,newelements)\n        end\n    end\nend\n\n# ╔═╡ 79584487-dd19-4014-97e7-7fcc0582efa8\nmd\"\"\"\nAn interesting point of note here is that nowhere in the function do I use the syntax `==`, and yet the function would not work without it. This demonstrates further the power of multiple dispatch, since the operator `∉` uses `==` to determine whether or not `υ` is an element of `G` (or `newelements`), and I have defined what `==` means for a `Permutation`, so `∉` will automatically work for permutations without me explicitly telling it how to.\n\nSome demonstrations of the `generate` function are shown below, with `C₅`, `D₁₀`, and `G` the group generated by `σ` and `τ`, which happens to be `S₅`:\n\"\"\"\n\n# ╔═╡ 4725c3bb-a1c1-49cc-9bf7-a7e443db085c\nC₅ = generate(Permutation(2,3,4,5,1))\n\n# ╔═╡ 9e84f004-fd88-4a25-bfba-0797d2df0942\nD₁₀ = generate(Permutation(2,3,4,5,1),Permutation(5,4,3,2,1))\n\n# ╔═╡ bd677d6a-3b42-497d-bcfb-58543dee7ebd\nG = generate(σ,τ)\n\n# ╔═╡ 076885f1-61b4-4913-8530-fd65c531f419\nS₅ = symmetricgroup(5)\n\n# ╔═╡ 738df784-eeb7-4d3b-b19f-6317f2459c6d\nall([g ∈ G for g ∈ S₅]) && all([g ∈ S₅ for g ∈ G])\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\n\n[compat]\nPlutoUI = \"~0.7.9\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"477bf42b4d1496b454c10cce46645bb5b8a0cf2c\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.2\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"Suppressor\"]\ngit-tree-sha1 = \"44e225d5837e2a2345e69a1d1e01ac2443ff9fcb\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.9\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Reexport]]\ngit-tree-sha1 = \"5f6c21241f0f655da3952fd60aa18477cf96c220\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[Suppressor]]\ngit-tree-sha1 = \"a819d77f31f83e5792a76081eee1ea6342ab8787\"\nuuid = \"fd094767-a336-5f1f-9728-57cf17d0bbfb\"\nversion = \"0.2.0\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─08eadc12-f8e9-11eb-1094-b7adc6936aa1\n# ╟─c4d2ff29-2579-4079-a6cb-29015ef5ecd2\n# ╟─db919e43-6dc8-4e53-8081-d9312446117a\n# ╠═524dee4b-6687-44de-af79-b99d3724f9ac\n# ╠═a16202d3-406a-4b43-807e-b60c673d4132\n# ╟─41fc4769-5b67-4503-b1d1-2854a0d9c3a2\n# ╠═1d56249e-d86a-4d1e-b7d2-6d63a621bfa8\n# ╠═acf690f4-b65b-4576-9145-1e894d5342f2\n# ╠═9ab255ff-b40a-4f16-bed8-fe14e4495502\n# ╠═98750bd0-84bd-4cb1-900b-9ee26142e4ec\n# ╟─9f193c51-b6ea-477f-ab0e-1bc5a4be4b86\n# ╠═29b729bb-cd1a-4ee1-ae2e-26b55ce744a4\n# ╠═4e4508db-47c0-462f-9cec-93e52bbffd7c\n# ╟─740f8275-ee0c-4aa2-b0c1-76d46fad3ecd\n# ╟─73d93917-b72e-468b-970c-f34ec6d51de4\n# ╟─c18ae801-b186-44cf-9e42-83188c4781aa\n# ╟─99fe42de-2afa-409f-9416-5c7671e4d0f4\n# ╠═b9c535e5-3317-4291-9925-696bc6cb0252\n# ╠═de16f61d-853a-43ed-adf0-fb77ea3c8f4a\n# ╟─322f2dbc-f8f4-4f62-a9bb-ea6b00a333ae\n# ╠═ff8ab6b4-34de-44eb-b98a-2f5e0f1c48fc\n# ╠═5ce89616-326b-4404-9f2f-707c91835fa3\n# ╟─9617f0f2-1b45-418f-8818-26df1abde6cb\n# ╠═ee9d45f3-0a25-47f6-8445-8ba733c3a8f6\n# ╟─b119e9f0-b8ba-42a3-a76c-82ed2dc170a4\n# ╠═e4ce9583-5c18-4df7-a5fb-a46670fe40af\n# ╟─b2ac585a-d84a-4d19-afe5-ad6d288e847f\n# ╠═7a96d2c8-aa9c-405f-b34f-1f3c7c53b6c6\n# ╟─12346644-107b-4c43-aaca-3e404fecc8b3\n# ╠═0afa030a-58ad-44f6-a10f-0ae3baabe6f8\n# ╟─1e8659dc-27d5-429d-8431-d5cfa9006411\n# ╠═068a9d15-ce46-4aa5-9c13-3f79e70b0eda\n# ╟─b3151f52-6dd7-4f63-a158-becb5d1aec2e\n# ╠═d614739d-b22f-4991-9722-e8371732bf4b\n# ╟─363481da-d185-4846-82ab-c227e9f668f8\n# ╠═8f925ec6-7cd8-49fe-a467-807711b3425b\n# ╟─4552e49c-af66-4fd3-a827-28284215f4f9\n# ╠═0e710b07-b5db-4ea7-986b-8eb7fc0946b1\n# ╟─7c082457-980c-4961-bb10-d91b7248d0f6\n# ╠═59075aa4-dd35-47af-b4d1-40e89b2e599f\n# ╟─764fb693-f4ac-4327-93a3-2171621ad039\n# ╠═75e5491a-6536-44b0-a5b9-10cf7f9e5c66\n# ╠═9d43f21c-c60a-4bf8-b1a0-bf3b56b3a97b\n# ╠═b421f174-d554-47a8-a72d-4d5f3ec6ba2e\n# ╠═ff82e088-aa60-49fe-bb12-fe39b0430d51\n# ╠═7c0c4e99-ebff-409b-87f3-919a6870cccc\n# ╠═029a0c9f-5d32-409d-b6ad-9e0d4e19e854\n# ╟─c75f7100-778e-44c6-9d43-675d11175673\n# ╠═0598e94b-a043-4106-bb7b-d032eb67be0b\n# ╠═00a61c28-230d-41b0-81ac-e2f0869d6640\n# ╠═32b52a58-6086-4c2f-a833-e1a7efb69d29\n# ╟─84bd5d92-00eb-4e66-a1c5-c86626b8f7d2\n# ╠═1b10a694-a310-4a4e-9831-654e3e9691d1\n# ╠═9812e6fb-9308-4c27-9d57-9fbf71474343\n# ╠═d69ce761-f489-4728-a19d-783b84b436a5\n# ╠═a6be1358-652d-4084-9c8e-f3089fb99169\n# ╟─41cf3bc2-c70c-4053-bed0-74a11f8a5ad5\n# ╠═c70a297d-adb7-4f70-b6bb-949a3d49d3c0\n# ╟─eb5640fa-0814-497c-b157-da718df1c129\n# ╠═d546b70a-eeaa-45db-8b65-d36cb13b67f6\n# ╠═5dea6f25-65fe-4304-a7e7-2d4b830f4724\n# ╠═13cacc56-7fcc-4a71-9cc5-be298295939b\n# ╟─46eeeed1-a8e4-49cc-8d97-6ddfb1fa2b1e\n# ╠═3e8b7d82-1d63-4aec-8ed6-0b1f11c5cb33\n# ╟─79584487-dd19-4014-97e7-7fcc0582efa8\n# ╠═4725c3bb-a1c1-49cc-9bf7-a7e443db085c\n# ╠═9e84f004-fd88-4a25-bfba-0797d2df0942\n# ╠═bd677d6a-3b42-497d-bcfb-58543dee7ebd\n# ╠═076885f1-61b4-4913-8530-fd65c531f419\n# ╠═738df784-eeb7-4d3b-b19f-6317f2459c6d\n# ╟─f1d0ed8f-bfd3-4210-84fd-f189bba6ebf9\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "b362106df380e1856d7390cbecb367e1f626473b", "size": 26637, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "casestudies/Permutations/permutationsnotebook.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "casestudies/Permutations/permutationsnotebook.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "casestudies/Permutations/permutationsnotebook.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 38.2166427547, "max_line_length": 706, "alphanum_fraction": 0.7235048992, "num_tokens": 9967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7630151228147518}}
{"text": "# Matern 3/2 ARD covariance function\n\n\"\"\"\n    Mat32Ard <: MaternARD\n\nARD Matern 3/2 kernel (covariance)\n```math\nk(x,x') = σ²(1 + √3|x-x'|/L)\\\\exp(- √3|x-x'|/L)\n```\nwith length scale ``ℓ = (ℓ₁, ℓ₂, …)`` and signal standard deviation ``σ`` where\n``L = diag(ℓ₁, ℓ₂, …)``.\n\"\"\"\nmutable struct Mat32Ard{T} <: MaternARD where {T<:Real}\n    \"Inverse squared length scale\"\n    iℓ2::Vector{T}\n    \"Signal variance\"\n    σ2::T\n    \"Priors for kernel parameters\"\n    priors::Array\nend\n\n\"\"\"\nMatern 3/2 ARD covariance function\n    \n    Mat32Ard(ll::Vector{T}, lσ::T)\n\n# Arguments\n  - `ll::Vector{Real}`: vector of length scales (given on log scale)\n  - `lσ::Real`: signal standard deviation (given on log scale)  \n\"\"\"\nMat32Ard(ll::Vector{T}, lσ::T) where T = Mat32Ard{T}(exp.(-2 .* ll), exp(2 * lσ), [])\n\nfunction set_params!(mat::Mat32Ard, hyp::AbstractVector)\n    length(hyp) == num_params(mat) || throw(ArgumentError(\"Mat32 kernel has $(num_params(mat)) parameters, received $(length(hyp)).\"))\n    @views @. mat.iℓ2 = exp(-2 * hyp[1:(end-1)])\n    mat.σ2 = exp(2 * hyp[end])\nend\n\nget_params(mat::Mat32Ard{T}) where T = T[-log.(mat.iℓ2) / 2; log(mat.σ2) / 2]\nget_param_names(mat::Mat32Ard) = [get_param_names(mat.iℓ2, :ll); :lσ]\nnum_params(mat::Mat32Ard) = length(mat.iℓ2) + 1\n\ncov(mat::Mat32Ard, r::Number) =\n    (s = √3 * r; mat.σ2 * (1 + s) * exp(-s))\n\ndk_dll(mat::Mat32Ard, r::Real, wdiffp::Real) = 3 * mat.σ2 * wdiffp * exp(-√3 * r)\n", "meta": {"hexsha": "91f24959f9e3946ce14ab2f51fec42a1185c4698", "size": 1424, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/mat32_ard.jl", "max_stars_repo_name": "mcusi/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 284, "max_stars_repo_stars_event_min_datetime": "2015-07-31T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T07:08:58.000Z", "max_issues_repo_path": "src/kernels/mat32_ard.jl", "max_issues_repo_name": "mcusi/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 171, "max_issues_repo_issues_event_min_datetime": "2015-05-28T12:04:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T06:48:23.000Z", "max_forks_repo_path": "src/kernels/mat32_ard.jl", "max_forks_repo_name": "mcusi/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-05-31T12:44:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:21:38.000Z", "avg_line_length": 30.2978723404, "max_line_length": 134, "alphanum_fraction": 0.6186797753, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7630151209530384}}
{"text": "mult(x, y) = x * y\ntypeof(mult) #> Function\nm = mult\nm(6, 6) #> 36\n\nplustwo = function (x)\n              x + 2\n          end\nplustwo(3) #> 5\n\n3+4 #> 7\n+(3,4) #> 7\n\nfunction numerical_derivative(f, x, dx=0.01)\n  derivative = (f(x+dx) - f(x-dx))/(2*dx)\n  return derivative\nend\n\nf = x -> 2x^2 + 30x + 9\nprintln(numerical_derivative(f, 1, 0.001)) #> 33.99999999999537\n\nfunction derivative(f)\n    return function(x)\n        # pick a small value for h\n        h = x == 0 ? sqrt(eps(Float64)) : sqrt(eps(Float64)) * x\n        xph = x + h\n        dx = xph - x\n        f1 = f(xph) # evaluate f at x + h\n        f0 = f(x) # evaluate f at x\n        return (f1 - f0) / dx  # divide by h\n    end\nend\n\n# closure:\nfunction counter()\n    n = 0\n    () -> n += 1, () -> n = 0\nend\n\n(addOne, reset) = counter()\naddOne()\naddOne()\naddOne()\nreset()\n\n# currying:\nfunction add(x)\n    return function f(y)\n        return x + y\n    end\nend\nadd(1)(2) #> 3\nadd(x) = f(y) = x + y \nadd(x) = y -> x + y\n\n# nested:\nfunction afun(x)\n    z = x * 2\n    function b(z)\n        z += 1\n    end\n    b(z)\nend\n\nd = 5\nafun(d) #> 11\n\n# recursive:\nsum(n) =  n > 1 ? sum(n-1) + n : n\nsum(100) #> 5050\nfib(n) = n < 2 ? n : fib(n-1) + fib(n-2)\nprintln(fib(25)) #> 75025", "meta": {"hexsha": "cd69bfbc6a85fb571a4b070896e5cea7dc93404d", "size": 1220, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Module 1/Chapter03/first_class.jl", "max_stars_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_stars_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2017-02-12T15:36:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T03:30:39.000Z", "max_issues_repo_path": "Module 1/Chapter03/first_class.jl", "max_issues_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_issues_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Module 1/Chapter03/first_class.jl", "max_forks_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_forks_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-02-10T16:19:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T11:46:44.000Z", "avg_line_length": 16.9444444444, "max_line_length": 64, "alphanum_fraction": 0.5106557377, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927012, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7630053692945381}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.7\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local iv = try Base.loaded_modules[Base.PkgId(Base.UUID(\"6e696c72-6542-2067-7265-42206c756150\"), \"AbstractPlutoDingetjes\")].Bonds.initial_value catch; b -> missing; end\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)\n        el\n    end\nend\n\n# ╔═╡ 736856ce-f490-11eb-3349-057c86edfe7e\nbegin\n    using Pkg\n\tPkg.activate(joinpath(Pkg.devdir(), \"MLCourse\"))\n    using MLJ, MLJLinearModels, Plots, DataFrames, Random\nend\n\n# ╔═╡ c693088f-7f80-4cdd-b9b5-65a50da732ac\nbegin\n    using MLCourse\n    import MLCourse: poly, Polynomial\n    MLCourse.list_notebooks(@__FILE__)\nend\n\n\n# ╔═╡ e1077092-f72a-42af-b6e0-a616f938cba8\nusing PlutoUI; PlutoUI.TableOfContents()\n\n# ╔═╡ 7eb6a060-f948-4d85-881a-4909e74c15bd\nmd\"# Validation Set Approach\n\nIn the following cell we define a `data_generator` that creates data sets with a polynomial relationship of degree 3 between the input x and the average output f(x).\n\"\n\n# ╔═╡ 7dd7e9a7-9245-4c64-af0c-8f7d2f62b2bf\nbegin\n    f(x) = 0.3 + 2x - 0.8x^2 - 0.4x^3\n    function data_generator(; n = 500, seed = 12)\n        rng = MersenneTwister(seed)\n        x = randn(rng, n)\n        DataFrame(x = x, y = f.(x) .+ randn(rng, n))\n    end\nend;\n\n# ╔═╡ 5049407c-bf93-41a5-97bd-863a69d7016a\nmd\"## Test Error Estimation\n\nWe will estimate here the test error with the validation set approach for fixed hyper-parameters.\"\n\n# ╔═╡ 46827e21-0eea-4ec9-83ed-05e41dda1502\ndata1 = data_generator(seed = 1);\n\n# ╔═╡ 6cfc32b3-40c0-4149-ba67-2ec67b3938f3\nmd\"split seed = $(@bind split_seed Slider(1:20, show_value = true))\"\n\n# ╔═╡ 1320b9b0-d6fc-4e61-8d62-de3988b8b21d\nidxs = shuffle(MersenneTwister(split_seed), 1:500) # shuffle the indices\n\n# ╔═╡ 5dc21667-d94f-4c2a-b217-80b9a2262d8c\nbegin\n\tdata1_train = data1[idxs[1:250], :]\n\tdata1_test = data1[idxs[251:end], :]\n\tmach = machine(Polynomial(degree = 8) |> LinearRegressor(),\n\t               select(data1_train, :x), data1_train.y)\n\tfit!(mach, verbosity = 0)\n\t(training_error = rmse(predict(mach), data1_train.y),\n\t test_error = rmse(predict(mach, select(data1_test, :x)), data1_test.y))\nend\n\n# ╔═╡ 1fe3f6d1-6336-417e-885e-de3fc5821bdf\nlet\n\tscatter(data1_train.x, data1_train.y, label = \"training set\")\n\tscatter!(data1_test.x, data1_test.y, label = \"test set\")\n\txgrid = -4:.1:4\n\tpred = predict(mach, DataFrame(x = xgrid))\n\tplot!(xgrid, pred, label = \"fit\", ylim = (-6, 5), xlim = (-4, 4))\nend\n\n# ╔═╡ b79fae90-87f3-4f89-933b-d82e76c94d81\nmd\"We see that the resulting curve and the test error depends strongly on the training set, i.e. the indices that are selected for the training set. The training error is always close to the irreducible error in this case.\"\n\n# ╔═╡ 7d30f043-2915-4bba-aad5-cb7dbe76a3e5\nmd\"## Hyper-parameter tuning\n\nNow we will use a nested validation set approach to find the optimal degree in polynomial regression and estimate the test error. For this we will split the data into training, validation and test set. For each hyper-parameter value we will fit the parameters on the training set and estimate the test error on the validation set. When we have found the best hyper-parameters based on the test error computed on the validation set, we will estimate the test error of the best model using the test set.\"\n\n# ╔═╡ ffffa3d0-bffb-4ff8-9966-c3312f952ac5\nbegin\n\tfunction data_split(data;\n                        shuffle = false,\n                        idx_train = 1:50,\n                        idx_valid = 51:100,\n                        idx_test = 101:500)\n        idxs = if shuffle\n                randperm(size(data, 1))\n            else\n                1:size(data, 1)\n            end\n        (train = data[idxs[idx_train], :],\n         valid = data[idxs[idx_valid], :],\n         test = data[idxs[idx_test], :])\n    end\n    function fit_and_evaluate(model, data)\n        mach = fit!(machine(model, select(data.train, :x), data.train.y),\n                    verbosity = 0)\n        (train = rmse(predict(mach, select(data.train, :x)), data.train.y),\n         valid = rmse(predict(mach, select(data.valid, :x)), data.valid.y),\n         test = rmse(predict(mach, select(data.test, :x)), data.test.y))\n    end\nend\n\n# ╔═╡ 2e02ac0d-c4d0-47ba-be57-445adeb6ab8b\nlosses1 = [fit_and_evaluate(Polynomial(; degree) |> LinearRegressor(),\n\t                        data_split(data1))\n           for degree in 1:10]\n\n# ╔═╡ 91eecd2b-af18-4a63-9684-28950e604d1a\nlet validlosses = getproperty.(losses1, :valid), i = argmin(validlosses)\n    plot(1:10, validlosses, label = nothing)\n    scatter!([i], [validlosses[i]], label = nothing,\n             xlabel = \"degree\", ylabel = \"validation loss\")\nend\n\n# ╔═╡ b45b32b1-8a65-4823-b3bb-f0b7cc57604b\nmd\"For this seed of the random number generator the optimal degree (x coordinate of the red point in the figure above) found by the validation set approach is close to the actual degree of the data generating process. The estimated test loss of the model with degree $(argmin((x -> x.valid).(losses1))) is $(losses1[argmin((x -> x.valid).(losses1))].test).\"\n\n# ╔═╡ 23e91f72-0124-48d4-8b53-bd5da67b7ac7\nlosses1[4]\n\n# ╔═╡ 4461d5b0-bc9b-4c89-aa76-70524a5caa7c\nmd\"Let us repeat the process above for other splits of the data.\"\n\n# ╔═╡ ac3c7e84-6c47-4dc1-b862-de4cfb05dad9\nlosses = [fit_and_evaluate(Polynomial(; degree) |> LinearRegressor(),\n                           data_split(data1, shuffle = true))\n          for degree in 1:10, _ in 1:20]\n\n# ╔═╡ 26362233-b006-423d-8fb5-7cd9150405b4\nlet validlosses = getproperty.(losses, :valid), i = argmin(validlosses, dims = 1)\n    plot(validlosses, label = nothing, ylims = (0, 10))\n    scatter!((x -> x[1]).(i), validlosses[i], label = nothing,\n             xlabel = \"degree\", ylabel = \"validation loss\")\nend\n\n# ╔═╡ 5cff19c7-3426-4d91-b555-f059f5f41886\nmd\"Here we see a large variability of the optimal degree (x coordinates of all the points in the figure above).\n\nIn the following cell we compare the validation set estimate of the test error to the test set estimation of the test error. We can confirm that the validation set estimate is much lower than the test set estimate.\"\n\n# ╔═╡ df16313f-76be-4d8b-88e7-7cc618ff49d4\nlet validlosses = getproperty.(losses, :valid),\n\ttestlosses = getproperty.(losses, :test),\n\twinners = argmin(validlosses, dims = 1)\n\t(mean_valid_winner = mean(validlosses[winners]),\n\t mean_test_winner = mean(testlosses[winners]))\nend\n\n# ╔═╡ 46bffe01-1a7c-405b-b3ec-bfe7570b8a3c\nmd\"# Cross-Validation\n\nHere we would like to find the optimal hyper-parameters with cross-validation.\nWe will not estimate the final test error of the model with the best hyper-parameters.\n\nIn the following cell we implement cross-validation.\"\n\n# ╔═╡ b3aed705-5072-4d9b-bb8f-865ac1561bf6\nbegin\n    function cross_validation_sets(idx, K)\n        n = length(idx)\n        r = n ÷ K\n        [let idx_valid = idx[(i-1)*r+1:(i == K ? n : i*r)]\n             (idx_valid = idx_valid, idx_train = setdiff(idx, idx_valid))\n         end\n         for i in 1:K]\n    end\n    function cross_validation(model, data; K = 5, shuffle = false)\n\t\tidxs = 1:size(data, 1)\n\t\tif shuffle\n            idxs = Random.shuffle(idxs)\n\t\tend\n        losses = [fit_and_evaluate(model,\n                                   data_split(data;\n\t\t\t\t\t\t\t\t\t          idx_test = [], # no test set\n\t\t\t\t\t\t\t\t\t          idxs...)) # training and validation\n                  for idxs in cross_validation_sets(idxs, K)]\n        (train = mean(getproperty.(losses, :train)),\n         valid = mean(getproperty.(losses, :valid)))\n    end\nend\n\n# ╔═╡ 6916273a-d116-4173-acaa-2bcac1d1753b\ncross_validation_sets(1:100, 4)\n\n# ╔═╡ c14c9e49-a993-456e-9115-97da86f8e498\nlosses1_cv10 = [cross_validation(Polynomial(; degree) |> LinearRegressor(),\n\t\t                         data1,\n\t\t                         K = 10) for degree in 1:10]\n\n# ╔═╡ 4b435518-2f12-4921-bb1f-fdd049ddfaed\nlet validlosses = getproperty.(losses1_cv10, :valid), i = argmin(validlosses)\n    plot(1:10, validlosses, label = nothing)\n    scatter!([i], [validlosses[i]], label = nothing,\n             xlabel = \"degree\", ylabel = \"validation loss\")\nend\n\n# ╔═╡ 1e584a38-2fef-4877-87f6-92237d71c4b3\nlosses_cv10 = [cross_validation(Polynomial(; degree) |> LinearRegressor(),\n                                data1,\n                                K = 10, shuffle = true)\n               for degree in 1:10, _ in 1:20]\n\n# ╔═╡ a7c88b3f-92cb-4253-a889-c78683722c1d\nlet validlosses = getproperty.(losses_cv10, :valid), i = argmin(validlosses, dims = 1)\n    plot(validlosses, label = nothing, ylims = (0.5, 2))\n    scatter!((x -> x[1]).(i), validlosses[i], label = nothing,\n             xlabel = \"degree\", ylabel = \"validation loss\")\nend\n\n# ╔═╡ 0b81c3d5-277a-4fe6-889b-550e2f83c39d\nmd\"With cross-validation we find often degree = 3 as the optimal one.\"\n\n# ╔═╡ 5747d116-1e61-45f0-a87b-89372c6f270f\nmd\"### Tuning Hyper-parameters with cross-validation and estimating the test error with the validation set approach\n\nInstead of using all data for hyper-parameter search using cross-validation, we could set some data aside as a test set and use this to estimate the test error of the model with the optimal hyper-parameters.\"\n\n# ╔═╡ 8204d9da-855d-4c66-b4dd-2c18a17b539b\nlosses2_cv10 = [cross_validation(Polynomial(; degree) |> LinearRegressor(),\n\t\t                         data1[1:100, :],\n\t\t                         K = 10) for degree in 1:10]\n\n# ╔═╡ 96b3c070-0c72-44c7-ac98-ff6cb7e82380\nmd\"The optimal degree found with cross-validation on the first 100 data points is:\"\n\n# ╔═╡ bae635b1-6eba-4ba4-80e9-547770612843\nargmin((x -> x.valid).(losses2_cv10))\n\n# ╔═╡ d9b04582-3a7a-4e19-a0da-d363810883f7\nmd\"Let us refit the model with the optimal degree on all data that was used for cross-validation and estimate it's test error on data points 101 to 500.\"\n\n# ╔═╡ 9042e811-9a34-42b8-8069-877f3b3f1e75\nlet \n\tmodel = Polynomial(degree = 4) |> LinearRegressor()\n\tmach = machine(model, select(data1[1:100, :], :x), data1[1:100, :y])\n\tfit!(mach, verbosity = 0)\n\ttestset = data1[101:end, :]\n\t(test_error = rmse(predict(mach, select(testset, :x)), testset.y),)\nend\n\n# ╔═╡ e2658128-4053-4484-8e1e-229eceb755ab\nmd\"# Resampling Strategies with MLJ\"\n\n# ╔═╡ eaacf529-1727-4743-941b-360c53088b1d\nmd\"Instead of our own cross-validation function we can also use the builtin functions of MLJ. The `train_test_pairs` function does basically the same as our `cross_validation_sets` function.\"\n\n# ╔═╡ 967a6e08-f0e6-45b7-988b-d0df237f3ddf\nMLJ.MLJBase.train_test_pairs(CV(nfolds = 10), 1:100)\n\n# ╔═╡ 535a11d9-833e-4237-949e-9a3e289c600b\nmd\"`MLJ` has the very useful function `evaluate!`. Have a look at the Live docs to learn more about this function. In the following you see an example where we perform 10-fold cross-validation on the `rmse` measure to estimate the expected test error for a polynomial regressor of degree 4.\"\n\n# ╔═╡ 8ae790b3-3987-4f41-8e21-adbb71081eb9\nevaluate!(machine(Polynomial(degree = 4) |> LinearRegressor(),\n\t              select(data1, :x), data1.y),\n          resampling = CV(nfolds = 10), measure = rmse)\n\n# ╔═╡ 134df37f-b737-4c80-a5f9-1149aeec970c\nmd\"We can use this now to find the best degree with 10-fold cross-validation for 100 different seeds. You will see that - even though not perfect - the hyper-parameters found with 10-fold cross-validation have lower variance and are usually closer to the true value than with the validation set approach.\"\n\n# ╔═╡ abb71af3-8aae-4806-9d5a-d144c15d22ef\nlosses_mlj_cv10 = [evaluate!(machine(Polynomial(; degree) |> LinearRegressor(),\n                                     select(data1, :x), data1.y),\n                             resampling = CV(nfolds = 10, shuffle = true),\n                             measure = rmse,\n                             verbosity = 0).measurement[]\n                   for degree in 1:10, seed in 1:20]\n\n# ╔═╡ 6599d2b4-68f4-4c22-8e40-bf3722597692\nlet validlosses  = losses_mlj_cv10, i = argmin(validlosses, dims = 1)\n    plot(validlosses, label = nothing, ylims = (0.5, 2))\n    scatter!((x -> x[1]).(i), validlosses[i], label = nothing,\n             xlabel = \"degree\", ylabel = \"validation loss\")\nend\n\n# ╔═╡ fc07009a-eeac-4c6b-9559-1e99ae68a6c3\nmd\"MLJ implements the following resampling strategies. With `Holdout` we use the validation set approach.\"\n\n# ╔═╡ 42511b31-6d70-495e-8362-01a29143b96e\nsubtypes(ResamplingStrategy)\n\n# ╔═╡ 29683c99-6a6a-4f65-bea2-d592895d887e\nmd\"# Model Tuning\n\nFinding good hyper-parameters (tuning) is such an important step in the process of finding good machine learning models that there exist some nice utility functions to tune the hyper-parameters ([tuning section in the MLJ manual](https://alan-turing-institute.github.io/MLJ.jl/dev/tuning_models/)). In the cell below you see an example where the degree of polynomial regression is automatically tuned on a given dataset by performing 10-fold cross-validation on all degrees on a \\\"grid\\\", i.e. of all degrees from 1 to 17 are tested.\"\n\n# ╔═╡ f93f20db-4fed-481f-b085-ca744b68fa8f\nbegin\n    model = Polynomial() |> LinearRegressor()\n    data2 = data_generator(seed = 2, n = 100)\n    self_tuning_model = TunedModel(model = model,\n                                   resampling = CV(nfolds = 10),\n                                   tuning = Grid(),\n                                   range = range(model, :(polynomial.degree),\n                                                 values = 1:17),\n                                   measure = rmse)\n    self_tuning_mach = machine(self_tuning_model, select(data2, :x), data2.y)\n\tfit!(self_tuning_mach, verbosity = 0)\nend\n\n# ╔═╡ d72609a1-f93f-4ca6-8759-727662233e97\nmd\"The self-tuned model actually found the true degree 3 for this data set, as we can see from the report of the tuned machine. The estimated test error can also be found in the report under `best_history_entry.measurement`.\"\n\n# ╔═╡ 59245b3e-ddfc-46c4-ba44-86ce191672ae\nreport(self_tuning_mach)\n\n# ╔═╡ f8b48f50-09cb-498a-89d1-9ac9b5722d0c\nmd\"The result of the tuned machine looks quite good here: the reducible error (average distance between red and green curve) looks small.\"\n\n# ╔═╡ 47a2c14b-a02d-43d7-ac8a-4d95a0d91fa8\nlet x = -3:.1:3\n    scatter(data2.x, data2.y, label = \"data\", legend = :bottomleft)\n    plot!(f, label = \"generator\", w = 2, xlims = (-3, 3))\n    plot!(x, predict(self_tuning_mach, DataFrame(x = x)), label = \"self tuning fit\", w = 2)\nend\n\n\n# ╔═╡ cf3841ba-3963-4716-8fc9-8cce1dc4a5fa\nmd\"# Nested Cross-Validation\n\nIf we want to tune the hyper-parameters with cross-validation and care about the estimated test error of the model found with cross-validation, we can use nested cross-validation, where hyper-parameters are optimized with cross-validation for each fold of the outer cross-validation. This happens when we `evaluate!` with cross-validation a self-tuning machine that itself uses cross-validation for hyper-parameter tuning. If we used `resampling = Holdout(fraction_train = 0.5)` we would use the validation set approach to estimate the test error with 50% of the data in the training set. If we used `resampling = Holdout(fraction_train = 0.5)` in the self-tuning machine, we would use the validation set approach for tuning the hyper-parameters.\n\"\n\n# ╔═╡ 3e9c6f1c-4cb6-48d8-8119-07a4b03c2e4b\nnested_cv = evaluate!(machine(self_tuning_model, select(data1, :x), data1.y),\n                      resampling = CV(nfolds = 5), measure = rmse)\n\n# ╔═╡ eba90af0-bf67-48f8-8d3c-f831b4fc289a\nmd\"Have a look at the best models found for each fold:\"\n\n# ╔═╡ c8d26ab6-86ec-4b37-9540-0f785fd8cdc2\nnested_cv.report_per_fold\n\n# ╔═╡ ee89c448-1e69-4fd1-a4b8-7297a09f2685\nmd\"# Exercises\n\n## Conceptual\n1. We review k-fold cross-validation.\n    - Explain how k-fold cross-validation is implemented.\n    - What are the advantages and disadvantages of k-fold cross-validation relative to:\n        - The validation set approach?\n        - LOOCV?\n3. You are given a model with unknown hyper-parameters and the goal is to find the optimal hyper-parameters and estimate the test error of the optimal model. Suppose of colleague of yours argues that this should be done in the following way: \\\"Take all the data and run cross-validation to find the best hyper-parameters. Taking all data is better, than taking only a subset, because one has more data to estimate the parameters and estimate the test error on the validation sets. Once the best hyper-parameters are found: estimate the test error by running again cross-validation on all the data with the hyper-parameter fixed to the best value.\\\" Do you agree with your colleague? If not, explain where you disagree and where you agree.\n2. Suppose you receive the following email of a colleague of yours. Write an answer to this email.\n```\n    Hi\n\n    In my internship I am doing this research project with a company that\n    manufactures constituents for medical devices. We need to assure high\n    quality and detect the pieces that are not fully functional. To do so we\n    perform 23 measurements on each piece. My goal is to find a machine\n    learning method that detects defective pieces automatically. Both, my\n    training set and my test set consist of 4000 pieces that were fine and\n    30 defective ones.  I ran logistic regression on that data and found a\n    training error of 0.1% and a test error of 0.3%, which is already pretty\n    good, I think, no? But with kNN classification it is even better. For\n    k = 7 I found a test error of 0.05% which is by far lower than all test\n    errors I obtained with other values of k. I was really impressed. Now\n    we have a method that predicts with 99.95% accuracy whether a piece is\n    defective or not!\n\n    Because you are taking this machine learning class now, I wanted to ask you\n    for advice. Does it all make sense to you what I described? If not, do you\n    have any suggestion to get even better results?\n\n    Ã bientôt\n    Jamie\n```\n\n\n\n## Applied\n1. Take the `classification_data` in our notebook on\n   \\\"flexibility and bias-variance-decomposition notebook\\\" and find with 10-fold\n   cross-validation the optimal number ``k`` of neighbors of kNN\n   classification, using the AUC measure. Hint: `MLJ` has the builtin function `auc`.\n   Plot the validation AUC for ``k = 1, \\ldots, 50``.\n3. With the same data as in the previous exercise, use the `MLJ` function `estimate!` and a self tuning machine to estimate with the validation set approach the test error of kNN classifier whose hyper-parameter is tuned with 5 fold cross-validation. Use one quarter of the data for the test set.\n2. In this exercise you apply our \\\"recipe for supervised learning\\\" (see slides). The goal is to predict the miles a car can drive per gallon fuel (mpg) as a function of its horsepower. You can download a dataset with `using OpenML; cars = DataFrame(OpenML.load(455))`. In the cleaning step we will remove all rows that contain missing values (you can use the function `dropmissing`). We select the machine learning methods polynomial regression and k nearest neighbors regression and we take as measure the `rmse`. Make sure to go trough the steps 2, 5, 9 of the recipe. Plot the predictions of the best method you found.\n\"\n\n# 1. Perform k-nearest neighbors regression on data generated with our `data_generator`\n#    defined in the first cell of this notebook and find the optimal number k of neighbors\n#    with k-fold cross validation.\n\n\n# ╔═╡ 0651292e-3f4e-4263-8235-4caa563403ec\nMLCourse.footer()\n\n# ╔═╡ Cell order:\n# ╠═736856ce-f490-11eb-3349-057c86edfe7e\n# ╟─7eb6a060-f948-4d85-881a-4909e74c15bd\n# ╠═7dd7e9a7-9245-4c64-af0c-8f7d2f62b2bf\n# ╟─5049407c-bf93-41a5-97bd-863a69d7016a\n# ╠═46827e21-0eea-4ec9-83ed-05e41dda1502\n# ╟─6cfc32b3-40c0-4149-ba67-2ec67b3938f3\n# ╠═1320b9b0-d6fc-4e61-8d62-de3988b8b21d\n# ╠═5dc21667-d94f-4c2a-b217-80b9a2262d8c\n# ╟─1fe3f6d1-6336-417e-885e-de3fc5821bdf\n# ╟─b79fae90-87f3-4f89-933b-d82e76c94d81\n# ╟─7d30f043-2915-4bba-aad5-cb7dbe76a3e5\n# ╠═ffffa3d0-bffb-4ff8-9966-c3312f952ac5\n# ╠═2e02ac0d-c4d0-47ba-be57-445adeb6ab8b\n# ╟─91eecd2b-af18-4a63-9684-28950e604d1a\n# ╟─b45b32b1-8a65-4823-b3bb-f0b7cc57604b\n# ╠═23e91f72-0124-48d4-8b53-bd5da67b7ac7\n# ╟─4461d5b0-bc9b-4c89-aa76-70524a5caa7c\n# ╠═ac3c7e84-6c47-4dc1-b862-de4cfb05dad9\n# ╟─26362233-b006-423d-8fb5-7cd9150405b4\n# ╟─5cff19c7-3426-4d91-b555-f059f5f41886\n# ╠═df16313f-76be-4d8b-88e7-7cc618ff49d4\n# ╟─46bffe01-1a7c-405b-b3ec-bfe7570b8a3c\n# ╠═b3aed705-5072-4d9b-bb8f-865ac1561bf6\n# ╠═6916273a-d116-4173-acaa-2bcac1d1753b\n# ╠═c14c9e49-a993-456e-9115-97da86f8e498\n# ╟─4b435518-2f12-4921-bb1f-fdd049ddfaed\n# ╠═1e584a38-2fef-4877-87f6-92237d71c4b3\n# ╟─a7c88b3f-92cb-4253-a889-c78683722c1d\n# ╟─0b81c3d5-277a-4fe6-889b-550e2f83c39d\n# ╟─5747d116-1e61-45f0-a87b-89372c6f270f\n# ╠═8204d9da-855d-4c66-b4dd-2c18a17b539b\n# ╟─96b3c070-0c72-44c7-ac98-ff6cb7e82380\n# ╠═bae635b1-6eba-4ba4-80e9-547770612843\n# ╟─d9b04582-3a7a-4e19-a0da-d363810883f7\n# ╠═9042e811-9a34-42b8-8069-877f3b3f1e75\n# ╟─e2658128-4053-4484-8e1e-229eceb755ab\n# ╟─eaacf529-1727-4743-941b-360c53088b1d\n# ╠═967a6e08-f0e6-45b7-988b-d0df237f3ddf\n# ╟─535a11d9-833e-4237-949e-9a3e289c600b\n# ╠═8ae790b3-3987-4f41-8e21-adbb71081eb9\n# ╟─134df37f-b737-4c80-a5f9-1149aeec970c\n# ╠═abb71af3-8aae-4806-9d5a-d144c15d22ef\n# ╟─6599d2b4-68f4-4c22-8e40-bf3722597692\n# ╟─fc07009a-eeac-4c6b-9559-1e99ae68a6c3\n# ╠═42511b31-6d70-495e-8362-01a29143b96e\n# ╟─29683c99-6a6a-4f65-bea2-d592895d887e\n# ╠═f93f20db-4fed-481f-b085-ca744b68fa8f\n# ╟─d72609a1-f93f-4ca6-8759-727662233e97\n# ╠═59245b3e-ddfc-46c4-ba44-86ce191672ae\n# ╟─f8b48f50-09cb-498a-89d1-9ac9b5722d0c\n# ╟─47a2c14b-a02d-43d7-ac8a-4d95a0d91fa8\n# ╟─cf3841ba-3963-4716-8fc9-8cce1dc4a5fa\n# ╠═3e9c6f1c-4cb6-48d8-8119-07a4b03c2e4b\n# ╟─eba90af0-bf67-48f8-8d3c-f831b4fc289a\n# ╠═c8d26ab6-86ec-4b37-9540-0f785fd8cdc2\n# ╟─ee89c448-1e69-4fd1-a4b8-7297a09f2685\n# ╟─c693088f-7f80-4cdd-b9b5-65a50da732ac\n# ╟─e1077092-f72a-42af-b6e0-a616f938cba8\n# ╟─0651292e-3f4e-4263-8235-4caa563403ec\n", "meta": {"hexsha": "1f6820d1b2e98e19b3a58faaf06073b8178f479d", "size": 22152, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/model_evaluation.jl", "max_stars_repo_name": "baltisberger/MLCourse", "max_stars_repo_head_hexsha": "9a2efad0f3d241503ad2fbce4f2d875d4332045b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/model_evaluation.jl", "max_issues_repo_name": "baltisberger/MLCourse", "max_issues_repo_head_hexsha": "9a2efad0f3d241503ad2fbce4f2d875d4332045b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/model_evaluation.jl", "max_forks_repo_name": "baltisberger/MLCourse", "max_forks_repo_head_hexsha": "9a2efad0f3d241503ad2fbce4f2d875d4332045b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.6387096774, "max_line_length": 746, "alphanum_fraction": 0.7039544962, "num_tokens": 7681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656671, "lm_q2_score": 0.8856314632529871, "lm_q1q2_score": 0.7630053356211806}}
{"text": "macro myevalpoly(z,a...)\n    isempty(a) && error(\"You forgot to pass coefficients!\")\n    ex = :($(a[length(a)]))\n    for i in 1:length(a)-1\n       ex = :($ex * $(z) + $(a[length(a)-i]) )\n    end\n    println(ex)\n    ex\nend\n\n@myevalpoly 7 2 3 4 5\n@evalpoly 7 2 3 4 5\n\n##\nfunction root2coeff(z::AbstractVector{T}) where T\n    N = length(z)\n    co = zeros(T, N+1)\n    # The last coefficient is always one\n    co[end] = 1\n    # The outer loop adds one root at a time\n    for j in 1:N, i in j:-1:1\n        co[end-i] -= z[j]*co[end-i+1]\n    end\n    co\nend\n@show typemax(Int), typemax(Int128)\nroot2coeff(1:20)\nroot2coeff(Int128(1):20)\n\n##\nusing LinearAlgebra\nfunction poly_roots(z)\n    len = length(z)\n    # construct the ones part\n    mat = diagm(-1 => ones(len-2))\n    # insert coefficients\n    mat[:, end] = -z[1:end-1]\n    eigvals(mat)\nend\n\n## Calculate all the roots and plot it\nusing Random\nRandom.seed!(2020)\nfunction wilkinson_poly_roots(n=100)\n    # original coefficients\n    coeff = root2coeff(Int128(1):20)\n    rts = Vector{Complex{Float64}}[]\n    # add perturbation\n    for i in 1:n\n        pert_coeff = coeff.*(1 .+ rand(21)*1e-6)\n        push!(rts, poly_roots(pert_coeff))\n    end\n    rts\nend\nusing Plots; gr()\nfunction plt_wilkinson_roots(rts)\n    # plot roots without perturbation\n    plt = scatter(1:20, zeros(20), color = :green, markersize = 5, legend = false, grid = false, aspect_ratio = 1)\n    for i in eachindex(rts)\n        # plot roots with perturbation\n        scatter!(plt, real.(rts[i]), imag.(rts[i]), color = :red, mscolor = :red, markersize = 2, shape = :star)\n    end\n    plt\nend\nwilkinson_poly_roots(100) |> plt_wilkinson_roots\n", "meta": {"hexsha": "fec125a72905283fe2616928e95b86dcc211e263", "size": 1653, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Wilkinson_Polynomial.jl", "max_stars_repo_name": "haotian127/JuliaStudies.jl", "max_stars_repo_head_hexsha": "7eaa63ba762d6b978112b789f6114667ffd300b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Wilkinson_Polynomial.jl", "max_issues_repo_name": "haotian127/JuliaStudies.jl", "max_issues_repo_head_hexsha": "7eaa63ba762d6b978112b789f6114667ffd300b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Wilkinson_Polynomial.jl", "max_forks_repo_name": "haotian127/JuliaStudies.jl", "max_forks_repo_head_hexsha": "7eaa63ba762d6b978112b789f6114667ffd300b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0454545455, "max_line_length": 114, "alphanum_fraction": 0.6206896552, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073575, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7629973210559639}}
{"text": "# ## Getting started\n\nusing MLJ, RDatasets, Random\nMLJ.color_off() # hide\n\ndata = dataset(\"datasets\", \"USArrests\")\nnames(data)\n\n# Let's have a look at the mean and standard deviation of each feature:\n\ndescribe(data, :mean, :std)\n\n# Let's extract the numerical component and coerce\n\nX = select(data, Not(:State))\nX = coerce(X, :UrbanPop=>Continuous);\n\n# ## PCA pipeline\n#\n# PCA is usually best done after standardization but we won't do it here:\n\n@load PCA pkg=MultivariateStats\n\npca_mdl = PCA(pratio=1)\npca = machine(pca_mdl, X)\nfit!(pca)\n\nW = transform(pca, X);\n\n# W is the PCA'd data; here we've used default settings for PCA and it has recovered 2 components:\n\nschema(W).names\n\n# Let's inspect the fit:\n\nr = report(pca)\ncumsum(r.principalvars ./ r.tvar)\n\n# In the second line we look at the explained variance with 1 then 2 PCA features and it seems that with 2 we almost completely recover all of the variance.\n\n# ## More interesting data...\n\n# Instead of just playing with toy data, let's load the orange juice data and extract only the columns corresponding to price data:\n\ndata = dataset(\"ISLR\", \"OJ\")\n\nX = select(data, [:PriceCH, :PriceMM, :DiscCH, :DiscMM, :SalePriceMM,\n                  :SalePriceCH, :PriceDiff, :PctDiscMM, :PctDiscCH]);\n\n# ### PCA pipeline\n\nRandom.seed!(1515)\n\n@pipeline SPCA(std = Standardizer(),\n               pca = PCA(pratio=1-1e-4))\nspca_mdl = SPCA()\nspca = machine(spca_mdl, X)\nfit!(spca)\nW = transform(spca, X)\nnames(W)\n\n# What kind of variance can we explain?\n\nr  = report(spca).reports[1]\ncs = cumsum(r.principalvars ./ r.tvar)\n\n# Let's visualise this\n\nusing PyPlot\n\nfigure(figsize=(8,6))\n\nbar(1:length(cs), cs)\nplot(1:length(cs), cs, color=\"red\", marker=\"o\")\n\nxlabel(\"Number of PCA features\", fontsize=14)\nylabel(\"Ratio of explained variance\", fontsize=14)\n\nsavefig(joinpath(@OUTPUT, \"ISL-lab-10-g1.svg\")) # hide\n\n# \\figalt{PCA explained variance}{ISL-lab-10-g1.svg}\n\n# So 4 PCA features are enough to recover most of the variance.\n\n# ### Clustering\n\nRandom.seed!(1515)\n\n@load KMeans pkg=Clustering\n@pipeline SPCA2(std = Standardizer(),\n                pca = PCA(),\n                km = KMeans(k=3))\n\nspca2_mdl = SPCA2()\nspca2 = machine(spca2_mdl, X)\nfit!(spca2)\n\nassignments = report(spca2).reports[1].assignments\nmask1 = assignments .== 1\nmask2 = assignments .== 2\nmask3 = assignments .== 3;\n\n# Now we can  try visualising this\n\nusing PyPlot\n\nfigure(figsize=(8, 6))\nfor (m, c) in zip((mask1, mask2, mask3), (\"red\", \"green\", \"blue\"))\n    plot(W[m, 1], W[m, 2], ls=\"none\", marker=\".\", markersize=10, color=c)\nend\n\nxlabel(\"PCA-1\", fontsize=13)\nylabel(\"PCA-2\", fontsize=13)\nlegend([\"Group 1\", \"Group 2\", \"Group 3\"], fontsize=13)\n\nsavefig(joinpath(@OUTPUT, \"ISL-lab-10-cluster.svg\")) # hide\n\n# \\fig{ISL-lab-10-cluster.svg}\nPyPlot.close_figs() # hide\n", "meta": {"hexsha": "f406933b7c2ec1f785c2d838c65bf42851c0d998", "size": 2788, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "_literate/ISL-lab-10.jl", "max_stars_repo_name": "ven-k/MLJTutorials", "max_stars_repo_head_hexsha": "42151c8a96ad701aeaf763d53c8b7c6689eb6e8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_literate/ISL-lab-10.jl", "max_issues_repo_name": "ven-k/MLJTutorials", "max_issues_repo_head_hexsha": "42151c8a96ad701aeaf763d53c8b7c6689eb6e8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_literate/ISL-lab-10.jl", "max_forks_repo_name": "ven-k/MLJTutorials", "max_forks_repo_head_hexsha": "42151c8a96ad701aeaf763d53c8b7c6689eb6e8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2333333333, "max_line_length": 156, "alphanum_fraction": 0.681133429, "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7629973194896059}}
{"text": "#\n# Estimate-pi.jl\n#\nsumsq(x,y) = x*x + y*y;\n\nN=1000000; \nx = 0;\nfor i = 1:N\n  if sumsq(rand(), rand()) < 1.0\n    x += 1\n  end\nend\n@printf \"Estimate of PI for %d trials is %8.5f\\n\" N 4.0*(x / N);\n\n", "meta": {"hexsha": "30c05c55a41a0570efa821a7c3361d9b0eb2310c", "size": 197, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Module 3/Chapter01/estimate-pi.jl", "max_stars_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_stars_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2017-02-12T15:36:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T03:30:39.000Z", "max_issues_repo_path": "Module 3/Chapter01/estimate-pi.jl", "max_issues_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_issues_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Module 3/Chapter01/estimate-pi.jl", "max_forks_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_forks_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-02-10T16:19:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T11:46:44.000Z", "avg_line_length": 13.1333333333, "max_line_length": 64, "alphanum_fraction": 0.5228426396, "num_tokens": 94, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.762997311945204}}
{"text": "export TFTS, TAAFT\n\n\"\"\"\n    TFTS(fϵ::Real)\n\nA truncated Fourier transform surrogate[^Nakamura2006] (TFTS).\n\nTFTS surrogates are generated by leaving some frequencies untouched when performing the\nphase shuffling step (as opposed to randomizing all frequencies, like for\n[`RandomFourier`](@ref) surrogates).\n\nThese surrogates were designed to deal with data with irregular fluctuations superimposed\nover long term trends (by preserving low frequencies)[^Nakamura2006]. Hence, TFTS surrogates\ncan be used to test the null hypothesis that the signal is a stationary linear system\ngenerated the irregular fluctuations part of the signal[^Nakamura2006].\n\n## Controlling the truncation of the spectrum\n\nThe truncation parameter `fϵ ∈ [-1, 0) ∪ (0, 1]` controls which parts of the spectrum are preserved.\n\n- If `fϵ > 0`, then `fϵ` indicates the ratio of high frequency domain to the entire frequency domain.\n    For example, `fϵ = 0.5` preserves 50% of the frequency domain (randomizing the higher\n    frequencies, leaving low frequencies intact).\n- If `fϵ < 0`, then `fϵ` indicates ratio of low frequency domain to the entire frequency domain.\n    For example, `fϵ = -0.2` preserves 20% of the frequency domain (leaving higher frequencies intact,\n    randomizing the lower frequencies).\n- If `fϵ ± 1`, then all frequencies are randomized. The method is then equivalent to\n    [`RandomFourier`](@ref).\n\nThe appropriate value of `fϵ` strongly depends on the data and time series length, and must be\nmanually determined[^Nakamura2006], for example by comparing periodograms for the time series and\nthe surrogates.\n\n[^Nakamura2006]: Nakamura, Tomomichi, Michael Small, and Yoshito Hirata. \"Testing for nonlinearity in irregular fluctuations with long-term trends.\" Physical Review E 74.2 (2006): 026205.\n\"\"\"\nstruct TFTS <: Surrogate\n    fϵ::Real\n\n    function TFTS(fϵ::Real)\n        if !(0 < fϵ ≤ 1) && !(-1 ≤ fϵ < 0)\n            throw(ArgumentError(\"`fϵ` must be on the interval [-1, 0) ∪ (0, 1] (positive if preserving high frequencies, negative if preserving low frequencies)\"))\n        end\n        new(fϵ)\n    end\nend\n\nfunction surrogenerator(x, method::TFTS, rng = Random.default_rng())\n    # Pre-plan Fourier transforms\n    forward = plan_rfft(x)\n    inverse = plan_irfft(forward*x, length(x))\n\n    # Pre-compute 𝓕\n    𝓕 = forward * x\n\n    # Polar coordinate representation of the Fourier transform\n    rx = abs.(𝓕)\n    ϕx = angle.(𝓕)\n    n = length(𝓕)\n\n    # These are updated during iteration procedure\n    𝓕new = Vector{Complex{Float64}}(undef, length(𝓕))\n    𝓕s = Vector{Complex{Float64}}(undef, length(𝓕))\n    ϕs = Vector{Complex{Float64}}(undef, length(𝓕))\n\n    init = (forward = forward, inverse = inverse,\n        rx = rx, ϕx = ϕx, n = n,\n        𝓕new = 𝓕new, 𝓕s = 𝓕s, ϕs = ϕs)\n\n    return SurrogateGenerator(method, x, similar(x), init, rng)\nend\n\nfunction (sg::SurrogateGenerator{<:TFTS})()\n    x, s = sg.x, sg.s\n    fϵ = sg.method.fϵ\n    L = length(x)\n\n    init_fields = (:forward, :inverse,\n        :rx, :ϕx, :n,\n        :𝓕new, :𝓕s, :ϕs)\n\n    forward, inverse,\n        rx, ϕx, n,\n        𝓕new, 𝓕s, ϕs = getfield.(Ref(sg.init), init_fields)\n\n    # Surrogate starts out as a random permutation of x\n    s .= x[StatsBase.sample(sg.rng, 1:L, L; replace = false)]\n    𝓕s .= forward * s\n    ϕs .= angle.(𝓕s)\n\n    # Updated spectrum is the old amplitudes with the mixed phases.\n    if fϵ > 0\n        # Frequencies are ordered from lowest when taking the Fourier\n        # transform, so by keeping the 1:n_ni first phases intact,\n        # we are only randomizing the high-frequency components of the\n        # signal.\n        n_preserve = ceil(Int, abs(fϵ * n))\n        ϕs[1:n_preserve] .= ϕx[1:n_preserve]\n    elseif fϵ < 0\n        # Do the exact opposite to preserve high-frequencies\n        n_preserve = ceil(Int, abs(fϵ * n))\n        ϕs[end-n_preserve+1:end] .= ϕx[end-n_preserve+1:end]\n    end\n\n    𝓕new .= rx .* exp.(ϕs .* 1im)\n    s .= inverse * 𝓕new\n    \n    return s\nend\n\n\"\"\"\n    TAAFT(fϵ)\n\nAn truncated version of the amplitude-adjusted-fourier-transform surrogate[^Theiler1991][^Nakamura2006].\n\nThe truncation parameter and phase randomization procedure is identical to [`TFTS`](@ref), but here an\nadditional step of rescaling back to the original data is performed. This preserves the\namplitude distribution of the original data.\n\n[^Theiler1991]: J. Theiler, S. Eubank, A. Longtin, B. Galdrikian, J. Farmer, Testing for nonlinearity in time series: The method of surrogate data, Physica D 58 (1–4) (1992) 77–94.\n[^Nakamura2006]: Nakamura, Tomomichi, Michael Small, and Yoshito Hirata. \"Testing for nonlinearity in irregular fluctuations with long-term trends.\" Physical Review E 74.2 (2006): 026205.\n\"\"\"\nstruct TAAFT <: Surrogate\n    fϵ::Real\n\n    function TAAFT(fϵ::Real)\n        fϵ != 0 || throw(ArgumentError(\"`fϵ` must be on the interval [-1, 0) ∪ (0, 1] (positive if preserving high frequencies, negative if preserving low frequencies)\"))\n        new(fϵ)\n    end\nend\n\nfunction surrogenerator(x, method::TAAFT, rng = Random.default_rng())\n    init = (\n        gen = surrogenerator(x, TFTS(method.fϵ), rng),\n        x_sorted = sort(x),\n        idxs = collect(1:length(x)),\n        perm = zeros(Int, length(x)),\n    )\n    \n    s = similar(x)\n    return SurrogateGenerator(method, x, s, init, rng)\nend\n\nfunction (taaft::SurrogateGenerator{<:TAAFT})()\n    sg = taaft.init.gen\n    x_sorted, idxs, perm = taaft.init.x_sorted, taaft.init.idxs, taaft.init.perm\n    \n    x, s = sg.x, sg.s\n    fϵ = sg.method.fϵ\n    L = length(x)\n\n    init_fields = (:forward, :inverse,\n        :rx, :ϕx, :n,\n        :𝓕new, :𝓕s, :ϕs)\n\n    forward, inverse,\n        rx, ϕx, n,\n        𝓕new, 𝓕s, ϕs = getfield.(Ref(sg.init), init_fields)\n\n    # Surrogate starts out as a random permutation of x\n    StatsBase.sample!(sg.rng, idxs, perm, replace = false)\n    permuted_x_into_s!(s, x, perm)\n    𝓕s .= forward * s\n    ϕs .= angle.(𝓕s)\n\n    # Updated spectrum is the old amplitudes with the mixed phases.\n    if fϵ > 0\n        # Frequencies are ordered from lowest when taking the Fourier\n        # transform, so by keeping the 1:n_ni first phases intact,\n        # we are only randomizing the high-frequency components of the\n        # signal.\n        n_preserve = ceil(Int, abs(fϵ * n))\n        ϕs[1:n_preserve] .= @view ϕx[1:n_preserve]\n    elseif fϵ < 0\n        # Do the exact opposite to preserve high-frequencies\n        n_preserve = ceil(Int, abs(fϵ * n))\n        ϕs[end-n_preserve+1:end] .= @view ϕx[end-n_preserve+1:end]\n    end\n\n    𝓕new .= rx .* exp.(ϕs .* 1im)\n    s .= inverse * 𝓕new\n    \n    s[sortperm(s)] .= x_sorted\n    return s\nend\n\n\nfunction permuted_x_into_s!(s, x, perm) \n    k = 1\n    for i in perm\n        s[k] = x[i]\n        k += 1\n    end\nend", "meta": {"hexsha": "dc8f0678e03cadfb6b2548a2d7353a28bd669b77", "size": 6750, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/methods/truncated_fourier.jl", "max_stars_repo_name": "kahaaga/TimeseriesSurrogates.jl", "max_stars_repo_head_hexsha": "d96f32cc4501b3e2b4a07c54af23b75a1e6d6033", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-09-08T02:48:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-22T20:40:48.000Z", "max_issues_repo_path": "src/methods/truncated_fourier.jl", "max_issues_repo_name": "kahaaga/TimeseriesSurrogates.jl", "max_issues_repo_head_hexsha": "d96f32cc4501b3e2b4a07c54af23b75a1e6d6033", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2018-05-15T14:44:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-06T13:11:31.000Z", "max_forks_repo_path": "src/methods/truncated_fourier.jl", "max_forks_repo_name": "kahaaga/TimeseriesSurrogates.jl", "max_forks_repo_head_hexsha": "d96f32cc4501b3e2b4a07c54af23b75a1e6d6033", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-12-23T10:00:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:03:07.000Z", "avg_line_length": 34.9740932642, "max_line_length": 187, "alphanum_fraction": 0.6608888889, "num_tokens": 2077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7629729842829975}}
{"text": "#=\n\n    Seguir tutorial de instalação do Julia demonstrado no README.md\n    Como rodar esse script: $ julia bhaskara.jl\n\n    Objetivo desse script: realizar uma operação básica de bhaskara.\n    Referência: https://brasilescola.uol.com.br/matematica/formula-bhaskara.htm\n\n=#\n\n#= \n    Declaração de variáveis a, b e c respectivamente\n    Como visto, variáveis no Julia não são tipadas como em algumas linguagens,\n    ou seja, você pode declará-las e o inicializador delas assumirá o valor\n    que você colocar como atribuição.\n    Ex.: Em a = 1 (a será um inteiro) / Em a = 'Olá' (a será uma string)\n=# \na = 1\nb = 0\nc = -16\n\n#   Definindo uma variável chamada 'delta' que assumirá o papel de\n#   uma função onde algo será executado e o resultado será armazenado\ndelta = function (a, b, c)\n    return b * b - 4 * a * c\nend\n\n#   Definindo uma variável chamada 'raiz1' que assumirá o papel de\n#   uma função onde algo será executado e o resultado será armazenado\nraiz1 = function (a, b, c)\n    return (-b + Base.Math.sqrt(delta(a, b, c))) / 2 * a;\nend\n\n#   Definindo uma variável chamada 'raiz2' que assumirá o papel de\n#   uma função onde algo será executado e o resultado será armazenado\nraiz2 = function (a, b, c) \n    return (-b - Base.Math.sqrt(delta(a, b, c))) / 2 * a;\nend\n\n#   Printando resultado das funções atribuídos a variável respectiva.\n#   Comentário para demonstrar o valor que deve ser apresentado.\n#   Seria interessante colocar um assert.equals para ficar mais nítida a compreensão.\n\nprintln(delta(a, b, c)) # Deve imprimir: 64\nprintln(raiz1(a, b, c)) # Deve imprimir: 4\nprintln(raiz2(a, b, c)) # Deve imprimir: -4\n            ", "meta": {"hexsha": "ec54b881ff7c8c9609b9ec1b7f97448267c3852a", "size": 1641, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "bhaskara.jl", "max_stars_repo_name": "hudsonr2018/julia-intro", "max_stars_repo_head_hexsha": "9bf9da9678b66ca8526fb8130299ca304894e38c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bhaskara.jl", "max_issues_repo_name": "hudsonr2018/julia-intro", "max_issues_repo_head_hexsha": "9bf9da9678b66ca8526fb8130299ca304894e38c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bhaskara.jl", "max_forks_repo_name": "hudsonr2018/julia-intro", "max_forks_repo_head_hexsha": "9bf9da9678b66ca8526fb8130299ca304894e38c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.914893617, "max_line_length": 85, "alphanum_fraction": 0.6977452773, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7629729721748696}}
{"text": "# Utility functions for space data analysis.\n\nusing ImageFiltering, OffsetArrays, FFTW, Statistics, LinearAlgebra\n\nexport mag2db, sma, spectrum\n\n\"Convert `x` from magnitude to decibels.\"\nmag2db(x) = 10. * log10.(x)\n\n\"\"\"\n    sma(x, n=(5,5))\n\nSimple moving average of `x` with `n[1]` leading and `n[2]` trailing points.\nDefault boundary is \"replicate\", meaning that the border pixels extend beyond\nthe boundaries.\n\"\"\"\nfunction sma(x, n::Tuple{Int,Int}=(5,5))\n   len = sum(n) + 1\n   kernel = OffsetArray(fill(1/len, len), -n[1]:n[2])\n   imfilter(x, kernel)\nend\n\n\"\"\"\n    sma(x, n=5)\n\nSimple moving box average of the vector data `x` with box length 'n'.\nOne-sided average on the left and right edge with replicate border.\n\"\"\"\nfunction sma(x::Vector, n::Int=5)\n   iseven(n) && @warn \"Even box length detected!\"\n   sma(x, ((n-1)÷2, (n-1)÷2))\nend\n\n\"\"\"\n    spectrum(x, Fs)\n\nReturn the frequency and amplitude for the single-sided spectrum of vector `x`\ngiven sample frequency of `Fs`.\n\"\"\"\nfunction spectrum(x::Vector, Fs)\n   L = length(x)\n   x̃ = fft(x)\n   # Compute the two-sided spectrum amplitude P2.\n   P₂ = @. abs(x̃/L)\n   # Compute the single-sided spectrum amplitude P1.\n   P₁ = P₂[1:floor(Int, L/2+1)]\n   P₁[2:end-1] .= 2 .* P₁[2:end-1]\n\n   f = Fs * (0:(L/2)) / L\n\n   f, P₁\nend", "meta": {"hexsha": "c2e27692283ef878435774d1eb843d2e53ea80ff", "size": 1277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utility.jl", "max_stars_repo_name": "henry2004y/VisAnaJulia", "max_stars_repo_head_hexsha": "cbf608847f66321f3fa8665f12a8850f7bd01408", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-07-29T18:10:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T07:29:39.000Z", "max_issues_repo_path": "src/utility.jl", "max_issues_repo_name": "henry2004y/VisAnaJulia", "max_issues_repo_head_hexsha": "cbf608847f66321f3fa8665f12a8850f7bd01408", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-10-07T16:08:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-08T20:18:32.000Z", "max_forks_repo_path": "src/utility.jl", "max_forks_repo_name": "henry2004y/VisAnaJulia", "max_forks_repo_head_hexsha": "cbf608847f66321f3fa8665f12a8850f7bd01408", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-04T10:31:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T10:31:52.000Z", "avg_line_length": 24.5576923077, "max_line_length": 78, "alphanum_fraction": 0.6507439311, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192066862062, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7629729686718524}}
{"text": "function haversine(p1, p2; R=6371.0)\n    lon1, lat1 = p1\n    lon2, lat2 = p2\n    φ1 = lat1 * π/180.0\n    φ2 = lat2 * π/180.0\n    Δφ = (lat2-lat1) * π/180.0\n    Δλ = (lon2-lon1) * π/180.0\n    a = sin(Δφ/2.0)^2.0 + cos(φ1)*cos(φ2) * sin(Δλ)^2.0\n    c = 2.0 * atan(sqrt(a), sqrt(1.0-a))\n    return R*c\nend\n\n\"\"\"\n    slidingwindow(L::LT, f::FT, d::IT) where {LT <: SimpleSDMLayer, FT <: Function, IT <: Number}\n\nThis function will replace the value at any cell by applying the function `f` to\nthe array of cells values that are within a distance `d` (in kilometers) from\nthe focal cell. This is, for example, useful to use an average to smooth out the\nlayers. The distance is estimated using the haversine distance, assuming that\nthe radius of the Earth is 6371.0 km. This means that the size of the window\nwill vary a little bit across latitudes, but this is far better than using a\nnumber of cells, which would have dramatic consequences near the poles.\n\nIt *always* returns a `SimpleSDMResponse`, and the cells containing `nothing`\nwill also not contain a value in the output. This is *different* from the\nbehavior of `coarsen`, which tends to expand the area of the layer in which we\nhave data.\n\nThis function is currently relatively slow. Performance improvements will arrive\nat some point.\n\"\"\"\nfunction slidingwindow(layer::LT, f::FT, d::IT) where {LT <: SimpleSDMLayer, FT <: Function, IT <: Number}\n    return_type = typeof(f(collect(layer)[1:min(3, length(layer))]))\n    newgrid = convert(Matrix{Union{Nothing,return_type}}, fill(nothing, size(layer)))\n    N = SimpleSDMResponse(newgrid, layer)\n    pixels = []\n    for lat in latitudes(layer)\n        for lon in longitudes(layer)\n            if !isnothing(layer[lon,lat])\n                push!(pixels, (lon, lat) => layer[lon,lat])\n            end\n        end\n    end\n\n    for p1 in pixels\n        ok = filter(p2 -> haversine(p2.first, p1.first) < 100.0, pixels)\n        val = [p2.second for p2 in ok]\n        N[p1.first...] = f(val)\n    end\n\n    #internal_types = unique(typeof.(N.grid))\n    #N.grid = convert(Matrix{Union{internal_types...}}, N.grid)\n    N = typeof(layer) <: SimpleSDMPredictor ? convert(SimpleSDMPredictor, N) : N\n\n    return N\nend\n", "meta": {"hexsha": "53df145866c3c8cf7263d020d4d5070a376825a0", "size": 2206, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operations/sliding.jl", "max_stars_repo_name": "gottacatchenall/SimpleSDMLayers.jl", "max_stars_repo_head_hexsha": "7c3316ca92e543104fadb3228873f74cd2c77121", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/operations/sliding.jl", "max_issues_repo_name": "gottacatchenall/SimpleSDMLayers.jl", "max_issues_repo_head_hexsha": "7c3316ca92e543104fadb3228873f74cd2c77121", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/operations/sliding.jl", "max_forks_repo_name": "gottacatchenall/SimpleSDMLayers.jl", "max_forks_repo_head_hexsha": "7c3316ca92e543104fadb3228873f74cd2c77121", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.701754386, "max_line_length": 106, "alphanum_fraction": 0.6650045331, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768635777511, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7629583672522608}}
{"text": "\"\"\"\n    F = JopErf(spc)\n\nwhere `F` is the error function operator with domain and range given by `spc::JetSpace`.\nwe use 'erf'(z) = 2/√π ∫_{0}^{z} \\exp{-t^2}dt,\nthe derivative of which is 2/√π  \\exp{-z^2}.\nWe expect the domain and range to be real.\n\"\"\"\nJopErf(spc::JetSpace) = JopNl(dom = spc, rng = spc, f! = JopErf_f!, df! = JopErf_df!)\nexport JopErf\n\n# TODO: assert denominator in linearization is > 0\n\nJopErf_f!(d::AbstractArray{T}, m::AbstractArray{T}) where {T<:Real} = d .= erf.(m)\nJopErf_df!(δd::AbstractArray{T}, δm::AbstractArray{T}; mₒ) where {T<:Real} = δd .= (2/sqrt( π )) .* exp.(-mₒ.^2) .* δm", "meta": {"hexsha": "07cbf48fa6fa8e996fe9d0fb30f6cb66daa37e34", "size": 607, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/jop_erf.jl", "max_stars_repo_name": "ChevronETC/JetPack.jl", "max_stars_repo_head_hexsha": "7b18a65344155dee4422958f54d045db354aaf6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-02T16:23:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-02T16:23:43.000Z", "max_issues_repo_path": "src/jop_erf.jl", "max_issues_repo_name": "ChevronETC/JetPack.jl", "max_issues_repo_head_hexsha": "7b18a65344155dee4422958f54d045db354aaf6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-10-08T15:13:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T02:56:17.000Z", "max_forks_repo_path": "src/jop_erf.jl", "max_forks_repo_name": "ChevronETC/JetPack.jl", "max_forks_repo_head_hexsha": "7b18a65344155dee4422958f54d045db354aaf6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4666666667, "max_line_length": 118, "alphanum_fraction": 0.6392092257, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176852582231, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7629583649133731}}
{"text": "\"\"\"\n    clebsch_gordan_condon_shortley(j₁, m₁, j₂, m₂, j₃, m₃=m₁+m₂)\n\nCalculate the vector coupling coefficient `⟨j₁ m₁, j₂ m₂|j₃ m₃⟩`\naccording to the Condon–Shortley phase convention and using the\ndefinition of Eq. (8.1.12) in Varshalovich (1988).\n\"\"\"\nclebsch_gordan_condon_shortley(j₁, m₁, j₂, m₂, j₃, m₃=m₁+m₂) =\n    powneg1(Int(j₁ - j₂ + m₃))*∏(j₃)*wigner3j(j₁, j₂, j₃,\n                                              m₁, m₂, -m₃)\n\nexport clebsch_gordan_condon_shortley\n", "meta": {"hexsha": "4f7588a9da74e68fed8a42ff6383db22e028bf1d", "size": 473, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/clebsch_gordan.jl", "max_stars_repo_name": "JuliaAtoms/AngularMomentumAlgebra.jl", "max_stars_repo_head_hexsha": "96ca4eb7f0c402452e546db46b95425abb61ada3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-01-09T19:02:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T18:11:05.000Z", "max_issues_repo_path": "src/clebsch_gordan.jl", "max_issues_repo_name": "jagot/AngularMomentumAlgebra.jl", "max_issues_repo_head_hexsha": "1aaba417aff0d91ae30e0c863b4e723476fd309a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-02-09T21:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-04T08:15:15.000Z", "max_forks_repo_path": "src/clebsch_gordan.jl", "max_forks_repo_name": "JuliaAtoms/AngularMomentumAlgebra.jl", "max_forks_repo_head_hexsha": "96ca4eb7f0c402452e546db46b95425abb61ada3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3846153846, "max_line_length": 64, "alphanum_fraction": 0.644820296, "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7629583634443527}}
{"text": "using Distributions, Turing, Plots, StatsPlots, MCMCChains, DataFrames\n\nfunction BiExponential(theta1::Real, theta2::Real, p::Real)\n    return MixtureModel(Exponential[\n                             Exponential(theta1),\n                             Exponential(theta2),\n                            ], [p, 1 - p])\nend\n\nfunction generate_samples(theta1::Real, theta2::Real, p::Real, n::Int64)\n    m = BiExponential(theta1, theta2, p)\n    rand(m, n)\nend\n\n@model bi_exponential(samples::Array{Real, 1}) = begin\n    theta1 ~ Gamma(1, 10)\n    theta2 ~ truncated(Normal(), theta1, Inf)\n    p ~ Beta(1, 1)\n    m = BiExponential(theta1, theta2, p)\n    for i in 1:length(samples)\n        samples[i] ~ m\n    end\nend\n\nfunction svf(x::Array{Real, 1}, digits::Int64)\n    x = round.(x, digits=digits)\n    unqx = unique(x) |> sort\n    counts = map(x_ -> sum(x .== x_), unqx)\n    DataFrame(x = unqx, count = counts, svr = 1. .- cumsum(counts ./ sum(counts)))\nend\n\nfunction predict(chains::Chains, x::Array{Real, 1})\n    theta1 = mean(chains[\"theta1\"])\n    theta2 = mean(chains[\"theta2\"])\n    p = mean(chains[\"p\"])\n    becdf = cdf(BiExponential(theta1, theta2, p), x)\n    return 1. .- becdf\nend\n\nsamples = Array{Real, 1}(generate_samples(0.1, 5, 0.9, 2000))\nchains = sample(bi_exponential(samples), NUTS(), MCMCThreads(), 1000, 4)\n\nsvf_samples = svf(samples, 2)\npred_samples = predict(chains, Array{Real, 1}(svf_samples.x))\nscatter(svf_samples.x, log10.(svf_samples.svr), markersize=2)\nplot!(svf_samples.x, log10.(pred_samples))\nylims!(-3, 0)\n", "meta": {"hexsha": "0b926be1d34779999d978875c29193f0df784343", "size": 1524, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "playground/turexas/biexp.jl", "max_stars_repo_name": "7cm-diameter/playground", "max_stars_repo_head_hexsha": "784ad5c34b7eb015bc055ec25b959ee0c20cadae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-25T11:03:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T11:03:51.000Z", "max_issues_repo_path": "playground/turexas/biexp.jl", "max_issues_repo_name": "7cm-diameter/playground", "max_issues_repo_head_hexsha": "784ad5c34b7eb015bc055ec25b959ee0c20cadae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "playground/turexas/biexp.jl", "max_forks_repo_name": "7cm-diameter/playground", "max_forks_repo_head_hexsha": "784ad5c34b7eb015bc055ec25b959ee0c20cadae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.75, "max_line_length": 82, "alphanum_fraction": 0.6279527559, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7628765298160098}}
{"text": "Store(α, rmax, Mmax) = Store(α, rmax, Mmax, Mmax)\n\nfunction Store(α::T, rmax::Integer, Mmax::Integer, ppImax::Integer\n              ) where T <: AbstractFloat\n    if Mmax < rmax\n        throw(ArgumentError(\"Mmax must be at least as big as rmax\"))\n    end\n    if Mmax > ppImax\n        throw(ArgumentError(\"ppImax must be at least as big as Mmax\"))\n    end\n    unitlegendre = Vector{Matrix{T}}(undef, Mmax)\n    legendre = Vector{Matrix{T}}(undef, Mmax)\n    jacobi1 = Vector{Matrix{T}}(undef, Mmax)\n    jacobi2 = Vector{Matrix{T}}(undef, Mmax)\n    jacobi3 = Vector{Matrix{T}}(undef, Mmax)\n    jacobi4 = Vector{Matrix{T}}(undef, Mmax)\n    jacobi5 = Vector{Matrix{T}}(undef, Mmax)\n    for M = 1:Mmax\n        unitlegendre[M] = Array{T}(undef, M, 2)\n        legendre[M] = Array{T}(undef, M, 2)\n        x, w = GaussQuadrature.legendre(T, M)\n        legendre[M][:,1], legendre[M][:,2] = x, w\n        unitlegendre[M][:,1] = ( x .+ 1 ) / 2\n        unitlegendre[M][:,2] = w / 2\n        jacobi1[M] = Array{T}(undef, M, 2)\n        jacobi1[M][:,1], jacobi1[M][:,2] = GaussQuadrature.jacobi(M, α-1, \n                                                                  zero(T))\n        jacobi2[M] = Array{T}(undef, M, 2)\n        jacobi2[M][:,1], jacobi2[M][:,2] = GaussQuadrature.jacobi(M, zero(T), \n                                                                  α-1)\n        jacobi3[M] = Array{T}(undef, M, 2)\n        jacobi3[M][:,1], jacobi3[M][:,2] = GaussQuadrature.jacobi(M, α, zero(T))\n        jacobi4[M] = Array{T}(undef, M, 2)\n        jacobi4[M][:,1], jacobi4[M][:,2] = GaussQuadrature.jacobi(M, zero(T), α)\n        jacobi5[M] = Array{T}(undef, M, 2)\n        jacobi5[M][:,1], jacobi5[M][:,2] = GaussQuadrature.jacobi(M, one(T), \n                                                                  α-1)\n    end\n    Ψ  = Array{T}(undef, rmax, ppImax)\n    dΨ = Array{T}(undef, rmax, Mmax)\n    A = Vector{T}(undef, rmax)\n    B = Vector{T}(undef, rmax)\n    C = Array{T}(undef, rmax, rmax)\n    return Store(α, rmax, Mmax, unitlegendre, legendre, \n                 jacobi1, jacobi2, jacobi3, jacobi4, jacobi5,\n                 ppImax, Ψ, dΨ, A, B, C)\nend\n\nfunction rule(storerule::Matrix{T}) where T <: AbstractFloat\n    return storerule[:,1], storerule[:,2]\nend\n\nfunction rules(storerules::Vector{Matrix{T}}) where T <: AbstractFloat\n    M = length(storerules)\n    pt = Vector{Vector{T}}(undef, M)\n    wt = Vector{Vector{T}}(undef, M)\n    for m = 1:M\n        pt[m] = view(storerules[m], :, 1)\n        wt[m] = view(storerules[m], :, 2)\n    end\n    return pt, wt\nend\n", "meta": {"hexsha": "d2aa3ddf69372168dfc16084f360fa8e63f9cff7", "size": 2549, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/parts/store.jl", "max_stars_repo_name": "billmclean/FractionalTimeDG.jl", "max_stars_repo_head_hexsha": "165bd96ac1355befaed4dff25172cc255e883768", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/parts/store.jl", "max_issues_repo_name": "billmclean/FractionalTimeDG.jl", "max_issues_repo_head_hexsha": "165bd96ac1355befaed4dff25172cc255e883768", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/parts/store.jl", "max_forks_repo_name": "billmclean/FractionalTimeDG.jl", "max_forks_repo_head_hexsha": "165bd96ac1355befaed4dff25172cc255e883768", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4603174603, "max_line_length": 80, "alphanum_fraction": 0.5288348372, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7628765275865603}}
{"text": "## Packages\nusing NLsolve\nusing Plots\nusing Parameters\n\n## Files\ninclude(\"Tauchen.jl\")\ninclude(\"NewtonRoot.jl\")\n\n## Parameters\nModel = @with_kw (θ = 0.35, # capital share\n    δ = 0.0464, # depreciation rate\n    γ_z = 0.016, # growth rate of productivity\n    γ_n = 0.015, # growth rate of population\n    β = 0.9722, # discount rate\n    β_hat = β*(1+γ_n), # detrended discount rate\n    ψ = 2.24, # labor coefficient\n    ρ = 0.2,# autocorr of productivity process\n    σ = 0.5, # stand. dev. for productivity process\n    nz = 5, # number of states for productivity\n    μ_z = 0.0, # mean of productivity process\n    zGrid = exp.(Tauchen(μ_z,ρ,σ,nz)[1]), # grid for productivity process\n    P_z = Tauchen(μ_z,ρ,σ,nz)[2]) # transition matrix\n\n## Get the Steady-State level of capital from a Nonlinear solver\nfunction getSS(md)\n    @unpack θ,ψ,δ,β_hat,γ_n,γ_z = md\n\n    function ee!(eq,x)\n        k=(x[1])\n        h=(x[2])\n        eq[1]=β_hat*(θ*k^(θ-1)*h^(1-θ)+1-δ)-(1+γ_n)*(1+γ_z)\n        eq[2]=(-(ψ/(1-h)))+((1-θ)*(k^θ)*(h^(-θ)))/((k^θ)*(h^(1-θ))-(1+γ_n)*(1+γ_z)*k+(1-δ)*k)\n    end\n\n    S = nlsolve(ee!, [0.5,0.5],ftol = :1.0e-9, method = :trust_region , autoscale = true);\n    kss = S.zero[1];\n    hss = S.zero[2];\n    lss = 1-hss;\n    css = (kss^θ)*((exp(0)*hss)^(1-θ))-(1+γ_n)*(1+γ_z)*kss+(1-δ)*kss;\n\n    return kss,hss,lss,css\nend\n\n# Solve h from intratemporal equation over the grids\nfunction geth(md,nk,kGrid)\n\n    @unpack θ,ψ,γ_n,γ_z,δ,nz,zGrid = md\n    \n    h_star = zeros(nk,nk,nz);\n\n    for i = 1:nk\n        for j = 1:nk\n            for k = 1:nz\n                intra(h) = (ψ/(1-θ))*((kGrid[i]^θ)*((zGrid[k]*h)^(1-θ))-(1+γ_n)*(1+γ_z)*kGrid[j]+(1-δ)*kGrid[i])+((h-1)*(kGrid[i]^θ)*(zGrid[k]^(1-θ))*(h^(-θ)))\n                h = NewtonRoot(h -> intra(h),0.5)\n                if h > 1\n                    h_star[i,j,k] = 0.9999;\n                else\n                    h_star[i,j,k] = h;\n                end\n            end\n        end\n    end\n\n    return h_star\n\nend\n\n\n# Precalculate return value\nfunction getrt(md,nk,kGrid)\n\n    @unpack θ,ψ,γ_n,γ_z,δ,nz,zGrid = md\n\n    h_star = geth(md,nk,kGrid)\n    rt = zeros(nk,nk,nz);\n\n    for i = 1:nk\n        for j = 1:nk\n            for k = 1:nz\n                c = (kGrid[i]^θ)*((zGrid[k]*h_star[i,j,k])^(1-θ))-(1+γ_n)*(1+γ_z)*kGrid[j]+(1-δ)*kGrid[i];\n                if c <= 0\n                    rt[i,j,k] = -100.0;\n                else\n                    rt[i,j,k] = log(c)+ψ*log(1-h_star[i,j,k]);\n                end\n            end\n        end\n    end\n\n    return rt,h_star\n    \nend\n\n# Main loop\nfunction VFI(md,nk,kGrid)\n    @unpack θ,ψ,γ_n,γ_z,δ,nz,zGrid,β_hat,P_z = md\n    \n    #Preallocate memories\n    V_old = zeros(nk,nz);\n    V_new = zeros(nk,nz);\n    argmax = Array{Int64,2}(undef,nk,nz);\n\n    kpol = zeros(nk,nz);\n    hpol = zeros(nk,nz);\n    cpol = zeros(nk,nz);\n\n    maxDiff = 10.0; \n    tol = 1.0e-10; \n    iter = 0;\n\n    rt,h_star = getrt(md,nk,kGrid);\n\n    while maxDiff > tol\n        iter = iter+1;\n        println(\"Current iteration: $iter\")\n        \n        EV = V_old*P_z';\n        for i = 1:nk, k = 1:nz\n            V_new[i,k],argmax[i,k] = findmax(rt[i,:,k].+β_hat*EV[:,k]);\n        end\n        \n        maxDiff = maximum(abs.(V_new-V_old));\n        println(\"maxDiff = $maxDiff\")\n        V_old = copy(V_new); \n    end\n\n    for i = 1:nk,j = 1:nz\n        kpol[i,j] = kGrid[argmax[i,j]];\n        hpol[i,j] = h_star[i,argmax[i,j],j];\n        cpol[i,j] = (kGrid[i]^θ)*(zGrid[j]*hpol[i,j])^(1-θ)-(1+γ_n)*(1+γ_z)*kpol[i,j]+(1-δ)*kGrid[i];\n    end\n\n    return V_new,kpol,hpol,cpol\nend", "meta": {"hexsha": "376d48955278a0093b8443db492e996f2e0d1783", "size": 3548, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Ellen/HW1/VFI.jl", "max_stars_repo_name": "wongr003/ECON8185", "max_stars_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ellen/HW1/VFI.jl", "max_issues_repo_name": "wongr003/ECON8185", "max_issues_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ellen/HW1/VFI.jl", "max_forks_repo_name": "wongr003/ECON8185", "max_forks_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0882352941, "max_line_length": 159, "alphanum_fraction": 0.5098647125, "num_tokens": 1342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374122, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7628765198632743}}
{"text": "\nusing Plots\n\nΔ = .1\nN = 100\nτ = N*Δ/5\nran = 0.0:2pi/N:2pi\nfunction fillxs(Ts = 1,N = 100, ini=0.0, fin=100)\n    xs = []\n    Δ = fin/N\n    τ = N*Δ/5\n\n    for j in 1:Ts\n        for i in ini:Δ:τ-Δ\n            push!(xs,1)\n        end\n\n        for i in τ:Δ:fin\n            push!(xs,0)\n        end\n\n    end\n\n    return xs\nend\n\nfunction Xforward(x,n)\n    N = length(x)\n    j = im\n    b = 2pi/N\n    sum = 0.0\n    for k in 1:N\n        sum += x[k] * exp(-j * k * b * n)\n    end\n\n    return abs(1/N * sum)\nend\n\nxs = Int.(fillxs())\n\nys =  [Xforward(xs,i) for i in 0:1:N]\n\nscatter(xs, title = \"Train signal\")\nscatter(ys, title = \"DFT\")\n\nfunction xback(x,n)\n    N = length(x)\n    j = im\n    b = 2pi/N\n    sum = 0.0\n    for k in 1:N\n        sum += x[k] * exp(j * k * b * n)\n    end\n\n    return abs(sum)\nend\n\nys2 = [xback(xs,i) for i in 0:1:N]\n\nscatter(ys2, title = \"DFT back\")\n", "meta": {"hexsha": "e66df67dcb59261f015d223b878e9a356289930b", "size": 863, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "kskyten/StagedFilters.jl", "max_stars_repo_head_hexsha": "893b0b9f1c80ee3399962127619a864a95521627", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-23T02:59:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T02:59:52.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "kskyten/StagedFilters.jl", "max_issues_repo_head_hexsha": "893b0b9f1c80ee3399962127619a864a95521627", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-07-26T16:45:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-23T22:43:16.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "kskyten/StagedFilters.jl", "max_forks_repo_head_hexsha": "893b0b9f1c80ee3399962127619a864a95521627", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:05:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-23T09:02:17.000Z", "avg_line_length": 14.1475409836, "max_line_length": 49, "alphanum_fraction": 0.4762456547, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7628765168831853}}
{"text": "\nusing DiffEqBayes, CmdStan, DynamicHMC\n\n\nusing Distributions, BenchmarkTools\nusing OrdinaryDiffEq, RecursiveArrayTools, ParameterizedFunctions\nusing Plots\n\n\ngr(fmt=:png)\n\n\nf = @ode_def LotkaVolterraTest begin\n    dx = a*x - b*x*y\n    dy = -c*y + d*x*y\nend a b c d\n\n\nu0 = [1.0,1.0]\ntspan = (0.0,10.0)\np = [1.5,1.0,3.0,1,0]\n\n\nprob = ODEProblem(f,u0,tspan,p)\nsol = solve(prob,Tsit5())\n\n\nt = collect(range(1,stop=10,length=10))\nsig = 0.49\ndata = convert(Array, VectorOfArray([(sol(t[i]) + sig*randn(2)) for i in 1:length(t)]))\n\n\nscatter(t, data[1,:], lab=\"#prey (data)\")\nscatter!(t, data[2,:], lab=\"#predator (data)\")\nplot!(sol)\n\n\npriors = [Truncated(Normal(1.5,0.5),0.5,2.5),Truncated(Normal(1.2,0.5),0,2),Truncated(Normal(3.0,0.5),1,4),Truncated(Normal(1.0,0.5),0,2)]\n\n\n@btime bayesian_result_stan = stan_inference(prob,t,data,priors,num_samples=10_000,printsummary=false)\n\n\n@btime bayesian_result_turing = turing_inference(prob,Tsit5(),t,data,priors,num_samples=10_000)\n\n\n@btime bayesian_result_dynamichmc = dynamichmc_inference(prob,Tsit5(),t,data,priors,num_samples=10_000)\n\n\nusing DiffEqBenchmarks\nDiffEqBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])\n\n", "meta": {"hexsha": "49ff97d7e810118d94c5859849eb5be71ff58a9e", "size": 1171, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ParameterEstimation/DiffEqBayesLotkaVolterra.jl", "max_stars_repo_name": "ven-k/SciMLBenchmarks.jl", "max_stars_repo_head_hexsha": "3f54fb3f3412a332526543f7947583b7ec2ab347", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-23T11:26:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T11:46:34.000Z", "max_issues_repo_path": "script/ParameterEstimation/DiffEqBayesLotkaVolterra.jl", "max_issues_repo_name": "ven-k/SciMLBenchmarks.jl", "max_issues_repo_head_hexsha": "3f54fb3f3412a332526543f7947583b7ec2ab347", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-12T12:07:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-23T10:04:12.000Z", "max_forks_repo_path": "script/ParameterEstimation/DiffEqBayesLotkaVolterra.jl", "max_forks_repo_name": "ven-k/SciMLBenchmarks.jl", "max_forks_repo_head_hexsha": "3f54fb3f3412a332526543f7947583b7ec2ab347", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-12T00:28:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T00:28:16.000Z", "avg_line_length": 22.0943396226, "max_line_length": 138, "alphanum_fraction": 0.7139197267, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7628168707700976}}
{"text": "\n# coding: utf-8\n\n# In[1]:\n\n\n#fractal is one of the interesting topics in geometry\n#it is usually described by a recursive function\n#voila,here we are!\nusing Plots\n\n\n# In[2]:\n\n\n#define starting and ending points\n#and the order of hilbert curve\nn=4\nstarting_point=(0,0)\nending_point=(2^n-1,0)\n\n\n# In[3]:\n\n\n#the code for hilbert curve may look intimidating at the first glance\n#it is extremely simple and straight forward\n#julia version is slightly different\n#as we cannot use yield like python\n#coroutine in julia is too complicated\n#maybe another day...\nfunction hilbert_curve(coordinates,point1,point2,n)\n\n    #unpack\n    x_start,y_start=point1\n    x_end,y_end=point2    \n\n    #the function consists four different parts\n    #which are 4 different rotations plus flips of a second order hilbert curve\n    #0 degree second order hilbert curve\n    if x_start<x_end && y_start==y_end\n        \n        #compute the grid length\n        L=x_end-x_start\n        \n        #keypoints are starting and ending points\n        #of 4 different first order hilbert curves\n        #on a second order hilbert curve\n        keypoints=[(x_start,y_start),(x_start,y_start-(L-1)/2),\n        (x_start,y_start-(L-1)/2-1),(x_start+(L-1)/2,y_start-(L-1)/2-1),\n        (x_start+(L-1)/2+1,y_start-(L-1)/2-1),(x_start+L,y_start-(L-1)/2-1),\n        (x_start+L,y_start-(L-1)/2),(x_start+L,y_start)]\n        \n        #base case\n        if n==1\n            append!(coordinates,keypoints)\n        else\n            \n            #recursion\n            for i in 1:2:8\n                hilbert_curve(coordinates,\n                    keypoints[i],keypoints[i+1],n-1)\n            end\n        end\n    end\n\n    #180 degree second order hilbert curve\n    if x_start>x_end && y_start==y_end\n        L=x_start-x_end\n        keypoints=[(x_start,y_start),(x_start,y_start+(L-1)/2),\n        (x_start,y_start+(L-1)/2+1),(x_start-(L-1)/2,y_start+(L-1)/2+1),\n        (x_start-(L-1)/2-1,y_start+(L-1)/2+1),(x_start-L,y_start+(L-1)/2+1),\n        (x_start-L,y_start+(L-1)/2),(x_start-L,y_start)]\n        if n==1\n            append!(coordinates,keypoints)\n        else\n            for i in 1:2:8\n                hilbert_curve(coordinates,\n                    keypoints[i],keypoints[i+1],n-1)\n            end\n        end\n    end\n    \n    #clockwise 90 degree horizontal flipped second order hilbert curve\n    if x_start==x_end && y_start>y_end\n        L=y_start-y_end\n        keypoints=[(x_start,y_start),(x_start+(L-1)/2,y_start),\n        (x_start+(L-1)/2+1,y_start),(x_start+(L-1)/2+1,y_start-(L-1)/2),\n        (x_start+(L-1)/2+1,y_start-(L-1)/2-1),(x_start+(L-1)/2+1,y_start-L),\n        (x_start+(L-1)/2,y_start-L),(x_start,y_start-L)]\n        if n==1\n            append!(coordinates,keypoints)\n        else\n            for i in 1:2:8\n                hilbert_curve(coordinates,\n                    keypoints[i],keypoints[i+1],n-1)\n            end\n        end\n    end\n    \n    #clockwise 270 degree horizontal flipped second order hilbert curve\n    if x_start==x_end && y_start<y_end\n        L=y_end-y_start\n        keypoints=[(x_start,y_start),(x_start-(L-1)/2,y_start),\n        (x_start-(L-1)/2-1,y_start),(x_start-(L-1)/2-1,y_start+(L-1)/2),\n        (x_start-(L-1)/2-1,y_start+(L-1)/2+1),(x_start-(L-1)/2-1,y_start+L),\n        (x_start-(L-1)/2,y_start+L),(x_start,y_start+L)]\n        if n==1\n            append!(coordinates,keypoints)\n        else\n            for i in 1:2:8\n                hilbert_curve(coordinates,\n                    keypoints[i],keypoints[i+1],n-1)\n            end\n        end\n    end\n    coordinates\nend\n\n\n# In[4]:\n\n\n#get coordinates\ncoordinates=hilbert_curve([],\n    starting_point,ending_point,n);\n\n\n# In[5]:\n\n\n#viz\ngr(size=(250,250))\nfig=plot(legend=false,grid=false,axis=false,ticks=false)\nplot!([i[1] for i in coordinates],\n        [i[2] for i in coordinates])\nfig\n\n\n\n", "meta": {"hexsha": "d95a699bda2daedc4a05779bf1a932a26091ca0d", "size": 3846, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "hilbert curve.jl", "max_stars_repo_name": "je-suis-tm/recursion-and-dynamic-programming", "max_stars_repo_head_hexsha": "55a6085cd45b73426379ff947d9a842ef7d325bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-03-22T10:31:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:30:17.000Z", "max_issues_repo_path": "hilbert curve.jl", "max_issues_repo_name": "je-suis-tm/recursion-and-dynamic-programming", "max_issues_repo_head_hexsha": "55a6085cd45b73426379ff947d9a842ef7d325bb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hilbert curve.jl", "max_forks_repo_name": "je-suis-tm/recursion-and-dynamic-programming", "max_forks_repo_head_hexsha": "55a6085cd45b73426379ff947d9a842ef7d325bb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2019-10-27T12:34:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T13:54:37.000Z", "avg_line_length": 27.2765957447, "max_line_length": 79, "alphanum_fraction": 0.5891835673, "num_tokens": 1148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7628168647841489}}
{"text": "# Binary search for zero of continuous function f\n# with one zero-crossing in [lo, hi]\nfunction binary_search(f, lo, hi; ϵ = 1e-10, maxiter = 100)\n    if f(lo) > 0\n        @warn \"f($(lo))=$(f(lo)) should be negative at low end\";\n        return lo;\n    end\n    if f(hi) < 0\n        @warn \"f($(hi))=$(f(hi)) should be positive at high end\";\n        return hi;\n    end\n\n    # @assert f(lo) < +ϵ \"f($(lo))=$(f(lo)) should be negative at low end\";\n    # @assert f(hi) > -ϵ \"f($(hi))=$(f(hi)) should be positive at high end\";\n\n    for i in 1:maxiter\n        mid = (lo+hi)/2;\n        if mid == lo || mid == hi\n            # not going to get any better ...\n            #@warn \"binary_search collapsed after $i iterations.\\nf($(lo)) = $(f(lo))\\nf($(hi)) = $(f(hi))\";\n            return mid;\n        end\n        fmid = f(mid);\n        if fmid < -ϵ\n            lo = mid\n        elseif fmid > ϵ\n            hi = mid;\n        else\n            return mid;\n        end\n    end\n    @warn \"binary_search did not reach tolerance $ϵ in $maxiter iterations.\\nf($(lo)) = $(f(lo))\\nf($(hi)) = $(f(hi)),\\nmid would be $((lo+hi)/2)\";\n    return (lo+hi)/2;\nend\n", "meta": {"hexsha": "3ef23ef8905e94f835e5a4f71b090a3c8142b185", "size": 1136, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "binary_search.jl", "max_stars_repo_name": "xuedong/LinBAI.jl", "max_stars_repo_head_hexsha": "47da3f6f3adb2cd077ad8696fa72b70de5b7a31b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-21T10:46:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-21T10:46:50.000Z", "max_issues_repo_path": "binary_search.jl", "max_issues_repo_name": "xuedong/LinBAI.jl", "max_issues_repo_head_hexsha": "47da3f6f3adb2cd077ad8696fa72b70de5b7a31b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "binary_search.jl", "max_forks_repo_name": "xuedong/LinBAI.jl", "max_forks_repo_head_hexsha": "47da3f6f3adb2cd077ad8696fa72b70de5b7a31b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4571428571, "max_line_length": 147, "alphanum_fraction": 0.5017605634, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89330940889474, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7628082932658987}}
{"text": "\"\"\"\n    legendre_1term_raise_lm_accuracy.jl\n\nSimple tests to explore the numerical accuracy of the 1-term recurrence relation which\nboosts (m,m) -> (m+1,m+1) in the associated Legendre polynomials.\n\n## Tests\n\n- `recur0`: Baseline version which is a direct translation of the math.\n- `recur1`: Uses FMA instructions to compute (1-x^2). Eliminating intermediate rounding\n  is expected to increase the accuracy of the entire recursion.\n- `recur2`: Same as `recur1` but also iterates upward in degree/order in pairs. Stepping\n  from even to odd ``(m,m) -> (m+1,m+1)`` multiplies by ``y = \\\\sqrt{1-x^2}`` and the\n  coefficient ``μ_m``. The second half then steps from even to even\n  ``(m,m) -> (m+2,m+2)`` by multiplying by ``y^2 = 1-x^2`` (without taking the square\n  root) and the pair of coefficients ``μ_m`` and ``μ_{m+1}``.\n- `recur3`: Same as `recur2` but replaces the FMA calculation of ``1-x^2`` with the\n  product ``(1-x)(1+x)``.\n\n## Conclusions\n- Without FMA, the product ``(1-x)(1+x)`` is better for ``|x| ≈ 1`` than ``1 - x^2``.\n- FMA is the best option for computing ``y = \\\\sqrt(1-x^2)`` and should be preferred.\n- The pair-wise iteration improves numerical accuracy as ``m \\\\to \\\\finty``.\n\"\"\"\n\nusing PyPlot, PyCall\n\nfunction recur0(x, nstep)\n    y = sqrt(one(x) - x^2)\n    vals = zeros(typeof(x), 2nstep)\n    z = inv(sqrt(4oftype(x, π)))\n    @inbounds for ii = 1:2nstep\n        μ = sqrt(one(x) + one(x)/2(ii+1))\n        z = -μ * y * z\n        vals[ii] = z\n    end\n    return vals\nend\n\nfunction recur1(x, nstep)\n    y = sqrt(-fma(x, x, -one(x)))\n    vals = zeros(typeof(x), 2nstep)\n    z = inv(sqrt(4oftype(x, π)))\n    @inbounds for ii = 1:2nstep\n        μ = sqrt(one(x) + one(x)/2(ii+1))\n        z = -μ * y * z\n        vals[ii] = z\n    end\n    return vals\nend\n\nfunction recur2(x, nstep)\n    y² = -fma(x, x, -one(x))\n    y¹ = sqrt(y²)\n    vals = zeros(typeof(x), 2nstep)\n    z = inv(sqrt(4oftype(x, π)))\n    @inbounds for ii = 1:2:2nstep\n        μ₁ = sqrt(one(x) + one(x)/2(ii+1))\n        μ₂ = sqrt(one(x) + one(x)/2(ii+2))\n        vals[ii] = -μ₁ * y¹ * z\n        z = μ₁ * μ₂ * y² * z\n        vals[ii+1] = z\n    end\n    return vals\nend\n\nfunction recur3(x, nstep)\n    y² = (one(x) - x) * (one(x) + x)\n    y¹ = sqrt(y²)\n    vals = zeros(typeof(x), 2nstep)\n    z = inv(sqrt(4oftype(x, π)))\n    @inbounds for ii = 1:2:2nstep\n        μ₁ = sqrt(one(x) + one(x)/2(ii+1))\n        μ₂ = sqrt(one(x) + one(x)/2(ii+2))\n        vals[ii] = -μ₁ * y¹ * z\n        z = μ₁ * μ₂ * y² * z\n        vals[ii+1] = z\n    end\n    return vals\nend\n\n# Half of the lmax/mmax to iterate to.\nnstep = 512\n# Range of arguments, taken more densely from x ≈ 1 where catastrophic cancellation is\n# expected without FMA.\nx₀ = 1 .- exp2.(range(-16, -eps(), length=2560))\n\n# Reference values calculated with extended precision.\nref = Float64.(reduce(hcat, setprecision(512) do\n    recur1.(big.(x₀), nstep)\nend))\n\nv0 = reduce(hcat, recur0.(x₀, nstep))\nv1 = reduce(hcat, recur1.(x₀, nstep))\nv2 = reduce(hcat, recur2.(x₀, nstep))\nv3 = reduce(hcat, recur3.(x₀, nstep))\n\ncolors = pyimport(\"matplotlib.colors\")\nfig, axs = subplots(2, 2, num = \"legendre_1term_raise_lm_accuracy\", clear = true)\nfunction plot_compare(ax, v; title=nothing, kws...)\n    lnorm = colors.LogNorm(vmin = 1, vmax=1e3)\n    ulps = abs.(v .- ref) ./ eps.(ref)\n    img = ax.pcolormesh(1 .- x₀, 1:2nstep, ulps,\n                    norm=lnorm;\n                    kws...)\n    ax.set_xscale(\"log\")\n    ax.set_xlabel(\"argument \\$(1-x)\\$\")\n    ax.set_ylabel(\"degree/order\")\n    cbar = ax.figure.colorbar(img, ax=ax)\n    cbar.set_label(\"ulps\");\n    title !== nothing && ax.set_title(title)\n    ax.text(0.05, 0.9, \"ulp max = $(round(maximum(ulps), digits=2))\", transform=ax.transAxes)\n    nothing\nend\nplot_compare(axs[1,1], v0, title=\"v0 — Baseline\")\nplot_compare(axs[1,2], v1, title=\"v1 — FMA \\$(1 - x^2)\\$\")\nplot_compare(axs[2,1], v2, title=\"v2 — FMA + pairwise iteration\")\nplot_compare(axs[2,2], v3, title=\"v3 — \\$(1-x)(1+x)\\$ + pairwise iteration\")\n\n", "meta": {"hexsha": "b3e32a11ef153a46f7ad3afd3b8aa0e858f9b5ef", "size": 3979, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/legendre_1term_raise_lm_accuracy.jl", "max_stars_repo_name": "jmert/LegendrePolynomials.jl", "max_stars_repo_head_hexsha": "b0df887a93570e176e8521faca3d8ea7a233d10b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-06-05T23:50:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T01:45:09.000Z", "max_issues_repo_path": "scripts/legendre_1term_raise_lm_accuracy.jl", "max_issues_repo_name": "jmert/Legendre.jl", "max_issues_repo_head_hexsha": "b0df887a93570e176e8521faca3d8ea7a233d10b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2020-04-26T18:17:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-15T15:48:24.000Z", "max_forks_repo_path": "scripts/legendre_1term_raise_lm_accuracy.jl", "max_forks_repo_name": "jmert/LegendrePolynomials.jl", "max_forks_repo_head_hexsha": "b0df887a93570e176e8521faca3d8ea7a233d10b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-24T01:01:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-24T01:01:38.000Z", "avg_line_length": 33.1583333333, "max_line_length": 93, "alphanum_fraction": 0.6009047499, "num_tokens": 1372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7628082894413379}}
{"text": "using Random\nusing LinearAlgebra\nusing Statistics\nusing Optim\nusing DataFrames\nusing CSV\nusing HTTP\nusing GLM\nusing FreqTables\nusing SMM\nusing DataFramesMeta\nusing Pipe,Distributions\n\n\nfunction wrapper()\nurl = \"https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2020/master/ProblemSets/PS1-julia-intro/nlsw88.csv\"\ndf = CSV.read(HTTP.get(url).body, DataFrame)\nX = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\ny = df.married.==1\n\n\n# 1)\nbols = inv(X'*X)*X'*y\nprintln(bols)\n\nfunction ols_gmm(beta, X, y)\n    g = y .- X*beta\n    # I defined in LinearAlgebra\n    J = g'*I*g\n    return J\nend\nα̂_optim = optimize(a -> ols_gmm(a, X, y), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-8, iterations=100_000))\nprintln(α̂_optim.minimizer)\n\n# the answers are very close\n# α̂_optim.minimizer.-bols |> println\n\n#2)\n#a) changed alpha_start to alpha_true to get the result quickly\ninclude(\"ps2question5.jl\")\n\n#b)\nalpha_true = [.1910213,-.0335262,.5963968,.4165052,-.1698368,-.0359784,1.30684,-.430997,.6894727,-.0104578,.5231634,-1.492475,\n            -2.26748,-.0053001,1.391402,-.9849661,-1.398468,-.0142969,-.0176531,-1.495123,.2454891,-.0067267,-.5382892,-3.78975]\n\nfunction gmm_logit(alpha, X, y)\n\n    K = size(X,2)\n    J = length(unique(y))\n    N = length(y)\n    bigY = zeros(N,J)\n    for j=1:J\n        bigY[:,j] = y.==j\n    end\n    bigAlpha = [reshape(alpha,K,J-1) zeros(K)]\n\n    num = zeros(N,J)\n    dem = zeros(N)\n    for j=1:J\n        num[:,j] = exp.(X*bigAlpha[:,j])\n        dem .+= num[:,j]\n    end\n\n    P = num./repeat(dem,1,J)\n\n    loglike = -sum( bigY.*log.(P) )\n    g = @pipe (bigY .- P) |> reshape(_,(J*N, 1))\n    J = g'*I*g\n    return J[1,1]\nend\n\nalpha_hat_optim = optimize(a -> gmm_logit(a, X, y), alpha_true, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\nalpha_hat_mle = alpha_hat_optim.minimizer\nprintln(alpha_hat_mle)\n\n#c)\nalpha_rand = rand(6*size(X,2))\n\nalpha_hat_optim = optimize(a -> gmm_logit(a, X, y), alpha_rand, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\nalpha_hat_mle = alpha_hat_optim.minimizer\nprintln(alpha_hat_mle)\n\n# I got different etimates which means that  the function isn't globally concave\n\n#4)\n\nN=size(X,1)\nK=size(X,2)\nJ = length(unique(y))\nXrand = rand(N,K)\nbeta = rand(J)\n# f)\n#https://github.com/JuliaStats/Distributions.jl/blob/master/src/univariate/continuous/gumbel.jl\nepsilon = rand(Gumbel(),N,J)\nYY = zeros(N)\nfor i in 1:N\nYY[i] = argmax(X[i]*beta[:] + epsilon[i,:])\nend\n\n# Q4\n\nMA = SMM.parallelNormal() # Note: this line may take up to 5 minutes to execute\ndc = SMM.history(MA.chains[1])\ndc = dc[dc[:accepted].==true, :]\nprintln(describe(dc))\n\n# Q5\nfunction ols_smm(θ, X, y, D)\n\tN=size(X,1)\n\tK=size(X,2)\n\tJ = length(unique(y))\n    β = θ[1:end-1]\n    σ = θ[end]\n    if length(β)==1\n        β = β[1]\n    end\n    bigY = zeros(N,J)\n\tfor j=1:J\n            bigY[:,j] = y.==j\n    end\n\tbigY2 = zeros(N,J)\n\n    # N+1 moments in both model and data\n    gmodel = zeros(N+1,D)\n    # data moments are just the y vector itself\n    # and the variance of the y vector\n    gdata  = vcat(y,var(y))\n    #### !!!!!!!!!!!!!!!!!!!!!!!!!!!!! ####\n    # This is critical!                   #\n    Random.seed!(1234)                    #\n    # You must always use the same ε draw #\n    # for every guess of θ!               #\n    #### !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ###\n    # simulated model moments\n    for d=1:D\n        ε = σ*randn(N)\n        ỹ = X*β .+ ε\n        gmodel[1:end-1,d] = ỹ\n        gmodel[  end  ,d] = var(ỹ)\n    end\n    # criterion function\n    err = vec(gdata .- mean(gmodel; dims=2))\n    # weighting matrix is the identity matrix\n    # minimize weighted difference between data and moments\n    J = err'*I*err\n    return J\nend\nreturn nothing\nend\nwrapper()\n", "meta": {"hexsha": "dd95349117f7e28a0ddf02afaea73de107c47541", "size": 3795, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS7-smm/PS7_Elfatmaoui.jl", "max_stars_repo_name": "aelfat/fall-2021", "max_stars_repo_head_hexsha": "0c0c0c08102b2f7e30c38e1ac510b313241f3f82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSets/PS7-smm/PS7_Elfatmaoui.jl", "max_issues_repo_name": "aelfat/fall-2021", "max_issues_repo_head_hexsha": "0c0c0c08102b2f7e30c38e1ac510b313241f3f82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS7-smm/PS7_Elfatmaoui.jl", "max_forks_repo_name": "aelfat/fall-2021", "max_forks_repo_head_hexsha": "0c0c0c08102b2f7e30c38e1ac510b313241f3f82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1324503311, "max_line_length": 153, "alphanum_fraction": 0.6163372859, "num_tokens": 1292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735663, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7628082876500941}}
{"text": "module NetworkBasedInference\n\t\n\tusing LinearAlgebra\n\t\n\texport NBI, \n\t\t\tNWNBI, \n\t\t\tSDTNBI\n\n\t\"\"\"\n\t\n\t\"\"\"\n\tfunction NBI(F₀::AbstractMatrix)\n\t\tM,N = size(F₀)\n\t\tR = diagm([ sum(F₀[i,:]) for i in 1:M ])\n\t\tH = diagm([ sum(F₀[:,j]) for j in 1:N ])\n\t\tW = (F₀ * H^-1)' * (R^-1 * F₀)\n\n\t\treturn W\n    end\n\n\tNBI(SymF₀::Symmetric, Nd::Int)::Matrix = NBI(SymF₀[1:Nd, Nd+1:end])\n\n\n\t\"\"\"\n\n\t\"\"\"\n\tfunction NWNBI(F₀::Matrix, β::AbstractFloat)::Matrix\n\t\tM,N = size(F₀)\n        R  = diagm([ sum(F₀[i,:])   for i in 1:M ])\n        H  = diagm([ sum(F₀[:,j])   for j in 1:N ])\n        H´ = diagm([ sum(F₀[:,j])^β for j in 1:N ])\n        W´ = (F₀ * H^-1)' * (R^-1 * F₀ * H´^-1)\n\n        return W´\n    end\n\n\tNWNBI(SymF₀::Symmetric, Nd::Int, β::AbstractFloat) = NWNBI(SymF₀[1:Nd, Nd+1:end], β)\n\n\t\"\"\"\n\n\t\"\"\"\n\tfunction SDTNBI(F₀::AbstractMatrix)::Matrix\n\t\tk(A, x) = count(r->(r != 0), A[x,:])\t# Degree helper function\n\t\tn_nodes = size(F₀, 1)\t\t\t\t\t# Number of nodes\t\n\t\tW\t    = zeros(n_nodes, n_nodes)\t\t# Transfer matrix\n\n\t\tfor idx in 1:n_nodes\n\t\t\tW[idx,:] = k(F₀, idx) > 0 ? F₀[idx,:] ./ k(F₀, idx) : zeros(n_nodes, 1)\n\t\tend\n\n\t\treturn W\n\tend\nend\n", "meta": {"hexsha": "2b886a69c728bcacfd6aa1c0054846343cd19aa7", "size": 1111, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NetworkBasedInference.jl", "max_stars_repo_name": "cvigilv/NetworkBasedInference.jl", "max_stars_repo_head_hexsha": "3d2d6dd26ac5a93817dec87217c299ed449762fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NetworkBasedInference.jl", "max_issues_repo_name": "cvigilv/NetworkBasedInference.jl", "max_issues_repo_head_hexsha": "3d2d6dd26ac5a93817dec87217c299ed449762fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NetworkBasedInference.jl", "max_forks_repo_name": "cvigilv/NetworkBasedInference.jl", "max_forks_repo_head_hexsha": "3d2d6dd26ac5a93817dec87217c299ed449762fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5740740741, "max_line_length": 85, "alphanum_fraction": 0.5310531053, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693731004241, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7627495646253378}}
{"text": "\nfunction constant_contractor(X, y_val)\n    x, y = X\n    y = y ∩ Interval(y_val)\n    return IntervalBox(x, y)\nend\n\n\n\"Contractor for y = x^2, x >= 0\"\nfunction square_pos(X::IntervalBox)\n\n    x, y = X\n\n    x = x ∩ (0..∞)\n\n    y = y ∩ (x^2)\n    x = x ∩ √y\n\n    return IntervalBox(x, y)\nend\n\nsquare_neg = symmetrise(square_pos, reflect_x(0.0))\nsquare!(X::IntervalBox) = square_pos(X) ∪ square_neg(X)\n\n\nfunction cube_pos(X::IntervalBox)  # contractor for y=x^3, x>=0\n\n    x, y = X\n\n    x = x ∩ (0..∞)\n\n    y = y ∩ (x ^ 3)\n    x = x ∩ Interval(y.lo ^ (1/3), y.hi^(1/3))   # not rigorous!\n\n    return x × y\nend\n\ncube_neg = symmetrise(cube_pos, odd)\ncube!(X::IntervalBox) = cube_pos(X) ∪ cube_neg(X)\n", "meta": {"hexsha": "378869431e6447f068038af46c6b5959dba5a561", "size": 692, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/powers.jl", "max_stars_repo_name": "kaarthiksundar/IntervalContractors.jl", "max_stars_repo_head_hexsha": "488b206aafc6e562655a0e395a0d6ca2217272ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-02-27T20:15:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T17:55:10.000Z", "max_issues_repo_path": "src/powers.jl", "max_issues_repo_name": "kaarthiksundar/IntervalContractors.jl", "max_issues_repo_head_hexsha": "488b206aafc6e562655a0e395a0d6ca2217272ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2017-05-03T14:08:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-04T20:43:33.000Z", "max_forks_repo_path": "src/powers.jl", "max_forks_repo_name": "kaarthiksundar/IntervalContractors.jl", "max_forks_repo_head_hexsha": "488b206aafc6e562655a0e395a0d6ca2217272ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-05-04T04:46:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T23:30:35.000Z", "avg_line_length": 17.3, "max_line_length": 64, "alphanum_fraction": 0.5751445087, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7627495421521499}}
{"text": "# https://github.com/SciML/GalacticOptim.jl/blob/master/test/rosenbrock.jl#L30\n\nusing GalacticOptim\nusing ForwardDiff\nusing Ipopt\n\nrosenbrock(x,p) =  (p[1] - x[1])^2 + p[2] * (x[2] - x[1]^2)^2\nx0 = zeros(2)\np  = Dict(1 => 1.0, 2=> 100.0)\n\nfunction con2_c(x,p)\n    [x[1]^2 + x[2]^2, x[2]*sin(x[1])-x[1]]\nend\n\noptprob = OptimizationFunction(rosenbrock, GalacticOptim.AutoForwardDiff(); cons=con2_c)\nprob = OptimizationProblem(optprob, x0, p, lcons=[-Inf,-Inf], ucons=[Inf,Inf])\n\nsol = solve(prob, Ipopt.Optimizer())\n\nprintln(sol.minimum)\nprintln(sol.u)\n", "meta": {"hexsha": "15d9b10d9b838cd7d2dfb95930cfd606d9da799f", "size": 551, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "debug/galacticoptim-mwe.jl", "max_stars_repo_name": "lanl-ansi/rosetta-opf", "max_stars_repo_head_hexsha": "09e76f505c04cc788256a4f3f479033ba6abe1f0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2022-03-25T19:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:42:04.000Z", "max_issues_repo_path": "debug/galacticoptim-mwe.jl", "max_issues_repo_name": "lanl-ansi/rosetta-opf", "max_issues_repo_head_hexsha": "09e76f505c04cc788256a4f3f479033ba6abe1f0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2022-03-28T01:10:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:44:10.000Z", "max_forks_repo_path": "debug/galacticoptim-mwe.jl", "max_forks_repo_name": "lanl-ansi/rosetta-opf", "max_forks_repo_head_hexsha": "09e76f505c04cc788256a4f3f479033ba6abe1f0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0454545455, "max_line_length": 88, "alphanum_fraction": 0.6733212341, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741281688026, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7627184926239268}}
{"text": "using jFEMTools\nimport Tensors: Vec,  ⋅\nusing SparseArrays\nimport WriteVTK\nconst jF = jFEMTools\n\n\n# We solve a simple 3D Poisson PDE with homogeneous Dirichlet boundary conditions\n# using ContinuousLagrange finite elements on a Hexahedral mesh\n\n# Problem: \n\n# Δu = f  in Ω\n# u  = 0  in ∂Ω\n\n# We start  generating a simple grid with 20x20 triangular elements\n# using `unitSquareMesh2`. The generator defaults to the unit square,\n# so we don't need to specify the corners of the domain.\nmesh = hyper_rectagle_mesh2(HexahedronCell,(10,10,10))\n\n# ### Initiate function Spaces\ndim = jF.getdim(mesh)\nP1 = ContinuousLagrange(:Hexahedron,1)\nWh = FEMFunctionSpace(mesh, P1, 1)\n\n# Declare variables\nu_h = TrialFunction(Wh)\n#v_h = TestFunction(Wh)\n\n# ### Degrees of freedom\n# Next we need to define a `DofHandler`, which will take care of numbering\n# and distribution of degrees of freedom for our approximated fields.\n# We create the `DofHandler` and then add a single field called `u_h`.\ndh = DofHandler(mesh,[u_h])\n\n# Now that we have distributed all our dofs we can create our tangent matrix,\n# using `create_sparsity_pattern`. This function returns a sparse matrix\n# with the correct elements stored.\nK = jF.create_sparsity_pattern(dh);\n\n# ### Boundary conditions\ndbc = Dirichlet(dh, u_h, \"boundary\", 0.0)\n\n# ### RHS function\nf(x::Vec{dim}) where {dim} = 2*π^2*sin(π*x[1])*sin(π*x[2])*sin(π*x[3])\n\n# ### Assembling the linear system\n# Now we have all the pieces needed to assemble the linear system, $K u = f$.\nfunction doassemble(Wh, K::SparseMatrixCSC, dh::jF.DofHandler)\n  # We allocate the element stiffness matrix and element force vector\n  # just once before looping over all the cells instead of allocating\n  # them every time in the loop.\n  n_basefuncs = jF.getnbasefunctions(Wh)\n  Ke = zeros(n_basefuncs, n_basefuncs)\n  fe = zeros(n_basefuncs)\n  b = zeros(jF.ndofs(dh))\n  cell_dofs = Vector{Int}(undef, jF.ndofs_per_cell(dh))\n\n  # Next we define the global force `f` and\n  # create an assembler. The assembler\n  # is just a thin wrapper around `f` and `K` and some extra storage\n  # to make the assembling faster.\n  assembler = jF.start_assemble(K, b)\n\n  # It is now time to loop over all the cells in our mesh\n  @inbounds for (cellcount, cell) in enumerate(CellIterator(mesh))\n      # Always remember to reset the function space local data\n      fill!(Ke, 0)\n      fill!(fe, 0)\n      jF.reinit!(Wh, cell)\n\n      # It is now time to loop over all the quadrature points in the cell and\n      # assemble the contribution to `Ke` and `fe`. The integration weight\n      # can be queried from `cellvalues` by `getdetJdV`.\n      for q_point in 1:jF.getnquadpoints(Wh)\n          dΩ = jF.getdetJdV(Wh, q_point)\n          fh = jF.function_value(f, Wh, cell, q_point)\n          # For each quadrature point we loop over all the (local) shape functions.\n          # We need the value and gradient of the testfunction `v` and also the gradient\n          # of the trial function `u`.\n          for i in 1:n_basefuncs\n              v  = jF.shape_value(Wh, q_point, i)\n              ∇v = jF.shape_gradient(Wh, q_point, i)\n              fe[i] += fh*v * dΩ\n              for j in 1:n_basefuncs\n                  ∇u = jF.shape_gradient(Wh, q_point, j)\n                  Ke[i, j] += (∇v ⋅ ∇u) * dΩ\n              end\n          end\n      end\n      # The last step in the element loop is to assemble `Ke` and `fe`\n      # into the global `K` and `f` with `assemble!`.\n      jF.celldofs!(cell_dofs, dh, cell)\n      jF.assemble!(assembler, cell_dofs, fe, Ke)\n  end\n  return K, b\nend\n\n# ### Solution of the system\n# The last step is to solve the system. First we call `doassemble`\n# to obtain the global stiffness matrix `K` and force vector `f`.\nK, b = doassemble(Wh, K, dh);\n\n# To account for the boundary conditions we use the `apply!` function.\n# This modifies elements in `K` and `f` respectively, such that\n# we can get the correct solution vector `u` by using `\\`.\napply!(K,b,dbc);\nu = K \\ b;\n\n# Plot approximation\nvi = jFEMTools.vertexdofs(dh, u_h);\nvtk_file = vtk_grid(\"poisson3D\", mesh)\nvtk_file[\"u\", WriteVTK.VTKPointData()] = u[vi]\noutfiles = WriteVTK.vtk_save(vtk_file)\n", "meta": {"hexsha": "0e565f1e16e5f06af31e14a14ec463d635c07e56", "size": 4160, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Poisson3DFEM.jl", "max_stars_repo_name": "Paulms/jFEMToools", "max_stars_repo_head_hexsha": "fab2579db69c3c5a3610a7aabc06ae0cbd627b2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-01-28T16:35:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T17:08:23.000Z", "max_issues_repo_path": "examples/Poisson3DFEM.jl", "max_issues_repo_name": "Paulms/jFEMToools", "max_issues_repo_head_hexsha": "fab2579db69c3c5a3610a7aabc06ae0cbd627b2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-11-28T17:27:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-28T17:27:48.000Z", "max_forks_repo_path": "examples/Poisson3DFEM.jl", "max_forks_repo_name": "Paulms/jFEMToools", "max_forks_repo_head_hexsha": "fab2579db69c3c5a3610a7aabc06ae0cbd627b2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-12-04T22:33:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T17:08:28.000Z", "avg_line_length": 36.1739130435, "max_line_length": 88, "alphanum_fraction": 0.6795673077, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574129515172, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7627184891715273}}
{"text": "using Distributions, Plots; pyplot()\n\nlambda, N = 1/3, 10^5\nbulbs = [1,10,50]\nxGrid = 0:0.1:10\nC = [:blue :red :green]\ndists = [Gamma(n,1/(n*lambda)) for n in bulbs]\n\nfunction normalizedData(d::Gamma)\n    sh = Int64(shape(d))\n    data = [sum(-(1/(sh*lambda))*log.(rand(sh))) for _ in 1:N]\nend\n\nL = [ \"Shape = \"*string.(shape.(i))*\", Scale = \"*\n    string.(round.(scale.(i),digits=2)) for i in dists ]\n\nstephist( normalizedData.(dists), bins=50, \n    normed=:true, c=C, xlims=(0,maximum(xGrid)),ylims=(0,1), \n    xlabel=\"x\", ylabel=\"Density\", label=\"\")\nplot!(xGrid, [pdf.(i,xGrid) for i in dists], c=C, label=reshape(L, 1,:))", "meta": {"hexsha": "0814ccb2a92d9954cf0f11f5eb7d5ce8c0868eff", "size": 624, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/gammaDist.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "3_chapter/gammaDist.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "3_chapter/gammaDist.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 31.2, "max_line_length": 72, "alphanum_fraction": 0.6073717949, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741227833249, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7627184883118178}}
{"text": "function dare(A, B, Q, R)\n    n = size(A, 1)\n    T = promote_type(eltype(A), eltype(B), eltype(Q), eltype(R))\n    \n    E = [\n        Matrix{T}(I, n, n)  B/R*B'\n        zeros(size(A))      A'\n    ]\n\n    F = [\n        A   zeros(size(A))\n        -Q  Matrix{T}(I, n, n)\n    ]\n    \n    QZ = schur(F, E)\n    QZ = ordschur(QZ, abs.(QZ.alpha./QZ.beta) .< 1)\n    \n    return QZ.Z[(n+1):end, 1:n]/QZ.Z[1:n, 1:n]\nend\n\nfunction care(A, B, Q, R)\n    G = B/R*B'\n\n    Z = [A   -G\n         -Q  -A']\n\n    S = schur(Z)\n    S = ordschur(S, real(S.values) .< 0)\n    U = S.Z\n\n    (m, n) = size(U)\n    U11 = U[1:div(m, 2), 1:div(n,2)]\n    U21 = U[div(m,2)+1:m, 1:div(n,2)]\n\n    return U21/U11\nend\n\nfunction lqr(A, B, Q, R)\n    P = care(A, B, Q, R)\n    K = R\\B'*P\n    return K\nend\n\nfunction dlqr(A, B, Q, R)\n    P = dare(A, B, Q, R)\n    K = (R + B'*P*B)\\B'*P*A\n    return K\nend\n\nfunction dlqr(A, B, Q, R, Δt)\n    Q = Q*Δt\n    R = R*Δt\n    A = A*Δt+I\n    B = B*Δt \n\n    P = dare(A, B, Q, R)\n    K = (R + B'*P*B)\\B'*P*A\n    return K\nend", "meta": {"hexsha": "f847af5066696b440b745d1053b2102088517355", "size": 1011, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/util/util.jl", "max_stars_repo_name": "DengYuelin/ConstrainedControl.jl", "max_stars_repo_head_hexsha": "b4214f8c5b9aaaf943ad451b40135046ea125225", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-12-11T01:06:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T09:15:05.000Z", "max_issues_repo_path": "src/util/util.jl", "max_issues_repo_name": "DengYuelin/ConstrainedControl.jl", "max_issues_repo_head_hexsha": "b4214f8c5b9aaaf943ad451b40135046ea125225", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-06-25T19:09:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T17:22:53.000Z", "max_forks_repo_path": "src/util/util.jl", "max_forks_repo_name": "DengYuelin/ConstrainedControl.jl", "max_forks_repo_head_hexsha": "b4214f8c5b9aaaf943ad451b40135046ea125225", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-11-04T12:33:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T08:17:49.000Z", "avg_line_length": 17.1355932203, "max_line_length": 64, "alphanum_fraction": 0.4263105836, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615412, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7627184811887009}}
{"text": "struct SimpleOG{TI <: Integer, T <: Real,\n                TR <: AbstractArray{T}, TQ <: AbstractArray{T}}\n    B :: TI\n    M :: TI\n    α :: T\n    β :: T\n    R :: TR\n    Q :: TQ\nend\n\nfunction SimpleOG{T <: Real}(;B::Integer=10, M::Integer=5, α::T=0.5, β::T=0.9)\n\n    u(c) = c^α\n    n = B + M + 1\n    m = M + 1\n\n    R = Matrix{T}(n, m)\n    Q = zeros(Float64,n,m,n)\n\n    for a in 0:M\n        Q[:, a + 1, (a:(a + B)) + 1] = 1 / (B + 1)\n        for s in 0:(B + M)\n            R[s + 1, a + 1] = a<=s ? u(s - a) : -Inf\n        end\n    end\n\n    return SimpleOG(B, M, α, β, R, Q)\nend\n", "meta": {"hexsha": "170aad6db48eb73dcb6cb25686fb152fe809de50", "size": 574, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "discrete_dp/finite_dp_og_example.jl", "max_stars_repo_name": "chenwang/QuantEcon.lectures.code", "max_stars_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2017-05-09T10:45:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:33:27.000Z", "max_issues_repo_path": "discrete_dp/finite_dp_og_example.jl", "max_issues_repo_name": "chenwang/QuantEcon.lectures.code", "max_issues_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2017-06-30T01:52:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-01T20:09:47.000Z", "max_forks_repo_path": "discrete_dp/finite_dp_og_example.jl", "max_forks_repo_name": "QuantEcon/QuantEcon.lectures.code", "max_forks_repo_head_hexsha": "d61ac7bc54529dd5c77470c17539eb2418b047c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 117, "max_forks_repo_forks_event_min_datetime": "2017-04-25T16:09:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T02:30:29.000Z", "avg_line_length": 19.7931034483, "max_line_length": 78, "alphanum_fraction": 0.4059233449, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741241296943, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7627184780637785}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Statistics, DataFrames, CSV\n\tusing Random, Distributions, Plots\n\tusing HypothesisTests\n\tRandom.seed!(0)\nend;\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.02\"\n\n# ╔═╡ 1aa41898-3afa-11eb-2f49-570853ce6435\nbegin\n\tdata = CSV.read(datadir(\"machine1.csv\"), DataFrame; header=false)[:,1]\n\txBar, n = mean(data), length(data)\n\ts = std(data)\n\talpha = 0.1\n\tt = quantile(TDist(n-1),1-alpha/2)\n\n\tText(\"Calculating formula: $((xBar - t*s/sqrt(n), xBar + t*s/sqrt(n)))\")\nend\n\n# ╔═╡ 88f0e5d6-3b0b-11eb-0af9-b964a1170ff3\nText(\"Using confint() function: $(confint(OneSampleTTest(xBar,s,n),alpha))\")\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.02\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═1aa41898-3afa-11eb-2f49-570853ce6435\n# ╠═88f0e5d6-3b0b-11eb-0af9-b964a1170ff3\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "a72bc2d305c88f682200d1a9d1dfa9fb5d969913", "size": 1180, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/06/listing6.02.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/06/listing6.02.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/06/listing6.02.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.652173913, "max_line_length": 76, "alphanum_fraction": 0.7245762712, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046026642945, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7626976409808461}}
{"text": "# An example of how the solution for the wave equation\n# using a gaussian initial condition converges\n\nusing ScalarWaveEquation\nusing PyPlot\n\nfunction get_gaussian(N::Int)\n\t# returns a normalized Gaussian distribution with (mean, std) = (0.5, 0.1)\n\tmean = 0.5\n\tstd  = 0.1\n\t\n\txdata      = range(0.0, stop = 1.0, length = N)\n\texponent   = -0.5 * (xdata.-mean) .* (xdata.-mean) / (std*std)\n\tnorm_coeff = std*sqrt(2*pi)\n\t\n\treturn exp.(exponent)/norm_coeff\nend\n\nfunction get_gaussian_solution(Nx::Int, Nt::Int, Ttot::T) where {T}\n\t# returns a FunArr2D instance for the solution to the gaussian\n\t# initial condition, performed at difference resolutions\n\t\n\t# initial conditions are accepted in the form of FunArr instances\n\t# the x-range is assumed to be [0, 1]\n\tinit_positions  = get_gaussian(Nx)\n\tinit_velocities = zeros(Nx)\n\tufun  = FunArr{Float64, Float64}(init_positions)\n\tutfun = FunArr{Float64, Float64}(init_velocities)\n\t\n\t# use the method of lines to calculate u(x, t) over [0, 1]x[0, Ttot]\n\tu2fun, energies = scalarwave_and_energy(ufun, utfun, Nt, Ttot)\n\t\n\treturn u2fun\nend\n\n# get the solution at different resolutions for the same duration\nu2fun1 = get_gaussian_solution(100, 150, 0.2)\nu2fun2 = get_gaussian_solution(200, 300, 0.2)\nu2fun3 = get_gaussian_solution(300, 450, 0.2)\nu2fun4 = get_gaussian_solution(400, 600, 0.2)\nu2fun5 = get_gaussian_solution(500, 750, 0.2)\nu2fun6 = get_gaussian_solution(600, 900, 0.2)\n\n# get the integrated squared difference between solutions\n# for successive resolutions, for a 2000x2000 spacing\narea12 = integrate_difference(u2fun1, u2fun2, 2000, 2000)\narea23 = integrate_difference(u2fun2, u2fun3, 2000, 2000)\narea34 = integrate_difference(u2fun3, u2fun4, 2000, 2000)\narea45 = integrate_difference(u2fun4, u2fun5, 2000, 2000)\narea56 = integrate_difference(u2fun5, u2fun6, 2000, 2000)\n\n# the differences between increasing resolutions decreases\nprintln(\"The integrated difference between 100x150 and 200x300 is $area12\")\nprintln(\"The integrated difference between 200x300 and 300x450 is $area23\")\nprintln(\"The integrated difference between 300x450 and 400x600 is $area34\")\nprintln(\"The integrated difference between 400x600 and 500x750 is $area45\")\nprintln(\"The integrated difference between 500x750 and 600x900 is $area56\")\n", "meta": {"hexsha": "d55fffa4e130d423e064bc041f04661e06539cd6", "size": 2263, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/example2.jl", "max_stars_repo_name": "AlexanderIbrahim1/ScalarWaveEquation", "max_stars_repo_head_hexsha": "72a7e5886aa89b4b165e9116d219df7c98671334", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/example2.jl", "max_issues_repo_name": "AlexanderIbrahim1/ScalarWaveEquation", "max_issues_repo_head_hexsha": "72a7e5886aa89b4b165e9116d219df7c98671334", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/example2.jl", "max_forks_repo_name": "AlexanderIbrahim1/ScalarWaveEquation", "max_forks_repo_head_hexsha": "72a7e5886aa89b4b165e9116d219df7c98671334", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0172413793, "max_line_length": 75, "alphanum_fraction": 0.7618205921, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7626854702036854}}
{"text": "#=\n  From the WebPPL model https://github.com/probmods/ppaml2016/blob/gh-pages/chapters/5-data.md\n  \"\"\"\n  Posterior prediction and model checking\n\n  One important use of posterior predictive distributions is to examine the descriptive \n  adequacy of a model. The posterior predictive can be viewed as a set of predictions about \n  what data the model expects to see, based on the posterior distribution over parameters. \n  If these predictions do not match the data already seen, the model is descriptively inadequate.\n\n  Let's say we ran 2 experiments that we believe are conceptually the same (e.g., asking \n  10 people whether or not they would vote for \"Hillary Clinton or Donald Trump\" and asking \n  a separate group of 10 people if they would vote for \"Donald Trump or Hillary Clinton\"). \n  Suppose we observed the following data from those 2 experiments: k1=0; k2=10.\n  \"\"\"\n=#\n\nusing Turing\ninclude(\"jl_utils.jl\")\n\n@model function bda2(k1=0,n1=10, k2=10,n2=10)\n    \n    # Sample rate from Uniform distribution\n    p ~ Uniform(0,1)\n    \n    k1 ~ Binomial(n1, p)\n    k2 ~ Binomial(n2, p)    \n\n    # sample from binomial with updated p\n    prior_p ~ Uniform(0,1)\n    posteriorPredictive1 ~ Binomial(n1,p)\n    posteriorPredictive2 ~ Binomial(n2,p)\n       \nend\n\n# data\nk1=0\nn1=10\nk2=10\nn2=10\nprintln(\"k1:$(k1) n1:$(n1) k2:$(k2) n2:$(n2)\")\nmodel = bda2(k1,n1,k2,2)\n\n# chns = sample(model, MH(), 10_000)\n# chns = sample(model, PG(15), 10_000)\n# chns = sample(model, IS(), 10_000)\nchns = sample(model, SMC(), 10_000)\n# chns = sample(model, SMC(), MCMCThreads(), 10_000, 4)\n\ndisplay(chns)\n\nshow_var_dist_pct(chns, :posteriorPredictive1)\nshow_var_dist_pct(chns, :posteriorPredictive2)\n", "meta": {"hexsha": "339c71021146afeb24f8e06e61fbed79bdd57e18", "size": 1682, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/bda2.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/bda2.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/bda2.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 31.1481481481, "max_line_length": 97, "alphanum_fraction": 0.7134363853, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7626854687452467}}
{"text": "\"\"\"\n    CompoundRatingCurve(threshold::Vector{<:Real},rc::Vector{RatingCurve})\n\nConstruct an object of type CompoundRatingCurve\n\"\"\"\nstruct CompoundRatingCurve\n    threshold::Vector{<:Real}\n    component::Vector{RatingCurve}\n    \n    function CompoundRatingCurve(threshold::Vector{<:Real}, component::Vector{RatingCurve})\n        length(threshold) == ( length(component) - 1 ) ||\n            error(\"The number of segments does not match the number of rating curves.\")\n        new(threshold, component)\n    end\n    \nend\n\nCompoundRatingCurve(threshold::Vector{<:Int}, component::Vector{RatingCurve}) = CompoundRatingCurve(float.(threshold), component)\n\nBase.Broadcast.broadcastable(obj::CompoundRatingCurve) = Ref(obj)\n\n\"\"\"\n    function bic(crc::CompoundRatingCurve)\n\nBIC of the compound rating curve model.\n\"\"\"\nfunction bic(crc::CompoundRatingCurve)\n   \n    n₁ = length(crc.component[1].gauging)\n    n₂ = length(crc.component[2].gauging)\n    n = n₁ + n₂\n    p = 6\n    \n    @assert n>6 \n    \n    σ̂² = RatingCurves.var(crc)\n    \n    return n₁*log(σ̂²[1]) + n₂*log(σ̂²[2]) + p*log(n)\n    \nend\n\n\"\"\"\n    cint(crc::CompoundRatingCurve; nboot::Int=100, α::Real=.05)\n\nCompound rating curve parameter confidence intervals of level `1-α` obtained by a bootstrap sample of size `nboot`.\n\"\"\"\nfunction cint(crc::CompoundRatingCurve; nboot::Int=100, α::Real=.05)\n    \n    k = Vector{Float64}(undef, nboot)\n    \n    a₁ = Vector{Float64}(undef, nboot)\n    b₁ = Vector{Float64}(undef, nboot)\n    c₁ = Vector{Float64}(undef, nboot)\n    \n    a₂ = Vector{Float64}(undef, nboot)\n    b₂ = Vector{Float64}(undef, nboot)\n    c₂ = Vector{Float64}(undef, nboot)\n    \n    for i in 1:nboot\n       \n        G₁ = RatingCurves.bootstrap(crc.component[1].gauging)\n        G₂ = RatingCurves.bootstrap(crc.component[2].gauging)\n        crcᵢ = crcfit([G₁..., G₂...])\n        \n        k[i] = crcᵢ.threshold[1]\n        \n        a₁[i] = crcᵢ.component[1].a\n        b₁[i] = crcᵢ.component[1].b\n        c₁[i] = crcᵢ.component[1].c\n        \n        a₂[i] = crcᵢ.component[2].a\n        b₂[i] = crcᵢ.component[2].b\n        c₂[i] = crcᵢ.component[2].c\n        \n    end\n    \n    M = hcat(\n            quantile(k, [α/2, 1-α/2]),\n            quantile(a₁, [α/2, 1-α/2]),\n            quantile(b₁, [α/2, 1-α/2]),\n            quantile(c₁, [α/2, 1-α/2]),\n            quantile(a₂, [α/2, 1-α/2]),\n            quantile(b₂, [α/2, 1-α/2]),\n            quantile(c₂, [α/2, 1-α/2])\n            )\n    \n    return M\n    \nend\n\n\"\"\"\n    discharge(crc::RatingCurve, h::Real)\n\nCompute the estimated discharge at level `h` with the compound rating curve `crc`.\n\"\"\"\nfunction discharge(crc::CompoundRatingCurve, h::Real)\n    \n    y = logdischarge(crc, h)\n    \n    return exp(y)\n    \nend\n\n\"\"\"\n    level(crc::RatingCurve, q::Real)\n\nCompute the level corresponding the the discharge `q` and the compound rating curve `crc`.\n\"\"\"\nfunction level(crc::CompoundRatingCurve, q::Real)\n    \n    @assert q>0\n    \n    threshold = vcat(crc.threshold, Inf)\n    component = crc.component\n    \n    i = 1\n    h = level(component[i], q)\n    \n    while(h > threshold[i])\n        i +=1\n        h = level(component[i], q)\n    end\n    \n    return h\n    \nend\n\n\"\"\"\n    logdischarge(crc::RatingCurve, h::Real)\n\nCompute the estimated log discharge at level `h` with the compound rating curve `crc`.\n\"\"\"\nfunction logdischarge(crc::CompoundRatingCurve, h::Real)\n    \n    threshold = vcat(crc.threshold, Inf)\n    \n    ind = findfirst(h .< threshold)\n    \n    y = logdischarge(crc.component[ind], h)\n    \n    return y\n    \nend\n\n\"\"\"\n    pint(crc::CompoundRatingCurve, level::Real, α::Real=0.05, rtol::Real=.05)\n\n`1-α` confidence interval of the estimated discharge at level `h` with the compound rating curve `crc`.\n\n## Details\n\nFor each segment of the compound rating curve, the confidence intervals are estimated separately. See [`pint(::RatingCurve, ::Real, ::Real, ::Real)`](@ref) \nfor the details for the estimation on each segment. \n\"\"\"\nfunction pint(crc::CompoundRatingCurve, level::Real, α::Real=0.05, rtol::Real=.05)\n    \n    res = pintlog(crc, level, α, rtol)\n    \n    return exp.(res)\nend\n\n\n\n\"\"\"\n    pintlog(crc::CompoundRatingCurve, level::Real, α::Real=0.05, rtol::Real=.05)\n\n`1-α` confidence interval of the estimated log discharge at level `h` with the compound rating curve `crc`.\n\n### Details\n\n`rtol` represents the relative uncertainty of the dishcarge so that the true discharge is included in the interval `q ± 1.96*rtol` 95% of the time\n\"\"\"\nfunction pintlog(crc::CompoundRatingCurve, level::Real, α::Real=0.05, rtol::Real=.05)\n    \n    threshold = vcat(crc.threshold, Inf)\n    \n    ind = findfirst(level .< threshold)\n    \n    rc = crc.component[ind]\n    \n    return pintlog(rc, level, α, rtol)\n    \nend\n\n\"\"\"\n    Base.show(io::IO, obj::EVA)\nOverride of the show function for the objects of type RatingCurve.\n\"\"\"\nfunction Base.show(io::IO, obj::CompoundRatingCurve)\n\n    showCompoundRatingCurve(io, obj)\n\nend\n\nfunction showCompoundRatingCurve(io::IO, obj::CompoundRatingCurve)\n\n    threshold = [0, obj.threshold..., Inf]\n    println(io, \"CompoundRatingCurve\")\n    for i in 1:length(obj.component)\n        println(io, \"\")\n        println(io, \"   for \",threshold[i],\" ≤ h < \",threshold[i+1])\n        showRatingCurve(io, obj.component[i],\"      \")\n    end\nend\n\n\"\"\"\n    sse(rc::RatingCurve)\n\nCompute the sum of the squares of residuals between the compound curve and the gauging in the log space.\n\n### Details\nA value of the sum of squares is given for each CompoundRatingCurve component.\n\"\"\"\nfunction sse(crc::CompoundRatingCurve)\n    \n    SSE = Float64[]\n    \n    for rc in crc.component\n        push!(SSE, sse(rc)[])\n    end\n    \n    return SSE\n\nend\n\n\"\"\"\n    var(crc::CompoundRatingCurve)\n\nEstimate the variance of the errors in the log space.\n\"\"\"\nfunction var(crc::CompoundRatingCurve)\n   \n    σ̂² = Float64[]\n    \n    for rc in crc.component\n        push!(σ̂², RatingCurves.var(rc)[])\n    end\n    \n    return σ̂²\n    \nend", "meta": {"hexsha": "090d2c294d4b2e0a20faac8befddb70c21d1975e", "size": 5939, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/structures/compoundratingcurve.jl", "max_stars_repo_name": "JuliaExtremes/RatingCurves.jl", "max_stars_repo_head_hexsha": "82512c19f89624443892e24e8fbde3f5b7c00c12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T11:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T11:25:59.000Z", "max_issues_repo_path": "src/structures/compoundratingcurve.jl", "max_issues_repo_name": "JuliaExtremes/RatingCurves.jl", "max_issues_repo_head_hexsha": "82512c19f89624443892e24e8fbde3f5b7c00c12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/structures/compoundratingcurve.jl", "max_forks_repo_name": "JuliaExtremes/RatingCurves.jl", "max_forks_repo_head_hexsha": "82512c19f89624443892e24e8fbde3f5b7c00c12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.643153527, "max_line_length": 156, "alphanum_fraction": 0.6273783465, "num_tokens": 1700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7626854608763107}}
{"text": "\n# Computes the logarithmic mean: (aR-aL)/(LOG(aR)-LOG(aL)) = (aR-aL)/LOG(aR/aL)\n# Problem: if aL~= aR, then 0/0, but should tend to --> 0.5*(aR+aL)\n#\n# introduce xi=aR/aL and f=(aR-aL)/(aR+aL) = (xi-1)/(xi+1)\n# => xi=(1+f)/(1-f)\n# => Log(xi) = log(1+f)-log(1-f), and for small f (f^2<1.0E-02) :\n#\n#    Log(xi) ~=     (f - 1/2 f^2 + 1/3 f^3 - 1/4 f^4 + 1/5 f^5 - 1/6 f^6 + 1/7 f^7)\n#                  +(f + 1/2 f^2 + 1/3 f^3 + 1/4 f^4 + 1/5 f^5 + 1/6 f^6 + 1/7 f^7)\n#             = 2*f*(1           + 1/3 f^2           + 1/5 f^4           + 1/7 f^6)\n#  (aR-aL)/Log(xi) = (aR+aL)*f/(2*f*(1 + 1/3 f^2 + 1/5 f^4 + 1/7 f^6)) = (aR+aL)/(2 + 2/3 f^2 + 2/5 f^4 + 2/7 f^6)\n#  (aR-aL)/Log(xi) = 0.5*(aR+aL)*(105/ (105+35 f^2+ 21 f^4 + 15 f^6)\nfunction ln_mean(value1::Float64, value2::Float64)\n  epsilon_f2 = 1.0e-4\n  ratio = value2/value1\n  # f2 = f^2\n  f2=(ratio*(ratio-2.)+1.)/(ratio*(ratio+2.)+1.)\n  if (f2<epsilon_f2)\n    return (value1+value2)*52.5/(105.0 + f2*(35.0 + f2*(21.0 +f2*15.0)))\n  else\n    return (value2-value1)/log(ratio)\n  end\nend\n", "meta": {"hexsha": "986520e9094c09e15d33affdb3b0535c574b0a76", "size": 1042, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/auxiliary/math.jl", "max_stars_repo_name": "sloede/Trixi.jl", "max_stars_repo_head_hexsha": "256ff44456725fd859bdf0903e105246e9893ae5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-13T11:11:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-30T15:11:05.000Z", "max_issues_repo_path": "src/auxiliary/math.jl", "max_issues_repo_name": "sloede/Trixi.jl", "max_issues_repo_head_hexsha": "256ff44456725fd859bdf0903e105246e9893ae5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/auxiliary/math.jl", "max_forks_repo_name": "sloede/Trixi.jl", "max_forks_repo_head_hexsha": "256ff44456725fd859bdf0903e105246e9893ae5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.68, "max_line_length": 114, "alphanum_fraction": 0.4846449136, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7626683115778392}}
{"text": "# Example of MLE estimation. The data is really drawn from the\n# Logit DGP, so the model is well specified, and the MLE has\n# the properties discussed in class. E.g., if you make n very\n# large you should see that the estimator is very close to the\n# true value of theta used to generate data\n\nusing Econometrics\ninclude(\"LogitDGP.jl\")\nn = 30 # sample size\nθ  = [0, 0.5] # true theta for generating data\n(y, x) = LogitDGP(n, θ) # generate the data\n\n# now define things for estimation\nmodel = θ -> logit(θ, y, x)\nθstart = zeros(size(x,2)) # start values for estimation\n\n# Perform the estimation - Make sure that you examine\n# the MLE estimation programs so that you see how this works\nθhat, objvalue, V, converged = mleresults(model, θstart, \"estimate logit model\");\n\n", "meta": {"hexsha": "5ccea2ef3ffdf1525238922b27b3d54c63c3e54e", "size": 767, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/MLE/EstimateLogit.jl", "max_stars_repo_name": "mcreel/EconometricsNotes", "max_stars_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-19T18:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T18:23:45.000Z", "max_issues_repo_path": "Examples/MLE/EstimateLogit.jl", "max_issues_repo_name": "mcreel/EconometricsNotes", "max_issues_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/MLE/EstimateLogit.jl", "max_forks_repo_name": "mcreel/EconometricsNotes", "max_forks_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5238095238, "max_line_length": 81, "alphanum_fraction": 0.7301173403, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9744347823646075, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7626535423434498}}
{"text": "using DifferentialEquations\nusing Plots\nusing PyPlot\n\n\n# Set the required model parameters for the SIRS model with two levels of transmission - Within and between households\nN = 10; # Household size - Change to 10 for final analysis\nbetaHH = 6; # Within household transmission parameter\nbetaG = 1; # Population wide transmission\ngamma = 1; # Rate of recovery from infection\ntau = 1; # Rate of loss of protection\nparams = [betaHH,gamma,tau,betaG,N]; # Put all the parameters together\ntime = (0.0, 30.0) # Simulation time - note it defined as a float\ndim = dim = 0.5*(N+1)*(N+2); # Number of possible configurations - works for three epidemiological classes\ny0 = vec(zeros(1,dim)); # Initial condition vector\ny0[end-1] = 0.00000001;\ny0[end] = 0.99999999;\n\nfunction hhTransitions(N,dim)\n    # Function to generate transition matrices for household model\n    # Input: N is the household size\n    \n    # Initialize things\n    Qinf = zeros(dim,dim);\n    Qrec = zeros(dim,dim);\n    Qext = zeros(dim,dim);\n    Qwane = zeros(dim,dim);\n    dataI = Array{Int64}(zeros(dim,3))\n    m = 0;\n    I = Array{Int64}(zeros(N+1,N+1))\n    \n    # To help remember where to store the variables\n    for ss = 0:N\n        for ii = 0:(N-ss)\n            m = m + 1;\n            I[ss+1,ii+1] = m\n        end\n    end\n    \n    # Describe the epidemiological transitions\n    \n    # Counter for susceptibles\n    for ss = 0:N\n        # Counter for infecteds\n        for ii = 0:(N-ss) \n            # If susceptibles and infecteds are more than 1, then infection within the household can occur\n            if (ss > 0 && ii > 0) \n                Qinf[I[ss+1,ii+1],I[ss,ii+2]] = ii*ss/(N-1);\n            end\n            \n            # If infecteds are more than 1, recovery can occur\n            if ii > 0\n                # Rate of recovery\n                Qrec[I[ss+1,ii+1],I[ss+1,ii]] = ii; \n            end\n            \n            # For external infection - just keep track of susceptibles\n            if ss > 0           \n                # Rate of within household infection\n                Qext[I[ss+1,ii+1],I[ss,ii+2]] = ss;           \n            end\n            \n            # Loss of protection hence becoming susceptible again. Possible if N-ss-ii = rr > 0 \n            if (N-ss-ii) > 0\n                # Rate of loss of protection\n                Qwane[I[ss+1,ii+1],I[ss+2,ii+1]] = N-ss-ii;\n            end\n            \n            # Store the relevant indices to help identify the household configurations\n            dataI[I[ss+1,ii+1],:] = [ss, ii, N-ss-ii];\n        end\n    end\n    \n    Qinf = Qinf - diagm(vec(sum(Qinf,2)),0);\n    Qrec = Qrec - diagm(vec(sum(Qrec,2)),0);\n    Qext = Qext - diagm(vec(sum(Qext,2)),0);\n    Qwane = Qwane - diagm(vec(sum(Qwane,2)),0);\n    \n    # Return\n    return Qinf, Qrec, Qext, Qwane, dataI\nend\n\nQinf, Qrec, Qext, Qwane, dataI = hhTransitions(N,dim);\n\nfunction rateSIRS(dy_dt,y0,params,time)\n    \n    # Extract the parameters\n    betaHH = params[1];\n    gamma = params[2];\n    tau = params[3];\n    betaG = params[4];\n    N = params[5];\n    \n    # Generate the transition matrices\n    Qinf, Qrec, Qext, Qwane, HHconfig = hhTransitions(N,dim);\n    \n    # Combine within and external transitions\n    Q = betaHH*Qinf + gamma*Qrec + tau*Qwane + (betaG*((HHconfig[:,2]'*y0)/N)*Qext);\n    \n    # Generate the rates of change for ODE solver\n    dy_dt .= (y0'*Q)';\n    \n    # Alternatively this works too\n    #=for i=1:length(y0)\n        dy_dt[i] = y0'*Q[:,i]\n    end=#\n\nend\n\n# Define the ODE problem\nprob = ODEProblem(rateSIRS,y0,time,params);\n\n# Solve\nsol = solve(prob);\n\nIconfig = dataI[:,2];\ninfProp = zeros(length(sol.t),1);\n\n# Prepare the plots\nfor i = 1:length(sol.t)\n    infProp[i,1] = sol[:,i]'*Iconfig/N;\nend\n\n# Total infectious in the population\nplot(sol.t,infProp,color=\"blue\",xlabel=\"Time\",ylabel=\"Proportion infectious\",label=[\"Mean infection\"],ylims=[0, 1])\n\n# Household profile at endemic prevalence\n# Prepare the plots\nyprop = zeros(N+1,length(sol.t))\nfor j = 1:length(sol.t)\n    for i = 1:N+1\n        index = find(Iconfig.==i-1);\n        yprop[i,j] = sum(sol[index,j])\n    end\nend\nstep(-0.5:1:10.5,[yprop[:,length(sol.t)];0])\n\n# Household profile at peak prevalence\n# Prepare the plots\nx = find(infProp.==maximum(infProp))\nstep(-0.5:1:10.5,[yprop[:,x];0]);\n", "meta": {"hexsha": "7af91a00fb935c9f0b9e217c1871a12f9907741c", "size": 4277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/metapopulation_models/large_population_sirs.jl", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/metapopulation_models/large_population_sirs.jl", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/metapopulation_models/large_population_sirs.jl", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 30.1197183099, "max_line_length": 118, "alphanum_fraction": 0.5896656535, "num_tokens": 1292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7626087499231846}}
{"text": "# See https://en.wikipedia.org/wiki/Matrix_(mathematics)\n# Examples from https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/\n\nusing LinearAlgebra\n\nexpressions = [\n    :(inv([1 2 3; 4 1 6; 7 8 1]))\n    :(det([1 2 3; 4 1 6; 7 8 1]))\n    :(eigvals([-4. -17.; 2. 2.]))\n    :(eigvecs([-4. -17.; 2. 2.]))\n    :(factorize([1.5 2 -4; 3 -1 -6; -10 2.3 4]))\n    :(factorize([1.5 2 -4; 2 -1 -3; -4 -3 5]))\n    :(([1 0; 1 -2] \\ [32; -4]))\n    :(([1 0; 1 -2] * [32.0, 18.0]))\n    :(dot([1; 1], [2; 3]))\n    :(cross([0; 1; 0], [0; 0; 1]))\n    :(UpperHessenberg([1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]))\n    :(cholesky([4. 12. -16.; 12. 37. -43.; -16. -43. 98.]).U)\n    :(cholesky([4. 12. -16.; 12. 37. -43.; -16. -43. 98.]).L)\n]\n\nfor expr in expressions\n    println(\"[] :julia-answer \\\"\\\"\\\"\", escape_string(string(expr)), \" = \", eval(expr), \"\\\"\\\"\\\".\")\nend\n", "meta": {"hexsha": "cec592b057776baea0c97b0dd0ad2782b2c098e3", "size": 849, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "reasoning/julia/matrix.jl", "max_stars_repo_name": "pmoura/eye", "max_stars_repo_head_hexsha": "03a4be110f5e9f8f21a6b1ac2756d79cc6518386", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reasoning/julia/matrix.jl", "max_issues_repo_name": "pmoura/eye", "max_issues_repo_head_hexsha": "03a4be110f5e9f8f21a6b1ac2756d79cc6518386", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reasoning/julia/matrix.jl", "max_forks_repo_name": "pmoura/eye", "max_forks_repo_head_hexsha": "03a4be110f5e9f8f21a6b1ac2756d79cc6518386", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.96, "max_line_length": 97, "alphanum_fraction": 0.4876325088, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7626087497044833}}
{"text": "#!/usr/bin/julia\n\n# Trizen\n# Date: 18 August 2016\n# https://github.com/trizen\n\n# Count the number of partitions of n.\n\n# See also: https://oeis.org/A000041\n#           https://en.wikipedia.org/wiki/Partition_(number_theory)\n\nfunction count_partitions(x::Int64)\n    n = 2\n    p = Int64[1]\n\n    while (n <= x+1)\n        i = 0\n        q = 2\n        push!(p, 0)\n\n        while q <= n\n            p[n] += (i % 4 > 1 ? -1 : 1) * p[n-q+1]\n            i += 1\n            j = div(i, 2) + 1\n            isodd(i) && (j *= -1)\n            q = div(j * (3j - 1), 2) + 1\n        end\n\n        n += 1\n    end\n\n    p[n-1]\nend\n\nprintln(\"P(200) = \", count_partitions(200))        # 3972999029388\n", "meta": {"hexsha": "68f8203985a286b775d48ec5051d530e30bc7a31", "size": 676, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Math/count_partitions.jl", "max_stars_repo_name": "trizen/julia-scripts", "max_stars_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-03-22T09:38:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T21:38:31.000Z", "max_issues_repo_path": "Math/count_partitions.jl", "max_issues_repo_name": "trizen/julia-scripts", "max_issues_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/count_partitions.jl", "max_forks_repo_name": "trizen/julia-scripts", "max_forks_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7777777778, "max_line_length": 67, "alphanum_fraction": 0.4630177515, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8056321866478978, "lm_q1q2_score": 0.7626087489281609}}
{"text": "\"\"\"\n    Chisq(ν)\nThe *Chi squared distribution* (typically written χ²) with `ν` degrees of freedom has the\nprobability density function\n\n```math\nf(x; k) = \\\\frac{x^{k/2 - 1} e^{-x/2}}{2^{k/2} \\\\Gamma(k/2)}, \\\\quad x > 0.\n```\n\nIf `ν` is an integer, then it is the distribution of the sum of squares of `ν` independent standard [`Normal`](@ref) variates.\n\n```julia\nChisq(k)     # Chi-squared distribution with k degrees of freedom\n\nparams(d)    # Get the parameters, i.e. (k,)\ndof(d)       # Get the degrees of freedom, i.e. k\n```\n\nExternal links\n\n* [Chi-squared distribution on Wikipedia](http://en.wikipedia.org/wiki/Chi-squared_distribution)\n\"\"\"\nstruct Chisq{T<:Real} <: ContinuousUnivariateDistribution\n    ν::T\n    Chisq{T}(ν::T) where {T} = new{T}(ν)\nend\n\nfunction Chisq(ν::T) where {T <: Real}\n    @check_args(Chisq, ν > zero(ν))\n    return Chisq{T}(ν)\nend\n\nChisq(ν::T, ::NoArgCheck) where {T <: Real} = Chisq{T}(ν)\nChisq(ν::Integer) = Chisq(float(ν))\n\n@distr_support Chisq 0.0 Inf\n\n#### Parameters\n\ndof(d::Chisq) = d.ν\nparams(d::Chisq) = (d.ν,)\n@inline partype(d::Chisq{T}) where {T<:Real} = T\n\n### Conversions\nconvert(::Type{Chisq{T}}, ν::Real) where {T<:Real} = Chisq(T(ν))\nconvert(::Type{Chisq{T}}, d::Chisq{S}) where {T <: Real, S <: Real} = Chisq(T(d.ν))\n\n\n#### Statistics\n\nmean(d::Chisq) = d.ν\n\nvar(d::Chisq) = 2d.ν\n\nskewness(d::Chisq) = sqrt(8 / d.ν)\n\nkurtosis(d::Chisq) = 12 / d.ν\n\nmode(d::Chisq{T}) where {T<:Real} = d.ν > 2 ? d.ν - 2 : zero(T)\n\nfunction median(d::Chisq; approx::Bool=false)\n    if approx\n        return d.ν * (1 - 2 / (9 * d.ν))^3\n    else\n        return quantile(d, 1//2)\n    end\nend\n\nfunction entropy(d::Chisq)\n    hν = d.ν/2\n    hν + logtwo + lgamma(hν) + (1 - hν) * digamma(hν)\nend\n\n\n#### Evaluation\n\n@_delegate_statsfuns Chisq chisq ν\n\nmgf(d::Chisq, t::Real) = (1 - 2 * t)^(-d.ν/2)\n\ncf(d::Chisq, t::Real) = (1 - 2 * im * t)^(-d.ν/2)\n\ngradlogpdf(d::Chisq{T}, x::Real) where {T<:Real} =  x > 0 ? (d.ν/2 - 1) / x - 1//2 : zero(T)\n\n\n#### Sampling\n\nrand(rng::AbstractRNG, d::Chisq) =\n    (ν = d.ν; rand(rng, Gamma(ν / 2.0, 2.0one(ν))))\n\nsampler(d::Chisq) = (ν = d.ν; sampler(Gamma(ν / 2.0, 2.0one(ν))))\n", "meta": {"hexsha": "09f58c7321d5e3fe4cd828e843614c3ecfb6fdbe", "size": 2136, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/chisq.jl", "max_stars_repo_name": "uwbanjoman/Distributions.jl", "max_stars_repo_head_hexsha": "3f3dbe911629120e0fd875291aaaec1645b0f855", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/chisq.jl", "max_issues_repo_name": "uwbanjoman/Distributions.jl", "max_issues_repo_head_hexsha": "3f3dbe911629120e0fd875291aaaec1645b0f855", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/chisq.jl", "max_forks_repo_name": "uwbanjoman/Distributions.jl", "max_forks_repo_head_hexsha": "3f3dbe911629120e0fd875291aaaec1645b0f855", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2173913043, "max_line_length": 126, "alphanum_fraction": 0.5959737828, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966656805269, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7626087350195669}}
{"text": "using LinearAlgebra, DataFrames, Statistics\n\nn = 1000\nx = [ones(n) rand(1:0.1:10, n)]\nb,sigma = [2.5, -1.2], 1\ny = x*b + sigma .* randn(n);\n\n# Write types\nabstract type StandardErrorEstimator end\nstruct Bootstrap <: StandardErrorEstimator\n    bootstrap_samples::Int\n    subsample_size::Int\nend\nstruct Spherical <: StandardErrorEstimator end\n\n# Estimator code\nols(x, y) = ols(x, y, Spherical())\nfunction ols(x, y, se_estimator::Spherical)\n    V_inv = inv(x'x)\n    b_hat = V_inv*x'y\n    y_hat = x*b_hat\n    e = y - y_hat\n\n    n = length(y)\n    k = size(x, 2)\n    s2  = e'e / (n-k)\n\n    se=sqrt.(s2 .* diag(V_inv))\n\n    return DataFrame(\n        b_hat=b_hat, \n        se=se,\n    )\nend\n\nfunction ols(x, y, se_estimator::Bootstrap)\n    n = length(y)\n    n_samples = se_estimator.bootstrap_samples\n    subsample_size = se_estimator.subsample_size\n    b_hats = zeros(n_samples, size(x, 2))\n\n    for k in 1:n_samples\n        inds = rand(1:n, subsample_size)\n        x_sub = x[inds,:]\n        y_sub = y[inds]\n\n        b_hats[k, :] = inv(x_sub'x_sub)*x_sub'y_sub\n    end\n\n    b_hat = vec(mean(b_hats, dims=1))\n    se_hat = vec(std(b_hats, dims=1))\n\n    return DataFrame(\n        b_hat=b_hat, \n        se_hat=se_hat,\n    )\nend\n\nfit1 = ols(x, y, Spherical())\nfit2 = ols(x, y, Bootstrap(100_000, 10))\n\nprintln(\"Spherical\")\ndisplay(fit1)\n\nprintln(\"\\nBootstrapped\")\ndisplay(fit2)\n", "meta": {"hexsha": "1cb15ec6f09753f7764468da6caf0bdef258fb47", "size": 1365, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "session-1/project.jl", "max_stars_repo_name": "INFONAVIT-EstudiosFyA/julia-bootcamp-2022", "max_stars_repo_head_hexsha": "a0e9bdbf2ff3627fa7fd2a4c3bc5485b0b029d41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 223, "max_stars_repo_stars_event_min_datetime": "2022-01-07T19:37:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:56:48.000Z", "max_issues_repo_path": "session-1/project.jl", "max_issues_repo_name": "INFONAVIT-EstudiosFyA/julia-bootcamp-2022", "max_issues_repo_head_hexsha": "a0e9bdbf2ff3627fa7fd2a4c3bc5485b0b029d41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-13T18:57:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T16:48:17.000Z", "max_forks_repo_path": "session-1/project.jl", "max_forks_repo_name": "INFONAVIT-EstudiosFyA/julia-bootcamp-2022", "max_forks_repo_head_hexsha": "a0e9bdbf2ff3627fa7fd2a4c3bc5485b0b029d41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2022-01-09T19:44:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T04:18:37.000Z", "avg_line_length": 20.3731343284, "max_line_length": 51, "alphanum_fraction": 0.6241758242, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.762570353410263}}
{"text": "# It was proposed by Christian Goldbach that every odd composite number can be\n# written as the sum of a prime and twice a square.\n#\n# 9 = 7 + 2×1^2\n# 15 = 7 + 2×2^2\n# 21 = 3 + 2×3^2\n# 25 = 7 + 2×3^2\n# 27 = 19 + 2×2^2\n# 33 = 31 + 2×1^2\n#\n# It turns out that the conjecture was false.\n#\n# What is the smallest odd composite that cannot be written as the sum of a\n# prime and twice a square?\n\nusing ProjectEulerSolutions\n\n# Make a resonable list of twice squares and primes, then sum combinations of\n# them and make a set that you compare against the set of odd composite\n# numbers.  Would probably be faster to not calculate all the prime numbers\n# and odd composite numbers upfront.\nfunction p046solution(n::Integer=100)::Integer\n    primearray = sieve_eratosthenes(n)\n    primeset = Set(primearray)\n    oddnumset = Set(9:2:n)\n    oddcompositeset = setdiff(oddnumset, primeset)\n\n    twicesquares = 2 .* (1:Integer(floor(0.75*sqrt(n)))).^2\n\n    sums = Set()\n    for ts in twicesquares\n        union!(sums, Set(ts .+ primearray))\n    end\n\n    oddcomp = setdiff(oddcompositeset, sums)\n    if length(oddcomp) > 0\n        return minimum(oddcomp)\n    else\n        return -1\n    end\nend\n\np046 = Problems.Problem(p046solution)\n\nProblems.benchmark(p046, 10_000)", "meta": {"hexsha": "30d8f37f04155a17c5618efa8aeebffefe342b7e", "size": 1252, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/046.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/046.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/046.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8222222222, "max_line_length": 78, "alphanum_fraction": 0.6869009585, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7625703449387675}}
{"text": "#=\nTake the number 192 and multiply it by each of 1, 2, and 3:\n\n192 × 1 = 192\n192 × 2 = 384\n192 × 3 = 576\nBy concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3)\n\nThe same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5).\n\nWhat is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1?\n=#\nfunction canbepandigital(n)\n  stringresult = \"\"\n  i = 1\n  while length(stringresult) < 9\n    stringresult *= string(n * i)\n    i += 1\n  end\n\n  if (length(stringresult)) == 9\n    result = parse(Int, stringresult)\n    if sort(digits(result)) == collect(1:9)\n      return (true,result)\n    end\n  end\n  (false, 0)\nend\n\nfunction calc()\n  maxpandigital = 0\n  for i in 2:10_000\n    (result, pandigital) = canbepandigital(i)\n    if result && pandigital > maxpandigital\n      maxpandigital = pandigital\n    end\n  end\n  maxpandigital\nend\n@time println(calc())\n", "meta": {"hexsha": "5af764fe637fecc27d83c1f71c2a105ddcbf51cc", "size": 1118, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p38.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p38.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p38.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 27.2682926829, "max_line_length": 171, "alphanum_fraction": 0.6797853309, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415278, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7625248615253917}}
{"text": "using Plots\n\nRotation(R, θ) = [cos(θ) -sin(θ);sin(θ) cos(θ)] * R\n\nfunction DragonFractal(;order, θ, points)\n    θ₁ = θ[1]; θ₂ = θ[2]\n    for num in 1:order\n        i = 1\n        while i < length(points)\n            point = (points[i+1] - points[i]) * sin(abs(θ₁))\n            point = Rotation(point, θ₁)  + points[i]\n            insert!(points,i+1,point)\n            i += 2\n            point = (points[i+1] - points[i]) * sin(abs(θ₂))\n            point = Rotation(point, θ₂)  + points[i]\n            insert!(points,i+1,point)\n            i += 2\n        end\n    end\n    return points\nend\n\n\nfor i in [1,5,10,15]\n    Parameters = Dict(:order => i,\n                    :θ => [pi/4, -pi/4],\n                    :points => [[0.0; 0.0],[1.0; 0.0],[1.0; 1.0]])\n\n    points = DragonFractal(;Parameters...)\n    half = Int(floor(length(points)/2))\n\n    plot(hcat(points...)[1,1:half], hcat(points...)[2,1:half], legend = false, color =:blue, border=:none)\n    plot!(hcat(points...)[1,half:end], hcat(points...)[2,half:end], legend = false, color =:red, border=:none)\n    savefig(\"C:\\\\Users\\\\Yaghoub\\\\Documents\\\\GitHub\\\\ComputationalPhysics-Fall2021\\\\ProblemSet1\\\\Figs\\\\Q2\\\\Heighway-dragon-O$i.png\")\n\n    Parameters = Dict(:order => i,\n                    :θ => [-pi/4, -pi/4],\n                    :points => [[0.0; 0.0],[1.0; 0.0],[1.0; 1.0]])\n    points = DragonFractal(;Parameters...)\n    plot(hcat(points...)[1,:], hcat(points...)[2,:], legend = false, border=:none, color =:black, linewidth=0.4)\n    savefig(\"C:\\\\Users\\\\Yaghoub\\\\Documents\\\\GitHub\\\\ComputationalPhysics-Fall2021\\\\ProblemSet1\\\\Figs\\\\Q2\\\\Lévy-C-curve-O$i.png\")\nend\n", "meta": {"hexsha": "574a15b657918bb81de1b53e6ace0ba8202f9d89", "size": 1622, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSet1/Codes/Q2.jl", "max_stars_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_stars_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSet1/Codes/Q2.jl", "max_issues_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_issues_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSet1/Codes/Q2.jl", "max_forks_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_forks_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-21T11:07:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-21T11:07:08.000Z", "avg_line_length": 37.7209302326, "max_line_length": 131, "alphanum_fraction": 0.5363748459, "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.8152324871074607, "lm_q1q2_score": 0.762524858586889}}
{"text": "using LinearAlgebra\nusing GLM\nusing LsqFit\nusing Distributions\nusing StatsBase\nusing Printf\nusing Plots\n\n#linear fit wrapper\n\nfunction lfit(ndf::DataFrame)\n    lr = lm(@formula(y_mean ~ x_mean), ndf)\n    c = coef(lr)\n    return x -> c[1] + c[2]*x, predict(lr), c\nend\n\nstruct RFit\n\tfitpar::Vector{Number}\n\tfitstd::Vector{Number}\n\tci::Vector{Tuple{Number, Number}}\n\tg::Function\nend\n\nfunction gpol1(ct)\n    function f1(z)\n        return ct[1] + ct[2] * z\n    end\n    return f1\nend\n\nfunction gpol2(ct)\n    function f2(z)\n        return ct[1] + ct[2] * z + ct[3] * z^2\n    end\n    return f2\nend\n\nfunction gpol3(ct)\n    function f3(z)\n        return ct[1] + ct[2] * z + ct[3] * z^2 + ct[4] * z^3\n    end\n    return f3\nend\n\n\nfunction polfit(pol, x::Vector{<:Real},y::Vector{<:Real}, p0::Vector{<:Real})\n    fq = curve_fit(pol, x, y, p0)\n    cfq = coef(fq)\n    @info \"coef(fq)\" cfq\n    sfq = stderror(fq)\n    @info \"std(fq)\" sfq\n    @info \"margin_of_error (90%)\" margin_error(fq, 0.1)\n    @info \" confidence_interval (90%)\" confidence_interval(fq, 0.1)\n    return cfq, sfq\nend\n\n\nfunction fit_pol1(x::Vector{<:Real},y::Vector{<:Real}, ci=0.1)\n    @. pol(x, p) = p[1] + p[2] * x\n    p0 = [1.0, 1.0]\n    fq = curve_fit(pol, x, y, p0)\n\n    RFit(coef(fq), stderror(fq), confidence_interval(fq, ci),\n         gpol1(coef(fq)))\nend\n\n\nfunction fit_pol2(x::Vector{<:Real},y::Vector{<:Real}, ci=0.1)\n    @. pol(x, p) = p[1] + p[2] * x + p[3] * x^2\n    p0 = [1.0, 1.0, 1.0]\n    fq = curve_fit(pol, x, y, p0)\n    RFit(coef(fq), stderror(fq), confidence_interval(fq, ci),\n         gpol2(coef(fq)))\nend\n\n\nfunction fit_pol3(x::Vector{<:Real},y::Vector{<:Real}, ci=0.1)\n    @. pol(x, p) = p[1] + p[2] * x + p[3] * x^2 + p[4] * x^3\n    p0 = [1.0, 1.0, 1.0, 1.0]\n    fq = curve_fit(pol, x, y, p0)\n    RFit(coef(fq), stderror(fq), confidence_interval(fq, ci),\n         gpol3(coef(fq)))\nend\n\n\"\"\"\n\tfit_gauss(y, xmin, xmax, bins=25)\n\nFit a normal distribution to data\n\"\"\"\n\nstruct FGauss\n\tmu::Vector{Number}\n\tstd::Vector{Number}\n\tC::Vector{Number}\n\th::Histogram\n\tX::Vector{Number}\n\tY::Vector{Number}\n\tg::Vector{Function}\nend\n\nfunction gausg(μ::Real, σ::Real, C::Real)\n\tfunction gausx(x)\n\t\treturn C * pdf(Normal(μ, σ,), x)\n\tend\n\treturn gausx\nend\n\nfunction gausg2(μ1::Real, σ1::Real, C1::Real, μ2::Real, σ2::Real, C2::Real)\n\tfunction gausx(x)\n\t\treturn C1 * pdf(Normal(μ1, σ1,), x) + C2 * pdf(Normal(μ2, σ2,), x)\n\tend\n\treturn gausx\nend\n\n@. gauss1fm(x, p) = p[1]* pdf(Normal(p[2], p[3]), x)\n@. gauss1(x, p) = p[1]* pdf(Normal(p[2], p[3]), x)\n@. gauss2(x, p) = p[1]* pdf(Normal(p[2], p[3]), x) +  p[4]* pdf(Normal(p[5], p[6]), x)\n@. gausscm(x, p) = p[1] * pdf(Normal(p[2], p[3]), x) + p[4] * pdf(Normal(p[2], p[5]), x)\n\nfunction gaussfm(mu::Real)\n\tfunction gauss(x::Vector{<:Real}, p::Vector{<:Real})\n\t\treturn @. p[1]* pdf(Normal(mu, p[2]), x)\n\tend\n\treturn gauss\nend\n\nfunction gauss2fm(mu::Real)\n\tfunction gauss2(x::Vector{<:Real}, p::Vector{<:Real})\n\t\treturn @. p[1]* pdf(Normal(mu, p[2]), x) + p[3]* pdf(Normal(mu, p[4]), x)\n\tend\n\treturn gauss2\nend\n\nfunction gauss1fm(mu)\n    function gauss1(x,p)\n        return @. p[1]* pdf(Normal(mu, p[2]), x)\n    end\n    return gauss1\nend\n\nfunction cfit(ffit::Function, x::Vector{Float64}, y::Vector{Float64},\n\t                         p0::Vector{Float64}, lb::Vector{Float64}, ub::Vector{Float64})\n\tfq = curve_fit(ffit, x, y, p0, lower=lb, upper=ub)\n    cfq = coef(fq)\n    @debug \"coef(fq)\" cfq\n    return cfq\nend\n\n\n\"\"\"\n    cfit\n\nTake into account the errors on the measured variables. Assuming weights\nof 1/sigma^2 as in standard least squares.\n\"\"\"\nfunction cfit(ffit::Function, x::Vector{<:Real}, y::Vector{<:Real},\n\t          yerr::Vector{<:Real}, p0::Vector{<:Real},\n              lb::Vector{<:Real}, ub::Vector{<:Real})\n\tfq = curve_fit(ffit, x, y, yerr.^-2, p0, lower=lb, upper=ub)\n    return fq\nend\n\n\nfunction fit_gauss(h::Histogram)\n\tc = centers(h)\n\tw = h.weights * 1.0\n\t@debug \"histo\"  w c\n\tmu, sigma = mean_and_std(c, Weights(h.weights); corrected = false)\n\t@debug \"mu, std\" mu, sigma\n\n\t# fit parameters lb, ub, po are lower, upper bounds and pars\n    lb = [0., mu - 100.0*sigma, sigma/100.0]\n    ub = [100*sum(w), mu + 100.0*sigma, 100.0*sigma]\n    p0_bounds = [sum(w), mu, sigma]\n\tCC, μ, σ  = cfit(gauss1, c, w, p0_bounds, lb, ub)\n\tgx = gausg(μ, σ, CC)\n\treturn FGauss([μ], [σ], [CC], h, c, gx.(c), [gx])\n\nend\n\n\nfit_gauss(x::Vector{Float64}, xmin::Float64, xmax::Float64;\n\t      bins::Integer=50, norm=false) =fit_gauss(hist1d(x, bins, xmin, xmax, norm))\n\n\n\"\"\"\n\tfit_gauss_fm(y::Vector{Float64}, xmin::Float64, xmax::Float64, bins=50, fm=0.0)\n\nFit a gaussian with a fixed mean fm\n\"\"\"\nfunction fit_gauss_fm(y::Vector{Float64}, xmin::Float64, xmax::Float64;\n\t                  bins=50, norm=false, fm=0.0)\n\n\t# fit the unbinned distribution\n\tx  =  in_range(y, xmin, xmax)\n\tσ = std(x)\n\t@debug \"gfit_gauss_fm: σ = $σ\"\n\n\t# bin distribution\n    h = hist1d(x, bins, xmin, xmax, norm)\n    c = centers(h)\n    w = h.weights *1.0\n    @debug \"histo w and c\"  w c\n\n\t# fit parameters lb, ub, po are lower, upper bounds and pars\n    lb = [0.0, σ/10.0]\n    ub = [1.0e+6*sum(w),  σ * 10.0]\n    p0_bounds = [0.0, σ]\n\n\tg1 = gaussfm(fm)\n\tCC, sigma  = cfit(g1, c, w, p0_bounds, lb, ub)\n\n\t@debug \"CC,  sigma\"  CC  sigma\n\tgx = gausg(fm, sigma, CC)\n\n\treturn FGauss([fm], [sigma], [CC], h, c, gx.(c), [gx])\nend\n\n\nfunction plot_fit_gauss(x::Vector{Float64}, xs::String, ys::String,\n    bins::Integer, xmin::Float64, xmax::Float64;\n    xgmin::Float64, xgmax::Float64, gbins::Integer=50)\n\n    h,p = hist1d(x, xs, bins, xmin, xmax, norm=true)\n    fg  = fit_gauss(x, xgmin, xgmax, bins=gbins, norm=true)\n    gx  = fg.g[1]\n    X   = centers(h)\n    Y   = h.weights\n    σY  = sqrt.(Y)\n    lbl = @sprintf \" μ=%5.1f, σ =%5.1f \" fg.mu[1] fg.std[1]\n    lbl =string(\"gaussian fit:\\n\", lbl)\n    p = scatter(X, Y, yerror=σY,fmt = :png,\n    shape = :circle, color = :black, label=\"data\", legend=true)\n    p = plot!(p, X, gx.(X), lw=2, label=lbl, legend=true, fmt = :png)\n    xlabel!(xs)\n    xlabel!(ys)\n    return fg, p\nend\n\n\"\"\"\n\tfitg1(x, xs, xmin, xmax, xgmin, xgmax; bins=100)\n\nreturns the fit and the plot\n\"\"\"\nfunction fitg1(x, xs, bins, xmin, xmax;\n\t           xgmin, xgmax, fbins=100, norm=true, fm=0.0, flex_mean=false)\n\n\th, p = hist1d(x, xs, bins, xmin, xmax, norm=norm, legend=true)\n    if flex_mean\n        fg = fit_gauss(x, xgmin, xgmax, bins=fbins, norm=norm)\n    else\n        fg = fit_gauss_fm(x, xgmin, xgmax, bins=fbins, norm=norm, fm=fm)\n    end\n\tgx = fg.g[1]\n\tX = centers(h)\n\tlbl = @sprintf \"σ =%4.1f \" fg.std[1]\n    p = plot!(p, X, gx.(X), lw=2, label=lbl, legend=true, fmt = :png)\n\txlabel!(xs)\n\treturn fg, p\nend\n\n\"\"\"\n\tgfit_gauss2_cmean(y, xmin, xmax, bins, sigmas, cs, cmean=0.0)\n\nFit a double gaussian (with sigmas -->[sigma1, sigma2] cs -->[c1, c2] )\nand a cmean to data.\n\"\"\"\nfunction gfit_gauss2_cmean(y::Vector{Float64}, xmin::Float64, xmax::Float64,\n\t                       bins::Integer, sigmas::Vector{Float64}, cs::Vector{Float64},\n\t\t\t\t\t\t   norm=false, cmean=0.0)\n\n    x =  in_range(y, xmin, xmax)\n    h = hist1d(x, bins, xmin, xmax, norm)\n    c = centers(h)\n    w = h.weights\n    @debug \"histo centers and weights in full region\"  w c\n\n    g2 = gauss2fm(cmean)\n    # fit parameters lb, ub, po are lower, upper bounds and pars\n\n    lb = [cs[1]/100.0, sigmas[1]/5.0, cs[2]/100.0, sigmas[2]/5.0]\n    ub = [cs[1]*100.0, sigmas[1]*5.0, cs[2]*100.0, sigmas[2]*5.0]\n    p0_bounds = [cs[1], sigmas[1], cs[2], sigmas[2]]\n\n    @debug \"pars\" p0 lb ub\n    # fit double gaussian\n    fq = curve_fit(g2, c, w, p0_bounds, lower=lb, upper=ub)\n    C1, sigma1, C2,  sigma2   = coef(fq)\n    @debug \"C1 sigma1 C2 sigma2\" C1 sigma1 C2  sigma2\n\n    #\n    gx = gausg2(cmean, sigma1, C1, cmean, sigma2, C2)\n    gx1 = gausg(cmean, sigma1, C1)\n    gx2 = gausg(cmean, sigma2, C2)\n    #return (sigma1 = sigma1, sigma2 = sigma2, C1 = C1, C2=C2,\n    #        h = h, xg = c, yg = gx.(c), gx = gx, gx1=gx1, gx2=gx2)\n\n\treturn FGauss([cmean, cmean], [sigma1, sigma2], [C1, C2],\n\t\t\t       h, c, gx.(c), [gx, gx1, gx2])\n    end\n\n\"\"\"\n\tfit_2gauss_cmean(data, gp, g1p, g2p, cm)\n\nFit two gaussian with common mean\n\"\"\"\nfunction fit_2gauss_cmean(data, gp, g1p, g2p, cm, norm=false)\n    gf1 = fit_gauss_fm(data, g1p.xmin,g1p.xmax, bins=g1p.nbin, norm=norm, fm=cm)\n    @debug gf1\n    gf2 = fit_gauss_fm(data, g2p.xmin,g2p.xmax,bins=g2p.nbin, norm= norm, fm=cm)\n    @debug gf2\n    gf = gfit_gauss2_cmean(data, gp.xmin,gp.xmax,gp.nbin,\n\t                       [gf1.std[1], gf2.std[1]], [gf1.C[1], gf2.C[1]], norm)\n    @debug gf\n    return gf\nend\n\n\n# fit_gauss2(x::Vector{Float64},\n#            xmin::Vector{Float64},\n# \t\t   xmax::Vector{Float64},\n# \t\t   bins::Vector{Int64}) = gfit_gauss2(x, xmin, xmax, bins)\n\n\n\"\"\"\n    fitg2(x, xs, xmin, xmax, xg1min, xg1max, xg2min, xg2max, xgmin, xgmax; bins=100)\nFits 2 gaussians with common mean (0 by default) to vector x.\n\"\"\"\nfunction fitg2(x, xs, bins, xmin, xmax;\n\t           xg1min, xg1max, xg2min, xg2max, xgmin, xgmax, cm=0.0,\n         \t   g1bins=100, g2bins=100, gbins=100, norm=true)\n\n\thp, p = hist1d(x, xs, bins, xmin, xmax, norm=norm, legend=true)\n\n    g1p = (xmin = xg1min, xmax = xg1max, nbin=g1bins)\n    g2p = (xmin= xg2min, xmax=  xg2max, nbin=g2bins)\n    gp  = (xmin= xgmin, xmax=  xgmax, nbin=gbins)\n\n    fg  = fit_2gauss_cmean(x, gp, g1p, g2p, cm, norm)\n\tgx  = fg.g[1]\n\tgx1 = fg.g[2]\n\tgx2 = fg.g[3]\n\n\tlbl = @sprintf \"σt =%4.1f mm, σ =%4.1f mm\" fg.std[1] fg.std[2]\n\tst  = @sprintf \"σt =%4.1f mm \" fg.std[1]\n\tsf  = @sprintf \"σ  =%4.1f mm\" fg.std[2]\n    p = plot!(p,fg.X, fg.Y, label=lbl, lw=2, fmt = :png)\n    p = plot!(p,fg.X, gx1.(fg.X), label=st, lw=1, fmt = :png)\n    p = plot!(p,fg.X, gx2.(fg.X), label=sf, lw=1, fmt = :png)\n    #xlabel!(xs)\n    return fg, p\nend\n\n\n\"\"\"\n\tfit_profile(x1, x2, tx1, ty1, fit=\"pol1\", bins=25)\n    fit_profile(df1, c1, c2, tx1, ty1, fit=\"pol1\", bins=25)\nCreate and fit a profile with pol1 or poli2 functions.\nReturn fit parameters, fit function and plot\n\"\"\"\nfit_profile(df1::DataFrame, c1::String, c2::String,\n            tx1::String, ty1::String, fit=\"pol1\", bins=25;\n            ybin_width::Real=0.1, ymin::Real=352.4, ymax::Real=392.4,\n            min_proportion::Real=0.0) =\n\tfit_profile(df1[!,c1], df1[!,c2], tx1, ty1, fit, bins,\n                ybin_width=ybin_width, ymin=ymin, ymax=ymax, min_proportion=min_proportion)\n\n\nfunction fit_profile(x1::Vector{<:Real}, x2::Vector{<:Real},\n\t                 tx1::String, ty1::String, fit=\"pol1\", bins=25;\n                     ybin_width::Real=0.1, ymin::Real=minimum(x2),\n                     ymax::Real=maximum(x2), min_proportion::Real=0.0)\n\n    pdf1, _ = p1df(x1,x2, bins, ybin_width=ybin_width, ymin=ymin, ymax=ymax, min_proportion=min_proportion)\n\n    if fit == \"pol1\"\n        fr = fit_pol1(pdf1.x_mean, pdf1.y_mean)\n    elseif fit == \"pol2\"\n        fr = fit_pol2(pdf1.x_mean, pdf1.y_mean)\n\telseif fit == \"pol3\"\n\t\tfr = fit_pol3(pdf1.x_mean, pdf1.y_mean)\n\telse\n\t\tprintln(\"option not implemented\")\n\t\treturn nothing\n    end\n\n    p1 = scatter(pdf1.x_mean,pdf1.y_mean, yerror=pdf1.y_std,fmt = :png,\n\t          shape = :circle, color = :black, legend=false)\n    p1 = plot!(p1, pdf1.x_mean, fr.g.(pdf1.x_mean), fmt = :png)\n    xlabel!(tx1)\n    ylabel!(ty1)\n\n   return fr, p1\nend\n", "meta": {"hexsha": "77928a6964a6675a30d546b6ba8e18edc793743e", "size": 11164, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fits.jl", "max_stars_repo_name": "jjgomezcadenas/ATools", "max_stars_repo_head_hexsha": "87151dc03d153637f957a0269f7290f752d6ca5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fits.jl", "max_issues_repo_name": "jjgomezcadenas/ATools", "max_issues_repo_head_hexsha": "87151dc03d153637f957a0269f7290f752d6ca5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-09-19T15:35:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T17:46:30.000Z", "max_forks_repo_path": "src/fits.jl", "max_forks_repo_name": "jjgomezcadenas/ATools", "max_forks_repo_head_hexsha": "87151dc03d153637f957a0269f7290f752d6ca5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-01T09:29:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-01T09:29:04.000Z", "avg_line_length": 28.2632911392, "max_line_length": 107, "alphanum_fraction": 0.5965603726, "num_tokens": 4317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7625248564874672}}
{"text": "function log_utility(;β = 0.9,\n                      ψ = 0.69,\n                      Π = 0.5 * ones(2, 2),\n                      G = [0.1, 0.2],\n                      Θ = ones(2),\n                      transfers = false)\n    # Derivatives of utility function\n    U(c,n) = log(c) + ψ * log(1 - n)\n    Uc(c,n) = 1 ./ c\n    Ucc(c,n) = -c.^(-2.0)\n    Un(c,n) = -ψ ./ (1.0 - n)\n    Unn(c,n) = -ψ ./ (1.0 - n).^2.0\n    n_less_than_one = true\n    return Model(β, Π, G, Θ, transfers,\n                 U, Uc, Ucc, Un, Unn, n_less_than_one)\nend", "meta": {"hexsha": "a945e2d7a51805be434b654c0b1cc3140226300c", "size": 534, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "opt_tax_recur/log_utility.jl", "max_stars_repo_name": "QuantEcon/QuantEcon.lectures.code", "max_stars_repo_head_hexsha": "d61ac7bc54529dd5c77470c17539eb2418b047c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2017-05-09T10:45:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:33:27.000Z", "max_issues_repo_path": "opt_tax_recur/log_utility.jl", "max_issues_repo_name": "QuantEcon/QuantEcon.lectures.code", "max_issues_repo_head_hexsha": "d61ac7bc54529dd5c77470c17539eb2418b047c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2017-06-30T01:52:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-01T20:09:47.000Z", "max_forks_repo_path": "opt_tax_recur/log_utility.jl", "max_forks_repo_name": "QuantEcon/QuantEcon.lectures.code", "max_forks_repo_head_hexsha": "d61ac7bc54529dd5c77470c17539eb2418b047c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 117, "max_forks_repo_forks_event_min_datetime": "2017-04-25T16:09:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T02:30:29.000Z", "avg_line_length": 33.375, "max_line_length": 54, "alphanum_fraction": 0.3857677903, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191335436404, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7625231032093038}}
{"text": "# Patrick Keast, MODERATE-DEGREE TETRAHEDRAL QUADRATURE FORMULAS\n# http://mech.fsv.cvut.cz/oofem/resources/doc/oofemrefman/gaussintegrationrule_8C_source.html\nfunction _get_gauss_tetdata(n::Int)\n    if n == 1\n        a = 1. / 4.\n        w = 1. / 6.\n        xw = [a a a w]\n    elseif n == 2\n        a = ( 5. + 3. * √(5.) ) / 20.\n        b = ( 5. - √(5.) ) / 20.\n        w = 1. / 24.\n        xw = [a b b w\n              b a b w\n              b b a w\n              b b b w]\n    elseif n == 3\n        a1 = 1. / 4.\n        a2 = 1. / 2.\n        b2 = 1. / 6.\n        w1 = -2. / 15.\n        w2 = 3. / 40.\n        xw = [a1 a1 a1 w1\n              a2 b2 b2 w2\n              b2 a2 b2 w2\n              b2 b2 a2 w2\n              b2 b2 b2 w2]\n    elseif n == 4\n        a1 = 1. / 4.;\n        w1 = -74. / 5625.;\n\n        a2 = 5. / 70.;\n        b2 = 11. / 14.;\n        w2 = 343. / 45000.;\n\n        a3 = ( 1. + √(5. / 14.) ) / 4.;\n        b3 = ( 1. - √(5. / 14.) ) / 4.;\n        w3 = 28. / 1125.;\n\n        xw = [a1 a1 a1 w1\n              b2 a2 a2 w2\n              a2 b2 a2 w2\n              a2 a2 b2 w2\n              a2 a2 a2 w2\n              a3 a3 b3 w3\n              a3 b3 a3 w3\n              a3 b3 b3 w3\n              b3 a3 a3 w3\n              b3 a3 b3 w3\n              b3 b3 a3 w3]\n    else\n        throw(ArgumentError(\"unsupported order for tetraheder gauss-legendre integration\"))\n    end\n    return xw\nend\n", "meta": {"hexsha": "4eb7b73ffedafdf2676a6aa6404ea81ee4039882", "size": 1393, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Quadrature/gaussquad_tet_table.jl", "max_stars_repo_name": "yijiangh/JuAFEM.jl", "max_stars_repo_head_hexsha": "44827b32e956f1f4abc20fa8e538250b2fc722b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 109, "max_stars_repo_stars_event_min_datetime": "2016-04-04T11:22:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T12:42:03.000Z", "max_issues_repo_path": "src/Quadrature/gaussquad_tet_table.jl", "max_issues_repo_name": "yijiangh/JuAFEM.jl", "max_issues_repo_head_hexsha": "44827b32e956f1f4abc20fa8e538250b2fc722b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 250, "max_issues_repo_issues_event_min_datetime": "2015-09-02T14:33:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-13T09:45:06.000Z", "max_forks_repo_path": "src/Quadrature/gaussquad_tet_table.jl", "max_forks_repo_name": "yijiangh/JuAFEM.jl", "max_forks_repo_head_hexsha": "44827b32e956f1f4abc20fa8e538250b2fc722b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 50, "max_forks_repo_forks_event_min_datetime": "2015-09-04T21:03:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T14:38:18.000Z", "avg_line_length": 25.3272727273, "max_line_length": 93, "alphanum_fraction": 0.384063173, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191271831559, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7625231004255478}}
{"text": "function _source_f(l::AbstractVector, r::AbstractVector, ϵ::Real)\n\n    L = dot(r, l)\n\n    non_normal = r - L * l\n\n    norm_non_normal = sqrt(norm(non_normal) ^ 2 + ϵ ^ 2)\n    nr = sqrt(norm(r) ^ 2 + ϵ ^ 2)\n\n    (l - non_normal * (L / norm_non_normal ^ 2)) / nr\n\nend\n\n\"\"\"\nSource line influence coefficient\n\"\"\"\nfunction source_line(colpt::AbstractVector, r1::AbstractVector, r2::AbstractVector, ϵ::Real)\n\n    l = r2 - r1\n    nl = norm(l) + 1e-10\n    @. l /= nl\n\n    (_source_f(l, colpt - r2, ϵ) - _source_f(l, colpt - r1, ϵ)) / (4 * pi)\n\nend\n\nfunction _gradPhi(r⃗::AbstractVector, ξ⃗::AbstractVector, η⃗::AbstractVector, ϵ::Real)\n\n    rxi = dot(r⃗, ξ⃗)\n    reta = dot(r⃗, η⃗)\n\n    r = sqrt(norm(r⃗) ^ 2 + ϵ ^ 2)\n\n    den = (r ^ 2 - rxi ^ 2 + ϵ ^ 2) * r\n\n    (\n        (rxi * η⃗ + reta * ξ⃗) * den - (den * r⃗ / r ^ 2 + 2 * (r⃗ - rxi * ξ⃗) * r) * rxi * reta\n    ) / den ^ 2\n\nend\n\n\"\"\"\nDoublet line influence coefficient\n\"\"\"\nfunction doublet_line(colpt::AbstractVector, r1::AbstractVector, r2::AbstractVector, η⃗::AbstractVector, ϵ::Real)\n\n    l = r2 - r1\n    nl = norm(l) + 1e-10\n    @. l /= nl\n\n    (_gradPhi(colpt - r2, l, η⃗, ϵ) - _gradPhi(colpt - r1, l, η⃗, ϵ)) / (4 * pi)\n\nend\n\n\"\"\"\nPoint doublet influence coefficient\n\"\"\"\nfunction point_doublet_infl(colpt::AbstractVector, pt::AbstractVector, ξ::AbstractVector, ϵ::Real)\n\n    r = colpt .- pt\n    nr = sqrt(norm(r) ^ 2 + ϵ ^ 2)\n\n    z = ξ ⋅ r\n    nprojr = r .- z .* ξ\n\n    (3 * z) .* nprojr ./ (nr ^ 5 * 4 * π) .- ξ .* ((nr ^ 2 - 3 * z ^ 2) / (4 * π * nr ^ 5))\n\nend\n\n\"\"\"\nPoint source influence coefficient\n\"\"\"\nfunction point_source_infl(colpt::AbstractVector, pt::AbstractVector, ϵ::Real)\n\n    r = colpt .- pt\n\n    r ./ (4 * π * sqrt(norm(r) + ϵ ^ 2) ^ 3)\n\nend\n", "meta": {"hexsha": "15ea1d94a99d0dfc60973571cb41af3829991c0a", "size": 1711, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FuselageAero.jl", "max_stars_repo_name": "Equipe-AeroDesign-ITA/WingBiology", "max_stars_repo_head_hexsha": "9d5d0cb5beaf564cd7fa51a2c02677b32609b7f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-12-02T14:22:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T17:56:39.000Z", "max_issues_repo_path": "src/FuselageAero.jl", "max_issues_repo_name": "Equipe-AeroDesign-ITA/WingBiology", "max_issues_repo_head_hexsha": "9d5d0cb5beaf564cd7fa51a2c02677b32609b7f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-12-31T22:10:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T05:11:50.000Z", "max_forks_repo_path": "src/FuselageAero.jl", "max_forks_repo_name": "Equipe-AeroDesign-ITA/WingBiology", "max_forks_repo_head_hexsha": "9d5d0cb5beaf564cd7fa51a2c02677b32609b7f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3875, "max_line_length": 113, "alphanum_fraction": 0.5534774985, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191259110588, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.7625230856515849}}
{"text": "#\n# 1D bound state energies for a QM particle in an infinite well and potential V(x) \n#\n\n## Definition of the orthonormal basis states \n@everywhere function φ(i) return  function (x) sin(π*i*x) end end\n\n## Coupling strength\n@everywhere λ = 1.0*π^2/4.0\n\n## Definition of the centered harmonic potential V(x)\n@everywhere function V(x) return λ*(x-0.5)^2 end \n\n## Multiply a potential to calculate <φ1|V|φ2> \n@everywhere function Vφ(i) return  function (x) sin(π*i*x)*V(x) end end\n\n## Definition of the inner product <φ1|φ2> \n@everywhere function ∫(φ1::Function,φ2::Function)\n    ψ(x)=φ1(x)*φ2(x)::Float64\n    return 2*quadgk(ψ,0,1,abstol=1e-8)[1]::Float64\nend\n\n##  Infinite well energies \n@everywhere function ɛ(i::Int,j::Int)\n    return  i == j ? i^2 : 0\nend \n\n# The numerical Hamiltonian \nfunction hamiltonian(n::Int)\n  h = SharedArray(Float64,n^2)\n  @sync for j=1:n\n    @parallel for i=j:n\n      h[i+(j-1)*n] = ɛ(i,j) + ∫(φ(i),Vφ(j))::Float64 \n     end\n  end;\n  H = reshape(h,n,n)\n  return H+transpose(H-triu(H))\nend\n\n# The exact Hamiltonian \nfunction hamiltonian_exact(n::Int)\n  return Float64[ i==j? i^2 + (1/12)*λ*(1-6/(i*π)^2) : 0.25*(1+(-1)^(i+j))*(1/(i-j)^2-1/(i+j)^2) for i=1:n,j=1:n ]\nend\n\n## Checking orthonomality \nfunction orthonormal(n::Int)\n    v = SharedArray(Float64,n^2)\n    @sync for j=1:n\n        @parallel for i=j:n\n            v[i+(j-1)*n] = ∫(φ(i),φ(j))::Float64\n        end\n    end; \n    m = reshape(v,n,n)\n    return m+transpose(m-triu(m))\nend\n\nfunction main(n::Int) \n   @time println(\"norm of difference = \", norm(eigvals(hamiltonian(n))-eigvals(hamiltonian_exact(n))))\nend\n\nmain(400)\n\n\n", "meta": {"hexsha": "5e975a43dfabe63922cf526da6f29179b8ba6907", "size": 1612, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "qmbs1d.jl", "max_stars_repo_name": "lmelwyn/julia-demo", "max_stars_repo_head_hexsha": "c146d7575d3aa831ccc9395583914bba09d045cb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qmbs1d.jl", "max_issues_repo_name": "lmelwyn/julia-demo", "max_issues_repo_head_hexsha": "c146d7575d3aa831ccc9395583914bba09d045cb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qmbs1d.jl", "max_forks_repo_name": "lmelwyn/julia-demo", "max_forks_repo_head_hexsha": "c146d7575d3aa831ccc9395583914bba09d045cb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1875, "max_line_length": 114, "alphanum_fraction": 0.635235732, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191246389618, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.762523084636214}}
{"text": "## linear.jl : implementation of linear covariance function\n\n## Linear ##\nstruct Linear{T} <: IsotropicCovarianceStructure{T}\n    λ::T\n    σ::T\n    p::T\n\n    function Linear{T}(λ::T, σ::T, p::T) where T\n        λ > 0 || throw(DomainError(λ, \"correlation length λ of linear covariance cannot be negative or zero\"))\n        σ > 0 || throw(DomainError(σ, \"marginal standard deviation σ of linear covariance cannot be negative or zero\"))\n        p >= 1 || throw(DomainError(p, \"in p-norm, p must be greater than or equal to 1\"))\n        isinf(p) && throw(DomainError(p, \"in p-norm, p cannot be infinity\"))\n\n        new{T}(λ, σ, p)\n    end\nend\n\n\"\"\"\n    Linear(λ, [σ = 1], [p = 2])\n\nLinear covariance structure with correlation length `λ`, (optional) marginal standard deviation `σ` and (optional) `p`-norm, defined as\n\n``C(x, y) = \\\\begin{cases} σ \\\\left(1 - \\\\displaystyle\\\\frac{ρ}{λ}\\\\right) & \\\\text{if }ρ ≤ λ\\\\\\\\ 0 & \\\\text{if }ρ>λ\\\\end{cases}``\n\nwith ``ρ = ||x - y||_p``.\n\n# Examples\n```jldoctest\njulia> Linear(0.1)\nlinear (λ=0.1, σ=1.0, p=2.0)\n\njulia> Linear(1.0, σ=2)\nlinear (λ=1.0, σ=2.0, p=2.0)\n\n```\nSee also: [`Exponential`](@ref), [`Spherical`](@ref), [`Whittle`](@ref), [`Gaussian`](@ref), [`SquaredExponential`](@ref), [`Matern`](@ref)\n\"\"\"\nLinear(λ::Real; σ::Real=1.0, p::Real=2) = Linear{promote_type(typeof(λ),typeof(σ),typeof(p))}(promote(λ, σ, p)...)\n\n# evaluate exponential covariance\napply(l::Linear, x::Real) = max(zero(x), 1 - x / l.λ)\n\n# short name\nshortname(::Linear) = \"linear\"\n", "meta": {"hexsha": "894032b6eceefa2ba4f2c7d53f55e98296466d3c", "size": 1497, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/covariance_functions/linear.jl", "max_stars_repo_name": "Philippe1123/GaussianRandomFields.jl", "max_stars_repo_head_hexsha": "86ae443ae46d27a45d4afcdceb453c48cbfd9807", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2018-02-01T10:43:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:29:00.000Z", "max_issues_repo_path": "src/covariance_functions/linear.jl", "max_issues_repo_name": "Philippe1123/GaussianRandomFields.jl", "max_issues_repo_head_hexsha": "86ae443ae46d27a45d4afcdceb453c48cbfd9807", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2018-01-17T18:32:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T07:14:13.000Z", "max_forks_repo_path": "src/covariance_functions/linear.jl", "max_forks_repo_name": "Philippe1123/GaussianRandomFields.jl", "max_forks_repo_head_hexsha": "86ae443ae46d27a45d4afcdceb453c48cbfd9807", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-08-01T17:13:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T11:19:26.000Z", "avg_line_length": 32.5434782609, "max_line_length": 139, "alphanum_fraction": 0.6132264529, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.7624989972378894}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.0\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 15b8afb9-ace9-4b5b-894e-dce9dda5bf5f\nbegin\n\tusing Pkg\n\t\n\ttry\n\t\tusing UnicodePlots\n\t\t\n\tcatch ArgumentError\n\t\tPkg.add(\"UnicodePlots\")\n\t\tusing UnicodePlots\n\tend\n\t\n\tusing Test\n\tusing PlutoUI\nend\n\n# ╔═╡ 45d72214-919c-11eb-2e69-23c0786baacb\nmd\"\"\"\n### Functional Programming\n\nSrc: [Julia 1.0 Cookbook -  Bogumił Kamiński , Przemysław Szufel - 2018](https://www.packtpub.com/product/julia-1-0-programming-cookbook/9781788998369)\n\"\"\"\n\n# ╔═╡ 6d80a12a-9649-4438-9a12-36003a57bf86\nfunction deriv(f::Function)::Function\n\th = √eps()\n\tdf(x) = (f(x + h) - f(x)) / h\n\tdf\nend\n\n# ╔═╡ 5e5c6b37-f3ee-42b1-94cc-686d54171833\nmd\"\"\"\nLet us test the `deriv` function. We will use the `UnicodePlots.jl` package to plot a $2×x×x + 5×x - 4$ function and its derivative. \n\"\"\"\n\n# ╔═╡ b3faae61-dcdc-473d-9a06-cc890ae74bd7\nbegin\n\tf(x) = 2x*x + 5x - 4\n\tx = -5.:3.;\nend\n\n# ╔═╡ 75442ce9-cf92-4800-b1aa-bfdd4229224c\nbegin\n\tplot = lineplot(x, f.(x), width=45, height=15, canvas=DotCanvas, name=\"f(x)\");\n\tplot = lineplot!(plot, x, deriv(f).(x), name=\"f'(x)\")\nend\n\n# ╔═╡ a2db212a-02f8-493c-a1f2-43c0e63c31fa\nmd\"\"\"\nNext, we can construct a function that solves any quadratic equation in the form\n\n$$ax^2 + bx +c = 0$$\n\"\"\"\n\n# ╔═╡ 415677ce-d5d6-4808-8789-f5fa66d7f7df\nfunction q_solve(f)\n\tc = f(0.)\n\tf1 = deriv(f)\n\tb = f1(0.) \n\ta = f(1,) - b - c\n\td = √(b * b - 4 * a * c)\n\t((-b - d) / 2a, -(-b + d) / 2a)\nend\n\n# ╔═╡ bd8d4613-c666-41e3-b877-e9ed6882fe04\n@test q_solve(x -> (x - 1) * (x + 7)) == (-7., -1.)\n\n# ╔═╡ b3ee6944-32c7-4dca-ab51-9f1dc0accd91\n@test_throws DomainError q_solve(x -> x * x + 1)  ## no solution in the real domain\n\n# ╔═╡ 6486f3b7-9a29-41d1-8d80-514a9212a174\nwith_terminal() do\n\tprintln(q_solve(x -> x * x + 1 + 0im)) \n\t## (-7.450580707946e-9 - 1.0000000074505im, 7.450580707946e-9 - 1.0000000074505im)\nend\n\n# ╔═╡ 75a80d9a-953e-41c0-9569-2f1c08ca16cd\nmd\"\"\"\nOur quadratic solver function takes any quadratic function as its argument. Such functions can be presented as $f(x) = a×x^2 + b×x + c$, and we calculate $f(0)$ to get the $c$ value. \nNext, we calculate `deriv(f)(0)`, which is $(2×a×x + b)(0)$, and hence obtain a numerical approximation of the value of b. \nFinally, we calculate a, and now we can calculate root values of the `f` function. \n\nSince we did not specify types, our function works not only for real numbers but also for complex numbers. \nThis can be observed when comparing the calls `q_solve(x -> x*x + 1)` and \n`q_solve(x -> x*x + 1 + 0im)`. \nThe first one fails because `x × x + 1` does not have a solution in the real domain. On the other hand - the second one - using complex numbers, works.\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─45d72214-919c-11eb-2e69-23c0786baacb\n# ╠═15b8afb9-ace9-4b5b-894e-dce9dda5bf5f\n# ╠═6d80a12a-9649-4438-9a12-36003a57bf86\n# ╟─5e5c6b37-f3ee-42b1-94cc-686d54171833\n# ╠═b3faae61-dcdc-473d-9a06-cc890ae74bd7\n# ╠═75442ce9-cf92-4800-b1aa-bfdd4229224c\n# ╟─a2db212a-02f8-493c-a1f2-43c0e63c31fa\n# ╠═415677ce-d5d6-4808-8789-f5fa66d7f7df\n# ╠═bd8d4613-c666-41e3-b877-e9ed6882fe04\n# ╠═b3ee6944-32c7-4dca-ab51-9f1dc0accd91\n# ╠═6486f3b7-9a29-41d1-8d80-514a9212a174\n# ╟─75a80d9a-953e-41c0-9569-2f1c08ca16cd\n", "meta": {"hexsha": "0e3f515a7423f68baac8aa795ac7f0b1aad56431", "size": 3191, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia_Investigation/cb06-FP.jl", "max_stars_repo_name": "pascal-p/julia-notebooks", "max_stars_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-01T20:34:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-01T20:34:56.000Z", "max_issues_repo_path": "Julia_Investigation/cb06-FP.jl", "max_issues_repo_name": "pascal-p/julia-notebooks", "max_issues_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia_Investigation/cb06-FP.jl", "max_forks_repo_name": "pascal-p/julia-notebooks", "max_forks_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-10T09:03:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T09:03:18.000Z", "avg_line_length": 29.5462962963, "max_line_length": 183, "alphanum_fraction": 0.6853650893, "num_tokens": 1438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.8740772450055544, "lm_q1q2_score": 0.7624989783433209}}
{"text": "# The number, 197, is called a circular prime because all rotations of the\n# digits: 197, 971, and 719, are themselves prime.\n#\n# There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71,\n# 73, 79, and 97.\n#\n# How many circular primes are there below one million?\n\nusing ProjectEulerSolutions\n\n# Helper function to generate an array of circular shifts given an input\n# integer.\nfunction circularnumbers(n::Integer)::Array{Integer}\n    digs = digits(n)\n    numdigits = length(digs)\n    multipliers = 10 .^ (0:numdigits-1)\n\n    circular_nums = Integer[]\n    for i in 1:numdigits-1\n        push!(circular_nums, sum(multipliers .* circshift(digs, i)))\n    end\n    return circular_nums\nend\n\n# Use Sieve of Eratosthenes to get primes, store in set, then cycle through\n# them creating circular shifts and checking whether all shifts are prime.  If\n# so, perform some set magic to move those primes into the verified set and\n# remove from the potential circular primes set.\nfunction p035solution(n::Integer=100)::Integer\n    primes = Set{Integer}(sieve_eratosthenes(n))\n    verified = Set{Integer}()\n\n    for prime in primes\n        if ndigits(prime) == 1\n            push!(verified, prime)\n        else\n            if mapreduce(x-> x % 2, *, digits(prime)) == 0\n                # If any digit is even, ignore number\n                continue\n            end\n\n            circnums = circularnumbers(prime)\n            if mapreduce(prime -> in(prime, primes), &, circnums)\n                push!(verified, prime)\n                union!(verified, circnums)\n                delete!(primes, prime)\n                setdiff!(primes, circnums)\n            end\n        end\n    end\n\n    return length(verified)\nend\n\np035 = Problems.Problem(p035solution)\n\nProblems.benchmark(p035, 1_000_000)", "meta": {"hexsha": "e8af46cbb63b536986b78626d6bd9115dbe8c0fe", "size": 1791, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/035.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/035.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/035.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4210526316, "max_line_length": 79, "alphanum_fraction": 0.6448911223, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897558991953, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.7624902611094092}}
{"text": "# Solves the Poisson equation using the Mixed finite element method \nusing Revise\nusing AdFem\nusing DelimitedFiles\nusing SparseArrays\nusing PyPlot\n\n\nn = 50\nmmesh = Mesh(n, n, 1/n, degree = BDM1)\n\nfunction ufunc(x, y)\n    x * (1-x) * y * (1-y)\nend\n\nfunction ffunc(x, y)\n    -2x*(1-x) -2y*(1-y)\nend\n\nfunction gfunc(x, y)\n    (1-2x)*y*(1-y)\nend\n\nA = compute_fem_bdm_mass_matrix1(mmesh)\nB = compute_fem_bdm_div_matrix1(mmesh)\nC = [A -B'\n    -B spzeros(mmesh.nelem, mmesh.nelem)]\n\ngD = (x1, y1, x2, y2)->!( (x1<1e-3 && y1>1e-3 && y1<1-1e-3) ||  (x2<1e-3 && y2>1e-3 && y2<1-1e-3))\ngN = (x1, y1, x2, y2)->x1<1e-5 && x2<1e-5\n\nD_bdedge = bcedge(gD, mmesh)\nN_bdedge = bcedge(gN, mmesh)\n\nt1 = eval_f_on_boundary_edge(ufunc, D_bdedge, mmesh)\ng = compute_fem_traction_term1(t1, D_bdedge, mmesh) \nt2 = eval_f_on_gauss_pts(ffunc, mmesh)\nf = compute_fvm_source_term(t2, mmesh)\n\ngN = eval_f_on_boundary_edge(gfunc, N_bdedge, mmesh)\ndof, val = impose_bdm_traction_boundary_condition1(gN, N_bdedge, mmesh)\nrhs = [-g; f]\nC, rhs = impose_Dirichlet_boundary_conditions(C, rhs, dof, val)\n\nsol = C\\rhs\nu = sol[mmesh.ndof+1:end]\nclose(\"all\")\nfigure(figsize=(15, 5))\nsubplot(131)\ntitle(\"Reference\")\nxy = fvm_nodes(mmesh)\nx, y = xy[:,1], xy[:,2]\nuf = ufunc.(x, y)\nvisualize_scalar_on_fvm_points(uf, mmesh)\nsubplot(132)\ntitle(\"Numerical\")\nvisualize_scalar_on_fvm_points(u, mmesh)\nsubplot(133)\ntitle(\"Absolute Error\")\nvisualize_scalar_on_fvm_points( abs.(u - uf) , mmesh)\nsavefig(\"mixed_poisson_neumann.png\")\n", "meta": {"hexsha": "716a53568b2d47bedeb5c8ed74198b6df751f2ef", "size": 1480, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/snippets/BDM/poisson_neumann.jl", "max_stars_repo_name": "kailaix/AdFem.jl", "max_stars_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2020-10-18T01:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:13:24.000Z", "max_issues_repo_path": "docs/src/snippets/BDM/poisson_neumann.jl", "max_issues_repo_name": "kailaix/AdFem.jl", "max_issues_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-10-19T03:51:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:38:46.000Z", "max_forks_repo_path": "docs/src/snippets/BDM/poisson_neumann.jl", "max_forks_repo_name": "kailaix/AdFem.jl", "max_forks_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-11-05T11:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T19:30:09.000Z", "avg_line_length": 23.8709677419, "max_line_length": 98, "alphanum_fraction": 0.697972973, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8104789109591831, "lm_q1q2_score": 0.7624902541117506}}
{"text": "using Distributions\n\nfunction sliceSampleStep(logf, x0, y0, w=1.0)\n    newy = y0 + log(rand())\n\n    # step outward\n    L = x0 - w * rand()\n    R = L + w\n    yL = logf(L)\n    yR = logf(R)\n    while yL > newy || yR > newy\n        if rand(Bool)\n            L -= R - L\n            yL = logf(L)\n        else\n            R += R - L\n            yR = logf(L)\n        end\n    end\n\n    #Step inward\n    x = rand(Uniform(L, R))\n    y = logf(x)\n    while y < newy\n        if x < x0\n            L = x\n            yL = logf(L)\n        else\n            R = x\n            yR = logf(R)\n        end\n        x = rand(Uniform(L, R))\n        y = logf(x)\n    end\n\n    return (x, y)\nend\n\n\nfunction sliceSample(logf, n, x0=0.0, y0=0.0, w=1.0)\n    (x,y) = (x0,logf(x0))\n    xs = zeros(n)\n    for i in 1:n \n        (x,y) = sliceSampleStep(logf, x, y, w)\n        xs[i] = x\n    end\n\n    return xs\nend\n\nfunction test(n)\n    sliceSample(x -> logpdf(Normal(),x), n)\nend\n\nx = test(10000)\nscatter(x[2:10000],x[1:9999],α=0.1)", "meta": {"hexsha": "f70e331e4fe3cda2de02ac33b978d4e1c883bf50", "size": 991, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Slice.jl", "max_stars_repo_name": "JuliaTagBot/RandomSamplers.jl", "max_stars_repo_head_hexsha": "c87d50c541e8d8f3f297b54e5b084902ee456247", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Slice.jl", "max_issues_repo_name": "JuliaTagBot/RandomSamplers.jl", "max_issues_repo_head_hexsha": "c87d50c541e8d8f3f297b54e5b084902ee456247", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Slice.jl", "max_forks_repo_name": "JuliaTagBot/RandomSamplers.jl", "max_forks_repo_head_hexsha": "c87d50c541e8d8f3f297b54e5b084902ee456247", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:06:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:06:18.000Z", "avg_line_length": 17.6964285714, "max_line_length": 52, "alphanum_fraction": 0.4439959637, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7624902524988052}}
{"text": "# MIT license\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# See LICENSE in the project root for full license information.\n\n\"\"\"\nModule to enclose [Zernike polynomial](https://en.wikipedia.org/wiki/Zernike_polynomials) specific functionality.\n\"\"\"\nmodule Zernike\n\n\"\"\"\n    OSAtoNM(j::Int) -> Tuple{Int, Int}\n\nConvert OSA zernike index `j` to `(N,M)` form according to formula `J = N * (N + 2) + M`.\n\"\"\"\nfunction OSAtoNM(j::Int)::Tuple{Int, Int}\n    n = Int(ceil((-3 + sqrt(9 + 8j)) / 2))\n    m = 2j - n * (n + 2)\n    return (Int(n), Int(m))\nend\n\n\"\"\"\n    NolltoNM(j::Int) -> Tuple{Int, Int}\n\nConvert Noll zernike index `j` to `(N,M)` form.\n\"\"\"\nfunction NolltoNM(j::Int)\n    n = Int(ceil((-3 + sqrt(1 + 8j)) / 2))\n    jr = j - Int(n * (n + 1) / 2)\n    if mod(n, 4) ∈ (0, 1)\n        m1 = jr\n        m2 = -(jr - 1)\n        if iseven(n - m1)\n            m = m1\n        else\n            m = m2\n        end\n    else # mod(n,4) ∈ (2,3)\n        m1 = jr - 1\n        m2 = -(jr)\n        if iseven(n - m1)\n            m = m1\n        else\n            m = m2\n        end\n    end\n    return (Int(n), Int(m))\nend\n\n\"\"\"\n    normalisation(::Type{T}, N::Int, M::Int) -> T\n\nNormalisation coefficient for Zernike polynomial term ``Z_{n}^{m}``.\n\"\"\"\n@inline function normalisation(::Type{T}, N::Int, M::Int) where {T <: Real}\n    return T(sqrt((2 * (N + 1)) / (1 + (M == 0 ? 1 : 0))))\nend\n\n\"\"\"\n    ζ(N::Int, M::Int, ρ::T, ϕ::T) -> Tuple{T,T}\n\nEvaluate Zernike polynomial term ``Z_{n}^{m}(\\\\rho, \\\\phi)``.\n\"\"\"\n@inline function ζ(N::Int, M::Int, ρ::T, ϕ::T)::T where {T <: Real}\n    aM = abs(M)\n    if M < 0\n        return normalisation(T, N, M) * R(N, aM, ρ) * sin(aM * ϕ)\n    else\n        return normalisation(T, N, M) * R(N, aM, ρ) * cos(aM * ϕ)\n    end\nend\n\n\"\"\"\n    δζ(N::Int, M::Int, ρ::T, ϕ::T) -> Tuple{T,T}\n\nEvaluate partial derivatives of Zernike polynomial term ``Z_{n}^{m}(\\\\rho, \\\\phi)``.\n\"\"\"\n@inline function δζ(N::Int, M::Int, ρ::T, ϕ::T)::Tuple{T, T} where {T <: Real}\n    n = normalisation(T, N, M)\n    aM = abs(M)\n    RNM = R(N, aM, ρ)\n    ρ2 = ρ^2\n    δRNM =\n        (\n            (2 * N * aM * (ρ2 - 1) + (N - aM) * (aM + N * (2 * ρ2 - 1))) * RNM -\n            (N + aM) * (N - aM) * R(N - 2, aM, ρ)\n        ) / (2 * N * ρ * (ρ2 - 1))\n    Mϕ = aM * ϕ\n    if M < 0\n        δρ = n * δRNM * sin(Mϕ)\n        δϕ = n * RNM * aM * cos(Mϕ)\n    else\n        δρ = n * δRNM * cos(Mϕ)\n        δϕ = n * RNM * aM * -sin(Mϕ)\n    end\n    return δρ, δϕ\nend\n\n\"\"\"\n    R(N::Int, M::Int, ρ::T) -> T\n\nEvaluate radial polynomial ``R_{n}^{m}(\\\\rho)``.\n\"\"\"\n@inline function R(N::Int, M::Int, ρ::T)::T where {T <: Real}\n    if (N - M) % 2 === 1\n        return zero(T)\n    end\n    total = zero(T)\n    @simd for k in 0:((N - M) ÷ 2)\n        total +=\n            ((-1)^k * factorial(N - k)) / (\n                factorial(k) *\n                factorial((N + M) ÷ 2 - k) *\n                factorial((N - M) ÷ 2 - k)\n            ) * ρ^(N - 2 * k)\n    end\n    return total\nend\n\nend # module Zernike\n\n#########################################################################################################\n\n\"\"\"\nEither `ZernikeIndexingOSA` or `ZernikeIndexingNoll`, see [Zernike polynomials wikipedia entry](https://en.wikipedia.org/wiki/Zernike_polynomials) for details.\n\"\"\"\n@enum ZernikeIndexType ZernikeIndexingOSA ZernikeIndexingNoll\n\n\"\"\"\n    ZernikeSurface{T,N,P,Q,M} <: ParametricSurface{T,N}\n\nSurface incorporating the Zernike polynomials - radius, conic and aspherics are defined relative to absolute semi-diameter, Zernike terms are normalized according to the `normradius` parameter.\n`T` is the datatype, `N` is the dimensionality, `P` is the number of Zernike terms, `Q` is the number of aspheric terms and `M` is the Aspheric Type.\n\nThe surface is centered at the origin and treated as being the cap of an infinite cylinder, thus creating a true half-space.\nOutside of `0 <= ρ <= 1` the height of the surface is not necessarily well defined, so NaN may be returned.\n\nFor convenience the input `zcoeff` can be indexed using either OSA or Noll convention, indicated using the `indexing` argument as either `ZernikeIndexingOSA` or `ZernikeIndexingNoll`.\n\n```julia\nZernikeSurface(semidiameter, radius = Inf, conic = 0, zcoeff = nothing, aspherics = nothing, normradius = semidiameter, indexing = ZernikeIndexingOSA)\n```\n\n`zcoeff` and `aspherics` should be vectors containing tuples of the form `(i, v)` where `i` is either the index of the Zernike term\nfor the corresponding `indexing`, or the polynomial power of the aspheric term (may be even or odd) and \n`v` is the corresponding coefficient ``A_i`` or ``\\\\alpha_i`` respectively..  `M` will be determined from the terms entered to optimize\nthe evaluation of the aspheric polynomial.\n\nThe sag is defined by the equation\n\n```math\nz(r,\\\\phi) = \\\\frac{cr^2}{1 + \\\\sqrt{1 - (1+k)c^2r^2}} + \\\\sum_{i}^{Q}\\\\alpha_ir^{2i} + \\\\sum_{i}^PA_iZ_i(\\\\rho, \\\\phi)\n```\n\nwhere ``\\\\rho = \\\\frac{r}{\\\\texttt{normradius}}``, ``c = \\\\frac{1}{\\\\texttt{radius}}``, ``k = \\\\texttt{conic}`` and ``Z_n`` is the nᵗʰ Zernike polynomial.\n\"\"\"\nstruct ZernikeSurface{T, N, P, Q, M} <: ParametricSurface{T, N}\n    asp::AsphericSurface{T, N, Q, M}\n    coeffs::SVector{P, Tuple{Int, Int, T}}\n    boundingcylinder::Cylinder{T, N}\n\n    function ZernikeSurface(\n        semidiameter::T;\n        radius::T = typemax(T),\n        conic::T = zero(T),\n        zcoeff::Union{Nothing, Vector{Tuple{Int, T}}} = nothing,\n        aspherics::Union{Nothing, Vector{Tuple{Int, T}}} = nothing,\n        normradius::T = semidiameter,\n        indexing::ZernikeIndexType = ZernikeIndexingOSA,\n    ) where {T <: Real}\n        asp =\n            AsphericSurface(semidiameter; radius, conic, aspherics, normradius)\n        Q = length(asp.aspherics) #this is not the same as the aspherics variable passed to the function!\n\n        zcs = []\n        if zcoeff !== nothing\n            for (i, k) in zcoeff\n                if abs(k) > zero(T)\n                    if indexing === ZernikeIndexingOSA\n                        R, S = Zernike.OSAtoNM(i)\n                    else\n                        R, S = Zernike.NolltoNM(i)\n                    end\n                    push!(zcs, (R, S, k))\n                end\n            end\n        end\n        P = length(zcs)\n        M = asphericType(asp)\n        return new{T, 3, P, Q, M}(\n            asp::AsphericSurface{T, 3, Q, M},\n            SVector{P, Tuple{Int, Int, T}}(zcs),\n            Cylinder(semidiameter, interface = opaqueinterface(T)),\n        ) # TODO!! incorrect interface on cylinder\n    end\nend\n\nfunction uvrange(\n    ::Type{ZernikeSurface{T, N, P, Q, M}},\n) where {T <: Real, N, P, Q, M}\n    return ((zero(T), one(T)), (-T(π), T(π)))\nend # ρ and ϕ\n\nsemidiameter(z::ZernikeSurface{T}) where {T <: Real} = z.asp.semidiameter\nhalfsizeu(z::ZernikeSurface{T}) where {T <: Real} = semidiameter(z)\nhalfsizev(z::ZernikeSurface{T}) where {T <: Real} = semidiameter(z)\n\nboundingobj(z::ZernikeSurface{T}) where {T <: Real} = z.boundingcylinder\n\nfunction point(\n    z::ZernikeSurface{T, 3, P, Q, M},\n    ρ::T,\n    ϕ::T,\n)::SVector{3, T} where {T <: Real, P, Q, M}\n    pnt = point(z.asp, ρ, ϕ)\n\n    # sum zernike\n    rad = semidiameter(z.asp)\n    r = ρ * rad\n    u = r / z.asp.normradius\n    h = zero(T)\n    @inbounds @simd for m in 1:P\n        (R, S, k) = z.coeffs[m]\n        h += k * Zernike.ζ(R, S, u, ϕ)\n    end\n    return SVector{3, T}(pnt[1], pnt[2], pnt[3] + h)\nend\n\nfunction partials(\n    z::ZernikeSurface{T, 3, P, Q, M},\n    ρ::T,\n    ϕ::T,\n)::Tuple{SVector{3, T}, SVector{3, T}} where {T <: Real, P, Q, M}\n    pρ, pϕ = partials(z.asp, ρ, ϕ)\n    # sum zernike partials\n    rad = z.asp.semidiameter\n    n = rad / z.asp.normradius\n    u = ρ * n\n    dhdρ = zero(T)\n    dhdϕ = zero(T)\n    @inbounds @simd for m in 1:P\n        (R, S, k) = z.coeffs[m]\n        du, dϕ = Zernike.δζ(R, S, u, ϕ)\n        dhdρ += k * du * n # want the derivative wrt ρ, not u\n        dhdϕ += k * dϕ\n    end\n    return SVector{3, T}(pρ[1], pρ[2], pρ[3] + dhdρ),\n    SVector{3, T}(pϕ[1], pϕ[2], pϕ[3] + dhdϕ)\nend\n\nfunction normal(\n    z::ZernikeSurface{T, 3, P, Q, M},\n    ρ::T,\n    ϕ::T,\n)::SVector{3, T} where {T <: Real, P, Q, M}\n    du, dv = partials(z, ρ, ϕ)\n    if ρ == zero(T) && norm(dv) == zero(T)\n        # in cases where there is no δϕ at ρ = 0 (i.e. anything which is rotationally symetric)\n        # then we get some big problems, hardcoding this case solves the problems\n        return SVector{3, T}(0, 0, 1)\n    end\n    return normalize(cross(du, dv))\nend\n\nfunction uv(\n    z::ZernikeSurface{T, 3, P, Q, M},\n    p::SVector{3, T},\n) where {T <: Real, P, Q, M}\n    # avoid divide by zero for ForwardDiff\n    ϕ = NaNsafeatan(p[2], p[1])\n    if p[1] == zero(T) && p[2] == zero(T)\n        ρ = zero(T)\n    else\n        ρ = sqrt(p[1]^2 + p[2]^2) / semidiameter(z)\n    end\n    return SVector{2, T}(ρ, ϕ)\nend\n\nfunction onsurface(\n    surf::ZernikeSurface{T, 3, P, Q, M},\n    p::SVector{3, T},\n) where {T <: Real, P, Q, M}\n    ρ, ϕ = uv(surf, p)\n    if ρ > one(T)\n        return false\n    else\n        surfpoint = point(surf, ρ, ϕ)\n        return samepoint(p[3], surfpoint[3])\n    end\nend\n\nfunction inside(\n    surf::ZernikeSurface{T, 3, P, Q, M},\n    p::SVector{3, T},\n) where {T <: Real, P, Q, M}\n    ρ, ϕ = uv(surf, p)\n    if ρ > one(T)\n        return false\n    else\n        surfpoint = point(surf, ρ, ϕ)\n        return p[3] < surfpoint[3]\n    end\nend\n\n#########################################################################################################\n\n# Assumes the ray has been transformed into the canonical coordinate frame which has the vertical axis passing through (0,0,0) and aligned with the z axis.\nfunction surfaceintersection(\n    surf::AcceleratedParametricSurface{T, 3, ZernikeSurface{T, 3, P, Q, M}},\n    r::AbstractRay{T, 3},\n) where {T <: Real, P, Q, M}\n    cylint = surfaceintersection(surf.surface.boundingcylinder, r)\n    if cylint isa EmptyInterval{T}\n        return EmptyInterval(T)\n    else\n        if doesintersect(surf.triangles_bbox, r) ||\n           inside(surf.triangles_bbox, origin(r))\n            surfint = triangulatedintersection(surf, r)\n            if !(surfint isa EmptyInterval{T})\n                return intervalintersection(cylint, surfint)\n            end\n        end\n        # hasn't hit the surface\n        if lower(cylint) isa RayOrigin{T} && upper(cylint) isa Infinity{T}\n            if inside(surf.surface, origin(r))\n                return Interval(RayOrigin(T), Infinity(T))\n            else\n                return EmptyInterval(T)\n            end\n            # otherwise check that the intersection is underneath the surface\n        else\n            p = point(closestintersection(cylint, false))\n            ρ, ϕ = uv(surf, p)\n            surfpoint = point(surf.surface, ρ, ϕ)\n            if p[3] < surfpoint[3]\n                return cylint # TODO!! UV (and interface) issues?\n            else\n                return EmptyInterval(T)\n            end\n        end\n    end\nend\n\nfunction AcceleratedParametricSurface(\n    surf::T,\n    numsamples::Int = 17;\n    interface::NullOrFresnel{S} = NullInterface(S),\n) where {S <: Real, N, T <: ZernikeSurface{S, N}}\n    # Zernike uses ρ, ϕ uv space so need to modify extension of triangulation\n    a = AcceleratedParametricSurface(\n        surf,\n        triangulate(surf, numsamples, true, false, true, false),\n        interface = interface,\n    )\n    emptytrianglepool!(S)\n    return a\nend\n\nfunction BoundingBox(\n    surf::ZernikeSurface{T, 3, P, Q, M},\n) where {T <: Real, P, Q, M}\n    bb = BoundingBox(surf.asp)\n    # zernike terms have condition than |Zᵢ| <= 1\n    # so this gives us a (loose) bounding box\n    ak = if P > 0\n        sum(abs.(Zernike.normalisation(T, n, m) * k for (n, m, k) in surf.coeffs))\n    else\n        zero(T)\n    end\n    bb.zmin -= ak\n    bb.zmax += ak\n    return BoundingBox(bb.xmin, bb.xmax, bb.ymin, bb.ymax, bb.zmin, bb.zmax) #could just return bb, but this way is safer\nend\n", "meta": {"hexsha": "9b2fd6f92084059009d8900d8731251c85d1b715", "size": 11901, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Geometry/Primitives/Zernike.jl", "max_stars_repo_name": "casparvitch/ArtefactModelling.jl", "max_stars_repo_head_hexsha": "bc191871287036706186a69a64b27ed3bd6e9b32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Geometry/Primitives/Zernike.jl", "max_issues_repo_name": "casparvitch/ArtefactModelling.jl", "max_issues_repo_head_hexsha": "bc191871287036706186a69a64b27ed3bd6e9b32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Geometry/Primitives/Zernike.jl", "max_forks_repo_name": "casparvitch/ArtefactModelling.jl", "max_forks_repo_head_hexsha": "bc191871287036706186a69a64b27ed3bd6e9b32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9061662198, "max_line_length": 193, "alphanum_fraction": 0.556591883, "num_tokens": 3943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7624902514207657}}
{"text": "@valueequals struct Circle\n    x::Number\n    y::Number\n\n    r::Number\n\n    Circle(x::Number, y::Number, r::Number) = new(x, y, r)\n    Circle(x1::Number, y1::Number, x2::Number, y2::Number) = new(x1, y1, sqrt((x1 - x2)^2 + (y1 - y2)^2))\nend\n\nfunction circumference(circle::Circle)\n    return 2 * pi * circle.r\nend\n\n# Efficient enough, checks might be too small for huge circles\nfunction pointsOnCircle(circle::Circle; filled::Bool=false, checks::Int=max(1, ceil(Int, circumference(circle))))\n    res = Set{Tuple{Number, Number}}()\n    step = 2 * pi / checks\n\n    if checks > 0\n        for theta in 0:step:2 * pi\n            ox = cos(theta) * circle.r\n            oy = sin(theta) * circle.r\n\n            push!(res, (round(Int, circle.x + ox), round(Int, circle.y + oy)))\n            push!(res, (round(Int, circle.x - ox), round(Int, circle.y + oy)))\n\n            if filled\n                for i in floor(Int, -ox + 1):ceil(Int, ox - 1)\n                    push!(res, (round(Int, circle.x + i), round(Int, circle.y + oy)))\n                end\n            end\n        end\n    end\n\n    return collect(res)\nend", "meta": {"hexsha": "d6a858046ad339b21e5a1046397e99769c1ecb75", "size": 1104, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/shapes/circle.jl", "max_stars_repo_name": "CelestialCartographers/Ahorn", "max_stars_repo_head_hexsha": "f62f882a851385002a8f9aeb95fc439567d3c4dc", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 170, "max_stars_repo_stars_event_min_datetime": "2018-05-18T19:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:42:34.000Z", "max_issues_repo_path": "src/shapes/circle.jl", "max_issues_repo_name": "CelestialCartographers/Ahorn", "max_issues_repo_head_hexsha": "f62f882a851385002a8f9aeb95fc439567d3c4dc", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2018-08-05T12:57:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-07T09:47:17.000Z", "max_forks_repo_path": "src/shapes/circle.jl", "max_forks_repo_name": "CelestialCartographers/Ahorn", "max_forks_repo_head_hexsha": "f62f882a851385002a8f9aeb95fc439567d3c4dc", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2018-05-18T21:37:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T22:36:04.000Z", "avg_line_length": 29.8378378378, "max_line_length": 113, "alphanum_fraction": 0.5561594203, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.8104789132480439, "lm_q1q2_score": 0.7624902508831171}}
{"text": "# GMM estimation for a sample from Chi^2(theta)\n# compare to two method of moments estimators (see chi2mm.m)\nusing Econometrics, Random, Distributions, Plots\nfunction main()\nn = 30\ntheta = 3.0\nreps = 1000\nresults = zeros(reps,2)\n\ny = zeros(n) # this is just a place holder to define the moments, below\n# define the moment conditions\nm = theta -> [(theta.- y) (theta .- 0.5*(y .- theta).^2.0)] \nfor i = 1:1000\n    rand!(Chisq(theta), y) # this replaces the place holder, from above\n    thetahat, junk, junk, ms, junk = gmm(m, [3.0], eye(2))\n    results[i,1] = sqrt(n)*(thetahat[1]-theta)\n    W = inv(cov(ms))\n    thetahat, junk, ms, junk = gmm(m, thetahat, W)\n    results[i,2] = sqrt(n)*(thetahat[1]-theta)\nend    \np1 = npdensity(results[:,1])\nplot!(p1, title=\"Inefficient\")\np2 = npdensity(results[:,2])\nplot!(p2, title=\"Efficient\")\np = plot(p1,p2,layout=(2,1),xlims=(-10,20))\n#savefig(\"Efficient.png\")\nprintln(\"Monte Carlo covariance: (1,1) is inefficient GMM, (2,2) is efficient\")\nprettyprint(cov(results))\nreturn p\nend\nmain()\n\n", "meta": {"hexsha": "01c1a99ac36dfea081346c182a0d9b824671c4e6", "size": 1029, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/GMM/EfficientGMM.jl", "max_stars_repo_name": "Hiroakiyusheng/Econometrics", "max_stars_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "Examples/GMM/EfficientGMM.jl", "max_issues_repo_name": "Hiroakiyusheng/Econometrics", "max_issues_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "Examples/GMM/EfficientGMM.jl", "max_forks_repo_name": "Hiroakiyusheng/Econometrics", "max_forks_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 31.1818181818, "max_line_length": 79, "alphanum_fraction": 0.6637512148, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7624902498050772}}
{"text": "\"\"\"\n    milca_weights(cij, a, B)\n\nThis function returns weights (a vector of the number of frequency channels) of the Modified ILC Algorith (MILCA) method.\n\n*Reference*: Equation (15) of Hurier, Macías-Pérez, Hildebrandt, A&A, 558, A118 (2013)\n\n# Arguments\n- `cij::Array{<:AbstractFloat,2}`: symmetric covariance matrix with the dimention of `(nν, nν)` where `nν` is the number of frequency bands.\n- `a::Array{<:AbstractFloat,1}`: vector of the frequency response, for the component to be extracted. E.g., `a = [1,...,1]` for CMB.\n- `B::Array{<:AbstractFloat,2}`: `nν`-by-`nrc` matrix of the frequency response, for `nrc` components to be nulled.\n\"\"\"\nfunction milca_weights(\n    cij::Array{T,2},\n    a::Array{T,1},\n    B::Array{T,2},\n) where {T<:AbstractFloat}\n    if size(cij)[1] ≠ size(cij)[2]\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    elseif size(cij)[1] ≠ length(a) || size(cij)[1] ≠ size(B)[1]\n        throw(DimensionMismatch(\"dimensions of the covariance matrix and the frequency response vector or matrix do not match\"))\n    else\n        M = Symmetric(cij)\n    end\n    e = zeros(size(B)[2] + 1)\n    e[1] = 1\n    F = [a B]\n    w = inv(M) * F * inv(F' * inv(M) * F) * e\nend\n\n\"\"\"\n    milca_weights(cijℓ, a, B[, ℓid=3])\n\nThis function returns weights (a `nν`-by-`nℓ` matrix) of the Modified ILC Algorith (MILCA) method.\n\nHere, `nν` is the number of frequency channels and `nℓ` is the number of elements in the relevant domain, e.g., multipoles, band-power bins, pixels, etc.\n\n*Reference*: Equation (15) of Hurier, Macías-Pérez, Hildebrandt, A&A, 558, A118 (2013)\n\n# Arguments\n- `cijℓ::Array{<:AbstractFloat,3}`: symmetric covariance matrix with the dimention of `(nℓ, nν, nν)`, `(nν, nℓ, nν)` or `(nν, nν, nℓ)` (default).\n- `a::Array{<:AbstractFloat,1}`: vector of the frequency response, for the component to be extracted. E.g., `a = [1,...,1]` for CMB.\n- `B::Array{<:AbstractFloat,2}`: `nν`-by-`nrc` matrix of the frequency response, for `nrc` components to be nulled.\n\n# Optional Arguments\n- `ℓid::Integer=3`: location of the index for the `nℓ` domain. `ℓid=1` if `cijℓ[nℓ,nν,nν]`, `ℓid=2` if `cijℓ[nν,nℓ,nν]`, and `ℓid=3` (the default value) if `cijℓ[nν,nν,nℓ]`.\n\"\"\"\nfunction milca_weights(\n    cijℓ::Array{T,3},\n    a::Array{T,1},\n    B::Array{T,2},\n    ℓid::Integer = 3,\n) where {T<:AbstractFloat}\n    if ℓid > 3 || ℓid < 1\n        throw(DomainError(ℓid, \"ℓid must be 1, 2, or 3\"))\n    end\n    if (ℓid == 3 && size(cijℓ)[1] ≠ size(cijℓ)[2]) ||\n       (ℓid == 2 && size(cijℓ)[1] ≠ size(cijℓ)[3]) ||\n       (ℓid == 1 && size(cijℓ)[2] ≠ size(cijℓ)[3])\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    end\n    nℓ = size(cijℓ)[ℓid]\n    nν = ifelse(ℓid == 3, size(cijℓ)[1], size(cijℓ)[3])\n    if length(a) ≠ nν || size(B)[1] ≠ nν\n        throw(DimensionMismatch(\"dimensions of the covariance matrix and the frequency response vector/matrix do not match\"))\n    end\n    wℓ = zeros(nν, nℓ) # ILC weights\n    e = zeros(size(B)[2] + 1)\n    e[1] = 1\n    F = [a B]\n    for iℓ = 1:nℓ\n        if ℓid == 3\n            M = Symmetric(cijℓ[:, :, iℓ])\n        elseif ℓid == 2\n            M = Symmetric(cijℓ[:, iℓ, :])\n        else\n            M = Symmetric(cijℓ[iℓ, :, :])\n        end\n        wℓ[:, iℓ] = inv(M) * F * inv(F' * inv(M) * F) * e\n    end\n    return wℓ\nend\n", "meta": {"hexsha": "402472b4a6133486cc8e3b061db1e8bbdb845cc4", "size": 3335, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/milca.jl", "max_stars_repo_name": "komatsu5147/CleanCMB.jl", "max_stars_repo_head_hexsha": "d44d5731f01047b6d02293cfb1b96d97b9c3e003", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-06-22T14:41:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-23T20:05:14.000Z", "max_issues_repo_path": "src/milca.jl", "max_issues_repo_name": "komatsu5147/CleanCMB.jl", "max_issues_repo_head_hexsha": "d44d5731f01047b6d02293cfb1b96d97b9c3e003", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/milca.jl", "max_forks_repo_name": "komatsu5147/CleanCMB.jl", "max_forks_repo_head_hexsha": "d44d5731f01047b6d02293cfb1b96d97b9c3e003", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-03T15:17:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T15:17:51.000Z", "avg_line_length": 40.1807228916, "max_line_length": 173, "alphanum_fraction": 0.6083958021, "num_tokens": 1231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7624902454984035}}
{"text": "function linear_interpolation(initial_state, final_state, horizon)\n    n = length(initial_state)\n    X = [copy(Array(initial_state)) for t = 1:horizon]\n    for t = 1:horizon\n        for i = 1:n\n            X[t][i] = (final_state[i] - initial_state[i]) / (horizon - 1) * (t - 1) + initial_state[i]\n        end\n    end\n    return X\nend\n", "meta": {"hexsha": "fe30d9547aab4a8f48d20ca8db8302cb29e01aa3", "size": 334, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "mcx/DirectTrajectoryOptimization.jl", "max_stars_repo_head_hexsha": "5487311bdb817f8da201dba5302ed20a466cce11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2021-10-02T22:26:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T23:52:38.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "mcx/DirectTrajectoryOptimization.jl", "max_issues_repo_head_hexsha": "5487311bdb817f8da201dba5302ed20a466cce11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-10-02T21:11:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T19:52:37.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "mcx/DirectTrajectoryOptimization.jl", "max_forks_repo_head_hexsha": "5487311bdb817f8da201dba5302ed20a466cce11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-10-02T22:29:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T07:23:43.000Z", "avg_line_length": 30.3636363636, "max_line_length": 102, "alphanum_fraction": 0.6017964072, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7624902417321214}}
{"text": "#   Unit examples of the FourierAnalysis Package for julia language\n#\n#   MIT License\n#   Copyright (c) 2019-2022,\n#   Marco Congedo, CNRS, Grenobe, France:\n#   https://sites.google.com/site/marcocongedo/home\n\n# ? CONTENTS :\n#   This example shows how to compute and plot spectra\n#   and how to extract inforation from them.\n\n#   ~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~  #\n#                                                                             #\n#   ~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~  #\n\n\nusing FourierAnalysis, FFTW, LinearAlgebra, Statistics,\n      Plots, Plots.PlotMeasures\n\n# add module for reading the two EEG text files to be used ater\npush!(LOAD_PATH, @__DIR__)\nusing IOtxt\n\n# Get EEG file names with complete path (they have extension .txt)\nS=getFilesInDir(@__DIR__; ext=(\".txt\",))\n\n# read the two EEG data files and put them in a Matrix object\nX1=readEEG(S[1])\nX2=readEEG(S[2])\n\n######## compute the FFT of one epoch of a time series ########\nsr, t, f, a = 128, 128, 8, 2\nv=sinusoidal(a, f, sr, t, 0.6)\nplot(v) # plot the time series\ntapering=hann\n\n### The long way using FFTW.jl only:\n# get a plan.  The normalization 2/t outputs correct peak amplitude\nP=plan_rfft(v)*(2/t)\n\n# get a tapering window\na=taper(tapering, t)\n\n# plot the tapered signal\nplot!(v.*a.y)\n\n# do the FFT on tapered data\nΨ=P*(v.*a.y)\n\n# get the amplitude spectrum\nΣ=abs.(Ψ)\nbar!(Σ[2:end])\n\n# check the amplitude at frequency f and neighbooring bins\npos=f2b(f, sr, t, DC=true)\n\nΣ[pos-1]\nΣ[pos]\nΣ[pos+1]\n\n# The fast way using FourierAnalysis.jl:\nΣ2=spectra(v, sr, t; tapering=tapering, func=√)\nbar!(Σ2.y)\n\n# equivalently:\nΣ2=spectra(v, sr, t; tapering=taper(hann, t), func=√)\nbar!(Σ2.y)\n\n####################################################\n\n# test spectra with odd samples and with DC\nsr=65; t=65\nf, a = fres(sr, t)*4, 2\nv=sinusoidal(a, f, sr, t, 0.6; DC=3)\nplot(v) # plot the time series\nΣ2=spectra(v, sr, t; tapering=rectangular, DC=true, func=√)\nbar!(Σ2.y)\n\n####################################################\n### Check amplitude spectra at all Fourier Frequency (rectangular taper) ###\n# the amplitudes are in increment of 10 along frequencies\n# NB when t is even, correct amplitude for the last frequency is obtained\n# only if the sinusoidal has a phase=π/6\nsr, t, = 16, 32\nt½ = t÷2\nV=Matrix{Float64}(undef, t, t½)\nfor i=1:t½ V[:, i]=sinusoidal(10*i, b2f(i, sr, t), sr, t, π/6) end\n\n# plot the sinusoids in V\nZ=deepcopy(V)\nfor i=2:size(Z, 2), j=1:size(Z, 1) Z[j, i]+=(10.0*i) end\nplot(Z, label=\"\")\n\n# long way using FFTW only.jl\nP=plan_rfft(V, 1)*(2/t)\nΨ=P*V\nΨ[end, :]*=0.5*2^0.25 # correction for Nyquist frequency\nΣ=abs.(Ψ)\nbar(Σ[brange(t, DC=true), :], labels=\"\")\n\n# fast way using FourierAnalysis.jl\nΣ2=spectra(V, sr, t; tapering=rectangular, func=√, DC=true)\nbar(Σ2.y[brange(t, DC=true), :], labels=\"\")\n\n#############################################################################\n### Check amplitude spectra on long signals obtained by welch methods\n# one sinusoidal is at an exact discrete Fourier Frequency and the other not\n# Rectangular window\nsr, t, f, a = 128, 128, 10, 0.5\nv=sinusoidal(a, f, sr, t*16)+sinusoidal(a, f*3.5+0.5, sr, t*16)+randn(t*16)\nΣ=spectra(v, sr, t; tapering=rectangular, func=√)\nbar(Σ.y, labels=\"rectangular\")\n\n# harris4 window (default)\nΣ2=spectra(v, sr, t; func=√)\nbar!(Σ2.y, labels=\"harris4\")\n\n#smooth spectra\nΣ3=smooth(blackmanSmoother, Σ2)\nbar!(Σ3.y, labels=\"smoothed\")\n\n\n######## Check amplitude spectrum obtained with dpss (slepian tapers) ########\nsr, t = 128, 128\nt½ = t÷2\nV=Matrix{Float64}(undef, t, t½)\nfor i=1:t½ V[:, i]=sinusoidal(1, b2f(i, sr, t), sr, t, 0 ) end\n# plot half of the the first 7 sinusoids in V\nplot(V[1:t½+1, 1:7], color=:gray, legend=false)\n\nΣ=spectra(V, sr, t; tapering=taper(slepian, t; α=2, n=3), func=√)\nplot(Σ.y, labels=\"\")\n#############################################################\n\n#### Compute Welch amplitude spectra of EEG data ####\nt, sr, slide, tapering = 1024, 128, 512, harris4\n\n# gather some attributes to obtain nice spectra plots\nspectraArgs=(fmax          = 48,\n             left_margin   = 2mm,\n             bottom_margin = 2mm,\n             xtickfont     = font(10, \"Times\"),\n             ytickfont     = font(10, \"Times\"))\n\nS=spectra(X1, sr, t; tapering=tapering, slide=sr, func=sqrt)\nplot(S; ytitle=\"Amplitude (\\\\muV)\", spectraArgs...)\n\n#smooth spectra\nS2=smooth(blackmanSmoother, S)\nplot(S2; ytitle=\"Amplitude (\\\\muV)\", spectraArgs...)\n\n# extract spectra in alpha range (8Hz to 12Hz) at all electrodes\ne=extract(S, (8, 12))\n\n# You can use any combination of integer and real numbers\ne=extract(S, (8, 12.5))\ne=extract(S, (8.5, 12))\n\n# the following equivalently extract the spectra at 10Hz only (1 bin)\ne=extract(S, 10)\ne=extract(S, (10))\ne=extract(S, (10, 10))\n\n# extract spectra at all frequencies. Equivalent to S.y\ne=extract(S, :)\n\n# All these ways to indicate frequency ranges work with the mean function\n# as well, e.g.,\n\n# compute average spectra in alpha range for each time-series\nbar(mean(S, (8, 12)))\n# or\nbar(mean(S, (8.0,12.0)))\n\n# this actually extract the power at 10Hz for each time series\n# and is equivalent to extract(S, 10)\nmean(S, 10)\n# thus this computes the average power at 10Hz across time-series\nmean(extract(S, 10)) # or mean(mean(S, 10))\n# and this computes the mean across time-series and across frequencies in range [8Hz, 12Hz]\nmean(extract(S, (8, 12))) # or equivalently mean(mean(S, (8, 12)))\n\n# average spectrum across all frequencies for each time-series\nbar(mean(S, :))\n\n# plot average spectra in 2Hz-band-pass regions for all time-series\nplot(bands(S, 2))\n\n# plot average spectra in in 2Hz-band-pass regions for series 15-19\nplot(bands(S, 2)[:, 15:19])\n\n# plot average spectra in in 2Hz-band-pass regions for series 19\nplot(bands(S, 2)[:, 19])\n\n# plot average spectra in alpha range for series 15-19\nbar(mean(S, (8,12))[15:19])\n\n# extract spectra in alpha range for series 15-19\ne=extract(S, (8, 12))[:, 15:19]\n\n# Compute several spectra altogether\n𝐗=[X1, X2]\n𝐒=spectra(𝐗, sr, t; tapering=tapering, slide=sr, func=√)\nplot(𝐒[1]; ytitle=\"Amplitude (\\\\muV)\", spectraArgs...)\nplot(𝐒[2]; ytitle=\"Amplitude (\\\\muV)\", spectraArgs...)\n\n# do the same thing using a fast FFTW plan (wait up to 10s for computing the plan)\nplan=Planner(plan_exhaustive, 10.0, t, eltype(𝐗[1]))\n𝐒_fast=spectra(𝐗, sr, t; planner=plan, slide=sr, func=√)\n\n# compute the average spectra in the alpha range for all time-series and all subjects\nmean(𝐒, (8,12))\n\n# compute the average spectra in the alpha range across subjects for all time-series\nmean(mean(𝐒, (8,12)))\n# compute and plot it\nplot(mean(mean(𝐒, (8,12))))\n\n# extract spectra in alpha range for all time-series and all subjects\nextract(𝐒, (8, 12))\n\n# if you enter en illegal range, nothing will be done and you will get\n# an error in the REPL explaining what is wrong in your argument\nextract(𝐒, (0, 12))\nmean(𝐒, (0, 128))\n\n# extract 4Hz-band-pass average spectra for all electrodes and all subjects\nbands(𝐒, 4)\n\n# Apply smoothing in the above spectra computations\n𝐒=spectra(𝐗, sr, t;\n    tapering=tapering, smoothing=blackmanSmoother, func=√)\nplot(𝐒[1]; ytitle=\"Amplitude (\\\\muV)\", spectraArgs...)\nplot(𝐒[2]; ytitle=\"Amplitude (\\\\muV)\", spectraArgs...)\n\n# plot the average spectrum across all electrodes for the two files\n# using Julia standard mean function\nplot(mean(𝐒[1].y[:, i] for i=1:size(𝐒[1].y, 2)))\nplot!(mean(𝐒[2].y[:, i] for i=1:size(𝐒[2].y, 2)))\n\n# plot spectra in in 1Hz band-pass regions for all electrodes in 𝐒[1]\nplot(bands(𝐒[1], 1))\n\n# use slepian multi-tapering on EEG data\nS_sl=spectra(X1, sr, t; tapering=slepians(sr, t, 1.25), func=√)\nplot(S_sl; ytitle=\"Amplitude (\\\\muV)\", spectraArgs...)\n\n# use slepian multi-tapering and get smoothed spectra\nS_sl=spectra(X1, sr, t;\n    tapering=slepians(sr, t, 1.25), func=√, smoothing=blackmanSmoother)\nplot(S_sl; xspace=8, ytitle=\"Amplitude (\\\\muV)\", spectraArgs...)\n\n# See how the variance of the spectra estimation is lower\n# as compared to using a normal tapering window !\nS=spectra(X1, sr, t;\n    tapering=harris4, func=√, smoothing=blackmanSmoother)\nplot(S; ytitle=\"Amplitude (\\\\muV)\", spectraArgs...)\n", "meta": {"hexsha": "b7e095545123a962779e7439efaff38eed1c139b", "size": 8182, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example_spectra.jl", "max_stars_repo_name": "proteanblank/FourierAnalysis.jl", "max_stars_repo_head_hexsha": "a1633c9e43bc53d915486b49a9355ff61b3ecb28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/example_spectra.jl", "max_issues_repo_name": "proteanblank/FourierAnalysis.jl", "max_issues_repo_head_hexsha": "a1633c9e43bc53d915486b49a9355ff61b3ecb28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/example_spectra.jl", "max_forks_repo_name": "proteanblank/FourierAnalysis.jl", "max_forks_repo_head_hexsha": "a1633c9e43bc53d915486b49a9355ff61b3ecb28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7131782946, "max_line_length": 91, "alphanum_fraction": 0.647030066, "num_tokens": 2767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7624680294369698}}
{"text": "using DrWatson\n@quickactivate \"StatReth\"\n\n# %%\nusing CSV\nusing DataFrames\nusing Turing\nusing Plots\n\ninclude(srcdir(\"quap.jl\"))\ninclude(srcdir(\"tools.jl\"))\n\n# %%\n# Load the data, don't forget to drop everything missing.\nd = DataFrame(CSV.File(datadir(\"exp_raw/cherry_blossoms.csv\"), missingstring = \"NA\"))\nd2 = dropmissing(d, :doy)\n\n# %% 4.76\n# Redo the model from the text ...\nusing BSplines: BSplineBasis, basismatrix\n\nnum_knots = 15\nknot_list = quantile(d2.year, range(0, 1, length = num_knots))\n\nbasis = BSplineBasis(4, knot_list)\nB = basismatrix(basis, d2.year)\n\n@model function spline(doy, B = B)\n    α ~ Normal(100, 10)\n    w ~ filldist(Normal(0, 10), size(B, 2))\n    σ ~ Exponential(1)\n    μ = α .+ B * w\n    doy ~ MvNormal(μ, σ)\nend\n\nm4_7 = quap(spline(d2.doy))\n\n# %%\n# ... and look at the splines\nw_str = [\"w[$i]\" for i in 1:length(basis)]\npost = DataFrame(rand(m4_7.distr, 1000)', [\"α\"; w_str; \"σ\"])\n\nw = mean.(eachcol(post[:, w_str]))\n\nplot(legend = false, xlabel = \"year\", ylabel = \"basis * weight\")\nfor y in eachcol(B .* w')\n    plot!(d2.year, y)\nend\nplot!()\n\nmu = B * Array(post[!, w_str])'\nmu_m, mu_lower, mu_upper = meanlowerupper(mu)\n\nplot!(d2.year, mu_m, ribbon = (mu_m .- mu_lower, mu_upper .- mu_m),\n                    lw = 2, fa = 0.1, c = :black)\n\n# %%\n# Now do the entire thing with more knots. The model can stay the same, just need to replace\n# B\nnum_knots = 30\nknot_list = quantile(d2.year, range(0, 1, length = num_knots))\n\nbasis2 = BSplineBasis(4, knot_list)\nB2 = basismatrix(basis2, d2.year)\n\nm4_7_2 = quap(spline(d2.doy, B2))\n\n# %%\n# ... and look at the splines\nw_str = [\"w[$i]\" for i in 1:length(basis2)]\npost = DataFrame(rand(m4_7_2.distr, 1000)', [\"α\"; w_str; \"σ\"])\n\nw = mean.(eachcol(post[:, w_str]))\n\nplot(legend = false, xlabel = \"year\", ylabel = \"basis * weight\")\nfor y in eachcol(B2 .* w')\n    plot!(d2.year, y)\nend\nplot!()\n\nmu = B2 * Array(post[!, w_str])'\nmu_m, mu_lower, mu_upper = meanlowerupper(mu)\n\nplot!(d2.year, mu_m, ribbon = (mu_m .- mu_lower, mu_upper .- mu_m),\n                    lw = 2, fa = 0.1, c = :black)\n\n# %%\n\"\"\"\nMore knots make it possible for the spline to have more wiggles. Since that improves the\nfit, it is taken advantage of and the spline gets wigglier. This is pretty similar to how\nthings go when trying to fit a polynomial while increasing its order. The fit gets better\nfor the cost of losing generality.\nI'm not going to do the prior on the weights thing, I already did the same thing in 4H6.\nThe amplitude goes up or down, depending in what direction I change the prior.\n\"\"\"\n", "meta": {"hexsha": "755d8d52bff0344dd608bf83700aa781a0776015", "size": 2548, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/ch04/4M8.jl", "max_stars_repo_name": "karajan9/statisticalrethinking", "max_stars_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-06-03T14:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T16:52:26.000Z", "max_issues_repo_path": "exercises/ch04/4M8.jl", "max_issues_repo_name": "karajan9/statisticalrethinking", "max_issues_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-13T05:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T14:05:57.000Z", "max_forks_repo_path": "exercises/ch04/4M8.jl", "max_forks_repo_name": "karajan9/statisticalrethinking", "max_forks_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-01T13:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-03T23:40:53.000Z", "avg_line_length": 26.5416666667, "max_line_length": 92, "alphanum_fraction": 0.6589481947, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7624680220954233}}
{"text": "\"\"\"\n    pearson_bounds(dA::UnivariateDistribution, dB::UnivariateDistribution; n::Int=7)\n\nCompute the theoretical lower and upper Pearson correlation values for a pair of \nunivariate distributions.\n\nSee also: [`pearson_match`](@ref)\n\n# Examples\n```jldoctest\njulia> using Distributions\n\njulia> A = Normal(78, 10); B = LogNormal(3, 1);\n\njulia> pearson_bounds(A, B)\n(lower = -0.7628739783668452, upper = 0.762873978367046)\n```\n\"\"\"\nfunction pearson_bounds(dA::UD, dB::UD; n::Int=7)\n    μA = mean(dA)\n    σA = std(dA)\n    μB = mean(dB)\n    σB = std(dB)\n    _pearson_bounds(dA, dB, μA, μB, σA, σB, n)\nend\nfunction _pearson_bounds(dA::UD, dB::UD, μA, μB, σA, σB, n)\n    k = 0:1:n\n    a = get_coefs(dA, n)\n    b = get_coefs(dB, n)\n\n    c1 = -μA * μB\n    c2 = 1 / (σA * σB)\n    kab = factorial.(k) .* a .* b\n    ρ_l = c1 * c2 + c2 * sum((-1) .^ k .* kab)\n    ρ_u = c1 * c2 + c2 * sum(kab)\n\n    ρ_l, ρ_u = clampcor.((ρ_l, ρ_u))\n    (lower = ρ_l, upper = ρ_u)\nend\n\n\n\"\"\"\n    pearson_bounds(margins::Vector{<:UnivariateDistribution})\n\nCompute the theoretical lower and upper Pearson correlation values for a set of \nunivariate distributions.\n    \nSee also: [`pearson_match`](@ref)\n\n# Examples\n```jldoctest\njulia> using Distributions\n\njulia> m = [Normal(78, 10), LogNormal(3, 1)];\n\njulia> b = pearson_bounds(m);\n\njulia> b.lower\n2×2 Array{Float64,2}:\n  1.0       -0.762874\n -0.762874   1.0\n\njulia> b.upper\n2×2 Array{Float64,2}:\n 1.0       0.762874\n 0.762874  1.0\n```\n\"\"\"\nfunction pearson_bounds(margins::Vector{<:UD})\n    d = length(margins)\n    lower, upper = zeros(Float64, d, d), zeros(Float64, d, d)\n\n    @threads for i in collect(subsets(1:d, Val{2}()))\n        l, u = pearson_bounds(margins[i[1]], margins[i[2]])\n        lower[i...] = l\n        upper[i...] = u\n    end\n\n    lower .= Symmetric(lower)\n    cor_constrain!(lower)\n\n    upper .= Symmetric(upper)\n    cor_constrain!(upper)\n    \n    (lower = lower, upper = upper)\nend\n", "meta": {"hexsha": "3ccd5f05c1f461eb1a3e1ddebfee420ffebfd74b", "size": 1918, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PearsonMatching/pearson_bounds.jl", "max_stars_repo_name": "adknudson/MvSim.jl", "max_stars_repo_head_hexsha": "6c3085289a5e23441f5f0db90f2b3cbbb9b49afc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PearsonMatching/pearson_bounds.jl", "max_issues_repo_name": "adknudson/MvSim.jl", "max_issues_repo_head_hexsha": "6c3085289a5e23441f5f0db90f2b3cbbb9b49afc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2020-07-08T20:07:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-16T01:56:40.000Z", "max_forks_repo_path": "src/PearsonMatching/pearson_bounds.jl", "max_forks_repo_name": "adknudson/MvSim.jl", "max_forks_repo_head_hexsha": "6c3085289a5e23441f5f0db90f2b3cbbb9b49afc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0459770115, "max_line_length": 84, "alphanum_fraction": 0.6183524505, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7624680197055171}}
{"text": "\"\n\n Himmelblau function\n\n author: Atsushi Sakai\n\"\n\nfunction himmelblau_function(x, y)\n    return (x^2 + y - 11)^2 + (x + y^2 - 7)^2\nend\n\nx = parse(Float64,ARGS[1])\ny = parse(Float64,ARGS[2])\nprintln(himmelblau_function(x, y))\n\n", "meta": {"hexsha": "e6f5e2971c70927510ecd168f7f619bab2532643", "size": 227, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/himmelblau_function.jl", "max_stars_repo_name": "AtsushiSakai/optuna_sample", "max_stars_repo_head_hexsha": "06282ea35e8fcd2a4b0ffafb8080f56ffbf3ff66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-06T09:43:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-06T09:43:04.000Z", "max_issues_repo_path": "julia/himmelblau_function.jl", "max_issues_repo_name": "AtsushiSakai/optuna_sample", "max_issues_repo_head_hexsha": "06282ea35e8fcd2a4b0ffafb8080f56ffbf3ff66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/himmelblau_function.jl", "max_forks_repo_name": "AtsushiSakai/optuna_sample", "max_forks_repo_head_hexsha": "06282ea35e8fcd2a4b0ffafb8080f56ffbf3ff66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.1875, "max_line_length": 45, "alphanum_fraction": 0.6563876652, "num_tokens": 84, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7624680171437822}}
{"text": "using LinearAlgebra, Random, Plots; pyplot()\nRandom.seed!(1)\n\nN = 10^4\nedges = [(1,2), (1,3), (2,4), (1,4), (3,4)]\nL = maximum(maximum.(edges))\nsource, dest = 1, L\n\nfunction adjMatrix(edges,L)\n    R = zeros(Int, L, L)\n    for e in edges\n        R[ e[1], e[2] ], R[ e[2], e[1] ] = 1, 1\n    end\n    R\nend\n\npathExists(R, source, destination) = sign.((I+R)^L)[source,destination]\nrandNet(p) = randsubseq(edges,1-p)\n\nrelEst(p) = sum([pathExists(adjMatrix(randNet(p),L),source,dest) for _ in 1:N])/N\nrelAnalytic(p) = 1-p^3*(p-2)^2\n\npGrid = 0:0.05:1\nscatter(pGrid, relEst.(pGrid),\n\tc=:blue, ms=5, msw=0,label=\"Monte Carlo\")\nplot!(pGrid, relAnalytic.(pGrid),\n\tc=:red, label=\"Analytic\", xlims=(0,1.05), ylims=(0,1.05), \n\txlabel=\"p\", ylabel=\"Reliability\")", "meta": {"hexsha": "ce34bde4c1d0596e96105e61bbfc87196512c800", "size": 745, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "10_chapter/reliability.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "10_chapter/reliability.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "10_chapter/reliability.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 26.6071428571, "max_line_length": 81, "alphanum_fraction": 0.6134228188, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.7624680169459315}}
{"text": "# Code to reproduce figure 1 numerical experiments for the paper \"Understanding the Origins of Information-Seeking Exploratin in Probabilistic Objectives for Control\"\n# Essentially what we do here is demonstrate the difference between an evidence \"maximizing\" objective vs a divergence \"probability matching\" objective in a simple univariate scenario where we have two overlapping Gaussians\n# as our \"desire distribution\". The evidence objective finds the peak of the distribution and concentrates all probability mass there. The divergence objective explicitly tries to match the desire distribution in all its modes.\n# Even though both the desire and evidence objective can fit two Gaussians, the evidence objective nevertheless only utilizes one Gaussian and collapses the weight of the other to zero.\n\nusing Plots\nusing LinearAlgebra\nusing Statistics\nusing Distributions\nusing Optim\n\ne = MathConstants.e\n\n\n### Utility Function ###\n\nfunction sigmoid(x)\n    return 1 / (1 + exp(-x))\nend\nfunction Gaussian_cdf(x, mu, var)\n    return (1 / sqrt(2 * pi * var)) * exp(-(x - mu)^2 / (2 * var))\nend\n\nfunction Gaussian_KL(mu1, mu2, var1, var2)\n    log(sqrt(var2) / sqrt(var1)) + (var1 + (mu1 - mu2)^2) / (2 * var2) - 0.5\nend\n\nfunction Gaussian_entropy(mu, var)\n    return log(sqrt(var * 2 * pi * e))\nend\n\nfunction approximate_KL(cdfs1, cdfs2)\n    sum = 0\n    for i in 1:length(cdfs1)\n        sum += cdfs1[i] * log(cdfs1[i] / cdfs2[i])\n    end\n    return sum\nend\n\nfunction approximate_evidence(cdfs1, cdfs2)\n    return sum(cdfs1 .* -log.(cdfs2))\nend\nfunction approximate_entropy(cdfs)\n    return sum(cdfs .* log.(cdfs))\nend\n\n# Create our desire distribution cdf\nfunction get_desired_cdf(mu_a=1, mu_b=4, var_1=1, var_b=0.4)\n    xs = [i*0.01 for i in -500:1000]\n    cdfs = (0.5 * Gaussian_cdf.(xs, mu_a, var_a)) + (0.5 * Gaussian_cdf.(xs, mu_b, var_b))\n    return cdfs\nend\n\n### loss functions for evidence and divergence objective ###\n\nfunction compute_divergence_loss(mu1, mu2, logvar1, logvar2, alpha,beta)\n    lambda = 1e6\n    desired_cdfs = get_desired_cdf()\n    xs = [i*0.01 for i in -500:1000]\n    cdfs = (sigmoid(alpha) .* Gaussian_cdf.(xs, mu1, exp(logvar1))) + (sigmoid(beta) .* Gaussian_cdf.(xs, mu2, exp(logvar2)))\n    loss = approximate_KL(cdfs / sum(cdfs), desired_cdfs / sum(desired_cdfs))\n    # ensure that constraint is respected\n    loss += lambda * ((sigmoid(alpha) + sigmoid(beta)) - 1)^2\n    return loss\nend\nfunction compute_evidence_loss(mu1, mu2, logvar1, logvar2, alpha,beta)\n    lambda = 1e6\n    desired_cdfs = get_desired_cdf()\n    xs = [i*0.01 for i in -500:1000]\n    cdfs = (sigmoid(alpha) .* Gaussian_cdf.(xs, mu1, exp(logvar1))) + (sigmoid(beta) .* Gaussian_cdf.(xs, mu2, exp(logvar2)))\n    loss = approximate_evidence(cdfs / sum(cdfs), desired_cdfs / sum(desired_cdfs))\n    # ensure that constraint is respected\n    loss += lambda * ((sigmoid(alpha) + sigmoid(beta)) - 1)^2\n    return loss\nend\n\n### Optimize using nonlinear optimization ###\n\nfunction optimize_loss(loss_fn)\n    init_params = zeros(6)\n    init_params[1:4] = rand(4)\n    print(\"$init_params \\n\")\n    if loss_fn == \"divergence\"\n        ll_func = compute_divergence_loss\n    elseif loss_fn == \"evidence\"\n        ll_func = compute_evidence_loss\n    else\n        error(\"Loss function not recognized\")\n    end\n    opt = optimize(init_params -> ll_func(init_params...), init_params)\n    output_params = Optim.minimizer(opt)\n    final_loss = Optim.minimum(opt)\n    return output_params,final_loss\nend\n\n### and plot ###\n\nfunction plot_cdf(params,loss_fn)\n    params, final_loss = optimize_loss(loss_fn)\n    mu1, mu2, logvar1, logvar2, alpha,beta = params\n    xs = [i*0.01 for i in -500:1000]\n    desired_cdf = get_desired_cdf()\n    cdfs = (sigmoid(alpha) .* Gaussian_cdf.(xs, mu1, exp(logvar1))) + (sigmoid(beta) .* Gaussian_cdf.(xs, mu2, exp(logvar2)))\n    plot(xs ./ 10, cdfs/sum(cdfs), xaxis=\"X value\", yaxis=\"Probability Density\", label=\"Predicted Density\")\n    if loss_fn == \"evidence\"\n        plot!(xs ./10, desired_cdf, title=\"Peak Finding with Evidence Objectives\",linestyle=:dash,label=\"Desired Density\")\n    else\n        plot!(xs ./10, desired_cdf / sum(desired_cdf),title=\"Probability Matching with Divergence objective\",linestyle=:dash,label=\"Desired Density\") # this is just for visibility\n    end\n    savefig(\"figures/$loss_fn\")\n    #return cdfs\nend\n\nplot_cdf(params,\"evidence\")\nplot_cdf(params, \"divergence\")\n", "meta": {"hexsha": "55751bf80f96b692a27dcffefc995f0fb73380a4", "size": 4402, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "figure_1.jl", "max_stars_repo_name": "BerenMillidge/origins_information_seeking_exploration", "max_stars_repo_head_hexsha": "7551a6fa1b5d708b83977eb0658d2ff636e9b264", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "figure_1.jl", "max_issues_repo_name": "BerenMillidge/origins_information_seeking_exploration", "max_issues_repo_head_hexsha": "7551a6fa1b5d708b83977eb0658d2ff636e9b264", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figure_1.jl", "max_forks_repo_name": "BerenMillidge/origins_information_seeking_exploration", "max_forks_repo_head_hexsha": "7551a6fa1b5d708b83977eb0658d2ff636e9b264", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9482758621, "max_line_length": 227, "alphanum_fraction": 0.701726488, "num_tokens": 1259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7624680156650642}}
{"text": "# # Visualization of Frank-Wolfe running on a 2-dimensional polytope\n\n# This example provides an intuitive view of the Frank-Wolfe algorithm\n# by running it on a polyhedral set with a quadratic function.\n# The Linear Minimization Oracle (LMO) corresponds to a call to a generic simplex solver from `MathOptInterface.jl` (MOI).\n\n# ## Import and setup\n\n# We first import the necessary packages, including Polyhedra to visualize the feasible set.\n\nusing LinearAlgebra\nusing FrankWolfe\n\nimport MathOptInterface\nconst MOI = MathOptInterface\nusing GLPK\n\nusing Polyhedra\nusing Plots\n\n# We can then define the objective function,\n# here the squared distance to a point in the place, and its in-place gradient.\n\nn = 2\ny = [3.2, 0.5]\n\nfunction f(x)\n    return 1 / 2 * norm(x - y)^2\nend\nfunction grad!(storage, x)\n    @. storage = x - y\nend\n\n# ## Custom callback\n#\n# FrankWolfe.jl lets users define custom callbacks to record information about each iteration.\n# In that case, the callback will copy the current iterate `x`, the current vertex `v`, and the current step size `gamma`\n# to an array thanks to a closure.\n# We then declare the array and the callback over this array.\n# Each iteration will then push to this array.\n\nfunction build_callback(trajectory_arr)\n    return function callback(state)\n        return push!(trajectory_arr, (copy(state.x), copy(state.v), state.gamma))\n    end\nend\n\niterates_information_vector = []\ncallback = build_callback(iterates_information_vector)\n\n# ## Creating the Linear Minimization Oracle\n# The LMO is defined as a call to a linear optimization solver, each iteration resets the objective and calls the solver.\n# The linear constraints must be defined only once at the beginning and remain identical along iterations.\n# We use here MathOptInterface directly but the constraints could also be defined with JuMP or Convex.jl.\n\no = GLPK.Optimizer()\nx = MOI.add_variables(o, n)\n\n## −x + y ≤ 2\nc1 = MOI.add_constraint(\n    o,\n    -1.0x[1] + x[2],\n    MOI.LessThan(2.0),\n)\n\n## x + 2 y ≤ 4\nc2 = MOI.add_constraint(\n    o,\n    x[1] + 2.0x[2],\n    MOI.LessThan(4.0),\n)\n        \n## −2 x − y ≤ 1\nc3 = MOI.add_constraint(\n    o,\n    -2.0x[1] - x[2],\n    MOI.LessThan(1.0),\n)\n    \n## x − 2 y ≤ 2\nc4 = MOI.add_constraint(\n    o,\n    x[1] - 2.0x[2],\n    MOI.LessThan(2.0),\n)\n    \n## x ≤ 2\nc5 = MOI.add_constraint(\n    o,\n    x[1] + 0.0x[2],\n    MOI.LessThan(2.0),\n)\n\n# The LMO is then built by wrapping the current MOI optimizer\n\nlmo_moi = FrankWolfe.MathOptLMO(o)\n\n# ## Calling Frank-Wolfe\n# We can now compute an initial starting point from any direction\n# and call the Frank-Wolfe algorithm.\n# Note that we copy `x0` before passing it to the algorithm because it is modified in-place by `frank_wolfe`.\n\nx0 = FrankWolfe.compute_extreme_point(lmo_moi, zeros(n))\n\nxfinal, vfinal, primal_value, dual_gap, traj_data = FrankWolfe.frank_wolfe(\n    f,\n    grad!,\n    lmo_moi,\n    copy(x0),\n    line_search = FrankWolfe.Adaptive(),\n    max_iteration = 10,\n    epsilon=1e-8,\n    callback=callback,\n    verbose=true,\n    print_iter=1,\n)\n\n# We now collect the iterates and vertices across iterations.\n\niterates = Vector{Vector{Float64}}()\npush!(iterates, x0)\nvertices = Vector{Vector{Float64}}()\nfor s in iterates_information_vector\n    push!(iterates, s[1])\n    push!(vertices, s[2])\nend\n\n# ## Plotting the algorithm run\n\n# We define another method for `f` adapted to plot its contours.\n\nfunction f(x1, x2)\n    x = [x1, x2]\n    return f(x)\nend\n\nxlist = collect(range(-1, 3, step = 0.2))\nylist = collect(range(-1, 3, step = 0.2))\n\nX = repeat(reshape(xlist, 1, :), length(ylist), 1)\nY = repeat(ylist, 1, length(xlist))\n\n# The feasible space is represented using Polyhedra.\n\nh = HalfSpace([-1, 1], 2) ∩\n    HalfSpace([1, 2], 4) ∩\n    HalfSpace([-2, -1], 1) ∩\n    HalfSpace([1, -2], 2) ∩\n    HalfSpace([1, 0], 2)\n\np = polyhedron(h)\n\np1 = contour(xlist, ylist, f, fill = true, line_smoothing = 0.85)\nplot(p1, opacity = 0.5)\nplot!(p, ratio = :equal, opacity = 0.5, label = \"feasible region\", framestyle = :zerolines, legend = true, color=:blue);\n\n# Finally, we add all iterates and vertices to the plot.\ncolors = [\"gold\", \"purple\", \"darkorange2\", \"firebrick3\"]\niterates = unique!(iterates)\nfor i in 1:3\n    scatter!([iterates[i][1]], [iterates[i][2]], label = string(\"x_\", i - 1), markersize = 6, color = colors[i])\nend\nscatter!([last(iterates)[1]], [last(iterates)[2]], label = string(\"x_\", length(iterates) - 1), markersize = 6, color = last(colors))\n\n# plot chosen vertices\nscatter!([vertices[1][1]], [vertices[1][2]], m = :diamond, markersize = 6, color = colors[1], label = \"v_1\")\nscatter!([vertices[2][1]], [vertices[2][2]], m = :diamond, markersize = 6, color = colors[2], label = \"v_2\", legend = :outerleft, colorbar = true)\n", "meta": {"hexsha": "3f8efe4dd964e983b1e9931a7b8297e662eba3d7", "size": 4736, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/0_fw_visualized.jl", "max_stars_repo_name": "INFORMSJoC/2021.0098", "max_stars_repo_head_hexsha": "28ec0ef2fb03b469cbcb032fbf96a17427bbae91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/src/examples/0_fw_visualized.jl", "max_issues_repo_name": "INFORMSJoC/2021.0098", "max_issues_repo_head_hexsha": "28ec0ef2fb03b469cbcb032fbf96a17427bbae91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/src/examples/0_fw_visualized.jl", "max_forks_repo_name": "INFORMSJoC/2021.0098", "max_forks_repo_head_hexsha": "28ec0ef2fb03b469cbcb032fbf96a17427bbae91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1904761905, "max_line_length": 146, "alphanum_fraction": 0.6822212838, "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.8705972566572504, "lm_q1q2_score": 0.7624577636347827}}
{"text": "#=\n\n  Euler #25 in Julia.\n\n  Problem 25:\n  \"\"\"\n  The Fibonacci sequence is defined by the recurrence relation:\n\n     Fn = Fn1 + Fn2, where F1 = 1 and F2 = 1.\n\n  Hence the first 12 terms will be:\n\n     F1 = 1\n     F2 = 1\n     F3 = 2\n     F4 = 3\n     F5 = 5\n     F6 = 8\n     F7 = 13\n     F8 = 21\n     F9 = 34\n     F10 = 55\n     F11 = 89\n     F12 = 144\n\n  The 12th term, F12, is the first term to contain three digits.\n\n  What is the first term in the Fibonacci sequence to contain 1000 digits?\")\n  \"\"\"\n\n  This Julia program was created by Hakan Kjellerstrand, hakank@gmail.com\n  See also my Julia page: http://www.hakank.org/julia/\n\n=#\n\nusing Memoization\ninclude(\"Euler.jl\")\n\n\n# Is not faster\n@memoize function fib_len_memo(n)\n    return fib(BigInt(n))|>string|>length\nend\n\nfunction fib_len(n)\n    return fibmemBigInt(n)|>string|>length\nend\n\n\n# Brute force: 0.09872957s\nfunction euler25a()\n    i = 0\n    len = 0\n    while len < 1000\n        i += 1\n        len = fibmemBigInt(i)|>string|>length\n    end\n\n    return i;\nend\n\n#\n# Using some heuristics to find the upper limit\n# (from my Picat solution).\n# 0.08765257s\nfunction euler25b()\n    target = 1000;\n    foundUpper = 0;\n    i = 1;\n    fibLen = 0;\n    step = 43;\n    # Get the upper limit\n    while fibLen < target && foundUpper == 0\n        fibLen = fib_len(step*i);\n        if fibLen > target\n            foundUpper = i\n            break\n        end\n        i += 1\n    end\n\n    # Now check all numbers from Step*(FoundUpper-1) .. Step*FoundUpper\n    # The target must be in that interval.\n    f = step*(foundUpper-1)\n    fibLen = fib_len(f);\n    while fibLen < target && f <= step*foundUpper\n        f += 1\n        fibLen = fib_len(f)\n    end\n\n    return f\nend\n\n# run_euler(euler25a)\nrun_euler(euler25b)\n", "meta": {"hexsha": "49eb6b2920c61cb7c731d5cd57214ff22d4d2235", "size": 1756, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/euler25.jl", "max_stars_repo_name": "Wikunia/hakank", "max_stars_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/euler25.jl", "max_issues_repo_name": "Wikunia/hakank", "max_issues_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/euler25.jl", "max_forks_repo_name": "Wikunia/hakank", "max_forks_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 18.2916666667, "max_line_length": 76, "alphanum_fraction": 0.5956719818, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7624097321726466}}
{"text": "struct FieldMatrix{T,N,Lt<:AbstractArray{T},Dt<:AbstractArray{T,N}} <: AbstractMatrix{T}\n    L :: Lt # Lower diagonal coefficients\n    D :: Dt # Diagonal coefficients\n    R :: CartesianIndices{N,NTuple{N,UnitRange{Int}}}\nend\nBase.size(p::FieldMatrix) = (s = length(p.R); (s,s))\nBase.IndexStyle(::Type{<:FieldMatrix}) = IndexCartesian()\nfunction Base.getindex(p::FieldMatrix{T}, i::Int, j::Int) where T\n    if i == j\n        return p.D[p.R[i]]\n    else\n        N = length(size(p.R))\n        for d ∈ 1:N\n            p.R[i]==p.R[j]+δ(d,N) && return p.L[p.R[i],d]\n            p.R[i]==p.R[j]-δ(d,N) && return p.L[p.R[j],d]\n        end\n        return zero(T)\n    end\nend\n\n@inline δ(i,N::Int) = CartesianIndex(ntuple(j -> j==i ? 1 : 0, N))\n@fastmath @inline multL(I::CartesianIndex{N},L,x) where {N} =\n    sum(@inbounds(x[I-δ(i,N)]*L[I,i]) for i ∈ 1:N)\n@fastmath @inline multU(I::CartesianIndex{N},L,x) where {N} =\n    sum(@inbounds(x[I+δ(i,N)]*L[I+δ(i,N),i]) for i ∈ 1:N)\n@fastmath @inline mult(I::CartesianIndex{N},L,D,x) where {N} =\n    @inbounds(x[I]*D[I])+multL(I,L,x)+multU(I,L,x)\n\nimport LinearAlgebra: mul!,dot,diag\nmul!(b::FieldVector,p::FieldMatrix,x::FieldVector) = (@loop b[I]=mult(I,p.L,p.D,x); b)\n@fastmath function dot(b::FieldVector,p::FieldMatrix,x::FieldVector)\n    s = zero(eltype(x))\n    @inbounds @simd for I ∈ b.R\n        s+= b[I]*mult(I,p.L,p.D,x)\n    end\n    s\nend\ndiag(p::FieldMatrix) = FieldVector(p.D)\n\nimport Base: *\n*(p::FieldMatrix,x::FieldVector) = mul!(zero(x),p,x)\n\n\"\"\"\n    Poisson(L)\n\nConstruct a symmetric `FieldMatrix` from lower diagonal coefficients `L` with zero-sum rows.\nThis is a requirement for conservative Poisson equations: ∫ ∇⋅β∇ϕ dv = ∮ β ∂ϕ/∂n da.\n\"\"\"\nfunction Poisson(L::AbstractArray{T}) where T\n    D = zeros(T,Base.front(size(L)))\n    R = inside(D)\n    for I ∈ R; D[I] = calcdiag(I,L); end\n    FieldMatrix(L,D,R)\nend\n@fastmath @inline calcdiag(I::CartesianIndex{N},L) where {N} =\n    -sum(@inbounds(L[I,i]+L[I+δ(i,N),i]) for i ∈ 1:N)\n", "meta": {"hexsha": "c5c3482faa8f459b5ed22c04e3313a1684f1e296", "size": 1980, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FieldMatrix.jl", "max_stars_repo_name": "navidcy/GeometricMultigrid.jl", "max_stars_repo_head_hexsha": "8b4c2f963352b4ac297f19399fc7789c424814dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-09-19T11:02:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:23:33.000Z", "max_issues_repo_path": "src/FieldMatrix.jl", "max_issues_repo_name": "navidcy/GeometricMultigrid.jl", "max_issues_repo_head_hexsha": "8b4c2f963352b4ac297f19399fc7789c424814dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-09-22T08:26:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T11:40:50.000Z", "max_forks_repo_path": "src/FieldMatrix.jl", "max_forks_repo_name": "navidcy/GeometricMultigrid.jl", "max_forks_repo_head_hexsha": "8b4c2f963352b4ac297f19399fc7789c424814dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-01T14:39:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T10:19:47.000Z", "avg_line_length": 34.7368421053, "max_line_length": 92, "alphanum_fraction": 0.6080808081, "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7624097321726465}}
{"text": "# 1-D interpolation from irregularly sampled data.\n\nimport PyPlot\nimport Random\nimport FIRRemez\n\nfig_num = 1\nPyPlot.close(\"all\")\n\nRandom.seed!(25)\n\n# generate sampling locations.\nN_samples = 25\nX = convert( Vector{BigFloat}, randn(N_samples).*π )\n\n# generate samples.\nY = sin.(X)\n\n# query.\nN_queries = 500\nxq_BF = convert(Vector{BigFloat}, collect( LinRange(minimum(X), maximum(X), N_queries) ) )\nyq_BF = collect( FIRRemez.Barycentric2nditp(xq_BF[i],X,Y) for i = 1:length(xq_BF) )\n\nxq = convert(Vector{Float64}, xq_BF)\nyq = convert(Vector{Float64}, yq_BF)\n\nX_display = convert(Vector{Float64}, X)\nY_display = convert(Vector{Float64}, Y)\n\nPyPlot.figure(fig_num)\nfig_num += 1\nPyPlot.plot(xq, yq, label = \"Barycentric\")\nPyPlot.plot(X_display, Y_display, label = \"samples\", \"x\")\nPyPlot.title(\"Barycentric interpolation\")\nPyPlot.legend()\n", "meta": {"hexsha": "b432a707cfcccdc4910e2cce4716ab94f1e7d1f7", "size": 833, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/barycentric.jl", "max_stars_repo_name": "RoyCCWang/FIRRemez", "max_stars_repo_head_hexsha": "41a3ad4e8bd851d51a62c7fcd35ac3abf6fdd84c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/barycentric.jl", "max_issues_repo_name": "RoyCCWang/FIRRemez", "max_issues_repo_head_hexsha": "41a3ad4e8bd851d51a62c7fcd35ac3abf6fdd84c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/barycentric.jl", "max_forks_repo_name": "RoyCCWang/FIRRemez", "max_forks_repo_head_hexsha": "41a3ad4e8bd851d51a62c7fcd35ac3abf6fdd84c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1388888889, "max_line_length": 90, "alphanum_fraction": 0.731092437, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072387, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7624097320546442}}
{"text": "# Is z within an isapprox of any x[i] ? \n# Assumes that x is sorted from lowest to highest\nfunction nearby(z::T, x::Vector{T}) where {T}\n    top = length(x)\n    bot = 1\n    mid = div(top, 2)\n    while bot < mid < top\n        if z > x[mid]\n            bot = mid\n        elseif z < x[mid]\n            top = mid\n        else\n            return mid\n        end\n        mid = bot + div(top-bot, 2)\n    end\n    isapprox(x[bot], z) && return bot\n    isapprox(x[top], z) && return top\n    return -1   # should error\nend\n\n\n# For general location points with precalculated weights\n\"\"\" \n    bary(z, f, x, w)  \n\nevaluate f(z)\n\n# Arguments\n- `z::Float64`:         the point at which to evaluate f\n- `f::Vector{Float64}`: vector of function values at x\n- `x:Vector{Float64}`:  vector of eval locations of f (sorted)\n- `w:Vector{Float64}`:  weights for locations x\n\"\"\"\nfunction bary(z::T, f::Vector{T}, x::Vector{T}, w::Vector{T}) where {T}\n    # assert(length(f) == length(x) == length(w))\n    num = zero(T)\n    den = zero(T)\n    @inbounds for j = 1:length(f)\n        t = w[j] / (z - x[j])\n        num += t * f[j]\n        den += t\n    end\n    fz = num / den\n    fz = isnan(fz) ? f[nearby(z, x)] : fz\nend\n\n\nfunction bary(z, f)\n    n = length(f)\n    x = chebpts(n)\n    num = den = zero(z)\n    t = 1 / 2(z - x[1])\n    num += t * f[1]\n    den += t\n    sgn = -1\n    @inbounds for j = 2:n-1\n        t = sgn / (z - x[j])\n        num += t*f[j]\n        den += t\n        sgn = -sgn\n    end\n    t = sgn / 2(z - x[n])\n    num += t * f[n]\n    den += t\n    fz = num / den\n    fz = isnan(fz) ? f[nearby(z, x)] : fz    \nend\n\n\n", "meta": {"hexsha": "eb70171baf473c46e4764f91400b1dec5bd79392", "size": 1596, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bary.jl", "max_stars_repo_name": "macd/BaryRational.jl", "max_stars_repo_head_hexsha": "6e5bb75e6fa3146bea855d2412fb45fecf9a8103", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-01-28T20:12:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T03:34:03.000Z", "max_issues_repo_path": "src/bary.jl", "max_issues_repo_name": "macd/BaryRational.jl", "max_issues_repo_head_hexsha": "6e5bb75e6fa3146bea855d2412fb45fecf9a8103", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-22T09:05:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-22T09:05:02.000Z", "max_forks_repo_path": "src/bary.jl", "max_forks_repo_name": "macd/BaryRational.jl", "max_forks_repo_head_hexsha": "6e5bb75e6fa3146bea855d2412fb45fecf9a8103", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4788732394, "max_line_length": 71, "alphanum_fraction": 0.5, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7624097302542983}}
{"text": "#The m-by-n Hilbert matrix has matrix elements\n# H_{ij} = 1/(i+j-1)\nexport Hilbert, InverseHilbert\n\nstruct Hilbert{T} <: AbstractMatrix{T}\n    m :: Int\n    n :: Int\nend\nHilbert(T::Type, m::Integer, n::Integer) = Hilbert{T}(m, n)\nHilbert(T::Type{<:Integer}, m::Integer, n::Integer) = Hilbert(Rational{T}, m, n)\nHilbert(m::Integer, n::Integer) = Hilbert(Int, m, n)\nHilbert(n::Integer) = Hilbert(n, n)\n\n# Define its size\nsize(H::Hilbert, dim::Integer) = dim==1 ? H.m : dim==2 ? H.n : 1\nsize(H::Hilbert)= size(H,1), size(H,2)\n\n# Index into a Hilbert matrix\nfunction getindex(H::Hilbert{T}, i::Integer, j::Integer) where {T}\n    return one(T)/(i+j-1)\nend\n\n# Dense version\nMatrix(H::Hilbert) = [H[i,j] for i=1:size(H,1), j=1:size(H,2)]\n\n# Some properties\nishermitian(H::Hilbert) = H.m==H.n\nisposdef(H::Hilbert) = H.m==H.n\ndet(H::Hilbert) = inv(det(inv(H)))\n\n\n# Inverse of a Hilbert matrix\nstruct InverseHilbert{T} <: AbstractMatrix{T}\n    n :: Int\nend\nInverseHilbert(T::Type, n::Integer) = InverseHilbert{T}(n)\nInverseHilbert(n::Integer) = InverseHilbert(Int, n)\n\n# Define its size\nsize(A::InverseHilbert, dim::Integer) = dim==1 || dim==2 ? A.n : 1\nsize(A::InverseHilbert) = size(A,1), size(A,2)\n\n# Index into a inverse Hilbert matrix\nfunction getindex(A::InverseHilbert{T}, i::Integer, j::Integer) where {T}\n    return T((-1)^(i+j)*(i+j-1)*binomial(A.n+i-1,A.n-j)*\n              binomial(A.n+j-1,A.n-i)*binomial(i+j-2,i-1)^2)\nend\n# Use bigger numbers in case of bigger types\nfunction getindex(A::InverseHilbert{T}, i::Integer, j::Integer) where {T<:Union{BigInt,BigFloat}}\n    N = big(A.n)\n    return T((-1)^(i+j)*(i+j-1)*binomial(N+i-1,N-j)*\n              binomial(N+j-1,N-i)*binomial(big(i+j-2),i-1)^2)\nend\n\n# Explicit formula for the determinant\ndet(A::InverseHilbert{T}) where {T} = prod(T,(2k+1)*binomial(2k,k)^2 for k=1:A.n-1)\n\n# Dense version\nMatrix(A::InverseHilbert) = [A[i,j] for i=1:size(A,1), j=1:size(A,2)]\n\n# Define Base.inv\nfunction inv(H::Hilbert{T}) where {T}\n    H.m == H.n || throw(ArgumentError(\"Works only for square Hilbert matrices.\"))\n    return InverseHilbert(T,H.n)\nend\nfunction inv(A::InverseHilbert{T}) where {T}\n    HT = promote_type(T,typeof(Rational(one(T))))\n    return Hilbert(HT,A.n)\nend\n", "meta": {"hexsha": "3928333e12af49d29c577fae6b6c0472c4d9167f", "size": 2217, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hilbert.jl", "max_stars_repo_name": "fkastner/SpecialMatrices.jl", "max_stars_repo_head_hexsha": "2915d5c4adeb200e6617d64bb44ef75d47e3eea5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hilbert.jl", "max_issues_repo_name": "fkastner/SpecialMatrices.jl", "max_issues_repo_head_hexsha": "2915d5c4adeb200e6617d64bb44ef75d47e3eea5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hilbert.jl", "max_forks_repo_name": "fkastner/SpecialMatrices.jl", "max_forks_repo_head_hexsha": "2915d5c4adeb200e6617d64bb44ef75d47e3eea5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6714285714, "max_line_length": 97, "alphanum_fraction": 0.650428507, "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7624097264176014}}
{"text": "function getIja(Ia::Matrix{T}, j::Int, N::Int) where T\n\n    Id = [one(T) zero(T); zero(T) one(T)]\n\n    Ias = collect( Id for i = 1:N )\n    Ias[j] = Ia\n    return Kronecker.kron(Ias...)\nend\n\nfunction productIaIb(Ixs, Iys, Izs, a::Int, b::Int)\n    return Ixs[a]*Ixs[b] + Iys[a]*Iys[b] + Izs[a]*Izs[b]\nend\n\n\"\"\"\nFor operator A.\n\nExample:\nN = 3\nIxs = collect( getIja(Ix, i, N) for i = 1:N )\nIys = collect( getIja(Iy, i, N) for i = 1:N )\nIzs = collect( getIja(Iz, i, N) for i = 1:N )\n\n# sanity check.\nout1 = productIaIb(Ixs, Iys, Izs, 1, 3)\nout2 = productIjIk(Ixs, Iys, Izs, [1;], [3;])\nnorm(out1-out2)\n\"\"\"\nfunction productIjIk(Ixs, Iys, Izs, inds_j::Vector{Int}, inds_k::Vector{Int})\n\n    #\n\n    out = sum(Ixs[j] for j in inds_j) * sum(Ixs[k] for k in inds_k) +\n        sum(Iys[j] for j in inds_j) * sum(Iys[k] for k in inds_k) +\n        sum(Izs[j] for j in inds_j) * sum(Izs[k] for k in inds_k)\n\n    return out\nend\n\n\n\"\"\"\nfor operator B.\n\nExample:\nN = 3\nIxs = collect( getIja(Ix, i, N) for i = 1:N )\nIys = collect( getIja(Iy, i, N) for i = 1:N )\nIzs = collect( getIja(Iz, i, N) for i = 1:N )\n\n# # sanity check.\n# out1 = productIaIb(Ixs, Iys, Izs, 1, 3)\n# out2 = productIjIk(Ixs, Iys, Izs, [1;], [3;])\n\nout1 = pairwiseproductIa(Ixs, Iys, Izs, [1; 2; 3])\nout2 = productIaIb(Ixs, Iys, Izs, 1, 3) + productIaIb(Ixs, Iys, Izs, 2, 3) + productIaIb(Ixs, Iys, Izs, 1, 2)\nnorm(out1-out2)\n\"\"\"\nfunction pairwiseproductIa(Ixs, Iys, Izs, inds::Vector{Int})\n\n    out = zeros(Float64, size(Ixs[1]))\n    for i = 1:length(inds)\n\n        ind1 = inds[i]\n        for j = i+1:length(inds)\n            ind2 = inds[j]\n\n            out += productIaIb(Ixs, Iys, Izs, ind1, ind2)\n        end\n    end\n\n    return out\nend\n", "meta": {"hexsha": "d37bb8cf01d6ef054d8ae4afca125c35731be7e9", "size": 1689, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "mag_eq/helpers/operators.jl", "max_stars_repo_name": "AI4DBiological-Systems/NMRSpectraSimulator.jl", "max_stars_repo_head_hexsha": "b03e18962c4b6dd151b5d9309ee3a77fe870c2be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mag_eq/helpers/operators.jl", "max_issues_repo_name": "AI4DBiological-Systems/NMRSpectraSimulator.jl", "max_issues_repo_head_hexsha": "b03e18962c4b6dd151b5d9309ee3a77fe870c2be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mag_eq/helpers/operators.jl", "max_forks_repo_name": "AI4DBiological-Systems/NMRSpectraSimulator.jl", "max_forks_repo_head_hexsha": "b03e18962c4b6dd151b5d9309ee3a77fe870c2be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4583333333, "max_line_length": 109, "alphanum_fraction": 0.5808170515, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7624097187442076}}
{"text": "function LC(p, var)\n    d = maxdegree(p, var)\n    d == 0 && return zero(p)\n    return polynomial([subs(t, var => 1) for t in terms(p) if degree(t, var) == d])\nend\n\nfunction pseudorem(f, g, y)\n    r = f\n    lc = LC(g, y)\n    m = maxdegree(g, y)\n    d = maxdegree(r, y)\n\n    while d ≥ m && !iszero(r)\n        r = lc * r - LC(r, y) * g * y ^ (d - m)\n        d = maxdegree(r, y)\n    end\n\n    return r\nend\n\nfunction triangulize(H, vars)\n    n = length(H)\n\n    T = similar(H)\n    @inbounds for i = n:-1:1\n        degrees = Int[] # degrees of polynomials in C\n        indeces = Int[] # indeces in H of polynomials in C\n\n        # initialize\n        @inbounds for (idx, p) in enumerate(H)\n            deg = maxdegree(p, vars[i])\n            if deg > 0\n                push!(degrees, deg)\n                push!(indeces, idx)\n            end\n        end\n\n        # If there are several polynomials in C but none has degree 1 in x, transform the\n        # set until there is a polynomial of degree 1 or only one polynomial is left\n        C = H[indeces]\n        while minimum(degrees) > 1 && length(C) > 1\n            _, idx_max = findmax(degrees)\n            _, idx_min = findmin(degrees)\n\n            # special case when all  have same degree\n            if idx_max == idx_min\n                idx_min = 1\n                idx_max = 2\n            end\n\n            r = pseudorem(C[idx_max], C[idx_min], vars[i])\n            d = maxdegree(r, vars[i])\n            if iszero(d)\n                H[indeces[idx_max]] = r\n                deleteat!(C, idx_max)\n                deleteat!(degrees, idx_max)\n                deleteat!(indeces, idx_max)\n            else\n                C[idx_max] = r\n                degrees[idx_max] = d\n            end\n        end\n\n        # if only one polynomial in C, add to triangular set and go to the next variable\n        if length(indeces) == 1\n            T[i] = H[indeces[1]]\n            deleteat!(H, indeces[1])\n            continue\n        end\n\n        # if multiple polynomials but at least one has degree 1, add this to triangular set\n        # and replace the others in H with the pseudoremainder\n        idx = findlast(==(1), degrees)\n        if !isnothing(idx)\n            pivot = H[indeces[idx]]\n            T[i] = pivot\n            #pushfirst!(T, pivot)\n\n            @inbounds for j in indeces\n                if j != indeces[idx]\n                    H[j] = pseudorem(H[j], pivot, vars[i])\n                end\n            end\n            deleteat!(H, indeces[idx])\n            continue\n        end\n\n    end\n    return T\nend\n", "meta": {"hexsha": "9c7807ba858a085c8e6d02dc7145c1974d970794", "size": 2554, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rittwu/triangulize.jl", "max_stars_repo_name": "lucaferranti/GeometricTheoremProver.jl", "max_stars_repo_head_hexsha": "970ed8fffe5011b22a757277cc8ac529efe50850", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2022-01-16T19:09:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:15:30.000Z", "max_issues_repo_path": "src/rittwu/triangulize.jl", "max_issues_repo_name": "lucaferranti/GeometricTheoremProver.jl", "max_issues_repo_head_hexsha": "970ed8fffe5011b22a757277cc8ac529efe50850", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-01-17T09:00:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T19:13:36.000Z", "max_forks_repo_path": "src/rittwu/triangulize.jl", "max_forks_repo_name": "lucaferranti/GeometricTheoremProver.jl", "max_forks_repo_head_hexsha": "970ed8fffe5011b22a757277cc8ac529efe50850", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0659340659, "max_line_length": 91, "alphanum_fraction": 0.4925606891, "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7624097169045274}}
{"text": "# # Even reduction\n\n#md # [![](https://mybinder.org/badge_logo.svg)](@__BINDER_ROOT_URL__/generated/Symmetry/even_reduction.ipynb)\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/generated/Symmetry/even_reduction.ipynb)\n\nusing Test #src\nusing DynamicPolynomials\n@polyvar x\n\n# We would like to find the minimum value of the following polynomial:\n\npoly = x^4 - 2x^2\n\nusing SumOfSquares\n\n# We define the custom action as follows:\n\nstruct OnSign <: Symmetry.OnMonomials end\nusing PermutationGroups\nimport SymbolicWedderburn\nSymbolicWedderburn.coeff_type(::OnSign) = Float64\nfunction SymbolicWedderburn.action(::OnSign, p::Permutation, mono::AbstractMonomial)\n    if isone(p) || iseven(DynamicPolynomials.degree(mono))\n        return 1 * mono\n    else\n        @assert p.perm == perm\"(1,2)\"\n        return -1 * mono\n    end\nend\nG = PermGroup([perm\"(1,2)\"])\n\n# We can exploit the symmetry as follows:\n\nimport CSDP\nsolver = CSDP.Optimizer\nmodel = Model(solver)\n@variable(model, t)\n@objective(model, Max, t)\npattern = Symmetry.Pattern(G, OnSign())\ncon_ref = @constraint(model, poly - t in SOSCone(), symmetry = pattern)\noptimize!(model)\n@test value(t) ≈ -1 #src\nvalue(t)\n\n# We indeed find `-1`, let's verify that symmetry was exploited:\n\n@test length(gram_matrix(con_ref).sub_gram_matrices) == 2 #src\n@test gram_matrix(con_ref).sub_gram_matrices[1].basis.polynomials == [x^2, 1] #src\n@test gram_matrix(con_ref).sub_gram_matrices[2].basis.polynomials == [x] #src\ngram_matrix(con_ref)\n", "meta": {"hexsha": "ac54c50303196d01c33b1c79ca9af377e0310d8f", "size": 1516, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/tutorials/Symmetry/even_reduction.jl", "max_stars_repo_name": "blegat/SumOfSquares", "max_stars_repo_head_hexsha": "a4e1a6ac8853bb3df3e46e33e6cce658c1c6df12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2016-11-10T11:05:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-10T09:08:47.000Z", "max_issues_repo_path": "docs/src/tutorials/Symmetry/even_reduction.jl", "max_issues_repo_name": "blegat/SumOfSquares", "max_issues_repo_head_hexsha": "a4e1a6ac8853bb3df3e46e33e6cce658c1c6df12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 138, "max_issues_repo_issues_event_min_datetime": "2016-11-23T01:37:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-08T18:13:22.000Z", "max_forks_repo_path": "docs/src/tutorials/Symmetry/even_reduction.jl", "max_forks_repo_name": "blegat/SumOfSquares", "max_forks_repo_head_hexsha": "a4e1a6ac8853bb3df3e46e33e6cce658c1c6df12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2017-03-16T20:55:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T19:05:37.000Z", "avg_line_length": 29.7254901961, "max_line_length": 130, "alphanum_fraction": 0.734828496, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7624094699236517}}
{"text": "function binary(n::Int)\r\n\tans=Int[]\r\n\twhile n>=1\r\n\t\t\r\n\t\tpush!(ans,n%2)\r\n\t\tn=floor(Int,n/2)\r\n\r\n\tend\r\n\r\n\treturn reverse(ans)\r\nend\r\n\r\nfunction is_decimal_binary_palindrome(n::Int)\r\n\ts=string(n)\r\n\tif s!=reverse(s)\r\n\t\treturn false\r\n\tend\r\n\r\n\tbin=binary(n)\r\n\t\r\n\treturn bin==reverse(bin)\r\nend\r\n\r\n\r\nfunction compute()\r\n\r\n\tans= sum(i for i=1:1000000 if is_decimal_binary_palindrome(i))\r\n\r\n\treturn ans\r\nend\r\n\r\n\r\n\r\nprintln(compute())\r\n\r\n", "meta": {"hexsha": "2c197be9ad3bef7e2aec87195df22e3341649693", "size": 425, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/p036.jl", "max_stars_repo_name": "tlming16/Projec_Euler", "max_stars_repo_head_hexsha": "797824c5159fae67493de9eba24c22cc7512d95d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-11-14T12:03:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-03T14:33:28.000Z", "max_issues_repo_path": "julia/p036.jl", "max_issues_repo_name": "tlming16/Projec_Euler", "max_issues_repo_head_hexsha": "797824c5159fae67493de9eba24c22cc7512d95d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/p036.jl", "max_forks_repo_name": "tlming16/Projec_Euler", "max_forks_repo_head_hexsha": "797824c5159fae67493de9eba24c22cc7512d95d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-17T14:39:22.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-17T14:39:22.000Z", "avg_line_length": 11.8055555556, "max_line_length": 64, "alphanum_fraction": 0.6329411765, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929796, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7624094623894174}}
{"text": "################################################\n## Specialized routines for tridiagonal matrices\n################################################\n\nexport numnegevals\n\n\"\"\"\nComputes the number of negative eigenvalues of T - σI, a.k.a. spectrum slicing\n\nInputs:\n    T: A SymTridiagonal{<:Real} matrix\n    σ: The shift parameter\n\nOutputs:\n    ν: The number of negative eigenvalues\n\nReference:\n    B. N. Parlett, \"The symmetric eigenvalue problem\", Section 3.3.1, p. 52.\n\"\"\"\nfunction numnegevals(T::SymTridiagonal{S}, σ::S = zero(S)) where S\n    α = T.dv\n    β = T.ev\n    n = length(α)\n    ϵ = eps(S)\n    δ = α[1] - σ\n    ν = δ < 0 ? 1 : 0\n    for k = 1:n - 1\n        if δ == 0\n        info(\"zero in iteration $k\")\n        δ = ϵ * (β[k]+ϵ) #Parlett prefers adjusting σ and starting again\n    end\n        δ = (α[k + 1] - σ) - β[k]*(β[k]/δ)\n    ν += (δ < 0)\n    end\n    ν\nend\n", "meta": {"hexsha": "a6bf562b16c2ffe290f0a60517b694ac24f7d05f", "size": 870, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tridiag.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/GenericLinearAlgebra.jl-14197337-ba66-59df-a3e3-ca00e7dcff7a", "max_stars_repo_head_hexsha": "4bd2e537f93279228c1c608e3354e221f648b3b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 79, "max_stars_repo_stars_event_min_datetime": "2018-12-16T12:11:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:32:55.000Z", "max_issues_repo_path": "src/tridiag.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/GenericLinearAlgebra.jl-14197337-ba66-59df-a3e3-ca00e7dcff7a", "max_issues_repo_head_hexsha": "4bd2e537f93279228c1c608e3354e221f648b3b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47, "max_issues_repo_issues_event_min_datetime": "2018-12-05T20:50:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T21:45:56.000Z", "max_forks_repo_path": "src/tridiag.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/GenericLinearAlgebra.jl-14197337-ba66-59df-a3e3-ca00e7dcff7a", "max_forks_repo_head_hexsha": "4bd2e537f93279228c1c608e3354e221f648b3b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2018-12-16T12:11:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T17:26:44.000Z", "avg_line_length": 23.5135135135, "max_line_length": 78, "alphanum_fraction": 0.5103448276, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900945711678, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7624094603357715}}
{"text": "using JuMP\nusing Cbc\n\ninclude(\"../OptMaps.jl\")\nusing .OptMaps\n\nfunction solve_model(solver, model_log, solver_options=Dict())\n    model = Model(solver)\n\n    for (k, v) in solver_options\n        set_optimizer_attribute(model, k, v)\n    end\n\n    n_variables = 7\n    n_constraints = 4\n\n    @variable(model, 0 <= x[1:6] <= 10, Int)\n    @variable(model, 0 <= y <= 1, Int)\n    \n    ocoeffs = [60 70 40 70 20 90]\n    ccoeffs = [30 20 30 90 30 70]\n    \n    @constraint(model, sum((x[i]*ccoeffs[i] for i in 1:6)) <= 2000)\n    @constraint(model, x[3] <= 10*x[4])\n    @constraint(model, x[1] + x[2] >= 4*y)\n    @constraint(model, x[5] + x[6] >= 4*(1 - y))\n\n    constraints_f = []\n    push!(constraints_f, (v) -> sum((v[i]*ccoeffs[i] for i in 1:6)) <= 2000)\n    push!(constraints_f, (v) -> v[3] <= 10*v[4])\n    push!(constraints_f, (v) -> v[1] + v[2] >= 4*v[7])\n    push!(constraints_f, (v) -> v[5] + v[6] >= 4*(1 - v[7]))\n\n    @objective(model, Max, sum(x[i]*ocoeffs[i] for i in 1:6))\n    obj_f(v) = sum(v[i]*ocoeffs[i] for i in 1:6)\n\n    starting_point = zeros(Float64, n_variables)\n    solution_point = zeros(Float64, n_variables)\n\n    ###############################################################\n    #save model textual description\n    open(model_log, \"w\") do f\n        print(f, model)\n\n        ###############################################################\n        #solve model\n        elapsed_time = @elapsed optimize!(model)\n\n        println(f, \"-----------------------------------------------\")\n        println(f, \"Elapsed time: $elapsed_time\")\n        println(f, \"-----------------------------------------------\")\n        println(f, \"Status:    $(termination_status(model))\")\n        println(f, \"Objective: $(objective_value(model))\")\n        println(f, \"-----------------------------------------------\")\n        println(f, \"Variables:\")\n\n        for i in 1:(n_variables-1)\n            println(f, \"$(x[i]): $(value(x[i]))\")\n            solution_point[i] = value(x[i])\n        end\n\n        println(f, \"$(y): $(value(y))\")\n        solution_point[n_variables] = value(y)\n    end\n\n    variable_names = vcat([\"x[$(string(i))]\" for i in 1:(n_variables-1)], [\"y\"])\n    constraint_names = [\"c$(string(c))\" for c in 1:n_constraints]\n\n    obj_val = objective_value(model)\n\n    return obj_f, constraints_f, variable_names, constraint_names, starting_point, solution_point, obj_val\nend\n\n#The datatype used in the tuples is used to determine if the variable is \"real\" or integer\nvariable_domains = [(0, 12), (0, 12), (0, 12), (0, 12), (0, 12), (0, 12), (0, 1)]\n\noptimizers = [Cbc.Optimizer]\nopt_names = [\"cbc\"]\n\nproblems = Dict()\n\nfor (opt, opt_name) in zip(optimizers, opt_names)\n    objective_f, constraints_f, variable_names, constraint_names, starting_point, solution_point, obj_val = solve_model(opt, \"knapsack_$(opt_name).log\")\n    problems[opt_name] = (objective_f, constraints_f, variable_names, constraint_names, starting_point, solution_point, obj_val)\nend\n\n#All functions are equal, get first to initialize OptMap\nobjective_f, constraints_f, variable_names, constraint_names, _, _, obj_val = problems[opt_names[1]]\nO = OptMap(variable_names, variable_domains, objective_f; constraint_names=constraint_names, constraints_f=constraints_f, verbose=true)\ncreate_map!(O)\n\nfor opt_name in opt_names\n    _, _, _, _, starting_point, solution_point, _ = problems[opt_name]\n\n    path_to_solution = zeros(Float64, length(variable_domains), 2)\n    path_to_solution[:,1] = starting_point\n    path_to_solution[:,2] = solution_point\n\n    draw_solution!(O, path_to_solution)\n    save_all(O, \"knapsack_$(opt_name)\", \".\")\nend\n\n", "meta": {"hexsha": "66ba4277308891bc27157c819ccd7c8be5cf7a8e", "size": 3608, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/knapsack.jl", "max_stars_repo_name": "nmaterise/optmap", "max_stars_repo_head_hexsha": "5a92727668e26d3a1270e4588dfe2d3ccbb4ba51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-24T20:35:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T20:35:08.000Z", "max_issues_repo_path": "examples/knapsack.jl", "max_issues_repo_name": "nmaterise/optmap", "max_issues_repo_head_hexsha": "5a92727668e26d3a1270e4588dfe2d3ccbb4ba51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/knapsack.jl", "max_forks_repo_name": "nmaterise/optmap", "max_forks_repo_head_hexsha": "5a92727668e26d3a1270e4588dfe2d3ccbb4ba51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-25T00:06:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T00:06:56.000Z", "avg_line_length": 35.0291262136, "max_line_length": 152, "alphanum_fraction": 0.5898004435, "num_tokens": 1010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915913, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7623500322428255}}
{"text": "function eval_metric(::Val{:mse}, p::AbstractMatrix{T}, y::AbstractVector{T}, α=0.0) where {T <: AbstractFloat}\n    eval = zero(T)\n    @inbounds for i in eachindex(y)\n        eval += (p[1,i] - y[i])^2\n    end\n    eval /= length(y)\n    return eval\nend\n\nfunction eval_metric(::Val{:rmse}, p::AbstractMatrix{T}, y::AbstractVector{T}, α=0.0) where {T <: AbstractFloat}\n    eval = zero(T)\n    @inbounds for i in eachindex(y)\n        eval += (p[1,i] - y[i])^2\n    end\n    eval = sqrt(eval / length(y))\n    return eval\nend\n\nfunction eval_metric(::Val{:mae}, p::AbstractMatrix{T}, y::AbstractVector{T}, α=0.0) where {T <: AbstractFloat}\n    eval = zero(T)\n    @inbounds for i in eachindex(y)\n        eval += abs(p[1,i] - y[i])\n    end\n    eval /= length(y)\n    return eval\nend\n\nfunction eval_metric(::Val{:logloss}, p::AbstractMatrix{T}, y::AbstractVector{T}, α=0.0) where {T <: AbstractFloat}\n    eval = zero(T)\n    @inbounds for i in eachindex(y)\n        pred = sigmoid(p[1,i])\n        eval -= y[i] * log(pred) + (1 - y[i]) * log(1 - pred)\n    end\n    eval /= length(y)\n    return eval\nend\n\nfunction eval_metric(::Val{:mlogloss}, p::AbstractMatrix{T}, y::AbstractVector{S}, α=0.0) where {T <: AbstractFloat,S <: Integer}\n    eval = zero(T)\n    p_prob = exp.(p) ./ sum(exp.(p), dims=1) \n    @inbounds for i in eachindex(y)\n        eval -= log(p_prob[y[i], i])\n    end\n    eval /= length(y)\n    return eval\nend\n\nfunction eval_metric(::Val{:poisson}, p::AbstractMatrix{T}, y::AbstractVector{T}, α=0.0) where {T <: AbstractFloat}\n    eval = zero(T)\n    @inbounds for i in eachindex(y)\n        eval += exp(p[1,i]) * (1 - y[i]) + log(factorial(y[i]))\n    end\n    eval /= length(y)\n    return eval\nend\n\nfunction eval_metric(::Val{:gaussian}, p::AbstractMatrix{T}, y::AbstractVector{T}, α=0.0) where {T <: AbstractFloat}\n    eval = zero(T)\n    @inbounds for i in eachindex(y)\n        eval += p[2,i] + (y[i] - p[1,i])^2 / (2 * exp(2 * p[2,i]))\n    end\n    eval /= length(y)\n    return eval\nend\n\nfunction eval_metric(::Val{:quantile}, p::AbstractMatrix{T}, y::AbstractVector{T}, α=0.0) where {T <: AbstractFloat}\n    eval = zero(T)\n    for i in eachindex(y)\n        eval += α * max(y[i] - p[1,i], zero(T)) + (1 - α) * max(p[1,i] - y[i], zero(T))\n    end\n    eval /= length(y)\n    return eval\nend\n\n\nfunction gini_raw(y::T, p::S) where {T,S}\n    if length(y) < 2 \n        return 0.0\n    end\n    random = (1:length(p)) ./ length(p)\n    l_sort = y[sortperm(p)]\n    l_cum_w = cumsum(l_sort) ./ sum(y)\n    gini = sum(l_cum_w .- random)\n    return gini\nend\n\nfunction gini_norm(y::T, p::S) where {T,S}\n    if length(y) < 2 \n        return 0.0\n    end\n    return gini_raw(y, p) / gini_raw(y, y)\nend\n\nfunction eval_metric(::Val{:gini}, p::AbstractMatrix{T}, y::AbstractVector{T}, α=0.0) where {T <: AbstractFloat}\n    return -gini_norm(y, view(p, 1, :))\nend", "meta": {"hexsha": "392919a5c778cdd77504f93930e2e8885fc56c82", "size": 2831, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/eval.jl", "max_stars_repo_name": "Evovest/EvoTrees.jl", "max_stars_repo_head_hexsha": "782a7f77209547677d51439f14a6b17b41b01173", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 96, "max_stars_repo_stars_event_min_datetime": "2019-05-01T05:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:32:33.000Z", "max_issues_repo_path": "src/eval.jl", "max_issues_repo_name": "Evovest/EvoTrees.jl", "max_issues_repo_head_hexsha": "782a7f77209547677d51439f14a6b17b41b01173", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 67, "max_issues_repo_issues_event_min_datetime": "2019-05-23T08:20:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T23:27:03.000Z", "max_forks_repo_path": "src/eval.jl", "max_forks_repo_name": "Evovest/EvoTrees.jl", "max_forks_repo_head_hexsha": "782a7f77209547677d51439f14a6b17b41b01173", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-05-31T02:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T22:39:41.000Z", "avg_line_length": 29.4895833333, "max_line_length": 129, "alphanum_fraction": 0.5853055457, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.76235002871426}}
{"text": "using Printf\nK = 0; N = 10000000;\n@time begin\nfor i in 1:N\n  if (rand()^2 + rand()^2) < 1.0\n    global K += 1\n  end\nend\nend\np = (4*K)/N\n@printf \"Estimation of PI is %.6f\\n\" p\n", "meta": {"hexsha": "22c23f2ff7ef4ef1a446053ffae630f93b7c71b1", "size": 175, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chp01/Code/pi.jl", "max_stars_repo_name": "PetrKryslUCSD/Mastering-Julia-1.0", "max_stars_repo_head_hexsha": "375342d933a48142b5b605b9c39cb5922e010691", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chp01/Code/pi.jl", "max_issues_repo_name": "PetrKryslUCSD/Mastering-Julia-1.0", "max_issues_repo_head_hexsha": "375342d933a48142b5b605b9c39cb5922e010691", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chp01/Code/pi.jl", "max_forks_repo_name": "PetrKryslUCSD/Mastering-Julia-1.0", "max_forks_repo_head_hexsha": "375342d933a48142b5b605b9c39cb5922e010691", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-15T19:05:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T19:05:40.000Z", "avg_line_length": 14.5833333333, "max_line_length": 38, "alphanum_fraction": 0.5714285714, "num_tokens": 82, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7623500266419243}}
{"text": "# # Symmetry reduction\n\n#md # [![](https://mybinder.org/badge_logo.svg)](@__BINDER_ROOT_URL__/generated/Symmetry/symmetry_reduction.ipynb)\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/generated/Symmetry/symmetry_reduction.ipynb)\n# **Adapted from**: [SymbolicWedderburn example](https://github.com/kalmarek/SymbolicWedderburn.jl/blob/tw/ex_sos/examples/ex_C4.jl)\n\nimport MutableArithmetics\nconst MA = MutableArithmetics\nusing MultivariatePolynomials\nconst MP = MultivariatePolynomials\nusing MultivariateBases\nconst MB = MultivariateBases\n\nusing Test #src\nusing DynamicPolynomials\n@polyvar x[1:4]\n\n# We would like to find the minimum value of the polynomial\n\npoly = sum(x) + sum(x.^2)\n\n# As we can decouple the problem for each `x[i]` for which `x[i] + x[i]^2` has\n# minimum value 0.25, we would expect to get `-1` as answer.\n# Can this decoupling be exploited by SumOfSquares as well ?\n# For this, we need to use a certificate that can exploit the permutation symmetry of the polynomial.\n\nusing SumOfSquares\n\n# We define the symmetry group as a permutation group in the variables.\n# In order to do that, we define the action of a permutation on a monomial\n# as the monomial obtained after permuting the variables.\n\nusing PermutationGroups\nG = PermGroup([perm\"(1,2,3,4)\"])\n\n# We can use this certificate as follows:\n\nimport CSDP\nsolver = CSDP.Optimizer\nmodel = Model(solver)\n@variable(model, t)\n@objective(model, Max, t)\npattern = Symmetry.Pattern(G, Symmetry.VariablePermutation())\ncon_ref = @constraint(model, poly - t in SOSCone(), symmetry = pattern)\noptimize!(model)\n@test value(t) ≈ -1 rtol=1e-6 #src\nvalue(t)\n\n# We indeed find `-1`, let's verify that symmetry was exploited:\n\ng = gram_matrix(con_ref).sub_gram_matrices    #src\n@test length(g) == 4                          #src\n@test length(g[1].basis.polynomials) == 2     #src\n@test g[1].basis.polynomials[1] == 1.0        #src\n@test g[1].basis.polynomials[2] ≈ -0.5 * sum(x) #src\n@test size(g[1].Q) == (2, 2)                  #src\n@test g[1].Q[1, 1] ≈ 1.0 atol=1e-6            #src\n@test g[1].Q[1, 2] ≈ -1.0 atol=1e-6            #src\n@test g[1].Q[2, 2] ≈ 1.0 atol=1e-6            #src\n@test length(g[2].basis.polynomials) == 1     #src\n@test g[2].basis.polynomials[1] ≈ (x[3] - x[1]) / √2 #src\n@test size(g[2].Q) == (1, 1)                  #src\n@test g[2].Q[1, 1] ≈ 1.0 atol=1e-6            #src\n@test length(g[3].basis.polynomials) == 1     #src\n@test g[3].basis.polynomials[1] ≈ (x[4] - x[2]) / √2 #src\n@test size(g[3].Q) == (1, 1)                  #src\n@test g[3].Q[1, 1] ≈ 1.0 atol=1e-6            #src\n@test length(g[4].basis.polynomials) == 1     #src\n@test g[4].basis.polynomials[1] ≈ (-x[1] + x[2] - x[3] + x[4]) / 2 #src\n@test size(g[4].Q) == (1, 1)                  #src\n@test g[4].Q[1, 1] ≈ 1.0 atol=1e-6            #src\nfor g in gram_matrix(con_ref).sub_gram_matrices\n    println(g.basis.polynomials)\nend\n", "meta": {"hexsha": "1477798b857bffe4fe9b433bf6008d5949778642", "size": 2920, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/tutorials/Symmetry/permutation_symmetry.jl", "max_stars_repo_name": "blegat/SumOfSquares", "max_stars_repo_head_hexsha": "a4e1a6ac8853bb3df3e46e33e6cce658c1c6df12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2016-11-10T11:05:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-10T09:08:47.000Z", "max_issues_repo_path": "docs/src/tutorials/Symmetry/permutation_symmetry.jl", "max_issues_repo_name": "blegat/SumOfSquares", "max_issues_repo_head_hexsha": "a4e1a6ac8853bb3df3e46e33e6cce658c1c6df12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 138, "max_issues_repo_issues_event_min_datetime": "2016-11-23T01:37:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-08T18:13:22.000Z", "max_forks_repo_path": "docs/src/tutorials/Symmetry/permutation_symmetry.jl", "max_forks_repo_name": "blegat/SumOfSquares", "max_forks_repo_head_hexsha": "a4e1a6ac8853bb3df3e46e33e6cce658c1c6df12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2017-03-16T20:55:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T19:05:37.000Z", "avg_line_length": 38.9333333333, "max_line_length": 134, "alphanum_fraction": 0.6537671233, "num_tokens": 990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7623500265635064}}
{"text": "# Single run of model with 2 parameters\nusing Turing, Statistics, Distributions, Random, LinearAlgebra, StatsPlots\nusing AdvancedMH\n\n# the data generating process\nfunction dgp(θ, n)\n    [rand.(Exponential(θ[1]),n) rand.(Poisson(θ[2]),n)] \nend\n\n# summary statistics for estimation\nfunction moments(y)\n    n = size(y,1)\n    sqrt(n) .* [mean(y, dims=1)[:]; std(y, dims=1)[:]]\nend\n\n@model function abc(z, S, n, calibrated)\n    # create the prior: the product of the following array of marginal priors\n    θ  ~ arraydist([LogNormal(1.,1.); LogNormal(1.,1.)])\n    # sample from the model, at the trial parameter value, and compute statistics\n    y = zeros(n,2)\n    zs = zeros(S, size(z,1))\n    @inbounds for i = 1:S\n        y .= dgp(θ, n)\n        zs[i,:] .= moments(y) # simulated summary statistics\n    end\n    # the asymptotic Gaussian distribution of the statistics\n    m = mean(zs, dims=1)[:]\n    calibrated ? Σ = Symmetric((1. + 1/S)*cov(zs)) : Σ = I\n    z ~ MvNormal(m, Σ)\nend;\n\nfunction main(calibrated=true)\n    θ⁰ = [2.; 3.] # true parameters\n    n = 100 # sample size\n    S = 100 # number of simulation draws\n    # get data and statistics\n    y = dgp(θ⁰, n)\n    z = moments(y)\n    # sample chains\n    length = 5000\n    burnin = 500\n    chain = sample(abc(z, S, n, calibrated), \n        MH(:θ => AdvancedMH.RandomWalkProposal(MvNormal(zeros(2), 0.25*I))),\n        MCMCThreads(), length+burnin, 4)\n    chain = chain[burnin+1:end,:,:]\n    @show display(chain)\n    p = plot(chain)\n    chain = Array(chain)\n    q1 = quantile(chain[:,1], [0.025, 0.975])\n    q2 = quantile(chain[:,2], [0.025, 0.975])\n    println()\n    println(\"is first true parameter inside 95% CI?\")\n    display(q1[1] <= θ⁰[1] && q1[2] >= θ⁰[1]) \n    println()\n    println(\"is second true parameter inside 95% CI?\")\n    display(q2[1] <= θ⁰[2] && q2[2] >= θ⁰[2])\n    p\nend\nprintln(\"first a well-calibrated run\")\np1 = main(true)\nprintln(\"now a poorly calibrated run\")\np2 = main(false)\nplot(p1, p2)\n\n", "meta": {"hexsha": "af326a0b704ef630f525829738ed23fce4d4cbdb", "size": 1963, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ParameterVector.jl", "max_stars_repo_name": "mcreel/ABC-MSM-Turing", "max_stars_repo_head_hexsha": "2dbd917cf7055e431bd69559bb226ee05901609f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-02-12T21:09:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T08:33:39.000Z", "max_issues_repo_path": "ParameterVector.jl", "max_issues_repo_name": "mcreel/ABC-MSM-Turing", "max_issues_repo_head_hexsha": "2dbd917cf7055e431bd69559bb226ee05901609f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-12T11:27:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T11:27:35.000Z", "max_forks_repo_path": "ParameterVector.jl", "max_forks_repo_name": "mcreel/ABC-MSM-Turing", "max_forks_repo_head_hexsha": "2dbd917cf7055e431bd69559bb226ee05901609f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-12T10:44:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T10:44:08.000Z", "avg_line_length": 30.2, "max_line_length": 81, "alphanum_fraction": 0.6164034641, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7623500234942118}}
{"text": "\"\"\"\n    wdist(d; h = 2, cri = 4, squared = false)\nCompute weights from distances, using a decreasing exponential function.\n* `d` : A vector of distances.\n* `h` : A scaling positive scalar defining the shape of the function. \n* `cri` : A positive scalar defining outliers in the distances vector.\n* `squared`: If true, distances are replaced by the squared distances;\n    the weight function is then a Gaussian (RBF) kernel function.\n\nWeights are computed by exp(-d / (h * MAD(d))), or are set to 0 for \ndistances > Median(d) + cri * MAD(d).\n\nThe weights decrease with increasing distances. Lower is h, sharper is the decreasing function. \nWeights are set to 0 for outliers (extreme distances).\n\"\"\"  \nfunction wdist(d; h = 2, cri = 4, squared = false)\n    w = copy(d)\n    wdist!(w; h = h, cri = cri, squared = squared)\n    w\nend\n\nfunction wdist!(d; h = 2, cri = 4, squared = false)\n    # d, out : (n,)\n    squared ? d = d.^2 : nothing\n    zmed =  Statistics.median(d)\n    zmad = Jchemo.mad(d)\n    cutoff = zmed + cri * zmad\n    d .= map(x -> ifelse(x <= cutoff, exp(-x / (h * zmad)), zero(eltype(d))), d)\n    d .= d / maximum(d)\n    d[isnan.(d)] .= 1\n    return\nend\n", "meta": {"hexsha": "f36de36edf93811de805446f12d6d4ca1fdd24aa", "size": 1165, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/wdist.jl", "max_stars_repo_name": "mlesnoff/Jchemo.jl", "max_stars_repo_head_hexsha": "fea8da15c0458c0e68921cda55a5bf448170eb53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/wdist.jl", "max_issues_repo_name": "mlesnoff/Jchemo.jl", "max_issues_repo_head_hexsha": "fea8da15c0458c0e68921cda55a5bf448170eb53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/wdist.jl", "max_forks_repo_name": "mlesnoff/Jchemo.jl", "max_forks_repo_head_hexsha": "fea8da15c0458c0e68921cda55a5bf448170eb53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.303030303, "max_line_length": 96, "alphanum_fraction": 0.6386266094, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7623500203464988}}
{"text": "using Colors\nusing Luxor\n\nstruct Pos\n    x::Float64\n    y::Float64\nend\n\nfunction jarvis_cross(point1::Pos, point2::Pos, point3::Pos)\n    vec1 = Pos(point2.x - point1.x, point2.y - point1.y)\n    vec2 = Pos(point3.x - point2.x, point3.y - point2.y)\n    ret_cross = vec1.x*vec2.y - vec1.y*vec2.x\n    return ret_cross*ret_cross\nend\n\nfunction jarvis_march(points::Vector{Pos})\n    hull = Vector{Pos}()\n\n    # sorting array based on leftmost point\n    sort!(points, by = item -> item.x)\n    push!(hull, points[1])\n\n    i = 1\n    curr_point = points[2]\n\n    # Find cross product between points\n    curr_product = jarvis_cross(Pos(0,0), hull[1], curr_point)\n    while (curr_point != hull[1])\n        for point in points\n                product = 0.0\n            if (i == 1)\n                if (hull[i] != point)\n                    product = jarvis_cross(Pos(0,0), hull[i], point)\n                end\n            else\n                if (hull[i] != point && hull[i-1] != point)\n                    product = jarvis_cross(hull[i-1], hull[i], point)\n                end\n            end\n            if (product > curr_product)\n                curr_point = point\n                curr_product = product\n            end\n        end\n        push!(hull, curr_point)\n        curr_product = 0\n        i += 1\n    end\n\n    return hull\nend\n\nfunction main(pts)\n    hull = jarvis_march(pts)\nend\n\n# Auxiliary drawing functions\nfunction make_drawing(width, height, img_path, bkg_color, origin_p)\n    d = Drawing(width, height, img_path)\n    background(bkg_color)\n    origin(origin_p)\n    return d\nend\n\nmap2luxor(p) = Point(p.x, -p.y)\nmap2luxor(p) = Point(p...)\n\n## Canvas constants\nwidth = 500\nheight = 500\npath = \"arcane_march.png\"\ncolor = RGBA(0, 0, 0)\nop = [width / 2, height / 2]\n\n# Setting up drawing\nmy_draw = make_drawing(width, height, path, color, Point(op...))\n\n# pts_list = [Pos(200, 15), Pos(100, 100), Pos(-20, -200), Pos(-130, 100)]\npts_list = [Pos(rand(-250:250), rand(-250:250)) for _ in 1:10]\n\nhull = main(pts_list)\nprintln(hull)\nhull = [Point(p.x, -p.y) for p in hull]\nprintln(hull)\npts_list = [Point(p.x, -p.y) for p in pts_list]\n\nsethue(RGBA(1.0, 1.0, 0.0))\ncircle.(pts_list, 15; action = :fill)\n\nsethue(RGBA(1.0, 1.0, 1.0))\npoly(hull, action = :stroke; close = true)\n\nfinish()\n", "meta": {"hexsha": "b90565e3c8d31a8d92b66e48ce4b3162101bcf6a", "size": 2273, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "VISUALIZATIONS/VORONOI/arcane_jarvis.jl", "max_stars_repo_name": "TheCedarPrince/DataExplorers", "max_stars_repo_head_hexsha": "fc11fba908ec7c820d3db93412aa6ffcf23f7539", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VISUALIZATIONS/VORONOI/arcane_jarvis.jl", "max_issues_repo_name": "TheCedarPrince/DataExplorers", "max_issues_repo_head_hexsha": "fc11fba908ec7c820d3db93412aa6ffcf23f7539", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VISUALIZATIONS/VORONOI/arcane_jarvis.jl", "max_forks_repo_name": "TheCedarPrince/DataExplorers", "max_forks_repo_head_hexsha": "fc11fba908ec7c820d3db93412aa6ffcf23f7539", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-11T06:56:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-11T06:56:51.000Z", "avg_line_length": 24.1808510638, "max_line_length": 74, "alphanum_fraction": 0.5877694677, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7623500188902693}}
{"text": "using LinearAlgebra\nusing GLM\nusing LsqFit\nusing Distributions\nusing StatsBase\nusing Printf\nusing Plots\n\n#linear fit wrapper\n\nfunction lfit(ndf::DataFrame)\n    lr = lm(@formula(y_mean ~ x_mean), ndf)\n    c = coef(lr)\n    return x -> c[1] + c[2]*x, predict(lr), c\nend\n\nstruct RFit\n\tfitpar::Vector{<:Number}\n\tfitstd::Vector{<:Number}\n\tci::Vector{Tuple{Number, Number}}\n\tg::Function\nend\n\n\n\"\"\"\n    gpol1(ct::Vector{<:Real})::Function\nreturn a degree 1 polynomial function with parameters ct.\n\"\"\"\nfunction gpol1(ct::Vector{<:Real})::Function\n    function f1(z::Real)\n        return ct[1] + ct[2] * z\n    end\n    return f1\nend\n\n\n\"\"\"\n    gpol2(ct::Vector{<:Real})::Function\nreturn a degree 2 polynomial function with parameters ct.\n\"\"\"\nfunction gpol2(ct::Vector{<:Real})::Function\n    function f2(z::Real)\n        return ct[1] + ct[2] * z + ct[3] * z^2\n    end\n    return f2\nend\n\n\n\"\"\"\n    gpol2(ct::Vector{<:Real})::Function\nreturn a degree 3 polynomial function with parameters ct.\n\"\"\"\nfunction gpol3(ct::Vector{<:Real})::Function\n    function f3(z::Real)\n        return ct[1] + ct[2] * z + ct[3] * z^2 + ct[4] * z^3\n    end\n    return f3\nend\n\n\n\"\"\"\n    func1dfit(ffit::Function, x::Vector{<:Real},\n              y::Vector{<:Real}, p0::Vector{<:Real},\n              lb::Vector{Float64}, ub::Vector{Float64})\n\nFit a function to the data x, y with start prediction p0\nand return coefficients and errors.\n\"\"\"\nfunction func1dfit(ffit::Function, x::Vector{<:Real},\n                   y::Vector{<:Real}, p0::Vector{<:Real},\n                   lb::Vector{Float64}, ub::Vector{Float64})\n    fq = curve_fit(ffit, x, y, p0, lower=lb, upper=ub)\n    cfq = coef(fq)\n    @info \"coef(fq)\" cfq\n    sfq = stderror(fq)\n    @info \"std(fq)\" sfq\n    @info \"margin_of_error (90%)\" margin_error(fq, 0.1)\n    @info \" confidence_interval (90%)\" confidence_interval(fq, 0.1)\n    return cfq, sfq\nend\n\n\n\"\"\"\n    func1dfit(ffit::Function, x::Vector{<:Real}, y::Vector{<:Real},\n              yerr::Vector{<:Real}, p0::Vector{<:Real},\n              lb::Vector{<:Real}, ub::Vector{<:Real})\nFit function ffit to data x,y taking into account the errors\non the y (yerr). Assumes weights of 1/sigma^2 as in standard least squares\nand returns fit result.\n\"\"\"\nfunction func1dfit(ffit::Function, x::Vector{<:Real}, y::Vector{<:Real},\n\t               yerr::Vector{<:Real}, p0::Vector{<:Real},\n                   lb::Vector{<:Real}, ub::Vector{<:Real})\n\tfq = curve_fit(ffit, x, y, yerr.^-2, p0, lower=lb, upper=ub)\n    return fq\nend\n\n\n\"\"\"\n    fit_pol1(x::Vector{<:Real}, y::Vector{<:Real}, ci=0.1)\nFit a 1st degree polynomial to the data x, y and return\na RFit object with the result.\n\"\"\"\nfunction fit_pol1(x::Vector{<:Real}, y::Vector{<:Real}, ci=0.1)\n    @. pol(x, p) = p[1] + p[2] * x\n    p0 = [1.0, 1.0]\n    fq = curve_fit(pol, x, y, p0)\n\n    RFit(coef(fq), stderror(fq), confidence_interval(fq, ci),\n         gpol1(coef(fq)))\nend\n\n\n\"\"\"\n    fit_pol2(x::Vector{<:Real}, y::Vector{<:Real}, ci=0.1)\nFit a 2nd degree polynomial to the data x, y and return\na RFit object with the result.\n\"\"\"\nfunction fit_pol2(x::Vector{<:Real}, y::Vector{<:Real}, ci=0.1)\n    @. pol(x, p) = p[1] + p[2] * x + p[3] * x^2\n    p0 = [1.0, 1.0, 1.0]\n    fq = curve_fit(pol, x, y, p0)\n    RFit(coef(fq), stderror(fq), confidence_interval(fq, ci),\n         gpol2(coef(fq)))\nend\n\n\n\"\"\"\n    fit_pol3(x::Vector{<:Real}, y::Vector{<:Real}, ci=0.1)\nFit a 3rd degree polynomial to the data x, y and return\na RFit object with the result.\n\"\"\"\nfunction fit_pol3(x::Vector{<:Real}, y::Vector{<:Real}, ci=0.1)\n    @. pol(x, p) = p[1] + p[2] * x + p[3] * x^2 + p[4] * x^3\n    p0 = [1.0, 1.0, 1.0, 1.0]\n    fq = curve_fit(pol, x, y, p0)\n    RFit(coef(fq), stderror(fq), confidence_interval(fq, ci),\n         gpol3(coef(fq)))\nend\n\n\nstruct FGauss\n\tmu ::Vector{<:Real}\n\tstd::Vector{<:Real}\n\tC  ::Vector{<:Real}\n\th  ::Histogram\n\tX  ::Vector{<:Real}\n\tY  ::Vector{<:Real}\n\tg  ::Vector{Function}\nend\n\n\n\"\"\"\n    gausg(μ::Real, σ::Real, C::Real)::Function\nReturn a Gaussian function with parameters μ, σ and normalisation C.\n\"\"\"\nfunction gausg(μ::Real, σ::Real, C::Real)::Function\n\tfunction gausx(x::Real)\n\t\treturn C * pdf(Normal(μ, σ,), x)\n\tend\n\treturn gausx\nend\n\n\n\"\"\"\n    gausg2(μ1::Real, σ1::Real, C1::Real, μ2::Real, σ2::Real, C2::Real)\nReturn a function for the sum of two Gaussians with parameters\n    μ1, σ1 and μ2, σ2 and normalisations C1 and C2.\n\"\"\"\nfunction gausg2(μ1::Real, σ1::Real, C1::Real, μ2::Real, σ2::Real, C2::Real)::Function\n\tfunction gausx(x::Real)\n\t\treturn C1 * pdf(Normal(μ1, σ1,), x) + C2 * pdf(Normal(μ2, σ2,), x)\n\tend\n\treturn gausx\nend\n\n@. gauss1(x, p)   = p[1] * pdf(Normal(p[2], p[3]), x)\n@. gauss2(x, p)   = p[1] * pdf(Normal(p[2], p[3]), x) + p[4] * pdf(Normal(p[5], p[6]), x)\n@. gauss2cm(x, p) = p[1] * pdf(Normal(p[2], p[3]), x) + p[4] * pdf(Normal(p[2], p[5]), x)\n\n\n\"\"\"\n    gaussfm(mu::Real)::Function\nReturn a Gaussian Fitting function with a fixed mean mu.\n\"\"\"\nfunction gaussfm(mu::Real)::Function\n\tfunction gauss(x::Vector{<:Real}, p::Vector{<:Real})\n\t\treturn @. p[1]* pdf(Normal(mu, p[2]), x)\n\tend\n\treturn gauss\nend\n\n\n\"\"\"\n    gauss2fm(mu::Real)::Function\nReturn a function of the sum of two Gaussians with a fixed common mean mu.\n\"\"\"\nfunction gauss2fm(mu::Real)::Function\n\tfunction gauss2(x::Vector{<:Real}, p::Vector{<:Real})\n\t\treturn @. p[1]* pdf(Normal(mu, p[2]), x) + p[3]* pdf(Normal(mu, p[4]), x)\n\tend\n\treturn gauss2\nend\n\n\n\"\"\"\n\tfit_gauss(h::Histogram)\n\nFit a normal distribution to a Histogram and return FGauss object.\n\"\"\"\nfunction fit_gauss(h::Histogram)\n\tc = centers(h)\n\tw = eltype(c).(h.weights)\n\t@debug \"histo\"  w c\n\tmu, sigma = mean_and_std(c, Weights(h.weights); corrected = false)\n\t@debug \"mu, std\" mu, sigma\n\n\t# fit parameters lb, ub, po are lower, upper bounds and pars\n    lb = [         0.0, mu - 100.0 * sigma, sigma / 100.0]\n    ub = [100 * sum(w), mu + 100.0 * sigma, 100.0 * sigma]\n    p0 = [      sum(w), mu                ,         sigma]\n\t(CC, μ, σ), _ = func1dfit(gauss1, c, w, p0, lb, ub)\n\tgx = gausg(μ, σ, CC)\n\treturn FGauss([μ], [σ], [CC], h, c, gx.(c), [gx])\n\nend\n\n\n\"\"\"\n\tfit_gauss(x::Vector{Float64}, xmin::Float64, xmax::Float64;\n              bins::Integer=50, norm=false)\n\nFit a normal distribution to data x,y and return FGauss object.\n\"\"\"\nfit_gauss(x::Vector{Float64}, xmin::Float64, xmax::Float64;\n\t      bins::Integer=50, norm=false) = fit_gauss(hist1d(x, bins, xmin, xmax, norm))\n\n\n\"\"\"\n\tfit_gauss_fm(x::Vector{Float64}, xmin::Float64, xmax::Float64, bins=50, fm=0.0)\n\nFit a gaussian with a fixed mean fm and return an FGauss object.\n\"\"\"\nfunction fit_gauss_fm(x::Vector{Float64}, xmin::Float64, xmax::Float64;\n\t                  bins=50, norm=false, fm=0.0)\n\n\t# fit the unbinned distribution\n\txx =  in_range(x, xmin, xmax)\n\tσ  = std(xx)\n\t@debug \"gfit_gauss_fm: σ = $σ\"\n\n\t# bin distribution\n    h = hist1d(xx, bins, xmin, xmax, norm)\n    c = centers(h)\n    w = eltype(c).(h.weights)\n    @debug \"histo w and c\"  w c\n\n\t# fit parameters lb, ub, po are lower, upper bounds and pars\n    lb = [            0.0, σ / 10.0]\n    ub = [1.0e+6 * sum(w), σ * 10.0]\n    p0 = [         sum(w), σ       ]\n\n\tg1 = gaussfm(fm)\n\t(CC, sigma), _ = func1dfit(g1, c, w, p0, lb, ub)\n\n\t@debug \"CC,  sigma\"  CC  sigma\n\tgx = gausg(fm, sigma, CC)\n\n\treturn FGauss([fm], [sigma], [CC], h, c, gx.(c), [gx])\nend\n\n\n\"\"\"\n    plot_fit_gauss(x::Vector{Float64}, xs::String, ys::String,\n                   bins::Integer, xmin::Float64, xmax::Float64;\n                   xgmin::Float64, xgmax::Float64, gbins::Integer=50)\nFit a Gaussian to the histogram of data x between xmin and xmax with bins\nand plot the results.\n\"\"\"\nfunction plot_fit_gauss(x::Vector{Float64}, xs::String, ys::String,\n                        bins::Integer, xmin::Float64, xmax::Float64;\n                        xgmin::Float64, xgmax::Float64, gbins::Integer=50)\n\n    h, _ = hist1d(x, xs, bins, xmin, xmax, norm=true)\n    fg   = fit_gauss(x, xgmin, xgmax, bins=gbins, norm=true)\n    gx   = fg.g[1]\n    X    = centers(h)\n    Y    = h.weights\n    σY   = sqrt.(Y)\n    lbl  = @sprintf \" μ=%5.1f, σ =%5.1f \" fg.mu[1] fg.std[1]\n    lbl  = string(\"gaussian fit:\\n\", lbl)\n    p    = scatter(X, Y, yerror=σY,fmt=:png, shape=:circle, color=:black, label=\"data\", legend=true)\n    p    = plot!(p, X, gx.(X), lw=2, label=lbl, legend=true, fmt = :png)\n    xlabel!(xs)\n    xlabel!(ys)\n    return fg, p\nend\n\n\n\"\"\"\n    fitg1(x::Vector{<:Real}, xs::String, nbins::Int64, xmin::Real, xmax::Real;\n\t      xgmin::Real, xgmax::Real, fbins::Int64=100, norm::Bool=true,\n          fm::Real=0.0, flex_mean=false)\n\nHistograms data x and returns a plot and a Gaussian fit to the histogram.\nOption flex_mean allows the mean to float or be fixed to fm.\n\"\"\"\nfunction fitg1(x::Vector{<:Real}, xs::String, nbins::Int64, xmin::Real, xmax::Real;\n\t           xgmin::Real, xgmax::Real, fbins::Int64=100, norm::Bool=true,\n               fm::Real=0.0, flex_mean=false)\n\n\th, p = hist1d(x, xs, nbins, xmin, xmax, norm=norm, legend=true)\n    if flex_mean\n        fg = fit_gauss(x, xgmin, xgmax, bins=fbins, norm=norm)\n    else\n        fg = fit_gauss_fm(x, xgmin, xgmax, bins=fbins, norm=norm, fm=fm)\n    end\n\tgx  = fg.g[1]\n\tX   = centers(h)\n\tlbl = @sprintf \"σ =%4.1f \" fg.std[1]\n    p   = plot!(p, X, gx.(X), lw=2, label=lbl, legend=true, fmt = :png)\n\txlabel!(xs)\n\treturn fg, p\nend\n\n\n\"\"\"\n\tgfit_gauss2_cmean(y, xmin, xmax, bins, sigmas, cs, cmean=0.0)\n\nFit a double gaussian (with sigmas -->[sigma1, sigma2] cs -->[c1, c2] )\nand a fixed mean, cmean, to data.\n\"\"\"\nfunction gfit_gauss2_cmean(y::Vector{Float64}, xmin::Float64, xmax::Float64,\n\t                       bins::Integer, sigmas::Vector{Float64}, cs::Vector{Float64},\n\t\t\t\t\t\t   norm=false, cmean=0.0)\n\n    x = in_range(y, xmin, xmax)\n    h = hist1d(x, bins, xmin, xmax, norm)\n    c = centers(h)\n    w = h.weights\n    @debug \"histo centers and weights in full region\"  w c\n\n    g2 = gauss2fm(cmean)\n    # fit parameters lb, ub, po are lower, upper bounds and pars\n\n    lb = [cs[1]/100.0, sigmas[1]/5.0, cs[2]/100.0, sigmas[2]/5.0]\n    ub = [cs[1]*100.0, sigmas[1]*5.0, cs[2]*100.0, sigmas[2]*5.0]\n    p0_bounds = [cs[1], sigmas[1], cs[2], sigmas[2]]\n\n    @debug \"pars\" p0 lb ub\n    # fit double gaussian\n    fq = curve_fit(g2, c, w, p0_bounds, lower=lb, upper=ub)\n    C1, sigma1, C2,  sigma2   = coef(fq)\n    @debug \"C1 sigma1 C2 sigma2\" C1 sigma1 C2  sigma2\n\n    #\n    gx  = gausg2(cmean, sigma1, C1, cmean, sigma2, C2)\n    gx1 = gausg( cmean, sigma1, C1)\n    gx2 = gausg( cmean, sigma2, C2)\n\n\treturn FGauss([cmean, cmean], [sigma1, sigma2], [C1, C2],\n\t\t\t       h, c, gx.(c), [gx, gx1, gx2])\n    end\n\n\"\"\"\n\tfit_2gauss_cmean(data, gp, g1p, g2p, cm)\n\nFit two gaussian with common mean JJ Review!!!\n\"\"\"\nfunction fit_2gauss_cmean(data, gp, g1p, g2p, cm, norm=false)\n    gf1 = fit_gauss_fm(data, g1p.xmin,g1p.xmax, bins=g1p.nbin, norm=norm, fm=cm)\n    @debug gf1\n    gf2 = fit_gauss_fm(data, g2p.xmin,g2p.xmax,bins=g2p.nbin, norm= norm, fm=cm)\n    @debug gf2\n    gf = gfit_gauss2_cmean(data, gp.xmin,gp.xmax,gp.nbin,\n\t                       [gf1.std[1], gf2.std[1]], [gf1.C[1], gf2.C[1]], norm)\n    @debug gf\n    return gf\nend\n\n\n\"\"\"\n    fitg2(x, xs, xmin, xmax, xg1min, xg1max, xg2min, xg2max, xgmin, xgmax; bins=100)\nFits 2 gaussians with common mean (0 by default) to vector x. JJ Review!!\n\"\"\"\nfunction fitg2(x::Vector{<:Real}, xs::String, bins::Int64, xmin::Real, xmax::Real;\n\t           xg1min::Real, xg1max::Real, xg2min::Real, xg2max::Real, xgmin::Real, xgmax::Real, cm=0.0,\n         \t   g1bins::Int64=100, g2bins::Int64=100, gbins::Int64=100, norm::Bool=true)\n\n\t_, p = hist1d(x, xs, bins, xmin, xmax, norm=norm, legend=true)\n\n    g1p = (xmin = xg1min, xmax = xg1max, nbin=g1bins)\n    g2p = (xmin = xg2min, xmax = xg2max, nbin=g2bins)\n    gp  = (xmin = xgmin , xmax = xgmax , nbin=gbins )\n\n    fg  = fit_2gauss_cmean(x, gp, g1p, g2p, cm, norm)\n\tgx  = fg.g[1]\n\tgx1 = fg.g[2]\n\tgx2 = fg.g[3]\n\n\tlbl = @sprintf \"σt =%4.1f mm, σ =%4.1f mm\" fg.std[1] fg.std[2]\n\tst  = @sprintf \"σt =%4.1f mm \" fg.std[1]\n\tsf  = @sprintf \"σ  =%4.1f mm\" fg.std[2]\n    p = plot!(p, fg.X, fg.Y, label=lbl, lw=2, fmt = :png)\n    p = plot!(p, fg.X, gx1.(fg.X), label=st, lw=1, fmt = :png)\n    p = plot!(p, fg.X, gx2.(fg.X), label=sf, lw=1, fmt = :png)\n    #xlabel!(xs)\n    return fg, p\nend\n\n\n\"\"\"\n\tfit_profile(x1, x2, tx1, ty1, fit=\"pol1\", bins=25)\n    fit_profile(df1, c1, c2, tx1, ty1, fit=\"pol1\", bins=25)\nCreate and fit a profile with pol1 or poli2 functions.\nReturn fit parameters, fit function and plot\n\"\"\"\nfit_profile(df1::DataFrame, c1::String, c2::String,\n            tx1::String, ty1::String, fit=\"pol1\", bins=25;\n            ybin_width::Real=0.1, ymin::Real=352.4, ymax::Real=392.4,\n            min_proportion::Real=0.0) =\n\tfit_profile(df1[!,c1], df1[!,c2], tx1, ty1, fit, bins,\n                ybin_width=ybin_width, ymin=ymin, ymax=ymax, min_proportion=min_proportion)\n\n\nfunction fit_profile(x1::Vector{<:Real}, x2::Vector{<:Real},\n\t                 tx1::String, ty1::String, fit=\"pol1\", bins=25;\n                     ybin_width::Real=0.1, ymin::Real=minimum(x2),\n                     ymax::Real=maximum(x2), min_proportion::Real=0.0)\n\n    pdf1, _ = p1df(x1,x2, bins, ybin_width=ybin_width, ymin=ymin, ymax=ymax, min_proportion=min_proportion)\n\n    if fit == \"pol1\"\n        fr = fit_pol1(pdf1.x_mean, pdf1.y_mean)\n    elseif fit == \"pol2\"\n        fr = fit_pol2(pdf1.x_mean, pdf1.y_mean)\n\telseif fit == \"pol3\"\n\t\tfr = fit_pol3(pdf1.x_mean, pdf1.y_mean)\n\telse\n\t\tprintln(\"option not implemented\")\n\t\treturn nothing\n    end\n\n    p1 = scatter(pdf1.x_mean, pdf1.y_mean, yerror=pdf1.y_std, fmt=:png,\n\t             shape=:circle, color=:black, legend=false)\n    p1 = plot!(p1, pdf1.x_mean, fr.g.(pdf1.x_mean), fmt=:png)\n    xlabel!(tx1)\n    ylabel!(ty1)\n\n   return fr, p1\nend\n", "meta": {"hexsha": "ddc13d903880403733606ac1f83e027a7f3e5f8b", "size": 13666, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fits.jl", "max_stars_repo_name": "andLaing/ATools", "max_stars_repo_head_hexsha": "fce9afdba002afb4e51ec1ee15622881d6ca5e19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fits.jl", "max_issues_repo_name": "andLaing/ATools", "max_issues_repo_head_hexsha": "fce9afdba002afb4e51ec1ee15622881d6ca5e19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fits.jl", "max_forks_repo_name": "andLaing/ATools", "max_forks_repo_head_hexsha": "fce9afdba002afb4e51ec1ee15622881d6ca5e19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2345132743, "max_line_length": 107, "alphanum_fraction": 0.6017122786, "num_tokens": 4975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7623500188902693}}
{"text": "#The lattice\r\nusing LinearAlgebra\r\n\r\n#print(\"Enter dim value: \"); d = parse(Int, readline(stdin)) # use it for IO input of d! else use fixed d!\r\nd = 4;\r\nv = Matrix{Any}(zeros(d,d));\r\nh = Matrix{Any}(zeros(d,d));\r\np = Matrix{Float64}(undef,d,d);\r\nx = Matrix{Float64}(undef,d,d);\r\ny = Matrix{Float64}(undef,d,d);\r\nΦ = Matrix{Float64}(undef,d,d);\r\n\r\nfor i = 1:d\r\n    h[i,d] = Matrix{Float64}(I,d,d)[i,:];\r\nend\r\n\r\n#=for k = d:-1:1\r\n    v[k,k] = (x[k,k] + y[k,k]im)*h[k,k];\r\n    \r\n    for j = k-1:-1:1 \r\n        v[j,k] = (x[j,k] + y[j,k]im) * sqrt(complex(p[j,k])) * h[j,k] + sqrt(complex(1-p[j,k])) * v[j+1,k];\r\n        h[j,k-1] = (x[j,k] + y[j,k]im) * sqrt(complex(1-p[j,k])) * h[j,k] - sqrt(complex(p[j,k])) * v[j+1,k];\r\n        println(\"k:\",k,\"\\t\",\"j:\",j)\r\n    end\r\nend=#\r\n\r\nfunction H(m::Int, n::Int)\r\n    for k = d:-1:1\r\n        v[k,k] = (x[k,k] + y[k,k]im)*h[k,k];\r\n        \r\n        for j = k-1:-1:1 \r\n            v[j,k] = (x[j,k] + y[j,k]im) * sqrt(complex(p[j,k])) * h[j,k] + sqrt(complex(1-p[j,k])) * v[j+1,k];\r\n            h[j,k-1] = (x[j,k] + y[j,k]im) * sqrt(complex(1-p[j,k])) * h[j,k] - sqrt(complex(p[j,k])) * v[j+1,k];\r\n        end\r\n    end\r\n    return (h[m,n])\r\nend\r\n\r\n\r\n#Ist = transpose(v);\r\n\r\n#-----------------------------------------------------------------------------------------------------\r\n#DFT\r\n\r\nm(n::Int) = 1/sqrt(n)*[exp(2*pi*im*(r-1)*(s-1)/n) for r in 1:n, s in 1:n];\r\n\r\n#Soll = m(d);\r\n\r\n#------------------------------------------------------------------------------------------------------\r\n#The solution of the algorithm\r\n\r\nDenom(j::Int,k::Int) = dot(Matrix{Float64}(I,d,d)[j,:], H(j,k)) * (j==1 ? 1.0 : prod(sqrt(complex(1-p[l,k])) for l = 1:j-1));\r\n\r\nNum(j::Int,k::Int) = j==1 ? 0.0 : sum((x[i,k] + y[i,k]im) * dot(Matrix{Float64}(I,d,d)[j,:], H(i,k)) * sqrt(complex(p[i,k])) * (i==1 ? 1.0 : prod(sqrt(complex(1-p[l,k])) for l = 1:i-1)) for i = 1:j-1);\r\n\r\nZ(j::Int,k::Int) = (m(d)[j,k] - Num(j,k)) / Denom(j,k);\r\n\r\n#=function Angle(Re,Im,j,k)\r\n    if abs(exp(asin(Float32(Im))*im) - (Re + Im*im)) < 10.0^-12\r\n        Φ[j,k] = asin(Float32(Im));\r\n    else\r\n        Φ[j,k] = -asin(Float32(Im)) - pi;\r\n    end\r\nend=#\r\n#Angle(Re,Im,j,k) = abs(exp(asin(Float32(Im))*im) - (Re + Float32(Im)*im)) < 10.0^-12 ? Φ[j,k] = asin(Float32(Im)) : Φ[j,k] = -asin(Float32(Im)) - pi;\r\nAngle(Re::Float16,Im::Float16,j::Int,k::Int) = abs2(exp(asin(Im)*im) - (Re + Im*im)) < 10.0^-12 ? Φ[j,k] = asin(Im) : Φ[j,k] = -asin(Im) - pi;\r\n# the results vary depending on the precision of the 'Float' used! \r\n\r\n#-----------------------------------------------------------------------------------------------------\r\n#Evaluation\r\n\r\n@time for k = d:-1:1\r\n    for j = 1:k-1\r\n        p[j,k] = abs2(Z(j,k));\r\n        x[j,k] = real(Z(j,k)/sqrt(complex(p[j,k])));\r\n        y[j,k] = imag(Z(j,k)/sqrt(complex(p[j,k])));\r\n        Angle(Float16(x[j,k]),Float16(y[j,k]),j,k);\r\n        println(\"p(\", j, \",\", k, \") = \", p[j,k], \"\\tΦ(\", j, \",\", k, \") = \", Φ[j,k]*180/pi);\r\n    end\r\n\r\n    x[k,k] = real(Z(k,k));\r\n    y[k,k] = imag(Z(k,k));\r\n    Angle(Float16(x[k,k]),Float16(y[k,k]),k,k);\r\n    println(\"Φ(\", k, \",\", k, \") = \", Φ[k,k]*180/pi);\r\nend\r\n\r\n#------------------------------------------------------------------------------------------------------\r\n", "meta": {"hexsha": "d81efd927ceda23827d1db873d83c6ecac045c36", "size": 3243, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Fourier2.jl", "max_stars_repo_name": "Bondan000/FFT", "max_stars_repo_head_hexsha": "1f42f034d14a8cf7fa142f0c5a688c398288d8ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Fourier2.jl", "max_issues_repo_name": "Bondan000/FFT", "max_issues_repo_head_hexsha": "1f42f034d14a8cf7fa142f0c5a688c398288d8ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Fourier2.jl", "max_forks_repo_name": "Bondan000/FFT", "max_forks_repo_head_hexsha": "1f42f034d14a8cf7fa142f0c5a688c398288d8ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8522727273, "max_line_length": 202, "alphanum_fraction": 0.4138143694, "num_tokens": 1160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291502, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7623500168179336}}
{"text": "# example with constraint in struct\n# struct Vector2D{T<:Number}\n#    x::T\n#    y::T\n# end\n\n# function dot(u::Vector2D{T}, v::Vector2D{T}) where T\n#     u.x*v.x + u.y*v.y\n# end\n\n# function cross(u::Vector2D{T}, v::Vector2D{T}) where T\n#     u.x*v.y - u.y*v.x\n# end\n\n# julia> a = Vector2D(1, 2)\n# Vector2D{Int64}(1, 2)\n\n# julia> b = Vector2D(3, 4)\n# Vector2D{Int64}(3, 4)\n\n# julia> c =Vector2D{Char}('A', 'B')\n# ERROR: TypeError: in Vector2D, in T, expected T<:Number, got Type{Char}\n# Stacktrace:\n#  [1] top-level scope\n#    @ REPL[11]:1\n\n# julia> dot(a,b)\n# 11\n\n# julia> cross(a,b)\n# -2\n\n# dot(a,c)\n\n# same example with simpler method signature \n# in this version  u and v can be of different Number subtype and still works\n# struct Vector2D{T<:Number}\n#    x::T\n#    y::T\n# end\n\n# function dot(u::Vector2D, v::Vector2D)\n#     u.x*v.x + u.y*v.y\n# end\n\n# function cross(u::Vector2D, v::Vector2D)\n#     u.x*v.y - u.y*v.x\n# end\n\n# julia> a = Vector2D(1, 2)\n# Vector2D{Int64}(1, 2)\n\n# julia> b = Vector2D(3.0, 4.0)\n# Vector2D{Float64}(3.0, 4.0)\n\n# julia> c =Vector2D{Char}('A', 'B')\n# ERROR: TypeError: in Vector2D, in T, expected T<:Number, got Type{Char}\n# Stacktrace:\n#  [1] top-level scope\n#    @ REPL[7]:1\n\n# julia> dot(a,b)\n# 11.0\n\n# julia> cross(a,b)\n# -2.0\n\n\n# example with constraint in method - allows non Number Vecttor2\n# but methods are type protected\n# struct Vector2D{T}\n#    x::T\n#    y::T\n# end\n\n# function dot(u::Vector2D{T}, v::Vector2D{T}) where T <: Number\n#     u.x*v.x + u.y*v.y\n# end\n\n# function cross(u::Vector2D{T}, v::Vector2D{T}) where T <: Number\n#     u.x*v.y - u.y*v.x\n# end\n\n# julia> a = Vector2D(1, 2)\n# Vector2D{Int64}(1, 2)\n\n# julia> b = Vector2D(3, 4)\n# Vector2D{Int64}(3, 4)\n\n# julia> c =Vector2D{Char}('A', 'B')\n# Vector2D{Char}('A', 'B')\n\n# julia> a = Vector2D(1, 2)\n# Vector2D{Int64}(1, 2)\n\n# julia> b = Vector2D(3, 4)\n# Vector2D{Int64}(3, 4)\n\n# julia> c =Vector2D{Char}('A', 'B')\n# Vector2D{Char}('A', 'B')\n\n# julia> dot(a,b)\n# 11\n\n# julia> cross(a,b)\n# -2\n\n# julia> dot(a,c)\n# ERROR: MethodError: no method matching dot(::Vector2D{Int64}, ::Vector2D{Char})\n# Closest candidates are:\n#   dot(::Vector2D{T}, ::Vector2D{T}) where T<:Number at REPL[4]:1\n# Stacktrace:\n#  [1] top-level scope\n#    @ REPL[14]:1\n\n# julia> cross(a,c)\n# ERROR: MethodError: no method matching cross(::Vector2D{Int64}, ::Vector2D{Char})\n# Closest candidates are:\n#   cross(::Vector2D{T}, ::Vector2D{T}) where T<:Number at REPL[5]:1\n# Stacktrace:\n#  [1] top-level scope\n#    @ REPL[15]:1\n", "meta": {"hexsha": "1ef35080be2776bdc594610ae49071023cd4333b", "size": 2499, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "parametrictypes.jl", "max_stars_repo_name": "FourMInfo/JuliaforBeginners", "max_stars_repo_head_hexsha": "4908cd82c777cc9934056bbada36bccd67158906", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "parametrictypes.jl", "max_issues_repo_name": "FourMInfo/JuliaforBeginners", "max_issues_repo_head_hexsha": "4908cd82c777cc9934056bbada36bccd67158906", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "parametrictypes.jl", "max_forks_repo_name": "FourMInfo/JuliaforBeginners", "max_forks_repo_head_hexsha": "4908cd82c777cc9934056bbada36bccd67158906", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3170731707, "max_line_length": 83, "alphanum_fraction": 0.6054421769, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7623489417366676}}
{"text": "#=\n\n    This is a port of the SPPL model election.pynb\n\n    This model:\n    Summary Statistics\n    parameters        mean        std   naive_se      mcse         ess      rhat   ess_per_sec \n        Symbol     Float64    Float64    Float64   Float64     Float64   Float64       Float64 \n\n        param    299.7774    28.9717     0.2897    0.3653   6479.7518    0.9999      866.9724\n            p      0.4814     0.0318     0.0003    0.0004   6508.3665    1.0002      870.8010\n        votes   1925.2743   131.9134     1.3191    1.7207   6442.0098    1.0003      861.9226\n          win      0.2902     0.4539     0.0045    0.0056   6597.9243    0.9999      882.7836\n\n\n=#\n\nusing Turing, StatsPlots, Distributions, StatsBase\nusing CSV\ninclude(\"jl_utils.jl\")\n\n#=\nfrom sppl.sym_util import binspace\nn = 4000\nparam ~= randint(low=250, high=350)\nswitch (param) cases (b in range(250, 350)):\n    p ~= beta(a=277, b=b)\nswitch (p) cases (x in binspace(0, 1, 20)):\n    votes ~= binom(n=n, p=(x.left + x.right)/2)\nwin ~= votes > 0.5*n\n\n=#\n@model function election(n=4000) \n    param ~ DiscreteUniform(250,350)\n    p ~ Beta(277,param)\n    votes ~ Binomial(n,p)\n\n    win ~ Dirac(votes > 0.5*n)\n\nend \n\nn = 4000\nmodel = election(n)\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(5), 10_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 10_000)\n\n# chns = sample(model, HMC(0.1,6), 1_000)\n# chns = sample(model, NUTS(), 1_000)\n\ndisplay(chns)\n\n\n", "meta": {"hexsha": "624d47a88d6246139c9ca53153da1d837f7dbf03", "size": 1502, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/election.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/election.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/election.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 26.350877193, "max_line_length": 95, "alphanum_fraction": 0.5845539281, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066391, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7623489375935549}}
{"text": "module NormalSmoothingSplines\r\n\r\n###### Inteface definition\r\nexport prepare_approximation, construct_approximation, approximate\r\nexport prepare_interpolation, construct_interpolation, interpolate\r\nexport evaluate, evaluate_at\r\nexport evaluate_gradient, evaluate_derivative\r\nexport NormalSpline, RK_H0, RK_H1, RK_H2\r\n\r\nexport get_epsilon, estimate_epsilon, get_cond, estimate_cond\r\nexport estimate_accuracy\r\n######\r\n\r\nusing LinearAlgebra\r\n\r\nabstract type ReproducingKernel end\r\nabstract type ReproducingKernel_0 <: ReproducingKernel end\r\nabstract type ReproducingKernel_1 <: ReproducingKernel_0 end\r\nabstract type ReproducingKernel_2 <: ReproducingKernel_1 end\r\n\r\nabstract type AbstractSpline end\r\n\r\n\"\"\"\r\n`struct NormalSpline{T, RK} <: AbstractSpline where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nDefine a structure containing full information of a normal spline\r\n# Fields\r\n- `_kernel`: a reproducing kernel spline was built with\r\n- `_compression`: factor of transforming the original node locations into unit hypercube\r\n- `_nodes`: transformed function value interpolation nodes\r\n- `_nodes_b`: transformed function value approximation nodes\r\n- `_values`: function values at interpolation nodes\r\n- `_values_lb`: function lower bound values at approximation nodes\r\n- `_values_ub`: function upper bound values at approximation nodes\r\n- `_d_nodes`: transformed function directional derivative interpolation nodes\r\n- `_d_nodes_b`: transformed function directional derivative approximation nodes\r\n- `_es`: normalized derivative directions at interpolation nodes\r\n- `_es_b`: normalized derivative directions at approximation nodes\r\n- `_d_values`: function directional derivative values at interpolation nodes\r\n- `_d_values_lb`: function lower bound directional derivative values at approximation nodes\r\n- `_d_values_ub`: function upper bound directional derivative values at approximation nodes\r\n- `_min_bound`: minimal bounds of the original node locations area\r\n- `_gram`: Gram matrix of the problem\r\n- `_chol`: Cholesky factorization of the Gram matrix\r\n- `_mu`: spline coefficients\r\n- `_active`: active inequality constraint numbers at solution\r\n- `_cond`: estimation of the Gram matrix condition number\r\n- `_ier`: An integer flag. If it is equal to 0, the optimal solution was found.\r\n          If it is equal to 1, the approximate solution was found. QP algorithm iterations were stopped\r\n          because of small spline norm change.\r\n          If it is equal to 2, the approximate solution was found. QP algorithm iterations were stopped\r\n          because of maximum allowed number of iterations was reached.\r\n          If it is equal to -1, the solution was not calculated.\r\n\"\"\"\r\nstruct NormalSpline{T, RK} <: AbstractSpline where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n    _kernel::RK\r\n    _compression::T\r\n    _nodes::Union{Matrix{T}, Nothing}\r\n    _nodes_b::Union{Matrix{T}, Nothing}\r\n    _values::Union{Vector{T}, Nothing}\r\n    _values_lb::Union{Vector{T}, Nothing}\r\n    _values_ub::Union{Vector{T}, Nothing}\r\n    _d_nodes::Union{Matrix{T}, Nothing}\r\n    _d_nodes_b::Union{Matrix{T}, Nothing}\r\n    _es::Union{Matrix{T}, Nothing}\r\n    _es_b::Union{Matrix{T}, Nothing}\r\n    _d_values::Union{Vector{T}, Nothing}\r\n    _d_values_lb::Union{Vector{T}, Nothing}\r\n    _d_values_ub::Union{Vector{T}, Nothing}\r\n    _min_bound::Union{Vector{T}, Nothing}\r\n    _gram::Union{Matrix{T}, Nothing}\r\n    _chol::Union{Cholesky{T, Matrix{T}}, Nothing}\r\n    _mu::Union{Vector{T}, Nothing}\r\n    _active::Union{Vector{Int}, Nothing}\r\n    _cond::T\r\n    _ier::Int\r\nend\r\n\r\ninclude(\"./NormalInterpolatingSplines.jl\")\r\ninclude(\"./ReproducingKernels.jl\")\r\ninclude(\"./GramMatrix.jl\")\r\ninclude(\"./Utils.jl\")\r\ninclude(\"./QP.jl\")\r\ninclude(\"./Interpolate.jl\")\r\ninclude(\"./Approximate.jl\")\r\n\r\n##\r\n#include(\"./examples/Main.jl\")\r\n##\r\n\r\n\"\"\"\r\n`prepare_approximation(nodes_b::Matrix{T}, kernel::RK = RK_H0())\r\n                       where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nPrepare the approximating normal spline by constructing and factoring a Gram matrix of the problem.\r\nInitialize the `NormalSpline` object.\r\n# Arguments\r\n- `nodes_b`: function value approximation nodes.\r\n          This should be an `n×n_1_b` matrix, where `n` is dimension of the sampled space and\r\n          `n_1_b` is the number of function value approximation nodes. It means that each column in the matrix defines one node.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H0` if the spline is constructing as a continuous function,\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n\r\nReturn: prepared `NormalSpline` object.\r\n\"\"\"\r\nfunction prepare_approximation(nodes_b::Matrix{T},\r\n                               kernel::RK = RK_H0()\r\n                              ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n     spline = _prepare_approximation(nodes_b, kernel)\r\n     return spline\r\nend\r\n\r\n\"\"\"\r\n`prepare_approximation(nodes::Matrix{T}, nodes_b::Matrix{T}, kernel::RK = RK_H0())\r\n                       where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nPrepare the approximating normal spline by constructing and factoring a Gram matrix of the problem.\r\nInitialize the `NormalSpline` object.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space and\r\n           `n_1` is the number of function value interpolation nodes. It means that each column in the matrix defines one node.\r\n- `nodes_b`: function value approximation nodes.\r\n          This should be an `n×n_1_b` matrix, where `n` is dimension of the sampled space and\r\n          `n_1_b` is the number of function value approximation nodes. It means that each column in the matrix defines one node.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H0` if the spline is constructing as a continuous function,\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n\r\nReturn: prepared `NormalSpline` object.\r\n\"\"\"\r\nfunction prepare_approximation(nodes::Matrix{T},\r\n                               nodes_b::Matrix{T},\r\n                               kernel::RK = RK_H0()\r\n                              ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n     spline = _prepare_approximation(nodes, nodes_b, kernel)\r\n     return spline\r\nend\r\n\r\n\"\"\"\r\n`construct_approximation(spline::NormalSpline{T, RK},\r\n                         values_lb::Vector{T}, values_ub::Vector{T},\r\n                         maxiter::Int, ftol::T)\r\n                         where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nconstruct the approximating normal spline by calculating its coefficients and\r\ncompletely initializing the `NormalSpline` object.\r\n# Arguments\r\n- `spline`: the partly initialized `NormalSpline` object returned by `prepare` function.\r\n- `values_lb`: function lower bound values at approximation nodes\r\n- `values_ub`: function upper bound values at approximation nodes\r\n- `maxiter`: Maximum allowed number of iterations.\r\n- `ftol`: convergence tolerance. The iteration stops when relative spline norm change is smaller than ftol.\r\n\r\nReturn: constructed `NormalSpline` object and the number of QP algorithm iterations done.\r\n\"\"\"\r\nfunction construct_approximation(spline::NormalSpline{T, RK},\r\n                                 values_lb::Vector{T},\r\n                                 values_ub::Vector{T},\r\n                                 maxiter::Int,\r\n                                 ftol::T = T(1.e-3)\r\n                                ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n    spline, nit_done = _construct_approximation(spline, values_lb, values_ub, maxiter, ftol)\r\n    return spline, nit_done\r\nend\r\n\r\n\"\"\"\r\n`construct_approximation(spline::NormalSpline{T, RK}, values::Vector{T},\r\n                         values_lb::Vector{T}, values_ub::Vector{T}, maxiter::Int, ftol::T)\r\n                         where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nconstruct the approximating normal spline by calculating its coefficients and\r\ncompletely initializing the `NormalSpline` object.\r\n# Arguments\r\n- `spline`: the partly initialized `NormalSpline` object returned by `prepare` function.\r\n- `values`: function values at interpolation nodes.\r\n- `values_lb`: function lower bound values at approximation nodes\r\n- `values_ub`: function upper bound values at approximation nodes\r\n- `maxiter`: Maximum allowed number of iterations.\r\n- `ftol`: convergence tolerance. The iteration stops when relative spline norm change is smaller than ftol.\r\n\r\nReturn: constructed `NormalSpline` object and the number of QP algorithm iterations done.\r\n\"\"\"\r\nfunction construct_approximation(spline::NormalSpline{T, RK},\r\n                                 values::Vector{T},\r\n                                 values_lb::Vector{T},\r\n                                 values_ub::Vector{T},\r\n                                 maxiter::Int,\r\n                                 ftol::T = T(1.e-3)\r\n                                ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n    spline, nit_done = _construct_approximation(spline, values, values_lb, values_ub, maxiter, ftol)\r\n    return spline, nit_done\r\nend\r\n\r\n\"\"\"\r\n`approximate(nodes::Matrix{T}, values::Vector{T}, nodes_b::Matrix{T}, values_lb::Vector{T}, values_ub::Vector{T},\r\n             kernel::RK, maxiter::Int, ftol::T) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nPrepare and construct the approximating normal spline.\r\n# Arguments\r\n- `nodes_b`: function value approximation nodes.\r\n        This should be an `n×n_1_b` matrix, where `n` is dimension of the sampled space and\r\n        `n_1_b` is the number of function value approximation nodes. It means that each column in the matrix defines one node.\r\n- `values_lb`: function lower bound values at approximation nodes\r\n- `values_ub`: function upper bound values at approximation nodes\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H0` if the spline is constructing as a continuous function,\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n- `maxiter`: Maximum allowed number of iterations.\r\n- `ftol`: convergence tolerance. The iteration stops when relative spline norm change is smaller than ftol.\r\n\r\nReturn: constructed `NormalSpline` object.\r\n\"\"\"\r\nfunction approximate(nodes_b::Matrix{T},\r\n                     values_lb::Vector{T},\r\n                     values_ub::Vector{T},\r\n                     kernel::RK,\r\n                     maxiter::Int,\r\n                     ftol::T = T(1.e-3)\r\n                    ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n     spline = _prepare_approximation(nodes_b, kernel)\r\n     spline, nit_done = _construct_approximation(spline, values_lb, values_ub, maxiter, ftol)\r\n     return spline\r\nend\r\n\r\n\"\"\"\r\n`approximate(nodes::Matrix{T}, values::Vector{T}, nodes_b::Matrix{T}, values_lb::Vector{T}, values_ub::Vector{T},\r\n             kernel::RK, maxiter::Int, ftol::T) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nPrepare and construct the approximating normal spline.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space\r\n           and `n_1` is the number of function value nodes.\r\n           It means that each column in the matrix defines one node.\r\n- `nodes_b`: function value approximation nodes.\r\n        This should be an `n×n_1_b` matrix, where `n` is dimension of the sampled space and\r\n        `n_1_b` is the number of function value approximation nodes. It means that each column in the matrix defines one node.\r\n- `values`: function values at interpolation nodes.\r\n- `values_lb`: function lower bound values at approximation nodes\r\n- `values_ub`: function upper bound values at approximation nodes\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H0` if the spline is constructing as a continuous function,\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n- `maxiter`: Maximum allowed number of iterations.\r\n- `ftol`: convergence tolerance. The iteration stops when relative spline norm change is smaller than ftol.\r\n\r\nReturn: constructed `NormalSpline` object.\r\n\"\"\"\r\nfunction approximate(nodes::Matrix{T},\r\n                     values::Vector{T},\r\n                     nodes_b::Matrix{T},\r\n                     values_lb::Vector{T},\r\n                     values_ub::Vector{T},\r\n                     kernel::RK,\r\n                     maxiter::Int,\r\n                     ftol::T = T(1.e-3)\r\n                    ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n     spline = _prepare_approximation(nodes, nodes_b, kernel)\r\n     spline, nit_done = _construct_approximation(spline, values, values_lb, values_ub, maxiter, ftol)\r\n     return spline\r\nend\r\n\r\n\"\"\"\r\n`evaluate(spline::NormalSpline{T, RK}, points::Matrix{T}) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nEvaluate the spline values at `points` locations.\r\n\r\n# Arguments\r\n- `spline: constructed `NormalSpline` object.\r\n- `points`: locations at which spline values are evaluating.\r\n            This should be an `n×m` matrix, where `n` is dimension of the sampled space\r\n            and `m` is the number of locations where spline values are evaluating.\r\n            It means that each column in the matrix defines one location.\r\n\r\nReturn: `Vector{T}` of the spline values at the locations defined in `points`.\r\n\"\"\"\r\nfunction evaluate(spline::NormalSpline{T, RK}, points::Matrix{T}\r\n                 ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n    return _evaluate(spline, points)\r\nend\r\n\r\n\"\"\"\r\n`evaluate_at(spline::NormalSpline{T, RK}, point::Vector{T}) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nEvaluate the spline value at the `point` location.\r\n\r\n# Arguments\r\n- `spline`: constructed `NormalSpline` object.\r\n- `point`: location at which spline value is evaluating.\r\n           This should be a vector of size `n`, where `n` is dimension of the sampled space.\r\n\r\nReturn: spline value at the location defined in `point`.\r\n\"\"\"\r\nfunction evaluate_at(spline::NormalSpline{T, RK}, point::Vector{T}\r\n                    ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n    return _evaluate(spline, reshape(point, :, 1))[1]\r\nend\r\n\r\n\"\"\"\r\n`evaluate_gradient(spline::NormalSpline{T, RK}, point::Vector{T}) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nEvaluate gradient of the spline at the location defined in `point`.\r\n\r\n# Arguments\r\n- `spline`: the `NormalSpline` object returned by `interpolate` or `construct` function.\r\n- `point`: location at which gradient value is evaluating.\r\n           This should be a vector of size `n`, where `n` is dimension of the sampled space.\r\n\r\nNote: Gradient of spline built with reproducing kernel RK_H0 does not exist at the spline nodes.\r\n\r\nReturn: `Vector{T}` - gradient of the spline at the `point` location.\r\n\"\"\"\r\nfunction evaluate_gradient(spline::NormalSpline{T, RK},\r\n                           point::Vector{T}\r\n                          ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n    return _evaluate_gradient(spline, point)\r\nend\r\n\r\n########\r\n\r\n\"\"\"\r\n`get_epsilon(spline::NormalSpline{T, RK}) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nGet the 'scaling parameter' of Bessel Potential space the spline was built in.\r\n# Arguments\r\n- `spline`: prepared `NormalSpline` object.\r\n\r\nReturn: `ε` - the 'scaling parameter'.\r\n\"\"\"\r\nfunction get_epsilon(spline::NormalSpline{T, RK}\r\n                    ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n    return spline._kernel.ε\r\nend\r\n\r\n\"\"\"\r\n`estimate_epsilon(nodes::Matrix{T}, kernel::RK = RK_H0()) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nGet the estimation of the 'scaling parameter'2 of Bessel Potential space the spline being built in.\r\nIt coincides with the result returned by `get_epsilon` function.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space\r\n           and `n_1` is the number of function value nodes.\r\n           It means that each column in the matrix defines one node.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline will be constructed in.\r\n           It must be a struct object of the following type:\r\n             `RK_H0` if the spline is constructing as a continuous function,\r\n             `RK_H1` if the spline is constructing as a differentiable function,\r\n             `RK_H2` if the spline is constructing as a twice differentiable function.\r\nReturn: estimation of `ε`.\r\n\"\"\"\r\nfunction estimate_epsilon(nodes::Matrix{T},\r\n                          kernel::RK = RK_H0()\r\n                         ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n    ε = _estimate_epsilon(nodes, kernel)\r\n    return ε\r\nend\r\n\r\n\"\"\"\r\n`estimate_epsilon(nodes::Matrix{T}, d_nodes::Matrix{T}, kernel::RK = RK_H1()) where {T <: AbstractFloat, RK <: ReproducingKernel_1}`\r\n\r\nGet an the estimation of the 'scaling parameter' of Bessel Potential space the spline being built in.\r\nIt coincides with the result returned by `get_epsilon` function.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space\r\n           and `n_1` is the number of function value nodes.\r\n           It means that each column in the matrix defines one node.\r\n- `d_nodes`: function directional derivative nodes.\r\n           This should be an `n×n_2` matrix, where `n` is dimension of the sampled space and\r\n           `n_2` is the number of function directional derivative nodes.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline will be constructed in.\r\n            It must be a struct object of the following type:\r\n            `RK_H1` if the spline is constructing as a differentiable function,\r\n            `RK_H2` if the spline is constructing as a twice differentiable function.\r\n\r\nReturn: estimation of `ε`.\r\n\"\"\"\r\nfunction estimate_epsilon(nodes::Matrix{T},\r\n                          d_nodes::Matrix{T},\r\n                          kernel::RK = RK_H1()\r\n                         ) where {T <: AbstractFloat, RK <: ReproducingKernel_1}\r\n    ε = _estimate_epsilon(nodes, d_nodes, kernel)\r\n    return ε\r\nend\r\n\r\n\"\"\"\r\n`estimate_cond(spline::NormalSpline{T, RK}) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nGet an estimation of the Gram matrix condition number. It needs the `spline` object is prepared and requires O(N^2) operations.\r\n(C. Brás, W. Hager, J. Júdice, An investigation of feasible descent algorithms for estimating the condition number of a matrix. TOP Vol.20, No.3, 2012.)\r\n# Arguments\r\n- `spline`: prepared `NormalSpline` object.\r\n\r\nReturn: an estimation of the Gram matrix condition number.\r\n\"\"\"\r\nfunction estimate_cond(spline::NormalSpline{T, RK}\r\n                      ) where {T <: AbstractFloat, RK <: ReproducingKernel}\r\n    return spline._cond\r\nend\r\n\r\n\"\"\"\r\n`estimate_accuracy(spline::NormalSpline{T, RK}) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nAssess accuracy of interpolation results by analyzing residuals.\r\n# Arguments\r\n- `spline`: constructed `NormalSpline` object.\r\n\r\nReturn: estimation of the number of significant digits in the interpolation result.\r\n\"\"\"\r\nfunction estimate_accuracy(spline::NormalSpline{T, RK}) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n    return _estimate_accuracy(spline)\r\nend\r\n\r\n############################## One-dimensional case\r\n\r\n\"\"\"\r\n`prepare_approximation(nodes_b::Vector{T}, kernel::RK = RK_H0())\r\n                       where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nPrepare the 1D approximating normal spline by constructing and factoring a Gram matrix of the problem.\r\nInitialize the `NormalSpline` object.\r\n# Arguments\r\n- `nodes_b`: function value approximation nodes.\r\n             This should be an `n_1_b` vector where `n_1_b` is the number of function value approximation nodes.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H0` if the spline is constructing as a continuous function,\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n\r\nReturn: prepared `NormalSpline` object.\r\n\"\"\"\r\nfunction prepare_approximation(nodes_b::Vector{T},\r\n                               kernel::RK = RK_H0()\r\n                              ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n\r\n     spline = _prepare_approximation(Matrix(nodes_b'), kernel)\r\n     return spline\r\nend\r\n\r\n\"\"\"\r\n`prepare_approximation(nodes::Vector{T}, nodes_b::Vector{T}, kernel::RK = RK_H0())\r\n                       where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nPrepare the 1D approximating normal spline by constructing and factoring a Gram matrix of the problem.\r\nInitialize the `NormalSpline` object.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n           This should be an `n_1` vector where `n_1` is the number of function value interpolation nodes.\r\n- `nodes_b`: function value approximation nodes.\r\n           This should be an `n_1_b` vector where `n_1_b` is the number of function value approximation nodes.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H0` if the spline is constructing as a continuous function,\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n\r\nReturn: prepared `NormalSpline` object.\r\n\"\"\"\r\nfunction prepare_approximation(nodes::Vector{T},\r\n                               nodes_b::Vector{T},\r\n                               kernel::RK = RK_H0()\r\n                              ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n     spline = _prepare_approximation(Matrix(nodes'), Matrix(nodes_b'), kernel)\r\n     return spline\r\nend\r\n\r\n\"\"\"\r\n`approximate(values::Vector{T}, nodes_b::Vector{T}, values_lb::Vector{T}, values_ub::Vector{T},\r\n             kernel::RK, maxiter::Int, ftol::T) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nPrepare and construct the 1D approximating normal spline.\r\n# Arguments\r\n- `nodes_b`: function value approximation nodes.\r\n          This should be an `n_1_b` vector where `n_1_b` is the number of function value approximation nodes.\r\n- `values_lb`: function lower bound values at approximation nodes\r\n- `values_ub`: function upper bound values at approximation nodes\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H0` if the spline is constructing as a continuous function,\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n- `maxiter`: Maximum allowed number of iterations.\r\n- `ftol`: convergence tolerance. The iteration stops when relative spline norm change is smaller than ftol.\r\n\r\nReturn: constructed `NormalSpline` object.\r\n\"\"\"\r\nfunction approximate(nodes_b::Vector{T},\r\n                     values_lb::Vector{T},\r\n                     values_ub::Vector{T},\r\n                     kernel::RK,\r\n                     maxiter::Int,\r\n                     ftol::T = T(1.e-3)\r\n               ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n     spline = _prepare_approximation(Matrix(nodes_b'), kernel)\r\n     spline, nit_done = _construct_approximation(spline, values_lb, values_ub, maxiter, ftol)\r\n     return spline\r\nend\r\n\r\n\"\"\"\r\n`approximate(nodes::Vector{T}, values::Vector{T}, nodes_b::Vector{T}, values_lb::Vector{T}, values_ub::Vector{T},\r\n             kernel::RK, maxiter::Int, ftol::T) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nPrepare and construct the 1D approximating normal spline.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n          This should be an `n_1` vector where `n_1` is the number of function value interpolation nodes.\r\n- `values`: function values at interpolation nodes.\r\n- `nodes_b`: function value approximation nodes.\r\n          This should be an `n_1_b` vector where `n_1_b` is the number of function value approximation nodes.\r\n- `values_lb`: function lower bound values at approximation nodes\r\n- `values_ub`: function upper bound values at approximation nodes\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H0` if the spline is constructing as a continuous function,\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n- `maxiter`: Maximum allowed number of iterations.\r\n- `ftol`: convergence tolerance. The iteration stops when relative spline norm change is smaller than ftol.\r\n\r\nReturn: constructed `NormalSpline` object.\r\n\"\"\"\r\nfunction approximate(nodes::Vector{T},\r\n                     values::Vector{T},\r\n                     nodes_b::Vector{T},\r\n                     values_lb::Vector{T},\r\n                     values_ub::Vector{T},\r\n                     kernel::RK,\r\n                     maxiter::Int,\r\n                     ftol::T = T(1.e-3)\r\n               ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n     spline = _prepare_approximation(Matrix(nodes'), Matrix(nodes_b'), kernel)\r\n     spline, nit_done = _construct_approximation(spline, values, values_lb, values_ub, maxiter, ftol)\r\n     return spline\r\nend\r\n\r\n\"\"\"\r\n`evaluate(spline::NormalSpline{T, RK}, points::Vector{T}) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nEvaluate the 1D spline values at the `points` locations.\r\n\r\n# Arguments\r\n- `spline`: constructed `NormalSpline` object.\r\n- `points`: locations at which spline values are evaluating.\r\n            This should be a vector of size `m` where `m` is the number of evaluating points.\r\n\r\nReturn: spline value at the `point` location.\r\n\"\"\"\r\nfunction evaluate(spline::NormalSpline{T, RK}, points::Vector{T}\r\n                               ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n    return _evaluate(spline, Matrix(points'))\r\nend\r\n\r\n\"\"\"\r\n`evaluate_at(spline::NormalSpline{T, RK}, point::T) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nEvaluate the 1D spline value at the `point` location.\r\n\r\n# Arguments\r\n- `spline`: constructed `NormalSpline` object.\r\n- `point`: location at which spline value is evaluating.\r\n\r\nReturn: spline value at the `point` location.\r\n\"\"\"\r\nfunction evaluate_at(spline::NormalSpline{T, RK},\r\n                                       point::T\r\n                                      ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n    v_points = Vector{T}(undef, 1)\r\n    v_points[1] = point\r\n    return _evaluate(spline, Matrix(v_points'))[1]\r\nend\r\n\r\n\"\"\"\r\n`evaluate_derivative(spline::NormalSpline{T, RK}, point::T) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nEvaluate the 1D spline derivative at the `point` location.\r\n\r\n# Arguments\r\n- `spline`: the `NormalSpline` object returned by `interpolate` or `construct` function.\r\n- `point`: location at which spline derivative is evaluating.\r\n\r\nNote: Derivative of spline built with reproducing kernel RK_H0 does not exist at the spline nodes.\r\n\r\nReturn: spline derivative value at the `point` location.\r\n\"\"\"\r\nfunction evaluate_derivative(spline::NormalSpline{T, RK},\r\n                             point::T\r\n                            ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n    v_points = Vector{T}(undef, 1)\r\n    v_points[1] = point\r\n    return _evaluate_gradient(spline, v_points)[1]\r\nend\r\n\r\n\"\"\"\r\n`estimate_epsilon(nodes::Vector{T}, kernel::RK = RK_H0()) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nGet an the estimation of the 'scaling parameter' of Bessel Potential space the spline being built in.\r\nIt coincides with the result returned by `get_epsilon` function.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H0` if the spline is constructing as a continuous function,\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n\r\nReturn: estimation of `ε`.\r\n\"\"\"\r\nfunction estimate_epsilon(nodes::Vector{T},\r\n                          kernel::RK = RK_H0()\r\n                         ) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n    ε = _estimate_epsilon(Matrix(nodes'), kernel)\r\n    return ε\r\nend\r\n\r\n\"\"\"\r\n`estimate_epsilon(nodes::Vector{T}, d_nodes::Vector{T}, kernel::RK = RK_H1()) where {T <: AbstractFloat, RK <: ReproducingKernel_1}`\r\n\r\nGet an the estimation of the 'scaling parameter' of Bessel Potential space the spline being built in.\r\nIt coincides with the result returned by `get_epsilon` function.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n- `d_nodes`: function derivative nodes.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n\r\nReturn: estimation of `ε`.\r\n\"\"\"\r\nfunction estimate_epsilon(nodes::Vector{T},\r\n                          d_nodes::Vector{T},\r\n                          kernel::RK = RK_H1()\r\n                         ) where {T <: AbstractFloat, RK <: ReproducingKernel_1}\r\n    ε = _estimate_epsilon(Matrix(nodes'), Matrix(d_nodes'), kernel)\r\n    return ε\r\nend\r\n\r\n\"\"\"\r\n`get_cond(nodes::Matrix{T}, kernel::RK = RK_H0()) where {T <: AbstractFloat, RK <: ReproducingKernel_0}`\r\n\r\nGet a value of the Gram matrix spectral condition number. It is obtained by means of the matrix SVD decomposition.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space and\r\n           `n_1` is the number of function value nodes. It means that each column in the matrix defines one node.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H0` if the spline is constructing as a continuous function,\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n\r\nReturn: a value of the Gram matrix spectral condition number.\r\n\"\"\"\r\nfunction get_cond(nodes::Matrix{T}, kernel::RK) where {T <: AbstractFloat, RK <: ReproducingKernel_0}\r\n  return _get_cond(nodes, kernel)\r\nend\r\n\r\n\"\"\"\r\n`get_cond(nodes::Matrix{T}, d_nodes::Matrix{T}, es::Matrix{T}, kernel::RK = RK_H1()) where {T <: AbstractFloat, RK <: ReproducingKernel_1}`\r\n\r\nGet a value of the Gram matrix spectral condition number. It is obtained by means of the matrix SVD decomposition.\r\n# Arguments\r\n- `nodes`: function value interpolation nodes.\r\n           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space and\r\n           `n_1` is the number of function value nodes.\r\n            It means that each column in the matrix defines one node.\r\n- `d_nodes`: function directional derivatives nodes.\r\n             This should be an `n×n_2` matrix, where `n` is dimension of the sampled space and\r\n             `n_2` is the number of function directional derivative nodes.\r\n- `es`: Directions of the function directional derivatives.\r\n        This should be an `n×n_2` matrix, where `n` is dimension of the sampled space and\r\n        `n_2` is the number of function directional derivative nodes.\r\n        It means that each column in the matrix defines one direction of the function directional derivative.\r\n- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.\r\n            It must be a struct object of the following type:\r\n              `RK_H1` if the spline is constructing as a differentiable function,\r\n              `RK_H2` if the spline is constructing as a twice differentiable function.\r\n\r\nReturn: value of the Gram matrix spectral condition number.\r\n\"\"\"\r\nfunction get_cond(nodes::Matrix{T}, d_nodes::Matrix{T}, es::Matrix{T}, kernel::RK = RK_H1()\r\n                 ) where {T <: AbstractFloat, RK <: ReproducingKernel_1}\r\n    return _get_cond(nodes, d_nodes, es, kernel)\r\nend\r\n\r\n\r\nend # module\r\n", "meta": {"hexsha": "45baa0056dd3180f91183c228e36ad2fde86431c", "size": 34006, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NormalSmoothingSplines.jl", "max_stars_repo_name": "IgorKohan/NormalSmoothingSplines.jl", "max_stars_repo_head_hexsha": "828b167daba02bf637463fe00afb53ea349058fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NormalSmoothingSplines.jl", "max_issues_repo_name": "IgorKohan/NormalSmoothingSplines.jl", "max_issues_repo_head_hexsha": "828b167daba02bf637463fe00afb53ea349058fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NormalSmoothingSplines.jl", "max_forks_repo_name": "IgorKohan/NormalSmoothingSplines.jl", "max_forks_repo_head_hexsha": "828b167daba02bf637463fe00afb53ea349058fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.58, "max_line_length": 153, "alphanum_fraction": 0.6711168617, "num_tokens": 7490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825847, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7623273914138737}}
{"text": "\"\"\"\n    skewness(x; method=:moment)\n\nCalculates the skewness using the specified method.\n\n# Methods\n- Moment (default)\n- Fisher-Pearson\n- Sample\n\n# Arguments\n- `x`:          Vector of values.\n- `method`:     Estimation method: `:moment`, `:fisher_pearson` or `:sample`.\n\"\"\"\nfunction skewness(x; method::Symbol=:moment)\n    n = length(x)\n    mean_devs = x .- mean(x)\n\n    if method == :moment\n        # Moment\n        return mean(mean_devs.^3) / sqrt(mean(mean_devs.^2))^3  # sqrt(x)^3 faster than x^1.5 !\n    elseif method == :fisher_pearson\n        # Fisher-Pearson\n        if n > 2\n            return sqrt(n*(n-1))/(n-2) * mean(mean_devs.^3) / sqrt(mean(mean_devs.^2))^3  # sqrt(x)^3 faster than x^1.5 !\n        else\n            return NaN\n        end\n    elseif method == :sample\n        # Sample\n        return n/((n-1)*(n-2)) * sum(mean_devs.^3 / sqrt(mean(mean_devs.^2))^3)\n    end\n\n    throw(ArgumentError(\"Passed method parameter '$(method)' is invalid, must be one of :moment, :fisher_pearson, :sample.\"))\nend\n\n\n\n\"\"\"\n    kurtosis(x; method=:excess)\n\nCalculates the kurtosis using on the specified method.\n\n# Methods\n- Excess (default)\n- Moment\n- Cornish-Fisher\n\n# Arguments\n- `x`:          Vector of values.\n- `method`:     Estimation method: `:excess`, `:moment` or `:cornish_fisher`.\n\"\"\"\nfunction kurtosis(x; method::Symbol=:excess)\n    n = length(x)\n    mean_devs = x .- mean(x)\n\n    if method == :excess\n        # Excess\n        return sum(mean_devs.^4 / mean(mean_devs.^2)^2 ) / n - 3\n    elseif method == :moment\n        # Moment\n        return sum(mean_devs.^4 / mean(mean_devs.^2)^2 ) / n\n    elseif method == :cornish_fisher\n        # Cornish-Fisher\n        return ((n+1)*(n-1)*((sum(x.^4)/n)/(sum(x.^2)/n)^2 -\n            (3*(n-1))/(n+1)))/((n-2)*(n-3))\n    end\n\n    throw(ArgumentError(\"Passed method parameter '$(method)' is invalid, must be one of :excess, :moment, :cornish_fisher.\"))\nend\n\n\n\n\"\"\"\n    lower_partial_moment(returns, threshold, n, method)\n\nThis function calculates the Lower Partial Moment (LPM) for a given threshold.\n\n# Arguments\n- `returns`:     Vector of asset returns.\n- `threshold`:   Scalar value or vector denoting the threshold returns.\n- `n`:           `n`-th moment to calculate.\n- `method`:      One of `:full` or `:partial`. Indicates whether to use the number of all returns (`:full`), or only the number of returns below the threshold (`:partial`) in the denominator.\n\"\"\"\nfunction lower_partial_moment(returns, threshold, n, method::Symbol)\n    if method == :full\n        denominator = length(returns)\n    elseif method == :partial\n        denominator = count(returns .< threshold)\n    else\n        throw(ArgumentError(\"Passed method parameter '$(method)' is invalid, must be one of :full, :partial.\"))\n    end\n    excess = threshold .- returns\n    sum(map(x -> max(0.0, x)^n, excess)) / denominator\nend\n\n\n\n\"\"\"\n    higher_partial_moment(returns, threshold, n, method)\n\nThis function calculates the Higher Partial Moment (HPM) for a given threshold.\n\n# Arguments\n- `returns`:     Vector of asset returns.\n- `threshold`:   Scalar value or vector denoting the threshold returns.\n- `n`:           `n`-th moment to calculate.\n- `method`:      One of `:full` or `:partial`. Indicates whether to use the number of all returns (`:full`), or only the number of returns above the threshold (`:partial`) in the denominator.\n\"\"\"\nfunction higher_partial_moment(returns, threshold, n, method::Symbol)\n    if method == :full\n        denominator = length(returns)\n    elseif method == :partial\n        denominator = count(returns .> threshold)\n    else\n        throw(ArgumentError(\"Passed method parameter '$(method)' is invalid, must be one of :full, :partial.\"))\n    end\n    excess = returns .- threshold\n    sum(map(x -> max(0.0, x)^n, excess)) / denominator\nend\n", "meta": {"hexsha": "dae4b63ff898da4a180b0c33db0bc78b00fa0b6c", "size": 3801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/moments.jl", "max_stars_repo_name": "rbeeli/RiskPerf.jl", "max_stars_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-07T19:19:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T19:19:09.000Z", "max_issues_repo_path": "src/moments.jl", "max_issues_repo_name": "rbeeli/RiskPerf.jl", "max_issues_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/moments.jl", "max_forks_repo_name": "rbeeli/RiskPerf.jl", "max_forks_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4132231405, "max_line_length": 191, "alphanum_fraction": 0.6314127861, "num_tokens": 1057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7623273897057511}}
{"text": "# Author: Lukasz Bratos\n\nmodule Diff\nusing Plots\ngr()\n\nexport ilorazyRoznicowe, warNewton, naturalna, rysujNnfx\n\n\"\"\"\nFunkcja oblicza iloraz różnicowy\n\nDane:\nx – wektor długości n + 1 zawierający węzły x0, ..., xn\n    x[1] = x0, ..., x[n+1] = xn\nf – wektor długości n + 1 zawierający wartości interpolowanej funkcji w węzłach\n    f(x0), ..., f(xn)\n\nWyniki:\nfx– wektor długości n + 1 zawierający obliczone ilorazy różnicowe\n    fx[1] = f[x0],\n    fx[2] = f[x0, x1], ..., fx[n] = f[x0, ..., xn−1], fx[n+1] = f[x0, ..., xn]\n\"\"\"\nfunction ilorazyRoznicowe(x::Vector{Float64}, f::Vector{Float64})\n    len = length(f)\n    fx = Vector{Float64}(undef, len)\n\n    for i in 1:len\n        fx[i] = f[i]\n    end\n\n    for i in 2:len\n        for j in len:-1:i\n            fx[j] = (fx[j] - fx[j - 1]) / (x[j] - x[j - i + 1])\n        end\n    end\n\n    return fx\nend\n\n\"\"\"\nFunkcja wyliczajaca wartosc wielomianu interpolacyjnego stopnia n w postaci Newtona Nn(x)\nza pomoca uogolnionego algorytmu Hornera\n\nDane:\nx – wektor długości n + 1 zawierający węzły x0, ..., xn\n    x[1] = x0, ..., x[n+1] = xn\nfx – wektor długości n+ 1 zawierający ilorazy różnicowe\n    fx[1] = f[x0],\n    fx[2] = f[x0, x1], ..., fx[n] = f[x0, ..., xn−1], fx[n+1] =f [x0, ..., xn]\nt – punkt, w którym należy obliczyć wartość wielomianu\n\nWyniki:\nnt – wartość wielomianu w punkcie t\n\"\"\"\nfunction warNewton(x::Vector{Float64}, fx::Vector{Float64}, t::Float64)\n    len = length(x)\n    nt = fx[len]\n\n    for i in (len - 1):-1:1\n        nt = fx[i] + (t - x[i]) * nt\n    end\n\n    return nt\nend\n\n\"\"\"\nFunkcja wyliczajaca wspolczynniki wielomianu w postaci normanej z wielomianu \ninterpolacyjnego w postaci Newtona\n\nDane:\nx – wektor długości n+ 1 zawierający węzły x0, ..., xn\n    x[1] = x0, ..., x[n+1] = xn\nfx – wektor długości n + 1 zawierający ilorazy różnicowe\n    fx[1] = f[x0],\n    fx[2] = f[x0, x1], ..., fx[n] = f[x0, ..., xn−1], fx[n+1] = f[x0, ..., xn]\n\nWyniki:\na – wektor długości n+ 1 zawierający obliczone współczynniki postaci naturalnej\n    a[1] = a0,\n    a[2] = a1, ..., a[n] = an−1, a[n+1] = an.\n\"\"\"\nfunction naturalna(x::Vector{Float64}, fx::Vector{Float64})\n    len = length(x)\n    a = Vector{Float64}(undef, len)\n    a[len] = fx[len]\n\n    for i in (len - 1):-1:1\n        a[i] = fx[i] - a[i + 1] * x[i]\n\n        for j in (i + 1):(len - 1)\n            a[j] = a[j] - a[j + 1] * x[i]\n        end\n    end\n\n    return a\nend\n\n\"\"\"\nFunkcja rysująca wielomian interpolacyjny i interpolowaną funkcję na danym przedziale\n\nDane:\nf – funkcja f(x) zadana jako anonimowa funkcja,\na, b – przedział interpolacji\nn – stopień wielomianu interpolacyjnego\nfilename - nazwa pliku wynikowego\n\nWyniki:\n– funkcja rysuje wielomian interpolacyjny i interpolowaną funkcję w przedziale [a, b]\n\"\"\"\nfunction rysujNnfx(f, a::Float64, b::Float64, n::Int, filename::String)\n    dist = (b - a) / n\n\n    x = Vector{Float64}(undef, n + 1)\n    y = Vector{Float64}(undef, n + 1)\n\n    for i in 1:(n + 1)\n        x[i] = a + (i - 1) * dist\n        y[i] = f(x[i]);\n    end\n\n    fx = ilorazyRoznicowe(x, y)\n\n    numOfPoints = 100\n    plot_dist = (b - a) / numOfPoints\n\n    fx_val = Vector{Float64}(undef, numOfPoints + 1)\n    wx_val = Vector{Float64}(undef, numOfPoints + 1)\n\n    for i in 1:(numOfPoints + 1)\n        t = a + (i - 1) * plot_dist\n        fx_val[i] = f(t)\n        wx_val[i] = warNewton(x, fx, t)\n    end\n\n    plot(range(a, stop=b, length=(numOfPoints + 1)), fx_val, color = \"red\", label = \"f(x)\")\n    plot!(range(a, stop=b, length=(numOfPoints + 1)), wx_val, color = \"blue\", label = \"w(x)\")\n    savefig(\"./plots/$filename.png\")\nend\n\nend\n\n", "meta": {"hexsha": "3517d172df7967da7870f7910cb040a1fc26a2bd", "size": 3567, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "list4/diff.jl", "max_stars_repo_name": "luk9400/on", "max_stars_repo_head_hexsha": "0f35fb60d020c065c96c54893161a3c41ab77acb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "list4/diff.jl", "max_issues_repo_name": "luk9400/on", "max_issues_repo_head_hexsha": "0f35fb60d020c065c96c54893161a3c41ab77acb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "list4/diff.jl", "max_forks_repo_name": "luk9400/on", "max_forks_repo_head_hexsha": "0f35fb60d020c065c96c54893161a3c41ab77acb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1197183099, "max_line_length": 93, "alphanum_fraction": 0.5915335015, "num_tokens": 1390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7623273836411519}}
{"text": "# Classification Metrics and Plots\n# This files contains various metrics used in Classifiaction problems\n\n# One Hot encode\nfunction onehot_encode(y, labels)\n   onehot_arr = zeros(length(labels), length(y))\n   for i in 1:length(y)\n       onehot_arr[Int(y[i]) + 1, i] = 1\n   end\n   onehot_arr\nend\n\n\"\"\"\n    bin_to_cat(y_pred, y_true)\n\nFunction to convert binary type of data to categorical with two categories. Return `y_pred` and `y_true` of shape `(2, length(y_pred))` as tuple. Utility function to support performance metrics like `Precision`, `Recall` etc, where the function first need to be converted to categorical form before applying metric. \n\"\"\" \nfunction bin_to_cat(y_pred, y_true)\n    @assert length(y_pred) == length(y_true)\n    y_pred_ = zeros(2, length(y_pred))\n    y_pred_[2, :] = y_pred\n    y_pred_[1, :] = 1 .- y_pred\n    return (y_pred_, onehot_encode(y_true, 0:1))\nend\n\n# Onecold\nfunction onecold(y)\n    onecold_arr = zeros(size(y,2))\n    argmax_vec = argmax(y, dims = 1)\n    for i in 1:size(y,2)\n        onecold_arr[i] = argmax_vec[i].I[1]\n    end\n    return onecold_arr\nend\n\n\"\"\"\n    confusion_matrix(y_pred, y_true)\n\nFunction to create a confusion_matrix for classification problems based on provided `y_pred` and `y_true`. Expects `y_true`, to be onehot_enocded already.\n\"\"\"\nfunction confusion_matrix(y_pred, y_true)\n    @assert size(y_pred) == size(y_true)\n    label_count = size(y_true, 1)\n    ŷ = onehot_encode(onecold(y_pred), 1:label_count)\n    return ŷ * transpose(y_true) \nend\n  \n\"\"\"\n    TFPN(y_pred, y_true)\n\nReturns `Confusion Matrix` and `True Positive`, `True Negative`, `False Positive` and `False Negative` for each class based on `y_pred` and `y_true`. Expects `y_true`, to be onehot_enocded already.  \n\"\"\" \nfunction TFPN(y_pred, y_true)\n    @assert size(y_pred) == size(y_true)\n    label_count = size(y_true, 1)\n    TP = zeros(label_count) ; TN = zeros(label_count)\n    FP = zeros(label_count) ; FN = zeros(label_count)\n    ConfusionMatrix = confusion_matrix(y_pred, y_true)\n    for c in 1 : label_count\n        TP[c] = ConfusionMatrix[c,c]\n        FP[c] = sum(ConfusionMatrix[:,c]) - TP[c]\n        FN[c] = sum(ConfusionMatrix[c,:]) - TP[c]\n        TN[c] = sum(ConfusionMatrix) - TP[c] - FP[c] - FN[c]\n    end\n    return ConfusionMatrix,TP, TN, FP, FN\nend\n\n\"\"\"\n    binary_accuracy(y_pred, y_true; threshold=0.5)\n\nCalculates Averaged Binary Accuracy based on `y_pred` and `y_true`. Argument `threshold` is used to specify the minimum predicted probability `y_pred` required to be labelled as `1`. Default value set as `0.5`.\n\"\"\" \nfunction binary_accuracy(y_pred, y_true; threshold=0.5)\n    @assert size(y_pred) == size(y_true)\n    return sum((y_pred .>= threshold) .== y_true) / size(y_true, 1)\nend\n\n\"\"\"\n    categorical_accuracy(y_pred, y_true)\n\nCalculates Averaged Categorical Accuracy based on `y_pred` and `y_true`.\n\"\"\"\nfunction categorical_accuracy(y_pred, y_true)\n    @assert size(y_pred) == size(y_true)\n    return sum(onecold(y_pred) .== onecold(y_true)) / size(y_true, 2)\nend\n\n\"\"\"\n    sparse_categorical(y_pred, y_true)\n\nCalculated Sparse Categorical Accuracy based on `y_pred` and `y_true`. It evaluates the maximal true value is equal to the index of the maximal predicted value. Here, `y_true` is expected to provide only an integer (start from `0` index) as label for each data element (ie. not one hot encoded). \n\"\"\"\nfunction sparse_categorical(y_pred, y_true)\n    @assert size(y_pred, 2) == length(y_true)\n    return sum(onecold(y_pred) .== (y_true .+ 1) ) / size(y_true, 1)\nend\n\n\"\"\"\n    top_k_categorical(y_pred, y_true; k=3)\n\nEvaluates if the index of true value is equal to any of the indices of top k predicted values. Default value of `k` set to `3`. \n\"\"\"\nfunction top_k_categorical(y_pred, y_true; k=3)\n    @assert size(y_pred) == size(y_true)\n    count = 0\n    sparse_y = onecold(y_true)\n    for i in 1:size(y_true, 2)\n        top_k = partialsortperm(y_pred[:,i], 1:k, lt= >)\n        for j in 1:k\n            if top_k[j] == sparse_y[i] \n                count+=1\n                break\n            end\n        end\n    end\n    return count / length(sparse_y) \nend\n\n\n\"\"\"\n    top_k_sparse_categorical(y_pred, y_true; k=3)\n\nEvaluates if the true value is equal to any of the indices of top k predicted values. Default value of `k` set to `3`. Similar to `sparse_categorical`, expects the `y_true` to provide only an integer (start from `0` index) as label for each data element (ie. not one hot encoded).\n\"\"\"\nfunction top_k_sparse_categorical(y_pred, y_true; k=3)\n    count = 0\n    for i in 1:length(y_true)\n        top_k = partialsortperm(y_pred[:,i], 1:k, lt= >)\n        for j in 1:k\n            if top_k[j] == y_true[i] + 1\n                count+=1\n                break\n            end\n        end\n    end\n    return count / length(y_true)\nend\n\n# Calculate Instances for each class in y\nfunction calc_instances(y)\n   instances = zeros(size(y, 1))\n   sparse_y = onecold(y)\n   for i in 1:length(instances)\n       instances[i] = sum(sparse_y .== i)\n   end\n   return instances\nend\n\n\"\"\"\n    precision(y_pred, y_true; avg_type=\"macro\", sample_weights=nothing)\n\nComputes the precision of the predictions with respect to the labels. \n\n# Arguments\n - `y_pred`: predicted values.\n - `y_true`: ground truth values on the basis of which predicted values are to be assessed.\n - `avg_type=\"macro\"`: Type of average to be used while calculating precision of multiclass models. Can take values as `macro`, `micro` and `weighted`. Default set to `macro`.\n - `sample_weights`: Class weights to be provided when `avg_type` is set to `weighted`. Useful in case of imbalanced classes.\n \n\"\"\"\nfunction precision(y_pred, y_true; avg_type=\"macro\", sample_weights=nothing)\n    _,TP, TN, FP, FN = TFPN(y_pred, y_true)\n    # Macro-averaged Precision\n    if avg_type == \"macro\"\n        return mean(TP ./ (TP .+ FP .+ eps(eltype(TP))))\n    # Micro-averaged Precision\n    elseif avg_type == \"micro\"   \n        return mean(TP) / (mean(TP) + mean(FP))\n    # Weighted-Averaged Precision\n    elseif avg_type == \"weighted\"\n        weights = []\n        if sample_weights != nothing\n            weights = sample_weights\n        else\n            weights = calc_instances(y_true) / size(y_true, 2)\n        end\n        return mean((TP ./ (TP .+ FP .+ eps(eltype(TP)))) .* weights)\n    end\nend\n\n\"\"\"\n    recall(y_pred, y_true; avg_type=\"macro\", sample_weights=nothing)\n\nComputes the recall of the predictions with respect to the labels.\n\n# Arguments\n - `y_pred`: predicted values.\n - `y_true`: ground truth values on the basis of which predicted values are to be assessed.\n - `avg_type=\"macro\"`: Type of average to be used while calculating precision of multiclass models. Can take values as `macro`, `micro` and `weighted`. Default set to `macro`.\n - `sample_weights`: Class weights to be provided when `avg_type` is set to `weighted`. Useful in case of imbalanced classes.\n\nAliases: `sensitivity` and `detection_rate`\n\"\"\"\nfunction recall(y_pred, y_true; avg_type=\"macro\", sample_weights=nothing)\n    _,TP, TN, FP, FN = TFPN(y_pred, y_true)\n    # Macro-averaged Precision\n    if avg_type == \"macro\"\n        return mean(TP ./ (TP .+ FN .+ eps(eltype(TP))))    \n    # Micro-averaged Precision\n    elseif avg_type == \"micro\"   \n        return mean(TP) / (mean(TP) + mean(FN))\n    # Weighted-Averaged Precision\n    else\n        weights = []\n        if sample_weights != nothing\n            weights = sample_weights\n        else\n            weights = calc_instances(y_true) / size(y_true, 2)\n        end\n        return mean((TP ./ (TP .+ FN .+ eps(eltype(TP)))) .* weights)\n    end\nend\nconst sensitivity = recall\nconst detection_rate = recall\n\n\"\"\"\n    f_beta_score(y_pred, y_true; β=1, avg_type=\"macro\", sample_weights=nothing)\n\nCompute fbeta score. The F_beta score is the weighted harmonic mean of precision and recall, reaching its optimal value at 1 and its worst value at 0.\n\n# Arguments\n - `y_pred`: predicted values.\n - `y_true`: ground truth values on the basis of which predicted values are to be assessed.\n - `β=1`: the weight of precision in the combined score. If `β<1`, more weight given to `precision`, while `β>1` favors recall.\n - `avg_type=\"macro\"`: Type of average to be used while calculating precision of multiclass models. Can take values as `macro`, `micro` and `weighted`. Default set to `macro`.\n - `sample_weights`: Class weights to be provided when `avg_type` is set to `weighted`. Useful in case of imbalanced classes.\n\n\"\"\"\nfunction f_beta_score(y_pred, y_true; β=1, avg_type=\"macro\", sample_weights=nothing)\n    recall_ = recall(y_pred, y_true, avg_type=avg_type, sample_weights=sample_weights)\n    precision_ = precision(y_pred, y_true, avg_type=avg_type, sample_weights=sample_weights)\n    return (1 + β^2) * precision_ * recall_ / (precision_ + (β^2) * recall_ + eps(eltype(y_pred)))\nend\n\n\n\"\"\"\n    specificity(y_pred, y_true; avg_type=\"macro\", sample_weights=nothing)\n\nComputes the specificity of the predictions with respect to the labels.\n\n# Arguments\n - `y_pred`: predicted values.\n - `y_true`: ground truth values on the basis of which predicted values are to be assessed.\n - `avg_type=\"macro\"`: Type of average to be used while calculating precision of multiclass models. Can take values as `macro`, `micro` and `weighted`. Default set to `macro`.\n - `sample_weights`: Class weights to be provided when `avg_type` is set to `weighted`. Useful in case of imbalanced classes.\n\"\"\"\nfunction specificity(y_pred, y_true; avg_type=\"macro\", sample_weights=nothing)\n    _, TP, TN, FP, FN = TFPN(y_pred, y_true)\n    # Macro-averaged Precision\n    if avg_type == \"macro\"\n        return mean(TN ./ (TN .+ FP .+ eps(eltype(TP))))    \n    # Micro-averaged Precision\n    elseif avg_type == \"micro\"   \n        return mean(TN) / (mean(TN) + mean(FP))\n    # Weighted-Averaged Precision\n    else\n        weights = []\n        if sample_weights != nothing\n            weights = sample_weights\n        else\n            weights = calc_instances(y_true) / size(y_true, 2)\n        end\n        return mean((TN ./ (TN .+ FP .+ eps(eltype(TP)))) .* weights)\n    end\nend\n\n\"\"\"\n    false_alarm_rate(y_pred, y_true; avg_type=\"macro\", sample_weights=nothing)\n\nComputes the false_alarm_raye of the predictions with respect to the labels as `1 - specificity(y_pred, y_true, avg_type, sample_weights)`\n\n# Arguments\n - `y_pred`: predicted values.\n - `y_true`: ground truth values on the basis of which predicted values are to be assessed.\n - `avg_type=\"macro\"`: Type of average to be used while calculating precision of multiclass models. Can take values as `macro`, `micro` and `weighted`. Default set to `macro`.\n - `sample_weights`: Class weights to be provided when `avg_type` is set to `weighted`. Useful in case of imbalanced classes.\n\nSee also: [`specificity`](@ref)\n\"\"\"\nfunction false_alarm_rate(y_pred, y_true; avg_type=\"macro\", sample_weights=nothing)\n    return 1 - specificity(y_pred, y_true, avg_type, sample_weights)\nend\n\n\"\"\"\n    cohen_kappa(y_pred, y_true)\n\nMeasures the agreement between two raters (predicted and ground truth, here) who each classify N items into C mutually exclusive categories, using the observed data to calculate the probabilities of each observer randomly seeing each category.\nIf the raters are in complete agreement then κ = 1. If there is no agreement among the raters other than what would be expected by chance,\nκ = 0.\n\nRef: [Cohen's Kappa](https://en.wikipedia.org/wiki/Cohen%27s_kappa)\n\"\"\"\nfunction cohen_kappa(y_pred, y_true)\n    _, tp, tn, fp, fn = TFPN(y_pred, y_true)\n    mrg_a = ((tp .+ fn) .* (tp .+ fp)) ./ (tp .+ fn .+ fp .+ tn)\n    mrg_b = ((fp .+ tn) .* (fn .+ tn)) ./ (tp .+ fn .+ fp .+ tn)\n    expec_agree = (mrg_a .+ mrg_b) ./ (tp .+ fn .+ fp .+ tn)\n    obs_agree = (tp .+ tn) ./ (tp .+ fn .+ fp .+ tn)\n    cohens_kappa = mean((obs_agree .- expec_agree) ./ (1 .- expec_agree))\n    return cohens_kappa\nend\n\n\"\"\"\n    statsfromTFPN(TP, TN, FP, FN)\n\nComputes statistics in case of binary classification or one-vs-all statsitics in case of multiclass classification.\n\n# Arguments:\n - `TP`: true positive values\n - `TN`: true negative values\n - `FP`: false positive values\n - `FN`: false negative values\n\nReturn the result stats as a dictionary.\n\"\"\"\nfunction statsfromTFPN(TP, TN, FP, FN)\n    Confusion_Matrix = reshape([TP, FP, FN, TN], 2, 2)\n    Precision = TP / (TP + FP + eps(eltype(TP)))\n    Recall = TP / (TP + FN + eps(eltype(TP)))\n    Specificity = TN / (TN + FP + eps(eltype(TP)))\n    F1_score = 2 * (Precision * Recall) / (Precision + Recall + eps(eltype(TP)))\n    Accuracy = (TP + TN) / (TP + TN + FP + FN)\n    False_alarm_rate = 1 - Specificity\n    return Dict(:Confusion_Matrix => Confusion_Matrix,\n                :Precision => Precision, :Recall => Recall,\n                :Specificity => Specificity, :F1_score => F1_score,\n                :Accuracy => Accuracy)\nend\n\n\"\"\"\n    classwise_stats(y_pred, y_true)\n\nComputes statistics for each of the class for multiclass classification based on provided `y_pred` and `y_true`.\n\nReturn the result stats as a dictionary.\n\"\"\"\nfunction classwise_stats(y_pred, y_true)\n    _, TP, TN, FP, FN = TFPN(y_pred, y_true)\n    ClasswiseStats = Dict() \n    for i in 1:size(y_true, 1)\n        ClasswiseStats[i] = StatsfromTFPN(TP[i], TN[i], FP[i], FN[i])\n    end\n    return ClasswiseStats\nend\n\n\"\"\"\n    global_stats(y_pred, y_true; avg_type=\"macro\")\n\nComputes the overall statistics based on provided `y_pred` and `y_true`. `avg_type` allows to specify the type of average to be used while evaluating the stats. Currently, it can take values as \"macro\" or \"micro\".\n\nReturn the result stats as a dictionary.\n\"\"\"\nfunction global_stats(y_pred, y_true; avg_type=\"macro\")\n    confusion_matrix_, TP, TN, FP, FN = TFPN(y_pred, y_true) \n    if avg_type == \"macro\"\n        precision = mean(TP ./ (TP .+ FP .+ eps(eltype(TP))))\n        recall = mean(TP ./ (TP .+ FN .+ eps(eltype(TP))))\n        f1_score = 2 * precision * recall / (precision + recall + eps(eltype(TP)))\n        specificity = mean(TN ./ (TN .+ FP .+ eps(eltype(TP))))\n        accuracy = categorical_accuracy(y_pred, y_true)\n        false_alarm_rate = 1 - specificity\n        return Dict(\"Confusion_Matrix\" => confusion_matrix_,\n                \"Precision\" => precision, \"Recall\" => recall,\n                \"Specificity\" => specificity, \"F1_score\" => f1_score,\n                \"Accuracy\" => accuracy, \"False_alarm_rate\" => false_alarm_rate)\n    elseif avg_type == \"micro\"\n        precision = mean(TP) / (mean(TP) + mean(FP))\n        recall = mean(TP) / (mean(TP) + mean(FN))\n        f1_score = 2 * precision * recall / (precision + recall + eps(eltype(TP)))\n        specificity = mean(TN)/ (mean(TN) + mean(FP))\n        accuracy = categorical_accuracy(y_pred, y_true)\n        false_alarm_rate = 1 - specificity\n        return Dict(\"Confusion_Matrix\" => confusion_matrix_,\n                \"Precision\" => precision, \"Recall\" => recall,\n                \"Specificity\" => specificity, \"F1_score\" => f1_score,\n                \"Accuracy\" => accuracy, \"False_alarm_rate\" => false_alarm_rate)\n    end\n    # TODO: add weighted stats option as above functions\nend\n\n# TODO\n# Concordance and Discordance\n    \n# Receiver Operating Characterstic (ROC) Curve\n\n# AUC\n\n\n\n\n\n\n", "meta": {"hexsha": "e04f7bb552016c9b0e7887de5a1b6e0a8c6a364d", "size": 15214, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Classification.jl", "max_stars_repo_name": "yuehhua/Metrics.jl", "max_stars_repo_head_hexsha": "6dc6fd6155afe551dd6424debdf7f034e68acb29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-06-02T14:09:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T00:08:26.000Z", "max_issues_repo_path": "src/Classification.jl", "max_issues_repo_name": "yuehhua/Metrics.jl", "max_issues_repo_head_hexsha": "6dc6fd6155afe551dd6424debdf7f034e68acb29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-12-22T06:28:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T02:47:49.000Z", "max_forks_repo_path": "src/Classification.jl", "max_forks_repo_name": "yuehhua/Metrics.jl", "max_forks_repo_head_hexsha": "6dc6fd6155afe551dd6424debdf7f034e68acb29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-13T11:32:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T06:04:19.000Z", "avg_line_length": 38.7124681934, "max_line_length": 316, "alphanum_fraction": 0.6695149205, "num_tokens": 4116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.762327382285616}}
{"text": "\"\"\"\n    Bounds.Ellipsoid([T=Float64], N)\n    Bounds.Ellipsoid(center::AbstractVector, A::AbstractMatrix)\n\nAn `N`-dimensional ellipsoid defined by\n\n```math\n(x - center)^T A (x - center) = 1\n```\n\nwhere `size(center) == (N,)` and `size(A) == (N,N)`.\n\nThis implementation follows the algorithm presented in Mukherjee et al. (2006).[^2]\n\n[^2]: Pia Mukherjee, et al., 2006, ApJ 638 L51 [\"A Nested Sampling Algorithm for Cosmological Model Selection\"](https://iopscience.iop.org/article/10.1086/501068)\n\"\"\"\nmutable struct Ellipsoid{T} <: AbstractBoundingSpace{T}\n    center::Vector{T}\n    A::Matrix{T}\n    axes::Matrix{T}\n    axlens::Vector{T}\n    volume::T\nend\n\n\nfunction Ellipsoid(center::AbstractVector, A::AbstractMatrix)\n    axes, axlens = decompose(A)\n    Ellipsoid(center, A, axes, axlens, _volume(A))\nend\nEllipsoid(ndim::Integer) = Ellipsoid(Float64, ndim)\nEllipsoid(T::Type, ndim::Integer) = Ellipsoid(zeros(T, ndim), diagm(0 => ones(T, ndim)))\nEllipsoid{T}(center::AbstractVector, A::AbstractMatrix) where {T} = Ellipsoid(T.(center), T.(A))\n\nBase.broadcastable(e::Ellipsoid) = (e,)\n\nBase.ndims(ell::Ellipsoid) = length(ell.center)\n\n# Returns the volume of an ellipsoid given its axes matrix\n_volume(A::AbstractMatrix{T}) where {T} = T(volume_prefactor(size(A, 1))) / sqrt(det(A))\nvolume(ell::Ellipsoid) = ell.volume\n\n# Returns the principal axes\naxes(ell::Ellipsoid) = ell.axes\n\ndecompose(A::AbstractMatrix) = decompose(Symmetric(A))  # ensure that eigen() always returns real values\n\nfunction decompose(A::Symmetric)\n    E = eigen(A)\n    axlens = @. 1 / sqrt(E.values)\n    axes = E.vectors * Diagonal(axlens)\n    return axes, axlens\nend\n\n# axes and axlens\ndecompose(ell::Ellipsoid) = ell.axes, ell.axlens\n\n# Scale to new volume\nfunction scale!(ell::Ellipsoid, factor)\n    # linear factor\n    f = factor^(1 / ndims(ell))\n    ell.A ./= f^2\n    ell.axes .*= f\n    ell.axlens .*= f\n    ell.volume *= factor\n    return ell\nend\n\nfunction endpoints(ell::Ellipsoid)\n    axes, axlens = decompose(ell)\n        # find major axis\n    major_axis = axes[:, argmax(axlens)]\n    return ell.center .- major_axis, ell.center .+ major_axis\nend\n\nfunction Base.in(x::AbstractVector, ell::Ellipsoid)\n    d = x .- ell.center\n    return dot(d, ell.A * d) ≤ 1.0\nend\n\nrandoffset(rng::AbstractRNG, ell::Ellipsoid{T}) where {T} = axes(ell) * randball(rng, T, ndims(ell))\nBase.rand(rng::AbstractRNG, ell::Ellipsoid) = ell.center .+ randoffset(rng, ell)\n\nfit(E::Type{<:Ellipsoid}, x::AbstractMatrix{S}; pointvol = 0) where {S} = fit(E{float(S)}, x; pointvol = pointvol)\n\nfunction fit(E::Type{<:Ellipsoid{R}}, x::AbstractMatrix{S}; pointvol = 0) where {R,S}\n    T = float(promote_type(R, S))\n    x = T.(x)\n    ndim, npoints = size(x)\n\n    # single element is an n-sphere with pointvol volume\n    if npoints == 1\n        pointvol > 0 || error(\"Cannot compute bounding ellipsoid with one point without a valid pointvol (got $pointvol)\")\n        d = log(pointvol) - log(volume_prefactor(ndim))\n        r = exp(d / ndim)\n        A = diagm(0 => fill(1 / r^2, ndim))\n        return Ellipsoid(vec(x), A)\n    end\n    # get estimators\n    center, cov = mean_and_cov(x, 2)\n    delta = x .- center\n    # Covariance is smaller than r^2 by a factor of 1/(n+2)\n    cov .*= ndim + 2\n    # Ensure cov is nonsingular\n    targetprod = (npoints * pointvol / volume_prefactor(ndim))^2\n    make_eigvals_positive!(cov, targetprod)\n\n    # get transformation matrix. Note: use pinv to avoid error when cov is all zeros\n    A = pinv(cov)\n\n    # calculate expansion factor necessary to bound each points\n    f = diag(delta' * (A * delta))\n    fmax = maximum(f)\n\n    # try to avoid round-off errors s.t. furthest point obeys\n    # x^T A x < 1 - √eps\n    flex = 1 - sqrt(eps(T))\n    if fmax > flex\n        A .*= flex / fmax\n    end\n\n    ell = E(vec(center), A)\n\n    if pointvol > 0\n        minvol = npoints * pointvol\n        vol = volume(ell)\n        vol < minvol && scale!(ell, minvol / vol)\n    end\n\n    return ell\nend\n\n\n# ---------------------------------------------\n# Helper functions\n\n\"\"\"\n    volume_prefactor(::Integer)\n\nVolume constant for an n-dimensional sphere:\n\nfor n even:      (2pi)^(n    /2) / (2 * 4 * ... * n)\nfor n odd :  2 * (2pi)^((n-1)/2) / (1 * 3 * ... * n)\n\"\"\"\nfunction volume_prefactor(n::Integer)\n    f, range = iseven(n) ? (1.0, 2:2:n) : (2.0, 3:2:n)\n    for i in range\n        f *= 2π / i\n    end\n    return f\nend\n\n# sample N samples from unit D-dimensional ball\nrandball(T::Type, D::Integer, N::Integer) = randball(GLOBAL_RNG, T, D, N)\nfunction randball(rng::AbstractRNG, T::Type, D::Integer, N::Integer)\n    z = randn(rng, T, D, N)\n    z .*= rand(rng, T, 1, N).^(1 ./ D) ./ sqrt.(sum(p->p^2, z, dims = 1))\n    return z\nend\n\n# sample from unit D-dimensional ball\nrandball(T::Type, D::Integer) = randball(GLOBAL_RNG, T, D)\nfunction randball(rng::AbstractRNG, T::Type, D::Integer)\n    z = randn(rng, T, D)\n    z .*= rand(rng)^(1 / D) / sqrt(sum(p->p^2, z))\n    return z\nend\n\nfunction make_eigvals_positive!(cov::AbstractMatrix, targetprod)\n    E = eigen(cov)\n    mask = E.values .< 1e-10\n    if any(mask)\n        nzprod = prod(E.values[.!mask])\n        nzeros = count(mask)\n        E.values[mask] .= (targetprod / nzprod)^(1 / nzeros)\n        cov .= E.vectors * Diagonal(E.values) / E.vectors\n    end\n    return cov\nend\n\nmake_eigvals_positive(cov::AbstractMatrix, targetprod) = make_eigvals_positive!(copy(cov), targetprod)\n", "meta": {"hexsha": "0eeaa649b4f43330452dcc3d5d529018b2d47a58", "size": 5396, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bounds/ellipsoid.jl", "max_stars_repo_name": "mileslucas/NestedSamplers", "max_stars_repo_head_hexsha": "d84341036163fc3ea9d9908111669bab1b10da12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-12-12T22:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-25T13:17:34.000Z", "max_issues_repo_path": "src/bounds/ellipsoid.jl", "max_issues_repo_name": "mileslucas/NestedSamplers", "max_issues_repo_head_hexsha": "d84341036163fc3ea9d9908111669bab1b10da12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bounds/ellipsoid.jl", "max_forks_repo_name": "mileslucas/NestedSamplers", "max_forks_repo_head_hexsha": "d84341036163fc3ea9d9908111669bab1b10da12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-09T05:03:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-09T05:03:24.000Z", "avg_line_length": 29.8121546961, "max_line_length": 162, "alphanum_fraction": 0.6328762046, "num_tokens": 1699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.7623273816979715}}
{"text": "@syms 𝑥\n@polyvar 𝑦\n\nfunction poly(eq, v::Pair)\n    α, β = value(first(v)), last(v)\n    terms = collect_powers(eq, α)\n\n    if !all(isone, denominator.(collect(keys(terms))))\n        error(\"fractional power not supported\")\n    end\n\n    sum([val*β^numerator(k) for (k,val) in terms]; init=0)\nend\n\nfunction poly(eq, β)\n    xs = get_variables(eq)\n\n    if length(xs) > 1\n        error(\"more than one implicit variable.\")\n    elseif length(xs) == 0\n        return nothing\n    else\n        return poly(eq, xs[1] => β)\n    end\nend\n\npoly(eq) = poly(eq, 𝑦)\n\nfunction sym(p::AbstractPolynomialLike, v::Pair)\n    β, α = first(v), value(last(v))\n    sum([α^maxdegree(t,β)*c for (t,c) in zip(terms(p), coefficients(p))]; init=0)\nend\n\nsym(p::AbstractPolynomialLike, α) = sym(p, var(p) => α)\nsym(p::AbstractPolynomialLike) = sym(p, var(p) => 𝑥)\n\n###############################################################################\n\n# pox (power-of-x) is a symbolic function to keep track of the powers of x\n# pox(k,n) means k*x^n\n@syms pox(k, n)\n\nis_pox(x) = istree(x) && operation(x)==pox\nis_not_pox(x) = !is_pox(x)\n\nget_coef(p) = is_pox(p) ? arguments(p)[1] : p\nget_power(p) = is_pox(p) ? arguments(p)[2] : 0\n\nreplace_x(eq, x) = substitute(eq, Dict(x => pox(1,1)))\n\niscomplex(x) = x isa Complex\n\ncount_rule1 = @rule ^(pox(~k, ~n1), ~n2) => isequal(~k,1) ? pox(1, ~n1 * ~n2) : pox(^(~k,~n2), ~n1 * ~n2)\ncount_rule2 = @rule pox(~k1, ~n1) * pox(~k2, ~n2) => pox(~k1 * ~k2, ~n1 + ~n2)\ncount_rule3 = @acrule pox(~k, ~n) * ~u::is_not_pox => pox(~k * ~u, ~n)\n\n\"\"\"\n    collect_powers separates the powers of x in eq (a polynomial) and returns\n    a dictionary of power => term\n\"\"\"\nfunction collect_powers(eq, x)\n    eq = expand(expand_derivatives(eq))\n    eq = replace_x(eq, x)\n    #eq = Prewalk(PassThrough(count_rule1))(eq)\n    eq = Fixpoint(Prewalk(PassThrough(Chain([count_rule1, count_rule2, count_rule3]))))(eq)\n\n    if !istree(eq)\n        return Dict{Any, Any}(0 => eq)\n    elseif is_pox(eq)\n        return Dict{Any, Any}(get_power(eq) => get_coef(eq))\n    else\n        eqs = Dict{Any, Any}()\n        for term in arguments(eq)\n            n = get_power(term)\n            if haskey(eqs, n)\n                eqs[n] = eqs[n] + get_coef(term)\n            else\n                eqs[n] = get_coef(term)\n            end\n        end\n\n        return eqs\n    end\nend\n", "meta": {"hexsha": "20e88ed3e95740b8729a370b3a9b97d8fd157830", "size": 2334, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/symbolics.jl", "max_stars_repo_name": "AlCap23/SymPoly.jl", "max_stars_repo_head_hexsha": "274d9e46a548989bd7665318838743613617a7e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-06-20T06:30:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:10:37.000Z", "max_issues_repo_path": "src/symbolics.jl", "max_issues_repo_name": "AlCap23/SymPoly.jl", "max_issues_repo_head_hexsha": "274d9e46a548989bd7665318838743613617a7e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-03T09:34:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-03T09:34:38.000Z", "max_forks_repo_path": "src/symbolics.jl", "max_forks_repo_name": "AlCap23/SymPoly.jl", "max_forks_repo_head_hexsha": "274d9e46a548989bd7665318838743613617a7e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-01T16:59:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T16:59:06.000Z", "avg_line_length": 27.4588235294, "max_line_length": 105, "alphanum_fraction": 0.5668380463, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7623273726872427}}
{"text": "\"\"\"\n    Xtal._is_linearly_independent(vecs::AbstractMatrix{<:Number}) -> Bool\n    Xtal._is_linearly_independent(vecs::AbstractVector{<:Number}...) -> Bool\n\nDetermines whether a set of vectors is linearly independent.\n\nThis function always returns `false` if the first dimension of the matrix is less than the second.\n\"\"\"\nfunction is_linearly_independent(vecs::AbstractMatrix{<:Number})\n    size(vecs)[1] < size(vecs)[2] || return false\n    return LinearAlgebra.rank(vecs) == minimum(size(vecs))\nend\n\n# Same thing but for sets of vectors\nfunction is_linearly_independent(vecs::AbstractVector{<:Number}...)\n    return is_linearly_independent(hcat(vecs...))\nend\n\n#=\n\"\"\"\n    _to_vectors(a::AbstractArray{T,N}) where {T,N} -> Vector{...Vector{T}}\n\nConverts an array to a nest of vectors within vectors.\n\"\"\"\nfunction _to_vectors(a::AbstractArray{T,N}) where {T,N}\n    \nend\n=#", "meta": {"hexsha": "913046a6d6f3032130d341b62f4cfd98bb542ba9", "size": 869, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vectors.jl", "max_stars_repo_name": "brainandforce/Xtal.jl", "max_stars_repo_head_hexsha": "0f547f8d291ee6deb3bdff3ae00ba07510cda10a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/vectors.jl", "max_issues_repo_name": "brainandforce/Xtal.jl", "max_issues_repo_head_hexsha": "0f547f8d291ee6deb3bdff3ae00ba07510cda10a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-30T05:38:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T05:38:09.000Z", "max_forks_repo_path": "src/vectors.jl", "max_forks_repo_name": "brainandforce/Xtal.jl", "max_forks_repo_head_hexsha": "0f547f8d291ee6deb3bdff3ae00ba07510cda10a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0357142857, "max_line_length": 98, "alphanum_fraction": 0.7249712313, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.762327372569714}}
{"text": "#=\n\n   The Euro coin problem.\n\n   From Think Bayes, page 33ff\n   \"\"\"\n   A statistical statement appeared in \"The Guardian\" on Friday January 4, 2002:\n      When spun on edge 250 times, a Belgian one-euro coin\n      came up heads 140 times and tails 110. 'It looks very\n      suspicious to me,' said Barry Blight, a statistics lecturer\n      at the London School of Economics. 'If the coin were\n      unbiased, the chance of getting a result as extreme as\n      that would be less than 7%.'\n\n   But do these data give evidence that the coin is biased rather than fair?\n   \"\"\"\n\n   Continues on page 41:\n   \"\"\"\n   Exercise 4.1. Suppose that instead of observing coin tosses directly, you measure\n   the outcome using an instrument that is not always correct. Specifically, suppose\n   there is a probability y that an actual heads is reported as tails, or actual tails re-\n   ported as heads.\n\n   Write a class that estimates the bias of a coin given a series of outcomes and the\n   value of y .\n   How does the spread of the posterior distribution depend on y ?\n   \"\"\"\n\n   mean(prob): 0.5213151098904925\n   Distributions of variable probLt0_5 (num:0)\n   0.00000 =>    7020  (0.702000)\n   1.00000 =>    2980  (0.298000)\n\n   Distributions of variable error (num:0)\n   0.00000 =>    7051  (0.705100)\n   1.00000 =>    2949  (0.294900)\n\n\n   Cf euro_coin_problem.jl\n   Cf ~/blog/euro_coin_unreliable_measurements.blog\n      ~/webppl/euro_coin_unreliable_measurements.wppl\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n@model function euro_coin_problem_unreliable_measurements()\n    n = 250\n    \n    # Probability of throwing head\n    prob ~ Beta(2,2)\n    \n    # We measure incorrect with probability 0.2\n    error ~ flip(0.2)\n    \n    throwCoin ~ filldist(flip(prob),n)\n    \n    coin = tzeros(n)\n    for i in 1:n\n        coin[i] ~ Dirac(error == true ? 1-throwCoin[i] : throwCoin[i])\n    end\n    \n    sum250 ~ Dirac(sum([coin[i] == true ? 1 : 0 for i in 1:n]))\n    true ~ Dirac(sum250 == 140)\n    probLt0_5 ~ Dirac(prob < 0.5)\n    \nend\n\nmodel = euro_coin_problem_unreliable_measurements()\n\nnum_chains = 4\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(5), 10_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 10_000)\n\ndisplay(chns)\n# display(plot(chns))\n\nprintln(\"mean(prob): \", mean(chns[:prob]))\nshow_var_dist_pct(chns, :probLt0_5)\nshow_var_dist_pct(chns, :error)\n\n    \n", "meta": {"hexsha": "2f2526434c64d17a37797d588a41b7877383c10f", "size": 2459, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/euro_coin_problem_unreliable_measurements.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/euro_coin_problem_unreliable_measurements.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/euro_coin_problem_unreliable_measurements.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 27.9431818182, "max_line_length": 90, "alphanum_fraction": 0.6742578284, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361628580401, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7623254002010438}}
{"text": "# # Approximate Inference on Sparse GPs using VI\n\n# Loading the necessary packages and setting seed.\n\nusing AbstractGPs, Plots, Random\nRandom.seed!(1234);\n\n# Loading toy regression \n# [dataset](https://github.com/GPflow/docs/blob/master/doc/source/notebooks/basics/data/regression_1D.csv) \n# taken from GPFlow examples.\n\nx = [0.8658165855998895, 0.6661700880180962, 0.8049218148148531, 0.7714303440386239, \n    0.14790478354654835, 0.8666105548197428, 0.007044577166530286, 0.026331737288148638, \n    0.17188596617099916, 0.8897812990554013, 0.24323574561119998, 0.028590102134105955];\ny = [1.5255314337144372, 3.6434202968230003, 3.010885733911661, 3.774442382979625, \n    3.3687639483798324, 1.5506452040608503, 3.790447985799683, 3.8689707574953, \n    3.4933565751758713, 1.4284538820635841, 3.8715350915692364, 3.7045949061144983];\nscatter(x, y, xlabel=\"x\", ylabel=\"y\")\n\n# Split the observations into train and test set.\n\n(x_train, y_train) = (x[begin:8], y[begin:8]);\n(x_test, y_test) = (x[9:end], y[9:end]);\n\n# Instantiate the kernel.\n\nk = Matern52Kernel()\n\n# Instantiate a Gaussian Process with the given kernel `k`.\n\nf = GP(k);\n\n# Instantiate a `FiniteGP`, a finite dimentional projection at the inputs of the dataset \n# observed under Gaussian Noise with $\\sigma = 0.001$ .\n\nfx = f(x_train, 0.001);\n\n# Calculating the exact posterior over `f` given `y`. The GP's kernel currently has some \n# arbitrary fixed parameters. \n\np_fx = posterior(fx, y_train)\n\nlogpdf(p_fx(x_test), y_test)\n\n# ## Variational Inference\n\n# Sanity check for the Evidence Lower BOund (ELBO) implemented according to \n# M. K. Titsias's _Variational learning of inducing variables in sparse Gaussian processes_\n\nelbo(fx, y_train, f(rand(7)))\n\n# We will be using `Optim.jl` package's `LBFGS` algorithm to maximize the given ELBO.\n\nusing Optim\n\n# Create a helper function for optimization. It takes in the parameters (both variational \n# and model parameters) and returns the negative of the ELBO.  \n\nfunction optim_function(params; x=x_train, y=y_train)\n    kernel = ScaledKernel(\n        transform(\n            Matern52Kernel(), \n            ScaleTransform(exp.(params[1]))\n            ), \n        exp.(params[2])\n    )\n    f = GP(kernel)\n    fx = f(x, 0.1)\n    return -elbo(fx, y, f(params[3:end]))\nend\n\n# Initialize the parameters (Varitational and Model parameters)\nx0 = rand(7)\n\n# Sanity check for the helper function. We intend to minimize the result of this function.\n\n-optim_function(x0)\n\n# Optimize using `Optim.jl` package's `LBFGS` algorithm.\n\nopt = optimize(optim_function, x0, LBFGS())\n\n# Optimal parameters:\n\nopt.minimizer\n\n# ELBO with optimal parameters. We see that there is significant improvement when compared \n# to the initial parameters.\n\n-optim_function(opt.minimizer; x=x_test, y=y_test)\n\n# Visualize the posterior.\n\nopt_kernel = ScaledKernel(\n    transform(\n        Matern52Kernel(), \n        ScaleTransform(exp.(opt.minimizer[1]))\n        ), \n    exp.(opt.minimizer[2])\n)\nopt_f = GP(opt_kernel)\nopt_fx = opt_f(x_train, 0.1)\nap = approx_posterior(VFE(), opt_fx, y_train, opt_f(opt.minimizer[3:end]));\n\n# Average log-marginal-probability of data with posterior kernel parameter samples sampled \n# using ESS. We can observe that there is significant improvement over exact posterior with \n# default kernel parameters.\n\nlogpdf(ap(x_test), y_test)\n\nplt = plot(ap, 0:0.001:1, label=\"Approx Posterior\")\nplot!(plt, p_fx, 0:0.001:1, label=\"Exact Posterior\")\nscatter!(\n    plt, \n    opt.minimizer[3:end], \n    mean(rand(ap(opt.minimizer[3:end], 0.1), 100), dims=2), \n    label=\"Pseudo-points\"\n)\nscatter!(plt, x_train, y_train, label=\"Train Data\")\nscatter!(plt, x_test, y_test, label=\"Test Data\")\nplt\n\n\n", "meta": {"hexsha": "b64598c5e422ccebb2c57438473ddd1e2c79eb50", "size": 3694, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/VariationalInference.jl", "max_stars_repo_name": "yiyuezhuo/AbstractGPs.jl", "max_stars_repo_head_hexsha": "23b7581849384c1f283e510c7394e033377d720b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-14T18:07:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-14T18:07:15.000Z", "max_issues_repo_path": "examples/VariationalInference.jl", "max_issues_repo_name": "cscherrer/AbstractGPs.jl", "max_issues_repo_head_hexsha": "19c63ac7345d55531d7ed9f5789c82151dd7d8e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/VariationalInference.jl", "max_forks_repo_name": "cscherrer/AbstractGPs.jl", "max_forks_repo_head_hexsha": "19c63ac7345d55531d7ed9f5789c82151dd7d8e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7903225806, "max_line_length": 107, "alphanum_fraction": 0.7203573362, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7623253887469853}}
{"text": "\"\"\"\n\ttransferoperator_exact(t::AbstractTriangulation)\n\nCompute the transfer operator from a triangulation.\n\"\"\"\nfunction transferoperator_exact(t::AbstractTriangulation)\n    n_simplices = size(t.simplex_inds, 1)\n    dim = size(t.points, 2)\n\n    #=\n    Mismatch for the markovity of the Markov matrix is at most δ if ϵ tolerance\n\tas below\n    =#\n    δ::Float64 = 1/10^5\n    ϵ::Float64 = δ/n_simplices\n\n    #=\n    Tolerance for similary of convex expansion coefficients of simplex vertices in\n    simplexintersection function.\n    =#\n    convex_params_tol::Float64 = 1/10^12\n\n    TO = zeros(Float64, n_simplices, n_simplices) # intersecting volumes\n\n    for i in 1:n_simplices\n        imvol = t.volumes_im[i]\n        for j in 1:n_simplices\n            vol = t.volumes[j]\n            if vol * imvol > 0 && (vol/imvol) > ϵ\n                # Intersecting volume between these two simplices\n                TO[i, j] = simplexintersection(\n                                transpose(t.points[t.simplex_inds[j, :], :]),\n                                transpose(t.impoints[t.simplex_inds[i, :], :])\n                            ) / imvol\n            end\n        end\n    end\n    return ExactSimplexTransferOperator(TO)\nend\n\n\"\"\"\n    transferoperator_exact_p(t::AbstractTriangulation)\n\nEstimate the transfer operator from a triangulation of a state space.\nWill run in parallel if `nprocs() > 1`.\n\"\"\"\nfunction transferoperator_exact_p(t::AbstractTriangulation)\n\n    n_simplices = size(t.simplex_inds, 1)\n    dim = size(t.points, 2)\n\n    #=\n    Mismatch for the markovity of the Markov matrix is at most δ if ϵ\n    tolerance as below.\n    =#\n    δ::Float64 = 1/10^5\n    ϵ::Float64 = δ/n_simplices\n\n    #=\n    Tolerance for similary of convex expansion coefficients of simplex vertices\n    in simplexintersection function.\n    =#\n    convex_params_tol::Float64 = 1/10^12\n\n    TO = SharedArray{Float64}(n_simplices, n_simplices)\n\n    @sync @distributed for i in 1:n_simplices\n        imvol = t.volumes_im[i]\n        for j in 1:n_simplices\n            vol = t.volumes[j]\n            if vol * imvol > 0 && (vol/imvol) > ϵ\n                # Intersecting volume between these two simplices\n                TO[i, j] = simplexintersection(\n                                transpose(t.points[t.simplex_inds[j, :], :]),\n                                transpose(t.impoints[t.simplex_inds[i, :], :])\n                            ) / imvol\n            end\n        end\n    end\n\n    return ExactSimplexTransferOperator(Array(TO))\nend\n\n\ntransferoperator_triang_exact = transferoperator_exact\nexport transferoperator_triang_exact\n", "meta": {"hexsha": "dd3fbc7ce373a7a29fa91668f2d6553e8b512517", "size": 2597, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/old_stuff/simplexestimators/exact.jl", "max_stars_repo_name": "JuliaTagBot/PerronFrobenius.jl", "max_stars_repo_head_hexsha": "94e114cce8fcce52ac4f9b529aafa2555d87ee97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/old_stuff/simplexestimators/exact.jl", "max_issues_repo_name": "JuliaTagBot/PerronFrobenius.jl", "max_issues_repo_head_hexsha": "94e114cce8fcce52ac4f9b529aafa2555d87ee97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/old_stuff/simplexestimators/exact.jl", "max_forks_repo_name": "JuliaTagBot/PerronFrobenius.jl", "max_forks_repo_head_hexsha": "94e114cce8fcce52ac4f9b529aafa2555d87ee97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8505747126, "max_line_length": 82, "alphanum_fraction": 0.613400077, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7623183890104629}}
{"text": "#=\n   Logistic regresiion\n   Inspired by WebPPL's examples/logisticRegression.wppl\n\n   Summary Statistics (for PG(15))\n      parameters       mean       std   naive_se      mcse         ess      rhat   ess_per_sec \n          Symbol    Float64   Float64    Float64   Float64     Float64   Float64       Float64 \n\n               m     1.0844    0.5870     0.0059    0.0077   6361.4279    1.0009      153.4390\n               b     0.1315    0.9292     0.0093    0.0111   6431.4331    0.9999      155.1275\n           sigma     0.8779    0.8513     0.0085    0.0107   6452.7250    0.9999      155.6411\n            y[1]   -10.7253    6.0611     0.0606    0.0801   6408.9867    1.0008      154.5861\n            y[2]    -5.3599    3.2295     0.0323    0.0439   6465.7579    1.0007      155.9555\n            y[3]     2.5165    1.7809     0.0178    0.0200   6562.8112    1.0010      158.2964\n            y[4]     6.6892    3.7534     0.0375    0.0454   6516.1303    1.0008      157.1705\n            y[5]    11.0158    5.9711     0.0597    0.0746   6263.6413    1.0010      151.0804\n  labels_post[1]     0.0163    0.1266     0.0013    0.0013   8339.5233    0.9999      201.1511\n  labels_post[2]     0.0552    0.2284     0.0023    0.0026   8486.3592    1.0001      204.6928\n  labels_post[3]     0.8459    0.3611     0.0036    0.0041   8013.9274    1.0001      193.2977\n  labels_post[4]     0.9707    0.1687     0.0017    0.0018   8543.2209    1.0002      206.0643\n  labels_post[5]     0.9873    0.1120     0.0011    0.0012   9349.4013    0.9999      225.5096\n\n  The labels_post are the posterior predictive and are fairly close to labels values: [0, 0, 1, 1, 1]\n\n=#\n\nusing Turing, StatsPlots, DataFrames\n\ninclude(\"jl_utils.jl\")\n\n@model function logistic_regression(x, labels)\n    m ~ Normal(0, 1)\n    b ~ Normal(0, 1)\n    sigma ~ Gamma(1, 1)\n\n    n = length(x)\n    y = tzeros(n)\n    sigmoid = tzeros(n)\n    for i in 1:n\n        y[i] ~ Normal(m * x[i] + b, sigma)\n        sigmoid[i] = 1 / (1 + exp(-1 * y[i]))\n        labels[i] ~ Bernoulli(sigmoid[i])\n    end\n\n    # Post predictive of labels\n    labels_post = tzeros(n)\n    for i in 1:n\n        labels_post[i] ~ Bernoulli(sigmoid[i])\n    end\nend\n\nxs = [-10, -5, 2, 6, 10]\nlabels = [0, 0, 1, 1, 1]\nmodel = logistic_regression(xs,labels)\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(15), 10_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 10_000)\n\ndisplay(chns)\n", "meta": {"hexsha": "e2d921bf750956c2b170bd52625b5dee65af52c9", "size": 2479, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/logistic_regression.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/logistic_regression.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/logistic_regression.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 39.3492063492, "max_line_length": 101, "alphanum_fraction": 0.5433642598, "num_tokens": 1037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.7623183741395461}}
{"text": "module _K2En\nexport K2En\nusing Statistics: std\n    \"\"\"\n        K2, Ci = K2En(Sig) \n        \n    Returns the Kolmogorov entropy estimates `K2` and the correlation\n    integrals `Ci` for `m` = [1,2] estimated from the data sequence `Sig`\n    using the default parameters: embedding dimension = 2, time delay = 1, \n    r = 0.2*SD(`Sig`), logarithm = natural\n\n        K2, Ci = K2En(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Real=0.2*std(Sig,corrected=false), Logx::Real=exp(1))\n        \n    Returns the Kolmogorov entropy estimates `K2` for dimensions = [1,...,`m`]\n    estimated from the data sequence `Sig` using the 'keyword' arguments:\n\n    # Arguments:\n    `m`     - Embedding Dimension, a positive integer\\n\n    `tau`   - Time Delay, a positive integer\\n\n    `r`     - Radius, a positive scalar \\n \n    `Logx`  - Logarithm base, a positive scalar\\n  \n\n    # See also `DistEn`, `XK2En`, `MSEn`\n\n    # References:\n        [1] Peter Grassberger and Itamar Procaccia,\n            \"Estimation of the Kolmogorov entropy from a chaotic signal.\" \n            Physical review A 28.4 (1983): 2591.\n\n        [2] Lin Gao, Jue Wang  and Longwei Chen\n            \"Event-related desynchronization and synchronization \n            quantification in motor-related EEG by Kolmogorov entropy\"\n            J Neural Eng. 2013 Jun;10(3):03602\n\n    \"\"\"\n    function K2En(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Real=0.2*std(Sig,corrected=false), Logx::Real=exp(1))\n\n    N = size(Sig)[1]\n    (N>10) ? nothing : error(\"Sig:   must be a numeric vector\")\n    (m > 0) ? nothing : error(\"m:     must be an integer > 0\")\n    (tau > 0) ? nothing : error(\"tau:   must be an integer > 0\")\n    (r>0) ? nothing :  error(\"r:     must be a positive scalar > 0\")\n    (Logx>0) ? nothing :  error(\"Logx:     must be a positive number > 0\")\n        \n    m = m+1\n    Zm = zeros(N,m)\n    Ci = zeros(m)\n    for n = 1:m\n        N2 = N-(n-1)*tau\n        Zm[1:N2,n] = Sig[(n-1)*tau + 1:N]   \n        Norm = Inf*ones(N2-1,N2-1)\n        for k = 1:N2-1\n            Temp = repeat(transpose(Zm[k,1:n]),N2-k,1) - Zm[k+1:N2,1:n]\n            Norm[k,k:N2-1] = sqrt.(sum(Temp.^2, dims=2)) \n        end\n        Ci[n] = 2*sum(Norm .< r)/(N2*(N2-1))    \n    end\n    \n    K2 = log.(Logx, Ci[1:m-1]./Ci[2:m])/tau\n    K2[isinf.(K2)] .= NaN\n\n    return K2, Ci\n    end\nend\n\n\"\"\"\nCopyright 2021 Matthew W. Flood, EntropyHub\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nFor Terms of Use see https://github.com/MattWillFlood/EntropyHub\n\"\"\"", "meta": {"hexsha": "302856f519aca639716b918d8bb11fc7d49f820f", "size": 2999, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/_K2En.jl", "max_stars_repo_name": "MattWillFlood/EntropyHub.jl", "max_stars_repo_head_hexsha": "d681c7fad3dbddaa708391b0afef1495c7dde20d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-06-19T19:20:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T16:13:41.000Z", "max_issues_repo_path": "src/_K2En.jl", "max_issues_repo_name": "MattWillFlood/EntropyHub.jl", "max_issues_repo_head_hexsha": "d681c7fad3dbddaa708391b0afef1495c7dde20d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-06-16T21:57:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T01:10:46.000Z", "max_forks_repo_path": "src/_K2En.jl", "max_forks_repo_name": "MattWillFlood/EntropyHub.jl", "max_forks_repo_head_hexsha": "d681c7fad3dbddaa708391b0afef1495c7dde20d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-15T05:41:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T05:41:21.000Z", "avg_line_length": 36.5731707317, "max_line_length": 139, "alphanum_fraction": 0.6158719573, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8080672204860317, "lm_q1q2_score": 0.7622882500595697}}
{"text": "@doc raw\"\"\"\n    LogEuclideanMetric <: RiemannianMetric\n\nThe LogEuclidean Metric consists of the Euclidean metric applied to all elements after mapping them\ninto the Lie Algebra, i.e. performing a matrix logarithm beforehand.\n\"\"\"\nstruct LogEuclideanMetric <: RiemannianMetric end\n\n@doc raw\"\"\"\n    distance(M::MetricManifold{SymmetricPositiveDefinite{N},LogEuclideanMetric}, p, q)\n\nCompute the distance on the [`SymmetricPositiveDefinite`](@ref) manifold between\n`p` and `q` as a [`MetricManifold`](@ref) with [`LogEuclideanMetric`](@ref).\nThe formula reads\n\n```math\n    d_{\\mathcal P(n)}(p,q) = \\lVert \\operatorname{Log} p - \\operatorname{Log} q \\rVert_{\\mathrm{F}}\n```\n\nwhere $\\operatorname{Log}$ denotes the matrix logarithm and\n$\\lVert\\cdot\\rVert_{\\mathrm{F}}$ denotes the matrix Frobenius norm.\n\"\"\"\nfunction distance(\n    M::MetricManifold{ℝ,SymmetricPositiveDefinite{N},LogEuclideanMetric},\n    p,\n    q,\n) where {N}\n    return norm(log(Symmetric(p)) - log(Symmetric(q)))\nend\n", "meta": {"hexsha": "a0a1f7bc9a7b4bdd7663365a955082fcf85b1d7b", "size": 980, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/manifolds/SymmetricPositiveDefiniteLogEuclidean.jl", "max_stars_repo_name": "fkastner/Manifolds.jl", "max_stars_repo_head_hexsha": "1ea58949b3df9ff6bfa8bc3f63dd8368d7e98bd4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 174, "max_stars_repo_stars_event_min_datetime": "2020-03-29T16:50:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:19:15.000Z", "max_issues_repo_path": "src/manifolds/SymmetricPositiveDefiniteLogEuclidean.jl", "max_issues_repo_name": "fkastner/Manifolds.jl", "max_issues_repo_head_hexsha": "1ea58949b3df9ff6bfa8bc3f63dd8368d7e98bd4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 305, "max_issues_repo_issues_event_min_datetime": "2020-03-20T17:31:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:36:57.000Z", "max_forks_repo_path": "src/manifolds/SymmetricPositiveDefiniteLogEuclidean.jl", "max_forks_repo_name": "fkastner/Manifolds.jl", "max_forks_repo_head_hexsha": "1ea58949b3df9ff6bfa8bc3f63dd8368d7e98bd4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2020-03-31T13:15:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T01:43:30.000Z", "avg_line_length": 32.6666666667, "max_line_length": 99, "alphanum_fraction": 0.7326530612, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.943347579470196, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7622882477740645}}
{"text": "\nusing  ForwardDiff,GenericLinearAlgebra,LinearAlgebra\n\nmutable struct svdmat\n    U::Any\n    S::Any\n    V::Any\nend\nexport svd_lowrank\n\nfunction svd_lowrank(A::Matrix, l::Int, q::Int)\n    #= note:: The implementation is based on the Algorithm 5.1 from\n    Halko et al, 2009.=#\n    Q = get_approximate_basis(A, l, q)\n    Q = conj(Q')\n    B = Q * A\n    U, S, V = svd(B)\n    V = conj(V')\n    U = Q * U\n    return svdmat(U, S, V)\nend\n\n\nfunction get_approximate_basis(A::Matrix, l::Int, q::Int)\n    #= note:: The implementation is based on the Algorithm 4.4 from\n    Halko et al, 2009. =#\n    m, n = size(A)\n    omega = randn(n, l)\n    Y = A * omega\n    Q, R = qr(Y)\n    Y_H = conj(Y')\n\n    for i = 1:q\n        Q, R = qr(Y_H * Q)\n        Q, R = qr(Y * Q)\n    end\n    return Q\nend", "meta": {"hexsha": "e0200676c8ff2527b9dc6fdd275375f2d0e46183", "size": 773, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SvdLowrank.jl", "max_stars_repo_name": "SamanthaWangdl/ReSparse", "max_stars_repo_head_hexsha": "d1a11886a4926e3b1dd25a8cc6d107d861cfbd96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SvdLowrank.jl", "max_issues_repo_name": "SamanthaWangdl/ReSparse", "max_issues_repo_head_hexsha": "d1a11886a4926e3b1dd25a8cc6d107d861cfbd96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SvdLowrank.jl", "max_forks_repo_name": "SamanthaWangdl/ReSparse", "max_forks_repo_head_hexsha": "d1a11886a4926e3b1dd25a8cc6d107d861cfbd96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3421052632, "max_line_length": 67, "alphanum_fraction": 0.5692108668, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993027, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7622882469862758}}
{"text": "\"\"\"\n```julia\nusing DifferentialEquations, Plots\nfunction lorenz!(du,u,p,t)\n du[1] = 10.0*(u[2]-u[1])\n du[2] = u[1]*(28.0-u[3]) - u[2]\n du[3] = u[1]*u[2] - (8/3)*u[3]\nend\n\nu0 = [1.0;0.0;0.0]\ntspan = (0.0,100.0)\nprob = ODEProblem(lorenz!,u0,tspan)\nsol = solve(prob)\nplot(sol)\n```\n\"\"\"\nmodule DifferentialEquations\n\n  using Reexport\n\n  @reexport using DiffEqBase\n  @reexport using DiffEqNoiseProcess\n  @reexport using RecursiveArrayTools\n\n  @reexport using SteadyStateDiffEq\n  @reexport using StochasticDiffEq\n  @reexport using OrdinaryDiffEq\n  @reexport using BoundaryValueDiffEq\n  using Sundials\n  @reexport using DelayDiffEq\n\n  @reexport using DiffEqCallbacks\n  @reexport using DiffEqJump\n\n  @reexport using DiffEqFinancial\n  @reexport using MultiScaleArrays\n  @reexport using DiffEqPhysics\n\n  @reexport using DimensionalPlotRecipes\n  @reexport using ParameterizedFunctions\n\n  using LinearAlgebra\n\n  import DiffEqBase: solve\n\n  include(\"default_solve.jl\")\n  include(\"default_arg_parsing.jl\")\n  include(\"ode_default_alg.jl\")\n  include(\"sde_default_alg.jl\")\n  include(\"dae_default_alg.jl\")\n  include(\"dde_default_alg.jl\")\n  include(\"discrete_default_alg.jl\")\n  include(\"rode_default_alg.jl\")\n  include(\"steady_state_default_alg.jl\")\n  include(\"bvp_default_alg.jl\")\n\nend # module\n", "meta": {"hexsha": "dcad1b485adcb0dfdc4e42b51b4d08a07c93467f", "size": 1276, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DifferentialEquations.jl", "max_stars_repo_name": "anandijain/DifferentialEquations.jl", "max_stars_repo_head_hexsha": "b19931bf5ce2bed8c3b2c2594d89e19505c9c35c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DifferentialEquations.jl", "max_issues_repo_name": "anandijain/DifferentialEquations.jl", "max_issues_repo_head_hexsha": "b19931bf5ce2bed8c3b2c2594d89e19505c9c35c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DifferentialEquations.jl", "max_forks_repo_name": "anandijain/DifferentialEquations.jl", "max_forks_repo_head_hexsha": "b19931bf5ce2bed8c3b2c2594d89e19505c9c35c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0, "max_line_length": 40, "alphanum_fraction": 0.7413793103, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7622882391587662}}
{"text": "#!/usr/bin/julia\n\n# Date: 21 August 2016\n# https://github.com/trizen\n\n# An efficient algorithm for computing factorial of a large number, modulus a larger number.\n# Algorithm from: http://stackoverflow.com/questions/9727962/fast-way-to-calculate-n-mod-m-where-m-is-prime\n\nfunction facmod(n::Int64, mod::Int64)\n\n    f = 1\n    for k in n+1:mod-1\n       f *= k\n       f %= mod\n    end\n\n    (-1 * invmod(f, mod) + mod) % mod\nend\n\nprintln(facmod(100_000_000, 100_000_037))\n", "meta": {"hexsha": "0b1b6889ff42d20af560f491a6009f5a5e523bde", "size": 468, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Math/modular_factorial.jl", "max_stars_repo_name": "trizen/julia-scripts", "max_stars_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-03-22T09:38:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T21:38:31.000Z", "max_issues_repo_path": "Math/modular_factorial.jl", "max_issues_repo_name": "trizen/julia-scripts", "max_issues_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/modular_factorial.jl", "max_forks_repo_name": "trizen/julia-scripts", "max_forks_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2857142857, "max_line_length": 107, "alphanum_fraction": 0.6688034188, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475699138559, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.762288235691578}}
{"text": "# Jonas August, 2/2022\n\n#=\nThis problem was asked by Two Sigma.\n\nUsing a function rand7() that returns an integer from 1 to 7 (inclusive) with uniform probability, implement a function rand5() that returns an integer from 1 to 5 (inclusive).\n=#\n\nrand7() = rand(1:7)\n\nfunction rand5()\n    x = 6\n    while x > 5  # Keep sampling uniformly on 1:7 until in range 1:5\n        x = rand7()\n    end\n    x\nend\n\nsample = [rand5() for _ in 1:50000]\n\n\" Calculate 5 bin histogram. \"\nfunction hist5(sample::Vector{Int})\n    h = zeros(Int, 5)\n    for x in sample\n        h[x] += 1\n    end\n    h\nend\n\n# Test uniformity of probability: All bins should have similar counts.\nprintln(hist5(sample))\n", "meta": {"hexsha": "2d65f11662bbe64e8e0bd1e77703c1cf73cd9bb6", "size": 679, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Random from random - Problem 71.jl", "max_stars_repo_name": "jonasaugust/daily-coding-problem-in-julia", "max_stars_repo_head_hexsha": "9d534a13f2a51a847187b4c2516561fc025e1608", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Random from random - Problem 71.jl", "max_issues_repo_name": "jonasaugust/daily-coding-problem-in-julia", "max_issues_repo_head_hexsha": "9d534a13f2a51a847187b4c2516561fc025e1608", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-01T16:28:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-01T16:28:59.000Z", "max_forks_repo_path": "Random from random - Problem 71.jl", "max_forks_repo_name": "jonasaugust/daily-coding-problem-in-julia", "max_forks_repo_head_hexsha": "9d534a13f2a51a847187b4c2516561fc025e1608", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.21875, "max_line_length": 176, "alphanum_fraction": 0.6597938144, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8791467706759583, "lm_q1q2_score": 0.7622516943317169}}
{"text": "### A Pluto.jl notebook ###\n# v0.11.14\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 9e38d21a-f785-11ea-1ce0-5d313a4e9a7e\nusing Pkg, DrWatson\n\n# ╔═╡ 9e393624-f785-11ea-077b-cb4f64059bb3\nbegin\n\t@quickactivate \"StatisticalRethinkingTuring\"\n\tusing StatisticalRethinking\nend\n\n# ╔═╡ 4e27a698-f785-11ea-1ded-a548d1953a14\nmd\"## Fig3.1t.jl\"\n\n# ╔═╡ 9e3b92a2-f785-11ea-090f-a78cbded0a8d\nbegin\n\tN = 10000\n\tp_grid = range(0, stop=1, length=N)\n\tprior = ones(length(p_grid))\n\tlikelihood = pdf.(Binomial.(9, p_grid), 6)\n\tposterior = likelihood .* prior\n\tposterior = posterior / sum(posterior)\n\tsamples = sample(p_grid, Weights(posterior), length(p_grid));\nend;\n\n# ╔═╡ 9e43adc0-f785-11ea-2b6a-f11004009094\nbegin\n\tp1 = scatter(samples, ylim=(0, 1), xlab=\"Sample number\",\n\t  ylab=\"Proportion water(p)\", leg=false)\n\tp2 = density(samples, xlim=(0.0, 1.0), ylim=(0.0, 3.0),\n\t  xlab=\"Proportion water (p)\",\n\t  ylab=\"Density\", leg=false)\nend;\n\n# ╔═╡ d13a98ea-f785-11ea-0cb5-e51b20ddcdac\nplot(p1, p2, layout=(1,2))\n\n# ╔═╡ 9e520366-f785-11ea-1d50-8f7ab0c29c9c\nmd\"## End of Fig3.1t.jl\"\n\n# ╔═╡ Cell order:\n# ╟─4e27a698-f785-11ea-1ded-a548d1953a14\n# ╠═9e38d21a-f785-11ea-1ce0-5d313a4e9a7e\n# ╠═9e393624-f785-11ea-077b-cb4f64059bb3\n# ╠═9e3b92a2-f785-11ea-090f-a78cbded0a8d\n# ╠═9e43adc0-f785-11ea-2b6a-f11004009094\n# ╠═d13a98ea-f785-11ea-0cb5-e51b20ddcdac\n# ╟─9e520366-f785-11ea-1d50-8f7ab0c29c9c\n", "meta": {"hexsha": "88a92cf8dff51c77013330f0a235228c87fec0a6", "size": 1366, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/Fig3.1t.jl", "max_stars_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_stars_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2020-10-01T23:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T11:48:45.000Z", "max_issues_repo_path": "notebooks/03/Fig3.1t.jl", "max_issues_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_issues_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-11-24T21:59:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T12:34:49.000Z", "max_forks_repo_path": "notebooks/03/Fig3.1t.jl", "max_forks_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_forks_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-11-30T18:25:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T06:59:27.000Z", "avg_line_length": 25.7735849057, "max_line_length": 62, "alphanum_fraction": 0.7159590044, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.8670357615200475, "lm_q1q2_score": 0.7622516760738834}}
{"text": "export eigen2x2\nfunction eigen2x2(A)\n\tTp = eltype(A)\n\ta = A[1, 1]; b = A[1, 2]; c = A[2, 1]; d = A[2, 2];\n\tT = tr(A); D = det(A);\n\n\tL₁ = T / 2 + sqrt((T^2 / 4) - D)\n\tL₂ = T / 2 - sqrt((T^2 / 4) - D)\n\tvalues = [L₁, L₂]\n\n\tglobal vectors = []\n\n\tif !iszero(c)\n\t\tpush!(vectors, [L₁ - d, c])\n\t\tpush!(vectors, [L₂ - d, c])\n\telseif !iszero(b)\n\t\tpush!(vectors, [b, L₁ - a])\n\t\tpush!(vectors, [b, L₂ - a])\n\telseif iszero(b) && iszero(c)\n\t\tpush!(vectors, [one(Tp), zero(Tp)])\n\t\tpush!(vectors, [zero(Tp), one(Tp)])\n\tend\n\n\treturn values, vectors\nend\n", "meta": {"hexsha": "528e010d44608ec46d94976ac244a4d4cb40f856", "size": 536, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Utilities/eigen2x2.jl", "max_stars_repo_name": "Goysa2/ARCTR.jl", "max_stars_repo_head_hexsha": "527772d3d25f0c7f45380bedd3060d720f5d0809", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utilities/eigen2x2.jl", "max_issues_repo_name": "Goysa2/ARCTR.jl", "max_issues_repo_head_hexsha": "527772d3d25f0c7f45380bedd3060d720f5d0809", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utilities/eigen2x2.jl", "max_forks_repo_name": "Goysa2/ARCTR.jl", "max_forks_repo_head_hexsha": "527772d3d25f0c7f45380bedd3060d720f5d0809", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6153846154, "max_line_length": 52, "alphanum_fraction": 0.5279850746, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.957912273285902, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7621706617105952}}
{"text": "using LinearAlgebra\n\nfunction polar_force(force,angle)\n    return force.*[sin(deg2rad(angle)), cos(deg2rad(angle))]\nend\n\nfunction moments(forces, locations)\n    sum = zeros(3)\n    for force_loc in zip(forces, locations)\n        force, location = force_loc\n        force = vcat(force,[0])\n        location = vcat(location,[0])\n        res = cross(force, location)\n        print(res)\n        sum+=res\n    end\n    sum\nend\n\n#forces = [polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90)]\nforces = [[0, -2000], [0, -1200], [0, 15600], [0, -12400]]\nlocation = [[0, 0], [6, 0], [10, 0], [12, 0]]\nprint(moments(forces, location))", "meta": {"hexsha": "9d0049ace9df22989e5eba5bab8b0c2839fca1dc", "size": 646, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ArithematicAnalysis/StaticEquilibrium.jl", "max_stars_repo_name": "Enforcer007/Algorithms-Julia", "max_stars_repo_head_hexsha": "19b3560f01f6376686c3066754e2b1ce4cf06cbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ArithematicAnalysis/StaticEquilibrium.jl", "max_issues_repo_name": "Enforcer007/Algorithms-Julia", "max_issues_repo_head_hexsha": "19b3560f01f6376686c3066754e2b1ce4cf06cbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ArithematicAnalysis/StaticEquilibrium.jl", "max_forks_repo_name": "Enforcer007/Algorithms-Julia", "max_forks_repo_head_hexsha": "19b3560f01f6376686c3066754e2b1ce4cf06cbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0869565217, "max_line_length": 88, "alphanum_fraction": 0.613003096, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122684798184, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7621706532450808}}
{"text": "# find expression of projections on cones and their derivatives here:\n#   https://stanford.edu/~boyd/papers/pdf/cone_prog_refine.pdf\n\n\n\"\"\"\n    projection_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.Zeros) where {T}\n\nprojection of vector `v` on zero cone i.e. K = {0}\n\"\"\"\nfunction projection_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.Zeros) where {T}\n    return FillArrays.Zeros{T}(size(v))\nend\n\n\"\"\"\n    projection_on_set(::AbstractDistance, ::MOI.Reals, v::Array{T}) where {T}\n\nprojection of vector `v` on real cone i.e. K = R\n\"\"\"\nfunction projection_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.Reals) where {T}\n    return v\nend\n\nfunction projection_on_set(::DefaultDistance, v::T, set::MOI.EqualTo) where {T}\n    return zero(T) + set.value\nend\n\nfunction projection_on_set(::DefaultDistance, v::T, set::MOI.LessThan) where {T}\n    return min(v, MOI.constant(set))\nend\n\nfunction projection_on_set(::DefaultDistance, v::T, set::MOI.GreaterThan) where {T}\n    return max(v, MOI.constant(set))\nend\n\n\"\"\"\n    projection_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.Nonnegatives) where {T}\n\nprojection of vector `v` on Nonnegative cone i.e. K = R^n+\n\"\"\"\nfunction projection_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.Nonnegatives) where {T}\n    return max.(v, zero(T))\nend\n\n\"\"\"\n    projection_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.Nonpositives) where {T}\n\nprojection of vector `v` on Nonpositive cone i.e. K = R^n-\n\"\"\"\nfunction projection_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.Nonpositives) where {T}\n    return min.(v, zero(T))\nend\n\n\"\"\"\n    projection_on_set(::NormedEpigraphDistance{p}, v::AbstractVector{T}, ::MOI.SecondOrderCone) where {T}\n\nprojection of vector `v` on second order cone i.e. K = {(t, x) ∈ R+ × Rn |  ||x|| ≤ t }\n\"\"\"\nfunction projection_on_set(::NormedEpigraphDistance{p}, v::AbstractVector{T}, ::MOI.SecondOrderCone) where {p, T}\n    t = v[1]\n    x = v[2:length(v)]\n    norm_x = LinearAlgebra.norm(x, p)\n    if norm_x <= t\n        return copy(v)\n    elseif norm_x <= -t\n        return zeros(T, size(v))\n    end\n    result = zeros(T, size(v))\n    result[1] = one(T)\n    result[2:length(v)] = x / norm_x\n    result *= (norm_x + t) / 2\n    return result\nend\n\nfunction projection_on_set(::DefaultDistance, v::AbstractVector{T}, cone::MOI.SecondOrderCone) where {T}\n    return projection_on_set(NormedEpigraphDistance{2}(), v, cone)\nend\n\n\"\"\"\n    projection_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.PositiveSemidefiniteConeTriangle) where {T}\n\nprojection of vector `v` on positive semidefinite cone i.e. K = S^n⨥\n\"\"\"\nfunction projection_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.PositiveSemidefiniteConeTriangle) where {T}\n    dim = isqrt(2*length(v))\n    X = unvec_symm(v, dim)\n    λ, U = LinearAlgebra.eigen(X)\n    D = LinearAlgebra.Diagonal(max.(λ, 0))\n    return vec_symm(U * D * U')\nend\n\n\"\"\"\n    unvec_symm(x, dim)\n\nReturns a dim-by-dim symmetric matrix corresponding to `x`.\n\n`x` is a vector of length dim*(dim + 1)/2, corresponding to a symmetric matrix\n```\nX = [ X11  X12 ... X1k\n      X21  X22 ... X2k\n      ...\n      Xk1  Xk2 ... Xkk ],\n```\nwhere `vec(X) = (X11, X12, X22, X13, X23, X33, ..., Xkk)`.\n\n### Note on inner products\n\nNote that the scalar product for the symmetric matrix in its vectorized form is\nthe sum of the pairwise product of the diagonal entries plus twice the sum of\nthe pairwise product of the upper diagonal entries; see [p. 634, 1].\nTherefore, this transformation breaks inner products:\n```\ndot(unvec_symm(x, dim), unvec_symm(y, dim)) != dot(x, y).\n```\n\n### References\n\n[1] Boyd, S. and Vandenberghe, L.. *Convex optimization*. Cambridge university press, 2004.\n\"\"\"\nfunction unvec_symm(x, dim=isqrt(2length(x)))\n    X = zeros(eltype(x), dim, dim)\n    idx = 1\n    for i in 1:dim\n        for j in 1:i\n            X[j,i] = X[i,j] = x[idx]\n            idx += 1\n        end\n    end\n    return X\nend\n\n\"\"\"\n    vec_symm(X)\n\nReturns a vectorized representation of a symmetric matrix `X`.\n`vec(X) = (X11, X12, X22, X13, X23, X33, ..., Xkk)`\n\n### Note on inner products\n\nNote that the scalar product for the symmetric matrix in its vectorized form is\nthe sum of the pairwise product of the diagonal entries plus twice the sum of\nthe pairwise product of the upper diagonal entries; see [p. 634, 1].\nTherefore, this transformation breaks inner products:\n```\ndot(vec_symm(X), vec_symm(Y)) != dot(X, Y).\n```\n\n### References\n\n[1] Boyd, S. and Vandenberghe, L.. *Convex optimization*. Cambridge university press, 2004.\n\n\"\"\"\nfunction vec_symm(X)\n    return X[LinearAlgebra.triu(trues(size(X)))]\nend\n\n\"\"\"\n    projection_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.ExponentialCone) where {T}\n\nprojection of vector `v` on closure of the exponential cone\ni.e. `cl(Kexp) = {(x,y,z) | y e^(x/y) <= z, y>0 } U {(x,y,z)| x <= 0, y = 0, z >= 0}`.\n\nReferences:\n* [Proximal Algorithms, 6.3.4](https://web.stanford.edu/~boyd/papers/pdf/prox_algs.pdf)\nby Neal Parikh and Stephen Boyd.\n* [Projection, presolve in MOSEK: exponential, and power cones]\n(https://docs.mosek.com/slides/2018/ismp2018/ismp-friberg.pdf) by Henrik Friberg\n* [Projection onto the exponential cone: a univariate root-finding problem]\n(https://docs.mosek.com/whitepapers/expcone-proj.pdf) by Henrik Friberg\n\"\"\"\nfunction projection_on_set(::DefaultDistance, v::AbstractVector{T}, s::MOI.ExponentialCone; tol=1e-8) where {T}\n    _check_dimension(v, s)\n\n    if _in_exp_cone(v; dual=false)\n        return SVector{3}(v)\n    end\n    if _in_exp_cone(-v; dual=true)\n        # if in polar cone Ko = -K*\n        return zeros(SVector{3,T})\n    end\n    if v[1] <= 0 && v[2] <= 0\n        return @SVector([v[1], 0, max(v[3],0)])\n    end\n\n    return _exp_cone_proj_case_4(v; tol=tol)\nend\n\nfunction _in_exp_cone(v::AbstractVector{T}; dual=false, tol=1e-8) where {T}\n    if dual\n        return (\n            (isapprox(v[1], 0, atol=tol) && v[2] >= 0 && v[3] >= 0) ||\n            (v[1] < 0 && v[1]*exp(v[2]/v[1]) + ℯ * v[3] >= tol)\n        )\n    else\n        return (\n            (v[1] <= 0 && isapprox(v[2], 0, atol=tol) && v[3] >= 0) ||\n            (v[2] > 0 && v[2] * exp(v[1] / v[2]) - v[3] <= tol)\n        )\n    end\nend\n\nfunction _exp_cone_proj_case_4(v::AbstractVector{T}; tol=1e-8) where {T}\n    # Try Heuristic solutions [Friberg 2021, Lemma 5.1]\n    # vp = proj onto primal cone, vd = proj onto polar cone\n    vp = SVector{3,T}(min(v[1], 0), zero(T), max(v[3], 0))\n    vd = SVector{3,T}(zero(T), min(v[2], 0), min(v[3], 0))\n    if v[2] > 0\n        zp = max(v[3], v[2]*exp(v[1]/v[2]))\n        if zp - v[3] < norm(vp - v)\n            vp = SVector{3,T}(v[1], v[2], zp)\n        end\n    end\n    if v[1] > 0\n        zd = min(v[3], -v[1]*exp(v[2]/v[1] - 1))\n        if v[3] - zd < norm(vd - v)\n            vd = SVector{3,T}(v[1], v[2], zd)\n        end\n    end\n\n    # Check if heuristics above approximately satisfy the optimality conditions\n    opt_norm = norm(vp + vd - v)\n    opt_ortho = abs(dot(vp, vd))\n    if norm(v - vp) < tol || norm(v - vd) < tol || (opt_norm < tol && opt_ortho < tol)\n        return vp\n    end\n\n    # Failure of heuristics -> non heuristic solution\n    # Ref: https://docs.mosek.com/slides/2018/ismp2018/ismp-friberg.pdf, p47-48\n    # Thm: h(x) is smooth, strictly increasing, and changes sign on domain\n    r, s, t = v[1], v[2], v[3]\n    h(x) = (((x-1)*r + s) * exp(x) - (r - x*s)*exp(-x))/(x^2 - x + 1) - t\n\n    # Note: won't both be Inf by case 3 of projection\n    lb = r > 0 ? 1 - s/r : -Inf\n    ub = s > 0 ? r/s : Inf\n\n    # Deal with ±Inf bounds\n    if isinf(lb)\n        lb = min(ub-0.125, -0.125)\n        for _ in 1:10\n            h(lb) < 0 && break\n            ub = lb\n            lb *= 2\n        end\n    end\n    if isinf(ub)\n        ub = max(lb+0.125, 0.125)\n        for _ in 1:10\n            h(ub) > 0 && break\n            lb = ub\n            ub *= 2\n        end\n    end\n\n    # Check bounds\n    if !(h(lb) < 0 && h(ub) > 0)\n        error(\"Failure to find bracketing interval for exp cone projection.\")\n    end\n\n    x = _bisection(h, lb, ub)\n    if x === nothing\n        error(\"Failure in root-finding for exp cone projection with boundaries ($lb, $ub).\")\n    end\n\n    return ((x - 1) * r + s)/(x^2 - x + 1) * SVector{3,T}(x, 1, exp(x))\nend\n\n\"\"\"\n    projection_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.DualExponentialCone) where {T}\n\nprojection of vector `v` on the dual exponential cone\ni.e. `Kexp^* = {(u,v,w) | u < 0, -u*exp(v/u) <= ew } U {(u,v,w)| u == 0, v >= 0, w >= 0}`.\n\nReferences:\n* [Proximal Algorithms, 6.3.4](https://web.stanford.edu/~boyd/papers/pdf/prox_algs.pdf)\nby Neal Parikh and Stephen Boyd.\n* [Projection, presolve in MOSEK: exponential, and power cones](https://docs.mosek.com/slides/2018/ismp2018/ismp-friberg.pdf)\nby Henrik Friberg\n\"\"\"\nfunction projection_on_set(d::DefaultDistance, v::AbstractVector{T}, ::MOI.DualExponentialCone) where {T}\n    p = projection_on_set(d, -v, MOI.ExponentialCone())\n    return SVector{3,T}(v[1] + p[1], v[2] + p[2], v[3] + p[3])\nend\n\n\"\"\"\n    projection_on_set(::DefaultDistance, v::AbstractVector{T}, sets::Array{<:MOI.AbstractSet})\n\nProjection onto `sets`, a product of sets\n\"\"\"\nfunction projection_on_set(::DefaultDistance, v::AbstractVector{T}, sets::Array{<:MOI.AbstractSet}) where {T}\n    length(v) == length(sets) || throw(DimensionMismatch(\"Mismatch between value and set\"))\n    return reduce(vcat, (projection_on_set(DefaultDistance(), v[i], sets[i]) for i in eachindex(sets)))\nend\n\n\"\"\"\n    projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.Zeros) where {T}\n\nderivative of projection of vector `v` on zero cone i.e. K = {0}^n\n\"\"\"\nfunction projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.Zeros) where {T}\n    return FillArrays.Zeros(length(v), length(v))\nend\n\n\"\"\"\n    projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.Reals) where {T}\n\nderivative of projection of vector `v` on real cone i.e. K = R^n\n\"\"\"\nfunction projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.Reals) where {T}\n    return FillArrays.Eye(length(v))\nend\n\n\"\"\"\n    projection_gradient_on_set(::DefaultDistance, v::T, ::MOI.EqualTo)\n\"\"\"\nfunction projection_gradient_on_set(::DefaultDistance, ::T, ::MOI.EqualTo) where {T}\n    return zero(T)\nend\n\nfunction projection_gradient_on_set(::DefaultDistance, v::T, s::MOI.LessThan) where {T}\n    return oneunit(T) * (v <= MOI.constant(s))\nend\n\nfunction projection_gradient_on_set(::DefaultDistance, v::T, s::MOI.GreaterThan) where {T}\n    return oneunit(T) * (v >= MOI.constant(s))\nend\n\n\"\"\"\n    projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.Nonnegatives) where {T}\n\nderivative of projection of vector `v` on Nonnegative cone i.e. K = R^n+\n\"\"\"\nfunction projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.Nonnegatives) where {T}\n    y = (sign.(v) .+ one(T))/2\n    return LinearAlgebra.Diagonal(y)\nend\n\n\"\"\"\n    projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.Nonpositives) where {T}\n\nderivative of projection of vector `v` on Nonpositives cone i.e. K = R^n-\n\"\"\"\nfunction projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.Nonpositives) where {T}\n    y = @. (-sign(v) + one(T))/2\n    return LinearAlgebra.Diagonal(y)\nend\n\n\"\"\"\n    projection_gradient_on_set(::NormedEpigraphDistance{p}, v::AbstractVector{T}, ::MOI.SecondOrderCone) where {T}\n\nderivative of projection of vector `v` on second order cone i.e. K = {(t, x) ∈ R+ × Rn |  ||x|| ≤ t }\n\"\"\"\nfunction projection_gradient_on_set(::NormedEpigraphDistance{p}, v::AbstractVector{T}, ::MOI.SecondOrderCone) where {p,T}\n    n = length(v)\n    t = v[1]\n    x = v[2:n]\n    norm_x = LinearAlgebra.norm(x, p)\n    if norm_x <= t\n        return Matrix{T}(LinearAlgebra.I,n,n)\n    elseif norm_x <= -t\n        return zeros(T, n, n)\n    end\n    result = [\n        norm_x     x';\n        x          (norm_x + t)*Matrix{T}(LinearAlgebra.I,n-1,n-1) - (t/(norm_x^2))*(x*x')\n    ]\n    result ./= (2 * norm_x)\n    return result\nend\n\nfunction projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, cone::MOI.SecondOrderCone) where {T}\n    return projection_gradient_on_set(NormedEpigraphDistance{2}(), v, cone)\nend\n\n\"\"\"\n    projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, cone::MOI.PositiveSemidefiniteConeTriangle) where {T}\n\nderivative of projection of vector `v` on positive semidefinite cone i.e. K = S^n⨥\n\"\"\"\nfunction projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.PositiveSemidefiniteConeTriangle) where {T}\n    n = length(v)\n    dim = isqrt(2n)\n    X = unvec_symm(v, dim)\n    λ, U = LinearAlgebra.eigen(X)\n    Tp = promote_type(T, Float64)\n\n    # if all the eigenvalues are >= 0\n    if all(λi ≥ zero(λi) for λi in λ)\n        return Matrix{Tp}(LinearAlgebra.I, n, n)\n    end\n\n    # k is the number of negative eigenvalues in X minus ONE\n    k = count(λi < 1e-4 for λi in λ)\n\n    y = zeros(Tp, n)\n    D = zeros(Tp, n, n)\n\n    for idx in 1:n\n        # set eigenvector\n        y[idx] = 1\n\n        # defining matrix B\n        X̃ = unvec_symm(y, dim)\n        B = U' * X̃ * U\n\n        for i in 1:size(B)[1] # do the hadamard product\n            for j in 1:size(B)[2]\n                if (i <= k && j <= k)\n                    @inbounds B[i, j] = 0\n                elseif (i > k && j <= k)\n                    λpi = max(λ[i], zero(Tp))\n                    λmj = -min(λ[j], zero(Tp))\n                    @inbounds B[i, j] *= λpi / (λmj + λpi)\n                elseif (i <= k && j > k)\n                    λmi = -min(λ[i], zero(Tp))\n                    λpj = max(λ[j], zero(Tp))\n                    @inbounds B[i, j] *= λpj / (λmi + λpj)\n                end\n            end\n        end\n        @inbounds D[idx, :] = vec_symm(U * B * U')\n        # reset eigenvector\n        @inbounds y[idx] = 0\n    end\n    return D\nend\n\n\"\"\"\n    projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.ExponentialCone) where {T}\n\nderivative of projection of vector `v` on closure of the exponential cone,\ni.e. `cl(Kexp) = {(x,y,z) | y e^(x/y) <= z, y>0 } U {(x,y,z)| x <= 0, y = 0, z >= 0}`.\n\nReferences:\n* [Solution Refinement at Regular Points of Conic Problems](https://stanford.edu/~boyd/papers/cone_prog_refine.html)\nby Enzo Busseti, Walaa M. Moursi, and Stephen Boyd\n\"\"\"\nfunction projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, s::MOI.ExponentialCone) where {T}\n    _check_dimension(v, s)\n\n    if _in_exp_cone(v; dual=false)\n        return SMatrix{3,3,T}(I)\n    end\n    if _in_exp_cone(-v; dual=true)\n        # if in polar cone Ko = -K*\n        return zeros(SMatrix{3,3,T})\n    end\n    if v[1] <= 0 && v[2] <= 0\n        return @SMatrix(T[\n            1 0 0\n            0 0 0\n            0 0 (v[3] >= 0)\n        ])\n    end\n\n    z1, z2, z3 = _exp_cone_proj_case_4(v)\n    nu = z3 - v[3]\n    rs = z1/z2\n    exp_rs = exp(rs)\n\n    mat = inv(@SMatrix([\n        1+nu*exp_rs/z2     -nu*exp_rs*rs/z2       0     exp_rs;\n        -nu*exp_rs*rs/z2   1+nu*exp_rs*rs^2/z2    0     (1-rs)*exp_rs;\n        0                  0                      1     -1\n        exp_rs             (1-rs)*exp_rs          -1    0\n    ]))\n    return SMatrix{3,3}(@view(mat[1:3,1:3]))\nend\n\n\"\"\"\n    projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.DualExponentialCone) where {T}\n\nderivative of projection of vector `v` on the dual exponential cone,\ni.e. `Kexp^* = {(u,v,w) | u < 0, -u*exp(v/u) <= ew } U {(u,v,w)| u == 0, v >= 0, w >= 0}`.\n\nReferences:\n* [Solution Refinement at Regular Points of Conic Problems]\n(https://stanford.edu/~boyd/papers/cone_prog_refine.html)\nby Enzo Busseti, Walaa M. Moursi, and Stephen Boyd\n\"\"\"\nfunction projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, ::MOI.DualExponentialCone) where {T}\n    # from Moreau decomposition: x = P_K(x) + P_-K*(x)\n    return I - projection_gradient_on_set(DefaultDistance(), -v, MOI.ExponentialCone())\nend\n\n\"\"\"\n    projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, sets::AbstractVector{<:MOI.AbstractSet})\n\nDerivative of the projection of vector `v` on product of `sets`\nprojection_gradient_on_set[i,j] = ∂projection_on_set[i] / ∂v[j] where `projection_on_set` denotes projection of `v` on `cone`\n\nFind expression of projections on cones and their derivatives here: https://stanford.edu/~boyd/papers/pdf/cone_prog_refine.pdf\n\"\"\"\nfunction projection_gradient_on_set(::DefaultDistance, v::AbstractVector{T}, sets::AbstractVector{<:MOI.AbstractSet}) where {T}\n    length(v) == length(sets) || throw(DimensionMismatch(\"Mismatch between value and set\"))\n    return BlockDiagonal([projection_gradient_on_set(DefaultDistance(), v[i], sets[i]) for i in eachindex(sets)])\nend\n\n\"\"\"\n    projection_on_set(::DefaultDistance, V::AbstractVector{T}, s::NormBallNuclear{T}) where {T}\n\nprojection of matrix `V` onto nuclear norm ball\n\"\"\"\nfunction projection_on_set(d::DefaultDistance, V::AbstractMatrix{T}, s::NormNuclearBall{T}) where {T}\n    U, sing_val, Vt = LinearAlgebra.svd(V)\n    if (sum(sing_val) <= s.radius)\n        return V\n    end\n    sing_val_proj = projection_on_set(d, sing_val, ProbabilitySimplex(length(sing_val), s.radius))\n    return U * Diagonal(sing_val_proj) * Vt'\nend\n\n# initial implementation in FrankWolfe.jl\nfunction projection_on_set(::DefaultDistance, v::AbstractVector{T}, s::ProbabilitySimplex{T}) where {T}\n    _check_dimension(v, s)\n    # TODO: allocating a ton, should implement the recent non-sorting alg\n    n = length(v)\n    if sum(v) ≈ s.radius && all(>=(0), v)\n        return v\n    end\n    rev = v .- maximum(v)\n    u = sort(rev, rev=true)\n    cssv = cumsum(u)\n    rho = sum(eachindex(u)) do idx\n        u[idx] * idx > (cssv[idx] - s.radius)\n    end - 1\n    theta = (cssv[rho+1] - s.radius) / (rho + 1)\n    w = clamp.(rev .- theta, 0.0, Inf)\n    return w\nend\n\nfunction projection_on_set(::DefaultDistance, v::AbstractVector{T}, s::StandardSimplex{T}) where {T}\n    _check_dimension(v, s)\n    n = length(v)\n    if sum(v) ≤ s.radius && all(>=(0), v)\n        return v\n    end\n    x = copy(v)\n    sum_pos = zero(T)\n    for idx in eachindex(x)\n        if x[idx] < 0\n            x[idx] = 0\n        else\n            sum_pos += x[idx]\n        end\n    end\n    # at least one positive element\n    if sum_pos > 0\n        @. x = x / sum_pos * s.radius\n    end\n    return x\nend\n\nfunction projection_on_set(::DefaultDistance, v::AbstractVector{T}, s::NormInfinityBall{T}) where {T}\n    if norm(v, Inf) <= s.radius\n        return v\n    end\n    return clamp.(v, -s.radius, s.radius)\nend\n\nfunction projection_on_set(::DefaultDistance, v::AbstractVector{T}, s::NormTwoBall{T}) where {T}\n    nv = norm(v)\n    if nv <= s.radius\n        return v\n    end\n    return v .* s.radius ./ nv\nend\n\n# inspired by https://github.com/MPF-Optimization-Laboratory/ProjSplx.jl\nfunction projection_on_set(::DefaultDistance, v::AbstractVector{T}, s::NormOneBall{T}) where {T}\n    n = length(v)\n    if norm(v, 1) ≤ τ\n        return v\n    end\n    u = abs.(v)\n    # simplex projection\n    bget = false\n    s_indices = sortperm(u, rev=true)\n    tsum = zero(τ)\n\n    @inbounds for i in 1:n-1\n        tsum += u[s_indices[i]]\n        tmax = (tsum - τ) / i\n        if tmax ≥ u[s_indices[i+1]]\n            bget = true\n            break\n        end\n    end\n    if !bget\n        tmax = (tsum + u[s_indices[n]] - τ) / n\n    end\n\n    @inbounds for i in 1:n\n        u[i] = max(u[i] - tmax, 0)\n        u[i] *= sign(v[i])\n    end\n    return u\nend\n", "meta": {"hexsha": "5ee0991555d0e714f60c9d5aacdf2a5a6f78a6f4", "size": 19514, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/projections.jl", "max_stars_repo_name": "joaquimg/MathOptSetDistances.jl", "max_stars_repo_head_hexsha": "a449c4b178855db0b461d1aa13d60a5ae81b0eac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2020-05-21T18:58:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:27:44.000Z", "max_issues_repo_path": "src/projections.jl", "max_issues_repo_name": "joaquimg/MathOptSetDistances.jl", "max_issues_repo_head_hexsha": "a449c4b178855db0b461d1aa13d60a5ae81b0eac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 53, "max_issues_repo_issues_event_min_datetime": "2020-05-23T16:42:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T19:51:21.000Z", "max_forks_repo_path": "src/projections.jl", "max_forks_repo_name": "joaquimg/MathOptSetDistances.jl", "max_forks_repo_head_hexsha": "a449c4b178855db0b461d1aa13d60a5ae81b0eac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-27T19:41:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-20T18:23:44.000Z", "avg_line_length": 32.6321070234, "max_line_length": 127, "alphanum_fraction": 0.6216050015, "num_tokens": 6128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7621636635370846}}
{"text": "\"\"\"\n    src\n\nA general module name. In this demo, it contains:\n2. DiscreteMarkovChain, a type to define a discrete Markov chain\n3. stationary_distribution, a function to solve stationary distribution of a `DiscreteMarkovChain`\n4. approx_ar1, approximates an AR(1) process with a discrete Markov Chain\n5. golden_section, Golden Section search\n6. golden_section_improved, improved 3-point Golden Section search\n7. DiscreteMarkovChain, discrete state Markov Chain\n\"\"\"\nmodule src\n    import Distributions\n    # ----------------------\n    export approx_ar1\n    export DiscreteMarkovChain, stationary_distribution\n    export DiscreteTimeAR1\n    export golden_section, golden_section_improved\n\n\n\n\n\n\n# ------------------ TYPE: DISCRETE MARKOV CHAIN\n\"\"\"\n    DiscreteMarkovChain( P::Matrix{T} where T <: Real ; w::Vector = Array(1:size(T,1)) )\n\nimmutable type for discrete markov chains,\nincluding:\n1. K::Int, the number of states\n2. w::Vector, state values, can be anything\n2. P::Matrix{T} where T <: Real, transition matrix, square matrix, P[i,j], prob from state i to j\n\"\"\"\nmutable struct DiscreteMarkovChain <: Any\n    K::Int  # number of states\n    w::Vector # state values, can be anything\n    P::Matrix{T} where T <: Real  # transition matrix\n    function DiscreteMarkovChain( P::Matrix{T} where T <: Real ; w::Vector = Array(1:size(P,1)) )\n        (size(P)[1] == size(P)[2])  ?  nothing  :  throw(ErrorException(\"non-square transition matrix received\"))\n        all(isapprox.( sum(P,dims = 2), 1.0))  ?  nothing  : throw(ErrorException(\"row-sum == 1 transition matrix received!\"))\n        # adjust P, making row-sum EXACT 1\n        local newP = copy(P)\n        for x in 1:size(P,1)\n            newP[x,:] ./= sum(newP[x,:])\n        end\n        return new( size(P,1), w, newP )\n    end\nend\n# -----\n\"\"\"\n    stationary_distribution( mc::DiscreteMarkovChain )\n\nget the stationary distribution of a given discrete Markov Chain.\nreturns a `Vector{Float64}`, elements are in the order of `mc.w`.\n\"\"\"\nfunction stationary_distribution( mc::DiscreteMarkovChain )\n    local tmpP = copy(mc.P)\n    while true\n        (sum(abs.(tmpP .- tmpP^2)) < 1E-8) ? break : nothing\n        tmpP ^= 2\n    end # while\n    return tmpP[1,:]::Vector{Float64}\nend # stationary_distribution\n\n\n\n\n\n\nabstract type AbstractARProcess <: Any end\n# ------------------------------- AR(1) process\n\"\"\"\n    DiscreteTimeAR1( ρ::Real, σ::Real ; Z̄::Real = 0.0, Z0::Union{Real,Distributions.UnivariateDistribution} = 0.0 )\n\nAn AR(1) process defined as: `` Z_{t+1} = (1-\\\\rho)\\\\cdot \\\\bar{Z} + \\\\rho Z_t + \\\\epsilon_t ``.\nwhere `ρ` is the auto-reg coefficient, `Z̄` is the mean value, `σ` is the std of the error term ``\\\\epsilon_t``\nwhich follows i.i.d. `N(0,σ)`, and `Z0` is the initial value/distribution of this process.\nIt can be a constant, or an instance of one of the subtypes of `Distributions.UnivariateDistribution`, e.g. `Normal()`.\n\"\"\"\nstruct DiscreteTimeAR1 <: AbstractARProcess\n    ρ::Real\n    Z̄::Real\n    Z0::Union{Real,Distributions.UnivariateDistribution}\n    σ::Real\n    # ---------------\n    function DiscreteTimeAR1( ρ::Real, σ::Real ; Z̄::Real = 0.0, Z0::Union{Real,Distributions.UnivariateDistribution} = 0.0 )\n        @assert(isfinite(ρ), \"rho must be finite\"); @assert(isfinite(Z̄), \"the mean value must be finite\")\n        @assert(0<σ<Inf, \"sigma must be non-negative and finite\")\n        isa(Z0, Real) ?  @assert(isfinite(Z0), \"Z0 must be finite\") : nothing\n        # -----\n        return new(ρ,Z̄,Z0,σ)\n    end # AR1()\nend # AR1\n\n\n\n\n\n\n\n\n\n\n# ------------------ APPROXIMATE AR(1) WITH MARKOV CHAIN\n\"\"\"\n    approx_ar1(ρ::Real, σ::Real ; m::Int = 9, λ::Int = 3, Z̄::Real = 0.0 )\n\napproximates a zero-mean AR(1) process with a discrete finite-state Markov Chain\nwhose states are equally divided.\nThe zero-mean AR(1) process is defined as:\n`` Z_{t+1} = (1-\\\\rho)\\\\cdot \\\\bar{Z} + \\\\rho Z_t + \\\\epsilon_t ``,\nwhere `ρ` is the auto-regression coefficient, `σ` is the standard error of ``\\\\epsilon_t``,\n`m` is the number of the new Markov chain's states, `Z̄` is the mean of `Zt`.\n`λ>0` is the absolute maximum deviation of the Markov chain's states,\nit is defined as `max(z) = λσ`, where `z` is the state value of the new Markov Chain.\n\nreturns an instance of `DiscreteMarkovChain`.\n\nThis algorithm is from `(Tauchen, 1986)` and developed by `(Heer & Maussner, 2015)`.\nIn most cases, `m=9` and `λ=3` are enough to approximate an AR(1).\n\"\"\"\nfunction approx_ar1(ρ::Real, σ::Real ; m::Int = 9, λ::Real = 3, Z̄::Real = 0.0 )\n    # assertions\n    abs(ρ) < 1  ?  nothing : @warn(\"the AR(1) process is not stationary becuase abs(ρ) >=1\")\n    @assert(0 < σ < Inf, \"the standard error must be greater than 0 and finite\")\n    @assert(1 < m, \"there must be at least two states to make a Markov chain\")\n    @assert(0 < λ < Inf, \"the absolute deviation must be greater than 0 and finite\")\n    @assert(isfinite(Z̄), \"the mean value of Zt must be finite\")\n    # 1. states\n    local w::Vector = zeros(m)\n    w[1] = -λ * σ / √(1-ρ^2)  # minimum state value (lower bound, finite)\n    local steplen::Real = -2 * w[1] / (m-1)  # step length between two states\n    for x in 2:m; w[x] = w[x-1] + steplen; end;  # fill\n    # 2. transition matrix\n    local P::Matrix = zeros(m,m)\n    local tmpNorm = Distributions.Normal() # std norm distrib\n    for x in 1:m\n        P[x,1] = Distributions.cdf(tmpNorm, (w[1]-ρ*w[x])/σ + 0.5 * steplen / σ )\n        if m>2\n            for y in 2:(m-1)\n                P[x,y] = Distributions.cdf(tmpNorm, (w[y]-ρ*w[x])/σ + 0.5 * steplen / σ ) -\n                    Distributions.cdf(tmpNorm, (w[y]-ρ*w[x])/σ - 0.5 * steplen / σ )\n            end # for\n        end # if\n        P[x,m] = 1 - sum(P[x,1:(m-1)])\n    end # x\n    return DiscreteMarkovChain(P,w = w .+ Z̄)::DiscreteMarkovChain # add mean value to state\nend # approx_ar1\n# -------------------\napprox_ar1(ar1::DiscreteTimeAR1 ; m::Int = 9, λ::Real = 3) = begin\n    return approx_ar1(ar1.ρ, ar1.σ, m = m, λ = λ, Z̄ = ar1.Z̄)::DiscreteMarkovChain\nend # approx_ar1\n\n\n\n# ----------------------- Linear interpolation & expolation\n\"\"\"\n    linear_function_interpolation( x0::Real, xsamples::Vector{T} where T <: Real, fsamples::Vector{T} where T <: Real )\n\nlinear interpolation on one-parameter function `f(x)` which is defined by a vector of sample `x` points\nand a vector of sample `f(x)` corresponding to sample `x`;\n`xsamples` should be increasingly sorted.\nreturns the function value evaluated at the given point `x0`.\nif `x0<findmin(x)` or `x0>findmax(x)`, this function uses the linear expolation\nof minimum/maximum sample `x` and the second minimum/maximum sample `x`.\n\"\"\"\nfunction linear_function_interpolation( x0::Real, xsamples::Vector{T} where T <: Real, fsamples::Vector{T} where T <: Real )\n    issorted(xsamples) ? nothing : throw(ErrorException(\"xsamples should be pre-sorted\"))\n    local N = length(fsamples); local xmax = xsamples[end]; local xmin = xsamples[1]\n    local x0_location = (x0 - xmin) / (xmax - xmin) * (N - 1) + 1  # locating x0\n    local nearest_xsample_loc = floor(Int,x0_location)  # the nearest sample x point (on the left side) to interpolate x0\n    local dist_from_nearest_xsample = x0_location - nearest_xsample_loc # the fractional distance between x0 and the nearest x point\n    # NOTE: relationship: x[near] < x0 < x[near+1]\n\n    # case: if touching the upper bound\n    if (x0 > xmax) | (nearest_xsample_loc == N)  # to prevent BoundsError at index N\n        res = fsamples[end]\n        return res::Float64\n    # case: if touching the lower bound\n    elseif (x0 <= xmin) | (nearest_xsample_loc == 1)\n        res = fsamples[1] - (1 - x0_location) * ( fsamples[2] - fsamples[1] )\n        return res::Float64\n    # case: normal case\n    else\n        res = (1 - dist_from_nearest_xsample) * fsamples[nearest_xsample_loc] +\n            dist_from_nearest_xsample * fsamples[nearest_xsample_loc + 1]\n        return res::Float64\n    end # if\n\nend # linear_function_interpolation\n\n\n\n\n\n# ------------------------------ conventional Golden Section for 1-parameter function\n\"\"\"\n    golden_section(f::Function, lb::Real, ub::Real ; atol::Real = 1E-8, maxiter::Int = 5000)\n\nconventional Golden Section search for MINIMIZATION problem.\n`f` must only receive one `Real` type location parameter;\n`lb` is the finite lower bound of searching; `ub` is the finite upper bound of searching;\n`atol` is the absolute error to converge,\nand `maxiter` sets the maximum loops to prevent dead loop.\nreturns a `Tuple` (in order) consisting of optimal x, optimal `f` value, a flag indicating if converged,\nand in which round the algorithm ends.\n\ntesting code:\n```\ng(x::Real) = (x-1)^2\nBenchmarkTools.@benchmark tmp = src.golden_section(g,-1.0,3.0,atol=1E-12)\n```\n\nperformance tips:\n```\nBenchmarkTools.Trial:\n  memory estimate:  96 bytes\n  allocs estimate:  1\n  --------------\n  minimum time:     144.933 ns (0.00% GC)\n  median time:      150.576 ns (0.00% GC)\n  mean time:        181.232 ns (7.65% GC)\n  maximum time:     71.892 μs (99.47% GC)\n  --------------\n  samples:          10000\n  evals/sample:     852\n```\n\"\"\"\nfunction golden_section(f::Function, lb::Real, ub::Real ; atol::Real = 1E-8, maxiter::Int = 5000)\n    @assert(-Inf < lb < ub < Inf, \"lb must be less than ub, both must be finite\")\n    local goldnum = 0.618033988749895  # the golden number\n    local bounds = [lb,ub]  # changable bounds to update\n    local left_x = bounds[1] + (1-goldnum) * (bounds[2] - bounds[1])  # left trial\n    local right_x = bounds[1] + goldnum * (bounds[2]-bounds[1])  # right trial\n    # initial evaluation (NOTE: using type assertion to test if `f` only returns one `Real` value)\n    local left_fval::Real = f(left_x)\n    local right_fval::Real = f(right_x)\n    # test if both trials are defined & finite (because NaN & Inf cannot be operated rationally)\n    if isnan(left_fval) | isinf(left_fval) | isnan(left_fval) | isinf(left_fval)\n        throw(DomainError(\"NaN or Inf function value(s) found in the initial evaluation of Golden section search\"))\n    end # if\n    # begin search\n    for j in 1:maxiter\n        # check convergency\n        if abs(bounds[2]-bounds[1]) < atol\n            local finalx::Real = (bounds[1] + bounds[2]) / 2\n            return ( finalx, f(finalx), true, j )::Tuple\n        end # if\n        # if not converge, go on to update\n        if left_fval > right_fval\n            bounds[1] = left_x; bounds[2] = bounds[2]; left_x = right_x\n            right_x = bounds[1] + goldnum * (bounds[2] - bounds[1])\n            left_fval = f(left_x)\n            right_fval = f(right_x)\n        else # i.e. if left_fval <= right_fvals\n            bounds[1] = bounds[1]; bounds[2] = right_x; right_x = left_x\n            left_x = bounds[1] + (1-goldnum) * (bounds[2] - bounds[1])\n            left_fval = f(left_x)\n            right_fval = f(right_x)\n        end # if\n    end # for j\n    # if loop normally ends, it means that the algorithm did not converge\n    local finalx::Real = (left_x+right_x)/2\n    return ( finalx, f(finalx), false, maxiter )::Tuple\nend # golden_section\n\n\n\n\n# ---------------------------- improved Golden Section search\n\"\"\"\n    golden_section_improved(f::Function, LLB::Float64, LB::Float64, RB::Float64 ;  TOL::Float64=1E-08, ITER=300)\n\nimproved Golden Section search, using a third point x_mid between (x_low,x_high) to improve performance.\ndesigned for one-dim function MAXIMIZATION problem\n\nPar:\n    1. f [annonymous func]: target to search (a maximization problem), it MUST HAVE ONLY ONE PARAMETER f(x)\n    1. LLB [num]: the (initial) very left bound of searching (initial)\n    1. LB [num]: the (initial) left bound of searching\n    1. RB [num]: the (initial) right bound of searching\n    1. TOL [num]: tolerance, 1E-4 or 1E-5 is enough\n    1. ITER [int]: maximum iteration times in searching\n\nRet:\n    1. Xmin [num]: the solution\n\nDepend:\n    1. func\n\"\"\"\nfunction golden_section_improved(f::Function, LLB::Real, LB::Real, RB::Real ;  TOL::Float64=1E-08)\n    # -------- DATA PROCESS ----------\n    # NOTE: in Julia, the golden numebr is an integrated const (before v0.6), but we redefine a golden number for case in v1.0 and later\n    GoldenNumber = 1.618033988749895\n    r1 = GoldenNumber - 1; r2 = 1 - r1\n    x0 = LLB; x3 = RB # initia-lize bounds\n    if abs(RB-LB)<=abs(LB-LLB)\n        x1 = LB; x2 = LB+r2*(RB-LB)\n    else\n        x2 = LB; x1 = LB-r2*(LB-LLB)\n    end\n    # initialization of function value (and turns a maximization to a minimization)\n    f1 = - f(x1); f2 = - f(x2)\n    # Searching\n    while true\n        if f2<f1\n            x0=x1 # Update the very lower bound\n            x1=x2; x2=r1*x1+r2*x3 # new left golden position\n            f1=f2; f2= - f(x2)\n        else\n            x3=x2; x2=x1; x1=r1*x2+r2*x0; f2=f1; f1= - f(x1)\n        end # if\n        if abs(x3-x0) > TOL * (abs(x1)+abs(x2))\n            break\n        end # if\n    end # while\n    # Post-convergence\n    Xmin = f1<=f2 ? x1 : x2\n\n    return Xmin::Float64\nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nend # src\n#\n", "meta": {"hexsha": "fe1e6695c635f14314e55169628eca8cb4587e75", "size": 12956, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "190623_LifeCycleWithOneShockOnConsumption/src.jl", "max_stars_repo_name": "Clpr/EconToolBox", "max_stars_repo_head_hexsha": "4c2cf1e5ec9a84dc07f76317910aea4682fa508c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "190623_LifeCycleWithOneShockOnConsumption/src.jl", "max_issues_repo_name": "Clpr/EconToolBox", "max_issues_repo_head_hexsha": "4c2cf1e5ec9a84dc07f76317910aea4682fa508c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "190623_LifeCycleWithOneShockOnConsumption/src.jl", "max_forks_repo_name": "Clpr/EconToolBox", "max_forks_repo_head_hexsha": "4c2cf1e5ec9a84dc07f76317910aea4682fa508c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5536231884, "max_line_length": 136, "alphanum_fraction": 0.6341463415, "num_tokens": 3932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7621636633425158}}
{"text": "using SMM\nusing Optim\nusing HTTP\nusing GLM\nusing LinearAlgebra\nusing Random\nusing Statistics\nusing DataFrames\nusing DataFramesMeta\nusing CSV\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 1\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nurl = \"https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2020/master/ProblemSets/PS1-julia-intro/nlsw88.csv\"\ndf = CSV.read(HTTP.get(url).body,DataFrame)\nX = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\ny = df.married.==1\n\n#GMM\nfunction ols_gmm(b, X, y)\n    g = y .- X*b\n    J = g'*I*g\n    return J\nend\nres =  optimize(b -> ols_gmm(b, X, y), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-6, iterations=100_000, show_trace=true))\nprintln(res.minimizer)\n\n\n#closed form solution\nres1 = inv(X'*X)*X'*y\nprintln(res1)\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 2\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\ndf = dropmissing(df, :occupation)\ndf[df.occupation.==8 ,:occupation] .= 7\ndf[df.occupation.==9 ,:occupation] .= 7\ndf[df.occupation.==10,:occupation] .= 7\ndf[df.occupation.==11,:occupation] .= 7\ndf[df.occupation.==12,:occupation] .= 7\ndf[df.occupation.==13,:occupation] .= 7\nX = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\ny = df.occupation\n\n#MlE\nfunction mlogit(alpha, X, y)\n        \n        K = size(X,2)\n        J = length(unique(y))\n        N = length(y)\n        bigY = zeros(N,J)\n        for j=1:J\n            bigY[:,j] = y.==j\n        end\n        bigAlpha = [reshape(alpha,K,J-1) zeros(K)]\n        \n        num = zeros(N,J)\n        dem = zeros(N)\n        for j=1:J\n            num[:,j] = exp.(X*bigAlpha[:,j])\n            dem .+= num[:,j]\n        end\n        \n        P = num./repeat(dem,1,J)\n        \n        loglike = -sum( bigY.*log.(P) )\n        \n        return loglike\n    end\n\nalpha_zero = zeros(6*size(X,2))\nalpha_rand = rand(6*size(X,2))\nalpha_true = [.1910213,-.0335262,.5963968,.4165052,-.1698368,-.0359784,1.30684,-.430997,.6894727,-.0104578,.5231634,-1.492475,-2.26748,-.0053001,1.391402,-.9849661,-1.398468,-.0142969,-.0176531,-1.495123,.2454891,-.0067267,-.5382892,-3.78975]\nalpha_start = alpha_true.*rand(size(alpha_true))\n#println(size(alpha_true))\nalpha_hat_optim = optimize(a -> mlogit(a, X, y), alpha_start, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\nalpha_hat_mle = alpha_hat_optim.minimizer\nprintln(alpha_hat_mle)\n\n\n#GMM\nfunction mlogit_gmm(alpha, X, y)\n    K = size(X,2)\n    J = length(unique(y))\n    N = length(y)\n    bigY = zeros(N,J)\n    for j=1:J\n        bigY[:,j] = y.==j\n    end\n    bigAlpha = [reshape(alpha,K,J-1) zeros(K)]\n        \n    num = zeros(N,J)\n    dem = zeros(N)\n    for j=1:J\n        num[:,j] = exp.(X*bigAlpha[:,j])\n        dem .+= num[:,j]\n    end\n        \n    P = num./repeat(dem,1,J)\n        \n    \n    g = bigY .-P\n    J = sum(g'*I*g)\n    return J\nend\n\nalpha_rand = rand(6*size(X,2))\nalpha_hat_optim1 = optimize(a -> mlogit(a, X, y), alpha_start, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\nalpha_hat_gmm = alpha_hat_optim1.minimizer\nprintln(alpha_hat_gmm)\n\n\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 3\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nfunction mlogit_sim(alpha,X,K,J,N)\n    bigAlpha = [reshape(alpha,K,J-1) zeros(K)]\n    num = zeros(N,J)\n    dem = zeros(N)\n    for j=1:J\n        num[:,j] = exp.(X*bigAlpha[:,j])\n        dem .+= num[:,j]\n    end\n        \n    P = num./repeat(dem,1,J)\n    epsilon = rand(N)\n\n    Y = zeros(N)\n    for i =1:N\n        temp = zeros(J)\n        for j = 1:J\n            temp[j] = convert(Int,(sum(P[i,j:end])>epsilon[i]))\n        end\n        Y[i] = sum(temp)\n    end\n    return Y\nend\n\nK = 3\nJ = 7\nN = 10000\nX = randn((N,K))\nalpha_true = rand((J-1)*K)\nprintln(\"beta true:\",alpha_true)\ny_sim = mlogit_sim(alpha_true,X,K,J,N)\nalpha_start = alpha_true.*rand(size(alpha_true))\nalpha_hat_optim2 = optimize(a -> mlogit(a, X, y_sim), alpha_start, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\nalpha_hat_sim = alpha_hat_optim2.minimizer\nprintln(\"beta estimated:\",alpha_hat_sim)\n\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 4\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nMA = SMM.parallelNormal()\ndc = SMM.history(MA.chains[1])\ndc = dc[dc[:accepted].==true,:]\nprintln(describe(dc))\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 5\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nfunction mlogit_smm(alpha, X, y, D) \n    K = size(X,2)\n    J = length(unique(y))\n    N = length(y)\n    \n   # N+1 moments in both model and data\n    gmodel = zeros(N+1,D)\n    # data moments are just the y vector itself\n    # and the variance of the y vector\n    gdata  = vcat(y,var(y))\n    \n    Random.seed!(1234)                    \n   \n    # simulated model moments\n    \n    for d = 1:D\n        y_sim = mlogit_sim(alpha,X,K,J,N)\n        gmodel[1:end-1,d] = y_sim\n        gmodel[  end  ,d] = var(y_sim)\n    end\n    # criterion function\n    err = vec(gdata .- mean(gmodel; dims=2))\n    # weighting matrix is the identity matrix\n    # minimize weighted difference between data and moments\n    J = err'*I*err\n    \n    return J\nend\n\n\nalpha_true = [.1910213,-.0335262,.5963968,.4165052,-.1698368,-.0359784,1.30684,-.430997,.6894727,-.0104578,.5231634,-1.492475,-2.26748,-.0053001,1.391402,-.9849661,-1.398468,-.0142969,-.0176531,-1.495123,.2454891,-.0067267,-.5382892,-3.78975]\nalpha_start = alpha_true.*rand(size(alpha_true))\nD = 2000\n#println(size(alpha_true))\nalpha_hat_optim = optimize(a -> mlogit_smm(a, X, y,D), alpha_start, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\nalpha_hat_smm = alpha_hat_optim.minimizer\nprintln(alpha_hat_smm)", "meta": {"hexsha": "2c604f9f8b4c5130d8cc7f13f140bf72b1a6e96a", "size": 5783, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS7-smm/PS7_ping.jl", "max_stars_repo_name": "babymetal287/fall-2021", "max_stars_repo_head_hexsha": "804f7fec898a0fccd018c8bc5d520d8f9156d62a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSets/PS7-smm/PS7_ping.jl", "max_issues_repo_name": "babymetal287/fall-2021", "max_issues_repo_head_hexsha": "804f7fec898a0fccd018c8bc5d520d8f9156d62a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS7-smm/PS7_ping.jl", "max_forks_repo_name": "babymetal287/fall-2021", "max_forks_repo_head_hexsha": "804f7fec898a0fccd018c8bc5d520d8f9156d62a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6287128713, "max_line_length": 242, "alphanum_fraction": 0.5621649663, "num_tokens": 1876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7621636485709157}}
{"text": "\"\"\"\n    hermite(x, p::Integer)\n\nEvaluate the Hermite polynomial of degree `p` at `x` using the three term recursion.\n\"\"\"\nfunction hermite(x, p::Integer)\n    T = typeof( 2x )\n    p₀ = one(T)\n    p₁ = 2x\n\n    if p <= 0\n        return p₀\n    elseif p == 1\n        return p₁\n    end\n\n    for n in 2:p\n        p₀, p₁ = p₁, 2x*p₁ - 2*(n-1)*p₀\n    end\n\n    p₁\nend\n", "meta": {"hexsha": "25cd6761eab7b243597d2ae799507a242a99a97c", "size": 357, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hermite.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_stars_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-09-11T18:12:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T21:08:56.000Z", "max_issues_repo_path": "src/hermite.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_issues_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2018-02-15T06:32:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T15:59:07.000Z", "max_forks_repo_path": "src/hermite.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_forks_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:34:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:01:42.000Z", "avg_line_length": 15.5217391304, "max_line_length": 84, "alphanum_fraction": 0.5238095238, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7621562736409597}}
{"text": "# Hello World\n# variable substitution with the $ operator\nword = \"world\"\noutput = \"Hello $word !\"\nprintln(output)\n\n# tab autocomplete of LateX characters\nℵ = \"world\"\noutput = \"Hello $ℵ, again!\"\nprintln(output)\n\n# this extends to function evaluations as well\nα = 2\nprintln(\"The sine of $α is $(sin(α))\")\n\n# sidenote:\n# so if printing to a file you can directly direference the evalutioan\n# without passing it to an array which can then be printed.\n\ntypeof(α)\ntypeof(sin)\nmethods(sin)\n\n\n# built in type promotion\ncheck = int8(10)\ntypemax(Int8)\ntypeof(check)\ncheck = check *1232\ntypeof(check)\n\n# defining numerical functions\n# looks and feels very much like real math\n\nf(x) = 2*x + x^2 + 5\nf(3.4)\n\ng(x, y) = 34 + 2*x^2 + y^3\ng(2, 3)\n\n# passing function results to arrays\narr = Float64[]\nfor x in 1.3:0.01:3.9 push!(arr, f(x)) end\nprintln(arr)\nfor x in 1.3:0.01:9.9 push!(arr, f(x)) end\nprintln(arr)\n\narr2 = [f(i) for i in [1:2:10, 15]]\nprintln(arr2)\n\nusing ASCIIPlots\nlineplot([1.3:0.01:3.9], [1.3:0.01:3.9])\nlineplot([1:2:10], [f(i) for i in [1:2:10]])\n\n# working with imaginary numbers\na = 23\nb = (1 + 34im)\nc = a+b\n\ntypeof(a)\ntypeof(b)\ntypeof(c)\n\n# now c can be dereferenced into real and imaginary parts\nd = c.re\ne = c.im\n\ntypeof(d)\ntypeof(e)\n\n\nd = c*conj(c)\ntypeof(d)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "b9b7e349736a6288d8bd5855d12e895673844a11", "size": 1292, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/my_tutorial.jl", "max_stars_repo_name": "thehackerwithin/swinburne", "max_stars_repo_head_hexsha": "8014fafc2989f7663aff08531d1ae584c1a2333b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/my_tutorial.jl", "max_issues_repo_name": "thehackerwithin/swinburne", "max_issues_repo_head_hexsha": "8014fafc2989f7663aff08531d1ae584c1a2333b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/my_tutorial.jl", "max_forks_repo_name": "thehackerwithin/swinburne", "max_forks_repo_head_hexsha": "8014fafc2989f7663aff08531d1ae584c1a2333b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.4583333333, "max_line_length": 70, "alphanum_fraction": 0.6594427245, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.762156271392363}}
{"text": "\"\"\"\n```\nfind_threshold(Entropy(),counts,edges)\n```\nAn algorithm for finding the threshold value for a gray-level histogram using\nthe entropy of the histogram.\n\n# Output\n\nReturns the point in the `AbstractRange` which corresponds to the threshold bin in the histogram.\n\n# Details\n\nThis algorithm uses the entropy of a gray level histogram to produce a threshold\nvalue.\n\nLet ``f_1, f_2, \\\\ldots, f_I`` be the frequencies in the various bins of the\nhistogram and ``I`` the number of bins. With ``N = \\\\sum_{i=1}^{I}f_i``, let\n``p_i = \\\\frac{f_i}{N}`` (``i = 1, \\\\ldots, I``) denote the probability\ndistribution of gray levels. From this distribution one derives two additional\ndistributions. The first defined for discrete values ``1`` to ``s`` and the\nother, from ``s+1`` to ``I``. These distributions are\n\n```math\nA: \\\\frac{p_1}{P_s}, \\\\frac{p_2}{P_s}, \\\\ldots, \\\\frac{p_s}{P_s}\n\\\\quad \\\\text{and} \\\\quad\nB: \\\\frac{p_{s+1}}{1-P_s}, \\\\ldots, \\\\frac{p_n}{1-P_s}\n\\\\quad \\\\text{where} \\\\quad\nP_s = \\\\sum_{i=1}^{s}p_i.\n```\nThe entropies associated with each distribution are as follows:\n\n```math\nH(A) = \\\\ln(P_s) + \\\\frac{H_s}{P_s}\n```\n```math\nH(B) = \\\\ln(1-P_s) + \\\\frac{H_n-H_s}{1-P_s}\n```\n```math\n\\\\quad \\\\text{where} \\\\quad\nH_s = -\\\\sum_{i=1}^{s}p_i\\\\ln{p_i}\n\\\\quad \\\\text{and} \\\\quad\nH_n = -\\\\sum_{i=1}^{I}p_i\\\\ln{p_i}.\n```\n\n\nCombining these two entropy functions we have\n\n```math\n\\\\psi(s) = \\\\ln(P_s(1-P_s)) + \\\\frac{H_s}{P_s} + \\\\frac{H_n-H_s}{1-P_s}.\n```\nFinding the discrete value ``s`` which maximises the function ``\\\\psi(s)`` produces\nthe sought-after threshold value (i.e. the bin which determines the threshold).\n\nSee Section 4 of [1] for more details on the derivation of the entropy.\n\n# Options\n\n## Choices for `counts`\nYou can specify an `AbstractArray` which should be a 1D array of frequencies for\na histogram. You should submit the corresponding `edges` range for the bins of\nthe histogram. The function will throw an error if it detects that the `edges`\nand `counts` have different lengths.\n\n## Choices for `edges`\nYou can specify an `AbstractRange` which should be the corresponding range for\nthe bins of the histogram array passed into `counts`.\n\n# Example\n\n```julia\n\nusing TestImages, Images\n\nimg = testimage(\"cameraman\")\n# building a histogram with 256 bins\nedges, counts = build_histogram(img, 256)\n#=\n  The `counts` array stores at index 0 the frequencies that were below the\n  first bin edge. Since we are seeking a threshold over the interval\n  partitioned by `edges` we need to discard the first bin in `counts`\n  so that the dimensions of `edges` and `counts` match.\n=#\nfind_threshold(EntropyThresholding(), counts[1:end], edges)\n```\n\n# References\n[1] J. N. Kapur, P. K. Sahoo, and A. K. C. Wong, “A new method for gray-level picture thresholding using the entropy of the histogram,” *Computer Vision, Graphics, and Image Processing*, vol. 29, no. 1, p. 140, Jan. 1985.[doi:10.1016/s0734-189x(85)90156-2](https://doi.org/10.1016/s0734-189x%2885%2990156-2)\n\"\"\"\nfunction find_threshold(algorithm::Entropy, counts::AbstractArray, edges::AbstractRange)\n    if length(edges) != length(counts)\n        error(\"the lengths of edges and counts must match\")\n    end\n    nbins = length(counts)\n    pdf = counts ./ sum(counts)\n    Ψₘₐₓ = 0\n    Hₛ = H(pdf)\n    Hₙ = -1*Hₛ[nbins]\n    Pₛ = cumsum(pdf)\n    threshold_bin = 1\n    for i in 1:nbins\n        Pᵢ = Pₛ[i]\n        Hᵢ = -1*Hₛ[i]\n        Ψᵢ = log(Pᵢ*(1-Pᵢ)) + (Hᵢ/Pᵢ) + ((Hₙ-Hᵢ)/(1-Pᵢ))\n        if Ψᵢ > Ψₘₐₓ\n            Ψₘₐₓ = Ψᵢ\n            threshold_bin = i\n        end\n    end\n    edges[threshold_bin]\nend\n\nfunction H(pdf::AbstractArray)\n    h_dist = zeros(length(pdf))\n    for i in 1:length(pdf)\n        h_dist[i] = (pdf[i] != 0) ? pdf[i]*log(pdf[i]) : 0.0\n    end\n    cumsum(h_dist)\nend\n", "meta": {"hexsha": "a2fe040e0c6d25d6978c1cc5949666ae5f6465db", "size": 3758, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/entropy_thresholding.jl", "max_stars_repo_name": "johnnychen94/HistogramThresholding.jl", "max_stars_repo_head_hexsha": "4dca5c8d80f73b83e80d31d44374aa6d70d36e04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-02T22:00:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-02T22:00:20.000Z", "max_issues_repo_path": "src/entropy_thresholding.jl", "max_issues_repo_name": "johnnychen94/HistogramThresholding.jl", "max_issues_repo_head_hexsha": "4dca5c8d80f73b83e80d31d44374aa6d70d36e04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/entropy_thresholding.jl", "max_forks_repo_name": "johnnychen94/HistogramThresholding.jl", "max_forks_repo_head_hexsha": "4dca5c8d80f73b83e80d31d44374aa6d70d36e04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3166666667, "max_line_length": 307, "alphanum_fraction": 0.6689728579, "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7621562703812502}}
{"text": "\"\"\"\n    local_clustering_coefficient(g, v)\n    local_clustering_coefficient(g, vs)\n\nReturn the [local clustering coefficient](https://en.wikipedia.org/wiki/Clustering_coefficient)\nfor node `v` in graph `g`. If a list of vertices `vs` is specified, return a vector\nof coefficients for each node in the list.\n\"\"\"\nfunction local_clustering_coefficient(g::AbstractGraph, v::Integer)\n    ntriang, alltriang = local_clustering(g, v)\n\n    return alltriang == 0 ? 0. : ntriang * 1.0 / alltriang\nend\nlocal_clustering_coefficient(g::AbstractGraph, vs = vertices(g)) =\n    [local_clustering_coefficient(g, v) for v in vs]\n\n\n@doc_str \"\"\"\n    local_clustering(g, v)\n    local_clustering(g, vs)\n\nReturn a tuple `(a, b)`, where `a` is the number of triangles in the neighborhood\nof `v` and `b` is the maximum number of possible triangles. If a list of vertices\n`vs` is specified, return two vectors representing the number of triangles and\nthe maximum number of possible triangles, respectively, for each node in the list.\n\nThis function is related to the local clustering coefficient `r` by ``r=\\frac{a}{b}``.\n\"\"\"\nfunction local_clustering(g::AbstractGraph, v::Integer)\n    k = degree(g, v)\n    k <= 1 && return (0, 0)\n    neighs = neighbors(g, v)\n    c = 0\n    for i in neighs, j in neighs\n        i == j && continue\n        if has_edge(g, i, j)\n            c += 1\n        end\n    end\n    return is_directed(g) ? (c , k*(k-1)) : (div(c,2) , div(k*(k-1),2))\nend\nfunction local_clustering(g::AbstractGraph, vs = vertices(g))\n    ntriang = zeros(Int, length(vs))\n    nalltriang = zeros(Int, length(vs))\n    i = 0\n    for (i, v) in enumerate(vs)\n        ntriang[i], nalltriang[i] = local_clustering(g, v)\n    end\n    return ntriang, nalltriang\nend\n\n\n\"\"\"\n    triangles(g[, v])\n    triangles(g, vs)\n\nReturn the number of triangles in the neighborhood of node `v` in graph `g`.\nIf a list of vertices `vs` is specified, return a vector of number of triangles\nfor each node in the list. If no vertices are specified, return the number\nof triangles for each node in the graph.\n\"\"\"\ntriangles(g::AbstractGraph, v::Integer) = local_clustering(g, v)[1]\ntriangles(g::AbstractGraph, vs = vertices(g)) = local_clustering(g, vs)[1]\n\n\n\"\"\"\n    global_clustering_coefficient(g)\n\nReturn the [global clustering coefficient](https://en.wikipedia.org/wiki/Clustering_coefficient)\nof graph `g`.\n\"\"\"\nfunction global_clustering_coefficient(g::AbstractGraph)\n    c = 0\n    ntriangles = 0\n    for v in vertices(g)\n        neighs = neighbors(g, v)\n        for i in neighs, j in neighs\n            i == j && continue\n            if has_edge(g, i, j)\n                c += 1\n            end\n        end\n        k = degree(g, v)\n        ntriangles += k*(k-1)\n    end\n    ntriangles == 0 && return 1.\n    return c / ntriangles\nend\n", "meta": {"hexsha": "ef31fb2507c31c2d2c11d7517397f49f4cec8a4e", "size": 2782, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/community/clustering.jl", "max_stars_repo_name": "AsileBcd/JohnsonCycles", "max_stars_repo_head_hexsha": "4928bc05eaaad75a6d05a1390be9f5840c68705e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/community/clustering.jl", "max_issues_repo_name": "AsileBcd/JohnsonCycles", "max_issues_repo_head_hexsha": "4928bc05eaaad75a6d05a1390be9f5840c68705e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/community/clustering.jl", "max_forks_repo_name": "AsileBcd/JohnsonCycles", "max_forks_repo_head_hexsha": "4928bc05eaaad75a6d05a1390be9f5840c68705e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2584269663, "max_line_length": 96, "alphanum_fraction": 0.6603163192, "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8376199572530449, "lm_q1q2_score": 0.7621562634090866}}
{"text": "function B(; T=T, λ=λ)\n\n    k_B = 1.380649e-23\n    h   = 6.62607015e-34\n    c   = 2.99792458e8\n\n    aux1 = (2.0 * h * c^2) / λ^5\n\n    aux2 = (h * c) / (λ * k_B * T)\n\n    aux1 / (exp(aux2) - 1.0)\n\nend\n\nfunction scaledB(; s=s, T=T, λ=λ)\n\n    s * B(T=T, λ=λ)\n\nend\n\n\nfunction fitgalaxy()\n\n    wave = [433,550,790] * 10^-9\n\n    Y = [4.18, 8.60, 20.83]\n\n    # wave = [0.5;4;6] * 1000.0 * 1e-9\n    # Y = 1e-8*[B(T=5555.5,λ = 500*1e-9); B(T=5555.5,λ = 4000*1e-9);B(T=5555.5,λ = 6000*1e-9)]\n\n    function loss(T)\n\n        local V = map( w -> B(T=T,λ=w), wave)\n\n        local s = dot(V,Y) / dot(V,V)\n\n        local l = 0.0\n\n        for i in 1:length(Y)\n            l += (Y[i] - s*V[i])^2\n        end\n\n        return l\n\n    end\n\n\n    result = optimize(loss, 10, 10_000)\n\n    @show T = result.minimizer\n\n    V = map( w -> B(T=T, λ=w), wave)\n\n    s = dot(V,Y) / dot(V,V)\n\n    λ = collect(LinRange(100, 10_000, 100)) * 1e-9;\n\n    plot(λ, map(λ -> s*B(T=T,λ=λ), λ), \"g.\")\n\n    plot(wave, Y, \"ko\")\n\nend\n\n\n\nfunction galaxyposterior()\n\n    Tmin = 1000.0\n    Tmax = 10_000.0\n    σ(x) = 1.0 / (exp(-x) + 1)\n\n    wave = [433,550,790] * 10^-9\n\n    Y = [4.18, 8.60, 20.83]\n\n    # wave = [0.5;4;6] * 1000.0 * 1e-9\n    # Y = 1e-8*[B(T=5555.5,λ = 500*1e-9); B(T=5555.5,λ = 4000*1e-9);B(T=5555.5,λ = 6000*1e-9)]\n\n    function loss(T)\n\n        local V = map( w -> B(T=T,λ=w), wave)\n\n        local s = dot(V,Y) / dot(V,V)\n\n        local l = 0.0\n\n        for i in 1:length(Y)\n            l += (Y[i] - s*V[i])^2\n        end\n\n        return l\n\n    end\n\n\n    Trange = 1000:20:8_000\n\n    negloss = map(x -> -loss(x), Trange)\n\n    plot(Trange, negloss, \".\")\n\n    Trange[argmax(negloss)], maximum(negloss)\n\nend\n\n# λ = collect(LinRange(10,10_000,1000)) * 1e-9;\n# plot(λ, map(λ->B(T=4000.0,λ=λ), λ), \"g.\")\n# plot(λ, map(λ->B(T=5000.0,λ=λ), λ), \"b.\")\n", "meta": {"hexsha": "20309bb407ed7079ef887bfec01ef1236dadab48", "size": 1812, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/OLD/planck.jl", "max_stars_repo_name": "HITS-AIN/ProbabilisticFluxVariationGradient.jl", "max_stars_repo_head_hexsha": "36849fadeb3378b4bd4346830cc63757c90819e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/OLD/planck.jl", "max_issues_repo_name": "HITS-AIN/ProbabilisticFluxVariationGradient.jl", "max_issues_repo_head_hexsha": "36849fadeb3378b4bd4346830cc63757c90819e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OLD/planck.jl", "max_forks_repo_name": "HITS-AIN/ProbabilisticFluxVariationGradient.jl", "max_forks_repo_head_hexsha": "36849fadeb3378b4bd4346830cc63757c90819e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-03T15:52:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T15:52:10.000Z", "avg_line_length": 16.623853211, "max_line_length": 94, "alphanum_fraction": 0.4668874172, "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144275, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7621492834334495}}
{"text": "module CoordinateSystem\n\nusing LinearAlgebra\n\nexport CSys\n\nstruct CSys\n    O::Vector{Float64}\n    x::Vector{Float64}\n    y::Vector{Float64}\n    z::Vector{Float64}\n    T::Matrix{Float64} #transorm_matrix\nend\n\nfunction CSys(o::Vector{Float64},p₁::Vector{Float64},p₂::Vector{Float64})\n    v₁=p₁-o\n    v₂=p₂-o\n    if abs(v₁⋅v₂/norm(v₁)/norm(v₂))==1\n        error(\"Two vectors should not be parallel!\")\n    end\n    x=v₁/norm(v₁)\n    z=v₁×v₂\n    z=z/norm(z)\n    y=z×x\n    T=[reshape(x,1,3);\n        reshape(y,1,3);\n        reshape(z,1,3)]\n    CSys(o,x,y,z,T)\nend\n\nend\n", "meta": {"hexsha": "073c288d7c8e9dcce61357526b3f836f2ca4dc1d", "size": 562, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/assembly/CoordinateSystem.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Mozi.jl-938b0b66-b18d-59c3-b436-87bb841ccf42", "max_stars_repo_head_hexsha": "392c31542dc2c8cc95ea87e06c258be2f4d0de37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/assembly/CoordinateSystem.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Mozi.jl-938b0b66-b18d-59c3-b436-87bb841ccf42", "max_issues_repo_head_hexsha": "392c31542dc2c8cc95ea87e06c258be2f4d0de37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/assembly/CoordinateSystem.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Mozi.jl-938b0b66-b18d-59c3-b436-87bb841ccf42", "max_forks_repo_head_hexsha": "392c31542dc2c8cc95ea87e06c258be2f4d0de37", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5625, "max_line_length": 73, "alphanum_fraction": 0.6103202847, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7621492722694015}}
{"text": "#=  https://www.damtp.cam.ac.uk/research/dd/files/teaching/MB17Gog.pdf#subsubsection.1.3.4  =#\r\nusing Plots\r\n\r\nδt = 0.001\r\nT = 1\r\ntimes = 0:δt:T\r\nntimes = length(times)\r\n\r\nN = 10000\r\n\r\nS = zeros(size(times))\r\nS[1] = N - 1\r\nI = zeros(size(times))\r\nI[1] = 1\r\nR = zeros(size(times))\r\n\r\n# Rate of infection\r\nβ = 0.005\r\n# Rate of recovery\r\nν = 4\r\n\r\n# Randomness for σ > 0\r\nσ = 1\r\n\r\nfor i ∈ 2:ntimes\r\n    δS = - β * I[i-1] * S[i-1] * δt\r\n\tδR = ν * I[i-1] * δt\r\n\tδI = - δS - δR\r\n    S[i] = max(S[i-1] + δS * exp(σ * randn()), 0)\r\n    I[i] = max(I[i-1] + δI * exp(σ * randn()), 0)\r\n\tR[i] = max(R[i-1] + δR * exp(σ * randn()), 0)\r\n\tscale = (S[i] + I[i] + R[i])/N\r\n\tS[i] /= scale; I[i] /= scale; R[i] /= scale\r\nend\r\n\r\nlineplot = plot(times, [S I R], label = [\"Susceptible\" \"Infectious\" \"Recovered\"], color = [:gold :red :blue]);\r\nareaplot_ = areaplot(times, [S I R], label = [\"Susceptible\" \"Infectious\" \"Recovered\"], color = [:gold :red :blue]);\r\n\r\ndisplay(lineplot)\r\ndisplay(areaplot_)", "meta": {"hexsha": "f8298c20037436e77e96459a851052f29c4bb43a", "size": 976, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "casestudies/Modelling infectious diseases/mathematicalmodel.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "casestudies/Modelling infectious diseases/mathematicalmodel.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "casestudies/Modelling infectious diseases/mathematicalmodel.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 24.4, "max_line_length": 116, "alphanum_fraction": 0.5471311475, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.8031738057795402, "lm_q1q2_score": 0.7621454872075526}}
{"text": "# # [Lotka-Volterra Model](@id predation_example)\n#\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/examples/predation/lotka-volterra.ipynb)\n\nusing AlgebraicPetri\n\nusing OrdinaryDiffEq\nusing Plots\n\nusing Catlab\nusing Catlab.Graphics\nusing Catlab.WiringDiagrams\nusing Catlab.CategoricalAlgebra\nusing Catlab.Programs.RelationalPrograms\n\ndisplay_uwd(ex) = to_graphviz(ex, box_labels=:name, junction_labels=:variable, edge_attrs=Dict(:len=>\".75\"));\n\n# #### Step 1: Define the building block Petri nets needed to construct the model\n\nbirth_petri = Open(PetriNet(1, 1=>(1,1)));\nGraph(birth_petri)\n#-\npredation_petri = Open(PetriNet(2, (1,2)=>(2,2)));\nGraph(predation_petri)\n#-\ndeath_petri = Open(PetriNet(1, 1=>()));\nGraph(death_petri)\n\n\n# #### Step 2: Generate models using a relational syntax\n\nlotka_volterra = @relation (wolves, rabbits) begin\n  birth(rabbits)\n  predation(rabbits, wolves)\n  death(wolves)\nend\ndisplay_uwd(lotka_volterra)\n#-\nlv_dict = Dict(:birth=>birth_petri, :predation=>predation_petri, :death=>death_petri);\nlotka_petri = apex(oapply(lotka_volterra, lv_dict))\nGraph(lotka_petri)\n\n# Generate appropriate vector fields, define parameters, and visualize solution\n\nu0 = [100, 10];\np = [.3, .015, .7];\nprob = ODEProblem(vectorfield(lotka_petri),u0,(0.0,100.0),p);\nsol = solve(prob,Tsit5(),abstol=1e-8);\nplot(sol)\n\n# #### Step 3: Extend your model to handle more complex phenomena\n# such as a small food chain between little fish, big fish, and sharks\n\ndual_lv = @relation (fish, Fish, Shark) begin\n  birth(fish)\n  predation(fish, Fish)\n  death(Fish)\n  predation(Fish, Shark)\n  death(Shark)\nend\ndisplay_uwd(dual_lv)\n#-\ndual_lv_petri = apex(oapply(dual_lv, lv_dict))\nGraph(dual_lv_petri)\n\n# Generate a new solver, provide parameters, and analyze results\n\nu0 = [100, 10, 2];\np = [.3, .015, .7, .017, .35];\nprob = ODEProblem(vectorfield(dual_lv_petri),u0,(0.0,100.0),p);\nsol = solve(prob,Tsit5(),abstol=1e-6);\nplot(sol)", "meta": {"hexsha": "31dc14ddb3029e89ccee530e8abc98f74f1959a5", "size": 1969, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/predation/lotka-volterra.jl", "max_stars_repo_name": "AlgebraicJulia/AlgebraicPetri", "max_stars_repo_head_hexsha": "43318f0eec62c93aa29a7c07f9534030cad98a4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 44, "max_stars_repo_stars_event_min_datetime": "2020-07-03T20:45:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T19:33:22.000Z", "max_issues_repo_path": "examples/predation/lotka-volterra.jl", "max_issues_repo_name": "AlgebraicJulia/AlgebraicPetri", "max_issues_repo_head_hexsha": "43318f0eec62c93aa29a7c07f9534030cad98a4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2020-07-01T02:02:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-14T18:58:49.000Z", "max_forks_repo_path": "examples/predation/lotka-volterra.jl", "max_forks_repo_name": "AlgebraicJulia/AlgebraicPetri", "max_forks_repo_head_hexsha": "43318f0eec62c93aa29a7c07f9534030cad98a4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-07-16T19:14:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T17:37:26.000Z", "avg_line_length": 27.3472222222, "max_line_length": 130, "alphanum_fraction": 0.7353986795, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875641, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7621454772764304}}
{"text": "\ninclude(\"../optimizers/trustregion.jl\")\ninclude(\"../utils/functions.jl\")\nusing Gadfly\n\nxvals = trust_region([3.;4.], 6, 1, 0.1, fenton, fenton_g, fenton_h, \n    2000, \"dogleg\");\ncvals = trust_region([3.;4.], 6, 1, 0.1, fenton, fenton_g, fenton_h, \n    2000, \"cg_steihaug\");\n\nprintln(xvals[end])\n\nnsamps = length(xvals)\nnsamps2 = length(cvals)\n\nfx = [fenton(xvals[i]) for i in 1:nsamps]\nfx2 = [fenton(cvals[i]) for i in 1:nsamps2]\n\n\nGadfly.plot(layer(x=1:nsamps, y=fx, Geom.line, Theme(default_color=color(\"blue\"))),\nlayer(x=1:nsamps2, y=fx2, Geom.line, Theme(default_color=color(\"red\"))),\n#layer(x=1:nsamps3, y=fx3, Geom.line, Theme(default_color=color(\"orange\"))),\nGuide.xlabel(\"iteration\"), Guide.ylabel(\"f(x)\"), Guide.title(\"Value of function\"),\nGuide.manual_color_key(\"Legend\", [\"Newton dogleg\", \"Steihaug-CG\", \"quasi-Newton SR1\"], [\"blue\", \"red\", \"orange\"]),\nScale.x_log10, Scale.y_log10)\n\nnsamps = length(xvals)\n\ngrads = [norm(fenton_g(xvals[i]), 2) for i in 1:nsamps]\ngrads2 = [norm(fenton_g(cvals[i]), 2) for i in 1:nsamps2]\n#grads3 = [norm(fenton_g(cvals[i]), 2) for i in 1:nsamps3]\n\nGadfly.plot(\nlayer(x=1:nsamps-2, y=grads[2:nsamps-1,:]./grads[1:nsamps-2,:], Geom.line, Theme(default_color=color(\"blue\"))),\nlayer(x=1:nsamps2-2, y=grads2[2:nsamps2-1,:]./grads2[1:nsamps2-2,:], Geom.line, Theme(default_color=color(\"red\"))),\n#layer(x=1:nsamps3-1, y=grads3[2:nsamps3,:]./grads3[1:nsamps3-1,:], Geom.line, Theme(default_color=color(\"orange\"))),\nGuide.xlabel(\"iteration\"), Guide.ylabel(\"gradient norm ratios\"), Guide.title(\"gradient norm ratios\"),\nGuide.manual_color_key(\"Legend\", [\"Newton dogleg\", \"Steihaug-CG\", \"quasi-Newton SR1\"], [\"blue\", \"red\", \"orange\"]),\nScale.x_log10, Scale.y_log10)\n\nGadfly.plot(layer(x=1:nsamps, y=grads, Geom.line, Theme(default_color=color(\"blue\"))),\nlayer(x=1:nsamps2, y=grads2, Geom.line, Theme(default_color=color(\"red\"))),\n#layer(x=1:nsamps3, y=grads3, Geom.line, Theme(default_color=color(\"orange\"))),\n    Guide.xlabel(\"iteration\"), Guide.ylabel(\"gradient norm\"), Guide.title(\"gradient norms\"),\nGuide.manual_color_key(\"Legend\", [\"Newton dogleg\", \"Steihaug-CG\", \"quasi-Newton SR1\"], [\"blue\", \"red\", \"orange\"]),\n    Scale.x_log10, Scale.y_log10)\n\nxvals = trust_region(randn(100), 6, 3, 0.1, rosenbrock, \n    rosenbrock_g, rosenbrock_h, 1000, \"dogleg\");\ncvals = trust_region(randn(100), 6, 3, 0.1, rosenbrock, \n    rosenbrock_g, rosenbrock_h, 1000, \"cg_steihaug\");\n\nnsamps = length(xvals)\nnsamps2 = length(cvals)\n\nfunc = rosenbrock\nfunc_g = rosenbrock_g\n\nfx = [func(xvals[i]) for i in 1:nsamps]\nfx2 = [func(cvals[i]) for i in 1:nsamps2]\n\n\nGadfly.plot(layer(x=1:nsamps, y=fx, Geom.line, Theme(default_color=color(\"blue\"))),\nlayer(x=1:nsamps2, y=fx2, Geom.line, Theme(default_color=color(\"red\"))),\n#layer(x=1:nsamps3, y=fx3, Geom.line, Theme(default_color=color(\"orange\"))),\nGuide.xlabel(\"iteration\"), Guide.ylabel(\"f(x)\"), Guide.title(\"Value of function\"),\nGuide.manual_color_key(\"Legend\", [\"Newton dogleg\", \"Steihaug-CG\", \"quasi-Newton SR1\"], \n    [\"blue\", \"red\", \"orange\"]),\nScale.x_log10, Scale.y_log10)\n\nnsamps = length(xvals)\nnsamps2 = length(cvals)\n\ngrads = [norm(func_g(xvals[i]), 2) for i in 1:nsamps]\ngrads2 = [norm(func_g(cvals[i]), 2) for i in 1:nsamps2]\n#grads3 = [norm(func_g(cvals[i]), 2) for i in 1:nsamps3]\n\n\nGadfly.plot(\nlayer(x=1:nsamps-2, y=grads[2:nsamps-1,:]./grads[1:nsamps-2,:], Geom.line, Theme(default_color=color(\"blue\"))),\nlayer(x=1:nsamps2-2, y=grads2[2:nsamps2-1,:]./grads2[1:nsamps2-2,:], Geom.line, Theme(default_color=color(\"red\"))),\n#layer(x=1:nsamps3-1, y=grads3[2:nsamps3,:]./grads3[1:nsamps3-1,:], Geom.line, Theme(default_color=color(\"orange\"))),\nGuide.xlabel(\"iteration\"), Guide.ylabel(\"gradient norm ratios\"), Guide.title(\"gradient norm ratios\"),\nGuide.manual_color_key(\"Legend\", [\"Newton dogleg\", \"Steihaug-CG\", \"quasi-Newton SR1\"], [\"blue\", \"red\", \"orange\"]),\nScale.x_log10, Scale.y_log10)\n\nGadfly.plot(layer(x=1:nsamps, y=grads, Geom.line, Theme(default_color=color(\"blue\"))),\nlayer(x=1:nsamps2, y=grads2, Geom.line, Theme(default_color=color(\"red\"))),\n#layer(x=1:nsamps3, y=grads3, Geom.line, Theme(default_color=color(\"orange\"))),\n    Guide.xlabel(\"iteration\"), Guide.ylabel(\"gradient norm\"), Guide.title(\"gradient norms\"),\nGuide.manual_color_key(\"Legend\", [\"Newton dogleg\", \"Steihaug-CG\", \"quasi-Newton SR1\"], [\"blue\", \"red\", \"orange\"]),\n    Scale.x_log10, Scale.y_log10)\n\nxvals = trust_region(ones(50)*10, 6, 3, 0.1, cute, cute_g, cute_h, 2000, \"dogleg\");\ncvals = trust_region(ones(50)*10, 6, 3, 0.1, cute, cute_g, cute_h, 2000, \"cg_steihaug\");\n\nnsamps = length(xvals)\nnsamps2 = length(cvals)\n\nfunc = cute\nfunc_g = cute_g\n\nfx = [func(xvals[i]) for i in 1:nsamps]\nfx2 = [func(cvals[i]) for i in 1:nsamps2]\n\n\nGadfly.plot(layer(x=1:nsamps, y=fx, Geom.line, Theme(default_color=color(\"blue\"))),\nlayer(x=1:nsamps2, y=fx2, Geom.line, Theme(default_color=color(\"red\"))),\n#layer(x=1:nsamps3, y=fx3, Geom.line, Theme(default_color=color(\"orange\"))),\nGuide.xlabel(\"iteration\"), Guide.ylabel(\"f(x)\"), Guide.title(\"Value of function\"),\nGuide.manual_color_key(\"Legend\", [\"Newton dogleg\", \"Steihaug-CG\", \"quasi-Newton SR1\"], [\"blue\", \"red\", \"orange\"]),\nScale.x_log10, Scale.y_log10)\n\nnsamps = length(xvals)\n\ngrads = [norm(func_g(xvals[i]), 2) for i in 1:nsamps]\ngrads2 = [norm(func_g(cvals[i]), 2) for i in 1:nsamps2]\n#grads3 = [norm(func_g(cvals[i]), 2) for i in 1:nsamps3]\n\n\nGadfly.plot(\nlayer(x=1:nsamps-1, y=grads[2:nsamps,:]./grads[1:nsamps-1,:], Geom.line, Theme(default_color=color(\"blue\"))),\nlayer(x=1:nsamps2-1, y=grads2[2:nsamps2,:]./grads2[1:nsamps2-1,:], Geom.line, Theme(default_color=color(\"red\"))),\n#layer(x=1:nsamps3-1, y=grads3[2:nsamps3,:]./grads3[1:nsamps3-1,:], Geom.line, Theme(default_color=color(\"orange\"))),\nGuide.xlabel(\"iteration\"), Guide.ylabel(\"gradient norm ratios\"), Guide.title(\"gradient norm ratios\"),\nGuide.manual_color_key(\"Legend\", [\"Newton dogleg\", \"Steihaug-CG\", \"quasi-Newton SR1\"], [\"blue\", \"red\", \"orange\"]),\nScale.x_log10, Scale.y_log10)\n\nGadfly.plot(layer(x=1:nsamps, y=grads, Geom.line, Theme(default_color=color(\"blue\"))),\nlayer(x=1:nsamps2, y=grads2, Geom.line, Theme(default_color=color(\"red\"))),\n#layer(x=1:nsamps3, y=grads3, Geom.line, Theme(default_color=color(\"orange\"))),\n    Guide.xlabel(\"iteration\"), Guide.ylabel(\"gradient norm\"), Guide.title(\"gradient norms\"),\nGuide.manual_color_key(\"Legend\", [\"Newton dogleg\", \"Steihaug-CG\", \"quasi-Newton SR1\"], [\"blue\", \"red\", \"orange\"]),\n    Scale.x_log10, Scale.y_log10)\n\nxvals = trust_region(ones(50)*10, 6, 3, 0.1, cute2, cute2_g, cute2_h, 2000, \"dogleg\");\ncvals = trust_region(ones(50)*10, 6, 3, 0.1, cute2, cute2_g, cute2_h, 2000, \"cg_steihaug\");\n\nnsamps = length(xvals)\nnsamps2 = length(cvals)\n\nfunc = cute2\nfunc_g = cute2_g\n\nfx = [func(xvals[i]) for i in 1:nsamps]\nfx2 = [func(cvals[i]) for i in 1:nsamps2]\n\n\nGadfly.plot(layer(x=1:nsamps, y=fx, Geom.line, Theme(default_color=color(\"blue\"))),\nlayer(x=1:nsamps2, y=fx2, Geom.line, Theme(default_color=color(\"red\"))),\n#layer(x=1:nsamps3, y=fx3, Geom.line, Theme(default_color=color(\"orange\"))),\nGuide.xlabel(\"iteration\"), Guide.ylabel(\"f(x)\"), Guide.title(\"Value of function\"),\nGuide.manual_color_key(\"Legend\", [\"Newton dogleg\", \"Steihaug-CG\", \"quasi-Newton SR1\"], [\"blue\", \"red\", \"orange\"]),\nScale.x_log10, Scale.y_log10)\n\nnsamps = length(xvals)\n\ngrads = [norm(func_g(xvals[i]), 2) for i in 1:nsamps]\ngrads2 = [norm(func_g(cvals[i]), 2) for i in 1:nsamps2]\n#grads3 = [norm(func_g(cvals[i]), 2) for i in 1:nsamps3]\n\n\nGadfly.plot(\nlayer(x=1:nsamps-1, y=grads[2:nsamps,:]./grads[1:nsamps-1,:], Geom.line, Theme(default_color=color(\"blue\"))),\nlayer(x=1:nsamps2-1, y=grads2[2:nsamps2,:]./grads2[1:nsamps2-1,:], Geom.line, Theme(default_color=color(\"red\"))),\n#layer(x=1:nsamps3-1, y=grads3[2:nsamps3,:]./grads3[1:nsamps3-1,:], Geom.line, Theme(default_color=color(\"orange\"))),\nGuide.xlabel(\"iteration\"), Guide.ylabel(\"gradient norm ratios\"), Guide.title(\"gradient norm ratios\"),\nGuide.manual_color_key(\"Legend\", [\"Newton dogleg\", \"Steihaug-CG\", \"quasi-Newton SR1\"], [\"blue\", \"red\", \"orange\"]),\nScale.x_log10, Scale.y_log10)\n\nGadfly.plot(layer(x=1:nsamps, y=grads, Geom.line, Theme(default_color=color(\"blue\"))),\nlayer(x=1:nsamps2, y=grads2, Geom.line, Theme(default_color=color(\"red\"))),\n#layer(x=1:nsamps3, y=grads3, Geom.line, Theme(default_color=color(\"orange\"))),\n    Guide.xlabel(\"iteration\"), Guide.ylabel(\"gradient norm\"), Guide.title(\"gradient norms\"),\nGuide.manual_color_key(\"Legend\", [\"Newton dogleg\", \"Steihaug-CG\", \"quasi-Newton SR1\"], [\"blue\", \"red\", \"orange\"]),\n    Scale.x_log10, Scale.y_log10)\n\n\n", "meta": {"hexsha": "365aad586ede573fda2ff44f1fe8377ad4af7604", "size": 8525, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jupyter/trust_region.jl", "max_stars_repo_name": "dicai/descent.jl", "max_stars_repo_head_hexsha": "f684b69f6c8dadc86402fc465455b51c0484cedf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-08-12T22:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-25T01:37:28.000Z", "max_issues_repo_path": "jupyter/trust_region.jl", "max_issues_repo_name": "dicai/descent.jl", "max_issues_repo_head_hexsha": "f684b69f6c8dadc86402fc465455b51c0484cedf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jupyter/trust_region.jl", "max_forks_repo_name": "dicai/descent.jl", "max_forks_repo_head_hexsha": "f684b69f6c8dadc86402fc465455b51c0484cedf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.625698324, "max_line_length": 117, "alphanum_fraction": 0.6929032258, "num_tokens": 3028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.762086843614213}}
{"text": "# period doubling route\nusing DrWatson\n@quickactivate \"NonlinearDynamicsTextbook\"\ninclude(srcdir(\"style.jl\"))\nusing DynamicalSystems, PyPlot\n\nfig = figure(figsize = (figx, 2figy))\naxlo = fig.add_subplot(3, 1, 1)\naxro = fig.add_subplot(3, 1, 3)\n\nzoomaxs = []\nfor i in 1:3\n\tpush!(zoomaxs, fig.add_subplot(3, 3, 3+i))\nend\n\naxlo.clear()\nds = Systems.logistic(0.5)\ni = 1\npvalues = range(2.5, 4; length = 2001)\nn = 2000\nTtr = 2000\np_index = 1\noutput = orbitdiagram(ds, i, p_index, pvalues; n = n, Ttr = Ttr)\n\nL = length(pvalues)\nx = Vector{Float64}(undef, n*L)\ny = copy(x)\nfor j in 1:L\n    x[(1 + (j-1)*n):j*n] .= pvalues[j]\n    y[(1 + (j-1)*n):j*n] .= output[j]\nend\naxlo.plot(x, y, ls = \"None\", ms = 0.5, color = \"black\", marker = \"o\", alpha = 0.01)\naxlo.set_xlim(pvalues[1], pvalues[end]); axlo.set_ylim(0,1)\naxlo.set_ylabel(\"\\$x\\$\", labelpad = 10)\naxlo.set_xticks(2.5:0.5:4)\naxlo.set_yticks(0:0.2:1)\naxlo.set_xlabel(\"\\$r\\$\"; labelpad = -20)\naxlo.text(2.6, 0.1, \"logistic map\", size = 36)\nr∞ = 3.56995\naxlo.axvline(r∞; color = \"C4\", alpha = 0.7, ls = \"dashed\")\n\n# Zoomin boxes\nzbox1 = ((3.629, 0.295), (3.640, 0.32))\nzbox2 = ((3.6338, 0.304), (3.6342, 0.3065))\nzbox3 = ((3.63407, 0.30495), (3.63408, 0.3052))\nallboxes = (zbox1, zbox2, zbox3)\nfor (k, zbox) in enumerate(allboxes)\n\tpval = range(zbox[1][1], zbox[2][1]; length = 1001)\n\tnsm = n÷3\n\toutput = orbitdiagram(ds, i, p_index, pval;\n\t\tn=nsm, Ttr, ulims = (zbox[1][2], zbox[2][2])\n\t)\n\tL = length(pval)\n\tx = Vector{Float64}(undef, nsm*L)\n\ty = copy(x)\n\tfor j in 1:L\n\t    x[(1 + (j-1)*nsm):j*nsm] .= pval[j]\n\t    y[(1 + (j-1)*nsm):j*nsm] .= output[j]\n\tend\n\tzoomaxs[k].clear()\n\tzoomaxs[k].plot(x, y, ls = \"None\", ms = 0.5, color = \"black\", marker = \"o\", alpha = 0.01)\n\tzoomaxs[k].set_xlim(zbox[1][1], zbox[2][1])\n\tzoomaxs[k].set_ylim(zbox[1][2], zbox[2][2])\n\tzoomaxs[k].axis(\"off\")\nend\n\nzbox0 = ((pvalues[1], 0.0), (pvalues[end], 1.0))\nallzoomaxs = [axlo, zoomaxs...]\nfor i in 1:3\n\torigin = allzoomaxs[i]\n\tzoomin = allzoomaxs[i+1]\n    zbox = allboxes[i]\n\tc = (\"C1\", \"C3\", \"C5\")[i]\n    axis_zoomin!(zoomin, origin, zbox, zbox, c;\tconnect_lines = i > 1, lw = 4.0)\nend\n\n# arrow indicator\naxlo.arrow(\n\t(zbox1[1][1] + zbox1[2][1])/2, 0.05, 0, zbox1[2][2] - 0.1;\n\tcolor = \"C1\", width = 0.005, length_includes_head = true, head_length = 0.1\n)\n\n# Roessler\nro = Systems.roessler()\npvalues = range(1.5, stop = 5.18, length = 2001)\ni = 1\nplane = (2, 0.0)\ntf = 4000.0\np_index = 3\noutput = produce_orbitdiagram(ro, plane, i, p_index, pvalues;\n                              tfinal = tf, Ttr = 2000.0)\n\nfor (j, p) in enumerate(pvalues)\n    axro.plot(fill(p, length(output[j])), output[j], lw = 0,\n    marker = \"o\", ms = 0.2, color = \"black\", alpha = 0.1)\nend\naxro.set_xlim(pvalues[1], pvalues[end]);\naxro.set_ylim(minimum(minimum(o) for o in output), maximum(maximum(o) for o in output))\naxro.set_ylabel(\"\\$x\\$ (at section)\", labelpad = 25)\naxro.set_xlabel(\"\\$c\\$\"; labelpad = -20)\naxro.set_yticks(3:3:9)\naxro.text(1.7, 7, \"Rössler system\", size = 36)\nfig.tight_layout(pad=0.3)\nfig.subplots_adjust(hspace = 0.3, wspace = 0.1)\nadd_identifiers!(fig, (axlo, axro))\nwsave(plotsdir(\"4\", \"orbit_diagrams\"), fig)", "meta": {"hexsha": "94588fa96f9ea3e8c6a1e4aa1ceead4a068d51de", "size": 3136, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "figure_generation/4/4.5.jl", "max_stars_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_stars_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 88, "max_stars_repo_stars_event_min_datetime": "2021-07-18T20:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T09:23:53.000Z", "max_issues_repo_path": "figure_generation/4/4.5.jl", "max_issues_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_issues_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figure_generation/4/4.5.jl", "max_forks_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_forks_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-07-28T18:49:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:45:11.000Z", "avg_line_length": 29.5849056604, "max_line_length": 90, "alphanum_fraction": 0.618622449, "num_tokens": 1333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797081106935, "lm_q2_score": 0.8652240686758841, "lm_q1q2_score": 0.762086834193185}}
{"text": "# Sampling from manifolds. Currently used for testing only.\nabstract type Manifold{Int, T<:AbstractFloat} end\n\n# ............................................................................ #\nstruct Torus{T} <: Manifold{3, T}\n    R::T\n    r::T\n    center::Tuple{T, T, T}\nend\n\nfunction Torus(R, r)\n    args = convert.(AbstractFloat, (R, r))\n    z = zero(eltype(args))\n    Torus(args..., (z, z, z))\nend\n\n(t::Torus)(θ, φ) =\n    ((t.R + t.r*cos(θ)) * cos(φ), (t.R + t.r*cos(θ)) * sin(φ), t.r * sin(θ)) .+\n    t.center\n\n# ............................................................................ #\nstruct AsymTorus{T} <: Manifold{3, T}\n    R::T\n    r_large::T\n    r_small::T\n    center::Tuple{T, T, T}\nend\n\nfunction AsymTorus(R, r1, r2)\n    args = convert.(AbstractFloat, (R, r1, r2))\n    z = zero(eltype(args))\n    AsymTorus(args..., (z, z, z))\nend\n\nfunction (at::AsymTorus)(θ, φ)\n    R = at.R\n    r_large = at.r_large\n    r_small = at.r_small\n\n    r = (r_large - r_small) * (cos(φ) + 1)/2 + r_small\n    ((R + r*cos(θ)) * cos(φ), (R + r*cos(θ)) * sin(φ), r*sin(θ)) .+ at.center\nend\n\n# ............................................................................ #\nstruct Sphere{T} <: Manifold{3, T}\n    r::T\n    center::Tuple{T, T, T}\nend\n\nfunction Sphere(r)\n    arg = convert(AbstractFloat, r)\n    z = zero(typeof(arg))\n    Sphere(arg, (z, z, z))\nend\n\n(s::Sphere)(θ, φ) =\n    (s.r*cos(θ) * sin(φ), s.r*sin(θ) * sin(φ), s.r*cos(φ)) .+ s.center\n\n# ............................................................................ #\nstruct Circle{T} <: Manifold{2, T}\n    r::T\n    center::Tuple{T, T}\nend\n\nfunction Circle(r)\n    arg = convert(AbstractFloat, r)\n    z = zero(typeof(arg))\n    Circle(arg, (z, z))\nend\n\n(c::Circle)(θ) = (c.r * cos(θ), c.r * sin(θ)) .+ c.center\n\n# ............................................................................ #\n# Uniformly sampling n points from a manifold returning D by n matrix.\n# TODO: Circular noise? Overenginnered as it is?\nfunction Base.rand(m::Manifold{D, T}, n=1; noise=0) where {D, T}\n    res = zeros(T, D, n)\n    for i in 1:n\n        pars = 2π .* rand(D-1)\n        res[:, i] .= m(pars...) .+ (rand(D) - 0.5) * noise\n    end\n    res\nend\n", "meta": {"hexsha": "96acfe64c49bc10de14eb2cd951cc3dea827a0c6", "size": 2185, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/manifolds.jl", "max_stars_repo_name": "mtsch/IntrinsicMetrics.jl", "max_stars_repo_head_hexsha": "2696a086ffa41a927fc099d32f950d6131ad8f6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-24T15:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-24T15:14:27.000Z", "max_issues_repo_path": "test/manifolds.jl", "max_issues_repo_name": "mtsch/IntrinsicMetrics.jl", "max_issues_repo_head_hexsha": "2696a086ffa41a927fc099d32f950d6131ad8f6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/manifolds.jl", "max_forks_repo_name": "mtsch/IntrinsicMetrics.jl", "max_forks_repo_head_hexsha": "2696a086ffa41a927fc099d32f950d6131ad8f6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0119047619, "max_line_length": 80, "alphanum_fraction": 0.4562929062, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7620420029979449}}
{"text": "#Ipopt.jl example - This is taken from the documentation available on:\r\n# http://ipoptjl.readthedocs.org/en/latest/ipopt.html#\r\n\r\n# Install Package if you don't have it\r\nPkg.add(\"Ipopt\")\r\n\r\ntic()\r\n# Load the package\r\nusing Ipopt\r\n\r\n# HS071\r\n# min x1 * x4 * (x1 + x2 + x3) + x3\r\n# st  x1 * x2 * x3 * x4 >= 25\r\n#     x1^2 + x2^2 + x3^2 + x4^2 = 40\r\n#     1 <= x1, x2, x3, x4 <= 5\r\n# Start at (1,5,5,1)\r\n# End at (1.000..., 4.743..., 3.821..., 1.379...)\r\n\r\n## Set the number of arguments to solve for and bounds for these\r\n## Aside for new Julia users: the '.0' after each number is important - it tells Julia\r\n## that the vectors x_L, etc are of Float type.\r\n## Note that Julia is a functional language, with methods (e.g. a function) working for the types\r\n## for which it is defined (e.g. integer, Float). So, a function defined for an integer will not\r\n## work if you enter a Float variable, and vice-versa.\r\nn = 4\r\nx_L = [1.0, 1.0, 1.0, 1.0]\r\nx_U = [5.0, 5.0, 5.0, 5.0]\r\n\r\n\r\n# Set the number of constraints and bounds on these - Note that equality\r\n# constraints can be accommodated for by setting the upper bound = lower bound\r\nm = 2\r\ng_L = [25.0, 40.0]\r\ng_U = [2.0e19, 40.0]\r\n\r\n# Set the objective function - Returns the value of the objective function at the current solution x\r\n# Note that the '::Vector{Float64}' below defines the type of x. This is a Julia-specific thing, and\r\n# need not be defined. The function would be created even without including the type for x.\r\nfunction eval_f(x::Vector{Float64})\r\n  return x[1] * x[4] * (x[1] + x[2] + x[3]) + x[3]\r\nend\r\n\r\n# Set the constraint set - Sets the value of the constraint functions g at the current solution x\r\n# Note that there is no need to create a separate vector g in which to save the constraints.\r\n# The values of g are set 'in-place'\r\nfunction eval_g(x::Vector{Float64}, g::Vector{Float64})\r\n  g[1] = x[1]   * x[2]   * x[3]   * x[4]\r\n  g[2] = x[1]^2 + x[2]^2 + x[3]^2 + x[4]^2\r\nend\r\n\r\n# Gradient of the objective function - Sets the value of the gradient of the objective function at the current solution x\r\n# Note that there is no need to create a vector grad_f to fill in. The values of grad_f are set 'in-place'.\r\nfunction eval_grad_f(x::Vector{Float64}, grad_f::Vector{Float64})\r\n  grad_f[1] = x[1] * x[4] + x[4] * (x[1] + x[2] + x[3])\r\n  grad_f[2] = x[1] * x[4]\r\n  grad_f[3] = x[1] * x[4] + 1\r\n  grad_f[4] = x[1] * (x[1] + x[2] + x[3])\r\nend\r\n\r\n\r\n# Gradient of the constraint set (Jacobian matrix). There are two ways of setting this:\r\n# (1) Under the ':Structure' mode, indicate the rows and columns with non-zero values (i.e. tell Ipopt\r\n# about the sparsity structure of the matrix)\r\n# (2) Undet the ':Values' mode, tell it the actual values.\r\n# Each non-zero value is indexed, starting from 1.\r\n###########################################\r\n# General specification is as follows:\r\n###########################################\r\n# function eval_jac_g(\r\n#  x::Vector{Float64},         # Current solution\r\n#  mode,                       # Either :Structure or :Values\r\n#  rows::Vector{Int32},        # Sparsity structure - row indices\r\n#  cols::Vector{Int32},        # Sparsity structure - column indices\r\n#  values::Vector{Float64})    # The values of the Hessian\r\n\r\n#  if mode == :Structure\r\n    # rows[...] = ...\r\n    # ...\r\n    # cols[...] = ...\r\n#  else\r\n    # values[...] = ...\r\n#  end\r\n# end\r\n#############################################\r\nfunction eval_jac_g(x, mode, rows, cols, values)\r\n  if mode == :Structure\r\n    # Constraint (row) 1\r\n    rows[1] = 1; cols[1] = 1\r\n    rows[2] = 1; cols[2] = 2\r\n    rows[3] = 1; cols[3] = 3\r\n    rows[4] = 1; cols[4] = 4\r\n    # Constraint (row) 2\r\n    rows[5] = 2; cols[5] = 1\r\n    rows[6] = 2; cols[6] = 2\r\n    rows[7] = 2; cols[7] = 3\r\n    rows[8] = 2; cols[8] = 4\r\n  else\r\n    # Constraint (row) 1\r\n    values[1] = x[2]*x[3]*x[4]  # 1,1\r\n    values[2] = x[1]*x[3]*x[4]  # 1,2\r\n    values[3] = x[1]*x[2]*x[4]  # 1,3\r\n    values[4] = x[1]*x[2]*x[3]  # 1,4\r\n    # Constraint (row) 2\r\n    values[5] = 2*x[1]  # 2,1\r\n    values[6] = 2*x[2]  # 2,2\r\n    values[7] = 2*x[3]  # 2,3\r\n    values[8] = 2*x[4]  # 2,4\r\n  end\r\nend\r\n\r\n# Hessian of the Lagrangian - this is an optional object. In terms of the Julia syntax, it is\r\n# similar to the Jacobian.\r\n# The general definition and types for the objects in the function below are:\r\n# function eval_h(\r\n# x::Vector{Float64},         # Current solution\r\n# mode,                       # Either :Structure or :Values\r\n# rows::Vector{Int32},        # Sparsity structure - row indices\r\n# cols::Vector{Int32},        # Sparsity structure - column indices\r\n# obj_factor::Float64,        # Lagrangian multiplier for objective\r\n# lambda::Vector{Float64},    # Multipliers for each constraint\r\n# values::Vector{Float64})    # The values of the Hessian\r\n# if....else...end            # the function text goes here\r\n# end                         # close the function\r\n\r\nfunction eval_h(x, mode, rows, cols, obj_factor, lambda, values)\r\n  if mode == :Structure\r\n    # Symmetric matrix, fill the lower left triangle only\r\n    idx = 1\r\n    for row = 1:4\r\n      for col = 1:row\r\n        rows[idx] = row\r\n        cols[idx] = col\r\n        idx += 1\r\n      end\r\n    end\r\n  else\r\n    # Again, only lower left triangle\r\n    # Objective\r\n    values[1] = obj_factor * (2*x[4])  # 1,1\r\n    values[2] = obj_factor * (  x[4])  # 2,1\r\n    values[3] = 0                      # 2,2\r\n    values[4] = obj_factor * (  x[4])  # 3,1\r\n    values[5] = 0                      # 3,2\r\n    values[6] = 0                      # 3,3\r\n    values[7] = obj_factor * (2*x[1] + x[2] + x[3])  # 4,1\r\n    values[8] = obj_factor * (  x[1])  # 4,2\r\n    values[9] = obj_factor * (  x[1])  # 4,3\r\n    values[10] = 0                     # 4,4\r\n\r\n    # First constraint\r\n    values[2] += lambda[1] * (x[3] * x[4])  # 2,1\r\n    values[4] += lambda[1] * (x[2] * x[4])  # 3,1\r\n    values[5] += lambda[1] * (x[1] * x[4])  # 3,2\r\n    values[7] += lambda[1] * (x[2] * x[3])  # 4,1\r\n    values[8] += lambda[1] * (x[1] * x[3])  # 4,2\r\n    values[9] += lambda[1] * (x[1] * x[2])  # 4,3\r\n\r\n    # Second constraint\r\n    values[1]  += lambda[2] * 2  # 1,1\r\n    values[3]  += lambda[2] * 2  # 2,2\r\n    values[6]  += lambda[2] * 2  # 3,3\r\n    values[10] += lambda[2] * 2  # 4,4\r\n  end\r\nend\r\n\r\n# Creates and returns an IpoptProblem with the given options. Raises error if something goes wrong during construction.\r\n# If you do not provide a callback for the Hessian, you must set the Hessian approximation option:\r\n# addOption(prob, \"hessian_approximation\", \"limited-memory\")\r\nprob = createProblem(n, x_L, x_U, m, g_L, g_U, 8, 10,\r\n                     eval_f, eval_g, eval_grad_f, eval_jac_g, eval_h)\r\n\r\n# Set starting solution\r\nprob.x = [1.0, 5.0, 5.0, 1.0]\r\n\r\n# Solve\r\nstatus = solveProblem(prob)\r\n\r\n# Display the solution\r\nprintln(Ipopt.ApplicationReturnStatus[status])\r\nprintln(prob.x)\r\nprintln(prob.obj_val)\r\n\r\ntoc()\r\n", "meta": {"hexsha": "27b878f710c85e5c25fa1eea05952f289f3c0399", "size": 6912, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JuMP/ipoptexample.jl", "max_stars_repo_name": "floswald/ucl-econ-julia", "max_stars_repo_head_hexsha": "c0b9077382d4245fb1276ae2f517cc9372259c25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-08-18T00:50:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-18T00:50:53.000Z", "max_issues_repo_path": "JuMP/ipoptexample.jl", "max_issues_repo_name": "floswald/ucl-econ-julia", "max_issues_repo_head_hexsha": "c0b9077382d4245fb1276ae2f517cc9372259c25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-05-01T13:10:23.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-14T08:44:31.000Z", "max_forks_repo_path": "JuMP/ipoptexample.jl", "max_forks_repo_name": "floswald/ucl-econ-julia", "max_forks_repo_head_hexsha": "c0b9077382d4245fb1276ae2f517cc9372259c25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-04-25T11:54:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T01:23:04.000Z", "avg_line_length": 37.5652173913, "max_line_length": 122, "alphanum_fraction": 0.5716145833, "num_tokens": 2355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7620420025552301}}
{"text": "\"\"\"\n        mairca(decisionMat, weights, fns)\n\nApply MAIRCA (Multi Attributive Ideal-Real Comparative Analysis) for a given matrix and weights.\n\n# Arguments:\n - `decisionMat::DataFrame`: n × m matrix of objective values for n alternatives and m criteria \n - `weights::Array{Float64, 1}`: m-vector of weights that sum up to 1.0. If the sum of weights is not 1.0, it is automatically normalized.\n - `fns::Array{Function, 1}`: m-vector of functions to be applied on the columns. \n\n# Description \nmairca() applies the MAIRCA method to rank n alternatives subject to m criteria which are supposed to be \neither maximized or minimized.\n\n# Output \n- `::MAIRCAResult`: MAIRCAResult object that holds multiple outputs including scores, rankings, and best index.\n\n# Examples\n```julia-repl\njulia> decmat = [6.952 8.000 6.649 7.268 8.000 7.652 6.316;\n       7.319 7.319 6.604 7.319 8.000 7.652 5.313;\n       7.000 7.319 7.652 6.952 7.652 6.952 4.642;\n       7.319 6.952 6.649 7.319 7.652 6.649 5.000]\n4×7 Array{Float64,2}:\n 6.952  8.0    6.649  7.268  8.0    7.652  6.316\n 7.319  7.319  6.604  7.319  8.0    7.652  5.313\n 7.0    7.319  7.652  6.952  7.652  6.952  4.642\n 7.319  6.952  6.649  7.319  7.652  6.649  5.0\n\n julia> df = makeDecisionMatrix(decmat)\n 4×7 DataFrame\n  Row │ Crt1     Crt2     Crt3     Crt4     Crt5     Crt6     Crt7    \n      │ Float64  Float64  Float64  Float64  Float64  Float64  Float64 \n ─────┼───────────────────────────────────────────────────────────────\n    1 │   6.952    8.0      6.649    7.268    8.0      7.652    6.316\n    2 │   7.319    7.319    6.604    7.319    8.0      7.652    5.313\n    3 │   7.0      7.319    7.652    6.952    7.652    6.952    4.642\n    4 │   7.319    6.952    6.649    7.319    7.652    6.649    5.0\n\njulia> weights = [0.172, 0.165, 0.159, 0.129, 0.112, 0.122, 0.140];\n\njulia> fns = [maximum, maximum, maximum, maximum, maximum, maximum, minimum];\n\njulia> result = mairca(df, weights, fns);\n\njulia> result.scores\n4-element Array{Float64,1}:\n 0.12064543054088471\n 0.08066456363291889\n 0.14586265389012484\n 0.14542366685864686\n\njulia> result.bestIndex\n2\n```\n\n# References\n\nPamučar, D., Lukovac, V., Božanić, D., & Komazec, N. (2018). Multi-criteria FUCOM-MAIRCA model for the evaluation of level crossings: case study in the Republic of Serbia. Operational Research in Engineering Sciences: Theory and Applications, 1(1), 108-129.\n\nUlutaş A.(2019),Swara Ve Mairca Yöntemleri İle Catering Firması Seçimi,BMIJ, (2019), 7(4): 1467-1479 http://dx.doi.org/10.15295/bmij.v7i4.1166\n\"\"\"\nfunction mairca(decisionMat::DataFrame, weights::Array{Float64,1}, fns::Array{Function,1})::MAIRCAResult\n\n    row, col = size(decisionMat)\n\n    w = unitize(weights)\n\n    T = zeros(Float64, row, col)\n\n    for i in 1:col\n        T[:, i] .= w[i] * (1 / row)\n    end \n\n    colMax = colmaxs(decisionMat)\n    colMin = colmins(decisionMat)\n\n    A = similar(decisionMat)\n\n    for i in 1:row\n        for j in 1:col\n            if fns[j] == maximum\n                @inbounds A[i, j] = T[i,j] * ((decisionMat[i, j] - colMin[j]) / (colMax[j] - colMin[j]))\n            elseif fns[j] == minimum\n                @inbounds A[i, j] = T[i,j] * ((decisionMat[i, j] - colMax[j]) / (colMin[j] - colMax[j]))\n            end                    \n        end\n    end\n\n    S = T .- A\n\n    scores = zeros(Float64, row)\n    for i in 1:row\n        scores[i] = sum(S[i, :])\n    end \n\n    rankings = sortperm(scores)\n    \n    bestIndex = rankings |> first\n    \n    result = MAIRCAResult(\n        decisionMat,\n        w,\n        scores,\n        rankings,\n        bestIndex\n    )\n\n    return result\nend\n", "meta": {"hexsha": "f1381d4bd63753fa324b328e730d29321d515087", "size": 3599, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mairca.jl", "max_stars_repo_name": "bahadirfyildirim/JMcDM", "max_stars_repo_head_hexsha": "c1c3f11d92cd8b8c6367245794464e6643caa735", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mairca.jl", "max_issues_repo_name": "bahadirfyildirim/JMcDM", "max_issues_repo_head_hexsha": "c1c3f11d92cd8b8c6367245794464e6643caa735", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mairca.jl", "max_forks_repo_name": "bahadirfyildirim/JMcDM", "max_forks_repo_head_hexsha": "c1c3f11d92cd8b8c6367245794464e6643caa735", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4234234234, "max_line_length": 257, "alphanum_fraction": 0.6004445679, "num_tokens": 1349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.8198933381139646, "lm_q1q2_score": 0.7620419984648961}}
{"text": "using LinearAlgebra\nusing StaticArrays\n\ninclude(\"./io.jl\")\n\n\"\"\"\n    repulsion(npoints, dims, fileopts...; niter = 1e7, convergence_tol = 1e-10)\n\nGenerates a uniform grid of `npoints` points in `dims` dimensions, distributed uniformly on the surface of the unit sphere\nusing the REPULSION algorithm\n\nThe function iterates, up to a maximum of `niter` times, until the algorithm converges. The convergence criterion \n`convergence_tol` is interpreted as the target for the maximum displacement between points in two successive iterations. The points\ninherit their floating point precision from `convergence_tol`.\nThe points are returned as a vector of vectors of length `npoints`, with each element containing the angles `[α, β, γ]` and the\nweight corresponding to each point (currently uniform weights are assigned)\n\nThe function optionally writes the resulting grid of points to a file  by calling `writedata`, which uses the contents of the optional \n`fileopts` parameters to determine the file format and filename. The first fileopt parameter is a String containing the file format,\nand the second is a String containing the filename. If the filename is not provided, a default is chosen using the current system time.\nThe file formats currently supported are: \"CSV\", \"TSV\", \"MAT\", \"JLD\", \"JLD2\". The [MAT](https://github.com/JuliaIO/MAT.jl) and \n[JLD](https://github.com/JuliaIO/JLD.jl)/[JLD2](https://github.com/JuliaIO/JLD2.jl) file types require packages not in the standard library \nthat must be installed and loaded by the user.\n\nThis function is adapted from its counterpart in Spinach (https://spindynamics.org) for MATLAB. The Spinach \nfunction, repulsion.m, is Copyright Ilya Kuprov and Frederic Mentink-Vigier\n\"\"\"\nfunction repulsion(npoints, dims, fileopts...; niter = 1e7, convergence_tol::T = 1e-10) where {T <: AbstractFloat}\n    R_raw = rand(T, dims, npoints) .- one(T)/2 # generating the first set of random points \n    R = [SVector{dims, T}(ntuple(i -> R_raw[n+i], Val(dims))) for n in 0:dims:(dims*npoints-1)]\n    R_n = copy(R) # pre-allocate\n    F = zeros(SVector{dims, T},npoints) # pre-allocate \"forces\"\n\n    for i in 1:niter # starting the conjugate gradient optimization\n        F .= zero(T) .* F # re-initializing F at each step\n        for k in eachindex(R)\n            F .-= dist_vector.(R,[R[k]]) # compute the distance between points, in place (speed-up)\n        end\n        R_n = normalize.(R_n - dims*F/npoints) # normalize\n        max_diff = maximum(norm.(R-R_n)) # get the maximum distance\n        R = R_n\n\t    if mod(i, 1000) == 0\n\t        @debug \"Maximum difference \" max_diff \"At iteration \" i # returns the convergence value every 1000 steps\n\t    end\n        if max_diff <= convergence_tol\n            @info \"Converged at iteration \" i # stops and return number of steps when converged\n            break\n        end\n    end\n    angles = @. vcat(toangles(R), one(T)/npoints) # computing the angles and weights\n\n    if !isempty(fileopts)\n        writedata(angles, fileopts...) # Optionally, write angles to file\n    end\n\n    return angles\nend\n\n\"\"\"\n    dist_vector(a::SVector{N,T}, b::SVector{N,T}) where N where T\n\nComputes the normalised distance between two vectors `a` and `b`, scaled by the cosine of the angle between them\n\"\"\" \nfunction dist_vector(a::SVector{N,T}, b::SVector{N,T}) where N where T\n    dd = normalize(a - b)\n    if isnan(first(dd))\n        zeros(typeof(a))\n    else\n        dd*dot(a, b)\n    end\nend\n\n\"\"\"\n    toangles(p)\n\nConverts a point `p` on the unit sphere to a vector of angles `[α, β, γ]`\n\nThe interpretation of `p` and the conversion depend on the number of dimensions:\n- Two dimensions: `p` is treated as 2D cartesian co-ordinates, and the polar angle is returned as `β`\n- Three dimensions: `p` is treated as 3D cartesian co-ordinates, and the spherical angles `θ` and `φ` are returned as `β` and `γ`\n- Four dimensions: `p` is treated as a quaternion, and the ZYZ Euler angles are returned\nAll angles are shifted to lie in the ranges ``α ∈ [0,2π)``, ``β ∈ [0,π]``, ``γ ∈ [0,2π)``. Missing angles are returned as 0s\n\"\"\"\nfunction toangles(p::SVector{N,T}) where N where T\n    angles = zeros(T, 3)\n    if N == 2\n\t    angles[2] = atan(p[2], p[1])\n    elseif N == 3\n\t    angles[3] = atan(p[2], p[1])\n\t    angles[2] = pi/(2*one(T)) + atan(p[3], hypot(p[1], p[2]))\n    elseif N == 4\n\t    angles = quat_to_euler(p)\n    end\n    angles\nend\n\n\"\"\"\n    quat_to_euler(q)\n\nConverts a normalised quaternion to its corresponding Euler angles `[α, β, γ]` about the \nZYZ rotation axes. \n\nAn active rotation convention is assumed - invert the input quaternion \nfor passive rotations. This code is adapted from EasySpin's quat2euler implementation at:\nhttps://github.com/StollLab/EasySpin/blob/main/easyspin/quat2euler.m\nEasySpin is Copyright Stefan Stoll and other contributors\n\"\"\"\nfunction quat_to_euler(q::AbstractVector{T}) where T\n    if length(q) != 4\n        e = DomainError(q, \"A Quaternion must have four elements\")\n        throw(e)\n    end\n    \n    sy = 2*sqrt((q[3]*q[4] + q[2]*q[1])^2 + (q[2]*q[4] - q[3]*q[1])^2)\n    beta = real(atan(sy, one(T) - 2*q[2]^2 - 2*q[3]^2))\n    if sy < 1e-10 # Singularity check: 1e-10 ≈ 0 for normalised quantities\n        alpha = zero(T)\n        gamma = atan(-2*(q[4]*q[1] - q[2]*q[3]), one(T) - 2*(q[2]^2 - q[4]^2))\n    else\n        alpha = atan(2*(q[3]*q[4] - q[1]*q[2]), 2*(q[2]*q[4] + q[1]*q[3]))\n        gamma = atan(2*(q[3]*q[4] + q[1]*q[2]), -2*(q[2]*q[4] - q[1]*q[3]))\n        if alpha < 0\n            alpha = alpha + pi + pi # Maintaining floating point precision\n        end\n        if gamma < 0\n            gamma = gamma + pi + pi\n        end\n    end\n    [alpha; beta; gamma]\nend\n", "meta": {"hexsha": "a057047f2e8c03af79ee9e3590aabcde1ce098aa", "size": 5676, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Repulsion.jl", "max_stars_repo_name": "murari0/Repulsion.jl", "max_stars_repo_head_hexsha": "16d002bd280f6aa4ff3bf05159e579b9a91e1c8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-07T01:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-07T01:30:55.000Z", "max_issues_repo_path": "src/Repulsion.jl", "max_issues_repo_name": "murari0/Repulsion.jl", "max_issues_repo_head_hexsha": "16d002bd280f6aa4ff3bf05159e579b9a91e1c8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Repulsion.jl", "max_forks_repo_name": "murari0/Repulsion.jl", "max_forks_repo_head_hexsha": "16d002bd280f6aa4ff3bf05159e579b9a91e1c8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3282442748, "max_line_length": 140, "alphanum_fraction": 0.6663143058, "num_tokens": 1664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7620419891244902}}
{"text": "###### beam splitter and special counter example matrices ######\n\nfunction beam_splitter(transmission_amplitude = sqrt(0.5))\n\n\t\"\"\"2d beam_splitter matrix, follows the conventions of Leonardo\"\"\"\n\n\t# |t|^2 is the \"transmission probability\"\n\n\tt = transmission_amplitude\n\tr = sqrt(1-t^2)\n\n\tbs = [[t -r]; [r t]]\n\nend\n\nfunction beam_splitter_modes(;in_up, in_down, out_up, out_down, transmission_amplitude, n)\n\n\t\"\"\"beam splitter incorrporated for connecting specific input modes, output modes in a dimension n interferometer\"\"\"\n\n\tif in_up == in_down || out_up == out_down\n\t\tthrow(ArgumentError())\n\tend\n\n\tbs = Matrix{ComplexF64}(I, n, n)\n\n\tsub_bs = beam_splitter(transmission_amplitude)\n\n\tbs[in_up, out_up] = sub_bs[1,1]\n\tbs[in_down, out_down] = sub_bs[2,2]\n\tbs[in_down, out_up] = sub_bs[2,1]\n\tbs[in_up, out_down] = sub_bs[1,2]\n\t#\n\t# # before convention checks:\n\t# bs[in_down, out_up] = sub_bs[1,2] ####### this change is a bit ad hoc and needs to be checked carefully with the conventions\n\t# bs[in_up, out_down] = sub_bs[2,1]\n\t#\n\n\tbs\n\nend\n\nfunction rotation_matrix(angle::Float64)\n\t[cos(angle) -sin(angle);\n\t sin(angle) coss(angle)]\n end\n\n function rotation_matrix_modes(;in_up, in_dow, out_up, out_down, angle, n)\n\n\t \"\"\"beam splitter incorrporated for connecting specific input modes, output modes in a dimension n interferometer\"\"\"\n\n \tif in_up == in_down || out_up == out_down\n \t\tthrow(ArgumentError())\n \tend\n\n \tr = Matrix{ComplexF64}(I, n, n)\n\n \tsub_r = rotation_matrix(angle)\n\n \tr[in_up, out_up] = sub_r[1,1]\n \tr[in_down, out_down] = sub_r[2,2]\n \t# bs[in_down, out_up] = sub_bs[2,1]\n \t# bs[in_up, out_down] = sub_bs[1,2]\n \tr[in_down, out_up] = sub_r[1,2] ####### this change is a bit ad hoc and needs to be checked carefully with the conventions\n \tr[in_up, out_down] = sub_r[2,1]\n\n \tr\n\n end\n\n function phase_shift(shifted_modes::Array, param_::Array)\n\n\tU = zeros(length(shifted_modes), length(shifted_modes))\n\n \tfor i in length(shifted_modes)\n\t\tfor j in length(shifted_modes)\n\t\t\ti == j && i in shifted_modes ? U[i,j] = exp(1im * param_[i]) : continue\n\t\tend\n\tend\n\n\t  U\n\nend\n\n# function build_circuit(mode_occ::ModeOccupation, circuit_elements::Vector{Vector{T}}, layers::Vector) where T <: Interferometer\n#\n# \tm = mode_occ.m\n# \tid = Matrix{ComplexF64}(LinearAlgebra.I, m, m)\n# \tres = id\n#\n# \tfor i in 1:length(circuit_elements)\n# \t\tu = id\n# \t\tfor j in 1:length(circuit_elements[i])\n# \t\t\tU = circuit_elements[i][j].U\n# \t\t\tu[layers[i][j], layers[i][j]] = U\n# \t\tend\n#\n# \t\tres *= u\n# \tend\n#\n# \tres\n# end\n#\n# mode_occ = first_modes(3,5)\n#\n# m = mode_occ.m\n#\n# b1 = BeamSplitter(1/sqrt(6))\n#\n# is_unitary(b1.U)\n#\n# U1 = RandHaar(1)\n#\n# is_unitary(U1.U)\n#\n# b2 = BeamSplitter(1/sqrt(2))\n#\n# is_unitary(b2.U)\n#\n# U2 = RandHaar(1)\n#\n# is_unitary(U2.U)\n#\n# circuit_elem = [[b1,U1],[b2,U2]]\n#\n# v_ = [[[1,2],[3]], [[1,3],[2]]]\n#\n# res = build_circuit(mode_occ, circuit_elem, v_)\n#\n# is_unitary(res)\n#\n# res * conj(transpose(res))\n#\n", "meta": {"hexsha": "f91f4e9497c095358da9a2da80dcd57828d52a66", "size": 2918, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/circuits/circuit_elements.jl", "max_stars_repo_name": "benoitseron/BosonSampling.jl", "max_stars_repo_head_hexsha": "941a73bd67602143d5957d1038258f996f8c37f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-03T07:44:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:14:02.000Z", "max_issues_repo_path": "src/circuits/circuit_elements.jl", "max_issues_repo_name": "benoitseron/BosonSampling.jl", "max_issues_repo_head_hexsha": "941a73bd67602143d5957d1038258f996f8c37f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2022-02-20T12:13:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T07:43:53.000Z", "max_forks_repo_path": "src/circuits/circuit_elements.jl", "max_forks_repo_name": "benoitseron/BosonSampling.jl", "max_forks_repo_head_hexsha": "941a73bd67602143d5957d1038258f996f8c37f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-17T20:38:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T20:38:50.000Z", "avg_line_length": 21.9398496241, "max_line_length": 129, "alphanum_fraction": 0.6696367375, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7620419859195856}}
{"text": "struct Spherical <: AbstractPredictorCorrectorAlgorithm{true} end\n\n\"\"\"\n\n    predict(alg::Affine, H, J_H, ∂H∂t, x, t, Δt)\n\nSpherical tangent predictor following the formulation of Chen[^1]. Denote by ``\\hat{H}`` the lift of the homotopy ``H``\nas a projective mapping.\nEuler's method yields\n```math\n\\begin{bmatrix}\nD_x\\hat{H}^(x,t) \\\\\nx^{H}\n\\end{bmatrix}\n\\dot{x} =\n\\begin{bmatrix}\n-D_t\\hat{H}^(x,t) \\\\\n0\n\\end{bmatrix}\n```\nand we can then obtain the spherical projection:\n```math\n\\cos(\\norm{\\dot{x}}_2 Δt) x + \\sin(\\norm{\\dot{x}}_2 Δt) \\frac{\\dot{x}}{\\norm{\\dot{x}}_2}\n```\n\n[^1]: Tianran Chen and Tien-Yien Li.\n    “Spherical projective path tracking for homotopy continuation methods”.\n    Communications in Information and Systems 12(3):195-220 (2012)\n\"\"\"\nfunction predict(alg::Spherical, H::AbstractHomotopy, J_H, ∂H∂t, x, t, Δt)\n    dot_x = \\([J_H(x,t); x'], [-∂H∂t(x,t); 0])\n    norm_dot_x = norm(dot_x)\n    # TODO: conditining? i.e. check singular values\n    cos(-norm_dot_x*Δt) .* x .+ (sin(-norm_dot_x*Δt) / norm_dot_x) .* dot_x\nend\n\nfunction correct!(\n    u::Vector{T},\n    alg::Spherical,\n    H::AbstractHomotopy,\n    J_H::F,\n    x::Vector{T},\n    t,\n    tol::Float64,\n    max_iterations::Int\n) where {T,F}\n    N = length(x)\n    res = zeros(x)\n    dx_xt = zeros(T, N, N)\n    Δx = zeros(x)\n    u .= x\n\n    for k = 1:max_iterations\n        res[1:N-1] = -evaluate(H, u, t)\n        # println(\"newton iteration: $(k), res: $(norm(res))\")\n        if norm(res) < tol\n            return true\n        end\n\n        dx_xt[1:(N-1), :] .= J_H(u, t)\n        dx_xt[N, :] = u'\n\n        Δx .= \\(dx_xt, res)\n        norm_Δx = norm(Δx)\n        u .= cos(norm_Δx) .* u .+ (sin(norm_Δx) / norm_Δx) .* Δx\n    end\n\n    norm(res) < tol\nend\n", "meta": {"hexsha": "b0d3a4c047c51ef0ad9a37ea1101c8c0ebfe44ae", "size": 1722, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PredictorCorrector/spherical.jl", "max_stars_repo_name": "blegat/HomotopyContinuation.jl", "max_stars_repo_head_hexsha": "331282442403125f15f2e022351ebe2d6f8816d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PredictorCorrector/spherical.jl", "max_issues_repo_name": "blegat/HomotopyContinuation.jl", "max_issues_repo_head_hexsha": "331282442403125f15f2e022351ebe2d6f8816d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PredictorCorrector/spherical.jl", "max_forks_repo_name": "blegat/HomotopyContinuation.jl", "max_forks_repo_head_hexsha": "331282442403125f15f2e022351ebe2d6f8816d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6, "max_line_length": 119, "alphanum_fraction": 0.5847851336, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7619679545091179}}
{"text": "#= \nvoid acb_elliptic_p(acb_t res, const acb_t z, const acb_t tau, slong prec)¶\nComputes Weierstrass’s elliptic function\n\nvoid acb_elliptic_inv_p(acb_t res, const acb_t z, const acb_t tau, slong prec)¶\nComputes the inverse of the Weierstrass elliptic function\n\nvoid acb_elliptic_zeta(acb_t res, const acb_t z, const acb_t tau, slong prec)¶\nComputes the Weierstrass zeta function\n\nvoid acb_elliptic_sigma(acb_t res, const acb_t z, const acb_t tau, slong prec)¶\nComputes the Weierstrass sigma function\n=#\n\n\"\"\"\n    weierstrass_p(z, tau)\n\n- weierstrass_p(z, tau) == weierstrass_p(z+1, tau) == weierstrass_p(z+tau, tau)\n\"\"\"\nfunction weierstrass_p(z::ArbComplex{P}, tau::ArbComplex{P}) where {P}\n    result = ArbComplex{P}()\n    flag = 0\n    ccall(@libarb(acb_elliptic_p), Cvoid, (Ref{ArbComplex}, Ref{ArbComplex}, Ref{ArbComplex}, Cint), \n          result, z, tau, P)\n    return result\nend\n\n\"\"\"\n    weierstrass_invp(z, tau)\n\n- weierstrass_p(weierstrass_invp(z, tau), tau) == z\n\"\"\"\nfunction weierstrass_invp(z::ArbComplex{P}, tau::ArbComplex{P}) where {P}\n    result = ArbComplex{P}()\n    flag = 0\n    ccall(@libarb(acb_elliptic_inv_p), Cvoid, (Ref{ArbComplex}, Ref{ArbComplex}, Ref{ArbComplex}, Cint), \n          result, z, tau, P)\n    return result\nend\n\n\"\"\"\n    weierstrass_zeta(z, tau)\n\n- weierstrass_zeta(z+1, tau) == weierstrass_zeta(z, tau) + weierstrass_zeta(1/2, tau)\n- weierstrass_zeta(z+tau, tau) == weierstrass_zeta(z, tau) + weierstrass_zeta(tau/2, tau)\n\"\"\"\nfunction weierstrass_zeta(z::ArbComplex{P}, tau::ArbComplex{P}) where {P}\n    result = ArbComplex{P}()\n    flag = 0\n    ccall(@libarb(acb_elliptic_zeta), Cvoid, (Ref{ArbComplex}, Ref{ArbComplex}, Ref{ArbComplex}, Cint), \n          result, z, tau, P)\n    return result\nend\n\n\"\"\"\n    weierstrass_sigma(z, tau)\n\n- weierstrass_sigma(z+1, tau) == −exp(2*(z+τ/2)*weierstrass_zeta(τ/2,τ)) * weierstrass_sigma(z, tau)\n\"\"\"\nfunction weierstrass_sigma(z::ArbComplex{P}, tau::ArbComplex{P}) where {P}\n    result = ArbComplex{P}()\n    flag = 0\n    ccall(@libarb(acb_elliptic_sigma), Cvoid, (Ref{ArbComplex}, Ref{ArbComplex}, Ref{ArbComplex}, Cint), \n          result, z, tau, P)\n    return result\nend\n\n\nweierstrass_p(z::ArbReal{P}, tau::ArbReal{P}) where {P} =\n    weierstrass_p(ArbComplex{P}(z), ArbComplex{P}(tau))\nweierstrass_p(z::ArbFloat{P}, tau::ArbFloat{P}) where {P} =\n    weierstrass_p(ArbComplex{P}(z), ArbComplex{P}(tau))\n\nweierstrass_pinv(z::ArbReal{P}, tau::ArbReal{P}) where {P} =\n    weierstrass_pinv(ArbComplex{P}(z), ArbComplex{P}(tau))\nweierstrass_pinv(z::ArbFloat{P}, tau::ArbFloat{P}) where {P} =\n    weierstrass_pinv(ArbComplex{P}(z), ArbComplex{P}(tau))\n    \nweierstrass_zeta(z::ArbReal{P}, tau::ArbReal{P}) where {P} =\n    weierstrass_zeta(ArbComplex{P}(z), ArbComplex{P}(tau))\nweierstrass_zeta(z::ArbFloat{P}, tau::ArbFloat{P}) where {P} =\n    weierstrass_zeta(ArbComplex{P}(z), ArbComplex{P}(tau))\n    \nweierstrass_sigma(z::ArbReal{P}, tau::ArbReal{P}) where {P} =\n    weierstrass_sigma(ArbComplex{P}(z), ArbComplex{P}(tau))\nweierstrass_sigma(z::ArbFloat{P}, tau::ArbFloat{P}) where {P} =\n    weierstrass_sigma(ArbComplex{P}(z), ArbComplex{P}(tau))\n", "meta": {"hexsha": "7c273388300b73e2858379cf147c78bb48832179", "size": 3124, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/float/weierstrass.jl", "max_stars_repo_name": "AdrianDAlessandro/ArbNumerics.jl", "max_stars_repo_head_hexsha": "637f40689b0cfb14c6d6980da4ac6cb02c40ec66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2018-07-18T17:45:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T08:18:57.000Z", "max_issues_repo_path": "src/float/weierstrass.jl", "max_issues_repo_name": "AdrianDAlessandro/ArbNumerics.jl", "max_issues_repo_head_hexsha": "637f40689b0cfb14c6d6980da4ac6cb02c40ec66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 43, "max_issues_repo_issues_event_min_datetime": "2018-07-29T06:12:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:47:58.000Z", "max_forks_repo_path": "src/float/weierstrass.jl", "max_forks_repo_name": "AdrianDAlessandro/ArbNumerics.jl", "max_forks_repo_head_hexsha": "637f40689b0cfb14c6d6980da4ac6cb02c40ec66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2018-08-07T14:06:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T08:19:27.000Z", "avg_line_length": 35.5, "max_line_length": 105, "alphanum_fraction": 0.6907810499, "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801274759925, "lm_q2_score": 0.8056321819811829, "lm_q1q2_score": 0.7619679447054227}}
{"text": "export HPoint, getz, dist, midpoint, RandomHPoint, between, polar\n\n\n\n\"\"\"\n`HPoint(z::Complex)` creates a new point in the hyperbolic plane.\nThe argument `z` must have absolute value less than 1.\n\n`HPoint(r,theta)` creates a new point with polar coordinates\n`(r,theta)`. See also: `polar`.\n\"\"\"\nstruct HPoint <: HObject\n    z::Complex{Float64}\n    attr::Dict{Symbol,Any}\n    function HPoint(z::Complex)\n        if _mag(z) >=  1\n            throw(DomainError(z, \"absolute value is too large\"))\n        end\n        P = new(z,Dict{Symbol,Any}())\n        set_color(P)\n        set_radius(P)\n        return P\n    end\nend\n\nHPoint(P::HPoint) = HPoint(getz(P))  # copy constructor\nHPoint(z::Number) = HPoint(Complex(z))\nHPoint() = HPoint(0)\n\nfunction show(io::IO,P::HPoint)\n    r,theta = polar(P)\n    print(io,\"HPoint($r, $theta)\")\nend\n\n\"\"\"\n`RandomHPoint()` generates a point at random in the hyperbolic plane.\n\"\"\"\nRandomHPoint() = HPoint(randn(), 2*pi*rand())\n\n\n\"\"\"\n`getz(P::HPoint)` returns the point (complex number) in the\ninterior of the unit disc that represents `P`.\n\"\"\"\ngetz(P::HPoint) = P.z\n\n\"\"\"\n`dist(P,Q)` gives the distance betwen two points in the\nhyperbolic plane. If `Q` is omitted, give the distance\nfrom `P` to `HPoint(0)`.\n\"\"\"\nfunction dist(P::HPoint, Q::HPoint)\n    a = getz(P)\n    b = getz(Q)\n    delta = 2 * _mag(a-b)/(1-_mag(a))/(1-_mag(b))\n    return acosh(1+delta)\nend\n\n\ndist(P::HPoint) = dist(P, HPoint(0))\n\n\nHPoint(r::Real, theta::Real) = HPoint( solve_dist(r) * exp(im*theta) )\n\n\n\n\n\"\"\"\n`polar(P::HPoint)` gives the polar coordinates of `P`\n\"\"\"\nfunction polar(P::HPoint)\n    r = dist(P)\n    theta = angle(getz(P))\n    return (r,theta)\nend\n\n(==)(P::HPoint,Q::HPoint) = _mag(getz(P)-getz(Q)) <= THRESHOLD*eps(1.0)\n\nfunction _dist(t::Real)\n    delta = 2*t*t/(1-t*t)\n    return acosh(1+delta)\nend\n\n\"\"\"\n`solve_dist(d)` is the inverse of `_dist()`\n\"\"\"\nfunction solve_dist(d::Real)\n    ex = exp(d)\n    return (ex-1)/(ex+1)\nend\n\n\n\n\"\"\"\n`midpoint(p,q)` finds the mid point of the line segment\nfrom `p` to `q`. Also `midpoint(L::HSegment)`.\n\"\"\"\nfunction midpoint(p::HPoint, q::HPoint)::HPoint\n    if p==q\n        return p\n    end\n    d = dist(p,q)\n    f = move2xplus(p,q)\n\n    t = solve_dist(d/2)\n\n    r = HPoint(t)\n    h = inv(f)\n    return h(r)\nend\n\n\"\"\"\n`between(a,b,c)` determines if the hyperbolic point `b`\nlies on the segment from `a` to `c`.\n\"\"\"\nfunction between(a::HPoint, b::HPoint, c::HPoint)::Bool\n    if a==b || b==c\n        return true\n    end\n    f = move2xplus(a,c)\n    aa = getz(f(a))\n    bb = getz(f(b))\n    cc = getz(f(c))\n\n    if abs(imag(bb)) > THRESHOLD * eps(1.0)\n        return false\n    end\n\n    if real(aa)-THRESHOLD*eps(1.0) <= real(bb) <= real(cc)+THRESHOLD*eps(1.0)\n        return true\n    end\n    return false\nend\n", "meta": {"hexsha": "2886eaf6903e467115b9a5f96d6709694e41726b", "size": 2746, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/point.jl", "max_stars_repo_name": "switzel/HyperbolicPlane.jl", "max_stars_repo_head_hexsha": "89ba26e080b520b4f200e985f2b431b1d61ecb21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-01-19T06:12:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T22:18:48.000Z", "max_issues_repo_path": "src/point.jl", "max_issues_repo_name": "switzel/HyperbolicPlane.jl", "max_issues_repo_head_hexsha": "89ba26e080b520b4f200e985f2b431b1d61ecb21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-01-31T08:33:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T19:44:39.000Z", "max_forks_repo_path": "src/point.jl", "max_forks_repo_name": "switzel/HyperbolicPlane.jl", "max_forks_repo_head_hexsha": "89ba26e080b520b4f200e985f2b431b1d61ecb21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-31T21:10:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T18:49:43.000Z", "avg_line_length": 20.4925373134, "max_line_length": 77, "alphanum_fraction": 0.6056081573, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.761967938551587}}
{"text": "# Conjugate\n\n\"\"\"\n  Conjugate(f::ProximableFunction)\n\nReturns the conjugate function of `f`, that is `f*(x) = sup{y'x - f(y)}`.\n\"\"\"\n\nimmutable Conjugate{T <: ProximableFunction} <: ProximableFunction\n  f::T\nend\n\nfun_dom(f::Conjugate) = fun_dom(f.f)\n\n# only prox! is provided here, call method would require being able to compute\n# an element of the subdifferential of the conjugate\n\nfunction prox!{R <: Real}(g::Conjugate, x::AbstractArray{R}, y::AbstractArray{R}, gamma::Real=1.0)\n  # need to make a copy, doing this in place is probably not possible in general:\n  # if object_id(x) == object_id(y), then prox! causes the loss of x (which is needed afterwards)\n  x_copy = copy(x)\n  # Moreau identity\n  v = prox!(g.f, x/gamma, y, 1.0/gamma)\n  v = vecdot(x_copy,y) - gamma*vecdot(y,y) - v\n  for k in eachindex(y)\n    y[k] = x_copy[k] - gamma*y[k]\n  end\n  return v\nend\n\n# complex case, need to cast inner products to real\n\nfunction prox!{R <: Real}(g::Conjugate, x::AbstractArray{Complex{R}}, y::AbstractArray{Complex{R}}, gamma::Real=1.0)\n  x_copy = copy(x)\n  v = prox!(g.f, x/gamma, y, 1.0/gamma)\n  v = real(vecdot(x_copy,y)) - gamma*real(vecdot(y,y)) - v\n  for k in eachindex(y)\n    y[k] = x_copy[k] - gamma*y[k]\n  end\n  return v\nend\n\n# special case for indicator of convex cones (the conjugate is also an indicator function)\n\nprox!{R <: Real, C <: IndicatorConvexCone}(g::Conjugate{C}, x::AbstractArray{R}, y::AbstractArray{R}, gamma::Real=1.0) =\n  prox_conjugate_convex_cone!(g.f, x, y, gamma)\n\nprox!{R <: Real, C <: IndicatorConvexCone}(g::Conjugate{C}, x::AbstractArray{Complex{R}}, y::AbstractArray{Complex{R}}, gamma::Real=1.0) =\n  prox_conjugate_convex_cone!(g.f, x, y, gamma)\n\nfunction prox_conjugate_convex_cone!{T <: RealOrComplex, C <: IndicatorConvexCone}(f::C, x::AbstractArray{T}, y::AbstractArray{T}, gamma::Real=1.0)\n  x_copy = copy(x)\n  prox!(f, x/gamma, y, 1.0/gamma)\n  for k in eachindex(y)\n    y[k] = x_copy[k] - gamma*y[k]\n  end\n  return 0.0\nend\n\n# naive implementation\n\nfunction prox_naive{T <: RealOrComplex}(g::Conjugate, x::AbstractArray{T}, gamma::Real=1.0)\n  y, v = prox_naive(g.f, x/gamma, 1.0/gamma)\n  return x - gamma*y, real(vecdot(x,y)) - gamma*real(vecdot(y,y)) - v\nend\n\nis_prox_accurate(f::Conjugate) = is_prox_accurate(f.f)\n", "meta": {"hexsha": "40a6ece9cbda47c9becd185ffbbbdde6ad6dd60a", "size": 2259, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/calculus/conjugate.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/calculus/conjugate.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/calculus/conjugate.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2205882353, "max_line_length": 147, "alphanum_fraction": 0.6795042054, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7619593461664084}}
{"text": "#=\n# 3D Poisson, Dirichlet bc\n=#\n\n### If the Finch package has already been added, use this line #########\nusing Finch # Note: to add the package, first do: ]add \"https://github.com/paralab/Finch.git\"\n\n### If not, use these four lines (working from the examples directory) ###\n# if !@isdefined(Finch)\n#     include(\"../Finch.jl\");\n#     using .Finch\n# end\n##########################################################################\n\ninit_finch(\"poisson3d\");\nuseLog(\"poisson3dlog\")\n\nn = 10;\nord = 2;\n\ndomain(3)\nfunctionSpace(order=ord)\n\nmesh(HEXMESH, elsperdim=n)\n\nu = variable(\"u\")\n\ntestSymbol(\"v\")\n\nboundary(u, 1, DIRICHLET, 0)\n\n# Write the weak form \ncoefficient(\"f\", \"-3*pi*pi*sin(pi*x)*sin(pi*y)*sin(pi*z)\")\nweakForm(u, \"-dot(grad(u), grad(v)) - f*v\")\n\nsolve(u);\n\noutputValues(u, \"p3dout\", format=\"vtk\", asci=false);\n\n# exact solution is sin(pi*x)*sin(pi*y)*sin(pi*z)\n# check error\nmaxerr = 0;\nexact(x,y,z) = sin(pi*x)*sin(pi*y)*sin(pi*z);\n\nfor i=1:size(Finch.grid_data.allnodes,2)\n    x = Finch.grid_data.allnodes[1,i];\n    y = Finch.grid_data.allnodes[2,i];\n    z = Finch.grid_data.allnodes[3,i];\n    err = abs(u.values[i] - exact(x,y,z));\n    global maxerr;\n    maxerr = max(err,maxerr);\nend\nprintln(\"max error = \"*string(maxerr));\n\n\nfinalize_finch()\n", "meta": {"hexsha": "adae308c1b4020f7317d7c7fa859a5fa320f39b2", "size": 1257, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/examples/example-poisson3d.jl", "max_stars_repo_name": "paralab/Finch", "max_stars_repo_head_hexsha": "77fb81c55a8b063f1d8dd7b91a01ab4d7371a9a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-10-06T16:09:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T20:56:15.000Z", "max_issues_repo_path": "src/examples/example-poisson3d.jl", "max_issues_repo_name": "paralab/Finch", "max_issues_repo_head_hexsha": "77fb81c55a8b063f1d8dd7b91a01ab4d7371a9a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/examples/example-poisson3d.jl", "max_forks_repo_name": "paralab/Finch", "max_forks_repo_head_hexsha": "77fb81c55a8b063f1d8dd7b91a01ab4d7371a9a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0526315789, "max_line_length": 93, "alphanum_fraction": 0.6062052506, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7619197531167137}}
{"text": "using Random, LinearAlgebra, StatsBase, Distributions\n\n##FUNCTION data_construction\n\"\"\"Generate synthetic data\nINPUTS\n- ℓ             Loss function\n- n             Number of samples\n- k             Number of relevant features\n- p             Number of features/covariates\n- SNR           Squareroot of the Signal-to-Noise Ratio\n- rho           Correlation coefficient between features\nOUTPUTS\n- X             Matrix of observed covariates\n- Y             Vector of responses\n- indices_true  Set of relevant features\n- w_true        True regressor\"\"\"\nfunction data_construction(ℓ::LossFunction, n::Int, k::Int, p::Int, SNR, ρ)\n  indices_true, w_true = generate_estimator(p, k)\n  #Auto-regresive AR(1) filter preserving noise power\n  X = randn(n, p)\n  for i in 2:p\n      X[:, i] = X[:, i] + ρ*X[:, i-1]\n  end\n  # rho = ρ\n  # R\"\"\"\n  # X=matrix(NA,$n,$p)\n  # for(i in 1:$n){\n  #     X[i,]=arima.sim(n=$p,list(ar=$rho))\n  # }\n  # \"\"\"\n  # @rget X\n  # X = √12 * rand(n, p) - (√12)/2\n\n  Y = generate_output(ℓ, noisy_signal(X, indices_true, w_true, SNR))\n\n  return X, Y, indices_true, w_true\nend\n\nfunction hard_data_construction(ℓ::LossFunction, n::Int, k::Int, p::Int, SNR, ρ)\n  indices_true, w_true = generate_estimator(p, k)\n\n  indices_true = collect(1:k)\n  w_true = ones(k)./√k #sample(-1:2:1, k)\n\n  #Covariance matrix\n  θ = (1/√k + 1/k)/2\n  Σ = SparseMatrixCSC{Float64}(I, p, p)\n  for i in 1:k\n    Σ[i,k+1] = θ\n    Σ[k+1,i] = θ\n  end\n\n  # perm = shuffle(1:p)\n  # indices_true = [findfirst( perm .== i) for i in indices_true]\n  # Σ[:,:] = Σ[perm, perm]\n\n  d = MvNormal(full(Σ))\n\n  X = rand(d, n)'\n\n  Y = generate_output(ℓ, noisy_signal(X, indices_true, w_true, SNR))\n\n  # E = randn(n, p)  #Noise\n  # for j in 1:p\n  #   E[:,j] *= norm(X[:,j])/norm(E[:,j])/SNR*2\n  # end\n\n  return X, Y, indices_true, w_true\nend\n\n# FUNCTIONS Generate support and regressor w\nfunction generate_estimator(p::Int, k::Int)\n  weights = ones(p) ./ p\n  indices = sort(sample(1:p, StatsBase.Weights(weights), k, replace=false))\n  w = sample(-1:2:1, k)\n  return indices, w\nend\n\nfunction noisy_signal(X, indices, w, SNR)\n  n = size(X,1)\n  S = X[:, indices]*w #Signal\n  E = randn(n)  #Noise\n  E *= (norm(S)/norm(E))/SNR #Scaling according to SNR\n  return S+E\nend\n\n#FUNCTIONS Generate Output Y\nfunction generate_output(ℓ::Regression, S)\n  return S\nend\n\nfunction generate_output(ℓ::L1SVM, S)\n  P = 1. ./( 1 .+ exp.(-S) )\n  return 1.0*(P .> .5) - 1.0*(P .< .5)\nend\n\nfunction generate_output(ℓ::LogReg, S)\n    n = size(S,1)\n    P = 1. ./( 1 .+ exp.(-S) )\n    return (-ones(n)).^(rand(n) .> P)\nend\n", "meta": {"hexsha": "d1406ac7f196dbd738edd99d52ccc48503dd2270", "size": 2558, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiments/data_construction.jl", "max_stars_repo_name": "jeanpauphilet/SubsetSelectionCIO.jl", "max_stars_repo_head_hexsha": "8b03d1fba9262b150d6c0f230c6bf9e8ee57f92e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-09-16T15:50:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T03:57:37.000Z", "max_issues_repo_path": "experiments/data_construction.jl", "max_issues_repo_name": "jeanpauphilet/SubsetSelectionCIO.jl", "max_issues_repo_head_hexsha": "8b03d1fba9262b150d6c0f230c6bf9e8ee57f92e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-10-11T13:21:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-26T17:47:08.000Z", "max_forks_repo_path": "experiments/data_construction.jl", "max_forks_repo_name": "jeanpauphilet/SubsetSelectionCIO.jl", "max_forks_repo_head_hexsha": "8b03d1fba9262b150d6c0f230c6bf9e8ee57f92e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-09-13T17:10:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T15:17:16.000Z", "avg_line_length": 25.0784313725, "max_line_length": 80, "alphanum_fraction": 0.6055512119, "num_tokens": 911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.7619197446039163}}
{"text": "include(\"backwards_activation_functions.jl\")\n\n\"\"\"\nPartial derivates of the components of linear forward function using the linear output (δZ) and caches of these components (cache).\n\"\"\"\nfunction linear_backward(δZ, cache)\n    # unpack cache\n    A_prev, W, b = cache\n    m = size(A_prev, 2)\n\n    # partial derivates of each component\n    δW = δZ * (A_prev') / m\n    δb = sum(δZ, dims = 2) / m\n    δA_prev = (W') * δZ\n\n    @assert (size(δA_prev)[1] == size(A_prev)[1])\n    @assert (size(δW) == size(W))\n    @assert (size(δb)[1] == size(b)[1])\n\n    return δW, δb, δA_prev\nend # function\n\n\"\"\"\nUnpack the linear activated caches (cache) and compute their derivates from the applied activation function.\n\"\"\"\nfunction linear_activation_backwards(δA, cache; activation_function=\"relu\")\n    @assert activation_function ∈ (\"sigmoid\", \"relu\", \"softmax\", \"tanh\", \"swish\")\n\n    linear_cache, cache_activation = cache\n\n    if (activation_function == \"relu\")\n\n        δZ = relu_backwards(δA, cache_activation)\n\n    elseif (activation_function == \"sigmoid\")\n\n        δZ = sigmoid_backwards(δA, cache_activation)\n\n    elseif (activation_function ==  \"tanh\")\n\n        δZ = tanh_backwards(δA, cache_activation)\n\n    elseif (activation_function == \"softmax\")\n\n        δZ = softmax_backwards(δA, cache_activation)\n        \n    elseif (activation_function == \"swish\")\n\n        δZ = swish_backwards(δA, cache_activation)\n\n    end # if\n\n    δW, δb, δA_prev = linear_backward(δZ, linear_cache)\n\n    return δW, δb, δA_prev\nend # function", "meta": {"hexsha": "da37f10a354dee813116c4b44708fc88440d670b", "size": 1511, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "case_names/backward_linear_steps.jl", "max_stars_repo_name": "Squalm/NeuralNetworks", "max_stars_repo_head_hexsha": "913a43e419c768e3ff29baab96c1f2871bc5e5bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "case_names/backward_linear_steps.jl", "max_issues_repo_name": "Squalm/NeuralNetworks", "max_issues_repo_head_hexsha": "913a43e419c768e3ff29baab96c1f2871bc5e5bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "case_names/backward_linear_steps.jl", "max_forks_repo_name": "Squalm/NeuralNetworks", "max_forks_repo_head_hexsha": "913a43e419c768e3ff29baab96c1f2871bc5e5bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9821428571, "max_line_length": 131, "alphanum_fraction": 0.6677696889, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7619197422407341}}
{"text": "# Sandpile64.jl\nmodule Sandpile64\n\nexport sandpile_init64, run_sandpile64!, avalanche64!, add_grain!, is_unstable64\n\nfunction sandpile_init64(x::Int64, y::Int64, setup::String=\"random\")\n    \"\"\"\n            sandpile_init(X, Y, setup)\n    Initialize a 2d sandpile grid with size (`X`, `Y`). Can either have a zero or random\n    initial condition.\n    Arguments:\n            x (Int64): length of grid along x\n            y (Int64): length of grid along y\n            setup (String): Type of inital setup for grid. Can either be `zero` or `random`.\n    Returns:\n            z (Matrix{Int64}): sandpile grid z with dimensions (x,y).\n    \"\"\"\n    if setup == \"random\"\n        return rand(0:3, x, y)\n    elseif setup == \"zero\"\n        return zeros(Int64, x, y)\n    else\n        error(\"`setup` must have value of `random` or `zero`\")\n    end\nend\n\nfunction add_grain64!(z::Array{Int64,2})\n    \"\"\"\n            add_grain!(z)\n    Adds a grain to a random location on the  2d array grid for the Abelian sandpile model, `z`.\n    Arguments:\n            z (Array{Int64, 2}): 2D sandpile grid.\n    \"\"\"\n    return z[rand(1:size(z)[1]), rand(1:size(z)[2])] += 1\nend\n\nfunction is_unstable64(z::Array{Int64,2}, fᵪ::Int64=4)\n    \"\"\"\n            is_unstable(z, fᵪ)\n    Checks whether or not any location on the grid is unstable (has value above critical value).\n    Arguments:\n            z (Array{Int64, 2}): 2D sandpile grid.\n            fₓ (Int64): Critical value for sandpile model (Must be > 1)\n    Returns:\n            (bool): Whether grid is stable or unstable.\n    \"\"\"\n    if fᵪ <= 1\n        error(\"`fᵪ` must be int greater than  1\")\n    end\n    if length(findall(>=(fᵪ), z)) > 0\n        return true\n    else\n        return false\n    end\nend\n\nfunction avalanche64!(z::Array{Int64,2}, fᵪ=4)\n    \"\"\"\n            avalanche(z, fᵪ)\n    Update grid to follow rules on locations that are unstable. \n    Follow Eq 3.2 of Self-organized criticality by Bak, Tang (1988).\n    Returns how many avalanches (or slides s) occur for input state after collapsing all \n    unstable locations.\n    Arguments:\n            z (Array{Int64, 2}): 2D sandpile grid.\n            fₓ (Int64): Critical value for sandpile model (Must be > 1)\n    Returns:\n            (Int64): Number of unstable locations collapsed.\n    \"\"\"\n    s::Int64 = 0\n    unstable_locs = findall(>=(fᵪ), z)\n    for crit_loc in unstable_locs\n        z[crit_loc] -= 4\n        s += 1\n        neighbors = [\n            CartesianIndex(0, 1),\n            CartesianIndex(0, -1),\n            CartesianIndex(1, 0),\n            CartesianIndex(-1, 0),\n        ]\n        for neighbor in neighbors\n            try\n                z[crit_loc + neighbor] += 1\n            catch\n            end\n        end\n    end\n    return s\nend\n\nfunction run_sandpile64!(z::Array{Int64,2}, N::Int64; N_crit::Bool=false, fᵪ::Int64=4)\n    \"\"\"\n            run_sandpile(z, N, fᵪ)\n    Run a sandpile model on an input grid `z` by adding `N` grains.\n    Arguments:\n            z (Array{Int64, 2}): 2D sandpile grid.\n            N (Int64): Number of grains to add\n            N_crit (boolean): Do you want to to all added `N` grains to result in collapses?\n                              If set to `false`, `N` grains will be added to system but\n                              returned sizes will only be those that result in avalanches.\n                              Warning:  longer runtimes if set to `true`.\n            fₓ (Int64): Critical value for sandpile model (Must be > 1)\n    Returns\n            (Vector{Int64}): Sizes of avalanches for each grain added.\n    \"\"\"\n    s_list = zeros(Int64, N)\n    if N_crit\n            i = 1\n            while i <= N\n                add_grain64!(z)\n                s = 0\n                while is_unstable64(z, fᵪ)\n                    s += avalanche64!(z)\n                end\n                if s > 0\n                    s_list[i] = s\n                    i += 1\n                end\n            end\n    else\n        for i in 1:N\n            add_grain64!(z)\n            s = 0\n            while is_unstable64(z, fᵪ)\n                s += avalanche64!(z)\n            end\n            s_list[i] = s\n        end\n    end\n    return s_list[s_list .> 0]\nend\nend", "meta": {"hexsha": "c6bd7328203608a86a93409c6adbfe330b84b64a", "size": 4183, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code/old/sandpile64.jl", "max_stars_repo_name": "romeroraa/sandpile-julia", "max_stars_repo_head_hexsha": "a9d5cf6269fab74529e7e5d53931816dd3450f6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/old/sandpile64.jl", "max_issues_repo_name": "romeroraa/sandpile-julia", "max_issues_repo_head_hexsha": "a9d5cf6269fab74529e7e5d53931816dd3450f6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/old/sandpile64.jl", "max_forks_repo_name": "romeroraa/sandpile-julia", "max_forks_repo_head_hexsha": "a9d5cf6269fab74529e7e5d53931816dd3450f6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6893939394, "max_line_length": 96, "alphanum_fraction": 0.5400430313, "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7619008960549578}}
{"text": "\"\"\"\n    eom_nonlinear3d(uᵢ, a₁, a₂, a₃,  b₁, b₂, b₃, \n        c₁₂, c₂₃, c₁₃, σ₁, σ₂, σ₃) -> DiscreteDynamicalSystem\n\nEquations of motion for a 3d nonlinear system with nonlinear couplings \n``x_1 \\\\to x_2``, ``x_2 \\\\to x_3`` and ``x_1 \\\\to x_3``. Modified from [1]. \n\n## Equations of motion \n\nThe equations of motion are\n\n```math\n\\\\begin{aligned}\nx_1(t+1) &= a_1 x_1 (1-x_1(t))^2  e^{-x_2(t)^2} + 0.4 \\\\xi_{1}(t) \\\\\\\\\nx_2(t+1) &= a_1 x_2 (1-x_2(t))^2  e^{-x_2(t)^2} + 0.4 \\\\xi_{2}(t) + b x_1 x_2 \\\\\\\\\nx_3(t+1) &= a_3 x_3 (1-x_3(t))^2  e^{-x_3(t)^2} + 0.4 \\\\xi_{3}(t) + c x_{2}(t) + d x_{1}(t)^2.\n\\\\end{aligned}\n```\n\n## References \n\n1. Gourévitch, B., Le Bouquin-Jeannès, R., & Faucon, G. (2006). Linear and nonlinear \n    causality between signals: methods, examples and neurophysiological \n    applications. Biological Cybernetics, 95(4), 349–369.\n\"\"\"\nfunction eom_nonlinear3d(x, p, n)\n    x₁, x₂, x₃ = (x...,)\n    a₁, a₂, a₃, b₁, b₂, b₃, c₁₂, c₂₃, c₁₃, σ₁, σ₂, σ₃ = (p...,)\n    ξ₁ = rand(Normal(0, σ₁))\n    ξ₂ = rand(Normal(0, σ₂))\n    ξ₃ = rand(Normal(0, σ₃))\n    \n    dx₁ = a₁*x₁*(1-x₁)^2 * exp(-x₁^2) + b₁*ξ₁\n    dx₂ = a₂*x₂*(1-x₂)^2 * exp(-x₂^2) + b₂*ξ₂ + c₁₂*x₁*x₂ \n    dx₃ = a₃*x₃*(1-x₃)^2 * exp(-x₃^2) + b₃*ξ₃ + c₂₃*x₂ + c₁₃*x₁^2\n\n    return SVector{3}(dx₁, dx₂, dx₃)\nend\n\nfunction nonlinear3d(uᵢ, a₁, a₂, a₃,  b₁, b₂, b₃, c₁₂, c₂₃, c₁₃, σ₁, σ₂, σ₃)\n    p = [a₁, a₂, a₃,  b₁, b₂, b₃, c₁₂, c₂₃, c₁₃, σ₁, σ₂, σ₃]\n    s = DiscreteDynamicalSystem(eom_nonlinear3d, uᵢ, p)\n    return s\nend\n\n\"\"\"\n    nonlinear3d(;uᵢ = rand(3), \n        σ₁ = 1.0, σ₂ = 1.0, σ₃ = 1.0, \n        a₁ = 3.4, a₂ = 3.4, a₃ = 3.4, \n        b₁ = 0.4, b₂ = 0.4, b₃ = 0.4, \n        c₁₂ = 0.5, c₂₃ = 0.3, c₁₃ = 0.5) -> DiscreteDynamicalSystem\n\nA 3d nonlinear system with nonlinear couplings ``x_1 \\\\to x_2``, \n``x_2 \\\\to x_3`` and ``x_1 \\\\to x_3``. Modified from [1]. \n\n## Equations of motion \n\nThe equations of motion are\n\n```math\n\\\\begin{aligned}\nx_1(t+1) &= a_1 x_1 (1-x_1(t))^2  e^{-x_2(t)^2} + 0.4 \\\\xi_{1}(t) \\\\\\\\\nx_2(t+1) &= a_1 x_2 (1-x_2(t))^2  e^{-x_2(t)^2} + 0.4 \\\\xi_{2}(t) + b x_1 x_2 \\\\\\\\\nx_3(t+1) &= a_3 x_3 (1-x_3(t))^2  e^{-x_3(t)^2} + 0.4 \\\\xi_{3}(t) + c x_{2}(t) + d x_{1}(t)^2.\n\\\\end{aligned}\n```\n\n## References \n\n1. Gourévitch, B., Le Bouquin-Jeannès, R., & Faucon, G. (2006). Linear and nonlinear \n    causality between signals: methods, examples and neurophysiological \n    applications. Biological Cybernetics, 95(4), 349–369.\n\"\"\"\nnonlinear3d(;uᵢ = rand(3), \n        σ₁ = 1.0, σ₂ = 1.0, σ₃ = 1.0, \n        a₁ = 3.4, a₂ = 3.4, a₃ = 3.4, \n        b₁ = 0.4, b₂ = 0.4, b₃ = 0.4, \n        c₁₂ = 0.5, c₂₃ = 0.3, c₁₃ = 0.5) = \n    nonlinear3d(uᵢ, a₁, a₂, a₃,  b₁, b₂, b₃, c₁₂, c₂₃, c₁₃, σ₁, σ₂, σ₃)\n", "meta": {"hexsha": "851c1e884d4cb21257ceddffe66eb6964c34e6c5", "size": 2687, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/systems/discretemaps/nonlinear3D_linear_and_nonlinear_coupling.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/CausalityTools.jl-5520caf5-2dd7-5c5d-bfcb-a00e56ac49f7", "max_stars_repo_head_hexsha": "93935b3bc73738c52b004e9cf23d6f6a4778982c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2020-06-11T01:51:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T18:39:43.000Z", "max_issues_repo_path": "src/systems/discretemaps/nonlinear3D_linear_and_nonlinear_coupling.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/CausalityTools.jl-5520caf5-2dd7-5c5d-bfcb-a00e56ac49f7", "max_issues_repo_head_hexsha": "93935b3bc73738c52b004e9cf23d6f6a4778982c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2020-12-21T02:52:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T10:40:08.000Z", "max_forks_repo_path": "src/systems/discretemaps/nonlinear3D_linear_and_nonlinear_coupling.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/CausalityTools.jl-5520caf5-2dd7-5c5d-bfcb-a00e56ac49f7", "max_forks_repo_head_hexsha": "93935b3bc73738c52b004e9cf23d6f6a4778982c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-09-27T08:56:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T15:05:51.000Z", "avg_line_length": 33.5875, "max_line_length": 94, "alphanum_fraction": 0.5489393376, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7619008957698843}}
{"text": "using LightGraphs: AbstractGraph, adjacency_matrix\n\nstruct Graph\n    neighbors::Vector{Set{Int}}\n    active::BitSet\n    peo::Vector{Int}\nend\n\n\n\n# # SIMPLE LINEAR-TIME ALGORITHMS TO TEST CHORDALITY OF GRAPHS, TEST ACYCLICITY OF HYPERGRAPHS, AND SELECTIVELY REDUCE ACYCLIC HYPERGRAPHS\n# # ROBERT E. TARJAN AND MIHALIS YANNAKAKIS\n# Algorithm 4.2 in VA\n\"\"\"\n    maximum_cardinality_search(A)\n\nCompute the perfect elimination ordering for a chordal graph represented by\na symmetric sparse matrix `A`. This function can also be used with AbstractGraph\nobjects from `LightGraphs.jl`.\n\"\"\"\nfunction maximum_cardinality_search(A::SparseMatrixCSC)\n    !issymmetric(A) && error(ArgumentError(\"Matrix must be symmetric\"))\n    n = size(A, 1)\n    peo = zeros(Int, n)\n    cache = zeros(Int, n)\n\n    _maximum_cardinality_search!(peo, A; n = n, cache=cache)\n    return peo\nend\nmaximum_cardinality_search(G::AbstractGraph) = maximum_cardinality_search(adjacency_matrix(G))\n\nfunction _maximum_cardinality_search!(peo, A; n=n, cache=cache)\n    v = 1\n    for i in n:-1:1\n        max_val = 0\n        for j in 1:n\n            peo[j] != 0 && continue\n            if cache[j] > max_val\n                max_val = cache[j]\n                v = j\n            end\n        end\n        peo[v] = i\n        @views cache[(rowvals(A)[nzrange(A, v)])] .+= 1\n    end\n\n    return peo\nend\n\n\n\"\"\"\n    is_chordal(A)\n\nTests if the graph represented by symmetric sparse matrix `A` is chordal. This\nfunction can also be used with AbstractGraph objects from `LightGraphs.jl`.\n\n# References\n* [Simple linear-time algorithms to test chordality of graphs, test acyclicity of hypergraphs, and selectively reduce acyclic hypergraphs](https://epubs.siam.org/doi/pdf/10.1137/0213035?casa_token=A22jkwrsrL0AAAAA:rx-G6F21ubTkMiJmRTH3IKqxmFTo_IVWDDZfJig5lsZxnQtNH2vUKWfZ3eZJKUv9CiKbIPt1VQs) by Robert Tarjan and Mihalis Yannakakis\n\"\"\"\nfunction is_chordal(A::SparseMatrixCSC; peo=nothing)\n    if isnothing(peo)\n        peo = maximum_cardinality_search(A)\n    end\n    i_peo = invperm(peo)\n\n    n = length(peo)\n    f = zeros(Int, n)\n    ind = zeros(Int, n)\n\n    for i in 1:n\n        w = i_peo[i]\n        f[w] = w\n        ind[w] = i\n        for v in rowvals(A)[nzrange(A, w)]\n            peo[v] >= i && continue\n            ind[v] = i\n            if f[v] == v\n                f[v] = w\n            end\n        end\n\n        for v in rowvals(A)[nzrange(A, w)]\n            peo[v] >= i && continue\n            ind[f[v]] < i && return false\n        end\n    end\n    return true\nend\n\nis_chordal(G::AbstractGraph; peo=nothing) = is_chordal(adjacency_matrix(G); peo=peo)\n", "meta": {"hexsha": "5c9592755e777714c9ed657361acc482e3c4659a", "size": 2598, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chordal_graph.jl", "max_stars_repo_name": "tjdiamandis/Chordal.jl", "max_stars_repo_head_hexsha": "0a2b8764931f07219626eaa4ec8bd87df05e0d25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T23:04:03.000Z", "max_issues_repo_path": "src/chordal_graph.jl", "max_issues_repo_name": "tjdiamandis/ChordalDecomp.jl", "max_issues_repo_head_hexsha": "0a2b8764931f07219626eaa4ec8bd87df05e0d25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-28T02:19:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T17:59:42.000Z", "max_forks_repo_path": "src/chordal_graph.jl", "max_forks_repo_name": "tjdiamandis/ChordalDecomp.jl", "max_forks_repo_head_hexsha": "0a2b8764931f07219626eaa4ec8bd87df05e0d25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5494505495, "max_line_length": 330, "alphanum_fraction": 0.6470361817, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7619008954848105}}
{"text": "module LocalMethods\n\nusing SpecialFunctions: besselk, gamma\n\n#M_vρσ is the matern covariance and G_σρ is Gaussian autocovariance model\nexport ℳ_ν, M_νρσ, G_σρ\n\ntν𝒦t(t,ν) = t^ν * besselk(ν, t)\n\n\"\"\"\n    ℳ_ν(t, ν)\n\nCompute (√(2ν)*t) ^ ν * 𝒦ν(√(2ν)*t) where 𝒦ν is the modified Bessel function of the second kind of order ν.\n\n# Example\n```julia-repl\njulia> ℳ_ν(0.0, 0.5)\n1.0\n```\n\"\"\"\nfunction ℳ_ν(t, ν)\n\tpt, pν, p0, p1 = promote(t, ν, 0, 1)\n\treturn (pt==p0) ? p1 : tν𝒦t(√(2pν)*pt,pν) * 2^(1-pν) / gamma(pν)\nend\n\nfunction M_νρσ(t; ν, ρ, σ)\n\treturn σ * σ * ℳ_ν(t/ρ, ν)\nend\n\nfunction G_σρ(t; σ,ρ)\n\treturn σ * σ *exp(-t^2/ρ^2)\n\nend\nend # end module\n", "meta": {"hexsha": "a9e404b5071d396c7e0937034fd39ff1d33fe66f", "size": 639, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code/LocalMethods.jl", "max_stars_repo_name": "hango1996/temperature-analysis", "max_stars_repo_head_hexsha": "2b9d978ed8ab6743b63464c39318a7398ea8aadc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/LocalMethods.jl", "max_issues_repo_name": "hango1996/temperature-analysis", "max_issues_repo_head_hexsha": "2b9d978ed8ab6743b63464c39318a7398ea8aadc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/LocalMethods.jl", "max_forks_repo_name": "hango1996/temperature-analysis", "max_forks_repo_head_hexsha": "2b9d978ed8ab6743b63464c39318a7398ea8aadc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.2571428571, "max_line_length": 107, "alphanum_fraction": 0.6322378717, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799399736476, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7618972678310907}}
{"text": "# Text provided under a Creative Commons Attribution license, CC-BY.  All code is made available under the FSF-approved BSD-3 license.  (c) Lorena A. Barba, Gilbert F. Forsyth 2017. Thanks to NSF for support via CAREER award #1149784.\n# [@LorenaABarba](https://twitter.com/LorenaABarba)\n# Translation to Julia by [@miguelraz_](https://twitter.com/miguelraz_)\n\n# 12 steps to Navier–Stokes\n# =====\n# ***\n\n# In the previous step, we solved the [2D Burgers' equation](./10_Step_8.ipynb): an important equation in the study of fluid mechanics because it contains the full convective nonlinearity of the flow equations. With that exercise, we also build the experience to incrementatlly code a Navier–Stokes solver.\n\n# In the next two steps, we will solve Laplace and then Poisson equation. We will then put it all together!\n\n# Step 9: 2D Laplace Equation\n# ----\n# ***\n\n# Here is Laplace's equation in 2D:\n\n# $$\\frac{\\partial ^2 p}{\\partial x^2} + \\frac{\\partial ^2 p}{\\partial y^2} = 0$$\n\n# We know how to discretize a 2nd order derivative. But think about this for a minute — Laplace's equation has the features typical of diffusion phenomena. For this reason, it has to be discretized with *central differences*, so that the discretization is consistent with the physics we want to simulate.\n\n# The discretized equation is:\n\n# $$\\frac{p_{i+1, j}^n - 2p_{i,j}^n + p_{i-1,j}^n}{\\Delta x^2} + \\frac{p_{i,j+1}^n - 2p_{i,j}^n + p_{i, j-1}^n}{\\Delta y^2} = 0$$\n\n# Notice that the Laplace Equation does not have a time dependence — there is no $p^{n+1}$.  Instead of tracking a wave through time (like in the previous steps), the Laplace equation calculates the equilibrium state of a system under the supplied boundary conditions.\n\n# If you have taken coursework in Heat Transfer, you will recognize the Laplace Equation as the steady-state heat equation.\n\n# Instead of calculating where the system will be at some time $t$, we will iteratively solve for $p_{i,j}^n$ until it meets a condition that we specify.  The system will reach equilibrium only as the number of iterations tends to $\\infty$, but we can approximate the equilibrium state by iterating until the change between one iteration and the next is *very* small.\n\n# Let's rearrange the discretized equation, solving for $p_{i,j}^n$:\n\n# $$p_{i,j}^n = \\frac{\\Delta y^2(p_{i+1,j}^n+p_{i-1,j}^n)+\\Delta x^2(p_{i,j+1}^n + p_{i,j-1}^n)}{2(\\Delta x^2 + \\Delta y^2)}$$\n\n# Using second-order central-difference schemes in both directions is the most widely applied method for the Laplace operator. It is also known as the **five-point difference operator**, alluding to its stencil.\n\n# We are going to solve Laplace's equation numerically by assuming an initial state of $p=0$ everywhere. Then we add boundary conditions as follows:\n\n# $p=0$ at $x=0$\n\n# $p=y$ at $x=2$\n\n# $\\frac{\\partial p}{\\partial y}=0$ at $y=0, \\ 1$\n\n# Under these conditions, there is an analytical solution for Laplace's equation:\n\n# $$p(x,y)=\\frac{x}{4}-4\\sum_{n=1,odd}^{\\infty}\\frac{1}{(n\\pi)^2\\sinh2n\\pi}\\sinh n\\pi x\\cos n\\pi y$$\n\n# ### Exercise\n\n# Write your own code to solve Poisson's equation using loops, in the style of coding used in our first lessons.\n# Then, consider the demonstration of how to write it using functions (below) and modify your code in that style.\n# Can you think of reasons to abandon the old style and adopt modular coding?\n\n# Other tips:\n\n# + Visualize each step of the iterative process\n# + Think about what the boundary conditions are doing\n# + Think about what the PDE is doing\n\n# ### Using functions\n\n# Remember the lesson on writing [functions with Julia](./11_Defining_Functions_in_Julia.jl)? We will use that style of code in this exercise.\n\n# We're going to define two functions: one that plots our data in a 3D projection plot and the other that iterates to solve\n# for $p$ until the change in the [L1 Norm][1] of $p$ is less than a specified value.\n\n# [1]: http://en.wikipedia.org/wiki/Norm_(mathematics)#Taxicab_norm_or_Manhattan_norm\n\n\nusing Plots\n\n# TODO PLOT\nfunction  plot2D(x, y, p)\n    fig = pyplot.figure(figsize=(11, 7), dpi=100)\n    ax = fig.gca(projection='3d')\n    X, Y = numpy.meshgrid(x, y)\n    surf = ax.plot_surface(X, Y, p[:], rstride=1, cstride=1, cmap=cm.viridis,\n            linewidth=0, antialiased=False)\n    ax.set_xlim(0, 2)\n    ax.set_ylim(0, 1)\n    ax.view_init(30, 225)\n    ax.set_xlabel('$x$')\n    ax.set_ylabel('$y$')\nend\n\n\n# The function `plot2D` takes three arguments, an x-vector, a y-vector and our p matrix.\n#     Given these three values, it produces a 3D projection plot,\n#     sets the plot limits and gives us a nice viewing angle.\n\n# $$p_{i,j}^n = \\frac{\\Delta y^2(p_{i+1,j}^n+p_{i-1,j}^n)+\\Delta x^2(p_{i,j+1}^n + p_{i,j-1}^n)}{2(\\Delta x^2 + \\Delta y^2)}$$\n\n\nfunction laplace2d(p, y, dx, dy, l1norm_target)\n    l1norm = 1\n    pn = empty(p)\n\n    while l1norm > l1norm_target\n        pn = copy(p)\n        p[2:end, 2:end] = ((dy^2 * (pn[2:end, 2:] + pn[2:end, 0:-2]) +\n                         dx^2 * (pn[2:, 2:end] + pn[0:-2, 2:end])) /\n                        (2 * (dx^2 + dy^2)))\n            \n        p[:, begin] = 0  # p = 0 @ x = 0\n        p[:,   end] = y  # p = y @ x = 2\n        p[begin, :] = p[2, :]  # dp/dy = 0 @ y = 0\n        p[end,   :] = p[end-1, :]  # dp/dy = 0 @ y = 1\n        # TODO Port\n        l1norm = (sum(abs.(p[:]) - abs.(pn[:])) /\n                sum(abs.(pn[:]))\n    end\n     \n    return p\nend\n\n# `laplace2d` takes five arguments, the `p` matrix, the `y`-vector, `dx`, `dy` and the value `l1norm_target`.\n# This last value defines how close the `p` matrix should be in two consecutive iterations before the loop breaks and returns the calculated `p` value.\n\n# Note that when executing the cells above in your own notebook, there will be no output.\n# You have *defined* the function but you have not yet *called* the function.\n# It is now available for you to use, the same as `numpy.linspace` or any other function in our namespace.\n\n## Variable declarations\nnx = 31\nny = 31\nc = 1\ndx = 2 / (nx - 1)\ndy = 2 / (ny - 1)\n\n# initial conditions\np = zeros((ny, nx))  # create a XxY vector of 0's\n\n# plotting aids\nx = LinRange(0, 2, nx)\ny = LinRange(0, 1, ny)\n\n##boundary conditions\np[:, begin] = 0  # p = 0 @ x = 0\np[:, end]   = y  # p = y @ x = 2\np[begin, :] = p[2, :]  # dp/dy = 0 @ y = 0\np[end, :]   = p[end-1, :]  # dp/dy = 0 @ y = 1\n\n# Now let's try using our `plot2D` function to look at our initial conditions.\n# If the function has been correctly defined,\n# you should be able to begin typing `plot2D`\n# and hit the **tab** key for auto-complete options.\n\n# TODO PLOT\nplot2D(x, y, p)\n\n# It worked!  This is the initial state of our problem, where the value of `p`\n# is zero everywhere except for along $x=2$ where $p=y$.\n# Now let's try to run our `laplace2d` function with a specified L1 target of .01\n\n# [Hint: if you are having trouble remembering the order in which variables are sent to a function,\n# you can just type `laplace2d(` and the iPython Notebook will put up a little popup box to remind you]\n\np = laplace2d(p, y, dx, dy, 1e-4)\n\n# Now try plotting this new value of `p` with our plot function.\n\n# TODO PLOT\nplot2D(x, y, p)\n\n# ***\n\n## Learn More\n\n# The [next step](./13_Step_10.ipynb) will be to solve Poisson's equation. Watch **Video Lesson 11** on You Tube to understand why we need Poisson's equation in CFD.\n#src=\"https://www.youtube.com/embed/ZjfxA3qq2Lg\"\n\n# And for a detailed walk-through of the discretization of Laplace and Poisson equations (steps 9 and 10), watch **Video Lesson 12** on You Tube:\n#src=\"https://www.youtube.com/embed/iwL8ashXhWU\"\n", "meta": {"hexsha": "a820e77ec8b2bb06dc0184059da50975791ae298", "size": 7593, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lessons/12_Step_9.jl", "max_stars_repo_name": "miguelraz/CFDPython", "max_stars_repo_head_hexsha": "21de302718cde87d2d9cb6993986662f0befc1ee", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-01-25T21:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T01:48:25.000Z", "max_issues_repo_path": "lessons/12_Step_9.jl", "max_issues_repo_name": "miguelraz/CFDJulia", "max_issues_repo_head_hexsha": "21de302718cde87d2d9cb6993986662f0befc1ee", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2022-01-25T20:04:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T20:52:15.000Z", "max_forks_repo_path": "lessons/12_Step_9.jl", "max_forks_repo_name": "miguelraz/CFDJulia", "max_forks_repo_head_hexsha": "21de302718cde87d2d9cb6993986662f0befc1ee", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-23T19:41:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T19:41:12.000Z", "avg_line_length": 42.8983050847, "max_line_length": 367, "alphanum_fraction": 0.6741735809, "num_tokens": 2347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.8824278649085118, "lm_q1q2_score": 0.7618808087654753}}
{"text": "module Probabilities\nusing Base:Integer, AbstractFloat\n\ninclude(\"CheckArgument.jl\")\n\n\"\"\"\n计算排列数 A_n^m,输入需要是整数类型，返回值是BigInt类型，因为排列数很容易变成大数\n\"\"\"\nfunction A(m::Integer, n::Integer)\n    # basic param check\n     if n < m\n        throw(ArgumentError(\"n should be lager than m\"))\n    elseif n <= 0 || m < 0\n        throw(ArgumentError(\"n or m should not be zero or negative\"))\n    elseif m == 0 return 1\n            end\n\n    function A_inner(m, n)\n        if (m <= 1)\n            return n\n        end\n        return A_inner(m - 1, n - 1) * n\n    end\n    return A_inner(BigInt(m), BigInt(n))\nend\n\n\"\"\"\n计算组合数\n\"\"\"\nfunction C(m::Integer, n::Integer)\n    # basic param check\n    if n < m\n        throw(ArgumentError(\"n should be lager than m\"))\n    elseif n <= 0 || m < 0\n        throw(ArgumentError(\"n or m should not be zero or negative\"))\n    elseif m == 0 return 1\n        end\n    return A(BigInt(m), BigInt(n)) / factorial(BigInt(m))\nend\n\n\"\"\"\n计算二项分布的列表\n其中参数n为发生次数，p为单次独立事件的概率\nBinomial_Distribution(n::Integer, p)\n返回值是一个列表\n\"\"\"\nfunction Binomial_Distribution(n::Integer, p::AbstractFloat)\n    check_probabilities(p) \n    resList = []\n\tfor k = 0:n\n\t\t# @info(k)\n\t\tpush!(resList, C(k, n) * p^k * (1 - p)^(n - k))\n\tend\n\treturn resList\nend\n\n\"\"\"\n泊松分布\nλᵏℯ^λ / k!,k=0,1,2\nλ=n⋅p\nfunction Poisson_Distribution(num::Integer, λ)\n\"\"\"\nfunction Poisson_Distribution(range::AbstractRange, λ::Real)\n    check_is_nonnegative(λ, range[1])\n    resList = []\n    for k in range\n        push!(resList, λ^k * ℯ^-λ / factorial(big(k)))\n    end\n    return resList\nend\n\n\"\"\"\n    几何分布\n他的每一项为 (1-p)^(k-1)*p\n起始项为k=1zz\nfunction Geometric_distribution(num::Integer, p::AbstractFloat)\n\"\"\"\nfunction Geometric_distribution(range::AbstractRange, p::AbstractFloat)\n    check_probabilities(p)\n    check_is_nonnegative(range[1])\n    resList = []\n    for k in range\n        push!(resList, p * (1 - p)^(k - 1))\n    end\n    return resList\nend\n\n\"\"\"\n    超几何分布\n从N件产品（其中次品M件）中任取n件，k为取到的次品数\n\np{x=k}=C(k,M)C(n-k,n-M)/C(n,N)\n\"\"\"\nfunction Hypergeometric_Distribution(n::Integer, N::Integer, k::Integer, M::Integer)\n    if !(0 <= k <= n <= N  && k <= M)\n        throw(ArgumentError(\"0 <= k <= n <= N  &&k <= M\"))\n    end\n    return C(k, M) * C(n - k, n - M) / C(n, N)\nend\n\n\"\"\"\n    正态分布\nfunction Normal_Distribution_pdf(range::AbstractRange, μ, σ)\n\"\"\"\nfunction Normal_Distribution_pdf(range::AbstractRange, μ::Real, σ::Real)\ncheck_not_empty(range)\n    check_is_nonnegative(μ)\n    resList = []\n    for x in range\n        constant = 1 / (sqrt(2π) * σ)\n        push!(resList, constant * ℯ^(-(x - μ)^2 / (2 * σ^2)))\n    end\n    return resList\nend\n\n\"\"\"\n    指数分布 概率密度函数\n\nfunction Exponential_Distribution(range::AbstractRange, θ::Real)\n\"\"\"\nfunction Exponential_Distribution_pdf(range::AbstractRange, θ::Real)\n    check_not_empty(range)\n    check_is_nonnegative(range[1])\n    resList = []\n    for x in range\n        push!(resList, (1 / θ) * ℯ^(-x / θ))\n    end\n    return resList\nend     \n\n\"\"\"\n    指数分布\nfunction Exponential_Distribution(range::AbstractRange, θ::Real)\n\"\"\"\nfunction Exponential_Distribution(range::AbstractRange, θ::Real)\n    check_not_empty(range)\n    check_is_nonnegative(range[1])\n    resList = []\n    for x in range\n        push!(resList, 1 - ℯ^(-x / θ))\n    end\n    return resList\nend \nexport A,C\nend", "meta": {"hexsha": "2c0b03bbecdeefa1c574724b42024af59512b56a", "size": 3248, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/probabilities.jl", "max_stars_repo_name": "mudssky/juliaPackages", "max_stars_repo_head_hexsha": "d05bf17542af45d96600b2cc009a6604b3fb4a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/probabilities.jl", "max_issues_repo_name": "mudssky/juliaPackages", "max_issues_repo_head_hexsha": "d05bf17542af45d96600b2cc009a6604b3fb4a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/probabilities.jl", "max_forks_repo_name": "mudssky/juliaPackages", "max_forks_repo_head_hexsha": "d05bf17542af45d96600b2cc009a6604b3fb4a8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4, "max_line_length": 84, "alphanum_fraction": 0.6243842365, "num_tokens": 1110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140206578809, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7618617179733052}}
{"text": "export TimeScaleMODWT\nimport Wavelets\nimport Wavelets: wavelet, maxdyadiclevel, modwt\n\n\"\"\"\n    TimeScaleMODWT <: WaveletProbabilitiesEstimator\n    TimeScaleMODWT(wl::Wavelets.WT.OrthoWaveletClass = Wavelets.WT.Daubechies{12}())\n\nApply the maximal overlap discrete wavelet transform (MODWT) to a\nsignal, then compute probabilities/entropy from the energies at different\nwavelet scales. This implementation is based on Rosso et\nal. (2001)[^Rosso2001].\nOptionally specify a wavelet to be used.\n\nThe probability `p[i]` is the relative/total energy for the i-th wavelet scale.\n\n## Example\n\nManually picking a wavelet is done as follows.\n\n```julia\nusing Entropies, Wavelets\nN = 200\na = 10\nt = LinRange(0, 2*a*π, N)\nx = sin.(t .+  cos.(t/0.1)) .- 0.1;\n\n# Pick a wavelet (if no wavelet provided, defaults to Wavelets.WL.Daubechies{12}())\nwl = Wavelets.WT.Daubechies{12}()\n\n# Compute the probabilities (relative energies) at the different wavelet scales\nprobabilities(x, TimeScaleMODWT(wl))\n```\n\n[^Rosso2001]: Rosso, O. A., Blanco, S., Yordanova, J., Kolev, V., Figliola, A., Schürmann, M., & Başar, E. (2001). Wavelet entropy: a new tool for analysis of short duration brain electrical signals. Journal of neuroscience methods, 105(1), 65-75.\n\"\"\"\nstruct TimeScaleMODWT <: WaveletProbabilitiesEstimator\n    wl::Wavelets.WT.OrthoWaveletClass\n    function TimeScaleMODWT(wl::Wavelets.WT.OrthoWaveletClass = Wavelets.WT.Daubechies{12}())\n        new(wl)\n    end\nend\n\nfunction get_modwt(x::AbstractVector{T}, wl::Wavelets.WT.OrthoWaveletClass = Wavelets.WT.Daubechies{12}()) where T<:Real\n    orthofilter = wavelet(wl)\n    nscales = maxdyadiclevel(x)\n    W = modwt(x, orthofilter, nscales)\nend\n\nfunction energy_at_scale(W::AbstractArray{T, 2}, j::Int) where T<:Real\n    1 <= j <= size(W, 2) || error(\"Scale j does not exist in wave coefficient matrix W. Available scales are j=1:$(size(W, 2))\")\n    Eⱼ = sum(W[:, j] .^ 2)\nend\n\nfunction energy_at_time(W::AbstractArray{T, 2}, t::Int) where T<:Real\n    1 <= t <= size(W, 1) || error(\"Time t does not exist in wave coefficient matrix W. Available times are t=1:$(size(W, 1))\")\n    Eⱼ = sum(W[t, :] .^ 2)\nend\n\nfunction energy_total(W::AbstractArray{T, 2}) where T<:Real\n    Etot = sum(W .^ 2)\nend\n\nfunction relative_wavelet_energy(W::AbstractArray{T, 2}, j::Int) where T<:Real\n    energy_at_scale(W, j) / energy_total(W)\nend\n\nfunction relative_wavelet_energies(W::AbstractArray{T, 2}, js = 1:size(W, 2)) where T<:Real\n    all(1 .<= js .<= size(W, 2)) || error(ArgumentError(\"scales $(js) contains scales not present in wavelet coefficient matrix with scales j=1:$(size(W, 2))\"))\n    [energy_at_scale(W, j) / energy_total(W) for j in js]\nend\n\nfunction time_scale_density(x::AbstractVector{T}, wl::Wavelets.WT.OrthoWaveletClass = WT.Daubechies{12}()) where T\n    W = get_modwt(x, wl)\n    Pⱼs = relative_wavelet_energies(W)\nend\n\nfunction probabilities(x::AbstractVector{T}, est::TimeScaleMODWT) where T<:Real\n    Probabilities(time_scale_density(x, est.wl))\nend\n", "meta": {"hexsha": "81cf8f7ba83b015cb3afe239dcccf5ba1cd7a6ff", "size": 2992, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/wavelet/TimeScaleMODWT.jl", "max_stars_repo_name": "stevengj/Entropies.jl", "max_stars_repo_head_hexsha": "4d94d76f9d1c909a607e97529180a115f6768e00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-08-15T14:23:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T16:12:21.000Z", "max_issues_repo_path": "src/wavelet/TimeScaleMODWT.jl", "max_issues_repo_name": "stevengj/Entropies.jl", "max_issues_repo_head_hexsha": "4d94d76f9d1c909a607e97529180a115f6768e00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2020-11-07T14:26:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T22:02:22.000Z", "max_forks_repo_path": "src/wavelet/TimeScaleMODWT.jl", "max_forks_repo_name": "stevengj/Entropies.jl", "max_forks_repo_head_hexsha": "4d94d76f9d1c909a607e97529180a115f6768e00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-23T16:39:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T16:39:33.000Z", "avg_line_length": 36.9382716049, "max_line_length": 247, "alphanum_fraction": 0.7145721925, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7618280300828233}}
{"text": "# CUR decomposition sketch\n# LinearTimeCUR - Drineas, et  al. \"Fast monte carlo algorithms for matrices iii: computing a compressed approximate matrix decomposition\", SIAM Journal of Computing, 2006.\n#\n# Danny Perry (dperry@cs.utah.edu)\n# April 2015\n\nusing Debug\n\n# CUR decomposition (rank-k)\n# A - the matrix to approximate\n# fro_norm - frobenius norm of A\n# num_cols - number of colums to sample for C (and U)\n# num_rows - number of rows to sample for R (and U)\n# k - rank k to approximate\n#\n# returns C,U,R matrices\n@debug function LinearTimeCUR(A,fro_norm, num_cols,num_rows,k)\n\tn = size(A,1)\n\td = size(A,2)\n\n\tc = num_cols\n\tr = num_rows\n\n\tC = zeros(n,c)\n\tU = zeros(c,r)\n\tR = zeros(r,d)\n\n\tfor i=1:d\n\t\tpc = norm(A[:,i])^2 / fro_norm^2\n\t\tscale = 1/sqrt(c*pc)\n\t\tfor j=1:c\n\t\t\tif rand() <= pc\n\t\t\t\tC[:,j] = scale * A[:,i]\n\t\t\tend\n\t\tend\n\tend\n\tCU,CS,CV = svd(C'*C)\n\tk = min(k, rank(diagm(CS)))\n\tfor i=1:n\n\t\tpc = norm(A[i,:])^2 / fro_norm^2\n\t\tscale = 1/sqrt(r*pc)\n\t\tfor j=1:r\n\t\t\tif rand() <= pc\n\t\t\t\tR[j,:] = scale * A[i,:]\n\t\t\t\tU[:,j] = scale * C[i,:]\n\t\t\tend\n\t\tend\n\tend\n\tU = CV[:,1:k] * pinv(diagm(CS[1:k])) * CU[:,1:k]' * U\n\n\tC,U,R\nend\n\n# This uses a decomposition to choose samples based on the leverage scores\n# Uk,Vk - the first k columns of the matrix U and V, such that  A = USV'\n@debug function LeverageCUR(A,fro_norm,Uk,Vk, num_cols,num_rows,k)\n\tn = size(A,1)\n\td = size(A,2)\n\n\tc = num_cols\n\tr = num_rows\n\n\tC = zeros(n,c)\n\tU = zeros(c,r)\n\tR = zeros(r,d)\n\n\tcol_lev = sum(Vk.^2,2) ./ k\n\trow_lev = sum(Uk.^2,2) ./ k\n\n\tfor i=1:d\n\t\tpc = col_lev[i]\n\t\tscale = 1/sqrt(c*pc)\n\t\tfor j=1:c\n\t\t\tif rand() <= pc\n\t\t\t\tC[:,j] = scale * A[:,i]\n\t\t\tend\n\t\tend\n\tend\n\tCU,CS,CV = svd(C'*C)\n\tk = min(k, rank(diagm(CS)))\n\tfor i=1:n\n\t\tpc = row_lev[i]\n\t\tscale = 1/sqrt(r*pc)\n\t\tfor j=1:r\n\t\t\tif rand() <= pc\n\t\t\t\tR[j,:] = scale * A[i,:]\n\t\t\t\tU[:,j] = scale * C[i,:]\n\t\t\tend\n\t\tend\n\tend\n\tU = CV[:,1:k] * pinv(diagm(CS[1:k])) * CU[:,1:k]' * U\n\n\tC,U,R\nend\n\n\n", "meta": {"hexsha": "10985b04098d4de09bd20d080a5e38d1fb1351f7", "size": 1919, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CUR.jl", "max_stars_repo_name": "daniel-perry/Sketch.jl", "max_stars_repo_head_hexsha": "002de02d3e99b0df0e0a9cd088c6359d9b3301e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-20T21:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-23T19:33:23.000Z", "max_issues_repo_path": "src/CUR.jl", "max_issues_repo_name": "daniel-perry/Sketch.jl", "max_issues_repo_head_hexsha": "002de02d3e99b0df0e0a9cd088c6359d9b3301e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-07-12T17:41:06.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-12T17:41:06.000Z", "max_forks_repo_path": "src/CUR.jl", "max_forks_repo_name": "daniel-perry/Sketch.jl", "max_forks_repo_head_hexsha": "002de02d3e99b0df0e0a9cd088c6359d9b3301e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-09T23:03:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-09T23:03:14.000Z", "avg_line_length": 19.7835051546, "max_line_length": 172, "alphanum_fraction": 0.5888483585, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.761828025806079}}
{"text": "\"\"\"\n`ExponentiatedKernel([ρ=1])`\nThe exponentiated kernel is a Mercer kernel given by:\n```\n    κ(x,y) = exp(ρ²xᵀy)\n```\n\"\"\"\nstruct ExponentiatedKernel{Tr} <: Kernel{Tr}\n    transform::Tr\nend\n@inline kappa(κ::ExponentiatedKernel, xᵀy::T) where {T<:Real} = exp(xᵀy)\n\nmetric(::ExponentiatedKernel) = DotProduct()\n", "meta": {"hexsha": "5e19ef99037e69b2303be081866efcdede628695", "size": 309, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/exponentiated.jl", "max_stars_repo_name": "IsakFalk/KernelFunctions.jl", "max_stars_repo_head_hexsha": "d629d2f8d26e31fa4a07d417d115416292aa7c62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/exponentiated.jl", "max_issues_repo_name": "IsakFalk/KernelFunctions.jl", "max_issues_repo_head_hexsha": "d629d2f8d26e31fa4a07d417d115416292aa7c62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/exponentiated.jl", "max_forks_repo_name": "IsakFalk/KernelFunctions.jl", "max_forks_repo_head_hexsha": "d629d2f8d26e31fa4a07d417d115416292aa7c62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0714285714, "max_line_length": 72, "alphanum_fraction": 0.6828478964, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7618280187062098}}
{"text": "\"\"\"\nStruct for Geometric Brownian Motion\n\n\t\tgbmProcess=GeometricBrownianMotion(σ::num1,μ::num2) where {num1,num2 <: Number}\n\t\nWhere:\\n\n\t\tσ\t=\tvolatility of the process.\n\t\tμ\t=\tdrift of the process.\n\t\tx0\t=\tinitial value.\n\"\"\"\nmutable struct GeometricBrownianMotion{num <: Number, num1 <: Number, num2 <: Number, numtype <: Number} <: ItoProcess{numtype}\n    σ::num\n    μ::num1\n    x0::num2\n    function GeometricBrownianMotion(σ::num, μ::num1, x0::num2) where {num <: Number, num1 <: Number, num2 <: Number}\n        if σ <= 0\n            error(\"Volatility must be positive\")\n        else\n            zero_typed = zero(num) + zero(num1)\n            return new{num, num1, num2, typeof(zero_typed)}(σ, μ, x0)\n        end\n    end\nend\n\nexport GeometricBrownianMotion;\n\nfunction simulate!(X, mcProcess::GeometricBrownianMotion, mcBaseData::AbstractMonteCarloConfiguration, T::Number)\n    @assert T > 0\n    σ_gbm = mcProcess.σ\n    mu_gbm = mcProcess.μ\n    μ_bm = mu_gbm - σ_gbm^2 / 2\n    simulate!(X, BrownianMotion(σ_gbm, μ_bm), mcBaseData, T)\n    S0 = mcProcess.x0\n    # @. X=S0*exp(X);\n    broadcast!(x -> S0 * exp(x), X, X)\n\n    nothing\nend\n", "meta": {"hexsha": "accbdb708aa6951464172feef6a56356c4d4b509", "size": 1134, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/geometric_brownian_motion.jl", "max_stars_repo_name": "rcalxrc08/FinancialMonteCarlo.jl", "max_stars_repo_head_hexsha": "3c7444414ea3a449d3aeb48c182d4c05b37c31b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-09-23T16:39:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T12:46:13.000Z", "max_issues_repo_path": "src/models/geometric_brownian_motion.jl", "max_issues_repo_name": "rcalxrc08/FinancialMonteCarlo.jl", "max_issues_repo_head_hexsha": "3c7444414ea3a449d3aeb48c182d4c05b37c31b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-12-25T03:35:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-07T14:06:39.000Z", "max_forks_repo_path": "src/models/geometric_brownian_motion.jl", "max_forks_repo_name": "rcalxrc08/FinancialMonteCarlo.jl", "max_forks_repo_head_hexsha": "3c7444414ea3a449d3aeb48c182d4c05b37c31b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-04T06:31:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-04T06:31:57.000Z", "avg_line_length": 29.0769230769, "max_line_length": 127, "alphanum_fraction": 0.6428571429, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029487, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7618280180074383}}
{"text": "#!/usr/bin/env julia\n\nusing SEM\nusing LinearAlgebra,Plots,UnPack\n\n#----------------------------------#\n# Set up grid\n#----------------------------------#\nEx = 8; nr1 = 8;\nEy = 8; ns1 = 8;\n\nfunction deform(x,y)\n    x = @. 0.5*(x+1)\n    y = @. 0.5*(y+1)\n    return x,y\nend\n\nifperiodic = [false,false] # [xdir, ydir]\n\nm1 = Mesh(nr1,ns1,Ex,Ey,deform,ifperiodic)\n\n#----------------------------------#\n# case setup\n#----------------------------------#\n# solve with Newton Raphson approach\n#\n# ν∇²u + G(u,x) = f(x), x∈Ω\n#     u = ub,         , x∈∂Ω\n#\n#----------------------------------#\nx1 = m1.x\ny1 = m1.y\n\nfunction G(u,msh::Mesh) # G(u,x⃗)\n    @unpack x,y = msh\n#   Gu = @. u^3\n    Gu = @. -exp.(-u)\n    return Gu\nend\nfunction Gdu(u,msh::Mesh) # d/du G(u,x⃗)\n    @unpack x,y = msh\n#   Gdu = @. 3u^2\n    Gdu = @. exp.(-u)\n    return Gdu\nend\n\nν  = @. 1+0*x1\nu  = @. 0+0*x1 # initial guess (must agree with boundary data)\nδu = @. 0+0*x1 # initialize\nf  = @. 1+0*x1\n\n# contrived example\nkx = 3\nky = 3\nut = @. 0 + sin(kx*pi*x1)*sin(ky*pi*y1) # true solution\nf  = @. ut*((kx^2+ky^2)*pi^2)         # forcing/RHS\nf += G(ut,m1)\n\n# boundary condition\n# 'N': Neumann (homogeneous)\n# 'D': Dirichlet (inhomogeniety applied through boundary data)\nM1 = generateMask(['D','D','D','D'],m1) # [xmin,xmax,ymin,ymax]\n\n#----------------------------------#\n# solve linearized homogeneous equation for δu\n#----------------------------------#\nfunction residual(v,msh::Mesh)\n    resi  = mass(f,msh)\n    resi -= mass(G(v,msh),msh) .+ ν.*lapl(v,msh)\n    resi .= mask(resi,M1)\n    resi .= gatherScatter(resi,m1)\n    return resi\nend\n\nfunction opHlmz(v,k,msh::Mesh) # LHS op\n    Hu = hlmz(v,ν,k,msh)\n    Hu = gatherScatter(Hu,msh)\n    Hu = mask(Hu,M1)\n    return Hu\nend\n\nfor i=1:100\n    local g = G(u,m1)\n    local k = Gdu(u,m1)\n\n    # LHS\n    opLHS(v) = opHlmz(v,k,m1)\n\n    # RHS\n    b  = mass(f,m1)                  # forcing\n    b -= ν.*lapl(u,m1) .+ mass(g,m1) # from LHS\n    b .= mask(b,M1)\n    b .= gatherScatter(b,m1)\n\n    # solve\n    pcg!(δu,b,opLHS,mult=m1.mult,ifv=false)\n    u .+= δu\n\n    r  = residual(u,m1);rr = norm(r,Inf);println(\"iter $i, res norm $rr\")\n    if(rr < 1e-8) break end\nend\n#----------------------------------#\ner=ut-u; er=norm(er,Inf); println(\"Error ∞ norm: $er\")\nplt = meshplt(u,m1)\ndisplay(plt)\n#----------------------------------#\nnothing\n", "meta": {"hexsha": "b96fa5211e252014d29202e464a0f07bb8a2fd42", "size": 2338, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/poissonNonlin.jl", "max_stars_repo_name": "vpuri3/SEM", "max_stars_repo_head_hexsha": "65f9d5bcf5c8270d3095d6f6fdab59566df73259", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/poissonNonlin.jl", "max_issues_repo_name": "vpuri3/SEM", "max_issues_repo_head_hexsha": "65f9d5bcf5c8270d3095d6f6fdab59566df73259", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/poissonNonlin.jl", "max_forks_repo_name": "vpuri3/SEM", "max_forks_repo_head_hexsha": "65f9d5bcf5c8270d3095d6f6fdab59566df73259", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6481481481, "max_line_length": 73, "alphanum_fraction": 0.4824636441, "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.8128673087708698, "lm_q1q2_score": 0.7618280109075688}}
{"text": "# # Approximate Inference using ESS\n\n# Loading the necessary packages and setting seed.\n\nusing AbstractGPs, Plots, Random\nRandom.seed!(1234);\n\n# Loading toy regression \n# [dataset](https://github.com/GPflow/docs/blob/master/doc/source/notebooks/basics/data/regression_1D.csv) \n# taken from GPFlow examples.\n\nx = [0.8658165855998895, 0.6661700880180962, 0.8049218148148531, 0.7714303440386239, \n    0.14790478354654835, 0.8666105548197428, 0.007044577166530286, 0.026331737288148638, \n    0.17188596617099916, 0.8897812990554013, 0.24323574561119998, 0.028590102134105955];\ny = [1.5255314337144372, 3.6434202968230003, 3.010885733911661, 3.774442382979625, \n    3.3687639483798324, 1.5506452040608503, 3.790447985799683, 3.8689707574953, \n    3.4933565751758713, 1.4284538820635841, 3.8715350915692364, 3.7045949061144983];\nscatter(x, y, xlabel=\"x\", ylabel=\"y\")\n\n# Split the observations into train and test set.\n\n(x_train, y_train) = (x[begin:8], y[begin:8]);\n(x_test, y_test) = (x[9:end], y[9:end]);\n\n# Instantiating the kernel.\n\nk = Matern52Kernel()\n\n# Instantiating a Gaussian Process with the given kernel `k`.\n\nf = GP(k)\n\n# Instantiating a `FiniteGP`, a finite dimentional projection at the inputs of the dataset\n# observed under Gaussian Noise with $\\sigma = 0.001$ .\n\nfx = f(x_train, 0.001)\n\n# Data's log-likelihood w.r.t prior `GP`. \n\nlogpdf(fx, y_train)\n\n# Calculating the exact posterior over `f` given `y`. The GP's kernel currently has some\n# arbitrary fixed parameters. \n\np_fx = posterior(fx, y_train)\n\n# Data's log-likelihood under the posterior `GP`. We see that it drastically increases.\n\nlogpdf(p_fx(x_test), y_test)\n\n# Plot the posterior `p_fx` along with the observations.\n\nplt = scatter(x_train, y_train; label = \"Train data\")\nscatter!(plt, x_test, y_test; label = \"Test data\")\nplot!(plt, p_fx, 0:0.001:1; label=\"Posterior\")\n\n# # Elliptical Slice Sampler\n# Previously we computed the log likelihood of the untuned kernel parameters \n# of the GP, $-1.285$. We now also perform approximate inference over said \n# kernel parameters using the \n# [Elliptical Slice Sampling](http://proceedings.mlr.press/v9/murray10a/murray10a.pdf)\n# provided by\n# [EllipticalSliceSampling.jl](https://github.com/TuringLang/EllipticalSliceSampling.jl/).\n# We start of by loading necessary packages.\n\nusing EllipticalSliceSampling, Distributions\n\n# We define a function which returns log-probability of the data under the \n# GP / log-likelihood of the parameters of the GP.\n\nfunction logp(params; x=x_train, y=y_train)\n    kernel = ScaledKernel(\n        transform(\n            Matern52Kernel(), \n            ScaleTransform(exp(params[1]))\n        ), \n        exp(params[2])\n    )\n    f = GP(kernel)\n    fx = f(x, 0.1)\n    return logpdf(fx, y)\nend\n\n# We define a Gaussian prior over the joint distribution on kernel parameters\n# space. Since we have only two parameters, we define a multi-variate Gaussian\n# of dimension two.\n\nprior = MvNormal(2, 1)\n\n# Sanity check for the defined `logp` function and `prior` distribution.\n\nlogp(rand(prior))\n\n# Generate 2,000 samples using `ESS_mcmc` provided by `EllipticalSliceSampling.jl`. \n\nsamples = sample(ESSModel(prior, logp), ESS(), 2_000; progress=false)\nsamples_mat = reduce(hcat, samples)';\n\n# Mean of samples of both the parameters.\n\nmean_params = mean(samples_mat, dims=1)\n\n# Plot a histogram of the samples for the two parameters. The vertical line in each \n# graph indicates the mean of the samples. \n\nplt = histogram(samples_mat; layout=2, labels=\"Param\")\nvline!(plt, mean_params; layout=2, label=\"Mean\")\n\n# Average log-marginal-probability of data with posterior kernel parameter samples \n# sampled using ESS. We can observe that there is significant improvement over \n# exact posterior with default kernel parameters.\n\nmean(logp(param; x=x_test, y=y_test) for param in samples)\n\n# Plot sampled functions from posterior with tuned parameters\n\n\nplt = scatter(x_train, y_train; label=\"Train data\")\nscatter!(plt, x_train, y_train; label=\"Test data\")\nfor params in @view(samples[(end-100):end,:])\n    opt_kernel = ScaledKernel(\n        transform(\n            Matern52Kernel(), \n            ScaleTransform(exp(params[1]))\n        ), \n        exp(params[2])\n    )\n    f = GP(opt_kernel)\n    p_fx = posterior(f(x, 0.1), y)\n    sampleplot!(plt, p_fx(collect(0:0.02:1)), 1)\nend\nplt\n\n\n", "meta": {"hexsha": "877565d5c549ecd2f327b0696b858681248ebabf", "size": 4324, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/EllipticalSliceSampling.jl", "max_stars_repo_name": "yiyuezhuo/AbstractGPs.jl", "max_stars_repo_head_hexsha": "23b7581849384c1f283e510c7394e033377d720b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-14T18:07:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-14T18:07:15.000Z", "max_issues_repo_path": "examples/EllipticalSliceSampling.jl", "max_issues_repo_name": "cscherrer/AbstractGPs.jl", "max_issues_repo_head_hexsha": "19c63ac7345d55531d7ed9f5789c82151dd7d8e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/EllipticalSliceSampling.jl", "max_forks_repo_name": "cscherrer/AbstractGPs.jl", "max_forks_repo_head_hexsha": "19c63ac7345d55531d7ed9f5789c82151dd7d8e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0296296296, "max_line_length": 107, "alphanum_fraction": 0.7252543941, "num_tokens": 1255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787538, "lm_q2_score": 0.8459424411924674, "lm_q1q2_score": 0.7617963611184965}}
{"text": "\n# The function rref(), but with the modification that it also returns the pivot vector\n\nexport rref_with_pivots, rref_with_pivots!\n\nfunction rref_with_pivots!(A::Matrix{T}, ɛ=T <: Union{Rational,Integer} ? 0 : eps(norm(A,Inf))) where T\n    nr, nc = size(A)\n    pivots = Vector{Int64}()\n    i = j = 1\n    while i <= nr && j <= nc\n        (m, mi) = findmax(abs.(A[i:nr,j]))\n        mi = mi+i - 1\n        if m <= ɛ\n            if ɛ > 0\n                A[i:nr,j] .= zero(T)\n            end\n            j += 1\n        else\n            for k=j:nc\n                A[i, k], A[mi, k] = A[mi, k], A[i, k]\n            end\n            d = A[i,j]\n            for k = j:nc\n                A[i,k] /= d\n            end\n            for k = 1:nr\n                if k != i\n                    d = A[k,j]\n                    for l = j:nc\n                        A[k,l] -= d*A[i,l]\n                    end\n                end\n            end\n            append!(pivots,j)\n            i += 1\n            j += 1\n        end\n    end\n    return A, pivots\nend\n\nrref_with_pivots_conv(::Type{T}, A::Matrix) where {T} = rref_with_pivots!(copyto!(similar(A, T), A))\n\n\"\"\"\n    rref_with_pivots(A)\nCompute the reduced row echelon form of the matrix A together with the\nposition of the pivots.\nSince this algorithm is sensitive to numerical imprecision,\n* Complex numbers are converted to ComplexF64\n* Integer, Float16 and Float32 numbers are converted to Float64\n* Rational are kept unchanged\n\n```jldoctest\njulia> rref_with_pivots([ 1  2 -1  -4;\n              2  3 -1 -11;\n             -2  0 -3  22])\n3×4 Array{Float64,2}:\n 1.0  0.0  0.0  -8.0\n 0.0  1.0  0.0   1.0\n 0.0  0.0  1.0  -2.0\n Int64[3]:\n 1\n 2\n 3\n\njulia> rref_with_pivots([16  2  3  13;\n              5 11 10   8;\n              9  7  6  12;\n              4 14 15   1])\n4×4 Array{Float64,2}:\n 1.0  0.0  0.0   1.0\n 0.0  1.0  0.0   3.0\n 0.0  0.0  1.0  -3.0\n 0.0  0.0  0.0   0.0\n Int64[3]:\n 1\n 2\n 3\n\njulia> rref_with_pivots([ 1  2  0   3;\n              2  4  0   7])\n2×4 Array{Float64,2}:\n 1.0  2.0  0.0  0.0\n 0.0  0.0  0.0  1.0\n Int64[3]:\n 1\n 4\n```\n\"\"\"\nrref_with_pivots(A::Matrix{T}) where {T} = rref_with_pivots!(copy(A))\nrref_with_pivots(A::Matrix{T}) where {T <: Complex} = rref_with_pivots_conv(ComplexF64, A)\nrref_with_pivots(A::Matrix{ComplexF64}) = rref_with_pivots!(copy(A))\nrref_with_pivots(A::Matrix{T}) where {T <: Union{Integer, Float16, Float32}} = rref_with_pivots_conv(Float64, A)\n\nrref_with_pivots(A::AbstractMatrix) = rref_with_pivots(Matrix(A))\n", "meta": {"hexsha": "e4c8ccb7d478f62aadf615d753ed7df9f3ca8abf", "size": 2487, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/RowEchelon_with_pivots.jl", "max_stars_repo_name": "rmcsqrd/RowEchelon.jl", "max_stars_repo_head_hexsha": "4e406d25b41e928eb416cf48fc4407ea6951ab4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/RowEchelon_with_pivots.jl", "max_issues_repo_name": "rmcsqrd/RowEchelon.jl", "max_issues_repo_head_hexsha": "4e406d25b41e928eb416cf48fc4407ea6951ab4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RowEchelon_with_pivots.jl", "max_forks_repo_name": "rmcsqrd/RowEchelon.jl", "max_forks_repo_head_hexsha": "4e406d25b41e928eb416cf48fc4407ea6951ab4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.90625, "max_line_length": 112, "alphanum_fraction": 0.5190993164, "num_tokens": 964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7617878313500361}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, Measures\n\tusing DataFrames, Plots, LaTeXStrings\n\tRandom.seed!(1)\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.31\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\tdelta = 0.01\n\tgrid = 0:delta:1\n\tf(x,y) = 9/8*(4x+y)*sqrt((1-x)*(1-y))\n\tz = [f(x,y) for y in grid, x in grid]\n\n\tdensityIntegral = sum(z)*delta^2\n\tText(\"2-dimensional Riemann sum over density: $(densityIntegral)\")\nend\n\n# ╔═╡ f3fb9a0e-2294-11eb-227d-135a8b801a20\nbegin\n\tprobB = sum([sum([f(x,y)*delta for y in x:delta:1])*delta for x in grid])\n\tText(\"2-dimensional Riemann sum to evaluate probability: $(probB)\")\nend\n\n# ╔═╡ f3fbcc54-2294-11eb-1a96-b1676ddb7772\nbegin\n\tp1 = surface(grid, grid, z, \n\t\tc=cgrad([:blue, :red]), la=1, camera=(60,50),\n\t\tylabel=\"y\", zlabel=L\"f(x,y)\", legend=:none)\n\tp2 = contourf(grid, grid, z, \n\t\tc=cgrad([:blue, :red]))\n\tp2 = contour!(grid, grid, z, \n\t\tc=:black, xlims=(0,1), ylims=(0,1), ylabel=\"y\", ratio=:equal)\n\n\tplot(p1, p2, size=(800, 400), xlabel=\"x\", margin=5mm)\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.31\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═f3fb9a0e-2294-11eb-227d-135a8b801a20\n# ╠═f3fbcc54-2294-11eb-1a96-b1676ddb7772\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "98b7c8a491341ce252fd96bcf041c6fa98cccf56", "size": 1646, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.31.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.31.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.31.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 26.5483870968, "max_line_length": 74, "alphanum_fraction": 0.6944106926, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513648201266, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.761787831350036}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local iv = try Base.loaded_modules[Base.PkgId(Base.UUID(\"6e696c72-6542-2067-7265-42206c756150\"), \"AbstractPlutoDingetjes\")].Bonds.initial_value catch; b -> missing; end\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)\n        el\n    end\nend\n\n# ╔═╡ dba46e66-8704-42de-938c-d576a1336398\nusing PlutoUI, Plots, Graphs, GraphMakie, CairoMakie, NetworkLayout, Test\n\n# ╔═╡ 4b3e86ea-6973-11ec-014f-9f2708ba86cf\nmd\"\"\"\n\n# RNAfolder\n\n*STMO*\n\n**Menno Van Damme**\n\nThis pluto notebook contains the code for a simple RNA secondary structure prediction tool.\n\n## Nussinov's Algorithm\n\nThe tool uses an algorithm called Nussinov's algorithm. This is a basepair maximization algorithm, it predicts the optimal structure by trying to maximize the amount of paired nucleotides in an RNA sequence. This was one of the first ever algorithms to be used in RNA folding but sadly this algorithm is often too simple to get realistic results. \n\nOther algorithms like energy minimization algorithms try to achieve the same thing but do this by taking base pairing energies, the energies of stacking of certain types of basepairs and the sizes of different structures into account and by calculating the total minimum free energy of the folded RNA. However, implementeing these is a lot more complicated and out of the scope of a project like this.\n\nNussinov's algorithm tries to maximize the amount of paired bases in the structure. It does this using the following formula:\n\n$$S(i,j) = \\max_{i\\leq k<j} \\begin{cases} S(i,j-1) \\qquad\\qquad\\qquad\\qquad\\qquad\\quad\\; \\text{if i unpaired} \\\\S(i,k-1)+S(k+1,j-1)+1 \\qquad \\text{if i, k complementary} \\end{cases}$$\n\nHere $$i$$, $$j$$, and $$k$$ are three positions in the RNA sequence with $$k$$ being equal to $$i$$ or in between $$i$$ and $$j$$. And $$S(i,j)$$ is the score of the subsequence from $$i$$ to $$j$$ given by the aglorithm, this score is equal to the amount of basepairs in the subsequence.\n\nThis formula is used to recursively fill in a dynamic programming matrix $$(S)$$ starting from smaller distances between $$i$$ and $$j$$ to larger ones, thus from smaller to larger subsequences, until $$i = 1$$ and $$j = n$$ (the length of the sequence). $$S(1,n)$$ then represents the score of the entire sequence.\n\nIf position $$j$$ is not paired to any nucleotide, the score does not change. So the score remains the same as the score of the subsequence one nucleotide smaller $$S(i,j-1)$$. If $$j$$ can basepair with a nucleotide $$k$$ in the range $$i:j-1$$ then the sequence is split into two subsequence $$i...k-1$$ and $$k+1...j-1$$, if we add their scores together with a $$+1$$ for the new basepair $$(k,j)$$ we get the score of the entire subsequence. if $$k=i$$ than we have a special case where $$S(i,k-1)=S(i,i-1)$$ this is why $$S(i,i-1)$$ is set to be equal to zero.\n\nThe matrix $$S$$ is initialized by all zeros and new values are only added to the upper right side of the matrix. Note that for two nucleotides to be able to basepair at least three other nucleotides need to be between them, otherwise there is not enough space for them to pair.\n\nBelow you can see the implementation for this algorithm.\n\n\"\"\"\n\n# ╔═╡ d3ee4413-c691-4fba-9f91-f24985fb8a88\nmd\"\"\" The Nussinov matrix for the example RNA looks like this: \"\"\"\n\n# ╔═╡ a455cfa0-ee29-4a4e-8b26-cf91c36985ec\nmd\"\"\"\n\nTo retrieve the basepairs which form the optimally scoring secondary structure we have to perform a backtracking procedure. This procedure starts in the upper right corner of the dynamic programming matrix where $$i=1$$ and $$j=n$$ and continues towards smaller subsequences. If $$S(i,j)$$ is equal to $$S(i,j-1)$$ we can say that $$j$$ is unpaired and we can continue the traceback from $$(i,j-1)$$. Else $$j$$ is paired to a $$k$$. If $$k=i$$ then $$S(i,j)=S(i+1,j-1)+1$$ and we can continue the traceback from $$(i+1,j-1)$$. If $$k \\neq i$$ then $$S(i,j)=S(i,k-1)+S(i+1,j-1)+1$$ and the traceback splits up in the two substructures that were formed $$(i,k-1)$$ and $$(k+1,j-1)$$.\n\nSince the rules of the Nussinov algorithm are simple there are most of the time many roads that lead to the same optimal score for a structure and thus many optimal ways to fold the RNA. This is because score for pairing $$j$$ with $$i$$ might give you the same score as pairing $$j$$ with $$k \\; (\\neq i)$$ or even the same as leaving $$j$$ unpaired.\n\"\"\"\n\n# ╔═╡ aea52dd9-7bcc-4873-9332-36b95592b27b\nmd\"\"\" If we backtrack from $$(i=1,j=n)$$ we get all the pairs in the sequence: \"\"\"\n\n# ╔═╡ 31aeff3d-5083-4c26-a556-847fbe76f9d6\nmd\"\"\"\n\n## Tool\n\n\"\"\"\n\n# ╔═╡ b2084e43-7914-495f-b93e-cf56a87be3c7\nmd\"\"\"\n\nYou can either choose an example sequence or input you own (DNA sequences are also allowed).\n\n\"\"\"\n\n# ╔═╡ 59108cf2-d8a5-4c16-b373-bb6a23d13735\nbegin\n\tchoices = [\"Choose an example sequence:\", \"Input your own sequence:\"]\n\t@bind choice Radio(choices, default = choices[1])\nend\n\n# ╔═╡ ed0a3dc5-99d3-4628-ad5c-7d13e699b353\nbegin\n\tRNAs = [\"GGGAAUAUUAUAUCC\" => \"Example 1 (15 nucleotides)\", \n\t\t\t\"GGGCACUUGACUCGAGCAGACCGUAGCGAUAGCGCGAGAUUUGCCGGACUACCAC\" => \"Example 2 (55 nucleotides)\", \"GCTCGTGCGTCGATGAACAACGCAGCTAGCTGCGAGAATTAATGTGAATTGCAGGACACATTGATCATCGACACTTCGAACGCACTTGCGGCCCCGGGTTCCTCCCGGGGCTACGCCTGTCTGAGCGTCGCTTGAAAAAAAAAAAAAAAAAAAAAA\" => \"Human 5.8S rRNA (156 nucleotides)\",\n\"ATGGACTCCAACACTGTGTCAAGCTTTCAGGTAGACTGCTTTCTTTGGCATGTCCGCAAACGATTTGCAGACCAAGAACTGGGTGATGCCCCATTCCTTGACCGGCTTCGCCGAGACCAGAAGTCCCTAAGAGGAAGAGGCAGCACTCTTGGTCTGGACATCGAGACAGCTACTCGTGCGGGAAAGCAAATAGTGGAGCGGATTCTGGGGGAAGAATCTGATGAAGCACTTAAAATGAATATTGCTTCTGTACCGACTTCACGCTACCTAACTGACATGACTCTTGAAGAAATGTCAAGAGACTGGTTCATGCTCATGCCCAAGCAGAAAGTAGCAGGTTCTCTCTGCATCAAAATGGACCAGGCAATAATGGATAAAACCATCATACTGAAAGCAAATTTCAGTGTGATTTTTGATCGGCTGGAAACCCTAATATTACTTAGAGCTTTCACAGAAGAAGGAGCAATTGTGGGAGAAATCTCACCATTACCTTCTCTTCCAGGACATACTGATGAGGATGTCAAAATTGCAATTGGGGTCCTCATCGGAGGGCTTGAATGGAATGATAACACAGTTCGAGTCTCTGAAACTCTACAGAGATTCACTTGGAGAAGCAGTAATGAGGATGGGAGACCTTCACTCCCTTCAAAACAGAAACGGAAAATGGCGAGAACAATTGAGTCAGAAGTTCGAGGAAATAAGATGGCTGATTGAGGAAATGCGACATAGATTGAAGACCACAGAGAACAGCTTCGAACAAATAACGTTTATGCAAGCTTTACAACTATTGCTTGAAGTGGAGCAAGAGATAAGAACCTTCTCGTTTCAGCTTATTTAA\" => \"Influenza A NS protein gene (838 nucleotides)\"]\n\t\n\tif choice == choices[1]\n\t\t@bind rna Radio(RNAs, default = RNAs[1][1])\n\telseif choice == choices[2]\n\t\t@bind rna TextField()\n\tend\nend\n\n# ╔═╡ 3c7f1384-33ac-4b2d-9a63-4bf412bfa685\nRNA = replace(uppercase(rna), 'T' => 'U')\n\n# ╔═╡ 45b4e0ec-5581-4a28-b6c1-c95b8e6a42bb\nRNA\n\n# ╔═╡ 42921538-4ff4-4902-aefa-d958f41d1404\nmd\"\"\"\n\nBelow you can see the dotbracket strucure of the RNA. This is a representation of the secondary structure by using dots and brackets. Each character represents a nucleotide in the sequence. Opening and closing brackets indicate two nucleotides that basepair. Dots represent unpaired nucleotides. Since guanine (G) and uracil (U) can also pair in RNA, GU pairs are allowed.\n\n\"\"\"\n\n# ╔═╡ fd14341c-f195-4b86-9f9c-379477eed4af\nmd\"\"\"\n\nHere is the visualization of the secondary structure:\n\n\"\"\"\n\n# ╔═╡ ca99ac1a-e4da-41fe-8ab6-834e2b7134b7\nmd\"\"\"\n\nSadly there are no RNA visualization packages for Julia so I've had to use graph visualization libraries, these aren't ideal for this task so the structure might not look entirely correct. If you want a better view of the structure you can copy the following link. It will take you to a ViennaRNA webpage especially designed for displaying secondary RNA structures based on the sequence and dotbracket structure embedded in the link.\n\n\"\"\"\n\n# ╔═╡ 2fbe430d-ab80-406e-aa87-c377d6ed30c2\nmd\"\"\"\n\n## Appendix\n\n\"\"\"\n\n# ╔═╡ e5650185-a6bc-488c-a02b-3c1363c52b8c\n\"\"\"\n\tbasepair(i, j, RNA)\n\nReturns a the logical true if 2 nucleotides can basepair, else false.\n\n\"\"\"\nfunction basepair(i, j, RNA)\n\tpair = string(RNA[i], RNA[j])\n\t# all possible pairs (GU is also possible in RNA):\n\tpairs = [\"AU\", \"UA\", \"GC\", \"CG\", \"UG\", \"GU\"]\n\tif pair in pairs\n\t\treturn true\n\telse\n\t\treturn false\n\tend\nend\n\n# ╔═╡ 2d83c447-1d33-496a-8a39-75d1cb9b2de1\n\"\"\"\n\tNussinov(RNA)\n\nReturns the Nussinov dynamic programming matrix of the RNA sequence.\n\n\"\"\"\nfunction Nussinov(RNA)\n\tn = length(RNA)\n\tS = zeros(n,n)\n\t# recursion happens from smaller to larger distancs between i and j,\n\t# from the diagonal towards the upper right corner in the matrix\n\tfor d in 4:n-1 # at least 3 other nucleotides between a bp\n\t\tfor i in 1:n-d\n\t\t\tj = i + d\n\t\t\t# j doesn't basepair\n\t\t\tnobp_score = S[i,j-1]\n\t\t\t# j basepairs with i (same as with k but S[i,k-1] = 0)\n\t\t\tif basepair(i,j,RNA)\n\t\t\t\tbpi_score = S[i+1,j-1] + 1\n\t\t\telse\n\t\t\t\tbpi_score = 0\n\t\t\tend\n\t\t\t# j basepairs with k in the range [i+1:j-4]\n\t\t\tbpk = []\n\t\t\tfor k in i+1:j-4 # at least 3 other nucleotides between a bp\n\t\t\t\tif basepair(k,j,RNA)\n\t\t\t\t\tpush!(bpk, S[i,k-1] + S[k+1,j-1] + 1)\n\t\t\t\tend\n\t\t\tend\n\t\t\tif !isempty(bpk)\n\t\t\t\tbpk_score = maximum(bpk)\n\t\t\telse\n\t\t\t\tbpk_score = 0\n\t\t\tend\n\t\t\t# the actual score is the maximum of these scores\n\t\t\tS[i,j] = max(nobp_score, bpi_score, bpk_score)\n\t\tend\n\tend\n\treturn S\nend\n\n# ╔═╡ 0a20eddd-24f7-43c6-a0f3-6c1c138fb90a\nS = Nussinov(RNA)\n\n# ╔═╡ 463d18c3-e155-4b73-896f-2bbcdb71bbd2\n\"\"\"\n\ttraceback(RNA, S, i, j; pairs = [])\n\nPerforms a backtracking through the Nussinov dynamic programming matrix starting from position (i,j). Outputs a list of tuples with all the pairs in the sequence.\n\n\"\"\"\nfunction traceback(RNA, S, i, j; pairs = [])\n\tif i < j\n\t\tif  S[i,j] == S[i,j-1] \n\t\t\ttraceback(RNA, S, i, j-1, pairs = pairs)\n\t\telseif S[i,j] == S[i+1,j-1] + 1 && basepair(i, j, RNA)\n\t\t\tpush!(pairs, (i,j))\n\t\t\ttraceback(RNA, S, i+1, j-1, pairs = pairs)\n\t\telse\n\t\t\tfor k in i+1:j-4\n\t\t\t\tif S[i,j] == S[i,k-1] + S[k+1,j-1] + 1 && basepair(k, j, RNA)\n\t\t\t\t\tpush!(pairs, (k,j))\n\t\t\t\t\ttraceback(RNA, S, i, k-1, pairs = pairs)\n\t\t\t\t\ttraceback(RNA, S, k+1, j-1, pairs = pairs)\n\t\t\t\t\tbreak\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n\treturn pairs\nend\n\n# ╔═╡ 43f97b8d-cd9c-4b8f-8821-68542488e49d\npairs = traceback(RNA, S, 1, length(RNA))\n\n# ╔═╡ b156a4c7-6ed9-4a4d-b3c9-d3c06fbc1faf\n\"\"\"\n\tdotbracket(RNA, pairs)\n\nReturns the dotbracket structure of the RNA, given a list of pairs.\n\n\"\"\"\nfunction dotbracket(RNA, pairs)\n\tn = length(RNA)\n\tdb = collect('.' ^ n)\n\tfor (i,j) in pairs\n\t\tdb[i] = '('\n\t\tdb[j] = ')'\n\tend\n\tdb = join(db)\n\treturn db\nend\n\n# ╔═╡ f66956d6-6d0d-42d1-b210-4bdf23ccd0b8\nstructure = dotbracket(RNA, pairs)\n\n# ╔═╡ c86cc53d-4675-4cd1-af75-ec4a717fd7fa\nlink = \"http://nibiru.tbi.univie.ac.at/forna/forna.html?id=url/name&sequence=$RNA&structure=$structure\"\n\n# ╔═╡ e25d53b9-0096-4b6c-85cb-fcae261fabcb\nmd\"\"\" $link \"\"\"\n\n# ╔═╡ f4e866fc-8e18-4917-b515-9cc00175a7a4\nbegin\n\tmyblue = \"#304da5\"\n\tmygreen = \"#2a9d8f\"\n\tmyyellow = \"#e9c46a\"\n\tmyred = \"#e76f51\"\nend\n\n# ╔═╡ 2e8fb274-0658-43f8-bfa0-40f2f1daf6f3\n\"\"\"\n\tplotstructure(RNA, pairs)\n\nPlots the secondary structure of the RNA, given a list of pairs.\n\n\"\"\"\nfunction plotstructure(RNA, pairs)\n\tn = length(RNA)\n\tedges = [(i,i+1) for i in 1:n-1]\n\tappend!(edges, pairs)\n\tG = SimpleGraph(Edge.(edges))\n\tcolors = [mygreen, myblue, myyellow, myred]\n\tmembers = replace(collect(RNA), 'A' => 1, 'U' => 2, 'G' => 3, 'C' => 4)\n\tnodecolors = colors[members]\n\tedgecolors = []\n\tfor edge in sort(edges)\n\t\tif edge in pairs\n\t\t\tpush!(edgecolors, :red)\n\t\telse\n\t\t\tpush!(edgecolors, :black)\n\t\tend\n\tend\n\tnuc = [string(i) for i in RNA]\n\tnodesize = 1000/n\n\tedgewidth = nodesize/3\n\tf, ax, p = graphplot(G,\n\t\t\t\t\t\tlayout = Stress(),\n\t\t\t\t\t\tnode_size = nodesize,\n\t\t\t\t\t\tnode_color = nodecolors,\n\t\t\t\t\t\tedge_color = edgecolors,\n\t\t\t\t\t\tedge_width = edgewidth,\n\t\t\t\t\t\tnlabels = nuc,\n\t\t\t\t\t\tnlabels_align = (:center,:center),\n\t\t\t\t\t\tnlabels_textsize = nodesize,\n\t\t\t\t\t\t)\n\thidedecorations!(ax); hidespines!(ax)\n\tax.aspect = DataAspect()\n\treturn f\t\nend\n\n# ╔═╡ 06983a7b-efca-4167-be5d-a158a4e0858d\nplotstructure(RNA, pairs)\n\n# ╔═╡ 94691ccf-b1ef-4cc3-8eed-72dd543001f5\nmd\"\"\" Unit tests are in the hidden chunk below: \"\"\"\n\n# ╔═╡ 32755c53-eefc-4d40-bf60-a8b21a545c6d\n@testset \"RNAfolder\" begin\n\t\n\t@testset \"Nussinov\" begin\n\t\t\n\t\t@test Nussinov(\"AGCU\") isa Array\n\t\t@test Nussinov(\"AAA\") == zeros(3,3)\n\t\t@test Nussinov(\"AGCU\") == zeros(4,4)\n\t\t@test Nussinov(\"AAAAU\")[1,5] == 1.0\n\t\t\n\tend\n\t\n\t@testset \"Traceback\" begin\n\t\t\n\t\t@test traceback(\"AAA\", Nussinov(\"AAA\"), 1, 3) isa Array\n\t\t@test isempty(traceback(\"AAA\", Nussinov(\"AAA\"), 1, 3))\n\t\t@test traceback(\"AAAAU\", Nussinov(\"AAAAU\"), 1, 5) == [(1,5)]\n\t\t\n\tend\n\t\t\nend\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nCairoMakie = \"13f3f980-e62b-5c42-98c6-ff1f3baf88f0\"\nGraphMakie = \"1ecd5474-83a3-4783-bb4f-06765db800d2\"\nGraphs = \"86223c79-3864-5bf0-83f7-82e725a168b6\"\nNetworkLayout = \"46757867-2c16-5918-afeb-47bfcb05e46a\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nTest = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[compat]\nCairoMakie = \"~0.6.6\"\nGraphMakie = \"~0.3.1\"\nGraphs = \"~1.5.1\"\nNetworkLayout = \"~0.4.4\"\nPlots = \"~1.25.6\"\nPlutoUI = \"~0.7.23\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[AbstractFFTs]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"6f1d9bc1c08f9f4a8fa92e3ea3cb50153a1b40d4\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"1.1.0\"\n\n[[AbstractPlutoDingetjes]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"8eaf9f1b4921132a4cff3f36a1d9ba923b14a481\"\nuuid = \"6e696c72-6542-2067-7265-42206c756150\"\nversion = \"1.1.4\"\n\n[[AbstractTrees]]\ngit-tree-sha1 = \"03e0550477d86222521d254b741d470ba17ea0b5\"\nuuid = \"1520ce14-60c1-5f80-bbc7-55ef81b5835c\"\nversion = \"0.3.4\"\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"af92965fb30777147966f58acb05da51c5616b5f\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.3\"\n\n[[Animations]]\ndeps = [\"Colors\"]\ngit-tree-sha1 = \"e81c509d2c8e49592413bfb0bb3b08150056c79d\"\nuuid = \"27a7e980-b3e6-11e9-2bcd-0b925532e340\"\nversion = \"0.4.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[ArnoldiMethod]]\ndeps = [\"LinearAlgebra\", \"Random\", \"StaticArrays\"]\ngit-tree-sha1 = \"f87e559f87a45bece9c9ed97458d3afe98b1ebb9\"\nuuid = \"ec485272-7323-5ecc-a04f-4719b315124d\"\nversion = \"0.1.0\"\n\n[[ArrayInterface]]\ndeps = [\"Compat\", \"IfElse\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"Static\"]\ngit-tree-sha1 = \"ffc6588e17bcfcaa79dfa5b4f417025e755f83fc\"\nuuid = \"4fba245c-0d91-5ea0-9b3e-6abc04ee57a9\"\nversion = \"4.0.1\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Automa]]\ndeps = [\"Printf\", \"ScanByte\", \"TranscodingStreams\"]\ngit-tree-sha1 = \"d50976f217489ce799e366d9561d56a98a30d7fe\"\nuuid = \"67c07d97-cdcb-5c2c-af73-a7f9c32a568b\"\nversion = \"0.8.2\"\n\n[[AxisAlgorithms]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"66771c8d21c8ff5e3a93379480a2307ac36863f7\"\nuuid = \"13072b0f-2c55-5437-9ae7-d433b7a33950\"\nversion = \"1.0.1\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[CEnum]]\ngit-tree-sha1 = \"215a9aa4a1f23fbd05b92769fdd62559488d70e9\"\nuuid = \"fa961155-64e5-5f13-b03f-caf6b980ea82\"\nversion = \"0.4.1\"\n\n[[Cairo]]\ndeps = [\"Cairo_jll\", \"Colors\", \"Glib_jll\", \"Graphics\", \"Libdl\", \"Pango_jll\"]\ngit-tree-sha1 = \"d0b3f8b4ad16cb0a2988c6788646a5e6a17b6b1b\"\nuuid = \"159f3aea-2a34-519c-b102-8c37f9878175\"\nversion = \"1.0.5\"\n\n[[CairoMakie]]\ndeps = [\"Base64\", \"Cairo\", \"Colors\", \"FFTW\", \"FileIO\", \"FreeType\", \"GeometryBasics\", \"LinearAlgebra\", \"Makie\", \"SHA\", \"StaticArrays\"]\ngit-tree-sha1 = \"774ff1cce3ae930af3948c120c15eeb96c886c33\"\nuuid = \"13f3f980-e62b-5c42-98c6-ff1f3baf88f0\"\nversion = \"0.6.6\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"4b859a208b2397a7a623a03449e4636bdb17bcf2\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+1\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"54fc4400de6e5c3e27be6047da2ef6ba355511f8\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.11.6\"\n\n[[ChangesOfVariables]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"bf98fa45a0a4cee295de98d4c1462be26345b9a1\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.2\"\n\n[[ColorBrewer]]\ndeps = [\"Colors\", \"JSON\", \"Test\"]\ngit-tree-sha1 = \"61c5334f33d91e570e1d0c3eb5465835242582c4\"\nuuid = \"a2cac450-b92f-5266-8821-25eda20663c8\"\nversion = \"0.4.0\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"6b6f04f93710c71550ec7e16b650c1b9a612d0b6\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.16.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"32a2b8af383f11cbb65803883837a149d10dfe8a\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.10.12\"\n\n[[ColorVectorSpace]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"LinearAlgebra\", \"SpecialFunctions\", \"Statistics\", \"TensorCore\"]\ngit-tree-sha1 = \"3f1f500312161f1ae067abe07d13b40f78f32e07\"\nuuid = \"c3611d14-8923-5661-9e6a-0046d554d3a4\"\nversion = \"0.9.8\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"44c37b4636bc54afac5c574d2d02b625349d6582\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.41.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"3daef5523dd2e769dad2365274f760ff5f282c7d\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.11\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[DensityInterface]]\ndeps = [\"InverseFunctions\", \"Test\"]\ngit-tree-sha1 = \"80c3e8639e3353e5d2912fb3a1916b8455e2494b\"\nuuid = \"b429d917-457f-4dbc-8f4c-0cc954292b1d\"\nversion = \"0.4.0\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Distributions]]\ndeps = [\"ChainRulesCore\", \"DensityInterface\", \"FillArrays\", \"LinearAlgebra\", \"PDMats\", \"Printf\", \"QuadGK\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"Test\"]\ngit-tree-sha1 = \"5863b0b10512ed4add2b5ec07e335dc6121065a5\"\nuuid = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nversion = \"0.25.41\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[EllipsisNotation]]\ndeps = [\"ArrayInterface\"]\ngit-tree-sha1 = \"d7ab55febfd0907b285fbf8dc0c73c0825d9d6aa\"\nuuid = \"da5c29d0-fa7d-589e-88eb-ea29b0a81949\"\nversion = \"1.3.0\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FFTW]]\ndeps = [\"AbstractFFTs\", \"FFTW_jll\", \"LinearAlgebra\", \"MKL_jll\", \"Preferences\", \"Reexport\"]\ngit-tree-sha1 = \"463cb335fa22c4ebacfd1faba5fde14edb80d96c\"\nuuid = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nversion = \"1.4.5\"\n\n[[FFTW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea\"\nuuid = \"f5851436-0d7a-5f13-b9de-f02708fd171a\"\nversion = \"3.3.10+0\"\n\n[[FileIO]]\ndeps = [\"Pkg\", \"Requires\", \"UUIDs\"]\ngit-tree-sha1 = \"67551df041955cc6ee2ed098718c8fcd7fc7aebe\"\nuuid = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nversion = \"1.12.0\"\n\n[[FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"8756f9935b7ccc9064c6eef0bff0ad643df733a3\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.12.7\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[FreeType]]\ndeps = [\"CEnum\", \"FreeType2_jll\"]\ngit-tree-sha1 = \"cabd77ab6a6fdff49bfd24af2ebe76e6e018a2b4\"\nuuid = \"b38be410-82b0-50bf-ab77-7b57e271db43\"\nversion = \"4.0.0\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FreeTypeAbstraction]]\ndeps = [\"ColorVectorSpace\", \"Colors\", \"FreeType\", \"GeometryBasics\", \"StaticArrays\"]\ngit-tree-sha1 = \"770050893e7bc8a34915b4b9298604a3236de834\"\nuuid = \"663a7486-cb36-511b-a19d-713bb74d65c9\"\nversion = \"0.9.5\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"0c603255764a1fa0b61752d2bec14cfbd18f7fe8\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+1\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"RelocatableFolders\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"4a740db447aae0fbeb3ee730de1afbb14ac798a1\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.63.1\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"aa22e1ee9e722f1da183eb33370df4c1aeb6c2cd\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.63.1+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"a32d672ac2c967f3deb8a81d828afc739c838a06\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+2\"\n\n[[GraphMakie]]\ndeps = [\"GeometryBasics\", \"Graphs\", \"LinearAlgebra\", \"Makie\", \"NetworkLayout\", \"StaticArrays\"]\ngit-tree-sha1 = \"8fc75ea16d1836cbcfb94227605afd49d5f3facf\"\nuuid = \"1ecd5474-83a3-4783-bb4f-06765db800d2\"\nversion = \"0.3.1\"\n\n[[Graphics]]\ndeps = [\"Colors\", \"LinearAlgebra\", \"NaNMath\"]\ngit-tree-sha1 = \"1c5a84319923bea76fa145d49e93aa4394c73fc2\"\nuuid = \"a2bd30eb-e257-5431-a919-1863eab51364\"\nversion = \"1.1.1\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[Graphs]]\ndeps = [\"ArnoldiMethod\", \"Compat\", \"DataStructures\", \"Distributed\", \"Inflate\", \"LinearAlgebra\", \"Random\", \"SharedArrays\", \"SimpleTraits\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"d727758173afef0af878b29ac364a0eca299fc6b\"\nuuid = \"86223c79-3864-5bf0-83f7-82e725a168b6\"\nversion = \"1.5.1\"\n\n[[GridLayoutBase]]\ndeps = [\"GeometryBasics\", \"InteractiveUtils\", \"Observables\"]\ngit-tree-sha1 = \"70938436e2720e6cb8a7f2ca9f1bbdbf40d7f5d0\"\nuuid = \"3955a311-db13-416c-9275-1d80ed98e5e9\"\nversion = \"0.6.4\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"0fa77022fe4b511826b39c894c90daf5fce3334a\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.17\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"129acf094d168394e80ee1dc4bc06ec835e510a3\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+1\"\n\n[[Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[HypertextLiteral]]\ngit-tree-sha1 = \"2b078b5a615c6c0396c77810d92ee8c6f470d238\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.3\"\n\n[[IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[IfElse]]\ngit-tree-sha1 = \"debdd00ffef04665ccbb3e150747a77560e8fad1\"\nuuid = \"615f187c-cbe4-4ef1-ba3b-2fcf58d6d173\"\nversion = \"0.1.1\"\n\n[[ImageCore]]\ndeps = [\"AbstractFFTs\", \"ColorVectorSpace\", \"Colors\", \"FixedPointNumbers\", \"Graphics\", \"MappedArrays\", \"MosaicViews\", \"OffsetArrays\", \"PaddedViews\", \"Reexport\"]\ngit-tree-sha1 = \"9a5c62f231e5bba35695a20988fc7cd6de7eeb5a\"\nuuid = \"a09fc81d-aa75-5fe9-8630-4744c3626534\"\nversion = \"0.9.3\"\n\n[[ImageIO]]\ndeps = [\"FileIO\", \"Netpbm\", \"OpenEXR\", \"PNGFiles\", \"TiffImages\", \"UUIDs\"]\ngit-tree-sha1 = \"a2951c93684551467265e0e32b577914f69532be\"\nuuid = \"82e4d734-157c-48bb-816b-45c225c6df19\"\nversion = \"0.5.9\"\n\n[[Imath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"87f7662e03a649cffa2e05bf19c303e168732d3e\"\nuuid = \"905a6f67-0a94-5f89-b386-d35d92009cd1\"\nversion = \"3.1.2+0\"\n\n[[IndirectArrays]]\ngit-tree-sha1 = \"012e604e1c7458645cb8b436f8fba789a51b257f\"\nuuid = \"9b13fd28-a010-5f03-acff-a1bbcff69959\"\nversion = \"1.0.0\"\n\n[[Inflate]]\ngit-tree-sha1 = \"f5fc07d4e706b84f72d54eedcc1c13d92fb0871c\"\nuuid = \"d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9\"\nversion = \"0.1.2\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[IntelOpenMP_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d979e54b71da82f3a65b62553da4fc3d18c9004c\"\nuuid = \"1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0\"\nversion = \"2018.0.3+2\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[Interpolations]]\ndeps = [\"AxisAlgorithms\", \"ChainRulesCore\", \"LinearAlgebra\", \"OffsetArrays\", \"Random\", \"Ratios\", \"Requires\", \"SharedArrays\", \"SparseArrays\", \"StaticArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"b15fc0a95c564ca2e0a7ae12c1f095ca848ceb31\"\nuuid = \"a98d9a8b-a2ab-59e6-89dd-64a1c18fca59\"\nversion = \"0.13.5\"\n\n[[IntervalSets]]\ndeps = [\"Dates\", \"EllipsisNotation\", \"Statistics\"]\ngit-tree-sha1 = \"3cc368af3f110a767ac786560045dceddfc16758\"\nuuid = \"8197267c-284f-5f27-9208-e0e47529a953\"\nversion = \"0.5.3\"\n\n[[InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.2\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[Isoband]]\ndeps = [\"isoband_jll\"]\ngit-tree-sha1 = \"f9b6d97355599074dc867318950adaa6f9946137\"\nuuid = \"f1662d9f-8043-43de-a69a-05efc1cc6ff4\"\nversion = \"0.1.1\"\n\n[[IterTools]]\ngit-tree-sha1 = \"fa6287a4469f5e048d763df38279ee729fbd44e5\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.4.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"22df5b96feef82434b07327e2d3c770a9b21e023\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.4.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[KernelDensity]]\ndeps = [\"Distributions\", \"DocStringExtensions\", \"FFTW\", \"Interpolations\", \"StatsBase\"]\ngit-tree-sha1 = \"591e8dc09ad18386189610acafb970032c519707\"\nuuid = \"5ab0869b-81aa-558d-bb23-cbf5423bbe9b\"\nversion = \"0.6.3\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"f2355693d6778a178ade15952b7ac47a4ff97996\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.3.0\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a8f4f279b6fa3c3c4f1adadd78a621b13a506bce\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.9\"\n\n[[LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"0b4a5d71f3e5200a7dff793393e09dfc2d874290\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+1\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"e5718a00af0ab9756305a0392832c8952c7426c1\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.6\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MKL_jll]]\ndeps = [\"Artifacts\", \"IntelOpenMP_jll\", \"JLLWrappers\", \"LazyArtifacts\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"5455aef09b40e5020e1520f551fa3135040d4ed0\"\nuuid = \"856f044c-d86e-5d09-b602-aeab76dc8ba7\"\nversion = \"2021.1.1+2\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[Makie]]\ndeps = [\"Animations\", \"Base64\", \"ColorBrewer\", \"ColorSchemes\", \"ColorTypes\", \"Colors\", \"Contour\", \"Distributions\", \"DocStringExtensions\", \"FFMPEG\", \"FileIO\", \"FixedPointNumbers\", \"Formatting\", \"FreeType\", \"FreeTypeAbstraction\", \"GeometryBasics\", \"GridLayoutBase\", \"ImageIO\", \"IntervalSets\", \"Isoband\", \"KernelDensity\", \"LaTeXStrings\", \"LinearAlgebra\", \"MakieCore\", \"Markdown\", \"Match\", \"MathTeXEngine\", \"Observables\", \"Packing\", \"PlotUtils\", \"PolygonOps\", \"Printf\", \"Random\", \"RelocatableFolders\", \"Serialization\", \"Showoff\", \"SignedDistanceFields\", \"SparseArrays\", \"StaticArrays\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"StructArrays\", \"UnicodeFun\"]\ngit-tree-sha1 = \"56b0b7772676c499430dc8eb15cfab120c05a150\"\nuuid = \"ee78f7c6-11fb-53f2-987a-cfe4a2b5a57a\"\nversion = \"0.15.3\"\n\n[[MakieCore]]\ndeps = [\"Observables\"]\ngit-tree-sha1 = \"7bcc8323fb37523a6a51ade2234eee27a11114c8\"\nuuid = \"20f20a25-4f0e-4fdf-b5d1-57303727442b\"\nversion = \"0.1.3\"\n\n[[MappedArrays]]\ngit-tree-sha1 = \"e8b359ef06ec72e8c030463fe02efe5527ee5142\"\nuuid = \"dbb5928d-eab1-5f90-85c2-b9b0edb7c900\"\nversion = \"0.4.1\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[Match]]\ngit-tree-sha1 = \"1d9bc5c1a6e7ee24effb93f175c9342f9154d97f\"\nuuid = \"7eb4fadd-790c-5f42-8a69-bfa0b872bfbf\"\nversion = \"1.2.0\"\n\n[[MathTeXEngine]]\ndeps = [\"AbstractTrees\", \"Automa\", \"DataStructures\", \"FreeTypeAbstraction\", \"GeometryBasics\", \"LaTeXStrings\", \"REPL\", \"RelocatableFolders\", \"Test\"]\ngit-tree-sha1 = \"70e733037bbf02d691e78f95171a1fa08cdc6332\"\nuuid = \"0a4f8689-d25c-4efe-a92b-7142dfc1aa53\"\nversion = \"0.2.1\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MosaicViews]]\ndeps = [\"MappedArrays\", \"OffsetArrays\", \"PaddedViews\", \"StackViews\"]\ngit-tree-sha1 = \"b34e3bc3ca7c94914418637cb10cc4d1d80d877d\"\nuuid = \"e94cdb99-869f-56ef-bcf0-1ae2bcbe0389\"\nversion = \"0.3.3\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"f755f36b19a5116bb580de457cda0c140153f283\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.6\"\n\n[[Netpbm]]\ndeps = [\"FileIO\", \"ImageCore\"]\ngit-tree-sha1 = \"18efc06f6ec36a8b801b23f076e3c6ac7c3bf153\"\nuuid = \"f09324ee-3d7c-5217-9330-fc30815ba969\"\nversion = \"1.0.2\"\n\n[[NetworkLayout]]\ndeps = [\"GeometryBasics\", \"LinearAlgebra\", \"Random\", \"Requires\", \"SparseArrays\"]\ngit-tree-sha1 = \"cac8fc7ba64b699c678094fa630f49b80618f625\"\nuuid = \"46757867-2c16-5918-afeb-47bfcb05e46a\"\nversion = \"0.4.4\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Observables]]\ngit-tree-sha1 = \"fe29afdef3d0c4a8286128d4e45cc50621b1e43d\"\nuuid = \"510215fc-4207-5dde-b226-833fc4488ee2\"\nversion = \"0.4.0\"\n\n[[OffsetArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"043017e0bdeff61cfbb7afeb558ab29536bbb5ed\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.8\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"887579a3eb005446d514ab7aeac5d1d027658b8f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+1\"\n\n[[OpenEXR]]\ndeps = [\"Colors\", \"FileIO\", \"OpenEXR_jll\"]\ngit-tree-sha1 = \"327f53360fdb54df7ecd01e96ef1983536d1e633\"\nuuid = \"52e1d378-f018-4a11-a4be-720524705ac7\"\nversion = \"0.3.2\"\n\n[[OpenEXR_jll]]\ndeps = [\"Artifacts\", \"Imath_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"923319661e9a22712f24596ce81c54fc0366f304\"\nuuid = \"18a262bb-aa17-5467-a713-aee519bc75cb\"\nversion = \"3.1.1+0\"\n\n[[OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"648107615c15d4e09f7eca16307bc821c1f718d8\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.13+0\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[PDMats]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"SuiteSparse\"]\ngit-tree-sha1 = \"ee26b350276c51697c9c2d88a072b339f9f03d73\"\nuuid = \"90014a1f-27ba-587c-ab20-58faa44d9150\"\nversion = \"0.11.5\"\n\n[[PNGFiles]]\ndeps = [\"Base64\", \"CEnum\", \"ImageCore\", \"IndirectArrays\", \"OffsetArrays\", \"libpng_jll\"]\ngit-tree-sha1 = \"6d105d40e30b635cfed9d52ec29cf456e27d38f8\"\nuuid = \"f57f5aa1-a3ce-4bc8-8ab9-96f992907883\"\nversion = \"0.3.12\"\n\n[[Packing]]\ndeps = [\"GeometryBasics\"]\ngit-tree-sha1 = \"1155f6f937fa2b94104162f01fa400e192e4272f\"\nuuid = \"19eb6ba3-879d-56ad-ad62-d5c202156566\"\nversion = \"0.4.2\"\n\n[[PaddedViews]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"03a7a85b76381a3d04c7a1656039197e70eda03d\"\nuuid = \"5432bcbf-9aad-5242-b902-cca2824c8663\"\nversion = \"0.5.11\"\n\n[[Pango_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"Glib_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9bc1871464b12ed19297fbc56c4fb4ba84988b0d\"\nuuid = \"36c8627f-9965-5494-a995-c6b170f724f3\"\nversion = \"1.47.0+0\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"92f91ba9e5941fc781fecf5494ac1da87bdac775\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.2.0\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PkgVersion]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"a7a7e1a88853564e551e4eba8650f8c38df79b37\"\nuuid = \"eebad327-c553-4316-9ea0-9fa01ccd7688\"\nversion = \"0.1.1\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"6f1b25e8ea06279b5689263cc538f51331d7ca17\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.1.3\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\", \"UnicodeFun\", \"Unzip\"]\ngit-tree-sha1 = \"db7393a80d0e5bef70f2b518990835541917a544\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.25.6\"\n\n[[PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"5152abbdab6488d5eec6a01029ca6697dff4ec8f\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.23\"\n\n[[PolygonOps]]\ngit-tree-sha1 = \"77b3d3605fc1cd0b42d95eba87dfcd2bf67d5ff6\"\nuuid = \"647866c9-e3ac-4575-94e7-e3d426903924\"\nversion = \"0.1.2\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"2cf929d64681236a2e074ffafb8d568733d2e6af\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.3\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[ProgressMeter]]\ndeps = [\"Distributed\", \"Printf\"]\ngit-tree-sha1 = \"afadeba63d90ff223a6a48d2009434ecee2ec9e8\"\nuuid = \"92933f4c-e287-5a05-a399-4b506db050ca\"\nversion = \"1.7.1\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[QuadGK]]\ndeps = [\"DataStructures\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"78aadffb3efd2155af139781b8a8df1ef279ea39\"\nuuid = \"1fd47b50-473d-5c70-9696-f719f8f3bcdc\"\nversion = \"2.4.2\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Ratios]]\ndeps = [\"Requires\"]\ngit-tree-sha1 = \"01d341f502250e81f6fec0afe662aa861392a3aa\"\nuuid = \"c84ed2f1-dad5-54f0-aa8e-dbefe2724439\"\nversion = \"0.4.2\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.2.1\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"37c1631cb3cc36a535105e6d5557864c82cd8c2b\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.5.0\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[RelocatableFolders]]\ndeps = [\"SHA\", \"Scratch\"]\ngit-tree-sha1 = \"cdbd3b1338c72ce29d9584fdbe9e9b70eeb5adca\"\nuuid = \"05181044-ff0b-4ac5-8273-598c1e38db00\"\nversion = \"0.1.3\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.3.0\"\n\n[[Rmath]]\ndeps = [\"Random\", \"Rmath_jll\"]\ngit-tree-sha1 = \"bf3188feca147ce108c76ad82c2792c57abe7b1f\"\nuuid = \"79098fc4-a85e-5d69-aa6a-4863f24498fa\"\nversion = \"0.7.0\"\n\n[[Rmath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"68db32dff12bb6127bac73c209881191bf0efbb7\"\nuuid = \"f50d1b31-88e8-58de-be2c-1cc44531875f\"\nversion = \"0.3.0+0\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[SIMD]]\ngit-tree-sha1 = \"39e3df417a0dd0c4e1f89891a281f82f5373ea3b\"\nuuid = \"fdea26ae-647d-5447-a871-4b548cad5224\"\nversion = \"3.4.0\"\n\n[[ScanByte]]\ndeps = [\"Libdl\", \"SIMD\"]\ngit-tree-sha1 = \"9cc2955f2a254b18be655a4ee70bc4031b2b189e\"\nuuid = \"7b38b023-a4d7-4c5e-8d43-3f3097f304eb\"\nversion = \"0.3.0\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[SignedDistanceFields]]\ndeps = [\"Random\", \"Statistics\", \"Test\"]\ngit-tree-sha1 = \"d263a08ec505853a5ff1c1ebde2070419e3f28e9\"\nuuid = \"73760f76-fbc4-59ce-8f25-708e95d2df96\"\nversion = \"0.4.0\"\n\n[[SimpleTraits]]\ndeps = [\"InteractiveUtils\", \"MacroTools\"]\ngit-tree-sha1 = \"5d7e3f4e11935503d3ecaf7186eac40602e7d231\"\nuuid = \"699a6c99-e7fa-54fc-8d76-47d257e15c1d\"\nversion = \"0.9.4\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"e08890d19787ec25029113e88c34ec20cac1c91e\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"2.0.0\"\n\n[[StackViews]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"46e589465204cd0c08b4bd97385e4fa79a0c770c\"\nuuid = \"cae243ae-269e-4f55-b966-ac2d0dc13c15\"\nversion = \"0.1.1\"\n\n[[Static]]\ndeps = [\"IfElse\"]\ngit-tree-sha1 = \"b4912cd034cdf968e06ca5f943bb54b17b97793a\"\nuuid = \"aedffcd0-7271-4cad-89d0-dc628f76c6d3\"\nversion = \"0.5.1\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"2884859916598f974858ff01df7dfc6c708dd895\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.3.3\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"d88665adc9bcf45903013af0982e2fd05ae3d0a6\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.2.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"51383f2d367eb3b444c961d485c565e4c0cf4ba0\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.14\"\n\n[[StatsFuns]]\ndeps = [\"ChainRulesCore\", \"InverseFunctions\", \"IrrationalConstants\", \"LogExpFunctions\", \"Reexport\", \"Rmath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"f35e1879a71cca95f4826a14cdbf0b9e253ed918\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.15\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"d21f2c564b21a202f4677c0fba5b5ee431058544\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.4\"\n\n[[SuiteSparse]]\ndeps = [\"Libdl\", \"LinearAlgebra\", \"Serialization\", \"SparseArrays\"]\nuuid = \"4607b0f0-06f3-5cda-b6b1-a6196a1729e9\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"bb1064c9a84c52e277f1096cf41434b675cd368b\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.6.1\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[TensorCore]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"1feb45f88d133a655e001435632f019a9a1bcdb6\"\nuuid = \"62fd8b95-f654-4bbd-a8a5-9c27f68ccd50\"\nversion = \"0.1.1\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[TiffImages]]\ndeps = [\"ColorTypes\", \"DataStructures\", \"DocStringExtensions\", \"FileIO\", \"FixedPointNumbers\", \"IndirectArrays\", \"Inflate\", \"OffsetArrays\", \"PkgVersion\", \"ProgressMeter\", \"UUIDs\"]\ngit-tree-sha1 = \"991d34bbff0d9125d93ba15887d6594e8e84b305\"\nuuid = \"731e570b-9d59-4bfa-96dc-6df516fadf69\"\nversion = \"0.5.3\"\n\n[[TranscodingStreams]]\ndeps = [\"Random\", \"Test\"]\ngit-tree-sha1 = \"216b95ea110b5972db65aa90f88d8d89dcb8851c\"\nuuid = \"3bb67fe8-82b1-5028-8e26-92a6c54297fa\"\nversion = \"0.9.6\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[UnicodeFun]]\ndeps = [\"REPL\"]\ngit-tree-sha1 = \"53915e50200959667e78a92a418594b428dffddf\"\nuuid = \"1cfade01-22cf-5700-b092-accc4b62d6e1\"\nversion = \"0.4.1\"\n\n[[Unzip]]\ngit-tree-sha1 = \"34db80951901073501137bdbc3d5a8e7bbd06670\"\nuuid = \"41fe7b60-77ed-43a1-b4f0-825fd5a5650d\"\nversion = \"0.1.2\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"66d72dc6fcc86352f01676e8f0f698562e60510f\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.23.0+0\"\n\n[[WoodburyMatrices]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"de67fa59e33ad156a590055375a30b23c40299d3\"\nuuid = \"efce3f68-66dc-5838-9240-27a6d6f5f9b6\"\nversion = \"0.5.5\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[isoband_jll]]\ndeps = [\"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"a1ac99674715995a536bbce674b068ec1b7d893d\"\nuuid = \"9a68df92-36a6-505f-a73e-abb412b6bfb4\"\nversion = \"0.2.2+0\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"b910cb81ef3fe6e78bf6acee440bda86fd6ae00c\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+1\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─4b3e86ea-6973-11ec-014f-9f2708ba86cf\n# ╠═2d83c447-1d33-496a-8a39-75d1cb9b2de1\n# ╠═45b4e0ec-5581-4a28-b6c1-c95b8e6a42bb\n# ╟─d3ee4413-c691-4fba-9f91-f24985fb8a88\n# ╠═0a20eddd-24f7-43c6-a0f3-6c1c138fb90a\n# ╟─a455cfa0-ee29-4a4e-8b26-cf91c36985ec\n# ╠═463d18c3-e155-4b73-896f-2bbcdb71bbd2\n# ╟─aea52dd9-7bcc-4873-9332-36b95592b27b\n# ╠═43f97b8d-cd9c-4b8f-8821-68542488e49d\n# ╟─31aeff3d-5083-4c26-a556-847fbe76f9d6\n# ╟─b2084e43-7914-495f-b93e-cf56a87be3c7\n# ╟─59108cf2-d8a5-4c16-b373-bb6a23d13735\n# ╟─ed0a3dc5-99d3-4628-ad5c-7d13e699b353\n# ╟─3c7f1384-33ac-4b2d-9a63-4bf412bfa685\n# ╟─42921538-4ff4-4902-aefa-d958f41d1404\n# ╟─f66956d6-6d0d-42d1-b210-4bdf23ccd0b8\n# ╟─fd14341c-f195-4b86-9f9c-379477eed4af\n# ╠═06983a7b-efca-4167-be5d-a158a4e0858d\n# ╟─ca99ac1a-e4da-41fe-8ab6-834e2b7134b7\n# ╟─e25d53b9-0096-4b6c-85cb-fcae261fabcb\n# ╟─2fbe430d-ab80-406e-aa87-c377d6ed30c2\n# ╠═dba46e66-8704-42de-938c-d576a1336398\n# ╠═e5650185-a6bc-488c-a02b-3c1363c52b8c\n# ╠═b156a4c7-6ed9-4a4d-b3c9-d3c06fbc1faf\n# ╠═c86cc53d-4675-4cd1-af75-ec4a717fd7fa\n# ╠═2e8fb274-0658-43f8-bfa0-40f2f1daf6f3\n# ╠═f4e866fc-8e18-4917-b515-9cc00175a7a4\n# ╟─94691ccf-b1ef-4cc3-8eed-72dd543001f5\n# ╟─32755c53-eefc-4d40-bf60-a8b21a545c6d\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "510e0250b34eb62c7356611a97803263989f7d51", "size": 60089, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebook/RNAfolder.jl", "max_stars_repo_name": "menvdamm/RNAfolder.jl", "max_stars_repo_head_hexsha": "0dcdcb2c063242259e391bc4f9a72b57ce441ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebook/RNAfolder.jl", "max_issues_repo_name": "menvdamm/RNAfolder.jl", "max_issues_repo_head_hexsha": "0dcdcb2c063242259e391bc4f9a72b57ce441ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebook/RNAfolder.jl", "max_forks_repo_name": "menvdamm/RNAfolder.jl", "max_forks_repo_head_hexsha": "0dcdcb2c063242259e391bc4f9a72b57ce441ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8342028986, "max_line_length": 892, "alphanum_fraction": 0.7343939823, "num_tokens": 26619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7617878299009877}}
{"text": "using Jchemo, LinearAlgebra\n\nn = 50 ; p = 7 \nXtrain = rand(n, p) \nm = 3 \nXtest = rand(m, p)  \n\nnlv = 5\nfm = pcasvd(Xtrain; nlv = nlv) ;\n#fm = pcaeigen(Xtrain; nlv = nlv) ;\npnames(fm)\nfm.T\nfm.T' * fm.T\nfm.P' * fm.P\n\nJchemo.transform(fm, Xtest)\n\nres = Jchemo.summary(fm, Xtrain) ;\npnames(res)\nres.explvar\nres.contr_var\nres.coord_var\nres.cor_circle\n\n# Weighted PCA\nw = collect(1:n) \nnlv = 5\nfm = pcasvd(Xtrain, w; nlv = nlv) ;\nD = Diagonal(mweights(w)) ;\nfm.T' * D * fm.T\nfm.P' * fm.P\n\n", "meta": {"hexsha": "8b6b9b0331459dde70a2108230e1f3f75dd19b21", "size": 483, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/demos/ex/ex_pcasvd.jl", "max_stars_repo_name": "mlesnoff/Jchemo.jl", "max_stars_repo_head_hexsha": "fea8da15c0458c0e68921cda55a5bf448170eb53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/src/demos/ex/ex_pcasvd.jl", "max_issues_repo_name": "mlesnoff/Jchemo.jl", "max_issues_repo_head_hexsha": "fea8da15c0458c0e68921cda55a5bf448170eb53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/src/demos/ex/ex_pcasvd.jl", "max_forks_repo_name": "mlesnoff/Jchemo.jl", "max_forks_repo_head_hexsha": "fea8da15c0458c0e68921cda55a5bf448170eb53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.6363636364, "max_line_length": 35, "alphanum_fraction": 0.6252587992, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7617799454346963}}
{"text": "using PolyChaos\nusing LinearAlgebra\nusing Distributions\n\n\n## This is an example on the usage of PolyChaos for non-intrusive PCE using\n## the projection and the regression approach and a comarison of them in the univariate setting.\n## f = e^x, x ~ N(1, 0.1)\n\nμ, σ = 1, 0.1\nmaxdegree = 7\n\n# model equation\nfunction model(x)\n    exp.(μ + σ * x)\nend\n\n\n# Analytic refernce\nk_values = 0:maxdegree\ncomputeCoefficient_analytic(k::Int) = exp(μ + 0.5*σ^2) * σ^k / factorial(k)\ny_ana = computeCoefficient_analytic.(k_values)\n\n\n# Setup and compute PCE coefficients of x\nop = GaussOrthoPoly(maxdegree, Nrec=2*maxdegree)\nt2 = Tensor(2, op)\n\n\n\n# ------- Projection -------\nprintln(\"\\t == Projection approach ==\")\n\n# Perform projection via numerical integration\nfunction computeProjection(k::Int, model::Function)\n    g(t) = model(t) * evaluate(k, t, op)\n    γ = t2.get([k,k])\n    integrate(g, op.quad) / γ\nend\n\ny_proj = computeProjection.(0:maxdegree, model)\nprintln.(y_proj)\nprintln()\n\n# Comparison to analytical solution\nprintln(\"Comapre coefficients analytic <-> projection:\")\nprintln(norm(y_ana - y_proj, Inf), \"\\n\")\n\n\n\n# ------- Regression -------\ninclude(\"../src/regression.jl\")\n\nprintln(\"\\t == Regression approach ==\")\n\n# FUTURE: Perform truncation somehow\n\n# Draw n samples, where N > P has to hold\nnSamples = maxdegree * 20\nX = sampleMeasure(nSamples, op)\n\n# Evaluate model -> vector Y\nY = model.(X)\n\n# Build matrix Φ with ϕ(x(i))\n# Φ = Array{Float64}(undef, nSamples, maxdegree+1)\nΦ = [ evaluate(j, X[i], op) for i = 1:nSamples, j = 0:maxdegree]\n\n# Ordinary least squares regression\ny_reg = leastSquares(Φ, Y)\nprintln.(y_reg)\nprintln()\n\n\n# Validation of PCE model\nprintln(\"Comapre coefficients analytic <-> regression:\")\nprintln(norm(y_ana - y_reg, Inf))\n\n# genError = empError(Y, Φ, y_reg)\n# println(\"Determination coefficient R² (normalized empicial error): \", 1 - genError)\n\nϵLoo = looError(Y, Φ, y_reg)\nprintln(\"Determination coefficient Q² (leave-one-out error): \", 1- ϵLoo)\nprintln()\n\n\n\n# ------- Monte-Carlo -------\n# Evaluate model function on same set of previously drawn samples X\ny_mc = model.(X)\n\n\n\n# ------- Comparison of moments -------\nprintln(\"Comparison of moments to analytic solution\")\n\n# Analytic moments for y\nmean_ana = exp(μ + σ^2/2)\nstd_ana = sqrt(exp(2*μ + σ^2) * (exp(σ^2) - 1))\nskew_ana = sqrt(exp(σ^2) - 1) * (exp(σ^2) + 2)\n\n# MC moments\nmean_mc, std_mc, skew_mc = mean(y_mc), std(y_mc), skewness(y_mc)\nerror_mean_mc = abs(mean_ana - mean_mc)\nerror_std_mc = abs(std_ana - std_mc)\nprintln(\"\\t\\t\\t error MC, mean: \\t $(error_mean_mc)\")\nprintln(\"\\t\\t\\t error MC, std: \\t $(error_std_mc)\")\n\n# Projection moments\nmean_proj = mean(y_proj, op)\nstd_proj = std(y_proj, op)\nerror_mean_proj = abs(mean_ana - mean_proj)\nerror_std_proj = abs(std_ana - std_proj)\nprintln(\"\\t\\t\\t error proj, mean: \\t $(error_mean_proj)\")\nprintln(\"\\t\\t\\t error proj, std: \\t $(error_std_proj)\")\n\n# Regression moments\nmean_reg = mean(y_reg, op)\nstd_reg = std(y_reg, op)\nerror_mean_reg = abs(mean_ana - mean_reg)\nerror_std_reg = abs(std_ana - std_reg)\nprintln(\"\\t\\t\\t error reg, mean: \\t $(error_mean_reg)\")\nprintln(\"\\t\\t\\t error reg, std: \\t $(error_std_reg)\")", "meta": {"hexsha": "071e13d9ce8ae395230866b888e257bc8be97185", "size": 3150, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Nonintrusive-univariate.jl", "max_stars_repo_name": "adriangrupp/sparsePolyChaos", "max_stars_repo_head_hexsha": "d35da2584bddd315db30b261ce7433343d9efd58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Nonintrusive-univariate.jl", "max_issues_repo_name": "adriangrupp/sparsePolyChaos", "max_issues_repo_head_hexsha": "d35da2584bddd315db30b261ce7433343d9efd58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Nonintrusive-univariate.jl", "max_forks_repo_name": "adriangrupp/sparsePolyChaos", "max_forks_repo_head_hexsha": "d35da2584bddd315db30b261ce7433343d9efd58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6097560976, "max_line_length": 96, "alphanum_fraction": 0.6895238095, "num_tokens": 942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7617799440705602}}
{"text": "function mass(u, q, w, v, x, t, mu, eta)\n    m = [1.0, 1.0, 1.0];\n    return m;\nend\nfunction flux(u, q, w, v, x, t, mu, eta)\n    g = mu[1];    \n    r = u[1];  # total height: h\n    ru = u[2]; # h*u \n    rv = u[3]; # h*v   \n    r1 = 1/r;\n    uv = ru*r1; # u\n    vv = rv*r1; #v    \n    p = (0.5*g)*(r*r); # 0.5*g*h^2    \n    f = [ru, ru*uv+p, rv*uv, rv, ru*vv, rv*vv+p];\n    # [h*u h*u^2 + 0.5*g*h^2  huv h*v h*u*v h*v^2+0.5*g*h^2]\n    f = reshape(f,(3,2));    \n\n    return f;\nend\nfunction source(u, q, w, v, x, t, mu, eta)\n    s = [0.0, 0.0, 0.0];\n    return s;\nend\nfunction ubou(u, q, w, v, x, t, mu, eta, uhat, n, tau)\n    ub = [0.0, 0.0, 0.0];\n    return ub;\nend\nfunction fbou(u, q, w, v, x, t, mu, eta, uhat, n, tau)\n    f = flux(u, q, w, v, x, t, mu, eta);\n    fb = f[:,1]*n[1] + f[:,2]*n[2] + tau[1]*(u-uhat);\n    return fb;\nend\nfunction initu(x, mu, eta)\n    epsil = 0.1; # perturbation magnitude\n    l = 0.5;     # Gaussian width\n    k = 0.5;     # Sinusoidal wavenumber\n    \n    x1 = x[1];\n    x2 = x[2];\n    \n    # The Bickley jet\n    U = (1/cosh(x2))*(1/cosh(x2));\n\n    # Slightly off-center vortical perturbations\n    Psiprime = exp(-(x2 + l/10)*(x2 + l/10) / (2*(l*l))) * cos(k * x1) * cos(k * x2);\n\n    # Vortical velocity fields (ũ, ṽ) = (-∂_y, +∂_x) ψ̃\n    uprime =  Psiprime * (k * tan(k * x2) + x2 /(l*l)); \n    vprime = -Psiprime * k * tan(k * x1); \n\n    u01 = 1.0; # h\n    u02 = U + epsil * uprime; # h*u\n    u03 = epsil * vprime;  # h*v\n   \n    u0 = [u01, u02, u03];\n    return u0;\nend\n", "meta": {"hexsha": "c51a1fbbaeb3a029fff76c220cb82f5e5d59e8b8", "size": 1506, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Applications/ShallowWater/BickleyJet/pdemodel.jl", "max_stars_repo_name": "rloekvh/Exasim", "max_stars_repo_head_hexsha": "c794431e8b1eff902c2ffad8182d1a9b53339c0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2020-12-09T20:24:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T17:19:23.000Z", "max_issues_repo_path": "Applications/ShallowWater/BickleyJet/pdemodel.jl", "max_issues_repo_name": "rloekvh/Exasim", "max_issues_repo_head_hexsha": "c794431e8b1eff902c2ffad8182d1a9b53339c0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2020-11-25T20:37:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T15:53:11.000Z", "max_forks_repo_path": "Applications/ShallowWater/BickleyJet/pdemodel.jl", "max_forks_repo_name": "rloekvh/Exasim", "max_forks_repo_head_hexsha": "c794431e8b1eff902c2ffad8182d1a9b53339c0d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-11-30T15:34:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T21:06:00.000Z", "avg_line_length": 25.9655172414, "max_line_length": 85, "alphanum_fraction": 0.4608233732, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133430934989, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7617799427064241}}
{"text": "using SimulatedAnnealing\r\nusing Random\r\n\r\n\"\"\"\r\n    Tour\r\n\r\nStruct representing a tour visiting cities.\r\n\r\nFields\r\n------\r\n`order::Vector{Int}` order in which each city is visited.\r\n`D::Matrix` Matrix of distances between each pair of cities. This is stored\r\nto be able to pass it down to new candidates without the need of\r\nrecomputing it. \r\n\"\"\"\r\nstruct Tour\r\n    order::Vector{Int}\r\n    D::Matrix{Float64}\r\nend\r\n\r\n\"\"\"\r\n    Tour(D::Matrix)\r\n\r\nCreate a tour with random ordering of the cities.\r\n\"\"\"\r\nTour(D::Matrix) = Tour(randcycle(size(D, 1)), D)\r\n\r\n\"\"\"\r\n    energy(tour::Tour)\r\n\r\nCompute the energy of a `Tour` by summing the distances of successive cities\r\nin the tour.\r\n\"\"\"\r\nfunction energy(tour::Tour)\r\n    s = 0.0\r\n\r\n    for (k, c1) in enumerate(tour.order)\r\n        c2 = tour.order[mod1(k + 1, length(tour.order))]\r\n        s += tour.D[c1, c2]\r\n    end\r\n\r\n    return s\r\nend\r\n\r\n\"\"\"\r\n    propose_candidate(tour::Tour)\r\n\r\nPropose a new candidate `Tour` by reversing the order of cities between two\r\nrandom indices.\r\n\"\"\"\r\nfunction propose_candidate(tour::Tour)\r\n    n = length(tour.order)\r\n    order = copy(tour.order)\r\n\r\n    # Order will be reversed between i1 and i2 included\r\n    i1 = rand(1:n)\r\n    i2 = mod1(rand(1:n-1) + i1, n)  # Make sure i1 != i2\r\n    \r\n    # Make sure that i1 < i2\r\n    if i1 > i2\r\n        i1, i2 = i2, i1\r\n    end\r\n\r\n    if i1 == 1 && i2 == n\r\n        return Tour(order, tour.D), 0.0\r\n    end\r\n\r\n    city_a1 = order[i1]\r\n    city_a2 = order[i2]\r\n\r\n    city_b1 = order[mod1(i1 - 1, n)]  # Index following i1\r\n    city_b2 = order[mod1(i2 + 1, n)]  # Index preceding i2\r\n\r\n\r\n    dE = (tour.D[city_a1, city_b2] + tour.D[city_a2, city_b1]\r\n          - tour.D[city_a1, city_b1] - tour.D[city_a2, city_b2])\r\n\r\n    order[i1:i2] = reverse(order[i1:i2])\r\n        \r\n    dE = energy(Tour(order, tour.D)) - energy(tour)\r\n\r\n    return Tour(order, tour.D), dE\r\nend\r\n\r\n\r\ncities = [\r\n    [0.0 1.0 2.0 3.0 3.0 3.0 3.0 2.0 1.0 0.0 0.0 0.0] ;\r\n    [0.0 0.0 0.0 0.0 1.0 2.0 3.0 3.0 3.0 3.0 2.0 1.0]\r\n]\r\n\r\n# Distance matrix, common for all Tour objects\r\nD = sqrt.((cities[1, :] .- cities[1, :]').^2 +\r\n          (cities[2, :] .- cities[2, :]').^2)\r\nn = size(D, 1)\r\n\r\n# Initial sampling of the configuration space\r\nsamples = [Tour(D) for _ in 1:1000]\r\n\r\n# Run the algorithm with default parameters\r\nprob = AnnealingOptimization(energy, propose_candidate, samples, n*(n - 1))\r\nbest_tour, tour_length = simulated_annealing(prob)", "meta": {"hexsha": "43ce0bca50740c3af5a7bc5266e94850413c1c71", "size": 2434, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/travelling_salesman.jl", "max_stars_repo_name": "Kolaru/SimulatedAnnealing.jl", "max_stars_repo_head_hexsha": "77d0962763fa4a364e75b6485aeb037ee893c05d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/travelling_salesman.jl", "max_issues_repo_name": "Kolaru/SimulatedAnnealing.jl", "max_issues_repo_head_hexsha": "77d0962763fa4a364e75b6485aeb037ee893c05d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/travelling_salesman.jl", "max_forks_repo_name": "Kolaru/SimulatedAnnealing.jl", "max_forks_repo_head_hexsha": "77d0962763fa4a364e75b6485aeb037ee893c05d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.099009901, "max_line_length": 77, "alphanum_fraction": 0.6002465078, "num_tokens": 795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7617799417089757}}
{"text": "using ITensors\nusing UnicodePlots\nusing Zygote\n\ninclude(\"ising_model.jl\")\ninclude(\"minimize.jl\")\ninclude(\"orthogonalize_eigenvectors.jl\")\n\n# Define the sites of the Hilbert space\nn = 10\ni = [Index(2, \"S=1/2\") for j in 1:n];\n\n# Define the Hamiltonian\nh = 0.5 # field\nH = MPO(ising(n; h), i);\n\n#\n# An example of a cost function for minimizing the energy\n#\nfunction E(psi::MPS)\n  psiHpsi = inner(psi', H, psi)\n  psipsi = inner(psi, psi)\n  return psiHpsi / psipsi\nend\ngradE(psi) = gradient(E, psi)[1]\n\n# Compute the ground state with gradient descent\npsi_init = MPS(i, \"Zp\");\npsi0 = minimize(E, gradE, psi_init; nsteps=50, gamma=0.1, cutoff=1e-5, maxdim=10);\npsi0 /= norm(psi0);\n\n@show E(psi_init), E(psi0)\n\n#\n# Write a cost function the minimizes the energy\n# as well as the overlap between states. For example:\n#\n# c = <psi_1|H|psi_1> + <psi_2|H|psi_2> + ... + \n#     |<psi_1|psi_2>|^2 + |<psi_1|H|psi_3>|^2 + ...\n#\n# Make sure to normalize!\nfunction cost_function(psis::Vector{MPS})\n  nstates = length(psis)\n  N = [inner(psis[i], psis[j]) for i in 1:nstates, j in 1:nstates]\n\n  energy = 0.0\n  for i in 1:nstates\n    energy += inner(psis[i]', H, psis[i]) / N[i, i]\n  end\n\n  off_diagonal_overlap = 0.0\n  for i in 1:(nstates - 1), j in (i + 1):nstates\n    if i != j\n      off_diagonal_overlap += abs2(N[i, j]) / (N[i, i] * N[j, j])\n    end\n  end\n  return energy + off_diagonal_overlap\nend\ngrad_cost_function(psi) = gradient(cost_function, psi)[1]\n\nnstates = 3\npsis_init = [randomMPS(i; linkdims=2) for _ in 1:nstates]\npsis = minimize(cost_function, grad_cost_function, psis_init; nsteps=50, gamma=0.1, cutoff=1e-5, maxdim=10);\npsis = normalize.(psis);\n\n@show E.(psis)\n\n# Plot <Sz> and <Sx> for our eigenvectors\nfor i in 1:nstates\n  plt = lineplot(expect(psis[i], \"Sz\"); title=\"Ising model state $i from gradient descent before orthogonalization\", name=\"Sz\", xlim=[1,10], ylim=[-0.5,0.5])\n  lineplot!(plt, expect(psis[i], \"Sx\"); name=\"Sx\")\n  display(plt)\nend\n# Construct an effective Hamiltonian `Heff` for the states we found\nHeff = [inner(psis[i]', H, psis[j]) for i in 1:nstates, j in 1:nstates]\n\n# Construct the overlap matrix `N` for the states we found\nN = [inner(psis[i], psis[j]) for i in 1:nstates, j in 1:nstates]\n\nprintln(\"\\nHeff = <psi_i|H|psi_j> from DMRG\")\ndisplay(Heff)\n\nprintln(\"\\nN = <psi_i|psi_j> from DMRG\")\ndisplay(N)\n\n#\n# Orthogonalize the eigenvectors by solving the generalized eigenvector\n# equations:\n#\n# <psi_i|H|psi_j><psi_j|v> = lambda_i * <psi_j|v>\n#\n# See `orthogonalize_eigenvectors.jl` for details.\n#\npsis = orthogonalize_eigenvectors(H, psis)\n\n# Replot <Sz> and <Sx> for our eigenvectors\nfor i in 1:nstates\n  plt = lineplot(expect(psis[i], \"Sz\"); title=\"Ising model state $i from gradient descent after orthogonalization\", name=\"Sz\", xlim=[1,10], ylim=[-0.5,0.5])\n  lineplot!(plt, expect(psis[i], \"Sx\"); name=\"Sx\")\n  display(plt)\nend\n\n# Construct an effective Hamiltonian `Heff` for the states we found\nHeff = [inner(psis[i]', H, psis[j]) for i in 1:nstates, j in 1:nstates]\n\n# Construct the overlap matrix `N` for the states we found\nN = [inner(psis[i], psis[j]) for i in 1:nstates, j in 1:nstates]\n\nprintln(\"\\nHeff = <psi_i|H|psi_j> from DMRG\")\ndisplay(Heff)\n\nprintln(\"\\nN = <psi_i|psi_j> from DMRG\")\ndisplay(N)\n", "meta": {"hexsha": "c7abc7cb5e2b8e1180c60d11f02e353f67bae231", "size": 3242, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/02_excitations_gradient_descent.jl", "max_stars_repo_name": "mtfishman/ITensorTutorials.jl", "max_stars_repo_head_hexsha": "dcbc1988299e6a7f3b612faeb31563da38ece3be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-11T10:42:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T01:03:58.000Z", "max_issues_repo_path": "exercises/02_excitations_gradient_descent.jl", "max_issues_repo_name": "mtfishman/ITensorTutorials.jl", "max_issues_repo_head_hexsha": "dcbc1988299e6a7f3b612faeb31563da38ece3be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercises/02_excitations_gradient_descent.jl", "max_forks_repo_name": "mtfishman/ITensorTutorials.jl", "max_forks_repo_head_hexsha": "dcbc1988299e6a7f3b612faeb31563da38ece3be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4385964912, "max_line_length": 157, "alphanum_fraction": 0.6779765577, "num_tokens": 1150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7617493051566321}}
{"text": "###############################\n#\n#        SECOND ORDER\n#\n###############################\n\n# Thanks to https://web.media.mit.edu/~crtaylor/calculator.html\n# For different stencil sizes:\n# c1 = [1, -2, 1]\n# c2 = [-1, 16, -30, 16, -1] / 12\n# c3 = [2, -27, 270, -490, 270, -27, 2] / 180\n# c4 = [-9, 128, -1008, 8064, -14350, 8064, …] / 5040\n# etc\n\nfunction fd_diff2_ord2!(dx2_U, U, dx⁻¹)\n    local c1 = SA[1.0, -2.0, 1.0]\n    for i = 2 : length(U)-1\n        dx2_U[i] = dot(c1, U[i-1 : i+1])\n    end\n    dx2_U[1] = dx2_U[2]\n    dx2_U[end] = dx2_U[end-1]\n    \n    @. dx2_U *= dx⁻¹ ^ 2\n\n    nothing\nend\n\nfunction fd_diff2_ord4!(dx2_U, U, dx⁻¹)\n    local c1 = SA[1.0, -2.0, 1.0]\n    local c2 = SA[-1.0, 16.0, -30.0, 16.0, -1.0] * 0.08333333333333333333\n    for i in 3 : length(U)-2\n        dx2_U[i] = dot(c2, U[i-2 : i+2])\n    end\n    \n    dx2_U[2] = dot(c1, U[1:3])\n    dx2_U[end-1] = dot(c1, U[end-2 : end])\n    \n    dx2_U[1] = dx2_U[2]\n    dx2_U[end] = dx2_U[end-1]\n\n    @. dx2_U *= dx⁻¹ ^ 2\n\n    nothing\nend\n\nfunction fd_diff2_ord6!(dx2_U, U, dx⁻¹)\n    local c1 = SA[1.0, -2.0, 1.0]\n    local c2 = SA[-1.0, 16.0, -30.0, 16.0, -1.0] * 0.08333333333333333333\n    local c3 = SA[2.0, -27.0, 270.0, -490.0, 270.0, -27.0, 2.0]\n    c3 *= 0.00555555555555555555\n    for i in 4 : length(U)-3\n        dx2_U[i] = dot(c3, U[i-3 : i+3])\n    end\n\n    dx2_U[3] = dot(c2, U[1:5])\n    dx2_U[end-2] = dot(c2, U[end-4 : end])\n    \n    dx2_U[2] = dot(c1, U[1:3])\n    dx2_U[end-1] = dot(c1, U[end-2 : end])\n    \n    dx2_U[1] = 2.0*dx2_U[2] - dx2_U[3]\n    dx2_U[end] = 2.0*dx2_U[end-1] - dx2_U[end-2]\n\n    @. dx2_U *= dx⁻¹ ^ 2\n\n    nothing\nend\n", "meta": {"hexsha": "275a4b92aa4d6fcd45309502ea8c882e1d8013da", "size": 1619, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/space_derivatives/second_order.jl", "max_stars_repo_name": "tremelow/StiffKinetic", "max_stars_repo_head_hexsha": "66b5b8ae4db53c9c58efb661f8834e139045e4ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/space_derivatives/second_order.jl", "max_issues_repo_name": "tremelow/StiffKinetic", "max_issues_repo_head_hexsha": "66b5b8ae4db53c9c58efb661f8834e139045e4ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/space_derivatives/second_order.jl", "max_forks_repo_name": "tremelow/StiffKinetic", "max_forks_repo_head_hexsha": "66b5b8ae4db53c9c58efb661f8834e139045e4ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8088235294, "max_line_length": 73, "alphanum_fraction": 0.4922791847, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333005, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7617492947311517}}
{"text": "# consider using the project of this directory for tested versions\nusing PGFPlotsX, KernelDensity, HighestDensityRegions, Distributions, Contour, LinearAlgebra\n\nd = MixtureModel([MultivariateNormal([-1, -1], Diagonal([0.5, 0.5])),\n                  MultivariateNormal([1, 1], Diagonal([0.7, 1.5]))], [0.6, 0.4])\nx = rand(d, 2000)\nx1, x2 = x[1, :], x[2, :]\nk = kde((x1, x2))\nik = InterpKDE(k)\nps = pdf.(Ref(ik), x1, x2)\nqs = 0.05:0.1:0.95\nthresholds = hdr_thresholds(qs, ps)\n\nxgrid = range(minimum(x); stop = maximum(x), length = 100)\npgrid = pdf.(Ref(ik), xgrid, xgrid')\n\np = @pgf Axis({ xlabel = raw\"$x_1$\", ylabel = raw\"$x_2$\", width = \"10cm\", height = \"10cm\" },\n              Plot({ thick }, Table(contours(xgrid, xgrid, pgrid, thresholds))))\npgfsave(\"2d-density.svg\", p)\n", "meta": {"hexsha": "2807ed3dfbb6f3d971e4d5e0d59d2a63ba96512a", "size": 775, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/2d-density.jl", "max_stars_repo_name": "UnofficialJuliaMirror/HighestDensityRegions.jl-ac8b01d9-0237-5573-85ad-ea456511aa8e", "max_stars_repo_head_hexsha": "ff97ea7bd83f8f000156ec6d6e01795ae2010d9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-06-14T01:41:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-06T02:32:48.000Z", "max_issues_repo_path": "examples/2d-density.jl", "max_issues_repo_name": "UnofficialJuliaMirror/HighestDensityRegions.jl-ac8b01d9-0237-5573-85ad-ea456511aa8e", "max_issues_repo_head_hexsha": "ff97ea7bd83f8f000156ec6d6e01795ae2010d9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-02T06:59:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-07T17:57:18.000Z", "max_forks_repo_path": "examples/2d-density.jl", "max_forks_repo_name": "UnofficialJuliaMirror/HighestDensityRegions.jl-ac8b01d9-0237-5573-85ad-ea456511aa8e", "max_forks_repo_head_hexsha": "ff97ea7bd83f8f000156ec6d6e01795ae2010d9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:48:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-02T03:54:16.000Z", "avg_line_length": 38.75, "max_line_length": 92, "alphanum_fraction": 0.6283870968, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333005, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7617492821474322}}
{"text": "using LinearAlgebra\n\nstruct LatticeVars\n    # lattice vectors stored column-wise\n    avec::Array{Float64,2}\n    # magnitude of random displacements added to lattice vectors\n    rndavec::Float64\n    # inverse of lattice vector matrix\n    ainv::Array{Float64,2}\n    # reciprocal lattice vectors\n    bvec::Array{Float64,2}\n    # inverse of reciprocal lattice vector matrix\n    binv::Array{Float64,2}\n    # unit cell volume\n    omega::Float64\n    # Brillouin zone volume\n    omegabz::Float64\n    # any vector with length less than epslat is considered zero\n    epslat::Float64\nend\n\n#=\ncase('avec')\n  read(50,*,err=20) avec(:,1)\n  read(50,*,err=20) avec(:,2)\n  read(50,*,err=20) avec(:,3)\n\navec is stored like lattice vectors in Quantum Espresso\n=#\n\nfunction LatticeVars( LatVecs )\n    @assert size(LatVecs,1) == 3\n    @assert size(LatVecs,2) == 3\n    \n    avec = LatVecs[:,:]\n    ainv = inv(avec)\n    \n    bvec = 2*pi*inv(avec')\n    binv = inv(bvec)\n    \n    omega = det(LatVecs)\n    omegabz = (2*pi)^3/omega\n\n    epslat = 1e-6\n    rndavec = 0.0\n\n    return LatticeVars( avec, rndavec, ainv, bvec, binv, omega, omegabz, epslat )\nend", "meta": {"hexsha": "b936400552d7cf27c8dc5668084bcc323d826f87", "size": 1128, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LAPW/LatticeVars.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "LAPW/LatticeVars.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LAPW/LatticeVars.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 23.5, "max_line_length": 81, "alphanum_fraction": 0.6524822695, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778024535094, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.7616658352135702}}
{"text": "begin\n\t# Exponential Search\n\n# Julia code to Exponential search x in arr[].\n# If x is present then return its location,\n# otherwise return -1\nimport Base:length,show,AbstractArray\narr = [2, 3, 4, 10, 40]\nx = 48\nn = length(arr)\nfunction binarysearch(arr::AbstractArray{},l,r,x)\n    if r >= l\n\t\tvalue=r-l//2\n        mid = round(Int,l + (r - l) // 2)\n        # If element is present at the middle itself \n        if arr[mid] == x \n            return mid \n        # If element is smaller than mid, then it  \n        # can only be present in left subarray \n\t\telseif arr[mid] > x\n            return binarysearch(arr, l, mid-1, x) \n        # Else the element can only be present  \n        # in right subarray \n        else\n            return binarysearch(arr, mid + 1, r, x) \n\t\tend\n    else\n        # Element is not present in the array \n        return -1\n\tend\nend\n\t\n# Returns the position of first\n# occurrence of x in array\nfunction exponentialsearch(arr::AbstractArray{}, n, x)\n    # IF x is present at first \n    # location itself\n    if arr[1] == x\n        return 1\n\tend   \n    # Find range for binary search \n    # j by repeated doubling\n    i = 2\n    while i < n+1 && arr[i] <= x\n        i = i * 2\n\tend \n\tval=round(Int,i/2)\n    # Call binary search for the found range\n    return binarysearch( arr,val, min(i, n), x)\nend     \nglobal result=-1\n\nresult=exponentialsearch(arr, n, x) \n\t\nprintln(\"Result after function execution:\",result)\nif result == -1\n    println(\"Element:\",x,\" is not present in array\",arr)\nelse\n    println(\"Element:\",x,\" is present at index:\", result,\" in array\",arr)\nend\nend\n", "meta": {"hexsha": "8cdeb4a836385e1477f2bddd9305dd20fa357e79", "size": 1594, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Searching_Algorithms/Exponential_Search.jl", "max_stars_repo_name": "Learning-Julia/Algorithms", "max_stars_repo_head_hexsha": "cb8ba88e155c65c58f124bed9870e97a76c85be8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Searching_Algorithms/Exponential_Search.jl", "max_issues_repo_name": "Learning-Julia/Algorithms", "max_issues_repo_head_hexsha": "cb8ba88e155c65c58f124bed9870e97a76c85be8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Searching_Algorithms/Exponential_Search.jl", "max_forks_repo_name": "Learning-Julia/Algorithms", "max_forks_repo_head_hexsha": "cb8ba88e155c65c58f124bed9870e97a76c85be8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7096774194, "max_line_length": 73, "alphanum_fraction": 0.6091593476, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7616336219835653}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing DataFrames\n\tusing HCubature\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.33\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\tM = 4.5\n\tmaxD = 10\nend\n\n# ╔═╡ dde25fec-228e-11eb-2ec8-099e48158d12\nf(x) = (2*pi)^(-length(x)/2) * exp(-(1/2)*x'x)\n\n# ╔═╡ dde2935e-228e-11eb-3074-f3bddb5149fc\nbegin\n\tdf = DataFrame()\n\tfor n in 1:maxD\n    \ta = -M*ones(n)\n    \tb = M*ones(n)\n    \tI,e = hcubature(f, a, b, maxevals = 10^7)\n    append!(df, DataFrame(:n => n, :integral => I, :error => e))\n\tend\n\tdf\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.33\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═dde25fec-228e-11eb-2ec8-099e48158d12\n# ╠═dde2935e-228e-11eb-3074-f3bddb5149fc\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "7c0e69299833ec09854c49cf7990209fd651763a", "size": 1138, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.33.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.33.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.33.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 21.8846153846, "max_line_length": 64, "alphanum_fraction": 0.6898066784, "num_tokens": 604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.7616336177800026}}
{"text": "using ProgressMeter, Plots, StatsBase, Statistics, LaTeXStrings, JLD\n\nfunction RandomWalker(P,L,X0)\n    X = X0\n    Tₛ= 0\n    while abs(X) != round(Int,L/2)\n        X += sample([1,-1], Weights([P,1-P]))\n        Tₛ+= 1\n    end\n    return Tₛ\nend\n\nPList = hcat(0:0.01:1)\nX0List = hcat(-20:20)\nrunnum = 10000\n\nData = zeros(length(X0List),length(PList),2)\nprogress = Progress(length(X0List)*length(PList)*runnum)\n\nfor i in 1:length(X0List)\n    X0 = X0List[i]\n    for j in 1:length(PList)\n        P = PList[j]\n        stepruns = []\n        for run in 1:runnum\n            push!(stepruns,RandomWalker(P,40,X0))\n            next!(progress)\n            update!(progress)\n        end\n        Data[i,j,1] = mean(stepruns)\n        Data[i,j,2] = std(stepruns)\n    end\nend\n\nsave(\"../../Data/Q5/Q5-LT.jld\", \"Data\", Data)\nData=load(\"../../Data/Q5/Q5-LT.jld\")[\"Data\"]\n\nP1 = heatmap(0:0.01:1,-20:20,Data[:,:,1], xaxis=nothing,legend = nothing, yaxis=nothing,title = L\"Average\\ Life\\ time\")\nP2 = contour(0:0.01:1,-20:20,Data[:,:,1], xaxis=nothing, fill = true ,legend = nothing,ylabel = L\"X_{init}\",title = L\"Average\\ Life\\ time\")\nP3 = heatmap(0:0.01:1,-20:20,Data[:,:,2], yaxis=nothing, legend = nothing, xlabel = L\"P\",title = L\"STD\\ of\\ Life\\ time\")\nP4 = contour(0:0.01:1,-20:20,Data[:,:,2], fill = true ,legend = nothing, xlabel = L\"P\",ylabel = L\"X_{init}\",title = L\"STD\\ of\\ Life\\ time\")\n\nPmain1 = begin\n    P_tot = [P2 P4;P1 P3]\n    CBar = plot(heatmap((0:400).*ones(401,1),xlabel =\"\",\n        legend=:none, xticks=:none, yticks=(1:40:401, string.(0:40:400))),\n            heatmap((0:300).*ones(301,1),xlabel = L\"range\",\n                legend=:none, xticks=:none, yticks=(1:30:301, string.(0:30:300))),\n                    layout = (2,1))\n    plot(P_tot...,CBar,\n        layout = @layout[grid(2,2) a{0.035w}],\n        plot_title = L\"Life\\ time\\ of\\ a\\ Random\\ Walker\\ (%$runnum \\ runs)\",size = (800,600))\nend\nsavefig(Pmain1,\"../../Figs/Q5/Q5-cont.pdf\")\n\n\n\nX0Plot = []\nfor X0 in [11,21,31]\n    PLT = begin\n        plot(PList,Data[X0,:,1], linestyle = :dot, c = :black)\n        scatter!(PList,Data[X0,:,1], yerr = Data[X0,:,2], c = :black, markersize = 1.75)\n        scatter!(PList,Data[X0,:,1], ribbon = Data[X0,:,2], markersize = 1.5, c = :purple, markerstrokewidth=0.2)\n        plot!(title = L\"X_{init} = %$(X0List[X0])\",\n            xlabel = L\"P\", ylabel = L\"Avg\\ Life\\ Time\", legend = :none)\n    end\n    push!(X0Plot, PLT)\nend\n\nX0P = plot(X0Plot...,layout = (1,3))\n\nPPlot = []\nfor P in [26,51,76]\n    PLT = begin\n        plot(X0List,Data[:,P,1], linestyle = :dot, c = :black)\n        scatter!(X0List,Data[:,P,1], yerr = Data[:,P,2], c = :black, markersize = 1.75)\n        scatter!(X0List,Data[:,P,1], ribbon = Data[:,P,2], markersize = 1.5, c = :steelblue, markerstrokewidth=0.2)\n        plot!(title = L\"P = %$(PList[P])\",\n            xlabel = L\"X0\", ylabel = L\"Avg\\ Life\\ Time\", legend = :none)\n    end\n    push!(PPlot, PLT)\nend\nPPlot[1]\nPP = plot(PPlot...,layout = (1,3))\n\nPmain2 = plot(PP,X0P,layout = (2,1),size = (850,690), plot_title = L\"Life\\ time\\ of\\ a\\ Random\\ Walker\\ (%$runnum \\ runs)\")\nsavefig(Pmain2,\"../../Figs/Q5/Q5-scat.pdf\")\n", "meta": {"hexsha": "b3a4e928f3a5a0a1a6ef61c1bd84f4c01a04128d", "size": 3132, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSet4/Codes/Q5/Q5-LT.jl", "max_stars_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_stars_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSet4/Codes/Q5/Q5-LT.jl", "max_issues_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_issues_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSet4/Codes/Q5/Q5-LT.jl", "max_forks_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_forks_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-21T11:07:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-21T11:07:08.000Z", "avg_line_length": 35.5909090909, "max_line_length": 139, "alphanum_fraction": 0.569284802, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8615382112085969, "lm_q1q2_score": 0.7616336161693529}}
{"text": "using LinearAlgebra\nusing Distributions\nusing StatsBase\nusing Plots\n\n# Predefined Length\n# The number printed at the end is the p-value of rejecting that the sample was\n# generated by the MLE of p (which is number_of_up/total)\n\npathlength = 1000\nprob = 0.7\n\njumps = sample([-1, 1], pweights([1-prob, prob]), pathlength)\npath = cumsum(jumps)\ncounts = let\n    c = addcounts!(Dict(-1 => 0, 1 => 0), jumps)\n    [c[-1], c[1]]\nend\n\nn=length(path) # Number of trials\np=counts[2]/n # What you think value of p is\n\ndist = Binomial(n, p)\nthreshold = pdf(dist, round(n*p))\nI = [pdf(dist, i) for i in 1:n if pdf(dist, i) < threshold]\nsum(I)\n\n# Streaming version\npvalues = Float64[]\nfor t in 1:15\n    jumps_t = jumps[1:t]\n    path_t = cumsum(jumps_t)\n    counts_t = let\n        c = addcounts!(Dict(-1 => 0, 1 => 0), jumps_t)\n        [c[-1], c[1]]\n    end\n\n    n=length(path_t) # Number of trials\n    p=counts_t[2]/n # What you think value of p is\n    dist = Binomial(n, p)\n    threshold = pdf(dist, round(n*p))\n    I = [pdf(dist, i) for i in 1:n if pdf(dist, i) < threshold]\n    push!(pvalues, sum(I))\nend\n\nplot(pvalues, labels = \"p-value\", legend = :bottomright)\n\n# Single changepoint\npathlength = 1000\nprob1 = rand()\nprob2 = rand()\nchangepoint = rand(1:1000)\njumps1 = sample([-1, 1], pweights([1-prob1, prob1]), changepoint)\njumps2 = sample([-1, 1], pweights([1-prob2, prob2]), 1000-changepoint)                             \njumps = vcat(jumps1, jumps2)\npath = cumsum(jumps)\ncounts = let\n    c = addcounts!(Dict(-1 => 0, 1 => 0), jumps)\n    [c[-1], c[1]]\nend\n\nplot(path, labels=\"path\", xlabel = \"Step\", ylabel = \"Value\")\n\n# Streaming version\npvalues = Float64[]\nprobs = Float64[]\nfor t in 5:1000\n    jumps_t = jumps[1:t]\n    path_t = cumsum(jumps_t)\n    counts_t = let\n        c = addcounts!(Dict(-1 => 0, 1 => 0), jumps_t)\n        [c[-1], c[1]]\n    end\n    \n    n=length(path_t) # Number of trials\n    p=counts_t[2]/n # What you think value of p is\n    push!(probs, p)\n\n    dist = Binomial(n, p)\n    threshold = pdf(dist, round(n*p))\n    I = [pdf(dist, i) for i in 1:n if pdf(dist, i) < threshold]\n    push!(pvalues, sum(I))\nend\n\nplot(probs, legend = :topleft)\n", "meta": {"hexsha": "40a63d0f73303ff388ccf92ce50377d4331bc029", "size": 2151, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ocp.jl", "max_stars_repo_name": "jacobusmmsmit/online-changepoints", "max_stars_repo_head_hexsha": "6eeabec837089565c3f9ae580c3ac8febb022cbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ocp.jl", "max_issues_repo_name": "jacobusmmsmit/online-changepoints", "max_issues_repo_head_hexsha": "6eeabec837089565c3f9ae580c3ac8febb022cbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ocp.jl", "max_forks_repo_name": "jacobusmmsmit/online-changepoints", "max_forks_repo_head_hexsha": "6eeabec837089565c3f9ae580c3ac8febb022cbc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.011627907, "max_line_length": 99, "alphanum_fraction": 0.6145978615, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067276593032, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7616087808179514}}
{"text": "function part1(input)\n    public_keys = parse.(Int, readlines(input))\n    secret_keys = find_log7.(public_keys)\n    encryption_key1 = pow(public_keys[1], secret_keys[2])\n    encryption_key2 = pow(public_keys[2], secret_keys[1])\n    @assert encryption_key1 == encryption_key2\n    return encryption_key1\nend\n\nfunction part2(input)\nend\n\nfunction find_log7(n)\n    i = 0\n    m = 1\n    while m != n\n        m *= 7\n        i += 1\n        if m > 20201227\n            m = mod(m, 20201227)\n        end\n    end\n    return i\nend\n\nfunction pow(b, n)\n    m = 1\n    for i = 1:n\n        m *= b\n        if m > 20201227\n            m = mod(m, 20201227)\n        end\n    end\n    return m\nend\n", "meta": {"hexsha": "a41abc5453b0dfc47471061c3dab79cc975cc3a7", "size": 672, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2020/day25.jl", "max_stars_repo_name": "GunnarFarneback/AdventOfCode.jl", "max_stars_repo_head_hexsha": "2f60011747bfe5d27e954f914f39b4ea2f7b0722", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-01T16:33:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T21:46:33.000Z", "max_issues_repo_path": "2020/day25.jl", "max_issues_repo_name": "GunnarFarneback/AdventOfCode.jl", "max_issues_repo_head_hexsha": "2f60011747bfe5d27e954f914f39b4ea2f7b0722", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/day25.jl", "max_forks_repo_name": "GunnarFarneback/AdventOfCode.jl", "max_forks_repo_head_hexsha": "2f60011747bfe5d27e954f914f39b4ea2f7b0722", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6666666667, "max_line_length": 57, "alphanum_fraction": 0.5699404762, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7616087803862374}}
{"text": "\"\"\"\r\n    cumulants_to_raw_moments(N::Int, max_order::Int)\r\n\r\nExpress all `N`-variate cumulants ``κ`` up to order given by `max_order`\r\nin terms of raw moments ``μ``. Return a Dictionary mapping from\r\nvector ``\\\\mathbf{i}`` (that indicates the cumulant ``κ_{\\\\mathbf{i}}``)\r\nto the corresponding raw moment expressions.\r\n\r\n# Example\r\n\r\n```julia\r\ncumulants_to_raw_moments(2, 2)\r\n\r\nDict{Any,Any} with 5 entries:\r\n  (1, 0) => μ₁₀(t)\r\n  (2, 0) => μ₂₀(t) - ((μ₁₀(t))^2)\r\n  (0, 1) => μ₀₁(t)\r\n  (0, 2) => μ₀₂(t) - ((μ₀₁(t))^2)\r\n  (1, 1) => μ₁₁(t) - ((μ₀₁(t))*(μ₁₀(t)))\r\n```\r\n\"\"\"\r\nfunction cumulants_to_raw_moments(N::Int, max_order::Int, μ=nothing)\r\n\r\n    # following Smith (1995)\r\n\r\n    iter_all = construct_iter_all(N, max_order)\r\n    iter_1 = filter(x -> sum(x) == 1, iter_all)\r\n\r\n    if μ == nothing\r\n        μ = define_μ(N, max_order, iter_all)\r\n    else\r\n        @assert (μ isa Dict) && length(μ) == length(iter_all) \"passed arguments are inconsistent (μ vs N & order)\"\r\n    end\r\n\r\n    K = Dict()\r\n    μ_star = Dict()\r\n\r\n    μ_star[Tuple(fill(0, N))] = 1.0\r\n    for i in 1:N\r\n        eᵢ = iter_1[i]\r\n        K[eᵢ] = μ[eᵢ]\r\n        μ_star[eᵢ] = -μ[eᵢ]\r\n    end\r\n\r\n    for order in 2:max_order\r\n\r\n        iter_order = filter(x -> sum(x) == order, iter_all)\r\n        for r in iter_order\r\n\r\n            ind = findall(x -> x!= 0, r)[end]\r\n            r_sub = r .- iter_1[ind]\r\n            iter_i = filter(x -> all(x .<= r_sub), iter_all)\r\n\r\n            suma = 0.0\r\n            for i in iter_i\r\n                factor = 1.0\r\n                for j in 1:N\r\n                    factor *= binomial(r_sub[j], i[j])\r\n                end\r\n                suma += factor*μ[r.-i]*μ_star[i]\r\n            end\r\n            K[r] = simplify(suma)\r\n\r\n            suma = 0.0\r\n            for i in iter_i\r\n                factor = 1.0\r\n                for j in 1:N\r\n                    factor *= binomial(r_sub[j], i[j])\r\n                end\r\n                suma += factor*(-K[r.-i])*μ_star[i]\r\n            end\r\n            μ_star[r] = simplify(suma)\r\n        end\r\n\r\n    end\r\n\r\n    K\r\n\r\nend\r\n\r\n\"\"\"\r\n    cumulants_to_central_moments(N::Int, max_order::Int)\r\n\r\nExpress all `N`-variate cumulants ``κ`` up to order given by `max_order`\r\nin terms of raw moments ``M``. Return a Dictionary mapping from\r\nvector ``\\\\mathbf{i}`` (that indicates the cumulant ``κ_{\\\\mathbf{i}}``)\r\nto the corresponding central moment expressions.\r\n\"\"\"\r\nfunction cumulants_to_central_moments(N::Int, max_order::Int)\r\n\r\n    # obtain cumulants up to (m_order)^th order in terms of\r\n    # central moments using formula from Balakrishan et al. (1998)\r\n\r\n    K = Dict()\r\n    M_star = Dict()\r\n\r\n    iter_all = construct_iter_all(N, max_order)\r\n    iter_1 = filter(x -> sum(x) == 1, iter_all)\r\n    μ = define_μ(N, 1, iter_1)\r\n    M = define_M(N, max_order, iter_all)\r\n\r\n    M_star[Tuple(zeros(N))] = 1.0\r\n    for i in 1:N\r\n        eᵢ = iter_1[i]\r\n        K[eᵢ] = μ[eᵢ]\r\n        M_star[eᵢ] = 0.0\r\n    end\r\n\r\n    for order in 2:max_order\r\n        # going up through the orders iteratively to build up the expressions (could do recursively?)\r\n\r\n        iter_order = filter(x -> sum(x) == order, iter_all)\r\n        for r in iter_order\r\n\r\n            ind = findall(x -> x!= 0, r)[end]\r\n            r_sub = r .- iter_1[ind]\r\n            iter_i = filter(x -> all(x .<= r_sub), iter_all)\r\n            # find the cumulant \\kappa_{\\bm{r}}}\r\n            suma = 0.0\r\n            for i in iter_i\r\n                factor = 1.0\r\n                for j in 1:N\r\n                    factor *= binomial(r_sub[j], i[j])\r\n                end\r\n                suma += factor*M[r.-i]*M_star[i]\r\n            end\r\n            K[r] = simplify(suma)\r\n\r\n            # Find the central moment \\M^*_{\\bm{r}}\r\n            suma = 0.0\r\n            for i in iter_i\r\n                factor = 1.0\r\n                for j in 1:N\r\n                    factor *= binomial(r_sub[j], i[j])\r\n                end\r\n                suma += factor*(-K[r.-i])*M_star[i]\r\n            end\r\n            suma -= -μ[iter_1[ind]]*M_star[r_sub]\r\n            M_star[r] = simplify(suma)\r\n\r\n        end\r\n\r\n    end\r\n\r\n    K\r\n\r\nend\r\n\r\n\r\nfunction raw_to_central_moments(N::Int, order::Int, μ=nothing; bernoulli=false)\r\n\r\n    # Return a dictionary of central moments expressed in terms of raw moments\r\n    # example use:\r\n    # 1 raw_to_central = raw_to_central_moments(2, 3)\r\n    # 2 M₁₂ = raw_to_central[(1,2)] = 2 μ₁₀ μ₀₁² - 2μ₁₁μ₀₁ - μ₀₂μ₁₀ + μ₁₂\r\n    # note that μ is an optional argument which can be used to pass\r\n    # arbitrary values/symbols for each raw moment (different from default μᵢ)\r\n\r\n    iter_all = construct_iter_all(N, order)\r\n    iter_μ = filter(x -> sum(x) == 1, iter_all)\r\n    M = define_M(N, order, iter_all)\r\n    if μ == nothing\r\n        μ = define_μ(N, order, iter_all)\r\n    elseif !(μ isa Dict) || length(μ) != length(iter_all)\r\n        if bernoulli\r\n            iter_all = keys(μ)\r\n        else\r\n            error(\"passed arguments are inconsistent (μ vs N & order)\")\r\n        end\r\n    else\r\n        iter_all = construct_iter_all(N, order)\r\n    end\r\n    raw_to_central = Dict()\r\n\r\n    for i in iter_all\r\n\r\n        iter_j = Iterators.filter(x -> all(x .<= i), iter_all)\r\n        suma = 0.0\r\n        for j in iter_j\r\n            term = μ[i.-j]\r\n            for (k, e_k) in zip(1:N, iter_μ)\r\n                term *= (-1)^(j[k])*binomial(i[k], j[k])*μ[e_k]^j[k]\r\n            end\r\n            suma += term\r\n        end\r\n        raw_to_central[i] = simplify(suma)\r\n    end\r\n\r\n    raw_to_central\r\n\r\nend\r\n\r\nfunction central_to_raw_moments(N::Int, order::Int)\r\n\r\n    # Return a dictionary of raw moments expressed in terms of central moments\r\n    # example use:\r\n    # 1 central_to_raw = central_to_raw_moments(2, 3)\r\n    # 2 μ₁₂ = central_to_raw[(1,2)] = 2 M₁₁ μ₀₁ + M₀₂μ₁₀ + M₁₂ + μ₁₀ μ₀₁²\r\n\r\n    iter_all = construct_iter_all(N, order)\r\n    iter_μ = filter(x -> sum(x) == 1, iter_all)\r\n\r\n    M = define_M(N, order, iter_all)\r\n    μ = define_μ(N, order, iter_μ)\r\n\r\n    central_to_raw = Dict()\r\n\r\n    central_to_raw[iter_all[1]] = 1.0\r\n    for i in iter_all[2:end]\r\n\r\n        iter_j = Iterators.filter(x -> all(x .<= i), iter_all)\r\n        suma = 0.0\r\n        for j in iter_j\r\n            term = M[i.-j]\r\n            for (k, e_k) in zip(1:N, iter_μ)\r\n                term *= binomial(i[k], j[k])*μ[e_k]^j[k]\r\n            end\r\n            suma += term\r\n        end\r\n        central_to_raw[i] = simplify(suma)\r\n    end\r\n\r\n    central_to_raw\r\n\r\nend\r\n", "meta": {"hexsha": "f295a8a4ec9b06ba089efd3c11109b88ebfa5792", "size": 6446, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/moment_convert.jl", "max_stars_repo_name": "augustinas1/MomentClosure.jl", "max_stars_repo_head_hexsha": "62d59a73726a8540cf2340b0817dfa603f4242b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2021-02-21T00:44:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T23:48:52.000Z", "max_issues_repo_path": "src/moment_convert.jl", "max_issues_repo_name": "augustinas1/MomentClosure.jl", "max_issues_repo_head_hexsha": "62d59a73726a8540cf2340b0817dfa603f4242b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-02-26T15:44:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T12:48:27.000Z", "max_forks_repo_path": "src/moment_convert.jl", "max_forks_repo_name": "augustinas1/MomentClosure.jl", "max_forks_repo_head_hexsha": "62d59a73726a8540cf2340b0817dfa603f4242b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-02-21T01:20:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T13:18:07.000Z", "avg_line_length": 28.5221238938, "max_line_length": 115, "alphanum_fraction": 0.519081601, "num_tokens": 1938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7616087782178431}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction _mphase{T<:AbstractFloat}(jd::T)\n    ram, decm, dism = moonpos(jd, radians=true)\n    ras, decs = sunpos(jd, radians=true)\n    # phi: geocentric elongation of the Moon from the Sun\n    # inc: selenocentric (Moon centered) elongation of the Earth from the Sun\n    phi = acos(sin(decs)*sin(decm) + cos(decs)*cos(decm)*cos(ras - ram))\n    # \"dism\" is in kilometers, AU in meters\n    inc = atan2(AU*sin(phi), dism*1e3 - AU*cos(phi))\n    return (1.0 + cos(inc))/2.0\nend\n\n\"\"\"\n    mphase(jd) -> k\n\n### Purpose ###\n\nReturn the illuminated fraction of the Moon at given Julian date(s).\n\n### Arguments ###\n\n* `jd`: the Julian ephemeris date.  It can be either a scalar or an array.\n\n### Output ###\n\nThe illuminated fraction \\$k\\$ of Moon's disk, with \\$0 \\\\leq k \\\\leq 1\\$. \\$k\n= 0\\$ indicates a new moon, while \\$k = 1\\$ stands for a full moon.  If `jd` is\ngiven as an array, an array of the same number of elements as `jd` is returned.\n\n### Method ###\n\nAlgorithm from Chapter 46 of \"Astronomical Algorithms\" by Jean Meeus\n(Willmann-Bell, Richmond) 1991.  `sunpos` and `moonpos` are used to get\npositions of the Sun and the Moon, and the Moon distance.  The selenocentric\nelongation of the Earth from the Sun (phase angle) is then computed, and used to\ndetermine the illuminated fraction.\n\n### Example ###\n\nPlot the illuminated fraction of the Moon for every day in January 2018 with a\nhourly sampling.  Use [PyPlot.jl](https://github.com/stevengj/PyPlot.jl) for\nplotting\n\n``` julia\nusing PyPlot\npoints = DateTime(2018,01,01):Dates.Hour(1):DateTime(2018,01,31,23,59,59);\nplot(points, mphase(jdcnv(points)))\n```\n\nNote that in this calendar month there are two full moons, this event is called\n[blue moon](https://en.wikipedia.org/wiki/Blue_moon).\n\n### Notes ###\n\nCode of this function is based on IDL Astronomy User's Library.\n\"\"\"\nmphase(jd::Real) = _mphase(float(jd))\n\nfunction mphase{J<:Real}(jd::AbstractArray{J})\n    k = similar(jd, float(J))\n    for i in eachindex(jd)\n        k[i] = mphase(jd[i])\n    end\n    return k\nend\n", "meta": {"hexsha": "67223ac8f8a113d81ff6e7d7a2290c1733cacede", "size": 2125, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mphase.jl", "max_stars_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_stars_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mphase.jl", "max_issues_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_issues_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mphase.jl", "max_forks_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_forks_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.25, "max_line_length": 80, "alphanum_fraction": 0.6865882353, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7615968713542192}}
{"text": "# indicator of the L1 norm ball with given radius\n\nexport IndBallL1\n\n\"\"\"\n**Indicator of a ``L_1`` norm ball**\n\n    IndBallL1(r=1.0)\n\nReturns the indicator function of the set\n```math\nS = \\\\left\\\\{ x : \\\\sum_i |x_i| \\\\leq r \\\\right\\\\}.\n```\nParameter `r` must be positive.\n\"\"\"\nstruct IndBallL1{R} <: ProximableFunction\n    r::R\n    function IndBallL1{R}(r::R) where R\n        if r <= 0\n            error(\"parameter r must be positive\")\n        else\n            new(r)\n        end\n    end\nend\n\nis_convex(f::IndBallL1) = true\nis_set(f::IndBallL1) = true\nis_prox_accurate(f::IndBallL1) = false\n\nIndBallL1(r::R=1.0) where R = IndBallL1{R}(r)\n\nfunction (f::IndBallL1)(x::AbstractArray{T}) where {R <: Real, T <: RealOrComplex{R}}\n    if norm(x, 1) - f.r > f.r*eps(R)\n        return R(Inf)\n    end\n    return R(0)\nend\n\nfunction prox!(y::AbstractArray{R}, f::IndBallL1, x::AbstractArray{R}, _::R=R(1)) where {R <: Real}\n    if norm(x, 1) <= f.r\n        y .= x\n        return R(0)\n    else # do a projection of abs(x) onto simplex then recover signs\n        abs_x = abs.(x)\n        simplex_proj_condat!(y, f.r, abs_x)\n        y .*= sign.(x)\n        return R(0)\n    end\nend\n\nfunction prox!(y::AbstractArray{T}, f::IndBallL1, x::AbstractArray{T}, _::R=R(1)) where {R <: Real, T <: Complex{R}}\n    if norm(x, 1) <= f.r\n        y .= x\n        return R(0)\n    else # do a projection of abs(x) onto simplex then recover signs\n        abs_x = real.(abs.(x))\n        y_temp = similar(abs_x)\n        simplex_proj_condat!(y_temp, f.r, abs_x)\n        y .= y_temp .* sign.(x)\n        return R(0)\n    end\nend\n\nfun_name(f::IndBallL1) = \"indicator of an L1 norm ball\"\nfun_dom(f::IndBallL1) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::IndBallL1) = \"x ↦ 0 if ‖x‖_1 ⩽ r, +∞ otherwise\"\nfun_params(f::IndBallL1) = \"r = $(f.r)\"\n\nfunction prox_naive(f::IndBallL1, x::AbstractArray{T}, _::R=R(1)) where {R <: Real, T <: RealOrComplex{R}}\n    # do a simple bisection (aka binary search) on λ\n    L = R(0)\n    U = maximum(abs, x)\n    λ = L\n    v = R(0)\n    maxit = 120\n    for _ in 1:maxit\n        λ = (L + U) / 2\n        v = sum(max.(abs.(x) .- λ, R(0)))\n        # modify lower or upper bound\n        (v < f.r) ? U = λ : L = λ\n        # exit condition\n        if abs(L - U) < (1 + abs(U))*eps(R)\n            break\n        end\n    end\n    return sign.(x) .* max.(R(0), abs.(x) .- λ), R(0)\nend\n", "meta": {"hexsha": "b1f88f85aa8eeb42d6390a0ad6b653da3b5cdda7", "size": 2374, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indBallL1.jl", "max_stars_repo_name": "fabian-sp/ProximalOperators.jl", "max_stars_repo_head_hexsha": "c9a250f8836e41450bada594ed23baa22dc8e928", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2016-10-29T12:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:11:52.000Z", "max_issues_repo_path": "src/functions/indBallL1.jl", "max_issues_repo_name": "kul-forbes/ProximalOperators.jl", "max_issues_repo_head_hexsha": "fcd3d987f6af7d701cd32c61e6c14594baa6289e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2016-10-26T16:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T20:38:48.000Z", "max_forks_repo_path": "src/functions/indBallL1.jl", "max_forks_repo_name": "fabian-sp/ProximalOperators.jl", "max_forks_repo_head_hexsha": "c9a250f8836e41450bada594ed23baa22dc8e928", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T10:40:24.000Z", "avg_line_length": 26.6741573034, "max_line_length": 116, "alphanum_fraction": 0.5602358888, "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7615968653004646}}
{"text": "vertices(array :: AbstractArray{Bool}) = sum(array)\n\nfunction ortvec(N, i)\n    vec = zeros(Int, N)\n    vec[i] = 1\n\n    return CartesianIndex(vec...)\nend\n\nfunction segments(array :: AbstractArray{Bool, N}) where N\n    δ = [ortvec(N, i) for i in 1:N]\n\n    indices    = CartesianIndices(array)\n    fidx, lidx = first(indices), last(indices)\n    uidx       = oneunit(fidx)\n\n    mapreduce(+, indices) do idx\n        slice = array[idx:min(idx + uidx, lidx)]\n\n        mapreduce(+, 1:N) do i\n            idx2 = uidx + δ[i]\n            (checkbounds(Bool, slice, idx2) && slice[uidx] && slice[idx2]) ? 1 : 0\n        end\n    end\nend\n\nfunction checkface(array :: AbstractArray{Bool, N},\n                   δ1    :: CartesianIndex{N},\n                   δ2    :: CartesianIndex{N}) where N\n    uidx = array |> CartesianIndices |> first |> oneunit\n\n    idx1 = uidx\n    idx2 = uidx + δ1\n    idx3 = uidx + δ2\n    idx4 = uidx + δ1 + δ2\n\n    return checkbounds(Bool, array, idx2) &&\n        checkbounds(Bool, array, idx3) &&\n        checkbounds(Bool, array, idx4) &&\n        array[idx1] && array[idx2] && array[idx3] && array[idx4]\nend\n\nfunction faces(array :: AbstractArray{Bool, 3})\n    indices    = CartesianIndices(array)\n    fidx, lidx = first(indices), last(indices)\n    uidx       = oneunit(fidx)\n\n    mapreduce(+, indices) do idx\n        slice = array[idx:min(idx + uidx, lidx)]\n\n        checkface(slice, CartesianIndex(1, 0, 0), CartesianIndex(0, 1, 0)) +\n            checkface(slice, CartesianIndex(1, 0, 0), CartesianIndex(0, 0, 1)) +\n            checkface(slice, CartesianIndex(0, 1, 0), CartesianIndex(0, 0, 1))\n    end\nend\n\nfunction volumes(array :: AbstractArray{Bool})\n    indices    = CartesianIndices(array)\n    fidx, lidx = first(indices), last(indices)\n    uidx       = oneunit(fidx)\n\n    mapreduce(+, fidx:(lidx - uidx)) do idx\n        slice = array[idx:(idx + uidx)]\n        all(isone, slice)\n    end\nend\n\n\"\"\"\n    euler_characteristic(array :: AbstractArray{Bool})\n\nCalculate Euler characteristic for a set of points `S` on a regular\ncubic or square grid. The points are defined by a binary array `array`\nin such a manner that if `array[idx] == true` then `idx ∈ S`.\n\"\"\"\nfunction euler_characteristic end\n\neuler_characteristic(array :: AbstractArray{Bool, 2}) =\n    vertices(array) - segments(array) + volumes(array)\n\neuler_characteristic(array :: AbstractArray{Bool, 3}) =\n    vertices(array) - segments(array) + faces(array) - volumes(array)\n", "meta": {"hexsha": "7ae5c5045a0e0d8800f988862acd7a0aa4797f87", "size": 2448, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/calc.jl", "max_stars_repo_name": "shamazmazum/EulerCharacteristic.jl", "max_stars_repo_head_hexsha": "d33c9f38fbd57565b4cbe236c01c91b3d7b1ccc9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-15T18:40:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T18:40:42.000Z", "max_issues_repo_path": "src/calc.jl", "max_issues_repo_name": "gazfaris/EulerCharacteristic.jl", "max_issues_repo_head_hexsha": "3fcbad66e726f248ca9ae3175809a5c761e28208", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/calc.jl", "max_forks_repo_name": "gazfaris/EulerCharacteristic.jl", "max_forks_repo_head_hexsha": "3fcbad66e726f248ca9ae3175809a5c761e28208", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-15T18:40:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T18:40:33.000Z", "avg_line_length": 29.8536585366, "max_line_length": 82, "alphanum_fraction": 0.6164215686, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7615968643181701}}
{"text": "function nthroot(n::Integer, r::Real)\n    r < 0 || n == 0 && throw(DomainError())\n    n < 0 && return 1 / nthroot(-n, r)\n    r > 0 || return 0\n    x = r / n\n    prevdx = r\n    while true\n        y = x ^ (n - 1)\n        dx = (r - y * x) / (n * y)\n        abs(dx) ≥ abs(prevdx) && return x\n        x += dx\n        prevdx = dx\n    end\nend\n\n@show nthroot.(-5:2:5, 5.0)\n@show nthroot.(-5:2:5, 5.0) - 5.0 .^ (1 ./ (-5:2:5))\n", "meta": {"hexsha": "a5acccf10f0bef1177ba7addc93ea331b5f38d91", "size": 418, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/nth-root.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/nth-root.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/nth-root.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2222222222, "max_line_length": 52, "alphanum_fraction": 0.4330143541, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939516, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7615968626454598}}
{"text": "export chebygrid, ischebygrid, chebycoef, cheby, chebyderiv\nexport ChebyshevInterpolator, BichebyshevInterpolator\n\nξ2x(ξ, a, b) = (ξ + 1)*((b - a)/2) + a\n\nx2ξ(x, a, b) = 2*(x - a)/(b - a) - 1\n\nx2θ(x, a, b) = acos(x2ξ(x, a, b))\n\n\"\"\"\n    chebygrid(n)\n\nCreate an array of `n` chebyshev nodes in [-1,1]\n\"\"\"\n@memoize chebygrid(n::Int) = cos.(π*(n-1:-1:0)/(n-1))\n\n\"\"\"\n    chebygrid(xa, xb, n)\n\nCreate an array of `n` chebyshev nodes in [`xa`,`xb`]\n\"\"\"\nchebygrid(xa, xb, n::Int) = ξ2x.(chebygrid(n), xa, xb)\n\n\"\"\"\n    chebygrid(xa, xb, nx, ya, yb, ny)\n\nCreate a two-dimensional grid of chebyshev nodes using `nx` points along the first axis, in [`xa`,`xb`], and `ny` points along the second axis, in [`ya`,`yb`].\n\"\"\"\nfunction chebygrid(xa, xb, nx::Int, ya, yb, ny::Int)\n    X = chebygrid(xa, xb, nx) .* ones(ny)'\n    Y = chebygrid(ya, yb, ny)' .* ones(nx)\n    return X, Y\nend\n\nfunction ischebygrid(x)::Bool\n    n = length(x)\n    c = chebygrid(n)\n    xa, xb = minimum(x), maximum(x)\n    @inbounds for i ∈ eachindex(x)\n        ξ = x2ξ(x[i], xa, xb)\n        #shift from [-1,1] to [1,3] to avoid issues comparing to zero\n        !isapprox(ξ+2, c[i]+2) && return false \n    end\n    return true\nend\n\n@memoize function chebymatrix(n::Int)\n    @assert n > 1 \"can't construct cheby matrix smaller than 2 x 2\"\n    A = zeros(n,n)\n    ξ = chebygrid(n)\n    for j ∈ 1:n, k ∈ 1:n\n        @inbounds A[j,k] = cos((k-1)*acos(ξ[j]))\n    end\n    return A\nend\n\nfunction chebyrecurrance!(T, ξ, L::Int)::Nothing\n    Tₖ₋₂ = one(ξ)\n    Tₖ₋₁ = ξ\n    @inbounds T[2] = Tₖ₋₁\n    for k = 3:L\n        #compute next value\n        Tₖ = 2ξ*Tₖ₋₁ - Tₖ₋₂\n        #set array value\n        @inbounds T[k] = Tₖ\n        #swaps\n        Tₖ₋₂ = Tₖ₋₁\n        Tₖ₋₁ = Tₖ\n    end\n    nothing\nend\n\nfunction chebyrecurrance(ξ::U, L::Int) where {U}\n    T = Vector{U}(undef, L)\n    @inbounds T[1] = one(ξ)\n    chebyrecurrance!(T, ξ, L)\n    return T\nend\n\n\"\"\"\n    chebycoef(y)\n\nCompute the Chebyshev expansion coefficients for a set of points `y`, which are assumed to be located on the Chebyshev points for some interval.\n\"\"\"\nfunction chebycoef(y)\n    n = length(y)\n    @assert n > 1 \"must have at least 2 points to form chebyshev coefficients\"\n    Aᴵ = invertedchebymatrix(n)\n    return Aᴵ*y\nend\n\n\"\"\"\n    cheby(coef, x, xa, xb)\n\nEvaluates the Chebyshev expansion represented by the coefficients in `coef` and defined on the interval [`xa`,`xb`] at the point `x`.\n\"\"\"\nfunction cheby(coef, x, xa, xb)\n    N = length(coef)\n    @assert xa <= x <= xb \"x must be inside [xa,xb]\"\n    #get coordinate in ξ space\n    ξ = x2ξ(x, xa, xb)\n    #first two elements of cheby recursion\n    Tₖ₋₂ = one(ξ)\n    Tₖ₋₁ = ξ\n    #first two terms of dot product\n    @inbounds y = Tₖ₋₂*coef[1] + Tₖ₋₁*coef[2]\n    #cheby recursion and rest of terms in dot product, all at once\n    for k = 3:N\n        #next value in recursion\n        Tₖ = 2*ξ*Tₖ₋₁ - Tₖ₋₂\n        #next term in dot product\n        @inbounds y += Tₖ*coef[k]\n        #swaps\n        Tₖ₋₂ = Tₖ₋₁\n        Tₖ₋₁ = Tₖ\n    end\n    return y\nend\n\n\"\"\"\n    chebyderiv(coef, xa, xb)\n\nGenerates the expansion coefficents for the derivative of a preexisting Chebyshev expansion defined on the interval [`xa`,`xb`].\n\"\"\"\nfunction chebyderiv(coef, xa, xb)\n    n = length(coef)\n    T = eltype(coef)\n    @assert xa < xb \"xa must be less than xb\"\n    #length 1 case is a trivial zero slope\n    n == 1 && return zeros(T, 1)\n    #start the array and check for length 2 case\n    d = zeros(T, n-1)\n    d[n-1] = 2*(n-2)*coef[n]\n    n == 2 && return d\n    #recurrance for all the rest\n    d[n-2] = 2*(n-3)*coef[n-1]\n    @inbounds for k ∈ n-2:-1:2\n        d[k-1] = d[k+1] + 2*(k-1)*coef[k]\n    end\n    #interval width factor\n    d .*= 2/(xb - xa)\n    #extra DC scaling\n    d[1] /= 2\n    return d\nend\n\n#-------------------------------------------------------------------------------\n# caching function for inverted cheby matrices, needed for interpolator setup\n\n@memoize invertedchebymatrix(n::Int64)::Matrix{Float64} = inv(chebymatrix(n))\n\n#-------------------------------------------------------------------------------\n# one-dimensional interpolation\n\nstruct ChebyshevInterpolator{N,T}\n    #lowest value in range\n    xa::T\n    #highest value in range\n    xb::T\n    #interpolation coefficents\n    a::NTuple{N,T}\n    #must always have strict boundaries\n    boundaries::StrictBoundaries\nend\n\nfunction Base.show(io::IO, ϕ::ChebyshevInterpolator)\n    print(io, \"$(typeof(ϕ)) ∈ [$(ϕ.xa), $(ϕ.xb)]\")\nend\n\n\"\"\"\n    ChebyshevInterpolator(x, y)\n\nConstruct a `ChebyshevInterpolator` for the points defined by coordinates `x` and values `y`. The `x` coordinates *must* be arranged on a chebyshev grid, which can be generated using the [`chebygrid`](@ref) function.\n\"\"\"\nfunction ChebyshevInterpolator(x, y)\n    #same types\n    T = promote_type(eltype(x), eltype(y))\n    x = collect(T, x)\n    y = collect(T, y)\n    #check for basic issues\n    rangecheck(x, y, 3)\n    #demand that the input points have chebyshev spacing\n    @assert ischebygrid(x) \"points must be on a chebyshev grid\"\n    #generate expansion coefficients\n    a = Tuple(chebycoef(y))\n    #construct\n    ChebyshevInterpolator(minimum(x), maximum(x), a, StrictBoundaries())\nend\n\n\"\"\"\n    ChebyshevInterpolator(f, xa, xb, n)\n\nConstruct a `ChebyshevInterpolator` for the function `f` using `n` function evaluations in the range [`xa`,`xb`]. The function evaluations will occur on the chebyshev nodes.\n\"\"\"\nfunction ChebyshevInterpolator(f::F, xa, xb, n::Int) where {F}\n    #set up the range coordinates\n    x = chebygrid(xa, xb, n)\n    #evaluate the function at those coordinates\n    y = f.(x)\n    #call the other constructor\n    ChebyshevInterpolator(x, y)\nend\n\nfunction (ϕ::ChebyshevInterpolator{N,U})(x) where {N,U}\n    #always enforce boundaries\n    ϕ.boundaries(x, ϕ.xa, ϕ.xb)\n    #evaluate the expansion\n    return cheby(ϕ.a, x, ϕ.xa, ϕ.xb)\nend\n\n\"\"\"\n    chebyderiv(ϕ::ChebyshevInterpolator)\n\nConstruct a ChebyshevInterpolator representing the derivative of a preexisting interpolator.\n\"\"\"\nfunction chebyderiv(ϕ::ChebyshevInterpolator)\n    #derivative expansion's coefficients\n    coef = Tuple(chebyderiv(ϕ.a, ϕ.xa, ϕ.xb))\n    #new interpolator\n    ChebyshevInterpolator(ϕ.xa, ϕ.xb, coef, StrictBoundaries())\nend\n\n#-------------------------------------------------------------------------------\n# bichebyshev interpolation, a little trickier now!\n\nstruct BichebyshevInterpolator{M,N,U}\n    #lowest value on axis 1\n    xa::U\n    #highest value on axis 1\n    xb::U\n    #lowest value on axis 2\n    ya::U\n    #highest value on axis 2\n    yb::U\n    #matrix and vectors for doing the interpolation\n    A::Matrix{U} # size (ny by nx) or (M by N)\n    a::Vector{U} # length ny for cosine expansion in θy\n    b::Vector{U} # length nx for cosine expansion in θx\n    c::Vector{U} # length ny for doing M*b in place\n    #must always use strict boundaries\n    boundaries::StrictBoundaries\nend\n\nfunction Base.show(io::IO, ϕ::BichebyshevInterpolator)\n    print(io, \"$(typeof(ϕ)) ∈ [$(ϕ.xa), $(ϕ.xb)], [$(ϕ.ya), $(ϕ.yb)]\")\nend\n\n\"\"\"\n    BichebyshevInterpolator(x, y, Z)\n\nConstruct a `BichebyshevInterpolator` for the grid of points defined by coordinates (`x`,`y`) and values `Z`. The given points must lie on a chebyshev grid in each direction. These can be generated with the [`chebygrid`](@ref) function or the interpolator can be constructed directly from a function using the method below.\n\n!!! warning\n\n    The Bichebyshev interpolator is *not thread-safe*. It computes a cosine expansion and does some linear algebra in-place using arrays stored with the object. A single `BichebyshevInterpolator` should never be called by multiple threads at once.\n\"\"\"\nfunction BichebyshevInterpolator(x, y, Z)\n    #same types\n    T = promote_type(eltype(x), eltype(y), eltype(Z))\n    x = collect(T, x)\n    y = collect(T, y)\n    Z = collect(T, Z)\n    #check for basic grid problems\n    gridcheck(x, y, Z, 3)\n    #grid properties\n    nx, ny = length(x), length(y)\n    xa, xb = T(minimum(x)), T(maximum(x))\n    ya, yb = T(minimum(y)), T(maximum(y))\n    #reject any non-cheby grid spacing\n    @assert ischebygrid(x) \"axis 1 coordinates must be on a chebyshev grid\"\n    @assert ischebygrid(y) \"axis 2 coordinates must be on a chebyshev grid\"\n    #get inverted matrices from cache or generate them\n    B = invertedchebymatrix(nx)\n    #generate interpolation coefficients along axis 1 for each value of axis 2\n    α = zeros(T, nx, ny)\n    for j = 1:ny\n        mul!(view(α,:,j), B, view(Z,:,j))\n    end\n    #then combine α and A\n    A = invertedchebymatrix(ny)*α'\n    #other vectors we need for doing the actual interpolation\n    a = ones(T, ny)\n    b = ones(T, nx)\n    c = zeros(T, ny)\n    #done\n    BichebyshevInterpolator{ny,nx,T}(xa, xb, ya, yb, A, a, b, c, StrictBoundaries())\nend\n\n\"\"\"\n    BichebyshevInterpolator(f, xa, xb, nx, ya, yb, ny)\n\nConstruct a `BichebyshevInterpolator` for the function `f` using a grid of `nx` points on the first axis in [`xa`,`xb`] and `ny` points on the second axis in [`ya`,`yb`].\n\"\"\"\nfunction BichebyshevInterpolator(f::F, xa, xb, nx::Int, ya, yb, ny::Int) where {F}\n    #set up the grid\n    X, Y = chebygrid(xa, xb, nx, ya, yb, ny)\n    #evaluate the function at chebyshev grid points\n    Z = f.(X, Y)\n    #call the other constructor\n    BichebyshevInterpolator(X[:,1], Y[1,:], Z)\nend\n\n#=====\nThis is the fast implementation. It's executed when the types of the\ninput coordinates match the type of the stored coefficients in the\ninterpolator. When the types match, the Chebyshev expansions can be\nevaluated in-place, using vectors pre-allocated in the interpolator.\nSee the a, b, and c fields of the struct. This method also guarantees\nthat the interpolator type and the coordinate types are <: AbstractFloat,\nmaking the low-level linear algebra functions safe. Without such a\nguarantee, there can be issues with, for example, the dual numbers in\nFowardDiff routines.\n=====#\nfunction (Φ::BichebyshevInterpolator{M,N,U})(x::U, y::U) where {M,N,U<:AbstractFloat}\n    #always enforce boundaries for Chebyshev\n    Φ.boundaries(x, Φ.xa, Φ.xb, y, Φ.ya, Φ.yb)\n    #evaluate Chebyshev polys at the coordinates recursively and in-place\n    ξy = x2ξ(y, Φ.ya, Φ.yb)\n    chebyrecurrance!(Φ.a, ξy, M)\n    ξx = x2ξ(x, Φ.xa, Φ.xb)\n    chebyrecurrance!(Φ.b, ξx, N)\n    #perform M*b, which interpolates along the first axis, also in-place\n    mul!(Φ.c, Φ.A, Φ.b)\n    #then a'*c interpolates along the second axis\n    return dot(Φ.a, Φ.c)\nend\n\n#=====\nThis is the slow, but type-flexible, implementation. It's\nexecuted whenever the type of the interpolator's coefficients or\nthe coordinate types don't match OR are not AbstractFloats. The\nprice of this flexibility is allocations for the expansions and\nloss of the low-level linear algebra routines 😭.\n=====#\nfunction (Φ::BichebyshevInterpolator{M,N,U})(x, y) where {M,N,U}\n    #always enforce boundaries for Chebyshev\n    Φ.boundaries(x, Φ.xa, Φ.xb, y, Φ.ya, Φ.yb)\n    #coordinates in ξ space\n    ξx, ξy = promote(x2ξ(x, Φ.xa, Φ.xb), x2ξ(y, Φ.ya, Φ.yb))\n    #allocating expansion in the x direction\n    b = chebyrecurrance(ξx, N)\n    c = Φ.A * b\n    #then perform the y-axis expansion and dot product simulataneously    \n    Tₖ₋₂ = one(ξy)\n    Tₖ₋₁ = ξy\n    @inbounds z = c[1] + ξy*c[2]\n    for i = 3:M\n        #compute next value\n        Tₖ = 2ξy*Tₖ₋₁ - Tₖ₋₂\n        #update running dot product\n        @inbounds z += c[i]*Tₖ\n        #swaps\n        Tₖ₋₂ = Tₖ₋₁\n        Tₖ₋₁ = Tₖ\n    end\n    return z\nend", "meta": {"hexsha": "1bda60ee5057158bcb535afd7e99621e48a5f783", "size": 11442, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chebyshev.jl", "max_stars_repo_name": "markmbaum/BasicInterpolators.jl", "max_stars_repo_head_hexsha": "6986d0418913b39207ccc7825a7f00822e434ef4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-13T22:38:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T22:38:31.000Z", "max_issues_repo_path": "src/chebyshev.jl", "max_issues_repo_name": "markmbaum/BasicInterpolators.jl", "max_issues_repo_head_hexsha": "6986d0418913b39207ccc7825a7f00822e434ef4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-16T15:16:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T15:05:48.000Z", "max_forks_repo_path": "src/chebyshev.jl", "max_forks_repo_name": "markmbaum/BasicInterpolators.jl", "max_forks_repo_head_hexsha": "6986d0418913b39207ccc7825a7f00822e434ef4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0504201681, "max_line_length": 323, "alphanum_fraction": 0.6362524034, "num_tokens": 3790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142225532629, "lm_q2_score": 0.8006919973399709, "lm_q1q2_score": 0.7615719683161057}}
{"text": "dt = 0.005\nfunction lorenz63(u0, s, n)\n    sigma, rho, beta = s\n    d, m = size(u0)\n    n = n+1\n    u_trj = zeros((m,d,n))\n    u_trj[:,:,1] = u0'\n    for i = 2:n\n    \tx = u_trj[:,1,i-1]\n    \ty = u_trj[:,2,i-1]\n    \tz = u_trj[:,3,i-1]\n    \n    \tu_trj[:,1,i] = x + dt*(sigma.*(y - x))\n    \tu_trj[:,2,i] = y + dt*(x.*(rho .- z) - y)\n    \tu_trj[:,3,i] = z + dt*(x.*y - beta.*z)\n    end \n    return permutedims(u_trj,[3,2,1])\nend\nfunction dlorenz63(u, s)\n    sigma, rho, beta = s\n    n, d = size(u)\n    x = view(u,:,1)\n    y = view(u,:,2)\n    z = view(u,:,3)\n    du = zeros(n, d, d)\n    @. du[:,1,1] = 1.0 - dt*sigma\n    @. du[:,1,2] = dt*sigma\n    @. du[:,2,1] = dt*(rho - z) \n    @. du[:,2,2] = 1.0 - dt\n    @. du[:,2,3] = -dt*x \n    @. du[:,3,1] = dt*y\n    @. du[:,3,2] = dt*x\n    @. du[:,3,3] = 1.0 - dt*beta\n    return reshape([du[:,:,1]'; du[:,:,2]'; \n    \t\t\t\tdu[:,:,3]'], d, d, n)\nend\nfunction perturbation(u,s)\n    n, d = size(u)\n    # the perturbation in row i in T_{u_(i+1)} M\n    return [zeros(1,n); dt*u[:,1]'; zeros(1,n)]\nend\nfunction vectorField(u,s)\n    n, d = size(u)\n    sigma, rho, beta = s\n    u = u'\n    x, y, z = u[1,:], u[2,:], u[3,:]\n    return [sigma.*(y - x)  x.*(rho .- z) - y  x.*y - beta.*z]'\nend\nfunction lorenz63_rhs_ad(du, u, s, t)\n    du[1] = s[1]*(u[2] - u[1])\n\tdu[2] = u[1]*(s[2] - u[3]) - u[2]\n\tdu[3] = u[1]*u[2] - s[3]*u[3]\nend\nfunction lorenz63_ad(u0, s, n)\n\tt = n*dt\n    prob = ODEProblem(lorenz63_rhs_ad, u0, (0.,t), s)\n\tsol = Array(solve(prob, Tsit5(), saveat=dt))\n\treturn sol[:,end]\nend\nfunction obj_fun(u0, s)\n    prob = ODEProblem(lorenz63_rhs_ad, u0, (0.,1.1), s)\n\t#_prob = remake(prob,u0=u0,p=s) \n\tsol = solve(prob, Tsit5(), saveat=0.005)\n\tsum(sol[3,:])/size(sol,2)\nend\n", "meta": {"hexsha": "7a98eb7c7c5ba544ed5a17208554a090c2d67f86", "size": 1710, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/lorenz63.jl", "max_stars_repo_name": "nishaChandramoorthy/energies", "max_stars_repo_head_hexsha": "17ffd87a976b9a6d23089fc182e16102bf4607c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-24T22:32:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-24T22:32:31.000Z", "max_issues_repo_path": "examples/lorenz63.jl", "max_issues_repo_name": "nishaChandramoorthy/energies", "max_issues_repo_head_hexsha": "17ffd87a976b9a6d23089fc182e16102bf4607c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/lorenz63.jl", "max_forks_repo_name": "nishaChandramoorthy/energies", "max_forks_repo_head_hexsha": "17ffd87a976b9a6d23089fc182e16102bf4607c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9090909091, "max_line_length": 63, "alphanum_fraction": 0.4748538012, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7615580215096004}}
{"text": "# Parts of this code were taken / derived from Graphs.jl. See LICENSE for\n# licensing details.\n\"\"\"\n    struct FloydWarshallState{T, U}\n\nAn [`AbstractPathState`](@ref) designed for Floyd-Warshall shortest-paths calculations.\n\"\"\"\nstruct FloydWarshallState{T,U<:Integer} <: AbstractPathState\n    dists::Matrix{T}\n    parents::Matrix{U}\nend\n\n@doc \"\"\"\n    floyd_warshall_shortest_paths(g, distmx=weights(g))\n\nUse the [Floyd-Warshall algorithm](http://en.wikipedia.org/wiki/Floyd–Warshall_algorithm)\nto compute the shortest paths between all pairs of vertices in graph `g` using an\noptional distance matrix `distmx`. Return a [`LightGraphs.FloydWarshallState`](@ref) with relevant\ntraversal information.\n\n### Performance\nSpace complexity is on the order of ``\\\\mathcal{O}(|V|^2)``.\n\"\"\"\nfunction floyd_warshall_shortest_paths(\n    g::AbstractGraph{U},\n    distmx::AbstractMatrix{T}=weights(g)\n) where T<:Real where U<:Integer\n    nvg = nv(g)\n    # if we do checkbounds here, we can use @inbounds later\n    checkbounds(distmx, Base.OneTo(nvg), Base.OneTo(nvg))\n\n    dists = fill(typemax(T), (Int(nvg), Int(nvg)))\n    parents = zeros(U, (Int(nvg), Int(nvg)))\n\n    @inbounds for v in vertices(g)\n        dists[v, v] = zero(T)\n    end\n    undirected = !is_directed(g)\n    @inbounds for e in edges(g)\n        u = src(e)\n        v = dst(e)\n\n        d = distmx[u, v]\n\n        dists[u, v] = min(d, dists[u, v])\n        parents[u, v] = u\n        if undirected\n            dists[v, u] = min(d, dists[v, u])\n            parents[v, u] = v\n        end\n    end\n\n    @inbounds for pivot in vertices(g)\n        # Relax dists[u, v] = min(dists[u, v], dists[u, pivot]+dists[pivot, v]) for all u, v\n        for v in vertices(g)\n            d = dists[pivot, v]\n            d == typemax(T) && continue\n            p = parents[pivot, v]\n            for u in vertices(g)\n                ans = (dists[u, pivot] == typemax(T) ? typemax(T) : dists[u, pivot] + d) \n                if dists[u, v] > ans\n                    dists[u, v] = ans\n                    parents[u, v] = p\n                end\n            end\n        end\n    end\n    fws = FloydWarshallState(dists, parents)\n    return fws\nend\n\nfunction enumerate_paths(s::FloydWarshallState{T,U}, v::Integer) where T where U<:Integer\n    pathinfo = s.parents[v, :]\n    paths = Vector{Vector{U}}()\n    for i in 1:length(pathinfo)\n        if (i == v) || (s.dists[v, i] == typemax(T))\n            push!(paths, Vector{U}())\n        else\n            path = Vector{U}()\n            currpathindex = i\n            while currpathindex != 0\n                push!(path, currpathindex)\n                if pathinfo[currpathindex] == currpathindex\n                    currpathindex = 0\n                else\n                    currpathindex = pathinfo[currpathindex]\n                end\n            end\n            push!(paths, reverse(path))\n        end\n    end\n    return paths\nend\n\nenumerate_paths(s::FloydWarshallState) = [enumerate_paths(s, v) for v in 1:size(s.parents, 1)]\nenumerate_paths(st::FloydWarshallState, s::Integer, d::Integer) = enumerate_paths(st, s)[d]\n", "meta": {"hexsha": "f49f7b0183125e45dcb8010e81ac900ccdf92c62", "size": 3079, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/shortestpaths/floyd-warshall.jl", "max_stars_repo_name": "SyxP/LightGraphs.jl", "max_stars_repo_head_hexsha": "6c488a872b991d99cc794f59d0ae617d5bf204a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-24T03:15:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-24T03:15:48.000Z", "max_issues_repo_path": "src/shortestpaths/floyd-warshall.jl", "max_issues_repo_name": "SyxP/LightGraphs.jl", "max_issues_repo_head_hexsha": "6c488a872b991d99cc794f59d0ae617d5bf204a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/shortestpaths/floyd-warshall.jl", "max_forks_repo_name": "SyxP/LightGraphs.jl", "max_forks_repo_head_hexsha": "6c488a872b991d99cc794f59d0ae617d5bf204a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-02-24T03:16:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-24T18:41:12.000Z", "avg_line_length": 31.7422680412, "max_line_length": 98, "alphanum_fraction": 0.5820071452, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7615580186578284}}
{"text": "using Plots\npyplot()\nusing QuantEcon \n\nP =[0.971 0.029 0.000\n    0.145 0.778 0.077\n    0.000 0.508 0.492]\n\npsi = [0.0 0.2 0.8]\n\nt = 20\nx_vals = Array(Float64, t+1)\ny_vals = Array(Float64, t+1)\nz_vals = Array(Float64, t+1)\ncolors = []\n\nfor i=1:t\n    x_vals[i] = psi[1]\n    y_vals[i] = psi[2]\n    z_vals[i] = psi[3]\n    psi = psi*P\n    push!(colors, :red)\nend\npush!(colors, :black)\n\nmc = MarkovChain(P)\npsi_star = stationary_distributions(mc)[1]\nx_vals[t+1] = psi_star[1]\ny_vals[t+1] = psi_star[2]\nz_vals[t+1] = psi_star[3]\nscatter(x_vals, y_vals, z_vals, color=colors)\nplot!(lims=(0, 1), ticks=[0.25 0.5 0.75]', legend=:none)\n\n", "meta": {"hexsha": "1697cc720dea8a0445621754af59834d05686d86", "size": 626, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "finite_markov/mc_convergence_plot.jl", "max_stars_repo_name": "mwhchen/quantecon", "max_stars_repo_head_hexsha": "1a401e3453cbccbcf609945fced1b478b945446e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-05-02T22:12:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T01:07:33.000Z", "max_issues_repo_path": "finite_markov/mc_convergence_plot.jl", "max_issues_repo_name": "mwhchen/quantecon", "max_issues_repo_head_hexsha": "1a401e3453cbccbcf609945fced1b478b945446e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "finite_markov/mc_convergence_plot.jl", "max_forks_repo_name": "mwhchen/quantecon", "max_forks_repo_head_hexsha": "1a401e3453cbccbcf609945fced1b478b945446e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-11-11T22:38:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T20:33:03.000Z", "avg_line_length": 18.4117647059, "max_line_length": 56, "alphanum_fraction": 0.624600639, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7615399774387901}}
{"text": "# TODO: combine into one function to avoid code repetition\n# pass integration 'method' parameter, enum?\n\nfunction left_riemann(f::Function, a::Real, b::Real, n::Int)\n\n    delta = (b - a) / n # Calculate delta between samples\n    X = a .+(0:n-1) * delta # Get range of samples\n    fX = map(f, X) # Calculate f(x) for each sample in range\n    return sum(fX) * delta # Sum and divide by sample width\n\nend\n\nfunction right_riemann(f::Function, a::Real, b::Real, n::Int)\n\n    delta = (b - a) / n\n    X = a .+(1:n) * delta\n    fX = map(f, X)\n    return sum(fX) * delta\n\nend\n\nfunction trapezoid(f::Function, a::Real, b::Real, n::Int)\n\n    delta = (b - a) / n\n    X = a .+(0:n) * delta\n    fX = map(f, X)\n\n    # must calculate mean height of left and right\n    return sum(fX[2:end] + diff(fX) * 0.5) * delta\n\nend\n", "meta": {"hexsha": "6eaa81bc60a94d0c5e8d29231e28bc7ebdfd8983", "size": 804, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Integration.jl", "max_stars_repo_name": "ChrisJanusiewicz/TestPackage.jl", "max_stars_repo_head_hexsha": "5d435b421707264f97a83de8725cfab554d09640", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Integration.jl", "max_issues_repo_name": "ChrisJanusiewicz/TestPackage.jl", "max_issues_repo_head_hexsha": "5d435b421707264f97a83de8725cfab554d09640", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Integration.jl", "max_forks_repo_name": "ChrisJanusiewicz/TestPackage.jl", "max_forks_repo_head_hexsha": "5d435b421707264f97a83de8725cfab554d09640", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.125, "max_line_length": 61, "alphanum_fraction": 0.6069651741, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7615399707021452}}
{"text": "#= \n\n# 2D Lid-driven cavity (AD-Newton)\n([source code](SOURCE_URL))\n\nThis example solves the lid-driven cavity problem where one seeks\na velocity ``\\mathbf{u}`` and pressure ``\\mathbf{p}`` of the incompressible Navier--Stokes problem\n```math\n\\begin{aligned}\n- \\mu \\Delta \\mathbf{u} + (\\mathbf{u} \\cdot \\nabla) \\mathbf{u} + \\nabla p & = 0\\\\\n\\mathrm{div}(u) & = 0\n\\end{aligned}\n```\nwhere ``\\mathbf{u} = (1,0)`` along the top boundary of a square domain.\n\nThis examples highlights the use of automatic differentation to obtain Newton derivatives of nonlinear PDEOperators. The user can \nswitch between a Newton obtained by automatic differentation (ADnewton = true) and a 'manual' Newton scheme (ADnewton = false). The runtime\nof the manual newton is slightly faster, but requires much more code input from the user that is more prone to errors.\n\n=#\n\n\nusing PDELib\nusing Printf\n\nfunction fe_liddrivencavity_autonewton(; verbosity = 0, Plotter = nothing, ADnewton = true, nref=2)\n\n    function boundary_data_top!(result)\n        result[1] = 1;\n        result[2] = 0;\n    end\n    \n    \n    ## grid\n    xgrid = uniform_refine(grid_unitsquare(Triangle2D), nref);\n    \n    ## problem parameters\n    viscosity = 1e-2\n    maxIterations = 50  # termination criterion 1 for nonlinear mode\n    maxResidual = 1e-12 # termination criterion 2 for nonlinear mode\n    broken_p = false\n    \n    ## choose one of these (inf-sup stable) finite element type pairs\n    #FETypes = [H1P2{2,2}, H1P1{1}] # Taylor--Hood\n    #FETypes = [H1P2B{2,2}, H1P1{1}]; broken_p = true # P2-bubble\n    #FETypes = [H1CR{2}, H1P0{1}] # Crouzeix--Raviart\n    #FETypes = [H1MINI{2,2}, H1P1{1}] # MINI element on triangles only\n    FETypes = [H1BR{2}, H1P0{1}]; broken_p = true # Bernardi--Raugel\n    \n    #####################################################################################    \n    #####################################################################################\n    \n    ## negotiate data functions to the package\n    user_function_bnd = DataFunction(boundary_data_top!, [2,2]; name = \"u_bnd\", dependencies = \"\", quadorder = 0)\n    \n    ## load linear Stokes problem prototype and assign data\n    ## we are adding the nonlinar convection term ourself below\n    ## to discuss the details\n    StokesProblem = IncompressibleNavierStokesProblem(2; viscosity = viscosity, nonlinear = false)\n    add_boundarydata!(StokesProblem, 1, [1,2,4], HomogeneousDirichletBoundary)\n    add_boundarydata!(StokesProblem, 1, [3], BestapproxDirichletBoundary; data = user_function_bnd)\n    \n    ## store matrix of Laplace operator for nonlinear solver\n    StokesProblem.LHSOperators[1,1][1].store_operator = true   \n    \n    ## add Newton for convection term\n    if ADnewton\n        ## AUTOMATIC DIFFERENTATION\n        ## requries kernel function for NonlinearForm action (u * grad) u\n        function ugradu_kernel_AD(result, input)\n            ## input = [u, grad(u)]\n            ## compute (u * grad) u = grad(u)*u\n            for j = 1 : 2\n                result[j] = 0.0\n                for k = 1 : 2\n                    result[j] += input[k]*input[2 + (j-1)*2+k]\n                end\n            end\n            return nothing\n        end \n        action_kernel = ActionKernel(ugradu_kernel_AD, [2,6]; dependencies = \"\", quadorder = 1)\n        \n        ## generate and add nonlinear PDEOperator (modifications to RHS are taken care of automatically)\n        NLConvectionOperator = GenerateNonlinearForm(\"(u * grad) u  * v\", [Identity, Gradient], [1,1], Identity, action_kernel; ADnewton = true)            \n        add_operator!(StokesProblem, [1,1], NLConvectionOperator)\n    else\n        ## MANUAL DIFFERENTATION\n        ## uses the following kernel function for the linearised convection operator\n        function ugradu_kernel_nonAD(result, input_current, input_ansatz)\n            ## input_current = [current, grad(current)]\n            ## input_ansatz = [ansatz, grad(ansatz)]\n            ## compute (current * grad) ansatz + (current * grad) ansatz\n            for j = 1 : 2\n                result[j] = 0.0\n                for k = 1 : 2\n                    result[j] += input_current[k]*input_ansatz[2 + (j-1)*2+k]\n                    result[j] += input_ansatz[k]*input_current[2 + (j-1)*2+k]\n                end\n            end\n            return nothing\n        end\n        ## and a similar kernel function for the right-hand side\n        function ugradu_kernel_rhs(result, input_current)\n            ## input_current = [current, grad(current)]\n            ## input_ansatz = [ansatz, grad(ansatz)]\n            ## compute (current * grad) current\n            for j = 1 : 2\n                result[j] = 0.0\n                for k = 1 : 2\n                    result[j] += input_current[k]*input_current[2 + (j-1)*2+k]\n                end\n            end\n            return nothing\n        end\n        newton_action_kernel = NLActionKernel(ugradu_kernel_nonAD, [2,6]; dependencies = \"\", quadorder = 1)\n        action_kernel_rhs = ActionKernel(ugradu_kernel_rhs, [2,6]; dependencies = \"\", quadorder = 1)\n        \n        ## generate and add nonlinear PDEOperator (modifications to RHS are taken care of by optional arguments)\n        NLConvectionOperator = GenerateNonlinearForm(\"(u * grad) u  * v\", [Identity, Gradient], [1,1], Identity, newton_action_kernel; ADnewton = false, action_kernel_rhs = action_kernel_rhs)            \n        add_operator!(StokesProblem, [1,1], NLConvectionOperator)         \n    end\n    \n    ## generate FESpaces\n    FESpaceVelocity = FESpace{FETypes[1]}(xgrid)\n    FESpacePressure = FESpace{FETypes[2]}(xgrid; broken = broken_p)\n    Solution = FEVector{Float64}(\"Stokes velocity\",FESpaceVelocity)\n    append!(Solution,\"Stokes pressure\",FESpacePressure)\n    \n    ## show configuration and solve Stokes problem\n    Base.show(StokesProblem)\n    GradientRobustMultiPhysics.solve!(Solution, StokesProblem; verbosity = verbosity, maxIterations = maxIterations, maxResidual = maxResidual)\n    \n    ## plot\n    GradientRobustMultiPhysics.plot(Solution, [1,2], [Identity, Identity]; Plotter = Plotter, verbosity = verbosity, use_subplots = true)\n    true \nend\n", "meta": {"hexsha": "a862c1ce48cdb1b58420638e2d3ccbfab574488d", "size": 6148, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/fe_liddrivencavity_autonewton.jl", "max_stars_repo_name": "WIAS-BERLIN/PDELib.jl", "max_stars_repo_head_hexsha": "45599ef4d3be94e03b64e3b02189f3c225c1ddfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-01-13T17:28:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T14:31:48.000Z", "max_issues_repo_path": "examples/fe_liddrivencavity_autonewton.jl", "max_issues_repo_name": "WIAS-BERLIN/PDELib.jl", "max_issues_repo_head_hexsha": "45599ef4d3be94e03b64e3b02189f3c225c1ddfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-15T14:06:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-21T09:05:29.000Z", "max_forks_repo_path": "examples/fe_liddrivencavity_autonewton.jl", "max_forks_repo_name": "WIAS-BERLIN/PDELib.jl", "max_forks_repo_head_hexsha": "45599ef4d3be94e03b64e3b02189f3c225c1ddfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-01T14:31:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T14:31:52.000Z", "avg_line_length": 44.8759124088, "max_line_length": 203, "alphanum_fraction": 0.6177618738, "num_tokens": 1646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462514578343, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7615399691698674}}
{"text": "#=\nCreated on 09/01/2021 12:54:49\nLast update: -\n\n@author: Michiel Stock\nmichielfmstock@gmail.com\n\nEstimate pi through Monte Carlo sampling. \nDo this by simuting to throw `n` pebbles in the [-1, 1] x [-1, 1] square\nand track the fraction that land in the unit circle.\n=#\n\nfunction estimatepi(n)\n    hits = 0\n    for i in 1:n\n        x = rand()\n        y = rand()\n        if x^2 + y^2 ≤ 1.0\n            hits += 1\n        end\n    end\n    return 4hits/n\nend\n\nestimatepi2(n) = 4count(x-> x ≤ 1.0, sum(rand(n, 2).^2, dims=2)) / n", "meta": {"hexsha": "d0155eff4835bb6050675a2df1477643a871e4cf", "size": 524, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/estimatepi.jl", "max_stars_repo_name": "Beramos/DS-Julia2925", "max_stars_repo_head_hexsha": "8496d623f9836bec1db9a4daf882f484ad87a0a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-02-03T14:07:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T13:27:08.000Z", "max_issues_repo_path": "examples/estimatepi.jl", "max_issues_repo_name": "Beramos/DS-Julia2925", "max_issues_repo_head_hexsha": "8496d623f9836bec1db9a4daf882f484ad87a0a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 74, "max_issues_repo_issues_event_min_datetime": "2020-11-23T22:50:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:49:00.000Z", "max_forks_repo_path": "examples/estimatepi.jl", "max_forks_repo_name": "Beramos/DS-Julia2925", "max_forks_repo_head_hexsha": "8496d623f9836bec1db9a4daf882f484ad87a0a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-01-31T14:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-19T07:11:30.000Z", "avg_line_length": 20.96, "max_line_length": 72, "alphanum_fraction": 0.5935114504, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7615399691466415}}
{"text": "# function Mpz(pz_pml::SparseMatrixCSC{Float64,Int64}, lambda::Array{Float64,2}, dz::Float64, dt::Float64, ext::Int64, iflag::Int64)\n#     lambda = modExpand(lambda, ext, iflag)\n#     (m, n) = size(lambda)\n#     a1 = 9/8;   a2 = -1/24;\n#     c1 = a1/dz; c2 = a2/dz;\n#     C3 = zeros(m*n)\n#     denum = zeros(m*n)\n#     for ix = 1 : n\n#         for iz = 1 : m\n#             a = 1/dt + pz_pml[iz,ix]/2\n#             b = 1/dt - pz_pml[iz,ix]/2\n#             denum[(ix-1)*m+iz] = lambda[iz,ix] / a\n#             C3[(ix-1)*m+iz]= b / a\n#         end\n#     end\n#     tmp = spzeros(m, m)\n#     tmp[1,1] =  c1; tmp[1,2] = c2;\n#     tmp[2,1] = -c1; tmp[2,2] = c1; tmp[2,3] = c2;\n#     for iz = 3: m-1\n#         tmp[iz,iz-1] = -c1; tmp[iz, iz  ] = c1;\n#         tmp[iz,iz-2] = -c2; tmp[iz, iz+1] = c2;\n#     end\n#     tmp[m,m-1] = -c1; tmp[m,m] = c1; tmp[m, m-2] = -c2\n#     MpzBpz = spdiagm(C3)\n#     MpzBvz = spdiagm(denum) * kron(speye(n), tmp)\n#     return MpzBpz, MpzBvz\n# end\n\nfunction Mpz(pz_pml::SparseMatrixCSC{Float64,Int64}, v::Array{Float64,2}, dz::Float64, dt::Float64, ext::Int64, iflag::Int64)\n    v = modExpand(v, ext, iflag)\n    (m, n) = size(pz_pml)\n    a1 = 9/8;   a2 = -1/24;\n    c1 = a1/dz; c2 = a2/dz;\n    C3 = zeros(m*n)\n    denum = zeros(m*n)\n    for ix = 1 : n\n        for iz = 1 : m\n            a = 1/dt + pz_pml[iz,ix]/2\n            b = 1/dt - pz_pml[iz,ix]/2\n            denum[(ix-1)*m+iz] = (v[iz,ix])^2 / a\n            C3[(ix-1)*m+iz]= b / a\n        end\n    end\n    tmp = spzeros(m, m)\n    tmp[1,1] =  c1; tmp[1,2] = c2;\n    tmp[2,1] = -c1; tmp[2,2] = c1; tmp[2,3] = c2;\n    for iz = 3: m-1\n        tmp[iz,iz-1] = -c1; tmp[iz, iz  ] = c1;\n        tmp[iz,iz-2] = -c2; tmp[iz, iz+1] = c2;\n    end\n    tmp[m,m-1] = -c1; tmp[m,m] = c1; tmp[m, m-2] = -c2\n    MpzBpz = spdiagm(C3)\n    MpzBvz = spdiagm(denum) * kron(speye(n), tmp)\n    return MpzBpz, MpzBvz\nend\n\nfunction Mpz_back(pz_pml::SparseMatrixCSC{Float64,Int64}, v::Array{Float64,2}, dz::Float64, dt::Float64, ext::Int64, iflag::Int64)\n    v = modExpand(v, ext, iflag)\n    (m, n) = size(pz_pml)\n    a1 = 9/8;   a2 = -1/24;\n    c1 = a1/dz; c2 = a2/dz;\n    C3 = zeros(m*n)\n    denum = zeros(m*n)\n    for ix = 1 : n\n        for iz = 1 : m\n            a = 1/dt - pz_pml[iz,ix]/2\n            b = 1/dt + pz_pml[iz,ix]/2\n            denum[(ix-1)*m+iz] = (v[iz,ix])^2 / a\n            C3[(ix-1)*m+iz]= b / a\n        end\n    end\n    tmp = spzeros(m, m)\n    tmp[1,1] =  c1; tmp[1,2] = c2;\n    tmp[2,1] = -c1; tmp[2,2] = c1; tmp[2,3] = c2;\n    for iz = 3: m-1\n        tmp[iz,iz-1] = -c1; tmp[iz, iz  ] = c1;\n        tmp[iz,iz-2] = -c2; tmp[iz, iz+1] = c2;\n    end\n    tmp[m,m-1] = -c1; tmp[m,m] = c1; tmp[m, m-2] = -c2\n    MpzBpz = spdiagm(C3)\n    MpzBvz = -spdiagm(denum) * kron(speye(n), tmp)\n    return MpzBpz, MpzBvz\nend\n", "meta": {"hexsha": "3b7006c96e191b59a9bee2f43d435b1716d2d5ee", "size": 2784, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FDMtx/Mpz.jl", "max_stars_repo_name": "WneleiGao/AcousticWaveLab", "max_stars_repo_head_hexsha": "133e605e13d30b6292b66bef19ec9a2357c58b0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FDMtx/Mpz.jl", "max_issues_repo_name": "WneleiGao/AcousticWaveLab", "max_issues_repo_head_hexsha": "133e605e13d30b6292b66bef19ec9a2357c58b0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FDMtx/Mpz.jl", "max_forks_repo_name": "WneleiGao/AcousticWaveLab", "max_forks_repo_head_hexsha": "133e605e13d30b6292b66bef19ec9a2357c58b0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1428571429, "max_line_length": 132, "alphanum_fraction": 0.474137931, "num_tokens": 1328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7615328717366264}}
{"text": "\nusing FrankWolfe\nusing ProgressMeter\nusing Arpack\nusing Plots\nusing DoubleFloats\nusing ReverseDiff\n\nusing LinearAlgebra\n\nn = Int(1e2);\nk = n\n\nf(x) = dot(x, x)\nfunction grad!(storage, x)\n    @. storage = 2 * x\nend\n\n# pick feasible region\nlmo = FrankWolfe.ProbabilitySimplexOracle{Rational{BigInt}}(1); # radius needs to be integer or rational\n\n# compute some initial vertex\nx0 = FrankWolfe.compute_extreme_point(lmo, zeros(n));\n\n\n# benchmarking Oracles\nFrankWolfe.benchmark_oracles(f, grad!, () -> rand(n), lmo; k=100)\n\n# the algorithm runs in rational arithmetic even if the gradients and the function itself are not rational\n# this is because we replace the descent direction by the directions of the LMO are rational\n\n@time x, v, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(\n    f,\n    grad!,\n    lmo,\n    x0,\n    max_iteration=k,\n    line_search=FrankWolfe.Agnostic(),\n    print_iter=k / 10,\n    verbose=true,\n    emphasis=FrankWolfe.blas,\n);\n\nprintln(\"\\nOutput type of solution: \", eltype(x))\n\n# you can even run everything in rational arithmetic using the shortstep rule\n# NOTE: in this case the gradient computation has to be rational as well\n\n@time x, v, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(\n    f,\n    grad!,\n    lmo,\n    x0,\n    max_iteration=k,\n    line_search=FrankWolfe.RationalShortstep(),\n    L=2,\n    print_iter=k / 10,\n    verbose=true,\n    emphasis=FrankWolfe.blas,\n);\n\nprintln(\"\\nOutput type of solution: \", eltype(x))\n\nprintln(\"\\nNote: the last step where we exactly close the gap. This is not an error. \")\nfract = 1 // n\nprintln(\n    \"We have *exactly* computed the optimal solution with with the $fract * (1, ..., 1) vector.\\n\",\n)\nprintln(\"x = $x\")\n\n\n####################################################################################################################\n### APPRROXIMATE CARATHEODORY WITH PLANTED SOLUTION\n####################################################################################################################\n\n\nrhs = 1\nn = 40\nk = 1e5\n\nxpi = rand(big(1):big(100), n)\ntotal = sum(xpi)\nxp = xpi .// total\n\nf(x) = norm(x - xp)^2\nfunction grad!(storage, x)\n    @. storage = 2 * (x - xp)\nend\n\nlmo = FrankWolfe.ProbabilitySimplexOracle{Rational{BigInt}}(rhs)\ndirection = rand(n)\nx0 = FrankWolfe.compute_extreme_point(lmo, direction)\n\n@time x, v, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(\n    f,\n    grad!,\n    lmo,\n    x0,\n    max_iteration=k,\n    line_search=FrankWolfe.Agnostic(),\n    print_iter=k / 10,\n    emphasis=FrankWolfe.memory,\n    verbose=true,\n)\nprintln(\"\\nOutput type of solution: \", eltype(x))\n\nprintln(\"Computed solution: x = $x\")\n", "meta": {"hexsha": "a2ba7b64ba8dde626f094eab092e018989981034", "size": 2630, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/approximate_caratheodory.jl", "max_stars_repo_name": "gdalle/FrankWolfe.jl-2", "max_stars_repo_head_hexsha": "c3b3903c4808e24aa9e0f655aa2f8de0f2c1571c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/approximate_caratheodory.jl", "max_issues_repo_name": "gdalle/FrankWolfe.jl-2", "max_issues_repo_head_hexsha": "c3b3903c4808e24aa9e0f655aa2f8de0f2c1571c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/approximate_caratheodory.jl", "max_forks_repo_name": "gdalle/FrankWolfe.jl-2", "max_forks_repo_head_hexsha": "c3b3903c4808e24aa9e0f655aa2f8de0f2c1571c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3518518519, "max_line_length": 116, "alphanum_fraction": 0.6319391635, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642804, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7615288356042889}}
{"text": "# The goal of this file is to provide tools that implements the MFK algorithm from these two references: \r\n# @article{furman2017,\r\n#   title = {On {{Log}}-{{Normal Convolutions}}: {{An Analytical}}-{{Numerical Method With Applications}} to {{Economic Capital Determination}}},\r\n#   shorttitle = {On {{Log}}-{{Normal Convolutions}}},\r\n#   author = {Furman, Edward and Hackmann, Daniel and Kuznetsov, Alexey},\r\n#   year = {2017},\r\n#   issn = {1556-5068},\r\n#   abstract = {We put forward an efficient algorithm for approximating the sums of independent and lognormally distributed random variables. Namely, by merging tools from probability theory and numerical analysis, we are able to compute the cumulative distribution functions of the just-mentioned sums with any desired precision. Importantly, our algorithm is fast and can tackle equally well sums with just a few or thousands of summands. We illustrate the effectiveness of the new method in the contexts of the individual and collective risk models, aggregate economic capital determination, and economic capital allocation.},\r\n#   journal = {SSRN Electronic Journal},\r\n#   language = {en}\r\n# }\r\n\r\n# @article{miles2019,\r\n#   ids = {mile,milesa},\r\n#   title = {Risk Aggregation: {{A}} General Approach via the Class of {{Generalized Gamma Convolutions}}},\r\n#   author = {Miles, Justin and Furman, Edward and Kuznetsov, Alexey},\r\n#   year = {2019},\r\n#   journal = {Variance},\r\n#   keywords = {gamma}\r\n# }\r\n\r\n\"\"\"\r\n\r\n    compute_g(dist,n, integrator)\r\n\r\nThis function will compute the n first theretical (-1)-exponentially shifted moments of a distribution, \r\nusing takashi-mori tanh-sinh exponentials formulas from the DoubleExponentialFormulas package. \r\n\r\nThis might take a long time. As an integrator, you should pass the result of `QuadDE(BigFloat)` after setting enough precision.\r\n\r\n\"\"\"\r\nfunction compute_g(dist,n, integrator)\r\n    g = Array{BigFloat}(undef, 1,2n+1)\r\n    residuals_g = deepcopy(g)\r\n    for i in 0:(2n)\r\n        g[i+1],residuals_g[i+1] = integrator(x -> (-x)^(i) * Distributions.pdf(dist,x) * exp(-x), 0, +Inf)\r\n        print(\"g_{\",i,\"} = \",Float64(g[i+1]),\", rez = \",Float64(residuals_g[i+1]),\"\\n\")\r\n    end\r\n    return g\r\nend\r\n\r\n\r\n\"\"\"\r\n\r\n    E_from_g(g)\r\n\r\nSimply computes the empirical laguerre coefficients from the exponentially shifted moments, \r\nif you computed those moments from a theoretical distribution.\r\n\r\n\"\"\"\r\nfunction E_from_g(g)\r\n    # this function should compute laguerre coefficients from g. \r\n    a = deepcopy(g)\r\n    for i in 1:length(a)\r\n        a[i] = sqrt(2) * sum(binomial(big(i-1),big(k))*big(2)^(k)/factorial(big(k)) * g[k+1] for k in 0:(i-1))\r\n    end\r\n    return a\r\nend\r\n\r\n\r\nfunction build_s!(s,g,facts)\r\n    s[1] = -g[2]/g[1]\r\n    for k in 1:(length(s)-1)\r\n        s[k+1] = g[k+2] / facts[k+1]\r\n        for i in 0:(k-1)\r\n            s[k+1] += s[i+1] * g[k-i+1] / facts[k-i+1]\r\n        end\r\n        s[k+1] = - s[k+1]/g[1]\r\n    end\r\nend\r\n\r\nfunction s_from_k(k)\r\n    if isodd(length(k))\r\n        n = Int((length(k)-1)/2)\r\n    else\r\n        n = Int(length(k)/2) - 1\r\n    end\r\n    # n = Int(round(length(k)/2))\r\n    s = k[2:2n+1] .* (-1) .^(2:(2n+1))\r\n    return s\r\nend\r\n\r\nfunction MFK_end(s::Vector{T}) where T\r\n    n = Int(length(s)//2)\r\n    S = zeros(T,(n,n))\r\n    for i in 0:(n-1)\r\n        for j in 0:(n-1)\r\n            S[i+1,j+1] = s[i+j+1]\r\n        end\r\n    end\r\n\r\n    sol_b = LinearAlgebra.Symmetric(S) \\ (-s[(n+1):end])\r\n    b = deepcopy(sol_b)\r\n    append!(b,1)\r\n    b = reverse(b)\r\n    b_deriv = reverse(sol_b) .* (1:n)\r\n\r\n    a = zeros(T,n)\r\n    a[1] = s[1]\r\n    for k in 1:(n-1)\r\n        a[k+1] = s[k+1]\r\n        for i in 0:(k-1)\r\n            a[k+1] = a[k+1] + b[i+2] * s[k-i]\r\n        end\r\n    end\r\n\r\n    z = real.(PolynomialRoots.roots(b, polish=true))\r\n\r\n    beta = -z .-1\r\n    alpha = deepcopy(beta)\r\n\r\n    for i in 1:length(alpha)\r\n        rez_num = 0\r\n        rez_denom = 0\r\n        for k in 1:length(a)\r\n            rez_num += a[k] * z[i]^(k-1)\r\n        end\r\n        for k in 1:length(b_deriv)\r\n            rez_denom += b_deriv[k] * z[i]^(k-1)\r\n        end\r\n        alpha[i] = rez_num/rez_denom\r\n    end\r\n    theta = 1 ./beta\r\n    return alpha,theta\r\nend\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"\r\n\r\n    MFK_Projection(g_integrals,n_gammas)\r\n\r\nFrom a set of g_integrals computed by the compute_g function, this function runs the algorithm from Miles, Furman & Kuznetsov \r\nto produce a univariate gamma convolution. \r\n\r\nThis algorithm works only if the distribution you computed the g_integrals from is, indeed, a generalized gamma convolution. \r\notherwise, it might fail and return garbage. \r\n\r\n\"\"\"\r\nfunction MFK_Projection(g_integrals::Vector{T},n) where T\r\n    facts = factorial.(T.(0:2n))\r\n    s = Array{T}(undef, 2n)\r\n    build_s!(s,g_integrals,facts)\r\n    alpha,beta = MFK_end(s,n)\r\n    return ThorinDistributions.UnivariateGammaConvolution(Float64.(alpha), Float64.(1 ./ beta))\r\nend", "meta": {"hexsha": "22dd261c1c40ec54cf4f19f67c1019205d207fe1", "size": 4881, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MFKProjection.jl", "max_stars_repo_name": "lrnv/ThorinDistributions.jl", "max_stars_repo_head_hexsha": "2d0a6c358878e38705e18b99ec5fa68552c9a2ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-02-23T15:28:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T17:58:25.000Z", "max_issues_repo_path": "src/MFKProjection.jl", "max_issues_repo_name": "lrnv/ThorinDistributions.jl", "max_issues_repo_head_hexsha": "2d0a6c358878e38705e18b99ec5fa68552c9a2ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2020-11-24T00:06:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T00:32:14.000Z", "max_forks_repo_path": "src/MFKProjection.jl", "max_forks_repo_name": "lrnv/ThorinDistributions.jl", "max_forks_repo_head_hexsha": "2d0a6c358878e38705e18b99ec5fa68552c9a2ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9797297297, "max_line_length": 630, "alphanum_fraction": 0.6168817865, "num_tokens": 1435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7615288348066541}}
{"text": "using BenchmarkTools\nusing InteractiveUtils\n\nfunction trapz(a::Float64,b::Float64,n::Int64,f::Function)\n    h::Float64=(b-a)/n\n    sum=0.5*(f(a)+f(b))\n    for i=1:n-1\n        sum+=f(i*h)\n    end\n    sum*=h\nend\n               \n@inline f(x::Float64)=+exp(-x)*x^2\n\nfunction g(x::Float64)\n    h=0.0\n    if x<0.5\n        h=-exp(-x)\n    else\n        h= exp(x)\n    end\n    return h*x^2\nend\n\n# Note: replacing f by f1 and g by g1 do not change the computing time:\n# f1(x)=x < 1.5 ? +exp(-x)*x^2 :  +exp(-x)*x^2\n# g1(x::Float64)=x < 0.5 ? -exp(-x)*x^2 :  exp(x)*x^2\n\nfunction implicit(t::Float64)\n    # implicit = root of  4*sin(x)-exp(x)+t\n    # Newton iterations, starting from zero:\n    x= 0.0\n    F= 4*sin(x)-exp(x)+t\n    while abs(F)> 1.e-15\n        #\n        x-= F/(4*cos(x) - exp(x))\n        F=  4*sin(x)-exp(x)+t\n        #\n    end\n    x\nend\n\nio = IOContext(stdout, :compact => false)\n\nfw=open(\"RunningOn\"*gethostname(),\"w\")\n# Note: it seems that a loop like:\n#\n# for F in [f,g,implicit]\n#   bench_res = @benchmark trapz(0.,1.,1000,F)\n# end\n#\n# is incompatible with @benchmark... who knows why?\n\nf(0.5)\nprintln(\"f:\")\nbench_res = @benchmark trapz(0.,1.,1000,f);\nshow(io, bench_res)\nwrite(fw,\"\\nf: \"*string(bench_res)*\"\\n\")\n\ng(0.5)\nprintln(\"\\ng:\")\nbench_res = @benchmark trapz(0.,1.,1000,g);\nshow(io, bench_res)\nwrite(fw,\"g: \"*string(bench_res)*\"\\n\")\n\nimplicit(0.5)\nprintln(\"\\nimplicit:\")\nbench_res = @benchmark trapz(0.,1.,1000,implicit)\nshow(io, bench_res)\nwrite(fw,\"implicit: \"*string(bench_res)*\"\\n\")\n\nprintln(\"\\nend.\")\nclose(fw)\n", "meta": {"hexsha": "bbf76de7df5d35ad1a6f4cd6cd394d455c0ea2bb", "size": 1530, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CallBack/Ju/main.jl", "max_stars_repo_name": "danielcort/benchmarks-python-julia-c", "max_stars_repo_head_hexsha": "aececc9f1fc3c368ae57f84028b0cf35a0c138e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-03-27T08:36:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T12:26:54.000Z", "max_issues_repo_path": "CallBack/Ju/main.jl", "max_issues_repo_name": "danielcort/benchmarks-python-julia-c", "max_issues_repo_head_hexsha": "aececc9f1fc3c368ae57f84028b0cf35a0c138e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-05-13T16:44:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-27T06:33:09.000Z", "max_forks_repo_path": "CallBack/Ju/main.jl", "max_forks_repo_name": "danielcort/benchmarks-python-julia-c", "max_forks_repo_head_hexsha": "aececc9f1fc3c368ae57f84028b0cf35a0c138e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-05-29T13:27:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-27T17:49:09.000Z", "avg_line_length": 20.6756756757, "max_line_length": 71, "alphanum_fraction": 0.5816993464, "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7615288158362602}}
{"text": "using Statistics\nusing StatsBase\n\n\n\"\"\"\nBounds given metric between -1.0 and 1.0, where 1.0 is perfect fit.\n\nSuitable for use with any metric that ranges from 1 to -∞.\n\n# References\n1. Mathevet, T., Michel, C., Andréassian, V., Perrin, C., 2006.\n    A bounded version of the Nash-Sutcliffe criterion for better model\n    assessment on large sets of basins.\n    IAHS-AISH Publication 307, 211–219.\n    https://iahs.info/uploads/dms/13614.21--211-219-41-MATHEVET.pdf\n\n# Example\n```julia\njulia> import Streamfall: @bound, KGE\njulia> @bound KGE([1,2], [3,2])\n-0.35653767993482094\n```\n\"\"\"\nmacro bound(metric)\n    tmp = :($metric)\n    return :($tmp / (2.0 - $tmp))\nend\n\n\n\"\"\"\nNormalizes given metric between 0.0 and 1.0, where 1.0 is perfect fit.\n\nSuitable for use with any metric that ranges from 1 to -∞.\n\n# References\n1. Nossent, J., Bauwens, W., 2012.\n    Application of a normalized Nash-Sutcliffe efficiency to improve the\n    accuracy of the Sobol’ sensitivity analysis of a hydrological model.\n    EGU General Assembly Conference Abstracts 237.\n\n# Example\n```julia\njulia> import Streamfall: @normalize, KGE\njulia> @normalize KGE([1,2], [3,2])\n0.1111111111111111\n```\n\"\"\"\nmacro normalize(metric)\n    return :(1.0 / (2.0 - $metric))\nend\n\n\n\"\"\"\nApplies mean inverse approach to a metric.\n\nSuitable for use with any metric that ranges from 1 to -∞.\n\nIf using with other macros such as `@normalize` or `@bound`,\nthese must come first.\n\n# References\n1. Garcia, F., Folton, N., Oudin, L., 2017.\n    Which objective function to calibrate rainfall–runoff\n        models for low-flow index simulations?\n    Hydrological Sciences Journal 62, 1149–1166.\n    https://doi.org/10.1080/02626667.2017.1308511\n\n# Example\n```julia\njulia> import Streamfall: @normalize, @mean_inverse, KGE\njulia> @normalize @mean_inverse KGE [1,2] [3,2] 1e-6\n0.3193506006429825\n```\n\"\"\"\nmacro mean_inverse(metric, obs, sim, ϵ=1e-2)\n    obj, o, s, ϵ = eval(metric), eval(obs), eval(sim), eval(ϵ)\n    q = obj(o, s)\n    q2 = obj(1.0 ./ (o .+ ϵ), 1.0 ./ (s .+ ϵ))\n    return mean([q, q2])\nend\n\n\n\"\"\"\nApplies split meta metric approach\n\nIf using with other macros such as `@normalize` or `@bound`,\nthese must come first.\n\n# References\n1. Fowler, K., Peel, M., Western, A., Zhang, L., 2018.\n    Improved Rainfall-Runoff Calibration for Drying Climate:\n    Choice of Objective Function.\n    Water Resources Research 54, 3392–3408.\n    https://doi.org/10.1029/2017WR022466\n\n# Example\n```julia\njulia> using Statistics\njulia> import Streamfall: @normalize, @split, KGE\njulia> @normalize @split KGE repeat([1,2], 365) repeat([3,2], 365) 365 mean\n0.3217309561946589\n```\n\"\"\"\nmacro split(metric, obs, sim, n, agg_func=mean)\n    obj, o, s, t, func = eval(metric), eval(obs), eval(sim), eval(n), eval(agg_func)\n    return naive_split_metric(o, s; n_members=t, metric=obj, comb_method=func)\nend\n\n\n\"\"\"The Nash-Sutcliffe Efficiency score\"\"\"\nNSE(obs, sim) = 1.0 - sum((obs .- sim).^2) / sum((obs .- mean(obs)).^2)\n\n\n\"\"\"Normalized Nash-Sutcliffe Efficiency score (bounded between 0 and 1).\n\n# References\n1. Nossent, J., Bauwens, W., 2012.\n    Application of a normalized Nash-Sutcliffe efficiency to improve the accuracy of the Sobol’ sensitivity analysis of a hydrological model.\n    EGU General Assembly Conference Abstracts 237.\n\"\"\"\nNNSE(obs, sim) = 1.0 / (2.0 - NSE(obs, sim))\n\n\n\"\"\"Root Mean Square Error\"\"\"\nRMSE(obs, sim) = (sum((sim .- obs).^2)/length(sim))^0.5\n\n\n\"\"\"Coefficient of determination (R^2)\n\nAliases `NSE()`\n\"\"\"\nfunction R2(obs, sim)::Float64\n    return NSE(obs, sim)\nend\n\n\n\"\"\"Adjusted R^2\n\n# Arguments\n- `obs::Vector` : observations\n- `sim::Vector` : modeled results\n- `p::Int` : number of explanatory variables\n\"\"\"\nfunction ADJ_R2(obs, sim, p::Int64)::Float64\n    n = length(obs)\n    adj_r2 = 1 - (1 - R2(obs, sim)) * ((n - 1) / (n - p - 1))\n\n    return adj_r2\nend\n\n\n\"\"\"\nMean Absolute Error\n\"\"\"\nMAE(obs, sim) = mean(abs.(sim .- obs))\n\n\n\"\"\"\nMean Error\n\"\"\"\nME(obs, sim) = mean(sim .- obs)\n\n\n\"\"\"\n    PBIAS(obs::Vector, sim::Vector)::Float64\n\nPercent bias between `sim` and `obs`\n\nModel performance for streamflow can be determined to be\nsatisfactory if the Nash-Sutcliffe Efficiency (NSE)\nscore > 0.5, the RMSE standard deviation ratio (RSR) < 0.7\nand percent bias (PBIAS) is +/- 25% (see [1]).\n\n# References\n1. Moriasi, D.N., Arnold, J.G., Liew, M.W.V., Bingner, R.L.,\n    Harmel, R.D., Veith, T.L., 2007.\n    Model Evaluation Guidelines for Systematic Quantification\n    of Accuracy in Watershed Simulations.\n    Transactions of the ASABE 50, 885–900.\n    https://doi.org/10.13031/2013.23153\n\"\"\"\nPBIAS(obs, sim) = (sum(obs .- sim) * 100) / sum(obs)\n\n\n\"\"\"\n    RSR(obs::Vector, sim::Vector)::Float64\n\nThe RMSE-observations standard deviation ratio (RSR).\n\nVaries between 0 and a large positive value, where 0\nindicates an RMSE value of 0.\n\n# References\n1. Moriasi, D.N., Arnold, J.G., Liew, M.W.V., Bingner, R.L.,\n    Harmel, R.D., Veith, T.L., 2007.\n    Model Evaluation Guidelines for Systematic Quantification\n    of Accuracy in Watershed Simulations.\n    Transactions of the ASABE 50, 885–900.\n    https://doi.org/10.13031/2013.23153\n\"\"\"\nfunction RSR(obs, sim)::Float64\n    rmse = RMSE(obs, sim)\n    σ_obs = std(obs)\n    rsr = rmse / σ_obs\n    return rsr\nend\n\n\n\"\"\"\n    EV(obs, sim)\n\nExplained Variance.\n\nIndicates the amount of variation in the observations which the predictions\nare able to explain.\n\"\"\"\nfunction EV(obs, sim)\n    return 1.0 - (var(obs - sim) / obs)\nend\n\n\n\"\"\"\nRelative Skill Score.\n\nProvides an indication of model performance relative to a known benchmark score.\n\nSuitable for use with least-squares approaches that provide skill scores ranging from 1 to -∞.\n\n# Arguments\n- `Sb` : Benchmark score\n- `Sm` : Model score\n\n# References\n1. Knoben, W.J.M., Freer, J.E., Woods, R.A., 2019.\n    Technical note: Inherent benchmark or not?\n        Comparing Nash-Sutcliffe and Kling-Gupta efficiency scores (preprint).\n    Catchment hydrology/Modelling approaches.\n    https://doi.org/10.5194/hess-2019-327\n\"\"\"\nfunction relative_skill_score(Sb::Float64, Sm::Float64)\n    return (Sm - Sb) / (1.0 - Sb)\nend\n\n\n\"\"\"\n    NSE_logbias(obs, sim; metric::Function=NSE, bias_threshold::Float64=5.0, shape::Float64=2.5)\n\nThe NSE_logbias meta-metric provides a weighted combination of a least-squares approach and a\nlogarithmic function of bias. The metric penalizes predictions with an overall bias above a\nthreshold (defined as 5% in [1]).\n\nIt is also referred to as the Viney F score.\n\n# Extended help\nThe penalty applied is non-symmetrical (or multiplicatively symmetrical) in that\npredictions that are _double_ the observed are penalized identically to predictions that are\n_half_ the observed volume.\n\n# Arguments\n- `obs::Vector` : Historic observations to compare against\n- `sim::Vector` : Modeled time series\n- `metric::Function` : least-squares method to use, defaults to NSE\n- `bias_threshold::Float64` : Bias threshold after which the score given by `metric` is penalized, defaults to 5 (%)\n- `shape::Float64` : Exponent value controlling shape of penalization (see Figure 2 in [1]).\n\n# References\n1. Viney, N. R., Perraud, J., Vaze, J., Chiew, F.H.S., Post, D.A., Yang, A. 2009\n    The usefulness of bias constraints in model calibration for regionalisation\n        to ungauged catchments\n    18th World IMACS / MODSIM Congress, Cairns, Australia, 13 - 17 July 2009\n    Available at:\n    https://www.researchgate.net/publication/294697092_The_usefulness_of_bias_constraints_in_model_calibration_for_regionalisation_to_ungauged_catchments\n\n2. Teng, J., Potter, N.J., Chiew, F.H.S., Zhang, L., Wang, B., Vaze, J., Evans, J.P., 2015.\n    How does bias correction of regional climate model precipitation affect modelled runoff?\n    Hydrology and Earth System Sciences 19, 711–728.\n    https://doi.org/10.5194/hess-19-711-2015\n\"\"\"\nfunction NSE_logbias(obs, sim; metric=NSE, bias_threshold=5.0, shape=2.5)\n    E_ns = metric(obs, sim)\n    B = PBIAS(obs, sim) / 100.0\n    return E_ns - bias_threshold * abs(log(1 + B))^shape\nend\n\n\n\"\"\"\n    KGE(obs::Vector, sim::Vector; scaling::Tuple=nothing)::Float64\n\nCalculate the 2009 Kling-Gupta Efficiency (KGE) metric.\n\nDecomposes NSE into correlation (`r`), relative variability (`α`), and bias (`β`) terms.\n\nA KGE score of 1 means perfect fit.\nA score < -0.41 indicates that the mean of observations\nprovides better estimates (see Knoben et al., [2]).\n\nThe `scaling` argument expects a three-valued tuple\nwhich scales `r`, `α` and `β` factors respectively.\nIf not specified, defaults to `1`.\n\nNote: Although similar, NSE and KGE cannot be directly compared.\n\n# References\n1. Gupta, H.V., Kling, H., Yilmaz, K.K., Martinez, G.F., 2009.\n    Decomposition of the mean squared error and NSE performance criteria:\n    Implications for improving hydrological modelling.\n    Journal of Hydrology 377, 80–91.\n    https://doi.org/10.1016/j.jhydrol.2009.08.003\n\n2. Knoben, W.J.M., Freer, J.E., Woods, R.A., 2019.\n    Technical note: Inherent benchmark or not? Comparing Nash-Sutcliffe and Kling-Gupta efficiency scores (preprint).\n    Catchment hydrology/Modelling approaches.\n    https://doi.org/10.5194/hess-2019-327\n\n3. Mizukami, N., Rakovec, O., Newman, A.J., Clark, M.P., Wood, A.W.,\n    Gupta, H.V., Kumar, R., 2019.\n    On the choice of calibration metrics for “high-flow”\n        estimation using hydrologic models.\n    Hydrology and Earth System Sciences 23, 2601–2614.\n    https://doi.org/10.5194/hess-23-2601-2019\n\"\"\"\nfunction KGE(obs, sim; scaling=nothing)::Float64\n    if isnothing(scaling)\n        scaling = (1, 1, 1)\n    end\n\n    # Correlation\n    r = Statistics.cor(obs, sim)\n    if isnan(r)\n        r = 0.0\n    end\n\n    # relative variance\n    α = std(sim) / std(obs)\n\n    # bias\n    β = mean(sim) / mean(obs)\n\n    rs = scaling[1]\n    as = scaling[2]\n    bs = scaling[3]\n\n    kge = 1 - sqrt(rs*(r - 1)^2 + as*(α - 1)^2 + bs*(β - 1)^2)\n\n    return kge\nend\n\n\n\"\"\"Bounded KGE, bounded between -1 and 1.\n\n# Arguments\n- `obs::Vector` : observations\n- `sim::Vector` : modeled results\n\"\"\"\nfunction BKGE(obs, sim)::Float64\n    kge = KGE(obs, sim)\n    return kge / (2 - kge)\nend\n\n\n\"\"\"Normalized KGE between 0 and 1.\n\n# Arguments\n- `obs::Vector` : observations\n- `sim::Vector` : modeled results\n\"\"\"\nfunction NKGE(obs, sim; scaling=nothing)::Float64\n    return 1 / (2 - KGE(obs, sim; scaling=scaling))\nend\n\n\n\"\"\"Calculate the modified KGE metric (2012).\n\nAlso known as KGE prime (KGE').\n\n# Extended help\n\nIt is not recommended to apply KGE' with log-transformed flows (see [2]).\nNumerical instabilities arise as flow approaches values close to zero.\nThis is possible under extreme dry conditions or by chance when sub-sampling.\n\nIn cases where observations are constant or otherwise displays zero variance or zero\nmean flow, this implementation applies a simple logistic function (ℯ⁻ˣ) to gain an \nindication of simulated data's distance to zero.\n\nThis is to:\n- avoid NaNs influencing subsequent calculations \n- allow use with split methods which may partition streamflows into periods of 0 flows.\n\n# Arguments\n- `obs::Vector`: observations\n- `sim::Vector` : modeled results\n- `scaling::Tuple` : scaling factors in order of timing (r), magnitude (β), variability (γ).\n                     Defaults to (1,1,1).\n\n# References\n1. Kling, H., Fuchs, M., Paulin, M., 2012.\n    Runoff conditions in the upper Danube basin under an ensemble of climate change scenarios.\n    Journal of Hydrology 424–425, 264–277.\n    https://doi.org/10.1016/j.jhydrol.2012.01.011\n\n2. Santos, L., Thirel, G., Perrin, C., 2018.\n    Technical note: Pitfalls in using log-transformed flows within the KGE criterion.\n    Hydrology and Earth System Sciences 22, 4583–4591.\n    https://doi.org/10.5194/hess-22-4583-2018\n\"\"\"\nfunction mKGE(obs, sim; scaling=nothing)::Float64\n    if isnothing(scaling)\n        scaling = (1,1,1)\n    end\n\n    # Timing (Pearson's correlation)\n    r = Statistics.cor(obs, sim)\n    if isnan(r)\n        # can happen if obs or sim is a constant (std of 0)\n        r = all(obs .== sim) ? 1.0 : 0.0\n    end\n\n    # Variability\n    cv_s = StatsBase.variation(sim)\n    if isnan(cv_s)\n        cv_s = 0.0\n    end\n\n    cv_o = StatsBase.variation(obs)\n    if isnan(cv_o)\n        cv_o = 0.0\n    end\n\n    if cv_o == 0.0 && cv_s == 0.0\n        γ = 1.0\n    elseif cv_o == 0.0\n        # Use logistic function to indicate distance from 0\n        γ = 1.0 / exp(cv_s)\n    else\n        γ = cv_s / cv_o\n    end\n\n    # Magnitude\n    μ_o = mean(obs)\n    μ_s = mean(sim)\n    if μ_o == 0.0\n        # use logistic function to indicate distance from 0 (μ_o)\n        β = 1.0 / exp(μ_s)\n    else\n        β = μ_s / μ_o\n    end\n\n    rs = scaling[1]\n    βs = scaling[2]\n    γs = scaling[3]\n\n    mod_kge = 1.0 - sqrt(rs*(r - 1)^2 + βs*(β - 1)^2 + γs*(γ - 1)^2)\n\n    return mod_kge\nend\n\n\n\"\"\"Bounded modified KGE between -1 and 1.\n\n# Arguments\n- `obs::Vector` : observations\n- `sim::Vector` : modeled results\n\"\"\"\nfunction BmKGE(obs, sim; scaling=nothing)::Float64\n    mkge = mKGE(obs, sim; scaling=scaling)\n    return mkge / (2 - mkge)\nend\n\n\n\"\"\"Normalized modified KGE between 0 and 1.\n\n# Arguments\n- `obs::Vector` : observations\n- `sim::Vector` : modeled results\n\"\"\"\nfunction NmKGE(obs, sim; scaling=nothing)::Float64\n    return 1 / (2 - mKGE(obs, sim; scaling=scaling))\nend\n\n\n\"\"\"\nMean Inverse NmKGE\n\nSaid to produce better fits for low-flow indices\ncompared to mKGE (see [1]).\n\n# Arguments\n- `obs::Vector` : observations\n- `sim::Vector` : modeled results\n- `scaling::Tuple` : scaling factors for r, α, and β (defaults to 1.0)\n- `ϵ::Float64` : small constant to use with inverse flow to allow consideration of periods with no flow. Defaults to 1e-2.\n\n# References\n1. Garcia, F., Folton, N., Oudin, L., 2017.\n    Which objective function to calibrate rainfall–runoff\n        models for low-flow index simulations?\n    Hydrological Sciences Journal 62, 1149–1166.\n    https://doi.org/10.1080/02626667.2017.1308511\n\"\"\"\nmean_NmKGE(obs, sim; scaling=nothing, ϵ=1e-2) = mean([Streamfall.NmKGE(obs, sim; scaling=scaling), Streamfall.NmKGE(1.0 ./ (obs .+ ϵ), 1.0 ./ (sim .+ ϵ); scaling=scaling)])\n\n\n\"\"\"Calculate the non-parametric Kling-Gupta Efficiency (KGE) metric.\n\n# Arguments\n- `obs::Vector` : observations\n- `sim::Vector` : modeled\n- `scaling::Tuple` : scaling factors for timing (s), variability (α), magnitude (β)\n\n# References\n1. Pool, S., Vis, M., Seibert, J., 2018.\n    Evaluating model performance: towards a non-parametric variant of the Kling-Gupta efficiency.\n    Hydrological Sciences Journal 63, 1941–1953.\n    https://doi.org/10.1080/02626667.2018.1552002\n\n\"\"\"\nfunction npKGE(obs, sim; scaling=nothing)::Float64\n    if isnothing(scaling)\n        scaling = (1,1,1)\n    end\n\n    # flow duration curves\n    μ_s = mean(sim)\n    if μ_s == 0.0\n        fdc_sim = repeat([0.0], length(sim))\n    else\n        x = length(sim) * μ_s\n        fdc_sim = sort(sim / x)\n    end\n\n    μ_o = mean(obs)\n    if μ_o == 0.0\n        fdc_obs = repeat([0.0], length(obs))\n    else\n        x = length(obs) * μ_o\n        fdc_obs = sort(obs / x)\n    end\n\n    α = 1 - 0.5 * sum(abs.(fdc_sim - fdc_obs))\n\n    # Magnitude\n    if μ_o == 0.0\n        β = μ_s == 0.0 ? 1.0 : μ_s\n    else\n        β = μ_s / μ_o\n    end\n\n    # Timing and flow dynamics\n    r = StatsBase.corspearman(fdc_obs, fdc_sim)\n    if isnan(r)\n        r = 1.0  # can occur if identical sequences are used (e.g., 0 flows)\n    end\n\n    rs = scaling[1]\n    αs = scaling[2]\n    βs = scaling[3]\n\n    kge = 1 - sqrt(rs*(r - 1)^2 + αs*(α - 1)^2 + βs*(β - 1)^2)\n\n    return kge\nend\n\n\n\"\"\"Bounded non-parametric KGE between -1 and 1.\n\n# Arguments\n- `obs::Vector` : observations\n- `sim::Vector` : modeled results\n\"\"\"\nfunction BnpKGE(obs, sim; scaling=nothing)::Float64\n    npkge = npKGE(obs, sim; scaling=scaling)\n    return npkge / (2 - npkge)\nend\n\n\n\"\"\"Normalized non-parametric KGE between 0 and 1.\n\n# Arguments\n- `obs::Vector` : observations\n- `sim::Vector` : modeled results\n\"\"\"\nfunction NnpKGE(obs, sim; scaling=nothing)::Float64\n    return 1 / (2 - npKGE(obs, sim; scaling=scaling))\nend\n\n\n\"\"\"Liu Mean Efficiency metric (LME).\n\nReformulation of the KGE metric said to be advantageous for capturing extreme\nflow events.\n\n# Arguments\n- `obs::Vector` : observations\n- `sim::Vector` : modeled results\n\n# References\n1. Liu, D., 2020.\n    A rational performance criterion for hydrological model.\n    Journal of Hydrology 590, 125488.\n    https://doi.org/10.1016/j.jhydrol.2020.125488\n\"\"\"\nfunction LME(obs, sim)::Float64\n    μ_o = mean(obs)\n    μ_s = mean(sim)\n    β = (μ_s / μ_o)\n\n    r = Statistics.cor(obs, sim)\n    σ_s = std(sim)\n    σ_o = std(obs)\n    α = (σ_s / σ_o)\n    k_1 = r * α\n\n    LME = 1 - sqrt((k_1 - 1)^2 + (β - 1)^2)\n\n    return LME\nend\n\n\nfunction naive_split_metric(obs::Vector, sim::Vector, n_members::Int, metric::Function=NNSE)\n    obs_chunks = collect(Iterators.partition(obs, n_members))\n    sim_chunks = collect(Iterators.partition(sim, n_members))\n    scores = Array{Float64, 1}(undef, length(obs_chunks))\n\n    for (idx, h_chunk) in enumerate(obs_chunks)\n        scores[idx] = metric(h_chunk, sim_chunks[idx])\n    end\n\n    return scores\nend\n\n\n\"\"\"Naive approach to split metrics.\n\nSplit metrics are a meta-objective optimization approach which \"splits\" data\ninto subperiods. The objective function is calculated for each subperiod and\nthen recombined. The approach addresses the lack of consideration of dry years\nwith least-squares.\n\nIn Fowler et al., [1] the subperiod is one year. The implementation offered here\nis \"naive\" in that the data is partitioned into `N` chunks of `n_members` and\ndoes not consider date/time.\n\n# Arguments\n- `obs::Vector` : Historic observations to compare against\n- `sim::Vector` : Modeled time series\n- `n_members::Int` : number of members per chunk (i.e., sub-samples), defaults to 365\n- `metric::Function` : Objective function to apply, defaults to NNSE\n- `comb_method::Function` : Recombination method, defaults to `mean`\n\n# References\n1. Fowler, K., Peel, M., Western, A., Zhang, L., 2018.\n    Improved Rainfall-Runoff Calibration for Drying Climate: Choice of Objective Function.\n    Water Resources Research 54, 3392–3408.\n    https://doi.org/10.1029/2017WR022466\n\"\"\"\nfunction naive_split_metric(obs, sim; n_members::Int=365, metric::Function=NNSE, comb_method::Function=mean)\n    scores = naive_split_metric(obs, sim, n_members, metric)\n    return comb_method(scores)\nend\n\n\n\"\"\"\n    inverse_metric(obs, sim; metric, comb_method::Function=mean)\n\nA meta-objective function which combines the performance of the\ngiven metric as applied to the discharge and the inverse of the\ndischarge.\n\nBy default, the combination method is to take the mean.\n\n# Arguments\n- obs : observed\n- sim : modeled results\n- `metric::Function` : objective function\n- `comb_method::Function` : mean\n- ϵ : offset value to use (enables use with zero-flow time steps), defaults to 1e-2\n\n\n# References\n1. Garcia, F., Folton, N., Oudin, L., 2017.\n    Which objective function to calibrate rainfall–runoff models\n        for low-flow index simulations?\n    Hydrological Sciences Journal 62, 1149–1166.\n    https://doi.org/10.1080/02626667.2017.1308511\n\"\"\"\nfunction inverse_metric(obs, sim, metric::Function; comb_method::Function=mean, ϵ=1e-2)\n    return comb_method([metric(obs, sim), metric(1.0 ./ (obs .+ ϵ), 1.0 ./ (sim .+ ϵ))])\nend\n\n\n\"\"\"\nAllows comparison of any model compared against a pre-defined benchmark, assuming both scores were obtained with\nthe same objective function.\n\nPositive values indicate a model is better than the benchmark, and negative values indicate a model performs worse.\n\n# Extended help\nIt is noted in Knoben et al., [1] that the skill score should always be contextualized with the original benchmark\nvalue. Interpreting skill scores by themselves may become difficult if the benchmark score is already quite high.\nA small improvement of no real practical value could be misconstrued as a large improvement.\nAs an example, if the benchmark has an KGE score of 0.999 and its counterpart 0.9995, then a skill score of 0.5 will\nbe reported.\n\n# References\n1. Knoben, W.J.M., Freer, J.E., Woods, R.A., 2019. \n    Technical note: Inherent benchmark or not? Comparing Nash-Sutcliffe and Kling-Gupta efficiency scores (preprint). \n    Catchment hydrology/Modelling approaches. \n    https://doi.org/10.5194/hess-2019-327\n\n2. Towner, J., Cloke, H.L., Zsoter, E., Flamig, Z., Hoch, J.M., Bazo, J., Coughlan de Perez, E., Stephens, E.M., 2019. \n    Assessing the performance of global hydrological models for capturing peak river flows in the Amazon basin. \n    Hydrology and Earth System Sciences 23, 3057–3080. \n    https://doi.org/10.5194/hess-23-3057-2019\n\"\"\"\nfunction skill_score(model_score, benchmark_score)\n    return (model_score - benchmark_score) / (1.0 - benchmark_score)\nend\n", "meta": {"hexsha": "749f30e38a57bb07669b838665ae0f3fea15cd09", "size": 20721, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/metrics.jl", "max_stars_repo_name": "ConnectedSystems/Streamfall.jl", "max_stars_repo_head_hexsha": "37d747e26d58281d21327f20a61e3a86f4369ed4", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-06-17T16:40:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T09:10:53.000Z", "max_issues_repo_path": "src/metrics.jl", "max_issues_repo_name": "ConnectedSystems/Streamfall.jl", "max_issues_repo_head_hexsha": "37d747e26d58281d21327f20a61e3a86f4369ed4", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-06-19T12:54:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T07:51:08.000Z", "max_forks_repo_path": "src/metrics.jl", "max_forks_repo_name": "ConnectedSystems/Streamfall.jl", "max_forks_repo_head_hexsha": "37d747e26d58281d21327f20a61e3a86f4369ed4", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8191933241, "max_line_length": 172, "alphanum_fraction": 0.6834612229, "num_tokens": 6269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7614181459658617}}
{"text": "# Based upon alg 1 in\n# A unified sparse optimization framework to learn parsimonious physics-informed models from data\n# by K Champion et. al.\n\nmutable struct SR3{U,T} <: AbstractOptimiser\n    λ::U\n    ν::U\n    R::T\nend\n\nfunction SR3(λ = 1e-1, ν = 1.0)\n    R = NormL1\n    return SR3(λ, ν, R)\nend\n\nfunction set_threshold!(opt::SR3, threshold)\n    opt.λ = threshold^2*opt.ν /2\n    return\nend\n\nget_threshold(opt::SR3) = sqrt(2*opt.λ/opt.ν)\n\ninit(o::SR3, A::AbstractArray, Y::AbstractArray) =  A \\ Y\ninit!(X::AbstractArray, o::SR3, A::AbstractArray, Y::AbstractArray) =  ldiv!(X, qr(A, Val(true)), Y)\n\nfunction fit!(X::AbstractArray, A::AbstractArray, Y::AbstractArray, opt::SR3; maxiter::Int64 = 10)\n    f = opt.R(get_threshold(opt))\n\n    n, m = size(A)\n    W = copy(X)\n\n    # Init matrices\n    P = inv(A'*A+I(m)/(opt.ν))\n    X̂ = A'*Y\n    for i in 1:maxiter\n        # Solve rigde regression\n        X .= P*(X̂+W/(opt.ν))\n        # Add proximal iteration\n        prox!(W, f, X, opt.ν*opt.λ)\n    end\n\n    # This is the effective threshold of the SR3 algorithm\n    # See Unified Framework paper supplementary material S1\n    #η = sqrt(2*opt.λ*opt.ν)\n    X[abs.(X) .< get_threshold(opt)] .= zero(eltype(X))\n    return\nend\n", "meta": {"hexsha": "432be93e11070a0233e5ea06d0f6eb1e826cdca8", "size": 1217, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/optimisers/sr3.jl", "max_stars_repo_name": "DanielParraUnam/DataDrivenDiffEq.jl", "max_stars_repo_head_hexsha": "8e81616be8463983fb0be9cf14f273b49c2a81ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-23T15:35:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-23T15:35:00.000Z", "max_issues_repo_path": "src/optimisers/sr3.jl", "max_issues_repo_name": "AlCap23/DataDrivenDiffEq.jl", "max_issues_repo_head_hexsha": "b5bcf7483641efa54c7c9661e23000f1ac8d0b62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimisers/sr3.jl", "max_forks_repo_name": "AlCap23/DataDrivenDiffEq.jl", "max_forks_repo_head_hexsha": "b5bcf7483641efa54c7c9661e23000f1ac8d0b62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3541666667, "max_line_length": 100, "alphanum_fraction": 0.622021364, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7614181402549326}}
{"text": "#' ---\n#' title: Nonlinear Modelling\n#' ---\n\n#' **Originally Contributed by**: Arpit Bhatia\n\n#' This tutorial provides a breif introduction to nonlinear modelling in JuMP.\n#' For more details and specifics, visit the [JuMP docs](http://www.juliaopt.org/JuMP.jl/stable/nlp/).\n\n#' ## Nonlinear Programs\n#' While we have already seen examples of linear, quadratic and conic programs,\n#' JuMP also supports other general smooth nonlinear (convex and nonconvex) optimization problems.\n\n#' A JuMP model object can contain a mix of linear, quadratic, and nonlinear contraints or objective functions.\n#' Thus, a model object for a nonlinear program is constructed in the same way as before.\n\nusing JuMP, Ipopt\nmodel = Model(optimizer_with_attributes(Ipopt.Optimizer, \"print_level\" => 0));\n\n#' ### Variables\n#' Variables are modelled using the `@variable` macro as usual and\n#' a starting point may be provided by using the `start` keyword argument\n\n@variable(model, x, start = 4)\n@variable(model, y, start = -9.66);\n\n#' ### Parameters\n#' Only in the case of nonlinear models, JuMP offers a syntax for \"parameter\" objects\n#' which can refer to a numerical value.\n\n@NLparameter(model, p == 0.003); # Providing a starting value is necessary for parameters\n@NLparameter(model, l[i = 1:10] == 4 - i); # A collection of parameters\n\n#' The `value` and `set_value` functions are used to query and update the value of a parameter respectively.\n\nvalue(l[1])\n\n#+\n\nset_value(l[1], -4)\nvalue(l[1])\n\n#' Parameters are useful since it's faster to modify a model in-place by changing the value of the parameter\n#' compared to creating an entirely new model object.\n\n#' ### Expressions\n#' JuMP also supports the creation of arithmetic expressions which can then be inserted into\n#' constraints, the objective and other expressions.\n\n@NLexpression(model, expr_1, sin(x))\n@NLexpression(model, expr_2, asin(expr_1)); # Inserting one expression into another\n\n#' There are some [syntax rules](https://pkg.julialang.org/docs/JuMP/DmXqY/0.19.2/nlp/#Syntax-notes-1)\n#' which must be followed while writing a nonlinear expression.\n\n#' Note that JuMP also supports linear and quadratic expression.\n#' You can find out more about this functionality in the [docs](https://pkg.julialang.org/docs/JuMP/DmXqY/0.19.2/expressions/).\n\n#' ### Nonlinear Objectives and Constraints\n#' Nonlinear objectives and constraints are specified by using the `@NLobjective` and `@NLconstraint` macros.\n\n@NLconstraint(model, exp(x) + y^4 <= 0)\n@NLobjective(model, Min, tan(x) + log(y))\n\n#' ### User-defined Functions\n#' In addition to supporting a library of built-in functions,\n#' JuMP supports the creation of user-defined nonlinear functions to use within nonlinear expressions.\n#' The `register` function is used to enable this functionality.\n\nmy_function(a,b) = (a * b)^-6 + (b / a)^3\nregister(model, :my_function, 2, my_function, autodiff = true)\n\n#' The arguements to the function are:\n#' - model for which the function is being registered\n#' - Julia symbol object corresponding to the name of the function\n#' - Number of arguments the function takes\n#' - name of the Julia method\n#' - instruction for JuMP to compute exact gradients automatically\n\n#' ## MLE using JuMP\n\n#' Since we already have a bit of JuMP experience at this point,\n#' let's try a modelling example and apply what we have learnt.\n#' In this example, we compute the maximum likelihood estimate (MLE) of\n#' the parameters of a Gaussian distribution i.e. the sample mean and variance.\n\n#' If $X_{1}, \\ldots, X_{n}$ are an id sample from a population with pdf or pmf\n#' $f\\left(x | \\theta_{1}, \\ldots, \\theta_{k}\\right),$ the likelihood function is defined by\n\n#' $$\n#' L(\\theta | \\mathbf{x})=L\\left(\\theta_{1}, \\ldots, \\theta_{k} | x_{1}, \\ldots, x_{n}\\right)=\\prod_{i=1}^{n} f\\left(x_{i} | \\theta_{1}, \\ldots, \\theta_{k}\\right)\n#' $$\n\n#' For each sample point $\\mathbf{x}$, let $\\hat{\\theta}(\\mathbf{x})$ be a parameter value\n#' at which $L(\\theta | \\mathbf{x})$ attains its maximum as a function of $\\theta,$ with $\\mathbf{x}$ held fixed.\n#' A maximum likelihood estimator (MLE) of the parameter $\\theta$ based on a sample $\\mathbf{X}$ is\n#' $\\hat{\\theta}(\\mathbf{X})$.\n\n#'The Gaussian likelihood is -\n\n#' $$\n#' L(\\theta | \\mathbf{x})=\\prod_{i=1}^{n} \\frac{1}{(2 \\pi)^{1 / 2}} e^{-(1 / 2)\\left(x_{i}-\\theta\\right)^{2}}=\\frac{1}{(2 \\pi)^{n / 2}} e^{(-1 / 2) \\Sigma_{i=1}^{n}\\left(x_{i}-\\theta\\right)^{2}}\n#' $$\n\n#' In most cases, the natural logarithm of\n#' $L(\\theta | \\mathbf{x}), \\log L(\\theta | \\mathbf{x})$ (known as the log likelihood),\n#' is used rather than $L(\\theta | \\mathbf{x})$ directly.\n#' The reason is that the log likelihood is easier to differentiate.\n#' This substituion is possible because the log function is strictly increasing on $(0, \\infty)$,\n#' which implies that the extrema of $L(\\theta | \\mathbf{x})$ and $\\log L(\\theta | \\mathbf{x})$ coincide.\n\nusing Random, Statistics\n\nRandom.seed!(1234)\n\nn = 1_000\ndata = randn(n)\n\nmle = Model(optimizer_with_attributes(Ipopt.Optimizer, \"print_level\" => 0))\n@NLparameter(mle, problem_data[i = 1:n] == data[i])\nμ0 = randn()\nσ0 = rand() + 1\n@info \"Starting guess, mean: $μ0, std: $σ0\"\n@variable(mle, μ, start = μ0)\n@variable(mle, σ >= 0.0, start = σ0)\n@NLexpression(mle, loglikelihood,\n    -(n / 2) * (log(2π) + 2 * log(σ)) - inv(2 * σ^2) * sum((xi - μ)^2 for xi in problem_data)\n)\n\n@NLobjective(mle, Max, loglikelihood)\n\noptimize!(mle)\n\nprintln(\"μ = \", value(μ))\nprintln(\"mean(data) = \", mean(data))\nprintln(\"σ^2 = \", value(σ)^2)\nprintln(\"var(data) = \", var(data))\nprintln(\"MLE value: \", exp(objective_value(mle)))\n\n#+\n\n# Changing the data\n\ndata = randn(n)\noptimize!(mle)\n\nprintln(\"μ = \", value(μ))\nprintln(\"mean(data) = \", mean(data))\nprintln(\"σ^2 = \", value(σ)^2)\nprintln(\"var(data) = \", var(data))\nprintln(\"MLE objective: \", objective_value(mle))\n\n#' ## Writing Convex Models\n\n#' Nonlinear solvers like Ipopt are usually local solvers.\n#' For convex problems, the local optima is also the global optima,\n#' and thus Ipopt is able to provide us with the correct solution.\n#' However, in case a problem is not written in the convex form, then we may be unable to solve it.\n\n#' A tool that helps us in dealing with this issue is [Disciplined Convex Programming](https://dcp.stanford.edu) (DCP).\n#' DCP is a system for constructing mathematical expressions with known curvature from a given library of base functions.\n#' Specifically, it helps us to construct convex optimization models when possible,\n#' i.e. minimize convex function or maximize concave function and use constraints that are convex $f$ <= concave $g$\n", "meta": {"hexsha": "61716af9a2f7c50fa23a155f174168dd15589fae", "size": 6601, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/using_JuMP/nonlinear_modelling.jl", "max_stars_repo_name": "mtanneau/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 75, "max_stars_repo_stars_event_min_datetime": "2020-06-15T13:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T12:58:48.000Z", "max_issues_repo_path": "script/using_JuMP/nonlinear_modelling.jl", "max_issues_repo_name": "mtanneau/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-05-27T05:36:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T09:52:29.000Z", "max_forks_repo_path": "script/using_JuMP/nonlinear_modelling.jl", "max_forks_repo_name": "mtanneau/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-10-09T09:32:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T17:41:21.000Z", "avg_line_length": 40.25, "max_line_length": 194, "alphanum_fraction": 0.7038327526, "num_tokens": 1837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7614181402183016}}
{"text": "\"\"\"Calculates the 2nd order centred gradient in x-direction on any grid (u,v,T or q).\nThe size of dudx must be m-1,n compared to m,n = size(u)\"\"\"\nfunction ∂x!(dudx::Matrix{T},u::Matrix{T}) where {T<:AbstractFloat}\n    m,n = size(dudx)\n    @boundscheck (m+1,n) == size(u) || throw(BoundsError())\n\n    @inbounds for j ∈ 1:n, i ∈ 1:m\n        dudx[i,j] = u[i+1,j] - u[i,j]\n    end\nend\n\n\"\"\"Calculates the 2nd order centred gradient in y-direction on any grid (u,v,T or q).\nThe size of dudy must be m,n-1 compared to m,n = size(u).\"\"\"\nfunction ∂y!(dudy::Array{T,2},u::Array{T,2}) where {T<:AbstractFloat}\n    m,n = size(dudy)\n    @boundscheck (m,n+1) == size(u) || throw(BoundsError())\n\n    @inbounds for j ∈ 1:n, i ∈ 1:m\n            dudy[i,j] = u[i,j+1] - u[i,j]\n    end\nend\n\n\"\"\" ∇² is the 2nd order centred Laplace-operator ∂/∂x^2 + ∂/∂y^2.\nThe 1/Δ²-factor is omitted and moved into the viscosity coefficient.\"\"\"\nfunction ∇²!(du::Matrix{T},u::Matrix{T}) where {T<:AbstractFloat}\n    m, n = size(du)\n    @boundscheck (m+2,n+2) == size(u) || throw(BoundsError())\n\n    @inbounds for j ∈ 1:n\n        for i ∈ 1:m\n            #        1\n            # the 1 -4 1  -stencil in low-precision resilient form\n            #        1\n            ui1j1 = u[i+1,j+1]\n            du[i,j] = ((u[i,j+1] - ui1j1) + (u[i+2,j+1] - ui1j1)) + ((u[i+1,j] - ui1j1) + (u[i+1,j+2] - ui1j1))\n        end\n    end\nend\n\n\"\"\"∂x is the 2nd order centred Gradient-operator ∂/∂x with grid spacing Δ (default 1).\"\"\"\nfunction ∂x(u::Array{T,2},Δx::Real) where {T<:AbstractFloat}\n\n    m,n = size(u)\n\n    dudx = Array{T,2}(undef,m-1,n)\n    one_over_dx = T(1.0/Δx)\n\n\n    @inbounds for j ∈ 1:n\n        for i ∈ 1:m-1\n            dudx[i,j] = one_over_dx*(u[i+1,j] - u[i,j])\n        end\n    end\n\n    return dudx\nend\n\n\"\"\"∂y is the 2nd order centred Gradient-operator ∂/∂y with grid spacing Δ (default 1).\"\"\"\nfunction ∂y(u::Array{T,2},Δy::Real=1) where {T<:AbstractFloat}\n\n    m,n = size(u)\n\n    dudy = Array{T,2}(undef,m,n-1)\n    one_over_dy = T(1.0/Δy)\n\n    @inbounds for j ∈ 1:n-1\n        for i ∈ 1:m\n            dudy[i,j] = one_over_dy*(u[i,j+1] - u[i,j])\n        end\n    end\n\n    return dudy\nend\n\n\"\"\" ∇² is the 2nd order centred Laplace-operator ∂/∂x^2 + ∂/∂y^2 with grid spacing Δ (default 1).\"\"\"\nfunction ∇²(u::Array{T,2},Δ::Real=1) where {T<:AbstractFloat}\n\n    m, n = size(u)\n    du = Array{T,2}(undef,m-2,n-2)\n\n    minus_4 = T(-4.0)\n    one_over_dx² = T(1/Δ^2)\n\n    @inbounds for j ∈ 2:n-1\n        for i ∈ 2:m-1\n            du[i-1,j-1] = one_over_dx²*(minus_4*u[i,j] + u[i,j-1] + u[i,j+1] + u[i-1,j] + u[i+1,j])\n        end\n    end\n    return du\nend", "meta": {"hexsha": "ba696ecb6465f34d829f91dc27f333221604f0bb", "size": 2607, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gradients.jl", "max_stars_repo_name": "milankl/ShallowWaters.jl", "max_stars_repo_head_hexsha": "27f5353a584d0cd4caa5ff1977d54f87ee5b1a67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 57, "max_stars_repo_stars_event_min_datetime": "2020-02-14T08:48:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T01:43:42.000Z", "max_issues_repo_path": "src/gradients.jl", "max_issues_repo_name": "farhadrclass/ShallowWaters.jl", "max_issues_repo_head_hexsha": "27f5353a584d0cd4caa5ff1977d54f87ee5b1a67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-01-23T11:37:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T14:56:52.000Z", "max_forks_repo_path": "src/gradients.jl", "max_forks_repo_name": "farhadrclass/ShallowWaters.jl", "max_forks_repo_head_hexsha": "27f5353a584d0cd4caa5ff1977d54f87ee5b1a67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:44:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T22:03:59.000Z", "avg_line_length": 28.9666666667, "max_line_length": 111, "alphanum_fraction": 0.5481396241, "num_tokens": 1025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.761418140206091}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.3\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ d1f4afa8-2501-4447-96a6-7fb93f463e2c\nusing IterativeSolvers, DataFrames\n\n# ╔═╡ 57c64cca-55ee-4c2b-ad27-2942a262df7b\nmd\" ### Ex-02-08.jl\"\n\n# ╔═╡ c7b3e4fb-8f17-4e0e-82a5-18d30f8b198a\nbegin\n\tA = Float64[\n\t  16 4 8;\n\t  4 5 -4;\n\t  8 -4 22;\n\t]\n\ta = Float64[4; 2; 5]\n\tr = vcat(collect(1:6), collect(10:10:100))\nend;\n\n# ╔═╡ 21a0af0a-7873-45f5-bd59-31c43cbb0f0c\nmd\" ##### Jacobi method:\"\n\n# ╔═╡ 137e76a3-ea70-49e0-a1f7-a2eadaac9963\nx_j = [(i=i, j=jacobi(A, a; maxiter=i)) for i in r]\n\n# ╔═╡ 31d9aa57-e96b-409b-b1ab-9e5966af6bf5\nx_j[1]\n\n# ╔═╡ 70d35d30-1798-4982-9b9e-3812a575d179\nA * x_j[11].j\n\n# ╔═╡ 954c3dec-86ad-4a29-9528-a790a9ebf2c0\nmd\" ##### Gauss-Seidel method:\"\n\n# ╔═╡ 53491c26-f5d1-48d0-a795-7c20a31b00df\nx_gs = [(i=i, gs=gauss_seidel(A, a; maxiter=i)) for i in r]\n\n# ╔═╡ b2a3e4de-cd59-466a-9872-f72e78bb91ba\nA * x_gs[11].gs\n\n# ╔═╡ df81e70f-ec63-4be6-8517-d962b315dc0f\nmd\" ##### Succesive Over-Relaxation method:\"\n\n# ╔═╡ cebd114d-8a7c-44c0-bbca-e39b124a263e\nx_sor = [(i=i, sor=sor(A, a, 1.0; maxiter=i)) for i in r]\n\n# ╔═╡ 9b86fca1-6867-4c70-b7a2-6e648bbfc26e\nA * x_sor[11].sor\n\n# ╔═╡ c1dd5a8b-5256-410f-9abc-58afd36cb1af\nmd\" ##### Sequential Succesive Over-Relaxation method:\"\n\n# ╔═╡ 09fd7541-fe59-435b-8f6d-73b72b0c01f0\nx_ssor = [(i=i, ssor=ssor(A, a, 1.0; maxiter=i)) for i in r]\n\n# ╔═╡ 96d4ef12-7a35-47c5-a255-5056e582e618\nA * x_ssor[11].ssor\n\n# ╔═╡ Cell order:\n# ╟─57c64cca-55ee-4c2b-ad27-2942a262df7b\n# ╠═d1f4afa8-2501-4447-96a6-7fb93f463e2c\n# ╠═c7b3e4fb-8f17-4e0e-82a5-18d30f8b198a\n# ╟─21a0af0a-7873-45f5-bd59-31c43cbb0f0c\n# ╠═137e76a3-ea70-49e0-a1f7-a2eadaac9963\n# ╠═31d9aa57-e96b-409b-b1ab-9e5966af6bf5\n# ╠═70d35d30-1798-4982-9b9e-3812a575d179\n# ╟─954c3dec-86ad-4a29-9528-a790a9ebf2c0\n# ╠═53491c26-f5d1-48d0-a795-7c20a31b00df\n# ╠═b2a3e4de-cd59-466a-9872-f72e78bb91ba\n# ╟─df81e70f-ec63-4be6-8517-d962b315dc0f\n# ╠═cebd114d-8a7c-44c0-bbca-e39b124a263e\n# ╠═9b86fca1-6867-4c70-b7a2-6e648bbfc26e\n# ╟─c1dd5a8b-5256-410f-9abc-58afd36cb1af\n# ╠═09fd7541-fe59-435b-8f6d-73b72b0c01f0\n# ╠═96d4ef12-7a35-47c5-a255-5056e582e618\n", "meta": {"hexsha": "191e5a5277df97db1c13e71760a02d53c4733d71", "size": 2105, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/02/ex-02-08.jl", "max_stars_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_stars_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "notebooks/02/ex-02-08.jl", "max_issues_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "notebooks/02/ex-02-08.jl", "max_forks_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 26.3125, "max_line_length": 60, "alphanum_fraction": 0.7016627078, "num_tokens": 1280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7614181383512895}}
{"text": "# Load X and y variable\r\nusing JLD\r\ndata = load(\"nonLinear.jld\")\r\n(X,y,Xtest,ytest) = (data[\"X\"],data[\"y\"],data[\"Xtest\"],data[\"ytest\"])\r\n\r\n# Compute number of training examples and number of features\r\n(n,d) = size(X)\r\n\r\ndisplay(size(X))\r\n\r\nntrain = Int(floor(n/2))\r\n\r\nXtrain = X[1:ntrain, :]\r\nytrain = y[1:ntrain, :]\r\nXvalidate = X[ntrain+1:n, :]\r\nyvalidate = y[ntrain+1:n, :]\r\n\r\ndisplay(size(Xtrain))\r\ndisplay(size(Xvalidate))\r\n\r\n# Fit least squares model\r\n#include(\"leastSquares.jl\")\r\n#model = leastSquares(X,y)\r\n\r\n\r\nbestError = 10000000000000000\r\nbestl = 0\r\nbestsigma = 0\r\n\r\ninclude(\"leastSquaresRBFL2.jl\")\r\n\r\n# Find best l, sigma values\r\nfor l = 0:0.1:3\r\n  for sigma = 0.1:0.1:3\r\n\t\tmodel = leastSquaresRBFL2(Xtrain,ytrain,l, sigma)\r\n\r\n\t\t# Report the error on the validation set\r\n\t\tt = size(Xvalidate,1)\r\n\t\tyhat = model.predict(Xvalidate)\r\n\t\tvalidationError = sum((yhat - yvalidate).^2)/t\r\n\t\t@printf(\"l = %f, sigma = %f, ValidationError = %.2f\\n\", l, sigma, validationError)\r\n    if validationError < bestError\r\n      bestError = validationError\r\n      bestl = l\r\n      bestsigma = sigma\r\n    end\r\n  end\r\nend\r\n\r\n@printf(\"Best validation l = %f, sigma = %f, error = %f\", bestl, bestsigma, bestError)\r\n\r\nmodel = leastSquaresRBFL2(X,y,bestl,bestsigma)\r\n\r\n# Report the error on the test set\r\nt = size(Xtest,1)\r\nyhat = model.predict(Xtest)\r\ntestError = sum((yhat - ytest).^2)/t\r\n@printf(\"l = %f, sigma = %f, TestError = %.2f\\n\", bestl, bestsigma, testError)\r\n\r\n\r\n# Plot model\r\nusing PyPlot\r\nfigure()\r\nplot(X,y,\"b.\")\r\nplot(Xtest,ytest,\"g.\")\r\nXhat = minimum(X):.1:maximum(X)\r\nXhat = reshape(Xhat,length(Xhat),1) # Make into an n by 1 matrix\r\nyhat = model.predict(Xhat)\r\nplot(Xhat,yhat,\"r\")\r\nylim((-300,400))\r\nshow()\r\n", "meta": {"hexsha": "0cff3df4dfcdbad80637eb4cf8353b247c4dd568", "size": 1713, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "a1sol/example_nonLinear.jl", "max_stars_repo_name": "d4l3k/cs540", "max_stars_repo_head_hexsha": "049617af46048b5471877b9bdfb0bd8a65f3cf0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "a1sol/example_nonLinear.jl", "max_issues_repo_name": "d4l3k/cs540", "max_issues_repo_head_hexsha": "049617af46048b5471877b9bdfb0bd8a65f3cf0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "a1sol/example_nonLinear.jl", "max_forks_repo_name": "d4l3k/cs540", "max_forks_repo_head_hexsha": "049617af46048b5471877b9bdfb0bd8a65f3cf0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7916666667, "max_line_length": 87, "alphanum_fraction": 0.6444833625, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798115, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7614181383146584}}
{"text": "# This script provides implementations of\n# multi-step methods of different orders\n# for assessing their performance on a test\n# equation y' = λ y\n\nprintln('\\n', \" \"^4, \"> Loading the packages...\")\n\nusing Printf\n\n# Define the value of λ\nconst λ = -1.5\n\n# Integrate the test equation using the\n# Euler's method, return the value of the\n# solution at the last step\nfunction euler(\n    y₀::F,\n    h::F,\n    n::I,\n)::F where\n{F <: AbstractFloat,I <: Unsigned}\n    # Prepare a buffer for the solution\n    y = y₀\n    # Compute the solution\n    for _ in 1:n\n        y += h * λ * y\n    end\n    return y\nend\n\n# Integrate the test equation using the\n# two-step Adams–Bashforth's method, return\n# the value of the solution at the last step\nfunction ab2(\n    y₀::F,\n    h::F,\n    n::I,\n)::F where\n{F <: AbstractFloat,I <: Unsigned}\n    # Prepare a buffer for the solution\n    y = y₀\n    # Prepare a buffer for previous values\n    yₖ₋₁ = y₀\n    # Compute the second value of the solution\n    # using the one-step Euler's method\n    y = euler(y₀, h, UInt(1))\n    # Compute the rest in two steps\n    for _ in 2:n\n        k = y\n        y += h * λ * (3 / 2 * y - 1 / 2 * yₖ₋₁)\n        yₖ₋₁ = k\n    end\n    return y\nend\n\n\n# Integrate the test equation using the\n# 4th order Runge-Kutta's method, return\n# the value of the solution at the last step\nfunction rk4(\n    y₀::F,\n    h::F,\n    n::I,\n)::F where\n{F <: AbstractFloat,I <: Unsigned}\n    # Prepare a buffer for the solution\n    y = y₀\n    # Compute the rest in two steps\n    for _ in 1:n\n        k₁ = λ * y\n        k₂ = λ * (y + h * k₁ / 2)\n        k₃ = λ * (y + h * k₂ / 2)\n        k₄ = λ * (y + h * k₃)\n        y += h / 6 * (k₁ + 2 * k₂ + 2 * k₃ + k₄)\n    end\n    return y\nend\n\n# Integrate the test equation using the\n# three-step Adams–Bashforth's method\n# (with Euler's method as the starter),\n# return the value of the solution at\n# the last step\nfunction ab3_euler(\n    y₀::F,\n    h::F,\n    n::I,\n)::F where\n{F <: AbstractFloat,I <: Unsigned}\n    # Prepare a buffer for the solution\n    y = y₀\n    # Prepare buffers for previous values\n    yₖ₋₁ = y₀\n    yₖ₋₂ = y₀\n    # Compute the second value of the solution\n    # using the one-step Euler's method\n    y = euler(y₀, h, UInt(1))\n    # Compute the third value of the solution\n    # using the two-step Adams–Bashforth's method\n    yₖ₋₁ = y\n    y = ab2(y₀, h, UInt(2))\n    # Compute the rest in two steps\n    for _ in 3:n\n        k = y\n        y += h * λ * (23 / 12 * y - 4 / 3 * yₖ₋₁ + 5 / 12 * yₖ₋₂)\n        yₖ₋₂ = yₖ₋₁\n        yₖ₋₁ = k\n    end\n    return y\nend\n\n# Integrate the test equation using the\n# three-step Adams–Bashforth's method\n# (with 4th order Runge-Kutta's method as the\n# starter), return the value of the solution\n# at the last step\nfunction ab3_rk4(\n    y₀::F,\n    h::F,\n    n::I,\n)::F where\n{F <: AbstractFloat,I <: Unsigned}\n    # Prepare a buffer for the solution\n    y = y₀\n    # Prepare buffers for previous values\n    yₖ₋₁ = y₀\n    yₖ₋₂ = y₀\n    # Compute the second and third values of the solution\n    # using the 4th-order Runge-Kutta's method\n    yₖ₋₁ = rk4(y₀, h, UInt(1))\n    y = rk4(y₀, h, UInt(2))\n    # Compute the rest in two steps\n    for _ in 3:n\n        k = y\n        y += h * λ * (23 / 12 * y - 4 / 3 * yₖ₋₁ + 5 / 12 * yₖ₋₂)\n        yₖ₋₂ = yₖ₋₁\n        yₖ₋₁ = k\n    end\n    return y\nend\n\nprintln(\" \"^4, \"> Integrating the test equation...\")\n\n# Define the initial values of the position and velocity\ny₀ = 1.0\n\n# Calculate the analytical solution\nyₐ = ℯ^λ\n\n# Print the initial values\nprintln(\n    '\\n',\n    \" \"^6, \"y₀: \", y₀,\n)\n\n# Define the output directories\nconst data_dir = \"$(@__DIR__)/../data/test\"\nconst files = joinpath.(\n    data_dir,\n    [\n        \"euler.dat\",\n        \"ab2.dat\",\n        \"rk4.dat\",\n        \"ab3_euler.dat\",\n        \"ab3_rk4.dat\",\n    ]\n)\n\n# Prepare a list of methods\nconst methods = (euler, ab2, rk4, ab3_euler, ab3_rk4)\n\n# Integrate the test equation using all available\n# methods and write the values of the solutions\n# on the last step\nfunction integrate(h::Vector{F}, n::Vector{I}) where {F <: AbstractFloat,I <: Unsigned}\n    # Open the data files\n    io = open.(files, \"a\")\n\n    # Prepare results vectors\n    y = [ Vector{F}() for _ in 1:length(io) ]\n    Δy = [ Vector{F}() for _ in 1:length(io) ]\n\n    # For each pair of parameters\n    for i in eachindex(h)\n        # Integrate and get the results of the last steps\n        for j in eachindex(io)\n            yᵢ = methods[j](y₀, h[i], n[i])\n            Δyᵢ = abs(yₐ - yᵢ)\n            push!(y[j], yᵢ)\n            push!(Δy[j], Δyᵢ)\n        end\n    end\n\n    # Get the format string based on the index of the iteration\n    function get_format(i)\n        Printf.Format(\n            \"\\$ 10^{-$(length(\"$(n[i])\") - 1)} \\$ \" *\n            \"& \\$ $(n[i] % 10 == 0 ? \"10^$(length(\"$(n[i])\") - 1)\" : n[i]) \\$ \" *\n            \"& \\$ %.14f \\$ \" *\n            \"& \\$ %.14f \\$ \" *\n            \"\\\\\\\\\\n\"\n        )\n    end\n\n    # Print the data in the files in the LaTeX format\n\n    for j in eachindex(io)\n        println(io[j], \"# Solution\")\n        for i in eachindex(h)\n            Printf.format(io[j], get_format(i), y[j][i], Δy[j][i])\n        end\n    end\nend\n\n# Truncate the previous results\nopen.(files; truncate=true)\n\n# Integrate n = 2^m iterations\nintegrate(\n    [1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7],\n    UInt.([ 10^i for i in 2:7 ]),\n)\n\nprintln()\n", "meta": {"hexsha": "e85da4b0d7d7c59acabef0a80df2c9d74bd3463f", "size": 5351, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Adam's/scripts/test.jl", "max_stars_repo_name": "paveloom-university/Computer-Methods-of-Celestial-Mechanics-S09-2021", "max_stars_repo_head_hexsha": "a650c76d6f299c20bbe82e98dd0708ef97a35f65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Adam's/scripts/test.jl", "max_issues_repo_name": "paveloom-university/Computer-Methods-of-Celestial-Mechanics-S09-2021", "max_issues_repo_head_hexsha": "a650c76d6f299c20bbe82e98dd0708ef97a35f65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Adam's/scripts/test.jl", "max_forks_repo_name": "paveloom-university/Computer-Methods-of-Celestial-Mechanics-S09-2021", "max_forks_repo_head_hexsha": "a650c76d6f299c20bbe82e98dd0708ef97a35f65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7822222222, "max_line_length": 87, "alphanum_fraction": 0.5651280135, "num_tokens": 1808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7614181364476461}}
{"text": "module kMeansClustering\n\nfunction squared_euclidean_distance(v::Array{Float64},w::Array{Float64})\n    dist = 0\n    for d in 1:length(v)\n        dist+= (v[d]-w[d])^2\n    end\n    return dist\nend\n\nfunction agroup(matrix::Matrix{Float64})\n    l = [Float64[]]\n    pop!(l)\n    dim,n_points = size(matrix)\n    for p in 1:n_points\n        v = Float64[]\n        for d in 1:dim\n            push!(v,matrix[dim*(p-1)+d])\n        end\n        push!(l,v)\n    end\n    return l,dim\nend\n\nfunction compare_distance(p::Array{Float64,1},old_ctr::Array{Float64,1},new_ctr::Array{Float64,1})\n    old_dist = squared_euclidean_distance(p,old_ctr)\n    new_dist = squared_euclidean_distance(p,new_ctr)\n    if new_dist<=old_dist\n        return new_ctr\n    end\n    return old_ctr\nend\n\n\nfunction dic(l::Array{Array{Float64,1},1},centers::Array{Array{Float64,1},1})\n    dic_centers = Dict()\n    for ctr in centers\n        dic_centers[ctr] = [Float64[]]\n        pop!(dic_centers[ctr])\n    end\n    for p in l\n        center = centers[1]\n        for ctr in centers\n            center = compare_distance(p,center,ctr)\n        end\n        c = dic_centers[center]\n        push!(c,p)\n        dic_centers[center] = c\n    end\n    return dic_centers\nend\n\nfunction reorganize(clusters::Array{Array{Array{Float64,1},1},1},dim::Int64)\n    centers = [Float64[]]\n    pop!(centers)\n    for cluster in clusters\n        s = zeros(dim)\n        for p in cluster\n            for n in 1:dim\n                s[n]+= p[n]\n            end\n        end\n        means = Float64[]\n        for d in s\n            push!(means,d/length(cluster))\n        end\n        push!(centers,means)\n    end\n    return centers\nend\n\nfunction cost(dic_centers::Dict{Any,Any})\n    cst = 0\n    for (centr,clus) in dic_centers\n        for p in clus\n            cst+=squared_euclidean_distance(p,centr)\n        end\n    end\n    return cst\nend\n\nfunction assign(clusters::Array{Array{Array{Float64,1},1},1},l::Array{Array{Float64,1},1})\n    dic_assign = Dict()\n    for n in 1:length(clusters)\n        for el in clusters[n]\n            dic_assign[el] = n\n        end\n    end\n    l_assign = Int64[]\n    for p in l\n        push!(l_assign,dic_assign[p])\n    end\n    return l_assign\nend\n\nfunction new_format(centers::Array{Array{Float64,1},1})\n    new = hcat(centers[1],centers[2])\n    for p in centers[3:length(centers)]\n        new = hcat(new,p)\n    end\n    return new\nend\n\nfunction build_clusters(dic_centers::Dict{Any,Any})\n    clusters = [[Float64[]]]\n    pop!(clusters)\n    for (center,cluster) in dic_centers\n        push!(clusters,cluster)\n    end\n    return clusters\nend\n\nfunction mykmeansclustering(matrix::Matrix{Float64},k::Int64)\n    l,dim = agroup(matrix)\n    centers = [Float64[]]\n    pop!(centers)\n    while length(unique(centers))<k\n        centers = rand(l,k) # Forgy Method\n    end\n    initials = centers\n    cop = [Float64[]]\n    pop!(cop)\n    while centers!=cop\n        dic_centers = dic(l,centers)\n        cop = centers[1:k]\n        clusters = build_clusters(dic_centers)\n        centers = reorganize(clusters,dim)\n    end\n    dic_centers = dic(l,centers)\n    clusters = build_clusters(dic_centers)\n    cst = cost(dic_centers)\n    assignment = assign(clusters,l)\n    centers = new_format(centers)\n    initials = new_format(initials)\n    return centers,cst,assignment,initials\nend\n\nexport mykmeansclustering\nend\n", "meta": {"hexsha": "8c8ceee5517b1fbefaf95b024734209b15ec2f9d", "size": 3342, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kMeansClustering.jl", "max_stars_repo_name": "PHamacher/kMeansClustering.jl", "max_stars_repo_head_hexsha": "5f13b53a625a76ffbe7d37b8b78c4ff0312c73af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kMeansClustering.jl", "max_issues_repo_name": "PHamacher/kMeansClustering.jl", "max_issues_repo_head_hexsha": "5f13b53a625a76ffbe7d37b8b78c4ff0312c73af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kMeansClustering.jl", "max_forks_repo_name": "PHamacher/kMeansClustering.jl", "max_forks_repo_head_hexsha": "5f13b53a625a76ffbe7d37b8b78c4ff0312c73af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8714285714, "max_line_length": 98, "alphanum_fraction": 0.6131059246, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7614181268805895}}
{"text": "using ControlSystems, RobustAndOptimalControl\nusing Plots\n\n\"\"\"\nThis is a simple SISO example which was used for debugging the implementation,\nas this exact example was use in the lecture notes of the \"Principles of Optimal\nControl\" cours of the MIT OpenCourseWare [1], however, this example is in discrete time\n\n[1] https://ocw.mit.edu/courses/aeronautics-and-astronautics/16-323-principles-of-optimal-control-spring-2008/lecture-notes/lec15.pdf\n\nThe example can be set to visualize and save plots using the two variables\n  makeplots - true/false (true if plots are to be generated, false for testing)\n\"\"\"\nmakeplots = true\n\n# Define the process\nts = 0.005\nGd = bilinearc2d(ss(tf([200], [0.025,1.0025,10.1,1])),ts)\n\n# Sensitivity weight function\nM, wB, A = 1.5, 10, 1e-4\nWS = tf([1/M, wB],[1, wB*A])\n\n# Output sensitivity weight function\nWU = ss(0.1)\n\n# Complementary sensitivity weight function\nWT = []\n\n# Create continuous time approximation of the process\nGc = bilineard2c(ss(Gd))\n\n# Form augmented P dynamics in state-space\nPc = hinfpartition(Gc, WS, WU, WT)\n\n# Check that the assumptions are satisfied\nflag = hinfassumptions(Pc)\n\n# Synthesize the H-infinity optimal controller\nflag, Cc, γ = hinfsynthesize(Pc)\n\n# Extract the transfer functions defining some signals of interest, but do so\n# using discrete equivalent of the continuous time objects Pc, Cc and Gc\nPcl, S, CS, T = hinfsignals(\n  bilinearc2d(Pc, ts),\n  bilinearc2d(Gc, ts),\n  bilinearc2d(Cc, ts)\n)\n\n# Visualize results\nif makeplots\n  specificationplot([S, CS, T], [WS, WU, WT], γ)\n  specificationplot(Pcl, γ; s_labels=[\"\\$\\\\sigma(P_{cl}(j\\\\omega))\\$\"], w_labels=[\"\\$\\\\gamma\\$\"])\nend\n", "meta": {"hexsha": "715a03e83526c65413447e966e483eed2c0022cf", "size": 1650, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/hinf_example_MIT_discrete.jl", "max_stars_repo_name": "ven-k/RobustAndOptimalControl.jl", "max_stars_repo_head_hexsha": "fdc9ec8e13a95be903357c51359216511d5e03ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2021-04-19T04:51:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T07:56:20.000Z", "max_issues_repo_path": "examples/hinf_example_MIT_discrete.jl", "max_issues_repo_name": "ven-k/RobustAndOptimalControl.jl", "max_issues_repo_head_hexsha": "fdc9ec8e13a95be903357c51359216511d5e03ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-05-15T09:05:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T19:25:31.000Z", "max_forks_repo_path": "examples/hinf_example_MIT_discrete.jl", "max_forks_repo_name": "ven-k/RobustAndOptimalControl.jl", "max_forks_repo_head_hexsha": "fdc9ec8e13a95be903357c51359216511d5e03ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-09-07T06:22:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T08:15:01.000Z", "avg_line_length": 30.0, "max_line_length": 133, "alphanum_fraction": 0.7345454545, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7613891189843413}}
{"text": "\"\"\"\n    autocor(x,lag)\n\nReturns autocorrelation function for a distance of lag, i.e. between values of\n```x[t]``` and ```x[t+lag]```. The autocorrelation function is normalized such\nthat ```autocor(x,0) = 1```. This is equvivalent to the quantity\n``\\\\Gamma_X(t)`` of equation (4.61) in [Gattringer/Lang](@cite).\n\"\"\"\nfunction autocor(x, lag)\n    # (wasteful in terms of allocations but clear)\n    z = x .- mean(x)\n    a = sum(z[1+lag:end].*z[1:end-lag])/sum(z.*z)\n    return a\nend\n\"\"\"\n    autocor(x)\n\nReturns autocorrelation function for a set of lags from ``0`` up to the closest\ninteger to ``10 \\\\text{log}_{10}(l)``. Here ``l`` is the number of elements in\n```x```.\n\"\"\"\nfunction autocor(x)\n    lx   = length(x)\n    lags = collect(0:min(lx-1, round(Int,10*log10(lx))))\n    a = zeros(eltype(x),length(lags))\n    for i in 1:length(lags)\n        a[i] = autocor(x, lags[i])\n    end\n    return a\nend\n\"\"\"\n    autotimeexp(x)\n\nReturns ``\\\\max(1,\\\\tau)`` where ``\\\\tau`` is the exponential autocorrelation\ntime of a series of measurements ``x``. This is obtained by fitting the\nautocorrelation function to an exponential function of the form\n``A \\\\exp(\\\\frac{t}{\\\\tau})``.\n\"\"\"\nfunction autotimeexp(O)\n    a = autocor(O)\n    @. modelτ(x,p) = abs.(p[2])*exp(-x/p[1])\n    x = collect(1:length(a))\n    c = curve_fit(modelτ, x, a, ones(2))\n    τ = c.param[1]\n    return max(one(τ),τ)\nend\n", "meta": {"hexsha": "37132f5b6cd37a81c5e74642aa4ff3ecb7416e99", "size": 1375, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/statistics.jl", "max_stars_repo_name": "briederer/LatSpec.jl", "max_stars_repo_head_hexsha": "0160bac1a5d58095b8890dcecc54cd640b443d1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-22T12:30:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T12:30:03.000Z", "max_issues_repo_path": "src/statistics.jl", "max_issues_repo_name": "gazfaris/LatSpec.jl", "max_issues_repo_head_hexsha": "c979622ff412ccbe25c386bab712665df667f023", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2021-05-23T20:00:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-25T15:45:12.000Z", "max_forks_repo_path": "src/statistics.jl", "max_forks_repo_name": "briederer/LatSpec.jl", "max_forks_repo_head_hexsha": "0160bac1a5d58095b8890dcecc54cd640b443d1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-23T20:44:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T18:37:18.000Z", "avg_line_length": 29.2553191489, "max_line_length": 79, "alphanum_fraction": 0.6225454545, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7613891172965639}}
{"text": "#=\n\n  https://edu.swi-prolog.org/mod/assign/view.php?id=249\n  \"\"\"\n  Medical diagnosis\n\n  Develop an expert system for medical diagnosis.\n\n  Consider three diseases: flu, gastroenteritis and bronchitis.\n\n  A priori, flu has probability 0.3, gastroenteritis 0 0.2, and bronchitis 0.25.\n\n  If you have the flu, you may have the following symptons, associated with their\n  probabilities (symptoms are not mutually exclusive):\n\n    fever, 0.8\n    cough 0.6\n    sore throat 0.5\n    headaches 0.4\n    aches 0.7\n\n  If you have gastroenteritis, you may have the following symptons, associated with their\n  probabilities (symptoms are not mutually exclusive):\n\n    diarrhea 0.8\n    aches 0.7\n    nausea 0.4\n    fatigue 0.3\n\n  If you have bronchitis, you may have the following symptons, associated with their probabilities\n  (symptoms are not mutually exclusive):\n\n    cough 0.8\n    fatigue 0.7\n    fever 0.3\n\n  Compute the probability of each disease given that the patient has the symptoms fever and aches.\n\n  Do the same supposing the patient adds that he also experiences fatigue.\n  \"\"\"\n\n  Cf ~/cplint/course_medical_diagnosis.pl\n     ~/blog/medical_diagnosis.blog\n     ~/psi/medical_diagnosis.psi\n     ~/webppl/medical_diagnosis.wppl\n\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n\n@model function medical_diagnosis()\n    #=\n      Consider three diseases: flu, gastroenteritis and bronchitis.\n\n      A priori, flu has probability 0.3, gastroenteritis 0.2, and bronchitis 0.25.\n    =#\n\n    flu ~ flip(0.3)\n    gastroenteritis ~ flip(0.2)\n    bronchitis ~ flip(0.25)\n\n    #=\n      If you have the flu, you may have the following symptons, associated with their\n      probabilities (symptoms are not mutually exclusive):\n\n      fever, 0.8\n      cough 0.6\n      sore throat 0.5\n      headaches 0.4\n    aches 0.7\n    =#\n\n    fever ~ flu ? flip(0.8) : ( bronchitis ? flip(0.3) : flip(0.0))\n    cough ~ flu ? flip(0.6) : ( bronchitis ? flip(0.8) : flip(0.0))\n    sore_throat ~ flu ? flip(0.5) : flip(0.0)\n    headaches ~ flu ? flip(0.4) : flip(0.0)\n    aches ~ flu ? flip(0.7) : (gastroenteritis ? flip(0.7) : flip(0.0))\n\n    #=\n      If you have gastroenteritis, you may have the following symptons, associated with their\n      probabilities (symptoms are not mutually exclusive):\n\n      diarrhea 0.8\n      aches 0.7\n      nausea 0.4\n      fatigue 0.3\n    =#\n\n    diarrhea ~ gastroenteritis ? flip(0.8) : flip(0.0)\n    nausea  ~ gastroenteritis ? flip(0.4) : flip(0.0)\n    fatigue ~ gastroenteritis ? flip(0.3) : ( bronchitis ? flip(0.7) : flip(0.0))\n\n    #=\n      If you have bronchitis, you may have the following symptons, associated with their probabilities\n      (symptoms are not mutually exclusive):\n\n      cough 0.8\n      fatigue 0.7\n      fever 0.3\n    =#\n    cough ~ bronchitis ? flip(0.8) : flip(0.0)\n    fatigue ~ bronchitis ? flip(0.7) : flip(0.0)\n    fever ~ bronchitis ? flip(0.3) : flip(0.0)\n\n    # The observations\n    true ~ Dirac(fever)\n    true ~ Dirac(aches)\n\nend\n\nmodel = medical_diagnosis()\nnum_chns = 4\n\n# HH has problem with this!\n# chns = sample(model, MH(), MCMCThreads(), 10_000, num_chns)\n# chns = sample(model, MH(), 40_000)\n\n# chns = sample(model, PG(20), MCMCThreads(), 1000, num_chns)\nchns = sample(model, SMC(1000), MCMCThreads(), 10_000, num_chns)\n\n# Note: IS don't generate chns the same way as MH, PG, and SMC!\n# chns = sample(model, IS(), MCMCThreads(), 1000, num_chns)\n\ndisplay(chns)\n\nshow_var_dist_pct(chns,:flu)\nshow_var_dist_pct(chns,:gastroenteritis)\nshow_var_dist_pct(chns,:bronchitis)\n", "meta": {"hexsha": "a8190f4f8f832eac83486195499e61ba96807662", "size": 3538, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/medical_diagnosis.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/medical_diagnosis.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/medical_diagnosis.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 27.0076335878, "max_line_length": 102, "alphanum_fraction": 0.6701526286, "num_tokens": 1122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7613891134467542}}
{"text": "\nexport\npoint_contained,\npoint_contained!\n\n\n\"\"\"\npoint_contained(simplex::ST, point::Vector{VT}) where {T <: AbstractSimplex, VT}\n\nCheck if `point` is contained in the interior of `simplex`.\n\nThe `point` is contained within `simplex` if it can be expressed as a\nconvex combination of the vertices of `simplex`. To check this condition,\nwe iteratively check the signed volume of a modified simplex. Specifically,\nat the i-th iteration step, substitute the i-th vertex of `simplex` with\n`point` and take the signed volume when when one vertex is substituted.\nIn the next step, replace the substitated vertex by the original, then\nreplace the (i + 1)th vertex by `point` and repeat the process.\nIf any two consecutive signs are different, the point is not contained.\n\nWhen the point is very close to the edge of a simplex, numerical accuracies\nwill play a role, so the function sometimes (very rarely) puts `point` inside\n`simplex`.\n\"\"\"\nfunction point_contained(simplex::T, point::Vector{VT}) where {T <: AbstractSimplex, VT}\n    dim = dimension(simplex)\n\n    # The signs of the linear combination coefficients\n    coefficient_signs = zeros(Float64, dim + 1)\n\n    # A temporary simplex into which we substitute `point`\n    temp_simplex = MutableSimplex([zeros(Float64, dim) for i = 1:(dim + 1)])\n\n    # Using the temporary simplex, replace the the first vertex by `point`\n    # and fill the remaining vertices with the original `simplex` vertices.\n    temp_simplex[1] = point\n    [temp_simplex[i] = simplex[i] for i = 2:(dim + 1)]\n\n    # The signed volume of the simplex\n    coefficient_signs[1] = sign(orientation(temp_simplex))\n\n    # Iteratively replace the other vertices and see if the signed\n    # volume changes. It it does, the point can not be expressed as a\n    # convex combination of the vertices of `simplex`.\n    for κ = 2:dim\n\n        # Replace the i-th vertex of the temporary simplex with `point`\n        temp_simplex[κ] = point\n\n        # Replace the remaining vertices of the temporary simplex\n        # with the original vertices\n        remaining_vertex_idxs = setdiff(1:(dim + 1), κ)\n        [temp_simplex[i] = simplex[i] for i in remaining_vertex_idxs]\n\n        # Check the signed volume and stop if it has changed.\n        coefficient_signs[κ] = sign(orientation(temp_simplex))\n\n        if !(coefficient_signs[κ-1] == coefficient_signs[κ])\n            return false\n        end\n    end\n\n    # Check when replacing the last point.\n    temp_simplex[end] = point\n    [temp_simplex[i] = simplex[i] for i = 1:dim]\n\n    coefficient_signs[end] = sign(orientation(temp_simplex))\n\n    if !(coefficient_signs[end-1] == coefficient_signs[end])\n        return false\n    else\n        return true\n    end\nend\n\n\"\"\"\n    point_contained!(temp_simplex::MutableSimplex, simplex::ST, point::Vector{VT}) where {T <: AbstractSimplex, VT}\n\nCheck if `point` is contained in the interior of `simplex`.\n\nThe `point` is contained within `simplex` if it can be expressed as a\nconvex combination of the vertices of `simplex`. To check this condition,\nwe iteratively check the signed volume of a modified simplex. Specifically,\nat the i-th iteration step, substitute the i-th vertex of `simplex` with\n`point` and take the signed volume when when one vertex is substituted.\nIn the next step, replace the substitated vertex by the original, then\nreplace the (i + 1)th vertex by `point` and repeat the process.\nIf any two consecutive signs are different, the point is not contained.\n\nWhen the point is very close to the edge of a simplex, numerical accuracies\nwill play a role, so the function sometimes (very rarely) puts `point` inside\n`simplex`.\n\"\"\"\nfunction point_contained!(temp_simplex::MutableSimplex, simplex::T, point::Vector{VT}) where {T <: AbstractSimplex, VT}\n    dim = dimension(simplex)\n\n    # The signs of the linear combination coefficients\n    coefficient_signs = zeros(Float64, dim + 1)\n\n    # Using the temporary simplex, replace the the first vertex by `point`\n    # and fill the remaining vertices with the original `simplex` vertices.\n    temp_simplex[1] = point\n    [temp_simplex[i] = simplex[i] for i = 2:(dim + 1)]\n\n    # The signed volume of the simplex\n    coefficient_signs[1] = sign(orientation(temp_simplex))\n\n    # Iteratively replace the other vertices and see if the signed\n    # volume changes. It it does, the point can not be expressed as a\n    # convex combination of the vertices of `simplex`.\n    for κ = 2:dim\n\n        # Replace the i-th vertex of the temporary simplex with `point`\n        temp_simplex[κ] = point\n\n        # Replace the remaining vertices of the temporary simplex\n        # with the original vertices\n        remaining_vertex_idxs = setdiff(1:(dim + 1), κ)\n        [temp_simplex[i] = simplex[i] for i in remaining_vertex_idxs]\n\n        # Check the signed volume and stop if it has changed.\n        coefficient_signs[κ] = sign(orientation(temp_simplex))\n\n        if !(coefficient_signs[κ-1] == coefficient_signs[κ])\n            return false\n        end\n    end\n\n    # Check when replacing the last point.\n    temp_simplex[end] = point\n    [temp_simplex[i] = simplex[i] for i = 1:dim]\n\n    coefficient_signs[end] = sign(orientation(temp_simplex))\n\n    if !(coefficient_signs[end-1] == coefficient_signs[end])\n        return false\n    else\n        return true\n    end\nend\n", "meta": {"hexsha": "8abbcd7166664555168b7f329626d6cce1cd6487", "size": 5314, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Discretization/TriangulationPartitions/Simplices/point_contained_in_simplex.jl", "max_stars_repo_name": "JuliaDynamics/StateSpaceReconstruction.jl", "max_stars_repo_head_hexsha": "d53dff4be52a319d435631768ac0560333629996", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-15T14:27:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T00:08:07.000Z", "max_issues_repo_path": "src/Discretization/TriangulationPartitions/Simplices/point_contained_in_simplex.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StateSpaceReconstruction.jl-1441a9f6-6a74-5418-a591-cdf1d78a07f0", "max_issues_repo_head_hexsha": "acb3f9705c6786c8db08a9841cfbe9ec8be0aec9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2018-04-23T20:14:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-01T13:36:05.000Z", "max_forks_repo_path": "src/Discretization/TriangulationPartitions/Simplices/point_contained_in_simplex.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StateSpaceReconstruction.jl-1441a9f6-6a74-5418-a591-cdf1d78a07f0", "max_forks_repo_head_hexsha": "acb3f9705c6786c8db08a9841cfbe9ec8be0aec9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:03:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:03:06.000Z", "avg_line_length": 37.6879432624, "max_line_length": 119, "alphanum_fraction": 0.7054949191, "num_tokens": 1328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.7613639285616944}}
{"text": "using Revise\nusing AdFem\nusing PyPlot\n\nn = 20\nmmesh = Mesh(n, n, 1/n, degree=2)\nbdedge = bcedge((x1,y1,x2,y2)->((y1<1e-5) && (y2<1e-5)), mmesh)\nbdnode = bcnode((x,y)->!(y<1e-5 && x>1e-5 && x<1-1e-5), mmesh)\n\nF1 = eval_f_on_gauss_pts((x,y)->3.0, mmesh)\nF2 = eval_f_on_gauss_pts((x,y)->-1.0, mmesh)\nF = compute_fem_source_term(F1, F2, mmesh)\n\nt1 = eval_f_on_boundary_edge((x,y)->-x-y, bdedge, mmesh)\nt2 = eval_f_on_boundary_edge((x,y)->2y, bdedge, mmesh)\nT = compute_fem_traction_term(t1, t2, bdedge, mmesh)\n\nD = constant(diagm(0=>[1,1,0.5]))\nK = compute_fem_stiffness_matrix(D, mmesh)\nrhs = T - F \nbdval = [eval_f_on_boundary_node((x,y)->x^2+y^2, bdnode, mmesh);\n        eval_f_on_boundary_node((x,y)->x^2-y^2, bdnode, mmesh)]\nDOF = [bdnode;bdnode .+ mmesh.ndof]\nK, rhs = impose_Dirichlet_boundary_conditions(K, rhs, DOF, bdval)\nu = K\\rhs \nsess = Session(); init(sess)\nS = run(sess, u)\n\n\nfigure(figsize=[10,4])\nsubplot(121)\nvisualize_scalar_on_fem_points(S[1:mmesh.nnode], mmesh)\nsubplot(122)\nvisualize_scalar_on_fem_points(S[mmesh.ndof+1:mmesh.ndof + mmesh.nnode], mmesh)\nsavefig(\"numerical.png\")\n\nfigure(figsize=[10,4])\nx = LinRange(0, 1, 50)\nX = zeros(50, 50)\nY = zeros(50, 50)\nfor i = 1:50\n    for j = 1:50\n        X[i,j] = x[i]\n        Y[i,j] = x[j]\n    end\nend\nsubplot(121)\nX = mmesh.nodes[:,1]\nY = mmesh.nodes[:,2]\nU = (@. X^2+Y^2)\nV = (@. X^2-Y^2)\nsubplot(121)\nvisualize_scalar_on_fem_points(U, mmesh)\nsubplot(122)\nvisualize_scalar_on_fem_points(V, mmesh)\nsavefig(\"exact.png\")\n\n\n\nfigure(figsize=[10,4])\nsubplot(121)\nvisualize_scalar_on_fem_points(U-S[1:mmesh.nnode], mmesh)\nsubplot(122)\nvisualize_scalar_on_fem_points(V-S[mmesh.ndof+1:mmesh.ndof + mmesh.nnode], mmesh)\nsavefig(\"difference.png\")", "meta": {"hexsha": "7303deba6289e02f56549833ca453f427b749733", "size": 1701, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/codes/LinearElasticity/unstructured_forward.jl", "max_stars_repo_name": "kailaix/AdFem.jl", "max_stars_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2020-10-18T01:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:13:24.000Z", "max_issues_repo_path": "docs/src/codes/LinearElasticity/unstructured_forward.jl", "max_issues_repo_name": "kailaix/AdFem.jl", "max_issues_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-10-19T03:51:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:38:46.000Z", "max_forks_repo_path": "docs/src/codes/LinearElasticity/unstructured_forward.jl", "max_forks_repo_name": "kailaix/AdFem.jl", "max_forks_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-11-05T11:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T19:30:09.000Z", "avg_line_length": 26.1692307692, "max_line_length": 81, "alphanum_fraction": 0.6796002352, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7613639282886714}}
{"text": "# 泡利算符\r\n\r\nconst σ0 = [1 0; 0 1]\r\nconst σx = [0 1; 1 0]\r\nconst σy = [0 -im; im 0]\r\nconst σz = [1 0; 0 -1]\r\nconst σv = σx + σy + σz\r\n\r\n\"\"\"\r\n    ⊗(x::AbstractVector, y::AbstractVector)\r\n张量积\r\n\"\"\"\r\n⊗(x::AbstractVector, y::AbstractVector) = begin\r\n    T = promote_type(eltype(x), eltype(y))\r\n    lx = length(x)\r\n    ly = length(y)\r\n    z = zeros(T, lx * ly)\r\n    for i = 1:lx\r\n        for j = 1:ly\r\n            z[(i-1)*ly+j] = x[i] * y[j]\r\n        end\r\n    end\r\n    return z\r\nend\r\n\r\n\"\"\"\r\n    ⊗(x::AbstractMatrix, y::AbstractMatrix)\r\n张量积\r\n\"\"\"\r\n⊗(x::AbstractMatrix, y::AbstractMatrix) = begin\r\n    T = promote_type(eltype(x), eltype(y))\r\n    xrows, xcols = size(x)\r\n    yrows, ycols = size(y)\r\n    z = zeros(T, xrows * yrows, xcols * ycols)\r\n    for xj = 1:xcols\r\n        for yj = 1:ycols\r\n            for xi = 1:xrows\r\n                for yi = 1:yrows\r\n                    z[(xi-1)*yrows+yi, (xj-1)*ycols+yj] = x[xi, xj] * y[yi, yj]\r\n                end\r\n            end\r\n        end\r\n    end\r\n    return z\r\nend", "meta": {"hexsha": "89a9696e09d0b3d0cfa0c1264b33c895a81124f9", "size": 1004, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pauli.jl", "max_stars_repo_name": "0382/MyTools.jl", "max_stars_repo_head_hexsha": "b2bb04347cea7f0564fc0d5e00c62142b31baebc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pauli.jl", "max_issues_repo_name": "0382/MyTools.jl", "max_issues_repo_head_hexsha": "b2bb04347cea7f0564fc0d5e00c62142b31baebc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pauli.jl", "max_forks_repo_name": "0382/MyTools.jl", "max_forks_repo_head_hexsha": "b2bb04347cea7f0564fc0d5e00c62142b31baebc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3111111111, "max_line_length": 80, "alphanum_fraction": 0.4741035857, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7613639265299623}}
{"text": "\"\"\"\n    circular_layout(g) -> x, y\n\nReturn two vectors representing the positions of the nodes of graph `g` \nwhen placed on the unit circonference of radius one centered at the origin.\n\"\"\"\nfunction circular_layout(g::AGraphOrDiGraph)\n    # Discard the extra angle since it matches 0 radians.\n    θ = range(0, stop=2pi, length=nv(g)+1)[1:end-1]\n    return cos.(θ), sin.(θ)\nend\n\n\"\"\"\n    spring_layout(g; \n                  k = 1 / √nv(g),\n                  maxiter = 100,\n                  inittemp = 2.0,\n                  [x0, y0]) -> x, y\n\nReturn the positions of the nodes in graph `g` according to \nFruchterman and Reingold's spring/repulsion model.\nThe forces as function of the distance `d` beetween two nodes \nare given by\n\n    f_a(d) =  d / k # attractive force\n    f_r(d) = -k^2 / d^2 # repulsive force:  \n\n`maxiter` is the number of updates of the positions. \n`inittemp` controls displacement per iteration.\n\nInitial positions can passed though the argument `x0` and `y0`.\n\nThe positions are rescaled to fit the [-1, +1]^2 box. \n\nThis function is adapted from [GraphLayout.jl](https://github.com/IainNZ/GraphLayout.jl).\n\"\"\"\nfunction spring_layout(g::AGraphOrDiGraph;\n                       x0 = 2*rand(nv(g)) .- 1.0,\n                       y0 = 2*rand(nv(g)) .- 1.0,\n                       k = 1/√nv(g),\n                       maxiters = 100,\n                       inittemp = 2.0)\n\n    x = copy(x0)\n    y = copy(y0)\n    nvg = nv(g)\n    adj_matrix = adjacency_matrix(g)\n    k² = k * k\n\n    # Store forces and apply at end of iteration all at once\n    force_x = zeros(nvg)\n    force_y = zeros(nvg)\n\n    # Iterate MAXITER times\n    @inbounds for iter = 1:maxiters\n        # Calculate forces\n        for i = 1:nvg\n            force_vec_x = 0.0\n            force_vec_y = 0.0\n            for j = 1:nvg\n                i == j && continue\n                d_x = x[j] - x[i]\n                d_y = y[j] - y[i]\n                dist²  = (d_x * d_x) + (d_y * d_y)\n                dist = sqrt(dist²)\n\n                if !(iszero(adj_matrix[i,j]) && iszero(adj_matrix[j,i]) )\n                    # Attractive + repulsive force\n                    # F_d = dist² / k - k² / dist # original FR algorithm\n                    F_d = dist / k - k² / dist²\n                else\n                    # Just repulsive\n                    # F_d = -k² / dist  # original FR algorithm\n                    F_d = -k² / dist²\n                end\n                force_vec_x += F_d * d_x\n                force_vec_y += F_d * d_y\n            end\n            force_x[i] = force_vec_x\n            force_y[i] = force_vec_y\n        end\n        # Cool down\n        temp = inittemp / iter\n        # Now apply them, but limit to temperature\n        for i = 1:nvg\n            fx = force_x[i]\n            fy = force_y[i]\n            force_mag  = sqrt((fx * fx) + (fy * fy))\n            scale      = min(force_mag, temp) / force_mag\n            x[i] += force_x[i] * scale\n            y[i] += force_y[i] * scale\n        end\n    end\n\n    # Scale to unit square\n    min_x, max_x = minimum(x), maximum(x)\n    min_y, max_y = minimum(y), maximum(y)\n    function scaler(z, a, b)\n        2.0*((z - a) / (b - a)) - 1.0\n    end\n    map!(z -> scaler(z, min_x, max_x), x, x)\n    map!(z -> scaler(z, min_y, max_y), y, y)\n\n    return x, y\nend\n\n\"\"\"\n    shell_layout(g, nlist) -> x, y\n\nPosition the nodes of `g` in concentric circles.\n\n`nlist` is a vector of vectors containing the nodes\nfor each shell.\n\"\"\"\nfunction shell_layout(g::AGraphOrDiGraph, nlist::Vector{Vector{T}}) where T<:Integer\n    if nv(g) == 1\n        return [0.0], [0.0]\n    end\n    radius = length(nlist[1]) > 1 ? 1.0 : 0.0\n    x = Float64[]\n    y = Float64[]\n    for nodes in nlist\n        θ = range(0, stop=2pi, length=length(nodes)+1)[1:end-1]\n        append!(x, radius * cos.(θ))\n        append!(y, radius * sin.(θ))\n        radius += 1.0\n    end\n    return x, y\nend\n\n", "meta": {"hexsha": "1e3014d4d8e859a844941bcf54c50b2c1527425b", "size": 3890, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/drawing/layout.jl", "max_stars_repo_name": "CarloLucibello/Erdos.jl", "max_stars_repo_head_hexsha": "59da367cb19e0cf2b4cbc686367695caf255f857", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2017-02-24T15:54:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T19:59:23.000Z", "max_issues_repo_path": "src/drawing/layout.jl", "max_issues_repo_name": "CarloLucibello/Erdos.jl", "max_issues_repo_head_hexsha": "59da367cb19e0cf2b4cbc686367695caf255f857", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 76, "max_issues_repo_issues_event_min_datetime": "2017-02-23T09:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T09:10:31.000Z", "max_forks_repo_path": "src/drawing/layout.jl", "max_forks_repo_name": "CarloLucibello/FatGraphs.jl", "max_forks_repo_head_hexsha": "59da367cb19e0cf2b4cbc686367695caf255f857", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-03-04T21:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:54:44.000Z", "avg_line_length": 29.6946564885, "max_line_length": 89, "alphanum_fraction": 0.5200514139, "num_tokens": 1146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7613639263479469}}
{"text": "export UpdateColley\n\n\"\"\"\n    UpdateColley\n\n Colley update rule, e.g., see \"Whos's #1\", Langville and Meyer, p.21\n\n## Parameters (none)\n```\n\"\"\"\nstruct UpdateColley <: UpdateRule\n# this is a batch calculation that takes no account of past ratings, and\n# has no parameters\nend\n\nfunction update_info( rule::UpdateColley )\n    info = Dict(\n                :name => \"Colley\",\n                :reference => \"\\\"Whos's #1\\\", Langville and Meyer, p.21\",\n                :computation => \"simultaneous\",\n                :state_model => \"none\",\n                :input => \"outcome\",\n                :output => \"deterministic\",\n                :model => \"single\",\n                :ties => false,\n                :factors => false,\n                :parameters => [],\n                :record => false\n                )\n    return info\nend\nupdate_info( ::Type{UpdateColley} ) =  update_info( UpdateColley() )\n\nfunction update_ratings( rule::UpdateColley,\n                         input_ratings::RatingsList,\n                         input_competitions::DataFrame)\n    n = size(input_competitions,1)\n    m = length( input_ratings.players )\n    I = player_indexes( input_ratings.players )\n    \n    # construct Colley matrices and vectors\n    C = diagm(0 => 2*ones(Int,m))\n    wins = zeros(Int, m)\n    losses = zeros(Int, m)\n    d = input_competitions\n    for i=1:n\n        if d[i,Outcome] == 1\n            wins[I[d[i,PlayerA]]] += 1\n            losses[I[d[i,PlayerB]]] += 1\n        elseif d[i,Outcome] == -1\n            wins[I[d[i,PlayerB]]] += 1\n            losses[I[d[i,PlayerA]]] += 1\n        end\n        C[ I[d[i,PlayerA]], I[d[i,PlayerB]] ] -= 1\n        C[ I[d[i,PlayerB]], I[d[i,PlayerA]] ] -= 1\n        C[ I[d[i,PlayerA]], I[d[i,PlayerA]] ] += 1\n        C[ I[d[i,PlayerB]], I[d[i,PlayerB]] ] += 1\n    end\n\n    # solve Colley's equation\n    b = 1 .+ 0.5*(wins .- losses)\n    r = C \\ b\n    ratings = Dict{String, Float64}()\n    for player in input_ratings.players\n        ratings[player] = r[ I[player] ]\n    end\n        \n    # output ratings list\n    output_ratings = RatingsList(input_ratings.players, ratings )   \n    return output_ratings\nend\n\n# Colley's predictions are deterministic, unless you apply some model after the fact\nfunction predict_outcome(rule::UpdateColley,\n                         ratingA::Real, ratingB::Real, \n                         factorA::Union{Missing,Real}, factorB::Union{Missing,Real})\n    rating_diff = ratingA - ratingB\n    s = sign(rating_diff)\n    if s==1\n        return (1.0, 0.0, 0.0)\n    elseif s==-1\n        return (0.0, 1.0, 0.0)\n    else\n        return (0.0, 0.0, 1.0)\n    end\nend\n", "meta": {"hexsha": "aa96c83f235ace27b0df5cc0ee9500d31aae10a1", "size": 2609, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/UpdateRules/Colley.jl", "max_stars_repo_name": "JuliaTagBot/RatPack.jl", "max_stars_repo_head_hexsha": "44d5735c1bbfaa97b12d3f418b0e1c4b967da1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/UpdateRules/Colley.jl", "max_issues_repo_name": "JuliaTagBot/RatPack.jl", "max_issues_repo_head_hexsha": "44d5735c1bbfaa97b12d3f418b0e1c4b967da1df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-08T16:23:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T16:23:16.000Z", "max_forks_repo_path": "src/UpdateRules/Colley.jl", "max_forks_repo_name": "JuliaTagBot/RatPack.jl", "max_forks_repo_head_hexsha": "44d5735c1bbfaa97b12d3f418b0e1c4b967da1df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:20:51.000Z", "avg_line_length": 29.9885057471, "max_line_length": 84, "alphanum_fraction": 0.5415868149, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7613639229215361}}
{"text": "using Plots, LaTeXStrings, Statistics\n\nfunction Deposition(;len, tot_time, time_steps)\n    Time = ceil.(Int, exp.(2:(tot_time-2)/(time_steps):tot_time))\n    surf = [0 for i=1:len]\n    VarList = [0.0 for i=1:time_steps]\n    for n in 2:time_steps+1\n        randsurf = rand(1:len,(Time[n]-Time[n-1]))\n        for i in randsurf\n            MAX = FindMax(surf, i, len)\n            surf[i] = MAX\n        end\n        VarList[n-1] = std(surf)\n    end\n    return VarList\nend\n\nfunction sides(n, L)\n    if n == L\n        return n-1 , 1\n    elseif n == 1\n        return L , n+1\n    else\n        return n-1, n+1\n    end\nend\n\nfunction FindMax(surface, index_,L_surf)\n    i1 , i2 = sides(index_, L_surf)\n    maxlen = max(surface[i1],surface[index_] + 1,surface[i2])\n    return maxlen\nend\n\nfunction Linear_fit(;Time, VarList, time_steps)\n    A = [hcat(log.(Time[1:time_steps])) reshape(ones(time_steps), time_steps, 1)]\n    b = reshape(log.(VarList[1:time_steps]), time_steps, 1)\n    line = (A \\ b)\n    return line\nend\n\n# function FindLine(tot_steps, Time, VarList)\n#     retline = [0.0 0.0]\n#     for i in 5:tot_steps\n#         Paraline = Dict(\n#                         :Time => Time,\n#                         :VarList => VarList,\n#                         :time_steps => i\n#                             )\n#         Line = Linear_fit(;Paraline...)\n#         absl = abs(Line[1]*Time[i] + Line[2] - VarList[i])\n#         standev = std(Line[1].*Time .+ Line[2] .- VarList)\n#         if absl > 0.2 && standev > 1 && retline == [0.0 0.0]\n#             retline = Line\n#         end\n#         if absl > 1 && standev > 3\n#             return retline, i\n#         end\n#     end\n# end\n\ntheme(:dark)\ngr()\n\n\niternum = 1000\nParameters = Dict(:len => 200,\n                    :tot_time => 13,\n                        :time_steps => 50)\nallVar = [ [0.0 for i in 1:Parameters[:time_steps]] for j = 1:iternum]\nmeanVar = [0.0 for i in 1:Parameters[:time_steps]]\nvars = [0.0 for i in 1:Parameters[:time_steps]]\nfor i in 1:iternum\n    VarList = Deposition(;Parameters...)\n    allVar[i] = VarList\n    meanVar += VarList\n    print(\"\\r$i\")\nend\nmeanVar /= iternum\nfor i in 1:Parameters[:time_steps]\n    vars[i] = std(log.(hcat(allVar...))[i,:])\nend\n\nTime = exp.(0:(Parameters[:tot_time])/(Parameters[:time_steps]-1):Parameters[:tot_time])\nscatter(log.(Time[3:end]), log.(meanVar[3:end]),\n    # xlims = (1, Parameters[:tot_time]),\n    xlabel= L\"Log\\ Time\",\n    ylabel= L\"Log\\ W_{(t)}\",\n    title= L\"Log-Log\\ Plot\\ ~W_{(t)}-Time~\\ (L = %$(Parameters[:len]))\",\n    label = L\"Data\\ point\",\n    yerror = vars,\n    legend = 150)\n\nParaline = Dict(\n                :Time => Time[3:end],\n                :VarList => meanVar[3:end],\n                :time_steps => 13)\nLine = Linear_fit(;Paraline...)\nX = log.(Time[3]:Time[30])\nY = X .* Line[1] .+ Line[2]\n\nplot!(X,Y,label = L\"y = %$(round(Line[1],digits= 2))x + %$(round(Line[2],digits= 2))\")\n\nsavefig(\"C:\\\\Users\\\\Yaghoub\\\\Documents\\\\GitHub\\\\Ballistic-Deposition\\\\Deposition\\\\Ballistic-Deposition-Kardar-Parisi-Zhang\\\\Fig\\\\W-t(L=$(Parameters[:len])).png\")\n", "meta": {"hexsha": "cb6d7d5b27484de55da379d64171f5a9ed82685a", "size": 3059, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Deposition/Ballistic-Deposition-Kardar-Parisi-Zhang/KPZ-BD-Logarithmic.jl", "max_stars_repo_name": "shahmari/Ballistic-Deposition", "max_stars_repo_head_hexsha": "0d6e52c2320cc023e2c351205236c82e371a71d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-29T12:35:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T12:35:39.000Z", "max_issues_repo_path": "Deposition/Ballistic-Deposition-Kardar-Parisi-Zhang/KPZ-BD-Logarithmic.jl", "max_issues_repo_name": "shahmari/Ballistic-Deposition", "max_issues_repo_head_hexsha": "0d6e52c2320cc023e2c351205236c82e371a71d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Deposition/Ballistic-Deposition-Kardar-Parisi-Zhang/KPZ-BD-Logarithmic.jl", "max_forks_repo_name": "shahmari/Ballistic-Deposition", "max_forks_repo_head_hexsha": "0d6e52c2320cc023e2c351205236c82e371a71d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4134615385, "max_line_length": 161, "alphanum_fraction": 0.5521412226, "num_tokens": 994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.76136391719037}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 5057c590-c5a4-11eb-2621-4b67f12ca95d\nmd\"\"\"\n# K Nearest Neighbors\n\"\"\"\n\n# ╔═╡ 74f4afa1-dd5a-4931-ab48-a1d4fc77bbe5\nmd\"\"\"\n[Reference 1](https://scikit-learn.org/stable/modules/neighbors.html)\\\n[Reference 2](https://en.wikipedia.org/wiki/Nearest_neighbor_search)\\\n[Reference 3](https://booking.ai/k-nearest-neighbours-from-slow-to-fast-thanks-to-maths-bec682357ccd)\n\n### Naive Approach\n\nNo transforming on original dataset (No training)\\\nFor prediction, iter through the original dataset, and find the nearest K data, by a given metrics\n\n\nCan use euclidean distance:\n\n$$\\text{dist}(X_1, X_2) = \\|X_1 - X_2\\|$$\n\nA better approach is cosine similarity:\n\n$$\\text{sim}(X_1, X_2) = \\frac{X_1 \\cdot X_2}{\\|X_1\\| \\|X_2\\|}$$\n\nwhich computes the cos value between two vectors\\\n1 for 0 degree, and less than 1 for $(0, \\pi]$\n\"\"\"\n\n# ╔═╡ cb1dd9ac-ca78-4169-b073-943f64160dbc\nmodule tools include(\"../tools.jl\") end\n\n# ╔═╡ f1fa76da-f656-4f12-97d7-a8b847ca0733\nJuTools = tools.JuTools\n\n# ╔═╡ c3ad6021-8080-4870-8350-1337d548f23a\nimport Statistics\n\n# ╔═╡ 83864e6e-4b62-45d5-962e-39e36bbcc43d\nimport Random\n\n# ╔═╡ 0d7f31a9-7ae2-4be5-81b2-313ac58af62d\nimport LinearAlgebra\n\n# ╔═╡ 73b4e7e0-7294-46dc-9545-9728277df652\nfunction cosine_sim(X1::Array{T} where T<:Number, X2::Array{T} where T<:Number)::AbstractFloat\n    @assert size(X1) == size(X2)\n    @assert ndims(X1) == ndims(X2) == 1\n    product = LinearAlgebra.dot(X1, X2)\n    X1_norm = LinearAlgebra.norm(X1, 2)\n    X2_norm = LinearAlgebra.norm(X2, 2)\n    return product / (X1_norm * X2_norm)\nend\n\n# ╔═╡ 19b1c000-6fa3-42b7-9fc7-983c7caf44b9\nbegin\nX_data, Y_data = JuTools.data_generate_linear_2d()\nsize(X_data), size(Y_data)\nend\n\n# ╔═╡ 063389c7-07b6-4050-9241-ea953c4f4338\nX_data[1:2, :]\n\n# ╔═╡ cf291226-c0a1-4206-a8cb-53bedb67b139\ncosine_sim(X_data[1, :], X_data[2, :])\n\n# ╔═╡ fbf7a012-dcf8-498f-ad29-ec8c4854406c\ncosine_sim(X_data[1, :], X_data[3, :])\n\n# ╔═╡ 2cf4e990-f788-44e3-94cc-9e210e47c762\n# define majority vote function\nfunction majority_vote(y::Array{T} where T<:Number)::Number\n    @assert ndims(y) == 1\n    unique_votes = Dict{Number, Integer}()\n    for y_val in y\n        if !haskey(unique_votes, y_val)\n            push!(unique_votes, y_val => 1)\n        else\n            unique_votes[y_val] += 1\n        end\n    end\n    result = sort(collect(unique_votes), by=m->m[2])\n    return result[end][1]\nend\n\n# ╔═╡ c9d27318-5e3d-4c9c-9ba5-556c649baaf9\nmajority_vote([1,1,0])\n\n# ╔═╡ ba24b3c5-f350-4774-a018-9acf1f4597ad\nmd\"\"\"\nOutput ordering is affected by input ordering\n\"\"\"\n\n# ╔═╡ 5e564f3b-1bda-41b1-8b22-bdf6d91314d2\nmajority_vote([1,1,0,0])\n\n# ╔═╡ ed575b52-7509-4140-b5e7-295920f73e3d\nmajority_vote([1,1,0,0,0])\n\n# ╔═╡ 8406faec-66f4-46aa-9582-964ebdbecfba\nbegin\nX_train, X_test, Y_train, Y_test = JuTools.split_data(X_data, Y_data, shuffle=true, ratio=0.3)\nsize(X_train), size(X_test), size(Y_train), size(Y_test)\nend\n\n# ╔═╡ 3001da4a-3288-4168-b514-c0b12f552fdd\n# define predict function, naive approach\nfunction predict_naive(X_predict::Array{T} where T<:Number, K::Integer, X_data::Array{T} where T<:Number, Y_data::Array{T} where T<:Number)::Array\n    @assert ndims(X_data) == 2\n    @assert ndims(Y_data) == 1\n    @assert size(X_data)[1] == size(Y_data)[1]\n    @assert 0 < ndims(X_predict) <= 2\n    @assert 0 < K < size(X_data)[1]\n    if ndims(X_predict) < 2\n        X_predict = reshape(X_predict, (1, size(X_predict)[1]))\n    end\n    @assert size(X_predict)[2] == size(X_data)[2]\n    result = Array{Number}(undef, size(X_predict)[1])\n    sim = Array{Tuple{Integer, AbstractFloat}}(undef, size(X_data)[1])\n    for i in 1:size(X_predict)[1]\n        vec_predict = X_predict[i, :]\n        for j in 1:size(X_data)[1]\n            vec_data = X_data[j, :]\n            vec_similarity = cosine_sim(vec_predict, vec_data)\n            sim[j] = (j, vec_similarity)\n        end\n        sort!(sim, by=m->m[2], rev=true)\n        K_nearest_votes = Y_data[[m[1] for m in sim[1:K]]]\n        result[i] = majority_vote(K_nearest_votes)\n    end\n    return result\nend\n\n# ╔═╡ 30320c6e-7ada-41b6-a938-f1fd19cc120a\nY_predict = predict_naive(X_test, 5, X_train, Y_train)\n\n# ╔═╡ 27b26afb-a91c-47c4-94ef-1d64761f291d\nJuTools.compute_accuracy(Y_predict, Y_test)\n\n# ╔═╡ 0e1b5c16-f444-41dd-9e44-999969ba647c\n# what about dist similarity?\nfunction dist_sim(X1::Array{T} where T<:Number, X2::Array{T} where T<:Number)::AbstractFloat\n    @assert size(X1) == size(X2)\n    @assert ndims(X1) == ndims(X2) == 1\n    return sqrt(sum((X1 .- X2).^2))\nend\n\n# ╔═╡ c42f2b8a-a88d-4e8c-a1c0-1a371ae6a669\ndist_sim(X_data[1, :], X_data[2, :])\n\n# ╔═╡ 158f77bf-2eb8-490a-a062-6364a6ec70e9\ndist_sim(X_data[2, :], X_data[3, :])\n\n# ╔═╡ 323e10a0-c68f-433a-afc5-0ac2514a90d1\nmd\"\"\"\nIt's greatly affected by the scale of data!\n\"\"\"\n\n# ╔═╡ 52010e3f-2e4f-4778-b53e-4fad04dd75bf\nfunction predict_naive_fun(X_predict::Array{T} where T<:Number, K::Integer, X_data::Array{T} where T<:Number, Y_data::Array{T} where T<:Number)::Array\n    @assert ndims(X_data) == 2\n    @assert ndims(Y_data) == 1\n    @assert size(X_data)[1] == size(Y_data)[1]\n    @assert 0 < ndims(X_predict) <= 2\n    @assert 0 < K < size(X_data)[1]\n    if ndims(X_predict) < 2\n        X_predict = reshape(X_predict, (1, size(X_predict)[1]))\n    end\n    @assert size(X_predict)[2] == size(X_data)[2]\n    result = Array{Number}(undef, size(X_predict)[1])\n    sim = Array{Tuple{Integer, AbstractFloat}}(undef, size(X_data)[1])\n    for i in 1:size(X_predict)[1]\n        vec_predict = X_predict[i, :]\n        for j in 1:size(X_data)[1]\n            vec_data = X_data[j, :]\n            vec_similarity = dist_sim(vec_predict, vec_data)\n            sim[j] = (j, vec_similarity)\n        end\n        sort!(sim, by=m->m[2])\n        K_nearest_votes = Y_data[[m[1] for m in sim[1:K]]]\n        result[i] = majority_vote(K_nearest_votes)\n    end\n    return result\nend\n\n# ╔═╡ 36ceae2a-4c04-4f67-9a6d-19a44cb2fa5b\nJuTools.compute_accuracy(predict_naive_fun(X_test, 5, X_train, Y_train), Y_test)\n\n# ╔═╡ 2c7f7263-5ba0-4786-8b68-8ca8fb3ffc26\nmd\"\"\"\nAlthough it (`predict_naive`) may be slow on large dataset, it is easy to implement and it works as expected\n\"\"\"\n\n# ╔═╡ b2aac2a9-cf86-44f0-ae97-b2a52327b0f9\nmd\"\"\"\n### K-Dimensional Tree (K-d tree) Approach\n\nA space partitioning technique\\\nTreat each data row as a point in `k`-dimensional space\\\n[Wikipedia](https://en.wikipedia.org/wiki/K-d_tree)\n\"\"\"\n\n# ╔═╡ b127297e-cb0c-46f5-8551-3ba2c4dae4c6\nmutable struct KdTree\n    X_data::Array{T} where T<:Number # 1d vector\n    Y_data::Number                   # number\n    child_l::Union{KdTree,Nothing}\n    child_r::Union{KdTree,Nothing}\nend\n\n# ╔═╡ c3c4fe2c-6e92-4c98-bce3-e77f394c405d\n# K-d tree generator function\nfunction create_kdtree(X_data::Array{T} where T<:Number, Y_data::Array{T} where T<:Number)::KdTree\n    @assert ndims(X_data) == 2\n    @assert ndims(Y_data) == 1\n    @assert size(X_data)[1] == size(Y_data)[1]\n    function kdtree_recursive_generate(X_data::Array, Y_data::Array, depth::Integer, n_axes::Integer)::KdTree\n        curr_axis = mod(depth, n_axes) + 1 # array starts from 1\n        data_combined = hcat(X_data, Y_data)\n        data_combined = sortslices(data_combined, by=m->m[curr_axis], dims=1)\n        X_data = data_combined[:, 1:end-1]\n        Y_data = data_combined[:, end]\n        i_mid = div(size(X_data)[1], 2) + 1\n        node_X_data = X_data[i_mid, :]\n        node_Y_data = Y_data[i_mid]\n        node = KdTree(node_X_data, node_Y_data, nothing, nothing)\n        if i_mid > 1\n            node.child_l = kdtree_recursive_generate(X_data[1:i_mid-1,:], Y_data[1:i_mid-1], depth+1, n_axes)\n        end\n        if i_mid < size(X_data)[1]\n            node.child_r = kdtree_recursive_generate(X_data[i_mid+1:end,:], Y_data[i_mid+1:end], depth+1, n_axes)\n        end\n        return node\n    end\n    return kdtree_recursive_generate(X_data, Y_data, 0, size(X_data)[2])\nend\n\n# ╔═╡ a76dcf16-060e-4ece-9b8d-76c45deb38c4\nkdtree = create_kdtree(X_data, Y_data)\n\n# ╔═╡ 4c3444dd-f2cb-4954-8dad-d2e9466252e8\nkdtree_test = create_kdtree(reshape([30,5,10,70,50,35], (6, 1)), [1,1,1,1,1,1])\n\n# ╔═╡ 94c43601-cff7-4c7f-a116-8a82aefed5b0\n# inspired from https://stackoverflow.com/questions/1627305/nearest-neighbor-k-d-tree-wikipedia-proof/37107030#37107030\n# note that for kdtree search, we use euclidean distance\nfunction predict_kdtree(X_predict::Array{T} where T<:Number, kdtree::KdTree; K::Integer=5)::Array\n    @assert K > 0\n    @assert 0 < ndims(X_predict) <= 2\n    if ndims(X_predict) == 1\n        X_predict = reshape(X_predict, (1, size(X_predict)[1]))\n    end\n    @assert size(X_predict)[2] == size(kdtree.X_data)[1]\n\n    function kdtree_closest_max(kdtree_closest::Array{Union{KdTree, Nothing}},\n                kdtree_closest_val::Array{AbstractFloat})::Tuple{Integer, AbstractFloat}\n        default = (0, 0.0)\n        for i in 1:size(kdtree_closest)[1]\n            if kdtree_closest[i] === nothing\n                break\n            elseif default[1] == 0 || (kdtree_closest_val[i] > default[2])\n                default = (i, kdtree_closest_val[i])\n            end\n        end\n        return default\n    end\n    \n    function kdtree_update_nearest!(X_vec::Array, kdtree::KdTree, kdtree_closest::Array{Union{KdTree, Nothing}},\n                kdtree_closest_val::Array{AbstractFloat})\n        @assert size(kdtree_closest) == size(kdtree_closest_val)\n        distance = dist_sim(kdtree.X_data, X_vec)\n        if nothing in kdtree_closest\n            for i in 1:size(kdtree_closest)[1]\n                if kdtree_closest[i] === nothing\n                    kdtree_closest[i] = KdTree(kdtree.X_data, kdtree.Y_data, nothing, nothing)\n                    kdtree_closest_val[i] = distance\n                    break\n                end\n            end\n        else\n            curr_max = kdtree_closest_max(kdtree_closest, kdtree_closest_val)\n            if distance < curr_max[2]\n                kdtree_closest[curr_max[1]] = KdTree(kdtree.X_data, kdtree.Y_data, nothing, nothing)\n                kdtree_closest_val[curr_max[1]] = distance\n            end\n        end\n    end\n    \n    function kdtree_recursive_search!(X_vec::Array, kdtree::KdTree, depth::Integer, n_axes::Integer, \n                kdtree_closest::Array{Union{KdTree, Nothing}}, kdtree_closest_val::Array{AbstractFloat})\n        @assert size(kdtree_closest) == size(kdtree_closest_val)\n        # check current node\n        kdtree_update_nearest!(X_vec, kdtree, kdtree_closest, kdtree_closest_val)\n        # run on children\n        curr_axis = mod(depth, n_axes) + 1 # array starts from 1\n        if X_vec[curr_axis] < kdtree.X_data[curr_axis]\n            if kdtree.child_l !== nothing\n                kdtree_recursive_search!(X_vec, kdtree.child_l, depth+1, n_axes, kdtree_closest, kdtree_closest_val)\n            end\n            if (X_vec[curr_axis] + kdtree_closest_max(kdtree_closest, kdtree_closest_val)[2] >= kdtree.X_data[curr_axis]) && kdtree.child_r !== nothing\n                kdtree_recursive_search!(X_vec, kdtree.child_r, depth+1, n_axes, kdtree_closest, kdtree_closest_val)\n            end\n        else\n            if kdtree.child_r !== nothing\n                kdtree_recursive_search!(X_vec, kdtree.child_r, depth+1, n_axes, kdtree_closest, kdtree_closest_val)\n            end\n            if (X_vec[curr_axis] - kdtree_closest_max(kdtree_closest, kdtree_closest_val)[2] <= kdtree.X_data[curr_axis]) && kdtree.child_l !== nothing\n                kdtree_recursive_search!(X_vec, kdtree.child_l, depth+1, n_axes, kdtree_closest, kdtree_closest_val)\n            end\n        end\n    end\n    \n    result = Array{Number}(undef, size(X_predict)[1])\n    for i in 1:size(X_predict)[1]\n        kdtree_closest = Array{Union{KdTree, Nothing}}(nothing, K)\n        kdtree_closest_val = Array{AbstractFloat}(undef, K)\n        kdtree_recursive_search!(X_predict[i, :], kdtree, 0, size(X_predict)[2], kdtree_closest, kdtree_closest_val)\n        K_nearest_votes = Number[]\n        for i in 1:K\n            if kdtree_closest[i] === nothing\n                break\n            else\n                push!(K_nearest_votes, kdtree_closest[i].Y_data)\n            end\n        end\n        result[i] = majority_vote(K_nearest_votes)\n    end\n    return result\nend\n\n# ╔═╡ 569da607-dea8-4994-9ffe-05959071a855\nkdtree_train = create_kdtree(X_train, Y_train)\n\n# ╔═╡ 0ea4cb86-6be5-49f1-b9b8-56f6a8cc8ed0\nJuTools.compute_accuracy(predict_kdtree(X_test, kdtree_train, K=10), Y_test)\n\n# ╔═╡ 98be952f-0591-45c6-be83-3c0f6cc5d26b\nmd\"\"\"\n### Ball Tree Approach\n\nA better space partition approach\\\nMore efficient than K-d Tree when searching\\\n[Wikipedia](https://en.wikipedia.org/wiki/Ball_tree)\n\"\"\"\n\n# ╔═╡ dc218b5e-73f5-4dc8-b523-62bed53a71e7\nmutable struct BallTree\n    X_data::Array{T} where T<:Number\n    Y_data::Number\n    pivot::Union{Array{T},Nothing} where T<:Number # defines pivot point of hypersphere\n    radius::AbstractFloat                            # defines radius of hypersphere\n    child_l::Union{BallTree,Nothing}\n    child_r::Union{BallTree,Nothing}\nend\n\n# ╔═╡ d7cc4b1c-f953-4f64-95bb-09e1d51a38f5\n# inspired from https://gist.github.com/jakevdp/5216193\n# ball tree generator function\nfunction create_balltree(X_data::Array{T} where T<:Number, Y_data::Array{T} where T<:Number)::BallTree\n    @assert ndims(X_data) == 2\n    @assert ndims(Y_data) == 1\n    @assert size(X_data)[1] == size(Y_data)[1]\n    balltree = nothing\n    if size(X_data)[1] == 1\n        balltree = BallTree(X_data[1, :], Y_data[1], nothing, 0.0, nothing, nothing)\n    else\n        # find pivot\n        pivot = vec(sum(X_data, dims=1)) ./ size(X_data)[1]\n        # find radius\n        radius = 0.0\n        for i in 1:size(X_data)[1]\n            X_vec = X_data[i, :]\n            dist = dist_sim(pivot, X_vec)\n            if dist > radius\n                radius = dist\n            end\n        end\n        # find greatest spread dimension\n        d_greatest_spread = 1\n        n_spread = 0.0\n        for i in 1:size(X_data)[2]\n            X_vec = X_data[:, i]\n            current_spread = abs(maximum(X_vec) - minimum(X_vec))\n            if current_spread > n_spread\n                d_greatest_spread = i\n                n_spread = current_spread\n            end\n        end\n        data_combined = hcat(X_data, Y_data)\n        data_combined = sortslices(data_combined, by=m->m[d_greatest_spread], dims=1)\n        X_data = data_combined[:, 1:end-1]\n        Y_data = data_combined[:, end]\n        i_mid = div(size(X_data)[1], 2) + 1\n        node_X_data = X_data[i_mid, :]\n        node_Y_data = Y_data[i_mid]\n        balltree = BallTree(node_X_data, node_Y_data, pivot, radius, nothing, nothing)\n        if i_mid > 1\n            balltree.child_l = create_balltree(X_data[1:i_mid-1,:], Y_data[1:i_mid-1])\n        end\n        if i_mid < size(X_data)[1]\n            balltree.child_r = create_balltree(X_data[i_mid+1:end,:], Y_data[i_mid+1:end])\n        end\n    end\n    return balltree\nend\n\n# ╔═╡ ffb15055-c887-47a9-88d7-71a33a3c2dba\nballtree = create_balltree(X_data, Y_data)\n\n# ╔═╡ 77ed169b-d426-4f3f-8362-809cb0c8dd22\nballtree.X_data\n\n# ╔═╡ 79ddb157-8ee4-4c44-b8bf-b4f36f88acce\nballtree.Y_data\n\n# ╔═╡ 6c589940-e00a-40c9-b2d9-c10384e4ac62\nballtree.pivot\n\n# ╔═╡ 5b5c5f78-75c2-4a85-b918-e7485f492d9e\nballtree.radius\n\n# ╔═╡ 75368c67-8774-4f67-9163-d31475f4e289\nballtree_test = create_balltree(reshape([30,5,10,70,50,35], (6, 1)), [1,1,1,1,1,1])\n\n# ╔═╡ a14bd64d-4188-4682-8a47-c3999afb0d09\n# search function for ball tree\n# similar to kdtree search\nfunction predict_balltree(X_predict::Array{T} where T<:Number, balltree::BallTree; K::Integer=5)::Array\n    @assert K > 0\n    @assert 0 < ndims(X_predict) <= 2\n    if ndims(X_predict) == 1\n        X_predict = reshape(X_predict, (1, size(X_predict)[1]))\n    end\n    @assert size(X_predict)[2] == size(balltree.X_data)[1]\n    \n    function balltree_closest_max(balltree_closest::Array{Union{BallTree, Nothing}},\n                balltree_closest_val::Array{AbstractFloat})::Tuple{Integer, AbstractFloat}\n        # find the maximum value in balltree_closest_val\n        # return its index and value\n        default = (0, 0.0)\n        for i in 1:size(balltree_closest)[1]\n            if balltree_closest[i] === nothing\n                break\n            elseif default[1] == 0 || (balltree_closest_val[i] > default[2])\n                default = (i, balltree_closest_val[i])\n            end\n        end\n        return default\n    end\n    \n    function balltree_update_nearest!(X_vec::Array, balltree::BallTree, balltree_closest::Array{Union{BallTree, Nothing}},\n                balltree_closest_val::Array{AbstractFloat})\n        # update current node by distance\n        @assert size(balltree_closest) == size(balltree_closest_val)\n        distance = dist_sim(balltree.X_data, X_vec)\n        if nothing in balltree_closest\n            for i in 1:size(balltree_closest)[1]\n                if balltree_closest[i] === nothing\n                    balltree_closest[i] = balltree\n                    balltree_closest_val[i] = distance\n                    break\n                end\n            end\n        else\n            curr_max = balltree_closest_max(balltree_closest, balltree_closest_val)\n            if distance < curr_max[2]\n                balltree_closest[curr_max[1]] = balltree\n                balltree_closest_val[curr_max[1]] = distance\n            end\n        end\n    end\n    \n    function balltree_recursive_search!(X_vec::Array, balltree::BallTree, balltree_closest::Array{Union{BallTree, Nothing}},\n            balltree_closest_val::Array{AbstractFloat})\n        # recursively search a balltree for K nearest neighbors\n        @assert size(balltree_closest) == size(balltree_closest_val)\n        if (!(nothing in balltree_closest) && (balltree.pivot !== nothing)\n                && (dist_sim(X_vec, balltree.pivot) - balltree.radius >= \n                    balltree_closest_max(balltree_closest, balltree_closest_val)[2]))\n            return nothing\n        end\n        # check current node\n        balltree_update_nearest!(X_vec, balltree, balltree_closest, balltree_closest_val)\n        # run on children\n        if balltree.child_l === nothing || balltree.child_r === nothing\n            if balltree.child_l !== nothing\n                balltree_recursive_search!(X_vec, balltree.child_l, balltree_closest, balltree_closest_val)\n            end\n            if balltree.child_r !== nothing\n                balltree_recursive_search!(X_vec, balltree.child_r, balltree_closest, balltree_closest_val)\n            end\n        else\n            dist_left = dist_sim(X_vec, balltree.child_l.X_data)\n            dist_right = dist_sim(X_vec, balltree.child_r.X_data)\n            if dist_left < dist_right\n                balltree_recursive_search!(X_vec, balltree.child_l, balltree_closest, balltree_closest_val)\n                balltree_recursive_search!(X_vec, balltree.child_r, balltree_closest, balltree_closest_val)\n            else\n                balltree_recursive_search!(X_vec, balltree.child_r, balltree_closest, balltree_closest_val)\n                balltree_recursive_search!(X_vec, balltree.child_l, balltree_closest, balltree_closest_val)\n            end\n        end\n    end\n    \n    result = Array{Number}(undef, size(X_predict)[1])\n    for i in 1:size(X_predict)[1]\n        balltree_closest = Array{Union{BallTree, Nothing}}(nothing, K)\n        balltree_closest_val = Array{AbstractFloat}(undef, K)\n        balltree_recursive_search!(X_predict[i, :], balltree, balltree_closest, balltree_closest_val)\n        K_nearest_votes = Number[]\n        for i in 1:K\n            if balltree_closest[i] === nothing\n                break\n            else\n                push!(K_nearest_votes, balltree_closest[i].Y_data)\n            end\n        end\n        result[i] = majority_vote(K_nearest_votes)\n    end\n    return result\nend\n\n# ╔═╡ 06e6d38d-b08e-4583-863a-e6e06726143b\nballtree_train = create_balltree(X_train, Y_train)\n\n# ╔═╡ 41e118e2-2172-4910-ba52-12e199737c6a\nJuTools.compute_accuracy(predict_balltree(X_test, balltree_train, K=20), Y_test)\n\n# ╔═╡ Cell order:\n# ╟─5057c590-c5a4-11eb-2621-4b67f12ca95d\n# ╟─74f4afa1-dd5a-4931-ab48-a1d4fc77bbe5\n# ╠═cb1dd9ac-ca78-4169-b073-943f64160dbc\n# ╠═f1fa76da-f656-4f12-97d7-a8b847ca0733\n# ╠═c3ad6021-8080-4870-8350-1337d548f23a\n# ╠═83864e6e-4b62-45d5-962e-39e36bbcc43d\n# ╠═0d7f31a9-7ae2-4be5-81b2-313ac58af62d\n# ╠═73b4e7e0-7294-46dc-9545-9728277df652\n# ╠═19b1c000-6fa3-42b7-9fc7-983c7caf44b9\n# ╠═063389c7-07b6-4050-9241-ea953c4f4338\n# ╠═cf291226-c0a1-4206-a8cb-53bedb67b139\n# ╠═fbf7a012-dcf8-498f-ad29-ec8c4854406c\n# ╠═2cf4e990-f788-44e3-94cc-9e210e47c762\n# ╠═c9d27318-5e3d-4c9c-9ba5-556c649baaf9\n# ╟─ba24b3c5-f350-4774-a018-9acf1f4597ad\n# ╠═5e564f3b-1bda-41b1-8b22-bdf6d91314d2\n# ╠═ed575b52-7509-4140-b5e7-295920f73e3d\n# ╠═8406faec-66f4-46aa-9582-964ebdbecfba\n# ╠═3001da4a-3288-4168-b514-c0b12f552fdd\n# ╠═30320c6e-7ada-41b6-a938-f1fd19cc120a\n# ╠═27b26afb-a91c-47c4-94ef-1d64761f291d\n# ╠═0e1b5c16-f444-41dd-9e44-999969ba647c\n# ╠═c42f2b8a-a88d-4e8c-a1c0-1a371ae6a669\n# ╠═158f77bf-2eb8-490a-a062-6364a6ec70e9\n# ╟─323e10a0-c68f-433a-afc5-0ac2514a90d1\n# ╠═52010e3f-2e4f-4778-b53e-4fad04dd75bf\n# ╠═36ceae2a-4c04-4f67-9a6d-19a44cb2fa5b\n# ╟─2c7f7263-5ba0-4786-8b68-8ca8fb3ffc26\n# ╟─b2aac2a9-cf86-44f0-ae97-b2a52327b0f9\n# ╠═b127297e-cb0c-46f5-8551-3ba2c4dae4c6\n# ╠═c3c4fe2c-6e92-4c98-bce3-e77f394c405d\n# ╠═a76dcf16-060e-4ece-9b8d-76c45deb38c4\n# ╠═4c3444dd-f2cb-4954-8dad-d2e9466252e8\n# ╠═94c43601-cff7-4c7f-a116-8a82aefed5b0\n# ╠═569da607-dea8-4994-9ffe-05959071a855\n# ╠═0ea4cb86-6be5-49f1-b9b8-56f6a8cc8ed0\n# ╟─98be952f-0591-45c6-be83-3c0f6cc5d26b\n# ╠═dc218b5e-73f5-4dc8-b523-62bed53a71e7\n# ╠═d7cc4b1c-f953-4f64-95bb-09e1d51a38f5\n# ╠═ffb15055-c887-47a9-88d7-71a33a3c2dba\n# ╠═77ed169b-d426-4f3f-8362-809cb0c8dd22\n# ╠═79ddb157-8ee4-4c44-b8bf-b4f36f88acce\n# ╠═6c589940-e00a-40c9-b2d9-c10384e4ac62\n# ╠═5b5c5f78-75c2-4a85-b918-e7485f492d9e\n# ╠═75368c67-8774-4f67-9163-d31475f4e289\n# ╠═a14bd64d-4188-4682-8a47-c3999afb0d09\n# ╠═06e6d38d-b08e-4583-863a-e6e06726143b\n# ╠═41e118e2-2172-4910-ba52-12e199737c6a\n", "meta": {"hexsha": "addd87d3c8885996e72ff701e94f5084325f8801", "size": 22021, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "K_Nearest_Neighbors/notebook.jl", "max_stars_repo_name": "teamclouday/JuliaLearn", "max_stars_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "K_Nearest_Neighbors/notebook.jl", "max_issues_repo_name": "teamclouday/JuliaLearn", "max_issues_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "K_Nearest_Neighbors/notebook.jl", "max_forks_repo_name": "teamclouday/JuliaLearn", "max_forks_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7071917808, "max_line_length": 151, "alphanum_fraction": 0.6624131511, "num_tokens": 7921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.8856314738181875, "lm_q1q2_score": 0.7613452679837491}}
{"text": "\nusing DifferentialEquations, ParameterizedFunctions\nball! = @ode_def BallBounce begin\n  dy =  v\n  dv = -g\nend g\n\n\nfunction condition(u,t,integrator)\n  u[1]\nend\n\n\nfunction affect!(integrator)\n    integrator.u[2] = -integrator.p[2] * integrator.u[2]\nend\n\n\nbounce_cb = ContinuousCallback(condition,affect!)\n\n\nu0 = [50.0,0.0]\ntspan = (0.0,15.0)\np = (9.8,0.9)\nprob = ODEProblem(ball!,u0,tspan,p,callback=bounce_cb)\n\n\nsol = solve(prob,Tsit5())\nusing Plots; gr()\nplot(sol)\n\n\nfunction condition_kick(u,t,integrator)\n    t == 2\nend\n\n\nfunction affect_kick!(integrator)\n    integrator.u[2] += 50\nend\n\n\nkick_cb = DiscreteCallback(condition_kick,affect_kick!)\nu0 = [50.0,0.0]\ntspan = (0.0,10.0)\np = (9.8,0.9)\nprob = ODEProblem(ball!,u0,tspan,p,callback=kick_cb)\n\n\nsol = solve(prob,Tsit5(),tstops=[2.0])\nplot(sol)\n\n\ncb = CallbackSet(bounce_cb,kick_cb)\n\n\nu0 = [50.0,0.0]\ntspan = (0.0,15.0)\np = (9.8,0.9)\nprob = ODEProblem(ball!,u0,tspan,p,callback=cb)\nsol = solve(prob,Tsit5(),tstops=[2.0])\nplot(sol)\n\n\nu0 = [1.,0.]\nharmonic! = @ode_def HarmonicOscillator begin\n   dv = -x\n   dx = v\nend\ntspan = (0.0,10.0)\nprob = ODEProblem(harmonic!,u0,tspan)\nsol = solve(prob)\nplot(sol)\n\n\nfunction terminate_affect!(integrator)\n    terminate!(integrator)\nend\n\n\nfunction terminate_condition(u,t,integrator)\n    u[2]\nend\nterminate_cb = ContinuousCallback(terminate_condition,terminate_affect!)\n\n\nsol = solve(prob,callback=terminate_cb)\nplot(sol)\n\n\nsol.t[end]\n\n\nterminate_upcrossing_cb = ContinuousCallback(terminate_condition,terminate_affect!,nothing)\n\n\nsol = solve(prob,callback=terminate_upcrossing_cb)\nplot(sol)\n\n\ntspan = (0.0,10000.0)\nprob = ODEProblem(harmonic!,u0,tspan)\nsol = solve(prob)\ngr(fmt=:png) # Make it a PNG instead of an SVG since there's a lot of points!\nplot(sol,vars=(1,2))\n\n\nplot(sol,vars=(0,1),denseplot=false)\n\n\nplot(sol.t,[u[2]^2 + u[1]^2 for u in sol.u]) # Energy ~ x^2 + v^2\n\n\nfunction g(resid,u,p,t)\n  resid[1] = u[2]^2 + u[1]^2 - 1\n  resid[2] = 0\nend\n\n\ncb = ManifoldProjection(g)\nsol = solve(prob,callback=cb)\nplot(sol,vars=(1,2))\n\n\nplot(sol,vars=(0,1),denseplot=false)\n\n\nu1,u2 = sol[500]\nu2^2 + u1^2\n\n\nprob = ODEProblem((du,u,p,t)->du.=u,rand(1000,1000),(0.0,1.0))\n\n\nsaved_values = SavedValues(Float64, Tuple{Float64,Float64})\n\n\nusing LinearAlgebra\ncb = SavingCallback((u,t,integrator)->(tr(u),norm(u)), saved_values)\n\n\nsol = solve(prob, Tsit5(), callback=cb, save_everystep=false, save_start=false, save_end = false) # Turn off normal saving\n\n\nsaved_values.t\n\n\nsaved_values.saveval\n\n\nsaved_values = SavedValues(Float64, Tuple{Float64,Float64}) # New cache\ncb = SavingCallback((u,t,integrator)->(tr(u),norm(u)), saved_values, saveat = 0.0:0.1:1.0)\nsol = solve(prob, Tsit5(), callback=cb, save_everystep=false, save_start=false, save_end = false) # Turn off normal saving\n\n\nsaved_values.t\n\n\nsaved_values.saveval\n\n\nusing DiffEqTutorials\nDiffEqTutorials.tutorial_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])\n\n", "meta": {"hexsha": "d479d7a15cbc4c95d62018573e52a88997f73beb", "size": 2906, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/introduction/04-callbacks_and_events.jl", "max_stars_repo_name": "isaacsas/DiffEqTutorials.jl", "max_stars_repo_head_hexsha": "46c1701ef613aacbd678bde7437a3c8de363990d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-05-24T10:30:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T12:13:03.000Z", "max_issues_repo_path": "script/introduction/04-callbacks_and_events.jl", "max_issues_repo_name": "LoopGlitch26/SciMLTutorials.jl", "max_issues_repo_head_hexsha": "837d71ad59de12af2fa48babb9e5cd2e280dc71a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-07T21:39:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T03:48:31.000Z", "max_forks_repo_path": "script/introduction/04-callbacks_and_events.jl", "max_forks_repo_name": "LoopGlitch26/SciMLTutorials.jl", "max_forks_repo_head_hexsha": "837d71ad59de12af2fa48babb9e5cd2e280dc71a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-24T14:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T14:30:36.000Z", "avg_line_length": 17.6121212121, "max_line_length": 122, "alphanum_fraction": 0.7040605643, "num_tokens": 971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8856314662716159, "lm_q1q2_score": 0.7613452614962352}}
{"text": "module SimpleML\n\nusing Optim\nusing OptionsMod\n\n\nexport predictLogistic, predictLogisticAll, learnLogistic, learnLogisticAll, predict2nn, learn2nn \n\nsigmoid(x) = (1 + exp (-1 * x)) .^ -1\n\nsigmoidGradient(z) = sigmoid(z) .* (1-sigmoid(z))\n\n#Cost function for a logistic regression, with regularisation\nfunction logisticCost(theta, X, y, grad, lambda)\n    m = length(y) #size of training set\n    n = length(theta) #number of features\n\n    h = sigmoid(X * theta)\n\n    sum =0\n    for i = 1:m \n        sum = sum + ( -1 * y[i] * log(h[i]) - (1-y[i]) * log (1-h[i]))\n    end    \n    for j=2:n \n        sum = sum + (lambda/2) * (theta[j] ^ 2)\n    end\n\n    if !(grad === nothing)\n        gptr = pointer(grad)\n        for j=1:n\n            grad[j]=0\n            for i = 1:m\n                grad[j] =  grad[j]  + (h[i] - y[i])*X[i,j]\n            end\n            \n           if j==1\n                grad[j] = grad[j]/m\n           else \n                grad[j] = ( grad[j] + lambda* theta[j]) / m\n           end\n        end\n        @assert gptr == pointer(grad)\n    end\n\n    return sum / m\nend\n\n\n\n#Learn via a logistic regression of two states\n#  X : features\n#  y : lables (binary)\n#  lambda : regularisation parameter\nfunction learnLogistic(X, y, lambda)\n    initial_theta = zeros(size(X,2))\n    ops = @options itermax=50 tol=1e-5\n    \n    results, fval, fcount, converged = cgdescent((g,t)->logisticCost(t, X, y, g, lambda),  initial_theta, ops)\n    #println(\"Converged: $converged @ $(fval[end]) with coefficients $results in $fcount iterations. \")\n\n    return results\nend\n\n#Learn via a logistic regression\n#  X : features\n#  y : lables\n#  nlables : number of lables\n#  lambda : regularisation parameter\nfunction learnLogisticAll(X, y, lambda, nlables)\n\n    m = size(X, 1); #number of data points\n    n = size(X, 2); #number of features\n\n    all_theta = zeros(nlables, n)\n\n    for c=1:nlables\n        initial_theta = zeros(n , 1)\n        all_theta[c,:]=learnLogistic(X,int((y.==c)),lambda)[:]\n    end\n\n     return all_theta\n\nend\n\nfunction predictLogistic(theta, X )\n    m = size(X, 1) \n    p = zeros(m, 1)\n    h = sigmoid(X * theta)\n\n    for i=1:m\n        if h[i] < 0.5 \n            p[i] = 0 \n        else\n            p[i] = 1\n        end\n    end\n    return p\nend\n\nfunction predictLogisticAll(all_theta, X)\n    m = size(X, 1) #Number of training examples\n    n = size(X, 2) #Number of features\n    nlables = size(all_theta, 1)\n    all_h = zeros(nlables, m)\n    for c = 1: nlables\n        theta = all_theta[c,:]\n        h = sigmoid(X * theta')\n        all_h[c,:] = h[:]\n    end    \n\n    p = zeros(m)\n\n    for i = 1:m\n        _ , p[i] = findmax(all_h[:,i])\n    end\n\n    return p\nend\n\n#Learn a 2 layer neural network\n#  X : features\n#  y : lables\n#  input_sz: size of input layer\n#  hidden_sz: size of hidden layer\n#  nlables : number of lables\n#  lambda : regularisation parameter\nfunction learn2nn(X, y, input_sz, hidden_sz, nlables, lambda)\n\n    initial_theta1 = SimpleML.randomInitialWeights(input_sz, hidden_sz)\n    initial_theta2 = SimpleML.randomInitialWeights(hidden_sz, nlables)\n    initial_params = [initial_theta1[:] ; initial_theta2[:]]\n\n\n    ops = @options itermax=50 tol=1e-5\n    \n    results, fval, fcount, converged = cgdescent((g,t)->nn2Cost(t, X, y,input_sz, hidden_sz, nlables, lambda, g),  initial_params, ops)\n\n    #println(\"Converged: $converged @ $(fval[end]) with coefficients $results in $fcount iterations. \")\n\n    theta1 = reshape(results[1:hidden_sz * (input_sz + 1)], hidden_sz, (input_sz + 1))\n    theta2 = reshape(results[(1 + (hidden_sz * (input_sz + 1))):end], nlables, (hidden_sz + 1))\n    return theta1 ,theta2\n\nend\n\n#Predict a 2 layer neural network\nfunction predict2nn(theta1, theta2, X)\n    m = size(X, 1)\n    nlables = size(theta2, 1)\n    p = zeros(size(X, 1), 1)\n    X = [ones(m, 1) X]\n    a2 = sigmoid(X * theta1'); \n    a2 = [ones(m, 1) a2]\n    a3 = sigmoid (a2 * theta2')\n\n    for i=1:m\n        _, p[i] = findmax(a3[i,:])\n    end\n\n    return p\nend\n\n#Cost function for a 2 layer neural network\nfunction nn2Cost(params, X, y, input_sz,  hidden_sz, nlables,  lambda, grad)\n\n    theta1 = reshape(params[1:hidden_sz * (input_sz + 1)], hidden_sz, (input_sz + 1))\n    theta2 = reshape(params[(1 + (hidden_sz * (input_sz + 1))):end], nlables, (hidden_sz + 1))\n\n    m = size(X, 1)\n\n    J = 0\n    theta1_grad = zeros(size(theta1))\n    theta2_grad = zeros(size(theta2))\n\n    X = [ones(m, 1) X]\n\n    z2 = X * theta1'\n    a2 = sigmoid(z2) \n\n    a2 = [ones(m, 1) a2]\n    a3 = sigmoid (a2 * theta2')\n    s=0\n    for i=1:m\n        yvector = int([1:nlables] .== y[i])\n        s=s+sum(-yvector' .* log(a3[i,:]) - (1-yvector') .* log (1-a3[i,:])); \n    end\n\n    temp1 = theta1\n    temp2 = theta2\n    temp1[:, 1] = zeros(size(temp1, 1), 1)\n    temp2[:, 1] = zeros(size(temp2, 1), 1)\n\n\n    if !(grad === nothing)\n        gptr = pointer(grad)\n        for t=1:m\n            yvector = int([1:nlables] .== y[t])\n\n            delta3 = zeros(1,nlables)\n            delta3 = a3[t,:] - yvector'\n\n            delta2 = zeros (1, hidden_sz)\n            delta2 = (theta2' * delta3' )[2:end] .* sigmoidGradient(z2[t,:])' \n\n            theta2_grad = theta2_grad + delta3' * a2[t,:]\n            theta1_grad = theta1_grad + delta2 * X[t,:]\n        end\n\n        theta1_grad = theta1_grad / m\n        theta2_grad = theta2_grad / m\n\n        theta1_grad = theta1_grad + (lambda/m) * temp1\n        theta2_grad = theta2_grad + (lambda/m) * temp2\n\n        grad[:] = [theta1_grad[:] ; theta2_grad[:]]\n        @assert gptr == pointer(grad)\n        \n    end\n    return s/m  + (lambda/(2*m))*(sum(sum(temp1 .* temp1)) + sum(sum(temp2 .* temp2)))\nend\n\nfunction randomInitialWeights(l_in, l_out)\n    ep = 0.12\n    rand(l_out, 1 + l_in) * 2 * ep - ep\nend\n\nend", "meta": {"hexsha": "4fbc646ba4122d5083db2605e5a807c3464441f0", "size": 5738, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SimpleML.jl", "max_stars_repo_name": "aviks/SimpleML.jl", "max_stars_repo_head_hexsha": "4b9b1103fc9de632e8701e129014db64de3cbb7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-22T09:32:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-22T09:32:41.000Z", "max_issues_repo_path": "src/SimpleML.jl", "max_issues_repo_name": "aviks/SimpleML.jl", "max_issues_repo_head_hexsha": "4b9b1103fc9de632e8701e129014db64de3cbb7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SimpleML.jl", "max_forks_repo_name": "aviks/SimpleML.jl", "max_forks_repo_head_hexsha": "4b9b1103fc9de632e8701e129014db64de3cbb7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2775330396, "max_line_length": 135, "alphanum_fraction": 0.5731962356, "num_tokens": 1839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100816, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7613181575858046}}
{"text": "const k_pio2 = Double64(1.5707963267948966, 6.123233995736766e-17)\n\n\nfunction atan(x::DoubleFloat{T}) where {T<:IEEEFloat}\n   signbit(x) && return -atan(abs(x))\n   isinf(x) && return DoubleFloat{T}(pi)/2\n   iszero(x) && return x\n   y = DoubleFloat{T}(atan(x.hi))\n   s, c = sin(y), cos(y)\n   c2 = square(c)\n   t = s/c\n   z = y - (t - x)*c2 # z - (tan(x)-x)*(cos(x)^2)\n   s, c = sin(z), cos(z)\n   t = s/c\n   z = z - (t - x)*c2 # z - (tan(x)-x)*(cos(x)^2)\n   return z\nend\n\nfunction atan(y::DoubleFloat{T}, x::DoubleFloat{T}) where {T<:IEEEFloat}\n   iszero(y) && iszero(x) && return x\n   iszero(x) && return copysign(pio2(DoubleFloat{T}), y)\n   iszero(y) && return signbit(x) ? pio1(DoubleFloat{T}) : zero(DoubleFloat{T})\n   atanyx = atan(y/x)\n   if x > 0\n      atanyx\n   elseif x < 0\n      if y >= 0\n         atanyx + T(pi)\n      else\n         atanyx - T(pi)\n      end\n   elseif y > 0\n       T(pi)/2\n   elseif y < 0\n      -T(pi)/2\n   else\n      zero(T)\n   end\nend\n\nfunction asin(x::DoubleFloat{T}) where {T<:IEEEFloat}\n   abs(x) > 1.0 && throw(DomainError(\"$x\"))\n   signbit(x) && return -asin(abs(x))\n   y = x\n   y = y / (1.0 + sqrt(1.0 - square(y)))\n   z = atan(y)\n   return DoubleFloat{T}(z.hi+z.hi, z.lo+z.lo)\nend\n\nfunction acos(x::DoubleFloat{T}) where {T<:IEEEFloat}\n   abs(x) > 1.0 && throw(DomainError(\"$x\"))\n   signbit(x) && return DoubleFloat{T}(onepi - acos(abs(x)))\n   y = x\n   y = sqrt(1.0 - square(y)) / (1.0 + y)\n   z = atan(y)\n   return DoubleFloat{T}(z.hi+z.hi, z.lo+z.lo)\nend\n\nacsc(x::DoubleFloat{T}) where {T<:IEEEFloat} = asin(inv(x))\nasec(x::DoubleFloat{T}) where {T<:IEEEFloat} = acos(inv(x))\n\nfunction acot(x::DoubleFloat{T}) where {T<:IEEEFloat}\n   signbit(x) && return DoubleFloat{T}(onepi - acot(abs(x)))\n   iszero(x) && return k_pio2\n   z = k_pio2 - atan(abs(x))\n   if signbit(x.hi)\n      z = -z\n   end\n   return z\nend\n", "meta": {"hexsha": "6d8c36eaac0459a918e73848f5e8a8d1e19a65f4", "size": 1842, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/elementary/arctrig.jl", "max_stars_repo_name": "yikait2/DoubleFloats.jl", "max_stars_repo_head_hexsha": "5ee5c9c35872d866a09d62877cf299780e2df40c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math/elementary/arctrig.jl", "max_issues_repo_name": "yikait2/DoubleFloats.jl", "max_issues_repo_head_hexsha": "5ee5c9c35872d866a09d62877cf299780e2df40c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/elementary/arctrig.jl", "max_forks_repo_name": "yikait2/DoubleFloats.jl", "max_forks_repo_head_hexsha": "5ee5c9c35872d866a09d62877cf299780e2df40c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9436619718, "max_line_length": 79, "alphanum_fraction": 0.5662323561, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065459, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7613181515528236}}
{"text": "#    Problem : GROUP A\n#    *********\n#    The ENGVAL1 problem.\n#    This problem is a sum of 2n-2 groups, n-1 of which contain 2 nonlinear\n#    elements\n#\n#    Original SIF Source: problem 31 in\n#    Ph.L. Toint,\n#    \"Test problems for partially separable optimization and results\n#    for the routine PSPMIN\",\n#    Report 83/4, Department of Mathematics, FUNDP (Namur, B), 1983.\n#\n#    See also Buckley#172 (p. 52)\n#    SIF input: Ph. Toint and N. Gould, Dec 1989.\n#\n#    Implementation translated from Source:\n#    http://eprints.tsu.ge/234/14/Tests%20collection-K-F.pdf\n#\n#    ENGVAL1.SIF classification OUR2-AN-V-0\n#\n#    N is the number of variables\n#\n# Daniel Henderson, 08/2021\n\nf = (x) -> begin\n    fx = 0.0 \n    for i in firstindex(x):lastindex(x)-1\n        γ = x[i]^2 + x[i+1]^2\n        fx += γ^2 + (3.0 - 4.0x[i])\n    end\n    return fx\nend\n\ng! = (g, x) -> begin\n    for i in firstindex(x):lastindex(x)-1\n        γ = x[i]^2 + x[i+1]^2\n        g[i] += 4.0γ*x[i] - 4.0\n        g[i+1] += 4.0γ*x[i+1]\n    end\n    return g\nend\n\nfg! = (g, x) -> begin\n    fx = 0.0 \n    for i in firstindex(x):lastindex(x)-1\n        γ = x[i]^2 + x[i+1]^2\n        fx += γ^2 + (3.0 - 4.0x[i])\n        g[i] += 4.0γ*x[i] - 4.0\n        g[i+1] += 4.0γ*x[i+1]\n    end\n    return fx, g\nend\n\ninit = (n::Int=5000) -> begin\n\tn < 2 && @warn(\"ENGVAL1: number of variables must be ≥ 2\")\n\tn = max(n, 2)\n    \n    return n, 2.0*ones(n)\nend\n\nTestSet[\"ENGVAL1\"] = UncProgram(\"ENGVAL1\",  f, g!, fg!, init)", "meta": {"hexsha": "99945cc89ae7f3930478280cef08b42691dedbde", "size": 1473, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/programs/ENGVAL1.jl", "max_stars_repo_name": "danphenderson/UncNLPrograms.jl", "max_stars_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/programs/ENGVAL1.jl", "max_issues_repo_name": "danphenderson/UncNLPrograms.jl", "max_issues_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/programs/ENGVAL1.jl", "max_forks_repo_name": "danphenderson/UncNLPrograms.jl", "max_forks_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1475409836, "max_line_length": 75, "alphanum_fraction": 0.5478615071, "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.761275645340182}}
{"text": "immutable Gumbel <: ContinuousUnivariateDistribution\n    μ::Float64   # location\n    β::Float64 # scale\n\n    function Gumbel(μ::Real, β::Real)\n        β > zero(β) || error(\"The scale of Gumbel must be positive\")\n        @compat new(Float64(μ), Float64(β))\n    end\n\n    Gumbel(μ::Real) = Gumbel(μ, 1.0)\n    Gumbel() = new(0.0, 1.0)\nend\n\n@distr_support Gumbel -Inf Inf\n\nconst DoubleExponential = Gumbel\n\n\n#### Parameters\n\nlocation(d::Gumbel) = d.μ\nscale(d::Gumbel) = d.β\nparams(d::Gumbel) = (d.μ, d.β)\n\n\n#### Statistics\n\nmean(d::Gumbel) = d.μ + d.β * 0.57721566490153286\n\nmedian(d::Gumbel) = d.μ + d.β * 0.366512920581664327\n\nmode(d::Gumbel) = d.μ\n\nvar(d::Gumbel) = 1.6449340668482264 * d.β^2\n\nskewness(d::Gumbel) = 1.13954709940464866\n\nkurtosis(d::Gumbel) = 2.4\n\nentropy(d::Gumbel) = 1.57721566490153286 + log(d.β)\n\n\n#### Evaluation\n\nzval(d::Gumbel, x::Float64) = (x - d.μ) / d.β\nxval(d::Gumbel, z::Float64) = x * d.β + d.μ\n\nfunction pdf(d::Gumbel, x::Float64)\n    z = zval(d, x)\n    exp(-z - exp(-z)) / d.β\nend\n\nfunction logpdf(d::Gumbel, x::Float64)\n    z = zval(d, x)\n    - (z + exp(-z) + log(d.β))\nend\n\ncdf(d::Gumbel, x::Float64) = exp(-exp(-zval(d, x)))\nlogcdf(d::Gumbel, x::Float64) = -exp(-zval(d, x))\n\nquantile(d::Gumbel, p::Float64) = d.μ - d.β * log(-log(p))\n\ngradlogpdf(d::Gumbel, x::Float64) = - (1.0 + exp((d.μ - x) / d.β)) / d.β\n\n\n#### Sampling\n\nrand(d::Gumbel) = quantile(d, rand())\n\n\n", "meta": {"hexsha": "55de73416757d3c42c64d0915a9eec262c0c74bb", "size": 1399, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/gumbel.jl", "max_stars_repo_name": "wildart/Distributions.jl", "max_stars_repo_head_hexsha": "041315226c919c1a6c7dae8437bddd61907bc73b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/gumbel.jl", "max_issues_repo_name": "wildart/Distributions.jl", "max_issues_repo_head_hexsha": "041315226c919c1a6c7dae8437bddd61907bc73b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/gumbel.jl", "max_forks_repo_name": "wildart/Distributions.jl", "max_forks_repo_head_hexsha": "041315226c919c1a6c7dae8437bddd61907bc73b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7042253521, "max_line_length": 72, "alphanum_fraction": 0.6011436741, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7612756351156259}}
{"text": "# -*- encoding: utf-8 -*-\r\n#\r\n# The MIT License (MIT)\r\n#\r\n# Copyright © 2021 Matteo Foglieni and Riccardo Gervasoni\r\n#\r\n\r\n\"\"\"\r\n    rotation_x(ϑ::Float64) :: Transformation\r\n\r\nEncoding a rotation around the x-axis of an angle `ϑ` _**in radiant**_. \r\n\r\nThe positive sign is given by the right-hand rule, therefore clockwise\r\nrotation for entering x-axis corresponds to a `ϑ>0` rotation angle. \r\n\r\nSee also: [`Transformation`](@ref)\r\n\"\"\"\r\nfunction rotation_x(ϑ::Float64)\r\n    Transformation(\r\n        [1.0    0.0     0.0     0.0 ;   \r\n         0.0    cos(ϑ)  -sin(ϑ) 0.0 ;\r\n         0.0    sin(ϑ)  cos(ϑ)  0.0 ;\r\n         0.0    0.0     0.0     1.0]\r\n         ,\r\n        [1.0    0.0     0.0     0.0 ;   \r\n         0.0    cos(ϑ)  sin(ϑ)  0.0 ;\r\n         0.0    -sin(ϑ) cos(ϑ)  0.0 ;\r\n         0.0    0.0     0.0     1.0]\r\n    )\r\nend\r\n\r\n\"\"\"\r\n    rotation_y(ϑ::Float64) :: Transformation\r\n\r\nEncoding a rotation around the y-axis of an angle `ϑ` _**in radiant**_. \r\n\r\nThe positive sign is given by the right-hand rule, therefore clockwise\r\nrotation for entering y-axis corresponds to a `ϑ>0` rotation angle. \r\n\r\nSee also: [`Transformation`](@ref)\r\n\"\"\"\r\nfunction rotation_y(ϑ::Float64)\r\n    Transformation(\r\n        [cos(ϑ)     0.0     sin(ϑ)  0.0 ;\r\n         0.0        1.      0.0     0.0 ;\r\n         -sin(ϑ)    0.0     cos(ϑ)  0.0 ;\r\n         0.0        0.0     0.0     1.  ]\r\n         ,\r\n        [cos(ϑ)     0.0     -sin(ϑ) 0.0 ;\r\n         0.0        1.      0.0     0.0 ;\r\n         sin(ϑ)     0.0     cos(ϑ)  0.0 ;\r\n         0.0        0.0     0.0     1.  ]\r\n    )\r\nend \r\n\r\n\"\"\"\r\n    rotation_z(ϑ::Float64) :: Transformation\r\n\r\nEncoding a rotation around the z-axis of an angle `ϑ` _**in radiant**_. \r\n\r\nThe positive sign is given by the right-hand rule, therefore clockwise\r\nrotation for entering z-axis corresponds to a `ϑ>0` rotation angle. \r\n\r\nSee also: [`Transformation`](@ref)\r\n\"\"\"\r\nfunction rotation_z(ϑ::Float64)\r\n    Transformation(\r\n        [cos(ϑ) -sin(ϑ) 0.0     0.0 ;\r\n         sin(ϑ) cos(ϑ)  0.0     0.0 ;\r\n         0.0    0.0     1.0     0.0 ;\r\n         0.0    0.0     0.0     1.0]\r\n         ,\r\n        [cos(ϑ)     sin(ϑ)  0.0     0.0 ;\r\n         -sin(ϑ)    cos(ϑ)  0.0     0.0 ;\r\n         0.0        0.0     1.0     0.0 ;\r\n         0.0        0.0     0.0     1.0]\r\n    )\r\nend \r\n\r\n##########################################################################################92\r\n\r\nfunction scaling(v::Vec)\r\n    Transformation(\r\n        [v.x    0.0     0.0     0.0 ;\r\n         0.0    v.y     0.0     0.0 ;\r\n         0.0    0.0     v.z     0.0 ;\r\n         0.0    0.0     0.0     1.0]\r\n         ,\r\n        [1/v.x  0.0     0.0     0.0 ;\r\n         0.0    1/v.y   0.0     0.0 ;\r\n         0.0    0.0     1/v.z   0.0 ;\r\n         0.0    0.0     0.0     1.0]\r\n    )\r\nend \r\n\r\nscaling(x::Float64, y::Float64, z::Float64) = scaling(Vec(x,y,z))\r\n\r\n\r\n\"\"\"\r\n    scaling(v::Vec) :: Transformation\r\n    scaling(x::Float64, y::Float64, z::Float64) = scaling(Vec(x,y,z))\r\n\r\nEncoding a scaling of the 3 spatial coordinates according to the\r\nvector `v` (negative values codify spatial reflections). \r\n\r\nEach component of  `v` must be different from zero.\r\n\r\nSee also: [`Transformation`](@ref)\r\n\"\"\"\r\nscaling\r\n\r\n##########################################################################################92\r\n\r\n\r\nfunction translation(v::Vec)\r\n   Transformation(\r\n        [1.0    0.0     0.0     v.x ;\r\n         0.0    1.0     0.0     v.y ;\r\n         0.0    0.0     1.0     v.z ;\r\n         0.0    0.0     0.0     1.0]\r\n         ,\r\n        [1.0    0.0     0.0     -v.x ;\r\n         0.0    1.0     0.0     -v.y ;\r\n         0.0    0.0     1.0     -v.z ;\r\n         0.0    0.0     0.0     1.0]\r\n    )\r\nend \r\n\r\ntranslation(x::Float64, y::Float64, z::Float64) = translation(Vec(x,y,z))\r\n\r\n\"\"\"\r\n    translation(v::Vec) :: Transformation\r\n    translation(x::Float64, y::Float64, z::Float64) = translation(Vec(x,y,z))\r\n\r\nEncoding a rigid translation of the 3 spatial coordinates according to the\r\nvector `v`, which specifies the amount of shift to be applied along the three axes.\r\n\r\nSee also: [`Transformation`](@ref)\r\n\"\"\"\r\ntranslation\r\n\r\n##########################################################################################92\r\n\r\n\"\"\"\r\n    inverse(T::Transformation) :: Transformation\r\n\r\nReturn the inverse affine transformation of `T`.\r\nThis method is very cheap to call.\r\n\r\nSee also: [`Transformation`](@ref)\r\n\"\"\"\r\nfunction inverse(T::Transformation)\r\n    return Transformation(T.invM, T.M)\r\nend \r\n\r\n\"\"\"\r\n    is_consistent(T::Transformation) :: Bool\r\n\r\nCheck the internal consistency of the  input transformation, \r\nreturning a bool variable indicating whether `T.M==T.invM`.\r\nThis method is useful when writing tests.\r\n\r\nSee also: [`Transformation`](@ref)\r\n\"\"\"\r\nfunction is_consistent(T::Transformation)\r\n    p = T.M * T.invM\r\n    I = SMatrix{4,4}( Diagonal(ones(4)) )\r\n    return p ≈ I\r\nend\r\n", "meta": {"hexsha": "66eb5b55f274cb7acdba90b95229c6d3d35b2802", "size": 4868, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Transformations.jl", "max_stars_repo_name": "cosmofico97/Raytracing", "max_stars_repo_head_hexsha": "cad69a94b9f98b7239adc617660cfcee9cb44f08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-03T20:36:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-03T20:36:21.000Z", "max_issues_repo_path": "src/Transformations.jl", "max_issues_repo_name": "cosmofico97/Raytracing", "max_issues_repo_head_hexsha": "cad69a94b9f98b7239adc617660cfcee9cb44f08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-05-05T17:15:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-24T21:56:44.000Z", "max_forks_repo_path": "src/Transformations.jl", "max_forks_repo_name": "cosmofico97/Raytracing", "max_forks_repo_head_hexsha": "cad69a94b9f98b7239adc617660cfcee9cb44f08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6352941176, "max_line_length": 93, "alphanum_fraction": 0.4804847987, "num_tokens": 1594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.761227684411646}}
{"text": "using LabelledArrays \n\nexport ulam\n\nfunction eom_ulam(dx, x, p, t)\n    ε = p[:ε]\n    f = x -> 2 - x^2\n    dx[1] = f(ε*x[length(dx)] + (1-ε)*x[1])\n    for i in 2:length(dx)\n        dx[i] = f(ε*x[i-1] + (1-ε)*x[i])\n    end\nend\n\n\"\"\"\n    ulam(D::Int = 10; u₀ = rand(D), ε::Real = 0.10) → DiscreteDynamicalSystem\n\nA lattice of `D` unidirectionally coupled ulam maps[^Schreiber2000] defined as \n\n```math\nx^{m}_{t+1} = f(\\\\epsilon x^{m-1}_{t} + (1 - \\\\epsilon) x_{t}^{m}),\n```\n\nwhere ``m = 1, 2, \\\\ldots, D`` and ``f(x) = 2 - x^2``. In this system, information transfer \nhappens only in the direction of increasing ``m``.\n\n[^Schreiber2000]: Schreiber, Thomas. \"Measuring information transfer.\" Physical review letters 85.2 (2000): 461.\n\"\"\"\nfunction ulam(D::Int = 10; u₀ = rand(D), ε::Real = 0.10)\n\n    p = LVector(ε = ε)\n\n    DiscreteDynamicalSystem(eom_ulam, u₀, p)\nend", "meta": {"hexsha": "d4499b9c45145f9f39ac500ad6ca6c3e812d71e7", "size": 863, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/example_systems/discretemaps/ulammap.jl", "max_stars_repo_name": "kahaaga/CausalityTools.jl", "max_stars_repo_head_hexsha": "e1de3943a2ccb3c9997ca38e7a4fac025f1f8475", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2018-11-07T11:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-05T06:26:37.000Z", "max_issues_repo_path": "src/example_systems/discretemaps/ulammap.jl", "max_issues_repo_name": "kahaaga/CausalityTools.jl", "max_issues_repo_head_hexsha": "e1de3943a2ccb3c9997ca38e7a4fac025f1f8475", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2018-09-04T08:02:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-04T11:59:38.000Z", "max_forks_repo_path": "src/example_systems/discretemaps/ulammap.jl", "max_forks_repo_name": "kahaaga/CausalityTools.jl", "max_forks_repo_head_hexsha": "e1de3943a2ccb3c9997ca38e7a4fac025f1f8475", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-12-03T10:59:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:02:55.000Z", "avg_line_length": 26.1515151515, "max_line_length": 112, "alphanum_fraction": 0.594438007, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856298, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7612276842430006}}
{"text": "nanmean(x::AbstractVector)::Float64 = mean(map(n -> isnan(n) ? 0 : n, x))\nnanmean(x::AbstractMatrix)::Vector{Float64} = map(nanmean, eachrow(x))\nabsnanmean(x::AbstractVector)::Float64 = nanmean(map(abs, x))\nabsnanmean(x::AbstractMatrix)::Vector{Float64} = map(absnanmean, eachrow(x))\n\n# The code for `calc_drop` and `drop_cor` below is inspired by the code by Brian Pietracatella, found at\n# https://towardsdatascience.com/are-you-dropping-too-many-correlated-features-d1c96654abe6\n\nfunction calc_drop(res::DataFrame)::Vector{Symbol}\n    # Get all variables that have some high correlation\n    all_corr_vars = unique([res[!, :v1]; res[!, :v2]])\n    # Get all variables that are possibly dropped\n    poss_drop = unique(res[!, :drop])\n    # Get variables that are definitely kept\n    keep = setdiff(all_corr_vars, poss_drop)\n    # Drop variables that are highly correlated to a variable that is definitely kept\n    p = res[in(keep).(res[!, :v1]) .| in(keep).(res[!, :v2]), [:v1, :v2]]\n    q = unique([p[!, :v1]; p[!, :v2]])\n    drop = setdiff(q, keep)\n    # Remove dropped variables from the list of possibilities\n    poss_drop = setdiff(poss_drop, drop)\n    # Get variables that (correlate highly to variables that) are still possibly dropped\n    m = res[in(poss_drop).(res[!, :v1]) .| in(poss_drop).(res[!, :v2]), [:v1, :v2, :drop]]\n    # Drop variables that are not (correlated to variables that are) already dropped\n    more_drop = m[.!in(drop).(m[!, :v1]) .& .!in(drop).(m[!, :v2]), :drop]\n    return [drop; more_drop]\nend\n\nfunction drop_cor(cormat::Matrix{Float64}, xs::Vector{Symbol}, t::Float64)::Vector{Symbol}\n    msize = size(cormat, 1)\n    (msize == size(cormat, 2)) || throw(\"cormat is not a square matrix\")\n    (msize == length(xs)) || throw(\"length of xs does not match size of cormat\")\n\n    avgcor = absnanmean(cormat)\n\n    res = DataFrame(v1 = Symbol[], v2 = Symbol[], v1mean = Float64[], v2mean = Float64[], corr = Float64[], drop = Symbol[])\n\n    @inbounds for row in 1:(msize - 1)\n        for col in (row + 1):msize\n            if abs(cormat[row, col]) > t\n                rowsym = xs[row]\n                colsym = xs[col]\n                drop = avgcor[row] > avgcor[col] ? rowsym : colsym\n                entry = [\n                    rowsym, colsym,\n                    avgcor[row], avgcor[col],\n                    cormat[row, col], drop\n                ]\n                push!(res, entry)\n            end\n        end\n    end\n\n    return calc_drop(res)\n\nend\n", "meta": {"hexsha": "c60a9dcc8552093eb3becc8af75320c1f8505d4d", "size": 2479, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "incl/correlation_drop.jl", "max_stars_repo_name": "KasperNooteboom/thesis-rvfl-fs", "max_stars_repo_head_hexsha": "31f8ee8ff58da5a8c1f505ef045c35ebbfe91255", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "incl/correlation_drop.jl", "max_issues_repo_name": "KasperNooteboom/thesis-rvfl-fs", "max_issues_repo_head_hexsha": "31f8ee8ff58da5a8c1f505ef045c35ebbfe91255", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "incl/correlation_drop.jl", "max_forks_repo_name": "KasperNooteboom/thesis-rvfl-fs", "max_forks_repo_head_hexsha": "31f8ee8ff58da5a8c1f505ef045c35ebbfe91255", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4912280702, "max_line_length": 124, "alphanum_fraction": 0.6131504639, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.7612166721136387}}
{"text": "\"\"\"\n    function recallfull(ranks::AbstractArray, rtrue::AbstractArray)\n\nComputes the relative number of matches in the input ranking with respect to the input ground truth\n\"\"\"\nfunction recallfull(ranks::AbstractArray, rtrue::AbstractArray)\n    recall = 0\n    nn, m = size(rtrue)\n    @assert size(ranks)[1] == size(rtrue)[1]\n    for i in 1:m\n        recall += size(findall(in(ranks[:,i]),rtrue[:,i]))[1]        \n    end\n    return recall / (nn*m)\nend\n\n\"\"\"\n    recallN(ranks::AbstractArray, rtrue::AbstractArray, N)\n\nTakes a parameter `N` and computes the N@N recall between the input ranking and the input ground truth.\n\"\"\"\nfunction recallN(ranks::AbstractArray, rtrue::AbstractArray, N)\n    recall = 0\n    nn, m = size(rtrue)\n    for i in 1:m\n        recall += size(findall(in(ranks[1:N,i]),rtrue[1:N,i]))[1]        \n    end\n    return recall / (N*m)\nend\n\n\"\"\"\n    recallN(ranks::AbstractArray, rtrue::AbstractArray, N)\n\nTakes a parameter `N` and computes the 1@N recall between the input ranking and the input ground truth.\n\"\"\"\nfunction recall1atN(ranking::AbstractArray, rtrue::AbstractArray,N)\n    score = 0\n    n_queries = length(rtrue[1,:])\n    for i in 1:n_queries\n        if rtrue[1,i] in @view(ranking[1:N,i])\n            score+=1\n        end\n    end\n    return score / n_queries\nend\n\n\"\"\"\n    approx_error(qd::QuantizerData, data::AbstractMatrix, rtrue::AbstractArray, queries::AbstractArray)\n\nTakes the input approximation data generated by a constructor, the exact data set, the true nearest neighbors and a set of test queries.\nTakes the nearest neighbor to each query, computes the approximated inner product with the query and the true inner product with the query\nReturns the average normalized absolute between the two: `|<q, ̃x-x>-<q,x>|`\n\"\"\"\nfunction approx_error(qd::QuantizerData, data::AbstractMatrix, rtrue::AbstractArray, queries::AbstractArray)\n    dist = zeros(size(queries)[2])\n    for i in 1:size(queries)[2]\n        qTx = dot(queries[:,i], data[:,rtrue[1,i]])\n        qTx_approx = dot(queries[:,i], qd.I.B[rtrue[1,i]]'qd.C)\n        dist[i] = abs((qTx - qTx_approx)/qTx)\n    end\n    return mean(dist)\nend\n\n\"\"\"\n    function get1atNscores(yhat::AbstractMatrix, groundtruth::AbstractMatrix, n_neighbors::Int)\n\nComputes the recall1atN score for every value between 1 and the input `n_neighbors` for the estimated\nranking and the groundtruth and outputs as a vector. Used for creating comparative 1@N plots.\n\"\"\"\nfunction get1atNscores(yhat::AbstractMatrix, groundtruth::AbstractMatrix, n_neighbors::Int)\n    scores = zeros(n_neighbors)\n    for i in 1:n_neighbors\n        scores[i] = recall1atN(yhat, groundtruth, i)\n    end\n    return scores\nend\n\nexport recallfull\nexport recallN\nexport recall1atN\nexport approx_error\nexport get1atNscores", "meta": {"hexsha": "8588570c78b60d91f6b19c1d70d1fd329883686f", "size": 2759, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/testmetrics.jl", "max_stars_repo_name": "AxelvL/AHPQ.jl", "max_stars_repo_head_hexsha": "66efa2b1febf83ad852836bf22603fd488d0f45e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-02-06T22:32:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-25T15:33:18.000Z", "max_issues_repo_path": "src/utils/testmetrics.jl", "max_issues_repo_name": "AxelvL/AHPQ.jl", "max_issues_repo_head_hexsha": "66efa2b1febf83ad852836bf22603fd488d0f45e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/testmetrics.jl", "max_forks_repo_name": "AxelvL/AHPQ.jl", "max_forks_repo_head_hexsha": "66efa2b1febf83ad852836bf22603fd488d0f45e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0617283951, "max_line_length": 138, "alphanum_fraction": 0.6995288148, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7612166680036017}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Combinatorics, Statistics, DataFrames, CSV\n\tusing Random, Distributions, Plots\n\tRandom.seed!(0)\nend\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.17\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tdata = CSV.read(datadir(\"fertilizer.csv\"), DataFrame; delim=\",\")\n\tcontrol = data.Control\n\tfertilizer = data.FertilizerX\nend;\n\n# ╔═╡ 1aa41898-3afa-11eb-2f49-570853ce6435\nsubGroups = collect(combinations([control;fertilizer],10))\n\n# ╔═╡ 1aa451f0-3afa-11eb-2bb1-65c72b577797\nbegin\n\tmeanFert = mean(fertilizer)\n\tpVal = sum([mean(i) >= meanFert for i in subGroups])/length(subGroups)\n\tText(\"p-value = $(pVal)\")\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.17\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═1aa41898-3afa-11eb-2f49-570853ce6435\n# ╠═1aa451f0-3afa-11eb-2bb1-65c72b577797\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "682f8cc14093f56164f64a10354e9f857a7e713f", "size": 1251, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/listing5.17.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/05/listing5.17.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/05/listing5.17.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.5306122449, "max_line_length": 71, "alphanum_fraction": 0.7434052758, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.8479677506936879, "lm_q1q2_score": 0.7612166646192411}}
{"text": "\"\"\"\n    kron_id(n, k)\n\nCompute the k-fold Kronecker product of the identity: `I ⊗ I ⊗ ... ⊗ I`, k times.\n\n### Input\n\n- `n` -- integer representing the order (dimension of the identity)\n- `k` -- integer representing the power\n\n### Output\n\nA `Diagonal` matrix with element `1` in the diagonal and order ``n^k``.\n\n### Examples\n\n```jldoctest\njulia> kron_id(2, 2)\n4×4 Diagonal{Float64,Array{Float64,1}}:\n 1.0   ⋅    ⋅    ⋅\n  ⋅   1.0   ⋅    ⋅\n  ⋅    ⋅   1.0   ⋅\n  ⋅    ⋅    ⋅   1.0\n```\n\"\"\"\nfunction kron_id(n::Int, k::Int)\n    return Diagonal(ones(n^k))\nend\n\n\"\"\"\n    kron_sandwich(F, n, k1, k2)\n\nCompute `A ⊗ F ⊗ C` where `A = I^{⊗ k1}` and `C = I^{⊗ k2}` where `I` is the\nidentity matrix of order `n`, the `k1`-fold and `k2`-fold Kronecker product of the\nidentity and `F` in between.\n\n### Input\n\n- `F`  -- matrix\n- `n`  -- integer, dimension of the identity\n- `k1` -- nonnegative integer\n- `k2` -- nonnegative integer\n\n### Output\n\nThe kronecker product `I^{⊗ k1} ⊗ F ⊗ I^{⊗ k2}`, represented as a sparse matrix\nif `F` is sparse.\n\n### Examples\n\n```jldoctest\njulia> F = sparse([0 1; -1 0.])\n2×2 SparseMatrixCSC{Float64,Int64} with 2 stored entries:\n  [2, 1]  =  -1.0\n  [1, 2]  =  1.0\n\njulia> Q = kron_sandwich(F, 2, 2, 2);\n\njulia> size(Q)\n(32, 32)\n\njulia> I2 = I(2)\nIdentityMultiple{Float64} of value 1.0 and order 2\n\njulia> Q == reduce(kron, [I2, I2, F, I2, I2])\ntrue\n```\n\"\"\"\nfunction kron_sandwich(F::AbstractMatrix, n::Int, k1::Int, k2::Int)\n    # compute A ⊗ F\n    if k1 == 0\n        AF = F\n    else\n        A = kron_id(n, k1)\n        AF = kron(A, F)\n    end\n\n    # compute A ⊗ F ⊗ C\n    if k2 == 0\n        AFC = AF\n    else\n        C = kron_id(n, k2)\n        AFC = kron(AF, C)\n    end\n\n    return AFC\nend\n\n\"\"\"\n    kron_sum(F::AbstractMatrix, k::Int)\n\nCompute the Kronecker sum of order k defined as:\n\n```math\n    F ⊕ F ⊕ ... ⊕ F := F ⊗ I ⊗ ... ⊗ I + I ⊗ F ⊗ I ⊗ ... ⊗ I + ... + I ⊗ ... ⊗ I ⊗ F\n```\nwhere each term has `k` products and there are a total of `k` summands\nand `I` is the identity matrix of order `n`.\n\n### Examples\n\nIt holds that:\n\n- ``k = 1: F``\n- ``k = 2: F ⊗ I + I ⊗ F``\n- ``k = 3: F ⊗ I ⊗ I + I ⊗ F ⊗ I + I ⊗ I ⊗ F``\n\n```jldoctest\njulia> F = sparse([0 1; -1 0.])\n2×2 SparseMatrixCSC{Float64,Int64} with 2 stored entries:\n  [2, 1]  =  -1.0\n  [1, 2]  =  1.0\n\njulia> kron_sum(F, 1) == F\ntrue\n\njulia> I2 = I(2)\nIdentityMultiple{Float64} of value 1.0 and order 2\n\njulia> kron_sum(F, 2) == kron(F, I2) + kron(I2, F)\ntrue\n\njulia> kron_sum(F, 3) == sum(reduce(kron, X) for X in [[F, I2, I2], [I2, F, I2], [I2, I2, F]])\ntrue\n```\n\"\"\"\nfunction kron_sum(F::AbstractMatrix, k::Int)\n    if k < 1\n        throw(ArgumentError(\"expected k ≥ 1, got $k\"))\n    elseif k == 1\n        return F\n    end\n\n    n = size(F, 1) # leading dimension\n    k1 = 0 # terms on the left of F\n    k2 = k-1 # terms on the right of F\n    A = kron_sandwich(F, n, k1, k2)  # I^(⊗k1) ⊗ F ⊗ I^(⊗k2)\n    for i in 2:k\n        k1 += 1\n        k2 -= 1\n        B = kron_sandwich(F, n, k1, k2)\n        A += B\n    end\n    return A\nend\n\n\"\"\"\n    kron_pow(x::Vector{<:AbstractVariable}, pow::Int)\n\nCompute the higher order concrete Kronecker power: `x ⊗ x ⊗ ... ⊗ x`, `pow` times\nfor a vector of symbolic monomials.\n\n### Input\n\n- `x`   -- polynomial variable\n- `pow` -- integer\n\n### Output\n\nVector of multivariate monomial corresponding to `x^{⊗ pow}`.\n\n### Examples\n\n```jldoctest\njulia> using DynamicPolynomials\n\njulia> @polyvar x[1:2]\n(PolyVar{true}[x₁, x₂],)\n\njulia> x\n2-element Vector{PolyVar{true}}:\n x₁\n x₂\n\njulia> kron_pow(x, 2)\n4-element Vector{Monomial{true}}:\n x₁²\n x₁x₂\n x₁x₂\n x₂²\n```\n\"\"\"\nfunction kron_pow(x::Vector{<:AbstractVariable}, pow::Int)\n    @assert pow > 0 \"expected positive power, got $pow\"\n    if pow == 1\n        return x\n    else\n        return kron(x, kron_pow(x, pow-1))\n    end\nend\n\nkron_pow(x::NTuple, pow::Int) = kron_pow([xi for xi in x], pow)\n", "meta": {"hexsha": "ad8883866fe270074471dcc76c83723b3646af08", "size": 3839, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kronecker.jl", "max_stars_repo_name": "pogudingleb/CarlemanLinearization.jl", "max_stars_repo_head_hexsha": "461d782c2f42cc5961bede7123ce237f441c1635", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kronecker.jl", "max_issues_repo_name": "pogudingleb/CarlemanLinearization.jl", "max_issues_repo_head_hexsha": "461d782c2f42cc5961bede7123ce237f441c1635", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kronecker.jl", "max_forks_repo_name": "pogudingleb/CarlemanLinearization.jl", "max_forks_repo_head_hexsha": "461d782c2f42cc5961bede7123ce237f441c1635", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8911917098, "max_line_length": 94, "alphanum_fraction": 0.5673352436, "num_tokens": 1531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7612166616373236}}
{"text": "using Distributions\nusing Statistics\nusing Random\n\n# This is a simple lookup table for the normal pdf\n#\n# Recall that the normal pdf has the form\n#\n# 1/(sigma sqrt(2pi)) exp(-1/2 ((x-mu) / sigma)^2)\nstruct NormalLookup\n  # PDF values for 0:increment:max\n  #\n  # WARNING: since the zvalues start at zero, we have to be careful with zero\n  # and one indexing\n  pdfvals::Vector{Float64}\n\n  # (unit: standard deviations)\n  increment::Float64\n\n  function NormalLookup(;increment, max)\n    zvals = 0.0:increment:max\n\n    N = Normal(0.0, 1.0)\n    pdfvals = map(x->pdf(N, x), zvals)\n\n    new(pdfvals, increment)\n  end\nend\n\nconst min_likelihood = 1e-6\nfunction evaluate_no_norm(l::NormalLookup; error::Float64, stddev::Float64)\n  if stddev < 0.0\n    error(\"Negative standard deviation: \", stddev)\n  end\n\n  # rounding returns the effective zero-index so we add one\n  index = round(Int64, abs(error) / (stddev * l.increment)) + 1\n\n  # Since this is a normal pdf, take the limit for out-of-bounds values\n  if index > length(l.pdfvals)\n    min_likelihood\n  else\n    l.pdfvals[index]\n  end\nend\nfunction evaluate(l::NormalLookup; error::Float64, stddev::Float64)\n  evaluate_no_norm(l; error=error, stddev=stddev) / stddev\nend\n", "meta": {"hexsha": "8fff2a768e2d4b47529394171feecf00786993d1", "size": 1211, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/normal_lookup_table.jl", "max_stars_repo_name": "mcorah/MultiAgentSensing", "max_stars_repo_head_hexsha": "3c35282f818c357b44d401732f35842f0667acf4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-20T03:27:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T03:27:55.000Z", "max_issues_repo_path": "src/normal_lookup_table.jl", "max_issues_repo_name": "mcorah/MultiAgentSensing", "max_issues_repo_head_hexsha": "3c35282f818c357b44d401732f35842f0667acf4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/normal_lookup_table.jl", "max_forks_repo_name": "mcorah/MultiAgentSensing", "max_forks_repo_head_hexsha": "3c35282f818c357b44d401732f35842f0667acf4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-30T00:08:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T00:08:16.000Z", "avg_line_length": 24.7142857143, "max_line_length": 77, "alphanum_fraction": 0.706028076, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7611961959128368}}
{"text": "# # Section Allocation\n# Suppose you have $n$ students in a class who need to be assigned to $m$ discussion sections. Each student needs to be assigned to exactly one section. Each discussion section should have between 6 and 10 students. Suppose an $n \\times m$ preference matrix $P$ is given, where $P_{ij}$ gives student $i$'s ranking for section $j$ (1 would mean it is the student's top choice, 10,000 or a large number would mean the student can not attend that section).\n#\n# The goal will be to get an allocation matrix $X$, where $X_{ij} = 1$ if student $i$ is assigned to section $j$ and $0$ otherwise. \n\nusing Convex, GLPKMathProgInterface\naux(str) = joinpath(@__DIR__, \"aux\", str) # path to auxiliary files\n\n# Load our preference matrix, P\ninclude(aux(\"data.jl\"))\nsummary(P)\n\nX = Variable(size(P), :Bin)\n\n# We want every student to be assigned to exactly one section. So, every row must have exactly one non-zero entry\n# In other words, the sum of all the columns for every row is 1\n# We also want each section to have between 6 and 10 students, so the sum of all the rows for every column should \n# be between these\nconstraints = [sum(X, dims=2) == 1, sum(X, dims=1) <= 10, sum(X, dims=1) >= 6]\n\n# Our objective is simple sum(X .* P), which can be more efficiently represented as vec(X)' * vec(P)\n# Since each entry of X is either 0 or 1, this is basically summing up the rankings of students that were assigned to them.\n# If all students got their first choice, this value will be the number of students since the ranking of the first choice is 1.\np = minimize(vec(X)' * vec(P), constraints)\n\nsolve!(p, GLPKSolverMIP())\np.optval\n", "meta": {"hexsha": "ea343e8e9a9d5b4ba7b9d3a335e57efc412a491b", "size": 1642, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/mixed_integer/section_allocation.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Convex.jl-f65535da-76fb-5f13-bab9-19810c17039a", "max_stars_repo_head_hexsha": "52a024f0880e5aab8ee6b1e4e4730f76e1b9d08a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/examples_literate/mixed_integer/section_allocation.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Convex.jl-f65535da-76fb-5f13-bab9-19810c17039a", "max_issues_repo_head_hexsha": "52a024f0880e5aab8ee6b1e4e4730f76e1b9d08a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/examples_literate/mixed_integer/section_allocation.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Convex.jl-f65535da-76fb-5f13-bab9-19810c17039a", "max_forks_repo_head_hexsha": "52a024f0880e5aab8ee6b1e4e4730f76e1b9d08a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.6428571429, "max_line_length": 454, "alphanum_fraction": 0.7295980512, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7611961947075819}}
{"text": "## Test MCMC routines\nusing PotentialUQ\nusing LinearAlgebra\nusing Statistics\nx0 = randn(2)\nnum_samples = 5\n\ntarget_mean = 2.0*ones(2)\ntarget_cov = [1.0 0.2; 0.2 1.0]\ntarget_cov_inverse = inv(target_cov)\nlog_likelihood(x) = 0.5*(x - target_mean)' * target_cov_inverse * (x - target_mean)\ngrad_log_likelihood(x) = target_cov_inverse * (x - target_mean)\n\ncurrent_state = state(x0, log_likelihood(x0), grad_log_likelihood(x0))\nchain_diagnostics(num_samples)\nchain(x0, num_samples)\n@time hmc_step(current_state, log_likelihood, grad_log_likelihood, randn(size(x0)), 1e-2, 20)\n@time burnin_chain, final_chain = hmc(x0, log_likelihood, grad_log_likelihood, 1000, 500)\n\n# println(\"Burnin Chain\")\n# show(stdout, \"text/plain\", burnin_chain.x)\n# show(stdout, \"text/plain\", burnin_chain.diagnostics.log_likelihood)\n# println(\" \")\n\nprintln(\"Sampling Chain:\")\nshow(stdout, \"text/plain\", final_chain.x[end-10:end])\nprintln(\" \")\nshow(stdout, \"text/plain\", final_chain.diagnostics.log_likelihood[end-10:end])\nprintln(\" \")\n\nprintln(\"Mean of chain: \")\nshow(stdout, \"text/plain\", mean(burnin_chain.x)); println(\" \"); \nshow(stdout, \"text/plain\", mean(final_chain.x)); println(\" \")\n\nprintln(\"Covariance of chain: \")\nshow(stdout, \"text/plain\", cov(final_chain.x))\nprintln(\" \")\nprintln(\"Acceptance rate: $(burnin_chain.diagnostics.acceptance_ratio[end])  $(final_chain.diagnostics.acceptance_ratio[end])\")\n", "meta": {"hexsha": "19ada64c4c9b2904e128ed277398ecbdcf3eb73c", "size": 1382, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_hmc.jl", "max_stars_repo_name": "cesmix-mit/PotentialUQ.jl", "max_stars_repo_head_hexsha": "66aa906f65a1f8fdb914c7659dc9ad1ea75061f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-07-14T15:42:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-19T03:23:06.000Z", "max_issues_repo_path": "test/test_hmc.jl", "max_issues_repo_name": "cesmix-mit/PotentialUQ.jl", "max_issues_repo_head_hexsha": "66aa906f65a1f8fdb914c7659dc9ad1ea75061f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_hmc.jl", "max_forks_repo_name": "cesmix-mit/PotentialUQ.jl", "max_forks_repo_head_hexsha": "66aa906f65a1f8fdb914c7659dc9ad1ea75061f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-15T23:29:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-15T23:29:36.000Z", "avg_line_length": 35.4358974359, "max_line_length": 127, "alphanum_fraction": 0.7460202605, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7611961877924567}}
{"text": "module Brick\n\nusing Base.Iterators\nusing LinearAlgebra\nusing Scapin.Elasticity\nusing Scapin.Grid\n\n\"\"\"\n    integrate(f, h)\n\nReturn the `d`-dimensional integral of `f` over `(0, h[1]) × (0, h[2]) × … × (0, h[d])`.\n\nUses 2-point Gauss-Legendre integration (tensorized over the `d` dimensions). `f` must\ntake a 1-dimensional array of size `d` as unique input. If `avg` is `true`, the\nfunction returns the `N`-dimensional average.\n\n\"\"\"\nfunction integrate(f, h::NTuple{d,T}; avg = false) where {d,T<:Number}\n    ξ = [-1 / √3, 1 / √3]\n    weight = (avg ? one(T) : prod(h)) / 2^d\n    return weight * sum(f, product((ξ .* h_ / 2 for h_ in h)...))\nend\n\n\n\"\"\"\n    shape(x, h)\n\nReturn the value of the shape functions of the element, at the specified point.\n\nThis function returns a `d`-dimensional array `N`, such that `N[p]` is the shape\nfunction associated with node `p`, evaluated at `x`. In particular, `N[p]`\nevaluated at node `q` is `δ[p, q]` (Kronecker).\n\n\"\"\"\nfunction shape(x::NTuple{d,T}, h::NTuple{d,T}) where {d,T<:Number}\n    ξ = 2 .* x ./ h\n    ℒ = cell_vertices(d)\n    return [prod((1 + (-1)^p[i] * ξ[i]) / 2 for i = 1:d) for p in ℒ]\nend\n\n\"\"\"\n    gradient_operator(x, h)\n\nReturn the gradient operator at the specified point.\n\nThis function returns a `(d+1)` dimensional array `D` of size `(d, 2, 2, …)`.\nIf  `i` is the index of a component and `p` the `CartesianIndex` of the node, then\n`D[i, p]` is the partial derivative of `N[p]` w.r.t. `x[i]`, evaluated at `x`.\n\n`h` is the size of the brick element.\n\n\"\"\"\nfunction gradient_operator(x::NTuple{d,T}, h::NTuple{d,T}) where {d,T<:Number}\n    ξ = 2 .* x ./ h\n    ℒ = cell_vertices(d)\n    return [\n        prod(j == i ? (-1)^n[j] / h[j] : (1 + (-1)^n[j] * ξ[j]) / 2 for j = 1:d) for\n        i = 1:d, n in ℒ\n    ]\nend\n\n\n\"\"\"\n    avg_gradient_operator(h)\n\nReturn the cell-average of the gradient operator.\n\n\"\"\"\nfunction avg_gradient_operator(h::NTuple{d,T}) where {d,T<:Number}\n    return integrate(x -> gradient_operator(x, h), h, avg = true)\nend\n\n\n\"\"\"\n    strain_displacement_operator(x, h)\n\nReturn the strain-displacement operator for the `d`-dimensional brick element of\nsize `h`, evaluated at point `x`.\n\nThis function returns a `(d+3)` dimensional array `B` of size `(d, d, 2, …, 2, d)`.\nIf `p` is the `CartesianIndex` of the node, and `i`, `j`, `k` are component\nindices then, the interpolated `(i, j)` component of the strain at `x` reads\n\n```\nε[i, j] = Σₖ Σₚ B[i, j, k, p] * u[k, p].\n```\n\n\"\"\"\nfunction strain_displacement_operator(x::NTuple{d,T}, h::NTuple{d,T}) where {d,T<:Number}\n    ℒ = cell_vertices(d)\n    D = gradient_operator(x, h)\n    B = zeros(T, d, d, d, fill(2, d)...)\n    for i = 1:d, j = 1:d, p ∈ ℒ\n        B[i, j, i, p] += D[j, p] / 2\n        B[i, j, j, p] += D[i, p] / 2\n    end\n    return B\nend\n\n\n\"\"\"\n    avg_strain_displacement_operator(h)\n\nReturn the cell average of the strain-displacement operator.\n\n\"\"\"\nfunction avg_strain_displacement_operator(h::NTuple{d,T}) where {d,T<:Number}\n    return integrate(x -> strain_displacement_operator(x, h), h, avg = true)\nend\n\n\n\"\"\"\n    stiffness_operator(h, C)\n\nReturn the stifness operator for the brick element of size `h`, and Hooke material `C`.\n\nThe stiffness operator `K` delivers the strain energy associated to the nodal\ndisplacements `u`\n\n```\nU = u[i, p] * K[i, p, j, q] * u[j, q] / 2,\n```\n\nwhere `i, j ∈ {1, …, d}` are component indices and `p, q ∈ CartesianIndices(1:2, …, 1:2)`.\n\n\"\"\"\nfunction stiffness_operator(h::NTuple{d,T}, C::Hooke{d,T}) where {d,T<:Number}\n    ℒ = cell_vertices(d)\n    function f(x)\n        D = gradient_operator(x, h)\n        B = strain_displacement_operator(x, h)\n        σε = Array{T}(undef, d, fill(2, d)..., d, fill(2, d)...)\n        for i = 1:d, p ∈ ℒ, j = 1:d, q ∈ ℒ\n            σε[i, p, j, q] =\n                C.λ * D[i, p] * D[j, q] +\n                2C.μ * sum(B[h, k, i, p] * B[h, k, j, q] for h = 1:d, k = 1:d)\n        end\n        return σε\n    end\n    integrate(f, h)\nend\n\n\n\"\"\"\n    global_strain_displacement_operator(N, h)\n\nReturn the global strain-displacement operator for periodic boundary conditions.\n\nThe grid is defined by its size `N` and its spacing `h`.\n\nThe global strain-displacement operator `B` is a `d+2`-dimensional array of size\n`(d, d, N[1], …, N[d])`, such that the average strain within element `p` reads\n\n```\nε[i, j, p] = B[i, j, p, k, q] * u[k, q],\n```\n\nwhere\n\n- `i, j, k ∈ {1, …, d}`: component indices,\n- `p, q ∈ CartesianIndices(1:N[1], …, 1:N[d])`: node indices,\n- `ε[i, j, p]`: `(i, j)`-th component of the average strain in element `p`,\n- `u[k, q]`: `i`-th component of the displacement of node `q`.\n\n!!! note\n\n    Assembly of the global strain-displacement operator is done under the\n    assumption of periodicity.\n\n\"\"\"\nfunction global_strain_displacement_operator(\n    N::NTuple{d,Int},\n    h::NTuple{d,T},\n) where {d,T<:Number}\n    Be = avg_strain_displacement_operator(h)\n    B = zeros(T, d, d, N..., d, N...)\n    𝓛 = cell_vertices(d) # Local node indices\n    for p ∈ CartesianIndices(N)\n        𝒢 = cell_vertices(p, N) # global node indices\n        for q ∈ 𝓛\n            B[:, :, p, :, 𝒢[q]] += Be[:, :, :, q]\n        end\n    end\n    return B\nend\n\n\n\"\"\"\n    global_stiffness_operator(N, h, μ, ν)\n\nReturn the global stiffness operator for periodic, homogeneous elasticity.\n\nThe grid size is `N`, the cell size is `h`. The constitutive material is\nhomogeneous, elastic linear and isotropic with stiffness `C`.\n\nThe global stiffness operator `K` is a `2d+2`-dimensional array of size\n`(d, N[1], …, N[d], d, N[1], …, N[d])`, such that the strain energy of the\nsystem reads\n\n```\nU = u[i, p] * K[i, p, j, q] * u[j, q] / 2,\n```\n\nwhere\n\n- `i, j ∈ {1, …, d}`: component indices,\n- `p, q ∈ CartesianIndices(1:N[1], …, 1:N[d])`: node indices,\n- `u[i, p]`: `i`-th component of the displacement of node `p`.\n\n!!! note\n\n    Assembly of the global stiffness opertor is done under the assumption of\n    periodicity.\n\n\"\"\"\nfunction global_stiffness_operator(\n    N::NTuple{d,Int},\n    h::NTuple{d,T},\n    C::Hooke{d,T},\n) where {d,T<:Number}\n    Ke = stiffness_operator(h, C)\n    K = zeros(T, d, N..., d, N...)\n    𝓛 = cell_vertices(d) # Local node indices\n    for e ∈ CartesianIndices(N)\n        𝒢 = cell_vertices(e, N) # global node indices\n        for m ∈ 𝓛, n ∈ 𝓛\n            K[:, 𝒢[m], :, 𝒢[n]] += Ke[:, m, :, n]\n        end\n    end\n    return K\nend\n\nexport integrate,\n    shape,\n    gradient_operator,\n    avg_gradient_operator,\n    strain_displacement_operator,\n    avg_strain_displacement_operator,\n    stiffness_operator,\n    global_strain_displacement_operator,\n    global_stiffness_operator\nend\n", "meta": {"hexsha": "a2daad97837c1a12c2ffcabe287742476a6b7177", "size": 6583, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Brick.jl", "max_stars_repo_name": "sbrisard/Scapin.jl", "max_stars_repo_head_hexsha": "7bd9a4ed36b3c9e8575dff384f34f9352e9e1845", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Brick.jl", "max_issues_repo_name": "sbrisard/Scapin.jl", "max_issues_repo_head_hexsha": "7bd9a4ed36b3c9e8575dff384f34f9352e9e1845", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-07-23T07:04:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T12:00:44.000Z", "max_forks_repo_path": "src/Brick.jl", "max_forks_repo_name": "sbrisard/Scapin.jl", "max_forks_repo_head_hexsha": "7bd9a4ed36b3c9e8575dff384f34f9352e9e1845", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0905349794, "max_line_length": 90, "alphanum_fraction": 0.6092966732, "num_tokens": 2157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7611961877412483}}
{"text": "#f(x,y)=mean(KL(x,sigmoid(y))), where KL is the Kullback-Leibler divergence\n\nFBinaryEntropyLossXsigmoidY(x,y)=([sum(x.*log(x)+(1.-x).*log(1.-x)-x.*y+log1pexp(y))/length(x)],nothing)\nFBinaryEntropyLossXsigmoidY_inplace(value,aux,x,y)=copy!(value,sum(x.*log(x)+(1.-x).*log(1.-x)-x.*y+log1pexp(y))/length(x))\n\nfunction DBinaryEntropyLossXsigmoidY(derivativeIDX,f_c,faux_c,grad_c,grad_n,x,y)\n    if derivativeIDX==1\n        axpy!(-grad_c[1]/length(x),y-log(x./(1-x)),grad_n)\n    elseif derivativeIDX==2\n        axpy!(grad_c[1]/length(x),sigmoid(y)-x,grad_n)\n    end\nend\n\n\nif PROC==\"GPU\"\n#    FBinaryEntropyLossXsigmoidY(x::CudaArray,y::CudaArray)=(binaryentropyXsigmoidY(x,y),nothing)\n    FBinaryEntropyLossXsigmoidY_inplace(value,aux,x::CudaArray,y::CudaArray)=binaryentropyXsigmoidY!(x,y,value)\n    \n    function DBinaryEntropyLossXsigmoidY(derivativeIDX,f_c,faux_c,grad_c,grad_n,x::CudaArray,y::CudaArray)\n        if derivativeIDX==1\n            DXbinaryentropyXsigmoidY!(x,y,grad_c,grad_n)\n        elseif derivativeIDX==2\n            DYbinaryentropyXsigmoidY!(x,y,grad_c,grad_n)\n        end\n    end\n\n#    FBinaryEntropyLossXsigmoidY_inplace(value,aux,x::CudaArray,y::CudaArray)=binaryentropyXsigmoidY!(x,y,value)\n    \n#    function DBinaryEntropyLossXsigmoidY(derivativeIDX,f_c,faux_c,grad_c,grad_n,x::CudaArray{Float64},y::CudaArray{Float64})\n#        if derivativeIDX==1\n#            DXbinaryentropyXsigmoidY!(x,y,grad_c,grad_n)\n#        elseif derivativeIDX==2\n#            DYbinaryentropyXsigmoidY!(x,y,grad_c,grad_n)\n#        end\n#    end\n   \n\n#    function DBinaryEntropyLossXsigmoidY(derivativeIDX,f_c,faux_c,grad_c::CudaArray{Float32},grad_n::CudaArray{Float32},x::CudaArray{Float32},y::CudaArray{Float32})\n#        if derivativeIDX==1\n#            DXbinaryentropyXsigmoidY_32!(x,y,grad_c,grad_n)\n#        elseif derivativeIDX==2\n#            DYbinaryentropyXsigmoidY_32!(x,y,grad_c,grad_n)\n#        end\n#    end    \n\n    \nend\n\n\n\n\nDerivative[FBinaryEntropyLossXsigmoidY]=DBinaryEntropyLossXsigmoidY\nInplace[FBinaryEntropyLossXsigmoidY]=FBinaryEntropyLossXsigmoidY_inplace\n\nBinaryKullbackLeiblerLossXsigmoidY(nx,ny)=ADnode(FBinaryEntropyLossXsigmoidY,[nx ny]) # give it a better name\nexport BinaryKullbackLeiblerLossXsigmoidY\n\n\n", "meta": {"hexsha": "36cde2f280ec5c884aee5c5ba5093b4b9caa89e6", "size": 2235, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/FBinaryKullbackLeiblerLossXsigmoidY.jl", "max_stars_repo_name": "davidbarber/AutoDiff", "max_stars_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2016-03-20T20:52:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T07:31:59.000Z", "max_issues_repo_path": "src/functions/FBinaryKullbackLeiblerLossXsigmoidY.jl", "max_issues_repo_name": "davidbarber/AutoDiff", "max_issues_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-06-17T20:12:48.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-17T20:12:48.000Z", "max_forks_repo_path": "src/functions/FBinaryKullbackLeiblerLossXsigmoidY.jl", "max_forks_repo_name": "davidbarber/AutoDiff", "max_forks_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-01-11T21:36:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-06T21:04:40.000Z", "avg_line_length": 37.8813559322, "max_line_length": 165, "alphanum_fraction": 0.722147651, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7611961877412483}}
{"text": "\"\"\"\n    solve_cubic(a, b, c, d)\n\nFinds real roots of a cubic equation\n```math\na x^3 + b x^2 + c x + d = 0\n```\n\nReturn Tuple{T, T, T} where first roots are real,\ncomplex roots are defined to `NaN`\n\nReference: J. F. Blinn, \"How to Solve a Cubic Equation, Part 5: Back to Numerics\",\nin IEEE Computer Graphics and Applications, vol. 27, no. 3, pp. 78-89, May-June 2007.\ndoi: 10.1109/MCG.2007.60\n\"\"\"\nfunction solve_cubic(a, b, c, d)\n    # convert to Ax³ + 3Bx² + 3Cx + D = 0\n    A, B, C, D = promote(float(a), float(b), float(c), float(d)) ./ (1, 3, 3, 1)\n    δ₁ = A * C - B * B\n    δ₂ = A * D - B * C\n    δ₃ = B * D - C * C\n    d13 = δ₁ * δ₃\n    d22 = δ₂ * δ₂\n    Δ = 4 * d13 - d22\n    nanvalue = zero(A) / zero(A)\n\n    if Δ < 0\n        At = Cb = Db = zero(A)  # A-tilde, C-bar, D-bar\n        if B^3 * D ≥ A * C^3\n            At, Cb, Db = A, δ₁, -2 * B * δ₁ + A * δ₂\n        else\n            At, Cb, Db = D, δ₃, -D * δ₂ + 2 * C * δ₃\n        end\n        T₀ = -copysign(At, Db) * sqrt(-Δ)\n        T₁ = -Db + T₀\n        p = cbrt(T₁ / 2)\n        q = T₁ == T₀ ? -p : -Cb / p\n        x₁ = Cb ≤ 0 ? p + q : -Db / (p^2 + q^2 + Cb)\n        x, w = B^3 * D ≥ A * C^3 ? (x₁ - B, A) : (-D, x₁ + C)\n        return (x/w, nanvalue, nanvalue)\n    else\n        δ₁ == δ₂ == δ₃ == 0 && return (-B/A, -B/A, -B/A)\n        sΔ = sqrt(Δ)\n        θA, θD = abs.(atan.((A*sΔ, 2*B*δ₁ - A*δ₂, D*sΔ, D*δ₂ - 2*C*δ₃)) ./ 3)\n        sCA, sCD = sqrt.(.-min.((δ₁, δ₃), 0))\n        x₁A, x₁D = 2 .* (sCA, sCD) .* cos.((θA, θD))\n        x₃A, x₃D = .-((sCA, sCD)) .* (cos.((θA, θD)) .+ sqrt(3) .* sin.((θA, θD)))\n        xlt = (x₁A + x₃A > 2 * B) ? x₁A : x₃A\n        xst = (x₁D + x₃D < 2 * C) ? x₁D : x₃D\n        xl, wl = xlt - B, A\n        xs, ws = -D, xst + C\n        E = wl * ws\n        F = -xl * ws - wl * xs\n        G = xl * xs\n        xm, wm = C * F - B * G, C * E - B * F\n        return (xs/ws, xm/wm, xl/wl)\n    end\nend\n\n\"\"\"\n    solve_cubic!(roots_::AbstractVector, a, b, c, d)\n\nFill first three items of `roots_` with the real roots of equation or `NaN`s.\n```math\na x^3 + b x^2 + c x + d = 0\n```\nSee also: [`solve_cubic`](@ref).\n\"\"\"\nBase.@propagate_inbounds function solve_cubic!(roots_::AbstractVector, a, b, c, d)\n    @view(roots_[1:3]) .= solve_cubic(a, b, c, d)\n    return roots_\nend\n", "meta": {"hexsha": "23202490bf0560ec7d99e2c849f2a5e749f8bfc0", "size": 2253, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solvecubic.jl", "max_stars_repo_name": "vvpisarev/CubicEoS", "max_stars_repo_head_hexsha": "686f7e97109e2d8266771ebaf7a61e2239cbabbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-04-15T07:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T23:10:45.000Z", "max_issues_repo_path": "src/solvecubic.jl", "max_issues_repo_name": "vvpisarev/MBWREoS.jl", "max_issues_repo_head_hexsha": "2e586648c5c098c05203f270503eaeee398f19c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2021-05-17T09:23:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T12:51:04.000Z", "max_forks_repo_path": "src/solvecubic.jl", "max_forks_repo_name": "vvpisarev/MBWREoS.jl", "max_forks_repo_head_hexsha": "2e586648c5c098c05203f270503eaeee398f19c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-18T08:10:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:26:40.000Z", "avg_line_length": 30.8630136986, "max_line_length": 85, "alphanum_fraction": 0.4656014203, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362858, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7611961861171724}}
{"text": "\"\"\"\nEstimates all parameters for a simple linear regression. \nSee also: [`sample_mean`](@ref), [`sum_of_squares`](@ref). \n\"\"\"\nfunction regression_linear_simple(x::Vector, y::Vector)\n    n = length(x)\n    x̅ = sample_mean(x)\n    y̅ = sample_mean(y)\n    SSE = sum_of_squares(y) - sum_of_squares(x, y)^2 / sum_of_squares(x) \n    SSR = sum_of_squares(x, y)^2 / sum_of_squares(x) \n    SST = SSR + SSR\n    R² = 1 - SSE / SST\n    s² = SSE / (n - 2)\n    β = sum_of_squares(x, y) / sum_of_squares(x) \n    α = y̅ - β * x̅\n    return Dict([(\"α\", α), (\"β\", β), (\"s²\", s²), (\"R²\", R²), (\"SST\", SST), (\"SSR\", SSR), (\"SSE\", SSE)]) \nend\n", "meta": {"hexsha": "8a4f8e2bcce206ba4d1d5e48a5fc4d1f32bc4009", "size": 621, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Regression.jl", "max_stars_repo_name": "persson-io/Stochastics.jl", "max_stars_repo_head_hexsha": "548c82646d786d9153015bd4a95fd2ea5e4861cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-02T19:01:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-02T19:01:17.000Z", "max_issues_repo_path": "src/Regression.jl", "max_issues_repo_name": "persson-io/Stochastics", "max_issues_repo_head_hexsha": "548c82646d786d9153015bd4a95fd2ea5e4861cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Regression.jl", "max_forks_repo_name": "persson-io/Stochastics", "max_forks_repo_head_hexsha": "548c82646d786d9153015bd4a95fd2ea5e4861cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5, "max_line_length": 104, "alphanum_fraction": 0.5716586151, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9566341987633822, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.7611537467258492}}
{"text": "## Activation functions\n#\n# Some of activation functions have its wrapper function for GPU in NNlibCUDA.jl.\n# https://github.com/JuliaGPU/CuArrays.jl/issues/614\n\nACTIVATIONS = [\n    :σ, :hardσ, :hardtanh, :relu,\n    :leakyrelu, :relu6, :rrelu, :elu, :gelu, :swish, :selu,\n    :celu, :softplus, :softsign, :logσ, :logcosh,\n    :mish, :tanhshrink, :softshrink, :trelu, :lisht,\n    :tanh_fast, :sigmoid_fast,\n    ]\n\nfor f in ACTIVATIONS\n    @eval export $(f)\nend\n\n# Aliases\nexport sigmoid, hardsigmoid, logsigmoid, thresholdrelu\n\n# of type float (to allow for integer inputs)\noftf(x, y) = oftype(float(x), y)\n\n\"\"\"\n    σ(x) = 1 / (1 + exp(-x))\n\nClassic [sigmoid](https://en.wikipedia.org/wiki/Sigmoid_function) activation\nfunction.\nUnicode `σ` can be entered as `\\\\sigma` then tab, in many editors.\nThe ascii name `sigmoid` is also exported.\n\nSee also [`sigmoid_fast`](@ref).\n\n```\njulia> lineplot(sigmoid, -5, 5, height=7)\n          ┌────────────────────────────────────────┐     \n        1 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⣀⡠⠤⠖⠒⠒⠋⠉⠉⠉⠉⠉⠉│ σ(x)\n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⢀⡠⠖⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│     \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⣀⠔⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│     \n   f(x)   │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⡏⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│     \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡔⠋⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│     \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠤⠊⠁⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│     \n        0 │⣀⣀⣀⣀⣀⣀⣀⠤⠤⠤⠒⠊⠉⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│     \n          └────────────────────────────────────────┘     \n          ⠀-5⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀5⠀     \n          ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀     \n\njulia> sigmoid === σ\ntrue\n```\n\"\"\"\nfunction σ(x)\n    t = exp(-abs(x))\n    ifelse(x ≥ 0, inv(1 + t), t / (1 + t))\nend\n\nconst sigmoid = σ\n\n\"\"\"\n    hardσ(x) = max(0, min(1, (x + 3) / 6))\n\nPiecewise linear approximation of [`sigmoid`](@ref).\n\n```\njulia> lineplot(hardsigmoid, -5, 5, height=7)\n          ┌────────────────────────────────────────┐         \n        1 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⢀⡠⠖⠋⠉⠉⠉⠉⠉⠉⠉⠉│ hardσ(x)\n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⣀⡤⠒⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⡠⠔⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n   f(x)   │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡤⡗⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠔⠊⠁⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡤⠖⠋⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n        0 │⣀⣀⣀⣀⣀⣀⣀⣀⣀⠤⠊⠁⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n          └────────────────────────────────────────┘         \n          ⠀-5⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀5⠀         \n          ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀         \n\njulia> lineplot(sigmoid, -5, 5, height=7)\n          ┌────────────────────────────────────────┐     \n        1 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⣀⡠⠤⠖⠒⠒⠋⠉⠉⠉⠉⠉⠉│ σ(x)\n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⢀⡠⠖⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│     \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⣀⠔⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│     \n   f(x)   │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⡏⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│     \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡔⠋⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│     \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠤⠊⠁⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│     \n        0 │⣀⣀⣀⣀⣀⣀⣀⠤⠤⠤⠒⠊⠉⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│     \n          └────────────────────────────────────────┘     \n          ⠀-5⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀5⠀     \n          ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀     \n```\n\"\"\"\nhardσ(x) = clamp((x + 3) / 6, 0, 1)\n\n# https://pytorch.org/docs/stable/generated/torch.nn.Hardsigmoid.html\n\nconst hardsigmoid = hardσ\n\n\"\"\"\n    logσ(x)\n\nReturn `log(σ(x))` which is computed in a numerically stable way.\n\n```\njulia> lineplot(logsigmoid, -5, 5, height=7)\n           ┌────────────────────────────────────────┐        \n         0 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡧⠤⠔⠒⠒⠒⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉│ logσ(x)\n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡤⠖⠊⠉⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠤⠒⠉⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n   f(x)    │⠀⠀⠀⠀⠀⠀⢀⡤⠖⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n           │⠀⠀⠀⣀⠔⠊⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n           │⡤⠖⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n        -6 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n           └────────────────────────────────────────┘        \n           ⠀-5⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀5⠀        \n           ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀        \n```\n\"\"\"\nlogσ(x) = -softplus(-x)\n\nconst logsigmoid = logσ\n\n\"\"\"\n    hardtanh(x) = max(-1, min(1, x))\n\nSegment-wise linear approximation of `tanh`, much cheaper to compute.\nSee [\"Large Scale Machine Learning\"](https://ronan.collobert.com/pub/matos/2004_phdthesis_lip6.pdf).\n\nSee also [`tanh_fast`](@ref).\n```\njulia> lineplot(hardtanh, -2, 2, height=7)\n           ┌────────────────────────────────────────┐            \n         1 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⣀⠔⠋⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉│ hardtanh(x)\n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⣀⡤⠊⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⢀⡤⠊⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n   f(x)    │⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⢤⡤⡷⠥⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤│            \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠖⠁⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠖⠋⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n        -1 │⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⠔⠋⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n           └────────────────────────────────────────┘            \n           ⠀-2⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀2⠀            \n           ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x\n\njulia> lineplot(tanh, -2, 2, height=7)\n           ┌────────────────────────────────────────┐        \n         1 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⣀⡠⠤⠤⠒⠒⠒⠊⠉⠉⠉│ tanh(x)\n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⢀⡠⠔⠊⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⢀⡤⠒⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n   f(x)    │⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⢤⡤⡷⠥⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤│        \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡤⠖⠁⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡠⠔⠊⠁⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n        -1 │⣀⣀⣀⡠⠤⠤⠤⠖⠒⠊⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n           └────────────────────────────────────────┘        \n           ⠀-2⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀2⠀        \n           ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀        \n```\n\"\"\"\nhardtanh(x) = clamp(x, oftype(x, -1), oftype(x, 1))  # clamp(x, -1, 1) is type-stable, but would promote Int32, for which we have tests\n\n\"\"\"\n    relu(x) = max(0, x)\n\n[Rectified Linear Unit](https://en.wikipedia.org/wiki/Rectifier_(neural_networks))\nactivation function.\n\n```\njulia> lineplot(relu, -2, 2, height=7)\n          ┌────────────────────────────────────────┐        \n        2 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠔⠋│ relu(x)\n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡤⠊⠁⠀⠀│        \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡤⠊⠁⠀⠀⠀⠀⠀│        \n   f(x)   │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⢀⡤⠖⠁⠀⠀⠀⠀⠀⠀⠀⠀│        \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⡠⠖⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⡠⠖⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n        0 │⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣇⠔⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n          └────────────────────────────────────────┘        \n          ⠀-2⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀2⠀        \n          ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀        \n```\n\"\"\"\nrelu(x) = ifelse(x<0, zero(x), x)  # faster than max(zero(x), x), still preserves NaN\n\n\"\"\"\n    leakyrelu(x, a=0.01) = max(a*x, x)\n\nLeaky [Rectified Linear Unit](https://en.wikipedia.org/wiki/Rectifier_(neural_networks))\nactivation function.\nYou can also specify the coefficient explicitly, e.g. `leakyrelu(x, 0.01)`.\n\n```julia\njulia> lineplot(x -> leakyrelu(x, 0.5), -2, 2, height=7)\n           ┌────────────────────────────────────────┐       \n         2 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠤⠒⠉│ #42(x)\n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡠⠔⠊⠉⠀⠀⠀⠀│       \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⣀⡤⠖⠊⠁⠀⠀⠀⠀⠀⠀⠀⠀│       \n   f(x)    │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⣀⠤⠖⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│       \n           │⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⣤⣤⡤⡧⠶⠭⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤│       \n           │⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣀⠤⠤⠒⠒⠋⠉⠁⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│       \n        -1 │⣀⣀⠤⠤⠒⠒⠊⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│       \n           └────────────────────────────────────────┘       \n           ⠀-2⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀2⠀       \n           ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀       \n\njulia> leakyrelu(-10f0, 1//5)\n-2.0f0\n\njulia> leakyrelu(-10f0, 1//20)\n-0.5f0\n```\n\"\"\"\nleakyrelu(x, a=oftf(x, 0.01)) = ifelse(x>0, float(x), oftf(x, a*x))  # max(a*x, x) is 3x slower\n\n\"\"\"\n    relu6(x) = min(max(0, x), 6)\n\n[Rectified Linear Unit](https://en.wikipedia.org/wiki/Rectifier_(neural_networks))\nactivation function capped at 6.\nSee [\"Convolutional Deep Belief Networks\"](https://www.cs.toronto.edu/~kriz/conv-cifar10-aug2010.pdf) from CIFAR-10.\n\n```\njulia> lineplot(relu6, -10, 10, height=7)\n          ┌────────────────────────────────────────┐         \n        6 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠎⠉⠉⠉⠉⠉⠉⠉⠉│ relu6(x)\n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⢀⡔⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⡤⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n   f(x)   │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⡠⠎⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⢀⠖⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⡔⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n        0 │⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⡧⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n          └────────────────────────────────────────┘         \n          ⠀-10⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀10⠀         \n          ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀         \n```\n\"\"\"\nrelu6(x) = clamp(x, oftype(x, 0), oftype(x, 6))  # clamp promotes, but clamp(x, 0, 6) would promote x::Int32\n\n\"\"\"\n    rrelu(x, lo=1/8, hi=1/3) = max(a*x, x)\n    # where `a` is randomly sampled from uniform distribution `U(lo, hi)`\n\nRandomized Leaky Rectified Linear Unit activation function.\nSee [\"Empirical Evaluation of Rectified Activations\"](https://arxiv.org/abs/1505.00853)\nYou can also specify the bound explicitly, e.g. `rrelu(x, 0.0, 1.0)`.\n\n```julia\njulia> lineplot(rrelu, -20, 10, height=7)\n            ┌────────────────────────────────────────┐         \n         10 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡤⠖⠋│ rrelu(x)\n            │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⠀⠀⠀⠀⢀⡠⠖⠋⠁⠀⠀⠀│         \n            │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⢀⡠⠔⠊⠁⠀⠀⠀⠀⠀⠀⠀│         \n   f(x)     │⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⢤⡤⠤⣤⣤⢤⣤⣤⠤⠤⠤⢼⠮⠥⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤│         \n            │⣰⢀⣆⡄⣄⡄⡠⡰⠦⠷⡜⢢⠷⠳⠢⠊⠉⠉⠀⠀⠁⠀⠀⠀⠀⠀⢸⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n            │⠃⠉⠙⠘⠃⠈⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n        -10 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n            └────────────────────────────────────────┘         \n            ⠀-20⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀10⠀         \n            ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀         \n\njulia> extrema(rrelu.(fill(-10f0, 1000)))\n(-3.3316886f0, -1.2548422f0)\n```\n\"\"\"\nfunction rrelu(x::T, l=1//8, u=1//3) where T<:Number\n    a = (u - l) * rand(float(T)) + l\n    return leakyrelu(x, a)\nend\n\n\"\"\"\n    elu(x, α=1) = x > 0 ? x : α * (exp(x) - 1)\n\nExponential Linear Unit activation function.\nSee [\"Fast and Accurate Deep Network Learning by Exponential Linear Units\"](https://arxiv.org/abs/1511.07289).\nYou can also specify the coefficient explicitly, e.g. `elu(x, 1)`.\n\n```\njulia> lineplot(elu, -2, 2, height=7)\n           ┌────────────────────────────────────────┐       \n         2 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠤⠒⠉│ elu(x)\n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡠⠔⠊⠉⠀⠀⠀⠀│       \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⣀⡤⠖⠊⠁⠀⠀⠀⠀⠀⠀⠀⠀│       \n   f(x)    │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⣀⠤⠖⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│       \n           │⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⢤⡤⡧⠶⠭⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤│       \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣀⠤⠔⠒⠋⠁⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│       \n        -1 │⠤⠤⠤⠤⠔⠒⠒⠒⠊⠉⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│       \n           └────────────────────────────────────────┘       \n           ⠀-2⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀2⠀       \n           ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀       \n\njulia> elu(-10f0)\n-0.9999546f0\n\njulia> elu(-10f0, 2)\n-1.9999092f0\n```\n\"\"\"\nelu(x, α=1) = ifelse(x ≥ 0, float(x), α * (exp(x) - 1))\n\nderiv_elu(Ω, α=1) = ifelse(Ω ≥ 0, one(Ω), Ω + α)\n\n\"\"\"\n    gelu(x) = 0.5x * (1 + tanh(√(2/π) * (x + 0.044715x^3)))\n\nActivation function from [\"Gaussian Error Linear Units\"](https://arxiv.org/abs/1606.08415).\n\n```\njulia> lineplot(gelu, -2, 2, height=7)\n           ┌────────────────────────────────────────┐        \n         2 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡠⠔⠊│ gelu(x)\n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠔⠊⠁⠀⠀⠀│        \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⣀⠤⠒⠉⠀⠀⠀⠀⠀⠀⠀│        \n   f(x)    │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⣀⡠⠤⠒⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n           │⣤⣤⣤⣤⣤⣤⣤⣤⡤⠤⠤⠤⠤⠤⠤⠤⣤⣤⣤⡤⡧⠶⠶⠭⠥⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤│        \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠉⠉⠉⠉⠉⠉⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n        -1 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n           └────────────────────────────────────────┘        \n           ⠀-2⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀2⠀        \n           ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀        \n```\n\"\"\"\nfunction gelu(x)\n    α = oftf(x, 0.044715)\n    λ = oftf(x, gelu_λ)\n    x/2 * (1 + tanh(λ * (x + α * x^3)))\nend\n\nconst gelu_λ = √(2 / π)\n\n\"\"\"\n    swish(x) = x * σ(x)\n\nSelf-gated activation function.\nSee [\"Swish: a Self-Gated Activation Function\"](https://arxiv.org/abs/1710.05941).\n\n```\njulia> lineplot(swish, -2, 2, height=7)\n           ┌────────────────────────────────────────┐         \n         2 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡤│ swish(x)\n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡤⠖⠋⠁⠀│         \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠤⠖⠋⠁⠀⠀⠀⠀⠀│         \n   f(x)    │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⢀⣀⡤⠔⠊⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n           │⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⢤⣤⣤⡤⡧⠴⠶⠯⠥⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤│         \n           │⠉⠑⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠉⠉⠉⠉⠁⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n        -1 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n           └────────────────────────────────────────┘         \n           ⠀-2⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀2⠀         \n           ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀         \n```\n\"\"\"\nswish(x) = x * σ(x)\n\n\"\"\"\n    lisht(x) = x * tanh(x)\n\nActivation function from \n[\"LiSHT: Non-Parametric Linearly Scaled Hyperbolic Tangent ...\"](https://arxiv.org/abs/1901.05894)\n\n```\njulia> lineplot(lisht, -2, 2, height=7)\n          ┌────────────────────────────────────────┐         \n        2 │⠢⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠔│ lisht(x)\n          │⠀⠈⠑⢦⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡤⠊⠁⠀│         \n          │⠀⠀⠀⠀⠈⠣⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠔⠁⠀⠀⠀⠀│         \n   f(x)   │⠀⠀⠀⠀⠀⠀⠀⠑⢆⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠁⠀⠀⠀⠀⠀⠀│         \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠢⡄⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⢀⠔⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠓⢄⡀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⢀⡠⠖⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n        0 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠓⠦⣄⣀⣀⣇⣀⣀⠤⠒⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n          └────────────────────────────────────────┘         \n          ⠀-2⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀2⠀         \n          ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀         \n```\n\"\"\"\nlisht(x) = x * tanh(x)\n\n\"\"\"\n    selu(x) = λ * (x ≥ 0 ? x : α * (exp(x) - 1))\n\n    λ ≈ 1.05070...\n    α ≈ 1.67326...\n\nScaled exponential linear units.\nSee [\"Self-Normalizing Neural Networks\"](https://arxiv.org/abs/1706.02515).\n\n```\njulia> lineplot(selu, -2, 2, height=7)\n           ┌────────────────────────────────────────┐        \n         3 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│ selu(x)\n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡠⠤⠔⠒│        \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⣀⣀⠤⠔⠒⠋⠉⠀⠀⠀⠀⠀│        \n   f(x)    │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⢀⣀⡤⠤⠒⠊⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n           │⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⣉⡩⠭⠛⡏⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉│        \n           │⠀⠀⠀⠀⠀⠀⠀⣀⣀⣀⡤⠤⠔⠒⠊⠉⠁⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n        -2 │⠒⠒⠉⠉⠉⠉⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n           └────────────────────────────────────────┘        \n           ⠀-2⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀2⠀        \n           ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀        \n\njulia> selu(-10f0)\n-1.7580194f0\n```\n\"\"\"\nfunction selu(x)\n    λ = oftf(x, selu_λ)\n    α = oftf(x, selu_α)\n    λ * ifelse(x > 0, x, α * (exp(x) - 1))\nend\n\nconst selu_λ = 1.0507009873554804934193349852946\nconst selu_α = 1.6732632423543772848170429916717\n\nfunction deriv_selu(Ω)\n    λ = oftf(Ω, selu_λ)\n    α = oftf(Ω, selu_α)\n    ifelse(Ω > 0, λ, Ω + α * λ)\nend\n\n\"\"\"\n    celu(x, α=1) = x ≥ 0 ? x : α * (exp(x/α) - 1)\n\nActivation function from [\"Continuously Differentiable Exponential Linear Units\"](https://arxiv.org/abs/1704.07483).\n\n```\njulia> lineplot(celu, -2, 2, height=7)\n           ┌────────────────────────────────────────┐        \n         2 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠤⠒⠉│ celu(x)\n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡠⠔⠊⠉⠀⠀⠀⠀│        \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⣀⡤⠖⠊⠁⠀⠀⠀⠀⠀⠀⠀⠀│        \n   f(x)    │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⣀⠤⠖⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n           │⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⢤⡤⡧⠶⠭⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤│        \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣀⠤⠔⠒⠋⠁⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n        -1 │⠤⠤⠤⠤⠔⠒⠒⠒⠊⠉⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n           └────────────────────────────────────────┘        \n           ⠀-2⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀2⠀        \n           ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀        \n\njulia> celu(-10f0)\n-0.9999546f0\n```\n\"\"\"\ncelu(x, α=1) = ifelse(x ≥ 0, float(x), α * (exp(x/α) - 1))\n\n\"\"\"\n    trelu(x, theta=1) = x > theta ? x : 0\n\nThreshold gated rectified linear activation function.\nSee [\"Zero-bias autoencoders and the benefits of co-adapting features\"](https://arxiv.org/abs/1402.3337)\n\n```\njulia> lineplot(trelu, -2, 4, height=7)\n          ┌────────────────────────────────────────┐         \n        4 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡤⠖⠋│ trelu(x)\n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡠⠖⠋⠁⠀⠀⠀│         \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡠⠔⠊⠁⠀⠀⠀⠀⠀⠀⠀│         \n   f(x)   │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠴⠊⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⣠⠤⠒⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⡏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n        0 │⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣀⣀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│         \n          └────────────────────────────────────────┘         \n          ⠀-2⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀4⠀         \n          ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀         \n```\n\"\"\"\ntrelu(x, theta=1) = ifelse(x <= theta, zero(x), x)\n\nconst thresholdrelu = trelu\n\n\"\"\"\n    softsign(x) = x / (1 + |x|)\n\nSee [\"Quadratic Polynomials Learn Better Image Features\"](http://www.iro.umontreal.ca/~lisa/publications2/index.php/attachments/single/205) (2009).\n\n```\njulia> lineplot(softsign, -5, 5, height=7)\n           ┌────────────────────────────────────────┐            \n         1 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⣀⣀⣀⠤⠤⠤⠤⠤│ softsign(x)\n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⣀⡤⠖⠒⠋⠉⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⡔⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n   f(x)    │⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⢤⡯⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤│            \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠔⠁⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⣀⠤⠤⠒⠋⠁⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n        -1 │⠒⠒⠒⠒⠒⠊⠉⠉⠉⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n           └────────────────────────────────────────┘            \n           ⠀-5⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀5⠀            \n           ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀            \n\njulia> lineplot!(ans, tanh)\n           ┌────────────────────────────────────────┐            \n         1 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⢀⡤⠖⠊⠉⠉⠉⣉⣉⣉⣉⣉⠭⠭⠭⠭⠭│ softsign(x)\n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⡔⣃⡤⠖⠒⠋⠉⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀│ tanh(x)    \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣧⡞⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n   f(x)    │⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⢤⡯⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤│            \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡴⠃⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⣀⠤⠤⠒⢋⠕⠁⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n        -1 │⣒⣒⣒⣒⣒⣊⣉⣉⣉⣉⣁⣀⣀⡠⠤⠒⠁⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n           └────────────────────────────────────────┘            \n           ⠀-5⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀5⠀            \n           ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀            \n\njulia> softsign(1f0)\n0.5f0\n\njulia> softsign(100f0)\n0.990099f0\n```\n\"\"\"\nsoftsign(x) = x / (1 + abs(x))\n\n\"\"\"\n    softplus(x) = log(exp(x) + 1)\n\nSee [\"Deep Sparse Rectifier Neural Networks\"](http://proceedings.mlr.press/v15/glorot11a/glorot11a.pdf), JMLR 2011.\n\n```\njulia> lineplot(softplus, -3, 3, height=7)\n          ┌────────────────────────────────────────┐            \n        4 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│ softplus(x)\n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡠│            \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡠⠔⠊⠁⠀│            \n   f(x)   │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡤⠔⠊⠁⠀⠀⠀⠀⠀│            \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⣀⡠⠤⠒⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⡧⠤⠒⠊⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n        0 │⣀⣀⣀⣀⣀⣀⣀⡠⠤⠤⠤⠤⠔⠒⠒⠚⠉⠉⠁⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n          └────────────────────────────────────────┘            \n          ⠀-3⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀3⠀            \n          ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀            \n\njulia> lineplot!(ans, relu)\n          ┌────────────────────────────────────────┐            \n        4 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│ softplus(x)\n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣠│ relu(x)    \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣠⡴⠞⠋⠁│            \n   f(x)   │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⡴⠞⠋⠁⠀⠀⠀⠀│            \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⣀⡠⢤⡲⠝⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀│            \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⡧⠤⠒⠊⣉⠥⠚⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n        0 │⣀⣀⣀⣀⣀⣀⣀⣠⣤⣤⣤⣤⣔⣒⣒⣚⣉⣉⣁⣀⣇⠴⠒⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│            \n          └────────────────────────────────────────┘            \n          ⠀-3⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀3⠀            \n          ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀            \n\njulia> softplus(16f0)\n16.0f0\n```\n\"\"\"\nsoftplus(x) = log1p(exp(-abs(x))) + max(x, 0)\n\n\"\"\"\n    logcosh(x)\n\nReturn `log(cosh(x))` which is computed in a numerically stable way.\n\n```\njulia> lineplot(logcosh, -5, 5, height=7)\n          ┌────────────────────────────────────────┐           \n        5 │⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│ logcosh(x)\n          │⠉⠢⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠔⠋│           \n          │⠀⠀⠀⠑⠢⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠔⠊⠁⠀⠀│           \n   f(x)   │⠀⠀⠀⠀⠀⠀⠑⠦⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡤⠊⠁⠀⠀⠀⠀⠀│           \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠑⠦⡀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⢀⡤⠊⠁⠀⠀⠀⠀⠀⠀⠀⠀│           \n          │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠓⠦⡀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⢀⡤⠒⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│           \n        0 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠑⠢⢄⣀⣀⣇⣀⡠⠔⠊⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│           \n          └────────────────────────────────────────┘           \n          ⠀-5⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀5⠀           \n          ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀           \n```\n\"\"\"\nlogcosh(x) = x + softplus(-2x) - oftf(x, log2)\n\nconst log2 = log(2)\n\n\"\"\"\n    mish(x) = x * tanh(softplus(x))\n\nActivation function from [\"Mish: A Self Regularized Non-Monotonic Neural Activation Function\"](https://arxiv.org/abs/1908.08681).\n\n```\njulia> lineplot(mish, -5, 5, height=7)\n           ┌────────────────────────────────────────┐        \n         5 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡠⠖⠋│ mish(x)\n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡤⠒⠁⠀⠀⠀│        \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠔⠋⠁⠀⠀⠀⠀⠀⠀│        \n   f(x)    │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⢀⡠⠖⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⢀⡤⠖⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n           │⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣧⣔⣊⣁⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀│        \n        -1 │⠀⠀⠀⠀⠀⠀⠀⠀⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│        \n           └────────────────────────────────────────┘        \n           ⠀-5⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀5⠀        \n           ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀        \n```\n\"\"\"\nmish(x) = x * tanh(softplus(x))\n\n\"\"\"\n    tanhshrink(x) = x - tanh(x)\n\nSee [\"Tanhshrink Activation Function\"](https://www.gabormelli.com/RKB/Tanhshrink_Activation_Function).\n\n```\njulia> lineplot(tanhshrink, -3, 3, height=7)\n           ┌────────────────────────────────────────┐              \n         3 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│ tanhshrink(x)\n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡠⠤⠖⠊│              \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⢀⣀⡠⠤⠒⠊⠉⠁⠀⠀⠀⠀│              \n   f(x)    │⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⢤⣤⡤⠤⠤⠤⠤⠤⠤⡷⠶⠶⠶⠶⠶⠮⠭⠥⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤│              \n           │⠀⠀⠀⠀⠀⣀⡠⠴⠒⠊⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│              \n           │⡠⠴⠒⠊⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│              \n        -3 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│              \n           └────────────────────────────────────────┘              \n           ⠀-3⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀3⠀              \n           ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀              \n\njulia> tanhshrink.((-10f0, 10f0))\n(-9.0f0, 9.0f0)\n```\n\"\"\"\ntanhshrink(x) = x - tanh(x)\n\n\"\"\"\n    softshrink(x, λ=0.5) =\n        (x ≥ λ ? x - λ : (-λ ≥ x ? x + λ : 0))\n\nSee [\"Softshrink Activation Function\"](https://www.gabormelli.com/RKB/Softshrink_Activation_Function).\n\n```\njulia> lineplot(softshrink, -2, 2, height=7)\n           ┌────────────────────────────────────────┐              \n         2 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀│ softshrink(x)\n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡤⠔⠒⠉⠁│              \n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⣀⡤⠤⠒⠋⠁⠀⠀⠀⠀⠀⠀│              \n   f(x)    │⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⣤⡤⠤⠤⠤⠤⠤⠤⡧⠤⠤⠤⠤⠶⠮⠭⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤│              \n           │⠀⠀⠀⠀⠀⠀⢀⣀⠤⠖⠒⠉⠁⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│              \n           │⠀⣀⠤⠔⠒⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│              \n        -2 │⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│              \n           └────────────────────────────────────────┘              \n           ⠀-2⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀2⠀              \n           ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀              \n\njulia> lineplot!(ans, tanhshrink)\n           ┌────────────────────────────────────────┐              \n         2 │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀│ softshrink(x)\n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡤⠔⠒⣉⡡│ tanhshrink(x)\n           │⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⣀⡤⠤⣒⣋⠥⠤⠒⠊⠉⠁⠀│              \n   f(x)    │⠤⠤⠤⠤⠤⠤⠤⠤⠤⣤⣤⣤⣤⡤⠤⠤⠤⠤⠤⠤⡷⠶⠶⠶⠶⠶⠾⠿⠯⠭⠭⠤⠤⠤⠤⠤⠤⠤⠤⠤│              \n           │⠀⢀⣀⡠⠤⠖⢒⣋⠭⠗⠒⠉⠁⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│              \n           │⠊⣉⠤⠔⠒⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│              \n        -2 │⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀│              \n           └────────────────────────────────────────┘              \n           ⠀-2⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀2⠀              \n           ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀x⠀\n\njulia> softshrink.((-10f0, 10f0))\n(-9.5f0, 9.5f0)\n```\n\"\"\"\nsoftshrink(x, λ=oftf(x, 0.5)) = min(max(0, x - λ), x + λ)\n\n# Provide an informative error message if activation functions are called with an array\nfor f in ACTIVATIONS\n    @eval $(f)(x::AbstractArray, args...) =\n      error(\"Use broadcasting (`\", $(string(f)), \".(x)`) to apply activation functions to arrays.\")\nend\n\n## Faster, less accurate, versions of some.\n\n\"\"\"\n    tanh_fast(x)\n\nThis is a faster but slighly less accurate version of `tanh`.\n\nWhere Julia's `tanh` function has an error under 2 eps, this\nmay be wrong by 5 eps, a reduction by less than one decimal digit. \n\nFor `x::Float32` this is usually about 10 times faster,\nwith a smaller speedup for `x::Float64`.\nFor any other number types, it just calls `tanh`.\n\nSee also [`sigmoid_fast`](@ref).\n\n```\njulia> tanh(0.5f0)\n0.46211717f0\n\njulia> tanh_fast(0.5f0)\n0.46211714f0\n\njulia> hard_tanh(0.5f0)\n0.5f0\n```\n\"\"\"\n@inline function tanh_fast(x::Float32)\n    x2 = abs2(x)\n    n = evalpoly(x2, (1.0f0, 0.1346604f0, 0.0035974074f0, 2.2332108f-5, 1.587199f-8))\n    d = evalpoly(x2, (1.0f0, 0.4679937f0, 0.026262015f0, 0.0003453992f0, 8.7767893f-7))\n    ifelse(x2 < 66f0, x * (n / d), sign(x))\nend\n\n@inline function tanh_fast(x::Float64)\n    exp2x = @fastmath exp(x + x)\n    y = (exp2x - 1) / (exp2x + 1) \n    # That has large errors near zero; using `expm1` would more accurate, but about as slow as `tanh`.\n    # Instead, we switch to a polynomial, which is very accurate within its range:\n    x2 = x * x\n    ypoly = x * evalpoly(x2, (1.0, -0.33333333333324583, 0.13333333325511604, -0.05396823125794372, 0.02186660872609521, -0.008697141630499953))\n    ifelse(x2 > 900.0, sign(y), ifelse(x2 < 0.017, oftype(y, ypoly), y))\nend\n\n# These approximations are very badly behaved for Float16; none are fast.\n# They are also a bit slower with ForwardDiff.Dual numbers, let's use Base:\ntanh_fast(x::Real) = Base.tanh(x)\n\n\"\"\"\n    sigmoid_fast(x)\n\nThis is a faster, and very slightly less accurate, version of `sigmoid`.\nFor `x::Float32, perhaps 3 times faster, and maximum errors 2 eps instead of 1.\n\nSee also [`tanh_fast`](@ref).\n\n```\njulia> sigmoid(0.2f0)\n0.54983395f0\n\njulia> sigmoid_fast(0.2f0)\n0.54983395f0\n\njulia> hardσ(0.2f0)\n0.53333336f0\n```\n\"\"\"\n@inline function sigmoid_fast(x::Real)\n    t = @fastmath exp(-abs(x))\n    y = ifelse(x ≥ 0, inv(1 + t), t / (1 + t))\n    ifelse(x > 40, one(y), ifelse(x < -80, zero(y), y))\nend\n# For x::Float32, this is not as quick as the rational tanh_fast(x) above,\n# but that polynomial has poor relative accuracy for negative x.\n\nsigmoid_fast(x::Float16) = sigmoid(x)  # sigmoid_fast is extremely badly behaved at large x\n\n## Define rrules for some activation functions, along with the\n## broadcasted rrule activation functions.\n## TODO: add to the lists below all activations.\n\n## This is a performance hack specifically for Zygote, because it doesn't handle fused\n## broadcasts well; but it generally should be good (or at least harmless) for any AD, as\n## it saves ADing the broadcasting machinery.\n## Related Issue https://github.com/JuliaDiff/ChainRulesCore.jl/issues/271\n\nUNARY_ACTS = [ # f, df\n    (:relu,         :(x > 0)),\n    (:hardtanh,     :(-1 < x < 1)),\n    (:selu,         :(deriv_selu(Ω))),\n    (:σ,            :(conj(Ω * (1 - Ω)))),\n    (:elu,          :(deriv_elu(Ω))),\n    (:softplus,     :(σ(x))),\n\n    (:tanh_fast,    :(conj(1 - Ω^2))),\n    (:sigmoid_fast, :(conj(Ω * (1 - Ω)))),\n    ]\n\nfor (f, df) in UNARY_ACTS\n    @eval @scalar_rule($f(x), $df)\n\n    pullback = Symbol(:broadcasted_, f, :_pullback)\n    @eval function rrule(::typeof(broadcasted),\n                         ::typeof($f), x::Numeric)\n        Ω = $f.(x)\n        function $pullback(Δ)\n            x_thunk = InplaceableThunk(\n                dx -> @.(dx += Δ * $df),\n                @thunk @.(Δ * $df)\n            )\n            NoTangent(), NoTangent(), x_thunk\n        end\n        return Ω, $pullback\n    end\nend\n\nBINARY_ACTS = [ # f, df1, df2\n    (:elu, :(deriv_elu(Ω, x2)), :(NoTangent())), # TODO use real deriv instead of DNE\n    ]\n\nfor (f, df1, df2) in BINARY_ACTS\n    @eval @scalar_rule($f(x1, x2), ($df1, $df2))\n\n    pullback = Symbol(:broadcasted_, f, :_pullback)\n    @eval function rrule(::typeof(broadcasted),\n                         ::typeof($f), \n                         x1::Numeric, x2::Numeric)\n        Ω = $f.(x1, x2)\n        function $pullback(Δ) \n            NoTangent(), NoTangent(), @.(Δ * $df1), @.(Δ * $df2)\n        end\n        return Ω, $pullback\n    end\nend\n", "meta": {"hexsha": "3f49978a5c30651e9b32ea4c998d6231ea7cbf48", "size": 30611, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/activations.jl", "max_stars_repo_name": "maxfreu/NNlib.jl", "max_stars_repo_head_hexsha": "063992bc295568551395207f99e135dd1e802138", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/activations.jl", "max_issues_repo_name": "maxfreu/NNlib.jl", "max_issues_repo_head_hexsha": "063992bc295568551395207f99e135dd1e802138", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-09T19:34:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-09T19:34:17.000Z", "max_forks_repo_path": "src/activations.jl", "max_forks_repo_name": "maxfreu/NNlib.jl", "max_forks_repo_head_hexsha": "063992bc295568551395207f99e135dd1e802138", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5528967254, "max_line_length": 147, "alphanum_fraction": 0.2721570677, "num_tokens": 15680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.761126444495001}}
{"text": "using DynamicalSystems, BenchmarkTools, StaticArrays\n\nds = Systems.towel()\n\nfunction lyapunovspectrum_normal(ds::DiscreteDS, N::Real; Ttr::Real = 100)\n\n    u = evolve(ds, Ttr)\n    D = length(u)\n    eom = ds.eom\n    jac = ds.jacob\n\n    # Initialization\n    λ = zeros(eltype(u), D)\n    Q = @SMatrix eye(eltype(u), D)\n    K = copy(Q)\n    # Main algorithm\n    for i in 1:N\n        u = eom(u)\n        K = jac(u)*Q\n\n        Q, R = DynamicalSystems.qr_sq(K)\n        for i in 1:D\n            λ[i] += log(abs(R[i, i]))\n        end\n    end\n    λ./N\nend\n\nfunction lyapunovspectrum_static(ds::DiscreteDS, N::Real; Ttr::Real = 100)\n\n    u = evolve(ds, Ttr)\n    D = length(u)\n    eom = ds.eom\n    jac = ds.jacob\n\n    # Initialization\n    λ = zeros(eltype(u), D)\n    Q = @SMatrix eye(eltype(u), D)\n    K = copy(Q)\n    # Main algorithm\n    for i in 1:N\n        u = eom(u)\n        K = jac(u)*Q\n\n        Q, R = qr(K)\n        for i in 1:D\n            λ[i] += log(abs(R[i, i]))\n        end\n    end\n    λ./N\nend\n\nN = 100000\nlyapunovspectrum_normal(ds, 100000)\nlyapunovspectrum_static(ds, 100000)\n\na = @btime lyapunovspectrum_normal(ds, 100000);\nb = @btime lyapunovspectrum_static(ds, 100000);\n\n# qr static is 3 times faster and does 0 allocations.\n", "meta": {"hexsha": "fb80faa618adf8b668087839f237eda63834c7f6", "size": 1227, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/benchmarks/qr_vs_staticqr.jl", "max_stars_repo_name": "KalelR/DynamicalSystems.jl", "max_stars_repo_head_hexsha": "ac80eca0d8a11b8f2a98764b63bfcb624a4db248", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 585, "max_stars_repo_stars_event_min_datetime": "2017-09-14T10:59:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:41:49.000Z", "max_issues_repo_path": "test/benchmarks/qr_vs_staticqr.jl", "max_issues_repo_name": "KalelR/DynamicalSystems.jl", "max_issues_repo_head_hexsha": "ac80eca0d8a11b8f2a98764b63bfcb624a4db248", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 101, "max_issues_repo_issues_event_min_datetime": "2017-09-08T17:07:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T15:41:36.000Z", "max_forks_repo_path": "test/benchmarks/qr_vs_staticqr.jl", "max_forks_repo_name": "KalelR/DynamicalSystems.jl", "max_forks_repo_head_hexsha": "ac80eca0d8a11b8f2a98764b63bfcb624a4db248", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 75, "max_forks_repo_forks_event_min_datetime": "2017-09-24T14:32:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T09:19:44.000Z", "avg_line_length": 20.1147540984, "max_line_length": 74, "alphanum_fraction": 0.5672371638, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7611264431787871}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction posang(units::Integer, ra1::T, dec1::T, ra2::T, dec2::T) where {T<:AbstractFloat}\n    # Convert all quantities to radians.\n    if units == 0\n        # All radians\n        ra1_rad  = ra1\n        ra2_rad  = ra2\n        dec1_rad = dec1\n        dec2_rad = dec2\n    elseif units == 1\n        # Right ascensions are in hours, declinations in degrees.\n        ra1_rad  = ra1*pi/12\n        ra2_rad  = ra2*pi/12\n        dec1_rad = deg2rad(dec1)\n        dec2_rad = deg2rad(dec2)\n    elseif units == 2\n        # Right ascensions and declinations are in degrees.\n        ra1_rad  = deg2rad(ra1)\n        ra2_rad  = deg2rad(ra2)\n        dec1_rad = deg2rad(dec1)\n        dec2_rad = deg2rad(dec2)\n    else\n        # In any other case throw an error.\n        error(\"units must be 0 (radians), 1 (hours, degrees) or 2 (degrees)\")\n    end\n    sin_radif, cos_radif = sincos(ra2_rad - ra1_rad)\n    sin_dec1, cos_dec1 = sincos(dec1_rad)\n    angle = atan(sin_radif, cos_dec1 * tan(dec2_rad) -\n                  sin_dec1 * cos_radif)\n    if units == 0\n        return angle\n    else\n        return rad2deg(angle)\n    end\nend\n\n\"\"\"\n    posang(units, ra1, dec1, ra2, dec2) -> angular_distance\n\n### Purpose ###\n\nCompute rigorous position angle of point 2 relative to point 1.\n\n### Explanation ###\n\nComputes the rigorous position angle of point 2 (with given right ascension and\ndeclination) using point 1 (with given right ascension and declination) as the\ncenter.\n\n### Arguments ###\n\n* `units`: integer, can be either 0, or 1, or 2.  Describes units of inputs and\n output:\n    * 0: everything (input right ascensions and declinations, and output\n      distance) is radians\n    * 1: right ascensions are in decimal hours, declinations in decimal degrees,\n      output distance in degrees\n    * 2: right ascensions and declinations are in degrees, output distance in\n      degrees\n* `ra1`:  right ascension or longitude of point 1\n* `dec1`: declination or latitude of point 1\n* `ra2`: right ascension or longitude of point 2\n* `dec2`: declination or latitude of point 2\n\nBoth `ra1` and `dec1`, and `ra2` and `dec2` can be given as 2-tuples `(ra1,\ndec1)` and `(ra2, dec2)`.\n\n### Output ###\n\nAngle of the great circle containing `[ra2, dec2]` from the meridian containing\n`[ra1, dec1]`, in the sense north through east rotating about `[ra1, dec1]`.\nSee `units` argument above for units.\n\n### Method ###\n\nThe \"four-parts formula\" from spherical trigonometry (p. 12 of Smart's Spherical\nAstronomy or p. 12 of Green' Spherical Astronomy).\n\n\n### Example ###\n\nMizar has coordinates (ra, dec) = (13h 23m 55.5s, +54° 55' 31'').  Its\ncompanion, Alcor, has coordinates (ra, dec) = (13h 25m 13.5s, +54° 59' 17'').\nFind the position angle of Alcor with respect to Mizar.\n\n```jldoctest\njulia> using AstroLib\n\njulia> posang(1, ten(13, 25, 13.5), ten(54, 59, 17), ten(13, 23, 55.5), ten(54, 55, 31))\n-108.46011246802047\n```\n\n### Notes ###\n\n* The function `sphdist` provides an alternate method of computing a spherical\n distance.\n* Note that `posang` is not commutative: the position angle between A and B is\n  \\$\\\\theta\\$, then the position angle between B and A is \\$180 + \\\\theta\\$.\n\nCode of this function is based on IDL Astronomy User's Library.\n\"\"\"\nposang(units::Integer, ra1::Real, dec1::Real, ra2::Real, dec2::Real) =\n    posang(units, promote(float(ra1), float(dec1), float(ra2), float(dec2))...)\n\n### Tuples input\nposang(units::Integer, radec1::Tuple{Real, Real}, ra2::Real, dec2::Real) =\n    posang(units, radec1..., ra2, dec2)\n\nposang(units::Integer, ra1::Real, dec1::Real, radec2::Tuple{Real, Real}) =\n    posang(units, ra1, dec1, radec2...)\n\nposang(units::Integer, radec1::Tuple{Real, Real}, radec2::Tuple{Real, Real}) =\n    posang(units, radec1..., radec2...)\n", "meta": {"hexsha": "77c47d90a87fe10eda86cb737a7872873ecab1c1", "size": 3837, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/posang.jl", "max_stars_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_stars_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2016-09-11T14:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T20:45:36.000Z", "max_issues_repo_path": "src/posang.jl", "max_issues_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_issues_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 64, "max_issues_repo_issues_event_min_datetime": "2017-01-19T21:03:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:27:46.000Z", "max_forks_repo_path": "src/posang.jl", "max_forks_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_forks_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:11:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:55:21.000Z", "avg_line_length": 33.0775862069, "max_line_length": 90, "alphanum_fraction": 0.6614542611, "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192066862062, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7611264316006799}}
{"text": "\"\"\"\n\n    UniformMesh(start, stop, length)\n\n    1D uniform mesh data.\n\n    length   : number of points\n    length-1 : number of cells\n\n    To remove the last point, set endpoint=false\n\n\"\"\"\nstruct UniformMesh\n\n   start    :: Float64\n   stop     :: Float64\n   length   :: Int\n   step     :: Float64\n   points   :: Vector{Float64}\n   endpoint :: Bool\n\n   function UniformMesh(start, stop, length::Int; endpoint=true)\n\n       if (endpoint)\n           points = range(start, stop=stop, length=length)\n       else\n           points = range(start, stop=stop, length=length+1)[1:end-1]\n       end\n       step = points[2]-points[1]\n\n       new( start, stop, length, step, points, endpoint)\n\n   end\n\nend\n", "meta": {"hexsha": "0d32f583416630fdb6f7179aeaa3d93d47bbe1bc", "size": 692, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/meshes.jl", "max_stars_repo_name": "pnavaro/Splittings.jl", "max_stars_repo_head_hexsha": "a2d98db435e9a2467b07ce0dacda2769fd94b752", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-25T05:52:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-25T05:52:11.000Z", "max_issues_repo_path": "src/meshes.jl", "max_issues_repo_name": "pnavaro/Splittings.jl", "max_issues_repo_head_hexsha": "a2d98db435e9a2467b07ce0dacda2769fd94b752", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/meshes.jl", "max_forks_repo_name": "pnavaro/Splittings.jl", "max_forks_repo_head_hexsha": "a2d98db435e9a2467b07ce0dacda2769fd94b752", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2222222222, "max_line_length": 69, "alphanum_fraction": 0.598265896, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7610764913543857}}
{"text": "abstract type AbstractFeatureScaling end\n\n#####\n##### Zero-mean unit-variance feature scaling\n#####\n\nstruct ZeroMeanUnitVarianceScaling{T} <: AbstractFeatureScaling\n    μ :: T\n    σ :: T\nend\n\n\"\"\"\n    ZeroMeanUnitVarianceScaling(data)\n\nReturns a feature scaler for `data` with zero mean and unit variance.\n\"\"\"\nfunction ZeroMeanUnitVarianceScaling(data)\n    μ, σ = mean(data), std(data)\n    return ZeroMeanUnitVarianceScaling(μ, σ)\nend\n\nscale(x, s::ZeroMeanUnitVarianceScaling) = (x .- s.μ) / s.σ\nunscale(y, s::ZeroMeanUnitVarianceScaling) = s.σ * y .+ s.μ\n\n#####\n##### Min-max feature scaling\n#####\n\nstruct MinMaxScaling{T} <: AbstractFeatureScaling\n           a :: T\n           b :: T\n    data_min :: T\n    data_max :: T\nend\n\n\"\"\"\n    MinMaxScaling(data; a=0, b=1)\n\nReturns a feature scaler for `data` with minimum `a` and `maximum `b`.\n\"\"\"\nfunction MinMaxScaling(data; a=0, b=1)\n    data_min, data_max = extrema(data)\n    return MinMaxScaling{typeof(data_min)}(a, b, data_min, data_max)\nend\n\nscale(x, s::MinMaxScaling) = s.a + (x - s.data_min) * (s.b - s.a) / (s.data_max - s.data_min)\nunscale(y, s::MinMaxScaling) = s.data_min .+ (y .- s.a) * (s.data_max - s.data_min) / (s.b - s.a)\n\n#####\n##### Convenience functions\n#####\n\n(s::AbstractFeatureScaling)(x) = scale(x, s)\nBase.inv(s::AbstractFeatureScaling) = y -> unscale(y, s)\n", "meta": {"hexsha": "ff6d4fb580ec8c6d08b8183d14f2a002c06672e2", "size": 1328, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DataWrangling/feature_scaling.jl", "max_stars_repo_name": "CliMA/ClimateParameterizations.jl", "max_stars_repo_head_hexsha": "1263e2edefced4e03e925d6bfa60ba1f1940e8c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2020-12-23T06:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:05:51.000Z", "max_issues_repo_path": "src/DataWrangling/feature_scaling.jl", "max_issues_repo_name": "CliMA/OceanParameterizations.jl", "max_issues_repo_head_hexsha": "5942c66ba8724b9661db170acb239ca3a2abd5c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-12-05T02:43:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T14:27:03.000Z", "max_forks_repo_path": "src/DataWrangling/feature_scaling.jl", "max_forks_repo_name": "ali-ramadhan/ClimateParameterizations.jl", "max_forks_repo_head_hexsha": "1263e2edefced4e03e925d6bfa60ba1f1940e8c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-17T18:06:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T18:06:40.000Z", "avg_line_length": 24.1454545455, "max_line_length": 97, "alphanum_fraction": 0.6506024096, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.8376199572530449, "lm_q1q2_score": 0.7610764819155127}}
{"text": "function generate_random_unit_quaternion()\n\t\n\tq0::Float64 = randn()\n\tq1::Float64 = randn()\n\tq2::Float64 = randn()\n\tq3::Float64 = randn()\n\t\n\tq_norm::Float64 = sqrt( q0^2 + q1^2 + q2^2 + q3^2 )\n\n\tq0 /= q_norm\n\tq1 /= q_norm\n\tq2 /= q_norm\n\tq3 /= q_norm\n\t\n\treturn (q0, q1, q2, q3)\nend", "meta": {"hexsha": "b80a2abc045c4acaa0b1ea349dd5fee7185031ee", "size": 279, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/generate_random_unit_quaternion.jl", "max_stars_repo_name": "roding/whitefish_characterization", "max_stars_repo_head_hexsha": "75d8572f86de9f8908c5d9651f6a2887d99a810b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-12-16T19:53:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-31T13:52:45.000Z", "max_issues_repo_path": "src/generate_random_unit_quaternion.jl", "max_issues_repo_name": "roding/whitefish_characterization", "max_issues_repo_head_hexsha": "75d8572f86de9f8908c5d9651f6a2887d99a810b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/generate_random_unit_quaternion.jl", "max_forks_repo_name": "roding/whitefish_characterization", "max_forks_repo_head_hexsha": "75d8572f86de9f8908c5d9651f6a2887d99a810b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-10-06T14:05:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T13:43:27.000Z", "avg_line_length": 17.4375, "max_line_length": 52, "alphanum_fraction": 0.6200716846, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7610754906110493}}
{"text": "mutable struct KSTestResult <: TestResult\n    n_obs::Int\n    statistic::Float64\n    pval::Float64\nend\n\nfunction show(io::IO, kstr::KSTestResult)\n    println(io, \"\\n        One Sample Kolmogorov-Smirnov test\")\n    println(io, \"\\n Result:\\n\", coeftable(kstr))\nend\n\nfunction coeftable(kstr::KSTestResult)\n    CoefTable(\n        [kstr.n_obs, kstr.statistic, kstr.pval],\n        [\"N\", \"D\", \"P-value\"],\n        [\"\"],\n        3, 2\n    )\nend\n\nfunction pkstwo(x::Float64, tol = 1e-06)\n    k_max = floor(Int, sqrt(2.0 - log(tol)))\n    if x < 1\n        z = - (π^2 / 8) / (x^2)\n        w = log(x)\n        s = 0.0\n        k = 1\n        while k < k_max\n            s += exp(k^2 * z - w)\n            k += 2\n        end\n        return s * sqrt(2 * π)\n    else\n        z = -2 * x²\n        s = -1.0\n        old = 0.0\n        new = 1.0\n        while abs(old - new) > tol\n            old = new\n            new += 2 * s * exp(z * k^2)\n            s *= -1.0\n            k += 1\n        end\n        return new\n    end\nend\n\nfunction ccdfNonExact(d::KSDist, x::Float64)\n    return 1 - pkstwo(sqrt(d.n) * x)\nend\n\n\"\"\"\n    ks_test(x, distr)\n\nOne sample Kolmogorov-Smirnov test\n\nThe argument `x` can be a numeric `Vector`.\n\nThe argument `distr` can be a `Distributions.UnivariateDistribution`.\n\"\"\"\nfunction ks_test(\n    x::NumVector,\n    distr::UnivariateDistribution;\n    exact::Union{Bool, Nothing}=nothing\n)::KSTestResult\n    n = length(x)\n    ties = false\n    if length(unique(x)) < n\n        @warn \"ties should not be present for the Kolmogorov-Smirnov test\"\n        ties = true\n    end\n\n    if isnothing(exact)\n        exact = (n < 100) & !ties\n    end\n\n    x_density_sorted = D.cdf.(distr, sort(x)) - collect(0:(n-1))/n\n    statistic = max(\n        Base.maximum(x_density_sorted),\n        Base.maximum(1/n .- x_density_sorted)\n    )\n\n    if exact\n        pval = D.ccdf(KSDist(n), statistic)\n    else\n        pval = ccdfNonExact(KSDist(n), statistic)\n    end\n\n    res = KSTestResult(n, statistic, pval)\n    return res\nend\n", "meta": {"hexsha": "0e3d31f3a36d4539aef5dc5c44d8d1fe404efc7e", "size": 1998, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kstest.jl", "max_stars_repo_name": "i-kiwamu/StatisticalTests.jl", "max_stars_repo_head_hexsha": "9dfce365ed961b1365f4effc6644081fe3611216", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-10T19:11:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T19:11:18.000Z", "max_issues_repo_path": "src/kstest.jl", "max_issues_repo_name": "i-kiwamu/StatisticalTests.jl", "max_issues_repo_head_hexsha": "9dfce365ed961b1365f4effc6644081fe3611216", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kstest.jl", "max_forks_repo_name": "i-kiwamu/StatisticalTests.jl", "max_forks_repo_head_hexsha": "9dfce365ed961b1365f4effc6644081fe3611216", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7173913043, "max_line_length": 74, "alphanum_fraction": 0.542042042, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7610754899339665}}
{"text": "# this script does a Monte Carlo that shows efficiency of GLS compared to OLS\n# when there are AR1 errors\nusing Econometrics, Plots\n\n# the function to be Monte Carlo'ed\nfunction wrapper(args)\n\tn, ρ = args    # sample size and AR parameter\n\tx = randn(n)     # an exogenous regressor\n\t# make the AR1 errors\n    ϵ = zeros(n)\n    ϵ[1] = randn()/sqrt(1-ρ^2)\n\tfor t = 2:n\n        ϵ[t] = ρ*ϵ[t-1] + randn()\n    end\n\t# the dep var\n\ty = 1. .+ x .+ ϵ\n\t# OLS\n\tx = [ones(n) x]\n\tβ_ols = x \\ y\n\t# estimate ρ\n\te = y - x*β_ols\n    # estimating ρ using correlation, to keep in stationary region\n    ρhat = cor(e[1:end-1], e[2:end]) \n\tystar = y - ρhat.*lag(y,1)\n\txstar = x - ρhat*lag(x,1)\n    ystar[1] = sqrt(1-ρhat^2) .*y[1]\n    xstar[1,:] = sqrt(1-ρhat^2) .* x[1,:]\n\tβ_gls = xstar\\ystar\n\tβ_ols, β_gls\nend\n\n# do the Monte Carlo\nn = 30\nρ = 0.9\nargs = (n, ρ)\nreps = 1000\nβ_ols = zeros(reps,2)\nβ_gls = zeros(reps,2)\nfor i = 1:reps\n    β_ols[i,:], β_gls[i,:] = wrapper(args)\nend    \n\n# analyze results\np1 = histogram(β_ols[:,2],bins=30, legend=false, xlabel=\"OLS\")\np2 = histogram(β_gls[:,2],bins=30, legend=false, xlabel=\"GLS\")\nplot(p1,p2)\n#savefig(\"AR1errors_OLSvsGLS.png\")\ngui()\n\t\t\n\n", "meta": {"hexsha": "b6e0fd803dfb01c34b7554614d3742631ce052f5", "size": 1164, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/GLS/AR1Errors.jl", "max_stars_repo_name": "Hiroakiyusheng/Econometrics", "max_stars_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-19T18:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T18:23:45.000Z", "max_issues_repo_path": "Examples/GLS/AR1Errors.jl", "max_issues_repo_name": "Hiroakiyusheng/Econometrics", "max_issues_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/GLS/AR1Errors.jl", "max_forks_repo_name": "Hiroakiyusheng/Econometrics", "max_forks_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8235294118, "max_line_length": 77, "alphanum_fraction": 0.6134020619, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7610754878117119}}
{"text": "function juliaset(z, z0, nmax::Int64)\r\n    for n = 1:nmax\r\n        if abs(z) > 2 (return n-1) end\r\n        z = z^2 + z0\r\n    end\r\n    return nmax\r\nend", "meta": {"hexsha": "ff9c66ea7ad306835841b0aa5ecb3ba3991feae9", "size": 150, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chp02/Code/jset.jl", "max_stars_repo_name": "PetrKryslUCSD/Mastering-Julia-1.0", "max_stars_repo_head_hexsha": "375342d933a48142b5b605b9c39cb5922e010691", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chp02/Code/jset.jl", "max_issues_repo_name": "PetrKryslUCSD/Mastering-Julia-1.0", "max_issues_repo_head_hexsha": "375342d933a48142b5b605b9c39cb5922e010691", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chp02/Code/jset.jl", "max_forks_repo_name": "PetrKryslUCSD/Mastering-Julia-1.0", "max_forks_repo_head_hexsha": "375342d933a48142b5b605b9c39cb5922e010691", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-15T19:05:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T19:05:40.000Z", "avg_line_length": 21.4285714286, "max_line_length": 39, "alphanum_fraction": 0.5066666667, "num_tokens": 59, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7610754877207058}}
{"text": "export CompleteHypergraph\n\nimport Combinatorics.combinations\n\n\"\"\"\n`CompleteHypergraph(n,k)` creates a complete hypergraph with vertex set\n`{1,2,...,n}`. The edges are all `k`-element subsets of the vertices.\n\"\"\"\nfunction CompleteHypergraph(n::Int, k::Int)::SimpleHypergraph{Int}\n    @assert n >= 0 && k >= 0 \"both arguments to CompleteHypergraph must be nonnegative\"\n\n    H = IntHypergraph(n)\n\n    if k > n\n        return H\n    end\n\n    for e in combinations(1:n, k)\n        add!(H, e)\n    end\n\n    return H\nend\n", "meta": {"hexsha": "161cd778a0d0fb7b90cb652674cf88e45e8ee643", "size": 512, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hyper/complete.jl", "max_stars_repo_name": "willtebbutt/SimpleGraphs.jl", "max_stars_repo_head_hexsha": "c0aaf98c56ef64b75b24e7ff24347c348ce5246c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2015-03-08T00:51:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T18:54:27.000Z", "max_issues_repo_path": "src/hyper/complete.jl", "max_issues_repo_name": "willtebbutt/SimpleGraphs.jl", "max_issues_repo_head_hexsha": "c0aaf98c56ef64b75b24e7ff24347c348ce5246c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-08-15T11:25:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T22:46:00.000Z", "max_forks_repo_path": "src/hyper/complete.jl", "max_forks_repo_name": "willtebbutt/SimpleGraphs.jl", "max_forks_repo_head_hexsha": "c0aaf98c56ef64b75b24e7ff24347c348ce5246c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-07-04T01:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-11T09:09:06.000Z", "avg_line_length": 21.3333333333, "max_line_length": 87, "alphanum_fraction": 0.6640625, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7610754862755338}}
{"text": "function autocovariance(z::AbstractVector{T}, k::Integer) where {T}\n    N = length(z)\n    m = mean(z)\n    γ = zero(T)\n    @inbounds @simd for i in 1:N - k\n        γ += (z[i + k] - m) * (z[i] - m)\n    end\n    return γ / N\nend\n\nfunction autocorrelation(z::AbstractVector, k::Integer)\n    return autocovariance(z, k) / autocovariance(z, 0)\nend\n\nfunction autocovariance_matrix(z::AbstractVector, k::Integer)\n    N = length(z)\n    T = typeof(zero(eltype(z)) / 1)\n    γ = Vector{T}(undef, k)\n    for i in 1:k\n        γ[i] = autocovariance(z, i - 1)\n    end\n    Γ = Matrix{T}(undef, k, k)\n    for j in 1:k\n        for i in 1:k\n            Γ[i,j] = γ[abs(i - j) + 1]\n        end\n    end\n    return Γ\nend\n\nfunction autocorrelation_matrix(z::AbstractVector, k::Integer)\n    return autocovariance_matrix(z, k) ./ autocovariance(z, 0)\nend\n\nfunction partial_autocorrelation(z::AbstractVector, k::Integer)\n    Ρ = autocorrelation_matrix(z, k)\n    Ρstar = copy(Ρ)\n    Ρstar[1:k - 1,k] = Ρstar[2:k,1]\n    Ρstar[k,k] = autocorrelation(z, k)\n    return det(Ρstar) / det(cholesky(Symmetric(Ρ)))\nend", "meta": {"hexsha": "2bf57c508fc2a31069e101648bd05f07bff9b357", "size": 1079, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stats.jl", "max_stars_repo_name": "pierrenodet/AutoARIMA.jl", "max_stars_repo_head_hexsha": "3bcfbda02b94fc249f60a431820df74081ee3c45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-06-06T22:29:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T03:00:23.000Z", "max_issues_repo_path": "src/stats.jl", "max_issues_repo_name": "pierrenodet/AutoARIMA.jl", "max_issues_repo_head_hexsha": "3bcfbda02b94fc249f60a431820df74081ee3c45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-05-03T11:21:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-07T15:21:55.000Z", "max_forks_repo_path": "src/stats.jl", "max_forks_repo_name": "pierrenodet/AutoARIMA.jl", "max_forks_repo_head_hexsha": "3bcfbda02b94fc249f60a431820df74081ee3c45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3170731707, "max_line_length": 67, "alphanum_fraction": 0.6033364226, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7610754855984511}}
{"text": "module NonDimensional\n\nusing LinearAlgebra: norm\nusing PrettyTables\n\nexport dynamic_pressure, force_coefficient, moment_coefficient, moment_coefficients, rate_coefficient, pressure_coefficient, aerodynamic_coefficients, print_coefficients, reynolds_number, print_derivatives\n\n\"\"\"\n    dynamic_pressure(ρ, V)\n\nCompute the dynamic pressure given density ``\\\\rho`` and speed ``V``.\n\"\"\"\ndynamic_pressure(ρ, V) = 1/2 * ρ * V^2\n\n\"\"\"\n    force_coefficient(force, q, S)\n\nCompute the non-dimensional force coefficient given force, dynamic pressure ``q``, and area ``S``.\n\"\"\"\nforce_coefficient(force, q, S) = force / (q * S)\n\n\"\"\"\n    moment_coefficient(moment, q, S, L)\n\nCompute the non-dimensional moment coefficient given force, dynamic pressure ``q``, area ``S``, and reference length ``L``.\n\"\"\"\nmoment_coefficient(moment, q, S, L) = force_coefficient(moment, q, S) / L\n\n\"\"\"\n    rate_coefficient(Ω, V, L)\n\nCompute the non-dimensional angular velocity coefficient given angular speed ``\\\\Omega``, reference speed ``V``, and reference length ``L``.\n\"\"\"\nrate_coefficient(Ω, V, L) = Ω * L / 2V\n\n\"\"\"\n    pressure_coefficient(force, ρ, V, S)\n\nCompute the pressure coefficient given force, reference density ``\\\\rho``, speed ``V`` and area ``S``.\n\"\"\"\npressure_coefficient(force, ρ, V, S) = force_coefficient(force, dynamic_pressure(ρ, V), S)\n\npressure_coefficient(mag, vels) = 1 - (norm(vels) / mag)^2\n\nmoment_coefficient(moment, q, S, b, c) = moment_coefficient.(moment, q, S, [b, c, b])\n\nrate_coefficient(Ω, V, b, c) = rate_coefficient.(Ω, V, [b, c, b])\n\n\n\"\"\"\n    aerodynamic_coefficients(force, moment, Ω, V, S, b, c, ρ)\n\nCompute the relevant aerodynamic coefficients given a net force, moment and angular rates ``\\\\Omega`` with reference speed ``V``, area ``S``, span ``b``, chord ``c``, and density ``\\\\rho``.\n\"\"\"\nfunction aerodynamic_coefficients(force, moment, Ω, V, S, b, c, ρ)\n    q = dynamic_pressure(ρ, V)\n\n    [ force_coefficient(force, q, S) \t\t ;\n      moment_coefficient(moment, q, S, b, c) ;\n      rate_coefficient(Ω, V, b, c) \t\t\t ]\nend\n\nfunction print_coefficients(nf_coeffs, ff_coeffs, name = \"\"; browser = false)\n    coeffs = [ ifelse(length(nf_coeffs) == 11, [\"CD\", \"CDp\"], []); [ \"CDi\", \"CY\", \"CL\", \"Cl\", \"Cm\", \"Cn\", \"p̄\", \"q̄\", \"r̄\" ] ]\n    data = [ coeffs nf_coeffs [ ff_coeffs; fill(\"—\", 6) ] ]\n    head = [ name, \"Nearfield\", \"Farfield\" ]\n    h1 = Highlighter( (data,i,j) -> (j == 1), foreground = :blue, bold = true)\n    if browser\n        pretty_table(String, data, head, alignment = [:c, :c, :c], tf = tf_html_minimalist, backend = :html, highlighters = HTMLHighlighter( (data,i,j) -> (j == 1), HTMLDecoration(font_weight = \"bold\")), formatters = ft_round(8))\n    else\n        pretty_table(data, head, alignment = [:c, :c, :c], tf = tf_compact, highlighters = h1, vlines = :none, formatters = ft_round(8))\n    end\nend\n\nfunction print_derivatives(derivs, name = \"\"; browser = false)\n    coeffs = [\"∂CD\", \"∂CY\", \"∂CL\", \"∂Cl\", \"∂Cm\", \"∂Cn\"]\n    nf_vars = [ \"$name\" \"\" \"Nearfield\" \"Stability\" \"Derivatives\" \"\" ; \"\" \"∂α, 1/rad\" \"∂β, 1/rad\" \"∂p̄\" \"∂q̄\" \"∂r̄\" ]\n    nf_rows = [ coeffs derivs ]\n\n    if browser\n        pretty_table(String, nf_rows, nf_vars, alignment = :c, tf = tf_html_minimalist, backend = :html, highlighters = HTMLHighlighter( (data,i,j) -> (j == 1), HTMLDecoration(color = \"blue\", font_weight = \"bold\")), formatters = ft_round(8))\n    else\n        pretty_table(nf_rows, nf_vars, alignment = :c, tf = tf_compact, header_crayon = Crayon(bold = true), subheader_crayon = Crayon(foreground = :yellow, bold = true), highlighters = Highlighter( (data,i,j) -> (j == 1), foreground = :blue, bold = true), vlines = :none, formatters = ft_round(8))\n    end\nend\n\nreynolds_number(ρ, V, c, μ) = ρ * V * c / μ\nreynolds_number(V, c, ν) = V * c / ν\n\nforce(CF, q, S) = CF * q * S\nmoment(CM, q, S, c) = CM * q * S * c\nmoment(CM, q, S, b, c) = moment.(CM, q, S, [b, c, b])\n\nend", "meta": {"hexsha": "d93eb9cee9a3c75e9391621d120d0c1938c15afd", "size": 3884, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Tools/NonDimensional.jl", "max_stars_repo_name": "GodotMisogi/AeroMDAO.jl", "max_stars_repo_head_hexsha": "e05b3d4589583a3e106c5fc2fde86578483133c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2021-09-23T08:04:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T13:28:01.000Z", "max_issues_repo_path": "src/Tools/NonDimensional.jl", "max_issues_repo_name": "GodotMisogi/AeroMDAO.jl", "max_issues_repo_head_hexsha": "e05b3d4589583a3e106c5fc2fde86578483133c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-02-08T06:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T06:08:38.000Z", "max_forks_repo_path": "src/Tools/NonDimensional.jl", "max_forks_repo_name": "GodotMisogi/AeroMDAO", "max_forks_repo_head_hexsha": "e05b3d4589583a3e106c5fc2fde86578483133c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-01-25T08:46:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T08:11:45.000Z", "avg_line_length": 41.3191489362, "max_line_length": 298, "alphanum_fraction": 0.6428939238, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7610754848303619}}
{"text": "\n@doc raw\"\"\"\n    sumBassUB(p,q,m,c0,alpha,F,T,Pi)\n\nThis function implements Udell an Boyd's algorithm to maximize a sum of Bass functions\nand returns the maximizer and maximum.\n\"\"\"\nfunction sumBassUB(p,q,m,c0,alpha,F,T,Pi::Real)\n    n = length(p)\n    # Generate model for solution\n    f = Vector{Function}(undef,n)\n    df = Vector{Function}(undef,n)\n    z = Vector{Float64}(undef,n)\n    for i in 1:n\n        f[i] = t -> alpha[i]*Bass(t,p[i],q[i],m[i],c0[i])\n        df[i] = t -> alpha[i]*Bass_derivative(t,p[i],q[i],m[i],c0[i])\n        z[i] = Bass_inflection(p[i],q[i],m[i],c0[i])\n    end\n\n    C = ones(1,n)\n    d = [Pi]\n\n    A = zeros(0,n)\n    b = zeros(0)\n\n    problem = LinearSP(f, df, z, A, b, C, d)\n\n    pq, bestnodes, lbs, ubs = solve_sp(F, T, problem,TOL=1e-6)\n\n    node = dequeue!(pq)\n\n    maximizer = Vector{Float64}(undef,n)\n    maximizer .= node.x\n    maximum = sum(alpha[i]*Bass(maximizer[i],p[i],q[i],m[i],c0[i]) for i in 1:n)\n    return maximizer, maximum\nend\n\n    # Maximizer\n    # node.x\n    # Lower bound of maximum\n    # node.lb\n    # Upper bound of maximum\n    # node.ub\n", "meta": {"hexsha": "9b39940a19bd6fe4b22628cf2fb83be69703c34c", "size": 1090, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Optimization/SumBassSolver/src/UdellBoyd.jl", "max_stars_repo_name": "andres-alban/res-alloc-bass-demands", "max_stars_repo_head_hexsha": "c7e6edcbf0f433017bf47623653b186a50f5dd44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Optimization/SumBassSolver/src/UdellBoyd.jl", "max_issues_repo_name": "andres-alban/res-alloc-bass-demands", "max_issues_repo_head_hexsha": "c7e6edcbf0f433017bf47623653b186a50f5dd44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Optimization/SumBassSolver/src/UdellBoyd.jl", "max_forks_repo_name": "andres-alban/res-alloc-bass-demands", "max_forks_repo_head_hexsha": "c7e6edcbf0f433017bf47623653b186a50f5dd44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7727272727, "max_line_length": 86, "alphanum_fraction": 0.5844036697, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7610754842442855}}
{"text": "#=\n\nThe sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.\n\nFind the sum of all the primes below two million.\n\n=#\nusing Distributed\naddprocs(3)\n\nmax_num = Int(2e6)\n\n@everywhere is_prime(n) = !any(n%i == 0 for i in 2:BigInt(floor(sqrt(n))))\npartial_sum(start, stop) = sum(i for i in start:stop if is_prime(i))\n\nres = @distributed (+) for i = 2:max_num\n    if is_prime(i)\n        i\n    else\n        0\n    end\nend\n\n# sieve of erathostenes\n# soooo much faster\nmax_num =  Int(2e6)\nprime_candidates = trues(max_num)\nfor i in 2:max_num\n    if prime_candidates[i]\n        prime_candidates[i^2:i:max_num] .= false\n    end\nend\n\nsum(findall(prime_candidates))-1\n", "meta": {"hexsha": "92480832d1c6ff37a83a9d0ba6ce9e24c8eefc05", "size": 650, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "euler_10.jl", "max_stars_repo_name": "pedvide/project-euler", "max_stars_repo_head_hexsha": "8e8e1e57b2c4d7e70a7127483539dca060c50a38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "euler_10.jl", "max_issues_repo_name": "pedvide/project-euler", "max_issues_repo_head_hexsha": "8e8e1e57b2c4d7e70a7127483539dca060c50a38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "euler_10.jl", "max_forks_repo_name": "pedvide/project-euler", "max_forks_repo_head_hexsha": "8e8e1e57b2c4d7e70a7127483539dca060c50a38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5714285714, "max_line_length": 74, "alphanum_fraction": 0.6584615385, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7610754821220309}}
{"text": "module GaussianBeamLens\n\n# Set optimization level 1 for faster compilation, at potential cost of later performance\nif isdefined(Base, :Experimental) && isdefined(Base.Experimental, Symbol(\"@optlevel\"))\n    @eval Base.Experimental.@optlevel 1\nend\n\n#include(\"GtkGUI.jl\")\n\nusing FFTW: ifft, fft, ifftshift, fftshift\n\nexport GaussianBeamLensPropagate\n\nconst L = 1                      # wavelength of light \nconst n = 1                      # refractive index\nconst k = 2*pi*n/L               # wave number in material\nconst Nx = 1024                  # number of x cells\nconst dx = L/2                   # length of x cells\nconst Lx = Nx*dx                 # length of grid in x\nconst dkx = (2*pi)/Lx            # length of kx cell\nconst Nkx = Nx                   # same number of cells in real and fourier space\n\nconst x = dx.*(-(Nx/2):Nx/2-1)\nconst kx = dkx.*(-(Nkx/2):Nkx/2-1)\nconst kz = sqrt.(k^2 .- kx.^2)\n\nconst dz = 10                    # steps in z\nconst zmax = 6000                # end of grid in z\nconst z = 0:dz:zmax              # z grid\n\nconst FE = zeros(Complex{Float64}, length(z), length(x))\n\nconst cache = Dict{Tuple{Int64,Int64,Int64,Int64},Matrix{Float64}}()\n\n\n\n\"\"\"\n    GaussianBeamLensPropagate(x0,w0,f,Lens_z)\n        x0:     Lateral offset of the input beam\n        w0:     Width of the Gaussian beam in object space\n        f:      Focal length of the lens\n        Lens_z: Axial Position of the lens\n\nComputes the intensity of the optical field at every point in x (lateral) and z (axial).\nThis method caches previously generated images in a dictionary at `GaussianBeamLens.cache`.\nSee GaussianBeamLensPropagate.GaussianBeamLensPropagateUncached for the actual implementation.\n\"\"\"\nfunction GaussianBeamLensPropagate(x0,w0,f,Lens_z)\n    if haskey(cache,(x0,w0,f,Lens_z))\n        return cache[(x0,w0,f,Lens_z)]\n    else\n        return GaussianBeamLensPropagateUncached(x0, w0, f, Lens_z)\n    end\nend\n\n\"\"\"\n    GaussianBeamLensPropagateUncached(x0,w0,f,Lens_z)\n        x0:     Lateral offset of the input beam\n        w0:     Width of the Gaussian beam in object space\n        f:      Focal length of the lens\n        Lens_z: Axial Position of the lens\nComputes the intensity of the optical field at every point in x (lateral) and z (axial)\n\"\"\"\nfunction GaussianBeamLensPropagateUncached(x0, w0, f, Lens_z)\n    E = exp.(-((x .- x0)./w0).^2)             # initial transverse electric field\n    Tf = exp.(1im.*k.*(x.^2)/(2*f))           # transmission function for a thin lens\n    \n    # Propagate beam\n    #FE = zeros(Complex{Float64},length(z),length(E))\n    FE[1,:] = E\n\n    for d = 1:length(z)-1\n        # We could save some time if we saved the prior iteration in Fourier space\n        FE[d+1,:] = ifft(ifftshift( fftshift(fft(FE[d,:])).*exp.(-1im.*kz.*dz) ))\n        if abs(z[d]- Lens_z) < dz/2        \n            FE[d+1,:] .*= Tf\n        end\n    end\n    I = abs2.(FE)                # intensity of the field at every point in x and z\n    cache[(x0,w0,f,Lens_z)] = I\n    return I\nend\n\nprecompile(GaussianBeamLensPropagateUncached, (Int64, Int64, Int64, Int64))\nprecompile(GaussianBeamLensPropagate, (Int64, Int64, Int64, Int64))\n\nend", "meta": {"hexsha": "6e6bc549be08ee9b9a4ce1a237d06b0b1897f01b", "size": 3157, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GaussianBeamLens.jl", "max_stars_repo_name": "mkitti/GaussianBeamLens", "max_stars_repo_head_hexsha": "1049f5413f647fe9354a2348c58bb3643f2cb893", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GaussianBeamLens.jl", "max_issues_repo_name": "mkitti/GaussianBeamLens", "max_issues_repo_head_hexsha": "1049f5413f647fe9354a2348c58bb3643f2cb893", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GaussianBeamLens.jl", "max_forks_repo_name": "mkitti/GaussianBeamLens", "max_forks_repo_head_hexsha": "1049f5413f647fe9354a2348c58bb3643f2cb893", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2873563218, "max_line_length": 94, "alphanum_fraction": 0.628444726, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7610754784635984}}
{"text": "\"\"\"\n    cl6(x::Float64)::Float64\n\nReturns the value of the Clausen function ``\\\\operatorname{Cl}_6(x)``\nfor a real angle ``x`` of type `Float64`.  This function is defined as\n\n```math\n\\\\operatorname{Cl}_6(x) = \\\\Im[\\\\operatorname{Li}_6(e^{ix})] = \\\\sum_{k=1}^\\\\infty \\\\frac{\\\\sin(kx)}{k^6}\n```\n\nAuthor: Alexander Voigt\n\nLicense: MIT\n\n# Example\n```jldoctest; setup = :(using ClausenFunctions), output = false\njulia> cl6(1.0)\n0.855629273183937\n```\n\"\"\"\nfunction cl6(x::Float64)::Float64\n    zeta3 = 1.2020569031595943\n    pi28 = pi*pi/8.0\n\n    (x, sgn) = range_reduce_even(x)\n\n    if x == zero(x) || x == pi\n        return zero(x)\n    end\n\n    if x < 0.5*pi\n        P = (1.0369277551433699e+00, -2.087195444107175e-01,\n             2.0652251045312954e-02, -1.383438138256840e-04)\n        Q = (1.0000000000000000e+00, -8.0784096827362542e-03,\n             5.8074568862993102e-06, -5.1960620033050114e-10)\n        y = x*x\n        y2 = y*y\n        p = P[1] + y * P[2] + y2 * (P[3] + y * P[4])\n        q = Q[1] + y * Q[2] + y2 * (Q[3] + y * Q[4])\n        sgn*x*(p/q - 1/120*y2*log(x))\n    else\n        P = (7.9544504578027050e-01, -1.9255025309738589e-01,\n             1.5805208288846591e-02, -5.4175380521534706e-04,\n             6.7577493541009068e-06)\n        Q = (1.0000000000000000e+00, -7.0798422394109274e-02,\n             7.1744189715634762e-04,  3.9098747334347093e-06,\n             3.5669441618295266e-08,  2.5315391843409925e-10)\n        y = pi - x\n        z = y*y - pi28\n        z2 = z*z\n        z4 = z2*z2\n        p = P[1] + z * P[2] + z2 * (P[3] + z * P[4]) + z4 * P[5]\n        q = Q[1] + z * Q[2] + z2 * (Q[3] + z * Q[4]) + z4 * (Q[5] + z * Q[6])\n        sgn*y*p/q\n    end\nend\n", "meta": {"hexsha": "de643731729dc3583e49085a8fc30ddada6a6dd0", "size": 1685, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Cl6.jl", "max_stars_repo_name": "Expander/Clausen.jl", "max_stars_repo_head_hexsha": "658c88bbbeecea05c8113061454c85acb5f41e38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-08T12:01:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T15:04:50.000Z", "max_issues_repo_path": "src/Cl6.jl", "max_issues_repo_name": "Expander/Clausen.jl", "max_issues_repo_head_hexsha": "658c88bbbeecea05c8113061454c85acb5f41e38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Cl6.jl", "max_forks_repo_name": "Expander/Clausen.jl", "max_forks_repo_head_hexsha": "658c88bbbeecea05c8113061454c85acb5f41e38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5614035088, "max_line_length": 105, "alphanum_fraction": 0.5400593472, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7610754770184263}}
{"text": "#Complex numbers\n1+2im\n(1 + 2im)*(2 - 3im)\n(1 + 2im)/(1 - 2im)\n(1 + 2im)+(1 - 2im)\n(-3 + 2im)-(5 - 1im)\n(-1 + 2im)^2.5\n3(2 - 5im)^2\n\n(2 + 3im) - 1\n(2 + 3im) - 0.5im\n\n1 + 3/4im\n# 3/(4im) == -(3/4im)\n\nz = 1 + 2im\nreal(1 + 2im)\nimag(1 + 2im)\nconj(z)\nabs(z) #sua distancia do 0\nabs(z)^2\nabs2(z)\nangle(z) #rad\nsqrt(1im)\nsqrt(1 + 2im)\ncos(z)\nexp(z)\nsinh(z)\n√(-4+0im)\na=1;b=2;\na + bim\na + b*im\n#not recomended, use this instead:\ncomplex(a,b)\n1 + Inf*im\n1 + NaN*im\n\n#Rational Numbers\n2//3\n6//9\n-4//8\n5//-15\n-4//-12\nnumerator(2//3)\ndenominator(2//3)\n2//3 == 6//9\n2//3 == 9//27\n2//4 + 1//6\nfloat(3//4)\nisequal(float(a//b), a/b)\n\n5//0 #inf\n-3//0\ntypeof(ans) #Rational{Int64}\n0//0\n#trying to construct a NaN,but is invalid\n\n3//5 + 1\n2//7 * (1 + 2im)\n2//7 * (1.5 + 2im)\n1//2 + 2im\n0.5 == 1//2\n0.5 == 1/2\n", "meta": {"hexsha": "0b46eae5ad045373716968e10c1032afd5af2708", "size": 791, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/cap13.jl", "max_stars_repo_name": "Mutanne/hiworld", "max_stars_repo_head_hexsha": "d4c536775ecdd948b6fa205cd43fb5f92c7496c5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/cap13.jl", "max_issues_repo_name": "Mutanne/hiworld", "max_issues_repo_head_hexsha": "d4c536775ecdd948b6fa205cd43fb5f92c7496c5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/cap13.jl", "max_forks_repo_name": "Mutanne/hiworld", "max_forks_repo_head_hexsha": "d4c536775ecdd948b6fa205cd43fb5f92c7496c5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.359375, "max_line_length": 41, "alphanum_fraction": 0.5360303413, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7610598219900973}}
{"text": "# Diffusion maps\n# --------------\n# Diffusion maps,\n# Coifman, R. & Lafon, S., Applied and Computational Harmonic Analysis, Elsevier, 2006, 21, 5-30\n\n\"\"\"\n\n    DiffMap{T <: Real} <: AbstractDimensionalityReduction\n\nThe `DiffMap` type represents diffusion maps model constructed for `T` type data.\n\"\"\"\nstruct DiffMap{T <: Real} <: AbstractDimensionalityReduction\n    t::Int\n    α::Real\n    ɛ::Real\n    λ::AbstractVector{T}\n    K::AbstractMatrix{T}\n    proj::Projection{T}\nend\n\n## properties\noutdim(R::DiffMap) = size(R.proj, 1)\neigvals(R::DiffMap) = R.λ\n\n## custom\n\"\"\"Returns the kernel matrix of the diffusion maps model `R`\"\"\"\nkernel(R::DiffMap) = R.K\n\n## show\nsummary(io::IO, R::DiffMap) = print(io, \"Diffusion Maps(outdim = $(outdim(R)), t = $(R.t), α = $(R.α), ɛ = $(R.ɛ))\")\nfunction show(io::IO, R::DiffMap)\n    summary(io, R)\n    io = IOContext(io, :limit=>true)\n    println(io)\n    println(io, \"Kernel: \")\n    Base.print_matrix(io, R.K, \"[\", \",\",\"]\")\n    println(io)\n    println(io, \"Embedding:\")\n    Base.print_matrix(io, transform(R), \"[\", \",\",\"]\")\nend\n\n## interface functions\n\"\"\"\n    fit(DiffMap, data; maxoutdim=2, t=1, α=1.0, ɛ=1.0)\n\nFit a isometric mapping model to `data`.\n\n# Arguments\n* `data::Matrix`: a (n_features, n_observations) matrix of observations. Each column of `data` is an observation.\n  if `isnothing(kernel)`, `data` is instead the (n_observations, n_observations) precomputed Gram matrix.\n\n# Keyword arguments\n* `kernel::Union{Nothing, Function}=(x, y) -> exp(-sum((x .- y) .^ 2) / ɛ)`: the kernel function. \n maps two input vectors (observations) to a scalar (a metric of their similarity).\n by default, a Gaussian kernel. if `isnothing(kernel)`, we assume `data` is instead \n the (n_observations, n_observations) precomputed Gram matrix.\n* `ɛ::Real=1.0`: the Gaussian kernel variance (the scale parameter). ignored if custom `kernel` passed.\n* `maxoutdim::Int=2`: the dimension of the reduced space.\n* `t::Int=1`: the number of transitions\n* `α::Real=0.0`: a normalization parameter\n\n# Examples\n```julia\nX = rand(3, 100)     # toy data matrix, 100 observations\n\n# default kernel\nM = fit(DiffMap, X)  # construct diffusion map model\nR = transform(M)     # perform dimensionality reduction\n\n# custom kernel\nkernel = (x, y) -> x' * y # linear kernel\nM = fit(DiffMap, X, kernel=kernel)\n\n# precomputed Gram matrix\nkernel = (x, y) -> x' * y # linear kernel\nK = StatsBase.pairwise(kernel, eachcol(X), symmetric=true) # custom Gram matrix\nM = fit(DiffMap, K, kernel=nothing)\n```\n\"\"\"\nfunction fit(::Type{DiffMap}, X::AbstractMatrix{T};\n             ɛ::Real=1.0,\n             kernel::Union{Nothing, Function}=(x, y) -> exp(-sum((x .- y) .^ 2) / convert(T, ɛ)), \n             maxoutdim::Int=2, \n             t::Int=1, \n             α::Real=0.0\n            ) where {T<:Real}\n    if isa(kernel, Function)\n        # compute Gram matrix\n        L = pairwise(kernel, eachcol(X), symmetric=true)\n    else\n        # X is the pre-computed Gram matrix\n        L = deepcopy(X) # deep copy needed b/c of procedure for α > 0\n        @assert issymmetric(L)\n    end\n\n    # Calculate Laplacian & normalize it\n    if α > 0\n        D = transpose(sum(L, dims=1))\n        L ./= (D * transpose(D)) .^ convert(T, α)\n    end\n    D = Diagonal(vec(sum(L, dims=1)))\n    M = inv(D) * L # normalize rows to interpret as transition probabilities\n\n    # D = Diagonal(vec(sum(L, dims=1)))\n    # D⁻ᵅ = inv(D^α)\n    # Lᵅ = D⁻ᵅ*L*D⁻ᵅ\n    # Dᵅ = Diagonal(vec(sum(Lᵅ, dims=1)))\n    # M = inv(Dᵅ)*Lᵅ\n\n    # Eigendecomposition & reduction\n    F = eigen(M, permute=false, scale=false)\n    # for symmetric matrix, eigenvalues should be real but owing to numerical imprecision, could have nonzero-imaginary parts.\n    λ = real.(F.values) \n    idx = sortperm(λ, rev=true)[2:maxoutdim+1]\n    λ = λ[idx]\n    V = real.(F.vectors[:, idx])\n    Y = (λ .^ t) .* V'\n\n    return DiffMap{T}(t, α, ɛ, λ, L, Y)\nend\n\n\"\"\"\n    transform(R::DiffMap)\n\nTransforms the data fitted to the diffusion map model `R` into a reduced space representation.\n\"\"\"\ntransform(R::DiffMap) = R.proj\n", "meta": {"hexsha": "9c3196e245af1ebefcfbf5c725d778eec5ab7196", "size": 4045, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/diffmaps.jl", "max_stars_repo_name": "SimonEnsemble/ManifoldLearning.jl", "max_stars_repo_head_hexsha": "c0c7763ed9473352a66497bd45d6395a0756fd2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/diffmaps.jl", "max_issues_repo_name": "SimonEnsemble/ManifoldLearning.jl", "max_issues_repo_head_hexsha": "c0c7763ed9473352a66497bd45d6395a0756fd2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/diffmaps.jl", "max_forks_repo_name": "SimonEnsemble/ManifoldLearning.jl", "max_forks_repo_head_hexsha": "c0c7763ed9473352a66497bd45d6395a0756fd2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6015625, "max_line_length": 126, "alphanum_fraction": 0.6286773795, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7610574580313578}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.18\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 4aebe8f8-502d-11eb-1925-694f35421317\nmd\"\"\"\n# Recursion\n\nRecursive function calls itself with a smaller instance of the same problem and ends with a base case. Three required ingredients:\n1. Calls itself\n2. with a smaller input parameter\n3. end with a base case\n\n\nBe careful with Infinite Recursion, which can occur when\n- parameter don't decrease/increase towards the base case criteria\n- base case cannot be reached\n\n\n\"\"\"\n\n# ╔═╡ 8c30ca4a-502d-11eb-2c0b-398047ab685f\nfunction addrecursive(x)\n\tx >= 1 && error(\"x < 1\")  # Defense against infinite recursion \n    if x == 1  # if x is less than 1 this becomes an infinite recursion\n        return 1\n    else \n        return x + addrecursive(x - 1)\n    end\nend\n\n# ╔═╡ 0d1581d2-502e-11eb-2b2b-e3cc836fc2b0\n# The Call Stack of Recursion\n\n# ╔═╡ 130ca5e8-502e-11eb-3f82-5ff3930f7421\n# Recurrence Relations\n\n\n# ╔═╡ 1b0fe3ae-502e-11eb-2d34-c5a885ec3791\nmd\"\"\"\nApplications\n- Factorial\n- Reverse a string\n- Palindrome Checking\n- List permutation\n- String Permutations\n- keypad Combinations\n- deep reverse ?\n- Tower of Hanoi\n- Staircase ?\n\n\n\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─4aebe8f8-502d-11eb-1925-694f35421317\n# ╠═8c30ca4a-502d-11eb-2c0b-398047ab685f\n# ╠═0d1581d2-502e-11eb-2b2b-e3cc836fc2b0\n# ╠═130ca5e8-502e-11eb-3f82-5ff3930f7421\n# ╠═1b0fe3ae-502e-11eb-2d34-c5a885ec3791\n", "meta": {"hexsha": "f588ea1d527f99246cb814cc42d45ffb3d4b6fd8", "size": 1392, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/Recursion.jl", "max_stars_repo_name": "rojesh-shikhrakar/DSA.jl", "max_stars_repo_head_hexsha": "0982ae96555df68096dc2fd1c8d8de3a2e1e1e4d", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/Recursion.jl", "max_issues_repo_name": "rojesh-shikhrakar/DSA.jl", "max_issues_repo_head_hexsha": "0982ae96555df68096dc2fd1c8d8de3a2e1e1e4d", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Recursion.jl", "max_forks_repo_name": "rojesh-shikhrakar/DSA.jl", "max_forks_repo_head_hexsha": "0982ae96555df68096dc2fd1c8d8de3a2e1e1e4d", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.75, "max_line_length": 130, "alphanum_fraction": 0.7270114943, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8933094017937621, "lm_q1q2_score": 0.7610574545986305}}
{"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 750ded6c-f15d-11eb-02ef-5156d6bf3200\nusing BenchmarkTools, CUDA, Images, PlutoUI\n\n# ╔═╡ 8548f5a7-de5b-44a1-a0f2-55314a6152b3\nmd\"\"\"\n# Parallelizing the Julia Set\n\n##### This notebook combines the Mandelbrot set example from the Julia Computing parallel programming class with the [Julia set example by Simon Danisch](https://nextjournal.com/sdanisch/julia-gpu-programming). \n##### Also see [this Discourse thread](https://discourse.julialang.org/t/julia-sets-in-julia-using-interact-jl-id-like-to-get-it-faster/35533) on the Julia set.\n##### Interesting values for the parameter `c` were chosen from the [Julia set wikipedia page](https://en.wikipedia.org/wiki/Julia_set).\n\"\"\"\n\n# ╔═╡ 062c93ab-df7e-485e-a4bc-f7e39c013c3f\nmd\"#### A macro to view stdout\"\n\n# ╔═╡ 6d12faf1-d8bc-400a-b934-e2c36a0fcc5c\nmacro terminal(stuff)\n\tquote\n\t\twith_terminal() do\n\t\t\t$(esc(stuff))\n\t\tend\n\tend\nend\n\n# ╔═╡ 9da77179-daff-4eb7-b95b-1c5b9da5e524\nmd\"#### The escape/iteration function\"\n\n# ╔═╡ 81fa04e2-147d-496d-bea4-cfe14a67868a\nfunction escape(z0, c, maxiter)\n    z = z0\n    for i ∈ 1:maxiter\n        abs2(z) > 4 && return (i-1) % UInt8\n         z = z*z + c\n    end\n    return maxiter % UInt8\nend\n\n# ╔═╡ 62c83a9e-d5ba-4479-b3b4-4584bbf2b70f\n@terminal @code_warntype escape(1.0+1im, 0+0.5im, 5)\n\n# ╔═╡ c05f8497-0ab5-4dae-8dac-3df2bfd36355\nmd\"#### Loop through each pixel of the image and count the number of escape iterations.\"\n\n# ╔═╡ 1001c583-b7ee-47e0-87ac-2d4be6e8b23b\nfunction juliaset(;width=800, height=600, maxiter=255, c = ComplexF64(-0.512511498387847167, 0.521295573094847167))\n\treal = range(-1.5, 1.5, length=width)\n\timag = range(-1.0, 1.0, length=height)*im\n    result =  zeros(Int, height, width)\n\tfor x = 1:width\n\t\tfor y = 1:height\n\t\t\tz₀ = real[x] + imag[y]\n\t\t\tresult[y, x] = escape(z₀, c, maxiter)\n\t\tend\n\tend\n    return result\nend\n\n# ╔═╡ 55bfc407-6b22-413e-aff5-d17bfd343f87\n@terminal @code_warntype juliaset()\n\n# ╔═╡ 58eda8b1-5205-4527-8e0c-69f6a3cb7607\nmd\"#### Plot a nice Julia set image\"\n\n# ╔═╡ 4aa12ee7-dce5-4e30-a1b8-569296760cb9\njs = juliaset();\n\n# ╔═╡ 6cd3120e-8164-4177-98cf-6b96953f9567\nGray.((js)/maximum(js))\n\n# ╔═╡ 0ee22f75-e720-4fd2-b081-80eed5e57928\nmd\"\"\"\n### Choose your own `c` value\n##### Use arrows to shift by 0.05, or type a value in the field\n\"\"\"\n\n# ╔═╡ 7db79200-d9ba-4199-a2ea-4d0862b36015\nmd\"\"\"`real(c)` = $(@bind cr NumberField(-2:0.05:2, default=-0.4))\n`imag(c)` = $(@bind ci NumberField(-2:0.05:2, default=0.6))\n\"\"\"\n\n# ╔═╡ a0cdf4a6-06ce-4379-b683-5c4d67192b21\nmd\"#### Run the single-threaded benchmark on the default image\"\n\n# ╔═╡ 49f344df-bc93-4cee-9179-a75214f0f905\njss = @benchmark juliaset()\n\n# ╔═╡ 6a9382e4-7e8f-44e8-9ca2-a50d19eb35c1\nmd\"#### Parallelize with threads and benchmark\"\n\n# ╔═╡ add716ef-d45b-4aab-8e00-666adaf38c77\nfunction juliaset_threads(;width=800, height=600, maxiter=256, c = ComplexF64(-0.512511498387847167, 0.521295573094847167))\n\treal = range(-1.5, 1.5, length=width)\n\timag = range(-1, 1, length=height)*im\n    result =  zeros(Int, height, width)\n\tThreads.@threads for x = 1:width\n\t\tfor y = 1:height\n\t\t\tz₀ = real[x] + imag[y]\n\t\t\tresult[y, x] = escape(z₀, c, maxiter)\n\t\tend\n\tend\n    return result\nend\n\n# ╔═╡ 2ee833fe-31e2-4784-be9a-1a4331ee10f5\njst = @benchmark juliaset_threads()\n\n# ╔═╡ 6ffd8442-f7fc-44bc-b3e4-a7d6ddb0fb1f\nmd\"#### Parallelize with tasks\"\n\n# ╔═╡ b39c8c16-9162-46e7-9fbf-4400eb69dd17\nfunction juliaset_spawn(;width=800, height=600, maxiter=256, c = ComplexF64(-0.512511498387847167, 0.521295573094847167))\n\treal = range(-1.5, 1.5, length=width)\n\timag = range(-1, 1, length=height)*im\n    result =  zeros(Int, height, width)\n\t@sync for x = 1:width\n\t\tThreads.@spawn for y = 1:height\n\t\t\tz₀ = real[x] + imag[y]\n\t\t\tresult[y, x] = escape(z₀,c, maxiter)\n\t\tend\n\tend\n    return result\nend\n\n# ╔═╡ c1f94c04-6796-4945-9adf-b97a4ef06d56\njs_image = juliaset_spawn(c=cr+ci*im);\n\n# ╔═╡ 0d5b251f-e0bb-46fd-a3ad-6ea3618eed5b\nGray.(js_image/maximum(js_image))\n\n# ╔═╡ d7ffd22f-d634-46d2-92ed-2d8bbacb0ad5\njsp = @benchmark juliaset_spawn()\n\n# ╔═╡ f1620901-49ca-4bb5-90b7-c258c25a3e7a\nhas_cuda() ||\tmd\"#### WARNING: CUDA not available!\"\n\n# ╔═╡ 6ddaf0d0-ee62-4f36-94c6-05f3bfb18e49\nfunction run!(in, out, c; maxiter=16)\n    out .= escape.(in, c, maxiter)\nend\n\n# ╔═╡ 6341b004-4426-4e30-9015-b1ee1a75e0da\nfunction juliaset_gpu(;width=800, height=600, maxiter=256, c = ComplexF64(-0.512511498387847167, 0.521295573094847167))\n    q =  CuArray([ComplexF64(real, imag) for imag in range(-2.0, 0.5, length=width), real in range(-1.0, 1.0, length=height)])\n    result = CuArray(zeros(UInt8, size(q)))\n    run!(q, result, maxiter=maxiter)\n    return result\nend\n\n# ╔═╡ 509fa4b9-c9a6-45da-a7a5-574f5a57b8cf\nif has_cuda()\n\tjsg = @benchmark juliaset_gpu(width=width, height=height)\n\tjsgt = round(jsg.times[1]/1e6, digits=2)\nelse\n\tjsgt = 1.1 # milliseconds, approx time on a K80 (via JuliaHub)\nend\n\n# ╔═╡ 3185c612-de1e-4acb-a232-dd5dfd3949d2\nmd\"\n##### 1-thread: $(round(jss.times[1]/1e6, digits=2)) ms\n##### $(Threads.nthreads())-threads: $(round(jst.times[1]/1e6, digits=2)) ms\n##### $(800*600)-tasks: $(round(jsp.times[1]/1e6, digits=2)) ms\n##### GPU version: $jsgt ms\n\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nBenchmarkTools = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\nCUDA = \"052768ef-5323-5732-b1bb-66c8b64840ba\"\nImages = \"916415d5-f1e6-5110-898d-aaa5f9f070e0\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\n\n[compat]\nBenchmarkTools = \"~1.1.1\"\nCUDA = \"~3.3.4\"\nImages = \"~0.24.1\"\nPlutoUI = \"~0.7.9\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[AbstractFFTs]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"485ee0867925449198280d4af84bdb46a2a404d0\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"1.0.1\"\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[ArrayInterface]]\ndeps = [\"IfElse\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"Static\"]\ngit-tree-sha1 = \"655d9e28a75f88eea3fb81a12f62da9bade89fb5\"\nuuid = \"4fba245c-0d91-5ea0-9b3e-6abc04ee57a9\"\nversion = \"3.1.19\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[AxisAlgorithms]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"a4d07a1c313392a77042855df46c5f534076fab9\"\nuuid = \"13072b0f-2c55-5437-9ae7-d433b7a33950\"\nversion = \"1.0.0\"\n\n[[AxisArrays]]\ndeps = [\"Dates\", \"IntervalSets\", \"IterTools\", \"RangeArrays\"]\ngit-tree-sha1 = \"d127d5e4d86c7680b20c35d40b503c74b9a39b5e\"\nuuid = \"39de3d68-74b9-583c-8d2d-e117c070f3a9\"\nversion = \"0.4.4\"\n\n[[BFloat16s]]\ndeps = [\"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"4af69e205efc343068dc8722b8dfec1ade89254a\"\nuuid = \"ab4f0b2a-ad5b-11e8-123f-65d77653426b\"\nversion = \"0.1.0\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[BenchmarkTools]]\ndeps = [\"JSON\", \"Logging\", \"Printf\", \"Statistics\", \"UUIDs\"]\ngit-tree-sha1 = \"c31ebabde28d102b602bada60ce8922c266d205b\"\nuuid = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\nversion = \"1.1.1\"\n\n[[CEnum]]\ngit-tree-sha1 = \"215a9aa4a1f23fbd05b92769fdd62559488d70e9\"\nuuid = \"fa961155-64e5-5f13-b03f-caf6b980ea82\"\nversion = \"0.4.1\"\n\n[[CUDA]]\ndeps = [\"AbstractFFTs\", \"Adapt\", \"BFloat16s\", \"CEnum\", \"CompilerSupportLibraries_jll\", \"DataStructures\", \"ExprTools\", \"GPUArrays\", \"GPUCompiler\", \"LLVM\", \"LazyArtifacts\", \"Libdl\", \"LinearAlgebra\", \"Logging\", \"Printf\", \"Random\", \"Random123\", \"RandomNumbers\", \"Reexport\", \"Requires\", \"SparseArrays\", \"SpecialFunctions\", \"TimerOutputs\"]\ngit-tree-sha1 = \"5e696e37e51b01ae07bd9f700afe6cbd55250bce\"\nuuid = \"052768ef-5323-5732-b1bb-66c8b64840ba\"\nversion = \"3.3.4\"\n\n[[CatIndices]]\ndeps = [\"CustomUnitRanges\", \"OffsetArrays\"]\ngit-tree-sha1 = \"a0f80a09780eed9b1d106a1bf62041c2efc995bc\"\nuuid = \"aafaddc9-749c-510e-ac4f-586e18779b91\"\nversion = \"0.2.2\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"f53ca8d41e4753c41cdafa6ec5f7ce914b34be54\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"0.10.13\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[ColorVectorSpace]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"LinearAlgebra\", \"SpecialFunctions\", \"Statistics\", \"TensorCore\"]\ngit-tree-sha1 = \"42a9b08d3f2f951c9b283ea427d96ed9f1f30343\"\nuuid = \"c3611d14-8923-5661-9e6a-0046d554d3a4\"\nversion = \"0.9.5\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"344f143fa0ec67e47917848795ab19c6a455f32c\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.32.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[ComputationalResources]]\ngit-tree-sha1 = \"52cb3ec90e8a8bea0e62e275ba577ad0f74821f7\"\nuuid = \"ed09eef8-17a6-5b46-8889-db040fac31e3\"\nversion = \"0.3.2\"\n\n[[CoordinateTransformations]]\ndeps = [\"LinearAlgebra\", \"StaticArrays\"]\ngit-tree-sha1 = \"6d1c23e740a586955645500bbec662476204a52c\"\nuuid = \"150eb455-5306-5404-9cee-2592286d6298\"\nversion = \"0.6.1\"\n\n[[CustomUnitRanges]]\ngit-tree-sha1 = \"537c988076d001469093945f3bd0b300b8d3a7f3\"\nuuid = \"dc8bdbbb-1ca9-579f-8c36-e416f6a65cce\"\nversion = \"1.0.1\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"ee400abb2298bd13bfc3df1c412ed228061a2385\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.7.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"4437b64df1e0adccc3e5d1adbc3ac741095e4677\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.9\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distances]]\ndeps = [\"LinearAlgebra\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"abe4ad222b26af3337262b8afb28fab8d215e9f8\"\nuuid = \"b4f34e82-e78d-54a5-968a-f98e89d6e8f7\"\nversion = \"0.10.3\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"a32185f5428d3986f47c2ab78b1f216d5e6cc96f\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.5\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EllipsisNotation]]\ndeps = [\"ArrayInterface\"]\ngit-tree-sha1 = \"8041575f021cba5a099a456b4163c9a08b566a02\"\nuuid = \"da5c29d0-fa7d-589e-88eb-ea29b0a81949\"\nversion = \"1.1.0\"\n\n[[ExprTools]]\ngit-tree-sha1 = \"b7e3d17636b348f005f11040025ae8c6f645fe92\"\nuuid = \"e2ba6199-217a-4e67-a87a-7c52f15ade04\"\nversion = \"0.1.6\"\n\n[[FFTViews]]\ndeps = [\"CustomUnitRanges\", \"FFTW\"]\ngit-tree-sha1 = \"70a0cfd9b1c86b0209e38fbfe6d8231fd606eeaf\"\nuuid = \"4f61f5a4-77b1-5117-aa51-3ab5ef4ef0cd\"\nversion = \"0.3.1\"\n\n[[FFTW]]\ndeps = [\"AbstractFFTs\", \"FFTW_jll\", \"LinearAlgebra\", \"MKL_jll\", \"Preferences\", \"Reexport\"]\ngit-tree-sha1 = \"f985af3b9f4e278b1d24434cbb546d6092fca661\"\nuuid = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nversion = \"1.4.3\"\n\n[[FFTW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3676abafff7e4ff07bbd2c42b3d8201f31653dcc\"\nuuid = \"f5851436-0d7a-5f13-b9de-f02708fd171a\"\nversion = \"3.3.9+8\"\n\n[[FileIO]]\ndeps = [\"Pkg\", \"Requires\", \"UUIDs\"]\ngit-tree-sha1 = \"256d8e6188f3f1ebfa1a5d17e072a0efafa8c5bf\"\nuuid = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nversion = \"1.10.1\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[GPUArrays]]\ndeps = [\"AbstractFFTs\", \"Adapt\", \"LinearAlgebra\", \"Printf\", \"Random\", \"Serialization\", \"Statistics\"]\ngit-tree-sha1 = \"ececbf05f8904c92814bdbd0aafd5540b0bf2e9a\"\nuuid = \"0c68f7d7-f131-5f86-a1c3-88cf8149b2d7\"\nversion = \"7.0.1\"\n\n[[GPUCompiler]]\ndeps = [\"DataStructures\", \"ExprTools\", \"InteractiveUtils\", \"LLVM\", \"Libdl\", \"Logging\", \"TimerOutputs\", \"UUIDs\"]\ngit-tree-sha1 = \"0da0f52fc521ff23b8291e7fda54c61907609f12\"\nuuid = \"61eb1bfa-7361-4325-ad38-22787b887f55\"\nversion = \"0.12.6\"\n\n[[Graphics]]\ndeps = [\"Colors\", \"LinearAlgebra\", \"NaNMath\"]\ngit-tree-sha1 = \"2c1cf4df419938ece72de17f368a021ee162762e\"\nuuid = \"a2bd30eb-e257-5431-a919-1863eab51364\"\nversion = \"1.1.0\"\n\n[[IdentityRanges]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"be8fcd695c4da16a1d6d0cd213cb88090a150e3b\"\nuuid = \"bbac6d45-d8f3-5730-bfe4-7a449cd117ca\"\nversion = \"0.3.1\"\n\n[[IfElse]]\ngit-tree-sha1 = \"28e837ff3e7a6c3cdb252ce49fb412c8eb3caeef\"\nuuid = \"615f187c-cbe4-4ef1-ba3b-2fcf58d6d173\"\nversion = \"0.1.0\"\n\n[[ImageAxes]]\ndeps = [\"AxisArrays\", \"ImageCore\", \"Reexport\", \"SimpleTraits\"]\ngit-tree-sha1 = \"794ad1d922c432082bc1aaa9fa8ffbd1fe74e621\"\nuuid = \"2803e5a7-5153-5ecf-9a86-9b4c37f5f5ac\"\nversion = \"0.6.9\"\n\n[[ImageContrastAdjustment]]\ndeps = [\"ColorVectorSpace\", \"ImageCore\", \"ImageTransformations\", \"Parameters\"]\ngit-tree-sha1 = \"2e6084db6cccab11fe0bc3e4130bd3d117092ed9\"\nuuid = \"f332f351-ec65-5f6a-b3d1-319c6670881a\"\nversion = \"0.3.7\"\n\n[[ImageCore]]\ndeps = [\"AbstractFFTs\", \"Colors\", \"FixedPointNumbers\", \"Graphics\", \"MappedArrays\", \"MosaicViews\", \"OffsetArrays\", \"PaddedViews\", \"Reexport\"]\ngit-tree-sha1 = \"db645f20b59f060d8cfae696bc9538d13fd86416\"\nuuid = \"a09fc81d-aa75-5fe9-8630-4744c3626534\"\nversion = \"0.8.22\"\n\n[[ImageDistances]]\ndeps = [\"ColorVectorSpace\", \"Distances\", \"ImageCore\", \"ImageMorphology\", \"LinearAlgebra\", \"Statistics\"]\ngit-tree-sha1 = \"6378c34a3c3a216235210d19b9f495ecfff2f85f\"\nuuid = \"51556ac3-7006-55f5-8cb3-34580c88182d\"\nversion = \"0.2.13\"\n\n[[ImageFiltering]]\ndeps = [\"CatIndices\", \"ColorVectorSpace\", \"ComputationalResources\", \"DataStructures\", \"FFTViews\", \"FFTW\", \"ImageCore\", \"LinearAlgebra\", \"OffsetArrays\", \"Requires\", \"SparseArrays\", \"StaticArrays\", \"Statistics\", \"TiledIteration\"]\ngit-tree-sha1 = \"bf96839133212d3eff4a1c3a80c57abc7cfbf0ce\"\nuuid = \"6a3955dd-da59-5b1f-98d4-e7296123deb5\"\nversion = \"0.6.21\"\n\n[[ImageIO]]\ndeps = [\"FileIO\", \"Netpbm\", \"PNGFiles\", \"TiffImages\", \"UUIDs\"]\ngit-tree-sha1 = \"d067570b4d4870a942b19d9ceacaea4fb39b69a1\"\nuuid = \"82e4d734-157c-48bb-816b-45c225c6df19\"\nversion = \"0.5.6\"\n\n[[ImageMagick]]\ndeps = [\"FileIO\", \"ImageCore\", \"ImageMagick_jll\", \"InteractiveUtils\", \"Libdl\", \"Pkg\", \"Random\"]\ngit-tree-sha1 = \"5bc1cb62e0c5f1005868358db0692c994c3a13c6\"\nuuid = \"6218d12a-5da1-5696-b52f-db25d2ecc6d1\"\nversion = \"1.2.1\"\n\n[[ImageMagick_jll]]\ndeps = [\"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pkg\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"1c0a2295cca535fabaf2029062912591e9b61987\"\nuuid = \"c73af94c-d91f-53ed-93a7-00f77d67a9d7\"\nversion = \"6.9.10-12+3\"\n\n[[ImageMetadata]]\ndeps = [\"AxisArrays\", \"ColorVectorSpace\", \"ImageAxes\", \"ImageCore\", \"IndirectArrays\"]\ngit-tree-sha1 = \"ae76038347dc4edcdb06b541595268fca65b6a42\"\nuuid = \"bc367c6b-8a6b-528e-b4bd-a4b897500b49\"\nversion = \"0.9.5\"\n\n[[ImageMorphology]]\ndeps = [\"ColorVectorSpace\", \"ImageCore\", \"LinearAlgebra\", \"TiledIteration\"]\ngit-tree-sha1 = \"68e7cbcd7dfaa3c2f74b0a8ab3066f5de8f2b71d\"\nuuid = \"787d08f9-d448-5407-9aad-5290dd7ab264\"\nversion = \"0.2.11\"\n\n[[ImageQualityIndexes]]\ndeps = [\"ColorVectorSpace\", \"ImageCore\", \"ImageDistances\", \"ImageFiltering\", \"OffsetArrays\", \"Statistics\"]\ngit-tree-sha1 = \"1198f85fa2481a3bb94bf937495ba1916f12b533\"\nuuid = \"2996bd0c-7a13-11e9-2da2-2f5ce47296a9\"\nversion = \"0.2.2\"\n\n[[ImageShow]]\ndeps = [\"Base64\", \"FileIO\", \"ImageCore\", \"OffsetArrays\", \"Requires\", \"StackViews\"]\ngit-tree-sha1 = \"832abfd709fa436a562db47fd8e81377f72b01f9\"\nuuid = \"4e3cecfd-b093-5904-9786-8bbb286a6a31\"\nversion = \"0.3.1\"\n\n[[ImageTransformations]]\ndeps = [\"AxisAlgorithms\", \"ColorVectorSpace\", \"CoordinateTransformations\", \"IdentityRanges\", \"ImageCore\", \"Interpolations\", \"OffsetArrays\", \"Rotations\", \"StaticArrays\"]\ngit-tree-sha1 = \"d966631de06f36c8cd4bec4bb2e8fa731db16ed9\"\nuuid = \"02fcd773-0e25-5acc-982a-7f6622650795\"\nversion = \"0.8.12\"\n\n[[Images]]\ndeps = [\"AxisArrays\", \"Base64\", \"ColorVectorSpace\", \"FileIO\", \"Graphics\", \"ImageAxes\", \"ImageContrastAdjustment\", \"ImageCore\", \"ImageDistances\", \"ImageFiltering\", \"ImageIO\", \"ImageMagick\", \"ImageMetadata\", \"ImageMorphology\", \"ImageQualityIndexes\", \"ImageShow\", \"ImageTransformations\", \"IndirectArrays\", \"OffsetArrays\", \"Random\", \"Reexport\", \"SparseArrays\", \"StaticArrays\", \"Statistics\", \"StatsBase\", \"TiledIteration\"]\ngit-tree-sha1 = \"8b714d5e11c91a0d945717430ec20f9251af4bd2\"\nuuid = \"916415d5-f1e6-5110-898d-aaa5f9f070e0\"\nversion = \"0.24.1\"\n\n[[IndirectArrays]]\ngit-tree-sha1 = \"c2a145a145dc03a7620af1444e0264ef907bd44f\"\nuuid = \"9b13fd28-a010-5f03-acff-a1bbcff69959\"\nversion = \"0.5.1\"\n\n[[Inflate]]\ngit-tree-sha1 = \"f5fc07d4e706b84f72d54eedcc1c13d92fb0871c\"\nuuid = \"d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9\"\nversion = \"0.1.2\"\n\n[[IntelOpenMP_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d979e54b71da82f3a65b62553da4fc3d18c9004c\"\nuuid = \"1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0\"\nversion = \"2018.0.3+2\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[Interpolations]]\ndeps = [\"AxisAlgorithms\", \"ChainRulesCore\", \"LinearAlgebra\", \"OffsetArrays\", \"Random\", \"Ratios\", \"Requires\", \"SharedArrays\", \"SparseArrays\", \"StaticArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"1470c80592cf1f0a35566ee5e93c5f8221ebc33a\"\nuuid = \"a98d9a8b-a2ab-59e6-89dd-64a1c18fca59\"\nversion = \"0.13.3\"\n\n[[IntervalSets]]\ndeps = [\"Dates\", \"EllipsisNotation\", \"Statistics\"]\ngit-tree-sha1 = \"3cc368af3f110a767ac786560045dceddfc16758\"\nuuid = \"8197267c-284f-5f27-9208-e0e47529a953\"\nversion = \"0.5.3\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"81690084b6198a2e1da36fcfda16eeca9f9f24e4\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.1\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[LLVM]]\ndeps = [\"CEnum\", \"LLVMExtra_jll\", \"Libdl\", \"Printf\", \"Unicode\"]\ngit-tree-sha1 = \"733abcbdc67337bb6aaf873c6bebbe1e6440a5df\"\nuuid = \"929cbde3-209d-540e-8aea-75f648917ca0\"\nversion = \"4.1.1\"\n\n[[LLVMExtra_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b36c0677a0549c7d1dc8719899a4133abbfacf7d\"\nuuid = \"dad2f222-ce93-54a1-a47d-0025e8a3acab\"\nversion = \"0.0.6+0\"\n\n[[LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"DocStringExtensions\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"7bd5f6565d80b6bf753738d2bc40a5dfea072070\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.2.5\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MKL_jll]]\ndeps = [\"Artifacts\", \"IntelOpenMP_jll\", \"JLLWrappers\", \"LazyArtifacts\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c253236b0ed414624b083e6b72bfe891fbd2c7af\"\nuuid = \"856f044c-d86e-5d09-b602-aeab76dc8ba7\"\nversion = \"2021.1.1+1\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"6a8a2a625ab0dea913aba95c11370589e0239ff0\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.6\"\n\n[[MappedArrays]]\ngit-tree-sha1 = \"18d3584eebc861e311a552cbb67723af8edff5de\"\nuuid = \"dbb5928d-eab1-5f90-85c2-b9b0edb7c900\"\nversion = \"0.4.0\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"4ea90bd5d3985ae1f9a908bd4500ae88921c5ce7\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.0\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MosaicViews]]\ndeps = [\"MappedArrays\", \"OffsetArrays\", \"PaddedViews\", \"StackViews\"]\ngit-tree-sha1 = \"b34e3bc3ca7c94914418637cb10cc4d1d80d877d\"\nuuid = \"e94cdb99-869f-56ef-bcf0-1ae2bcbe0389\"\nversion = \"0.3.3\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[Netpbm]]\ndeps = [\"ColorVectorSpace\", \"FileIO\", \"ImageCore\"]\ngit-tree-sha1 = \"09589171688f0039f13ebe0fdcc7288f50228b52\"\nuuid = \"f09324ee-3d7c-5217-9330-fc30815ba969\"\nversion = \"1.0.1\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[OffsetArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"4f825c6da64aebaa22cc058ecfceed1ab9af1c7e\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.3\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PNGFiles]]\ndeps = [\"Base64\", \"CEnum\", \"ImageCore\", \"IndirectArrays\", \"OffsetArrays\", \"libpng_jll\"]\ngit-tree-sha1 = \"520e28d4026d16dcf7b8c8140a3041f0e20a9ca8\"\nuuid = \"f57f5aa1-a3ce-4bc8-8ab9-96f992907883\"\nversion = \"0.3.7\"\n\n[[PaddedViews]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"0fa5e78929aebc3f6b56e1a88cf505bb00a354c4\"\nuuid = \"5432bcbf-9aad-5242-b902-cca2824c8663\"\nversion = \"0.5.8\"\n\n[[Parameters]]\ndeps = [\"OrderedCollections\", \"UnPack\"]\ngit-tree-sha1 = \"2276ac65f1e236e0a6ea70baff3f62ad4c625345\"\nuuid = \"d96e819e-fc66-5662-9728-84c9c7592b0a\"\nversion = \"0.12.2\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"94bf17e83a0e4b20c8d77f6af8ffe8cc3b386c0a\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"1.1.1\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PkgVersion]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"a7a7e1a88853564e551e4eba8650f8c38df79b37\"\nuuid = \"eebad327-c553-4316-9ea0-9fa01ccd7688\"\nversion = \"0.1.1\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"Suppressor\"]\ngit-tree-sha1 = \"44e225d5837e2a2345e69a1d1e01ac2443ff9fcb\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.9\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[ProgressMeter]]\ndeps = [\"Distributed\", \"Printf\"]\ngit-tree-sha1 = \"afadeba63d90ff223a6a48d2009434ecee2ec9e8\"\nuuid = \"92933f4c-e287-5a05-a399-4b506db050ca\"\nversion = \"1.7.1\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Random123]]\ndeps = [\"Libdl\", \"Random\", \"RandomNumbers\"]\ngit-tree-sha1 = \"0e8b146557ad1c6deb1367655e052276690e71a3\"\nuuid = \"74087812-796a-5b5d-8853-05524746bad3\"\nversion = \"1.4.2\"\n\n[[RandomNumbers]]\ndeps = [\"Random\", \"Requires\"]\ngit-tree-sha1 = \"56ead4aaafc41d83694e17b0dd89d3e929d01a14\"\nuuid = \"e6cf234a-135c-5ec9-84dd-332b85af5143\"\nversion = \"1.5.0\"\n\n[[RangeArrays]]\ngit-tree-sha1 = \"b9039e93773ddcfc828f12aadf7115b4b4d225f5\"\nuuid = \"b3c3ace0-ae52-54e7-9d0b-2c1406fd6b9d\"\nversion = \"0.3.2\"\n\n[[Ratios]]\ngit-tree-sha1 = \"37d210f612d70f3f7d57d488cb3b6eff56ad4e41\"\nuuid = \"c84ed2f1-dad5-54f0-aa8e-dbefe2724439\"\nversion = \"0.4.0\"\n\n[[Reexport]]\ngit-tree-sha1 = \"5f6c21241f0f655da3952fd60aa18477cf96c220\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.1.0\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[Rotations]]\ndeps = [\"LinearAlgebra\", \"StaticArrays\", \"Statistics\"]\ngit-tree-sha1 = \"2ed8d8a16d703f900168822d83699b8c3c1a5cd8\"\nuuid = \"6038ab10-8711-5258-84ad-4b1120ba62dc\"\nversion = \"1.0.2\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[SimpleTraits]]\ndeps = [\"InteractiveUtils\", \"MacroTools\"]\ngit-tree-sha1 = \"5d7e3f4e11935503d3ecaf7186eac40602e7d231\"\nuuid = \"699a6c99-e7fa-54fc-8d76-47d257e15c1d\"\nversion = \"0.9.4\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"LogExpFunctions\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"508822dca004bf62e210609148511ad03ce8f1d8\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.6.0\"\n\n[[StackViews]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"46e589465204cd0c08b4bd97385e4fa79a0c770c\"\nuuid = \"cae243ae-269e-4f55-b966-ac2d0dc13c15\"\nversion = \"0.1.1\"\n\n[[Static]]\ndeps = [\"IfElse\"]\ngit-tree-sha1 = \"62701892d172a2fa41a1f829f66d2b0db94a9a63\"\nuuid = \"aedffcd0-7271-4cad-89d0-dc628f76c6d3\"\nversion = \"0.3.0\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"885838778bb6f0136f8317757d7803e0d81201e4\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.9\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"1958272568dc176a1d881acb797beb909c785510\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.0.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"fed1ec1e65749c4d96fc20dd13bea72b55457e62\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.9\"\n\n[[Suppressor]]\ngit-tree-sha1 = \"a819d77f31f83e5792a76081eee1ea6342ab8787\"\nuuid = \"fd094767-a336-5f1f-9728-57cf17d0bbfb\"\nversion = \"0.2.0\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[TensorCore]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"1feb45f88d133a655e001435632f019a9a1bcdb6\"\nuuid = \"62fd8b95-f654-4bbd-a8a5-9c27f68ccd50\"\nversion = \"0.1.1\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[TiffImages]]\ndeps = [\"ColorTypes\", \"DocStringExtensions\", \"FileIO\", \"FixedPointNumbers\", \"IndirectArrays\", \"Inflate\", \"OffsetArrays\", \"OrderedCollections\", \"PkgVersion\", \"ProgressMeter\"]\ngit-tree-sha1 = \"03fb246ac6e6b7cb7abac3b3302447d55b43270e\"\nuuid = \"731e570b-9d59-4bfa-96dc-6df516fadf69\"\nversion = \"0.4.1\"\n\n[[TiledIteration]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"52c5f816857bfb3291c7d25420b1f4aca0a74d18\"\nuuid = \"06e1c1a7-607b-532d-9fad-de7d9aa2abac\"\nversion = \"0.3.0\"\n\n[[TimerOutputs]]\ndeps = [\"ExprTools\", \"Printf\"]\ngit-tree-sha1 = \"209a8326c4f955e2442c07b56029e88bb48299c7\"\nuuid = \"a759f4b9-e2f1-59dc-863e-4aeb61b1ea8f\"\nversion = \"0.5.12\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[UnPack]]\ngit-tree-sha1 = \"387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b\"\nuuid = \"3a884ed6-31ef-47d7-9d2a-63182c4928ed\"\nversion = \"1.0.2\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[WoodburyMatrices]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"59e2ad8fd1591ea019a5259bd012d7aee15f995c\"\nuuid = \"efce3f68-66dc-5838-9240-27a6d6f5f9b6\"\nversion = \"0.5.3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─8548f5a7-de5b-44a1-a0f2-55314a6152b3\n# ╠═750ded6c-f15d-11eb-02ef-5156d6bf3200\n# ╟─062c93ab-df7e-485e-a4bc-f7e39c013c3f\n# ╠═6d12faf1-d8bc-400a-b934-e2c36a0fcc5c\n# ╟─9da77179-daff-4eb7-b95b-1c5b9da5e524\n# ╠═81fa04e2-147d-496d-bea4-cfe14a67868a\n# ╠═62c83a9e-d5ba-4479-b3b4-4584bbf2b70f\n# ╟─c05f8497-0ab5-4dae-8dac-3df2bfd36355\n# ╠═1001c583-b7ee-47e0-87ac-2d4be6e8b23b\n# ╠═55bfc407-6b22-413e-aff5-d17bfd343f87\n# ╟─58eda8b1-5205-4527-8e0c-69f6a3cb7607\n# ╠═4aa12ee7-dce5-4e30-a1b8-569296760cb9\n# ╠═6cd3120e-8164-4177-98cf-6b96953f9567\n# ╟─0ee22f75-e720-4fd2-b081-80eed5e57928\n# ╟─7db79200-d9ba-4199-a2ea-4d0862b36015\n# ╟─0d5b251f-e0bb-46fd-a3ad-6ea3618eed5b\n# ╠═c1f94c04-6796-4945-9adf-b97a4ef06d56\n# ╟─a0cdf4a6-06ce-4379-b683-5c4d67192b21\n# ╠═49f344df-bc93-4cee-9179-a75214f0f905\n# ╟─6a9382e4-7e8f-44e8-9ca2-a50d19eb35c1\n# ╟─add716ef-d45b-4aab-8e00-666adaf38c77\n# ╠═2ee833fe-31e2-4784-be9a-1a4331ee10f5\n# ╟─6ffd8442-f7fc-44bc-b3e4-a7d6ddb0fb1f\n# ╠═b39c8c16-9162-46e7-9fbf-4400eb69dd17\n# ╠═d7ffd22f-d634-46d2-92ed-2d8bbacb0ad5\n# ╠═f1620901-49ca-4bb5-90b7-c258c25a3e7a\n# ╠═6ddaf0d0-ee62-4f36-94c6-05f3bfb18e49\n# ╠═6341b004-4426-4e30-9015-b1ee1a75e0da\n# ╠═509fa4b9-c9a6-45da-a7a5-574f5a57b8cf\n# ╟─3185c612-de1e-4acb-a232-dd5dfd3949d2\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "b8b279991af1d28ff4f5c3d15298631a79050af4", "size": 31530, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "juliaset.jl", "max_stars_repo_name": "mihalybaci/scratch", "max_stars_repo_head_hexsha": "ca70b7fc6d2e067c58f024b4633316d3dab844e8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "juliaset.jl", "max_issues_repo_name": "mihalybaci/scratch", "max_issues_repo_head_hexsha": "ca70b7fc6d2e067c58f024b4633316d3dab844e8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "juliaset.jl", "max_forks_repo_name": "mihalybaci/scratch", "max_forks_repo_head_hexsha": "ca70b7fc6d2e067c58f024b4633316d3dab844e8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1406727829, "max_line_length": 417, "alphanum_fraction": 0.7338090707, "num_tokens": 14236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.7610574464757998}}
{"text": "using TaylorSeries\n#using Plots\n\n#plotlyjs()\n\ntₚ = Float64[]\nxe₁ = Float64[]\nxe₂ = Float64[]\nx₁ = Float64[]\nx₂ = Float64[]\nq₁ = Float64[]\nq₂ = Float64[]\n\nfunction linear(coeff::Vector{Float64})\n  if coeff[2] == 0.0\n    res = Complex{Float64}[Inf]\n  else\n    res = Complex{Float64}[-coeff[1] / coeff[2]]\n  end\n  return res\nend\n\nfunction quadratic(coeff::Vector{Float64})\n  if coeff[3] == 0.0\n    res = linear(coeff[1:2])\n  else\n    res = Array{Complex{Float64}}(2)\n    if coeff[1] == 0.0\n      res[1] = 0.0\n      res[2] = linear(coeff[2:3])\n    else\n      if coeff[2] == 0.0\n        r = -coeff[1] / coeff[3]\n        if r < 0.0\n          res[1] = sqrt(-r)*im\n          res[2] = -imag(res[1])*im\n        else\n          res[1] = sqrt(r)\n          res[2] = -real(res[1])\n        end\n      else\n        Δ = 1.0 - 4coeff[1]*coeff[3] / (coeff[2]*coeff[2])\n        if Δ < 0.0\n          res[1] = -0.5coeff[2]/coeff[3]+0.5coeff[2]*sqrt(-Δ)/coeff[3]*im\n          res[2] = real(res[1]) - imag(res[1])*im\n        else\n          q = -0.5*(1.0+sign(coeff[2])*sqrt(Δ))*coeff[2]\n          res[1] = q / coeff[3]\n          res[2] = coeff[1] / q\n        end\n      end\n    end\n  end\n  return res\nend\n\nfunction cubic(coeff::Vector{Float64})\n  if coeff[4] == 0.0\n    res = quadratic(coeff[1:3])\n  else\n    res = Array{Complex{Float64}}(3)\n    if coeff[1] == 0.0\n      res[1] = 0.0\n      res[2:3] = quadratic(coeff[2:4])\n    else\n      A = coeff[3]/coeff[4]\n      B = coeff[2]/coeff[4]\n      C = coeff[1]/coeff[4]\n      Q = (A^2-3B)/9\n      R = (2*A^3-9A*B+27C)/54\n      S = -A/3\n      if R^2 < Q^3\n        P = -2*sqrt(Q)\n        ϕ = acos(R/sqrt(Q^3))\n        res[1] = P*cos(ϕ/3)+S\n        res[2] = P*cos((ϕ+2π)/3)+S\n        res[3] = P*cos((ϕ-2π)/3)+S\n      else\n        T = -sign(R)*cbrt(abs(R)+sqrt(R^2-Q^3))\n        U = 0.0\n        if T != 0.0\n          U = Q/T\n        end\n        V = 0.5*(T+U)\n        W = 0.5*sqrt(3)*(T-U)\n        res[1] = S+2V\n        res[2] = S-V+W*im\n        res[3] = conj(res[2])\n      end\n    end\n  end\n  return res\nend\n\nfunction quartic(coeff::Vector{Float64})\n  if coeff[5] == 0.0\n    res = cubic(coeff[1:4])\n  else\n    res = Array{Complex{Float64}}(4)\n    if coeff[1] == 0.0\n      res[1] = 0.0\n      res[2:4] = cubic(coeff[2:5])\n    else\n      a₀ = coeff[1]/coeff[5]\n      a₁ = coeff[2]/coeff[5]\n      a₂ = coeff[3]/coeff[5]\n      a₃ = coeff[4]/coeff[5]\n      y₁ = cubic([4a₂*a₀-a₁^2-a₃^2*a₀, a₁*a₃-4a₀, -a₂, 1.0])[1]\n      R = sqrt(0.25a₃^2-a₂+y₁)\n      if R == 0.0\n        A = 0.75a₃^2-2a₂\n        B = 2*sqrt(y₁^2-4a₀)\n      else\n        A = 0.75a₃^2-R^2-2a₂\n        B = (a₃*a₂-2a₁-0.25a₃^3)/R\n      end\n      D = sqrt(A+B)\n      E = sqrt(A-B)\n      res[1] = -0.25a₃+0.5R+0.5D\n      res[2] = res[1]-D\n      res[3] = -0.25a₃-0.5R+0.5E\n      res[4] = res[3]-E\n    end\n  end\n  return res\nend\n\nfunction roots(coeff::Vector{Float64}) :: Vector{Complex{Float64}}\n  n = length(coeff)\n  if n == 1\n    res = Complex{Float64}[]\n  elseif n == 2\n    res = linear(coeff)\n  elseif n == 3\n    res = quadratic(coeff)\n  elseif n == 4\n    res = cubic(coeff)\n  elseif n == 5\n    res = quartic(coeff)\n  else\n    if coeff[n] == 0.0\n      res = roots(coeff[1:n-1])\n    else\n      res = Array{Complex{Float64}}(n-1)\n      if coeff[1] == 0.0\n        res[1] = 0.0\n        res[2:n-1] = roots(coeff[2:n])\n      else\n        mat = zeros(Float64, n-1, n-1)\n        mat[2:n-1, 1:n-2] = eye(Float64, n-2)\n        mat[:, n-1] = - coeff[1:n-1] / coeff[n]\n        res[1:n-1] = eigvals(mat)\n        #res[1:n-1] = roots(Poly(coeff))\n      end\n    end\n  end\n  return res\nend\n\nfunction brent(f::Function, x0::Number, x1::Number, args...;\n               xtol::AbstractFloat=1e-7, ytol=2eps(Float64),\n               maxiter::Integer=50)\n    EPS = eps(Float64)\n    y0 = f(x0,args...)\n    y1 = f(x1,args...)\n    if abs(y0) < abs(y1)\n        # Swap lower and upper bounds.\n        x0, x1 = x1, x0\n        y0, y1 = y1, y0\n    end\n    x2 = x0\n    y2 = y0\n    x3 = x2\n    bisection = true\n    for _ in 1:maxiter\n        # x-tolerance.\n        if abs(x1-x0) < xtol\n            return x1\n        end\n\n        # Use inverse quadratic interpolation if f(x0)!=f(x1)!=f(x2)\n        # and linear interpolation (secant method) otherwise.\n        if abs(y0-y2) > ytol && abs(y1-y2) > ytol\n            x = x0*y1*y2/((y0-y1)*(y0-y2)) +\n                x1*y0*y2/((y1-y0)*(y1-y2)) +\n                x2*y0*y1/((y2-y0)*(y2-y1))\n        else\n            x = x1 - y1 * (x1-x0)/(y1-y0)\n        end\n\n        # Use bisection method if satisfies the conditions.\n        delta = abs(2EPS*abs(x1))\n        min1 = abs(x-x1)\n        min2 = abs(x1-x2)\n        min3 = abs(x2-x3)\n        if (x < (3x0+x1)/4 && x > x1) ||\n           (bisection && min1 >= min2/2) ||\n           (!bisection && min1 >= min3/2) ||\n           (bisection && min2 < delta) ||\n           (!bisection && min3 < delta)\n            x = (x0+x1)/2\n            bisection = true\n        else\n            bisection = false\n        end\n\n        y = f(x,args...)\n        # y-tolerance.\n        if abs(y) < ytol\n            return x\n        end\n        x3 = x2\n        x2 = x1\n        if sign(y0) != sign(y)\n            x1 = x\n            y1 = y\n        else\n            x0 = x\n            y0 = y\n        end\n        if abs(y0) < abs(y1)\n            # Swap lower and upper bounds.\n            x0, x1 = x1, x0\n            y0, y1 = y1, y0\n        end\n    end\n    error(\"Max iteration exceeded\")\nend\n\nfunction integrate_ode(f::Function, q₀::Float64, q::Vector{Taylor1{Float64}}, order::Int, i::Int)\n  q[i].coeffs[2:end] = 0.0\n  q[i].coeffs[1] = q₀\n  for n in 1:order\n    q[i].coeffs[n+1] = f(q).coeffs[n]/n\n  end\n  q[i]\nend\n\nfunction nth_derivative(q₀::Float64, f::Function, q::Vector{Taylor1{Float64}}, order::Int, i::Int)\n  q[i].coeffs[2:end] = 0.0\n  q[i].coeffs[1] = q₀\n  q[i] = integrate(f(q), q₀)\n  for k in 1:order-1\n    q[i] = integrate(f(q), q₀)\n  end\n  q[i].coeffs[end]\n  #integrate_ode(f, q₀, q, order, i).coeffs[end]\nend\n\nfunction f₁(q::Vector)\n  0.01*q[2]\nend\n\nfunction f₂(q::Vector)\n  2020.0-100.0*q[1]-100.0*q[2]\nend\n\nfunction test(order::Int, Δq::Float64, duration::Float64)\n  λ, P = eig([0.0 0.01; -100.0 -100.0])\n  C = inv(P)*[0.0; 2020.0]\n  E = -C./λ\n  D = -E + inv(P)*[0.0; 20.0]\n  f = [f₁, f₂]\n  q = [0*Taylor1(zeros(order+1))+0.0, 0*Taylor1(zeros(order+1))+20.0]\n  x = [integrate(f[1](q), 0.0), integrate(f[2](q), 20.0)]\n  for i in 1:order-1\n    q = deepcopy(x)\n    x = [integrate(f[1](q), 0.0), integrate(f[2](q), 20.0)]\n  end\n  #q = deepcopy(x)\n  #q[1].coeffs[end] = 0.0\n  #q[2].coeffs[end] = 0.0\n  tₙ = [0.0, 0.0]\n  t = 0.0\n  it = [0, 0]\n  start = true\n  while t < duration && sum(it) < 100000\n    tₒ = t\n    t, i = findmin(tₙ)\n    ##println(\"-------- $tₙ, $i\")\n    j = 3 - i\n    it[i] += 1\n    xe = P*diagm(exp.(λ*t))*inv(P)*[0.0; 20.0]+P*diagm((exp.(λ*t)-1)./λ)*inv(P)*[0.0;2020.0]\n    if t-tₒ > 0.0\n      for tt in 0.0:(t-tₒ)/20:t-tₒ\n        xe = P*diagm(exp.(λ*(tₒ+tt)))*inv(P)*[0.0; 20.0]+P*diagm((exp.(λ*(tₒ+tt))-1)./λ)*inv(P)*[0.0;2020.0]\n        push!(tₚ, tₒ+tt)\n        push!(x₁, evaluate(x[1], tt))#x[1].coeffs[1])\n        push!(x₂, evaluate(x[2], tt))#x[2].coeffs[1])\n        push!(q₁, evaluate(q[1], tt))#q[1].coeffs[1])\n        push!(q₂, evaluate(q[2], tt))#q[2].coeffs[1])\n        push!(xe₁, xe[1])\n        push!(xe₂, xe[2])\n      end\n    end\n    x₀ = evaluate(x[i], t-tₒ)\n    x[i] = evaluate(x[i], Taylor1([t-tₒ, 1.0]))\n    q[i] = evaluate(q[i], Taylor1([t-tₒ, 1.0]))\n    ##println(\"$t, $i, q = $(q[i])\")\n    q[j] = evaluate(q[j], Taylor1([t-tₒ, 1.0]))\n    ##println(\"$t, $j, q = $(q[j])\")\n    q[i] = deepcopy(x[i])\n    q[i][end] = 0.0\n    tₙ[i] = t + (abs(Δq/x[i].coeffs[end]))^(1.0/order)\n    #println(\"$t, $i, q = $(q[i])\")\n    #println(\"$t, $i, x = $(x[i])\")\n    x₀ = evaluate(x[j], t-tₒ)\n    x[j] = integrate(f[j](q), x₀)\n    #println(\"$t, $j, x = $(x[j])\")\n    p = (x[j]-q[j]).coeffs\n    p[1] -= Δq\n    a = roots(p)\n    p[1] += 2Δq\n    b = roots(p)\n    r = filter(v->abs(imag(v)) < 1.0e-15 && real(v)>=0.0, [a..., b...])\n    min_r = Inf\n    for val_r in r\n      if real(val_r) < min_r\n        min_r = real(val_r)\n      end\n    end\n    tₙ[j] = t + min_r\n    # t₂ = brent(nth_derivative_time, 0.0, tₙ[j]-t, f[j], deepcopy(q), order, i)\n    # println(\"$(tₙ[j]), $(t₂+t)\")\n    # if t₂ > 0.0 && t + t₂ < tₙ[j]\n    #   tₙ[j] = t + t₂\n    # end\n    # if start\n    #   tₙ[j] = 0.0\n    #   start = false\n    # end\n  end\n  println(it)\nend\nδ = 1e-6\n@time test(4, δ, 500.0)\n#plot(tₚ, [abs(x₁-xe₁), abs(x₂-xe₂)])\nprintln(\"$(mean(abs.(x₁-xe₁))), $(maximum(abs.(x₁-xe₁))), $(mean(abs.(x₂-xe₂))), $(maximum(abs.(x₂-xe₂))), $(2δ)\")\n#plot(tₚ, [x₁, q₁, xe₁, x₂, q₂, xe₂])\n", "meta": {"hexsha": "e7f611fc96225683ad14e936d0c40ef08cb5b17c", "size": 8593, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/prototyping/proto2.jl", "max_stars_repo_name": "JuliaTagBot/QuantizedStateSystems.jl", "max_stars_repo_head_hexsha": "5b58f55bf8dcdf33549f0f718c1b43cf245ceea4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-03-23T00:03:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T10:02:14.000Z", "max_issues_repo_path": "test/prototyping/proto2.jl", "max_issues_repo_name": "JuliaTagBot/QuantizedStateSystems.jl", "max_issues_repo_head_hexsha": "5b58f55bf8dcdf33549f0f718c1b43cf245ceea4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/prototyping/proto2.jl", "max_forks_repo_name": "JuliaTagBot/QuantizedStateSystems.jl", "max_forks_repo_head_hexsha": "5b58f55bf8dcdf33549f0f718c1b43cf245ceea4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:00:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:00:57.000Z", "avg_line_length": 25.2735294118, "max_line_length": 114, "alphanum_fraction": 0.4757360642, "num_tokens": 3622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7610574433149914}}
{"text": "## PART 3\n\nprintln(\"\\nPart 3\");\n\n# Estimate the covariance matrix for these quantities\nprintln(\"\\n\\tCalculating the covariance matrices, Cmoldy_1069 and Cmoldy_1304\");\n\n# Calculate the mean values of each quantity\nmdavg_1069 = zeros(3);\nmdavg_1304 = zeros(3);\nfor n in 1:3\n    mdavg_1069[n] = mean(md_1069[:,n]);\n    mdavg_1304[n] = mean(md_1304[:,n]);\nend\n\n# Calculate the covariance for T = 1.069...\nprintln(\"\\n\\tCovariance matrix for T = 1.069:\\n\")\nD = md_1069 - ones(lengthmd) * transpose(mdavg_1069);\nCmoldy_1069 = transpose(D) * D ./ lengthmd\nshow(Cmoldy_1069)\n\n# ...and for T = 1.304.\nprintln(\"\\n\\n\\tCovariance matrix for T = 1.304\\n\")\nD = md_1304 - ones(lengthmd) * transpose(mdavg_1304);\nCmoldy_1304 = transpose(D) * D ./ lengthmd;\nshow(Cmoldy_1304)\n", "meta": {"hexsha": "2cab42d7ae806d13c446ff914cde219db29c7218", "size": 759, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "set03/q4/p3.jl", "max_stars_repo_name": "stefco/g6080", "max_stars_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "set03/q4/p3.jl", "max_issues_repo_name": "stefco/g6080", "max_issues_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "set03/q4/p3.jl", "max_forks_repo_name": "stefco/g6080", "max_forks_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1111111111, "max_line_length": 80, "alphanum_fraction": 0.7009222661, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673113726775, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7610222881199763}}
{"text": "export make_continuous!\n\n\"\"\"\n`make_continuous!(vals,mod)` assumes that the list of numbers in `vals`\nshould represent a continuous stream of numbers, but with ambiguity modulo `mod`.\nFor example, they are the angles of a continuous list of complex values, but there\nis an ambiguity modulo 2π. This function adjusts the values so they\nappear continuous.\n\nFor finer control, use `make_continuous!(vals,mod,thresh)` where `thresh` is\nthe maximum allowable difference between consecutive entries in `val`.\n\"\"\"\nfunction make_continuous!(vals::Array{T,1}, mod::Real, thresh::Real) where T\n    @assert mod>0 \"mod must be positive, not $mod\"\n    @assert thresh>0 \"threshold must be positive, not $thresh\"\n    @assert thresh<mod/2 \"threshold must be less than half the modulus, not $thresh\"\n\n    nvals = length(vals)\n    for j=2:nvals\n        while abs(vals[j-1]-vals[j]) > thresh\n            if vals[j] < vals[j-1]\n                vals[j] += mod\n            else\n                vals[j] -= mod\n            end\n        end\n    end\n    nothing\nend\nmake_continuous!(vals::Array{T,1}, mod::Real) where T = make_continuous!(vals, mod, mod/5)\n", "meta": {"hexsha": "07a376fda24b71187d584a4dce52f352cc735e27", "size": 1129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/make_continuous.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleTools.jl-4696fa5f-36f0-5b18-99a6-fef83351280f", "max_stars_repo_head_hexsha": "0c1d97931f575a44e679d3b0dade526e86082491", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/make_continuous.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleTools.jl-4696fa5f-36f0-5b18-99a6-fef83351280f", "max_issues_repo_head_hexsha": "0c1d97931f575a44e679d3b0dade526e86082491", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/make_continuous.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleTools.jl-4696fa5f-36f0-5b18-99a6-fef83351280f", "max_forks_repo_head_hexsha": "0c1d97931f575a44e679d3b0dade526e86082491", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4193548387, "max_line_length": 90, "alphanum_fraction": 0.6740478299, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7610158030912375}}
{"text": "\nusing DiffEqBayes\n\n\nusing Distributions\nusing OrdinaryDiffEq, RecursiveArrayTools, ParameterizedFunctions, DiffEqUncertainity\nusing Plots\nusing DiffEqMonteCarlo\n\n\ngr(fmt=:png)\n\n\nf = @ode_def LotkaVolterraTest begin\n    dx = a*x - b*x*y\n    dy = -c*y + d*x*y\nend a b c d\n\n\nu0 = [1.0,1.0]\ntspan = (0.0,10.0)\np = [1.5,1.0,3.0,1,0]\n\n\nprob = ODEProblem(f,u0,tspan,p)\nsol = solve(prob,Tsit5())\n\n\nt = collect(range(1,stop=10,length=10))\nsig = 0.49\ndata = convert(Array, VectorOfArray([(sol(t[i]) + sig*randn(2)) for i in 1:length(t)]))\n\n\nscatter(t, data[1,:], lab=\"#prey (data)\")\nscatter!(t, data[2,:], lab=\"#predator (data)\")\nplot!(sol)\n\n\npriors = [Truncated(Normal(1.5,0.5),0.5,2.5),Truncated(Normal(1.2,0.5),0,2),Truncated(Normal(3.0,0.5),1,4),Truncated(Normal(1.0,0.5),0,2)]\n\n\ncb = AdaptiveProbIntsUncertainty(5)\nmonte_prob = MonteCarloProblem(prob)\nsim = solve(monte_prob,Tsit5(),num_monte=100,callback=cb,reltol=1e-5,abstol=1e-5)\nplot(sim,vars=(0,1),linealpha=0.4)\n\n\n@time bayesian_result_stan = stan_inference(prob,t,data,priors;reltol=1e-5,abstol=1e-5,vars =(StanODEData(),InverseGamma(3,2)))\n\n\nplot_chain(bayesian_result_stan)\n\n\n@time bayesian_result_turing = turing_inference(prob,Tsit5(),t,data,priors)\n\n\nplot_chain(bayesian_result_turing)\n\n", "meta": {"hexsha": "0d32cfb52630f2c62b18a8b98eac3eaefd34daea", "size": 1246, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ParameterEstimation/DiffEqBayesLotkaVolterra.jl", "max_stars_repo_name": "jamesjscully/DiffEqBenchmarks.jl", "max_stars_repo_head_hexsha": "4a47f59717f3166864fa4f1b96a0faa5a0db7764", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-01T00:02:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T00:02:56.000Z", "max_issues_repo_path": "script/ParameterEstimation/DiffEqBayesLotkaVolterra.jl", "max_issues_repo_name": "jamesjscully/DiffEqBenchmarks.jl", "max_issues_repo_head_hexsha": "4a47f59717f3166864fa4f1b96a0faa5a0db7764", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/ParameterEstimation/DiffEqBayesLotkaVolterra.jl", "max_forks_repo_name": "jamesjscully/DiffEqBenchmarks.jl", "max_forks_repo_head_hexsha": "4a47f59717f3166864fa4f1b96a0faa5a0db7764", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1186440678, "max_line_length": 138, "alphanum_fraction": 0.7070626003, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7610157982525002}}
{"text": "# This is basically maple/lda_c_vwn.mpl and maple/vwn.mpl from libxc\n#\n# LDA correlation according to Vosko Wilk,and Nusair, (DOI 10.1139/p80-159)\n#\n# This version generates the \"standard\" parametrization, where a Pade approximation of a\n# numerical diffusion Monte-Carlo simulation is used.\n\nas_rational(x) = nsimplify(Sym(x))\n\nA_vwn  = as_rational.([ 0.0310907, 0.01554535, -1/(6*PI^2)])\nb_vwn  = as_rational.([ 3.72744,   7.06042,    1.13107  ])\nc_vwn  = as_rational.([12.9352,   18.0578,    13.0045   ])\nx0_vwn = as_rational.([-0.10498,  -0.32500,   -0.0047584])\n\nA_rpa  = as_rational.([ 0.0310907,  0.01554535,  -1/(6*PI^2)])\nb_rpa  = as_rational.([13.0720,    20.1231,      1.06835  ])\nc_rpa  = as_rational.([42.7198,   101.578,      11.4813   ])\nx0_rpa = as_rational.([-0.409286,  -0.743294,   -0.228344 ])\n\nQ(b, c)      = sqrt(4*c - b^2)\nf1(b, c)     = 2*b/Q(b, c)\nf2(b, c, x0) = b*x0/(x0^2 + b*x0 + c)\nf3(b, c, x0) = 2*(2x0 + b)/Q(b, c)\n\nfpp = 4/(9*(2^(1//3) - 1))\n\nfx(b, c, rs) = rs + b*sqrt(rs) + c\n\nf_aux(A, b, c, x0, rs) = A*(\n  + log(rs/fx(b, c, rs))\n  + (f1(b, c) - f2(b, c, x0)*f3(b, c, x0))*atan(Q(b, c)/(2*sqrt(rs) + b))\n  - f2(b, c, x0)*log((sqrt(rs) - x0)^2/fx(b, c, rs))\n)\n\nDMC(rs, z) = (\n    + f_aux(A_vwn[2], b_vwn[2], c_vwn[2], x0_vwn[2], rs)\n    - f_aux(A_vwn[1], b_vwn[1], c_vwn[1], x0_vwn[1], rs)\n)\n\nDRPA(rs, z) = (\n    + f_aux(A_rpa[2], b_rpa[2], c_rpa[2], x0_rpa[2], rs)\n    - f_aux(A_rpa[1], b_rpa[1], c_rpa[1], x0_rpa[1], rs)\n)\n\nf_vwn(rs, z) = (\n  + f_aux(A_vwn[1], b_vwn[1], c_vwn[1], x0_vwn[1], rs)\n  + f_aux(A_vwn[3], b_vwn[3], c_vwn[3], x0_vwn[3], rs)*f_zeta(z)*(1 - z^4)/fpp\n  +  DMC(rs, z)*f_zeta(z)*z^4\n)\n\nf(rs, z, junk...) = f_vwn(rs, z)\n", "meta": {"hexsha": "d10100d6befab75d59f389a7ff4274b79f227ea3", "size": 1677, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "codegen/xc_fallback/lda_c_vwn.jl", "max_stars_repo_name": "chemicalfiend/DFTK.jl", "max_stars_repo_head_hexsha": "757122b9e23ddefda9dae59c175a4260c81c8836", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 243, "max_stars_repo_stars_event_min_datetime": "2019-11-26T19:51:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T08:29:35.000Z", "max_issues_repo_path": "codegen/xc_fallback/lda_c_vwn.jl", "max_issues_repo_name": "chemicalfiend/DFTK.jl", "max_issues_repo_head_hexsha": "757122b9e23ddefda9dae59c175a4260c81c8836", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 372, "max_issues_repo_issues_event_min_datetime": "2019-11-10T09:28:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:32:08.000Z", "max_forks_repo_path": "codegen/xc_fallback/lda_c_vwn.jl", "max_forks_repo_name": "chemicalfiend/DFTK.jl", "max_forks_repo_head_hexsha": "757122b9e23ddefda9dae59c175a4260c81c8836", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53, "max_forks_repo_forks_event_min_datetime": "2020-03-13T18:23:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T08:29:38.000Z", "avg_line_length": 32.25, "max_line_length": 88, "alphanum_fraction": 0.5676803816, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109728022221, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7609864668870442}}
{"text": "function retro_substituicao(A, b)\n    n = size(A)[2]\n    x = zeros(n)\n    x[n] = b[n]/A[n,n]\n    for i = n-1:-1:1\n        temp = 0\n        for k = i+1:n\n            temp += A[i,k]*x[k]\n        end\n        x[i] = (b[i]-temp)/A[i,i]\n    end\n    return x\nend\n\n\nfunction substituicao(A, b)\n    n = size(A)[2]\n    x = zeros(n)\n    x[1] = b[1]/A[1,1]\n    for i = 2:n\n        temp = 0\n        for k = 1:i-1\n            temp += A[i,k]*x[k]\n        end\n        x[i] = (b[i]-temp)/A[i,i]\n    end\n    return x\nend\n\n\nfunction eliminacao(A)\n    row, col = size(A)\n    for j in 1:row-1\n        for i in j+1:row\n            m = A[i,j]/A[j,j]\n            A[i,:] = A[i,:]-m*A[j,:]\n        end\n    end\n    return A\nend\n\nfunction fatoracao_lu(A)\n    row, col = size(A)\n    L = eye(row)\n\n    for j in 1:row-1\n        for i in j+1:row\n            L[i,j] = A[i,j]/A[j,j]\n            A[i,:] = A[i,:]-L[i,j]*A[j,:]\n        end\n    end\n\n    U = A[:, 1:end-1]\n    return L, A\nend\n\nfunction resolve_fatlu(A)\n    for i in 6:8\n        L, U = fatoracao_lu(A[:, [1:5; i]])\n        println(\"A fatoração LU estará coreta se L*U for igual a A \")\n        println(L*U, A)\n\n        y = substituicao(L, b)\n        x = retro_substituicao(U, y)\n        println(\"Valor do y é $y o valor do x é $x\")\n    end\nend\n", "meta": {"hexsha": "79b10bb87e2e9ddd2bd3f7e765d3869ae654c88e", "size": 1270, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "003 - Sistemas_Lineares.jl", "max_stars_repo_name": "LudwigFonseca/Julia-Language-Examples", "max_stars_repo_head_hexsha": "0e293e78d8d4d1c36eb1211ee65328d81016277a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "003 - Sistemas_Lineares.jl", "max_issues_repo_name": "LudwigFonseca/Julia-Language-Examples", "max_issues_repo_head_hexsha": "0e293e78d8d4d1c36eb1211ee65328d81016277a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "003 - Sistemas_Lineares.jl", "max_forks_repo_name": "LudwigFonseca/Julia-Language-Examples", "max_forks_repo_head_hexsha": "0e293e78d8d4d1c36eb1211ee65328d81016277a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6764705882, "max_line_length": 69, "alphanum_fraction": 0.4409448819, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109756113862, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7609864600960419}}
{"text": "@doc raw\"\"\"\n# Lorenz Attractor\n\n\"\"\"\nmodule LorenzAttractor\n\n    using GeometricEquations\n\n    export lorenz_attractor_ode, plot_lorenz_attractor\n\n\n    Δt = 0.01\n    nt = 1000\n\n    const q₀ = [1., 1., 1.]\n    const default_params = (σ = 10., ρ = 28., β = 8/3)\n\n    function lorenz_attractor_v(t, x, v, params=default_params)\n        σ, ρ, β = params\n        v[1] = σ * (x[2] - x[1])\n        v[2] = x[1] * (ρ - x[3]) - x[2]\n        v[3] = x[1] * x[2] - β * x[3]\n        nothing\n    end\n\n\n    function lorenz_attractor_ode(q₀=q₀)\n        ODE(lorenz_attractor_v, q₀)\n    end\n\nend\n", "meta": {"hexsha": "93c0329da349ce79ed8da033f1c86d4f0601aef5", "size": 576, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lorenz_attractor.jl", "max_stars_repo_name": "DDMGNI/GeometricProblems.jl", "max_stars_repo_head_hexsha": "367f4cf63ff614c3051c7760b835889fdb7a040f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lorenz_attractor.jl", "max_issues_repo_name": "DDMGNI/GeometricProblems.jl", "max_issues_repo_head_hexsha": "367f4cf63ff614c3051c7760b835889fdb7a040f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-02-11T01:23:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-24T11:06:23.000Z", "max_forks_repo_path": "src/lorenz_attractor.jl", "max_forks_repo_name": "DDMGNI/GeometricProblems.jl", "max_forks_repo_head_hexsha": "367f4cf63ff614c3051c7760b835889fdb7a040f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0, "max_line_length": 63, "alphanum_fraction": 0.546875, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109756113862, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7609864600960419}}
{"text": "# # Auto-tuning Hyperparameters\n\n#md # [![](https://img.shields.io/badge/show-github-579ACA.svg)](@__REPO_ROOT_URL__/docs/src/examples/autotuning-ridge.jl)\n\n# This example shows how to learn a hyperparameter in Ridge Regression using a gradient descent routine.\n# Let the regularized regression problem be formulated as:\n\n# ```math\n# \\begin{equation}\n# \\min_{w} \\quad \\frac{1}{2nd} \\sum_{i=1}^{n} (w^T x_{i} - y_i)^2 + \\frac{\\alpha}{2d} \\| w \\|_2^2\n# \\end{equation}\n# ```\n\n# where \n# - `x`, `y` are the data points\n# - `w` are the learned weights\n# - `α` is the hyperparameter acting on regularization.\n\n# The main optimization model will be formulated with JuMP.\n# Using the gradient of the optimal weights with respect to the regularization parameters\n# computed with DiffOpt, we can perform a gradient descent on top of the inner model\n# to minimize the test loss.\n\n# This tutorial uses the following packages\n\nusing JuMP     # The mathematical programming modelling language\nimport DiffOpt # JuMP extension for differentiable optimization\nimport Ipopt    # Optimization solver that handles quadratic programs\nimport Plots   # Graphing tool\nimport LinearAlgebra: norm, dot\nimport Random\n\n# ## Generating a noisy regression dataset\n\nRandom.seed!(42)\n\nN = 100\nD = 20\nnoise = 5\n\nw_real = 10 * randn(D)\nX = 10 * randn(N, D)\ny = X * w_real + noise * randn(N)\nl = N ÷ 2  # test train split\n\nX_train = X[1:l, :]\nX_test  = X[l+1:N, :]\ny_train = y[1:l]\ny_test  = y[l+1:N];\n\n# ## Defining the regression problem\n\n# We implement the regularized regression problem as a function taking the problem data,\n# building a JuMP model and solving it.\n\nfunction fit_ridge(model, X, y, α)\n    JuMP.empty!(model)\n    set_silent(model)\n    N, D = size(X)\n    @variable(model, w[1:D])\n    @expression(model, err_term, X * w - y)\n    @objective(\n        model,\n        Min,\n        dot(err_term, err_term) / (2 * N * D) + α * dot(w, w) / (2 * D),\n    )\n    optimize!(model)\n    @assert termination_status(model) in [MOI.OPTIMAL, MOI.LOCALLY_SOLVED, MOI.ALMOST_LOCALLY_SOLVED]\n    return w\nend\n\n# We can solve the problem for several values of α\n# to visualize the effect of regularization on the testing and training loss.\n\nαs = 0.00:0.01:0.50\nmse_test = Float64[]\nmse_train = Float64[]\nmodel = Model(() -> DiffOpt.diff_optimizer(Ipopt.Optimizer))\n(Ntest, D) = size(X_test)\n(Ntrain, D) = size(X_train)\nfor α in αs\n    w = fit_ridge(model, X_train, y_train, α)\n    ŵ = value.(w)\n    ŷ_test = X_test * ŵ \n    ŷ_train = X_train * ŵ \n    push!(mse_test, norm(ŷ_test - y_test)^2 / (2 * Ntest * D))\n    push!(mse_train, norm(ŷ_train - y_train)^2 / (2 * Ntrain * D))\nend\n\n# Visualize the Mean Score Error metric\n\nPlots.plot(\n    αs, mse_test ./ sum(mse_test),\n    label=\"MSE test\", xaxis = \"α\", yaxis=\"MSE\", legend=(0.8, 0.2),\n    width=3,\n)\nPlots.plot!(\n    αs, mse_train ./ sum(mse_train),\n    label=\"MSE train\",\n    linestyle=:dash,\n    width=3,\n)\nPlots.title!(\"Normalized MSE on training and testing sets\")\n\n# ## Leveraging differentiable optimization: computing the derivative of the solution\n\n# Using DiffOpt, we can compute `∂w_i/∂α`, the derivative of the learned solution `̂w`\n# w.r.t. the regularization parameter.\n\nfunction compute_dw_dα(model, w)\n    D = length(w)\n    dw_dα = zeros(D)\n    MOI.set(\n        model, \n        DiffOpt.ForwardObjectiveFunction(),\n        dot(w, w)  / (2 * D),\n    )\n    DiffOpt.forward_differentiate!(model)\n    for i in 1:D\n        dw_dα[i] = MOI.get(\n            model,\n            DiffOpt.ForwardVariablePrimal(), \n            w[i],\n        )\n    end\n    return dw_dα\nend\n\n# Using `∂w_i/∂α` computed with `compute_dw_dα`,\n# we can compute the derivative of the test loss w.r.t. the parameter α\n# by composing derivatives.\n\nfunction d_testloss_dα(model, X_test, y_test, w, ŵ)\n    N, D = size(X_test)\n    dw_dα = compute_dw_dα(model, w)\n    err_term = X_test * ŵ - y_test\n    return sum(eachindex(err_term)) do i\n        dot(X_test[i,:], dw_dα) * err_term[i]\n    end / (N * D)\nend\n\n# We can define a meta-optimizer function performing gradient descent\n# on the test loss w.r.t. the regularization parameter.\n\nfunction descent(α0, max_iters=100; fixed_step = 0.01, grad_tol=1e-3)\n    α_s = Float64[]\n    ∂α_s = Float64[]\n    test_loss = Float64[]\n    α = α0\n    N, D = size(X_test)\n    model = Model(() -> DiffOpt.diff_optimizer(Ipopt.Optimizer))\n    for iter in 1:max_iters\n        w = fit_ridge(model, X_train, y_train, α)\n        ŵ = value.(w)\n        err_term = X_test * ŵ - y_test\n        ∂α = d_testloss_dα(model, X_test, y_test, w, ŵ)\n        push!(α_s, α)\n        push!(∂α_s, ∂α)\n        push!(test_loss, norm(err_term)^2 / (2 * N * D))\n        α -= fixed_step * ∂α\n        if abs(∂α) ≤ grad_tol\n            break\n        end\n    end\n    return α_s, ∂α_s, test_loss\nend\n\nᾱ, ∂ᾱ, msē = descent(0.10, 500)\niters = 1:length(ᾱ);\n\n# Visualize gradient descent and convergence\n\nPlots.plot(\n    αs, mse_test,\n    label=\"MSE test\", xaxis = (\"α\"),\n    legend=:topleft,\n    width=2,\n)\nPlots.plot!(\n    ᾱ, msē,\n    label=\"learned α\", width = 5,\n    style=:dot,\n)\nPlots.title!(\"Regularizer learning\")\n\n# Visualize the convergence of α to its optimal value\n\nPlots.plot(\n    iters, ᾱ, label = nothing, color = :blue,\n    xaxis = (\"Iterations\"), legend=:bottom,\n    title = \"Convergence of α\"\n)\n\n# Visualize the convergence of the objective function\n\nPlots.plot(\n    iters, msē, label = nothing, color = :red,\n    xaxis = (\"Iterations\"), legend=:bottom,\n    title = \"Convergence of MSE\"\n)\n\n# Visualize the convergence of the derivative to zero\n\nPlots.plot(\n    iters, ∂ᾱ, label = nothing, color = :green,\n    xaxis = (\"Iterations\"), legend=:bottom,\n    title = \"Convergence of ∂α\"\n)\n", "meta": {"hexsha": "5bea5b88654c32c4973ada19041a2300bd33be66", "size": 5708, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/autotuning-ridge.jl", "max_stars_repo_name": "AKS1996/DiffOpt.jl", "max_stars_repo_head_hexsha": "8dfa684c49ad51a0e6801c4b7f1ea3d167c84812", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-05-22T11:38:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T12:18:47.000Z", "max_issues_repo_path": "docs/src/examples/autotuning-ridge.jl", "max_issues_repo_name": "AKS1996/DiffOpt.jl", "max_issues_repo_head_hexsha": "8dfa684c49ad51a0e6801c4b7f1ea3d167c84812", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-05-21T20:29:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-27T06:57:03.000Z", "max_forks_repo_path": "docs/src/examples/autotuning-ridge.jl", "max_forks_repo_name": "AKS1996/DiffOpt.jl", "max_forks_repo_head_hexsha": "8dfa684c49ad51a0e6801c4b7f1ea3d167c84812", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3110047847, "max_line_length": 122, "alphanum_fraction": 0.6464611072, "num_tokens": 1758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8740772318846386, "lm_q1q2_score": 0.7609692416526694}}
{"text": "\"\"\"\nSo, ReX = oscillatory integral + hyperbolic integral. I expanded the first integral ages ago, but it was not an arbitrary precision algorithm. I tested solving ReX with this old expansion for the oscillatory integral added to the hyperbolic integral solved by arbitrary precision quadgk, and it still diverged when digits beyond Float64 became important. Thus, the oscillatory integral needs to be rewritten in the arbitrary precision summation algorithm (the algorithm I used for BesselI-StruveL). I will do this here and also test it against brute forcing the integral with arb. prec. quadgk provided quadgk manages to solve this!\n\"\"\"\n\ninclude(\"bessel_minus_struve.jl\")\nimport .bessel_minus_struve\n\nusing QuadGK\nusing Plots\nusing ArbNumerics\nplotly()\nPlots.PlotlyBackend()\n\nfunction oscillatory_integral(Ω, β, α, v, w)\n\n    R = (v^2 - w^2) / (w^2 * v)\n    a = sqrt(β^2 / 4 + R * β * coth(β * v / 2))\n    b = R * β / sinh(β * v / 2)\n\n    coefficient = 2 * α * β^(3 / 2) * v^3 * sinh(Ω * β / 2) / (3 * √π * w^3 * sinh(β / 2))\n\n    integrand(x) = (sin(Ω * x) * cos(x) / (x^2 + a^2 - b * cos(v * x))^(3 / 2))\n\n    integral = QuadGK.quadgk(x -> integrand(x), 0, Inf)[1]\n    @show(coefficient * integral)\n    BigFloat(coefficient * integral)\nend\n\nfunction arb_binomial(x, y)\n    x = ArbReal(\"$x\")\n    y = ArbReal(\"$y\")\n    one = ArbReal(\"1\")\n    ArbNumerics.gamma(x + one) / (ArbNumerics.gamma(y + one) * ArbNumerics.gamma(x - y + one))\nend\n\nfunction oscillatory_integral_expansion(Ω, β, α, v, w; prec = 64)\n\n    # Initialise precision of ArbReal to prec.\n    setextrabits(0)\n    setprecision(ArbReal, prec + 8)\n\n    Ω = ArbReal(\"$Ω\")\n    β = ArbReal(\"$β\")\n    α = ArbReal(\"$α\")\n    v = ArbReal(\"$v\")\n    w = ArbReal(\"$w\")\n\n    R = ArbReal((v^2 - w^2) / (w^2 * v))\n    a = ArbReal(sqrt(β^2 / 4 + R * β * coth(β * v / 2)))\n    b = ArbReal(R * β / sinh(β * v / 2))\n\n    coefficient = ArbReal(α * β^(3/2) * v^3 / (3 * a * √π * w^3 * sinh(β / 2)))\n\n    θ(z, n) = ArbReal(√π * ArbNumerics.gamma(-n - 1/2) * abs(z)^n * z * bessel_minus_struve.BesselI_minus_StruveL(n + 1, a * abs(z); prec = prec) / 2)\n\n    s = ArbReal(sinh(Ω * β / 2))\n\n    n = ArbReal(\"0\")\n    result = ArbReal(\"0.0\")\n    err = eps(ArbReal(0, bits = prec + 8))  # Machine accuracy of specified precision prec.\n\n    while true\n\n        previous_result = ArbReal(\"$result\")\n\n        if mod(n, 2) == 0\n            even_term = ArbReal(\"0.0\")\n            @fastmath @inbounds @simd for z in [ArbReal(Ω + 1), ArbReal(Ω - 1)]\n                even_term += ArbReal(arb_binomial(n, n/2) * s * θ(z, n) / 2)\n            end\n        else\n            even_term = ArbReal(\"0.0\")\n        end\n\n        k_term = ArbReal(\"0.0\")\n        @fastmath @inbounds @simd for k in ArbReal(\"0\"):ArbReal(floor(n / 2 - 1 / 2))\n            k_coeff = ArbReal(arb_binomial(n, k))\n            @fastmath @inbounds @simd for z in [ArbReal(Ω + 1 + v * (n - 2 * k)), ArbReal(Ω - 1 + v * (n - 2 * k)), ArbReal(Ω + 1 - v * (n - 2 * k)), ArbReal(Ω - 1 - v * (n - 2 * k))]\n                k_term += ArbReal(k_coeff * s * θ(z, n) / 2)\n            end\n        end\n\n        term = ArbReal(arb_binomial(-3/2, n) * (-b / (4 * a))^n * (even_term\n         + k_term))\n\n        # Break loop if term smaller than accuracy of result.\n        if abs(term) < err\n            break\n        end\n\n        result += ArbReal(term)\n        println(\"term: n = \", n, \"\\nterm value: \", coefficient * term, \"\\ncurrent result: \", coefficient * result, \"\\n\")\n\n        n += ArbReal(\"1\")\n\n        # Double precision if rounding error in result exceeds accuracy specified by prec.\n        if ball(result)[2] > err\n            setprecision(ArbReal, precision(result) + 8)\n\n            println(\"Not precise enough. Required error < \", err, \". Increasing precision to \", precision(result) + 8, \" bits.\\n\")\n\n            Ω = ArbReal(\"$Ω\")\n            β = ArbReal(\"$β\")\n            α = ArbReal(\"$α\")\n            v = ArbReal(\"$v\")\n            w = ArbReal(\"$w\")\n\n            R = ArbReal((v^2 - w^2) / (w^2 * v))\n            a = ArbReal(sqrt(β^2 / 4 + R * β * coth(β * v / 2)))\n            b = ArbReal(R * β / sinh(β * v / 2))\n\n            coefficient = ArbReal(α * β^(3/2) * v^3 / (3 * a * √π * w^3 * sinh(β / 2)))\n\n            θ(z, n) = ArbReal(√π * ArbNumerics.gamma(-n - 1/2) * abs(z)^n * z * bessel_minus_struve.BesselI_minus_StruveL(n + 1, a * abs(z); prec = precision(result)) / 2)\n\n            s = ArbReal(sinh(Ω * β / 2))\n\n            n = ArbReal(\"$(n - 1)\")\n            result = ArbReal(\"$previous_result\")\n        end\n    end\n\n    result *= ArbReal(coefficient)\n    println(\"Frequency: \", ArbReal(Ω, bits = prec + 8), \". Final result: \", ArbReal(result, bits = prec + 8))\n    ArbReal(result, bits = prec + 8)\nend\n\nΩ_range = 0.01:0.5:20.01\nβ = 2.0\nα = 7.0\nv = 5.8\nw = 1.6\n# For Ω_range = 3.1:\n# 9.828299 seconds (46.17 M allocations: 1.859 GiB, 12.89% gc time)\n@time oscill_expansion = [oscillatory_integral_expansion(Ω, β, α, v, w; prec = 64) for Ω in Ω_range]\n# oscill_expansion = fill(36.009791933858445279331705890513148915488)\n# @show(oscill_expansion)\n# 273.411207 seconds (931.57 M allocations: 32.002 GiB, 5.19% gc time)\n@time oscill_integral = [oscillatory_integral(Ω, β, α, v, w) for Ω in Ω_range]\n\ndiff = oscill_expansion .- oscill_integral\n@show(diff)\n# oscill_integral = fill(-5.81034244862553995092)\n# @show(oscill_integral)\n# p = plot(Ω_range, abs.(oscill_expansion), yaxis = :log, label = \"Oscillatory\", xlabel = \"Ω\", ylabel = \"ReX\")\n# plot!(Ω_range, abs.(oscill_integral), label = \"Integral\")\n# display(p)\n", "meta": {"hexsha": "13147aa568c41df670e8a3fa974273b66efebbcf", "size": 5513, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "arb/oscillatory_integral_expansion.jl", "max_stars_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_stars_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-07-26T17:46:18.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-26T17:46:18.000Z", "max_issues_repo_path": "arb/oscillatory_integral_expansion.jl", "max_issues_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_issues_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arb/oscillatory_integral_expansion.jl", "max_forks_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_forks_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.25, "max_line_length": 632, "alphanum_fraction": 0.5768184292, "num_tokens": 1880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7609631330181748}}
{"text": "module Model\nexport make_model_data\n\n#using Plots\n\nfunction calculate_data(scale::Float64, r::Float64)\n\t\n\tq = 10 .^ (-1:0.01:1) # q-values [nm^-1]\n\t\n\t#scale = 0.02 # Number of spheres per nm^3 [nm^-3]\n\t#r = 0.5 # nm\n\trho = 1 # nm^-2\n\tbackground = 0 # nm^-1\n\t\n\tqr = q .* r\n\tintensity = scale .* ((3*(4*pi*r^3/3)*rho).*(sin.(qr) - qr .* cos.(qr)) ./ qr.^3).^2 .+ background # nm^-1\n\t\n\tphi = scale * (4*pi*r^3/3)\n\t\n\tpsi = 3*phi / (1 - phi)\n\tb = psi .* ((cos.(qr) + qr .* sin.(qr)) .* (sin.(qr) - qr .* cos.(qr))) ./ qr.^3\n\tc = psi .* (sin.(qr) - qr .* cos.(qr)).^2 ./ qr.^3\n\td = 1 .+ psi .* (qr.^2 .* sin.(qr) .* cos.(qr)) ./ qr.^3\n\te = psi .* (qr.^2 .* (sin.(qr).^2)) ./ qr.^3\n\tf = psi .* (qr .* sin.(qr) .* (sin.(qr) - qr .* cos.(qr))) ./ qr.^3\n\tg = - psi .* (qr .* cos.(qr) .* (sin.(qr) - qr .* cos.(qr))) ./ qr.^3\n\t\n\tX = 1 .+ b + (2 .* e .* f .* g + d .* (f.^2 - g.^2)) ./ (d.^2 + e.^2)\n\tY = c + (2 .* d .* f .* g - e .* (f.^2 - g.^2)) ./ (d.^2 + e.^2)\n\t\n\tS = (Y ./ c) ./ (X.^2 + Y.^2)\n\t\n\t#gr()\n\t#global plt = plot(q, intensity; xaxis = :log, yaxis = :log)\n\t\n\tintensity = S .* intensity\n\t\n\t#plot!(q, intensity)\n\t\n\treturn q::Array{Float64, 1}, intensity::Array{Float64, 1}\n\t\nend\n\nfunction save_data_to_file(data::Tuple{Array{Float64, 1}, Array{Float64, 1}}, outputFileName::String)\n\t\n\tio = open(outputFileName, \"w\")\n\tif isempty(read(outputFileName, String))\n\t\tprintln(io, \"q-Value [nm^-1], Intensity [nm^-1]\")\n\tend\n\t\n\tfor i in 1:length(data[1])\n\t\t\n\t\tlocal qValue = data[1][i]\n\t\tlocal intensity = data[2][i]\n\t\t\n\t\tprintln(io, qValue, \", \", intensity)\n\t\t\n\tend\n\t\n\tclose(io)\n\t\n\treturn nothing\n\t\nend\n\nfunction make_model_data(scale::Float64, r::Float64)\n\t\n\tsave_data_to_file(calculate_data(scale::Float64, r::Float64), \"calculated.data\")\n\t\n\treturn nothing\n\t\nend\n\nend # Model\n", "meta": {"hexsha": "ee31a503a8e274da25b8e5fa5291f0de3087a82b", "size": 1769, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/calculated/model.jl", "max_stars_repo_name": "JonPallbo/Scatt", "max_stars_repo_head_hexsha": "2eb195b7c9bb51ac32d332f4ac864c0dbc23bc15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/calculated/model.jl", "max_issues_repo_name": "JonPallbo/Scatt", "max_issues_repo_head_hexsha": "2eb195b7c9bb51ac32d332f4ac864c0dbc23bc15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/calculated/model.jl", "max_forks_repo_name": "JonPallbo/Scatt", "max_forks_repo_head_hexsha": "2eb195b7c9bb51ac32d332f4ac864c0dbc23bc15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5866666667, "max_line_length": 107, "alphanum_fraction": 0.5330695308, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368929, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7609631276570609}}
{"text": "\"\"\"\nProduce an elliptic torus with circular tube cross \nsection\n\"\"\"\nmodule MajorEllipticTorus\n\n\n# minimum distance between a point and ellipse\nfunction min_distance(a, b, coordinates)\n    x = abs(coordinates[1])\n    y = abs(coordinates[2])\n    z = coordinates[3]\n    function aux(phi, accum)\n        new_phi = atan(((a^2 - b^2)*sin(phi) + y*b)/(x*a))\n        if abs(phi - new_phi) < 1e-4\n            return new_phi\n        else\n            return aux(new_phi, accum+1)\n        end\n    end\n    phi = aux(0, 0)\n    return sqrt(z^2 + (x - a * cos(phi))^2 + (y - b*sin(phi))^2)\nend\n\n# check whether a point is inside the torus\n\nfunction get_fn(argd::Dict)\n    a = float(argd[\"major\"][\"a\"])\n    b = float(argd[\"major\"][\"b\"])\n    r = float(argd[\"minor\"][\"radius\"])\n    center = [float(x) for x in argd[\"center\"]]\n    force_constant = float(argd[\"k\"])\n\n    function fn_compute(raw_coordinates)\n        coordinates = raw_coordinates - center \n        if norm(coordinates[1:2]) < 1e-6\n            d = sqrt(min(a,b)^2 + coordinates[3]^2)\n        else\n            d = min_distance(a, b, coordinates)\n        end\n        if d < r\n            return 0\n        else\n            return force_constant * d\n        end\n    end\n    return fn_compute\nend\n\nexport get_fn\n\nend", "meta": {"hexsha": "df257c76066f6b598cffd679aec745bed3747438", "size": 1255, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BuildGrid/deps/MajorEllipticTorus.jl", "max_stars_repo_name": "yuhangwang/SimShape", "max_stars_repo_head_hexsha": "57b9df7aaba56eb2fd21356fd70a09765d111c77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BuildGrid/deps/MajorEllipticTorus.jl", "max_issues_repo_name": "yuhangwang/SimShape", "max_issues_repo_head_hexsha": "57b9df7aaba56eb2fd21356fd70a09765d111c77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BuildGrid/deps/MajorEllipticTorus.jl", "max_forks_repo_name": "yuhangwang/SimShape", "max_forks_repo_head_hexsha": "57b9df7aaba56eb2fd21356fd70a09765d111c77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1346153846, "max_line_length": 64, "alphanum_fraction": 0.5729083665, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541593883189, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7609198548835354}}
{"text": "module Regularizer\n\nexport regularizer, createElasticOperatorCentered, createElasticOperatorStaggered, createDiffusiveOperatorCentered\nexport createCurvatureOperatorCentered\n\nfunction regularizer(deformationField::Array{Float64,1}, operator)\n\n    d2functionValue = operator'*operator\n    dfunctionValue  = d2functionValue*deformationField\n    functionValue   = (0.5 .* deformationField'*dfunctionValue)[1]\n    return [functionValue, dfunctionValue, d2functionValue]\n\nend\n\n\nfunction createElasticOperatorCentered(h::Array{Float64,1},m::Array{Int64,1}; mu::Number = 1, lambda::Number = 0)\n\n  m = m.-1\n\n  a   = sqrt(mu)\n  b   = sqrt(mu+lambda)\n  dx(k) = spdiagm((-1.*ones(m[k]),ones(m[k])),0:1,m[k],m[k]+1)/h[k]\n  av(k) = spdiagm((ones(m[k])/2,ones(m[k])/2),0:1,m[k],m[k]+1)\n  D1   = kron(speye(m[2]+1),dx(1))\n  D2   = kron(dx(2),speye(m[1]+1))\n  A1   = kron( av(2) , speye(m[1]))\n  A2   = kron( speye(m[2]),  av(1))\n  p1,p2 = size(D1)\n  p3,p4 = size(D2)\n\n  B = [ a*D1 spzeros(p1,p2);\n       a*D2 spzeros(p3,p4);\n       spzeros(p1,p2) a*D1;\n       spzeros(p3,p4) a*D2;\n       b*A1*D1 b*A2*D2 ]\n\n  return B\n\nend\n\n# function createElasticOperatorStaggered(h::Array{Float64,1},m::Array{Int64,1}; mu::Number = 1, lambda::Number = 0)\n#\n#     a   = sqrt(mu)\n#     b   = sqrt(mu+lambda)\n#\n#     dx(h,m) = spdiagm((-ones(m,1),ones(m,1)),[0,1],m,m+1)/h\n#\n#     D11 = kron(dx(h[2],m[2]),speye(m[1]))\n#     D21 = kron(speye(m[2]+1),dx(h[1],m[1]-1))\n#     D12 = kron(dx(h[2],m[2]-1),speye(m[1]+1))\n#     D22 = kron(speye(m[2]),dx(h[1],m[1]))\n#\n#     B = spzeros(2*size(D11,1)+size(D21,1)+size(D12,1)+size(D22,1),size(D11,2)+size(D12,2))\n#     B[1:size(D11,1), 1:size(D11,2)]                         = a*D11\n#     B[size(D11,1)+1:size(D11,1)+size(D21,1), 1:size(D11,2)] = a*D21\n#     B[size(D11,1)+size(D21,1)+1:size(D11,1)+size(D21,1)+size(D12,1), size(D11,2)+1:end]                         = a*D12\n#     B[size(D11,1)+size(D21,1)+size(D12,1)+1:size(D11,1)+size(D21,1)+size(D12,1)+size(D22,1), size(D11,2)+1:end] = a*D22\n#     B[size(D11,1)+size(D21,1)+size(D12,1)+size(D22,1)+1:end, 1:size(D11,2)]     = b*D11\n#     B[size(D11,1)+size(D21,1)+size(D12,1)+size(D22,1)+1:end, size(D11,2)+1:end] = b*D22\n#\n#     return B\n#\n# end\n\n\nfunction createDiffusiveOperatorCentered(h::Array{Float64,1},m::Array{Int64,1})\n\n  d(k) = spdiagm((-ones(m[k]-1,1),ones(m[k]-1,1)),[0 1],m[k]-1,m[k])/(h[k])\n  dx = d(1)\n  dy = d(2)\n  D1 = kron(speye(m[2]),dx)\n  D2 = kron(dy,speye(m[1]))\n  p1,p2 = size(D1)\n  p3,p4 = size(D2)\n  B = [ D1 spzeros(p1,p2);\n        D2 spzeros(p3,p4);\n        spzeros(p1,p2) D1;\n        spzeros(p3,p4) D2\n      ]\nend\n\nfunction createCurvatureOperatorCentered(h::Array{Float64,1},m::Array{Int64,1})\n\n  d(k) = spdiagm((-ones(m[k]-2,1),2*ones(m[k]-2,1), -ones(m[k]-2,1)),[0 1 2],m[k]-2,m[k])/(h[k])\n  dx = d(1); #dx[1,1]=1; dx[end, end]=1\n  dy = d(2); #dy[1,1]=1; dy[end, end]=1\n  D1 = kron(speye(m[2]),dx)\n  D2 = kron(dy,speye(m[1]))\n  p1,p2 = size(D1)\n  p3,p4 = size(D2)\n  B = [ D1 spzeros(p1,p2);\n        D2 spzeros(p3,p4);\n        spzeros(p1,p2) D1;\n        spzeros(p3,p4) D2\n      ]\nend\n\nend#\n", "meta": {"hexsha": "61bd1fe905795e4e6602a48a7851ac96d870aef0", "size": 3085, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Regularizer.jl", "max_stars_repo_name": "muxiao1217/DeformableRegistration.jl", "max_stars_repo_head_hexsha": "e3b2c7a7d5b15b8b34302ee62a4727fe5a63176f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-10-11T15:07:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T06:26:07.000Z", "max_issues_repo_path": "src/Regularizer.jl", "max_issues_repo_name": "muxiao1217/DeformableRegistration.jl", "max_issues_repo_head_hexsha": "e3b2c7a7d5b15b8b34302ee62a4727fe5a63176f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-10-06T20:06:58.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-06T20:07:00.000Z", "max_forks_repo_path": "src/Regularizer.jl", "max_forks_repo_name": "muxiao1217/DeformableRegistration.jl", "max_forks_repo_head_hexsha": "e3b2c7a7d5b15b8b34302ee62a4727fe5a63176f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-10-06T19:54:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T07:57:57.000Z", "avg_line_length": 31.1616161616, "max_line_length": 121, "alphanum_fraction": 0.5750405186, "num_tokens": 1302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7609198413560618}}
{"text": "\nexport get_prop_mass,\n       hohmann_circular_coplanar,\n       hohmann_circular,\n       hohmann_circle2circle,\n       get_launch_asymptote,\n       lambert,\n       lambert_target,\n       lambert_transfer\n\nfunction get_prop_mass(m0, dV, Isp) \n    # dV in m/s, Isp in s, m0 in kg\n    return m0 * (1. - exp(-dV/(9.81*Isp)))\nend\n\n\"Hohmann transfer between two circular orbits\"\nfunction hohmann_circle2circle(a1, a2, mu)\n    aT = (a1 + a2)/2.\n    vc1 = getv( mu, a1, a1 )\n    vc2 = getv( mu, a2, a2 )\n    \n    vT1 = getv( mu, a1, aT )\n    vT2 = getv( mu, a2, aT )\n\n    dV1 = abs(vc1 - vT1)\n    dV2 = abs(vc2 - vT2)\n\n    return (aT, dV1, dV2)\nend\n\nfunction get_launch_asymptote(v_INF_HCI::Vector{S}, epoch) where {S<:AbstractFloat}\n    T = get_hci2eci_matrix( epoch )\n    v_INF_ECI = T*v_INF_HCI\n    α = atan(v_INF_ECI[2],v_INF_ECI[1])\n    δ = asin(v_INF_ECI[3]/norm(v_INF_ECI))\n    return (α,δ)\nend\n\n\"\"\"\nCompute the relevant quantities for a Hohmann transfer between objects\norbiting the Sun, assuming circular, coplanar orbits also assuming\ncircular parking orbit\n\"\"\"\nfunction hohmann_circular_coplanar(muDepart,\n                                   aDepart,\n                                   rPark,\n                                   muDest,\n                                   aDest,\n                                   aCapture,\n                                   rCapture)\n    \n    # v_INF_depart: v_infinity required wrt departure planet\n    # v_INF_arrive: v_infinity wrt destination planet\n    (aTrans, v_INF_depart, v_INF_arrive) = hohmann_circle2circle(aDepart, aDest, muSun)\n    \n    ### Departure\n\n    # departure velocity wrt Sun:\n    v_SC_S_depart = getv(muSun, aDepart, aTrans)\n    \n    # delta V required:\n    dV_depart = getvhyp(muDepart, rPark, v_INF_depart) -\n                sqrt(muDepart/rPark)\n    \n    ### Arrival\n    \n    # arrival velocity wrt Sun:\n    v_SC_S_arrive = getv(muSun, aDest, aTrans)\n    \n    \n    # delta V required for capture into orbit specified by aCapture and rCapture\n    dV_cap = getArrivalDV( muDest, rCapture, aCapture, v_INF_arrive )\n    \n    TOF = getPeriod(muSun, aTrans)/2. # seconds\n    \n    return (v_INF_depart, dV_depart, v_INF_arrive, dV_cap, TOF)\nend\n\nfunction getArrivalDV(muDest, rCapture, aCapture, v_INF_arrive)\n    return abs( getvhyp(muDest, rCapture, v_INF_arrive) -\n               getv(muDest, rCapture, aCapture) )\nend\n\n\"\"\"\nCompute the relevant quantities for a Hohmann transfer between objects\norbiting the Sun, assuming circular non-coplanar orbits\n\"\"\"\nfunction hohmann_circular(muDepart, aDepart, rPark, muDest,\n                          aDest, dInc, aCapture, rCapture)\n\n    aTrans = (aDepart + aDest)/2\n    \n    # Departure\n\n    # departure velocity wrt Sun:\n    v_SC_S_depart = getv(muSun, aDepart, aTrans)\n    v_depart_S = sqrt(muSun/aDepart)\n\n    # arrival velocity wrt Sun:\n    v_SC_S_arrive = getv(muSun, aDest, aTrans)\n    v_dest_S = sqrt(muSun/aDest)\n\n    # v_infinity required \n    v_INF_depart(alpha) = sqrt(v_SC_S_depart^2 + v_depart_S^2 - \n                        2*v_SC_S_depart*v_depart_S*cos(alpha))\n    v_INF_arrive(alpha) = sqrt(v_SC_S_arrive^2 + v_dest_S^2 -\n                               2*v_SC_S_arrive*v_dest_S*cos(dInc - alpha))\n\n    # numerically solve for the optimal plane change split\n    f(beta) = v_SC_S_depart*v_depart_S*sin(beta)/v_INF_depart(beta) - \n                v_dest_S*v_SC_S_arrive*sin(dInc - beta)/v_INF_arrive(beta)\n    alpha1 = fzero(f,0.,dInc)\n\n    # delta V required for departure:\n    dV_depart = getvhyp(muDepart, rPark, v_INF_depart(alpha1))-\n                sqrt(muDepart/rPark)\n    \n    # delta V required for capture into orbit specified by aCapture and rCapture\n    dV_cap = getArrivalDV( muDest, rCapture, aCapture, v_INF_arrive(alpha1) )\n    \n    TOF = getPeriod(muSun, aTrans)/2. #seconds\n    \n    return (v_INF_depart(alpha1), dV_depart, v_INF_arrive(alpha1), dV_cap, alpha1, TOF)\nend\n\n\"\"\"\nTranslation of lambert_target.m\n\nOriginal Matlab code provided by Brent Barbee\n\"\"\"\nfunction lambert_target(mu, TOF, r1::Vector{T}, r2::Vector{T},\n                        v1::Vector{T}, v2::Vector{T}) where {T<:AbstractFloat}\n\n    uu = cross(r1, r2)\n    \n    uh = (1/norm(uu))*uu\n    \n    (vi1, vf1) = lambert(mu, TOF, r1, r2, uh)\n\n    tot_dv1 = norm(v1-vi1) + norm(vf1-v2)\n\n    uu = cross(r2, r1)\n    \n    uh = (1/norm(uu))*uu\n    \n    (vi2, vf2) = lambert(mu, TOF, r1, r2, uh)\n\n    tot_dv2 = norm(v1-vi2) + norm(vf2-v2)\n\n    if tot_dv1 < tot_dv2\n\n        vi = vi1\n        vf = vf1\n\n    else\n\n        vi = vi2\n        vf = vf2\n\n    end\n    return (vi, vf)\nend\n\n\"\"\"\nTitle     : Lambert                                                    \nPurpose   : Given a conic gravity field, compute the required velocity \n            to transfer between initial and final inertial position    \n            vectors in a specified transfer time interval.             \nInputs    : mu  - (km^3/s^2) Gravitational constant                    \n            dt  - (s)        Transfer time interval                    \n            ri  - (km)       Init. inertial position vector            \n            rf  - (km)       Final inertial position vector            \n            uh  - (na)       Unit angular momentum vector              \nOutputs   : vi  - (km/s)     Init. inertial velocity vector (required) \n            vf  - (km/s)     Final inertial velocity vector            \nComments  : 1) This routine does not have a multi-revolution capability\n            2) The unit angular momentum vector determines the plane,  \n               and direction, of the transfer                          \nReference : Shepperd, S.W., unpublished notes.                         \nOriginal author: Brent Barbee\n\"\"\"\nfunction lambert(mu, dt, ri::Vector{T}, rf::Vector{T},\n                 uh::Vector{T}) where {T<:AbstractFloat}\n\n    ### Initialization Iteration Loop \n\n    r0 = ri - dot(ri, uh) * uh\n    r1 = rf - dot(rf, uh) * uh\n\n    if abs(dot(uh, uh) - 1) > 10000 * eps()\n        error(\"Lambert : Aborting : Normal vector not unitary\\n\")\n    end\n\n    if abs(dot(ri, uh)) > 0.00001\n        error(\"Lambert : Warning : Init. position not in plane\\n\")\n    end\n\n    if abs(dot(rf, uh)) > 0.00001\n        error(\"Lambert : Warning : Final position not in plane\\n\")\n    end\n\n    imax      = 20\n    maxu      = typemax(Int64)\n    tolerance = 1000 * eps()\n\n    m0 = norm(r0)\n    m1 = norm(r1)\n    cc = norm(r1 - r0)\n    ss = (m0 + m1 + cc) / 2\n\n    rc = ss / 2\n    vc = sqrt(mu / rc)\n    wc = vc / rc\n\n    k1 = sqrt(abs((ss - m0) * (ss - m1)))\n    k  = dot(cross(r0, r1), uh)\n\n    if  (k1 * k1) > (ss * (ss - cc))\n        k  = k / (2 * k1 * ss)\n        k2 = 1 - k * k\n    else\n        k2 = cc / ss\n        if k >= 0\n            k  = +sqrt(1 - k2)\n        else\n            k  = -sqrt(1 - k2)\n        end\n    end\n\n    tdesired = wc * dt\n\n    if tdesired > 4 * (1 - k * k * k) / 3\n        u = 0 \n        umin = -1 \n        umax = 1\n    else\n        u = 1 \n        umin = 1 \n        umax = maxu\n    end\n\n    ### Iterate Until Transfer Time Matches \n\n    # initialize values outside of loop\n    q = 0.\n    y = 0.\n    h1 = 0.\n    h0 = 0.\n    uu = 0.\n    pp = 0.\n    dt = 0.\n    slope = 0.\n    terror = 0.\n    uold = 0.0\n    dtold = 0.0\n\n    for i=1:imax \n\n        q = k * u\n        y = sqrt(q * q + k2)\n\n        if q <= 0 \n            h1 = y - q\n        else\n            h1 = k2 / (y + q)\n        end\n\n        h0 = k + u * h1\n        q  = (1 - abs(h0)) / 2\n        uu = (16 / 15) * h1 ^ 5 * cfgauss(5, q)\n\n        if h0 < 0\n            pp = 2 * pi / sqrt(1 - u * u)^5\n            uu = pp - uu\n        end\n\n        dt     = 4 * h1 * (k + h0 * h1 * h1 / 3) + (1 - u * u) * uu\n        slope  = 3 * u * uu - 4 * (h1 / y) * (k * k + (k * h0 + h1 * h1) * h1 * h1)\n        terror = tdesired - dt\n\n        if abs(terror) < wc\n            if abs(terror) < tolerance * abs(tdesired )\n                break\n            end\n            \n            if abs(terror) < tolerance * abs(slope * u)\n                break\n            end\n        end\n\n        if (i > 1) && (u  ==  uold)\n            break\n        end\n\n        if (i > 1) && (dt == dtold)\n            break\n        end\n\n        uold  = u\n        dtold = dt\n        ustep = terror / slope\n\n        if ustep > 0\n            umin = u\n            u    = u + ustep\n            if u > umax\n                u = (umin + umax) / 2\n            end\n        else\n            umax = u\n            u    = u + ustep\n            if u < umin\n                u = (umin + umax) / 2\n            end\n        end\n\n    end\n\n    ### Final Computations \n\n    h1 = h1 / vc\n    uu = uu / vc^5\n\n    h  = k1 / h1\n    n0 = +(k * ss - m0 * h0) / h1\n    n1 = -(k * ss - m1 * h0) / h1\n    v0 = (n0 * r0 + h * cross(uh, r0)) / (m0 * m0)\n    v1 = (n1 * r1 + h * cross(uh, r1)) / (m1 * m1)\n\n    vi  = v0\n    vf  = v1\n\n    return (vi, vf)\nend\n\n\"\"\"\nTitle     : CF Gauss                                             \nPurpose   : Compute the Gaussian continued fraction.             \nInputs    : i - (na) Order of continued fraction                 \n            q - (na) Argument of continued fraction              \nOutputs   : g - (na) Continued fraction result                   \nComments  : The continued fraction is defined as the ratio of two\n            hypergeometric functions as follows:                 \n                                                                 \n                                   F(i,1,1+(i/2),q)              \n                g = G(i,0,i/2,q) = ----------------              \n                                     F(i,0,i/2,q)                \n                                                                 \nException : Illegal argument                                     \nReference : Shepperd, S.W., \"Universal Keplerian State Transition\n            Matrix,\" Celestial Mechanics, Vol. 35, 1985.         \nOriginal author: Brent Barbee\n\"\"\"\nfunction cfgauss(i, q)\n\n    if q > 0.5 + 16 * eps()\n        error(\"CF Gauss : Illegal argument\\n\\n\")\n    end\n\n    g = 1\n    r = 1\n    s = 1\n    n = 0\n    l = i - 2\n    d = i * (i - 2)\n    k = 1 - 2 * i\n\n    while(true)\n\n        k    = -k\n        l    = l + 2\n        d    = d + 4 * l\n        n    = n + (1 + k) * l\n        r    = d / (d - n * r * q)\n        s    = (r - 1) * s\n        gold = g\n        g    = gold + s\n        \n        if g == gold\n            break\n        end\n\n    end\n\n    return g\nend\n\n    \n\"\"\"\nWrapper to get delta V values for a Lambert-targeted transfer\nassumes Sun as the central body\n\nUnits are km and s\n\"\"\"\nfunction lambert_transfer(muDepart, \n                         TOF,\n                         launchEpoch,\n                         rPark, \n                         x1_HCI::Vector{T}, x2_HCI::Vector{T},\n                         muDest = 0., \n                         rCapture = 1000.0,\n                         aCapture = 1000.0 ) where {T<:AbstractFloat}\n    (v_SC_S_depart_HCI, v_SC_S_arrive_HCI) = lambert_target( muSun,\n                                                             TOF,\n                                                             x1_HCI[1:3], x2_HCI[1:3],\n                                                             x1_HCI[4:6], x2_HCI[4:6] )\n    # departure:\n    v_INF_E_HCI = v_SC_S_depart_HCI - x1_HCI[4:6]\n    C3_depart = norm(v_INF_E_HCI)^2\n    dV_depart = abs(getvhyp(muEarth, rPark, norm(v_INF_E_HCI)) - getv(muEarth, rPark, rPark))\n    \n    (RLA,DLA) = get_launch_asymptote( v_INF_E_HCI, launchEpoch )\n    \n    # arrival:\n    v_INF_arrive = norm(v_SC_S_arrive_HCI - x2_HCI[4:6])\n    dV_arrive = abs(getArrivalDV( muDest, rCapture, aCapture, v_INF_arrive ))\n    \n    return (dV_depart, dV_arrive, C3_depart, RLA, DLA)\nend\n", "meta": {"hexsha": "c1ec8921a0aee1a3d87bd8344e4a8c968e2aa3f4", "size": 11622, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transfers.jl", "max_stars_repo_name": "crbinz/Interplanetary.jl", "max_stars_repo_head_hexsha": "67521f799f7d0cdb20b8db3060ee84ade3cdf3e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2015-08-19T14:10:59.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-14T20:46:32.000Z", "max_issues_repo_path": "src/transfers.jl", "max_issues_repo_name": "crbinz/Interplanetary.jl", "max_issues_repo_head_hexsha": "67521f799f7d0cdb20b8db3060ee84ade3cdf3e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-09-11T17:04:48.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-10T02:42:49.000Z", "max_forks_repo_path": "src/transfers.jl", "max_forks_repo_name": "crbinz/Interplanetary.jl", "max_forks_repo_head_hexsha": "67521f799f7d0cdb20b8db3060ee84ade3cdf3e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-08-19T14:11:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:09:20.000Z", "avg_line_length": 27.6714285714, "max_line_length": 93, "alphanum_fraction": 0.4948373774, "num_tokens": 3475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7609116275276423}}
{"text": "# Mathematical Constants\nexport RAD2DEG\n\"\"\"\nConstant to convert radians to degrees. Equal to 360/2pi. [deg/rad]\n\"\"\"\nconst RAD2DEG = 360.0/(2.0*pi)\n\nexport DEG2RAD\n\"\"\"\nConstant to convert radians to degrees. Equal to 2pi/360. [rad/deg]\n\"\"\"\nconst DEG2RAD = 2.0*pi/360.0\n\nexport AS2RAD\n\"\"\"\nConstant to convert arcseconds to radians. Equal to 2pi/(360*3600). [rad/as]\n\"\"\"\nconst AS2RAD = 2.0*pi/360.0/3600.0\n\nexport RAD2AS\n\"\"\"\nConstant to convert radians to arcseconds. Equal to 2pi/(360*3600) [as/ras]\n\"\"\"\nconst RAD2AS = 360.0*3600.0/pi/2.0\n\n# Physical Constants\nexport C_LIGHT\n\"\"\"\nSpeed of light in vacuum. [m/s]\n\nD. Vallado, _Fundamentals of Astrodynamics and Applications_ (4th Ed.), 2010\n\"\"\"\nconst C_LIGHT     = 299792458.0                 # [m/s]Exact definition Vallado\n\nexport AU\n\"\"\"\nAstronomical Unit. Equal to the mean distance of the Earth from the sun.\nTDB-compatible value. [m]\n\nP. Gérard and B. Luzum, IERS Technical Note 36, 2010\n\"\"\"\nconst AU          = 1.49597870700e11            # [m] Astronomical Unit IAU 2010\n\n# Time Consants\n\nexport SECONDS_IN_DAY\n\"\"\"\nNumber of seconds in a day.\n\"\"\"\nconst SECONDS_IN_DAY = 86400\n\nexport MJD_ZERO\n\"\"\"\nOffset of Modified Julian Days representation with respect to Julian Days. For \na time, t, MJD_ZERO is equal to:\n\n    MJD_ZERO = t_jd - t_mjd\n\nWhere t_jd is the epoch represented in Julian Days, and t_mjd is the epoch in\nModified Julian Days.\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst MJD_ZERO = 2400000.5\n\nexport MJD2000\n\"\"\"\nModified Julian Date of January 1, 2000 00:00:00. Value is independent of time\nscale.\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst MJD2000  = 51544.0\n\nexport GPS_TAI\n\"\"\"\nOffset of GPS time system with respect to TAI time system.\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst GPS_TAI  = -19.0\n\nexport TAI_GPS\n\"\"\"\nOffset of TAI time system with respect to GPS time system.\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst TAI_GPS  = -GPS_TAI\n\nexport TT_TAI\n\"\"\"\nOffset of TT time system with respect to TAI time system.\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst TT_TAI   = 32.184\n\nexport TAI_TT\n\"\"\"\nOffset of TAI time system with respect to TT time system.\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst TAI_TT   = -TT_TAI\n\nexport GPS_TT\n\"\"\"\nOffset of GPS time system with respect to TT time system.\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst GPS_TT   = GPS_TAI + TAI_TT\n\nexport TT_GPS\n\"\"\"\nOffset of TT time system with respect to GPS time system.\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst TT_GPS   = -GPS_TT\n\nexport GPS_ZERO\n\"\"\"\nModified Julian Date of the start of the GPS time system in the GPS time system.\nThis date was January 6, 1980 0H as reckond in the UTC time system.\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst GPS_ZERO = 44244.0\n\n# Earth Constants\nexport R_EARTH\n\"\"\"\nEarth's equatorial radius. [m]\n\nGGM05s Gravity Model\n\"\"\"\nconst R_EARTH     = 6.378136300e6               # [m] GGM05s Value\n\nexport WGS84_a\n\"\"\"\nEarth's semi-major axis as defined by the WGS84 geodetic system. [m]\n\nNIMA Technical Report TR8350.2\n\"\"\"\nconst WGS84_a     = 6378137.0                   # WGS-84 semi-major axis\n\nexport WGS84_f\n\"\"\"\nEarth's ellipsoidal flattening.  WGS84 Value.\n\nNIMA Technical Report TR8350.2\n\"\"\"\nconst WGS84_f     = 1.0/298.257223563           # WGS-84 flattening\n\nexport GM_EARTH\n\"\"\"\nEarth's Gravitational constant [m^3/s^2]\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst GM_EARTH    = 3.986004415e14              # [m^3/s^2] GGM05s Value\n\nexport e_EARTH\n\"\"\"\nEarth's first eccentricity. WGS84 Value. [dimensionless]\n\nNIMA Technical Report TR8350.2\n\"\"\"\nconst e_EARTH     = 8.1819190842622e-2          # [] First Eccentricity WGS84 Value\n\nexport J2_EARTH\n\"\"\"\nEarth's first zonal harmonic. [dimensionless]\n\nGGM05s Gravity Model.\n\"\"\"\nconst J2_EARTH    = 0.0010826358191967          # [] GGM05s value\n\nexport OMEGA_EARTH\n\"\"\"\nEarth axial rotation rate. [rad/s]\n\nD. Vallado, _Fundamentals of Astrodynamics and Applications_ (4th Ed.), p. 222, 2010\n\"\"\"\nconst OMEGA_EARTH = 7.292115146706979e-5        # [rad/s] Taken from Vallado 4th Ed page 222\n\n# Sun Constants\nexport GM_SUN\n\"\"\"\nGravitational constant of the Sun. [m^3/s^2]\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst GM_SUN      = 132712440041.939400*1e9     # Gravitational constant of the Sun\n\nexport R_SUN\n\"\"\"\nNominal solar photospheric radius. [m]\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst R_SUN       = 6.957*1e8                   # Nominal solar radius corresponding to photospheric radius\n\nexport P_SUN\n\"\"\"\nNominal solar radiation pressure at 1 AU. [N/m^2]\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst P_SUN       = 4.560E-6                    # [N/m^2] (~1367 W/m^2) Solar radiation pressure at 1 AU\n\n# Celestial Constants - from JPL DE430 Ephemerides\nexport GM_MOON\n\"\"\"\nGravitational constant of the Moon. [m^3/s^2]\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst GM_MOON     = 4902.800066*1e9\n\nexport GM_MERCURY\n\"\"\"\nGravitational constant of the Mercury. [m^3/s^2]\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst GM_MERCURY  = 22031.780000*1e9\n\nexport GM_VENUS\n\"\"\"\nGravitational constant of the Venus. [m^3/s^2]\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst GM_VENUS    = 324858.592000*1e9\n\nexport GM_MARS\n\"\"\"\nGravitational constant of the Mars. [m^3/s^2]\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst GM_MARS     = 42828.37521*1e9\n\nexport GM_JUPITER\n\"\"\"\nGravitational constant of the Jupiter. [m^3/s^2]\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst GM_JUPITER  = 126712764.8*1e9\n\nexport GM_SATURN\n\"\"\"\nGravitational constant of the Saturn. [m^3/s^2]\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst GM_SATURN   = 37940585.2*1e9\n\nexport GM_URANUS\n\"\"\"\nGravitational constant of the Uranus. [m^3/s^2]\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst GM_URANUS   = 5794548.6*1e9\n\nexport GM_NEPTUNE\n\"\"\"\nGravitational constant of the Neptune. [m^3/s^2]\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst GM_NEPTUNE  = 6836527.100580*1e9\n\nexport GM_PLUTO\n\"\"\"\nGravitational constant of the Pluto. [m^3/s^2]\n\nO. Montenbruck, and E. Gill, _Satellite Orbits: Models, Methods and \nApplications_, 2012.\n\"\"\"\nconst GM_PLUTO    = 977.000000*1e9", "meta": {"hexsha": "55be23f0917635846389406c88267b1aa2324763", "size": 7226, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/constants.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SatelliteDynamics.jl-0e7c1a32-1b9f-5532-88a4-e668712d6a4c", "max_stars_repo_head_hexsha": "8afaaf79609b6710fd433bb6d423f1b5af98a386", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-01-02T17:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:40:54.000Z", "max_issues_repo_path": "src/constants.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SatelliteDynamics.jl-0e7c1a32-1b9f-5532-88a4-e668712d6a4c", "max_issues_repo_head_hexsha": "8afaaf79609b6710fd433bb6d423f1b5af98a386", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-01-14T10:38:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-10T16:07:56.000Z", "max_forks_repo_path": "src/constants.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SatelliteDynamics.jl-0e7c1a32-1b9f-5532-88a4-e668712d6a4c", "max_forks_repo_head_hexsha": "8afaaf79609b6710fd433bb6d423f1b5af98a386", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-02-08T08:12:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-29T20:48:52.000Z", "avg_line_length": 23.5374592834, "max_line_length": 107, "alphanum_fraction": 0.713672848, "num_tokens": 2344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809826, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7609116205229887}}
{"text": "module Probability\n\n#Binomial Theorem\nfunction KSuccess(n, k, pSuccess)\n    possibilities = Binomial(n,k)\n    nCk =  n == k ? 1 : possibilities\n    probability = nCk * pSuccess ^ k * (1 - pSuccess) ^ (n-k)\n\n    return probability\nend\n\nfunction KorMoreSuccess(n, k, pSuccess)\n    totalProb = Float64(0)\n    for i in [k:n;]\n        prob = KSuccess(n, i, pSuccess)\n        totalProb = totalProb + prob\n    end\n\n    return totalProb\nend\n\nfunction Binomial(n,k)\n    return factorial(BigInt(n))/(factorial(BigInt(n-k)) * factorial(BigInt(k)))\nend\n\nend\n", "meta": {"hexsha": "d75a8d666ea9d27bbbc5d5f6456560b1836b4828", "size": 546, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/probability.jl", "max_stars_repo_name": "OICR/mp-biopath", "max_stars_repo_head_hexsha": "3da9fc6e4ce7b3dd0ca184e61d58fab2f63940b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-04-03T19:41:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T21:14:15.000Z", "max_issues_repo_path": "src/probability.jl", "max_issues_repo_name": "OICR/mp-biopath", "max_issues_repo_head_hexsha": "3da9fc6e4ce7b3dd0ca184e61d58fab2f63940b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2017-04-12T14:04:02.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T21:22:08.000Z", "max_forks_repo_path": "src/probability.jl", "max_forks_repo_name": "OICR/mp-biopath", "max_forks_repo_head_hexsha": "3da9fc6e4ce7b3dd0ca184e61d58fab2f63940b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2222222222, "max_line_length": 79, "alphanum_fraction": 0.6501831502, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750427013548, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7608915392097784}}
{"text": "## SVD on an image\nusing LinearAlgebra\nusing Images\nim = load(\"low-rank-image.png\")\nA = Float64.(Gray.(im))\nA = 1.0.-A # invert the colors\n## Show the image inverted\nGray.(A)\n## Compute the SVD\nU,S,V = svd(A)\n\n## setup interact\nusing Interact\nui = button()\nsettheme!(:nativehtml)\ndisplay(ui)\n\n## Show the best rank-k approximations\nmp = @manipulate for k in 1:25\n    X = U[:,1:k]*Diagonal(S[1:k])*V[:,1:k]'\n    Gray.(X)\nend\n\n## \n", "meta": {"hexsha": "665c20ec74954609c8c21b399f08d8f1253d372d", "size": 429, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4-unit-3-demos/svd-image.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "4-unit-3-demos/svd-image.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4-unit-3-demos/svd-image.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 17.16, "max_line_length": 43, "alphanum_fraction": 0.648018648, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7608915337429337}}
{"text": "using Printf, LinearAlgebra\r\nimport FixedPointNumbers: N0f8\r\nimport Images\r\nimport CSV, DataFrames\r\nimport Cairo\r\n\r\ntoRadians(α::Float64) = α / 180.0 * π\r\ntoDegrees(α::Float64) = α * 180.0 / π\r\n\r\n#===========================================\r\n  ____            _   _ _   _ _\r\n / ___| ___  ___ | | | | |_(_) |___\r\n| |  _ / _ \\/ _ \\| | | | __| | / __|\r\n| |_| |  __/ (_) | |_| | |_| | \\__ \\\r\n \\____|\\___|\\___/ \\___/ \\__|_|_|___/\r\n\r\n=============================================#\r\n\r\nstruct PositionLLH\r\n    lat::Float64\r\n    lon::Float64\r\n    height::Float64\r\nend\r\n\r\n\r\nstruct PositionXYZ\r\n    x::Float64\r\n    y::Float64\r\n    z::Float64\r\nend\r\n\r\n\r\nabstract type Ellipsoid\r\nend\r\n\r\n\r\nstruct Wgs84 <: Ellipsoid\r\n    a::Float64\r\n    b::Float64\r\n    f::Float64\r\n    e::Float64\r\n    e²::Float64\r\n    function Wgs84()\r\n        a  = 6378137.0\r\n        f  = 1.0/298.257223563\r\n        b  = a*(1.0-f)\r\n        e² = 1.0 - b*b/(a*a) # or f * (2.0-f)\r\n        e  = sqrt(e²)\r\n        new(a,b,f,e,e²)\r\n    end\r\nend\r\n\r\n\r\nstruct SphericalEarth <: Ellipsoid\r\n    r::Float64\r\n    SphericalEarth() = new(6378137.0)\r\nend\r\n\r\n\r\nfunction llh_to_xyz(ellipsoid::Wgs84, llh::PositionLLH)::PositionXYZ\r\n    Φ    = toRadians(llh.lat)\r\n    λ    = toRadians(llh.lon)\r\n    h    = llh.height\r\n    e²   = ellipsoid.e²\r\n    sinΦ = sin(Φ)\r\n    cosΦ = cos(Φ)\r\n    sinλ = sin(λ)\r\n    cosλ = cos(λ)\r\n    v = ellipsoid.a / sqrt(1.0 - e² * sinΦ * sinΦ)\r\n    x = (v+h) * cosΦ * cosλ\r\n    y = (v+h) * cosΦ * sinλ\r\n    z = ((1.0 - e²) * v + h) * sinΦ;\r\n    return PositionXYZ(x,y,z)\r\nend\r\n\r\n\r\n# TODO: make it work for south and west\r\nfunction xyz_to_llh(ellipsoid::Wgs84, xyz::PositionXYZ)::PositionLLH\r\n    e²       = ellipsoid.e²\r\n    p        = sqrt(xyz.x*xyz.x + xyz.y*xyz.y)\r\n    lon      = atan(xyz.y / xyz.x)\r\n    lat_init = atan(xyz.z/(p*(1.0 - e²)))\r\n    v        = ellipsoid.a / sqrt(1.0-e²*sin(lat_init)*sin(lat_init))\r\n    lat      = atan((xyz.z + e²*v*sin(lat_init))/p)\r\n    height   = (p/cos(lat))-v\r\n    return PositionLLH(toDegrees(lat), toDegrees(lon), height)\r\nend\r\n\r\n\r\nfunction llh_to_xyz(ellipsioid::SphericalEarth, llh::PositionLLH)::PositionXYZ\r\n    Φ    = toRadians(llh.lat)\r\n    λ    = toRadians(llh.lon)\r\n    h    = llh.height\r\n    cosΦ = cos(Φ)\r\n    v    = ellipsioid.r + h\r\n    x    = v * cosΦ * cos(λ)\r\n    y    = v * cosΦ * sin(λ)\r\n    z    = v * sin(Φ)\r\n    return PositionXYZ(x,y,z)\r\nend\r\n\r\n\r\nfunction xyz_to_llh(ellipsoid::SphericalEarth, xyz::PositionXYZ)::PositionLLH\r\n    v      = sqrt(xyz.x*xyz.x + xyz.y*xyz.y + xyz.z*xyz.z) \r\n    height = v - ellipsoid.r\r\n    lon    = atan(xyz.y, xyz.x)\r\n    lat    = asin(xyz.z/v)\r\n    return PositionLLH(toDegrees(lat), toDegrees(lon), height)\r\nend\r\n\r\n\r\n# https://www.movable-type.co.uk/scripts/latlong.html\r\n# for SphericalEarth, but best source found\r\nfunction bearing(p1::PositionLLH, p2::PositionLLH)::Float64\r\n    φ1 = toRadians(p1.lat)\r\n    φ2 = toRadians(p2.lat)\r\n    Δλ = toRadians(p2.lon-p1.lon)\r\n    y  = sin(Δλ)*cos(φ2)\r\n    x  = cos(φ1)*sin(φ2) - sin(φ1)*cos(φ2)*cos(Δλ)\r\n    θ  = atan(y, x)\r\n    return mod(toDegrees(θ) + 360.0, 360.0)\r\nend\r\n\r\n\r\nxyz_to_vector(xyz::PositionXYZ)::Vector{Float64} = [xyz.x; xyz.y; xyz.z]\r\n\r\n\r\n\r\n# GeoUtils test\r\n#testXYZ = llh_to_xyz(wgs84, PositionLLH(49.0, 16.0, 225.0))\r\n#println(testXYZ)\r\n#testLLH= xyz_to_llh(wgs84, testXYZ)\r\n#println(testLLH)\r\n\r\n#================================================================\r\n _   _      _       _     _   __  __\r\n| | | | ___(_) __ _| |__ | |_|  \\/  | __ _ _ __\r\n| |_| |/ _ \\ |/ _` | '_ \\| __| |\\/| |/ _` | '_ \\\r\n|  _  |  __/ | (_| | | | | |_| |  | | (_| | |_) |\r\n|_| |_|\\___|_|\\__, |_| |_|\\__|_|  |_|\\__,_| .__/\r\n              |___/                       |_|\r\n===============================================================#\r\n\r\n\r\nstruct LatLonRange\r\n    minLat::Int16\r\n    minLon::Int16\r\n    maxLat::Int16\r\n    maxLon::Int16\r\nend\r\n\r\n\r\nfunction loadData(range::LatLonRange, tileDir)\r\n    getHgtFileName(lat, lon) = @sprintf \"N%02dE%03d.hgt\" lat lon\r\n    getHgtFilePath(lat, lon, tileDir) = @sprintf \"%s/%s\" tileDir getHgtFileName(lat, lon)\r\n\r\n    nTilesHoriz = range.maxLon - range.minLon + 1\r\n    nTilesVert  = range.maxLat - range.minLat + 1\r\n    nTilesTotal = nTilesHoriz * nTilesVert\r\n    dataWidth   = nTilesHoriz*1200+1\r\n    dataHeight  = nTilesVert*1200+1\r\n\r\n    @printf(\"Requesting data for area %d°N %d°E - %d°N %d°E ... (aprox. %3.0fx%3.0f km).\\n\",\r\n        range.minLat, range.minLon,\r\n        range.maxLat, range.maxLon,\r\n        (nTilesHoriz)*111.1*cos(range.minLat/180.0*π),\r\n        (nTilesVert)*111.1\r\n        )\r\n    @printf(\"I will read %dx%d=%d tiles, heightmap size is %dx%d (%d MB).\\n\",\r\n        nTilesHoriz, nTilesVert, nTilesTotal,\r\n        dataWidth, dataHeight, dataWidth*dataHeight*2/1000000\r\n        )\r\n\r\n    # Note: array is indexed by row, column and starting index is 1\r\n    data = Array{UInt16}(undef, dataHeight, dataWidth)\r\n    progress = 0\r\n    progressLock = Threads.SpinLock()\r\n    Threads.@threads for i in 0:(nTilesTotal-1)\r\n        lat = range.minLat + div(i, nTilesHoriz)\r\n        lon = range.minLon + mod(i, nTilesHoriz)\r\n        # Print progress\r\n        lock(progressLock) do\r\n            progress = progress + 1\r\n            @printf(\"Loading tile %03d/%03d lat=%02d, lon=%02d\\n\", progress, nTilesTotal, lat, lon)\r\n        end\r\n        # Load tile\r\n        tile = Array{Int16}(undef, 1201, 1201)\r\n        path = getHgtFilePath(lat, lon, tileDir)\r\n        io = open(path, \"r\")\r\n        read!(io, tile)\r\n        close(io)\r\n        # Fix endianity, clamp, transpose and copy to data\r\n        tile .= ntoh.(tile)\r\n        clamp!(tile, 0, 6000)\r\n        tile = transpose(tile)\r\n        rOffset = (range.maxLat-lat) * 1200\r\n        cOffset = (lon-range.minLon) * 1200\r\n        for r in 1:1201\r\n            @simd for c in 1:1201\r\n                data[rOffset+r, cOffset+c] = tile[r, c]\r\n            end\r\n        end\r\n    end\r\n    return data\r\nend\r\n\r\n\r\nfunction saveHeightMap(data)\r\n   maxValue = maximum(data)\r\n   norm = Images.Gray.(data/maxValue)\r\n   println(\"Saving heightmap-gray.png\")\r\n   save(\"heightmap-gray.png\", norm)\r\nend\r\n\r\n\r\n# getHeight(srtmRange, heightMap, 49.142158, 16.627978) -> 192 Svratka, Svitava\r\nfunction getHeight(range::LatLonRange, data::Matrix{UInt16}, lat::Float64, lon::Float64)\r\n    r = Int64(trunc((range.maxLat+1 - lat)*1200))\r\n    c = Int64(trunc((lon-range.minLon)*1200))\r\n    r = clamp(r, 1, size(data)[1])\r\n    c = clamp(c, 1, size(data)[2])\r\n    return data[r,c]\r\nend\r\n\r\n\r\nmakeEarthCurve(radius, distMax, distStep) = [sqrt(radius*radius-x*x)-radius for x=range(0, distMax, step=distStep)]\r\n\r\nstruct ViewPort\r\n    ellipsoid::Ellipsoid\r\n    eye::PositionLLH\r\n\r\n    angleMin::Float64\r\n    angleMax::Float64\r\n    vertAngleMin::Float64\r\n    vertAngleMax::Float64\r\n    angleStep::Float64\r\n\r\n    distMax::Float64\r\n    distStep::Float64\r\n\r\n    refractionCoef::Float64\r\n\r\n    vUp::Vector{Float64}\r\n    vNorth::Vector{Float64}\r\n    vEast::Vector{Float64}\r\n\r\n    outWidth::Int\r\n    outHeight::Int\r\n\r\n    function ViewPort(ellipsoid::Ellipsoid, eye::PositionLLH, azimuthMinR, azimuthMaxR, elevationMinR, elevationMaxR, angularStepR, distMaxM, refractionCoef)\r\n        distStep = 50.0\r\n        pRef   = xyz_to_vector(llh_to_xyz(ellipsoid, eye))\r\n        vZ     = [0.0; 0.0; 1.0]\r\n        vUp    = normalize(pRef)\r\n        vEast  = normalize(cross(-vUp,vZ))\r\n        vNorth = normalize(cross(vEast,-vUp))\r\n\r\n        azimuthDiff = abs(azimuthMinR-azimuthMaxR)\r\n        if (azimuthDiff > 2.0*π)\r\n            throw(DomainError(azimuthDiff, \"Azimuth difference should not exceed 2π\"))\r\n        end\r\n        if (azimuthMinR > azimuthMaxR)\r\n            azimuthMinR = azimuthMinR - 2.0*π\r\n        end\r\n        if (azimuthMinR < 0.0 && azimuthMaxR < 0.0)\r\n            azimuthMinR = azimuthMinR + 2.0*π\r\n            azimuthMaxR = azimuthMaxR + 2.0*π\r\n        end\r\n        xMax        = Int64(trunc( (azimuthMaxR-azimuthMinR)/angularStepR ))+1\r\n        outWidth    = xMax+1\r\n        outHeight   = size(range(elevationMinR, elevationMaxR, step=angularStepR))[1]+1\r\n        new(ellipsoid, eye,\r\n            azimuthMinR, azimuthMaxR, elevationMinR, elevationMaxR, angularStepR, \r\n            distMaxM, distStep, \r\n            refractionCoef,\r\n            vUp, vNorth, vEast,\r\n            outWidth, outHeight)\r\n    end\r\nend\r\n\r\n\r\nfunction eyeVec(vp::ViewPort)::Vector{Float64}\r\n    eyeXYZ = llh_to_xyz(vp.ellipsoid, vp.eye)\r\n    return [eyeXYZ.x; eyeXYZ.y; eyeXYZ.z]\r\nend\r\n\r\n\r\nfunction makeDistMap(vp::ViewPort, latLonRange::LatLonRange, heightMap::Matrix{UInt16})::Matrix{UInt16}\r\n    pRef = eyeVec(vp)\r\n    earthRadius = sqrt(dot(pRef, pRef)) * vp.refractionCoef\r\n    earthCurve  = makeEarthCurve(earthRadius, vp.distMax, vp.distStep)\r\n    @printf(\"Earth radius is %6.1f km (refraction x%4.2f)\\n\", earthRadius/vp.refractionCoef/1000.0, vp.refractionCoef)\r\n    @printf(\"Output size is %d x %d pixels\\n\", vp.outWidth, vp.outHeight)\r\n    @printf(\"Output resolution is %f mrad per pixel or %f pixels per degree\\n\", vp.angleStep * 1000.0, 1.0/toDegrees(vp.angleStep))\r\n    output      = zeros(UInt16, vp.outHeight, vp.outWidth)\r\n    distances   = range(0.0, vp.distMax, step=vp.distStep)\r\n    Threads.@threads for x in 0:(vp.outWidth-1)\r\n        azimuth = vp.angleMin + x*vp.angleStep\r\n        cosAz   = cos(azimuth)\r\n        sinAz   = sin(azimuth)\r\n\r\n        vertAngle     = vp.vertAngleMin\r\n        h0            = vp.eye.height\r\n        rayCastHeight = h0\r\n        index         = 1\r\n        direction     = vp.vNorth*cosAz + vp.vEast*sinAz\r\n        point = [0.0,0.0,0.0]\r\n        for dist in distances\r\n            #point = pRef + dist * direction;\r\n            #point = [pRef[1]+dist*direction[1], pRef[2]+dist*direction[2], pRef[3]+dist*direction[3]]\r\n            point[1] = pRef[1]+dist*direction[1]\r\n            point[2] = pRef[2]+dist*direction[2]\r\n            point[3] = pRef[3]+dist*direction[3]\r\n            llh = xyz_to_llh(vp.ellipsoid, PositionXYZ(point[1], point[2], point[3]))\r\n            rayCastHeight = h0 + sin(vertAngle) * dist\r\n            terrainHeight = earthCurve[index] + getHeight(latLonRange, heightMap, llh.lat, llh.lon)\r\n            if terrainHeight > rayCastHeight \r\n                newVertAngle = atan((terrainHeight-h0)/dist)\r\n                yTop = Int64(trunc( (vp.vertAngleMax-newVertAngle)/vp.angleStep ))\r\n                yBot = Int64(trunc( (vp.vertAngleMax-   vertAngle)/vp.angleStep ))\r\n                v = UInt16(trunc( dist / vp.distStep ))\r\n                for y in yTop:yBot \r\n                    output[y, x+1] = v\r\n                end\r\n                vertAngle = newVertAngle\r\n            end\r\n            index = index + 1\r\n        end\r\n    end\r\n    return output\r\nend\r\n\r\n\r\nfunction extractOutlines(distMap::Matrix{UInt16})\r\n    nRows = size(distMap)[1]\r\n    nCols = size(distMap)[2]\r\n    #ouput = Array{Int16}(undef, nRows, nCols)\r\n    output = zeros(N0f8, nRows, nCols)\r\n    Threads.@threads for row in 2:nRows\r\n        for col in 1:nCols\r\n            diff::UInt8 = 255-clamp(abs(reinterpret(Int16,distMap[row-1,col]) - reinterpret(Int16,distMap[row,col])), 0, 255)\r\n            output[row, col] = reinterpret(N0f8, diff)\r\n        end\r\n    end\r\n    return output\r\nend\r\n\r\n\r\nfunction testPixel(distMap::Matrix{UInt16}, x::UInt64, y::UInt64, radius::Int64, value::UInt16, valueTolerance::UInt16)::Bool\r\n    if (x < radius+1) || (y < radius+1) || (x+radius> size(distMap)[2]) || (y+radius> size(distMap)[1])\r\n        return false\r\n    end\r\n    for row in (y-radius):(y+radius)\r\n        for col in (x-radius):(x+radius)\r\n            mapValue = distMap[row, col]\r\n            if (mapValue > value) && ((mapValue - value) ≤ valueTolerance)\r\n                return true\r\n            end\r\n            if (mapValue < value) && ((value - mapValue) ≤ valueTolerance)\r\n                return true\r\n            end\r\n        end\r\n    end\r\n    return false\r\nend\r\n\r\n\r\nfunction drawSummits(vp::ViewPort, distMap::Matrix{UInt16})\r\n    println(\"Loading data\")\r\n    dfFiltered = DataFrames.DataFrame(Summit = String[], Elevation = Float64[], Distance=Float64[], X=UInt64[], Y=UInt64[])\r\n\r\n    # TODO: options\r\n    #hillsCZ = CSV.File(\"data-cz-prom100.tsv\") |> DataFrames.DataFrame\r\n    #hillsSK = CSV.File(\"data-sk-prom200.tsv\") |> DataFrames.DataFrame\r\n    #hills = vcat(hillsCZ, hillsSK)\r\n    hills =  CSV.File(\"osm-cz-sk.tsv\") |> DataFrames.DataFrame\r\n    # convert to ours azimuth, angle above horizon and distance - project into \r\n    hill_to_xyz(ellipsoid::Ellipsoid, dfRow)::PositionXYZ = llh_to_xyz(ellipsoid, PositionLLH(dfRow[\"Latitude\"], dfRow[\"Longitude\"], dfRow[\"Elevation\"])) \r\n    # difference between true and seen earth curvature\r\n    elevationDropAtDistance(distance::Float64, radius::Float64)::Float64 = sqrt(radius*radius-distance*distance)-radius\r\n    elevationDropCompensation(distance::Float64, radius::Float64, refractionCoef::Float64)::Float64 = elevationDropAtDistance(distance, radius*refractionCoef) - elevationDropAtDistance(distance, radius)\r\n    # TODO: make distance function\r\n    mLocalToWorld = hcat(vp.vEast,vp.vNorth,vp.vUp)\r\n    mWorldToLocal = inv(mLocalToWorld)\r\n    #ground = PositionLLH(vp.eye.lat, vp.eye.lon, 0.0)\r\n    pRef = xyz_to_vector(llh_to_xyz(vp.ellipsoid, vp.eye))\r\n    earthRadius = sqrt(dot(pRef, pRef))\r\n    for hill in eachrow(hills)\r\n        hill_world = hill_to_xyz(vp.ellipsoid, hill)\r\n        hill_local_xyz = mWorldToLocal * [hill_world.x; hill_world.y; hill_world.z]\r\n#        hill_local_xyz[3] = hill_local_xyz[3] - earthRadius  <---- this gives weird altitutude, let's restore it in the same way as raytracer\r\n        hill_local_xyz[3] = 0.0\r\n        distance = sqrt(dot(hill_local_xyz, hill_local_xyz))\r\n        if distance > vp.distMax\r\n            continue\r\n        end\r\n        hill_local_xyz[3] = hill[\"Elevation\"] + elevationDropAtDistance(distance, earthRadius * vp.refractionCoef) - vp.eye.height\r\n        azimuth = bearing(vp.eye, PositionLLH(hill[\"Latitude\"], hill[\"Longitude\"], 0.0))\r\n        if (azimuth < toDegrees(vp.angleMin) || azimuth > toDegrees(vp.angleMax)) # FIXME: test for weird angles\r\n            continue\r\n        end\r\n        @printf(\"%20s is possibly visible at azimuth %6.2f, distance %6.2f km\", hill[\"Summit\"], azimuth, distance/1000.0)\r\n        elevationAngle=atan(hill_local_xyz[3], distance)\r\n#        @printf(\"              hill=%f+%f, dist=%f\\n\", hill_local_xyz[3], elevationDropCompensation(distance, earthRadius, vp.refractionCoef), distance)\r\n#        @printf(\"              , pixel.x,y=%5.0f,%5.0f\\n\", (toRadians(azimuth)-vp.angleMin)/vp.angleStep , (vp.vertAngleMax-elevationAngle)/vp.angleStep )\r\n        testX::UInt64 = round((toRadians(azimuth)-vp.angleMin)/vp.angleStep)\r\n        testY::UInt64 = round((vp.vertAngleMax-elevationAngle)/vp.angleStep)\r\n        visible::Bool = testPixel(distMap, testX, testY, 4, UInt16(trunc(distance/vp.distStep)), UInt16(5))\r\n        @printf(\", visible=%s\\n\", visible)\r\n        if visible\r\n            push!(dfFiltered, (hill[\"Summit\"], hill[\"Elevation\"], distance, testX, testY))\r\n        end\r\n    end\r\n    println(\"Drawing ...\")\r\n    # Initialize\r\n    Cairo_set_line_color(ctx::Cairo.CairoContext) = Cairo.set_source_rgb(ctx, 131/255, 148/255, 150/255)\r\n    Cairo_set_text_color(ctx::Cairo.CairoContext) = Cairo.set_source_rgb(ctx,  38/255, 139/255, 210/255)\r\n    function Cairo_line(ctx::Cairo.CairoContext, x1::Core.Real, y1::Core.Real, x2::Core.Real, y2::Core.Real)\r\n        Cairo.move_to(ctx, x1, y1)\r\n        Cairo.line_to(ctx, x2, y2)\r\n        Cairo.stroke(ctx)\r\n    end\r\n    surf = Cairo.CairoARGBSurface(vp.outWidth, vp.outHeight)\r\n    ctx  = Cairo.CairoContext(surf)\r\n    # Background (previous image)\r\n    bgSurf = Cairo.read_from_png(\"outlines.png\")\r\n    Cairo.set_source_surface(ctx, bgSurf, 0.0, 0.0)\r\n    Cairo.paint(ctx)\r\n    # Annotations\r\n    Cairo.select_font_face(ctx, \"Fira Sans\", Cairo.FONT_SLANT_NORMAL, Cairo.FONT_WEIGHT_NORMAL)\r\n    Cairo.set_font_size(ctx, 18.0)\r\n    Cairo.set_line_width(ctx, 1.0)\r\n    for poi in eachrow(dfFiltered)\r\n        Cairo_set_line_color(ctx)\r\n        Cairo_line(ctx, poi[\"X\"]+0.5, poi[\"Y\"], poi[\"X\"]+0.5, 300.0)\r\n        Cairo_set_text_color(ctx)\r\n        Cairo.move_to(ctx, poi[\"X\"]+5, 300.0-5.0)\r\n        Cairo.save(ctx)\r\n        Cairo.rotate(ctx, toRadians(-45.0))\r\n        Cairo.show_text(ctx, poi[\"Summit\"])\r\n        Cairo.show_text(ctx, @sprintf(\" (%3.0f km)\", poi[\"Distance\"]/1000.0))\r\n        Cairo.restore(ctx)\r\n    end\r\n    # Azimuth ticks\r\n    azMinD::Int = Int(ceil(toDegrees(vp.angleMin)))\r\n    azMaxD::Int = Int(floor(toDegrees(vp.angleMax)))\r\n    for az in azMinD:azMaxD\r\n        x = round((toRadians(Float64(az))-vp.angleMin)/vp.angleStep)+0.5\r\n        Cairo_set_line_color(ctx)\r\n        Cairo_line(ctx, x, 38, x, 42)\r\n        Cairo_line(ctx, x, 63, x, 68)\r\n        Cairo_set_text_color(ctx)\r\n        ext = Cairo.text_extents(ctx, @sprintf(\"%d\", az))\r\n        Cairo.move_to(ctx, x - ext[3]/2, 58)\r\n        Cairo.show_text(ctx, @sprintf(\"%d °\", az))\r\n    end\r\n    # Horizon line\r\n    horizY = round(vp.vertAngleMax/vp.angleStep)+0.5\r\n    Cairo.set_source_rgb(ctx, 238/255, 232/255, 213/255)\r\n    Cairo_line(ctx, 0.0, horizY, vp.outWidth, horizY)\r\n    # Finalize\r\n    Cairo.write_to_png(surf, \"outline-with-annotations.png\" )\r\nend\r\n\r\n# Info (from https://www.udeuschle.de/panoramas/makepanoramas_en.htm)\r\n# Lat: 50.08309 Lon 17.23094 Alt(auto+10m): 1500+10\r\n# View direction: 112.5, extension 45 left: 90, right: 135, resolution 20pix/deg\r\n# Tilt, range, vert. exaggeration 1.2\r\n\r\n# TODO: determine lat/long range automatically\r\nfunction main()\r\n    tileDir     = \"d:/_disk_d_old/devel-python/panorama/data_srtm\"\r\n\t#tileDir     = \"data_srtm\"\r\n    latLonRange = LatLonRange(47, 15, 50, 21)\r\n    eye         = PositionLLH(50.08309, 17.23094, 1510)\r\n\r\n    heightMap = loadData(latLonRange, tileDir)\r\n    #saveHeightMap(data)\r\n    ellipsoid = SphericalEarth()\r\n    #ellipsoid = Wgs84()\r\n    vp = ViewPort(ellipsoid, eye, toRadians(90.0), toRadians(135.0), -0.0560, 0.0339, 0.0001, 250.0e3, 1.18)\r\n    distMap   = makeDistMap(vp, latLonRange, heightMap)\r\n\r\n    minValue = minimum(distMap)\r\n    maxValue = maximum(distMap)\r\n    @printf(\"min=%d max=%d\\n\", minValue, maxValue)\r\n    println(\"Saving distmap-gray.png\")\r\n    Images.save(\"distmap-gray.png\", Images.Gray.(distMap/maxValue))\r\n\r\n    println(\"Extracting outlines ...\")\r\n    outlines=extractOutlines(distMap)\r\n    println(\"Saving outlines.png\")\r\n    Images.save(\"outlines.png\", outlines)\r\n\r\n    println(\"Creating annotations\")\r\n    drawSummits(vp, distMap)\r\n    println(\"All done\")\r\n\r\n    # This can be fun: https://wiki.flightgear.org/Atmospheric_light_scattering\r\n    # http://www.science-and-fiction.org/rendering/als.html\r\nend\r\n\r\nmain()\r\n\r\n", "meta": {"hexsha": "403fd15f76fda6123302a8af896be574a2e0e822", "size": 18684, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "pano.jl", "max_stars_repo_name": "pavel-perina/panorama-jl", "max_stars_repo_head_hexsha": "d492e3e76b73f837413ae00b87a577bef6a855fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pano.jl", "max_issues_repo_name": "pavel-perina/panorama-jl", "max_issues_repo_head_hexsha": "d492e3e76b73f837413ae00b87a577bef6a855fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pano.jl", "max_forks_repo_name": "pavel-perina/panorama-jl", "max_forks_repo_head_hexsha": "d492e3e76b73f837413ae00b87a577bef6a855fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.998019802, "max_line_length": 203, "alphanum_fraction": 0.5988011133, "num_tokens": 5701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561685659695, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7608510676890474}}
{"text": "using LinearAlgebra\r\nusing Plots\r\n\r\n\r\nfunction main()\r\n\r\n    # vector_ops()\r\n    matrix_ops()\r\n\r\nend\r\n\r\nfunction vector_ops()\r\n    x = [1, 2, 3]\r\n    y = [1; 2; 3]\r\n    z = [1 2 3]\r\n    q = [1 2 3; 4 5 6]\r\n\r\n    # display(x)\r\n    # display(y)\r\n    # display(z)\r\n    # display(q)\r\n\r\n    # norm\r\n    # println(norm(x))\r\n    # println(x / norm(x))\r\n    # println(normalize(x))\r\n\r\n    # dot product\r\n    # println(dot(x, y))\r\n    # println(x ⋅ y)\r\n\r\n    # cross product\r\n    println(cross(x,y))\r\n    println(x × y)\r\n\r\nend\r\n\r\nfunction matrix_ops()\r\n\r\n    A = [0 2 4; 2 4 2; 3 3 1]\r\n    B = ones(3,3)\r\n    C = [1 1; 1 1; 1 1]\r\n\r\n    # matrix multiplication\r\n    # display(A * B)\r\n    # display(A * C)\r\n\r\n    # elementwise multiplication\r\n    # display(A .* B)\r\n\r\n    # special operations\r\n    # println(tr(A))\r\n    # println(det(A))\r\n    # display(transpose(A))\r\n    # display(eigvals(A))\r\n    # display(eigvecs(A))\r\n    # display(inv(A))\r\n\r\n    # special matrices\r\n    # D = [1 0 0; 0 1 0; 0 0 1]\r\n    # display(D)\r\n    # D = Diagonal(D)\r\n\r\n    # linear system Ax = b\r\n    A = [1 2; 1 -1]\r\n    b = [5, -1]\r\n\r\n    # A = factorize(A)\r\n    # display(A)\r\n    # display(A.L * A.U)\r\n\r\n    x0 = A \\ b\r\n\r\n    xlin = range(0, 5, length=50)\r\n    f(x) = 5 - 2x\r\n    g(x) = -1 + x\r\n\r\n    println(x0)\r\n\r\n    plot(xlin, f.(xlin), label=\"f(x)\", xaxis=\"x\", yaxis=\"y\")\r\n    plot!(xlin, g.(xlin), label=\"g(x)\", title=\"Showing Solved Values\")\r\n    scatter!((x0[2], x0[1]), label=\"solved values\", dpi=150)\r\nend\r\n\r\n\r\nmain()", "meta": {"hexsha": "eddb31dc0fe567988c180200c8c4988abd46c6c0", "size": 1497, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia-learning-src/advance/09-linear_algebra.jl", "max_stars_repo_name": "nunesmelo/djs-office-hours", "max_stars_repo_head_hexsha": "aa5cc3dfe3072c5608bf25f5dab27cbfa3664713", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-03-27T14:23:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T14:50:37.000Z", "max_issues_repo_path": "julia-learning-src/advance/09-linear_algebra.jl", "max_issues_repo_name": "nunesmelo/djs-office-hours", "max_issues_repo_head_hexsha": "aa5cc3dfe3072c5608bf25f5dab27cbfa3664713", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia-learning-src/advance/09-linear_algebra.jl", "max_forks_repo_name": "nunesmelo/djs-office-hours", "max_forks_repo_head_hexsha": "aa5cc3dfe3072c5608bf25f5dab27cbfa3664713", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-03-29T20:01:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T14:33:47.000Z", "avg_line_length": 17.4069767442, "max_line_length": 71, "alphanum_fraction": 0.4762859051, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561658682131, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7608510655704762}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,jl:hydrogen\n#     text_representation:\n#       extension: .jl\n#       format_name: hydrogen\n#       format_version: '1.3'\n#       jupytext_version: 1.10.3\n#   kernelspec:\n#     display_name: Julia 1.7.0\n#     language: julia\n#     name: julia-1.7\n# ---\n\n# %%\nusing Distributions\nusing StatsPlots\n\n# %% [markdown]\n# 負の二項分布の確率函数は\n#\n# $$\n# P(k) = \\binom{k+r-1}{k} p^r (1 - p)^k \\quad (k = 0,1,2,\\ldots)\n# $$\n#\n# であり, $k$ は成功確率 $p$ のBernoulli試行で初めて $r$ 回成功するまでの失敗する回数を意味している. \n#\n# これのパラメータを $r = \\alpha$, $p = 1/(N\\theta)$ とおくと, $N$ が大きいとき $k/N$ は近似的に分布 $\\operatorname{Gamma}(\\alpha, \\theta)$ に従う.\n\n# %%\nfunction plot_scaled_negbin(; α = 3, θ = 5, N = 100)\n    gamma = Gamma(α, θ)\n    negbin = LocationScale(0, 1/N, NegativeBinomial(α, 1/(N*θ)))\n    \n    xmax = quantile(gamma, 0.995)\n    plot(; legend=:bottomright)\n    plot!(x -> cdf(negbin, x), 0, xmax; label=\"NegativeBinomial(r = α, p = 1/(Nθ)) scaled by 1/N\")\n    plot!(x -> cdf(gamma, x), 0, xmax; label=\"Gamma(α = $α, θ = $θ)\", ls=:dash)\n    title!(\"cdf of scaled NegativeBinomial distribution for N = $N\"; titlefontsize=10)\nend\n\n# %%\nplot_scaled_negbin(N = 1)\n\n# %%\nplot_scaled_negbin(N = 10)\n\n# %%\nplot_scaled_negbin(N = 100)\n\n# %%\nα = 3\nθ = 5\nN = 100\ngamma = Gamma(α, θ)\nnegbin = LocationScale(0, 1/N, NegativeBinomial(α, 1/(N*θ)))\nX = rand(negbin, 10^5)\n\nxmax = 60\nstephist(X; norm=true, bin=0:xmax, label=\"NegativeBinomial(r = α, p = 1/(Nθ)) scaled by 1/N\")\nplot!(gamma, 0, xmax; label=\"Gamma(α = $α, θ = $θ)\", ls=:dash)\ntitle!(\"sample of scaled NegativeBinomial distribution for N = $N\"; titlefontsize=10)\n\n# %% [markdown]\n# 二項分布の確率函数は\n#\n# $$\n# P(k) = \\binom{n}{k} p^k (1 - p)^{n-k} \\quad (k = 0,1,\\ldots,n)\n# $$\n#\n# であり, $k$ は成功確率 $p$ の $n$ 回のBernoulli試行中の成功回数を意味している.\n#\n# これのパラメータを $p = \\lambda/n$ とおくと, $n$ が大きいとき $k$ は近似的に分布 $\\operatorname{Poisson}(\\lambda)$ に従う.\n\n# %%\nfunction plot_bin(; λ = 5, n = 100)\n    poisson = Poisson(λ)\n    bin(n) = Binomial(n, λ/n)\n    \n    xmax = quantile(poisson, 0.995)\n    plot(; legend=:bottomright)\n    plot!(x -> cdf(bin(n), x), 0, xmax; label=\"Binomial(n, p = λ/n)\")\n    plot!(x -> cdf(poisson, x), 0, xmax; label=\"Poisson(λ = $λ)\", ls=:dash)\n    title!(\"cdf of Binomial distribution for n = $n\"; titlefontsize=10)\nend\n\n# %%\nplot_bin(n = 5)\n\n# %%\nplot_bin(n = 10)\n\n# %%\nplot_bin(n = 100)\n\n# %%\n", "meta": {"hexsha": "3aae5a0da9344e200cfd880eee64b23170d69682", "size": 2371, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0025/scaled NegativeBinomial distribution approximates Gamma distribution.jl", "max_stars_repo_name": "genkuroki/public", "max_stars_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-06-06T00:33:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T06:56:08.000Z", "max_issues_repo_path": "0025/scaled NegativeBinomial distribution approximates Gamma distribution.jl", "max_issues_repo_name": "genkuroki/public", "max_issues_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0025/scaled NegativeBinomial distribution approximates Gamma distribution.jl", "max_forks_repo_name": "genkuroki/public", "max_forks_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-02T11:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T11:46:05.000Z", "avg_line_length": 23.9494949495, "max_line_length": 118, "alphanum_fraction": 0.588781105, "num_tokens": 1031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.7608037503650289}}
{"text": "# indicator of a generic box\n\nexport IndBox, IndBallLinf\n\n\"\"\"\n**Indicator of a box**\n\n    IndBox(low, up)\n\nReturns the indicator function of the set\n```math\nS = \\\\{ x : low \\\\leq x \\\\leq up \\\\}.\n```\nParameters `low` and `up` can be either scalars or arrays of the same dimension as the space: they must satisfy `low <= up`, and are allowed to take values `-Inf` and `+Inf` to indicate unbounded coordinates.\n\"\"\"\nstruct IndBox{T <: Union{Real, AbstractArray}, S <: Union{Real, AbstractArray}} <: ProximableFunction\n    lb::T\n    ub::S\n    function IndBox{T,S}(lb::T, ub::S) where {T <: Union{Real, AbstractArray}, S <: Union{Real, AbstractArray}}\n        if !(eltype(lb) <: Real && eltype(ub) <: Real)\n            error(\"`lb` and `ub` must be real\")\n        end\n        if any(lb .> ub)\n            error(\"`lb` and `ub` must satisfy `lb <= ub`\")\n        else\n            new(lb, ub)\n        end\n    end\nend\n\nis_separable(f::IndBox) = true\nis_convex(f::IndBox) = true\nis_set(f::IndBox) = true\nis_cone(f::IndBox) = all((f.lb .== -Inf) .+ (f.ub .== +Inf) .> 0)\n\nIndBox(lb::T, ub::T) where {T <: Real} = IndBox{T, T}(lb, ub)\n\nIndBox(lb::T, ub::S) where {T <: AbstractArray, S <: Real} = IndBox{T, S}(lb, ub)\n\nIndBox(lb::T, ub::S) where {T <: Real, S <: AbstractArray} = IndBox{T, S}(lb, ub)\n\nIndBox(lb::T, ub::S) where {T <: AbstractArray, S <: AbstractArray} =\n    size(lb) != size(ub) ? error(\"bounds must have the same dimensions, or at least one of them be scalar\") :\n    IndBox{T, S}(lb, ub)\n\nfunction (f::IndBox)(x::AbstractArray{R}) where R <: Real\n    for k in eachindex(x)\n        if x[k] < get_kth_elem(f.lb, k) || x[k] > get_kth_elem(f.ub, k)\n            return +Inf\n        end\n    end\n    return 0.0\nend\n\nfunction prox!(y::AbstractArray{R}, f::IndBox, x::AbstractArray{R}, gamma::Real=R(1)) where R <: Real\n    for k in eachindex(x)\n        if x[k] < get_kth_elem(f.lb, k)\n            y[k] = get_kth_elem(f.lb, k)\n        elseif x[k] > get_kth_elem(f.ub, k)\n            y[k] = get_kth_elem(f.ub, k)\n        else\n            y[k] = x[k]\n        end\n    end\n    return R(0)\nend\n\nprox!(y::AbstractArray{R}, f::IndBox, x::AbstractArray{R}, gamma::AbstractArray) where {R <: Real} = prox!(y, f, x, R(1))\n\n\"\"\"\n**Indicator of a ``L_∞`` norm ball**\n\n    IndBallLinf(r=1.0)\n\nReturns the indicator function of the set\n```math\nS = \\\\{ x : \\\\max (|x_i|) \\\\leq r \\\\}.\n```\nParameter `r` must be positive.\n\"\"\"\nIndBallLinf(r::R=1.0) where {R <: Real} = IndBox(-r, r)\n\nfun_name(f::IndBox) = \"indicator of a box\"\nfun_dom(f::IndBox) = \"AbstractArray{Real}\"\nfun_expr(f::IndBox) = \"x ↦ 0 if all(lb ⩽ x ⩽ ub), +∞ otherwise\"\nfun_params(f::IndBox) =\n    string( \"lb = \", typeof(f.lb) <: AbstractArray ? string(typeof(f.lb), \" of size \", size(f.lb)) : f.lb, \", \",\n            \"ub = \", typeof(f.ub) <: AbstractArray ? string(typeof(f.ub), \" of size \", size(f.ub)) : f.ub)\n\nfunction prox_naive(f::IndBox, x::AbstractArray{R}, gamma=R(1)) where R <: Real\n    y = min.(f.ub, max.(f.lb, x))\n    return y, R(0)\nend\n", "meta": {"hexsha": "a7ae8bee493c9e17391be4affaf4ca4da6d9b8a6", "size": 2992, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indBox.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_stars_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/indBox.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_issues_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/indBox.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_forks_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.829787234, "max_line_length": 208, "alphanum_fraction": 0.5812165775, "num_tokens": 1019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7607904298603569}}
{"text": "\"\"\"\n# Usage\n\n    solve(α, dx, dt, xStart, xEnd, n, κ, FiniteDiffIm())\n\nUse implicit finite difference to discrete equations.\n\n### References\n\n```tex\n@article{Murio2008ImplicitFD,\n  title={Implicit finite difference approximation for time fractional diffusion equations},\n  author={Diego A. Murio},\n  journal={Comput. Math. Appl.},\n  year={2008},\n  volume={56},\n  pages={1138-1145}\n}\n```\n\nMatlab version: https://github.com/awstown/Fractional-Derivative\n\"\"\"\nstruct FiniteDiffIm <: FractionalDiffEqAlgorithm end\n\n\nfunction solve(α, dx, dt, xStart, xEnd, n, κ, u0t, uendt, u0, ::FiniteDiffIm)\n    x = collect(0:dx:xEnd)\n    t = collect(0:dt:n)\n\n    U = zeros(Int64(n/dt + 1), Int64((xEnd - xStart)/dx + 1))\n\n    # Boundry conditions\n    U[:, 1] .= u0t\n    U[:, end] .= uendt\n\n    U[1, :] .= u0.(x)\n\n    mu = (dt^α)/(dx^2)\n    r = mu * gamma(2-α)\n    A1 = diagm((1+2*r)*ones(length(x)-2))\n    A2 = diagm(1 => -r*ones(length(x)-3))\n    A3 = diagm(-1 => -r*ones(length(x)-3))\n    A = A1 + A2 + A3\n\n\n    U[2, 2:end-1] = A \\ U[1, 2:end-1]\n\n    j = collect(0:length(t))\n    b_j = (j.+1).^(1-α) .- j.^(1-α)\n    c_j = b_j[1:end-1] - b_j[2:end]\n\n    V = copy(U[2:end, 2:end-1])\n    for k = 1:length(V[:, 1])-1\n        V[k+1, :] = A \\ ImNextStep(V, U[1, 2:end-1], k, b_j, c_j)'\n    end\n    U[2:end, 2:end-1] = V\n    return U\nend\n\nImNextStep( V, U_0, k, b_j, c_j ) = c_j[1:k]' * reverse(V[1:k, :], dims=1) .+ (b_j[k+1].*U_0)'", "meta": {"hexsha": "fc3fede214fa71aed5dc5885b6a43d064d9aaed2", "size": 1411, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FPDE/FiniteDiffIm.jl", "max_stars_repo_name": "SciFracX/FractionalDiffEq.jl", "max_stars_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-11-05T12:49:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:57:20.000Z", "max_issues_repo_path": "src/FPDE/FiniteDiffIm.jl", "max_issues_repo_name": "SciFracX/FractionalDiffEq.jl", "max_issues_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-11-01T22:05:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:57:19.000Z", "max_forks_repo_path": "src/FPDE/FiniteDiffIm.jl", "max_forks_repo_name": "SciFracX/FractionalDiffEq.jl", "max_forks_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5166666667, "max_line_length": 94, "alphanum_fraction": 0.5634301914, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450965, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7607904280434754}}
{"text": "################################################################################\n#                                   SiO₂                                       #\n################################################################################\nexport SiO₂\n\n\"\"\"\nThis code creates a symbolic representation of the Sellmeier Equation model\nfor the index of refraction of amorphous SiO₂.Equation form is based on:\n     Kitamura, et al.\n     \"Optical constants of silica glass from extreme ultraviolet to far\n     infrared at near room temperature.\" Applied optics 46.33 (2007): 8118-8133.\nwhich references\n    Malitson, “Interspecimen comparison of the refractive index of fused\n    silica,” J. Opt. Soc. Am.55,1205–1209 (1965)\nand has been validated from 0.21-6.7 μm (free space wavelength).\nThe thermo-optic coefficient (for 300K) is from the literature, but I forgot\nthe source.\nThe symbolic index model and its derivatives in turn are used to generate\nnumerical functions for the SiO₂ index, group index and GVD as a function\nof temperature and wavelength.\nVariable units are lm in [um] and T in [deg C]\n\"\"\"\n\np_n²_SiO₂ = (\n    A₀ = 1,\n    B₁ = 0.6961663,\n    C₁ = (0.0684043)^2,     #                           [μm²]\n    B₂ = 0.4079426,\n    C₂ = (0.1162414)^2,     #                           [μm²]\n    B₃ = 0.8974794,\n    C₃ = (9.896161)^2,      #                           [μm²]\n    dn_dT = 6.1e-6,         # thermo-optic coefficient  [K⁻¹]\n    T₀ = 20,                # reference temperature     [°C]\n)\n\nfunction make_SiO₂(;p_n²=p_n²_SiO₂)\n\t@variables λ, T\n\tn = sqrt(n²_sym_fmt1( λ ; p_n²...)) + p_n².dn_dT  *  ( T - p_n².T₀  )\n\tn² = n^2\n\tε \t= diagm([n², n², n²])\n\tng = ng_model(n,λ)\n\tgvd = gvd_model(n,λ)\n\tmodels = Dict([\n\t\t:n\t\t=>\tn,\n\t\t:ng\t\t=>\tng,\n\t\t:gvd\t=>\tgvd,\n\t\t:ε \t\t=> \tdiagm([n², n², n²]),\n\t])\n\tdefaults =\tDict([\n\t\t:λ\t\t=>\t\t0.8,\t\t# μm\n\t\t:T\t\t=>\t\tp_n².T₀,\t# °C\n\n\t])\n\tMaterial(models, defaults, :SiO₂, colorant\"aqua\")\nend\n\n################################################################\n\nSiO₂ = make_SiO₂()\n# SiO₂_num = \n\n# struct NumMaterial{T,F1,F2,F3,TC} where {T, F1<:Function, F2<:Function, F3<:Function, TC}\n# \tε::T\n# \tfε::F1\n# \tfng::F2\n# \tfgvd::F3\n# \tfχ⁽²⁾::F4\n# \tname::Symbol\n# \tcolor::TC\n# end\n", "meta": {"hexsha": "d0d2b9bb39555ddf873c4062438d2c4689ae4280", "size": 2208, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/material_lib/SiO2.jl", "max_stars_repo_name": "doddgray/OptiMode.jl", "max_stars_repo_head_hexsha": "8d3185000218e0094c01b83f420dcebdf270b2c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-26T00:20:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T05:24:38.000Z", "max_issues_repo_path": "src/material_lib/SiO2.jl", "max_issues_repo_name": "doddgray/OptiMode.jl", "max_issues_repo_head_hexsha": "8d3185000218e0094c01b83f420dcebdf270b2c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/material_lib/SiO2.jl", "max_forks_repo_name": "doddgray/OptiMode.jl", "max_forks_repo_head_hexsha": "8d3185000218e0094c01b83f420dcebdf270b2c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0985915493, "max_line_length": 91, "alphanum_fraction": 0.5217391304, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7607189249915028}}
{"text": "## Julia program for Random walk Metropolis-Hastings for Normal distribution\r\n## author: weiya <szcfweiya@gmail.com>\r\n## date: 2018-08-21\r\n\r\n# random walk Metropolis-Hastings\r\nfunction rmh(T, delta, f::Function, initval = 5)\r\n    x = ones(T+1)\r\n    x[1] = initval\r\n    for t = 1:T\r\n        # generate Yt\r\n        epsi = rand() * 2 * delta - delta\r\n        Yt = epsi + x[t]\r\n        # accept or not\r\n        u = rand()\r\n        r = f(Yt)/f(x[t])\r\n        if r >= 1\r\n            x[t+1] = Yt\r\n        else\r\n            if u <= r\r\n                x[t+1] = Yt\r\n            else\r\n                x[t+1] = x[t]\r\n            end\r\n        end\r\n    end\r\n    return(x)\r\nend\r\n\r\n# density function of N(0, 1) without normalization\r\nfunction dnorm(x)\r\n    return(exp(-0.5 * x^2))\r\nend\r\n\r\n# example\r\ndeltalist = [0.1, 0.5, 1]\r\nN = 15000\r\n# results of mean and variance\r\nmuvar = zeros(3, 2)\r\nusing Statistics\r\nps = []\r\nfor i = 1:3\r\n    x = rmh(N, deltalist[i], dnorm)\r\n    push!(ps, plot(x, legend=false))\r\n    muvar[i, 1] = mean(x)\r\n    muvar[i, 2] = var(x)\r\nend\r\n# plot\r\nusing Plots\r\nplot(ps[1], ps[2], ps[3], layout=(3,1))\r\nsavefig(\"res_rmh.png\")\r\n", "meta": {"hexsha": "b3a65890b467698c19e6bff4d0d1dbd0b3083173", "size": 1135, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "MH/RWMH/normal_rmh.jl", "max_stars_repo_name": "szcf-weiya/MCMC", "max_stars_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-07-19T12:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T08:06:50.000Z", "max_issues_repo_path": "MH/RWMH/normal_rmh.jl", "max_issues_repo_name": "szcf-weiya/MCMC", "max_issues_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-02-03T15:08:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-05T15:41:39.000Z", "max_forks_repo_path": "MH/RWMH/normal_rmh.jl", "max_forks_repo_name": "szcf-weiya/MCMC", "max_forks_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-07-19T12:50:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T08:06:52.000Z", "avg_line_length": 22.2549019608, "max_line_length": 77, "alphanum_fraction": 0.5057268722, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7607189167198952}}
{"text": "# Generic update function\n\n\"\"\"\n    update(filter::AbstractFilter, b0::GaussianBelief, u::AbstractVector,\n        y::AbstractVector)\n\nUses AbstractFilter filter to update gaussian belief b0, given control vector\nu and measurement vector y.\n\"\"\"\nfunction update(filter::AbstractFilter, b0::GaussianBelief,\n                u::AbstractVector{<:Number}, y::AbstractVector{<:Number})\n\n    # predict\n    bp = predict(filter, b0, u)\n\n    # measure\n    bn = measure(filter, bp, y; u = u)\n\n    return bn\nend\n\n# Kalman filter functions\n\n\"\"\"\n    predict(filter::KalmanFilter, b0::GaussianBelief, u::AbstractVector)\n\nUses Kalman filter to run prediction step on gaussian belief b0, given control\nvector u.\n\"\"\"\nfunction predict(filter::KalmanFilter, b0::GaussianBelief,\n            u::AbstractVector{<:Number})\n\n    # Motion update\n    μp = filter.d.A * b0.μ + filter.d.B * u\n    Σp = filter.d.A * b0.Σ * filter.d.A' + filter.d.W\n    return GaussianBelief(μp, Σp)\nend\n\n\"\"\"\n    measure(filter::KalmanFilter, bp::GaussianBelief, y::AbstractVector;\n        u::AbstractVector = [false])\n\nUses Kalman filter to run measurement update on predicted gaussian belief bp,\ngiven measurement vector y. If u is specified and filter.o.D has been declared,\nthen matrix D will be factored into the y predictions\n\"\"\"\nfunction measure(filter::KalmanFilter, bp::GaussianBelief, y::AbstractVector{<:Number};\n                u::AbstractVector{<:Number} = [false])\n\n    # Kalman Gain\n    K = bp.Σ * filter.o.C' *\n        inv(filter.o.C * bp.Σ * filter.o.C' + filter.o.V)\n\n    # Predicted measurement\n    yp = measure(filter.o, bp.μ, u)\n\n    # Measurement update\n    μn = bp.μ + K * (y-yp)\n    Σn = (I - K * filter.o.C) * bp.Σ\n    return GaussianBelief(μn, Σn)\nend\n", "meta": {"hexsha": "4b09a90ea95f873e5b2febedfbfaaa5857412dff", "size": 1727, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kf.jl", "max_stars_repo_name": "JuliaTagBot/GaussianFilters.jl", "max_stars_repo_head_hexsha": "a509925631bbdde5b1adaa85024a436cfa14722f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2019-09-20T23:22:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:27:05.000Z", "max_issues_repo_path": "src/kf.jl", "max_issues_repo_name": "JuliaTagBot/GaussianFilters.jl", "max_issues_repo_head_hexsha": "a509925631bbdde5b1adaa85024a436cfa14722f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2019-09-21T00:10:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-06T20:48:10.000Z", "max_forks_repo_path": "src/kf.jl", "max_forks_repo_name": "JuliaTagBot/GaussianFilters.jl", "max_forks_repo_head_hexsha": "a509925631bbdde5b1adaa85024a436cfa14722f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:41:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T12:54:23.000Z", "avg_line_length": 27.8548387097, "max_line_length": 87, "alphanum_fraction": 0.6653155761, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7607189162285873}}
{"text": "#!/usr/bin/env julia\n\n# Best run in the REPL until I work out how to get unicodeplots to print to stdout when in an `include`\n# `env JULIA_NUM_THREADS=(nproc) julia --project`\n\nusing JustJoshing\n\nimport Plots\nPlots.unicodeplots()\n\n# This should look like Figure 5.3, page 121 in Joshi (it does)\n# NB: looks like Joshi's graph is mislabelled - should be spot price\np = Plots.plot(); for t in 0:0.2499:1; Plots.plot!(p,x->C(x,t;K=100,σ=0.3,r=0),60:140); end; p\n\nPlots.plot(x->C(1,x),0:0.001:0.9999) # Value of at-the-money approaches zero as time approaches maturity (Fig 2.1, page 35)\n\nPlots.plot(x->C(0.5,0;σ=x),0:0.01:1) # Call options with volatile underlyings are more expensive (Fig 3.8, page 66)\n\n# Simulated stock price\nPlots.plot(x->B(x,σ=0.02),0:0.01:1)\n\n\n# Monte-Carlo validation of contracts from payoffs\n\n# max(S-K,0): call option\nlet S_t=100, t=0.01, K=100, r=0.02, σ=0.05, T=1, trials=100_000_000\n    @show bs = C(S_t,t;T=T,K=K,r=r,σ=σ)\n\n    @show mc = mc_pricer((S,K,t,T,r)->max(S-K,0),S_t;t=t,T=T,K=S_t,r=r,σ=σ) |> first\n\n    @assert isapprox(mc, bs, rtol=1e-3)\nend\n\n# S-K: forward contract\nlet S_t=100, t=0.01, K=100, r=0.02, σ=0.05, T=1, trials=100_000_000\n    @show exact = S_t - K*exp(-r*(T-t))\n\n    @show mc = mc_pricer((S,K,t,T,r)->S-K,S_t;t=t,T=T,K=K,r=r,σ=σ) |> first\n\n    @assert isapprox(mc, exact, rtol=1e-3)\nend\n\n# Int(S>E): binary option\nlet S_t=100, t=0.01, E=100, r=0.02, σ=0.05, T=1, trials=100_000_000\n    @show exact = binary(S_t,t;E=E,r=r,σ=σ,T=T)\n\n    @show mc = mc_pricer((S,E,t,T,r)->Int(S>E),S_t;t=t,T=T,K=E,r=r,σ=σ) |> first\n\n    @assert isapprox(mc, exact, rtol=1e-3)\nend\n\n# Asian option, fixed strike\n# TODO: compare prices with European options, look at impact volatility has\ns = 80:1:120; t = [0; round.(-1*10 .^(-2:0.2:-1);sigdigits = 2)]\na = (x->mc_pricer_pathdep((S,K,t,T,r)->max(mean(S)-100,0),x[1],trials=100_000,r=0,t=x[2]:0.1:0,T=0,σ=0.5)).(Iterators.product(s,t))\nplot(s,first.(a),labels=string.(t'))\n", "meta": {"hexsha": "3491eed9ba27d45c701a29da62aa5a608f704dfe", "size": 1952, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/black_scholes_vanilla.jl", "max_stars_repo_name": "bovine3dom/JustJoshing.jl", "max_stars_repo_head_hexsha": "0da2d140fe44692954a6c03d181fdc2c5a45a24e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/black_scholes_vanilla.jl", "max_issues_repo_name": "bovine3dom/JustJoshing.jl", "max_issues_repo_head_hexsha": "0da2d140fe44692954a6c03d181fdc2c5a45a24e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-07T23:11:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-09T15:35:08.000Z", "max_forks_repo_path": "examples/black_scholes_vanilla.jl", "max_forks_repo_name": "bovine3dom/JustJoshing.jl", "max_forks_repo_head_hexsha": "0da2d140fe44692954a6c03d181fdc2c5a45a24e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2456140351, "max_line_length": 131, "alphanum_fraction": 0.6485655738, "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7607140166108718}}
{"text": "function Helmholtz{T<:AbstractFloat}(isz::Array{Int,1},isx::Array{Int,1},ot::Array{T,1},vp::Array{T,2},wav::Array{T,1},fmin::T,fmax::T,nf::Int,nt::Int,dz::T,dx::T,dt::T,ext::Int=10,atten_max::T=1.,flag=2)\n\n# This function solves the acoustic Helmholtz equation for a prescribed\n# source wavelet and range of frequencies. A complex-numbered attenuating\n# boundary is used to damp the boundary reflections. This code is intended\n# for simultaneous sources.\n#\n# INPUTS:     isz       - z-index for each source location\n#             isx       - x-index for each source location \n#             ot        - Activation time for each source\n#             vp        - Acoustic velocity model\n#             wav       - Source wavelet (time domain)\n#             fmin      - Minimum frequency to model\n#             fmax      - Maximum frequency to model\n#             nf        - Number of frequency bins; 'nf' must be greater than or equal to 'length(wav)' and 'nt'\n#             nt        - Number of time steps to perform modeling for\n#             dz        - Grid spacing in z-direction\n#             dx        - Grid spacing in x-direction\n#             dt        - Sampling interval (time step)\n#             ext       - Thickness (number of grid points) of absorbing boundary region\n#             atten_max - Maximum complex amplitude in the attenuating boundary layer\n#             flag      - Output frequency-domain data if flag==1, Output time-domain data if flag==2\n#\n# OUTPUTS:    u         - Solution to Helmhotz equation; stored as a 3D volume with dimensions (w,z,x) or (t,z,x)\n\n    nz = size(vp,1) + 2*ext\n    nx = size(vp,2) + 2*ext\n\n    L = Laplacian(nz,nx,dz,dx)\n    M = MassMatrix(vp,nz,nx,ext) .* Attenuation(nz,nx,ext,atten_max)\n\n    WAV = fft([wav;zeros(nf-length(wav))])\n    fs = 1/dt\n    df = fs/nf\n    faxis = fftshift(-fs/2:df:fs/2-df)\n    waxis = 2*pi*faxis\n\n    _,iwmin = findmin(abs(fmin-faxis))\n    _,iwmax = findmin(abs(fmax-faxis))\n    U = complex(zeros(nf,nz,nx))\n    for iw = iwmin:iwmax\n        w = waxis[iw]\n        H = L + w^2*M\n        s = Source(isz,isx,ot,WAV,waxis,w,nz,nx,ext)\n        U_tmp = H\\s\n        U_tmp = reshape(U_tmp,nz,nx)\n        U[iw,:,:] = U_tmp\n        U[nf-iw+2,:,:] = conj(U_tmp)\n    end\n\n    if flag==1\n        return U\n    elseif flag==2 \n        return real(ifft(U,1))[1:nt,ext+1:end-ext,ext+1:end-ext]\n    end\n\nend\n\n\n\n\n\nfunction Helmholtz{T<:AbstractFloat}(isz::Int,isx::Int,ot::T,vp::Array{T,2},wav::Array{T,1},fmin::T,fmax::T,nf::Int,nt::Int,dz::T,dx::T,dt::T,ext::Int=10,atten_max::T=1.;flag=2)\n\n# This function solves the acoustic Helmholtz equation for a prescribed\n# source wavelet and range of frequencies. A complex-numbered attenuating\n# boundary is used to damp the boundary reflections. This code is intended\n# for a single source.\n#\n# INPUTS:     isz       - z-index for source location\n#             isx       - x-index for source location \n#             ot        - Activation time for the source\n#             vp        - Acoustic velocity model\n#             wav       - Source wavelet (time domain)\n#             fmin      - Minimum frequency to model\n#             fmax      - Maximum frequency to model\n#             nf        - Number of frequency bins; 'nf' must be greater than or equal to 'length(wav)' and 'nt'\n#             nt        - Number of time steps to perform modeling for\n#             dz        - Grid spacing in z-direction\n#             dx        - Grid spacing in x-direction\n#             dt        - Sampling interval (time step)\n#             ext       - Thickness (number of grid points) of absorbing boundary region\n#             atten_max - Maximum complex amplitude in the attenuating boundary layer\n#             flag      - Output frequency-domain data if flag==1, Output time-domain data if flag==2\n#\n# OUTPUTS:    U         - Solution to Helmhotz equation; stored as a 3D volume with dimensions (w,z,x) or (t,z,x)\n#\n# Contributors: Landon Safron\n# Institution: University of Alberta\n# Date: March 1, 2017\n\n    nz = size(vp,1) + 2*ext\n    nx = size(vp,2) + 2*ext\n\n    L = Laplacian(nz,nx,dz,dx)\n    M = MassMatrix(vp,nz,nx,ext) .* Attenuation(nz,nx,ext,atten_max)\n\n    WAV = fft([wav;zeros(nf-length(wav))])\n    fs = 1/dt\n    df = fs/nf\n    faxis = fftshift(-fs/2:df:fs/2-df)\n    waxis = 2*pi*faxis\n\n    _,iwmin = findmin(abs(fmin-faxis))\n    _,iwmax = findmin(abs(fmax-faxis))\n    U = complex(zeros(nf,nz,nx))\n    for iw = iwmin:iwmax\n        w = waxis[iw]\n        H = L + w^2*M\n        s = Source(isz,isx,ot,WAV,waxis,w,nz,nx,ext)\n        U_tmp = H\\s\n        U_tmp = reshape(U_tmp,nz,nx)\n        U[iw,:,:] = U_tmp\n        U[nf-iw+2,:,:] = conj(U_tmp)\n    end\n\n    if flag==1\n        return U[:,ext+1:end-ext,ext+1:end-ext]\n    elseif flag==2 \n        return real(ifft(U,1))[1:nt,ext+1:end-ext,ext+1:end-ext]\n    end\n\nend\n\n\n\n", "meta": {"hexsha": "0d510190428eccaa05b496d99d9a75c00c1b1843", "size": 4831, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Modeling/Helmholtz.jl", "max_stars_repo_name": "lsafron/AcousticFWI.jl", "max_stars_repo_head_hexsha": "7ba478407b76faf7eef0c784289281ec7997e0d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-13T01:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-13T01:24:30.000Z", "max_issues_repo_path": "src/Modeling/Helmholtz.jl", "max_issues_repo_name": "lsafron/AcousticFWI.jl", "max_issues_repo_head_hexsha": "7ba478407b76faf7eef0c784289281ec7997e0d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Modeling/Helmholtz.jl", "max_forks_repo_name": "lsafron/AcousticFWI.jl", "max_forks_repo_head_hexsha": "7ba478407b76faf7eef0c784289281ec7997e0d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0393700787, "max_line_length": 204, "alphanum_fraction": 0.584351066, "num_tokens": 1447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7607140051583255}}
{"text": "# ======================================================================\n# Logarithmic norms of matrices (a.k.a matrix measures)\n#\n# Reference:\n#\n# C. Desoer and M. Vidyasagar, Feedback Systems: Input-Output Properties.\n# Philadelphia, PA: Society for Industrial and Applied Mathematics,\n# Jan. 2009, ser. Classics in Applied Mathematics.\n# ======================================================================\n\n# logarithmic norm (also known as matrix measure) for commonly used p-norms\nfunction logarithmic_norm(A::AbstractMatrix, p::Real=Inf)\n    if p == Inf\n        return logarithmic_norm_inf(A)\n    elseif p == 1\n        return logarithmic_norm_1(A)\n    elseif p == 2\n        return logarithmic_norm_2(A)\n    else\n        throw(ArgumentError(\"logarithmic norm only implemented for p = 1, 2, or Inf, got p = $p\"))\n    end\nend\n\n# max_j a_jj + ∑_{i ≠ j} |a_ij|\nfunction logarithmic_norm_1(A::AbstractMatrix{N}) where {N}\n    out = -Inf\n    @inbounds for j in 1:size(A, 2)\n        α = A[j, j]\n        for i in 1:size(A, 1)\n            if i ≠ j\n                α += abs(A[i, j])\n            end\n        end\n        if α > out\n            out = α\n        end\n    end\n    return out\nend\n\n# max_i a_ii + ∑_{j ≠ i} |a_ij|\nfunction logarithmic_norm_inf(A::AbstractMatrix{N}) where {N}\n    out = -Inf\n    @inbounds for i in 1:size(A, 1)\n        α = A[i, i]\n        for j in 1:size(A, 2)\n            if i ≠ j\n                α += abs(A[i, j])\n            end\n        end\n        if α > out\n            out = α\n        end\n    end\n    return out\nend\n\n# max_j  1/2 * λⱼ(A + A^T)\nfunction logarithmic_norm_2(A::AbstractMatrix)\n    B = A + A'\n    λ = eigvals(B)\n    return maximum(λ) / 2\nend\n\n# ========================================================================\n# Specialized functions on LazySets.Arrays.SingleEntryVector\n# TODO refactor to LazySets.jl\n# ========================================================================\n\n# difference between single entry vectors (SEV); it is type unstable because\n# it may return either a SEV or a regular Vector depending on the indices\n# but it is much faster than the fallback if the indices match\nfunction minus(e1::SingleEntryVector{N}, e2::SingleEntryVector{N}) where {N}\n    e1.n == e2.n || throw(DimensionMismatch(\"dimensions must match, but they are $(length(e1)) and $(length(e2)) respectively\"))\n\n    if e1.i == e2.i\n        return SingleEntryVector(e1.i, e1.n, e1.v - e2.v)\n    else\n        out = zeros(N, e1.n)\n        @inbounds begin\n            out[e1.i] = e1.v\n            out[e2.i] = -e2.v\n        end\n        return out\n    end\nend\n\n# addition between single entry vectors (SEV); it is type unstable because\n# it may return either a SEV or a regular Vector depending on the indices\n# but it is much faster than the fallback if the indices match\nfunction plus(e1::SingleEntryVector{N}, e2::SingleEntryVector{N}) where {N}\n    e1.n == e2.n || throw(DimensionMismatch(\"dimensions must match, but they are $(length(e1)) and $(length(e2)) respectively\"))\n\n    if e1.i == e2.i\n        return SingleEntryVector(e1.i, e1.n, e1.v + e2.v)\n    else\n        out = zeros(N, e1.n)\n        @inbounds begin\n            out[e1.i] = e1.v\n            out[e2.i] = e2.v\n        end\n        return out\n    end\nend\n\n# norm of the difference of two SEV ||x - y|| in the (vector p norm)\nfunction normdiff(e1::SingleEntryVector{N}, e2::SingleEntryVector{N}, p::Real=2) where {N}\n    e1.n == e2.n || throw(DimensionMismatch(\"dimensions must match, but they are $(length(e1)) and $(length(e2)) respectively\"))\n\n    if e1.i == e2.i\n        δ = e1.v - e2.v\n        return abs(δ)\n\n    else\n        a = abs(e1.v)\n        b = abs(e2.v)\n        if isinf(p)\n            return max(a, b)\n        else\n            s = a^p + b^p\n            return s^(1/p)\n        end\n    end\nend\n\n# fallback\nfunction normdiff(x::AbstractVector{N}, y::AbstractVector{N}, p::Real=2) where {N}\n    norm(x - y, p)\nend\n", "meta": {"hexsha": "53471c0f65f71b5fc8dddd566a85f43cbcdbea11", "size": 3918, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Flowpipes/arrayops.jl", "max_stars_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_stars_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2020-03-30T16:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:26:48.000Z", "max_issues_repo_path": "src/Flowpipes/arrayops.jl", "max_issues_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_issues_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 258, "max_issues_repo_issues_event_min_datetime": "2020-03-30T14:13:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T17:07:04.000Z", "max_forks_repo_path": "src/Flowpipes/arrayops.jl", "max_forks_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_forks_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-04-23T03:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T23:11:32.000Z", "avg_line_length": 30.1384615385, "max_line_length": 128, "alphanum_fraction": 0.5515569168, "num_tokens": 1108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7607140045173975}}
{"text": "function unspliced(τ, u₀, α, β)\n    expᵘ = exp(-β * τ)\n    u₀ * expᵘ + α / β * (1 - expᵘ)\nend\n\nfunction spliced(τ, s₀, u₀, α, β, γ)\n    c = (α - u₀ * β) / (γ - β)\n    expᵘ = exp(-β * τ)\n    expˢ = exp(-γ * τ)\n    s₀ * expˢ + α / γ * (1 - expˢ) + c * (expˢ - expᵘ)\nend\n\nfunction mRNA(τ, u₀, s₀, α, β, γ)\n    expᵘ, expˢ = exp(-β * τ), exp(-γ * τ)\n    expᵘˢ = (α - u₀ * β) * inv(γ - β) * (expˢ - expᵘ)\n    u = u₀ * expᵘ + α / β * (1 - expᵘ)\n    s = s₀ * expˢ + α / γ * (1 - expˢ) + expᵘˢ\n    u, s\nend\n", "meta": {"hexsha": "42ca8de587163b24dacc3b0a1afc12a2b7fd0473", "size": 498, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/model.jl", "max_stars_repo_name": "yuehhua/SnowyOwl.jl", "max_stars_repo_head_hexsha": "0ca35a190b508ae1b5496e873ade63d6731c3633", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/model.jl", "max_issues_repo_name": "yuehhua/SnowyOwl.jl", "max_issues_repo_head_hexsha": "0ca35a190b508ae1b5496e873ade63d6731c3633", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-02-16T14:40:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T05:24:51.000Z", "max_forks_repo_path": "src/model.jl", "max_forks_repo_name": "yuehhua/SnowyOwl.jl", "max_forks_repo_head_hexsha": "0ca35a190b508ae1b5496e873ade63d6731c3633", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9, "max_line_length": 54, "alphanum_fraction": 0.437751004, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900508, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7607109637798275}}
{"text": "using Plots, LaTeXStrings, Statistics\n\nfunction Deposition(;len, tot_time, time_steps)\n    Time = exp.(0:tot_time/(time_steps-1):tot_time)\n    surf = [0 for i=1:len]\n    VarList = [0.0 for i=1:time_steps]\n    for n in 1:time_steps\n        randsurf = rand(1:len,floor(Int,Time[n]*1000 + 1000))\n        for i in randsurf\n            surf[i] += 1\n        end\n        VarList[n] = std(surf)\n    end\n    return Time, VarList\nend\n\nfunction Linear_fit(;len, tot_time, time_steps)\n    A = [hcat(log.(Time)) reshape(ones(time_steps), time_steps, 1)]\n    b = reshape(log.(VarList), time_steps, 1)\n    line = (A \\ b)\n    x = 0:tot_time\n    y = x .* line[1] .+ line[2]\n    return x, y, line\nend\n\nParameters = Dict(\n                :len => 200,\n                :tot_time => 10,\n                :time_steps => 20\n                    )\n\nTime, VarList = Deposition(;Parameters...)\nX, Y, Line = Linear_fit(;Parameters...)\n\ntheme(:dark)\ngr()\n\nscatter(log.(Time),log.(VarList),\n    xlabel= L\"Log\\ Time\",\n    ylabel= L\"Log\\ W_{(t)}\",\n    title= L\"Log-Log\\ Plot\\ of\\ ~W_{(t)}-Time~\",\n    label = L\"Data\\ point\")\nplot!(X,Y,label = L\"y = %$(round(Line[1],digits= 2))x + %$(round(Line[2],digits= 2))\")\nsavefig(\"C:\\\\Users\\\\Yaghoub\\\\Documents\\\\GitHub\\\\Ballistic-Deposition\\\\Deposition\\\\Random-Ballistic-Deposition\\\\Fig\\\\log-log.png\")\n", "meta": {"hexsha": "85cf4ebabe435c3ecba8a7987c81718e4633a968", "size": 1308, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Deposition/Random-Ballistic-Deposition/Random-Ballistic-Deposition-Logarithmic.jl", "max_stars_repo_name": "shahmari/Ballistic-Deposition", "max_stars_repo_head_hexsha": "0d6e52c2320cc023e2c351205236c82e371a71d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-29T12:35:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T12:35:39.000Z", "max_issues_repo_path": "Deposition/Random-Ballistic-Deposition/Random-Ballistic-Deposition-Logarithmic.jl", "max_issues_repo_name": "shahmari/Ballistic-Deposition", "max_issues_repo_head_hexsha": "0d6e52c2320cc023e2c351205236c82e371a71d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Deposition/Random-Ballistic-Deposition/Random-Ballistic-Deposition-Logarithmic.jl", "max_forks_repo_name": "shahmari/Ballistic-Deposition", "max_forks_repo_head_hexsha": "0d6e52c2320cc023e2c351205236c82e371a71d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0666666667, "max_line_length": 129, "alphanum_fraction": 0.5833333333, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7606592787334281}}
{"text": "function get_dft_interval(max_val::Float64,N::Int64)\r\n    #Returns the interval over which we obtain the Fourier transform\r\n\t(-N÷2:N-1-N÷2)*(2*max_val/N)\r\nend\r\n\r\nfunction get_reciprocal_dft_interval(max_val::Float64,N::Int64)\r\n    #Returns the interval over which we have to sample our function to perform the DFT\r\n\t(-N÷2:N-1-N÷2)*(π/max_val)\r\nend\r\n\r\nfunction get_fourier_transform(k_max::Float64,N::Int64,ψ0)\r\n\t#Calculates the Fourier transform of the given initial profile ψ0\r\n\r\n    ks = get_dft_interval(k_max,N)\r\n    rs = get_reciprocal_dft_interval(k_max,N)\r\n\r\n\t#This is a matrix containing the ψ0s\r\n\tψ0s = convert(Matrix{ComplexF64},[ ψ0(x,y) for x in rs, y in rs])\r\n\r\n\t#Then, we calculate the Fourier transform of ψ, which returns a matrix\r\n\tϕs =  (0.5*π/k_max^2)*ifftshift( fft( fftshift(  ifftshift(fft(fftshift(ψ0s,1),1),1)  ,2),2),2)\r\n    \r\n\t#Now, we interpolate this matrix, to be able to calculate the function at an arbitrary point.\r\n\tCubicSplineInterpolation( (ks , ks),ϕs,extrapolation_bc=0.0)\r\nend\r\n\r\nfunction display_fourier_transform(plot_range::Float64,plot_N::Int64,clim::Float64,ϕ)\r\n\t#Displays the fourier transform ϕ. It is useful to see if the chosen parameters are adequate\r\n\tks = LinRange(-plot_range,plot_range,plot_N)\r\n\r\n\tI = [ real(ϕ(kx,ky)*conj(ϕ(kx,ky))) for ky in ks, kx in ks ]\r\n\r\n\theatmap(ks,ks,I,clims=(0,clim),aspect_ratio=:equal,\r\n\txlabel=L\"k_x\",ylabel=L\"k_y\",xlims=(-plot_range,plot_range),ylims=(-plot_range,plot_range),\r\n\ttitle=\"Fourier transform of initial profile\")\r\nend\r\n\r\nfunction propagate_beam(r_max::Float64,N::Int64,z::Float64,ϕ)\r\n\t#Propagates a beam to a distance z given the fourier transform of its initial profile\r\n\r\n\trs = get_dft_interval(r_max,N)\r\n    ks = get_reciprocal_dft_interval(r_max,N)\r\n\t\t\t\r\n\ts = zeros(ComplexF64,N,N)\r\n\r\n\tThreads.@threads for n in 1:N\r\n\t\tThreads.@threads for m in 1:N\r\n\t\t\ts[n,m] = ϕ(ks[m],ks[n])*exp(-im*z*(ks[n]^2+ks[m]^2)/2)\r\n\t\tend\r\n\tend\r\n\r\n\t( 0.5*π/r_max^2 )*ifftshift( bfft( fftshift(  ifftshift(bfft(fftshift(s,1),1),1)  ,2),2),2)\r\nend\r\n\r\nfunction propagate_beam(r_max::Float64,N::Int64,z::Float64,ϕ,bplan1,bplan2)\r\n\t#Same as before, but accepts plans for the FFT.\r\n\r\n\trs = get_dft_interval(r_max,N)\r\n    ks = get_reciprocal_dft_interval(r_max,N)\r\n\t\t\t\r\n\ts = zeros(ComplexF64,N,N)\r\n\t\r\n\tThreads.@threads for n in 1:N\r\n\t\tThreads.@threads for m in 1:N\r\n\t\t\ts[n,m] = ϕ(ks[m],ks[n])*exp(-im*z*(ks[n]^2+ks[m]^2)/2)\r\n\t\tend\r\n\tend\r\n\r\n\t( 0.5*π/r_max^2 )*ifftshift(bplan2*fftshift(ifftshift(bplan1*fftshift(s,1),1),2),2)\r\nend\r\n\r\nfunction decrease_size(a,rs,I)\r\n\t#This function decreses the size of a range and corresponding intensities. \r\n\t#It is analogous to setting xlims=(-a,a), ylims=(-a,a) but somehow is faster\r\n\tK=1\r\n\tfor k in eachindex(rs)\r\n\t\tif rs[k]>-a\r\n\t\t\tK = k\r\n\t\t\tbreak\r\n\t\tend\r\n\tend\r\n\trs[ K:(length(rs)+1-K) ],I[K:(length(rs)+1-K),K:(length(rs)+1-K)]\r\nend;\r\n\r\nfunction display_beam(r_max::Float64,N::Int64,z::Float64,plot_range::Float64,clim::Float64,ϕ)\r\n\t#Displays a propageted beam\r\n\trs = get_dft_interval(r_max,N)\r\n\tψs = propagate_beam(r_max,N,z,ϕ)\r\n\r\n\tI = real(ψs.*conj(ψs))\r\n\r\n\tdrs,dI = decrease_size(plot_range,rs,I)\r\n\r\n\theatmap(drs,drs,dI,clims=(0,clim),aspect_ratio=:equal,title=\"z=\"*(@sprintf \"%.2f\" z),xlabel=L\"x\",ylabel=L\"y\",xlims=(-plot_range,plot_range),ylims=(-plot_range,plot_range))\r\nend\r\n\r\nfunction animate_beam(r_max::Float64,N::Int64,zmax::Float64,\r\n\tplot_range::Float64,clim::Float64,ϕ,fps::Int64,nframes::Int64,file_name::String)\r\n\t#Animates a beam propagation\r\n\t#The file_name should end in .gif\r\n\t\r\n\trs = get_dft_interval(r_max,N)\r\n\tks = get_reciprocal_dft_interval(r_max,N)\r\n\r\n\tplan1 = plan_bfft( zeros(ComplexF64, N,N ) , 1)\r\n\tplan2 = plan_bfft( zeros(ComplexF64, N,N ) , 2)\r\n\r\n\tanim = @animate for z in LinRange(0,zmax,nframes)\r\n\t\tψs = propagate_beam(r_max,N,z,ϕ,plan1,plan2)\r\n\r\n\t\tI = real(ψs.*conj(ψs))\r\n\r\n\t\tdrs,dI = decrease_size(plot_range,rs,I)\r\n\r\n\t\theatmap(drs,drs,dI,clims=(0,clim),aspect_ratio=:equal,\r\n\t\ttitle=L\"z=\"*(@sprintf \"%.2f\" z),xlabel=L\"x\",ylabel=L\"y\",\r\n\t\txlims=(-plot_range,plot_range),size=(1200,900),labelfontsize=20,titlefontsize=20,tickfontsize=14)\r\n\tend\r\n\r\n\tgif(anim,file_name,fps=fps)\r\nend;\r\n", "meta": {"hexsha": "3931bd3f46a9bc4f63289a786264ac16b3966913", "size": 4126, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Propagation.jl", "max_stars_repo_name": "marcsgil/ParaxialBeamPropagation.jl", "max_stars_repo_head_hexsha": "fc13356950902a43b0eaa4adc115fe9e358044f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Propagation.jl", "max_issues_repo_name": "marcsgil/ParaxialBeamPropagation.jl", "max_issues_repo_head_hexsha": "fc13356950902a43b0eaa4adc115fe9e358044f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Propagation.jl", "max_forks_repo_name": "marcsgil/ParaxialBeamPropagation.jl", "max_forks_repo_head_hexsha": "fc13356950902a43b0eaa4adc115fe9e358044f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8196721311, "max_line_length": 173, "alphanum_fraction": 0.6934076587, "num_tokens": 1414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176863577751, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7606592689833955}}
{"text": "\"\"\"\n\tMMC(μ, λ, c)\n\nTạo mô hình M/M/c\n\"\"\"\nstruct MMC{T} <: AbstractMMCK\n\tμ::Union{T, Real}\n\tλ::Union{T, Real}\n\tc::Union{T, Integer}\n\tr::Union{T, Real}\n\tρ::Union{T, Real}\n\tfunction MMC(λ, μ, c)\n\t\tr = λ / μ\n\t\tρ = r / c\n\t\tT = Union{typeof(μ), typeof(λ)}\n\t\tnew{T}(μ, λ, c, r, ρ) \n\tend\nend\n\nfunction pn(m::MMC, n::Integer)\n\tμ = m.μ\n\tλ = m.λ\n\tc = m.c\n\tr = m.r\n\tρ = m.ρ\n\tif n == 0\n\t\td1 = (c * r^c) / factorial(c) / (c - r)\n\t\td2 = sum(r^i / factorial(i) for i = 0:c-1)\n\t\t1 / (d1 + d2)\n\telseif n < c\n\t\tpn(m, 0) * r^n / factorial(n)\n\telse pn(m, 0) * r^n / factorial(c) / c^(n-c)\n\tend\nend\n\nfunction Lq(m::MMC)\n\tr = m.r\n\tρ = m.ρ\n\tc = m.c\n\tpn(m, 0) * r^c * ρ / factorial(m.c) / (1 - ρ)^2\nend\n\nfunction Wq(m::MMC)\n\tLq(m) / m.λ\nend\n\nfunction W(m::MMC)\n\tWq(m) + 1 / m.μ\nend\n\nfunction L(m::MMC)\n\tLq(m) + m.r\nend\n", "meta": {"hexsha": "c6b44669a412b59152c3430a33123a9107c6cfa8", "size": 794, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mmc.jl", "max_stars_repo_name": "ndgnuh/MarkovAndQueueModels.jl", "max_stars_repo_head_hexsha": "30d0c3ecb9da61a466b95b791e8dbefc854ed38f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mmc.jl", "max_issues_repo_name": "ndgnuh/MarkovAndQueueModels.jl", "max_issues_repo_head_hexsha": "30d0c3ecb9da61a466b95b791e8dbefc854ed38f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mmc.jl", "max_forks_repo_name": "ndgnuh/MarkovAndQueueModels.jl", "max_forks_repo_head_hexsha": "30d0c3ecb9da61a466b95b791e8dbefc854ed38f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.7037037037, "max_line_length": 48, "alphanum_fraction": 0.5100755668, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7606592635936307}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.21\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ f493fdb0-022f-11eb-34a6-4b133c23a71a\nusing OrdinaryDiffEq\n\n# ╔═╡ c803fe10-0231-11eb-1f84-dbe43fd97eb4\nusing Plots\n\n# ╔═╡ be8523c0-0239-11eb-0439-592e370c5618\nusing LaTeXStrings #rotulos de las figuras bonitos\n\n# ╔═╡ 5fe018a0-023b-11eb-1e69-d59b562edc9b\nusing Symbolics\n#alternativamente también se puede usar SymEngine pero hay que definir el jacobiano a mano\n\n# ╔═╡ 1c0442a0-a993-11eb-1b2d-55eb8b868dc7\n#algunas definiciones útiles\nbegin\n\tusing Latexify  # si no lo tenéis hay que instalarlo\n    Base.show(io::IO, ::MIME\"text/html\", x::Symbolics.Num) = print(io, latexify(x))\n    Base.show(io::IO, ::MIME\"text/html\", x::Symbolics.Symbolic) = print(io, latexify(x))\n    Base.show(io::IO, ::MIME\"text/html\", x::Symbolics.Vector{Equation}) = print(io, latexify(x))\n    Base.show(io::IO, ::MIME\"text/html\", x::Symbolics.AbstractArray{Num}) = print(io, latexify(x))\n\t\n\tdiff(f,variable) = expand_derivatives(Symbolics.derivative(f,variable))\n\tsubs(expr,dict) = substitute(expr, dict)\n\texpand(x) = simplify(x;polynorm=true) #En ciertas versiones es expand = true\n\tsolve_for(ecuacion,variable) = Symbolics.solve_for(ecuacion, variable)\n\tjacobian(f,x) = Symbolics.jacobian(f,x)\nend\n\n\n# ╔═╡ 183a6460-a9ca-11eb-340e-872e08f29a9e\nusing LinearAlgebra\n\n# ╔═╡ c900ad60-095f-11eb-3d18-9f187abdb9b3\nusing PlutoUI\n\n# ╔═╡ 5c4af6e0-022e-11eb-152f-2153b9b672c1\nmd\"\"\"# Ejemplos de sistemas a controlar \n\nPrimer ejemplo\n\n$$J \\ddot \\theta + MgLsin(\\theta)=u$$\n\n\"\"\"\n\n# ╔═╡ 6b1fd530-0a28-11eb-1142-47afd1798c3e\nhtml\"<button onclick=present()>Present</button>\"\n\n# ╔═╡ 85c03440-0274-11eb-3c81-514259334750\nmd\"## Simulamos y pintamos\"\n\n# ╔═╡ e3e9d0a0-022c-11eb-04ba-97dcb9ba908a\nmd\"\"\"# Grado relativo \nLa idea es \"derivar hasta que sale u\" \n\"\"\"\n\n# ╔═╡ 6831eb02-023b-11eb-0842-fbe8f8eb8937\nmd\"Vamos a usar cálculo simbólico\"\n\n# ╔═╡ 3ff84c30-0248-11eb-33ba-f99304ee8672\nbegin\n\tD=x1=x2=t=u=J=M=g=L=0  #eso es cosa de pluto y las macros (si no no es necesario)\n\t@variables D x1 x2 t u J M g L  # =symbols(\"D,x1,x2,t,u,J, M, g, L\")\nend\n\n# ╔═╡ 6d535e50-a99a-11eb-08c1-4d98301e53b3\nbegin\n\t#escribir las ecuaciones simbólicas\n\tx=[x1;x2]\n\tdx1=x2\n\tdx2=-M*g*L/J*sin(x1)+u/J\n\tdx=[dx1;dx2]\nend\n\n# ╔═╡ 5525d1a0-a9c7-11eb-1de0-1700c9c20460\ny=x1\n\n# ╔═╡ 65893910-a9c7-11eb-2f9f-ebadf375cdbc\ndy=diff(y,x1)*dx1+diff(y,x2)*dx2\n\n# ╔═╡ a0571620-a9c7-11eb-070f-297fa9e406b2\nddy=diff(dy,x1)*dx1+diff(dy,x2)*dx2\n\n# ╔═╡ 39ce8af0-023d-11eb-3178-857433b369ae\nmd\"ya aparece u --> grado relativo 2\"\n\n# ╔═╡ 4c478bf0-023d-11eb-0dce-439d408010fa\nmd\"¿Es repetitivo podemos hacerlo en general?\n hagamos una **función**\"\n\n# ╔═╡ b7e08f60-023d-11eb-13cb-ad5285e900d8\nbegin\n\tfunction derivada(funcion,variables,derivadas)\n\t\td=0\n\t\tfor i=1:length(variables)\n\t\t\td=d+diff(funcion,variables[i])*derivadas[i]\n\t\tend\n\t\treturn d\n\tend\n\t\n\tfunction derivada(f,x,dx,n) #multiple distpach #esto es nuevo\n\t\td=f\n\t\tfor i=1:n\n\t\t\td=derivada(d,x,dx)\n\t\tend\n\t\treturn d\n\tend\nend\n\n# ╔═╡ 697f24d0-a99a-11eb-26e6-a749fb04cb0f\n#usar la función\nder=derivada(y,x,dx,2)\n\n# ╔═╡ 9ecc5ff0-022d-11eb-3715-51831818d04f\nmd\"\"\"# Cambio de variables\nvamos a cambiar u por v para ello despejamos de\n$$y^{(\\gamma)}=v$$\n\"\"\"\n\n# ╔═╡ 65ad8360-a99a-11eb-3764-aded1015107e\nbegin\n\t#definir v\n\tv=0\n\t@variables v\nend\n\n# ╔═╡ 4b753d20-a9c8-11eb-320a-d58ec5e3c431\necuación=der~v\n\n# ╔═╡ 6e31c180-a9c8-11eb-3893-f55415fa4fad\nuc=solve_for(ecuación,u)\n\n# ╔═╡ 561e07e2-0250-11eb-1380-4b5dfa861cd6\nmd\"vamos a ver que lo hemos hecho bien\"\n\n# ╔═╡ 64db3f40-a99a-11eb-01df-d3ca4846ca33\n#sustituir u en la derivada y ver que sale v\nexpand(subs(der,u=>uc))\n\n# ╔═╡ de497f50-0250-11eb-028e-ffe56cf1ba45\nmd\"La idea es controlar un nuevo sistema:\n\n$$\\dot z_1=z_2$$\n\n$$...$$\n\n$$\\dot z_{\\gamma}=v$$\n\n$$y=z_1$$\n\"\n\n# ╔═╡ c2f97c40-a99a-11eb-30e7-359effec0a1d\n#define z1 y su derivada z2\nz1=y\n\n# ╔═╡ 85e1f1f0-a9c9-11eb-2a97-1944f7fcb34b\nz2=derivada(y,x,dx)\n\n# ╔═╡ 0db8c9c0-0252-11eb-199c-2d69997c6769\nmd\"veamos que lo hemos hecho bien y la derivada es la corecta\"\n\n# ╔═╡ dd56c0c2-a99a-11eb-0c87-8f8e2c6321a8\nexpand(subs(derivada(z2,x,dx), u=>uc))\n\n# ╔═╡ 72e4e740-022d-11eb-3a63-31023b9d464f\nmd\"\"\"# Difeomorfismo\nA partir de ahora controlaremos las **z** pero *OJO* que nuestro objetivo son las **x** \n\n¿Al controlar z **se controla x**?\n\n-Si se puede despejar x(x) entonces si-->difeomorfismo (al menos local)\n\nPara verlo calculamos el jacobiano y vemos si es singular\n\n$$\\begin{pmatrix}\n\n\\frac{\\partial z_1}{\\partial x_1}... & \\frac{\\partial z_1}{\\partial x_n} \\\\\n...\\\\\n\\frac{\\partial z_n}{\\partial x_1}... & \\frac{\\partial z_n}{\\partial x_n}\n\n\\end{pmatrix}$$\n\n\"\"\"\n\n# ╔═╡ f1e0ee80-a99a-11eb-0c06-85f8d7086aac\n#definir el vector z, calcular el jacobiano y derivar\nz=[z1,z2]\n\n# ╔═╡ 03abf0e0-a9ca-11eb-339c-5599c951871c\njac=jacobian(z,x)\n\n# ╔═╡ 2d9109e0-a9ca-11eb-08a5-7596eee9e4b2\ndet(jac)\n\n# ╔═╡ 9ec274e0-022d-11eb-085a-7907b8f1eb93\nmd\"\"\"# Estabilización\nEl sitema en las zs es lineal\nPara estabilizar la dinámica se realimentan negativamente las zs con ganancias\n$$v=-d_0z_1-d_1z_2-...-d_{\\gamma-1}z_{\\gamma}$$\n\nRecordemos que $$\\dot z_1=z_2$$, $$\\ddot z_1= \\dot z_2=z_3$$... \n$$z_1^{(\\gamma)}=v=-d_0z_1-d_1z_2-...-d_{\\gamma-1}z_{\\gamma}$$\n\n$$z_1^{(\\gamma)} +d_{\\gamma-1}z^{\\gamma-1}+...+d_1\\dot z+ d_0z  =0$$\n\nQue es un sistema lineal con polinomio característico\n\n$$s^{(\\gamma)} +d_{\\gamma-1}s+...+d_1s+ d_0  =0$$\n\n## Elección de polos\n\nHay que hacer que el polinomio sea hurwitz\nLo más fácil es constuirlo, si queremos unos polos $p_1$, $p_2$... $p_{\\gamma}$ podemos hacer que el polinomio sea \n\n$$(s-p_1)(s-p_2)...(s-p_{\\gamma})$$\n\"\"\"\n\n\n# ╔═╡ aed8d350-0265-11eb-1223-1dd0651632b6\nbegin\n\t#expandir (s-p1)*(s-p2)) y comparar con lo deseado\n\tp1=p2=-1\n\ts=0\n\t@variables s\n\texpand((s-p1)*(s-p2))\nend\n\n# ╔═╡ 0d736c40-0266-11eb-3433-ad75c1617314\nmd\"Entonces $d_0$ y $d_1$ son 1 y 2 ;)\"\n\n# ╔═╡ 454272d0-a9cb-11eb-36db-ffb885a95a52\nstring(uc)\n\n# ╔═╡ f54ff5b2-0266-11eb-1df3-49f3c95729c7\nmd\"Ahora lo ponemos todo junto\"\n\n# ╔═╡ 2814f040-0267-11eb-3f4d-2933c0c3528a\nfunction control_1_estabilizacion(x,p,t)\n\tx1,x2=x\n\tM,g,L,J=p  \n\td0=1\n\td1=2\n\t\n\ty=x1 #o si lo preferís z1\n\tdy=x2 #z2\n\tv=-d0*y-d1*dy\n\tu=J*v + L*M*g*sin(x1)\n\treturn u\nend\t\n\n# ╔═╡ 3b125190-0269-11eb-2473-33cbb7451779\nmd\"Si queremos podemos sustituir todo **ojo a veces no compensa** (por que queda muy largo y difícil de depurar) en este caso si\"\n\n# ╔═╡ 639dce00-0269-11eb-191e-d16a91f3bcf9\nu_sustituido=subs(uc,[v=>-2*y-3*dy,L=>1,M=>1,g=>1,J=>1])\n\n# ╔═╡ e0b21ca0-0a2c-11eb-0e50-efa6c355e7c5\nmd\"Pero **ojo** se pierde la interpretación física de lo que hace el control\"\n\n# ╔═╡ f162f3f0-022d-11eb-30d9-55fb6e39c8c0\nmd\"\"\"# Seguimiento\nUna vez linealizado seguir una referencia es fácil, si definimos errores\n\n$$e_0=y_r-y$$\n\n$$\\dot e_0= \\dot y_r - \\dot y = e_1$$\n\n...\n\n$$e_0^{(\\gamma)}=y_r^{(\\gamma)} - v$$\n\nEs todo igual pero añadiendo $y_r$ y con el signo contrario (aparece -v en vez de v) es decir:\n\n$$v=d_0e_0+d_1e_1+...+d_{\\gamma-1}e_{\\gamma-1} + y_r^{(\\gamma)}$$\n\n**OJO a la notación** no solo cambian los signos sino que *los índices ahora están \"bien\"* ya que $y=e_0$ no como antes que era $z_1$\n\"\"\"\n\n# ╔═╡ a7745f70-026b-11eb-1abe-d1944165d231\nfunction referencia_1_a(t)\n\tyr=sin(t)\n\tdyr=cos(t)\n\tddyr=-sin(t)\n\treturn [yr,dyr,ddyr]\nend\n\n# ╔═╡ a0e6f960-026b-11eb-23c9-410e6d61c4a1\nfunction control_1_seguimiento(x,p,t)\n\tx1,x2=x\n\tyr,dyr,ddyr=referencia_1_a(t)\n\t\n\tM,g,L,J=p\n\t\n\td0=2\n\td1=3\n\t\n\ty=x1\n\tdy=x2\n\t\n\te0=yr-y #esto es lo nuevo\n\te1=dyr-dy\n\tv=d0*e0 + d1*e1 + ddyr #y aquí también aparece la referencia y cambian los signos\n\t#v=-d0*y-d1*dy esto es lo de antes \n\t#v=-d0*z1-d1*z2 o en términos de las zetas\n\t\n\t\n\tu=J*(v + L*M*g*sin(x1)/J)\n\treturn u\nend\t\n\n# ╔═╡ 506a20d0-026f-11eb-2bde-f94724bd27f3\nbegin\n\t#control_1(x,p,t)=0\n\t#referencia_1(t)=0\n\t\n\t#control_1=control_1_estabilizacion\n\t\t\n\tcontrol_1=control_1_seguimiento\n\treferencia_1=referencia_1_a\nend\n\n# ╔═╡ 85c0d350-022e-11eb-0873-c118ffde014c\nfunction derivadas_ejemplo1(x,p,t)\n\tx1,x2=x\n\tM,g,L,J=p\n\tu=control_1(x,p,t)#calculamos el control\n\tdx1=x2\n    dx2=-M*g*L/J*sin(x1)+u/J\n\tdx=[dx1 dx2] #no hace falta return dx\nend\n\n# ╔═╡ 922bccde-022d-11eb-17f2-270aae61f923\nmd\"\"\"# Dinámica cero\nEl ejemplo anterior funciona muy bien por dos motivos:\n1) Al derivar obtengo tantos estados como tenía antes (grado relativo máximo)\n2) El cambio de variabes de los estados a las derivadas de y era invertible (difeomorfismo)\nEso significa que controlar $y$ y sus derivadas $y, \\dot y ... y^{(\\gamma)}$ es lo mismo que controlar $x_1...x_\\gamma$.\n\nPero ¿y si no es así? ¿Qué pasa si u aparece \"demasiado pronto\"?\n\n\"\"\"\n\n# ╔═╡ cc0e02e2-04c9-11eb-2e08-b906aaec3959\nmd\"\"\"# Otro ejemplo\n\nSegundo ejemplo\n\n$$\\dot x_1=-ax_1 + e^{2x_2}u$$\n$$\\dot x_2=2x_1x_2 +sin(x_2) + \\frac{u}{2} $$\n$$\\dot x_3=2x_2$$\n$$y=x_3$$\n\"\"\"\n\n# ╔═╡ 8839fb60-095a-11eb-063e-85fd960ea83a\nmd\"Ya sabemos hacerlo, vamos al grano\"\n\n# ╔═╡ 54523da0-0958-11eb-2730-cbef0823f684\nbegin\n\ta=x3=0\n\t@variables a x3\n\t#copia de las ecuaciones poniendo Bs para no pisar variables anteriores\n\tdxb1=-x1 + exp(2x2)*u\n    dxb2=2x1*x2 +sin(x2) + u/2\n\tdxb3=2x2\t\n\tdxb=[dxb1 dxb2 dxb3]\n\t#estados y salida\n\txb=[x1;x2;x3]\n\tyb=x3\nend\n\n# ╔═╡ 2a98e6e0-a227-11eb-026a-bb5831f344bb\nlet\n\tx0 = [0.1 0.1]\n\tparametros=[1 1 1 1] # una g un poco rara ¿no?\n\ttspan = (0.0,10.0)\n\tprob = ODEProblem(derivadas_ejemplo1,x0,tspan,parametros);\n\tsol = solve(prob,Tsit5());\n\t\n\t# Salida y referencia\n\tfig1=plot(sol,vars=(0,1), xaxis=L\"t\",yaxis=L\"y(t)\",label=L\"y(t)\")\n\t#referencia, x1 no se usa para nada pero espera que le pases algún estado\n\tfig1=plot!(fig1,sol,vars=( (t,x1)->(t,referencia_1(t)[1]) , 0, 1 ), \t\t\t\t\tlabel=L\"y_r\", linestyle=[:dot], linewidth=2) \n\t\t\n\t#Pinto los estados, si no quiero etiquetasp1=\n\tfig2=plot(sol, xaxis=\"t\",yaxis=L\"x(t)\", label=:none)\n\t#fig2=plot(sol,vars=(0,1), xaxis=L\"t\",yaxis=L\"x(t)\",label=L\"x_1\")\n\t#fig2=plot!(sol,vars=(0,2), ,label=L\"x_2\")\n\t    \n\t#Señal de control, u no se guarda, hay que recalcularlo\n\tfig3=plot(sol, vars=((t,x1,x2)->(t,control_1([x1,x2],parametros,t)),0, 1, 2),\n\t\t    xaxis=L\"t\",yaxis=L\"u(t)\",legend=false)\n\tl = @layout [a ; b ; c]\n\tplot(fig1,fig2,fig3, layout=l)\nend\n\n# ╔═╡ 0610d2ee-0958-11eb-2490-19e0efcd3996\ndyb=derivada(yb,xb,dxb,1)\n\n# ╔═╡ 52eade10-095b-11eb-0717-a9686481d875\nddyb=expand(derivada(yb,xb,dxb,2))\n\n# ╔═╡ 5c70004e-095b-11eb-0068-89e38689515b\nmd\"\"\"El grado relativo es 2, pero hay tres estados... *ups*\n\nEl jacobiano es obvio que es singular (2x3)\n\"\"\"\n\n# ╔═╡ ab5f1de0-0960-11eb-2cf6-414898fd1323\njacobian([yb;dyb],xb)\n\n# ╔═╡ c7d09f80-0a28-11eb-3548-11dbb05bbbbb\nmd\"\"\"Vamos a seguir *como si nada* a ver que pasa...\n\"\"\"\n\n# ╔═╡ 77f78c80-a997-11eb-0b80-8da3a424a52f\nstring(solve_for(ddyb~v,u))\n\n# ╔═╡ 706b0500-0a2d-11eb-023e-1de0809fe6cf\nreferencia_2(t)=0*referencia_1_a(t)\n\n# ╔═╡ c8abde00-095c-11eb-237c-a9fd2bd95b8a\nfunction control_2(x,p,t)\n\tx1,x2,x3=x\n\t\n\tyr,dyr,ddyr=referencia_2(t) #defindia más abajo\n\t\n\td0=2\n\td1=3\n\t\n\ty=x3\n\tdy=2*x2\n\t\n\te0=yr-y\n\te1=dyr-dy\n\t\n\tv=d0*e0 + d1*e1 + ddyr\n\t\n\tu= v - 2*sin(x2) - 4*x1*x2\n\treturn u\nend\t\n\n# ╔═╡ 97e9d100-04ca-11eb-07ea-3f5f5addbc45\nfunction derivadas_ejemplo2(x,p,t)\n\tx1,x2,x3=x\n\ta=p[1]\n\tu=control_2(x,p,t);#calculamos el control\n\tdx1=-a*x1 + exp(2x2)*u\n    dx2=2x1*x2 +sin(x2) + u/2\n\tdx3=2x2\n\tdx=[dx1 dx2 dx3]\nend\n\n# ╔═╡ c8a04540-095c-11eb-0b16-0bbf6ae0b6eb\nmd\"\"\"# ¡Funciona!\nPero si cambiamos a=1 por a=-1 ¿Qué pasaría?\"\"\"\n\n# ╔═╡ 062714d0-0a2e-11eb-073f-6bd47b020c54\n\tconstante_a=1\n\n# ╔═╡ 667f8b70-095f-11eb-08a8-0f49a920e3cb\n@bind tf Slider(10:100)\n\n# ╔═╡ b117ab50-04cc-11eb-1580-fdafb3c3213b\nlet\n\tx0 = [0.1 0.1 0.1]\n\tparametros=[constante_a]\n\ttspan = (0.0,tf)\n\tprob = ODEProblem(derivadas_ejemplo2,x0,tspan,parametros);\n\tsol = solve(prob,Tsit5());\n\t\n\t# Salida y referencia\n\tfig1=plot(sol,vars=(0,3), xaxis=L\"t\",yaxis=L\"y(t)\",label=L\"y(t)\")\n\tfig1=plot!(fig1,sol,vars=( (t,x1)->(t,referencia_2(t)[1]) , 0, 1 ), \t\t\t\t\tlabel=L\"y_r\", linestyle=[:dot], linewidth=2) \n\t\t\n\tfig2=plot(sol, xaxis=\"t\",yaxis=L\"x(t)\", label=:none)\n\t#fig2=plot(sol,vars=(0,1), xaxis=L\"t\",yaxis=L\"x(t)\",label=L\"x_1\")\n\t#fig2=plot!(sol,vars=(0,2), ,label=L\"x_2\")\n\t\n\n\t#Señal de control, u no se guarda, hay que recalcularlo\n\tfig3=plot(sol, vars=((t,x1,x2, x3)->(t,control_2([x1,x2,x3],parametros,t)),0, 1, 2, 3),\n\t\t    xaxis=L\"t\",yaxis=L\"u(t)\",legend=false)\n\tl = @layout [a ; b ; c]\n\tplot(fig1,fig2,fig3, layout=l)\nend\n\n# ╔═╡ 1f8be93e-0962-11eb-14f4-73a59ba80a72\nmd\"\"\" Que raro... para ver que ha pasado veamos la dinámica cero, recordemos las ecuaciones:\n\n$\\dot x_1=-ax_1 + e^{2x_2}u$\n$\\dot x_2=2x_1x_2 +sin(x_2) + \\frac{u}{2}$\n$\\dot x_3=2x_2$\n$y=x_3$\n\nSi la salida $y(t)=0$ cero entonces:\n\n$y=x_3=0 \\to \\dot x_3=0=2x_2 \\to x_2=0 \\to \\dot x_2=0$\n$0=0 +sin(0) + \\frac{u}{2} \\to u=0$\n\n$\\dot x_1=-ax_1$\n\nEsto es estable si a es positivo pero *inestable* si a es negativo, eso podría explica por qué x_1 se aleja del origen (dinámica cero inestable)\n\"\"\"\n\n# ╔═╡ 41656a80-0a7c-11eb-1070-db649ce73728\nmd\"\"\"Para comprobar la teoría ponemos la referenica a cero, cuando la salida se haga cero lo que queda es \"la dimámica cero\" y la teoría nos dice:\n\n-Dinámica cero asintóticamete estable $\\to$ el sistema es **localmente** estable\n\n-Dinámica cero inestable $\\to$ el sistema es inestable\n\n**OJO** lo que la teoría no dice es que pueda seguir una trayectoria, en este caso la sigue pero podría ser que no (al seguir una referencia *general* la salida no es cero y si es muy distinta de cero nos alejamos de la zona conocida)\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─5c4af6e0-022e-11eb-152f-2153b9b672c1\n# ╟─6b1fd530-0a28-11eb-1142-47afd1798c3e\n# ╠═85c0d350-022e-11eb-0873-c118ffde014c\n# ╠═506a20d0-026f-11eb-2bde-f94724bd27f3\n# ╠═f493fdb0-022f-11eb-34a6-4b133c23a71a\n# ╠═c803fe10-0231-11eb-1f84-dbe43fd97eb4\n# ╠═be8523c0-0239-11eb-0439-592e370c5618\n# ╟─85c03440-0274-11eb-3c81-514259334750\n# ╟─2a98e6e0-a227-11eb-026a-bb5831f344bb\n# ╟─e3e9d0a0-022c-11eb-04ba-97dcb9ba908a\n# ╟─6831eb02-023b-11eb-0842-fbe8f8eb8937\n# ╠═5fe018a0-023b-11eb-1e69-d59b562edc9b\n# ╠═1c0442a0-a993-11eb-1b2d-55eb8b868dc7\n# ╠═3ff84c30-0248-11eb-33ba-f99304ee8672\n# ╠═6d535e50-a99a-11eb-08c1-4d98301e53b3\n# ╠═5525d1a0-a9c7-11eb-1de0-1700c9c20460\n# ╠═65893910-a9c7-11eb-2f9f-ebadf375cdbc\n# ╠═a0571620-a9c7-11eb-070f-297fa9e406b2\n# ╟─39ce8af0-023d-11eb-3178-857433b369ae\n# ╟─4c478bf0-023d-11eb-0dce-439d408010fa\n# ╟─b7e08f60-023d-11eb-13cb-ad5285e900d8\n# ╠═697f24d0-a99a-11eb-26e6-a749fb04cb0f\n# ╟─9ecc5ff0-022d-11eb-3715-51831818d04f\n# ╠═65ad8360-a99a-11eb-3764-aded1015107e\n# ╠═4b753d20-a9c8-11eb-320a-d58ec5e3c431\n# ╠═6e31c180-a9c8-11eb-3893-f55415fa4fad\n# ╟─561e07e2-0250-11eb-1380-4b5dfa861cd6\n# ╠═64db3f40-a99a-11eb-01df-d3ca4846ca33\n# ╟─de497f50-0250-11eb-028e-ffe56cf1ba45\n# ╠═c2f97c40-a99a-11eb-30e7-359effec0a1d\n# ╠═85e1f1f0-a9c9-11eb-2a97-1944f7fcb34b\n# ╟─0db8c9c0-0252-11eb-199c-2d69997c6769\n# ╠═dd56c0c2-a99a-11eb-0c87-8f8e2c6321a8\n# ╟─72e4e740-022d-11eb-3a63-31023b9d464f\n# ╠═f1e0ee80-a99a-11eb-0c06-85f8d7086aac\n# ╠═03abf0e0-a9ca-11eb-339c-5599c951871c\n# ╠═183a6460-a9ca-11eb-340e-872e08f29a9e\n# ╠═2d9109e0-a9ca-11eb-08a5-7596eee9e4b2\n# ╟─9ec274e0-022d-11eb-085a-7907b8f1eb93\n# ╠═aed8d350-0265-11eb-1223-1dd0651632b6\n# ╟─0d736c40-0266-11eb-3433-ad75c1617314\n# ╠═454272d0-a9cb-11eb-36db-ffb885a95a52\n# ╟─f54ff5b2-0266-11eb-1df3-49f3c95729c7\n# ╠═2814f040-0267-11eb-3f4d-2933c0c3528a\n# ╟─3b125190-0269-11eb-2473-33cbb7451779\n# ╠═639dce00-0269-11eb-191e-d16a91f3bcf9\n# ╟─e0b21ca0-0a2c-11eb-0e50-efa6c355e7c5\n# ╟─f162f3f0-022d-11eb-30d9-55fb6e39c8c0\n# ╠═a7745f70-026b-11eb-1abe-d1944165d231\n# ╠═a0e6f960-026b-11eb-23c9-410e6d61c4a1\n# ╟─922bccde-022d-11eb-17f2-270aae61f923\n# ╟─cc0e02e2-04c9-11eb-2e08-b906aaec3959\n# ╠═97e9d100-04ca-11eb-07ea-3f5f5addbc45\n# ╟─8839fb60-095a-11eb-063e-85fd960ea83a\n# ╠═54523da0-0958-11eb-2730-cbef0823f684\n# ╠═0610d2ee-0958-11eb-2490-19e0efcd3996\n# ╠═52eade10-095b-11eb-0717-a9686481d875\n# ╟─5c70004e-095b-11eb-0068-89e38689515b\n# ╠═ab5f1de0-0960-11eb-2cf6-414898fd1323\n# ╟─c7d09f80-0a28-11eb-3548-11dbb05bbbbb\n# ╠═77f78c80-a997-11eb-0b80-8da3a424a52f\n# ╠═c8abde00-095c-11eb-237c-a9fd2bd95b8a\n# ╠═706b0500-0a2d-11eb-023e-1de0809fe6cf\n# ╟─c8a04540-095c-11eb-0b16-0bbf6ae0b6eb\n# ╠═062714d0-0a2e-11eb-073f-6bd47b020c54\n# ╠═c900ad60-095f-11eb-3d18-9f187abdb9b3\n# ╠═667f8b70-095f-11eb-08a8-0f49a920e3cb\n# ╟─b117ab50-04cc-11eb-1580-fdafb3c3213b\n# ╟─1f8be93e-0962-11eb-14f4-73a59ba80a72\n# ╟─41656a80-0a7c-11eb-1070-db649ce73728\n", "meta": {"hexsha": "e855fa6ebb533d4caaeee569f03a1e3f364e063f", "size": 16617, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Tema 4.jl", "max_stars_repo_name": "Dictino/CNL", "max_stars_repo_head_hexsha": "2bd66f82a9821c721e512b0e15b3a4e49054b74d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-24T20:12:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T20:12:39.000Z", "max_issues_repo_path": "Tema 4.jl", "max_issues_repo_name": "Dictino/CNL", "max_issues_repo_head_hexsha": "2bd66f82a9821c721e512b0e15b3a4e49054b74d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tema 4.jl", "max_forks_repo_name": "Dictino/CNL", "max_forks_repo_head_hexsha": "2bd66f82a9821c721e512b0e15b3a4e49054b74d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6489184692, "max_line_length": 234, "alphanum_fraction": 0.704880544, "num_tokens": 8155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.8652240947405565, "lm_q1q2_score": 0.7606589660625189}}
{"text": "# Computing deviation in a variety of ways\n\n## count the number of equal/non-equal pairs\n\n\"\"\"\n    counteq(a, b)\n\nCount the number of indices at which the elements of the arrays\n`a` and `b` are equal.\n\"\"\"\nfunction counteq(a::AbstractArray, b::AbstractArray)\n    n = length(a)\n    length(b) == n || throw(DimensionMismatch(\"Inconsistent lengths.\"))\n    c = 0\n    for i = 1:n\n        @inbounds if a[i] == b[i]\n            c += 1\n        end\n    end\n    return c\nend\n\n\n\"\"\"\n    countne(a, b)\n\nCount the number of indices at which the elements of the arrays\n`a` and `b` are not equal.\n\"\"\"\nfunction countne(a::AbstractArray, b::AbstractArray)\n    n = length(a)\n    length(b) == n || throw(DimensionMismatch(\"Inconsistent lengths.\"))\n    c = 0\n    for i = 1:n\n        @inbounds if a[i] != b[i]\n            c += 1\n        end\n    end\n    return c\nend\n\n\n\"\"\"\n    sqL2dist(a, b)\n\nCompute the squared L2 distance between two arrays: ``\\\\sum_{i=1}^n |a_i - b_i|^2``.\nEfficient equivalent of `sumabs2(a - b)`.\n\"\"\"\nfunction sqL2dist(a::AbstractArray{T}, b::AbstractArray{T}) where T<:Number\n    n = length(a)\n    length(b) == n || throw(DimensionMismatch(\"Input dimension mismatch\"))\n    r = 0.0\n    for i = 1:n\n        @inbounds r += abs2(a[i] - b[i])\n    end\n    return r\nend\n\n\n# L2 distance\n\"\"\"\n    L2dist(a, b)\n\nCompute the L2 distance between two arrays: ``\\\\sqrt{\\\\sum_{i=1}^n |a_i - b_i|^2}``.\nEfficient equivalent of `sqrt(sumabs2(a - b))`.\n\"\"\"\nL2dist(a::AbstractArray{T}, b::AbstractArray{T}) where {T<:Number} = sqrt(sqL2dist(a, b))\n\n\n# L1 distance\n\"\"\"\n    L1dist(a, b)\n\nCompute the L1 distance between two arrays: ``\\\\sum_{i=1}^n |a_i - b_i|``.\nEfficient equivalent of `sum(abs, a - b)`.\n\"\"\"\nfunction L1dist(a::AbstractArray{T}, b::AbstractArray{T}) where T<:Number\n    n = length(a)\n    length(b) == n || throw(DimensionMismatch(\"Input dimension mismatch\"))\n    r = 0.0\n    for i = 1:n\n        @inbounds r += abs(a[i] - b[i])\n    end\n    return r\nend\n\n\n# Linf distance\n\"\"\"\n    Linfdist(a, b)\n\nCompute the L∞ distance, also called the Chebyshev distance, between\ntwo arrays: ``\\\\max_{i\\\\in1:n} |a_i - b_i|``.\nEfficient equivalent of `maxabs(a - b)`.\n\"\"\"\nfunction Linfdist(a::AbstractArray{T}, b::AbstractArray{T}) where T<:Number\n    n = length(a)\n    length(b) == n || throw(DimensionMismatch(\"Input dimension mismatch\"))\n    r = 0.0\n    for i = 1:n\n        @inbounds v = abs(a[i] - b[i])\n        if r < v\n            r = v\n        end\n    end\n    return r\nend\n\n\n# Generalized KL-divergence\n\"\"\"\n    gkldiv(a, b)\n\nCompute the generalized Kullback-Leibler divergence between two arrays:\n``\\\\sum_{i=1}^n (a_i \\\\log(a_i/b_i) - a_i + b_i)``.\nEfficient equivalent of `sum(a*log(a/b)-a+b)`.\n\"\"\"\nfunction gkldiv(a::AbstractArray{T}, b::AbstractArray{T}) where T<:AbstractFloat\n    n = length(a)\n    r = 0.0\n    for i = 1:n\n        @inbounds ai = a[i]\n        @inbounds bi = b[i]\n        if ai > 0\n            r += (ai * log(ai / bi) - ai + bi)\n        else\n            r += bi\n        end\n    end\n    return r::Float64\nend\n\n\n# MeanAD: mean absolute deviation\n\"\"\"\n    meanad(a, b)\n\nReturn the mean absolute deviation between two arrays: `mean(abs(a - b))`.\n\"\"\"\nmeanad(a::AbstractArray{T}, b::AbstractArray{T}) where {T<:Number} =\n    L1dist(a, b) / length(a)\n\n\n# MaxAD: maximum absolute deviation\n\"\"\"\n    maxad(a, b)\n\nReturn the maximum absolute deviation between two arrays: `maxabs(a - b)`.\n\"\"\"\nmaxad(a::AbstractArray{T}, b::AbstractArray{T}) where {T<:Number} = Linfdist(a, b)\n\n\n# MSD: mean squared deviation\n\"\"\"\n    msd(a, b)\n\nReturn the mean squared deviation between two arrays: `mean(abs2(a - b))`.\n\"\"\"\nmsd(a::AbstractArray{T}, b::AbstractArray{T}) where {T<:Number} =\n    sqL2dist(a, b) / length(a)\n\n\n# RMSD: root mean squared deviation\n\"\"\"\n    rmsd(a, b; normalize=false)\n\nReturn the root mean squared deviation between two optionally\nnormalized arrays. The root mean squared deviation is computed\nas `sqrt(msd(a, b))`.\n\"\"\"\nfunction rmsd(a::AbstractArray{T}, b::AbstractArray{T}; normalize::Bool=false) where T<:Number\n    v = sqrt(msd(a, b))\n    if normalize\n        amin, amax = extrema(a)\n        v /= (amax - amin)\n    end\n    return v\nend\n\n\n# PSNR: peak signal-to-noise ratio\n\"\"\"\n    psnr(a, b, maxv)\n\nCompute the peak signal-to-noise ratio between two arrays `a` and `b`.\n`maxv` is the maximum possible value either array can take. The PSNR\nis computed as `10 * log10(maxv^2 / msd(a, b))`.\n\"\"\"\nfunction psnr(a::AbstractArray{T}, b::AbstractArray{T}, maxv::Real) where T<:Real\n    20. * log10(maxv) - 10. * log10(msd(a, b))\nend\n", "meta": {"hexsha": "dd393afc3dbb92e2af85ba7a686d3182877c25e3", "size": 4529, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/deviation.jl", "max_stars_repo_name": "logankilpatrick/StatsBase.jl", "max_stars_repo_head_hexsha": "c5328b186f721f9e320928356fb69cf579035240", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 449, "max_stars_repo_stars_event_min_datetime": "2015-01-03T14:38:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:34:50.000Z", "max_issues_repo_path": "src/deviation.jl", "max_issues_repo_name": "logankilpatrick/StatsBase.jl", "max_issues_repo_head_hexsha": "c5328b186f721f9e320928356fb69cf579035240", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 606, "max_issues_repo_issues_event_min_datetime": "2015-02-08T16:52:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T07:41:08.000Z", "max_forks_repo_path": "src/deviation.jl", "max_forks_repo_name": "logankilpatrick/StatsBase.jl", "max_forks_repo_head_hexsha": "c5328b186f721f9e320928356fb69cf579035240", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 254, "max_forks_repo_forks_event_min_datetime": "2015-02-23T22:15:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T00:25:18.000Z", "avg_line_length": 23.5885416667, "max_line_length": 94, "alphanum_fraction": 0.6120556414, "num_tokens": 1418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.8652240912652671, "lm_q1q2_score": 0.7606589630072295}}
{"text": "\"\"\"\narmijo(f,fk,dfk,xk,pk)\nBacktracked Armijo linesearch\n\"\"\"\nfunction armijo(f::Function,fk,dfk,xk,pk;t=1.0, maxIter=10, c1=1e-4,b=0.5)\n    LS = 1\n\n    while LS<=maxIter\n        if f(xk+t*pk)[1] <= fk + t*c1*dot(dfk,pk)\n            break\n        end\n        t *= b\n        LS += 1\n    end\n    if LS>maxIter\n    \tLS= -1\n    \tt = 0.0\n    end\n    return t,LS\nend\n\n\n\"\"\"\nbfgs(f,df,x)\nBFGS method for solving min_x f(x)\n\"\"\"\nfunction bfgs(f::Function,fdf::Function,x::Vector;H=Matrix(1.0I,length(x),length(x)), maxIter=20,atol=1e-8,out::Int=0,storeInterm::Bool=false,\n\tlineSearch::Function=(f,fk,dfk,xk,pk,ak)->armijo(f,fk,dfk,xk,pk,maxIter=30,t=ak),cb::Function=()->())\n\n    his = zeros(maxIter,3)\n    # I   = speye(length(x))\n    X   = (storeInterm) ? zeros(length(x),maxIter) : []\n    fk,dfk  = fdf(x)\n\n    i = 1; flag = -1; a0 = 1.0\n    while i<=maxIter\n\n        his[i,1:2] = [fk norm(dfk)]\n        if storeInterm; X[:,i] = x; end;\n        if norm(dfk)<atol\n            his  = his[1:i,:]\n            flag = 0\n            break\n        end\n\n        # get search direction\n        pk    = - H*dfk\n        # line search\n        ak,his[i,3] = lineSearch(f,fk,dfk,x,pk,a0)\n        if his[i,3]==1\n            a0 =5*ak\n        else\n            a0= 2*ak\n        end\n        cb(i)\n        if out>0\n             Printf.@printf( \"iter=%4d\\t|f|=%1.2e\\t|df|=%1.2e\\tLS=%d\\tmuLS=%1.2e\\n\", i, his[i,1] ,his[i,2] ,his[i,3],ak)\n        end\n        if his[i,3]==-1\n             flag = -3\n             his  = his[1:i,:]\n             break;\n        end\n        x    += ak*pk\n        fk,dfnew    = fdf(x)\n        sk    = ak*pk\n        yk    = dfnew - dfk\n        if dot(yk,sk)>0 # ensure that approximate Hessians remain positive definite\n        \tH     = (I - (sk*yk')/dot(sk,yk)) * H * (I - (yk*sk')/dot(sk,yk)) + (sk*sk')/dot(yk,sk)\n        else\n            if out>0\n                println(\"bfgs detected negative curvature. Resetting Hessian\")\n                a0=1.0\n            end\n            H = Matrix(1.0I,length(x),length(x))\n        end\n        dfk  = dfnew\n        i+=1\n    end\n    i = min(maxIter,i)\n\n    if out>=0\n        if flag==-1\n            Printf.@printf(\"bfgs iterated maxIter (=%d) times but reached only atol of %1.2e instead of tol=%1.2e\",i,his[i,2],atol)\n        elseif flag==-3\n            Printf.@printf(\"bfgs stopped of a line search fail at iteration %d.\",i)\n        elseif out>1\n            Printf.@printf(\"bfgs achieved desired atol of %1.2e at iteration %d.\",atol,i)\n        end\n    end\n\n    if storeInterm; X = X[:,1:i]; end\n    return x,flag,his,X,H\nend\n", "meta": {"hexsha": "ca7a8082899a13e336c8468e2a6bce922827806c", "size": 2564, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bfgs.jl", "max_stars_repo_name": "EmoryMLIP/MFGnet", "max_stars_repo_head_hexsha": "f50f02ff9d9da1a55c47fb3f9ab88e2f84b1de05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2019-12-19T15:42:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T07:41:59.000Z", "max_issues_repo_path": "src/bfgs.jl", "max_issues_repo_name": "EmoryMLIP/MFGnet", "max_issues_repo_head_hexsha": "f50f02ff9d9da1a55c47fb3f9ab88e2f84b1de05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-01-09T12:07:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-27T17:29:37.000Z", "max_forks_repo_path": "src/bfgs.jl", "max_forks_repo_name": "EmoryMLIP/MFGnet", "max_forks_repo_head_hexsha": "f50f02ff9d9da1a55c47fb3f9ab88e2f84b1de05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-12-30T06:40:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T16:20:00.000Z", "avg_line_length": 26.9894736842, "max_line_length": 142, "alphanum_fraction": 0.4933697348, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460027, "lm_q2_score": 0.8558511506439707, "lm_q1q2_score": 0.7606452335337401}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local iv = try Base.loaded_modules[Base.PkgId(Base.UUID(\"6e696c72-6542-2067-7265-42206c756150\"), \"AbstractPlutoDingetjes\")].Bonds.initial_value catch; b -> missing; end\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)\n        el\n    end\nend\n\n# ╔═╡ a5d4303a-81b0-11ec-1083-ed13a1d29807\nusing PlutoUI, LinearAlgebra, FFTW,Plots, StructuredOptimization, Distributions, FileIO, QuartzImageIO, ImageShow, TestImages , Colors\n\n# ╔═╡ f4cb8cfd-b6b1-4e93-9985-2c71b384093f\nmd\"\"\"\n# Recovering images from a few pixels using compressed sensing (L₁-norm minimization)\n\nProject by Yeji Bae and Manon Montyne\n\n## Introduction\n\n### Data compression \n\nIn data compression, a certain signal is represented more efficiently in terms of the sparse vector of coefficients in a generic transform basis e.g. Fourier or wavelet bases. Since most natural signals are compressible, they can be written in terms of a sparse vector s ∈ Rⁿ and a transform basis Ψ ∈ Rⁿ ˣ ⁿ\t:\n\n\t\t\t\t\t\t\t\t\tx = Ψs\n\nThe number of non-zero elements in the vector s equals K. Therefore, we also describe s as being K-sparse.\n\nBoth images and audio signals are compressible in Fourier or wavelet bases. After taking the transform, most coefficients are close to zero and can thus be set equal to zero with a limited loss of quality. Afterward, these few active coefficients can replace the original signal to be stored and transmitted. The original signal can then be recovered by taking the inverse transform [1].\n\n\nExample of data compression (adapted code from [1]):\n\"\"\"\n\n# ╔═╡ 62a8366f-14dc-410b-ba31-a8f695dfe986\nbegin\n\turl = \"https://www.thespruce.com/thmb/JObhDcNNBALGVyF9S7bFoQwoXsI=/941x0/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/plants-with-big-flowers-4138211-hero-b10becb169064cc4b3c7967adc1b22e1.jpg\"\n\tdownload(url, \"flower.jpeg\")\n\tflower = load(\"flower.jpeg\") #Load in mage from url\nend\n\n# ╔═╡ 97006203-2819-489d-a4dc-cef3af6e72b3\nflower2 = Gray.(flower) #Convert to grayscale\n\n# ╔═╡ 7415fc09-1155-49e5-b523-c9df2bd8d7d7\nbegin\n\tflower2_array = convert(Array{Float64}, flower2) #Convert image to array\n\tflower_tranformed = fft(flower2_array) #Apply Fourier transformation\n\tF = log.(abs.(fftshift(flower_tranformed)) .+1) #Put on log-scale\n\tGray.(F) #Plot Fourrier coefficients\nend\n\n# ╔═╡ bc36eb16-5b31-4639-864c-4ee4b627108e\nbegin\n\tBt = sort(abs.(flower_tranformed[:,:]), dims=2) #sortFourrier coefficients\n\tthr= floor.(0.95*length.(Bt)) #Keep 5% of the data (1-0.95 = 0.05)\n\tind = abs.(flower_tranformed) .> thr\n\tAtlow = flower_tranformed.*ind\n\talow = ifft(Atlow)\t#Take inverse FFT (iFFT) to plot compressed image\n\tGray.(abs.(alow))\nend\n\n# ╔═╡ 56a83328-2689-42be-8dfd-8ee38c5a70e0\nmd\"\"\"\nAs can be seen in this example, we were able to reconstruct the original image by keeping only 5% of the data.\n\nCompressed sensing on the other hand, turns the compression paradigm upside down: instead of compressing high-dimensional data by discarding most of the information, it is now possible to reconstruct a full signal from only a few measurements. Before we go deeper into compressed sensing, we will have a look at the reconstruction of a simple signal (based on an example from Kutz et al. (7)).\n\n### Reconstruction of a simple signal (Kutz example)\n\nThis example is based on the Kutz example which was worked out further in Nextjournal (6). Herein, a simple signal is constructed from 2 frequencies.\n\n\t\t\t\t\ty = sin.(1394 * π * t) + sin.(3266 * π * t)\n\nIn the following plots we show the signal both in the time domain and the frequency domain. These plots clearly show that in the time domain the signal is not sparse, whereas in the frequency domain it is. By looking at the frequency domain, we see that the signal is zero everywhere except at two points, representing th etwo cosine waves. This example thus introduces 2 very important concepts in compressed sensing: sparsity and incoherence.\n\"\"\"\n\n# ╔═╡ 6e37dfac-5f50-498b-b356-f56fcbd7d02a\nbegin\n\t\n\tn = 5000 #number of samples\n\tt = range(0.0, step=1/n, length=n) #Step size is 1/5000\n\ty = sin.(1394 * pi * t) + sin.(3266 * pi * t) #Signal consisting of 2 sinus waves (Kutz example)\n\tplot(t, y, title = \"Simple signal (time domain)\", xlabel=\"t\", ylabel=\"y\", legend=false)\nend\n\n# ╔═╡ 68a5c2c4-e1ca-420d-b421-c4f570308884\nplot(t, y, xlim=(0.0, 0.02), title = \"Zoom in on simple signal plot (time domain)\", xlabel = \"t\", ylabel = \"y\", legend=false)\n\n# ╔═╡ 39f25941-cab4-4776-9167-5b75d555fdbf\nbegin\n\tfreq = fftfreq(n,n)\n\tplot(freq,dct(y),title=\"Simple signal (frequency domain)\", legend=false, xlabel = \"Frequency\", ylabel = \"dct(y)\") #dct = discrete cosine transform which is needed to get the frequency domain signal (a widely used transformation technique in signal processing and data compression)\nend\n\n# ╔═╡ c899003d-bee5-4857-919a-8007d22c9f90\nmd\"\"\"\n## Compressed sensing\n\n### Sparsity\nAll of data compression relies on sparsity. This means that a signal is represented more efficiently in terms of a sparse vector of coefficients in a transform basis (e.g. Fourier or wavelet basis). As previously seen, signals can thus be written in terms of a sparse vector s ∈ Rⁿ and a transform basis Ψ ∈ Rⁿ ˣ ⁿ:\n\n\t\t\t\t\t\t\t\t\tx = Ψs [Eq. 1]\n\nNow, in compressed sensing it is possible to collect only a few measurements and then infer the sparse representation in the transformed basis. Until recently, finding the sparsest vector consistent with the measurements was considered a NP hard problem. However, nowadays it is possible to achieve a full signal reconstruction using convex optimization algorithms.\n\nIf we have a signal that is K-sparse in Ψ, it is possible to collect only a few measurements y ∈ Rᵖ, with K < p << n (with n = number of measurements in original signal x). These measurements y are then given by:\n\n\t\t\t\t\t\t\t\t\ty = Cx [Eq. 2]\n\nIn this formula, C ∈ Rᵖ ˣ ⁿ is the measurement matrix  with a set of p linear measurements on the state of x. The choice of this measurement matrix is very important in compressed sensing because it must be incoherent with respect to Ψ (see further). \n\nAnother important condition for compressed sensing is that the number of measurements p must be sufficiently large. It must be in the order of p =  (K * log(n/K)) = k₁ * K * log(n/K) (k₁ depends on how incoherent C and Ψ are)\n\nIf we now know the sparse vector s, we are capable of reconstructing the signal x. The ultimate goal in compressed sensing is thus to find the sparsest vector s that is consistent with the measurements. \n\n\t\t\t\t\t\t\t\ty = CΨs = Θs [Eq. 3]\nThis system of equations is an underdetermined problem and we thus have infinitely many solutions for s, however, we want to find the sparsest s for which these equations hold:\n\t\t\t\t\tŝ = argmin ||s||₀ subject to y = CΨs [Eq. 4]\n\nThis optimization however is non-convex and a solution can only be found by brute-force search, therefore we will relax the optimization to a convex optimization by taking the l₁ norm or Manhattan norm:\n\n\t\t\t\t\tŝ = argmin ||s||₁ subject to y = CΨs [Eq. 5]\n[1]\n\n\n*Note on different norms*\n- *The l₀ norm is used to count non-zero elements in a vector*\n- *The l₁ norm sums the absolute values of each element in a vector*\n\n\n### Incoherence\n\nWe have now discussed the concept of sparsity and compressed sensing. In this part we will discuss incoherence, because an important part of compressed sensing is the incoherence of the measurement matrix C (see before).\n\nIf we have enough good measurements we will have a matrix Θ = CΨ that preserves the distance and inner product structure of sparse vectors. We thus seek a measurement matrix C such that Θ acts as a near isometry map on sparse vectors. Isometry means that we perform a distance-preservind transformation. If now Θ acts as a near isometry, we can solve equation 3 using convex l₁ minimization.\n\nIn other words, the measurements C are good measurements if they are incoherent with respect to the columns of the sparsifying basis Ψ. In this case the rows of C will have a small inner product with the columns of Ψ. On the other hand, if the measurements are coherent with the basis, it will provide little information. The (in)coherence of measurements C and the basis Ψ is given by $$μ(C,Ψ) = \\sqrt{n}*max|⟨c_{k},ψ_{j}⟩|$$ where $$c_{k}$$ is the k-th row of the matrix C and $$ψ_{j}$$ is the j-th column of the matrix ψ. The coherence will range between 1 and $$\\sqrt{n}$$ [1].\n\nHence, in compressed sensing it is important to find low coherence pairs. A first example of such a pair is the canonical or spike basis ϕₖ(t) = δ(t − k) as C combined with the Fourier basis as Ψ. This pair has a μ(C,Ψ) = 1, giving us maximal incoherence. In a second example, we have noiselets for C and wavelet bases as Ψ. The coherence between this pair is $$\\sqrt{2}$$. Finally, also random matrices are largely incoherent with any fixed basis. For this purpose, an orthobasis C needs to be selected uniformly at random. This can be done by orthonormalizing n vectors sampled independently and uniformly on the unit sphere. The coherence between C and Ψ in this case is then about 2 log(n) [8]. This last example is shown below in the code.\n\"\"\"\n\n# ╔═╡ 135c1b29-8e82-4d06-b2f6-ff6fa7e3f031\nmd\"\"\"\n### Kutz example part 2: reconstructing the signal from a sample\n\nNow we will work further on the Kutz example. In the following plot, we sampled 10% of the original signal and made a scatter plot of the data points. The data points were also connected through lines. The percentage of sampling can be changed with the following slider. The code that follows was adapted from Nextjournal [6].\n\n$@bind x Slider(1:100, show_value=true, default=10)\n\"\"\"\n\n# ╔═╡ 832052d7-c34d-4bce-8236-64cdc8f32be5\nbegin\n\t#Sample x procent of the signal\n\tn_sample= Int(n*x/100) #number of data points sampled\n\tsampled_t_coordinates = sort(rand(1:n,n_sample)) # sorting for nice plotting\n\t#Sample the signal\n\tsampled_y_coordinates = y[sampled_t_coordinates]\n\t#Plot sampled signal\n\tplot(sampled_t_coordinates, sampled_y_coordinates, seriestype=scatter, title = \"Sparse signal\", xlabel=\"t\", ylabel=\"y\", legend=false) #Scatter\n\tplot!(sampled_t_coordinates,sampled_y_coordinates,seriestype=:line) #Add line\nend\n\n# ╔═╡ df23221a-1dc6-4f45-9f03-35bc12c48e46\nmd\"\"\"\n\nNow we have our sparse data and we would like to reconstruct our original signal. As previously stated, we can solve this problem using convex optimization:\n\n\t\t\t\t\tŝ = argmin ||s||₁ subject to y = CΨs\n\nWe can solve this using the StructuredOptimization.jl package (more details on this package later).\n\"\"\"\n\n# ╔═╡ 7a9864b2-fc6f-4b89-8efa-183d644f8943\nbegin\n\ts = Variable(n)\n\t~s .= 0.0\n\tlambda = 1e-1\n\t@minimize ls(idct(s)[sampled_t_coordinates]-sampled_y_coordinates) + lambda*norm(s,1)\nend\n\n# ╔═╡ d32b08c7-8262-4231-9469-df9f667e5c59\n~s\n\n# ╔═╡ c490029b-2b61-42c4-bd5f-72ba844e03b0\nbegin\n\tplot(freq,dct(y),color=\"blue\",title=\"Original vs reconstructed signal (frequency domain)\", label = \"Original signal\", xlabel = \"Frequency\", ylabel = \"dct(y)\")\n\tplot!(freq,~s,color=\"orange\", label = \"Reconstructed signal\")\nend\n\n# ╔═╡ 7a104d94-6062-47a2-82cb-553513e28a86\nbegin\n\tplot(t, y,xlim=(0.0, 0.02), title = \"Original vs reconstructed signal (time domain)\", xlabel = \"t\", ylabel = \"y\", color=\"blue\", label = \"Original signal\")\n\tplot!(t, idct(~s), label = \"Reconstructed signal\", color=\"orange\")\nend\n\n# ╔═╡ 2bef7c97-8b88-4203-8825-eda70d5fab56\nmd\"\"\"\nThis result is pretty good for only 10 percent of data. The higher the percentage of sampling (adjust with the slider), the more related the original and the reconstructed signal become, as expected.\n\nNow, to show that we cannot use l₂-norm minimization to solve the sparsity problem, we have solved the example for the l₂-norm and plotted the results above the previous plots. We clearly see that the signal is not sparse in the frequency domain, in contrast to the l₁-norm. We are thus not able to reconstruct the original signal using l₂-norm minimization (see plot in time domain).\n\"\"\"\n\n# ╔═╡ 9c19aaf2-3c25-425b-9e48-4d90d1366ce2\nbegin\n\ts1 = Variable(n)\n\t~s1 .= 0.0\n\t@minimize ls(idct(s1)[sampled_t_coordinates]-sampled_y_coordinates) + lambda*norm(s1,2)\nend\n\n# ╔═╡ 4d4ec391-7219-459a-9b49-6ba901eeae92\n~s1\n\n# ╔═╡ 57a799e2-68b2-4867-867a-24d8590a84a5\nbegin\n\tplot(freq,dct(y),color=\"blue\",title=\"Original vs reconstructed signal (frequency domain)\", label = \"Original signal\", xlabel = \"Frequency\", ylabel = \"dct(y)\")\n\tplot!(freq,~s,color=\"orange\", label = \"Reconstructed signal (l₁)\")\n\tplot!(freq, ~s1, color=\"green\", label = \"Reconstructed signal (l₂)\")\nend\n\n# ╔═╡ 7c3a2e4b-419f-44f1-bea7-20c7a3aa06a3\nbegin\n\tplot(t, y,xlim=(0.0, 0.02), title = \"Original vs reconstructed signal (time domain)\", xlabel = \"t\", ylabel = \"y\", color=\"blue\", label = \"Original signal\")\n\tplot!(t, idct(~s), label = \"Reconstructed signal (l₁)\", color=\"orange\")\n\tplot!(t, idct(~s1), label = \"Reconstructed signal (l₂)\", color = \"green\")\nend\n\n# ╔═╡ 84e6d7fb-4df6-498b-bd5c-151004756e9e\nmd\"\"\"\n### Application: MRI\n\nMagnetic Resonance Imaging (MRI) is a medical imaging technique that is widely used to provide reproducible, non-invasive, and quantitative measurements of tissue. However, a major disadvantage of MRI is the long acquisition time. Due to this disadvantage, there could be major artifacts present when there is patient or physiological movement. This prolonged acquisition time also limits the usage of MRI due to its expensive cost and considerations of patient comfort and compliance. Furthermore, if contrast agent injection is required, there could be a contrast washout leading to poor quality or non-diagnostic images [2].\n\nThe reason for this slow acquisition time is that data samples are being collected in the k-space, rather than directly in the image space. This k-space is the 2D or 3D Fourier transform of the MR image that is measured. The raw data samples are obtained sequentially in this k-space and the speed at which this is done is limited by both physiological and hardware constraints. Once the desired field-of-view and spatial resolution are specified, the required raw data in the k-space is conventionally determined by the Nyquist-Shannon sampling criteria. However, compressed sensing allows for fast acquisition without adhering to the Nyquist-Shannon sampling criteria by performing a more aggressive undersampling. With compressed sensing, an image can be reconstructed without deterioration of the quality by performing a non-linear optimization on randomly undersampled raw data, assuming that the data is compressible [2], [3].\n\nFor this purpose, it is important to find a good undersampling scheme that is as random as possible to create incoherent undersampling artifacts so that a proper non-linear reconstruction can be applied (see the part about incoherence). The acceleration rate is determined by the sparsity of this random undersampling. Secondly, we also need a good non-linear optimization algorithm to have an efficient, stable, and accurate reconstruction [2].\n\"\"\"\n\n# ╔═╡ afb35a7d-1454-4c8f-a230-daabafc8e7a3\nmd\"\"\"\n### Algorithms for l₁-norm minimization\n\nNowadays, there are mainly 2 categories of reconstruction algorithms: convex optimization algorithms and greedy algorithms. The greedy algorithm uses a fast iterative process, whereas the convex optimization algorithms have a higher computational complexity [11].  In the StructuredOptimization.jl package that was used in the Kutz example, we used LASSO for l₁-minimization. However, other proximal algorithms can be used by adding a 'solver object' from the ProximalAlgorithms.jl package [10]. Least Absolute Shrinkage and Selection Operator (LASSO) is a penalizd least squares technique for which we can rewrite the problem in Eq. 5 as:\n\n\t\t\t\t\tŝ = argmin (||CΨs - y||²)/2 + λ||s||₁  [Eq. 6]\n\nwhere λ ≥ 0 is the regularization parameter which controls the amount of shrinkage. It makes us of the coordinate descent algorithm [12].\n\nIn the following paragraphs, we will discuss two commonly used algorithms to perform l₁-norm minimization. The first one is the Alternating Direction Method of Multipliers (ADMM) and the second one is l₁-norm minimization via l₂-norm minimization.\n\n##### Alternating Direction Method of Multipliers (ADMM)\n\nADMM is an algorithm which solves convex optimization problems by breaking them into smaller subproblems, that are easier to solve. The solutions to these small local subproblems are then used to find the solution to the large global problem. ADMM blends the benefits of dual composition and augmented Lagrangian methods for constrained optimization and is closely related to a lot of other algorithm such as proximal methods . In general, ADMM is very efficient in optimization, however, it is not trivial to determine the optimal parameter settings (e.g. penalty parameters, update rates) that influence the accuracy and speed of reconstruction.\n\nthe algorithm solves problem in the form:\n\t\n\t\t\t\t\tminimize f(x) + g(z) subject to Ax + Bz = c\n\nThe only difference between this and the general linear equality-constrained problem:\n\n\t\t\t\t\tminimize f(x) subject to Ax = b\n\nis that the variable, called x there, has here been split into 2 parts (x and z). The augmented Lagrangian for this problem is:\n\n\t\t\tLρ(x, z, y) = f(x) + g(z) + yᵀ(Ax + Bz - c) + (ρ/2)||Ax + Bz - c||²₂\n\nADMM will then peform iterations in which there is an x-minimization step, a z-minimization step and a dual variable update (which is very similar to dual ascent method and method of multipliers). The dual variable update will use a step size that is equal to the augmented Lagrangian parameter ρ.\n\n\t\t\t\txᵏ⁺¹ := argmin(x)  Lρ(x, zᵏ, yᵏ)\n\t\t\t\tzᵏ⁺¹ := argmin(z)  Lρ(xᵏ⁺¹, z, yᵏ)\n\t\t\t\tyᵏ⁺¹ := yᵏ + ρ(Axᵏ⁺¹ + Bzᵏ⁺¹ - c) where ρ > 0\n\nIn ADMM, x and z are thus updated in alternating or sequential fashion. This is reflected in the name by calling it 'alternating direction' method of multipliers [9].\n\n##### l₁-norm minimization via l₂-norm minimization \n\nIn this last paragraph we introduce the state of the art compressed sensing reconstruction algorithm which uses l₂-norm minimization to achieve l₁-norm minimization. This method makes use of the geometrical interpretation of the minimization problem and the fact that the Euclidean distance between the l₁-norm and the l₂-norm solutions lie closely to one another. This means that if we can find the l₂-norm solution, the direction of the l₁-norm solution is on the shortest path connecting them. This method provides a more stable solution than the greedy algorithm and is faster compared to the convex optimization methods. The pseudocode for the method is provided below:\n\n*Pseudocode*\n\n- Input: y ∈ Rᴹ and A ∈ Rᴹˣᴺ with sparsity k\n- Output: xˆ ∈ Rᴺ\n- Extra information: Q = l₂-norm solution, P = l₁-norm minimization\n\n\t\t1: [M, N] <- dim(A)  # initiate the dimension\n\t\t2: γ <- det(AAᵀ)\n\t\t3: If γ = 0 then stop, return xˆ<- {}, else continue to step 4\n\t\t4: calculate xQ <-(AAᵀ)-Aᵀy  # L2-norm solution\n\t\t5: [U ζ] = sort(abs(xQ))      # sort L2-norm solution \n\t\t6: ds = zeros (N,1)           # initiate direction vector\n\t\t7: for i=1 to k\n\t\t8: ds(∫(k))=1    # vector direction from L2-norm solution to L1-norm solution\n\t\t9: end for loop\n\t\t10: As = Ads,\n\t\t11: xP = (AsAsᵀ)^(-1)Asᵀy    # L1-norm solution\n\t\t12: xˆ<- xp \n\t\t13: return xˆ\n\n\"\"\"\n\n# ╔═╡ ef90c37f-0e7e-48d1-8ab3-4ae779c3ed91\nmd\"\"\"\n## References\n\n[1] S. L. Brunton and N. J. Kutz, Data-Driven Science & Engineering. 2017.\n\n[2] G. Yang et al., “DAGAN: Deep De-Aliasing Generative Adversarial Networks for Fast Compressed Sensing MRI Reconstruction,” IEEE Trans. Med. Imaging, vol. 37, no. 6, pp. 1310–1321, Jun. 2018.\n\n[3] “k-space (magnetic resonance imaging) - Wikipedia.” [Online]. Available: https://en.wikipedia.org/wiki/K-space_(magnetic_resonance_imaging). [Accessed: 17-Dec-2021]\n\n[4] M. Lustig, D. L. Donoho, J. M. Santos, and J. M. Pauly, “Compressed sensing MRI: A look at how CS can improve on current imaging techniques,” IEEE Signal Process. Mag., vol. 25, no. 2, pp. 72–82, 2008.\n\n[5] Pereira, M. P., Lovisolo, L., da Silva, E. A. B., &amp; de Campos, M. L. R. (2014). On the design of maximally incoherent sensing matrices for compressed sensing using orthogonal bases and its extension for Biorthogonal Bases Case. Digital Signal Processing, 27, 12–22. https://doi.org/10.1016/j.dsp.2014.01.006 \n\n[6] Compressed Sensing in Julia. Nextjournal. 2021 Feb 15\n\n[7] Brunton, Steven L., and Jose N. Kutz. Data-driven science and engineering: machine learning, dynamical systems, and control. Cambridge, United Kingdom New York, NY: Cambridge University Press, 2019. Print.\n\n[8] Candes EJ, Wakin MB. An introduction to compressive sampling: A sensing/sampling paradigm that goes against the common knowledge in data acquisition. IEEE Signal Process Mag [Internet]. 2008 [cited 2022 Jan 30];25(2):21–30. Available from: https://www.researchgate.net/publication/3322018_Wakin_MB_An_introduction_to_compressive_sampling_IEEE_Signal_Process_Mag_252_21-30\n\n[9] Boyd S, Parikh N, Chu E, Eckstein J, Boyd S, Parikh N, et al. Distributed Optimization and Statistical Learning via the Alternating Direction Method of Multipliers. Found Trends R Mach Learn. 2010;3(1):1–122. \n\n[10] Home · StructuredOptimization [Internet]. [cited 2022 Jan 31]. Available from: https://juliafirstorder.github.io/StructuredOptimization.jl/latest/\n\n[11] Usman, K., Gunawan, H., &amp; Suksmono, A. B. (2018). Compressive Sensing Reconstruction Algorithm using L1-norm Minimization via L2-norm Minimization. International Journal on Electrical Engineering and Informatics, 10(1), 37–50. https://doi.org/10.15676/ijeei.2018.10.1.3 \n\n[12] Gauraha N. Introduction to the LASSO A Convex Optimization Approach for High-dimensional Problems.\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nColors = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nDistributions = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nFFTW = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nFileIO = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nImageShow = \"4e3cecfd-b093-5904-9786-8bbb286a6a31\"\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nQuartzImageIO = \"dca85d43-d64c-5e67-8c65-017450d5d020\"\nStructuredOptimization = \"46cd3e9d-64ff-517d-a929-236bc1a1fc9d\"\nTestImages = \"5e47fb64-e119-507b-a336-dd2b206d9990\"\n\n[compat]\nColors = \"~0.12.8\"\nDistributions = \"~0.25.43\"\nFFTW = \"~1.3.0\"\nFileIO = \"~1.12.0\"\nImageShow = \"~0.3.3\"\nPlots = \"~1.25.7\"\nPlutoUI = \"~0.7.32\"\nQuartzImageIO = \"~0.7.4\"\nStructuredOptimization = \"~0.3.0\"\nTestImages = \"~1.6.2\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[AbstractFFTs]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"051c95d6836228d120f5f4b984dd5aba1624f716\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"0.5.0\"\n\n[[AbstractOperators]]\ndeps = [\"AbstractFFTs\", \"DSP\", \"FFTW\", \"LinearAlgebra\", \"RecursiveArrayTools\"]\ngit-tree-sha1 = \"ea4e4ad8d7def7e6e83e2336454d67d4cc5c421f\"\nuuid = \"d9c5613a-d543-52d8-9afd-8f241a8c3f1c\"\nversion = \"0.2.2\"\n\n[[AbstractPlutoDingetjes]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"8eaf9f1b4921132a4cff3f36a1d9ba923b14a481\"\nuuid = \"6e696c72-6542-2067-7265-42206c756150\"\nversion = \"1.1.4\"\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"af92965fb30777147966f58acb05da51c5616b5f\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.3\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[ArrayInterface]]\ndeps = [\"Compat\", \"IfElse\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"Static\"]\ngit-tree-sha1 = \"ffc6588e17bcfcaa79dfa5b4f417025e755f83fc\"\nuuid = \"4fba245c-0d91-5ea0-9b3e-6abc04ee57a9\"\nversion = \"4.0.1\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[AxisArrays]]\ndeps = [\"Dates\", \"IntervalSets\", \"IterTools\", \"RangeArrays\"]\ngit-tree-sha1 = \"d127d5e4d86c7680b20c35d40b503c74b9a39b5e\"\nuuid = \"39de3d68-74b9-583c-8d2d-e117c070f3a9\"\nversion = \"0.4.4\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[BenchmarkTools]]\ndeps = [\"JSON\", \"Logging\", \"Printf\", \"Profile\", \"Statistics\", \"UUIDs\"]\ngit-tree-sha1 = \"940001114a0147b6e4d10624276d56d531dd9b49\"\nuuid = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\nversion = \"1.2.2\"\n\n[[BinaryProvider]]\ndeps = [\"Libdl\", \"Logging\", \"SHA\"]\ngit-tree-sha1 = \"ecdec412a9abc8db54c0efc5548c64dfce072058\"\nuuid = \"b99e7846-7c00-51b0-8f62-c81ae34c0232\"\nversion = \"0.5.10\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"4b859a208b2397a7a623a03449e4636bdb17bcf2\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+1\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"f9982ef575e19b0e5c7a98c6e75ee496c0f73a93\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.12.0\"\n\n[[ChangesOfVariables]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"bf98fa45a0a4cee295de98d4c1462be26345b9a1\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.2\"\n\n[[CodecBzip2]]\ndeps = [\"Bzip2_jll\", \"Libdl\", \"TranscodingStreams\"]\ngit-tree-sha1 = \"2e62a725210ce3c3c2e1a3080190e7ca491f18d7\"\nuuid = \"523fee87-0ab8-5b00-afb7-3ecf72e48cfd\"\nversion = \"0.7.2\"\n\n[[CodecZlib]]\ndeps = [\"TranscodingStreams\", \"Zlib_jll\"]\ngit-tree-sha1 = \"ded953804d019afa9a3f98981d99b33e3db7b6da\"\nuuid = \"944b1d66-785c-5afd-91f1-9de20f533193\"\nversion = \"0.7.0\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"6b6f04f93710c71550ec7e16b650c1b9a612d0b6\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.16.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[ColorVectorSpace]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"LinearAlgebra\", \"SpecialFunctions\", \"Statistics\", \"TensorCore\"]\ngit-tree-sha1 = \"3f1f500312161f1ae067abe07d13b40f78f32e07\"\nuuid = \"c3611d14-8923-5661-9e6a-0046d554d3a4\"\nversion = \"0.9.8\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"44c37b4636bc54afac5c574d2d02b625349d6582\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.41.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[DSP]]\ndeps = [\"FFTW\", \"IterTools\", \"LinearAlgebra\", \"Polynomials\", \"Random\", \"Reexport\", \"SpecialFunctions\", \"Statistics\"]\ngit-tree-sha1 = \"2a63cb5fc0e8c1f0f139475ef94228c7441dc7d0\"\nuuid = \"717857b8-e6f2-59f4-9121-6e50c889abd2\"\nversion = \"0.6.10\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"3daef5523dd2e769dad2365274f760ff5f282c7d\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.11\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[DensityInterface]]\ndeps = [\"InverseFunctions\", \"Test\"]\ngit-tree-sha1 = \"80c3e8639e3353e5d2912fb3a1916b8455e2494b\"\nuuid = \"b429d917-457f-4dbc-8f4c-0cc954292b1d\"\nversion = \"0.4.0\"\n\n[[Distances]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"3258d0659f812acde79e8a74b11f17ac06d0ca04\"\nuuid = \"b4f34e82-e78d-54a5-968a-f98e89d6e8f7\"\nversion = \"0.10.7\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Distributions]]\ndeps = [\"ChainRulesCore\", \"DensityInterface\", \"FillArrays\", \"LinearAlgebra\", \"PDMats\", \"Printf\", \"QuadGK\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"Test\"]\ngit-tree-sha1 = \"38bcc22b6e358e88a7715ad0db446dfd3a4fea47\"\nuuid = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nversion = \"0.25.43\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[EllipsisNotation]]\ndeps = [\"ArrayInterface\"]\ngit-tree-sha1 = \"d7ab55febfd0907b285fbf8dc0c73c0825d9d6aa\"\nuuid = \"da5c29d0-fa7d-589e-88eb-ea29b0a81949\"\nversion = \"1.3.0\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[ExprTools]]\ngit-tree-sha1 = \"56559bbef6ca5ea0c0818fa5c90320398a6fbf8d\"\nuuid = \"e2ba6199-217a-4e67-a87a-7c52f15ade04\"\nversion = \"0.1.8\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FFTW]]\ndeps = [\"AbstractFFTs\", \"FFTW_jll\", \"IntelOpenMP_jll\", \"Libdl\", \"LinearAlgebra\", \"MKL_jll\", \"Reexport\"]\ngit-tree-sha1 = \"8fda0934cb99db617171f7296dc361f4d6fa5424\"\nuuid = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nversion = \"1.3.0\"\n\n[[FFTW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea\"\nuuid = \"f5851436-0d7a-5f13-b9de-f02708fd171a\"\nversion = \"3.3.10+0\"\n\n[[FileIO]]\ndeps = [\"Pkg\", \"Requires\", \"UUIDs\"]\ngit-tree-sha1 = \"67551df041955cc6ee2ed098718c8fcd7fc7aebe\"\nuuid = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nversion = \"1.12.0\"\n\n[[FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"8756f9935b7ccc9064c6eef0bff0ad643df733a3\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.12.7\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"0c603255764a1fa0b61752d2bec14cfbd18f7fe8\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+1\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"RelocatableFolders\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"4a740db447aae0fbeb3ee730de1afbb14ac798a1\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.63.1\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"aa22e1ee9e722f1da183eb33370df4c1aeb6c2cd\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.63.1+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"a32d672ac2c967f3deb8a81d828afc739c838a06\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+2\"\n\n[[Graphics]]\ndeps = [\"Colors\", \"LinearAlgebra\", \"NaNMath\"]\ngit-tree-sha1 = \"1c5a84319923bea76fa145d49e93aa4394c73fc2\"\nuuid = \"a2bd30eb-e257-5431-a919-1863eab51364\"\nversion = \"1.1.1\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"0fa77022fe4b511826b39c894c90daf5fce3334a\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.17\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"129acf094d168394e80ee1dc4bc06ec835e510a3\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+1\"\n\n[[Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[HypertextLiteral]]\ngit-tree-sha1 = \"2b078b5a615c6c0396c77810d92ee8c6f470d238\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.3\"\n\n[[IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[IfElse]]\ngit-tree-sha1 = \"debdd00ffef04665ccbb3e150747a77560e8fad1\"\nuuid = \"615f187c-cbe4-4ef1-ba3b-2fcf58d6d173\"\nversion = \"0.1.1\"\n\n[[ImageBase]]\ndeps = [\"ImageCore\", \"Reexport\"]\ngit-tree-sha1 = \"b51bb8cae22c66d0f6357e3bcb6363145ef20835\"\nuuid = \"c817782e-172a-44cc-b673-b171935fbb9e\"\nversion = \"0.1.5\"\n\n[[ImageCore]]\ndeps = [\"AbstractFFTs\", \"ColorVectorSpace\", \"Colors\", \"FixedPointNumbers\", \"Graphics\", \"MappedArrays\", \"MosaicViews\", \"OffsetArrays\", \"PaddedViews\", \"Reexport\"]\ngit-tree-sha1 = \"9a5c62f231e5bba35695a20988fc7cd6de7eeb5a\"\nuuid = \"a09fc81d-aa75-5fe9-8630-4744c3626534\"\nversion = \"0.9.3\"\n\n[[ImageShow]]\ndeps = [\"Base64\", \"FileIO\", \"ImageBase\", \"ImageCore\", \"OffsetArrays\", \"StackViews\"]\ngit-tree-sha1 = \"d0ac64c9bee0aed6fdbb2bc0e5dfa9a3a78e3acc\"\nuuid = \"4e3cecfd-b093-5904-9786-8bbb286a6a31\"\nversion = \"0.3.3\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[InlineStrings]]\ndeps = [\"Parsers\"]\ngit-tree-sha1 = \"61feba885fac3a407465726d0c330b3055df897f\"\nuuid = \"842dd82b-1e85-43dc-bf29-5d0ee9dffc48\"\nversion = \"1.1.2\"\n\n[[IntelOpenMP_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d979e54b71da82f3a65b62553da4fc3d18c9004c\"\nuuid = \"1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0\"\nversion = \"2018.0.3+2\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[IntervalSets]]\ndeps = [\"Dates\", \"EllipsisNotation\", \"Statistics\"]\ngit-tree-sha1 = \"3cc368af3f110a767ac786560045dceddfc16758\"\nuuid = \"8197267c-284f-5f27-9208-e0e47529a953\"\nversion = \"0.5.3\"\n\n[[Intervals]]\ndeps = [\"Dates\", \"Printf\", \"RecipesBase\", \"Serialization\", \"TimeZones\"]\ngit-tree-sha1 = \"323a38ed1952d30586d0fe03412cde9399d3618b\"\nuuid = \"d8418881-c3e1-53bb-8760-2df7ec849ed5\"\nversion = \"1.5.0\"\n\n[[InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.2\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[IterTools]]\ngit-tree-sha1 = \"fa6287a4469f5e048d763df38279ee729fbd44e5\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.4.0\"\n\n[[IterativeSolvers]]\ndeps = [\"LinearAlgebra\", \"Printf\", \"Random\", \"RecipesBase\", \"SparseArrays\"]\ngit-tree-sha1 = \"1169632f425f79429f245113b775a0e3d121457c\"\nuuid = \"42fd0dbc-a981-5370-80f2-aaf504508153\"\nversion = \"0.9.2\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"22df5b96feef82434b07327e2d3c770a9b21e023\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.4.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[JSONSchema]]\ndeps = [\"HTTP\", \"JSON\", \"URIs\"]\ngit-tree-sha1 = \"2f49f7f86762a0fbbeef84912265a1ae61c4ef80\"\nuuid = \"7d188eb4-7ad8-530c-ae41-71a32a6d4692\"\nversion = \"0.3.4\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"f2355693d6778a178ade15952b7ac47a4ff97996\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.3.0\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a8f4f279b6fa3c3c4f1adadd78a621b13a506bce\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.9\"\n\n[[LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"0b4a5d71f3e5200a7dff793393e09dfc2d874290\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+1\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"e5718a00af0ab9756305a0392832c8952c7426c1\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.6\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MKL_jll]]\ndeps = [\"IntelOpenMP_jll\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"eb540ede3aabb8284cb482aa41d00d6ca850b1f8\"\nuuid = \"856f044c-d86e-5d09-b602-aeab76dc8ba7\"\nversion = \"2020.2.254+0\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[MappedArrays]]\ngit-tree-sha1 = \"e8b359ef06ec72e8c030463fe02efe5527ee5142\"\nuuid = \"dbb5928d-eab1-5f90-85c2-b9b0edb7c900\"\nversion = \"0.4.1\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MathOptInterface]]\ndeps = [\"BenchmarkTools\", \"CodecBzip2\", \"CodecZlib\", \"JSON\", \"JSONSchema\", \"LinearAlgebra\", \"MutableArithmetics\", \"OrderedCollections\", \"SparseArrays\", \"Test\", \"Unicode\"]\ngit-tree-sha1 = \"575644e3c05b258250bb599e57cf73bbf1062901\"\nuuid = \"b8f27783-ece8-5eb3-8dc8-9495eed66fee\"\nversion = \"0.9.22\"\n\n[[MathProgBase]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"9abbe463a1e9fc507f12a69e7f29346c2cdc472c\"\nuuid = \"fdba3010-5040-5b88-9595-932c9decdf73\"\nversion = \"0.7.8\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[Mocking]]\ndeps = [\"Compat\", \"ExprTools\"]\ngit-tree-sha1 = \"29714d0a7a8083bba8427a4fbfb00a540c681ce7\"\nuuid = \"78c3b35d-d492-501b-9361-3d52fe80e533\"\nversion = \"0.7.3\"\n\n[[MosaicViews]]\ndeps = [\"MappedArrays\", \"OffsetArrays\", \"PaddedViews\", \"StackViews\"]\ngit-tree-sha1 = \"b34e3bc3ca7c94914418637cb10cc4d1d80d877d\"\nuuid = \"e94cdb99-869f-56ef-bcf0-1ae2bcbe0389\"\nversion = \"0.3.3\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[MutableArithmetics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"Test\"]\ngit-tree-sha1 = \"8d9496b2339095901106961f44718920732616bb\"\nuuid = \"d8a4904e-b15c-11e9-3269-09a3773c0cb0\"\nversion = \"0.2.22\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"b086b7ea07f8e38cf122f5016af580881ac914fe\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.7\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[OSQP]]\ndeps = [\"BinaryProvider\", \"Libdl\", \"LinearAlgebra\", \"MathOptInterface\", \"MathProgBase\", \"OSQP_jll\", \"SparseArrays\"]\ngit-tree-sha1 = \"1231412a185b8c160111bdfa0c186108e2b5c049\"\nuuid = \"ab2f91bb-94b4-55e3-9ba0-7f65df51de79\"\nversion = \"0.6.1\"\n\n[[OSQP_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d0f73698c33e04e557980a06d75c2d82e3f0eb49\"\nuuid = \"9c4f68bf-6205-5545-a508-2878b064d984\"\nversion = \"0.600.200+0\"\n\n[[OffsetArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"043017e0bdeff61cfbb7afeb558ab29536bbb5ed\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.8\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"887579a3eb005446d514ab7aeac5d1d027658b8f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+1\"\n\n[[OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"648107615c15d4e09f7eca16307bc821c1f718d8\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.13+0\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[PDMats]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"SuiteSparse\"]\ngit-tree-sha1 = \"ee26b350276c51697c9c2d88a072b339f9f03d73\"\nuuid = \"90014a1f-27ba-587c-ab20-58faa44d9150\"\nversion = \"0.11.5\"\n\n[[PaddedViews]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"03a7a85b76381a3d04c7a1656039197e70eda03d\"\nuuid = \"5432bcbf-9aad-5242-b902-cca2824c8663\"\nversion = \"0.5.11\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b5cfbb704034b5b4c1869e36634438a047df065\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.2.1\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"6f1b25e8ea06279b5689263cc538f51331d7ca17\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.1.3\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\", \"UnicodeFun\", \"Unzip\"]\ngit-tree-sha1 = \"7e4920a7d4323b8ffc3db184580598450bde8a8e\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.25.7\"\n\n[[PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"ColorTypes\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"ae6145ca68947569058866e443df69587acc1806\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.32\"\n\n[[Polynomials]]\ndeps = [\"Intervals\", \"LinearAlgebra\", \"OffsetArrays\", \"RecipesBase\"]\ngit-tree-sha1 = \"0b15f3597b01eb76764dd03c3c23d6679a3c32c8\"\nuuid = \"f27b6e38-b328-58d1-80ce-0feddd5e7a45\"\nversion = \"1.2.1\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"2cf929d64681236a2e074ffafb8d568733d2e6af\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.3\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Profile]]\ndeps = [\"Printf\"]\nuuid = \"9abbd945-dff8-562f-b5e8-e1ebf5ef1b79\"\n\n[[ProximalAlgorithms]]\ndeps = [\"LinearAlgebra\", \"Printf\", \"ProximalOperators\"]\ngit-tree-sha1 = \"55476be8224b3db55f0bf862f2f84ac8597aaae5\"\nuuid = \"140ffc9f-1907-541a-a177-7475e0a401e9\"\nversion = \"0.4.1\"\n\n[[ProximalOperators]]\ndeps = [\"IterativeSolvers\", \"LinearAlgebra\", \"OSQP\", \"SparseArrays\", \"SuiteSparse\", \"TSVD\"]\ngit-tree-sha1 = \"d32ba50ff3e3192a3d4b9510618b9670d6925009\"\nuuid = \"a725b495-10eb-56fe-b38b-717eba820537\"\nversion = \"0.14.2\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[QuadGK]]\ndeps = [\"DataStructures\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"78aadffb3efd2155af139781b8a8df1ef279ea39\"\nuuid = \"1fd47b50-473d-5c70-9696-f719f8f3bcdc\"\nversion = \"2.4.2\"\n\n[[QuartzImageIO]]\ndeps = [\"FileIO\", \"ImageCore\", \"Libdl\"]\ngit-tree-sha1 = \"16de3b880ffdfbc8fc6707383c00a2e076bb0221\"\nuuid = \"dca85d43-d64c-5e67-8c65-017450d5d020\"\nversion = \"0.7.4\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RangeArrays]]\ngit-tree-sha1 = \"b9039e93773ddcfc828f12aadf7115b4b4d225f5\"\nuuid = \"b3c3ace0-ae52-54e7-9d0b-2c1406fd6b9d\"\nversion = \"0.3.2\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.2.1\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"37c1631cb3cc36a535105e6d5557864c82cd8c2b\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.5.0\"\n\n[[RecursiveArrayTools]]\ndeps = [\"Adapt\", \"ArrayInterface\", \"ChainRulesCore\", \"DocStringExtensions\", \"FillArrays\", \"LinearAlgebra\", \"RecipesBase\", \"Requires\", \"StaticArrays\", \"Statistics\", \"ZygoteRules\"]\ngit-tree-sha1 = \"5144e1eafb2ecc75765888a4bdcd3a30a6a08b14\"\nuuid = \"731186ca-8d62-57ce-b412-fbd966d074cd\"\nversion = \"2.24.1\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[RelocatableFolders]]\ndeps = [\"SHA\", \"Scratch\"]\ngit-tree-sha1 = \"cdbd3b1338c72ce29d9584fdbe9e9b70eeb5adca\"\nuuid = \"05181044-ff0b-4ac5-8273-598c1e38db00\"\nversion = \"0.1.3\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.3.0\"\n\n[[Rmath]]\ndeps = [\"Random\", \"Rmath_jll\"]\ngit-tree-sha1 = \"bf3188feca147ce108c76ad82c2792c57abe7b1f\"\nuuid = \"79098fc4-a85e-5d69-aa6a-4863f24498fa\"\nversion = \"0.7.0\"\n\n[[Rmath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"68db32dff12bb6127bac73c209881191bf0efbb7\"\nuuid = \"f50d1b31-88e8-58de-be2c-1cc44531875f\"\nversion = \"0.3.0+0\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"f0bccf98e16759818ffc5d97ac3ebf87eb950150\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.8.1\"\n\n[[StackViews]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"46e589465204cd0c08b4bd97385e4fa79a0c770c\"\nuuid = \"cae243ae-269e-4f55-b966-ac2d0dc13c15\"\nversion = \"0.1.1\"\n\n[[Static]]\ndeps = [\"IfElse\"]\ngit-tree-sha1 = \"b4912cd034cdf968e06ca5f943bb54b17b97793a\"\nuuid = \"aedffcd0-7271-4cad-89d0-dc628f76c6d3\"\nversion = \"0.5.1\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"2884859916598f974858ff01df7dfc6c708dd895\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.3.3\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"d88665adc9bcf45903013af0982e2fd05ae3d0a6\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.2.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"51383f2d367eb3b444c961d485c565e4c0cf4ba0\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.14\"\n\n[[StatsFuns]]\ndeps = [\"ChainRulesCore\", \"InverseFunctions\", \"IrrationalConstants\", \"LogExpFunctions\", \"Reexport\", \"Rmath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"f35e1879a71cca95f4826a14cdbf0b9e253ed918\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.15\"\n\n[[StringDistances]]\ndeps = [\"Distances\", \"StatsAPI\"]\ngit-tree-sha1 = \"ceeef74797d961aee825aabf71446d6aba898acb\"\nuuid = \"88034a9c-02f8-509d-84a9-84ec65e18404\"\nversion = \"0.11.2\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"d21f2c564b21a202f4677c0fba5b5ee431058544\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.4\"\n\n[[StructuredOptimization]]\ndeps = [\"AbstractOperators\", \"DSP\", \"FFTW\", \"LinearAlgebra\", \"ProximalAlgorithms\", \"ProximalOperators\", \"RecursiveArrayTools\"]\ngit-tree-sha1 = \"35bc5ae5ba1177ee119fabf40980d799c06b4ed2\"\nuuid = \"46cd3e9d-64ff-517d-a929-236bc1a1fc9d\"\nversion = \"0.3.0\"\n\n[[SuiteSparse]]\ndeps = [\"Libdl\", \"LinearAlgebra\", \"Serialization\", \"SparseArrays\"]\nuuid = \"4607b0f0-06f3-5cda-b6b1-a6196a1729e9\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TSVD]]\ndeps = [\"Adapt\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"61cd1ce64b4ffb69e2d156ff7166a8eb796d699a\"\nuuid = \"9449cd9e-2762-5aa3-a617-5413e99d722e\"\nversion = \"0.4.3\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"bb1064c9a84c52e277f1096cf41434b675cd368b\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.6.1\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[TensorCore]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"1feb45f88d133a655e001435632f019a9a1bcdb6\"\nuuid = \"62fd8b95-f654-4bbd-a8a5-9c27f68ccd50\"\nversion = \"0.1.1\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[TestImages]]\ndeps = [\"AxisArrays\", \"ColorTypes\", \"FileIO\", \"OffsetArrays\", \"Pkg\", \"StringDistances\"]\ngit-tree-sha1 = \"f91d170645a8ba6fbaa3ac2879eca5da3d92a31a\"\nuuid = \"5e47fb64-e119-507b-a336-dd2b206d9990\"\nversion = \"1.6.2\"\n\n[[TimeZones]]\ndeps = [\"Dates\", \"Downloads\", \"InlineStrings\", \"LazyArtifacts\", \"Mocking\", \"Printf\", \"RecipesBase\", \"Serialization\", \"Unicode\"]\ngit-tree-sha1 = \"0f1017f68dc25f1a0cb99f4988f78fe4f2e7955f\"\nuuid = \"f269a46b-ccf7-5d73-abea-4c690281aa53\"\nversion = \"1.7.1\"\n\n[[TranscodingStreams]]\ndeps = [\"Random\", \"Test\"]\ngit-tree-sha1 = \"216b95ea110b5972db65aa90f88d8d89dcb8851c\"\nuuid = \"3bb67fe8-82b1-5028-8e26-92a6c54297fa\"\nversion = \"0.9.6\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[UnicodeFun]]\ndeps = [\"REPL\"]\ngit-tree-sha1 = \"53915e50200959667e78a92a418594b428dffddf\"\nuuid = \"1cfade01-22cf-5700-b092-accc4b62d6e1\"\nversion = \"0.4.1\"\n\n[[Unzip]]\ngit-tree-sha1 = \"34db80951901073501137bdbc3d5a8e7bbd06670\"\nuuid = \"41fe7b60-77ed-43a1-b4f0-825fd5a5650d\"\nversion = \"0.1.2\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"66d72dc6fcc86352f01676e8f0f698562e60510f\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.23.0+0\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[ZygoteRules]]\ndeps = [\"MacroTools\"]\ngit-tree-sha1 = \"8c1a8e4dfacb1fd631745552c8db35d0deb09ea0\"\nuuid = \"700de1a5-db45-46bc-99cf-38207098b444\"\nversion = \"0.2.2\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"b910cb81ef3fe6e78bf6acee440bda86fd6ae00c\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+1\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╠═a5d4303a-81b0-11ec-1083-ed13a1d29807\n# ╟─f4cb8cfd-b6b1-4e93-9985-2c71b384093f\n# ╠═62a8366f-14dc-410b-ba31-a8f695dfe986\n# ╠═97006203-2819-489d-a4dc-cef3af6e72b3\n# ╠═7415fc09-1155-49e5-b523-c9df2bd8d7d7\n# ╠═bc36eb16-5b31-4639-864c-4ee4b627108e\n# ╟─56a83328-2689-42be-8dfd-8ee38c5a70e0\n# ╟─6e37dfac-5f50-498b-b356-f56fcbd7d02a\n# ╟─68a5c2c4-e1ca-420d-b421-c4f570308884\n# ╟─39f25941-cab4-4776-9167-5b75d555fdbf\n# ╟─c899003d-bee5-4857-919a-8007d22c9f90\n# ╟─135c1b29-8e82-4d06-b2f6-ff6fa7e3f031\n# ╟─832052d7-c34d-4bce-8236-64cdc8f32be5\n# ╟─df23221a-1dc6-4f45-9f03-35bc12c48e46\n# ╠═7a9864b2-fc6f-4b89-8efa-183d644f8943\n# ╠═d32b08c7-8262-4231-9469-df9f667e5c59\n# ╟─c490029b-2b61-42c4-bd5f-72ba844e03b0\n# ╟─7a104d94-6062-47a2-82cb-553513e28a86\n# ╟─2bef7c97-8b88-4203-8825-eda70d5fab56\n# ╠═9c19aaf2-3c25-425b-9e48-4d90d1366ce2\n# ╠═4d4ec391-7219-459a-9b49-6ba901eeae92\n# ╟─57a799e2-68b2-4867-867a-24d8590a84a5\n# ╟─7c3a2e4b-419f-44f1-bea7-20c7a3aa06a3\n# ╟─84e6d7fb-4df6-498b-bd5c-151004756e9e\n# ╟─afb35a7d-1454-4c8f-a230-daabafc8e7a3\n# ╟─ef90c37f-0e7e-48d1-8ab3-4ae779c3ed91\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "cfdfc921d058254d4ab91b630cd59cb47cbf8df4", "size": 67429, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebook/CompressedSensing.jl", "max_stars_repo_name": "yejiBae/STMOZOO", "max_stars_repo_head_hexsha": "8fa021726d69f64f5b17427ba08ee095ee72bfb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebook/CompressedSensing.jl", "max_issues_repo_name": "yejiBae/STMOZOO", "max_issues_repo_head_hexsha": "8fa021726d69f64f5b17427ba08ee095ee72bfb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebook/CompressedSensing.jl", "max_forks_repo_name": "yejiBae/STMOZOO", "max_forks_repo_head_hexsha": "8fa021726d69f64f5b17427ba08ee095ee72bfb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-12-10T09:37:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T14:22:18.000Z", "avg_line_length": 40.1602144133, "max_line_length": 932, "alphanum_fraction": 0.7444719631, "num_tokens": 27408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7606452311539021}}
{"text": "#########################################################################\r\n# Insolation\r\n#########################################################################\r\n#=\r\nCode originally from:\r\nhttps://github.com/climate-machine/RRTMGP.jl/blob/master/src/rte/SolarZenithAngle.jl\r\n\r\nwith examples at:\r\nhttps://climate-machine.github.io/RRTMGP.jl/latest/RTE/SolarZenithAngle.html\r\n\r\nThe physics and details about the algorithm\r\ncan be found in Tapio Schneider’s book Physics of the Earth's Climate, section 3.4\r\nhttp://climate-dynamics.org/wp-content/uploads/2017/04/Climate_Book.pdf\r\n=#\r\nexport insolation, monthly_insolation\r\n\"\"\"\r\n    insolation(t, ϕ; kwargs...)\r\nCalculate daily averaged insolation in W/m² at given time and latitude `t, φ`.\r\n`φ` is given in **degrees**, and `t` in **days** (real number or date).\r\n\r\nKeywords:\r\n```\r\nYa = DAYS_IN_YEAR # = 365.26 # days\r\nt_VE = 76.0 # days of vernal equinox\r\nS_0 = 1362.0 # W/m^2\r\nγ=23.44\r\nϖ=282.95\r\ne=0.017 # eccentricity\r\n```\r\n\"\"\"\r\ninsolation(t::TimeType, φ; kwargs...) = insolation(float(dayofyear(t)), φ; kwargs...)\r\nfunction insolation(t::Real, ϕ;\r\n        Ya = DAYS_IN_YEAR, # = 365.26 # days\r\n        t_VE = 76.0, # days since Jan 1\r\n        S_0 = 1362.0, # W/m^2\r\n        γ=23.44,\r\n        ϖ=282.95,\r\n        e=0.017,\r\n    )\r\n\r\n    # convert inputs from degrees to radians\r\n    ϕ = ϕ * π / 180\r\n    γ = γ * π / 180\r\n    ϖ = ϖ * π / 180\r\n\r\n    # step 1, calculate the mean anomaly at vernal equinox\r\n    β = sqrt(1 - e^2)\r\n    M_VE = -ϖ + (e + e^3 / 4) * (1 + β) * sin(ϖ)\r\n\r\n    # step 2, calculate the mean anomaly\r\n    M = (2 * π * (t - t_VE)) / (Ya) + M_VE\r\n\r\n    # step 3, calculate the true anomaly\r\n    A = M + (2 * e - e^3 / 4) * sin(M)\r\n\r\n    # step 4, calculate the distance to the sun\r\n    d = (1 - e^2) / (1 + e * cos(A))\r\n\r\n    # step 5, calculate the solar longitude\r\n    L_s = A + ϖ\r\n\r\n    # step 6, calculate the declination angle\r\n    δ = asin(sin(γ) * sin(L_s))\r\n\r\n    # step 7, calculate the sunrise/sunset angle\r\n    T = tan(ϕ) * tan(δ)\r\n    if T >= 1\r\n        η_d = π\r\n    elseif T <= -1\r\n        η_d = 0.0\r\n    else\r\n        η_d = acos(-1 * T)\r\n    end\r\n\r\n    # step 8, calculate the daily averaged cos(zenith angle)\r\n    c1 = η_d * sin(ϕ) * sin(δ)\r\n    c2 = cos(ϕ) * cos(δ) * sin(η_d)\r\n    cosbar = (1 / π) * (c1 + c2)\r\n\r\n    # step 9, calculate the flux\r\n    F = S_0 * (1 / d)^2 * cosbar\r\n    return F\r\nend\r\n", "meta": {"hexsha": "fb62532af16993042e70293184db15a9a55597aa", "size": 2386, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/climate/solar.jl", "max_stars_repo_name": "Lucalino/ClimateBase.jl", "max_stars_repo_head_hexsha": "2ae5c2b68897097304e6c9988a03d0c0c6a9b8e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/climate/solar.jl", "max_issues_repo_name": "Lucalino/ClimateBase.jl", "max_issues_repo_head_hexsha": "2ae5c2b68897097304e6c9988a03d0c0c6a9b8e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/climate/solar.jl", "max_forks_repo_name": "Lucalino/ClimateBase.jl", "max_forks_repo_head_hexsha": "2ae5c2b68897097304e6c9988a03d0c0c6a9b8e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4047619048, "max_line_length": 86, "alphanum_fraction": 0.5347862531, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452771, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7606343067415453}}
{"text": "#' ---\r\n#' title: Conic Programming\r\n#' ---\r\n\r\n#' **Originally Contributed by**: Arpit Bhatia\r\n\r\n#' This tutorial is aimed at providing a simplistic introduction to conic programming using JuMP.\r\n\r\n#' ## What is a Cone?\r\n#' A subset $C$ of a vector space $V$ is a cone if $\\forall x \\in C$ and positive scalars $\\alpha$,\r\n#' the product $\\alpha x \\in C$. A cone C is a convex cone if $\\alpha x + \\beta y \\in C$,\r\n#' for any positive scalars $\\alpha, \\beta$, and any $x, y \\in C$.\r\n\r\n#' ## Conic Programming\r\n#' Conic programming problems are convex optimization problems in which a convex function is minimized\r\n#' over the intersection of an affine subspace and a convex cone.\r\n#' An example of a conic-form minimization problems, in the primal form is:\r\n\r\n#' $$\r\n#' \\begin{align}\r\n#' & \\min_{x \\in \\mathbb{R}^n} & a_0^T x + b_0 \\\\\r\n#' & \\;\\;\\text{s.t.} & A_i x + b_i & \\in \\mathcal{C}_i & i = 1 \\ldots m\r\n#' \\end{align}\r\n#' $$\r\n\r\n#' The corresponding dual problem is:\r\n\r\n#' $$\r\n#' \\begin{align}\r\n#' & \\max_{y_1, \\ldots, y_m} & -\\sum_{i=1}^m b_i^T y_i + b_0 \\\\\r\n#' & \\;\\;\\text{s.t.} & a_0 - \\sum_{i=1}^m A_i^T y_i & = 0 \\\\\r\n#' & & y_i & \\in \\mathcal{C}_i^* & i = 1 \\ldots m\r\n#' \\end{align}\r\n#' $$\r\n\r\n#' where each $\\mathcal{C}_i$ is a closed convex cone and $\\mathcal{C}_i^*$ is its dual cone.\r\n\r\n#' ## Some of the Types of Cones Supported by JuMP\r\n\r\nusing JuMP\r\nusing ECOS\r\nusing LinearAlgebra\r\nusing Random\r\n\r\nRandom.seed!(1234);\r\n\r\n#' By this point we have used quite a few different solvers.\r\n#' To find out all the different solvers and their supported problem types, check out the\r\n#' [solver table](http://www.juliaopt.org/JuMP.jl/v0.19.0/installation/#Getting-Solvers-1) in the docs.\r\n\r\n#' ### Second-Order Cone\r\n#' The Second-Order Cone (or Lorenz Cone) of dimension $n$ is of the form:\r\n\r\n#' $$\r\n#' Q^n = \\{ (t,x) \\in \\mathbb{R}^\\mbox{n} : t \\ge ||x||_2 \\}\r\n#' $$\r\n\r\n#' A Second-Order Cone rotated by $\\pi/4$ in the $(x_1,x_2)$ plane is called a Rotated Second-Order Cone.\r\n#' It is of the form:\r\n\r\n#' $$\r\n#' Q_r^n = \\{ (t,u,x) \\in \\mathbb{R}^\\mbox{n} : 2tu \\ge ||x||_2^2, t,u \\ge 0 \\}\r\n#' $$\r\n\r\n#' These cones are represented in JuMP using the MOI sets `SecondOrderCone` and `RotatedSecondOrderCone`.\r\n\r\n#' #### Example: Euclidean Projection on a Hyperplane\r\n#' For a given point $u_{0}$ and a set $K$, we refer to any point $u \\in K$\r\n#' which is closest to $u_{0}$ as a projection of $u_{0}$ on $K$.\r\n#' The projection of a point $u_{0}$ on a hyperplane $K = \\{u | p' \\cdot u = q\\}$ is given by\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' & \\min & ||u - u_{0}|| \\\\\r\n#' & \\;\\;\\text{s.t.} & p' \\cdot u = q  \\\\\r\n#' \\end{align*}\r\n#' $$\r\n\r\nu0 = rand(10)\r\np = rand(10)\r\nq = rand();\r\n\r\n#' We can model the above problem as the following conic program:\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' & \\min & t \\\\\r\n#' & \\;\\;\\text{s.t.} & p' \\cdot u = q \\\\\r\n#' & & (t, u - u_{0}) \\in Q^{n+1}\r\n#' \\end{align*}\r\n#' $$\r\n\r\n#' On comparing this with the primal form of a conic problem we saw above,\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' & x = (t , u) &\\\\\r\n#' & a_0 = e_1 &\\\\\r\n#' & b_0 = 0 &\\\\\r\n#' & A_1 = (0, p) &\\\\\r\n#' & b_1 = -q &\\\\\r\n#' & C_1 = \\mathbb{R}_- &\\\\\r\n#' & A_2 = 1 &\\\\\r\n#' & b_2 = -(0, u_0) &\\\\\r\n#' & C_2 = Q^{n+1} &\r\n#' \\end{align*}\r\n#' $$\r\n\r\n#' Thus, we can obtain the dual problem as:\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' & \\max & y_1 + (0, u_0)^T y_2 \\\\\r\n#' & \\;\\;\\text{s.t.} & e_1 - (0,p)^T y_1 - y_2 = 0 \\\\\r\n#' & & y_1 \\in \\mathbb{R}_- \\\\\r\n#' & & y_2 \\in Q^{n+1}\r\n#' \\end{align*}\r\n#' $$\r\n\r\nmodel = Model(optimizer_with_attributes(ECOS.Optimizer, \"printlevel\" => 0))\r\n@variable(model, u[1:10])\r\n@variable(model, t)\r\n@objective(model, Min, t)\r\n@constraint(model, [t, (u - u0)...] in SecondOrderCone())\r\n@constraint(model, u' * p == q)\r\noptimize!(model)\r\n\r\n#+\r\n\r\n@show objective_value(model);\r\n@show value.(u);\r\n\r\n#+\r\n\r\ne1 = [1, zeros(10)...]\r\ndual_model = Model(optimizer_with_attributes(ECOS.Optimizer, \"printlevel\" => 0))\r\n@variable(dual_model, y1 <= 0)\r\n@variable(dual_model, y2[1:11])\r\n@objective(dual_model, Max, q * y1 + dot(vcat(0, u0), y2))\r\n@constraint(dual_model, e1 - [0, p...] .* y1 - y2 .== 0)\r\n@constraint(dual_model, y2 in SecondOrderCone())\r\noptimize!(dual_model)\r\n\r\n#+\r\n\r\n@show objective_value(dual_model);\r\n\r\n\r\n#' We can also have an equivalent formulation using a Rotated Second-Order Cone:\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' & \\min & t \\\\\r\n#' & \\;\\;\\text{s.t.} & p' \\cdot u = q \\\\\r\n#' & & (t, 1/2, u - u_{0})\\in Q_r^{n+2}\r\n#' \\end{align*}\r\n#' $$\r\n\r\nmodel = Model(optimizer_with_attributes(ECOS.Optimizer, \"printlevel\" => 0))\r\n@variable(model, u[1:10])\r\n@variable(model, t)\r\n@objective(model, Min, t)\r\n@constraint(model, [t, 0.5, (u - u0)...] in RotatedSecondOrderCone())\r\n@constraint(model, u' * p == q)\r\noptimize!(model)\r\n\r\n#+\r\n\r\n@show value.(u);\r\n\r\n#' The difference here is that the objective in the case of the Second-Order Cone is $||u - u_{0}||_2$,\r\n#' while in the case of a Rotated Second-Order Cone is $||u - u_{0}||_2^2$.\r\n#' However, the value of x is the same for both.\r\n\r\n#' ### Exponential Cone\r\n\r\n#' An Exponential Cone is a set of the form:\r\n\r\n#' $$\r\n#' K_{exp} = \\{ (x,y,z) \\in \\mathbb{R}^3 : y \\exp (x/y) \\le z, y > 0 \\}\r\n#' $$\r\n\r\n#' It is represented in JuMP using the MOI set `ExponentialCone`.\r\n\r\n#' #### Example: Entropy Maximization\r\n#' As the name suggests, the entropy maximization problem consists of maximizing the entropy function,\r\n#' $H(x) = -x\\log{x}$ subject to linear inequality constraints.\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' & \\max & - \\sum_{i=1}^n x_i \\log x_i \\\\\r\n#' & \\;\\;\\text{s.t.} & \\mathbf{1}' x = 1 \\\\\r\n#' & & Ax \\leq b\r\n#' \\end{align*}\r\n#' $$\r\n\r\n#' We can model this problem using an exponential cone by using the following transformation:\r\n\r\n#' $$\r\n#' t\\leq -x\\log{x} \\iff t\\leq x\\log(1/x)  \\iff (1, x, t) \\in K_{exp}\r\n#' $$\r\n\r\n#' Thus, our problem becomes,\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' & \\max & 1^Tt \\\\\r\n#' & \\;\\;\\text{s.t.} & Ax \\leq b \\\\\r\n#' & & 1^T x = 1 \\\\\r\n#' & & (1, x_i, t_i) \\in K_{exp} && \\forall i = 1 \\ldots n \\\\\r\n#' \\end{align*}\r\n#' $$\r\n\r\nn = 15;\r\nm = 10;\r\nA = randn(m, n);\r\nb = rand(m, 1);\r\n\r\nmodel = Model(optimizer_with_attributes(ECOS.Optimizer, \"printlevel\" => 0))\r\n@variable(model, t[1:n])\r\n@variable(model, x[1:n])\r\n@objective(model, Max, sum(t))\r\n@constraint(model, sum(x) == 1)\r\n@constraint(model, A * x .<= b )\r\n# Cannot use the exponential cone directly in JuMP, hence we use MOI to specify the set.\r\n@constraint(model, con[i = 1:n], [1, x[i], t[i]] in MOI.ExponentialCone())\r\n\r\noptimize!(model);\r\n\r\n#+\r\n\r\n@show objective_value(model);\r\n\r\n#' ### Positive Semidefinite Cone\r\n#' The set of Positive Semidefinite Matrices of dimension $n$ form a cone in $\\mathbb{R}^n$.\r\n#' We write this set mathematically as\r\n\r\n#' $$\r\n#' \\mathcal{S}_{+}^n = \\{ X \\in \\mathcal{S}^n \\mid z^T X z \\geq 0, \\: \\forall z\\in \\mathbb{R}^n \\}.\r\n#' $$\r\n\r\n#' A PSD cone is represented in JuMP using the MOI sets\r\n#' `PositiveSemidefiniteConeTriangle` (for upper triangle of a PSD matrix) and\r\n#' `PositiveSemidefiniteConeSquare` (for a complete PSD matrix).\r\n#' However, it is prefferable to use the `PSDCone` shortcut as illustrated below.\r\n\r\n#' #### Example: Largest Eigenvalue of a Symmetric Matrix\r\n#' Suppose $A$ has eigenvalues $\\lambda_{1} \\geq \\lambda_{2} \\ldots \\geq \\lambda_{n}$.\r\n#' Then the matrix $t I-A$ has eigenvalues $t-\\lambda_{1}, t-\\lambda_{2}, \\ldots, t-\\lambda_{n}$.\r\n#' Note that $t I-A$ is PSD exactly when all these eigenvalues are non-negative,\r\n#' and this happens for values $t \\geq \\lambda_{1} .$\r\n#' Thus, we can model the problem of finding the largest eigenvalue of a symmetric matrix as:\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' \\lambda_{1} = \\max t \\\\\r\n#' \\text { s.t. } t I-A \\succeq 0\r\n#' \\end{align*}\r\n#' $$\r\n\r\n#+ tangle = false\r\n\r\nusing LinearAlgebra\r\nusing SCS\r\n\r\nA = [3 2 4;\r\n     2 0 2;\r\n     4 2 3]\r\n\r\nmodel = Model(optimizer_with_attributes(SCS.Optimizer, \"verbose\" => 0))\r\n@variable(model, t)\r\n@objective(model, Min, t)\r\n@constraint(model, t .* Matrix{Float64}(I, 3, 3) - A in PSDCone())\r\n\r\noptimize!(model)\r\n\r\n#+ tangle = false\r\n\r\n@show objective_value(model);\r\n\r\n#' ## Other Cones and Functions\r\n#' For other cones supported by JuMP, check out the\r\n#' [MathOptInterface Manual](http://www.juliaopt.org/MathOptInterface.jl/dev/apimanual/#Standard-form-problem-1).\r\n#' A good resource for learning more about functions which can be modelled using cones is the\r\n#' MOSEK Modeling Cookbook[[1]](#c1).\r\n\r\n#' ### References\r\n#' <a id='c1'></a>\r\n#' 1. MOSEK Modeling Cookbook — MOSEK Modeling Cookbook 3.1. Available at: https://docs.mosek.com/modeling-cookbook/index.html.\r\n", "meta": {"hexsha": "24469f9285009a17f806984d54eeb8ea4bf2fe37", "size": 8541, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/optimization_concepts/conic_programming.jl", "max_stars_repo_name": "frapac/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "55374d470e4e1b16a3a16f2ec7088ecf317b48b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-07T20:43:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-06T17:51:12.000Z", "max_issues_repo_path": "script/optimization_concepts/conic_programming.jl", "max_issues_repo_name": "frapac/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "55374d470e4e1b16a3a16f2ec7088ecf317b48b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/optimization_concepts/conic_programming.jl", "max_forks_repo_name": "frapac/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "55374d470e4e1b16a3a16f2ec7088ecf317b48b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4517241379, "max_line_length": 128, "alphanum_fraction": 0.5954806229, "num_tokens": 2888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813457476621, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7606342966212433}}
{"text": "function laplace_matrix(::Type{T}, n, dims) where T\n    D = second_order_central_diff(T, n);\n    A = copy(D);\n\n    for idx = 2 : dims\n        A = kron(A, speye(n)) + kron(speye(size(A, 1)), D);\n    end\n\n    A\nend\n\nsecond_order_central_diff(::Type{T}, dim) where {T} = convert(SparseMatrixCSC{T, Int}, SymTridiagonal(fill(2 * one(T), dim), fill(-one(T), dim - 1)))\n", "meta": {"hexsha": "fb44eb21d4f5d6922b2d7715607d2cfff825f57f", "size": 364, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/laplace_matrix.jl", "max_stars_repo_name": "tkf/IterativeSolvers.jl", "max_stars_repo_head_hexsha": "c1c6dedd8770fe65f307eef4cb92eaacc0535018", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/laplace_matrix.jl", "max_issues_repo_name": "tkf/IterativeSolvers.jl", "max_issues_repo_head_hexsha": "c1c6dedd8770fe65f307eef4cb92eaacc0535018", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/laplace_matrix.jl", "max_forks_repo_name": "tkf/IterativeSolvers.jl", "max_forks_repo_head_hexsha": "c1c6dedd8770fe65f307eef4cb92eaacc0535018", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0, "max_line_length": 149, "alphanum_fraction": 0.6071428571, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9559813501370535, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.7606342954815392}}
{"text": "\n\"\"\"\nVerify, that |A * Q - Q * T| ≈ 0\nA, Q and T must be Matrices with appropriate sizes.\n\"\"\"\nfunction checkfactors(A::AbstractMatrix{T1}, Q::AbstractMatrix{T2}, T::AbstractMatrix{T3}; atol::Real = zero(real(eltype(A))), rtol::Real = eps(real(eltype(A)))) where {T1<:Number, T2<:Number, T3<:Number}\n\n  res = norm(A * Q - Q * T, 1)\n  tol = rtol * norm(A, 1) + atol\n  # println(\"checkfactors() = $(Float64(res)) < ! $(Float64(tol)) $(Float64(res/tol))\")\n  res <= rtol * norm(A, 1) + atol\nend\n\n", "meta": {"hexsha": "f68d0054182432f48acb183400dd08496e1d1381", "size": 491, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/utils_test.jl", "max_stars_repo_name": "KlausC/LinAlgBigFloat", "max_stars_repo_head_hexsha": "5dcfbd8605d39cf0f82b8d4db4a7cafa0dbb3df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-08-03T02:29:42.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-03T02:29:42.000Z", "max_issues_repo_path": "test/utils_test.jl", "max_issues_repo_name": "KlausC/LinAlgBigFloat", "max_issues_repo_head_hexsha": "5dcfbd8605d39cf0f82b8d4db4a7cafa0dbb3df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/utils_test.jl", "max_forks_repo_name": "KlausC/LinAlgBigFloat", "max_forks_repo_head_hexsha": "5dcfbd8605d39cf0f82b8d4db4a7cafa0dbb3df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0714285714, "max_line_length": 204, "alphanum_fraction": 0.6130346232, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7606049437089245}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots, LaTeXStrings\n\tRandom.seed!(1)\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.26\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\talphas = [0.5, 1.5, 1]\n\tlam = 2\n\n\tlambda(dist::Weibull) = shape(dist)*scale(dist)^(-shape(dist))\n\ttheta(lam,alpha) = (alpha/lam)^(1/alpha)\n\n\tdists = [Weibull.(a,theta(lam,a)) for a in alphas]\n\n\thA(dist,x) = pdf(dist,x)/ccdf(dist,x)\n\thB(dist,x) = lambda(dist)*x^(shape(dist)-1)\nend\n\n# ╔═╡ 884176a0-21c0-11eb-06f8-55964a60d533\nbegin\n\txGrid = 0.01:0.01:10\n\thazardsA = [hA.(d,xGrid) for d in dists]\n\thazardsB = [hB.(d,xGrid) for d in dists]\n\n\tText(\"Maximum difference between implementations: $(maximum(maximum.(hazardsA-hazardsB)))\")\nend\n\n# ╔═╡ 8841a7b0-21c0-11eb-313a-bfa4eb49f351\nbegin\n\tCl = [:blue :red :green]\n\tLb = [L\"\\lambda=\" * string(lambda(d)) * \",   \" * L\"\\alpha =\" * string(shape(d)) \n\t\t\tfor d in dists]\n\n\tplot(xGrid, hazardsA, c=Cl, label=reshape(Lb, 1,:), xlabel=\"x\",\n\t\tylabel=\"Instantaneous failure rate\", xlims=(0,10), ylims=(0,10))\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.26\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═884176a0-21c0-11eb-06f8-55964a60d533\n# ╠═8841a7b0-21c0-11eb-313a-bfa4eb49f351\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "5d4b394577387cfbdc22645f115669cd5950e11f", "size": 1679, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.26.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.26.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.26.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 26.234375, "max_line_length": 92, "alphanum_fraction": 0.6974389518, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7606049277020542}}
{"text": "abstract type Angle <: Number end\n\nstruct Radian <: Angle\n    radians::Float64\nend\n\nstruct DMS <: Angle\n    seconds::Int\nend\n\nbegin\n    Degree(degrees::Integer) = Minute(degrees * 60)\n    Degree(deg::Integer, min::Integer) = Degree(deg) + Minute(min)\n    Degree(deg::Integer, min::Integer, secs::Integer) = Degree(deg, min) + Second(secs)\n\n    function Minute(minutes::Integer)\n        DMS(minutes * 60)\n    end\n\n    function Second(seconds::Integer)\n        DMS(seconds)\n    end \n\n    import Base: -, +, show, convert, *, /, promote_rule\n    +(Θ::DMS, α::DMS) = DMS(Θ.seconds + α.seconds)      \n    -(Θ::DMS, α::DMS) = DMS(Θ.seconds - α.seconds)\n\n    +(Θ::Radian, α::Radian) = Radian(Θ.radians + α.radians)\n    -(Θ::Radian, α::Radian) = Radian(Θ.radians - α.radians)\n\n    function degrees(dms::DMS)\n        minutes = dms.seconds ÷ 60\n        minutes ÷ 60\n    end\n\n    function minutes(dms::DMS)\n        minutes = dms.seconds ÷ 60\n        minutes % 60\n    end\n\n    seconds(dms::DMS) = dms.seconds % 60\n\n    function show(io::IO, dms::DMS)\n    print(io, degrees(dms), \"° \", minutes(dms), \"' \", seconds(dms), \"''\")\n    end\n\n    function show(io::IO, rad::Radian)\n    print(io, rad.radians, \"rad\")\n    end\n\n    # convert constructors\n    Radian(dms::DMS) = Radian(deg2rad(dms.seconds/3600))\n    DMS(rad::Radian) = DMS(floor(Int, rad2deg(rad.radians) * 3600))\n\n    convert(::Type{Radian},  dms::DMS)    = Radian(dms)\n    convert(::Type{DMS},     rad::Radian) = DMS(rad)\n\n    sin(rad::Radian) = Base.sin(rad.radians)\n    cos(rad::Radian) = Base.cos(rad.radians)\n\n    sin(dms::DMS) = sin(Radian(dms))\n    cos(dms::DMS) = cos(Radian(dms))\n\n    *(coeff::Number, dms::DMS) = DMS(coeff * dms.seconds)\n    *(dms::DMS, coeff::Number) = coeff * dms\n    /(dms::DMS, denom::Number) = DMS(dms.seconds/denom)\n\n    *(coeff::Number, rad::Radian) = Radian(coeff * rad.radians)\n    *(rad::Radian, coeff::Number) = coeff * rad\n    /(rad::Radian, denom::Number) = Radian(rad.radians/denom)\n\n    const ° = Degree(1)\n    const rad = Radian(1)\n\n    Base.promote_rule(::Type{Radian}, ::Type{DMS}) = Radian\nend\n# Examples\n# α = Degree(90, 30, 45)\n# β = α + Degree(89, 29, 15)\n# sin(Degree(90))\n# sin(Radian(π/2))\n# sin(90°)\n# sin(1.5rad)\n\n# Problem\n# While this works:\n# +(promote(90°,3.14rad/2)...)\n# 3.140796326794897rad\n# Doing this\n# 90°+ 3.14rad/2\n# gives this error\n# ERROR: MethodError: no method matching +(::DMS, ::Radian)\n# Closest candidates are:\n#   +(::Any, ::Any, ::Any, ::Any...) at operators.jl:560\n#   +(::DMS, ::DMS) at REPL[10]:1\n#   +(::Radian, ::Radian) at REPL[12]:1\n# Stacktrace:\n#  [1] top-level scope\n#    @ REPL[38]:1\n# Solution\n# For the solution to the problem see the discussion here\n# https://discourse.julialang.org/t/type-promotion-not-working-as-expected/65944\n# one solution to get the promotion to work is to subtype Angle from Number as above\n# Adding +(Angle, Angle) is probably more in the spirit of what Engheim is trying to do\n", "meta": {"hexsha": "b858572c571fa536b455023d67bc015351107d63", "size": 2939, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "angleunits.jl", "max_stars_repo_name": "FourMInfo/JuliaforBeginners", "max_stars_repo_head_hexsha": "4908cd82c777cc9934056bbada36bccd67158906", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "angleunits.jl", "max_issues_repo_name": "FourMInfo/JuliaforBeginners", "max_issues_repo_head_hexsha": "4908cd82c777cc9934056bbada36bccd67158906", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "angleunits.jl", "max_forks_repo_name": "FourMInfo/JuliaforBeginners", "max_forks_repo_head_hexsha": "4908cd82c777cc9934056bbada36bccd67158906", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9904761905, "max_line_length": 87, "alphanum_fraction": 0.6175569922, "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.76054525310034}}
{"text": "\"\"\"\n`solve_system(f,u0,n)` #code\n\nSolves the dynamical system\n\n``u_{n+1} = f(u_n)`` #latex\n\nfor N steps. Returns the solution at step `n` with parameters `p`.\n\n\"\"\"\nfunction solve_system(f,u0,p,n)\n  u = u0\n  for i in 1:n-1\n    u = f(u,p)\n  end\n  u\nend\n\nf(u,p) = u^2 - p*u\ntypeof(f)\n\nfunction lorenz(u,p)\n  α,σ,ρ,β = p\n  du1 = u[1] + α*(σ*(u[2]-u[1]))\n  du2 = u[2] + α*(u[1]*(ρ-u[3]) - u[2])\n  du3 = u[3] + α*(u[1]*u[2] - β*u[3])\n  [du1,du2,du3]\nend\np = (0.02,10.0,28.0,8/3)\n\nfunction solve_system_save(f,u0,p,n)\n  u = Vector{typeof(u0)}(undef,n)\n  u[1] = u0\n  for i in 1:n-1\n    u[i+1] = f(u[i],p)\n  end\n  u\nend\n\na = solve_system_save(lorenz,[1.0,0.0,0.0],p,1000)\n\na[1]\n\nreduce(hcat,a)\n\nusing BenchmarkTools\nfunction solve_system_save_matrix(f,u0,p,n)\n  u = Matrix{eltype(u0)}(undef,length(u0),n)\n  u[:,1] = u0\n  for i in 1:n-1\n    u[:,i+1] = f(u[:,i],p)\n  end\n  u\nend\n@btime solve_system_save_matrix(lorenz,[1.0,0.0,0.0],p,1000)\n@btime solve_system_save(lorenz,[1.0,0.0,0.0],p,1000)\n\nfunction solve_system_save_matrix_view(f,u0,p,n)\n  u = Matrix{eltype(u0)}(undef,length(u0),n)\n  u[:,1] = u0\n  for i in 1:n-1\n    u[:,i+1] = f(@view(u[:,i]),p)\n  end\n  u\nend\n@btime  solve_system_save_matrix_view(lorenz,[1.0,0.0,0.0],p,1000)\n\n\nfunction lorenz(du,u,p)\n  α,σ,ρ,β = p\n  du[1] = u[1] + α*(σ*(u[2]-u[1]))\n  du[2] = u[2] + α*(u[1]*(ρ-u[3]) - u[2])\n  du[3] = u[3] + α*(u[1]*u[2] - β*u[3])\nend\np = (0.02,10.0,28.0,8/3)\nfunction solve_system_save(f,u0,p,n)\n  u = Vector{typeof(u0)}(undef,n)\n  du = similar(u0) # create cache array, modify it, add to output\n  u[1] = u0\n  for i in 1:n-1\n    f(du,u[i],p)\n    u[i+1] = du\n  end\n  u\nend\n@btime solve_system_save(lorenz,[1.0,0.0,0.0],p,1000)\n\nfunction solve_system_save(f,u0,p,n)\n  u = Vector{typeof(u0)}(undef,n)\n  du = similar(u0) # create cache array, modify it, add to output\n  u[1] = u0\n  for i in 1:n-1\n    f(du,u[i],p)\n    u[i+1] = du[:]\n  end\n  u\nend\n@btime solve_system_save(lorenz,[1.0,0.0,0.0],p,1000)\n\nb = solve_system_save(lorenz,[1.0,0.0,0.0],p,1000)\n", "meta": {"hexsha": "6905f9c6e64ba8e6ebaaa63ee13d8fc44907c2d1", "size": 2000, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test3.jl", "max_stars_repo_name": "kosm6966/ExamplePackage.jl", "max_stars_repo_head_hexsha": "44d1a260e732a45aff03a3320ebe39f769c8600e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test3.jl", "max_issues_repo_name": "kosm6966/ExamplePackage.jl", "max_issues_repo_head_hexsha": "44d1a260e732a45aff03a3320ebe39f769c8600e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test3.jl", "max_forks_repo_name": "kosm6966/ExamplePackage.jl", "max_forks_repo_head_hexsha": "44d1a260e732a45aff03a3320ebe39f769c8600e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.801980198, "max_line_length": 66, "alphanum_fraction": 0.585, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.8807970889295663, "lm_q1q2_score": 0.7604728104789716}}
{"text": "# Examples presented in class - Lecture 1\n# LP Resource allocation\n\nusing JuMP, Cbc\n# JuMP is for implementing math. programming models;\n# Cbc is for solving them.\n\n# Example 1 - resource allocation\n\n# Problem data\ni = 1:2 # i=1: Seattle; i=2: San Diego\nj = 1:3 # j=1: New York; j=2: Chicago; j=3: Miami\n\nC = [350 600] # Capacities of the factories\nD = [325 300 275] # Demand of clients\nT = [2.5 1.7 1.8\n     3.5 1.9 1.4] # Transportation costs\n\n# Model implementation\n# Creates a model and informs the solver to be used\nm = Model(solver = CbcSolver())\n\n# Decision variable for the total transported\n@variable(m, x[i,j] >= 0)\n\n# Capacity constraint\n@constraint(m, cap[i = 1:2], sum(x[i,j] for j = 1:3) <= C[i])\n# Demand constraint\n@constraint(m, dem[j = 1:3], sum(x[i,j] for i = 1:2) >= D[j])\n\n# Total distribution cost that we want to minimise\n@objective(m, Min, sum(T[i,j]*x[i,j] for i=1:2, j=1:3))\n\nprintln(m) # Prints the mathematical model for debugging\nsolve(m) # Solve the model\n\n# Prints the optimal solution\nprintln(\"\\nDistribution plan: \\n\", getvalue(x))", "meta": {"hexsha": "024c65d5c253eb98bf4f6560e20bdfe3d5808139", "size": 1064, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/lectures/Lecture_1/Other/L1_Ex1-LP_resource_allocation.jl", "max_stars_repo_name": "gamma-opt/CourseParser.jl", "max_stars_repo_head_hexsha": "be59cf09c2c8b34373a6cd0f972f46528c4233dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/lectures/Lecture_1/Other/L1_Ex1-LP_resource_allocation.jl", "max_issues_repo_name": "gamma-opt/CourseParser.jl", "max_issues_repo_head_hexsha": "be59cf09c2c8b34373a6cd0f972f46528c4233dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/lectures/Lecture_1/Other/L1_Ex1-LP_resource_allocation.jl", "max_forks_repo_name": "gamma-opt/CourseParser.jl", "max_forks_repo_head_hexsha": "be59cf09c2c8b34373a6cd0f972f46528c4233dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0, "max_line_length": 61, "alphanum_fraction": 0.6785714286, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9817357227168956, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7604361886747768}}
{"text": "struct Connection\n    weight::AbstractArray\n    adjacency::AbstractArray\nend\n\nfunction randomConnection(n_source::Int, n_target::Int, p::AbstractFloat;\n    min_weight=0, max_weight=1, amplitude=nothing, seed=nothing)\n    if !isnothing(seed)\n        Random.seed!(seed)\n    end\n    adjacency = rand(n_source, n_target) .< p\n    if isnothing(amplitude)\n        weights = rand(n_source, n_target) .* (max_weight - min_weight) .+ min_weight\n    else\n        weights = ones(n_source, n_target) .* amplitude\n    end\n    weights .*= adjacency\n    return Connection(weights, adjacency)\nend\n\nfunction randomConnection(n::Int, p::AbstractFloat; min_weight=0, max_weight=1,\n    amplitude=nothing, seed=nothing)\n    randomConnection(n, n, p; min_weight, max_weight, amplitude, seed)\nend\n\n\n\nfunction EI(Nₑ::Integer, Nᵢ::Integer;\n    E_E::Tuple=(0, 1), E_I::Tuple=(0, 1), I_E::Tuple=(0, 1), I_I::Tuple=(0, 1),\n    adjacency::Union{Nothing,AbstractMatrix}=nothing, shuffle::Bool=false, seed=nothing\n)\n    excitatory = [ones(Bool, Nₑ); zeros(Bool, Nᵢ)]\n    if shuffle\n        if !isnothing(seed)\n            Random.seed!(seed)\n        end\n        shuffle!(excitatory)\n    end\n    inhibitory = .!excitatory\n\n    min_weight = (excitatory * transpose(excitatory)) .* E_E[1]\n    min_weight += (excitatory * transpose(inhibitory)) .* E_I[1]\n    min_weight -= (inhibitory * transpose(excitatory)) .* abs(I_E[2])\n    min_weight -= (inhibitory * transpose(inhibitory)) .* abs(I_I[2])\n\n    max_weight = (excitatory * transpose(excitatory)) .* E_E[2]\n    max_weight += (excitatory * transpose(inhibitory)) .* E_I[2]\n    max_weight -= (inhibitory * transpose(excitatory)) .* abs(I_E[1])\n    max_weight -= (inhibitory * transpose(inhibitory)) .* abs(I_I[1])\n\n    if !isnothing(adjacency)\n        min_weight .*= adjacency\n        max_weight .*= adjacency\n    end\n\n    return excitatory, inhibitory, min_weight, max_weight\nend\n\n\nfunction EI(n::Integer, EI_rate::AbstractFloat;\n    E_E::Tuple=(0, 1), E_I::Tuple=(0, 1), I_E::Tuple=(0, 1), I_I::Tuple=(0, 1),\n    adjacency::Union{Nothing,AbstractMatrix}=nothing, shuffle::Bool=false, seed=nothing\n)\n    if EI_rate > 1\n        Nₑ = Int(ceil(EI_rate * n / (EI_rate + 1)))\n    else\n        Nₑ = Int(ceil(EI_rate * n))\n    end\n    Nᵢ = n - Nₑ\n    return EI(Nₑ, Nᵢ; E_E, E_I, I_E, I_I, adjacency, shuffle, seed)\nend\n", "meta": {"hexsha": "284cb8eecb5d1ebce4733b341dd9c03929cec801", "size": 2328, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/connection.jl", "max_stars_repo_name": "mahbodnr/FastSpike.jl", "max_stars_repo_head_hexsha": "7498f6eb01e32ca25f8036dc026121e043aef1a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/connection.jl", "max_issues_repo_name": "mahbodnr/FastSpike.jl", "max_issues_repo_head_hexsha": "7498f6eb01e32ca25f8036dc026121e043aef1a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/connection.jl", "max_forks_repo_name": "mahbodnr/FastSpike.jl", "max_forks_repo_head_hexsha": "7498f6eb01e32ca25f8036dc026121e043aef1a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3333333333, "max_line_length": 87, "alphanum_fraction": 0.6533505155, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.7604162377855084}}
{"text": "\n@doc raw\"\"\"\nCompute δL = L(0)-L(h) where L is the quadratic model\n\n```math\nL(h)=f(\\theta) + \\langle \\nabla f, h \\rangle + \\frac{1}{2}\\langle \\nabla^2 f h, h \\rangle\n```\n\nwith ``f(\\theta)=\\frac{1}{2}\\| r(θ) \\|_2^2``, ``\\nabla f = J^t r`` and ``\\nabla^2 f = J^t J``\n\nA direct computation gives:\n\n\n```math\nδL = L(0)-L(h) = -\\left(  \\langle J^tr, h \\rangle + \\frac{1}{2}\\langle \\nabla^2 f h, h \\rangle \\right)\n```\n\nHowever one can avoid the computation of ``\\nabla^2 f h`` if one uses the\nfact that ``h`` is solution of:\n\n```math\n(\\nabla^2 f + \\mu I)h + \\nabla f = 0\n```\n\nWith this hypothesis, one gets:\n\n```math\nδL = L(0)-L(h) = \\frac{1}{2} \\langle h, \\mu h - \\nabla f \\rangle\n```\n\"\"\"\nfunction compute_δL_unconstrained(∇f::AbstractVector,\n                                  μ::Real,\n                                  h::AbstractVector)\n\n    # The syntax to desctructure is unexpected... \n    # https://discourse.julialang.org/t/argument-destructuring-and-anonymous-functions/24893/2\n    #\n    mapreduce(((h_i,∇f_i),)->h_i*(μ*h_i-∇f_i),+,zip(h,∇f))/2\nend\n\n\n@doc raw\"\"\"\n\nSame idea than [`compute_δL_unconstrained`](@ref), however when bound\nconstraints are present ``h`` is such that:\n\n```math\n(\\nabla^2 f + \\mu I)h + \\nabla f + \\tau = 0\n```\nit follows that:\n\n```math\nδL = L(0)-L(h) = \\frac{1}{2} \\langle h, \\mu h + \\tau - \\nabla f \\rangle\n```\n\"\"\"\nfunction compute_δL_constrained(∇f::AbstractVector,\n                                μ::Real,\n                                τ::AbstractVector,\n                                h::AbstractVector)\n    mapreduce(((h_i,τ_i,∇f_i),)->h_i*(μ*h_i+τ_i-∇f_i),+,zip(h,τ,∇f))/2\nend\n\n\n@doc raw\"\"\"\n\nCompute true variation of the real model: ``δf = \\frac{1}{2}(r^t(θ)r(θ)-r^t(θ+h)r(θ+h))``\n\nContrary to ``δL`` things are simpler. However a trick is to use an equivalent formulation:\n\n```math\nδf = \\frac{1}{2}(r^t(θ)r(θ)-r^t(θ+h)r(θ+h)) = \\frac{1}{2}(r(θ)-r(θ+h))^t(r(θ)+r(θ+h))\n```\n\nthat has a better numerical behavior. \n\"\"\"\nfunction compute_δf(r::AbstractVector,\n                    r_new::AbstractVector)\n    mapreduce(((r_i,r_new_i),)->(r_i-r_new_i)*(r_i+r_new_i),+,zip(r,r_new))/2\nend\n", "meta": {"hexsha": "749aa1c458323ce542102f7ec21dba982ecb1083", "size": 2118, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Levenberg-Marquardt/rho.jl", "max_stars_repo_name": "vincent-picaud/NLS_Solver.jl", "max_stars_repo_head_hexsha": "55d1a21e2128427ce168579ee67bde6f3499870b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-02T14:49:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T19:49:40.000Z", "max_issues_repo_path": "src/Levenberg-Marquardt/rho.jl", "max_issues_repo_name": "vincent-picaud/NLS_Solver.jl", "max_issues_repo_head_hexsha": "55d1a21e2128427ce168579ee67bde6f3499870b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-12-25T23:06:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-30T21:04:01.000Z", "max_forks_repo_path": "src/Levenberg-Marquardt/rho.jl", "max_forks_repo_name": "vincent-picaud/NLS_Solver.jl", "max_forks_repo_head_hexsha": "55d1a21e2128427ce168579ee67bde6f3499870b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.475, "max_line_length": 102, "alphanum_fraction": 0.5670443815, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7604162363924976}}
{"text": "# indicator of the L0 norm ball with given (integer) radius\n\nexport IndBallL0\n\n\"\"\"\n**Indicator of a ``L_0`` pseudo-norm ball**\n\n    IndBallL0(r=1)\n\nReturns the indicator function of the set\n```math\nS = \\\\{ x : \\\\mathrm{nnz}(x) \\\\leq r \\\\}.\n```\nParameter `r` must be a positive integer.\n\"\"\"\nstruct IndBallL0{I <: Integer} <: ProximableFunction\n  r::I\n  function IndBallL0{I}(r::I) where {I <: Integer}\n    if r <= 0\n      error(\"parameter r must be a positive integer\")\n    else\n      new(r)\n    end\n  end\nend\n\nis_set(f::IndBallL0) = true\n\nIndBallL0(r::I) where {I <: Integer} = IndBallL0{I}(r)\n\nfunction (f::IndBallL0)(x::AbstractArray{T}) where T <: RealOrComplex\n  if count(!isequal(0), x) > f.r\n    return +Inf\n  end\n  return zero(T)\nend\n\nfunction prox!(y::AbstractArray{T}, f::IndBallL0, x::AbstractArray{T}, gamma::Real=1.0) where T <: RealOrComplex\n  p = []\n  if ndims(x) == 1\n    p = partialsortperm(x, 1:f.r, by=abs, rev=true)\n  else\n    p = partialsortperm(x[:], 1:f.r, by=abs, rev=true)\n  end\n  sort!(p)\n  idx = 1\n  for i = 1:length(p)\n    y[idx:p[i]-1] .= zero(T)\n    y[p[i]] = x[p[i]]\n    idx = p[i]+1\n  end\n  y[idx:end] .= zero(T)\n  return zero(T)\nend\n\nfun_name(f::IndBallL0) = \"indicator of an L0 pseudo-norm ball\"\nfun_dom(f::IndBallL0) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::IndBallL0) = \"x ↦ 0 if countnz(x) ⩽ r, +∞ otherwise\"\nfun_params(f::IndBallL0) = \"r = $(f.r)\"\n\nfunction prox_naive(f::IndBallL0, x::AbstractArray{T}, gamma::Real=1.0) where T <: RealOrComplex\n  p = sortperm(abs.(x)[:], rev=true)\n  y = similar(x)\n  y[p[1:f.r]] .= x[p[1:f.r]]\n  y[p[f.r+1:end]] .= 0.0\n  return y, 0.0\nend\n", "meta": {"hexsha": "c53af29ae2111a30383ef36772d8ba2ce36b3e6c", "size": 1630, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indBallL0.jl", "max_stars_repo_name": "lostella/ProximalOperators.jl", "max_stars_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-15T13:57:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T13:57:52.000Z", "max_issues_repo_path": "src/functions/indBallL0.jl", "max_issues_repo_name": "lostella/ProximalOperators.jl", "max_issues_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/indBallL0.jl", "max_forks_repo_name": "lostella/ProximalOperators.jl", "max_forks_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9705882353, "max_line_length": 112, "alphanum_fraction": 0.618404908, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7604162248402234}}
{"text": "\n\"The set of all natural numbers.\"\nstruct NaturalNumbers <: Domain{Int}\nend\n\nin(x, d::NaturalNumbers) = isinteger(x) && (x >= 0)\nin(x::AbstractArray, d::NaturalNumbers) = false\n==(::NaturalNumbers, ::NaturalNumbers) = true\n\napprox_in(x::Real, d::NaturalNumbers, tol) =\n    (abs(x-round(x)) < tol) && (round(Int, x) ∈ d)\n\n\n\"The set of all integers.\"\nstruct Integers <: Domain{Int}\nend\n\nin(x, d::Integers) = isinteger(x)\nin(x::AbstractArray, d::Integers) = false\n==(::Integers, ::Integers) = true\n\napprox_in(x::Real, d::Integers, tol) =\n    (abs(x-round(x)) < tol) && (round(Int, x) ∈ d)\n\n\n\"The set of all real numbers.\"\nstruct RealNumbers <: Domain{Float64}\nend\n\nin(x::Number, d::RealNumbers) = isreal(x)\n# isreal also allows real arrays, we want to disallow that here:\nin(x::AbstractArray, d::RealNumbers) = false\n\napprox_in(x::Complex, d::RealNumbers, tol) = (imag(x) < tol) && (real(x) ∈ d)\n==(::RealNumbers, ::RealNumbers) = true\n\n\"The set of all rationals.\"\nstruct Rationals <: Domain{Rational{Int}}\nend\n\nin(x, d::Rationals) = x ∈ Integers()\nin(x::Rational, d::Rationals) = true\n==(::Rationals, ::Rationals) = true\n\n\"The set of all complex numbers whose real and imaginary parts are real numbers.\"\nstruct ComplexNumbers <: Domain{Complex{Float64}}\nend\n\nin(x::Complex{T}, d::ComplexNumbers) where {T} =\n    isreal(real(x)) && isreal(imag(x))\nin(x::Complex{T}, d::ComplexNumbers) where {T<:Real} = true\nin(x, d::ComplexNumbers) = x ∈ RealNumbers()\n==(::ComplexNumbers, ::ComplexNumbers) = true\n\n\n\"The set of natural numbers.\"\nconst ℕ = NaturalNumbers()\n\"The set of integers.\"\nconst ℤ = Integers()\n\"The set of rational numbers.\"\nconst ℚ = Rationals()\n\"The set of real numbers.\"\nconst ℝ = RealNumbers()\n\"The set of complex numbers.\"\nconst ℂ = ComplexNumbers()\n\n\"The space ℝ^1.\"\nconst ℝ1 = VcatDomain(ℝ)\n\"The space ℝ^2.\"\nconst ℝ2 = VcatDomain(ℝ, ℝ)\n\"The space ℝ^3.\"\nconst ℝ3 = VcatDomain(ℝ, ℝ, ℝ)\n\"The space ℝ^4.\"\nconst ℝ4 = VcatDomain(ℝ, ℝ, ℝ, ℝ)\n", "meta": {"hexsha": "164afdacdb770440d4c7334db4c7d533dde80d53", "size": 1947, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/domains/numbers.jl", "max_stars_repo_name": "JuliaApproximation/DomainSets.jl", "max_stars_repo_head_hexsha": "5f3918304d3ca14284ca9330be158047c3d32db5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-10-27T21:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T08:22:43.000Z", "max_issues_repo_path": "src/domains/numbers.jl", "max_issues_repo_name": "JuliaApproximation/DomainSets.jl", "max_issues_repo_head_hexsha": "5f3918304d3ca14284ca9330be158047c3d32db5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 76, "max_issues_repo_issues_event_min_datetime": "2018-10-26T08:52:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T12:50:39.000Z", "max_forks_repo_path": "src/domains/numbers.jl", "max_forks_repo_name": "JuliaApproximation/Domains.jl", "max_forks_repo_head_hexsha": "cb578c2763e25184eac1026ac47b0b34e1b9028e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-10-28T13:02:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:51:20.000Z", "avg_line_length": 25.96, "max_line_length": 81, "alphanum_fraction": 0.6718027735, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.76041357976209}}
{"text": "function tinterval(x, δ, op)\n    μ = mean(x)\n    σ = std(x, mean=μ)\n    t = 0.0\n    n = length(x)\n    Zygote.ignore() do\n        t = quantile(TDist(n-1), δ)\n    end\n    s = t * σ / √n\n    return op(μ,s)\nend\n\nfunction tdist_ci(;δ=0.05, tail=:both)\n    if tail == :right\n        return x->tinterval(x,δ,(μ,s)->μ-s) # quantile of 0.05 is negative so need to subtract to get upper\n    elseif tail == :left\n        return x->tinterval(x,δ,(μ,s)->μ+s) # need to add to get lower bound\n    else\n        return x->tinterval(x,δ/2,(μ,s)->(μ+s,μ-s))\n    end\nend\n\nfunction andersons_ucb(x, b, δ)\n    n = length(x)\n    ϵ = √(log(1/δ)/(2n))\n    r = floor(Int, n*ϵ)\n    upper = (1/n) * ((r+1)*x[r+1] + sum(view(x, r+1:n))) + ϵ * (b - x[r+1])\n    return upper\nend\n\nfunction andersons_lcb(x, a, δ)\n    n = length(x)\n    ϵ = √(log(1/δ)/(2n))\n    s = floor(Int, n*ϵ)\n    lower = (1/n) * (sum(view(x, 1:n-s-1)) + (s+1)*x[n-s]) - ϵ * (x[n-s] - a)\n    return lower\nend\n\nfunction andersons_ci(a, b; δ=0.05, tail=:both)\n    if tail == :both\n        function f(x)\n            z = sort(x)\n            upper = andersons_ucb(z, b, δ/2)\n            lower = andersons_lcb(z, a, δ/2)\n            return lower, upper\n        end\n        return f\n    elseif tail == :left\n        return x->andersons_lcb(sort(x), a, δ)\n    elseif tail == :right\n        return x->andersons_ucb(sort(x), b, δ)\n    else\n        throw(ArgumentError(\"tail=$(tail) is invalid\"))\n    end\nend\n", "meta": {"hexsha": "3a1a00bffbad7029ec64753620575425d267507d", "size": 1437, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/confidenceintervals.jl", "max_stars_repo_name": "DecisionMakingAI/OffPolicyDecisionMaking.jl", "max_stars_repo_head_hexsha": "e5156c525c7a33eb93ddf2678fbaefb9f308bd6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/confidenceintervals.jl", "max_issues_repo_name": "DecisionMakingAI/OffPolicyDecisionMaking.jl", "max_issues_repo_head_hexsha": "e5156c525c7a33eb93ddf2678fbaefb9f308bd6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/confidenceintervals.jl", "max_forks_repo_name": "DecisionMakingAI/OffPolicyDecisionMaking.jl", "max_forks_repo_head_hexsha": "e5156c525c7a33eb93ddf2678fbaefb9f308bd6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6607142857, "max_line_length": 107, "alphanum_fraction": 0.5212247738, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7604135720935907}}
{"text": "# Squared Exponential Function with ARD\n\n\"\"\"\n    SEArd <: StationaryARD{WeightedSqEuclidean}\n\nARD Squared Exponential kernel (covariance)\n```math\nk(x,x') = σ²\\\\exp(- (x - x')ᵀL⁻²(x - x')/2)\n```\nwith length scale ``ℓ = (ℓ₁, ℓ₂, …)`` and signal standard deviation ``σ`` where\n``L = diag(ℓ₁, ℓ₂, …)``.\n\"\"\"\nmutable struct SEArd{T<:Real} <: StationaryARD{WeightedSqEuclidean}\n    \"Inverse squared length scale\"\n    iℓ2::Vector{T}\n    \"Signal variance\"\n    σ2::T\n    \"Priors for kernel parameters\"\n    priors::Array\nend\n\n\"\"\"\nSquared Exponential Function with ARD\n\n    SEArd(ll::Vector{Real}, lσ::Real)\n\n# Arguments\n  - `ll::Vector{Real}`: vector of length scales (given on log scale)\n  - `lσ::Real`: signal standard deviation (given on log scale)  \n\"\"\"\nSEArd(ll::Vector{T}, lσ::T) where T = SEArd{T}(exp.(-2 .* ll), exp(2 * lσ), [])\n\nfunction set_params!(se::SEArd, hyp::AbstractVector)\n    length(hyp) == num_params(se) || throw(ArgumentError(\"SEArd has $(num_params(se)) parameters, received $(length(hyp)).\"))\n    @views @. se.iℓ2 = exp(-2 * hyp[1:(end-1)])\n    se.σ2 = exp(2 * hyp[end])\nend\n\nget_params(se::SEArd) = [-log.(se.iℓ2) / 2 ; log(se.σ2) / 2]\nget_param_names(k::SEArd) = [get_param_names(k.iℓ2, :ll); :lσ]\nnum_params(se::SEArd) = length(se.iℓ2) + 1\n\ncov(se::SEArd, r::Number) = se.σ2*exp(-r / 2)\n\n@inline dk_dll(se::SEArd, r::Real, wdiffp::Real) = wdiffp*cov(se,r)\n@inline function dKij_dθp(se::SEArd, X1::AbstractMatrix, X2::AbstractMatrix, i::Int, j::Int, p::Int, dim::Int)\n    if p <= dim\n        return dk_dll(se, distij(metric(se),X1,X2,i,j,dim), distijk(metric(se),X1,X2,i,j,p))\n    elseif p==dim+1\n        return dk_dlσ(se, distij(metric(se),X1,X2,i,j,dim))\n    else\n        return NaN\n    end\nend\n", "meta": {"hexsha": "a1c6358b734276d751261cccbb4a4bbe2b9e3983", "size": 1713, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/se_ard.jl", "max_stars_repo_name": "mcusi/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 284, "max_stars_repo_stars_event_min_datetime": "2015-07-31T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T07:08:58.000Z", "max_issues_repo_path": "src/kernels/se_ard.jl", "max_issues_repo_name": "mcusi/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 171, "max_issues_repo_issues_event_min_datetime": "2015-05-28T12:04:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T06:48:23.000Z", "max_forks_repo_path": "src/kernels/se_ard.jl", "max_forks_repo_name": "mcusi/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-05-31T12:44:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:21:38.000Z", "avg_line_length": 31.1454545455, "max_line_length": 125, "alphanum_fraction": 0.6351430239, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7604135682517428}}
{"text": "\nfunction bitCount(n::Int)\n\tcount = 0 \n\twhile n>0 \n\t\tcount += n & 1\n\t\tn >>= 1\n\tend\n\treturn count\nend\n\nfunction findFirstBit(n::Int)\n\tn > 0 || throw(DomainError(\" n needs to be larger than 0\"))\n\t\n\tbreakcondition = 0\n\tsearchposition = 1\n\tidx = 0\n\twhile breakcondition==0\n\t\tbreakcondition = n & searchposition\n\t\tsearchposition <<= 1 \n\t\tidx += 1\n\tend\n\t\n\treturn idx\nend\n\n\nfunction getBitPos(n::Int)\n\n\tPos = Vector{Int}([])\n\twhile n > 0 \n\t\n\t\tidx = findFirstBit(n)\n\t\tpush!(Pos,idx)\n\n\t\tn -= 2^(idx-1)\n\n\tend\n\n\treturn Pos\nend\n\n\"\"\"\n    bitSwap(n, i, j)\n\nswaps bit i with j in n, for e.g.\n\nn = 001001 , i = 1, j = 2 results in bitSwap(n,i,j) = 001010\n\n#Arguments\n- n: bit-string represented as an integer \n- i: position of the first bit which should be swaped with the second\n- j: position of the second bit which should be swaped with the first\n\n\"\"\"\nfunction bitSwap(n::Int, i::Int, j::Int)\t\n\ti -= 1\n\tj -= 1\n\n\tbit1 = (n >> i) & 1\n\tbit2 = (n >> j) & 1\n\n\tx = bit1 ⊻ bit2\n\n\tx = (x << i) | (x << j)\n\n\treturn (n ⊻ x)\nend\n\n\n\nfunction FermionicBitSwap(n::Int, j::Int, k::Int)\n\tn_new = bitSwap(n,j,k)\n\tuntouchedBit =  n & n_new\t\n\tinbetween = j<k ? (j+1:k-1) : (k+1:j-1)\n\tc = Int(sum(2.0.^[x-1 for x in inbetween]))\n\toverjumped_fermions = bitCount(untouchedBit & c)\n\treturn n_new, (-1)^overjumped_fermions\nend\n\n\n\n", "meta": {"hexsha": "a23cbec61b29af0fc1d959eb7d55097f6a3cc6cb", "size": 1293, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bitOperations.jl", "max_stars_repo_name": "Gawatz/exactQmodule", "max_stars_repo_head_hexsha": "ee789937abdb2289a68bb0ec5190d1a69d0a22dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bitOperations.jl", "max_issues_repo_name": "Gawatz/exactQmodule", "max_issues_repo_head_hexsha": "ee789937abdb2289a68bb0ec5190d1a69d0a22dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bitOperations.jl", "max_forks_repo_name": "Gawatz/exactQmodule", "max_forks_repo_head_hexsha": "ee789937abdb2289a68bb0ec5190d1a69d0a22dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.7682926829, "max_line_length": 69, "alphanum_fraction": 0.6194895592, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.76041356822135}}
{"text": "\"\"\"\n  Rudimentary adaptive function sampling\n  Adapted from https://stackoverflow.com/a/14084715\n\"\"\"\nfunction sample_function(func, nodes, values=func.(nodes), mask=Colon(); \n    depth=0, min_nodes=16, max_level=16, tol=0.01)\n\n  if depth > max_level\n    return nodes, values\n  end\n  \n  # Calculate the function in between the nodes\n  x_c = 0.5 * (nodes[1:end-1][mask] + nodes[2:end][mask])\n  y_c = func.(x_c)\n\n  x₂ = vcat(nodes, x_c)\n  y₂ = vcat(values, y_c)\n  is = sortperm(x₂)\n\n  x₂ = x₂[is]\n  y₂ = y₂[is]\n\n  # Determine where to refine\n  if length(x₂) < min_nodes\n    mask = trues(length(x₂) - 1)\n  else\n    # Rescale and compute the length of each line segment in the path\n    dx = diff(x₂) / ptp(x₂)\n    dy = diff(y₂) / abs(ptp(y₂))\n    ds = sqrt.(abs2.(dx) + abs2.(dy))\n    \n    # Compute the angle between consecutive line segments θ = acos(a⋅b / (|a||b|))\n    dx ./= ds\n    dy ./= ds\n\n    if eltype(dy) <: Complex\n      @views dy_re = reinterpret(Float64, dy)[1:2:end]\n      @views dy_im = reinterpret(Float64, dy)[2:2:end]\n      dθ = acos.(clamp.(dx[2:end] .* dx[1:end-1] + dy_re[2:end] .* dy_re[1:end-1] + dy_im[2:end] .* dy_im[1:end-1], -1, 1))\n    else\n      dθ = acos.(clamp.(dx[2:end] .* dx[1:end-1] + dy[2:end] .* dy[1:end-1], -1, 1))\n    end\n\n    # Determine where to subdivide (total length of the path is computed ≈ to accuracy `tol`)\n    mask = 0.5 * dθ .* (ds[2:end] .+ ds[1:end-1]) .> tol * sum(ds)\n    mask = [mask; false]\n    mask[2:end] .|= mask[1:end-1]\n  end\n  \n  # Refine!\n  if any(mask)\n    return sample_function(func, x₂, y₂, mask; tol=tol, depth=depth+1, min_nodes=min_nodes, max_level=max_level)\n  else\n    return x₂, y₂\n  end\nend\n", "meta": {"hexsha": "84e28f435d190e54d5e0cf73d6f2c4f55d13421d", "size": 1663, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sampling.jl", "max_stars_repo_name": "FMeirinhos/Adaptive1D.jl", "max_stars_repo_head_hexsha": "4b1750bb246471ba9e031bc7ae743547c7da6a28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-25T16:23:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T01:53:40.000Z", "max_issues_repo_path": "src/sampling.jl", "max_issues_repo_name": "FMeirinhos/Adaptive1D.jl", "max_issues_repo_head_hexsha": "4b1750bb246471ba9e031bc7ae743547c7da6a28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sampling.jl", "max_forks_repo_name": "FMeirinhos/Adaptive1D.jl", "max_forks_repo_head_hexsha": "4b1750bb246471ba9e031bc7ae743547c7da6a28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1754385965, "max_line_length": 123, "alphanum_fraction": 0.6049308479, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7604135681909568}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.2\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 38fdd4ef-c383-4f97-8451-c6f602307e7d\nusing Images\n\n# ╔═╡ 3dceca5d-7d1e-425b-9516-24e0a24adaff\nusing LinearAlgebra\n# examples follow:\n\n# ╔═╡ 3eb50f44-9091-45e8-a7e1-92d25b4b2090\nbegin\n\tusing StaticArrays\n\tOption{T} = Union{Missing, T}\n\t\n\tsquared_length(v::SVector{3,Float32}) = v ⋅ v\n\tnear_zero(v::SVector) = squared_length(v) < 1e-5\nend\n\n# ╔═╡ 0866add2-9b95-45e7-8081-c01cd2a66911\nmd\"\"\"# Chapter 1: Overview\"\"\"\n\n# ╔═╡ 611d5eae-4b09-11ec-27bf-ef4a1ecdcc41\nmd\"Adapted from [Ray Tracing In One Weekend by Peter Shirley](https://raytracing.github.io/books/RayTracingInOneWeekend.html) and [cshenton's Julia implementation](https://github.com/cshenton/RayTracing.jl)\"\n\n# ╔═╡ 97bb4432-ed41-423b-b4d9-bafc519de641\nmd\"# Chapter 2 - Manipulating images\"\n\n# ╔═╡ 84d29423-cf11-41c3-af4d-c5f63b1ef23e\nimg = rand(4, 3)\n\n# ╔═╡ 7d26fef0-9a06-479a-ae08-e9d04e455767\nimg_rgb = rand(RGB{Float32}, 4, 4)\n\n# ╔═╡ f29ad2c0-c3ff-484d-8fdd-dff34d2bb863\nex1 = [RGB{Float32}(1,0,0) RGB{Float32}(0,1,0) RGB{Float32}(0,0,1);\n       RGB{Float32}(1,1,0) RGB{Float32}(1,1,1) RGB{Float32}(0,0,0)]\n\n# ╔═╡ 2192e695-4378-4b47-8ce0-353636cd2cd1\nbegin\n\tex2 = zeros(RGB{Float32}, 2, 3)\n\tex2[1,1] = RGB{Float32}(1,0,0)\n\tex2\nend\n\n# ╔═╡ 538d1aa5-07f9-4fca-8410-ef63b8a6857b\n# TODO: save as image, e.g. PNG\n\n# ╔═╡ 8aeb7373-6bb0-4544-8655-fa941561688c\n# The \"Hello World\" of graphics\nfunction gradient(nx::Int, ny::Int)\n\timg = zeros(RGB{Float32}, ny, nx)\n\tfor i in 1:ny, j in 1:nx # Julia is column-major, i.e. iterate 1 column at a time\n\t\tx = j; y = (ny-i);\n\t\tr = x/nx\n\t\tg = y/ny\n\t\tb = 0.2\n\t\timg[i,j] = RGB{Float32}(r,g,b)\n\tend\n\timg\nend\n\n# ╔═╡ 154d736b-8fdc-44af-ae2a-9e5ba6d2c92e\ngradient(200,100)\n\n# ╔═╡ 216922d8-613a-4ac1-9559-40878e6587e2\nmd\"\"\"Unlike the C++ implementation:\n- Julia uses i for row, j for column, so I inverted the C++ code's variable names.\n- The C++ code used a Y-up coordinate system, so I used (ny-i) instead of i for the row number.\"\"\"\n\n# ╔═╡ 961fd749-d439-4dfa-ae21-b1659dc54511\nmd\"# Chapter 3: Linear Algebra\"\n\n# ╔═╡ f8007c75-9487-414a-9592-138a696c2957\n# Dot product (\\cdot) is defined by LinearAlgebra...\n[1; 1] ⋅ [2; 3]\n\n# ╔═╡ 668030c8-24a7-4aa6-b858-cedf8ac5f988\n# Cross product (\\times)\n[0;1;0] × [0;0;1]\n\n# ╔═╡ 78f209df-d176-4711-80fc-a8054771f105\nt_col = @SVector[0.4f0, 0.5f0, 0.1f0] # Float32 test color\n\n# ╔═╡ e88de775-6904-4182-8209-06db22758470\nt_col[1] # first, i.e. red, component\n\n# ╔═╡ 5fd1ec87-3616-448a-ab4d-fede804b26d5\nsquared_length(t_col)\n\n# ╔═╡ a0893bf4-9607-4853-8162-9f34d3337060\nrgb(v::SVector{3,Float32}) = RGB(v[1], v[2], v[3]) # IIRC RGB(v...) was much slower...\n\n# ╔═╡ cfbcb883-d12e-4ad3-a084-064749bddcdb\nrgb(t_col)\n\n# ╔═╡ 6348c03d-e8ec-4dbb-9f8a-8e4a48bb1cb3\nrgb_gamma2(v::SVector{3,Float32}) = RGB(sqrt.(v)...) # claforte: try to expand?\n\n# ╔═╡ dbc8fc2d-39c2-4ec9-b82d-7c6a8b12dde7\nrgb_gamma2(t_col)\n\n# ╔═╡ 53832af1-a9be-4e02-8b71-a70dae63c233\nstruct Ray\n\torigin::SVector{3,Float32}\n\tdir::SVector{3,Float32} # direction (unit vector)\nend\n\n# ╔═╡ 81b4c9e4-9f93-45ca-9fa0-7e9686a55e9a\n# equivalent to C++'s ray.at()\n#\"3D Point of ray `r` evaluated at parameter t\"\npoint(r::Ray, t::Float32)::SVector{3,Float32} = r.origin .+ t .* r.dir\n\n# ╔═╡ 772674b0-5c40-4457-9526-5b4e81cca711\nmd\"\"\"# Random vectors\nC++'s section 8.1\"\"\"\n\n# ╔═╡ 709861a3-202a-4bff-a46d-b46c6e14b334\n# equiv to random_double()\nrandom_between(min=0.0f0, max=1.0f0) = rand(Float32)*(max-min) + min\n\n# ╔═╡ 135000d6-a675-4d8b-9385-50853bf9a169\nrandom_vec3(min::Float32, max::Float32) = @SVector[random_between(min,max) for i∈1:3]\n\n# ╔═╡ 7d1146d7-74da-42e6-92c2-1312ed03f70d\nrandom_vec2(min::Float32, max::Float32) = @SVector[random_between(min,max) for i∈1:2]\n\n# ╔═╡ 46a4aa4b-82c1-4941-b36d-dc8c977af2bc\nfunction random_vec3_in_sphere() # equiv to random_in_unit_sphere()\n\twhile true\n\t\tp = random_vec3(-1f0, 1f0)\n\t\tif p⋅p <= 1\n\t\t\treturn p\n\t\tend\n\tend\nend\n\n# ╔═╡ 203a9b25-742a-4d8b-adee-862ce4c67670\nsquared_length(random_vec3_in_sphere())\n\n# ╔═╡ 2e98c6bd-0289-4105-ad25-24414ecf2750\n#\"Random unit vector. Equivalent to C++'s `unit_vector(random_in_unit_sphere())`\"\nrandom_vec3_on_sphere() = normalize(random_vec3_in_sphere())\n\n# ╔═╡ c0c23cb3-6a57-487d-943a-af4330a94ffe\nfunction random_vec2_in_disk() # equiv to random_in_unit_disk()\n\twhile true\n\t\tp = random_vec2(-1f0, 1f0)\n\t\tif p⋅p <= 1\n\t\t\treturn p\n\t\tend\n\tend\nend\n\n# ╔═╡ 678214c5-de81-489f-b002-c343d48071c9\nmd\"# Chapter 4: Rays, simple camera, and background\"\n\n# ╔═╡ cbb6418c-79e9-4359-80a6-40a8fa40679e\nfunction skycolor(ray::Ray)\n\t# NOTE: unlike in the C++ implem., we assume the ray direction is pre-normalized.\n\twhite = @SVector[1.0f0,1.0f0,1.0f0]\n\tskyblue = @SVector[0.5f0,0.7f0,1.0f0]\n\tt = 0.5f0(ray.dir[2] + 1.0f0)\n    (1.0f0-t)*white + t*skyblue\nend\n\n# ╔═╡ 14be6068-6a15-4fad-ac0a-f156da71f103\nrgb(@SVector[0.5f0, 0.7f0, 1.0f0]), rgb(@SVector[1.0f0, 1.0f0, 1.0f0])\n\n# ╔═╡ 64ef0313-2d2b-49d5-a1a1-3b04426a82f8\nbegin\n\t_origin = @SVector[0.0f0,0.0f0,0.0f0]\n\t_v3_minusY = @SVector[0.0f0,-1.0f0,0.0f0]\n\t_t_ray1 = Ray(_origin, _v3_minusY)\nend\n\n# ╔═╡ 971777a6-f269-4344-8dba-7a55118396e5\n# \"\"\" Temporary function to shoot rays through each pixel. Later replaced by `render`\n#\n# \tArgs:\n# \t\tscene: a function that takes a ray, returns the color of any object it hit\n# \"\"\"\nfunction main(nx::Int, ny::Int, scene)\n\tlower_left_corner = @SVector[-2,-1,-1]\n\thorizontal = @SVector[4,0,0]\n\tvertical = @SVector[0f0,2f0,0f0]\n\torigin = @SVector[0,0,0]\n\t\n\timg = zeros(RGB{Float32}, ny, nx)\n\tfor i in 1:ny, j in 1:nx # Julia is column-major, i.e. iterate 1 column at a time\n\t\tu = j/nx\n\t\tv = (ny-i)/ny # Y-up!\n\t\tray = Ray(origin, normalize(lower_left_corner + u*horizontal + v*vertical))\n\t\t#r = x/nx\n\t\t#g = y/ny\n\t\t#b = 0.2\n\t\timg[i,j] = rgb(scene(ray))\n\tend\n\timg\nend\n\n# ╔═╡ 655ffa6c-f1e9-4149-8f1d-51145c5a51e4\nmain(200,100, skycolor)\n\n# ╔═╡ 9075f8ed-f319-486d-94b2-486806aba3fd\nmd\"# Chapter 5: Add a sphere\"\n\n# ╔═╡ c00e2004-2002-4dd2-98ed-f898ef2c14f1\nfunction hit_sphere1(center::SVector{3,Float32}, radius::Float32, r::Ray)\n\toc = r.origin - center\n\ta = r.dir ⋅ r.dir\n\tb = 2oc ⋅ r.dir\n\tc = (oc ⋅ oc) - radius*radius\n\tdiscriminant = b*b - 4a*c\n\tdiscriminant > 0\nend\n\n# ╔═╡ b7399fb8-6205-41ea-9c70-eb62daedcefb\nfunction sphere_scene1(r::Ray)\n\t# sphere of radius 0.5 centered at z=-1\n\tif hit_sphere1(@SVector[0f0,0f0,-1f0], 0.5f0, r) \n\t\treturn @SVector[1f0,0f0,0f0] # red\n\telse\n\t\tskycolor(r)\n\tend\nend\n\n# ╔═╡ 1d04159d-87bd-4cf8-a73c-817f20ca1026\nmain(200,100,sphere_scene1)\n\n# ╔═╡ fed81f09-e4a0-433f-99e8-261096114b7b\nmd\"# Chapter 6: Surface normals and multiple objects\"\n\n# ╔═╡ 24e8740a-8e44-4206-b2b6-c4a55002dad8\nfunction hit_sphere2(center::SVector{3,Float32}, radius::Float32, r::Ray)\n\toc = r.origin - center\n\ta = r.dir ⋅ r.dir\n\tb = 2oc ⋅ r.dir\n\tc = (oc ⋅ oc) - radius*radius\n\tdiscriminant = b*b - 4a*c\n\tif discriminant < 0\n\t\treturn -1\n\telse\n\t\treturn (-b - sqrt(discriminant)) / 2a\n\tend\nend\n\n# ╔═╡ 359832af-7598-4c45-8033-c28cb0d86772\nfunction sphere_scene2(r::Ray)\n\tsphere_center = SVector{3,Float32}(0f0,0f0,-1f0)\n\tt = hit_sphere2(sphere_center, 0.5f0, r) # sphere of radius 0.5 centered at z=-1\n\tif t > 0f0\n\t\tn⃗ = normalize(point(r, t) - sphere_center) # normal vector. typed n\\vec\n\t\treturn 0.5f0n⃗ + SVector{3,Float32}(0.5f0,0.5f0,0.5f0) # remap normal to rgb\n\telse\n\t\tskycolor(r)\n\tend\nend\n\n# ╔═╡ ed6ab8be-587c-4cb6-8172-618c74d3f9cc\nmain(200,100,sphere_scene2)\n\n# ╔═╡ a65c68c9-e489-465a-9687-93ae9da14a5e\n\"An object that can be hit by Ray\"\nabstract type Hittable end\n\n# ╔═╡ 2c4b4453-1a46-4889-9a14-16b18cc8c240\n\"\"\"Materials tell us how rays interact with a surface\"\"\"\nabstract type Material end\n\n# ╔═╡ 98c43f3f-4bfc-49db-806a-850b7d75b5a4\nbegin\n\tstruct NoMaterial <: Material end\n\t\n\tconst _no_material = NoMaterial()\n\tconst _y_up = @SVector[0f0,1f0,0f0]\nend\n\n# ╔═╡ 3b570d37-f407-41d8-b8a0-a0af4d85b14d\n\"Record a hit between a ray and an object's surface\"\nmutable struct HitRecord\n\tt::Float32 # vector from the ray's origin to the intersection with a surface. \n\t\n\t# If t==Inf32, there was no hit, and all following values are undefined!\n\t#\n\tp::SVector{3,Float32} # point of intersection between an object's surface and ray\n\tn⃗::SVector{3,Float32} # local normal (see diagram below)\n\t\n\t# If true, our ray hit from outside to the front of the surface. \n\t# If false, the ray hit from within.\n\tfront_face::Bool\n\tmat::Material\n\n\tHitRecord() = new(Inf32) # no hit!\n\tHitRecord(t,p,n⃗,front_face,mat) = new(t,p,n⃗,front_face,mat)\nend\n\n# ╔═╡ 138bb5b6-0f45-4f13-8339-5110eb7cd1ff\nstruct Sphere <: Hittable\n\tcenter::SVector{3,Float32}\n\tradius::Float32\n\tmat::Material\nend\n\n# ╔═╡ 6b36d245-bf01-45a7-b119-8315226dd4a3\nHTML(\"\"\"The geometry defines an `outside normal`. A HitRecord stores the `local normal`.\n<img src=\"https://raytracing.github.io/images/fig-1.06-normal-sides.jpg\"\nstyle=\"width:24em\"> \"\"\")\n\n# ╔═╡ 4a396b3f-f920-4ec2-91f6-7d61fe2b9699\n#\"\"\"Equivalent to `hit_record.set_face_normal()`\"\"\"\nfunction ray_to_HitRecord(t, p, outward_n⃗, r_dir::SVector{3,Float32}, mat::Material)\n\tfront_face = r_dir ⋅ outward_n⃗ < 0\n\tn⃗ = front_face ? outward_n⃗ : -outward_n⃗\n\trec = HitRecord(t,p,n⃗,front_face,mat)\nend\n\n# ╔═╡ 427f247c-055c-459e-9862-26e9f6f3e24f\nstruct Scatter\n\tr::Ray\n\tattenuation::SVector{3,Float32}\n\t\n\t# claforte: TODO: rename to \"absorbed?\", i.e. not reflected/refracted?\n\treflected::Bool # whether the scattered ray was reflected, or fully absorbed\n\tScatter(r,a,reflected=true) = new(r,a,reflected)\nend\n\n# ╔═╡ 88e51c27-0f28-4dcc-b9e9-ac44eeb876f5\n#\"Diffuse material\"\nmutable struct Lambertian<:Material\n\talbedo::SVector{3,Float32}\nend\n\n# ╔═╡ 7c4a67b2-8208-4cd4-b1ea-16f6f50adfe8\n# \"\"\"Compute reflection vector for v (pointing to surface) and normal n⃗.\n\n# \tSee [diagram](https://raytracing.github.io/books/RayTracingInOneWeekend.html#metal/mirroredlightreflection)\"\"\"\nreflect(v::SVector{3,Float32}, n⃗::SVector{3,Float32}) = v - (2v⋅n⃗)*n⃗\n\n# ╔═╡ ca649864-5a6d-4ca7-896e-e80e8a48443e\nreflect(@SVector[0.6f0,-0.8f0,0f0], @SVector[0f0,1f0,0f0]) # diagram's example\n\n# ╔═╡ 485f9c5b-4c5d-453c-b190-e84ae0cd1a21\n# \"\"\"Create a scattered ray emitted by `mat` from incident Ray `r`. \n\n# \tArgs:\n# \t\trec: the HitRecord of the surface from which to scatter the ray.\n\n# \tReturn missing if it's fully absorbed. \"\"\"\nfunction scatter(mat::Lambertian, r::Ray, rec::HitRecord)::Scatter\n\tscatter_dir = rec.n⃗ + random_vec3_on_sphere()\n\tif near_zero(scatter_dir) # Catch degenerate scatter direction\n\t\tscatter_dir = rec.n⃗ \n\telse\n\t\tscatter_dir = normalize(scatter_dir)\n\tend\n\tscattered_r = Ray(rec.p, scatter_dir)\n\tattenuation = mat.albedo\n\treturn Scatter(scattered_r, attenuation)\nend\n\n# ╔═╡ c63d10c2-dd43-4836-83ee-61b782545a02\nconst _no_hit = HitRecord() # will be reused \n\n# ╔═╡ 78efebc5-53fd-417d-bd9e-667fd504e3fd\nfunction hit(s::Sphere, r::Ray, tmin::Float32, tmax::Float32)\n    oc = r.origin - s.center\n    a = 1 #r.dir ⋅ r.dir # normalized vector - always 1\n    half_b = oc ⋅ r.dir\n    c = oc⋅oc - s.radius^2\n    discriminant = half_b^2 - a*c\n\tif discriminant < 0 return _no_hit end\n\tsqrtd = √discriminant\n\t\n\t# Find the nearest root that lies in the acceptable range\n\troot = (-half_b - sqrtd) / a\t\n\tif root < tmin || tmax < root\n\t\troot = (-half_b + sqrtd) / a\n\t\tif root < tmin || tmax < root\n\t\t\treturn _no_hit\n\t\tend\n\tend\n\t\t\n\tt = root\n\tp = point(r, t)\n\tn⃗ = (p - s.center) / s.radius\n\treturn ray_to_HitRecord(t, p, n⃗, r.dir, s.mat)\nend\n\n# ╔═╡ 05e57afd-6eb9-42c5-9666-7be3771fa6b8\nstruct HittableList <: Hittable\n    list::Vector{Hittable}\nend\n\n# ╔═╡ 08e18ae5-9927-485e-9644-552f03e06f27\n#\"\"\"Find closest hit between `Ray r` and a list of Hittable objects `h`, within distance `tmin` < `tmax`\"\"\"\nfunction hit(hittables::HittableList, r::Ray, tmin::Float32, tmax::Float32)\n    closest = tmax # closest t so far\n    rec = _no_hit\n    for h in hittables.list\n        temprec = hit(h, r, tmin, closest)\n        if temprec !== _no_hit\n            rec = temprec\n            closest = rec.t # i.e. ignore any further hit > this one's.\n        end\n    end\n    rec\nend\n\n# ╔═╡ 737e2f87-82f5-45b6-a76c-4f560c29f5b9\ncolor_vec3_in_rgb(v::SVector{3,Float32}) = 0.5normalize(v) + @SVector[0.5f,0.5f,0.5f]\n\n# ╔═╡ 0bf88264-d4c5-4d5a-babe-d2433e46024d\nmd\"# Metal material\"\n\n# ╔═╡ 555bea1d-5178-48dd-87e6-4e2a2471a5dd\nmutable struct Metal<:Material\n\talbedo::SVector{3,Float32}\n\tfuzz::Float32 # how big the sphere used to generate fuzzy reflection rays. 0=none\n\tMetal(a,f=0.0) = new(a,f)\nend\n\n# ╔═╡ c299ca47-46c4-42da-9f8b-ae3abbeb6e51\nfunction scatter(mat::Metal, r_in::Ray, rec::HitRecord)::Scatter\n\treflected = normalize(reflect(r_in.dir, rec.n⃗) + mat.fuzz*random_vec3_on_sphere())\n\tScatter(Ray(rec.p, reflected), mat.albedo)\nend\n\n# ╔═╡ 851c002c-dc23-4999-b28c-a716c5d2d42c\nmd\"# Scenes\"\n\n# ╔═╡ 70530f8e-1b29-4588-927f-d38d5d12d5c9\n#\"Scene with 2 Lambertian spheres\"\nfunction scene_2_spheres()::HittableList\n\tspheres = Sphere[]\n\t\n\t# small center sphere\n\tpush!(spheres, Sphere(@SVector[0f0,0f0,-1f0], 0.5,\n\t\t\t\t\t\t  Lambertian(@SVector[0.7f0,0.3f0,0.3f0])))\n\t\n\t# ground sphere (planet?)\n\tpush!(spheres, Sphere(@SVector[0f0,-100.5f0,-1f0], 100,\n\t\t\t\t\t\t  Lambertian(@SVector[0.8f0,0.8f0,0.0f0])))\n\tHittableList(spheres)\nend\n\n# ╔═╡ c5349670-4df4-421f-9d5a-b28c1b9040c2\n#\"\"\"Scene with 2 Lambertian, 2 Metal spheres.\n#\n#\tSee https://raytracing.github.io/images/img-1.11-metal-shiny.png\"\"\"\nfunction scene_4_spheres()::HittableList\n\tscene = scene_2_spheres()\n\n\t# left and right Metal spheres\n\tpush!(scene.list, Sphere(@SVector[-1f0,0f0,-1f0], 0.5f0,\n\t\t\t\t\t\t\t Metal(@SVector[0.8f0,0.8f0,0.8f0], 0.3f0))) \n\tpush!(scene.list, Sphere(@SVector[1f0,0f0,-1f0], 0.5f0, \n\t\t\t\t\t\t\t Metal(@SVector[0.8f0,0.6f0,0.2f0], 0.8f0)))\n\treturn scene\nend\n\n# ╔═╡ 282a4912-7a6e-44ae-90eb-f2f7c8f3d0f4\nmd\"\"\"# Camera\n\nAdapted from C++'s sections 7.2, 11.1 \"\"\"\n\n# ╔═╡ a0e5a1f3-244f-427b-a335-7e233af1d9d8\nmutable struct Camera\n\torigin::SVector{3,Float32}\n\tlower_left_corner::SVector{3,Float32}\n\thorizontal::SVector{3,Float32}\n\tvertical::SVector{3,Float32}\n\tu::SVector{3,Float32}\n\tv::SVector{3,Float32}\n\tw::SVector{3,Float32}\n\tlens_radius::Float32\nend\n\n# ╔═╡ 5d00f26b-35f2-4071-8e04-227ffc25f184\n# \"\"\"\n# \tArgs:\n# \t\tvfov: vertical field-of-view in degrees\n# \t\taspect_ratio: horizontal/vertical ratio of pixels\n#       aperture: if 0 - no depth-of-field\n# \"\"\"\nfunction default_camera(lookfrom::SVector{3,Float32}=@SVector[0f0,0f0,0f0], \n\t\t\tlookat::SVector{3,Float32}=@SVector[0f0,0f0,-1f0], \n\t\t\tvup::SVector{3,Float32}=@SVector[0f0,1f0,0f0], vfov=90.0f0, aspect_ratio=16.0f0/9.0f0,\n\t\t\t\t\t\taperture=0.0f0, focus_dist=1.0f0)\n\tviewport_height = 2.0f0 * tand(vfov/2f0)\n\tviewport_width = aspect_ratio * viewport_height\n\t\n\tw = normalize(lookfrom - lookat)\n\tu = normalize(vup × w)\n\tv = w × u\n\t\n\torigin = lookfrom\n\thorizontal = focus_dist * viewport_width * u\n\tvertical = focus_dist * viewport_height * v\n\tlower_left_corner = origin - horizontal/2f0 - vertical/2f0 - focus_dist*w\n\tlens_radius = aperture/2f0\n\tCamera(origin, lower_left_corner, horizontal, vertical, u, v, w, lens_radius)\nend\n\n# ╔═╡ c1aef1be-79d4-4417-be36-ae8416465986\ndefault_camera()\n\n# ╔═╡ 94081092-afc6-4359-bd2c-15e8407bf70e\nfunction get_ray(c::Camera, s::Float32, t::Float32)\n\trd = SVector{2,Float32}(c.lens_radius * random_vec2_in_disk())\n\toffset = c.u * rd[1] + c.v * rd[2] #offset = c.u * rd.x + c.v * rd.y\n    Ray(c.origin + offset, normalize(c.lower_left_corner + s*c.horizontal +\n\t\t\t\t\t\t\t\t\t t*c.vertical - c.origin - offset))\nend\n\n# ╔═╡ 813eaa13-2eb2-4302-9e4d-5d1dab0ac7c4\nget_ray(default_camera(), 0.0f0, 0.0f0)\n\n# ╔═╡ 891ce2c8-f8b2-472b-a8d9-389dafddcf22\nmd\"# Render\n\n(equivalent to final `main`)\"\n\n# ╔═╡ 5f1bae02-d425-4a73-8668-d6383faba79d\nmd\"\"\"# Dielectrics\n\nfrom Section 10.2 Snell's Law:\"\"\"\n\n# ╔═╡ 71f3626c-e61d-4838-82b9-ac8a978c0cb4\nHTML(\"\"\"<img src=\"https://raytracing.github.io/images/fig-1.13-refraction.jpg\"\nstyle=\"width: 8em; height: 8em; margin-bottom: -.2em;\">\"\"\")\n\n# ╔═╡ fbba5135-7ea3-4471-938a-be13c764feff\nmd\"\"\"\nRefracted angle `sinθ′ = (η/η′)⋅sinθ`, where η (\\eta) are the refractive indices.\n\nSplit the parts of the ray into `R′=R′⊥+R′∥` (perpendicular and parallel to n⃗′).\"\"\"\n\n# ╔═╡ 9dc64353-c41c-45b4-aacd-12d5d6117c58\n# \"\"\"\n# \tArgs:\n# \t\trefraction_ratio: incident refraction index divided by refraction index of \n# \t\t\thit surface. i.e. η/η′ in the figure above\"\"\"\nfunction refract(dir::SVector{3,Float32}, n⃗::SVector{3,Float32}, \n\t\t\t\t refraction_ratio::Float32)\n\tcosθ = min(-dir ⋅ n⃗, 1)\n\tr_out_perp = refraction_ratio * (dir + cosθ*n⃗)\n\tr_out_parallel = -√(abs(1-squared_length(r_out_perp))) * n⃗\n\tnormalize(r_out_perp + r_out_parallel)\nend\n\n# ╔═╡ bbfd4db5-3650-4f27-9777-2ff981c3d28b\nbegin # optional tests\n\t# unchanged angle\n\t@assert refract(SVector{3,Float32}(0.6,-0.8,0), \n\t\tSVector{3,Float32}(0,1,0), 1.0f0) == SVector{3,Float32}(0.6,-0.8,0) \n\n\t# wider angle\n\tt_refract_widerθ = refract(SVector{3,Float32}(0.6,-0.8,0), \n\t\tSVector{3,Float32}(0,1,0), 2.0f0)\n\t@assert isapprox(t_refract_widerθ, \n\t\tSVector{3,Float32}(0.87519, -0.483779, 0.0); atol=1e-3)\n\n\t# narrower angle\n\tt_refract_narrowerθ = refract(SVector{3,Float32}(0.6,-0.8,0), \n\t\tSVector{3,Float32}(0,1,0), 0.5f0)\n\t@assert isapprox(t_refract_narrowerθ, \n\t\tSVector{3,Float32}(0.3, -0.953939, 0.0); atol=1e-3)\nend\n\n# ╔═╡ f5c4e502-048c-4fcd-879f-eaeb4430c012\nmutable struct Dielectric <: Material\n\tir::Float32 # index of refraction, i.e. η.\nend\n\n# ╔═╡ 167cc207-7be6-4624-8425-2df81b3f6c3b\nfunction reflectance(cosθ::Float32, refraction_ratio::Float32)\n\t# Use Schlick's approximation for reflectance.\n\t# claforte: may be buggy? I'm getting black pixels in the Hollow Glass Sphere...\n\tr0 = (1f0-refraction_ratio) / (1f0+refraction_ratio)\n\tr0 = r0^2\n\tr0 + (1f0-r0)*((1f0-cosθ)^5)\nend\n\n# ╔═╡ ae3b8f15-985d-4f74-ac8c-86a3ffc3b8b1\nfunction scatter(mat::Dielectric, r_in::Ray, rec::HitRecord)\n\tattenuation = @SVector[1f0,1f0,1f0]\n\trefraction_ratio = rec.front_face ? (1.0f0/mat.ir) : mat.ir # i.e. ηᵢ/ηₜ\n\tcosθ = min(-r_in.dir⋅rec.n⃗, 1.0f0)\n\tsinθ = √(1.0f0 - cosθ^2)\n\tcannot_refract = refraction_ratio * sinθ > 1.0\n\tif cannot_refract || reflectance(cosθ, refraction_ratio) > rand()\n\t\tdir = reflect(r_in.dir, rec.n⃗)\n\telse\n\t\tdir = refract(r_in.dir, rec.n⃗, refraction_ratio)\n\tend\n\tScatter(Ray(rec.p, dir), attenuation) # TODO: rename reflected -> !absorbed?\nend\n\n# ╔═╡ f72214f9-03c4-4ba3-bb84-069256446b31\n# \"\"\"Compute color for a ray, recursively\n\n# \tArgs:\n# \t\tdepth: how many more levels of recursive ray bounces can we still compute?\"\"\"\nfunction ray_color(r::Ray, world::HittableList, depth=4)\n    if depth <= 0\n\t\treturn @SVector[0f0,0f0,0f0]\n\tend\n\t\t\n\trec = hit(world, r, 1f-4, Inf32)\n    if rec !== _no_hit\n\t\t# For debugging, represent vectors as RGB:\n\t\t# return color_vec3_in_rgb(rec.p) # show the normalized hit point\n\t\t# return color_vec3_in_rgb(rec.n⃗) # show the normal in RGB\n\t\t# return color_vec3_in_rgb(rec.p + rec.n⃗)\n\t\t# return color_vec3_in_rgb(random_vec3_in_sphere())\n\t\t#return color_vec3_in_rgb(rec.n⃗ + random_vec3_in_sphere())\n\n        s = scatter(rec.mat, r, rec)\n\t\tif s.reflected\n\t\t\treturn s.attenuation .* ray_color(s.r, world, depth-1)\n\t\telse\n\t\t\treturn @SVector[0f0,0f0,0f0]\n\t\tend\n    else\n        skycolor(r)\n    end\nend\n\n# ╔═╡ 64104df6-4b79-4329-bfed-14619aa73e3c\n# \"\"\"Render an image of `scene` using the specified camera, number of samples.\n#\n# \tArgs:\n# \t\tscene: a HittableList, e.g. a list of spheres\n# \t\tn_samples: number of samples per pixel, eq. to C++ samples_per_pixel\n#\n# \tEquivalent to C++'s `main` function.\"\"\"\nfunction render(scene::HittableList, cam::Camera, image_width=400,\n\t\t\t\tn_samples=1)\n\t# Image\n\taspect_ratio = 16.0f0/9.0f0 # TODO: use cam.aspect_ratio for consistency\n\timage_height = convert(Int64, floor(image_width / aspect_ratio))\n\n\t# Render\n\timg = zeros(RGB{Float32}, image_height, image_width)\n\t# Compared to C++, Julia is:\n\t# 1. column-major, i.e. iterate 1 column at a time, so invert i,j compared to C++\n\t# 2. 1-based, so no need to subtract 1 from image_width, etc.\n\t# 3. The array is Y-down, but `v` is Y-up \n\tfor i in 1:image_height, j in 1:image_width\n\t\taccum_color = @SVector[0f0,0f0,0f0]\n\t\tfor s in 1:n_samples\n\t\t\tu = convert(Float32, j/image_width)\n\t\t\tv = convert(Float32, (image_height-i)/image_height) # i=Y-down, v=Y-up!\n\t\t\tif s != 1 # 1st sample is always centered, for 1-sample/pixel\n\t\t\t\t# claforte: I think the C++ version had a bug, the rand offset was\n\t\t\t\t# between [0,1] instead of centered at 0, e.g. [-0.5, 0.5].\n\t\t\t\tu += convert(Float32, (rand()-0.5f0) / image_width)\n\t\t\t\tv += convert(Float32 ,(rand()-0.5f0) / image_height)\n\t\t\tend\n\t\t\tray = get_ray(cam, u, v)\n\t\t\taccum_color += ray_color(ray, scene)\n\t\tend\n\t\timg[i,j] = rgb_gamma2(accum_color / n_samples)\n\tend\n\timg\nend\n\n\n# ╔═╡ aa38117f-45e8-4070-a412-958f0ce19aa5\nrender(scene_2_spheres(), default_camera(), 96, 16)\n\n# ╔═╡ 9fd417cc-afa9-4f12-9c29-748f0522554c\nrender(scene_4_spheres(), default_camera(), 96, 16)\n\n# ╔═╡ a2221922-31be-42f3-8f70-845fae385d2c\nrender(scene_4_spheres(), default_camera(), 200, 256)\n\n# ╔═╡ ddf5883c-036a-4a21-908d-bb7cec731f7f\n#\"From C++: Image 15: Glass sphere that sometimes refracts\"\nfunction scene_diel_spheres(left_radius=0.5f0)::HittableList # dielectric spheres\n\tspheres = Sphere[]\n\t\n\t# small center sphere\n\tpush!(spheres, Sphere(SVector{3,Float32}(0f0,0f0,-1f0), 0.5f0, \n\t\t\t\t\t\t  Lambertian(SVector{3,Float32}(0.1f0,0.2f0,0.5f0))))\n\t\n\t# ground sphere (planet?)\n\tpush!(spheres, Sphere(SVector{3,Float32}(0f0,-100.5f0,-1f0), 100f0, \n\t\t\t\t\t\t  Lambertian(SVector{3,Float32}(0.8f0,0.8f0,0.0f0))))\n\t\n\t# left and right spheres.\n\t# Use a negative radius on the left sphere to create a \"thin bubble\" \n\tpush!(spheres, Sphere(SVector{3,Float32}(-1f0,0f0,-1f0), left_radius, \n\t\t\t\t\t\t  Dielectric(1.5f0))) \n\tpush!(spheres, Sphere(SVector{3,Float32}( 1f0,0f0,-1f0), 0.5f0, \n\t\t\t\t\t\t  Metal(SVector{3,Float32}(0.8f0,0.6f0,0.2f0), 0.0f0)))\n\tHittableList(spheres)\nend\n\n# ╔═╡ a1564d79-3628-4121-99a9-d3674e16eb04\nrender(scene_diel_spheres(), default_camera(), 96, 16)\n\n# ╔═╡ 330a8972-adbd-471b-ade1-15901a258cbb\nrender(scene_diel_spheres(), default_camera(), 200, 64)\n\n# ╔═╡ 2e9672e3-f2b8-439e-b1f3-3cc60a459885\n# Hollow Glass sphere using a negative radius\n# claforte: getting a weird black halo in the glass sphere... might be due to my\n# \"fix\" for previous black spots, by moving the RecordHit point a bit away from \n# the hit surface... \nrender(scene_diel_spheres(-0.5), default_camera(), 200, 64)\n\n# ╔═╡ 0587d381-b957-4c40-b6b7-e5e0fd46267b\nmd\"# Positioning camera\"\n\n# ╔═╡ 7c75b0d8-578d-4ca9-8d74-935c1ac582b9\nfunction scene_blue_red_spheres()::HittableList # dielectric spheres\n\tspheres = Sphere[]\n\tR = cos(pi/4)\n\tpush!(spheres, Sphere(@SVector[-R,0f0,-1f0], R, \n\t\t\t\t\t\t  Lambertian(@SVector[0f0,0f0,1f0]))) \n\tpush!(spheres, Sphere(@SVector[R,0f0,-1f0], R, \n\t\t\t\t\t\t  Lambertian(@SVector[1f0,0f0,0f0]))) \n\tHittableList(spheres)\nend\n\n# ╔═╡ dcde1539-23af-4abf-96d3-6a903add3ea8\nrender(scene_blue_red_spheres(), default_camera(), 96, 16)\n\n# ╔═╡ e7f5c672-0bd9-4cfe-8a47-17cd67aa01f4\nrender(scene_diel_spheres(), default_camera(@SVector[-2f0,2f0,1f0], \n\t@SVector[0f0,0f0,-1f0], @SVector[0f0,1f0,0f0], 20.0f0), 200, 256)\n\n# ╔═╡ e3ef265c-1911-429d-84be-5d5174d55fa1\nmd\"# Spheres with depth-of-field\"\n\n# ╔═╡ a7d95d91-6571-4696-bad3-2979296d5f84\nbegin\n\tt_lookfrom2 = @SVector[3.0f0,3.0f0,2.0f0]\n\tt_lookat2 = @SVector[0.0f0,0.0f0,-1.0f0]\n\tdist_to_focus2 = norm(t_lookfrom2-t_lookat2)\n\tt_cam2 = default_camera(t_lookfrom2, t_lookat2, @SVector[0.0f0,1.0f0,0.0f0], \n\t\t\t20.0f0, 16.0f0/9.0f0, 2.0f0, dist_to_focus2)\nend\n\n# ╔═╡ 5bc1a6eb-8867-48b4-b141-fc0636d36694\nrender(scene_diel_spheres(), t_cam2, 200, 128)\n\n# ╔═╡ 3c54cde0-6509-45e1-a4a0-26c6aa840b8e\nmd\"# Random spheres\"\n\n# ╔═╡ a52911a2-1e24-4237-81ca-f613913d29c1\nfunction scene_random_spheres()::HittableList # dielectric spheres\n\tspheres = Sphere[]\n\n\t# ground \n\tpush!(spheres, Sphere(@SVector[0f0,-1000f0,-1f0], 1000f0, \n\t\t\t\t\t\t  Lambertian(@SVector[0.5f0,0.5f0,0.5f0])))\n\n\tfor a in -11:10, b in -11:10\n\t\tchoose_mat = rand()\n\t\tcenter = @SVector[a + 0.9f0*rand(), 0.2f0, b + 0.90f0*rand()]\n\n\t\t# skip spheres too close?\n\t\tif norm(center - @SVector[4f0,0.2f0,0f0]) < 0.9f0 continue end \n\t\t\t\n\t\tif choose_mat < 0.8f0\n\t\t\t# diffuse\n\t\t\talbedo = @SVector[rand() for i ∈ 1:3] .* @SVector[rand() for i ∈ 1:3]\n\t\t\tpush!(spheres, Sphere(center, 0.2f0, Lambertian(albedo)))\n\t\telseif choose_mat < 0.95f0\n\t\t\t# metal\n\t\t\talbedo = @SVector[random_between(0.5f0,1.0f0) for i ∈ 1:3]\n\t\t\tfuzz = random_between(0.0f0, 5.0f0)\n\t\t\tpush!(spheres, Sphere(center, 0.2f0, Metal(albedo, fuzz)))\n\t\telse\n\t\t\t# glass\n\t\t\tpush!(spheres, Sphere(center, 0.2f0, Dielectric(1.5f0)))\n\t\tend\n\tend\n\n\tpush!(spheres, Sphere(@SVector[0f0,1f0,0f0], 1.0f0, Dielectric(1.5f0)))\n\tpush!(spheres, Sphere(@SVector[-4f0,1f0,0f0], 1.0f0, \n\t\t\t\t\t\t  Lambertian(@SVector[0.4f0,0.2f0,0.1f0])))\n\tpush!(spheres, Sphere(@SVector[4f0,1f0,0f0], 1.0f0, \n\t\t\t\t\t\t  Metal(@SVector[0.7f0,0.6f0,0.5f0], 0.0f0)))\n\tHittableList(spheres)\nend\n\n# ╔═╡ 541aa3e5-4632-4f74-8088-f08fe24e07f8\nscene_random_spheres()\n\n# ╔═╡ 840d2599-245c-4e6c-8813-4abdcd802b01\nbegin\n\tt_lookfrom1 = @SVector[13.0f0,2.0f0,3.0f0]\n\tt_lookat1 = @SVector[0.0f0,0.0f0,0.0f0]\n\tt_cam1 = default_camera(t_lookfrom1, t_lookat1, @SVector[0.0f0,1.0f0,0.0f0], \n\t\t\t\t\t\t\t20.0f0, 16.0f0/9.0f0, 0.1f0, 10.0f0)\nend\n\n# ╔═╡ da047747-1845-4c2b-b3cb-eaa6534ce5ff\nrender(scene_random_spheres(), t_cam1, 200, 32) # takes 3.2s\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nImages = \"916415d5-f1e6-5110-898d-aaa5f9f070e0\"\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nStaticArrays = \"90137ffa-7385-5640-81b9-e52037218182\"\n\n[compat]\nImages = \"~0.25.0\"\nStaticArrays = \"~1.2.13\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[AbstractFFTs]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"485ee0867925449198280d4af84bdb46a2a404d0\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"1.0.1\"\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[ArnoldiMethod]]\ndeps = [\"LinearAlgebra\", \"Random\", \"StaticArrays\"]\ngit-tree-sha1 = \"62e51b39331de8911e4a7ff6f5aaf38a5f4cc0ae\"\nuuid = \"ec485272-7323-5ecc-a04f-4719b315124d\"\nversion = \"0.2.0\"\n\n[[ArrayInterface]]\ndeps = [\"Compat\", \"IfElse\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"Static\"]\ngit-tree-sha1 = \"e527b258413e0c6d4f66ade574744c94edef81f8\"\nuuid = \"4fba245c-0d91-5ea0-9b3e-6abc04ee57a9\"\nversion = \"3.1.40\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[AxisAlgorithms]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"66771c8d21c8ff5e3a93379480a2307ac36863f7\"\nuuid = \"13072b0f-2c55-5437-9ae7-d433b7a33950\"\nversion = \"1.0.1\"\n\n[[AxisArrays]]\ndeps = [\"Dates\", \"IntervalSets\", \"IterTools\", \"RangeArrays\"]\ngit-tree-sha1 = \"d127d5e4d86c7680b20c35d40b503c74b9a39b5e\"\nuuid = \"39de3d68-74b9-583c-8d2d-e117c070f3a9\"\nversion = \"0.4.4\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[CEnum]]\ngit-tree-sha1 = \"215a9aa4a1f23fbd05b92769fdd62559488d70e9\"\nuuid = \"fa961155-64e5-5f13-b03f-caf6b980ea82\"\nversion = \"0.4.1\"\n\n[[CatIndices]]\ndeps = [\"CustomUnitRanges\", \"OffsetArrays\"]\ngit-tree-sha1 = \"a0f80a09780eed9b1d106a1bf62041c2efc995bc\"\nuuid = \"aafaddc9-749c-510e-ac4f-586e18779b91\"\nversion = \"0.2.2\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"f885e7e7c124f8c92650d61b9477b9ac2ee607dd\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.11.1\"\n\n[[ChangesOfVariables]]\ndeps = [\"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"9a1d594397670492219635b35a3d830b04730d62\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.1\"\n\n[[Clustering]]\ndeps = [\"Distances\", \"LinearAlgebra\", \"NearestNeighbors\", \"Printf\", \"SparseArrays\", \"Statistics\", \"StatsBase\"]\ngit-tree-sha1 = \"75479b7df4167267d75294d14b58244695beb2ac\"\nuuid = \"aaaa29a8-35af-508c-8bc3-b662a17a0fe5\"\nversion = \"0.14.2\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[ColorVectorSpace]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"LinearAlgebra\", \"SpecialFunctions\", \"Statistics\", \"TensorCore\"]\ngit-tree-sha1 = \"3f1f500312161f1ae067abe07d13b40f78f32e07\"\nuuid = \"c3611d14-8923-5661-9e6a-0046d554d3a4\"\nversion = \"0.9.8\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"dce3e3fea680869eaa0b774b2e8343e9ff442313\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.40.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[ComputationalResources]]\ngit-tree-sha1 = \"52cb3ec90e8a8bea0e62e275ba577ad0f74821f7\"\nuuid = \"ed09eef8-17a6-5b46-8889-db040fac31e3\"\nversion = \"0.3.2\"\n\n[[CoordinateTransformations]]\ndeps = [\"LinearAlgebra\", \"StaticArrays\"]\ngit-tree-sha1 = \"681ea870b918e7cff7111da58791d7f718067a19\"\nuuid = \"150eb455-5306-5404-9cee-2592286d6298\"\nversion = \"0.6.2\"\n\n[[CustomUnitRanges]]\ngit-tree-sha1 = \"1a3f97f907e6dd8983b744d2642651bb162a3f7a\"\nuuid = \"dc8bdbbb-1ca9-579f-8c36-e416f6a65cce\"\nversion = \"1.0.2\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataStructures]]\ndeps = [\"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"88d48e133e6d3dd68183309877eac74393daa7eb\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.17.20\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distances]]\ndeps = [\"LinearAlgebra\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"837c83e5574582e07662bbbba733964ff7c26b9d\"\nuuid = \"b4f34e82-e78d-54a5-968a-f98e89d6e8f7\"\nversion = \"0.10.6\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EllipsisNotation]]\ndeps = [\"ArrayInterface\"]\ngit-tree-sha1 = \"9aad812fb7c4c038da7cab5a069f502e6e3ae030\"\nuuid = \"da5c29d0-fa7d-589e-88eb-ea29b0a81949\"\nversion = \"1.1.1\"\n\n[[FFTViews]]\ndeps = [\"CustomUnitRanges\", \"FFTW\"]\ngit-tree-sha1 = \"cbdf14d1e8c7c8aacbe8b19862e0179fd08321c2\"\nuuid = \"4f61f5a4-77b1-5117-aa51-3ab5ef4ef0cd\"\nversion = \"0.3.2\"\n\n[[FFTW]]\ndeps = [\"AbstractFFTs\", \"FFTW_jll\", \"LinearAlgebra\", \"MKL_jll\", \"Preferences\", \"Reexport\"]\ngit-tree-sha1 = \"463cb335fa22c4ebacfd1faba5fde14edb80d96c\"\nuuid = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nversion = \"1.4.5\"\n\n[[FFTW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea\"\nuuid = \"f5851436-0d7a-5f13-b9de-f02708fd171a\"\nversion = \"3.3.10+0\"\n\n[[FileIO]]\ndeps = [\"Pkg\", \"Requires\", \"UUIDs\"]\ngit-tree-sha1 = \"2db648b6712831ecb333eae76dbfd1c156ca13bb\"\nuuid = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nversion = \"1.11.2\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Graphics]]\ndeps = [\"Colors\", \"LinearAlgebra\", \"NaNMath\"]\ngit-tree-sha1 = \"1c5a84319923bea76fa145d49e93aa4394c73fc2\"\nuuid = \"a2bd30eb-e257-5431-a919-1863eab51364\"\nversion = \"1.1.1\"\n\n[[Graphs]]\ndeps = [\"ArnoldiMethod\", \"DataStructures\", \"Distributed\", \"Inflate\", \"LinearAlgebra\", \"Random\", \"SharedArrays\", \"SimpleTraits\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"92243c07e786ea3458532e199eb3feee0e7e08eb\"\nuuid = \"86223c79-3864-5bf0-83f7-82e725a168b6\"\nversion = \"1.4.1\"\n\n[[IfElse]]\ngit-tree-sha1 = \"debdd00ffef04665ccbb3e150747a77560e8fad1\"\nuuid = \"615f187c-cbe4-4ef1-ba3b-2fcf58d6d173\"\nversion = \"0.1.1\"\n\n[[ImageAxes]]\ndeps = [\"AxisArrays\", \"ImageBase\", \"ImageCore\", \"Reexport\", \"SimpleTraits\"]\ngit-tree-sha1 = \"c54b581a83008dc7f292e205f4c409ab5caa0f04\"\nuuid = \"2803e5a7-5153-5ecf-9a86-9b4c37f5f5ac\"\nversion = \"0.6.10\"\n\n[[ImageBase]]\ndeps = [\"ImageCore\", \"Reexport\"]\ngit-tree-sha1 = \"b51bb8cae22c66d0f6357e3bcb6363145ef20835\"\nuuid = \"c817782e-172a-44cc-b673-b171935fbb9e\"\nversion = \"0.1.5\"\n\n[[ImageContrastAdjustment]]\ndeps = [\"ImageCore\", \"ImageTransformations\", \"Parameters\"]\ngit-tree-sha1 = \"0d75cafa80cf22026cea21a8e6cf965295003edc\"\nuuid = \"f332f351-ec65-5f6a-b3d1-319c6670881a\"\nversion = \"0.3.10\"\n\n[[ImageCore]]\ndeps = [\"AbstractFFTs\", \"ColorVectorSpace\", \"Colors\", \"FixedPointNumbers\", \"Graphics\", \"MappedArrays\", \"MosaicViews\", \"OffsetArrays\", \"PaddedViews\", \"Reexport\"]\ngit-tree-sha1 = \"9a5c62f231e5bba35695a20988fc7cd6de7eeb5a\"\nuuid = \"a09fc81d-aa75-5fe9-8630-4744c3626534\"\nversion = \"0.9.3\"\n\n[[ImageDistances]]\ndeps = [\"Distances\", \"ImageCore\", \"ImageMorphology\", \"LinearAlgebra\", \"Statistics\"]\ngit-tree-sha1 = \"7a20463713d239a19cbad3f6991e404aca876bda\"\nuuid = \"51556ac3-7006-55f5-8cb3-34580c88182d\"\nversion = \"0.2.15\"\n\n[[ImageFiltering]]\ndeps = [\"CatIndices\", \"ComputationalResources\", \"DataStructures\", \"FFTViews\", \"FFTW\", \"ImageBase\", \"ImageCore\", \"LinearAlgebra\", \"OffsetArrays\", \"Reexport\", \"SparseArrays\", \"StaticArrays\", \"Statistics\", \"TiledIteration\"]\ngit-tree-sha1 = \"15bd05c1c0d5dbb32a9a3d7e0ad2d50dd6167189\"\nuuid = \"6a3955dd-da59-5b1f-98d4-e7296123deb5\"\nversion = \"0.7.1\"\n\n[[ImageIO]]\ndeps = [\"FileIO\", \"Netpbm\", \"OpenEXR\", \"PNGFiles\", \"TiffImages\", \"UUIDs\"]\ngit-tree-sha1 = \"a2951c93684551467265e0e32b577914f69532be\"\nuuid = \"82e4d734-157c-48bb-816b-45c225c6df19\"\nversion = \"0.5.9\"\n\n[[ImageMagick]]\ndeps = [\"FileIO\", \"ImageCore\", \"ImageMagick_jll\", \"InteractiveUtils\", \"Libdl\", \"Pkg\", \"Random\"]\ngit-tree-sha1 = \"5bc1cb62e0c5f1005868358db0692c994c3a13c6\"\nuuid = \"6218d12a-5da1-5696-b52f-db25d2ecc6d1\"\nversion = \"1.2.1\"\n\n[[ImageMagick_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pkg\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"ea2b6fd947cdfc43c6b8c15cff982533ec1f72cd\"\nuuid = \"c73af94c-d91f-53ed-93a7-00f77d67a9d7\"\nversion = \"6.9.12+0\"\n\n[[ImageMetadata]]\ndeps = [\"AxisArrays\", \"ImageAxes\", \"ImageBase\", \"ImageCore\"]\ngit-tree-sha1 = \"36cbaebed194b292590cba2593da27b34763804a\"\nuuid = \"bc367c6b-8a6b-528e-b4bd-a4b897500b49\"\nversion = \"0.9.8\"\n\n[[ImageMorphology]]\ndeps = [\"ImageCore\", \"LinearAlgebra\", \"Requires\", \"TiledIteration\"]\ngit-tree-sha1 = \"5581e18a74a5838bd919294a7138c2663d065238\"\nuuid = \"787d08f9-d448-5407-9aad-5290dd7ab264\"\nversion = \"0.3.0\"\n\n[[ImageQualityIndexes]]\ndeps = [\"ImageContrastAdjustment\", \"ImageCore\", \"ImageDistances\", \"ImageFiltering\", \"OffsetArrays\", \"Statistics\"]\ngit-tree-sha1 = \"1d2d73b14198d10f7f12bf7f8481fd4b3ff5cd61\"\nuuid = \"2996bd0c-7a13-11e9-2da2-2f5ce47296a9\"\nversion = \"0.3.0\"\n\n[[ImageSegmentation]]\ndeps = [\"Clustering\", \"DataStructures\", \"Distances\", \"Graphs\", \"ImageCore\", \"ImageFiltering\", \"ImageMorphology\", \"LinearAlgebra\", \"MetaGraphs\", \"RegionTrees\", \"SimpleWeightedGraphs\", \"StaticArrays\", \"Statistics\"]\ngit-tree-sha1 = \"36832067ea220818d105d718527d6ed02385bf22\"\nuuid = \"80713f31-8817-5129-9cf8-209ff8fb23e1\"\nversion = \"1.7.0\"\n\n[[ImageShow]]\ndeps = [\"Base64\", \"FileIO\", \"ImageBase\", \"ImageCore\", \"OffsetArrays\", \"StackViews\"]\ngit-tree-sha1 = \"d0ac64c9bee0aed6fdbb2bc0e5dfa9a3a78e3acc\"\nuuid = \"4e3cecfd-b093-5904-9786-8bbb286a6a31\"\nversion = \"0.3.3\"\n\n[[ImageTransformations]]\ndeps = [\"AxisAlgorithms\", \"ColorVectorSpace\", \"CoordinateTransformations\", \"ImageBase\", \"ImageCore\", \"Interpolations\", \"OffsetArrays\", \"Rotations\", \"StaticArrays\"]\ngit-tree-sha1 = \"b4b161abc8252d68b13c5cc4a5f2ba711b61fec5\"\nuuid = \"02fcd773-0e25-5acc-982a-7f6622650795\"\nversion = \"0.9.3\"\n\n[[Images]]\ndeps = [\"Base64\", \"FileIO\", \"Graphics\", \"ImageAxes\", \"ImageBase\", \"ImageContrastAdjustment\", \"ImageCore\", \"ImageDistances\", \"ImageFiltering\", \"ImageIO\", \"ImageMagick\", \"ImageMetadata\", \"ImageMorphology\", \"ImageQualityIndexes\", \"ImageSegmentation\", \"ImageShow\", \"ImageTransformations\", \"IndirectArrays\", \"IntegralArrays\", \"Random\", \"Reexport\", \"SparseArrays\", \"StaticArrays\", \"Statistics\", \"StatsBase\", \"TiledIteration\"]\ngit-tree-sha1 = \"35dc1cd115c57ad705c7db9f6ef5cc14412e8f00\"\nuuid = \"916415d5-f1e6-5110-898d-aaa5f9f070e0\"\nversion = \"0.25.0\"\n\n[[Imath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"87f7662e03a649cffa2e05bf19c303e168732d3e\"\nuuid = \"905a6f67-0a94-5f89-b386-d35d92009cd1\"\nversion = \"3.1.2+0\"\n\n[[IndirectArrays]]\ngit-tree-sha1 = \"012e604e1c7458645cb8b436f8fba789a51b257f\"\nuuid = \"9b13fd28-a010-5f03-acff-a1bbcff69959\"\nversion = \"1.0.0\"\n\n[[Inflate]]\ngit-tree-sha1 = \"f5fc07d4e706b84f72d54eedcc1c13d92fb0871c\"\nuuid = \"d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9\"\nversion = \"0.1.2\"\n\n[[IntegralArrays]]\ndeps = [\"IntervalSets\"]\ngit-tree-sha1 = \"26c4df96fdf6127a92d53cb8ffb577104617adca\"\nuuid = \"1d092043-8f09-5a30-832f-7509e371ab51\"\nversion = \"0.1.0\"\n\n[[IntelOpenMP_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d979e54b71da82f3a65b62553da4fc3d18c9004c\"\nuuid = \"1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0\"\nversion = \"2018.0.3+2\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[Interpolations]]\ndeps = [\"AxisAlgorithms\", \"ChainRulesCore\", \"LinearAlgebra\", \"OffsetArrays\", \"Random\", \"Ratios\", \"Requires\", \"SharedArrays\", \"SparseArrays\", \"StaticArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"61aa005707ea2cebf47c8d780da8dc9bc4e0c512\"\nuuid = \"a98d9a8b-a2ab-59e6-89dd-64a1c18fca59\"\nversion = \"0.13.4\"\n\n[[IntervalSets]]\ndeps = [\"Dates\", \"EllipsisNotation\", \"Statistics\"]\ngit-tree-sha1 = \"3cc368af3f110a767ac786560045dceddfc16758\"\nuuid = \"8197267c-284f-5f27-9208-e0e47529a953\"\nversion = \"0.5.3\"\n\n[[InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.2\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[JLD2]]\ndeps = [\"DataStructures\", \"FileIO\", \"MacroTools\", \"Mmap\", \"Pkg\", \"Printf\", \"Reexport\", \"TranscodingStreams\", \"UUIDs\"]\ngit-tree-sha1 = \"46b7834ec8165c541b0b5d1c8ba63ec940723ffb\"\nuuid = \"033835bb-8acc-5ee8-8aae-3f567f8a3819\"\nversion = \"0.4.15\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"be9eef9f9d78cecb6f262f3c10da151a6c5ab827\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.5\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MKL_jll]]\ndeps = [\"Artifacts\", \"IntelOpenMP_jll\", \"JLLWrappers\", \"LazyArtifacts\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"5455aef09b40e5020e1520f551fa3135040d4ed0\"\nuuid = \"856f044c-d86e-5d09-b602-aeab76dc8ba7\"\nversion = \"2021.1.1+2\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[MappedArrays]]\ngit-tree-sha1 = \"e8b359ef06ec72e8c030463fe02efe5527ee5142\"\nuuid = \"dbb5928d-eab1-5f90-85c2-b9b0edb7c900\"\nversion = \"0.4.1\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[MetaGraphs]]\ndeps = [\"Graphs\", \"JLD2\", \"Random\"]\ngit-tree-sha1 = \"2af69ff3c024d13bde52b34a2a7d6887d4e7b438\"\nuuid = \"626554b9-1ddb-594c-aa3c-2596fe9399a5\"\nversion = \"0.7.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MosaicViews]]\ndeps = [\"MappedArrays\", \"OffsetArrays\", \"PaddedViews\", \"StackViews\"]\ngit-tree-sha1 = \"b34e3bc3ca7c94914418637cb10cc4d1d80d877d\"\nuuid = \"e94cdb99-869f-56ef-bcf0-1ae2bcbe0389\"\nversion = \"0.3.3\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[NearestNeighbors]]\ndeps = [\"Distances\", \"StaticArrays\"]\ngit-tree-sha1 = \"16baacfdc8758bc374882566c9187e785e85c2f0\"\nuuid = \"b8a86587-4115-5ab1-83bc-aa920d37bbce\"\nversion = \"0.4.9\"\n\n[[Netpbm]]\ndeps = [\"FileIO\", \"ImageCore\"]\ngit-tree-sha1 = \"18efc06f6ec36a8b801b23f076e3c6ac7c3bf153\"\nuuid = \"f09324ee-3d7c-5217-9330-fc30815ba969\"\nversion = \"1.0.2\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[OffsetArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"043017e0bdeff61cfbb7afeb558ab29536bbb5ed\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.8\"\n\n[[OpenEXR]]\ndeps = [\"Colors\", \"FileIO\", \"OpenEXR_jll\"]\ngit-tree-sha1 = \"327f53360fdb54df7ecd01e96ef1983536d1e633\"\nuuid = \"52e1d378-f018-4a11-a4be-720524705ac7\"\nversion = \"0.3.2\"\n\n[[OpenEXR_jll]]\ndeps = [\"Artifacts\", \"Imath_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"923319661e9a22712f24596ce81c54fc0366f304\"\nuuid = \"18a262bb-aa17-5467-a713-aee519bc75cb\"\nversion = \"3.1.1+0\"\n\n[[OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PNGFiles]]\ndeps = [\"Base64\", \"CEnum\", \"ImageCore\", \"IndirectArrays\", \"OffsetArrays\", \"libpng_jll\"]\ngit-tree-sha1 = \"6d105d40e30b635cfed9d52ec29cf456e27d38f8\"\nuuid = \"f57f5aa1-a3ce-4bc8-8ab9-96f992907883\"\nversion = \"0.3.12\"\n\n[[PaddedViews]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"646eed6f6a5d8df6708f15ea7e02a7a2c4fe4800\"\nuuid = \"5432bcbf-9aad-5242-b902-cca2824c8663\"\nversion = \"0.5.10\"\n\n[[Parameters]]\ndeps = [\"OrderedCollections\", \"UnPack\"]\ngit-tree-sha1 = \"34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe\"\nuuid = \"d96e819e-fc66-5662-9728-84c9c7592b0a\"\nversion = \"0.12.3\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PkgVersion]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"a7a7e1a88853564e551e4eba8650f8c38df79b37\"\nuuid = \"eebad327-c553-4316-9ea0-9fa01ccd7688\"\nversion = \"0.1.1\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[ProgressMeter]]\ndeps = [\"Distributed\", \"Printf\"]\ngit-tree-sha1 = \"afadeba63d90ff223a6a48d2009434ecee2ec9e8\"\nuuid = \"92933f4c-e287-5a05-a399-4b506db050ca\"\nversion = \"1.7.1\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RangeArrays]]\ngit-tree-sha1 = \"b9039e93773ddcfc828f12aadf7115b4b4d225f5\"\nuuid = \"b3c3ace0-ae52-54e7-9d0b-2c1406fd6b9d\"\nversion = \"0.3.2\"\n\n[[Ratios]]\ndeps = [\"Requires\"]\ngit-tree-sha1 = \"01d341f502250e81f6fec0afe662aa861392a3aa\"\nuuid = \"c84ed2f1-dad5-54f0-aa8e-dbefe2724439\"\nversion = \"0.4.2\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[RegionTrees]]\ndeps = [\"IterTools\", \"LinearAlgebra\", \"StaticArrays\"]\ngit-tree-sha1 = \"4618ed0da7a251c7f92e869ae1a19c74a7d2a7f9\"\nuuid = \"dee08c22-ab7f-5625-9660-a9af2021b33f\"\nversion = \"0.3.2\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[Rotations]]\ndeps = [\"LinearAlgebra\", \"Random\", \"StaticArrays\", \"Statistics\"]\ngit-tree-sha1 = \"6a23472b6b097d66da87785b61137142ac104f94\"\nuuid = \"6038ab10-8711-5258-84ad-4b1120ba62dc\"\nversion = \"1.0.4\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[SimpleTraits]]\ndeps = [\"InteractiveUtils\", \"MacroTools\"]\ngit-tree-sha1 = \"5d7e3f4e11935503d3ecaf7186eac40602e7d231\"\nuuid = \"699a6c99-e7fa-54fc-8d76-47d257e15c1d\"\nversion = \"0.9.4\"\n\n[[SimpleWeightedGraphs]]\ndeps = [\"Graphs\", \"LinearAlgebra\", \"Markdown\", \"SparseArrays\", \"Test\"]\ngit-tree-sha1 = \"a6f404cc44d3d3b28c793ec0eb59af709d827e4e\"\nuuid = \"47aef6b3-ad0c-573a-a1e2-d07658019622\"\nversion = \"1.2.1\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"e08890d19787ec25029113e88c34ec20cac1c91e\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"2.0.0\"\n\n[[StackViews]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"46e589465204cd0c08b4bd97385e4fa79a0c770c\"\nuuid = \"cae243ae-269e-4f55-b966-ac2d0dc13c15\"\nversion = \"0.1.1\"\n\n[[Static]]\ndeps = [\"IfElse\"]\ngit-tree-sha1 = \"e7bc80dc93f50857a5d1e3c8121495852f407e6a\"\nuuid = \"aedffcd0-7271-4cad-89d0-dc628f76c6d3\"\nversion = \"0.4.0\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3c76dde64d03699e074ac02eb2e8ba8254d428da\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.13\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"0f2aa8e32d511f758a2ce49208181f7733a0936a\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.1.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"2bb0cb32026a66037360606510fca5984ccc6b75\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.13\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[TensorCore]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"1feb45f88d133a655e001435632f019a9a1bcdb6\"\nuuid = \"62fd8b95-f654-4bbd-a8a5-9c27f68ccd50\"\nversion = \"0.1.1\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[TiffImages]]\ndeps = [\"ColorTypes\", \"DocStringExtensions\", \"FileIO\", \"FixedPointNumbers\", \"IndirectArrays\", \"Inflate\", \"OffsetArrays\", \"OrderedCollections\", \"PkgVersion\", \"ProgressMeter\"]\ngit-tree-sha1 = \"945b8d87c5e8d5e34e6207ee15edb9d11ae44716\"\nuuid = \"731e570b-9d59-4bfa-96dc-6df516fadf69\"\nversion = \"0.4.3\"\n\n[[TiledIteration]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"5683455224ba92ef59db72d10690690f4a8dc297\"\nuuid = \"06e1c1a7-607b-532d-9fad-de7d9aa2abac\"\nversion = \"0.3.1\"\n\n[[TranscodingStreams]]\ndeps = [\"Random\", \"Test\"]\ngit-tree-sha1 = \"216b95ea110b5972db65aa90f88d8d89dcb8851c\"\nuuid = \"3bb67fe8-82b1-5028-8e26-92a6c54297fa\"\nversion = \"0.9.6\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[UnPack]]\ngit-tree-sha1 = \"387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b\"\nuuid = \"3a884ed6-31ef-47d7-9d2a-63182c4928ed\"\nversion = \"1.0.2\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[WoodburyMatrices]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"de67fa59e33ad156a590055375a30b23c40299d3\"\nuuid = \"efce3f68-66dc-5838-9240-27a6d6f5f9b6\"\nversion = \"0.5.5\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─0866add2-9b95-45e7-8081-c01cd2a66911\n# ╟─611d5eae-4b09-11ec-27bf-ef4a1ecdcc41\n# ╟─97bb4432-ed41-423b-b4d9-bafc519de641\n# ╠═38fdd4ef-c383-4f97-8451-c6f602307e7d\n# ╠═84d29423-cf11-41c3-af4d-c5f63b1ef23e\n# ╠═7d26fef0-9a06-479a-ae08-e9d04e455767\n# ╠═f29ad2c0-c3ff-484d-8fdd-dff34d2bb863\n# ╠═2192e695-4378-4b47-8ce0-353636cd2cd1\n# ╠═538d1aa5-07f9-4fca-8410-ef63b8a6857b\n# ╠═8aeb7373-6bb0-4544-8655-fa941561688c\n# ╠═154d736b-8fdc-44af-ae2a-9e5ba6d2c92e\n# ╟─216922d8-613a-4ac1-9559-40878e6587e2\n# ╠═961fd749-d439-4dfa-ae21-b1659dc54511\n# ╠═3dceca5d-7d1e-425b-9516-24e0a24adaff\n# ╠═f8007c75-9487-414a-9592-138a696c2957\n# ╠═668030c8-24a7-4aa6-b858-cedf8ac5f988\n# ╠═3eb50f44-9091-45e8-a7e1-92d25b4b2090\n# ╠═78f209df-d176-4711-80fc-a8054771f105\n# ╠═e88de775-6904-4182-8209-06db22758470\n# ╠═5fd1ec87-3616-448a-ab4d-fede804b26d5\n# ╠═a0893bf4-9607-4853-8162-9f34d3337060\n# ╠═cfbcb883-d12e-4ad3-a084-064749bddcdb\n# ╠═6348c03d-e8ec-4dbb-9f8a-8e4a48bb1cb3\n# ╠═dbc8fc2d-39c2-4ec9-b82d-7c6a8b12dde7\n# ╠═53832af1-a9be-4e02-8b71-a70dae63c233\n# ╠═81b4c9e4-9f93-45ca-9fa0-7e9686a55e9a\n# ╟─772674b0-5c40-4457-9526-5b4e81cca711\n# ╠═709861a3-202a-4bff-a46d-b46c6e14b334\n# ╠═135000d6-a675-4d8b-9385-50853bf9a169\n# ╠═7d1146d7-74da-42e6-92c2-1312ed03f70d\n# ╠═46a4aa4b-82c1-4941-b36d-dc8c977af2bc\n# ╠═203a9b25-742a-4d8b-adee-862ce4c67670\n# ╠═2e98c6bd-0289-4105-ad25-24414ecf2750\n# ╠═c0c23cb3-6a57-487d-943a-af4330a94ffe\n# ╟─678214c5-de81-489f-b002-c343d48071c9\n# ╠═cbb6418c-79e9-4359-80a6-40a8fa40679e\n# ╠═14be6068-6a15-4fad-ac0a-f156da71f103\n# ╠═64ef0313-2d2b-49d5-a1a1-3b04426a82f8\n# ╠═971777a6-f269-4344-8dba-7a55118396e5\n# ╠═655ffa6c-f1e9-4149-8f1d-51145c5a51e4\n# ╟─9075f8ed-f319-486d-94b2-486806aba3fd\n# ╠═c00e2004-2002-4dd2-98ed-f898ef2c14f1\n# ╠═b7399fb8-6205-41ea-9c70-eb62daedcefb\n# ╠═1d04159d-87bd-4cf8-a73c-817f20ca1026\n# ╟─fed81f09-e4a0-433f-99e8-261096114b7b\n# ╠═24e8740a-8e44-4206-b2b6-c4a55002dad8\n# ╠═359832af-7598-4c45-8033-c28cb0d86772\n# ╠═ed6ab8be-587c-4cb6-8172-618c74d3f9cc\n# ╠═a65c68c9-e489-465a-9687-93ae9da14a5e\n# ╠═2c4b4453-1a46-4889-9a14-16b18cc8c240\n# ╠═98c43f3f-4bfc-49db-806a-850b7d75b5a4\n# ╠═3b570d37-f407-41d8-b8a0-a0af4d85b14d\n# ╠═138bb5b6-0f45-4f13-8339-5110eb7cd1ff\n# ╟─6b36d245-bf01-45a7-b119-8315226dd4a3\n# ╠═4a396b3f-f920-4ec2-91f6-7d61fe2b9699\n# ╠═427f247c-055c-459e-9862-26e9f6f3e24f\n# ╠═88e51c27-0f28-4dcc-b9e9-ac44eeb876f5\n# ╠═7c4a67b2-8208-4cd4-b1ea-16f6f50adfe8\n# ╠═ca649864-5a6d-4ca7-896e-e80e8a48443e\n# ╠═485f9c5b-4c5d-453c-b190-e84ae0cd1a21\n# ╠═c63d10c2-dd43-4836-83ee-61b782545a02\n# ╠═78efebc5-53fd-417d-bd9e-667fd504e3fd\n# ╠═05e57afd-6eb9-42c5-9666-7be3771fa6b8\n# ╠═08e18ae5-9927-485e-9644-552f03e06f27\n# ╠═737e2f87-82f5-45b6-a76c-4f560c29f5b9\n# ╠═f72214f9-03c4-4ba3-bb84-069256446b31\n# ╠═0bf88264-d4c5-4d5a-babe-d2433e46024d\n# ╠═555bea1d-5178-48dd-87e6-4e2a2471a5dd\n# ╠═c299ca47-46c4-42da-9f8b-ae3abbeb6e51\n# ╟─851c002c-dc23-4999-b28c-a716c5d2d42c\n# ╠═70530f8e-1b29-4588-927f-d38d5d12d5c9\n# ╠═c5349670-4df4-421f-9d5a-b28c1b9040c2\n# ╟─282a4912-7a6e-44ae-90eb-f2f7c8f3d0f4\n# ╠═a0e5a1f3-244f-427b-a335-7e233af1d9d8\n# ╠═5d00f26b-35f2-4071-8e04-227ffc25f184\n# ╠═c1aef1be-79d4-4417-be36-ae8416465986\n# ╠═94081092-afc6-4359-bd2c-15e8407bf70e\n# ╠═813eaa13-2eb2-4302-9e4d-5d1dab0ac7c4\n# ╟─891ce2c8-f8b2-472b-a8d9-389dafddcf22\n# ╠═64104df6-4b79-4329-bfed-14619aa73e3c\n# ╠═aa38117f-45e8-4070-a412-958f0ce19aa5\n# ╠═9fd417cc-afa9-4f12-9c29-748f0522554c\n# ╠═a2221922-31be-42f3-8f70-845fae385d2c\n# ╟─5f1bae02-d425-4a73-8668-d6383faba79d\n# ╟─71f3626c-e61d-4838-82b9-ac8a978c0cb4\n# ╟─fbba5135-7ea3-4471-938a-be13c764feff\n# ╠═9dc64353-c41c-45b4-aacd-12d5d6117c58\n# ╠═bbfd4db5-3650-4f27-9777-2ff981c3d28b\n# ╠═f5c4e502-048c-4fcd-879f-eaeb4430c012\n# ╠═167cc207-7be6-4624-8425-2df81b3f6c3b\n# ╠═ae3b8f15-985d-4f74-ac8c-86a3ffc3b8b1\n# ╠═ddf5883c-036a-4a21-908d-bb7cec731f7f\n# ╠═a1564d79-3628-4121-99a9-d3674e16eb04\n# ╠═330a8972-adbd-471b-ade1-15901a258cbb\n# ╠═2e9672e3-f2b8-439e-b1f3-3cc60a459885\n# ╟─0587d381-b957-4c40-b6b7-e5e0fd46267b\n# ╠═7c75b0d8-578d-4ca9-8d74-935c1ac582b9\n# ╠═dcde1539-23af-4abf-96d3-6a903add3ea8\n# ╠═e7f5c672-0bd9-4cfe-8a47-17cd67aa01f4\n# ╟─e3ef265c-1911-429d-84be-5d5174d55fa1\n# ╠═a7d95d91-6571-4696-bad3-2979296d5f84\n# ╠═5bc1a6eb-8867-48b4-b141-fc0636d36694\n# ╟─3c54cde0-6509-45e1-a4a0-26c6aa840b8e\n# ╠═a52911a2-1e24-4237-81ca-f613913d29c1\n# ╠═541aa3e5-4632-4f74-8088-f08fe24e07f8\n# ╠═840d2599-245c-4e6c-8813-4abdcd802b01\n# ╠═da047747-1845-4c2b-b3cb-eaa6534ce5ff\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "3dfbc0f712e0ff91161b27db21762e611b00b965", "size": 54879, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pluto_RayTracingWeekend.jl", "max_stars_repo_name": "one-pr/RayTracingWeekend.jl", "max_stars_repo_head_hexsha": "7d2eaf65dc8e117b9d800e692df105aaa8c827b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pluto_RayTracingWeekend.jl", "max_issues_repo_name": "one-pr/RayTracingWeekend.jl", "max_issues_repo_head_hexsha": "7d2eaf65dc8e117b9d800e692df105aaa8c827b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pluto_RayTracingWeekend.jl", "max_forks_repo_name": "one-pr/RayTracingWeekend.jl", "max_forks_repo_head_hexsha": "7d2eaf65dc8e117b9d800e692df105aaa8c827b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2627865961, "max_line_length": 419, "alphanum_fraction": 0.7248674356, "num_tokens": 25180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7604135605376537}}
{"text": "###############################################\n#FEniCS tutorial demo program: Heat equation with Dirichlet conditions.\n#Test problem is chosen to give an exact solution at all nodes of the mesh.\n#  u'= Laplace(u) + f  in the unit square\n#  u = u_D             on the boundary\n#  u = u_0             at t = 0\n#  u = 1 + x^2 + α*y^2 + β*t\n#  f = β - 2 - 2*α\n###############################################\n\nmodule ft03\n\nusing FenicsPy\n\nT = 2.0            # final time\nnum_steps = 10     # number of time steps\nΔt = T / num_steps # time step size\nα = 3          # parameter α\nβ = 1.2         # parameter β\n\n# Create mesh and define function space\nnx = ny = 8\nmesh = UnitSquareMesh(nx, ny)\nV = FunctionSpace(mesh, \"P\", 1)\n\n# Define boundary condition\nu_D = Expression(\"1 + x[0]*x[0] + alpha*x[1]*x[1] + beta*t\",\n                 degree=2, alpha=α, beta=β, t=0)\n\nbc = DirichletBC(V, u_D, \"on_boundary\")\n\n# Define initial value\nu_n = interpolate(u_D, V)\n#u_n = project(u_D, V)\n\n# Define variational problem\nu = TrialFunction(V)\nv = TestFunction(V)\nf = Constant(β - 2 - 2*α)\n\nF = u*v*dx + Δt*dot(grad(u), grad(v))*dx - (u_n + Δt*f)*v*dx\na = lhs(F)\nL = rhs(F)\n\n# Time-stepping\nu = FeFunction(V)\n\nt = 0\nfor n = 1:num_steps\n\n    # Update current time\n    global t += Δt\n    #u_D.t = t\n\n    # Compute solution\n    solve(a == L, u, bc)\n\n    # Plot solution\n    #plot(u)\n\n    # Compute error at vertices\n    u_e = interpolate(u_D, V)\n    error = max(abs.(array(u_e)-array(u))...)\n    println(\"t = \", t, \"\\t error = \", error)\n\n    # Update previous solution\n    u_n.assign(u)\n\nend\n\nend # module ft03\n\n", "meta": {"hexsha": "9d1889fde7a6a9ba58b993fbc22f355f08d7a035", "size": 1588, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ft03_heat.jl", "max_stars_repo_name": "chaoskey/FenicsPy.jl", "max_stars_repo_head_hexsha": "18b42f6b193a220702d544560f403a9917adda6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/ft03_heat.jl", "max_issues_repo_name": "chaoskey/FenicsPy.jl", "max_issues_repo_head_hexsha": "18b42f6b193a220702d544560f403a9917adda6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ft03_heat.jl", "max_forks_repo_name": "chaoskey/FenicsPy.jl", "max_forks_repo_head_hexsha": "18b42f6b193a220702d544560f403a9917adda6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7534246575, "max_line_length": 75, "alphanum_fraction": 0.5541561713, "num_tokens": 512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.7603926738668159}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.20\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ e429e976-30d8-11eb-27dd-590119e09f74\nusing DifferentialEquations, PlutoUI\n\n# ╔═╡ 167e7be6-30dc-11eb-15de-ad9ff925a787\nusing Plots; gr()\n\n# ╔═╡ cdab643c-30da-11eb-29f6-53bdde7b82f5\n\n\n# ╔═╡ d560f3f6-30da-11eb-31dc-f510ae97bada\n\n\n# ╔═╡ c93b2276-30db-11eb-1669-27ae204265d1\nf = function (du,u,p,t) # Define f as an in-place update into du\n    a,b,c,d = p\n du[1] = a*u[1] - b*u[1]*u[2]\n    du[2] = -c*u[2]+ d*u[1]*u[2]\nend \n\n\n# ╔═╡ 210ce916-30dd-11eb-0321-4fb5cae1d9f3\nmd\"\"\"\nEnter the exponential growth of the prey:\n$(@bind a Slider(0.00 : 0.1 : 10; default=3.0, show_value=true))\n\n\nEnter the rate at which predator prey interactions will result in predator eating the prey:\n$(@bind b Slider(0.00 : 0.1 : 10; default=2.0, show_value=true))\n\nEnter the rate at which the predators growth is limited by eating only prey:\n$(@bind c Slider(0.00 : 0.1 : 10; default=1.0, show_value=true))\n\nEnter the exponential decline of the predator:\n$(@bind d Slider(0.00 : 0.1 : 10; default=4.0, show_value=true))\n\"\"\"\n\n# ╔═╡ 3fa4a936-30dd-11eb-3ef1-8bb442940777\nbegin\np = (a,b,c,d)\nend\n\n# ╔═╡ 5a535432-30fe-11eb-3442-817440f3830e\nmd\"Enter a value for x\n$(@bind x Slider(0.00 : 0.1 : 10; default=1.0, show_value=true))\n\nEnter a value for y\n$(@bind y Slider(0.00 : 0.1 : 10; default=1.0, show_value=true))\"\n\n# ╔═╡ f6f9f872-30db-11eb-25d3-f18fdd57d80c\nu0 = [x;y]; tspan = (0.0,10.0)\n\n# ╔═╡ 986c0e84-31bd-11eb-27af-d1702ee5442e\nprob = ODEProblem(f,u0,tspan,p);\n\n# ╔═╡ a063e0d0-31bd-11eb-056b-cb400ad0e45b\nsol = solve(prob);\n\n# ╔═╡ 1ce67d12-30dc-11eb-3f11-4b72daa20236\nplot(sol,title=\"Population of predator/prey over time\")\n\n# ╔═╡ d3028ce4-31bd-11eb-1710-d5a7ecba6bfe\nmd\" ## Scenerio One\n**How does changing the growth rate of the prey affect the population of the predators and prey over time?**\n\nAs the growth rate of the prey increases, the amount of population fluctuations increase. Looking at the graph, there are more relative maximums and minimums as the value of a increases, which means there are more rapid changes in populations.\n\n## Scenerio Two\n**How does changing the rate at which the predator eats the prey affect the overall population of the predators and preys over time?**\n\nAs the predation rate increases, the rate at which the prey populates decreases.\n\n## Scenerio Three\n**How does changing the limit on the predator affect the overall population of the predators and preys over time?**\n\nAs the limit on the predator increases, the frequency of population change increases. The graph squeezes and the number of periods(in the graph) increases. The maximum point in the population also increases. \n\n## Scenerio Four\n**How does changing the rate of predator decline affect the overall population of predator and prey over time?**\n\nThe course of the predator population stays the same over time, but the rate of population growth and decline for the prey as the maximums for the prey shrinks as the rate of predator decline increases.\n\n\n\"\n\n# ╔═╡ 49c55e48-30dc-11eb-02be-398a6bd228eb\nplot(sol,title=\"Phase Diagram\",vars=(1,2))\n\n# ╔═╡ a5c27f1a-31bc-11eb-2a2d-5fd911b57f2a\nmd\" ## Acknowledgements\n1. http://ucidatascienceinitiative.github.io/IntroToJulia/Html/DiffEq#Example:-Lotka-Volterra-ODE\n2. https://en.wikipedia.org/wiki/Lotka–Volterra_equations\n3. https://observablehq.com/@mbostock/predator-and-prey\n4. https://www.pnas.org/content/6/7/410.full\n\n\n\"\n\n# ╔═╡ Cell order:\n# ╠═cdab643c-30da-11eb-29f6-53bdde7b82f5\n# ╠═d560f3f6-30da-11eb-31dc-f510ae97bada\n# ╠═e429e976-30d8-11eb-27dd-590119e09f74\n# ╠═c93b2276-30db-11eb-1669-27ae204265d1\n# ╠═3fa4a936-30dd-11eb-3ef1-8bb442940777\n# ╠═210ce916-30dd-11eb-0321-4fb5cae1d9f3\n# ╠═1ce67d12-30dc-11eb-3f11-4b72daa20236\n# ╠═5a535432-30fe-11eb-3442-817440f3830e\n# ╠═f6f9f872-30db-11eb-25d3-f18fdd57d80c\n# ╠═986c0e84-31bd-11eb-27af-d1702ee5442e\n# ╠═a063e0d0-31bd-11eb-056b-cb400ad0e45b\n# ╟─167e7be6-30dc-11eb-15de-ad9ff925a787\n# ╠═d3028ce4-31bd-11eb-1710-d5a7ecba6bfe\n# ╠═49c55e48-30dc-11eb-02be-398a6bd228eb\n# ╠═a5c27f1a-31bc-11eb-2a2d-5fd911b57f2a\n", "meta": {"hexsha": "2e5b970b9247f2e2cb56fbffea7e56fab216cd65", "size": 4443, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "calculus/Predator-prey.jl", "max_stars_repo_name": "22natarajank/Highschool-Julia", "max_stars_repo_head_hexsha": "9d37e181178876c84aae3ebad7071cd61757daa7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-02-04T11:01:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-19T08:36:58.000Z", "max_issues_repo_path": "calculus/Predator-prey.jl", "max_issues_repo_name": "22natarajank/Highschool-Julia", "max_issues_repo_head_hexsha": "9d37e181178876c84aae3ebad7071cd61757daa7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calculus/Predator-prey.jl", "max_forks_repo_name": "22natarajank/Highschool-Julia", "max_forks_repo_head_hexsha": "9d37e181178876c84aae3ebad7071cd61757daa7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4418604651, "max_line_length": 243, "alphanum_fraction": 0.7364393428, "num_tokens": 1716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7603926716541625}}
{"text": "#############################################################################\n#############################################################################\n#\n# This file implements polynomial GCD \n#                                                                               \n#############################################################################\n#############################################################################\n\n\"\"\"\nThe extended euclid algorithm for polynomials modulo prime.\n\"\"\"\nfunction extended_euclid_alg(a::Polynomial, b::Polynomial, prime::Int)\n    old_r, r = mod(a,prime), mod(b,prime)\n    old_s, s = one(Polynomial), zero(Polynomial)\n    old_t, t = zero(Polynomial), one(Polynomial)\n\n    while !iszero(mod(r,prime))\n        q = divide(old_r, r)(prime) |> first\n        old_r, r = r, mod(old_r - q*r, prime)\n        old_s, s = s, mod(old_s - q*s, prime)\n        old_t, t = t, mod(old_t - q*t, prime)\n    end\n    g, s, t = old_r, old_s, old_t\n    @assert mod(s*a + t*b - g, prime) == 0\n    return g, s, t  \nend\n\n\"\"\"\nThe GCD of two polynomials modulo prime.\n\"\"\"\ngcd(a::Polynomial, b::Polynomial, prime::Int) = extended_euclid_alg(a,b,prime) |> first", "meta": {"hexsha": "e6ecca5c503bcd5224530c9022f45016d0bc95a3", "size": 1177, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basic_polynomial_operations/polynomial_gcd.jl", "max_stars_repo_name": "s4642266/2504_2021_project1", "max_stars_repo_head_hexsha": "41948baa4fc9d069980697df0b5ba8b022978699", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basic_polynomial_operations/polynomial_gcd.jl", "max_issues_repo_name": "s4642266/2504_2021_project1", "max_issues_repo_head_hexsha": "41948baa4fc9d069980697df0b5ba8b022978699", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basic_polynomial_operations/polynomial_gcd.jl", "max_forks_repo_name": "s4642266/2504_2021_project1", "max_forks_repo_head_hexsha": "41948baa4fc9d069980697df0b5ba8b022978699", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2021-09-05T21:53:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T12:11:07.000Z", "avg_line_length": 37.9677419355, "max_line_length": 87, "alphanum_fraction": 0.414613424, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025231, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7603926693730305}}
{"text": "function f(x)\n    if x < 8\n        return 0\n    end\n    ans = (x ÷ 3) - 2\n    return ans + f((x ÷ 3) - 2)\nend\n\na = [140170,75120,75645,134664,124948,137630,146662,116881,120030,94332,50473,59361,128237,84894,51368,128802,57275,129235,113481,66378,55842,90548,107696,53603,130458,80306,120820,131313,100303,59224,123369,140584,60642,68184,103101,82278,51968,51048,98139,60498,127082,71197,109478,71286,84840,141305,51800,72352,93147,73549,122739,62363,58453,59000,63564,63424,51053,120826,123337,130824,59053,77983,68977,67126,96051,53024,145647,139343,113236,59396,146174,148622,83384,86938,100673,80757,107675,147417,124538,136463,104609,149559,136037,54997,139674,101638,65739,70029,143847,122035,66256,78087,105045,108867,99630,127173,139021,139759,134171,104869]\nprintln(sum(f.(a)))", "meta": {"hexsha": "b75ed68aef45aec3b3521097f77dd6448d3fc35d", "size": 786, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Day 1/Day 1 Part 2.jl", "max_stars_repo_name": "soumitradev/AdventOfCode2019", "max_stars_repo_head_hexsha": "09001caaa4e0aa6c4c17303a59ea6a40089d9f74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Day 1/Day 1 Part 2.jl", "max_issues_repo_name": "soumitradev/AdventOfCode2019", "max_issues_repo_head_hexsha": "09001caaa4e0aa6c4c17303a59ea6a40089d9f74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day 1/Day 1 Part 2.jl", "max_forks_repo_name": "soumitradev/AdventOfCode2019", "max_forks_repo_head_hexsha": "09001caaa4e0aa6c4c17303a59ea6a40089d9f74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 78.6, "max_line_length": 655, "alphanum_fraction": 0.7748091603, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693716759488, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7603926682781166}}
{"text": "import StatsBase: entropy\nentropy(probs::ProbabilityWeights) = -sum(x->(x * log(x)), probs[probs .> 0])\n\n\nfunction entropy(counts::FrequencyWeights; method=:Naive)\n    method == :Naive && return entropy_naive(counts)\n    method == :Shrink && return entropy_shrinkage(counts)\n    method == :CS && return entropy_cs(counts)\n    throw(ArgumentError(\"Unknown method $method\"))\nend\n\n\nentropy_naive(counts::FrequencyWeights) =\n    entropy(ProbabilityWeights(counts / sum(counts)))\n\n\n\"Chao-Shen (2003) entropy estimator.\"\nfunction entropy_cs(counts::FrequencyWeights)\n  n = sum(counts)\n  θ_ML = counts / n\n\n  f1 = sum(counts .== 1)\n  f1 = (f1 == n) ? n - 1 : f1 # avoid C=0\n\n  # Estimate coverage\n  C = (1 - f1 / n)\n  p_a = C * θ_ML\n  l_a = (1 .- (1 .- p_a) .^ n)\n\n  return - sum(p_a .* log.(p_a) ./ l_a)\nend\n\n\n#=\nFrom http://www.jmlr.org/papers/volume10/hausser09a/hausser09a.pdf\n=#\n\"Shrinkage entropy estimator.\"\nfunction entropy_shrinkage(counts::FrequencyWeights)\n    n = sum(counts)\n    θ_ML = counts / n\n\n    # Uniform distribution\n    t_k = 1 / length(θ_ML)\n\n    den = (n - 1) * sum((θ_ML .- t_k) .^2)\n    if den < 1e-10\n      return entropy(ProbabilityWeights(θ_ML))\n    else\n      # Regularization parameter\n      λ = (1 - sum(θ_ML .^ 2)) / den\n      return entropy(ProbabilityWeights(λ * t_k .+ (1 - λ) * θ_ML))\n    end\nend\n\n\n\"\"\"\nEstimate the entropy of an array using a naive (frequencies-based),\nChao-Shen, or shrinkage estimator. Chao-Shen and shrinkage estimators reduce\nthe bias for small samples and a large number of classes.\n\"\"\"\nfunction estimate_entropy(data::AbstractVector; method::Symbol=:Naive)\n  count_values = values(countmap(data))\n  freqs = FrequencyWeights(collect(count_values))\n  return entropy(freqs; method=method)\nend\n\n\nfunction estimate_joint_entropy(x::AbstractVector, y::AbstractVector; method::Symbol=:Naive)\n  @assert length(x) == length(y) \"Vectors must be the same length\"\n\n  count = countmap([hash(yᵢ, hash(xᵢ)) for (xᵢ, yᵢ) ∈ zip(x, y)])\n  freqs = FrequencyWeights(collect(values(count)))\n  entropy(freqs; method=method)\nend\n", "meta": {"hexsha": "910124d9310353b3e8c5ceac03bbdab6146a064f", "size": 2060, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/entropy.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Discreet.jl-c2843242-4f35-58a6-a2a0-7e7527607317", "max_stars_repo_head_hexsha": "8388e9a19c564eaad84fdc77f959e65123f27566", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/entropy.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Discreet.jl-c2843242-4f35-58a6-a2a0-7e7527607317", "max_issues_repo_head_hexsha": "8388e9a19c564eaad84fdc77f959e65123f27566", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/entropy.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Discreet.jl-c2843242-4f35-58a6-a2a0-7e7527607317", "max_forks_repo_head_hexsha": "8388e9a19c564eaad84fdc77f959e65123f27566", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4666666667, "max_line_length": 92, "alphanum_fraction": 0.6800970874, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.760392662598113}}
{"text": "# elastic-net regularization\n\nexport ElasticNet\n\n\"\"\"\n**Elastic-net regularization**\n\n    ElasticNet(μ=1, λ=1)\n\nReturns the function\n```math\nf(x) = μ\\\\|x\\\\|_1 + (λ/2)\\\\|x\\\\|^2,\n```\nfor nonnegative parameters `μ` and `λ`.\n\"\"\"\nstruct ElasticNet{R <: Real, S <: Real} <: ProximableFunction\n    mu::R\n    lambda::S\n    function ElasticNet{R, S}(mu::R, lambda::S) where {R <: Real, S <: Real}\n        if lambda < 0 || mu < 0\n            error(\"parameters `μ` and `λ` must be nonnegative\")\n        else\n            new(mu, lambda)\n        end\n    end\nend\n\nis_separable(f::ElasticNet) = true\nis_prox_accurate(f::ElasticNet) = true\nis_convex(f::ElasticNet) = true\n\nElasticNet(mu::R=1, lambda::S=1) where {R <: Real, S <: Real} = ElasticNet{R, S}(mu, lambda)\n\nfunction (f::ElasticNet)(x::AbstractArray{T}) where {\n    R <: Real, T <: RealOrComplex{R}\n}\n    return f.mu * norm(x, 1) + f.lambda / R(2) * norm(x, 2)^2\nend\n\nfunction prox!(y::AbstractArray{R}, f::ElasticNet, x::AbstractArray{R}, gamma::R=R(1)) where {\n    R <: Real,\n}\n    sqnorm2x = R(0)\n    norm1x = R(0)\n    gm = gamma * f.mu\n    gl = gamma * f.lambda\n    for i in eachindex(x)\n        y[i] = (x[i] + (x[i] <= -gm ? gm : (x[i] >= gm ? -gm : -x[i])))/(1 + gl)\n        sqnorm2x += abs2(y[i])\n        norm1x += abs(y[i])\n    end\n    return f.mu * norm1x + f.lambda / R(2) * sqnorm2x\nend\n\nfunction prox!(y::AbstractArray{R}, f::ElasticNet, x::AbstractArray{R}, gamma::AbstractArray{R}) where {\n    R <: Real\n}\n    sqnorm2x = R(0)\n    norm1x = R(0)\n    for i in eachindex(x)\n        gm = gamma[i] * f.mu\n        gl = gamma[i] * f.lambda\n        y[i] = (x[i] + (x[i] <= -gm ? gm : (x[i] >= gm ? -gm : -x[i])))/(1 + gl)\n        sqnorm2x += abs2(y[i])\n        norm1x += abs(y[i])\n    end\n    return f.mu * norm1x + f.lambda / R(2) * sqnorm2x\nend\n\nfunction prox!(y::AbstractArray{Complex{R}}, f::ElasticNet, x::AbstractArray{Complex{R}}, gamma::R=R(1)) where {\n    R <: Real\n}\n    sqnorm2x = R(0)\n    norm1x = R(0)\n    gm = gamma * f.mu\n    gl = gamma * f.lambda\n    for i in eachindex(x)\n        y[i] = sign(x[i]) * max(0, abs(x[i]) - gm)/(1 + gl)\n        sqnorm2x += abs2(y[i])\n        norm1x += abs(y[i])\n    end\n    return f.mu * norm1x + f.lambda / R(2) * sqnorm2x\nend\n\nfunction prox!(y::AbstractArray{Complex{R}}, f::ElasticNet, x::AbstractArray{Complex{R}}, gamma::AbstractArray{R}) where {\n    R <: Real\n}\n    sqnorm2x = R(0)\n    norm1x = R(0)\n    for i in eachindex(x)\n        gm = gamma[i] * f.mu\n        gl = gamma[i] * f.lambda\n        y[i] = sign(x[i]) * max(0, abs(x[i]) - gm)/(1 + gl)\n        sqnorm2x += abs2(y[i])\n        norm1x += abs(y[i])\n    end\n    return f.mu * norm1x + f.lambda / R(2) * sqnorm2x\nend\n\nfunction gradient!(y::AbstractArray{T}, f::ElasticNet, x::AbstractArray{T}) where {\n    R <: Real, T <: RealOrComplex{R}\n}\n    # Gradient of 1 norm\n    y .= f.mu .* sign.(x)\n    # Gradient of 2 norm\n    y .+= f.lambda .* x\n    return f.mu * norm(x, 1) + f.lambda / R(2) * norm(x, 2)^2\nend\n\nfun_name(f::ElasticNet) = \"elastic-net regularization\"\nfun_dom(f::ElasticNet) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::ElasticNet) = \"x ↦ μ||x||_1 + (λ/2)||x||²\"\nfun_params(f::ElasticNet) = \"μ = $(f.mu), λ = $(f.lambda)\"\n\nfunction prox_naive(f::ElasticNet, x::AbstractArray{T}, gamma::R=R(1)) where {\n    R <: Real, T <: RealOrComplex{R}\n}\n    uz = max.(0, abs.(x) .- gamma * f.mu)/(1 + f.lambda * gamma)\n    return sign.(x) .* uz, f.mu * norm(uz, 1) + f.lambda / R(2) * norm(uz)^2\nend\n\nfunction prox_naive(f::ElasticNet, x::AbstractArray{T}, gamma::AbstractArray{R}) where {\n    R <: Real, T <: RealOrComplex{R}\n}\n    uz = max.(0, abs.(x) .- gamma .* f.mu)./(1 .+ f.lambda .* gamma)\n    return sign.(x) .* uz, f.mu * norm(uz, 1) + f.lambda / R(2) * norm(uz)^2\nend\n", "meta": {"hexsha": "f83bcc882a532643164fc727c0b4e74baf5018dd", "size": 3747, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/elasticNet.jl", "max_stars_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_stars_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2016-10-29T12:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:11:52.000Z", "max_issues_repo_path": "src/functions/elasticNet.jl", "max_issues_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_issues_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2016-10-26T16:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T20:38:48.000Z", "max_forks_repo_path": "src/functions/elasticNet.jl", "max_forks_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_forks_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T10:40:24.000Z", "avg_line_length": 29.2734375, "max_line_length": 122, "alphanum_fraction": 0.5564451561, "num_tokens": 1356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7603877830056177}}
{"text": "using DrWatson\n@quickactivate \"StatReth\"\n\n# %%\nusing DataFrames\nusing CSV\nusing Turing\nusing Plots\n\ninclude(srcdir(\"quap.jl\"))\ninclude(srcdir(\"tools.jl\"))\n\n# %% 5.45\nd = CSV.read(datadir(\"exp_raw/Howell_1.csv\"), DataFrame)\n\n# %% 5.46\nμ_female = rand(Normal(178, 20), 10_000)\nμ_male = rand(Normal(178, 20), 10_000) .+ rand(Normal(0, 10), 10_000)\nDataFrame((; μ_female, μ_male)) |> precis\n\n# %% 5.47\nd.sex = ifelse.(d.male .== 1, 2, 1)\n\n# %% 5.48\n@model function categ(sex, height)\n    σ ~ Uniform(0, 50)\n    a ~ filldist(Normal(178, 20), 2)\n    μ = a[sex]\n    height ~ MvNormal(μ, σ)\nend\n\nq5_8 = quap(categ(d.sex, d.height), NelderMead())\n# precis\n\n# %% 5.49\npost = DataFrame(rand(q5_8.distr, 1000)', q5_8.params)\npost.diff_fm = post[:, \"a[1]\"] .- post[:, \"a[2]\"]\nprecis(post)\n\n# %% 5.50\nd = CSV.read(datadir(\"exp_raw/milk.csv\"), DataFrame; missingstring = \"NA\")\nd.clade |> unique |> sort\n\n# %% 5.51\n# You can't just turn Strings into Integers in Julia but hashing them should give the same\n# result\nd.clade_id = Int.(indexin(d.clade, unique(d.clade)))\n\n# %% 5.52\nd.K = zscore(d.kcal_per_g)\n\n@model function clade(clade_id, K)\n    σ ~ Exponential(1)\n    α ~ filldist(Normal(0, 0.5), length(unique(clade_id)))\n    μ = α[clade_id]\n    K ~ MvNormal(μ, σ)\nend\n\nq5_9 = quap(clade(d.clade_id, d.K))\npost = DataFrame(rand(q5_9.distr, 1000)', q5_9.params)\nprecis(post)\n\n# TODO: plot\n\n# %% 5.54\nd.house = rand(1:4, nrow(d))\n\n@model function clade_house(clade_id, house, K)\n    σ ~ Exponential(1)\n    a ~ filldist(Normal(0, 0.5), length(unique(clade_id)))\n    h ~ filldist(Normal(0, 0.5), length(unique(house)))\n    μ = a[clade_id] + h[house]\n    K ~ MvNormal(μ, σ)\nend\n\nq5_10 = quap(clade_house(d.clade_id, d.house, d.K))\nDataFrame(rand(q5_10.distr, 1000)', q5_10.params) |> precis\n", "meta": {"hexsha": "5f388f5b7aa9f23b577720e5a56fb51dc6f57f0f", "size": 1772, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/5_3 Categorical variables.jl", "max_stars_repo_name": "karajan9/statisticalrethinking", "max_stars_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-06-03T14:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T16:52:26.000Z", "max_issues_repo_path": "scripts/5_3 Categorical variables.jl", "max_issues_repo_name": "karajan9/statisticalrethinking", "max_issues_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-13T05:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T14:05:57.000Z", "max_forks_repo_path": "scripts/5_3 Categorical variables.jl", "max_forks_repo_name": "karajan9/statisticalrethinking", "max_forks_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-01T13:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-03T23:40:53.000Z", "avg_line_length": 22.7179487179, "max_line_length": 90, "alphanum_fraction": 0.64503386, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7603555096682647}}
{"text": "\"\"\"\nContains some functions for calculating cross-correlations, autocorrelations,\nand Pearson correlations among rate units in a rate network\n\"\"\"\n\nusing Statistics\nimport DSP.xcorr\n\n\n\"\"\"\n\txcorr_unbiased(x::Vector, y::Vector, maxlag::Int64)\n\nReturns the cross-correlation of two signals normalized by the length of the\navailable convolution window.\n\nWritten by Rainer Engelken (re2365@columbia.edu).\n\"\"\"\nfunction xcorr_unbiased(x, y, maxlag)\n\tl = length(x) # we assume same length for x and y\n\tlags = -maxlag:maxlag\n\tscale = l .- abs.(lags)\n\tscale[scale .<= 0] .= 1 # avoid zero division\n    xcorr(x, y)[l .+ lags] ./ scale\nend\n\n\n\n\"\"\"\n\tavg_autocorrs(A::Matrix{T}, maxlag::Int64, wait::Int64=0) where T <: AbstractFloat\n\nReturns the average autocorrelation for the activity of each unit described in\nthe `N x NT` matrix `A`.\n\nNote the autocorrelations are not mean-subtracted. The `maxlag` parameter\ngives the maximum shift of the signal, and the `wait` parameter gives the number\nof timesteps in the beginning to disregard.\n\"\"\"\nfunction avg_autocorrs(A::Matrix{T}, maxlag::Int64, wait::Int64=0) where T <: AbstractFloat\n\n\t(N, NT) = size(A)\n\n\tunit_autocorrs = mapslices(view(A, :, (wait + 1):NT), dims=2) do x\n\t\treturn xcorr_unbiased(x, x, maxlag)\n\tend\n\n\treturn vec(mean(unit_autocorrs, dims=1))\nend\n", "meta": {"hexsha": "213adadb662b5159e4536e0b6a132a9f1fa6b842", "size": 1298, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code/processing/31-Aug-21_Lspecs_small_g/autocorrelations.jl", "max_stars_repo_name": "mattding20/RateNet-Lyapunov", "max_stars_repo_head_hexsha": "e2de8b6daa3db1e2d14fad9d219560e4f531d67d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/processing/31-Aug-21_Lspecs_small_g/autocorrelations.jl", "max_issues_repo_name": "mattding20/RateNet-Lyapunov", "max_issues_repo_head_hexsha": "e2de8b6daa3db1e2d14fad9d219560e4f531d67d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/processing/31-Aug-21_Lspecs_small_g/autocorrelations.jl", "max_forks_repo_name": "mattding20/RateNet-Lyapunov", "max_forks_repo_head_hexsha": "e2de8b6daa3db1e2d14fad9d219560e4f531d67d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0416666667, "max_line_length": 91, "alphanum_fraction": 0.7295839753, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7603555038113464}}
{"text": "@doc raw\"\"\"\n    Moments <: AbstractImageBinarizationAlgorithm\n    Moments()\n\n    binarize([T,] img, f::Moments)\n    binarize!([out,] img, f::Moments)\n\nThe following rule determines the binarization threshold:  if one assigns all\nobservations below the threshold to a value z₀ and all observations above the\nthreshold to a value z₁, then the first three moments of the original histogram\nmust match the moments of this specially constructed bilevel histogram.\n\n# Output\n\nReturn the binarized image as an `Array{Gray{T}}` of size `size(img)`. If\n`T` is not specified, it is inferred from `out` and `img`.\n\n# Details\n\nLet ``f_i`` ``(i=1 \\ldots I)`` denote the number of observations in the\n``i``th bin of the histogram and ``z_i`` ``(i=1 \\ldots I)`` the observed value\nassociated with the ``i``th bin.  Then the probability that an observation ``z_i``\nbelongs to the ``i``th bin is given by  ``p_i = \\frac{f_i}{N}`` (``i = 1,\n\\ldots, I``), where ``N = \\sum_{i=1}^{I}f_i``.\n\nMoments can be computed from the histogram ``f`` in the following way:\n\n```math\nm_k = \\frac{1}{N} \\sum_i p_i (z_i)^k \\quad k = 0,1,2,3, \\ldots.\n```\nThe principle of moment-preserving thresholding is to select a threshold value,\nas well as two representative values ``z_0`` and ``z_1`` (``z_0 < z_1``),\nsuch that if all below-threshold values in ``f`` are replaced by ``z_0`` and\nall above-threshold values are replaced by ``z_1``, then this specially constructed\nbilevel histogram ``g`` will have the same first three moments as ``f``.\n\nConcretely, let ``q_0`` and ``q_1`` denote the fractions of observations below\nand above the threshold in ``f``, respectively. The constraint that the first\nthree moments in ``g`` must equal the first three moments in ``f`` can be\nexpressed by the following system of four equations\n\n```math\n\\begin{aligned}\n   q_0 (z_0)^0 + q_1 (z_1)^0   & = m_0 \\\\\n   q_0 (z_0)^1 + q_1 (z_1)^1   & = m_1 \\\\\n   q_0 (z_0)^2 + q_1 (z_1)^2   & = m_2 \\\\\n   q_0 (z_0)^3 + q_1 (z_1)^3   & = m_3 \\\\\n\\end{aligned}\n```\nwhere the left-hand side represents the moments of ``g`` and the right-hand side\nrepresents the moments of ``f``. To find the desired treshold value, one first solves\nthe four equations to obtain ``q_0`` and ``q_1``, and then chooses the threshold\n``t`` such that ``q_0 = \\sum_{z_i \\le t} p_i``.\n\n\n# Arguments\n\nThe function argument is described in more detail below.\n\n##  `img::AbstractArray`\n\nThe image that needs to be binarized. The image is automatically converted\nto `Gray` in order to construct the requisite graylevel histogram.\n\n\n# Example\n\nBinarize the \"cameraman\" image in the `TestImages` package.\n\n```julia\nusing TestImages, ImageBinarization\n\nimg = testimage(\"cameraman\")\nimg_binary = binarize(img, Moments())\n```\n\n# Reference\n\n[1] W.-H. Tsai, “Moment-preserving thresolding: A new approach,” Computer Vision, Graphics, and Image Processing, vol. 29, no. 3, pp. 377–393, Mar. 1985. [doi:10.1016/0734-189x(85)90133-1](https://doi.org/10.1016/0734-189x%2885%2990133-1)\n\"\"\"\nstruct Moments <: AbstractImageBinarizationAlgorithm end\n\nfunction (f::Moments)(out::GenericGrayImage, img::GenericGrayImage)\n    edges, counts = build_histogram(img,  256)\n    t = find_threshold(HistogramThresholding.Moments(), counts[1:end], edges)\n    for i in CartesianIndices(img)\n        out[i] = img[i] < t ? 0 : 1\n    end\n    out\nend\n\n(f::Moments)(out::GenericGrayImage, img::AbstractArray{<:Color3}) =\n    f(out, of_eltype(Gray, img))\n", "meta": {"hexsha": "8ea0dbdd0b9ece455e802a1997bb232980f8081c", "size": 3431, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algorithms/moments.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ImageBinarization.jl-cbc4b850-ae4b-5111-9e64-df94c024a13d", "max_stars_repo_head_hexsha": "e6b3b13279196544e815c821e45e2bef37c18376", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algorithms/moments.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ImageBinarization.jl-cbc4b850-ae4b-5111-9e64-df94c024a13d", "max_issues_repo_head_hexsha": "e6b3b13279196544e815c821e45e2bef37c18376", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithms/moments.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ImageBinarization.jl-cbc4b850-ae4b-5111-9e64-df94c024a13d", "max_forks_repo_head_hexsha": "e6b3b13279196544e815c821e45e2bef37c18376", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-13T20:29:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-13T20:29:41.000Z", "avg_line_length": 36.5, "max_line_length": 238, "alphanum_fraction": 0.6980472166, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7603554939859718}}
{"text": "#=\nAn optimization oracle is a linear optimization oracle for the set S, i.e., it solves\n    z^\\ast(c) :=    min c^Tw\n                    s.t. w \\in S\nThe solution of the above problem returned by the oracle is referred to as w^\\ast(\\cdot) in\nthe paper\n\nA specific implementation of an optimization oracle should take a single input argument c,\nand should return the pair (z^\\ast(c), w^\\ast(c))\n\nThis file contains the code for the assignment problem optimization oracle, which\nrelies on the Hungarian solver package.\n=#\n\nusing Hungarian\n\n\"\"\"\n    assignment_oracle(c)\n\nOptimization oracle for the assignment problem. Uses Hungarian algorithm. Assumes\nthat the input c is a vector of length d^2 and must be reshaped into a matrix\n\"\"\"\nfunction assignment_oracle(c::Vector{Float64})\n    d_sq = length(c)\n    d = isqrt(d_sq)\n    C = reshape(c, (d,d))\n    assignment, z = hungarian(C)\n\n    W = zeros(d, d)\n    for i = 1:d\n        W[i, assignment[i]] = 1\n    end\n    w = vec(W)\n    return (z, w)\nend\n\n\"\"\"\n    assignment_hamming_reduce(c)\n\nUtility function that converts c to a cost matrix with 0 on the optimal edges and 1 on all\nother possible edges. Therefore, the SPO loss becomes equal to the hamming loss between the\npredicted assignment and the optimal one. Returns the new cost vector c associated with\nthe Hamming loss.\n\"\"\"\nfunction assignment_hamming_reduce(c::Vector{Float64})\n    d_sq = length(c)\n    d = isqrt(d_sq)\n    C = reshape(c, (d,d))\n    assignment, z = hungarian(C)\n\n    new_C = ones(d, d)\n    for i = 1:d\n        new_C[i, assignment[i]] = 0\n    end\n    new_c = vec(new_C)\n    return new_c\nend\n", "meta": {"hexsha": "e86ebb0ce424f82582864546ec34f6fd1d9ecd8e", "size": 1609, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "oracles/assignment_oracle.jl", "max_stars_repo_name": "paulgrigas/SmartPredictThenOptimize", "max_stars_repo_head_hexsha": "a969f66e85684e0a1228cbb83b390110e1b83030", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-11-30T07:50:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:02:36.000Z", "max_issues_repo_path": "oracles/assignment_oracle.jl", "max_issues_repo_name": "paulgrigas/SmartPredictThenOptimize", "max_issues_repo_head_hexsha": "a969f66e85684e0a1228cbb83b390110e1b83030", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "oracles/assignment_oracle.jl", "max_forks_repo_name": "paulgrigas/SmartPredictThenOptimize", "max_forks_repo_head_hexsha": "a969f66e85684e0a1228cbb83b390110e1b83030", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-10-12T10:11:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T23:58:51.000Z", "avg_line_length": 27.7413793103, "max_line_length": 91, "alphanum_fraction": 0.6830329397, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7603554903048131}}
{"text": "using LinearAlgebra, Statistics\n\nfunction nelder_mead(f, S, ϵ; α=1.0, β=2.0, γ=0.5)\n    Δ, y_arr = Inf, f.(S)\n    iteractions = 0\n    while Δ > ϵ\n        p = sortperm(y_arr) # sort lowest to highest\n        S, y_arr = S[p], y_arr[p]\n        xl, yl = S[1], y_arr[1] # lowest\n        xh, yh = S[end], y_arr[end] # highest\n        xs, ys = S[end-1], y_arr[end-1] # second-highest\n        xm = mean(S[1:end-1]) # centroid\n        xr = xm + α*(xm - xh) # reflection point\n        yr = f(xr)\n    \n        if yr < yl\n            xe = xm + β*(xr-xm) # expansion point\n            ye = f(xe)\n            S[end],y_arr[end] = ye < yr ? (xe, ye) : (xr, yr)\n        elseif yr > ys\n            if yr ≤ yh\n                xh, yh, S[end], y_arr[end] = xr, yr, xr, yr\n            end\n            xc = xm + γ*(xh - xm) # contraction point\n            yc = f(xc)\n            if yc > yh\n                for i in 2 : length(y_arr)\n                    S[i] = (S[i] + xl)/2\n                    y_arr[i] = f(S[i])\n                end\n            else\n                S[end], y_arr[end] = xc, yc\n            end\n        else\n            S[end], y_arr[end] = xr, yr\n        end\n\n        Δ = std(y_arr, corrected=false)\n        iteractions = iteractions + 1\n    end\n    println(\"Iteractions: \",iteractions)\n    return S,iteractions\nend\n\n#valores dos parametros\nka = 9.0 \nkb = 2.0\nLa = 10.0\nLb = 10.0\n\n#Caso 1\n#F1 = 2.0; F2 = 4.0;\n\n#Caso 2\n#F1 = 0.0 ;F2 = 4.0;\n\n#Caso 3\nF1 = 0.0; F2 = 400.0;\n\n#tolerancia\ntol = 1e-8\n\n#ponto inicial\nu0 = [-0.01,0.0]\n#u0 = [0.0,0.0]\n#numero de pontos iniciais = dimensao do problema + 1\nu1 = [u0[1]-0.00001,u0[2]+0.00001]\nu2 = [u0[1]+0.00001,u0[2]+0.00001]\nu = [u0,u1,u2]\n\n#function\nf(u) = 0.5e0 * ka * (sqrt(u[1] ^ 2 + (La - u[2]) ^ 2) - La) ^ 2 + 0.5e0 * kb * (sqrt(u[1] ^ 2 + (Lb + u[2]) ^ 2) - Lb) ^ 2 - F1 * u[1] - F2 * u[2];\n\n#tolerancia\ntol = 1e-8\n\n@time u_est,iterac = nelder_mead(f, u, tol)\nprintln(\"u*: \",mean(u_est))\nprintln(\"f(u*): \",f(mean(u_est)))\n", "meta": {"hexsha": "edbf3aadecb000d793b85392fd408576425ad31b", "size": 1966, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Nelder_Mead.jl", "max_stars_repo_name": "GilbertoLucas/Structural_Optimization", "max_stars_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Nelder_Mead.jl", "max_issues_repo_name": "GilbertoLucas/Structural_Optimization", "max_issues_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nelder_Mead.jl", "max_forks_repo_name": "GilbertoLucas/Structural_Optimization", "max_forks_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.575, "max_line_length": 147, "alphanum_fraction": 0.4715157681, "num_tokens": 793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363299661721, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7603389954852223}}
{"text": "using Revise\nusing DifferentialEquations\nusing DynamicalSystems\nusing Basins\nusing Plots\nusing Printf\n\n# Equations of motion:\nfunction forced_pendulum(u, p, t)\n    @inbounds begin\n    d = p[1]; F = p[2]; omega = p[3]\n    du1 = u[2]\n    du2 = -d*u[2] - sin(u[1])+ F*cos(omega*t)\n    return SVector{2}(du1, du2)\n    end\nend\n\n# We have to define a callback to wrap the phase in [-π,π]\nfunction affect!(integrator)\n    if integrator.u[1] < 0\n        integrator.u[1] += 2*π\n    else\n        integrator.u[1] -= 2*π\n    end\nend\n\ncondition(u,t,integrator) = (integrator.u[1] < -π  || integrator.u[1] > π)\n\ncb = DiscreteCallback(condition,affect!)\n\n#d, F ,w\nF = 1.66\nω = 1.\nd=0.2\np=[d, F, ω]\n#p=[0.15, 0.2, 0.1]\ndf = ODEProblem(forced_pendulum,rand(2),(0.0,20.0), p)\ninteg_df  = init(df, alg=AutoTsit5(Rosenbrock23()); reltol=1e-9, save_everystep=false, callback=cb)\n\nxres=200\nyres=200\n\n# range for forced pend\nxg = range(-pi,pi,length=xres)\nyg = range(-2.,4.,length=yres)\n\n# compute basin\n@time bsn = Basins.basins_map2D(xg, yg, integ_df; T=2*pi/ω)\n\n# Basin entropy\n@show Sb,Sbb = basin_entropy(bsn; eps_x=20, eps_y=20)\n\n# Wada merge Haussdorff distances\n@time max_dist,min_dist = detect_wada_merge_method(xg, yg, bsn)\nepsilon = xg[2]-xg[1]\n@show dmax = max_dist/epsilon\n@show dmin = min_dist/epsilon\n\n# Wada grid\nW = detect_wada_grid_method(integ_df, bsn; max_iter=8)\n@show W[:,end]\n\n# Uncertainty exponent for these parameter and grid\nbd = box_counting_dim(xg, yg, bsn)\nα = 2 - bd\n\nD = uncertainty_exponent(bsn, integ_df)\n@show 2-D\n\n\nprintln(\"---------------\")\nprintln(\"---------------\")\nprintln(\"Basin Report: \")\nprintln(\"---------------\")\nprintln(\"---------------\")\n\n@printf(\"Basin entropy %.2f \\n\", Sb)\n@printf(\"Boundary Basin Entropy: %.2f\\n\", Sbb)\n@printf(\"Uncertainty exponent: α= %.2f\\n\", α )\n@printf(\"Box counting dim: bd= %.2f\\n\", bd)\n@printf(\"Uncertainty dim estimator: d = %.2f\\n\", 2-D[1])\n@printf(\"Number of basins: %d\\n\", bsn.Na)\n@printf(\"Merge Method: Max fattening parameter: %.2f\\n\", dmax)\n@printf(\"Wada Grid Method: W_Na = %.2f\\n \", W[end,end] )\n\nplot(xg, yg, bsn.basin', seriestype=:heatmap)\n", "meta": {"hexsha": "ad1d4325418f9c3c692af204a2842b11008491b4", "size": 2104, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/examples/tst_pendulum_all.jl", "max_stars_repo_name": "awage/Basins.jl", "max_stars_repo_head_hexsha": "765a232b0568a257a845ee95a14c0cf2776046a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-27T14:46:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T08:39:36.000Z", "max_issues_repo_path": "src/examples/tst_pendulum_all.jl", "max_issues_repo_name": "awage/Basins.jl", "max_issues_repo_head_hexsha": "765a232b0568a257a845ee95a14c0cf2776046a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-12T15:47:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-14T13:47:35.000Z", "max_forks_repo_path": "src/examples/tst_pendulum_all.jl", "max_forks_repo_name": "awage/Basins.jl", "max_forks_repo_head_hexsha": "765a232b0568a257a845ee95a14c0cf2776046a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.183908046, "max_line_length": 99, "alphanum_fraction": 0.6487642586, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7603389905474081}}
{"text": "\"\"\"\n        cocoso(decisionMat, weights, fns, lambda)\n\nApply CoCoSo (Combined Compromise Solution) method for a given matrix and weights.\n\n# Arguments:\n - `decisionMat::DataFrame`: n × m matrix of objective values for n alternatives and m criteria \n - `weights::Array{Float64, 1}`: m-vector of weights that sum up to 1.0. If the sum of weights is not 1.0, it is automatically normalized.\n - `fns::Array{Function, 1}`: m-vector of functions to be applied on the columns.\n - `lambda::Float64`: joint criterion. 0<=lambda<=1, default=0.5.\n\n# Description \ncocoso() applies the CoCoSo method to rank n alterntives subject to m criteria which are supposed to be \neither maximized or minimized.\n\n# Output \n- `::CoCoSoResult`: CoCoSoResult object that holds multiple outputs including scores, rankings, and best index.\n\n# Examples\n```julia-repl\njulia> decmat = [3        12.5        2        120        14        3;\n       5        15        3        110        38        4;\n       3        13        2        120        19        3;\n       4        14        2        100        31        4;\n       3        15        1.5        125        40        4]\n5×6 Array{Float64,2}:\n 3.0  12.5  2.0  120.0  14.0  3.0\n 5.0  15.0  3.0  110.0  38.0  4.0\n 3.0  13.0  2.0  120.0  19.0  3.0\n 4.0  14.0  2.0  100.0  31.0  4.0\n 3.0  15.0  1.5  125.0  40.0  4.0\n\njulia> df = makeDecisionMatrix(decmat)\n5×6 DataFrame\n Row │ Crt1     Crt2     Crt3     Crt4     Crt5     Crt6    \n     │ Float64  Float64  Float64  Float64  Float64  Float64 \n─────┼──────────────────────────────────────────────────────\n   1 │     3.0     12.5      2.0    120.0     14.0      3.0\n   2 │     5.0     15.0      3.0    110.0     38.0      4.0\n   3 │     3.0     13.0      2.0    120.0     19.0      3.0\n   4 │     4.0     14.0      2.0    100.0     31.0      4.0\n   5 │     3.0     15.0      1.5    125.0     40.0      4.0\n\njulia> weights = [0.221, 0.159, 0.175, 0.127, 0.117, 0.201];\n\njulia> fns = [maximum, minimum, minimum, maximum, minimum, maximum];\n\njulia> lambda = 0.5;\n\njulia> result = cocoso(df, weights, fns, lambda);\n\njulia> result.scores\n7-element Array{Float64,1}:\n 2.0413128390265998\n 2.787989783418825\n 2.8823497955972495\n 2.4160457689259287\n 1.2986918936013303\n 1.4431429073391682\n 2.519094173200623\n\njulia> result.bestIndex\n3\n```\n# References\n\nYazdani, M., Zarate, P., Kazimieras Zavadskas, E. and Turskis, Z. (2019), \"A combined compromise solution (CoCoSo) method for multi-criteria decision-making problems\", Management Decision, Vol. 57 No. 9, pp. 2501-2519. https://doi.org/10.1108/MD-05-2017-0458\n\n\"\"\"\nfunction cocoso(decisionMat::DataFrame, weights::Array{Float64,1}, fns::Array{Function,1}, lambda::Float64=0.5):CoCoSoResult\n   \n    row, col = size(decisionMat)\n    w = unitize(weights)\n    colMax = colmaxs(decisionMat)\n    colMin = colmins(decisionMat)\n\n    A = similar(decisionMat)\n\n    for i in 1:row\n        for j in 1:col\n            if fns[j] == maximum\n                @inbounds A[i, j] = (decisionMat[i, j] - colMin[j]) / (colMax[j] - colMin[j])\n            elseif fns[j] == minimum\n                @inbounds A[i, j] = (colMax[j] - decisionMat[i, j]) / (colMax[j] - colMin[j])\n            end                    \n        end\n    end\n\n    scoreMat = similar(A)\n    for i in 1:col\n        scoreMat[:, i] = A[:, i].^w[i]\n    end\n\n    P = zeros(Float64, row)\n    for i in 1:row\n        P[i] = sum(scoreMat[i, :])\n    end\n\n    S = w * A |> rowsums\n    \n    scoreTable = [S P]\n\n    kA = (S .+ P) ./ sum(scoreTable)\n\n    kB = (S ./ minimum(S)) .+ (P ./ minimum(P))\n\n    kC = ((lambda .* S) .+ ((1-lambda) .* P)) ./ ((lambda .* maximum(S)) .+ ((1-lambda) * maximum(P)))\n\n    scores = (kA .+ kB .+ kC) ./ 3 .+ (kA .* kB .* kC) .^ (1/3)\n\n    rankings = sortperm(scores)\n    \n    bestIndex = rankings |> last\n    \n    result = CoCoSoResult(\n        decisionMat,\n        w,\n        scores,\n        rankings,\n        bestIndex\n    )\n\n    return result\nend\n", "meta": {"hexsha": "a50cbc0f2b3b767e4b66ebf6f49343505141653f", "size": 3929, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cocoso.jl", "max_stars_repo_name": "bahadirfyildirim/JMcDM", "max_stars_repo_head_hexsha": "c1c3f11d92cd8b8c6367245794464e6643caa735", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cocoso.jl", "max_issues_repo_name": "bahadirfyildirim/JMcDM", "max_issues_repo_head_hexsha": "c1c3f11d92cd8b8c6367245794464e6643caa735", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cocoso.jl", "max_forks_repo_name": "bahadirfyildirim/JMcDM", "max_forks_repo_head_hexsha": "c1c3f11d92cd8b8c6367245794464e6643caa735", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.432, "max_line_length": 258, "alphanum_fraction": 0.5487401374, "num_tokens": 1447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7603389893634328}}
{"text": "using JuMP, Gurobi, Distributions, StatsFuns\r\n\r\n\r\nconst gurobi_env = Gurobi.Env()\r\n\r\n\r\n# DIMENSIONS\r\nconst numAssets = 1000\r\nconst numRandomVariables = numAssets\r\nconst numVariables = numAssets\r\n\r\nconst returnLBD = 1.2 #lower bound on the return\r\n\r\n\r\n# CASES\r\n# number of samples, replicates for scenario approximations\r\nconst NumSamples = ceil.(Int64,logspace(1,5,50))\r\nconst NumReplicates = 20\r\n\r\n\r\n#*============ OTHER MODEL PARAMETERS ================\r\nconst mean = Array{Float64}(numAssets)\r\nconst stdev = Array{Float64}(numAssets)\r\nfor i = 1:numAssets\r\n\tmean[i] = 1.05 + 0.3*(numAssets-i)/(numAssets-1)\r\n\tstdev[i] = (0.05 + 0.6*(numAssets-i)/(numAssets-1))/3\r\nend\r\nconst sigma = zeros(Float64, numAssets, numAssets)\r\nfor i = 1:numAssets\r\n\tsigma[i,i] = stdev[i]\r\nend\r\n#*===============================================\r\n\r\n\r\n# FILENAMES\r\nconst objFile = \"objectiveValue.txt\"\r\nconst solnFile = \"solution.txt\"\r\nconst riskFile = \"riskLevel.txt\"\r\nconst solnTimeFile = \"solutionTime.txt\"\r\nconst checkingTimeFile = \"checkingTime.txt\"\r\nconst sortingTimeFile = \"sortingTime.txt\"\r\nconst callbackFile = \"numCallbacks.txt\"\r\nconst numConstraintsFile = \"numConstraintsEnforced.txt\"\r\n\r\n\r\n# compute negative probability of all constraints being satisfied\r\n# for given scenarios of demands d and a given decision vector x\r\nfunction computeRiskLevel(y_opt::Array{Float64})\r\n\r\n\triskLevel::Float64 = 1.0 - normcdf((sum(mean[i]*y_opt[i] for i = 1:numAssets) - returnLBD)/norm(sigma*y_opt))\r\n\t\r\n\treturn riskLevel\r\nend\r\n\r\n\r\n# generate random samples of the demands\r\nfunction generateRandomSamples(numSamples::Int64)\r\n\r\n\txi = Array{Float64}(numAssets,numSamples)\r\n\tfor i = 1:numAssets\r\n\t\txi[i,:] = rand(Normal(mean[i],stdev[i]), numSamples)\r\n\tend\r\n\r\n\treturn xi\r\nend\r\n\r\n\r\n# determines if all constraints are satisfied for a given single scenario\r\n# returns one if scenario constraints are all satisfied, zero otherwise\r\nfunction getScenarioConstraintViolations(x::Array{Float64},xi::Array{Float64},pickFirstSetOfConstraints::Bool,maxNumConstraintsPerIteration::Int64)\r\n\r\n\tconst numSamples = size(xi,2)\r\n\tnumViolated::Int64 = 0\r\n\tconstraintViolations = Float64[]\r\n\tconstraintViolationIndices = Int64[]\r\n\tconstraintViolationTolerance::Float64 = 1E-06\r\n\r\n\tfor iter = 1:numSamples\r\n\t\tcon::Float64 = returnLBD - xi[:,iter]'*x\r\n\r\n\t\tif(con >= constraintViolationTolerance)\r\n\t\t\tnumViolated += 1\r\n\t\t\tpush!(constraintViolations,con)\r\n\t\t\tpush!(constraintViolationIndices,iter)\r\n\t\t\tif(pickFirstSetOfConstraints && numViolated == maxNumConstraintsPerIteration)\r\n\t\t\t\tbreak\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\n\t\r\n\treturn numViolated, constraintViolations, constraintViolationIndices\r\nend\r\n\r\n\r\n# write solution to file\r\nfunction initializeFiles(details_file::String)\r\n\r\n\twriteMode::String = \"w\"\r\n\t\r\n\topen(details_file, writeMode) do f\r\n\t\twrite(f,\"Model: $modelName \\n\")\r\n\t\twrite(f,\"numAssets: $numAssets \\n\")\r\n\t\twrite(f,\"returnLBD: $returnLBD \\n\")\r\n\t\twrite(f,\"NumSamples: $NumSamples \\n\")\r\n\t\twrite(f,\"NumReplicates: $NumReplicates \\n\")\r\n\t\twrite(f,\"Method: Scenario approximations \\n\")\r\n\tend\r\n\r\nend\r\n\r\n\r\n# write solution to file\r\nfunction writeSolutionToFile(dirName::String, status::Symbol, objvar_opt::Float64, x_opt::Array{Float64}, riskLevel::Float64, solutionTime::Float64, checkingTime::Float64, sortingTime::Float64, numCallbacks::Int64, numConstraintsAdded::Int64)\r\n\r\n\tif(status == Symbol(\"Optimal\"))\r\n\t\twriteMode::String = \"a\"\r\n\t\t\r\n\t\tobj_file::String = dirName * objFile\r\n\t\topen(obj_file, writeMode) do f\r\n\t\t\twrite(f,\"$objvar_opt \\n\")\r\n\t\tend\r\n\t\r\n\t\tsolution_file::String = dirName * solnFile\r\n\t\topen(solution_file, writeMode) do f\r\n\t\t\tfor i = 1:numVariables\r\n\t\t\t\twrite(f,\"$(x_opt[i]) \")\r\n\t\t\tend\r\n\t\t\twrite(f,\"\\n\")\r\n\t\tend\r\n\t\r\n\t\trisk_file::String = dirName * riskFile\r\n\t\topen(risk_file, writeMode) do f\r\n\t\t\twrite(f,\"$riskLevel \\n\")\r\n\t\tend\r\n\t\t\r\n\t\tsolntime_file::String = dirName * solnTimeFile\r\n\t\topen(solntime_file, writeMode) do f\r\n\t\t\twrite(f,\"$solutionTime \\n\")\r\n\t\tend\r\n\t\t\r\n\t\tchecktime_file::String = dirName * checkingTimeFile\r\n\t\topen(checktime_file, writeMode) do f\r\n\t\t\twrite(f,\"$checkingTime \\n\")\r\n\t\tend\r\n\t\t\r\n\t\tsorttime_file::String = dirName * sortingTimeFile\r\n\t\topen(sorttime_file, writeMode) do f\r\n\t\t\twrite(f,\"$sortingTime \\n\")\r\n\t\tend\r\n\t\t\r\n\t\tcallback_file::String = dirName * callbackFile\r\n\t\topen(callback_file, writeMode) do f\r\n\t\t\twrite(f,\"$numCallbacks \\n\")\r\n\t\tend\r\n\t\t\r\n\t\tconstraints_file::String = dirName * numConstraintsFile\r\n\t\topen(constraints_file, writeMode) do f\r\n\t\t\twrite(f,\"$numConstraintsAdded \\n\")\r\n\t\tend\r\n\tend\r\n\r\nend\r\n\r\n# solve the scenario approximation model\r\nfunction solveScenarioApproximationModel(numScenarios::Int64,dirName::String)\r\n\r\n\ttic()\r\n\r\n\t# sample the random variables\r\n\txi = generateRandomSamples(numScenarios)\r\n\t\r\n\tmaxNumConstraintsPerIteration::Int64 = 100000\r\n\tnumConstraintsAdded::Int64 = 0\r\n\t\r\n\tpickFirstSetOfConstraints::Bool = false\r\n\t\r\n\tsortingTime::Float64 = 0.0\r\n\tcheckingTime::Float64 = 0.0\r\n\tnumCallbacks::Int64 = 0\r\n\r\n\t\r\n\tobjvar_opt::Float64 = Inf\r\n\ty_opt = zeros(Float64,numVariables)\r\n\tstatus::Symbol = Symbol(\"Error\")\r\n\t\r\n\t\r\n\tnumViolations::Int64 = numScenarios\r\n\tconstraintIndices = Int64[]\r\n\t\r\n\t\r\n\twhile(numViolations > 0)\r\n\r\n\t\tnumCallbacks += 1\r\n\t\tnumViolations = 0\r\n\t\t\r\n\t\tnumConstraintsConsidered::Int64 = size(constraintIndices)[1]\r\n\t\r\n\r\n\t\t# construct the scenario model\r\n\t\tmod = Model(solver=GurobiSolver(gurobi_env,Presolve=0,OutputFlag=0))\r\n\r\n\t\t@variable(mod, y[1:numAssets] >= 0)\r\n\r\n\t\t@objective(mod, Min, sum(abs2(50.0*sigma[i,i])*y[i]*y[i] for i = 1:numAssets))\r\n\t\t@constraint(mod, sum(y[i] for i = 1:numAssets) == 1)\r\n\t\t@constraint(mod, [scen=1:numConstraintsConsidered], sum(xi[i,scen]*y[i] for i = 1:numAssets) >= returnLBD)\r\n\t\r\n\t\r\n\t\tstatus = solve(mod)\r\n\t\ty_opt = getvalue(y)\r\n\t\tobjvar_opt = sum(abs2(sigma[i,i]*y_opt[i]) for i = 1:numAssets)\r\n\r\n\r\n\t\tnumViolatedConstraints::Int64 = 0\r\n\t\tconstraintViolations = Float64[]\r\n\t\tconstraintViolationIndices = Int64[]\r\n\r\n\t\ttic()\r\n\t\t\r\n\t\tnumViolatedConstraints, constraintViolations, constraintViolationIndices = getScenarioConstraintViolations(y_opt,xi,pickFirstSetOfConstraints,maxNumConstraintsPerIteration)\r\n\t\t\r\n\t\tcheckingTime += toq()\r\n\t\t\r\n\t\tnumConstraintsEnforced::Int64 = min(size(constraintViolations,1),maxNumConstraintsPerIteration)\r\n\t\t\r\n\t\ttic()\r\n\t\trelevantIndices = 1:1:numConstraintsEnforced\r\n\t\tif(!pickFirstSetOfConstraints)\r\n\t\t\trelevantIndices = sortperm(constraintViolations, rev=true)\r\n\t\tend\r\n\t\tsortingTime += toq()\r\n\t\t\t\r\n\t\tfor iter = 1:numConstraintsEnforced\r\n\t\t\tpush!(constraintIndices,constraintViolationIndices[relevantIndices[iter]])\r\n\t\tend\r\n\t\t\r\n\t\tnumConstraintsAdded += numConstraintsEnforced\r\n\t\t\r\n\t\tnumViolations += numViolatedConstraints\r\n\r\n\tend\r\n\r\n\triskLevel::Float64 = computeRiskLevel(y_opt)\r\n\r\n\tsolutionTime::Float64 = toq()\r\n\t\t\r\n\t@printf \"  Objective: %1.5f,  Risklevel: %.5f,  Time: %4.2f,  NumCallbacks: %d,  NumConstraints: %d \\n\" objvar_opt riskLevel solutionTime numCallbacks numConstraintsAdded\r\n\t\r\n\twriteSolutionToFile(dirName, status, objvar_opt, y_opt, riskLevel, solutionTime, checkingTime, sortingTime, numCallbacks, numConstraintsAdded)\r\n\t\r\n\treturn status, objvar_opt, y_opt, riskLevel, solutionTime, checkingTime, sortingTime, numCallbacks, numConstraintsAdded\r\nend", "meta": {"hexsha": "795088878b828d115f19585a9281c35b57a29780", "size": 7169, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Scenario approximation/portfolio_var/portfolio_var_scenmodel_template.jl", "max_stars_repo_name": "rohitkannan/SA-for-CCP", "max_stars_repo_head_hexsha": "8bb62c8e095eb6a825807c016617d1999c744d24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-12-22T08:52:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T07:23:15.000Z", "max_issues_repo_path": "Scenario approximation/portfolio_var/portfolio_var_scenmodel_template.jl", "max_issues_repo_name": "rohitkannan/SA-for-CCP", "max_issues_repo_head_hexsha": "8bb62c8e095eb6a825807c016617d1999c744d24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scenario approximation/portfolio_var/portfolio_var_scenmodel_template.jl", "max_forks_repo_name": "rohitkannan/SA-for-CCP", "max_forks_repo_head_hexsha": "8bb62c8e095eb6a825807c016617d1999c744d24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-21T23:45:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-25T17:29:29.000Z", "avg_line_length": 28.4484126984, "max_line_length": 243, "alphanum_fraction": 0.7120937369, "num_tokens": 1974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467158, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7603389860715567}}
{"text": "\n\n\nmodule jump\n\n    using JuMP \n    using Ipopt\n    using Distributions\n    srand(12345)\n    normal = Normal(0,0.01)\n    \n    function run()\n\n        # create a model\n        m = Model(solver=IpoptSolver())\n\n        # define constants (N, price, etc)\n        N = 100\n        price = collect(linspace(0.05,0.95,N))\n        beta0 = 0.1\n        demand0 = (1.0-price) / (2*beta0)\n        demand = demand0 - rand(normal,N)\n\n        #define JuMP variables\n        @variable(m,eps[1:N])\n        @variable(m,0 <= beta <= 1)\n\n        # define constraints and objective\n        @objective(m,Min,sum(eps[i]^2 for i in 1:N))\n        @constraint(m,constr[i=1:N], 1.0 - 2*beta*(demand[i]-eps[i])-price[i] == 0)\n\n        # solve\n        status = solve(m)\n        Dict(:obj=>getobjectivevalue(m),:beta=>getvalue(beta),:eps=>getvalue(eps))\n    end\nend\n\n\nmodule nlopt\n\n    using Distributions\n    using NLopt\n    srand(12345)\n    normal = Normal(0,0.01)\n    N = 100\n    price = collect(linspace(0.05,0.95,N))\n    beta0 = 0.1\n    demand0 = (1.0-price) / (2*beta0)\n    demand = demand0 - rand(normal,N)\n\n    # objective function\n    function obj(x,g)\n        # x = [e_1,...,e_N,beta] i.e. (N+1,1)\n        \n        # gradient = [grad w.r.t e_1,\n        #            ...,grad w.r.t e_N,\n        #                grad w.r.t beta] i.e. (N+1,1)\n        if length(g)>0\n           g[:] = vcat(2.0*x[1:(end-1)],0.0)\n        end\n        # value of objective\n        r = sum(x[1:(end-1)].^2)\n        return r\n    end\n\n    # function test_constr()\n    #     x = rand(N+1)\n    #     my_c = zeros(N+1)\n    #     my_g = zeros(N+1,N)\n    #     constr(my_c,x,my_g,N,demand,price);\n    #     @test all(my_g .== Calculus.hessian()\n    # end\n\n    # \n    function constr(r::Vector,x::Vector,g::Matrix,n,q,p)\n        if length(g) > 0\n            # g has to be n by m for nlopt\n            g[:,:] = cat(1,diagm(2*x[end]*ones(n)),-2*(q'.-x[1:(end-1)]'))\n        end\n        # value of contraints\n        r[:] = 1.0 - 2*x[end].*(q.-x[1:(end-1)]) .- p\n    end\n    constr_clos(r::Vector,x::Vector,g::Matrix) = constr(r::Vector,x::Vector,g::Matrix,N,demand,price)\n\n    function run()\n        opt = Opt(:LD_SLSQP,N+1)\n        lower_bounds!(opt,[[-Inf for i in 1:N]...,0.0])\n        upper_bounds!(opt,[[Inf for i in 1:N]...,1.0])\n        min_objective!(opt,obj)\n        equality_constraint!(opt,constr_clos,[1e-10 for i in 1:N])\n        xtol_rel!(opt,1e-4)\n        ftol_rel!(opt,1e-6)\n\n        res = optimize(opt, vcat(rand(normal,N),0.9))\n        println(\"beta0 = $beta0\")\n        println(\"beta  = $(res[2][end])\")\n        r = zeros(N)\n        g =zeros(N+1,N)\n        constr(r,res[2],g,N,demand,price);\n        println(\"maximal error of constraint at solution = $(maxabs(r))\")\n        return res\n    end\n\nend # module", "meta": {"hexsha": "1f4107d556a2e02d34522a6f1c1a7e7304f573ad", "size": 2769, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mpec.jl", "max_stars_repo_name": "snowdj/CoursePack", "max_stars_repo_head_hexsha": "f3ad25012167f580b9ea97aa7e84890986648837", "max_stars_repo_licenses": ["MIT-0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2017-06-21T16:55:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T13:44:26.000Z", "max_issues_repo_path": "src/mpec.jl", "max_issues_repo_name": "snowdj/CoursePack", "max_issues_repo_head_hexsha": "f3ad25012167f580b9ea97aa7e84890986648837", "max_issues_repo_licenses": ["MIT-0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-01-23T14:13:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-01T11:10:31.000Z", "max_forks_repo_path": "src/mpec.jl", "max_forks_repo_name": "snowdj/CoursePack", "max_forks_repo_head_hexsha": "f3ad25012167f580b9ea97aa7e84890986648837", "max_forks_repo_licenses": ["MIT-0"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2017-02-24T12:23:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T07:25:38.000Z", "avg_line_length": 26.625, "max_line_length": 101, "alphanum_fraction": 0.5117370892, "num_tokens": 921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7603389836363014}}
{"text": "export Gaussian_Peak\n\n@doc raw\"\"\"\nGaussian peak\n\n```math\np(x; θ = [h,μ,σ]) = h e^{-\\frac{1}{2} \\left(\\frac{x-μ}{σ} \\right)^2}\n```\n\"\"\"\nstruct Gaussian_Peak <: Abstract_Model2Fit_Peak\nend\n\n# Visit  ================\n#\nvisit_submodel_size(model::Gaussian_Peak) = 0\n\n# Interface  ================\n#\nparameter_size(::Gaussian_Peak) = 3\n\nfunction accumulate_y!(m::Gaussian_Peak,Y::AbstractVector,X::AbstractVector,θ::AbstractVector)\n    @assert length(θ) == parameter_size(m)\n    @assert length(Y) == length(X)\n    \n    h=θ[1]\n    μ=θ[2]\n    σ=θ[3]\n\n    @. Y += h*exp(-((X-μ)/σ)^2/2)\n\n    Y\nend\n\n# ================================================================\n\nusing StaticArrays: @SVector, SVector\n\nstruct Const_μ_Gaussian_Peak{μ_T <: Real} <: Abstract_Model2Fit_Peak\n    _μ::μ_T\nend\n\n# Visit  ================\n#\nvisit_submodel_size(model::Const_μ_Gaussian_Peak) = 0\n\n# Interface  ================\n#\nparameter_size(::Const_μ_Gaussian_Peak) = 2\n\nfunction accumulate_y!(m::Const_μ_Gaussian_Peak,Y::AbstractVector,X::AbstractVector,θ::AbstractVector{T}) where {T}\n    @assert length(θ) == parameter_size(m)\n    @assert length(Y) == length(X)\n\n    h=θ[1]\n    μ=m._μ\n    σ=θ[2]\n\n    θ̂ = @SVector T[h,μ,σ]\n\n    accumulate_y!(Gaussian_Peak(),Y,X,θ̂)\nend\n", "meta": {"hexsha": "aa1e85cf2aeba237e1243a45557f1e10933a3a9d", "size": 1245, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/model2fit/peak/gaussian.jl", "max_stars_repo_name": "vincent-picaud/NLS_Fit.jl", "max_stars_repo_head_hexsha": "f72882bb00495dff81500a40e4e417a1a720d947", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-02T14:49:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T14:49:07.000Z", "max_issues_repo_path": "src/model2fit/peak/gaussian.jl", "max_issues_repo_name": "vincent-picaud/NLS_Fit.jl", "max_issues_repo_head_hexsha": "f72882bb00495dff81500a40e4e417a1a720d947", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-15T23:39:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-15T23:49:32.000Z", "max_forks_repo_path": "src/model2fit/peak/gaussian.jl", "max_forks_repo_name": "vincent-picaud/NLS_Fit.jl", "max_forks_repo_head_hexsha": "f72882bb00495dff81500a40e4e417a1a720d947", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0806451613, "max_line_length": 115, "alphanum_fraction": 0.5895582329, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317102, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7603389807390837}}
{"text": "# Copyright 2017, Iain Dunning, Joey Huchette, Miles Lubin, and contributors    #src\n# This Source Code Form is subject to the terms of the Mozilla Public License   #src\n# v.2.0. If a copy of the MPL was not distributed with this file, You can       #src\n# obtain one at https://mozilla.org/MPL/2.0/.                                   #src\n\n# # The correlation problem\n\n# Given three random variables A, B, C and given bounds on two of the three\n# correlation coefficients:\n#\n#     -0.2 <= ρ_AB <= -0.1\n#     0.4 <= ρ_BC <=  0.5\n#\n# We can use the following property of the correlations to determine bounds on\n# ρ_AC by solving a SDP:\n#\n#     |  1    ρ_AB  ρ_AC |\n#     | ρ_AB   1    ρ_BC |  ≽ 0\n#     | ρ_AC  ρ_BC   1   |\n\n\nusing JuMP\nimport SCS\nimport Test  #src\n\nfunction example_corr_sdp()\n    model = Model(SCS.Optimizer)\n    set_silent(model)\n    @variable(model, X[1:3, 1:3], PSD)\n    ## Diagonal is 1s\n    @constraint(model, X[1, 1] == 1)\n    @constraint(model, X[2, 2] == 1)\n    @constraint(model, X[3, 3] == 1)\n    ## Bounds on the known correlations\n    @constraint(model, X[1, 2] >= -0.2)\n    @constraint(model, X[1, 2] <= -0.1)\n    @constraint(model, X[2, 3] >=  0.4)\n    @constraint(model, X[2, 3] <=  0.5)\n    ## Find upper bound\n    @objective(model, Max, X[1, 3])\n    optimize!(model)\n    println(\"An upper bound for X[1, 3] is $(value(X[1, 3]))\")\n    Test.@test value(X[1, 3]) ≈ 0.87195 atol = 1e-4  #src\n    ## Find lower bound\n    @objective(model, Min, X[1, 3])\n    optimize!(model)\n    println(\"A lower bound for X[1, 3] is $(value(X[1, 3]))\")\n    Test.@test value(X[1, 3]) ≈ -0.978 atol = 1e-3  #src\n    return\nend\n\nexample_corr_sdp()\n", "meta": {"hexsha": "9bb2a2908072206ba855a36fa5a6517c6b7e1bff", "size": 1658, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/corr_sdp.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/corr_sdp.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/corr_sdp.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2830188679, "max_line_length": 84, "alphanum_fraction": 0.5940892642, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7603389770525488}}
{"text": "struct Domain{T<:Real,P<:AbstractFloat,O<:Signed} <: TwoDim\n    L       :: T\n    N       :: O\n    dx      :: P\n    dy      :: P\n    x       :: Vector\n    y       :: Vector\n    tspan   :: P\n    n       :: O\n    dt      :: P\n    t       :: Vector\n    v       :: P\n    Δr      :: P\n    rings1D :: O\n    rings2D :: O\n\n    # constructor\n    function Domain{T,P,O}(L::T,N::O,tspan::P,n::O,v::P) where {T<:Real,P<:AbstractFloat,O<:Signed}\n        # Space discretisation\n        x_inf = -L/2 # Inferior lim in x\n        x_sup = L/2  # Superior lim in x\n        dx = (x_sup-x_inf)/N # x step\n        dy = dx    # y step\n    \n        # Mesh grid\n        x = collect(x_inf:dx:x_sup-dx)\n        y = x\n\n        # Time discretisation\n        dt = tspan/n             # Time step\n        t  = collect(0:dt:tspan) # Time discretized\n\n        # Delay computations\n        τ_max_1D = L/(2*v)              # Maximum delay 1D domain\n        τ_max_2D = L/(sqrt(2)*v)        # Maximum delay 2D domain\n        Δr    = max(1.0,(v*dt)/dx)      # Compute rings width\n        rings1D = 1+floor(O,τ_max_1D/dt) # Number of delay rings (u_max)\n        rings2D = 1+floor(O,τ_max_2D/dt) # Number of delay rings (u_max)\n        \n        new(L,N,dx,dy,x,y,tspan,n,dt,t,v,Δr,rings1D,rings2D)\n    end\nend", "meta": {"hexsha": "3dcbda6088f0158073eb2e413e0f2744abfc8e93", "size": 1268, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DomainConstruct.jl", "max_stars_repo_name": "tiagoseq/NFEquations.jl", "max_stars_repo_head_hexsha": "8ffd395a587c3f9640cd783f8afdf2c165b0f9cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-06-16T17:34:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T03:54:13.000Z", "max_issues_repo_path": "src/DomainConstruct.jl", "max_issues_repo_name": "tiagoseq/NeuralFieldEq.jl", "max_issues_repo_head_hexsha": "8ffd395a587c3f9640cd783f8afdf2c165b0f9cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-06-01T13:02:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T11:41:27.000Z", "max_forks_repo_path": "src/DomainConstruct.jl", "max_forks_repo_name": "tiagoseq/NFEquations.jl", "max_forks_repo_head_hexsha": "8ffd395a587c3f9640cd783f8afdf2c165b0f9cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-07T07:32:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T07:32:43.000Z", "avg_line_length": 30.1904761905, "max_line_length": 99, "alphanum_fraction": 0.4842271293, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7603297371909326}}
{"text": "demand = [12, 14, 16, 18, 20, 22, 24, 26, 28, 30] # Demand of newspapers in each scenario\nlengthS = length(demand)\nvec_prob = [0.05, 0.10, 0.10, 0.10, 0.15, 0.15, 0.10, 0.10, 0.10, 0.05 ] # probability of scenario\nc = 20 # purchase price\np = 70 # selling price\nh = 10 # scrap value\ny = 20\n# 1. Solved by L-Shaped Benders Algorithm ------------------------------------------------------------------------------\nn_x = 10\nn_y = 1\nvec_min_y = hcat([0])\nvec_max_y = hcat([30])\nvec_f = hcat(c - 10)\nvec_pi = hcat(vec_prob)\nmat_c = zeros(10, 1, 1)\nfor i = 1:10\n    mat_c[i, :, :] = hcat([- 70 + 10])\nend\nmat_h = zeros(10, 2, 1)\nfor i = 1: 10\n    mat_h[i, 1, :] = hcat(- demand[i])\n    mat_h[i, 2, :] = hcat(0)\nend\nmat3_t = zeros(10, 2, 1)\nfor i = 1:10\n    mat3_t[i, 1, :] = hcat(0)\n    mat3_t[i, 2, :] = hcat(1)\nend\nmat3_w = - ones(10, 2, 1)\nepsilon = 0.001\ntimesIterationMax = 500\n", "meta": {"hexsha": "35f716229124ba145128e31dd87745ffccd3e7f1", "size": 875, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/benders/news-boy/data.jl", "max_stars_repo_name": "edxu96/MatrixOptim", "max_stars_repo_head_hexsha": "97ef8b1311351291427f8f650b0215c7ff00bddc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/benders/news-boy/data.jl", "max_issues_repo_name": "edxu96/MatrixOptim", "max_issues_repo_head_hexsha": "97ef8b1311351291427f8f650b0215c7ff00bddc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/benders/news-boy/data.jl", "max_forks_repo_name": "edxu96/MatrixOptim", "max_forks_repo_head_hexsha": "97ef8b1311351291427f8f650b0215c7ff00bddc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-04T09:41:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-04T09:41:13.000Z", "avg_line_length": 27.34375, "max_line_length": 120, "alphanum_fraction": 0.5382857143, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661944, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7603297357888481}}
{"text": "using Plots\n\nfunction khayyam_triangle(lentingle)\n    output = []\n    for i in 1:lentingle\n        push!(output, [])\n        for j in 1:i\n            if j == 1\n                append!(output[i], 1)\n            elseif j == i\n                append!(output[i], 1)\n            else j != 1 && j != i\n                add = output[i - 1][j] + output[i - 1][j - 1]\n                append!(output[i], add)\n            end\n        end\n    end\n    return output\nend\n\norder = 2^11\ntriangle = khayyam_triangle(order)\nx = []\ny = []\nfor i in 1:order\n    for j in 1:i\n        if triangle[i][j]%2 != 0\n            push!(x, j - i/2)\n            push!(y, -i)\n        end\n    end\nend\nscatter(x,y,markersize = 0.000001, legend = false, border=:none, dpi=300)\nsavefig(\"C:\\\\Users\\\\Yaghoub\\\\Documents\\\\GitHub\\\\A-few-fractals-in-Julia\\\\Fractals-Fig\\\\SKT.png\")\n", "meta": {"hexsha": "0e1de73216c432182c3adc90c381ea329d081b56", "size": 836, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Fractals-code/Sierpinski-Khayyam-triangle.jl", "max_stars_repo_name": "shahmari/A-few-fractals-in-Julia", "max_stars_repo_head_hexsha": "bf0373174af16d1473e8e865377cac061b7191d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-25T09:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T12:35:32.000Z", "max_issues_repo_path": "Fractals-code/Sierpinski-Khayyam-triangle.jl", "max_issues_repo_name": "shahmari/A-few-fractals-in-Julia", "max_issues_repo_head_hexsha": "bf0373174af16d1473e8e865377cac061b7191d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Fractals-code/Sierpinski-Khayyam-triangle.jl", "max_forks_repo_name": "shahmari/A-few-fractals-in-Julia", "max_forks_repo_head_hexsha": "bf0373174af16d1473e8e865377cac061b7191d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8857142857, "max_line_length": 96, "alphanum_fraction": 0.4940191388, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7603297344749803}}
{"text": "using PyPlot\n\n# TeX labels\n#rc('font',**{'family':'sans-serif','sans-serif':['Helvetica'],'size':6})\n#rc('text', usetex=True)\n#rc('xtick',labelsize=6)\n\ng1=3.\ng2=2.\ng3=1.\neps=1.e-3\n\n# calculations for plotting the POTATO stats here\n\nfunction rmin(u)\n    \"minimal radius from zeros of the determinant of the Hessian of classical energy\"\n    u1=u[1]\n    u2=u[2]\n    u3=u[3]\n    s2=g1 * u1^2 + g2 * u2^2 + g3 * u3^2;\n    s1=-(g1*g2+g1*g3+g2*g3) + g1*g2*u3^2 + g1*g3*u2^2 + g2*g3*u1^2;\n    s0=g1*g2*g3;\n    discr=s1^2-4*s0*s2\n    if discr > 0\n        q0 = (-s1+(s1^2-4*s0*s2)^0.5)/2/s2\n        q1 = (-s1-(s1^2-4*s0*s2)^0.5)/2/s2\n        qq=min(q0,q1)\n        ret=1/qq\n        if  ret > 1/g2-eps && ret < 1/g3+eps\n            return ret;\n        end\n    end \nend \n\nfunction phi1(X)\n    theta=X[1]\n    phi=X[2]\n    u1=sin(theta)*cos(phi)\n    u2=sin(theta)*sin(phi)\n    u3=cos(theta)\n    r=rmin([u1,u2,u3])\n    return (r-1/g1)*u1;\nend \n\nfunction phi2(X)\n    theta=X[1]\n    phi=X[2]\n    u1=sin(theta)*cos(phi)\n    u2=sin(theta)*sin(phi)\n    u3=cos(theta)\n    r=rmin([u1,u2,u3])\n    return (r-1/g2)*u2;\nend \n\nfunction phi3(X)\n    theta=X[1]\n    phi=X[2]\n    u1=sin(theta)*cos(phi)\n    u2=sin(theta)*sin(phi)\n    u3=cos(theta)\n    r=rmin([u1,u2,u3])\n    return (r-1/g3)*u3;\nend \n\n# save data for potato in an array\nNN=100\nths=linspace(0,pi/2,NN)\nphs=linspace(0,2*pi,NN)\n\npp=Iterators.product(ths,phs)\nP1=map(phi1,pp)\n\npp=Iterators.product(ths,phs)\nP2=map(phi2,pp)\n\npp=Iterators.product(ths,phs)\nP3=map(phi3,pp)\n\nP1=reshape(P1,(NN,NN))\nP2=reshape(P2,(NN,NN))\nP3=reshape(P3,(NN,NN))\n\n# calculate disc region as a surface\nph1d(X)=(1/g3-1/g1)*X[1]*cos(X[2]); \nph2d(X)=(1/g3-1/g2)*X[1]*sin(X[2]);\nph3d(X)=0;\n\nrs=linspace(0,1,NN)\nps=linspace(0,2*pi,NN)\n\npp=Iterators.product(rs,ps)\nP1a=map(ph1d,pp)\n\npp=Iterators.product(rs,ps)\nP2a=map(ph2d,pp)\n\npp=Iterators.product(rs,ps)\nP3a=map(ph3d,pp)\n\nP1a=reshape(P1a,(NN,NN))\nP2a=reshape(P2a,(NN,NN))\nP3a=reshape(P3a,(NN,NN))\n\n# Plotting starts here\n\nfig2 = figure()\nfig2[:set_size_inches]([3.487,2*3.487/1.618])\n#plt.tick_params(labelsize=6)\n\n#ax = fig2[:add_subplot](111),# projection=\"3d\")\n#ax[:set_xlabel](\"phi_1^r\")\n#ax[:set_ylabel](\"phi_2^r\")\n#ax[:set_zlabel](\"phi_3^r\")\n\n# plot disc region\n#plot_surface(P1a,P2a,P3a,alpha=1,color=\"r\")\n#ax[:plot_surface](P1a, P2a, P3a,alpha=1,color=\"r\")\n# plot potato\n#ax.plot_wireframe(P1, P2, P3)\n#ax.plot_wireframe(P1l, P2l, P3l)\n\n#ax.plot_surface(P1l, P2l, P3l,rstride=1,cstride=1,color=\"w\")\nplot_surface(P1, P2, P3,rstride=4,cstride=2,color=\"w\",alpha=0.8)\n\nax = gca()\nax[:set_xlim](1/g1-1/g3,1/g3-1/g1)\nax[:set_ylim](1/g2-1/g3,1/g3-1/g2)\nax[:set_zlim](1/g2-1/g3,1/g3-1/g2)\n\n\n#ax[:view_init](100,30)\n\nsavefig(\"fig2bot.svg\")\n", "meta": {"hexsha": "ccd3d464bd7b9a294ff5d718a6663a18466eb257", "size": 2692, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "misc/potato.jl", "max_stars_repo_name": "akels/WeylDisc", "max_stars_repo_head_hexsha": "7879358f2c5e77b1b81b1081d8d7e444204c7da1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "misc/potato.jl", "max_issues_repo_name": "akels/WeylDisc", "max_issues_repo_head_hexsha": "7879358f2c5e77b1b81b1081d8d7e444204c7da1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc/potato.jl", "max_forks_repo_name": "akels/WeylDisc", "max_forks_repo_head_hexsha": "7879358f2c5e77b1b81b1081d8d7e444204c7da1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0895522388, "max_line_length": 85, "alphanum_fraction": 0.6188707281, "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164656, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7603297244839547}}
{"text": "# skip the first prime (2) and try only odd numbers. 10000. item is now 10001. item :)\n\nfunction buildPrimes(count)\n    primes = Array(Int64, count)\n    slot = 1\n\n    function check(n)\n        i = 1\n        while i < slot\n            if n%primes[i] == 0\n                return false\n            end\n            i += 1\n        end\n        return true\n    end\n\n    n = 3\n    while slot <= count\n        if check(n)\n            primes[slot] = n\n            slot += 1\n        end\n        n += 2\n    end\n\n    return primes\nend\n\nprintln(buildPrimes(10000)[end])", "meta": {"hexsha": "e1285b15a26eb1892b0aad0b0ea4a526e10a3d11", "size": 555, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "007 - 10001st Prime/007 - 10001st_Prime.jl", "max_stars_repo_name": "LanguageAdventures/Project-Euler-Julia", "max_stars_repo_head_hexsha": "e4ecad7ed0037f6c2472ac25118466c126cbcf38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-27T10:41:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T14:48:59.000Z", "max_issues_repo_path": "007 - 10001st Prime/007 - 10001st_Prime.jl", "max_issues_repo_name": "LanguageAdventures/Project-Euler-Julia", "max_issues_repo_head_hexsha": "e4ecad7ed0037f6c2472ac25118466c126cbcf38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "007 - 10001st Prime/007 - 10001st_Prime.jl", "max_forks_repo_name": "LanguageAdventures/Project-Euler-Julia", "max_forks_repo_head_hexsha": "e4ecad7ed0037f6c2472ac25118466c126cbcf38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5, "max_line_length": 86, "alphanum_fraction": 0.4846846847, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.938124016006303, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.760329724395738}}
{"text": "\"\"\"\n    bbands(x::Array{Float64}; n::Int64=10, sigma::Float64=2.0)::Matrix{Float64}\n\nBollinger bands (moving average with standard deviation bands)\n\n*Output*\n- Column 1: lower band\n- Column 2: middle band\n- Column 3: upper band\n\"\"\"\nfunction bbands(x::Array{Float64}; n::Int64=10, sigma::Float64=2.0, ma::Function=sma, args...)::Matrix{Float64}\n    @assert n<size(x,1) && n>0 \"Argument n is out of bounds.\"\n    out = zeros(size(x,1), 3)  # cols := lower bound, ma, upper bound\n    out[:,2] = ma(x, n=n, args...)\n    sd = runsd(x, n=n, cumulative=false)\n    out[:,1] = out[:,2] - sigma*sd\n    out[:,3] = out[:,2] + sigma*sd\n    return out\nend\n\n\"\"\"\n    tr(hlc::Matrix{Float64})::Array{Float64}\n\nTrue range\n\"\"\"\nfunction tr(hlc::Matrix{Float64})::Array{Float64}\n    @assert size(hlc,2) == 3 \"HLC array must have 3 columns.\"\n    n = size(hlc,1)\n    out = zeros(n)\n    out[1] = NaN\n    @inbounds for i=2:n\n        out[i] = max(hlc[i,1]-hlc[i,2], hlc[i,1]-hlc[i-1,3], hlc[i-1,3]-hlc[i,2])\n    end\n    return out[:,1]\nend\n\n\"\"\"\n    atr(hlc::Matrix{Float64}; n::Int64=14)::Array{Float64}\n\nAverage true range (uses exponential moving average)\n\"\"\"\nfunction atr(hlc::Matrix{Float64}; n::Int64=14, ma::Function=ema)::Array{Float64}\n    @assert n<size(hlc,1) && n>0 \"Argument n out of bounds.\"\n    return [NaN; ma(tr(hlc)[2:end], n=n)]\nend\n\n\"\"\"\n    keltner(hlc::Matrix{Float64}; nema::Int64=20, natr::Int64=10, mult::Int64=2)::Matrix{Float64}\n\nKeltner bands\n\n*Output*\nColumn 1: lower band\nColumn 2: middle band\nColumn 3: upper band\n\"\"\"\nfunction keltner(hlc::Array{Float64,2}; nema::Int64=20, natr::Int64=10, mult::Int64=2)::Matrix{Float64}\n    @assert size(hlc,2) == 3 \"HLC array must have 3 columns.\"\n    out = zeros(size(hlc,1), 3)\n    out[:,2] = ema(hlc[:,3], n=nema)\n    out[:,1] = out[:,2] - mult*atr(hlc, n=natr)\n    out[:,3] = out[:,2] + mult*atr(hlc, n=natr)\n    return out\nend\n", "meta": {"hexsha": "1ba9d2681e31e678869eff98d72a32d6512135b6", "size": 1870, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vol.jl", "max_stars_repo_name": "bisraelsen/Indicators.jl", "max_stars_repo_head_hexsha": "c8e81512d78e9394777cd8817ed60b6a44197cfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/vol.jl", "max_issues_repo_name": "bisraelsen/Indicators.jl", "max_issues_repo_head_hexsha": "c8e81512d78e9394777cd8817ed60b6a44197cfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vol.jl", "max_forks_repo_name": "bisraelsen/Indicators.jl", "max_forks_repo_head_hexsha": "c8e81512d78e9394777cd8817ed60b6a44197cfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7692307692, "max_line_length": 111, "alphanum_fraction": 0.6176470588, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565738, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.7603297216797853}}
{"text": "@doc raw\"\"\"\n    gausshermite(n::Integer) -> x, w  # nodes, weights\n\nReturn nodes `x` and weights `w` of [Gauss-Hermite quadrature](https://en.wikipedia.org/wiki/Gauss%E2%80%93Hermite_quadrature).\n\n```math\n\\int_{-\\infty}^{+\\infty} f(x) \\exp(-x^2) dx \\approx \\sum_{i=1}^{n} w_i f(x_i)\n```\n\n# Examples\n```jldoctest\njulia> x, w = gausshermite(3);\n\njulia> f(x) = x^4;\n\njulia> I = dot(w, f.(x));\n\njulia> I ≈ 3(√π)/4\ntrue\n```\n\"\"\"\nfunction gausshermite(n::Integer)\n    x,w = unweightedgausshermite(n)\n    w .*= exp.(-x.^2)\n    x, w\nend\n\nfunction unweightedgausshermite(n::Integer)\n    # GAUSSHERMITE(n) COMPUTE THE GAUSS-HERMITE NODES AND WEIGHTS IN O(n) time.\n    if n < 0\n        throw(DomainError(n, \"Input n must be a non-negative integer\"))\n    elseif n == 0\n        return Float64[],Float64[]\n    elseif n == 1\n        return [0.0],[sqrt(π)]\n    elseif n ≤ 20\n       # GW algorithm\n       x = hermite_gw(n)\n    elseif n ≤ 200\n       # REC algorithm\n       x = hermite_rec(n)\n    else\n       # ASY algorithm\n       x = hermite_asy(n)\n    end\n\n    # fold out\n    if isodd(n)\n        _w = [reverse(x[2][:]); x[2][2:end]]\n        _x = [-reverse(x[1]) ; x[1][2:end]]\n    else\n        _w = [reverse(x[2][:]); x[2][:]]\n        _x = [-reverse(x[1]) ; x[1]]\n    end\n    _w .*= sqrt(π)/sum(exp.(-_x.^2).*_w)\n\n    return _x, _w\nend\n\nfunction hermite_asy(n::Integer)\n    # Compute Hermite nodes and weights using asymptotic formula\n\n    x0 = hermite_initialguess(n)  # get initial guesses\n    t0 = x0./sqrt(2n+1)\n    θ = acos.(t0)  # convert to θ-variable\n    val = x0\n    for _ in 1:20\n        val = hermpoly_asy_airy(n, θ)\n        dθ = -val[1]./(sqrt(2).*sqrt(2n+1).*val[2].*sin.(θ))\n        θ .-= dθ  # Newton update\n        if norm(dθ,Inf) < sqrt(eps(Float64))/10\n           break\n        end\n    end\n    t0 = cos.(θ)\n    x = sqrt(2n+1)*t0  #back to x-variable\n    w = x.*val[1] .+ sqrt(2).*val[2]\n    w .= 1 ./ w.^2  # quadrature weights\n\n    return x, w\nend\n\nfunction hermite_rec(n::Integer)\n    # Compute Hermite nodes and weights using recurrence relation.\n\n    x0 = hermite_initialguess(n)\n    x0 .*= sqrt(2)\n    val = x0\n    for _ in 1:10\n        val = hermpoly_rec.(n, x0)\n        dx = first.(val)./last.(val)\n        dx[ isnan.( dx ) ] .= 0\n        x0 .= x0 .- dx\n        if norm(dx, Inf) < sqrt(eps(Float64))\n            break\n        end\n    end\n    x0 ./= sqrt(2)\n    w = 1 ./ last.(val).^2  # quadrature weights\n\n    return x0, w\nend\n\nfunction hermpoly_rec(n::Integer, x0)\n    # HERMPOLY_rec evaluation of scaled Hermite poly using recurrence\n    n < 0 && throw(DomainError(n, \"Input n must be a non-negative integer\"))\n    # evaluate:\n    w = exp(-x0^2 / (4*n))\n    wc = 0 # 0 times we've applied wc\n    Hold = one(x0)\n    # n == 0 && return (Hold, 0)\n    H = x0\n    for k = 1:n-1\n        Hold, H = H, (x0*H/sqrt(k+1) - Hold/sqrt(1+1/k))\n        while abs(H) ≥ 100 && wc < n  # regularise\n            H *= w\n            Hold *= w\n            wc += 1\n        end\n        k += 1\n    end\n    for _ = wc+1:n\n        H *= w\n        Hold *= w\n    end\n\n    return H, -x0*H + sqrt(n)*Hold\nend\n\nfunction hermpoly_rec(r::Base.OneTo, x0)\n    isempty(r) && return [1.0]\n    n = maximum(r)\n    # HERMPOLY_rec evaluation of scaled Hermite poly using recurrence\n    n < 0 && throw(DomainError(n, \"Input n must be a non-negative integer\"))\n    n == 0 && return [exp(-x0^2 / 4)]\n    p = max(1,floor(Int,x0^2/100))\n    w = exp(-x0^2 / 4p)\n    wc = 0 # 0 times we've applied wc\n    ret = Vector{Float64}()\n    Hold = one(x0)\n    push!(ret, Hold)\n    H = x0\n    push!(ret, H)\n    for k = 1:n-1\n        Hold, H = H, (x0*H/sqrt(k+1) - Hold/sqrt(1+1/k))\n        while abs(H) ≥ 100 && wc < p  # regularise\n            ret .*= w\n            H *= w\n            Hold *= w\n            wc += 1\n        end\n        push!(ret, H)\n        k += 1\n    end\n    ret .*= w^(p-wc)\n\n    return ret\nend\n\nhermpoly_rec(r::AbstractRange, x0) = hermpoly_rec(Base.OneTo(maximum(r)), x0)[r.+1]\n\nfunction hermpoly_asy_airy(n::Integer, θ::AbstractVector)\n    # HERMPOLY_ASY evaluation hermite poly using Airy asymptotic formula in θ-space.\n\n    musq = 2n+1\n    cosT = cos.(θ)\n    sinT = sin.(θ)\n    sin2T = 2 .* cosT.*sinT\n    η = 0.5 .* θ .- 0.25 .* sin2T\n    χ = -(3*η/2).^(2/3)\n    φ = (-χ./sinT.^2).^(1/4)\n    C = 2*sqrt(π)*musq^(1/6)*φ\n    Airy0 = real.(airyai.(musq.^(2/3).*χ))\n    Airy1 = real.(airyaiprime.(musq.^(2/3).*χ))\n\n    # Terms in (12.10.43):\n    a0 = 1\n    b0 = 1\n    a1 = 15/144\n    b1 = -7/5*a1\n    a2 = 5*7*9*11/2/144^2\n    b2 = -13/11*a2\n    a3 = 7*9*11*13*15*17/6/144^3\n    b3 = -19/17*a3\n\n    # u polynomials in (12.10.9)\n    u0 = 1\n    u1 = (cosT.^3-6*cosT)/24\n    u2 = (-9*cosT.^4 + 249*cosT.^2 .+ 145)/1152\n    u3 = (-4042*cosT.^9+18189*cosT.^7-28287*cosT.^5-151995*cosT.^3-259290*cosT)/414720\n\n    # first term\n    A0 = 1\n    val = A0*Airy0\n\n    # second term\n    B0 = -(a0*u1.*φ.^6 .+ a1*u0) ./ χ.^2\n    val .+=  B0.*Airy1./musq.^(4/3)\n\n    # third term\n    A1 = (b0*u2.*φ.^12 + b1*u1.*φ.^6 .+ b2*u0) ./ χ.^3\n    val .+= A1.*Airy0/musq.^2\n\n    # fourth term\n    B1 = -(u3.*φ.^18 + a1*u2.*φ.^12 + a2*u1.*φ.^6 .+ a3*u0) ./ χ.^5\n    val .+= B1.*Airy1./musq.^(4/3+2)\n\n    val .= C.*val\n\n    ## Derivative\n    η = .5*θ - .25*sin2T\n    χ = -(3*η/2).^(2/3)\n    φ = (-χ./sinT.^2).^(1/4)\n    C = sqrt(2*π)*musq^(1/3)./φ\n\n    # v polynomials in (12.10.10)\n    v0 = 1\n    v1 = (cosT.^3+6cosT)/24\n    v2 = (15*cosT.^4 - 327*cosT.^2 .- 143)/1152\n    v3 = (259290*cosT + 238425*cosT.^3 - 36387*cosT.^5 + 18189*cosT.^7 - 4042*cosT.^9)/414720\n\n    # first term\n    C0 = -(b0*φ.^6 .* v1 .+ b1.*v0)./χ\n    dval = C0.*Airy0/musq.^(2/3)\n\n    # second term\n    D0 =  a0*v0\n    dval = dval + D0*Airy1\n\n    # third term\n    C1 = -(v3.*φ.^18 + b1*v2.*φ.^12 + b2*v1.*φ.^6 .+ b3*v0) ./ χ.^4\n    dval = dval + C1.*Airy0/musq.^(2/3+2)\n\n    # fourth term\n    D1 = (a0*v2.*φ.^12 + a1*v1.*φ.^6 .+ a2*v0) ./ χ.^3\n    dval = dval + D1.*Airy1/musq.^2\n\n    dval = C.*dval\n\n    return val, dval\nend\n\nfunction hermite_initialguess(n::Integer)\n    # HERMITEINTITIALGUESSES(N), Initial guesses for Hermite zeros.\n    #\n    # [1] L. Gatteschi, Asymptotics and bounds for the zeros of Laguerre\n    # polynomials: a survey, J. Comput. Appl. Math., 144 (2002), pp. 7-27.\n    #\n    # [2] F. G. Tricomi, Sugli zeri delle funzioni di cui si conosce una\n    # rappresentazione asintotica, Ann. Mat. Pura Appl. 26 (1947), pp. 283-300.\n\n    # Error if n < 20 because initial guesses are based on asymptotic expansions:\n    @assert n ≥ 20\n\n    # Gatteschi formula involving airy roots [1].\n    # These initial guess are good near x = sqrt(n+1/2);\n    if isodd(n)\n        m = (n-1)>>1\n        # bess = (1:m)*π\n        a = .5\n    else\n        m = n>>1\n        # bess = ((0:m-1) .+ 0.5)*π\n        a = -.5\n    end\n    ν = 4m + 2a + 2\n\n    T(t) = t^(2/3)*(1+5/48*t^(-2)-5/36*t^(-4)+(77125/82944)*t^(-6) -108056875/6967296*t^(-8)+162375596875/334430208*t^(-10))\n    airyrts = -T.(3π/8*(4*(1:m) .- 1))\n\n    airyrts[1:10] .= AIRY_ROOTS[1:10]  # correct first 10.\n\n    x_init = sqrt.(abs.(ν .+ (2^(2/3)).*airyrts.*ν^(1/3) .+ (1/5*2^(4/3)).*airyrts.^2 .* ν^(-1/3) .+\n        (11/35-a^2-12/175).*airyrts.^3 ./ ν .+ ((16/1575).*airyrts.+(92/7875).*airyrts.^4).*2^(2/3).*ν^(-5/3) .-\n        ((15152/3031875).*airyrts.^5 .+ (1088/121275).*airyrts.^2).*2^(1/3).*ν^(-7/3)))\n    x_init_airy = reverse(x_init)\n\n    # Tricomi initial guesses. Equation (2.1) in [1]. Originally in [2].\n    # These initial guesses are good near x = 0 . Note: zeros of besselj(+/-.5,x)\n    # are integer and half-integer multiples of π.\n    # x_init_bess =  bess/sqrt(ν).*sqrt((1+ (bess.^2+2*(a^2-1))/3/ν^2) );\n    Tnk0 = fill(π/2,m)\n    rhs = ((4m+3) .- 4*(1:m))/ν*π\n\n    for k = 1:7\n        val = Tnk0 .- sin.(Tnk0) .- rhs\n        dval = 1 .- cos.(Tnk0)\n        dTnk0 = val./dval\n        Tnk0 = Tnk0 .- dTnk0\n    end\n\n    tnk = cos.(Tnk0/2).^2\n    x_init_sin = sqrt.(ν*tnk - ((tnk.+1/4)./(tnk.-1).^2 .+ (3a^2-1))/3ν)\n\n    # Patch together\n    p = 0.4985+eps(Float64)\n    x_init = [x_init_sin[1:convert(Int,floor(p*n))]\n    x_init_airy[convert(Int,ceil(p*n)):end]]\n\n    if isodd(n)\n        x_init = [0 ; x_init]\n        x_init = x_init[1:m+1]\n    else\n        x_init = x_init[1:m]\n    end\n\n    return x_init\nend\n\nfunction hermite_gw(n::Integer)\n    # Golub--Welsch algorithm. Used here for n ≤ 20.\n\n    beta = sqrt.((1:n-1)/2)  # 3-term recurrence coeffs\n    T = SymTridiagonal(zeros(n), beta)  # Jacobi matrix\n    D, V = eigen(T)  # Eigenvalue decomposition\n    ind = sortperm(D)  # Hermite points\n    x = D[ind]  # nodes\n    w = sqrt(π)*V[1,ind].^2  # weights\n\n    # Enforce symmetry:\n    i = floor(Int, n/2)+1:n\n    x = x[i]\n    w = w[i]\n    return x, exp.(x.^2).*w\nend\n", "meta": {"hexsha": "9e7f79e34cfb1401682e5c95dfbcdf4127362e03", "size": 8670, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gausshermite.jl", "max_stars_repo_name": "ajt60gaibb/FastGaussQuadrature.jl", "max_stars_repo_head_hexsha": "7b256f3b10f66e42caea5f38c4bd8593a18c96b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-01-10T01:35:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-31T05:59:51.000Z", "max_issues_repo_path": "src/gausshermite.jl", "max_issues_repo_name": "ajt60gaibb/FastGaussQuadrature.jl", "max_issues_repo_head_hexsha": "7b256f3b10f66e42caea5f38c4bd8593a18c96b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2015-05-26T13:30:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-08T20:47:12.000Z", "max_forks_repo_path": "src/gausshermite.jl", "max_forks_repo_name": "ajt60gaibb/FastGaussQuadrature.jl", "max_forks_repo_head_hexsha": "7b256f3b10f66e42caea5f38c4bd8593a18c96b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2015-04-24T20:26:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-04T14:23:46.000Z", "avg_line_length": 26.5950920245, "max_line_length": 127, "alphanum_fraction": 0.5262975779, "num_tokens": 3544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415278, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.760312615064}}
{"text": "\"\"\"\n    initial_population(individues::Integer, lower_limits::AbstractArray, upper_limits::AbstractArray)\nReturn a `m*n` matrix which `m` is the number of `individues` and `n` the number of parameters. Each individue (row) has `n` parameters\nwith upper and lower limits given by `lower_limits, upper_limits` arrays.\n\n# Examples\n```julia-repl\njulia> initial_population(4,[-1,-5],[1,5])\n4×3 Array{Float64,2}:\n -0.997462  -3.461379\n  0.056423   4.564237\n  0.167943  -4.467215\n  0.695743   0.561379\n```\n\"\"\"\nfunction initial_population(individues::Integer, lower_limits::AbstractArray, upper_limits::AbstractArray)\n    \n    #Error checks\n    if length(lower_limits) != length(upper_limits)\n        throw(ErrorException(\"The limits must have the same length: lower and upper limits of length $(length(lower_limits)) and $(length(upper_limits)).\"))\n    end\n\n    return row_mul( (upper_limits .- lower_limits), rand(individues,length(lower_limits)) ) .+ lower_limits'\n    \nend\n", "meta": {"hexsha": "345d7d18dde0eb5d8042348cfd16fc139daf876e", "size": 969, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PopulationFunctions.jl", "max_stars_repo_name": "Urcelay97/DiferentialEvolution", "max_stars_repo_head_hexsha": "d8543c9af1286ff5d3bb9bca7ab064fb7b3202ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PopulationFunctions.jl", "max_issues_repo_name": "Urcelay97/DiferentialEvolution", "max_issues_repo_head_hexsha": "d8543c9af1286ff5d3bb9bca7ab064fb7b3202ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PopulationFunctions.jl", "max_forks_repo_name": "Urcelay97/DiferentialEvolution", "max_forks_repo_head_hexsha": "d8543c9af1286ff5d3bb9bca7ab064fb7b3202ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2692307692, "max_line_length": 156, "alphanum_fraction": 0.7265221878, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7603126135990115}}
{"text": "export shannon_entropy, von_neumann_entropy, joint_entropy, conditional_entropy\nexport holevo_bound, mutual_information\nexport success_probability, error_probability\n\n\"\"\"\n    shannon_entropy( probabilities :: AbstractVector ) :: Float64\n\nThe classical entropy of a probability distribution:\n\n```math\nS = -\\\\sum_{i=1}^n p_i \\\\log_2(p_i)\n```\n\nA `DomainError` is thrown if input `probabilities` does not satisfy [`is_probability_distribution`](@ref).\n\"\"\"\nfunction shannon_entropy( probabilities :: AbstractVector ) :: Float64\n    is_probability_distribution(probabilities) || Probabilities(probabilities)\n\n    entropy = -1*sum(map(\n        (p) -> isapprox(p, 0, atol=1e-7) ? 0 : p*log2(p),\n        probabilities\n    ))\n\n    entropy\nend\n\n\"\"\"\n    von_neumann_entropy( ρ :: AbstractMatrix ) :: Float64\n\nThe von neumann entropy of a density matrix:\n\n\n```math\nS(\\\\rho) = - \\\\sum_j  \\\\lambda_j \\\\log_2(\\\\lambda_j)\n```\n\nwhere ``\\\\lambda_j`` are the eigenvalues of quantum  state ``\\\\rho``.\n\nA `DomainError` is thrown if `ρ` does not satisfy [`is_density_matrix`](@ref).\n\"\"\"\nfunction von_neumann_entropy(ρ :: AbstractMatrix) :: Float64\n    is_density_matrix(ρ) || State(ρ)\n\n    λs = Probabilities(eigvals(ρ))\n    entropy = shannon_entropy(λs)\n\n    entropy\nend\n\n\"\"\"\n    holevo_bound(\n        priors :: AbstractVector,\n        ρ_states :: Vector{<:AbstractMatrix}\n    ) :: Float64\n\nThe Holevo theorem places a bound on the [`mutual_information`](@ref) ``I(X : Y) \\\\leq \\\\mathcal{X}``.\nIt places a limit on the amount information that can be decoded from a set of quantum states.\nFor a mixed state ``\\\\rho = \\\\sum_i p_i \\\\rho_i`` the Holevo bound ``\\\\mathcal{X}`` is\n\n```math\n\\\\mathcal{X}  := S(\\\\rho) - \\\\sum_i p_i S(\\\\rho_i)\n```\n\nwhere ``S(\\\\rho)`` is the [`von_neumann_entropy`](@ref).\n\n\nA `DomainError` is thrown  if:\n* `priors` does not satisfy [`is_probability_distribution`](@ref).\n* Any `ρ ∈ ρ_states` does not satisfy [`is_density_matrix`](@ref).\n\"\"\"\nfunction holevo_bound(priors::AbstractVector, ρ_states::Vector{<:AbstractMatrix}) :: Float64\n    is_probability_distribution(priors) || Probabilities(priors)\n    all(is_density_matrix.(ρ_states)) || State.(ρ_states)\n\n    ρ = mixed_state(priors, ρ_states)\n    ρ_ent = von_neumann_entropy(ρ)\n\n    ρ_states_ent = von_neumann_entropy.(ρ_states)\n    ρ_sum_ent = sum( priors .* ρ_states_ent )\n\n    bound = ρ_ent - ρ_sum_ent\n\n    bound\nend\n\n\"\"\"\n    joint_entropy(priors :: AbstractVector, conditionals :: AbstractMatrix) :: Float64\n\nReturns the entropy for the union of pdf ``P(x,y)``. The joint entropy is the [`shannon_entropy`](@ref)\nof the joint probability distribution:\n\n```math\nS(X,Y) = - \\\\sum_{x,y} p(x,y) \\\\log_2(p(x,y))\n```\n\"\"\"\nfunction joint_entropy(priors::AbstractVector, conditionals::AbstractMatrix) :: Float64\n    is_probability_distribution(priors) || Probabilities(priors)\n    is_conditional_distribution(conditionals) || Conditionals(conditionals)\n\n    joint_probabilities = JointProbabilities(priors, conditionals)\n    shannon_entropy(joint_probabilities[:])\nend\n\n\"\"\"\n    conditional_entropy(priors::AbstractVector, conditionals::AbstractMatrix) :: Float64\n\nReturns the conditional entropy for the system with specified `priors` ``p(x)`` and `conditionals` ``p(y|x)``:\n\n```math\nS(Y|X) = - \\\\sum_{x,y} p(x,y)\\\\log_2\\\\left(\\\\frac{p(y|x)}{p(x)}\\\\right)\n```\n\"\"\"\nfunction conditional_entropy(priors::AbstractVector, conditionals::AbstractMatrix) :: Float64\n    is_probability_distribution(priors) || Probabilities(priors)\n    is_conditional_distribution(conditionals) || Conditionals(conditionals)\n\n    joint_probabilities = JointProbabilities(priors, conditionals)\n    (num_row, num_col) = size(joint_probabilities)\n\n    conditional_entropy = shannon_entropy(Probabilities(joint_probabilities[:])) + sum(sum(map( row -> map( col ->\n        joint_probabilities[row,col]*( isapprox(priors[col], 0, atol=1e-7) ? 0 : log2(priors[col]) ),\n    1:num_col), 1:num_row)))\n\n    conditional_entropy\nend\n\n\"\"\"\n    mutual_information(\n        priors :: AbstractVector,\n        conditionals :: AbstractMatrix\n    ) :: Float64\n\nThe entropy of the overlap between ``p(x)`` and ``p(y)``. The mutual information\nis directly computed from the [`shannon_entropy`](@ref) and [`joint_entropy`](@ref):\n\n\n```math\nI(X : Y) = S(X) + S(Y) - S(X,Y)\n```\n\"\"\"\nfunction mutual_information(priors::AbstractVector, conditionals::AbstractMatrix) :: Float64\n    is_probability_distribution(priors) || Probabilities(priors)\n    is_conditional_distribution(conditionals) || Conditionals(conditional)\n\n    prior_ent = shannon_entropy(priors)\n\n    outcome_probs = outcome_probabilities(priors,conditionals)\n    outcome_ent = shannon_entropy( outcome_probs )\n    joint_ent = joint_entropy(priors, conditionals)\n\n    mutual_information = prior_ent + outcome_ent - joint_ent\n\n    mutual_information\nend\n\n\"\"\"\n    mutual_information(\n        priors :: AbstractVector,\n        ρ_states :: Vector{<:AbstractMatrix},\n        Π :: AbstractVector\n    ) :: Float64\n\nComputes the classical mutual information for a quantum state and measurement\nencoding and decoding.\nThe conditional probabilities are obtained from quantum states and measurements\nusing [`measure`](@ref).\n\nA `DomainError` is thrown if:\n* `priors` does not satisfy [`is_probability_distribution`](@ref).\n* Any `ρ ∈ ρ_states` does not satisfy [`is_density_matrix`](@ref).\n* `Π` does not satisfy [`is_povm`](@ref).\n\"\"\"\nfunction mutual_information(\n    priors::AbstractVector,\n    states::Vector{<:AbstractMatrix},\n    Π::AbstractVector{<:AbstractMatrix}\n) :: Float64\n    is_probability_distribution(priors) || Probabilities(priors)\n\n    if !all(ρ -> ρ isa State, states)\n        states = State.(states)\n    end\n    if !(Π isa POVM)\n        Π = POVM(Π)\n    end\n\n    conditionals = measure(Π, states)\n    mutual_information(priors, conditionals)\nend\n\n\"\"\"\n    success_probability(\n        priors::AbstractVector,\n        states::Vector{<:AbstractMatrix},\n        Π::Vector{<:AbstractMatrix}\n    ) :: Float64\n\nThe probability of correctly distinguishing quantum states with the specifed POVM:\n\n```math\nP_{\\\\text{Success}} = \\\\sum_{i=1}^n p_i \\\\text{Tr}[\\\\Pi_i \\\\rho_i].\n```\n\nThe number of states must match the number POVMs.\n\"\"\"\nfunction success_probability(priors::AbstractVector,states::Vector{<:AbstractMatrix}, Π::AbstractVector{<:AbstractMatrix}) :: Float64\n    is_probability_distribution(priors) || Probabilities(priors)\n    all(is_density_matrix.(states)) || State.(states)\n    is_povm(Π) || POVM(Π)\n\n    sum(priors .* tr.(states .* Π))\nend\n\n\"\"\"\n    error_probability(\n        priors::AbstractVector,\n        ρ_states::Vector{<:AbstractMatrix},\n        Π::AbstractVector{<:AbstractMatrix}\n    ) :: Float64\n\nThe probability of incorrectly distinguishing quantum states with the specifed POVM.\nThis quantity is simply obtained as ``P_{\\\\text{Error}} = 1 - P_{\\\\text{Success}}``.\n\"\"\"\nfunction error_probability(priors::AbstractVector, ρ_states::Vector{<:AbstractMatrix}, Π::AbstractVector{<:AbstractMatrix}) :: Float64\n    1 .- success_probability(priors, ρ_states, Π)\nend\n", "meta": {"hexsha": "a4b6cf7fd7fc52343950d6d68a65377857626f1b", "size": 7042, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/information.jl", "max_stars_repo_name": "ChitambarLab/QBase.jl", "max_stars_repo_head_hexsha": "cb30a84b784c61abdae8b007e1de691f3ccd4e4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-05T01:27:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T01:27:24.000Z", "max_issues_repo_path": "src/information.jl", "max_issues_repo_name": "ChitambarLab/QBase.jl", "max_issues_repo_head_hexsha": "cb30a84b784c61abdae8b007e1de691f3ccd4e4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-06-15T00:20:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T15:59:20.000Z", "max_forks_repo_path": "src/information.jl", "max_forks_repo_name": "ChitambarLab/QBase.jl", "max_forks_repo_head_hexsha": "cb30a84b784c61abdae8b007e1de691f3ccd4e4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0220264317, "max_line_length": 134, "alphanum_fraction": 0.7030673104, "num_tokens": 1857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7603126109784567}}
{"text": "using LinearAlgebra\r\n\r\nfunction so3ToVec(so3mat)\r\n    if( size(so3mat)!=(3,3) )\r\n        println(\"!Warning! : Input matrix should be 3x3.\")\r\n        return\r\n    end\r\n    if( !((so3mat[1,1]==so3mat[2,2]==so3mat[3,3]==0)) )\r\n        println(\"!Warning! : Diagonals should be zero.\")\r\n        return\r\n    end\r\n    if( so3mat[2,1]!=-so3mat[1,2] ||\r\n        so3mat[3,1]!=-so3mat[1,3] ||\r\n        so3mat[3,2]!=-so3mat[2,3] )\r\n        println(\"!Warning! : Entered matrix isn't a skew symmetric matrix.\")\r\n        return\r\n    end\r\n    ret_vec = [so3mat[3,2];\r\n               so3mat[1,3];\r\n               so3mat[2,1] ]\r\n        return ret_vec\r\nend\r\n\r\nfunction vecToSo3(omg)\r\n    if( size(omg)!=(3,) )\r\n        println(\"!Warning! : Input matrix should be 3x1.\")\r\n        return\r\n    end\r\n\r\n    ret_ss_matrix = [0      -omg[3]   omg[2];\r\n                     omg[3]    0     -omg[1];\r\n                    -omg[2]  omg[1]      0];\r\n    return ret_ss_matrix\r\nend\r\n\r\nusing LinearAlgebra\r\n\r\nfunction so3ToVec(so3mat)\r\n    if( size(so3mat)!=(3,3) )\r\n        println(\"!Warning! : Input matrix should be 3x3.\")\r\n        return\r\n    end\r\n    if( !((so3mat[1,1]==so3mat[2,2]==so3mat[3,3]==0)) )\r\n        println(\"!Warning! : Diagonals should be zero.\")\r\n        return\r\n    end\r\n    if( so3mat[2,1]!=-so3mat[1,2] ||\r\n        so3mat[3,1]!=-so3mat[1,3] ||\r\n        so3mat[3,2]!=-so3mat[2,3] )\r\n        println(\"!Warning! : Entered matrix isn't a skew symmetric matrix.\")\r\n        return\r\n    end\r\n    ret_vec = [so3mat[3,2];\r\n               so3mat[1,3];\r\n               so3mat[2,1] ]\r\n        return ret_vec\r\nend\r\n\r\nfunction VecToso3(omg)\r\n    if( size(omg)!=(3,) )\r\n        println(\"!Warning! : Input matrix should be 3x1.\")\r\n        return\r\n    end\r\n\r\n    ret_ss_matrix = [0      -omg[3]   omg[2];\r\n                     omg[3]    0     -omg[1];\r\n                    -omg[2]  omg[1]      0];\r\n    return ret_ss_matrix\r\nend\r\n#****************************************************************#\r\n# VeysiADN 17 Apr 2021\r\n# Advanced Robotics Homework 4 Codes\r\n#****************************************************************#\r\nusing LinearAlgebra\r\nconst lAlgebra = LinearAlgebra\r\n#****************************************************************#\r\n# Returns normalized version of given matrix/array\r\nfunction Normalize(N)\r\n    return N/lAlgebra.norm(N)\r\nend\r\n#****************************************************************#\r\n# Returns 4x4 twist matrix ‘se3mat’ (an element of Lie Algebra se3)\r\n# from given twist vector (= 6x1 vector) ‘xi\r\nfunction VecTose3( xi )\r\n    w_skew = [ 0   -xi[3]   xi[2];\r\n              xi[3]   0    -xi[1];\r\n             -xi[2]  xi[1]    0 ]\r\n    return vcat(hcat(w_skew,xi[4:6]), zeros(1, 4))\r\nend\r\n#****************************************************************#\r\n# Returns twist vector ‘xi’ from given twist matrix ‘se3mat’\r\nfunction se3ToVec( se3mat )\r\n    omg = [se3mat[3, 2], se3mat[1, 3],se3mat[2, 1]]\r\n    v = se3mat[1:3, 4]\r\n    return vcat(omg,v)\r\nend\r\n#****************************************************************#\r\n# Calculates and return rotation matrix ‘R’ by\r\n# evaluating matrix exponential of 3x3 skew symmetric matrix ‘so3mat’\r\n\r\nfunction MatrixExp3(so3mat)\r\n        omg = [so3mat[3, 2], so3mat[1, 3],so3mat[2, 1]]\r\n        theta = lAlgebra.norm(omg)\r\n        omg_n = so3mat / theta\r\n        return lAlgebra.I + sin(theta) * omg_n + (1 - cos(theta)) * omg_n * omg_n\r\nend\r\n\r\n#****************************************************************#\r\n# Calculates and return transformation matrix ‘g’ by\r\n# evaluating matrix exponential of 4x4 twist matrix ‘se3mat’\r\nfunction MatrixExp6( se3mat )\r\n    omg = [se3mat[3, 2], se3mat[1, 3],se3mat[2, 1]]\r\n    theta = norm(omg)\r\n    if theta==0\r\n        return vcat(hcat(I, se3mat[1:3, 4]), [0 0 0 1])\r\n    else\r\n    omg_n = se3mat[1:3, 1:3] / theta\r\n    temp  = hcat(MatrixExp3(se3mat[1:3, 1:3]),\r\n                         (I * theta +\r\n                          (1 - cos(theta)) * omg_n +\r\n                          (theta - sin(theta)) * omg_n * omg_n) *\r\n                         se3mat[1:3, 4] / theta)\r\n    end\r\n    return    vcat(temp,[0 0 0 1])\r\nend\r\n\r\n#****************************************************************#\r\n# VeysiADN 12 May 2021\r\n# Advanced Robotics Homework 5 Codes\r\n#****************************************************************#\r\nusing LinearAlgebra\r\nconst lAlgebra = LinearAlgebra\r\n#****************************************************************#\r\n# Computes exponential coordinate ‘so3mat’\r\n# (skew symmetric matrix) of the rotation matrix R\r\n\r\nfunction MatrixLog3(R)\r\n    acosinput = (lAlgebra.tr(R) - 1) / 2\r\n    if acosinput >= 1\r\n        return zeros(3, 3)\r\n    else\r\n        theta = acos(acosinput)\r\n        return theta / 2 / sin(theta) * (R - R')\r\n    end\r\nend\r\n#****************************************************************#\r\n# Computes exponential coordinate ‘se3mat’\r\n# (twist matrix) of the rigid body transformation matrix T\r\nfunction MatrixLog6(T)\r\n    if( size(T)!=(4,4) )\r\n        println(\"!Warning! : Transformation matrix should be 4x4.\")\r\n        return\r\n    end\r\n    R = T[1:3,1:3]\r\n    t = T[1:3,4]\r\n    omg_h = MatrixLog3(R)\r\n    w = [omg_h[3,2];omg_h[1,3];omg_h[2,1]]\r\n    if omg_h == zeros(3, 3)\r\n        return vcat(hcat(zeros(3, 3), T[1:3, 4]), [0 0 0 0])\r\n    else\r\n        theta = acos((lAlgebra.tr(R) - 1) / 2)\r\n        return vcat(hcat(omg_h,\r\n                         (I - omg_h / 2 +\r\n                          (1 / theta - 1 / tan(theta / 2) / 2) *\r\n                          omg_h * omg_h / theta) * T[1:3, 4]),\r\n                    [0 0 0 0])\r\n    end\r\nend\r\n#****************************************************************#\r\n\r\n#****************************************************************#\r\n# VeysiADN 12 May 2021\r\n# Advanced Robotics Homework 5 Codes\r\n#****************************************************************#\r\nusing LinearAlgebra\r\n#****************************************************************#\r\n# Returns Adjoint matrix with given rigid body\r\n# transformation matrix g\r\nfunction Adjoint(g)\r\n\r\n    R=g[1:3,1:3];\r\n    p=g[1:3,4];\r\n    p_hat = [ 0       -p[3]     p[2];\r\n             p[3]       0      -p[1];\r\n            -p[2]      p[1]       0 ]\r\n\r\n    return [R zeros(3,3);p_hat*R R]\r\nend\r\n#****************************************************************#\r\n# VeysiADN 4 Apr 2021\r\n# Advanced Robotics Homework 3 Codes\r\n#****************************************************************#\r\nusing LinearAlgebra\r\n#****************************************************************#\r\n# Returns 3 x 3 rotation matrix representing\r\n# rotation about unit vector w by angle theta.\r\n# theta should be in radian\r\nfunction Rodrigues(w,theta)\r\n    if( length(w) != 3)\r\n        println(\"!Warning! : W matrix should have 3 elements.\")\r\n        return\r\n    end\r\n    if(size(w)==(1,3))\r\n        w=w';\r\n    end\r\n    w_hat = [0      -w[3]    w[2];\r\n             w[3]     0     -w[1];\r\n            -w[2]    w[1]      0];\r\n    rotation_matrix = cos(theta)*Matrix(1I,3,3) + sin(theta)*w_hat+(1-cos(theta))*w*w';\r\n    return rotation_matrix;\r\nend\r\n#****************************************************************#\r\n# Builds rigid transformation matrix T from given\r\n#rotation matrix R and translation t\r\nfunction RpToTrans(R,t)\r\n    if( size(R)!=(3,3) )\r\n        println(\"!Warning! : Rotation matrix should be 3x3.\")\r\n        return\r\n    end\r\n    if( length(t) != 3 )\r\n        println(\"!Warning! : Translation matrix should have 3 elements.\")\r\n        return\r\n    end\r\n    if(size(t)==(1,3))\r\n        t=t';\r\n    end\r\n    R_B_T = hcat(R,t) ;\r\n    R_B_T = vcat(R_B_T,[0 0 0 1]) ;\r\n    return R_B_T\r\nend\r\n#****************************************************************#\r\n#Extracts rotation matrix R and translation t from given /\r\n# rigid transformation matrix T\r\nfunction TransToRp(T)\r\n    if( size(T)!=(4,4) )\r\n        println(\"!Warning! : Transformation matrix should be 4x4.\")\r\n        return\r\n    end\r\n    R = T[1:3,1:3]\r\n    t = T[1:3,4]\r\n    return R,t;\r\nend\r\n#****************************************************************#\r\n# Inverts rigid transformation matrix T\r\nfunction TransInv(T)\r\n    if( size(T)!=(4,4) )\r\n        println(\"!Warning! : W matrix should be 4x4.\")\r\n        return\r\n    end\r\n    if( det(T)==0 )\r\n        println(\"!Warning! : Inverse doesn't exist (Determinant is equal to zero).\")\r\n        return\r\n    end\r\n    R,t = TransToRp(T);\r\n    r_inv =hcat(R',-(R'*t))\r\n    r_inv = vcat(r_inv,[0 0 0 1]);\r\n    return r_inv;\r\nend\r\n#****************************************************************#\r\n#  Starting from here  is homework 7.\r\n\"\"\"\r\n    Calculates Spatial geometric Jacobian Js, given 6 x n matrix\r\n    ‘Twists’ whose columns are Twist parameter of each joints\r\n    and n x 1 vector of joint angles\r\n\"\"\"\r\nfunction JacobianSpace(Twists, JointAngles)\r\n    T = I;\r\n    Js = Twists\r\n    for i = 2:length(JointAngles)\r\n        T *= MatrixExp6(VecTose3(Twists[:, i - 1] * JointAngles[i - 1]))\r\n        Js[:, i] = Adjoint(T) * Twists[:, i]\r\n    end\r\n    return Js\r\nend\r\n\"\"\"\r\nCalculates Forward Kinematics given initial configuration M,\r\n6 x n matrix ‘Twists’ whose columns are twist parameter\r\nof each joints, and n x 1 joint angles\r\n\"\"\"\r\nfunction FwdKin(M,Twists,JointAngles)\r\n    T=M\r\n    for i = length(JointAngles):-1:1\r\n        T = MatrixExp6(VecTose3(Twists[:,i]*JointAngles[i])) * T\r\n    end\r\n    return T\r\nend\r\n\"\"\"\r\nSolves Paden-Kahan subproblem 1\r\n\r\n\"\"\"\r\nfunction PadenKahanFirst(w, x, y)\r\n    p = x\r\n    q = y\r\n    u = p - (w'*p)*w;\r\n    v = q - (w'*q)*w;\r\n    theta = atan((w'*(cross(u,v)))/(u'*v))\r\n    return theta\r\nend\r\n\"\"\"\r\nSolves Paden-Kahan subproblem 2. th will be 2 x 2 matrix\r\ncontaining solution pair (th1, th2) each row\r\n\"\"\"\r\n\r\nfunction PadenKahanSecond(w1, w2, x, y)\r\n    p=x\r\n    q=y\r\n\r\n    A = [1 w1'*w2;\r\n        w1'*w2 1];\r\n    B=[w1'*q; w2'*p]\r\n    alfa,beta = A\\B\r\n\r\n    gamma_sq = ((norm(p)^2)-(alfa^2)-(beta^2)-(2*alfa*beta*(w1'*w2)))/((norm(cross(w1,w2)))^2)\r\n    gamma_1 = sqrt.(gamma_sq);\r\n    gamma_2 = -sqrt.(gamma_sq);\r\n    c_1 = alfa*w1+beta*w2+gamma_1*(cross(w1,w2));\r\n    c_2 = alfa*w1+beta*w2+gamma_2*(cross(w1,w2));\r\n    th_1 = PadenKahanFirst(w2,p,c_1)\r\n    th_2 = PadenKahanFirst(w2,p,c_2)\r\n    th_3 = PadenKahanFirst(-w1,q,c_1)\r\n    th_4 = PadenKahanFirst(-w1,q,c_2)\r\n    th = [th_1 th_3;th_4 th_2];\r\n    return th\r\nend\r\n", "meta": {"hexsha": "3caa9a32553bcabd41836ee8d19103fc6fb7bf98", "size": 10317, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HW7.jl", "max_stars_repo_name": "veysiadn/AdvancedRoboticsJulia", "max_stars_repo_head_hexsha": "0484999de1908b73fd19c7c78f5c8471a62610ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW7.jl", "max_issues_repo_name": "veysiadn/AdvancedRoboticsJulia", "max_issues_repo_head_hexsha": "0484999de1908b73fd19c7c78f5c8471a62610ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW7.jl", "max_forks_repo_name": "veysiadn/AdvancedRoboticsJulia", "max_forks_repo_head_hexsha": "0484999de1908b73fd19c7c78f5c8471a62610ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7446153846, "max_line_length": 95, "alphanum_fraction": 0.4694194049, "num_tokens": 3035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7603126088583294}}
{"text": "using LinearAlgebra\n\nexport Generic2DLattice\n\nabstract type Abstract2DLattice end \n\n\"\"\"\n\nStructure containing the real and the reciprical basis vectors of a surface\n\"\"\"\nstruct Generic2DLattice <: Abstract2DLattice\n    a1\n    a2\n    b1\n    b2\nend\n\n\"\"\"\n# Arguments\n* a1 first lattice vector\n* a2 second lattice vector\n\n# Example\n` Generic2DLattice([1,0],[1,0]) `\n\"\"\"\nfunction Generic2DLattice(a1, a2)\n    area = a2[2]*a1[1]-a2[1]*a1[2]\n    b1 = 2π * [ a2[2],-a2[1]] / area\n    b2 = 2π * [-a1[2], a1[1]] / area\n    Generic2DLattice(a1,a2,b1,b2)\nend\n\nstruct HexGrid <: Abstract2DLattice\n    a\n    l::Generic2DLattice\nend\n\nHexGrid(a) = HexGrid(a,Generic2DLattice([a,0],[cos(pi/180*120),sin(pi/180*120)].*a))\n\nfunction rotate_reciprocal(lattice::Generic2DLattice,direction)\n\tunitx = [lattice.b1 lattice.b2] * direction\n\tang = -atan(unitx[2],unitx[1])\n\tR = [cos(ang) -sin(ang)\n\t     sin(ang) cos(ang)]\n\tR*lattice.b1,R*lattice.b2\nend", "meta": {"hexsha": "ba6564bb4f10c6b585eb668f12abecdf452bef89", "size": 925, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lattice.jl", "max_stars_repo_name": "at677/HAS_lib", "max_stars_repo_head_hexsha": "26306e3bea5f822ca4d8e65dc88e2d5201243695", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lattice.jl", "max_issues_repo_name": "at677/HAS_lib", "max_issues_repo_head_hexsha": "26306e3bea5f822ca4d8e65dc88e2d5201243695", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-20T10:43:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-20T10:48:12.000Z", "max_forks_repo_path": "src/lattice.jl", "max_forks_repo_name": "at677/HAS_lib", "max_forks_repo_head_hexsha": "26306e3bea5f822ca4d8e65dc88e2d5201243695", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1086956522, "max_line_length": 84, "alphanum_fraction": 0.6767567568, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.8128673087708698, "lm_q1q2_score": 0.7603125987581199}}
{"text": "######### StanSample example  ###########\n\nusing StanSample\n\nbernoulli_model = \"\ndata { \n  int<lower=1> N; \n  int<lower=0,upper=1> y[N];\n} \nparameters {\n  real<lower=0,upper=1> theta;\n} \nmodel {\n  theta ~ beta(1,1);\n  y ~ bernoulli(theta);\n}\n\";\n\nbernoulli_data = Dict(\"N\" => 10, \"y\" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1])\n\n# Keep tmpdir identical to prevent re-compilation\nstanmodel = SampleModel(\n  \"bernoulli\", bernoulli_model;\n  method = StanSample.Sample(adapt=StanSample.Adapt(delta=0.85)))\n\nstan_sample(stanmodel, data=bernoulli_data, n_chains=6, diagnostics=true)\n\n# Fetch the same output in the `sdf` ChainDataFrame\nsdf = read_summary(stanmodel)\n  ", "meta": {"hexsha": "4c325ed9c574a7769cf98ed3b59a8a51f2bfe20a", "size": 652, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_basic_runs/test_bernoulli_dict.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StanSample.jl-c1514b29-d3a0-5178-b312-660c88baa699", "max_stars_repo_head_hexsha": "768894f98284a1840f01fd9c6c51c5247bae2ad5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_basic_runs/test_bernoulli_dict.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StanSample.jl-c1514b29-d3a0-5178-b312-660c88baa699", "max_issues_repo_head_hexsha": "768894f98284a1840f01fd9c6c51c5247bae2ad5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_basic_runs/test_bernoulli_dict.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StanSample.jl-c1514b29-d3a0-5178-b312-660c88baa699", "max_forks_repo_head_hexsha": "768894f98284a1840f01fd9c6c51c5247bae2ad5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7333333333, "max_line_length": 73, "alphanum_fraction": 0.6641104294, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870767, "lm_q2_score": 0.8031737892899221, "lm_q1q2_score": 0.7602816321138557}}
{"text": "function doubling(a::Array{T, 2}, b::Array{T, 2}, g::Array{T, 2}, tol::T, maxiters::S) where {T <: AbstractFloat, S <: Int}\n\n  retcode = 0\n  iters = 1\n  len = Inf\n\n  gn = similar(g)\n\n  while len > tol && iters <= maxiters\n    gn = g+a*g*b\n    len = maximum(abs,gn-g)\n    a = a*a\n    b = b*b\n    g = copy(gn)\n    iters += 1\n  end\n\n  if iters > maxiters\n    retcode = 1\n  end\n\n  return gn,retcode\n\nend\n", "meta": {"hexsha": "d6fceb38767522a8d12c476619907c97e44b9be7", "size": 400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/doubling.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SolveDSGE.jl-00bf1f32-23ad-54cc-bf6e-3216db8a43a2", "max_stars_repo_head_hexsha": "ab3d113fd08cb569b44798588f369f3f6c642168", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2015-09-20T07:02:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:38:12.000Z", "max_issues_repo_path": "src/doubling.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SolveDSGE.jl-00bf1f32-23ad-54cc-bf6e-3216db8a43a2", "max_issues_repo_head_hexsha": "ab3d113fd08cb569b44798588f369f3f6c642168", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 53, "max_issues_repo_issues_event_min_datetime": "2017-03-03T15:53:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:41:07.000Z", "max_forks_repo_path": "src/doubling.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SolveDSGE.jl-00bf1f32-23ad-54cc-bf6e-3216db8a43a2", "max_forks_repo_head_hexsha": "ab3d113fd08cb569b44798588f369f3f6c642168", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2016-01-27T16:29:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-03T23:53:53.000Z", "avg_line_length": 16.0, "max_line_length": 123, "alphanum_fraction": 0.545, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7602793360998648}}
{"text": "\"\"\"\nA simple optimal growth model, for testing the DiscreteDP class.\n\nFilename: finite_dp_og.jl\n\n\"\"\"\n\n\"\"\"\nSet up R, Q and beta, the three elements that define an instance of\nthe DiscreteDP object.\n\"\"\"\nmutable struct SimpleOG\n\t#-Paramters-#\n\tB::Int64\n\tM::Int64\n\talpha::Float64\n\tbeta::Float64\n\t#-Internal Variables-#\n\tn::Int64\n\tm::Int64\n\tR::Array{Float64}\n\tQ::Array{Float64}\n\n\tfunction SimpleOG(B::Int64, M::Int64, alpha::Float64, beta::Float64, u::Function)\n\t\tn = B + M + 1\n\t\tm = M + 1\n\t\tR = zeros(Float64, n, m)\n\t\tQ = zeros(Float64, n, m, n)\n\t\t#-Populate R-#\n\t\tpopulate_R!(n,m,R,u,alpha)\n\t\tpopulate_Q!(m,Q,B)\n\t\treturn new(B,M,alpha,beta,n,m,R,Q)\n\tend\nend\n\nSimpleOG() = SimpleOG(10,5,0.5,0.9,u)\nSimpleOG(B::Int64, M::Int64, alpha::Float64, beta::Float64) = SimpleOG(B,M,alpha,beta,u)\n\n#-Support Functions-#\n\nfunction u(c, alpha)\n    return c^alpha\nend\n\nfunction populate_R!(n,m,R,u,alpha)\n    for s in 1:n\n        for a in 1:m\n            if a <= s\n                R[s, a] = u(s-a,alpha)\n            else\n                R[s, a] = -Inf\n            end\n        end\n    end\nend\n\nfunction populate_Q!(m,Q,B)\n    for a in 1:m\n        Q[:, a, a:(a + B)] .= 1.0 / (B+1)\n    end\nend\n", "meta": {"hexsha": "2954df1c7e0c1481d558b273dfbed7ec1d93b7a6", "size": 1175, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/finite_dp_og_example.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/QuantEcon.jl-fcd29c91-0bd7-5a09-975d-7ac3f643a60c", "max_stars_repo_head_hexsha": "ff4697f2be73edbc905373fdf268056bdc93d129", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 455, "max_stars_repo_stars_event_min_datetime": "2015-01-16T18:10:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T20:08:45.000Z", "max_issues_repo_path": "examples/finite_dp_og_example.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/QuantEcon.jl-fcd29c91-0bd7-5a09-975d-7ac3f643a60c", "max_issues_repo_head_hexsha": "ff4697f2be73edbc905373fdf268056bdc93d129", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 236, "max_issues_repo_issues_event_min_datetime": "2015-01-26T20:56:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T15:19:56.000Z", "max_forks_repo_path": "examples/finite_dp_og_example.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/QuantEcon.jl-fcd29c91-0bd7-5a09-975d-7ac3f643a60c", "max_forks_repo_head_hexsha": "ff4697f2be73edbc905373fdf268056bdc93d129", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 364, "max_forks_repo_forks_event_min_datetime": "2015-01-15T18:04:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T21:24:53.000Z", "avg_line_length": 18.9516129032, "max_line_length": 88, "alphanum_fraction": 0.5889361702, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7602793271385745}}
{"text": "\"\"\"\n    chisquaretest(A, adjusted=false)\n\ncalculate chi-square statistic and the p-value of a two-way Row x Colums. `A` is a matrix return from `crossTable` (which conveniently includes row total and column total).\n\nThe following statistics are reported\n\n- Expectation values table\n- Chi-Square Test\n- Likelihood-ratio test\n- Continuity-Adjusted Chi-Square Test (if `adjusted=true`)\n- Mantel-Haenszel Chi-Square Test (not implemented)\n- Fisher’s Exact Test (not implemented)\n\n## Examples\n```julia\njulia> using Epi\n\njulia> gender = [\"Female\", \"Male\"][rand(1:2, 100)];\n\njulia> age = [\"0-5\", \"6-10\", \"11-15\"][rand(1:3, 100)];\n\njulia> tm_ = crossTable(age, gender);\n\njulia> chisquaretest(tm_)\nChi-square: 0.247 with 2 degrees of freedom\n\tp-value: 0.8837\nLikelihood-ratio Chi-square: 0.2466 with 2 degrees of freedom\n\tp-value: 0.8839\n===================================\nExpectation values table\nFrequency (expected value)\n\n-----------------------------------\n3×2 Named Array{Text{String},2}\nA ╲ B │       Male      Female\n──────┼───────────────────────\n11-15 │  16 (14.7)   14 (15.3)\n0-5   │ 15 (17.14)  20 (17.85)\n6-10  │ 18 (17.14)  17 (17.85)\n```\n\n\"\"\"\nfunction chisquaretest(A; adjusted=false, expect=true)\n\tnr, nc = (size(A).-1)\n\temat = Matrix{Float64}(undef, nr, nc)\n\tfor i in 1:nr, j in 1:nc\n\t\temat[i, j] = A[i, end] * A[end, j] / A[end, end]\n\tend\n\tcells = Array(A[1:nr, 1:nc]);\n\tkdf = prod(size(cells).-1)\n\tchi = sum((cells - emat).^2 .* (1 ./ emat))\n\tG2  = 2*sum(removeNaN(unlist(cells .* log.(cells .* (1 ./ emat) ))))  \n\tif adjusted \n\t\tAdj = sum( max.(0, abs.(cells - emat).-0.5) .^2 .* (1 ./ emat) )\n\tend\n\tif (any(cells[i]==0 for i in eachindex(cells))) \n\t\t@info \"Zero cells are omitted in calculating likelihood-ratio\" \n\tend\n\tprintln(\"Chi-square: \", trunc(chi, digits=4), \" with $kdf degrees of freedom\", \"\\n\\tp-value: \", trunc(ccdf(Chisq(kdf), chi), digits=4))\n\tif adjusted \n\t\tprintln(\"Continuity-Adjusted Chi-square: \", trunc(Adj, digits=4), \" with $kdf degrees of freedom\", \"\\n\\tp-value: \", trunc(ccdf(Chisq(kdf), Adj), digits=4))\n\tend\n\tprintln(\"Likelihood-ratio Chi-square: \", trunc(G2, digits=4), \" with $kdf degrees of freedom\", \"\\n\\tp-value: \", trunc(ccdf(Chisq(kdf), G2), digits=4))\n\tif expect\n\t\tprintln(\"\\n\", \"=\"^35)\n\t\tprintln(\"Expectation values table\")\n\t\tprintln(\"Frequency (expected value)\")\n\t\tprintln(\"\\n\", \"-\"^35)\n\t\tNamedArray(Text.(string.(cells, \" (\", trunc.(emat, digits=2), \")\")), \n\t\t           (names(A)[1][1:end-1], names(A)[2][1:end-1]))\n\tend\nend\n", "meta": {"hexsha": "c583c620704ac491ab69eb5e7a01c6bb72279fb3", "size": 2475, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chisquare.jl", "max_stars_repo_name": "kklot/Epi.jl", "max_stars_repo_head_hexsha": "13498e5d98d028b318c1bd0ce7540afef250521c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-16T17:33:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T17:33:19.000Z", "max_issues_repo_path": "src/chisquare.jl", "max_issues_repo_name": "kklot/Epi.jl", "max_issues_repo_head_hexsha": "13498e5d98d028b318c1bd0ce7540afef250521c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chisquare.jl", "max_forks_repo_name": "kklot/Epi.jl", "max_forks_repo_head_hexsha": "13498e5d98d028b318c1bd0ce7540afef250521c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4459459459, "max_line_length": 172, "alphanum_fraction": 0.6206060606, "num_tokens": 821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7602793248904985}}
{"text": "#=\ndists.jl - Prior distributions and their moments (Author: Julian Johs)\nneed to calculate mean and standard deviation of used distributions to use them in Dynare\n\nbeta_moments calculates mean and standard deviation of Beta distribution\ngiving plot as argument plots the distribution\n\nbeta_solve uses beta_moments to calculate parameters α and β for given\nmean and standard deviation - this should give you a feeling for what Dynare does\nbeta_solve takes 2 real numbers as inputs\n\nthe same applies for the functions for the Gamma distribution\n=#\nusing Distributions, StatsPlots, NLsolve\n\nfunction beta_moments(params::Tuple{Real, Real}; plot=nothing)#; plot::Bool=false\n    α = params[1]\n    β = params[2]\n    dist = Beta(α, β)\n    mu = mean(dist)\n    sig = std(dist)\n    if plot !== nothing\n        display(plot(dist)) # you can comment this out\n     end\n    return (mu, sig)\nend\nbeta_moments(α::Real, β::Real; args...) = beta_moments((α, β); args...)\nbeta_moments(params::AbstractArray{<:Real, 1}; args...) = beta_moments((params[1], params[2]); args...)\n\nfunction beta_solve(m::Real, s::Real)\n    solver = nlsolve(params -> beta_moments(params) .- (m, s), [1.0, 1.0])\n    return solver.zero\nend\nbeta_solve(params::AbstractArray{<:Real, 1}) = beta_solve(params[1], params[2])\nbeta_solve(params::Tuple{Vararg{<:Real}}) = beta_solve(params[1], params[2])\n\n\nfunction gamma_moments(params::Tuple{Real, Real}; plot=nothing)\n    α = params[1]\n    β = params[2]\n    dist = Gamma(α, β)\n    mu = mean(dist)\n    sig = std(dist)\n    if plot !== nothing\n        display(plot(dist)) # you can comment this out\n    end\n    return (mu, sig)\nend\ngamma_moments(α::Real, β::Real; args...) = gamma_moments((α, β); args...)\ngamma_moments(params::AbstractArray{<:Real, 1}; args...) = gamma_moments((params[1], params[2]); args...)\n\n\nfunction gamma_solve(m::Real, s::Real)\n    solver = nlsolve(params -> gamma_moments(params) .- (m, s), [1.0, 1.0])\n    return solver.zero\nend\ngamma_solve(params::AbstractArray{<:Real, 1}) = gamma_solve(params[1], params[2])\ngamma_solve(params::Tuple{Vararg{<:Real}}) =    gamma_solve(params[1], params[2])\n\nfunction invgamma_moments(params::Tuple{Real, Real}; plot=nothing)\n    α = params[1]\n    β = params[2]\n    dist = InverseGamma(α, β)\n    mu = mean(dist)\n    sig = std(dist)\n    if plot !== nothing\n        display(plot(dist)) # you can comment this out\n    end\n    return (mu, sig)\nend\ninvgamma_moments(α::Real, β::Real; args...) = invgamma_moments((α, β); args...)\ninvgamma_moments(params::AbstractArray{<:Real, 1}; args...) = invgamma_moments((params[1], params[2]); args...)\n\nfunction invgamma_solve(m::Real, s::Real; ftol=1e-12)\n    solver = nlsolve(params -> invgamma_moments(params) .- (m, s), [2.1, 0.2])\n    return solver.zero\nend\ninvgamma_solve(params::AbstractArray{<:Real, 1}) = invgamma_solve(params[1], params[2])\ninvgamma_solve(params::Tuple{Vararg{<:Real}}) =    invgamma_solve(params[1], params[2])\n", "meta": {"hexsha": "7eee2037c136f38d488066726b353e677d2e4a47", "size": 2936, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dists.jl", "max_stars_repo_name": "julianjohs/dynare_aux_tools", "max_stars_repo_head_hexsha": "505e8ad209d23651f8b55451e584e4492950b227", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dists.jl", "max_issues_repo_name": "julianjohs/dynare_aux_tools", "max_issues_repo_head_hexsha": "505e8ad209d23651f8b55451e584e4492950b227", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dists.jl", "max_forks_repo_name": "julianjohs/dynare_aux_tools", "max_forks_repo_head_hexsha": "505e8ad209d23651f8b55451e584e4492950b227", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7, "max_line_length": 111, "alphanum_fraction": 0.681880109, "num_tokens": 885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825847, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.760279324605612}}
{"text": "@doc \"\"\"\nGenerate some data using\ny = mat*x + n\nwhere x = vector of interest\nmat = some transformation matrix\nn = noise\nThis assumes p(n) ~ iid Normal(0, sigma^2)\n\"\"\" ->\nfunction generate_data(x::Array{Float64, 1}, mat::Array{Float64, 2}, sigma=1.0)\n\t@assert length(x) == size(mat)[2]\n\treturn mat*x + sigma*randn(size(mat)[1])\nend\n\n", "meta": {"hexsha": "2d37b41f9835902978ea0bf2951d8ccb46ee8976", "size": 332, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "generate_data.jl", "max_stars_repo_name": "eggplantbren/MeanImage", "max_stars_repo_head_hexsha": "30777dcef531ba8b1cfe3a57b54c8bf15d688b5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "generate_data.jl", "max_issues_repo_name": "eggplantbren/MeanImage", "max_issues_repo_head_hexsha": "30777dcef531ba8b1cfe3a57b54c8bf15d688b5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "generate_data.jl", "max_forks_repo_name": "eggplantbren/MeanImage", "max_forks_repo_head_hexsha": "30777dcef531ba8b1cfe3a57b54c8bf15d688b5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7142857143, "max_line_length": 79, "alphanum_fraction": 0.6746987952, "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7602793176075112}}
{"text": "function evaluate(a::STaylor1{N,T}, dx::T) where {N, T<:Number}\r\n    @inbounds suma = a[N-1]\r\n    @inbounds for k in (N-1):-1:0\r\n        suma = suma*dx + a[k]\r\n    end\r\n    suma\r\nend\r\n#=\r\nfunction evaluate(a::STaylor1{N,T}, dx::S) where {N, T<:Number, S<:Number}\r\n    suma = a[N-1]*one(dx)\r\n    @inbounds for k in (N-1):-1:0\r\n        suma = suma*dx + a[k]\r\n    end\r\n    suma\r\nend\r\n=#\r\nevaluate(a::STaylor1{N,T}) where {N, T<:Number} = a[0]\r\n\r\nevaluate(x::Union{Array{STaylor1{N,T}}, SubArray{STaylor1{N,T}}}, δt::S) where\r\n        {N, T<:Number, S<:Number} = evaluate.(x, δt)\r\nevaluate(a::Union{Array{STaylor1{N,T}}, SubArray{STaylor1{N,T}}}) where\r\n        {N, T<:Number} = evaluate.(a, zero(T))\r\n\r\n(p::STaylor1)(x) = evaluate(p, x)\r\n(p::STaylor1)() = evaluate(p)\r\n\r\n(p::Array{STaylor1{N,T}})(x) where {N,T<:Number} = evaluate.(p, x)\r\n(p::SubArray{STaylor1{N,T}})(x) where {N,T<:Number} = evaluate.(p, x)\r\n(p::Array{STaylor1{N,T}})() where {N,T<:Number} = evaluate.(p)\r\n(p::SubArray{STaylor1{N,T}})() where {N,T<:Number} = evaluate.(p)\r\n", "meta": {"hexsha": "57092f98c73ddcdb1f0305f984da19330b388886", "size": 1038, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/evaluate.jl", "max_stars_repo_name": "mewilhel/StaticTaylorSeries.jl", "max_stars_repo_head_hexsha": "962b75010152ce076e8f5831279edc783a5a8361", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/evaluate.jl", "max_issues_repo_name": "mewilhel/StaticTaylorSeries.jl", "max_issues_repo_head_hexsha": "962b75010152ce076e8f5831279edc783a5a8361", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/evaluate.jl", "max_forks_repo_name": "mewilhel/StaticTaylorSeries.jl", "max_forks_repo_head_hexsha": "962b75010152ce076e8f5831279edc783a5a8361", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4838709677, "max_line_length": 79, "alphanum_fraction": 0.5674373796, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7602335852775032}}
{"text": "immutable Tradeoff{T} <: Model\n    a::T\n    k::T\n    γx::T\n    γt::T\nend\n\nBase.show(io::IO, ::Type{Tradeoff}) = print(io, \"Heuristic Tradeoff\")\n\nfunction Base.show(io::IO, m::Tradeoff)\n    @printf(\n        io,\n        \"Heuristic Tradeoff (a = %.3f, k = %.3f, γx = %.3f, γt = %.3f)\",\n        m.a,\n        m.k,\n        m.γx,\n        m.γt,\n    )\nend\n\nfunction initial_parameters(::Type{Tradeoff})\n    return Float64[log(1.0), log(1.0), log(1.0), log(1.0)]\nend\n\ncanonical_parameters(m::Tradeoff) = (m.a, m.k, m.γx, m.γt)\n\nfunction Tradeoff(parameters::Vector)\n    a = exp(parameters[1])\n    k = exp(parameters[2])\n    γx = exp(parameters[3])\n    γt = exp(parameters[4])\n    return Tradeoff(a, k, γx, γt)\nend\n\n@inline ϕ(χ, γ) = log(1 + γ * χ) / γ\n\n@inline ϕ′(χ, γ) = ((γ * χ) / (1 + γ * χ) - log(1 + γ * χ)) / γ^2\n\n@inline function predict(m::Tradeoff, x2::Real, t2::Real, x1::Real, t1::Real)\n    a, k, γx, γt = m.a, m.k, m.γx, m.γt\n    δϕx = ϕ(x2, γx) - ϕ(x1, γx)\n    δϕt = ϕ(t2, γt) - ϕ(t1, γt)\n    z = a * (δϕx - k * δϕt)\n    p = invlogit(z)\n    return p\nend\n\n@inline function gradient_component(\n    m::Tradeoff,\n    x2::Real,\n    t2::Real,\n    x1::Real,\n    t1::Real,\n)\n    a, k, γx, γt = m.a, m.k, m.γx, m.γt\n    δϕx = ϕ(x2, γx) - ϕ(x1, γx)\n    δϕt = ϕ(t2, γt) - ϕ(t1, γt)\n    δϕ′x = ϕ′(x2, γx) - ϕ′(x1, γx)\n    δϕ′t = ϕ′(t2, γt) - ϕ′(t1, γt)\n    gr = (\n        (δϕx - k * δϕt) * a,\n        -a * δϕt * k,\n        a * δϕ′x * γx,\n        a * -k * δϕ′t * γt,\n    )\n    return gr\nend\n", "meta": {"hexsha": "1435cfb9be2ca046dd25b49252137fbcaaa65c5a", "size": 1481, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/heuristics/tradeoff.jl", "max_stars_repo_name": "johnmyleswhite/IntertemporalChoiceHeuristics.jl", "max_stars_repo_head_hexsha": "6562fb1740a5e7af67b3a427a32acfd473a7e53f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-02T21:33:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-02T21:33:51.000Z", "max_issues_repo_path": "src/models/heuristics/tradeoff.jl", "max_issues_repo_name": "johnmyleswhite/IntertemporalChoiceHeuristics.jl", "max_issues_repo_head_hexsha": "6562fb1740a5e7af67b3a427a32acfd473a7e53f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/heuristics/tradeoff.jl", "max_forks_repo_name": "johnmyleswhite/IntertemporalChoiceHeuristics.jl", "max_forks_repo_head_hexsha": "6562fb1740a5e7af67b3a427a32acfd473a7e53f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7794117647, "max_line_length": 77, "alphanum_fraction": 0.4929101958, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587142, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7602213555709906}}
{"text": "using Plots\n\nf(x) = sin(x)\n\nfunction trapezoidal_rule(a, b, n)\n    h = (b - a) / n\n    res = 0.0\n    for i in 1:n\n        if (i==0 || i==n)\n            res += f(a+i*h)\n        else\n            res += 2 * f(a+i*h)\n        end\n    end\n\n    res*h/2\nend\n\nprintln(\"Analytical=\", 2)\nprintln(\"Numerical=\", trapezoidal_rule(0, pi, 100))", "meta": {"hexsha": "a377a7560eb7d16eb0f21b1db68c083f95c0fa2e", "size": 328, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "calculus/trapezoidal_rule.jl", "max_stars_repo_name": "nocotan/numerical_calculus.jl", "max_stars_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-07T06:26:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T06:21:01.000Z", "max_issues_repo_path": "calculus/trapezoidal_rule.jl", "max_issues_repo_name": "nocotan/numerical_calculus.jl", "max_issues_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-01-10T08:22:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-08T13:31:00.000Z", "max_forks_repo_path": "calculus/trapezoidal_rule.jl", "max_forks_repo_name": "nocotan/numerical_calculus.jl", "max_forks_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-10T05:59:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T13:22:34.000Z", "avg_line_length": 16.4, "max_line_length": 51, "alphanum_fraction": 0.4725609756, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897509188345, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.76022135473823}}
{"text": "#testing for julia functions :)\n\nusing Statistics\nusing LinearAlgebra\n#using InvertedIndices\n#operations:\n#const LiefiesMatrix = Union{Matrix{Missing}, Matrix{<:Real}}\nLiefiesMatrix{T <: Union{Missing, Real}} = AbstractMatrix{T}\n#function f=some_function(x::LiefiesMatrix) :D\n\n\n# function closure(data::Union{Array{Union{Float64,Missing},2},Array{Union{Int64, Missing},2},Vector{Float64},Vector{Int64}}) #Union{Vector{Regex}, NTuple{N, Regex}}\n#::LiefiesMatrix) #Union{Vector{Regex}, NTuple{N, Regex}}\nfunction closure(data::T) where T\n    cvec = Array{Union{Missing, Float64}}(undef, size(data)...)\n    for i in 1:size(data,1)\n      cvec[i,:] = data[i,:] ./ sum(skipmissing(data[i,:])) #work around for sum not accepting skipmissing with dims argument\n    end\n    return cvec\nend\n\nfunction center(data::T) where T #inherit type T from data :D\n    #data must be compositions!\n    gvec = Matrix{Union{Missing, Float64}}(undef, 1, size(data,2))\n    data = closure(data) #just in case\n    data = BigFloat.(data)\n    for j in 1:size(gvec,2) #by columns\n      gvec[j] = prod(skipmissing((data[:,j]))) ^ (1/size(collect(skipmissing(data[:,j])),1)) #work around for sum not accepting skipmissing with dims argument\n    end\n    gvec=closure(gvec)\n    return gvec\nend\n\n\nfunction ait_var(data::T) where T\n    cen = center(data)\n    avar = zeros(Float64, size(data,2), size(data,2))\n    #avar = Matrix{Float64}(undef, size(data,2), size(data,2))\n    #avar = Matrix{Union{Missing, Float64}}(undef, size(data,2), size(data,2))\n    for i=1:size(data,2)\n        for j=i:size(data,2)\n            n=min(length(collect(skipmissing(data[:,i]))),length(collect(skipmissing(data[:,j]))))\n            avar[i,j]=(1/(n-1))*sum(skipmissing((log.(data[:,i]./data[:,j]) .- log(cen[i]/cen[j])).^2))\n        end\n    end\n    #avar = Symmetric(avar) #to make symmetric :)\n    return avar\nend\n\nfunction geo(x)\n    geo_mean = prod(x) .^ (1 ./ length(x))\n    return geo_mean\nend\n\nfunction ait_inner(x,y)\n    ai=sum( log.(x ./ geo(x)) .* log.(y ./ geo(y))   )\n    return ai\n\n    # ai=0.0        #alternative calculation:\n    # for i=1:length(x)\n    #     ai = ai + sum((log.(x[i] ./ x) .* (log.(y[i] ./ y))))\n    # end\n    # ai = 1/(2*length(x)) * ai\n    #return ai\nend\n\nfunction ait_norm(x)\n    an=0.0\n    for i=1:length(x)\n        an= an + sum((log.(x[i] ./ x) .^2))\n    end\n    an = sqrt(1/(2*length(x)) * an)\n    return an\nend\n\nfunction square_ait_norm(x)\n    an=0.0\n    for i=1:length(x)\n        an= an + sum((log.(x[i] ./ x) .^2))\n    end\n    an = (1/length(x)) * 1/(2*length(x)) * an\n    return an\nend\n\nfunction ait_dist(x,y)\n    if length(x) == length(y)\n        ad = 0.0\n        for i=1:length(x)\n            ad = ad + sum((log.(x[i] ./ x) .- log.(y[i] ./ y)).^2)\n        end\n        ad = sqrt(1/(2*length(x)) * ad)\n        return ad\n    else\n        println(\"x and y must be the same length\")\n    end\nend\n\nfunction perturb(x,y)\n    p=closure(x) .* closure(y) #works even if x is mulitple rows!\n    p=closure(p)\n    return p\nend\n\nfunction perturb_diff(x,y)\n    p=closure(x) .* inverse(y) #works even if x is mulitple rows!\n    p=closure(p)\n    return p\nend\n\nfunction power(x,a)\n    p=closure(x) .^ a\n    p=closure(p)\n    return p\nend\n\nfunction inverse(x)\n    ix = closure(1 ./ x)\n    return ix\nend\n\nfunction clr(data)\n    cvec = Matrix{Union{Missing, Float64}}(undef, size(data))\n    for i=1:size(data,1) #by rows\n        gmean = prod(skipmissing(data[i,:])) ^ (1/size(collect(skipmissing(data[i,:])),1)) #work around for sum not accepting skipmissing with dims argument\n        cvec[i,:]=log.(data[i,:]./gmean)\n    end\n    return cvec\nend\n\nfunction ilr(x,sbp::Matrix{<:Real})\n\n    bal=zeros(size(sbp)) #create orthonormal basis based on partition\n    for i=1:size(sbp,1) #number of rows of sbp\n        rr=findall(sbp[i,:] .== 1)\n        ss=findall(sbp[i,:] .== -1)\n        r=length(rr)\n        s=length(ss)\n        bal[i,rr] .= (1/r).*sqrt((r*s)/(r+s))\n        bal[i,ss] .= -(1/s).*sqrt((r*s)/(r+s))\n    end\n\n    ilr_x=log.(x)*bal'\n    return ilr_x, bal\nend\n\nfunction invilr(ilr_x,bal)\n    #balance refers to contrast matrix (it is not the sbp!)\n    x=invclr(ilr_x*bal);\n    return x\nend\n\nfunction invclr(x_clr)\n    x=closure(exp.(x_clr));\n    return x\nend\n\nfunction amalga(x,col1,col2)\n\n    A = zeros(size(x,2),3)\n    A[col1,1] = 1\n    A[col2,2] = 1\n    A[setdiff(collect(1:size(x,2)),[col1;col2]),3] .= 1\n\n    y = x * A\n    return y, A\n\nend\n\n\nfunction bayes_multi_zero_replace(c,method,prior)\n    #c is a count vector!\n    #tj is the prior estimate\n    #s is the strength parameter\n\n    samples, D = size(c) #number of rows then columns\n    n=sum(c,dims=2)\n\n    if prior == \"uniform\"\n        t=1/D .* ones(size(c))\n    elseif prior == \"modified\"\n        println(\"Assuming prior based on ratios found within dataset\")\n        t=zeros(size(c))\n        for q=1:samples\n            global t\n            to_use = setdiff(1:samples, q)\n            t[q,:]=sum(c[to_use,:],dims=1)\n        end\n        t=t./sum(t,dims=2)\n    end\n\n    #common imprecise Dirichlet models considered here: Bayes-Laplace and Square-root\n    if method == \"Bayes-Laplace\"\n        s = D * ones(samples,1)\n    elseif method == \"Square-root\"\n        s = sqrt.(sum(c,dims=2)) #total trials per sample!\n    elseif method == \"Geometric\"\n        #if these are very small numbers, can result in a zero multiplicative product\n        println(\"accounting for very small values here...\")\n        temp = 10 .^ ((1/D) .* sum(log10.(t),dims=2))\n        s = 1 ./ temp    \n        #s = 1 ./ prod(closure(t),dims=2).^(1/D)\n    elseif method == \"Jeffreys\"\n        s = D/2 * ones(samples,1)\n    elseif method == \"Perks\"\n        s = ones(samples,1)\n    else\n        println(\"Not a recognized method; please choose from Bayes-Laplace, Square-root, Geomteric, Jeffreys, or Perks\")\n    end\n\n    println(method)\n    #@show s\n    #multiplicative part: only adjust rows for which there is a zero\n    #fieldnames()...\n    x=closure(c)\n    r=deepcopy(x)\n    global r, x, t, s\n    for i=1:samples\n        if any(x[i,:] .== 0) #row contains zeros\n            zeroind=findall(x[i,:] .== 0) #work on the columns\n            nonzero=findall(x[i,:] .!= 0)\n            r[i,zeroind] = t[i,zeroind] .* s[i]./(n[i] .+ s[i])\n            r[i,nonzero] = x[i,nonzero] .* (1 - sum(r[i,zeroind]))\n        end\n    end\n\n    return r\n    # x=closure(c)\n    # r=x\n    # zeroind=findall(x .== 0)\n    # nonzero=findall(x .!= 0)\n    # colind=map(x->x.I[2], zeroind)\n    # rowind=map(x->x.I[1], zeroind)\n    #\n    # r[zeroind] = t[zeroind] .* s[colind]./(n[colind] .+ s[colind])\n    # r[nonzero] = x[nonzero] .* (1 - sum(r[zeroind]))\n\nend\n\n#To compare with R package- that one seems to be doing strange thins with BDL values\n# g=Matrix{Union{Missing, Float64}}(undef, 1, size(y,2))\n# for j in 1:size(y,2) #by columns\n#   g[j] = prod(skipmissing(y[:,j])) ^ (1/size(collect(skipmissing(y[:,j])),1)) #work around for sum not accepting skipmissing with dims argument\n# end\n#\n# #(0.3 * x).^(1/2) = nrm\n# g0=sum(g[1,[1,2,3]])\n# #sum(g[1,[1,2,4]]) + q = nrm\n# #nrm = y[1,4] + g0\n#\n# r_cen=[0.5116703 0.2558351 0.1193897 0.1131049]\n# mm=((g[1]./r_cen[1] - g0).^2)./y[1,4]\n", "meta": {"hexsha": "a33b26a2a9e8a5b236a63b9cff798a727c470699", "size": 7157, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "coda_ops_transforms.jl", "max_stars_repo_name": "khuntercevera/coda_utilities", "max_stars_repo_head_hexsha": "759cdba32e01dc5aa4ef145e716f99dace8bcfa1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-04T02:29:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-04T02:30:16.000Z", "max_issues_repo_path": "coda_ops_transforms.jl", "max_issues_repo_name": "khuntercevera/coda_utilities", "max_issues_repo_head_hexsha": "759cdba32e01dc5aa4ef145e716f99dace8bcfa1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coda_ops_transforms.jl", "max_forks_repo_name": "khuntercevera/coda_utilities", "max_forks_repo_head_hexsha": "759cdba32e01dc5aa4ef145e716f99dace8bcfa1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4007936508, "max_line_length": 165, "alphanum_fraction": 0.5858599972, "num_tokens": 2367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7602123353767775}}
{"text": "using Revise\nusing Random\nusing SpecialFunctions\nusing PyCall\nusing PyPlot\nusing StatsPlots\n\nfunction mySliceSampler(pdf_log, x_0, w, m, N, burnIn = 1000)\n    # REQUIRES MODULES:\n    # Random\n    #\n    # INPUT:\n    # pdf_log --> log-pdf of the target distribution (a function)\n    # x_init --> inital vector of x (dimension 1xD), where D dimension of pdf\n    # w --> typical slice size, for a window (dimension 1xD)\n    # m --> integer limiting the slice size to m*w\n    # N --> number of sample points\n    # burnIn --> number of burn-in samples (optional, results will be discarded)\n    #\n    # OUTPUT:\n    # x_s --> sampled x values (NxD), only keep values after full permutations along dimensions\n    # pdflog_x_s --> log-pdf of sampled values\n\n    D = length(x_0)  # the dimension of the distribution (nr of coordinates)\n    x_s = Array{Float64}(undef,N,D)   # Samples (NxD), preallocate array, with undefined values\n    pdflog_x_s = Array{Float64}(undef,N)   # (unnormalised) log-prob of sampled points (Nx1)\n                                           # for reducing evaluations\n    pdflog_x_1 = 0.0;\n\n    # to be able to input scalars:\n    if typeof(x_0) == Float64\n        x_0 = [x_0]\n    end\n\n\n    for ii in 1:(N+burnIn)\n        # Update the new x progressively for each dimension:\n        L   = 1*x_0  # R and L need to be of same dimension, because we apply the pdf upon those!\n        R   = 1*x_0\n        x_1 = 1*x_0  # \"1*\" needed, otherwise x_0 suddendly takes mysterious values\n        for d in randperm(D)\n            ### 1) Make the Slice\n            # random \"vertical\" position\n            if (ii == 1)\n                #vertical = rand() * pdf_log(x_0) # in normal space\n                z = pdf_log(x_0) + log(rand()) # in log-space\n            else\n                # saving evaluations, pdflog_x_1 was updated for current permutation in the end\n                z = pdflog_x_1 + log(rand())\n            end\n\n            ### 2) Make the window, \"Stepping-out\" alogrithm\n            # Randomly place a window, containing x_0:\n            L[d] = x_0[d] - rand() * w[d]\n            R[d] = L[d] + w[d]\n\n            # Randomly share the max window size among left/right:\n            J = floor(m*rand());\n            K = (m-1) - J;\n\n            # Extend window to the left, until outside slice or allowance seizes:\n            while ((J > 0) && (z < pdf_log(L)))\n                #println(\"Lefting\")\n                L[d] -= w[d]\n                J -= 1\n            end\n\n            # Extend window to the right, until outside slice or allowance seizes:\n            while ((K > 0) && (z < pdf_log(R)))\n                #println(\"Righting\")\n                R[d] += w[d]\n                K -= 1\n            end\n\n            ### 3) Sample from window\n            # finding an allowable point:\n            while true\n                x_1[d] = L[d] + rand() * (R[d] - L[d])\n\n                # this + breaking out of loop reduces the amount of log-pdf evaluations:\n                pdflog_x_1 = pdf_log(x_1)\n\n                if (pdflog_x_1 >= z)     # new value found\n                    x_0[d] = x_1[d]     # update value for this dimension\n                    break\n                # Value was not within slice, shrink the interval:\n                elseif (x_1[d] < x_0[d])\n                    L[d] = x_1[d]\n                elseif (x_1[d] > x_0[d])\n                    R[d] = x_1[d]\n                else\n                    throw(ErrorException(\"Error during shrinking the interval\"))\n                end\n            end\n\n        end # end of permutating through dimensions\n\n        ### 4) Update the chain:\n        # Just overwrite the burnIn by using modular arithmetic:\n        i = 1 + (ii-1)%N    # gives 1,2,3,...N,1,2,3,...,(N+burnIn)\n        x_s[i,:] = x_1    # sample point, after one round of permutations\n        pdflog_x_s[i] = pdflog_x_1 # now contains log_pdf of all new coordinates of new point, since has been updated at each permutation\n        # note that x_0 has been updated during the permutations\n\n    end\n\n    return x_s, pdflog_x_s\nend\n\n#%%\n################################################################\n\nfunction log_beta(θ,a::Any,b::Any)\n    #using SpecialFunctions\n    θ = θ[1]\n    if 0 < θ < 1\n        # Numerator\n        num = log(θ)*(a-1) + log(1-θ)*(b-1)\n        # The denominator (Beta-function) can be integrated or made up of Gamma-functions\n        # Since we only treat integer values here, Γ(a) = (a-1)!\n        #den = log(factorial(a-1) * factorial(b-1) / factorial(a+b-1))\n        den = log(SpecialFunctions.beta(a,b))\n        return num - den\n    else\n        return -Inf\n    end\nend\n\n################################################################\n\n# Log-Bernoulli PDF:\nfunction log_bernoulli_pdf(θ,y)\n    if 0 < θ < 1 && (y==0 || y==1)    # Only admissible values\n        return y * log(θ) + (1-y) * log(1-θ)\n    else\n        return -Inf\n    end\nend\n\n# Log-Likelihood fct of a (series of) coin tosses with bias:\nfunction log_likelihood_fct(θ, y)\n    # Make array s.t. multiple theta values can be input:\n    #likelihood = Array{Float64}(undef,length(θ))\n    # Do that for every theta value requested:\n    #for ii in 1:length(θ)\n    #    # Elementwise application of the log_beronoulli_pdf over outcome vector y, then SUM together:\n    #    likelihood[ii] = sum(log_bernoulli_pdf.(θ[ii],y))\n    #end\n\n    # Un array-ise the output:\n    #if length(θ) == 1\n    #    likelihood = likelihood[1]\n    #end\n\n    θ = θ[1]\n    likelihood = sum(log_bernoulli_pdf.(θ,y))\n\n    return likelihood\nend\n\n#%%\n################################################################\n\n# Chain inputs:\nN = 10^6\nx_start = 0.5;\nw = .5;  # typical window width\nm = 100; # maximum number of window widths\n\n# Final posteriors in one array:\nposteriors = Array{Float64}(undef,N,3);\n\n#%%\n# First Column of Figure 6.4\na = 100\nb = 100\ny = [ones(1,17) zeros(1,3)]\n\nlog_prior(θ) = log_beta(θ,a,b)\nlog_lklhd(θ) = log_likelihood_fct(θ,y)\nlog_posterior(θ) = log_lklhd(θ) + log_prior(θ)\n\n# Need to use \"StatsPlots\" or \"Plots\" histogram to add the density curve, PyPlot won't work\nchain, pdf = mySliceSampler(log_prior,x_start,w,m,N);\nhistogram(chain, bins=100, normalize=:pdf, label=\"prior\")   # Comes from StatsPlots now\ndensity!(chain,linewidth=3,label=\"prior\")\n\nchain, pdf = mySliceSampler(log_lklhd,x_start,w,m,N)\nhistogram!(chain, bins=100, normalize=:pdf,label=\"likelihood\")\ndensity!(chain,linewidth=3,label=\"likelihood\")\n\nchain, pdf = mySliceSampler(log_posterior,x_start,w,m,N)\nhistogram!(chain, bins=100, normalize=:pdf,label=\"posterior\")\ndensity!(chain,linewidth=3,label=\"posterior\")\n\nposteriors[:,1] = chain # save the posterior\n\nPlots.savefig(\"A4-A-C1_Slice.pdf\")\n\n#%%\n# Second Column\na = 18.25\nb = 6.75\ny = [ones(1,17) zeros(1,3)]\n\nlog_prior(θ) = log_beta(θ,a,b)\nlog_lklhd(θ) = log_likelihood_fct(θ,y)\nlog_posterior(θ) = log_lklhd(θ) + log_prior(θ)\n\nchain, pdf = mySliceSampler(log_prior,x_start,w,m,N);\nhistogram(chain, bins=100, normalize=:pdf, label=\"prior\")   # Comes from StatsPlots now\ndensity!(chain,linewidth=3,label=\"prior\")\n\nchain, pdf = mySliceSampler(log_lklhd,x_start,w,m,N)\nhistogram!(chain, bins=100, normalize=:pdf,label=\"likelihood\")\ndensity!(chain,linewidth=3,label=\"likelihood\")\n\nchain, pdf = mySliceSampler(log_posterior,x_start,w,m,N)\nhistogram!(chain, bins=100, normalize=:pdf,label=\"posterior\")\ndensity!(chain,linewidth=3,label=\"posterior\")\n\nposteriors[:,2] = chain # save the posterior\n\nPlots.savefig(\"A4-A-C2_Slice.pdf\")\n\n#%%\n# Third Column\na = 1\nb = 1\ny = [ones(1,17) zeros(1,3)]\n\nlog_prior(θ) = log_beta(θ,a,b)\nlog_lklhd(θ) = log_likelihood_fct(θ,y)\nlog_posterior(θ) = log_lklhd(θ) + log_prior(θ)\n\nchain, pdf = mySliceSampler(log_prior,x_start,w,m,N);\nhistogram(chain, bins=100, normalize=:pdf, label=\"prior\")   # Comes from StatsPlots now\ndensity!(chain,linewidth=3,label=\"prior\")\n\nchain, pdf = mySliceSampler(log_lklhd,x_start,w,m,N)\nhistogram!(chain, bins=100, normalize=:pdf,label=\"likelihood\")\ndensity!(chain,linewidth=3,label=\"likelihood\")\n\nchain, pdf = mySliceSampler(log_posterior,x_start,w,m,N)\nhistogram!(chain, bins=100, normalize=:pdf,label=\"posterior\")\ndensity!(chain,linewidth=3,label=\"posterior\")\n\nposteriors[:,3] = chain # save the posterior\n\nPlots.savefig(\"A4-A-C3_Slice.pdf\")\n\n#%%\n\ndensity(posteriors, label=[\"a=100, b=100\",\"a=18.25, b=6.75\",\"a=1, b=1\"])\nPlots.savefig(\"A4-A-all_Slice.pdf\")\n", "meta": {"hexsha": "ffa440c64d290204336321ee34ae51db2dde2626", "size": 8348, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "A4/A4-TaskA.jl", "max_stars_repo_name": "vis-florum/Applied-Bayesian-Data-Analysis", "max_stars_repo_head_hexsha": "6d460443269d920ea61859df9434938139245c2b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A4/A4-TaskA.jl", "max_issues_repo_name": "vis-florum/Applied-Bayesian-Data-Analysis", "max_issues_repo_head_hexsha": "6d460443269d920ea61859df9434938139245c2b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A4/A4-TaskA.jl", "max_forks_repo_name": "vis-florum/Applied-Bayesian-Data-Analysis", "max_forks_repo_head_hexsha": "6d460443269d920ea61859df9434938139245c2b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.609375, "max_line_length": 137, "alphanum_fraction": 0.5955917585, "num_tokens": 2392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7602123273896617}}
{"text": "@doc raw\"\"\"\n    K, γ, info = glover_mcfarlane(G::AbstractStateSpace, γ = 1.1; W1=1, W2=1)\n\nDesign a controller for `G` that maximizes the stability margin ϵ = 1/γ with normalized coprime factor uncertainty using the method of Glover and McFarlane\n```\nγ = 1/ϵ = ||[K;I] inv(I-G*K)*inv(M)||∞\nG = inv(M + ΔM)*(N + ΔN)\n```\nγ is given as a relative factor above γmin and must be greater than 1, i.e., if γ = 1.1, the controller will be designed for γ = 1.1*γmin.\n\nWe want γmin (which is always ≥ 1) as small as possible, and we usually require that γmin is less than 4, corresponding to 25% allowed coprime uncertainty.\n\nPerformance modeling is incorporated in the design by calling `glover_mcfarlane` on the shaped system `Gs = W2*G*W1` and then forming the controller as `K = W1*Ks*W2`. Using this formulation, traditional loop shaping can be done on `Gs = W2*G*W1`. The plant shaping is handled internally if keyword arguments `W1, W2` are used and the returned controller is already scaled. In this case, `Gs` and `Ks` are included in the `info` named tuple for inspection. \n\nSee also [`glover_mcfarlane_2dof`](@ref) to design a feedforward filter as well.\n\n# Example:\nExample 9.3 from the reference below.\n```julia\nusing RobustAndOptimalControl, ControlSystems, Plots, Test\nG = tf(200, [10, 1])*tf(1, [0.05, 1])^2     |> ss\nGd = tf(100, [10, 1])                       |> ss\nW1 = tf([1, 2], [1, 1e-6])                  |> ss\nK, γ, info = glover_mcfarlane(G, 1.1; W1)\n@test info.γmin ≈ 2.34 atol=0.005\nGcl = extended_gangoffour(G, K) # Form closed-loop system\n\nbodeplot([G, info.Gs, G*K], lab=[\"G\" \"\" \"G scaled\" \"\" \"Loop transfer\"]) |> display\nbodeplot(Gcl, lab=[\"S\" \"KS\" \"PS\" \"T\"], plotphase=false) |> display # Plot gang of four\n\nplot( step(Gd*feedback(1, info.Gs), 3), lab=\"Initial controller\")\nplot!(step(Gd*feedback(1, G*K), 3), lab=\"Robustified\") |> display\n\nnyquistplot([info.Gs, G*K], ylims=(-2,1), xlims=(-2, 1),\n    Ms_circles = 1.5,\n    lab = [\"Initial controller\" \"Robustified\"],\n    title = \"Loop transfers with and without robustified controller\"\n    ) |> display\n```\n\nRef: Sec 9.4.1 of Skogestad, \"Multivariable Feedback Control: Analysis and Design\"\n\n# Extended help\n\nSkogestad gives the following general advice:\n1. Scale the plant outputs and inputs. This is very important for most design\n    procedures and is sometimes forgotten. In general, scaling improves the\n    conditioning of the design problem, it enables meaningful analysis to be made\n    of the robustness properties of the feedback system in the frequency domain,\n    and for loop-shaping it can simplify the selection of weights. There are a variety\n    of methods available including normalization with respect to the magnitude of\n    the maximum or average value of the signal in question. If one is to go straight to a design the following variation has\n    proved useful in practice:\n    (a) The outputs are scaled such that equal magnitudes of cross-coupling into each\n        of the outputs is equally undesirable.\n    (b) Each input is scaled by a given percentage (say 10%) of its expected range\n        of operation. That is, the inputs are scaled to reflect the relative actuator\n        capabilities. An example of this type of scaling is given in the aero-engine\n        case study of Chapter 12.\n2. Order the inputs and outputs so that the plant is as diagonal as possible. The\n    relative gain array [`rga`](@ref) can be useful here. The purpose of this pseudo-diagonalization\n    is to ease the design of the pre- and post-compensators which, for simplicity, will\n    be chosen to be diagonal.\n\n    Next, we discuss the selection of weights to obtain the shaped plant $G_s = W_2 G W_1$\n    where $W_1 = W_p W_a W_g$\n3. Select the elements of diagonal pre- and post-compensators $W_p$ and $W_2$ so that\n    the singular values of $W_2 G W_p$ are desirable. This would normally mean high\n    gain at low frequencies, roll-off rates of approximately 20 dB/decade (a slope of\n    about 1) at the desired bandwidth(s), with higher rates at high frequencies. Some\n    trial and error is involved here. $W_2$ is usually chosen as a constant, reflecting the\n    relative importance of the outputs to be controlled and the other measurements\n    being fed back to the controller. For example, if there are feedback measurements\n    of two outputs to be controlled and a velocity signal, then $W_2$ might be chosen\n    to be `diag([1, 1, 0.1])`, where 0.1 is in the velocity signal channel. $W_p$ contains the\n    dynamic shaping. Integral action, for low frequency performance; phase-advance\n    for reducing the roll-off rates at crossover, and phase-lag to increase the roll-off\n    rates at high frequencies should all be placed in $W_p$ if desired. The weights should\n    be chosen so that no unstable hidden modes are created in $G_s$.\n5. Optional: Introduce an additional gain matrix $W_g$ cascaded with $W_a$ to provide\n    control over actuator usage. $W_g$ is diagonal and is adjusted so that actuator rate\n    limits are not exceeded for reference demands and typical disturbances on the\n    scaled plant outputs. This requires some trial and error.\n    \n6. Robustly stabilize the shaped plant $G_s = W_2 G W_1$ , where $W_1 = W_p W_a W_g$,\n    using `glover_mcfarlane`. First, the maximum stability\n    margin $ϵ_{max} = 1/γ_{min}$ is calculated. If the margin is too small, $ϵmax < 0.25$, then go back and modify the weights. Otherwise, a γ-suboptimal controller is synthesized. There is usually no advantage to be gained by using the optimal controller. When $ϵ_{max}$ > 0.25\n    (respectively $γ_{min}$ < 4) the design is usually successful. In this case, at least\n    25% coprime factor uncertainty is allowed, and we also find that the shape of the\n    open-loop singular values will not have changed much after robust stabilization.\n    A small value of ϵmax indicates that the chosen singular value loop-shapes are\n    incompatible with robust stability requirements. That the loop-shapes do not\n    change much following robust stabilization if γ is small (ϵ large), is justified\n    theoretically in McFarlane and Glover (1990).\n\n7. Analyze the design and if all the specifications are not met make further\n    modifications to the weights.\n8. Implement the controller. The configuration shown in below has been found\n    useful when compared with the conventional set up. This is because\n    the references do not directly excite the dynamics of $K$, which can result in large amounts of overshoot (classical derivative kick). The constant prefilter ensures a steady-state gain of 1 between r and y, assuming integral action in $W_1$ or $G$ (note, the K returned by this function has opposite sign compared to that of Skogestad, so we use negative feedback here).\n\nAnti-windup can be added to $W_1$ but putting $W_1$ on Hanus form after the synthesis, see [`hanus`](@ref).\n\n```\n       ┌─────────┐      ┌────────┐      ┌────────┐\n    r  │         │    us│        │  u   │        │  y\n   ───►│(K*W2)(0)├──+──►│   W1   ├─────►│   G    ├────┬──►\n       │         │  │-  │        │      │        │    │\n       └─────────┘  │   └────────┘      └────────┘    │\n                    │                                 │\n                    │                                 │\n                    │   ┌────────┐      ┌────────┐    │\n                    │   │        │  ys  │        │    │\n                    └───┤   K    │◄─────┤   W2   │◄───┘\n                        │        │      │        │\n                        └────────┘      └────────┘\n```\nKeywords: nfcsyn, coprimeunc\n\"\"\"\nfunction glover_mcfarlane(G::AbstractStateSpace{Continuous}, γ = 1.1; W1=1, W2=1)\n    γ > 1 || throw(ArgumentError(\"γ must be greater than 1\"))\n    Gs = W2*G*W1\n    A,B,C,D = ssdata(Gs)\n\n    R = I + D*D'\n    S = I + D'D\n    Sl = lu(S)\n    # arec(A, B, R, Q, S) solves A'X + XA - (XB+S)R^(-1)(B'X+S') + Q = 0\n    \n    Ā = A - B*(S\\D'C)\n    Z,_ = MatrixEquations.arec(Ā', C', R, B*(Sl\\B'))\n    X,_ = MatrixEquations.arec(Ā, B, S, C'*(R\\C))\n\n    γmin = sqrt(1 + ρ(X*Z))\n\n    γ *= γmin\n\n    L = (1-γ^2)*I + X*Z\n    F = -(Sl\\(D'C + B'X))\n    BK = γ^2*(L'\\Z)*C'\n    AK = A + B*F + BK*(C + D*F)\n    CK = B'X\n    DK = -D'\n    Ks = -ss(AK, BK, CK, DK)\n    Gcl = extended_gangoffour(Gs, Ks)\n    imargin, ω = hinfnorm2(Gcl)\n    K = W1*Ks*W2\n    Gcl = extended_gangoffour(G, K)\n    K, γ, (; Gcl, margin = inv(imargin), ω, γmin, Ks, Gs, Z, X)\nend\n\n\"\"\"\n    K, γ, info = glover_mcfarlane(G::AbstractStateSpace{<:Discrete}, γ = 1.1; W1=1, W2=1, strictly_proper=false)\n\nFor discrete systems, the `info` tuple contains also feedback gains `F, L` and observer gain `Hkf` such that the controller on observer form is given by\n```math\nx′ = Ax + Bu + H_{kf}*(Cx - y)\\\\\\\\\nu = Fx + L*(Cx - y)\n```\nNote, this controller is *not* strictly proper, i.e., it has a non-zero D matrix.\nThe controller can be transformed to observer form for the scaled plant (`info.Gs`)\nby `Ko = observer_controller(info)`, in which case the following holds `G*K == info.Gs*Ko` (realizations are different).\n\nIf `strictly_proper = true`, the returned controller `K` will have `D == 0`.\nThis can be advantageous in implementations where computational delays are present. In this case, `info.L == 0` as well.\n\nRef discrete version: Iglesias, \"The Strictly Proper Discrete-Time Controller for the Normalized Left-Coprime Factorization Robust Stabilization Problem\"\n\"\"\"\nfunction glover_mcfarlane(G::AbstractStateSpace{<:Discrete}, γ = 1.1; W1=1, W2=1, strictly_proper=false)\n    γ > 1 || throw(ArgumentError(\"γ must be greater than 1\"))\n    Gs = W2*G*W1\n    A,B,C,D = ssdata(Gs)\n    iszero(D) || throw(ArgumentError(\"System must be strictly proper (D must be 0)\"))\n\n    X,_,Flq = MatrixEquations.ared(A, B, I, C'C)\n    Z,_ = MatrixEquations.ared(A', C', I, B*B')\n    Q1 = I + C*Z*C'\n\n    if strictly_proper\n        T = Q1 # They appear to be the same\n        T12 = sqrt(T)\n        X12 = sqrt(X)\n        M1 = T12\\C*Z*A'X12\n        Q2 = I + X12*Z*X12\n\n        QM = [\n            sqrt(Q1 + 1/4 * M1*M1') -1/2*M1\n            -1/2*M1'       sqrt(Q2 + 1/4 * M1'*M1)\n        ]\n        γmin = ρ(QM)\n        γ *= γmin\n\n\n        W = (γ^2 - 1)*I - Z*X\n        XW = X/W\n        Hkf = -A*Z*C'/Q1\n\n        # Flq is the feedback gain from the ARE above, ref Rowe and Maciejowski, \"Tuning MPC using H∞ Loop Shaping\" between eq 36-37.\n        # Flq = -B'X*((I + B*B'X)\\A) # NOTE: Flq might be required for inverse optimal control\n        F = -γ^2*Flq/W # Original paper\n        # F = -γ^2*B'XW*((I + γ^2*B*B'XW)\\A) # Merl paper\n        # @show [F; Flq; F0]\n        Ak = A + B*F + Hkf*C\n        # NOTE: It's unclear what the best realization is. Both papers talk about a \"dual\" realization, but they appear to disagree on the formulation, and none of the expressions for the Q-matrices, in the Merl paper or the Maciejowski paper, do not lead to the same caluclated feedback gain. I think they might have left out a similarity transform on some matrices. The equations used here are thus not any of the dual forms, even if those appear to be recommended.\n\n        L = 0\n        Ck = F\n        Bk = -Hkf\n        Dk = 0\n    else\n\n        γmin = sqrt(1 + ρ(X*Z))\n        γ *= γmin\n\n        W = (γ^2 - 1)*I - Z*X\n        Hkf = -A*Z*C'/Q1\n        Akf = A+Hkf*C\n\n        XW = X/W\n        hest = lu(I + γ^2*B*B'XW)\n        γ2B = γ^2*B'\n        arne = γ2B*XW\n        Ak = hest\\Akf\n        Ck = arne*Ak\n        Bk = hest\\Hkf\n        Dk = arne*Bk\n\n        F0 = -γ2B*XW/hest\n        F = F0*A\n        L = F0*Hkf\n    end\n\n    \n    Ks = -ss(Ak, Bk, Ck, Dk, G.timeevol)\n    Gcl = extended_gangoffour(Gs, Ks)\n    imargin, ω = hinfnorm2(Gcl)\n    K = W1*Ks*W2\n    Gcl = extended_gangoffour(G, K)\n    K, γ, (; Gcl, margin = inv(imargin), ω, γmin, Ks, Gs, Z, X, F, L, Hkf, W)\nend\n\n\"\"\"\n    observer_controller(glover_mcfarlane_info::NamedTuple)\n\nReturn a controller on observer form (observer of the scaled plant `info.Gs`).\nThe observer controller has input vector `y`.\n\nRef: eq (2.5)-(2.6) of Iglesias, \"The Strictly Proper Discrete-Time Controller for the Normalized Left-Coprime Factorization Robust Stabilization Problem\"\n\"\"\"\nfunction ControlSystems.observer_controller(info::NamedTuple)\n    isdiscrete(info.Gs) || throw(ArgumentError(\"Observer controller can only be generated for Glover McFarlane designs on discrete systems.\"))\n    A,B,C,D = ssdata(info.Gs)\n    iszero(D) || throw(ArgumentError(\"observer_controller does not support non-zero D matrix\")) # not sure if this is a strict limitation or the paper author simplified.\n    H, L, F = info.Hkf, info.L, info.F\n    Ao = A + B*(F + L*C) + H*C\n    Bo = (B*L+H)\n    Co = F + L*C\n    Do = L\n    ss(Ao, Bo, Co, Do, info.Gs.timeevol)\nend\n\n\"\"\"\n    observer_predictor(glover_mcfarlane_info::NamedTuple)\n\nReturn a predictor for the scaled plant `info.Gs`.\nThe observer predictor has input vector `[u; y]`.\n\nRef: eq (2.5)-(2.6) of Iglesias, \"The Strictly Proper Discrete-Time Controller for the Normalized Left-Coprime Factorization Robust Stabilization Problem\"\n\"\"\"\nfunction ControlSystems.observer_predictor(info::NamedTuple)\n    isdiscrete(info.Gs) || throw(ArgumentError(\"Observer predictor can only be generated for Glover McFarlane designs on discrete systems.\"))\n    A,B,C,D = ssdata(info.Gs)\n    H, L, F = info.Hkf, info.L, info.F\n    Ao = A + H*C\n    Bo = [B-H*D -H]\n    Co = C\n    Do = [D zeros(size(D,1), size(H, 2))]\n    ss(Ao, Bo, Co, Do, info.Gs.timeevol)\nend\n\n\"\"\"\n    K, γ, info = glover_mcfarlane_2dof(G::AbstractStateSpace{Continuous}, Tref::AbstractStateSpace{Continuous}, γ = 1.1, ρ = 1.1;\n    W1 = 1, Wo = I, match_dc = true, kwargs...)\n\nJoint design of feedback and feedforward compensators\n```math\nK = \\\\left\\\\[K_1 & K_2\\\\right\\\\]\n```\n```\n   ┌──────┐   ┌──────┐        ┌──────┐    ┌─────┐\nr  │      │   │      │        │      │    │     │\n──►│  Wi  ├──►│  K1  ├───+───►│  W1  ├───►│  G  ├─┐y\n   │      │   │      │   │    │      │    │     │ │\n   └──────┘   └──────┘   │    └──────┘    └─────┘ │\n                         │                        │\n                         │    ┌──────┐            │\n                         │    │      │            │\n                         └────┤  K2  ◄────────────┘\n                              │      │\n                              └──────┘\n```\nWhere the returned controller `K` takes the measurement vector `[r; y]` (positive feedback), \ni.e., it includes all blocks `Wi, K1, K2, W1`.\nIf `match_dc = true`, `Wi` is automatically computed to make sure the static gain matches `Tref` exactly, otherwise `Wi` is set to `I`.\nThe `info` named tuple contains the feedforward filter for inspection (`info.K1 = K1*Wi`).\n\n\n# Arguments:\n- `G`: Plant model\n- `Tref`: Reference model\n- `γ`: Relative γ\n- `ρ`: Design parameter, typically 1 < ρ < 3. Increase to emphasize model matching at the expense of robustness.\n- `W1`: Pre-compensator for loop shaping.\n- `Wo`: Output selction matrix. If there are more measurements than controlled variables, this matrix let's you select which measurements are to be controlled. \n- `kwargs`: Are sent to [`hinfsynthesize`](@ref).\n\nRef: Sec. 9.4.3 of Skogestad, \"Multivariable Feedback Control: Analysis and Design\".\nThe reference contains valuable pointers regarding gain-scheduling implementation of the designed controller as an observer with feedback from estimated states.\nIn order to get anti-windup protection when `W1` contains an integrator,\ntransform `W1` to self-conditioned Hanus form (using [`hanus`](@ref)) and implement the controller like this\n```julia\nW1h = hanus(W1)             # Perform outside loop\n\n# Each iteration\nus = filter(Ks, [r; y])     # filter inputs through info.Ks (filter is a fictive function that applies the transfer function)\nu  = filter(W1h, [us; ua])  # filter us and u-actual (after input saturation) through W1h\nua = clamp(u, lower, upper) # Calculate ua for next iteration as the saturated value of u\n```\n\n\n# Example:\n```julia\nP = tf([1, 5], [1, 2, 10]) # Plant\nW1 = tf(1,[1, 0]) |> ss    # Loop shaping controller\n\nTref = tf(1, [1, 1]) |> ss # Reference model\n\nK1dof, γ1, info1 = glover_mcfarlane(ss(P), 1.1; W1)\nK2dof, γ2, info2 = glover_mcfarlane_2dof(ss(P), Tref, 1.1, 1.1; W1)\n\nG1 = feedback(P*K1dof)\nG2 = info2.Gcl\n\nbodeplot(info2.K1, w, lab=\"Feedforward filter\")\nplot([step(G1, 15), step(G2, 15), step(Tref, 15)], lab=[\"1-DOF\" \"2-DOF\" \"Tref\"])\n```\n\"\"\"\nfunction glover_mcfarlane_2dof(G::AbstractStateSpace{Continuous}, Tref::AbstractStateSpace{Continuous}, γ = 1.1, ρ = 1.1; W1=1, Wo = I, match_dc = true, kwargs...)\n    γ > 1 || throw(ArgumentError(\"γ must be greater than 1\"))\n    ρ > 1 || throw(ArgumentError(\"ρ must be greater than 1\"))\n    Gs = G*W1\n    As,Bs,Cs,Ds = ssdata(Gs)\n    Ar,Br,Cr,Dr = ssdata(Tref)\n    nr,nr = size(Ar)\n    lr,mr = size(Dr)\n    ns,ns = size(As)\n    ls,ms = size(Ds)\n    Rs = I + Ds*Ds'\n    sRs = sqrt(Rs) # Example in Skogestad uses matlab sqrt which is elementwise\n    Ss = lu!(I + Ds'Ds)\n    A1 = (As - Bs*(Ss\\Ds'Cs))\n    R1 = Cs'*(Rs\\Cs)\n    Q1 = Bs*(Ss\\Bs')\n    Zs, _ = MatrixEquations.arec(A1', R1, Q1)\n\n    A = cat(As, Ar, dims=(1,2))\n    B1 = [\n        zeros(ns,mr) ((Bs*Ds')+(Zs*Cs'))/sRs\n        Br zeros(nr,ls)\n    ]\n    B2 = [Bs; zeros(nr,ms)]\n    C1 = [zeros(ms,ns+nr); Cs zeros(ls,nr); ρ*Wo*Cs -ρ^2*Cr]\n    C2 = [zeros(mr,ns+nr); Cs zeros(ls,nr)]\n    D11 = [zeros(ms,mr+ls); zeros(ls,mr) sRs;-ρ^2*Dr ρ*Wo*sRs]\n    D12 = [I(ms);Ds;ρ*Ds]\n    D21 = [ρ*I(mr) zeros(mr,ls);zeros(ls,mr) sRs]\n    D22 = [zeros(mr,ms); Ds]\n    P = ss(A, B1, B2, C1, C2, D11, D12, D21, D22)\n    _, Ks, γopt = hinfsynthesize(P, γrel = γ; kwargs...)\n    \n    u1 = 1:ms\n    K1 = Ks[:, u1]\n    if match_dc\n        K2 = Ks[:, ms+1:end]\n        sens = output_sensitivity(Gs, -K2)*Gs*K1 # eq. 9.89\n        Wi = (Wo*dcgain(sens, 1e-6))\\dcgain(Tref)\n        K1 = K1*Wi\n        Ks.B[:,u1] .= K1.B\n        Ks.D[:,u1] .= K2.D\n    else\n        Wi = I\n    end\n    K = W1*Ks\n    Gcl = feedback(G*K, ss(1), W1=1:ms, U1=ms+1:2ms, pos_feedback=true)\n    info = (; Gcl, Ks, Gs, Wi, K1)\n    K, γopt, info\nend\n\n\n\n\"Spectral radius\"\nfunction ρ(X)\n    e = eigvals(X)\n    abs(e[end])\nend\n\n\n\"\"\"\n    Wh = hanus(W)\n\nReturn `Wh` on Hanus form. `Wh` has twice the number of inputs, where the second half of the inputs are \"actual inputs\", e.g., potentially saturated. This is used to endow `W` with anti-windup protection.\n`W` must have an invertable `D` matrix and be minimum phase.\n\nRef: Sec 9.4.5 of Skogestad, \"Multivariable Feedback Control: Analysis and Design\"\n\"\"\"\nfunction hanus(W)\n    A,B,C,D = ssdata(W)\n    nu = W.nu\n    BD = B/D\n    A2 = A - BD*C\n    B2 = [0*I(nu) BD]\n    D2 = [D 0*I(nu)]\n    ss(A2, B2, C, D2)\nend\n\n\"\"\"\n    extended_gangoffour(P, C)\n\nReturns a single statespace system that maps \n- `w1` reference or measurement noise\n- `w2` load disturbance\nto\n- `z1` control error\n- `z2` control input\n```\n      z1          z2\n      ▲  ┌─────┐  ▲      ┌─────┐\n      │  │     │  │      │     │\nw1──+─┴─►│  C  ├──┴───+─►│  P  ├─┐\n    │    │     │      │  │     │ │\n    │    └─────┘      │  └─────┘ │\n    │                 w2         │\n    └────────────────────────────┘\n```\n\nThe returned system has the transfer-function matrix\n```math\n\\\\begin{bmatrix}\nI \\\\\\\\ C\n\\\\end{bmatrix} (I + PC)^{-1} \\\\begin{bmatrix}\nI & P\n\\\\end{bmatrix}\n```\n\nThe gang of four can be plotted like so\n```julia\nGcl = extended_gangoffour(G, C) # Form closed-loop system\nbodeplot(Gcl, lab=[\"S\" \"CS\" \"PS\" \"T\"], plotphase=false) |> display # Plot gang of four\n```\nNote, the last output of Gcl is the negative of the `CS` and `PS` transfer functions from `gangoffour2`.\nSee [`glover_mcfarlane`](@ref) for an extended example. See also [`ncfmargin`](@ref).\n\"\"\"\nfunction extended_gangoffour(P, C)\n    ny,nu = size(P)\n    S = feedback(ss(I(ny+nu), P.timeevol), [0*I(ny) P; -C 0*I(nu)], pos_feedback=true)\n    Gcl = S + cat(0*I(ny), -I(nu), dims=(1,2))\n    Gcl\nend\n\n\"\"\"\n    m, ω = ncfmargin(P, K)\n\nNormalized coprime factor margin, defined has the inverse H∞ norm of\n```math\n\\\\begin{bmatrix}\nI \\\\\\\\ K\n\\\\end{bmatrix} (I + PK)^{-1} \\\\begin{bmatrix}\nI & P\n\\\\end{bmatrix}\n```\nA margin ≥ 0.25-0.3 is a reasonable for robustness. \n\nIf controller `K` stabilizes `P` with margin `m`, then `K` will also stabilize `P̃` if `nugap(P, P̃) < m`.\n\nSee also [`extended_gangoffour`](@ref), [`diskmargin`](@ref).\n\"\"\"\nfunction ncfmargin(P, K)\n    Gcl = extended_gangoffour(P, K)\n    im, w = hinfnorm2(Gcl)\n    inv(im), w\nend", "meta": {"hexsha": "7a8b09b36a79231a96965e50fc6cd3d7a194a481", "size": 20359, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/glover_mcfarlane.jl", "max_stars_repo_name": "ven-k/RobustAndOptimalControl.jl", "max_stars_repo_head_hexsha": "fdc9ec8e13a95be903357c51359216511d5e03ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/glover_mcfarlane.jl", "max_issues_repo_name": "ven-k/RobustAndOptimalControl.jl", "max_issues_repo_head_hexsha": "fdc9ec8e13a95be903357c51359216511d5e03ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/glover_mcfarlane.jl", "max_forks_repo_name": "ven-k/RobustAndOptimalControl.jl", "max_forks_repo_head_hexsha": "fdc9ec8e13a95be903357c51359216511d5e03ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4643584521, "max_line_length": 467, "alphanum_fraction": 0.6141264306, "num_tokens": 6591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7602123257035168}}
{"text": "\n#function blkd(A :: Array,B :: Array)\n#\t# block diagonal matrix of A and B\n#\tal = size(A,1)\n#\tac = size(A,2)\n#\tbl = size(B,1)\n#\tbc = size(B,2)\n#\tC = zeros(al+bl, ac + bc)\n#\tC[1:al, 1:ac] = A\n#\tC[al+1:end, ac+1:end] = B\n#\tC\n#end\nfunction eig(p :: Phs)\n\t# computes the eigenvalues and eigenvectors of a linear PHS\n\t#  (which haves a Q matrix!)\n\t#\n\t#\tconstrained (G != 0) cases can be addressed using\n\t#  generalized eigenvalues\n\t#\n\t#\n\t#  TODO: eigenvalues around a linearized condition:\n\t#       just need to compute the Hamiltonian Hessian at a given point!\n\t#       For e.g.: hess = ForwardDiff.hessian(p.Hamiltonian)\n\t#                 Q = hess(x)\n\t#               --> this can be useful for validating our nonlinear system!\n\t# \n\n\tif isdefined(p, :Q)\n\t\tif isdefined(p,:G)\n\t\t\tnconst = size(p.G,2)\n\t\t\tI = eye(size(p.J,1))\n\t\t\tz = zeros(nconst,nconst)\n\t\t\tE = blkdiag(I,z)\n\t\t\tA = [p.J*p.Q p.G;\n\t\t\t     p.G'*p.Q p.G_D]\n\t\t\te = eigfact(A,E)\n\t\t\tind = sortperm(imag(e.values))\n\t\t\treturn e.values[ind], e.vectors[ind,ind]\n\t\telse\n\t\t\ta,v = eig(p.J*p.Q)\n\t\t\tind = sortperm(imag(a))\n\t\t\treturn a[ind], v[:,ind]\n\t\tend\n\telse\n\t\tfprintln(\"Undefined Q matrix (nonlinear system?)!\")\n\t\treturn\n\tend\nend\n\nfunction eigdamp(p :: Phs)\n\t# computes the frequency and damping of PHS with damping\n\t#  (which haves a Q matrix!)\n\t#\n\t#\tconstrained (G != 0) cases can be addressed using\n\t#  generalized eigenvalues\n\t#\n\n\tif isdefined(p, :Q)\n\t\tif isdefined(p,:G)\n\t\t\tnconst = size(p.G,2)\n\t\t\tI = eye(size(p.J,1))\n\t\t\tz = zeros(nconst,nconst)\n\t\t\tE = blkdiag(I,z)\n\t\t\tA = [(p.J-p.R)*p.Q p.G;\n\t\t\t     p.G'*p.Q p.G_D]\n\t\t\te = eigfact(A,E)\n\t\t\tind = sortperm(imag(e.values))\n\t\t\treturn e.values[ind], e.vectors[ind,ind]\n\t\telse\n\t\t\ta,v = eig((p.J-p.R)*p.Q)\n\t\t\tind = sortperm(imag(a))\n\t\t\treturn a[ind], v[:,ind]\n\t\tend\n\telse\n\t\tfprintln(\"Undefined Q matrix (nonlinear system?)!\")\n\t\treturn\n\tend\nend\n\nfunction damp(p :: Phs)\n\ta,v = eigdamp(p)\n\treturn [abs(a) -cos(angle(a))]\nend\nfunction frequencies(a :: Array)\n\t\timag(a[imag(a).>=0])\nend\n\nfunction frequencies(ph :: Phs)\n\ta,v = eig(ph)\n\treturn frequencies(a)\nend", "meta": {"hexsha": "0663e5f96e95c0fdc9665403797d224a82bcee90", "size": 2057, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/eigenphs.jl", "max_stars_repo_name": "flavioluiz/PortHamiltonian", "max_stars_repo_head_hexsha": "8dc9e517292a95b4ae04ab15e8fbde30f0349caf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-08T05:39:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-08T05:39:52.000Z", "max_issues_repo_path": "src/eigenphs.jl", "max_issues_repo_name": "flavioluiz/PortHamiltonian", "max_issues_repo_head_hexsha": "8dc9e517292a95b4ae04ab15e8fbde30f0349caf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eigenphs.jl", "max_forks_repo_name": "flavioluiz/PortHamiltonian", "max_forks_repo_head_hexsha": "8dc9e517292a95b4ae04ab15e8fbde30f0349caf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6043956044, "max_line_length": 76, "alphanum_fraction": 0.6042780749, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.7602123204675764}}
{"text": "using Revise\nusing Random\nusing SpecialFunctions\nusing PyCall\nusing PyPlot\nusing StatsPlots\n\nfunction mySliceSampler(pdf_log, x_0, w, m, N, burnIn = 1000)\n    # REQUIRES MODULES:\n    # Random\n    #\n    # INPUT:\n    # pdf_log --> log-pdf of the target distribution (a function)\n    # x_init --> inital vector of x (dimension 1xD), where D dimension of pdf\n    # w --> typical slice size, for a window (dimension 1xD)\n    # m --> integer limiting the slice size to m*w\n    # N --> number of sample points\n    # burnIn --> number of burn-in samples (optional, results will be discarded)\n    #\n    # OUTPUT:\n    # x_s --> sampled x values (NxD), only keep values after full permutations along dimensions\n    # pdflog_x_s --> log-pdf of sampled values\n\n    D = length(x_0)  # the dimension of the distribution (nr of coordinates)\n    x_s = Array{Float64}(undef,N,D)   # Samples (NxD), preallocate array, with undefined values\n    pdflog_x_s = Array{Float64}(undef,N)   # (unnormalised) log-prob of sampled points (Nx1)\n                                           # for reducing evaluations\n    pdflog_x_1 = 0.0;\n\n    # to be able to input scalars:\n    if typeof(x_0) == Float64\n        x_0 = [x_0]\n    end\n\n\n    for ii in 1:(N+burnIn)\n        # Update the new x progressively for each dimension:\n        L   = 1*x_0  # R and L need to be of same dimension, because we apply the pdf upon those!\n        R   = 1*x_0\n        x_1 = 1*x_0  # \"1*\" needed, otherwise x_0 suddendly takes mysterious values\n        for d in randperm(D)\n            ### 1) Make the Slice\n            # random \"vertical\" position\n            if (ii == 1)\n                #vertical = rand() * pdf_log(x_0) # in normal space\n                z = pdf_log(x_0) + log(rand()) # in log-space\n            else\n                # saving evaluations, pdflog_x_1 was updated for current permutation in the end\n                z = pdflog_x_1 + log(rand())\n            end\n\n            ### 2) Make the window, \"Stepping-out\" alogrithm\n            # Randomly place a window, containing x_0:\n            L[d] = x_0[d] - rand() * w[d]\n            R[d] = L[d] + w[d]\n\n            # Randomly share the max window size among left/right:\n            J = floor(m*rand());\n            K = (m-1) - J;\n\n            # Extend window to the left, until outside slice or allowance seizes:\n            while ((J > 0) && (z < pdf_log(L)))\n                #println(\"Lefting\")\n                L[d] -= w[d]\n                J -= 1\n            end\n\n            # Extend window to the right, until outside slice or allowance seizes:\n            while ((K > 0) && (z < pdf_log(R)))\n                #println(\"Righting\")\n                R[d] += w[d]\n                K -= 1\n            end\n\n            ### 3) Sample from window\n            # finding an allowable point:\n            while true\n                x_1[d] = L[d] + rand() * (R[d] - L[d])\n\n                # this + breaking out of loop reduces the amount of log-pdf evaluations:\n                pdflog_x_1 = pdf_log(x_1)\n\n                if (pdflog_x_1 >= z)     # new value found\n                    x_0[d] = x_1[d]     # update value for this dimension\n                    break\n                # Value was not within slice, shrink the interval:\n                elseif (x_1[d] < x_0[d])\n                    L[d] = x_1[d]\n                elseif (x_1[d] > x_0[d])\n                    R[d] = x_1[d]\n                else\n                    throw(ErrorException(\"Error during shrinking the interval\"))\n                end\n            end\n\n        end # end of permutating through dimensions\n\n        ### 4) Update the chain:\n        # Just overwrite the burnIn by using modular arithmetic:\n        i = 1 + (ii-1)%N    # gives 1,2,3,...N,1,2,3,...,(N+burnIn)\n        x_s[i,:] = x_1    # sample point, after one round of permutations\n        pdflog_x_s[i] = pdflog_x_1 # now contains log_pdf of all new coordinates of new point, since has been updated at each permutation\n        # note that x_0 has been updated during the permutations\n\n    end\n\n    return x_s, pdflog_x_s\nend\n\n#%%\n################################################################\n\nfunction log_beta(θ,a::Any,b::Any)\n    #using SpecialFunctions\n    θ = θ[1]\n    if 0 < θ < 1\n        # Numerator\n        num = log(θ)*(a-1) + log(1-θ)*(b-1)\n        # The denominator (Beta-function) can be integrated or made up of Gamma-functions\n        # Since we only treat integer values here, Γ(a) = (a-1)!\n        #den = log(factorial(a-1) * factorial(b-1) / factorial(a+b-1))\n        den = log(SpecialFunctions.beta(a,b))\n        return num - den\n    else\n        return -Inf\n    end\nend\n\n# Jespers HDI:\nfunction hdi(theta_samp,alpha=0.05)\n    cred_mass = 1.0-alpha\n    ci = zeros(2)\n    if length(size(theta_samp))>1   # multidimensional theta\n        K,N = size(theta_samp)\n        cis = zeros(2,K)\n        for k in 1:K    # for each dimension\n\n            ts = theta_samp[k,:]\n            sind = sortperm(ts)     # get series of indices that sorts theta values\n            sts = ts[sind]  # sorted theta values\n\n            # Shifting a 95% index block from far left to far right and use the\n            # samllest interval that can be found during the shift\n            N = length(sind)    # number of sample points\n            length_ci = Inf     # start with inf HDI interval and shrink\n            for i in 1:Int(floor(N*alpha))  # iterate over the 5% lowest values (low to high)\n                i2 = Int(floor(N*cred_mass)+i)  # the 5% highest values (low to high), one 95% block away on the other side\n                prop_ci = [sts[i],sts[i2]]      # proposed interval\n                length_prop_ci = prop_ci[2]-prop_ci[1]\n                if length_prop_ci < length_ci\n                    ci = prop_ci\n                    length_ci = ci[2]-ci[1]\n                end\n            end\n            cis[:,k] = ci\n\n        end\n        return cis\n    else\n        N = length(theta_samp)\n\n        ts = theta_samp\n        sind = sortperm(ts)\n        sts = ts[sind]\n\n        N = length(sind)\n        length_ci = Inf\n        for i in 1:Int(floor(N*alpha))\n            i2 = Int(floor(N*cred_mass)+i)\n            prop_ci = [sts[i],sts[i2]]\n            length_prop_ci = prop_ci[2]-prop_ci[1]\n            if length_prop_ci < length_ci\n                ci = prop_ci\n                length_ci = ci[2]-ci[1]\n            end\n        end\n        return ci\n    end\nend\n\n################################################################\n\n# Log-Bernoulli PDF:\nfunction log_bernoulli_pdf(θ,y)\n    if 0 < θ < 1 && (y==0 || y==1)    # Only admissible values\n        return y * log(θ) + (1-y) * log(1-θ)\n    else\n        return -Inf\n    end\nend\n\n# Log-Likelihood fct of a (series of) coin tosses with bias:\nfunction log_likelihood_fct(θ, y)\n    # Make array s.t. multiple theta values can be input:\n    #likelihood = Array{Float64}(undef,length(θ))\n    # Do that for every theta value requested:\n    #for ii in 1:length(θ)\n    #    # Elementwise application of the log_beronoulli_pdf over outcome vector y, then SUM together:\n    #    likelihood[ii] = sum(log_bernoulli_pdf.(θ[ii],y))\n    #end\n\n    # Un array-ise the output:\n    #if length(θ) == 1\n    #    likelihood = likelihood[1]\n    #end\n\n    θ = θ[1]\n    likelihood = sum(log_bernoulli_pdf.(θ,y))\n\n    return likelihood\nend\n\n#%%\n################################################################\n\n### Part A\n# Chain inputs:\nN = 10^6\nx_start = 0.5;\nw = .5;  # typical window width\nm = 100; # maximum number of window widths\n\n#%%\n#First sampling\na = 1   # Flat Prior\nb = 1\ny = [ones(Int64,11); zeros(Int64,3)];   # Given observaitons\n\nlog_prior(θ) = log_beta(θ,a,b)\nlog_lklhd(θ) = log_likelihood_fct(θ,y)\nlog_posterior(θ) = log_lklhd(θ) + log_prior(θ)\n\n# Need to use \"StatsPlots\" or \"Plots\" histogram to add the density curve, PyPlot won't work\nchain, pdf = mySliceSampler(log_posterior,x_start,w,m,N);\nchain = reshape(chain,:)\n#%%\nhistogram(chain, bins=100, normalize=:pdf, label=\"posterior\")   # Comes from StatsPlots now\ndensity!(chain,linewidth=3,label=\"posterior\")\n\n#%%\n# Sample Mean\nμ = sum(chain)/N\n\n# Mode\nω = chain[argmax(pdf)]\n\n# Equal Tail Interval:\n# Find the 2.5% highest and lowest (equal tails)\n# get their index and receive an interval\nα = 0.05;\nidcesForOrder = sortperm(chain) # Indices of the chain which make it sorted\nchain_sorted = chain[idcesForOrder]\n\nleftTailIdx = Int(floor(N*(α/2)))\nrightTailIdx = Int(ceil(N*(1- α/2)))\n\nETI = [chain_sorted[leftTailIdx],chain_sorted[rightTailIdx]]\n\nHDI = hdi(chain)\n\n#%%\np_gthalf = count(i->(i>0.5), chain)/N\n\n#%%\n\n### Part B\n\n# Chain inputs:\nN = 10^6\nx_start = 0.5;\nw = .5;  # typical window width\nm = 100; # maximum number of window widths\n\n#%%\n#Second dataset\na = 1   # Flat Prior\nb = 1\ny = [ones(Int64,3); zeros(Int64,7)];   # Given observtions\n\nlog_prior(θ) = log_beta(θ,a,b)\nlog_lklhd(θ) = log_likelihood_fct(θ,y)\nlog_posterior(θ) = log_lklhd(θ) + log_prior(θ)\n\n# Need to use \"StatsPlots\" or \"Plots\" histogram to add the density curve, PyPlot won't work\nchain2, pdf2 = mySliceSampler(log_posterior,x_start,w,m,N);\nchain2 = reshape(chain2,:);\n#%%\nhistogram(chain2, bins=100, normalize=:pdf, label=\"posterior\")   # Comes from StatsPlots now\ndensity!(chain2,linewidth=3,label=\"posterior\")\n\n#%%  Method 1\ngt = (chain .> chain2)*1\nsum(gt)/N\n\n#%% Method 1.1, questionable...\n#gt = Array{Float64,1}(undef,N)\n#for i in 1:length(chain)\n    # for each entry in chain 1, compare it to ALL entries in chain2\n#    gt[i] = sum((chain[i] .> chain2) * 1)/length(chain2)\n#end\n\n#sum(gt)/length(chain)\n\n#%% Method 1.1, questionable...\n#gt = (μ .> chain2) * 1\n#sum(gt)/N\n\n#%% Method 1.2, questionable...\n#μ2 = sum(chain2)/N\n#ω2 = chain[argmax(pdf)]\n\n#idcesForOrder = sortperm(chain2) # Indices of the chain which make it sorted\n#chain2_sorted = chain[idcesForOrder]\n\n#gt = (chain_sorted .> maximum(chain2_sorted))*1\n#sum(gt)\n\n#%% Method 2\ndθ = (chain - chain2)\ngtZero = (dθ .> 0)*1\nsum(gtZero)/N\nhdi(dθ)\n\n#%% Method 3\ndθ = (chain - chain2)\ndθ = reshape(dθ,:)      # to get an Array{Float64,1}\nhistogram(dθ, bins=100, normalize=:pdf, label=\"d_theta\")\ndensity!(dθ,linewidth=3,label=\"d_theta\")\n#%%\ndiff_hdi = hdi(dθ)\n#%%\nusing Plots\nPlots.savefig(\"/home/johhub/Desktop/ABDA/A4/A4-B-hist.pdf\")\n", "meta": {"hexsha": "40504af047eef16396d544e187da1a4e6e197616", "size": 10208, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "A4/A4-TaskB.jl", "max_stars_repo_name": "vis-florum/Applied-Bayesian-Data-Analysis", "max_stars_repo_head_hexsha": "6d460443269d920ea61859df9434938139245c2b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A4/A4-TaskB.jl", "max_issues_repo_name": "vis-florum/Applied-Bayesian-Data-Analysis", "max_issues_repo_head_hexsha": "6d460443269d920ea61859df9434938139245c2b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A4/A4-TaskB.jl", "max_forks_repo_name": "vis-florum/Applied-Bayesian-Data-Analysis", "max_forks_repo_head_hexsha": "6d460443269d920ea61859df9434938139245c2b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5628742515, "max_line_length": 137, "alphanum_fraction": 0.5714145768, "num_tokens": 2947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7602123139891006}}
{"text": "# A semi-separable matrix is defined by\n#\n# S = triu(uvᵀ, bu+1) + tril(pqᵀ, -bl-1),\n#\n# where bu, bl >= 0. u and v are n × ru matrices and p and q are n × rl matrices.\n# See [1] for the definition.\n\n# [1] Chandrasekaran and Gu, Fast and stable algorithms for banded plus\n# Semiseparable systems of linear equations, SIMAX, 25 (2003), pp. 373-384.\n\n## Constructors\n\nstruct SemiSeparableMatrix{T} <: AbstractMatrix{T}\n    L::LowRankMatrix{T}\n    U::LowRankMatrix{T}\n    bl::Int\n    bu::Int\n\n    function SemiSeparableMatrix(L::LowRankMatrix{T}, U::LowRankMatrix{T}, bl, bu) where T\n        Lm, Ln = size(L)\n        Um, Un = size(U)\n        @assert Um == Un == Lm == Ln && Un >= bu+1 && Lm >= bl+1\n        new{T}(L, U, bl, bu)\n    end\nend\n\nfunction Base.convert(::Type{Matrix}, S::SemiSeparableMatrix)\n    return triu(Matrix(S.U), S.bu+1) + tril(Matrix(S.L), -S.bl-1)\nend\n\nsize(S::SemiSeparableMatrix) = size(S.L)\n\nfunction getindex(S::SemiSeparableMatrix{T}, k::Int, j::Int)  where T\n    k-j ≥ S.bl && return S.L[k,j]\n    j-k ≥ S.bu && return S.U[k,j]\n    return zero(T)\nend\n", "meta": {"hexsha": "98e07ec3b524633ff379e132e0c38ea3a5803edf", "size": 1073, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SemiSeparableMatrix.jl", "max_stars_repo_name": "kuanxu/AlmostBandedMatrices.jl", "max_stars_repo_head_hexsha": "5d954bb50cc3c23f9e50556972aa5a55f0961b04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SemiSeparableMatrix.jl", "max_issues_repo_name": "kuanxu/AlmostBandedMatrices.jl", "max_issues_repo_head_hexsha": "5d954bb50cc3c23f9e50556972aa5a55f0961b04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-24T20:10:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-24T20:10:23.000Z", "max_forks_repo_path": "src/SemiSeparableMatrix.jl", "max_forks_repo_name": "kuanxu/AlmostBandedMatrices.jl", "max_forks_repo_head_hexsha": "5d954bb50cc3c23f9e50556972aa5a55f0961b04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2368421053, "max_line_length": 90, "alphanum_fraction": 0.6225535881, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7601662404006825}}
{"text": "# A version of Stiefel’s Conjugate Residual method for linesearch.\n\n\"\"\"A version of Stiefel’s Conjugate Residual method for linesearch.\nCR(A, b, ϵa, ϵr, itmax; quad) solves the symmetric linear system 'A * x = b'\nor the least-squares problem : 'min ‖b - A * x‖²'\nIf quad = true, the values of the quadratic model are computed\nA can be positive definite or not.\n\"\"\"\nfunction CRlin(A, b, ϵa::Float64=1e-8, ϵr::Float64=1e-6, itmax::Int=0, ε::Float64=1e-6; quad::Bool=false)\n    n = size(b, 1) # size of the problem\n    (size(A, 1) == n & size(A, 2) == n) || error(\"Inconsistent problem size\")\n    @info(loggerCRlin, @sprintf(\"CRlin: system of %d equations in %d variables\", n, n))\n\n    x = zeros(n) # initial estimation x = 0\n    xNorm = 0.0\n    xNorms = [xNorm] # Values of ‖x‖\n    r = b # initial residual r = b - Ax = b\n    rNorm = norm(r, 2) # ‖r‖\n    rNorm² = rNorm * rNorm\n    pr = rNorm²\n    s = A * r\n    ρ = dot(r, s)\n    p = r\n    pNorm² = rNorm²\n    q = s\n    ϵ = ϵa + ϵr * rNorm\n    pAp = ρ # = dot(p, q) = dot(r, s)\n\n    iter = 0\n    itmax == 0 && (itmax = 2 * n)\n\n    if quad\n        m = 0.0\n        mvalues = [m] # values of the quadratic model\n        @info(loggerCRlin, @sprintf(\"%5s %7s %8s\", \"Iter\", \"‖r‖\", \"q\"))\n        @info(loggerCRlin, @sprintf(\"%5d %7.1e %8.1e\", iter, rNorm, m))\n    end\n\n    solved = rNorm ≤ ϵ\n    tired = iter ≥ itmax\n\n    while ! (solved || tired)\n        iter += 1\n\n        if (pAp ≤ ε * pNorm²) || (ρ ≤ ε * rNorm²)\n            @debug(loggerCRlin, @sprintf(\"nonpositive curvature detected: pAp = %8.1e and rAr = %8.1e\", pAp, ρ))\n            iter == 1 && return b\n            return x\n        end\n\n        α = ρ / dot(q, q) # step\n        x = x + α * p\n        xNorm = norm(x, 2)\n        push!(xNorms, xNorm)\n        r = r - α * q  # residual\n        rNorm² = abs(rNorm² - α * ρ)\n        rNorm = sqrt(rNorm²)\n\n        if quad\n            m = -dot(b, x) + 0.5 * dot(x, A * x)\n            push!(mvalues, m)\n            @info(loggerCRlin, @sprintf(\"%5d %7.1e %8.1e\", iter, rNorm, m))\n        end\n\n        solved = rNorm <= ϵ\n        tired = iter >= itmax\n        (solved || tired) && continue\n\n        s = A * r\n        ρbar = ρ\n        ρ = dot(r, s)\n        β = ρ / ρbar # step for the direction calculus\n        p = r + β * p # descent direction\n        pNorm² = rNorm² + 2 * β * pr - 2 * β * α * pAp + β^2 * pNorm²\n        pr = rNorm² + β * pr - β * α * pAp # pᵀr\n        q = s + β * q\n        pAp = ρ + β^2 * pAp # dot(p, q)\n\n    end\n\n    return x\nend\n", "meta": {"hexsha": "e2399112ba22559629a8d19cfa5b8ab580b95774", "size": 2494, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CRlin.jl", "max_stars_repo_name": "DahitoMA/Linesearch.jl", "max_stars_repo_head_hexsha": "b27f91be32716e25ce24805b372dde7cfbcc8246", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CRlin.jl", "max_issues_repo_name": "DahitoMA/Linesearch.jl", "max_issues_repo_head_hexsha": "b27f91be32716e25ce24805b372dde7cfbcc8246", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CRlin.jl", "max_forks_repo_name": "DahitoMA/Linesearch.jl", "max_forks_repo_head_hexsha": "b27f91be32716e25ce24805b372dde7cfbcc8246", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0481927711, "max_line_length": 112, "alphanum_fraction": 0.5088211708, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915913, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7601662388704313}}
{"text": "function integrate(\n    f::Function,\n    a::Real,\n    b::Real;\n    method::Symbol = :quadrature,\n)\n    if method == :quadrature\n        res, err = quadgk(f, a, b)\n        return res\n    elseif method == :simpsons\n        return adaptivesimpsons(f, a, b)\n    elseif method == :monte_carlo\n        return montecarlo(f, a, b)\n    else\n        throw(\n            ArgumentError(\n                \"method must be :quadrature, :simpsons or :monte_carlo\"\n            )\n        )\n    end\nend\n", "meta": {"hexsha": "49930efafaefdc07947ebe3870f34133005fa0be", "size": 482, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/api/integrate.jl", "max_stars_repo_name": "johnmyleswhite/Calculus2.jl", "max_stars_repo_head_hexsha": "57f56fed859ceb6c87455249f22a0a2eb85029a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-08-25T19:12:38.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-25T19:12:38.000Z", "max_issues_repo_path": "src/api/integrate.jl", "max_issues_repo_name": "johnmyleswhite/Calculus2.jl", "max_issues_repo_head_hexsha": "57f56fed859ceb6c87455249f22a0a2eb85029a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/api/integrate.jl", "max_forks_repo_name": "johnmyleswhite/Calculus2.jl", "max_forks_repo_head_hexsha": "57f56fed859ceb6c87455249f22a0a2eb85029a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-01T12:21:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:21:27.000Z", "avg_line_length": 21.9090909091, "max_line_length": 71, "alphanum_fraction": 0.5352697095, "num_tokens": 135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7601662383077544}}
{"text": "# julia --project=. plotscript.jl\n#\n# This will take a long time to start so won't\n# recommend doing this.\nusing Plots\ngr\n\n# x = 1:10\n# y = rand(10)\n# p = plot(x,y)\n# gui()\n# display(p)\n# println(\"Hello World!\")\n# readline()\n\nn = 50 # points\nx_vec = fill(0.0, n)\ny_vec = fill(0.0, n)\nxmin = -10.0\nxmax = 10.0\nx_range = LinRange(xmin, xmax, n)\n# Sigmoid function\n# Generalized logistic function\nfunction fx(x, w, b, alpha)\n    #y = 1/(1 + exp(-w*x + b))\n    y = (1+ exp(-w*x)+b)^(-alpha)\n    #y = exp(-w*x)\n    return y\nend\n\n\"\"\"\n    glf(x, A, K, B, mu, Q, C, M)\n\nGeneralized logistic function\n\"\"\"\nfunction glf(x, A, K, B, mu, Q, C, M)\n    Y = A + (K-A)/(C + Q*exp(-B*(x-M)))^(1/mu)\nend\n# w = 1\n# b = 20# 0 - 10\n# alp = 0.3\nA = 0.01\nK = 1.0\nQ = 1.0 #0.5\nC = 1.0\n\n# B = 1.8# 2 # 5 # 0 to 10 # top angle\n# mu = 1.8 # Close rate  # bottom angle\n# M = 5.8 # shift left and right\nB = 1.8 # 2 # 5 # 0 to 10 # top angle\nmu = 1.7 # Close rate  # bottom angle\nM = 5.8 # shift left and right\nfor (ind,x) in enumerate(x_range)\n    y_vec[ind] = glf(x, A, K, B, mu, Q, C, M)\nend\n\n# scale to 14.7 to 9200 psi\npmin = 14.7\npmax = 9200\npdist = pmax - pmin\ndist = xmax - xmin\nscale = pdist/dist\nfor (ind,x) in enumerate(x_range)\n    x_vec[ind] = (x+10)*scale + pmin\nend\n\npt = plot(x_vec,y_vec, legend=(0.1,0.9))\n\n# B = 2 # 2 # 5 # 0 to 10 # top angle\n# mu = 2 # Close rate  # bottom angle\n# M = 5 # shift left and right\n# for (ind,x) in enumerate(x_range)\n#     y_vec[ind] = glf(x, A, K, B, mu, Q, C, M)\n# end\n\n# scale to 14.7 to 9200 psi\n# pmin = 14.7\n# pmax = 9200\n# pdist = pmax - pmin\n# dist = xmax - xmin\n# scale = pdist/dist\n# for (ind,x) in enumerate(x_range)\n#     x_vec[ind] = (x+10)*scale + pmin\n# end\n#\n# plot!(pt, x_vec, y_vec)\n\nps = [  14.7,   3000,    5000,    5316,    5800,   6284,   6500,       6700, 7167,  7601, 7900, 8200, 9204]\nks = [0.01, 0.01,    0.01,    0.015,    0.04,      0.08,     0.16,   0.30,   0.65,  0.85, 0.95, 1, 1]\n\nplot!(pt, ps, ks)\n", "meta": {"hexsha": "83169ece4c88b3ace3a9082dc6da78bc6cf9a6f1", "size": 1950, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "plots/plotscript.jl", "max_stars_repo_name": "ykyang/org.allnix.julia", "max_stars_repo_head_hexsha": "58933a5848dec81c53d591b4163e9a70df62ddd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plots/plotscript.jl", "max_issues_repo_name": "ykyang/org.allnix.julia", "max_issues_repo_head_hexsha": "58933a5848dec81c53d591b4163e9a70df62ddd8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plots/plotscript.jl", "max_forks_repo_name": "ykyang/org.allnix.julia", "max_forks_repo_head_hexsha": "58933a5848dec81c53d591b4163e9a70df62ddd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1956521739, "max_line_length": 107, "alphanum_fraction": 0.5538461538, "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7601662369352822}}
{"text": "module bavarian_wood\n\nusing JuMP\nusing Cbc\nusing CSV\n\nfunction solve_bavarian_wood()\n\n    n = 10;\n\n    Q = 25;\n    h = 5;\n\n    K = 8;\n    o = [ 1  1  2  2  3  3  4  4  ];\n    d = [ 9  10 9  10 9  10 9  10 ];\n    L = [ 28 14 42 35 39 18 19 31 ];\n\n    R = [\n        (1,5) (1,7) (1,8) (1,9) (1,10) #=\twhy this #= =# stuff? because otherwise\n    =#  (2,5) (2,7) (2,8) (2,9) (2,10) #=\tJulia interprets it as 8 different rows\n    =#  (3,5) (3,7) (3,8) (3,9) (3,10) #=\tbut it is just one row of pairs. I want\n    =#  (4,6) (4,7) (4,8) (4,9) (4,10) #=\tto display it in 8 rows in the code to\n    =#  (5,7) (5,8) (5,9) (5,10)       #=\tincrease readability. See further dis-\n    =#  (6,7) (6,8) (6,9) (6,10)       #=    cussion here: https://github.com/JuliaLang/julia/issues/27533\n    =#  (7,8) (7,9) (7,10)             #=\n    =#  (8,10)\n    ];\n\n    N = [5 6 7 8];\n\n    N_out = [\n    #=  1 =# (5, 7, 8, 9, 10)\n    #=  2 =# (5, 7, 8, 9, 10)\n    #=  3 =# (5, 7, 8, 9, 10)\n    #=  4 =# (6, 7, 8, 9, 10)\n    #=  5 =# (7, 8, 9, 10)\n    #=  6 =# (7, 8, 9, 10)\n    #=  7 =# (8, 9, 10)\n    #=  8 =# (10)\n    #=  9 =# ()\n    #= 10 =# ()\n    ];\n\n    N_in = [\n    #=  1 =# ()\n    #=  2 =# ()\n    #=  3 =# ()\n    #=  4 =# ()\n    #=  5 =# (1, 2, 3)\n    #=  6 =# (4)\n    #=  7 =# (1, 2, 3, 4, 5, 6)\n    #=  8 =# (1, 2, 3, 4, 5, 6, 7)\n    #=  9 =# (1, 2, 3, 4, 5, 6, 7)\n    #= 10 =# (1, 2, 3, 4, 5, 6, 7, 8)\n    ];\n\n    c = [\n        Inf\tInf\tInf\tInf\t280\tInf\t530\t830\t780\t1000;\n        Inf\tInf\tInf\tInf\t245\tInf\t495\t795\t745\t965;\n        Inf\tInf\tInf\tInf\t175\tInf\t425\t725\t675\t895;\n        Inf\tInf\tInf\tInf\tInf\t220\t670\t680\t920\t850;\n        Inf\tInf\tInf\tInf\tInf\tInf\t250\t550\t500\t720;\n        Inf\tInf\tInf\tInf\tInf\tInf\t450\t460\t700\t630;\n        Inf\tInf\tInf\tInf\tInf\tInf\tInf\t300\t250\t470;\n        Inf\tInf\tInf\tInf\tInf\tInf\tInf\tInf\tInf\t170;\n        Inf\tInf\tInf\tInf\tInf\tInf\tInf\tInf\tInf\tInf;\n        Inf\tInf\tInf\tInf\tInf\tInf\tInf\tInf\tInf\tInf;\n    ]\n\n    model = Model(with_optimizer(Cbc.Optimizer));\n\n    @variable(model, x[1:n,1:n,1:K] >= 0)\n    @variable(model, y[1:n,1:n] >= 0, Int)\n\n    @objective(model, Min, sum( c[i,j]*y[i,j] for (i,j) in R ) +\n        sum(\n            sum(\n                sum(\n                    h*x[j,i,k]\n                for j in N_in[i] )\n            for i in N )\n        for k in 1:K ));\n\n    @constraint(model,[k in 1:K,i = o[k]], sum(x[i,j,k] for j in N_out[i]) == L[k]);\n    @constraint(model,[k in 1:K,j = d[k]], sum(x[i,j,k] for i in N_in[j]) == L[k]);\n    @constraint(model,[(i,j) in R], sum(x[i,j,k] for k in 1:K) <= Q*y[i,j]);\n\n    f = open(\"bavarian_wood.lp\", \"w\")\n    print(f, model)\n    close(f)\n\n    #-------\n    # SOLVE\n    #-------\n\n    optimize!(model)\n\n    #------------------------\n    # WRITE SOLUTION TO FILE\n    #------------------------\n\n    f = open(\"bavarian_wood.csv\",\"w\");\n\n    for k in 1:K\n        print(f,\"commodity \",o[k],\"-\",d[k],\" - qty = \",L[k]);\n        for (i,j) in R\n            if (value(x[i,j,k]) > 0)\n                println(f,\",route \",i,\"-\",j,\",\",value(x[i,j,k]));\n            end\n        end\n    end\n\n    for (i,j) in R\n        if (value(y[i,j]) != 0)\n            print(f,\"route \",i,\"-\",j,\" - \",value(y[i,j]),\" trucks\");\n            for k in 1:K\n                if (value(x[i,j,k]) != 0)\n                    println(f,\",commodity \",o[k],\"-\",d[k],\",\",value(x[i,j,k]));\n                end\n            end\n        end\n    end\n\n    close(f);\n\nend\n\nsolve_bavarian_wood();\n\nend\n", "meta": {"hexsha": "128c3c5b5c24df0cd23558012d8a18842124b042", "size": 3393, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/network/supply-net/bavarian_wood.jl", "max_stars_repo_name": "edxu96/MatrixOptim", "max_stars_repo_head_hexsha": "97ef8b1311351291427f8f650b0215c7ff00bddc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/network/supply-net/bavarian_wood.jl", "max_issues_repo_name": "edxu96/MatrixOptim", "max_issues_repo_head_hexsha": "97ef8b1311351291427f8f650b0215c7ff00bddc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/network/supply-net/bavarian_wood.jl", "max_forks_repo_name": "edxu96/MatrixOptim", "max_forks_repo_head_hexsha": "97ef8b1311351291427f8f650b0215c7ff00bddc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-04T09:41:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-04T09:41:13.000Z", "avg_line_length": 25.7045454545, "max_line_length": 106, "alphanum_fraction": 0.4137931034, "num_tokens": 1490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7601662369352821}}
{"text": "function reciprocal_cycle_len(n::Int)\r\n\tseen=Dict{Int,Int}()\r\n    x=1\r\n    index=1\r\n\twhile true\r\n\r\n\t\tif x in keys(seen)\r\n\t\t\treturn index-seen[x]+1\r\n\t\telse\r\n\t\t\tseen[x]=index\r\n\t\t\tx=x*10 %n \r\n\t\tend\r\n\t\tindex+=1\r\n\tend\r\nend\r\n\r\nfunction compute()\r\n\tans=0\r\n\tfor i =1:1000\r\n\t\tans=max(ans,reciprocal_cycle_len(i))\r\n\tend\r\n\r\n\treturn ans\r\n\r\nend\r\n\r\n\r\nprintln(compute())\r\n", "meta": {"hexsha": "68b7f4de2aa99ae10aac306af0a8010ec94dc363", "size": 357, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/p026.jl", "max_stars_repo_name": "tlming16/Projec_Euler", "max_stars_repo_head_hexsha": "797824c5159fae67493de9eba24c22cc7512d95d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-11-14T12:03:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-03T14:33:28.000Z", "max_issues_repo_path": "julia/p026.jl", "max_issues_repo_name": "tlming16/Projec_Euler", "max_issues_repo_head_hexsha": "797824c5159fae67493de9eba24c22cc7512d95d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/p026.jl", "max_forks_repo_name": "tlming16/Projec_Euler", "max_forks_repo_head_hexsha": "797824c5159fae67493de9eba24c22cc7512d95d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-17T14:39:22.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-17T14:39:22.000Z", "avg_line_length": 12.3103448276, "max_line_length": 39, "alphanum_fraction": 0.5994397759, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7601662333121029}}
{"text": "# Patrick Keast, MODERATE-DEGREE TETRAHEDRAL QUADRATURE FORMULAS\nfunction _get_gauss_tetdata(n::Int)\n    if n == 1\n        a = 1. / 4.\n        w = 1. / 6.\n        xw = [a a a w]\n    elseif n == 2\n        a = ( 5. + 3. * √(5.) ) / 20.\n        b = ( 5. - √(5.) ) / 20.\n        w = 1. / 24.\n        xw = [a b b w\n              b a b w\n              b b a w\n              b b b w]\n    elseif n == 3\n        a1 = 1. / 4.\n        a2 = 1. / 2.\n        b2 = 1. / 6.\n        w1 = -2. / 15.\n        w2 = 3. / 40.\n        xw = [a1 a1 a1 w1\n              a2 b2 b2 w2\n              b2 a2 b2 w2\n              b2 b2 a2 w2\n              b2 b2 b2 w2]\n    else\n        throw(ArgumentError(\"unsupported order for tetraheder gauss-legendre integration\"))\n    end\n    return xw\nend\n", "meta": {"hexsha": "ff5c555d43ebcc5ed304b14ac3028b52d9070dc4", "size": 761, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Quadrature/gaussquad_tet_table.jl", "max_stars_repo_name": "louisponet/JuAFEM.jl", "max_stars_repo_head_hexsha": "a007e3d0a650954472fe059150088abc69d567c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Quadrature/gaussquad_tet_table.jl", "max_issues_repo_name": "louisponet/JuAFEM.jl", "max_issues_repo_head_hexsha": "a007e3d0a650954472fe059150088abc69d567c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Quadrature/gaussquad_tet_table.jl", "max_forks_repo_name": "louisponet/JuAFEM.jl", "max_forks_repo_head_hexsha": "a007e3d0a650954472fe059150088abc69d567c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5483870968, "max_line_length": 91, "alphanum_fraction": 0.3981603154, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885302, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7601216278769894}}
{"text": "\"\"\"\n\n  function procrustes(x,y) -> xnew\n\n  aligns two structures [sets of points in 3D space]. Solves\n  the \"Procrustes\" problem. Structures are expected to be of the same size, and the \n  correspondence is assumed from the vector indices. \n \n  Returns x aligned, by performing the rigid body transformation [rotation\n  and translation that minimizes the RMSD between x and y].\n \n  x, y, and xnew (return) are matrices of dimensions (n,3) \n  (n is the number of points, 3 is the dimension of the space).\n \n  L. Martinez, Institute of Chemistry - University of Campinas\n  Jan 04, 2019\n\n\"\"\"\n\nusing LinearAlgebra\n\nfunction procrustes( x :: Matrix{}, y :: Matrix{} )\n\n  n = size(x,1)\n\n  # Computing centroid\n\n  cmx = zeros(3)\n  cmy = zeros(3)\n  for i in 1:n\n    for j in 1:3\n      cmx[j] = cmx[j] + x[i,j]\n      cmy[j] = cmy[j] + y[i,j]\n    end\n  end\n  cmx = cmx / n\n  cmy = cmy / n\n\n  # Translating both sets to the origin\n\n  for i in 1:n\n    for j in 1:3\n      x[i,j] = x[i,j] - cmx[j]\n      y[i,j] = y[i,j] - cmy[j]\n    end\n  end\n\n  # Computing the quaternion matrix\n\n  xm = Vector{Float64}(undef,n)\n  ym = Vector{Float64}(undef,n)\n  zm = Vector{Float64}(undef,n)\n  xp = Vector{Float64}(undef,n)\n  yp = Vector{Float64}(undef,n)\n  zp = Vector{Float64}(undef,n)\n  for i in 1:n\n    xm[i] = y[i,1] - x[i,1]\n    ym[i] = y[i,2] - x[i,2]\n    zm[i] = y[i,3] - x[i,3]\n    xp[i] = y[i,1] + x[i,1]\n    yp[i] = y[i,2] + x[i,2]\n    zp[i] = y[i,3] + x[i,3]\n  end\n\n  q = zeros(4,4)\n  for i in 1:n\n    q[1,1] = q[1,1] + xm[i]^2 + ym[i]^2 + zm[i]^2\n    q[1,2] = q[1,2] + yp[i]*zm[i] - ym[i]*zp[i]\n    q[1,3] = q[1,3] + xm[i]*zp[i] - xp[i]*zm[i]\n    q[1,4] = q[1,4] + xp[i]*ym[i] - xm[i]*yp[i]\n    q[2,2] = q[2,2] + yp[i]^2 + zp[i]^2 + xm[i]^2\n    q[2,3] = q[2,3] + xm[i]*ym[i] - xp[i]*yp[i]\n    q[2,4] = q[2,4] + xm[i]*zm[i] - xp[i]*zp[i]\n    q[3,3] = q[3,3] + xp[i]^2 + zp[i]^2 + ym[i]^2\n    q[3,4] = q[3,4] + ym[i]*zm[i] - yp[i]*zp[i]\n    q[4,4] = q[4,4] + xp[i]^2 + yp[i]^2 + zm[i]^2\n  end\n  q[2,1] = q[1,2]\n  q[3,1] = q[1,3]\n  q[3,2] = q[2,3]\n  q[4,1] = q[1,4]\n  q[4,2] = q[2,4]\n  q[4,3] = q[3,4]          \n\n  # Computing the eigenvectors 'v' of the q matrix\n\n  v = LinearAlgebra.eigvecs(q)\n\n  # Compute rotation matrix\n  \n  u = Matrix{Float64}(undef,3,3)\n  u[1,1] = v[1,1]^2 + v[2,1]^2 - v[3,1]^2 - v[4,1]^2\n  u[1,2] = 2. * ( v[2,1]*v[3,1] + v[1,1]*v[4,1] )\n  u[1,3] = 2. * ( v[2,1]*v[4,1] - v[1,1]*v[3,1] )\n  u[2,1] = 2. * ( v[2,1]*v[3,1] - v[1,1]*v[4,1] )\n  u[2,2] = v[1,1]^2 + v[3,1]^2 - v[2,1]^2 - v[4,1]^2\n  u[2,3] = 2. * ( v[3,1]*v[4,1] + v[1,1]*v[2,1] )\n  u[3,1] = 2. * ( v[2,1]*v[4,1] + v[1,1]*v[3,1] )\n  u[3,2] = 2. * ( v[3,1]*v[4,1] - v[1,1]*v[2,1] )\n  u[3,3] = v[1,1]^2 + v[4,1]^2 - v[2,1]^2 - v[3,1]^2      \n\n  # Rotate vector x [will be stored in xnew], and restore y\n\n  xnew = zeros(n,3)\n  for i in 1:n\n    for j in 1:3\n      for k in 1:3\n        xnew[i,j] = xnew[i,j] + u[j,k] * x[i,k]\n      end \n    end\n  end\n\n  # Translate vector to the centroid of y [and restore x and y]\n\n  for i in 1:n\n    for j in 1:3\n      xnew[i,j] = xnew[i,j] + cmy[j]\n      y[i,j] = y[i,j] + cmy[j]\n      x[i,j] = x[i,j] + cmx[j]\n    end\n  end\n\n  return xnew\n\nend\n\n\n\n", "meta": {"hexsha": "6f4917ed7e438a47a0c0c6713b838d71e003313c", "size": 3147, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/procrustes.jl", "max_stars_repo_name": "mcubeg/M3GTools", "max_stars_repo_head_hexsha": "48ab02a23f0095e7964bfb047836f090f8d35331", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-22T05:04:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-30T06:32:25.000Z", "max_issues_repo_path": "src/procrustes.jl", "max_issues_repo_name": "mcubeg/M3GTools", "max_issues_repo_head_hexsha": "48ab02a23f0095e7964bfb047836f090f8d35331", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/procrustes.jl", "max_forks_repo_name": "mcubeg/M3GTools", "max_forks_repo_head_hexsha": "48ab02a23f0095e7964bfb047836f090f8d35331", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-17T10:16:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T10:16:37.000Z", "avg_line_length": 24.3953488372, "max_line_length": 84, "alphanum_fraction": 0.5014299333, "num_tokens": 1502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715436, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7601074126805825}}
{"text": "b1 = BSplineBasis(1, 0:5)\n\nB₁ = x -> Int(0 ≤ x < 1)\nB₂ = x -> Int(1 ≤ x < 2)\nB₃ = x -> Int(2 ≤ x < 3)\nB₄ = x -> Int(3 ≤ x < 4)\nB₅ = x -> Int(4 ≤ x ≤ 5)\n\nb1_exact = [B₁, B₂, B₃, B₄, B₅]\n\nb2 = BSplineBasis(2, big(0):1:big(5))\n\nB₁ = x -> 0 ≤ x < 1 ? -x + 1 : 0*one(x)\nB₂ = x -> 0 ≤ x < 1 ?  x + 0 :\n          1 ≤ x < 2 ? -x + 2 : 0*one(x)\nB₃ = x -> 1 ≤ x < 2 ?  x - 1 :\n          2 ≤ x < 3 ? -x + 3 : 0*one(x)\nB₄ = x -> 2 ≤ x < 3 ?  x - 2 :\n          3 ≤ x < 4 ? -x + 4 : 0*one(x)\nB₅ = x -> 3 ≤ x < 4 ?  x - 3 :\n          4 ≤ x ≤ 5 ? -x + 5 : 0*one(x)\nB₆ = x -> 4 ≤ x ≤ 5 ?  x - 4 : 0*one(x)\n# 1st derivatives\nB₁′ = x -> 0 ≤ x < 1 ? -1*one(x) : 0*one(x)\nB₂′ = x -> 0 ≤ x < 1 ?  1*one(x) :\n           1 ≤ x < 2 ? -1*one(x) : 0*one(x)\nB₃′ = x -> 1 ≤ x < 2 ?  1*one(x) :\n           2 ≤ x < 3 ? -1*one(x) : 0*one(x)\nB₄′ = x -> 2 ≤ x < 3 ?  1*one(x) :\n           3 ≤ x < 4 ? -1*one(x) : 0*one(x)\nB₅′ = x -> 3 ≤ x < 4 ?  1*one(x) :\n           4 ≤ x ≤ 5 ? -1*one(x) : 0*one(x)\nB₆′ = x -> 4 ≤ x ≤ 5 ?  1*one(x) : 0*one(x)\n\nb2_exact = [B₁ B₁′; B₂ B₂′; B₃ B₃′; B₄ B₄′; B₅ B₅′; B₆ B₆′]\n\nb3 = BSplineBasis(3, 0//1:5//1)\n\nB₁ = x -> 0 ≤ x < 1 ? 1//1*x^2 - 2//1*x + 1//1 : 0//1*one(x)\nB₂ = x -> 0 ≤ x < 1 ? -3//2*x^2 + 2//1*x        :\n          1 ≤ x < 2 ?  1//2*x^2 - 2//1*x + 2//1 : 0//1*one(x)\nB₃ = x -> 0 ≤ x < 1 ?  1//2*x^2                 :\n          1 ≤ x < 2 ? -1//1*x^2 + 3//1*x - 3//2 :\n          2 ≤ x < 3 ?  1//2*x^2 - 3//1*x + 9//2 : 0//1*one(x)\nB₄ = x -> 1 ≤ x < 2 ?  1//2*x^2 - 1//1*x +  1//2 :\n          2 ≤ x < 3 ? -1//1*x^2 + 5//1*x - 11//2 :\n          3 ≤ x < 4 ?  1//2*x^2 - 4//1*x +  8//1 : 0//1*one(x)\nB₅ = x -> 2 ≤ x < 3 ?  1//2*x^2 - 2//1*x +  2//1 :\n          3 ≤ x < 4 ? -1//1*x^2 + 7//1*x - 23//2 :\n          4 ≤ x ≤ 5 ?  1//2*x^2 - 5//1*x + 25//2 : 0//1*one(x)\nB₆ = x -> 3 ≤ x < 4 ?  1//2*x^2 -  3//1*x +  9//2 :\n          4 ≤ x ≤ 5 ? -3//2*x^2 + 13//1*x - 55//2 : 0//1*one(x)\nB₇ = x -> 4 ≤ x ≤ 5 ? 1//1*x^2 - 8//1*x + 16//1 : 0//1*one(x)\n# 1st derivatives\nB₁′ = x -> 0 ≤ x < 1 ? 2//1*x - 2//1 : 0//1*one(x)\nB₂′ = x -> 0 ≤ x < 1 ? -3//1*x + 2//1 :\n           1 ≤ x < 2 ?  1//1*x - 2//1 : 0//1*one(x)\nB₃′ = x -> 0 ≤ x < 1 ?  1//1*x        :\n           1 ≤ x < 2 ? -2//1*x + 3//1 :\n           2 ≤ x < 3 ?  1//1*x - 3//1 : 0//1*one(x)\nB₄′ = x -> 1 ≤ x < 2 ?  1//1*x - 1//1 :\n           2 ≤ x < 3 ? -2//1*x + 5//1 :\n           3 ≤ x < 4 ?  1//1*x - 4//1 : 0//1*one(x)\nB₅′ = x -> 2 ≤ x < 3 ?  1//1*x - 2//1 :\n           3 ≤ x < 4 ? -2//1*x + 7//1 :\n           4 ≤ x ≤ 5 ?  1//1*x - 5//1 : 0//1*one(x)\nB₆′ = x -> 3 ≤ x < 4 ?  1//1*x -  3//1 :\n           4 ≤ x ≤ 5 ? -3//1*x + 13//1 : 0//1*one(x)\nB₇′ = x -> 4 ≤ x ≤ 5 ? 2//1*x - 8//1 : 0//1*one(x)\n# 2nd derivatives\nB₁′′ = x -> 0 ≤ x < 1 ? 2//1*one(x) : 0//1*one(x)\nB₂′′ = x -> 0 ≤ x < 1 ? -3//1*one(x) :\n            1 ≤ x < 2 ?  1//1*one(x) : 0//1*one(x)\nB₃′′ = x -> 0 ≤ x < 1 ?  1//1*one(x) :\n            1 ≤ x < 2 ? -2//1*one(x) :\n            2 ≤ x < 3 ?  1//1*one(x) : 0//1*one(x)\nB₄′′ = x -> 1 ≤ x < 2 ?  1//1*one(x) :\n            2 ≤ x < 3 ? -2//1*one(x) :\n            3 ≤ x < 4 ?  1//1*one(x) : 0//1*one(x)\nB₅′′ = x -> 2 ≤ x < 3 ?  1//1*one(x) :\n            3 ≤ x < 4 ? -2//1*one(x) :\n            4 ≤ x ≤ 5 ?  1//1*one(x) : 0//1*one(x)\nB₆′′ = x -> 3 ≤ x < 4 ?  1//1*one(x) :\n            4 ≤ x ≤ 5 ? -3//1*one(x) : 0//1*one(x)\nB₇′′ = x -> 4 ≤ x ≤ 5 ? 2//1*one(x) : 0//1*one(x)\n\nb3_exact = [B₁ B₁′ B₁′′; B₂ B₂′ B₂′′; B₃ B₃′ B₃′′; B₄ B₄′ B₄′′; B₅ B₅′ B₅′′; B₆ B₆′ B₆′′; B₇ B₇′ B₇′′]\n\nb4 = BSplineBasis(4, Int128[0,1,2,3,4,5])\n\nB₁ = x -> 0 ≤ x < 1 ? -1//1*x^3 + 3//1*x^2 - 3//1*x + 1//1 : 0//1*one(x)\nB₂ = x -> 0 ≤ x < 1 ?  7//4*x^3 - 9//2*x^2 + 3//1*x        :\n          1 ≤ x < 2 ? -1//4*x^3 + 3//2*x^2 - 3//1*x + 2//1 : 0//1*one(x)\nB₃ = x -> 0 ≤ x < 1 ? -11//12*x^3 + 3//2*x^2                 :\n          1 ≤ x < 2 ?   7//12*x^3 - 3//1*x^2 + 9//2*x - 3//2 :\n          2 ≤ x < 3 ?   -1//6*x^3 + 3//2*x^2 - 9//2*x + 9//2 : 0//1*one(x)\nB₄ = x -> 0 ≤ x < 1 ?  1//6*x^3                      :\n          1 ≤ x < 2 ? -1//2*x^3 + 2//1*x^2 -  2//1*x +  2//3 :\n          2 ≤ x < 3 ?  1//2*x^3 - 4//1*x^2 + 10//1*x - 22//3 :\n          3 ≤ x < 4 ? -1//6*x^3 + 2//1*x^2 -  8//1*x + 32//3 : 0//1*one(x)\nB₅ = x -> 1 ≤ x < 2 ?  1//6*x^3 -  1//2*x^2 +  1//2*x -   1//6 :\n          2 ≤ x < 3 ? -1//2*x^3 +  7//2*x^2 - 15//2*x +  31//6 :\n          3 ≤ x < 4 ?  1//2*x^3 - 11//2*x^2 + 39//2*x - 131//6 :\n          4 ≤ x ≤ 5 ? -1//6*x^3 +  5//2*x^2 - 25//2*x + 125//6 : 0//1*one(x)\nB₆ = x -> 2 ≤ x < 3 ?   1//6*x^3 -  1//1*x^2 +   2//1*x -    4//3 :\n          3 ≤ x < 4 ? -7//12*x^3 + 23//4*x^2 -  73//4*x + 227//12 :\n          4 ≤ x ≤ 5 ? 11//12*x^3 - 49//4*x^2 + 215//4*x - 925//12 : 0//1*one(x)\nB₇ = x -> 3 ≤ x < 4 ?  1//4*x^3 -  9//4*x^2 +  27//4*x -  27//4 :\n          4 ≤ x ≤ 5 ? -7//4*x^3 + 87//4*x^2 - 357//4*x + 485//4 : 0//1*one(x)\nB₈ = x -> 4 ≤ x ≤ 5 ? 1//1*x^3 - 12//1*x^2 + 48//1*x - 64//1 : 0//1*one(x)\n# 1st derivatives\nB₁′ = x -> 0 ≤ x < 1 ? -3//1*x^2 + 6//1*x - 3//1 : 0//1*one(x)\nB₂′ = x -> 0 ≤ x < 1 ? 21//4*x^2 - 9//1*x + 3//1 :\n           1 ≤ x < 2 ? -3//4*x^2 + 3//1*x - 3//1 : 0//1*one(x)\nB₃′ = x -> 0 ≤ x < 1 ? -11//4*x^2 + 3//1*x        :\n           1 ≤ x < 2 ?   7//4*x^2 - 6//1*x + 9//2 :\n           2 ≤ x < 3 ?  -1//2*x^2 + 3//1*x - 9//2 : 0//1*one(x)\nB₄′ = x -> 0 ≤ x < 1 ?  1//2*x^2                  :\n           1 ≤ x < 2 ? -3//2*x^2 + 4//1*x -  2//1 :\n           2 ≤ x < 3 ?  3//2*x^2 - 8//1*x + 10//1 :\n           3 ≤ x < 4 ? -1//2*x^2 + 4//1*x -  8//1 : 0//1*one(x)\nB₅′ = x -> 1 ≤ x < 2 ?  1//2*x^2 -  1//1*x +  1//2 :\n           2 ≤ x < 3 ? -3//2*x^2 +  7//1*x - 15//2 :\n           3 ≤ x < 4 ?  3//2*x^2 - 11//1*x + 39//2 :\n           4 ≤ x ≤ 5 ? -1//2*x^2 +  5//1*x - 25//2 : 0//1*one(x)\nB₆′ = x -> 2 ≤ x < 3 ?  1//2*x^2 -  2//1*x +   2//1 :\n           3 ≤ x < 4 ? -7//4*x^2 + 23//2*x -  73//4 :\n           4 ≤ x ≤ 5 ? 11//4*x^2 - 49//2*x + 215//4 : 0//1*one(x)\nB₇′ = x -> 3 ≤ x < 4 ?   3//4*x^2 -  9//2*x +  27//4 :\n           4 ≤ x ≤ 5 ? -21//4*x^2 + 87//2*x - 357//4 : 0//1*one(x)\nB₈′ = x -> 4 ≤ x ≤ 5 ? 3//1*x^2 - 24//1*x + 48//1 : 0//1*one(x)\n# 2nd derivatives\nB₁′′ = x -> 0 ≤ x < 1 ? -6//1*x + 6//1 : 0//1*one(x)\nB₂′′ = x -> 0 ≤ x < 1 ? 21//2*x - 9//1 :\n            1 ≤ x < 2 ? -3//2*x + 3//1 : 0//1*one(x)\nB₃′′ = x -> 0 ≤ x < 1 ? -11//2*x + 3//1 :\n            1 ≤ x < 2 ?   7//2*x - 6//1 :\n            2 ≤ x < 3 ?  -1//1*x + 3//1 : 0//1*one(x)\nB₄′′ = x -> 0 ≤ x < 1 ?  1//1*x        :\n            1 ≤ x < 2 ? -3//1*x + 4//1 :\n            2 ≤ x < 3 ?  3//1*x - 8//1 :\n            3 ≤ x < 4 ? -1//1*x + 4//1 : 0//1*one(x)\nB₅′′ = x -> 1 ≤ x < 2 ?  1//1*x -  1//1 :\n            2 ≤ x < 3 ? -3//1*x +  7//1 :\n            3 ≤ x < 4 ?  3//1*x - 11//1 :\n            4 ≤ x ≤ 5 ? -1//1*x +  5//1 : 0//1*one(x)\nB₆′′ = x -> 2 ≤ x < 3 ?  1//1*x -  2//1 :\n            3 ≤ x < 4 ? -7//2*x + 23//2 :\n            4 ≤ x ≤ 5 ? 11//2*x - 49//2 : 0//1*one(x)\nB₇′′ = x -> 3 ≤ x < 4 ?   3//2*x -  9//2 :\n            4 ≤ x ≤ 5 ? -21//2*x + 87//2 : 0//1*one(x)\nB₈′′ = x -> 4 ≤ x ≤ 5 ? 6//1*x - 24//1 : 0//1*one(x)\n# 3rd derivatives\nB₁′′′ = x -> 0 ≤ x < 1 ? -6//1 : 0//1*one(x)\nB₂′′′ = x -> 0 ≤ x < 1 ? 21//2 :\n             1 ≤ x < 2 ? -3//2 : 0//1*one(x)\nB₃′′′ = x -> 0 ≤ x < 1 ? -11//2 :\n             1 ≤ x < 2 ?   7//2 :\n             2 ≤ x < 3 ?  -1//1 : 0//1*one(x)\nB₄′′′ = x -> 0 ≤ x < 1 ?  1//1 :\n             1 ≤ x < 2 ? -3//1 :\n             2 ≤ x < 3 ?  3//1 :\n             3 ≤ x < 4 ? -1//1 : 0//1*one(x)\nB₅′′′ = x -> 1 ≤ x < 2 ?  1//1 :\n             2 ≤ x < 3 ? -3//1 :\n             3 ≤ x < 4 ?  3//1 :\n             4 ≤ x ≤ 5 ? -1//1 : 0//1*one(x)\nB₆′′′ = x -> 2 ≤ x < 3 ?  1//1 :\n             3 ≤ x < 4 ? -7//2 :\n             4 ≤ x ≤ 5 ? 11//2 : 0//1*one(x)\nB₇′′′ = x -> 3 ≤ x < 4 ?   3//2 :\n             4 ≤ x ≤ 5 ? -21//2 : 0//1*one(x)\nB₈′′′ = x -> 4 ≤ x ≤ 5 ? 6//1 : 0//1*one(x)\n\nb4_exact = [B₁ B₁′ B₁′′ B₁′′′; B₂ B₂′ B₂′′ B₂′′′; B₃ B₃′ B₃′′ B₃′′′; B₄ B₄′ B₄′′ B₄′′′;\n            B₅ B₅′ B₅′′ B₅′′′; B₆ B₆′ B₆′′ B₆′′′; B₇ B₇′ B₇′′ B₇′′′; B₈ B₈′ B₈′′ B₈′′′]\n\nb5 = BSplineBasis(3, [-5.0, -3.5, -2.2, 1.0, 2.0, 3.6])\n\n# The exact B-spline functions are for the breakpoint sequence [-5, -7//2, -11//5, 1, 2, 18//5].\n# Note that this is not exactly equal to [-5.0, -3.5, -2.2, 1.0, 2.0, 3.6], because the\n# floating-point representations of -11//5 and 18//5 are not exact.\nB₁ = x -> -5.0 ≤ x < -3.5 ? 4//9*x^2 + 28//9*x + 49//9 : 0//1*one(x)\nB₂ = x -> -5.0 ≤ x < -3.5 ? -43//63*x^2 - 346//63*x - 655//63 :\n          -3.5 ≤ x < -2.2 ?  25//91*x^2 + 110//91*x + 121//91 : 0//1*one(x)\nB₃ = x -> -5.0 ≤ x < -3.5 ?     5//21*x^2 +    50//21*x +   125//21 :\n          -3.5 ≤ x < -2.2 ? -365//819*x^2 - 1970//819*x - 1985//819 :\n          -2.2 ≤ x <  1.0 ?     5//72*x^2 -     5//36*x +     5//72 : 0//1*one(x)\nB₄ = x -> -3.5 ≤ x < -2.2 ?    20//117*x^2 + 140//117*x +  245//117 :\n          -2.2 ≤ x <  1.0 ? -145//1008*x^2 -  95//504*x + 575//1008 :\n           1.0 ≤ x <  2.0 ?      5//21*x^2 -   20//21*x +    20//21 : 0//1*one(x)\nB₅ = x -> -2.2 ≤ x < 1.0 ?   25//336*x^2 +  55//168*x + 121//336 :\n           1.0 ≤ x < 2.0 ? -170//273*x^2 + 470//273*x -  92//273 :\n           2.0 ≤ x ≤ 3.6 ?   25//104*x^2 -   45//26*x +   81//26 : 0//1*one(x)\nB₆ = x ->  1.0 ≤ x < 2.0 ?     5//13*x^2 -   10//13*x +    5//13 :\n           2.0 ≤ x ≤ 3.6 ? -525//832*x^2 + 685//208*x - 765//208 : 0//1*one(x)\nB₇ = x ->  2.0 ≤ x ≤ 3.6 ? 25//64*x^2 - 25//16*x + 25//16 : 0//1*one(x)\n# 1st derivatives\nB₁′ = x -> -5.0 ≤ x < -3.5 ? 8//9*x + 28//9 : 0//1*one(x)\nB₂′ = x -> -5.0 ≤ x < -3.5 ? -86//63*x - 346//63 :\n           -3.5 ≤ x < -2.2 ?  50//91*x + 110//91 : 0//1*one(x)\nB₃′ = x -> -5.0 ≤ x < -3.5 ?    10//21*x +    50//21 :\n           -3.5 ≤ x < -2.2 ? -730//819*x - 1970//819 :\n           -2.2 ≤ x <  1.0 ?     5//36*x -     5//36 : 0//1*one(x)\nB₄′ = x -> -3.5 ≤ x < -2.2 ?   40//117*x + 140//117 :\n           -2.2 ≤ x <  1.0 ? -145//504*x -  95//504 :\n            1.0 ≤ x <  2.0 ?    10//21*x -   20//21 : 0//1*one(x)\nB₅′ = x -> -2.2 ≤ x < 1.0 ?   25//168*x +  55//168 :\n            1.0 ≤ x < 2.0 ? -340//273*x + 470//273 :\n            2.0 ≤ x ≤ 3.6 ?    25//52*x -   45//26 : 0//1*one(x)\nB₆′ = x ->  1.0 ≤ x < 2.0 ?    10//13*x -   10//13 :\n            2.0 ≤ x ≤ 3.6 ? -525//416*x + 685//208 : 0//1*one(x)\nB₇′ = x ->  2.0 ≤ x ≤ 3.6 ? 25//32*x - 25//16 : 0//1*one(x)\n# 2nd derivatives\nB₁′′ = x -> -5.0 ≤ x < -3.5 ? 8//9*one(x) : 0//1*one(x)\nB₂′′ = x -> -5.0 ≤ x < -3.5 ? -86//63*one(x) :\n            -3.5 ≤ x < -2.2 ?  50//91*one(x) : 0//1*one(x)\nB₃′′ = x -> -5.0 ≤ x < -3.5 ?    10//21*one(x) :\n            -3.5 ≤ x < -2.2 ? -730//819*one(x) :\n            -2.2 ≤ x <  1.0 ?     5//36*one(x) : 0//1*one(x)\nB₄′′ = x -> -3.5 ≤ x < -2.2 ?   40//117*one(x) :\n            -2.2 ≤ x <  1.0 ? -145//504*one(x) :\n             1.0 ≤ x <  2.0 ?    10//21*one(x) : 0//1*one(x)\nB₅′′ = x -> -2.2 ≤ x < 1.0 ?   25//168*one(x) :\n             1.0 ≤ x < 2.0 ? -340//273*one(x) :\n             2.0 ≤ x ≤ 3.6 ?    25//52*one(x) : 0//1*one(x)\nB₆′′ = x ->  1.0 ≤ x < 2.0 ?    10//13*one(x) :\n             2.0 ≤ x ≤ 3.6 ? -525//416*one(x) : 0//1*one(x)\nB₇′′ = x ->  2.0 ≤ x ≤ 3.6 ? 25//32*one(x) : 0//1*one(x)\n\nb5_exact = [B₁ B₁′ B₁′′; B₂ B₂′ B₂′′; B₃ B₃′ B₃′′; B₄ B₄′ B₄′′; B₅ B₅′ B₅′′; B₆ B₆′ B₆′′; B₇ B₇′ B₇′′]\n\nb6 = BSplineBasis(4, Rational{Int64}[-5//1, -7//2, -11//5, 1//1, 2//1, 18//5])\n\nB₁ = x ->  -5//1 ≤ x <  -7//2 ? -8//27*x^3 - 28//9*x^2 - 98//9*x - 343//27 : 0//1*one(x)\nB₂ = x ->  -5//1 ≤ x <  -7//2 ? 1429//2646*x^3 + 5339//882*x^2 + 19429//882*x + 69635//2646 :\n           -7//2 ≤ x < -11//5 ? -125//1274*x^3 - 825//1274*x^2 - 1815//1274*x -  1331//1274 : 0//1*one(x)\nB₃ = x ->  -5//1 ≤ x <  -7//2 ?   -125//441*x^3 -   520//147*x^2 -   2075//147*x -    7750//441 :\n           -7//2 ≤ x < -11//5 ? 2965//17199*x^3 + 7160//5733*x^2 + 15115//5733*x + 33890//17199 :\n          -11//5 ≤ x <   1//1 ?     -5//432*x^3 +     5//144*x^2 -      5//144*x +       5//432 : 0//1*one(x)\nB₄ = x ->  -5//1 ≤ x <  -7//2 ?       5//126*x^3 +       25//42*x^2 +      125//42*x +     625//126 :\n           -7//2 ≤ x < -11//5 ? -5695//54054*x^3 - 16715//18018*x^2 - 42415//18018*x - 68015//54054 :\n          -11//5 ≤ x <   1//1 ?  1255//33264*x^3 +   185//11088*x^2 -  3065//11088*x +  8825//33264 :\n            1//1 ≤ x <   2//1 ?     -10//231*x^3 +       20//77*x^2 -       40//77*x +      80//231 : 0//1*one(x)\nB₅ = x ->  -7//2 ≤ x < -11//5 ?       40//1287*x^3 +      140//429*x^2 +      490//429*x +     1715//1287 :\n          -11//5 ≤ x <   1//1 ? -12535//321552*x^3 - 14585//107184*x^2 + 13385//107184*x + 188599//321552 :\n            1//1 ≤ x <   2//1 ?   13120//87087*x^3 -  20465//29029*x^2 +  20140//29029*x +   34564//87087 :\n            2//1 ≤ x ≤  18//5 ?     -125//3016*x^3 +     675//1508*x^2 -     1215//754*x +       729//377 : 0//1*one(x)\nB₆ = x -> -11//5 ≤ x <   1//1 ?      125//9744*x^3 +      275//3248*x^2 +     605//3248*x +    1331//9744 :\n            1//1 ≤ x <   2//1 ? -26275//102921*x^3 +   30500//34307*x^2 -  21205//34307*x + 41654//102921 :\n            2//1 ≤ x ≤  18//5 ?  89125//313664*x^3 - 368175//156832*x^2 + 459135//78416*x - 153333//39208 : 0//1*one(x)\nB₇ = x ->   1//1 ≤ x <   2//1 ?       25//169*x^3 -       75//169*x^2 +       75//169*x -      25//169 :\n            2//1 ≤ x <  18//5 ? -42125//86528*x^3 + 145575//43264*x^2 - 155175//21632*x + 53325//10816 : 0//1*one(x)\nB₈ = x ->   2//1 ≤ x ≤  18//5 ? 125//512*x^3 - 375//256*x^2 + 375//128*x - 125//64 : 0//1*one(x)\n# 1st derivatives\nB₁′ = x ->  -5//1 ≤ x <  -7//2 ? -8//9*x^2 - 56//9*x - 98//9 : 0//1*one(x)\nB₂′ = x ->  -5//1 ≤ x <  -7//2 ?  1429//882*x^2 + 5339//441*x + 19429//882 :\n            -7//2 ≤ x < -11//5 ? -375//1274*x^2 -  825//637*x - 1815//1274 : 0//1*one(x)\nB₃′ = x ->  -5//1 ≤ x <  -7//2 ?  -125//147*x^2 -   1040//147*x -   2075//147 :\n            -7//2 ≤ x < -11//5 ? 2965//5733*x^2 + 14320//5733*x + 15115//5733 :\n           -11//5 ≤ x <   1//1 ?    -5//144*x^2 +       5//72*x -      5//144 : 0//1*one(x)\nB₄′ = x ->  -5//1 ≤ x <  -7//2 ?        5//42*x^2 +      25//21*x +      125//42 :\n            -7//2 ≤ x < -11//5 ? -5695//18018*x^2 - 16715//9009*x - 42415//18018 :\n           -11//5 ≤ x <   1//1 ?  1255//11088*x^2 +   185//5544*x -  3065//11088 :\n             1//1 ≤ x <   2//1 ?      -10//77*x^2 +      40//77*x -       40//77 : 0//1*one(x)\nB₅′ = x ->  -7//2 ≤ x < -11//5 ?        40//429*x^2 +     280//429*x +      490//429 :\n           -11//5 ≤ x <   1//1 ? -12535//107184*x^2 - 14585//53592*x + 13385//107184 :\n             1//1 ≤ x <   2//1 ?   13120//29029*x^2 - 40930//29029*x +  20140//29029 :\n             2//1 ≤ x ≤  18//5 ?     -375//3016*x^2 +     675//754*x -     1215//754 : 0//1*one(x)\nB₆′ = x -> -11//5 ≤ x <   1//1 ?      125//3248*x^2 +     275//1624*x +     605//3248 :\n             1//1 ≤ x <   2//1 ?  -26275//34307*x^2 +  61000//34307*x -  21205//34307 :\n             2//1 ≤ x ≤  18//5 ? 267375//313664*x^2 - 368175//78416*x + 459135//78416 : 0//1*one(x)\nB₇′ = x ->   1//1 ≤ x <   2//1 ?        75//169*x^2 -      150//169*x +       75//169 :\n             2//1 ≤ x ≤  18//5 ? -126375//86528*x^2 + 145575//21632*x - 155175//21632 : 0//1*one(x)\nB₈′ = x ->   2//1 ≤ x ≤  18//5 ? 375//512*x^2 - 375//128*x + 375//128 : 0//1*one(x)\n# 2nd derivatives\nB₁′′ = x ->  -5//1 ≤ x <  -7//2 ? -16//9*x - 56//9 : 0//1*one(x)\nB₂′′ = x ->  -5//1 ≤ x <  -7//2 ? 1429//441*x + 5339//441 :\n             -7//2 ≤ x < -11//5 ? -375//637*x -  825//637 : 0//1*one(x)\nB₃′′ = x ->  -5//1 ≤ x <  -7//2 ?  -250//147*x -   1040//147 :\n             -7//2 ≤ x < -11//5 ? 5930//5733*x + 14320//5733 :\n            -11//5 ≤ x <   1//1 ?     -5//72*x +       5//72 : 0//1*one(x)\nB₄′′ = x ->  -5//1 ≤ x <  -7//2 ?       5//21*x +      25//21 :\n             -7//2 ≤ x < -11//5 ? -5695//9009*x - 16715//9009 :\n            -11//5 ≤ x <   1//1 ?  1255//5544*x +   185//5544 :\n              1//1 ≤ x <   2//1 ?     -20//77*x +      40//77 : 0//1*one(x)\nB₅′′ = x ->  -7//2 ≤ x < -11//5 ?       80//429*x +     280//429 :\n            -11//5 ≤ x <   1//1 ? -12535//53592*x - 14585//53592 :\n              1//1 ≤ x <   2//1 ?  26240//29029*x - 40930//29029 :\n              2//1 ≤ x ≤  18//5 ?    -375//1508*x +     675//754 : 0//1*one(x)\nB₆′′ = x -> -11//5 ≤ x <   1//1 ?      125//1624*x +     275//1624 :\n              1//1 ≤ x <   2//1 ?  -52550//34307*x +  61000//34307 :\n              2//1 ≤ x ≤  18//5 ? 267375//156832*x - 368175//78416 : 0//1*one(x)\nB₇′′ = x ->   1//1 ≤ x <   2//1 ?       150//169*x -      150//169 :\n              2//1 ≤ x ≤  18//5 ? -126375//43264*x + 145575//21632 : 0//1*one(x)\nB₈′′ = x ->   2//1 ≤ x ≤  18//5 ? 375//256*x - 375//128 : 0//1*one(x)\n# 3rd derivative\nB₁′′′ = x ->  -5//1 ≤ x <  -7//2 ? -16//9*one(x) : 0//1*one(x)\nB₂′′′ = x ->  -5//1 ≤ x <  -7//2 ? 1429//441*one(x) :\n              -7//2 ≤ x < -11//5 ? -375//637*one(x) : 0//1*one(x)\nB₃′′′ = x ->  -5//1 ≤ x <  -7//2 ?  -250//147*one(x) :\n              -7//2 ≤ x < -11//5 ? 5930//5733*one(x) :\n             -11//5 ≤ x <   1//1 ?     -5//72*one(x) : 0//1*one(x)\nB₄′′′ = x ->  -5//1 ≤ x <  -7//2 ?       5//21*one(x) :\n              -7//2 ≤ x < -11//5 ? -5695//9009*one(x) :\n             -11//5 ≤ x <   1//1 ?  1255//5544*one(x) :\n               1//1 ≤ x <   2//1 ?     -20//77*one(x) : 0//1*one(x)\nB₅′′′ = x ->  -7//2 ≤ x < -11//5 ?       80//429*one(x) :\n             -11//5 ≤ x <   1//1 ? -12535//53592*one(x) :\n               1//1 ≤ x <   2//1 ?  26240//29029*one(x) :\n               2//1 ≤ x ≤  18//5 ?    -375//1508*one(x) : 0//1*one(x)\nB₆′′′ = x -> -11//5 ≤ x <   1//1 ?      125//1624*one(x) :\n               1//1 ≤ x <   2//1 ?  -52550//34307*one(x) :\n               2//1 ≤ x ≤  18//5 ? 267375//156832*one(x) : 0//1*one(x)\nB₇′′′ = x ->   1//1 ≤ x <   2//1 ?       150//169*one(x) :\n               2//1 ≤ x ≤  18//5 ? -126375//43264*one(x) : 0//1*one(x)\nB₈′′′ = x ->   2//1 ≤ x ≤  18//5 ? 375//256*one(x) : 0//1*one(x)\n\nb6_exact = [B₁ B₁′ B₁′′ B₁′′′; B₂ B₂′ B₂′′ B₂′′′; B₃ B₃′ B₃′′ B₃′′′; B₄ B₄′ B₄′′ B₄′′′;\n            B₅ B₅′ B₅′′ B₅′′′; B₆ B₆′ B₆′′ B₆′′′; B₇ B₇′ B₇′′ B₇′′′; B₈ B₈′ B₈′′ B₈′′′]\n\nb7 = BSplineBasis(3, Int8[-6,-4,-2,0,0,1,2])\n\nB₁ = x -> -6 ≤ x < -4 ? 1//4*x^2 + 2//1*x + 4//1 : 0//1*one(x)\nB₂ = x -> -6 ≤ x < -4 ? -3//8*x^2 - 7//2*x - 15//2 :\n          -4 ≤ x < -2 ?  1//8*x^2 + 1//2*x +  1//2 : 0//1*one(x)\nB₃ = x -> -6 ≤ x < -4 ?  1//8*x^2 + 3//2*x + 9//2 :\n          -4 ≤ x < -2 ? -1//4*x^2 - 3//2*x - 3//2 :\n          -2 ≤ x <  0 ?  1//8*x^2                 : 0//1*one(x)\nB₄ = x -> -4 ≤ x < -2 ?  1//8*x^2 + 1//1*x + 2//1 :\n          -2 ≤ x <  0 ? -3//8*x^2 - 1//1*x        : 0//1*one(x)\nB₅ = x -> -2 ≤ x <  0 ? 1//4*x^2 + 1//1*x + 1//1 :\n           0 ≤ x <  1 ? 1//1*x^2 - 2//1*x + 1//1 : 0//1*one(x)\nB₆ = x ->  0 ≤ x <  1 ? -3//2*x^2 + 2//1*x        :\n           1 ≤ x ≤  2 ?  1//2*x^2 - 2//1*x + 2//1 : 0//1*one(x)\nB₇ = x ->  0 ≤ x <  1 ?  1//2*x^2                 :\n           1 ≤ x ≤  2 ? -3//2*x^2 + 4//1*x - 2//1 : 0//1*one(x)\nB₈ = x ->  1 ≤ x ≤  2 ? 1//1*x^2 - 2//1*x + 1//1 : 0//1*one(x)\n# 1st derivatives\nB₁′ = x -> -6 ≤ x < -4 ? 1//2*x + 2//1 : 0//1*one(x)\nB₂′ = x -> -6 ≤ x < -4 ? -3//4*x - 7//2 :\n           -4 ≤ x < -2 ?  1//4*x + 1//2 : 0//1*one(x)\nB₃′ = x -> -6 ≤ x < -4 ?  1//4*x + 3//2 :\n           -4 ≤ x < -2 ? -1//2*x - 3//2 :\n           -2 ≤ x <  0 ?  1//4*x        : 0//1*one(x)\nB₄′ = x -> -4 ≤ x < -2 ?  1//4*x + 1//1 :\n           -2 ≤ x <  0 ? -3//4*x - 1//1 : 0//1*one(x)\nB₅′ = x -> -2 ≤ x <  0 ? 1//2*x + 1//1 :\n            0 ≤ x <  1 ? 2//1*x - 2//1 : 0//1*one(x)\nB₆′ = x ->  0 ≤ x <  1 ? -3//1*x + 2//1 :\n            1 ≤ x ≤  2 ?  1//1*x - 2//1 : 0//1*one(x)\nB₇′ = x ->  0 ≤ x <  1 ?  1//1*x        :\n            1 ≤ x ≤  2 ? -3//1*x + 4//1 : 0//1*one(x)\nB₈′ = x ->  1 ≤ x ≤  2 ? 2//1*x - 2//1 : 0//1*one(x)\n# 2nd derivatives\nB₁′′ = x -> -6 ≤ x < -4 ? 1//2*one(x) : 0//1*one(x)\nB₂′′ = x -> -6 ≤ x < -4 ? -3//4*one(x) :\n            -4 ≤ x < -2 ?  1//4*one(x) : 0//1*one(x)\nB₃′′ = x -> -6 ≤ x < -4 ?  1//4*one(x) :\n            -4 ≤ x < -2 ? -1//2*one(x) :\n            -2 ≤ x <  0 ?  1//4*one(x) : 0//1*one(x)\nB₄′′ = x -> -4 ≤ x < -2 ?  1//4*one(x) :\n            -2 ≤ x <  0 ? -3//4*one(x) : 0//1*one(x)\nB₅′′ = x -> -2 ≤ x <  0 ? 1//2*one(x) :\n             0 ≤ x <  1 ? 2//1*one(x) : 0//1*one(x)\nB₆′′ = x ->  0 ≤ x <  1 ? -3//1*one(x) :\n             1 ≤ x ≤  2 ?  1//1*one(x) : 0//1*one(x)\nB₇′′ = x ->  0 ≤ x <  1 ?  1//1*one(x) :\n             1 ≤ x ≤  2 ? -3//1*one(x) : 0//1*one(x)\nB₈′′ = x ->  1 ≤ x ≤  2 ? 2//1*one(x) : 0//1*one(x)\n\nb7_exact = [B₁ B₁′ B₁′′; B₂ B₂′ B₂′′; B₃ B₃′ B₃′′; B₄ B₄′ B₄′′; B₅ B₅′ B₅′′; B₆ B₆′ B₆′′; B₇ B₇′ B₇′′; B₈ B₈′ B₈′′]\n\n# Compare arrays element-wise, and use a non-zero atol\n≈ₑₗ(x::AbstractArray, y::AbstractArray) = all(x .≈ₑₗ y)\n≈ₑₗ(x::Number, y::Number) = isapprox(x, y; atol=1e-15, rtol = Base.rtoldefault(x,y,0))\n", "meta": {"hexsha": "88bcf4b0c96cc76a7192bcca92dd181729e133d9", "size": 20614, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/bases.jl", "max_stars_repo_name": "sostock/BSplines.jl", "max_stars_repo_head_hexsha": "c76eb279f1ea0c309058f49c9eaec438da88ff7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-04-13T12:31:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T07:34:39.000Z", "max_issues_repo_path": "test/bases.jl", "max_issues_repo_name": "sostock/BSplines.jl", "max_issues_repo_head_hexsha": "c76eb279f1ea0c309058f49c9eaec438da88ff7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2020-04-26T15:47:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T18:52:24.000Z", "max_forks_repo_path": "test/bases.jl", "max_forks_repo_name": "sostock/BSplines.jl", "max_forks_repo_head_hexsha": "c76eb279f1ea0c309058f49c9eaec438da88ff7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-28T21:08:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-02T12:28:11.000Z", "avg_line_length": 54.6790450928, "max_line_length": 119, "alphanum_fraction": 0.3445231396, "num_tokens": 11429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191284552528, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.7601074003862196}}
{"text": "# Benchmark script for comparing the convergence rate of GD, BiasSEGA, and SEGA\n# for minimizing a multivariate quadratic on the unit ball\n\nusing Random, LinearAlgebra\n\nfunction main(n=10, γ=1/(2n), niterations=30)\n\n    Random.seed!(123)\n    Q = Symmetric(randn(n, n))\n    c = randn(n)\n    f = (x) -> x'*Q*x ./ 2 .+ c'*x\n    ∇ = (x) -> Q*x .+ c\n\n    xgd = zeros(n, niterations)\n    xbias = zeros(n, niterations)\n    xsega = zeros(n, niterations)\n\n    bsega = BiasSEGA(n)\n    sega = SEGA(n)\n\n    s = zeros(n)\n    for i in 2:niterations\n        # GD\n        xgd[:, i] .= xgd[:, i-1] .- γ.*∇(xgd[:, i-1])\n        xgd[:, i] ./= norm(xgd[:, i])\n\n        # BiasSEGA\n        s .= randn(n)\n        project!(bsega, dot(s, ∇(xbias[:, i-1])), s)\n        xbias[:, i] .= xbias[:, i-1] .- γ.*gradient(bsega)\n        xbias[:, i] ./= norm(xbias[:, i])        \n\n        # SEGA\n        project!(sega, 1/n, dot(s, ∇(xsega[:, i-1])), s)\n        unbias!(sega)\n        xsega[:, i] .= xsega[:, i-1] .- γ.*gradient(sega)\n        xsega[:, i] ./= norm(xsega[:, i])        \n    end\n\n    println(\"GD \\t BiasSEGA \\t SEGA\")\n    for i in 2:niterations\n        println(\"$(f(xgd[:, i])) \\t $(f(xbias[:, i])) \\t $(f(xsega[:, i]))\")\n    end\nend", "meta": {"hexsha": "ce9d69eb33638a183afbd27a12ee1aabcb119439", "size": 1209, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmark.jl", "max_stars_repo_name": "severinson/GradientSketching.jl", "max_stars_repo_head_hexsha": "8fd6ca672ac1475d280a52ab27ad88172e11e99d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmark.jl", "max_issues_repo_name": "severinson/GradientSketching.jl", "max_issues_repo_head_hexsha": "8fd6ca672ac1475d280a52ab27ad88172e11e99d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark.jl", "max_forks_repo_name": "severinson/GradientSketching.jl", "max_forks_repo_head_hexsha": "8fd6ca672ac1475d280a52ab27ad88172e11e99d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4772727273, "max_line_length": 79, "alphanum_fraction": 0.4954507858, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7600894556900587}}
{"text": "export DS, run_lt_test\nconst DS = DirectSearch\n\n\n#= Following functions sourced from https://www.sfu.ca/~ssurjano/optimization.html =#\n#Valley\n#soln: -1.0316 @ [±0.0898, ∓0.7126]\ncamel6(x)=(4-2.1x[1]^2.0 + x[1]^4/3)x[1]^2.0 + x[1]x[2] + (-4 + 4x[2]^2.0)x[2]^2.0\n#soln: 0 @ [1,...,1]\nrosenbrock(x;a=1,b=100,d=length(x)) = sum([b*(x[i+1] - x[i]^2)^2 + (x[i]-a)^2 for i=1:d-1])\n\n#Local Minima\nackley(x;a=20,b=0.2,c=2pi,d=length(x)) = -a * exp(-b*√(sum(x.^2)/d)) - exp(sum(cos.(c.*x))/d) + a + exp(1)\neggholder(x) = -(x[2]+47)sin(√abs(x[2] + x[1]/2 + 47)) - x[1]sin(√abs(x[1]-x[2]+47))\n\n#Example Benchmarks from papers\n#Audet & Dennis 2006 benchmark one, take x₀=[-2.1,1.7]\n#soln: 0 @ [0,0]\nbm_1(x;c=[30;40],d=[-30;-40]) = (1-exp(-norm(x)^2)) * max(norm(x-c)^2, norm(x-d)^2)\n\n#Audet & Dennis 2006 benchmark three, should take x₀=[0,...,0]\n#soln: -√(3)n @ [-√3,...,-√3]\nbm_3(x)=sum(x)\nbm_3_con(x)=sum(x.^2)-3*length(x)\n\nfunction run_lt_test(;f=camel6,n=2,\n                     constraints::Vector=[],\n                     initial=zeros(Float64,n),\n                     lim=1000,\n                     lb=-5*ones(Float64,n), \n                     ub=5*ones(Float64,n),\n                     run=true)\n    p = DSProblem(n)\n    SetObjective(p, f)\n    SetInitialPoint(p, initial)\n    SetMaxEvals(p, 1)\n    for c in constraints\n        AddExtremeConstraint(p, c)\n    end\n    p.iteration_limit = lim\n    SetVariableRanges(p, lb, ub)\n    if run\n        DS.Optimize!(p)\n        println(\"$(p.iteration)\\t$(p.x)\\t$(p.x_cost)\")\n    end\n    return p\nend\n\n", "meta": {"hexsha": "890112bfc0bfbf532222d19f7e3782ce6312a184", "size": 1536, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/test_utils.jl", "max_stars_repo_name": "imciner2/DirectSearch.jl", "max_stars_repo_head_hexsha": "d13df50686b07f35e8676214b43baf88ddbbc53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-09T02:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T09:42:04.000Z", "max_issues_repo_path": "src/test_utils.jl", "max_issues_repo_name": "imciner2/DirectSearch.jl", "max_issues_repo_head_hexsha": "d13df50686b07f35e8676214b43baf88ddbbc53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-08-20T18:01:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T23:13:36.000Z", "max_forks_repo_path": "src/test_utils.jl", "max_forks_repo_name": "imciner2/DirectSearch.jl", "max_forks_repo_head_hexsha": "d13df50686b07f35e8676214b43baf88ddbbc53d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-09-02T17:21:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T13:40:48.000Z", "avg_line_length": 31.3469387755, "max_line_length": 106, "alphanum_fraction": 0.5397135417, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359676, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7600894530433108}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.0\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 0a57947c-3a56-11ec-1341-534834850daf\nmd\"\"\"\n# Chapter 1\n## Section 3\n\"\"\"\n\n# ╔═╡ 8fcfe29e-049c-4df3-9d4b-325d3f4e171e\nfunction newton(f, fp, x0, tol)\n\tx = x0\n\twhile abs(f(x)) > tol\n\t\tx = x - f(x) / fp(x)\n\tend\n\tx\nend\n\n# ╔═╡ 74555744-e6a7-47bd-96b9-7e8909664f42\nnewton(x -> x^2 - 5., x -> 2. * x, 1., 10e-6)\n\n# ╔═╡ 40d3098f-4b1b-4ca1-be89-5eb9a18ef3a8\nfunction secant(f, x0, x1, tol)\n\tx = x0\n\txx = x1\n\twhile abs(f(xx)) > tol\n\t\ttmp = xx\n\t\txx = xx - f(xx) * (xx - x) / (f(xx) - f(x))\n\t\tx = xx\n\tend\n\txx\nend\n\n# ╔═╡ 7d023bfd-53fb-46a1-84dc-1c34519387dc\nsecant(x -> x^2 - 5., 2, 2.3, 10e-6)\n# Well ... I'm definitly not got at finding roots\n\n# ╔═╡ Cell order:\n# ╟─0a57947c-3a56-11ec-1341-534834850daf\n# ╠═8fcfe29e-049c-4df3-9d4b-325d3f4e171e\n# ╠═74555744-e6a7-47bd-96b9-7e8909664f42\n# ╠═40d3098f-4b1b-4ca1-be89-5eb9a18ef3a8\n# ╠═7d023bfd-53fb-46a1-84dc-1c34519387dc\n", "meta": {"hexsha": "744420a8444c20cb0aa0eab8a1e9310c533cea0d", "size": 939, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "roots.jl", "max_stars_repo_name": "zazbone/ComputationalPhysics", "max_stars_repo_head_hexsha": "be3c4dd0b75fefb71aab5ccbd91fa1a5e837b598", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "roots.jl", "max_issues_repo_name": "zazbone/ComputationalPhysics", "max_issues_repo_head_hexsha": "be3c4dd0b75fefb71aab5ccbd91fa1a5e837b598", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "roots.jl", "max_forks_repo_name": "zazbone/ComputationalPhysics", "max_forks_repo_head_hexsha": "be3c4dd0b75fefb71aab5ccbd91fa1a5e837b598", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9787234043, "max_line_length": 49, "alphanum_fraction": 0.6368477103, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218434359676, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7600894530433108}}
{"text": "\n\n\"\"\"\nCosine taper a N-dimensional array along given dimensions.\n\n# Arguments\n* `x::Array{Float64,N}` : \n* `perc::Float64` : taper percentage\n\"\"\"\nfunction taper(x::AbstractArray,perc::Float64;dims=[1])\n\txout=copy(x);\n\ttaper!(xout,perc,dims=dims)\n\treturn xout\nend\n\n\"\"\"\n# no allocations\n* `dims=[1]` : taper along these dimensions (default only first)\n\"\"\"\nfunction taper!(x, perc=0.0; bperc=perc, eperc=perc, dims=[1])\n\tfor dim in dims\n\t\tnt=size(x,dim)\n\t\tnttb=min(round(Int,nt*bperc*0.01), nt)\n\t\tntte=min(round(Int,nt*eperc*0.01), nt)\n\t\tkb=inv(2.0*round(Int,nt*bperc*0.01)-1)*pi\n\t\tke=inv(2.0*round(Int,nt*eperc*0.01)-1)*pi\n\t\tfor i in CartesianIndices(size(x))\n\t\t\tif(1≤i[dim]≤nttb)\n\t\t\t\tx[i] *= sin((i[dim]-1)*kb)\n\t\t\tend\n\t\t\tif(nt-ntte+1≤i[dim]≤nt)\n\t\t\t\tx[i] *= sin((-i[dim]+nt)*ke)\n\t\t\tend\n\t\tend\n\tend\nend\n\n\n\n\"\"\"\nTapering is necessary to be able to input random signal into finite-difference code\nFiltering tapering are applied only if the length of the time series is greater than 10\n\"\"\"\nfunction get_tapered_random_tmax_signal(tgrid; \n\t\t\t\t\tfmin=nothing,\n\t\t\t\t\tfmax=nothing,\n\t\t\t\t\ttmaxfrac::Float64=1.0,\n\t\t\t\t\tdist=Uniform(-2.0, 2.0),\n\t\t\t\t\tsparsep=1.0,\n\t\t\t\t\ttaperperc=20.\n\t\t\t\t\t)\n\tfilt_flag=(length(tgrid) > 5) && (!(fmin === nothing)) && (!(fmax===nothing))\n\n\tfs = inv(step(tgrid));\n\tif(filt_flag)\n\t\tdesignmethod = Butterworth(6);\n\t\tfiltsource = Bandpass(fmin, fmax; fs=fs);\n\tend\n\n\titind = argmin(abs.(tgrid.-abs(tmaxfrac)*tgrid[end]))\n\tif(tmaxfrac>0.0)\n\t\tits=1:itind\n\telseif(tmaxfrac<0.0)\n\t\tits=itind:length(tgrid)\n\tend\n\t# 20% taper window\n\ttwin = taper(ones(length(its)),taperperc) \n\tX = zeros(length(its))\n\twavsrc = zeros(length(tgrid)) \n\tif(filt_flag) \n\t\tX[:] = rand(dist, length(its)) .* twin\n\telse\n\t\tX[:] = rand(dist, length(its))\n\tend\n\tif(sparsep ≠ 1.0)\n\t\tXs=sprandn(length(X), sparsep)\n\t\tX[findall(Xs.==0.0)].=0.0\n\tend\n\t# band limit\n\t(filt_flag) && (filt!(X, digitalfilter(filtsource, designmethod), X))\n\t\n\t(length(X) ≠ 1) && normalize!(X)\n\twavsrc[its] = X\n\treturn wavsrc\nend\n\n\n", "meta": {"hexsha": "d5881b7f7bf6e7c4d9844947f1a57575db012efa", "size": 1977, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Utils/taper.jl", "max_stars_repo_name": "ayushinav/GeoPhyInv.jl", "max_stars_repo_head_hexsha": "b0ce642161cb5300e2e7a5bd737b58fe37ddbfeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-01-05T04:30:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-26T18:32:37.000Z", "max_issues_repo_path": "src/Utils/taper.jl", "max_issues_repo_name": "ayushinav/GeoPhyInv.jl", "max_issues_repo_head_hexsha": "b0ce642161cb5300e2e7a5bd737b58fe37ddbfeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-11-14T19:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-16T19:55:36.000Z", "max_forks_repo_path": "src/Utils/taper.jl", "max_forks_repo_name": "ayushinav/GeoPhyInv.jl", "max_forks_repo_head_hexsha": "b0ce642161cb5300e2e7a5bd737b58fe37ddbfeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-08-15T14:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T21:18:19.000Z", "avg_line_length": 22.4659090909, "max_line_length": 87, "alphanum_fraction": 0.6494688923, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.760089452152738}}
{"text": "loadcrabs(filename) = parse.(Int, split(readchomp(filename), ','))\n\nif basename(pwd()) == \"aoc\"\n    cd(\"2021/7\")\nend\nexamplecrabs = loadcrabs(\"example.txt\")\ninputcrabs = loadcrabs(\"input.txt\")\n\nusing Statistics\npart1(crabs) = sum(abs.(crabs .- median(crabs)))\npart1(inputcrabs) # 331067\n\ntriangle(n) = n * (n + 1) ÷ 2\noffset(a, b) = triangle(abs(a - b))\n\nfunction part2(crabs)\n    minimum(sum(offset(x, n) for x in crabs) for n in range(extrema(crabs)...))\nend\n", "meta": {"hexsha": "f89b48fbcf8a6e4f15134f81f34aaadc616bedf1", "size": 461, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2021/7/7.jl", "max_stars_repo_name": "stellartux/advent-of-code", "max_stars_repo_head_hexsha": "03e666a44fd61da64e293b556b3cc7ea8e608489", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2021/7/7.jl", "max_issues_repo_name": "stellartux/advent-of-code", "max_issues_repo_head_hexsha": "03e666a44fd61da64e293b556b3cc7ea8e608489", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2021/7/7.jl", "max_forks_repo_name": "stellartux/advent-of-code", "max_forks_repo_head_hexsha": "03e666a44fd61da64e293b556b3cc7ea8e608489", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2631578947, "max_line_length": 79, "alphanum_fraction": 0.6637744035, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7600894506035994}}
{"text": "function distances(resids::Array{Float64,1}, fitteds::Array{Float64})::Array{Float64,2}\n    n = length(resids)\n    d = zeros(Float64, n, n)\n    @inbounds for i in 1:n\n        for j in i:n\n            if i != j \n                p1 = [resids[i], fitteds[i]]\n                p2 = [resids[j], fitteds[j]]\n                d[i, j] = sqrt(sum((p1 .- p2).^2.0))\n                d[j, i] = d[i, j]\n            end\n        end\n    end\n    return d\nend\n\nfunction majona(cluster::Hclust)::Float64\n    heights = cluster.heights\n    return mean(heights) + 1.25 * std(heights)\nend\n\n\"\"\"\n\n    smr98(setting)\n\nPerform the Sebert, Monthomery and Rollier (1998) algorithm for the given regression setting.\n\n# Arguments\n- `setting::RegressionSetting`: RegressionSetting object with a formula and dataset.\n\n# Examples\n```julia-repl\njulia> reg0001 = createRegressionSetting(@formula(calls ~ year), phones);\njulia> smr98(reg0001)\n10-element Array{Int64,1}:\n 15\n 16\n 17\n 18\n 19\n 20\n 21\n 22\n 23\n 24\n```\n\n# References\nSebert, David M., Douglas C. Montgomery, and Dwayne A. Rollier. \"A clustering algorithm for \nidentifying multiple outliers in linear regression.\" Computational statistics & data analysis \n27.4 (1998): 461-484.\n\"\"\"\nfunction smr98(setting::RegressionSetting)\n    X, y = @extractRegressionSetting setting\n    return smr98(X, y)\nend\n\n\n\"\"\"\n\n    smr98(X, y)\n\nPerform the Sebert, Monthomery and Rollier (1998) algorithm for the given regression setting.\n\n# Arguments\n- `X::Array{Float64, 2}`: Desing matrix of the linear regression model.\n- `y::Array{Float64, 1}`: Response vector of the linear regression model.\n\n\n# References\nSebert, David M., Douglas C. Montgomery, and Dwayne A. Rollier. \"A clustering algorithm for \nidentifying multiple outliers in linear regression.\" Computational statistics & data analysis \n27.4 (1998): 461-484.\n\"\"\"\n\nfunction smr98(X::Array{Float64,2}, y::Array{Float64,1})\n    olsreg = ols(X, y)\n    stdres = standardize(ZScoreTransform, residuals(olsreg), dims=1)\n    stdfit = standardize(ZScoreTransform, predict(olsreg), dims=1)\n    n, p = size(X)\n    d = distances(stdres, stdfit)\n    h = floor((n + p - 1) / 2)\n    hcl = hclust(d, linkage=:single)\n    majonacrit = majona(hcl)\n    clustermappings = cutree(hcl, h=majonacrit)\n    uniquemappings = unique(clustermappings)\n    for clustid in uniquemappings\n        cnt = count(x -> x == clustid, clustermappings)\n        if cnt >= h \n            return filter(i -> clustermappings[i] != clustid, 1:n)\n        end\n    end\n    return []\nend\n\n", "meta": {"hexsha": "e53e6fe34d7f3139785763648bb478482be9a1bf", "size": 2502, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/smr98.jl", "max_stars_repo_name": "angeris/LinRegOutliers", "max_stars_repo_head_hexsha": "093fc64345e6761d8871949ca71f2f1f529cb9e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/smr98.jl", "max_issues_repo_name": "angeris/LinRegOutliers", "max_issues_repo_head_hexsha": "093fc64345e6761d8871949ca71f2f1f529cb9e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/smr98.jl", "max_forks_repo_name": "angeris/LinRegOutliers", "max_forks_repo_head_hexsha": "093fc64345e6761d8871949ca71f2f1f529cb9e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0625, "max_line_length": 94, "alphanum_fraction": 0.654676259, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7600894444195316}}
{"text": "# 'cstrt_audet_ngon' provides the vertices coordinates (a,b) of a convex\r\n# equilateral small n-gon for n = 2^s and s >= 4\r\nfunction cstrt_audet_ngon(n)\r\nif mod(log2(n),1)==0 && n>=16\r\n    # initialization\r\n    x(t) = sin(t)-(2*cos(t)-1)*cos((n/4-2)*t)*sin(n*t/4)/cos(2*t);\r\n    F(t) = (2*x(t)+sin((n/2-1)*t))^2 + cos((n/2-1)*t)^2 - 4*sin(t/2)^2;\r\n    z = find_zero(F,(2*asin(sin(pi/n)/2),pi/n));\r\n    # construction\r\n    a = zeros(n-1); b = zeros(n-1);\r\n    a[Int(n/2-1)] = sin(z); a[Int(n/2+1)] = -a[Int(n/2-1)];\r\n    b[Int(n/2-1)] = cos(z); b[Int(n/2+1)] = b[Int(n/2-1)];\r\n    a[n-1] = a[Int(n/2-1)]-sin(2*z); a[1] = -a[n-1];\r\n    b[n-1] = b[Int(n/2-1)]-cos(2*z); b[1] = b[n-1];\r\n    a[n-2] = a[Int(n/2-1)]-sin(3*z); a[2] = -a[n-2];\r\n    b[n-2] = b[Int(n/2-1)]-cos(3*z); b[2] = b[n-2];\r\n    for i = 1:Int(n/8-1)\r\n        a[Int(mod(n/2-1+i*(3*n/2-2),n))] = sin(z)-(2*cos(z)-1)*sin(i*(2*z-pi/2))*sin((i+1)*(2*z-pi/2))/cos(2*z);\r\n        a[Int(n-mod(n/2-1+i*(3*n/2-2),n))] = -a[Int(mod(n/2-1+i*(3*n/2-2),n))];\r\n        b[Int(mod(n/2-1+i*(3*n/2-2),n))] = cos(z)-(2*cos(z)-1)*sin(i*(2*z-pi/2))*cos((i+1)*(2*z-pi/2))/cos(2*z);\r\n        b[Int(n-mod(n/2-1+i*(3*n/2-2),n))] = b[Int(mod(n/2-1+i*(3*n/2-2),n))];\r\n        a[Int(mod(n-1+i*(3*n/2-2),n))] = a[Int(mod(n/2-1+i*(3*n/2-2),n))]-(-1)^i*sin((4*i+2)*z);\r\n        a[Int(n-mod(n-1+i*(3*n/2-2),n))] = -a[Int(mod(n-1+i*(3*n/2-2),n))];\r\n        b[Int(mod(n-1+i*(3*n/2-2),n))] = b[Int(mod(n/2-1+i*(3*n/2-2),n))]-(-1)^i*cos((4*i+2)*z);\r\n        b[Int(n-mod(n-1+i*(3*n/2-2),n))] = b[Int(mod(n-1+i*(3*n/2-2),n))];\r\n        a[Int(mod(n-2+i*(3*n/2-2),n))] = a[Int(mod(n/2-1+i*(3*n/2-2),n))]-(-1)^i*sin((4*i+3)*z);\r\n        a[Int(n-mod(n-2+i*(3*n/2-2),n))] = -a[Int(mod(n-2+i*(3*n/2-2),n))];\r\n        b[Int(mod(n-2+i*(3*n/2-2),n))] = b[Int(mod(n/2-1+i*(3*n/2-2),n))]-(-1)^i*cos((4*i+3)*z);\r\n        b[Int(n-mod(n-2+i*(3*n/2-2),n))] = b[Int(mod(n-2+i*(3*n/2-2),n))];\r\n        a[Int(mod(n+i*(3*n/2-2),n))] = a[Int(mod(n/2-1+i*(3*n/2-2),n))]-(-1)^i*sin((4*i+1)*z);\r\n        a[Int(n-mod(n+i*(3*n/2-2),n))] = -a[Int(mod(n+i*(3*n/2-2),n))];\r\n        b[Int(mod(n+i*(3*n/2-2),n))] = b[Int(mod(n/2-1+i*(3*n/2-2),n))]-(-1)^i*cos((4*i+1)*z);\r\n        b[Int(n-mod(n+i*(3*n/2-2),n))] = b[Int(mod(n+i*(3*n/2-2),n))];\r\n    end\r\n    a[Int(n/2)] = 0; b[Int(n/2)] = 1;\r\n    return(a,b)\r\nend\r\nend", "meta": {"hexsha": "a7aa53c3cd3e966f9b20d5f08d8cb1597a4d04c7", "size": 2313, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "cstrt_ngon/cstrt_audet_ngon.jl", "max_stars_repo_name": "cbingane/optigon", "max_stars_repo_head_hexsha": "f585de7a2b01ff1e7a15c566596a7ba8f77f782a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cstrt_ngon/cstrt_audet_ngon.jl", "max_issues_repo_name": "cbingane/optigon", "max_issues_repo_head_hexsha": "f585de7a2b01ff1e7a15c566596a7ba8f77f782a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cstrt_ngon/cstrt_audet_ngon.jl", "max_forks_repo_name": "cbingane/optigon", "max_forks_repo_head_hexsha": "f585de7a2b01ff1e7a15c566596a7ba8f77f782a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.8684210526, "max_line_length": 113, "alphanum_fraction": 0.4375270212, "num_tokens": 1150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347868191549, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.7600522254464678}}
{"text": "#=\n # 121: 1D Poisson with point charge\n ([source code](SOURCE_URL))\n\nSolve a Poisson equation\n```math\n- \\Delta u = 0\n```\n\nin $\\Omega=(-1,1)$\nwith a point charge $Q$ at $x=0$. \n=#\n\nmodule Example121_PoissonPointCharge1D\n\nusing Printf\n\nusing VoronoiFVM\nusing ExtendableGrids\nusing GridVisualize\n\nfunction main(;nref=0,Plotter=nothing, verbose=false, unknown_storage=:sparse, brea=false)\n    \n    ## Create grid in (-1,1) refined around 0\n    hmax=0.2/2.0^nref\n    hmin=0.05/2.0^nref\n    X1=geomspace(-1.0,0.0, hmax,hmin)\n    X2=geomspace(0.0,1.0, hmin,hmax)\n    X=glue(X1,X2)\n    grid=VoronoiFVM.Grid(X)\n\n    ## Edit default region numbers:\n    ##   additional boundary region 3 at 0.0\n    bfacemask!(grid, [0.0],[0.0],3)\n    ## Material 1 left of 0\n    cellmask!(grid, [-1.0],[0.0],1)\n    ## Material 2 right of 0\n    cellmask!(grid, [0.0],[1.0],2)\n    \n\n    Q=0.0\n\n    function flux!(f,u0,edge)\n        u=unknowns(edge,u0)\n        f[1]=u[1,1]-u[1,2]\n    end\n    function storage!(f,u,node)\n        f[1]=u[1]\n    end\n\n    ## Define boundary reaction defining charge\n    ## Note that the term  is written on  the left hand side, therefore the - sign\n    function breaction!(f,u,node)\n        if node.region==3\n            f[1]=-Q\n        end\n    end\n\n   ## Create physics\n    physics=VoronoiFVM.Physics(\n        flux=flux!,\n        storage=storage!,\n        breaction=breaction!\n    )\n\n    ## Create system\n    sys=VoronoiFVM.System(grid,physics,unknown_storage=:dense)\n\n\n    ##  put potential into both regions\n    enable_species!(sys,1,[1,2])\n\n    ## Set boundary conditions\n\n    boundary_dirichlet!(sys,1,1,1.0)\n    boundary_dirichlet!(sys,1,2,0.0)\n\n    ## Create a solution array\n    inival=unknowns(sys)\n    U=unknowns(sys)\n    inival.=0\n\n    ## Create solver control info\n    control=VoronoiFVM.NewtonControl()\n    control.verbose=verbose\n    if ispyplot(Plotter)\n        Plotter.clf()\n    end\n\n    ## Solve and plot for several values of charge\n    for q in [0.1,0.2,0.4,0.8,1.6]\n        \n        if brea\n            ## Charge in reaction term\n            Q=q\n        else\n            ## Charge as boundary condition\n            sys.boundary_values[1,3]=q\n        end\n        solve!(U,inival,sys, control=control)\n        \n        ## Plot data\n        if ispyplot(Plotter)\n            Plotter.grid()\n            coord=grid[Coordinates]\n            Plotter.plot(coord[1,:],U[1,:],label=@sprintf(\"Q=%.2f\",q))\n            Plotter.xlabel(\"x\")\n            Plotter.ylabel(\"\\$\\\\phi\\$\")\n            Plotter.legend(loc=\"upper right\")\n            Plotter.pause(1.0e-10)\n        end\n    end\n    return sum(U)\nend\n\nfunction test()\n    main()≈20.254591679579015\nend\nend \n\n", "meta": {"hexsha": "e06bf906f0a779cfd44efd08d15bcc9b0efe7dd8", "size": 2665, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Example121_PoissonPointCharge1D.jl", "max_stars_repo_name": "NunoEdgarGFlowHub/VoronoiFVM.jl", "max_stars_repo_head_hexsha": "c9f5834a2052414e9d174e7c423d9d68e1406fd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Example121_PoissonPointCharge1D.jl", "max_issues_repo_name": "NunoEdgarGFlowHub/VoronoiFVM.jl", "max_issues_repo_head_hexsha": "c9f5834a2052414e9d174e7c423d9d68e1406fd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Example121_PoissonPointCharge1D.jl", "max_forks_repo_name": "NunoEdgarGFlowHub/VoronoiFVM.jl", "max_forks_repo_head_hexsha": "c9f5834a2052414e9d174e7c423d9d68e1406fd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0247933884, "max_line_length": 90, "alphanum_fraction": 0.5864915572, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7599922642130491}}
{"text": "# # Tutorial 04 Perturbation Theory\n#\n# ## Introduction\n#\n# This tutorial demonstrates how perturbation theory is utilized using the\n# WavesAndEigenvalues package. You may ask: 'What is perturbation theory?'\n# Well, perturbation theory deals with the approximation of a solution of a\n# mathematical problem based on a *known* solution of a problem similar to the\n# problem of interest. (Puhh, that was a long sentence...) The problem is said\n# to be perturbed from a baseline solution.\n# You can find a comprehensive presentation of the internal algorithms in\n# [1,2,3].\n## #jl\n# ## Model set-up and baseline-solution\n# The model is the same Rijke tube configuration as in Tutorial 01:\nusing WavesAndEigenvalues.Helmholtz\nmesh=Mesh(\"Rijke_mm.msh\",scale=0.001) #load mesh\ndscrp=Dict() #initialize model descriptor\ndscrp[\"Interior\"]=(:interior, ()) #define resonant cavity\ndscrp[\"Outlet\"]=(:admittance, (:Y,1E15)) #specify outlet BC\nγ=1.4 #ratio of specific heats\nρ=1.225 #density at the reference location upstream to the flame in kg/m^3\nTu=300.0    #K unburnt gas temperature\nTb=1200.0    #K burnt gas temperature\nP0=101325.0 # ambient pressure in Pa\nA=pi*0.025^2 # cross sectional area of the tube\nQ02U0=P0*(Tb/Tu-1)*A*γ/(γ-1) #the ratio of mean heat release to mean velocity Q02U0\nx_ref=[0.0; 0.0; -0.00101] #reference point\nn_ref=[0.0; 0.0; 1.00] #directional unit vector of reference velocity\nn=0.01 #interaction index\nτ=0.001 #time delay\ndscrp[\"Flame\"]=(:flame,(γ,ρ,Q02U0,x_ref,n_ref,:n,:τ,n,τ)) #flame dynamics\nR=287.05 # J/(kg*K) specific gas constant (air)\nspeedofsound(x,y,z) = z<0. ? sqrt(γ*R*Tu) : sqrt(γ*R*Tb)\nc=generate_field(mesh,speedofsound)\nL=discretize(mesh,dscrp,c)\n\n# To obtain a baseline solution we solve it using the housholder iteration with\n# a very small stopping tollerance of `tol=1E-11`.\nsol,nn,flag=householder(L,340*2*pi,maxiter=20,tol=1E-11)\n\n# this small tolerance is necessary because as the name suggests the base-line\n# solution is the basis to our subsequent steps. If it is inaccurate we will\n# definetly also encounter inaccurate approximations to other configurations\n# than the base-line set-up.\n## #jl\n# ## Taylor series\n#\n# Probably, you are somewhat familiar with the concept of Taylor series\n# which is a basic example of perturbation theory. There is some function\n# f from which the value f(x0) is known together with some derivatives at the\n# same point, the first N say. Then, we can approximate f(x0+Δ) as:\n#\n# f(x0+Δ)≈∑_n=0^N f_n(x0)Δ^n\n\n# Let's consider the time delay `τ`. Our problem depends exponentially on this\n# value.  We can utilize a fast perturbation algorithm to compute the first\n# 20 Taylor-series coefficients of the eigenfrequency `ω` w.r.t. `τ` by just\n# typing\nperturb_fast!(sol,L,:τ,20)\n# The output shows you how long it takes to compute the coefficients.\n# Obviously, it takes longer and longer for higher order coefficients.\n# Note, that there is also an algorithm `perturb!(sol,L,:τ,20)` which does\n# exactly the same as the fast algorithm but is slower, when it comes to high\n# orders (N>5).\n\n# Both algorithms populate a field in the solution object holding the Taylor\n# coefficients.\nsol.eigval_pert\n\n# We can use these values to form the Taylor-series approximation and for\n# convenience we can just do so by calling to the solution object itself.\n# For instance let's assume we would like to approximate the value of the\n# eigenfrequency when \"τ==0.00125\" based on the 20th order series expansion.\nΔ=0.00001\nω_approx=sol(:τ,τ+Δ,20)\n\n# Let's compare this value to the true solution:\nL.params[:τ]=τ+Δ #change parameter\nsol_exact,nn,flag=householder(L,340*2*pi,maxiter=20,tol=1E-11) #solve again\nω_exact=sol_exact.params[:ω]\nprintln(\" exact=$(ω_exact/2/pi)  vs  approx=$(ω_approx/2/pi))\")\n# Clearly, the approximation matches the first 4 digits after the point!\n\n# We can also compute the approximation at any lower order than 20.\n# For instance, the first-order approximation is:\nω_approx=sol(:τ,τ+Δ,1)\nprintln(\" first-order approx=$(ω_approx/2/pi)\")\n\n# Note that the accuracy is less than at twentieth order.\n#\n# Also note that we cannot compute the perturbation at higher order than 20\n# because we have only computed the Taylor series coefficients up to 20th order.\n# Of course we could, prepare higher order coefficients, let's say up to 30th\n# order by\nperturb_fast!(sol,L,:τ,30)\n# and then\nω_approx=sol(:τ,τ+Δ,30)\nprintln(\" 30th-order approx=$(ω_approx/2/pi)\")\n\n# Indeed, `30` is a special limit because per default the WavesAndEigenvalues\n# package installs the perturbation algorithm on your machine up to 30th order.\n# This is because higher orders would consume significantly more memory in\n# the installation directory and also the computation of higher orders may take\n# some time.  However, if you really want to use higher orders. You can rebuild\n# your package by first setting a special environment variable to your desired\n# order -- say 40 -- by `ENV[\"JULIA_WAE_PERT_ORDER\"]=40` and then run\n# `Pkg.build(\"WavesAndEigenvalues\")`\n# Note, that if you don't make the environment variable permanent,\n# these steps will be necessary once every time you got any update to the\n# package from julias package manager.\n\n\n#TODO:speed\n\n## #jl\n# Ok, we've seen how we can compute Taylor-series coefficients and how to\n# evaluate them as a Taylor series. But how do we choose parameters like\n# the baseline set-up or the eprturbation order to get a reasonable estimate?\n# Well there is a lot you can do but, unfornately, there are a lot of\n# misunderstandings when it comes to the quality perturbative approximations.\n#\n# Take a second and try to answer the following questions:\n# 1. What is the range of Δ in which you can expect reliable results from\n# the approximation, i.e., the difference from the true solution is small?\n# 2. How does the quality of your approximation improve if you increase the\n# number of known derivatives?\n# 3. What else can you do to improve your solution?\n#\n# Regarding the first question, many people misbelieve that the approximation is\n# good as long as Δ (the shift from the expansion point) is small. This is right\n# and wrong at the same time. Indeed, to classify Δ as small, you need to\n# compare it agains some value. For Taylor series this is the radius of\n# convergence. Convergence radii can be quite huge and sometimes super small.\n# Also keep in mind that the nuemrical value of Δ in most engineering\n# applications is meaningless if it is not linked to some unit of measure.\n# (You know the joke: What is larger, 1 km or a million mm?)\n\n# So how do we get the radius of convergence? It's as simple like\nr=conv_radius(sol,:τ)\n#The return value here is an array that holds N-1 values, where N is the order\n# of Taylor-series coefficients that have been computed for `:τ`. This is\n# because the convergenvce radius is estimated based on the ratio of two\n# consecutive Taylor-series coefficients. Usually, the last entry of r should\n# give you the best approximate.\nprintln(\"Best estimate available: r=$(r[end])\")\n# However, there are cases where the estimation procedure for the convergence\n# radius is not appropriate. That is why you can have a look on the other entries\n# in r to judge whether there is smooth convergence.\n## #jl\n# Let's see what's happening if we evaluate the Taylor series beyond it's radius\n# of convergence.\nω_approx=sol(:τ,τ+r[end]+0.001,20)\nL.params[:τ]=τ+r[end]+0.001\nsol_exact,nn,flag=householder(L,340*2*pi,maxiter=20,tol=1E-11) #solve again\nω_exact=sol_exact.params[:ω]\nprintln(\" exact=$(ω_exact/2/pi)  vs  approx=$(ω_approx/2/pi))\")\n# Outch, the approximation is completely off.\n# Remember question 2? Maybe the estimate gets better if we increase the\n# perturbation order ? At least the last time we've seen an improvement.\n# But this time...\nω_approx=sol(:τ,τ+r[end]+0.001,30)\nprintln(\" exact=$(ω_exact/2/pi)  vs  approx=$(ω_approx/2/pi))\")\n# things get *way* worse! This is exaclty the reason why some clever person\n# named r the radius of *convergence*. Beyond that radius we cannot make the\n# Taylor-series converge without shifting the expansion point. You might think:\n# 'Well, then let's shift the expansion point!' While this is definitely a valid\n# approach, there is something better you can do...\n\n# ## Series accelartion by Padé approximation\n#\n# The Taylor-series cannot converge beyond its radius of convergence. So why\n# not trying someting else than a Taylor-series?. The truncated Taylor series is\n# a polynomial approximation to our unknown relation ω=ω(τ). An alternative\n# (if not to say a generalazation) of this approach is to consider rational\n# polynomial approximations.  So isntead of\n# f(x0+Δ)≈∑_n=0^N f_n(x0)Δ^n\n# we try something like\n# f(x0+Δ)≈[ ∑_l=0^L a_l(x0)Δ^l ] / [ 1 + ∑_m=0^M b_m(x0)Δ^m ]\n# In order to get the same asymptotic behaviour close to our expansion point, we\n# demand that the truncated Taylor series expansion of our Padé approximant is\n# identical to the approximation of our unknown function. Here comes the clou:\n# we already know these values because we computed the Taylor-series\n# coefficients. Only little algebra is needed to convert the Taylor coefficients\n# to Padé coefficients and all of this is build in to the solution type. All you\n# need to know is that the number of Padé coefficients is related to the number\n# of Taylor coefficients by the simple formula L+M=N. Let's give it a try and\n# compute the Padé approximant for L=M=10 (a so-called diagonal Padé\n# approximant). This is just achieve by an extra argument for the call to our\n# solution object.\nω_approx=sol(:τ,τ+r[end]+0.001,10,10)\nprintln(\" exact=$(ω_exact/2/pi)  vs  approx=$(ω_approx/2/pi))\")\n# Wow! There is now only a diffrence of about 1hz between the true solution and\n# it's estimate. I'would say that's fine for many egineering applications.\n# What's your opinion?\n## #jl\n# ## Conclusion\n# You learned how to use perturbation theory. The main computational costs for\n# this approach is the computation of Taylor-series coefficients. Once you have\n# them everything comes down to ta few evaluations of scalar polynomials.\n# Especially, when you like to rapidly evalaute your model for a bunch of values\n# in a given parameter range. This approach should speed up your computations.\n#\n# The next tutorial will familiarize you with the use of higher order\n# finite elements.\n", "meta": {"hexsha": "a8bfa8bf3a771cfa86f2941974e33070039ef238", "size": 10362, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/tutorials/tutorial_04_perturbation_theory.jl", "max_stars_repo_name": "Geometheus/WavesAndEigenvalues.jl", "max_stars_repo_head_hexsha": "88cd39e4c3e1d3da1eaf17adf227f49502602062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-24T15:32:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T15:32:55.000Z", "max_issues_repo_path": "examples/tutorials/tutorial_04_perturbation_theory.jl", "max_issues_repo_name": "Geometheus/WavesAndEigenvalues.jl", "max_issues_repo_head_hexsha": "88cd39e4c3e1d3da1eaf17adf227f49502602062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-06-05T12:52:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T16:35:55.000Z", "max_forks_repo_path": "examples/tutorials/tutorial_04_perturbation_theory.jl", "max_forks_repo_name": "Geometheus/WavesAndEigenvalues.jl", "max_forks_repo_head_hexsha": "88cd39e4c3e1d3da1eaf17adf227f49502602062", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-29T08:33:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-29T08:33:39.000Z", "avg_line_length": 50.3009708738, "max_line_length": 83, "alphanum_fraction": 0.7573827446, "num_tokens": 2780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624557, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7599922603041167}}
{"text": "function svdbyeigen(A; nsv::Integer=3)\n\tP,N = size(A)\n\tK = Symmetric(N<=P ? A'A : A*A')\n\tM = size(K,1)\n\tF = eigen(K, M-nsv+1:M)\n\tS = sqrt.(max.(0.,reverse(F.values)))\n\n\tV = F.vectors[:,end:-1:1]\n\tN<=P ? SVD(A*V./S',S,V') : SVD(V,S,V'A./S)\nend\n", "meta": {"hexsha": "7378532056e704433d5fa43d175acbbe9bbd2061", "size": 243, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pca.jl", "max_stars_repo_name": "PrincipalMomentAnalysis/PrincipalMomentAnalysisApp", "max_stars_repo_head_hexsha": "aea141354bd74ba606d84b1cf9fde8bd3018d6cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-01T19:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-01T19:00:01.000Z", "max_issues_repo_path": "src/pca.jl", "max_issues_repo_name": "PrincipalMomentAnalysis/PrincipalMomentAnalysisApp", "max_issues_repo_head_hexsha": "aea141354bd74ba606d84b1cf9fde8bd3018d6cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-03-05T00:38:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-24T09:48:11.000Z", "max_forks_repo_path": "src/pca.jl", "max_forks_repo_name": "PrincipalMomentAnalysis/PrincipalMomentAnalysisApp", "max_forks_repo_head_hexsha": "aea141354bd74ba606d84b1cf9fde8bd3018d6cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0909090909, "max_line_length": 43, "alphanum_fraction": 0.5390946502, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7599911816571125}}
{"text": "\nfunction niche_network(S::Int, C::Float64)\n\n    cond = false\n    adj = fill(0, S, S)\n    n = fill(0.0, S)\n    r = fill(0.0, S)\n    c = fill(0.0, S)\n\n    while !cond\n        n = sort(rand(S))\n        β = 1 / (2 * C) - 1\n        r = n .* rand(Beta(1, β), S)\n\n        # set r[position of min[η]] = 0, so that every web has at least one basal species\n        r[1] = 0.0\n\n        for pred in 1:S\n\n            c[pred] = rand(Uniform(r[pred]/2, n[pred]))\n\n            for prey in 1:S\n                if ((c[pred] - r[pred] / 2) <= n[prey] <= (c[pred] + r[pred] / 2))\n                    adj[prey, pred] = 1\n                else\n                    adj[prey, pred] = 0\n                end\n            end\n        end\n\n        cond = is_connected(DiGraph(adj))\n    end\n\n    return (fw = adj, n = n, r = r, c = c)\nend\n\nfunction prob_network(S, C)\n\n    cond = false\n    adj = fill(0, S, S)\n\n    n = fill(0.0, S)\n    r = fill(0.0, S)\n    c = fill(0.0, S)\n\n    while !cond\n\n        n = sort(rand(S))\n        β = 1 / (2 * C) - 1\n        r = n .* rand(Beta(1, β), S)\n\n        # set r[position of min[η]] = 0, so that every web has at least one basal species\n        r[1] = 0.0\n\n        @inbounds for pred in 1:S\n\n            c[pred] = rand(Uniform(r[pred] / 2, n[pred]))\n\n            for prey in 1:S\n                ϕ = exp(-((n[prey] - c[pred]) / (r[pred] / 2)) ^ 2)\n                adj[prey, pred] = rand(Bernoulli(ϕ), 1)[1]\n            end\n        end\n\n        cond = is_connected(DiGraph(adj))\n    end\n\n    return (fw = adj, n = n, r = r, c = c)\nend\n\n\nfunction ϕ_mat(θ, m)\n\n    ϕ = fill(0.0, m.S, m.S)\n\n    @inbounds for pred in 1:m.nonbasal\n        for prey in 1:m.S\n            ϕ[prey, m.basal + pred] = 0.99 * exp(-((θ.n[prey] - θ.c[pred] * θ.n[m.basal + pred]) / (θ.r[pred] / 2)) ^ 2)\n        end\n    end\n\n    return ϕ\n\nend\n", "meta": {"hexsha": "ddb0550e6172bd30b38c1706ec15c397a59685ff", "size": 1818, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/generate.jl", "max_stars_repo_name": "clint-leach/niche-model", "max_stars_repo_head_hexsha": "1ec06f9351b8982d20c4b41bcfe4c9b025074fd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/generate.jl", "max_issues_repo_name": "clint-leach/niche-model", "max_issues_repo_head_hexsha": "1ec06f9351b8982d20c4b41bcfe4c9b025074fd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-10-14T21:16:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-17T20:03:01.000Z", "max_forks_repo_path": "src/generate.jl", "max_forks_repo_name": "clint-leach/niche-model", "max_forks_repo_head_hexsha": "1ec06f9351b8982d20c4b41bcfe4c9b025074fd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3882352941, "max_line_length": 120, "alphanum_fraction": 0.4383938394, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475794701961, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7599911776199099}}
{"text": "#=\nA Pythagorean triplet is a set of three natural numbers, a < b < c, for which,\n\na2 + b2 = c2\nFor example, 32 + 42 = 9 + 16 = 25 = 52.\n\nThere exists exactly one Pythagorean triplet for which a + b + c = 1000.\nFind the product abc.\n=#\n\n# Kinda ugly brute force approach\nfunction findABC()\n  max = 1000\n  for a in 1:max, b in 1:max, c in 1:max\n    if a >= b || b >= c || a + b + c != max\n      continue\n    end\n    if a^2 + b^2 == c^2\n      return a*b*c\n    end\n  end\nend\n\n@time println(findABC())\n\n", "meta": {"hexsha": "6dc464c82a9df8788e7bc54204cf90ee31f64f81", "size": 499, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p9.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p9.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p9.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 19.1923076923, "max_line_length": 78, "alphanum_fraction": 0.5911823647, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475762847496, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7599911750536117}}
{"text": "# Utility functions for common algebraic operations.\n\n\"\"\"\n    rotateTensorToVectorZ(tensor, vector)\n\nRotates `tensor` with a rotation matrix that aligns z-axis with `vector`.\n\"\"\"\nfunction rotateTensorToVectorZ(tensor::AbstractMatrix{T}, v::AbstractVector{T}) where T\n   unitz = SVector{3, T}(0.0, 0.0, 1.0)\n   vz = v × unitz::SVector{3, T}\n   vz ./= hypot(vz[1], vz[2], vz[3])\n   angle = acos(v ⋅ unitz / hypot(v[1], v[2], v[3]))\n   R = getRotationMatrix(vz, angle)\n   # Rotate tensor\n   R * tensor * R'\nend\n\n\"\"\"\n    getRotationMatrix(vector, angle)\n\nCreates a rotation matrix that rotates around a unit `vector` by an `angle` in radians.\nReferences: https://en.wikipedia.org/wiki/Rodrigues'_rotation_formula\nhttps://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle\n\"\"\"\nfunction getRotationMatrix(v::AbstractVector, θ)\n   sinθ, cosθ = sincos(eltype(v)(θ))\n   tmp = 1 - cosθ\n   m =  @SMatrix [\n        cosθ+v[1]^2*tmp         v[1]*v[2]*tmp-v[3]*sinθ v[1]*v[3]*tmp+v[2]*sinθ;\n        v[1]*v[2]*tmp+v[3]*sinθ cosθ+v[2]^2*tmp         v[2]*v[3]*tmp-v[1]*sinθ;\n        v[1]*v[3]*tmp-v[2]*sinθ v[3]*v[2]*tmp+v[1]*sinθ cosθ+v[3]^2*tmp]\nend\n\n\"\"\"\n    getRotationB(B) -> SMatrix\n\nObtain a rotation matrix with each column being a unit vector which is parallel (`v3`) and\nperpendicular (`v1,v2`) to the magnetic field `B`. The two perpendicular directions are\nchosen based on the reference vector of z-axis in the Cartesian coordinates.\n\"\"\"\nfunction getRotationB(B::AbstractVector{T}) where T\n   b = hypot(B[1], B[2], B[3])\n   if B[3] / b ≈ -1.0 # B aligned with reference vector\n      R = SMatrix{3,3,T}([0.0 -1.0 0.0; 1.0 0.0 0.0; 0.0 0.0 1.0])\n   elseif B[3] / b ≈ 1.0 # B aligned with reference vector\n      R = SMatrix{3,3,T}([0.0 -1.0 0.0; 1.0 0.0 0.0; 0.0 0.0 1.0])\n   else\n      v0 = SVector{3,T}(0.0, 0.0, 1.0) # reference vector\n      v3 = SVector{3,T}(B[1]/b, B[2]/b, B[3]/b) # unit vector along B\n      v1 = v0 × v3::SVector{3, T}\n      v2 = v3 × v1::SVector{3, T}\n\n      R = @SMatrix [v1[1] v2[1] v3[1]; v1[2] v2[2] v3[2]; v1[3] v2[3] v3[3]]\n   end\n   R\nend\n\n\"\"\"\n    rotateWithB(T, B) -> Matrix\n\nRotate the tensor `T` with the 3rd direction aligned with `B`.\nSee also: [`rotateWithB!`](@ref)\n\"\"\"\nfunction rotateWithB(T::AbstractMatrix, B::AbstractVector)\n   R = getRotationB(B)\n   R * T * R'\nend\n\n\"\"\"\n    rotateWithB!(T, B)\n\nRotate the tensor `T` with the 3rd direction aligned with `B`.\nSee also: [`rotateWithB`](@ref)\n\"\"\"\nfunction rotateWithB!(T::AbstractMatrix, B::AbstractVector)\n   R = getRotationB(B)\n   T[:] = R * T * R'\nend", "meta": {"hexsha": "3df1d5cfdaf2a507ab51aee56798fdab608436e2", "size": 2557, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utility/rotation.jl", "max_stars_repo_name": "henry2004y/Vlasiator.jl", "max_stars_repo_head_hexsha": "a92eab34adf7ace6b88109d6ea68d472cb54878e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-05-03T11:54:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T12:56:13.000Z", "max_issues_repo_path": "src/utility/rotation.jl", "max_issues_repo_name": "henry2004y/Vlasiator.jl", "max_issues_repo_head_hexsha": "a92eab34adf7ace6b88109d6ea68d472cb54878e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 76, "max_issues_repo_issues_event_min_datetime": "2021-01-26T21:00:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T19:46:46.000Z", "max_forks_repo_path": "src/utility/rotation.jl", "max_forks_repo_name": "henry2004y/Vlasiator.jl", "max_forks_repo_head_hexsha": "a92eab34adf7ace6b88109d6ea68d472cb54878e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-22T06:27:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T06:27:50.000Z", "avg_line_length": 32.7820512821, "max_line_length": 90, "alphanum_fraction": 0.6288619476, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993027, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.759991168084979}}
{"text": "using AmbientForcing\nusing OrdinaryDiffEq, Distributions\n\n# Adopting the Robertson Example from the DifferentialEquation Docs\n# https://diffeq.sciml.ai/stable/tutorials/advanced_ode_example/#Handling-Mass-Matrices\nfunction rober(du,u,p,t)\n  y₁,y₂,y₃ = u\n  du[1] = -0.04 * y₁ + 1e4 * y₂ * y₃\n  du[2] =  0.04 * y₁ - 1e4 * y₂ * y₃ - 3e7 * y₂^2\n  du[3] =  y₁ + y₂ + y₃ - 1\n  nothing\nend\n\n# Creating the mass matrix M\n# The last row depicts our constraint\nM = [1. 0  0\n     0  1. 0\n     0  0  0];\n\n# Setting up the DAE as an ODE in mass matrix form\node_rober = ODEFunction(rober, mass_matrix = M) \n\n# Choosing an inital condition which fulfills the constraint\nu0 = [1.0,0.0,0.0]; \n\n# Acsessing the constraint equations g\ng_rober = constraint_equations(ode_rober) \ng_rober(u0)\n\n# Randomly perturbing all variables  \nFrand = random_force(ode_rober, [0.0,1], Uniform)\nz_new = ambient_forcing(ode_rober, u0, 2.0, Frand)\n\n# g ≈ 0 means the constraint is fulfilled\ng_rober(z_new) \n\n# Only perturbing the second variable y₂\nh = [0, 1 ,0]\nz_new = ambient_forcing(ode_rober, u0, 2.0, h)\n\ng_rober(z_new)", "meta": {"hexsha": "7f8793cc03415031c1ee5a4a8c6948158401bdef", "size": 1088, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/DifferentialEquation_example.jl", "max_stars_repo_name": "Anbue63/AmbientForcing.jl", "max_stars_repo_head_hexsha": "631945e82db7df69e88485507eef30d7cc2ce630", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-28T07:26:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T07:26:46.000Z", "max_issues_repo_path": "examples/DifferentialEquation_example.jl", "max_issues_repo_name": "Anbue63/AmbientForcing.jl", "max_issues_repo_head_hexsha": "631945e82db7df69e88485507eef30d7cc2ce630", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/DifferentialEquation_example.jl", "max_forks_repo_name": "Anbue63/AmbientForcing.jl", "max_forks_repo_head_hexsha": "631945e82db7df69e88485507eef30d7cc2ce630", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-28T07:44:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-28T07:44:34.000Z", "avg_line_length": 26.5365853659, "max_line_length": 87, "alphanum_fraction": 0.7040441176, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7599911675320924}}
{"text": "@doc raw\"\"\"\nThe linear trend model is defined by:\n```math\n\\begin{gather*}\n    \\begin{aligned}\n        y_{t} &=  \\mu_{t} + \\gamma_{t} + \\varepsilon_{t} \\quad &\\varepsilon_{t} \\sim \\mathcal{N}(0, \\sigma^2_{\\varepsilon})\\\\\n        \\mu_{t+1} &= \\mu_{t} + \\nu_{t} + \\xi_{t} \\quad &\\xi_{t} \\sim \\mathcal{N}(0, \\sigma^2_{\\xi})\\\\\n        \\nu_{t+1} &= \\nu_{t} + \\zeta_{t} \\quad &\\zeta_{t} \\sim \\mathcal{N}(0, \\sigma^2_{\\zeta})\\\\\n    \\end{aligned}\n\\end{gather*}\n```\n\n# Example\n```jldoctest\njulia> model = LocalLinearTrend(rand(100))\nLocalLinearTrend model\n```\n\nSee more on [Finland road traffic fatalities](@ref)\n\n# References\n * Durbin, James, & Siem Jan Koopman. (2012). \"Time Series Analysis by State Space Methods:\n    Second Edition.\" Oxford University Press. pp. 44\n\"\"\"\nmutable struct LocalLinearTrend <: StateSpaceModel\n    hyperparameters::HyperParameters\n    system::LinearUnivariateTimeInvariant\n    results::Results\n\n    function LocalLinearTrend(y::Vector{Fl}) where Fl\n        Z = Fl.([1.0; 0.0])\n        T = Fl.([1 1; 0 1])\n        R = Fl.([1 0; 0 1])\n        d = zero(Fl)\n        c = zeros(Fl, 2)\n        H = one(Fl)\n        Q = Fl.([1 0; 0 1])\n\n        system = LinearUnivariateTimeInvariant{Fl}(y, Z, T, R, d, c, H, Q)\n\n        names = [\"sigma2_ε\", \"sigma2_ξ\", \"sigma2_ζ\"]\n        hyperparameters = HyperParameters{Fl}(names)\n\n        return new(hyperparameters, system, Results{Fl}())\n    end\nend\n\nfunction default_filter(model::LocalLinearTrend)\n    Fl = typeof_model_elements(model)\n    steadystate_tol = Fl(1e-5)\n    a1 = zeros(Fl, 2)\n    P1 = Fl(1e6) .* Matrix{Fl}(I, 2, 2)\n    return UnivariateKalmanFilter(a1, P1, 2, steadystate_tol)\nend\n\nfunction initial_hyperparameters!(model::LocalLinearTrend)\n    Fl = typeof_model_elements(model)\n    initial_hyperparameters = Dict{String,Fl}(\n        \"sigma2_ε\" => var(model.system.y),\n        \"sigma2_ξ\" => var(model.system.y),\n        \"sigma2_ζ\" => one(Fl),\n    )\n    set_initial_hyperparameters!(model, initial_hyperparameters)\n    return model\nend\n\nfunction constrain_hyperparameters!(model::LocalLinearTrend)\n    constrain_variance!(model, \"sigma2_ε\")\n    constrain_variance!(model, \"sigma2_ξ\")\n    constrain_variance!(model, \"sigma2_ζ\")\n    return model\nend\n\nfunction unconstrain_hyperparameters!(model::LocalLinearTrend)\n    unconstrain_variance!(model, \"sigma2_ε\")\n    unconstrain_variance!(model, \"sigma2_ξ\")\n    unconstrain_variance!(model, \"sigma2_ζ\")\n    return model\nend\n\nfunction fill_model_system!(model::LocalLinearTrend)\n    model.system.H = get_constrained_value(model, \"sigma2_ε\")\n    model.system.Q[1] = get_constrained_value(model, \"sigma2_ξ\")\n    model.system.Q[end] = get_constrained_value(model, \"sigma2_ζ\")\n    return model\nend\n\nfunction reinstantiate(::LocalLinearTrend, y::Vector{Fl}) where Fl\n    return LocalLinearTrend(y)\nend\n\nhas_exogenous(::LocalLinearTrend) = false\n", "meta": {"hexsha": "828ba87e9f827b2c62e1789c43626da8d0cbded2", "size": 2853, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/locallineartrend.jl", "max_stars_repo_name": "pkofod/StateSpaceModels.jl", "max_stars_repo_head_hexsha": "2921e9fd8c30ede584f6606a068700e0027f207b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/models/locallineartrend.jl", "max_issues_repo_name": "pkofod/StateSpaceModels.jl", "max_issues_repo_head_hexsha": "2921e9fd8c30ede584f6606a068700e0027f207b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/locallineartrend.jl", "max_forks_repo_name": "pkofod/StateSpaceModels.jl", "max_forks_repo_head_hexsha": "2921e9fd8c30ede584f6606a068700e0027f207b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6774193548, "max_line_length": 125, "alphanum_fraction": 0.6652646337, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993027, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7599911636826449}}
{"text": "#=\nAodwt.jl\n2019-02-23 Jeff Fessler, University of Michigan\n=#\n\nexport Aodwt\n\nusing LinearMapsAA: LinearMapAA, LinearMapAM, LinearMapAO\nusing Wavelets: dwt!, idwt!, wavelet, WT\n\n\n\"\"\"\n    A, levels, mfun = Aodwt(dims ; level::Int=3, wt=wavelet(WT.haar))\n\nCreate orthogonal discrete wavelet transform (ODWT) `LinearMapAA`\n\nin\n- `dims::Dims` tuple of dimensions\n\noption\n- `level::Int` # of levels; default 3\n- `wt` wavelet transform type (see `Wavelets` package); default Haar\n- `operator::Bool=true` default to `LinearMapAO`\n\nout\n- `A` a `LinearMapAX` object\n- `scales` array of size `dims` showing the scale of each coefficient\nwhich is useful when imposing scale-dependent regularization\n- `mfun` convenience function for A*X when X is a Matrix or Array (not vector)\n\n2019-02-23 Jeff Fessler, University of Michigan\n\"\"\"\nfunction Aodwt(\n\tdims::Dims ;\n\tT::DataType = Float32,\n\tlevel::Int = 3,\n\twt = wavelet(WT.haar),\n\toperator::Bool = true, # !\n)\n\n\tfunction mfunA(lev)\n\t\t# todo: avoiding convert involves `dwt!` limitation; see:\n\t\t# https://github.com/JuliaDSP/Wavelets.jl/issues/53\n\t\t# https://github.com/JuliaDSP/Wavelets.jl/pull/54\n\t#\tforw!(y,x) = dwt!(y, convert(AbstractArray{T},x), wt, level)\n\t#\tback!(x,y) = idwt!(x, convert(AbstractArray{T},y), wt, level)\n\t\tforw!(y,x) = dwt!(y, x, wt, lev)\n\t\tback!(x,y) = idwt!(x, y, wt, lev)\n\n\t\tif operator\n\t\t\tmfun = (A, x) -> A * x\n\t\t\treturn mfun, LinearMapAA(forw!, back!,\n\t\t\t\t(prod(dims), prod(dims)) ;\n\t\t\t\tprop = (wt=wt, level=lev), T=T,\n\t\t\t\toperator = true, idim=dims, odim=dims,\n\t\t\t)\n\t\telse\n\t\t\tmfun = (A, x) -> reshape(A * vec(x), dims)\n\t\t\treturn mfun, LinearMapAA(\n\t\t\t\t(y,x) -> vec(forw!(reshape(y, dims), reshape(x, dims))),\n\t\t\t\t(x,y) -> vec(back!(reshape(x, dims), reshape(y, dims))),\n\t\t\t#\tx -> vec(dwt(reshape(x, dims), wt, level)),\n\t\t\t#\ty -> vec(idwt(reshape(y, dims), wt, level)),\n\t\t\t\t(prod(dims), prod(dims)) ;\n\t\t\t\tprop = (wt=wt, level=lev), T=T,\n\t\t\t)\n\t\tend\n\tend\n\n\tmfun, A = mfunA(level)\n\n\tscales = zeros(dims)\n\tfor il=1:level\n\t\t_,Al = mfunA(il)\n\t\ttmp = mfun(Al, ones(dims)) .== 0\n\t\tscales += il * (tmp .& (scales .== 0))\n\tend\n\n\treturn A, scales, mfun\nend\n", "meta": {"hexsha": "f595481606b1318cafe294f1285f3d2ab69cde50", "size": 2110, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/regularize/Aodwt.jl", "max_stars_repo_name": "jamesthesnake/MIRT.jl", "max_stars_repo_head_hexsha": "3a4b1e33a35e2ab062f532a22866bfb11f6e5cd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/regularize/Aodwt.jl", "max_issues_repo_name": "jamesthesnake/MIRT.jl", "max_issues_repo_head_hexsha": "3a4b1e33a35e2ab062f532a22866bfb11f6e5cd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/regularize/Aodwt.jl", "max_forks_repo_name": "jamesthesnake/MIRT.jl", "max_forks_repo_head_hexsha": "3a4b1e33a35e2ab062f532a22866bfb11f6e5cd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.049382716, "max_line_length": 78, "alphanum_fraction": 0.6421800948, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993028, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7599911614814777}}
{"text": "# # clip-02-05.jl\n\n# Load Julia packages (libraries) needed  for the snippets in chapter 0\n\nusing StatisticalRethinking, Optim\n#gr(size=(600,600));\n\n# ### snippet 3.2\n\np_grid = range(0, step=0.001, stop=1)\nprior = ones(length(p_grid))\nlikelihood = [pdf(Binomial(9, p), 6) for p in p_grid]\nposterior = likelihood .* prior\nposterior = posterior / sum(posterior)\nsamples = sample(p_grid, Weights(posterior), length(p_grid));\nsamples[1:5]\n\n# ### snippet 3.3\n# Draw 10000 samples from this posterior distribution\n\nN = 10000\nsamples = sample(p_grid, Weights(posterior), N);\n\n# In StatisticalRethinkingJulia samples will always be stored\n# in an MCMCChains.Chains object. \n\nchn = MCMCChains.Chains(reshape(samples, N, 1, 1), [\"toss\"]);\n\n# Describe the chain\n\nMCMCChains.describe(chn)\n\n# Plot the chain\n\nplot(chn)\n\n# ### snippet 3.4\n\n# Create a vector to hold the plots so we can later combine them\n\np = Vector{Plots.Plot{Plots.GRBackend}}(undef, 2)\np[1] = scatter(1:N, samples, markersize = 2, ylim=(0.0, 1.3), lab=\"Draws\")\n\n# ### snippet 3.5\n\n# Analytical calculation\n\nw = 6\nn = 9\nx = 0:0.01:1\np[2] = density(samples, ylim=(0.0, 5.0), lab=\"Sample density\")\np[2] = plot!( x, pdf.(Beta( w+1 , n-w+1 ) , x ), lab=\"Conjugate solution\")\n\n# Add quadratic approximation\n\nplot(p..., layout=(1, 2))\n\n# End of `03/clip-02-05.jl`\n", "meta": {"hexsha": "af8c986a349226f98941b803698a31c09c65b7a9", "size": 1313, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/03/clip-02-05.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_stars_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/03/clip-02-05.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_issues_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/03/clip-02-05.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_forks_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2542372881, "max_line_length": 74, "alphanum_fraction": 0.6824067022, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857379, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7599828398240599}}
{"text": "\"\"\"\n2D Predator-Prey Model\n\nTaken from:\n[14.3 pp2: A 2D Predator-Prey Model][auto07p/14.3]\nof AUTO-07p manual.\n\n[auto07p/14.3]: http://www.dam.brown.edu/people/sandsted/auto/auto07p.pdf#page=138\n\"\"\"\nmodule PredatorPrey\n\nusing DiffEqBase: ODEProblem\nusing StaticArrays: SVector\nusing Setfield: @lens\nimport Setfield\n\nusing ...Bifurcations: BifurcationProblem\nusing ...Codim2: cast_container, DiffEqCodim2Problem\n\nf1(u, p) =\n    p[2] * u[1] * (1 - u[1]) - u[1] * u[2] - p[1] * (1 - exp(- p[3] * u[1]))\nf2(u, p) =\n    - u[2] + p[4] * u[1] * u[2]\n\nf(u::SVector, p, t) = SVector(f1(u, p), f2(u, p))\n\nfunction f(du, u, p, t)\n    du[1] = f1(u, p)\n    du[2] = f2(u, p)\n    nothing\nend\n\nconst _f = f\n\n\nfunction make_prob(\n        p = (0.0, 3, 5, 3);\n        f = _f,\n        u0 = SVector(0.0, 0.0),\n        tspan = (0.0, 30.0),\n        ode = ODEProblem{!(u0 isa SVector)}(f, u0, tspan, p),\n        param_axis = (@lens _[1]),\n        t_domain = (0.0, 1.0),\n        kwargs...)\n    x_min = SVector(-0.2, -Inf)\n    x_max = SVector(1.0, Inf)\n    x_min = cast_container(typeof(ode.u0), x_min)\n    x_max = cast_container(typeof(ode.u0), x_max)\n    return BifurcationProblem(\n        ode, param_axis, t_domain;\n        phase_space = (x_min, x_max),\n        kwargs...)\nend\n\nprob = make_prob()\node = prob.p.de_prob\np = ode.p\nu0 = ode.u0\nparam_axis = prob.p.param_axis\n\nfunction make_codim2_prob(\n        p = ode.p;\n        u0 = SVector(0.0, 0.0),\n        tspan = (0.0, 30.0),\n        ode = ODEProblem{!(u0 isa SVector)}(f, u0, tspan, p),\n        param_axis1 = (@lens _[1]),\n        param_axis2 = (@lens _[3]),\n        t_domain = ([-Inf, -Inf], [Inf, Inf]),\n        kwargs...)\n    return DiffEqCodim2Problem(\n        ode,\n        param_axis1,\n        param_axis2,\n        t_domain;\n        kwargs...)\nend\n\nend  # module\n", "meta": {"hexsha": "ba505d8db38ce0e0ffe883a0bc1bdfe77a9166cc", "size": 1799, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/examples/predator_prey.jl", "max_stars_repo_name": "jhardenberg/Bifurcations.jl", "max_stars_repo_head_hexsha": "cc1bfe55389efdfa0c4e6a817707c235afe1aea8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2018-07-06T21:05:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:24:57.000Z", "max_issues_repo_path": "src/examples/predator_prey.jl", "max_issues_repo_name": "jhardenberg/Bifurcations.jl", "max_issues_repo_head_hexsha": "cc1bfe55389efdfa0c4e6a817707c235afe1aea8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2018-07-11T08:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-23T09:42:42.000Z", "max_forks_repo_path": "src/examples/predator_prey.jl", "max_forks_repo_name": "jhardenberg/Bifurcations.jl", "max_forks_repo_head_hexsha": "cc1bfe55389efdfa0c4e6a817707c235afe1aea8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-07-11T08:41:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T19:52:03.000Z", "avg_line_length": 22.7721518987, "max_line_length": 82, "alphanum_fraction": 0.5619788772, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7599828374643355}}
{"text": "using Plots\nusing Random\nusing Pkg; Pkg.add(\"LaTeXStrings\")\nusing LaTeXStrings\n\n# Set working directory\ncd(\"/Users/elvis/Documents/DSI/courses/content/stochastic-approximations/julia-code/\")\n\n# Set seed\nRandom.seed!(123)\n\n# Generate MC points\nn = 4000\npoints_x = 3 .* rand(n)\npoints_y = -3 .+ 7 .* rand(n)\n\n# Define functions\nf1(x) = 3*abs(cos(x)) .+ 2*sin(x)\nf2(x) = -3*abs(cos(x)) .+ 2*sin(x)\n\n\n# Label points in circle\nlabels = [f2(x) <= y <= f1(x) for (x,y) in zip(points_x, points_y)]\n\n# Create curves\nx_vals = 0:.01:3\nf1_x = 3*abs.(cos.(x_vals)) .+ 2*sin.(x_vals)\nf2_x = -3*abs.(cos.(x_vals)) .+ 2*sin.(x_vals)\n\n# Create plot of MC points\nplot(points_x, points_y, seriestype = :scatter,\n     group = .!labels,\n     legend = false,\n     ms = 3,\n     bg = RGB(247/255, 236/255, 226/255))\n\n# Add curves to plot\nplot!(x_vals, f1_x, seriestype= :line, label = L\"f_1(x)\", lc = :blue,\n    legend = false)\nplot!(x_vals, f2_x, seriestype= :line, label = L\"f_2(x)\", lc = :violet)\nplot!(x_vals, f1_x, fillrange = [f2_x, f1_x], fillcolor = :blue, alpha = .12)\n\n\n# Area estimate\narea = 21*sum(labels)/n\n\nsavefig(\"../images/area-ex1-monte-carlo.svg\")\n", "meta": {"hexsha": "7ec7ce690eacdd5399dd08199cc3a9e9abef7175", "size": 1143, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/stochastic-approximations/code/area_ex_1.jl", "max_stars_repo_name": "seanrattana/courses", "max_stars_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-08-21T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T15:46:58.000Z", "max_issues_repo_path": "content/stochastic-approximations/code/area_ex_1.jl", "max_issues_repo_name": "seanrattana/courses", "max_issues_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-08-23T06:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-26T12:47:12.000Z", "max_forks_repo_path": "content/stochastic-approximations/code/area_ex_1.jl", "max_forks_repo_name": "seanrattana/courses", "max_forks_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-08-18T21:23:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T19:14:33.000Z", "avg_line_length": 23.8125, "max_line_length": 86, "alphanum_fraction": 0.6456692913, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7599828319476555}}
{"text": "using Turing, ReverseDiff, Memoization\nusing DifferentialEquations\nusing Plots\nusing Statistics\nusing StatsPlots\nTuring.setadbackend(:reversediff)\nTuring.setrdcache(true)\nusing Distributions\nusing LinearAlgebra\n\n# here we are simulating the signal of two coupled oscillators\n# with amplitudes A1 and A2 of kBT/k and kBT/(k+c) where c is the coupling constant\n# D = kBT/gamma\n# in terms of the standard parameters of a OU process:\n# sigma = sqrt(2*D)\n# Theta = D/A\n\nfunction corr_osc(c)\n    # function that returns two time series that are correlated through a coupling coefficient c\n    μ = 0.0 # mean is zero\n    σ = sqrt(2) # D=1\n    Θ1 = 1.0\n    Θ2 = 1.0+abs(c)\n\n    W1 = OrnsteinUhlenbeckProcess(Θ1,μ,σ,0.0,1.0)\n    W2 = OrnsteinUhlenbeckProcess(Θ2,μ,σ,0.0,1.0)\n    prob1 = NoiseProblem(W1,(0.0,100.0))\n    prob2 = NoiseProblem(W2,(0.0,100.0))\n    sol1 = solve(prob1;dt=0.1)\n    sol2 = solve(prob2;dt=0.1)\n\n    # creating the two correlated\n    x1 = (sol1.u .+ sol2.u)/2\n    if c>0 \n        x2 = (sol1.u .- sol2.u)/2\n    else\n        x2 = (sol2.u .- sol1.u)/2\n    end\n    return x1,x2\nend\n\n# Ornstein-Uhlenbeck process\n@model ou(rn,T,delta_t) = begin\n    ampl ~ Uniform(0.0,5.0)\n    b ~ beta(5.0,1.0)\n    \n    rn[1] ~ Normal(0,sqrt(ampl))\n    \n    for i=2:T\n        rn[i] ~ Normal(rn[i-1]*b,sqrt(ampl*(1-b^2)))\n    end\nend\n\n# Ornstein-Uhlenbeck process of two coupled oscillators\n@model ou_corr(rn1,rn2,T,delta_t) = begin\n    ampl1 ~ Uniform(0.0,5.0)\n    ampl2 ~ Uniform(0.0,5.0)\n    d ~ Uniform(0.0,5.0)\n    b1 = exp(-delta_t*d/ampl1)\n    b2 = exp(-delta_t*d/ampl2)\n\n    rn1[1] ~ Normal(0,sqrt(ampl1))\n    rn2[1] ~ Normal(0,sqrt(ampl2))   \n\n    for i=2:T\n        rn1[i] ~ Normal(rn1[i-1]*b1,sqrt(ampl1*(1-b1^2)))\n        rn2[i] ~ Normal(rn2[i-1]*b2,sqrt(ampl2*(1-b2^2)))\n    end\nend\n\n# Ornstein-Uhlenbeck process with added Gaussian noise\n@model oupn(rn,T,delta_t,::Type{R}=Vector{Float64}) where {R} = begin\n    ampl ~ Uniform(0.0,5.0)\n    b ~ Beta(5.0,1.0)\n    noise_ampl ~ Uniform(0.0,1)\n    \n    b = exp(-delta_t/tau)\n    r = R(undef, T)\n    \n    r[1] ~ Normal(0,sqrt(ampl))\n    \n    for i=2:T\n        r[i] ~ Normal(r[i-1]*b,sqrt(ampl*(1-b^2)))\n    end\n    rn ~ MvNormal(r,sqrt(noise_ampl))\nend\n\nx1, x2 = corr_osc(-0.8)\n\np1 = Plots.plot(x1)\np1 = Plots.plot!(x2)\n\npearson = Statistics.cor(x1,x2)\nprintln(pearson)\n\n# lets see whether we can estimate c from the data\ny1 = x1 .+ x2\ny2 = x1 .- x2\nchn = sample(ou_corr(y1,y2,length(y1),0.1), NUTS(0.65), 10000)\n\nprint(describe(chn))\np2 = plot(chn)\n\nampl1 = Array(chn[:ampl1])\nampl2 = Array(chn[:ampl2])\n\nif ampl1>ampl2\n    c = (ampl1 .- ampl2)./ampl2\nelse\n    c = (ampl1 .- ampl2)./ampl1\nend\n\nprintln(\"A1,A2: \",mean(ampl1),\",\",mean(ampl2))\nprintln(\"c estimate: \",mean(c),\"std: \",std(c))\n", "meta": {"hexsha": "f7ed8d774593b929f9b14add749edb78f9cbe5b9", "size": 2740, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Correlation.jl", "max_stars_repo_name": "laofei177/Ornstein-Uhlenbeck-Correlations", "max_stars_repo_head_hexsha": "d1bcf4e1ec80ad3bf5e7851ac3d63c728aff76eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-29T02:28:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-23T08:32:29.000Z", "max_issues_repo_path": "Correlation.jl", "max_issues_repo_name": "laofei177/Ornstein-Uhlenbeck-Correlations", "max_issues_repo_head_hexsha": "d1bcf4e1ec80ad3bf5e7851ac3d63c728aff76eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Correlation.jl", "max_forks_repo_name": "laofei177/Ornstein-Uhlenbeck-Correlations", "max_forks_repo_head_hexsha": "d1bcf4e1ec80ad3bf5e7851ac3d63c728aff76eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-12-29T02:28:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T08:32:37.000Z", "avg_line_length": 23.8260869565, "max_line_length": 96, "alphanum_fraction": 0.6226277372, "num_tokens": 1076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.759982823029588}}
{"text": "T = 3\nn = 2\nm = 1\n\nA = [1.0 1.0; 0.0 1.0]\nB = [0.0; 1.0]\n\nQ = [1.0 0.0; 0.0 1.0]\nR = [1.0]\n\nx_init = [1.0; 0.0]\n\nnz = T * n + (T - 1) * m + T * n\n\nfunction unpack(z)\n\tx3 = z[1:n]\n\tu2 = z[n .+ (1:m)]\n\tx2 = z[n + m .+ (1:n)]\n\tu1 = z[n + m + n .+ (1:m)]\n\tx1 = z[n + m + n + m .+ (1:n)]\n\ty3 = z[n + m + n + m + n .+ (1:n)]\n\ty2 = z[n + m + n + m + n + n .+ (1:n)]\n\ty1 = z[n + m + n + m + n + n + n .+ (1:n)]\n\n\treturn x3, u2, x2, u1, x1, y3, y2, y1\nend\n\nz0 = rand(nz)\n\nfunction lagrangian(z, x_init)\n\tx3, u2, x2, u1, x1, y3, y2, y1 = unpack(z)\n\n\tL = 0.0\n\n\t# objective\n\tL += transpose(x3) * Q * x3\n\tL += (transpose(u2) * R * u2)[1]\n\tL += transpose(x2) * Q * x2\n\tL += (transpose(u1) * R * u1)[1]\n\tL += transpose(x1) * Q * x1\n\n\t# constraints\n\tL += transpose(y3) * (A * x2 + B * u2[1] - x3)\n\tL += transpose(y2) * (A * x1 + B * u1[1] - x2)\n\tL += transpose(y1) * (x_init - x1)\n\n\treturn L\nend\n\n@variables z_sym[1:nz]\n@variables x_sym[1:n]\n\nL = lagrangian(z_sym, x_sym)\nL = simplify.(L)\n\ndL = Symbolics.gradient(L, z_sym)\nddL = Symbolics.hessian(L, z_sym)\nddLx = Symbolics.jacobian(dL, x_sym)\n\nL_grad = eval(Symbolics.build_function(dL, z_sym, x_sym)[1])\nL_hess = eval(Symbolics.build_function(ddL, z_sym, x_sym)[1])\nLx_hess = eval(Symbolics.build_function(ddLx, z_sym, x_sym)[1])\n\nfunction solve(z0, x_init)\n\tz = copy(z0)\n\n\t∇L = L_grad(z, x_init)\n\n\tprintln()\n\tfor i = 1:10\n\t\tr_norm = norm(∇L)\n\t\tprintln(\"iter ($i)\")\n\t\tprintln(\"\tgrad norm: $(r_norm)\")\n\t\tr_norm < 1.0e-8 && break\n\n\t\t∇²L = L_hess(z, x_init)\n\n\t\tΔ = ∇²L \\ ∇L\n\n\t\tα = 1.0\n\t\tẑ = z - α * Δ\n\n\t\t∇L̂ = L_grad(ẑ, x_init)\n\n\t\titer = 1\n\t\twhile norm(∇L̂) > norm(∇L)\n\t\t\tα *= 0.5\n\t\t\tẑ = z - α * Δ\n\t\t\t∇L̂ = L_grad(ẑ, x_init)\n\t\t\titer += 1\n\n\t\t\tif iter > 100\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\n\t\tz = ẑ\n\t\t∇L = ∇L̂\n\tend\n\n\treturn z, ∇L, L_hess(z, x_init)\nend\n\nz_sol, ∇L_sol, ∇²L_sol = solve(z0, x_init)\nK_direct = (∇²L_sol \\ Lx_hess(z_sol, x_init))[n + m + n .+ (1:m), :]\n\n# LQR solution\nK, P = tvlqr([A for t = 1:T-1], [B for t = 1:T-1], [Q for t = 1:T], [R[1,1] for t = 1:T-1])\n\n@assert norm(K[1] - K_direct) < 1.0e-8\n", "meta": {"hexsha": "180cfe1e2694218bedd83c89993e757d42e51f13", "size": 2042, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/development/direct_lqr_3.jl", "max_stars_repo_name": "thowell/motion_planning", "max_stars_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2021-02-07T10:46:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:30:20.000Z", "max_issues_repo_path": "examples/development/direct_lqr_3.jl", "max_issues_repo_name": "thowell/DirectMotionPlanning", "max_issues_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-10-07T05:36:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-11T17:16:28.000Z", "max_forks_repo_path": "examples/development/direct_lqr_3.jl", "max_forks_repo_name": "thowell/motion_planning", "max_forks_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-01-25T19:23:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T06:43:01.000Z", "avg_line_length": 18.3963963964, "max_line_length": 91, "alphanum_fraction": 0.5210577865, "num_tokens": 983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.759982821971942}}
{"text": "using Pkg; Pkg.activate(pwd())\nusing DEMC\nusing Random\nusing LinearAlgebra\nusing Distributions\nRandom.seed!(319531501)\n\n# generate data\nnobs = 1000\nnpar = 25\nΣ = ones(npar, npar)\nfor i = 1:npar\n    for iprime = 1:i\n        if i != iprime\n            Σ[i, iprime] = 0.25\n            Σ[iprime, i] = 0.25\n        end\n    end\nend\n\nDataDistribution = MvNormal(zeros(npar), Σ)\nX = zeros(nobs, npar+1)\nX[:,1] .= 1.\nfor iobs = 1:nobs\n    X[iobs, 2:end] .= rand(DataDistribution)\nend\n\nβ = 1 .+ rand(npar+1)*3\ny = X*β + randn(nobs)\n\n# log objective function - for correct std errors need to use optimal weights\nlog_obj(b) = -0.5 * sum((y.-X*b).^2)\n\n\n# set up of DEMCz chain\nndim = length(β)\nopts = DEMC.demcopt(ndim)\nopts.blockindex = [1:ndim] # parameter blocks: here choose all parameters to be updated simultaenously\nopts.Nblocks = length(opts.blockindex)\nopts.eps_scale = 1e-5*ones(ndim) # scale of random error around DE update\nopts.γ = 2. # scale of DE update, 2.38 is the \"optimal\" number for a normal distribution\nopts.N = 5 # number of chains\nopts.K = 10 # every K steps add current N draws to Z\n# Number of iterations in Chain\nopts.Ngeneration = 100000\nopts.autostop = :Rhat\nopts.autostop_every = 2000\nopts.autostop_Rhat = 1.1\nopts.print_step = 1000\nopts.verbose = false\n\nZ = randn((10*ndim, ndim))\n\n# run chain\nmc, Z = DEMC.demcz_sample(log_obj, Z, opts)\n\n# drop first half of chain\nN, Npar, Ntot = size(mc.chain)\nkeep = Int(Ntot-opts.autostop_every)+1:Ntot\nNgen_burned = length(keep)\nchain_burned = mc.chain[:,:,keep]\nchainflat = DEMC.flatten_chain(chain_burned, N, Ngen_burned, Npar)'\n\n# covariance of estimates\nb, Σb = DEMC.mean_cov_chain(chain_burned)\n# correct std errors for incorrect weighting matrix\n# OLS\nbols = (X'*X)\\(X'*y)\nui = y .- X*bols\ns2hat = (1/(nobs-npar)) * sum(ui.^2)\nΣols = inv(X'X)*s2hat\n\n# difference simulated to OLS\nprintln(\"\\n MCMC estimates: \", b, \"\\n dist to OLS: \", b .- bols)\n\naccept_ratio, Rhat = DEMC.convergence_check(mc.chain, mc.log_obj, \"none\"; verbose = false, parnames = [])\n", "meta": {"hexsha": "4a6888a58013f8debdba4ade9abd77756241a990", "size": 2015, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/example_linreg.jl", "max_stars_repo_name": "chrished/DEMC.jl", "max_stars_repo_head_hexsha": "cfc68c617072b464924ca50e96b08b037959cd78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-03-14T23:54:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T21:37:13.000Z", "max_issues_repo_path": "test/example_linreg.jl", "max_issues_repo_name": "chrished/DEMC.jl", "max_issues_repo_head_hexsha": "cfc68c617072b464924ca50e96b08b037959cd78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-05-16T12:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-03T18:33:41.000Z", "max_forks_repo_path": "test/example_linreg.jl", "max_forks_repo_name": "chrished/DEMC.jl", "max_forks_repo_head_hexsha": "cfc68c617072b464924ca50e96b08b037959cd78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-02-12T10:31:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-27T06:57:02.000Z", "avg_line_length": 26.1688311688, "max_line_length": 105, "alphanum_fraction": 0.6868486352, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7599828198726329}}
{"text": "# Test Benders Algorithm for Mixed Integer Linear Programming\n# Edward J. Xu, edxu96@outlook.com\n# April 5th, 2019\n# ---------------------------------------------------------------------------\npush!(LOAD_PATH, \"$(homedir())/Desktop/Benders Decomposition, MILP\")\ncd(\"$(homedir())/Desktop/Benders Decomposition, MILP\")\nusing Benders\n# ---------------------------------------------------------------------------\n# Test Example 1: mat_a and mat_b being column vector\nn_x = 1\nn_y = 1\nvec_min_y = hcat([0])\nvec_max_y = hcat([10])\nvec_c = hcat([5])\nvec_f = hcat([-3])\nvec_b = hcat([4; 0; -13])\nmat_a = hcat([1; 2; 1])\nmat_b = hcat([2; -1; -3])\nBenders.milp(n_x = n_x,\n             n_y = n_y,\n             vec_min_y = vec_min_y,\n             vec_max_y = vec_max_y,\n             vec_c = vec_c,\n             vec_f = vec_f,\n             vec_b = vec_b,\n             mat_a = mat_a,\n             mat_b = mat_b,\n             epsilon = 0,\n             timesIterationMax = 5)\n# ---------------------------------------------------------------------------\n# Test Example 2: mat_a and mat_b being matrix\nn_x_2 = 2\nn_y_2 = 2\nvec_min_y_2 = hcat([0; 0])\nvec_max_y_2 = hcat([10; 10])\nvec_c_2 = hcat([5; 3])\nvec_f_2 = hcat([-3; 1])\nvec_b_2 = hcat([4; 0; -13])\nmat_a_2 = [1 3; 2 1; 1 -5]\nmat_b_2 = [2 -4; -1 2; -3 1]\nBenders.milp(n_x = n_x_2,\n             n_y = n_y_2,\n             vec_min_y = vec_min_y_2,\n             vec_max_y = vec_max_y_2,\n             vec_c = vec_c_2,\n             vec_f = vec_f_2,\n             vec_b = vec_b_2,\n             mat_a = mat_a_2,\n             mat_b = mat_b_2,\n             epsilon = 0.000001,\n             timesIterationMax = 10)\n# ---------------------------------------------------------------------------\n# Test Example 3: sub and ray problem\nn_x_3 = 2\nn_y_3 = 2\nvec_min_y_3 = hcat([0; 0])\nvec_max_y_3 = hcat([2; 2])\nvec_c_3 = hcat([2; 6])\nvec_f_3 = hcat([2; 3])\nvec_b_3 = hcat([5; 4])\nmat_a_3 = [-1 2; 1 -3]\nmat_b_3 = [3 -1; 2 2]\nBenders.milp(n_x = n_x_3,\n             n_y = n_y_3,\n             vec_min_y = vec_min_y_3,\n             vec_max_y = vec_max_y_3,\n             vec_c = vec_c_3,\n             vec_f = vec_f_3,\n             vec_b = vec_b_3,\n             mat_a = mat_a_3,\n             mat_b = mat_b_3,\n             epsilon = 0.000001,\n             timesIterationMax = 10)\n", "meta": {"hexsha": "a781c946623662f5d000674eb55d202255b72de5", "size": 2291, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/test_milp.jl", "max_stars_repo_name": "eitt/BendersDecomposition", "max_stars_repo_head_hexsha": "2fcf52de52eff264450e33ef6d5651428da28bab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-08-10T14:49:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T13:41:44.000Z", "max_issues_repo_path": "src/test_milp.jl", "max_issues_repo_name": "edxu96/BendersMilpOptimization", "max_issues_repo_head_hexsha": "2fcf52de52eff264450e33ef6d5651428da28bab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test_milp.jl", "max_forks_repo_name": "edxu96/BendersMilpOptimization", "max_forks_repo_head_hexsha": "2fcf52de52eff264450e33ef6d5651428da28bab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-10-22T15:09:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T06:23:07.000Z", "avg_line_length": 30.9594594595, "max_line_length": 77, "alphanum_fraction": 0.4666084679, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570318, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7599526860183313}}
{"text": "#\n# Denoise an SPD Example with Douglas Rachford\n#\n# Denoise an SPD Example with Parallel Douglas-Rachford to minimize the\n#\n# L2-TV functional with anisotropic TV\n#\n# where the example is the same data and cost as for SPD_Image_CP_vs_CPPA\n#\n# This example and its data is used for comparison in Section 6.2 of\n#\n# > R. Bergmann, R. Herzog, M. Silva Louzeiro, D. Tenbrinck, J. Vidal Núñez:\n# > _Fenchel Duality Theory and a Primal-Dual Algorithm on Riemannian Manifolds_,\n# > arXiv: [1908.02022](https://arxiv.org/abs/1908.02022)\n#\nusing Manopt, Manifolds\nusing Images, CSV, DataFrames, LinearAlgebra, JLD2, Dates\n#\n# Settings\nexperiment_name = \"SPD_Image_DR\"\nexport_orig = true\nexport_result = true\nexport_table = true\nuse_debug = true\nasy_render_detail = 2\nresults_folder = joinpath(@__DIR__, \"Image_TV\")\ncomparison_data = joinpath(\n    @__DIR__, \"..\", \"CyclicProximalPoint\", \"Image_TV\", \"SPD_Image_CPPA-cost.jld2\"\n)\n!isdir(results_folder) && mkdir(results_folder)\n#\n# Parameters\nη = 0.58\nλ = 0.93\nα = 6.0\n#\n# Manifold & Data\nf = artificial_SPD_image2(32)\nif export_orig\n    fn = joinpath(results_folder, experiment_name * \"-orig.asy\")\n    asymptote_export_SPD(fn; data=f, scale_axes=(7.5, 7.5, 7.5))\n    render_asymptote(fn; render=asy_render_detail)\nend\nsC = StopAfterIteration(400)\ntry\n    cppa_data = load(comparison_data)\n    cost_threshold = cppa_data[\"cost_function_value\"]\n    cppa_iter = cppa_data[\"iterations\"]\n    global sC = StopWhenAny(StopAfterIteration(400), StopWhenCostLess(cost_threshold))\n    @info \"Comparison to CPPA (`SPDImage_CPPA.jl`) and its cost after $(cppa_iter) iterations of $cost_threshold.\"\ncatch e\n    msg = sprint(showerror, e)\n    @info \"Comparison to CPPA (`CyclicProximalPoint/SPDImage_CPPA.jl`) not possible, data file $(comparison_data) either missing or corrupted.\\n Error: $(msg).\\n\\n Starting with a default stopping criterion.\"\nend\n#\n# Build Problem for L2-TV\npixelM = SymmetricPositiveDefinite(3);\nM = PowerManifold(pixelM, NestedPowerRepresentation(), size(f)...)\nd = length(size(f))\nrep(d) = (d > 1) ? [ones(Int, d)..., d] : d\nfidelity(x) = 1 / 2 * distance(M, x, f)^2\nΛ(x) = forward_logs(M, x) # on T_xN\nprior(x) = norm(norm.(Ref(pixelM), repeat(x, rep(d)...), Λ(x)), 1)\n#\n# Setup & Optimize\nprint(\"--- Douglas–Rachford with η: $(η) and λ: $(λ) ---\\n\")\ncost(x) = 1 / α * fidelity(x[1]) + prior(x[1])\nN = PowerManifold(M, NestedPowerRepresentation(), 5)\nprox1 = (η, x) -> [prox_distance(M, η, f, x[1]), prox_parallel_TV(M, α * η, x[2:5])...]\nprox2 = (η, x) -> fill(mean(M, x, GradientDescentEstimation(); stop_iter=4), 5)\nx0 = fill(f, 5)\n@time o = DouglasRachford(\n    N,\n    cost,\n    [prox1, prox2],\n    x0;\n    λ=i -> η,\n    α=i -> λ, # map from Paper notation of BPS16 to toolbox notation\n    debug=use_debug ? [:Iteration, \" | \", :Cost, \"\\n\", 10, :Stop] : missing,\n    record=export_table ? [:Iteration, :Cost] : missing,\n    stopping_criterion=sC,\n    return_options=true,\n)\ny = get_solver_result(o)[1]\nexport_table && (r = get_record(o))\n#\n# Result\nnumIter = length(r)\nif export_result\n    fn = joinpath(\n        results_folder,\n        experiment_name * \"img-result-$(numIter)-α$(replace(string(α), \".\" => \"-\")).asy\",\n    )\n    asymptote_export_SPD(fn; data=y, scale_axes=(7.5, 7.5, 7.5))\n    render_asymptote(fn; render=asy_render_detail)\nend\nif export_table\n    # scale cost back for saving such that its comparable with the other two results\n    A = cat([ri[1] for ri in r], [ri[2] / α for ri in r]; dims=2)\n    CSV.write(\n        joinpath(results_folder, experiment_name * \"-Cost.csv\"),\n        DataFrame(A);\n        writeheader=false,\n    )\nend\n", "meta": {"hexsha": "01e45223aeeed31d62a5c0e7cb730da805fb93d1", "size": 3606, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/DouglasRachford/SPD_Image_DR_vs_CPPA.jl", "max_stars_repo_name": "fkastner/Manopt.jl", "max_stars_repo_head_hexsha": "89c60404c7cf756102bcf45dd58dc443ef2b2d4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 141, "max_stars_repo_stars_event_min_datetime": "2020-03-30T08:00:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T09:37:54.000Z", "max_issues_repo_path": "examples/DouglasRachford/SPD_Image_DR_vs_CPPA.jl", "max_issues_repo_name": "fkastner/Manopt.jl", "max_issues_repo_head_hexsha": "89c60404c7cf756102bcf45dd58dc443ef2b2d4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 90, "max_issues_repo_issues_event_min_datetime": "2020-03-30T08:00:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T08:55:37.000Z", "max_forks_repo_path": "examples/DouglasRachford/SPD_Image_DR_vs_CPPA.jl", "max_forks_repo_name": "fkastner/Manopt.jl", "max_forks_repo_head_hexsha": "89c60404c7cf756102bcf45dd58dc443ef2b2d4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2020-04-14T11:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T21:36:59.000Z", "avg_line_length": 34.0188679245, "max_line_length": 208, "alphanum_fraction": 0.6835829174, "num_tokens": 1141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.759952681512658}}
{"text": "# # [Linear Time Continuous System with Controls](@id linear_continuous_controls)\n# \n# Now we will extend the [`previous example`](@ref linear_continuous) by adding some exegeneous control signals.\n# As always, we will generate some data via `OrdinaryDiffEq.jl`\n\nusing DataDrivenDiffEq\nusing ModelingToolkit\nusing LinearAlgebra\nusing OrdinaryDiffEq\n#md using Plots \n\nA = [-0.9 0.2; 0.0 -0.2]\nB = [0.0; 1.0]\nu0 = [10.0; -10.0]\ntspan = (0.0, 10.0)\n\nf(u,p,t) = A*u .+ B .* sin(0.5*t)\n\nsys = ODEProblem(f, u0, tspan)\nsol = solve(sys, Tsit5(), saveat = 0.05);\n\n# We will use the data provided by our problem, but add the control signal `U = sin(0.5*t)` to it. \nX = Array(sol) \nt = sol.t \ncontrol(u,p,t) = [sin(0.5*t)]\nprob = ContinuousDataDrivenProblem(X, t, U = control)\n\n# And plot the problems data.\n\n#md plot(prob) \n\n# Again, we will use `gDMD` to estimate the systems dynamics. Since we have a control signal \n# defined in the problem, the algorithm will detect it automatically and use `gDMDc`:\n\nres = solve(prob, DMDSVD(), digits = 1)\n#md println(res) \n\n# We see that the system has been recovered correctly, indicated by the small error and high AIC score of the result. We can confirm this by looking at the resulting [`Basis`](@ref)\n\n#md \nsystem = result(res)\n#md println(system)\n\n# And also plot the prediction of the recovered dynamics\n\n#md plot(res) \n\n# Again, we can have a look at the generator of the system, which is independent from the inputs.\n\ngenerator(system)\n\n# Sticking to the same procedure as earlier, we now use a linear sparse regression to solve the problem\n\n@parameters t\n@variables x[1:2](t) u[1:1](t)\n\nbasis = Basis([x; u], x, controls = u, independent_variable = t, name = :LinearBasis)\n#md print(basis) #hide\n\n# Note that we added a new variable `u[1](t)` as a control to both the equations and the basis constructor. \n# Afterwards, we simply `solve` the already defined problem with our `Basis` and a `SparseOptimizer`\n\nsparse_res = solve(prob, basis, STLSQ(1e-1))\n#md println(sparse_res)\n\n# Which holds the same equations\nsparse_system = result(sparse_res)\n#md println(sparse_system)\n\n# Again, we can have a look at the result\n\n#md plot(\n#md     plot(prob), plot(sparse_res), layout = (1,2)\n#md )\n\n# Both results can be converted into an `ODESystem`. To include the control signal, we simply \n# substitute the control variables in the corresponding equations.\n\nsubs_control = (u[1] => sin(0.5*t))\n\neqs = map(equations(sparse_system)) do eq\n    eq.lhs ~ substitute(eq.rhs, subs_control)\nend\n\n@named sys = ODESystem(\n    eqs, \n    get_iv(sparse_system),\n    states(sparse_system), \n    parameters(sparse_system)\n    );\n\n# And simulated using `OrdinaryDiffEq.jl` using the (known) initial conditions and the parameter mapping of the estimation.\n\nx0 = [x[1] => u0[1], x[2] => u0[2]]\nps = parameter_map(sparse_res)\n\node_prob = ODEProblem(sys, x0, tspan, ps)\nestimate = solve(ode_prob, Tsit5(), saveat = prob.t);\n\n# And look at the result\n#md plot(sol, color = :black)\n#md plot!(estimate, color = :red, linestyle = :dash)\n\n#md # ## [Copy-Pasteable Code](@id linear_continuous_copy_paste)\n#md #\n#md # ```julia\n#md # @__CODE__\n#md # ```\n\n@test all(aic(sparse_res) .>= 1e3) #src\n@test all(l2error(sparse_res) .<= 5e-1) #src\n@test all(determination(sparse_res) .>= 0.97) #src\n@test Array(sol) ≈ Array(estimate) rtol = 5e-2 #src\n", "meta": {"hexsha": "bf4819847b09c733c376e7cdd35ffce2ad76af18", "size": 3349, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples/3_linear_continuous_system_controls.jl", "max_stars_repo_name": "JuliaDiffEq/DataDrivenDiffEq.jl", "max_stars_repo_head_hexsha": "27f5537d2d04719b80f5785531b2b02e27a8208f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2019-11-22T17:20:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-07T17:10:27.000Z", "max_issues_repo_path": "docs/examples/3_linear_continuous_system_controls.jl", "max_issues_repo_name": "JuliaDiffEq/DataDrivenDiffEq.jl", "max_issues_repo_head_hexsha": "27f5537d2d04719b80f5785531b2b02e27a8208f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 53, "max_issues_repo_issues_event_min_datetime": "2019-11-22T17:20:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T15:11:55.000Z", "max_forks_repo_path": "docs/examples/3_linear_continuous_system_controls.jl", "max_forks_repo_name": "AlCap23/DataDrivenDiffEq", "max_forks_repo_head_hexsha": "3be031060d5a3cad08473506be60108e572ac0fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-11-22T18:36:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:36:14.000Z", "avg_line_length": 29.3771929825, "max_line_length": 181, "alphanum_fraction": 0.7046879666, "num_tokens": 1005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.759952668168187}}
{"text": "#*************************************************************************#\n#\n# AbstractType\n#\n#*************************************************************************#\nabstract type ElementwiseOperator <: AparametricModel end\n\n\n#*************************************************************************#\n#\n# Generate Buffers\n#\n#*************************************************************************#\nfunction dx_buffer(f::ElementwiseOperator)\n    return Diagonal{Float64}(zeros(f.noutputs))\nend\n\n\n#*************************************************************************#\n#\n# LogisticFunction\n#\n#*************************************************************************#\n\"\"\"\n    LogisticFunction(n)\n\nInitialize `ParametricModel` representing logistic function. It applies\n`f(x) = 1 / (1+exp(-x))` elementwise to a given input vector.\n`n` is the input vector dimension.\n\"\"\"\nstruct LogisticFunction <: ElementwiseOperator\n    ninputs::Int\n    noutputs::Int\nend\n\nfunction LogisticFunction(n::Int)\n    LogisticFunction(n, n)\nend\n\nfunction _evaluate!(f::LogisticFunction,\n                    x::AbstractVector{<:Real},\n                    z::AbstractVector{Float64},\n                    dx::AbstractMatrix{Float64})\n\n    z .= 1 ./ (1+exp.(-x))\n\n    if !isempty(dx)\n        dx.diag .=  z .* (1-z)\n    end\nend\n\n\n#*************************************************************************#\n#\n# Hyperbolic Tangent\n#\n#*************************************************************************#\n\"\"\"\n    HyperbolicTangent(n)\n\nInitialize `ParametricModel` representing hyperbolic tangent. It\napplies `f(x) = tanh(x)` elementwise to a given input vector.\n `n` is the input vector dimension.\n\"\"\"\nstruct HyperbolicTangent <: ElementwiseOperator\n    ninputs::Int\n    noutputs::Int\nend\n\nfunction HyperbolicTangent(n::Int)\n    HyperbolicTangent(n, n)\nend\n\nfunction _evaluate!(f::HyperbolicTangent,\n                    x::AbstractVector{<:Real},\n                    z::AbstractVector{Float64},\n                    dx::AbstractMatrix{Float64})\n    z .= tanh.(x)\n\n    if !isempty(dx)\n        dx.diag .=  1 - z.^2\n    end\nend\n\n\n#*************************************************************************#\n#\n# AffineMap\n#\n#*************************************************************************#\n\"\"\"\n    AffineMap(a[, b])\n\nInitialize `ParametricModel` representing affine function. It applies\n`f(x) = a*x + b` elementwise to a given input vector. `a` and\n`b` are vectors.\n\"\"\"\nstruct AffineMap <: ElementwiseOperator\n    ninputs::Int\n    noutputs::Int\n    a::Vector{Float64}\n    b::Vector{Float64}\nend\n\nfunction AffineMap{R<:Real, S<:Real}(a::Vector{R}, b::Vector{S}=zeros(length(a)))\n    if length(a) != length(b)\n        throw(ArgumentError(\"Vector `a` and `b` should have the same size.\"))\n    end\n\n    n = length(a)\n    AffineMap(n, n, a, b)\nend\n\nfunction _evaluate!(f::AffineMap,\n                    x::AbstractVector{<:Real},\n                    z::AbstractVector{Float64},\n                    dx::AbstractMatrix{Float64})\n    z .= f.a.*x + f.b\n\n    if !isempty(dx)\n        dx.diag .=  f.a\n    end\nend\n\n\n#*************************************************************************#\n#\n# Identity\n#\n#*************************************************************************#\n\"\"\"\n    Identity(n)\n\nInitialize `ParametricModel` representing identity function.  It applies\n`f(x) = x` elementwise to a given input vector. `n` is the input vector\ndimension.\n\"\"\"\nstruct Identity <: ElementwiseOperator\n    ninputs::Int\n    noutputs::Int\nend\n\nfunction Identity(n::Int)\n    Identity(n, n)\nend\n\nfunction _evaluate!(f::Identity,\n                    x::AbstractVector{<:Real},\n                    z::AbstractVector{Float64},\n                    dx::AbstractMatrix{Float64})\n    z .= x\n\n    if !isempty(dx)\n        dx.diag .=  1\n    end\nend\n", "meta": {"hexsha": "d89c94b84b8e12b6fc1b14ba894d998e8eea1c38", "size": 3811, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/static_models/elementwise_operator.jl", "max_stars_repo_name": "antonior92/ParallelTrainingNN.jl", "max_stars_repo_head_hexsha": "76d829dfc39182f196ef00cfa1908f90c0175250", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/static_models/elementwise_operator.jl", "max_issues_repo_name": "antonior92/ParallelTrainingNN.jl", "max_issues_repo_head_hexsha": "76d829dfc39182f196ef00cfa1908f90c0175250", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/static_models/elementwise_operator.jl", "max_forks_repo_name": "antonior92/ParallelTrainingNN.jl", "max_forks_repo_head_hexsha": "76d829dfc39182f196ef00cfa1908f90c0175250", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2738853503, "max_line_length": 81, "alphanum_fraction": 0.4710049856, "num_tokens": 842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305639, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7598867597577026}}
{"text": "using LinearAlgebra;\nusing Printf;\n\nfunction linspace(start::Number, stop::Number, n::Int64)\n\tlinx = zeros(Float64, n);\n\tdelta = (stop - start) / (n - 1);\n\tfor i = 1:n\n\t\tlinx[i] = start + delta * (i - 1)\n\tend\n\treturn linx;\nend\n\nlx = 1.0;\nt = 0.0\nnx = 11;\ndx = lx / (nx - 1);\ndt = 1e-2;\ntlim = 0.1;\nkappa = 1.0\nbeta = dt * kappa / 2.0dx^2;\nt_save = linspace(0.0, tlim, nx);\nsave_count = 1;\n\nfunction solve_linear(n::Int64, a::Float64, b::Float64, c::Float64, r::Array)\n\tA = zeros(n, n);\n\tfor i = 2:n+1\n\t\tfor j = 2:n+1\n\t\t\tif(i-1 == j-1-1)\n\t\t\t\tA[i-1, j-1] = c;\n\t\t\telseif (i-1==j-1)\n\t\t\t\tA[i-1,j-1] = b;\n\t\t\telseif (i-1-1 == j-1)\n\t\t\t\tA[i-1,j-1] = a;\n\t\t\tend\n\t\tend\n\tend\n\treturn A \\ r;\nend\n\nfunction crank_nicolson(u::Array)\n\ta = Float64(0.0);\n\tb = Float64(0.0);\n\tc = Float64(0.0);\n\tr = zeros(Float64, nx - 2);\n\tfor i = 2:nx-1\n\t\ta = -beta;\n\t\tb = 1.0 + 2.0beta;\n\t\tc = -beta;\n\t\tr[i-1] = u[i] + beta*(u[i+1] - 2.0u[i] + u[i-1]);\n\tend\n\tr[begin] = r[begin] - a*u[begin]\n\tr[end] = r[end] - c * u[end];\n\tu[2:end-1] = solve_linear(nx - 2, a, b, c, r) \nend\n\nfunction output(x::Array, u::Array, t::Float64)\n\tfilename = @sprintf(\"cn_t=%4.3f.dat\", t);\n\topen(filename, \"w\") do io\n\t\tfor i = 1:nx\n\t\t\twrite(io, @sprintf(\"%.5f\\t%.5f\\n\", x[i], u[i]));\n\t\tend\n\tend;\nend\n\nfunction main()\n\t@printf(\"beta = %.5f, dt = %.5f, dx = %.5f\\n\", beta, dt, dx);\n\tu = ones(Float64, nx);\n\tu[begin] = u[end] = 0.0;\n\tx = linspace(0, lx, nx);\n\twhile t < tlim\n\t\toutput(x, u, t);\n\t\tcrank_nicolson(u);\n\t\tglobal t = t + dt;\n\tend\nend\n\nmain()\n", "meta": {"hexsha": "2e3b9796262c1e28891bfdb0ebbf77ba00646ecb", "size": 1491, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "cn.jl", "max_stars_repo_name": "Makoto523sys/crank-nicolson", "max_stars_repo_head_hexsha": "8ea01712e6734fda065ff442b4f47204e403ba50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cn.jl", "max_issues_repo_name": "Makoto523sys/crank-nicolson", "max_issues_repo_head_hexsha": "8ea01712e6734fda065ff442b4f47204e403ba50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cn.jl", "max_forks_repo_name": "Makoto523sys/crank-nicolson", "max_forks_repo_head_hexsha": "8ea01712e6734fda065ff442b4f47204e403ba50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1153846154, "max_line_length": 77, "alphanum_fraction": 0.5419181757, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305639, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7598867576920628}}
{"text": "using LinearAlgebra\r\ninclude(\"poisson_linear_system.jl\")\r\ninclude(\"simpson_integrate.jl\")\r\n\r\nfunction poisson_error(numelements)\r\n    xL = -1.0\r\n    xR = +1.0\r\n    wavenumber = pi / 2\r\n    bcleft = bcright = 0.0\r\n\r\n    numpts = numelements + 1\r\n    stepsize = (xR - xL) / numelements\r\n    xrange = range(xL, stop = xR, length = numpts)\r\n\r\n    rhs = cos.(wavenumber * xrange)\r\n    op = -poisson_linear_system(numpts)\r\n    rhs[1] = bcleft / stepsize^2\r\n    rhs[end] = bcright / stepsize^2\r\n    sol = stepsize^2 * (op \\ rhs)\r\n    exactsolution =\r\n        1.0 / wavenumber^2 * (cos.(wavenumber * xrange) .- cos(wavenumber))\r\n    err = simpson_integrate(sol - exactsolution, stepsize)\r\n    return err\r\nend\r\n\r\nfunction convergence_rate(err,dx)\r\n    return diff(log.(err)) ./ diff(log.(dx))\r\nend\r\n\r\npowers = 1:10\r\nnumelements = 2 .^ powers\r\nstepsize = 2.0 ./ numelements\r\nerr = poisson_error.(numelements)\r\nrate = convergence_rate(err,stepsize)\r\n\r\n# using Plots\r\n# plot(stepsize,err,xscale = :log, yscale = :log)\r\n# scatter!(stepsize,err)\r\n", "meta": {"hexsha": "cc737e2fdcea41cceb98bdddb0975fc2a402f480", "size": 1033, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test_poisson.jl", "max_stars_repo_name": "ArjunNarayanan/ExploreJacobi", "max_stars_repo_head_hexsha": "cbeeba2a165ecc61ea294c8974929a28edea6481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test_poisson.jl", "max_issues_repo_name": "ArjunNarayanan/ExploreJacobi", "max_issues_repo_head_hexsha": "cbeeba2a165ecc61ea294c8974929a28edea6481", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_poisson.jl", "max_forks_repo_name": "ArjunNarayanan/ExploreJacobi", "max_forks_repo_head_hexsha": "cbeeba2a165ecc61ea294c8974929a28edea6481", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4871794872, "max_line_length": 76, "alphanum_fraction": 0.6398838335, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7598867513003826}}
{"text": "#=============================================\n\nDefinitions of various similarity functions\n\n=============================================#\n\nusing QuadGK\nusing LinearAlgebra: dot, norm\n\n#====================\nDefinitions of built-in similarity functions\n====================#\n\n#====================\nCosine similarity\n====================#\n\n@doc raw\"\"\"\n    cossim(x,y)\n\nComputes the cosine similarity between two inputs ``x`` and ``y``. Cosine similarity is defined as\n\n``\\text{cossim}(x,y) = \\frac{\\left\\langle x,y\\right\\rangle}{\\|x\\|\\cdot\\|y\\|}``\n\nwhere ``\\left\\langle\\cdot,\\cdot\\right\\rangle`` is an inner product (e.g. dot product) and ``\\|\\cdot\\|`` is its derived norm. This is roughly interpreted as being related to the angle between the inputs ``x`` and ``y``: when ``x`` and ``y`` have low angle between them, `cossim(x,y)` is high (close to ``1``). When ``x`` and ``y`` have large angle between them, `cossim(x,y)` is low (close to ``-1``).\n\n# Arguments\n- `x` and `y`: two inputs for which `dot(x,y)`, `norm(x)`, and `norm(y)` are defined.\n\n# Examples\n```jldoctest; setup = :(using LSHFunctions)\njulia> using LinearAlgebra: dot, norm;\n\njulia> x, y = rand(4), rand(4);\n\njulia> cossim(x,y) == dot(x,y) / (norm(x) * norm(y))\ntrue\n\njulia> z = rand(5);\n\njulia> cossim(x,z)\nERROR: DimensionMismatch(\"dot product arguments have lengths 4 and 5\")\n```\n\nSee also: [`SimHash`](@ref)\n\"\"\"\nfunction cossim(x::AbstractVector, y::AbstractVector)\n    norm_x = norm(x)\n    norm_y = norm(y)\n\n    if norm_x == 0 || norm_y == 0\n        \"x and y must be nonzero\" |> ErrorException |> throw\n    end\n\n    dot(x,y) / (norm_x * norm_y)\nend\n\nfunction cossim(f, g, interval::LSHFunctions.RealInterval)\n    norm_f = L2_norm(f, interval)\n    norm_g = L2_norm(g, interval)\n\n    if norm_f == 0 || norm_g == 0\n        \"f and g must be nonzero\" |> ErrorException |> throw\n    end\n\n    inner_prod(f, g, interval) / (norm_f * norm_g)\nend\n\n#====================\nL^p distance\n====================#\n\n@doc raw\"\"\"\n    ℓp(x::AbstractVector, y::AbstractVector, p::Real=2)\n    ℓ1(x::AbstractVector, y::AbstractVector)\n    ℓ2(x::AbstractVector, y::AbstractVector)\n\nComputes the ``\\ell^p`` distance between a pair of vectors, given by\n\n``\\ell^p(x,y) \\coloneqq \\|x - y\\|_p = \\left(\\sum_i \\left|x_i - y_i\\right|^p\\right)^{1/p}``\n\n`ℓ1(x,y)` is the same as `ℓp(x,y,1)`, and `ℓ2(x,y)` is the same as `ℓp(x,y,2)`.\n\n# Examples\n```jldoctest; setup = :(using LSHFunctions)\njulia> x = [1, 2, 3];\n\njulia> y = [4, 5, 6];\n\njulia> ℓp(x,y,2) == (abs(1-4)^2 + abs(2-5)^2 + abs(3-6)^2)^(1/2)\ntrue\n\njulia> ℓp(x,y,3) == (abs(1-4)^3 + abs(2-5)^3 + abs(3-6)^3)^(1/3)\ntrue\n```\n\nSee also: [`ℓp_norm`](@ref), [`L1Hash`](@ref), [`L2Hash`](@ref)\n\"\"\"\nℓp(x::AbstractVector, y::AbstractVector, p::Real=2) = Lp(x, y, p)\n\n@doc (@doc ℓp)\nℓ1(x::AbstractVector, y::AbstractVector) = L1(x, y)\n\n@doc (@doc ℓp)\nℓ2(x::AbstractVector, y::AbstractVector) = L2(x, y)\n\n@doc raw\"\"\"\n    Lp(x::AbstractVector, y::AbstractVector, p::Real=2)\n    L1(x::AbstractVector, y::AbstractVector)\n    L2(x::AbstractVector, y::AbstractVector)\n\nComputes the ``ℓ^p`` distance between a pair of vectors ``x`` and ``y``. Identical to `ℓp(x,y,p)`, `ℓ1(x,y)`, and `ℓ2(x,y)`, respectively.\n\nSee also: [`ℓp`](@ref)\n\"\"\"\nfunction Lp(x::AbstractVector{T}, y::AbstractVector, p::Real=2) where T\n    if p ≤ 0\n        \"p must be positive\" |> ErrorException |> throw\n    elseif length(x) != length(y)\n        \"length(x) != length(y)\" |> DimensionMismatch |> throw\n    end\n\n    result = T(0)\n    @inbounds @simd for ii = 1:length(x)\n        result += abs(x[ii] - y[ii])^p\n    end\n\n    return result^(1/p)\nend\n\n@doc (@doc Lp)\nfunction L1(x::AbstractVector{T}, y::AbstractVector) where T\n    if length(x) != length(y)\n        \"length(x) != length(y)\" |> DimensionMismatch |> throw\n    end\n\n    result = T(0)\n    @inbounds @simd for ii = 1:length(x)\n        result += abs(x[ii] - y[ii])\n    end\n\n    return result\nend\n\n@doc (@doc Lp)\nfunction L2(x::AbstractVector{T}, y::AbstractVector) where T\n    if length(x) != length(y)\n        \"length(x) != length(y)\" |> DimensionMismatch |> throw\n    end\n\n    result = T(0)\n    @inbounds @simd for ii = 1:length(x)\n        result += abs2(x[ii] - y[ii])\n    end\n\n    return √result\nend\n\n# Function space L^p distances\n\n@doc raw\"\"\"\n    Lp(f, g, interval::LSHFunctions.RealInterval, p)\n    L1(f, g, interval::LSHFunctions.RealInterval)\n    L2(f, g, interval::LSHFunctions.RealInterval)\n\nComputes the ``L^p`` distance between two functions, given by\n\n``L^p(f,g) \\coloneqq \\|f - g\\|_p = \\left(\\int_a^b \\left|f(x) - g(x)\\right|^p \\hspace{0.15cm} dx\\right)^{1/p}``\n\n# Examples\nBelow we compute the ``L^1``, ``L^2``, and ``L^3`` distances between ``f(x) = x^2 + 1`` and ``g(x) = 2x`` over the interval ``[0,1]``. The distances are computed by evaluating the integral\n\n``\\left(\\int_0^1 \\left|f(x) - g(x)\\right|^p \\hspace{0.15cm}dx\\right)^{1/p} = \\left(\\int_0^1 \\left|x^2 - 2x + 1\\right|^p \\hspace{0.15cm}dx\\right)^{1/p} = \\left(\\int_0^1 (x - 1)^{2p} \\hspace{0.15cm}dx\\right)^{1/p}``\n\nfor ``p = 1``, ``p = 2``, and ``p = 3``.\n\n```jldoctest; setup = :(using LSHFunctions)\njulia> f(x) = x^2 + 1; g(x) = 2x;\n\njulia> interval = @interval(0 ≤ x ≤ 1);\n\njulia> Lp(f, g, interval, 1) ≈ L1(f, g, interval) ≈ 3^(-1)\ntrue\n\njulia> Lp(f, g, interval, 2) ≈ L2(f, g, interval) ≈ 5^(-1/2)\ntrue\n\njulia> Lp(f, g, interval, 3) ≈ 7^(-1/3)\ntrue\n```\n\nSee also: [`Lp_norm`](@ref), [`ℓp`](@ref)\n\"\"\"\nLp(f, g, interval::LSHFunctions.RealInterval, p::Real=2) =\n    Lp_norm(x -> f(x) - g(x), interval, p)\n\n@doc (@doc Lp)\nL1(f, g, interval::LSHFunctions.RealInterval) = L1_norm(x -> f(x) - g(x), interval)\n\n@doc (@doc Lp)\nL2(f, g, interval::LSHFunctions.RealInterval) = L2_norm(x -> f(x) - g(x), interval)\n\n#====================\nJaccard similarity\n====================#\n\n@doc raw\"\"\"\n    jaccard(A::Set, B::Set) :: Float64\n\nComputes the Jaccard similarity between sets ``A`` and ``B``, which is defined as\n\n``\\text{Jaccard}(A,B) = \\frac{\\left|A \\cap B\\right|}{\\left|A \\cup B\\right|}``\n\n# Arguments\n- `A::Set`, `B::Set`: two sets whose Jaccard similarity we would like to compute.\n\n# Examples\n```jldoctest; setup = :(using LSHFunctions)\njulia> A, B = Set([1, 2, 3]), Set([2, 3, 4]);\n\njulia> jaccard(A,B)\n0.5\n\njulia> jaccard(A,B) == length(A ∩ B) / length(A ∪ B)\ntrue\n```\n\nSee also: [`MinHash`](@ref)\n\"\"\"\nfunction jaccard(A::Set, B::Set) :: Float64\n    if isempty(A)\n        # Use the convention that if A = B = ∅, their Jaccard\n        # similarity is zero.\n        Float64(0)\n    else\n        length(A ∩ B) / length(A ∪ B)\n    end\nend\n\n@doc raw\"\"\"\n    function jaccard(x::BitArray{1}, y::BitArray{1})\n\nComputes the Jaccard similarity between a pair of binary vectors:\n\n``J(x, y) = \\frac{\\sum_{i} \\min{(x_i,y_i)}}{\\sum_{i} \\max{(x_i,y_i)}}``\n\n# Arguments\n- `x::BitArray{1}`, `y::BitArray{1}`: two binary vectors, in the form of `BitArray`s.\n\n# Examples\n```jldoctest; setup = :(using LSHFunctions)\njulia> x = BitArray([true, false, true, true, false]);\n\njulia> y = BitArray([false, false, true, true, true]);\n\njulia> jaccard(x,y)\n0.5\n```\n\"\"\"\nfunction jaccard(x::BitArray{1}, y::BitArray{1}) :: Float64\n    union = sum(x .| y)\n    if union == 0\n        # Use the convention that if x and y are full of zeros, their Jaccard\n        # similarity is zero.\n        Float64(0)\n    else\n        intersection = sum(x .& y)\n        intersection / union\n    end\nend\n\n@doc raw\"\"\"\n    function jaccard(x::AbstractVector{<:Real}, y::AbstractVector{<:Real})\n\nComputes the Jaccard similarity between a pair of vectors of real numbers:\n\n``J(x, y) = \\frac{\\sum_{i} \\min{(x_i,y_i)}}{\\sum_{i} \\max{(x_i,y_i)}}``\n\n# Arguments\n- `x::AbstractVector{<:Real}`, `y::AbstractVector{<:Real}`: a pair of vectors containing real numbers (subtypes of `Real`).\n\n# Examples\n```jldoctest; setup = :(using LSHFunctions)\njulia> x = [0.8, 0.1, 0.3, 0.4, 0.1];\n\njulia> y = [1.0, 0.6, 0.0, 0.4, 0.5];\n\njulia> jaccard(x,y)\n0.5\n```\n\"\"\"\nfunction jaccard(x::AbstractVector{T},\n                 y::AbstractVector) :: Float64 where {T <: Real}\n    if length(x) != length(y)\n        DimensionMismatch(\"dimensions must match\") |> throw\n    end\n\n    intersection = T(0)\n    union = T(0)\n\n    @inbounds @simd for ii = 1:length(x)\n        if 0 ≤ x[ii] ≤ y[ii]\n            intersection += x[ii]\n            union += y[ii]\n        elseif 0 ≤ y[ii] < x[ii]\n            intersection += y[ii]\n            union += x[ii]\n        else\n            ErrorException(\"vectors must have non-negative elements\") |> throw\n        end\n    end\n\n    if union == T(0)\n        # Use the convention that if x and y are full of zeros, their Jaccard\n        # similarity is zero.\n        Float64(0)\n    else\n        Float64(intersection / union)\n    end\nend\n\njaccard(x::AbstractVector{<:Integer}, y::AbstractVector{<:AbstractFloat}) =\n    jaccard(y, x)\n\n@doc raw\"\"\"\n    function jaccard(A::Set{<:K},\n                     B::Set{<:K},\n                     weights::Dict{K,V}) where {K,V<:Number}\n\nComputes the weighted Jaccard similarity between two sets:\n\n``J(x, y) = \\frac{\\sum_{x\\in A\\cap B} w_x}{\\sum_{y\\in A\\cup B} w_y}``\n\n# Arguments\n- `A::Set`, `B::Set`: two sets whose Jaccard similarity we would like to compute.\n- `weights::Dict`: a dictionary mapping symbols in the sets `A` and `B` to numerical weights. These weights must be positive.\n\n# Examples\n```jldoctest; setup = :(using LSHFunctions)\njulia> A = Set([\"a\", \"b\", \"c\"]);\n\njulia> B = Set([\"b\", \"c\", \"d\"]);\n\njulia> W = Dict(\"a\" => 0.2, \"b\" => 2.4, \"c\" => 0.6, \"d\" => 1.8);\n\njulia> jaccard(A,B,W)\n0.6\n```\n\"\"\"\nfunction jaccard(A::Set{<:K},\n                 B::Set{<:K}, \n                 weights::Dict{K,V}) :: Float64 where {K,V<:Real}\n\n    union_weight = V(0)\n\n    for el in A ∪ B\n        w = weights[el]\n        if w < 0\n            ErrorException(\"weights must be non-negative\") |> throw\n        end\n        union_weight += w\n    end\n\n    intersection_weight = sum(weights[el] for el in A ∩ B)\n\n    # By convention, if A = B = ∅, their Jaccard similarity is zero\n    if union_weight == V(0)\n        Float64(0)\n    else\n        Float64(intersection_weight / union_weight)\n    end\nend\n\n#====================\nInner product and norms\n====================#\n\n### Inner products\n\n@doc raw\"\"\"\n    inner_prod(x::AbstractVector, y::AbstractVector)\n\nComputes the ``\\ell^2`` inner product (dot product)\n\n``\\left\\langle x, y\\right\\rangle = \\sum_i x_iy_i``\n\n# Examples\n```jldoctest; setup = :(using LSHFunctions)\njulia> using LinearAlgebra: dot;\n\njulia> x, y = randn(4), randn(4);\n\njulia> inner_prod(x,y) ≈ dot(x,y)\ntrue\n```\n\"\"\"\ninner_prod(x::AbstractVector, y::AbstractVector) = dot(x,y)\n\n# 1-dimensional inner product between L^2 functions\n@doc raw\"\"\"\n    inner_prod(f, g, interval::LSHFunctions.RealInterval)\n\nComputes the ``L^2`` inner product\n\n``\\left\\langle f, g\\right\\rangle = \\int_a^b f(x)g(x) \\hspace{0.15cm} dx``\n\nwhere the interval we're integrating over is specified by the `interval` argument.\n\n# Examples\n```jldoctest; setup = :(using LSHFunctions)\njulia> f(x) = cos(x); g(x) = sin(x);\n\njulia> inner_prod(f, g, @interval(0 ≤ x ≤ π/2)) ≈ 1/2\ntrue\n```\n\"\"\"\ninner_prod(f, g, interval::LSHFunctions.RealInterval) =\n    quadgk(x -> f(x)g(x), interval.lower, interval.upper)[1]\n\n### L^p norms\n@doc raw\"\"\"\n    Lp_norm(x::AbstractVector, p::Real = 2)\n    L1_norm(x::AbstractVector)\n    L2_norm(x::AbstractVector)\n\nCompute the ``\\ell^p`` norm of a vector ``x``. Identical to `ℓp_norm(x,p)`, `ℓ1_norm(x)`, and `ℓ2_norm(x)`, respectively.\n\nSee also: [`ℓp_norm`](@ref)\n\"\"\"\nLp_norm(x::AbstractVector, p::Real = 2) = norm(x,p)\n\n@doc (@doc Lp_norm)\nL1_norm(x::AbstractVector) = norm(x,1)\n\n@doc (@doc Lp_norm)\nL2_norm(x::AbstractVector) = norm(x)\n\n@doc raw\"\"\"\n    ℓp_norm(x::AbstractVector, p::Real = 2)\n    ℓ1_norm(x::AbstractVector)\n    ℓ2_norm(x::AbstractVector)\n\nCompute the ``\\ell^p`` norm of a point ``x``, defined as\n\n``\\|x\\|_p = \\left(\\sum_i \\left|x_i\\right|^p\\right)^{1/p}``\n\n# Examples\n\n```jldoctest; setup = :(using LSHFunctions)\njulia> x = randn(4);\n\njulia> ℓp_norm(x, 1) ≈ ℓ1_norm(x) ≈ (map(u -> abs(u)^1, x) |> sum)^(1/1)\ntrue\n\njulia> ℓp_norm(x, 2) ≈ ℓ2_norm(x) ≈ (map(u -> abs(u)^2, x) |> sum)^(1/2)\ntrue\n\njulia> ℓp_norm(x, 3) ≈ (map(u -> abs(u)^3, x) |> sum)^(1/3)\ntrue\n```\n\nSee also: [`ℓp`](@ref), [`Lp_norm`](@ref)\n\"\"\"\nℓp_norm(x::AbstractVector, p::Real = 2) = Lp_norm(x, p)\n\n@doc (@doc ℓp_norm)\nℓ1_norm(x::AbstractVector) = L1_norm(x)\n\n@doc (@doc ℓp_norm)\nℓ2_norm(x::AbstractVector) = L2_norm(x)\n\n# 1-dimensional L^p norms\n\n@doc raw\"\"\"\n    Lp_norm(f, interval::LSHFunctions.RealInterval, p::Real=2)\n    L1_norm(f, interval::LSHFunctions.RealInterval)\n    L2_norm(f, interval::LSHFunctions.RealInterval)\n\nComputes the ``L^p`` function-space norm of a function ``f``, which is given by the equation\n\n``\\|f\\|_p = \\left(\\int_a^b \\left|f(x)\\right|^p \\hspace{0.15cm} dx\\right)^{1/p}``\n        \n`L1_norm(f, interval)` is the same as `Lp_norm(f, interval, 1)`, and `L2_norm(f, interval)` is the same as `Lp_norm(f, interval, 2)`.\n\n# Examples\n\n```jldoctest; setup = :(using LSHFunctions)\njulia> f(x) = x;\n\njulia> interval = @interval(0 ≤ x ≤ 1);\n\njulia> Lp_norm(f, interval, 1) ≈ L1_norm(f, interval) ≈ 2^(-1/1)\ntrue\n\njulia> Lp_norm(f, interval, 2) ≈ L2_norm(f, interval) ≈ 3^(-1/2)\ntrue\n\njulia> Lp_norm(f, interval, 3) ≈ 4^(-1/3)\ntrue\n```\n\"\"\"\nLp_norm(f, interval::LSHFunctions.RealInterval, p::Real=2) = (quadgk(x -> abs(f(x)).^p, interval.lower, interval.upper)[1])^(1/p)\n\n@doc (@doc Lp_norm)\nL1_norm(f, interval::LSHFunctions.RealInterval) = quadgk(x -> abs(f(x)), interval.lower, interval.upper)[1]\n\n@doc (@doc Lp_norm)\nL2_norm(f, interval::LSHFunctions.RealInterval) = √quadgk(x -> abs2(f(x)), interval.lower, interval.upper)[1]\n", "meta": {"hexsha": "48bcb830e5dd8797a41376559b062446baf92cd6", "size": 13604, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/similarities.jl", "max_stars_repo_name": "wshand/LSH.jl", "max_stars_repo_head_hexsha": "a76d5e03a8bde1c6b7b33ed3e32b41036f9660e1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-01-21T00:47:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T03:52:35.000Z", "max_issues_repo_path": "src/similarities.jl", "max_issues_repo_name": "wshand/LSH.jl", "max_issues_repo_head_hexsha": "a76d5e03a8bde1c6b7b33ed3e32b41036f9660e1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2020-01-21T18:30:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-31T15:37:29.000Z", "max_forks_repo_path": "src/similarities.jl", "max_forks_repo_name": "kernelmethod/LSH.jl", "max_forks_repo_head_hexsha": "a76d5e03a8bde1c6b7b33ed3e32b41036f9660e1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:42:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:42:17.000Z", "avg_line_length": 26.7269155206, "max_line_length": 400, "alphanum_fraction": 0.5979858865, "num_tokens": 4719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7598867506379015}}
{"text": "\n@doc raw\"\"\"\n    gaussian([T=Float64], point; x, y, fwhm, amp=1, theta=0, bkg=0)\n    gaussian([T=Float64], px, py; x, y, fwhm, amp=1, theta=0, bkg=0)\n\nAn unnormalized bivariate Gaussian distribution. The position can be specified in `(x, y)` coordinates as a `Tuple`, `AbstractVector`, or as separate arguments. If `theta` is given, the PSF will be rotated by `theta` degrees counter-clockwise from the x-axis. If `bkg` is given it will be added as a scalar to the PSF.\n\nThe `fwhm` can be a scalar (isotropic) or a vector/tuple (diagonal). Keep in mind that `theta` has no effect for isotropic distributions and is degenerate with the `fwhm` parameters (i.e., theta=90 is the same as reversing the `fwhm` tuple)\n\n# Functional form\n```\nf(x | x̂, FWHM) = exp[-4ln(2) * ||x - x̂|| / FWHM^2]\n```\nwhere `x̂` and `x` are position vectors (indices) `||⋅||` represents the square-distance, and `FWHM` is the full width at half-maximum. If `FWHM` is a scalar, the Gaussian distribution will be isotropic. If `FWHM` is a vector or tuple, the weighting is applied along each axis (diagonal).\n\"\"\"\ngaussian(T, px, py; x, y, fwhm, amp=one(T), theta=0, bkg=0) = convert(T, _gaussian(px, py, x, y, fwhm, amp, theta, bkg))\n\n\n\"\"\"\n    normal\n\nAn alias for [`gaussian`](@ref)\n\"\"\"\nconst normal = gaussian\n\n# this is the factor to convert 1/(2σ²) to 1/(2fwhm²)\nconst GAUSS_PRE = -4 * log(2)\n\n# isotropic\nfunction _gaussian(px, py, x, y, fwhm, amp, theta, background)\n    # find offset from center\n    dx = px - x\n    dy = py - y\n    # rotate\n    !iszero(theta) && @warn \"isotropic gaussian is not affected by non-zero rotation angle $theta\"\n    # unnormalized gaussian likelihood\n    sqmahab = dx^2 + dy^2\n    sqmahab /= fwhm^2\n    return amp * exp(GAUSS_PRE * sqmahab) + background\nend\n\n# bivariate\nfunction _gaussian(px, py, x, y, fwhm::BivariateLike, amp, theta, background)\n    # find offset from center\n    dx = px - x\n    dy = py - y\n    # rotate\n    if !iszero(theta)\n        dx, dy = rotate_point(dx, dy, theta)\n    end\n    # unnormalized gaussian likelihood\n    fwhmx, fwhmy = fwhm\n    sqmahab = (dx / fwhmx)^2 + (dy / fwhmy)^2\n    return amp * exp(GAUSS_PRE * sqmahab) + background\nend\n", "meta": {"hexsha": "fb04d6f43e4e32254fc5e77c5e55ffcf9877ea93", "size": 2174, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gaussian.jl", "max_stars_repo_name": "JuliaAstro/PSFKernels.jl", "max_stars_repo_head_hexsha": "8518cd63512133d9636c42ebb3210628ea9e480d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-29T20:59:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-29T21:15:24.000Z", "max_issues_repo_path": "src/gaussian.jl", "max_issues_repo_name": "JuliaAstro/PSFKernels.jl", "max_issues_repo_head_hexsha": "8518cd63512133d9636c42ebb3210628ea9e480d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gaussian.jl", "max_forks_repo_name": "JuliaAstro/PSFKernels.jl", "max_forks_repo_head_hexsha": "8518cd63512133d9636c42ebb3210628ea9e480d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8214285714, "max_line_length": 318, "alphanum_fraction": 0.6651333947, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7598867467013832}}
{"text": "module YaWorkingData\n\nusing LinearAlgebra\n\nexport de_μ, directional_σ, ∇directional_σ,\n  first_principal_component, pca, transform\n\nconst DT{T} = Vector{T} where {T <: Real}\nconst VDT{T} = Vector{DT{T}} where {T <: Real}\n\n\"\"\"\nRe-center to have mean 0. across all dim\n\n```julia-repl\njulia> de_μ([[1., 3., 2., 4.], [1., 3., 2., 4.]])\n2-element Vector{Vector{Float64}}:\n [-1.5, 0.5, -0.5, 1.5]\n [-1.5, 0.5, -0.5, 1.5]\n```\n\"\"\"\nfunction de_μ(data::VDT)::VDT\n  \"\"\"\n  Re-center to have mean 0. across all dim\n  \"\"\"\n  μ₀ = μ.(data)\n  map(((d, μ)=t) -> d .- μ, zip(data, μ₀))\nend\n\n\n\"\"\"\nReturns the variance of data in the direction of v\n\"\"\"\nfunction directional_σ(data::VDT, v::DT)::Float64\n  dir_v = direction(v)\n  sum(dot(u, dir_v) .^ 2 for u ∈ data)\nend\n\n\nfunction ∇directional_σ(data::VDT, v::DT)::DT\n  \"\"\"\n  The gradient of directional variance with respect to v\n  \"\"\"\n  v_dir = direction(v)\n  sum(map(v -> 2 * dot(v, v_dir), data) .* data)\nend\n\n\nfunction first_principal_component(data::VDT, n::Integer=100, η=0.1)::DT\n  # Start with a random guess\n  guess = ones(eltype(data[1]), length(data[1]))\n  for _ ∈ 1:n\n    dσ = directional_σ(data, guess)\n    ∇ = ∇directional_σ(data, guess)\n    guess .+= ∇ * η\n  end\n  direction(guess)\nend\n\n\nfunction pca(data::VDT, ncomp::Integer)::VDT\n  comps = VDT{eltype(data[1])}()\n  for _ ∈ 1:ncomp\n    comp = first_principal_component(data)\n    push!(comps, comp)\n    data = rm_project(data, comp)\n  end\n  comps\nend\n\n\nfunction transform(data::VDT, comps::VDT)::VDT\n  transform_vect.(data, Ref(comps))\nend\n\n\n## Internals\n\"\"\"\n```julia-repl\njulia> μ([1., 3., 2., 4.])\n2.5\n```\n\"\"\"\nfunction μ(data::DT)::Float64\n  sum(data) / length(data)\nend\n\n\nfunction direction(v::DT)::DT\n  v ./ norm(v)\nend\n\n\nfunction project(u::DT, v::DT)::DT\n  \"\"\"return the projection of u onto the direction v\"\"\"\n  proj_len = dot(u, v)\n  proj_len * v\nend\n\n\nfunction rm_project_from_vect(u::DT, v::DT)::DT\n  \"\"\"projects u onto v and subtracts the result from u\"\"\"\n  u - project(u, v)\nend\n\n\nfunction rm_project(data::VDT, v::DT)::VDT\n  rm_project_from_vect.(data, Ref(v))\nend\n\n\nfunction transform_vect(v::DT, comps::VDT)::DT\n  dot.(Ref(v), comps)\nend\n\nend  # module\n", "meta": {"hexsha": "3c7a76a85c1cdb291ebe01f0412b7f003476431d", "size": 2163, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Data Science From Scratch/src/YaWorkingData.jl", "max_stars_repo_name": "pascal-p/julia-notebooks", "max_stars_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-01T20:34:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-01T20:34:56.000Z", "max_issues_repo_path": "Data Science From Scratch/src/YaWorkingData.jl", "max_issues_repo_name": "pascal-p/julia-notebooks", "max_issues_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Science From Scratch/src/YaWorkingData.jl", "max_forks_repo_name": "pascal-p/julia-notebooks", "max_forks_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-10T09:03:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T09:03:18.000Z", "avg_line_length": 18.6465517241, "max_line_length": 72, "alphanum_fraction": 0.6352288488, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7598867460389025}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Statistics, DataFrames, CSV\n\tusing Random, Distributions, Plots\n\tusing HypothesisTests\n\tRandom.seed!(0)\nend;\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.06\"\n\n# ╔═╡ 1aa41898-3afa-11eb-2f49-570853ce6435\nbegin\n\tmu1, sig1, n1 = 0, 2, 8\n\tmu2, sig2, n2 = 0, 30, 15\n\tdist1 = Normal(mu1, sig1)\n\tdist2 = Normal(mu2, sig2)\n\n\tN = 10^4\n\ttdArray = Array{Tuple{Float64,Float64}}(undef,N)\n\n\tdf(s1,s2,n1,n2) =\n\t\t(s1^2/n1 + s2^2/n2)^2 / ( (s1^2/n1)^2/(n1-1) + (s2^2/n2)^2/(n2-1) )\nend;\n\n# ╔═╡ fd06acdc-3b1d-11eb-1d5f-03f5cf0f595a\nbegin\n\tfor i in 1:N\n\t\tx1Data = rand(dist1, n1)\n\t\tx2Data = rand(dist2, n2)\n\t\tx1Bar,x2Bar = mean(x1Data),mean(x2Data)\n\t\ts1,s2 = std(x1Data),std(x2Data)\n\t\ttStat = (x1Bar - x2Bar) / sqrt(s1^2/n1 + s2^2/n2)\n\t\ttdArray[i] = (tStat , df(s1,s2,n1,n2))\n\tend\n\tsort!(tdArray, by = first)\n\n\tinvVal(v,i) = quantile(TDist(v),i/(N+1))\n\n\txCoords  = Array{Float64}(undef,N)\n\tyCoords1 = Array{Float64}(undef,N)\n\tyCoords2 = Array{Float64}(undef,N)\n\n\tfor i in 1:N\n\t\txCoords[i] = first(tdArray[i])\n\t\tyCoords1[i] = invVal(last(tdArray[i]), i)\n\t\tyCoords2[i] = invVal(n1+n2-2, i)\n\tend\nend;\n\n# ╔═╡ fd06e9ae-3b1d-11eb-1646-d9c440ed4b98\nbegin\n\tscatter(xCoords, yCoords1, c=:blue, label=\"Calculated v\", msw=0)\n\tscatter!(xCoords, yCoords2, c=:red, label=\"Fixed v\", msw=0)\n\tplot!([-10,10], [-10,10],\n\t\t c=:black, lw=0.3, xlims=(-8,8), ylims=(-8,8), ratio=:equal, label=\"\", \n\t\t xlabel=\"Theoretical t-distribution quantiles\", \n\t\t ylabel=\"Simulated t-distribution quantiles\", legend=:topleft)\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.06\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═1aa41898-3afa-11eb-2f49-570853ce6435\n# ╠═fd06acdc-3b1d-11eb-1d5f-03f5cf0f595a\n# ╠═fd06e9ae-3b1d-11eb-1646-d9c440ed4b98\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "6bd4f1ddca4a7f5af5c97df9ea1da4af546f3779", "size": 2118, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/06/listing6.06.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/06/listing6.06.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/06/listing6.06.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.8292682927, "max_line_length": 73, "alphanum_fraction": 0.6817752597, "num_tokens": 1032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.759819357434098}}
{"text": "\"\"\"\n    Univariate optimization and root finding examples with a few different packages\n\"\"\"\n\nusing Plots \n#=\n You should load all packages at beginning of file!\n I just load the optimizers later to make it clear which package is being demonstrated.\n=#\n\n# Function definition\n# f(x) = x[1]^2 - 0.5\nf(x) = x[1]^3 - x[1]\nxlim_low = -1.5\nxlim_high = 1.5\nplot1 = plot(f, xlim_low, xlim_high, label = \"f(x)\")\nplot1 = plot!(x -> 0, xlim_low, xlim_high, label = \"\")\nplot(plot1)\n\n# Optimization\ninitial_value = -0.01\nscatter!([initial_value],\n         [0.],\n         label = \"Initial Value\",\n         markershape = :x)\n\n\n## Optim\nusing Optim\n\noptim_result = Optim.optimize(f, [initial_value], BFGS())\nprint(\"Optim minimum: \")\nif optim_result.ls_success\n    println(optim_result.minimizer)\n    scatter!([optim_result.minimizer], [optim_result.minimum], label = \"Optim minimum\")\nelse\n    println(\"Failed to converge\")\nend\n\n# Root finding\n\n## Roots\nusing Roots\nroots_zero = find_zero(f, initial_value)\nprintln(\"Roots 'find_zero' zero: $(roots_zero)\")\nscatter!([roots_zero],[f(roots_zero)], label = \"Roots 'find_zero' zero\")\n\n## Alternative syntax\nroots_fzero_zero = fzero(f, initial_value)\nprintln(\"Roots 'fzero' zero: $(roots_fzero_zero)\")\nscatter!([roots_fzero_zero],[f(roots_zero)], label = \"Roots 'fzero' zero\")\n\n\n## Alternative syntax\nfx = ZeroProblem(f, initial_value)\nroots_solve_zero = solve(fx)\nprintln(\"Roots 'solve' zero: $(roots_solve_zero)\")\nscatter!([roots_solve_zero],[f(roots_zero)], label = \"Roots 'solve' zero\")\n\n\n## NLsolve\nusing NLsolve\nf!(F, x) = F[1] = f(x)\nnls_zero = nlsolve(f!, [initial_value])\nprintln(\"NLsolve zero: $(nls_zero.zero)\")\nscatter!([nls_zero.zero], [f(nls_zero.zero)], label = \"NLsolve zero\")\n\n## LeastSquaresOptim\n### Nonlinear least squares\n### minₓ F(x)ᵀF(x)\nusing LeastSquaresOptim\n\nls_optim_result = LeastSquaresOptim.optimize(f, [initial_value], Dogleg())\nprint(\"LeastSquaresOptim minimum: \")\nif ls_optim_result.converged\n    println(ls_optim_result.minimizer)\n    scatter!([ls_optim_result.minimizer], [f(ls_optim_result.minimizer)], label = \"LeastSquaresOptim minimum\")\nelse\n    println(\"Failed to converge\")\nend\n", "meta": {"hexsha": "c2f62999b2895c48d66f9da890667711198aabdb", "size": 2148, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Optimization_demo.jl", "max_stars_repo_name": "PhilipCaoChicago/ECON602_2021", "max_stars_repo_head_hexsha": "ef62b3763663c076ab5ea40009a57232ba338885", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-17T23:05:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T04:17:50.000Z", "max_issues_repo_path": "src/Optimization_demo.jl", "max_issues_repo_name": "PhilipCaoChicago/ECON602_2021", "max_issues_repo_head_hexsha": "ef62b3763663c076ab5ea40009a57232ba338885", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Optimization_demo.jl", "max_forks_repo_name": "PhilipCaoChicago/ECON602_2021", "max_forks_repo_head_hexsha": "ef62b3763663c076ab5ea40009a57232ba338885", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-09-21T19:07:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T22:37:40.000Z", "avg_line_length": 26.5185185185, "max_line_length": 110, "alphanum_fraction": 0.7104283054, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7598193571386509}}
{"text": "# # Custom halftoning with SDFs\n# Ordered dithering & halftoning algorithms typically use predefined threshold matrices\n# with unique values ranging from `1//n` to `(n-1)/n`, where `n` is the number of elements\n# in the matrix.\n#\n# In this example, we will be generating these threshold matrices\n# from signed distance functions (SDFs). A good resource for those is Inigo Quilez'\n# blogpost [\"2D distance functions\"](https://www.iquilezles.org/www/articles/distfunctions2d/distfunctions2d.htm).\n#\n# Here we reimplement his function `sdStar5`:\nusing Images\nusing DitherPunk\nusing ColorSchemes\nusing TestImages\n\nfunction star_sdf(x, y; r=0.5, rf=2.0)\n    k1 = [0.809016994375, -0.587785252292]\n    k2 = [-k1[1], k1[2]]\n    p = [abs(x), y]\n    p -= 2.0 * maximum([k1 ⋅ p, 0.0]) * k1\n    p -= 2.0 * maximum([k2 ⋅ p, 0.0]) * k2\n    p = [abs(p[1]), p[2] - r]\n    ba = rf * [-k1[2], k1[1]] - [0, 1]\n    h = clamp((p ⋅ ba) / (ba ⋅ ba), 0.0, r)\n    return norm(p - ba * h) * sign(p[2] * ba[1] - p[1] * ba[2])\nend;\n\n# This SDF can be visualized by its contour:\n#\n# ![](https://user-images.githubusercontent.com/20258504/144755939-19b13e29-e50b-4744-bdeb-234f33790ca8.png)\n#\n# To convert an SDF to an `OrderedDither` algorithm, use this function:\nfunction sdf2halftone(sdf, n)\n    rg = range(-1, 1; length=n)\n    A = [sdf(x, y) for y in rg, x in rg]\n    p = sortperm(reshape(-A, :))\n    B = Vector{Int}(undef, n^2)\n    B[p] .= 1:(n^2)\n    return OrderedDither(reshape(B, size(A)...)//(n^2 + 1))\nend;\n\n# Let's try it on a test image:\nimg = testimage(\"fabio_gray_512\")\nalg = sdf2halftone(star_sdf, 7)\ndither(img, alg)\n\n# We can also change the size of the matrix.\n# Large halftoning matrices look great on high resolution images.\nalg = sdf2halftone(star_sdf, 15)\ndither(img, alg)\n", "meta": {"hexsha": "9764916057f82e6ab62ceb429ae1799006edf405", "size": 1767, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/literate/sdf_halftoning.jl", "max_stars_repo_name": "JuliaImages/DitherPunk.jl", "max_stars_repo_head_hexsha": "2915ec4994a2da386f3d68902480eca6f96e2f51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2021-09-05T22:57:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T13:35:40.000Z", "max_issues_repo_path": "docs/literate/sdf_halftoning.jl", "max_issues_repo_name": "JuliaImages/DitherPunk.jl", "max_issues_repo_head_hexsha": "2915ec4994a2da386f3d68902480eca6f96e2f51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2021-05-17T09:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T00:20:04.000Z", "max_forks_repo_path": "docs/literate/sdf_halftoning.jl", "max_forks_repo_name": "adrhill/DitherPunk.jl", "max_forks_repo_head_hexsha": "2915ec4994a2da386f3d68902480eca6f96e2f51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-03T08:07:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-03T08:07:34.000Z", "avg_line_length": 34.6470588235, "max_line_length": 114, "alphanum_fraction": 0.6576117714, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7598193557163364}}
{"text": "@defcomp co2forcing begin\n    c_CO2concentration = Parameter(index=[time], unit=\"ppbv\")\n    f0_CO2baseforcing = Parameter(unit=\"W/m2\", default=1.68)\n    fslope_CO2forcingslope = Parameter(unit=\"W/m2\", default=5.5)\n    c0_baseCO2conc = Parameter(unit=\"ppbv\", default=400859.5833)\n    f_CO2forcing = Variable(index=[time], unit=\"W/m2\")\n\n    function run_timestep(p, v, d, t)\n\n        # eq.13 in Hope 2006\n        # the max() condition was added to prevent numerical issues due to  non-positive CO2 concentration levels which occurs in 2300 for low-emission scenarios\n        # if the growth effects are paired with GDP-emission feedback\n        if p.c_CO2concentration[t] > 0\n            v.f_CO2forcing[t] = max(0, p.f0_CO2baseforcing + p.fslope_CO2forcingslope * log(p.c_CO2concentration[t] / p.c0_baseCO2conc) )\n        else\n            v.f_CO2forcing[t] = 0 \n        end\n    end\nend\n", "meta": {"hexsha": "cb5cbcc8da55aa6fa2617434ba0374c31c969abc", "size": 884, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/components/extensions/CO2forcing_growth.jl", "max_stars_repo_name": "tammyt123/MimiPAGE2020.jl", "max_stars_repo_head_hexsha": "9292ca11543c3bf627d3b39ca3fa7c18996dd231", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-26T14:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T03:57:42.000Z", "max_issues_repo_path": "src/components/extensions/CO2forcing_growth.jl", "max_issues_repo_name": "tammyt123/MimiPAGE2020.jl", "max_issues_repo_head_hexsha": "9292ca11543c3bf627d3b39ca3fa7c18996dd231", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2019-01-29T21:11:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-02T09:52:03.000Z", "max_forks_repo_path": "src/components/extensions/CO2forcing_growth.jl", "max_forks_repo_name": "tammyt123/MimiPAGE2020.jl", "max_forks_repo_head_hexsha": "9292ca11543c3bf627d3b39ca3fa7c18996dd231", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-01-26T05:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T15:01:28.000Z", "avg_line_length": 44.2, "max_line_length": 161, "alphanum_fraction": 0.6798642534, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214470715362, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.7598189603794904}}
{"text": "# K=funLtoK(L)\n# The function funLtoK(L) converts a kernel L matrix into a (normalized)\n# kernel K matrix. The K matrix has to be semi-positive definite.\n#\n# Code available here:\n# Keeler, 2018, https://github.com/hpaulkeeler/DetPoisson_Julia\n#\n# #TEST\n# B=[3, 2, 1; 4, 5,6; 9, 8,7];\n# L=B'*B\n# L =\n#\n#   106    98    90\n#    98    93    88\n#    90    88    86\n# K=funLtoK(L)\n# K =\n#\n#     0.7602    0.3348   -0.0906\n#     0.3348    0.3320    0.3293\n#    -0.0906    0.3293    0.7492\n\nfunction funLtoK(L)\n    eigenVectLK=eigvecs(L); #eigen decomposition -- vectors\n    eigenValL=(eigvals(L)); #eigen decomposition -- values\n    eigenValK = eigenValL./(1 .+eigenValL); #eigenvalues of K\n    eigenValK=Diagonal(eigenValK); #eigenvalues of L as diagonal matrix\n    K=eigenVectLK*eigenValK*(eigenVectLK'); #recombine from eigen components\n    K=real(K); #make sure all values are real\n    return K;\nend\n", "meta": {"hexsha": "648581a7af4ebd6a45b2c45f2603b58806e0677e", "size": 898, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "funLtoK.jl", "max_stars_repo_name": "hpaulkeeler/DetPoisson_Julia", "max_stars_repo_head_hexsha": "9d5273e1f5dcf0869b01edd6e0486b900838a971", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "funLtoK.jl", "max_issues_repo_name": "hpaulkeeler/DetPoisson_Julia", "max_issues_repo_head_hexsha": "9d5273e1f5dcf0869b01edd6e0486b900838a971", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "funLtoK.jl", "max_forks_repo_name": "hpaulkeeler/DetPoisson_Julia", "max_forks_repo_head_hexsha": "9d5273e1f5dcf0869b01edd6e0486b900838a971", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0625, "max_line_length": 76, "alphanum_fraction": 0.6391982183, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214511730026, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.7598189468035886}}
{"text": "function solve_lyapunov(A,Q,guess = I;iter_lim=100,epsilon=1e-14)\n    iter = 1\n    err = 1\n    while iter <= iter_lim && err > epsilon\n        new_guess = A*guess*A' + Q\n        err = maximum(abs.(new_guess - guess))\n        guess = new_guess\n        iter += 1\n    end\n    return(guess)\nend\n\nusing LinearAlgebra\n\nfunction solve_lyapunov_vec(A,Q)\n    aux = (I - kron(A,A))\n    vec_ans = \\(aux,vec(Q))\n    res = reshape(vec_ans,size(Q))\n    return res\nend\n\nusing ToeplitzMatrices\n\nfunction build_variance(g,h,Q,T) #only works for a single series\n    sig_x = solve_lyapunov_vec(h,Q)\n    y_autocov(t) = g*h*sig_x*h'^(t)*g'\n    vec_st = map(x->first(y_autocov(x)),1:(T))\n    res = Toeplitz(vec_st,vec_st)\n    return res\nend\n", "meta": {"hexsha": "9a42578d6718d35a203e51fdbfc55561ff04177e", "size": 719, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "misc/matrix_no_kalman.jl", "max_stars_repo_name": "danmrc/DSGE-HMC", "max_stars_repo_head_hexsha": "04601e6d7c5a878ea0812d48e974b3f9c91c90ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "misc/matrix_no_kalman.jl", "max_issues_repo_name": "danmrc/DSGE-HMC", "max_issues_repo_head_hexsha": "04601e6d7c5a878ea0812d48e974b3f9c91c90ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc/matrix_no_kalman.jl", "max_forks_repo_name": "danmrc/DSGE-HMC", "max_forks_repo_head_hexsha": "04601e6d7c5a878ea0812d48e974b3f9c91c90ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-20T09:15:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-20T09:15:46.000Z", "avg_line_length": 23.1935483871, "max_line_length": 65, "alphanum_fraction": 0.6272600834, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172572644806, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7597904517729467}}
{"text": "\nfunction discreteIntegration(values::Array{Float64,1}, coordinates::AbstractArray{Float64,2}, l::Int, m::Int)\n\n  @polyvar x y z\n\n  sum = 0\n  p = ylm(l,m,x,y,z)\n\n  for k in 1:length(values)\n    sum += values[k] * p((x,y,z)=>(coordinates[k,1],coordinates[k,2],coordinates[k,3]))\n  end\n  return sum * ((4*pi)/length(values))\nend\n\n\nfunction sphericalQuadrature(values::Array{Float64,1}, coordinates::AbstractArray{Float64,2}, L)\n\n  C = [discreteIntegration(values,coordinates,l,m) for l=0:L for m=-l:l]\n  return SphericalHarmonicCoefficients(C)\nend\n\n# Error propagation\nfunction errorDiscreteIntegration(values::Array{Float64,1}, coordinates::AbstractArray{Float64,2}, l::Int, m::Int)\n\n  @polyvar x y z\n\n  sum = 0\n  p = ylm(l,m,x,y,z)\n\n  for k in 1:length(values)\n    sum += (values[k] * p((x,y,z)=>(coordinates[k,1],coordinates[k,2],coordinates[k,3])))^2\n  end\n  return sqrt(sum) * ((4*pi)/length(values))\nend\n\n\nfunction errorSphericalQuadrature(values::Array{Float64,1}, coordinates::AbstractArray{Float64,2}, L)\n\n  C = [errorDiscreteIntegration(values,coordinates,l,m) for l=0:L for m=-l:l]\n  return SphericalHarmonicCoefficients(C)\nend\n", "meta": {"hexsha": "55eacf5e612a3f56a0ef69b4c818c150b9b1ea2a", "size": 1137, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sphericalQuadrature.jl", "max_stars_repo_name": "hofmannmartin/SphericalHarmonicExpansions.jl", "max_stars_repo_head_hexsha": "29880d443a44e838a756f30c17f5916f17f7ab79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2020-10-22T16:18:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T22:34:15.000Z", "max_issues_repo_path": "src/sphericalQuadrature.jl", "max_issues_repo_name": "hofmannmartin/SphericalHarmonics.jl", "max_issues_repo_head_hexsha": "40c04bb15e4e4b6dfea748526404edbab7dff3a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-07-24T18:07:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-16T18:56:22.000Z", "max_forks_repo_path": "src/sphericalQuadrature.jl", "max_forks_repo_name": "hofmannmartin/SphericalHarmonics.jl", "max_forks_repo_head_hexsha": "40c04bb15e4e4b6dfea748526404edbab7dff3a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-06-24T23:52:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-08T21:45:35.000Z", "avg_line_length": 27.0714285714, "max_line_length": 114, "alphanum_fraction": 0.7000879507, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632343454896, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.7597646478710401}}
{"text": "# Statistical model for analyzing Radial Velocity observations\r\n# Assumes existance of data in arrays times, obs, sigma_obs\r\n# Assumes existance of function calc_model_rv(theta, time)\r\n\r\nexport ploglikelihood, plogprior, plogtarget\r\nexport set_times, set_obs, set_sigma_obs\r\n\r\n# Observational data to compare model to\r\nglobal times # ::Array{Float64,1}\r\nglobal obs # ::Array{Float64,1}\r\nglobal sigma_obs #::Array{Float64,1}\r\n\r\n# Functions to set global data within module\r\nfunction set_times(t::Array{Float64,1}) global times = t   end\r\nfunction set_obs(o::Array{Float64,1})  global obs = o   end\r\nfunction set_sigma_obs(so::Array{Float64,1}) global sigma_obs = so  end\r\n\r\nfunction ploglikelihood(p::Vector)\r\n  num_pl = num_planets(p)\r\n  @assert num_pl >= 1\r\n  if !is_valid(p) return -Inf end  # prempt model evaluation\r\n  # Set t, o, and so to point to global arrays with observational data, while enforcing types\r\n  t::Array{Float64,1} = times\r\n  o::Array{Float64,1} = obs\r\n  so::Array{Float64,1} = sigma_obs\r\n  @assert length(times) == length(obs) == length(sigma_obs)\r\n  jitter_sq = RvModelKeplerian.num_jitters >=1 ? extract_jitter(p)^2 : 0.\r\n  chisq = zero(eltype(p))\r\n  log_normalization = -0.5*length(t)*log(2pi)\r\n  for i in 1:length(t)\r\n    model::eltype(p) = calc_model_rv(p,t[i])\r\n    sigma_eff_sq = so[i]^2+jitter_sq\r\n    chisq += abs2(model-o[i])/sigma_eff_sq\r\n    log_normalization -= 0.5*log(sigma_eff_sq)\r\n  end\r\n  return -0.5*(chisq)+log_normalization\r\nend\r\n\r\nfunction plogprior(p::Vector) \r\n  num_pl = num_planets(p)\r\n  @assert num_pl >= 1\r\n  if !is_valid(p) return -Inf end  # prempt model evaluation\r\n  logp = zero(eltype(p))\r\n  logp -= 2*log(2pi)\r\n  const max_period = 10000.0\r\n  const max_amplitude = 10000.0\r\n  for plid in 1:num_pl\r\n    P::eltype(p) = extract_period(p,plid=plid)\r\n    K::eltype(p) = extract_amplitude(p,plid=plid)\r\n    logp += -log((1+P/P0::Float64)*log1p(max_period/P0::Float64)* \r\n                 (1+K/K0::Float64)*log1p(max_amplitude/K0::Float64) )\r\n\r\n  end\r\n  if RvModelKeplerian.num_jitters >=1\r\n     const max_jitter = 10000.0\r\n     jitter::eltype(p) = extract_jitter(p)\r\n     logp += -log((1+jitter/Jitter0::Float64)*log1p(max_jitter/Jitter0::Float64))\r\n  end\r\n \r\n  return logp::eltype(p)\r\nend\r\n\r\nplogtarget(p::Vector) = ploglikelihood(p) + plogprior(p)\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "75feda0fcf02b73293348254e59b34608bfe7b08", "size": 2311, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/radial_velocity/src/stat_model.jl", "max_stars_repo_name": "scidom/PGUManifoldMC.jl", "max_stars_repo_head_hexsha": "766cf983b122678d47524c566ebd6fffa7f804d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-08T12:59:00.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-08T12:59:00.000Z", "max_issues_repo_path": "examples/radial_velocity/analysis/src/stat_model.jl", "max_issues_repo_name": "eford/PGUManifoldMC.jl", "max_issues_repo_head_hexsha": "0a75d899f580a79282eb742f17a207b14963ea79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-04-13T03:04:56.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-13T03:05:48.000Z", "max_forks_repo_path": "examples/radial_velocity/analysis/src/stat_model.jl", "max_forks_repo_name": "eford/PGUManifoldMC.jl", "max_forks_repo_head_hexsha": "0a75d899f580a79282eb742f17a207b14963ea79", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-08-21T18:03:01.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-21T18:03:01.000Z", "avg_line_length": 33.9852941176, "max_line_length": 94, "alphanum_fraction": 0.6871484206, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7597646366568348}}
{"text": "using Distributions\n\n# ρ(x) in integrand\nρ(x) = 1/sqrt(π)*exp(-x^2)\n\n#=\nImplementation of random walk sampler Metropolis-Hastings.\nInputs:\n- n: The number of states to return\n- b: The standard deviation of the normal distribution used in the proposal\n     distribution\nOutputs:\n- Returns an array of length n denoting states S_i in Metropolis-Hastings alg.\n=#\nfunction metropolis_hastings(n, b)\n\n    # Samples\n    samples = zeros(n)\n    samples[1] = rand()\n\n    # Conditional Q distribution\n    d = Normal(0,b)\n\n    acceptances = 0\n\n    for i=2:n\n        # Propose Y\n        ξ = rand(d)\n        Y = samples[i-1] + ξ\n\n        # Acceptance probability\n        α = min(1, ρ(Y)/ρ(samples[i-1]))\n\n        # Next state\n        if rand() < α\n            samples[i] = Y\n            acceptances += 1\n        else\n            samples[i] = samples[i-1]\n        end\n    end\n\n    println(acceptances)\n\n    return samples\nend\n\n# Obtain 1000 samples with b = 2\nS = metropolis_hastings(10000,1)\n\n# f(x) in integrand\nf(x) = -1/2 < x < 2 ? abs(cos(x)) : 0\n\n# Estimate integral\nint_estimate = sqrt(π)*mean([f(x) for x in S])\n", "meta": {"hexsha": "9cd80bab7828f32f353a99efa1b14bf1243b14f7", "size": 1106, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/stochastic-approximations/code/metropolis_hastings_integral.jl", "max_stars_repo_name": "seanrattana/courses", "max_stars_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-08-21T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T15:46:58.000Z", "max_issues_repo_path": "content/stochastic-approximations/code/metropolis_hastings_integral.jl", "max_issues_repo_name": "seanrattana/courses", "max_issues_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-08-23T06:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-26T12:47:12.000Z", "max_forks_repo_path": "content/stochastic-approximations/code/metropolis_hastings_integral.jl", "max_forks_repo_name": "seanrattana/courses", "max_forks_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-08-18T21:23:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T19:14:33.000Z", "avg_line_length": 19.75, "max_line_length": 78, "alphanum_fraction": 0.6012658228, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632275178339, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7597646355668859}}
{"text": "\"Provide routines for making fake Gaussian models which have analytic Fourier transforms, for the purposes of testing.\"\nmodule gauss\n\nexport imageGauss, FTGauss\n\nusing LinearAlgebra\nusing ..constants\n\n\n\"\n    imageGauss(ll::AbstractVector{Float64}, mm::AbstractVector{Float64}, p::Vector{Float64}, k::Real; theta=0)\n\nGiven two arrays of ``l`` and ``m`` coordinates, corresponding to ``x`` and ``y``, fill an array of the Gaussian image\nfollowing the MATLAB convention for images (each row corresponds to a different y value).\n\n`p0` is a vector of `[mu_RA, mu_DEC, sigma_x, sigma_y, rho]` in units of arcseconds.\n``\\\\rho`` is the correlation of the Gaussian, ranging from 0 to 1.\n\n```math\n\\\\rho = \\\\frac{\\\\sigma_{xy}}{\\\\sigma_x \\\\sigma_y}\n```\n\n``\\\\mu_\\\\alpha`` and ``\\\\mu_\\\\delta`` are the locations of the centroid emission relative to the\nimage origin (RA=0, DEC=0).\n\n``k`` is a scaling pre-factor to adjust the amplitude of the Gaussian.\n\nThe image intensity as a function of ``l`` and ``m`` (sky plane coordinates) is\n\n```math\n    I(l,m) = \\\\frac{k}{2 \\\\pi \\\\sqrt{|\\\\boldsymbol{\\\\Sigma}|}} \\\\exp \\\\left \\\\{ -\\\\frac{1}{2} \\\\boldsymbol{R}^\\\\mathrm{T} \\\\boldsymbol{\\\\Sigma}^{-1} \\\\boldsymbol{R} \\\\right \\\\}\n```\n\nWhere ``\\\\boldsymbol{\\\\Sigma}`` is\n```math\n\\\\boldsymbol{\\\\Sigma} = \\\\left [ \\\\begin{array}{cc}\n\\\\sigma_x & \\\\sigma_{xy} \\\\\\\\\n\\\\sigma_{xy} & \\\\sigma_y \\\\\\\\\n\\\\end{array} \\\\right ]\n```\n\n``\\\\theta`` is a desired angle to rotate the Gaussian about the origin. To make sense of the order of operations, the rotation must occur about the origin. A positive value means a counter-clockwise rotation of the Gaussian from North towards East.\n\"\nfunction imageGauss(ll::AbstractVector{Float64}, mm::AbstractVector{Float64}, p::Vector{Float64}, k::Real; theta=0)\n\n    # Both ll and mm increase with array index\n    nx = length(ll)\n    ny = length(mm)\n\n    img = Array{Float64}(undef, ny, nx)\n    mu = p[1:2] * arcsec #ll and mm shifts\n    sigma_x = p[3] * arcsec\n    sigma_y = p[4] * arcsec\n    rho = p[5]\n    sigma_xy = rho * sigma_x * sigma_y\n    Sigma = Float64[[sigma_x^2, sigma_xy] [sigma_xy, sigma_y^2]]\n    rot = [[cosd(theta), +sind(theta)] [-sind(theta), cosd(theta)]]\n    # Sigma = Diagonal((p[3:4] * arcsec).^2) #Convert from arcsec to radians\n    pre = 1.0 / (2pi * sqrt(det(Sigma))) * k\n    for j=1:ny\n        for i=1:nx\n            # Rotation of Gaussian occurs about origin, so subtract off mean first.\n            R = rot * (Float64[ll[i] , mm[j]] - mu)\n            img[j, i] = pre * exp(-0.5 * (R' * (Sigma\\R))[1]) # backslash solves for Sigma^{-1}R\n        end\n    end\n    return img\nend\n\n\"\n    FTGauss(uu::Float64, vv::Float64, p::Vector{Float64}, k::Real)\n\nGiven u and v coordinates in [kλ], evaluate the analytic FT of the\naforementioned Gaussian.\n\n`p` is a length 5 vector of `[mu_RA, mu_DEC, sigma_x, sigma_y, rho]` in units of arcseconds, corresponding to the **image** plane.\n\nN.B. Here Sigma refers to the (same) covariance matrix in the *image* domain.\n\nThis function always returns a complex value.\"\nfunction FTGauss(uu::Float64, vv::Float64, p::Vector{Float64}, k::Real; theta=0)\n    uu = uu .* 1e3 #[λ]\n    vv = vv .* 1e3 #[λ]\n\n    rot = Float64[[cosd(theta), -sind(theta)] [sind(theta), cosd(theta)]]\n\n    mu = p[1:2] * arcsec #ll and mm shifts\n    sigma_x = p[3] * arcsec\n    sigma_y = p[4] * arcsec\n    rho = p[5]\n    sigma_xy = rho * sigma_x * sigma_y\n    Sigma = Float64[[sigma_x^2, sigma_xy] [sigma_xy, sigma_y^2]]\n\n    # mu_RA, mu_DEC = p[1:2]\n    # mu = Float64[mu_RA, mu_DEC] * arcsec #ll and mm shifts\n\n    R0 = Float64[uu, vv]\n\n    # Position to evaluate the rotated Gaussian centered at the origin. Evaluating the Gaussian as if we were\n    # in uu', vv'.\n    R = rot * R0\n    model = k * exp(-2 * (pi^2) * (R' * Sigma * R)[1])\n    # in this case, Sigma serves as an inverse matrix, since the covariance matrix corresponds to the *image* plane.\n    # Sigma = Diagonal((p[3:4] * arcsec).^2) #Convert from arcsec to radians\n\n    # Phase shift should be evaluated using the original coordinates and mu, since this is the direction that we are actually moving things. And, the interferometer samples uu,vv, not uu', vv'.\n    phase_shift = exp(-2pi * 1.0im * (R0' * mu)[1]) # Not actually in polar phase form\n\n    return model * phase_shift\nend\n\n\"\n    FTGauss(uu::AbstractVector{Float64}, vv::AbstractVector{Float64}, p::Vector{Float64}, k::Int)\n\n`p` is a length 5 vector of `mu_RA`, `mu_DEC`, `sigma_RA`, `sigma_DEC`, `rho`.\n\nGiven two arrays of u and v coordinates in [kλ], fill an array with the\nanalytic FT of `imageGauss` evaluated at every pairwise (u,v) pair.\"\nfunction FTGauss(uu::AbstractVector{Float64}, vv::AbstractVector{Float64}, p::Vector{Float64}, k::Real; theta=0)\n    nu = length(uu)\n    nv = length(vv)\n    # Both uu and vv increase with array index\n    img = Array{ComplexF64}(undef, nv, nu)\n    for j=1:nv\n        for i=1:nu\n            img[j, i] = FTGauss(uu[i], vv[j], p, k, theta=theta)\n        end\n    end\n    return img\nend\n\nend # module\n", "meta": {"hexsha": "3306aa503be818954c4b4723f257672d4b4c26e6", "size": 4998, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gauss.jl", "max_stars_repo_name": "j6626/DiskJockey", "max_stars_repo_head_hexsha": "7e10f8417fc5769efd9f950a5f1de3949f0df70b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-10-15T16:58:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-26T19:30:34.000Z", "max_issues_repo_path": "src/gauss.jl", "max_issues_repo_name": "j6626/DiskJockey", "max_issues_repo_head_hexsha": "7e10f8417fc5769efd9f950a5f1de3949f0df70b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2016-02-14T00:07:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-25T19:19:05.000Z", "max_forks_repo_path": "src/gauss.jl", "max_forks_repo_name": "j6626/DiskJockey", "max_forks_repo_head_hexsha": "7e10f8417fc5769efd9f950a5f1de3949f0df70b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-02-09T08:20:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T10:33:18.000Z", "avg_line_length": 37.5789473684, "max_line_length": 248, "alphanum_fraction": 0.6510604242, "num_tokens": 1542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122768904644, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.7597259275141502}}
{"text": "type SimpleOG\n    B :: Int64\n    M :: Int64\n    alpha :: Float64\n    beta :: Float64\n    R :: Array{Float64}\n    Q :: Array{Float64}\nend\n\nfunction SimpleOG(;B=10, M=5, alpha=0.5, beta=0.9)\n\n    u(c) = c^alpha\n    n = B + M + 1\n    m = M + 1\n\n    R = Array(Float64,n,m)\n    Q = zeros(Float64,n,m,n)\n\n    for a in 0:M\n        Q[:, a + 1, (a:(a + B)) + 1] = 1 / (B + 1)\n        for s in 0:(B + M)\n            R[s + 1, a + 1] = a<=s ? u(s - a) : -Inf\n        end\n    end\n    \n    return SimpleOG(B, M, alpha, beta, R, Q)\nend\n", "meta": {"hexsha": "f174b3577fd3300b9c9040ba359f4d7bb33815a0", "size": 521, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "discrete_dp/finite_dp_og_example.jl", "max_stars_repo_name": "mwhchen/quantecon", "max_stars_repo_head_hexsha": "1a401e3453cbccbcf609945fced1b478b945446e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-05-02T22:12:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T01:07:33.000Z", "max_issues_repo_path": "discrete_dp/finite_dp_og_example.jl", "max_issues_repo_name": "mwhchen/quantecon", "max_issues_repo_head_hexsha": "1a401e3453cbccbcf609945fced1b478b945446e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "discrete_dp/finite_dp_og_example.jl", "max_forks_repo_name": "mwhchen/quantecon", "max_forks_repo_head_hexsha": "1a401e3453cbccbcf609945fced1b478b945446e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-11-11T22:38:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T20:33:03.000Z", "avg_line_length": 18.6071428571, "max_line_length": 52, "alphanum_fraction": 0.4452975048, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9579122756889437, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7597259218768052}}
{"text": "import Distributions\n\nfunction laplace_mechanism(result::Number; sensitivity::Number, epsilon::Number)\n    @assert sensitivity > 0\n    @assert epsilon > 0\n    lap = Distributions.Laplace(0.0, sensitivity/epsilon) # mean 0, scale=sensitivity/epsilon\n    result + rand(lap)\nend\n\nfunction laplace_mechanism(result::Array; sensitivity::Number, epsilon::Number)\n    [laplace_mechanism(x, sensitivity=sensitivity, epsilon=epsilon) for x in result]\nend\n\nfunction geometric_mechanism(result::Int; sensitivity::Int, epsilon::Number)\n    @assert sensitivity > 0\n    @assert epsilon > 0\n    p = 1-exp(-epsilon/sensitivity)\n    geo = Distributions.Geometric(p)\n    result + rand(geo) - rand(geo)\nend\n\nfunction noisy_max(answers::Vector{S}; sensitivity::Number, epsilon::Number) where S <: Number\n    noisy_answers = [laplace_mechanism(x, sensitivity=2*sensitivity, epsilon=epsilon) for x in answers]\n    return argmax(noisy_answers)\nend\n\nfunction sparse_vector(;T::Number, N::Int, answers::Vector{S}, sensitivity::Number, epsilon::Number) where S <: Number\n    noisy_T = laplace_mechanism(T; sensitivity=sensitivity, epsilon=epsilon/2)\n    answered = 0\n    i=1\n    output = Bool[] # empty array of booleans\n    while(answered < N && i <= length(answers))\n        noisy_query = laplace_mechanism(answers[i]; sensitivity=2*N, epsilon=epsilon/2)\n\t    i = i + 1\n\t    if noisy_query >= noisy_T\n\t       append!(output, true)\n\t       answered = answered + 1\n\t    else\n           append!(output, false)\n\t    end\n    end\n    output\nend\n", "meta": {"hexsha": "960f1d114d864f84fed25cee936dfa8d643b8b05", "size": 1515, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "mechanisms/mech.jl", "max_stars_repo_name": "dkifer/dpcourse", "max_stars_repo_head_hexsha": "ecb2bf8792425202d770a767306e3365339f6164", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-05T02:03:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T02:03:40.000Z", "max_issues_repo_path": "mechanisms/mech.jl", "max_issues_repo_name": "dkifer/dpcourse", "max_issues_repo_head_hexsha": "ecb2bf8792425202d770a767306e3365339f6164", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mechanisms/mech.jl", "max_forks_repo_name": "dkifer/dpcourse", "max_forks_repo_head_hexsha": "ecb2bf8792425202d770a767306e3365339f6164", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4318181818, "max_line_length": 118, "alphanum_fraction": 0.702310231, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122684798183, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.7597259114747932}}
{"text": "## PART 7\n\ninclude(\"autocorrelation.jl\");\n\nprintln(\"\\nPart 7\");\nprintln(\"\\n\\tPick subjets v1 and v2 of each dataset,\");\nprintln(\"\\tsizes N1 = 1,000 & N2 = 10,000.\");\n\nv1 = v[[1:N1],:];\nv2 = v[[1:N2],:];\n\nprintln(\"\\n\\tEstimate autocorrelations\");\nprintln(\"\\n\\t...for N1...\");\nxcorr = [0:10:400];\nycorr1 = zeros( length( xcorr ), 5 );\nfor a in [1:5]\n  # Calculate autocorrelations\n  ycorr1[:,a] = autocorrelation(N1, v1, a, xcorr);\n  # Normalize by dividing through by Ĉ[1,a]\n  ycorr1[:,a] /= ycorr1[1,a];\nend\nprintln(\"\\n\\t...for N2 (See plots below)\");\nycorr2 = zeros( length( xcorr ), 5 );\nfor a in [1:5]\n  # Calculate autocorrelations\n  ycorr2[:,a] = autocorrelation(N2, v2, a, xcorr);\n  # Normalize by dividing through by Ĉ[1,a]\n  ycorr2[:,a] /= ycorr2[1,a];\nend\n\n# Make plots for each alpha\nprintln(\"\\n\\tPlacing estimated autocorrelation plots 'plots1' and 'plots2':\");\nusing Gadfly\nplots1 = Plot[];\nplots2 = Plot[];\nfor i in [1:5]\n  # Plot\n  push!(plots1, Gadfly.plot ( x = xcorr, y = ycorr1[:,i], Geom.line, Geom.point,\n      Guide.xlabel(\"Separation\"), Guide.ylabel(\"Normalized Autocorrelation\"),\n      Guide.title(join([\"Estimated Autocorrelation for Dataset\",string(i),\n                        \"with Sample Size N1 = $N1\"],\" \",\" \"))))\n  push!(plots2, Gadfly.plot ( x = xcorr, y = ycorr2[:,i], Geom.line, Geom.point,\n      Guide.xlabel(\"Separation\"), Guide.ylabel(\"Normalized Autocorrelation\"),\n      Guide.title(join([\"Estimated Autocorrelation for Dataset\",string(i),\n                        \"with Sample Size N2 = $N2\"],\" \",\" \"))))\nend\n\n# Estimate autocorrelation times\nprintln(\"\\n\\tEstimating autocorrelation times τ1 and τ2\");\nτ1 = Float64[];\nτ2 = Float64[];\nfor a in [1:5]\n  corra = autocorrelation(N1, v1, a, ns);\n  corra /= corra[1];                          # Normalize\n  push!(τ1,sum(corra) - 0.5);                 # Get autocorrelation time\nend\nfor a in [1:5]\n  corra = autocorrelation(N2, v2, a, ns);\n  corra /= corra[1];                          # Normalize\n  push!(τ2,sum(corra) - 0.5);                 # Get autocorrelation time\nend\n\nprintln(\"\\n\\tEstimated Autocorrelation Times for N1 = $N1:\\n\");\nfor i in [1:5]\n  println(\"\\t\\tτ̂1v$i:\\t$(τ1[i])\");\nend\nprintln(\"\\n\\tEstimated Autocorrelation Times for N2 = $N2:\\n\");\nfor i in [1:5]\n  println(\"\\t\\tτ̂2v$i:\\t$(τ2[i])\");\nend\nprintln(\"\\n\\tThe estimated autocorrelation times are clearly far better for the larger sample.\");\n\n# Estimate standard deviation\nσ1 = Float64[];\nσ2 = Float64[];\nprintln(\"\\n\\tCreating estimators σ1 for the standard deviation for N1 = $N1\");\nfor a in [1:5]\n  diff1 = v1[:,a] .- mean(v1[:,a]);\n  σ1a = sqrt( dot( diff1, diff1 ) / (N1-1) );\n  println(\"\\t\\tσ̂1[$a] = $σ1a\");\n  push!(σ1, σ1a);\nend\nprintln(\"\\n\\tCreating estimators σ2 for the standard deviation for N2 = $N2\");\nfor a in [1:5]\n  diff2 = v2[:,a] .- mean(v2[:,a]);\n  σ2a = sqrt( dot( diff2, diff2 ) / (N2-1) );\n  println(\"\\t\\tσ̂2[$a] = $σ2a\");\n  push!(σ2, σ2a);\nend\n\n# Estimate standard deviation of the sample mean\nσN1 = sqrt( 2 / N1 .* τ1 ) .* σ1;\nσN2 = sqrt( 2 / N2 .* τ2 ) .* σ2;\nprintln(\"\\n\\tEstimating standard deviations of the sample mean for N1 = $N1:\");\nfor i in [1:5]\n  println(\"\\n\\t\\tσ̂N1[$i] = $(σN1[i])\");\nend\nprintln(\"\\n\\tEstimating standard deviations of the sample mean for N2 = $N2:\");\nfor i in [1:5]\n  println(\"\\n\\t\\tσ̂N2[$i] = $(σN2[i])\");\nend\n\n# Compare to the actual measured values of the standard deviations of the sample mean\nsigmean1 = σ̂1./σN1;\nsigmean2 = σ̂2./σN2;\nprintln(\"\\n\\tTake ratio of measured standard deviation of sample means over the estimated\");\nprintln(\"\\tstandard deviation just found in order to measure the accuracy of the estimate.\");\nprintln(\"\\n\\tFind the ratio for N1 = $N1:\")\nfor i in [1:5]\n  println(\"\\n\\t\\tσ̂1[$i] / σ̂N1[$i] = $(sigmean1[i])\");\nend\nprintln(\"\\n\\tFind the ratio for N2 = $N2:\")\nfor i in [1:5]\n  println(\"\\n\\t\\tσ̂2[$i] / σ̂N2[$i] = $(sigmean2[i])\");\nend\n\nprintln(\"\\n\\tFor both sample sizes, these estimates are close to the true values of\");\nprintln(\"\\tthe standard deviation of the sample means, though the agreement is far\");\nprintln(\"\\tbetter for the larger sample size.\");\n\n# Find sample means\nv̄1 = zeros(5);\nv̄2 = zeros(5);\nfor i in [1:5]\n  v̄1[i] = mean(v1[:,i]);\n  v̄2[i] = mean(v2[:,i]);\nend\n\n# Finally, compare the normalized covariance matrices ρ1 and ρ2 to the true value ρ̂.\nprintln(\"\\n\\tFinally, estimate the normalized covariance matrices ρ1 and ρ2.\\n\");\nprintln(\"\\tEstimating the covariance matrix c1 for sample size N1 = $N1\");\nD1 = v1 - ones(N1) * transpose(v̄1);\nc1 = transpose(D1) * D1 / N1;\nprintln(\"\\tEstimating the covariance matrix c2 for sample size N2 = $N2\");\nD2 = v2 - ones(N2) * transpose(v̄2);\nc2 = transpose(D2) * D2 / N2;\n\nprintln(\"\\tEstimating the normalized covariant matrix ρ1 for N1 = $N1\");\nρ1 = c1 ./ ( σ1 * transpose(σ1) );\nprintln(\"\\tEstimating the normalized covariant matrix ρ2 for N2 = $N2\");\nρ2 = c2 ./ ( σ2 * transpose(σ2) );\n", "meta": {"hexsha": "7e758547b4b5c8fbdbf7972dfdb64ac9b40bcc1f", "size": 4888, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "set03/q1/p7.jl", "max_stars_repo_name": "stefco/g6080", "max_stars_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "set03/q1/p7.jl", "max_issues_repo_name": "stefco/g6080", "max_issues_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "set03/q1/p7.jl", "max_forks_repo_name": "stefco/g6080", "max_forks_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4225352113, "max_line_length": 97, "alphanum_fraction": 0.6333878887, "num_tokens": 1655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8856314632529872, "lm_q1q2_score": 0.7596664283943374}}
{"text": "#\n# Computes the density function of a list of values\n#\nstruct Density\n  x :: Vector{Float64}\n  d :: Vector{Float64}\n  step :: Float64\n  norm :: Int64\nend\n\n\"\"\"\n```\nfitdensity(x; step, norm)\n```\n\nObtains the density function given data sampled.\n\nUse `step=(Float64)` to control the bin step. Use `norm=(0 or 1)` to set\nif the number of data points or the probability of finding a data point\nwithin ± step/2 will be output.\n\nBy default, `norm=1` (probability) and the step is `(xmax-xmin)/100`.\n\n# Examples\n```jldoctest\njulia> x = randn(1000)\n\njulia> d = fitdensity(x)\n\n ------------------- Density -------------\n\n  `d` contains the number of data points within x ± 0.028325979340904375\n\n -----------------------------------------\n\n```\n\"\"\"\nfunction fitdensity(v;nbins=nothing,\n                      step=nothing, steptype=\"absolute\",\n                      vmin=nothing, vmax=nothing,\n                      norm :: Int64 = 1)\n\n  ndata = length(v)\n\n  if vmin == nothing\n    vmin = minimum(v)\n  end\n  if vmax == nothing\n    vmax = maximum(v)\n  end\n  if nbins == nothing\n    nbins = 100\n  end\n  if step == nothing\n    step = (vmax - vmin)/nbins\n  else\n    # By default, the step size is absolute\n    if steptype == \"relative\"\n      step = step*(vmax-vmin)/nbins\n    elseif steptype != \"absolute\"\n      error(\" steptype must be \\\"relative\\\" or \\\"absolute\\\"\")\n    end\n  end\n\n  x = Vector{Float64}(undef,nbins)\n  df = Vector{Float64}(undef,nbins)\n\n  binstep = (vmax - vmin)/nbins\n  for i in 1:nbins\n    x[i] = vmin + (i-1)*binstep + binstep/2\n    nv = 0\n    for j in 1:ndata\n      if ( v[j] > x[i] - step/2 ) && ( v[j] <= x[i] + step/2 )\n        nv = nv + 1\n      end\n    end\n    binsize = min(vmax,x[i]+step/2) - max(vmin,x[i]-step/2)\n    if norm == 0\n      df[i] = nv\n    elseif norm == 1\n      df[i] = nv/(binsize*ndata)\n    end\n  end\n\n  return Density(x,df,step,norm)\nend\nexport fitdensity\n\nfunction Base.show( io :: IO, d :: Density )\n  if d.norm == 0\n    s = \"number of\"\n  end\n  if d.norm == 1\n    s = \"probability of finding\"\n  end\n  println(\" \n ------------------- Density -------------\n\n  d contains the $s data points within x ± $(round(d.step/2,sigdigits=3))\n\n ----------------------------------------- \")\nend\n", "meta": {"hexsha": "62d034661e6ab1d78a53b0096fc758ace19e5d78", "size": 2212, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fitdensity.jl", "max_stars_repo_name": "m3g/EasyF", "max_stars_repo_head_hexsha": "601df86cb3927a195d91558a4027bb5e949771c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-04-07T12:58:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T13:42:50.000Z", "max_issues_repo_path": "src/fitdensity.jl", "max_issues_repo_name": "m3g/EasyF", "max_issues_repo_head_hexsha": "601df86cb3927a195d91558a4027bb5e949771c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-17T14:34:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-24T14:19:10.000Z", "max_forks_repo_path": "src/fitdensity.jl", "max_forks_repo_name": "m3g/EasyFit.jl", "max_forks_repo_head_hexsha": "601df86cb3927a195d91558a4027bb5e949771c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-08-19T20:58:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-17T18:43:12.000Z", "avg_line_length": 21.4757281553, "max_line_length": 73, "alphanum_fraction": 0.5551537071, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7596664184186116}}
{"text": "using Plots, Printf\n\n\"\"\"\n    shallow_water_1D(;nx=1024, do_visu=false)\n\n1D shallow water equations solver for an instantaneous dam break.\nThe Lax-Friedrichs Method was applied to the continuity equation.\nGeometry (length of 40 meters) and initial conditions (half of domain \nhave initial water level of 5 meters, other half is dry) match \nBASEMENT version 2.8 Test Case H_1 \"Dam break in a closed channel\n\n# Arguments\n    - `nx`: number of discretised cells.\n    - `do_visu`: if true, each physical time step will be ploted.\n\n# Return values\n    - `H`: The solution arrray (Water surface height in m).\n\"\"\"\n@views function shallow_water_1D(;\n    # Numerics\n    nx = 1024,\n    # Visualisation\n    do_visu = false)\n    # Physics\n    Lx = 40.0\n    g = 9.81\n    u_max = 6 #from review of results with very small timesteps\n    ttot = 20.0\n    # Numerics\n    nout = 100\n    # Derived numerics\n    dx = Lx / nx\n    dt = dx / u_max / 10 #stability condition of Lax-Friedrichs Method, further divided by 10 for stability of initially discontinuous wave front\n    #println(dt)\n    nt = cld(ttot, dt)\n    xc = LinRange(dx / 2, Lx - dx / 2, nx)\n    # Array initialisation\n    H = zeros(Float64, nx)\n    H[1:round(Int64(nx / 2))] = 5.0 .+ zeros(Float64, round(Int64(nx / 2)))\n    u = zeros(Float64, nx)\n    dHdx = zeros(Float64, nx - 1)\n    dudx = zeros(Float64, nx - 1)\n    dudt = zeros(Float64, nx - 1)\n    t_tic = 0.0\n    niter = 0\n    # Time loop\n    for it = 0:nt\n        if (it == 11)\n            t_tic = Base.time()\n            niter = 0\n        end\n        dHdx .= diff(H) ./ dx\n        dudx .= diff(u) ./ dx\n        dudt .= -1 / 2 .* (u[1:end-1] .+ u[2:end]) .* dudx .- (g .* dHdx) #momentum\n        H[2:end-1] .= 1 / 2 .* (H[3:end] .+ H[1:end-2]) .- dt / 2 / dx .* ((H[3:end] .* u[3:end]) .- (H[1:end-2] .* u[1:end-2])) #continuity with Lax-Friedrichs Method\n        H[1] = H[2]\n        H[end] = H[end-1]\n        u[2:end-1] .= u[2:end-1] .+ 1 / 2 .* (dudt[1:end-1] .+ dudt[2:end]) .* dt\n        u[1] = -u[2]\n        u[end] = -u[end-1]\n\n        niter += 1\n        if do_visu && (it % nout == 0)\n            p1 = plot(xc, H, xlims = (xc[1], xc[end]), ylims = (0, 10),\n                xlabel = \"Lx (m)\", ylabel = \"water surface elevation (m)\", label = \"h\",\n                title = \"time = $(round(it*dt, sigdigits=3)) s, stability: $(round(maximum(abs.(u))*dt/dx,sigdigits=3)) /1\",\n                linewidth = :1.0, framestyle = :box)\n            plot!(xc, u, label = \"u\", linewidth = :1.0)\n            display(p1)\n        end\n    end\n    t_toc = Base.time() - t_tic\n    A_eff = (2 * 2) / 1e9 * nx * sizeof(Float64)  # Effective main memory access per iteration [GB]\n    t_it = t_toc / niter                      # Execution time per iteration [s]\n    T_eff = A_eff / t_it                       # Effective memory throughput [GB/s]\n    @printf(\"Time = %1.3f sec, T_eff = %1.2f GB/s (niter = %d)\\n\", t_toc, round(T_eff, sigdigits = 3), niter)\n    return H\nend\n\n# shallow_water_1D(;do_visu=true)", "meta": {"hexsha": "5a19e13b0c0a7b048ee209a341f0aecedee1e093", "size": 2986, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts-part2/1D_SWE/shallow_water_1D_LF.jl", "max_stars_repo_name": "mchalso/FinalProjectRepo.jl", "max_stars_repo_head_hexsha": "08056c39b71fb572a3749a82c2f47b0529792757", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-26T22:53:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T22:53:07.000Z", "max_issues_repo_path": "scripts-part2/1D_SWE/shallow_water_1D_LF.jl", "max_issues_repo_name": "mchalso/FinalProjectRepo.jl", "max_issues_repo_head_hexsha": "08056c39b71fb572a3749a82c2f47b0529792757", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts-part2/1D_SWE/shallow_water_1D_LF.jl", "max_forks_repo_name": "mchalso/FinalProjectRepo.jl", "max_forks_repo_head_hexsha": "08056c39b71fb572a3749a82c2f47b0529792757", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.325, "max_line_length": 167, "alphanum_fraction": 0.5579370395, "num_tokens": 1034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7596657813828894}}
{"text": "export srDistance\n\n\"\"\"\nfunction srDistance\n\nUnnormalized distance (reconstruction error) between two pairs (M,w):\n\nmin_P ||M1*diagm(w1) - M2*diagm(w2)*P ||_p\n\nwhere P is a permutation matrix and || ||_p denotes the entrywise matrix pn-norm\n(i.e., pn=2 corresponds to the Frobenius norm).\n\nBefore computing the error, the first dimensions of the binary matrices are\naugmented from m*(p-1) to m*p so that the column sums of each block become 1.\nThis can be disabled by setting p=1.\n\nIf n has different values among the inputs, then the largest n is chosen and\nthe rest are augmented with zeros to make the dimensions compatible.\n\nInput:\n    M1 - binary array of size (m*(p-1),n) or (m*(p-1),n,N)\n    w1 - frequency vector of length n or an array of size (n,N)\n    M2 - as M1\n    w2 - as w1\n\nKeyword arguments:\n    p - number of categories (default=2)\n    pn - exponent in the matrix norm (default=2.0)\n\nOutput:\n    distance(s) as a scalar or an N-vector\n\"\"\"\n\nfunction srDistance(M1::BitArray{2},w1::Vector,M2::BitArray{2},w2::Vector;p::Int64=2,pn::Float64=2.0)\n    n = maximum((size(M1,2),length(w1),size(M2,2),length(w2)))\n    M1 = [M1 falses(size(M1,1),n-size(M1,2))]\n    w1 = [w1; zeros(n-length(w1))]\n    M2 = [M2 falses(size(M2,1),n-size(M2,2))]\n    w2 = [w2; zeros(n-length(w2))]\n\n    perms = permutations(1:n)\n\n    if p>1\n        M1 = fullCategoricalMatrix(M1,p)\n        M2 = fullCategoricalMatrix(M2,p)\n    end\n\n    distance = Inf\n    for perm in perms\n        M2perm = M2[:,perm]\n        w2perm = w2[perm]\n\n        mat = M1*diagm(w1) - M2perm*diagm(w2perm)\n        dist = (sum(abs.(mat[:]).^pn))^(1/pn)\n        if dist < distance\n            distance = dist\n        end\n    end\n\n    return distance\nend\n\nfunction srDistance(M1::BitArray{3},w1::Array{Float64,2},M2::BitArray{3},w2::Array{Float64,2};p::Int64=2,pn::Float64=2.0)\n    N = size(M1,3)\n    distances = SharedArray{Float64}(N)\n\n    @sync @parallel for idx = 1:N\n        distances[idx] = srDistance(M1[:,:,idx],w1[:,idx],M2[:,:,idx],w2[:,idx],p=p,pn=pn)\n    end\n\n    return distances\nend\n\nfunction fullCategoricalMatrix(M::BitArray{2},p::Int64)\n    n = size(M,2)\n\n    M1 = reshape(M,(p-1,:))\n    blockcolsums = sum(M1,1)\n    Mfull = [1-blockcolsums; M1]\n\n    return reshape(Mfull,(:,n))\nend\n", "meta": {"hexsha": "8b0c697467105a4f3428da26255de344f0a38720", "size": 2255, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/srDistance.jl", "max_stars_repo_name": "lruthotto/StrainRecon.jl", "max_stars_repo_head_hexsha": "ba1c5392994e80bb0f7e6b94f90b404f25c40958", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-05-01T00:47:02.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-01T00:47:02.000Z", "max_issues_repo_path": "src/srDistance.jl", "max_issues_repo_name": "lruthotto/StrainRecon.jl", "max_issues_repo_head_hexsha": "ba1c5392994e80bb0f7e6b94f90b404f25c40958", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/srDistance.jl", "max_forks_repo_name": "lruthotto/StrainRecon.jl", "max_forks_repo_head_hexsha": "ba1c5392994e80bb0f7e6b94f90b404f25c40958", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1686746988, "max_line_length": 121, "alphanum_fraction": 0.6376940133, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595161, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7596657752513067}}
{"text": "using Distributions, Random, Statistics, Plots; pyplot()\nRandom.seed!(2)\n\nn, N, alpha = 10, 10^7, 0.05\nmActual = 0.75\ndist0, dist1 = Uniform(0,1), Uniform(0,mActual)\n\nts(sample) = maximum(sample) - minimum(sample)\n\nempiricalDistUnderH0 = [ts(rand(dist0,n)) for _ in 1:N]\nrejectionValue = quantile(empiricalDistUnderH0,alpha)\n\nsample = rand(dist1,n)\ntestStat = ts(sample)\npValue = sum(empiricalDistUnderH0 .<= testStat)/N\n\nif testStat > rejectionValue\n    print(\"Didn't reject: \", round(testStat,digits=4))\n    print(\" > \", round(rejectionValue,digits=4))\nelse\n    print(\"Reject: \", round(testStat,digits=4))\n    print(\" <= \", round(rejectionValue,digits=4))\nend\nprintln(\"\\np-value = $(round(pValue,digits=4))\")\n\nstephist(empiricalDistUnderH0, bins=100, c=:blue, normed=true, label=\"\")\nplot!([testStat, testStat], [0,4], c=:red, label=\"Observed test statistic\")\nplot!([rejectionValue, rejectionValue], [0,4], c=:black, ls=:dash,\n\tlabel=\"Critical value boundary\", legend=:topleft, ylims=(0,4),\n    \txlabel = \"x\", ylabel = \"Density\")", "meta": {"hexsha": "dfb2df64fa183e4cdc13af44c73713c76a257ee8", "size": 1030, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5_chapter/teststatPvalRejectregion.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "5_chapter/teststatPvalRejectregion.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "5_chapter/teststatPvalRejectregion.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 34.3333333333, "max_line_length": 75, "alphanum_fraction": 0.6961165049, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7596428069060468}}
{"text": "#= convex.jl\nPhilip Barrett, pobarrett@gmail.com\n27may2016, Chicago\n\nCalculates the convex hull of a set of points\n=#\n\n\"\"\"\n    acw( p1, p2, p3 )\nPositive if p1 -> p2 -> p3 is anti-clockwise\n\"\"\"\nfunction acw( p1, p2, p3 )\n  return (p2[1] - p1[1]) * (p3[2] - p1[2]) - (p2[2] - p1[2]) * (p3[1] - p1[1])\nend\n\n\"\"\"\n    grahamScan( pts::Matrix )\nComputes a convex hull using the Graham Scan algortithm NB: Returns a polygon object even when a matrix is submitted\n\"\"\"\n\nfunction grahamScan( pts::Matrix )\n\n  N = size(pts)[1]\n      # Number of points\n  lex = sortrows( pts[ :, [2, 1 ] ] )[ :, [ 2, 1 ] ]\n      # Sorts the points lexicographically by y then x\n  P = lex[ 1, : ]\n      # The initial point\n  otherpts = lex[ 2:end, : ]\n      # The other points\n  orderpts = [ P; otherpts ; P ]\n      # Initialize the anti-clockwise ordered points\n  cah = zeros( N - 1 )\n      # The cosine of the angle between each point and P.  Will be in\n      # [-1,1] because of choice of P\n\n  ## Order the points anti-clockwise ##\n  for( i in 1:(N-1) )\n    diff = otherpts[i,:] - P\n    cah[i] = diff[1] / norm(diff)\n        # Cosine is adjacent over hypotenuse\n  end\n  orderpts[2:N,:] = otherpts[ sortperm(cah, rev=true), : ]\n      # Order the points by the angle measure\n\n  ## Create the output ##\n  out = similar( pts )\n  out[ 1:2, : ] = orderpts[1:2,:]\n      # Initialize\n  M = 2\n      # Counts number of rows in convex hull\n  for( i in 3:N )\n    while( acw( out[ M-1, : ], out[ M, : ], orderpts[ i, : ] ) < 0 )\n      if( M > 2 )\n        M -= 1\n      elseif( i == N )\n        break\n      else\n        i += 1\n      end\n    end\n    M += 1\n        # Increment counter\n    out[ M, : ] = orderpts[ i, : ]\n        # Add to the output if we have an acw angle\n  end\n  return Polygon( pts=out[ 1:M, : ] )\nend\n\nfunction grahamScan( poly::Polygon )\n    return grahamScan( poly.pts )\nend\n\n\"\"\"\n    convexhull( poly::Polygon )\nComputes a convex hull using the Graham Scan algortithm from the CHull2D package\n\"\"\"\nfunction chull( poly::Polygon )\n  return Polygon( pts = chull(poly.pts) )\nend\n\nfunction chull( pts::Matrix )\n  N = size(pts)[1]\n      # Number of points\n  oldpts = Point{2, Float64}[Point(pts[i, 1], pts[i, 2])\n                            for i=1:N]\n      # Convert poly.pts to an array of points\n  ch = CHull2d.convexhull(oldpts, _at=false)\n      # The convex hull object\n  N_newpts = length(ch.extremepoints)\n  newpts = Array(Float64, N_newpts, 2)\n      # Create the container for the new points\n  for i=1:N_newpts\n      curr_pt = ch.extremepoints[i]\n      newpts[i, 1] = curr_pt[1]\n      newpts[i, 2] = curr_pt[2]\n  end\n  return newpts\nend\n", "meta": {"hexsha": "6f29e516677bb9c32a7a04498c05d75267121776", "size": 2617, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/convex.jl", "max_stars_repo_name": "philipbarrett/Polygons.jl", "max_stars_repo_head_hexsha": "99878cafc7d17807a80648f6790ac2e6acebeacd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-09-23T16:14:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:11:57.000Z", "max_issues_repo_path": "src/convex.jl", "max_issues_repo_name": "philipbarrett/Polygons.jl", "max_issues_repo_head_hexsha": "99878cafc7d17807a80648f6790ac2e6acebeacd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/convex.jl", "max_forks_repo_name": "philipbarrett/Polygons.jl", "max_forks_repo_head_hexsha": "99878cafc7d17807a80648f6790ac2e6acebeacd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-05-31T23:22:02.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-31T23:22:02.000Z", "avg_line_length": 26.17, "max_line_length": 116, "alphanum_fraction": 0.5869316011, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7596428012230635}}
{"text": "function ABCDQR_simula(nt::Int,seed::Int)\n\t#\n\t# simulated model to test the functions\n\t#\n\t# nt: number of time instants\n\t# seed: seed for the random numbers\n\n\t# random seed\n\t# ------------------------------\n\tRandom.seed!(seed)\n\n\t# simulated system\n\tm = simula01()\n\n\t# vibration parameters\n\t# ----------------------------\n\t# time interval (s)\n\tdt = m[\"dt\"]\n\n\t# state-space matrices\n\t# --------------------------------------\n\tA = m[\"A\"]\n\tB = m[\"B\"]\n\tC = m[\"C\"]\n\tD = m[\"D\"]\n\n\t# input definition\n\t# ---------------------------------------\n\t# system input\n\tu = 100*randn(2,nt) # if 100 is not used, Q and R are too little\n\n\t# state equation, no noise\n\t# ---------------------------------\n\tx = zeros(4,nt)\n\tfor t=1:nt-1\n\t\tx[:,t+1] = A*x[:,t] + B*u[:,t]\n\tend\n\tP = cov(x')\n\tQ = 0.01*P # std approx 0.1\n\tch = cholesky(Q)\n\tw = ch.L*randn(4,nt)\n\n\t# state equation with noise\n\t# ------------------------------------------\n\tx = zeros(4,nt)\n\tfor t = 1:nt-1\n\t\tx[:,t+1] = A*x[:,t] + B*u[:,t] + w[:,t]\n\tend\n\n\t# observation equation\n\t# -------------------------------------\n\ty = C*x + D*u\n\tL = cov(y')\n\tR = 0.01*L # std approx 0.1\n\tch = cholesky(R)\n\tv = ch.L*randn(2,nt)\n\ty = y + v\n\n\t#\n\tS = cov(w',v')\n\n\t# starting values\n\tm1 = C\\y[:,1:1]\n\tP1 = 0*A\n\n\tm = Dict(\"dt\"=>dt,\n\t\"y\"=>y,\"u\"=>u,\n\t\"A\"=>A,\"B\"=>B,\"C\"=>C,\"D\"=>D,\n\t\"Q\"=>Q,\"R\"=>R,\"S\"=>S,\n\t\"m1\"=>m1,\"P1\"=>P1)\n\n\treturn m\n\nend\n", "meta": {"hexsha": "b29802b3905cd1add6a63fe34e6a8e7b5ddb61a2", "size": 1357, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ABCDQR/ABCDQR_simula.jl", "max_stars_repo_name": "javiercara/StateSpaceModelsEM.jl", "max_stars_repo_head_hexsha": "989d538b01274885e4579df130f9b38bbb99cc7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ABCDQR/ABCDQR_simula.jl", "max_issues_repo_name": "javiercara/StateSpaceModelsEM.jl", "max_issues_repo_head_hexsha": "989d538b01274885e4579df130f9b38bbb99cc7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ABCDQR/ABCDQR_simula.jl", "max_forks_repo_name": "javiercara/StateSpaceModelsEM.jl", "max_forks_repo_head_hexsha": "989d538b01274885e4579df130f9b38bbb99cc7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0933333333, "max_line_length": 65, "alphanum_fraction": 0.4347826087, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7596427943130685}}
{"text": "\"\"\"Calculate the Fermi Function given some energy and some temperature.\n\nParameters\n----------\nen : float\n    Energy relative to the fermi energy (E-Ef).\n\nkbt : Temperature in same units as Energy (using kB).\n\nReturns\n-------\nffun : float\n    The Fermi Function at en and temp.\"\"\"\nfunction fermi_fun(en, kbt)\n    if en == 0\n        ffun = 0.5\n    elseif kbt == 0\n        if en < 0\n            ffun = 1.0\n        elseif en > 0\n            ffun = 0.0\n        else\n            throw(DomainError(\"Energy must be a real number.\"))\n        end\n    elseif kbt > 0\n        #Using a tanh here instead of the more traditional formulation because\n        #the function is better behaved for very large or small values of en/kbt\n        ffun = 0.5*(1-tanh(0.5*en/kbt))\n\n    elseif kbt < 0\n        throw(DomainError(\"Temperature must be >= 0.\"))\n    end\n\n    return ffun\nend\n", "meta": {"hexsha": "31e9a1f35254bec42c7cb42fc3ad2a6adb49d6de", "size": 862, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fermi_functions.jl", "max_stars_repo_name": "FaustinCarter/Barmat.jl", "max_stars_repo_head_hexsha": "5cbd2de198f24f81486fbf3464c1c75fcc7ab60a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fermi_functions.jl", "max_issues_repo_name": "FaustinCarter/Barmat.jl", "max_issues_repo_head_hexsha": "5cbd2de198f24f81486fbf3464c1c75fcc7ab60a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fermi_functions.jl", "max_forks_repo_name": "FaustinCarter/Barmat.jl", "max_forks_repo_head_hexsha": "5cbd2de198f24f81486fbf3464c1c75fcc7ab60a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9444444444, "max_line_length": 80, "alphanum_fraction": 0.5928074246, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012701768144, "lm_q2_score": 0.8031737869342624, "lm_q1q2_score": 0.7596427878551475}}
{"text": "\nfunction add_mass_matrix!{T<:Number}(bas::GenBasis1d, el::Element1d, mass::AbstractMatrix{T}, λ=one(T))\n    M = nmodes(bas)\n    Q = nquad(bas)\n    ϕ = qbasis(bas)\n    wJ = jacweights(el)\n    for k = 1:M\n        for i = k:M\n            m = 0.0\n            for q = 1:Q\n                m += ϕ[q,k] * ϕ[q, i] * wJ[q] \n            end\n            mass[k,i] += m*λ\n            if k != i\n                mass[i,k] += m*λ\n            end\n        end\n    end\n    return mass\nend\n\nfunction add_mass_matrix!{T<:Number}(bas::SEM1d{T}, el::Element1d, mass::AbstractMatrix{T}, λ=one(T))\n\n    M = nmodes(bas)\n    wJ = jacweights(el)\n\n    for i = 1:M\n        mass[i,i] += wJ[i]*λ\n    end\nend\n\n\nmass_matrix{T<:Number}(bas::GenBasis1d, el::Element1d{T}, λ=one(T)) =\n    add_mass_matrix!(bas, el, zeros(T, nmodes(bas), nmodes(bas)), λ)\n\n   \n\nfunction add_mass_matrix!{T<:Number}(bas::SEM1d{T}, el::Element1d, mass::AbstractMatrix{T}, λ::AbstractVector{T})\n\n    M = nmodes(bas)\n    wJ = jacweights(el)\n\n    for i = 1:M\n        mass[i,i] += wJ[i]*λ[i]\n    end\nend\n\nfunction add_mass_matrix!{T<:Number}(bas::GenBasis1d, el::Element1d, mass::AbstractMatrix{T}, λ::AbstractVector{T})\n    M = nmodes(bas)\n    Q = nquad(bas)\n    ϕ = qbasis(bas)\n    wJ = jacweights(el)\n    for k = 1:M\n        for i = k:M\n            m = zero(T)\n            for q = 1:Q\n                m += ϕ[q,k] * ϕ[q, i] * wJ[q] * λ[q]\n            end\n            mass[k,i] += m\n            if k != i\n                mass[i,k] += m\n            end\n        end\n    end\n    return mass\nend\n\n\nfunction add_stiff_matrix!{T<:Number}(bas::GenBasis1d, el::Element1d, mat::AbstractMatrix{T}, λ=one(T))\n    M = nmodes(bas)\n    Q = nquad(bas)\n    dϕ = dqbasis(bas)\n    D = diffmat(bas)\n    wJ = jacweights(el)\n    dξdx = deriv_ξ(el)\n    for k = 1:M\n        for i = k:M\n            L = zero(T)\n            for q = 1:Q\n                L += dϕ[q,i] * dϕ[q,k] *wJ[q] * (dξdx[q]^2)*λ\n            end\n            mat[i,k] += L\n            if k != i\n                mat[k,i] += L\n            end\n        end\n    end\n    return mat\nend\n\nstiff_matrix{T<:Number}(bas::GenBasis1d, el::Element1d{T}, λ=one(T)) =\n    add_stiff_matrix!(bas, el, zeros(T, nmodes(bas), nmodes(bas)), λ)\n\nfunction add_stiff_matrix!{T<:Number}(bas::GenBasis1d, el::Element1d, mat::AbstractMatrix{T},\n                                      λ::AbstractVector{T})\n    M = nmodes(bas)\n    Q = nquad(bas)\n    dϕ = dqbasis(bas)\n    D = diffmat(bas)\n    wJ = jacweights(el)\n    dξdx = deriv_ξ(el)\n    \n\n    for k = 1:M\n        for i = k:M\n            L = zero(T)\n            for q = 1:Q\n                L += dϕ[q,i] * dϕ[q,k] *wJ[q] * (dξdx[q]^2)*λ[q]\n            end\n            mat[i,k] += L\n            if k != i\n                mat[k,i] += L\n            end\n        end\n    end\n\n    return mat\nend\n\n\n# RHS\n\nfunction add_rhs!{T<:Number}(bas::GenBasis1d{T}, el::Element1d{T}, f::AbstractVector{T},\n                            Fe::AbstractVector{T})\n\n    wJ = jacweights(el)\n    ϕ = qbasis(bas)\n    M = nmodes(bas)\n    Q = nquad(bas)\n\n    for k = 1:M\n        F = zero(T)\n        for q = 1:Q\n            F += f[q] * ϕ[q,k] * wJ[q]\n        end\n        Fe[k] += F\n    end\n    return Fe \nend\n\n\nfunction add_rhs!{T<:Number}(bas::SEM1d{T}, el::Element1d{T}, f::AbstractVector{T},\n                            Fe::AbstractVector{T})\n\n    wJ = jacweights(el)\n    M = nmodes(bas)\n\n    for k = 1:M\n        Fe[k] = f[k] * wJ[k]\n    end\n    return Fe \nend\n\n", "meta": {"hexsha": "a0bf71db5fa767de34ead006f635645de7159e67", "size": 3437, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operator.jl", "max_stars_repo_name": "pjabardo/HPFEM.jl", "max_stars_repo_head_hexsha": "3c3d13204ad720129b23ccd44a7a26897986cdbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-03-15T19:03:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-22T00:13:53.000Z", "max_issues_repo_path": "src/operator.jl", "max_issues_repo_name": "pjabardo/HPFEM.jl", "max_issues_repo_head_hexsha": "3c3d13204ad720129b23ccd44a7a26897986cdbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/operator.jl", "max_forks_repo_name": "pjabardo/HPFEM.jl", "max_forks_repo_head_hexsha": "3c3d13204ad720129b23ccd44a7a26897986cdbc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-09-03T00:36:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-24T20:04:15.000Z", "avg_line_length": 22.3181818182, "max_line_length": 115, "alphanum_fraction": 0.4722141402, "num_tokens": 1203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7595895901099243}}
{"text": "## Multivariate linear Gaussian model\n\nmodule MVLinearGaussian\n\nusing SequentialMonteCarlo\nusing RNGPool\nusing StaticArrays\nimport SMCExamples.Particles.MVFloat64Particle\nusing LinearAlgebra\nusing Random\n\nstruct MVLGTheta{d}\n  A::SMatrix{d, d, Float64}\n  Q::SMatrix{d, d, Float64}\n  C::SMatrix{d, d, Float64}\n  R::SMatrix{d, d, Float64}\n  x0::SVector{d, Float64}\n  v0::SVector{d, Float64}\nend\n\n## scratch space for computations\nstruct MVLGPScratch{d}\n  t1::MVector{d, Float64}\n  t2::MVector{d, Float64}\nend\nMVLGPScratch{d}() where d = MVLGPScratch{d}(MVector{d, Float64}(undef),\n  MVector{d, Float64}(undef))\n\nfunction makeMVLGModel(theta::MVLGTheta, ys::Vector{SVector{d, Float64}}) where\n  d\n  n = length(ys)\n  cholQ = SMatrix{d, d, Float64}(cholesky(theta.Q).L)\n  invRover2 = 0.5 * inv(theta.R)\n  sqrtv0 = sqrt.(theta.v0)\n  logncG = - 0.5 * d * log(2 * π) - 0.5 * logdet(theta.R)\n  @inline function lG(p::Int64, particle::MVFloat64Particle{d},\n    scratch::MVLGPScratch{d})\n    mul!(scratch.t1, theta.C, particle.x)\n    @inbounds scratch.t2 .= scratch.t1 .- ys[p]\n    mul!(scratch.t1, invRover2, scratch.t2)\n    return logncG - dot(scratch.t1,scratch.t2)\n  end\n  @inline function M!(newParticle::MVFloat64Particle{d}, rng::RNG, p::Int64,\n    particle::MVFloat64Particle{d}, scratch::MVLGPScratch{d})\n    if p == 1\n      randn!(rng, scratch.t1)\n      scratch.t2 .= sqrtv0 .* scratch.t1\n      newParticle.x .= theta.x0 .+ scratch.t2\n    else\n      randn!(rng, scratch.t1)\n      mul!(scratch.t2, cholQ, scratch.t1)\n      mul!(scratch.t1, theta.A, particle.x)\n      newParticle.x .= scratch.t1 .+ scratch.t2\n    end\n  end\n  return SMCModel(M!, lG, length(ys), MVFloat64Particle{d}, MVLGPScratch{d})\nend\n\nfunction simulateMVLGModel(theta::MVLGTheta{d}, n::Int64) where d\n  model = makeMVLGModel(theta, Vector{SVector{d, Float64}}(undef, 0))\n  ys = Vector{SVector{d, Float64}}(undef, n)\n  xParticle = MVFloat64Particle{d}()\n  xScratch = MVLGPScratch{d}()\n  cholR = cholesky(theta.R).L\n  rng = getRNG()\n  for p in 1:n\n    model.M!(xParticle, rng, p, xParticle, xScratch)\n    ys[p] = theta.C*(xParticle.x) + cholR * randn(rng,d)\n  end\n  return ys\nend\n\nfunction defaultMVLGModel(d::Int64, n::Int64)\n  function toeplitz(d::Int64, a::Float64, C::Float64)\n    M = Matrix{Float64}(undef, d, d)\n    for i = 1:d\n      for j = 1:d\n        M[i,j] = C * a^abs(i-j)\n      end\n    end\n    return SMatrix{d, d, Float64}(M)\n  end\n\n  tA = SMatrix{d, d, Float64}(0.9 * Matrix{Float64}(I, d, d))\n  tC = toeplitz(d, 0.5, 1.2)\n  tQ = toeplitz(d, 0.2, 0.6)\n  tR = toeplitz(d, 0.3, 1.5)\n  tx0 = SVector{d,Float64}(range(1, step=1, length=d))\n  tv0 = SVector{d,Float64}(range(2, step=1, length=d))\n  theta = MVLGTheta(tA, tQ, tC, tR, tx0, tv0)\n  ys = simulateMVLGModel(theta, n)\n\n  ko = kalmanMV(theta, ys)\n\n  mvlgModel = makeMVLGModel(theta, ys)\n\n  return mvlgModel, theta, ys, ko\nend\n\ninclude(\"mvlgKalman.jl\")\n\nend\n", "meta": {"hexsha": "e6518707e83795651b9d410e04baef1526b218a6", "size": 2890, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mvlgModel.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SMCExamples.jl-251f48c7-f5a4-5bc8-b6b6-ff4797c45649", "max_stars_repo_head_hexsha": "b843bea5ae123dd9c643daba03e2254ca56f0bd2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-12-31T12:57:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T14:00:31.000Z", "max_issues_repo_path": "src/mvlgModel.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SMCExamples.jl-251f48c7-f5a4-5bc8-b6b6-ff4797c45649", "max_issues_repo_head_hexsha": "b843bea5ae123dd9c643daba03e2254ca56f0bd2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-02T15:47:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T09:32:00.000Z", "max_forks_repo_path": "src/mvlgModel.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SMCExamples.jl-251f48c7-f5a4-5bc8-b6b6-ff4797c45649", "max_forks_repo_head_hexsha": "b843bea5ae123dd9c643daba03e2254ca56f0bd2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:37:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T14:00:38.000Z", "avg_line_length": 28.0582524272, "max_line_length": 79, "alphanum_fraction": 0.6615916955, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7595895865433867}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,jl:hydrogen\n#     text_representation:\n#       extension: .jl\n#       format_name: hydrogen\n#       format_version: '1.3'\n#       jupytext_version: 1.11.2\n#   kernelspec:\n#     display_name: Julia 1.8.0-DEV\n#     language: julia\n#     name: julia-1.8\n# ---\n\n# %%\nusing GaloisFields, LinearAlgebra\nconst F5 = @GaloisField 5\nA = F5[1 2; 0 3]\n\n# %%\ndet(A)\n\n# %%\nB = F5[1 2; 3 4]\n\n# %%\ndet(B)\n\n# %%\nF5(3) |> dump\n\n# %%\nF5 |> dump\n\n# %%\nBase.abs(x::GaloisFields.PrimeField) = x.n # type-piracy!\ndet(B)\n\n# %%\nF3 = @GaloisField 3\n[det(F3.(rand(0:2, 3, 3))) for _ in 1:20]\n\n# %%\nBase.abs(x::GaloisFields.ExtensionField) = x.coeffs # type-piracy!\nBase.isless(x::GaloisFields.PrimeField, y::GaloisFields.PrimeField) = isless(x.n, y.n) # type-piracy!\nF9 = @GaloisField! 3 a^2 + 1\nC = F9[1+a 2+a; 2+a 2+a]\n\n# %%\ndet(C)\n\n# %%\n", "meta": {"hexsha": "03da4ff9c7f7b70fc7eb3984359dcda4146c70f9", "size": 865, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0010/GaloisFields.jl and LinearAlgebra.jl", "max_stars_repo_name": "genkuroki/public", "max_stars_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-06-06T00:33:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T06:56:08.000Z", "max_issues_repo_path": "0010/GaloisFields.jl and LinearAlgebra.jl", "max_issues_repo_name": "genkuroki/public", "max_issues_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0010/GaloisFields.jl and LinearAlgebra.jl", "max_forks_repo_name": "genkuroki/public", "max_forks_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-02T11:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T11:46:05.000Z", "avg_line_length": 16.0185185185, "max_line_length": 101, "alphanum_fraction": 0.5826589595, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7595895808578154}}
{"text": "#########################################################################################################################################\n############################## quadrature.jl contains basic univariate quadrature routines ##############################################\n#########################################################################################################################################\n#\n# Types:\n#       QuadRule               - object that stores n quadrature points and weights on the interval [-1,1]\n#\n# Functions:\n#       dim()                  - determine the order of the quadrature rule\n#\n#\n#########################################################################################################################################\n#\n# File part of the Julia IsoGeometric Analysis toolbox\n# R.R.Hiemstra\n# 19-04-2016\n#\n#########################################################################################################################################\n\n\n\"container for quadrature formula\"\nstruct QuadRule\n    points  :: Vector{Float64}\n    weights :: Vector{Float64}\nend\n\n\"order of the quadrature rule - number of quadrature points\"\ndim(qr::QuadRule) = length(qr.points)\n\n\"\"\"\ncompute an 'n'-point Gausian integration rule of type 'method' on the interval [-1,1]\n\n## input:\n    n       :: Int             - number of quadrature points\n    method  :: String          - choose among the following methods: \"legendre\", \"lobatto\", \"chebyshev\", \"hermite\", \"jacobi\", #                                 \"radau\". If left blank then the standard is \"legendre\"\n\n## output:\n    u       :: Vector{Float64} - quadrature points\n    w       :: Vector{Float64} - quadrature weights\n\"\"\"\nfunction QuadRule(n::Int,method=\"legendre\")\n\n    if method==\"legendre\"\n        u, w = gausslegendre(n)\n    elseif method==\"lobatto\"\n        u, w = gausslobatto(n)\n    elseif method==\"chebyshev\"\n        u, w = gausschebyshev(n)\n    elseif method==\"hermite\"\n        u, w = gausshermite(n)\n    elseif method==\"jacobi\"\n        u, w = gaussjacobi(n)\n    elseif method==\"radau\"\n        u, w = gaussradau(n)\n    else\n        error(\"Not a valid quadrature method\")\n    end\n\n    return QuadRule(u,w)\nend\n", "meta": {"hexsha": "a151619c8412452d53d1d5d90b094cbde67e8b0b", "size": 2201, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/quadrature.jl", "max_stars_repo_name": "michakraus/iga-demos", "max_stars_repo_head_hexsha": "05f636ee1de517ac5d36befbf96ff24ef6bb9273", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/quadrature.jl", "max_issues_repo_name": "michakraus/iga-demos", "max_issues_repo_head_hexsha": "05f636ee1de517ac5d36befbf96ff24ef6bb9273", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/quadrature.jl", "max_forks_repo_name": "michakraus/iga-demos", "max_forks_repo_head_hexsha": "05f636ee1de517ac5d36befbf96ff24ef6bb9273", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0819672131, "max_line_length": 214, "alphanum_fraction": 0.4402544298, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7595895786604467}}
{"text": "# Information about mathematical functions needed for expression parsing\n\n#################################################\n#\n#    Additional math functions\n#\n#################################################\n\nsqr(x::Number) = x * x\nrcp(x::Number) = one(x) / x\nrsqrt(x::Number) = one(x) / sqrt(x) \nrcbrt(x::Real) = one(x) / cbrt(x)\n\nlogit(x::Real) = log(x / (one(x) - x))\nxlogx(x::Real) = x > zero(x) ? x * log(x) : zero(x)\nxlogy(x::Real, y::Real) = x > zero(x) ? x * log(y) : zero(x)\n\nlogistic(x::Real) = one(x) / (one(x) + exp(-x))\ninvlogistic(y::Real) = -log(one(y) / y - one(y))\n\nsoftplus(x::Real) = log(one(x) + exp(x))\ninvsoftplus(x::Real) = log(exp(x) - one(x))\n\nlogsumexp{T<:Real}(x::T, y::T) = x > y ? x + log(one(T) + exp(y - x)) : y + log(one(T) + exp(x - y))\n\n@vectorize_1arg Number sqr\n@vectorize_1arg Number rcp\n@vectorize_1arg Real rsqrt\n@vectorize_1arg Real rcbrt\n\n@vectorize_1arg Real logit\n@vectorize_1arg Real logistic\n\n", "meta": {"hexsha": "8e64fe9d9ba44c98263a8f7f36b007a99f5a1824", "size": 939, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mathfuns.jl", "max_stars_repo_name": "lendle/NumericExtensions.jl", "max_stars_repo_head_hexsha": "35f0ca97e38500f50a34c6b2e35a737fef50256d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mathfuns.jl", "max_issues_repo_name": "lendle/NumericExtensions.jl", "max_issues_repo_head_hexsha": "35f0ca97e38500f50a34c6b2e35a737fef50256d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mathfuns.jl", "max_forks_repo_name": "lendle/NumericExtensions.jl", "max_forks_repo_head_hexsha": "35f0ca97e38500f50a34c6b2e35a737fef50256d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6176470588, "max_line_length": 100, "alphanum_fraction": 0.5537806177, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.759589571553483}}
{"text": "using Statistics\n\nexport bachelierFormula\n\n\"Price of a vanilla option under the Bachelier/Normal model\"\nfunction bachelierFormula(isCall::Bool, strike::T, forward::T, variance::T, discountDf::T) where {T}\n    sign = 1.0\n    if !isCall\n        sign = -1.0\n    end\n    if variance == 0\n        return Max(sign * (forward - strike), 0) * discountDf\n    end\n    sqrtvar = sqrt(variance)\n    d = sign * (forward - strike) / sqrtvar\n    if forward == strike\n        return sqrtvar / sqrt(2 * pi)\n    end\n    normal = Normal()\n    Nd = cdf(normal, d)\n    nd = pdf(normal, d)\n    return discountDf * (sign * (forward - strike) * Nd + sqrtvar * nd)\nend\n", "meta": {"hexsha": "af3d1f516ca79708d12de2cce04cd3e787ad43b4", "size": 644, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Bachelier.jl", "max_stars_repo_name": "fabienlefloch/ArbitrageFreeSABR.jl", "max_stars_repo_head_hexsha": "c2fbc3c96c6c744ae3eb6d4ca97ba63369ccc6e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-22T19:06:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T20:53:52.000Z", "max_issues_repo_path": "src/Bachelier.jl", "max_issues_repo_name": "fabienlefloch/ArbitrageFreeSABR.jl", "max_issues_repo_head_hexsha": "c2fbc3c96c6c744ae3eb6d4ca97ba63369ccc6e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-30T13:21:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-30T13:21:24.000Z", "max_forks_repo_path": "src/Bachelier.jl", "max_forks_repo_name": "fabienlefloch/ArbitrageFreeSABR.jl", "max_forks_repo_head_hexsha": "c2fbc3c96c6c744ae3eb6d4ca97ba63369ccc6e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8333333333, "max_line_length": 100, "alphanum_fraction": 0.6211180124, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9546474207360066, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.7595729622643922}}
{"text": "module Marcos\n\nimport GreyDecision.GreyNumbers: GreyNumber\nimport GreyDecision.Utility: unitize, weightize\n\nfunction marcos(decisionMat::Array{GreyNumber{T}, 2}, weights::Array{Float64,1}, \n    fns::Array{Function,1}) where {T <: Real}\n\n    row, col = size(decisionMat)\n\n    w = unitize(weights)\n\n    AAI = zeros(GreyNumber{T}, col)\n    AI  = zeros(GreyNumber{T}, col)\n\n    temp = [decisionMat; AI'; AAI']\n\n    normalizedDecisionMat = similar(temp)\n\n    @inbounds for i in 1:col\n        if fns[i] == maximum\n            AI[i] = maximum(decisionMat[:, i])\n            temp[row + 1, i] = AI[i]\n            AAI[i] = minimum(decisionMat[:, i])\n            temp[row + 2, i] = AAI[i]\n            normalizedDecisionMat[:, i] = map(x -> x / AI[i], temp[:, i])\n        elseif fns[i] == minimum\n            AI[i] = minimum(decisionMat[:, i])\n            temp[row + 1, i] = AI[i]\n            AAI[i] = maximum(decisionMat[:, i])\n            temp[row + 2, i] = AAI[i]\n            normalizedDecisionMat[:, i] = map(x -> AI[i] / x, temp[:, i])\n        end\n    end\n\n    S  = zeros(GreyNumber{T}, col)\n\n    for i in 1:(row + 2)\n        S[i] = w .* normalizedDecisionMat[i, :] |> sum\n    end\n\n    KPlus  = map(x -> x / S[row + 1], S[1:row])\n    KMinus = map(x -> x / S[row + 2], S[1:row])\n\n    fKPlus = KPlus ./ (KPlus .+ KMinus)\n    fKMinus = KMinus ./ (KPlus .+ KMinus)\n\n    scores = zeros(GreyNumber{T}, row)\n\n    for i in 1:row\n        scores[i] = (KPlus[i] + KMinus[i]) / ((GreyNumber(1.0) + (GreyNumber(1.0) - fKPlus[i]) / fKPlus[i]) + ((GreyNumber(1.0) - fKMinus[i]) / fKMinus[i]))\n    end\n\n    rankings = sortperm(scores)\n\n    bestIndex = rankings |> last\n\n    result = Dict(\n        :scores => scores, \n        :rankings => rankings,\n        :bestIndex => bestIndex\n    )\n\n    return result \nend\n\nend # end of module ", "meta": {"hexsha": "137dadbf99f1085b4e936b3a986ecb4cda0bdc7d", "size": 1808, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/marcos.jl", "max_stars_repo_name": "jbytecode/GreyDecision.jl", "max_stars_repo_head_hexsha": "1714e531af9a4ce2d1ae6bea09c21e20e694eef3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-15T09:42:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T09:42:00.000Z", "max_issues_repo_path": "src/marcos.jl", "max_issues_repo_name": "jbytecode/GreyDecision.jl", "max_issues_repo_head_hexsha": "1714e531af9a4ce2d1ae6bea09c21e20e694eef3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-09-06T12:30:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-21T17:44:37.000Z", "max_forks_repo_path": "src/marcos.jl", "max_forks_repo_name": "jbytecode/GreyDecision.jl", "max_forks_repo_head_hexsha": "1714e531af9a4ce2d1ae6bea09c21e20e694eef3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-06T21:55:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T10:50:02.000Z", "avg_line_length": 26.9850746269, "max_line_length": 156, "alphanum_fraction": 0.5403761062, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7595392967810582}}
{"text": "\n\"\"\"\n    reconstruction_matrix_meshwidth(f, domain, N)\n\nAssemble inverse discrete filtering matrix from a continuous filter `f` width constant width\n\\$h(x) = \\\\Delta x / 2\\$.\n\"\"\"\nfunction reconstruction_matrix_meshwidth(f::TopHatFilter, domain::PeriodicIntervalDomain, N)\n    x = discretize(domain, N)\n    Δx = 1 // N * (domain.right - domain.left)\n    h = f.width\n    h₀ = h(x[1])\n\n    all(h.(x) .≈ h(x[1])) || error(\"Filter width must be constant\")\n\n    if Δx .≈ 2h₀\n        # Three point stencil\n        inds = [-1, 0, 1]\n        stencil = [-1 // 24, 13 // 12, -1 // 24]\n    elseif Δx .≈ h₀\n        # Three point stencil\n        inds = [-1, 0, 1]\n        stencil = [-1 // 6, 8 // 6, -1 // 6]\n    else\n        error(\"Filter width must be equal to mesh width\")\n    end\n\n    # Five point stencil\n    # inds = [-2, -1, 0, 1, 2]\n    # stencil = [3//640, -29//480, 1067//960, -29//480, 3//640]\n\n    # Construct banded matrix\n    diags = [i => fill(s, N - abs(i)) for (i, s) ∈ zip(inds, stencil)]\n    R = spdiagm(diags...)\n\n    # Periodic extension of three point stencil\n    R[1, end] = stencil[1]\n    R[end, 1] = stencil[end]\n\n    # Periodic extension of five point stencil\n    # R[1, [end - 1, end]] = stencil[[1, 2]]\n    # R[2, end] = stencil[1]\n    # R[end - 1, 1] = stencil[end]\n    # R[end, [1, 2]] = stencil[[end-1, end]]\n\n    R\nend\n\n\nfunction reconstruction_matrix_meshwidth(f::TopHatFilter, domain::ClosedIntervalDomain, N)\n    x = discretize(domain, N)\n    Δx = 1 // N * (domain.right - domain.left)\n    h = f.width\n    h₀ = h(x[1])\n\n    all(h.(x) .≈ h(x[1])) || error(\"Filter width must be constant\")\n    Δx .≈ 2h₀ || error(\"Filter width must be equal to mesh width\")\n\n    # Three point stencil\n    inds = [-1, 0, 1]\n    stencil = [-1 // 24, 13 // 12, -1 // 24]\n\n    # Five point stencil\n    # inds = [-2, -1, 0, 1, 2]\n    # stencil = [3 // 640, -29 // 480, 1067 // 960, -29 // 480, 3 // 640]\n\n    # Construct banded matrix\n    diags = [i => fill(s, N + 1 - abs(i)) for (i, s) ∈ zip(inds, stencil)]\n    R = spdiagm(diags...)\n\n    # Boundary weights for three point stencil\n    R[1, [1, 2]] = [4 // 3, -1 // 3]\n    R[end, [end, end - 1]] = [4 // 3, -1 // 3]\n\n    # Boundary weights for five point stencil\n    # R[1, [1, 2, 3]] = [23 // 15, -41 // 60, 3 // 20]\n    # R[2, [1, 2, 3, 4]] = [-8//105, 319//280, -29//420, 1//168]\n    # R[end - 1, [end, end - 1, end - 2, end - 3]] = [-8//105, 319//280, -29//420, 1//168]\n    # R[end, [end, end - 1, end - 2]] = [23 // 15, -41 // 60, 3 // 20]\n\n    R\nend\n", "meta": {"hexsha": "a81bd81d0c75610332d0217740694aea9f46879f", "size": 2505, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrices/reconstruction_matrix_meshwidth.jl", "max_stars_repo_name": "agdestein/DiscreteFiltering.jl", "max_stars_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-23T12:51:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T12:51:11.000Z", "max_issues_repo_path": "src/matrices/reconstruction_matrix_meshwidth.jl", "max_issues_repo_name": "agdestein/DiscreteFiltering.jl", "max_issues_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrices/reconstruction_matrix_meshwidth.jl", "max_forks_repo_name": "agdestein/DiscreteFiltering.jl", "max_forks_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1807228916, "max_line_length": 92, "alphanum_fraction": 0.5273453094, "num_tokens": 941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.7595392921067995}}
{"text": "# Triangle in 2D defined by its 3 vertices.\nstruct Triangle_2D <: Face_2D\n    points::SVector{3, Point_2D}\nend\n\n# Constructors\n# -------------------------------------------------------------------------------------------------\nTriangle_2D(p₁::Point_2D, p₂::Point_2D, p₃::Point_2D) = Triangle_2D(SVector(p₁, p₂, p₃))\n\n# Methods\n# -------------------------------------------------------------------------------------------------\n# Interpolation\nfunction (tri::Triangle_2D)(r::Real, s::Real)\n    # See The Visualization Toolkit: An Object-Oriented Approach to 3D Graphics, 4th Edition\n    # Chapter 8, Advanced Data Representation, in the interpolation functions section\n    rₜ = Float64(r); sₜ = Float64(s)\n    return (1 - rₜ - sₜ)*tri[1] + rₜ*tri[2] + sₜ*tri[3]\nend\n\nfunction area(tri::Triangle_2D)\n    # A = bh/2\n    # Let u⃗ = (v₂ - v₁), v⃗ = (v₃ - v₁)\n    # b = |u⃗|\n    # h = |sin(θ) v⃗|, where θ is the angle between u⃗ and v⃗\n    # u⃗ × v⃗ = |u⃗||v⃗| sin(θ), hence\n    # A = |u⃗ × v⃗|/2 = bh/2\n    u⃗ = tri[2] - tri[1]\n    v⃗ = tri[3] - tri[1]\n    # 2D cross product returns a scalar\n    return abs(u⃗ × v⃗)/2\nend\n\ncentroid(tri::Triangle_2D) = tri(0.3333333333333333, 0.3333333333333333)\n\nfunction in(p::Point_2D, tri::Triangle_2D)\n    # If the point is to the left of every edge\n    #  3<-----2\n    #  |     ^\n    #  | p  /\n    #  |   /\n    #  |  /\n    #  v /\n    #  1\n    return isleft(p, LineSegment_2D(tri[1], tri[2])) &&\n           isleft(p, LineSegment_2D(tri[2], tri[3])) &&\n           isleft(p, LineSegment_2D(tri[3], tri[1]))\nend\n\nfunction intersect(l::LineSegment_2D, tri::Triangle_2D)\n    # Create the 3 line segments that make up the triangle and intersect each one\n    edges = SVector(LineSegment_2D(tri[1], tri[2]),\n                    LineSegment_2D(tri[2], tri[3]),\n                    LineSegment_2D(tri[3], tri[1]))\n    ipoints = MVector(Point_2D(), Point_2D(), Point_2D())\n    n_ipoints = 0x00000000\n    # We need to account for 3 points returned due to vertex intersection\n    for k ∈ 1:3\n        npoints, point = l ∩ edges[k]\n        if npoints === 0x00000001\n            n_ipoints += 0x00000001\n            ipoints[n_ipoints] = point\n        end\n    end\n    return n_ipoints, SVector(ipoints)\nend\n\n# Plot\n# -------------------------------------------------------------------------------------------------\nif enable_visualization\n    function convert_arguments(LS::Type{<:LineSegments}, tri::Triangle_2D)\n        l₁ = LineSegment_2D(tri[1], tri[2])\n        l₂ = LineSegment_2D(tri[2], tri[3])\n        l₃ = LineSegment_2D(tri[3], tri[1])\n        lines = [l₁, l₂, l₃]\n        return convert_arguments(LS, lines)\n    end\n\n    function convert_arguments(LS::Type{<:LineSegments}, T::Vector{Triangle_2D})\n        point_sets = [convert_arguments(LS, tri) for tri ∈  T]\n        return convert_arguments(LS, reduce(vcat, [pset[1] for pset ∈ point_sets]))\n    end\n\n    function convert_arguments(M::Type{<:Mesh}, tri::Triangle_2D)\n        points = [tri[i] for i = 1:3]\n        face = [1 2 3]\n        return convert_arguments(M, points, face)\n    end\n\n    function convert_arguments(M::Type{<:Mesh}, T::Vector{Triangle_2D})\n        points = reduce(vcat, [[tri[i] for i = 1:3] for tri ∈  T])\n        faces = zeros(Int64, length(T), 3)\n        k = 1\n        for i in 1:length(T), j = 1:3\n            faces[i, j] = k\n            k += 1\n        end\n        return convert_arguments(M, points, faces)\n    end\nend\n", "meta": {"hexsha": "7d2c34e7692dff6eca81b13267cf1f2b6b78361d", "size": 3424, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/primitives/Triangle_2D.jl", "max_stars_repo_name": "KyleVaughn/MOCNeutronTransport", "max_stars_repo_head_hexsha": "6de0f5987c2b37c3c3039d073b63c223ff6cd5f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-11-10T19:36:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T15:34:40.000Z", "max_issues_repo_path": "src/primitives/Triangle_2D.jl", "max_issues_repo_name": "KyleVaughn/MOCNeutronTransport", "max_issues_repo_head_hexsha": "6de0f5987c2b37c3c3039d073b63c223ff6cd5f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2022-01-20T03:03:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T18:29:33.000Z", "max_forks_repo_path": "src/primitives/Triangle_2D.jl", "max_forks_repo_name": "KyleVaughn/MOCNeutronTransport", "max_forks_repo_head_hexsha": "6de0f5987c2b37c3c3039d073b63c223ff6cd5f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.24, "max_line_length": 99, "alphanum_fraction": 0.5417640187, "num_tokens": 1135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7595392899888286}}
{"text": "module ErrorFree\n\nimport Base:fma\n\nexport eftRecip, eftSquare, eftCube,\n       eftSqrt,  eftRecipSqrt, # see comment for eftSqrt\n       eftSum2,  eftSum2inOrder, eftDiff2, eftDiff2inOrder,\n       eftProd2, eftDiv2,\n       eftSum3,  eftSum3as2, eftSum3inOrder, eftSum3inOrderAs2,\n       eftProd3, eftProd3as2,\n       eftFMA,   eftFMS\n\n\n#>   one operand error free transformations\n\n@inline function eftSquare(a::Float64)\n    x = a * a\n    y = fma(a, a, -x)\n    x,y\nend\n\nfunction eftCube(a::Float64)\n    p = a*a; e = fma(a, a, -p)\n    x = p*a; p = fma(p, a, -x)\n    y = e*a\n    x,y\nend\n\n@inline function eftRecip(a::Float64)\n     x = one(Float64)/a\n     y = -(fma(x,a,-1.0)/a)\n     x,y\nend\n\n#=\n   While not strictly an error-free transformation it is quite reliable and recommended for use.\n   Augmented precision square roots, 2-D norms and discussion on correctly reounding sqrt(x^2 + y^2)\n   by Nicolas Brisebarre, Mioara Joldes, Erik Martin-Dorel, Hean-Michel Muller, Peter Kornerup\n=#\n@inline function eftSqrt(a::Float64)\n     x = sqrt(a)\n     t = fma(x,-x,a)\n     y = t / (x*2.0)\n     x,y\nend\n\n@inline function eftRecipSqrt(a::Float64)\n     r = 1.0/a\n     x = sqrt(r)\n     t = fma(x,-x,r)\n     y = t / (x*2.0)\n     x,y\nend\n\n\n#>   two operand error free transformations\n\n\"\"\"\n (a,b) ↦ (x,y)\\\\\nx⊕y ≖ a⊕b and x⊕y≖x\n\"\"\"\n@inline function eftSum2{T<:Float64}(a::T, b::T)\n  x = a + b\n  t = x - a\n  y = (a - (x - t)) + (b - t)\n  x,y\nend\n\n\"\"\"\n (a,b) ↦ (x,y)\\\\\nx⊕y ≖ a⊕b and x⊕y≖x\\\\\n *presumes* |a| ≥ |b|\n\"\"\"\n@inline function eftSum2inOrder{T<:Float64}(a::T, b::T)\n  x = a + b\n  y = b - (x - a)\n  x,y\nend\n\n\n\"\"\"\n (a,b) ↦ (x,y)\\\\\nx⊕y ≖ a⊝b and x⊕y≖x\n\"\"\"\n@inline function eftDiff2{T<:Float64}(a::T, b::T)\n  x = a - b\n  t = x - a\n  y = (a - (x - t)) - (b + t)\n  x,y\nend\n\n\"\"\"\n (a,b) ↦ (x,y)\\\\\nx⊕y ≖ a⊝b and x⊕y≖x\\\\\n*presumes* |a| ≥ |b|\n\"\"\"\n@inline function eftDiff2inOrder{T<:Float64}(a::T, b::T)\n  x = a - b\n  y = (a - x) - b\n  x,y\nend\n\n@inline function eftProd2{T<:Float64}(a::T, b::T)\n    x = a * b\n    y = fma(a, b, -x)\n    x,y\nend\n\n@inline function eftDiv2{T<:Float64}(a::T,b::T)\n     x = a/b\n     y = -(fma(x,b,-a)/b)\n     x,y\nend\n\n#>   three operand error free transformations\n\nfunction eftSum3{T<:Float64}(a::T,b::T,c::T)\n    s,t = eftSum2(b, c)\n    x,u = eftSum2(a, s)\n    y,z = eftSum2(u, t)\n    x,y = eftSum2inOrder(x, y)\n    x,y,z\nend\n\nfunction eftSum3inOrder{T<:Float64}(a::T,b::T,c::T)\n    s,t = eftSum2inOrder(b, c)\n    x,u = eftSum2inOrder(a, s)\n    y,z = eftSum2inOrder(u, t)\n    x,y = eftSum2inOrder(x, y)\n    x,y,z\nend\n\n@inline function eftSum3as2{T<:Float64}(a::T,b::T,c::T)\n    s,t = eftSum2(b, c)\n    x,u = eftSum2(a, s)\n    y = u+t\n    x,y = eftSum2inOrder(x, y)\n    x,y\nend\n\n@inline function eftSum3inOrderAs2{T<:Float64}(a::T,b::T,c::T)\n    s,t = eftSum2inOrder(b, c)\n    x,u = eftSum2inOrder(a, s)\n    y = u+t\n    x,y = eftSum2inOrder(x, y)\n    x,y\nend\n\nfunction eftProd3{T<:Float64}(a::T, b::T, c::T)\n    p,e = eftProd2(a,b)\n    x,p = eftProd2(p,c)\n    y,z = eftProd2(e,c)\n    x,y,z\nend\n\n@inline function eftProd3as2{T<:Float64}(a::T, b::T, c::T)\n    p,e = eftProd2(a,b)\n    x,p = eftProd2(p,c)\n    y = e*c\n    x,y\nend\n\n\nend # module ErrorFree\n", "meta": {"hexsha": "48adcf8dab4bdbece283a324250dacf13c673c41", "size": 3158, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/jas/ErrorFree.jl/src/ErrorFree.jl", "max_stars_repo_name": "J-Sarnoff/InterVal.jl", "max_stars_repo_head_hexsha": "320e6980b596fc89f50b460669481ea0d80645d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/jas/ErrorFree.jl/src/ErrorFree.jl", "max_issues_repo_name": "J-Sarnoff/InterVal.jl", "max_issues_repo_head_hexsha": "320e6980b596fc89f50b460669481ea0d80645d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/jas/ErrorFree.jl/src/ErrorFree.jl", "max_forks_repo_name": "J-Sarnoff/InterVal.jl", "max_forks_repo_head_hexsha": "320e6980b596fc89f50b460669481ea0d80645d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1393939394, "max_line_length": 100, "alphanum_fraction": 0.5601646612, "num_tokens": 1399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7595392878708578}}
{"text": "export SVD\n\n\"\"\"\n    SVD(\n        data::DataAccessor,\n        k::Int\n    )\n\nRecommendation based on SVD of a user-item matrix ``R \\\\in \\\\mathbb{R}^{|\\\\mathcal{U}| \\\\times |\\\\mathcal{I}|}``, which was originally studied by [Sarwar et al.](http://files.grouplens.org/papers/webKDD00.pdf) Rank ``k`` is configured by `k`.\n\nIn a context of recommendation, ``U_k \\\\in \\\\mathbb{R}^{|\\\\mathcal{U}| \\\\times k}``, ``V \\\\in \\\\mathbb{R}^{|\\\\mathcal{I}| \\\\times k}`` and ``\\\\Sigma \\\\in \\\\mathbb{R}^{k \\\\times k}`` are respectively seen as ``k`` user/item feature vectors and corresponding weights. The idea of low-rank approximation that discards lower singular values intuitively works as *compression* or *denoising* of the original matrix; that is, each element in a rank-``k`` matrix ``A_k`` holds the best *compressed* (or *denoised*) value of the original element in ``A``. Thus, ``R_k = \\\\mathrm{SVD}_k(R)``, the best rank-``k`` approximation of ``R``, captures as much as possible of underlying users' preferences. Once ``R`` is decomposed into ``U, \\\\Sigma`` and ``V``, a ``(u, i)`` element of ``R_k`` calculated by ``\\\\sum^k_{j=1} \\\\sigma_j u_{u, j} v_{i, j}`` could be a prediction for the user-item pair.\n\"\"\"\nstruct SVD <: Recommender\n    data::DataAccessor\n    k::Int\n    U::AbstractMatrix\n    S::AbstractVector\n    Vt::AbstractMatrix\n\n    function SVD(data::DataAccessor, k::Int)\n        n_user, n_item = size(data.R)\n        U = matrix(n_user, k)\n        S = vector(k)\n        Vt = matrix(k, n_item)\n        new(data, k, U, S, Vt)\n    end\nend\n\nSVD(data::DataAccessor) = SVD(data, 20)\n\nisbuilt(recommender::SVD) = isfilled(recommender.U)\n\nfunction build!(recommender::SVD)\n    # NaNs are filled by zeros for now\n    R = copy(recommender.data.R)\n    R[isnan.(R)] .= 0\n\n    res = svd(R)\n    recommender.U[:] = res.U[:, 1:recommender.k]\n    recommender.S[:] = res.S[1:recommender.k]\n    recommender.Vt[:] = res.Vt[1:recommender.k, :]\nend\n\nfunction predict(recommender::SVD, u::Int, i::Int)\n    check_build_status(recommender)\n    dot(recommender.U[u, :] .* recommender.S, recommender.Vt[:, i])\nend\n", "meta": {"hexsha": "31cb82375b49aab89c28f80389a47ecad65e34b2", "size": 2096, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/model/svd.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Recommendation.jl-d27d45ae-66f1-5d53-80d2-11744f5c9556", "max_stars_repo_head_hexsha": "799cb093bc7c72e3855d381c0f011076d8cdd6a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/model/svd.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Recommendation.jl-d27d45ae-66f1-5d53-80d2-11744f5c9556", "max_issues_repo_head_hexsha": "799cb093bc7c72e3855d381c0f011076d8cdd6a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/model/svd.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Recommendation.jl-d27d45ae-66f1-5d53-80d2-11744f5c9556", "max_forks_repo_head_hexsha": "799cb093bc7c72e3855d381c0f011076d8cdd6a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6666666667, "max_line_length": 884, "alphanum_fraction": 0.643129771, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7595392878708578}}
{"text": "#NOTE: LogNormal_Models reuse Normal_Records\n\nstruct LogNormal_Model <: GMC_NS_Model\n    trajectory::Integer #id integer assigned at construction\n    i::Integer #id of parent model, if any\n\n    θ::Vector{Float64} #model's parameter Vector\n    log_Li::Float64 #model's likelihood, calculated by constructor\n\n    pos::Vector{Float64}\n    v::Vector{Float64} #model's velocity in parameter space\nend\n\nfunction construct_lognormal_model(trajectory::Integer, i::Integer, θ::Vector{Float64}, pos::Vector{Float64}, v::Vector{Float64}, obs::Vector{Float64}; v_init=false)\n    μ,λ=θ\n    lμ=log(μ^2/sqrt(μ^2 + inv(λ)))\n    lσ=sqrt(log(1+(inv(λ)/μ^2)))\n    mod_lnormal=LogNormal(lμ,lσ)\n    log_lh=lps(logpdf.(mod_lnormal, obs))\n    v_init && (v=rand(MvNormal(length(θ),1.)))\n\n    LogNormal_Model(trajectory, i, θ, log_lh, pos, v)\nend\n\nfunction Base.show(io::IO, m::LogNormal_Model; xsteps=100)\n    μ,λ=m.θ\n    lμ=log(μ^2/sqrt(μ^2 + inv(λ)))\n    lσ=sqrt(log(1+(inv(λ)/μ^2)))\n    n=LogNormal(lμ,lσ)\n    X=[quantile(n,.025):(quantile(n,.975)-quantile(n,.025))/xsteps:quantile(n,.975)...]\n    y=pdf.(n,X)\n\n    show(io, lineplot(X,y,xlabel=\"X\",ylabel=\"p\",title=title=\"LogNormal Model $(m.trajectory).$(m.i), log_Li $(m.log_Li)\"))\n    println()\n    println(\"θ: $(m.θ)\")\n    println(\"v: $(m.v)\")\nend", "meta": {"hexsha": "a862321f828b241b75e1bcc2d4b01b89bfa5a214", "size": 1280, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/model/normal/LogNormal_Model.jl", "max_stars_repo_name": "mmattocks/GMC_NS", "max_stars_repo_head_hexsha": "0849facc0e2695b6f7dbce2ab170aeb4762fa919", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/model/normal/LogNormal_Model.jl", "max_issues_repo_name": "mmattocks/GMC_NS", "max_issues_repo_head_hexsha": "0849facc0e2695b6f7dbce2ab170aeb4762fa919", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/model/normal/LogNormal_Model.jl", "max_forks_repo_name": "mmattocks/GMC_NS", "max_forks_repo_head_hexsha": "0849facc0e2695b6f7dbce2ab170aeb4762fa919", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5945945946, "max_line_length": 165, "alphanum_fraction": 0.6640625, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.759539285752887}}
{"text": "\nimport Base: ∘\n\nabstract type AbstractMobiusTransformation{T <: Number} <: Function end\n\n\"\"\"\n    MobiusTransformation(a,b,c,d)\n\nMöbius transformation, a conformal automorphism in the Riemann sphere\n\\$z \\\\mapsto \\\\frac{az+b}{cz+d}\\$\nwith \\$ad-bc\\\\neq 0\\$.\n\"\"\"\nstruct MobiusTransformation{T} <: AbstractMobiusTransformation{T}\n  a::T\n  b::T\n  c::T\n  d::T\n\n  function MobiusTransformation{T}(a0::T, b0::T, c0::T, d0::T) where T <: Number\n    #@assert a0 * d0 - b0 * c0 != 0 \"Invalid parameters for Möbius transformation.\"\n    new(a0,b0,c0,d0)\n  end\n\nend\n\nMobiusTransformation(a0::T, b0::T, c0::T, d0::T) where {T <: Number} =\nMobiusTransformation{T}(a0,b0,c0,d0)\n\nMobiusTransformation(a0::Number, b0::Number, c0::Number, d0::Number) =\nMobiusTransformation(promote(a0,b0,c0,d0)...)\n\n\n\"\"\"\n    LinearTransformation(a)\n\nLinear transformation (homotecy and rotation) in the Riemann sphere\n\\$z \\\\mapsto a z\\$.\n\"\"\"\nstruct LinearTransformation{T} <: AbstractMobiusTransformation{T}\n  a::T\n\n  function LinearTransformation{T}(a0::T) where T <: Number\n    #@assert a0 == 0 \"Invalid parameters for Möbius transformation.\"\n    new(a0)\n  end\nend\n\nLinearTransformation(a0::T) where {T <: Number} = LinearTransformation{T}(a0)\n\nMobiusTransformation(a0::Number) = LinearTransformation(a0)\n\n\n\"\"\"\n    Translation(b)\n\nTranslation in the Riemann sphere\n\\$z \\\\mapsto z + b\\$.\n\"\"\"\nstruct Translation{T} <: AbstractMobiusTransformation{T}\n  b::T\n\n  function Translation{T}(b0::T) where T <:Number\n    new(b0)\n  end\nend\n\nTranslation(b0::T) where {T <: Number} = Translation{T}(b0)\n\n\n\"\"\"\n    AffineTransformation(a,b)\n\nAffine transformation in the Riemann sphere\n\\$z \\\\mapsto a z + b\\$.\n\"\"\"\nstruct AffineTransformation{T} <: AbstractMobiusTransformation{T}\n  a::T\n  b::T\n\n  function AffineTransformation{T}(a0::T, b0::T) where T <:Number\n    new(a0,b0)\n  end\nend\n\nAffineTransformation(a0::T, b0::T) where {T <: Number} = AffineTransformation{T}(a0,b0)\n\nAffineTransformation(a0::Number, b0::Number) = AffineTransformation(promote(a0,b0)...)\n\nMobiusTransformation(a0::Number, b0::Number) = AffineTransformation(promote(a0,b0)...)\n\n\n\"\"\"\n    InversionReflection(b)\n\nInversion reflection in the Riemann sphere\n\\$z \\\\mapsto \\\\frac{b}{z}\\$.\n\"\"\"\nstruct InversionReflection{T} <: AbstractMobiusTransformation{T}\n  b::T\n\n  function InversionReflection{T}(b0::T) where T <:Number\n    new(b0)\n  end\nend\n\nInversionReflection(b0::T) where {T <: Number} = InversionReflection{T}(b0)\n\n\nBase.show(io::IO, f::MobiusTransformation{T}) where T =\n  print(io, \"MöbiusTransformation{$T}: z -> ((\", f.a, \")z + (\", f.b, \")) / ((\", f.c, \")z + (\", f.d, \"))\")\n\nBase.show(io::IO, f::LinearTransformation{T}) where T  =\n  print(io, \"LinearTransformation{$T}: z -> (\", f.a, \")z\")\n\nBase.show(io::IO, f::Translation{T}) where T  =\n  print(io, \"Translation{$T}: z -> z + (\", f.b, \")\")\n\nBase.show(io::IO, f::AffineTransformation{T}) where T  =\n  print(io, \"AffineTransformation{$T}: z -> (\", f.a, \")z + (\", f.b, \")\")\n\nBase.show(io::IO, f::InversionReflection{T}) where T  =\n  print(io, \"InversionReflection{$T}: z -> (\", f.b, \") / z\")\n\n\nfunction (f::MobiusTransformation)(z::Number)\n  # ToDo! Create a method to eval infinity case\n  if isinf(z)\n    return f.a / f.c\n  end\n\n  (f.a * z + f.b) / (f.c * z + f.d)\nend\n\nfunction (f::LinearTransformation)(z::Number)\n  f.a * z\nend\n\nfunction (f::Translation)(z::Number)\n  z + f.b\nend\n\nfunction (f::AffineTransformation)(z::Number)\n  f.a * z + f.b\nend\n\nfunction (f::InversionReflection)(z::Number)\n  # ToDo! Create a method to eval infinity case\n  if isinf(z)\n    return 0\n  end\n\n  f.b / z\nend\n\n\n\"\"\"\nMöbius transformation parameters accesors.\n\"\"\"\na(f::MobiusTransformation) = f.a\nb(f::MobiusTransformation) = f.b\nc(f::MobiusTransformation) = f.c\nd(f::MobiusTransformation) = f.d\n\na(f::LinearTransformation) = f.a\nb(f::LinearTransformation) = 0\nc(f::LinearTransformation) = 0\nd(f::LinearTransformation) = 1\n\na(f::Translation) = 1\nb(f::Translation) = f.b\nc(f::Translation) = 0\nd(f::Translation) = 1\n\na(f::AffineTransformation) = f.a\nb(f::AffineTransformation) = f.b\nc(f::AffineTransformation) = 0\nd(f::AffineTransformation) = 1\n\na(f::InversionReflection) = 0\nb(f::InversionReflection) = f.b\nc(f::InversionReflection) = 1\nd(f::InversionReflection) = 0\n\n\n\"\"\"\nTrace\n\n\\$tr(T)=a+d\\$\n\"\"\"\ntr(f::AbstractMobiusTransformation) = a(f) + d(f)\n\ntr(f::MobiusTransformation) = f.a + f.d\n\ntr(f::LinearTransformation) = f.a + 1\n\ntr(f::Translation) = 1\n\ntr(f::AffineTransformation) = f.a + 1\n\ntr(f::InversionReflection) = 0\n\n\n\"\"\"\nDeterminant.\n\n\\$det(T)=ad-bc\\$\n\"\"\"\ndet(f::AbstractMobiusTransformation) = a(f)*d(f) - b(f)*c(f)\n\ndet(f::MobiusTransformation) = f.a * f.d - f.b * f.c\n\ndet(f::LinearTransformation) = f.a\n\ndet(f::Translation) = 1\n\ndet(f::AffineTransformation) = f.a\n\ndet(f::InversionReflection) = -f.b\n\n\n#function normalize(f::MobiusTransformation)\n#  dt = det(f)\n#  MobiusTransformation(f.a/dt, f.b/det, f.c/det, f.d/det)\n#end\n\n#function normalize(f::LinearTransformation)\n#  f\n#end\n\n\n\"\"\"\nInverse.\n\n\\$T^{-1}(z)=\\\\frac{d z - b}{-c z + a}\\$\n\"\"\"\ninverse(f::MobiusTransformation) = MobiusTransformation(f.d, -f.b, -f.c, f.a)\n\ninverse(f::LinearTransformation) = LinearTransformation(1.0 / f.a)\n\ninverse(f::Translation) = Translation(-f.b)\n\ninverse(f::AffineTransformation) = AffineTransformation(1.0 / f.a, -f.b / f.a)\n\ninverse(f::InversionReflection) = InversionReflection(f.b)\n\n\n\"\"\"\nDerivative.\n\n\\$T'(z)=\\\\frac{ad-bc}{(c z + d)^2}\\$\n\"\"\"\nfunction derivative(f::MobiusTransformation)\n  function der(z::Number)\n    (f.a * f.d - f.b * f.c) / ((f.c * z + f.d)^2)\n  end\nend\n\nfunction derivative(f::LinearTransformation)\n  function der(z::Number)\n    f.a\n  end\nend\n\nfunction derivative(f::Translation)\n  function der(z::Number)\n    1\n  end\nend\n\nfunction derivative(f::AffineTransformation)\n  function der(z::Number)\n    f.a\n  end\nend\n\nfunction derivative(f::InversionReflection)\n  function der(z::Number)\n    -f.b / (z^2)\n  end\nend\n\n\n\"\"\"\n    fixedpoints(f)\n\nReturns the fixed points of a Möbius transformation. Always returns two points,\neven in the parabolic case returns the one fixed point duplicated.\n\"\"\"\nfunction fixedpoints(f::MobiusTransformation{T}) where T <: Real\n  if f.c == 0\n    return f.b / (f.d - f.a), Inf\n  end\n  discr = (f.a + f.d)^2 - 4 * (f.a * f.d - f.b * f.c)\n  rd = discr < 0 ? sqrt(complex(discr)) : sqrt(discr)\n  (f.a - f.d + rd)/(2*f.c), (f.a - f.d - rd)/(2*f.c)\nend\n\nfunction fixedpoints(f::MobiusTransformation)\n  if f.c == 0\n    return f.b / (f.d - f.a), Inf\n  end\n  rd = sqrt((f.a + f.d)^2 - 4 * (f.a * f.d - f.b * f.c))\n  (f.a - f.d + rd)/(2*f.c), (f.a - f.d - rd)/(2*f.c)\nend\n\nfunction fixedpoints(f::LinearTransformation)\n  0, Inf\nend\n\nfunction fixedpoints(f::Translation)\n  Inf, Inf\nend\n\nfunction fixedpoints(f::AffineTransformation)\n  if f.a == 1\n    return Inf, Inf\n  end\n  f.b / (1 - f.a), Inf\nend\n\nfunction fixedpoints(f::InversionReflection{T}) where T <: Real\n  rd = f.b < 0 ? sqrt(complex(f.b)) : sqrt(f.b)\n  rd, -rd\nend\n\nfunction fixedpoints(f::InversionReflection)\n  rd = sqrt(f.b)\n  rd, -rd\nend\n\n\n\"\"\"\nKind of Möbius transformation:\n- `:parabolic` if \\$t^2=4\\$.\n- `:elliptic` if \\$t^2\\\\in [0,4)\\$.\n- `:hyperbolic` if \\$t^2\\\\in (-\\\\infty,0)\\\\cup (4,\\\\infty)\\$.\n- `:loxodromic` otherwise.\nwhere \\$t=tr(T)/det(T)\\$.\n\"\"\"\nfunction kind(f::AbstractMobiusTransformation)\n  t = tr(f) / det(f)\n  t2 = t^2\n  if imag(t2) ≈ 0\n    t2 = real(t2)\n    if t2 == 4\n      return :parabolic\n    end\n\n    if 0 <= t2 < 4\n      return :elliptic\n    end\n\n    return :hyperbolic\n  end\n\n  :loxodromic\nend\n\nkind(f::Translation) = :parabolic\n\n\n\"\"\"\nCompose two Möbius transformations.\n\"\"\"\ncompose(f::AbstractMobiusTransformation, g::AbstractMobiusTransformation) =\n  MobiusTransformation(a(f)*a(g)+b(f)*c(g), a(f)*b(g)+b(f)*d(g),\n    c(f)*a(g)+d(f)*c(g), c(f)*b(g)+c(f)*d(g))\n\ncompose(f::MobiusTransformation, g::MobiusTransformation) =\n  MobiusTransformation(f.a*g.a+f.b*g.c, f.a*g.b+f.b*g.d,\n    f.c*g.a+f.d*g.c, f.c*g.b+f.d*g.d)\n\ncompose(f::LinearTransformation, g::LinearTransformation) =\n  LinearTransformation(f.a * g.a)\n\ncompose(f::Translation, g::Translation) =\n  Translation(f.b + g.b)\n\ncompose(f::AffineTransformation, g::AffineTransformation) =\n  AffineTransformation(f.a * g.a, f.a * g.b + f.b)\n\ncompose(f::InversionReflection, g::InversionReflection) =\n  InversionReflection(f.b / g.b)\n\n\n# LinearTransformation vs ...\ncompose(f::LinearTransformation, g::MobiusTransformation) =\n  MobiusTransformation(f.a*g.a, f.a*g.b, g.c, g.d)\n\ncompose(f::MobiusTransformation, g::LinearTransformation) =\n  MobiusTransformation(f.a*g.a, f.b, f.c*g.a, f.d)\n\n\ncompose(f::LinearTransformation, g::Translation) =\n  AffineTransformation(f.a, f.a * g.b)\n\ncompose(f::Translation, g::LinearTransformation) =\n  AffineTransformation(g.a, f.b)\n\n\ncompose(f::LinearTransformation, g::AffineTransformation) =\n  AffineTransformation(f.a * g.a, f.a * g.b)\n\ncompose(f::AffineTransformation, g::LinearTransformation) =\n  AffineTransformation(f.a * g.a, f.b)\n\n\n# Translation vs ...\ncompose(f::Translation, g::MobiusTransformation) =\n  MobiusTransformation(g.a+f.b*g.c, g.b+f.b*g.d, g.c, g.d)\n\ncompose(f::MobiusTransformation, g::Translation) =\n  MobiusTransformation(f.a, f.a*g.b+f.b, f.c, f.c*g.b+f.d)\n\n\ncompose(f::Translation, g::AffineTransformation) =\n  AffineTransformation(g.a, g.b+f.b)\n\ncompose(f::AffineTransformation, g::Translation) =\n  AffineTransformation(f.a, f.a*g.b+f.b)\n\n\n# AffineTransformation vs ...\ncompose(f::AffineTransformation, g::MobiusTransformation) =\n  MobiusTransformation(f.a*g.a+f.b*g.c, f.a*g.b+f.b*g.d, g.c, g.d)\n\ncompose(f::MobiusTransformation, g::AffineTransformation) =\n  MobiusTransformation(f.a*g.a, f.a*g.b+f.b, f.c*g.a, f.c*g.b+f.d)\n\n\n# InversionReflection vs ...\n# result in a MobiusTransformation, fall back to AbstractMobiusTransformation implementation\n\n\n\"\"\"\nBinary operator to compose two Möbius transformations.\n\"\"\"\n∘(f::AbstractMobiusTransformation, g::AbstractMobiusTransformation) = compose(f,g)\n\n\n\"\"\"\n    maptozerooneinf(z1,z2,z3)\n\nCreate the Möbius transformation such that \\$z_1 \\\\mapsto 0\\$,\n\\$z_2 \\\\mapsto 1\\$ and \\$z_3 \\\\mapsto \\\\infty\\$.\n\"\"\"\nmaptozerooneinf(z1::Number, z2::Number, z3::Number) =\n  MobiusTransformation(z2-z3, z1*(z3-z2), z2-z1, z3*(z1-z2))\n\n\"\"\"\n    mapfromzerooneinf(z1,z2,z3)\n\nCreate the Möbius transformation such that \\$0 \\\\mapsto z_1\\$,\n  \\$1 \\\\mapsto z_2\\$ and \\$\\\\infty \\\\mapsto z_3\\$.\n\"\"\"\nmapfromzerooneinf(z1::Number, z2::Number, z3::Number) =\n  MobiusTransformation(z3*(z1-z2), z1*(z2-z3), z1-z2, z2-z3)\n\n\"\"\"\nCreate the Möbius transformation such that \\$z_1 \\\\mapsto w_1\\$,\n  \\$z_2 \\\\mapsto w_2\\$ and \\$z_3 \\\\mapsto w_3\\$.\n\"\"\"\nfunction MobiusTransformation(z1::Number, z2::Number, z3::Number,\n  w1::Number, w2::Number, w3::Number)\n  f = maptozerooneinf(z1,z2,z3)\n  g = mapfromzerooneinf(w1,w2,w3)\n  g∘f\nend\n\n\n\n#=\nfunction (f::MobiusTransformation)(c::CLine)\n  CLine(\n   abs2(f.d) * c.A - 2 * real( conj(f.c) * f.d * c.B ) + abs2(f.c) * c.C,\n   conj(f.a) * (f.d * c.B - f.c * c.C) - conj(f.b) * (f.c * conj(c.B) - f.d * c.A),\n   abs2(f.b) * c.A - 2 * real( conj(f.a) * f.b * c.B ) + abs2(f.a) * c.C\n  )\nend\n\n# ToDO: Methods!!!\n=#\n\n\"\"\"\nGiven a Möbius transformation \\$f(z)=\\\\frac{az+b}{cz+d}\\$ and a circle\n\\$C: |center-z|=radius\\$, the circle  \\$f(C)\\$ has center\n\n\\$ w = f(center - \\\\frac{radius^2}{\\\\overline{\\\\frac{d}{c}+center}})\n\nand radius\n\n\\$|w - f(center+radius)|\\$.\n\"\"\"\nfunction (f::MobiusTransformation)(c::Circle)\n  if f.c ≈ 0.0\n    return Circle( f(c.center), abs(f.a/f.d)*c.radius )\n  elseif abs(c.center + f.d/f.c) ≈ c.radius\n    z = c.center + f.d/f.c\n    w1 = f(c.center + z)\n    w2 = f(c.center + im*z)\n    return Line(w1, angle(w1-w2))\n  end\n\n  # \"Grandma's recipe\" from \"Indra's Pearls\" to calculate image of a circle\n  z = c.center - c.radius*c.radius/conj(f.d/f.c + c.center)\n  Circle(f(z), abs(z - f(c.center + c.radius)))\nend\n\nfunction (f::LinearTransformation)(c::Circle)\n  Circle( f(c.center), abs(f.a)*c.radius )\nend\n\nfunction (f::Translation)(c::Circle)\n  Circle( f(c.center), c.radius )\nend\n\nfunction (f::AffineTransformation)(c::Circle)\n  Circle( f(c.center), abs(f.a)*c.radius )\nend\n\nfunction (f::InversionReflection)(c::Circle)\n  if abs(c.center) ≈ c.radius\n    w1 = f(2*c.center)\n    w2 = f(c.center + im*c.center)\n    return Line(w1, angle(w1-w2))\n  end\n\n  # \"Grandma's recipe\" from \"Indra's Pearls\" to calculate image of a circle\n  z = c.center - c.radius*c.radius/conj(c.center)\n  Circle(f(z), abs(z - f(c.center + c.radius)))\nend\n\n\nfunction (f::MobiusTransformation)(c::Arc)\n  if f.c ≈ 0.0\n    return Arc( f(c.center), f(c.p1), f(c.p2) )\n  elseif abs(c.center + f.d/f.c) ≈ radius(c)\n    #ToDo!: Case 2 rays!\n    return LineSegment(f(c.p1), f(c.p2))\n  end\n\n  # \"Grandma's recipe\" from \"Indra's Pearls\" to calculate image of a circle\n  z = c.center - radius2(c)/conj(f.d/f.c + c.center)\n  Arc(f(z), f(c.p1), f(c.p2))\nend\n\nfunction (f::LinearTransformation)(c::Arc)\n  Arc(f(c.center), f(c.p1), f(c.p2))\nend\n\nfunction (f::Translation)(c::Arc)\n  Arc(f(c.center), f(c.p1), f(c.p2))\nend\n\nfunction (f::AffineTransformation)(c::Arc)\n  Arc(f(c.center), f(c.p1), f(c.p2))\nend\n\nfunction (f::InversionReflection)(c::Arc)\n  if abs(c.center) ≈ c.radius\n    #ToDo!: Case 2 rays!\n    return LineSegment(f(c.p1), f(c.p2))\n  end\n\n  # \"Grandma's recipe\" from \"Indra's Pearls\" to calculate image of a circle\n  z = c.center - radius2(c)/conj(c.center)\n  Arc(f(z), f(c.p1), f(c.p2))\nend\n\n\nfunction (f::MobiusTransformation)(l::Line)\n  if f.c ≈ 0.0\n    w1 = f(l.base)\n    return Line( w1, angle(w1-f(l.base+exp(l.angle*im))) )\n  elseif l.base ≈ -f.d/f.c\n    w = f(Inf)\n    return Line(w, angle(w-f(Inf)))\n  else\n    a = angle(l.base + f.d/f.c)\n    if a ≈ l.angle || a ≈ (l.angle + pi)\n      w = f(l.base)\n      return Line(w, angle(w-f(Inf)))\n    end\n  end\n\n  v = exp(im*l.angle)\n  w1 = f(l.base)\n  w2 = f(l.base + v)\n  w3 = f(l.base - v)\n  Circle(circumcenter(w1,w2,w3), circumradius(w1,w2,w3))\nend\n\nfunction (f::LinearTransformation)(l::Line)\n  Line(f(l.base), l.angle + angle(f.a))\nend\n\nfunction (f::Translation)(l::Line)\n  Line(f(l.base), l.angle)\nend\n\nfunction (f::AffineTransformation)(l::Line)\n  Line(f(l.base), l.angle + angle(f.a))\nend\n\nfunction (f::InversionReflection)(l::Line)\n  if l.base ≈ 0\n    return Line(l.base, l.angle + angle(f.b))\n  else\n    a = angle(l.base)\n    if a ≈ l.angle || a ≈ (l.angle + pi)\n      return Line(l.base, l.angle + angle(f.b))\n    end\n  end\n\n  v = exp(im*l.angle)\n  w1 = f(l.base)\n  w2 = f(l.base + v)\n  w3 = f(l.base - v)\n  Circle(circumcenter(w1,w2,w3), circumradius(w1,w2,w3))\nend\n\n\nfunction (f::MobiusTransformation)(l::LineSegment)\n  if f.c ≈ 0.0\n    return LineSegment( f(l.p1), f(l.p2) )\n  elseif l.p1 ≈ -f.d/f.c\n    # ToDo! Ray\n  elseif l.p2 ≈ -f.d/f.c\n    # ToDo! Ray\n  else\n    # ToDo! Two Rays!\n    # ToDo! Line Segment!\n  end\n\n  w1 = f(l.z1)\n  w2 = f(l.z2)\n  w3 = f((l.z1+l.z2)/2)\n  Arc(circumcenter(w1,w2,w3), w1, w2)\nend\n\nfunction (f::LinearTransformation)(l::LineSegment)\n  LineSegment(f(l.p1), f(l.p2))\nend\n\nfunction (f::Translation)(l::LineSegment)\n  LineSegment(f(l.p1), f(l.p2))\nend\n\nfunction (f::AffineTransformation)(l::LineSegment)\n  LineSegment(f(l.p1), f(l.p2))\nend\n\nfunction (f::InversionReflection)(l::LineSegment)\n  if l.p1 ≈ 0\n    # ToDo! Ray\n  elseif l.p2 ≈ 0\n    # ToDo! Ray\n  else\n    # ToDo! Two Rays!\n    # ToDo! Line Segment!\n  end\n\n  w1 = f(l.z1)\n  w2 = f(l.z2)\n  w3 = f((l.z1+l.z2)/2)\n  Arc(circumcenter(w1,w2,w3), w1, w2)\nend\n", "meta": {"hexsha": "4183ef7bd4ae5db8d33c357034208e604e5c4a49", "size": 15353, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mobiustransformations.jl", "max_stars_repo_name": "Colectivo-SDD/SDDGeometry.jl", "max_stars_repo_head_hexsha": "f3fe97b8b9f846ea7955f88877e2c4715984987a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mobiustransformations.jl", "max_issues_repo_name": "Colectivo-SDD/SDDGeometry.jl", "max_issues_repo_head_hexsha": "f3fe97b8b9f846ea7955f88877e2c4715984987a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mobiustransformations.jl", "max_forks_repo_name": "Colectivo-SDD/SDDGeometry.jl", "max_forks_repo_head_hexsha": "f3fe97b8b9f846ea7955f88877e2c4715984987a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9835329341, "max_line_length": 105, "alphanum_fraction": 0.6445645802, "num_tokens": 5174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7595131708117582}}
{"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    TaubinSmoothing(n; λ=0.5, μ=-0.5)\n\nPerform `n` iterations of Taubin smoothing with parameters `λ` and `μ`.\n\n## References\n\n* Taubin, G. 1995. [Curve and Surface Smoothing without Shrinkage]\n  (https://ieeexplore.ieee.org/document/466848)\n\"\"\"\nstruct TaubinSmoothing <: SmoothingMethod\n  n::Int\n  λ::Float64\n  μ::Float64\nend\n\nfunction TaubinSmoothing(n; λ=0.5, μ=-0.5)\n  @assert n > 0 \"invalid number of iterations\"\n  @assert 0 < λ ≤ -μ < 1 \"invalid parameters λ and μ\"\n  TaubinSmoothing(n, λ, μ)\nend\n\nfunction smooth(mesh, method::TaubinSmoothing)\n  n = method.n\n  λ = method.λ\n  μ = method.μ\n\n  # Laplacian matrix with uniform weights\n  L = laplacematrix(mesh, weights=:uniform)\n\n  # matrix with vertex coordinates (nvertices x ndims)\n  V = reduce(hcat, coordinates.(vertices(mesh))) |> transpose\n\n  # Taubin updates\n  for _ in 1:n\n    V = V + λ*L*V\n    V = V + μ*L*V\n  end\n\n  # new points of the smooth mesh\n  points = Point.(eachrow(V))\n\n  SimpleMesh(points, topology(mesh))\nend\n", "meta": {"hexsha": "a751f028c5527bea886a07ddabbe3c1d0c6958ce", "size": 1195, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/smoothing/taubin.jl", "max_stars_repo_name": "deltaeecs/Meshes.jl", "max_stars_repo_head_hexsha": "f2041f726c07c489583976944558498082a048cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/smoothing/taubin.jl", "max_issues_repo_name": "deltaeecs/Meshes.jl", "max_issues_repo_head_hexsha": "f2041f726c07c489583976944558498082a048cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/smoothing/taubin.jl", "max_forks_repo_name": "deltaeecs/Meshes.jl", "max_forks_repo_head_hexsha": "f2041f726c07c489583976944558498082a048cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.387755102, "max_line_length": 71, "alphanum_fraction": 0.6033472803, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.808067208930584, "lm_q1q2_score": 0.7595131599506386}}
{"text": "#==============================================================================\n\n          Solving the HJB with labor supply using the implicit method\n\n               Translated from matlab code on Ben Moll's website:\n                             https://benjaminmoll.com/codes/\n\n==============================================================================#\n\nusing LinearAlgebra, SparseArrays, Plots, Roots, LaTeXStrings\n\nγ = 2 # parameter from CRRA utility\nφ = .5 # frisch elasticity\nρ = 0.05 # the discount rate\nr = 0.03\nw = 1.0\n\nz1=.1\nz2 =.2\nz= [z1 z2]\n\nλ1 = 1.5\nλ2 = 1.0\n\nλ = [λ1 λ2]\n\nH = 500 # number of points in the grid space\namin= -0.15\namax= 3.0\n\na = LinRange(amin,amax,H)\nda = (amax-amin)/(H-1)\n\naa = [a a]\nzz = ones(H,1)*z\n\nmaxit = 20 # the maximum number of iterations we allow the finite differencing algorithm\ncrit = 10^(-6) # our critical value\nΔ = 1000\n\ndVf=zeros(H,2)\ndVb = zeros(H,2)\nc= zeros(H,2)\n\n# Create the matrix that captures the systems dynamic from λ process\nAswitch = [-1*sparse(I,H,H)*λ[1] sparse(I,H,H)*λ[1]; sparse(I,H,H)*λ[2] -1*sparse(I,H,H)*λ[2]]\n\nx0 = (w*z1)^(φ*(1-γ)/(1+γ*φ)) #inital value for labor\n\n# create function for labor supply\nlabor_solve(l, a, z, w, r, γ, φ) = (l .- ((w*z*l .+ r*a).^(-γ*φ))*(w*z)^φ)\n\n# set empty matrix and find all possible values for l\nl0 = zeros(500,2)\n\nfor i in 1:H\n    l_solve1(l) = labor_solve(l, a[i], z1, w, r, γ, φ)\n    l01 = find_zero(l_solve1,x0)\n\n    l_solve2(l) = labor_solve(l, a[i], z2, w, r, γ, φ)\n    l02 = find_zero(l_solve2,x0)\n\n    l0[i,:] = [l01 l02]\nend\n\n\nv0=zeros(H,2)\nv0[:,1] = (w*z[1].*l0[1,1] .+ r.*a).^(1-γ)/(1-γ)/ρ\nv0[:,2] = (w*z[2].*l0[1,2] .+ r.*a).^(1-γ)/(1-γ)/ρ\nplot(a,v0[:,2])\n\nlmin = l0[1,:]\nlmax = l0[H,:]\n\nglobal v=v0\n\n# set up spaces to save variables of interest\ndist=[]; V_n=[]; g_r=[]; dV_r=[]; V_r=[]; c_r=[]; adot=[]\n\n\n\n# Loop that finds the equilibrium interest rate\nfor n in 1:maxit\n    global V=v\n    push!(V_n,V)\n    # Forward differencing\n    dVf[1:H-1,:]=(V[2:H,:]-V[1:H-1,:])/da\n    dVf[H,:] = (w*z'.*lmax .+ r.*amax).^(-γ) # impose state constraint at the max, just in case\n    # Backward differencing\n    dVb[2:H,:]=(V[2:H,:]-V[1:H-1,:])/da\n    dVb[1,:]= (w*z'.*lmin .+ r.*amin).^(-γ)\n\n    # Find consumption and savings with the forward difference\n    cf = dVf.^(-1/γ)\n    lf = (dVf.*w.*zz).^φ\n    sf = w*zz.*lf +r.*aa -cf\n\n    # Find consumption and savings with the backward difference\n    cb= dVb.^(-1/γ)\n    lb = (dVb.*w.*zz).^φ\n    sb = w*zz.*lb +r.*aa -cb\n\n    # Find consumption and savings at steady state\n    c0 = w*zz.*l0 + r.*aa\n    dV0 = c0.^(-γ)\n\n    # Now implement the upwind scheme in order to select the best differencing method\n    Ib = (sb .< 0)\n    If = (sf .> 0)#.*(1 .-Ib) this term was included in Matlab code, messes up julia code for some reason??? Probably rounding differences?\n    I0 = (1 .- If - Ib)\n\n    # State constraint at amin is automatically implemented\n    global c = cf.*If + cb.*Ib + c0.*I0\n    global l = lf.*If + lb.*Ib + l0.*I0\n    u = c.^(1-γ)/(1-γ) - l.^(1+1/φ)/(1+1/φ)\n\n    # Construct matrix for the evolution of the system\n    global X = -Ib.*sb/da\n    global Y = -If.*sf/da + Ib.*sb/da\n    global Z = If.*sf/da\n\n    A1 = spdiagm(0=>Y[:,1], -1 => X[2:H,1], 1=> Z[1:H-1,1])\n    A2 = spdiagm(0=>Y[:,2], -1 => X[2:H,2], 1=> Z[1:H-1,2])\n    AA = [A1 spzeros(H,H); spzeros(H,H) A2]\n\n    global A = AA + Aswitch\n\n    B = (ρ +1/Δ)*sparse(I,2*H,2*H) - A\n\n    u_stacked = [u[:,1]; u[:,2]]\n    V_stacked = [V[:,1]; V[:,2]]\n\n    b = u_stacked + V_stacked/Δ\n    V_stacked = B\\b # Solves the system of equations\n\n    V = [V_stacked[1:H] V_stacked[H+1:2*H]]\n\n    V_change = V - v\n\n\n    global v = V\n\n    push!(dist, findmax(abs.(V_change))[1])\n\n    if dist[n] < crit\n        println(\"Value Function converged, Iteration=\")\n        println(n)\n        break\n    end\nend\n\nadot = w.*zz.*l + r.*aa - c\n\n#plot savings\nplot(a, adot[:,1], label = L\"s_1(a)\", xlabel=\"Wealth, a\", ylabel=L\"\\mathrm{Savings,\\hspace{1ex} } s_i(a)\")\nplot!(a, adot[:,2], label = L\"s_2(a)\")\nplot!(a, zeros(H,1), line=:dash, color=:black, label=\"\")\n\n#plot value function for j=1,2\nplot(a, v[:,1], label = L\"v_1(a)\", xlabel=\"Wealth, a\", ylabel=L\"\\mathrm{Value Function,\\hspace{1ex} } v_i(a)\")\nplot!(a, v[:,2], label = L\"v_2(a)\", legend=:bottomright)\n\n\n#plot labor for j=1,2\nplot(a, l[:,1], label = L\"l_1(a)\", xlabel=\"Wealth, a\", ylabel=L\"\\mathrm{Labor Supply,\\hspace{1ex} } l_i(a)\")\nplot!(a, l[:,2], label = L\"l_2(a)\")\n\n#plot consumption for j=1,2\nplot(a, c[:,1], label = L\"c_1(a)\", xlabel=\"Wealth, a\", ylabel=L\"\\mathrm{Consumption,\\hspace{1ex} } c_i(a)\")\nplot!(a, c[:,2], label = L\"c_2(a)\", legend=:bottomright)\n", "meta": {"hexsha": "706a2e29fbec694e6259f6bded838ce538775bb0", "size": 4630, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Moll_Code/Section01-Hugget-Achdou_etal_2017/HJB_labor_supply/HJB_labor_supply.jl", "max_stars_repo_name": "chandlerlester/Radio_Free_Julia", "max_stars_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-02-26T11:52:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T12:41:38.000Z", "max_issues_repo_path": "Moll_Code/Section01-Hugget-Achdou_etal_2017/HJB_labor_supply/HJB_labor_supply.jl", "max_issues_repo_name": "chandlerlester/Radio_Free_Julia", "max_issues_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Moll_Code/Section01-Hugget-Achdou_etal_2017/HJB_labor_supply/HJB_labor_supply.jl", "max_forks_repo_name": "chandlerlester/Radio_Free_Julia", "max_forks_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-11T08:09:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-30T18:54:12.000Z", "avg_line_length": 27.0760233918, "max_line_length": 139, "alphanum_fraction": 0.5552915767, "num_tokens": 1750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597457, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7595131523381079}}
{"text": "const errmax = 1e-15\r\n\r\n#Compute tail of noncentral Beta distribution\r\n#Russell Lenth, Algorithm AS 226: Computing Noncentral Beta Probabilities,\r\n#Applied Statistics,Volume 36, Number 2, 1987, pages 241-244\r\n\r\n\"\"\"\r\n\tncbeta_tail(x,a,b,lambda)\r\n\r\nCompute tail of the noncentral beta distribution.\r\nUses the recursive relation\r\n```math\r\nI_{x}(a,b+1;0) = I_{x}(a,b;0) - \\\\Gamma(a+b)/\\\\Gamma(a+1)\\\\Gamma(b)x^{a}(1-x)^{b}\r\n```\r\nand ``\\\\Gamma(a+1) = a\\\\Gamma(a)`` given in https://dlmf.nist.gov/8.17.21.\r\n\"\"\"\r\nfunction ncbeta_tail(a::Float64, b::Float64, lambda::Float64, x::Float64)\r\n    if x <= 0.0\r\n        return 0.0\r\n    elseif x >= 1.0\r\n        return 1.0\r\n    end\r\n\r\n    c = 0.5*lambda\r\n    #Init series\r\n\r\n    beta = logabsbeta(a,b)[1]\r\n    temp = beta_inc(a,b,x)[1]\r\n    gx = (beta_integrand(a,b,x,1.0-x))/a\r\n    q = exp(-c)\r\n    xj = 0.0\r\n    ax = q*temp\r\n    sumq = 1.0 - q\r\n    ans = ax\r\n\r\n    while true\r\n        xj += 1.0\r\n        temp -= gx\r\n        gx *= x*(a+b+xj-1.0)/(a+xj)\r\n        q *= c/xj\r\n        sumq -= q\r\n        ax = temp*q\r\n        ans += ax\r\n\r\n        #Check convergence\r\n        errbd = abs((temp-gx)*sumq)\r\n        if xj > 1000 || errbd < 1e-10\r\n            break\r\n        end\r\n    end\r\n    return ans\r\nend\r\n\r\n\"\"\"\r\n    ncbeta_poisson(a,b,lambda,x)\r\n\r\nCompute CDF of noncentral beta if lambda >= 54 using:\r\nFirst ``\\\\lambda/2`` is calculated and the Poisson term is calculated using ``P(j-1)=j/\\\\lambda P(j)`` and ``P(j+1) = \\\\lambda/(j+1) P(j)``.\r\nThen backward recurrences are used until either the Poisson weights fall below `errmax` or `iterlo` is reached.\r\n```math\r\nI_{x}(a+j-1,b) = I_{x}(a+j,b) + \\\\Gamma(a+b+j-1)/\\\\Gamma(a+j)\\\\Gamma(b)x^{a+j-1}(1-x)^{b}\r\n```\r\nThen forward recurrences are used until error bound falls below `errmax`.\r\n```math\r\nI_{x}(a+j+1,b) = I_{x}(a+j,b) - \\\\Gamma(a+b+j)/\\\\Gamma(a+j)\\\\Gamma(b)x^{a+j}(1-x)^{b}\r\n```\r\n\"\"\"\r\nfunction ncbeta_poisson(a::Float64, b::Float64, lambda::Float64, x::Float64)\r\n    c = 0.5*lambda\r\n    xj = 0.0\r\n    m = round(Int, c)\r\n    mr = float(m)\r\n    iterlo = m - trunc(Int, 5.0*sqrt(mr))\r\n    iterhi = m + trunc(Int, 5.0*sqrt(mr))\r\n    t = -c + mr*log(c) - logabsgamma(mr + 1.0)[1]\r\n    q = exp(t)\r\n    r = q\r\n    psum = q\r\n\r\n    beta = logabsbeta(a+mr,b)[1]\r\n    gx = beta_integrand(a+mr,b,x,1.0-x)/(a + mr)\r\n    fx = gx\r\n    temp = beta_inc(a+mr,b,x)[1]\r\n    ftemp = temp\r\n    xj += 1.0\r\n\r\n    sm = q*temp\r\n    iter1 = m\r\n\r\n    #Iterations start from M and goes downwards\r\n\r\n    for iter1 = m:-1:iterlo\r\n        if q < errmax\r\n            break\r\n        end\r\n\r\n        q *= iter1/c\r\n        xj += 1.0\r\n        gx *= (a + iter1)/(x*(a+b+iter1-1.0))\r\n        iter1 -= 1\r\n        temp += gx\r\n        psum += q\r\n        sm += q*temp\r\n    end\r\n\r\n    t0 = logabsgamma(a+b)[1] - logabsgamma(a+1.0)[1] - logabsgamma(b)[1]\r\n    s0 = a*log(x) + b*log1p(-x)\r\n\r\n    s = 0.0\r\n    for j = 0:iter1-1\r\n        s += exp(t0+s0+j*log(x))\r\n        t1 = log(a+b+j) - log(a+j+1.0) + t0\r\n        t0 = t1\r\n    end\r\n    #Compute first part of error bound\r\n\r\n    errbd = (gamma_inc(float(iter1),c,0)[2])*(temp+s)\r\n    q = r\r\n    temp = ftemp\r\n    gx = fx\r\n    iter2 = m\r\n    #Iterations for the higher part\r\n\r\n    for iter2 = m:iterhi-1\r\n        ebd = errbd + (1.0 - psum)*temp\r\n        if ebd < errmax\r\n            return sm\r\n        end\r\n        iter2 += 1\r\n        xj += 1.0\r\n        q *= c/iter2\r\n        psum += q\r\n        temp -= gx\r\n        gx *= x*(a+b+iter2-1.0)/(a+iter2)\r\n        sm += q*temp\r\n    end\r\n    return sm\r\nend\r\n\r\n#R Chattamvelli, R Shanmugam, Algorithm AS 310: Computing the Non-central Beta Distribution Function,\r\n#Applied Statistics, Volume 46, Number 1, 1997, pages 146-156\r\n\r\n\"\"\"\r\n\tncbeta(a,b,lambda,x)\r\n\r\nCompute the CDF of the noncentral beta distribution given by\r\n```math\r\nI_{x}(a,b;\\\\lambda ) = \\\\sum_{j=0}^{\\\\infty}q(\\\\lambda/2,j)I_{x}(a+j,b;0)\r\n```\r\nFor ``\\\\lambda < 54`` : algorithm suggested by Lenth(1987) in `ncbeta_tail(a,b,lambda,x)`.\r\nElse for ``\\\\lambda >= 54`` : modification in Chattamvelli(1997) in `ncbeta_poisson(a,b,lambda,x)` by using both forward and backward recurrences.\r\n\"\"\"\r\nfunction ncbeta(a::Float64, b::Float64, lambda::Float64, x::Float64)\r\n    ans = x\r\n    if x <= 0.0\r\n        return 0.0\r\n    elseif x >= 1.0\r\n        return 1.0\r\n    end\r\n\r\n    if lambda < 54.0\r\n        return ncbeta_tail(a,b,lambda,x)\r\n    else\r\n        return ncbeta_poisson(a,b,lambda,x)\r\n    end\r\nend\r\n\r\n\"\"\"\r\n    ncF(x,v1,v2,lambda)\r\n\r\nCompute CDF of noncentral F distribution given by:\r\n```math\r\nF(x, v1, v2; lambda) = I_{v1*x/(v1*x + v2)}(v1/2, v2/2; \\\\lambda)\r\n```\r\nwhere ``I_{x}(a,b; lambda)`` is the noncentral beta function computed above.\r\n\r\nWikipedia: https://en.wikipedia.org/wiki/Noncentral_F-distribution\r\n\"\"\"\r\nfunction ncF(x::Float64, v1::Float64, v2::Float64, lambda::Float64)\r\n    return ncbeta(v1/2, v2/2, lambda, (v1*x)/(v1*x + v2))\r\nend\r\n\r\nfunction ncbeta(a::T,b::T,lambda::T,x::T) where {T<:Union{Float16,Float32}}\r\n\tT.(ncbeta(Float64(a),Float64(b),Float64(lambda),Float64(x)))\r\nend\r\n\r\nfunction ncF(x::T,v1::T,v2::T,lambda::T) where {T<:Union{Float16,Float32}}\r\n\tT.(ncF(Float64(x),Float64(v1),Float64(v2),Float64(lambda)))\r\nend\r\n\r\nncbeta(a::Real,b::Real,lambda::Real,x::Real) = ncbeta(promote(float(a),float(b),float(lambda),float(x))...)\r\nncbeta(a::T,b::T,lambda::T,x::T) where {T<:AbstractFloat} = throw(MethodError(ncbeta,(a,b,lambda,x,\"\")))\r\nncF(x::Real,v1::Real,v2::Real,lambda::Real) = ncF(promote(float(x),float(v1),float(v2),float(lambda))...)\r\nncF(x::T,v1::T,v2::T,lambda::T) where {T<:AbstractFloat} = throw(MethodError(ncF,(x,v1,v2,lambda,\"\")))\r\n", "meta": {"hexsha": "7c13480ed3ddf766b85f15ff6ef7b848791f5cf9", "size": 5565, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/betanc.jl", "max_stars_repo_name": "alyst/SpecialFunctions.jl", "max_stars_repo_head_hexsha": "414385a7097e0f376b1273a3e0deac9d30cf0f9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 257, "max_stars_repo_stars_event_min_datetime": "2016-09-13T16:58:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T01:33:15.000Z", "max_issues_repo_path": "src/betanc.jl", "max_issues_repo_name": "alyst/SpecialFunctions.jl", "max_issues_repo_head_hexsha": "414385a7097e0f376b1273a3e0deac9d30cf0f9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 345, "max_issues_repo_issues_event_min_datetime": "2016-05-28T00:23:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T07:47:36.000Z", "max_forks_repo_path": "src/betanc.jl", "max_forks_repo_name": "alyst/SpecialFunctions.jl", "max_forks_repo_head_hexsha": "414385a7097e0f376b1273a3e0deac9d30cf0f9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 106, "max_forks_repo_forks_event_min_datetime": "2016-06-02T17:26:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T04:29:30.000Z", "avg_line_length": 28.5384615385, "max_line_length": 147, "alphanum_fraction": 0.5597484277, "num_tokens": 1994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7594702592061651}}
{"text": "using MacroTools, SymEngine\nimport MacroTools.postwalk\n\n\"\"\"\n    abs_to_relu!(ex::Expr)\n    abs_to_relu(ex::Expr)\nfunction to convert an `abs(x)` expression to `relu(x) + relu(-x)`. Mutating and nonmutating versions.\n\"\"\"\nfunction abs_to_relu(ex::Expr)\n    check_for_abs(ex)\n    x = ex.args[2] # the thing getting abs'ed\n    return :(relu($x) + relu(-$x))\nend\nfunction abs_to_relu!(ex::Expr)\n    check_for_abs(ex)\n    x = ex.args[2] # the thing getting abs'ed\n    ex.args = [:+, :(relu($x)), :(relu(-$x))]\nend\n\nfunction check_for_abs(ex::Expr)\n    ex.args[1] == :abs || throw(ArgumentError(\"Not an absolute value expression\"))\n    @assert length(ex.args) == 2 \"Malformed expression. `abs` can take only one argument. Got $ex\"\n    return nothing\nend\n\nfunction check_for_maxmin(ex::Expr)\n    ex.args[1] ∈ (:max, :min) || throw(ArgumentError(\"function is neither max nor min. Got $(ex.args[1])\"))\n    @assert length(ex.args) == 3 \"max/min_to_abs can't handle more than two inputs at the moment.\"\n    return nothing\nend\n\nfunction maxmin_to_abs(ex::Expr)\n    check_for_maxmin(ex)\n    a, b = ex.args[2:3]\n    if ex.args[1] == :max\n        return :(0.5*($a + $b + abs($a-$b)))\n    elseif ex.args[1] == :min\n        return :(0.5*($a + $b - abs($a-$b)))\n    end\nend\n\nfunction max0torelu(ex::Expr)\n    @assert(length(ex.args)==3)\n    a, b = ex.args[2:3]\n    if (a == 0)\n        return :(relu($b))\n    elseif (b == 0)\n        return :(relu($a))\n    end\nend\n\nto_relu_expression(not_ex) = not_ex\nfunction to_relu_expression(ex::Expr)\n    ex.head != :call && return ex\n    if ex.args[1] ∈ (:max, :min)\n        if (ex.args[1] == :max) & ((ex.args[2] == 0) | (ex.args[3] == 0))\n            ex = max0torelu(ex)\n        else\n            ex = maxmin_to_abs(ex)\n        end\n    elseif ex.args[1] == :abs\n        ex = abs_to_relu(ex) end\n    for i in 1:length(ex.args)\n        ex.args[i] = to_relu_expression(ex.args[i])\n    end\n    return ex\nend\n\n##########################################################################################\n\n\"\"\"\nConstruct a symbolic expression for a line between the points (x₀, 1.0) on the left and (x₁, 0) on the right.\n`pos_unit` has positive slope while `neg_unit` has negative slope. Note that due to the left-to-right assumption\n\n    neg_unit(x₀, x₁) == pos_unit(x₁, x₀)\n\"\"\"\nneg_unit(x0, x1) = :($(1/(x0-x1)) * (x - $x1))\n\"\"\"\nConstruct a symbolic expression for a line between the points (x₀, 0.0) on the left and (x₁, 1.0) on the right.\n`pos_unit` has positive slope while `neg_unit` has negative slope. Note that due to the left-to-right assumption\n\n    neg_unit(x₀, x₁) == pos_unit(x₁, x₀)\n\"\"\"\npos_unit(x0, x1) = :($(1/(x1-x0)) * (x - $x0))\n\n\"\"\"\n    closed_form_piecewise_linear(pts)::Expr\n\nConstructs a closed-form piecewise linear expression from an ordered (left to right) sequence of points.\nThe method is inspired by the paper by Lum and Chua (cite) that considers a piecewise linear function of the form:\n`f(x) = Σᵢ(yᵢ⋅gᵢ(xᵢ))` where `gᵢ(xⱼ) = δᵢⱼ`\nHere in the 1D case, `gᵢ = max(0, yᵢ*min(L1, L2))`, where `L1` and `L2` are the lines \"ramping up\" towards xᵢ\nand \"ramping down\" away from xᵢ. The function returns an `Expr` based on a variable `x`.\nThis can be turned into a callable function `f` by running something like `eval(:(f(x) = \\$expression_of_x))`.\n\n# Example\n    julia> pts = [(0,0), (1,1), (2, 0)]\n    3-element Array{Tuple{Int64,Int64},1}:\n     (0, 0)\n     (1, 1)\n     (2, 0)\n\n    julia> closed_form_piecewise_linear(pts)\n    :(max(0, 0 * (-1.0 * (x - 1))) + max(0, 1 * min(1.0 * (x - 0), -1.0 * (x - 2))) + max(0, 0 * (1.0 * (x - 1))))\n\"\"\"\nfunction closed_form_piecewise_linear(pts)\n    n = length(pts)\n    x, y = first.(pts), last.(pts) # split the x and y coordinates\n    G = []\n    for i in 2:n-1\n        x0, x1, x2 = x[i-1:i+1] # consider the \"triangulation\" of points x0,x1,x2\n        L1 = pos_unit(x0, x1) # x0-x1 is an increasing linear unit\n        L2 = neg_unit(x1, x2) # x1-x2 is a decreasing linear unit\n        gᵢ = :($(y[i]) * max(0, min($L1, $L2)))\n        push!(G, gᵢ)\n    end\n    # first and last points are special cases that ignore the min\n    g₀ = :($(y[1]) * max(0, $(neg_unit(x[1], x[2]))))\n    gᵣ = :($(y[end]) * max(0, $(pos_unit(x[end-1], x[end]))))\n    # Order doesn't matter now but for our debugging purposes earlier we enforce sequential ordering.\n    pushfirst!(G, g₀)\n    push!(G, gᵣ)\n    return :(+$(G...))\nend\n\n##########################################################################################\n\nfunction make_expr_dict(ex)\n    D = Dict()\n    ex = postwalk(ex) do e\n        if is_relu_expr(e)\n            return get!(D, e, Symbol(\"z$(length(D)+1)\"))\n        end\n        return e\n    end\n    D[ex] = Symbol(\"z$(length(D)+1)\")\n    return D\nend\n\nis_relu_expr(ex) = ex isa Expr && ex.head == :call && ex.args[1] == :relu\n\nsimplify(ex::Expr) = postwalk(e -> _simplify(e), ex)\n_simplify(s) = s\n_simplify(e::Expr) = Meta.parse(string(expand(Basic(e))))\n\n# thinking/scripting:\nBase.occursin(x, y) = x == y\nfunction Base.occursin(needle::Union{Symbol, Expr}, haystack::Expr)\n    needle == haystack && return true\n    for arg in haystack.args\n        occursin(needle, arg) && return true\n    end\n    return false\nend\n\n# Type piracy again:\nBase.Expr(B::Basic) = Meta.parse(string(B))\n\n\nfunction get_symbols(ex::Union{Expr, Symbol})\n    syms = Symbol[]\n    ops = (:*, :+, :-, :relu)\n    postwalk(e -> e isa Symbol && e ∉ ops ? push!(syms, e) : nothing, ex)\n    unique(syms)\nend\n\nfunction count_min_max(expr)\n    \"\"\" count number of min and max in expr\"\"\"\n    c = [0, 0]\n    if expr == :min\n        c[1] = 1\n    elseif expr == :max\n        c[2] = 1\n    elseif expr isa Expr\n        for arg in expr.args\n            c += count_min_max(arg)\n        end\n    end\n    return c\nend", "meta": {"hexsha": "9637d27f5416a1bdbc809bd520c72604fb6bce3f", "size": 5739, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/autoline.jl", "max_stars_repo_name": "sisl/Overt.jl", "max_stars_repo_head_hexsha": "9711229136555b1413c9d6f78c48e219070d143c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-08-12T04:50:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T03:18:19.000Z", "max_issues_repo_path": "src/autoline.jl", "max_issues_repo_name": "sisl/Overt.jl", "max_issues_repo_head_hexsha": "9711229136555b1413c9d6f78c48e219070d143c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-20T01:09:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T02:29:54.000Z", "max_forks_repo_path": "src/autoline.jl", "max_forks_repo_name": "sisl/Overt.jl", "max_forks_repo_head_hexsha": "9711229136555b1413c9d6f78c48e219070d143c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8833333333, "max_line_length": 114, "alphanum_fraction": 0.5845966196, "num_tokens": 1858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7594702588359397}}
{"text": "# -----------------------------------------------------------\n#\n# An example of contructing the initial data for a traveling\n# wave in D-dimensions using the tensor_construct method\n# and the wave_evolve in PDEs.jl\n#\n# -----------------------------------------------------------\n\nusing GalerkinSparseGrids\nusing LinearAlgebra\n\n# -----------------------------------------------------\n# Generates the coefficients for a waveform\n# A cos(\\vec{k} \\cdot \\vec{x} + \\phi), \\vec{k} = 2 \\pi \\vec{m}\n# using an interpolation of type (k,n)\n# and periodic boundary conditions in D-dimensionss\n# -----------------------------------------------------\nfunction cos_coeffs(k::Int, n::Int, m::AbstractArray{T,1};\n                    scheme=\"sparse\", phase = 0.0, A = 1.0) where T\n    D = length(m)\n    wavenumber = 2*pi*m\n\n    # Begin with writing cos(\\sum_i k_i x_i) as a sum of products\n    # of sines/cosines of individual k_j x_j\n    sines   = [i==1 ? x->sin(wavenumber[i]*x[1]+phase) : x->sin(wavenumber[i]*x[1]) for i in 1:D]\n    cosines = [i==1 ? x->cos(wavenumber[i]*x[1]+phase) : x->cos(wavenumber[i]*x[1]) for i in 1:D]\n\n    sine_dicts   = [coeffs_DG(1, k, n, sines[i]) for i in 1:D]\n    cosine_dicts = [coeffs_DG(1, k, n, cosines[i]) for i in 1:D]\n\n    ansVect = zeros(get_size(Val(D), k, n, Val(Symbol(scheme))))\n\n    for SCs in CartesianIndices(ntuple(q->2, D))\n        num_sines = sum([SCs[i]-1 for i in 1:D])\n        if num_sines % 2 == 1\n            continue\n        end\n        sign = num_sines%4==0 ? 1 : -1\n\n        coeff_array = [SCs[i]==1 ? cosine_dicts[i] : sine_dicts[i] for i in 1:D]\n        productDict = tensor_construct(D, k, n, coeff_array; scheme=scheme)\n        productVect = D2V(D, k, n, productDict; scheme=scheme)\n\n        ansVect += sign * productVect\n    end\n\n    return A * ansVect\nend\n\n# -----------------------------------------------------\n# The same as above, but using sin\n# -----------------------------------------------------\nfunction sin_coeffs(k::Int, n::Int, m::Array{Int,1};\n                    scheme=\"sparse\", phase=0.0, A=1.0)\n    return cos_coeffs(k, n, m; scheme=scheme, phase=phase-pi/2, A=A)\nend\n\n# -----------------------------------------------------\n# Returns the data for a traveling wave\n# using the above methods\n# ----------------------------------------------------\nfunction traveling_wave(k::Int, n::Int, m::Array{Int,1};\n                        scheme=\"sparse\", phase=0.0, A=1.0)\n    wavenumber = 2*pi*m\n    frequency = sqrt(dot(wavenumber,wavenumber))\n\n    # u(x) = A * cos(dot(wavenumber,x) + phase)\n    # v(v) = A * frequency * sin(dot(k,x) + phase)\n    u0_coeffs = cos_coeffs(k, n, m; scheme=scheme, phase=phase, A=A)\n    v0_coeffs = sin_coeffs(k, n, m; scheme=scheme, phase=phase, A=A*frequency)\n    return (u0_coeffs, v0_coeffs)\nend\n\n# -----------------------------------------------------\n# Main routine:\n# -----------------------------------------------------\n\n# Modify m to change the wavenumber.\n# We use integer entries here because of periodic boundary conditions\nm = [1,2,-1]\ntruesoln = x -> cos(2*pi*(dot(m,x) - sqrt(dot(m,m))*0.54))\nk_max = 5\nn_max = 6\nD = length(m)\n\nt0 = 0;\nt1 = 0.54;\n\nprintln(\"Wave Evolution in \", D, \"D.\")\nprintln(\"Going to k_max = \", k_max, \", n_max = \", n_max, \":\")\n\nfor k_used in 1:k_max\n    for n_used in 1:n_max\n        f0coeffs, v0coeffs = traveling_wave(k_used, n_used, m)\n        soln = wave_evolve(D, k_used, n_used, f0coeffs, v0coeffs, t0, t1)\n        dict = V2D(D, k_used, n_used, soln[2][end])\n\n        err = mcerr(x->reconstruct_DG(dict, [x...]), truesoln, D)\n        println(\"(k = \", k_used, \", n = \", n_used, \") : err = \", err)\n    end\nend\n\n\n", "meta": {"hexsha": "b56fd12a5bdf9d3b89a3a50d6c89153e538e8f90", "size": 3641, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/traveling_wave.jl", "max_stars_repo_name": "AlexAtanasov14/GalerkinSparseGrids.jl", "max_stars_repo_head_hexsha": "89ee55e078c040760a07f547b626e947fb0d21c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2016-07-26T19:16:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T14:27:38.000Z", "max_issues_repo_path": "examples/traveling_wave.jl", "max_issues_repo_name": "mkosiol/GalerkinSparseGrids.jl", "max_issues_repo_head_hexsha": "b89cc619126285dcaef1f749115ddbe4d43dd3ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-05-20T19:30:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-07T23:59:29.000Z", "max_forks_repo_path": "examples/traveling_wave.jl", "max_forks_repo_name": "mkosiol/GalerkinSparseGrids.jl", "max_forks_repo_head_hexsha": "b89cc619126285dcaef1f749115ddbe4d43dd3ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2016-07-26T19:16:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T14:27:42.000Z", "avg_line_length": 35.0096153846, "max_line_length": 97, "alphanum_fraction": 0.5201867619, "num_tokens": 1068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7594702530913697}}
{"text": "\"\"\"\r\nidwi(args...)  -->Plot\r\n\r\niwm is a Plot Recipe in which makes a spatial interpolation of data provided applying Inverse Weight Mapping.\r\n\r\n\r\nGeneral equation for spatial interpolation is:\r\n``{ Z }^{ * }=\\\\sum _{ i=1 }^{ n }{ { \\\\lambda  }_{ i }{ z }_{ i } } ``\r\n\r\nwhere ``\\\\lambda`` is the weight Parameter\r\n\r\nApplying the Inverse‐Distance Weighted Interpolation\r\n\r\n``{ Z }\\\\left( x \\\\right) =\\\\frac { \\\\sum _{ i=1 }^{ n }{ { w }_{ i }{ z }_{ i } }  }{ \\\\sum _{ i=1 }^{ n }{ { z }_{ i } }  } \\\\\\\\ \\\\\\\\ { w }_{ i }=\\\\frac { 1 }{ { d }_{ i }^{ n } } ``\r\n\r\n<br> The next table show the list of variables allowed:\r\n\r\n|PropertyName|Args|Default|Input|Description\r\n|---|---|---|---|---|\r\n|x|Mandatory|--|Array{Number,1}| X values|\r\n|y|Mandatory|--|Array{Number,1}| Y values|\r\n|z|Mandatory|--|Array{Number,1}| Z values|\r\n|m|Optional|m=100|m=number| Number of grids in y axis|\r\n|n|Optional|n=100|n=number| Number of grids in x axis|\r\n|p|Optional|p=2|p=number| IDWI exponent. The greater more influenced by near points|\r\n\"\"\"\r\n@userplot idwi\r\n\r\n@recipe function f(h::idwi; m=100, n=100, p=2, surf=false)\r\n\r\n\r\n    ylabel --> \"North [m]\"\r\n    xlabel --> \"East [m]\"\r\n    seriescolor --> :Spectral\r\n\r\nx, y, z = h.args\r\n\r\n# Build the grid of prediction points\r\n\r\n    ## X & Y range\r\n  Xrange=range(minimum(x),stop=maximum(x),length=n)\r\n  Yrange=range(minimum(y),stop=maximum(y),length=m)\r\n\r\n\r\n\r\n    ## X & Y grids\r\n  X=repeat(Xrange',length(Yrange),1)\r\n  Y=repeat(Yrange,1,length(Xrange))\r\n\r\n    # X & Y grids converted to vectors\r\n    Xvec=vec(X)\r\n    Yvec=vec(Y)\r\n\r\n    #Number of Sample Points and Prediction Points\r\n    Nsp=length(x)                           #Numbers of Sample Points\r\n    Npp=length(Xrange)*length(Yrange)       #Number of Prediction Points\r\n\r\n\r\n\r\n    #DISTANCE BETWEEN PREDICTION AND SAMPLE POINTS---------------------------\r\n    #Matrix of distance   I x J    Sample Points x Prediction Points\r\n\r\n    d=zeros(Nsp,Npp)\r\n    for i=1:Nsp\r\n        for j=1:Npp\r\n            d[i,j]=sqrt((x[i]-Xvec[j]).^2+(y[i]-Yvec[j]).^2)\r\n        end\r\n    end\r\n\r\n\r\n    #Estimate the matrix of weights\r\n\r\n    W=map(dis->(1 ./(dis.^p)),d)\r\n\r\n    #Calculate value in prediction point in a vector\r\n\r\n    Zvec=zeros(Npp)\r\n    for i=1:Npp\r\n        Zvec[i]=W[:,i]'*z ./ sum(W[:,i])\r\n    end\r\n\r\n    Z=reshape(Zvec,m,n)\r\n\r\n#Coutour series\r\nif surf==true\r\n    @series begin\r\n        seriestype := :surface\r\n        zflip := true\r\n        Xrange, Yrange, Z\r\n        end\r\nelse\r\n@series begin\r\n    seriestype := :contour\r\n    clabels := true\r\n    fill --> true\r\n\r\n    Xrange, Yrange, Z\r\nend\r\nend\r\nend\r\n", "meta": {"hexsha": "ba3e9f233ebf0187e3514f2725d29b68b31c40b8", "size": 2584, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/IDWIRecipe.jl", "max_stars_repo_name": "scuervo91/WellLogs.jl", "max_stars_repo_head_hexsha": "bc691fdd0500414b4f78172f905ca81930364f8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-05-23T12:19:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T21:34:04.000Z", "max_issues_repo_path": "src/IDWIRecipe.jl", "max_issues_repo_name": "scuervo91/WellLogs.jl", "max_issues_repo_head_hexsha": "bc691fdd0500414b4f78172f905ca81930364f8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-21T23:04:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-25T15:37:20.000Z", "max_forks_repo_path": "src/IDWIRecipe.jl", "max_forks_repo_name": "scuervo91/WellLogs.jl", "max_forks_repo_head_hexsha": "bc691fdd0500414b4f78172f905ca81930364f8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-06-21T22:50:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T18:28:16.000Z", "avg_line_length": 25.5841584158, "max_line_length": 185, "alphanum_fraction": 0.5661764706, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7594702514233301}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.0\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 0bdd0fc6-9203-11eb-1ea3-9fe58aca7da0\nusing SymPy, LinearAlgebra\n\n# ╔═╡ aa073e00-323c-11eb-0297-83e3db12248d\nmd\"\n# Gradijent, divergencija i rotacija\n\n__Nabla__ ili __Hamiltonov operator__  je\n\n$$\\nabla = \\frac{\\partial}{\\partial x} \\vec{\\imath}+\\frac{\\partial}{\\partial y} \\vec{\\jmath} +\\frac{\\partial}{\\partial z} \\vec{k}.$$\n\nNabla ima svojstva derivacije i vektora.\n\n__Gradijent__ skalarnog polja $f(x,y,z)$ je\n\n$\\mathop{\\mathrm{grad}} f = \\nabla \\cdot f=\\frac{\\partial f}{\\partial x} \\vec{\\imath}+\\frac{\\partial f}{\\partial y} \\vec{\\jmath} +\\frac{\\partial f}{\\partial z} \\vec{k}.$\n\n__Divergencija__ vektorskog polja\n\n$\\vec{w}(x,y,z)=w_x(x,y,z)\\vec{\\imath} + w_y(x,y,z) \\vec{\\jmath} + w_z(x,y,z)\\vec{k}$\n\nje\n\n$\\mathop{\\mathrm{div}} \\vec{w} = \\nabla \\cdot \\vec{w}= \\frac{\\partial w_x}{\\partial x} +\\frac{\\partial w_y}{\\partial y} +\\frac{\\partial w_z}{\\partial z}.$\n\n__Rotacija__ vektorskog polja $\\vec{w}(x,y,z)$ je\n\n$\\mathop{\\mathrm{rot}} \\vec{w} = \\nabla \\times \\vec{w}= \\begin{vmatrix} \\vec{\\imath} & \\vec{\\jmath} & \\vec{k} \\\\ \\frac{\\partial}{\\partial x} & \\frac{\\partial}{\\partial y} & \\frac{\\partial}{\\partial z} \\\\ w_x & w_y &w_z \\end{vmatrix}.$\n\n__Usmjerena derivacija__ skalarnog polja $f(x,y,z)$ u smjeru vektora $\\vec a$ je\n\n$$\\frac{\\partial f}{\\partial \\vec a}(x,y,z)=\\vec a_0 \\cdot \\mathop{\\mathrm{grad}} f(x,y,z).$$\n\n__Usmjerena derivacija__ vektorskog polja $\\vec w(x,y,z)$ u smjeru vektora $\\vec a$ je\n\n$$\\frac{\\partial \\vec w}{\\partial \\vec a}(x,y,z)=(\\vec a_0 ∇) \\vec w(x,y,z).$$\n\"\n\n# ╔═╡ c75d36c0-923c-11eb-0477-c3101e21f880\nx,y,z=symbols(:x),symbols(:y),symbols(:z)\n\n# ╔═╡ 1b261092-923a-11eb-01d6-7f705b30d46e\nbegin\n\t∂x(f::Sym) = diff(f,x)\n\t∂y(f::Sym) = diff(f,y)\n\t∂z(f::Sym) = diff(f,z)\n\t∇=[∂x,∂y,∂z]\nend\n\n# ╔═╡ 1ca28980-925d-11eb-2be1-815a5df595ff\nbegin\n\timport Base.*\n\t*(∂x::typeof(∂x),f::Sym)=∂x(f)\n\t*(∂y::typeof(∂y),f::Sym)=∂y(f)\n\t*(∂z::typeof(∂z),f::Sym)=∂z(f)\n\t*(∇::Function,f::Sym)=∇(f)\n\tgrad(f)=∇*f\n\trot(u)=∇×u\n\timport LinearAlgebra.⋅\n\t⋅(∇::Array{Function,1},w::Array{Sym,1})=∇[1]*w[1]+∇[2]*w[2]+∇[3]*w[3]\n\tdiv(u)=∇⋅u\n\t⋅(a::Vector,∇::Array{Function,1})=a[1]*∇[1]+a[2]*∇[2]+a[3]*∇[3]\nend\n\n# ╔═╡ c2a476e6-e948-485f-9b2e-b6f821504263\n# Izvedeni operator a∇\nbegin\n\ta∂x(a::Vector,f::Sym) = a[1]*diff(f,x)\n\ta∂y(a::Vector,f::Sym) = a[2]*diff(f,y)\n\ta∂z(a::Vector,f::Sym) = a[3]*diff(f,z)\n\ta∇(a::Vector,f::Sym)=a∂x(a,f)+a∂y(a,f)+a∂z(a,f)\n\ta∇(a::Vector,w::Array{Sym,1})=[a∇(a,w[1]),a∇(a,w[2]),a∇(a,w[3])]\nend\n\n# ╔═╡ bd70ec2e-ad07-4526-aa70-5f25c86b444e\nmd\"\n## Primjeri\n\"\n\n# ╔═╡ fd3305b2-923a-11eb-15c4-5b79db40bf46\nbegin\n\t# Skalarna polja\n\tf=x^2+3*y*z+5\n\tg=x*y*z\n\t# Vektorska polja\n\tw=[y*z,z*x,x*y]\n\tu=[x^2*y,x*y,z/x]\n\t# Vektor\n\ta=[1,1,-2]\n\t# Točka\n\tT=(1,-1/2,2)\nend\n\n# ╔═╡ 2b00c286-0807-4fa0-a9c2-6b1d56ae3716\nf\n\n# ╔═╡ 66b9df0a-06c4-409c-9ae4-79b3cc3833b5\n∂x(f)\n\n# ╔═╡ 9b816a31-675a-4dea-83e7-67430eeb741e\n∂x*f\n\n# ╔═╡ ec770eca-54d2-4394-b359-ad5e47218e92\na∇(a,f)\n\n# ╔═╡ 3577e5e0-8fa8-4938-9119-b7c14f31e5be\na∇(a,u)\n\n# ╔═╡ 2a47ed85-0691-4cb2-84b5-52facb4eda0b\n# Gradijent\n∇*f\n\n# ╔═╡ 26292a50-9627-40a3-bacc-034de0882ac2\ngrad(f)\n\n# ╔═╡ 8d4a98d1-414e-4714-9c94-6b6426388bc0\n# Gradijent u zadanoj točki\nsubs.(∇*f,x=>T[1],y=>T[2],z=>T[3])\n\n# ╔═╡ c62f2abe-b330-4e5b-8a73-c2ac5fe32284\n# Divergencija\n∇⋅u\n\n# ╔═╡ f141e418-574d-4a0f-903c-35ad8d3e6883\ndiv(u)\n\n# ╔═╡ 0e012c70-afc3-410f-a73c-978783948cc3\n# Divergencija u zadanoj točki\nsubs(∇⋅u,x=>T[1],y=>T[2],z=>T[2])\n\n# ╔═╡ faea848e-f4d7-4476-993f-d9db5c6ca2ee\n# Rotor\n∇×u\n\n# ╔═╡ e3c9e5d1-8542-4940-8dd2-c60849b152c3\nrot(u)\n\n# ╔═╡ 0496ef19-9e5c-4f5b-aa4b-22d98cfcf9a0\n# Rotor u zadanoj točki\nsubs.(∇×u,x=>T[1],y=>T[2],z=>T[3])\n\n# ╔═╡ ad3b7955-cd19-4aaf-8a98-b4727bafe572\n# Primjer svojstva\nrot(f*grad(g))\n\n# ╔═╡ 93446240-2427-4964-9e3a-75f2de6b67e6\ngrad(f)×grad(g)\n\n# ╔═╡ 44c1a521-657b-43c4-ac59-7a8e24bf25cc\n# Drugi primjer svojstva\nrot(w×u)\n\n# ╔═╡ 54692583-1661-4b04-8f2c-94689630cff8\nexpand.(w*div(u)-u*div(w)+a∇(u,w)-a∇(w,u))\n\n# ╔═╡ fadb40e2-6c5e-48b2-a45f-88ea4f8cc4e5\n# Usmjerena derivacija skalarnog polja\na/norm(a)⋅grad(f)\n\n# ╔═╡ 180512f7-c8e8-4aee-9872-0057d6fe9c5d\n# Usmjerena derivacija skalarnog polja u točki\nsubs(a/norm(a)⋅grad(f),x=>T[1],y=>T[2],z=>T[3])\n\n# ╔═╡ 258fbdc7-7c24-4ecf-bc5a-468069f5c482\n# Skalarno polje najbrže raste u smjeru gradijenta\nsubs(grad(f)/norm(grad(f))⋅grad(f),x=>T[1],y=>T[2],z=>T[3])\n\n# ╔═╡ eeb8e757-668e-48c1-b560-076b3f47b5bf\n# Usmjerena derivacija vektorskog polja\na∇(a/norm(a),u)\n\n# ╔═╡ 694962cc-cca2-4a4d-939d-7eb329de9917\n# Usmjerena derivacija vektorskog polja u točki\nsubs.(a∇(a/norm(a),u),x=>T[1],y=>T[2],z=>T[3])\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nSymPy = \"24249f21-da20-56a4-8eb1-6a02cf4ae2e6\"\n\n[compat]\nSymPy = \"~1.0.52\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"a325370b9dd0e6bf5656a6f1a7ae80755f8ccc46\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.7.2\"\n\n[[CommonEq]]\ngit-tree-sha1 = \"d1beba82ceee6dc0fce8cb6b80bf600bbde66381\"\nuuid = \"3709ef60-1bee-4518-9f2f-acd86f176c50\"\nversion = \"0.2.0\"\n\n[[CommonSolve]]\ngit-tree-sha1 = \"68a0743f578349ada8bc911a5cbd5a2ef6ed6d1f\"\nuuid = \"38540f10-b2f7-11e9-35d8-d573e4eb0ff2\"\nversion = \"0.2.0\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"31d0151f5716b655421d9d75b7fa74cc4e744df2\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.39.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Conda]]\ndeps = [\"JSON\", \"VersionParsing\"]\ngit-tree-sha1 = \"299304989a5e6473d985212c28928899c74e9421\"\nuuid = \"8f4d0f93-b110-5947-807f-2305c1781a2d\"\nversion = \"1.5.2\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"a32185f5428d3986f47c2ab78b1f216d5e6cc96f\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.5\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"f76424439413893a832026ca355fe273e93bce94\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"DocStringExtensions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"34dc30f868e368f8a17b728a1238f3fcda43931a\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.3\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"5a5bc6bf062f0f95e62d0fe0a2d99699fed82dd9\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.8\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"a8709b968a1ea6abc2dc1967cb1db6ac9a00dfb6\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.5\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[PyCall]]\ndeps = [\"Conda\", \"Dates\", \"Libdl\", \"LinearAlgebra\", \"MacroTools\", \"Serialization\", \"VersionParsing\"]\ngit-tree-sha1 = \"169bb8ea6b1b143c5cf57df6d34d022a7b60c6db\"\nuuid = \"438e738f-606a-5dbb-bf0a-cddfbfd45ab0\"\nversion = \"1.92.3\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"44a75aa7a527910ee3d1751d1f0e4148698add9e\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.2\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"793793f1df98e3d7d554b65a107e9c9a6399a6ed\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.7.0\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[SymPy]]\ndeps = [\"CommonEq\", \"CommonSolve\", \"LinearAlgebra\", \"Markdown\", \"PyCall\", \"RecipesBase\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"1ef257ecbcab8058595a68ca36a6844b41babcbd\"\nuuid = \"24249f21-da20-56a4-8eb1-6a02cf4ae2e6\"\nversion = \"1.0.52\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[VersionParsing]]\ngit-tree-sha1 = \"80229be1f670524750d905f8fc8148e5a8c4537f\"\nuuid = \"81def892-9a0e-5fdd-b105-ffc91e053289\"\nversion = \"1.2.0\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─aa073e00-323c-11eb-0297-83e3db12248d\n# ╠═0bdd0fc6-9203-11eb-1ea3-9fe58aca7da0\n# ╠═c75d36c0-923c-11eb-0477-c3101e21f880\n# ╠═1b261092-923a-11eb-01d6-7f705b30d46e\n# ╠═1ca28980-925d-11eb-2be1-815a5df595ff\n# ╠═c2a476e6-e948-485f-9b2e-b6f821504263\n# ╟─bd70ec2e-ad07-4526-aa70-5f25c86b444e\n# ╠═fd3305b2-923a-11eb-15c4-5b79db40bf46\n# ╠═2b00c286-0807-4fa0-a9c2-6b1d56ae3716\n# ╠═66b9df0a-06c4-409c-9ae4-79b3cc3833b5\n# ╠═9b816a31-675a-4dea-83e7-67430eeb741e\n# ╠═ec770eca-54d2-4394-b359-ad5e47218e92\n# ╠═3577e5e0-8fa8-4938-9119-b7c14f31e5be\n# ╠═2a47ed85-0691-4cb2-84b5-52facb4eda0b\n# ╠═26292a50-9627-40a3-bacc-034de0882ac2\n# ╠═8d4a98d1-414e-4714-9c94-6b6426388bc0\n# ╠═c62f2abe-b330-4e5b-8a73-c2ac5fe32284\n# ╠═f141e418-574d-4a0f-903c-35ad8d3e6883\n# ╠═0e012c70-afc3-410f-a73c-978783948cc3\n# ╠═faea848e-f4d7-4476-993f-d9db5c6ca2ee\n# ╠═e3c9e5d1-8542-4940-8dd2-c60849b152c3\n# ╠═0496ef19-9e5c-4f5b-aa4b-22d98cfcf9a0\n# ╠═ad3b7955-cd19-4aaf-8a98-b4727bafe572\n# ╠═93446240-2427-4964-9e3a-75f2de6b67e6\n# ╠═44c1a521-657b-43c4-ac59-7a8e24bf25cc\n# ╠═54692583-1661-4b04-8f2c-94689630cff8\n# ╠═fadb40e2-6c5e-48b2-a45f-88ea4f8cc4e5\n# ╠═180512f7-c8e8-4aee-9872-0057d6fe9c5d\n# ╠═258fbdc7-7c24-4ecf-bc5a-468069f5c482\n# ╠═eeb8e757-668e-48c1-b560-076b3f47b5bf\n# ╠═694962cc-cca2-4a4d-939d-7eb329de9917\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "942606105fc38eb494c7d7a18bfe0dd3f8055cd9", "size": 13592, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Pluto/Nabla.jl", "max_stars_repo_name": "ivanslapnicar/Matematika", "max_stars_repo_head_hexsha": "6ec31e97470cb10e1e0505421461ede257d64035", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-13T12:02:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-13T12:02:36.000Z", "max_issues_repo_path": "Pluto/Nabla.jl", "max_issues_repo_name": "ivanslapnicar/Matematika", "max_issues_repo_head_hexsha": "6ec31e97470cb10e1e0505421461ede257d64035", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Pluto/Nabla.jl", "max_forks_repo_name": "ivanslapnicar/Matematika", "max_forks_repo_head_hexsha": "6ec31e97470cb10e1e0505421461ede257d64035", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8524590164, "max_line_length": 280, "alphanum_fraction": 0.7037963508, "num_tokens": 6870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.926303728259492, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7594702477170252}}
{"text": "function assemble_system!(problem::SpectralBVPProblem{TF, TBCL, TBCR}) where {TF<:AbstractArray, TBCL<:PeriodicBC, TBCR<:PeriodicBC}\n\n    # build eigenvalues\n    @. problem.λ = ((2*π/(problem.b-problem.a)) * [0:problem.N÷2; -(problem.N÷2)+1:-1])^2;\n\n    # build rhs\n    @. problem.rhs = problem.f;\n\n    problem\nend\n\nfunction assemble_system!(problem::SpectralBVPProblem{TF, TBCL, TBCR}) where {TF<:Function, TBCL<:PeriodicBC, TBCR<:PeriodicBC}\n\n    # build eigenvalues\n    @. problem.λ = ((2*π/(problem.b-problem.a)) * [0:problem.N÷2; -(problem.N÷2)+1:-1])^2;\n\n    # build rhs\n    @. problem.rhs = problem.f(problem.x);\n\n    problem\nend\n\nfunction assemble_system!(problem::SpectralBVPProblem{TF, TBCL, TBCR}) where {TF<:AbstractArray, TBCL<:DirichletBC, TBCR<:DirichletBC}\n\n    # build eigenvalues\n    @. problem.λ = ((π/(problem.b-problem.a)) * [0:problem.N÷2; -(problem.N÷2)+1:-1])^2;\n    \n    # build rhs\n    @. problem.rhs = problem.f;\n\n    problem\nend\n\nfunction assemble_system!(problem::SpectralBVPProblem{TF, TBCL, TBCR}) where {TF<:Function, TBCL<:DirichletBC, TBCR<:DirichletBC}\n\n    # build eigenvalues\n    @. problem.λ = ((π/(problem.b-problem.a)) * [0:problem.N÷2; -(problem.N÷2)+1:-1])^2;\n\n    # build rhs with odd extension\n    @. problem.rhs[problem.N÷2+1:end] = problem.f([problem.a; problem.x]);\n    problem.rhs[1:problem.N÷2] .= -reverse(problem.f.([problem.x; problem.b]));\n\n    problem\nend\n\n\nfunction assemble_system!(problem::SpectralBVPProblem{TF, TBCL, TBCR}) where {TF<:AbstractArray, TBCL<:NeumannBC, TBCR<:NeumannBC}\n\n    # build eigenvalues\n    @. problem.λ = ((π/(problem.b-problem.a)) * [0:problem.N÷2; -(problem.N÷2)+1:-1])^2;\n    \n    # build rhs\n    @. problem.rhs = problem.f;\n\n    problem\nend\n\nfunction assemble_system!(problem::SpectralBVPProblem{TF, TBCL, TBCR}) where {TF<:Function, TBCL<:NeumannBC, TBCR<:NeumannBC}\n\n    # build eigenvalues\n    @. problem.λ = ((π/(problem.b-problem.a)) * [0:problem.N÷2; -(problem.N÷2)+1:-1])^2;\n\n    # build rhs with even extension\n    @. problem.rhs[problem.N÷2+1:end] = problem.f(problem.x[1:end-1]);\n    problem.rhs[1:problem.N÷2] .= reverse(problem.f.(problem.x[2:end]));\n\n    problem\nend\n\n", "meta": {"hexsha": "df11982eda4ab8435b08931f20870c7830b70550", "size": 2167, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "BasicBVP1D/src/assembly_spectral.jl", "max_stars_repo_name": "liamfdoherty/Math_540_2021", "max_stars_repo_head_hexsha": "6b84b88ca1c587650a82f5bc9351f27a518e104d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BasicBVP1D/src/assembly_spectral.jl", "max_issues_repo_name": "liamfdoherty/Math_540_2021", "max_issues_repo_head_hexsha": "6b84b88ca1c587650a82f5bc9351f27a518e104d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BasicBVP1D/src/assembly_spectral.jl", "max_forks_repo_name": "liamfdoherty/Math_540_2021", "max_forks_repo_head_hexsha": "6b84b88ca1c587650a82f5bc9351f27a518e104d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9571428571, "max_line_length": 134, "alphanum_fraction": 0.6511305953, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8198933271118222, "lm_q1q2_score": 0.7594702440107205}}
{"text": "\"\"\" package  -------------------------------------------------------\n \n   Performs several verification calculations given a file of grid spacings \n   and some observed quantity corresponding to each grid spacing.\n \n   Computes:\n   - order of convergence\n   - Richardson extrapolation to zero grid spacing\n   - grid convergence indices (GCI)\n \n --------------------------------------------------------------------------\n \nAdapted from:\n    \n    NPARC Alliance CFD Verification and Validation Web Site\n    Examining Spatial (Grid) Convergence\n    verify.f90\n    URL: http://www.grc.nasa.gov/WWW/wind/valid/tutorial/spatconv.html\n    \n    Nov '11: Updated to reflect Celik et al 2008.\n    Sept '18: Translated to Julia\n\n    Credit to Matthew Topper.\n\"\"\"\n\n\"\"\" Calculate the order of convergence values generated with three\ngrids of reducing resolution (ie grid_1 is finest). The values of the grids\nare needed along with the ratios between them.\n\nAn iterative method with under-relaxation is used to calculate the order\nof convergence as the refinement ratio is not necessarily constant.\n\nThis has been modified to the method of Celik (2008).\n\"\"\"\nfunction order_of_convergence(value_1, value_2, value_3, ratio_21, ratio_32, omega=0.5, tol=1.E-6)\n    # Set a maximum residual and number of iterations\n    max_res = 1.E6\n    # calculate the epsilons.\n    epsilon32 = float(value_3 - value_2)\n    epsilon21 = float(value_2 - value_1)\n    # Calculate the fraction\n    epfrac = epsilon32 / epsilon21\n    # Get the signed unit, s\n    s = epfrac / abs(epfrac)\n    # Initial guess at order of convergence, p\n    p1 = (1. / log(ratio_21)) * abs(log(abs(epfrac))) # start_p\n    # Initialise the residual and number of iterations\n    residual = 1.0\n    iterations = 0\n    while abs(residual) > tol\n        # Break if it's all gone bad\n        if float(iterations) > max_res && residual > max_res\n            println(\"Residual out of range or too many iterations\")\n        end\n        # Get the last value\n        p0 = p1\n        # Calculate q\n        q = log((ratio_21^p0 - s) / (ratio_32^p0 - s))\n        # Calculate the p iteration\n        pnew = (1. / log(ratio_21)) * abs(log(abs(epfrac)) + q)\n        # Calculate the relaxation step.\n        p1 = (1. - omega) * p0 + omega * pnew\n        residual = p1 - p0 \n        iterations += 1\n    end\n    # if abs(p1) > 1.0\n    #     return 1.0\n    # else\n    return abs(p1)\n    # end\nend\n\n\n\"\"\" Estimate the zero grid spacing value using richardsons extrapolation and\ntwo grids of reducing resolution (ie grid_1 is finest). The refinement ratio\nis needed. The order of convergence, p, is also required.\n\"\"\"\nfunction richardson_extrapolate(value_1, value_2, ratio_21, p)\n    f_exact = ( ratio_21^p * value_1 - value_2 ) / ( ratio_21^p - 1.0 )\n    return f_exact\nend\n\n\n\"\"\" This routine returns the relative error and extrapolated \nrelative error. The values of the grids and needed along \nwith the extrapolated value.\n\"\"\"\nfunction error_estimates(value_1, value_2, f_exact)\n    # Get the approximate relative error\n    e21a =  abs( (value_1 - value_2) / value_1 )\n    # Get the extrapolated relative error\n    e21ext = abs( ( f_exact - value_1 ) / f_exact )\n    return e21a, e21ext\nend\n\n\n\"\"\" Calculate the fine and coarse grid convergence index for two grids of \nreducing resolution (ie grid_1 is finest). The refinement ration between the \ngrids is required along with the approximate relative error (e21_approx) and \nthe order of convergence, p.\n\"\"\"\nfunction gci(ratio_21, e21_approx, p)\n    # Using a fixed safety factor as per Celik (2008)\n    safety_factor = 1.25\n    # Calculate the gci\n    gci_fine = safety_factor * e21_approx / (ratio_21^p - 1.0)\n    gci_coarse = ratio_21^p * gci_fine\n    return gci_fine, gci_coarse\nend\n\n\n\"\"\" Calculate the ratio in succesive Eps as defined at the bottom of page\n129 in Roache. If the ration is close to one then the asymptotic range has\nbeen reached.\n\"\"\"\nfunction asymptotic_ratio(gci_fine_21, gci_fine_32, ratio_21, p)\n    ratio = ratio_21^p * ( gci_fine_21 / gci_fine_32)\n    return ratio\nend\n\n\n\"\"\"Return the fine GCI value\"\"\"\nfunction GCI_calc(value_1, value_2, value_3, h1, h2, h3)\n    ratio_21 = h2/h1\n    ratio_32 = h3/h2\n    ooc = order_of_convergence(value_1, value_2, value_3, ratio_21, ratio_32)\n    f_exact_21 = richardson_extrapolate(value_1, value_2, ratio_21, ooc)\n    f_exact_32 = richardson_extrapolate(value_2, value_3, ratio_32, ooc)\n    e21a, e21ext = error_estimates(value_1, value_2, f_exact_21)\n    e32a, e32ext = error_estimates(value_2, value_3, f_exact_32)\n    gci_fine_21, gci_coarse_21 = gci(ratio_21, e21a, ooc)\n    gci_fine_32, gci_coarse_32 = gci(ratio_32, e32a, ooc)\n    ratio = asymptotic_ratio(gci_fine_21, gci_fine_32, ratio_21, ooc)\n    return abs(gci_fine_21)\nend\n\n\n\"\"\"Return the fine GCI value\"\"\"\nfunction extrap_value(value_1, value_2, value_3, h1, h2, h3)\n    ratio_21 = h2/h1\n    ratio_32 = h3/h2\n    ooc = order_of_convergence(value_1, value_2, value_3, ratio_21, ratio_32)\n    f_exact_21 = richardson_extrapolate(value_1, value_2, ratio_21, ooc)\n    return abs(f_exact_21)\nend\n\n\n\"\"\"Return the order of convergence.\"\"\"\nfunction ooc_value(value_1, value_2, value_3, h1, h2, h3)\n    ratio_21 = h2/h1\n    ratio_32 = h3/h2\n    ooc = order_of_convergence(value_1, value_2, value_3, ratio_21, ratio_32)\n    return ooc\nend\n", "meta": {"hexsha": "fe4f3a3c37dad791b5402f4e3a5e43cccf0f7567", "size": 5330, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/uncertainty/discretization_error.jl", "max_stars_repo_name": "TAJD/sail_route.jl", "max_stars_repo_head_hexsha": "8f8548188719564f6634868cbe2687a88df1d4a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-08-03T15:34:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T18:05:16.000Z", "max_issues_repo_path": "src/uncertainty/discretization_error.jl", "max_issues_repo_name": "TAJD/SailRoute.jl", "max_issues_repo_head_hexsha": "8f8548188719564f6634868cbe2687a88df1d4a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/uncertainty/discretization_error.jl", "max_forks_repo_name": "TAJD/SailRoute.jl", "max_forks_repo_head_hexsha": "8f8548188719564f6634868cbe2687a88df1d4a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3870967742, "max_line_length": 98, "alphanum_fraction": 0.6833020638, "num_tokens": 1591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.8705972801594706, "lm_q1q2_score": 0.7594632546383636}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.10\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, StatsPlots, Plots\n\tRandom.seed!(0)\n end\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing4.18\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tmu = 20\n\td1, d2 = Normal(mu,mu), Exponential(mu)\n \n\tn = 100\n\tdata1 = rand(d1,n)\n\tdata2 = rand(d2,n)\nend\n\n# ╔═╡ bdabe54e-250a-11eb-1714-25afa772347e\nbegin\n\tqqnorm(data1, c=:blue, ms=3, msw=0, label=\"Normal Data\")\n\tqqnorm!(data2, c=:red, ms=3, msw=0, label=\"Exponential Data\",\n\t\t\txlabel=\"Normal Theoretical Quantiles\",\n\t\t\tylabel=\"Data Quantiles\", legend=true)\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing4.18\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═bdabe54e-250a-11eb-1714-25afa772347e\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "0e2fd8ee81fe2783251c6757b4c5fdc615e3788d", "size": 1125, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/04/listing4.18.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/04/listing4.18.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/04/listing4.18.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 23.4375, "max_line_length": 62, "alphanum_fraction": 0.7235555556, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.8740772351648677, "lm_q1q2_score": 0.7594217004739132}}
{"text": "# Reset the per-thread random seeds to make results reproducible\nreseed!() = for i in 1:Threads.nthreads() Random.seed!(TRNG[i], i) end\n\n\"Per-thread rand()\"\n@inline function trand() \n\t@inbounds rng = TRNG[Threads.threadid()]\n\trand(rng)\nend\n\n@inline function trand(::Type{T}) where T \n\t@inbounds rng = TRNG[Threads.threadid()]\n\trand(rng, T)\nend\n\n@inline function random_vec3_in_sphere(::Type{T}) where T # equiv to random_in_unit_sphere()\n\twhile true\n\t\tp = random_vec3(T(-1), T(1))\n\t\tif p⋅p <= 1\n\t\t\treturn p\n\t\tend\n\tend\nend\n\n@inline random_between(min::T=0, max::T=1) where T = trand(T)*(max-min) + min # equiv to random_double()\n@inline random_vec3(min::T, max::T) where T = @inbounds @SVector[random_between(min, max) for i ∈ 1:3]\n@inline random_vec2(min::T, max::T) where T = @inbounds @SVector[random_between(min, max) for i ∈ 1:2]\n\n\"Random unit vector. Equivalent to C++'s `unit_vector(random_in_unit_sphere())`\"\n@inline random_vec3_on_sphere(::Type{T}) where T = normalize(random_vec3_in_sphere(T))\n\n@inline function random_vec2_in_disk(::Type{T}) where T # equiv to random_in_unit_disk()\n\twhile true\n\t\tp = random_vec2(T(-1), T(1))\n\t\tif p⋅p <= 1\n\t\t\treturn p\n\t\tend\n\tend\nend", "meta": {"hexsha": "5e406ea0444eef90713faff637f533946d0c138d", "size": 1176, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rand.jl", "max_stars_repo_name": "stillyslalom/RayTracingWeekend.jl", "max_stars_repo_head_hexsha": "d5c8f889f35b1f6054bbe3e7551646236d9a985d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 51, "max_stars_repo_stars_event_min_datetime": "2021-12-12T16:47:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T21:39:08.000Z", "max_issues_repo_path": "src/rand.jl", "max_issues_repo_name": "stillyslalom/RayTracingWeekend.jl", "max_issues_repo_head_hexsha": "d5c8f889f35b1f6054bbe3e7551646236d9a985d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-22T10:38:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T10:38:38.000Z", "max_forks_repo_path": "src/rand.jl", "max_forks_repo_name": "stillyslalom/RayTracingWeekend.jl", "max_forks_repo_head_hexsha": "d5c8f889f35b1f6054bbe3e7551646236d9a985d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-12-12T06:30:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T01:37:15.000Z", "avg_line_length": 30.9473684211, "max_line_length": 104, "alphanum_fraction": 0.7015306122, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7593988190121052}}
{"text": "# used when thinking about the `alpha` exponent for xQ\nusing PyPlot\nusing LaTeXStrings\n\nx = collect(linspace(0.,1.,1000))\ny(r) = x.^r\nrs = [1/4,1/3,1/2,2/3,3/4,1.]\n\nfig = plt[:figure](figsize=(5.0,4.0))\nax = fig[:subplots](1,1)\nfs = 10\n\nfor r in rs\n    lw = 1\n    if r == 1/2\n        lw = 3\n    end\n    ax[:plot](x,y(r),label=\"$(@sprintf(\"r=%.2f\",r))\",lw = lw)\nend\n\nax[:set_title](L\"$y=x^r$ for different $r$\",fontsize=fs)\nax[:set_xlabel](L\"x\",fontsize=fs)\nax[:set_ylabel](L\"y=x^r\",fontsize=fs)\nax[:legend]()\n\nsavefig(\"figs/power_comparison.pdf\",dpi=300,transparent=true)\n", "meta": {"hexsha": "8245e7e291af0812c9a3e250374376577f27ac39", "size": 572, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "plot_root_comparison.jl", "max_stars_repo_name": "COHRINT/FaMSeC", "max_stars_repo_head_hexsha": "91fffe8913abc3c187fe70fd45892330453f6a24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plot_root_comparison.jl", "max_issues_repo_name": "COHRINT/FaMSeC", "max_issues_repo_head_hexsha": "91fffe8913abc3c187fe70fd45892330453f6a24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plot_root_comparison.jl", "max_forks_repo_name": "COHRINT/FaMSeC", "max_forks_repo_head_hexsha": "91fffe8913abc3c187fe70fd45892330453f6a24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1851851852, "max_line_length": 61, "alphanum_fraction": 0.6153846154, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605945, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7593988151406741}}
{"text": "# Verify discretization technique by simulating income generating process\n# and markov chain simulation for T_ret periods and then comparing distributions\n\nusing Plots, LinearAlgebra, Statistics, Random, Roots, QuantEcon, Interpolations\nusing BenchmarkTools\n\n# Simulate income generating process\n# Parameters\n## Demographics\nN = 1000000\nT_ret = 10\nκ = zeros(T_ret)\n\n# Directly from KV2010\nσ_η = 0.01\nσ_z0 = 0.15\nσ_ε = 0.05\n\nfunction net_labor_income(N, T_ret, σ_ε, σ_η, σ_z0, κ)\n    Y = zeros(Float64, N, T_ret-1)\n    z_t1 = sqrt(σ_z0) .* randn(N)\n\n    for t in 1:(T_ret-1)\n        z_t = z_t1 + sqrt(σ_η) .* randn(N)\n        Y[:,t] = exp.( κ[t] .+ z_t + sqrt(σ_ε) .* randn(N) )\n        z_t1 = copy(z_t)\n    end\n    return Y\nend\n\nY_igp = net_labor_income(N, T_ret, σ_ε, σ_η, σ_z0, κ)\nhistogram(Y_igp[:,1], alpha = 0.3, bins = 100)\nhistogram!(Y_igp[:,end], alpha = 0.3, bins = 100)\nmeans = mean(Y_igp,dims=1)'\nvars = var(Y_igp,dims=1)'\nplot(1:(T_ret-1), means, label=\"means\")\nplot!(1:(T_ret-1), vars, label=\"vars\", xlabel=\"t\")\n\n\n\n# Tauchen discretization\ntauc_ε = tauchen(19,0.,sqrt(σ_ε))\ntauc_η = tauchen(39,0.99999,sqrt(σ_η))\n\ntauc_ε.p\n", "meta": {"hexsha": "583bbe10766aaf78982371aaa524060f90aefda2", "size": 1136, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/persistent discretization test.jl", "max_stars_repo_name": "alpeters/KaplanViolante2010", "max_stars_repo_head_hexsha": "642b9d6acd9b4bccfa5b9043ee490f2faf7cce57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-22T19:45:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-22T19:45:38.000Z", "max_issues_repo_path": "test/persistent discretization test.jl", "max_issues_repo_name": "alpeters/KaplanViolante2010", "max_issues_repo_head_hexsha": "642b9d6acd9b4bccfa5b9043ee490f2faf7cce57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/persistent discretization test.jl", "max_forks_repo_name": "alpeters/KaplanViolante2010", "max_forks_repo_head_hexsha": "642b9d6acd9b4bccfa5b9043ee490f2faf7cce57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6956521739, "max_line_length": 80, "alphanum_fraction": 0.6716549296, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7593988076205381}}
{"text": "```\nCentral difference\n\n```\nfunction central_diff(\n    y::AbstractArray{<:AbstractFloat,1},\n    x::AbstractArray{<:AbstractFloat,1},\n)\n\n    dy = zeros(eltype(y), axes(y))\n\n    idx = eachindex(y) |> collect\n    i0 = idx[1]\n    i1 = idx[end]\n\n    dy[i0] = (y[i0+1] - y[i0]) / (x[i0+1] - x[i0])\n    dy[i1] = (y[i1] - y[i1-1]) / (x[i1] - x[i1-1])\n    for i = i0+1:i1-1\n        dy[i] = (y[i+1] - y[i-1]) / (x[i+1] - x[i-1])\n    end\n\n    return dy\n\nend\n\n\nfunction central_diff(y::AbstractArray{<:AbstractFloat,1}, dx::Real)\n    x = ones(eltype(y), axes(y)) .* dx\n    dy = central_diff(y, x)\n\n    return dy\nend\n\n\nfunction central_diff!(\n    dy::AbstractArray{<:AbstractFloat,1},\n    y::AbstractArray{<:AbstractFloat,1},\n    x::AbstractArray{<:AbstractFloat,1},\n)\n\n    @assert axes(dy) == axes(y) == axes(x)\n\n    idx = eachindex(y) |> collect\n    i0 = idx[1]\n    i1 = idx[end]\n\n    dy[i0] = (y[i0+1] - y[i0]) / (x[i0+1] - x[i0])\n    dy[i1] = (y[i1] - y[i1-1]) / (x[i1] - x[i1-1])\n    for i = i0+1:i1-1\n        dy[i] = (y[i+1] - y[i-1]) / (x[i+1] - x[i-1])\n    end\n\nend\n\n\nfunction central_diff!(\n    dy::AbstractArray{<:AbstractFloat,1},\n    y::AbstractArray{<:AbstractFloat,1},\n    dx::Real,\n)\n    x = ones(eltype(y), axes(y)) .* dx\n    central_diff!(dy, y, x)\nend\n\n\n```\nUpwind difference\n\n```\nfunction upwind_diff(\n    y::AbstractArray{<:Real,1},\n    x::AbstractArray{<:Real,1};\n    stream = :right::Symbol,\n)\n\n    dy = zeros(eltype(y), axes(y))\n\n    idx = eachindex(y) |> collect\n    i0 = idx[1]\n    i1 = idx[end]\n\n    if stream == :right\n        dy[i0] = 0.0\n        for i = i0+1:i1\n            dy[i] = (y[i] - y[i-1]) / (x[i] - x[i-1])\n        end\n    elseif stream == :left\n        dy[i1] = 0.0\n        for i = i0:i1-1\n            dy[i] = (y[i+1] - y[i]) / (x[i+1] - x[i])\n        end\n    else\n        throw(\"streaming direction should be :left or :right\")\n    end\n\n    return dy\n\nend\n\n\nfunction upwind_diff(y::AbstractArray{<:AbstractFloat,1}, dx::Real; stream = :right::Symbol)\n    x = ones(eltype(y), axes(y)) .* dx\n    dy = upwind_diff(y, x, stream = stream)\n\n    return dy\nend\n\n\nfunction upwind_diff!(\n    dy::AbstractArray{<:AbstractFloat,1},\n    y::AbstractArray{<:AbstractFloat,1},\n    x::AbstractArray{<:AbstractFloat,1};\n    stream = :right::Symbol,\n)\n\n    @assert axes(dy) == axes(y) == axes(x)\n\n    idx = eachindex(y) |> collect\n    i0 = idx[1]\n    i1 = idx[end]\n\n    if stream == :right\n        dy[i0] = 0.0\n        for i = i0+1:i1\n            dy[i] = (y[i] - y[i-1]) / (x[i] - x[i-1])\n        end\n    elseif stream == :left\n        dy[i1] = 0.0\n        for i = i0:i1-1\n            dy[i] = (y[i+1] - y[i]) / (x[i+1] - x[i])\n        end\n    else\n        throw(\"streaming direction should be :left or :right\")\n    end\n\n    return dy\n\nend\n\n\nfunction upwind_diff!(\n    dy::AbstractArray{<:AbstractFloat,1},\n    y::AbstractArray{<:AbstractFloat,1},\n    dx::Real;\n    stream = :right::Symbol,\n)\n    x = ones(eltype(y), axes(y)) .* dx\n    upwind_diff!(dy, y, x, stream = stream)\nend\n", "meta": {"hexsha": "22272cc04d26f735afb326712e87557d07f84ce3", "size": 2986, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/diff.jl", "max_stars_repo_name": "vavrines/Kinnosuke.jl", "max_stars_repo_head_hexsha": "ae9b73ca16b70fb97c19775dfbfde7564273e58d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/diff.jl", "max_issues_repo_name": "vavrines/Kinnosuke.jl", "max_issues_repo_head_hexsha": "ae9b73ca16b70fb97c19775dfbfde7564273e58d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/diff.jl", "max_forks_repo_name": "vavrines/Kinnosuke.jl", "max_forks_repo_head_hexsha": "ae9b73ca16b70fb97c19775dfbfde7564273e58d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9066666667, "max_line_length": 92, "alphanum_fraction": 0.5247823175, "num_tokens": 1086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7593988037119864}}
{"text": "\n\n\"\"\"\n    laplace_to_z(rho, n, N, dt, A, b)\n\nReturns the complex matrix valued Laplace variable s that correspond to the\nvariable z = rho*exp(2*im*pi*n/N) for a given Butcher tableau (A,b,c) and a time step dt.\n\"\"\"\nfunction laplace_to_z(rho, n, N, dt, A, b)\n\tz = rho * exp(2*im*pi*n/N);\n\ts = inv(dt * (A + ones(b) * b' / (z-1)));\n\treturn s;\nend\n\n\"\"\"\n    inverse_z_transform(k, rho, N, X)\n\nReturns the k-th term of the inverse z-transform. X is an array of the z-transform\nevaluated in the points z=rho*exp(2*im*pi*n/N) for n in 0:(N-1).\n\"\"\"\nfunction inverse_z_transform(k, rho, N, X::AbstractArray{T,1}) where T\n\treturn ((rho^k) / N) * sum(n -> X[n+1] * exp(2*im*pi*k*n/N), 0:(N-1));\nend\n\n\"\"\"\n    real_inverse_z_transform(k, rho, N, X)\n\nReturns the k-th term of the inverse z-transform.\nIt is assumed that X[n+1] = conj(X[N-n]) for each n in 1:(N-1)\nso that Nmax = N/2+1 or (N+1)/2 (resp. if N%2==0 or N%2==1) terms are used in X\nX is an array of the z-transform\nevaluated in the points z=rho*exp(2*im*pi*n/N) for n in 0:(Nmax-1).\n\"\"\"\nfunction real_inverse_z_transform(k, rho, N, X::AbstractArray{T,1}) where T\n\tNmax = (N+1)>>1;\n\trealTerms = (N%2==0) ? real(X[1]) + (-1)^k * real(X[Nmax+1]) : real(X[1]);\n\treturn ((rho^k) / N) * (realTerms + 2*sum(n -> real(X[n+1] * exp(2*im*pi*k*n/N)), 1:(Nmax-1)));\nend\n", "meta": {"hexsha": "e0ea789c55d9ba99e8801c9a7cb7ce5c3376c9dd", "size": 1306, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/timedomain/zdomain.jl", "max_stars_repo_name": "HoBeZwe/BEAST.jl", "max_stars_repo_head_hexsha": "aa122c9eef0435c8b958f5d257be8f6f5793d422", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2018-06-25T21:04:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T12:29:20.000Z", "max_issues_repo_path": "src/timedomain/zdomain.jl", "max_issues_repo_name": "HoBeZwe/BEAST.jl", "max_issues_repo_head_hexsha": "aa122c9eef0435c8b958f5d257be8f6f5793d422", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2017-05-16T16:25:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T00:39:41.000Z", "max_forks_repo_path": "src/timedomain/zdomain.jl", "max_forks_repo_name": "HoBeZwe/BEAST.jl", "max_forks_repo_head_hexsha": "aa122c9eef0435c8b958f5d257be8f6f5793d422", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2017-05-12T10:28:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T09:50:24.000Z", "avg_line_length": 33.4871794872, "max_line_length": 96, "alphanum_fraction": 0.624042879, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642906, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7593958885588002}}
{"text": "@doc raw\"\"\"\nPathIntegralTrigonometric is a path integral along a cos^2/sin^2 path\n\n```math\n\\phi (\\tau; q^-, q^+) = \\cos^2 (\\pi \\tau / 2) q^- + \\sin^2 (\\pi \\tau / 2) q^+ .\n```\n\"\"\"\nstruct PathIntegralTrigonometric <: PathIntegral end\n\nevaluate_l(path::PathIntegralTrigonometric, τ::T) where {T} = cos(π/2*τ)^2\nevaluate_r(path::PathIntegralTrigonometric, τ::T) where {T} = sin(π/2*τ)^2\n\nderivative_l(path::PathIntegralTrigonometric, τ::T) where {T} = -π*sin(π/2*τ)*cos(π/2*τ)\nderivative_r(path::PathIntegralTrigonometric, τ::T) where {T} = +π*sin(π/2*τ)*cos(π/2*τ)\n", "meta": {"hexsha": "2ec302c9742255f4a4e8c2807f3819627e1c9be8", "size": 562, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/discontinuities/path_integral_trigonometric.jl", "max_stars_repo_name": "JuliaGNI/GeometricIntegrators.jl", "max_stars_repo_head_hexsha": "bf1ca810d75e43c1d89e4981beea35451858155a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-12-29T10:41:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T11:48:39.000Z", "max_issues_repo_path": "src/discontinuities/path_integral_trigonometric.jl", "max_issues_repo_name": "JuliaGNI/GeometricIntegrators.jl", "max_issues_repo_head_hexsha": "bf1ca810d75e43c1d89e4981beea35451858155a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2020-11-16T16:45:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T17:51:11.000Z", "max_forks_repo_path": "src/discontinuities/path_integral_trigonometric.jl", "max_forks_repo_name": "michakraus/GeometricIntegrators.jl", "max_forks_repo_head_hexsha": "fcca462f25a1f9d5ff0954d5d71ef7cd1389ab3e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-05T12:54:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T18:19:13.000Z", "avg_line_length": 37.4666666667, "max_line_length": 88, "alphanum_fraction": 0.6690391459, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970239909496136, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.759370367826754}}
{"text": "export awa\n\n\"\"\"\n    awa(twa, v_s, v_t)\n\nCalculate the apparent wind angle given true wind angle, boat speed and wind speed.\n\n# Example\n\n```jldoctest\nusing sail_route\nc_awa = sail_route.awa(60, 3.086, 5.144)\nisapprox(0.6669807044553968, c_awa, rtol=3)\n\n# output\n\ntrue\n```\n\"\"\"\nfunction awa(twa::Float64, v_s::Float64, v_t::Float64)\n    return atan(sind(twa)/(cosd(twa) + v_s/v_t))\nend\n", "meta": {"hexsha": "711fc4b1e0605dcbd1d5db18f7d75153ad1216a6", "size": 383, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/performance/aerodynamics.jl", "max_stars_repo_name": "TAJD/sail_route_old.jl", "max_stars_repo_head_hexsha": "41bb26cd3407bfa5d090464fe18e5a7ba7e0bb56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/performance/aerodynamics.jl", "max_issues_repo_name": "TAJD/sail_route_old.jl", "max_issues_repo_head_hexsha": "41bb26cd3407bfa5d090464fe18e5a7ba7e0bb56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/performance/aerodynamics.jl", "max_forks_repo_name": "TAJD/sail_route_old.jl", "max_forks_repo_head_hexsha": "41bb26cd3407bfa5d090464fe18e5a7ba7e0bb56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.652173913, "max_line_length": 83, "alphanum_fraction": 0.6971279373, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7593585045656975}}
{"text": "# Distance metrics for kernel functions\n\nδ(Φ, z) = diff(Φ) ./ diff(z)\n\n\"\"\"\n    sq_mag(a, b)\n\n||a - b||^2 = norm(a - b)^2 but more efficient.\n\"\"\"\nfunction sq_mag(a, b)\n    ll = 0.0\n    @inbounds for k in 1:length(a)\n        ll += (a[k] - b[k])^2\n    end\n    return ll\nend\n\n\"\"\"\n    euclidean_distance(a, b, z)\n\nComputes the Euclidean distance (l²-norm) between two vectors:\n\n    d(x, x') = || x - x' ||\n\"\"\"\n@inline euclidean_distance(a, b, z) = sqrt(sq_mag(a, b))\n\n@inline euclidean_distance(a, b) = sqrt(sq_mag(a, b))\n\n\"\"\"\n    derivative_distance(a, b, z)\n\nComputes the H¹-norm with respect to z of two vectors:\n\n    d(x, x') = || diff(x) / diff(z) - diff(x') / diff(z) ||\n\"\"\"\n@inline derivative_distance(a, b, z) = sqrt(sq_mag( δ(a, z), δ(b, z) ))\n\n\"\"\"\n    antiderivative_distance(a, b, z)\n\nComputes the H⁻¹-norm with respect to z of two vectors:\n\n    d(x, x′) = || diff(x) * diff(z) - diff(x') * diff(z) ||\n\"\"\"\n@inline antiderivative_distance(a,b,z) = sqrt(sq_mag(diff(a) .* diff(z), diff(b) .* diff(z)))\n", "meta": {"hexsha": "0389efa3ee685ff3e0b2aa3a07665f10513fc901", "size": 1006, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GaussianProcesses/distances.jl", "max_stars_repo_name": "CliMA/ClimateParameterizations.jl", "max_stars_repo_head_hexsha": "1263e2edefced4e03e925d6bfa60ba1f1940e8c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2020-12-23T06:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:05:51.000Z", "max_issues_repo_path": "src/GaussianProcesses/distances.jl", "max_issues_repo_name": "CliMA/OceanParameterizations.jl", "max_issues_repo_head_hexsha": "5942c66ba8724b9661db170acb239ca3a2abd5c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-12-05T02:43:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T14:27:03.000Z", "max_forks_repo_path": "src/GaussianProcesses/distances.jl", "max_forks_repo_name": "ali-ramadhan/ClimateParameterizations.jl", "max_forks_repo_head_hexsha": "1263e2edefced4e03e925d6bfa60ba1f1940e8c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-17T18:06:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T18:06:40.000Z", "avg_line_length": 21.8695652174, "max_line_length": 93, "alphanum_fraction": 0.5795228628, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462514578343, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7593585024070719}}
{"text": "module Wynn\n    using SymPy\n\n    # data structure to store the epsilon table\n    # ϵ_ij indexed by ints i & j, stored within dict.\n    struct EpsilonTable{T}\n        series::T\n        terms::Vector{T}\n        etable::Dict{Tuple{Int,Int},T}\n    end\n\n    function EpsilonTable(terms::Vector{T}; simplified::Bool = true) where T<:Union{Float64,Sym}\n        # maximum occuring i & j index\n        max_ind = length(terms)\n\n        # setting base case j = -1\n        etable = Dict((i, -1) => eltype(terms)(0) for i in 0:max_ind)\n\n        # setting base case j = 0, i = 0:max_ind-1\n        merge!(etable, Dict((i-1, 0) => sum(terms[1:i]) for i in 1:max_ind))\n\n        # setting base case i = -j-1, j even\n        merge!(etable, Dict((-j-1, 2j) => eltype(terms)(0) for j in 0:max_ind))\n\n        # setting base case for odd j\n        merge!(etable, Dict((-j-1, 2j-1) => eltype(terms)(0) for j in 0:max_ind))\n\n        # recursive calculations, j>=1, i = floor(Int,-j/2):(max_ind-j-1)\n        for j in 1:2*(max_ind-1), i in floor(Int,-j/2):(max_ind-j-1)#j-1\n            ϵ_ij = etable[i+1, j-2] + 1 / (etable[i+1, j-1] - etable[i, j-1])\n            eltype(terms) <: Sym && simplified ? push!(etable, (i, j) =>\n                simplify(ϵ_ij)) : push!(etable, (i, j) => ϵ_ij)\n        end\n        series = sum(terms)\n        EpsilonTable(series, terms, etable)\n    end\n\n    EpsilonTable(terms::Vector{Int}; simplified::Bool = true) = EpsilonTable(convert(Vector{Float64}, terms); simplified = simplified)\n\n\n    # recursive function to generate just one term of the epsilon table, much more efficient.\n    function epsilon(terms::Vector{T}, order::Tuple{Int,Int}; simplified::Bool = true) where T<:Union{Real,Sym}\n        max_ind = length(terms)\n        if order[2] == -1\n            return 0\n        elseif (0 <= order[1] < max_ind) && (order[2] == 0)\n            return sum(terms[1:order[1]+1])\n        elseif iseven(order[2]) && (order[1] == -order[2]/2-1)\n            return 0\n        elseif isodd(order[2]) && (order[1] == -(order[2]+1)/2-1)\n            return 0\n        end\n        max_ind = length(terms)\n        ϵ_order = epsilon(terms, (order[1]+1, order[2]-2)) + 1 / (epsilon(terms, (order[1]+1, order[2]-1)) - epsilon(terms, (order[1], order[2]-1)))\n        if (eltype(terms) <: Sym) && simplified\n            return simplify(ϵ_order)\n        else\n            return ϵ_order\n        end\n    end\n\n    export EpsilonTable, epsilon\nend\n", "meta": {"hexsha": "1444b9fc87385b2cc6ec9a5b7d0ffcdce3dacc77", "size": 2428, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Wynn.jl", "max_stars_repo_name": "J-Revell/Wynn", "max_stars_repo_head_hexsha": "d4bc9d55fd69133e04216e42d3af6f2d94cbceaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-03-17T15:42:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T19:14:30.000Z", "max_issues_repo_path": "src/Wynn.jl", "max_issues_repo_name": "J-Revell/Wynn.jl", "max_issues_repo_head_hexsha": "d4bc9d55fd69133e04216e42d3af6f2d94cbceaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Wynn.jl", "max_forks_repo_name": "J-Revell/Wynn.jl", "max_forks_repo_head_hexsha": "d4bc9d55fd69133e04216e42d3af6f2d94cbceaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9375, "max_line_length": 148, "alphanum_fraction": 0.5646622735, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7593584972821937}}
{"text": "\"\"\"\nap_test_fm(re, factors)\n\nCROSS-SECTIONAL TESTS USING THE FAMA-MACBETH REGRESSION\n\nFama-MacBeth standard errors do not include corrections for the fact that the betas are also estimated.\n\nINPUTS\n`re': T x N matrix of excess returns, where T is the number of periods for each test assets and N is the number of test assets\n`factors': T x K matrix of factors. Factors must be excess returns for time-series tests\n\nOUTPUTS\n`lambda': T x K vector of risk premiums for the factors\n`alpha': T x N vector of alphas for each test assets\n\n`test_statistics': Wald-statistics of the asset pricing test using Fama-MacBeth procedure\n`pvalue': pvalue of the test statistics. The test statistics has a Chi-square distribution.\n\n\"\"\"\n\nfunction ap_test_fm(re, factors)\n    (T, K) = size(factors);\n    N = size(re, 2);\n    cov_f = cov(factors); # coviance matrix for the factors K x K\n\n    X = [ones(T,1) factors];\n    (a, beta, resid, cov_resid) = OLSFn(re, X) # First-stage time-series regressions to obatin betas N x K\n\n    lambda = fill(NaN, (T, K))\n    alpha = fill(NaN, (T, N))\n    \n    for t = 1:T # run cross-sectional regressions for each period\n        lambda[t, :] = ((beta' * beta) \\  (beta' * vec(re[t, :])))'; # 1 x K\n        alpha[t, :] = re[t, :]' - lambda[t, :]' * beta';\n    end\n\n    alpha_mean = mean(alpha, dims = 1)'; # time-series average of alphas N x 1\n    alpha_mean_cov = zeros(N, N);\n        \n    for t = 1:T\n        alpha_mean_cov = alpha_mean_cov + (alpha[t, :] - alpha_mean) * (alpha[t, :] - alpha_mean)';\n    end\n    alpha_mean_cov = alpha_mean_cov ./ T^2;\n    \n    test_statistics = alpha_mean' * (alpha_mean_cov \\ alpha_mean);\n    pvalue = 1.0 .- cdf.(Chisq(N - K), test_statistics);\n\n    return (alpha_mean, test_statistics, pvalue)\nend\n", "meta": {"hexsha": "33c7c1dd6a3a08d98ecba9fa83fa27177cb29434", "size": 1755, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ap_test_fm.jl", "max_stars_repo_name": "yingxiangli/Linear-Factor-Model-and-Random-Walk-Tests", "max_stars_repo_head_hexsha": "0d844c9e8b383b7239727379e11d7149144cfd63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-13T12:56:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-13T12:56:24.000Z", "max_issues_repo_path": "src/ap_test_fm.jl", "max_issues_repo_name": "yingxiangli/Linear-Factor-Model-and-Random-Walk-Tests", "max_issues_repo_head_hexsha": "0d844c9e8b383b7239727379e11d7149144cfd63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ap_test_fm.jl", "max_forks_repo_name": "yingxiangli/Linear-Factor-Model-and-Random-Walk-Tests", "max_forks_repo_head_hexsha": "0d844c9e8b383b7239727379e11d7149144cfd63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1, "max_line_length": 126, "alphanum_fraction": 0.6621082621, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7593584956632247}}
{"text": "# This script solves a parabolic partial differential equation\n\nusing LinearAlgebra\n\n# Define the paths\nCURRENT_DIR = @__DIR__\nROOT_DIR = basename(CURRENT_DIR) == \"scripts\" ? dirname(CURRENT_DIR) : CURRENT_DIR\nTABLES = joinpath(ROOT_DIR, \"tables\")\n\n# Prepare the output directories\nmkpath(TABLES)\n\n# Define the maximum time\nT = 0.1\n\n# Define the differential equation's functions\np(x) = x + 3\nb(_, _) = 0\nc(x, _) = -x\nα₁(t) = 0\nα₂(t) = -1\nβ₁(t) = 1\nβ₂(t) = 0\n\n# Define the first problem's functions\nu(x, t) = x + 3t\nf(x, t) = x^2 + 3 * x * t + 2\nφ(x) = x\nα(t) = 1\nβ(t) = 1 + 3t\n\n\"Check if a solution will be stable on the specified grid\"\nfunction is_stable(N, M)::Bool\n    A = maximum(p, 0:0.0001:1)\n    h = 1 / N\n    τ = T / M\n    ν = τ / h^2\n    return A * ν ≤ 0.5\nend\n\n\"Using provided N, find M, which gives a stable solution\"\nfunction find_stable(N)::Int\n    M = 5\n    while !is_stable(N, M)\n        M *= 2\n    end\n    return M\nend\n\n\"Calculate the value of the differential operator L\"\nfunction L(um, x, t, h, i, k)::Float64\n    return p(x[i] + h / 2) * (um[k, i+1] - um[k, i]) / h^2 -\n           p(x[i] - h / 2) * (um[k, i] - um[k, i-1]) / h^2 +\n           b(x[i], t[k]) * (um[k, i+1] - um[k, i-1]) / (2h) +\n           c(x[i], t[k]) * um[k, i]\nend\n\n\"Solve the problem for the specified grid, return the solution matrix\"\nfunction solve(N, M, h, τ, x, t; σ = 0)::Matrix{Float64}\n    # Prepare a matrix for the solution\n    # (number of columns is the number of nodes for x's)\n    um = Matrix{Float64}(undef, M + 1, N + 1)\n    # Compute the first layer\n    um[1, :] .= φ.(x)\n    if σ == 0\n        # Use the explicit scheme for other layers\n        for k = 2:M+1\n            # Compute for i in 2:N\n            for i = 2:N\n                um[k, i] = um[k-1, i] +\n                           τ * (L(um, x, t, h, i, k - 1) +\n                                f(x[i], t[k-1]))\n            end\n            # Compute the rest\n            um[k, 1] = (α(t[k]) + α₂(t[k]) * (4 * um[k, 2] - um[k, 3]) / (2h)) /\n                       (α₁(t[k]) + 3 * α₂(t[k]) / (2h))\n            um[k, N+1] = (β(t[k]) + β₂(t[k]) * (4 * um[k, N] - um[k, N-1]) / (2h)) /\n                         (β₁(t[k]) + 3 * β₂(t[k]) / (2h))\n        end\n    else\n        # Use the implicit scheme for other layers\n        for k = 2:M+1\n            # Compute the linear system's matrix\n            tm = Tridiagonal(\n                # A's\n                [\n                    [σ * (p(x[i] - h / 2) / h^2 - b(x[i], t[k]) / (2h)) for i = 2:N]\n                    -β₂(t[k]) / h\n                ],\n                # B's\n                [\n                    α₁(t[k]) + α₂(t[k]) / h\n                    -[1 / τ + σ * ((p(x[i] + h / 2) + p(x[i] - h / 2)) / h^2 - c(x[i], t[i])) for i = 2:N]\n                    β₁(t[k]) + β₂(t[k]) / h\n                ],\n                # C's\n                [\n                    -α₂(t[k]) / h\n                    [σ * (p(x[i] + h / 2) / h^2 + b(x[i], t[k]) / (2h)) for i = 2:N]\n                ],\n            )\n            # Compute the linear system's right-hand side vector\n            g = [\n                α(t[k])\n                [-um[k-1, i] / τ - (1 - σ) * L(um, x, t, h, i, k - 1) - f(x[i], t[k] - (1 - σ) * τ) for i = 2:N]\n                β(t[k])\n            ]\n            # Compute the solution of the linear system\n            um[k, :] = tm \\ g\n        end\n    end\n    return um\nend\n\n\"\"\"\nCompare the approximate solution to the exact one,\nfind the biggest absolute difference between the nodes\n\"\"\"\nfunction max_difference(um, x, t)::Float64\n    M1, N1 = size(um)\n    # Find the maximum\n    Δu = 0\n    for i = 1:N1, k = 1:M1\n        _Δu = abs(u(x[i], t[k]) - um[k, i])\n        if _Δu > Δu\n            Δu = _Δu\n        end\n    end\n    return Δu\nend\n\n\"Create the TeX tables and write them to disk\"\nfunction tables(dir, digits, um, N, M)\n    # Prepare the output directories\n    OUTPUT_DIR = joinpath(TABLES, dir)\n    mkpath(OUTPUT_DIR)\n    # Create and write the table with the solution grid\n    open(joinpath(OUTPUT_DIR, \"$N, $M.tex\"), \"w\") do io\n        for k in Int.([1:M/5:M+1]...)\n            s = \"\"\n            for i in Int.([1:N/5:N+1]...)\n                s = \"$(s)& \\$ $(sprint(show, round(um[k, i]; digits))) \\$ \"\n            end\n            s = \"$(s)\\\\\\\\\"\n            println(io, s)\n        end\n    end\nend\n\n\"\"\"\nSolve the specified problem for different grids,\ncreate the TeX tables and write them to disk\n\"\"\"\nfunction solve_all(dir, digits)\n    # Print the output directory\n    println('\\n', \" \"^5, \"> Output for u(x, t) = \", dir)\n    # Define grids\n    N = [5, 10, 20]\n    Mₑ = find_stable.(N)\n    Mᵢ = repeat([Int(1 / (0.1 / 100))], length(N))\n    # For each grid\n    for l in eachindex(N)\n        # Compute the steps\n        h = 1 / N[l]\n        τₑ = T / Mₑ[l]\n        τᵢ = T / Mᵢ[l]\n        # Compute the nodes\n        x = [j * h for j = 0:N[l]]\n        tₑ = [j * τₑ for j = 0:Mₑ[l]]\n        tᵢ = [j * τᵢ for j = 0:Mᵢ[l]]\n        # Solve the problem with the explicit scheme\n        um = solve(N[l], Mₑ[l], h, τₑ, x, tₑ)\n        # Print info about the solution\n        println(\n            '\\n',\n            \" \"^5, \"σ: 0\", '\\n',\n            \" \"^5, \"N: \", N[l], '\\n',\n            \" \"^5, \"M: \", Mₑ[l], '\\n',\n            \" \"^5, \"Δu: \", max_difference(um, x, tₑ)\n        )\n        # Create and write the tables\n        tables(joinpath(dir, \"σ = 0\"), digits, um, N[l], Mₑ[l])\n        # Solve the problem with the implicit scheme (σ = 0.5)\n        um = solve(N[l], Mᵢ[l], h, τᵢ, x, tᵢ; σ = 0.5)\n        # Print info about the solution\n        println(\n            '\\n',\n            \" \"^5, \"σ: 0.5\", '\\n',\n            \" \"^5, \"N: \", N[l], '\\n',\n            \" \"^5, \"M: \", Mᵢ[l], '\\n',\n            \" \"^5, \"Δu: \", max_difference(um, x, tᵢ)\n        )\n        # Create and write the tables\n        tables(joinpath(dir, \"σ = 0.5\"), digits, um, N[l], Mᵢ[l])\n        # Solve the problem with the implicit scheme (σ = 1)\n        um = solve(N[l], Mᵢ[l], h, τᵢ, x, tᵢ; σ = 1.0)\n        # Print info about the solution\n        println(\n            '\\n',\n            \" \"^5, \"σ: 1.0\", '\\n',\n            \" \"^5, \"N: \", N[l], '\\n',\n            \" \"^5, \"M: \", Mᵢ[l], '\\n',\n            \" \"^5, \"Δu: \", max_difference(um, x, tᵢ)\n        )\n        # Create and write the tables\n        tables(joinpath(dir, \"σ = 1.0\"), digits, um, N[l], Mᵢ[l])\n    end\nend\n\n# Solve the first problem\nsolve_all(\"x + 3t\", 2)\n\n# Define the second problem's functions\nu(x, t) = x^3 + t^3\nf(x, t) = x^4 + x * t^3 - 9 * x^2 + 3 * t^2 - 18 * x\nφ(x) = x^3\nα(t) = 0\nβ(t) = 1 + t^3\n\n# Solve the second problem\nsolve_all(\"x^3 + t^3\", 6)\n\nprintln()\n", "meta": {"hexsha": "914378f7eaa02c4d00d4b5d5fd174db8d52b79f5", "size": 6595, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "A2/scripts/script.jl", "max_stars_repo_name": "paveloom-university/Computational-Workshop-S09-2021", "max_stars_repo_head_hexsha": "d8efe691d9af333f00b45c50ad2ffb69e5fc4aef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A2/scripts/script.jl", "max_issues_repo_name": "paveloom-university/Computational-Workshop-S09-2021", "max_issues_repo_head_hexsha": "d8efe691d9af333f00b45c50ad2ffb69e5fc4aef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A2/scripts/script.jl", "max_forks_repo_name": "paveloom-university/Computational-Workshop-S09-2021", "max_forks_repo_head_hexsha": "d8efe691d9af333f00b45c50ad2ffb69e5fc4aef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4419642857, "max_line_length": 112, "alphanum_fraction": 0.4454890068, "num_tokens": 2324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7593584910100813}}
{"text": "# Julia GARCH package\n# Copyright 2013 Andrey Kolev\n# Distributed under MIT license (see LICENSE.md)\n\ntype GarchFit\n  data::Vector\n  params::Vector\n  llh::Float64\n  status::Symbol\n  converged::Bool\n  sigma::Vector\n  hessian::Array{Float64,2}\n  cvar::Array{Float64,2}\n  secoef::Vector\n  tval::Vector\nend\n\nfunction Base.show(io::IO ,fit::GarchFit)\n  pnorm(x) = 0.5*(1+erf(x/sqrt(2)))\n  prt(x) = 2*(1-pnorm(abs(x)))\n  @printf io \"Fitted garch model \\n\"\n  @printf io \" * Coefficient(s): \\tomega \\t\\talpha \\t\\tbeta\\n\"\n  @printf io \"   \\t\\t\\t%f\\t%f\\t%f\\n\" fit.params[1] fit.params[2] fit.params[3]\n  @printf io \" * Log Likelihood: %f\\n\" fit.llh\n  @printf io \" * Converged: %s\\n\" fit.converged\n  @printf io \" * Solver status: %s\\n\\n\" fit.status\n  println(io,\" * Standardised Residuals Tests:\")\n  println(io,\"   \\t\\t\\t\\tStatistic\\tp-Value\")\n  jbstat,jbp = jbtest(fit.data./fit.sigma);\n  @printf io \"   Jarque-Bera Test\\t\\U1D6D8\\u00B2\\t%.6f\\t%.6f\\n\\n\" jbstat jbp\n  println(io,\" * Error Analysis:\")\n  println(io,\"   \\t\\tEstimate\\t\\Std.Error\\tt value \\tPr(>|t|)\")\n  @printf io \"   omega\\t%f\\t%f\\t%f\\t%f\\n\" fit.params[1] fit.secoef[1] fit.tval[1] prt(fit.tval[1])\n  @printf io \"   alpha\\t%f\\t%f\\t%f\\t%f\\n\" fit.params[2] fit.secoef[2] fit.tval[2] prt(fit.tval[2])\n  @printf io \"   beta \\t%f\\t%f\\t%f\\t%f\\n\"  fit.params[3] fit.secoef[3] fit.tval[3] prt(fit.tval[3])\nend\n\nfunction cdHessian(par,LLH)\n  eps = 1e-4 * par\n  n = length(par)\n  H = zeros(n,n)\n  for(i = 1:n)\n    for(j = 1:n)\n      x1 = copy(par) \n      x1[i] += eps[i]\n      x1[j] += eps[j] \n      x2 = copy(par)\n      x2[i] += eps[i]\n      x2[j] -= eps[j]\n      x3 = copy(par)\n      x3[i] -= eps[i]\n      x3[j] += eps[j]\n      x4 = copy(par)\n      x4[i] -= eps[i]\n      x4[j] -= eps[j]\n      H[i,j] = (LLH(x1)-LLH(x2)-LLH(x3)+LLH(x4)) / (4.*eps[i]*eps[j])\n    end\n  end\n  H\nend\n\nfunction garchLLH(rets::Vector,x::Vector)\n  rets2   = rets.^2;\n  T = length(rets); \n  ht = zeros(T);\n  omega,alpha,beta = x;\n  ht[1] = sum(rets2)/T;\n  for i=2:T\n    ht[i] = omega + alpha*rets2[i-1] + beta * ht[i-1];\n  end\n  -0.5*(T-1)*log(2*pi)-0.5*sum( log(ht) + (rets./sqrt(ht)).^2 );\nend\n\nfunction predict(fit::GarchFit)\n omega, alpha, beta = fit.params;\n rets = fit.data\n rets2   = rets.^2;\n T = length(rets); \n ht    = zeros(T);\n ht[1] = sum(rets2)/T;\n for i=2:T\n    ht[i] = omega + alpha*rets2[i-1] + beta * ht[i-1];\n end\n sqrt(omega + alpha*rets2[end] + beta*ht[end]);\nend\n\nfunction garchFit(data::Vector)\n  rets = data\n  rets2   = rets.^2;\n  T = length(rets); \n  ht = zeros(T);\n  function garchLike(x::Vector, grad::Vector)\n    omega,alpha,beta = x;\n    ht[1] = sum(rets2)/T;\n    for i=2:T\n      ht[i] = omega + alpha*rets2[i-1] + beta * ht[i-1];\n    end\n    sum( log(ht) + (rets./sqrt(ht)).^2 );\n  end\n  opt = Opt(:LN_SBPLX,3)\n  lower_bounds!(opt,[1e-10, 0.0, 0.0])\n  upper_bounds!(opt,[1; 0.3; 0.99])\n  min_objective!(opt, garchLike)\n  (minf,minx,ret) = NLopt.optimize(opt, [1e-5, 0.09, 0.89])\n  converged = minx[1]>0 && all(minx[2:3].>=0) && sum(minx[2:3])<1.0\n  H = cdHessian(minx,x->garchLLH(rets,x))\n  cvar = -inv(H)\n  secoef = sqrt(diag(cvar))\n  tval = minx./secoef\n  out = GarchFit(data, minx, -0.5*(T-1)*log(2*pi)-0.5*minf, ret, converged, sqrt(ht),H,cvar,secoef,tval)\nend\n\n# function garchPkgTest()\n#   println(\"Running GARCH package test...\")\n#   try\n#     include(Pkg.dir(\"GARCH\", \"test\",\"GARCHtest.jl\"))\n#     println(\"All tests passed!\")\n#   catch err\n#     throw(err)\n#   end\n# end\n", "meta": {"hexsha": "7bf7e20e825f1ff3ddade60220f75e2061f853a1", "size": 3430, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GARCH.jl", "max_stars_repo_name": "JuliaPackageMirrors/TimeModels.jl", "max_stars_repo_head_hexsha": "136ea7ef2664aadc475c5188aad0c5c586872b60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GARCH.jl", "max_issues_repo_name": "JuliaPackageMirrors/TimeModels.jl", "max_issues_repo_head_hexsha": "136ea7ef2664aadc475c5188aad0c5c586872b60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GARCH.jl", "max_forks_repo_name": "JuliaPackageMirrors/TimeModels.jl", "max_forks_repo_head_hexsha": "136ea7ef2664aadc475c5188aad0c5c586872b60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1147540984, "max_line_length": 104, "alphanum_fraction": 0.5874635569, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7593584858172813}}
{"text": "using SimplePolynomials, BigCombinatorics\n\n\nfunction sine_coeffs(n::Int)\n    T = Rational{BigInt}\n    result = zeros(T,2n)\n    for j=1:n\n        result[2j] = (-1)^(j-1)//Factorial(2j-1)\n    end\n\n\n    return result\nend\n\n\n\"\"\"\n`sine_poly(n)` create exact sine power series of degree `2n`\n(actually `2n-1` because `sin` is odd).\n\"\"\"\nfunction sine_poly(n::Int)\n    return SimplePolynomial(sine_coeffs(n))\nend\n", "meta": {"hexsha": "63da6c76795c2e3a9bff29b0dfd98e02af55c327", "size": 404, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sine_poly.jl", "max_stars_repo_name": "scheinerman/HalfSine.jl", "max_stars_repo_head_hexsha": "029bfeb9f340c08178716ea4dfc7f602123d677c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sine_poly.jl", "max_issues_repo_name": "scheinerman/HalfSine.jl", "max_issues_repo_head_hexsha": "029bfeb9f340c08178716ea4dfc7f602123d677c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sine_poly.jl", "max_forks_repo_name": "scheinerman/HalfSine.jl", "max_forks_repo_head_hexsha": "029bfeb9f340c08178716ea4dfc7f602123d677c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5652173913, "max_line_length": 60, "alphanum_fraction": 0.6608910891, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9669140197044659, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7593258766545918}}
{"text": "using AccretionFormulae\nusing Plots\n\nfunction r_hor(a, M)\n    (M +  √(M^2 - (a*M)^2))/M\nend\n\nM = 10*1.99e30\nspin_vals_pos = LinRange(0, 1, 1000)\nspin_vals_neg = LinRange(-1, 0 , 1000)\nISCO_pos_vals = AccretionFormulae.r_isco.(spin_vals_pos, M) ./ M\nISCO_neg_vals = reverse(AccretionFormulae.r_isco.(spin_vals_neg, M)) ./ M\nEH_pos_vals = r_hor.(spin_vals_pos, M)\n\nplt = plot(\n            spin_vals_pos, \n            ISCO_pos_vals, \n            legend=:topleft, \n            label=\"\\$r_{ISCO} \\\\; \\\\textrm{Prograde}\\$\", \n            xlabel=\"a (M)\", \n            ylabel=\"R (M)\", \n            grid=false, \n            framestyle=:box\n            )\nplot!(spin_vals_pos, ISCO_neg_vals, label=\"\\$r_{ISCO} \\\\; \\\\textrm{Retrograde}\\$\")\nplot!(spin_vals_pos, EH_pos_vals, label=\"\\$r_{s}\\$\")\npng(plt, \"ISCO_EH_spin_comp.png\")", "meta": {"hexsha": "70bb9859060567ba430f6a705d3808acf2ab8ca4", "size": 813, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/solva_plots/Others/ISCO_spin.jl", "max_stars_repo_name": "dangoh123/AccretionFormulae.jl", "max_stars_repo_head_hexsha": "02443e3a7053f68c2671cadf121b21b64451ac1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/solva_plots/Others/ISCO_spin.jl", "max_issues_repo_name": "dangoh123/AccretionFormulae.jl", "max_issues_repo_head_hexsha": "02443e3a7053f68c2671cadf121b21b64451ac1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-28T00:10:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T16:17:20.000Z", "max_forks_repo_path": "scripts/solva_plots/Others/ISCO_spin.jl", "max_forks_repo_name": "dangoh123/AccretionFormulae.jl", "max_forks_repo_head_hexsha": "02443e3a7053f68c2671cadf121b21b64451ac1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1111111111, "max_line_length": 82, "alphanum_fraction": 0.5990159902, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140235181257, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.7593258699326976}}
{"text": "## R code 7.3\nm7.1 <- quap(\n    alist(\n        brain_std ~ dnorm( mu , exp(log_sigma) ),\n        mu <- a + b*mass_std,\n        a ~ dnorm( 0.5 , 1 ),\n        b ~ dnorm( 0 , 10 ),\n        log_sigma ~ dnorm( 0 , 1 )\n    ), data=d )\n\n## R code 7.7\nm7.2 <- quap(\n    alist(\n        brain_std ~ dnorm( mu , exp(log_sigma) ),\n        mu <- a + b[1]*mass_std + b[2]*mass_std^2,\n        a ~ dnorm( 0.5 , 1 ),\n        b ~ dnorm( 0 , 10 ),\n        log_sigma ~ dnorm( 0 , 1 )\n    ), data=d , start=list(b=rep(0,2)) )\n\n## R code 7.8\nm7.3 <- quap(\n    alist(\n        brain_std ~ dnorm( mu , exp(log_sigma) ),\n        mu <- a + b[1]*mass_std + b[2]*mass_std^2 +\n                  b[3]*mass_std^3,\n        a ~ dnorm( 0.5 , 1 ),\n        b ~ dnorm( 0 , 10 ),\n        log_sigma ~ dnorm( 0 , 1 )\n    ), data=d , start=list(b=rep(0,3)) )\n\nm7.4 <- quap(\n    alist(\n        brain_std ~ dnorm( mu , exp(log_sigma) ),\n        mu <- a + b[1]*mass_std + b[2]*mass_std^2 +\n                  b[3]*mass_std^3 + b[4]*mass_std^4,\n        a ~ dnorm( 0.5 , 1 ),\n        b ~ dnorm( 0 , 10 ),\n        log_sigma ~ dnorm( 0 , 1 )\n    ), data=d , start=list(b=rep(0,4)) )\n\nm7.5 <- quap(\n    alist(\n        brain_std ~ dnorm( mu , exp(log_sigma) ),\n        mu <- a + b[1]*mass_std + b[2]*mass_std^2 +\n                  b[3]*mass_std^3 + b[4]*mass_std^4 +\n                  b[5]*mass_std^5,\n        a ~ dnorm( 0.5 , 1 ),\n        b ~ dnorm( 0 , 10 ),\n        log_sigma ~ dnorm( 0 , 1 )\n    ), data=d , start=list(b=rep(0,5)) )\n\n## R code 7.9\nm7.6 <- quap(\n    alist(\n        brain_std ~ dnorm( mu , 0.001 ),\n        mu <- a + b[1]*mass_std + b[2]*mass_std^2 +\n                  b[3]*mass_std^3 + b[4]*mass_std^4 +\n                  b[5]*mass_std^5 + b[6]*mass_std^6,\n        a ~ dnorm( 0.5 , 1 ),\n        b ~ dnorm( 0 , 10 )\n    ), data=d , start=list(b=rep(0,6)) )\n\n## R code 7.19\ndata(cars)\nm <- quap(\n    alist(\n        dist ~ dnorm(mu,sigma),\n        mu <- a + b*speed,\n        a ~ dnorm(0,100),\n        b ~ dnorm(0,10),\n        sigma ~ dexp(1)\n    ) , data=cars )\n\nm5.1 <- quap(\n    alist(\n        D ~ dnorm( mu , sigma ) ,\n        mu <- a + bA * A ,\n        a ~ dnorm( 0 , 0.2 ) ,\n        bA ~ dnorm( 0 , 0.5 ) ,\n        sigma ~ dexp( 1 )\n    ) , data = d )\n\nm5.2 <- quap(\n    alist(\n        D ~ dnorm( mu , sigma ) ,\n        mu <- a + bM * M ,\n        a ~ dnorm( 0 , 0.2 ) ,\n        bM ~ dnorm( 0 , 0.5 ) ,\n        sigma ~ dexp( 1 )\n    ) , data = d )\n\nm5.3 <- quap(\n    alist(\n        D ~ dnorm( mu , sigma ) ,\n        mu <- a + bM*M + bA*A ,\n        a ~ dnorm( 0 , 0.2 ) ,\n        bM ~ dnorm( 0 , 0.5 ) ,\n        bA ~ dnorm( 0 , 0.5 ) ,\n        sigma ~ dexp( 1 )\n    ) , data = d )\n\nm5.3t <- quap(\n    alist(\n        D ~ dstudent( 2 , mu , sigma ) ,\n        mu <- a + bM*M + bA*A ,\n        a ~ dnorm( 0 , 0.2 ) ,\n        bM ~ dnorm( 0 , 0.5 ) ,\n        bA ~ dnorm( 0 , 0.5 ) ,\n        sigma ~ dexp( 1 )\n    ) , data = d )\n", "meta": {"hexsha": "bcc5cc78c58c06ec5a1fda2d95e1896eabdabe24", "size": 2889, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/07/models.jl", "max_stars_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_stars_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2020-10-01T23:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T11:48:45.000Z", "max_issues_repo_path": "models/07/models.jl", "max_issues_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_issues_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-11-24T21:59:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T12:34:49.000Z", "max_forks_repo_path": "models/07/models.jl", "max_forks_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_forks_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-11-30T18:25:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T06:59:27.000Z", "avg_line_length": 25.7946428571, "max_line_length": 53, "alphanum_fraction": 0.4063689858, "num_tokens": 1130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8267118026095992, "lm_q1q2_score": 0.7593184581994447}}
{"text": "#---------------------------------------------------------------------#\n#This function computes the Initial & Exact Solutions.\n#Written by F.X. Giraldo on April 19, 2019\n#           Department of Applied Mathematics\n#           Naval Postgraduate School\n#           Monterey; CA 93943-5216\n#---------------------------------------------------------------------#\nfunction exact_solution(coord,Npoin,time,case,DFloat)\n\n    #Set some constants\n    xmin=-1\n    xmax=+1\n    xc=0.5*(xmax+xmin)\n    xl=xmax-xmin\n    rc=0.125\n    sigma=1/16; #best for right convergence rates\n    # sigma=1/8\n    # sigma=1/4; #fatter Gaussian to compare against 2D code\n    u=DFloat(2.0)\n\n    #Initialize\n    qe=zeros(DFloat,Npoin)\n\n    #timec=time - floor(time)\n    timec=time\n    #Generate Grid Points\n    for I=1:Npoin\n        x=coord[I]\n        xbar=xc + u*timec\n        if (xbar > xmax)\n            xbar=xmin + (xbar-xmax)\n        end\n        r=x-xbar\n        if (case == 1) #Gaussian\n            qe[I]=exp( -(x-xbar)^2/(2*sigma)^2 )\n        elseif (case == 2) #Square Wave\n      \t    if ( abs(r) <= rc )\n                qe[I]=1\n            end\n        end\n    end #I\n    return (qe,u)\nend\n", "meta": {"hexsha": "a35128ce072bc73577d09a07523152659810cff3", "size": 1170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Projects/Project_02_1D_Wave/For_Students/julia/exact_solution.jl", "max_stars_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_stars_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-12-28T06:19:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:40:33.000Z", "max_issues_repo_path": "Projects/Project_02_1D_Wave/For_Instructors/julia/RHS_Vector_approach/exact_solution.jl", "max_issues_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_issues_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-29T19:12:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-29T21:53:41.000Z", "max_forks_repo_path": "Projects/Project_02_1D_Wave/For_Instructors/julia/RHS_Vector_approach/exact_solution.jl", "max_forks_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_forks_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:35:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T06:53:34.000Z", "avg_line_length": 26.5909090909, "max_line_length": 71, "alphanum_fraction": 0.4854700855, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.826711791935942, "lm_q1q2_score": 0.7593184557748911}}
{"text": "# This is based on Higham's own Matlab implementation based on his paper:\n#   By N. J. Higham, 13/6/01, updated 30/1/13.\n#   Reference:  N. J. Higham, Computing the nearest correlation\n#   matrix---A problem from finance. IMA J. Numer. Anal.,\n#   22(3):329-343, 2002.\n#\n# as presented on: http://nickhigham.wordpress.com/2013/02/13/the-nearest-correlation-matrix/\n# It is typically not the fastest algorithm but should be ok for small (<500) dimensions...\n\n# NEARCORR    Nearest correlation matrix.\n#    (X, iter) = NEARCORR(A,TOL,FLAG,MAXITS,N_POS_EIG,W,PRNT)\n#    finds the nearest correlation matrix to the symmetric matrix A.\n#    TOL is a convergence tolerance, which defaults to 16*EPS.\n#    If using FLAG == 1, TOL must be a 2-vector, with first component\n#    the convergence tolerance and second component a tolerance\n#    for defining \"sufficiently positive\" eigenvalues.\n#    FLAG = 0: solve using full eigendecomposition (EIG).\n#    FLAG = 1: treat as \"highly non-positive definite A\" and solve\n#              using partial eigendecomposition (EIGS).\n#    MAXITS is the maximum number of iterations (default 100, but may\n#    need to be increased).\n#    N_POS_EIG (optional) is the known number of positive eigenvalues of A.\n#    W is a vector defining a diagonal weight matrix diag(W).\nfunction nearcorr(A, tol = [16*Base.eps()], flag = 0, maxits = 100, \n   n_pos_eig = false, w = ones(size(A, 1),1))\n\n   if A != A'\n      throw( ArgumentError(\"The matrix must be symmetric.\") )\n   end\n   \n   if length(tol) == 1 && flag == 1\n      tol = size(A, 1) * Base.eps() * [1.0, 1.0]\n   end\n \n   n = size(A, 1)\n   if flag == 1 && n_pos_eig == false\n      d, V = eig(A)\n      n_pos_eig = sum(d >= tol[2] * d[n])\n   end\n\n   X = copy(A)\n   Y = copy(A)\n   iter = 1\n   rel_diffXY = rel_diffY = rel_diffX = Inf\n   dS = zeros(size(A)) \n   w = w[:]\n   Whalf = sqrt(w*w')\n\n   while max(rel_diffX, rel_diffY, rel_diffXY) > tol[1]\n \n      Xold = X\n      R = X - dS\n      R_wtd = Whalf .* R\n\n      if flag == 0\n         X = proj_spd(R_wtd)\n      elseif flag == 1\n         X, np = proj_spd_eigs(R_wtd, n_pos_eig, tol[2])\n      end\n\n      X =  X ./ Whalf\n      dS = X - R\n      Yold = Y\n      Y = proj_unitdiag(X)\n      normy = normfro(Y)\n      rel_diffX = normfro(X-Xold)/normfro(X)\n      rel_diffY = normfro(X-Xold)/normy\n      rel_diffXY = normfro(Y-X)/normy\n\n      iter = iter + 1;\n      if iter > maxits\n         throw( OverflowError(\"Stopped after $(maxits) iterations. Try increasing maxits.\") )\n      end\n\n      X = Y\n \n   end\n\n   return X, iter\nend\n\nfunction proj_spd(A)\n   d, V = eig(A)\n   d[d .< 0.0] = 0.0 # Set negative eigen values to 0\n   B = V * diagm(d) * V'\n   (B+B')/2 # Ensure symmetric\nend\n\nfunction proj_spd_eigs(A, n_pos_eig, tol)\n   k = n_pos_eig + 10 # 10 is safety factor.\n   if k > size(A, 1)\n      k = n_pos_eig\n   end\n   d, V = eigs(A, k; which = \"LM\") \n   j = d .> tol*maximum(d)\n   n_pos_eig_found = sum(j)\n   B = V * diagm(d[j]) * V'\n   B = (B+B')/2 # Ensure symmetric\n   return B, n_pos_eig_found\nend\n\nfunction proj_unitdiag(A)\n   B = copy(A)\n   B[diagind(B)] = 1.0\n   B\nend\n", "meta": {"hexsha": "a3228772946e01fe297cb7de4999bd9abd425cf6", "size": 3097, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nearcorr.jl", "max_stars_repo_name": "robertfeldt/FeldtLib.jl", "max_stars_repo_head_hexsha": "8b7fd87097a77a0a1f4a2f2b4d89938572ed7243", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nearcorr.jl", "max_issues_repo_name": "robertfeldt/FeldtLib.jl", "max_issues_repo_head_hexsha": "8b7fd87097a77a0a1f4a2f2b4d89938572ed7243", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nearcorr.jl", "max_forks_repo_name": "robertfeldt/FeldtLib.jl", "max_forks_repo_head_hexsha": "8b7fd87097a77a0a1f4a2f2b4d89938572ed7243", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-04-18T18:30:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:14:25.000Z", "avg_line_length": 28.9439252336, "max_line_length": 93, "alphanum_fraction": 0.6092993219, "num_tokens": 1032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881363, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7593184540461051}}
{"text": "\"\"\"\n    a = rand_regular_bipartite(n,k)\n\nRandom k-regular bipartite graph between two sets of n vertices.\nNo repeat edges, so can take a long time to build of k is close to n.\n\nReturns a (possibly) asymmetric matrix that contains the upper-right block.\n\"\"\"\nfunction rand_regular_bipartite(n,k)\n    @assert k <= div(n,2)\n    \n    p = randperm(n)\n    \n    # start by building the upper-right block    \n    b = sparse(1:n, p, 1, n, n) \n    \n    for i in 2:k\n        done = false\n        while !done\n            p = randperm(n)\n            done = true\n            for i in 1:n\n                if b[i,p[i]] > 0\n                    done = false\n                end\n            end\n            if done \n                b = b + sparse(1:n, p, 1, n, n)\n            end\n        end\n        \n    end\n    \n    return b    \nend\n\nfunction test_regular_bipartite(B)\n    d = maximum(sum(B,dims=1))\n    d == minimum(sum(B,dims=1)) &&\n    d == minimum(sum(B,dims=2)) &&\n    d == maximum(sum(B,dims=2)) &&\n    length(unique(B)) <= 2\nend\n\nfunction regular_bipartite_matching(B)\n    @assert test_regular_bipartite(B)\n    \n    n = size(B,1)\n    match = zeros(Int,n) \n    \n    # match is indexed by right vertices, and gives name of match on left\n    \n    matched = zeros(Bool,n) # indicates which vertices on left are matched\n    \n    d = maximum(sum(B,dims=1))    \n    if d == 1\n        return invperm(B.rowval)\n    end\n    \n    for i in 1:n\n        ops = match_walk(B, match, matched, n, d)\n        \n        # eliminate loops in ops\n        us = [op[1] for op in ops]\n\n        firsts = indexin(us,us)\n        i = length(ops)\n        while i > 0\n            (u,v) = ops[i]\n            match[v] = u\n            matched[u] = true\n            \n            if firsts[i] < i\n                i = firsts[i] - 1\n            else\n                i = i - 1\n            end\n        end\n        \n    end\n    \n    return match\nend\n\nfunction match_walk(B, match, matched, n, d)\n    \n    ops = Tuple{Int64,Int64}[]\n   \n    u = rand(findall(.!matched))\n    v = 0\n\n    \n    done = false\n    while !done\n        \n        foundv = false\n        while !foundv\n            i = rand(1:d)\n            v = B.rowval[B.colptr[u]+i-1]\n            foundv = (u != match[v])\n        end\n        \n        push!(ops,(u,v))\n        \n        if match[v] == 0\n            done = true\n        else\n            u = match[v]\n        end\n        \n    end\n    \n    return ops\nend\n\n\"\"\"\n    S = latin_square(n)\n\nComputes a random (but not uniformly random) n-by-n latin square.\n\"\"\"\nfunction latin_square(n)\n    \n    S = zeros(Int,n,n)\n    \n    B = ones(Int,n,n)\n    \n    for j in 1:n\n   \n        match = regular_bipartite_matching(sparse(B))\n        for i in 1:n\n            S[i,match[i]] = j\n            B[i,match[i]] = 0\n        end        \n    end\n    \n    return S\nend\n\nfunction test_latin_square(S)\n    n = size(S,1)\n    \n    b = true\n    b = b && size(S,2) == n\n    \n    for i in 1:n\n        b = b && length(unique(S[:,i])) == n\n        b = b && length(unique(S[i,:])) == n\n    end\n    \n    b = b && length(unique(S)) == n\n    return b\nend\n\n\"\"\"\n    a = latin_square_graph(S::Matrix{Int})\n    a = latin_square_graph(n::Int)\n\nConstruct the adjacency matrix of the latin square graph for the latin square S.\nIf only n is provided, construct a latin square graph of dimension n.\n\"\"\"\nfunction latin_square_graph(S::Matrix{Int})\n\n    @assert test_latin_square(S)\n\n    n = size(S,1)\n\n    ijv = Laplacians.complete_graph_ijv(n)\n    ci = copy(ijv.i)\n    cj = copy(ijv.j)\n\n    lsgi = Int[]\n    lsgj = Int[]\n\n    # construct the column cliques\n    for i in 1:n\n        append!(lsgi, ci .+ n*(i-1))\n        append!(lsgj, cj .+ n*(i-1))\n    end\n\n    # construct the row cliques\n    for i in 1:n\n        append!(lsgi, n*ci .+ (i-n))\n        append!(lsgj, n*cj .+ (i-n))\n    end\n    \n    # construct the value cliques\n    nums = reshape([1:n^2;],n,n)\n\n    for i in 1:n\n        ind = nums[S .== i]\n        append!(lsgi, ind[ci])\n        append!(lsgj, ind[cj])\n    end\n\n    return sparse(lsgi, lsgj, 1.0, n^2, n^2)\nend\n\nlatin_square_graph(n::Int) = latin_square_graph(latin_square(n))\n", "meta": {"hexsha": "0fce74414e95204932b64d6b32b4edd852e987cd", "size": 4111, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/latinSquares.jl", "max_stars_repo_name": "HighDimensionalEconLab/Laplacians.jl", "max_stars_repo_head_hexsha": "25c75811f697ff1030ded0155d0d35c1fa3223c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 167, "max_stars_repo_stars_event_min_datetime": "2016-02-06T01:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:19:41.000Z", "max_issues_repo_path": "src/latinSquares.jl", "max_issues_repo_name": "HighDimensionalEconLab/Laplacians.jl", "max_issues_repo_head_hexsha": "25c75811f697ff1030ded0155d0d35c1fa3223c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2016-05-15T18:21:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T23:56:02.000Z", "max_forks_repo_path": "src/latinSquares.jl", "max_forks_repo_name": "HighDimensionalEconLab/Laplacians.jl", "max_forks_repo_head_hexsha": "25c75811f697ff1030ded0155d0d35c1fa3223c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2016-07-08T17:32:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:42:36.000Z", "avg_line_length": 20.6582914573, "max_line_length": 80, "alphanum_fraction": 0.5020676234, "num_tokens": 1199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.759318454046105}}
{"text": "using Random, Statistics, FreqTables\nusing LinearAlgebra, Optim, GLM\nusing DataFrames, CSV, HTTP\n\nfunction ps2()\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 1\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nf(x) = -x[1]^4-10x[1]^3-2x[1]^2-3x[1]-2\nminusf(x) = x[1]^4+10x[1]^3+2x[1]^2+3x[1]+2\nstartval = rand(1)   # random starting value\nresult = optimize(minusf, startval, BFGS())\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 2\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nurl = \"https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2020/master/ProblemSets/PS1-julia-intro/nlsw88.csv\"\ndf = CSV.read(HTTP.get(url).body)\nX = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\ny = df.married.==1\n\nfunction ols(beta, X, y)\n    ssr = (y.-X*beta)'*(y.-X*beta)\n    return ssr\nend\n\nbeta_hat_ols = optimize(b -> ols(b, X, y), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-6, iterations=100_000, show_trace=true))\nprintln(beta_hat_ols.minimizer)\n\nbols = inv(X'*X)*X'*y\ndf.white = df.race.==1\nbols_lm = lm(@formula(married ~ age + white + collgrad), df)\nprintln(\"β_lm estimates:\", bols_lm)\n\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 3\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nfunction logit(β, X, y)\n\n    # your turn\n    diff_u = X*β\n    loglike = sum(y.*diff_u - log.(1 .+ exp.(diff_u)))\n    loglike = -loglike\n\n    return loglike\nend\n\nβ_llk = optimize(β -> logit(β, X,y),\n                 rand(size(X,2)),\n                 # LBFGS(),\n                 Newton(),\n                 Optim.Options(g_tol=1e-6, iterations=100_000, show_trace=true))\nprintln(β_llk.minimizer)\n\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 4\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nb_glm = glm(@formula(married ~ age + white + collgrad), df, Binomial(), LogitLink())\nprintln(\"β_glm estimates:\", b_glm)\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 5\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nfreqtable(df, :occupation) # note small number of obs in some occupations\ndf = dropmissing(df, :occupation)\ndf[df.occupation.==10,:occupation] .= 9\ndf[df.occupation.==11,:occupation] .= 9\ndf[df.occupation.==12,:occupation] .= 9\ndf[df.occupation.==13,:occupation] .= 9\nfreqtable(df, :occupation) # problem solved\n\nX = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\ndf.white = df.race.==1\ny = df.occupation\n\nfunction mlogit(β, X, y)\n\n    K = size(X,2)\n    J = length(unique(y))\n    N = length(y)\n    bigY = zeros(N,J)\n\n    for j=1:J\n        bigY[:,j] = y.==j\n    end\n\n    β_big = [reshape(β,K,J-1) zeros(K)]\n\n    numerator = zeros(N,J)\n    denominator = zeros(N)\n\n    for j=1:J\n        numerator[:,j] = exp.(X*β_big[:,j])\n        denominator .+= numerator[:,j]\n    end\n\n    P = numerator./repeat(denominator, 1, J)\n    loglike = sum(bigY.*log.(P))\n    \n    return -loglike\nend\n\n\n    alpha_zero = zeros(6*size(X,2))\n    alpha_rand = rand(6*size(X,2))\n    alpha_true = [.1910213,-.0335262,.5963968,.4165052,-.1698368,-.0359784,1.30684,-.430997,.6894727,-.0104578,.5231634,-1.492475,-2.26748,-.0053001,1.391402,-.9849661,-1.398468,-.0142969,-.0176531,-1.495123,.2454891,-.0067267,-.5382892,-3.78975]\n    alpha_start = alpha_true.*rand(size(alpha_true))\n    println(size(alpha_true))\n    alpha_hat_optim = optimize(a -> mlogit(a, X, y), alpha_start, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\n    alpha_hat_mle = alpha_hat_optim.minimizer\n    println(alpha_hat_mle)\n    \n    \n    #:::::::::::::::::::::::::::::::::::::::::::::::::::\n    # bonus: how to get standard errors?\n    # need to obtain the hessian of the obj fun\n    #:::::::::::::::::::::::::::::::::::::::::::::::::::\n    # first, we need to slightly modify our objective function\n    function mlogit_for_h(alpha, X, y)\n        \n        K = size(X,2)\n        J = length(unique(y))\n        N = length(y)\n        bigY = zeros(N,J)\n        for j=1:J\n            bigY[:,j] = y.==j\n        end\n        bigAlpha = [reshape(alpha,K,J-1) zeros(K)]\n        \n        T = promote_type(eltype(X),eltype(alpha)) # this line is new\n        num   = zeros(T,N,J)                      # this line is new\n        dem   = zeros(T,N)                        # this line is new\n        for j=1:J\n            num[:,j] = exp.(X*bigAlpha[:,j])\n            dem .+= num[:,j]\n        end\n        \n        P = num./repeat(dem,1,J)\n        \n        loglike = -sum( bigY.*log.(P) )\n        \n        return loglike\n    end\n\n    # declare that the objective function is twice differentiable\n    td = TwiceDifferentiable(b -> mlogit_for_h(b, X, y), alpha_start; autodiff = :forward)\n    # run the optimizer\n    alpha_hat_optim_ad = optimize(td, alpha_zero, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\n    alpha_hat_mle_ad = alpha_hat_optim_ad.minimizer\n    # evaluate the Hessian at the estimates\n    H  = Optim.hessian!(td, alpha_hat_mle_ad)\n    # standard errors = sqrt(diag(inv(H))) [usually it's -H but we've already multiplied the obj fun by -1]\n    alpha_hat_mle_ad_se = sqrt.(diag(inv(H)))\n    println([alpha_hat_mle_ad alpha_hat_mle_ad_se]) # these standard errors match Stata\n\n   \n return nothing\n\nend\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 6\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nps2()\n", "meta": {"hexsha": "8497d957967afc0dcb1ecb1e1406d08635b926e2", "size": 5379, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS2-optimization-intro/gps.jl", "max_stars_repo_name": "gpetrini/OU_Econometrics_III", "max_stars_repo_head_hexsha": "81b5f35999d6b10f65f84b3344593d1c28acf1e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSets/PS2-optimization-intro/gps.jl", "max_issues_repo_name": "gpetrini/OU_Econometrics_III", "max_issues_repo_head_hexsha": "81b5f35999d6b10f65f84b3344593d1c28acf1e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS2-optimization-intro/gps.jl", "max_forks_repo_name": "gpetrini/OU_Econometrics_III", "max_forks_repo_head_hexsha": "81b5f35999d6b10f65f84b3344593d1c28acf1e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4036144578, "max_line_length": 246, "alphanum_fraction": 0.5326268823, "num_tokens": 1633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7593184523173186}}
{"text": "\"\"\"\n    Exponential\n\nExponential likelihood is to be used if we assume that the \nuncertainity associated with the data follows an Exponential distribution.\n\n```math\n    p(y|f) = Exponential(y | f)\n```\nOn calling, this would return an Exponential distribution with rate parameter `f`.\n\"\"\"\nstruct ExponentialLikelihood end\n\n(l::ExponentialLikelihood)(f::Real) = Exponential(exp(f))\n\n(l::ExponentialLikelihood)(fs::AbstractVector{<:Real}) = Product(Exponential.(exp.(fs)))\n", "meta": {"hexsha": "14478f1c2890ebcb03460c6c6fbde5178a5c4602", "size": 470, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/likelihoods/exponential.jl", "max_stars_repo_name": "kaandocal/GPLikelihoods.jl", "max_stars_repo_head_hexsha": "ee43721a04885e305a9102d89d0660a12e2d4ec5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/likelihoods/exponential.jl", "max_issues_repo_name": "kaandocal/GPLikelihoods.jl", "max_issues_repo_head_hexsha": "ee43721a04885e305a9102d89d0660a12e2d4ec5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/likelihoods/exponential.jl", "max_forks_repo_name": "kaandocal/GPLikelihoods.jl", "max_forks_repo_head_hexsha": "ee43721a04885e305a9102d89d0660a12e2d4ec5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6470588235, "max_line_length": 88, "alphanum_fraction": 0.7404255319, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.826711787666479, "lm_q1q2_score": 0.7593184518534736}}
{"text": "\nabstract type AbstractSimplicialComplex <: AbstractFiniteSetCollection end\n\nfunction show(io::IO, K::AbstractSimplicialComplex)\n    println(io, \"$(dim(K))-dimensional simplcial complex\")\n    println(io, \"V = {$(join(\",\",vertices(K)))}\")\n    println(io, \"max K = {$(join(\",\",facets(K)))}\")\nend\n\n################################################################################\n# General functions, defined for any subtype. Not always the most efficient\n# implementations.\n################################################################################\n\"\"\"\n    dim(K)\n\nThe dimension of `K`, defined as the maximum size of a face of `K` minus 1. If\n`K` is the void complex (i.e. `K` has no faces), throws an `ArgumentError`.\n\n\"\"\"\ndim(K::AbstractSimplicialComplex) = maximum(map(length, facets(K))) - 1\n\n\"\"\"\n    link(sigma, K)\n\nThe link of `sigma` in `K`.\n\n``link_σ(K) = {τ ∈ K : σ ∩ τ = ∅, σ ∪ τ ∈ K}``\n\"\"\"\nfunction link{T<:AbstractSimplicialComplex}(sigma,K::T)\n    newFacets = Vector()\n    for F in facets(K)\n        if issubset(sigma, F)\n            push!(newFacets, setdiff(F,sigma))\n        end\n    end\n    return T(newFacets)\nend\n\n\"\"\"\n    del(tau, K)\n\nThe deletion of `tau` from `K`. This is the set faces in `K` which are _not_\ncofaces of `tau`. For \"deletion\" to mean \"faces which do not intersect `tau`\",\ncompute the complement of `tau` in `K`'s vertex set and use `res` to restrict to\nthat set.\n\n``del_τ(K) = {σ ∈ K : τ ⊏̸ σ}``\n\"\"\"\nfunction del{T<:AbstractSimplicialComplex}(tau, K::T)\n    return T(map(F -> setdiff(F,tau), collect(facets(K))))\nend\n\n\"\"\"\n    res(Vprime, K)\n\nThe restriction of `K` to `Vprime`.\n\n``res_{V'}(K) = {σ ∈ K : σ ⊆ V'}``\n\"\"\"\nfunction res{T<:AbstractSimplicialComplex}(Vprime, K::T)\n    return T(map(F -> intersect(F,Vprime),collect(facets(K))))\nend\n\n################################################################################\n# BEGIN CONCRETE SUBTYPES OF ASC\n################################################################################\n\n# FACETLIST\n\"\"\"\n    FacetList\n\nA simplicial complex, stored as a list of its facets. Low storage, high\ncomputation time (generally).\n\"\"\"\nstruct FacetList{V} <: AbstractSimplicialComplex\n    vertices::Vector{V}\n    facets::BitMatrix # rows as facets\nend\nfunction FacetList(L)\n    V = union(L...)\n    B = falses(length(L),length(V))\n    keep = falses(length(L))\n    for i = 1:length(L)\n        keep[i] = all(map(G -> !issubset(L[i],G), L[i+1:end]))\n        if keep[i]\n            B[i,indexin(L[i],V)] = true\n        end\n    end\n    B = B[keep,:]\n    return FacetList(V,B)\nend\nfunction FacetList(C::AbstractFiniteSetCollection)\n    return FacetList(collect(facets(C)))\nend\n\nvertices(K::FacetList) = K.V\n\n#TODO iteration functions to iterate over *all* faces of K\nfunction start(K::FacetList)\nend\nfunction next(K::FacetList, state)\nend\nfunction done(K::FacetList, state)\nend\n\n# Functions for iterating over the facets of K.\nstart{V}(maxK::MaximalSetIterator{FacetList{V}}) = 0\nnext{V}(maxK::MaximalSetIterator{FacetList{V}}, state) = (maxK.C.vertices[maxK.C.facets[state+1,:]], state+1)\ndone{V}(maxK::MaximalSetIterator{FacetList{V}}, state) = state >= size(maxK.C.facets,1)\n", "meta": {"hexsha": "f2b6d9f6c71119bdf2cc01a7b22f18927121dcd8", "size": 3150, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SimplicialComplex.jl", "max_stars_repo_name": "sekunder/FiniteSetCollections.jl", "max_stars_repo_head_hexsha": "48973ad66b5c446bbee9228c22a4398ad88a70de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SimplicialComplex.jl", "max_issues_repo_name": "sekunder/FiniteSetCollections.jl", "max_issues_repo_head_hexsha": "48973ad66b5c446bbee9228c22a4398ad88a70de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SimplicialComplex.jl", "max_forks_repo_name": "sekunder/FiniteSetCollections.jl", "max_forks_repo_head_hexsha": "48973ad66b5c446bbee9228c22a4398ad88a70de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3783783784, "max_line_length": 109, "alphanum_fraction": 0.5850793651, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7593184427456975}}
{"text": "\n\"\"\"\n    haversine(lon1, lat1, lon2, lat2)\n\nCalculate the haversine distance and bearing. Distance is in nm.\n\"\"\"\n@inline @fastmath function haversine(lon1, lat1, lon2, lat2)\n    R = 6372.8  # Earth radius in kilometers\n\n    dLat = deg2rad(lat2 - lat1)\n    dLon = deg2rad(lon2 - lon1)\n    lat1 = deg2rad(lat1)\n    lat2 = deg2rad(lat2)\n    lon1 = deg2rad(lon1)\n    lon2 = deg2rad(lon2)\n    a = sin(dLat/2)^2 + cos(lat1)*cos(lat2)*sin(dLon/2)^2\n    c = 2*asin(sqrt(a))\n    theta = atan(sin(dLon)*cos(lat2),\n                 cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(dLon))\n    theta = (rad2deg(theta) + 360) % 360\n    return R*c*0.5399565, theta\nend\n\n\nfunction rotate_point(ox, oy, px, py, angle,ret_x)\n    \"\"\"\n    Rotate a point counterclockwise by a given angle around a given origin.\n\n    The angle should be given in radians.\n    \"\"\"\n    qx = ox + cos(angle) * (px - ox) - sin(angle) * (py - oy)\n    qy = oy + sin(angle) * (px - ox) + cos(angle) * (py - oy)\n    if ret_x == true\n        return qx\n    else\n        return qy\n    end\nend\n\n\nfunction generate_grid(start_lon, start_lat, finish_lon, finish_lat, nodes)\n    dist = haversine(start_lon, start_lat, finish_lon, finish_lat)\n    spacing = dist[1]/(nodes+1)\n    alpha = dist[2]\n    x_dist = spacing\n    y_dist = spacing\n    grid_x = reshape(start_lon.+[i*x_dist for i in range(1, length=nodes) for j in range(0, length=nodes).-(nodes-1)/2], (nodes, nodes))\n    grid_y = reshape(start_lat.+[j*y_dist for i in range(1, length=nodes) for j in range(0, length=nodes).-(nodes-1)/2], (nodes, nodes))\n    rot_grid_x = [rotate_point(start_lon, start_lat, x, y, alpha, true) for (x, y) in zip(grid_x,grid_y)]\n    rot_grid_y = [rotate_point(start_lon, start_lat, x, y, alpha, false) for (x, y) in zip(grid_x,grid_y)]\n    return transpose(rot_grid_x), rot_grid_y\nend\n\n\n\"\"\"\n    euclidean(x1, y1, x2, y2)\n\nCalculate the distance and argument between the vector and north between points 1 and 2.\neuclidean(0.0, 0.0, 10.0, 10.0) = (14.142135623730951, 45.0)\neuclidean(0.0, 0.0, 10.0, 10.0) = (14.142135623730951, 45.0)\neuclidean(0.0, 0.0, 10.0, 10.0) = (14.142135623730951, 45.0)\neuclidean(0.0, 0.0, 10.0, 10.0) = (14.142135623730951, 45.0)\n\"\"\"\n@inline @fastmath function euclidean(x1::Float64, y1::Float64, x2::Float64, y2::Float64)\n    dx = x2 - x1\n    dy = y2 - y1\n    dist = (dx^2 + dy^2)^(0.5)\n    theta = 0.0\n    if dy > 0.0 && dx > 0.0\n        theta = 90.0 - rad2deg(atan(dy, dx))\n    elseif dy == 0 && dx > 0.0\n        theta = 90.0\n    elseif dx == 0 && dy < 0.0\n        theta = 180.0\n    elseif dy < 0.0 && dx > 0.0\n        theta = 90.0 + rad2deg(atan(abs(dy), dx))\n    elseif dy < 0.0 && dx < 0.0\n        theta = 180 + rad2deg(atan(abs(dy), abs(dx)))\n    elseif dy > 0.0 && dx < 0.0\n        theta = 360 - rad2deg(atan(dy, abs(dx)))\n    end\n    return dist, theta\nend\n\n\n\"\"\"Calculate the number of nodes for a specific distance in nm.\"\"\"\nfunction calc_nodes(lon1, lon2, lat1, lat2, req_d)\n    d = haversine(lon1, lon2, lat1, lat2)[1]\n    return round(Int, d/req_d)\nend\n\n\n", "meta": {"hexsha": "1dc029546764b132f5408f33e49916757249af24", "size": 3022, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/route/domain.jl", "max_stars_repo_name": "TAJD/sail_route.jl", "max_stars_repo_head_hexsha": "8f8548188719564f6634868cbe2687a88df1d4a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-08-03T15:34:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T18:05:16.000Z", "max_issues_repo_path": "src/route/domain.jl", "max_issues_repo_name": "TAJD/SailRoute.jl", "max_issues_repo_head_hexsha": "8f8548188719564f6634868cbe2687a88df1d4a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/route/domain.jl", "max_forks_repo_name": "TAJD/SailRoute.jl", "max_forks_repo_head_hexsha": "8f8548188719564f6634868cbe2687a88df1d4a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4946236559, "max_line_length": 136, "alphanum_fraction": 0.6158173395, "num_tokens": 1108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145365, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7593137608282394}}
{"text": "# ------------------------------------------------------------------------------------------\n# ## Intro to neurons\n#\n# At this point, we know how to build models and have a computer automatically learn how to\n# match the model to data. This is the core of how any machine learning method works.\n#\n# Now, let's narrow our focus and look at **neural networks**. Neural networks (or \"neural\n# nets\", for short) are a specific choice of a **model**. It's a network made up of\n# **neurons**; this, in turn, leads to the question, \"what is a neuron?\"\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ### Models with multiple inputs\n#\n# So far, we have been using the sigmoid function as our model. One of the forms of the\n# sigmoid function we've used is\n#\n# $$\\sigma_{w, b}(x) = \\frac{1}{1 + \\exp(-wx + b)},$$\n#\n# where `x` and `w` are both single numbers. We have been using this function to model how\n# the amount of the color green in an image (`x`) can be used to determine if an image shows\n# an apple or a banana.\n#\n# But what if we had multiple data features we wanted to fit?\n#\n# We could then extend our model to include multiple features like\n#\n# $$\\sigma_{\\mathbf{w},b}(\\mathbf{x}) = \\frac{1}{1 + \\exp(-w_1 x_1 - w_2 x_2 - \\cdots - w_n\n# x_n + b)}$$\n#\n# Note that now $\\mathbf{x}$ and $\\mathbf{w}$ are vectors with many components, rather than\n# a single number.\n#\n# For example, $x_1$ might be the amount of the color green in an image, $x_2$ could be the\n# height of the object in the picture, $x_3$ could be the width, and so forth. We can add\n# information for as many features as we have! Our model now has more parameters, but the\n# same idea of gradient descent (\"rolling the ball downhill\") will still work to train our\n# model.\n#\n# This version of the sigmoid model that takes multiple inputs is an example of a\n# **neuron**.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# In the video, we see that one huge class of learning techniques is based around neurons,\n# that is, *artificial neurons*. These are caricatures of real, biological neurons. Both\n# *artificial* and *biological* neurons have several inputs $x_1, \\ldots, x_n$, and a single\n# output, $y$. Schematically they look like this:\n# ------------------------------------------------------------------------------------------\n\ninclude(\"draw_neural_net.jl\")\n\nnumber_inputs, number_neurons = 4, 1\n\ndraw_network([number_inputs, number_neurons])\n\n# ------------------------------------------------------------------------------------------\n# We should read this as showing how information flows from left to right:\n# - 4 pieces of input information arrive (shown in green on the left);\n#\n# - the neuron (shown in red on the right) receives all the inputs, processes them, and\n# outputs a single number to the right.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# In other words, a neuron is just a type of function that takes multiple inputs and returns\n# a single output.\n#\n# The simplest interesting case that we will look at in this notebook is when there are just\n# two pieces of input data:\n# ------------------------------------------------------------------------------------------\n\ndraw_network([2, 1])\n\n# ------------------------------------------------------------------------------------------\n# Each link between circles above represents a **weight** $w$ that can be modified to allow\n# the neuron to learn, so in this case the neuron has two weights, $w_1$ and $w_2$.\n#\n# The neuron also has a single bias $b$, and an **activation function**, which we will take\n# to be the $\\sigma$ sigmoidal function that we have been using. (Note that other activation\n# functions can be used!)\n#\n# Let's call our neuron $f_{w_1,w_2, b}(x_1, x_2)$, where\n#\n# $$f_{w_1,w_2, b}(x_1, x_2) := \\sigma(w_1 x_1 + w_2 x_2 + b).$$\n#\n# Note that $f_{w_1,w_2, b}(x_1, x_2)$ has 3 parameters: two weights and a bias.\n#\n# To simplify the notation, and to prepare for more complicated scenarios later, we put the\n# two weights into a vector, and the two data values into another vector:\n#\n# $$\n# \\mathbf{w} = \\begin{pmatrix} w_1 \\\\ w_2 \\end{pmatrix};\n# \\qquad\n# \\mathbf{x} = \\begin{pmatrix} x_1 \\\\ x_2 \\end{pmatrix}.\n# $$\n#\n# We thus have\n#\n# $$f_{\\mathbf{w}, b}(\\mathbf{x}) = \\sigma(\\mathbf{w} \\cdot \\mathbf{x} + b),$$\n#\n# where the dot product $\\mathbf{w} \\cdot \\mathbf{x}$ is an abbreviated syntax for $w_1 x_1\n# + w_2 x_2$.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 1\n#\n# Declare the function `f(x, w, b)` in Julia. `f` should take vectors `x` and `w` as vectors\n# and `b` as a scalar. Furthermore `f` should call\n#\n# ```julia\n# σ(x) = 1 / (1 + exp(-x))\n# ```\n#\n# What output do you get for\n#\n# ```julia\n# f(3, 4, 5)\n# ```\n# ?\n# ------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "effdc6dd0a6b3d8ee651a8eed38ce95176631f7d", "size": 5366, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/11. ML - Intro to neurons.jl", "max_stars_repo_name": "grenkoca/JuliaTutorials", "max_stars_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 535, "max_stars_repo_stars_event_min_datetime": "2020-07-15T14:56:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T12:50:32.000Z", "max_issues_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/11. ML - Intro to neurons.jl", "max_issues_repo_name": "grenkoca/JuliaTutorials", "max_issues_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2018-02-25T22:53:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-14T02:15:50.000Z", "max_forks_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/11. ML - Intro to neurons.jl", "max_forks_repo_name": "grenkoca/JuliaTutorials", "max_forks_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 394, "max_forks_repo_forks_event_min_datetime": "2020-07-14T23:22:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:12:57.000Z", "avg_line_length": 43.6260162602, "max_line_length": 92, "alphanum_fraction": 0.5238538949, "num_tokens": 1266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145365, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7593137564298293}}
{"text": "using Plots;\nusing Printf;\ngr();\nanim = Animation();\nf(x) = 1/2*cos(8pi*(x-1/2));\n\nfunction forward(u_old::Array, i::Int64)\n\treturn (3u_old[ir[i]] + 3u_old[i] - 7u_old[il[i]] + u_old[il2[i]]) / 8;\nend\n\nfunction backward(u_old::Array, i::Int64)\n\treturn (3u_old[il[i]] + 3u_old[i] - 7u_old[ir[i]] + u_old[ir2[i]]) / 8;\nend\n\nfunction main()\n#=********Numerical Set Up*********=#\n\tglobal c = 1.0;\n\tglobal nx = 101;\n\tglobal lx = 100;\n\tglobal x = range(0.0, stop=lx, length=nx);\n\tglobal dx = lx /(nx-1);\n\tglobal u  = zeros(Float64, nx);\n\t@inbounds for i = 1:nx\n\t\tif 40.0 < x[i] < 60.0; \n\t\t\tu[i] = f(x[i]);\n\t\tend\n\tend\n\tglobal t = 0.0;\n\tglobal dt = 2e-2;\n\tglobal tlims = 300;\n\tglobal C = dt * c / dx;\n\tglobal ir = zeros(Int64, nx);\n\tglobal ir2 = zeros(Int64, nx);\n\tglobal il = zeros(Int64, nx);\n\tglobal il2 = zeros(Int64, nx);\n\t@inbounds for i = 1:nx\n\t\tir[i] = i + 1;\n\t\tir2[i] = i + 2;\n\t\til[i] = i - 1;\n\t\til2[i] = i - 2;\n\tend\n\tir[end] = 1;\n\tir2[end - 1] = 1;\n\tir2[end] = 2;\n\til[begin] = nx;\n\til2[begin + 1] = nx;\n\til2[begin] = nx - 1;\n#=******Finish Numerical Set Up*************=#\n\n\twhile t < tlims\n\t\tu_old = copy(u);\n\t\t##First substep\n\t\t@inbounds for i = 1:nx-1\n\t\t\tu[i] = u_old[i] - C * forward(u_old, i);\n\t\tend\n\t\tu[end] = u[begin];\n\t\t\n\t\t##Second substep\n\t\t@inbounds for i = 1:nx\n\t\t\tu_old[i] = 0.5*(u_old[i] + u[i]) - 0.5*C/8.0*(forward(u, i));\n\t\tend\n\t\tu_old[end] = u_old[begin];\n\n\t\tu = copy(u_old);\n\n\t\tplt = plot(x, u, xlims=(0, lx), xticks=0:lx/5:lx, ylims=(-0.2, 1.2), yticks=-0.2:0.2:1.2,\n\t\txlabel=\"x\", ylabel=\"u\", color=\"blue\", title=\"QUICK method by using Heun\", legend=false);\n\t\tframe(anim, plt);\n\t\tt += dt;\n\t\t@printf(\"t = %.4f\\n\", t);\n\tend\n\tgif(anim, \"quick.gif\", fps=5);\nend\n\nmain();\n", "meta": {"hexsha": "ffd5504c4fb48fbb1a881b0f4124eab9e25b6d72", "size": 1687, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "quick.jl", "max_stars_repo_name": "Makoto523sys/QUICK", "max_stars_repo_head_hexsha": "98b19a9233a424050dfed2bc56631d06ac53bfb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quick.jl", "max_issues_repo_name": "Makoto523sys/QUICK", "max_issues_repo_head_hexsha": "98b19a9233a424050dfed2bc56631d06ac53bfb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quick.jl", "max_forks_repo_name": "Makoto523sys/QUICK", "max_forks_repo_head_hexsha": "98b19a9233a424050dfed2bc56631d06ac53bfb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1973684211, "max_line_length": 91, "alphanum_fraction": 0.5536455246, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7593084613403323}}
{"text": "wdot(wx, x, wy, y) = dot(wx.*x, wy.*y)\nwnorm(w, x) = norm(w.*x)\n\nassess_convergence(f, ftol) = assess_convergence(NaN, NaN, f, NaN, ftol)\nfunction assess_convergence(x,\n                            x_previous,\n                            f,\n                            xtol,\n                            ftol)\n    x_converged, f_converged = false, false\n    if norm(x-x_previous) <= xtol\n        x_converged = true\n    end\n    if maximum(abs, f) <= ftol\n        f_converged = true\n    end\n\n    return x_converged, f_converged\nend\n\nfunction check_isfinite(x::AbstractArray)\n    if any(!isfinite, x)\n        i = findall(!isfinite, x)\n        throw(IsFiniteException(i))\n    end\nend\n\n\"\"\"\n    qrdelete!(Q, R, k)\n\nDelete the left-most column of F = Q[:, 1:k] * R[1:k, 1:k] by updating Q and R.\n\nOnly Q[:, 1:(k-1)] and R[1:(k-1), 1:(k-1)] are valid on exit.\n\"\"\"\nfunction qrdelete!(Q::AbstractMatrix, R::AbstractMatrix, k::Int)\n  n, m = size(Q)\n  m == LinearAlgebra.checksquare(R) || throw(DimensionMismatch())\n  1 ≤ k ≤ m || throw(ArgumentError())\n\n  # apply Givens rotations\n  for i in 2:k\n      g = first(givens(R, i - 1, i, i))\n      lmul!(g, R)\n      rmul!(Q, g')\n  end\n\n  # move columns of R\n  @inbounds for j in 1:(k-1)\n    for i in 1:(k-1)\n      R[i, j] = R[i, j + 1]\n    end\n  end\n\n  Q, R\nend\n\n\"\"\"\n    qradd!(Q, R, v, k)\n\nReplace the right-most column of F = Q[:, 1:k] * R[1:k, 1:k] with v by updating Q and R.\n\nThis implementation modifies vector v as well. Only Q[:, 1:k] and R[1:k, 1:k] are valid on\nexit.\n\"\"\"\nfunction qradd!(Q::AbstractMatrix, R::AbstractMatrix, v::AbstractVector, k::Int)\n  n, m = size(Q)\n  n == length(v) || throw(DimensionMismatch())\n  m == LinearAlgebra.checksquare(R) || throw(DimensionMismatch())\n  1 ≤ k ≤ m || throw(ArgumentError())\n\n  @inbounds for i in 1:(k-1)\n    q = view(Q, :, i)\n    r = dot(q, v)\n\n    R[i, k] = r\n    axpy!(-r, q, v)\n  end\n\n  @inbounds begin\n    d = norm(v)\n    R[k, k] = d\n    @. Q[:, k] = v / d\n  end\n\n  Q, R\nend\n", "meta": {"hexsha": "d0c7869c0ab5f79d877218d5a735d6ec3b2e882e", "size": 1967, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlsolve/utils.jl", "max_stars_repo_name": "SarThak191119/NLsolve.jl", "max_stars_repo_head_hexsha": "2e7172fbc11c5c04f0c1ec0c28a8fa5609efc752", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 245, "max_stars_repo_stars_event_min_datetime": "2017-02-27T14:20:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T05:35:35.000Z", "max_issues_repo_path": "src/nlsolve/utils.jl", "max_issues_repo_name": "SarThak191119/NLsolve.jl", "max_issues_repo_head_hexsha": "2e7172fbc11c5c04f0c1ec0c28a8fa5609efc752", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 170, "max_issues_repo_issues_event_min_datetime": "2017-02-27T13:34:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T02:57:56.000Z", "max_forks_repo_path": "src/nlsolve/utils.jl", "max_forks_repo_name": "SarThak191119/NLsolve.jl", "max_forks_repo_head_hexsha": "2e7172fbc11c5c04f0c1ec0c28a8fa5609efc752", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 61, "max_forks_repo_forks_event_min_datetime": "2017-03-20T05:01:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T19:20:33.000Z", "avg_line_length": 22.6091954023, "max_line_length": 90, "alphanum_fraction": 0.5500762583, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8499711813581708, "lm_q1q2_score": 0.7592872584251323}}
{"text": "scalaradd(a, b) = a + b\n\nfunction sum(v)\n  s = 0.0\n  N = length(v)\n  for i = 1:N\n      s += v[i]\n  end\n  return s\nend\n\n# y = dot(a,b)\nfunction dot(a, b)\n  s = 0.0\n  N = length(a)\n  for i = 1:N\n      s += a[i] * b[i]\n  end\n  return s\nend\n\nfunction tuplereturn(x)\n  a = x * 1.2\n  b = x * 1.3\n  return a, b\nend\n\nfunction tuplecall(x)\n  ab = tuplereturn(x)\n  r = ab[1]\n  #r = getfield(ab,1)\n  return r\nend\n\n# y = W*X\nmul(W, X) = mul_(zeros(size(W,1), size(X,2)), W, X)\nfunction mul_(y, W, X)\n    szW = size(W)\n    szX = size(X)\n    s = 0.0\n    for n = 1:szX[2]\n        for i = 1:szW[1]\n            s = 0.0\n            for j = 1:szW[2]\n                s += W[i,j] * X[j,n]\n            end\n            y[i,n] = s\n        end\n    end\n    return y\nend\n\n# y = W*X .+ b\nmuladd(W, X, b) = muladd_(zeros(size(W,1), size(X,2)), W, X, b)\nfunction muladd_(y, W, X, b)\n    szW = size(W)\n    szX = size(X)\n    s = 0.0\n    for n = 1:szX[2]\n        for i = 1:szW[1]\n            s = 0.0\n            for j = 1:szW[2]\n                s += W[i,j] * X[j,n]\n            end\n            y[i,n] = s + b[i]\n        end\n    end\n    return y\nend\n\n# y = a .+ b\nadd(a, b) = add_(zeros(size(a)), a, b)\nfunction add_(r, a, b)\n  N = length(r)\n  for i = 1:N\n      r[i] = a[i] + b[i]\n  end\n  return r\nend\n\n\nfunction exports()\n  scalaradd(1.0, 2.0)\n\n  a=randn(3,1)\n  b=randn(3,1)\n  dot(a,b)\n  res = add(a,b)\n\n  tuplereturn(1.2)\n  tuplecall(2.1)\n\n  M1=randn(4,2)\n  M2=randn(2,5)\n  r = mul(M1,M2)\n\n  b = randn(4,1)\n  r2 = muladd(M1,M2, b)\n  sum(a)\nend\n\nexports()", "meta": {"hexsha": "1b66815149f3c4309798044cab5c23e802cf944b", "size": 1522, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/jl/array.jl", "max_stars_repo_name": "Andersgee/WebAssemblyText.jl", "max_stars_repo_head_hexsha": "cf128cd283ee2c929aa808dbad2f2944823ee603", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-29T21:23:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T10:14:09.000Z", "max_issues_repo_path": "test/jl/array.jl", "max_issues_repo_name": "Andersgee/WebAssemblyText.jl", "max_issues_repo_head_hexsha": "cf128cd283ee2c929aa808dbad2f2944823ee603", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/jl/array.jl", "max_forks_repo_name": "Andersgee/WebAssemblyText.jl", "max_forks_repo_head_hexsha": "cf128cd283ee2c929aa808dbad2f2944823ee603", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-16T13:43:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-16T13:43:35.000Z", "avg_line_length": 14.9215686275, "max_line_length": 63, "alphanum_fraction": 0.4520367937, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7592872511823809}}
{"text": "\"\"\"\n\tOrderedPair\n\nOrderedPair representation.\nEx:\n```\njulia> o = OrderedPair(1,3.2)\n(1,3.2)\n```\n\"\"\"\nmutable struct OrderedPair\n\tleft::Real\n\tright::Real\n\tOrderedPair(left,right) = left > right ? error(\"OrderedPair must be ordered\") : new(left,right)\nend\n\n\"\"\"\n\tstring(p)\n\nReturns a string representation of an `OrderedPair`.\n\"\"\"\nfunction string(p::OrderedPair)\n\t\"($(p.left),$(p.right))\"\nend\n\n\"\"\"\n\tshow(io,p)\n\nPrints the string representation of an `OrderedPair`.\n\"\"\"\nfunction show(io::IO, p::OrderedPair)\n\tprintln(string(p))\nend \n\n\"\"\"\n\to1 == o2\n\nEquality defined for `OrderedPair`.\n\"\"\"\nfunction ==(o1::OrderedPair, o2::OrderedPair)\n\t(o1.left == o2.left) && (o1.right == o2.right)\nend\n\n\"\"\"\n\to1 < o2\n\nLexicographical order for `OrderedPair`.\n\"\"\"\nfunction isless(o1::OrderedPair, o2::OrderedPair)\n\to1.left == o2.left ? o1.right < o2.right : o1.left < o2.left\nend\n\n\"\"\"\n\tInterval\n\n`Interval` representation.\nAttributes:\n\t- limits::OrderedPair : The left and right limits of the interval.\n\t- open_left::Bool : Set to true if the interval is open on the left.\n\t- open_right::Bool : Set to true if the interval is open on the right.\nEx:\n```\njulia> i = Interval(0,1)\n[0,1]\njulia> j = Interval(1,true,3.4)\n]1,3.4]\njulia> k = Interval(-1,true,3.12,true)\n]-1,3.12[\n```\n\"\"\"\nmutable struct Interval\n    limits::OrderedPair\n    open_left::Bool\n    open_right::Bool\nend\n\n\"\"\"\n\ti1 == i2\n\nEquality defined for `Interval`.\n\"\"\"\nfunction ==(i1::Interval, i2::Interval)\n\t(i1.limits == i2.limits) && (i1.open_left == i2.open_left) && (i1.open_right == i2.open_right)\nend\n\n\"\"\"\n\ti1 < i2\n\nLexicographical order for `Interval`.\nEx:\n```\njulia> Interval(0,2) < Interval(1,2,true)\ntrue\njulia> Interval(1,3) > Interval(-1,10)\ntrue\njulia> Interval(0,1) < Interval(0,1,true)\ntrue\n```\n\"\"\"\nfunction isless(i1::Interval, i2::Interval)\n\tif left(i1) < left(i2)\n        return true\n    elseif left(i1) == left(i2)\n        if !i1.open_left & i2.open_left\n        \treturn true\n        elseif i1.open_left & !i2.open_left\n        \treturn false\n        else\n        \tif right(i1) < right(i2)\n        \t\treturn true\n        \telseif right(i1) == right(i2)\n        \t\tif !i1.open_right & i2.open_right\n        \t\t\treturn true\n        \t\telse\n        \t\t\treturn false\n        \t\tend\n        \telse\n        \t\treturn false\n        \tend\n        end\n    else\n        return false\n    end\nend\n\n\"\"\"\n\tInterval(left, open_left, right, open_right)\n\nFull constructor for `Interval`.\nRequires:\n\t- left::Real Left limit of the interval.\n\t- open_left::Bool Set to true if the interval is open on the left.\n\t- right::Real Right limit of the interval.\n\t- open_right::Bool Set to true if the interval is open on the left.\nEx:\n```\njulia> i = Interval(0,false,1,true)\n[0,1[\njulia> j = Interval(1,false,2,false)\n[1,2]\n```\n\"\"\"\nfunction Interval(left::Real, open_left::Bool, right::Real, open_right::Bool)\n\tp = OrderedPair(left,right)\n\tInterval(p,open_left,open_right)\nend\n\n\"\"\"\n\tInterval(left, right)\n\nSimplified constructor for closed `Interval`.\nRequires:\n\t- left::Real Left limit of the interval.\n\t- right::Real Right limit of the interval.\nEx:\n```\njulia> i = Interval(0,2)\n[0,2]\n```\n\"\"\"\nfunction Interval(left::Real, right::Real)\n\tp = OrderedPair(left,right)\n\tInterval(p,false,false)\nend\n\n\"\"\"\n\tInterval(left, open_left, right)\n\nSimplified constructor for `Interval` closed on the right.\nRequires:\n\t- left::Real Left limit of the interval.\n\t- open_left::Bool Set to true if the interval is open on the left.\n\t- right::Real Right limit of the interval.\nEx:\n```\njulia> i = Interval(2,true,3)\n]2,3]\n```\n\"\"\"\nfunction Interval(left::Real, open_left::Bool, right::Real)\n\tp = OrderedPair(left,right)\n\tInterval(p,open_left,false)\nend\n\n\"\"\"\n\tInterval(left, right, open_right)\n\nSimplified constructor for `Interval` closed on the left.\nRequires:\n\t- left::Real Left limit of the interval.\n\t- right::Real Right limit of the interval.\n\t- open_right::Bool Set to true if the interval is open on the right.\nEx:\n```\njulia> i = Interval(-1,2,true)\n[-1,2[\n```\n\"\"\"\nfunction Interval(left::Real, right::Real, open_right::Bool)\n\tp = OrderedPair(left,right)\n\tInterval(p,false,open_right)\nend\n\n\"\"\"\n\tInterval()\n\nEmpty `Interval`.\nEx:\n```\njulia> i = Interval()\n∅\n```\n\"\"\"\nfunction Interval()\n\tInterval(0,true,0,true)\nend\n\n\"\"\"\n\tleft(i)\n\nReturns the left limit of the given `Interval`.\nEx:\n```\njulia> i = Interval(0,2)\n[0,2]\njulia> left(i)\n0\n```\n\"\"\"\nfunction left(i::Interval)\n\ti.limits.left\nend\n\n\"\"\"\n\tright(i)\n\nReturns the right limit of the given `Interval`.\nEx:\n```\njulia> i = Interval(0,2)\n[0,2]\njulia> right(i)\n2\n```\n\"\"\"\nfunction right(i::Interval)\n\ti.limits.right\nend\n\n\"\"\"\n\tempty(i)\n\nReturns true if the given `Interval` is empty.\nEx:\n```\njulia> i = Interval(0,1)\n[0,1]\njulia> empty(i)\nfalse\njulia> j = Interval()\n∅\njulia> empty(j)\ntrue\n```\n\"\"\"\nfunction empty(i::Interval)\n\t(left(i) == right(i)) && i.open_left && i.open_right\nend\n\n\"\"\"\n\tstring(i)\n\nReturns a string representation of an `Interval`.\nEx:\n```\njulia> i = Interval(0,1)\n[0,1]\njulia> string(i)\n\"[0,1]\"\n```\n\"\"\"\nfunction string(i::Interval)\n\tempty(i) && return \"∅\"\n\tif i.open_left\n        i.open_right ? \"]$(left(i)),$(right(i))[\" : \"]$(left(i)),$(right(i))]\"\n    else\n        i.open_right ? \"[$(left(i)),$(right(i))[\" : \"[$(left(i)),$(right(i))]\"\n    end\nend \n\n\"\"\"\n\tshow(io,i)\n\nPrints the string representation of an `Interval`.\n\"\"\"\nfunction show(io::IO, i::Interval)\n\tprintln(string(i))\nend\n\n\"\"\"\n\tx ∈ i\n\nReturns true if x ∈ i and false if x ∉ i.\nEx:\n```\njulia> i = Interval(-1,true,2)\n]-1,2]\njulia> 0 ∈ i\ntrue\njulia> 2 ∈ i\ntrue\njulia> -1 ∈ i\nfalse\njulia> -0.9999999 ∈ i\ntrue\n```\n\"\"\"\nfunction ∈(x::Real, i::Interval)\n    if i.open_left\n        i.open_right ? left(i) < x < right(i) : left(i) < x <= right(i)\n    else\n        i.open_right ? left(i) <= x < right(i) : left(i) <= x <= right(i)\n    end\nend\n\n\"\"\"\n\ti1 ⊆ i2\n\nReturns true if the interval i1 is included in the interval i2.\nEx:\n```\njulia> i = Interval(0,3)\n[0,3]\njulia> j = Interval(1,2)\n[1,2]\njulia> j ⊆ i\ntrue\njulia> k = Interval(0,true,3,true)\n]0,3[\njulia> k ⊆ i\ntrue\njulia> i ⊈ k\ntrue\n```\n\"\"\"\nfunction ⊆(i1::Interval, i2::Interval)\n    if i2.open_left\n        if i2.open_right\n        \tif i1.open_left\n        \t\tc1 = left(i2) <= left(i1)\n        \telse\n        \t\tc1 = left(i2) < left(i1)\n        \tend\n        \tif i1.open_right\n        \t\tc2 = right(i1) <= right(i2)\n        \telse\n        \t\tc2 = right(i1) < right(i2)\n        \tend\n        \treturn c1 && c2\n        else\n        \tif i1.open_left\n        \t\tc1 = left(i2) <= left(i1)\n        \telse\n        \t\tc1 = left(i2) < left(i1)\n        \tend\n        \treturn c1 && (right(i1) <= right(i2))\n        end\n    else\n        if i2.open_right\n        \tif i1.open_right\n        \t\tc2 = right(i1) <= right(i2)\n        \telse\n        \t\tc2 = right(i1) < right(i2)\n        \tend\n        \treturn (left(i2) <= left(i1)) && c2\n        else\n        \treturn (left(i2) <= left(i1)) && (right(i1) <= right(i2))\n        end\n    end\nend\n\n\"\"\"\n\tcardinal(i)\n\nReturns the cardinal of the given `Interval` defined as:\n```math\n\\\\left| [a,b] \\\\right| = b - a\n```\n**Warning:** An `Interval` can be non empty and have a cardinal of zero (ex: [1,1]).\nEx:\n```\njulia> i = Interval(1,true,3)\n]1,3]\njulia> cardinal(i)\n2\njulia> cardinal(Interval(1,1))\n0\n```\n\"\"\"\nfunction cardinal(i::Interval)\n\tright(i) - left(i)\nend\n\n\"\"\"\n\tdisjoint(i1,i2)\n\nReturns true if interval i1 and interval i2 are disjoint, false otherwise.\nEx:\n```\njulia> i = Interval(0,1,true)\n[0,1[\njulia> j = Interval(1,true,2)\n]1,2]\njulia> disjoint(i,j)\ntrue\njulia> k = Interval(-1,0)\n]-1,0]\njulia> disjoint(i,k)\nfalse\n```\n\"\"\"\nfunction disjoint(i1::Interval, i2::Interval)\n\ti1 == i2 && return false\n\t(empty(i1) || empty(i2)) && return false\n\tif i1 < i2\n\t\tif right(i1) < left(i2)\n\t\t\treturn true\n\t\telseif right(i1) == left(i2)\n\t\t\t(i1.open_right || i2.open_left) ? (return true) : (return false)\n\t\telse\n\t\t\treturn false\n\t\tend\n\telse\n\t\tdisjoint(i2,i1)\n\tend\nend\n\n\"\"\"\n\ti1 ∩ i2\n\nReturns the `Interval` corresponding to the intersection between `Interval` i1 and `Interval` i2.\nIf i1 and i2 are disjoint, this function returns an empty `Interval`.\nEx:\n```\njulia> i = Interval(0,1,true)\n[0,1[\njulia> j = Interval(0.8,true,1.2)\n]0.8,1.2]\njulia> i ∩ j\n]0.8,1[\n```\n\"\"\"\nfunction ∩(i1::Interval, i2::Interval)\n    disjoint(i1,i2) && return Interval()\n    (empty(i1) || empty(i2)) && return Interval()\n\n    l::Real = left(i2)\n    open_left::Bool = i2.open_left\n    r::Real = right(i2)\n    open_right::Bool = i2.open_right\n\n    if left(i1) > left(i2)\n        l = left(i1)\n        open_left = i1.open_left\n    elseif left(i1) == left(i2)\n        open_left = i1.open_left | i2.open_left \n    end\n\n    if right(i1) < right(i2)\n        r = right(i1)\n        open_right = i1.open_right\n    elseif right(i1) == right(i2)\n        open_right = i1.open_right | i2.open_right \n    end\n\n    l == r ? Interval(OrderedPair(l,r),false,false) : Interval(OrderedPair(l,r),open_left,open_right)\nend\n\n\n\"\"\"\n\ti1 ∪ i2\n\nReturns the `Interval` corresponding to the union between `Interval` i1 and `Interval` i2.\nIf i1 and i2 are disjoint, this function raises an error since the results wouldn't be an `Interval`.\nPlease use the `IntervalUnion` type to work with unions of disjoint intervals.\nEx:\n```\njulia> i = Interval(0,1,true)\n[0,1[\njulia> j = Interval(0.8,true,1.2)\n]0.8,1.2]\njulia> i ∪ j\n[0,1.2]\n```\n\"\"\"\nfunction ∪(i1::Interval,i2::Interval)\n    if disjoint(i1,i2)\n    \tif right(i1)==left(i2) && (!i1.open_right || !i2.open_left)\n    \t\treturn Interval(left(i1),i1.open_left,right(i2),i2.open_right)\n    \telseif right(i2)==left(i1) && (!i2.open_right || !i1.open_left)\n    \t\treturn Interval(left(i2),i2.open_left,right(i1),i1.open_right)\n    \telse\n\t        throw(\"Interval $(string(i1)) and $(string(i2)) are disjoints.\")\n\t    end\n    end\n    l::Real = left(i2)\n    open_left::Bool = i2.open_left\n    r::Real = right(i2)\n    open_right::Bool = i2.open_right\n\n    if left(i1) < left(i2)\n        l = left(i1)\n        open_left = i1.open_left\n    elseif left(i1) == left(i2)\n        open_left = i1.open_left & i2.open_left\n    end\n\n    if right(i1) > right(i2)\n        r = right(i1)\n        open_right = i1.open_right\n    elseif right(i1) == right(i2)\n        open_right = i1.open_right & i2.open_right\n    end\n\n    l == r ? Interval(OrderedPair(l,r),false,false) : Interval(OrderedPair(l,r),open_left,open_right)\nend\n\n\"\"\"\n\tsetdiff(i1,i2)\n\nSetdiff is not implemented for `Interval`s.\nPlease use `IntervalUnion`s instead.\n\"\"\"\nfunction setdiff(i1::Interval, i2::Interval)\n\tthrow(\"Not implemented.\")\nend\n\n\"\"\"\n\tsymdiff(i1,i2)\n\nSymdiff is not implemented for `Interval`s.\nPlease use `IntervalUnion`s instead.\n\"\"\"\nfunction symdiff(i1::Interval, i2::Interval)\n\tthrow(\"Not implemented.\")\nend\n\n\"\"\"\n\tcompact(i)\n\nReturns the compact of the given `Interval`.\nEx: \n```\njulia> i = Interval(0,true,1)\n]0,1]\njulia> compact(i)\n[0,1]\n```\n\"\"\"\nfunction compact(i::Interval)\n\tempty(i) && return Interval()\n\tInterval(left(i),right(i))\nend\n\n\"\"\"\n\tcompactness(i)\n\nRetuns the compactness of a simple `Interval`, which is always 1 unless it is empty.\nEx:\n```\njulia> compactness(Interval(0,true,1))\n1.0\njulia> compactness(Interval())\n0.0\n```\n\"\"\"\nfunction compactness(i::Interval)\n\tempty(i) ? 0.0 : 1.0\nend\n\n\"\"\"\n\tsuperset(i)\n\nReturns the superset of the given `Interval`, which is the `Interval` itself.\nEx:\n```\njulia> superset(Interval(0,true,1))\n]0,1]\n```\n\"\"\"\nfunction superset(i::Interval)\n\treturn i\nend\n\n\"\"\"\n\tsample(i)\n\nReturns a number drawn uniformly at random in the given `Interval`.\nEx:\n```\njulia> i = Interval(2,4,true)\n[2,4[\njulia> sample(i)\n3.935796996224805\n```\n\"\"\"\nfunction sample(i::Interval)\n\tif cardinal(i) == 0 && (i.open_left && i.open_right)\n\t\tthrow(\"Cannot sample from empty Interval.\")\n\tend\n\ts = rand() * (right(i)-left(i)) + left(i)\n\tif i.open_left && s == left(i)\n\t\treturn sample(i)\n\telseif i.open_right && s == right(i)\n\t\treturn sample(i)\n\telse\n\t\treturn s\n\tend\nend\n\n\"\"\"\n\tsample(i,n)\n\nReturns an array of n random numbers drawn uniformly in the given `Interval`.\nEx:\n```\njulia> i = Interval(3,true,6)\n]3,6]\njulia> sample(i,4)\n4-element Array{Float64,1}:\n 5.543827369817867 \n 4.678054798740224 \n 3.1740822420010355\n 3.6870186624440504\n```\n\"\"\"\nfunction sample(i::Interval, n::Int64)\n\t[sample(i) for x in 1:n]\nend\n\n\"\"\"\n\tjaccard(i1,i2)\n\nReturns the jaccard coefficient between two `Interval`s defined as:\n```math\n\\\\frac{\\\\left| A \\\\cap B \\\\right|}{\\\\left| A \\\\cup B \\\\right|}\n```\nNote: If |i1 ∪ i2|=0, this function returns 0.\nEx:\n```\njulia> i = Interval(3,true,6)\n]3,6]\njulia> j = Interval(4,7)\n[4,7]\njulia> jaccard(i,j)\n0.5\n```\n\"\"\"\nfunction jaccard(i1::Interval, i2::Interval)\n\ti1 == i2 && return 1.0\n\tu = i1 ∪ i2\n\tcardu = cardinal(u)\n\tcardu != 0 ? cardinal(i1 ∩ i2) / cardu : 0.0\nend\n\n\"\"\"\n\toverlap_coefficient(i1,i2)\n\nReturns the overlap coefficient between two `Interval`s defined as:\n```math\n\\\\frac{\\\\left| A \\\\cap B \\\\right|}{min \\\\left( \\\\left|A \\\\right|, \\\\left|B \\\\right| \\\\right)}\n```\nThis means that if setA is a subset of B or the converse then the overlap coefficient is equal to 1.\nNote: If `|A|=0` and `|B|=0`, this function returns 0.\nEx:\n```\njulia> i = Interval(3,true,6)\n]3,6]\njulia> j = Interval(4,7)\n[4,7]\njulia> overlap_coefficient(i,j)\n0.6666666666666666\n```\n\"\"\"\nfunction overlap_coefficient(i1::Interval, i2::Interval)\n\ti1 == i2 && return 1.0\n\tdenom = min(cardinal(i1),cardinal(i2))\n\tdenom != 0 ? cardinal(i1 ∩ i2) / denom : 0\nend\n\n\"\"\"\n\tdice_coefficient(i1,i2)\n\nReturns the Sørensen–Dice coefficient between two `Interval`s defined as:\n```math\n\\\\frac{2 \\\\left| A \\\\cap B \\\\right|}{\\\\left|A \\\\right| + \\\\left|B \\\\right|}\n```\nNote: If `|A|+|B|=0`, this function returns 0.\nEx:\n```\njulia> i = Interval(3,true,6)\n]3,6]\njulia> j = Interval(4,7)\n[4,7]\njulia> dice_coefficient(i,j)\n0.6666666666666666\n```\n\"\"\"\nfunction dice_coefficient(i1::Interval, i2::Interval)\n\ti1 == i2 && return 1.0\n\tdenom = cardinal(i1) + cardinal(i2)\n\tdenom != 0 ? 2 * cardinal(i1 ∩ i2) / denom : 0\nend\n\n\"\"\"\n\tIntervalUnion\n\n`IntervalUnion` representation.\n\"\"\"\nmutable struct IntervalUnion\n\tcomponents::Array{Interval,1}\n\tfunction IntervalUnion(intervals::Array{Interval,1})\n\t\tsorted_intervals = sort(intervals)\n\t\tcleaned_intervals = Interval[]\n\t\tfor interval in sorted_intervals\n\t\t\tif !empty(interval)\n\t\t\t\tif length(cleaned_intervals) == 0\n\t\t\t\t\tpush!(cleaned_intervals,interval)\n\t\t\t\telse\n\t\t\t\t\tif !disjoint(cleaned_intervals[end],interval) || ((right(cleaned_intervals[end]) == left(interval)) && (!cleaned_intervals[end].open_right || !interval.open_left))\n\t\t\t\t\t\tcleaned_intervals[end] = cleaned_intervals[end] ∪ interval\n\t\t\t\t\telse\n\t\t\t\t\t\tpush!(cleaned_intervals,interval)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\tnew(cleaned_intervals)\n\tend\nend\n\n\"\"\"\n\tIntervalUnion()\n\nEmpty union of `Interval`s.\nEx:\n```\njulia> i = IntervalUnion()\n∅\n```\n\"\"\"\nfunction IntervalUnion()\n\tIntervalUnion(Interval[])\nend\n\n\"\"\"\n\tIntervalUnion(left,right)\n\nSimplified constructor for `IntervalUnions` with only one `Interval` closed on both side.\nEx:\n```\njulia> i = IntervalUnion(2,3)\n[2,3]\n\"\"\"\nfunction IntervalUnion(left::Real, right::Real)\n\tIntervalUnion([Interval(left,right)])\nend\n\n\"\"\"\n\tIntervalUnion(left,open_left,right)\n\nSimplified constructor for `IntervalUnions` with only one `Interval` closed on the right side.\nEx:\n```\njulia> i = IntervalUnion(2,true,3)\n]2,3]\njulia> i = IntervalUnion(2,false,3)\n[2,3]\n\"\"\"\nfunction IntervalUnion(left::Real, open_left::Bool, right::Real)\n\tIntervalUnion([Interval(left,open_left,right)])\nend\n\n\"\"\"\n\tIntervalUnion(left,right,open_right)\n\nSimplified constructor for `IntervalUnions` with only one `Interval` closed on the left side.\nEx:\n```\njulia> i = IntervalUnion(2,3,true)\n[2,3[\njulia> i = IntervalUnion(2,3,false)\n[2,3]\n\"\"\"\nfunction IntervalUnion(left::Real, right::Real, open_right::Bool)\n\tIntervalUnion([Interval(left,right,open_right)])\nend\n\n\"\"\"\n\tIntervalUnion(left,open_left,right,open_right)\n\nSimplified constructor for `IntervalUnions` with only one `Interval`.\nEx:\n```\njulia> i = IntervalUnion(2,true,3,true)\n]2,3[\njulia> i = IntervalUnion(2,false,3,false)\n[2,3]\n\"\"\"\nfunction IntervalUnion(left::Real, open_left::Bool, right::Real, open_right::Bool)\n\tIntervalUnion([Interval(left,open_left,right,open_right)])\nend\n\n\"\"\"\n\tempty(iu)\n\nReturns true if the given `IntervalUnion` is empty.\nEx:\n```\njulia> empty(IntervalUnion())\ntrue\njulia> empty(IntervalUnion([Interval(0,1)]))\nfalse\n```\n\"\"\"\nfunction empty(iu::IntervalUnion)\n\t(number_of_components(iu) == 0) || all([empty(c) for c in iu.components])\nend\n\n\"\"\"\n\tstring(iu)\n\nReturns a string representation of an `IntervalUnion`.\nEx:\n```\njulia> string(IntervalUnion([Interval(0,1,true),Interval(1,true,2)]))\n\"[0,1[ ∪ ]1,2]\"\n```\n\"\"\"\nfunction string(iu::IntervalUnion)\n\tif empty(iu)\n\t\treturn \"∅\"\n\telseif number_of_components(iu) == 1\n\t\treturn string(iu.components[1])\n\telse\n\t\treturn reduce((x,y)->\"$(string(x)) ∪ $(string(y))\", iu.components)\n\tend\nend\n\n\"\"\"\n\tshow(io,iu)\n\nPrints the string representation of an `IntervalUnion`.\n\"\"\"\nfunction show(io::IO, iu::IntervalUnion)\n\tprintln(string(iu))\nend\n\n\"\"\"\n\tiu1 == iu2\n\nEquality defined for `IntervalUnion`s.\n\"\"\"\nfunction ==(iu1::IntervalUnion, iu2::IntervalUnion)\n\tif number_of_components(iu1) != number_of_components(iu2)\n\t\treturn false\n\tend\n\tfor (i,j) in zip(iu1.components,iu2.components)\n\t\tif i != j\n\t\t\treturn false\n\t\tend\n\tend\n\ttrue\nend\n\n\"\"\"\n\tleft(iu)\n\nReturns a vector of left limits of the given `IntervalUnion`.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,1,true),Interval(1,true,2)])\n[0,1[ ∪ ]1,2]\njulia> left(i)\n2-element Array{Int64,1}:\n 0\n 1\n```\n\"\"\"\nfunction left(iu::IntervalUnion)\n\t[left(i) for i in iu.components]\nend\n\n\"\"\"\n\tright(iu)\n\nReturns a vector of right limits of the given `IntervalUnion`.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,1,true),Interval(1,true,2)])\n[0,1[ ∪ ]1,2]\njulia> left(i)\n2-element Array{Int64,1}:\n 1\n 2\n```\n\"\"\"\nfunction right(iu::IntervalUnion)\n\t[right(i) for i in iu.components]\nend\n\n\"\"\"\n\tlimits(iu)\n\nReturns a sorted array of limits of the given `IntervalUnion`.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,1,true),Interval(1,true,2)])\n[0,1[ ∪ ]1,2]\njulia> limits(i)\n3-element Array{Real,1}:\n 0\n 1\n 2\n```\n\"\"\"\nfunction limits(iu::IntervalUnion)\n\tlimit_set = Set{Real}()\n\tfor i in iu.components\n\t\tpush!(limit_set,left(i))\n\t\tpush!(limit_set,right(i))\n\tend\n\tlimit_array = Real[]\n\tfor l in limit_set\n\t\tpush!(limit_array,l)\n\tend\n\tsort(limit_array)\nend\n\n\"\"\"\n\tcompact(iu)\n\nReturns the compact of the given `IntervalUnion`.\nEx: \n```\njulia> i = IntervalUnion([Interval(0,true,1),Interval(2,3)])\n]0,1] ∪ [2,3]\njulia> compact(i)\n[0,3]\n```\n\"\"\"\nfunction compact(iu::IntervalUnion)\n\tempty(iu) && return IntervalUnion()\n\tl = minimum(left(iu))\n\tr = maximum(right(iu))\n\tif l == -Inf || r == Inf\n\t\tthrow(\"IntervalUnion $(string(iu)) has no compact.\")\n\tend\n\tIntervalUnion([Interval(l,r)])\nend\n\n\"\"\"\n\tcompactness(iu)\n\nReturns the compactness of the given `IntervalUnion` defined as:\n```math\n\\\\frac{ \\\\left| iu \\\\right|}{\\\\left| compact(iu) \\\\right|}\n```\nNote: If `|compact(iu)|=0`, this function returns 0.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,true,1),Interval(3,5)])\n]0,1] ∪ [3,5]\njulia> compactness(i)\n0.6\n```\n\"\"\"\nfunction compactness(iu::IntervalUnion)\n\tcciu = cardinal(compact(iu))\n\tcciu != 0 ? cardinal(iu) / cciu : 0\nend\n\n\"\"\"\n\tsuperset(iu)\n\nReturns the superset of the given `IntervalUnion`.\nEx: \n```\njulia> i = IntervalUnion([Interval(0,true,1),Interval(2,3)])\n]0,1] ∪ [2,3]\njulia> superset(i)\n]0,3]\n```\nNote: `superset` and `compact` are strongly related but `compact` is always closed on both sides.\n\"\"\"\nfunction superset(iu::IntervalUnion)\n\tif empty(iu) || number_of_components(iu) < 2\n\t\tthrow(\"IntervalUnion $(string(iu)) has not enough components.\")\n\tend\n\tsmallest = minimum(iu.components)\n\tlargest  = maximum(iu.components)\n\tIntervalUnion([Interval(left(smallest), smallest.open_left, right(largest), largest.open_right)]) \nend\n\n\"\"\"\n\tsuper_complement(iu)\n\nReturns the complement of the superset of the given `IntervalUnion`.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,true,1),Interval(2,3)])\n]0,1] ∪ [2,3]\njulia> super_complement(i)\n]-Inf,0] ∪ ]3,Inf[\n```\n\"\"\"\nfunction super_complement(iu::IntervalUnion)\n\tcomplement(superset(iu))\nend\n\n\"\"\"\n\trestricted_complement(iu)\n\nReturns the complement of iu intersected with its superset.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,1),Interval(4,5)])\n[0,1] ∪ [4,5]\njulia> restricted_complement(i)\n]1,4[\njulia> j = IntervalUnion([Interval(0,true,1,true),Interval(2.5,true,3),Interval(3.5,6)])\n]0,1[ ∪ ]2.5,3] ∪ [3.5,6]\njulia> restricted_complement(j)\n[1,2.5] ∪ ]3,3.5[\n```\n\"\"\"\nfunction restricted_complement(iu::IntervalUnion)\n\tsuperset(iu) ∩ complement(iu)\nend\n\n\"\"\"\n\tcomplement_cardinal(iu)\n\nReturns the cardinal of the restricted complement of iu.\nEx:\n```\njulia> IntervalUnion([Interval(0,1),Interval(4,5)])\n[0,1] ∪ [4,5]\njulia> complement_cardinal(i)\n3\njulia> j = IntervalUnion([Interval(0,true,1,true),Interval(2.5,true,3),Interval(3.5,6)])\n]0,1[ ∪ ]2.5,3] ∪ [3.5,6]\njulia> complement_cardinal(j)\n2\n```\n\"\"\"\nfunction complement_cardinal(iu::IntervalUnion)\n\tcardinal(restricted_complement(iu))\nend\n\n\"\"\"\n\tx ∈ iu\n\nReturns true if x ∈ iu and false if x ∉ iu.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,true,1,true),Interval(2.5,true,3),Interval(3.5,6)])\n]0,1[ ∪ ]2.5,3] ∪ [3.5,6]\njulia> 0.5 ∈ i\ntrue\njulia> 1 ∈ i\nfalse\njulia> 0.9999999 ∈ i\ntrue\n```\n\"\"\"\nfunction ∈(x::Real, iu::IntervalUnion)\n\tfor i in iu.components\n\t\tx ∈ i && return true\n\tend\n\tfalse\nend\n\n\"\"\"\n\tcardinal(iu)\n\nReturns the cardinal of the given `IntervalUnion`.\n```math\n\\\\left| [a,b] ∪ ]c,d] ∪ [e,f[ ∪ ]g,h[ \\\\right| = (b - a) + (d-c) + (f-e) + (h-g)\n```\nEx:\n```\njulia> i = IntervalUnion([Interval(0,true,1,true),Interval(2.5,true,3),Interval(3.5,6)])\n]0,1[ ∪ ]2.5,3] ∪ [3.5,6]\njulia> cardinal(i)\n4.0\n```\n\"\"\"\nfunction cardinal(iu::IntervalUnion)\n\tempty(iu) && return 0\n\tsum([cardinal(i) for i in iu.components])\nend\n\n\"\"\"\n\tnumber_of_components(iu)\n\nReturns the number of components in the given `IntervalUnion`.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,true,1,true),Interval(2.5,true,3),Interval(3.5,6)])\n]0,1[ ∪ ]2.5,3] ∪ [3.5,6]\njulia> number_of_components(i)\n3\n```\n\"\"\"\nfunction number_of_components(iu::IntervalUnion)\n\tlength(iu.components)\nend\n\n\"\"\"\n\tiu1 ⊆ iu2\n\nReturns true if the `IntervalUnion` iu1 is included in the `IntervalUnion` iu2.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,true,1,true),Interval(2.5,true,3),Interval(3.5,6)])\n]0,1[ ∪ ]2.5,3] ∪ [3.5,6]\njulia> j = IntervalUnion([Interval(2.6,3),Interval(3.5,4,true)])\n[2.6,3] ∪ [3.5,4[\njulia> j ⊆ i\ntrue\n```\n\"\"\"\nfunction ⊆(iu1::IntervalUnion, iu2::IntervalUnion)\n    for i in iu1.components\n    \t!any([i ⊆ j for j in iu2.components]) && return false\n    end\n    true\nend\n\n\"\"\"\n\tiu1 ∪ iu2\n\nReturns the `IntervalUnion` corresponding to the union between \n`IntervalUnion` iu1 and `IntervalUnion` iu2.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,1,true),Interval(1,true,2.3)])\n[0,1[ ∪ ]1,2.3]\njulia> j = IntervalUnion([Interval(1,1),Interval(2.3,true,4,true)])\n[1,1] ∪ ]2.3,4[\njulia> i ∪ j\n[0,4[\njulia> k = IntervalUnion([Interval(-1,0,true),Interval(3,4)])\n[-1,0[ ∪ [3,4]\njulia> i ∪ k\n[-1,1[ ∪ ]1,2.3] ∪ [3,4]\njulia> i ∪ IntervalUnion()\n[0,1[ ∪ ]1,2.3]\n```\n\"\"\"\nfunction ∪(iu1::IntervalUnion, iu2::IntervalUnion)\n\tIntervalUnion(vcat(iu1.components,iu2.components))\nend\n\n\"\"\"\n\tiu1 ∩ iu2\n\nReturns the `IntervalUnion` corresponding to the intersection between \n`IntervalUnion` iu1 and `IntervalUnion` iu2.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,1,true),Interval(1,true,2.3)])\n[0,1[ ∪ ]1,2.3]\njulia> j = IntervalUnion([Interval(1,1),Interval(2.3,true,4,true)])\n[1,1] ∪ ]2.3,4[\njulia> i ∩ j\n∅\njulia> k = IntervalUnion([Interval(-1,0,true),Interval(3,4)])\n[-1,0[ ∪ [3,4]\njulia> j ∩ k\n[3,4[\njulia> i ∩ IntervalUnion()\n∅\n```\n\"\"\"\nfunction ∩(iu1::IntervalUnion, iu2::IntervalUnion)\n\tcomponents = Interval[]\n\tfor c1 in iu1.components\n\t\tfor c2 in iu2.components\n\t\t\tif !disjoint(c1,c2)\n\t\t\t\tpush!(components,c1 ∩ c2)\n\t\t\tend\n\t\tend\n\tend\n\tIntervalUnion(components)\nend\n\n\"\"\"\n\tcomplement(iu)\n\nReturns the complement of the given `IntervalUnion`.\n\nEx:\n```\njulia> i = IntervalUnion([Interval(0,1)])\n[0,1]\njulia> complement(i)\n]-Inf,0[ ∪ ]1,Inf[\njulia> j = IntervalUnion([Interval(0,0)])\n[0,0]\njulia> complement(j)\n]-Inf,0[ ∪ ]0,Inf[\njulia> k = IntervalUnion([Interval(0,true,0,true)])\n]0,0[\njulia> complement(k)\n]-Inf,Inf[\njulia> complement(IntervalUnion())\n]-Inf,Inf[\njulia> l = IntervalUnion([Interval(0,1,true),Interval(2,true,3)])\n[0,1[ ∪ ]2,3]\njulia> complement(l)\n]-Inf,0[ ∪ [1,2] ∪ ]3,Inf[\n```\n\"\"\"\nfunction complement(iu::IntervalUnion)\n\tcomponents = Interval[]\n\tif empty(iu)\n\t\treturn IntervalUnion([Interval(-Inf,true,Inf,true)])\n\telseif number_of_components(iu) == 1\n\t\tif left(iu.components[1]) == -Inf && right(iu.components[1]) == Inf\n\t\t\treturn IntervalUnion()\n\t\telseif left(iu.components[1]) == -Inf && right(iu.components[1]) != Inf\n\t\t\tif iu.components[1].open_right\n\t\t\t\treturn IntervalUnion([Interval(right(iu.components[1]),Inf,true)])\n\t\t\telse\n\t\t\t\treturn IntervalUnion([Interval(right(iu.components[1]),true,Inf,true)])\n\t\t\tend\n\t\telseif left(iu.components[1]) != -Inf && right(iu.components[1]) == Inf\n\t\t\tif iu.components[1].open_left\n\t\t\t\treturn IntervalUnion([Interval(-Inf,true,left(iu.components[1]))])\n\t\t\telse\n\t\t\t\treturn IntervalUnion([Interval(-Inf,true,left(iu.components[1]),true)])\n\t\t\tend\n\t\telse\n\t\t\tif iu.components[1].open_left\n\t\t\t\tif iu.components[1].open_right\n\t\t\t\t\treturn IntervalUnion([Interval(-Inf,true,left(iu.components[1])),Interval(right(iu.components[1]),Inf,true)])\n\t\t\t\telse\n\t\t\t\t\treturn IntervalUnion([Interval(-Inf,true,left(iu.components[1])),Interval(right(iu.components[1]),true,Inf,true)])\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tif iu.components[1].open_right\n\t\t\t\t\treturn IntervalUnion([Interval(-Inf,true,left(iu.components[1]),true),Interval(right(iu.components[1]),Inf,true)])\n\t\t\t\telse\n\t\t\t\t\treturn IntervalUnion([Interval(-Inf,true,left(iu.components[1]),true),Interval(right(iu.components[1]),true,Inf,true)])\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\telse\n\t\tif left(iu.components[1]) != -Inf\n\t\t\tif iu.components[1].open_left\n\t\t\t\tpush!(components,Interval(-Inf,true,left(iu.components[1])))\n\t\t\telse\n\t\t\t\tpush!(components,Interval(-Inf,true,left(iu.components[1]),true))\n\t\t\tend\n\t\tend\n\t\tfor (c1,c2) in zip(iu.components[1:(end-1)],iu.components[2:end])\n\t\t\tif c1.open_right && c2.open_left\n\t\t\t\tpush!(components,Interval(right(c1),left(c2)))\n\t\t\telseif !c1.open_right && c2.open_left\n\t\t\t\tpush!(components,Interval(right(c1),true,left(c2)))\n\t\t\telseif c1.open_right && !c2.open_left\n\t\t\t\tpush!(components,Interval(right(c1),left(c2),true))\n\t\t\telse\n\t\t\t\tpush!(components,Interval(right(c1),true,left(c2),true))\n\t\t\tend\n\t\tend\n\t\tif right(iu.components[end]) != Inf\n\t\t\tif iu.components[end].open_right\n\t\t\t\tpush!(components,Interval(right(iu.components[end]),Inf,true))\n\t\t\telse\n\t\t\t\tpush!(components,Interval(right(iu.components[end]),true,Inf,true))\n\t\t\tend\n\t\tend\n\tend\n\tIntervalUnion(components)\nend\n\n\"\"\"\n\tsetdiff(iu1,iu2)\n\nReturns the `IntervalUnion` with elements in iu1 but not in iu2.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,1,true),Interval(1,true,2.3)])\n[0,1[ ∪ ]1,2.3]\njulia> j = IntervalUnion([Interval(1,1),Interval(2.3,true,4,true)])\n[1,1] ∪ ]2.3,4[\njulia> k = IntervalUnion([Interval(-1,0,true),Interval(3,4)])\n[-1,0[ ∪ [3,4]\njulia> julia> setdiff(j,k)\n[1,1] ∪ ]2.3,3[\n```\n\"\"\"\nfunction setdiff(iu1::IntervalUnion, iu2::IntervalUnion)\n\tcomplement(iu2) ∩ iu1\nend\n\n\"\"\"\n\tsymdiff(iu1,iu2)\n\nReturns the `IntervalUnion` with elements in iu1 or iu2 but not in both.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,1,true),Interval(1,true,2.3)])\n[0,1[ ∪ ]1,2.3]\njulia> j = IntervalUnion([Interval(1,1),Interval(2.3,true,4,true)])\n[1,1] ∪ ]2.3,4[\njulia> k = IntervalUnion([Interval(-1,0,true),Interval(3,4)])\n[-1,0[ ∪ [3,4]\njulia> symdiff(i,k)\n[-1,1[ ∪ ]1,2.3] ∪ [3,4]\njulia> symdiff(j,k)\n[-1,0[ ∪ [1,1] ∪ ]2.3,3[ ∪ [4,4]\n```\n\"\"\"\nfunction symdiff(iu1::IntervalUnion, iu2::IntervalUnion)\n\tsetdiff(iu1 ∪ iu2, iu1 ∩ iu2)\nend\n\n\"\"\"\n\tsample(iu)\n\nReturns a number drawn uniformly at random in the given `IntervalUnion`.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,1,true),Interval(1,true,2.3)])\n[0,1[ ∪ ]1,2.3]\njulia> sample(i)\n0.22557298488974253\n```\n\"\"\"\nfunction sample(iu::IntervalUnion)\n\tif empty(iu)\n\t\tthrow(\"Cannot sample from empty union of Intervals.\")\n\tend\n\tsize_components = [cardinal(i) for i in iu.components]\n\tfull_size = sum(size_components)\n\tif full_size == 0\n\t\treturn left(iu.components[rand(1:number_of_components(iu))])\n\tend\n\tsize_components_normalized = size_components ./ full_size\n\tprobabilities = cumsum(size_components_normalized)\n\tr = rand()\n\tidx_component = findfirst(x->x>r,probabilities)\n\tsample(iu.components[idx_component])\nend\n\n\"\"\"\n\tsample(iu,n)\n\nReturns an array of n random numbers drawn uniformly in the given `IntervalUnion`.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,1,true),Interval(1,true,2.3)])\n[0,1[ ∪ ]1,2.3]\njulia> sample(i,4)\n4-element Array{Float64,1}:\n 0.7974550091944592 \n 0.36823887828930935\n 1.1796141777238074 \n 2.2731170537623138\n```\n\"\"\"\nfunction sample(iu::IntervalUnion, n::Int64)\n\t[sample(iu) for x in 1:n]\nend\n\n\"\"\"\n\tjaccard(iu1,iu2)\n\nReturns the jaccard similarity between two `IntervalUnion`s.\nIf |iu1 ∪ iu2|=0, this function returns 0.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,1,true),Interval(1,true,2.3)])\n[0,1[ ∪ ]1,2.3]\njulia> j = IntervalUnion([Interval(1,1),Interval(2.3,true,4,true)])\n[1,1] ∪ ]2.3,4[\njulia> k = IntervalUnion([Interval(-1,0,true),Interval(3,4)])\n[-1,0[ ∪ [3,4]\njulia> jaccard(i,j)\n0.0\njulia> jaccard(j,k)\n0.37037037037037035\n```\n\"\"\"\nfunction jaccard(iu1::IntervalUnion, iu2::IntervalUnion)\n\tu = iu1 ∪ iu2\n\tcardu = cardinal(u)\n\tcardu != 0 ? cardinal(iu1 ∩ iu2) / cardu : 0.0\nend\n\n\"\"\"\n\toverlap_coefficient(iu1,iu2)\n\nReturns the overlap coefficient between two `IntervalUnion`s defined as:\n```math\n\\\\frac{\\\\left| A \\\\cap B \\\\right|}{min \\\\left( \\\\left|A \\\\right|, \\\\left|B \\\\right| \\\\right)}\n```\nThis means that if set A is a subset of B or the converse then the overlap coefficient is equal to 1.\nNote: If `|A|=0` and `|B|=0`, this function returns 0.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,1,true),Interval(1,true,2.3)])\n[0,1[ ∪ ]1,2.3]\njulia> j = IntervalUnion([Interval(1,1),Interval(2.3,true,4,true)])\n[1,1] ∪ ]2.3,4[\njulia> k = IntervalUnion([Interval(-1,0,true),Interval(3,4)])\n[-1,0[ ∪ [3,4]\njulia> overlap_coefficient(i,j)\n0.0\njulia> overlap_coefficient(j,k)\n0.588235294117647\n```\n\"\"\"\nfunction overlap_coefficient(iu1::IntervalUnion, iu2::IntervalUnion)\n\tdenom = min(cardinal(iu1),cardinal(iu2))\n\tdenom != 0 ? cardinal(iu1 ∩ iu2) / denom : 0\nend\n\n\"\"\"\n\tdice_coefficient(iu1,iu2)\n\nReturns the Sørensen–Dice coefficient between two `IntervalUnion`s defined as:\n```math\n\\\\frac{2 \\\\left| A \\\\cap B \\\\right|}{\\\\left|A \\\\right| + \\\\left|B \\\\right|}\n```\nNote: If `|A|+|B|=0`, this function returns 0.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,1,true),Interval(1,true,2.3)])\n[0,1[ ∪ ]1,2.3]\njulia> j = IntervalUnion([Interval(1,1),Interval(2.3,true,4,true)])\n[1,1] ∪ ]2.3,4[\njulia> k = IntervalUnion([Interval(-1,0,true),Interval(3,4)])\n[-1,0[ ∪ [3,4]\njulia> dice_coefficient(i,j)\n0.0\njulia> dice_coefficient(j,k)\n0.5405405405405405\n```\n\"\"\"\nfunction dice_coefficient(iu1::IntervalUnion, iu2::IntervalUnion)\n\tdenom = cardinal(iu1) + cardinal(iu2)\n\tdenom != 0 ? 2 * cardinal(iu1 ∩ iu2) / denom : 0\nend", "meta": {"hexsha": "104081c59c33608a42b8782b20456bc5c986eef0", "size": 31113, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/base.jl", "max_stars_repo_name": "juliastreamgraphs/IntervalUnions.jl", "max_stars_repo_head_hexsha": "0e380d8ba2241aec06511346010b80088e5c4753", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/base.jl", "max_issues_repo_name": "juliastreamgraphs/IntervalUnions.jl", "max_issues_repo_head_hexsha": "0e380d8ba2241aec06511346010b80088e5c4753", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-04-29T15:03:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-29T15:03:24.000Z", "max_forks_repo_path": "src/base.jl", "max_forks_repo_name": "juliastreamgraphs/IntervalUnions.jl", "max_forks_repo_head_hexsha": "0e380d8ba2241aec06511346010b80088e5c4753", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3395061728, "max_line_length": 168, "alphanum_fraction": 0.6569601131, "num_tokens": 10367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7592872485042353}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.17\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 85d5a830-4116-11eb-1479-630b53b50e94\nbegin\n\tusing Pkg\n    Pkg.activate(pwd())\nend\n\n# ╔═╡ 4862c2d0-4116-11eb-3f26-1bdefcb9ce3d\nbegin\n\tusing UCIData\n\tusing PlutoUI\n\tusing DataFrames\n\tusing Statistics\n\tusing LinearAlgebra\n\tusing Plots\n\tusing Clustering\n\tusing Distances\nend\n\n# ╔═╡ c73d5420-4126-11eb-19b3-bf6c04aef086\nmd\"\"\"\n# Data Mining\n## Assignment 2 - K-means Clustering\n### Aadam & Obaidullah (CS1945 & CS1947)\n\"\"\"\n\n# ╔═╡ 360ab320-411d-11eb-2d11-c9fe7b3137d1\nplotly()\n\n# ╔═╡ 73936e9e-4116-11eb-0594-1d202bd073cd\nfunction Kmeans(X, k; max_iters = 300, tol = 1e-5)\n    # Reshape 2D array to a 1D array with length of all training examples\n    X_array_list = collect(eachrow(X))\n\n    # Save some info on the incoming data\n    N = length(X_array_list)  # Length of all training examples\n    n = length(X_array_list[1])  # Length of a single training example\n    distances = zeros(N)  # Empty vector for all training examples.\n\n    # Step 1: Random initialization\n    reps_centroids = [zeros(n) for grp = 1:k]  # Initiate centroids for each\n    labels = rand(1:k, N)  # Randomly assign labels to all training examples\n\n    J_previous = Inf\n\n    for iter = 1:max_iters\n\n        # Step 2: Update the representative centroids for each group\n        for j = 1:k\n            # get group indices for each group\n            group_idx = [i for i = 1:N if labels[i] == j]\n\n            # use group indices to locate each group\n            reps_centroids[j] = mean(X_array_list[group_idx]);\n        end;\n\n        # Step 3: Update the group labels\n        for i = 1:N\n            # compute the distance between each example and the updated centroid\n            nearest_rep_distance = \n\t\t\t[norm(X_array_list[i] - reps_centroids[x]) for x = 1:k]\n\n            # update distances and label arrays \n            # findmin returns the min value & index location\n            distances[i], labels[i] = findmin(nearest_rep_distance)\n        end;\n\n        # Step 4: Compute the clustering cost\n        J = (norm(distances)^ 2) / N\n\n        # Show progress and terminate if J stopped decreasing.\n        println(\"Iteration \", iter, \": Jclust = \", J, \".\")\n\n        # Final Step 5: Check for convergence\n        if iter > 1 && abs(J - J_previous) < (tol * J)\n            # Terminate algorithm with the assumption that K-means has converged\n            return labels, reps_centroids\n        end\n\n        J_previous = J\n    end\n\treturn labels, reps_centroids\nend\n\n# ╔═╡ aac40900-41cc-11eb-1103-97d9373bdd65\nfunction calculate_average_distance(i, X, result)\n\tdist = 0\n\tcenter = result.centers[i]\n\tfor instance in X[:, result.assignments .== i]\n\t\tdist += Euclidean()(instance, center)\n\tend\n\treturn dist/result.counts[i]\nend\n\n# ╔═╡ 12615c80-41c7-11eb-2aed-c1eb96003ff1\nfunction dbi(X, result)\n\tnum_of_clusters = length(result.counts)\n\t\n\t#average distance of all points in a cluster to its center, for each cluster\n    average_centroid_distances = [\n\t\tcalculate_average_distance(i, X, result) for i in 1:num_of_clusters]\n\t\n\tsum_Dij = 0\n\t\n\t#calculate the sum Dij\n    for i in 1:num_of_clusters     \n        max_Dij = 0\n        \n        #calculate the max Dij\n        for j in 1:num_of_clusters            \n            if i != j\n\t\t\t\t\n\t\t\t\t#calculate di + dj\n\t\t\t\tnumerator = \n\t\t\t\taverage_centroid_distances[i] + average_centroid_distances[j]\n\n\t\t\t\t#calculate dij\n\t\t\t\tdenominator = \n\t\t\t\tEuclidean()( result.centers[i], result.centers[j] )\n\n\t\t\t\tcurrent_Dij = numerator/denominator\n\n\t\t\t\tif max_Dij < current_Dij\n\t\t\t\t\tmax_Dij = current_Dij\n\t\t\t\tend\n\t\t\tend\n                \n\t\tend\n\t\tsum_Dij += max_Dij\n\tend\n    \n    return sum_Dij / num_of_clusters\nend\n\n# ╔═╡ c7001000-42c6-11eb-23d1-314932816f0a\nfunction big_delta(maskci, distances)\n\tmaximum(distances[maskci, :][:, maskci])\nend\n\n# ╔═╡ c6ca5a00-42c6-11eb-386e-2f13a99d75b6\nfunction delta(maskci, maskcj, distances)\n\tminimum(distances[maskci, :][:, maskcj])\nend\n\n# ╔═╡ c69d2f80-42c6-11eb-10cf-e70c07e40e97\nfunction dunn(X, result)\n\tn = length(result.counts) # number of clusters\n\t\n\tdistances = pairwise(Euclidean(), X, dims=2)\n\t\n\tdeltas = ones(n, n) * Inf\n\tbig_deltas = zeros(n)\n\t\n\tfor k in 1:n\n\t\tfor l in 1:n\n\t\t\tif k == l\n\t\t\t\tcontinue\n\t\t\tend\n            deltas[k, l] = delta(\n\t\t\t\tresult.assignments .== k, \n\t\t\t\tresult.assignments .== l, \n\t\t\t\tdistances)\n\t\tend\n        \n        big_deltas[k] = big_delta(result.assignments .== k, distances)\n\t\t\n\tend\n\tminimum(deltas)/maximum(big_deltas)\nend\n\n# ╔═╡ 9accd320-4117-11eb-0fc4-15e8e85040a8\ndatasets = [\"iris\" => \"iris\", \"glass-identification\" => \"glass\"];\n\n# ╔═╡ 8b43a9a0-4118-11eb-127d-d57dcea189e1\nmd\"\"\"\nDataset: $(@bind selected_dataset Select(datasets))\n\n\"\"\"\n\n# ╔═╡ 73c57b20-4116-11eb-3dba-01c9f7b91fa7\ndata = UCIData.dataset(selected_dataset);\n\n# ╔═╡ 5cddc6a0-411c-11eb-2380-1b9442938a9b\nfeatures = collect(Matrix(data[:, 2:end-1])');\n\n# ╔═╡ bec93fa0-4119-11eb-026e-0be14d6a5779\nmd\"\"\"\nVlaue of **k**: $(@bind k Slider(2:15; show_value=true))\n\"\"\"\n# size(UCIData.dataset(selected_dataset))[1]\n\n# ╔═╡ 737b2bb0-4116-11eb-124b-d981032a9638\nresult = kmeans(features, k);\n\n# ╔═╡ 725d2e10-42c2-11eb-3ee7-4ba089ebb440\nmd\"\"\"\n### Davies Bouldin Index: $(round(dbi(features, result), digits=5))\n### Dunn Index : $(round(dunn(features, result), digits=5))\n\"\"\"\n\n# ╔═╡ ce4134a0-4124-11eb-2a7c-9761e81b2064\nmd\"\"\"\n## Plot Clusters\nFeature $(@bind feature1 Select(string.(collect(1:size(features)[1])))) vs.\nFeature $(@bind feature2 Select(string.(collect(1:size(features)[1])));)\n\"\"\"\n\n# ╔═╡ 73454ea0-4116-11eb-0938-f9a06f3dbaf8\nbegin\n\ttheme(:dark)\n\tscatter(\n\t\tfeatures[parse(Int,feature1), :], \n\t\tfeatures[parse(Int, feature2), :],\n\t\tmarker_z = result.assignments, \n\t\tmarkershape = :diamond,\n\t\tmarkersize = 3,\n\t\txlabel=\"Feature $(feature1)\", \n\t\tylabel=\"Feature $(feature2)\",\n\t\tcolor = :seaborn_bright, \n\t\tlegend = false)\n\tscatter!(\n\t\tresult.centers[parse(Int,feature1), :], \n\t\tresult.centers[parse(Int, feature2), :],\n\t\tmarkersize = 6,\n\t\tmarker_z = result.centers',\n\t\tcolor = :temperaturemap\n\t)\nend\n\n# ╔═╡ 6cd3fe00-41c4-11eb-2e84-376a14af7398\nmd\"\"\"\n### Cluster Centers\n$(\ndf = DataFrame(hcat(result.centers', result.counts));\nlast_col_name = names(df)[end];\ndf[!,last_col_name] = convert.(Int,df[:,last_col_name]);\nrename!(df, last_col_name => :NodeCount)\n)\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─c73d5420-4126-11eb-19b3-bf6c04aef086\n# ╟─85d5a830-4116-11eb-1479-630b53b50e94\n# ╠═4862c2d0-4116-11eb-3f26-1bdefcb9ce3d\n# ╟─360ab320-411d-11eb-2d11-c9fe7b3137d1\n# ╠═73936e9e-4116-11eb-0594-1d202bd073cd\n# ╠═aac40900-41cc-11eb-1103-97d9373bdd65\n# ╠═12615c80-41c7-11eb-2aed-c1eb96003ff1\n# ╠═c7001000-42c6-11eb-23d1-314932816f0a\n# ╠═c6ca5a00-42c6-11eb-386e-2f13a99d75b6\n# ╠═c69d2f80-42c6-11eb-10cf-e70c07e40e97\n# ╟─9accd320-4117-11eb-0fc4-15e8e85040a8\n# ╟─8b43a9a0-4118-11eb-127d-d57dcea189e1\n# ╠═73c57b20-4116-11eb-3dba-01c9f7b91fa7\n# ╠═5cddc6a0-411c-11eb-2380-1b9442938a9b\n# ╟─bec93fa0-4119-11eb-026e-0be14d6a5779\n# ╠═737b2bb0-4116-11eb-124b-d981032a9638\n# ╠═725d2e10-42c2-11eb-3ee7-4ba089ebb440\n# ╟─ce4134a0-4124-11eb-2a7c-9761e81b2064\n# ╟─73454ea0-4116-11eb-0938-f9a06f3dbaf8\n# ╟─6cd3fe00-41c4-11eb-2e84-376a14af7398\n", "meta": {"hexsha": "5ff73ef29e0245c1fa4a6ab30a0c25cb75bf6fe4", "size": 7495, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2.k-means/notebook.jl", "max_stars_repo_name": "aadimator/CSE553-Data-Mining", "max_stars_repo_head_hexsha": "8acc3a1dafe297b37c2e3a355ba00e9e2b1981a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2.k-means/notebook.jl", "max_issues_repo_name": "aadimator/CSE553-Data-Mining", "max_issues_repo_head_hexsha": "8acc3a1dafe297b37c2e3a355ba00e9e2b1981a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2.k-means/notebook.jl", "max_forks_repo_name": "aadimator/CSE553-Data-Mining", "max_forks_repo_head_hexsha": "8acc3a1dafe297b37c2e3a355ba00e9e2b1981a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1557971014, "max_line_length": 195, "alphanum_fraction": 0.6745830554, "num_tokens": 2735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7592872426950539}}
{"text": "export lanczosBidiag\n\nfunction lanczosBidiag(A::SparseMatrixCSC{T1,Int},b::Array{T2,1}, k::Int) where {T1,T2}\n\tT  = promote_type(T1,T2)\n\tx1 = zeros(T,size(A,1))\n\tx2 = zeros(T,size(A,2))\n\t\n\tAf(x,flag) = (flag=='F') ? mul!(x1,A,x,1.0,0.0) : mul!(x2,transpose(A),x,1.0,0.0)\n\treturn lanczosBidiag(Af,b,k)\nend\n\n\nlanczosBidiag(A,b,k) = lanczosBidiag((x,flag) -> ((flag=='F') ? A*x : A'*x),b,k)\n\n\"\"\"\nU, B, V =  lanczosBidiag(A,p::Vector,k::Int)\n\nLanczos bidiagonalization of matrix A.\n\nInput:\n\n  A       - function computing A*x = A(x,'F') and A'*x = A(x,'T')\n  p       - starting vector\n  k       - dimension of subspace\n\nOutput:\n\n  U,B,V   - Lanczos vectors\n\"\"\"\nfunction lanczosBidiag(A::Function,p::Vector,k::Int)\n\t\n\tm      = length(p)\n\tbeta   = norm(p)\n\tu      = p/beta\n\tATu    = A(u,'T')\n\t\n\tn      = length(ATu)\n\tv      = zeros(n)\n\t\n\t# alocate space for Lanczos vectors\n\tU = zeros(m,k+1)\n\tV = zeros(n,k)\n\tB = zeros(k,2)\n\t# Prepare for Lanczos iteration.\n\tU[:,1] = u\n\t\n\tfor i=1:k # perform Lanczos bidiagonalization with reorthogonalization.\n\t\tif i>1;\n\t\t\tATu = A(u,'T')\n\t\tend\n\t\tr = ATu - beta*v\n\t\t\n\t\tfor j=1:i-1 # reorthogonalization of V\n\t\t\tr -= dot(V[:,j],r)*V[:,j]\n\t\tend\n\t\t\n\t\talpha = norm(r)\n\t\tv = r/alpha\n\t\tB[i,2] = alpha\n\t\tV[:,i] = v\n\t\t\n\t\tAv = A(v,'F')\n\t\tp = Av - alpha*u\n\t\t\n\t\tfor j=1:i; p = p - dot(U[:,j],p)*U[:,j]; end\n\t\tbeta = norm(p)\n\t\tu    = p/beta\n\t\t\n\t\tB[i,1]   = beta\n\t\tU[:,i+1] = u\n\tend\n\tII,JJ,VV = SparseArrays.spdiagm_internal(-1=>B[:,1], 0=>B[:,2])\n\tB = sparse(II,JJ,VV,k+1,k)\n\t# Bt = spdiagm((B[:,1],B[:,2]),[-1,0],k+1,k)\n\treturn U, B, V\nend\n", "meta": {"hexsha": "d732a31418a1775277987dc041f790a03255e9fe", "size": 1557, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lanczosBidiag.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/KrylovMethods.jl-9a2cd570-f05c-5dc1-9209-93ad6f5727f7", "max_stars_repo_head_hexsha": "10eab6b7804df804257c457648c67e926fa144aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-02-11T21:49:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T07:08:10.000Z", "max_issues_repo_path": "src/lanczosBidiag.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/KrylovMethods.jl-9a2cd570-f05c-5dc1-9209-93ad6f5727f7", "max_issues_repo_head_hexsha": "10eab6b7804df804257c457648c67e926fa144aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-06-14T22:48:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:06:49.000Z", "max_forks_repo_path": "src/lanczosBidiag.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/KrylovMethods.jl-9a2cd570-f05c-5dc1-9209-93ad6f5727f7", "max_forks_repo_head_hexsha": "10eab6b7804df804257c457648c67e926fa144aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-08-01T09:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T12:17:33.000Z", "avg_line_length": 20.2207792208, "max_line_length": 87, "alphanum_fraction": 0.5561978163, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927838, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7592872381304474}}
{"text": "#=\n\n  Crypto problem (alphametic) in Julia ConstraintSolver.jl \n\n  This is a standard alphametic problem in mathematical recreations, \n  constraint programming etc.\n    \n  From GLPK:s model cryto.mod.\n \n  \"\"\"\n  This problem comes from the newsgroup rec.puzzle.\n  The numbers from 1 to 26 are assigned to the letters of the alphabet.\n  The numbers beside each word are the total of the values assigned to\n  the letters in the word (e.g. for LYRE: L, Y, R, E might be to equal\n  5, 9, 20 and 13, or any other combination that add up to 47).\n  Find the value of each letter under the equations:\n \n  BALLET  45     GLEE  66     POLKA      59     SONG     61\n  CELLO   43     JAZZ  58     QUARTET    50     SOPRANO  82\n  CONCERT 74     LYRE  47     SAXOPHONE 134     THEME    72\n  FLUTE   30     OBOE  53     SCALE      51     VIOLIN  100\n  FUGUE   50     OPERA 65     SOLO       37     WALTZ    34\n \n  Solution:\n  A, B,C, D, E,F, G, H, I, J, K,L,M, N, O, P,Q, R, S,T,U, V,W, X, Y, Z\n  5,13,9,16,20,4,24,21,25,17,23,2,8,12,10,19,7,11,15,3,1,26,6,22,14,18\n \n  Reference:\n  Koalog Constraint Solver <http://www.koalog.com/php/jcs.php>,\n  Simple problems, the crypto-arithmetic puzzle ALPHACIPHER.\n  \"\"\"\n\n  Model created by Hakan Kjellerstrand, hakank@gmail.com\n  See also my Julia page: http://www.hakank.org/julia/\n\n=#\n\n\nusing ConstraintSolver, JuMP\nusing Cbc, GLPK, Ipopt\nconst CS = ConstraintSolver\ninclude(\"constraints_utils.jl\")\n\nfunction crypto(print_solutions=true,all_solutions=true)\n\n    cbc_optimizer = optimizer_with_attributes(Cbc.Optimizer, \"logLevel\" => 0)\n    glpk_optimizer = optimizer_with_attributes(GLPK.Optimizer)\n    ipopt_optimizer = optimizer_with_attributes(Ipopt.Optimizer)\n\n    model = Model(optimizer_with_attributes(CS.Optimizer,   \"all_solutions\"=> all_solutions,\n                                                            # \"all_optimal_solutions\"=>all_solutions, \n                                                            \"logging\"=>[],\n\n                                                            \"traverse_strategy\"=>:BFS,\n                                                            # \"traverse_strategy\"=>:DFS,\n                                                            # \"traverse_strategy\"=>:DBFS,\n\n                                                            # \"branch_split\"=>:Smallest,\n                                                            # \"branch_split\"=>:Biggest,\n                                                            \"branch_split\"=>:InHalf,\n\n                                                            # https://wikunia.github.io/ConstraintSolver.jl/stable/options/#branch_strategy-(:Auto)\n                                                            \"branch_strategy\" => :IMPS, # default\n                                                            # \"branch_strategy\" => :ABS, # Activity Based Search\n                                                            # \"activity.decay\" => 0.999, # default 0.999\n                                                            # \"activity.max_probes\" => 10, # default, 10\n                                                            # \"activity.max_confidence_deviation\" => 20, # default 20\n\n                                                            # \"simplify\"=>false,\n                                                            # \"simplify\"=>true, # default\n\n                                                            \"time_limit\"=>6,\n\n                                                            # \"backtrack\" => false, # default true\n                                                            # \"backtrack_sorting\" => false, # default true\n\n                                                            # \"lp_optimizer\" => cbc_optimizer,\n                                                            # \"lp_optimizer\" => glpk_optimizer,\n                                                            # \"lp_optimizer\" => ipopt_optimizer,\n                                        ))\n\n    BALLET     =  45\n    CELLO      =  43\n    CONCERT    =  74\n    FLUTE      =  30\n    FUGUE      =  50\n    GLEE       =  66\n    JAZZ       =  58\n    LYRE       =  47\n    OBOE       =  53\n    OPERA      =  65\n    POLKA      =  59\n    QUARTET    =  50\n    SAXOPHONE  = 134\n    SCALE      =  51\n    SOLO       =  37\n    SONG       =  61\n    SOPRANO    =  82\n    THEME      =  72\n    VIOLIN     = 100\n    WALTZ      =  34\n\n    n = 26\n    @variable(model, 1 <= x[1:n] <= n, Int)\n    A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z = x \n\n    @constraint(model, x in CS.AllDifferent())\n\n    @constraint(model,B + A + L + L + E + T == BALLET)\n    @constraint(model,C + E + L + L + O == CELLO)\n    @constraint(model,C + O + N + C + E + R + T == CONCERT)\n    @constraint(model,F + L + U + T + E == FLUTE)\n    @constraint(model,F + U + G + U + E == FUGUE)\n    @constraint(model,G + L + E + E == GLEE)\n    @constraint(model,J + A + Z + Z == JAZZ)\n    @constraint(model,L + Y + R + E == LYRE)\n    @constraint(model,O + B + O + E == OBOE)\n    @constraint(model,O + P + E + R + A == OPERA)\n    @constraint(model,P + O + L + K + A == POLKA)\n    @constraint(model,Q + U + A + R + T + E + T == QUARTET)\n    @constraint(model,S + A + X + O + P + H + O + N + E == SAXOPHONE)\n    @constraint(model,S + C + A + L + E == SCALE)\n    @constraint(model,S + O + L + O == SOLO)\n    @constraint(model,S + O + N + G == SONG)\n    @constraint(model,S + O + P + R + A + N + O == SOPRANO)\n    @constraint(model,T + H + E + M + E == THEME)\n    @constraint(model,V + I + O + L + I + N == VIOLIN)\n    @constraint(model,W + A + L + T + Z == WALTZ)\n\n    # Solve the problem\n    optimize!(model)\n\n    status = JuMP.termination_status(model)\n    # println(\"status:$status\")\n    if status == MOI.OPTIMAL\n        num_sols = MOI.get(model, MOI.ResultCount())\n        println(\"num_sols:$num_sols\\n\")\n        if print_solutions\n            for sol in 1:num_sols\n                println(\"solution #$sol\")\n                x_val = convert.(Integer,JuMP.value.(x; result=sol))\n                println(\"x:$x_val\")\n\n            end\n        end\n    else\n        println(\"status:$status\")\n    end\n\n    return status\nend\n\n@time crypto()\n", "meta": {"hexsha": "1c6ca8aaf25f1a33b5750a0aaac8600c7f3b0801", "size": 6160, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/constraints/crypto.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/constraints/crypto.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/constraints/crypto.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 40.0, "max_line_length": 147, "alphanum_fraction": 0.4636363636, "num_tokens": 1606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.8418256472515684, "lm_q1q2_score": 0.7592599572890524}}
{"text": "\n\"\"\"\n    AdaptiveExtrapolationD\n\nThis module is  implementing an\nadaptive extrapolation of the explicit midpoint rule according to Deuflhard.\n\"\"\"\nmodule AdaptiveExtrapolationD\n\n\n\n\"\"\"\n    (Δ,Δx,statisitic) = (mySolver::solver)(f::Function, x₀::Vector{T}, t₀::S, tEnd::S; <options>)\n        where {T<:Number,S<:AbstractFloat}\n\nComputes the grid function `xΔ` on the grid `Δ` approximating the solution of the initial value problem\n\n        x′ = f(t,x),  x(t₀) = x₀\n\non the interval `[t₀,tEnd]` (or `[tEnd,t₀]` if `tEnd < t₀`). The integrator is the extrapolated explicit midpoint rule.\nThe algorithm adaptively controls stepsize and extrapolation order in the line of thought of Deuflhard.\nNote that `solver` is a callable instance of the `struct solver`.\n\n***\n## Initialize `solver`\n\n\n    solver(N::Integer, sequence::String)\n\nInitializes and returns the an instance of `solver`.\n`N ≧ 1` is the maximal order of extrapolation. `sequence` specifies the subdividing sequence\nused. The options are\n* `Harmonic`, that is `1, 2, 3, 4, 5, 6,...`\n* `Romberg`, that is `1, 2, 4, 8, 16, 32,...`\n* `Bulirsch`, that is `1, 2, 3, 4, 6, 8,... `\nThe structure contains all quantities for the adaptive extrapolation of the the explicit\nmidpoint rule for all orders in `1:N` that can be tabulated before the actual computation .\nThese are the *subdividing sequence* and the *weights* for the extrapolation based on the first barycentric formula.\n\n***\n## Options\n\nThe following options can be passed as keyword arguments.\n* `tol::S > 0` is tolerance used for accuracy check. Default is `1e-3`.\n* `relativeScaling::Vector{S}` and `absoluteScaling::Vector{S}` are vectors of the same length as `x₀`\n    containing no negative elements.\n    Default (in every component) is `relativeScaling[i] = 1.0` and `absoluteScaling[i] = 1e-3`.\n    The accuracy check is passed iff the estimated error satisfies in every component:\n\n        |relativeError[i]| ≦ relativeScaling[i]⋅tol & |absoluteError[i]| ≦ absoluteScaling[i]⋅tol\n\n* `firstGuessStepsize::S` is the length of the first step. Its modulus must be greater than\n    `eps(S)` Default is `1e-3`.\n* `maximalSteplength::S > 0` is the maximal absolute stepsize used for the integration. Default is `Inf`.\n* `minimalStepsizeScaling::S` and `maximalStepsizeScaling::S` are safety factors for the stepsize\n    selection. Default are `0.25` and `4.0`. The new stepsize satisfies:\n\n         0 ≦ minimalStepsizeScaling ≦ newStepsize / oldStepsize ≦ maximalStepsizeScaling\n\n* `safetyStepsizeSelection::S>0`. Use `safetyStepsizeSelection⋅tol` instead of `tol`. Default is `0.25`.\n* `minimumOrder::Int64 ≧ 1` and `maximumOrder::Int64 ≦ N` are the minimal and maximal order of extrapolation for the integration (`N` is the number that has been passed to the constructor). Default are `1` and `N`.\n* `firstGuessOrder::Int64` is the extrapolation order for the first step. It must satisfy\n    `minimumOrder ≦ firstGuessOrder ≦ maximumOrder`. Default is `round(Int64,(maximumOrder-minimumOrder)/2)`.\n* `maximumReduction::Int64` is the upper bound of the number of successive reductions allowed per step.\n    Exceeding this boundary leads to ending the integration prematurely (`Δ[end] ≠ tEnd`). Default is `10`.\n* `maximumSteps::Int64 ≧ 0` is the maximal length of the array `Δ`. Exceeding this boundary leads to\n    ending the integration prematurely (`Δ[end] ≠ tEnd`). Default is `10 000`.\n* `rescaleWeights::Bool` If `true` Lagrange interpolation is used otherwise the frist barycentric fromula. Default is `false`\n* `detailedStatistics::Bool` flag for the content of `statisitic`. Default is `false`\n    + `true`: `statisitic[:,i]` contains [extrapolation order; stepsize; number of `f`-evaluations;\n        number of reductions] for the ith step.\n    + `false`: `statisitic` contains [total number of evaluations of the right side `f`, total number of reductions].\n\"\"\"\nstruct solver\n    \"\"\"\n    The structure contains all quantities for the adaptive extrapolation of the the explicit\n    midpoint rule that can be tabulated before the acutal computation.\n    These are for all orders in `1:N` (`N` is provided the constructor):\n    The subdividing sequence, the weights and scaling used for\n    the extrapolation based on the first barycentric formula.\n    \"\"\"\n   subdividingSequence::Array{BigInt,1}\n\n   # weights and scaling factors for extrapolation operators\n   ω::Array{Rational{BigInt},2}\n   ρ::Array{Rational{BigInt},1}\n\n   # weights and scaling factors for internal extrapolation operators (used for error estimate)\n   ω2::Array{Rational{BigInt},2}\n   ρ2::Array{Rational{BigInt},1}\n\n   # constructor\n   function solver(N::Integer, sequence::String)\n       # check input and initialize subdividing sequence subdividingSequence for barycentric weights\n       if N < 0\n           error(\"Order of extrapolation must not be negative. But I got N = $N\")\n       end\n       if sequence == \"Harmonic\"\n           subdividingSequence = [BigInt(n+1) for n = 0:N]\n       elseif sequence == \"Romberg\"\n           subdividingSequence = [BigInt(2)^n for n = 0:N]\n       elseif sequence == \"Bulirsch\"\n           subdividingSequence = [n==0 ? BigInt(1) : (isodd(n) ? BigInt(2)^Int64(n/2+0.5) : 3*BigInt(2^Int64(n/2-1))) for n = 0:N]\n       else\n           error(\"Name of subdividing sequence must be ''Harmonic'', ''Romberg'' or ''Bulirsch''. But I got ''$sequence''\")\n       end\n\n       # compute nodes corresponding to the subdividing sequence subdividingSequence\n       nodes = BigInt(1).// subdividingSequence.^2\n\n       # compute barycentric weights for internal extrapolation operators\n       ω2 = zeros(Rational{BigInt},N,N)\n       ω2[1,:] = ones(Rational{BigInt},1,N)\n       for n = 2:N\n           distance = nodes[2:n] .- nodes[n+1]\n           ω2[1:(n-1),n] = ω2[1:n-1,n-1] .// distance\n           ω2[n,n] = 1 // prod(-distance)\n       end\n\n       # compute barycentric weights for extrapolation operators\n       ω = zeros(Rational{BigInt},N+1,N+1)\n       for n = 1:N\n           ω[n+1,(n+1):(N+1)] = ω2[n,n:N] // (nodes[n+1]-nodes[1])\n           ω[1,n] = 1 // prod(nodes[1].-nodes[2:n])\n       end\n       ω[1,N+1] = 1 // prod(nodes[1].-nodes[2:N+1])\n\n       #rescale barycentric weights to obtain weights of 1. barycentric formula\n       for m = 1:(N+1)\n           ω[1:m,m] = - ω[1:m,m] .// nodes[1:m]\n           if 2 <= m\n               ω2[1:m-1,m-1] = - ω2[1:m-1,m-1] .// nodes[2:m]\n           end\n       end\n\n       # compute scaling factors for internal extrapolation operators\n       ρ2 = ones(Rational{BigInt},N)\n       ρ2[1] = -nodes[2]\n       for n = 1:(N-1)\n           ρ2[n+1] = -ρ2[n]*nodes[n+2]\n       end\n\n       # compute scaling factors for extrapolation operators\n       ρ = -nodes[1]*[BigInt(1); ρ2]\n\n       # initialize structure\n       new(subdividingSequence,ω,ρ,ω2,ρ2)\n   end\nend\n\nfunction (mySolver::solver)(\n            f::Function, x₀::Vector{T}, t₀::S, tEnd::S;\n            tol::S = parse(S,\"1e-3\"),\n            relativeScaling::Vector{S} =ones(S,size(x₀)),\n            absoluteScaling::Vector{S} = fill(parse(S,\"1e-3\"),size(x₀)),\n            firstGuessStepsize::S = parse(S,\"1e-3\"),\n            maximalSteplength::S = parse(S,\"Inf\"),\n            minimalStepsizeScaling::S = parse(S,\"0.02\"),\n            maximalStepsizeScaling::S = parse(S,\"4\"),\n            safetyStepsizeSelection::S =  parse(S,\"0.25\"),\n            minimumOrder::Int64 = 1,\n            maximumOrder::Int64 = length(mySolver.subdividingSequence)-1,\n            firstGuessOrder = round(Int64,(maximumOrder-minimumOrder)/2),\n            maximumReduction::Int64 = 10,\n            maximumSteps::Int64 = 10000,\n            rescaleWeights::Bool = false,\n            detailedStatistics::Bool = false,\n            kwargs...\n            )where {T<:Number,S<:AbstractFloat}\n    # initialize\n    # 1. constants\n    d = length(x₀) # systems dimension\n    if 1<= minimumOrder <= maximumOrder <= length(mySolver.ρ)-1\n        n_ex, N_ex = minimumOrder, maximumOrder\n    else\n        error(\"Minimal and maximal order must satisfy: 1 ≦ minimumOrder ≦ maximumOrder ≦ $(length(mySolver.ρ)-1)!\")\n    end\n\n    if length(relativeScaling) == length(absoluteScaling) == d\n        if all(el->el>=zero(S),relativeScaling ) && all(el->el>=zero(S),absoluteScaling)\n            σᵣ, σₐ = relativeScaling,  absoluteScaling # scaling factors for the  error estimate\n        else\n            error(\"All elements of relativeScaling and absoluteScaling must be non-negative!\")\n        end\n    else\n        error(\"relativeScaling and absoluteScaling must be vectors of length $(d)!\")\n    end\n\n    if zero(S) <= minimalStepsizeScaling <= maximalStepsizeScaling\n        p1, p2 = minimalStepsizeScaling, maximalStepsizeScaling\n    else\n        error(\"Minimal and maximal stepsize scaling must satisfy: 0.0 <= minimalStepsizeScaling <= maximalStepsizeScaling!\")\n    end\n\n\n    # 2. arrays\n    if maximumSteps >= 0\n        Δ = zeros(S, maximumSteps + 1) # time grid\n        xΔ = zeros(T, d, maximumSteps + 1) # solution\n    else\n        error(\"maximumSteps must not be negative!\")\n    end\n    X = zeros(T, d, N_ex + 1) # storage for the internal discretisations obtained by the explicit midpoint rule\n    λ = zeros(S, N_ex - n_ex +1) # storage for scaling factors of stepsize. λ[k] contains the scalar for extr. order (k + n_ex - 1)\n    τ_opt =zeros(S, N_ex - n_ex +1) # storage for optimal stepsize. τ_opt[k] contains the stepsize for extr. order (k + n_ex - 1)\n    s = [2*sum(Int64.(mySolver.subdividingSequence[1:n+1])) - n for n in n_ex:N_ex] # s[k] is the number of stages for  extrapolation order (k + n_ex - 1)\n    statistics = detailedStatistics ? zeros(S,4,maximumSteps) : zeros(Int64,2)\n\n\n    # 3. initialization for integration loop\n    Δ[1], xΔ[:,1] = t₀, x₀ # store inital values\n    tRest = tEnd - Δ[1] # remaining size of the interval\n    if maximalSteplength > zero(S)\n        maximalSteplength = min(abs(tRest),maximalSteplength)\n    else\n        error(\"maximalSteplength must be positive!\")\n    end\n\n    if abs(firstGuessStepsize) > eps(S)\n        τ = flipsign(min(abs(firstGuessStepsize),maximalSteplength),tRest) # stepsize for first step, accomodate backward integration\n    else\n        error(\"Absolute value of firstGuessStepsize must be greater than eps($S) = $(eps(S))!\")\n    end\n    if n_ex <= firstGuessOrder <= N_ex\n        m = firstGuessOrder # extrapolation order for first step\n    else\n        error(\"firstGuessOrder must be between $n_ex and $(N_ex)!\")\n    end\n\n    counterStep = 1\n    counterReduction = 0\n    counterEvaluation = 0\n    converged = false\n\n    finished = maximumSteps == 0\n\n    x_n = ones(T,d) # storage for the latest solution\n    ϵ_n = zero(S) # storage for the latest error estimate\n    if safetyStepsizeSelection > 0\n        tol = safetyStepsizeSelection*tol # the tolerance for accuracy checks\n    else\n        error(\"safetyStepsizeSelection must be positive!\")\n    end\n\n    # integration loop\n    while !finished\n        # the nth step: the approximation for the time t₀ + τ is saved in xΔ[n+1].\n\n        # check if the computation must be aborted\n        if counterStep > maximumSteps\n            println(\"Not finished. Exceeded maximal number of steps ($maximumSteps)\")\n            return (Δ[1:counterStep], xΔ[:,1:counterStep], detailedStatistics ? statistics[:,1:counterStep-1] : statistics)\n        end\n        if counterReduction > maximumReduction\n            println(\"Not finished. Too many reductions in step number $(counterStep)!\")\n            return (Δ[1:counterStep], xΔ[:,1:counterStep], detailedStatistics ? statistics[:,1:counterStep-1] : statistics)\n        end\n        if abs(τ) <= eps(S)\n            println(\"Stepsize is becoming too small in step $(counterStep)!\")\n            return (Δ[1:counterStep], xΔ[:,1:counterStep], detailedStatistics ? statistics[:,1:counterStep-1] : statistics)\n        end\n\n        # preperations for current step:\n        n_win, N_win = max(n_ex, m - 1), min(N_ex, m + 1) # order window\n        n = n_win # start with smalles order in the order window\n\n\n        # compute all necessary internal approximations:\n        f₀ = f(t₀,x₀) # the information for the Euler step\n        counterEvaluation = counterEvaluation + 1\n\n        for i = 0:n\n            X[:,i+1] = explicitMidpointRule(t₀,x₀,f₀,f,τ,2*Int64(mySolver.subdividingSequence[i+1]))\n            counterEvaluation = counterEvaluation + 2*Int64(mySolver.subdividingSequence[i+1]) - 1\n        end\n\n        #  compute all information relating to an extrapolation order ≦ n_win:\n        for i = n_ex : n\n            if rescaleWeights\n                # rescaling weights is equivalent to Lagrange interpolation\n                x_i= X[:, 1:(i+1)]*T.(broadcast(*,mySolver.ω,mySolver.ρ')[1:(i+1),(i+1)]) # discretisation of order i\n                xx_i = X[:, 2:(i+1)]*T.(broadcast(*,mySolver.ω2,mySolver.ρ2')[1:i, i]) # its internal counterpart\n            else\n                x_i = T.(mySolver.ρ[i+1])*(X[:, 1:(i+1)]*T.(mySolver.ω[1:(i+1), (i+1)]))\n                xx_i = T.(mySolver.ρ2[i])*(X[:, 2:(i+1)]*T.(mySolver.ω2[1:i, i]))\n            end\n            σ = max.(σₐ, σᵣ.*abs.(x_i)) # scaling for error estimate\n            ϵ_i = sqrt(sum((abs.(x_i-xx_i)./σ).^2)/d) # scaled mean square norm of the estimated error\n            λ[i-n_ex+1] = min(p2, max(p1, (tol/ϵ_i)^(1/(2i+1)))) # factor for optimal stepsize, including safety scaling\n            if i == n\n                x_n, ϵ_n = x_i, ϵ_i # save solution and error for the current order n\n            end\n        end\n\n        # check if soltution with for n in the order window can be accepted\n        while n <= N_win\n            if ϵ_n <= tol\n                # accept order n\n                converged = true\n                break\n            elseif ϵ_n <= tol^(s[n-n_ex+1]/s[N_win-n_ex+1])\n                # reject order n but pass convergence monitor\n                n = n + 1\n                # compute x_n, λ_n and ϵ_n for new n:\n                X[:,n+1] = explicitMidpointRule(t₀,x₀,f₀,f,τ,2*Int64.(mySolver.subdividingSequence[n+1]))\n                counterEvaluation = counterEvaluation + 2Int64(mySolver.subdividingSequence[n+1]) - 1\n                if rescaleWeights\n                    # rescaling weights is equivalent to Lagrange interpolation\n                    x_n= X[:, 1:(n+1)]*T.(broadcast(*,mySolver.ω,mySolver.ρ')[1:(n+1),(n+1)])\n                    xx_n = X[:, 2:(n+1)]*T.(broadcast(*,mySolver.ω2,mySolver.ρ2')[1:n, n])\n                else\n                    x_n = T.(mySolver.ρ[n+1])*(X[:, 1:(n+1)]*T.(mySolver.ω[1:(n+1), (n+1)])) # approximation of extrapolation order n\n                    xx_n = T.(mySolver.ρ2[n])*(X[:, 2:(n+1)]*T.(mySolver.ω2[1:n, n])) # and its internal counterpart\n                end\n                σ = max.(σₐ, σᵣ.*abs.(x_n)) # scaling for error estimate\n                ϵ_n = sqrt(sum((abs.(x_n-xx_n)./σ).^2)/d) # scaled mean square norm of the estimated error\n                λ[n-n_ex+1] = min(p2,max(p1,(tol/ϵ_n)^(1/(2n+1)))) # factor for optimal stepsize, including safety scaling\n\n            else\n                # reject order n and not pass convergence monitor\n                break\n            end\n        end\n\n        if converged\n            #  step is accepted, save x_n for the time t₀ + τ and update statistics\n            Δ[counterStep+1] = t₀ + τ\n            xΔ[:, counterStep+1] = x_n\n            tRest = tEnd - Δ[counterStep+1]\n            maximalSteplength = min(abs(tRest),maximalSteplength)\n            if detailedStatistics\n                statistics[:,counterStep] = [n, τ, counterEvaluation, counterReduction]\n            else\n                statistics = statistics + [counterEvaluation,counterReduction]\n            end\n\n            #  check if tEnd is already reached\n            if abs(tRest) < eps(S)\n                finished = true\n            else\n                # preperations for the next step:\n                t₀, x₀  = Δ[counterStep+1], xΔ[:, counterStep+1] # new inital data\n\n                ## compute optimal order m and stepsize τ for the next step acc. Deuflhard\n                # first compute the optimal extrapolation order\n                temp = (n_ex:n) .- n_ex .+ 1 # index range of computed quantities\n                τ_opt[temp] = min.(abs(τ)*λ[temp], maximalSteplength) # safety boundary for τ_opt\n                ω = s[temp]./(τ_opt[temp]) # work per step\n\n                m = argmin(ω) + n_ex - 1 # optimal order\n\n                # check if we may increase m\n                if m == n < N_win\n                    # compute scaling for order m+1, including safety scaling\n                    λ[n-n_ex+2] = min(p2, max(p1, (tol^(s[n-n_ex+1]/s[n-n_ex+2])/ϵ_n)^(1/(2n+1))))\n                    # check if work dereases from order m to  m+1\n                    if ω[end] > s[n-n_ex+2]/(τ_opt[n-n_ex+2] = min(abs(τ)*λ[n-n_ex+2], maximalSteplength))\n                        m = m + 1\n                    end\n                end\n                τ = flipsign(τ_opt[m-n_ex+1],τ) # accomodate backward integration\n\n                counterStep = counterStep + 1\n                converged = false\n                counterEvaluation = 0\n                counterReduction = 0\n                fill!(λ,zero(S))\n                fill!(τ_opt,zero(S))\n            end\n        else\n            counterReduction = counterReduction + 1\n            # compute reduced stepsize τ for order m. Use latest error estimate ϵ_n if estimate of order m is not available\n            if n < m\n                 λ[m-n_ex+1] = min(p2,max(p1,(tol^(s[n-n_ex+1]/s[m-n_ex+1])/ϵ_n)^(1/(2n+1))))\n            end\n            τ_opt[m-n_ex+1] = min(abs(τ)*λ[m-n_ex+1],maximalSteplength) # safety boundary for τ_opt\n            τ = flipsign(τ_opt[m-n_ex+1],τ) # accomodate backward integration\n        end\n    end # integration loop\n    return (Δ[1:counterStep+1], xΔ[:,1:counterStep+1], detailedStatistics ? statistics[:,1:counterStep] : statistics)\nend\n\n\"\"\"\n    explicitMidpointRule(t₀,x₀,f₀,f,τ,N)\n\nComputes the value ``x_\\\\Delta(t_0 + \\\\tau)`` recursively. Here ``x_\\\\Delta`` is the grid-function generated\nby the explicit midpoint rule on the equidistant grid `[t₀ + n/N*τ for n = 0:N]`\nwith the initial data `(t₀,x₀)` and the right side `f`.\nIn the starting step `f₀` is used instead of `f(t₀,x₀)`.\n\"\"\"\nfunction explicitMidpointRule(t₀::S,x₀::Vector{T},f₀::Vector{T},f::Function,τ::S,N) where{S<:AbstractFloat, T<:Number}\n    τ_n = τ/N\n    x = x₀ + τ_n*f₀\n    for i = 0:N-2\n        temp = x\n        x = x₀+2*τ_n*f(t₀+(i+1)*τ_n,x)\n        x₀ = temp\n    end\n    return x\nend\n\nexport solver\nend # module AdaptiveExtrapolationD\n", "meta": {"hexsha": "3bc7f8ec5d023f17edf9ed266fca0db369075f8f", "size": 18562, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solver/adaptive-extrapolation-Deuflhard.jl", "max_stars_repo_name": "AlthausKonstantin/Extrapolation", "max_stars_repo_head_hexsha": "ad4b97fb0c5c568574abcd9b378f5ae5d6958105", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Solver/adaptive-extrapolation-Deuflhard.jl", "max_issues_repo_name": "AlthausKonstantin/Extrapolation", "max_issues_repo_head_hexsha": "ad4b97fb0c5c568574abcd9b378f5ae5d6958105", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solver/adaptive-extrapolation-Deuflhard.jl", "max_forks_repo_name": "AlthausKonstantin/Extrapolation", "max_forks_repo_head_hexsha": "ad4b97fb0c5c568574abcd9b378f5ae5d6958105", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.9455445545, "max_line_length": 214, "alphanum_fraction": 0.6167438854, "num_tokens": 5291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.8418256492357359, "lm_q1q2_score": 0.7592599546399931}}
{"text": "function lgwt(N0::Integer,a::Real=-1,b::Real=1)\n    # This script is for computing definite integrals using Legendre-Gauss\n    # Quadrature. Computes the Legendre-Gauss nodes and weights on an interval\n    # [a,b] with truncation order N\n    #\n    # Suppose you have a continuous function f(x) which is defined on [a,b]\n    # which you can evaluate at any x in [a,b]. Simply evaluate it at all of\n    # the values contained in the x vector to obtain a vector f. Then compute\n    # the definite integral using sum(f.*w);\n    #\n    # Written by Greg von Winckel - 02/25/2004\n    # First adapted to Julia by Tyler Ransom on 08-04-2015\n    # Updated on 08-17-2020\n\n    N  = N0-1\n    N1 = N+1\n    N2 = N+2\n\n    xu = range(-1,stop=1,length=N1)\n\n    # Initial guess\n    y = cos.((2*(0:N) .+ 1)*pi/(2*N .+ 2))  .+  ( 0.27/N1 ) .* sin.( pi .* xu .* N/N2 )\n\n    # Legendre-Gauss Vandermonde Matrix\n    L  = zeros(N1,N2)\n\n    # Derivative of LGVM\n    Lp = zeros(N1,N2)\n\n    # Compute the zeros of the N+1 Legendre Polynomial\n    # using the recursion relation and the Newton-Raphson method\n\n    y0 = 2\n\n\n    vareps = 2e-52\n    # Iterate until new points are uniformly within epsilon of old points\n\n\n    i = 0\n    tracker=0\n    it_max=10\n    while (norm(y.-y0,Inf)>vareps && tracker<=it_max)\n        d=norm(y.-y0,Inf)\n\n        L[:,1]  .= 1\n        Lp[:,1] .= 0\n\n        L[:,2] .= y\n\n        for k=2:N1\n            L[:,k+1] = ( (2*k-1)*y .* L[:,k] .- (k-1)*L[:,k-1] )/k\n        end\n\n        Lp = (N2)*( L[:,N1] .- y .* L[:,N2] )./(1 .- y.^2)\n        y0 = y\n        y  = y0 - L[:,N2]./Lp\n        if norm(y.-y0,Inf)==d\n            tracker+=1\n        end\n        i+=1\n\n    end\n\n    # Linear map from[-1,1] to [a,b]\n    x = (a.*(1 .- y) .+ b .* (1 .+ y))./2\n\n    # Compute the weights\n    w=(b-a)./((1 .- y.^2).*Lp.^2)*(N2/N1)^2\n\n    return x,w\nend\n\n#--------------------------------------------------\n\n# Dr. Ransom Function for mlogit from PS3 solution\nfunction mlogit_with_Z(theta, X, Z, y)\n\n        alpha = theta[1:end-1]\n        gamma = theta[end]\n        K = size(X,2)\n        J = length(unique(y))\n        N = length(y)\n        bigY = zeros(N,J)\n        for j=1:J\n            bigY[:,j] = y.==j\n        end\n        bigAlpha = [reshape(alpha,K,J-1) zeros(K)]\n\n        T = promote_type(eltype(X),eltype(theta))\n        num   = zeros(T,N,J)\n        dem   = zeros(T,N)\n        for j=1:J\n            num[:,j] = exp.(X*bigAlpha[:,j] .+ (Z[:,j] .- Z[:,J])*gamma)\n            dem .+= num[:,j]\n        end\n\n        P = num./repeat(dem,1,J)\n\n        loglike = -sum( bigY.*log.(P) )\n\n        return loglike\n    end\n", "meta": {"hexsha": "45401624b80c7e8b0b36dd0c0efb833aa1d7f592", "size": 2592, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS4-mixture/functions.jl", "max_stars_repo_name": "aelfat/fall-2021", "max_stars_repo_head_hexsha": "0c0c0c08102b2f7e30c38e1ac510b313241f3f82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSets/PS4-mixture/functions.jl", "max_issues_repo_name": "aelfat/fall-2021", "max_issues_repo_head_hexsha": "0c0c0c08102b2f7e30c38e1ac510b313241f3f82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS4-mixture/functions.jl", "max_forks_repo_name": "aelfat/fall-2021", "max_forks_repo_head_hexsha": "0c0c0c08102b2f7e30c38e1ac510b313241f3f82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9230769231, "max_line_length": 87, "alphanum_fraction": 0.5023148148, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7592599537804949}}
{"text": "### A Pluto.jl notebook ###\n# v0.11.14\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 4133e4a2-ed4d-11ea-11cd-0da48c09c2e8\nusing Pkg, DrWatson\n\n# ╔═╡ 54bd3938-ed4d-11ea-29e4-c1c7020c1400\nbegin\n\t@quickactivate \"SR2TuringPluto\"\n\tusing StatisticalRethinking\nend\n\n# ╔═╡ 0c5fe59e-ed4f-11ea-35a8-45c3aff83362\nmd\"## Broadcasting.jl\"\n\n# ╔═╡ 54ccfc74-ed4d-11ea-366d-b738d54ff79a\np_grid = range(0, 1, length = 5)\n\n# ╔═╡ 54d9bce8-ed4d-11ea-279e-3bc3bf465e28\nprior = ones(5)\n\n# ╔═╡ 54da91d4-ed4d-11ea-04f5-e9a4f8c659a3\nlikelihood = pdf.(Binomial.(9, p_grid), 6)\n\n# ╔═╡ 54e45ff4-ed4d-11ea-0288-e3475c709007\nposterior = likelihood .* prior\n\n# ╔═╡ 54e8f906-ed4d-11ea-2fee-316c2df1d8f6\nposterior ./= sum(posterior)\n\n# ╔═╡ 54f1592c-ed4d-11ea-0210-0be7741d2604\nmd\"##### Broadcasting is another important difference between Julia and R.\n\nYou don't have automatic\nbroadcasting (making functions work the same whether you run it on a single\nnumber or on an array of numbers). However, fixing this is very easy,\nyou only have to annotate your function call with a dot:\n  `f(single_number)` -> `f.(array_of_numbers)`.\n\nThat means the translation of the line `likelihood = pdf.(Binomial.(9, p_grid), 6)` goes something like:\n1. First or every value in `p_grid` make a binomial distribution with that p value.\n2. For every distribution then take the pdf of 6.\n\nThe same in the next line, this is elementwise multiplication.\n\nFor more infos read [this](https://julialang.org/blog/2017/01/moredots).\"\n\n# ╔═╡ e822d97e-ed4f-11ea-2c18-17ecfc81fdbd\nmd\"## End of broadcasting.jl\"\n\n# ╔═╡ Cell order:\n# ╟─0c5fe59e-ed4f-11ea-35a8-45c3aff83362\n# ╠═4133e4a2-ed4d-11ea-11cd-0da48c09c2e8\n# ╠═54bd3938-ed4d-11ea-29e4-c1c7020c1400\n# ╠═54ccfc74-ed4d-11ea-366d-b738d54ff79a\n# ╠═54d9bce8-ed4d-11ea-279e-3bc3bf465e28\n# ╠═54da91d4-ed4d-11ea-04f5-e9a4f8c659a3\n# ╠═54e45ff4-ed4d-11ea-0288-e3475c709007\n# ╠═54e8f906-ed4d-11ea-2fee-316c2df1d8f6\n# ╟─54f1592c-ed4d-11ea-0210-0be7741d2604\n# ╟─e822d97e-ed4f-11ea-2c18-17ecfc81fdbd\n", "meta": {"hexsha": "2f80a9827b94d7ddc230f4cdaaeabf296e281bd4", "size": 1976, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/Intros/intro-R-users/2_broadcasting.jl", "max_stars_repo_name": "SimonAB/StatisticalRethinkingTuring.jl", "max_stars_repo_head_hexsha": "fe8bc9430ef7bed17f532d9b70a5f6a85910266f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/Intros/intro-R-users/2_broadcasting.jl", "max_issues_repo_name": "SimonAB/StatisticalRethinkingTuring.jl", "max_issues_repo_head_hexsha": "fe8bc9430ef7bed17f532d9b70a5f6a85910266f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Intros/intro-R-users/2_broadcasting.jl", "max_forks_repo_name": "SimonAB/StatisticalRethinkingTuring.jl", "max_forks_repo_head_hexsha": "fe8bc9430ef7bed17f532d9b70a5f6a85910266f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4, "max_line_length": 104, "alphanum_fraction": 0.7484817814, "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7592599519203673}}
{"text": "\"\"\"\n    advection_pde!(duhat,uhat,p,t)\n\nRHS for the advection equation ``u_t = - u_x`` for numerical integration in Fourier space.\n\n\"\"\"\nfunction advection_pde!(duhat,uhat,p,t)\n    N, k, dL, nu, alpha = p;\n    uhat[Int(N/2)+1] = 0; # Set the most negative mode to zero to prevent an asymmetry\n    duhat .= -alpha*im*k.*uhat;\nend\n\n\"\"\"\n    advection_diffusion_pde!(duhat,uhat,p,t)\n\nRHS for the advection-diffusion equation \\$u_t = - u_x + ν u_{xx}\\$ for numerical integration in Fourier space where ν is the viscosity.\n\n\"\"\"\nfunction advection_diffusion_pde!(duhat,uhat,p,t)\n    N, k, dL, nu, alpha = p;\n    uhat[Int(N/2)+1] = 0; # Set the most negative mode to zero to prevent an asymmetry\n    duhat .= -alpha*im*k.*uhat + nu*(im*k).^2 .*uhat;\nend\n\n\"\"\"\n    viscous_burgers_pde!(duhat,uhat,p,t)\n\nRHS for the viscous Burgers equation \\$u_t = - u u_x + ν u_{xx}\\$ for numerical integration in Fourier space where ν is the viscosity.\n\n\"\"\"\nfunction viscous_burgers_pde!(duhat,uhat,p,t)\n    N, k, dL, nu = p;\n    alpha = 1.0;\n    uhat[Int(N/2)+1] = 0.0; # Set the most negative mode to zero to prevent an asymmetry\n    uhat_nonlinear = quadratic_nonlinear(uhat,N,dL,alpha);\n    duhat .= -nu*k.^2 .*uhat .- uhat_nonlinear;\nend\n\n\"\"\"\n    inviscid_burgers_pde!(duhat,uhat,p,t)\n\nRHS for the inviscid Burgers equation \\$u_t = - u u_x\\$ for numerical integration in Fourier space.\n\n\"\"\"\nfunction inviscid_burgers_pde!(duhat,uhat,p,t)\n    N, k, dL, nu = p;\n    alpha = 1.0;\n    uhat[Int(N/2)+1] = 0; # Set the most negative mode to zero to prevent an asymmetry\n    uhat_nonlinear = quadratic_nonlinear(uhat,N,dL,alpha);\n    duhat .= -uhat_nonlinear;\nend\n\n\"\"\"\n    quadratic_nonlinear!(uhat,N,dL,alpha)\n\nCompute the convolution sum \\$\\\\frac{ik}{2}\\\\sum_{p+q=k} u_p u_q\\$ resulting from the quadratic nonlinearity of Burgers equation \\$u u_x\\$ in Fourier space. Convolution sum is padded with the 3/2 rule for dealiasing.\n\n\"\"\"\nfunction quadratic_nonlinear(uhat,N,dL,alpha)\n    M = Int((3/2)*N); # For dealiasing -> For MZ models must be 3*N to account for unresolved modes + dealiasing\n    k_M = reduce(vcat,(2*π/dL)*[0:M/2-1 -M/2:-1]); # Wavenumbers for convolution sum with padding\n    u_M = zeros(Complex{Float64},Int(M));\n    u_M[1:Int(N/2)] = uhat[1:Int(N/2)];\n    u_M[end-Int(N/2)+2:end] = uhat[Int(N/2)+2:end];\n    u_M_sum = fft_norm(ifft_norm(u_M).*ifft_norm(u_M));\n    u_M_convolution = alpha*im.*k_M/2.0 .*u_M_sum;\n    uhat_nonlinear  = zeros(Complex{Float64},Int(N)); # Extract N modes from convolution\n    uhat_nonlinear[1:Int(N/2)] = u_M_convolution[1:Int(N/2)];\n    uhat_nonlinear[end-Int(N/2)+2:end] = u_M_convolution[end-Int(N/2)+2:end];\n    return uhat_nonlinear\nend\n\n\"\"\"\n    generate_fourier_solution(L1,L2,tspan,N,initial_condition,pde_function;dt=1e-3,nu=0.1,rtol=1e-10,atol=1e-14)\n\nGenerate the solution for a given `pde_function` and `initial_condition` on a periodic domain using a `N` mode Fourier expansion.\n\n\"\"\"\nfunction generate_fourier_solution(L1,L2,tspan,N,initial_condition,pde_function;dt=1e-3,nu=0.1,rtol=1e-10,atol=1e-14,alpha=1.0)\n    # Transform random initial condition to Fourier domain\n    uhat0 = fft_norm(initial_condition);\n    dL = abs(L2-L1);\n\n    # Generate Fourier Galerkin solution for N\n    k = reduce(vcat,(2*π/dL)*[0:N/2-1 -N/2:-1]);\n    p = [N,k,dL,nu,alpha]\n    t_length = Int(round(tspan[2]/dt)+1);\n\n    # Solve the system of ODEs in Fourier domain\n    prob = ODEProblem(pde_function,uhat0,tspan,p);\n    sol = solve(prob,DP5(),reltol=rtol,abstol=atol,saveat = dt)\n\n    u_sol = zeros(t_length,N);\n    for j in 1:size(sol.t,1) # Reshape output and plot\n        u_sol[j,:] = real.(ifft_norm(sol.u[j]));\n    end\n    return u_sol, sol.u, k\nend\n\n\"\"\"\n    central_difference(u_j,u_jpos,u_jneg,mu)\n\nCompute the second order central difference for the viscous term of the viscous Burgers equation \\$u_t = - u u_x + ν u_{xx}\\$. `mu` is equal to \\$ \\\\frac{\\\\nu}{\\\\Delta x^2}\\$.\n\n\"\"\"\nfunction central_difference(u_j,u_jpos,u_jneg,mu)\n    ux = zeros(size(u_j,2));\n    ux = mu.*(u_jpos-2*u_j+u_jneg);\n    return ux\nend\n\n\"\"\"\n    minmod(x,y)\n\n\"\"\"\nfunction minmod(x,y)\n    return sign(x)*max(0,min(abs(x),y*sign(x)));\nend\n\n\"\"\"\n    ub(ulv,urv)\n\n\"\"\"\nfunction ub(ulv,urv)\n    if ulv != urv\n        return ((1/2)*urv^2 - (1/2)*ulv^2) / (urv - ulv); # ̄u_{j+/-1/2}\n    else\n        return ulv\n    end\nend\n\n\"\"\"\n    fl(ulv,urv,ubv)\n\n\"\"\"\nfunction fl(ulv,urv,ubv)\n    return (1/2).*((1/2).*ulv.^2 .+ (1/2).*urv.^2 .- abs.(ubv).*(urv .- ulv)); # f_{j+/-1/2}\n# fln(ulv,urv,ubv) = (1/2)*(flux.(urv) - flux.(ulv) - abs.(ubv).*(ulv - urv)); # f_{j+/-1/2}\nend\n\n\"\"\"\n    ulpl(ujp,uj,ujn,kappa,omega)\n\n\"\"\"\nfunction ulpl(ujp,uj,ujn,kappa,omega)\n    return uj .+ ((1-kappa)/4).*minmod.((uj .- ujn),omega.*(ujp .- uj)) .+ ((1+kappa)/4).*minmod.((ujp .- uj),omega.*(uj .- ujn)); # u_{j+1/2}^L\nend\n\n\"\"\"\n    urpl(ujpp,ujp,uj,kappa,omega)\n\n\"\"\"\nfunction urpl(ujpp,ujp,uj,kappa,omega)\n    return ujp  .- ((1+kappa)/4).*minmod.((ujp .- uj),omega.*(ujpp .- ujp)) .- ((1-kappa)/4).*minmod.((ujpp .- ujp),omega.*(ujp .- uj)); # u_{j+1/2}^R\nend\n\n\"\"\"\n    ulnl(uj,ujn,ujnn,kappa,omega)\n\n\"\"\"\nfunction ulnl(uj,ujn,ujnn,kappa,omega)\n    return ujn .+ ((1-kappa)/4).*minmod.((ujn .- ujnn),omega.*(uj .- ujn)) .+ ((1+kappa)/4).*minmod.((uj .- ujn),omega.*(ujn .- ujnn)); # u_{j-1/2}^L\nend\n\n\"\"\"\n    urnl(ujp,uj,ujn,kappa,omega)\n\n\"\"\"\nfunction urnl(ujp,uj,ujn,kappa,omega)\n    return uj .- ((1+kappa)/4).*minmod.((uj .- ujn),omega.*(ujp .- uj)) .- ((1-kappa)/4).*minmod.((ujp .- uj),omega.*(uj .- ujn)); # u_{j-1/2}^R\nend\n\n\"\"\"\n    muscl_minmod_RHS!(du,u,p,t)\n\n\"\"\"\nfunction muscl_minmod_RHS!(du,u,p,t)\n    dx, kappa, omega, nu = p;\n\n    ulpvp = zeros(size(u,1));\n    urpvp = zeros(size(u,1));\n    ulnvp = zeros(size(u,1));\n    urnvp = zeros(size(u,1));\n\n    # ulp(ujp,uj,ujn,omega)\n    ulpvp[2:end-1] .= ulpl(u[3:end],u[2:end-1],u[1:end-2],kappa,omega);\n    ulpvp[1] = ulpl(u[2],u[1],u[end],kappa,omega);\n    ulpvp[end] = ulpl(u[1],u[end],u[end-1],kappa,omega);\n\n    # urp(ujpp,ujp,uj,omega)\n    urpvp[1:end-2] .= urpl(u[3:end],u[2:end-1],u[1:end-2],kappa,omega);\n    urpvp[end-1] = urpl(u[1],u[end],u[end-1],kappa,omega);\n    urpvp[end] = urpl(u[2],u[1],u[end],kappa,omega);\n\n    ubpp = ub.(ulpvp,urpvp);\n    fpp = fl(ulpvp,urpvp,ubpp);\n\n    # uln(uj,ujn,ujnn,omega)\n    ulnvp[3:end] .= ulnl(u[3:end],u[2:end-1],u[1:end-2],kappa,omega);\n    ulnvp[2] = ulnl(u[2],u[1],u[end],kappa,omega);\n    ulnvp[1] = ulnl(u[1],u[end],u[end-1],kappa,omega);\n\n    # urn(ujp,uj,ujn,omega)\n    urnvp[2:end-1] .= urnl(u[3:end],u[2:end-1],u[1:end-2],kappa,omega);\n    urnvp[1] = urnl(u[2],u[1],u[end],kappa,omega);\n    urnvp[end] = urnl(u[1],u[end],u[end-1],kappa,omega);\n\n    ubnp = ub.(ulnvp,urnvp);\n    fnp = fl(ulnvp,urnvp,ubnp);\n\n    du .= -(1/dx).*(fpp .- fnp);\nend\n\n\"\"\"\n    muscl_minmod_viscous_RHS!(du,u,p,t)\n\n\"\"\"\nfunction muscl_minmod_viscous_RHS!(du,u,p,t)\n    dx, kappa, omega, nu = p;\n\n    mu = nu/(dx)^2;\n\n    ulpvp = zeros(size(u,1));\n    urpvp = zeros(size(u,1));\n    ulnvp = zeros(size(u,1));\n    urnvp = zeros(size(u,1));\n    ux_viscous = zeros(size(u,1));\n\n    # ulp(ujp,uj,ujn,omega)\n    ulpvp[2:end-1] .= ulpl(u[3:end],u[2:end-1],u[1:end-2],kappa,omega);\n    ulpvp[1] = ulpl(u[2],u[1],u[end],kappa,omega);\n    ulpvp[end] = ulpl(u[1],u[end],u[end-1],kappa,omega);\n\n    # urp(ujpp,ujp,uj,omega)\n    urpvp[1:end-2] .= urpl(u[3:end],u[2:end-1],u[1:end-2],kappa,omega);\n    urpvp[end-1] = urpl(u[1],u[end],u[end-1],kappa,omega);\n    urpvp[end] = urpl(u[2],u[1],u[end],kappa,omega);\n\n    ubpp = ub.(ulpvp,urpvp);\n    fpp = fl(ulpvp,urpvp,ubpp);\n\n    # uln(uj,ujn,ujnn,omega)\n    ulnvp[3:end] .= ulnl(u[3:end],u[2:end-1],u[1:end-2],kappa,omega);\n    ulnvp[2] = ulnl(u[2],u[1],u[end],kappa,omega);\n    ulnvp[1] = ulnl(u[1],u[end],u[end-1],kappa,omega);\n\n    # urn(ujp,uj,ujn,omega)\n    urnvp[2:end-1] .= urnl(u[3:end],u[2:end-1],u[1:end-2],kappa,omega);\n    urnvp[1] = urnl(u[2],u[1],u[end],kappa,omega);\n    urnvp[end] = urnl(u[1],u[end],u[end-1],kappa,omega);\n\n    ux_viscous[1] = central_difference(u[1],u[2],u[end],mu);\n    ux_viscous[2:end-1] = central_difference(u[2:end-1],u[3:end],u[1:end-2],mu);\n    ux_viscous[end] = central_difference(u[end],u[1],u[end-1],mu);\n\n    ubnp = ub.(ulnvp,urnvp);\n    fnp = fl(ulnvp,urnvp,ubnp);\n\n    du .= -(1/dx).*(fpp .- fnp) .+ ux_viscous;\nend\n\n\"\"\"\n    generate_muscl_minmod_solution(L1,L2,t_end,N,u0,pde_function_handle;dt=1e-4,kappa=-1)\n\n\"\"\"\nfunction generate_muscl_minmod_solution(L1,L2,t_end,N,u0,pde_function_handle;dt=1e-4,kappa=-1,nu=0.1)\n\n    omega = ((3-kappa)/(1-kappa))\n\n    dL = abs(L2-L1);\n    # Set up periodic domain\n    j = reduce(vcat,[0:1:N-1]);\n    x = (dL.*j)./N;\n    dx = x[2]-x[1];\n    t = reduce(vcat,[0:dt:t_end]);\n\n    p = [dx,kappa,omega,nu]\n    t_span = (0,t_end);\n\n    prob = ODEProblem(pde_function_handle,u0,t_span,p);\n    sol = solve(prob,BS3(),reltol=1e-6,abstol=1e-8,saveat = dt);\n   \n    u_sol = zeros(size(sol.t,1),size(x,1));\n    for i in 1:size(sol.t,1)\n        u_sol[i,:] = sol.u[i];\n    end\n\n    return u_sol\n\nend\n\n\"\"\"\n    generate_muscl_reduced(L1,L2,t_end,dt,M,N,ic_func,pde_function_handle;kappa=-1,nu=0.1)\n\n\"\"\"\n# function generate_muscl_reduced(L1,L2,t_end,dt,M,N,ic_func,pde_function_handle;kappa=-1,nu=0.1)\nfunction generate_muscl_reduced(L1,L2,t_end,dt,M,N,ic,pde_function_handle;kappa=-1,nu=0.1)\n    dL = abs(L2 - L1);\n    j = reduce(vcat,[0:1:N-1]);\n    x = (dL.*j)./N;\n    j_full = reduce(vcat,[0:1:M-1]);\n    x_full = (dL.*j_full)./M;\n    # ic = ic_func.(x_full);\n    u_full = generate_muscl_minmod_solution(L1,L2,t_end,M,ic,pde_function_handle;dt=dt,kappa=kappa,nu=nu)\n    u_reduced = solution_spatial_sampling(x,x_full,u_full);\n    return u_full, u_reduced\nend\n\n\"\"\"\n    get_1D_energy_fft(u_solution)\n\nCompute the energy in the Fourier domain using the scaling of \\$ \\\\frac{1}{N} \\$. Note: this does not include the 2π multiplier found in Parseval's identity for Fourier series and computes \\$ \\\\frac{1}{2} \\\\sum \\\\vert \\\\hat{u}_k \\\\vert^2 \\$.\n\n\"\"\"\nfunction get_1D_energy_fft(u_solution) # To Do: Add and extraction of specific mode step\n    energy = zeros(size(u_solution,1))\n    for i in 1:size(u_solution,1)\n        u_hat = fft_norm(u_solution[i,:]);\n        energy[i] = (1/2)*real((u_hat'*u_hat));\n    end\n    return energy\nend\n\n\"\"\"\n    get_1D_energy_custom(basis,u_solution,L1,L2,weights;multiplier=1/(4*pi))\n\nCompute the energy in the custom basis domain: \\$ \\\\frac{1}{2} \\\\sum \\\\vert \\\\a_k \\\\vert^2 \\$. Multiplier defaults to \\$ \\\\frac{1}{4\\\\pi} \\$ to match the Fourier calculation.\n\n\"\"\"\nfunction get_1D_energy_custom(basis,u_solution,nodes,weights;multiplier=1/(4*pi))\n    energy = zeros(size(u_solution,1));\n    for i in 1:size(u_solution,1)\n        a_hat = expansion_coefficients(basis,u_solution[i,:],nodes,weights);\n        energy[i] = get_1D_energy_custom_coefficients(a_hat,zeta=multiplier);\n    end\n    return energy\nend\n\n\"\"\"\n    get_1D_energy_custom_coefficients(u_coefficients;zeta=1/(4*pi))\n\nCompute the energy in the custom basis domain: \\$ \\\\zeta \\\\sum \\\\vert \\\\a_k \\\\vert^2 \\$. \\$ \\\\zeta \\$ defaults to \\$ \\\\frac{1}{4\\\\pi} \\$ to match the Fourier calculation.\n\n\"\"\"\nfunction get_1D_energy_custom_coefficients(u_coefficients;zeta=1/(4*pi))\n        # energy[i] = (1/2)*(a_hat'*a_hat);\n        energy = zeta*(u_coefficients'*u_coefficients);\n    return energy\nend\n\n\"\"\"\n    mode_extractor(uhat,N)\n\n\"\"\"\nfunction mode_extractor(uhat,N)\n    uhat_N = zeros(typeof(uhat[1]),N);\n    uhat_N[1:Int(N/2)] = uhat[1:Int(N/2)];\n    uhat_N[end-Int(N/2)+2:end] = uhat[end-Int(N/2)+2:end];\n    return uhat_N\nend\n\n\"\"\"\n    get_1D_energy_upwind(u_solution_full,u_solution,N)\n\n\"\"\"\nfunction get_1D_energy_upwind(u_solution_full,u_solution,N)\n    energy = zeros(size(u_solution,1))\n    for i in 1:size(u_solution,1)\n        u_upwind_fft = mode_extractor(fft_norm(u_solution_full[i,:]),N);\n        energy[i] = (1/2)*real(u_upwind_fft'*u_upwind_fft);\n    end\n    return energy\nend\n\n\"\"\"\n    spectral_approximation_fourier(x_locations,k,coefficients)\n\n\"\"\"\nfunction spectral_approximation_fourier(x_locations,k,coefficients)\n    approximation = zeros(size(x_locations,1));\n    for i = 1:length(k)\n        approximation += coefficients[i]*exp.(im*k[i]*(x_locations));\n    end\n    return approximation\nend\n", "meta": {"hexsha": "1a942644fcf63ce75299a411342837b6aab76d85", "size": 12151, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PDESolve.jl", "max_stars_repo_name": "brekmeuris/DrMZ.jl", "max_stars_repo_head_hexsha": "18eedfae28357523c9a595bf48d2674038c8e45a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-12-14T00:05:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T04:06:35.000Z", "max_issues_repo_path": "src/PDESolve.jl", "max_issues_repo_name": "brekmeuris/DrMZ.jl", "max_issues_repo_head_hexsha": "18eedfae28357523c9a595bf48d2674038c8e45a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PDESolve.jl", "max_forks_repo_name": "brekmeuris/DrMZ.jl", "max_forks_repo_head_hexsha": "18eedfae28357523c9a595bf48d2674038c8e45a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-14T01:07:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T01:07:11.000Z", "avg_line_length": 31.4792746114, "max_line_length": 241, "alphanum_fraction": 0.6314706609, "num_tokens": 4503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.8418256393148981, "lm_q1q2_score": 0.7592599456921844}}
{"text": "\nh₁(i::Int) = max(6 - abs(i-7), 0)\nh₂(i::Int) = h₁(i - 8)\nh₃(i::Int) = h₁(i - 4)\n\n\"\"\"\n  triangular_test_function(c1::Int, c2::Int, c3::Int, L::Int=32)\n\nGenerates a set of triangluar test functions with 3 classes.\n\"\"\"\nfunction triangular_test_functions(c1::Int, c2::Int, c3::Int; L::Int=32, shuffle::Bool=false)\n  @assert c1 >= 0\n  @assert c2 >= 0\n  @assert c3 >= 0\n\n  u = rand(Uniform(0,1),1)[1]\n  ϵ = rand(Normal(0,1),(L,c1+c2+c3))\n\n  y = string.(vcat(ones(c1), ones(c2) .+ 1, ones(c3) .+ 2))\n\n  H₁ = Array{Float64,2}(undef,L,c1)\n  H₂ = Array{Float64,2}(undef,L,c2)\n  H₃ = Array{Float64,2}(undef,L,c3)\n  for i in 1:L\n    H₁[i,:] .= u * h₁(i) + (1 - u) * h₂(i)\n    H₂[i,:] .= u * h₁(i) + (1 - u) * h₃(i)\n    H₃[i,:] .= u * h₂(i) + (1 - u) * h₃(i)\n  end\n\n  H = hcat(H₁, H₂, H₃) + ϵ\n\n  if shuffle\n    idx = [1:(c1+c2+c3)...]\n    shuffle!(idx)\n    return H[:,idx], y[idx]\n  end\n\n  return H, y\nend", "meta": {"hexsha": "2db89813f4086889fbf180aee28ebc1cdcc0812c", "size": 893, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "BoundaryValueProblems/LDBExperiments", "max_stars_repo_head_hexsha": "cb3cf17bc1f6b0473ea97da2de65c2ef32a607c4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "BoundaryValueProblems/LDBExperiments", "max_issues_repo_head_hexsha": "cb3cf17bc1f6b0473ea97da2de65c2ef32a607c4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "BoundaryValueProblems/LDBExperiments", "max_forks_repo_head_hexsha": "cb3cf17bc1f6b0473ea97da2de65c2ef32a607c4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8974358974, "max_line_length": 93, "alphanum_fraction": 0.5375139978, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7592599430431247}}
{"text": "#=\nThe prime factors of 13195 are 5, 7, 13 and 29.\n\nWhat is the largest prime factor of the number 600851475143 ?\n=#\n\nusing Primes\n@time println(maximum(keys(factor(600851475143))))\n", "meta": {"hexsha": "4dbae7bade15db067c229600a65cfecf83b923e6", "size": 182, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p3.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p3.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p3.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 20.2222222222, "max_line_length": 61, "alphanum_fraction": 0.7417582418, "num_tokens": 56, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9572778024535095, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7592227197216725}}
{"text": "module AnalyticalPlaneSolver\r\n\r\nstruct PlaneSolver\r\n    L::Any\r\n    W::Any\r\n    R::Any\r\n    lambda1::Any\r\n    mu1::Any\r\n    lambda2::Any\r\n    mu2::Any\r\n    theta0::Any\r\n    C1::Any\r\n    C2::Any\r\n    D::Any\r\n    uI::Any\r\n    function PlaneSolver(L, W, R, lambda1, mu1, lambda2, mu2, theta0)\r\n        C1 = solver_coefficient(lambda1, mu1)\r\n        C2 = solver_coefficient(lambda2, mu2)\r\n        D = 2 * lambda1 * mu1 / (lambda1 + 2mu1)\r\n\r\n        uI = interface_displacement(L, R, C1, C2, D, theta0)\r\n        new(L, W, R, lambda1, mu1, lambda2, mu2, theta0, C1, C2, D, uI)\r\n    end\r\nend\r\n\r\n\r\nfunction solver_coefficient(lambda, mu)\r\n    C = 4 * mu * (lambda + mu) / (lambda + 2mu)\r\n    return C\r\nend\r\n\r\nfunction interface_displacement(L, R, C1, C2, D, theta0)\r\n    uI = -(C1 + D) / (C2 / R + C1 / (L - R)) * theta0 / 3\r\n    return uI\r\nend\r\n\r\nfunction parent_displacement_field(solver::PlaneSolver,x)\r\n    uI = solver.uI\r\n    R = solver.R\r\n    lambda = solver.lambda2\r\n    mu = solver.mu2\r\n\r\n    ux = uI/R*x[1]\r\n    uy = -lambda/(lambda+2mu)*uI/R*x[2]\r\n    return [ux,uy]\r\nend\r\n\r\nfunction product_displacement_field(solver::PlaneSolver,x)\r\n    uI = solver.uI\r\n    L = solver.L\r\n    R = solver.R\r\n    lambda = solver.lambda1\r\n    mu = solver.mu1\r\n    t0 = solver.theta0\r\n\r\n    ux = ((L-R)-(x[1]-R))/(L-R)*uI\r\n    uy = (lambda/(lambda+2mu)*uI/(L-R) + (3lambda+2mu)/(lambda+2mu)*t0/3)*x[2]\r\n\r\n    return [ux,uy]\r\nend\r\n\r\nfunction displacement_field(solver::PlaneSolver,x)\r\n    R = solver.R\r\n    if x[1] < R\r\n        return parent_displacement_field(solver,x)\r\n    else\r\n        return product_displacement_field(solver,x)\r\n    end\r\nend\r\n\r\nend\r\n", "meta": {"hexsha": "50d088381fd64eb9206983904430d70a723a46da", "size": 1637, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/time-step/perturbed-plane-interface/lagrange-levelset/analytical-solver.jl", "max_stars_repo_name": "ArjunNarayanan/CutCellDG.jl", "max_stars_repo_head_hexsha": "674897dfe1a6d317ec889bf1dd43f6524b5723a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/time-step/perturbed-plane-interface/lagrange-levelset/analytical-solver.jl", "max_issues_repo_name": "ArjunNarayanan/CutCellDG.jl", "max_issues_repo_head_hexsha": "674897dfe1a6d317ec889bf1dd43f6524b5723a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/time-step/perturbed-plane-interface/lagrange-levelset/analytical-solver.jl", "max_forks_repo_name": "ArjunNarayanan/CutCellDG.jl", "max_forks_repo_head_hexsha": "674897dfe1a6d317ec889bf1dd43f6524b5723a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7361111111, "max_line_length": 79, "alphanum_fraction": 0.5778863775, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079558, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7591891449258711}}
{"text": "function simulate_exp_gpreal(t,alpha,beta,ndev)\n#\n# Function for simulating a GP based upon an exponential correlation\n# matrix using an analytic form for the Cholesky decomposition and\n# a computation in O(N) operations.  The autocorrelation function is:\n#\n#    K_ij = alpha * exp(-beta*(|t_i-t_j|))\n#\n# Requirements:\n#  - alpha should be a real positive number.\n#  - The times t *must* be sorted in order from least to greatest.\n#  - beta may be complex\n#  - ndev: normal deviates drawn from N(0,1) with the same length as time vector t.\n# Output:\n#  - data is a GP drawn from this correlation function with length nt\n#\nnt = length(t)\ndata = zeros(eltype(beta),nt)\ndata[nt] = sqrt(alpha)*ndev[nt]\ngamma = zero(eltype(beta))\nfor i=nt-1:-1:1\n  gamma = exp(-beta*(t[i+1]-t[i]))\n#  println(i,\" \",abs(sqrt(1.0-gamma^2)))\n  data[i] = sqrt(1.0-gamma^2)*sqrt(alpha)*ndev[i]+gamma*data[i+1]\nend\nreturn data\nend\n", "meta": {"hexsha": "568af3d647437b3aca222e9298df6b3a95dce03a", "size": 904, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/simulate_exp_gpreal.jl", "max_stars_repo_name": "ericagol/GenRP.jl", "max_stars_repo_head_hexsha": "700848e75a88d2212560322724e87253482d145a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-03-27T11:11:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-18T23:33:48.000Z", "max_issues_repo_path": "examples/simulate_exp_gpreal.jl", "max_issues_repo_name": "tagordon/celerite2d.jl", "max_issues_repo_head_hexsha": "7fa487b1b1283f574559c06398449b6ba1dcf3ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2017-01-18T03:37:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-19T22:10:59.000Z", "max_forks_repo_path": "examples/simulate_exp_gpreal.jl", "max_forks_repo_name": "tagordon/celerite2d.jl", "max_forks_repo_head_hexsha": "7fa487b1b1283f574559c06398449b6ba1dcf3ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-03-23T20:03:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-18T13:11:16.000Z", "avg_line_length": 32.2857142857, "max_line_length": 83, "alphanum_fraction": 0.6991150442, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422158380861, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7591891404319253}}
{"text": "function CostGradient(X::Array,y::Vector;λ=0, Norm=false)\r\n\r\n   #Size of the X Parameters\r\n    m=size(X,1)\r\n    n=size(X,2)\r\n    #if Normalize\r\n\r\n    if Norm==true\r\n       μ=mean(X,dims=1)\r\n       σ=std(X,dims=1)\r\n       X=(X.-μ)./σ\r\n    else\r\n        μ=zeros(1,n)\r\n        σ=ones(1,n)\r\n    end\r\n\r\n\r\n    #Add vector of ones to X parameters\r\n    X=[ones(m) X]\r\n\r\n    CostFunction=function (θ)\r\n                    se=(X*θ).-y\r\n                    J=(0.5./m).*((se'*se)+λ*(θ[2:end]'*θ[2:end]))\r\n                    return J\r\n                end\r\n    θr=zeros(n+1)\r\n    Gradient=function (θ)\r\n             θr.=θ\r\n             θr[1]=0\r\n             g=(1/m).*(X'*((X*θ).-y)) .+ ((λ./m).*θr)\r\n        return g\r\n            end\r\n\r\n    return CostFunction, Gradient, μ, σ\r\nend\r\n", "meta": {"hexsha": "fa162247dc7b8df494e10c2c0759b147b5292edd", "size": 770, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CostGradient.jl", "max_stars_repo_name": "scuervo91/MachineLearning.jl", "max_stars_repo_head_hexsha": "b541ffd559d6994e08f4f9fd25c2259643ddff1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CostGradient.jl", "max_issues_repo_name": "scuervo91/MachineLearning.jl", "max_issues_repo_head_hexsha": "b541ffd559d6994e08f4f9fd25c2259643ddff1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CostGradient.jl", "max_forks_repo_name": "scuervo91/MachineLearning.jl", "max_forks_repo_head_hexsha": "b541ffd559d6994e08f4f9fd25c2259643ddff1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-01T12:53:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-01T12:53:18.000Z", "avg_line_length": 21.3888888889, "max_line_length": 66, "alphanum_fraction": 0.4168831169, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545392102523, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7591797562966239}}
{"text": "using AQFED.Math\nconst SqrtEpsilon = sqrt(eps())\n# totalVariance is vol^2*τ\nexport blackScholesFormula, blackScholesVega\n\nfunction blackScholesFormula(isCall::Bool, strike::Number, spot::Number, totalVariance::Number, driftDf::Number, discountDf::Number)\n    sign = 1\n    if !isCall\n        sign = -1\n    end\n    forward = spot / driftDf\n    if totalVariance < eps()\n        price = discountDf * max(sign * (forward - strike), 0)\n        return price\n    elseif spot < eps()\n        if isCall\n            return 0\n        else\n            return discountDf * strike\n        end\n    elseif strike < eps()\n        if isCall\n            return discountDf * forward\n        else\n            return 0\n        end\n    else\n        sqrtVar = sqrt(totalVariance)\n        d1 = log(forward / strike)/sqrtVar + sqrtVar/2\n        d2 = d1 - sqrtVar\n        nd1 = normcdf(sign * d1)\n        nd2 = normcdf(sign * d2)\n        price = sign * discountDf * (forward * nd1 - strike * nd2)\n        return price\n    end\nend\n\nfunction blackScholesVega(strike::Number,\n\tspot::Number,\n\tvariance::Number,\n\tdriftDf::Number,\n\tdiscountDf::Number,\n\ttte::Number)::Number\n\tforward = spot / driftDf\n\tsqrtVar = sqrt(variance)\n\td1 = 1.0/sqrtVar*log(forward/strike) + 0.5*sqrtVar\n\tnd1 = normpdf(d1)\n\tvega = discountDf * forward * nd1 * sqrt(tte)\n\treturn vega\nend\n", "meta": {"hexsha": "65ce63082dc6a5d6e53e51eb598483ec850d6a57", "size": 1327, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/black/black.jl", "max_stars_repo_name": "IngiOrn/AQFED.jl", "max_stars_repo_head_hexsha": "dcd9f4bc2cf87e11d2ec7bde2a757a010c07b0af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-07-12T06:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T09:50:37.000Z", "max_issues_repo_path": "src/black/black.jl", "max_issues_repo_name": "IngiOrn/AQFED.jl", "max_issues_repo_head_hexsha": "dcd9f4bc2cf87e11d2ec7bde2a757a010c07b0af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-02-10T19:25:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-10T21:54:48.000Z", "max_forks_repo_path": "src/black/black.jl", "max_forks_repo_name": "IngiOrn/AQFED.jl", "max_forks_repo_head_hexsha": "dcd9f4bc2cf87e11d2ec7bde2a757a010c07b0af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-09-01T10:35:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T16:26:00.000Z", "avg_line_length": 26.0196078431, "max_line_length": 132, "alphanum_fraction": 0.6164280332, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7591797516958799}}
{"text": "##\n##  s p e c i a l . j l  Special Functions\n##\n\n\n# Lambert W function, inverse of x -> x exp(x)\n# its derivative is 1 / (1+zw) / exp(zw) where zw = lambertW(z)\n#\nfunction lambertW(x::Real)\n    if x <  -1.0/exp(1.0); return NaN, NaN;  end\n    if x == -1.0/exp(1.0); return -Inf, Inf; end\n\n    local w0::Real = 1.0, w1::Real, w2::Real\n    w1 = w0 - (w0 * exp(w0) - x)/((w0 + 1.0) * exp(w0) - \n        (w0 + 2.0) * (w0 * exp(w0) - x)/(2.0 * w0 + 2.0))\n\n    while abs(w1 - w0) > 1e-15\n        w0 = w1\n        w1 = w0 - (w0 * exp(w0) - x)/((w0 + 1.0) * exp(w0) - \n            (w0 + 2.0) * (w0 * exp(w0) - x)/(2.0 * w0 + 2.0))\n    end\n\n    w2 = 1.0 / (1 + w1) / exp(w1)\n\n    return w1, w2\nend\n", "meta": {"hexsha": "6a76024f873df83025ebd1de7a349242436ad643", "size": 689, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/specfun.jl", "max_stars_repo_name": "MaxandreJ/NumericalMath.jl", "max_stars_repo_head_hexsha": "e3835ec3f2f9f04a9dde843b825c0b510c3ade59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-03-11T19:26:16.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-12T21:39:58.000Z", "max_issues_repo_path": "src/specfun.jl", "max_issues_repo_name": "MaxandreJ/NumericalMath.jl", "max_issues_repo_head_hexsha": "e3835ec3f2f9f04a9dde843b825c0b510c3ade59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-02-05T14:03:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-26T03:45:52.000Z", "max_forks_repo_path": "src/specfun.jl", "max_forks_repo_name": "MaxandreJ/NumericalMath.jl", "max_forks_repo_head_hexsha": "e3835ec3f2f9f04a9dde843b825c0b510c3ade59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2015-01-25T21:38:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T04:30:29.000Z", "avg_line_length": 25.5185185185, "max_line_length": 63, "alphanum_fraction": 0.4615384615, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7591797492585025}}
{"text": "export Random, random\n\"\"\"\n    random(x;args)\n\nRandomly generate a vector of size `x`, based on provided (optional arguments) :\n- `L` is the typical wavelength (default is `L=1`),\n- `s` is the (real) Sobolev index regularity (default is `s=∞`, smooth data),\n- `λ` is the length of spatial localization (default is `λ=∞`, no localization),\n- `a` is the amplitude of the returned vector (default is `a=1`).\n\nThe vector is generated through randomly chosen Fourier coefficients,\nmultiplied with weigth `w=10^(-|k|L/(2π))` if `s=∞`, or `w=1/(1+9(|k|L/(2π))^(s+1/2))` otherwise.\nIf `λ≠∞`, the function in spatial variables is multiplied by `exp(-|x/λ|^2)`,\nand in any case normalized to have maximum absolute value 1.\n\n\n\"\"\"\nfunction random( x;L=1,s=Inf,λ=Inf,a=1 )\n\n\n    k = Mesh( x ).k\n    if s == Inf\n        w = 10 .^(-abs.(k*L/(2*π)))\n    else\n        w = 1 ./( 1 .+ 9*abs.(k*L/(2*π)).^(s+1/2) )\n    end\n    if λ == Inf\n        φ = zero(x).+1\n    else\n        φ = exp.(-abs.((x/λ).^2))\n    end\n\n    θ = 2*π*rand(Float64,length(x))\n    r = rand(Float64,length(x))\n    Fourier = r.*exp.(-1im.*θ).*w\n    Physic = real.(ifft(Fourier)).*φ\n    return Physic./(maximum(Physic)-minimum(Physic))*a\nend\n\n\"\"\"\n    Random(param;args)\n\nRandomly generated initial data, based on provided (optional arguments) :\n- `L` is the typical wavelength (default is `L=1`),\n- `s` is the (real) Sobolev index regularity (default is `s=∞`),\n- `λ` is the length of spatial localization (default is `λ=∞`, no localization),\n- `a` is the couple of amplitudes of the surface deformation, and velocity (default is `a=(1,1)`).\n\n\nReturn an initial data `init::InitialData`,  to be used in initial-value problems `Problem(model, init, param)`,\nwith `init.η` and `init.v` two samples of `random(x;L,s,λ)`,\nwhere `x` is the set of collocation points generated by `Mesh(param)`.\n\n\"\"\"\nstruct Random <: InitialData\n\n    η\n    v\n    label :: String\n    info  :: String\n\n    function Random(param;L=1,s=Inf,λ=Inf,a=(1,1))\n        mesh=Mesh(param);x=mesh.x;\n        η = random( x; L=L,s=s,λ=λ,a=a[1] )\n        v = random( x; L=L,s=s,λ=λ,a=a[2] )\n        init=Init(x,η,v)\n        if s == Inf s=\"∞\" end\n        if λ == Inf λ=\"∞\" end\n        label = \"randomly generated\"\n        info = \"Randomly generated initial data with \\n\\\n        ├───typical wavelength: L = $L,\\n\\\n        ├─────regularity index: s = $s,\\n\\\n        ├─spatial localization: λ = $λ,\\n\\\n        ├────surface amplitude: $(a[1]),\\n\\\n        └───velocity amplitude: $(a[2]).\"\n    \tnew( init.η,init.v,label,info )\n\n    end\n\nend\n", "meta": {"hexsha": "b664ac963e2a3694b0deb87e89fd41e74e3c6ba1", "size": 2545, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/initialdata/Random.jl", "max_stars_repo_name": "DeepWaterModels/FModels.jl", "max_stars_repo_head_hexsha": "66f58bbee576abcc47c73d64b2a66f1f80b824f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/initialdata/Random.jl", "max_issues_repo_name": "DeepWaterModels/FModels.jl", "max_issues_repo_head_hexsha": "66f58bbee576abcc47c73d64b2a66f1f80b824f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/initialdata/Random.jl", "max_forks_repo_name": "DeepWaterModels/FModels.jl", "max_forks_repo_head_hexsha": "66f58bbee576abcc47c73d64b2a66f1f80b824f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4197530864, "max_line_length": 112, "alphanum_fraction": 0.5952848723, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9481545333502202, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7591797470951359}}
{"text": "using BenchmarkTools\nusing LinearAlgebra\n\nfunction progonka!(u,a,b,c,f)\n    N = size(f,1)\n    α=similar(f)\n    β=similar(f)\n    α[2] = -c[1]/b[1]\n    β[2] = f[1]/b[1]\n    @inbounds @fastmath for i in 2:N-1 #Forward Sweep\n        α[i+1]=-c[i]/(a[i-1]*α[i]+b[i])\n        β[i+1]=(f[i]-a[i-1]*β[i])/(a[i-1]*α[i]+b[i])\n    end\n    u[N]=(f[N]-a[N-1]*β[N])/(a[N-1]*α[N]+b[N])\n    @inbounds @fastmath for i in N-1:-1:1 #Backward Sweep\n        u[i]=α[i+1]*u[i+1]+β[i+1]\n    end\n    u\nend\n\nprogonka(a,b,c,f)=progonka!(similar(f),a,b,c,f)\n\n\nfunction tprogonka()\n    N=1000\n    a=-rand(N-1)\n    c=-rand(N-1)\n    b=2.0.+rand(N)\n    f=rand(N)\n   \n    A=Tridiagonal(a,b,c)\n    utri=A\\f\n    upro=progonka(a,b,c,f)\n    @assert utri≈upro\n    @btime utri=$A\\$f\n    @btime upro=progonka($a,$b,$c,$f)\n    nothing\nend\n", "meta": {"hexsha": "fd964b1bb7f7118bfd995f05b12dd28037f35721", "size": 796, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/testThomas.jl", "max_stars_repo_name": "CliMA/CGDycore.jl", "max_stars_repo_head_hexsha": "77297631f8db7775f19daee2d7ac75bc810d9c11", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-05T07:09:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T07:09:16.000Z", "max_issues_repo_path": "Examples/testThomas.jl", "max_issues_repo_name": "CliMA/CGDycore.jl", "max_issues_repo_head_hexsha": "77297631f8db7775f19daee2d7ac75bc810d9c11", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/testThomas.jl", "max_forks_repo_name": "CliMA/CGDycore.jl", "max_forks_repo_head_hexsha": "77297631f8db7775f19daee2d7ac75bc810d9c11", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4102564103, "max_line_length": 57, "alphanum_fraction": 0.5175879397, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856297, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.7591560331696622}}
{"text": "# v0.6.0\n\nfunction magicsquareodd(base::Int)\n    if base & 1 == 0 || base < 3; error(\"base must be odd and >3\") end\n\n    square = fill(0, base, base)\n    r, number = 1, 1\n    size = base * base\n\n    c = div(base, 2) + 1\n    while number ≤ size\n        square[r, c] = number\n        fr = r == 1 ? base : r - 1\n        fc = c == base ? 1 : c + 1\n        if square[fr, fc] != 0\n            fr = r == base ? 1 : r + 1\n            fc = c\n        end\n        r, c = fr, fc\n        number += 1\n    end\n\n    return square\nend\n\nfor n in 3:2:7\n    println(\"Magic square with size $n - magic constant = \", div(n ^ 3 + n, 2))\n    println(\"----------------------------------------------------\")\n    square = magicsquareodd(n)\n    for i in 1:n\n        println(square[i, :])\n    end\n    println()\nend\n", "meta": {"hexsha": "df9772524f8a17d95d50e787706e75631a0d7562", "size": 786, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/magic-squares-of-odd-order.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/magic-squares-of-odd-order.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/magic-squares-of-odd-order.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4571428571, "max_line_length": 79, "alphanum_fraction": 0.4440203562, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7591560244027854}}
{"text": "import MathematicalSets.AbstractSet\n\n# ===========================================================================\n# This is a collection of concrete subtypes of `AbstractSet` for the purposes\n# of testing and code coverage.\n#\n# For use cases of `MathematicalSets` in external libraries, see the section\n# `Usage` in the documentation.\n# ===========================================================================\n\n\"\"\"\n    DummySet <: MathematicalSets.AbstractSet\n\nThe dummy set is a set with no fields. It is used to cover the `MathematicalSets`\nfunctions.\n\"\"\"\nstruct DummySet <: MathematicalSets.AbstractSet end\n\n\"\"\"\n    Singleton{T<:AbstractVector} <: AbstractSet\n\nA singleton is a set with one element.\n\n### Fields\n\n- `element` -- element in the singleton\n\"\"\"\nstruct Singleton{T<:AbstractVector} <: MathematicalSets.AbstractSet\n    element::T\nend\n\nMathematicalSets.space_dimension(s::Singleton) = length(s.element)\n\n# the dimension of a point is conventionally 0\nMathematicalSets.dimension(s::Singleton) = 0\n\n# the following metric properties for a singleton are usually zero, although\n# depending on the applicaton one could be interested to have e.g. a Dirac δ\n# if commented, defaults to returning `nothing` in `MathematicalSets`:\nMathematicalSets.volume(s::Singleton) = 0.\nMathematicalSets.surface_area(s::Singleton) = 0.\n\n\"\"\"\n    Ball{T} <: AbstractSet\n\nEuclidean ``n``-dimensional ball in ``\\\\mathbb{R}^n``.\n\n### Fields\n\n- `center` -- vector that represents the center of the ball\n- `radius` -- scalar that represents the radius of the ball\n\"\"\"\nstruct Ball{T, VT <: AbstractVector{T}} <: MathematicalSets.AbstractSet\n    center::VT\n    radius::T\nend\nradius(S::Ball) = S.radius\ncenter(S::Ball) = S.center\n\nMathematicalSets.space_dimension(S::Ball) = length(S.center)\nMathematicalSets.dimension(S::Ball) = space_dimension(S)\n\n# convenience constructor: if only the radius and dimension are supplied,\n# the ball is centered in the origin\nBall(R::T, n::Int) where T = Ball(zeros(T, n), R)\n \nusing SpecialFunctions # needed for the gamma function\n\nfunction MathematicalSets.volume(S::Ball)\n    n, R = dimension(S), radius(S)\n    return π^(n/2) * R^n / gamma(n/2 + 1)\nend\n\nfunction MathematicalSets.surface_area(S::Ball)\n    n, R = dimension(S), radius(S)\n    return π^(n/2) * n * R^(n-1) / gamma(n/2 + 1)\nend\n", "meta": {"hexsha": "2d49545dfc63c69a2f6850b80f44d05d107fc167", "size": 2314, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_sets.jl", "max_stars_repo_name": "JuliaReach/MathematicalSets.jl", "max_stars_repo_head_hexsha": "f577ffbc527fe7a8269d942dfc0bb771c14226f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-12-10T21:53:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:16:27.000Z", "max_issues_repo_path": "test/test_sets.jl", "max_issues_repo_name": "JuliaReach/MathematicalSets.jl", "max_issues_repo_head_hexsha": "f577ffbc527fe7a8269d942dfc0bb771c14226f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2018-12-12T20:05:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-11T12:34:37.000Z", "max_forks_repo_path": "test/test_sets.jl", "max_forks_repo_name": "JuliaReach/MathematicalSets.jl", "max_forks_repo_head_hexsha": "f577ffbc527fe7a8269d942dfc0bb771c14226f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6666666667, "max_line_length": 81, "alphanum_fraction": 0.6780466724, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8633916205190225, "lm_q1q2_score": 0.7590479577418494}}
{"text": "\r\n# =========================================================================== #\r\n# Types\r\n# =========================================================================== #\r\n\r\nabstract type DistributionType \r\nend\r\n\r\nstruct UniformDistribution{T} <: DistributionType\r\n    a::T\r\n    b::T\r\nend\r\nfunction UniformDistribution(a::T, b::T) where {T}\r\n    a = min(a, b)\r\n    b = max(a, b)\r\n    UniformDistribution{T}(a, b)\r\nend\r\nfunction UniformDistribution() where {T}\r\n    UniformDistribution{T}(0.0, 1.0)\r\nend\r\n\r\n\r\nstruct NormalDistribution{T} <: DistributionType\r\n    mu::T\r\n    sigma::T\r\nend\r\nfunction NormalDistribution(mu::T, sigma::T) where {T}\r\n    if sigma < 0\r\n        error(\"sigma must be positive\")\r\n    end\r\n    NormalDistribution{T}(mu, sigma)\r\nend\r\nfunction NormalDistribution(;mu = 0.0, sigma = 1.0) \r\n    NormalDistribution(mu, sigma)\r\nend\r\n\r\nstruct CauchyDistribution{T} <: DistributionType\r\n    mu::T\r\n    c::T\r\nend\r\nfunction CauchyDistribution(mu::T, c::T) where {T}\r\n    CauchyDistribution{T}(mu, c)\r\nend\r\nfunction CauchyDistribution(;mu = 0.0, c = 1.0)\r\n    CauchyDistribution(mu, c)\r\nend\r\n\r\n\r\n\r\nstruct MultiNormalDistribution{T} <: DistributionType\r\n    mu::Vector{T}\r\n    sigma::Matrix{T}\r\n    L::LowerTriangular{T, Matrix{T}}\r\n    inv_sigma::Matrix{T}\r\nend\r\nfunction MultiNormalDistribution(mu::Vector{T}, sigma::Matrix{T}) where {T}\r\n    n_dim = length(mu)\r\n    sz = size(sigma)\r\n    if sz[1] != sz[2]\r\n        error(\"Non-square sigma matrix\")\r\n    end\r\n    if sz[1] != n_dim\r\n        error(\"dimension mismatch between mu and sigma\")\r\n    end\r\n\r\n    fact = cholesky(sigma)\r\n    \r\n    id = Matrix{T}( one(T) * I, n_dim, n_dim )\r\n    inv_sigma = fact.L \\ ( fact.U \\ id )\r\n    MultiNormalDistribution{T}(mu, sigma, fact.L, inv_sigma)\r\nend\r\n", "meta": {"hexsha": "5bf36ecc3aaab281151096bc21e23c137cb77f05", "size": 1755, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/common/distributions/src/distr_types.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "__lib__/math/common/distributions/src/distr_types.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "__lib__/math/common/distributions/src/distr_types.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.375, "max_line_length": 80, "alphanum_fraction": 0.5698005698, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7590433514756608}}
{"text": "\"\"\"\n    TDist(ν)\n\nThe *Students T distribution* with `ν` degrees of freedom has probability density function\n\n```math\nf(x; d) = \\\\frac{1}{\\\\sqrt{d} B(1/2, d/2)}\n\\\\left( 1 + \\\\frac{x^2}{d} \\\\right)^{-\\\\frac{d + 1}{2}}\n```\n\n```julia\nTDist(d)      # t-distribution with d degrees of freedom\n\nparams(d)     # Get the parameters, i.e. (d,)\ndof(d)        # Get the degrees of freedom, i.e. d\n```\n\nExternal links\n\n[Student's T distribution on Wikipedia](https://en.wikipedia.org/wiki/Student%27s_t-distribution)\n\n\"\"\"\nstruct TDist{T<:Real} <: ContinuousUnivariateDistribution\n    ν::T\n    TDist{T}(ν::T) where {T <: Real} = new{T}(ν)\nend\n\nfunction TDist(ν::T) where {T <: Real}\n    @check_args(TDist, ν > zero(ν))\n    return TDist{T}(ν)\nend\n\nTDist(ν::T, ::NoArgCheck) where {T<:Real} = TDist{T}(ν)\nTDist(ν::Integer) = TDist(float(ν))\n\n@distr_support TDist -Inf Inf\n\n#### Conversions\nconvert(::Type{TDist{T}}, ν::Real) where {T<:Real} = TDist(T(ν))\nconvert(::Type{TDist{T}}, d::TDist{S}) where {T<:Real, S<:Real} = TDist(T(d.ν), NoArgCheck())\n\n#### Parameters\n\ndof(d::TDist) = d.ν\nparams(d::TDist) = (d.ν,)\n@inline partype(d::TDist{T}) where {T<:Real} = T\n\n\n#### Statistics\n\nmean(d::TDist{T}) where {T<:Real} = d.ν > 1 ? zero(T) : T(NaN)\nmedian(d::TDist{T}) where {T<:Real} = zero(T)\nmode(d::TDist{T}) where {T<:Real} = zero(T)\n\nfunction var(d::TDist{T}) where T<:Real\n    ν = d.ν\n    isinf(ν) && return one(T)\n    ν > 2 ? ν / (ν - 2) :\n    ν > 1 ? T(Inf) : T(NaN)\nend\n\nskewness(d::TDist{T}) where {T<:Real} = d.ν > 3 ? zero(T) : T(NaN)\n\nfunction kurtosis(d::TDist{T}) where T<:Real\n    ν = d.ν\n    ν > 4 ? 6 / (ν - 4) :\n    ν > 2 ? T(Inf) : T(NaN)\nend\n\nfunction entropy(d::TDist{T}) where T <: Real\n    isinf(d.ν) && return entropy( Normal(zero(T), one(T)) )\n    h = d.ν/2\n    h1 = h + 1//2\n    h1 * (digamma(h1) - digamma(h)) + log(d.ν)/2 + lbeta(h, 1//2)\nend\n\n\n#### Evaluation & Sampling\n\n@_delegate_statsfuns TDist tdist ν\n\nrand(rng::AbstractRNG, d::TDist) = randn(rng) / ( isinf(d.ν) ? 1 : sqrt(rand(rng, Chisq(d.ν))/d.ν) )\n\nfunction cf(d::TDist{T}, t::Real) where T <: Real\n    isinf(d.ν) && return cf(Normal(zero(T), one(T)), t)\n    t == 0 && return complex(1)\n    h = d.ν/2\n    q = d.ν/4\n    complex(2(q*t^2)^q * besselk(h, sqrt(d.ν) * abs(t)) / gamma(h))\nend\n\ngradlogpdf(d::TDist{T}, x::Real) where {T<:Real} = isinf(d.ν) ? gradlogpdf(Normal(zero(T), one(T)), x) : -((d.ν + 1) * x) / (x^2 + d.ν)\n", "meta": {"hexsha": "dca9a38101440926402be6ea1ed68847cf7f7a16", "size": 2396, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/tdist.jl", "max_stars_repo_name": "uwbanjoman/Distributions.jl", "max_stars_repo_head_hexsha": "3f3dbe911629120e0fd875291aaaec1645b0f855", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/tdist.jl", "max_issues_repo_name": "uwbanjoman/Distributions.jl", "max_issues_repo_head_hexsha": "3f3dbe911629120e0fd875291aaaec1645b0f855", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/tdist.jl", "max_forks_repo_name": "uwbanjoman/Distributions.jl", "max_forks_repo_head_hexsha": "3f3dbe911629120e0fd875291aaaec1645b0f855", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7634408602, "max_line_length": 135, "alphanum_fraction": 0.57721202, "num_tokens": 941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7590433452856196}}
{"text": "doc\"\"\"\n    rsi(ta, n=14; wilder=false)\n\nRelative Strength Index\n\n```math\n    RSI = \\frac{EMA(Up, n)}{EMA(Up, n) + EMA(Dn, n)}\n```\n\"\"\"\nfunction rsi(ta::TimeArray, n::Int=14; wilder::Bool=false)\n    ret = diff(ta.values)\n    ups = zeros(size(ta.values, 1) - 1, size(ta.values, 2))\n    dns = zeros(size(ta.values, 1) - 1, size(ta.values, 2))\n\n    @inbounds for i in 1:size(ta.values, 1) - 1\n        for j in 1:size(ta.values, 2)\n            if ret[i, j] >= 0\n                ups[i, j] += ret[i, j]\n            else\n                dns[i, j] += ret[i, j]\n            end\n        end\n    end\n\n    upsema = ema(ups, n, wilder=wilder)\n    dnsema = abs.(ema(dns, n, wilder=wilder))\n    rs     = upsema ./ dnsema\n\n    res  = @. 100 - (100 / (1 + rs))\n\n    cname   = String[]\n    cols    = colnames(ta)\n    for c in 1:length(cols)\n        push!(cname, string(cols[c], \"_rsi_\", n))\n    end\n\n    TimeArray(ta.timestamp[n+1:end], res, cname, ta.meta)\nend\n\ndoc\"\"\"\n    cci(ohlc, ma=20, c=0.015)\n\nCommodity Channel Index\n\n```math\n    CCI = \\frac{P_{typical} - SMA(P_{typical})}{c \\times \\sigma(P_{typical})}\n```\n\n**Reference**\n\n- https://en.wikipedia.org/wiki/Commodity_channel_index\n\n\"\"\"\nfunction cci(ohlc::TimeArray, ma::Int=20, c::AbstractFloat=0.015)\n    pt = typical(ohlc)\n    cci = safediv.((pt .- sma(pt, ma)), moving(mean_abs_dev, pt, ma)) ./ c\n    rename(cci, \"cci\")\nend\n\ndoc\"\"\"\n    chaikinoscillator(ohlcv, fast=3, slow=10; h=\"High\", l=\"Low\", c=\"Close\")\n\n**Chaikin Oscillator**\n\nDeveloped by Marc Chaikin\n\n**Formula**\n\n```math\n    Chaikin\\ OSC = EMA(ADL, fast) - EMA(ADL, slow)\n```\n\nwhere the [`adl`](@ref) is the Accumulation/Distribution Line.\n\n**Reference**\n\n- [StockCharts]\n  (http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:chaikin_oscillator)\n\"\"\"\nfunction chaikinoscillator(ohlcv::TimeArray, fast::Integer=3, slow::Integer=10;\n                           h=\"High\", l=\"Low\", c=\"Close\")\n    _adl = adl(ohlcv, h=h, l=l, c=c)\n    rename(ema(_adl, fast) .- ema(_adl, slow), [\"chaikinoscillator\"])\nend\n\ndoc\"\"\"\n    macd(ta, fast=12, slow=26, signal=9; wilder=false)\n\nMoving Average Convergence / Divergence\n\n```math\n    \\begin{align*}\n        MACD Bar & = DIF - DEM \\\\\n        DIF & = EMA(P_{close}, fast) - EMA(P_{close}, slow) \\\\\n        DEM & = EMA(DIF, 9) \\tag{signal}\n    \\end{align*}\n```\n\n**Return**:\n\n`TimeArray` with 3 columns `[\"macd\", \"dif\", \"signal\"]`.\n\nIf the input is a multi-column `TimeArray`, the new column names will be\n`[\"A_macd\", \"B_macd\", \"A_dif\", \"B_dif\", \"A_signal\", \"B_signal\"]`.\n\n\"\"\"\nfunction macd(ta::TimeArray{T,N},\n              fast::Int=12, slow::Int=26, signal::Int=9;\n              wilder::Bool=false) where {T,N}\n    dif = ema(ta, fast, wilder=wilder) .- ema(ta, slow, wilder=wilder)\n    sig = ema(dif, signal, wilder=wilder)\n    osc = dif .- sig\n\n    cols = [\"macd\", \"dif\", \"signal\"]\n    new_cols = (N > 1) ? gen_colnames(ta.colnames, cols) : cols\n\n    merge(merge(osc, dif), sig, colnames=new_cols)\nend\n\ndoc\"\"\"\n    roc(ta, n)\n\n**Rate of Change**\n\n**Formula**:\n\n```math\n    roc = \\frac{close_{t} - close_{t-n}}{close_{t-n}}\n```\n\n**Reference**:\n\n- [Wikipedia](https://en.wikipedia.org/wiki/Momentum_(technical_analysis))\n\n\"\"\"\nfunction roc(ta::TimeArray, n::Integer)\n    prev = lag(ta, n)\n    rename((ta .- prev) ./ prev, [\"$c\\_roc_$n\" for c ∈ ta.colnames])\nend\n\ndoc\"\"\"\n    aroon(ohlc, n=25; h=\"High\", l=\"Low\")\n\n**Aroon Oscillator**\n\n**Formula**\n\n```math\n    \\begin{align*}\n        up   & = \\frac{\\mathop{argmax}(High_{t-n} \\dots High_t)}{n} \\times 100 \\\\\n        down & = \\frac{\\mathop{argmin}(Low_{t-n} \\dots Low_t)}{n} \\times 100 \\\\\n        osc  & = up - down\n    \\end{align*}\n```\n\n**Reference**\n\n- [StockCharts]\n  (http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:aroon_oscillator)\n\"\"\"\nfunction aroon(ohlc::TimeArray, n::Integer=25; h=\"High\", l=\"Low\")\n    up = rename(moving(indmax, ohlc[h], n) ./ n .* 100, \"up\")\n    dn = rename(moving(indmin, ohlc[l], n) ./ n .* 100, \"dn\")\n    osc = rename(up .- dn, \"osc\")\n\n    merge(merge(up, dn), osc)\nend\n\ndoc\"\"\"\n    adx(ohlc, n=14; h=\"High\", l=\"Low\", c=\"Close\")\n\n**Average Directional Movement Index**\n\nDeveloped by J. Welles Wilder.\nThis Implementation follows StockCharts.\n\n**Reference**\n\n- [wikipedia]\n  (https://en.wikipedia.org/wiki/Average_directional_movement_index)\n\n- [StockCharts]\n  (http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_directional_index_adx)\n\"\"\"\nfunction adx(ohlc::TimeArray, n::Integer=14; h=\"High\", l=\"Low\", c=\"Close\")\n    dm = relu(merge(ohlc[h] .- lag(ohlc[h]), lag(ohlc[l]) .- ohlc[l]))\n    dm.values[findmin(dm.values, 2)[2]] = 0\n\n    dm = wilder_smooth(dm, n)\n\n    tr = wilder_smooth(truerange(ohlc, h=h, l=l, c=c), n)\n\n    di = (dm ./ tr) .* 100\n    di = rename(di, [\"+di\", \"-di\"])\n\n    dx = @. abs((di[\"+di\"] - di[\"-di\"]) / (di[\"+di\"] + di[\"-di\"])) * 100\n    adx = wilder_smooth(dx, n, dx=true)\n\n    rename(merge(adx, merge(dx, di)), [\"adx\", \"dx\", \"+di\", \"-di\"])\nend\n\ndoc\"\"\"\n    stochasticoscillator(ohlc, n=14, fast_d=3, slow_d=3; h=\"High\", l=\"Low\", c=\"Close\")\n\n**Stochastic Oscillator**\n\nA.k.a *%K%D*, or *KD*\n\n**Parameter**\n\n- `n`: period of fast(raw) `%K`\n\n- `fast_d`: MA period of fast `%D`\n\n- `slow_d`: MA period of slow `%D`\n\n**Formula**\n\n```math\n    \\begin{align*}\n        fast\\ \\%K & = \\frac{Close_t - \\max(High_{t-n}, \\dots, High_t)}\n            {\\max(High_{t-n}, \\dots, High_t) - \\min(Low_{t-n}, \\dots, Low_t)}\n            \\times 100 \\\\\n        fast\\ \\%D & = SMA(fast\\ \\%K) \\\\\n        slow\\ \\%D & = SMA(fast\\ \\%D)\n    \\end{align*}\n```\n\n**Reference**\n\n- [Wikipedia]\n  (https://en.wikipedia.org/wiki/Stochastic_oscillator)\n\n- [FMLabs]\n  (http://www.fmlabs.com/reference/default.htm?url=StochasticOscillator.htm)\n\"\"\"\nfunction stochasticoscillator(ohlc::TimeArray, n::Integer=14, fast_d::Integer=3,\n                              slow_d::Integer=3; h=\"High\", l=\"Low\", c=\"Close\")\n    high = moving(maximum, ohlc[h], n)\n    low = moving(minimum, ohlc[l], n)\n    fast_k = rename((ohlc[c] .- low) ./ (high .- low) .* 100, \"fast_k\")\n    fast_d = rename(sma(fast_k, fast_d), \"fast_d\")\n    slow_d = rename(sma(fast_d, slow_d), \"slow_d\")\n    merge(merge(fast_k, fast_d), slow_d)\nend\n", "meta": {"hexsha": "b537cad7603bf5f61f59d2d8d11f610fc06fc164", "size": 6173, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/momentum.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/MarketTechnicals.jl-4f8c86c6-9e40-5506-9807-98571cb48bc8", "max_stars_repo_head_hexsha": "168ab386e9e368e13a908642dedb4c51c82a642b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/momentum.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/MarketTechnicals.jl-4f8c86c6-9e40-5506-9807-98571cb48bc8", "max_issues_repo_head_hexsha": "168ab386e9e368e13a908642dedb4c51c82a642b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/momentum.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/MarketTechnicals.jl-4f8c86c6-9e40-5506-9807-98571cb48bc8", "max_forks_repo_head_hexsha": "168ab386e9e368e13a908642dedb4c51c82a642b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.093495935, "max_line_length": 109, "alphanum_fraction": 0.5836708246, "num_tokens": 2125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7590433424905187}}
{"text": "module MyInterpolations\nexport my_lin_interp\nfunction my_lin_interp(grid,vals)\n    function func(x::Real)\n        if x <= grid[1]\n            return (vals[2] - vals[1])/(grid[2] - grid[1])*(x - grid[1]) + vals[1]\n        elseif x >= grid[end]\n            return (vals[end] - vals[end-1])/(grid[end] - grid[end-1])*(x - grid[end]) + vals[end]\n        else\n            index = searchsortedlast(grid,x)\n            return (vals[index+1] - vals[index])/(grid[index+1] - grid[index])*(x - grid[index]) + vals[index]\n        end\n    end\nend\nend\n", "meta": {"hexsha": "a8f2639a4f50a340eccbe34a256e847665af3540", "size": 539, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MyInterpolations.jl", "max_stars_repo_name": "R-Tsushima/MyInterpolation.jl", "max_stars_repo_head_hexsha": "b13ff178cce5beba4083f27c66f2f0f3bafd61c7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MyInterpolations.jl", "max_issues_repo_name": "R-Tsushima/MyInterpolation.jl", "max_issues_repo_head_hexsha": "b13ff178cce5beba4083f27c66f2f0f3bafd61c7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-05-22T01:35:19.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-07T10:04:34.000Z", "max_forks_repo_path": "src/MyInterpolations.jl", "max_forks_repo_name": "R-Tsushima/MyInterpolation.jl", "max_forks_repo_head_hexsha": "b13ff178cce5beba4083f27c66f2f0f3bafd61c7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6875, "max_line_length": 110, "alphanum_fraction": 0.560296846, "num_tokens": 161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9539660936744719, "lm_q2_score": 0.7956581097540518, "lm_q1q2_score": 0.7590308588624871}}
{"text": "using sparsePolyChaos\nusing PolyChaos\n\n###\n### Multivariate sparse PCE\n###\nmaxDeg = 10\ninteractions = 3\n\n\nmodel(x,y) = (x^4 - 6 * x^2  + 3) + (x^2 - 1) * (y^2 - 1) + (y^3 - 3 * y) # He_4(x) + He_2(x) * He_2(y) + He_3(y)\n# model(x,y) = (x^2 - 1) * (y^2 - 1) # He2(x) * He2(y)\n# model(x,y) = (x^2 - 1) # He2(x)\n\n\n### Setup and compute PCE coefficients of x ###\nk = 2\nop = GaussOrthoPoly(maxDeg)\nmop = MultiOrthoPoly([op for i in 1:k], maxDeg)\nL = dim(mop)\n\npce, Ap, p, R², Q² = sparsePCE(mop, model; pMax = maxDeg, jMax = interactions)\n\nprintln(\"Basis polynomials: \", Ap)\nprintln(\"PCE coefficients: \", pce)\nprintln(\"Max degree:: \", p)\nprintln(\"R² error: \", R²)\nprintln(\"Q² error: \", Q²)", "meta": {"hexsha": "9727a89fe31a89712622466a3e5f9f895bab0d56", "size": 684, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Sparse-Multivariate.jl", "max_stars_repo_name": "adriangrupp/sparsePolyChaos", "max_stars_repo_head_hexsha": "d35da2584bddd315db30b261ce7433343d9efd58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Sparse-Multivariate.jl", "max_issues_repo_name": "adriangrupp/sparsePolyChaos", "max_issues_repo_head_hexsha": "d35da2584bddd315db30b261ce7433343d9efd58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Sparse-Multivariate.jl", "max_forks_repo_name": "adriangrupp/sparsePolyChaos", "max_forks_repo_head_hexsha": "d35da2584bddd315db30b261ce7433343d9efd58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4285714286, "max_line_length": 113, "alphanum_fraction": 0.5891812865, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7590308573640759}}
{"text": "#############################################################################\n# JuMP\n# An algebraic modelling langauge for Julia\n# See http://github.com/JuliaOpt/JuMP.jl\n#############################################################################\n# corr_sdp.jl\n#\n# Given three random variables A,B,C and given bounds on two of the three\n# correlation coefficients:\n# -0.2 <= ρ_AB <= -0.1\n#  0.4 <= ρ_BC <=  0.5\n# We can use the following property of the correlations:\n# [  1    ρ_AB  ρ_AC ]\n# [ ρ_AB   1    ρ_BC ]  ≽ 0\n# [ ρ_AC  ρ_BC   1   ]\n# To determine bounds on ρ_AC by solving a SDP\n#############################################################################\n\nusing JuMP\n\nm = Model()\n\n@variable(m, X[1:3,1:3], SDP)\n\n# Diagonal is 1s\n@constraint(m, X[1,1] == 1)\n@constraint(m, X[2,2] == 1)\n@constraint(m, X[3,3] == 1)\n\n# Bounds on the known correlations\n@constraint(m, X[1,2] >= -0.2)\n@constraint(m, X[1,2] <= -0.1)\n@constraint(m, X[2,3] >=  0.4)\n@constraint(m, X[2,3] <=  0.5)\n\n# Find upper bound\n@objective(m, Max, X[1,3])\nsolve(m)\nprintln(\"Maximum value is \", getvalue(X)[1,3])\n@assert +0.8719 <= getvalue(X)[1,3] <= +0.8720\n\n# Find lower bound\n@objective(m, Min, X[1,3])\nsolve(m)\nprintln(\"Minimum value is \", getvalue(X)[1,3])\n@assert -0.9779 >= getvalue(X)[1,3] >= -0.9799\n", "meta": {"hexsha": "29a69d6a64db57ed23f086ca41461fd2f1e94ee7", "size": 1286, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "public/.julia/v0.5/JuMP/examples/corr_sdp.jl", "max_stars_repo_name": "Giarcr0b/MVO_Tool", "max_stars_repo_head_hexsha": "8f3348b8b56968febca8307acea3ebe1817fccae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-12T03:24:25.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-12T03:24:25.000Z", "max_issues_repo_path": "public/.julia/v0.5/JuMP/examples/corr_sdp.jl", "max_issues_repo_name": "Giarcr0b/MVO_Tool", "max_issues_repo_head_hexsha": "8f3348b8b56968febca8307acea3ebe1817fccae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "public/.julia/v0.5/JuMP/examples/corr_sdp.jl", "max_forks_repo_name": "Giarcr0b/MVO_Tool", "max_forks_repo_head_hexsha": "8f3348b8b56968febca8307acea3ebe1817fccae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3617021277, "max_line_length": 77, "alphanum_fraction": 0.5101088647, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100817, "lm_q2_score": 0.8031737987125613, "lm_q1q2_score": 0.7589949873877905}}
{"text": "module moo_functions\n\nfunction quickavg(xs::Vector{Float64}; first::Int64 = 1, last::Int64 = length(xs))::Float64\n    out = 0.0\n    for k in first:last\n        out += xs[k]\n    end\n    return out/(last - first + 1)\nend\n\nfunction zdt1(x::Vector{Float64})::Tuple{Float64, Float64}\n    g  = 1.0 + 9.0*quickavg(x, first = 2)\n    f1 = x[1]\n    f2 = g * (1.0 - sqrt(f1/g))\n    return (f1, f2)\nend\n\nfunction zdt2(x::Vector{Float64})::Tuple{Float64, Float64}\n    g  = 1.0 + 9.0*quickavg(x, first = 2)\n    f1 = x[1]\n    f2 = g * (1.0 - (f1/g)^2)\n    return (f1, f2)\nend\n\nfunction zdt3(x::Vector{Float64})::Tuple{Float64, Float64}\n    g  = 1.0 + 9.0*quickavg(x, first = 2)\n    f1 = x[1]\n    f2 = g * (1.0 - sqrt(f1/g) - f1/g * sin(10*pi*f1))\n    return (f1, f2)\nend\n\nfunction zdt4(x::Vector{Float64})::Tuple{Float64, Float64}\n    g  = 1.0 + 10*(length(x)-1)\n    for k in 2:length(x)\n        g += x[k]^2 - 10*cos(4*pi*x[k])\n    end\n    f1 = x[1]\n    f2 = g * (1.0 - sqrt(f1/g))\n    return (f1, f2)\nend\n\nfunction zdt6(x::Vector{Float64})::Tuple{Float64, Float64}\n    g  = 1.0 + 9.0*quickavg(x, first = 1)^0.25\n    f1 = 1.0 - exp(-4.0*x[1])*sin(6*pi*x[1])^6\n    f2 = g*(1.0 - (f1/g)^2)\n    return (f1, f2)\nend\n\nfunction zdt()\n    return Dict{Int8, Function}(\n        1 => zdt1,\n        2 => zdt2, \n        3 => zdt3, \n        4 => zdt4,\n        6 => zdt6\n    )\nend\n\nfunction opt_hvs()\n    return Dict{Int8, Float64}(\n        1 => 120.0 + 2/3,\n        2 => 120.0 + 1/3,\n        3 => 128.77811613069076060,\n        4 => 120.0 + 2/3,\n        6 => 117.51857519692037009,\n    )\nend\n\nend", "meta": {"hexsha": "fa5469c3b1e7bb228d49df3e088b0aecb2f58ccd", "size": 1568, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/moo_functions.jl", "max_stars_repo_name": "OndrejKincl/evaTeaching-python", "max_stars_repo_head_hexsha": "76e33e7928bfd3c1e336ea3d3f3a9f6487c7bdfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/moo_functions.jl", "max_issues_repo_name": "OndrejKincl/evaTeaching-python", "max_issues_repo_head_hexsha": "76e33e7928bfd3c1e336ea3d3f3a9f6487c7bdfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/moo_functions.jl", "max_forks_repo_name": "OndrejKincl/evaTeaching-python", "max_forks_repo_head_hexsha": "76e33e7928bfd3c1e336ea3d3f3a9f6487c7bdfd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7246376812, "max_line_length": 91, "alphanum_fraction": 0.5235969388, "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538935, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7589949871929119}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.5\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ c930a0fa-4ef8-4963-b4b2-0d576ecdde7e\nusing Pkg, DrWatson\n\n# ╔═╡ 919b41e5-7e43-45e0-8676-373b77ac6208\nbegin\n\t@quickactivate \"NumericalMethodsforEngineers\"\n\tusing Roots, Plots\n\tusing Symbolics, SymbolicUtils, Latexify, LaTeXStrings, ModelingToolkit\n\tusing NumericalMethodsforEngineers, Test\nend\n\n# ╔═╡ c34bdc36-5013-4096-9cb2-581ad9e02239\nmd\" ## f-03-01.jl\"\n\n# ╔═╡ 0b1514c5-eded-4f60-ac31-6f27a4deff1d\nbegin\n\t@variables f x\n\tf = exp(x) - x^4\n\tL(f)\nend\n\n# ╔═╡ 7c4288f0-38d9-4c39-b6b1-789aba5465b6\nf_j = build_function(f, [x], expression=Val{false});\n\n# ╔═╡ c7c87623-9c41-4a68-8673-47a71c67f083\nbegin\n\ty = -10.0:0.1:10.0\n\tplot(y, f_j.(y), leg=false)\n\thline!([0.0])\n\tvline!([fzeros(f_j, [-1, 2])])\nend\n\n# ╔═╡ 2708dfb1-09dd-458c-8b5f-2e2ec3d800c4\nbegin\n\tD = Differential(x)\n\tfp_s = expand_derivatives(D(f))\n\tfp_j = build_function(fp_s, [x], expression=Val{false})\n\tL(fp_s)\nend\n\n# ╔═╡ 1dd78a44-b910-4bb2-8af0-9a1ab3ee4a51\nRoots.newton(f_j, fp_j, 8)        # 8.6131694564414\n\n# ╔═╡ 8054c3fd-3ecb-4c2a-b606-7fd518d750a3\nbegin\n\tfpp_s = expand_derivatives(D(D(f)))\n\tfpp_j = build_function(fpp_s, [x], expression=Val{false})\n\tL(fpp_s)\nend\n\n# ╔═╡ 7e2f4bd6-4f9a-4a72-8e70-e5fc56f806ee\nhalley(f_j, fp_j, fpp_j, 8)\n\n# ╔═╡ 3e022154-6933-4ba7-8cf9-2d48d3cbb27f\nsecant_method(f_j, [8, 8.5])\n\n# ╔═╡ 26cd9127-ae9e-4f09-97e4-d10f514e2164\nmd\" ## End of f-03-01.jl\"\n\n# ╔═╡ Cell order:\n# ╟─c34bdc36-5013-4096-9cb2-581ad9e02239\n# ╠═c930a0fa-4ef8-4963-b4b2-0d576ecdde7e\n# ╠═919b41e5-7e43-45e0-8676-373b77ac6208\n# ╠═0b1514c5-eded-4f60-ac31-6f27a4deff1d\n# ╠═7c4288f0-38d9-4c39-b6b1-789aba5465b6\n# ╠═c7c87623-9c41-4a68-8673-47a71c67f083\n# ╠═2708dfb1-09dd-458c-8b5f-2e2ec3d800c4\n# ╠═1dd78a44-b910-4bb2-8af0-9a1ab3ee4a51\n# ╠═8054c3fd-3ecb-4c2a-b606-7fd518d750a3\n# ╠═7e2f4bd6-4f9a-4a72-8e70-e5fc56f806ee\n# ╠═3e022154-6933-4ba7-8cf9-2d48d3cbb27f\n# ╟─26cd9127-ae9e-4f09-97e4-d10f514e2164\n", "meta": {"hexsha": "19a75a7e989c2445507acddf0e58ebc77383c905", "size": 1937, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/f-03-01.jl", "max_stars_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_stars_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "notebooks/03/f-03-01.jl", "max_issues_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "notebooks/03/f-03-01.jl", "max_forks_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 24.5189873418, "max_line_length": 72, "alphanum_fraction": 0.7237996902, "num_tokens": 1075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587964389113, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7589224755334198}}
{"text": "module UnionFindAlgo \n\nexport UnionFind, union!, find, isconnected\n\n\"\"\"\nUnion find with the *Weighted quick union* (WQU)\nalgorithm. \n\n- `id`: the parent node's id\n- `sz`: size of the tree\n\"\"\"\nmutable struct UnionFind\n    id::Vector{Int}\n    sz::Vector{Int}\n    ncomp::Int\n    UnionFind(n::Int) = new(collect(1:n), fill(1, n), n) \nend\n\nfunction UnionFind(data::NamedTuple)\n    uf = UnionFind(data.nv)\n    edges = data.edges\n    for (p, q) in edges\n        union!(uf, p, q)\n    end\n    uf\nend \n\nfunction union!(uf, p, q) \n    i = find(uf, p)\n    j = find(uf, q)\n    i == j && return\n    # weighted quick-union: always connect the root \n    # of smaller tree to the root of the larger tree \n    if (uf.sz[i] < uf.sz[j])\n        uf.id[i] = j\n        uf.sz[j] += uf.sz[i]\n    else\n        uf.id[j] = i\n        uf.sz[i] += uf.sz[j]\n    end\n    uf.ncomp -= 1\n    return nothing\nend\n\n\"\"\"\n    find(uf, p)\n\nFind the root of p. The component in WQUPC is defined by\nthe root of each node. \n\nIn theory path compression can help further flatten\nthe tree. There are two ways to conduct path compression: \n\n1. find the root for `p` and then assign all nodes on the path \n   from `p` to root to the newly found root. This requires running \n   the `find` twice.\n2. Directly change parent to grandparent, this will halve the \n   height in the subtree. In code: `uf.id[i] = uf.id[uf.id[i]]`\n\nIn practice, the performance gain from path compression is not \nsignificant. On `largeUF.txt`(V=1e6, E=2e6) approach (2) gives\nabout 1% improvement. The difference might be larger for larger\ndataset.\n\"\"\"\nfunction find(uf, p) \n    i = uf.id[p] \n    while uf.id[i] != i\n        # path compression: set parent to grandparent\n        # this trick halves the subtree each time\n        uf.id[i] = uf.id[uf.id[i]]\n        # go to the parent node\n        i = uf.id[i]\n    end\n    i\nend\n\nisconnected(uf, p, q) = find(uf, p) == find(uf, q)\n\nend", "meta": {"hexsha": "56ddbb718ac05650e48219035232ff07fe5a9aea", "size": 1906, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unionfind.jl", "max_stars_repo_name": "Jetafull/AlgorithmsInJulia", "max_stars_repo_head_hexsha": "6e4d8a58e063861967de9260f15d182eb7d35ada", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-21T03:27:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T03:27:23.000Z", "max_issues_repo_path": "src/unionfind.jl", "max_issues_repo_name": "Jetafull/algorithms-in-julia", "max_issues_repo_head_hexsha": "6e4d8a58e063861967de9260f15d182eb7d35ada", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/unionfind.jl", "max_forks_repo_name": "Jetafull/algorithms-in-julia", "max_forks_repo_head_hexsha": "6e4d8a58e063861967de9260f15d182eb7d35ada", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1265822785, "max_line_length": 67, "alphanum_fraction": 0.6238195173, "num_tokens": 580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381606, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7589127754397073}}
{"text": "module NewtonsMethod\n\nusing ForwardDiff, LinearAlgebra\n\nexport newtonroot\n\nfunction iterativesolver(f, x₀, checkconvergence, updatex)\n    xold = x₀.*10\n    fold = 10*f(x₀)\n    xnew = x₀\n    fnew = f(xnew)\n    iter = 1\n    while !checkconvergence(xold, xnew, fold, fnew, iter)\n        xold = xnew\n        xnew = updatex(f, xold)\n        fold = fnew\n        fnew = f(xnew)\n        iter += 1\n    end\n    return(value = xnew, iter=iter)\nend\n\nfunction newtonroot(f, f′; x₀, tol=1e-7, maxiter=1000)\n    res = iterativesolver(f,\n                          x₀,\n                          (xold, xnew, fold, fnew, iter) -> norm(xnew - xold) < 1e-4 || iter > maxiter,\n                          (f, x) -> x - f(x) / f′(x))\n    if res.iter <= maxiter\n        return res\n    else\n        return (value = nothing, iter=res.iter)\n    end\nend\n\nfunction newtonroot(f; x₀, tol=1e-7, maxiter=1000)\n    return newtonroot(f, x -> ForwardDiff.derivative(f, x); x₀, tol, maxiter)\nend\n\nend\n", "meta": {"hexsha": "8c73f48df1ba4d1e2c4fdc53813649f56f4bd6ec", "size": 964, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NewtonsMethod.jl", "max_stars_repo_name": "saattvic/NewtonsMehtod.jl", "max_stars_repo_head_hexsha": "f9b82f54c00b9ed13cf03ddbc0bef9006a2924a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NewtonsMethod.jl", "max_issues_repo_name": "saattvic/NewtonsMehtod.jl", "max_issues_repo_head_hexsha": "f9b82f54c00b9ed13cf03ddbc0bef9006a2924a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NewtonsMethod.jl", "max_forks_repo_name": "saattvic/NewtonsMehtod.jl", "max_forks_repo_head_hexsha": "f9b82f54c00b9ed13cf03ddbc0bef9006a2924a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1, "max_line_length": 103, "alphanum_fraction": 0.5601659751, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7589127728885897}}
{"text": "\"\"\"\n    center(A)\n\nCenters columns of a 2d array\n\n# Arguments\n\n- A = 2d array of floats\n\n# Value\n\n2d array of floats\n\n\"\"\"\nfunction center(A::AbstractArray{Float64,2})\n    \n    # Row means of A\n    m = mean(A, dims=1)\n    # Initialize centered matrix\n    W = zeros(size(A))\n    \n    # Subtract column means\n    W .= A .- m\n    \n    return W\nend\n\n\n\"\"\"\n    cov_est(resid)\n\nEstimates error variance and its variance/covariance\n\n# Arguments\n\n- resid = 2d array of floats consisting of the residuals\n\n# Value\n\nTuple\n- est: 2d array of floats; estimate\n- varest: 2d array of floats; variance/covariance estimate\n\n2d array of floats\n\n\"\"\"\nfunction cov_est(resid::AbstractArray{Float64,2})\n    \n    # Dimensions of residuals\n    n = size(resid, 1)\n    p = size(resid, 2)\n    \n    # Centered residual matrix\n    W = center(resid)\n    \n    # Allocate space for the estimates and their variances\n    est = zeros(p, p)\n    varEst = zeros(p, p)\n    \n    # Loop through the possible entries\n    for i = 1:p\n        for j = i:p\n            # Multiply the ith and jth columns\n            ww = W[:,i].*W[:,j]\n            \n            if i==j # Diagonal elements\n                est[i,i] = (n/(n-1)) * mean(ww)\n                varEst[i,i] = (n/(n-1)^2) * var(ww)\n            else # Non-diagonal elements\n                est[i,j] = est[j,i] = (n/(n-1)) * mean(ww)\n                varEst[i,j] = varEst[j,i] = (n/(n-1)^2) * var(ww)\n            end\n                \n        end\n    end\n    \n    return est, varEst\nend\n\n\n\"\"\"\n    shrink_sigma(resid, targetType)\n\nEstimates variance of errors and the shrinkage coefficient\n\n# Arguments\n\n- resid = 2d array of floats consisting of the residuals\n- targetType = string indicating the target type toward which to shrink the \n  variance. Acceptable inputs are \"A\", \"B\", \"C\", and \"D\". \n    - \"A\": Target is identity matrix\n    - \"B\": Target is diagonal matrix with constant diagonal\n    - \"C\": Target is has same diagonal element, and same off-diagonal element\n    - \"D\": Target is diagonal matrix with unequal entries\n\n# Value\n\nTuple\n- sigma: 2d array of floats; shrunk estimated variance of errors\n- lambda: floating scalar; estimated shrinkage coefficient \n  (0 = no shrinkage, 1 = complete shrinkage)\n\n# Reference\n\nLedoit, O., & Wolf, M. (2003). Improved estimation of the covariance matrix \n    of stock returns with an application to portfolio selection. Journal of \n    empirical finance, 10(5), 603-621.\n\n\"\"\"\nfunction shrink_sigma(resid::AbstractArray{Float64,2}, targetType::String)\n    \n    # Dimensions of resid\n    (n, p) = size(resid)\n    \n    # Estimates and the variance of the error variance\n    (est, varEst) = cov_est(resid)\n    \n    if targetType==\"A\"  # Shrink to identity\n        # Create identity target matrix\n        T = Matrix{Float64}(I, p, p)\n        # Estimate optimal lambda\n        lambda = sum(varEst) / sum((est-T).^2)\n        \n    elseif targetType==\"B\"  # Shrink to common variance\n        # Create target matrix\n        T = Matrix{Float64}(I, p, p) * mean(diag(est))\n        # Estimate optimal lambda\n        lambda = sum(varEst) / sum((est-T).^2)\n        \n    elseif targetType==\"C\"  # Shrink to equal variance and covariance\n        v = mean(diag(est))\n        c = (sum(est) - sum(diag(est))) / (n*(n-1))\n        # Create target matrix\n        T = fill(c,(p,p)) + (v-c) * Matrix{Float64}(I, p, p)\n        # Estimate optimal lambda\n        lambda = sum(varEst) / sum((est-T).^2)\n        \n    elseif targetType==\"D\"  # Shrink to zero correlation\n        v = diag(est)\n        # Create target matrix\n        T = diagm(0 => v)\n        # Estimate optimal lambda\n        lambda = (sum(varEst) - sum(diag(varEst))) /\n                 (sum(est.^2) - sum(diag(est).^2))\n    end\n        \n    return lambda*T + (1-lambda)*est, lambda\nend\n", "meta": {"hexsha": "6c4a0849bd5ad4eea4ea75916f768a7daf83318b", "size": 3781, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/shrink_sigma.jl", "max_stars_repo_name": "janewliang/matrixLM.jl", "max_stars_repo_head_hexsha": "43f06210f9849d99002345be29c82909bc9830c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-17T13:00:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T13:00:07.000Z", "max_issues_repo_path": "src/shrink_sigma.jl", "max_issues_repo_name": "janewliang/matrixLM.jl", "max_issues_repo_head_hexsha": "43f06210f9849d99002345be29c82909bc9830c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-22T00:11:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T00:11:58.000Z", "max_forks_repo_path": "src/shrink_sigma.jl", "max_forks_repo_name": "janewliang/matrixLM.jl", "max_forks_repo_head_hexsha": "43f06210f9849d99002345be29c82909bc9830c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3758389262, "max_line_length": 77, "alphanum_fraction": 0.5916424226, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7589127722285601}}
{"text": "\"\"\"\nComputes mean resultant vector length for circular data.\n\n\t1. α: sample of angles in radians\n    - w: number of incidences in case of binned angle data\n    - d: spacing of bin centers for binned data, used to correct for bias in estimation of r, in radians\n    - dims: compute along this dimension(default=1)\n\n\treturn: mean resultant length\n\"\"\"\nfunction circ_r(α; w = ones(size(α)), d = 0, dims = 1)\n  # compute weighted sum of cos and sin of angles\n  r = sum(w .* cis.(α); dims)\n\n  # obtain length\n  r = abs.(r) ./ sum(w; dims)\n\n  # for data with known spacing, apply correction factor to correct for bias in the estimation of r (see Zar, p. 601, equ. 26.16)\n  if d != 0\n    c = d / 2 / sin(d / 2)\n    r *= c\n  end\n  length(r) == 1 ? r[1] : r\nend\n\n\"\"\"\nComputes the mean direction for circular data.\n\n\t1. α: sample of angles in radians\n    - w: weightings in case of binned angle data\n    - dims: compute along this dimension(default=1)\n\n\treturn:\n\t- μ: mean direction\n\t- ul: upper 95% confidence limit\n\t- ll: lower 95% confidence limit\n\"\"\"\nfunction circ_mean(α; w = ones(size(α)), dims = 1)\n  # compute weighted sum of cos and sin of angles\n  r = sum(w .* cis.(α); dims)\n\n  # obtain mean by\n  μ = angle.(r)\n  μ = length(μ) == 1 ? μ[1] : μ\n\n  # confidence limits\n  t = circ_confmean(α; xi = 0.05, w, d = 0, dims)\n  ul = μ .+ t\n  ll = μ .- t\n\n  return (; μ, ul, ll)\nend\n\n\"\"\"\nTransforms p-axial data to a common scale.\n\n  1. α: sample of angles in radians\n  2. p: number of modes(default=1)\n\n  return: transformed data\n\"\"\"\ncirc_axial(α, p = 1) = mod2pi.(α * p)\n\n\"\"\"\nComputes the median direction for circular data.\n\n  1. α: sample of angles in radians\n\n  return: median direction\n\"\"\"\nfunction circ_median(α::AbstractVector)\n  α = mod2pi.(α)\n  n = length(α)\n\n  dd = circ_dist2(α)\n  m1 = dropdims(count(>=(0), dd; dims = 1), dims = 1)\n  m2 = dropdims(count(<=(0), dd; dims = 1), dims = 1)\n\n  dm = abs.(m1 .- m2)\n  m = minimum(dm)\n  md = circ_mean(α[dm.==m]).μ\n  αμ = circ_mean(α).μ\n  if abs(circ_dist(αμ, md)) > abs(circ_dist(αμ, md + π))\n    md = mod2pi(md + π)\n  end\n  return md\nend\n\n\"\"\"\nComputes circular standard deviation for circular data (equ. 26.20, Zar).\n\n\t1. α: sample of angles in radians\n   - w: weightings in case of binned angle data\n   - d: spacing of bin centers for binned data, used to correct for bias in estimation of r, in radians\n   - dims: compute along this dimension(default=1)\n\n\treturn:\n  - s: angular deviation\n  - s0: circular standard deviation\n\"\"\"\nfunction circ_std(α; w = ones(size(α)), d = 0, dims = 1)\n  # compute mean resultant vector length\n  r = circ_r(α; w, d, dims)\n\n  s = sqrt.(2 .* (1 .- r))      # 26.20\n  s0 = sqrt.(-2 .* log.(r))   # 26.21\n  return (; s, s0)\nend\n\n\"\"\"\nComputes circular variance for circular data (equ. 26.17/18, Zar).\n\n\t1. α: sample of angles in radians\n  - w: number of incidences in case of binned angle data\n  - d: spacing of bin centers for binned data, used to correct for bias in estimation of r, in radians\n\t- dims: compute along this dimension(default=1)\n\n\treturn:\n\t- S: circular variance 1-r\n\t- s: angular variance 2(1-r)\n\"\"\"\nfunction circ_var(α; w = ones(size(α)), d = 0, dims = 1)\n  # compute mean resultant vector length\n  r = circ_r(α; w, d, dims)\n\n  # apply transformation to var\n  S = 1 .- r\n  s = 2 * S\n  return (; S, s)\nend\n\n\n\"\"\"\nComputes the confidence limits on the mean for circular data.\n\n\t1. α: sample of angles in radians\n   - xi: (1-xi) confidence limits are computed, default=0.05\n   - w: number of incidences in case of binned angle data\n   - d: spacing of bin centers for binned data, used to correct for bias in estimation of r, in radians\n   - dims: compute along this dimension(default=1)\n\n\treturn: mean ± d yields upper/lower (1-xi)% confidence limit\n\"\"\"\nfunction circ_confmean(α; xi = 0.05, w = ones(size(α)), d = 0, dims = 1)\n  # compute ingredients for conf. lim.\n  r = circ_r(α; w, d, dims)\n  n = sum(w; dims)\n  R = n .* r\n  c2 = quantile(Chisq(1), 1 - xi)\n\n  # check for resultant vector length and select appropriate formula\n  t = zeros(size(r))\n\n  for i = 1:length(r)\n    if r[i] < 0.9 && r[i] > sqrt(c2 / 2 / n[i])\n      t[i] = sqrt((2 * n[i] * (2 * R[i]^2 - n[i] * c2)) / (4 * n[i] - c2))  # equ. 26.24\n    elseif r[i] >= 0.9\n      t[i] = sqrt(n[i]^2 - (n[i]^2 - R[i]^2) * exp(c2 / n[i]))      # equ. 26.25\n    else\n      t[i] = NaN\n      @warn \"Requirements for confidence levels not met.\"\n    end\n  end\n\n  # apply final transform\n  t = acos.(clamp.(t ./ R, -1, 1))\n  t = length(t) == 1 ? t[1] : t\nend\n\n\n\"\"\"\nCalculates a measure of angular skewness.\n\n\t1. α: sample of angles in radians\n    - w: weightings in case of binned angle data\n    - dims: compute along this dimension(default=1)\n\n\treturn:\n\t- b: skewness (from Pewsey)\n\t- b0: alternative skewness measure (from Fisher)\n\"\"\"\nfunction circ_skewness(α; w = ones(size(α)), dims = 1)\n  # compute neccessary values\n  R = circ_r(α; w, d = 0, dims)\n  θ = circ_mean(α; w, dims).μ\n  _, ρ₂, μ₂ = circ_moment(α; w, p = 2, cent = false, dims)\n\n  # compute skewness\n  if ndims(θ) > 0\n    θ₂ = repeat(θ, outer = Int.(size(α) ./ size(θ)))\n  else\n    θ₂ = θ\n  end\n  b = sum(w .* sin.(2 * circ_dist(α, θ₂)); dims) ./ sum(w; dims)\n  b0 = ρ₂ .* sin.(circ_dist(μ₂, 2θ)) ./ (1 .- R) .^ (3 / 2)   # (formula 2.29)\n  b = length(b) == 1 ? b[1] : b\n  b0 = length(b0) == 1 ? b0[1] : b0\n  return (; b, b0)\nend\n\n\n\"\"\"\nCalculates a measure of angular kurtosis.\n\n  1. α: sample of angles in radians\n    - w: weightings in case of binned angle data\n    - dims: compute along this dimension(default=1)\n\n  return:\n  - k: kurtosis (from Pewsey)\n  - k0: kurtosis (from Fisher)\n\"\"\"\nfunction circ_kurtosis(α; w = ones(size(α)), dims = 1)\n  # compute mean direction\n  R = circ_r(α; w, d = 0, dims)\n  θ = circ_mean(α; w, dims).μ\n  _, ρ₂, _ = circ_moment(α; w, p = 2, cent = true, dims)\n  _, _, μ₂ = circ_moment(α; w, p = 2, cent = false, dims)\n\n  # compute skewness\n  if ndims(θ) > 0\n    θ₂ = repeat(θ, outer = Int.(size(α) ./ size(θ)))\n  else\n    θ₂ = θ\n  end\n  k = sum(w .* cos.(2 * circ_dist(α, θ₂)); dims) ./ sum(w; dims)\n  k0 = (ρ₂ .* cos.(circ_dist(μ₂, 2θ)) .- R .^ 4) ./ (1 .- R) .^ 2    # (formula 2.30)\n  k = length(k) == 1 ? k[1] : k\n  k0 = length(k0) == 1 ? k0[1] : k0\n  return (; k, k0)\nend\n\n\n\"\"\"\nCalculates the complex p-th centred or non-centred moment of the angular data in angle.\n\n  1. α: sample of angles in radians\n   - w: number of incidences in case of binned angle data\n   - p: p-th moment to be computed, default=1\n   - cent: if true, central moments are computed, default = false\n   - dims: compute along this dimension(default=1)\n\n  return:\n  - mp: complex p-th moment\n  - ρp: magnitude of the p-th moment\n  - μp: angle of th p-th moment\n\"\"\"\nfunction circ_moment(α; w = ones(size(α)), p = 1, cent = false, dims = 1)\n  if cent\n    θ = circ_mean(α; w, dims).μ\n    if ndims(θ) > 0\n      v = Int.(size(α) ./ size(θ))\n      θ = repeat(θ, outer = v)\n    end\n    α = circ_dist(α, θ)\n  end\n\n  n = size(α, dims)\n  c̄ = sum(cos.(p * α) .* w; dims) / n\n  s̄ = sum(sin.(p * α) .* w; dims) / n\n  mp = c̄ .+ im * s̄\n  ρp = abs.(mp)\n  μp = angle.(mp)\n  mp = length(mp) == 1 ? mp[1] : mp\n  ρp = length(ρp) == 1 ? ρp[1] : ρp\n  μp = length(μp) == 1 ? μp[1] : μp\n  return (; mp, ρp, μp)\nend\n\n\n\n\"\"\"\nPairwise difference α-β around the circle computed efficiently.\n\n  1. α: sample of linear random variable\n  2. β: sample of linear random variable or one single angle\n\n  return: matrix with differences\n\"\"\"\ncirc_dist(α, β) = angle.(cis.(α) ./ cis.(β))\n\n\n\"\"\"\nAll pairwise difference α-β around the circle computed efficiently.\n\n  1. α: sample of linear random variable\n  2. β: sample of linear random variable\n\n  return: matrix with pairwise differences\n\"\"\"\ncirc_dist2(α) = circ_dist2(α, α)\ncirc_dist2(α, β) = angle.(cis.(α) ./ cis.(β'))\n\n\n\"\"\"\nComputes descriptive statistics for circular data.\n\n  1. α: sample of angles in radians\n    - w: weightings in case of binned angle data\n    - d: spacing of bin centers for binned data, used to correct for bias in estimation of r, in radians\n\n  return: descriptive statistics\n\"\"\"\nfunction circ_stats(α::AbstractVector; w = ones(size(α)), d = 0)\n  # mean\n  mean = circ_mean(α; w).μ\n  # median\n  median = circ_median(α)\n  # variance\n  var = circ_var(α; w, d)\n  # standard deviation\n  std, std0 = circ_std(α; w, d)\n  # skewness\n  skewness, skewness0 = circ_skewness(α; w)\n  # kurtosis\n  kurtosis, kurtosis0 = circ_kurtosis(α; w)\n\n  return (; mean, median, var,std,std0, skewness,skewness0,kurtosis,kurtosis0)\nend\n\n\n\n\"\"\"\nComputes Rayleigh test for non-uniformity of circular data.\n\n\tH0: the population is uniformly distributed around the circle\n  HA: the populatoin is not distributed uniformly around the circle\n\tAssumption: the distribution has maximally one mode and the data is\n\t\t\t\t\t\t\tsampled from a von Mises distribution!\n\n\t1. α: sample of angles in radians\n    - w: number of incidences in case of binned angle data\n    - d: spacing of bin centers for binned data, used to correct for bias in estimation of r, in radians\n\n\treturn:\n\t- p: p-value of Rayleigh's test\n\t- z: value of the z-statistic\n\"\"\"\nfunction circ_rtest(α; w = ones(size(α)), d = 0)\n  r = circ_r(α; w, d)\n  n = sum(w)\n\n  # compute Rayleigh's R (equ. 27.1)\n  R = n * r\n\n  # compute Rayleigh's z (equ. 27.2)\n  z = R^2 / n\n\n  # compute p value using approxation in Zar, p. 617\n  p = exp(sqrt(1 + 4n + 4(n^2 - R^2)) - (1 + 2n))\n  return (; p, z)\nend\n\n\n\"\"\"\nComputes Omnibus or Hodges-Ajne test for non-uniformity of circular data.\n\n\tH0: the population is uniformly distributed around the circle\n\tHA: the population is not distributed uniformly around the circle\n\tAlternative to the Rayleigh and Rao's test. Works well for unimodal,\n\tbimodal or multimodal data. If requirements of the Rayleigh test are met, the latter is more powerful.\n\n\t1. α: sample of angles in radians\n    - sz: step size for evaluating distribution, default 1 degree\n    - w: number of incidences in case of binned angle data\n\n\treturn:\n\t- p: p-value\n\t- m: minimum number of samples falling in one half of the circle\n\"\"\"\nfunction circ_otest(α; sz = deg2rad(1), w = ones(size(α)))\n  α = mod2pi.(α)\n  n = sum(w)\n  dg = 0:sz:π\n\n  m1 = zeros(size(dg))\n  m2 = zeros(size(dg))\n  for i = 1:length(dg)\n    m1[i] = sum((α .> dg[i]) .& (α .< π + dg[i]) .* w)\n    m2[i] = n - m1[i]\n  end\n  m = min(minimum(m1), minimum(m2))\n\n  if n > 50\n    # approximation by Ajne (1968)\n    A = π * sqrt(n) / 2 / (n - 2m)\n    p = sqrt(2π) / A * exp(-π^2 / 8 / A^2)\n  else\n    # exact formula by Hodges (1955)\n    # p = 2^(1-n) * (n-2m) * nchoosek(n,m)  # revised below for numerical stability\n    p = exp((1 - n) * log(2) + log(n - 2m) + loggamma(n + 1) - loggamma(m + 1) - loggamma(n - m + 1))\n  end\n  return (; p, m)\nend\n\n\"\"\"\nCalculates Rao's spacing test by comparing distances between points on a circle to those expected from a uniform distribution.\n  H0: Data is distributed uniformly around the circle.\n  H1: Data is not uniformly distributed around the circle.\n\n  Alternative to the Rayleigh test and the Omnibus test. Less powerful\n  than the Rayleigh test when the distribution is unimodal on a global scale but uniform locally.\n\n  Due to the complexity of the distributioin of the test statistic, we resort to the tables published by\n  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\n  Therefore the reported p-value is the smallest α level at which the test would still be significant.\n  If the test is not significant at the α=0.1 level, we return the critical value for α = 0.05 and p = 0.5.\n\n  1. α: sample of angles in radians\n\n  return:\n  - p: smallest p-value at which test would be significant\n  - u: computed value of the test-statistic u\n  - UC: critical value of the test statistic at sig-level\n\"\"\"\nfunction circ_raotest(α)\n  # for the purpose of the test, convert to angles\n  α = sort(rad2deg.(α))\n  n = length(α)\n\n  # compute test statistic\n  u = 0\n  λ = 360 / n\n  for j = 1:n-1\n    ti = α[j+1] - α[j]\n    u += abs(ti - λ)\n  end\n\n  tn = 360 - α[n] + α[1]\n  u = 0.5(u + abs(tn - λ))\n\n  getVal = (N, u) -> begin\n      # Table II from Russel and Levitin, 1995\n      α = [0.001, 0.01, 0.05, 0.10]\n      table = [\n        4 247.32 221.14 186.45 168.02\n        5 245.19 211.93 183.44 168.66\n        6 236.81 206.79 180.65 166.30\n        7 229.46 202.55 177.83 165.05\n        8 224.41 198.46 175.68 163.56\n        9 219.52 195.27 173.68 162.36\n        10 215.44 192.37 171.98 161.23\n        11 211.87 189.88 170.45 160.24\n        12 208.69 187.66 169.09 159.33\n        13 205.87 185.68 167.87 158.50\n        14 203.33 183.90 166.76 157.75\n        15 201.04 182.28 165.75 157.06\n        16 198.96 180.81 164.83 156.43\n        17 197.05 179.46 163.98 155.84\n        18 195.29 178.22 163.20 155.29\n        19 193.67 177.08 162.47 154.78\n        20 192.17 176.01 161.79 154.31\n        21 190.78 175.02 161.16 153.86\n        22 189.47 174.10 160.56 153.44\n        23 188.25 173.23 160.01 153.05\n        24 187.11 172.41 159.48 152.68\n        25 186.03 171.64 158.99 152.32\n        26 185.01 170.92 158.52 151.99\n        27 184.05 170.23 158.07 151.67\n        28 183.14 169.58 157.65 151.37\n        29 182.28 168.96 157.25 151.08\n        30 181.45 168.38 156.87 150.80\n        35 177.88 165.81 155.19 149.59\n        40 174.99 163.73 153.82 148.60\n        45 172.58 162.00 152.68 147.76\n        50 170.54 160.53 151.70 147.05\n        75 163.60 155.49 148.34 144.56\n        100 159.45 152.46 146.29 143.03\n        150 154.51 148.84 143.83 141.18\n        200 151.56 146.67 142.35 140.06\n        300 148.06 144.09 140.57 138.71\n        400 145.96 142.54 139.50 137.89\n        500 144.54 141.48 138.77 137.33\n        600 143.48 140.70 138.23 136.91\n        700 142.66 140.09 137.80 136.59\n        800 142.00 139.60 137.46 136.33\n        900 141.45 139.19 137.18 136.11\n        1000 140.99 138.84 136.94 135.92]\n\n      ridx = findfirst(table[:, 1] .>= N)\n      cidx = findfirst(table[ridx, 2:end] .< u)\n\n      if isnothing(cidx)\n        UC = table[ridx, end-1]\n        p = 0.5\n      else\n        UC = table[ridx, cidx+1]\n        p = α[cidx]\n      end\n      return p, UC\n    end\n\n  # get critical value from table\n  p, UC = getVal(n, u)\n\n  return (; p, u, UC)\nend\n\n\"\"\"\nComputes V test for non-uniformity of circular data with a specified mean direction.\n\n  H0: the population is uniformly distributed around the circle\n  HA: the population is not distributed uniformly around the circle but has a mean of `m`.\n\n  !!!note\n    Not rejecting H0 may mean that the population is uniformly distributed around the circle OR\n    that it has a mode but that this mode is not centered at `m`.\n\n  The V test has more power than the Rayleigh test and is preferred if there is reason to believe in a specific mean direction.\n\n  1. α: sample of angles in radians\n  - m: suspected mean direction, default=0\n  - w: number of incidences in case of binned angle data\n  - d: spacing of bin centers for binned data, used to correct for bias in estimation of r, in radians\n\n  return:\n  - p: p-value of V test\n  - v: value of the V statistic\n\"\"\"\nfunction circ_vtest(α; m = 0, w = ones(size(α)), d = 0)\n  # compute some ingredients\n  r = circ_r(α; w, d)\n  μ, = circ_mean(α; w)\n  n = sum(w)\n\n  # compute Rayleigh's R (equ. 27.1)\n  R = n * r\n\n  # compute the V statistic (equ. 27.5)\n  v = R * cos(μ - m)\n\n  # compute u (equ. 27.6)\n  u = v * sqrt(2 / n)\n\n  # compute p-value from one tailed normal approximation\n  p = 1 - cdf(Normal(), u)\n\n  return (; p, v)\nend\n\n\n\"\"\"\nTests for significance of the median.\n\n  H0: the population has median angle `md`\n  HA: the population has not median angle `md`\n\n  1. α: sample of angles in radians\n  - md: median to test, default=0\n\n  return: p-value\n\"\"\"\nfunction circ_medtest(α; md = 0)\n  n = length(α)\n\n  # compute deviations from median\n  d = circ_dist(α, md)\n\n  n1 = sum(d .< 0)\n  n2 = sum(d .> 0)\n\n  # compute p-value with binomial test\n  sum(pdf.(Binomial(n, 0.5), [0:min(n1, n2); max(n1, n2):n]))\nend\n\n\n\"\"\"\nOne-Sample test for the mean angle.\n  H0: the population has mean `m`.\n  HA: the population has not mean `m`.\n\n  !!!note: This is the equvivalent to a one-sample t-test with specified mean direction.\n\n  1. α: sample of angles in radians\n  - m: assumed mean direction, default=0\n  - w: number of incidences in case of binned angle data\n  - d: spacing of bin centers for binned data, used to correct for bias in estimation of r, in radians\n  - xi: alpha level of the test\n\n  return:\n  - h: false if H0 can not be rejected, true otherwise\n  - μ: mean\n  - ul: upper (1-xi) confidence level\n  - ll: lower (1-xi) confidence level\n\"\"\"\nfunction circ_mtest(α; xi = 0.05, m = 0, w = ones(size(α)), d = 0)\n  # compute ingredients\n  μ, = circ_mean(α; w)\n  t = circ_confmean(α; xi, w, d)\n  ul = μ + t\n  ll = μ - t\n\n  # compute test via confidence limits (example 27.3)\n  h = abs(circ_dist2(m, μ)) > t\n\n  return (; h, μ, ul, ll)\nend\n\n\n\n\"\"\"\nParametric Watson-Williams multi-sample test for equal means. Can be used as a one-way ANOVA test for circular data.\n\n  H0: the s populations have equal means\n  HA: the s populations have unequal means\n\n  !!! note\n  Use with binned data is only advisable if binning is finer than 10 deg.\n  In this case, α is assumed to correspond to bin centers.\n\n  The Watson-Williams two-sample test assumes underlying von-Mises distributrions.\n  All groups are assumed to have a common concentration parameter k.\n\n  1. α: angles in radians\n  2. idx: indicates which population the respective angle in α comes from, 1:s\n    - w: number of incidences in case of binned angle data\n\n  return:\n  - p: p-value of the Watson-Williams multi-sample test. Discard H0 if p is small.\n  - F: F statistics\n\"\"\"\nfunction circ_wwtest(α, idx; w = ones(size(α)))\n  # number of groups\n  u = unique(idx)\n  s = length(u)\n\n  # number of samples\n  n = sum(w)\n\n  # compute relevant quantitites\n  pn = zeros(s)\n  pr = zeros(s)\n  for t = 1:s\n    pidx = idx .== u[t]\n    pn[t] = sum(pidx .* w)\n    pr[t] = circ_r(α[pidx]; w = w[pidx])\n  end\n\n  r = circ_r(α; w)\n  rw = sum(pn .* pr) / n\n\n  # make sure assumptions are satisfied\n  checkAssumption =\n    (rw, n) -> begin\n      if n >= 11 && rw < 0.45\n        @warn \"Test not applicable. Average resultant vector length < 0.45.\"\n      elseif n < 11 && n >= 7 && rw < 0.5\n        @warn \"Test not applicable. Average number of samples per population 6 < x < 11 and average resultant vector length < 0.5.\"\n      elseif n >= 5 && n < 7 && rw < 0.55\n        @warn \"Test not applicable. Average number of samples per population 4 < x < 7 and average resultant vector length < 0.55.\"\n      elseif n < 5\n        @warn \"Test not applicable. Average number of samples per population < 5.\"\n      end\n    end\n  checkAssumption(rw, mean(pn))\n\n  # test statistic\n  kk = circ_kappa(rw)\n  β = 1 + 3 / (8 * kk)    # correction factor\n  A = sum(pr .* pn) - r * n\n  B = n - sum(pr .* pn)\n\n  F = β * (n - s) * A / (s - 1) / B\n  # p = 1 - fcdf(F, s - 1, n - s)\n  p = 1 - cdf(FDist(s - 1, n - s), F)\n\n  # fprintf('\\nANALYSIS OF VARIANCE TABLE (WATSON-WILLIAMS TEST)\\n\\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');\n  # fprintf('--------------------------------------------------------------------\\n');\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);\n  # fprintf('%s\\t\\t%u\\t\\t%.2f\\t%.2f\\n', 'Residual ', n-s, B, B/(n-s));\n  # fprintf('--------------------------------------------------------------------\\n');\n  # fprintf('%s\\t\\t%u\\t\\t%.2f', 'Total   ',n-1,A+B);\n  # fprintf('\\n\\n')\n\n  # table = [\"Source\",'d.f.','SS','MS','F','P-Value';\n  #          'Columns', s-1 , A, A/(s-1), F, pval;\n  #          'Residual ', n-s, B, B/(n-s), [], [];\n  #          'Total',n-1,A+B,[],[],[]]\n\n  return (; p, F)\nend\n\n\n\"\"\"\nParametric two-way ANOVA for circular data with interations.\n\n  !!!note\n  The test assumes underlying von-Mises distributrions.\n  All groups are assumed to have a common concentration parameter k, between 0 and 2.\n\n  1. α: angles in radians\n  2. idp: indicates the level of factor 1 (1:p)\n  3. idq: indicates the level of factor 2 (1:q)\n    - inter: whether to include effect of interaction\n    - fn: string array containing names of the factors\n\n  return:\n  - p: pvalues for factors and interaction\n  - s: statistic of each p value\n\"\"\"\nfunction circ_hktest(α, idp, idq; inter = true, fn = ['A', 'B'])\n  # number of groups for every factor\n  pu = unique(idp)\n  p = length(pu)\n  qu = unique(idq)\n  q = length(qu)\n\n  # number of samples\n  n = length(α)\n\n  # compute important sums for the test statistics\n  cn = zeros(p, q)\n  cr = zeros(p, q)\n  pm = zeros(p)\n  pr = zeros(p)\n  pn = zeros(p)\n  qm = zeros(q)\n  qr = zeros(q)\n  qn = zeros(q)\n  for pp = 1:p\n    p_id = idp .== pu[pp] # indices of factor1 = pp\n    for qq = 1:q\n      q_id = idq .== qu[qq] # indices of factor2 = qq\n      idx = p_id .& q_id\n      cn[pp, qq] = sum(idx)     # number of items in cell\n      cr[pp, qq] = cn[pp, qq] * circ_r(α[idx]) # R of cell\n    end\n    # R and mean angle for factor 1\n    pr[pp] = sum(p_id) * circ_r(α[p_id])\n    pm[pp] = circ_mean(α[p_id]).μ\n    pn[pp] = sum(p_id)\n  end\n\n  # R and mean angle for factor 2\n  for qq = 1:q\n    q_id = idq .== qu[qq]\n    qr[qq] = sum(q_id) * circ_r(α[q_id])\n    qm[qq] = circ_mean(α[q_id]).μ\n    qn[qq] = sum(q_id)\n  end\n\n  # R and mean angle for whole sample (total)\n  tr = n * circ_r(α)\n\n  # estimate kappa\n  kk = circ_kappa(tr / n)\n\n  # different formulas for different width of the distribution\n  if kk > 2\n    # large kappa\n\n    # effect of factor 1\n    eff_1 = sum(pr .^ 2 ./ dropdims(sum(cn, dims = 2), dims = 2)) - tr .^ 2 / n\n    df_1 = p - 1\n    ms_1 = eff_1 / df_1\n\n    # effect of factor 2\n    eff_2 = sum(qr .^ 2 ./ dropdims(sum(cn, dims = 1), dims = 1)) - tr .^ 2 / n\n    df_2 = q - 1\n    ms_2 = eff_2 / df_2\n\n    # total effect\n    eff_t = n - tr .^ 2 / n\n    df_t = n - 1\n\n    m = mean(cn)\n\n    if inter\n      # correction factor for improved F statistic\n      β = 1 / (1 - 1 / (5kk) - 1 / (10kk^2))\n\n      # residual effects\n      eff_r = n - sum(cr .^ 2 ./ cn)\n      df_r = p * q * (m - 1)\n      ms_r = eff_r / df_r\n\n      # interaction effects\n      eff_i =\n        sum(cr .^ 2 ./ cn) - sum(qr .^ 2 ./ qn) - sum(pr .^ 2 ./ pn) +\n        tr .^ 2 / n\n      df_i = (p - 1) * (q - 1)\n      ms_i = eff_i / df_i\n\n      # interaction test statistic\n      FI = ms_i / ms_r\n      pI = 1 - cdf(FDist(df_i, df_r), FI)\n\n    else\n      # residual effect\n      eff_r = n - sum(qr .^ 2 ./ qn) - sum(pr .^ 2 ./ pn) + tr .^ 2 / n\n      df_r = (p - 1) * (q - 1)\n      ms_r = eff_r / df_r\n\n      # interaction effects\n      eff_i = []\n      df_i = []\n      ms_i = []\n\n      # interaction test statistic\n      FI = []\n      pI = NaN\n      β = 1\n    end\n\n    # compute all test statistics as F = β * MS(A) / MS(R)\n    F1 = β * ms_1 / ms_r\n    p1 = 1 - cdf(FDist(df_1, df_r), F1)\n\n    F2 = β * ms_2 / ms_r\n    p2 = 1 - cdf(FDist(df_2, df_r), F2)\n    s = [F1, F2, FI]\n  else\n    # small kappa\n\n    # correction factor\n    rr = besseli(1, kk) / besseli(0, kk)\n    f = 2 / (1 - rr^2)\n\n    chi1 = f * (sum(pr .^ 2 ./ pn) - tr .^ 2 / n)\n    df_1 = 2 * (p - 1)\n    p1 = 1 - cdf(Chisq(df_1), chi1)\n\n    chi2 = f * (sum(qr .^ 2 ./ qn) - tr .^ 2 / n)\n    df_2 = 2 * (q - 1)\n    p2 = 1 - cdf(Chisq(df_2), chi2)\n\n    chiI =\n      f * (\n        sum(cr .^ 2 ./ cn) - sum(pr .^ 2 ./ pn) - sum(qr .^ 2 ./ qn) +\n        tr .^ 2 / n\n      )\n    df_i = (p - 1) * (q - 1)\n    pI = 1 - cdf(Chisq(df_i), chiI)\n    s = [chi1, chi2, chiI]\n  end\n  p = [p1, p2, pI]\n  #\n  # if kk>2\n  #\n  #   fprintf('\\nANALYSIS OF VARIANCE TABLE (HIGH KAPPA MODE)\\n\\n');\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');\n  #   fprintf('--------------------------------------------------------------------\\n');\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);\n  #   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);\n  #   if (inter)\n  #       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);\n  #   end\n  #   fprintf('%s\\t\\t%u\\t\\t%.2f\\t%.2f\\n', 'Residual ', df_r, eff_r, ms_r);\n  #   fprintf('--------------------------------------------------------------------\\n');\n  #   fprintf('%s\\t\\t%u\\t\\t%.2f', 'Total   ',df_t,eff_t);\n  #   fprintf('\\n\\n')\n  # else\n  #   fprintf('\\nANALYSIS OF VARIANCE TABLE (LOW KAPPA MODE)\\n\\n');\n  #\n  #   fprintf('%s\\t\\t\\t\\t%s\\t%s\\t\\t\\t%s\\n', ' ' ,'d.f.', 'CHI2', 'P-Value');\n  #   fprintf('--------------------------------------------------------------------\\n');\n  #   fprintf('%s\\t\\t\\t\\t%u\\t\\t%.2f\\t\\t\\t%.4f\\n', fn{1}, df_1 , chi1, p1);\n  #   fprintf('%s\\t\\t\\t\\t%u\\t\\t%.2f\\t\\t\\t%.4f\\n', fn{2}, df_2 , chi2, p2);\n  #   if (inter)\n  #       fprintf('%s\\t\\t%u\\t\\t%.2f\\t\\t\\t%.4f\\n', 'Interaction', df_i , chiI, pI);\n  #   end\n  #   fprintf('--------------------------------------------------------------------\\n');\n  #   fprintf('\\n\\n')\n  #\n  # end\n  return (; p, s)\nend\n\n\n\"\"\"\nA parametric two-sample test to determine whether two concentration parameters are different.\n\n  H0: The two concentration parameters are equal.\n  HA: The two concentration parameters are different.\n\n  Assumptions: both samples are drawn from von Mises type distributions and their joint resultant vector length should be > .7\n\n  1. α₁: sample of angles in radians\n  2. α₂: sample of angles in radians\n\n  return:\n  - p: p-value that samples have different concentrations\n  - f: f-statistic calculated\n\"\"\"\nfunction circ_ktest(α₁, α₂)\n  n1 = length(α₁)\n  n2 = length(α₂)\n\n  R1 = n1 * circ_r(α₁)\n  R2 = n2 * circ_r(α₂)\n\n  # make sure that r̄ > .7\n  r̄ = (R1 + R2) / (n1 + n2)\n\n  if r̄ < 0.7\n    @warn \"Resultant vector length should be > 0.7\"\n  end\n\n  # calculate test statistic\n  f = ((n2 - 1) * (n1 - R1)) / ((n1 - 1) * (n2 - R2))\n  if f > 1\n    p = 2 * (1 - cdf(FDist(n1, n2), f))\n  else\n    f = 1 / f\n    p = 2 * (1 - cdf(FDist(n2, n1), f))\n  end\n  return (; p, f)\nend\n\n\n\"\"\"\nTests for symmetry about the median.\n  H0: the population is symmetrical around the median\n  HA: the population is not symmetrical around the median\n\n  1. α: sample of angles in radians\n\n  return: p-value\n\"\"\"\nfunction circ_symtest(α)\n  # compute median\n  md = circ_median(α)\n\n  # compute deviations from median\n  d = circ_dist(α, md)\n\n  # compute wilcoxon sign rank test\n  pvalue(SignedRankTest(d))\nend\n\nconst kuipertable= [5\t1.45800000000000\t1.56500000000000\t1.68200000000000\t1.76300000000000\t1.83800000000000\t1.92000000000000\t1.97000000000000;\n                    6\t1.47100000000000\t1.58200000000000\t1.71100000000000\t1.79300000000000\t1.86700000000000\t1.95700000000000\t2.02000000000000;\n                    7\t1.48300000000000\t1.59800000000000\t1.72700000000000\t1.81400000000000\t1.89400000000000\t1.98700000000000\t2.05100000000000;\n                    8\t1.49300000000000\t1.60800000000000\t1.74100000000000\t1.83000000000000\t1.91100000000000\t2.00900000000000\t2.07700000000000;\n                    9\t1.50000000000000\t1.61800000000000\t1.75200000000000\t1.84300000000000\t1.92600000000000\t2.02700000000000\t2.09700000000000;\n                    10\t1.50700000000000\t1.62500000000000\t1.76100000000000\t1.85400000000000\t1.93800000000000\t2.04100000000000\t2.11300000000000;\n                    11\t1.51300000000000\t1.63100000000000\t1.76900000000000\t1.86200000000000\t1.94800000000000\t2.05300000000000\t2.12600000000000;\n                    12\t1.51700000000000\t1.63700000000000\t1.77600000000000\t1.87000000000000\t1.95700000000000\t2.06200000000000\t2.13700000000000;\n                    13\t1.52200000000000\t1.64200000000000\t1.78200000000000\t1.87600000000000\t1.96400000000000\t2.07100000000000\t2.15400000000000;\n                    14\t1.52500000000000\t1.64600000000000\t1.78700000000000\t1.88200000000000\t1.97000000000000\t2.07800000000000\t2.15400000000000;\n                    15\t1.52900000000000\t1.65000000000000\t1.79100000000000\t1.88700000000000\t1.97600000000000\t2.08500000000000\t2.16100000000000;\n                    16\t1.53200000000000\t1.65300000000000\t1.79500000000000\t1.89200000000000\t1.98100000000000\t2.09000000000000\t2.16800000000000;\n                    17\t1.53400000000000\t1.65700000000000\t1.79900000000000\t1.89600000000000\t1.98600000000000\t2.09600000000000\t2.17300000000000;\n                    18\t1.53700000000000\t1.65900000000000\t1.80200000000000\t1.89900000000000\t1.99000000000000\t2.10000000000000\t2.17800000000000;\n                    19\t1.53900000000000\t1.66200000000000\t1.80500000000000\t1.90300000000000\t1.99300000000000\t2.10400000000000\t2.18300000000000;\n                    20\t1.54100000000000\t1.66400000000000\t1.80800000000000\t1.90600000000000\t1.99700000000000\t2.10800000000000\t2.18700000000000;\n                    21\t1.54300000000000\t1.66700000000000\t1.81000000000000\t1.90800000000000\t2\t                2.11200000000000\t2.19100000000000;\n                    22\t1.54500000000000\t1.66900000000000\t1.81300000000000\t1.91100000000000\t2.00300000000000\t2.11500000000000\t2.19400000000000;\n                    23\t1.54700000000000\t1.67000000000000\t1.81500000000000\t1.91300000000000\t2.00500000000000\t2.11800000000000\t2.19800000000000;\n                    24\t1.54900000000000\t1.67200000000000\t1.81700000000000\t1.91600000000000\t2.00800000000000\t2.12100000000000\t2.20100000000000;\n                    25\t1.55000000000000\t1.67400000000000\t1.81900000000000\t1.91800000000000\t2.01000000000000\t2.12300000000000\t2.20300000000000;\n                    30\t1.55600000000000\t1.68100000000000\t1.82600000000000\t1.92600000000000\t2.01900000000000\t2.13400000000000\t2.21500000000000;\n                    35\t1.56100000000000\t1.68600000000000\t1.83200000000000\t1.93300000000000\t2.02600000000000\t2.14100000000000\t2.22300000000000;\n                    40\t1.56500000000000\t1.69000000000000\t1.83700000000000\t1.93800000000000\t2.03200000000000\t2.14800000000000\t2.23000000000000;\n                    45\t1.56800000000000\t1.69400000000000\t1.84100000000000\t1.94200000000000\t2.03600000000000\t2.15200000000000\t2.23500000000000;\n                    50\t1.57100000000000\t1.69700000000000\t1.84400000000000\t1.94600000000000\t2.04000000000000\t2.15700000000000\t2.23900000000000;\n                    100\t1.58800000000000\t1.71400000000000\t1.86200000000000\t1.96500000000000\t2.06000000000000\t2.17800000000000\t2.26200000000000;\n                    200\t1.60000000000000\t1.72600000000000\t1.87600000000000\t1.97900000000000\t2.07500000000000\t2.19400000000000\t2.27900000000000;\n                    500\t1.61000000000000\t1.73700000000000\t1.88700000000000\t1.99000000000000\t2.08700000000000\t2.20700000000000\t2.29200000000000;\n                    501\t1.62000000000000\t1.74700000000000\t1.89800000000000\t2.00100000000000\t2.09800000000000\t2.21800000000000\t2.30300000000000]\n\n\n\"\"\"\nThe Kuiper two-sample test tests whether the two samples differ significantly.\nThe difference can be in any property, such as mean location and dispersion.\nIt is a circular analogue of the Kolmogorov-Smirnov test.\n\n  H0: The two distributions are identical.\n  HA: The two distributions are different.\n\n  1. α₁: sample of angles in radians\n  2. α₂: sample of angles in radians\n    - n: resolution at which the cdf are evaluated\n\n  return:\n  - p: p-value; the smallest of .10, .05, .02, .01, .005, .002, .001,\n        for which the test statistic is still higher than the respective critical value.\n        this is due to the use of tabulated values. if p>.1, pval is set to 1.\n  - k: test statistic\n  - K: critical value\n\"\"\"\nfunction circ_kuipertest(α₁, α₂; n = 100)\n  n = length(α₁)\n  m = length(α₂)\n\n  # create cdfs of both samples\n  ϕ₁, cdf1 = circ_samplecdf(α₁; n)\n  _, cdf2 = circ_samplecdf(α₂; n)\n\n  # maximal difference between sample cdfs\n  dplus, gdpi = findmax([0; cdf1 .- cdf2])\n  dminus, gdmi = findmax([0; cdf2 .- cdf1])\n\n  # calculate k-statistic\n  k = n * m * (dplus + dminus)\n\n  # find p-value\n  p, K = kuiperlookup(min(n, m), k / sqrt(n * m * (n + m)))\n  K *= sqrt(n * m * (n + m))\n\n  return (; p, k, K)\nend\n\nfunction kuiperlookup(n, k)\n  α = [0.10, 0.05, 0.02, 0.01, 0.005, 0.002, 0.001]\n  nn = kuipertable[:, 1]\n\n  # find correct row of the table\n  row = findfirst(n.==nn)\n  if isnothing(row)\n    # find closest value if no entry is present\n    row = length(nn) - sum(n .< nn)\n    if row == 0\n      error(\"n too small.\")\n    else\n      @warn \"n=$n not found in table, using closest n=$(nn[row]) present.\"\n    end\n  end\n\n  # find minimal p-value and test-statistic\n  idx = findlast(kuipertable[row, 2:end] .< k)\n  if isnothing(idx)\n    p = 1\n    K = NaN\n  else\n    p = α[idx]\n    K = kuipertable[row, idx+1]\n  end\n\n  return (; p, K)\nend\n\n\n\"\"\"\nCircular correlation coefficient for two circular random variables.\n\n  1. α₁: sample of angles in radians\n  2. α₂: sample of angles in radians\n\n  return:\n  - ρ: correlation coefficient\n  - p: p-value\n\"\"\"\nfunction circ_corrcc(α₁, α₂)\n  # compute mean directions\n  n = length(α₁)\n  ᾱ₁ = circ_mean(α₁).μ\n  ᾱ₂ = circ_mean(α₂).μ\n\n  # compute correlation coeffcient from p. 176\n  num = sum(sin.(α₁ .- ᾱ₁) .* sin.(α₂ .- ᾱ₂))\n  den = sqrt(sum(sin.(α₁ .- ᾱ₁) .^ 2) .* sum(sin.(α₂ .- ᾱ₂) .^ 2))\n  ρ = num / den\n\n  # compute pvalue\n  l20 = mean(sin.(α₁ .- ᾱ₁) .^ 2)\n  l02 = mean(sin.(α₂ .- ᾱ₂) .^ 2)\n  l22 = mean((sin.(α₁ .- ᾱ₁) .^ 2) .* (sin.(α₂ .- ᾱ₂) .^ 2))\n\n  ts = sqrt((n * l20 * l02) / l22) * ρ\n  p = 2 * (1 - cdf(Normal(), abs(ts)))\n  return (; ρ, p)\nend\n\n\n\"\"\"\nCorrelation coefficient between one circular and one linear random variable.\n\n  1. α: sample of angles in radians\n  2. x: sample of linear random variable\n\n  return:\n  - ρ: correlation coefficient\n  - p: p-value\n\"\"\"\nfunction circ_corrcl(α, x)\n  n = length(α)\n\n  # compute correlation coefficent for sin and cos independently\n  rxs = cor(x, sin.(α))\n  rxc = cor(x, cos.(α))\n  rcs = cor(sin.(α), cos.(α))\n\n  # compute angular-linear correlation (equ. 27.47)\n  ρ = sqrt((rxc^2 + rxs^2 - 2 * rxc * rxs * rcs) / (1 - rcs^2))\n\n  # compute pvalue\n  p = 1 - cdf(Chisq(2), n * ρ^2)\n  return (; ρ, p)\nend\n\n\n\"\"\"\nComputes an approximation to the ML estimate of the concentration parameter kappa of the von Mises distribution.\n\n  1. α: angles in radians OR α is length resultant\n    - w: number of incidences in case of binned angle data\n\n  return: estimated value of kappa\n\"\"\"\nfunction circ_kappa(α; w = ones(size(α)))\n  N = length(α)\n\n  if N > 1\n    R = circ_r(α; w)\n  else\n    R = α\n  end\n\n  if R < 0.53\n    κ = 2R + R^3 + 5R^5 / 6\n  elseif R >= 0.53 && R < 0.85\n    κ = -0.4 + 1.39R + 0.43 / (1 - R)\n  else\n    κ = 1 / (R^3 - 4R^2 + 3R)\n  end\n\n  if N < 15 && N > 1\n    if κ < 2\n      κ = max(κ - 2 * (N * κ)^-1, 0)\n    else\n      κ = (N - 1)^3 * κ / (N^3 + N)\n    end\n  end\n  κ\nend\n\n\"\"\"\nPerforms a simple agglomerative clustering of angular data.\n\n1. α: sample of angles in radians\n  - k: number of clusters desired, default=2\n\nreturn:\n- cid: cluster id for each entry of α\n- α: sorted angles, matched with cid\n- μ: mean direction of angles in each cluster\n\"\"\"\nfunction circ_clust(α; k = 2)\n\n  n = length(α)\n  n < k && error(\"Not enough data for clusters.\")\n\n  # prepare data\n  cid = 1:n\n\n  # main clustering loop\n  num_unique = length(unique(cid))\n\n  while (num_unique > k)\n\n    # find centroid means...\n\n    # calculate the means for each putative cluster\n    μ = fill(NaN, n)\n    for j = 1:n\n      if sum(cid .== j) > 0\n        μ[j], = circ_mean(α(cid .== j))\n      end\n    end\n\n    # find distance between centroids...\n    μdist = abs.(circ_dist2(μ))\n\n    # find closest pair of clusters/datapoints\n    mindist = minimum(μdist[tril(ones(size(μdist), size(μdist)), -1)==1])\n    row, col = findall(μdist .== mindist)\n\n    # update cluster id's\n    cid[cid.==maximum(row)] = minimum(col)\n\n    # update stop criteria\n    num_unique = length(unique(cid))\n\n  end\n\n  # renumber cluster ids (so cids [1 3 7 10] => [1 2 3 4])\n  cid2 = deepcopy(cid)\n  uniquecids = unique(cid)\n  for j = 1:length(uniquecids)\n    cid[cid2.==uniquecids[j]] = j\n  end\n\n  # compute final cluster means\n  μ = fill(NaN, num_unique)\n  for j = 1:num_unique\n    if sum(cid .== j) > 0\n      μ[j], = circ_mean(α[cid.==j]')\n    end\n  end\n\n  return (; cid, α, μ)\nend\n\n\"\"\"\nHelper function for circ_kuipertest. Evaluates CDF of sample.\n\n  1. α: sample of angles in radians\n    - n: resolution at which the cdf are evaluated\n\n  return:\n  - ϕ: angles at which CDF are evaluated\n  - c: CDF values at ϕ\n\"\"\"\nfunction circ_samplecdf(α; n = 100)\n  ϕ = range(0, 2π, length = n + 1)\n\n  # ensure all points in α are on interval [0, 2pi)\n  α = sort(mod2pi.(α))\n\n  dp = 1 / length(α) # incremental change in probability\n  c = cumsum(map((l, r) -> dp * sum(l .<= α .< r), ϕ[1:end-1], ϕ[2:end]))\n  ϕ = ϕ[1:end-1]\n\n  return (; ϕ, c)\nend\n", "meta": {"hexsha": "58597c4eec27c20d687ee3459fd2ca6e2c38f65c", "size": 36679, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/src.jl", "max_stars_repo_name": "babaq/CircStat.jl", "max_stars_repo_head_hexsha": "8d056506b6c4203e9f739db7efbb101c787669c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2022-01-21T18:22:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T21:11:44.000Z", "max_issues_repo_path": "src/src.jl", "max_issues_repo_name": "babaq/CircStat.jl", "max_issues_repo_head_hexsha": "8d056506b6c4203e9f739db7efbb101c787669c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-21T17:42:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T18:20:19.000Z", "max_forks_repo_path": "src/src.jl", "max_forks_repo_name": "babaq/CircStat.jl", "max_forks_repo_head_hexsha": "8d056506b6c4203e9f739db7efbb101c787669c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-15T11:50:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T11:50:11.000Z", "avg_line_length": 30.0894175554, "max_line_length": 171, "alphanum_fraction": 0.6130756018, "num_tokens": 13300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7589127647256448}}
{"text": "# # [Basic Epidemiology Models](@id epidemiology_example)\n#\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/examples/covid/epidemiology.ipynb)\n\nusing AlgebraicPetri.Epidemiology\n\nusing Petri\nusing StochasticDiffEq\nusing Plots\n\nusing Catlab.Theories\nusing Catlab.CategoricalAlgebra.ShapeDiagrams\nusing Catlab.Graphics\n\ndisplay_wd(ex) = to_graphviz(ex, orientation=LeftToRight, labels=true);\n\n# #### SIR Model:\n\n# define model\n\nsir = transmission ⋅ recovery\n\n# get resulting petri net and visualize model\n\np_sir = decoration(F_epi(sir));\ndisplay_wd(sir)\n#-\nGraph(p_sir)\n\n# define initial states and transition rates, then\n# create, solve, and visualize ODE problem\n\nu0 = [10.0, 1, 0];\np = [0.4, 0.4];\n\nprob,cb = SDEProblem(p_sir,u0,(0.0,7.5),p);\nsol = solve(prob,SRA1(),callback=cb)\n\nplot(sol)\n\n# #### SEIR Model:\n\n# define model\n\nsei = exposure ⋅ (illness ⊗ id(I)) ⋅ ∇(I)\n\nseir = sei ⋅ recovery\n\n# get resulting petri net and visualize model\n\np_seir = decoration(F_epi(seir));\n\ndisplay_wd(seir)\n#-\nGraph(p_seir)\n\n# define initial states and transition rates, then\n# create, solve, and visualize ODE problem\n\nu0 = [10.0, 1, 0, 0];\np = [0.9, 0.2, 0.5];\n\nprob,cb = SDEProblem(p_seir,u0,(0.0,15.0),p);\nsol = solve(prob,SRA1(),callback=cb)\n\nplot(sol)\n\n# #### SEIRD Model:\n\n# define model\n\nseird = sei ⋅ Δ(I) ⋅ (death ⊗ recovery)\n\n# get resulting petri net and visualize model\n\np_seird = decoration(F_epi(seird));\n\ndisplay_wd(seird)\n#-\nGraph(p_seird)\n\n# define initial states and transition rates, then\n# create, solve, and visualize ODE problem\n\nu0 = [10.0, 1, 0, 0, 0];\np = [0.9, 0.2, 0.5, 0.1];\n\nprob,cb = SDEProblem(p_seird,u0,(0.0,15.0),p);\nsol = solve(prob,SRA1(),callback=cb)\n\nplot(sol)", "meta": {"hexsha": "c47a80681e63cc734f7148183e345c45168c695b", "size": 1728, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/covid/epidemiology.jl", "max_stars_repo_name": "olynch/AlgebraicPetri.jl", "max_stars_repo_head_hexsha": "26de81cdac3ee3a4274c6779665a5b56019848d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/covid/epidemiology.jl", "max_issues_repo_name": "olynch/AlgebraicPetri.jl", "max_issues_repo_head_hexsha": "26de81cdac3ee3a4274c6779665a5b56019848d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/covid/epidemiology.jl", "max_forks_repo_name": "olynch/AlgebraicPetri.jl", "max_forks_repo_head_hexsha": "26de81cdac3ee3a4274c6779665a5b56019848d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.989010989, "max_line_length": 124, "alphanum_fraction": 0.6996527778, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210671, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7589127636450236}}
{"text": "using Distributions\n\n\n\"\"\"\n    bubbleKernel(x::Float64, r::Float64)::Float64\n\nReturn 1.0 if dist <= r, otherwise 0.0.\n\"\"\"\nfunction bubbleKernel(x::Float64, r::Float64)::Float64\n    return x <= r ? 1.0 : 0.0\nend\n\n\n\"\"\"\n    gaussianKernel(x::Float64, r::Float64)::Float64\n\nReturn Gaussian(x) for μ=0.0 and σ = r/3.\n(a value of σ = r/3 makes the training results comparable between different kernels\nfor same values of r).\n\"\"\"\nfunction gaussianKernel(x::Float64, r::Float64)::Float64\n    return Distributions.pdf.(Distributions.Normal(0.0,r/3), x)\nend\n", "meta": {"hexsha": "d4da2e484f38c062a647b0c6dffde032b5db159a", "size": 547, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SOM.jl-172a5912-0be3-5bce-b68a-ea4f60b69b05", "max_stars_repo_head_hexsha": "51b9073c8e9f896f415b938ea15a65ea3b32558e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-10-31T10:17:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T17:55:05.000Z", "max_issues_repo_path": "src/kernels.jl", "max_issues_repo_name": "andreasdominik/SOM.jl", "max_issues_repo_head_hexsha": "a0a85496bb7c15921bfeed636e9ff37ee8a138f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2018-04-25T06:25:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T17:14:57.000Z", "max_forks_repo_path": "src/kernels.jl", "max_forks_repo_name": "andreasdominik/SOM.jl", "max_forks_repo_head_hexsha": "a0a85496bb7c15921bfeed636e9ff37ee8a138f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2018-05-07T16:14:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:45:10.000Z", "avg_line_length": 22.7916666667, "max_line_length": 83, "alphanum_fraction": 0.6910420475, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7589127636450236}}
{"text": "\"\"\"\n    differentiate(f::Expr, x::Symbol)\n\nDifferentiate f with respect to x.\n\"\"\"\nfunction differentiate(f::Expr, x::Symbol)\n    @assert f.head == :call\n    return differentiate(Val{f.args[1]}, f, x)\nend\n\n\"\"\"\n    differentiate(::Number, ::Symbol)\n\nDifferentiate a constant.\n\"\"\"\nfunction differentiate(::Number, ::Symbol)\n    return 0\nend\n\n\"\"\"\n    differentiate(f::Symbol, x::Symbol)\n\nDifferentiate a symbol.\n\"\"\"\nfunction differentiate(f::Symbol, x::Symbol)\n    return f == x ? 1 : 0\nend\n\n\"\"\"\n    differentiate(Val{:*}, f::Expr, x::Symbol)\n\nDifferentiate (fg)' using chain rule: ```(fgh)' = f'gh + fg'h + fgh'```.\n\"\"\"\nfunction differentiate(::Type{Val{:*}}, f::Expr, x::Symbol)\n    op = first(f.args)\n    @assert op == :*\n    res_args = Any[:+]\n    for i in 2:length(f.args)\n        new_args = copy(f.args)\n        new_args[i] = differentiate(f.args[i], x)\n        push!(res_args, Expr(:call, new_args...))\n    end\n    return Expr(:call, res_args...)\nend\n\n\"\"\"\n    differentiate(Val{:^}, f::Expr, x::Symbol)\n\nDifferentiate d/dx f^a = a * f ^ (a - 1) * diff(f, x)\n\"\"\"\nfunction differentiate(::Type{Val{:^}}, ex::Expr, x::Symbol)\n    op, f, a = ex.args\n    @assert op == :^\n    df = differentiate(f, x)\n    return :($a * $f ^ ($a - 1) * $df)\nend\n\n\"\"\"\n    differentiate(Val{:/}, ex::Expr, x::Symbol)\n\nDifferentiate d/dx f/g.\n\"\"\"\nfunction differentiate(::Type{Val{:/}}, ex::Expr, x::Symbol)\n    op, g, h = ex.args\n    @assert op == :/\n    dg = differentiate(g, x)\n    dh = differentiate(h, x)\n    return :(($dg * $h + $g * $dh) / $h^2)\nend\n\n\"\"\"\n    differentiate(Val{:+}, ex::Expr, x::Symbol)\n\nDifferentiate d/dx (f + g)\n\"\"\"\nfunction differentiate(::Type{Val{:+}}, ex::Expr, x::Symbol)\n    op = first(ex.args)\n    @assert op == :+\n    args = differentiate.(ex.args[2:end], x)\n    return Expr(:call, :+, args...)\nend\n\n\"\"\"\n    differentiate(Val{:-}, ex::Expr, x::Symbol)\n\nDifferentiate d/dx (f - g)\n\"\"\"\nfunction differentiate(::Type{Val{:-}}, ex::Expr, x::Symbol)\n    op = first(ex.args)\n    @assert op == :-\n    args = differentiate.(ex.args[2:end], x)\n    return Expr(:call, :-, args...)\nend\n", "meta": {"hexsha": "37a1b33d0d7b568ced11059086f59ecf98c4d6ba", "size": 2086, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/differentiate.jl", "max_stars_repo_name": "ahojukka5/SymDiff.jl", "max_stars_repo_head_hexsha": "1c33d5a998c1cb4e49e15a8a810ae624a937cf70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-22T14:09:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-22T14:09:23.000Z", "max_issues_repo_path": "src/differentiate.jl", "max_issues_repo_name": "ahojukka5/SymDiff.jl", "max_issues_repo_head_hexsha": "1c33d5a998c1cb4e49e15a8a810ae624a937cf70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-22T16:26:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-12T14:41:50.000Z", "max_forks_repo_path": "src/differentiate.jl", "max_forks_repo_name": "ahojukka5/SymDiff.jl", "max_forks_repo_head_hexsha": "1c33d5a998c1cb4e49e15a8a810ae624a937cf70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-28T21:43:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T21:43:02.000Z", "avg_line_length": 22.1914893617, "max_line_length": 72, "alphanum_fraction": 0.5747842761, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7589127566824188}}
{"text": "#=\n  From https://mhtess.github.io/bdappl/chapters/04-hypothesisTesting.html\n  WebPPL model:\n  \"\"\"\n  The research assistants\n\n  Recall our example from the previous chapter about two research assistants \n  who returned wildly different results. We had the intuition that they were \n  doing something different from one another. Is there a way to quantify our \n  degree of belief in that proposition?\n\n  We can take a model comparison approach, comparing a model where we posit a \n  single latent parameter (research assistants are doing / measuring the same \n  thing) vs. a model where we posit different parameters for the different \n  research assistants. The latter model has more flexibility, but it also probably \n  predicts the observed data better.\n  \"\"\"\n\n  Note: The WebPPL model use AIS() for this comparison.\n  Here we use SMC's logevidence. \n  PG() and IS() also has chns.logevidence, but HM() does not.\n\n=#\nusing Turing\ninclude(\"jl_utils.jl\")\n\n\n@model function model_comparison_simple(k1=0,n1=10,k2=10,n=10)\n    p1 ~ Uniform(0,1)\n    k1 ~ Binomial(n1,p1)\n    p2 = p1\n    k2 ~ Binomial(n2,p2)\nend\n\n#\n# \"Complex\" model with separate p for Binomial\n#\n@model function model_comparison_complex(k1=0,n1=10,k2=10,n=10)\n    p1 ~ Uniform(0,1)\n    k1 ~ Binomial(n1,p1)\n    p2 ~ Uniform(0,1)\n    k2 ~ Binomial(n2,p2)\nend\n\nmodel = model_comparison_simple()\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\n# chns = sample(model, PG(15), 10_000)\n# chns = sample(model, IS(), 10_000)\nchns = sample(model, SMC(), 10_000)\n# chns = sample(model, SMC(), MCMCThreads(), 10_000, 4)\n# display(chns)\ndisplay(chns)\nll1 = chns.logevidence\n\n\nmodel = model_comparison_complex()\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\n# chns = sample(model, PG(15), 10_000)\n# chns = sample(model, IS(), 10_000)\nchns = sample(model, SMC(), 10_000)\n# chns = sample(model, SMC(), MCMCThreads(), 10_000, 4)\n# display(chns)\ndisplay(chns)\nll2 = chns.logevidence\n\n\nprintln(\"\\nlog evidence model 1: \", ll1)\nprintln(\"log evidence model 2: \", ll2)\nprintln(\"diff exp(ll2-ll1): \", exp(ll2-ll1))\n\n\n", "meta": {"hexsha": "d5548daf084751bdd272b6c4585e1ea633b56b71", "size": 2119, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/model_comparison.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/model_comparison.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/model_comparison.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 28.6351351351, "max_line_length": 83, "alphanum_fraction": 0.7050495517, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.758875169890853}}
{"text": "\"\"\"\n    Deterministic(value)\n\nCreate a deterministic distribution over only one value.\n\nThis is intended to be used when a distribution is required, but the outcome is deterministic. It is equivalent to a Kronecker Delta distribution.\n\"\"\"\nstruct Deterministic{T}\n    val::T\nend\n\nrand(rng::AbstractRNG, d::Deterministic) = d.val\nrand(d::Deterministic) = d.val\nsupport(d::Deterministic) = (d.val,)\nsampletype(::Type{Deterministic{T}}) where T = T\nRandom.gentype(::Type{Deterministic{T}}) where T = T\npdf(d::Deterministic, x) = convert(Float64, x == d.val)\nmode(d::Deterministic) = d.val\nmean(d::Deterministic{N}) where N<:Number = d.val / 1 # / 1 is to make this return a similar type to Statistics.mean\nmean(d::Deterministic) = d.val # so that division need not be implemented for the value type\n", "meta": {"hexsha": "cdcb205f122ef5705170cef8ebfacf41058acf3e", "size": 795, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distributions/deterministic.jl", "max_stars_repo_name": "JuliaPOMDP/POMDPModelTools.jl", "max_stars_repo_head_hexsha": "0c34223cbe6622c32f97dad1a40628dac2bb1ae9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-05-19T22:20:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-20T21:24:20.000Z", "max_issues_repo_path": "src/distributions/deterministic.jl", "max_issues_repo_name": "JuliaPOMDP/POMDPModelTools.jl", "max_issues_repo_head_hexsha": "0c34223cbe6622c32f97dad1a40628dac2bb1ae9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2018-08-17T00:38:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T22:18:58.000Z", "max_forks_repo_path": "src/distributions/deterministic.jl", "max_forks_repo_name": "JuliaPOMDP/POMDPModelTools.jl", "max_forks_repo_head_hexsha": "0c34223cbe6622c32f97dad1a40628dac2bb1ae9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-10-17T02:55:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T22:24:33.000Z", "avg_line_length": 37.8571428571, "max_line_length": 146, "alphanum_fraction": 0.7320754717, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7588751656385393}}
{"text": "\"\"\"\n    hadi1992_handle_singularity(S)\n\nPerform the sub-algorithm of handling singularity defined in Hadi (1992).\n\n# Arguments \n- `S::Array{Float64, 2}`: A covariance matrix.\n\n# Reference\nHadi, Ali S. \"Identifying multiple outliers in multivariate data.\" \nJournal of the Royal Statistical Society: Series B (Methodological) 54.3 (1992): 761-771.\n \"\"\"\nfunction hadi1992_handle_singularity(S::Array{Float64,2})::Array{Float64,2}\n    p, _ = size(S)\n    eigen_structure = eigen(S)\n    values = eigen_structure.values\n    vectors = eigen_structure.vectors\n    lambda_s = find_minimum_nonzero(values)\n    W = zeros(Float64, p, p)\n    for i in 1:p\n        @inbounds W[i, i] = 1 / max(values[i], lambda_s) \n    end\n    newS = vectors * W * vectors\n    return newS\nend\n\n\"\"\"\n    hadi1992(multivariateData)\n\nPerform Hadi (1992) algorithm for a given multivariate data. \n\n# Arguments\n-`multivariate::Array{Float64, 2}`: Multivariate data.\n\n# Examples\n```julia-repl\njulia> multidata = hcat(hbk.x1, hbk.x2, hbk.x3);\n\njulia> hadi1992(multidata)\nDict{Any,Any} with 3 entries:\n  \"outliers\"              => [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]\n  \"criticial.chi.squared\" => 7.81473\n  \"rth.robust.distance\"   => 5.04541\n```\n\n# Reference\nHadi, Ali S. \"Identifying multiple outliers in multivariate data.\" \nJournal of the Royal Statistical Society: Series B (Methodological) 54.3 (1992): 761-771.\n\"\"\"\nfunction hadi1992(multivariateData::Array{Float64,2}; alpha=0.05)\n    n, p = size(multivariateData)\n    h = Int(floor((n + p + 1.0) / 2.0))\n    chi_50_quantile = quantile(Chisq(p), 0.50)\n    critical_quantile = quantile(Chisq(p), 1 - alpha)\n    allindices = collect(1:n)\n\n    # Step 0\n    meds = coordinatwisemedians(multivariateData)\n    Sm = (1.0 / (n - 1.0)) * (multivariateData .- meds')' * (multivariateData .- meds')\n    mah0 = diag(mahalanobisSquaredMatrix(multivariateData, meanvector=meds, covmatrix=Sm))\n    ordering_indices_mah0 = sortperm(mah0)\n    best_indices_mah0 = ordering_indices_mah0[1:h]\n    starting_data = multivariateData[best_indices_mah0, :]\n\n    Cv = coordinatwisemedians(starting_data)\n    Sv = (1.0 / (h - 1.0)) * (starting_data .- Cv')' * (starting_data .- Cv')\n    mah1 = diag(mahalanobisSquaredMatrix(multivariateData, meanvector=Cv, covmatrix=Sv))\n    ordering_indices_mah1 = sortperm(mah1)\n\n    r = p + 1\n    basic_subset_indices = []\n    basic_subset = []\n    sorted_mah1 = []\n\n    while r < n\n        cnpr = 1 + (r / (n - p))^2.0\n        basic_subset_indices = ordering_indices_mah1[1:r]\n        basic_subset = multivariateData[basic_subset_indices, :]\n        Cb = applyColumns(mean, basic_subset)\n        Sb = cov(basic_subset)\n\n        r += 1\n        cfactor = cnpr * sqrt(sort(mah1)[h]) / chi_50_quantile\n        if det(cfactor * Sb) == 0\n            @info \"singular Sb case\"\n            newSb = hadi1992_handle_singularity(cfactor * Sb) \n            mah1 = diag(mahalanobisSquaredMatrix(multivariateData, meanvector=Cb, covmatrix=newSb))\n            ordering_indices_mah1 = sortperm(mah1)\n            basic_subset_indices = ordering_indices_mah1[1:r]\n        else\n            mah1 = diag(mahalanobisSquaredMatrix(multivariateData, meanvector=Cb, covmatrix=(cfactor * Sb)))\n            ordering_indices_mah1 = sortperm(mah1)\n            basic_subset_indices = ordering_indices_mah1[1:r]\n        end\n        \n        sorted_mah1 = sort(mah1)\n        if sorted_mah1[r] >= critical_quantile\n            break \n        end\n    end\n\n    outlierset = setdiff(allindices, basic_subset_indices)\n\n    result = Dict()\n    result[\"outliers\"] = sort(outlierset)\n    result[\"criticial.chi.squared\"] = critical_quantile\n    result[\"rth.robust.distance\"] = sorted_mah1[r - 1]\n    return result\nend", "meta": {"hexsha": "422ec09ccacd1368317f09c03d7881b6090267a4", "size": 3708, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hadi1992.jl", "max_stars_repo_name": "akadal/LinRegOutliers", "max_stars_repo_head_hexsha": "86bcb5ffb61ddc40b162b30c782d9f6799de64ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hadi1992.jl", "max_issues_repo_name": "akadal/LinRegOutliers", "max_issues_repo_head_hexsha": "86bcb5ffb61ddc40b162b30c782d9f6799de64ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hadi1992.jl", "max_forks_repo_name": "akadal/LinRegOutliers", "max_forks_repo_head_hexsha": "86bcb5ffb61ddc40b162b30c782d9f6799de64ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0183486239, "max_line_length": 108, "alphanum_fraction": 0.6615426106, "num_tokens": 1160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7588751643822138}}
{"text": "\n\nfunction subtract(d1::Dict, d2::Dict)\n    res = Dict()\n    for key in keys(d1)\n        if key ∉ keys(d2)\n            res[key] = nothing\n        end\n    end\n    res\nend\n\n\n# using Sets instead\n\"\"\"\n    Subtract two sets.\n    Result is a Set.\n\"\"\"\nfunction subtract(s1::Set, s2::Set)\n    setdiff(s1, s2)\nend\n\n\n\n#   ---------- Duplicates ----------\n\n# ... using dictionaries\n\nfunction hasduplicates(t::Dict)\n    d = Dict()\n    for x in t\n        if x ∈ d\n            return true\n        end\n        d[x] = nothing\n    end\n    false\nend\n\nfunction usesonly(word, available)\n    for letter in word\n        if word ∉ available\n            return false\n        end\n    end\n    true\nend\n\n\n# ... using sets\nfunction hasduplicates(t)\n    length(Set(t)) < length(t)\nend\n\nfunction usesonly_set(word, available)\n    Set(word) ⊆ Set(available)\nend\n\n\n\n# ---------- Math -----------\n\nx = 0:0.1:2π\n\ncos.(x) == 0.5*(ℯ.^(im*x) + ℯ.^(-im*x))\n\n\n# ----------- Strings --------\n\nfunction usesonly_regex(word::String, available::String)\n    r = Regex(\"[^$(available)]\")\n    @show r;\n    !occursin(r,word)\nend\n\nusesonly_regex(\"banana\", \"abn\")\nusesonly_regex(\"bananas\", \"abn\")\n\nmatch(r\"[^abn]\", \"banana\")\n\nm = match(r\"[^abn]\", \"bananas\")\n\n\n# ---------------- Matricies  -----------------\n\nz = zeros(Float64, 2,3)\n\nz[1,2] = 2\n\nz[2,3] = 1\nz\n\nsize(z)\n\n# 1x3 row matrix\ns = ones(String, 1, 3)\nsize(s)\n\n# 3 x _ column matrix\ns_col = [\"\", \"\", \"\"]\nsize(s_col)\ns == s_col\n\n# also a column matrix\ns_col2 = [\"\";\"\";\"\"]\nsize(s_col2)\n\ns_col == s_col2\n\ns == s_col2\n\n\n\na = [1 2 3; 4 5 6]\n\n@show a\nprint(a)\nsize(a)\n\n#slicing\n\nu = z[:,2:end]\n\n#broadcasting\n@show im*u\nsize(im*u)\ng = ℯ.^(im*u)\n@show g\ntypeof(g)\n\ntypeof(u)\n\n\n\n\n# ----------- Interfaces: p243 -----------------\n\n#parametric type with no fields\nstruct Fibonacci{T<:Real} end\n\n#outer constructor\nFibonacci(d::DataType) = d<:Real ? Fibonacci{d}() : error(\"Not Real type!\")\n\n# Iterator interface implementation: 2 parts:\n\n# Part 1: called to initialize the iterator\nBase.iterate(::Fibonacci{T}) where {T<:Real} = (zero(T), (one(T), one(T)))\n\n# Part 2:\nBase.iterate(::Fibonacci{T}, state::Tuple{T,T}) where {T<:Real} = (state[1], (state[2], state[1] + state[2]))\n\nfor e in Fibonacci(Int64)\n    e > 100 && break\n    print(e, \" \")\nend\n\n\n#Equivalently:\nf = Fibonacci(Int64)\n\n#initialize state sequence\n(a, (b,c)) = iterate(f)\n\n#iterate ...\n(a, (b,c)) = iterate(f, (b,c))\n\n(a, (b,c)) = iterate(f, (b,c))\n\n(a, (b,c)) = iterate(f, (b,c))\n\n(a, (b,c)) = iterate(f, (b,c))\n\n(a, (b,c)) = iterate(f, (b,c))\n\n(a, (b,c)) = iterate(f, (b,c))\n\n(a, (b,c)) = iterate(f, (b,c))\n\n(a, (b,c)) = iterate(f, (b,c))\n\n(a, (b,c)) = iterate(f, (b,c))\n\n(a, (b,c)) = iterate(f, (b,c))\n\n#= a for loop in julia:\n\nfor i in iter\n    body\nend\n\n    equivalant to:\n\nnext = iterate(iter)\nwhile next !== nothing\n    (i, state) = next\n    body\n    next = iterate(iter, state)\nend\n\n=#\n", "meta": {"hexsha": "c634c8036429b570d77e7d450e1b7724da34402e", "size": 2859, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ch20.jl", "max_stars_repo_name": "sgibbs409/ThinkJuliaBook.jl", "max_stars_repo_head_hexsha": "2998e81dc72bd73fb5871502b0683813368c61c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch20.jl", "max_issues_repo_name": "sgibbs409/ThinkJuliaBook.jl", "max_issues_repo_head_hexsha": "2998e81dc72bd73fb5871502b0683813368c61c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch20.jl", "max_forks_repo_name": "sgibbs409/ThinkJuliaBook.jl", "max_forks_repo_head_hexsha": "2998e81dc72bd73fb5871502b0683813368c61c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.223880597, "max_line_length": 109, "alphanum_fraction": 0.5438964673, "num_tokens": 949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.8376199694135333, "lm_q1q2_score": 0.7588751613862252}}
{"text": "#This example has been adopted from https://github.com/IntelLabs/ParallelAccelerator.jl/blob/master/examples/black-scholes/black-scholes.jl\n\nusing ArrayFire\n\nfunction blackscholes_serial(sptprice::AbstractArray{Float32},\n                           strike::AbstractArray{Float32},\n                           rate::AbstractArray{Float32},\n                           volatility::AbstractArray{Float32},\n                           time::AbstractArray{Float32})\n    logterm = log10( sptprice ./ strike)\n    powterm = .5f0 .* volatility .* volatility\n    den = volatility .* sqrt(time)\n    d1 = (((rate .+ powterm) .* time) .+ logterm) ./ den\n    d2 = d1 .- den\n    NofXd1 = cndf2(d1)\n    NofXd2 = cndf2(d2)\n    futureValue = strike .* exp(- rate .* time)\n    c1 = futureValue .* NofXd2\n    call_ = sptprice .* NofXd1 .- c1\n    put  = call_ .- futureValue .+ sptprice\nend\n\n@inline function cndf2(in::AbstractArray{Float32})\n    out = 0.5f0 .+ 0.5f0 .* erf(0.707106781f0 .* in)\n    return out\nend\n\nfunction run(iterations)\n    sptprice   = Float32[ 42.0 for i = 1:iterations ]\n    initStrike = Float32[ 40.0 + (i / iterations) for i = 1:iterations ]\n    rate       = Float32[ 0.5 for i = 1:iterations ]\n    volatility = Float32[ 0.2 for i = 1:iterations ]\n    time       = Float32[ 0.5 for i = 1:iterations ]\n\n    sptprice_gpu = AFArray(sptprice)\n    initStrike_gpu = AFArray(initStrike)\n    rate_gpu = AFArray(rate)\n    volatility_gpu = AFArray(volatility)\n    time_gpu = AFArray(time)\n\n    tic()\n    put1 = blackscholes_serial(sptprice, initStrike, rate, volatility, time)\n    t1 = toq()\n    println(\"Serial checksum: \", sum(put1))\n    tic()\n    put2 = blackscholes_serial(sptprice_gpu, initStrike_gpu, rate_gpu, volatility_gpu, time_gpu)\n    t2 = toq()\n    println(\"Parallel checksum: \", sum(put2))\n    return t1, t2\nend\n\nfunction driver()\n    srand(0)\n    tic()\n    iterations = 10^7\n    blackscholes_serial(Float32[], Float32[], Float32[], Float32[], Float32[])\n    blackscholes_serial(AFArray(Float32[1., 2.]), AFArray(Float32[1., 2.]), \n                        AFArray(Float32[1., 2.]), AFArray(Float32[1., 2.]), AFArray(Float32[1., 2.]))\n    println(\"SELFPRIMED \", toq())\n    tserial, tparallel = run(iterations)\n    println(\"Time taken for CPU = $tserial\")\n    println(\"Time taken for GPU = $tparallel\")\n    println(\"Speedup = $(tserial / tparallel)\")\n    println(\"CPU rate = \", iterations / tserial, \" opts/sec\")\n    println(\"GPU rate = \", iterations / tparallel, \" opts/sec\")\nend\ndriver()\n", "meta": {"hexsha": "128b50c9711e550ff5c0143da52f4720b36b2844", "size": 2493, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/blackscholes.jl", "max_stars_repo_name": "JuliaPackageMirrors/ArrayFire.jl", "max_stars_repo_head_hexsha": "0f7ac6dc6d54fbc6364b5fbb6e3d68877c64d2ce", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/blackscholes.jl", "max_issues_repo_name": "JuliaPackageMirrors/ArrayFire.jl", "max_issues_repo_head_hexsha": "0f7ac6dc6d54fbc6364b5fbb6e3d68877c64d2ce", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/blackscholes.jl", "max_forks_repo_name": "JuliaPackageMirrors/ArrayFire.jl", "max_forks_repo_head_hexsha": "0f7ac6dc6d54fbc6364b5fbb6e3d68877c64d2ce", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6617647059, "max_line_length": 139, "alphanum_fraction": 0.6269554753, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7588751540413727}}
{"text": "\"\"\"\n```julia\nrate(q::Integer, M::Integer, n::Integer) -> Real\n```\n\t\nCalculate the rate of a code.  That is, how efficient the code is.\n\nParameters:\n  - `q::Integer`: the number of symbols in the code.\n  - `M::Integer`: the size/number of elements in the code.\n  - `n::Integer`: The word length.\n\nReturns:\n  - `Real`: Rate of the code.\n\n---\n\n### Examples\n\n```julia\njulia> rate(3, 5, 4) # the rate of the code which has 3 symbols, 5 words in the code, and word length of 4 (e.g., Σ = {A, B, C}, C = {ABBA,CABA,BBBB,CAAB,ACBB})\n0.3662433801794817\n```\n\"\"\"\nrate(q::T, M::T, n::T) where {T <: Integer} = log(q, M) / n\n\n__spheres(q::T, n::T, r::T) where {T <: Integer} = sum(Integer[((big(q) - 1)^i) * binomial(big(n), big(i)) for i in 0:r])\n__sphere_bound(round_func::Function, q::T, n::T, d::T) where {T <: Integer} = round_func((big(q)^n) / __spheres(q, n, d))\n\n\"\"\"\n```julia\nsphere_covering_bound(q::Integer, n::Integer, d::Integer) -> Integer\n```\n\t\nComputes the sphere covering bound of a ``[n, d]_q``-code.\n\nParameters:\n  - `q::Integer`: the number of symbols in the code.\n  - `n::Integer`: the word length.\n  - `d::Integer`: the distance of the code.\n  \nReturns:\n  - `Integer`: the sphere covering bound.\n\n---\n\n### Examples\n\n```julia\njulia> sphere_covering_bound(5,7,3)\n215\n```\n\"\"\"\nsphere_covering_bound(q::T, n::T, d::T) where {T <: Integer} = __sphere_bound(ceil, q, n, d - 1)\n\n\"\"\"\n```julia\nsphere_packing_bound(q::Integer, n::Integer, d::Integer) -> Integer\nsphere_packing_bound(q::Integer, n::Integer, d::Integer, ::Rounding) -> Real\n```\n\t\nComputes the sphere packing bound of a ``[n, d]_q``-code.  The sphere packing bound is also known as the hamming bound.  You can use `hamming_bound` to compute the same thing.\n\nParameters:\n  - `q::Integer`: the number of symbols in the code.\n  - `n::Integer`: the word length.\n  - `d::Integer`: the distance of the code.\n  - `::Rounding`: use the argument `no_round` in this position to preserve the rounding of the code &mdash; which usually by default rounds down.\n  \nReturns:\n  - `Integer`: the sphere packing bound.\n\n---\n\n### Examples\n\n```julia\njulia> sphere_packing_bound(5,7,3)\n2693\n```\n\"\"\"\nsphere_packing_bound(q::T, n::T, d::T) where T <: Integer =\n\t__sphere_bound(a -> floor(T, a), q, n, floor(T, (d - 1) / 2))\nsphere_packing_bound(q::T, n::T, d::T, ::Rounding) where T <: Integer =\n\t__sphere_bound(identity, q, n, floor(T, (d - 1) / 2))\nhamming_bound(q::T, n::T, d::T) where T <: Integer =\n\tsphere_packing_bound(q, n, d)\nhamming_bound(q::T, n::T, d::T, ::Rounding) where T <: Integer =\n\tsphere_packing_bound(q, n, d, no_round)\n\n\"\"\"\n```julia\nsphere_packing_bound(q::Integer, n::Integer, d::Integer) -> Real\n```\n\t\nComputes the Singleton bound of a ``[n, d]_q``-code.\n\nParameters:\n  - `q::Integer`: the number of symbols in the code.\n  - `n::Integer`: the word length.\n  - `d::Integer`: the distance of the code.\n  \nReturns:\n  - `Real`: the Singleton bound.  Can round down, as it is an equivalent to the Hamming bound in that it is an upper bound.\n\"\"\"\n# promote()\n# _T = typeof(T)\n\nsingleton_bound(q::T, n::T, d::T) where T <: Integer =\n\tfloor(T, float(big(q))^(big(n) - big(d) + 1))\nsingleton_bound(q::T, n::T, d::T, ::Rounding) where T <: Integer =\n\tfloat(big(q))^(big(n) - big(d) + 1)\n\t\n\t\ngilbert_varshamov_bound(q::T, n::T, d::T) where T <: Integer =\n\t__sphere_bound(a -> floor(T, a), q, n, d - 1)\ngilbert_varshamov_bound(q::T, n::T, d::T, ::Rounding) where T <: Integer =\n\t__sphere_bound(identity, q, n, d - 1)\n\nfunction __plotkin_bound_core(round_func::Function, q::T, n::T, d::T) where T <: Integer\n\tif ! isequal(q, 2)\n\t\tthrow(error(\"The Plotkin bound only works for the binary code.\"))\n\tend\n\t\n\tif iseven(d) && 2d > n\n\t\treturn round_func((d) / (2d + 1 - n))\n\telseif isodd(d) && 2d + 1 > n\n\t\treturn round_func((d + 1) / (2d + 1 - n))\n\telseif iseven(d)\n\t\treturn T(4d)\n\t\t# return A_2(2d, d) ≤ 4d\n\telseif isodd(d)\n\t\treturn T(4d + 4)\n\t\t# return A_2(2d + 1, d) ≤ 4d + 4\n\tend\nend\n\nplotkin_bound(q::T, n::T, d::T) where T <: Integer =\n\t__plotkin_bound_core(a -> floor(T, a), q, n, d)\nplotkin_bound(q::T, n::T, d::T, ::Rounding) where T <: Integer =\n\t__plotkin_bound_core(identity, q, n, d, no_round)\n\nelias_bassalygo_bound(q::T, n::T, d::T) where T <: Integer =\nelias_bassalygo_bound(q::T, n::T, d::T, ::Rounding) where T <: Integer =\n\t\nfunction __johnson_bound_core(round_func::Function, q::T, n::T, d::T) where T <: Integer\n\tif isinteger((d - 1) / 2) # is odd\n\t\tt = T((d - 1) / 2)\n\t\t__sphere_bound(round_func, q, n, t) # if d = 2t + 1\n\telseif isinteger(d / 2)\n\t\tt = T(d / 2)\n\t\t__sphere_bound(round_func, q, n, t)\n\tend\nend\n\n@doc raw\"\"\"\n```julia\nconstruct_ham_matrix(r::Int, q::Int) -> Matrix\n```\n\t\nConstruct a Hamming parity-check matrix.\n\nParameters:\n  - `r::Int`: number of rows of a parity check matrix.\n  - `q:::Int`: The size of the alphabet of the code.\n  \nReturns:\n  - `Matrix`: The Hamming matrix, denoted as ``\\text{Ham}(r, q)``\n\n---\n\n### Examples\n\n```julia\njulia> construct_ham_matrix(3,2)\n3×7 Array{Int64,2}:\n 0  0  0  1  1  1  1\n 0  1  1  0  0  1  1\n 1  0  1  0  1  0  1\n```\n\"\"\"\nfunction construct_ham_matrix(r::Int, q::Int)\n    ncols = Int(floor((q^r - 1) / (q - 1)))\n    M = Matrix{Int}(undef, r, ncols)\n    \n    for i in 1:ncols\n        M[:, i] = reverse(digits(parse(Int, string(i, base = q)), pad = r), dims = 1)\n    end\n    \n    return M\nend\n\n\"\"\"\n```julia\nisperfect(n::Int, k::Int, d::Int, q::Int) -> Bool\n```\n\t\nChecks if a code is perfect.  That is, checks if the number of words in the code is exactly the \"Hamming bound\", or the \"Sphere Packing Bound\".\n\t\nParameters:\n  - `q:::Int`: The size of the alphabet of the code.\n  - `n::Int`: The length of the words in the code (block length).\n  - `d::Int`: The distance of the code.\n  - `k::Int`: The dimension of the code.\n  \nReturns:\n  - `Bool`: true or false\n\n---\n\n### Examples\n\n```julia\njulia> isperfect(11, 6, 5, 3)\ntrue\n```\n\"\"\"\nfunction isperfect(n::T, k::T, d::T, q::T) where T <: Int\n\tisprimepower(q) || throw(error(\"Cannot check if the code is perfect with q not a prime power.\"))\n    M = q^k\n\t\n    isequal(sphere_packing_bound(q, n, d), M) && return true\n\treturn false\nend\n\n\"\"\"\n```julia\nishammingbound(r::Int, q::Int) -> Bool\n```\n\t\nChecks if the code is a perfect code that is of the form of a generalised Hamming code.\n\t\nParameters:\n  - `r::Int`: number of rows of a parity check matrix.\n  - `q::Int`: The size of the alphabet of the code.\n  \nReturns:\n  - `Bool`: true or false\n\"\"\"\nfunction ishammingperfect(r::Int, q::Int)\n    n = 2^r - 1\n    k = n - r\n    M = q^k\n    d = size(construct_ham_matrix(r, q), 1) # the number of rows of the hamming matrix (which is, by design, linearly independent)\n    d = r\n    # r is dim of dueal code; dim of code itself is block length minus r\n    # println(n)\n    # println((q^r - 1) / (q - 1))\n    \n    isequal(n, (q^r - 1) / (q - 1)) && \\\n\t\tisequal(d, 3) && \\\n\t\tisequal(M, q^(((q^r - 1) / (q - 1)) - r)) && \\\n        return true\n    return false\nend\n\n\"\"\"\n```julia\nishammingperfect(n::Int, k::Int, d::Int, q::Int) -> Bool\nishammingperfect(q::Int, n::Int, d::Int) -> Bool\n```\n\t\nChecks if the code is a perfect code that is of the form of a generalised Hamming code.\n\t\nParameters:\n  - `q:::Int`: The size of the alphabet of the code.\n  - `n::Int`: The length of the words in the code (block length).\n  - `d::Int`: The distance of the code.\n  - `k::Int`: The dimension of the code.\n  \nReturns:\n  - `Bool`: true or false\n\n---\n\n### Examples\n\n```julia\njulia> isgolayperfect(11, 6, 5, 3) # this is one of golay's perfect codes\ntrue\n```\n\"\"\"\nfunction ishammingperfect(n::T, k::T, d::T, q::T) where T <: Int\n    isprimepower(q) || return false\n    \n    M = q^k\n    r = log(ℯ, ((n * log(ℯ, 1)) / (log(ℯ, 2))) + 1) / log(ℯ, 2)\n        \n    if isequal(n, (q^(r - 1)) / (q - 1)) && isequal(d, 3) && isequal(M, q^(((q^r - 1) / (q - 1)) - r))\n        return true\n    end\n    \n    return false\nend\nfunction ishammingperfect(q::Int, n::Int, d::Int)\n\tisprimepower(q) || return false # we are working in finite fields, so q must be a prime power\n\td ≠ 3 && return false\n\t\n\tr = 1\n\twhile ((q^r - 1) / (q - 1)) < n\n\t\tr = r + 1\n\tend\n\t\n\treturn ifelse(isequal(((q^r - 1) / (q - 1)), n), true, false)\nend\n\n\"\"\"\n```julia\nisgolayperfect(n::Int, k::Int, d::Int, q::Int) -> Bool\n```\n\t\nGolay found two perfect codes.  `isgolayperfect` checks if a code of block length n, distance d, alphabet size q, and dimension k, is a perfect code as described by Golay.\n\nParameters:\n  - `n::Int`: The block length of words in the code (e.g., word \"abc\" has block length 3).\n  - `k::Int`: The dimension of the code.\n  - `d::Int`: The distance of the code (i.e., the minimum distance between codewords in the code).\n  - `q::Int`: An Int that is a prime power.  The modulus of the finite field.\n  \nReturns:\n  - `Bool`: true or false.\n\n---\n\n### Examples\n\n```julia\njulia> isgolayperfect(11, 6, 5, 3) # this is one of golay's perfect codes\ntrue\n```\n\"\"\"\nfunction isgolayperfect(n::T, k::T, d::T, q::T) where T <: Int\n\tisprimepower(q) ||  false # we are working in finite fields, so q must be a prime power\n    M = q^k\n    (isequal(q, 2) && isequal(n, 23) && isequal(d, 7) && isequal(M, 2^12)) && return true\n    (isequal(q, 3) && isequal(n, 11) && isequal(d, 5) && isequal(M, 3^6)) && return true\n    return false\nend\n", "meta": {"hexsha": "ea30740cb3b78fa94d79ef10df4013732b18148f", "size": 9229, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bounds.jl", "max_stars_repo_name": "jakewilliami/CodingTheory.jl", "max_stars_repo_head_hexsha": "44b1fa85b1124c9d4ec7d5776ad988d028a65ccf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-10-05T21:24:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T21:20:06.000Z", "max_issues_repo_path": "src/bounds.jl", "max_issues_repo_name": "jakewilliami/CodingTheory.jl", "max_issues_repo_head_hexsha": "44b1fa85b1124c9d4ec7d5776ad988d028a65ccf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-10-23T08:08:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-12T09:59:12.000Z", "max_forks_repo_path": "src/bounds.jl", "max_forks_repo_name": "jakewilliami/CodingTheory.jl", "max_forks_repo_head_hexsha": "44b1fa85b1124c9d4ec7d5776ad988d028a65ccf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-11T06:03:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T06:03:22.000Z", "avg_line_length": 27.2241887906, "max_line_length": 175, "alphanum_fraction": 0.6172933146, "num_tokens": 3253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7588751485327334}}
{"text": "export HPolygon, add_point!, npoints, RandomHPolygon, sides\nexport polygon_check\n\n\"\"\"\n`HPolygon()` creates a new polygon (with no points).\n\n`HPolygon(list)` creates a polygon whose points are specified in `list`.\n\nSee: `add_point!`\n\"\"\"\nstruct HPolygon <: HObject\n    plist::Array{HPoint,1}\n    attr::Dict{Symbol,Any}\n    function HPolygon()\n        X = new(HPoint[],Dict{Symbol,Any}())\n        set_color(X)\n        set_thickness(X)\n        set_line_style(X)\n        return X\n    end\nend\n\n\n\"\"\"\n`add_point!(X::HPolygon, P::HPoint)` adds the point `P`\nas the last point of the polygon `X`\n\"\"\"\nadd_point!(X::HPolygon, P::HPoint) = push!(X.plist,P)\n\n\"\"\"\n`endpoints(X::HPolygon)` returns the list of vertices (in order)\nof the polygon.\n\"\"\"\nendpoints(X::HPolygon) = deepcopy(X.plist)\n\n\n\"\"\"\n`sides(P:::HPolygon/HTriangle)` returns a list of the line segments\nthat are the sides of the polygon.\n\"\"\"\nfunction sides(X::HPolygon)::Array{HSegment,1}\n    n = npoints(X)\n    if n < 2\n        return HSegment[]\n    end\n\n    result = Array{HSegment,1}(undef,n)\n    for k=1:n-1\n        a = X.plist[k]\n        b = X.plist[k+1]\n        result[k] = a+b\n    end\n    result[end] = X.plist[end] + X.plist[1]\n    return result\nend\n\nsides(T::HTriangle) = sides(HPolygon(T))\n\n\n\"\"\"\n`npoints(X::HPolygon)` returns the number of points on the polygon.\n\"\"\"\nnpoints(X::HPolygon) = length(X.plist)\n\nfunction HPolygon(pts::Array{HPoint,1})\n    X = HPolygon()\n    for p in pts\n        add_point!(X,p)\n    end\n    return X\nend\n\nHPolygon(pts...) = HPolygon(collect(pts))\nHPolygon(X::HPolygon) = HPolygon(X.plist)  # copy constructor\n\n\"\"\"\n`polygon_check(X::HPolygon,quiet=true)` checks that the polygon is nondegenerate.\nPossible degeneracies are:\n+ Repeated vertices\n+ Fewer than three distinct vertices\n+ Angles that are either 0 degrees or 180 degrees\nIf `quiet` is `false`, then a reason for the failed check is printed.\n\"\"\"\nfunction polygon_check(X::HPolygon, quiet::Bool=true)::Bool\n\n    # Check that the endpoints are all distinct\n    n = npoints(X)\n\n    C = HContainer(X.plist...)\n    if length(C) != n\n        quiet || println(\"The polygon has repeated vertices\")\n        return false\n    end\n\n    if length(C) < 3\n        quiet || println(\"The polygon is degenerate (fewer than 3 distinct vertices)\")\n        return false\n    end\n\n    angs = angles(X)\n    zero_angs = angs .< (THRESHOLD * eps(1.0))\n    if any(zero_angs)\n        quiet || println(\"The polygon has 0-degree angles\")\n        return false\n    end\n\n    big_angs = angs .> (pi - THRESHOLD*eps(1.0))\n    if any(big_angs)\n        quiet || println(\"The polygon has 180-degree angles\")\n        return false\n    end\n\n    return true\nend\n\n\n\n\n\n\nfunction HPolygon(T::HTriangle)\n    a,b,c = endpoints(T)\n    return HPolygon(a,b,c)\nend\n\n\nfunction HTriangle(X::HPolygon)\n    @assert npoints(X)==3 \"Can only convert a 3-point HPolygon into an HTriangle\"\n    return HTriangle(X.plist...)\nend\n\n\"\"\"\n`RandomHPolygon(n::Int,simple::Bool=false)` create a new `HPolygon` with\n`n` points chosen at random. With `simple` set to `true`, return a polygon\nthat does not self-intersect.\n\"\"\"\nfunction RandomHPolygon(n::Int, simple::Bool=false)\n    @assert n>=0 \"Number of vertices must be nonnegative\"\n    if simple && n>3\n        P = RandomHPolygon(n)\n        while !is_simple(P)\n            P = RandomHPolygon(n)\n        end\n        return P\n    end\n\n    pts = [ RandomHPoint() for j=1:n ]\n    return HPolygon(pts)\nend\n\n\"\"\"\n`angles(P::HPolygon)` returns a list of the angles at the vertices of `P`.\n\n+ The results are always in the interval `[0,pi]`.\n+ The order of the angles is the order of the vertices in `P.plist`.\n\"\"\"\nfunction angles(P::HPolygon)::Array{Float64,1}\n    n = npoints(P)\n    result = zeros(Float64,n)\n    if n < 3\n        return result\n    end\n\n    # first angle\n    result[1] = angle(P.plist[end],P.plist[1],P.plist[2])\n\n    for j=2:n-1\n        result[j] = angle(P.plist[j-1], P.plist[j], P.plist[j+1])\n    end\n\n    result[n] = angle(P.plist[n-1],P.plist[n],P.plist[1])\n\n    return result\nend\n\n\nfunction perimeter(P::HPolygon)\n    n = npoints(P)\n    if n < 2\n        return 0.0\n    end\n    result = dist(P.plist[1],P.plist[end])\n    if n==2\n        return 2*result\n    end\n    for j=1:n-1\n        result += dist(P.plist[j],P.plist[j+1])\n    end\n    return result\nend\n\n\n\nfunction show(io::IO,X::HPolygon)\n    print(io,\"HPolygon with $(npoints(X)) points\")\nend\n\n# require 0 <= k < n\n\"\"\"\n`_cycle(A,k)` returns a `k`-step shift of `A`. We require\n`k` to be in the interval `[0,n-1]` where `n=length(A)`.\nNo checking is done.\n\"\"\"\nfunction _cycle(A::Array{T,1}, k::Int) where T\n    n = length(A)\n    B = Array{T,1}(undef,n)\n    for t = 1:n-k\n        @inbounds B[t] = A[t+k]\n    end\n    for t = 1:k\n        @inbounds B[n-k+t] = A[t]\n    end\n    return B\nend\n\n\"\"\"\n`_cyclic_equal(A,B)` checks if some cyclic shift of one list\nequals the other.\n\"\"\"\nfunction _cyclic_equal(A::Array{S,1}, B::Array{T,1}) where {S,T}\n    n = length(A)\n    if length(B) != n\n        return false\n    end\n    for s=0:n-1\n        if A == _cycle(B,s)\n            return true\n        end\n    end\n    return false\nend\n\n(==)(X::HPolygon, Y::HPolygon) = _cyclic_equal(X.plist, Y.plist) ||\n    _cyclic_equal(X.plist,reverse(Y.plist))\n\n\n\n\"\"\"\n`is_simple(X::HPolygon)` determines if the polygon edges do not self-intersect.\nBe sure the polygon is legit using `polygon_check` first.\n\"\"\"\nfunction is_simple(X::HPolygon)\n    n = npoints(X)\n    if n <= 3\n        return true   # triangles are fine\n    end\n    slist = sides(X)\n    for i=1:n-2\n        for j=i+2:n\n            if i==1 && j==n\n                continue\n            end\n            if meet_check(slist[i], slist[j])\n                return false\n            end\n        end\n    end\n    return true\nend\n", "meta": {"hexsha": "63ceed936e36baa3bfa0320f2a52a50a9692d87d", "size": 5746, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polygon.jl", "max_stars_repo_name": "switzel/HyperbolicPlane.jl", "max_stars_repo_head_hexsha": "89ba26e080b520b4f200e985f2b431b1d61ecb21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-01-19T06:12:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T22:18:48.000Z", "max_issues_repo_path": "src/polygon.jl", "max_issues_repo_name": "switzel/HyperbolicPlane.jl", "max_issues_repo_head_hexsha": "89ba26e080b520b4f200e985f2b431b1d61ecb21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-01-31T08:33:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T19:44:39.000Z", "max_forks_repo_path": "src/polygon.jl", "max_forks_repo_name": "switzel/HyperbolicPlane.jl", "max_forks_repo_head_hexsha": "89ba26e080b520b4f200e985f2b431b1d61ecb21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-31T21:10:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T18:49:43.000Z", "avg_line_length": 22.1, "max_line_length": 86, "alphanum_fraction": 0.6122520014, "num_tokens": 1685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7588403513476881}}
{"text": "# # Example (Ch. 9 Bathe)\n\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/models/example_9_1_Bathe.ipynb)\n#\n\n# The example considered next can be found in Chapter 9 of [[BATHE]](@ref).\n\nusing StructuralDynamicsODESolvers, Plots\n\n# ## Problem formulation\nM = [2 0; 0 1.]\nK = [6 -2; -2 4.]\nC = zeros(2, 2)\nf = [0.0, 10.0]\nexample_9_1_Bathe = SecondOrderAffineContinuousSystem(M, C, K, f)\n\nNSTEPS = 500\ntdom = range(0, NSTEPS * 0.1, length=NSTEPS + 1)\nU₀, U₀′ = zeros(2), zeros(2)\nprob = InitialValueProblem(example_9_1_Bathe, (U₀, U₀′))\n\n# ## Analytic solution\nA = [1/√3  (1/2)*√(2/3);\n     1/√3      -√(2/3)]\nx₁(t) = (5 / √3) * (1 - cos(t*√2))\nx₂(t) = (2 * √(2/3)) * (-1 + cos(t*√5))\nU(t) = A * [x₁(t), x₂(t)]\n\n# ## Central difference\n\nsol = solve(prob, CentralDifference(Δt=0.1); NSTEPS=NSTEPS) |> displacements\nind = 150:170\nfig = plot(xlab=\"time\", ylab=\"x1(t)\", legend=:outertopright)\nfig2 = plot(xlab=\"time\", ylab=\"x1(t)\", legend=:outertopright)\nplot!(fig, tdom, [s[1] for s in sol], lab=\"Central difference\")\nplot!(fig2, tdom[ind], [s[1] for s in sol[ind]], lab=\"Central difference\")\n\n# ## Houbolt\n\nsol = solve(prob, Houbolt(Δt=0.1); NSTEPS=NSTEPS) |> displacements\nplot!(fig, tdom, [s[1] for s in sol], lab=\"Houbolt\")\nplot!(fig2, tdom[ind], [s[1] for s in sol[ind]], lab=\"Houbolt\")\n\n# ## Newmark\n\nsol = solve(prob, Trapezoidal(Δt=0.1); NSTEPS=NSTEPS) |> displacements\nplot!(fig, tdom, [s[1] for s in sol], lab=\"Newmark\")\nplot!(fig2, tdom[ind], [s[1] for s in sol[ind]], lab=\"Newmark\")\n\n# ## Bathe\n\nsol = solve(prob, Bathe(Δt=0.1); NSTEPS=NSTEPS) |> displacements\nplot!(fig, tdom, [s[1] for s in sol], lab=\"Bathe\")\nplot!(fig2, tdom[ind], [s[1] for s in sol[ind]], lab=\"Bathe\")\n\n# ## Analytic solution\n\ntdom = range(0, NSTEPS*0.1, length=1000)\nplot!(fig, tdom, [U(t)[1] for t in tdom], lab=\"Analytic\")\nplot!(fig2, tdom[299:330], [U(t)[1] for t in tdom[299:330]], lab=\"Analytic\")\n", "meta": {"hexsha": "6d12102b90615281d8549c0daeea4c63c5b8e26e", "size": 1925, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example_9_1_Bathe.jl", "max_stars_repo_name": "ONSAS/StructuralDynamicsODESolvers.jl", "max_stars_repo_head_hexsha": "88fa774de9f57ee789801fb188a4f5e91366dcb5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-09T16:44:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T14:34:41.000Z", "max_issues_repo_path": "examples/example_9_1_Bathe.jl", "max_issues_repo_name": "ONSAS/StructuralDynamicsODESolvers.jl", "max_issues_repo_head_hexsha": "88fa774de9f57ee789801fb188a4f5e91366dcb5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2021-02-10T12:55:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T11:26:31.000Z", "max_forks_repo_path": "examples/example_9_1_Bathe.jl", "max_forks_repo_name": "ONSAS/StructuralDynamicsODESolvers.jl", "max_forks_repo_head_hexsha": "88fa774de9f57ee789801fb188a4f5e91366dcb5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5573770492, "max_line_length": 121, "alphanum_fraction": 0.6311688312, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970717197768, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.7588403304758852}}
{"text": "export i_mean_sum, i_var_mean_sum, i_normal_logpdf, i_cor_cov\n\n\"\"\"\n    i_mean_sum(out!, sum!, x)\n\nget the `mean` and `sum` of `x`.\n\"\"\"\n@i function i_mean_sum(out!, sum!, x)\n    for i=1:length(x)\n        sum! += x[i]\n    end\n    out! += sum!/length(x)\nend\n\n\"\"\"\n    i_var_mean_sum(var!, varsum!, mean!, sum!, sqv)\n\nCompute the variance, the accumulated variance, mean and sum.\n\"\"\"\n@i function i_var_mean_sum(var!, varsum!, mean!, sum!, v::AbstractVector{T}) where T\n    i_mean_sum(mean!, sum!, v)\n    for i=1:length(v)\n        v[i] -= mean!\n        varsum! += v[i] ^ 2\n        v[i] += mean!\n    end\n    var! += varsum! / (length(v)-1)\nend\n\n\"\"\"\n    i_normal_logpdf(out, x, μ, σ)\n\nget the pdf of `Normal(μ, σ)` at point `x`.\n\"\"\"\n@i function i_normal_logpdf(out, x::T, μ, σ) where T\n    @zeros T anc1 anc2 anc3\n\n    @routine begin\n        anc1 += x\n        anc1 -= μ\n        anc2 += anc1 / σ  # (x- μ)/σ\n        anc3 += anc2^2 # (x-μ)^2/σ^2\n    end\n\n    out -= anc3 * 0.5 # -(x-μ)^2/2σ^2\n    out -= log(σ) # -(x-μ)^2/2σ^2 - log(σ)\n    out -= log(2π)/2 # -(x-μ)^2/2σ^2 - log(σ) - log(2π)/2\n\n    ~@routine\nend\n\n\"\"\"\n     i_cor_cov(rho!,cov!,a,b)\n\nget Pearson correlation and covariance of two vectors `a` and `b` \n\n\"\"\"\n\n@i function i_cor_cov(rho!::T,cov!::T,a::AbstractVector{T},b::AbstractVector{T}) where T\n    @safe @assert length(a) == length(b)\n    @routine  @invcheckoff begin\n        @zeros T var1 varsum1 mean1 sum1 std1\n        i_var_mean_sum(var1, varsum1, mean1, sum1, a)\n        std1 += sqrt(var1)\n        @zeros T var2 varsum2 mean2 sum2 std2\n        i_var_mean_sum(var2, varsum2, mean2, sum2, b)\n        std2 += sqrt(var2)\n        @zeros T anc3 anc4 anc5 anc6 anc7\n        @inbounds for i=1:length(b)\n            a[i] -= mean1\n            anc3 += a[i]\n            b[i] -= mean2\n            anc4 += b[i]\n            anc5 += anc3*anc4\n            anc3 -= a[i]\n            anc4 -= b[i]\n            a[i] += mean1\n            b[i] += mean2     \n        end\n        anc6+=std1*std2\n        anc7+=anc6*(length(b)-1)\n    end\n        cov! += anc5/(length(b)-1)\n        rho! += anc5/anc7 \n    ~@routine\nend\n", "meta": {"hexsha": "fe03963c3799915eb56aafb505b6857a829d6175", "size": 2103, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stdlib/statistics.jl", "max_stars_repo_name": "HanLi123/NiLang.jl", "max_stars_repo_head_hexsha": "a485b7f3f4d3d03dbcaa4ee96ef2e6f6a68cdc1f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stdlib/statistics.jl", "max_issues_repo_name": "HanLi123/NiLang.jl", "max_issues_repo_head_hexsha": "a485b7f3f4d3d03dbcaa4ee96ef2e6f6a68cdc1f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stdlib/statistics.jl", "max_forks_repo_name": "HanLi123/NiLang.jl", "max_forks_repo_head_hexsha": "a485b7f3f4d3d03dbcaa4ee96ef2e6f6a68cdc1f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1724137931, "max_line_length": 88, "alphanum_fraction": 0.5249643367, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8104789109591831, "lm_q1q2_score": 0.7588392474833028}}
{"text": "# Represents an N-dimensional ellipsoid\nstruct Ellipsoid\n    ctr::Vector{Float64}  # center coordinates\n    cov::Array{Float64, 2}\n    icov::Array{Float64, 2}  # inverse of cov\n    vol::Float64\nend\n\n# Draw a random point from within a unit N-ball\nfunction randnball(ndim)\n    z = randn(ndim)\n    r2 = 0.\n    for i=1:ndim\n        r2 += z[i]*z[i]\n    end\n    factor = rand()^(1. /ndim) / sqrt(r2)\n    for i=1:ndim\n        z[i] *= factor\n    end\n    return z\nend\n\n# proportionality constant depending on dimension\n# for n even:      (2pi)^(n    /2) / (2 * 4 * ... * n)\n# for n odd :  2 * (2pi)^((n-1)/2) / (1 * 3 * ... * n)\nfunction nball_vol_factor(ndim::Int)\n    if ndim % 2 == 0\n        c = 1.\n        for i=2:2:ndim\n            c *= 2pi / i\n        end\n        return c\n    else\n        c = 2.\n        for i = 3:2:ndim\n            c *= 2pi / i\n        end\n        return c\n    end\nend\n\nfunction ellipsoid_volume(scaled_cov::Matrix{Float64})\n    ndim = size(scaled_cov, 1)\n    return nball_vol_factor(ndim) * sqrt(det(scaled_cov))\nend\n\n# find the bounding ellipsoid of points x where \nfunction bounding_ellipsoid(x::Matrix{Float64}, enlarge=1.0)\n\n    ndim, npoints = size(x)\n\n    ctr = mean(x, dims=2)[:, 1]\n    delta = x .- ctr\n    cov = unscaled_covzm(delta, 2)\n    icov = inv(cov)\n\n    # Calculate expansion factor necessary to bound each point.\n    # This finds the maximum of (delta_i' * icov * delta_i)\n    fmax = -Inf\n    for k in 1:npoints\n        f = 0.0\n        for j=1:ndim\n            for i=1:ndim\n                f += icov[i, j] * delta[i, k] * delta[j, k]\n            end\n        end\n        fmax = max(fmax, f)\n    end\n\n    fmax *= enlarge\n    cov .*= fmax\n    icov .*= 1. /fmax\n    vol = ellipsoid_volume(cov)\n\n    return Ellipsoid(ctr, cov, icov, vol)\nend\n\nfunction sample_ellipsoid(ell::Ellipsoid)\n    ndim = length(ell.ctr)\n\n    # Get scaled eigenvectors (in columns): vs[:,i] is the i-th eigenvector.\n    f = eigen(ell.cov)\n    v, w = f.vectors, f.values\n    for j=1:ndim\n        tmp = sqrt(abs(w[j]))\n        for i=1:ndim\n            v[i, j] *= tmp\n        end\n    end\n\n    return v*randnball(ndim) + ell.ctr\nend", "meta": {"hexsha": "d0fe17dfd01865de87e7dd9cd9b3469201d18bee", "size": 2133, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utilities/ellipsoid.jl", "max_stars_repo_name": "mmattocks/GMC_NS", "max_stars_repo_head_hexsha": "0849facc0e2695b6f7dbce2ab170aeb4762fa919", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utilities/ellipsoid.jl", "max_issues_repo_name": "mmattocks/GMC_NS", "max_issues_repo_head_hexsha": "0849facc0e2695b6f7dbce2ab170aeb4762fa919", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utilities/ellipsoid.jl", "max_forks_repo_name": "mmattocks/GMC_NS", "max_forks_repo_head_hexsha": "0849facc0e2695b6f7dbce2ab170aeb4762fa919", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1847826087, "max_line_length": 76, "alphanum_fraction": 0.5550867323, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480347, "lm_q2_score": 0.8104789040926009, "lm_q1q2_score": 0.7588392453770018}}
{"text": "module HermiteNormalForm\n\nusing LinearAlgebra\nexport hnf!, hnf, ishnf\n\n\"\"\"\n    ishnf(A)\n\nCheck if matrix `A` is in Hermite norm form.\n\"\"\"\nfunction ishnf(A)\n    m, n = size(A)\n    for j in 1:n\n        for i in 1:min(m, j-1)\n            A[i, j] == 0 || return false\n        end\n        if m >= j\n            A[j, j] > 0 || return false\n        end\n    end\n    for i in 1:min(m, n)\n        p = A[i, i]\n        for j in 1:min(n, i-1)\n            0 <= A[i, j] < p || return false\n        end\n    end\n    return true\nend\n\n\"\"\"\n    H, U = hnf(A)\n\n`U` is unimodular and `H` is the Hermite normal form of `A`. If `A` is singular,\nthen it returns `nothing`.\n\"\"\"\nhnf(A) = hnf!(copy(A))\n\nfunction hnf!(A)\n    m, n = size(A)\n    T = eltype(A)\n    U = Matrix{T}(I, n, n)\n    zz = zero(T)\n    for k in 1:m\n        # Pivot: A[k, k] should not be 0\n        if n >= k && A[k, k] == zz\n            pivot = k\n            for j in k+1:n\n                if A[k, j] != zz\n                    pivot = j\n                end\n            end\n            pivot == k && return nothing # rank deficient\n            for i in 1:m\n                A[i, k], A[i, pivot] = A[i, pivot], A[i, k]\n            end\n            for i in 1:n\n                U[i, k], U[i, pivot] = U[i, pivot], U[i, k]\n            end\n        end\n        # [A11   0 ] k-1 rows\n        # [A21  A22]\n        # Zero out A[k, k+1:n] === A22[1, 2:end] by multiplying\n        # [p  -A[k, j]/d]\n        # [q   A[k, k]/d]\n        for j in k+1:n\n            Akk, Akj = A[k, k], A[k, j]\n            d, p, q = gcdx(Akk, Akj)\n            Akkd, Akjd = div(Akk, d), div(Akj, d)\n            for i in 1:m\n                Aik, Aij = A[i, k], A[i, j]\n                A[i, k] = Aik * p + Aij * q\n                A[i, j] = -Aik * Akjd + Aij * Akkd\n            end\n            for i in 1:n\n                Uik, Uij = U[i, k], U[i, j]\n                U[i, k] = Uik * p + Uij * q\n                U[i, j] = -Uik * Akjd + Uij * Akkd\n            end\n        end\n        n >= k || continue\n        # Ensure the positivity of A[k, k]\n        if A[k, k] < zz\n            @. A[:, k] = -A[:, k]\n            @. U[:, k] = -U[:, k]\n        end\n        # Minimize A[k, 1:k-1] === A21[1, :]\n        for j in 1:k-1\n            mul = fld(A[k, j], A[k, k])\n            @. A[:, j] -= mul * A[:, k]\n            @. U[:, j] -= mul * U[:, k]\n        end\n    end\n    A, U\nend\n\nend\n", "meta": {"hexsha": "aad075ec52f3291ae3a1832801e1c352b6e42882", "size": 2375, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HermiteNormalForm.jl", "max_stars_repo_name": "YingboMa/HermiteNormalForm.jl", "max_stars_repo_head_hexsha": "6b22513607fd583e39b3f06c0db4fbe7a77427b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-14T01:02:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T13:05:06.000Z", "max_issues_repo_path": "src/HermiteNormalForm.jl", "max_issues_repo_name": "YingboMa/HermiteNormalForm.jl", "max_issues_repo_head_hexsha": "6b22513607fd583e39b3f06c0db4fbe7a77427b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HermiteNormalForm.jl", "max_forks_repo_name": "YingboMa/HermiteNormalForm.jl", "max_forks_repo_head_hexsha": "6b22513607fd583e39b3f06c0db4fbe7a77427b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4845360825, "max_line_length": 80, "alphanum_fraction": 0.3747368421, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7588392453770015}}
{"text": "# Hessian Eigenmaps (HLLE)\n# ---------------------------\n# Hessian eigenmaps: Locally linear embedding techniques for high-dimensional data,\n# D. Donoho and C. Grimes, Proc Natl Acad Sci U S A. 2003 May 13; 100(10): 5591–5596\n\n#### HLLE type\nimmutable HLLE{T <: Real} <: SpectralResult\n    k::Int\n    λ::AbstractVector{T}\n    proj::Projection{T}\n\n    HLLE{T}(k::Int, λ::AbstractVector{T}, proj::Projection{T}) = new(k, λ, proj)\nend\n\n## properties\noutdim(M::HLLE) = size(M.proj, 1)\nprojection(M::HLLE) = M.proj\n\neigvals(M::HLLE) = M.λ\nneighbors(M::HLLE) = M.k\n\n## show & dump\nfunction show(io::IO, M::HLLE)\n    print(io, \"Hessian Eigenmaps(outdim = $(outdim(M)), neighbors = $(neighbors(M)))\")\nend\n\nfunction dump(io::IO, M::HLLE)\n    show(io, M)\n    println(io, \"eigenvalues: \")\n    Base.showarray(io, M.λ', header=false, repr=false)\n    println(io)\n    println(io, \"projection:\")\n    Base.showarray(io, M.proj, header=false, repr=false)\nend\n\n## interface functions\nfunction transform{T<:Real}(::Type{HLLE}, X::DenseMatrix{T}; d::Int=2, k::Int=12)\n    n = size(X, 2)\n\n    # Identify neighbors\n    D, I = find_nn(X, k)\n\n    # Obtain tangent coordinates and develop Hessian estimator\n    hs = Int(d*(d+1)/2)\n    W = spzeros(hs*n,n)\n    for i=1:n\n        # re-center points in neighborhood\n        μ = mean(X[:,I[:,i]],2)\n        N = X[:,I[:,i]] .- μ\n        # calculate tangent coordinates\n        #tc = svdfact(N')[:U][:,1:d]\n        tc = svdfact(N)[:V][:,1:d]\n\n        # Develop Hessian estimator\n        Yi = [ones(k) tc zeros(k,hs)]\n        for ii=1:d\n            Yi[:,d+ii+1] = tc[:,ii].^2\n        end\n        yi = 2(1+d)\n        for (ii,jj) in combinations(1:d,2)\n            Yi[:, yi] = tc[:, ii] .* tc[:, jj]\n            yi += 1\n        end\n        F = qrfact(Yi)\n        H = full(F[:Q])[:,d+2:end]'\n        W[(i-1)*hs+(1:hs),I[:,i]] = H\n    end\n\n    # decomposition\n    λ, V = decompose(W'*W, d)\n    return HLLE{T}(k, λ, V' .* sqrt(n))\nend", "meta": {"hexsha": "41c0df8bdb65d9dd1edf4cc1574429987daf1f40", "size": 1945, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hlle.jl", "max_stars_repo_name": "JuliaPackageMirrors/ManifoldLearning.jl", "max_stars_repo_head_hexsha": "4f994ed07f1f7cd62c5b36efae9db473a5031ac3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hlle.jl", "max_issues_repo_name": "JuliaPackageMirrors/ManifoldLearning.jl", "max_issues_repo_head_hexsha": "4f994ed07f1f7cd62c5b36efae9db473a5031ac3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hlle.jl", "max_forks_repo_name": "JuliaPackageMirrors/ManifoldLearning.jl", "max_forks_repo_head_hexsha": "4f994ed07f1f7cd62c5b36efae9db473a5031ac3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0138888889, "max_line_length": 86, "alphanum_fraction": 0.5496143959, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7587951633361104}}
{"text": "\nusing SatisfiabilityInterface, Symbolics\n\n\"Constraints representing different colours for each edge of a graph\"\ndifferent_colours(E, c) = [c[i] ≠ c[j] for (i, j) in E]\n\n\n\n\n\"k is the number of colours\"\nfunction graph_colouring_problem(V, E, k=3)\n\n    colours = [:red, :green, :yellow, :blue, :black][1:k]\n    # c = [Num(Variable(:c, i)) for i in 1:length(V)]   # colour variables\n\n    @variables c[1:length(V)]\n    \n    constraints = \n    [ \n        [c[i] ∈ colours for i in 1:length(V)]\n        \n        [c[i] ≠ c[j] for (i, j) in E]  #  different_colours(E, c)\n    ]\n\n    return DiscreteCSP(constraints)\nend\n\n\n# cs = [Num(Variable(:c, i)) for i in 1:length(V)]   # colour variables\n\n\n# constraints = [ \n#     [c ∈ colours for c in cs]\n#     different_colours(E, cs)\n# ]\n\n\n\nV = [1, 2, 3]  # vertices\nE = [(1, 2), (2, 3)]  # edges\n\nprob = graph_colouring_problem(V, E, 2)\nstatus, results = solve(prob)\n\n# final_colours = [second(results[k]) for k in prob.original_vars]\n\n# # check that it satisfies the constraint:\n# all(different_neighbours(E, final_colours))\n\n\n## Ring graph \n\nfunction ring_graph(n=11)\n    V = 1:n\n    E = [(i, mod1((i+1), n)) for i in 1:n]\n    \n    return V, E\nend\n\nV, E = ring_graph(11)\n\nprob = graph_colouring_problem(V, E, 2)\nstatus, results = solve(prob)\n\n\nprob = graph_colouring_problem(V, E, 3)\nstatus, results = solve(prob)\nstatus==:sat\n\n# final_colours = [results[k] for k in prob.variables]\n# all(different_neighbours(E, final_colours))\n\n\n\n\nk = 3\ncolours = [:red, :green, :yellow, :blue, :black][1:k]\n\nc = [Num(Variable(:c, i)) for i in 1:length(V)]   # colour variables\n\n\nconstraints = \n    [ \n        [c[i] ∈ colours for i in 1:length(V)]\n        \n        [c[i] ≠ c[j] for (i, j) in E]  #  different_colours(E, c)\n    ]\n\nconstraints\n\nprob = ConstraintSatisfactionProblem(constraints)\nprob2 = DiscreteCSP(prob)\n\nsolve(prob2)\n\n\nk = 3\n\n\n", "meta": {"hexsha": "9b969fd4e9fa5390a70eb4bef8c5f6c077bf3a17", "size": 1865, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/graph_colouring.jl", "max_stars_repo_name": "Wimmerer/SatisfiabilityInterface.jl", "max_stars_repo_head_hexsha": "b2148fadf45dca6304e9f4b571d1e3ea54c85ba4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-01-15T22:50:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T22:24:42.000Z", "max_issues_repo_path": "examples/graph_colouring.jl", "max_issues_repo_name": "Wimmerer/SatisfiabilityInterface.jl", "max_issues_repo_head_hexsha": "b2148fadf45dca6304e9f4b571d1e3ea54c85ba4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-06-26T21:09:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-08T12:12:43.000Z", "max_forks_repo_path": "examples/graph_colouring.jl", "max_forks_repo_name": "Wimmerer/SatisfiabilityInterface.jl", "max_forks_repo_head_hexsha": "b2148fadf45dca6304e9f4b571d1e3ea54c85ba4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-06-25T20:22:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:47:46.000Z", "avg_line_length": 18.65, "max_line_length": 74, "alphanum_fraction": 0.6166219839, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.758764140783664}}
{"text": "\r\n\r\n\r\ncigar(x) = x[1]^2 + 1 * sum(abs2, view(x, 2:length(x)))   # 1e6\r\n\r\ncigtab(x) = x[1]^2 + 1 * x[end]^2 + 1e4 * sum(abs2, view(x, 2:length(x)-1)) # 1e8\r\n\r\n\r\nfunction griewank(x)\r\n  n = length(x)\r\n  1 + (1/4000)*sum(abs2, (x.+7)) - prod(cos.((x.+7) ./ sqrt.(1:n)))\r\nend\r\n\r\n\r\nfunction rosenbrock2d(x)\r\n  return sum((x).*(x).*cos.((x)).*sin.((x.-5)))+200\r\nend\r\n\r\nfunction quartic(x)\r\n  D = length(x)\r\n  sum( (1:D) .* (x.-2).^4 )\r\nend\r\n\r\nfunction schwefel1_2(x)\r\n  D = length(x)\r\n  partsums = zeros(D)\r\n  partsum = 0\r\n  for i in 1:D\r\n    partsum += x[i]-9\r\n    partsums[i] = partsum\r\n  end\r\n  sum(abs2, partsums)\r\nend\r\n\r\nfunction ellipsoid(x)\r\n    res = 0.0\r\n    cumsum = 0.0\r\n    for xx in x\r\n        cumsum += xx-sqrt(2)\r\n        res += cumsum^2\r\n    end\r\n    res\r\nend\r\n\r\nfunction elliptic(x)\r\n  D = length(x)\r\n  condition = 1e+3\r\n  if D==1\r\n      coefficients=1\r\n  else\r\n      coefficients = condition .^ range(0,stop=1,length=D)\r\n  end\r\n  sum(coefficients .* (x.+3/2).^2)\r\nend\r\n\r\nfunction rastrigin(x)\r\n  D = length(x)\r\n  10 * D + sum(abs2, (x.+0.7)) - 10 * sum(xx -> cos.(2π * xx), (x.+0.7))\r\nend\r\n\r\nfunction sphere(x)\r\n  sum(abs2, (x.-1.3))\r\nend\r\n\r\n\r\nfunction sin_01_x_2(x)\r\n  sum(sin.((x.+0.7))+0.01.*(x.+0.7).^2)\r\nend\r\n\r\nfunction x_i(x)\r\n  ress=0\r\n  for i=1:length(x)\r\n    ress+=(x[i]-i-2.1)^2\r\n  end\r\n  return ress\r\nend\r\n\r\nfunction x_5_sq(x)\r\n  sum((x.-5).^2).-5\r\nend\r\n\r\nfunction x_plus_y(x)\r\n    ress=0\r\n    for i=1:length(x)\r\n      ress+=x[i]\r\n    end\r\n    return ress\r\nend\r\n\r\n#\r\n\r\n\r\nfunction rand_poly(x)\r\n    return sum(rand(length(x)).*x)\r\nend\r\n    \r\n# rand_poly(rand(10))\r\n# x=-10:0.001:10\r\n# y=sin.(10rand()x).+(rand()/1000)x.^2\r\n# plot(x,y)\r\n\r\n# function limited_domain(x::Vector)::Float64\r\n#   sum( sqrt.(1 ./ (x.+1) .+ (x.+1) ) )  ## min is at 1,1,1...\r\n# end#function\r\n# limited_domain(rand(9))\r\n\r\n\r\n# x=-10:0.01:10\r\n\r\n# y=rand()rastrigin.(x)-.010rand()elliptic.(x)\r\n# scatter(x,y)\r\n\r\n\r\nfunction alpine_1(x)\r\n  return sum(abs.(x.*sin.(x)+0.1x))\r\nend", "meta": {"hexsha": "e82573ae3e204ee9d137b73050ca22c98b1cb850", "size": 1968, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "functions_opti.jl", "max_stars_repo_name": "nbakas/BNO.jl", "max_stars_repo_head_hexsha": "b8be07be915dd284a50a3e918d8b6e7a94aaf3a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-28T18:33:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-28T18:33:18.000Z", "max_issues_repo_path": "functions_opti.jl", "max_issues_repo_name": "nbakas/BNO.jl", "max_issues_repo_head_hexsha": "b8be07be915dd284a50a3e918d8b6e7a94aaf3a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions_opti.jl", "max_forks_repo_name": "nbakas/BNO.jl", "max_forks_repo_head_hexsha": "b8be07be915dd284a50a3e918d8b6e7a94aaf3a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-14T17:39:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T17:39:27.000Z", "avg_line_length": 16.9655172414, "max_line_length": 82, "alphanum_fraction": 0.5304878049, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7587641304101901}}
{"text": "# Example that computes the full inverse wavelet transform using all the \n# scales from Jmin=1, to Jmax=log2(n)-1 the coarsest scale\n\n#push path \npush!(LOAD_PATH,pwd()*\"/src\") # for julia 0.4 you need to put your path\n#import libraries\nusing FWT\nusing PyPlot\nusing Images\n\nn = 1024;\nname = \"data_samples/ernst_reuter_haus.bmp\";\nf = load_image(name, n);\nf = rescale(sum(f,3));\nf = f[:,:,1];\n\n# filter call \nh=filt_gen(WT.db2)\n# high pass filter\ng = cat(1, 0, h[length(h):-1:2]) .* ( (-1).^(1:length(h)) )\ng = cat(1, 0, h[length(h):-1:2]) .* ( (-1).^(1:length(h)) )\n\n# First compute wavelet transform \n# Perform of the wavelet transform\nJmax = round(Int64,log2(n))-1;\nJmin = 1;\nfW = copy(f);\nclf;\nfor j=Jmax:-1:Jmin\n    A = fW[1:2^(j+1),1:2^(j+1)];\n    for d=1:2\n        Coarse = subsampling(cconvol(A,h,d),d);\n        Detail = subsampling(cconvol(A,g,d),d);\n        A = cat(d, Coarse, Detail );\n    end\n    fW[1:2^(j+1),1:2^(j+1)] = A;\n    j1 = Jmax-j;\n    if j1<4\n        imageplot(A[1:2^j,2^j+1:2^(j+1)], \"Horizontal, j=$j\", 3,4, j1 + 1);\n        imageplot(A[2^j+1:2^(j+1),1:2^j], \"Vertical, j=$j\", 3,4, j1 + 5);\n        imageplot(A[2^j+1:2^(j+1),2^j+1:2^(j+1)], \"Diagonal, j=$j\", 3,4, j1 + 9);\n    end\nend\n\n# Now the inverse\n\nf1 = copy(fW);\nclf;\nfor j=Jmin:Jmax\n    A = f1[1:2^(j+1),1:2^(j+1)];\n    for d=1:2\n        if d==1\n            Coarse = A[1:2^j,:];\n            Detail = A[2^j+1:2^(j+1),:];\n        else\n            Coarse = A[:,1:2^j];\n            Detail = A[:,2^j+1:2^(j+1)];                \n        end\n        Coarse = cconvol(upsampling(Coarse,d),FWT.reverse(h),d);\n        Detail = cconvol(upsampling(Detail,d),FWT.reverse(g),d);\n        A = Coarse + Detail;\n        j1 = Jmax-j;\n        if j1>0 && j1<5\n            imageplot(A, \"Partial reconstruction, j=$j\", 2,2,j1);\n        end\n    end\n    f1[1:2^(j+1),1:2^(j+1)] = A;\nend\n", "meta": {"hexsha": "cdd67983a7272d2e015a0aa3c22285cf20c10d0c", "size": 1843, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/full_inv_wavelet_transform.jl", "max_stars_repo_name": "arsenal9971/FWT.jl", "max_stars_repo_head_hexsha": "da066c18515124a7cf70570c9256b43dd1e9099e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-10T01:50:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-10T01:50:00.000Z", "max_issues_repo_path": "examples/full_inv_wavelet_transform.jl", "max_issues_repo_name": "arsenal9971/FWT.jl", "max_issues_repo_head_hexsha": "da066c18515124a7cf70570c9256b43dd1e9099e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/full_inv_wavelet_transform.jl", "max_forks_repo_name": "arsenal9971/FWT.jl", "max_forks_repo_head_hexsha": "da066c18515124a7cf70570c9256b43dd1e9099e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7101449275, "max_line_length": 81, "alphanum_fraction": 0.5306565383, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7587641210690493}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Statistics, DataFrames, CSV, HypothesisTests\n\tusing Random, Distributions, Plots\n\tRandom.seed!(0)\nend;\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.01\"\n\n# ╔═╡ 1aa41898-3afa-11eb-2f49-570853ce6435\nbegin\n\tdata = CSV.read(datadir(\"machine1.csv\"), DataFrame; header=false)[:, 1]\n\txBar, n = mean(data), length(data)\n\tsig = 1.2\n\talpha = 0.1\n\tz = quantile(Normal(),1-alpha/2)\n\n\tText(\"Calculating formula: $((xBar - z*sig/sqrt(n), xBar + z*sig/sqrt(n)))\")\nend\n\n# ╔═╡ 07d8c2c0-3b2e-11eb-344d-c14ab2a82d0d\nText(\"Using confint() function: $(confint(OneSampleZTest(xBar,sig,n),alpha))\")\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.01\"\n\n# ╔═╡ Cell order:\n# ╠═ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═1aa41898-3afa-11eb-2f49-570853ce6435\n# ╠═07d8c2c0-3b2e-11eb-344d-c14ab2a82d0d\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "b4e0e866719a02082bf9b9844f93661e2a2637d6", "size": 1175, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/06/listing6.01.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/06/listing6.01.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/06/listing6.01.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 26.1111111111, "max_line_length": 78, "alphanum_fraction": 0.725106383, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7587641147417311}}
{"text": "#=\r\nCatenary Problem\r\n\r\nThe problem is to find the shape of a hanging chain. It can be defined as the configuration that minimizes the potential energy.\r\n\r\nObjective: linear\r\nConstraints: convex quadratic\r\nFeasible set: convex\r\n\r\nThis model finds the shape of a hanging chain\r\nThe solution is known to be y = cosh(a*x) + b\r\nfor appropriate a and b.\r\n\r\nThis problem is a port to Julia/JuMP of a model by Professor Robert Vanderbei\r\nat Princeton University, originally written in AMPL.\r\nSource: http://orfe.princeton.edu/~rvdb/ampl/nlmodels/\r\n=#\r\n\r\nusing JuMP\r\nusing Ipopt  # Nonlinear solver\r\nusing Gadfly # Graphing support\r\n\r\nN = 100   # number of chainlinks\r\nL = 1     # difference in x-coords of endlinks\r\nh = 2*L/N # length of each link\r\n\r\nm = Model(solver=IpoptSolver())\r\n\r\n@defVar(m, x[0:N])\r\n@defVar(m, y[0:N])\r\n\r\n# Minimize potential energy from center of mass for link\r\n@setObjective(m, Min, sum{(y[j-1] + y[j])/2, j=1:N})\r\n\r\n# Anchor ends\r\n@addConstraint(m, x[0] == 0)\r\n@addConstraint(m, y[0] == 0)\r\n@addConstraint(m, x[N] == L)\r\n@addConstraint(m, y[N] == 0)\r\n\r\n# Set starting values\r\nfor j in 0:N\r\n    setValue(x[j], 0)\r\n    setValue(y[j], 0)\r\nend\r\n\r\n\r\n# Link together pieces\r\nfor j in 1:N\r\n    @addNLConstraint(m,\r\n        (x[j] - x[j-1])^2 + (y[j] - y[j-1])^2 <= h^2\r\n    )\r\nend\r\n\r\nsolve(m)\r\n\r\n# Graph the data\r\n\r\nx_clean = Float64[]\r\ny_clean = Float64[]\r\nfor j in 0:N\r\n    push!(x_clean, getValue(x)[j])\r\n    push!(y_clean, getValue(y)[j])\r\nend\r\n\r\ncatenary = plot(x=x_clean, y=y_clean, Coord.Cartesian(xmin=0, xmax=1,))\r\ndraw(SVG(\"catenary.svg\", 6inch, 6inch), catenary)\r\n", "meta": {"hexsha": "3b348e9453f309a6b7f1d3e81d2ac10c79b6c8b5", "size": 1586, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Meetups/2015Berkeley/BerkeleyTalk1/src/catenary.jl", "max_stars_repo_name": "JuliaQuantum/Resources", "max_stars_repo_head_hexsha": "144b774a3a86992cd0e0838d5c2adc94d012ab14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2015-03-15T23:07:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T00:48:58.000Z", "max_issues_repo_path": "Meetups/2015Berkeley/BerkeleyTalk1/src/catenary.jl", "max_issues_repo_name": "JuliaQuantum/Resources", "max_issues_repo_head_hexsha": "144b774a3a86992cd0e0838d5c2adc94d012ab14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2015-03-21T21:20:56.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-23T17:56:55.000Z", "max_forks_repo_path": "Meetups/2015Berkeley/BerkeleyTalk1/src/catenary.jl", "max_forks_repo_name": "JuliaQuantum/Resources", "max_forks_repo_head_hexsha": "144b774a3a86992cd0e0838d5c2adc94d012ab14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-03-21T19:56:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T00:59:23.000Z", "avg_line_length": 23.3235294118, "max_line_length": 129, "alphanum_fraction": 0.6532156368, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258009, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7587553988536696}}
{"text": "function Δ(model::LogReturnComputationModel; multiplier::Float64 = 1.0)::DataFrame\n\n    # get stuff from the computational model -\n    raw_data = model.data\n    from = model.from\n    to = model.to\n    map = model.map\n\n    # ok, so need to filter the data (if we have a from and to date set)\n    data = raw_data\n    if (isnothing(to) == false && isnothing(from) == false)\n\n        # get the date key from the map -\n        date_key = map.first\n\n        # filter to the specified date range -\n        data = filter(date_key => d -> (d >= from && d <= to), raw_data)\n    end\n\n    # initialize -\n    (number_of_rows, _) = size(data)\n    return_table = DataFrame(date = Date[], P₁ = Float64[], P₂ = Float64[], Δ = Float64[], Δ₍μ₎ = Float64[], Z = Float64[])\n\n    # main loop -\n    for row_index ∈ 2:number_of_rows\n\n        # grab the date -\n        tmp_date = data[row_index, map.first]\n\n        # grab the price data -\n        yesterday_close_price = data[row_index-1, map.second]\n        today_close_price = data[row_index, map.second]\n\n        # compute the diff -\n        δ_value = multiplier * log(today_close_price / yesterday_close_price)\n\n        # push! -\n        push!(return_table, (tmp_date, yesterday_close_price, today_close_price, δ_value, 0.0, 0.0))\n    end\n\n    # compute the mean -\n    μ = mean(return_table[!, :Δ])\n\n    # compute the std -\n    σ = std(return_table[!, :Δ])\n\n    # add values to the δ - μ col -\n    (number_of_rows, _) = size(return_table)\n    for row_index ∈ 1:number_of_rows\n        value = return_table[row_index, :Δ] - μ\n        return_table[row_index, :Δ₍μ₎] = value\n    end\n\n    # add the Z column -\n    for row_index ∈ 1:number_of_rows\n        value = (1 / σ) * (return_table[row_index, :Δ] - μ)\n        return_table[row_index, :Z] = value\n    end\n\n    # return -\n    return return_table\nend\n\nfunction Δ(model::LinearReturnComputationModel; multiplier::Float64 = 1.0)::DataFrame\n\n    # get stuff from the computational model -\n    raw_data = model.data\n    from = model.from\n    to = model.to\n    map = model.map\n\n    # ok, so need to filter the data (if we have a from and to date set)\n    data = raw_data\n    if (isnothing(to) == false && isnothing(from) == false)\n\n        # get the date key from the map -\n        date_key = map.first\n\n        # filter to the specified date range -\n        data = filter(date_key => d -> (d >= from && d <= to), raw_data)\n    end\n\n    # initialize -\n    (number_of_rows, _) = size(data)\n    return_table = DataFrame(date = Date[], P₁ = Float64[], P₂ = Float64[], Δ = Float64[], Δ₍μ₎ = Float64[], Z = Float64[])\n\n    # main loop -\n    for row_index ∈ 2:number_of_rows\n\n        # grab the date -\n        tmp_date = data[row_index, map.first]\n\n        # grab the price data -\n        yesterday_close_price = data[row_index-1, map.second]\n        today_close_price = data[row_index, map.second]\n\n        # compute the diff -\n        δ_value = multiplier * ((today_close_price - yesterday_close_price) / (yesterday_close_price))\n\n        # push! -\n        push!(return_table, (tmp_date, yesterday_close_price, today_close_price, δ_value, 0.0, 0.0))\n    end\n\n    # compute the mean -\n    μ = mean(return_table[!, :Δ])\n\n    # compute the std -\n    σ = std(return_table[!, :Δ])\n\n    # add values to the δ - μ col -\n    (number_of_rows, _) = size(return_table)\n    for row_index ∈ 1:number_of_rows\n        value = return_table[row_index, :Δ] - μ\n        return_table[row_index, :Δ₍μ₎] = value\n    end\n\n    # add the Z column -\n    for row_index ∈ 1:number_of_rows\n        value = (1 / σ) * (return_table[row_index, :Δ] - μ)\n        return_table[row_index, :Z] = value\n    end\n\n    # return -\n    return return_table\nend\n\nfunction Δ(models::Array{T,1};\n    multiplier::Float64 = 1.0)::Dict{String,DataFrame} where {T<:AbstractBaseCampComputation}\n\n\n    # initialize -\n    Δ_dictionary = Dict{String,DataFrame}()\n\n    # compute the returns for each model in the array -\n    for model ∈ models\n        ticker = model.ticker\n        Δ_dictionary[ticker] = Δ(model; multiplier = multiplier)\n    end\n\n    # return -\n    return Δ_dictionary\nend\n\nfunction 𝒟(distribution::Type{T}, ticker_symbol_array::Array{String,1}, data::Dict{String, DataFrame}; \n    colkey::Symbol = :Δ)::ContinuousMultivariateDistribution where {T <: ContinuousMultivariateDistribution}\n\n    # how many keys and rows do we have?\n    number_of_ticker_symbols = length(ticker_symbol_array)\n    number_of_rows = length(data[first(ticker_symbol_array)][!,colkey])\n\n    # initialize -\n    tmp_array = Array{Float64,2}(undef, number_of_rows, number_of_ticker_symbols)\n\n    # build the data array -\n    for (ticker_index, ticker_symbol) ∈ enumerate(ticker_symbol_array)\n        \n        # grab the data for this ticker -\n        tmp_data_col = data[ticker_symbol][!,colkey]\n\n        # copy into the tmp array -\n        for row_index ∈ 1:number_of_rows\n            tmp_array[row_index, ticker_index] = tmp_data_col[row_index]\n        end\n    end\n\n    # fit the distribution -\n    return fit(distribution, transpose(tmp_array))\nend\n\nfunction 𝒟(distribution::Type{T}, data::DataFrame; \n    colkey::Symbol = :Δ)::UnivariateDistribution where {T<:ContinuousUnivariateDistribution}\n\n    # get the array of data from the data frame -\n    data_array = data[!, colkey]\n\n    # do the fit -\n    return fit(distribution, data_array)\nend\n\nfunction 𝒟(distribution::Type{T}, data::DataFrame, weights::Union{Nothing,Array{Float64,1}};\n    colkey::Symbol = :Δ)::UnivariateDistribution where {T<:ContinuousUnivariateDistribution}\n\n    # get the array of data from the data frame -\n    data_array = data[!, colkey]\n\n    # check: do we have a weight array?\n    if (isnothing(weights) == false)\n        \n        # do the fit w/weights -\n        return fit(distribution, data_array, weights)\n    else\n         # do the fit w/o weights -\n        return fit(distribution, data_array)\n    end\nend\n\nfunction 𝒟(distribution::Type{T}, data::Dict{String, DataFrame}; \n    colkey::Symbol = :Δ, weights::Union{Nothing, Dict{String, Union{Nothing,Array{Float64,1}}}} = nothing)::Dict{String, T} where {T<:ContinuousUnivariateDistribution}\n\n    # initialize -\n    distribution_dictionary = Dict{String, T}()\n\n    # call the single 𝒟 -\n    for (key,value) ∈ data\n        \n        # get the array of data from the data frame -\n        data_array = value[!, colkey]\n\n        # check: do we have weights?\n        d = nothing\n        if (isnothing(weights) == false && \n            isnothing(weights[key]) == false)\n\n            # we have a weights -\n            w = weights[key]\n\n            # fit -\n            d = fit(distribution, data_array, w);\n        else\n            # fit a distribution -\n            d = fit(distribution, data_array);\n        end\n    \n        # capture -\n        distribution_dictionary[key] = d;\n    end\n    \n    # return data -\n    return distribution_dictionary\nend\n\nfunction 𝒫(compare::Function, samples::Array{Float64})::Float64\n\n    # initialize -\n    number_of_samples = length(samples)\n    tmp_array = BitArray(undef, (number_of_samples, 1))\n\n    # main -\n    for sample_index ∈ 1:number_of_samples\n\n        # get the sample price -\n        sample_price = samples[sample_index]\n\n        # check: which is larger, sample or target price?\n        compare(sample_price) ? tmp_array[sample_index] = 1 : tmp_array[sample_index] = 0\n    end\n\n    # sum the tmp_array -\n    number_of_larger_values = sum(tmp_array)\n\n    # compute the probability -\n    return (number_of_larger_values / number_of_samples)\nend\n\nfunction covariance(tickers::Array{String,1}, data::Dict{String,DataFrame}; \n    key::Symbol = :Δ)::Array{Float64,2}\n\n    # build a return matrix -\n    number_of_tickers = length(tickers)\n\n    # get the first data table so we can get the number of rows -\n    (number_of_rows, _) = size(data[first(tickers)])\n\n    # initialize -\n    price_return_array = Array{Float64,2}(undef, number_of_rows, number_of_tickers)\n\n    # populate the price return array -\n    for col_index ∈ 1:number_of_tickers\n\n        # get the ticker -\n        ticker_symbol = tickers[col_index]\n\n        # get data -\n        df = data[ticker_symbol]\n\n        for row_index ∈ 1:number_of_rows\n            price_return_array[row_index, col_index] = df[row_index, key]\n        end\n    end\n\n    # compute the cov array -\n    return Statistics.cov(price_return_array)\nend\n\nfunction β(tickers::Array{String,1}, data::Dict{String,DataFrame};\n    key::Symbol = :Δ, base::String = \"SPY\")::Array{Float64,1}\n\n    # initialize -\n    number_of_tickers = length(tickers)\n    β_array = Array{Float64,1}(undef, number_of_tickers)\n\n    # get the return data for the base -\n    base_return_array = data[base][!,key]\n    var_base = var(base_return_array)\n\n    # compute β -\n    for ticker_index ∈ 1:number_of_tickers\n\n        # what ticker?\n        ticker_value = tickers[ticker_index]\n        return_array_ticker = data[ticker_value][!,key]\n\n        # compute the β_value -\n        β_value = cov(return_array_ticker, base_return_array) * (1 / var_base)\n\n        # capture -\n        β_array[ticker_index] = β_value\n    end\n\n    # return -\n    return β_array\nend\n\nfunction sample(model::T, number_of_steps::Int64; \n    number_of_sample_paths = 100)::Array{Array{Float64,2},1} where {T<:ContinuousMultivariateDistribution}\n    \n    # initialize -\n    number_of_steps = number_of_steps + 1\n    number_of_dimensions = length(model)\n    sample_return_data = Array{Array{Float64,2},1}(undef, number_of_steps)\n    \n    for time_step_index ∈ 1:number_of_steps\n\n        # generate a random block -\n        B = rand(model, number_of_sample_paths)\n        \n        # capture -\n        sample_return_data[time_step_index] = B\n    end\n\n    # return -\n    return sample_return_data\nend\n\nfunction sample(model::T, number_of_steps::Int64;\n    number_of_sample_paths = 100, number_of_strata = 1)::Array{Float64,2} where {T<:ContinuousUnivariateDistribution} \n\n    # initialize -\n    number_of_steps = number_of_steps + 1\n    sample_return_data = Array{Array{Float64,1},1}(undef, number_of_steps)\n\t\n\t# Let's use stratefied sampling to generate the return samples -\n    for time_step_index ∈ 1:number_of_steps\n\n\t\ttmp_vector = Array{Float64,1}()\n                \n        # sample the strata ...\n        for strata_index ∈ 1:number_of_strata\n            \n            # compute a number_of_sample_paths draws from tis strata?\n            for _ ∈ 1:number_of_sample_paths\n                \n                # role a random number -\n                r = rand()\n\n                # compute V -\n                V₁ = (strata_index - 1)/number_of_strata + r/number_of_strata\n                V₂ = (strata_index - 1)/number_of_strata + (1 - r)/number_of_strata\n\n                # compute the quantile for this V -\n                q₁ = quantile(model, V₁)\n                q₂ = quantile(model, V₂)\n\n                # grab this value -\n                push!(tmp_vector, q₁)\n                push!(tmp_vector, q₂)\n            end\n        end\n\t\t\n        sample_return_data[time_step_index] = tmp_vector\n    end\n\n    # crunch the data together -\n    sample_return_array = transpose(hcat(sample_return_data...))\n\n    # return -\n    return sample_return_array\nend\n\nfunction sample(models::Dict{String,T}, number_of_steps::Int64; \n    number_of_sample_paths = 100, number_of_strata = 1)::Dict{String,Array{Float64,2}} where {T<:ContinuousUnivariateDistribution} \n\n    # initialize -\n    sample_dictionary = Dict{String,Array{Float64,2}}()\n\n    # compute -\n    for (ticker_symbol, model) ∈ models\n        \n        # sample this model -\n        tmp_array = sample(model, number_of_steps; \n            number_of_sample_paths = number_of_sample_paths, number_of_strata = number_of_strata)\n\n        # store the samples -\n        sample_dictionary[ticker_symbol] = tmp_array\n    end\n\n    # return -\n    return sample_dictionary\nend", "meta": {"hexsha": "6275517682c2d434710ed45541440329e7c826be", "size": 11854, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Compute.jl", "max_stars_repo_name": "Paliquant/PQBaseCamp.jl", "max_stars_repo_head_hexsha": "8174b11e5689fd7b1c7797915d8e674c08c2bd5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Compute.jl", "max_issues_repo_name": "Paliquant/PQBaseCamp.jl", "max_issues_repo_head_hexsha": "8174b11e5689fd7b1c7797915d8e674c08c2bd5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Compute.jl", "max_forks_repo_name": "Paliquant/PQBaseCamp.jl", "max_forks_repo_head_hexsha": "8174b11e5689fd7b1c7797915d8e674c08c2bd5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.709273183, "max_line_length": 167, "alphanum_fraction": 0.6337944997, "num_tokens": 3045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7587553985275435}}
{"text": "struct Margins\n    # critical frequency\n    ω_c::Float64\n    # gain cross-over frequency\n    ω_g::Float64\n    # gain margin\n    gain_margin::Float64\n    # phase margin (radians)\n    phase_margin::Float64\nend\n\n\"\"\"\n    margins = gain_phase_margins(g_ol, ω_c_guess=0.001, ω_g_guess=0.001)\n\ncompute critical frequency (radians / time), gain crossover frequency (radians / time), \ngain margin, and phase margin (radians) of a closed loop, given its\nclosed loop transfer function `g_ol::TransferFunction`.\n\nif ω_c or ω_g is not found (i.e. if either are `NaN`), but the `bode_plot` clearly shows \na critical/gain crossover frequency, adjust `ω_c_guess` or `ω_g_guess` to find the root.\n\n# Example\n```\ng_ol = 2 * exp(-s) / (5 * s + 1)\nmargins = gain_phase_margins(g_ol)\nmargins.ω_c # critical freq. (radians / time)\nmargins.ω_g # gain crossover freq. (radians / time)\nmargins.gain_margin # gain margin\nmargins.phase_margin # phase margin (radians)\n```\n\"\"\"\nfunction gain_phase_margins(g_ol::TransferFunction; ω_c_guess::Float64=0.001, ω_g_guess::Float64=0.001)\n    # critical frequency ∠ G(i ω_c) = -π\n    ω_c = NaN\n    try\n        ω_c = fzero(ω -> angle(evaluate(g_ol, im * ω)) + π, ω_c_guess, atol=2*sqrt(eps()))\n    catch da_error\n        if isa(da_error, Roots.ConvergenceFailed)\n            ω_c = NaN\n        else\n            println(da_error)\n            error(\"something went wrong when computing ω_c\")\n        end\n    end\n    # check for spurious solution (often ω_c d.n.e.) TODO check issue on Roots.jl\n    if ! isapprox(angle(evaluate(g_ol, im * ω_c)), -π, rtol=0.01)\n        ω_c = NaN\n    end\n\n    # gain cross over frequency | G(i ω_g) | = 1\n    ω_g = NaN\n    try\n        ω_g = fzero(ω -> abs(evaluate(g_ol, im * ω)) - 1.0, ω_g_guess, atol=2*sqrt(eps()))\n    catch da_error\n        if isa(da_error, Roots.ConvergenceFailed)\n            ω_g = NaN\n        else\n            println(da_error)\n            error(\"something went wrong when computing ω_g\")\n        end\n    end\n    # check for spurious solution (often ω_c d.n.e.) TODO check issue on Roots.jl\n    if ! isapprox(abs(evaluate(g_ol, im * ω_g)), 1.0, rtol=0.01)\n        ω_g = NaN\n    end\n    # gain margin = 1 / | G(i ω_c) |\n    gm = 1 / abs(evaluate(g_ol, im * ω_c))\n    # phase margin = ∠ G(i ω_g) + π\n    pm = π + angle(evaluate(g_ol, im * ω_g))\n    return Margins(ω_c, ω_g, gm, pm)\nend\n", "meta": {"hexsha": "2c7551699dc7680ba87f7d832e6596fe2384fb4b", "size": 2349, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/margins.jl", "max_stars_repo_name": "SimonEnsemble/Controlz", "max_stars_repo_head_hexsha": "d09ce3500a954fcb0a7a96001cda1142139fccc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/margins.jl", "max_issues_repo_name": "SimonEnsemble/Controlz", "max_issues_repo_head_hexsha": "d09ce3500a954fcb0a7a96001cda1142139fccc5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/margins.jl", "max_forks_repo_name": "SimonEnsemble/Controlz", "max_forks_repo_head_hexsha": "d09ce3500a954fcb0a7a96001cda1142139fccc5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.625, "max_line_length": 103, "alphanum_fraction": 0.6343124734, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7587526154119817}}
{"text": "\"\"\"\r\n$(TYPEDEF)\r\n\r\nA system of partial differential equations.\r\n\r\n# Fields\r\n$(FIELDS)\r\n\r\n# Example\r\n\r\n```julia\r\nusing ModelingToolkit\r\n\r\n@parameters t x\r\n@variables u(..)\r\nDxx = Differential(x)^2\r\nDtt = Differential(t)^2\r\nDt = Differential(t)\r\n\r\n#2D PDE\r\nC=1\r\neq  = Dtt(u(t,x)) ~ C^2*Dxx(u(t,x))\r\n\r\n# Initial and boundary conditions\r\nbcs = [u(t,0) ~ 0.,# for all t > 0\r\n       u(t,1) ~ 0.,# for all t > 0\r\n       u(0,x) ~ x*(1. - x), #for all 0 < x < 1\r\n       Dt(u(0,x)) ~ 0. ] #for all  0 < x < 1]\r\n\r\n# Space and time domains\r\ndomains = [t ∈ IntervalDomain(0.0,1.0),\r\n           x ∈ IntervalDomain(0.0,1.0)]\r\n\r\npde_system = PDESystem(eq,bcs,domains,[t,x],[u])\r\n```\r\n\"\"\"\r\nstruct PDESystem <: ModelingToolkit.AbstractSystem\r\n    \"The equations which define the PDE\"\r\n    eqs\r\n    \"The boundary conditions\"\r\n    bcs\r\n    \"The domain for the independent variables.\"\r\n    domain\r\n    \"The independent variables\"\r\n    indvars\r\n    \"The dependent variables\"\r\n    depvars\r\n    \"The parameters\"\r\n    ps\r\n    \"\"\"\r\n    defaults: The default values to use when initial conditions and/or\r\n    parameters are not supplied in `ODEProblem`.\r\n    \"\"\"\r\n    defaults::Dict\r\n    @add_kwonly function PDESystem(eqs, bcs, domain, indvars, depvars, ps = SciMLBase.NullParameters(), defaults = Dict())\r\n        new(eqs, bcs, domain, indvars, depvars, ps, defaults)\r\n    end\r\nend\r\n\r\nBase.getproperty(x::PDESystem, sym::Symbol) = getfield(x, sym)\r\n\r\nBase.summary(prob::PDESystem) = string(nameof(typeof(prob)))\r\nfunction Base.show(io::IO, ::MIME\"text/plain\", sys::PDESystem)\r\n    println(io,summary(sys))\r\n    println(io,\"Equations: \", get_eqs(sys))\r\n    println(io,\"Boundary Conditions: \", get_bcs(sys))\r\n    println(io,\"Domain: \", get_domain(sys))\r\n    println(io,\"Dependent Variables: \", get_depvars(sys))\r\n    println(io,\"Independent Variables: \", get_indvars(sys))\r\n    println(io,\"Parameters: \", get_ps(sys))\r\n    print(io,\"Default Parameter Values\", get_defaults(sys))\r\n    return nothing\r\nend\r\n", "meta": {"hexsha": "6cfbeac2994caacbb41d90261d48a4cbff8cfed5", "size": 1978, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/systems/pde/pdesystem.jl", "max_stars_repo_name": "catethos/ModelingToolkit.jl", "max_stars_repo_head_hexsha": "7e7fb1740fe36262027aead8805ad8e19cd94e90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/systems/pde/pdesystem.jl", "max_issues_repo_name": "catethos/ModelingToolkit.jl", "max_issues_repo_head_hexsha": "7e7fb1740fe36262027aead8805ad8e19cd94e90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/systems/pde/pdesystem.jl", "max_forks_repo_name": "catethos/ModelingToolkit.jl", "max_forks_repo_head_hexsha": "7e7fb1740fe36262027aead8805ad8e19cd94e90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7297297297, "max_line_length": 123, "alphanum_fraction": 0.6258847321, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7587526076145716}}
{"text": "\"\"\"\n    get_neg_binomial_prn(p, r, shape=1; seed=nothing)\n\nGenerate a random variable from a Negative Binomial(`p`, `r`) distribution. Optionally you can set a specific seed.\n\n# Examples\n\n```julia-repl\njulia> get_neg_binomial_prn(.2, 2)\n 16\n\njulia> get_neg_binomial_prn(.2, 2, seed=42)\n 6\n\n```\n\n# References\n\nWalk, C. Handbook on statistical distributions for experimentalists. 2007.\n\"\"\"\nfunction get_neg_binomial_prn(p::Real, r::Int; seed::Union{Int, Nothing}=nothing)\n    check_p(p)\n    n = convert(Int, r/p * 10)\n    U = bernoulli_rng(p, n, seed=seed)\n    X = sum(cumsum(U, dims=1) .< r) + 1   # TODO CHECK THIS AGAINST ANOTHER METHOD (e.g. convolution)\n    return X\nend\n\n\n\"\"\"\n    neg_binomial_rng(p, r, shape=1; seed=nothing)\n\nGenerate a `shape` element array of random variables from a Negative Binomial(`p`, `r`) distribution. Optionally you can set a specific seed.\n\n# Notes\n\nThe Negative Binomial distribution is given:\n\n``f(x,p,r) = \\\\binom{x-1}{r-1} (1-p)^{x-r} p^r \\\\quad x = 0,1,\\\\dots, n``\n\n# Examples\n\n```julia-repl\njulia> neg_binomial_rng(.5, 2)\n1-element Vector{Float64}:\n 3.0\n\njulia> neg_binomial_rng(.5, 5, 5)\n5-element Vector{Float64}:\n  8.0\n 10.0\n  8.0\n 13.0\n 10.0\n\njulia> neg_binomial_rng(.5, 2, (2,2))\n2×2 Matrix{Float64}:\n 3.0  4.0\n 4.0  2.0\n \n```\n\n# References\n\nWalk, C. Handbook on statistical distributions for experimentalists. 2007.\n\"\"\"\nfunction neg_binomial_rng(p::Real, r::Int, shape::Union{Int, Tuple{Vararg{Int}}}=1; seed::Union{Int, Nothing}=nothing)\n    check_p(p)\n    X = zeros(shape)\n    X .= get_neg_binomial_prn.(p, r, seed=seed)\n    return X\nend\n\n\n\"\"\"\n    conv_neg_binomial_rng(p, r, shape=1; seed=nothing)\n\nGenerate a `shape` element array of random variables from a Negative Binomial(`p`, `r`) distribution. Optionally you can set a specific seed.\n\n# Notes\n\nThe Negative Binomial distribution is given:\n\n``f(x,p,r) = \\\\binom{x-1}{r-1} (1-p)^{x-r} p^r \\\\quad x = 0,1,\\\\dots, n``\n\nUses a convolution algorithm to generate random variables, which is slightly slower than [`neg_binomial_rng`](@ref).\n\n# Examples\n\n```julia-repl\njulia> conv_neg_binomial_rng(.4, 5, 1)\n1×1 Matrix{Int64}:\n 8\n\njulia> conv_neg_binomial_rng(.4, 5, 5)\n5×1 Matrix{Int64}:\n 11\n 14 \n 8\n 10\n 13\n\njulia> conv_neg_binomial_rng(.4, 5, (2,2))\n2×2×1 Array{Int64, 3}:\n[:, :, 1] =\n 20  11\n 7  10\n```\n\n# References\n\nLaw, A. Simulation modeling and analysis, 5th Ed. McGraw Hill Education, Tuscon, 2013.\n\"\"\"\nfunction conv_neg_binomial_rng(p::Real, r::Int, shape::Union{Int, Tuple{Vararg{Int}}}=1; seed::Union{Int, Nothing}=nothing)\n    check_p(p)\n    Y = geometric_rng(p, (shape..., r), seed=seed)\n    X = sum(Y, dims=ndims(Y))\n    return X\nend\n", "meta": {"hexsha": "d829136d8d2b4361928d2945729c21b3441b1fff", "size": 2645, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/neg_binomial.jl", "max_stars_repo_name": "chris-santiago/RandomVariates.jl", "max_stars_repo_head_hexsha": "75cf7057d06482f5208233f0f78f08e0dcfee58f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/neg_binomial.jl", "max_issues_repo_name": "chris-santiago/RandomVariates.jl", "max_issues_repo_head_hexsha": "75cf7057d06482f5208233f0f78f08e0dcfee58f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/neg_binomial.jl", "max_forks_repo_name": "chris-santiago/RandomVariates.jl", "max_forks_repo_head_hexsha": "75cf7057d06482f5208233f0f78f08e0dcfee58f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0416666667, "max_line_length": 141, "alphanum_fraction": 0.6744801512, "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894548800271, "lm_q2_score": 0.8479677526147222, "lm_q1q2_score": 0.758752603117969}}
{"text": "using EngEconomics, Roots\n\n# Given\naInit = -200000\naAnnual = 30000\naScrap = 45000\naLife = 20\n\nbInit = -180000\nbAnnual = 24000\nbScrap = 20000\nbLife = 15\n\nMARR = 0.09\n\n# Find Annual Worth Analysis\naAW = aInit * capitalRecoveryFactor(MARR, aLife) + aAnnual + aScrap * sinkingFundFactor(MARR, aLife)\n\nbAW = bInit * capitalRecoveryFactor(MARR, bLife) + bAnnual + bScrap * sinkingFundFactor(MARR, bLife)\n\nif aAW > bAW\n\tprintln(\"A\")\nelse\n\tprintln(\"B\")\nend\n", "meta": {"hexsha": "7d2b4b4f988dd88b769d2289297f9eccfac2d305", "size": 449, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps5/p3.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/ps5/p3.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/ps5/p3.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.2692307692, "max_line_length": 100, "alphanum_fraction": 0.7216035635, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997376, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7587122818042055}}
{"text": "using ApproxFun\n\n#The following solves the Airy ODE with dirichlet boundary conditions\n\nx=Fun(identity,[-1000.,15.])   # Fun corresponding to multiplication by x, on [-100,15]\nd=domain(x)\nD=Derivative()             # The derivative operator\nB=dirichlet()              # Dirichlet boundary conditions, [u(-100),u(15)]\n\n#Construct operator\n\nA=[B;D^2-x]                # This is dirichlet conditions and u'' - x u\nb=[airyai(first(d)),0.]         # We want it to equal airyai(-100) at -100, and 0 at\n                           # 10, with 0 rhs\n#Solve ODE\n\nu=A\\b                      # u satisfies A*u = b, or in other words,\n                           # B*u = [airyai(-100.),0.] and (D2 - x)*u = 0.\n\n# Check the accuracy\nnorm(u - Fun(airyai,d))\n\n\n## We now solve with Neumann conditions\n\nB=neumann()\nA=[B;D^2-x]\nb=[airyaiprime(first(d)),0.,0.]\n\nu=A\\b\n\n\n# Check the accuracy\nnorm(u - Fun(airyai,d))\n", "meta": {"hexsha": "7b7ffe3a580803bb3700d15d5e7546fe24b2cc98", "size": 894, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Airy equation.jl", "max_stars_repo_name": "JuliaPackageMirrors/ApproxFun.jl", "max_stars_repo_head_hexsha": "f73e9d168b0d139efa2953b1bad7fac808db2d8d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Airy equation.jl", "max_issues_repo_name": "JuliaPackageMirrors/ApproxFun.jl", "max_issues_repo_head_hexsha": "f73e9d168b0d139efa2953b1bad7fac808db2d8d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Airy equation.jl", "max_forks_repo_name": "JuliaPackageMirrors/ApproxFun.jl", "max_forks_repo_head_hexsha": "f73e9d168b0d139efa2953b1bad7fac808db2d8d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5428571429, "max_line_length": 87, "alphanum_fraction": 0.5771812081, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342024724487, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7587122744090041}}
{"text": "function romberg(f, a, b, n)\n\tr = zeros(2, n)\n\th = b - a\n\tr[1, 1] = (h/2) * (f(a) + f(b))\n\tfor i ∈ 2:n\n\t\ttsum = 0\n\t\tfor k ∈ 1:(2^(i - 2))\n\t\t\ttsum += f(a + (k - 0.5) * h)\n\t\tend\n\t\tr[2, 1] = (1/2)*(h*tsum + r[1, 1])\n\t\tfor j ∈ 2:i\n\t\t\tr[2, j] = r[2, j - 1] + (r[2, j - 1] - r[1, j - 1])/(4^(j - 1) - 1)\n\t\tend\n\t\th = h/2\n\t\tfor j ∈ 1:i\n\t\t\tr[1, j] = r[2, j]\n\t\tend\n\tend\n\treturn r[2, n]\nend\n\nf(x) = sin(x)\nprintln(romberg(f, 0, 3, 20))\n", "meta": {"hexsha": "0ef65f8c29ffcd506cc5a44609f5ddbb9bfd5a6f", "size": 425, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter4/romberg.jl", "max_stars_repo_name": "Matt8898/julia-numerical", "max_stars_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-05T01:36:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-26T04:07:41.000Z", "max_issues_repo_path": "chapter4/romberg.jl", "max_issues_repo_name": "Matt8898/julia-numerical", "max_issues_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter4/romberg.jl", "max_forks_repo_name": "Matt8898/julia-numerical", "max_forks_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7083333333, "max_line_length": 70, "alphanum_fraction": 0.4, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7587122724478823}}
{"text": "\r\n##\r\nimport LinearAlgebra as linalg\r\nimport Plots as plt\r\n\r\ninclude(\"KalmanFilter.jl\")\r\nimport .KalmanFilter as kf\r\n\r\n##\r\nfunction get_data()\r\n    # Observations\r\n    x = [4000.0 4260.0 4550.0 4860.0 5110.0] # position [m]\r\n    v = [ 280.0  282.0  285.0  286.0  290.0] # velocity [m/s]\r\n    # x = [4000.0 4260.0 4550.0 4860.0 5110.0 5220.0 5115.0 4995.0 4871.0] # position [m]\r\n    # v = [ 280.0  282.0  285.0  286.0  290.0  295.0  292.0  287.0  284.0] # velocity [m/s]\r\n    X = [x; v]\r\n\r\n    # Initial values\r\n    a = 2.0 # acceleration\r\n    Δt = 1.0 # Time step\r\n    ΔP = [20.0; 5.0] # Process errors in process covariance matrix\r\n    Δ = [25.0; 6.0] # Observation errors\r\n    return X, a, Δ, ΔP, Δt\r\nend\r\n\r\n## Define the state space model\r\n\r\nfunction define_model(X, a, Δ, ΔP, Δt)\r\n    m, n = size(X)\r\n    Q = zeros(m, m) # Process noise covariance matrix\r\n    F = [1.0 Δt; 0.0 1.0] # Transition matrix\r\n    B = [Δt^2/2.0 Δt]' # Control-input matrix\r\n    u = 2.0 # # Control vector, acceleration\r\n    R = linalg.Diagonal([Δ[1]^2 0.0; 0.0 Δ[2]^2]) # Sensor noise covariance matrix\r\n    H = kf.eye(m) # Measurement matrix\r\n    w = zeros(m)\r\n    v = zeros(m)\r\n    # Initial predicted process covariance matrix\r\n    P = linalg.Diagonal([ΔP[1]^2 ΔP[1]*ΔP[2]; ΔP[2]*ΔP[1] ΔP[2]^2])\r\n    return P, Q, R, F, H, B, u, m, n\r\nend\r\n\r\n## Data input\r\nfunction data_input(X, n)\r\n    X = [ [X[1,i], X[2,i]] for i in 1:n ]\r\n    Xp = [ X[1] ] # Initialize predicted state\r\n    Xk = copy(Xp) # Initialized new state matrix\r\n    return Xp, Xk, X\r\nend\r\n\r\n## Run Kalman Filter\r\nfunction run_kf(X, P, F, H, Q, R, B, u; filter=kf.CholeskySqrt())\r\n    n = size(X, 2)\r\n    _, _, Xx = data_input(X, n)\r\n    k = 1\r\n    S = kf._innovation_covariance(P, H, R)\r\n    K = kf._kalman_gain(P, H, S)\r\n    skf = [ kf.LinearKF(Xx[k], Xx[k], P, K, S, Xx[1], filter) ]\r\n    while k < n\r\n        s = kf.linear_kalman(\r\n            Xx[k+1], skf[k].xk, skf[k].P, F, H, Q, R;\r\n            B=B, u=u, sqrt_filter=filter,\r\n        )\r\n        push!(skf, s)\r\n        k += 1\r\n    end\r\n    return skf\r\nend\r\n\r\n## Smoothers\r\nfunction run_smoothers_bts(Xk, F, Σ)\r\n    k = length(Xk)\r\n    sm = Vector{kf.RTSSmoother}(undef, k)\r\n    sm[k] = kf.RTSSmoother(Xk[k], Σ[k])\r\n    ksmoother = kf.RauchTungStriebel()\r\n    while k > 1\r\n        s = kf.kalman_smooth(ksmoother, sm[k].xk, Xk[k-1], Xk[k], Σ[k-1], Σ[k], F)\r\n        k -= 1\r\n        sm[k] = s\r\n    end\r\n    return sm\r\nend\r\n\r\nfunction run_smoothers_mbf(skf, F, H)\r\n    m = size(skf[1].xk, 1)\r\n    k = length(skf)\r\n    sm = Vector{kf.MBFSmoother}(undef, k)\r\n    ksmoother = kf.ModifiedBrysonFrazier()\r\n    # Λ, λ = zeros(size(lsm.F)), zeros(size(lsm.F,1))\r\n    SH = skf[k].S \\ H'\r\n    Λ, λ = SH*H, -SH*skf[k].y\r\n    sm[k] = kf.MBFSmoother(skf[k].xk, skf[k].P, Λ, λ)\r\n    while k > 1\r\n        s = kf.kalman_smooth(\r\n            ksmoother,\r\n            skf[k-1].xk,\r\n            skf[k-1].P,\r\n            skf[k-1].K,\r\n            F,\r\n            H,\r\n            sm[k].L,\r\n            sm[k].l,\r\n            skf[k-1].S,\r\n            skf[k-1].y,\r\n        )\r\n        k -= 1\r\n        sm[k] = s\r\n    end\r\n    return sm\r\nend\r\n\r\n## Plots\r\nfunction plot_kf(Xp, Xk, Xx, Δ)\r\n    # Xp, Xk, Xx = reduce(hcat, Xp), reduce(hcat, Xk), reduce(hcat, Xx)\r\n    p1 = plt.plot(Xp[1,:], m=:o, label=\"Predicted\", legend=:topleft, ylabel=\"Position [m]\", xlabel=\"Time [s]\")\r\n    plt.plot!(p1, Xx[1,:], m=:s, label=\"Measured\", ribbon=Δ[1])\r\n    plt.plot!(p1, Xk[1,:], m=:p, label=\"KF\")\r\n    p2 = plt.plot(Xp[2,:], m=:o, label=\"Predicted\", legend=:topleft, ylabel=\"Velocity [m/s]\", xlabel=\"Time [s]\")\r\n    plt.plot!(p2, Xx[2,:], m=:s, label=\"Measured\", ribbon=Δ[2])\r\n    plt.plot!(p2, Xk[2,:], m=:p, label=\"KF\")\r\n    p = plt.plot(p1, p2, size=(700,350))\r\n    return p\r\nend\r\n\r\nfunction plot_kf_smooth(Xp, Xk, Xx, Xks, Δ)\r\n    # Xp, Xk = reduce(hcat, Xp), reduce(hcat, Xk)\r\n    # Xx, Xks = reduce(hcat, Xx), reduce(hcat, Xks)\r\n    p1 = plt.plot(Xp[1,:], m=:o, label=\"Predicted\", legend=:topleft, ylabel=\"Position [m]\", xlabel=\"Time [s]\")\r\n    plt.plot!(p1, Xx[1,:], m=:s, label=\"Measured\", ribbon=Δ[1])\r\n    plt.plot!(p1, Xk[1,:], m=:p, label=\"KF\")\r\n    plt.plot!(p1, Xks[1,:], m=:h, label=\"Smooth\")\r\n    p2 = plt.plot(Xp[2,:], m=:o, label=\"Predicted\", legend=:topleft, ylabel=\"Velocity [m/s]\", xlabel=\"Time [s]\")\r\n    plt.plot!(p2, Xx[2,:], m=:s, label=\"Measured\", ribbon=Δ[2])\r\n    plt.plot!(p2, Xk[2,:], m=:p, label=\"KF\")\r\n    plt.plot!(p2, Xks[2,:], m=:h, label=\"Smooth\")\r\n    p = plt.plot(p1, p2, size=(700,350))\r\n    return p\r\nend\r\n\r\n## Run KFs\r\nX, a, Δ, ΔP, Δt = get_data()\r\nP, Q, R, F, H, B, u, m, n = define_model(X, a, Δ, ΔP, Δt)\r\n\r\n## Simple Kalman filter\r\nskf = run_kf(X, P, F, H, Q, R, B, u; filter=kf.CholeskyModSqrt())\r\nXp, Xk = kf.unpack(skf, [:xp, :xk])\r\np = plot_kf(Xp, Xk, X, Δ)\r\n\r\n## Rauch Tung Striebel Smoother\r\nΣ, Xk2m = kf.unpack_matrix(skf, [:P, :xk])\r\nskfm = run_smoothers_bts(Xk2m, F, Σ)\r\nXk2m = kf.unpack(skfm, :xk)\r\np2m = plot_kf_smooth(Xp, Xk, X, Xk2m, Δ)\r\n\r\n## Modified Bryson–Frazier Smoother\r\nskfmb = run_smoothers_mbf(skf, F, H)\r\nXk2mb = kf.unpack(skfmb, :xk)\r\np2m = plot_kf_smooth(Xp, Xk, X, Xk2mb, Δ)\r\n", "meta": {"hexsha": "d4632d0218608ec4858204b5261016cee6906ea2", "size": 5103, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test_package_LKF.jl", "max_stars_repo_name": "lnacquaroli/KalmanFilter.jl", "max_stars_repo_head_hexsha": "9746b6b1079c499323f777ecf7077a995ec49f78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test_package_LKF.jl", "max_issues_repo_name": "lnacquaroli/KalmanFilter.jl", "max_issues_repo_head_hexsha": "9746b6b1079c499323f777ecf7077a995ec49f78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_package_LKF.jl", "max_forks_repo_name": "lnacquaroli/KalmanFilter.jl", "max_forks_repo_head_hexsha": "9746b6b1079c499323f777ecf7077a995ec49f78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0943396226, "max_line_length": 113, "alphanum_fraction": 0.5371350186, "num_tokens": 2062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.7587122707114032}}
{"text": "N = 100\nh = 1.0/N\ny = zeros(N)\ny[1] = 0\nt = linrange(0,2,N)\n\nfunction func(t,x)\n    return x^(1/3.0)\nend\n\nfor i=1:N-1\n    y[i+1] = y[i] + h*func(t[i], y[i])\nend\nprintln(\"y\", \"  \", \"y(t)\", \"  \", \"Error\")\nfor i=1:N\n    println(t[i]^(3/2.0), \"  \", y[i], \" \", abs(t[i]^1.5-y[i])/t[i]^1.5)\nend\n", "meta": {"hexsha": "47f01694bb340a993b7e392ad93b6ef68fe00110", "size": 289, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2015_Spring/MATH-501/hw5/forwardEuler.jl", "max_stars_repo_name": "NeveIsa/hatex", "max_stars_repo_head_hexsha": "c5cfa2410d47c7e43a476a8c8a9795182fe8f836", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2015-09-10T02:45:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T03:20:47.000Z", "max_issues_repo_path": "2015_Spring/MATH-501/hw5/forwardEuler.jl", "max_issues_repo_name": "NeveIsa/hatex", "max_issues_repo_head_hexsha": "c5cfa2410d47c7e43a476a8c8a9795182fe8f836", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-09-16T23:11:00.000Z", "max_issues_repo_issues_event_max_datetime": "2015-09-23T21:21:52.000Z", "max_forks_repo_path": "2015_Spring/MATH-501/hw5/forwardEuler.jl", "max_forks_repo_name": "saketkc/hatex", "max_forks_repo_head_hexsha": "c5cfa2410d47c7e43a476a8c8a9795182fe8f836", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-09-25T19:06:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T03:21:09.000Z", "avg_line_length": 16.0555555556, "max_line_length": 71, "alphanum_fraction": 0.4567474048, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.75862691179931}}
{"text": "using LinearAlgebra\nusing Plots\n\ninclude(\"cheb.jl\")\ninclude(\"parameters.jl\")\ninclude(\"geometry.jl\")\ninclude(\"profile.jl\")\ninclude(\"build_A.jl\")\ninclude(\"compute_spectrum.jl\")\ninclude(\"mesh.jl\")\ninclude(\"plot_fields.jl\")\n\nOmega = 2*π/(24*3600)\nlat   = π/4\n\nparams=parameters(\n     H = 2e3, \n    Ly = 600e3, \n    f₀ = 2*Omega*cos(lat), \n     g = 10, \n    Lj = 60e3, \n    Uj = 1.0,\n    Ny = 200,\n    dk = 5e-2,\n    kₘ = 2e0\n    );\n\nparams.Fr = (params.f₀ * params.Lj)^2/(params.g * params.H);\nparams.Ro =  params.Uj/(params.f₀ * params.Lj)\n\nprint(\"\\n\")\nprint(\"Linear-Stability-Caluculator\\n\")\nprint(\"============================\\n\\n\")\nprint(\"Repo:      Linear-Stability-Calculators\\n\")\nprint(\"Code:      ShallowWater/Julia/linear_stability_shallow_water.jl\\n\")\nprint(\"Model:     Rotating Shallow Water\\n\")\nprint(\"Geometry:  Cartesian\\n\")\nprint(\"Structure: Bickley Jet\\n\")\nprint(\"\\n\")\nprint(\"Nondimensional Parameters\\n\")\nprint(\"=========================\\n\")\nprint(\"Fr = \", params.Fr, \"\\n\")\nprint(\"Ro = \", params.Ro, \"\\n\")\n\n# Wavenumbers\nks = collect(params.dk:params.dk:params.kₘ) / params.Lj;\nNk = length(ks);\n\n# Grid and basic state\nDy, Dy2, y = geometry(params);\nU,  E      = profile(         y, params);\n\nplot_basic_state(y, U, E, params.Ly, \"basic_state.png\")\n\n# initialize fields to store \nNmodes = 2\n     σ = zeros(Nmodes, Nk);\n     ω = zeros(Nmodes, Nk);   \nσmodes = zeros(ComplexF64, 3*params.Ny+1, Nmodes, Nk);\n\n# Compute growth rates\nfor cnt in 1:Nk\n    local k = ks[cnt]\n    local A = build_A(k, U, E, Dy, y, params);\n    local σ[:,cnt], ω[:,cnt], σmodes[:,:,cnt] = compute_spectrum(A, k, params, Nmodes);\nend\n\nplot_growth_rates(ks, σ, Nmodes, \"growth_rates_Cartesian_Bickley_jet.png\")\n\nmode_number = 1;\n      σ_max = maximum(σ[mode_number,:]);\n    k_index = sortperm(σ[mode_number,:],rev=true)[1];\n          k = ks[k_index]; # pick wavenumber\n\nplot_1D_streamfunction(k_index, k, y, σmodes, mode_number, \"modes_1D_streamfunction.png\")\nplot_2D_streamfunction(k_index, k, y, σmodes, mode_number, \"modes_2D_streamfunction.png\")\nplot_2D_vorticity( Dy, k_index, k, y, σmodes, mode_number, \"modes_2D_vorticity.png\")\n", "meta": {"hexsha": "6c057fdf041131755ec623948ecde682598a1d7e", "size": 2119, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ShallowWater/Julia/Cartesian/linear_stability_shallow_water.jl", "max_stars_repo_name": "francispoulin/Linear-Stability-Calculators", "max_stars_repo_head_hexsha": "2e1cf66b0bed95f24ddfeea09ec7d66956cdce64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-22T20:00:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T17:19:18.000Z", "max_issues_repo_path": "ShallowWater/Julia/Cartesian/linear_stability_shallow_water.jl", "max_issues_repo_name": "francispoulin/Linear-Stability-Calculators", "max_issues_repo_head_hexsha": "2e1cf66b0bed95f24ddfeea09ec7d66956cdce64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-27T16:14:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-27T16:14:05.000Z", "max_forks_repo_path": "ShallowWater/Julia/Cartesian/linear_stability_shallow_water.jl", "max_forks_repo_name": "francispoulin/Linear-Stability-Calculators", "max_forks_repo_head_hexsha": "2e1cf66b0bed95f24ddfeea09ec7d66956cdce64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-05-18T11:05:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T18:57:19.000Z", "avg_line_length": 27.1666666667, "max_line_length": 89, "alphanum_fraction": 0.6432279377, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7586269060857467}}
{"text": "export  w_legendre,\n        build_w_jacobi,\n        w_jacobi,\n        w_laguerre,\n        w_hermite,\n        build_w_genhermite,\n        build_w_genlaguerre,\n        w_meixner_pollaczek,\n        build_w_meixner_pollaczek,\n\n        w_gaussian,\n        w_uniform01,\n        w_uniform_11,\n        w_logistic,\n        w_genhermite,\n        build_w_beta,\n        build_w_gamma\n\n_throwError(t) = throw(DomainError(t, \"not in support\"))\n\nfunction w_legendre(t)\n    -1. <= t <= 1. ? 1. : _throwError(t)\nend\n\nfunction build_w_jacobi(a,b)\n    return t->w_jacobi(t,a,b)\nend\n\nfunction w_jacobi(t,a,b)\n    -1. <= t <= 1. ? (1-t)^a*(1+t)^b : _throwError(t)\nend\n\nfunction w_hermite(t)\n    exp(-t^2)\nend\n\nfunction build_w_genhermite(mu)\n    return t->w_genhermite(t,mu)\nend\n\nfunction w_genhermite(t,μ)\n    abs(t)^(2*μ)*exp(-t^2)\nend\n\nfunction build_w_genlaguerre(a)\n    return t -> w_genlaguerre(t,a)\nend\n\nfunction w_laguerre(t)\n    t >= 0. ? exp(-t) : _throwError(t)\nend\n\nfunction w_meixner_pollaczek(t,lambda,phi)\n    1 / (2pi) * exp((2*phi - pi)*t) * abs(gamma(lambda+im*t))^2\nend\n\nfunction build_w_meixner_pollaczek(lambda,phi)\n    t->w_meixner_pollaczek(t,lambda,phi)\nend\n\n##################################################\n# probability density functions\nfunction w_gaussian(t)\n    1 / (sqrt(2*pi))*exp(-0.5*t^2)\nend\n\nfunction build_w_beta(α,β)\n    return t->w_beta(t,α,β)\nend\n\nfunction w_beta(t,α,β)\n    -1 <= t <= 1 ? t^(α-1)*(1-t)^(β-1)/beta(α,β) : _throwError(t)\nend\n\nfunction build_w_gamma(α)\n    return t->w_gamma(t,α)\nend\n\nfunction w_gamma(t,α)\n    t >= 0. ? (1/gamma(α)*Float64(t)^(α-1)*exp(-t)) : _throwError(t)\nend\n\nfunction w_uniform01(t)\n    0. <= t <= 1. ? 1. : _throwError(t)\nend\n\nfunction w_uniform_11(t)\n    -1. <= t <= 1. ? 0.5 : _throwError(t)\nend\n\nfunction w_logistic(t)\n    0.25*sech(0.5t)^2\nend\n", "meta": {"hexsha": "7a0f8edcdb1e851f583bffd3feb054c0e19e5ba6", "size": 1806, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/densities.jl", "max_stars_repo_name": "adriangrupp/PolyChaos.jl", "max_stars_repo_head_hexsha": "d0091cc575456721b5f4c20dd219ce3789d889bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71, "max_stars_repo_stars_event_min_datetime": "2019-02-08T15:13:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T09:48:18.000Z", "max_issues_repo_path": "src/densities.jl", "max_issues_repo_name": "adriangrupp/PolyChaos.jl", "max_issues_repo_head_hexsha": "d0091cc575456721b5f4c20dd219ce3789d889bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 55, "max_issues_repo_issues_event_min_datetime": "2019-02-08T12:21:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T20:21:46.000Z", "max_forks_repo_path": "src/densities.jl", "max_forks_repo_name": "adriangrupp/PolyChaos.jl", "max_forks_repo_head_hexsha": "d0091cc575456721b5f4c20dd219ce3789d889bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-03-20T08:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T14:25:42.000Z", "avg_line_length": 19.2127659574, "max_line_length": 68, "alphanum_fraction": 0.6101882614, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7586268911422721}}
{"text": "using EngEconomics\n\n# Given\n# Both\ni = 0.08\n# Option 1: Get 100,000 -> 120,000 -> 140,000 etc.\nn = 30\nA = 100000\nG = 10000\n\ntotalOption1 = G * singlePaymentPresentWorthArithmetic(i, n) + A * seriesPresentAmountFactor(i, n)\ntotalOption2 = 2500000\n\nif totalOption1 > totalOption2\n\tprintln(\"Don\\'t take the money from Gill\")\nelse\n\tprintln(\"Take the money from Gill\")\nend\n", "meta": {"hexsha": "265e266bca63081777e41796358c26e9ec837c32", "size": 368, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps3/p1.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/ps3/p1.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/ps3/p1.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3684210526, "max_line_length": 98, "alphanum_fraction": 0.7201086957, "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7585898831143766}}
{"text": "# this function shows the behavior of the \n# likelihood, the log-likelihood and the average\n# log-likelihood as the sample size increases\nusing Distributions\nfunction main(n)\np = 0.3\ny = rand(Bernoulli(p),n)\nf =  pdf(Bernoulli(p), y)\n@show ℒ = prod(f)\n@show lnℒ = sum(log.(f)) \n@show avglnℒ = (1/n)*sum(log.(f)) \nnothing\nend\n\n\n", "meta": {"hexsha": "d280c3df6e5b4911154d0eede7ab4e9926ba128c", "size": 327, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/MLE/PlainLF.jl", "max_stars_repo_name": "Hiroakiyusheng/Econometrics", "max_stars_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "Examples/MLE/PlainLF.jl", "max_issues_repo_name": "Hiroakiyusheng/Econometrics", "max_issues_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "Examples/MLE/PlainLF.jl", "max_forks_repo_name": "Hiroakiyusheng/Econometrics", "max_forks_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 20.4375, "max_line_length": 48, "alphanum_fraction": 0.6941896024, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.8198933337131077, "lm_q1q2_score": 0.758589879042572}}
{"text": "\"\"\"\r\nCompute the stopping times of numbers subjected to the Collatz sequence.\r\nhttps://en.wikipedia.org/wiki/Collatz_conjecture\r\n\"\"\"\r\n\r\ninclude(\"../ragamuffin.jl\")\r\n\r\nfunction collatz_length(x)\r\n    if x == 1\r\n        return 0\r\n    elseif x % 2 == 0\r\n        return 1 + collatz_length(x / 2)\r\n    else\r\n        return 1 + collatz_length(3 * x + 1)\r\n    end\r\nend\r\nN = 100\r\nrange = 1:N\r\nexpected = @time collect(map(collatz_length, range))\r\n\r\n\r\nfunction ragamuffin_collatz()\r\n    T = Int32\r\n    program = initialize(map(T, range) |> collect, T(-1), Frame, 32, T)\r\n    add!(program, :root, (:end, :increment), value_function=x -> x.value == 1)\r\n    add!(program, :increment, :parity, dest_function = x -> 1)\r\n    add!(program, :parity, (:even, :odd), value_function = x -> x.value % 2 == 0)\r\n    add!(program, :even, value_function = x -> x.value > 0 ? Cell{T}(T(x.value / 2), x.depth, x.output_index) : x)\r\n    add!(program, :odd, value_function = x -> Cell{T}(T(x.value * 3 + 1), x.depth, x.output_index))\r\n    @time run(program)\r\n    return program.dest\r\nend\r\n\r\nbatched = ragamuffin_collatz()\r\n@info batched\r\n@assert expected == batched\r\n", "meta": {"hexsha": "c9aa89cfbaa1afa83deefcf2eb251fadca68c97d", "size": 1138, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/collatz.jl", "max_stars_repo_name": "xaellison/Ragamuffin.jl", "max_stars_repo_head_hexsha": "6d0fe5c29b632e3c06f44804f3660cb0a270d38a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/collatz.jl", "max_issues_repo_name": "xaellison/Ragamuffin.jl", "max_issues_repo_head_hexsha": "6d0fe5c29b632e3c06f44804f3660cb0a270d38a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/collatz.jl", "max_forks_repo_name": "xaellison/Ragamuffin.jl", "max_forks_repo_head_hexsha": "6d0fe5c29b632e3c06f44804f3660cb0a270d38a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7567567568, "max_line_length": 115, "alphanum_fraction": 0.6177504394, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7585898760073294}}
{"text": "# Matern 3/2 isotropic covariance function\n\n\"\"\"\n    Mat32Iso <: MaternIso\n\nIsotropic Matern 3/2 kernel (covariance)\n```math\nk(x,x') = σ²(1 + √3|x-x'|/ℓ)\\\\exp(-√3|x-x'|/ℓ)\n```\nwith length scale ``ℓ`` and signal standard deviation ``σ``.\n\"\"\"\nmutable struct Mat32Iso{T<:Real} <: MaternIso\n    \"Length scale\"\n    ℓ::T\n    \"Signal variance\"\n    σ2::T\n    \"Priors for kernel parameters\"\n    priors::Array\nend\n\n\"\"\"\nMatern 3/2 isotropic covariance function\n    \n    Mat32Iso(ll::T, lσ::T)\n\n# Arguments\n  - `ll::Real`: length scale (given on log scale)\n  - `lσ::Real`: signal standard deviation (given on log scale)  \n\"\"\"\nMat32Iso(ll::T, lσ::T) where T = Mat32Iso{T}(exp(ll), exp(2 * lσ), [])\n\nfunction set_params!(mat::Mat32Iso, hyp::AbstractVector)\n    length(hyp) == 2 || throw(ArgumentError(\"Matern 3/2 has two parameters, received $(length(hyp)).\"))\n    mat.ℓ, mat.σ2 = exp(hyp[1]), exp(2 * hyp[2])\nend\n\nget_params(mat::Mat32Iso{T}) where T = T[log(mat.ℓ), log(mat.σ2) / 2 ]\nget_param_names(mat::Mat32Iso) = [:ll, :lσ]\nnum_params(mat::Mat32Iso) = 2\n\ncov(mat::Mat32Iso, r::Number) =\n    (s = √3 * r / mat.ℓ; mat.σ2 * (1 + s) * exp(-s))\n\n@inline dk_dll(mat::Mat32Iso, r::Real) =\n    (s = √3 * r / mat.ℓ; mat.σ2 * s^2 * exp(-s))\n", "meta": {"hexsha": "05b56a22bdfe7e79a491a1efded1af176c9b76aa", "size": 1222, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/mat32_iso.jl", "max_stars_repo_name": "mcusi/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 284, "max_stars_repo_stars_event_min_datetime": "2015-07-31T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T07:08:58.000Z", "max_issues_repo_path": "src/kernels/mat32_iso.jl", "max_issues_repo_name": "mcusi/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 171, "max_issues_repo_issues_event_min_datetime": "2015-05-28T12:04:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T06:48:23.000Z", "max_forks_repo_path": "src/kernels/mat32_iso.jl", "max_forks_repo_name": "mcusi/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-05-31T12:44:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:21:38.000Z", "avg_line_length": 26.5652173913, "max_line_length": 103, "alphanum_fraction": 0.6145662848, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229959153748, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7585898756618088}}
{"text": "module Exponential\n\nusing ..Auxiliary, ..TensorTrain\n\nexport trigevalmask, trigeval, trigrefmask, trigrefmask2, trigdiffmask, trigdiff, trigdec, trigdeceval!\nexport cosfactor, cosdec\n\nfunction trigevalmask(t::Vector{T}, ν::Vector{T}) where {T<:AbstractFloat}\n\tn = length(t)\n\tr = length(ν)\n\tif r == 0\n\t\tthrow(ArgumentError(\"the number of frequencies should be positive\"))\n\tend\n\tV = zeros(T, n, 2*r)\n\tfor α ∈ 1:r\n\t\tfor i ∈ 1:n\n\t\t\tV[i,2*α-1] = cos(π*ν[α]*t[i])\n\t\t\tV[i,2*α  ] = sin(π*ν[α]*t[i])\n\t\tend\n\tend\n\treturn V\nend\n\nfunction trigeval(t::Vector{T}, ν::Vector{T}, c::Vector{T}) where {T<:AbstractFloat}\n\tn = length(t)\n\tr = length(ν)\n\tif r == 0\n\t\tthrow(ArgumentError(\"the number of frequencies should be positive\"))\n\tend\n\tif length(c) ≠ 2*r\n\t\tthrow(ArgumentError(\"ν and c are incompatible in size\"))\n\tend\n\tu = zeros(T, length(t))\n\tfor i ∈ 1:n\n\t\tfor α ∈ 1:r\n\t\t\tu[i] += c[2*α-1]*cos(π*ν[α]*t[i])+c[2*α]*sin(π*ν[α]*t[i])\n\t\tend\n\tend\n\treturn u\nend\n\nfunction trigrefmask(η::T, ν::Vector{T}) where {T<:AbstractFloat}\n\tr = length(ν)\n\tif r == 0\n\t\tthrow(ArgumentError(\"the number of frequencies should be positive\"))\n\tend\n\tW = zeros(T, 2*r, 2*r)\n\tfor α ∈ 1:r\n\t\tW[2*α-1,2*α-1] =  cos(π*ν[α]*η)\n\t\tW[2*α,  2*α-1] = -sin(π*ν[α]*η)\n\t\tW[2*α-1,2*α  ] =  sin(π*ν[α]*η)\n\t\tW[2*α,  2*α  ] =  cos(π*ν[α]*η)\n\tend\n\treturn W\nend\n\nfunction trigrefmask2(ν::Vector{T}) where {T<:AbstractFloat}\n\tr = length(ν)\n\tif r == 0\n\t\tthrow(ArgumentError(\"the number of frequencies should be positive\"))\n\tend\n\tW1 = trigrefmask(convert(T, -1/2), ν)\n\tW2 = trigrefmask(convert(T, 1/2), ν)\n\tW = [W1[:] W2[:]]\n\tW = reshape(W, 2*r, 2*r, 2)\n\treturn W\nend\n\nfunction trigdiffmask(ν::Vector{T}) where {T<:AbstractFloat}\n\tr = length(ν)\n\tif r == 0\n\t\tthrow(ArgumentError(\"the number of frequencies should be positive\"))\n\tend\n\tW = zeros(T, 2*r, 2*r)\n\tfor α ∈ 1:r\n\t\tW[2*α-1,2*α  ] =  π*ν[α]\n\t\tW[2*α,  2*α-1] = -π*ν[α]\n\tend\n\treturn W\nend\n\nfunction trigdiff(ν::Vector{T}, c::Vector{T}) where {T<:AbstractFloat}\n\tr = length(ν)\n\tif length(c) ≠ 2*r\n\t\tthrow(ArgumentError(\"ν and c are incompatible in size\"))\n\tend\n\td = zeros(T, 2*r)\n\tfor α ∈ 1:r\n\t\td[2*α-1] =  π*ν[α]*c[2*α]\n\t\td[2*α]   = -π*ν[α]*c[2*α-1]\n\tend\n\treturn d\nend\n\n\nfunction cosfactor(τ::Vector{T}, c::T) where {T<:AbstractFloat}\n\tn = length(τ)\n\tif n == 0\n\t\tthrow(ArgumentError(\"τ should be nonempty\"))\n\tend\n\tU = zeros(T, 2, n, 2)\n\tfor i ∈ 1:n\n\t\tα = c*cos(τ[i])\n\t\tβ = c*sin(τ[i])\n\t\tU[1,i,1] =  α\n\t\tU[2,i,1] =  β\n\t\tU[1,i,2] = -β\n\t\tU[2,i,2] =  α\n\tend\n\treturn U\nend\n\nfunction cosdec(τ::Vector{Vector{T}}, c::Vector{T}) where {T<:AbstractFloat}\n\tL = length(τ)\n\tif length(c) ≠ L\n\t\tthrow(ArgumentError(\"τ and c should be of the same length\"))\n\tend\n\tn = [ size(τ[ℓ]) for ℓ ∈ 1:L ]\n\tif any(τ .== 0)\n\t\tthrow(ArgumentError(\"all elements of τ should be nonempty\"))\n\tend\n\tU = [ cosfactor(τ[ℓ], c[ℓ]) for ℓ ∈ 1:L ]\n\tU[1] = U[1][1:1,:,:]\n\tU[L] = U[L][:,:,1:1]\n\tU = dec(U)\n\treturn U\nend\n\n\n\nfunction trigdec(ν::Vector{T}, c::Vector{T}, L::Int; major::String=\"last\") where {T<:AbstractFloat}\n\tif major ∉ (\"first\", \"last\")\n\t\tthrow(ArgumentError(\"major should be either \\\"last\\\" (default) or \\\"first\\\"\"))\n\tend\n\tr = length(ν)\n\tif length(c) ≠ 2*r\n\t\tthrow(ArgumentError(\"ν and c are incompatible in size\"))\n\tend\n\tU = dec(T, 1, L+1)\n\tU[1] = factor(Matrix{T}(c'), 1, [])\n\tfor ℓ ∈ 1:L\n\t\tU[ℓ+1] = permutedims(trigrefmask2(ν/2^(ℓ-1)), (2,3,1))\n\tend\n\t(major == \"last\") && decreverse!(U)\n\treturn U\nend\n\nfunction trigdeceval!(U::Dec{T,N}, t::Vector{T}, ν::Vector{T}; major::String=\"last\") where {T<:AbstractFloat,N}\n\tif major ∉ (\"first\", \"last\")\n\t\tthrow(ArgumentError(\"major should be either \\\"last\\\" (default) or \\\"first\\\"\"))\n\tend\n\tif N ≠ 3\n\t\tthrow(ArgumentError(\"only one mode index per factor is currently supported\"))\n\tend\n\tn = length(t)\n\tr = length(ν)\n\tL = declength(U)\n\tp = decrank(U)\n\tp = (major == \"last\") ? p[1] : p[L+1]\n\tif p ≠ 2*r\n\t\tthrow(ArgumentError(\"the \", (major == \"last\") ? \"first\" : \"last\", \" rank of U and the size of ν are incompatible\"))\n\tend\n\tW = trigevalmask(t, ν)\n\tif major == \"last\"\n\t\tW = reshape(W, 1, n, 2*r)\n\t\tW = Array{T,N}(W)\n\t\tdecpushfirst!(U, W)\n\telse\n\t\tW = reshape(transpose(W), 2*r, n, 1)\n\t\tW = Array{T,N}(W)\n\t\tdecpush!(U, W)\n\tend\n\treturn U\nend\n\n\nend\n", "meta": {"hexsha": "8da303da50a4f132dd8a3cd59bad350dcdb3c691", "size": 4151, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Exponential.jl", "max_stars_repo_name": "TensorRefinement/TensorRefinement.jl", "max_stars_repo_head_hexsha": "f07d06f67414269cc2c6fdd8db387b3558390d28", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Exponential.jl", "max_issues_repo_name": "TensorRefinement/TensorRefinement.jl", "max_issues_repo_head_hexsha": "f07d06f67414269cc2c6fdd8db387b3558390d28", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-11-21T10:48:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-26T16:03:28.000Z", "max_forks_repo_path": "src/Exponential.jl", "max_forks_repo_name": "TensorRefinement/TensorRefinement.jl", "max_forks_repo_head_hexsha": "f07d06f67414269cc2c6fdd8db387b3558390d28", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-21T09:36:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T09:36:10.000Z", "avg_line_length": 23.3202247191, "max_line_length": 117, "alphanum_fraction": 0.6063599133, "num_tokens": 1643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299591537478, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7585898695541016}}
{"text": "\"\"\"\r\n    planepoint(point::Point, triangle::Polygon)\r\n\r\nTake a triangular plane as a Polygon and a Point within that triangle\r\nand returns the z-value at that point.\r\n\r\n# Examples\r\n```jldoctest\r\njulia> point = Point([-175, 22])\r\nPoint([-175.0, 22.0])\r\n\r\njulia> triangle = Polygon([[-174.55, 32.54, 55], [-186.94, 17.64, 24.5], [-167.95, 17.81, 33.6], [-174.55, 32.54, 55]])\r\nPolygon(Array{Array{Float64,1},1}[[[-174.55, 32.54, 55.0], [-186.94, 17.64, 24.5], [-167.95, 17.81, 33.6], [-174.55, 32.54, 55.0]]])\r\n\r\njulia> planepoint(point, triangle)\r\n37.28550123965308\r\n```\r\n\"\"\"\r\nfunction planepoint(point::Point, triangle::Polygon)\r\n    pCoords = point.coordinates\r\n    tCoords = triangle.coordinates\r\n\r\n    outer = tCoords[1]\r\n    length(outer) < 4 && throw(error(\"The outer ring of a Polygon must have 4 or more Points.\"))\r\n\r\n    x = pCoords[1]\r\n    y = pCoords[2]\r\n\r\n    x1 = outer[1][1]\r\n    y1 = outer[1][2]\r\n    z1 = outer[1][3]\r\n\r\n    x2 = outer[2][1]\r\n    y2 = outer[2][2]\r\n    z2 = outer[2][3]\r\n\r\n    x3 = outer[3][1]\r\n    y3 = outer[3][2]\r\n    z3 = outer[3][3]\r\n\r\n    return (z3 * (x - x1) * (y - y2) + z1 * (x - x2) * (y - y3) + z2 * (x - x3) * (y - y1) -\r\n            z2 * (x - x1) * (y - y3) - z3 * (x - x2) * (y - y1) - z1 * (x - x3) * (y - y2)) /\r\n           ((x - x1) * (y - y2) + (x - x2) * (y - y3) + (x - x3) * (y - y1) -\r\n           (x - x1) * (y - y3) - (x - x2) * (y - y1) - (x - x3) * (y - y2))\r\nend\r\n", "meta": {"hexsha": "06a5ba3e58d56a4f4632b2972d85a5111ee721cb", "size": 1421, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lib/Planes.jl", "max_stars_repo_name": "visr/Turf.jl", "max_stars_repo_head_hexsha": "fe3a61fabe6d5b9e7f0197bf1820be25432c467d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2019-07-08T06:51:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T10:28:51.000Z", "max_issues_repo_path": "src/lib/Planes.jl", "max_issues_repo_name": "visr/Turf.jl", "max_issues_repo_head_hexsha": "fe3a61fabe6d5b9e7f0197bf1820be25432c467d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2019-06-20T13:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-17T19:51:03.000Z", "max_forks_repo_path": "src/lib/Planes.jl", "max_forks_repo_name": "visr/Turf.jl", "max_forks_repo_head_hexsha": "fe3a61fabe6d5b9e7f0197bf1820be25432c467d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-08-01T16:58:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-07T02:30:07.000Z", "avg_line_length": 30.8913043478, "max_line_length": 133, "alphanum_fraction": 0.5045742435, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522863, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7585604314975083}}
{"text": "# Locally Linear Embedding (LLE)\n# ------------------------\n# Nonlinear dimensionality reduction by locally linear embedding,\n# Roweis, S. & Saul, L., Science 290:2323 (2000)\n\n\"\"\"\n\n    LLE{NN <: AbstractNearestNeighbors, T <: Real} <: AbstractDimensionalityReduction\n\nThe `LLE` type represents a locally linear embedding model constructed for `T` type data constructed with a help of the `NN` nearest neighbor algorithm.\n\"\"\"\nstruct LLE{NN <: AbstractNearestNeighbors, T <: Real} <: AbstractDimensionalityReduction\n    nearestneighbors::NN\n    component::AbstractVector{Int}\n    λ::AbstractVector{T}\n    proj::Projection{T}\nend\n\n## properties\noutdim(R::LLE) = size(R.proj, 1)\neigvals(R::LLE) = R.λ\nneighbors(R::LLE) = R.nearestneighbors.k\nvertices(R::LLE) = R.component\n\n## show\nsummary(io::IO, R::LLE) = print(io, \"LLE(outdim = $(outdim(R)), neighbors = $(neighbors(R)))\")\n\n## interface functions\n\"\"\"\n    fit(LLE, data; k=12, maxoutdim=2, nntype=BruteForce, tol=1e-5)\n\nFit a locally linear embedding model to `data`.\n\n# Arguments\n* `data`: a matrix of observations. Each column of `data` is an observation.\n\n# Keyword arguments\n* `k`: a number of nearest neighbors for construction of local subspace representation\n* `maxoutdim`: a dimension of the reduced space.\n* `nntype`: a nearest neighbor construction class (derived from `AbstractNearestNeighbors`)\n* `tol`: an algorithm regularization tolerance\n\n# Examples\n```julia\nM = fit(LLE, rand(3,100)) # construct LLE model\nR = transform(M)          # perform dimensionality reduction\n```\n\"\"\"\nfunction fit(::Type{LLE}, X::AbstractMatrix{T};\n             k::Int=12, maxoutdim::Int=2, nntype=BruteForce, tol::Real=1e-5) where {T<:Real}\n    # Construct NN graph\n    NN = fit(nntype, X, k)\n    D, E = knn(NN, X)\n    _, C = largest_component(SimpleWeightedGraph(adjmat(D,E)))\n\n    X = @view X[:, C]\n    n = length(C)\n\n    # Correct indexes of neighbors if more then one connected component\n    Ec = E\n    if size(E,2) != n\n        R = Dict(zip(C, collect(1:n)))\n        Ec = zeros(Int,k,n)\n        for i in 1 : n\n            Ec[:,i] = map(j->get(R,j,C[i]), E[:,C[i]])\n        end\n    end\n\n    if k > maxoutdim\n        @warn(\"k > maxoutdim: regularization will be used\")\n    else\n        tol = 0\n    end\n\n    # Reconstruct weights and compute embedding:\n    # M = (I - w)'(I - w) = I - w'I - Iw + w'w\n    M = spdiagm(0 => fill(one(T), n))\n    Ones = fill(one(T), k, 1)\n    for i in 1 : n\n        J = Ec[:,i]\n        Z = view(X, :, J) .- view(X, :, i)\n        G = transpose(Z)*Z\n        G += I * tol # regularize\n        w = vec(G \\ Ones)\n        w ./= sum(w)\n        ww = w*transpose(w)\n        for (l, j) in enumerate(J)\n            M[i,j] -= w[l]\n            M[j,i] -= w[l]\n            for (m, jj) in enumerate(J)\n                M[j,jj] = ww[l,m]\n            end\n        end\n    end\n\n    λ, V = decompose(M, maxoutdim)\n    return LLE{nntype, T}(NN, C, λ, rmul!(transpose(V), sqrt(n)))\nend\n\n\"\"\"\n    transform(R::LLE)\n\nTransforms the data fitted to the LLE model `R` into a reduced space representation.\n\"\"\"\ntransform(R::LLE) = R.proj\n", "meta": {"hexsha": "9e939a6be7ca60af92b116ef9adacff7b5add4b9", "size": 3078, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lle.jl", "max_stars_repo_name": "yha/ManifoldLearning.jl", "max_stars_repo_head_hexsha": "29a97cce829f0ab8fb172ac27ddfcfff446596a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71, "max_stars_repo_stars_event_min_datetime": "2015-03-15T17:34:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T19:17:06.000Z", "max_issues_repo_path": "src/lle.jl", "max_issues_repo_name": "yha/ManifoldLearning.jl", "max_issues_repo_head_hexsha": "29a97cce829f0ab8fb172ac27ddfcfff446596a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2015-02-13T17:18:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T21:36:26.000Z", "max_forks_repo_path": "src/lle.jl", "max_forks_repo_name": "yha/ManifoldLearning.jl", "max_forks_repo_head_hexsha": "29a97cce829f0ab8fb172ac27ddfcfff446596a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2015-06-17T17:56:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T21:45:13.000Z", "avg_line_length": 29.0377358491, "max_line_length": 152, "alphanum_fraction": 0.6007147498, "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666346, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7585604190436377}}
{"text": "using GLM, QuantileRegression\n\n# Load data\nurl = \"http://vincentarelbundock.github.io/Rdatasets/csv/quantreg/engel.csv\"\n# TODO: Make automatic URL downloads work\ndat = readtable(\"engel.csv\")\n\n# Fit least absolute deviation model (quantile =.5)\nres = qreg(:(foodexp~income), dat, .5)\ndescribe(res)\n\n# Fit quantile regression for a bunch of different quantiles\ndat_plot = [summary(qreg(:(foodexp ~ income), dat, i/10))[2,:] for i in 1:9]\ndat_plot = reduce(vcat, dat_plot)\n\n# Fit OLS model to compare\nres_lm = lm(:(foodexp~income), dat)\nols = coeftable(res_lm)[2,1]\nols = rep(ols, 9)\n\n# Plot results\nusing Winston\n\nx = [i/10 for i=1:9]\ny = dat_plot[\"Estimate\"]\np = FramedPlot()\nadd(p, Curve(x, dat_plot[\"Estimate\"]))\nadd(p, Curve(x, dat_plot[\"2.5%\"], \"type\", \"dash\"))\nadd(p, Curve(x, dat_plot[\"97.5%\"], \"type\", \"dash\"))\nadd(p, Curve(x, ols, \"color\", \"red\"))\nsetattr(p, \"title\", \"Quantile regression: Food Expenditure ~ Income\\n Red bar: OLS coefficient\")\nsetattr(p, \"xlabel\", \"Quantiles\")\nsetattr(p, \"ylabel\", \"Coefficient on Income\")\nfile(p, \"/Users/USERNAME/qreg_example_plot.png\")\n\n# > summary(res)\n# 2x5 DataFrame:\n#         Estimate Std.Error t value     2.5%    97.5%\n# [1,]     81.4823   14.6345 5.56783  52.7987  110.166\n# [2,]    0.560181 0.0131756 42.5164 0.534356 0.586005\n# insheet using engel.csv\n# qreg foodexp income, vce(iid, kernel(epan2))\n \n# . qreg foodexp income, vce(iid, kernel(epan2))\n# Iteration  1:  WLS sum of weighted deviations =  18051.196\n# \n# Iteration  1: sum of abs. weighted deviations =  18035.127\n# Iteration  2: sum of abs. weighted deviations =  17815.249\n# Iteration  3: sum of abs. weighted deviations =  17567.085\n# Iteration  4: sum of abs. weighted deviations =  17559.932\n# \n# Median regression                                    Number of obs =       235\n#   Raw sum of deviations 46278.06 (about 582.54126)\n#   Min sum of deviations 17559.93                     Pseudo R2     =    0.6206\n# \n# ------------------------------------------------------------------------------\n#      foodexp |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]\n# -------------+----------------------------------------------------------------\n#       income |   .5601805   .0131763    42.51   0.000     .5342206    .5861403\n#        _cons |   81.48233   14.63518     5.57   0.000     52.64815    110.3165\n# ------------------------------------------------------------------------------\n", "meta": {"hexsha": "e30ee51054204571babebcbb43496eda7ac9c4c5", "size": 2420, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/qreg_example.jl", "max_stars_repo_name": "johnmyleswhite/QuantileRegression.jl", "max_stars_repo_head_hexsha": "633e0b8340eca27f0f3b0929081f9fa57cea937e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-08-17T13:07:38.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-17T13:07:38.000Z", "max_issues_repo_path": "examples/qreg_example.jl", "max_issues_repo_name": "johnmyleswhite/QuantileRegression.jl", "max_issues_repo_head_hexsha": "633e0b8340eca27f0f3b0929081f9fa57cea937e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/qreg_example.jl", "max_forks_repo_name": "johnmyleswhite/QuantileRegression.jl", "max_forks_repo_head_hexsha": "633e0b8340eca27f0f3b0929081f9fa57cea937e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-18T22:57:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T22:57:23.000Z", "avg_line_length": 39.0322580645, "max_line_length": 96, "alphanum_fraction": 0.5772727273, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810421953309, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7585604189174029}}
{"text": "immutable BetaPrime <: ContinuousUnivariateDistribution\n    betad::Beta\n\n    BetaPrime(α::Float64, β::Float64) = new(Beta(α, β))\n    BetaPrime(α::Float64) = new(Beta(α))\n    BetaPrime() = new(Beta())\nend\n\n@distr_support BetaPrime 0.0 Inf\n\n\n#### Parameters\n\nparams(d::BetaPrime) = params(d.betad)\n\n\n#### Statistics\n\nmean(d::BetaPrime) = ((α, β) = params(d); β > 1.0 ? α / (β - 1.0) : NaN)\n\nmode(d::BetaPrime) = ((α, β) = params(d); α > 1.0 ? (α - 1.0) / (β + 1.0) : 0.0)\n\nfunction var(d::BetaPrime)\n    (α, β) = params(d)\n    β > 2.0 ? α * (α + β - 1.0) / ((β - 2.0) * (β - 1.0)^2) : NaN\nend\n\nfunction skewness(d::BetaPrime)\n    (α, β) = params(d)\n    if β > 3.0\n        s = α + β - 1.0\n        2.0 * (α + s) / (β - 3.0) * sqrt((β - 2.0) / (α * s))\n    else\n        return NaN\n    end\nend\n\n\n#### Evaluation\n\nfunction logpdf(d::BetaPrime, x::Float64)\n    (α, β) = params(d)\n    (α - 1.0) * log(x) - (α + β) * log1p(x) - lbeta(α, β)\nend\n\npdf(d::BetaPrime, x::Float64) = exp(logpdf(d, x))\n\ncdf(d::BetaPrime, x::Float64) = cdf(d.betad, x / (1.0 + x))\nccdf(d::BetaPrime, x::Float64) = ccdf(d.betad, x / (1.0 + x))\nlogcdf(d::BetaPrime, x::Float64) = logcdf(d.betad, x / (1.0 + x))\nlogccdf(d::BetaPrime, x::Float64) = logccdf(d.betad, x / (1.0 + x))\n\nquantile(d::BetaPrime, p::Float64) = (x = quantile(d.betad, p); x / (1.0 - x))\ncquantile(d::BetaPrime, p::Float64) = (x = cquantile(d.betad, p); x / (1.0 - x))\ninvlogcdf(d::BetaPrime, p::Float64) = (x = invlogcdf(d.betad, p); x / (1.0 - x))\ninvlogccdf(d::BetaPrime, p::Float64) = (x = invlogccdf(d.betad, p); x / (1.0 - x))\n    \n\n#### Sampling\n\nfunction rand(d::BetaPrime) \n    (α, β) = params(d)\n    rand(Gamma(α)) / rand(Gamma(β))\nend\n\n", "meta": {"hexsha": "976ea388ec241e3fd4cdfbc6999d1e57bcb3aea7", "size": 1681, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/betaprime.jl", "max_stars_repo_name": "Hua-Zhou/Distributions.jl", "max_stars_repo_head_hexsha": "c80563a8cf839642dc1b8b2c32d6518d89f1229e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-11T18:43:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T18:43:39.000Z", "max_issues_repo_path": "src/univariate/continuous/betaprime.jl", "max_issues_repo_name": "Hua-Zhou/Distributions.jl", "max_issues_repo_head_hexsha": "c80563a8cf839642dc1b8b2c32d6518d89f1229e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/betaprime.jl", "max_forks_repo_name": "Hua-Zhou/Distributions.jl", "max_forks_repo_head_hexsha": "c80563a8cf839642dc1b8b2c32d6518d89f1229e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4696969697, "max_line_length": 82, "alphanum_fraction": 0.5496728138, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7585398071856887}}
{"text": "using LinearAlgebra, Plots\n\nRx(θ::Real) = [1 0 0 0; \n        0 cos(θ) -sin(θ) 0; \n        0 sin(θ) cos(θ) 0;\n        0 0 0 1]\n\nRy(θ::Real) = [cos(θ) 0 -sin(θ) 0; \n        0 1 0 0; \n        sin(θ) 0 cos(θ) 0;\n        0 0 0 1]\n\nRz(θ::Real) = [cos(θ) -sin(θ) 0 0;\n        sin(θ) cos(θ) 0 0;\n        0 0 1 0;\n        0 0 0 1]\n\nTx(d::Real) = [1 0 0 d;\n        0 1 0 0;\n        0 0 1 0;\n        0 0 0 1]\n\nπ = pi\nd = 2\nangToRad(ang::Real) = (π/180)*ang\nθ(ang::Real = 150) = angToRad(ang) #70\nω(ang::Real = 160) = angToRad(ang)\n\nB1 = I(4) #nada a fazer\n\n#B2 =  Ry(π)*Tx(d)\n\nB2 = zeros(4,4)\nB2[1,1] = -1.0\nB2[2,2] = 1.0\nB2[3,3] = -1.0\nB2[4,4] = 1.0\nB2[1,4] = -d\n\n#B3 = Rx(π)*Rz(θ())*Ry(π)*Tx(d)\n\n# tird atom\ncθ,sθ = (cos(θ()),sin(θ()))\nB3 = zeros(4,4)\nB3[1,1] = -cθ\nB3[1,2] = -sθ\nB3[1,4] = -d*cθ\nB3[2,1] = sθ\nB3[2,2] = -cθ\nB3[2,4] = d*sθ\nB3[3,3] = 1.0\nB3[4,4] = 1.0\n\nfunction torsionmatrix(cosθ,sinθ,cosω,sinω,d34,sign::Bool)\n\tif sign == true\n\t\t\n\t\tB=zeros(4,4)\n\t\tB[1,1] = -cosθ\n\t\tB[1,2] = -sinθ\n\t\tB[1,4] = -d34*cosθ\n\t\tB[2,1] = sinθ*cosω\n\t\tB[2,2] = -cosθ*cosω\n\t\tB[2,3] = -sinω\n\t\tB[2,4] = d34*sinθ*cosω\n\t\tB[3,1] = sinθ*sinω\n\t\tB[3,2] = -cosθ*sinω\n\t\tB[3,3] = cosω\n\t\tB[3,4] = d34*sinθ*sinω \n\t\tB[4,4] = 1\n\telse\n\t\t\n\t\tB=zeros(4,4)\n\t\tB[1,1] = -cosθ\n\t\tB[1,2] = -sinθ\n\t\tB[1,4] = -d34*cosθ\n\t\tB[2,1] = sinθ*cosω\n\t\tB[2,2] = -cosθ*cosω\n\t\tB[2,3] = sinω\n\t\tB[2,4] = d34*sinθ*cosω\n\t\tB[3,1] = -sinθ*sinω\n\t\tB[3,2] = cosθ*sinω\n\t\tB[3,3] = cosω\n\t\tB[3,4] = -d34*sinθ*sinω \n\t\tB[4,4] = 1\n\t\t\n\tend\n\treturn B\nend\n\nBi(ω = ω(), θ = θ(), d = d) = torsionmatrix(cos(angToRad(θ)), sin(angToRad(θ)), cos(angToRad(ω)), sin(angToRad(ω)), d, false) #Bi(ω = ω(), θ = θ(), d = d) = Rx(ω)*Rx(π)*Rz(θ)*Ry(π)*Tx(d)\n\nBi′(B) = B*inv(Tx(d))\n\nunk = [1 0 0 0;\n        0 1 0 0;\n        0 0 1 0;\n        1 1 1 1]\n\nfunction sysGenerate(B, α = 1; title = true)\n    if title\n\t\treturn [\"x/|x|\" \"y/|y|\" \"z/|z|\" \"i\"; B*unk*α]\t\t\n\telse\n\t\treturn B*unk*α\n\tend\nend\n\nfunction flatProjection(A, x̂ = [cos(π/4) -cos(π/4)]'*0.5; x :: Bool = true)\n\tif x\n\t\treturn [A[2:3,1]+x̂*A[1,1] A[2:3,2]+x̂*A[1,2] A[2:3,3]+x̂*A[1,3] A[2:3,4]+x̂*A[1,4]]\n\telse\n\t\treturn [A[1:2,1]+x̂*A[3,1] A[1:2,2]+x̂*A[3,2] A[1:2,3]+x̂*A[3,3] A[1:2,4]+x̂*A[3,4]]\n\tend\nend\t\n\nfunction plotFlatProjection(B; sprain=1.01, static = false)\n\tparam = [B[1,4]+B[2,4]im, B[1,4]+B[2,4]im+B[1,1]+B[2,1]im, Inf, B[1,4]+B[2,4]im, B[1,4]+B[2,4]im+B[1,2]+B[2,2]im, Inf, B[1,4]+B[2,4]im, B[1,4]+B[2,4]im+B[1,3]+B[2,3]im]\n\tif static\n\t\tplot!(param, arrow = 2)\n\telse\n\t\tplot(param, arrow = 2)\n\tend\n\tannotate!(B[1,4]*sprain, B[2,4]*sprain, text(\"v\", :black, :right, 10))\n\tannotate!(B[1,4]+B[1,1]*sprain, B[2,4]+B[2,1]*sprain, text(\"x\", :black, :right, 10))\n\tannotate!(B[1,4]+B[1,2]*sprain, B[2,4]+B[2,2]*sprain, text(\"y\", :black, :right, 10))\n\tannotate!(B[1,4]+B[1,3]*sprain, B[2,4]+B[2,3]*sprain, text(\"z\", :black, :right, 10))\n\t# ylims!((-1.5,2)); xlims!((-1.5,1.5))\nend\n\nprint(\"DmdgpRealization included\\n\")\n\n#rotationFactor = Rz(π/2)*Rx(π/2)*Rz(-θ(30))*Rx(π)\n#sysGenerate(flatProjection(rotationFactor*B2*B3*Bi(ω(230),θ(120))), 20)\n#Bo = B2*B3*Bi(ω(230),θ(120))\n#B = Bi(ω(230),θ(120))\n#sysGenerate(flatProjection(rotationFactor*Bo*B*B*B), 20)\n\n# a good initial image \n\n# plotFlatProjection(flatProjection(B1, [-cos(π/4) -cos(π/4)]'*0.707))\n# plotFlatProjection(flatProjection(B1*Ry(π)*Tx(2.5), [-cos(π/4) -cos(π/4)]'*0.707), static = true)\n# plotFlatProjection(flatProjection(B1*B2*Rx(π)*Rz(θ(75))*Ry(π)*Tx(2.5), [-cos(π/4) -cos(π/4)]'*0.707), static = true)\n# ylims!((-1,2)); xlims!((-1,4))", "meta": {"hexsha": "f8f1b0b647141c317e0599b60da66edfa307b80a", "size": 3468, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "DmdgpRealization.jl", "max_stars_repo_name": "caomem/DmdgpRealization", "max_stars_repo_head_hexsha": "3a810c6e806fee5dfe1f38af36b2c6cf12251046", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DmdgpRealization.jl", "max_issues_repo_name": "caomem/DmdgpRealization", "max_issues_repo_head_hexsha": "3a810c6e806fee5dfe1f38af36b2c6cf12251046", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DmdgpRealization.jl", "max_forks_repo_name": "caomem/DmdgpRealization", "max_forks_repo_head_hexsha": "3a810c6e806fee5dfe1f38af36b2c6cf12251046", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4225352113, "max_line_length": 186, "alphanum_fraction": 0.5265282584, "num_tokens": 1928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509314, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7585397967434384}}
{"text": "# Define and register smooth functions\n_cos_wave(t, f, A, st, ϕ) = A*cos(2*π*f*(t - st) + ϕ)\n_sin_wave(t, f, A, st, ϕ) = A*sin(2*π*f*(t - st) + ϕ)\n_damped_sine_wave(t, f, A, st, ϕ, d) = exp((st-t)*d)*A*sin(2*π*f*(t-st) + ϕ)\n_ramp(t, δ, st, et, h) = h/(et-st)*(_xH(t, δ, st) - _xH(t, δ, et))\n_square_wave(t, δ, f, A, st) = A*2atan(sin(2π*(t-st)*f)/δ)/π\n_step(t, δ, h, a) = h*(atan((t-a)/δ)/π + 0.5)\n_triangular_wave(t, δ, f, A, st) = A*(1-2acos((1 - δ)sin(2π*(t-st)*f))/π)\n_xH(t, δ, tₒ) = (t-tₒ)*(1+((t-tₒ)/sqrt((t-tₒ)^2+δ^2)))/2\n\n@register_symbolic _cos_wave(t, f, A, st, ϕ)\n@register_symbolic _sin_wave(t, f, A, st, ϕ)\n@register_symbolic _damped_sine_wave(t, f, A, st, ϕ, damping)\n@register_symbolic _ramp(t, δ, st, et, h)\n@register_symbolic _square_wave(t, δ, f, A, st)\n@register_symbolic _step(t, δ, h, a)\n@register_symbolic _triangular_wave(t, δ, f, A, st)\n\n\"\"\"\n    ConstantVoltage(;name, V = 1.0)   \n\nSource for constant voltage,\n\n# Parameters:\n- `V`: [V] Voltage\n\"\"\"\nfunction ConstantVoltage(;name, V = 1.0)   \n    @named oneport = OnePort()\n    @unpack v, i = oneport\n    pars = @parameters V=V\n    eqs = [\n        v ~ V\n    ]\n    \n    extend(ODESystem(eqs, t, [], pars; name=name), oneport)\nend\n\n\"\"\"\n    CosineVoltage(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0)\n\nGenerate cosine voltage.\n\n# Parameters:\n- `frequency`: [Hz] Frequency of sine wave\n- `amplitude`: [V] Amplitude of sine wave\n- `phase`: [rad] Phase of sine wave \n- `offset`: [V] Offset of output voltage\n- `start_time`: [s] Output `y = offset` for `t < start_time`\n\"\"\"\nfunction CosineVoltage(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0)\n    δ = 0.00001\n\n    @named oneport = OnePort()\n    @unpack v, i = oneport\n    pars = @parameters begin\n        offset=offset\n        amplitude=amplitude \n        frequency=frequency \n        start_time=start_time \n        phase=phase\n    end\n    eqs = [\n        v ~ _cos_wave(t, frequency, amplitude, start_time, phase) * _step(t, δ, 1.0, start_time) + offset\n    ]\n    \n    extend(ODESystem(eqs, t, [], pars; name=name), oneport)\nend\n\n\"\"\"\nGenerate damped sine voltage.\n\n# Parameters:\n- `frequency`: [Hz] Frequency of sine wave\n- `amplitude`: [V] Amplitude of sine wave\n- `damping`: [1/s] Damping coefficient of sine wave\n- `phase`: [rad] Phase of sine wave \n- `offset`: [V] Offset of output voltage\n- `start_time`: [s] Output `y = offset` for `t < start_time`\n\"\"\"\nfunction ExpSineVoltage(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0, damping=0.0)\n    δ = 0.00001\n    @named oneport = OnePort()\n    @unpack v, i = oneport\n    pars = @parameters begin\n        offset=offset\n        amplitude=amplitude \n        frequency=frequency\n        start_time=start_time\n        phase=phase \n        damping=damping\n    end\n    eqs = [\n        v ~ _damped_sine_wave(t, frequency, amplitude, start_time, phase, damping) * _step(t, δ, 1.0, start_time)\n    ]\n    \n    extend(ODESystem(eqs, t, [], pars; name=name), oneport)\nend\n\n\"\"\"\n    RampVoltage(;name, offset=0.0, start_time=0.0, duration=1.0, height=1.0)\n\nGenerate ramp voltage.\n\n# Parameters:\n- `height`: [V] Height of ramp\n- `duration`: [s] Duration of ramp (= 0.0 gives a Step)\n- `offset`: [V] Offset of output voltage\n- `start_time`: [s] Output `y = offset` for `t < start_time`\n\"\"\"\nfunction RampVoltage(;name, offset=0.0, start_time=0.0, duration=1.0, height=1.0)\n    δ = 0.00001\n    @named oneport = OnePort()\n    @unpack v, i = oneport\n    pars = @parameters begin\n        offset=offset\n        height=height \n        start_time=start_time \n        duration=duration\n    end\n    eqs = [\n        v ~ _ramp(t, δ, start_time, start_time + duration, height) + offset\n    ]\n    \n    extend(ODESystem(eqs, t, [], pars; name=name), oneport)\nend\n\n\"\"\"\n    SineVoltage(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0)\n\nGenerate sine voltage.\n\n# Parameters:\n- `frequency`: [Hz] Frequency of sine wave\n- `amplitude`: [V] Amplitude of sine wave\n- `phase`: [rad] Phase of sine wave \n- `offset`: [V] Offset of output voltage\n- `start_time`: [s] Output `y = offset` for `t < start_time`\n\"\"\"\nfunction SineVoltage(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0)\n    δ = 0.00001\n\n    @named oneport = OnePort()\n    @unpack v, i = oneport\n    pars = @parameters begin\n        offset=offset\n        amplitude=amplitude \n        frequency=frequency \n        start_time=start_time \n        phase=phase\n    end\n    eqs = [\n        v ~ _sin_wave(t, frequency, amplitude, start_time, phase) * _step(t, δ, 1.0, start_time) + offset\n    ]\n    \n    extend(ODESystem(eqs, t, [], pars; name=name), oneport)\nend\n\n\"\"\"\n    SquareVoltage(; name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0)\n\nGenerate square voltage.\n\"\"\"\nfunction SquareVoltage(; name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0)\n    δ = 0.0001\n\n    @named oneport = OnePort()\n    @unpack v, i = oneport\n    pars = @parameters begin\n        offset=offset\n        amplitude=amplitude \n        start_time=start_time \n    end\n    eqs = [\n        v ~ _square_wave(t, δ, frequency, amplitude, start_time) * _step(t, δ, 1.0, start_time) + offset\n    ]\n    \n    extend(ODESystem(eqs, t, [], pars; name=name), oneport)\nend\n\n\"\"\"\n    StepVoltage(;name, offset=0.0, start_time=0.0, height=1.0)\n\nGenerate step voltage.\n\n# Parameters:\n- `height`: [V] Height of step\n- `offset`: [V] Offset of output voltage\n- `start_time`: [s] Output `y = offset` for `t < start_time`\n\"\"\"\nfunction StepVoltage(;name, offset=0.0, start_time=0.0, height=1.0)\n    δ = 0.0001\n\n    @named oneport = OnePort()\n    @unpack v, i = oneport\n    pars = @parameters begin\n        offset=offset\n        height=height \n        start_time=start_time \n    end\n    eqs = [\n        v ~ _step(t, δ, height, start_time) + offset\n    ]\n    \n    extend(ODESystem(eqs, t, [], pars; name=name), oneport)\nend\n\nfunction TriangularVoltage(; name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0)\n    δ = 0.00001\n\n    @named oneport = OnePort()\n    @unpack v, i = oneport\n    pars = @parameters begin\n        offset=offset\n        amplitude=amplitude \n        frequency=frequency \n        start_time=start_time \n    end\n    eqs = [\n        v ~ _triangular_wave(t, δ, frequency, amplitude, start_time) * _step(t, δ, 1.0, start_time) + offset\n    ]\n    \n    extend(ODESystem(eqs, t, [], pars; name=name), oneport)\nend\n\n# Current Sources ######################################################################################################\n\"\"\"\n    ConstantCurrent(;name, I = 1.0)   \n\nSource for constant current.\n\n# Parameters:\n- `I`: [A] Current\n\"\"\"\nfunction ConstantCurrent(;name, I = 1.0)   \n    @named oneport = OnePort()\n    @unpack v, i = oneport\n    pars = @parameters I=I\n    eqs = [\n        i ~ I\n    ]\n    \n    extend(ODESystem(eqs, t, [], pars; name=name), oneport)\nend\n\n\"\"\"\n    CosineCurrent(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0)\n\nGenerate cosine current.\n\n# Parameters:\n- `frequency`: [Hz] Frequency of sine wave\n- `amplitude`: [A] Amplitude of sine wave\n- `phase`: [rad] Phase of sine wave \n- `offset`: [A] Offset of output current\n- `start_time`: [s] Output `y = offset` for `t < start_time`\n\"\"\"\nfunction CosineCurrent(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0)\n    δ = 0.00001\n\n    @named oneport = OnePort()\n    @unpack v, i = oneport\n    pars = @parameters begin\n        offset=offset\n        amplitude=amplitude \n        frequency=frequency \n        start_time=start_time \n        phase=phase\n    end\n    eqs = [\n        i ~ _cos_wave(t, frequency, amplitude, start_time, phase) * _step(t, δ, 1.0, start_time) + offset\n    ]\n    \n    extend(ODESystem(eqs, t, [], pars; name=name), oneport)\nend\n\n\"\"\"\n    ExpSineCurrent(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0, damping=0.0)\n\nGenerate damped sine current.\n\n# Parameters:\n- `frequency`: [Hz] Frequency of sine wave\n- `amplitude`: [A] Amplitude of sine wave\n- `damping`: [1/s] Damping coefficient of sine wave\n- `phase`: [rad] Phase of sine wave \n- `offset`: [A] Offset of output current\n- `start_time`: [s] Output `y = offset` for `t < start_time`\n\"\"\"\nfunction ExpSineCurrent(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0, damping=0.0)\n    δ = 0.00001\n    @named oneport = OnePort()\n    @unpack v, i = oneport\n    pars = @parameters begin\n        offset=offset\n        amplitude=amplitude \n        frequency=frequency\n        start_time=start_time\n        phase=phase \n        damping=damping\n    end\n    eqs = [\n        i ~ _damped_sine_wave(t, frequency, amplitude, start_time, phase, damping) * _step(t, δ, 1.0, start_time)\n    ]\n    \n    extend(ODESystem(eqs, t, [], pars; name=name), oneport)\nend\n\n\"\"\"\n    RampCurrent(;name, offset=0.0, start_time=0.0, duration=1.0, height=1.0)\n\nGenerate ramp current.\n\n# Parameters:\n- `height`: [A] Height of ramp\n- `duration`: [s] Duration of ramp (= 0.0 gives a Step)\n- `offset`: [A] Offset of output current\n- `start_time`: [s] Output `y = offset` for `t < start_time`\n\"\"\"\nfunction RampCurrent(;name, offset=0.0, start_time=0.0, duration=1.0, height=1.0)\n    δ = 0.00001\n    @named oneport = OnePort()\n    @unpack v, i = oneport\n    pars = @parameters begin\n        offset=offset\n        height=height \n        start_time=start_time \n        duration=duration\n    end\n    eqs = [\n        i ~ _ramp(t, δ, start_time, start_time + duration, height) + offset\n    ]\n    \n    extend(ODESystem(eqs, t, [], pars; name=name), oneport)\nend\n\n\"\"\"\n    SineCurrent(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0)\n\nGenerate sine current.\n\n# Parameters:\n- `frequency`: [Hz] Frequency of sine wave\n- `amplitude`: [A] Amplitude of sine wave\n- `phase`: [rad] Phase of sine wave \n- `offset`: [A] Offset of output current\n- `start_time`: [s] Output `y = offset` for `t < start_time`\n\"\"\"\nfunction SineCurrent(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0)\n    δ = 0.00001\n\n    @named oneport = OnePort()\n    @unpack v, i = oneport\n    pars = @parameters begin\n        offset=offset\n        amplitude=amplitude \n        frequency=frequency \n        start_time=start_time \n        phase=phase\n    end\n    eqs = [\n        i ~ _sin_wave(t, frequency, amplitude, start_time, phase) * _step(t, δ, 1.0, start_time) + offset\n    ]\n    \n    extend(ODESystem(eqs, t, [], pars; name=name), oneport)\nend\n\nfunction SquareCurrent(; name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0)\n    δ = 0.0001\n\n    @named oneport = OnePort()\n    @unpack v, i = oneport\n    pars = @parameters begin\n        offset=offset\n        amplitude=amplitude \n        start_time=start_time \n    end\n    eqs = [\n        i ~ _square_wave(t, δ, frequency, amplitude, start_time) * _step(t, δ, 1.0, start_time) + offset\n    ]\n    \n    extend(ODESystem(eqs, t, [], pars; name=name), oneport)\nend\n\n\"\"\"\n    StepCurrent(;name, offset=0.0, start_time=0.0, height=1.0)\n\nGenerate step current.\n\n# Parameters:\n- `height`: [A] Height of step\n- `offset`: [A] Offset of output current\n- `start_time`: [s] Output `y = offset` for `t < start_time`\n\"\"\"\nfunction StepCurrent(;name, offset=0.0, start_time=0.0, height=1.0)\n    δ = 0.0001\n\n    @named oneport = OnePort()\n    @unpack v, i = oneport\n    pars = @parameters begin\n        offset=offset\n        height=height \n        start_time=start_time \n    end\n    eqs = [\n        i ~ _step(t, δ, height, start_time) + offset\n    ]\n    \n    extend(ODESystem(eqs, t, [], pars; name=name), oneport)\nend\n\nfunction TriangularCurrent(; name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0)\n    δ = 0.00001\n\n    @named oneport = OnePort()\n    @unpack v, i = oneport\n    pars = @parameters begin\n        offset=offset\n        amplitude=amplitude \n        frequency=frequency \n        start_time=start_time \n    end\n    eqs = [\n        i ~ _triangular_wave(t, δ, frequency, amplitude, start_time) * _step(t, δ, 1.0, start_time) + offset\n    ]\n    \n    extend(ODESystem(eqs, t, [], pars; name=name), oneport)\nend\n", "meta": {"hexsha": "c68f1c96294735c5f02bb727b45aebbbec6f4106", "size": 12109, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Electrical/Analog/sources.jl", "max_stars_repo_name": "AayushSabharwal/ModelingToolkitStandardLibrary.jl", "max_stars_repo_head_hexsha": "4b081e638e26db5d67e0de258e40815242687132", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Electrical/Analog/sources.jl", "max_issues_repo_name": "AayushSabharwal/ModelingToolkitStandardLibrary.jl", "max_issues_repo_head_hexsha": "4b081e638e26db5d67e0de258e40815242687132", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Electrical/Analog/sources.jl", "max_forks_repo_name": "AayushSabharwal/ModelingToolkitStandardLibrary.jl", "max_forks_repo_head_hexsha": "4b081e638e26db5d67e0de258e40815242687132", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2920560748, "max_line_length": 120, "alphanum_fraction": 0.6162358576, "num_tokens": 3912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806521, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7585397873109708}}
{"text": "#=\n  Aircrat position.\n  From BLOG example/aircraft-position.blog\n\n  Distributions of variable numAircraft (num:0)\n  3.00000 =>    5857  (0.585700)\n  4.00000 =>    3178  (0.317800)\n  5.00000 =>     833  (0.083300)\n  6.00000 =>     114  (0.011400)\n  7.00000 =>      18  (0.001800)\n\n  Also see ~/webppl/aircraft_position.wppl \n=#  \n\nusing Turing, StatsPlots, DataFrames\n# using ReverseDiff, Zygote, Tracker\n# Turing.setadbackend(:reversediff)\n# Turing.setadbackend(:zygote)\n# Turing.setadbackend(:tracker)\n\ninclude(\"jl_utils.jl\")\n\n@model function aircraft_position()\n    epsilon = 0.05\n    \n    # Poisson might get 0 which is not good for this model\n    pp ~ Poisson(5) \n    numAircraft ~ Dirac(pp == 0 ? 1 : pp)\n\n    blips = tzeros(numAircraft)\n    positions = tzeros(numAircraft)\n    obsPos = tzeros(numAircraft)\n    for b in 1:numAircraft\n        blips[b] ~ flip(0.9)\n        positions[b] ~ Normal(0,10)\n        obsPos[b] ~ Normal(positions[b],1)\n    end\n    \n    sumBlips ~ Dirac(sum(blips))\n\n    function inRange(x,y,epsilon)\n        Dirac(x > y - epsilon && x < y + epsilon)\n    end\n    \n    true ~ Dirac(sumBlips == 3)\n   \n    inRange(obsPos[1],5.0,epsilon)\n    numAircraftPositionLt5 ~ Dirac(sum([positions[a] > 5 ? 1 : 0 for a in 1:numAircraft]))\nend\n\nmodel = aircraft_position()\n\nnum_chns = 4\n# chns = sample(model, Prior(), 1000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(5), 10_000)\n# chns = sample(model, IS(), 10_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, SMC(), MCMCThreads(), 10_000, num_chns)\n\n\ndisplay(chns)\n# display(plot(chns))\n\nshow_var_dist_pct(chns, :numAircraft)\n", "meta": {"hexsha": "2114cc28a3ff8ff52ce971991838611f72725df2", "size": 1627, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/aircraft_position.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/aircraft_position.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/aircraft_position.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 24.6515151515, "max_line_length": 90, "alphanum_fraction": 0.6422864167, "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7585268405382178}}
{"text": "using SchumakerSpline\nfrom = 0.5\nto = 10\nx1 = collect(range(from, stop=to, length=40))\ny1 = (x1).^2\nx2 = [0.5,0.75,0.8,0.93,0.9755,1.0,1.1,1.4,2.0]\ny2 = sqrt.(x2)\nleft_spline = Schumaker(x1,y1)\nright_spline = Schumaker(x2,y2)\n\ncrossover_point = get_intersection_points(left_spline,right_spline)\n\nsplice_point = crossover_point[1]\nspliced = splice_splines(left_spline, right_spline, splice_point)\n# Testing at splice point\nabs(evaluate(spliced, splice_point) - evaluate(right_spline, splice_point))          < 100*eps()\n# As this was a continuous split\nabs(evaluate(spliced, splice_point- 100*eps()) - evaluate(spliced, splice_point + 100*eps()))          < 10000*eps()\n# Testing in left spline territory.\nabs(evaluate(spliced, splice_point-0.5) - evaluate(left_spline, splice_point-0.5))   < 100*eps()\nabs(evaluate(spliced, splice_point-0.5) - evaluate(right_spline, splice_point-0.5))  > 0.1\n# Testing solidly into right spline territory.\nabs(evaluate(spliced, splice_point+0.5) - evaluate(left_spline, splice_point+0.5))   > 100*eps()\nabs(evaluate(spliced, splice_point+0.5) - evaluate(right_spline, splice_point+0.5))  < 0.1\n\nsplice_point = 1.7\nspliced = splice_splines(left_spline, right_spline, splice_point)\n# Testing at splice point\nabs(evaluate(spliced, splice_point) - evaluate(right_spline, splice_point))          < 100*eps()\n# As this was NOT a continuous split\nabs(evaluate(spliced, splice_point- 100*eps()) - evaluate(spliced, splice_point + 100*eps()))  > 0.1\n# Testing in left spline territory.\nabs(evaluate(spliced, splice_point-0.5) - evaluate(left_spline, splice_point-0.5))   < 100*eps()\nabs(evaluate(spliced, splice_point-0.5) - evaluate(right_spline, splice_point-0.5))  > 0.1\n# Testing solidly into right spline territory.\nabs(evaluate(spliced, splice_point+0.5) - evaluate(left_spline, splice_point+0.5))   > 100*eps()\nabs(evaluate(spliced, splice_point+0.5) - evaluate(right_spline, splice_point+0.5))  < 0.1\n", "meta": {"hexsha": "8ebae9fe723cf91cd59d1edcfe90231793481f2f", "size": 1934, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_splice_splines.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SchumakerSpline.jl-65e68595-3a03-5ff5-a6a2-f05fa774f32e", "max_stars_repo_head_hexsha": "d9ec5723ab4896e96c83ad4cf47e16b7c82731c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-04-12T00:50:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T18:31:02.000Z", "max_issues_repo_path": "test/test_splice_splines.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SchumakerSpline.jl-65e68595-3a03-5ff5-a6a2-f05fa774f32e", "max_issues_repo_head_hexsha": "d9ec5723ab4896e96c83ad4cf47e16b7c82731c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-10-14T12:39:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T23:53:29.000Z", "max_forks_repo_path": "test/test_splice_splines.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SchumakerSpline.jl-65e68595-3a03-5ff5-a6a2-f05fa774f32e", "max_forks_repo_head_hexsha": "d9ec5723ab4896e96c83ad4cf47e16b7c82731c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-08-10T06:39:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:21:27.000Z", "avg_line_length": 50.8947368421, "max_line_length": 116, "alphanum_fraction": 0.7388831437, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.758526835791341}}
{"text": "export gauss_legendre_weights;   # For debugging only\nexport distributed_kernel_trapezoidal;    # For debugging only\nexport distributed_kernel_gauss_legendre; # For debugging only\n\n\"\n#Creates the NEP associated with example in E. Jarlebring and\n#W. Michiels and K. Meerbergen, The infinite  {Arnoldi} method and an application to time-delay systems with distributed delays, Delay Systems - Methods, Applications and New Trends, 2012\n\"\nfunction gallery_dep_distributed()\n    # E. Jarlebring and W. Michiels and K. Meerbergen},\n    # The infinite  {Arnoldi} method and an application to time-delay systems with distributed delays,\n    # Delay Systems - Methods, Applications and New Trends\n    # 2012\n    #\n    # Some correct eigenvalues:\n    # -0.400236388049641 + 0.970633098237807i\n    # -0.400236388049641 - 0.970633098237807i\n    #  2.726146249832675 + 0.000000000000000i\n    # -1.955643591177653 + 3.364550574688863i\n    # -1.955643591177653 - 3.364550574688863i\n    #  4.493937056300693 + 0.000000000000000i\n    # -1.631513006819252 + 4.555484848248613i\n    # -1.631513006819252 - 4.555484848248613i\n    # -1.677320660400946 + 7.496870451838560i\n    # -1.677320660400946 - 7.496870451838560i\n    #\n    #\n\n\n\n    A0 = Matrix(-1.0I, 3, 3)\n    A1=[2.5    2.8   -0.5\n        1.8    0.3    0.3\n        -2.3   -1.4    3.5];\n    A2=[1.7    0.7   -0.3\n        -2.4   -2.1   -0.2\n        2.0    0.7    0.4];\n    A3=[1.4   -1.3    0.4\n        1.4    0.7    1.0\n        0.6    1.6    1.7];\n    idop= S -> S\n    oneop = S -> one(S)\n    f1 = S -> exp(-S)\n    N = 10\n    f2 = S -> distributed_kernel_gauss_legendre(S, N)\n    #N = 1000\n    #f2 = S -> distributed_kernel_trapezoidal(Matrix(S), N)\n    return SPMF_NEP([A0,A1,A2,A3],[idop,oneop,f1,f2])\nend\n\n\nfunction distributed_kernel_trapezoidal(S,N0)\n\n    fS = x -> exp(x*S) * (exp((x+0.5)^2) - exp(1/4))\n\n    F=zero(S)\n\n    h=1/N0;\n    for i=1:(N0+1) # Trapezoidal rule\n        x=float((i-1)*h-1)\n        if (i==1 || i==N0+1)\n            F += 0.5*fS(x)*h;\n        else\n            F += fS(x)*h;\n        end\n    end\n    return F\nend\n\"\"\"\nComputes distributed kernel matrix function using\nGauss-Legender quadrature.\n\"\"\"\nfunction distributed_kernel_gauss_legendre(S,N)\n    f=x-> (exp((x+0.5)^2)-exp(1/4))\n    F=zero(S);\n    xv,wv=gauss_legendre_weights(N,-1,0);\n    local E = one(S)\n\n    accumulative_expm_comp=true\n    for i=1:length(xv)\n        if (accumulative_expm_comp)\n            # An accumulative way to compute E=exp(xv[i]*S) which is\n            # faster due to the fact that scaling and squaring\n            # for exp((xv[i]-xv[i-1])*S) is faster than\n            # exp(xv[i]*S)\n            if (i==1)\n                E=exp(xv[1]*S);\n            else\n                E=E*exp((xv[i]-xv[i-1])*S)\n            end\n        else\n            E=exp(xv[i]*S);\n\n        end\n\n        fSw=E*(f(xv[i])*wv[i]);\n        F=F+fSw;\n    end\n    return F\nend\n\n\n\n\nfunction  gauss_legendre_weights(N,a,b)\n\n    N1=N; N2=N+1;\n    xu = range(-1, stop = 1, length = N1)\n\n    # L will be the Legendre-Gauss Vandermonde Matrix\n    L=zeros(N1,N2);\n\n\n\n    # \"Derivative\" of L\n    Lp=zeros(N1,N2);\n\n\n    # Starting values of Newton's method\n    y = cos.((2 * (0:(N-1)) .+ 1) * pi / (2 * (N-1) + 2)) + (0.27/N1) * sin.(pi * xu * (N-1) / N2)\n    y0 = 2\n\n\n    local Lp0\n    # Newton's method to decide points\n    # Iterate until new points are uniformly within epsilon of old points\n\n    while maximum(abs.(y .- y0)) > eps()\n\n\n\n        L[:,1]=ones(size(L,1));\n        Lp[:,1]=zeros(size(Lp,1));\n\n        L[:,2]=y;\n        Lp[:,2]=ones(size(Lp,1));\n\n        # Recurrence\n        for k=2:N1\n            L[:,k+1]=( (2*k-1)*(y).*L[:,k]-(k-1)*L[:,k-1] )/k;\n        end\n\n        Lp0 = N2 * (L[:,N1] - y .* L[:,N2]) ./ (1 .- y.^2)\n\n        y0=y;\n        y=y0-L[:,N2]./Lp0;\n    end\n\n    # Linear map from[-1,1] to [a,b]\n    x = (a * (1 .- y) + b * (1 .+ y)) / 2\n\n    # Compute the weights\n    w = (b-a) ./ ((1 .- y.^2) .* Lp0.^2) * (N2/N1)^2\n\n    return x,w\nend\n", "meta": {"hexsha": "cb39ac80ffe607bdf0b41a71bb63cb57f5a8a804", "size": 3967, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gallery_extra/distributed_example.jl", "max_stars_repo_name": "harrymd/NonlinearEigenproblems.jl", "max_stars_repo_head_hexsha": "ffb050eb040dc22cb9c3c00c38da117b45ca7937", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2018-06-07T09:54:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T06:57:07.000Z", "max_issues_repo_path": "src/gallery_extra/distributed_example.jl", "max_issues_repo_name": "harrymd/NonlinearEigenproblems.jl", "max_issues_repo_head_hexsha": "ffb050eb040dc22cb9c3c00c38da117b45ca7937", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 180, "max_issues_repo_issues_event_min_datetime": "2018-06-06T11:25:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T21:49:00.000Z", "max_forks_repo_path": "src/gallery_extra/distributed_example.jl", "max_forks_repo_name": "harrymd/NonlinearEigenproblems.jl", "max_forks_repo_head_hexsha": "ffb050eb040dc22cb9c3c00c38da117b45ca7937", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2018-06-05T15:30:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T08:39:25.000Z", "avg_line_length": 25.2675159236, "max_line_length": 187, "alphanum_fraction": 0.547769095, "num_tokens": 1483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7585268336052231}}
{"text": "# # Implementation of the quartic root finding method described in:\n# # A Geometric Interpretation of the Solution of the General Quartic Polynomial\n# # Author(s): William M. Faucette\n# # Source: The American Mathematical Monthly , Jan., 1996, Vol. 103, No. 1 (Jan., 1996), pp. 51-57\n# # Published by: The Mathematical Association of America\n# # Stable URL: https://www.jstor.org/stable/2975214\n\nconst S = [-1 1 1; -1 -1 -1; 1 1 -1; 1 -1 1] # permuting signs on the roots\n\n\"\"\"\nDefined by the taking the positive square root relationship\n    (-x)^(1/2) = xsign(x)*sqrt(abs(x))\n\"\"\"\nfunction xsign(x::R) where {R<:Real}\n\n    if sign(x) == 1.0\n        return im\n    elseif sign(x) == -1.0\n        return 1.0\n    else\n        error(\"Sign of input value not comparable to ±1.0\")\n        return nothing\n    end\n\nend\n\n\"\"\"\nReturn all the real roots of a quartic equation represented as a\nvector of real coefficients for terms of increasing degree.\nNote that any higher order coefficients (degree >= 5) are ignored.\n\nTheory described in Faucette (1996).\n\"\"\"\nfunction solve_all_quartic_roots(polycoeff::Vector{T}; \n    warn_scaling::Bool=true,\n    leading_tol::Float64=QUARTIC_ATOL,\n    coeff_tol::Float64=1.0/QUARTIC_ATOL) where {T<:Real}\n\n    Rts = Vector{Complex{Float64}}() # object to return with real roots inside.\n\n    if length(polycoeff) < 5\n        @error \"There are too few coefficients given.\"\n        return Rts\n    end\n\n    if warn_scaling && isapprox(polycoeff[5], zero(T), atol=leading_tol)\n        @warn \"The leading quartic coefficient is approximately zero. Returning empty array.\"\n        ## TODO?: fall back to solving a cubic instead?\n        return Rts\n    end\n\n    a = polycoeff[1:4]./polycoeff[5]\n\n    if warn_scaling && poor_conditioning(a, coeff_tol)\n        @warn \"Large coefficients in scaled polynomial. Poor conditioning may occur.\"\n    end\n\n    # We reduce p(z) = a1 + a2*z + a3*z^2 + a4*z^3 + z^4 via z == x - a4/4 to\n    # the standard transformed form P(x) = r + q*x + p*x^2 + x^4\n\n    p = -3*(a[4]^2)/8   + a[3]\n    q =    (a[4]^3)/8   - a[4]*a[3]/2 + a[2]\n    r = -3*(a[4]^4)/256 + (a[4]^2)*a[3]/16 - a[4]*a[2]/4 + a[1]\n\n    # The \"resolvent cubic of P(x)\" is h(z) = z^3 - 2p*z^2 + (p^2 - 4r)z + q^2.\n    # We find it's roots:\n    resolvent_coeff = [q^2, p^2 - 4r, -2p, 1]\n    resolvent_roots = solve_all_cubic_roots(resolvent_coeff; warn_scaling, leading_tol, coeff_tol)\n\n    alpha = convert(T,resolvent_roots[1])  # ensure first root is Real.\n    beta, gamma = resolvent_roots[2:3]\n    \n    if !isreal(beta) && !isreal(gamma) && sign(alpha) == -1.0\n        A = sqrt(-alpha)\n        B = sqrt(-beta)\n        C = sign(q)*sqrt(-gamma)\n    elseif isreal(beta) && isreal(gamma)\n        A = xsign(alpha)*sqrt(abs(alpha))\n        B = xsign(real(beta))*sqrt(abs(real(beta)))\n        C_sign = sign(q)/(xsign(alpha)*xsign(real(beta)))\n        C = C_sign*sqrt(abs(real(gamma)))\n    else\n        error(\"Unrecognised case.\")\n    end\n\n    R_res = S*([A; B; C])/2\n    # R_res = S*(sqrt.(-resolvent_roots))/2\n\n    # # A, B, C = sqrt.(-resolvent_roots)\n    # # x1 = (-A + B + C)/2\n    # # x2 = (-A - B - C)/2\n    # # x3 = ( A + B - C)/2\n    # # x4 = ( A - B + C)/2\n\n    append!(Rts, R_res .- a[4]/4)\n\n    return Rts\nend\n", "meta": {"hexsha": "64d9c48224dda3d373a6a679de915c7016a84e7a", "size": 3230, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/quartic.jl", "max_stars_repo_name": "jd-foster/HyperCubicRoots", "max_stars_repo_head_hexsha": "2094f30676e9b76a0cc621666868a546084cf17e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/quartic.jl", "max_issues_repo_name": "jd-foster/HyperCubicRoots", "max_issues_repo_head_hexsha": "2094f30676e9b76a0cc621666868a546084cf17e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/quartic.jl", "max_forks_repo_name": "jd-foster/HyperCubicRoots", "max_forks_repo_head_hexsha": "2094f30676e9b76a0cc621666868a546084cf17e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6262626263, "max_line_length": 99, "alphanum_fraction": 0.6055727554, "num_tokens": 1068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7585268325430311}}
{"text": "#=\nCopyright (c) 2015, Intel Corporation\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without \nmodification, are permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice, \n  this list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright notice, \n  this list of conditions and the following disclaimer in the documentation \n  and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE \nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF \nTHE POSSIBILITY OF SUCH DAMAGE.\n=#\n\nusing HPAT \nusing MPI\nusing DocOpt\n\n@acc hpat function kmeans(numCenter, iterNum, file_name)\n    points = DataSource(Matrix{Float64},HDF5,\"/points\", file_name)\n    D,N = size(points) # number of features, instances\n    centroids = rand(D, numCenter)\n\n    for l in 1:iterNum\n        dist::Array{Array{Float64,1},1} = [ Float64[sqrt(sum((points[:,i]-centroids[:,j]).^2)) for j in 1:numCenter] for i in 1:N]\n        labels::Array{Int,1} = [indmin(dist[i]) for i in 1:N]\n        centroids::Array{Float64,2} = [ sum(points[j,labels.==i])/sum(labels.==i) for j in 1:D, i in 1:numCenter]\n    end \n    return centroids\nend\n\nfunction main()\n    doc = \"\"\"K-means clustering algorithm.\n\nUsage:\n  kmeans.jl -h | --help\n  kmeans.jl [--iterations=<iterations>] [--file=<file>] [--centers=<centers>]\n\nOptions:\n  -h --help                  Show this screen.\n  --iterations=<iterations>  Specify number of iterations; defaults to 20.\n  --file=<file>              Specify input file; defaults to HPAT's default generated data file.\n  --centers=<centers>        Specify number of centers; defaults to 5.\n\n\"\"\"\n    arguments = docopt(doc)\n\n    if (arguments[\"--iterations\"] != nothing)\n        iterations = parse(Int, arguments[\"--iterations\"])\n    else\n        iterations = 20\n    end\n\n    if (arguments[\"--file\"] != nothing)\n        file_name::ASCIIString = arguments[\"--file\"]\n    else\n        file_name = HPAT.getDefaultDataPath()*\"kmeans_large.hdf5\"\n    end \n\n    if (arguments[\"--centers\"] != nothing)\n        numCenter = parse(Int, arguments[\"--centers\"])\n    else\n        numCenter = 5\n    end\n\n    srand(0)\n    rank = MPI.Comm_rank(MPI.COMM_WORLD)\n    pes = MPI.Comm_size(MPI.COMM_WORLD)\n\n    if rank==0 println(\"iterations = \", iterations) end\n    if rank==0 println(\"file= \", file_name) end\n    if rank==0 println(\"centers= \", numCenter) end\n\n    tic()\n    kmeans(numCenter, 2, file_name)\n    time = toq()\n    if rank==0 println(\"SELFPRIMED \", time) end\n    MPI.Barrier(MPI.COMM_WORLD)\n\n    tic()\n    centroids_out = kmeans(numCenter, iterations, file_name)\n    time = toq()\n    if rank==0 println(\"result = \", centroids_out) end\n    if rank==0 println(\"rate = \", iterations / time, \" iterations/sec\") end\n    if rank==0 println(\"SELFTIMED \", time) end\n\nend\n\nmain()\n", "meta": {"hexsha": "aa3329f61d180ad44bb1a524f20ed3adf679ebeb", "size": 3571, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/kmeans.jl", "max_stars_repo_name": "JuliaPackageMirrors/HPAT.jl", "max_stars_repo_head_hexsha": "bbdac66d8b93ac957cae5a86e20c8b7cf4012671", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/kmeans.jl", "max_issues_repo_name": "JuliaPackageMirrors/HPAT.jl", "max_issues_repo_head_hexsha": "bbdac66d8b93ac957cae5a86e20c8b7cf4012671", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/kmeans.jl", "max_forks_repo_name": "JuliaPackageMirrors/HPAT.jl", "max_forks_repo_head_hexsha": "bbdac66d8b93ac957cae5a86e20c8b7cf4012671", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3564356436, "max_line_length": 130, "alphanum_fraction": 0.6928031364, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7585268274215118}}
{"text": "# estimate the mean by numerical integration over uniform percentiles\nestimateMean(d::ContinuousUnivariateDistribution;kwargs...) = \n  meanFunOfProb(d;kwargs...,fun=(d,p)->quantile(d,p))\n\n# estimate variance by numerical integration over uniform percentiles\nfunction estimateVariance(d::ContinuousUnivariateDistribution; mean=missing, kwargs...)\n    m = ismissing(mean) ? Distributions.mean(d) : mean\n    function squaredDiff(d,p)\n        t = quantile(d, p) - m\n        t*t\n    end\n    meanFunOfProb(d;kwargs...,fun=squaredDiff)\nend\n\n\"\"\"\ncompute mean over a function(uniformly distributed probabilities)\n    \nused to estimate moments of logitnorm\n\"\"\"\nfunction meanFunOfProb(d::ContinuousUnivariateDistribution;relPrec = 1e-4, maxCnt=2^18, fun=(d,p)->quantile.(d,p) )\n    δ = 1/32 # start with 31 points (32 intervals between 0 and 1)\n    p = δ:δ:(1-δ)\n    # for K=1/δ intervals, there are (K-1) points at c_i\n    # The first points at δ represents interval (δ/2,3/2δ)\n    # The following picture shows points and intervals for K = 4\n    #---|---|---|---#\n    # |---|---|---| #\n    # we need to add points for δ/4 and 1-δ/4 representing the edges\n    # but their weight is only half, because they represents half an inverval\n    #m = sum(c_i*δ) + el*(δ/2) + er*(δ/2) = (sum(c_i) + er/2 + el/2)*δ\n    s = sum(fun.(d,p))   # sum at points c_i\n    el = fun(d,δ/4)  # \n    er = fun(d,1-δ/4)\n    m = (s + el/2 + er/2)*δ\n    relErr = 1\n    while 1/δ < maxCnt\n        mPrev = m\n        δ  = δ / 2\n        # to double the number of reference points, half the interval\n        # for each second point we already computed fun\n        # only need to add the new points to the sum of central points\n        p = δ:δ*2:(1-δ) # points at the center of current intervals\n        s += sum(fun.(d,p))\n        el = fun(d,δ/4)\n        er = fun(d,1-δ/4)\n        m = (s + el/2 + er/2)*δ\n        relErr = abs(m - mPrev)/m \n        #println(\"cnt=$(1/δ), m=$m, mPrev=$mPrev, relErr=$relErr\")\n        #if the estimate did not change much, can return\n        relErr <= relPrec && break\n    end\n    relErr > relPrec && @warn \"Returning meanFunOfProb results of low relative precision of $relErr\"\n    m\nend\n\n", "meta": {"hexsha": "51509a07c1765dcf2735172c95059121cdba7f0f", "size": 2178, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/estimateMoments.jl", "max_stars_repo_name": "bgctw/DistributionFits.jl", "max_stars_repo_head_hexsha": "c4b4b5fc063ea3f13a497568c00164acc03ba4bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-12-30T15:17:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T11:18:15.000Z", "max_issues_repo_path": "src/univariate/continuous/estimateMoments.jl", "max_issues_repo_name": "bgctw/DistributionFits.jl", "max_issues_repo_head_hexsha": "c4b4b5fc063ea3f13a497568c00164acc03ba4bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-02T15:23:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T16:18:10.000Z", "max_forks_repo_path": "src/univariate/continuous/estimateMoments.jl", "max_forks_repo_name": "bgctw/DistributionFits.jl", "max_forks_repo_head_hexsha": "c4b4b5fc063ea3f13a497568c00164acc03ba4bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8928571429, "max_line_length": 115, "alphanum_fraction": 0.6221303949, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7585268241732022}}
{"text": "#=\nTest function \n\nProperties \n----------\n\n- There are 9 steady states:\n    - Stable\n        - (-2.39,2.35)    (2.3,-2.34) (-2.18,-2.12)   (2.06,2.12) \n    - Unstable\n        - (-2.27,-0.23)   (2.17,0.22) (-0.12,-2.23)   (0.33,2.22) (0.1,0.01)\n\nReference \n---------\n1. Source code from https://static-content.springer.com/esm/art%3A10.1038%2Fs41598-017-15889-2/MediaObjects/41598_2017_15889_MOESM2_ESM.rar\n=#\n\nmodule SampleDE\n\n\"\"\"\nReference\n---------\n- `ODE.m`\n\"\"\"\nfunction ODE!(du,u,p,t)\n    du[1]= -1 + 9 *u[1] - 2*u[1]^3 + 9 *u[2] - 2*u[2]^3;\n    du[2]=  1 - 11*u[1] + 2*u[1]^3 + 11*u[2] - 2*u[2]^3;\nend\n\nfunction ODE(u,p,t)\n    du = deepcopy(u)\n    return ODE!(du,u,p,t)\nend\n\nu0 = [1.0, 2.0]\np = [2.0, 3.0]\n\n\n\n\"\"\"\nReference\n---------\n- `exact_potential.m`\n\"\"\"\nfunction exact_potential(points, RefPointNum)\n    pot = zeros(length(points), 1)\n    for i in 1:length(points)\n        x = points[i][1]; y = points[i][2];\n        pot[i] = -5*(x^2+y^2)+(x^4+y^4)/2+x*y+x;\n    end\n    pot = pot .- pot[RefPointNum]\n    return pot\nend\n\n\n\"\"\"\nReference\n---------\n- `Readme.pdf`\n\"\"\"\nODE_features = Dict(\n    \"StableStates\" => [ (-2.39,2.35),(2.3,-2.34), (-2.18,-2.12),   (2.06,2.12)  ],\n    \"UnstableStates\" => [(-2.27,-0.23) ,  (2.17,0.22), (-0.12,-2.23),   (0.33,2.22), (0.1,0.01)],\n    \"SteadyStates\" => [(-2.39,2.35),(2.3,-2.34), (-2.18,-2.12),   (2.06,2.12), (-2.27,-0.23) ,  (2.17,0.22), (-0.12,-2.23),   (0.33,2.22) ,(0.1,0.01)]\n)\n\n\n\nfunction gradient(dt,x) \n\n    x = reshape(x, 2, 3)\n\n    F=[ [(dt*(1/dt - 6*x[1, 1]^2 + 9)*(9*x[1, 1] + 9*x[2, 1] + (x[1, 1] - x[1, 2])/dt - 2*x[1, 1]^3 - 2*x[2, 1]^3 - 1))/2 + (dt*(6*x[1, 1]^2 - 11)*(11*x[2, 1] - 11*x[1, 1] + (x[2, 1] - x[2, 2])/dt + 2*x[1, 1]^3 - 2*x[2, 1]^3 + 1))/2,x[1, 1]^3 - (9*x[2, 1])/2 - (x[1, 1] - x[1, 2])/(2*dt) - (9*x[1, 1])/2 + x[2, 1]^3 + (dt*(1/dt - 6*x[1, 2]^2 + 9)*(9*x[1, 2] + 9*x[2, 2] + (x[1, 2] - x[1, 3])/dt - 2*x[1, 2]^3 - 2*x[2, 2]^3 - 1))/2 + (dt*(6*x[1, 2]^2 - 11)*(11*x[2, 2] - 11*x[1, 2] + (x[2, 2] - x[2, 3])/dt + 2*x[1, 2]^3 - 2*x[2, 2]^3 + 1))/2 + 1/2,x[1, 2]^3 - (9*x[2, 2])/2 - (x[1, 2] - x[1, 3])/(2*dt) - (9*x[1, 2])/2 + x[2, 2]^3 + 1/2 ],[\n    (dt*(1/dt - 6*x[2, 1]^2 + 11)*(11*x[2, 1] - 11*x[1, 1] + (x[2, 1] - x[2, 2])/dt + 2*x[1, 1]^3 - 2*x[2, 1]^3 + 1))/2 - (dt*(6*x[2, 1]^2 - 9)*(9*x[1, 1] + 9*x[2, 1] + (x[1, 1] - x[1, 2])/dt - 2*x[1, 1]^3 - 2*x[2, 1]^3 - 1))/2,(11*x[1, 1])/2 - (11*x[2, 1])/2 - (x[2, 1] - x[2, 2])/(2*dt) - x[1, 1]^3 + x[2, 1]^3 + (dt*(1/dt - 6*x[2, 2]^2 + 11)*(11*x[2, 2] - 11*x[1, 2] + (x[2, 2] - x[2, 3])/dt + 2*x[1, 2]^3 - 2*x[2, 2]^3 + 1))/2 - (dt*(6*x[2, 2]^2 - 9)*(9*x[1, 2] + 9*x[2, 2] + (x[1, 2] - x[1, 3])/dt - 2*x[1, 2]^3 - 2*x[2, 2]^3 - 1))/2 - 1/2,(11*x[1, 2])/2 - (11*x[2, 2])/2 - (x[2, 2] - x[2, 3])/(2*dt) - x[1, 2]^3 + x[2, 2]^3 - 1/2]]\n    return hcat(F...)'\nend\n\n\nend", "meta": {"hexsha": "e2aaef5c6d04c042ff24b16c194a6fc479106d28", "size": 2795, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/SampleDE.jl", "max_stars_repo_name": "stevengogogo/PotentialMap.jl", "max_stars_repo_head_hexsha": "bb8fe3df8bf20c9ee30e17dd61640a3546befd83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-20T06:05:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-20T06:05:07.000Z", "max_issues_repo_path": "test/SampleDE.jl", "max_issues_repo_name": "stevengogogo/PotentialMap.jl", "max_issues_repo_head_hexsha": "bb8fe3df8bf20c9ee30e17dd61640a3546befd83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-01-04T00:26:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T06:41:56.000Z", "max_forks_repo_path": "test/SampleDE.jl", "max_forks_repo_name": "stevengogogo/PotentialMap.jl", "max_forks_repo_head_hexsha": "bb8fe3df8bf20c9ee30e17dd61640a3546befd83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-02T03:43:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-02T03:43:40.000Z", "avg_line_length": 35.3797468354, "max_line_length": 640, "alphanum_fraction": 0.430411449, "num_tokens": 1597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7585268158033728}}
{"text": "using Plots\nusing ImplicitEquations\nusing ForwardDiff\n\na, b = 1 / √2, 1 / √2\nf(x, y) = x^2 + y^2 - 1\nf(xy) = f(xy[1], xy[2])\ng = xy -> ForwardDiff.gradient(f, xy)\n\n\"\"\"\nx' = x-a\ny' = y-b\n\"\"\"\nfunction shift(f::Function, a, b)\n    t = [\n        1 0 a;\n        0 1 b;\n        0 0 1\n    ]\n    function tf(xy)\n        x, y = xy\n        tx, ty, tz = t * [x, y, 1]\n        txy = [tx, ty]\n        return f(txy)\n    end\n    tf(x, y) = tf([x, y])\n    return tf\nend\n\n\"\"\"\nx'' = x'\ny'' = f_x(a,b)*x' + f_y(a,b)*y'\n\"\"\"\nfunction cvt(f, a, b)\n    fx, fy = g([a, b])\n    t = [\n        1 0 0;\n        -fx / fy 1 / fy 0;\n        0 0 1\n    ]\n    t = t / fy\n    function tf(xy)\n        x, y = xy\n        tx, ty, tz = t * [x, y, 1]\n        txy = [tx, ty]\n        return f(txy)\n    end\n    tf(x, y) = tf([x, y])\n    return tf\nend\n\nplot(aspect_ratio = :equal)\nplot!(Eq(f, 0))\nsf = shift(f, a, b)\nplot!(Eq(sf, 0))\nplot!(Eq(cvt(sf, a, b), 0))\n", "meta": {"hexsha": "3a149838cdbf74e3754f63cff77751fdc2d1a26f", "size": 916, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "drawImplicitFunctions/circle.jl", "max_stars_repo_name": "terasakisatoshi/juliaExer", "max_stars_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-02T01:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-04T12:03:25.000Z", "max_issues_repo_path": "drawImplicitFunctions/circle.jl", "max_issues_repo_name": "terasakisatoshi/juliaExer", "max_issues_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "drawImplicitFunctions/circle.jl", "max_forks_repo_name": "terasakisatoshi/juliaExer", "max_forks_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.0701754386, "max_line_length": 37, "alphanum_fraction": 0.4192139738, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731083722524, "lm_q2_score": 0.78793120560257, "lm_q1q2_score": 0.7585201828809224}}
{"text": "#=\nthis file includes functionality for estimating linear scaling regions and\ndefines the `generalized_dim` function.\n=#\n\nexport linear_region, linear_regions, estimate_boxsizes, linreg\n#####################################################################################\n# Functions and methods to deduce linear scaling regions\n#####################################################################################\nusing Statistics\nusing Statistics: covm, varm\n# The following function comes from a version in StatsBase that is now deleted\n# StatsBase is copyrighted under the MIT License with\n# Copyright (c) 2012-2016: Dahua Lin, Simon Byrne, Andreas Noack, Douglas Bates,\n# John Myles White, Simon Kornblith, and other contributors.\n\"\"\"\n    linreg(x, y) -> a, b\nPerform a linear regression to find the best coefficients so that the curve:\n`z = a + b*x` has the least squared error with `y`.\n\"\"\"\nfunction linreg(x::AbstractVector, y::AbstractVector)\n    # Least squares given\n    # Y = a + b*X\n    # where\n    # b = cov(X, Y)/var(X)\n    # a = mean(Y) - b*mean(X)\n    if size(x) != size(y)\n        throw(DimensionMismatch(\"x has size $(size(x)) and y has size $(size(y)), \" *\n            \"but these must be the same size\"))\n    end\n    mx = Statistics.mean(x)\n    my = Statistics.mean(y)\n    # don't need to worry about the scaling (n vs n - 1)\n    # since they cancel in the ratio\n    b = covm(x, mx, y, my)/varm(x, mx)\n    a = my - b*mx\n    return a, b\nend\n\nslope(x, y) = linreg(x, y)[2]\n\n\n\"\"\"\n    linear_regions(x, y; dxi::Int = 1, tol = 0.25) -> (lrs, tangents)\nIdentify regions where the curve `y(x)` is linear, by scanning the\n`x`-axis every `dxi` indices sequentially\n(e.g. at `x[1] to x[5], x[5] to x[10], x[10] to x[15]` and so on if `dxi=5`).\n\nIf the slope (calculated via linear regression) of a region of width `dxi` is\napproximatelly equal to that of the previous region,\nwithin tolerance `tol`,\nthen these two regions belong to the same linear region.\n\nReturn the indices of `x` that correspond to linear regions, `lrs`,\nand the _correct_ `tangents` at each region\n(obtained via a second linear regression at each accumulated region).\n\"\"\"\nfunction linear_regions(\n        x::AbstractVector, y::AbstractVector;\n        method = :sequential, dxi::Int = method == :overlap ? 3 : 1, tol = 0.25,\n    )\n    @assert length(x) == length(y)\n    return if method == :overlap\n        linear_regions_overlap(x, y, dxi, tol)\n    elseif method == :sequential\n        linear_regions_sequential(x, y, dxi, tol)\n    end\nend\n\nfunction linear_regions_sequential(x, y, dxi, tol)\n    maxit = length(x) ÷ dxi\n\n    tangents = Float64[slope(view(x, 1:max(dxi, 2)), view(y, 1:max(dxi, 2)))]\n\n    prevtang = tangents[1]\n    lrs = Int[1] #start of first linear region is always 1\n    lastk = 1\n\n    # Start loop over all partitions of `x` into `dxi` intervals:\n    for k in 1:maxit-1\n        tang = slope(view(x, k*dxi:(k+1)*dxi), view(y, k*dxi:(k+1)*dxi))\n        if isapprox(tang, prevtang, rtol=tol, atol = 0)\n            # Tanget is similar with initial previous one (based on tolerance)\n            continue\n        else\n            # Tangent is not similar.\n            # Push new tangent for a new linear region\n            push!(tangents, tang)\n\n            # Set the START of a new linear region\n            # which is also the END of the previous linear region\n            push!(lrs, k*dxi)\n            lastk = k\n        end\n\n        # Set new previous tangent (only if it was not the same as current)\n        prevtang = tang\n    end\n    push!(lrs, length(x))\n    # create new tangents that do have linear regression weighted\n    tangents = Float64[]\n    for i in 1:length(lrs)-1\n        push!(tangents, linreg(view(x, lrs[i]:lrs[i+1]), view(y ,lrs[i]:lrs[i+1]))[2])\n    end\n    return lrs, tangents\nend\n\n\"\"\"\n    linear_region(x, y; kwargs...) -> ((ind1, ind2), slope)\nCall [`linear_regions`](@ref) and identify and return the largest linear region\nand its slope. The region starts and stops at `x[ind1:ind2]`.\n\nThe keywords `dxi, tol` are propagated as-is to [`linear_regions`](@ref).\nThe keyword `ignore_saturation = true` ignores saturation that (sometimes) happens\nat the start and end of the curve `y(x)`, where the curve flattens.\nThe keyword `sat = 0.01` decides what saturation is (while `abs(y[i]-y[i+1])<sat` we \nare in a saturation regime).\n\nThe keyword `warning = true` prints a warning if the linear region is less than 1/3\nof the available x-axis.\n\"\"\"\nfunction linear_region(x::AbstractVector, y::AbstractVector;\n    dxi::Int = 1, tol::Real = 0.2, ignore_saturation = true, warning = true, sat = 0.01)\n\n    isat = 0\n    if ignore_saturation\n        j = findfirst(i -> abs(y[i] - y[i-1]) > sat, length(y):-1:2)\n        if !isnothing(j)\n            i = (length(y):-1:2)[j]\n            x, y = x[1:i], y[1:i]\n        end\n        k = findfirst(i -> abs(y[i+1] - y[i]) > sat, 1:length(y)-1)\n        if !isnothing(k)\n            x, y = x[k:end], y[k:end]\n            isat = k-1\n        end\n    end\n\n    lrs, tangents = linear_regions(x,y; dxi, tol)\n    # Find biggest linear region:\n    j = findmax(diff(lrs))[2]\n    if lrs[j+1] - lrs[j] ≤ length(x)÷3 && warning\n        @warn \"Found linear region spans less than a 3rd of the available x-axis \"*\n              \"and might imply inaccurate slope or insufficient data. \"*\n              \"Recommended: plot `x` vs `y`.\"\n    end\n    return (lrs[j] + isat, lrs[j+1] + isat), tangents[j]\nend\n\n#####################################################################################\n# Autotomatic estimation for proper `ε` from a Dataset\n#####################################################################################\n\"\"\"\n    estimate_boxsizes(A::Dataset; kwargs...) → εs\nReturn `k` exponentially spaced values: `εs = base .^ range(lower + w, upper + z; length = k)`,\nthat are a good estimate for sizes ε that are used in calculating a [Fractal Dimension](@ref).\nIt is strongly recommended to [`standardize`](@ref) input dataset `A` before using this\nfunction.\n\nLet `d₋` be the minimum pair-wise distance in `A` and `d₊` the average total length of `A`\nalong each of the dimensions of `A`.\nThen `lower = log(base, d₋)` and `upper = log(base, d₊)`.\nBecause by default `w=1, z=-1`, the returned sizes are an order of mangitude\nlarger than the minimum distance, and an order of magnitude smaller than the maximum\ndistance.\n\n## Keywords\n* `w = 1, z = -1, k = 20` : as explained above.\n* `base = MathConstants.e` : the base used in the `log` function.\n* `warning = true`: Print some warnings for bad estimates.\n* `autoexpand = true`: If the final estimated range does not cover at least 2 orders of\n  magnitude, it is automatically expanded by setting `w -= we` and `z -= ze`.\n  You can set different default values to the keywords `we = w, ze = z`.\n\"\"\"\nfunction estimate_boxsizes(\n        A::AbstractDataset;\n        k::Int = 20, z = -1, w = 1, base = MathConstants.e,\n        warning = true, autoexpand = true, ze = z, we = w\n    )\n\n    mi, ma = minmaxima(A)\n    max_d = mean(ma - mi)\n    min_d, _ = minimum_pairwise_distance(A)\n    if min_d == 0 && warning\n        @warn(\n        \"Minimum distance in the dataset is zero! Probably because of having data \"*\n        \"with low resolution, or duplicate data points. Setting to `d₊/base^4` for now.\")\n        min_d = max_d/(base^4)\n    end\n\n    lower = log(base, min_d)\n    upper = log(base, max_d)\n\n    if lower ≥ upper\n        error(\"`lower ≥ upper`. There must be something fundamentally wrong with dataset.\")\n    elseif lower+w ≥ upper+z && warning\n        @warn(\n        \"Automatic boxsize determination was inappropriate: `lower+w` was found ≥ than \"*\n        \"`upper+z`. Returning `base .^ range(lower, upper; length = k)`. \"*\n        \"Please adjust keywords or provide a bigger dataset.\")\n        εs = float(base) .^ range(lower, upper; length = k)\n    elseif abs(upper+z - (lower+w)) < 2 && autoexpand\n        if warning\n            @warn(\n            \"Boxsize limits do not differ by at least 2 orders of magnitude. \"*\n            \"Setting `w-=$(we)` and `z+=$(ze)`, please adjust keywords `w, z` otherwise.\")\n        end\n        εs = float(base) .^ range(lower+w-we, upper+z-ze; length = k)\n    else\n        εs = float(base) .^ range(lower+w, upper+z; length = k)\n    end\n    return εs\nend\n\n\"\"\"\n    minimum_pairwise_distance(A::Dataset, metric = Euclidean())\nReturn `min_d, min_pair`: the minimum pairwise distance\nof all points in the dataset, and the corresponding point pair.\n\"\"\"\nfunction minimum_pairwise_distance(A::AbstractDataset, metric = Euclidean())\n    tree = KDTree(A, metric)\n    min_d = eltype(A[1])(Inf)\n    max_d = -min_d\n    min_pair = max_pair = (0, 0)\n    theiler = Theiler(0)\n    for i in 1:length(A)\n        inds, dists = Neighborhood.knn(tree, A[i], 1, theiler(i); sortds=false)\n        ind, dist = inds[1], dists[1]\n        if dist < min_d\n            min_d = dist\n            min_pair = (i, ind)\n        end\n    end\n    return min_d, min_pair\nend\n", "meta": {"hexsha": "54ad13e50ac3bd722ff2a616acab7053c4ddc2db", "size": 8976, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dimensions/linear_regions.jl", "max_stars_repo_name": "onkyo14taro/ChaosTools.jl", "max_stars_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 168, "max_stars_repo_stars_event_min_datetime": "2018-01-07T15:46:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T13:38:24.000Z", "max_issues_repo_path": "src/dimensions/linear_regions.jl", "max_issues_repo_name": "onkyo14taro/ChaosTools.jl", "max_issues_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 176, "max_issues_repo_issues_event_min_datetime": "2017-12-19T20:26:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:08:23.000Z", "max_forks_repo_path": "src/dimensions/linear_regions.jl", "max_forks_repo_name": "onkyo14taro/ChaosTools.jl", "max_forks_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2018-01-27T07:59:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T10:08:36.000Z", "avg_line_length": 38.0338983051, "max_line_length": 95, "alphanum_fraction": 0.6082887701, "num_tokens": 2496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7584886680205891}}
{"text": "module MatrixChainMultiply\n\nexport matrixchainmultiply\n\n### mcm = matrix chain multiply\n\n\"\"\"\n  `matrixchainmultiply(A,B,C,D,...)`\n\nAlgorithm for **Matrix-chain multiplication** (where matrices are also\ngeneralizations of scalars and vectors). Using *Cormen* Ed. 3, p. 371.\n\nArguments\n---------\n`A,B,C,...` are matrices, vectors, or scalars of appropriate sizes.\n\n\"\"\"\nfunction matrixchainmultiply(A...)\n  p = mcm_makep(A...)\n  m, s, n = mcm_cost_matrices(p)\n  mcm_compute(s, 1, n, A...)\nend\n\"\"\"\n  `matrixchainmultiply(fn_name::String, A...)`\n\nPrint out the optimal matrix order as an expresion and its\ncost. Also use this to...\n\nConstruc a function for repeated use (Julia v0.6-?)\n---------------------------------------------------\nSometimes, you will do a chain multiplication many times with matrices of the same size. Another use case for this is to do the analysis on the CPU but use the generated function on the GPU. In either case, you only need to find the optimal order and JIT compile that function once. To save this function to the global scope:\n\n```julia\na = rand(Float32, 10000,2000)\nb = rand(Float32, 2000,100)\nc = rand(Float32, 100)\n\neval(matrixchainmultiply(\"mcm_abc\", a,b,c))\n\nmcm_abc(a,b,c)\n\n# multiple-dispatch is nice; taking advantage below\nusing ArrayFire\naa = AFArray(a)\nab = AFArray(b)\nac = AFArray(c)\n\nmcm_abc(aa,ab,ac)  # no new analysis; ke\n```\n\"\"\"\nfunction matrixchainmultiply(fn_name::String, A...)\n  matrixchainmultiply_fn(fn_name, A...)\nend\nfunction matrixchainmultiply_fn(fn_name::String, A...)\n  p = mcm_makep(A...)\n  m, s, n = mcm_cost_matrices(p)\n  ex = parse(fn_name * \"(A...) = \" * mcm_print(s, 1, n))\n  cost = m[1,n]\n  println(\"Operation: $ex\")\n  println(\"Cost: $cost\")\n  ex\nend\n\n\"Cost information tells which order to do.\"\nfunction mcm_cost_matrices(p::Vector{Int})\n  ∞ = typemax(Int)  # watch for overflow?\n  n = length(p) - 1  # number of matrices\n  @assert (n > 1) \"TODO: allow to use for short lists\"\n  # stores costs\n  m = zeros(Int, (n, n))\n  # records corresponding indices\n  s = zeros(Int, (n-1, n-1))  # Cormen has 2nd index going 2..n\n  # zero on diagonals\n  for i ∈ 1:n\n    m[i,i] = 0\n  end\n  # l is chain length\n  for l ∈ 2:n\n    for i ∈ 1:(n-l+1)\n      j = i + l - 1\n      m[i,j] = ∞  # this should be replaced?!\n      for k ∈ i:(j-1)\n        q1 = m[i,k]\n        q2 = m[k+1,j]\n        q3 = p[i] * p[k+1] * p[j+1]  # Cormen p vec indexed from 0\n        q = +(q1, q2, q3)\n        if q < m[i,j]\n          m[i,j] = q\n          s[i,j-1] = k\n        end\n      end\n    end\n  end\n  m, s, n\nend\n\n\"Use this if you want to see what the operation looks like.\"\nfunction mcm_print(s::Matrix, i::Int, j::Int)\n  str = \"\"\n  if i!=j\n    a = mcm_print(s, i, s[i, j-1])\n    b = mcm_print(s, s[i, j-1] + 1, j)\n    return \"($a * $b)\"\n  else\n    return \"A[$i]\"\n  end\nend\n\n\"\"\"\nThe function describing the optimal order for the input of a specific size.\n\"\"\"\nfunction mcm_optimalorder(s, i, j, mats...)\n  if i!=j\n    m1 = mcm_compute(s, i, s[i, j-1], mats...)\n    m2 = mcm_compute(s, s[i, j-1] + 1, j, mats...)\n    return :(m1 * m2)\n  else\n    return mats[i]\n  end\nend\n\n\"Do the actual matrix chain multiplication computation.\"\nfunction mcm_compute(s, i, j, mats...)\n  if i!=j\n    m1 = mcm_compute(s, i, s[i, j-1], mats...)\n    m2 = mcm_compute(s, s[i, j-1] + 1, j, mats...)\n    return (m1 * m2)\n  else\n    return mats[i]\n  end\nend\n\n\"The matrix sizes.\"\nfunction mcm_makep(mats...)\n  # Made some assumptions below that disallow these\n  lenmats = length(mats)\n  # convert to matrix-style sizes\n  msizes = map(msize, mats)\n  # produce unique number list\n  p = zeros(Int, lenmats + 1)\n  for i in 1:lenmats\n    firstiter::Bool = (i==1)\n    if firstiter\n      p[1] = msizes[1][1]\n    else\n      check1 = msizes[i-1][2]\n      check2 = msizes[i][1]\n      @assert (check1 == check2) \"Matrix sizes don't match ($check1 != $check2)!\"\n    end\n    p[i+1] = msizes[i][2]\n  end\n  p\nend\n\n###\n\n\"\"\"\nMatrix-style sizes. Return type looks like `(i,j)` where `i` and `j` are `Ints`.\n\nIf other packages with matrix types (e.g., OpenCl or ArrayFire) inherit from\nAbstractArray, there shouldn't be issues with other packages using this one.\n\"\"\"\nmsize(m::AbstractMatrix) = size(m)\nmsize(v::AbstractVector) = (size(v,1), 1)\nmsize(s::Number) = (1, 1)\n\n\nend # module\n", "meta": {"hexsha": "409d9e6c9a3f979e6525fc23219ec207dc853fa5", "size": 4265, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MatrixChainMultiply.jl", "max_stars_repo_name": "mcabbott/MatrixChainMultiply.jl", "max_stars_repo_head_hexsha": "a594b1ad239d2cb91fcb5b2b26a2d70144653ea0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MatrixChainMultiply.jl", "max_issues_repo_name": "mcabbott/MatrixChainMultiply.jl", "max_issues_repo_head_hexsha": "a594b1ad239d2cb91fcb5b2b26a2d70144653ea0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MatrixChainMultiply.jl", "max_forks_repo_name": "mcabbott/MatrixChainMultiply.jl", "max_forks_repo_head_hexsha": "a594b1ad239d2cb91fcb5b2b26a2d70144653ea0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2366863905, "max_line_length": 325, "alphanum_fraction": 0.61992966, "num_tokens": 1380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.758488652214568}}
{"text": "#### Beta diversity calculation functions\n\n## Function to calculate beta diversity statistics\n\"\"\"\n    betadiv(Y::Matrix)\n\nComputes the beta diversity statistics from the community matrix `Y` based on\nLegendre & De Cáceres (2013). This function was based on the `beta.div` R\nfunction from the supplementary material of that paper, and results were also\ntested against the `beta.div` function from `adespatial`.\n\"\"\"\nfunction betadiv(Y::Matrix)\n    @assert !any(isnothing, Y) \"Y must only contain observed sites and no nothing values\"\n    # S -> squared deviations from column mean\n    S = (Y .- mean(Y; dims=1)) .^ 2.0\n    # SStotal -> total sum of squares\n    SStotal = sum(S)\n    # BDtotal -> index of beta diversity, unbiased & comparable estimator of Var(Y)\n    BDtotal = SStotal / (size(Y, 1) - 1)\n    # SSj -> sum of squares for species j\n    SSj = sum(S; dims=1)\n    # SCBDj -> species contribution to beta diversity (species j, relative)\n    SCBDj = SSj ./ SStotal\n    # SSi -> sum of squares for site i\n    SSi = sum(S; dims=2)\n    # LCBD -> local contribution to beta diversity (site i, relative)\n    LCBDi = SSi ./ SStotal\n    # Combine results in tuple\n    res = (\n        S=S, SStotal=SStotal, BDtotal=BDtotal, SSj=SSj, SCBDj=SCBDj, SSi=SSi, LCBDi=LCBDi\n    )\n    return res\nend\n", "meta": {"hexsha": "b499b571fb6476103811b07f7d33ffa164d635e0", "size": 1290, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lib/betadiv.jl", "max_stars_repo_name": "gabrieldansereau/betadiversity-hotspots", "max_stars_repo_head_hexsha": "da20f43e73a89b495988b0e8e26644a5620b17b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-01T04:31:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-01T04:31:51.000Z", "max_issues_repo_path": "src/lib/betadiv.jl", "max_issues_repo_name": "gabrieldansereau/betadiversity-hotspots", "max_issues_repo_head_hexsha": "da20f43e73a89b495988b0e8e26644a5620b17b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-05-01T21:24:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T19:00:23.000Z", "max_forks_repo_path": "src/lib/betadiv.jl", "max_forks_repo_name": "gabrieldansereau/betadiversity-hotspots", "max_forks_repo_head_hexsha": "da20f43e73a89b495988b0e8e26644a5620b17b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-31T05:32:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-31T05:32:12.000Z", "avg_line_length": 37.9411764706, "max_line_length": 89, "alphanum_fraction": 0.6759689922, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.7584810153828906}}
{"text": "\nlogistic(x) = 1 ./ (1 + exp.(-x))\n@scalardiff logistic(x::Number) 1 (logistic(x) .* (1 .- logistic(x)))\n\n\nfunction autoencoder_cost(We1, We2, Wd, b1, b2, x)\n    firstLayer = logistic(We1 * x .+ b1)\n    encodedInput = logistic(We2 * firstLayer .+ b2)\n    reconstructedInput = logistic(Wd * encodedInput)\n    cost = sum((reconstructedInput .- x) .^ 2.0)\n    return cost\nend\n\n\nfunction mlp1(w1, w2, w3, x1)\n    xx2 = w1 * x1\n    x2 = log.(1. + exp.(xx2))\n    xx3 = w2 * x2\n    x3 = log.(1. + exp.(xx3))\n    x4 = w3 * x3\n    sum(1. ./ (1. + exp.(-x4)))\nend\n\n\nfunction mlp2(w1, w2, w3, b1, b2,  b3, x1)\n    x2 = logistic(w1 * x1 .+ b1)\n    x3 = logistic(w2 * x2 .+ b2)\n    x4 = logistic(w3 * x3 .+ b3)\n    sum(x4)\nend\n\n\n\nfunction rnn(Wxh, Whh, Wy, hprev, x, y)\n    h = tanh.(Whh * hprev + Wxh * x)\n    yhat = Why * h\n    cost = sum((yhat .- y) .^ 2.0)\n    return h, cost\nend\n\n", "meta": {"hexsha": "81f104d15ae0cfd4f7a348e06b72ec3dd595bd4a", "size": 872, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmarks/functions.jl", "max_stars_repo_name": "JuliaTagBot/XDiff.jl", "max_stars_repo_head_hexsha": "429b3263cc5201322531e2ec863541d9cf2f0d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-01-15T14:47:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T00:18:54.000Z", "max_issues_repo_path": "benchmarks/functions.jl", "max_issues_repo_name": "JuliaTagBot/XDiff.jl", "max_issues_repo_head_hexsha": "429b3263cc5201322531e2ec863541d9cf2f0d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2017-01-08T00:49:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:32:26.000Z", "max_forks_repo_path": "benchmarks/functions.jl", "max_forks_repo_name": "JuliaTagBot/XDiff.jl", "max_forks_repo_head_hexsha": "429b3263cc5201322531e2ec863541d9cf2f0d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-08-14T03:35:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:29:58.000Z", "avg_line_length": 21.2682926829, "max_line_length": 69, "alphanum_fraction": 0.5447247706, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739075, "lm_q2_score": 0.795658104908603, "lm_q1q2_score": 0.7584810128762334}}
{"text": "using SymPy\n\n\n\nfunction lagrange(order)\n\n  is=collect(-floor(Int,order/2) : 1 : floor(Int,order/2));\n  x=symbols(\"x\");\n  L=x^0;\n  Ls=Array(typeof(L),(order,));\n\n\n  for j = 1 : order\n    ith=is[j];\n    for i in is\n      if i!= ith\n        L=L*(x-i)/(ith-i);\n      end\n    end\n    Ls[j]=copy(L);\n    L=x^0;\n  end\n\n\n  return Ls;\n\nend\n\n\n\nfunction fd(order,d;t=Rational)\n  Ls=lagrange(order);\n  x =symbols(\"x\");\n\n  is=collect(-floor(Int,order/2) : 1 : floor(Int,order/2));\n  D=Array(typeof(x),(order,order));\n  for i = 1 : order\n    for j = 1 : order\n      D[i,j] =diff(Ls[j],x,d)(x=>is[i]);\n    end\n  end\n\n\n  return Array{t}(D);\n\nend\n\n\norder=4\nD=fd(order+1,2,t=Float64);\n", "meta": {"hexsha": "42da32a2af53d079beac8ac84457a2bd4ae7bd8b", "size": 667, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "fd.jl", "max_stars_repo_name": "ReidAtcheson/FiniteDifferenceCoeffs", "max_stars_repo_head_hexsha": "d14127d3fb31eb3d644da1068f3089a224362431", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fd.jl", "max_issues_repo_name": "ReidAtcheson/FiniteDifferenceCoeffs", "max_issues_repo_head_hexsha": "d14127d3fb31eb3d644da1068f3089a224362431", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fd.jl", "max_forks_repo_name": "ReidAtcheson/FiniteDifferenceCoeffs", "max_forks_repo_head_hexsha": "d14127d3fb31eb3d644da1068f3089a224362431", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.0784313725, "max_line_length": 59, "alphanum_fraction": 0.5412293853, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739075, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7584810082571879}}
{"text": "#############################################################################\n#############################################################################\n#\n# This file implements polynomial multiplication \n#                                                                               \n#############################################################################\n#############################################################################\n\n\"\"\"\nMultiply two polynomials.\n\"\"\"\n\nfunction *(p1::Polynomial, p2::Polynomial)::Polynomial\n    p_out = Polynomial()\n    for t in p1\n        p_out = p_out + (t * p2)\n    end\n    return p_out\nend\n\n\"\"\"\nMultiply two polynomials modulo P.\n\"\"\"\nfunction *(p1::PolynomialModP, p2::PolynomialModP)::Polynomial\n    @assert p1.prime == p2.prime \"Primes must be the same\"\n    p_out = Polynomial()\n    for t in p1.terms\n        p_out = p_out + (t * p2.terms)\n    end\n    return mod(p_out, p1.prime)\nend\n\n\n\"\"\"\nPower of a polynomial.\n\"\"\"\n\nfunction ^(p::Polynomial, n::Int)\n    n < 0 && error(\"No negative power\")\n    out = one(p)\n    binary_arr = digits(n, base=2)\n    for i in 1:length(binary_arr)\n        binary_arr[i] == 1 ? out = out*p : out *= 1\n        p = p*p\n    end\n    return out\nend\n\n# I decided to keep the ^ as a general function and not restrict it to only polynomials since this also works with raising integers and other types to a power n mod p.\nfunction ^(p, n::Int, prime::Int)\n    n < 0 && error(\"No negative power\")\n    out = one(p)\n    binary_arr = digits(n, base=2)\n    p = mod(p, prime)\n    for i in 1:length(binary_arr)\n        binary_arr[i] == 1 ? out = mod(out*p, prime) : out *= 1\n        p = mod(p*p, prime)\n    end\n    return mod(out, prime)\nend\n\n^(p::PolynomialModP, n::Int) = ^(p.terms, n, p.prime)\n\nfunction CRT(poly_arr, prime_arr)\n\n    c = 0\n    max_input_deg = max(degree(poly_arr[1]), degree(poly_arr[2]))+1\n    exponent_arr_1 = zeros(Int64, 1, max_input_deg)\n    exponent_arr_2 = zeros(Int64, 1, max_input_deg)\n    for i in poly_arr[1]\n        exponent_arr_1[i.degree+1] = i.coeff\n    end\n    for i in poly_arr[2]\n        exponent_arr_2[i.degree+1] = i.coeff\n    end\n    \"\"\"\n    The lines above actually result in a marginally slower CRT implementation as opposed to the approach where you cycle through exponent arrays 1 and 2 and check if k matches the exponent value before sending those values off to the iCRT call. I chose to keep this approach because the computational time difference was only marginal and I felt like it shows that I *really* tried to tackle the task given.\n    \"\"\"\n\n    for k in max_input_deg-1:-1:0\n        ak = exponent_arr_1[k+1]\n        bk = exponent_arr_2[k+1]\n        ck = iCRT([ak, bk], prime_arr)\n        k == 0 ? c = c + ck : c = c + ck * x^k # Can probably remove the turnery, its only there because I had a strange bug with Term(1,1)\n    end\n    return c\nend\n\nfunction mult_poly_with_crt(a, b)\n    height_a = maximum(coeffs(a))\n    height_b = maximum(coeffs(b))\n    B = 2*height_a*height_b*min(degree(a)+1, degree(b)+1)\n    M = 3\n    c = poly_modP_multiplication(a, b, M)\n    while M < B\n        nextprime(M) == M ? p = nextprime(M, 2) : p = nextprime(M)\n        d = poly_modP_multiplication(a, b, p)\n        c = CRT([c, d], [M, p])\n        M = M*p\n    end\n    return c\nend\n\nfunction iCRT(u, m)\n    v = Vector{Int}(undef, 2)\n    v[1] = u[1]\n    v[2] = mod((u[2] - v[1])*inverse_mod(m[1], m[2]), m[2])\n    output = u[1] + v[2]*m[1]\n    smod(output, m[1]) == smod(u[1], m[1]) && smod(output, m[2]) == smod(u[2], m[2]) && return smod(output, m[1]*m[2])\n    error(\"Output modulo prime is not consistent with inputs\")\nend\n\nfunction poly_modP_multiplication(a::Polynomial, b::Polynomial, prime::Int)\n    if length(a) == 0 || length(b) == 0\n        return 0\n    end\n    if leading(a) == a.terms[1] && leading(b) == b.terms[1]\n        return mod(mod(a, prime) * mod(b, prime), prime)\n    end\n\n    if length(a.terms) == 1\n        a1 = a\n        a2 = Polynomial()\n    else\n        a1 = Polynomial(a.terms[1:(length(a.terms)÷2)])\n        a2 = Polynomial(a.terms[(length(a.terms)÷2)+1:length(a.terms)])    \n    end\n    \n    if length(b.terms) == 1\n        b1 = b\n        b2 = Polynomial()\n    else\n        b1 = Polynomial(b.terms[1:(length(b.terms)÷2)])\n        b2 = Polynomial(b.terms[(length(b.terms)÷2)+1:length(b.terms)])    \n    end\n\n    return mod(poly_modP_multiplication(a1, b1, prime) + poly_modP_multiplication(a1, b2, prime) + poly_modP_multiplication(a2, b1, prime) + poly_modP_multiplication(a2, b2, prime), prime)\nend\n\nfunction mult_vec_el_up_to(arr::Vector, el::Int)\n    @assert length(arr) > 0 \"Array must contain at least 1 element.\" \n    el == 0 ? 1 : arr[el]*mult_vec_el_up_to(arr, el-1) \nend\n\nfunction i_ext_euclid_alg(a,b)\n    a == 0 && return b, 0, 1\n    g, s, t = i_ext_euclid_alg(b % a, a)\n    return g, t - (b ÷ a)*s, s\nend\n\nsmod(a::Int,m::Int)::Int = mod(a,m) > m ÷ 2 ?  mod(a,m) - m : mod(a,m) \n\ninverse_mod(a,m) = mod(i_ext_euclid_alg(a,m)[2],m);\n", "meta": {"hexsha": "cf5b655e966db69d646642faf83e80ecf177d4dd", "size": 4968, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basic_polynomial_operations/polynomial_multiplication.jl", "max_stars_repo_name": "ILikeTheCodespace/William-Idoine-2504-2021-PROJECT1", "max_stars_repo_head_hexsha": "2c1cf923b17dd97c91e80baab58890bfd33fc987", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basic_polynomial_operations/polynomial_multiplication.jl", "max_issues_repo_name": "ILikeTheCodespace/William-Idoine-2504-2021-PROJECT1", "max_issues_repo_head_hexsha": "2c1cf923b17dd97c91e80baab58890bfd33fc987", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basic_polynomial_operations/polynomial_multiplication.jl", "max_forks_repo_name": "ILikeTheCodespace/William-Idoine-2504-2021-PROJECT1", "max_forks_repo_head_hexsha": "2c1cf923b17dd97c91e80baab58890bfd33fc987", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-23T22:26:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T22:26:51.000Z", "avg_line_length": 32.2597402597, "max_line_length": 407, "alphanum_fraction": 0.5628019324, "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.758481003835277}}
{"text": "abstract type ActivationFunction end\n\n\"\"\"\n    ReLU <: ActivationFunction\n\n    (ReLU())(x) -> max.(x, 0)\n\"\"\"\nstruct ReLU <: ActivationFunction end\n\n\"\"\"\n    Max <: ActivationFunction\n\n    (Max())(x) -> max(maximum(x), 0)\n\"\"\"\nstruct Max <: ActivationFunction end\n\n\"\"\"\n    Id <: ActivationFunction\nIdentity operator\n\n    (Id())(x) -> x\n\"\"\"\nstruct Id <: ActivationFunction end\n\n\"\"\"\n    Sigmoid <: ActivationFunction\n\n    (Sigmoid())(x) -> 1 ./ (1 .+ exp.(-x))\n\"\"\"\nstruct Sigmoid <: ActivationFunction end\n\n\"\"\"\n    Tanh <: ActivationFunction\n\n    (Tanh())(x) -> tanh.(x)\n\"\"\"\nstruct Tanh <: ActivationFunction end\n\n\"\"\"\n    GeneralAct <: ActivationFunction\nWrapper type for a general activation function.\n\n### Usage\n```julia\nact = GeneralAct(tanh)\n\nact(0) == tanh(0)           # true\nact(10.0) == tanh(10.0)     # true\n```\n```julia\nact = GeneralAct(x->tanh.(x))\n\njulia> act(-2:2)\n5-element Array{Float64,1}:\n -0.9640275800758169\n -0.7615941559557649\n  0.0\n  0.7615941559557649\n  0.9640275800758169\n```\n\"\"\"\nstruct GeneralAct <: ActivationFunction\n    f::Function\nend\n\n#=\nTODO: consider writing our own interpolation scheme to avoid a dependency for this one thing.\nShould only require a handful of functions.\nAlso NOTE: inherently not type stable unless parameterized.\n=#\n\"\"\"\n    PiecewiseLinear <: ActivationFunction\nActivation function that uses linear interpolation between supplied `knots`.\nAn extrapolation condition can be set for values outside the set of knots. Default is `Linear`.\n\n    PiecewiseLinear(knots_x, knots_y, [extrapolation = Line()])\n\n### Usage\n```julia\nkx = [0.0, 1.2, 1.7, 3.1]\nky = [0.0, 0.5, 1.0, 1.5]\nact = PiecewiseLinear(kx, ky)\n\nact(first(kx)) == first(ky) == 0.0\nact(last(kx))  == last(ky)  == 1.5\n\nact(1.0)    # 0.4166666666666667\nact(-102)   # -42.5\n```\n```julia\nact = PiecewiseLinear(kx, ky, Flat())\n\nact(-102)   # 0.0\nact(Inf)    # 1.5\n```\n\n### Extrapolations\n- Flat()\n- Line()\n- constant (supply a number as the argument)\n- Throw() (throws bounds error)\n\n`PiecewiseLinear` uses [Interpolations.jl](http://juliamath.github.io/Interpolations.jl/latest/).\n\"\"\"\nstruct PiecewiseLinear <: ActivationFunction\n    f::Interpolations.Extrapolation\nend\n\n# default extrapolation is Line(). Can also do Flat() or supply a constant,\nfunction PiecewiseLinear(knots_x::AbstractVector,\n                         knots_y::AbstractVector,\n                         extrapolation = Interpolations.Line())\n    PiecewiseLinear(LinearInterpolation(knots_x, knots_y, extrapolation_bc = extrapolation))\nend\n\n# the type stable definitions probably don't need to go in the paper as-is\n(f::ReLU)(x) = max.(x, zero(eltype(x)))\n(f::Max)(x) = max(maximum(x), zero(eltype(x)))\n(f::Id)(x) = x\n(f::Sigmoid)(x) = @. 1 / (1 + exp(-x))\n(f::Tanh)(x) = tanh.(x)\n(G::GeneralAct)(x) = G.f(x)\n(PL::PiecewiseLinear)(x) = PL.f(x)\n", "meta": {"hexsha": "b97668fabd4fec59ad7e2697141b754cc6a6a4cc", "size": 2811, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/activation.jl", "max_stars_repo_name": "phK3/NeuralVerification.jl", "max_stars_repo_head_hexsha": "6c71231279c9474908f6db08a573c4b2b8cf2f01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 185, "max_stars_repo_stars_event_min_datetime": "2019-01-07T02:34:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T04:00:39.000Z", "max_issues_repo_path": "src/utils/activation.jl", "max_issues_repo_name": "phK3/NeuralVerification.jl", "max_issues_repo_head_hexsha": "6c71231279c9474908f6db08a573c4b2b8cf2f01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 141, "max_issues_repo_issues_event_min_datetime": "2019-01-06T21:59:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-15T00:32:57.000Z", "max_forks_repo_path": "src/utils/activation.jl", "max_forks_repo_name": "phK3/NeuralVerification.jl", "max_forks_repo_head_hexsha": "6c71231279c9474908f6db08a573c4b2b8cf2f01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 44, "max_forks_repo_forks_event_min_datetime": "2019-01-11T06:15:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T17:24:48.000Z", "avg_line_length": 22.6693548387, "max_line_length": 97, "alphanum_fraction": 0.6563500534, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7583649810775257}}
{"text": "\"\"\"\n    correction_hull(A::IntervalMatrix{T}, t, p) where {T}\n\nCompute the correction term for the convex hull of a point and its linear map\nwith an interval matrix in order to contain all trajectories of a linear system.\n\n### Input\n\n- `A` -- interval matrix\n- `t` -- non-negative time value\n- `p` -- order of the approximation\n\n### Output\n\nAn interval matrix representing the correction term.\n\n### Algorithm\n\nSee Theorem 3 in [1].\n\n[1] M. Althoff, O. Stursberg, M. Buss. Reachability Analysis of Linear Systems\nwith Uncertain Parameters and Inputs. CDC 2007.\n\"\"\"\nfunction correction_hull(A::IntervalMatrix{T}, t, p) where {T}\n    # initialize interval matrix with zero intervals\n    m, n = size(A)\n    F = IntervalMatrix(zeros(Interval{T}, m, n))\n\n    A2i = A\n    fac_i = 1\n    t2i = t\n    @inbounds for i in 2:p\n        t2i *= t\n        left = (one(T) / i^(i/i-1) - one(T) / i^(1/i-1)) * t2i\n        itv = Interval(left, zero(T))\n        A2i = A2i * A\n        fac_i *= i\n        F += itv * A2i * (1/fac_i)\n    end\n    F += _expm_remainder(A, t, p)\n    return F\nend\n", "meta": {"hexsha": "eee3dbfa71e1a787fa38d84cc234e3e54cde3d08", "size": 1067, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/correction_hull.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/IntervalMatrices.jl-5c1f47dc-42dd-5697-8aaa-4d102d140ba9", "max_stars_repo_head_hexsha": "945294c6f6f514c40e5d68df43499e668678a02b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/correction_hull.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/IntervalMatrices.jl-5c1f47dc-42dd-5697-8aaa-4d102d140ba9", "max_issues_repo_head_hexsha": "945294c6f6f514c40e5d68df43499e668678a02b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/correction_hull.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/IntervalMatrices.jl-5c1f47dc-42dd-5697-8aaa-4d102d140ba9", "max_forks_repo_head_hexsha": "945294c6f6f514c40e5d68df43499e668678a02b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8139534884, "max_line_length": 80, "alphanum_fraction": 0.6241799438, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7583649712532202}}
{"text": "# this file depends on jacobi.jl from JuliaOptics/OpticsPolynomials that\n# should be found in the same directory\n\nexport cheby1, cheby1_series, cheby1_sum, cheby2, cheby2_series, cheby2_sum\n\n\"\"\"\n    cheby1(n, x)\n\nCompute the Chebyshev polynomial of the first kind of order n at point x.\n\nThis family of Chebyshev polynomials are a special case of the Jacobi polynomials\nwith α, β = -1/2.\n\nSee also: [`cheby1_series`](@ref), [`cheby1_sum`](@ref)\n\"\"\"\nfunction cheby1(n, x)\n    return jacobi(n, -0.5, -0.5, x)\nend\n\n\"\"\"\n    cheby1_series(ns, α, β, x)\n\nCompute a series of Chebyshev polynomials of the first kind of orders n.\nReturns an array with shape (size(x)..., length(ns)).\nThat is, the _final_ dimension contains the modes and the first dimension(s)\nare spatial.\n\nSee also: [`cheby1`](@ref), [`cheby1_sum`](@ref)\n\"\"\"\nfunction cheby1_series(ns, x)\n    return jacobi_series(ns, -0.5, -0.5, x)\nend\n\"\"\"\n    cheby1_sum(ns, weights, x)\n\nCompute a sum of Chebyshev polynomial of the first kind of order n weighted by weights.\n\nSee also: [`cheby1`](@ref), [`cheby1_series`](@ref)\n\"\"\"\nfunction cheby1_sum(ns, weights, x)\n    return jacobi_sum(ns, weights, -0.5, -0.5, x)\nend\n\n\"\"\"\n    cheby2(n, x)\n\nCompute the Chebyshev polynomial of the second kind of order n at point x.\n\nThis family of Chebyshev polynomials are a special case of the Jacobi polynomials\nwith α, β = 1/2.\n\nSee also: [`cheby2_series`](@ref), [`cheby2_sum`](@ref)\n\"\"\"\nfunction cheby2(n, x)\n    return jacobi(n, 0.5, 0.5, x)\nend\n\n\"\"\"\n    cheby2_series(ns, α, β, x)\n\nCompute a series of Chebyshev polynomials of the second kind of orders n.\nReturns an array with shape (size(x)..., length(ns)).\nThat is, the _final_ dimension contains the modes and the first dimension(s)\nare spatial.\n\nSee also: [`cheby1`](@ref), [`cheby1_sum`](@ref)\n\"\"\"\nfunction cheby2_series(ns, x)\n    return jacobi_series(ns, 0.5, 0.5, x)\nend\n\"\"\"\n    cheby1_sum(ns, weights, x)\n\nCompute a sum of Chebyshev polynomial of the second kind of order n weighted by weights.\n\nSee also: [`cheby1`](@ref), [`cheby1_series`](@ref)\n\"\"\"\nfunction cheby2_sum(ns, weights, x)\n    return jacobi_sum(ns, weights, 0.5, 0.5, x)\nend\n", "meta": {"hexsha": "e96ceaa16be2a7f516685afe9853d0882ced3581", "size": 2142, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cheby.jl", "max_stars_repo_name": "JuliaOptics/OpticsPolynomials.jl", "max_stars_repo_head_hexsha": "bd7354474ddeea0d93338af06315d4511cc6c30a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-22T15:49:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T22:33:40.000Z", "max_issues_repo_path": "src/cheby.jl", "max_issues_repo_name": "JuliaOptics/OpticsPolynomials.jl", "max_issues_repo_head_hexsha": "bd7354474ddeea0d93338af06315d4511cc6c30a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cheby.jl", "max_forks_repo_name": "JuliaOptics/OpticsPolynomials.jl", "max_forks_repo_head_hexsha": "bd7354474ddeea0d93338af06315d4511cc6c30a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-12T14:40:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-12T14:40:26.000Z", "avg_line_length": 26.4444444444, "max_line_length": 88, "alphanum_fraction": 0.697945845, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7583649696284989}}
{"text": "module SDC\nexport SDC, make_SDC, make_spectral_int_matrix, gauss_lobatto_nodes\n\nusing FastGaussQuadrature: gausslobatto\nusing InvertedIndices: Not\nusing Polynomials: fromroots, integrate \n#import BenchmarkTools\n\n#\"\"\"\n#Solves the equation:\n#    w + alpha*fI(t,w) = b\n#For w given α, t, and b\n#Do I need a best guess for w, as well?\n#\"\"\"\n#function implicit_solve(α, t, b)\n#end\n\n\"\"\"\nGet n Gauss-Lobatto quadrature nodes, on interval [0-1].\n\"\"\"\nfunction gauss_lobatto_nodes(n::Int)\n    nodes, weights =  gausslobatto(n)\n    return 0.5*(nodes .+ 1.0)\nend\n\n\"\"\"\nGet the spectral integration matrix\n\"\"\"\nfunction make_spectral_int_matrix(n::Int)\n    nodes = gauss_lobatto_nodes(n) # Perhaps add option to change quadrature in the future\n    S = zeros(n,n)\n\n    for j = 1:n\n        Lt = fromroots(nodes[Not(j)])\n        Li = (1.0/Lt(nodes[j]))*Lt\n        for i = 1:n\n            S[i,j] = integrate(Li,0.0,nodes[i])\n        end\n    end\n    return S\nend\n\n\"\"\"\nNotes for improvement:\n\nThe main usage for this function will probably be something like:\nfor i in 1:number_of_timesteps\n    SDC(...)\n\nSo I don't want to waste resources recomputing S everytime, or setting up all\nthe equations.\n\nPerhaps I should have a create_SDC function? This would be provided all\nparameters except the initial guess, and create an SDC function which only\nneeds the initial values as arguments.\n\nFrom a UX perspective, I like that they will have an SDC function whose only\narguments are the initial data. That would be very easy to use. But I don't\nlike that they have to call a function to create a function. That seems like it\nmight be confusing.\n\nActually, I think it would be good to also have Δt as an argument to the\nuser-SDC function. I can imagine a user might want to use variable timestep\nsize (but they probably don't need to vary the number of collocation nodes,\nimplicit/explicit f, etc).\n\"\"\"\nfunction sdc(n, fE, fI, t, Δt, u, implicit_solver)\n    nodes = gauss_lobatto_nodes(n)\n    n_cor = 2*n-3\n    S = make_spectral_int_matrix(n) # nodes will be computed twice; should make more efficient\n    subtimes = (Δt*nodes).+ t \n    subvals = Vector{typeof(u)}(undef, n)\n\n    subvals[1] = u\n    # Prediction\n    for m in 1:n-1\n        subvals[m+1] = begin\n            u_m = subvals[m]\n            t_m = subtimes[m]\n            t_mp1 = subtimes[m+1]\n            Δt_m = t_mp1 - t_m\n            RHS = u_m + Δt_m*fE(t_m,u_m)\n            implicit_solver(-Δt_m, t_m, RHS)\n        end\n    end\n\n    f(t, u) = fE(t, u) + fI(t, u)\n    # Correction\n    for k in 1:n_cor\n        # B15 - Not needed for gauss lobatto nodes, just leaves subvals as they were\n        # But B15 will be needed if start point is not a node\n        f_subvals = [f(subtimes[i], subvals[i]) for i in 1:n]\n        u_m_k = subvals[1]\n        for m in 1:n-1\n            #B16\n            u_m_k_next = subvals[m+1] # Should figure out better notation for this\n            subvals[m+1] = begin\n                u_m_kp1 = subvals[m]\n                t_m = subtimes[m]\n                t_mp1 = subtimes[m+1]\n                Δt_m = t_mp1 - t_m\n                u_mp1_k = subvals[m+1]\n                ΔfE = fE(t_m, u_m_kp1) - fE(t_m, u_m_k)\n                RHS = subvals[m] + Δt_m*(ΔfE - f(t_mp1, u_mp1_k))\n                RHS += sum(q -> (S[m+1,q]-S[m,q])*f_subvals[q], 1:size(S)[2])\n                implicit_solver(-Δt_m, fI, RHS)\n            end\n            u_m_k = u_m_k_next\n        end\n    end\n    # Will be different if endpoint is a node, need to use B6\n    return subvals[end]\nend\n\n\n\"\"\"\nThis function returns a function: an SDC solver which needs only the initial\nconditions as the arguments. Moreover, the quadrature and spectral integration\nmatrix are built-in to the function, not calculated each run.\n\"\"\"\nfunction make_SDC(n, fE, fI, implicit_solver)\n    nodes = gauss_lobatto_nodes(n)\n    n_cor = 2*n-3\n    S = make_spectral_int_matrix(n) # nodes will be computed twice; should make more efficient\n\n    return function small_arg_list_SDC(u, t, Δt)\n        subtimes = (Δt*nodes).+ t \n        subvals = Vector{typeof(u)}(undef, n)\n        subvals[1] = u\n        # Prediction\n        for m in 1:n-1\n            subvals[m+1] = begin\n                u_m = subvals[m]\n                t_m = subtimes[m]\n                t_mp1 = subtimes[m+1]\n                Δt_m = t_mp1 - t_m\n                RHS = u_m + Δt_m*fE(t_m,u_m)\n                implicit_solver(-Δt_m, fI, RHS)\n            end\n        end\n\n        f(t, u) = fE(t, u) + fI(t, u)\n        # Correction\n        for k in 1:n_cor\n            # B15 - Not needed for gauss lobatto nodes, just leaves subvals as they were\n            # But B15 will be needed if start point is not a node\n            f_subvals = [f(subtimes[i], subvals[i]) for i in 1:n]\n            u_m_k = subvals[1]\n            for m in 1:n-1\n                #B16\n                u_m_k_next = subvals[m+1] # Should figure out better notation for this\n                subvals[m+1] = begin\n                    u_m_kp1 = subvals[m]\n                    t_m = subtimes[m]\n                    t_mp1 = subtimes[m+1]\n                    Δt_m = t_mp1 - t_m\n                    u_mp1_k = subvals[m+1]\n                    ΔfE = fE(t_m, u_m_kp1) - fE(t_m, u_m_k)\n                    RHS = subvals[m] + Δt_m*(ΔfE - f(t_mp1, u_mp1_k))\n                    RHS += sum(q -> (S[m+1,q]-S[m,q])*f_subvals[q], 1:size(S)[2])\n                    implicit_solver(-Δt_m, fI, RHS)\n                end\n                u_m_k = u_m_k_next\n            end\n        end\n        # Will be different if endpoint is a node, need to use B6\n        return subvals[end]\n    end\nend\n\n#function graph(u_np1_saves, T::Timing;\n#              graph_name::String=\"SDC_evolution.png\",\n#              display_plot::Bool=false)\n#\n#    # Get exact value for comparison purposes\n#    u_exact = u(T.t_n + T.Δt)\n#    # Compute errors\n#    u_np1_saves_errors = Vector{Tuple{Int64, Float64}}(undef, length(u_np1_saves))\n#    for (i, (j, u_np1)) in enumerate(u_np1_saves)\n#        #u_np1_saves_errors[i] = (j, abs(u_np1-u_exact))\n#        u_np1_saves_errors[i] = (j, u_np1 - u_exact)\n#    end\n#\n#    # Plotting\n#    plot = Plots.plot(\n#        getindex.(u_np1_saves_errors, 1), # No of Corrections\n#        getindex.(u_np1_saves_errors, 2), # Error\n#        label=\"Approximation of u(t_n+Δt)\"\n#    )\n#    p = length(T.Δtimes)+1\n#    Plots.plot!(\n#        plot,\n#        title=\"Error Over 1 Timestep Vs No of Corrections \\nλ=$λ, Δt=$(T.Δt), t_n=$(T.t_n), p=$p (Gauss-Lobatto)\",\n#        xlabel=\"# of Corrections (0 ⟹ Initial Prediction)\",\n#        ylabel=\"Error\",\n#        xlim=(0, 2*p),\n#        #yaxis=:log,\n#    )\n#    # Make a line on y=0, for easier comprehension\n#    Plots.hline!(plot, [0], label=\"\")\n#\n#    Plots.savefig(plot, graph_name)\n#\n#    if display_plot\n#        display(plot)\n#    end\n#    return nothing\n#end\n\n\n#\"\"\"\n#Make sure collocation nodes have proper scale and order.\n#\"\"\"\n#function validate_collocation_nodes(c_nodes)\n#    for node in c_nodes\n#        if node < 0 || node > 1\n#            throw(DomainError(node, \"Collocation nodes must be ∈ [0,1].\"))\n#        end\n#    end\n#    for i in 1:length(c_nodes)-1\n#        if c_nodes[i+1] <= c_nodes[i]\n#            throw(DomainError(node, \"Collocation nodes must be obey c_m+1 > c_m ∀ m = 1, ... , p.\"))\n#        end\n#    end\n#end\n\n\nend\n\n", "meta": {"hexsha": "2cf0c5fc26baf2232d4e6b3d478ecf1ae9f82a58", "size": 7301, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SDC.jl", "max_stars_repo_name": "leespen1/SDC.jl", "max_stars_repo_head_hexsha": "13885d9a01456c63f1551b3a8d2f7ec4173d5a42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SDC.jl", "max_issues_repo_name": "leespen1/SDC.jl", "max_issues_repo_head_hexsha": "13885d9a01456c63f1551b3a8d2f7ec4173d5a42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SDC.jl", "max_forks_repo_name": "leespen1/SDC.jl", "max_forks_repo_head_hexsha": "13885d9a01456c63f1551b3a8d2f7ec4173d5a42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7434782609, "max_line_length": 115, "alphanum_fraction": 0.5838926174, "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7583649695576365}}
{"text": "\"\"\"\n    omega_ratio(returns, target_return)\n\nThis function calculates the Omega ratio.\n\n# Formula\n\n    E[max(returns - target_return, 0)] / E[max(target_return - returns, 0)]\n\n# Arguments\n- `returns`:        Vector of asset returns.\n- `target_return`:  Vector or scalar value of benchmark returns having same same frequency (e.g. daily) as the provided returns.\n\"\"\"\nfunction omega_ratio(returns, target_return)\n    excess = returns .- target_return\n    sum1 = sum(map(x -> max(0.0, x), excess))\n    sum2 = -sum(map(x -> min(0.0, x), excess))\n    sum1 / sum2\nend\n", "meta": {"hexsha": "b997ef64a7699e30ce1dfaa23cfac0cc32bc7dda", "size": 562, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/omega_ratio.jl", "max_stars_repo_name": "rbeeli/RiskPerf.jl", "max_stars_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-07T19:19:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T19:19:09.000Z", "max_issues_repo_path": "src/omega_ratio.jl", "max_issues_repo_name": "rbeeli/RiskPerf.jl", "max_issues_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/omega_ratio.jl", "max_forks_repo_name": "rbeeli/RiskPerf.jl", "max_forks_repo_head_hexsha": "2569c1995b823f3e10443682a0f45077ffcff144", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1, "max_line_length": 128, "alphanum_fraction": 0.6779359431, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7583449272335138}}
{"text": "\"\"\"\n    dominate(p, q)\n\nReturns `1` if `p` is dominated by `q`, `-1` if otherwise, and `0` if dominance cannot be determined.\n\"\"\"\nfunction dominate(p::T, q::T) where {T <: AbstractArray}\n    ret = 0\n    for (i,j) in zip(p,q)\n        if i < j\n            ret == -1 && return 0\n            ret = 1\n        elseif j < i\n            ret == 1 && return 0\n            ret = -1\n        end\n    end\n    return ret\nend\n\n\"\"\"\ndominations(P::AbstractVector)\n\nReturns a domination matrix of all elements in the input collection `P`.\n\"\"\"\nfunction dominations(P::AbstractVector{T}) where {T <: AbstractArray}\n    l = length(P)\n    D = zeros(Int8, l, l)\n    for i in 1:l\n        for j in (i+1):l\n            D[i,j] = dominate(P[i],P[j])\n            D[j,i] = -D[i,j]\n        end\n    end\n    D\nend\n\n\"\"\"\n    nondominatedsort!(R, F)\n\nCalculate fronts for fitness values `F`, and store ranks of the individuals into `R`.\n\"\"\"\nfunction nondominatedsort!(R, P)\n    n = size(P,2)\n    @assert length(R) == n \"Ranks must be defined for the whole population\"\n\n    Sₚ = Dict(i=>Set() for i in 1:n)\n    C = zeros(Int, n)\n\n    # construct first front\n    F =[Int[]]\n    for i in 1:n\n        for j in i+1:n\n            r = dominate(view(P,:,i), view(P,:,j)) #M[i,j]\n            if r == 1\n                push!(Sₚ[i], j)\n                C[j] += 1\n            elseif r == -1\n                push!(Sₚ[j], i)\n                C[i] += 1\n            end\n        end\n        if C[i] == 0\n            R[i] = 1\n            push!(F[1], i)\n        end\n    end\n\n    # construct rest of the fronts\n    while !isempty(last(F))\n        Q = Int[]\n        for i in last(F)\n            for j in Sₚ[i]\n                C[j] -= 1\n                if C[j] == 0\n                    push!(Q, j)\n                    R[j] = length(F) + 1\n                end\n            end\n        end\n        push!(F, Q)\n    end\n    isempty(last(F)) && pop!(F)\n\n    F #, R #, Sₚ\nend\n\n\"\"\"\n    crowding_distance!((C, F, fronts)\n\nCalculate crowding distance for individuals and save the results into `C`\ngiven the fitness values `F` and collection of `fronts`.\n\"\"\"\nfunction crowding_distance!(C::AbstractVector, F::AbstractMatrix{T}, fronts) where {T}\n    for f in fronts\n        cf = @view C[f]\n        if length(cf) <= 2\n            cf .= typemax(T)\n        else\n            # sort front by each objective value\n            SF = F[:, f]\n            d = size(SF,1)\n            IX = zeros(Int, size(SF))\n            IIX = zeros(Int, size(SF))\n            for i in 1:d\n                irow, iirow, row = view(IX,i,:), view(IIX,i,:), view(SF,i,:)\n                sortperm!(irow, row)\n                sortperm!(iirow, irow)\n                permute!(row, irow)\n            end\n            nrm = SF[:,end] - SF[:,1]\n            dst = (hcat(SF, fill(typemax(T), d)) - hcat(fill(typemin(T), d), SF)) ./ nrm\n            dst[isnan.(dst)] .= zero(T)\n            ss = sum(mapslices(v->diag(dst[:,v]) + diag(dst[:,v.+1]), IIX, dims=1), dims=1)\n            cf .= vec(ss)/d\n        end\n    end\n    C\nend\n\n", "meta": {"hexsha": "d0f9059c6923a3d310bc90b5b50896bd29bd3652", "size": 3013, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/api/moea.jl", "max_stars_repo_name": "miguelbiron/Evolutionary.jl", "max_stars_repo_head_hexsha": "ee42fee04c62d88d2a76ce7ecf4224a1c5d759ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/api/moea.jl", "max_issues_repo_name": "miguelbiron/Evolutionary.jl", "max_issues_repo_head_hexsha": "ee42fee04c62d88d2a76ce7ecf4224a1c5d759ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/api/moea.jl", "max_forks_repo_name": "miguelbiron/Evolutionary.jl", "max_forks_repo_head_hexsha": "ee42fee04c62d88d2a76ce7ecf4224a1c5d759ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1083333333, "max_line_length": 101, "alphanum_fraction": 0.462993694, "num_tokens": 893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7583449217157235}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction _mag2flux{T<:AbstractFloat}(mag::T, zero_point::T, ABwave::T)\n    if isnan(ABwave)\n        return exp10(-0.4*(mag + zero_point))\n    else\n        return exp10(-0.4*(mag + 2.406 + 5*log10(float(ABwave))))\n    end\nend\n\n\"\"\"\n    mag2flux(mag[, zero_point, ABwave=number]) -> flux\n\n### Purpose ###\n\nConvert from magnitudes to flux expressed in erg/(s cm² Å).\n\n### Explanation ###\n\nThis is the reverse of `flux2mag`.\n\n### Arguments ###\n\n* `mag`: the magnitude to be converted in flux.  It can be either a scalar or an\n  array.\n* `zero_point`: scalar giving the zero point level of the magnitude.  If not\n supplied then defaults to 21.1 (Code et al 1976).  Ignored if the `ABwave`\n keyword is supplied\n* `ABwave` (optional numeric keyword): wavelength, scalar or array, in\n Angstroms.  If supplied, then the input `mag` is assumed to contain Oke AB\n magnitudes (Oke & Gunn 1983, ApJ, 266, 713;\n http://adsabs.harvard.edu/abs/1983ApJ...266..713O).\n\n### Output ###\n\nThe flux.  It is of the same type, scalar or array, as `mag`.\n\nIf the `ABwave` keyword is set, then the flux is given by the expression\n\n\\$\\$\\\\text{flux} = 10^{-0.4(\\\\text{mag} +2.406 + 4\\\\log_{10}(\\\\text{ABwave}))}\\$\\$\n\nOtherwise the flux is given by\n\n\\$\\$\\\\text{flux} =  10^{-0.4(\\\\text{mag} + \\\\text{zero point})}\\$\\$\n\n### Example ###\n\n``` julia\nmag2flux(8.3)\n# => 1.7378008287493692e-12\nmag2flux(8.3, 12)\n# => 7.58577575029182e-9\nmag2flux(8.3, ABwave=12)\n# => 3.6244115683017193e-7\n```\n\n### Notes ###\n\nCode of this function is based on IDL Astronomy User's Library.\n\"\"\"\nmag2flux(mag::Real, zero_point::Real=21.1; ABwave::Real=NaN) =\n    _mag2flux(promote(float(mag), float(zero_point), float(ABwave))...,)\n\nfunction mag2flux{N<:Real}(mag::AbstractArray{N}, zero_point::Real=21.1;\n                           ABwave::Real=NaN)\n    flux = similar(mag, typeof(float(one(N))))\n    for i in eachindex(mag)\n        flux[i] = mag2flux(mag[i], zero_point, ABwave=ABwave)\n    end\n    return flux\nend\n", "meta": {"hexsha": "7ba0a030f61a9ae8c12ea50b8d1f580f86263e86", "size": 2059, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mag2flux.jl", "max_stars_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_stars_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mag2flux.jl", "max_issues_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_issues_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mag2flux.jl", "max_forks_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_forks_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2054794521, "max_line_length": 82, "alphanum_fraction": 0.6532297232, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7583449178885322}}
{"text": "\n\"\"\"\n    density1d(x::AbstractVector, grid::AbstractVector; normalize::Bool=True)\nCompute number density on a line. Normalized such that int n dx =1.\n\"\"\"\nfunction density1d(x::AbstractVector, grid::AbstractVector; normalize::Bool=true)\n    bins = length(grid) -1\n    # initialize array to store number\n    n = zeros(bins)\n    # in a cell [a,b], particles that has a<=x<b is counted.\n    # for the last cell, x==b is also counted.\n    for i in 1:bins\n        for position in x\n            if grid[i] <=position <grid[i+1]\n                n[i] += 1\n            end\n        end\n    end\n    # last cell: add particles on the right boundary\n    n[end] += sum(x .== grid[end])\n    # use bin centers as representative locations.\n    dx = diff(grid)\n    bin_centers = grid[1:end-1] + dx/2\n    if normalize\n        n ./= dx *length(x)\n    end\n    return bin_centers, n\nend\n\n\n\"\"\"\n    density1d(x::AbstractVector, xmin::Real, xmax::Real; bins::Int=100)\nCompute number density on a line. Normalized such that int n dx =1.\n\"\"\"\nfunction density1d(x::AbstractVector, xmin::Real, xmax::Real; bins::Int=100, normalize::Bool=true)\n    xmin < xmax ||throw(ArgumentError(\"xmin>=xmax\"))\n    grid = LinRange(xmin, xmax, bins+1)\n    return density1d(x, grid, normalize=normalize)\nend\n\n\n\"\"\"\n    density1d(x::AbstractVector; bins::Int=100, normalize::Bool=true)\nCompute number density on a line.\n\"\"\"\nfunction density1d(x::AbstractVector; bins::Int=100, normalize::Bool=true)\n    xmin = minimum(x)\n    xmax = maximum(x)\n    return density1d(x, xmin, xmax, bins=bins, normalize=normalize)\nend\n", "meta": {"hexsha": "8538e9dee2516e64e122462c11cf39d013aa108c", "size": 1566, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/density.jl", "max_stars_repo_name": "zpeng2/Pda.jl", "max_stars_repo_head_hexsha": "a33acdca7d98e2e00221cb1502755baabf1f92e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/density.jl", "max_issues_repo_name": "zpeng2/Pda.jl", "max_issues_repo_head_hexsha": "a33acdca7d98e2e00221cb1502755baabf1f92e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/density.jl", "max_forks_repo_name": "zpeng2/Pda.jl", "max_forks_repo_head_hexsha": "a33acdca7d98e2e00221cb1502755baabf1f92e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7058823529, "max_line_length": 98, "alphanum_fraction": 0.6481481481, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.758300699859854}}
{"text": "# # How similar do two strings look?\n\n# ## VisualStringDistances.jl\n\n# <img src=\"assets/julia_visual.gif\" style=\"width: 65%\" class=\"center\" />\n\n# ---\n\n# ## Let's compare strings\n\n# <br />\n\nusing StringDistances\n\n# How many single-character edits are needed to turn \"Julia\" into \"JuIia\"?\n\nStringDistances.Levenshtein()(\"Julia\", \"JuIia\")\n\n# What about \"Julia\" into \"JuQia\"?\n\nStringDistances.Levenshtein()(\"Julia\", \"JuQia\")\n\n\n# We can also compare based on how many times consecutive pairs of letters appear in each string...\n\nStringDistances.QGram(2)(\"Julia\", \"JuIia\"), StringDistances.QGram(2)(\"Julia\", \"JuQia\")\n\n# ---\n# ## Visual distances\n\n# <br />\n\n\n# But none of these take into account that \"Julia\" and \"JuIia\" look pretty similar, while \"Julia\" and \"JuQia\" look pretty different.\n\nusing VisualStringDistances: VisualStringDistances\nconst VSD = VisualStringDistances\nVSD.visual_distance(\"Julia\",  \"JuIia\"), VSD.visual_distance(\"Julia\", \"JuQia\")\n\n# <br />\n\n# That seems better! But how do we know it does something reasonable in other cases too? And how does it work?\n\n# <br />\n\n# Just need two tools:\n# 1. <p> A way to translate strings into images </p>\n# 2. <p> A way to compare images </p>\n\n# ---\n\n# ## 1. A way to translate strings into images: GNU Unifont\n\nVSD.printglyph(\"GNU Unifont\"; symbols=(\"#\", \"-\"))\n\n# A bitmap font!\n\n# ---\n\n# Unifont stores characters as bitmaps, making things quite easy for us:\n\nVSD.Glyph(\"Julia\")\n\n# <br />\n\n# (see also FreeTypeAbstraction.jl to render bitmaps from many fonts!)\n\n# ---\n\n# It is low resolution, but simple and comprehensive, with 57086 supported characters, including...\n\nchars = [VSD.get_char(k) for k in rand(collect(keys(VSD.UNIFONT_LOOKUP)), 5)];\npermutedims(chars)\n\n# Which render as:\n\nVSD.printglyph(join(chars, \" \"))\n\n# ---\n\nVSD.printglyph(\"Julia vs JuIia\"); VSD.printglyph(\"Julia vs JuQia\") # hide\n\n# ---\n\n# ## 2. A way to compare images: Optimal transport\n\n# <br />\n\n# * <p> you have $a(x_1)$ amount of stuff at site $x_1$, $a(x_2)$ amount of stuff at $x_2$, ..., $a(x_n)$ stuff at $x_n$. </p>\n# * <p> you want to move it around until you have $b(y_1)$ stuff at site $y_1$, $b(y_2)$ stuff at $y_2$, ..., $b(y_m)$ stuff at $y_m$ </p>\n# * <p> it costs $c(x_i, y_j)$ to move one unit of mass from $x_i$ to $y_j$ </p>\n\n# ```math\n# \\begin{aligned}\n# \\operatorname{OT}(a,b) := \\text{minimize} \\quad & \\sum\\_{x,y} π(x,y)\\, c(x,y)\\\\\\\\\n# \\text{such that} \\quad & a(x) = \\sum\\_{y} \\pi(x,y)\\\\\\\\\n# & b(y) = \\sum\\_{x} \\pi(x,y) \\\\\\\\\n# & \\pi(x,y) \\geq 0 \n# \\end{aligned}\n# ```\n\n# * <p> We optimize to find the variables $\\pi(x,y)$ (how much stuff to move from $x$ to $y$) </p>\n\n# ---\n\n# ## How does optimal transport relate to our problem?\n\n# <br />\n\n# - <p> If we have a black pixel in the 3rd column and 2nd row of the bitmap, we can see that as $a(1) = 1$ unit of mass at site $x_1 = (2,3)$. </p>\n# - <p> In this way, we can translate the bitmap representation of the string into the language of optimal transport. </p>\n# - <p> $c(x,y)$ is just the distance between those points </p>\n# - <p> Note: we do two modifications to this </p>\n#   - <p> we solve an approximate version for speed (\"entropic regularization\") </p>\n#   - <p> add penalties for creating/destroying stuff for the case $\\sum_x a(x) \\neq  \\sum_y b(y)$   &nbsp; [1]. </p>\n\n# <br />\n# <br />\n# <br />\n\n# [1]: Séjourné, T., Feydy, J., Vialard, F.-X., Trouvé, A., Peyré, G., 2019. *Sinkhorn Divergences for Unbalanced Optimal Transport*. https://arxiv.org/abs/1910.12958.\n\n\n# ---\n\n# ## What use does this have?\n\n# Making gifs!\n\n\n# ---\n\n# ## What use does this have?\n\n\n# Adding a check for new packages being added to the General registry to try to prevent the malicious impersonation another package.\n\n# Two main concerns:\n\n# 1. Possibly, one will make a typo, and end up at the wrong package (\"typosquatting\") $\\leadsto$ edit distance check\n# 2. Possibly, one will copy a malicious tutorial that has mimicked the appearance of the name of a popular package $\\leadsto$ visual distance\n\n# <img src=\"assets/FIux.gif\" style=\"width: 45%\" class=\"center\" />\n\n\n# ---\n\n# ## Is this the right visual distance for an automated registry check?\n\n# I'm not sure.\n\n# * <p> Human perception is actually a bit different </p>\n#   * e.g. we mix up \"p\" vs \"q\" more than \"a\" vs \"e\"  [2], but `visual_distance` says \"p\" and \"q\" are further apart than \"a\" and \"e\"\n# * <p> optimal transport is a bit slow (though not prohibitively so, with entropic regularization and the low resolution font) </p>\n# * <p> there are several parameters and cutoffs to tune </p>\n#\n#\n# Possibly a perceptually-weighted edit distance is more sensible.\n\n# <br />\n# <br />\n\n# [2]: Courrieu, Pierre, Fernand Farioli, and Jonathan Grainger. *Inverse Discrimination Time as a Perceptual Distance for Alphabetic Characters*. Visual Cognition 11, no. 7 (October 2004): 901–19. https://doi.org/10.1080/13506280444000049.\n\n# ---\n\n# ## References & Notes\n\n# * Package for `visual_distance`, `printglyph`, etc: VisualStringDistances.jl\n# * <p> Package with the underlying algorithm optimal transport algorithm: UnbalancedOptimalTransport.jl </p>\n\n# <br />\n# <br />\n\n# References:\n# <br />\n\n# [1]: Séjourné, T., Feydy, J., Vialard, F.-X., Trouvé, A., Peyré, G., 2019. *Sinkhorn Divergences for Unbalanced Optimal Transport*. https://arxiv.org/abs/1910.12958.\n#\n# [2]: Courrieu, Pierre, Fernand Farioli, and Jonathan Grainger. *Inverse Discrimination Time as a Perceptual Distance for Alphabetic Characters*. Visual Cognition 11, no. 7 (October 2004): 901–19. https://doi.org/10.1080/13506280444000049.\n\n# <br />\n\n# Slides made with the help of Remark.jl, Literate.jl, and Documenter.jl; gifs made with Makie.jl.\n\n# Thanks to Stefan Karpinski for suggesting GNU Unifont.\n", "meta": {"hexsha": "27feb0b9d27032a577b37712c21391d32bfdd8b6", "size": 5727, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/slides/src/index.jl", "max_stars_repo_name": "strickek/VisualStringDistances.jl", "max_stars_repo_head_hexsha": "637205ce9c721263da8464ce4d6b3bdaee9c8dd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-10-23T09:30:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T04:04:56.000Z", "max_issues_repo_path": "scripts/slides/src/index.jl", "max_issues_repo_name": "strickek/VisualStringDistances.jl", "max_issues_repo_head_hexsha": "637205ce9c721263da8464ce4d6b3bdaee9c8dd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-07-29T14:07:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T22:37:59.000Z", "max_forks_repo_path": "scripts/slides/src/index.jl", "max_forks_repo_name": "strickek/VisualStringDistances.jl", "max_forks_repo_head_hexsha": "637205ce9c721263da8464ce4d6b3bdaee9c8dd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-08-27T15:25:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-22T21:05:12.000Z", "avg_line_length": 30.6256684492, "max_line_length": 240, "alphanum_fraction": 0.6720796228, "num_tokens": 1781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541611, "lm_q2_score": 0.8840392771633079, "lm_q1q2_score": 0.7583006922948756}}
{"text": "# # Intro to AbstractGPs: one-dimensional regression\n#\n# ## Setup\n#\n# Loading the necessary packages.\n\nusing AbstractGPs\nusing Distributions\nusing StatsFuns\n\nusing Plots\ndefault(; legend=:outertopright, size=(700, 400))\n\nusing Random\nRandom.seed!(42)  # setting the seed for reproducibility of this notebook\n#md nothing #hide\n\n# Load toy regression\n# [dataset](https://github.com/GPflow/GPflow/blob/7705cee6723f78066981f27954130daaede55dfc/doc/sphinx/notebooks/basics/data/regression_1D.csv)\n# taken from GPflow examples.\n\nx = [\n    0.8658165855998895,\n    0.6661700880180962,\n    0.8049218148148531,\n    0.7714303440386239,\n    0.14790478354654835,\n    0.8666105548197428,\n    0.007044577166530286,\n    0.026331737288148638,\n    0.17188596617099916,\n    0.8897812990554013,\n    0.24323574561119998,\n    0.028590102134105955,\n]\ny = [\n    1.5255314337144372,\n    3.6434202968230003,\n    3.010885733911661,\n    3.774442382979625,\n    3.3687639483798324,\n    1.5506452040608503,\n    3.790447985799683,\n    3.8689707574953,\n    3.4933565751758713,\n    1.4284538820635841,\n    3.8715350915692364,\n    3.7045949061144983,\n]\nscatter(x, y; xlabel=\"x\", ylabel=\"y\", legend=false)\n\n# We split the observations into train and test data.\n\nx_train = x[1:8]\ny_train = y[1:8]\nx_test = x[9:end]\ny_test = y[9:end]\n#md nothing #hide\n\n# We instantiate a Gaussian process with a Matern kernel. The kernel has\n# fixed variance and length scale parameters of default value 1.\n\nf = GP(Matern52Kernel())\n#md nothing #hide\n\n# We create a finite dimensional projection at the inputs of the training dataset\n# observed under Gaussian noise with variance $\\sigma^2 = 0.1$, and compute the\n# log-likelihood of the outputs of the training dataset.\n\nfx = f(x_train, 0.1)\nlogpdf(fx, y_train)\n\n# We compute the posterior Gaussian process given the training data, and calculate the\n# log-likelihood of the test dataset.\n\np_fx = posterior(fx, y_train)\nlogpdf(p_fx(x_test), y_test)\n\n# We plot the posterior Gaussian process (its mean and a ribbon of 2 standard deviations\n# around it) on a grid along with the observations.\n\nscatter(\n    x_train,\n    y_train;\n    xlim=(0, 1),\n    xlabel=\"x\",\n    ylabel=\"y\",\n    title=\"posterior (default parameters)\",\n    label=\"Train Data\",\n)\nscatter!(x_test, y_test; label=\"Test Data\")\nplot!(0:0.001:1, p_fx; label=false, ribbon_scale=2)\n\n# ## Markov Chain Monte Carlo\n#\n# Previously we computed the log likelihood of the untuned kernel parameters of the GP.\n# We now also perform approximate inference over said kernel parameters using different\n# Markov chain Monte Carlo (MCMC) methods. I.e., we approximate the posterior distribution\n# of the kernel parameters with samples from a Markov chain.\n#\n# We define a function which returns the log-likelihood of the data for different variance\n# and inverse lengthscale parameters of the Matern kernel. We ensure that these parameters are\n# positive with the softplus function\n# ```math\n# f(x) = \\log (1 + \\exp x).\n# ```\n\nfunction gp_loglikelihood(x, y)\n    function loglikelihood(params)\n        kernel =\n            softplus(params[1]) * (Matern52Kernel() ∘ ScaleTransform(softplus(params[2])))\n        f = GP(kernel)\n        fx = f(x, 0.1)\n        return logpdf(fx, y)\n    end\n    return loglikelihood\nend\n\nconst loglik_train = gp_loglikelihood(x_train, y_train)\n#md nothing #hide\n\n# We define a Gaussian prior for the joint distribution of the two transformed kernel\n# parameters. We assume that both parameters are independent with mean 0 and variance 1.\n\nlogprior(params) = logpdf(MvNormal(2, 1), params)\n#md nothing #hide\n\n# ### Hamiltonian Monte Carlo\n#\n# We start with a Hamiltonian Monte Carlo (HMC) sampler. More precisely, we use the\n# [No-U-Turn sampler (NUTS)](http://www.jmlr.org/papers/volume15/hoffman14a/hoffman14a.pdf),\n# which is provided by the Julia packages\n# [AdvancedHMC.jl](https://github.com/TuringLang/AdvancedHMC.jl/) and\n# [DynamicHMC.jl](https://github.com/tpapp/DynamicHMC.jl/).\n#\n# #### AdvancedHMC\n#\n# We start with performing inference with AdvancedHMC.\n\nusing AdvancedHMC\nusing ForwardDiff\n\n# Set the number of samples to draw and warmup iterations.\n\nn_samples = 2_000\nn_adapts = 1_000\n#md nothing #hide\n\n# Define a Hamiltonian system of the log joint probability.\n\nlogjoint_train(params) = loglik_train(params) + logprior(params)\nmetric = DiagEuclideanMetric(2)\nhamiltonian = Hamiltonian(metric, logjoint_train, ForwardDiff)\n#md nothing #hide\n\n# Define a leapfrog solver, with initial step size chosen heuristically.\n\ninitial_params = rand(2)\ninitial_ϵ = find_good_stepsize(hamiltonian, initial_params)\nintegrator = Leapfrog(initial_ϵ)\n#md nothing #hide\n\n# Define an HMC sampler, with the following components:\n# - multinomial sampling scheme,\n# - generalised No-U-Turn criteria, and\n# - windowed adaption for step-size and diagonal mass matrix\n\nproposal = NUTS{MultinomialTS,GeneralisedNoUTurn}(integrator)\nadaptor = StanHMCAdaptor(MassMatrixAdaptor(metric), StepSizeAdaptor(0.8, integrator))\n#md nothing #hide\n\n# We draw samples from the posterior distribution of kernel parameters. These samples\n# are in the unconstrained space $\\mathbb{R}^2$.\n\nsamples, _ = sample(\n    hamiltonian, proposal, initial_params, n_samples, adaptor, n_adapts; progress=false\n)\n#md nothing #hide\n\n# We transform the samples back to the constrained space and compute the mean of both\n# parameters:\n\nsamples_constrained = [map(softplus, p) for p in samples]\nmean_samples = mean(samples_constrained)\n\n# We plot a histogram of the samples for the two parameters.\n# The vertical line in each graph indicates the mean of the samples.\n\nhistogram(\n    reduce(hcat, samples_constrained)';\n    xlabel=\"sample\",\n    ylabel=\"counts\",\n    layout=2,\n    title=[\"variance\" \"inverse length scale\"],\n    legend=false,\n)\nvline!(mean_samples'; linewidth=2)\n\n# We approximate the log-likelihood of the test data using the posterior Gaussian processes\n# for kernels with the sampled kernel parameters. We can observe that there is a significant\n# improvement over the log-likelihood of the test data with respect to the posterior\n# Gaussian process with default kernel parameters of value 1.\n\nfunction gp_posterior(x, y, p)\n    kernel = softplus(p[1]) * (Matern52Kernel() ∘ ScaleTransform(softplus(p[2])))\n    f = GP(kernel)\n    return posterior(f(x, 0.1), y)\nend\n\nmean(logpdf(gp_posterior(x_train, y_train, p)(x_test), y_test) for p in samples)\n\n# We sample 5 functions from each posterior GP given by the final 100 samples of kernel\n# parameters.\n\nplt = plot(; xlim=(0, 1), xlabel=\"x\", ylabel=\"y\", title=\"posterior (AdvancedHMC)\")\nfor (i, p) in enumerate(samples[(end - 100):end])\n    sampleplot!(\n        plt,\n        0:0.02:1,\n        gp_posterior(x_train, y_train, p);\n        samples=5,\n        seriescolor=\"red\",\n        label=(i == 1 ? \"samples\" : nothing),\n    )\nend\nscatter!(plt, x_train, y_train; label=\"Train Data\", markercolor=1)\nscatter!(plt, x_test, y_test; label=\"Test Data\", markercolor=2)\nplt\n\n# #### DynamicHMC\n#\n# We repeat the inference with DynamicHMC. DynamicHMC requires us to\n# implement the LogDensityProblems interface for `loglik_train`.\n\nusing DynamicHMC\nusing LogDensityProblems\n\n## Log joint density\nfunction LogDensityProblems.logdensity(ℓ::typeof(loglik_train), params)\n    return ℓ(params) + logprior(params)\nend\n\n## The parameter space is two-dimensional\nLogDensityProblems.dimension(::typeof(loglik_train)) = 2\n\n## `loglik_train` does not allow to evaluate derivatives of\n## the log-likelihood function\nfunction LogDensityProblems.capabilities(::Type{<:typeof(loglik_train)})\n    return LogDensityProblems.LogDensityOrder{0}()\nend\n\n# Now we can draw samples from the posterior distribution of kernel parameters with\n# DynamicHMC. Again we use [ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl)\n# to compute the derivatives of the log joint density with automatic differentiation.\n\nsamples =\n    mcmc_with_warmup(\n        Random.GLOBAL_RNG,\n        ADgradient(:ForwardDiff, loglik_train),\n        n_samples;\n        reporter=NoProgressReport(),\n    ).chain\n#md nothing #hide\n\n# We transform the samples back to the constrained space and compute the mean of both\n# parameters:\n\nsamples_constrained = [map(softplus, p) for p in samples]\nmean_samples = mean(samples_constrained)\n\n# We plot a histogram of the samples for the two parameters.\n# The vertical line in each graph indicates the mean of the samples.\n\nhistogram(\n    reduce(hcat, samples_constrained)';\n    xlabel=\"sample\",\n    ylabel=\"counts\",\n    layout=2,\n    title=[\"variance\" \"inverse length scale\"],\n    legend=false,\n)\nvline!(mean_samples'; linewidth=2)\n\n# Again we can observe that there is a significant improvement over the log-likelihood\n# of the test data with respect to the posterior Gaussian process with default kernel\n# parameters.\n\nmean(logpdf(gp_posterior(x_train, y_train, p)(x_test), y_test) for p in samples)\n\n# We sample a function from the posterior GP for the final 100 samples of kernel\n# parameters.\n\nplt = plot(; xlim=(0, 1), xlabel=\"x\", ylabel=\"y\", title=\"posterior (DynamicHMC)\")\nscatter!(plt, x_train, y_train; label=\"Train Data\")\nscatter!(plt, x_test, y_test; label=\"Test Data\")\nfor p in samples[(end - 100):end]\n    sampleplot!(plt, 0:0.02:1, gp_posterior(x_train, y_train, p); seriescolor=\"red\")\nend\nplt\n\n# ### Elliptical slice sampling\n#\n# Instead of HMC, we use\n# [elliptical slice sampling](http://proceedings.mlr.press/v9/murray10a/murray10a.pdf)\n# which is provided by the Julia package\n# [EllipticalSliceSampling.jl](https://github.com/TuringLang/EllipticalSliceSampling.jl/).\n\nusing EllipticalSliceSampling\n\n# We draw 2000 samples from the posterior distribution of kernel parameters.\n\nsamples = sample(ESSModel(\n    MvNormal(2, 1), # Gaussian prior\n    loglik_train,\n), ESS(), n_samples; progress=false)\n#md nothing #hide\n\n# We transform the samples back to the constrained space and compute the mean of both\n# parameters:\n\nsamples_constrained = [map(softplus, p) for p in samples]\nmean_samples = mean(samples_constrained)\n\n# We plot a histogram of the samples for the two parameters.\n# The vertical line in each graph indicates the mean of the samples.\n\nhistogram(\n    reduce(hcat, samples_constrained)';\n    xlabel=\"sample\",\n    ylabel=\"counts\",\n    layout=2,\n    title=[\"variance\" \"inverse length scale\"],\n)\nvline!(mean_samples'; layout=2, labels=\"mean\")\n\n# Again we can observe that there is a significant improvement over the log-likelihood\n# of the test data with respect to the posterior Gaussian process with default kernel\n# parameters.\n\nmean(logpdf(gp_posterior(x_train, y_train, p)(x_test), y_test) for p in samples)\n\n# We sample a function from the posterior GP for the final 100 samples of kernel\n# parameters.\n\nplt = plot(;\n    xlim=(0, 1), xlabel=\"x\", ylabel=\"y\", title=\"posterior (EllipticalSliceSampling)\"\n)\nscatter!(plt, x_train, y_train; label=\"Train Data\")\nscatter!(plt, x_test, y_test; label=\"Test Data\")\nfor p in samples[(end - 100):end]\n    sampleplot!(plt, 0:0.02:1, gp_posterior(x_train, y_train, p); seriescolor=\"red\")\nend\nplt\n\n# ## Variational Inference\n#\n# Sanity check for the Evidence Lower BOund (ELBO) implemented according to\n# M. K. Titsias's _Variational learning of inducing variables in sparse Gaussian processes_.\n\nelbo(VFE(f(rand(5))), fx, y_train)\n\n# We use the LBFGS algorithm to maximize the given ELBO. It is provided by the Julia\n# package [Optim.jl](https://github.com/JuliaNLSolvers/Optim.jl).\n\nusing Optim\n\n# We define a function which returns the negative ELBO for different variance and inverse\n# lengthscale parameters of the Matern kernel and different pseudo-points. We ensure that\n# the kernel parameters are positive with the softplus function\n# ```math\n# f(x) = \\log (1 + \\exp x),\n# ```\n# and that the pseudo-points are in the unit interval $[0,1]$ with the logistic function\n# ```math\n# f(x) = \\frac{1}{1 + \\exp{(-x)}}.\n# ```\n\njitter = 1e-6  # \"observing\" the latent process with some (small) amount of jitter improves numerical stability\n\nfunction objective_function(x, y)\n    function negative_elbo(params)\n        kernel =\n            softplus(params[1]) * (Matern52Kernel() ∘ ScaleTransform(softplus(params[2])))\n        f = GP(kernel)\n        fx = f(x, 0.1)\n        z = logistic.(params[3:end])\n        approx = VFE(f(z, jitter))\n        return -elbo(approx, fx, y)\n    end\n    return negative_elbo\nend\n#md nothing #hide\n\n# We randomly initialize the kernel parameters and 5 pseudo points, and minimize the\n# negative ELBO with the LBFGS algorithm and obtain the following optimal parameters:\n\nx0 = rand(7)\nopt = optimize(objective_function(x_train, y_train), x0, LBFGS())\n\n#-\n\nopt.minimizer\n\n# The optimized value of the variance is\n\nsoftplus(opt.minimizer[1])\n\n# and of the inverse lengthscale is\n\nsoftplus(opt.minimizer[2])\n\n# We compute the log-likelihood of the test data for the resulting approximate\n# posterior. We can observe that there is a significant improvement over the\n# log-likelihood with the default kernel parameters of value 1.\n\nopt_kernel =\n    softplus(opt.minimizer[1]) *\n    (Matern52Kernel() ∘ ScaleTransform(softplus(opt.minimizer[2])))\nopt_f = GP(opt_kernel)\nopt_fx = opt_f(x_train, 0.1)\nap = posterior(VFE(opt_f(logistic.(opt.minimizer[3:end]), jitter)), opt_fx, y_train)\nlogpdf(ap(x_test), y_test)\n\n# We visualize the approximate posterior with optimized parameters.\n\nscatter(\n    x_train,\n    y_train;\n    xlim=(0, 1),\n    xlabel=\"x\",\n    ylabel=\"y\",\n    title=\"posterior (VI with sparse grid)\",\n    label=\"Train Data\",\n)\nscatter!(x_test, y_test; label=\"Test Data\")\nplot!(0:0.001:1, ap; label=false, ribbon_scale=2)\nvline!(logistic.(opt.minimizer[3:end]); label=\"Pseudo-points\")\n\n# ## Exact Gaussian Process Inference\n#\n# Here we use Type-II MLE to train the hyperparameters of the Gaussian process.\n# This means that our loss function is the negative log marginal likelihood.\n\n# We re-calculate the log-likelihood of the test dataset with the\n# default kernel parameters of value 1 for the sake of comparison.\n\nlogpdf(p_fx(x_test), y_test)\n\n# We define a function which returns the negative log marginal\n# likelihood for different variance and inverse lengthscale parameters\n# of the Matern kernel and different pseudo-points. We ensure that the\n# kernel parameters are positive with the softplus function\n# ``f(x) = \\log (1 + \\exp x)``.\n\nfunction loss_function(x, y)\n    function negativelogmarginallikelihood(params)\n        kernel =\n            softplus(params[1]) * (Matern52Kernel() ∘ ScaleTransform(softplus(params[2])))\n        f = GP(kernel)\n        fx = f(x, 0.1)\n        return -logpdf(fx, y)\n    end\n    return negativelogmarginallikelihood\nend\n\n#md nothing #hide\n\n# We randomly initialize the kernel parameters, and minimize the\n# negative log marginal likelihood with the LBFGS algorithm\n# and obtain the following optimal parameters:\n\nθ0 = randn(2)\nopt = Optim.optimize(loss_function(x_train, y_train), θ0, LBFGS())\n\n#-\n\nopt.minimizer\n\n# The optimized value of the variance is\n\nsoftplus(opt.minimizer[1])\n\n# and of the inverse lengthscale is\n\nsoftplus(opt.minimizer[2])\n\n# We compute the log-likelihood of the test data for the resulting optimized\n# posterior. We can observe that there is a significant improvement over the\n# log-likelihood with the default kernel parameters of value 1.\n\nopt_kernel =\n    softplus(opt.minimizer[1]) *\n    (Matern52Kernel() ∘ ScaleTransform(softplus(opt.minimizer[2])))\n\nopt_f = GP(opt_kernel)\nopt_fx = opt_f(x_train, 0.1)\nopt_p_fx = posterior(opt_fx, y_train)\nlogpdf(opt_p_fx(x_test), y_test)\n\n# We visualize the posterior with optimized parameters.\n\nscatter(\n    x_train,\n    y_train;\n    xlim=(0, 1),\n    xlabel=\"x\",\n    ylabel=\"y\",\n    title=\"posterior (optimized parameters)\",\n    label=\"Train Data\",\n)\nscatter!(x_test, y_test; label=\"Test Data\")\nplot!(0:0.001:1, opt_p_fx; label=false, ribbon_scale=2)\n", "meta": {"hexsha": "6552e3d46f1abeacf09ddf64bf55a8b53ff432d7", "size": 15838, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/0-intro-1d/script.jl", "max_stars_repo_name": "JuliaGaussianProcesses/AbstractGP", "max_stars_repo_head_hexsha": "6ee8549f536c6037a02a1cc445fd35c0811425ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-11T11:07:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T06:42:23.000Z", "max_issues_repo_path": "examples/0-intro-1d/script.jl", "max_issues_repo_name": "JuliaGaussianProcesses/AbstractGP", "max_issues_repo_head_hexsha": "6ee8549f536c6037a02a1cc445fd35c0811425ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/0-intro-1d/script.jl", "max_forks_repo_name": "JuliaGaussianProcesses/AbstractGP", "max_forks_repo_head_hexsha": "6ee8549f536c6037a02a1cc445fd35c0811425ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.873294347, "max_line_length": 142, "alphanum_fraction": 0.7323525698, "num_tokens": 4250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.8840392756357327, "lm_q1q2_score": 0.7583006909845704}}
{"text": "#2-dim CAs\n\n#Two dimensional Cellular Automaton\n#TODO: Change naming to be consistent\nmutable struct CA2d\n\n    #User given values\n    k::Int #Number of states\n    r::Int #r-nearest neigbors\n\n    #Internal values\n    cells::Array{Int8, 3}\n\n    function CA2d(B::Array{Int,1},\n                  S::Array{Int,1},\n                  init::Array{Int,2},\n                  gen::Int,\n                  k::Int=2,\n                  r::Int=1)\n\n        h, w = size(init)\n\n\n        cells = Array{Int8}(undef, (h, w, gen)) #Syntax A(T, dims) is deprecated\n        cells[:, :, 1] = Array{Int8}(init[:, :])\n\n        for g = 2:gen\n            for i = 1:h, j = 1:w\n                cc = -cells[i, j, g-1]\n                for p = (i-r):(i+r), q = (j-r):(j+r)\n\n                    #Cyclic boundary conditions\n                    if p < 1; p = h-p; end\n                    if p > h; p = p-h; end\n                    if q < 1; q = w-q; end\n                    if q > w; q = q-w; end\n\n                    cc += cells[p, q, g-1]\n                end\n                cells[i, j, g] = eval_rule(cc, cells[i, j, g-1], B, S)\n            end #hw ij\n        end #gen\n\n        new(k, r, cells)\n    end\nend\n\n#Evaluate life rules\n#TODO: make this more general\nfunction eval_rule(cc, olds, B, S, k=2)\n    if cc in B || (olds == 1 && cc in S)\n        return 1\n    end\n\n    return 0\nend\n", "meta": {"hexsha": "783578d4f5ff096634c90ee3a44861035ed33395", "size": 1348, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/2dim.jl", "max_stars_repo_name": "ceferisbarov/CellularAutomata.jl", "max_stars_repo_head_hexsha": "05d84c738bdfdbdce70a70a84c0ee542a6eedb75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-31T12:56:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T07:05:16.000Z", "max_issues_repo_path": "src/2dim.jl", "max_issues_repo_name": "ceferisbarov/CellularAutomata.jl", "max_issues_repo_head_hexsha": "05d84c738bdfdbdce70a70a84c0ee542a6eedb75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/2dim.jl", "max_forks_repo_name": "ceferisbarov/CellularAutomata.jl", "max_forks_repo_head_hexsha": "05d84c738bdfdbdce70a70a84c0ee542a6eedb75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.649122807, "max_line_length": 80, "alphanum_fraction": 0.4354599407, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7582478954164481}}
{"text": "#=\nThis script shows how a simple MLP net may be used\nfor regression. It shows how data in memory may be\nused for training and evaluation, and how to obtain\nthe predictions from the trained net.\n=#\nusing MXNet\nusing Distributions\nusing PyPlot\n\n# data generating process\ngenerate_inputs(mean, var, size) = rand(MvNormal(mean, var), size)\noutput(data) = sin(data[1,:]).*sin(data[2,:])./(data[1,:].*data[2,:])\n\n# create training and evaluation data sets\nmean=[0.0;0.0]\nvar=[1.0 0.0;0.0 1.0]\nsamplesize  = 5000\nTrainInput = generate_inputs(mean, var, samplesize)\nTrainOutput = output(TrainInput)\nValidationInput = generate_inputs(mean, var, samplesize)\nValidationOutput = output(ValidationInput)\n\n# how to set up data providers using data in memory\nbatchsize = 100 # can adjust this later, but must be defined now for next line\ntrainprovider = mx.ArrayDataProvider(:data => TrainInput, batch_size=batchsize, shuffle=true, :label => TrainOutput)\nevalprovider = mx.ArrayDataProvider(:data => ValidationInput, batch_size=batchsize, shuffle=true, :label => ValidationOutput)\n\n# create a two hidden layer MPL: try varying num_hidden, and change tanh to relu,\n# or add/remove a layer\ndata = mx.Variable(:data)\nlabel = mx.Variable(:label)\nnet  = @mx.chain    mx.FullyConnected(data = data, num_hidden=10) =>\n                    mx.Activation(act_type=:tanh) =>\n                    mx.FullyConnected(num_hidden=3) =>\n                    mx.Activation(act_type=:tanh) =>\n                    mx.FullyConnected(num_hidden=1)        \n\n# squared error loss is appropriate for regression, don't change\ncost = mx.LinearRegressionOutput(data = net, label=label)\n\n# final model definition, don't change, except if using gpu\nmodel = mx.FeedForward(cost, context=mx.cpu())\n\n# set up the optimizer: select one, explore parameters, if desired\n#optimizer = mx.SGD(lr=0.01, momentum=0.9, weight_decay=0.00001)\noptimizer = mx.ADAM()\n\n# train, reporting loss for training and evaluation sets\n# initial training with small batch size, to get to a good neighborhood\nbatchsize = 100\nmx.fit(model, optimizer, initializer=mx.NormalInitializer(0.0,0.1), eval_metric=mx.MSE(), trainprovider, eval_data=evalprovider, n_epoch = 500)\n# more training with the full sample\nbatchsize = samplesize\nmx.fit(model, optimizer, eval_metric=mx.MSE(), trainprovider, eval_data=evalprovider, n_epoch = 500)\n\n# obtain predictions\nplotprovider = mx.ArrayDataProvider(:data => ValidationInput, :label => ValidationOutput)\nfit = mx.predict(model, plotprovider)\nplot(ValidationOutput,fit',\".\")\nxlabel(\"true\")\nylabel(\"predicted\")\ntitle(\"outputs: true versus predicted. 45º line is what we hope for\")\n", "meta": {"hexsha": "8c949f9b2facb9b34f86da1ec36d254fc55b9839", "size": 2643, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/regression-example.jl", "max_stars_repo_name": "Arkoniak/MXNet.jl", "max_stars_repo_head_hexsha": "c06b21111971878d9a8f46c75f9a22bb668fd780", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/regression-example.jl", "max_issues_repo_name": "Arkoniak/MXNet.jl", "max_issues_repo_head_hexsha": "c06b21111971878d9a8f46c75f9a22bb668fd780", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-12-30T09:01:03.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-10T07:14:52.000Z", "max_forks_repo_path": "examples/regression-example.jl", "max_forks_repo_name": "Arkoniak/MXNet.jl", "max_forks_repo_head_hexsha": "c06b21111971878d9a8f46c75f9a22bb668fd780", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.296875, "max_line_length": 143, "alphanum_fraction": 0.7347710935, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7582478910393804}}
{"text": "function mult(M, V) #funkcja mnozaca macierze M V\n    R = zeros(size(M,1), size(V,2))\n    for i = 1:size(M,1)\n        for j = 1:size(V,2)\n            for k = 1:size(M,1)\n                R[i,j] += M[i,k] * V[k,j]\n            end\n        end\n    end\n    return R\nend\n\nfunction strassen(A, B, size, stop) #algorytm Strassena, mnozy macierze A, B o rozmiarze size\n   if size <= stop\n      return mult(A,B)\n   end\n   half = div(size,2)\n   a11 = A[1:half, 1:half]\n   a12 = A[1:half, half+1:size]\n   a21 = A[half+1:size, 1:half]\n   a22 = A[half+1:size, half+1:size]\n\n   b11 = B[1:half, 1:half]\n   b12 = B[1:half, half+1:size]\n   b21 = B[half+1:size, 1:half]\n   b22 = B[half+1:size, half+1:size]\n\n   m1 = strassen(a11 + a22, b11 + b22, half, stop)\n   m2 = strassen(a21 + a22, b11, half, stop)\n   m3 = strassen(a11, b12 - b22, half, stop)\n   m4 = strassen(a22, b21 - b11, half, stop)\n   m5 = strassen(a11 + a12, b22, half, stop)\n   m6 = strassen(a21 - a11, b11 + b12, half, stop)\n   m7 = strassen(a12 - a22, b21 + b22, half, stop)\n\n   c11 = m1 + m4 - m5 + m7\n   c12 = m3 + m5\n   c21 = m2 + m4\n   c22 = m1 - m2 + m3 + m6\n\n   res = vcat(hcat(c11, c12), hcat(c21, c22))\n   return res\nend\nfunction s_mult(A,B,stop)\n   edge1 = size(A, 1)\n   edge2 = size(A, 2)\n   pow2 = 2^Integer(ceil(max(log(2, edge2),\n                             log(2, edge1))))\n   if edge1 < pow2 || edge2 < pow2\n      zero_ = zeros(pow2-edge1, edge2)\n      A = vcat(A, zero_)\n      zero_ = zeros(size(A, 1), pow2-edge2)\n      A = hcat(A, zero_)\n      zero_ = zeros(edge2, pow2-edge1)\n      B = hcat(B, zero_)\n      zero_ = zeros(pow2-edge2, size(B,2))\n      B = vcat(B, zero_)\n   end\n\n   res = strassen(A,B, pow2, stop)\n   return res[1:edge1, 1:edge1]\nend\n\n\nfunction err(M)\n   r = size(M, 1)\n   c = size(M, 2)\n   sum = Float64(0)\n   for i in 1:r\n      for j in 1:c\n         k = M[r,c]\n         sum += k*k\n      end\n   end\n    return sum\nend\n\nfunction bestStrass(A, B)\n   return s_mult(A, B, 64)\nend\n\n\nfunction compare()\n    M_size = 64\n    for i in 1:10\n        A = rand(-100.0:0.001:100.0, M_size, M_size)\n        B = rand(-100.0:0.001:100.0, M_size, M_size)\n        C = rand(-100.0:0.001:100.0, M_size, M_size)\n        S_result = test_str(A,B,C, 64)\n        N_result = test_normal(A,B,C)\n        println(err(S_result))\n        println(err(N_result))\n        println(\"Blad wzgledny:\", abs(err(S_result) - err(N_result)) / err(N_result) )\n    end\nend\n#compare()\nfunction memory_usage()\n    M_size = 512\n    A = rand(-100.0:0.001:100.0, M_size, M_size)\n    B = rand(-100.0:0.001:100.0, M_size, M_size)\n    @timev mult(A,B)\n    @timev s_mult(A,B, 64)\nend\n#memory_usage()\n", "meta": {"hexsha": "ca1d3c9a8156a7bd08593107b899a5ccc53bec77", "size": 2628, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "II rok/I semestr/ANM/Pracownia 1/prog/program.jl", "max_stars_repo_name": "antonitomaszewski/Studia", "max_stars_repo_head_hexsha": "ff2fa59e25cf3f5c86b59de9994b80a502ec1e7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "II rok/I semestr/ANM/Pracownia 1/prog/program.jl", "max_issues_repo_name": "antonitomaszewski/Studia", "max_issues_repo_head_hexsha": "ff2fa59e25cf3f5c86b59de9994b80a502ec1e7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "II rok/I semestr/ANM/Pracownia 1/prog/program.jl", "max_forks_repo_name": "antonitomaszewski/Studia", "max_forks_repo_head_hexsha": "ff2fa59e25cf3f5c86b59de9994b80a502ec1e7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0285714286, "max_line_length": 93, "alphanum_fraction": 0.549847793, "num_tokens": 1027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.7582405540910142}}
{"text": "# This code generates the 2l+1 dimensional matrix Fourier coefficients\n# for a function defined over the rotation and rotation/reflection groups\n#\n# The routines in this file are based upon:\n#\n#   FFTs on the Rotation Group\n#   Peter J. Kostelec and Daniel N. Rockmore\n#   J. Fourier. Anal. Appl., Vol. 14, Issue. 2, p. 145-179, 2008\n\nimport Base.fft\n\nfunction w(B::Int, k::Int)\n    s = 0.0\n    \n    for j in 0:B-1\n        s += sin((2j + 1) * (2k + 1) * (π / (4B))) / (2j + 1)\n    end\n    \n    s *= (2/B) * sin(π * (2k + 1) / (4B))\nend\n\nfunction S₁(f::Function, B::Int, k::Int, j₂::Int)\n    β = π * (2k + 1) / (4B)\n    γ = (2π * j₂) / (2B)\n    \n    A = [exp(-im * ((2π * j₁) / (2B)) * (B - 1)) * f(O3((2π * j₁) / (2B), β, γ)) for j₁ in 0:2B-1]\n    A′ = ifft(A)\nend\n\nfunction S₂(f::Function, B::Int, k::Int)\n    S = [S₁(f, B, k, j₂) for j₂ in 0:2B-1]\n    A = Vector{Vector{Complex128}}(2B)\n    A′ = Vector{Vector{Complex128}}(2B)\n    \n    for M′ in -(B-1):B\n        A[M′ + B] = [exp(-im * ((2π * j₂) / (2B)) * (B - 1)) * S[j₂ + 1][M′ + B] for j₂ in 0:2B-1]\n        A′[M′ + B] = ifft(A[M′ + B])\n    end\n    \n    return hcat(A′...)\nend\n\nfunction fast_fourier_coeffs(f::Function, B::Int)\n    S = [S₂(f, B, k) for k in 0:2B-1]\n    f̂ = [zeros(Complex128, 2l + 1, 2l + 1) for l in 0:B-1]\n    \n    for l in 0:B-1\n        for M in -l:l, M′ in -l:l\n            for k in 0:2B-1\n                β = π * (2k + 1) / (4B)\n                f̂[l + 1][M′ + l + 1, M + l + 1] += wigner_d̃(l, M, M′, β) * w(B, k) * S[k + 1][M′ + B, M + B] / sqrt(2 / (2l + 1))\n            end\n        end\n    end\n    \n    return f̂\nend\n\nfft(f::Function, ::Type{O3}, L::Int) = fast_fourier_coeffs(f, L)\n", "meta": {"hexsha": "53432dc649dae0fc5e52d1d83456e76ba6659c6b", "size": 1665, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fft_O3.jl", "max_stars_repo_name": "NickMcNutt/GroupFFT.jl", "max_stars_repo_head_hexsha": "b89283174ff8d57101619df97ea891bfe656acbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-02T05:53:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T14:42:41.000Z", "max_issues_repo_path": "src/fft_O3.jl", "max_issues_repo_name": "NickMcNutt/GroupFFT.jl", "max_issues_repo_head_hexsha": "b89283174ff8d57101619df97ea891bfe656acbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fft_O3.jl", "max_forks_repo_name": "NickMcNutt/GroupFFT.jl", "max_forks_repo_head_hexsha": "b89283174ff8d57101619df97ea891bfe656acbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.75, "max_line_length": 131, "alphanum_fraction": 0.4828828829, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576265, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7582405451448232}}
{"text": "# Algorithm 3.2\n# Newton's interpolatory divided difference.\n\nfunction dividedDiff(x, y)\n\tn = length(x)\n\tout = zeros(n, n)\n\tfor i ∈ 1:n\n\t\tout[i, 1] = y[i]\n\tend\n\tfor i ∈ 2:n\n\t\tfor j ∈ 2:i\n\t\t\tout[i, j] = (out[i, j - 1] - out[i - 1, j - 1]) / (x[i] - x[i - j + 1])\n\t\tend\n\tend\n\treturn out\nend\n\nprintln(dividedDiff([1, 1.3, 1.6, 1.9, 2.2], [-0.76, -0.54, -0.57, -0.57, 0.3]))\n", "meta": {"hexsha": "861254bd1381f274a5e949e3639b2b2f0168704a", "size": 371, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter3/div_diff.jl", "max_stars_repo_name": "Matt8898/julia-numerical", "max_stars_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-05T01:36:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-26T04:07:41.000Z", "max_issues_repo_path": "chapter3/div_diff.jl", "max_issues_repo_name": "Matt8898/julia-numerical", "max_issues_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter3/div_diff.jl", "max_forks_repo_name": "Matt8898/julia-numerical", "max_forks_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5263157895, "max_line_length": 80, "alphanum_fraction": 0.5336927224, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576265, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.7582405333111848}}
{"text": "# Source: https://julialang.org/blog/2016/02/iteration/#writing_multidimensional_algorithms_with_cartesianindex_iterators\n# compute the \"moving average\" over a 3-by-3-by-... block around each element\n# Origin code:\nfunction boxcar3(A::AbstractArray)\n    out = similar(A)\n    R = CartesianIndices(A)\n    Ifirst, Ilast = first(R), last(R)\n    I1 = oneunit(Ifirst)\n    for I in R\n        n, s = 0, zero(eltype(out))\n        for J in max(Ifirst, I-I1):min(Ilast, I+I1)\n            s += A[J]\n            n += 1\n        end\n        out[I] = s/n\n    end\n    out\nend\n#--------------------------------------------------------------\n\"\"\"\n    move_average(A, N)\n\ncompute the moving average over a (2N+1)-by-(2N+1)-by-... block around each element\n\"\"\"\nfunction move_average(A::AbstractArray, N::Integer)\n    out = similar(A)\n    R = CartesianIndices(A)\n    Ifirst, Ilast = first(R), last(R)\n    I1 = oneunit(Ifirst)\n    for I in R\n        n, s = 0, zero(eltype(out))\n        for J in max(Ifirst, I-N*I1):min(Ilast, I+N*I1)\n            s += A[J]\n            n += 1\n        end\n        out[I] = s/n\n    end\n    out\nend\n\n", "meta": {"hexsha": "c29a776e45309edd7b34c0c2757583bd7307c676", "size": 1105, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/moving average.jl", "max_stars_repo_name": "lihua-cat/UsefulFunctions.jl", "max_stars_repo_head_hexsha": "05346a3756cabd93c716d0121a64fcc4debd8f49", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/moving average.jl", "max_issues_repo_name": "lihua-cat/UsefulFunctions.jl", "max_issues_repo_head_hexsha": "05346a3756cabd93c716d0121a64fcc4debd8f49", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/moving average.jl", "max_forks_repo_name": "lihua-cat/UsefulFunctions.jl", "max_forks_repo_head_hexsha": "05346a3756cabd93c716d0121a64fcc4debd8f49", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9512195122, "max_line_length": 121, "alphanum_fraction": 0.5447963801, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7582102564642518}}
{"text": "# PAU 2016-Modelo A-Pregunta 3\n\n# Física Enrique García @FiQuiPedia www.fiquipedia.es\n# Código por Samuel Gómez @profesor_s www.ingetec.com.es\n# Licencia Creative Commons\n# http://creativecommons.org/licenses/by/4.0/deed.es_ES\n\n# Una carga puntual, q = 3 μC, se encuentra situada en\n# el origen de coordenadas, tal y como se muestra en la figura. Una\n# segunda carga q1 = 1 μC se encuentra inicialmente en el punto P1(1,0)\n# m y, recorriendo la espiral de la figura, llega al punto P2(0,2) m.\n# Determine:\n# a. La diferencia de potencial entre los puntos P1 y P2.\n# b. El trabajo realizado para llevar la carga q1 del punto P1 al P2.\n# Datos: Constante de la Ley de Coulomb; K = 9·109 N m2 C-2\n\nusing Distances     # https://github.com/JuliaStats/Distances.jl\n\nconst k = 9.00e9            # N m^2 C^-2\n\ntype carga\n    punto::Vector{Float64}  # (x,y). Metros\n    carga::Float16          # Culombios\nend\n\nq = carga([0,0], 3e-6)\nq1 = carga([1,0], 1e-6)\ndestino = [0, 2]\n\n# Potencial V\nfunction potencial(q, r)\n    return (k*q)/r\nend\n\n# Distancia entre dos puntos\nfunction dist(a, b)\n    return evaluate(Euclidean(), a, b)\nend\n\n\n### Resolución\n\n# a. La diferencia de potencial entre los puntos P1 y P2.\nv1 = potencial(q.carga, dist(q.punto, q1.punto))\nv2 = potencial(q.carga, dist(q.punto, destino))\nv = v2 - v1\nprintln(\"a) La diferencia de potencial es \",round(v,2),\" voltios\")\n\n\n\n# b. El trabajo realizado para llevar la carga q1 del punto P1 al P2.\nw = -q1.carga * (v2-v1)\nprintln(\"b) El trabajo realizado es \",round(w, 4), \" julios\")\n", "meta": {"hexsha": "f3e23a2f0113388916938243d1054c8226c216a6", "size": 1534, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PAU/2016-Modelo-A3.jl", "max_stars_repo_name": "profesors/physics", "max_stars_repo_head_hexsha": "723bf0c0945d423ea95f3c531f26f34cc5fb66ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PAU/2016-Modelo-A3.jl", "max_issues_repo_name": "profesors/physics", "max_issues_repo_head_hexsha": "723bf0c0945d423ea95f3c531f26f34cc5fb66ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PAU/2016-Modelo-A3.jl", "max_forks_repo_name": "profesors/physics", "max_forks_repo_head_hexsha": "723bf0c0945d423ea95f3c531f26f34cc5fb66ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4074074074, "max_line_length": 71, "alphanum_fraction": 0.6870925684, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7582102551508849}}
{"text": "function ten_to_two(n)\r\n    b = zeros(Int8,10)\r\n    temp_b = zeros(Int8,10)\r\n\r\n    ite=1\r\n    while n > 0\r\n        b[ite] = n % 2\r\n        n = Int((n-b[ite])/2)\r\n        ite = ite +1\r\n    end\r\n    \r\n    #=\r\n    for i in 1:6\r\n        temp_b[i] = b[6+1-i]\r\n    end\r\n    =#\r\n    \r\n    return b\r\nend\r\n\r\nfunction two_to_ten(b)\r\n    n = Int8(0)\r\n\r\n    for i in 1:length(b)\r\n        n = n + 2^(i-1)*b[i]\r\n    end\r\n    return n\r\nend\r\n\r\n# ----------------------\r\n# -- Inverse matrix   --\r\n# ----------------------\r\nfunction inverse_matrix(eu,ev)\r\n# ----------------------\r\n# -- A = ( eu[1]  ev[1])  --\r\n# --     ( eu[2]  ev[2])  --\r\n# ----------------------\r\n    invA = zeros(2,2)\r\n    detA = eu[1]*ev[2] - eu[2]*ev[1]\r\n\r\n    invA[1,1] = (ev[2])/detA\r\n    invA[1,2] = (-ev[1])/detA\r\n    invA[2,1] = (-eu[2])/detA\r\n    invA[2,2] = (eu[1])/detA\r\n    return invA\r\nend\r\n        \r\n\r\nfunction cal_morton(ulx,uly,lrx,lry,n_div) # 0<=s,tでreturn\r\n    # 左上と右下の座標を整数で\r\n    morton_belong = 0\r\n    morton_num = 0\r\n\r\n    upl_morton = zeros(Int8,10)\r\n    lowr_morton = zeros(Int8,10)\r\n    temp_morton = zeros(Int8,10)\r\n\r\n\r\n    # 左上の点のモートン空間番号\r\n    x_two = ten_to_two(ulx)\r\n    y_two = ten_to_two(uly)\r\n    \r\n    for k in 1:5\r\n        upl_morton[k*2-1] = x_two[k]\r\n        upl_morton[k*2] = y_two[k]\r\n    end\r\n\r\n    # 右下の点のモートン空間番号\r\n    x_two = ten_to_two(lrx)\r\n    y_two = ten_to_two(lry)\r\n    \r\n    for k in 1:5\r\n        lowr_morton[k*2-1] = x_two[k]\r\n        lowr_morton[k*2] = y_two[k]\r\n    end\r\n    \r\n    # 排他的論理和 xor\r\n    for i in 1:10\r\n        if upl_morton[i]+lowr_morton[i] == 2\r\n            temp_morton[i] = 0\r\n        else\r\n            temp_morton[i] = upl_morton[i]+lowr_morton[i]\r\n        end\r\n    end\r\n    \r\n    # 所属空間のチェック\r\n    \r\n    ite = Int64(0)\r\n    for i in 1:n_div\r\n        s_even = 2*(n_div-(i-1))\r\n        s_odd = 2*(n_div-(i-1)) - 1\r\n        \r\n        if temp_morton[s_even] == 1 || temp_morton[s_odd] == 1\r\n            morton_belong = ite                             # ルート空間\r\n            break\r\n        end\r\n        #=\r\n        if temp_morton[s_even] == 1 || temp_morton[s_odd] == 1\r\n            morton_belong = 0                             # ルート空間\r\n        elseif temp_morton[4] == 1 || temp_morton[3] == 1\r\n            morton_belong = 1                             # 親空間\r\n        elseif temp_morton[2] == 1 || temp_morton[1] == 1\r\n            morton_belong = 2                             # 子空間\r\n        else\r\n            morton_belong = 3                             # 孫空間\r\n        end\r\n        =#\r\n        ite += 1\r\n    end\r\n    \r\n    # 所属空間番号\r\n    temp_morton = zeros(Int8,10)\r\n    if morton_belong == 0                             # ルート空間\r\n        morton_num = 0\r\n    elseif morton_belong == 1                         # 親空間\r\n        s_even = 2*(n_div)\r\n        s_odd = 2*(n_div) - 1\r\n\r\n        # 4右シフト\r\n        temp_morton[1] = lowr_morton[s_odd]\r\n        temp_morton[2] = lowr_morton[s_even]\r\n        \r\n        morton_num = two_to_ten(temp_morton)\r\n\r\n    elseif morton_belong == 2                         # 子空間\r\n\r\n        s_even = 2*(n_div)\r\n        s_odd = 2*(n_div) - 1\r\n        \r\n        # 2右シフト\r\n        temp_morton[1] = lowr_morton[s_odd-2]\r\n        temp_morton[2] = lowr_morton[s_even-2]\r\n        temp_morton[3] = lowr_morton[s_odd]\r\n        temp_morton[4] = lowr_morton[s_even]\r\n        \r\n        morton_num = two_to_ten(temp_morton)\r\n    elseif morton_belong == 3                         # 孫空間\r\n        s_even = 2*(n_div)\r\n        s_odd = 2*(n_div) - 1\r\n        \r\n        # 0右シフト\r\n        temp_morton[1] = lowr_morton[s_odd-4]\r\n        temp_morton[2] = lowr_morton[s_even-4]\r\n        temp_morton[3] = lowr_morton[s_odd-2]\r\n        temp_morton[4] = lowr_morton[s_even-2]\r\n        temp_morton[5] = lowr_morton[s_odd]\r\n        temp_morton[6] = lowr_morton[s_even]\r\n        \r\n        morton_num = two_to_ten(temp_morton)\r\n        \r\n    elseif morton_belong == 4                         # 孫空間\r\n        temp_morton = copy(lowr_morton)\r\n        morton_num = two_to_ten(temp_morton)\r\n    end\r\n\r\n    return morton_belong,morton_num\r\nend\r\n\r\n\r\nfunction liner_morton(n_div)\r\n    # 両方の探査を行うため，煩雑\r\n    s = zeros(Int64,5)\r\n\r\n    for j in 1:5\r\n        for i in 1:(n_div+1)        \r\n            s[j] += floor(4.0^(i-j))\r\n        end\r\n        s[j] += (j-1)\r\n    end\r\n\r\n    search0 = zeros(Int64,4^0,s[1])\r\n    search1 = zeros(Int64,4^1,s[2])\r\n    search2 = zeros(Int64,4^2,s[3])\r\n    search3 = zeros(Int64,4^3,s[4])\r\n    search4 = zeros(Int64,4^4,s[5])\r\n    \r\n    # ルート空間：s0\r\n    for i in 1:1\r\n        for j in 1:s[1]\r\n            search0[i,j] = j\r\n        end\r\n    end\r\n\r\n    # 親空間：s1\r\n    for i in 1:4\r\n        search1[i,1] = 1　　　　　　　　　　　　　　　　# ルート空間\r\n        search1[i,2] = i+1                           # 親空間\r\n        for j in 1:4\r\n            search1[i,j+2] = 6 + 4*(i-1) + (j-1)     # 子空間\r\n        end\r\n        for j in 1:16\r\n            search1[i,j+6] = 22 + 16*(i-1) + (j-1)   # 孫空間\r\n        end\r\n\r\n        if n_div ==4\r\n            for j in 1:64\r\n                search1[i,j+22] = 86 + 64*(i-1) + (j-1)   # ひ孫空間\r\n            end\r\n        end\r\n    end\r\n    \r\n    # 子空間：s2\r\n    for i in 1:16\r\n        search2[i,1] = 1                             # ルート空間\r\n        search2[i,2] = div(i-1,4) + 2                # 親空間\r\n        search2[i,3] = i+5                           # 子空間\r\n        for j in 1:4\r\n            search2[i,j+3] = 22 + 4*(i-1) + (j-1)    # 孫空間\r\n        end\r\n        if n_div ==4\r\n            for j in 1:16\r\n                search2[i,j+7] = 86 + 16*(i-1) + (j-1)    # 孫空間\r\n            end\r\n        end\r\n    end\r\n    \r\n    # 孫空間\r\n    for i in 1:64\r\n        search3[i,1] = 1                             # ルート空間\r\n        search3[i,2] = div(i-1,16) + 2               # 親空間\r\n        search3[i,3] = div(i-1,4) + 6                # 子空間\r\n        search3[i,4] = 22 + (i-1)                    # 孫空間\r\n        if n_div >=4\r\n            for j in 1:4\r\n                search3[i,j+4] = 86 + 4*(i-1) + (j-1)    # 孫空間\r\n            end\r\n        end\r\n    end\r\n    \r\n    # ひ孫空間\r\n    if n_div >=4\r\n        for i in 1:256\r\n            search4[i,1] = 1                             # ルート空間\r\n            search4[i,2] = div(i-1,64) + 2               # 親空間\r\n            search4[i,3] = div(i-1,16) + 6                # 子空間\r\n            search4[i,4] = div(i-1,4) + 22                # 孫空間\r\n            search4[i,5] = 86 + (i-1)                    # 孫空間\r\n        end\r\n    end\r\n\r\n    return s,search0,search1,search2,search3,search4\r\nend\r\n", "meta": {"hexsha": "d8be03c0fddf72ea4ef17bca167c4d494fe239a5", "size": 6424, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/misc.jl", "max_stars_repo_name": "hide-dog/Qtree", "max_stars_repo_head_hexsha": "3c2b4a53bfc4c073d0cdeb6d079785a35c3bd9d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/misc.jl", "max_issues_repo_name": "hide-dog/Qtree", "max_issues_repo_head_hexsha": "3c2b4a53bfc4c073d0cdeb6d079785a35c3bd9d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/misc.jl", "max_forks_repo_name": "hide-dog/Qtree", "max_forks_repo_head_hexsha": "3c2b4a53bfc4c073d0cdeb6d079785a35c3bd9d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4362139918, "max_line_length": 68, "alphanum_fraction": 0.4151618929, "num_tokens": 2346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7582102531676184}}
{"text": "function Clifford(x::Float64, y::Float64, a::Float64, b::Float64, c::Float64, d::Float64)\n    sin(a * y) + c * cos(a * x), sin(b * x) + d * cos(b * y)\nend\nfunction De_Jong(x::Float64, y::Float64, a::Float64, b::Float64, c::Float64, d::Float64)\n    sin(a * y) - cos(b * x),sin(c * x) - cos(d * y)\nend\nfunction Svensson(x::Float64, y::Float64, a::Float64, b::Float64, c::Float64, d::Float64)\n    d * sin(a * x) - sin(b * y), c * cos(a * x) + cos(b * y)\nend\nfunction Bedhead(x::Float64, y::Float64, a::Float64, b::Float64, c::Float64, d::Float64)\n    sin(x*y/b)*y + cos(a*x-y), x + sin(y)/b\nend\nfunction Fractal_Dream(x::Float64, y::Float64, a::Float64, b::Float64, c::Float64, d::Float64)\n    sin(y*b)+c*sin(x*b), sin(x*a) + d*sin(y*a)\nend\nfunction trajectory(fn, x0::Float64, y0::Float64, a::Float64, b::Float64, c::Float64, d::Float64, \n        dθ::Float64,  n::Int64)\n    x, y, θ = zeros(n), zeros(n), 0.0\n    x[1], y[1] = x0, y0\n    for i = 1:n\n        xd, yd = fn(x[i], y[i], a, b, c, d)\n        @inbounds x[i+1], y[i+1] = xd*cos(θ), yd*cos(θ)\n        θ += dθ\n    end\n    x, y\nend\n#Examples\ncliffordExamples = [\n    [-1.3, -1.3, -1.8, -1.9],\n    [-1.4, 1.6, 1.0, 0.7],\n    [1.7, 1.7, 0.6, 1.2],\n    [1.7, 0.7, 1.4, 2.0],\n    [-1.6, 1.6, 0.7, -1.0],\n    [-1.32, -1.65, 0.74, 1.81]]\nDe_JongExamples = [\n    [-1.244, -1.251, -1.815, -1.908],\n    [1.4, -2.3, 2.4, -2.1],\n    [1.4, 1.56, 1.4, -6.56],\n    [2.01, -2.53, 1.61, -0.33],\n    [-0.827, -1.637, 1.659, -0.943],\n    [-0.709, 1.638, 0.452, 1.740]]\nSvenssonExamples = [\n    [1.5, -1.8, 1.6, 0.9],\n    [-1.78, 1.29, -0.09, -1.18],\n    [-0.91, -1.29, -1.97, -1.56],\n    [1.4, 1.56, 1.4, -6.56],\n    [-0.827, -1.637, 1.659, -0.943],\n    [1.7, 1.7, 0.6, 1.2]]\nBedheadExamples = [\n    [-0.81, -0.92, 0.0, 0.0],\n    [-0.64, 0.76, 0.0, 0.0],\n    [0.06, 0.98, 0.0, 0.0],\n    [-0.67, 0.83, 0.0, 0.0],\n    [0.65343, 0.7345345, 0.0, 0.0],\n    [1.7, 1.7, 0.0, 0.0]]\n\nattractorExamples = OrderedDict(Clifford => cliffordExamples, \n    De_Jong => De_JongExamples, Svensson => SvenssonExamples,\n    Bedhead => BedheadExamples)\n\nfunction pkgsVersion()\n    println(\"Julia == \" * string(VERSION))\n    for (key, version) ∈ sort(collect(Pkg.installed()))\n        try\n            isa(eval(Symbol(key)), Module) && println(key * \" == \" * string(version))\n        catch\n        end\n    end\nend", "meta": {"hexsha": "bb9bd4aabca9d49be8bf8de0b0f473d86fdc47d5", "size": 2324, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CodeSnippetsJulia/attractorsClifford.jl", "max_stars_repo_name": "lazarusA/CodeSnippets", "max_stars_repo_head_hexsha": "7438645d2390ad1121ddc5323dfc963b4f2432e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-09-11T08:37:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T00:44:41.000Z", "max_issues_repo_path": "attractorsClifford.jl", "max_issues_repo_name": "lazarusA/helpfulJulia", "max_issues_repo_head_hexsha": "7f0165db0de6515e0a07549e418620b7deafcb51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "attractorsClifford.jl", "max_forks_repo_name": "lazarusA/helpfulJulia", "max_forks_repo_head_hexsha": "7f0165db0de6515e0a07549e418620b7deafcb51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-08-30T12:56:21.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-03T13:17:29.000Z", "avg_line_length": 33.6811594203, "max_line_length": 98, "alphanum_fraction": 0.5180722892, "num_tokens": 1088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7582102524977186}}
{"text": "\"\"\"\n    function seasonal_matrices(fcycle,t,overtones=1)\n# Arguments\n- `fcycle`: frequency of seasonal cycle\n- `t`: time\n- `overtones=1`: optional argument for number of overtones\n# Output\n- `E`: matrix that solves E*parameters= seasonal cycle\n- `F=E†`: generalized inverse of `E`\n\"\"\"\nfunction seasonal_matrices(fcycle,t,overtones=1)\n\n    ω = 2π * fcycle # day^{-1} , seasonal frequency\n    nt = length(t)\n    freqs = overtones+1\n        \n    # times 2 for sines and cosines \n    nβ = freqs*2 + 1 # plus one to remove mean\n\n    # would be neat to return whatever type goes in\n    E = zeros(Float32,nt,nβ)\n    println(size(E))\n    \n    # mean value: make it an option\n    E[:,1] = ones(Float32,nt,1)\n    println(size(E))\n\n    for i = 1:freqs # change to 3 or 4 to get higher harmonics\n        println(length(sin.(i*ω*t)))\n        E[:,i+1] = sin.(i*ω*t)\n        E[:,i+freqs+1] = cos.(i*ω*t)\n    end\n\n    F = (E'*E)\\E' # least squares estimator\n\n    return E,F\nend\n\n\"\"\"\n    function trend_matrices(t)\n# Arguments\n- `t`: time\n# Output\n- `E`: matrix that solves E*parameters= timeseries\n- `F=E†`: generalized inverse of `E`\n\"\"\"\nfunction trend_matrices(t)\n\n    nt = length(t)\n    tbar = StatsBase.mean(t)\n\n    # 2 = y-intercept and trend\n    nβ = 2\n\n    # would be neat to return whatever type goes in\n    E = zeros(Float32,nt,nβ)\n\n    # parameter 1: value at mean t\n    # mean value: make it an option\n    E[:,1] = ones(Float32,nt,1)\n\n    E[:,2] = t .- tbar\n\n    F = (E'*E)\\E' # least squares estimator\n\n    return E,F\nend\n\n\n", "meta": {"hexsha": "bbf04b2fcf74ec98f2fdacd9fe66803eb8426e7e", "size": 1520, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SeasonalCycle.jl", "max_stars_repo_name": "ggebbie/ECCOtour.jl", "max_stars_repo_head_hexsha": "6ef98c13675038c4efafb52a837c1504244e6af8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SeasonalCycle.jl", "max_issues_repo_name": "ggebbie/ECCOtour.jl", "max_issues_repo_head_hexsha": "6ef98c13675038c4efafb52a837c1504244e6af8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-10-01T22:09:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-08T02:33:45.000Z", "max_forks_repo_path": "src/SeasonalCycle.jl", "max_forks_repo_name": "ggebbie/ECCOtour.jl", "max_forks_repo_head_hexsha": "6ef98c13675038c4efafb52a837c1504244e6af8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7142857143, "max_line_length": 62, "alphanum_fraction": 0.6078947368, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7582102508494021}}
{"text": "## Power iteration-based centrality indices ##\n\n\"\"\"\n    eigenvector(g::Graph[, eps::Real, maxiter::Int])\n\nCompute eigenvector centrality for all nodes in the graph.\n\nThe process does not always converge for directed graphs, in which case\nthe function returns an error. Oftentimes, it is useful to treat the graph\nas undirected, `eigenvector(undirected(g))`.\n\n# Arguments\n* `g::Graph`: the graph itself.\n* `eps::Real=0.0001`: convergence threshold (when score changes for each node\nstop exceeding it, the algorithm terminates).\n* `maxiter::Int=100`: maximum number of iterations.\n\"\"\"\nfunction eigenvector(g::Graph, eps::Real=1e-4, maxiter::Int=100)\n    @assert(0 < eps <= 0.1, \"convergence threshold (eps) should be positive and small\")\n    n         = nodecount(g)\n    score     = fill(0.,     n)\n    prevscore = fill(1. / n, n)\n    maxdiff   = 1.\n    iter      = 0\n    @inbounds while maxdiff > eps\n        for i = 1:n             # transfer the scores\n            score[i] = 0.\n            for j = inneighbors(g, i)\n                score[i] += prevscore[j]\n            end\n        end\n        λ = 0                   # normalize the scores\n        for i = 1:n\n            if abs(score[i]) > λ\n                λ = score[i]\n            end\n        end\n        if λ == 0\n            error(\"power iteration cannot converge\")\n            break\n        else\n            maxdiff = 0.\n            for i = 1:n\n                score[i] /= λ\n                maxdiff = max(maxdiff, abs(score[i] - prevscore[i]))\n            end\n        end\n        iter += 1\n        if iter > maxiter && maxdiff > eps\n            warn(\"power iteration did not converge in $maxiter steps, current convergence value is $maxdiff\")\n            return score\n        end\n        prevscore, score = score, prevscore\n    end\n    return prevscore\nend\n\n\n\"\"\"\n    pagerank(g::Graph[, d::Real, eps::Real])\n\nCompute PageRank scores for all nodes in the graph.\n\n# Arguments\n* `g::Graph`: the graph itself.\n* `d::Real=0.85`: damping factor (the lesser it is, the bigger proportion\n    of scores is redistributed equally between all nodes at each iteration).\n* `eps::Real=0.0001`: convergence threshold (when score changes for each node\n    stop exceeding it, the algorithm terminates).\n\"\"\"\nfunction pagerank(g::Graph, d::Real=0.85, eps::Real=1e-4)\n    @assert(0 < d < 1,     \"damping factor (d) should be between 0 and 1\")\n    @assert(0 < eps < 0.1, \"convergence threshold (eps) should be positive and small\")\n    n         = nodecount(g)\n    score     = fill(0.,     n)\n    prevscore = fill(1. / n, n)\n    ratio     = [d / outdegree(g, i) for i = 1:n]\n    maxdiff   = 1.\n    @inbounds while maxdiff > eps\n        for i = 1:n                    # transfer the scores\n            score[i] = 0.\n            for j = inneighbors(g, i)\n                score[i] += prevscore[j] * ratio[j]\n            end\n        end\n        leak = (1. - sum(score)) / n    # put the leaked scores back\n        maxdiff = 0.\n        for i = 1:n\n            score[i] += leak\n            maxdiff = max(maxdiff, abs(score[i] - prevscore[i]))\n        end\n        prevscore, score = score, prevscore\n    end\n    return prevscore\nend\n", "meta": {"hexsha": "e65558caa83a368772a5274eb442f0d320bcc1e4", "size": 3161, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/measure/centrality/power_iter.jl", "max_stars_repo_name": "inguar/Junet.jl", "max_stars_repo_head_hexsha": "168d8e4b6c8f6473cec336d0e29bd3926bfe3305", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2017-05-21T18:22:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T20:21:47.000Z", "max_issues_repo_path": "src/measure/centrality/power_iter.jl", "max_issues_repo_name": "inguar/Junet.jl", "max_issues_repo_head_hexsha": "168d8e4b6c8f6473cec336d0e29bd3926bfe3305", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-06-06T19:01:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-09T17:07:01.000Z", "max_forks_repo_path": "src/measure/centrality/power_iter.jl", "max_forks_repo_name": "inguar/Junet.jl", "max_forks_repo_head_hexsha": "168d8e4b6c8f6473cec336d0e29bd3926bfe3305", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-04-26T08:13:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-17T02:55:09.000Z", "avg_line_length": 32.9270833333, "max_line_length": 109, "alphanum_fraction": 0.5621638722, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706048, "lm_q2_score": 0.8244619199068832, "lm_q1q2_score": 0.7582102414354939}}
{"text": "function assemble_system!(u, problem::FDGZProblem{TBC, TBC}) where {TBC<:DirichletBC}\n\n\n    problem.F[1] =problem.ϵ * (u[2] - 2*u[1] + problem.left_bc.u_bc)/problem.Δx^2 +  u[1] * (1-u[1]^2);\n\n    for i in 2:problem.n-1\n        problem.F[i]= problem.ϵ * (u[i+1] - 2*u[i] +u[i-1])/problem.Δx^2 +u[i] * (1-u[i]^2);\n    end\n    problem.F[end] = problem.ϵ * (problem.right_bc.u_bc - 2*u[end] + u[end-1])/problem.Δx^2 +  u[end] * (1-u[end]^2);\n\n    problem\nend\n", "meta": {"hexsha": "be09ce0652c754f3b9277c39c6f3ec9db68e7c40", "size": 456, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "GZBVP1D/src/assembly.jl", "max_stars_repo_name": "liamfdoherty/Math_540_2021", "max_stars_repo_head_hexsha": "6b84b88ca1c587650a82f5bc9351f27a518e104d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GZBVP1D/src/assembly.jl", "max_issues_repo_name": "liamfdoherty/Math_540_2021", "max_issues_repo_head_hexsha": "6b84b88ca1c587650a82f5bc9351f27a518e104d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GZBVP1D/src/assembly.jl", "max_forks_repo_name": "liamfdoherty/Math_540_2021", "max_forks_repo_head_hexsha": "6b84b88ca1c587650a82f5bc9351f27a518e104d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0769230769, "max_line_length": 117, "alphanum_fraction": 0.5745614035, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9559813513911655, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7581945036843319}}
{"text": "function f(x::Real, σ::Real, μ::Real)\n    return exp(-0.5((x-μ)/σ)^2) / (σ * sqrt(2π))\nend\n\nf(σ::Real, μ::Real) = x -> f(x, σ, μ)\n\nsurface(range::AbstractRange; σ=1, μ=0) = f(σ, μ).(range) * f(σ, μ).(range)'\n", "meta": {"hexsha": "00aab3fbbe8e0bb709ead60056c457aecf155be4", "size": 208, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SurfaceGenerator/src/generator.jl", "max_stars_repo_name": "foldfelis/Replotter", "max_stars_repo_head_hexsha": "8afdeaa2a172005fb9ef7806d96d012836130dee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SurfaceGenerator/src/generator.jl", "max_issues_repo_name": "foldfelis/Replotter", "max_issues_repo_head_hexsha": "8afdeaa2a172005fb9ef7806d96d012836130dee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SurfaceGenerator/src/generator.jl", "max_forks_repo_name": "foldfelis/Replotter", "max_forks_repo_head_hexsha": "8afdeaa2a172005fb9ef7806d96d012836130dee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0, "max_line_length": 76, "alphanum_fraction": 0.5288461538, "num_tokens": 93, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9559813538993888, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7581945033361344}}
{"text": "#  Unit \"QnLogLike.jl\" of the Diagonalization.jl Package for Julia language\n#\n#  MIT License\n#  Copyright (c) 2020-2021,\n#  Marco Congedo°, Ronald Phlypo, CNRS, UGA, Grenoble-INP, France\n#  Alexandre Gramfort¨, INRIA, U. Paris Saclay, France\n#  ° https://sites.google.com/site/marcocongedo/\n#  ¨ http://alexandre.gramfort.net/\n\n# ? CONTENTS :\n#  Quasi-Newton Approximate Joint Diagonalization (AJD) algorithm of:\n#  P. Ablin, J.F. Cardoso and A. Gramfort. Beyond Pham's algorithm\n#  for joint diagonalization. Proc. ESANN 2019.\n#  https://hal.archives-ouvertes.fr/hal-01936887v1\n#\n#  Code adapted in Julia from Python code provided from the authors at:\n#  https://github.com/pierreablin/qndiag/blob/master/qndiag/qndiag.py\n#\n#  NOTATION\n#  lower-case letter: a scalar, e.g.: a\n#  Upper case letter: a matrix, e.g., A\n#  Bold lover case letter: a vector of matrices, e.g., 𝐀\n#\n#  ADVANCED QnLogLike algorithm (no PRIMITIVE version is available):\n#  The algorithm takes as input a vector of k real symmetric matrices\n#  𝐂 and find a non-singular matrix B such that the congruences\n#  B'*𝐂_κ*B are as diagonal as possible for all κ=1:k.\n#\n#  `w` is an optional vector of k positive weights for each matrix in 𝐂.\n#  if `w` is different from `nothing` (default), the input matrices are\n#  weighted with these weights.\n#  A function can be passed as the `w` argument, in which case the kth weight\n#  is found as the output of the function applied to the kth matrix in 𝐂.\n#  A good choice in general is the `nonD` function declared in tools.jl unit.\n#\n#  if `whitening` = true is passed, the Jeffrey mean of the matrices in 𝐂 is\n#  computed (using the PosDefManifold.jl package) and the matrices in 𝐂\n#  are pre-transformed using the whitening matrix of the mean.\n#  Dimensionality reduction can be obtained at this stage using optional\n#  arguments `eVar` and `eVarMeth` (see documentation of the AJD constructors).\n#\n#  if `sort`=true (default) the column vectors of the B matrix are normalized\n#  to unit norm and permuted so as to sort in descending order the mean over\n#  κ=1:k of the diagonal elements of B'*𝐂_κ*B.\n#  Note that if `whitening` is true the output B will not have unit norm\n#  columns, as it is multiplied by the whitener after being scaled and sorted\n#  and before being returned.\n#\n#  if  `whitening` = false (default), a matrix can be provided with the `init`\n#  argument in order to initialize B. In this case the actual AJD\n#  will be given by init*B, where B is the output of the algorithm.\n#\n#  `tol` is the convergence to be attained. It defaults to 1e-6.\n#\n#  `maxiter` is the maximum number of iterations allowed. It defaults to 1000.\n#\n#  `𝜆min` is used to reguarize Hessian coefficients; all coefficients smaller\n#  than 𝜆min  will be set to 𝜆min. It defauts tp 1e-4.\n#\n#  `lsmax` is the maximum number of steps in the line search. It defaults to 10.\n#\n#  if `verbose`=true, the convergence attained at each iteration and other\n#  information will be printed.\n#\n#  if `threaded` is true, the algorithm runs in multi-threaded mode.\n#  By default this is activated if the number of threads Julia is instructed\n#  to use is higher than 1 and if the number of matrices in 𝐂 is higher than\n#  twice the number of threads julia is instructed to use. For small matrices\n#  and/or small number of matrices, setting threaded to false may result\n#  in better performances in term of speed.\n#\n#  return a 5-tuple holding: B, its pseudo-inverse,\n# \t\tthe mean diagonal elements of B'*mean(𝐂)*B,\n#       the number of iterations and the convergence attained.\n#\n#  Note on the implementation:\n#  GRADIENT:\n#  D_1,...,D_n are the matrices in 𝐃;\n#  the jth column in D_i is divided by D_i[j, j],\n#  the mean of these matrices is then taken and finally\n#  the identity is subtracted\n#\n#  HESSIAN COEFFICIENTS\n#  for each COLUMN vector dg_1,...,dg_n\n#  (the diagonal part of the n matrices in 𝐃)\n#  we form a m·m matrix stacking vertically m copies of these vectors\n#  transposed and dividing each of them by the mth element, as\n#   _                   _\n#  |  (dg_i)'/dg_i[1]   |\n#  |  (dg_i)'/dg_i[...] |\n#  |  (dg_i)'/dg_i[m]   |\n#  _                   _\n#  finally we take the mean of all the n matrices created in this way.\n\n\n# function to get the weights from argment `w`\nfunction _qnlogLikeWeights!(w, 𝐂)\n\tif w isa Function w=[w(C) for C∈𝐂] end\n\treturn w./mean(w)\nend\n\nfunction qnLogLike( 𝐂::Union{Vector{Hermitian}, Vector{Symmetric}};\n\t\t\t\tw           :: \tTwf   = ○,\n\t\t\t\tpreWhite    :: \tBool = false,\n\t\t\t\tsort        :: \tBool = true,\n\t\t\t\tinit        :: \tUnion{Matrix, Nothing} = ○,\n\t\t\t\ttol         :: \tReal = 1e-6,\n\t\t\t\tmaxiter     :: \tInt  = 1000,\n\t\t\t\t𝜆min        ::\t Real = 1e-4,\n\t\t\t\tlsmax       :: \tInt  = 10,\n\t\t\t\tverbose     :: \tBool = false,\n\t\t\t\tthreaded\t:: \tBool =\n\t\t\t\t\t\t\tbegin\n\t\t\t\t\t\t\t\tthr = Threads.nthreads()\n\t\t\t\t\t\t\t\tlength(𝐂) ≥ 2*thr && thr>1\n\t\t\t\t\t\t\tend,\n\t\t\teVar     :: TeVaro = ○,\n\t\t\teVarMeth :: Function = searchsortedfirst)\n\n\t# # # # # # # # #  internal functions\n\t# half sum of mean of log of Diagonals\n\thsmld(𝐀) = 0.5*sum(mean(log, [𝔻(A) for A ∈ 𝐀]))\n\thsmld(𝐀, 𝛎) = 0.5*sum(mean(log, [𝔻(A)*ν for (A, ν) ∈ zip(𝐀, 𝛎)]))\n\n\t# minus log abs det\n\tmlad(A) = -logabsdet(A)[1]\n\n\t# line search: update B and 𝐃\n\t@inline function _linesearch!(B, B₊, M, 𝐃, 𝐃₊, 𝒟, 𝐯, loss, lsmax)\n\t    for i ∈ 1:lsmax\n\t        M[:] = (1.0/i * 𝒟) + I\n\t\t\tB₊[:] = B * M\n\t\t\t### 𝐃₊ = [Hermitian(M'*D*M) for D in 𝐃]\n\t\t\t@threads for j ∈ eachindex(𝐃) 𝐃₊[j] = Hermitian(M'*𝐃[j]*M) end\n\t\t\t### iter>2 && (loss₊ = w===○ ? mlad(B₊)+hsmld(𝐃₊) : mlad(B₊)+hsmld(𝐃₊, 𝐯))\n\t\t\tloss₊ = w===○ ? mlad(B₊)+hsmld(𝐃₊) : mlad(B₊)+hsmld(𝐃₊, 𝐯)\n\t        loss₊ < loss && break\n\t    end\n\t\tB[:] = B₊\n\t\t𝐃[:] = 𝐃₊\n\t    return loss₊\n\tend\n\t# # # # # # # # #\n\n\t# pre-whiten or initialize or nothing\n\tW, 𝐃 = _preWhiteOrInit(𝐂, preWhite, Jeffrey, eVar, eVarMeth, init, :Hvector)\n\t𝐯 = w===○ ? ○ : _qnlogLikeWeights!(w, 𝐂) # if w is `nonD` function, apply it to the original input 𝐂\n\n\t# set variables\n\titer, conv, 😋, sqrtn, loss₊ = 1, Inf, false, √size(𝐃[1], 1), Inf\n\tB, ⩫ = Matrix{eltype(𝐃[1])}(I, size(𝐃[1])), similar\n\tB₊, 𝒟, M, ∇, ℌ, 𝐃₊ = ⩫(B), ⩫(B), ⩫(B), ⩫(B), ⩫(B), ⩫(𝐃)\n\t𝕯 = [zeros(eltype(𝐃[1]), size(𝐃[1], 1)) for i = 1:length(𝐃)]\n\tloss = w===○ ? \thsmld(𝐃) : hsmld(𝐃, 𝐯) #loss = Inf\n\n\tverbose && println(\"Iterating quasi-Newton LogLike algorithm...\")\n\twhile true\n\t\tfor j ∈ eachindex(𝐃) 𝕯[j] = diag(𝐃[j]) end\n\t    #𝕯 = [diag(D) for D ∈ 𝐃]\n\n\t    # gradient\n\t\tw===○ ? ∇[:] = mean(D./𝔡 for (D, 𝔡) ∈ zip(𝐃, 𝕯)) - I :\n\t\t\t\t∇[:] = mean(v.*(D./𝔡) for (v, D, 𝔡) ∈ zip(𝐯, 𝐃, 𝕯)) - I\n\t    conv = norm(∇)/sqrtn # relative norm of ∇ with respect to the identity : ||∇-I||/||I||\n\n\t    verbose && println(\"iteration: \", iter, \"; convergence: \", conv)\n\t    (overRun = iter > maxiter) && @warn(\"qnLogLike: reached the max number of iterations before convergence:\", iter-1)\n\t    (😋 = conv <= tol) || overRun==true ? break : iter += 1\n\n\t\t# Hessian Coefficients\n\t\tw===○ ? ℌ[:] = mean(𝔡'./𝔡 for 𝔡 ∈ 𝕯) :\n\t\t\t\tℌ[:] = mean(v.*(𝔡'./𝔡) for (v, 𝔡) ∈ zip(𝐯, 𝕯))\n\n\t\t# Quasi-Newton Direction 𝒟\n\t    𝒟[:] = -(∇' .* ℌ - ∇)./replace(x -> x<𝜆min ? 𝜆min : x, @. (ℌ'*ℌ) - 1.)\n\n\t    loss = _linesearch!(B, B₊, M, 𝐃, 𝐃₊, 𝒟, 𝐯, loss, lsmax) # Line Search\n\tend\n\tverbose && @info(\"Convergence has \"*(😋 ? \"\" : \"not \")*\"been attained.\\n\\n\")\n\n\t# scale and permute the vectors of B\n\tλ = sort ? _permute!(_scale!(B, mean(𝔻(D) for D ∈ 𝐃), size(𝐃[1], 1))...) :\n\t            diag(mean(𝔻(D) for D ∈ 𝐃))\n\n\treturn preWhite ? (W.F*B, pinv(B)*W.iF, λ, iter, conv) :\n\t                  (B, pinv(B), λ, iter, conv)\nend\n", "meta": {"hexsha": "4aec17f00bd5cac14bf45d4ccb34c5db93c9b36d", "size": 7526, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/optim/QnLogLike.jl", "max_stars_repo_name": "Marco-Congedo/Diagonalizations.jl", "max_stars_repo_head_hexsha": "135473ab7ee9926cb25ac135aadc79e4c716d422", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2020-01-02T05:10:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T02:16:04.000Z", "max_issues_repo_path": "src/optim/QnLogLike.jl", "max_issues_repo_name": "Marco-Congedo/Diagonalizations.jl", "max_issues_repo_head_hexsha": "135473ab7ee9926cb25ac135aadc79e4c716d422", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2020-01-01T19:37:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-26T10:38:14.000Z", "max_forks_repo_path": "src/optim/QnLogLike.jl", "max_forks_repo_name": "Marco-Congedo/Diagonalizations.jl", "max_forks_repo_head_hexsha": "135473ab7ee9926cb25ac135aadc79e4c716d422", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:20:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T09:32:27.000Z", "avg_line_length": 40.0319148936, "max_line_length": 119, "alphanum_fraction": 0.6283550359, "num_tokens": 2799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7581885602598342}}
{"text": "# functions related to normal distribution\n\nfunction xval(μ::Real, σ::Real, z::Number)\n    if isinf(z) && iszero(σ)\n        μ + one(σ) * z\n    else\n        μ + σ * z\n    end\nend\nzval(μ::Real, σ::Real, x::Number) = (x - μ) / σ\n\n# pdf\nnormpdf(z::Number) = exp(-abs2(z)/2) * invsqrt2π\nfunction normpdf(μ::Real, σ::Real, x::Number)\n    if iszero(σ)\n        if x == μ\n            z = zval(μ, one(σ), x)\n        else\n            z = zval(μ, σ, x)\n            σ = one(σ)\n        end\n    else\n        z = zval(μ, σ, x)\n    end\n    normpdf(z) / σ\nend\n\n# logpdf\nnormlogpdf(z::Number) = -(abs2(z) + log2π)/2\nfunction normlogpdf(μ::Real, σ::Real, x::Number)\n    if iszero(σ)\n        if x == μ\n            z = zval(μ, one(σ), x)\n        else\n            z = zval(μ, σ, x)\n            σ = one(σ)\n        end\n    else\n        z = zval(μ, σ, x)\n    end\n    normlogpdf(z) - log(σ)\nend            \n\n# cdf\nnormcdf(z::Number) = erfc(-z * invsqrt2)/2\nfunction normcdf(μ::Real, σ::Real, x::Number)\n    if iszero(σ) && x == μ\n        z = zval(zero(μ), σ, one(x))\n    else        \n        z = zval(μ, σ, x)        \n    end\n    normcdf(z)\nend\n# ccdf\nnormccdf(z::Number) = erfc(z * invsqrt2)/2\nfunction normccdf(μ::Real, σ::Real, x::Number)\n    if iszero(σ) && x == μ\n        z = zval(zero(μ), σ, one(x))\n    else        \n        z = zval(μ, σ, x)        \n    end\n    normccdf(z)\nend\n\n# logcdf\nnormlogcdf(z::Number) = z < -1.0 ?\n    log(erfcx(-z * invsqrt2)/2) - abs2(z)/2 :\n    log1p(-erfc(z * invsqrt2)/2)\nfunction normlogcdf(μ::Real, σ::Real, x::Number)\n    if iszero(σ) && x == μ\n        z = zval(zero(μ), σ, one(x))\n    else        \n        z = zval(μ, σ, x)        \n    end\n    normlogcdf(z)\nend\n\n# logccdf\nnormlogccdf(z::Number) = z > 1.0 ?\n    log(erfcx(z * invsqrt2)/2) - abs2(z)/2 :\n    log1p(-erfc(-z * invsqrt2)/2)\nfunction normlogccdf(μ::Real, σ::Real, x::Number)\n    if iszero(σ) && x == μ\n        z = zval(zero(μ), σ, one(x))\n    else        \n        z = zval(μ, σ, x)        \n    end\n    normlogccdf(z)\nend\n\nnorminvcdf(p::Real) = -erfcinv(2*p) * sqrt2\nnorminvcdf(μ::Real, σ::Real, p::Real) = xval(μ, σ, norminvcdf(p))\n\nnorminvccdf(p::Real) = erfcinv(2*p) * sqrt2\nnorminvccdf(μ::Real, σ::Real, p::Real) = xval(μ, σ, norminvccdf(p))\n\n# invlogcdf. Fixme! Support more precisions than Float64\nnorminvlogcdf(lp::Union{Float16,Float32}) = convert(typeof(lp), _norminvlogcdf_impl(Float64(lp)))\nnorminvlogcdf(lp::Real) = _norminvlogcdf_impl(Float64(lp))\nnorminvlogcdf(μ::Real, σ::Real, lp::Real) = xval(μ, σ, norminvlogcdf(lp))\n\n# invlogccdf. Fixme! Support more precisions than Float64\nnorminvlogccdf(lp::Union{Float16,Float32}) = convert(typeof(lp), -_norminvlogcdf_impl(Float64(lp)))\nnorminvlogccdf(lp::Real) = -_norminvlogcdf_impl(Float64(lp))\nnorminvlogccdf(μ::Real, σ::Real, lp::Real) = xval(μ, σ, norminvlogccdf(lp))\n\n\n# norminvcdf & norminvlogcdf implementation\n#\n#   Rational approximations for the inverse cdf and its logarithm, from:\n#\n#   Wichura, M.J. (1988) Algorithm AS 241: The Percentage Points of the Normal Distribution\n#   Journal of the Royal Statistical Society. Series C (Applied Statistics), Vol. 37, No. 3, pp. 477-484\n#\n\nfunction _norminvlogcdf_impl(lp::Float64)\n    if isfinite(lp) && lp < 0.0\n        q = exp(lp) - 0.5\n        # qnorm_kernel(lp, q, true)\n        if abs(q) <= 0.425\n            _qnorm_ker1(q)\n        else\n            r = sqrt(q < 0 ? -lp : -log1mexp(lp))\n            return copysign(_qnorm_ker2(r), q)\n        end\n    elseif lp >= 0.0\n        lp == 0.0 ? Inf : NaN\n    else # lp is -Inf or NaN\n        lp\n    end\nend\n\nfunction _qnorm_ker1(q::Float64)\n    # pre-condition: abs(q) <= 0.425\n    r = 0.180625 - q*q\n    return q * @horner(r,\n                       3.38713_28727_96366_6080e0,\n                       1.33141_66789_17843_7745e2,\n                       1.97159_09503_06551_4427e3,\n                       1.37316_93765_50946_1125e4,\n                       4.59219_53931_54987_1457e4,\n                       6.72657_70927_00870_0853e4,\n                       3.34305_75583_58812_8105e4,\n                       2.50908_09287_30122_6727e3) /\n    @horner(r,\n            1.0,\n            4.23133_30701_60091_1252e1,\n            6.87187_00749_20579_0830e2,\n            5.39419_60214_24751_1077e3,\n            2.12137_94301_58659_5867e4,\n            3.93078_95800_09271_0610e4,\n            2.87290_85735_72194_2674e4,\n            5.22649_52788_52854_5610e3)\nend\n\nfunction _qnorm_ker2(r::Float64)\n    if r < 5.0\n        r -= 1.6\n        @horner(r,\n                1.42343_71107_49683_57734e0,\n                4.63033_78461_56545_29590e0,\n                5.76949_72214_60691_40550e0,\n                3.64784_83247_63204_60504e0,\n                1.27045_82524_52368_38258e0,\n                2.41780_72517_74506_11770e-1,\n                2.27238_44989_26918_45833e-2,\n                7.74545_01427_83414_07640e-4) /\n        @horner(r,\n                1.0,\n                2.05319_16266_37758_82187e0,\n                1.67638_48301_83803_84940e0,\n                6.89767_33498_51000_04550e-1,\n                1.48103_97642_74800_74590e-1,\n                1.51986_66563_61645_71966e-2,\n                5.47593_80849_95344_94600e-4,\n                1.05075_00716_44416_84324e-9)\n    else\n        r -= 5.0\n        @horner(r,\n                6.65790_46435_01103_77720e0,\n                5.46378_49111_64114_36990e0,\n                1.78482_65399_17291_33580e0,\n                2.96560_57182_85048_91230e-1,\n                2.65321_89526_57612_30930e-2,\n                1.24266_09473_88078_43860e-3,\n                2.71155_55687_43487_57815e-5,\n                2.01033_43992_92288_13265e-7) /\n        @horner(r,\n                1.0,\n                5.99832_20655_58879_37690e-1,\n                1.36929_88092_27358_05310e-1,\n                1.48753_61290_85061_48525e-2,\n                7.86869_13114_56132_59100e-4,\n                1.84631_83175_10054_68180e-5,\n                1.42151_17583_16445_88870e-7,\n                2.04426_31033_89939_78564e-15)\n    end\nend\n", "meta": {"hexsha": "7461dcf8f61f479e02dd2f9517a02296ee673427", "size": 5987, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distrs/norm.jl", "max_stars_repo_name": "mileslucas/StatsFuns.jl", "max_stars_repo_head_hexsha": "d99fdf43d40a70ca7a688e11afba1a84963eb396", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 190, "max_stars_repo_stars_event_min_datetime": "2015-07-26T02:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T02:30:17.000Z", "max_issues_repo_path": "src/distrs/norm.jl", "max_issues_repo_name": "mileslucas/StatsFuns.jl", "max_issues_repo_head_hexsha": "d99fdf43d40a70ca7a688e11afba1a84963eb396", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 110, "max_issues_repo_issues_event_min_datetime": "2015-08-18T16:34:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T17:36:11.000Z", "max_forks_repo_path": "src/distrs/norm.jl", "max_forks_repo_name": "mileslucas/StatsFuns.jl", "max_forks_repo_head_hexsha": "d99fdf43d40a70ca7a688e11afba1a84963eb396", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 50, "max_forks_repo_forks_event_min_datetime": "2015-08-06T14:28:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T22:28:36.000Z", "avg_line_length": 30.0854271357, "max_line_length": 104, "alphanum_fraction": 0.5525304827, "num_tokens": 2280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632856092016, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7581885586562297}}
{"text": "include(\"../interfaces.jl\")\n\nimport PhysicalConstants.CODATA2018 as Constants # this must be moved at a high level in the package to standardize use\n\n### Boundary conditions\nfunction Temperature(;name,T=273.15)\n    val = T\n    @parameters T # how to give default parameters. how to give default to variables\n\n    @named port = HeatPort()\n\n    eqs = \n    [\n        port.T ~ T\n    ]\n    ODESystem(eqs, t, [], [T], systems=[port], name=name)\nend\n\n### Resistance Models\n# how to have the similar effect as extend PartialResistance to avoid code rewrite\nfunction Sphere(;name, r_inner = 0.01, r_outer=1.0, lambda=5.0)\n    val0 = r_inner # don't understand why there \"val*\" are required for parameters with default values\n    val1 = r_outer\n    val2 = lambda\n    @variables R(t)\n    @parameters r_inner, r_outer, lambda\n\n    @named port_a = HeatPort()\n    @named port_b = HeatPort()\n\n    eqs =\n    [\n        0 ~ port_a.Q_flow + port_b.Q_flow\n        port_a.Q_flow ~ (port_a.T - port_b.T)/R\n        R ~ 1/(4*3.14159*lambda)*(1/r_inner - 1/r_outer)\n    ]\n    ODESystem(eqs, t, [R], [r_inner, r_outer, lambda], systems=[port_a, port_b], name=name)\nend\n\nfunction Convection(;name, surfaceArea = 0.01, alpha=1000.0)\n    val0 = surfaceArea\n    val1 = alpha\n    @variables R(t)\n    @parameters surfaceArea, alpha\n\n    @named port_a = HeatPort()\n    @named port_b = HeatPort()\n\n    eqs =\n    [\n        0 ~ port_a.Q_flow + port_b.Q_flow\n        port_a.Q_flow ~ (port_a.T - port_b.T)/R\n        R ~ 1/(alpha*max(eps(),surfaceArea))\n    ]\n    ODESystem(eqs, t, [R], [surfaceArea, alpha], systems=[port_a, port_b], name=name)\nend\n\nfunction Contact(;name, surfaceArea = 0.01, Rc_pp=1.0)\n    val0 = surfaceArea\n    val1 = Rc_pp\n    @variables R(t)\n    @parameters surfaceArea, Rc_pp\n\n    @named port_a = HeatPort()\n    @named port_b = HeatPort()\n\n    eqs =\n    [\n        0 ~ port_a.Q_flow + port_b.Q_flow\n        port_a.Q_flow ~ (port_a.T - port_b.T)/R\n        R ~ Rc_pp/max(eps(),surfaceArea)\n    ]\n    ODESystem(eqs, t, [R], [surfaceArea, Rc_pp], systems=[port_a, port_b], name=name)\nend\n\nfunction Radiation(;name, surfaceArea = 0.01, epsilon=1.0)\n    val0 = surfaceArea\n    val1 = epsilon\n    @variables R(t)\n    @parameters surfaceArea, epsilon\n\n    @named port_a = HeatPort()\n    @named port_b = HeatPort()\n\n    eqs =\n    [\n        0 ~ port_a.Q_flow + port_b.Q_flow\n        port_a.Q_flow ~ (port_a.T - port_b.T)/R\n        R ~ 1/(surfaceArea*5.6703744E-8*epsilon*(port_a.T^2+port_b.T^2)*(port_a.T + port_b.T))\n    ]\n # exact: R ~ 1/(surfaceArea*5.6703744E-8*epsilon*(port_a.T^2+port_b.T^2)*(port_a.T + port_b.T))\n # approximate: R ~ 1/(4*surfaceArea*5.6703744E-8*epsilon*(0.5*(port_a.T + port_b.T))^3)\n    # seems to be having issues :(\n\n    # using \"Constants.StefanBoltzmannConstant\" causes Unitful error\n    ODESystem(eqs, t, [R], [surfaceArea, epsilon], systems=[port_a, port_b], name=name)\nend\n", "meta": {"hexsha": "c11de1e7fb7b43666b6241f5c5fde91772854279", "size": 2882, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "TRANSFORM - ModelingToolkit/HeatAndMassTransfer/Resistances/heat.jl", "max_stars_repo_name": "greenwoodms06/TRANSFORM-Julia", "max_stars_repo_head_hexsha": "8278099d745e7ed4c775e6173eca66e9bf9ee7ea", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TRANSFORM - ModelingToolkit/HeatAndMassTransfer/Resistances/heat.jl", "max_issues_repo_name": "greenwoodms06/TRANSFORM-Julia", "max_issues_repo_head_hexsha": "8278099d745e7ed4c775e6173eca66e9bf9ee7ea", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TRANSFORM - ModelingToolkit/HeatAndMassTransfer/Resistances/heat.jl", "max_forks_repo_name": "greenwoodms06/TRANSFORM-Julia", "max_forks_repo_head_hexsha": "8278099d745e7ed4c775e6173eca66e9bf9ee7ea", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4081632653, "max_line_length": 119, "alphanum_fraction": 0.6370575989, "num_tokens": 912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7581885586185512}}
{"text": "\"\"\"\nImport packages and files\n\"\"\"\nimport Pkg\nPkg.activate(@__DIR__)\nPkg.instantiate()\n\n@info(\"Loading Packages...\")\nusing Zygote, LinearAlgebra, Random\nusing Flux\nusing Random\nusing Plots\n\ninclude(\"bayes_nn.jl\")\n\"\"\"\nclass_data.jl contains the data of the example\nfor Bayesian Neural Network with Turing language from Turinglang\n    https://turing.ml/dev/tutorials/3-bayesnn/.\n\"\"\"\ninclude(\"turing_data.jl\")    #\nplot_data()\n\nX = hcat(xs...)\nY = hcat(ts...)\n\n\"\"\"\nSet up a bnn for classification. The architecture and standard deviation are the\nsame as in the example of Turing in order to ensure correctness of the algorithm.\n\"\"\"\n# Create a regularization term and a Gaussain prior variance term.\nalpha = 0.09\nsig = sqrt(1.0 / alpha)\n\n\"\"\" NNet with 2 input units, 3 units in 1st hidden layer,\n2 units in 2nd hidden layer and 1 output unit and their correpsonding\nactivation function.\n\"\"\"\nffnet = network([2, 3, 2, 1], [identity, tanh, tanh, sigmoid])\n\n\"\"\"\nSample from the posterior distribution using Hamiltonian Monte Carlo.\n\"\"\"\nfunction main(net::network, X, Y, prior_sigma, maxiter, burnin)\n    # matrices to store mcmc results\n    sampled_weights = []\n    sampled_bias = []\n    lp = zeros(maxiter)\n\n    for its in 1:maxiter\n        hmc_bnn!(net, X, Y, prior_sigma, 0.05, 4)\n        lp[its] = log_posterior(net, X, Y, prior_sigma)\n        if its > burnin\n            push!(sampled_weights, net.weights)\n            push!(sampled_bias, net.biases)\n        end\n        if mod(its, 100) == 0\n            println(\"HMC iterations: $its\")\n        end\n    end\n\n    return sampled_weights, sampled_bias, lp\nend\n\nRandom.seed!(12345)\n@time sampled_weights, sampled_bias, lp = main(ffnet, X, Y, sig, 5000, 1000)\n\n# define test set\nx_range = collect(range(-6,stop=6,length=25))\ny_range = collect(range(-6,stop=6,length=25))\n\n\"\"\"\nVisualise the results\n\"\"\"\nn_end = 4000\nanim = @gif for i=1:100:n_end\n    plot_data();\n    bnn_posterior!(ffnet, sampled_weights[i], sampled_bias[i])\n    Z = [nn_forward(ffnet, [x, y]) for x=x_range, y=y_range]\n    contour!(x_range, y_range, cell2array(Z), title=\"Iteration $i\", clim = (0,1));\nend every 10;\n\n\n_, idx = findmax(lp)\nbnn_posterior!(ffnet, sampled_weights[idx], sampled_bias[idx])\nZ = [nn_forward(ffnet, [x, y]) for x=x_range, y=y_range]\nplot_data()\ncontour!(x_range, y_range, cell2array(Z))\n", "meta": {"hexsha": "b464a233a790ff2ecc4d1e980b908154665116d9", "size": 2322, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example.jl", "max_stars_repo_name": "cmerkatas/bayes_nn", "max_stars_repo_head_hexsha": "2f1934e4cfb52dd200197b32f8f9bb1b85c0e299", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example.jl", "max_issues_repo_name": "cmerkatas/bayes_nn", "max_issues_repo_head_hexsha": "2f1934e4cfb52dd200197b32f8f9bb1b85c0e299", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example.jl", "max_forks_repo_name": "cmerkatas/bayes_nn", "max_forks_repo_head_hexsha": "2f1934e4cfb52dd200197b32f8f9bb1b85c0e299", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3863636364, "max_line_length": 82, "alphanum_fraction": 0.6838931955, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7581885516336786}}
{"text": "# #TODO: finish\n# function hilbert_transform(x::Array{T}; n::Int=10)\n# end\n\nfunction estimate_rsrange(x::Array{T})::T where T<:Real\n    n = size(x,1)\n    @assert n>2 \"need more than two elements, have $x\"\n    m = sum(x)/n\n    y = x .- m\n    z = cumsum(y)\n    r = maximum(z) - minimum(z)\n    s = sqrt(sum((x.-m).^2)/n)\n    return r/s\nend\n\nfunction npieces(x::Array{T}; minsize::Int=8)::Int where {T<:Real}\n    i = 0\n    n = size(x,1)\n    while n > minsize\n        i += 1\n        n = fld(n, 2)\n    end\n    return i\nend\n\nfunction genrsdata(x::Array{T})::Matrix{T} where {T<:Real}\n    depth = npieces(x)\n    if depth == 0\n        return [size(x,1) estimate_rsrange(x)]\n    end\n    rsdata = zeros(0,2)\n    rsdata = [rsdata; [size(x,1) estimate_rsrange(x)]]\n    a, b = divide(x)\n    rsdata = [rsdata; genrsdata(a)]\n    rsdata = [rsdata; genrsdata(b)]\n    return rsdata\nend\n\nfunction divide(x::A)::Tuple{A, A} where {A<:AbstractArray}\n    n = size(x,1)\n    @assert n>=2\n    h = n/2\n    a = x[1:floor(Int,h)]\n    if floor(h) == h\n        b = x[(ceil(Int,h)+1):end]\n    else\n        b = x[ceil(Int,h):end]\n    end\n    return a, b\nend\n\nfunction estimate_hurst(x::Array{T}; intercept::Bool=false)::T where {T<:Real}\n    RS = genrsdata(x)\n    RS = RS[sortperm(RS[:,1]),:]\n    xx = log2.(RS[:,1])\n    yy = log2.(RS[:,2])\n    if intercept\n        _, beta = [ones(size(xx)) xx]\\yy\n    else\n        beta = xx\\yy\n    end\n    return beta\nend\n\n\"\"\"\n```\nrsrange(x::Array{T}; n::Int=100, cumulative::Bool=false, intercept::Bool=true)\n```\n\nCompute the rescaled range of a time series\n\"\"\"\nfunction rsrange(x::Array{T}; n::Int=100, cumulative::Bool=false, intercept::Bool=true) where {T<:Real}\n    @assert size(x,1) >= n\n    return runfun(x, estimate_rsrange; n=n, cumulative=cumulative)\nend\n\n\"\"\"\n```\nhurst(x::Array{T}; n::Int=100, cumulative::Bool=false, intercept::Bool=false)\n```\n\nCompute the Hurst exponent of a time series\n\"\"\"\nfunction hurst(x::Array{T}; n::Int=100, cumulative::Bool=false, intercept::Bool=false) where {T<:Real}\n    @assert size(x,1) >= n\n    return runfun(x, estimate_hurst; n=n, cumulative=cumulative, intercept=intercept)\nend\n", "meta": {"hexsha": "8bc25d1bc55b8ae77443b55eed63ee42f0976ee1", "size": 2127, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chaos.jl", "max_stars_repo_name": "mrchaos/Indicators.jl", "max_stars_repo_head_hexsha": "970ccbb424277cfdbf0d0c893b5dc4fa7e702c08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/chaos.jl", "max_issues_repo_name": "mrchaos/Indicators.jl", "max_issues_repo_head_hexsha": "970ccbb424277cfdbf0d0c893b5dc4fa7e702c08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chaos.jl", "max_forks_repo_name": "mrchaos/Indicators.jl", "max_forks_repo_head_hexsha": "970ccbb424277cfdbf0d0c893b5dc4fa7e702c08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1704545455, "max_line_length": 103, "alphanum_fraction": 0.5937940762, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.758188547931372}}
{"text": "# ==============================================================================\n# Xavier Gandibleux - November 2021\n#   Implemented in Julia 1.6\n\n# ==============================================================================\n# Parser of MO-MKP instances generated by E. Zitzler and M. Laumanns available at\n# https://sop.tik.ee.ethz.ch/download/supplementary/testProblemSuite/?page=testProblem.php#source\n#\n#   NB1: Number of objectives = number of constraints\n#   NB2: All coefficients P, W are integer, all variables are binary\n#   NB3: All coefficients ω are floored to the integer\n\n# ==============================================================================\n# Datastructure of a multi-objective multi-dimensionnal KP with 0/1 variables\nstruct _MOMKP\n    P  :: Matrix{Int} # profit of items for the objectives, k=1..p, j=1..n\n    W  :: Matrix{Int} # weight of items for the constraints, i=1..m, j=1..n\n    ω  :: Vector{Int} # capacity of knapsacks, i=1..m\nend\n\n# ==============================================================================\nfunction readInstanceMOMKPformatZL(verbose::Bool, fname::String)\n\n    f=open(fname)\n        lines = readlines(f)\n    close(f)\n\n    # Extract the problem dimensions from the file name ------------------------\n    line=(split(fname,\".\"))\n    #line = split(lines[1],\" \")\n    m = parse(Int, line[3])\n    p = m\n    n = parse(Int, line[2])\n    momkp = _MOMKP(zeros(Int,p,n),zeros(Int,m,n),zeros(Int,m))\n    !verbose ? nothing : println(\"Instance of MKP : \",m,\" couples objective/constraint and \",n,\" variables\")\n\n    # Extract the data of the MKP from the following lines ---------------------\n    i=0; j=0\n    for l = 2:length(lines)\n        if occursin(\"knapsack \", lines[l])\n            i = i + 1\n            j = 0\n            !verbose ? nothing : println(\"Couple objective/constraint n°\",i)\n        elseif occursin(\"capacity\", lines[l])\n            line = split(lines[l],\"+\")\n            momkp.ω[i] = floor(Int, parse(Float64, line[2]))\n            !verbose ? nothing : println(\"ω[\",i,\"]=\",momkp.ω[i])\n        elseif occursin(\"item\", lines[l])\n            j = j + 1\n        elseif occursin(\"weight\", lines[l])\n            line = split(lines[l],\"+\")\n            momkp.W[i,j] = parse(Int, line[2])\n            !verbose ? nothing : println(\"w[\",i,\",\",j,\"]=\",momkp.W[i,j])\n        elseif occursin(\"profit\", lines[l])\n            line = split(lines[l],\"+\")\n            momkp.P[i,j] = parse(Int, line[2])\n            !verbose ? nothing : println(\"p[\",i,\",\",j,\"]=\",momkp.P[i,j])\n        end\n    end\n\n    return momkp\nend\n\n# ==============================================================================\n\n# Example on how to use it :\n# fname=\"knapsack.100.3\"; verbose = true\n# instanceZitzler = readInstanceMOMKPformatZL(verbose,fname)\n", "meta": {"hexsha": "a3e0195b6cb7e2f3300129054a6c9b9c212eefd7", "size": 2779, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "parserMomkpZL.jl", "max_stars_repo_name": "PoltyPoltou/NSGA2-vs-MOVNS", "max_stars_repo_head_hexsha": "93ce5607d19ba077b3d659228e7fe69955c340b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "parserMomkpZL.jl", "max_issues_repo_name": "PoltyPoltou/NSGA2-vs-MOVNS", "max_issues_repo_head_hexsha": "93ce5607d19ba077b3d659228e7fe69955c340b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "parserMomkpZL.jl", "max_forks_repo_name": "PoltyPoltou/NSGA2-vs-MOVNS", "max_forks_repo_head_hexsha": "93ce5607d19ba077b3d659228e7fe69955c340b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2753623188, "max_line_length": 108, "alphanum_fraction": 0.5059373875, "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759492, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7581770757182489}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,jl:hydrogen\n#     text_representation:\n#       extension: .jl\n#       format_name: hydrogen\n#       format_version: '1.3'\n#       jupytext_version: 1.10.3\n#   kernelspec:\n#     display_name: Julia 1.7.0\n#     language: julia\n#     name: julia-1.7\n# ---\n\n# %% [markdown]\n# https://twitter.com/mkashi/status/1469153893179596801\n\n# %%\nusing Plots\n\nf(x) = x^3 - 3x^2 + 3x - 3\ndf(x) = 3x^2 - 6x + 3\n\nx = 2.1\ndx = @. 2.0 ^ (-60:4)\n\nfinitediff = @. (f(x + dx) - f(x)) / dx\nabserr_finirediff = @. abs(finitediff - df(x))\n\nplot(dx, abserr_finirediff; xscale=:log10, yscale=:log10, label=\"\")\nplot!(; xtick=@.(1e1^(-20:2:2)), ytick=@.(1e1^(-20:2:2)))\nplot!(; xlabel=\"dx\", ylabel=\"absolute error\")\n\n# %%\ndf(x)\n\n# %%\nusing ForwardDiff\nForwardDiff.derivative(f, x)\n\n# %%\n@show finitediff;\n\n# %%\nusing FiniteDifferences\n@show [central_fdm(k, 1)(f, x) for k in 2:10];\n\n# %%\n", "meta": {"hexsha": "1fc5865d4b91b9230b0d2a8c9642fb762dbfcdfa", "size": 910, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0025/finite difference and autimatic differentiation.jl", "max_stars_repo_name": "genkuroki/public", "max_stars_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-06-06T00:33:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T06:56:08.000Z", "max_issues_repo_path": "0025/finite difference and autimatic differentiation.jl", "max_issues_repo_name": "genkuroki/public", "max_issues_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0025/finite difference and autimatic differentiation.jl", "max_forks_repo_name": "genkuroki/public", "max_forks_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-02T11:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T11:46:05.000Z", "avg_line_length": 18.2, "max_line_length": 67, "alphanum_fraction": 0.5879120879, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7581770658082605}}
{"text": "# # Foundations of Bilevel Programming: Example 6\n# This example is from the book Princeton Handbook of Test Problems in Local and Global Optimization\n# Dempe, Chapter 9.3.2 -parg 221 [url](https://www.springer.com/gp/book/9780792358015)\n\n# Here, only the second level is described\n\n# Model of the problem\n# First level\n# ```math\n# \\min (x-5)^2+(2y+1)^2,\\\\\n# \\notag s.t.\\\\\n# x \\geq 0,\\\\\n# y \\geq 0,\\\\\n# ```\n# Second level\n# ```math\n# \\min (y-1)^2-1.5xy,\\\\\n# \\notag s.t.\\\\\n# -3x+y \\leq -3,\\\\\n# x-0.5y \\leq 4,\\\\\n# x+y \\leq 7,\\\\\n# ```\n\n\nusing BilevelJuMP\nusing Ipopt\nusing JuMP\nusing Test\n\nmodel = BilevelModel(Ipopt.Optimizer, mode = BilevelJuMP.ProductMode(1e-9))\n\n# Global variables\natol = 1e-3\n\n# First we need to create all of the variables in the upper and lower problems:\n\n# Upper level variables\n@variable(Upper(model), x)\n\n#Lower level variables\n@variable(Lower(model), y)\n\n# Then we can add the objective and constraints of the upper problem:\n\n# Upper level objecive function\n@objective(Upper(model), Min, (x-5)^2 + (2y+1)^2)\n\n# Upper level constraints\n@constraint(Upper(model), x >= 0)\n@constraint(Upper(model), y >= 0) # only in lowrrin GAMS\n\n\n\n# Followed by the objective and constraints of the lower problem:\n\n# Lower objective function\n@objective(Lower(model), Min, (y-1)^2 -1.5*x*y)\n\n# Lower constraints\n@constraint(Lower(model), -3x +    y <= -3)\n@constraint(Lower(model),   x - 0.5y <= 4)\n@constraint(Lower(model),   x +    y <= 7)\n\n# Initial Starting conditions  #src\n\n# Now we can solve the problem and verify the solution again that reported by\n# Dempe.\n\noptimize!(model)\nprimal_status(model)\ntermination_status(model)\n\n@test value(x) ≈ 1 atol=atol\n@test value(y) ≈ 0 atol=atol\n\n", "meta": {"hexsha": "404c3e13e53db325bf32d884ef36c18fdeffc4df", "size": 1697, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/PHTP_example1.jl", "max_stars_repo_name": "NLaws/BilevelJuMP.jl", "max_stars_repo_head_hexsha": "e8d0020b0634fcd49d795a042b29e13d4751b60d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 58, "max_stars_repo_stars_event_min_datetime": "2019-11-11T02:06:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:10:36.000Z", "max_issues_repo_path": "docs/src/examples/PHTP_example1.jl", "max_issues_repo_name": "NLaws/BilevelJuMP.jl", "max_issues_repo_head_hexsha": "e8d0020b0634fcd49d795a042b29e13d4751b60d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 146, "max_issues_repo_issues_event_min_datetime": "2019-11-08T22:26:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T00:41:16.000Z", "max_forks_repo_path": "docs/src/examples/PHTP_example1.jl", "max_forks_repo_name": "NLaws/BilevelJuMP.jl", "max_forks_repo_head_hexsha": "e8d0020b0634fcd49d795a042b29e13d4751b60d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2019-12-02T03:41:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-02T01:37:55.000Z", "avg_line_length": 22.3289473684, "max_line_length": 100, "alphanum_fraction": 0.6859163229, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.7580890709337929}}
{"text": "#### Kahan matrix\n\nexport Kahan\n\nimmutable Kahan{T<:Number,T1<:Number} <: AbstractMatrix{T}\n    m::Int # dimension\n    n::Int # dimension\n    theta::T # angle\n    pert::T1 # perturbation is pert*eps()\nend # immutable\n\n# Define its size\nsize(A::Kahan, r::Int) = r==1 ? A.m : A.n\nsize(A::Kahan) = A.m, A.n\n\n# Index into a Kahan\nfunction getindex(A::Kahan,i::Integer,j::Integer)\n    m=minimum(size(A))\n    t=tan(A.theta)\n    c=1.0/sqrt(1.0+t^2)\n    s=t*c\n    if i>m; return 0.0\n    elseif i>j; return 0.0\n    elseif i==j; return s^(i-1)+A.pert*eps()*(m-i+1)\n    else return -c*s^(i-1)\n    end\nend # getindex\n\n# Dense version of Kahan\nfull(A::Kahan) =[A[i,j] for i=1:size(A,1), j=1:size(A,2)]\n\n\n\n", "meta": {"hexsha": "680d6c6b9b54bb6c2867f14b6d2e07a38b87bacf", "size": 692, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kahan.jl", "max_stars_repo_name": "JuliaPackageMirrors/SpecialMatrices.jl", "max_stars_repo_head_hexsha": "726b43fd2a968ef340ed89234f3ef3439f64fdb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kahan.jl", "max_issues_repo_name": "JuliaPackageMirrors/SpecialMatrices.jl", "max_issues_repo_head_hexsha": "726b43fd2a968ef340ed89234f3ef3439f64fdb6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kahan.jl", "max_forks_repo_name": "JuliaPackageMirrors/SpecialMatrices.jl", "max_forks_repo_head_hexsha": "726b43fd2a968ef340ed89234f3ef3439f64fdb6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3529411765, "max_line_length": 58, "alphanum_fraction": 0.598265896, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505204, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7580786286494489}}
{"text": "using Plots\n\n# Problem parameters\nα = 0.3\nδ = 0.1\nβ = 0.9\n\n# Capital grid\nkupper = 2\nklower = 0.001\nn = 10\nkgrid = collect(range(klower, stop = kupper, length = n))\n\n# Iteration parameters\ntolerance = 0.001\nimax = 1000\n\n# Initialize values\nvnew = zeros(length(kgrid)) # initial value function guess\nv = vnew .+ 2*tolerance # initialize v in a way that ensures loop will start\nglobal cartesianindex = Array{CartesianIndex{2}, n}\ni = 1\n\nwhile maximum(abs.(v - vnew)) > tolerance && i<=imax\n    v = vnew;\n    c = zeros(n, n);\n    for i in 1:n\n        for j in 1:n\n            c[i,j] = kgrid[i]^α + (1-δ)*kgrid[i] - kgrid[j];\n            if c[i,j] <= 0\n                c[i,j] = 0;\n            end\n        end\n        (vnew, cartesianindex) = findmax(log.(c) .+ β*v', dims = 2);\n    end\n    i += 1\nend\n\nscatter(kgrid, vnew, title = \"v(k)\")\n\n# Policy function\nkprimeindex = getindex.(cartesianindex, 2)\nkprime = kgrid[kprimeindex]\nscatter(kgrid, kprime, title = \"k'(k)\")\n\n\n", "meta": {"hexsha": "194e180833aba884eac9c4a82136c8ff091d419a", "size": 967, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vf_iteration_intuitive_steps_final.jl", "max_stars_repo_name": "PhilipCaoChicago/ECON602_2021", "max_stars_repo_head_hexsha": "ef62b3763663c076ab5ea40009a57232ba338885", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-17T23:05:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T04:17:50.000Z", "max_issues_repo_path": "src/vf_iteration_intuitive_steps_final.jl", "max_issues_repo_name": "PhilipCaoChicago/ECON602_2021", "max_issues_repo_head_hexsha": "ef62b3763663c076ab5ea40009a57232ba338885", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vf_iteration_intuitive_steps_final.jl", "max_forks_repo_name": "PhilipCaoChicago/ECON602_2021", "max_forks_repo_head_hexsha": "ef62b3763663c076ab5ea40009a57232ba338885", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-09-21T19:07:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T22:37:40.000Z", "avg_line_length": 20.5744680851, "max_line_length": 76, "alphanum_fraction": 0.5915201655, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7580786271887648}}
{"text": "\"\"\"\n    binary_brier_score(ytrue, yscore)\n\nComputes the binary formulation of the Brier score, defined as:\n\n```math\n\\\\frac{1}{N}\\\\sum\\\\limits _{t=1}^{N}(f_t-o_t)^2 \\\\,\\\\!\n```\n\nLower values are better. Best value is 0.\n\"\"\"\nfunction binary_brier_score(\n        ytrue::AbstractVector{<:Integer},\n        yscore::AbstractVector{<:AbstractFloat},\n        )\n    if length(ytrue) != length(yscore)\n        error(\"length(ytrue) != length(yscore)\")\n    end\n    if length(ytrue) == 0\n        error(\"length(ytrue) == 0\")\n    end\n    result = mean_square_error(ytrue, yscore)\n    return result\nend\n\n", "meta": {"hexsha": "6ad75d63ac71d302398cd32a48052d4283e5e4a4", "size": 587, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/toplevel/always-loaded/metrics/brier_score.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PredictMD.jl-3e7d7328-36f8-4388-bd01-4613c92c7370", "max_stars_repo_head_hexsha": "7987993b5900e658c3aa9c568a9ed7fe38e82f11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2018-05-24T14:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T08:17:39.000Z", "max_issues_repo_path": "src/toplevel/always-loaded/metrics/brier_score.jl", "max_issues_repo_name": "UnofficialJuliaMirror/PredictMD.jl-3e7d7328-36f8-4388-bd01-4613c92c7370", "max_issues_repo_head_hexsha": "7987993b5900e658c3aa9c568a9ed7fe38e82f11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 383, "max_issues_repo_issues_event_min_datetime": "2018-04-12T21:53:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-24T15:53:37.000Z", "max_forks_repo_path": "src/toplevel/always-loaded/metrics/brier_score.jl", "max_forks_repo_name": "UnofficialJuliaMirror/PredictMD.jl-3e7d7328-36f8-4388-bd01-4613c92c7370", "max_forks_repo_head_hexsha": "7987993b5900e658c3aa9c568a9ed7fe38e82f11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-05-06T23:16:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T15:49:49.000Z", "avg_line_length": 22.5769230769, "max_line_length": 63, "alphanum_fraction": 0.6252129472, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7580786186252529}}
{"text": "#for every different type of linkfunction, internally julia will find the right apply_inverse_link function\n\n# This super type of all response distribution types\nabstract type InverseLinkFunction end\n\n##LINK FUNCTIONS##\n\n\"\"\"inverse cauchit link.\"\"\"\n\nstruct CauchitLink <: InverseLinkFunction\nend\n\nfunction cauchit_inverse_link(x)\n  return atan(x) / pi + one(x) / 2\nend\n\n\"\"\"inverse cloglog link.\"\"\"\n\nstruct CloglogLink <: InverseLinkFunction\nend\n\nfunction cloglog_inverse_link(x)\n  return one(x) - exp(-exp(x))\nend \n\n\"\"\"inverse identity link.\"\"\"\n\nstruct IdentityLink <: InverseLinkFunction\nend\n\nfunction identity_inverse_link(x)\n  return x\nend\n\n\"\"\"inverse inverse link.\"\"\"\n\nstruct InverseLink <: InverseLinkFunction\nend\n\nfunction inverse_inverse_link(x)\n  return one(x) / x\nend\n\n\"\"\"inverse logit link.\"\"\"\n\nstruct LogitLink <: InverseLinkFunction\nend\n\nfunction logit_inverse_link(x)\n  return one(x) / (one(x) + exp(-x))\nend\n\n\"\"\"inverse log link.\"\"\"\n\nstruct LogLink <: InverseLinkFunction\nend\n\nfunction log_inverse_link(x)\n  return exp(x)\nend\n\n\"\"\"inverse probit link.\"\"\"\n \nstruct ProbitLink <: InverseLinkFunction\nend\n\n\nfunction probit_inverse_link(x)\n  return (one(x) + erf(x / sqrt(2 * one(x)))) / 2\nend\n\n\"\"\"inverse sqrt link.\"\"\"\n\nstruct SqrtLink <: InverseLinkFunction\nend\n\nfunction sqrt_inverse_link(x)\n  return x * x\nend\n\n##APPLY INVERSE LINK FUNCTIONS\n\napply_inverse_link(μ, link::LogLink) = log_inverse_link.(μ)\n\napply_inverse_link(μ, link::IdentityLink) = identity_inverse_link.(μ)\n\napply_inverse_link(μ, link::SqrtLink) = sqrt_inverse_link.(μ)\n\napply_inverse_link(μ, link::ProbitLink) = probit_inverse_link.(μ)\n\napply_inverse_link(μ, link::LogitLink) = logit_inverse_link.(μ)\n\napply_inverse_link(μ, link::InverseLink) = inverse_inverse_link.(μ)\n\napply_inverse_link(μ, link::CauchitLink) = cauchit_inverse_link.(μ)\n\napply_inverse_link(μ, link::CloglogLink) = cloglog_inverse_link.(μ)\n\n", "meta": {"hexsha": "58ad984ac6788e904a8f71730b7d9bd452da6758", "size": 1890, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "TraitSimulation/src/apply_inverse_link_new.jl", "max_stars_repo_name": "sarah-ji/Tutorials", "max_stars_repo_head_hexsha": "7619ccb8b8089b65792134ca9d12777a916510cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TraitSimulation/src/apply_inverse_link_new.jl", "max_issues_repo_name": "sarah-ji/Tutorials", "max_issues_repo_head_hexsha": "7619ccb8b8089b65792134ca9d12777a916510cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TraitSimulation/src/apply_inverse_link_new.jl", "max_forks_repo_name": "sarah-ji/Tutorials", "max_forks_repo_head_hexsha": "7619ccb8b8089b65792134ca9d12777a916510cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0909090909, "max_line_length": 107, "alphanum_fraction": 0.755026455, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7580786171645688}}
{"text": "# https://github.com/stan-dev/blob/master/basic_estimators/normal_mixture.stan\n\n# normal mixture, unknown proportion and means, known variance\n# p(y|mu,theta) = theta * Normal(y|mu[1],1) + (1-theta) * Normal(y|mu[2],1);\n\nconst simplenormalmixturemodel = \"\ndata {\n  int<lower=0>  N;\n  real y[N];\n}\nparameters {\n  real<lower=0,upper=1> theta;\n  real mu[2];\n}\ntransformed parameters {\n  real log_theta;\n  real log_one_minus_theta;\n\n  log_theta <- log(theta);\n  log_one_minus_theta <- log(1.0 - theta);\n}\nmodel {\n  theta ~ uniform(0,1); // equivalently, ~ beta(1,1);\n  for (k in 1:2)\n    mu[k] ~ normal(0,10);\n  for (n in 1:N)\n    increment_log_prob(\n      log_sum_exp(log_theta + normal_log(y[n],mu[1],1.0),\n                  log_one_minus_theta + normal_log(y[n],mu[2],1.0)));\n}\n\"\n", "meta": {"hexsha": "a783f432cbe0a27ab044bb9f65d5d316f8c384b8", "size": 779, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/stan-models/normal-mixture-stan.model.jl", "max_stars_repo_name": "JuliaTagBot/ContinuousBenchmarks.jl", "max_stars_repo_head_hexsha": "000432d25acef05a11ea51dedfd841c761735e0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/stan-models/normal-mixture-stan.model.jl", "max_issues_repo_name": "JuliaTagBot/ContinuousBenchmarks.jl", "max_issues_repo_head_hexsha": "000432d25acef05a11ea51dedfd841c761735e0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/stan-models/normal-mixture-stan.model.jl", "max_forks_repo_name": "JuliaTagBot/ContinuousBenchmarks.jl", "max_forks_repo_head_hexsha": "000432d25acef05a11ea51dedfd841c761735e0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.34375, "max_line_length": 78, "alphanum_fraction": 0.6469833119, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075701109193, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.7580745704501466}}
{"text": "@doc \"\"\"\n  Computes the error-free addition `a + b = x + y`, where `x = fl(a + b)`, for\n  general floating-point numbers `a` and `b`. The algorithm requires 6 flops;\n  twice as many as `err_fast_add`. However, failed branch prediction because of\n  the required comparison `|a| ≥ |b|` in the general case, cause this algorithm\n  to be faster on modern pipelined architectures.\n\n  References:\n\n    * D.E. Knuth, The Art of Computer Programming, 3rd ed., vol. 2,\n      Addison-Wesley, 1998.\n    * D. Møller, Quasi double-precision in floating-point addition, BIT\n      Numerical Mathematics 5, pp. 37–50, 1965.\n\"\"\" ->\n# TODO: Extend the definition to floating-point arrays\nfunction err_add{T<:IEEE754}(a::T, b::T)\n  x = a + b\n  c = x - a\n  y = (a - (x-c)) + (b-c)\n  x, y\nend\n\n\n@doc \"\"\"\n  Computes the error-free addition `a + b = x + y`, where `x = fl(a + b)`, for\n  floating-point numbers `a` and `b` such that the exponent of `a` is larger\n  than or equal to that of `b`. If `|a| ≥ |b|`, this condition is always\n  satisfied. The algorithm requires 3 flops.\n\n  References:\n\n    * T.J. Dekker, A floating-point technique for extending the available\n      precision, Numerische Mathematik 18, pp. 224–242, 1971.\n  \"\"\" ->\n# TODO: Extend the definition to floating-point arrays\nfunction err_fast_add{T<:IEEE754}(a::T, b::T)\n  x = a + b\n  y = b - (x-a)\n  x, y\nend\n", "meta": {"hexsha": "ed904fd7663889e6bb9b22387e2d8921c72590e6", "size": 1358, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/add.jl", "max_stars_repo_name": "JuliaPackageMirrors/ErrorFreeTransforms.jl", "max_stars_repo_head_hexsha": "8404370db86c85f150469ec36259bce33103bb51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/add.jl", "max_issues_repo_name": "JuliaPackageMirrors/ErrorFreeTransforms.jl", "max_issues_repo_head_hexsha": "8404370db86c85f150469ec36259bce33103bb51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-11-25T13:03:27.000Z", "max_issues_repo_issues_event_max_datetime": "2015-11-25T15:42:28.000Z", "max_forks_repo_path": "src/add.jl", "max_forks_repo_name": "JuliaPackageMirrors/ErrorFreeTransforms.jl", "max_forks_repo_head_hexsha": "8404370db86c85f150469ec36259bce33103bb51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:13:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:13:42.000Z", "avg_line_length": 33.1219512195, "max_line_length": 79, "alphanum_fraction": 0.6531664212, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164657, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7580672618916693}}
{"text": "\"\"\"\n    N, E = latlon2yx(φ₀, λ₀, φ, λ)\n\nCoordinate transformation between geographic and plane rectangular coordinates on the Gauss-Krüger Projection\nThis function is based on the following documents:\n        https://www.gsi.go.jp/common/000061216.pdf\n        https://vldb.gsi.go.jp/sokuchi/surveycalc/surveycalc/algorithm/xy2bl/xy2bl.htm\n        https://vldb.gsi.go.jp/sokuchi/surveycalc/surveycalc/algorithm/bl2xy/bl2xy.htm\n\n### input arguments\n- φ₀, λ₀ : latitude of origin and central meridian\n- φ , λ  : geographic latitude and longitude\n### return values\n- N, E   : plane rectangular coordinates northing and easting\n\n### Examples\n```julia-repl\njulia> # ANSWER: y = 11543.6883, x = 22916.2436\n\njulia> latlon2yx(36.0, 139.0+5.0/6.0, 36.103774791666666, 140.08785504166664)\n(11543.688321484718, 22916.24355431881)\n```\n\"\"\"\nfunction latlon2yx(φ₀, λ₀, φ, λ)\n\n    φ₀ = deg2rad(φ₀)\n    λ₀ = deg2rad(λ₀)\n    φ = deg2rad(φ)\n    λ = deg2rad(λ)\n\n    S̅φ₀ = arclength(φ₀)\n\n    ncoef1 = 2sqrt(n)/(1+n)\n\n    t = sinh(atanh(sin(φ)) - ncoef1*atanh(ncoef1*sin(φ)))\n    t̅ = sqrt(1+t^2)\n    λc = cos(λ-λ₀)\n    λs = sin(λ-λ₀)\n    ξ′ = atan(t,λc)\n    η′ = atanh(λs/t̅)\n\n    # α terms\n    αcoef = [1/2   -2/3    5/16        41/180     -127/288; # α₁\n             0.0  13/48    -3/5      557/1440      281/630; # α₂\n             0.0    0.0  61/240      -103/140  15061/26880; # α₃\n             0.0    0.0     0.0  49561/161280     -179/168; # α₄\n             0.0    0.0     0.0           0.0  34729/80460; # α₅\n            ]\n    αj = αcoef * [n^k for k=1:5]\n\n    N = A̅*(ξ′ + sum([αj[j]sin(2j*ξ′)cosh(2j*η′) for j=1:5])) - S̅φ₀\n    E = A̅*(η′ + sum([αj[j]cos(2j*ξ′)sinh(2j*η′) for j=1:5]))\n\n    return [N E]\nend\n# -------------------------------------\n\"\"\"\n    E, N = lonlat2xy(λ₀, φ₀, λ, φ)\n\nSee [`lanlon2yx`](@ref)\n\"\"\"\nlonlat2xy(λ₀, φ₀, λ, φ) = reverse(latlon2yx(φ₀, λ₀, φ, λ), dims=2)\n\n# -------------------------------------\nfunction latlon2yx_ja(zone::Integer, φ, λ)\n    !(0 < zone < 20) && error(\"zone ID must be a integer in the range of 1 to 19.\")\n    return latlon2yx(Origin_LatLon_Japan[zone,:]..., φ, λ)\nend\n# -------------------------------------\nlonlat2xy_ja(zone::Integer, λ, φ)  = reverse(latlon2yx_ja(zone, φ, λ), dims=2)\n# -------------------------------------\n", "meta": {"hexsha": "8d9e56a6ff25a17085585c7e4e7b9721293ee26d", "size": 2261, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/latlon2yx.jl", "max_stars_repo_name": "hydrocoast/CoordinateConverterGK.jl", "max_stars_repo_head_hexsha": "179f51bff0d1b1284cbf4c4d368467cab3449bb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-10T17:16:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T04:54:01.000Z", "max_issues_repo_path": "src/latlon2yx.jl", "max_issues_repo_name": "hydrocoast/CoordinateConverterGK.jl", "max_issues_repo_head_hexsha": "179f51bff0d1b1284cbf4c4d368467cab3449bb0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-02-10T16:55:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-06T02:31:53.000Z", "max_forks_repo_path": "src/latlon2yx.jl", "max_forks_repo_name": "hydrocoast/CoordinateConverterGK.jl", "max_forks_repo_head_hexsha": "179f51bff0d1b1284cbf4c4d368467cab3449bb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4027777778, "max_line_length": 109, "alphanum_fraction": 0.5457762052, "num_tokens": 903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.8080672112416736, "lm_q1q2_score": 0.7580672602088773}}
{"text": "const ymeyer = [3.478e4, 2.861e4, 2.365e4, 1.963e4, 1.637e4, 1.372e4,\n                1.154e4, 9.744e3, 8.261e3, 7.030e3, 6.005e3, 5.147e3,\n                4.427e3, 3.820e3, 3.307e3, 2.872e3]\n\nconst meyer = let res_init=zeros(16), jac_init=zeros(16,3), x_init=[0.02, 4.e3, 2.5e2]\n\n    function res(x, r)\n        for i = 1:16\n            ti = Float64(5*i + 45)\n            r[i] = x[1] * exp(x[2] / (ti + x[3])) - ymeyer[i]\n        end\n        return r\n    end\n\n    function jac(x, j)\n        for i = 1:16\n            ti = Float64(5*i + 45)\n            u = ti + x[3]\n            t = exp(x[2] / u)\n            j[i, 1] = t\n            j[i, 2] = x[1] * t/u\n            j[i, 3] = -x[1] * x[2] * t / (u * u)\n        end\n        return j\n    end\n\n    f(;scale=1, verbose=false, print_steps=false) = testone(\"meyer\", res, jac,\n                                                   res_init, jac_init, x_init;\n                                                   scale=scale, verbose=verbose,\n                                                   print_steps=print_steps)\nend\n", "meta": {"hexsha": "7c808f90c5f552b7ae078b268814a587902396b0", "size": 1058, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/optests/meyer.jl", "max_stars_repo_name": "macd/NL2sol.jl", "max_stars_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-01-19T21:59:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T00:42:56.000Z", "max_issues_repo_path": "test/optests/meyer.jl", "max_issues_repo_name": "macd/NL2sol.jl", "max_issues_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/optests/meyer.jl", "max_forks_repo_name": "macd/NL2sol.jl", "max_forks_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0625, "max_line_length": 86, "alphanum_fraction": 0.4120982987, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.758044430005795}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.22\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\tlambda, N = 1, 10^6\n\txGrid = 0:6\nend\n\n# ╔═╡ 84a73e9a-2165-11eb-3620-d7ddf9c07aff\nbegin\n\texpDist = Exponential(1/lambda)\n\tfloorData = counts(convert.(Int,floor.(rand(expDist,N))), xGrid)/N\n\tgeomDist = Geometric(1-MathConstants.e^-lambda)\nend\n\n# ╔═╡ 84a76f3c-2165-11eb-0eeb-1bb55507bb51\nbegin\n\tplot( xGrid, floorData, \n\t\tline=:stem, marker=:circle, \n\t\tc=:blue, ms=10, msw=0, lw=4, \n\t\tlabel=\"Floor of Exponential\")\n\tplot!( xGrid, pdf.(geomDist,xGrid), \n\t\tline=:stem, marker=:xcross, \n\t\tc=:red, ms=6, msw=0, lw=2, \n\t\tlabel=\"Geometric\", ylims=(0,1), \n\t\txlabel=\"x\", ylabel=\"Probability\")\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.22\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═84a73e9a-2165-11eb-3620-d7ddf9c07aff\n# ╠═84a76f3c-2165-11eb-0eeb-1bb55507bb51\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "e9b8e4fb9dd98b344427acc111a46fc9f0801b48", "size": 1402, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.22.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.22.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.22.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 24.5964912281, "max_line_length": 67, "alphanum_fraction": 0.7161198288, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7580444297701762}}
{"text": "#=\nFor details, please visit:\nhttps://computationalmindset.com/en/neural-networks/experiments-with-neural-odes-in-julia.html#exp1\n\nParametric system to train:\nx' = a1 x + b1 y + c1 e^(-d1 t)\ny' = a2 x + b2 y + c2 e^(-d2 t)\nx(0) = 0\ny(0) = 0\n\nto generate dataset use the following param values\na1 = 1.11\nb1 = 2.43\nc1 = -3.66\nd1 = 1.37\na2 = 2.89\nb2 = -1.97\nc2 = 4.58\nd2 = 2.86\n\nAnalytical solution is:\nhttps://www.wolframalpha.com/input/?i=x%27+%3D+1.11+x+%2B+2.43+y+%2B+-3.66+e%5E%28-1.37+t%29%3B+y%27+%3D+2.89+x+-1.97+y+%2B+4.58+e%5E+%28-2.86+t%29%3B+x%280%29%3D0%3B+y%280%29%3D0%3B\n=#\n\nusing Flux, DiffEqFlux, DifferentialEquations, Plots\n\nfunction parametric_ode_system!(du,u,p,t)\n  x, y = u\n  a1, b1, c1, d1, a2, b2, c2, d2 = p\n  du[1] = dx = a1*x + b1*y + c1*exp(-d1*t)\n  du[2] = dy = a2*x + b2*y + c2*exp(-d2*t)\nend\n\ntrue_params = [1.11, 2.43, -3.66, 1.37, 2.89, -1.97, 4.58, 2.86]\n\nan_sol_x(t) =\n  -1.38778e-17 * exp(-8.99002 * t) -\n  2.77556e-17 * exp(-7.50002 * t) +\n  3.28757 * exp(-3.49501 * t) -\n  3.18949 * exp(-2.86 * t) +\n  0.258028 * exp(-1.37 * t) -\n  0.356108 * exp(2.63501 * t) +\n  4.44089e-16 * exp(3.27002 * t) +\n  1.11022e-16 * exp(4.76002 * t)\nan_sol_y(t) =\n  -6.23016 * exp(-3.49501 * t) +\n  5.21081 * exp(-2.86 * t) +\n  1.24284 * exp(-1.37 * t) -\n  0.223485 * exp(2.63501 * t) +\n  2.77556e-17 * exp(4.76002 * t)\n\ntbegin=0.0\ntend=1.5\ntstep=0.01\ntrange = tbegin:tstep:tend\nu0 = [0.0,0.0]\ntspan = (tbegin,tend)\np = ones(8)\n\nprob = ODEProblem(parametric_ode_system!, u0, tspan, p)\n\nfunction net()\n    solve(prob, Tsit5(), p=p, saveat=trange)\nend\n\ndataset_outs = [an_sol_x.(trange), an_sol_y.(trange)]\nfunction loss_func()\n  pred = net()\n  sum(abs2, dataset_outs[1] .- pred[1,:]) +\n  sum(abs2, dataset_outs[2] .- pred[2,:])\nend\n\nepochs = 1000\nlearning_rate = 0.05\ndata = Iterators.repeated((), epochs)\nopt = ADAM(learning_rate)\n\ncallback_func = function ()\n  loss_value = loss_func()\n  println(\"Loss: \", loss_value)\nend\nfparams = Flux.params(p)\nFlux.train!(loss_func, fparams, data, opt, cb=callback_func)\n\npredict_prob = ODEProblem(parametric_ode_system!, u0, tspan, p)\npredict_sol = solve(prob, Tsit5(), saveat=trange)\nx_predict_sol = [u[1] for u in predict_sol.u]\ny_predict_sol = [u[2] for u in predict_sol.u]\n\nprintln(\"Learned parameters:\", p)\n\nplot(trange, dataset_outs[1],\n    linewidth=2, ls=:dash,\n    title=\"Neural ODEs to fit params\",\n    xaxis=\"t\",\n    label=\"dataset x(t)\",\n    legend=true)\nplot!(trange, dataset_outs[2],\n    linewidth=2, ls=:dash,\n    label=\"dataset y(t)\")\nplot!(predict_sol.t, x_predict_sol,\n    linewidth=1,\n    label=\"predicted x(t)\")\nplot!(predict_sol.t, y_predict_sol,\n    linewidth=1,\n    label=\"predicted y(t)\")\n", "meta": {"hexsha": "9c782fda2ff7a5e59caa1b6ff2e1cfd454c9e804", "size": 2668, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ODEs/neural-odes-demos/julia/DiffEqFlux/train-sys-of-odes-to-meet-objective.jl", "max_stars_repo_name": "ettoremessina/differential-equations", "max_stars_repo_head_hexsha": "b0f74aa177e090ef654574e11af5e54e2c7b1472", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-04-23T00:41:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T23:49:31.000Z", "max_issues_repo_path": "ODEs/neural-odes-demos/julia/DiffEqFlux/train-sys-of-odes-to-meet-objective.jl", "max_issues_repo_name": "ettoremessina/differential-equations", "max_issues_repo_head_hexsha": "b0f74aa177e090ef654574e11af5e54e2c7b1472", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ODEs/neural-odes-demos/julia/DiffEqFlux/train-sys-of-odes-to-meet-objective.jl", "max_forks_repo_name": "ettoremessina/differential-equations", "max_forks_repo_head_hexsha": "b0f74aa177e090ef654574e11af5e54e2c7b1472", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-18T06:03:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T15:39:50.000Z", "avg_line_length": 24.9345794393, "max_line_length": 182, "alphanum_fraction": 0.6356821589, "num_tokens": 1136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.758044429770176}}
{"text": "# Linear Isotropic Covariance Function\n\n\"\"\"\n    LinIso <: Kernel\n\nIsotropic linear kernel (covariance)\n```math\nk(x, x') = xᵀx'/ℓ²\n```\nwith length scale ``ℓ``.\n\"\"\"\nmutable struct LinIso <: Kernel\n    \"Squared length scale\"\n    ℓ2::Float64\n    \"Priors for kernel parameters\"\n    priors::Array\n\n    \"\"\"\n        LinIso(ll::Float64)\n\n    Create `LinIso` with length scale `exp(ll)`.\n    \"\"\"\n    LinIso(ll::Float64) = new(exp(2 * ll), [])\nend\n\nstruct LinIsoData{D} <: KernelData\n    XtX::D\nend\n\nfunction KernelData(k::LinIso, X::MatF64)\n    XtX=X'*X\n    LinearAlgebra.copytri!(XtX, 'U') # make sure it's symmetric\n    LinIsoData(XtX)\nend\nkernel_data_key(k::LinIso, X::MatF64) = \"LinIsoData\"\n\n_cov(lin::LinIso, xTy) = xTy ./ lin.ℓ2\nfunction Statistics.cov(lin::LinIso, x::VecF64, y::VecF64)\n    K = _cov(lin, dot(x,y))\n    return K\nend\n\n@inline @inbounds function cov_ij(lin::LinIso, X::MatF64, data::LinIsoData, i::Int, j::Int, dim::Int)\n    return _cov(lin, data.XtX[i, j])\nend\nfunction Statistics.cov(lin::LinIso, X::MatF64, data::LinIsoData)\n    K = _cov(lin, data.XtX)\n    return K\nend\nfunction cov!(cK::MatF64, lin::LinIso, X::MatF64, data::LinIsoData)\n    iℓ2 = 1/lin.ℓ2\n    @inbounds @simd for I in eachindex(cK,data.XtX)\n        cK[I] = data.XtX[I]*iℓ2\n    end\n    return cK\nend\n\nget_params(lin::LinIso) = Float64[log(lin.ℓ2) / 2]\nget_param_names(::LinIso) = [:ll]\nnum_params(lin::LinIso) = 1\n\nfunction set_params!(lin::LinIso, hyp::VecF64)\n    length(hyp) == 1 || throw(ArgumentError(\"Linear isotropic kernel only has one parameter\"))\n    lin.ℓ2 = exp(2 * hyp[1])\nend\n\n@inline dk_dll(lin::LinIso, xTy::Float64) = -2 * _cov(lin,xTy)\n@inline function dKij_dθp(lin::LinIso, X::MatF64, i::Int, j::Int, p::Int, dim::Int)\n    if p==1\n        return dk_dll(lin, dotij(X,i,j,dim))\n    else\n        return NaN\n    end\nend\n@inline function dKij_dθp(lin::LinIso, X::MatF64, data::LinIsoData, i::Int, j::Int, p::Int, dim::Int)\n    if p==1\n        return dk_dll(lin, data.XtX[i,j])\n    else\n        return NaN\n    end\nend\n", "meta": {"hexsha": "dc281e80fe37a6d920a3fd80feb884f0c6737624", "size": 2012, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/lin_iso.jl", "max_stars_repo_name": "jbrea/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/lin_iso.jl", "max_issues_repo_name": "jbrea/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/lin_iso.jl", "max_forks_repo_name": "jbrea/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5365853659, "max_line_length": 101, "alphanum_fraction": 0.6381709742, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7580444262891239}}
{"text": "OPT_PROBS = Dict()\n\n#### Himmelblau\n\nOPT_PROBS[\"himmelblau\"] = Dict()\nOPT_PROBS[\"himmelblau\"][\"array\"] = Dict()\n\nfunction himmelblau!(x)\n    fx = (x[1]^2 + x[2] - 11)^2 + (x[1] + x[2]^2 - 7)^2\n    return fx\nend\nfunction himmelblau_batched_f!(X)\n    F = map(himmelblau!, X)\n    return F\nend\nfunction himmelblau_batched_f!(F, X)\n    map!(himmelblau!, F, X)\n    return F\nend\nfunction himmelblau_g!(∇f, x)\n    ∇f[1] = 4.0 * x[1]^3 + 4.0 * x[1] * x[2] -\n        44.0 * x[1] + 2.0 * x[1] + 2.0 * x[2]^2 - 14.0\n    ∇f[2] = 2.0 * x[1]^2 + 2.0 * x[2] - 22.0 +\n        4.0 * x[1] * x[2] + 4.0 * x[2]^3 - 28.0 * x[2]\n    ∇f\nend\n\nfunction himmelblau_fg!(∇f, x)\n    ∇f = himmelblau_g!(∇f, x)\n    fx = himmelblau!(x)\n    return fx, ∇f\nend\nfunction himmelblau_fgh!(∇f, ∇²f, x)\n    ∇²f = himmelblau_h!(∇²f, x)\n    fx, ∇f = himmelblau_fg!(∇f, x)\n    return fx, ∇f, ∇²f\nend\nfunction himmelblau_h!(∇²f, x)\n    ∇²f[1, 1] = 12.0 * x[1]^2 + 4.0 * x[2] - 44.0 + 2.0\n    ∇²f[1, 2] = 4.0 * x[1] + 4.0 * x[2]\n    ∇²f[2, 1] = ∇²f[1, 2]\n    ∇²f[2, 2] = 2.0 + 4.0 * x[1] + 12.0 * x[2]^2 - 28.0\n    return ∇²f\nend\nfunction himmelblau_hv!(hv, x, v)\n    hv[1] = (12.0 * x[1]^2 + 4.0 * x[2] - 44.0 + 2.0)*v[1] + (4.0 * x[1] + 4.0 * x[2])*v[2]\n    hv[2] =  (4.0 * x[1] + 4.0 * x[2])*v[1] + (2.0 + 4.0 * x[1] + 12.0 * x[2]^2 - 28.0)*v[2]\n    return hv\nend\n\nOPT_PROBS[\"himmelblau\"][\"array\"][\"x0\"] = [3.0, 1.0]\nOPT_PROBS[\"himmelblau\"][\"array\"][\"mutating\"] = ScalarObjective(himmelblau!, himmelblau_g!, himmelblau_fg!, himmelblau_fgh!, himmelblau_h!, himmelblau_hv!, himmelblau_batched_f!, nothing)\n\n\n### Exponential\n\nexponential!(x) = exp((2.0 - x[1])^2) + exp((3.0 - x[2])^2)\nfunction exponential_g!(g, x)\n    g[1] = -2.0 * (2.0 - x[1]) * exp((2.0 - x[1])^2)\n    g[2] = -2.0 * (3.0 - x[2]) * exp((3.0 - x[2])^2)\n    return g\nend\nfunction exponential_h!(H, x)\n    H[1, 1] = 2.0 * exp((2.0 - x[1])^2) * (2.0 * x[1]^2 - 8.0 * x[1] + 9)\n    H[1, 2] = 0.0\n    H[2, 1] = 0.0\n    H[2, 2] = 2.0 * exp((3.0 - x[2])^2) * (2.0 * x[2]^2 - 12.0 * x[2] + 19)\n    return H\nend\nfunction exponential_hv!(Hv, x, v)\n    Hv[1, 1] = (2.0 * exp((2.0 - x[1])^2) * (2.0 * x[1]^2 - 8.0 * x[1] + 9))*v[1]\n    Hv[2, 2] = (2.0 * exp((3.0 - x[2])^2) * (2.0 * x[2]^2 - 12.0 * x[2] + 19))*v[2]\n    return Hv\nend\nfunction exponential_fg!(g, x)\n    fx = exponential!(x)\n    g = exponential_g!(g, x)\n    return fx, g\nend\nfunction exponential_fgh!(g, H, x)\n    fx, g = exponential_fg!(g, x)\n    H = exponential_h!(H, x)\n    return fx, g, H\nend\n\nOPT_PROBS[\"exponential\"] = Dict()\nOPT_PROBS[\"exponential\"][\"array\"] = Dict()\n# Byttet om på x og H\nOPT_PROBS[\"exponential\"][\"array\"][\"x0\"] = [0.0, 0.0]\nOPT_PROBS[\"exponential\"][\"array\"][\"mutating\"] = ScalarObjective(exponential!, exponential_g!, exponential_fg!, exponential_fgh!, exponential_h!, exponential_hv!, nothing, nothing)\n\nexponential_prb = Dict()\nexponential_prb[\"twicediffed!\"] = TwiceDiffed(exponential!)\nexponential_prb[\"oncediffed!\"] = OnceDiffed(exponential!)\nexponential_prb[\"initial_x\"] = [0.0, 0.0]\nexponential_prb[\"minimizer\"] = [2.0, 3.0]\nexponential_prb[\"minimum\"] = exponential!(nothing, nothing, [2.0, 3.0])\nproblems[\"unconstrained\"][\"exponential\"] = exponential_prb\n", "meta": {"hexsha": "572fda8fe0a31b2325c70f4d3d52007808ae45bb", "size": 3165, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/problem_dict.jl", "max_stars_repo_name": "pkofod/NLSolvers.jl", "max_stars_repo_head_hexsha": "65034bb76cbf91e22784bd0156f28b85416adb2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2019-09-09T19:46:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T07:14:45.000Z", "max_issues_repo_path": "problems/problem_dict.jl", "max_issues_repo_name": "pkofod/NLSolvers.jl", "max_issues_repo_head_hexsha": "65034bb76cbf91e22784bd0156f28b85416adb2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2019-08-05T01:35:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-03T09:37:14.000Z", "max_forks_repo_path": "problems/problem_dict.jl", "max_forks_repo_name": "pkofod/NLSolvers.jl", "max_forks_repo_head_hexsha": "65034bb76cbf91e22784bd0156f28b85416adb2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-23T19:54:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-23T19:54:29.000Z", "avg_line_length": 31.9696969697, "max_line_length": 186, "alphanum_fraction": 0.5538704581, "num_tokens": 1517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.758044425346648}}
{"text": "module entropy\nexport velocity_histogram, kB, entropy_2D_MB, plot_velocity_distr\n\nusing SmoothedParticles\nusing Plots: plot, savefig\nusing Ipopt\nusing JuMP\n\n\"\"\"\n\tHistogram(xs::Vector{Float64}, ys::Vector{Float64},N,dx)\n\nHistogram structure storing ``N`` x values ``xs`` with uniform bin width ``dx`` and ``N`` y values ``ys``.\n\"\"\"\nstruct Histogram\n\txs::Vector{Float64}\n\tys::Vector{Float64}\n\tN::Int64\n\tdx::Float64\nend\n\n\"\"\"\n\tvelocity_histogram(sys::ParticleSystem; v_max = 0, N = 10)\n\nBuilding the histrogram of 2D velocities (norms) with ``v_max`` the maximum velocity in the histogram and ``N`` bins.\n\"\"\"\nfunction velocity_histogram(sys::ParticleSystem; v_max = 0.0, N = 100)::Histogram\n\tif v_max == 0.0 # if v_max = 0, find the maximum velocity of the particles\n\t\tfor k in 1:length(sys.particles) \n\t\t\tv = norm(sys.particles[k].v)\n\t\t\tif v > v_max\n\t\t\t\tv_max = v\n\t\t\tend\n\t\tend\n\tend\n\n\t# Find the heights of the histogram bins\n\tdv = v_max/N # velocity increment between the bins\n\tvs = 0.:dv:v_max\n\tns = zeros(length(vs))\n\tfor k in 1:length(sys.particles)\n\t\tv = norm(sys.particles[k].v)\n\t\tn = Int64(round(v/dv))\n\t\tif 1 <= n <= length(ns)\n\t\t\tns[n] += 1.0/(dv*length(sys.particles))\n\t\tend\n\tend\n\n\treturn Histogram(vs,ns,100,dv)\nend\n\n\n\n\"\"\"\n\tkB\n\nBoltzmann constant (in the SI units)\n\"\"\"\nconst kB = 1.380649e-23\n\n\"\"\"\n\tentropy(fMB::Histogram)::Float64\n\nCalculate Boltzmann entropy of a 2D Maxwell-Boltzmann distribution approximated by an ``fMB`` histogram.\n\"\"\"\nfunction entropy_2D_MB(fMB::Histogram)::Float64\n\t@assert(fMB.xs[1] == 0) # Assuming that the histogram starts at zero velocity\n\n\tS = 0.0\n\n\t# Approximating the reduced entropy near v=0, where a numerical singularity could appear\n\tfMBder = (fMB.ys[2]-fMB.ys[1])/fMB.dx\n\tif fMBder > 0\n\t\tS = - fMB.ys[1] * (log(fMBder)*fMB.dx - fMBder*(fMB.dx^3)/6)\n\tend\n\n\t# Approximating the rest of entropy\n\tfor k in 2:length(fMB.xs)\n\t\tif fMB.xs[k] != 0\n\t\t\tif fMB.ys[k] > 0\n\t\t\t\tS += -fMB.ys[k] * log(fMB.ys[k]/fMB.xs[k]) * fMB.dx\n\t\t\tend\n\t\tend\n\tend\n\n\treturn S\nend\n\n\"\"\" \n\tplot_velocity_distr(sys::ParticleSystem, name::String)\n\nPlots the distribution of velocity magnitudes among the particles of ``sys`` and saves the resulting pdf,\ntogether with a fit of the Maxwell-Boltzmann distribution, to file ``name``. ``m`` is the mass of each particle.\nReturns the temperature.\n\"\"\"\nfunction plot_velocity_distr(sys::ParticleSystem, m::Float64, name::String; v_max = 0.0)::Float64\n\tdistr = velocity_histogram(sys, v_max=v_max, N = 100)\n\t\n\t# fitting the histogram to a 2D Maxwell-Boltzmann distribution\n\tmodel = Model(Ipopt.Optimizer)\n\t@variable(model, beta)\n\t@NLobjective(\n\t\t\tmodel,\n\t\t\tMin,\n\t\t\tsum((distr.ys[i] - m*beta*distr.xs[i]*exp(-0.5*m*beta*distr.xs[i]^2))^2 for i in 1:length(distr.xs)),\n\t\t) \n\toptimize!(model)\n\tbeta = value(beta)\n\n\t# Plotting both the actual histogram and the fitted Maxwell-Boltzmann distribution\n\tns_boltz = zeros(length(distr.xs))\n\tfor i in 1:length(ns_boltz)\n\t\tns_boltz[i] = m*beta*distr.xs[i]*exp(-0.5*m*beta*distr.xs[i]^2)\n\tend\n\t@show(beta)\n\tT = 1/(beta*kB)\n\t@show(T)\n\n\tp = plot(distr.xs, [distr.ys ns_boltz], label = [\"data\" \"Maxwell-Boltzmann, T=\"*string(T)])\n\tsavefig(p, name)\n\treturn T\nend\n\n#\"\"\"\n#\tplot_velocity_distr(path::String, name:: String)\n#\n#Plot velocity distribution of particles loaded from a VTK file.\n#\"\"\"\n#function plot_velocity_distr(path::String, name::String)\n#\t@error \"Not working, sorry\"\n#\tdomain = Rectangle(-box_width, -box_width, 2*box_width, 3*box_height) \n#\tsys = ParticleSystem(Particle, domain, h)\n#\tread_vtk!(sys, path, x -> Particle(x = x, type = 0.0))\n#\tplot_velocity_distr(sys, name)  #not yet working\n#end\n\nend", "meta": {"hexsha": "4348259afe64a2627fc7713089161e52079453c1", "size": 3598, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/utils/entropy.jl", "max_stars_repo_name": "OndrejKincl/SPHLib.jl", "max_stars_repo_head_hexsha": "58fed2b67f5b658c25d4a926bb07182966e1ff2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-06T21:13:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T21:13:53.000Z", "max_issues_repo_path": "examples/utils/entropy.jl", "max_issues_repo_name": "OndrejKincl/SPHLib.jl", "max_issues_repo_head_hexsha": "58fed2b67f5b658c25d4a926bb07182966e1ff2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-16T15:50:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T15:50:30.000Z", "max_forks_repo_path": "examples/utils/entropy.jl", "max_forks_repo_name": "OndrejKincl/SPHLib.jl", "max_forks_repo_head_hexsha": "58fed2b67f5b658c25d4a926bb07182966e1ff2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4558823529, "max_line_length": 117, "alphanum_fraction": 0.6945525292, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7580444230170742}}
{"text": "# Util functions.\nmodule Util\nusing Random\n\nexport weighted_median,\n       err_must_be_overriden,\n       holdout\n\n# Weighted median.\n#\n# @param weights Weights of values.\n# @param values Values.\n# @return Weighted median.\nfunction weighted_median( weights::AbstractVector{U}, values::AbstractVector{V}) where {U,V<:Real}\n\n  k = 1\n  sorted_ind = sortperm(values)\n  weight_sum = sum(weights)\n\n  remaining_sum = weight_sum - weights[sorted_ind[k]]\n  while remaining_sum > weight_sum / 2.0\n    k += 1\n    remaining_sum -= weights[sorted_ind[k]]\n  end\n\n  return values[sorted_ind[k]]\nend\n\nfunction err_must_be_overriden(s = \"\")\n  error(\"Function must be overriden.\")\nend\n\n# Holdout method that partitions a collection\n# into two partitions.\n#\n# @param n Size of collection to partition.\n# @param right_prop Percentage of collection placed in right partition.\n# @return Two partitions of indices, left and right.\nfunction holdout(n, right_prop)\n  shuffled_indices = randperm(n)\n  partition_pivot = round(Int, right_prop * n)\n  right = shuffled_indices[1:partition_pivot]\n  left = shuffled_indices[partition_pivot+1:end]\n  return (left, right)\nend\n\nend # module\n", "meta": {"hexsha": "045406dbfee0e89aeec3c44343179bd0b50a97a5", "size": 1155, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/util.jl", "max_stars_repo_name": "pevnak/GradientBoost.jl", "max_stars_repo_head_hexsha": "770066448e7fa67316a8679823815b891b693cc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/util.jl", "max_issues_repo_name": "pevnak/GradientBoost.jl", "max_issues_repo_head_hexsha": "770066448e7fa67316a8679823815b891b693cc6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util.jl", "max_forks_repo_name": "pevnak/GradientBoost.jl", "max_forks_repo_head_hexsha": "770066448e7fa67316a8679823815b891b693cc6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0625, "max_line_length": 98, "alphanum_fraction": 0.7385281385, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7580136844499062}}
{"text": "# two main type systems - static and dynamic\n\n#Integers\na = 1;\nprintln(typeof(a));\n\nprintln(Sys.WORD_SIZE);\nprintln(Int);\nprintln(UInt);\n\n# Types of Integers\n\nprintln(typemin(Int8));\nprintln(typemax(Int8));\nprintln(typemin(UInt8));\nprintln(typemax(UInt8));\n\nprintln(typemin(Int16));\nprintln(typemax(Int16));\nprintln(typemin(UInt16));\nprintln(typemax(UInt16));\n\nprintln(typemin(Int32));\nprintln(typemax(Int32));\nprintln(typemin(UInt32));\nprintln(typemax(UInt32));\n\nprintln(typemin(Int64));\nprintln(typemax(Int64));\nprintln(typemin(UInt64));\nprintln(typemax(UInt64));\n\nprintln(typemin(Int128));\nprintln(typemax(Int128));\nprintln(typemin(UInt128));\nprintln(typemax(UInt128));\n\nprintln(typemin(Bool));\nprintln(false == 0);\n\nprintln(typemax(Bool));\n\n# Number Bases\n\nb = 4; #decimal\nb = 0b0100; # binary\nb = 0o010; # octal\nb = 0x1f; # hexadecimal\n\n# overflow handled by wrap around\n\na = typemax(Int64);\na = a + 1;\nprintln(a);\n\n# BigInt -> larger than Int128\n\nb = BigInt(typemax(Int128) + 1);\nprintln(b);\n\n# floating point numbers (IEEE 754)\nc = 1.2\nprintln(typeof(c));\n\nprintln(typemin(Float16));\nprintln(typemax(Float16));\n\nFloat16; # half precision 16-bit float\nFloat32; # single precision 32-bit float\nFloat64; # double precision 64-bit float\n\n# Simple floats\n\nf = 1.0;\nf = 1.;\nf = 0.1;\nf = .1;\n\nf = 22.5f-3; # single precision\nprintln(typeof(f));\n\nf = 22.5e-3; # double precision\nprintln(typeof(f));\n\nf = 0x1fp-1; # p - base2 exponent for 64-bit hex floats\n\n# Special floats\nInf;\n-Inf;\nNaN;\n\nprintln(Inf / Inf);\n\n# BigFloat for big computations\n\na = parse(BigFloat, \"0.00000000000000000000000000000000000000001\");\nprintln(a);\n\n# static type a variable using ::\nlocal a::Int8;\n\n# This throws TypeError\n# local a::Int8 = 128;\n\n# isa -> check if an object is a particular type\na = 2;\nprintln(isa(a, Int));\n\na = 2.0;\nprintln(isa(a, Int));\n\n# supertype -> see type's supertype or parent type\n\nprintln(supertype(Float64));\nprintln(supertype(AbstractFloat));\nprintln(supertype(Real));\nprintln(supertype(Number));\nprintln(supertype(Any));\n\n# Type Conversion\n\nx = 12;\nprintln(typeof(x));\nprintln(typeof(convert(UInt8, x)));\n\n# Type Promotion\n\nprintln(promote(x, 2.3));", "meta": {"hexsha": "ad9a23a7db77814ba6374045799fa7d53f2638ad", "size": 2157, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia-programming/3-basics/types.jl", "max_stars_repo_name": "cadamsmith/julia-programming", "max_stars_repo_head_hexsha": "56435144a2775f5c5e75b3eec9023983caa86d3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia-programming/3-basics/types.jl", "max_issues_repo_name": "cadamsmith/julia-programming", "max_issues_repo_head_hexsha": "56435144a2775f5c5e75b3eec9023983caa86d3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia-programming/3-basics/types.jl", "max_forks_repo_name": "cadamsmith/julia-programming", "max_forks_repo_head_hexsha": "56435144a2775f5c5e75b3eec9023983caa86d3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.8515625, "max_line_length": 67, "alphanum_fraction": 0.7051460362, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7580136763683241}}
{"text": "# ---\n# title: 233. Number of Digit One\n# id: problem233\n# author: zhwang\n# date: 2022-03-12\n# difficulty: Hard\n# categories: Math\n# link: <https://leetcode.com/problems/number-of-digit-one/description/>\n# hidden: true\n# ---\n# \n# Given an integer n, count the total number of digit 1 appearing in all non-\n# negative integers less than or equal to n.\n# \n# **Example:**\n# \n#     \n#     \n#     Input: 13\n#     Output: 6 \n#     Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.\n#     \n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction count_digit_one(n::Int)::Int\n    nums = reverse!([parse(Int, i) for i in string(n + 1)])\n    res, ones = 0, count(==(1), nums)\n    for (i, num) in enumerate(nums)\n        num == 1 && (ones -= 1)\n        res += 10^(i - 1) * (num * ones + (num > 1))\n        res += i > 1 && (10^(i - 2) * (i - 1) * num)\n    end\n    return res\nend\n\n## example: reduce 21413 to 0\n## num: step => reduced num\n## 2141|4|-1: 4*2*1 + 4*0 + (4>1)*10 => 21410-1\n## 214|1|0-1: 1*1*10 + 1*1*1 + (1>1)*10 => 21400-1\n## 21|4|00-1: 4*1*100 + 4*2*10 + (4>1)*100 => 21000-1\n## 2|1|000-1: 1*0*1000 + 1*3*100 + (1>1)*1000 => 20000-1\n## |2|0000-1: 2*0*10000 + 2*4*10000 + (2>1)*10000 => 0\n\n## @lc code=end\n", "meta": {"hexsha": "bd680c7fd35ee9aaebfcaa3f1c661bb5c8fe6e41", "size": 1225, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/233.number-of-digit-one.jl", "max_stars_repo_name": "RexWzh/LeetCode.jl", "max_stars_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/233.number-of-digit-one.jl", "max_issues_repo_name": "RexWzh/LeetCode.jl", "max_issues_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/233.number-of-digit-one.jl", "max_forks_repo_name": "RexWzh/LeetCode.jl", "max_forks_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5208333333, "max_line_length": 80, "alphanum_fraction": 0.5551020408, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.949669363129097, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7580135357126636}}
{"text": "# PS8 Dayuan Xie\r\n# using Pkg\r\n# Pkg.add(\"MultivariateStats\")\r\n\r\nusing Optim\r\nusing HTTP\r\nusing GLM\r\nusing LinearAlgebra\r\nusing Random\r\nusing Statistics\r\nusing DataFrames\r\nusing DataFramesMeta\r\nusing Distributions\r\nusing CSV\r\nusing MultivariateStats\r\n\r\nfunction allwrap()\r\n# Question 1\r\nurl = \"https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2020/master/ProblemSets/PS8-factor/nlsy.csv\"\r\ndf = CSV.read(HTTP.get(url).body)\r\n\r\nols_lm = lm(@formula(logwage ~ black + hispanic + female + schoolt + gradHS + grad4yr), df)\r\nprintln(ols_lm)\r\n\r\n# Question 2\r\nmatrix_asvab = hcat(df.asvabAR, df.asvabCS,df.asvabMK,df.asvabNO,df.asvabPC,df.asvabWK)\r\ncor_asvab = cor(matrix_asvab)\r\nprintln(cor_asvab)\r\n\r\n# Question 3\r\nols_asvab_lm = lm(@formula(logwage ~ black + hispanic + female + schoolt + gradHS + grad4yr + \r\n                               asvabAR + asvabCS + asvabMK + asvabNO + asvabPC + asvabWK), df)\r\nprintln(ols_asvab_lm)\r\n\r\n#  It will be problematic to directly include  the six asvab variables in the regression \r\n#  since these variables are highly correlated with each other.\r\n\r\n# Question 4\r\nasvabMat = (hcat(df.asvabAR, df.asvabCS,df.asvabMK,df.asvabNO,df.asvabPC,df.asvabWK))'\r\nM = fit(PCA, asvabMat; maxoutdim=1)\r\nasvabPCA = MultivariateStats.transform(M, asvabMat)\r\nasvabPCA= vec(asvabPCA')\r\ninsert!(df,7, asvabPCA, :asvabPCA)\r\nols_PCA = lm(@formula(logwage ~ black + hispanic + female + schoolt + gradHS + grad4yr + asvabPCA), df)\r\nprintln(ols_PCA)\r\n\r\n# Question 5\r\nasvabMat = (hcat(df.asvabAR, df.asvabCS,df.asvabMK,df.asvabNO,df.asvabPC,df.asvabWK))'\r\nM = fit(FactorAnalysis, asvabMat; maxoutdim=1)\r\nasvabFactorAnalysis = MultivariateStats.transform(M, asvabMat)\r\nasvabFactorAnalysis= vec(asvabFactorAnalysis')\r\ninsert!(df,8, asvabFactorAnalysis, :asvabFactorAnalysis)\r\nols_FactorAnalysis = lm(@formula(logwage ~ black + hispanic + female + schoolt + gradHS + grad4yr + asvabFactorAnalysis), df)\r\nprintln(ols_FactorAnalysis)\r\n\r\n# Question 6\r\nfunction lgwt(N0::Integer,a::Real=-1,b::Real=1) \r\n    N  = N0-1\r\n    N1 = N+1\r\n    N2 = N+2 \r\n    xu = range(-1,stop=1,length=N1) \r\n    y = cos.((2*(0:N) .+ 1)*pi/(2*N .+ 2))  .+  ( 0.27/N1 ) .* sin.( pi .* xu .* N/N2 ) \r\n    L  = zeros(N1,N2) \r\n    Lp = zeros(N1,N2)  \r\n    y0 = 2    \r\n    vareps = 2e-52\r\n    i = 0\r\n    tracker=0\r\n    it_max=10\r\n\r\n    while (norm(y.-y0,Inf)>vareps && tracker<=it_max)\r\n        d=norm(y.-y0,Inf)\r\n    \r\n        L[:,1]  .= 1\r\n        Lp[:,1] .= 0\r\n        \r\n        L[:,2] .= y\r\n        \r\n        for k=2:N1\r\n            L[:,k+1] = ( (2*k-1)*y .* L[:,k] .- (k-1)*L[:,k-1] )/k\r\n        end\r\n        \r\n        Lp = (N2)*( L[:,N1] .- y .* L[:,N2] )./(1 .- y.^2)\r\n        y0 = y\r\n        y  = y0 - L[:,N2]./Lp\r\n        if norm(y.-y0,Inf)==d\r\n            tracker+=1\r\n        end\r\n        i+=1\r\n\r\n    end\r\n    \r\n    x = (a.*(1 .- y) .+ b .* (1 .+ y))./2\r\n    w=(b-a)./((1 .- y.^2).*Lp.^2)*(N2/N1)^2\r\n    \r\n    return x,w\r\nend\r\n\r\nD= Normal(0,1)\r\nξ= rand(Normal(0,1),size(df,1),1)\r\nM= hcat(df.asvabAR, df.asvabCS,df.asvabMK,df.asvabNO,df.asvabPC,df.asvabWK)\r\nXm= hcat(ones(size(df,1)), df.black, df.hispanic, df.female)\r\nX= hcat(ones(size(df,1)), df.black, df.hispanic, df.female, df.schoolt, df.gradHS, df.grad4yr)\r\nY= df.logwage\r\nL= zeros(size(df,1),1)\r\nfunction likelihoodfunction(sigma,alpha,beta,gamma,delta)\r\n    sigmaj=sigma[1:end-1]\r\n    sigmaw=sigma[end]\r\n    for i= 1: size(df,1)\r\n        for j= 1:6\r\n            part1vec=zeros(6,1)\r\n            part1vec[j,1]=(1/sigma[1,j])*pdf.(D, (M[i,j]-Xm[i,:]*alpha-gamma*ξ[i,1])/1/sigma[1,j])) \r\n            part1=part1vec[1,1]*part1vec[2,1]*part1vec[3,1]*part1vec[4,1]*part1vec[5,1]*part1vec[6,1]\r\n        end\r\n        part2=(1/sigmaw)*pdf.(D,(Y[i,1]-X[i,:]*beta-delta*ξ[i,1])/sigmaw)\r\n        L[i,1]= part1*part2\r\n    end\r\n    return L\r\nend\r\n\r\nnodes, weights = lgwt(7,-4,4)\r\nlikelihood=zeros(size(df,1),1)\r\nfor i= 1: size(df,1)\r\nlikelihood[i,1]=log(sum(weights.* L[i,1].*pdf.(D,nodes)))\r\nend\r\n\r\nsigma_hat = optimize(sigma -> -sum(likelihood), rand(1,7), LBFGS(), Optim.Options(g_tol=1e-6, iterations=100_000, show_trace=true))\r\nprintln(sigma_hat.minimizer)\r\n\r\nend\r\n\r\nallwrap()", "meta": {"hexsha": "467145403c4b8f2f55f80f08812dc2a5c8234e9e", "size": 4118, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS8-factor/PS8_Dayuan Xie.jl", "max_stars_repo_name": "dayuanxie/fall-2020", "max_stars_repo_head_hexsha": "a51f0a924efcffde8f934e987e1306c236eb4a5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSets/PS8-factor/PS8_Dayuan Xie.jl", "max_issues_repo_name": "dayuanxie/fall-2020", "max_issues_repo_head_hexsha": "a51f0a924efcffde8f934e987e1306c236eb4a5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS8-factor/PS8_Dayuan Xie.jl", "max_forks_repo_name": "dayuanxie/fall-2020", "max_forks_repo_head_hexsha": "a51f0a924efcffde8f934e987e1306c236eb4a5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-16T11:54:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T11:54:59.000Z", "avg_line_length": 31.196969697, "max_line_length": 132, "alphanum_fraction": 0.6066051481, "num_tokens": 1527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359675, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7579941248889291}}
{"text": "\"\"\"\n    ∈(M::AbstractMatrix, A::AbstractIntervalMatrix)\n\nCheck whether a concrete matrix is an instance of an interval matrix.\n\n### Input\n\n- `M` -- concrete matrix\n- `A` -- interval matrix\n\n### Output\n\n`true` iff `M` is an instance of `A`\n\n### Algorithm\n\nWe check for each entry in `M` whether it belongs to the corresponding interval\nin `A`.\n\"\"\"\nfunction ∈(M::AbstractMatrix, A::AbstractIntervalMatrix)\n    @assert size(M) == size(A) \"incompatible matrix sizes (M: $(size(M)), A: \" *\n                               \"$(size(A)))\"\n\n    m, n = size(A)\n    @inbounds for j in 1:n\n        for i in 1:m\n            if M[i, j] ∉ A[i, j]\n                return false\n            end\n        end\n    end\n    return true\nend\n\n\"\"\"\n    ⊆(A::AbstractIntervalMatrix, B::AbstractIntervalMatrix)\n\nCheck whether an interval matrix is contained in another interval matrix.\n\n### Input\n\n- `A` -- interval matrix\n- `B` -- interval matrix\n\n### Output\n\n`true` iff `A[i, j] ⊆ B[i, j]` for all `i, j`.\n\"\"\"\nfunction ⊆(A::AbstractIntervalMatrix, B::AbstractIntervalMatrix)\n    @assert size(A) == size(B) \"incompatible matrix sizes $(size(A)) and \" *\n                               \"$(size(B))\"\n\n    m, n = size(A)\n    @inbounds for j in 1:n, i in 1:m\n        if !(A[i, j] ⊆ B[i, j])\n            return false\n        end\n    end\n    return true\nend\n\n\"\"\"\n    ∩(A::IntervalMatrix, B::IntervalMatrix)\n\nIntersect two interval matrices.\n\n### Input\n\n- `A` -- interval matrix\n- `B` -- interval matrix (of the same shape as `A`)\n\n### Output\n\nA new matrix `C` of the same shape as `A` such that\n`C[i, j] = A[i, j] ∩ B[i, j]` for each `i` and `j`.\n\"\"\"\nfunction ∩(A::IntervalMatrix, B::IntervalMatrix)\n    m, n = size(A)\n    @assert size(A) == size(B) \"incompatible matrix sizes (A: $(size(A)), B: \" *\n                               \"$(size(B)))\"\n\n    return IntervalMatrix(map((x, y) -> x ∩ y, A, B))\nend\n\n\n\"\"\"\n    hull(A::IntervalMatrix, B::IntervalMatrix)\n\nFinds the interval hull of two interval matrices. This is equivalent to [`∪`](@ref).\n\n### Input\n\n- `A` -- interval matrix\n- `B` -- interval matrix (of the same shape as `A`)\n\n### Output\n\nA new matrix `C` of the same shape as `A` such that\n`C[i, j] = hull(A[i, j], B[i, j])` for each `i` and `j`.\n\"\"\"\nfunction hull(A::IntervalMatrix, B::IntervalMatrix)\n    @assert size(A) == size(B) \"incompatible matrix sizes (A: $(size(A)), B: \" *\n                               \"$(size(B)))\"\n\n    return IntervalMatrix(map((x, y) -> hull(x, y), A, B))\nend\n\n\"\"\"\n    ∪(A::IntervalMatrix, B::IntervalMatrix)\n\nFinds the interval union (hull) of two interval matrices.\nThis is equivalent to [`hull`](@ref).\n\n### Input\n\n- `A` -- interval matrix\n- `B` -- interval matrix (of the same shape as `A`)\n\n### Output\n\nA new matrix `C` of the same shape as `A` such that\n`C[i, j] = A[i, j] ∪ B[i, j]` for each `i` and `j`.\n\"\"\"\n∪(A::IntervalMatrix, B::IntervalMatrix) = hull(A, B)\n", "meta": {"hexsha": "0592026dc7efd7b1dbd5c1d2104babf3b4926376", "size": 2873, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operations/setops.jl", "max_stars_repo_name": "JuliaReach/IntervalMatrices.jl", "max_stars_repo_head_hexsha": "2689974c1b5bc57daf4eccf37552f912986f1b27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-03-07T06:01:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T17:54:28.000Z", "max_issues_repo_path": "src/operations/setops.jl", "max_issues_repo_name": "JuliaReach/IntervalMatrices.jl", "max_issues_repo_head_hexsha": "2689974c1b5bc57daf4eccf37552f912986f1b27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113, "max_issues_repo_issues_event_min_datetime": "2018-02-12T22:54:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T19:16:29.000Z", "max_forks_repo_path": "src/operations/setops.jl", "max_forks_repo_name": "JuliaReach/IntervalMatrices.jl", "max_forks_repo_head_hexsha": "2689974c1b5bc57daf4eccf37552f912986f1b27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:30:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-30T18:05:43.000Z", "avg_line_length": 22.984, "max_line_length": 84, "alphanum_fraction": 0.5718760877, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7579941143062219}}
{"text": "using DataFrames\n\nfunction lagrangianpolynomial(np::Int, x::Vector{Float64}, y::Vector{Float64}, xi::Vector{Float64})\n  local yi = Vector{Float64}(undef, length(xi))\n  m = sort(hcat(x, y), dims=1)\n  for l in 1:length(xi)\n    for i in 1:np\n      term = 1.0\n      for j in 1:np\n        j !== i && (term *= (xi[l] - m[j, 1])/(m[i, 1] - m[j, 1]))\n      end\n      yi[l] += term * m[i, 2]\n    end\n  end\n  columns=[]\n  push!(columns, m[:,1])\n  push!(columns, m[:,2])\n  df = DataFrame(columns, [:x, :y])\n  \n  columns=[]\n  push!(columns, xi)\n  push!(columns, yi)\n  dfxi = DataFrame(columns, [:xi, :yi])\n  \n  (df, dfxi)\nend", "meta": {"hexsha": "054103a19aa8d9b400a9caca544661759632a70b", "size": 613, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ch05/lagrangianpolynomial.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "src/ch05/lagrangianpolynomial.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "src/ch05/lagrangianpolynomial.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 23.5769230769, "max_line_length": 99, "alphanum_fraction": 0.5464926591, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7579941093111255}}
{"text": "function modalparam(A,C,dt)\n\t# \n\t# Compute modal parameters from A, C and dt\n\t#\n\t# javier.cara@upm.es, 2016-02 \n\t#  \n\n\tno,ns = size(C)\n\t\n\t# allocating\n\twm1 = zeros(1,ns)\n\tzm1 = zeros(1,ns)\n\tvm1 = zeros(no,ns)\n\t\n\t# eigenvalues and eigenvectors\n\tD,V = eig(A)\n\t\n\t# C*V\n\tvm0 = C*V\n\t\n\ti = 1\n\tii = 1\n\tfm1 = zeros(Number,no,ns) # can be real or complex numbers\n\twhile i < ns\n\t\td = D[i]\n\t\tif abs(imag(d)) > 1e-10 # complex number\n\t\t\twm1[ii] = abs(log(d))/dt\n\t\t\tzm1[ii] = -real(log(d))/(wm1[ii]*dt)\n\t\t\t\t\t\t\t\t\n\t\t\t# modal shapes normalized with max component = 1\n\t\t\tmaxval = vm0[1,i]\n\t\t\tfor j in 2:no\n\t\t\t\tif abs(vm0[j,i]) > abs(maxval)\n\t\t\t\t\tmaxval = vm0[j,i]\n\t\t\t\tend\n\t\t\tend\n\t\t\tvm1[:,ii] = real( vm0[:,i]/maxval )\n\t\t\t\n\t\t\ti = i+2\n\t\t\tii = ii+1\n\t\t\t\n\t\telse\n\t\t\t# real eigenvalue\n\t\t\ti = i+1\n\t\tend\n\tend\n\t\n\t# deleting zero values\n\twm = wm1[1:ii-1]\n\tzm = zm1[1:ii-1]\t     \t\n\tvm = vm1[:,1:ii-1]        \n        \n\t# sorting frequencies\t\t\t\n\tpos=sortperm(wm)\n\twm = wm[pos]\n\tzm = zm[pos]\t\n\tvm = vm[:,pos]\n\t\n\treturn wm,zm,vm\n\t\nend\n\n", "meta": {"hexsha": "59a644a138733135d0c586e1ae072a188f5a774f", "size": 1004, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/modalparam.jl", "max_stars_repo_name": "javiercara/ModalSSM.jl", "max_stars_repo_head_hexsha": "eb1c5200c34f3f5662ccf11f618df209e4b91111", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/modalparam.jl", "max_issues_repo_name": "javiercara/ModalSSM.jl", "max_issues_repo_head_hexsha": "eb1c5200c34f3f5662ccf11f618df209e4b91111", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/modalparam.jl", "max_forks_repo_name": "javiercara/ModalSSM.jl", "max_forks_repo_head_hexsha": "eb1c5200c34f3f5662ccf11f618df209e4b91111", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.9365079365, "max_line_length": 59, "alphanum_fraction": 0.5458167331, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7579941087702801}}
{"text": "import Base.*\n\n\nexport S¹\nexport U1\n\n\n\"\"\"\n    Represents a point in a one-sphere.\n\"\"\"\nabstract type S¹ end\n\n\n\"\"\"\n    Represents a point in U(1).\n\nfield: α.\n\"\"\"\nstruct U1 <: S¹\n    r::Float64\n    U1(z::Complex) = begin\n        @assert(isapprox(abs(z), 1), \"The magnitude must be equal to 1, but it's $(abs(z)).\")\n        θ = angle(z) ≥ 0 ? angle(z) : π + angle(z)\n        new(θ)\n    end\n    U1(α::Real) = begin\n        #@assert(-pi ≤ α ≤ pi, \"The phase angle must be in the interval [-π, π].\")\n        new(float(α))\n    end\nend\n\n\nBase.angle(u::U1) = u.r\n*(u1::U1, u2::U1) = U1(u1.r + u2.r)\n*(u::U1, scale::Float64) = U1(u.r * scale)\n*(scale::Float64, u::U1) = U1(u.r * scale)\nBase.isapprox(u1::U1, u2::U1) = isapprox(u1.r, u2.r)\n", "meta": {"hexsha": "301bf664e670c34b75126bf88346d7b4297452ca", "size": 728, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geometry/s1.jl", "max_stars_repo_name": "iamazadi/geometrizer", "max_stars_repo_head_hexsha": "73a97d879d06a1466ff3b966b2ea8e8a846d4c78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-03-12T02:01:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-19T09:32:54.000Z", "max_issues_repo_path": "src/geometry/s1.jl", "max_issues_repo_name": "iamazadi/Porta", "max_issues_repo_head_hexsha": "73a97d879d06a1466ff3b966b2ea8e8a846d4c78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geometry/s1.jl", "max_forks_repo_name": "iamazadi/Porta", "max_forks_repo_head_hexsha": "73a97d879d06a1466ff3b966b2ea8e8a846d4c78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1578947368, "max_line_length": 93, "alphanum_fraction": 0.5453296703, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7579941082811047}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.0\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ a82f22e4-f35b-461a-b481-1dff43722e44\nusing StaticArrays\n\n# ╔═╡ d42f842d-6c2a-40db-b0c4-e936244a9e7c\nusing BenchmarkTools\n\n# ╔═╡ 99b5c818-a825-4939-849e-1cade802f63d\nusing Measurements\n\n# ╔═╡ d6564250-f646-40de-9463-a956af1a5b1d\nusing ForwardDiff\n\n# ╔═╡ d2f4d622-8e35-4be3-b421-39b28a748cab\nusing CellListMap\n\n# ╔═╡ f049ab19-7ecf-4c65-bf6d-21352c1fe767\nusing FastPow\n\n# ╔═╡ 7c792b6b-b6ee-4e30-88d5-d0b8064f2734\nbegin\n    using Plots\n    plot_font = \"Computer Modern\"\n    default(\n        fontfamily=plot_font,\n        linewidth=2, framestyle=:box, label=:none, grid=false,\n        size=(400,400)\n    )    \nend\n\n# ╔═╡ febe8c06-b3aa-4db1-a3ea-fdc2a81bdebd\nusing Printf\n\n# ╔═╡ a756dd18-fac6-4527-944e-c16d8cc4bf95\nbegin\n    using PlutoUI\n    TableOfContents()\nend\n\n# ╔═╡ a87fad48-73c1-4a08-a6f1-aae759b3c6fc\nmd\"\"\"\n# Particle Simulations with Julia\n\nLeandro Martínez\n\nInstitute of Chemistry - University of Campinas\n\n[http://m3g.iqm.unicamp.br](http://m3g.iqm.unicamp.br) - \n[https://github.com/m3g](https://github.com/m3g)\n\n\"\"\"\n\n# ╔═╡ 172227c2-b27a-40db-91f4-9566c2f6cf52\nmd\"\"\"\n# Outline\n\n- Elements of a particle simulation\n- Benchmarking vs. a conventional compiled language (Fortran)\n- Exploring the generic character of functions\n- Differentiable simulations and parameter fitting\n- Using cell lists\n- An efficient and generic cell list implementation\n- The Packmol strategy\n- Benchmarking vs. NAMD\n- Remarks\n\n\"\"\"\n\n# ╔═╡ 4b484cf6-4888-4f04-b3fd-94862822b0c0\nmd\"\"\"\n# Defining the type of particle\n\nWe define a simple point in 2D space, with coordinates `x` and `y`. The point will be defined with the aid of the `StaticArrays` package, which provides convenient constructors for this type of variable, and all the arithmetics. The memory layout of a vector of these points is identical to that of a `N×M` matrix, where `N` is the dimensio nf the space (2D here) and `M` is the number of points. Julia is column-major, thus this is the most efficient memory layout for this type of computation.\n\"\"\"\n\n# ╔═╡ 8c444ee4-8c77-413a-bbeb-9e5ae2428876\nstruct Vec2D{T} <: FieldVector{2,T}\n    x::T\n    y::T\nend\n\n# ╔═╡ a0de01b5-779a-48c0-8d61-12b02a5f527e\nmd\"\"\"\nFor convenience, here we will also define a function that returns a random point, given a range of coordinates:\n\"\"\"\n\n# ╔═╡ 532eb3bc-5522-4348-afa5-5336ec6752c7\nmd\"\"\"\nIn defining the function above we took care of making it generic for the type and dimension of the point desired, such that we do not need to redefine it later when peforming simulations with different point structures. \n\"\"\"\n\n# ╔═╡ dc5f7484-3dc3-47a7-ad4a-30f97fc14d11\nmd\"\"\"\n## Force between a pair of particles \n\nInitially, the energy function will be a soft potential, which is zero for distances greater than a cutoff, and increasing quadratically for distances smaller than the cutoff:\n\nIf $d = ||\\vec{y}-\\vec{x}||$ is the norm of the relative position of two points, we have:\n\n$$u(\\vec{x},\\vec{y},c)=\n\\begin{cases}\n(d-c)^2 &\\textrm{if} & d\\leq c \\\\\n0 & \\textrm{if} & d > c \\\\\n\\end{cases}$$\n\nfor which the forces are\n\n$$\\vec{f_x}(\\vec{x},\\vec{y},c)=\n\\begin{cases}\n2(d-c)\\frac{(\\vec{y}-\\vec{x})}{d} &\\textrm{if} & d\\leq c \\\\\n\\vec{0} & \\textrm{if} & d > c \\\\\n\\end{cases}$$\nand\n$$\\vec{f_y} = -\\vec{f_x}$$.\n\n\n\"\"\"\n\n# ╔═╡ ab3ff21b-bf82-4d8c-abd1-c27418956ed8\nmd\"\"\"\nThe standard Julia `LinearAlgebra` library provides a `norm` function, and there is no reason not to use it (although a manual definition of the same function can also be easily implemented):\n\"\"\"\n\n# ╔═╡ 7a1db355-bba9-4322-9fb4-a6d7b7bdd60d\nimport LinearAlgebra: norm\n\n# ╔═╡ cc49ef04-08d8-42bb-9170-9db64e275a51\nmd\"\"\"\nThe energy and force functions are clear to read:\n\"\"\"\n\n# ╔═╡ d00e56f2-9d3a-4dd3-80eb-3201eff39b96\nmd\"\"\"\nAnd for a unidimensional case, with a defined cutoff, look like:\n\"\"\"\n\n# ╔═╡ b5c09cd3-6063-4a36-96cd-2d128aa11b82\nconst cutoff = 5.\n\n# ╔═╡ 7719b317-e85b-4583-b401-a8614d4b2373\nmd\"\"\"\nThe function that will compute the force over all pairs will just *naively* run over all (non-repeated) the pairs. The function `forces!` will receive as a parameter the function that computes the force between pairs, such that this pairwise function can be changed later. \n\nInside `forces!`, the `force_pair` function will receive four parameters: the indexes of the particles and their positions. We will use the indexes later. \n\"\"\"\n\n# ╔═╡ 144119ad-ab88-4165-883a-f2fc2464a838\nmd\"\"\"\nLet us create some points to explain how the function will be called. \n\"\"\"\n\n# ╔═╡ dd9e4332-2908-40ef-b461-6b571df56cf4\nmd\"\"\"\nThe function `force_pair`, will be passed to the function that computes the forces to all pairs as *closure*, which will capture the value of the cutoff. The closure also allows us to ignore the indexes of the particles, which are expected by the inner implementation of the function inside `forces`. For example:\n\"\"\"\n\n# ╔═╡ 017cd6a8-712d-4ec5-b31f-7f1f507764f2\nmd\"\"\"\nThe third argument of `forces!` function is a *closure*, which can be read as: it is the function that *given* `(i,j,x,y)`, returns `fₓ(x,y,cutoff)`. Thus, it is consistent with the internal call of `fₓ` of `forces!`, and *closes over* the additional parameter `cutoff` required for the computation. \n\"\"\"\n\n# ╔═╡ b5206dd5-1f46-4437-929b-efd68393b12b\nmd\"\"\"\n# Performing a particle simulation\n\nNow, given the function that computes the forces, we can perform a particle simulation. We will use a simple Euler integration scheme, and the algorithm will be:\n\n1. Compute forces at time $t$ from positions $x$:\n$f(t) = f(x)$\n\n2. Update the positions (using $a = f/m$):\n$x(t + dt) = x(t) + v(t)dt + a(t)dt^2/2$\n\n3. Update the velocities:\n$v(t+dt) = v(t) + a(t)dt$\n\n4. Goto 1.\n\n## The actual simulation code is as short:\n\"\"\"\n\n# ╔═╡ eb5dc224-1491-11ec-1cae-d51c93cd292c\nfunction md(\n    x0::Vector{T},\n    v0::Vector{T},\n    mass,dt,nsteps,isave,forces!\n) where T\n    x = copy(x0)\n    v = copy(v0)\n    a = similar(x0)\n    f = similar(x0)\n    trajectory = [ copy(x0) ] # will store the trajectory\n    for step in 1:nsteps\n        # Compute forces\n        forces!(f,x)\n        # Accelerations\n        @. a = f / mass\n        # Update positions\n        @. x = x + v*dt + a*dt^2/2\n        # Update velocities\n        @. v = v + a*dt\n        # Save if required\n        if mod(step,isave) == 0\n            println(\"Saved trajectory at step: \",step)\n            push!(trajectory,copy(x))\n        end\n    end\n    return trajectory\nend\n\n# ╔═╡ 594ba1d6-2dae-4f20-9546-f52fac17c2f0\nmd\"\"\"\nBy using a parametric type of input (i. e. `Vector{T}`) we can guarantee that an error will be thrown if the positions and velocities are not provided as the same type of variable. \n\nThe `@.` notation is very common in Julia and means that the computation will be performed element-wise.\n\"\"\"\n\n# ╔═╡ 66c7d960-7e05-4613-84e8-2a40fe40dc3d\nmd\"\"\"\n## Let us run the simulation!\n\"\"\"\n\n# ╔═╡ e717a8d9-ccfb-4f89-b2a2-f244f108b48d\nmd\"\"\"\nHere we generate random positions and velocities, and use masses equal to `1.0` for all particles.\n\"\"\"\n\n# ╔═╡ eab7b195-64d5-4587-8687-48a673ab091b\nmd\"\"\"\n## Using periodic boundary conditions\n\nOur particles just explode, since they have initial random velocities and there are only repulsive interactions. \n\nWe have a more interesting dynamics if we use periodic boundary conditions. To do so, we will update how the forces are computed.\n\"\"\"\n\n# ╔═╡ 34dc72dc-4864-47c0-b730-183f67e7aea3\nmd\"\"\"\n## Wrapping of coordinates\n\nThe following function defines how to wrap the coordinates on the boundaries, for a square or cubic box of side `side`:\n\"\"\"\n\n# ╔═╡ 02d9bf3b-708c-4293-b198-9043b334ff7e\nmd\"\"\"\nThis allows writting the force computation now as:\n\"\"\"\n\n# ╔═╡ 0a5282ee-c88a-4bcc-aca2-477f28e9e04d\nmd\"\"\"\nOur box has a side of 100:\n\"\"\"\n\n# ╔═╡ b2a4a505-47ff-40bb-9a6d-a08d91c53217\nconst side = 100.\n\n# ╔═╡ fcff6973-012a-40fc-a618-f6262266287a\nmd\"\"\"\nTo run the simulation with the new periodic forces, we use the same `md` function, just passing the new `fₓ` function in the *closure* definition:\n\"\"\"\n\n# ╔═╡ 14867ffd-cde5-43f8-8399-01169ee29b73\nmd\"\"\"\nA relevant detail here is that we could use the same `fₓ` name for the function, because it receives the `side` of the box as a parameter, and multiple-dispatch then chooses the correct method automaticaly. \n\"\"\"\n\n# ╔═╡ c4798182-de75-4b59-8be7-f7cf1051364d\nmd\"\"\"\nWhile plotting the trajectory, we will wrap the coordinates:\n\"\"\"\n\n# ╔═╡ 22fb0386-d4fa-47b9-ac31-decf2731cbc1\nmd\"\"\"\n## Benchmarking\n\"\"\"\n\n# ╔═╡ 8e23a3ea-3039-4a5f-b37f-c4710153938e\nmd\"\"\"\nBenchmarkming in Julia can be done with the `@time` macro or the macros from the `BenchmarkTools` package. Compilation occurs on the first call to each method, and the macros from `BenchmarkTools` discount the compilation time automatically. \n\"\"\"\n\n# ╔═╡ 2a3e7257-63ad-4761-beda-cec18b91f99c\nmd\"\"\"\n\nSomething of the order of `200ms` and `200KiB` of allocations does not seem bad, but it doesn't mean anything either. What is interesting to point here is just that this code, compared to ahead-of-time compiled language like Fortran, is completely comparable in terms of performance, as [this benchmark](https://github.com/m3g/2021_FortranCon/tree/main/benchmark_vs_fortran) shows. \n\n\"\"\"\n\n# ╔═╡ 49b1f040-929a-4238-acd9-6554757b592c\nmd\"\"\"\n# Exploring generics\n\n## Running the simulations in 3D\n\nNot much is needed to just run the simulation in three dimensions. We only need to define our 3D point:\n\"\"\"\n\n# ╔═╡ 26d5c6e9-a903-4792-a0e0-dec1a2e86a01\nstruct Vec3D{T} <: FieldVector{3,T}\n    x::T\n    y::T\n    z::T\nend\n\n# ╔═╡ 2aef27bd-dea6-4a93-9d0f-b9249c9dd2cd\nmd\"\"\"\nThat is enough such that we can run the simulations in 3D:\n\"\"\"\n\n# ╔═╡ b6dcb9a3-59e3-4eae-9399-fb072c704f1a\nmd\"\"\"\n## Automatic error propagation\n\nPerforming simulations in different dimensions is not the most interesting, or most useful property of generic programming. We can, more interestingly, propagate the error in the positions of the particles, simply by defining a type of particle that carries both the position and the cumulative error. \n\nA small example of how that can be done is shown. First, we create a type of variable that carries both the coordinates and the uncertainty on the coordinates:\n\"\"\"\n\n# ╔═╡ e4657169-1bb2-4d4a-ac9d-adc80499d07d\nstruct MyMeasurement{T}\n    x::T\n    Δx::T\nend\n\n# ╔═╡ 5d395353-5681-4780-983e-902fdb89eaf2\nmd\"\"\"\nand we will overload the printing of this variables to make things prettier:\n\"\"\"\n\n# ╔═╡ e9376a4b-3d60-42eb-8681-cd2bcec13fe8\nBase.show(io::IO,m::MyMeasurement) = println(io,\" $(m.x) ± $(m.Δx)\")\n\n# ╔═╡ c5cdd71f-5ded-482f-9205-c13f01a14d0b\nm = MyMeasurement(1.0,0.1)\n\n# ╔═╡ a0993a1f-60a6-45b5-815e-676c49a9f049\nmd\"\"\"\nNow we define the arithmetics for this type of variable. For example, the sum of two `MyMeasurement`s sums the uncertainties, but so do the subtraction. The other uncertainties are also propagaged linearly, according to the first derivative of their operations relative to the values:\n\"\"\"\n\n# ╔═╡ 4e7f8db4-b5cc-4a3e-9fa7-e62d8f2a36ac\nbegin\n    import Base: -, +, *, /, ^, sqrt\n    +(m1::MyMeasurement,m2::MyMeasurement) = MyMeasurement(m1.x+m2.x,m1.Δx+m2.Δx)\n    -(m1::MyMeasurement,m2::MyMeasurement) = MyMeasurement(m1.x-m2.x,m1.Δx+m2.Δx)\n    *(α,m::MyMeasurement) = MyMeasurement(α*m.x,sign(α)*α*m.Δx)\n    *(m::MyMeasurement,α) = α*m\n    /(m::MyMeasurement,α) = inv(α)*m\n    sqrt(m::MyMeasurement{T}) where T = MyMeasurement(sqrt(m.x),inv(2*sqrt(m.x))*m.Δx)\n    ^(m::MyMeasurement{T},n) where T = MyMeasurement{T}(m.x^n,n*m.x^(n-1)*m.Δx)\nend\n\n# ╔═╡ f87e4036-8f82-41c7-90c1-daa5f677488d\nfunction random_point(::Type{PointType},range) where PointType \n    dim = length(PointType)\n    T = eltype(PointType)\n    p = PointType(\n        range[begin] + rand(T)*(range[end]-range[begin]) for _ in 1:dim\n    )\n    return p\nend\n\n# ╔═╡ df33b999-4a42-4133-bf59-5a65240790cf\nfunction energy(x::T,y::T,cutoff) where T\n    Δv = y - x\n    d = norm(Δv)\n    if d > cutoff\n        energy = zero(T)\n    else\n        energy = (d - cutoff)^2\n    end\n    return energy\nend\n\n# ╔═╡ 0f52365d-34f4-46ed-923e-3ea31c6db0ca\nfunction fₓ(x::T,y::T,cutoff) where T\n    Δv = y - x\n    d = norm(Δv)\n    if d > cutoff\n        fₓ = zero(T)\n    else\n        fₓ = 2*(d - cutoff)*(Δv/d)\n    end\n    return fₓ\nend\n\n# ╔═╡ f58769a6-a656-42a3-8bc6-c204d4cfd897\nfunction forces!(f::Vector{T},x::Vector{T},fₓ::F) where {T,F}\n    fill!(f,zero(T))\n    n = length(x)\n    for i in 1:n-1\n        for j in i+1:n\n            fᵢ = fₓ(i,j,x[i],x[j])\n            f[i] += fᵢ \n            f[j] -= fᵢ\n        end\n    end\n    return f\nend\n\n# ╔═╡ beeb3335-5c49-47de-a1d3-3eef5f9479f1\nfunction wrap(x,side)\n    x = rem(x,side)\n    if x >= side/2\n        x -= side\n    elseif x < -side/2\n        x += side\n    end\n    return x\nend\n\n# ╔═╡ 0967b90d-ac88-476d-a57a-7c38dfa82204\nfunction fₓ(x::T,y::T,cutoff,side) where T\n    Δv = wrap.(y - x, side)\n    d = norm(Δv)\n    if d > cutoff\n        fₓ = zero(T)\n    else\n        fₓ = 2*(d - cutoff)*(Δv/d)\n    end\n    return fₓ\nend\n\n# ╔═╡ 36da3e92-000c-4d4b-9abf-4cd588b3a354\nmd\"\"\"\nWith such definitions, we can operate over variables of type `MyMeasurement`, propagating automatically the uncertainty along the operations:\n\"\"\"\n\n# ╔═╡ 70eb2e0a-a5c8-4975-8f6c-589035bea29c\nsqrt((2*(m + 4*m)^2/3))\n\n# ╔═╡ b4646a29-3efd-4bd1-bffc-3575559de937\nmd\"\"\"\nAnd we can also define a 2D (or 3D) point of values with uncertainties, without changing the previous definitions of these points:\n\"\"\"\n\n# ╔═╡ d32743c0-fc80-406f-83c5-4528e439589a\nx = Vec2D(MyMeasurement(1.0,0.1),MyMeasurement(2.0,0.2))\n\n# ╔═╡ 98478246-5940-4828-a8f1-9c9fa990676d\nmd\"\"\"\nAnd now operations on this point propagate the uncertainties of the componentes as well:\n\"\"\"\n\n# ╔═╡ 310f247e-3fe8-4621-ae0b-b5ee38d2ee89\n2*x .+ sqrt.(x)\n\n# ╔═╡ 8267220a-f06e-4761-b310-00f8ba44e4b1\nmd\"\"\"\nProgapating uncertainties in more general scenarios requires the definition of other propagation rules. Also, one might want to consider the correlation between variables, which makes the propagation rules more complicated and expensive.\n\nFortunately, there are some package that provide the error propagation in more general scenarios, by defining the proper progagation rules. \n\nHere, we use the `Measurements`  package.\n\"\"\"\n\n# ╔═╡ ce916139-221a-462e-877f-88212663c05e\nmd\"\"\"\n### Using `Measurements`\n\"\"\"\n\n# ╔═╡ 8e2903be-4975-4e14-84ed-6e712f47fe47\nmd\"\"\"\nUsing `Measurments`  we do not need to change anything in our previous code, but only redefine the content of our points, which will now carry in each coordinate the position and the error in the position, accumulated from an initial uncertainty:\n\"\"\"\n\n# ╔═╡ 418f31bb-81d5-459b-b402-4fd4e3f4ab27\nmd\"\"\"\nWe need to redefine your initial random point generator only:\n\"\"\"\n\n# ╔═╡ 05402cbd-78c6-4234-8680-c351c8c37778\nfunction random_point(::Type{Vec2D{Measurement{T}}},range,Δ) where T    \n    p = Vec2D(\n        range[begin] + rand(T)*(range[end]-range[begin]) ± rand()*Δ,\n        range[begin] + rand(T)*(range[end]-range[begin]) ± rand()*Δ\n    )\n    return p\nend\n\n# ╔═╡ 356ac5a4-c94e-42cb-a085-0198b29c7e52\nx0 = [ random_point(Vec2D{Float64},(0,100)) for _ in 1:100] \n\n# ╔═╡ d23b4a92-055e-4ed7-bd46-8a3c59312993\nf = similar(x0)\n\n# ╔═╡ e6e29d1e-9a93-49db-a358-6b66f0bc3433\nforces!(\n    f,\n    x0, \n    (i,j,x,y) -> fₓ(x,y,cutoff) # closure\n) \n\n# ╔═╡ 3755a4f3-1842-4de2-965e-d294c06c54c7\ntrajectory = md((\n    x0 = [random_point(Vec2D{Float64},(-50,50)) for _ in 1:100 ], \n    v0 = [random_point(Vec2D{Float64},(-1,1)) for _ in 1:100 ], \n    mass = [ 1.0 for _ in 1:100 ],\n    dt = 0.1,\n    nsteps = 1000,\n    isave = 10,\n    forces! = (f,x) -> forces!(f,x, (i,j,p1,p2) -> fₓ(p1,p2,cutoff))\n)...)\n\n# ╔═╡ 985b4ffb-7964-4b50-8c2f-e5f45f352500\ntrajectory_periodic = md((\n    x0 = [random_point(Vec2D{Float64},(-50,50)) for _ in 1:100 ], \n    v0 = [random_point(Vec2D{Float64},(-1,1)) for _ in 1:100 ], \n    mass = [ 10.0 for _ in 1:100 ],\n    dt = 0.1,\n    nsteps = 1000,\n    isave = 10,\n    forces! = (f,x) -> forces!(f,x,(i,j,p1,p2) -> fₓ(p1,p2,cutoff,side))\n)...)\n\n# ╔═╡ 1ad401b5-20b2-489b-b2aa-92f729b1d725\n@benchmark md($(\n    x0 = [random_point(Vec2D{Float64},-50:50) for _ in 1:100 ], \n    v0 = [random_point(Vec2D{Float64},-1:1) for _ in 1:100 ], \n    mass = [ 1.0 for _ in 1:100 ],\n    dt = 0.1,\n    nsteps = 1000,\n    isave = 10,\n    forces! = (f,x) -> forces!(f,x, (i,j,p1,p2) -> fₓ(p1,p2,cutoff,side))\n)...)\n\n# ╔═╡ 0546ee2d-b62d-4c7a-8172-ba87b3c1aea4\ntrajectory_periodic_3D = md((\n    x0 = [random_point(Vec3D{Float64},-50:50) for _ in 1:100 ], \n    v0 = [random_point(Vec3D{Float64},-1:1) for _ in 1:100 ], \n    mass = [ 1.0 for _ in 1:100 ],\n    dt = 0.1,\n    nsteps = 1000,\n    isave = 10,\n    forces! = (f,x) -> forces!(f,x,(i,j,p1,p2) -> fₓ(p1,p2,cutoff,side))\n)...)\n\n# ╔═╡ 4e97f24c-c237-4117-bc57-e4e88c8fb8d2\nmd\"\"\"\nWhich generates random points carrying an initial uncertainty we defined:\n\"\"\"\n\n# ╔═╡ b31da90d-7165-42de-b18d-90584affea03\nrandom_point(Vec2D{Measurement{Float64}},(-50,50),1e-5)\n\n# ╔═╡ 5f37640b-ffd9-4877-a78c-a699b2671919\nmd\"\"\"\nThat given, the same simulation codes can be used to run the particles simulations while propagating the uncertinties of the coordinates of each point:\n\"\"\"\n\n# ╔═╡ 1d6eedfd-d013-4557-9cf2-103f8fb7b72a\nmd\"\"\"\nThe trajectory, of course, looks the same (except that we ran less steps, because propagating the error is expensive):\n\"\"\"\n\n# ╔═╡ c003a61d-a434-4d7b-9214-5b52aa044248\nmd\"\"\"\nBut now we have an estimate of the error of the positions, propagated from the initial uncertainty:\n\"\"\"\n\n# ╔═╡ 63eb391f-0238-434a-bc3a-2fa8ed41448e\nmd\"\"\"\n### Planetary motion\n\nPerhaps this is more interesting to see in a planetary trajectory:\n\"\"\"\n\n# ╔═╡ 7b9bb0fd-34a5-42e1-bc35-7259447b73d0\nfunction gravitational_force(i,j,x,y,mass)\n    G = 0.00049823382528 # MKm³ / (10²⁴kg days²)\n    dr = y - x\n    r = norm(dr)\n    return G*mass[i]*mass[j]*dr/r^3\nend\n\n# ╔═╡ 6a4e0e2e-75c5-4cab-987d-3d6b62f9bb06\nmd\"\"\"\nNote that now we need the indexes of the particles to be able to pass the information of their masses. \n\nA set of planetary positions and velocities is something that we have to obtain [experimentaly](https://nssdc.gsfc.nasa.gov/planetary/factsheet/). Here, the distance units $10^6$ km), and time is in days. Thus, velocities are in MKm per day.\n\nThe uncertainty of the positions will be taken as the diameter of each planet. In this illustrative example we will not add uncertainties to the velcities. \n\"\"\"\n\n# ╔═╡ c91862dd-498a-4712-8e3d-b77e088cd470\nplanets_x0 = [\n    Vec2D(  0.0 ±  1.39    , 0. ±  1.39    ), # \"Sun\"\n    Vec2D( 57.9 ±  4.879e-3, 0. ±  4.879e-3), # \"Mercury\"\n    Vec2D(108.2 ± 12.104e-3, 0. ± 12.104e-3), # \"Venus\"\n    Vec2D(149.6 ± 12.756e-3, 0. ± 12.756e-3), # \"Earth\"\n    Vec2D(227.9 ±  6.792e-3, 0. ±  6.792e-3), # \"Mars\"\n]\n\n# ╔═╡ a08d6e6d-ddc4-40aa-b7c4-93ea03191415\nplanets_v0 = [\n    Vec2D(0. ± 0.,   0.0 ± 0.), # \"Sun\"\n    Vec2D(0. ± 0.,  4.10 ± 0.), # \"Mercury\"\n    Vec2D(0. ± 0.,  3.02 ± 0.), # \"Venus\"\n    Vec2D(0. ± 0.,  2.57 ± 0.), # \"Earth\"\n    Vec2D(0. ± 0.,  2.08 ± 0.)  # \"Mars\"  \n]\n\n# ╔═╡ a356e2cc-1cb1-457a-986c-998cf1efe008\nmd\"\"\"\nAnd the masses are given in units of $10^{24}$ kg:\n\"\"\"\n\n# ╔═╡ 57141f7c-9261-4dc5-98e4-b136a15f86fc\nconst masses = [ 1.99e6, 0.330, 4.87, 5.97, 0.642 ]\n\n# ╔═╡ 055e32d7-073c-40db-a267-750636b9f786\nmd\"\"\"\nLet us see the planets orbiting the sun:\n\"\"\"\n\n# ╔═╡ aaa97ce4-a5ff-4332-89a2-843cee2e5b6d\ntrajectory_planets = md((\n    x0 = planets_x0, \n    v0 = planets_v0, \n    mass = masses,\n    dt = 1, # days\n    nsteps = 2*365, # two Earth years\n    isave = 1, # save every day\n    forces! = (f,x) -> forces!(\n        f,x, (i,j,p1,p2) -> gravitational_force(i,j,p1,p2,masses)\n    )\n)...)\n\n# ╔═╡ 93697e4d-369b-48e9-8b28-a0ff58604d02\nmd\"\"\"\nIf you are wandering why the errors oscilate, it is because the trajectories are periodic. Whenever all possible trajectories starting from within the uncertainty interval cross each other, the error of the predicted position is independent on the initial coordinates. Thus, the derivative of the uncertainty is zero relative to the position, and so it the propagated uncertainty when using a linear propagation rule.\n\"\"\"\n\n# ╔═╡ c4344e64-aa22-4328-a97a-71e44bcd289f\nmd\"\"\"\nOne thing I don't like, though, is that in two years the Earth did not complete two  revolutions around the Sun. Something is wrong with our data. Can we improve that?\n\"\"\"\n\n# ╔═╡ 827bda6f-87d4-4d36-8d89-f144f4595240\nmd\"\"\"\n## We can differentiate everything!\n\nPerhaps astoningshly (at least for me), our simulation is completely differentiable. That means that we can tune the parameters of the simulation, and the data, using optimization algorithms that require derivatives. \n\nHere we speculate that what was wrong with our data was that the initial position of the Earth was somewhat out of place. That caused the Earth orbit to be slower than it should.\n\nWe will define, then, an objective function which returns the displacement of the Earth relative to its initial position (at day one) after one year. Our goal is that after one year the Earth returns to its initial position.\n\"\"\"\n\n# ╔═╡ 1ff4077a-4742-4c5e-a8d6-c4699469a683\nmd\"\"\"\nFirst, se define a function that executes a simulation of *one year* of an Earth orbit, starting from a given position for the Earth `x` coordinate as a parameter. We will be careful in making all other coordinates of the same type of `x`, so that the generality of the type of variable being used is kept consistent:\n\"\"\"\n\n# ╔═╡ 4a75498d-8f4e-406f-8b01-f6a5f153919f\nfunction earth_orbit(x::T=149.6,nsteps=365,isave=1) where T\n    x0 = [\n        Vec2D( zero(T), zero(T)), # \"Sun\"\n        Vec2D(       x, zero(T))  # \"Earth\"\n    ]\n    v0 = [ \n        Vec2D( zero(T), zero(T)), # \"Sun\"\n        Vec2D( zero(T), 2.57*one(T)), # \"Earth\"\n    ]\n    masses = [ 1.99e6, 5.97 ]\n    trajectory = md((\n        x0 = x0, \n        v0 = v0, \n        mass = masses,\n        dt = 1, # days\n        nsteps = nsteps, # one Earth year\n        isave = isave, # save only last point\n        forces! = (f,x) -> forces!(f,x, \n            (i,j,p1,p2) -> gravitational_force(i,j,p1,p2,masses)\n        )\n    )...)\n    return trajectory\nend\n\n# ╔═╡ 3ae783ce-d06e-4cc2-b8a3-94512e8f1490\nmd\"\"\"\nNow we define our objective function, consisting of the norm of the difference between the initial and final coordinates of the Earth after one  year (what we want is that the Earth returns to its initial position):\n\"\"\"\n\n# ╔═╡ 13e7da81-8581-4f32-9fdb-2599dd36a12c\nfunction error_in_orbit(x::T=149.6) where T\n    traj = earth_orbit(x,365,365) # Save one point only\n    return norm(traj[end][2]-[x,0.])\nend\n\n# ╔═╡ 4870b1f3-3134-4ddc-a59d-fa806b456a23\nmd\"\"\"\nWe can see that our current data results in a significant error:\n\"\"\"\n\n# ╔═╡ fda6171c-9675-4f2e-b226-7ccf100529cd\nerror_in_orbit()\n\n# ╔═╡ a862f8a3-0131-4644-bc90-246bf3120790\nmd\"\"\"\nWe want to minimize this error, and it turns out that your simulation is fully differentiable. We will use here the `ForwardDiff` automatic differentiation package:\n\"\"\"\n\n# ╔═╡ eee3ac4b-4ddb-4699-b6e6-f0ffcc562c07\nmd\"\"\"\nWhich can be used just as it it to compute the derivative of the error in the orbit relative to the initial `x` position of the Earth:\n\"\"\"\n\n# ╔═╡ 107aec28-ecb5-4007-95e5-25d0a7f0c465\nForwardDiff.derivative(error_in_orbit,149.6)\n\n# ╔═╡ 1394e4c6-c371-47c0-8ca8-f0830d63d8ec\nmd\"\"\"\nTo minimize the error in the orbit we will write a simple stepest descent algorithm. Many packages are available for optimization, but here we will keep things simpler also to illustrate that writting the optimizer in Julia is a valid alternative:\n\"\"\"\n\n# ╔═╡ 535716e6-9c1c-4324-a4cd-b1214df3c01d\nfunction gradient_descent(x,f,g,tol,maxtrial)\n    itrial = 0\n    step = 1.0\n    fx = f(x)\n    gx = g(x)\n    while (abs(gx) > tol) && (itrial < maxtrial) && (step > 1e-10)\n        xtrial = x - gx*step\n        ftrial = f(xtrial)\n        if ftrial > fx\n            step = step / 2\n        else\n            x = xtrial\n            fx = ftrial\n            gx = g(x)\n            step = step * 2\n        end\n        itrial += 1\n    end \n    return x, gx, itrial\nend\n\n# ╔═╡ b8edfb4e-6780-4ce7-94c1-4073ff7fa832\nmd\"\"\"\nThe derivative of our error can be computed by *closing over* the `error_in_orbit` function:\n\"\"\"\n\n# ╔═╡ b8320f78-323c-49a9-a9f9-2748d19ecb35\nerror_derivative(x) = ForwardDiff.derivative(error_in_orbit,x)\n\n# ╔═╡ 92737d73-676c-4c96-a321-831ecaf37690\nmd\"\"\"\nAnd now we can call the `gradient_descent` function directly:\n\"\"\"\n\n# ╔═╡ 931a9c5f-8f91-4e88-956b-50c0efc9c58b\nbest_x0 = gradient_descent(149.6,error_in_orbit,error_derivative,1e-4,1000)\n\n# ╔═╡ b5b96082-efde-464f-bcd4-f2e0a84befcd\nmd\"\"\"\nThe result is reasonable: the error in the orbit has significantly being disminished:\n\"\"\"\n\n# ╔═╡ 7658a32c-d3da-4ec9-9d96-0d30bb18f08c\nerror_in_orbit(best_x0[1])\n\n# ╔═╡ e61981d5-5448-45e9-81dc-320ac87ba813\nmd\"\"\"\nLet us see our trajectory now with the new initial condition:\n\"\"\"\n\n# ╔═╡ 31e1bb51-c531-4c4a-8634-5caafb7e9e51\nearth_traj_0 = earth_orbit(149.6)\n\n# ╔═╡ b0b81da4-6788-45c4-b618-188a02b5e09c\nearth_traj_best = earth_orbit(best_x0[1])\n\n# ╔═╡ 47c205c3-ceae-4e12-9ade-753df1608deb\nmd\"\"\"\nThe dark blue dot is the corrected trajectory, and the light blue dot is the original one. Therefore, we were able to optimize the *initial point* of the trajectory with a gradient-based method. This concept can be used for adjusting parameters in simulations of many kinds (particle simulations or differential equations in general).\n\"\"\"\n\n# ╔═╡ 826693ff-9a9b-46b1-aeb3-767a5e6f9441\nmd\"\"\"\n# Accelerating with CellListMap.jl\n\"\"\"\n\n# ╔═╡ d231842d-9b7a-4711-b71b-5d54041ebc1f\nmd\"\"\"\n[`CellListMap.jl`](https://m3g.github.io/CellListMap.jl/stable/) is package aiming an efficient implementation of [cell lists](https://en.wikipedia.org/wiki/Cell_lists). Cell lists are practical algorithm to reduce the cost of computing short-ranged distances between particles. The package provides a general interface to compute any distance-dependent property, as potential energies and forces, nearest-neighbour lists, distribution functions, etc. It accepts systems with general (triclinic) periodic boundary conditions, in two and three dimensions. \n\nThe most simple cell list algorithm is relatively simple. Many optimizations can be done, however, on the construction of the lists, on the handling of periodic conditions, minimization of the number of unnecessary distance computations, and the parallelization of the construction of the lists and the mapping of the property to be evaluated. \n\n\"\"\"\n\n# ╔═╡ 53cedd26-3742-4c23-a8b8-8a1f2bdfa135\nmd\"\"\"\n## The naive algorithm is too slow O(n²)\n\"\"\"\n\n# ╔═╡ 889f837d-2e26-4261-b276-5fd91efdda6a\nmd\"\"\"\nWith ~1k, particles, the number of pairs of particles is already of the order of hundreds of thousands. The naive O(n²) algorithm is already too slow. Typical simulations involve tenths of thousands to millions of particles.\n\"\"\"\n\n# ╔═╡ 670a01e3-82f8-4c7f-8577-852081d91ed7\nmd\"\"\"\nHere, we will simulate 1000 particles to start:\n\"\"\"\n\n# ╔═╡ fce1e3e0-cdf7-453f-b913-964c10fa85a6\nconst n_large = 1000\n\n# ╔═╡ 69a92ac6-833c-4605-b3d0-9400e4572886\nmd\"\"\"\nOur previous system had 100 particles in a square of side 100. We will keep the density constant:\n\"\"\"\n\n# ╔═╡ 542a9ef5-d9ee-49bd-9d31-61e28b80b5cb\nconst box_side = sqrt(n_large / (100/100^2))\n\n# ╔═╡ 8bada25c-b586-42b4-851d-232ccca8a456\nmd\"\"\"\nWe only need to generate the coordinates and run:\n\"\"\"\n\n# ╔═╡ 7600c6dc-769e-4c77-8526-281a1bcec079\nx0_large = [ Vec2D(box_side*rand(),box_side*rand()) for _ in 1:n_large ] \n\n# ╔═╡ 29dbc47b-3697-4fdf-8f34-890ab4d0cdae\nt_naive = @elapsed trajectory_periodic_large = md((\n    x0 = x0_large, \n    v0 = [random_point(Vec2D{Float64},(-1,1)) for _ in 1:n_large ], \n    mass = [ 10.0 for _ in 1:n_large ],\n    dt = 0.1,\n    nsteps = 1000,\n    isave = 10,\n    forces! = (f,x) -> forces!(f,x,(i,j,p1,p2) -> fₓ(p1,p2,cutoff,box_side))\n)...)\n\n# ╔═╡ 0ee7fc18-f41f-4179-a75e-1e1d56b2db29\nmd\"\"\" \nRunning time of naive algorithm: $t_naive seconds\n\"\"\"\n\n# ╔═╡ 0d0374ed-5150-40e6-b5a4-9a344b6ca47a\nmd\"\"\"\n## Using cell lists\n\"\"\"\n\n# ╔═╡ f7cf613e-be9d-4f62-a778-cc4375eb99df\nmd\"\"\"\nIn cell lists, the particles are classified in cells before any distance computation. The distances are computed only for particles of vicinal cells. If the side of the cells is much smaller than the side of the complete system, the number of computations is drastically reduced.\n\"\"\"\n\n# ╔═╡ 5be87c6f-5c31-4d14-a8cb-4e63ef39d538\nbegin\n    \nfunction cell_list_picture()\n    \n    function square(c,side)\n          x = [ c[1]-side/2, c[1]+side/2, c[1]+side/2, c[1]-side/2, c[1]-side/2]  \n          y = [ c[2]-side/2, c[2]-side/2, c[2]+side/2, c[2]+side/2, c[2]-side/2]\n          return x, y\n    end\n    \n    plt = plot()\n    \n    x,y=square([5,5],2)\n    plot!(\n        plt,x,y,seriestype=[:shape],\n        linewidth=2,fillalpha=0.05,color=\"green\",label=\"\"\n    )\n    \n    x,y=square([5,5],6)\n    plot!(\n        plt,x,y,seriestype=[:shape],\n          linewidth=2,fillalpha=0.05,color=\"orange\",label=\"\"\n    )\n    \n    lines = collect(2:2:8)\n    vline!(plt,lines,color=\"gray\",label=\"\",style=:dash)\n    hline!(plt,lines,color=\"gray\",label=\"\",style=:dash)\n    \n    px = [ 0.1 + 9.8*rand() for i in 1:100 ]\n    py = [ 0.1 + 9.8*rand() for i in 1:100 ]\n    scatter!(plt,px,py,label=\"\",alpha=0.20,color=\"blue\")\n    \n    fontsize=8\n    annotate!(plt,3,3,text(\"(i-1,j-1)\",fontsize,:Courier))\n    annotate!(plt,5,3,text(\"(i-1,j)\",fontsize,:Courier))\n    annotate!(plt,7,3,text(\"(i-1,j+1)\",fontsize,:Courier))\n    \n    annotate!(plt,3,5,text(\"(i,j-1)\",fontsize,:Courier))\n    annotate!(plt,5,5,text(\"(i,j)\",fontsize,:Courier))\n    annotate!(plt,7,5,text(\"(i,j+1)\",fontsize,:Courier))\n    \n    annotate!(plt,3,7,text(\"(i+1,j-1)\",fontsize,:Courier))\n    annotate!(plt,5,7,text(\"(i+1,j)\",fontsize,:Courier))\n    annotate!(plt,7,7,text(\"(i+1,j+1)\",fontsize,:Courier))\n    \n    plot!(\n        plt,size=(400,400), \n        xlim=(1.3,8.7),xticks=:none,\n        ylim=(1.3,8.7),yticks=:none,\n        framestyle=:box,\n        xlabel=\"x\",ylabel=\"y\",grid=false\n    )\n    \n    return plt\nend\n\ncell_list_picture()\nend\n\n# ╔═╡ 0c07edd3-c0a1-4f72-a16a-74badb7a6123\nmd\"\"\"\nUsing `CellListMap.jl` we need to setup our system, by providing the data on the box properties and the cutoff of the interactions:\n\"\"\"\n\n# ╔═╡ 4fc5ef4d-e072-41f7-aef9-b42730c8313c\nbox = Box([box_side,box_side],cutoff)\n\n# ╔═╡ 19c5cc9d-8304-4e36-a3ea-a1151f28f71d\nmd\"\"\"\nThe particles are then classified in the cells. Virtual (ghost) particles are created at the boundaries to handle peridic boundary conditions and avoid having to wrap coordinates during the pairwise computation stage:\n\"\"\"\n\n# ╔═╡ 7dcadd85-2986-4e42-aa84-67128a8f666d\ncl = CellList(x0_large,box)\n\n# ╔═╡ 0b5c6ede-bceb-499a-a9a8-3c6a75ed340a\nmd\"\"\"\nUsing `CellListMap.jl`, we need to provide only the function that has to be evaluated *if$ the particles are closer than the cutoff. This function will only be called in that case. Here, the function will update the force vector:\n\"\"\"\n\n# ╔═╡ 91b5eac1-4799-4a72-ac6a-e2b117b787d5\nfunction fpair_cl(x,y,i,j,d2,f,box::Box)\n    Δv = y - x\n    d = sqrt(d2)\n    fₓ = 2*(d - box.cutoff)*(Δv/d)\n    f[i] += fₓ\n    f[j] -= fₓ\n    return f\nend\n\n# ╔═╡ 0f86ab3c-29aa-472b-8194-228c736ee940\nmd\"\"\"\nThe function that computes the forces in our simulation will, then, consist of an update of the cell lists followed by a call to the `map_pairwise!` function of `CellListMap.jl`, which takes as arguments the function to be mapped (`fpair_cl` here), the initial value of the forces vector `f`, and the system properties. We run only the serial version in this example:\n\"\"\"\n\n# ╔═╡ 0b8a2292-c0d6-44e4-b560-32d9d579a008\nfunction forces_cl!(f::Vector{T},x,box::Box,cl::CellList,fpair::F) where {T,F}\n    fill!(f,zero(T))\n    cl = UpdateCellList!(x,box,cl,parallel=false)\n    map_pairwise!(\n        (x,y,i,j,d2,f) -> fpair(x,y,i,j,d2,f,box),\n        f, box, cl, parallel=false\n    )\n    return f\nend\n\n# ╔═╡ d6585cca-78bf-41d1-aea3-01d9831d76cb\nmd\"\"\"\nWith a proper definition of the function to compute forces, we can now run again the simulation:\n\"\"\"\n\n# ╔═╡ 1b7b7d48-79d2-4317-9045-5b7e7bd073e5\nt_cell_lists = @elapsed trajectory_cell_lists = md((\n    x0 = x0_large, \n    v0 = [random_point(Vec2D{Float64},(-1,1)) for _ in 1:n_large ], \n    mass = [ 10.0 for _ in 1:n_large ],\n    dt = 0.1,\n    nsteps = 1000,\n    isave = 10,\n    forces! = (f,x) -> forces_cl!(f,x,box,cl,fpair_cl)\n)...)\n\n# ╔═╡ 3f9dad58-294c-405c-bfc4-67855bb1e825\nmd\"\"\" \nRunning time of CellListMap: $t_cell_lists seconds (on the second run - compilation takes about 2 seconds).\n\"\"\"\n\n# ╔═╡ 6d61b58f-b88f-48f4-8bdd-0bb1a8bc1c82\nmd\"\"\"\nEven for a small system like this one, the speedup is significant (of about $(round(Int,t_naive/t_cell_lists)) times here). \n\"\"\"\n\n# ╔═╡ 76b8695e-64dc-44bc-8938-ce22c4a9e4d0\nmd\"\"\"\n## Energy minimization: the Packmol strategy\n\"\"\"\n\n# ╔═╡ 372637ff-9305-4d45-bf6e-e6531dadbd14\nmd\"\"\"\n### A Lennard-Jones potential energy\n\nMolecular dynamics simulations usually involve computing, for each pair of atoms, a Lennard-Jones function of the form:\n\n$$u(r) = \\varepsilon\\left(\\frac{\\sigma^{12}}{r^{12}} - 2\\frac{\\sigma^6}{r^6}\\right)$$\n\nThe high powers make the numerical behavior of this function quite undesirable. For example, let us try to minimize the energia a randomly generated set of points.\n\nWe will define one function that adds to the energy the contribution of a given pair of particles, and then use the `map_pairwise!` function of `CellListMap.jl` to compute this function for all pairs closer than a cutoff.\n\"\"\"\n\n# ╔═╡ 3b2c08a6-b27e-49be-a0b0-e5cb3d5546e0\nmd\"\"\"\nThe `FastPow` package unrols the high powers that need to be computed into multiplications, squares and cubes, which are faster to compute (with some loss of precision which is of no concern here). This could be done by hand, but for code clarity and convenience, we opt to use the `@fastpow` macro.\n\"\"\"\n\n# ╔═╡ 7280e368-c68a-48a5-91fe-93c76607c144\nmd\"\"\"\nThe function that computes the energy associated to one pair of particles is, then:\n\"\"\"\n\n# ╔═╡ 755fae26-6db9-45a0-a60d-d0e9c063f8aa\nfunction ulj_pair(r2,u,ε,σ)\n    @fastpow u += ε*(σ^12/r2^6 - 2*σ^6/r2^3)\n    return u\nend\n\n# ╔═╡ 9a8d8012-ba54-4d9b-8c4c-fe6358508f2a\nmd\"\"\"\nAnd the function that computes the total energy is the mapping of that function to all relevant pairs through the `map_pairwise!` function:\n\"\"\"\n\n# ╔═╡ ffbeae5f-8aec-4473-a446-5b73bd911733\nfunction ulj(x,ε,σ,box::Box,cl::CellList)\n    cl = UpdateCellList!(x,box,cl,parallel=false)\n    u = map_pairwise!(\n        (x,y,i,j,d2,u) -> ulj_pair(d2,u,ε,σ),\n        zero(eltype(σ)), box, cl,\n        parallel=false\n    )\n    return u\nend\n\n# ╔═╡ 3738e40f-9596-469d-aa58-a4b28d8a22f8\nmd\"\"\"\nand we implement the corresponding functions that updates the forces:\n\"\"\"\n\n# ╔═╡ 5f1054b8-2337-43c1-a086-26233e95d42b\nfunction flj_pair!(x,y,i,j,r2,f,ε,σ)\n    @fastpow ∂u∂x = 12*ε*(σ^12/r2^7 - σ^6/r2^4)*(y-x)\n    f[i] -= ∂u∂x\n    f[j] += ∂u∂x\n    return f\nend\n\n# ╔═╡ bd719619-bdd4-4c3c-8d66-1df0f210c595\nfunction flj!(f::Vector{T},x,ε,σ,box,cl) where T\n    cl = UpdateCellList!(x,box,cl,parallel=false)\n    fill!(f,zero(T))\n    map_pairwise!(\n        (x,y,i,j,d2,f) -> flj_pair!(x,y,i,j,d2,f,ε,σ),\n        f, box, cl, \n        parallel=false\n    )\n    return f\nend\n\n# ╔═╡ f289955b-0239-4b8d-ba08-2edf0a7284c2\nmd\"\"\"\n### A physical system: Neon gas\n\nTo explore something more interesting than a two-dimensional set of points, we will approach an actual physical system. \n\nWe will compute the energy of a Ne gas with 10k particles, with density $\\sim 0.1$ particles/Å³, which is roughly the atomic density of liquid water. \n\nThe Lennard-Jones parameters for Neon are:\n\"\"\"\n\n# ╔═╡ 878ab5f7-28c1-4832-9c58-cb36b360766f\nconst ε = 0.0441795 # kcal/mol\n\n# ╔═╡ a0dcd888-059d-4abe-bb6b-958d2879101c\nconst σ = 2*1.64009 # Å\n\n# ╔═╡ b1c5b7e5-cfbf-4d93-bd79-2924d957ae14\nmd\"\"\"\nAnd we chose to simulate 10k particles, for which an atomic density typical of room-temperature liquids results in the following corresponding box side (thus, we are actually simulating a hihgly-compressed Neon gas, but this is more interesting because the number or pairwise interactions which have to be computed is greater for denser systems):\n\"\"\"\n\n# ╔═╡ cd1102ac-1500-4d79-be83-72ac9180c7ce\nconst n_Ne = 10_000\n\n# ╔═╡ f21604f4-e4f7-4d43-b3d9-32f429df443e\nconst box_side_Ne = (10_000/0.1)^(1/3)\n\n# ╔═╡ 59b1dbce-64af-4868-8c9d-23792c4a3a9f\nmd\"\"\"\nInitial coordinates, box and cell lists. A typical cutoff for Lennard-Jones interactions in MD simulations is 12Å. \n\"\"\"\n\n# ╔═╡ 10826a95-16f8-416d-b8c1-0ef3347c9b20\nx0_Ne = [random_point(Vec3D{Float64},(0,box_side_Ne)) for _ in 1:n_Ne ]\n\n# ╔═╡ c46a4f97-78e4-42fd-82b3-4dc6ce99abac\nmd\"\"\"\nGiven the initial coordinates, we can initialize the system box and cell lists:\n\"\"\"\n\n# ╔═╡ 7c433791-a653-4836-91e2-084355c01d90\nconst box_Ne = Box([box_side_Ne for _ in 1:3],12.)\n\n# ╔═╡ 410b9da4-7848-4385-bffc-a3d9bd03cf19\nconst cl_Ne = CellList(x0_Ne,box_Ne)\n\n# ╔═╡ c08fff28-520e-40af-951c-fe3c324f67e0\nmd\"\"\"\n### First, let us try to minimize the energy\n\"\"\"\n\n# ╔═╡ eb0f9080-2523-4633-be21-3a2281a1629e\nmd\"\"\"\nThe first thing in a MD simulation is trying to remove bad contacts by energy minimization:\n\"\"\"\n\n# ╔═╡ e3cc3c77-71ad-4006-8e27-fabaa1ae9cfb\nmd\"\"\"\nThe obtained energy (after 500 steps of stepest descent) is:\n\"\"\"\n\n# ╔═╡ 739c9a8a-13a5-4a33-a441-f5bc6cb35e82\nmd\"\"\"\n### Packing the atoms\n\"\"\"\n\n# ╔═╡ 4e059cb8-6dac-450d-9f46-b3e657d9c3cf\nmd\"\"\"\nTo pack the atoms the \"cutoff\" needs to be of the order of the atom radii, instead of the cutoff of the Lennard-Jones interactions. Thus, we redefine the cell lists with a cutoff of σ/2. Since only very short-ranged interactions have to be computed, and the function is well behaved, the optimization is fast:\n\"\"\"\n\n# ╔═╡ 5ff9c89a-d999-4af2-8e7e-fb99d4948c36\nmd\"\"\"\nLet us initialize again the system, considering the smaller cutoff:\n\"\"\"\n\n# ╔═╡ 0f2f55f6-060b-475e-bef7-eaa99da4d99f\nbox_pack = Box([box_side_Ne for _ in 1:3],σ/2)\n\n# ╔═╡ 415ad590-247b-4a5d-b21e-7af4d0c17493\ncl_pack = CellList(x0_Ne,box_pack)\n\n# ╔═╡ 53c2e16e-b7f5-4df2-96f4-08402b5f8979\nmd\"\"\"\nWe previously defined the short-range forces in the `forces_cl` function, but we didn't use the \"energy\" associated to it, which we will use now:\n\"\"\"\n\n# ╔═╡ 16cdbc18-e846-4d0a-b7e6-87f07c0c52d9\nfunction u_pack(x,box::Box,cl::CellList)\n    cl = UpdateCellList!(x,box,cl,parallel=false)\n    u = map_pairwise!(\n        (x,y,i,j,d2,u) -> begin\n\t\t\tu += (sqrt(d2) - box.cutoff)^2 # objective function\n\t\t\treturn u\n\t\tend,\n        0., box, cl,\n        parallel=false\n    )\n    return u\nend\n\n# ╔═╡ 79169f89-fedc-466b-8170-fff99b98e147\nmd\"\"\"\nGiven the packing energy and gradient, we can solve the packing problem:\n\"\"\"\n\n# ╔═╡ b5e258cd-5542-4a4c-ae0f-91c2fee426db\nmd\"\"\"\nImportantly, the result is a packing function which converged to a global minimizer (the resulting packing function value is zero):\n\"\"\"\n\n# ╔═╡ b0dc1c2b-82b7-488d-8074-1ef9f59a15e5\nmd\"\"\"\nThe energy, on the other side, is not necessarily small:\n\"\"\"\n\n# ╔═╡ 97b8b15b-75c7-4321-999d-b067ed2a04f9\nmd\"\"\"\nIn two dimensions, this is the difference between a randomly generated set of coordinates, and a set obtained after solving the packing problem:\n\"\"\"\n\n# ╔═╡ 591e6a9c-444c-471f-a56b-4dfbc9111989\nmd\"\"\"\nEven if the energy is high, we have the guarantee that no atoms are too close to each other, and this is an adequate configuration for a molecular dynamics simulation.\n\n`Packmol` solves this packing problem for molecules of complex shape, allowing the user to specify different geometrical constraints that define the arrangements of the atoms in the system.\n\"\"\"\n\n# ╔═╡ 1f265576-824a-4764-a738-685554068079\nmd\"\"\"\n## How fast is CellListMap.jl?\n\nAn idea of the efficiency of the cell list implementation in `CellListMap.jl` can be obtained by comparing the time required for an actual simulation of these Ne gas, compared to a stablished molecular dynamics simulation package, as [NAMD](https://www.ks.uiuc.edu/Research/namd/). \n\nWe can run a simulation of this gas using the same functions we defined before, but with the actual potential energy:\n\"\"\"\n\n# ╔═╡ 1e099e1f-6494-419b-8517-5bded3e18aa6\nmd\"\"\"\n# Remarks\n\n1. Many types of distributions of values, for instance, coordinates, can ben generated with the `Distributions.jl`  package. The generic character of the functions allow the functions to be used on custom types, as the `Vec2D` implemented here.\n\n2. The integrator of our `md` function is only the simplest one. The standard integrator for MD simulations is `Velocity-Verlet`, and is implemented in the code that compares the performance of `CellListMap.jl` and NAMD. Many other integration algorithms are implemented, for example, in the `DifferentialEquations.jl` package.\n\n3. The propagation of the uncertainty and the differentiability of particle simulations must be taken with a grain of salt. These systems are typically chaotic, thus uncertainties increase exponentialy, and derivatives are very unstable. An interesting blog post discussing the sensitivity of these calculations is [here](https://frankschae.github.io/post/shadowing/), and again the `DifferentialEquations.jl` package provides more adequate tools to deal with parameter optimization under such circunstances. \n\n\"\"\"\n\n# ╔═╡ 10c86547-d4f4-4c3f-8906-ac18ce93f3b6\nmd\"\"\"\n# Acknowledgements\n\nThe author thanks [Mosè Giordano](https://giordano.github.io/) for valuable discussions on the working of `Measurements`, and many other members of the Julia and Fortran discourse forums for indirect contributions to this work. We also thank the FortranCon organizing comitee, in particular [Milan Curcic](https://milancurcic.com/) and [Ondřej Čertík](Ondřej Čertík) for the kind invitation and great contributions for the developement of a modern community and tools around Fortran.\n\"\"\"\n\n# ╔═╡ 2871aca3-e6b4-4a2d-868a-36562e9a274c\nmd\"\"\"\n# Some notebook options and setup\n\"\"\"\n\n# ╔═╡ 2a2e9155-1c77-46fd-8502-8431573f94d0\nmd\"\"\"\n## Default plot setup\n\"\"\"\n\n# ╔═╡ b557a646-8c3c-4dc7-8788-bf98aec8c5c0\nmd\"\"\"\nUse Printf to print some data.\n\"\"\"\n\n# ╔═╡ 260d5753-6cc2-4137-8a2c-8d8a47585ecf\nmd\"\"\"\nWe can set this to false to avoid ploting everything. \n\"\"\"\n\n# ╔═╡ a9981931-4cc9-4d16-a6d2-34b4071a84d7\nconst build_plots = true\n\n# ╔═╡ 374f239b-6470-40ed-b068-a8ecaace4f09\nbuild_plots && begin\n    r = 0:0.1:1.2*cutoff\n    plot(layout=(1,2),size=(600,300))\n    plot!(r,energy.(0.,r,cutoff),xlabel=\"Distance\",ylabel=\"Energy\",subplot=1)\n    plot!(r,fₓ.(0.,r,cutoff),xlabel=\"Distance\",ylabel=\"Force\",subplot=2)\nend    \n\n# ╔═╡ 43e6b146-ee35-40f1-b540-3da22b9e1b1b\nbuild_plots && scatter([(x.x, x.y) for x in x0])\n\n# ╔═╡ 505ef5ab-f131-4ab3-a723-795b5eb5dc0f\nbuild_plots && @gif for (step,x) in pairs(trajectory)\n    scatter([ (p.x,p.y) for p in x ], lims=(-250,250))\n    annotate!(130,-210,text(\"step: $step\",plot_font,12,:left))\nend\n\n# ╔═╡ efc586a2-0946-4dc5-ab3a-3902a811f3ad\nbuild_plots && @gif for (step,x) in pairs(trajectory_periodic)\n    scatter([ wrap.((p.x,p.y),100) for p in x ], lims=(-60,60))\n    annotate!(25,-50,text(\"step: $step\",plot_font,12,:left))\nend\n\n# ╔═╡ 4a498c18-406f-4437-b378-aa9fdc75b919\nbuild_plots && @gif for x in trajectory_periodic_3D\n    scatter([ wrap.((p.x,p.y,p.z),100) for p in x ], lims=(-60,60))\nend\n\n# ╔═╡ d87c22d1-d595-4d43-ab1c-f28d282a3485\nbuild_plots && ( trajectory_2D_error = md((\n    x0 = [random_point(Vec2D{Measurement{Float64}},(-50,50),1e-5) for _ in 1:100 ], \n    v0 = [random_point(Vec2D{Measurement{Float64}},(-1,1),1e-5) for _ in 1:100 ],\n    mass = [ 1.0 for _ in 1:100 ],\n    dt = 0.1,\n    nsteps = 100,\n    isave = 1,\n    forces! = (f,x) -> forces!(f,x, (i,j,p1,p2) -> fₓ(p1,p2,cutoff,side))\n)...) )\n\n# ╔═╡ bf0a5303-f5ce-4711-b9ee-a12ce2d8a397\nbuild_plots && @gif for x in trajectory_2D_error\n    positions = [ wrap.((p.x.val,p.y.val),100) for p in x ]\n    scatter(positions, lims=(-60,60))\nend\n\n# ╔═╡ e24ce081-e367-4feb-8a79-66b8654a0b3a\nbuild_plots && @gif for x in trajectory_2D_error\n    histogram(\n        [ p.x.err for p in x ],\n        xlabel=\"Uncertainty in x\",ylabel=\"Number of points\",\n        bins=0:1e-4:20e-4,ylims=[0,50]\n    )\nend\n\n# ╔═╡ 1067527e-76b7-4331-b3ab-efd72fb99dfc\nbuild_plots && @gif for (step,x) in pairs(trajectory_planets)\n    colors = [ :yellow, :grey, :brown, :blue, :red ]\n    positions = [ (p.x.val,p.y.val) for p in x ]\n    xerr = [ p.x.err for p in x ]\n    yerr = [ p.y.err for p in x ] \n    scatter(positions,lims=[-250,250], markercolor=colors, xerror=xerr, yerror=yerr)\n    annotate!(150,-210,text(@sprintf(\"%5i days\",step),plot_font,12))\nend\n\n# ╔═╡ 4cef9cea-1e84-42b9-bff6-b9a8b3bfe8da\nbuild_plots && @gif for step in eachindex(earth_traj_best)\n    colors = [ :yellow, :blue ]\n    positions0 = [ (p.x,p.y) for p in earth_traj_0[step] ] \n    positions_best = [ (p.x,p.y) for p in earth_traj_best[step] ]\n    scatter(positions0,lims=[-250,250], markercolor=colors, alpha=0.5)\n    scatter!(positions_best,lims=[-250,250], markercolor=colors)\n    scatter!(\n        (earth_traj_best[1][2].x,earth_traj_best[1][2].y),\n        markercolor=:white,alpha=0.5,\n        markersize=10\n    )\n    annotate!(150,-210,text(@sprintf(\"%5i days\",step),plot_font,12))\nend\n\n# ╔═╡ e5b557d7-0952-4409-ae4c-a0c8ce736e03\nbuild_plots && @gif for (step,x) in pairs(trajectory_periodic_large)\n    scatter(\n        [ wrap.((p.x,p.y),box_side) for p in x ], \n        lims=(-1.1*box_side/2,1.1*box_side/2)\n    )\nend\n\n# ╔═╡ 30d2f39e-5df2-4f38-8032-e5f8492ba335\nbuild_plots && @gif for (step,x) in pairs(trajectory_cell_lists)\n    scatter(\n        [ wrap.((p.x,p.y),box_side) for p in x ], \n        lims=(-1.1*box_side/2,1.1*box_side/2)\n    )\nend\n\n# ╔═╡ 2634feff-7442-4d8f-b8e5-c11113136980\nbuild_plots && begin\n\tr_lj = 2.8:0.05:8\n\tplot(\n\t\tr_lj,ulj_pair.(r_lj.^2,0.,ε,σ),\n\t\txlabel=\"Distance / Å\", ylabel=\"Potential energy / kcal/mol\"\n\t)\nend\n\n# ╔═╡ b4154fb7-e0b0-4211-8490-8a8fe47cd2da\nmd\"\"\"\n## Gradient descent for vectors\n\"\"\"\n\n# ╔═╡ 8ac7b1bf-c958-4eb5-8376-f802b372e796\nfunction gradient_descent!(x::Vector{T},f,g!;tol=1e-3,maxtrial=500) where T\n    gnorm(x) = maximum(norm(v) for v in x)\n    itrial = 0\n    step = 1.0\n    xtrial = similar(x)\n    g = fill!(similar(x),zero(T))\n    fx = f(x)\n    g = g!(g,x)\n    while (gnorm(g) > tol) && (itrial < maxtrial) \n        @. xtrial = x - step*g\n        ftrial = f(xtrial)  \n        if ftrial >= fx\n            step = step / 2\n        else\n            x .= xtrial\n            fx = ftrial\n            g = g!(g,x)\n            step = step * 2\n        end\n        @show itrial, step, fx, ftrial, gnorm(g)\n\t\titrial += 1\n    end \n    return x\nend\n\n# ╔═╡ 357c6621-b2b8-4f30-ba41-ffc1ae6f031b\nt_min = @elapsed x_min = gradient_descent!(\n    copy(x0_Ne),\n    (x) -> ulj(x,ε,σ,box_Ne,cl_Ne),\n    (g,x) -> -flj!(g,x,ε,σ,box_Ne,cl_Ne)\n)\n\n# ╔═╡ 58eb5b4b-76ad-4f7a-b86b-0494a857dca1\nulj(x_min,ε,σ,box_Ne,cl_Ne)\n\n# ╔═╡ 574047fa-6626-4cd0-8317-32118129711e\nmd\"\"\"\nHere the example is only illustrative, but shows a common behavior: the energy after minimization is still too high. The cost and numerical instability of the true potential, at short distances, make it hard to minimize.\n\n**Time required for energy minimization: $t_min seconds**\n\nBecause of that [`Packmol`](http://m3g.iqm.unicamp.br/packmol) was introduced. We first solve the problem of packing the atoms in the space guaranteeing a minimum distance between the atoms. Here, this consists on the minimization of our simplified potential:\n\"\"\"\n\n# ╔═╡ 224336e2-522c-44af-b9a1-307e2ffff0f9\nt_pack = @elapsed x_pack = gradient_descent!(\n    copy(x0_Ne),\n    (x) -> u_pack(x,box_pack,cl_pack),\n    (g,x) -> -forces_cl!(g,x,box_pack,cl_pack,fpair_cl)\n)\n\n# ╔═╡ 06526edf-911a-4ecc-a350-6d932ca56cd5\nmd\"\"\"\n**Time required for packing: $t_pack seconds**\n\"\"\"\n\n# ╔═╡ c48210e0-1a04-4f84-a4e2-f6b5d34a603d\nu_pack(x_pack,box_pack,cl_pack)\n\n# ╔═╡ 0471b987-f987-4656-b961-285e32d0a5e1\nulj(x_pack,ε,σ,box_Ne,cl_Ne)\n\n# ╔═╡ 339487cd-8ee8-4d1d-984b-b4c5ff00bae3\nt_Ne = @elapsed trajectory_Ne = md((\n    x0 = x_pack, \n    v0 = [random_point(Vec3D{Float64},(-1,1)) for _ in 1:n_Ne ], \n    mass = [ 20.179 for _ in 1:n_Ne ],\n    dt = 0.01,\n    nsteps = 100,\n    isave = 10,\n    forces! = (f,x) -> flj!(f,x,ε,σ,box_Ne,cl_Ne)\n)...)\n\n# ╔═╡ 9cb29b01-7f49-4145-96d8-c8fd971fe1c8\nbuild_plots && @gif for x in trajectory_Ne\n    scatter(\n      [ wrap.((p.x,p.y,p.z),box_side_Ne) for p in x ], \n      lims=(-1.1*box_side_Ne/2,1.1*box_side_Ne/2)\n    )\nend\n\n# ╔═╡ ac52a71b-1138-4f1b-99c3-c174d9f09187\nmd\"\"\"\nThis simulation took $t_Ne seconds. \n\nAgain, to understand exactly what that means, we need to perform a proper comparison. In [this benchmark](https://github.com/m3g/2021_FortranCon/tree/main/celllistmap_vs_namd) two simulations of the same gas, with proper thermodynamic conditions, are performed. The Julia algorithm implemented is similar to the present one, except that thermalization is done by velocity rescaling and the velocity-verlet algorithm is used for propagating the positions. The same algorthms are used in the equivalent NAMD simulations. The benchmark result is, for a 4-cores/8-threads execution in my Laptop:\n\n````\nNAMD:\n\nreal    1m14,049s\nuser    8m59,065s\nsys     0m1,130s\n\nCellListMap:\n\nreal    1m21,054s\nuser    7m38,053s\nsys     0m2,172s\n````\n\nThis comparison of course can be questined: `NAMD` is a general purpose MD package designed for massive-parallel simulations, wnd `CellListMap.jl` is a package for computing any distance-dependent property, and for now designed and optimized on shared-memory computers. \n\nNevertheless,the benchmark shows that it is possible to write high-performant code in Julia, and that `CellListMap.jl` is a powerful tool for simulating or computing distance-dependent properties from the results of simulations.\n\nOne of the applications of this package is the computation of distribution functions, in the [ComplexMixtures.jl](https://m3g.github.io/ComplexMixtures.jl/stable/)  package.\n\n\"\"\"\n\n# ╔═╡ b5008faf-fd43-45dd-a5a1-7f51e0b4ede5\nmd\"\"\"\n## Table of Contents\n\"\"\"\n\n# ╔═╡ 555d1f62-b95b-4377-a8e2-9e442ee7526d\n\n\n# ╔═╡ f5510c1e-9b9f-49f0-bc7e-0fd8e79a5760\nmd\"\"\"\n## 2D packing example\n\"\"\"\n\n# ╔═╡ 5d9a40b5-4050-47d2-9855-e9b62d56e8df\nside_test = 50\n\n# ╔═╡ 7f556f7c-cdb0-4f91-a359-2f933bbc5b68\nxtest = [ random_point(Vec2D{Float64},(-side_test,side_test)) for _ in 1:1000 ]\n\n# ╔═╡ 0fc843d2-ac4f-4717-a298-92a476223112\ntol_test = 2\n\n# ╔═╡ fc7f665b-00d9-431b-a97e-d2ff7253221a\nbox_test = Box([side_test,side_test],tol_test)\n\n# ╔═╡ aadf6e48-0cbf-4973-86a1-173b6648d1df\ncl_test = CellList(xtest,box_test)\n\n# ╔═╡ 452e1ea7-98be-4910-ba6b-c0881fb251b2\nx_pack_test = gradient_descent!(\n    copy(xtest),\n    (x) -> u_pack(x,box_test,cl_test),\n    (g,x) -> -forces_cl!(g,x,box_test,cl_test,fpair_cl)\n)\n\n# ╔═╡ d9f254dc-ae4a-40b3-b682-f8a501e10a2d\nbuild_plots && begin\n\tplot(layout=(1,2))\n\tscatter!([ wrap.(Tuple(p),side_test) for p in xtest ],subplot=1)\n\tscatter!([ wrap.(Tuple(p),side_test) for p in x_pack_test ],subplot=2)\n\tplot!(lims=(-1.1*side_test/2,1.1*side_test/2),aspect_ratio=1,size=(800,400))\nend\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nBenchmarkTools = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\nCellListMap = \"69e1c6dd-3888-40e6-b3c8-31ac5f578864\"\nFastPow = \"c0e83750-1142-43a8-81cf-6c956b72b4d1\"\nForwardDiff = \"f6369f11-7733-5829-9624-2563aa707210\"\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nMeasurements = \"eff96d63-e80a-5855-80a2-b1b0885c5ab7\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nPrintf = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\nStaticArrays = \"90137ffa-7385-5640-81b9-e52037218182\"\n\n[compat]\nBenchmarkTools = \"~1.2.0\"\nCellListMap = \"~0.5.19\"\nFastPow = \"~0.1.0\"\nForwardDiff = \"~0.10.19\"\nMeasurements = \"~2.6.0\"\nPlots = \"~1.22.1\"\nPlutoUI = \"~0.7.10\"\nStaticArrays = \"~1.2.12\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[BenchmarkTools]]\ndeps = [\"JSON\", \"Logging\", \"Printf\", \"Profile\", \"Statistics\", \"UUIDs\"]\ngit-tree-sha1 = \"61adeb0823084487000600ef8b1c00cc2474cd47\"\nuuid = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\nversion = \"1.2.0\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"f2202b55d816427cd385a9a4f3ffb226bee80f99\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+0\"\n\n[[Calculus]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"f641eb0a4f00c343bbc32346e1217b86f3ce9dad\"\nuuid = \"49dc2e85-a5d0-5ad3-a950-438e2897f1b9\"\nversion = \"0.5.1\"\n\n[[CellListMap]]\ndeps = [\"DocStringExtensions\", \"LinearAlgebra\", \"Parameters\", \"ProgressMeter\", \"Random\", \"Setfield\", \"StaticArrays\"]\ngit-tree-sha1 = \"bb9ce9a37fbb004d8cdeee19d382439f77f74c81\"\nuuid = \"69e1c6dd-3888-40e6-b3c8-31ac5f578864\"\nversion = \"0.5.19\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"bd4afa1fdeec0c8b89dad3c6e92bc6e3b0fec9ce\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.6.0\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"9995eb3977fbf67b86d0a0a0508e83017ded03f2\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.14.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[CommonSubexpressions]]\ndeps = [\"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"7b8a93dba8af7e3b42fecabf646260105ac373f7\"\nuuid = \"bbf7d656-a473-5ed7-a52c-81e309532950\"\nversion = \"0.3.0\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"4866e381721b30fac8dda4c8cb1d9db45c8d2994\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.37.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[ConstructionBase]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"f74e9d5388b8620b4cee35d4c5a618dd4dc547f4\"\nuuid = \"187b0558-2788-49d3-abe0-74a17ed4e7c9\"\nversion = \"1.3.0\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[DiffResults]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"c18e98cba888c6c25d1c3b048e4b3380ca956805\"\nuuid = \"163ba53b-c6d8-5494-b064-1a9d43ac40c5\"\nversion = \"1.0.3\"\n\n[[DiffRules]]\ndeps = [\"NaNMath\", \"Random\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"7220bc21c33e990c14f4a9a319b1d242ebc5b269\"\nuuid = \"b552c78f-8df3-52c6-915a-8e097449b14b\"\nversion = \"1.3.1\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"a32185f5428d3986f47c2ab78b1f216d5e6cc96f\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.5\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FastPow]]\ngit-tree-sha1 = \"7d961335144dad74de0e1b3a9b60e4d114a78dc2\"\nuuid = \"c0e83750-1142-43a8-81cf-6c956b72b4d1\"\nversion = \"0.1.0\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[ForwardDiff]]\ndeps = [\"CommonSubexpressions\", \"DiffResults\", \"DiffRules\", \"LinearAlgebra\", \"NaNMath\", \"Printf\", \"Random\", \"SpecialFunctions\", \"StaticArrays\"]\ngit-tree-sha1 = \"b5e930ac60b613ef3406da6d4f42c35d8dc51419\"\nuuid = \"f6369f11-7733-5829-9624-2563aa707210\"\nversion = \"0.10.19\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"dba1e8614e98949abfa60480b13653813d8f0157\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+0\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"c2178cfbc0a5a552e16d097fae508f2024de61a3\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.59.0\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"ef49a187604f865f4708c90e3f431890724e9012\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.59.0+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"7bf67e9a481712b3dbe9cb3dac852dc4b1162e02\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+0\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"60ed5f1643927479f845b0135bb369b031b541fa\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.14\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"8a954fed8ac097d5be04921d595f741115c1b2ad\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+0\"\n\n[[HypertextLiteral]]\ngit-tree-sha1 = \"72053798e1be56026b81d4e2682dbe58922e5ec9\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.0\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"f76424439413893a832026ca355fe273e93bce94\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.0\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a4b12a1bd2ebade87891ab7e36fdbce582301a92\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.6\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"761a393aeccd6aa92ec3515e428c26bf99575b3b\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+0\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"DocStringExtensions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"34dc30f868e368f8a17b728a1238f3fcda43931a\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.3\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"5a5bc6bf062f0f95e62d0fe0a2d99699fed82dd9\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.8\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measurements]]\ndeps = [\"Calculus\", \"LinearAlgebra\", \"Printf\", \"RecipesBase\", \"Requires\"]\ngit-tree-sha1 = \"31c8c0569b914111c94dd31149265ed47c238c5b\"\nuuid = \"eff96d63-e80a-5855-80a2-b1b0885c5ab7\"\nversion = \"2.6.0\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+0\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[Parameters]]\ndeps = [\"OrderedCollections\", \"UnPack\"]\ngit-tree-sha1 = \"34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe\"\nuuid = \"d96e819e-fc66-5662-9728-84c9c7592b0a\"\nversion = \"0.12.3\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"438d35d2d95ae2c5e8780b330592b6de8494e779\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.3\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"2537ed3c0ed5e03896927187f5f2ee6a4ab342db\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.0.14\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\"]\ngit-tree-sha1 = \"4c2637482176b1c2fb99af4d83cb2ff0328fc33c\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.22.1\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"HypertextLiteral\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"Suppressor\"]\ngit-tree-sha1 = \"26b4d16873562469a0a1e6ae41d90dec9e51286d\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.10\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Profile]]\ndeps = [\"Printf\"]\nuuid = \"9abbd945-dff8-562f-b5e8-e1ebf5ef1b79\"\n\n[[ProgressMeter]]\ndeps = [\"Distributed\", \"Printf\"]\ngit-tree-sha1 = \"afadeba63d90ff223a6a48d2009434ecee2ec9e8\"\nuuid = \"92933f4c-e287-5a05-a399-4b506db050ca\"\nversion = \"1.7.1\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"44a75aa7a527910ee3d1751d1f0e4148698add9e\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.2\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"7ad0dfa8d03b7bcf8c597f59f5292801730c55b8\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.4.1\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[Setfield]]\ndeps = [\"ConstructionBase\", \"Future\", \"MacroTools\", \"Requires\"]\ngit-tree-sha1 = \"fca29e68c5062722b5b4435594c3d1ba557072a3\"\nuuid = \"efcf1570-3423-57d1-acb7-fd33fddbac46\"\nversion = \"0.7.1\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"LogExpFunctions\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"a322a9493e49c5f3a10b50df3aedaf1cdb3244b7\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.6.1\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3240808c6d463ac46f1c1cd7638375cd22abbccb\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.12\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"1958272568dc176a1d881acb797beb909c785510\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.0.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"8cbbc098554648c84f79a463c9ff0fd277144b6c\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.10\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.3\"\n\n[[Suppressor]]\ngit-tree-sha1 = \"a819d77f31f83e5792a76081eee1ea6342ab8787\"\nuuid = \"fd094767-a336-5f1f-9728-57cf17d0bbfb\"\nversion = \"0.2.0\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"1162ce4a6c4b7e31e0e6b14486a6986951c73be9\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.5.2\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[UnPack]]\ngit-tree-sha1 = \"387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b\"\nuuid = \"3a884ed6-31ef-47d7-9d2a-63182c4928ed\"\nversion = \"1.0.2\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\"]\ngit-tree-sha1 = \"2839f1c1296940218e35df0bbb220f2a79686670\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.18.0+4\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─a87fad48-73c1-4a08-a6f1-aae759b3c6fc\n# ╟─172227c2-b27a-40db-91f4-9566c2f6cf52\n# ╟─4b484cf6-4888-4f04-b3fd-94862822b0c0\n# ╠═a82f22e4-f35b-461a-b481-1dff43722e44\n# ╠═8c444ee4-8c77-413a-bbeb-9e5ae2428876\n# ╟─a0de01b5-779a-48c0-8d61-12b02a5f527e\n# ╠═f87e4036-8f82-41c7-90c1-daa5f677488d\n# ╟─532eb3bc-5522-4348-afa5-5336ec6752c7\n# ╟─dc5f7484-3dc3-47a7-ad4a-30f97fc14d11\n# ╟─ab3ff21b-bf82-4d8c-abd1-c27418956ed8\n# ╠═7a1db355-bba9-4322-9fb4-a6d7b7bdd60d\n# ╟─cc49ef04-08d8-42bb-9170-9db64e275a51\n# ╠═df33b999-4a42-4133-bf59-5a65240790cf\n# ╠═0f52365d-34f4-46ed-923e-3ea31c6db0ca\n# ╟─d00e56f2-9d3a-4dd3-80eb-3201eff39b96\n# ╠═b5c09cd3-6063-4a36-96cd-2d128aa11b82\n# ╟─374f239b-6470-40ed-b068-a8ecaace4f09\n# ╟─7719b317-e85b-4583-b401-a8614d4b2373\n# ╠═f58769a6-a656-42a3-8bc6-c204d4cfd897\n# ╟─144119ad-ab88-4165-883a-f2fc2464a838\n# ╠═356ac5a4-c94e-42cb-a085-0198b29c7e52\n# ╟─43e6b146-ee35-40f1-b540-3da22b9e1b1b\n# ╟─dd9e4332-2908-40ef-b461-6b571df56cf4\n# ╠═d23b4a92-055e-4ed7-bd46-8a3c59312993\n# ╠═e6e29d1e-9a93-49db-a358-6b66f0bc3433\n# ╟─017cd6a8-712d-4ec5-b31f-7f1f507764f2\n# ╟─b5206dd5-1f46-4437-929b-efd68393b12b\n# ╠═eb5dc224-1491-11ec-1cae-d51c93cd292c\n# ╟─594ba1d6-2dae-4f20-9546-f52fac17c2f0\n# ╟─66c7d960-7e05-4613-84e8-2a40fe40dc3d\n# ╟─e717a8d9-ccfb-4f89-b2a2-f244f108b48d\n# ╠═3755a4f3-1842-4de2-965e-d294c06c54c7\n# ╟─505ef5ab-f131-4ab3-a723-795b5eb5dc0f\n# ╟─eab7b195-64d5-4587-8687-48a673ab091b\n# ╟─34dc72dc-4864-47c0-b730-183f67e7aea3\n# ╠═beeb3335-5c49-47de-a1d3-3eef5f9479f1\n# ╟─02d9bf3b-708c-4293-b198-9043b334ff7e\n# ╠═0967b90d-ac88-476d-a57a-7c38dfa82204\n# ╟─0a5282ee-c88a-4bcc-aca2-477f28e9e04d\n# ╠═b2a4a505-47ff-40bb-9a6d-a08d91c53217\n# ╟─fcff6973-012a-40fc-a618-f6262266287a\n# ╠═985b4ffb-7964-4b50-8c2f-e5f45f352500\n# ╟─14867ffd-cde5-43f8-8399-01169ee29b73\n# ╟─c4798182-de75-4b59-8be7-f7cf1051364d\n# ╠═efc586a2-0946-4dc5-ab3a-3902a811f3ad\n# ╟─22fb0386-d4fa-47b9-ac31-decf2731cbc1\n# ╟─8e23a3ea-3039-4a5f-b37f-c4710153938e\n# ╠═d42f842d-6c2a-40db-b0c4-e936244a9e7c\n# ╠═1ad401b5-20b2-489b-b2aa-92f729b1d725\n# ╟─2a3e7257-63ad-4761-beda-cec18b91f99c\n# ╟─49b1f040-929a-4238-acd9-6554757b592c\n# ╠═26d5c6e9-a903-4792-a0e0-dec1a2e86a01\n# ╟─2aef27bd-dea6-4a93-9d0f-b9249c9dd2cd\n# ╠═0546ee2d-b62d-4c7a-8172-ba87b3c1aea4\n# ╟─4a498c18-406f-4437-b378-aa9fdc75b919\n# ╟─b6dcb9a3-59e3-4eae-9399-fb072c704f1a\n# ╠═e4657169-1bb2-4d4a-ac9d-adc80499d07d\n# ╟─5d395353-5681-4780-983e-902fdb89eaf2\n# ╠═e9376a4b-3d60-42eb-8681-cd2bcec13fe8\n# ╠═c5cdd71f-5ded-482f-9205-c13f01a14d0b\n# ╟─a0993a1f-60a6-45b5-815e-676c49a9f049\n# ╠═4e7f8db4-b5cc-4a3e-9fa7-e62d8f2a36ac\n# ╟─36da3e92-000c-4d4b-9abf-4cd588b3a354\n# ╠═70eb2e0a-a5c8-4975-8f6c-589035bea29c\n# ╟─b4646a29-3efd-4bd1-bffc-3575559de937\n# ╠═d32743c0-fc80-406f-83c5-4528e439589a\n# ╟─98478246-5940-4828-a8f1-9c9fa990676d\n# ╠═310f247e-3fe8-4621-ae0b-b5ee38d2ee89\n# ╟─8267220a-f06e-4761-b310-00f8ba44e4b1\n# ╟─ce916139-221a-462e-877f-88212663c05e\n# ╠═99b5c818-a825-4939-849e-1cade802f63d\n# ╟─8e2903be-4975-4e14-84ed-6e712f47fe47\n# ╟─418f31bb-81d5-459b-b402-4fd4e3f4ab27\n# ╠═05402cbd-78c6-4234-8680-c351c8c37778\n# ╟─4e97f24c-c237-4117-bc57-e4e88c8fb8d2\n# ╠═b31da90d-7165-42de-b18d-90584affea03\n# ╟─5f37640b-ffd9-4877-a78c-a699b2671919\n# ╠═d87c22d1-d595-4d43-ab1c-f28d282a3485\n# ╟─1d6eedfd-d013-4557-9cf2-103f8fb7b72a\n# ╟─bf0a5303-f5ce-4711-b9ee-a12ce2d8a397\n# ╟─c003a61d-a434-4d7b-9214-5b52aa044248\n# ╠═e24ce081-e367-4feb-8a79-66b8654a0b3a\n# ╟─63eb391f-0238-434a-bc3a-2fa8ed41448e\n# ╠═7b9bb0fd-34a5-42e1-bc35-7259447b73d0\n# ╟─6a4e0e2e-75c5-4cab-987d-3d6b62f9bb06\n# ╠═c91862dd-498a-4712-8e3d-b77e088cd470\n# ╠═a08d6e6d-ddc4-40aa-b7c4-93ea03191415\n# ╟─a356e2cc-1cb1-457a-986c-998cf1efe008\n# ╠═57141f7c-9261-4dc5-98e4-b136a15f86fc\n# ╟─055e32d7-073c-40db-a267-750636b9f786\n# ╠═aaa97ce4-a5ff-4332-89a2-843cee2e5b6d\n# ╟─1067527e-76b7-4331-b3ab-efd72fb99dfc\n# ╟─93697e4d-369b-48e9-8b28-a0ff58604d02\n# ╟─c4344e64-aa22-4328-a97a-71e44bcd289f\n# ╟─827bda6f-87d4-4d36-8d89-f144f4595240\n# ╟─1ff4077a-4742-4c5e-a8d6-c4699469a683\n# ╠═4a75498d-8f4e-406f-8b01-f6a5f153919f\n# ╟─3ae783ce-d06e-4cc2-b8a3-94512e8f1490\n# ╠═13e7da81-8581-4f32-9fdb-2599dd36a12c\n# ╟─4870b1f3-3134-4ddc-a59d-fa806b456a23\n# ╠═fda6171c-9675-4f2e-b226-7ccf100529cd\n# ╟─a862f8a3-0131-4644-bc90-246bf3120790\n# ╠═d6564250-f646-40de-9463-a956af1a5b1d\n# ╟─eee3ac4b-4ddb-4699-b6e6-f0ffcc562c07\n# ╠═107aec28-ecb5-4007-95e5-25d0a7f0c465\n# ╟─1394e4c6-c371-47c0-8ca8-f0830d63d8ec\n# ╠═535716e6-9c1c-4324-a4cd-b1214df3c01d\n# ╟─b8edfb4e-6780-4ce7-94c1-4073ff7fa832\n# ╠═b8320f78-323c-49a9-a9f9-2748d19ecb35\n# ╟─92737d73-676c-4c96-a321-831ecaf37690\n# ╠═931a9c5f-8f91-4e88-956b-50c0efc9c58b\n# ╟─b5b96082-efde-464f-bcd4-f2e0a84befcd\n# ╠═7658a32c-d3da-4ec9-9d96-0d30bb18f08c\n# ╟─e61981d5-5448-45e9-81dc-320ac87ba813\n# ╠═31e1bb51-c531-4c4a-8634-5caafb7e9e51\n# ╠═b0b81da4-6788-45c4-b618-188a02b5e09c\n# ╟─47c205c3-ceae-4e12-9ade-753df1608deb\n# ╟─4cef9cea-1e84-42b9-bff6-b9a8b3bfe8da\n# ╟─826693ff-9a9b-46b1-aeb3-767a5e6f9441\n# ╟─d231842d-9b7a-4711-b71b-5d54041ebc1f\n# ╟─53cedd26-3742-4c23-a8b8-8a1f2bdfa135\n# ╟─889f837d-2e26-4261-b276-5fd91efdda6a\n# ╟─670a01e3-82f8-4c7f-8577-852081d91ed7\n# ╠═fce1e3e0-cdf7-453f-b913-964c10fa85a6\n# ╟─69a92ac6-833c-4605-b3d0-9400e4572886\n# ╠═542a9ef5-d9ee-49bd-9d31-61e28b80b5cb\n# ╟─8bada25c-b586-42b4-851d-232ccca8a456\n# ╠═7600c6dc-769e-4c77-8526-281a1bcec079\n# ╠═29dbc47b-3697-4fdf-8f34-890ab4d0cdae\n# ╟─0ee7fc18-f41f-4179-a75e-1e1d56b2db29\n# ╟─e5b557d7-0952-4409-ae4c-a0c8ce736e03\n# ╟─0d0374ed-5150-40e6-b5a4-9a344b6ca47a\n# ╠═d2f4d622-8e35-4be3-b421-39b28a748cab\n# ╟─f7cf613e-be9d-4f62-a778-cc4375eb99df\n# ╟─5be87c6f-5c31-4d14-a8cb-4e63ef39d538\n# ╟─0c07edd3-c0a1-4f72-a16a-74badb7a6123\n# ╠═4fc5ef4d-e072-41f7-aef9-b42730c8313c\n# ╟─19c5cc9d-8304-4e36-a3ea-a1151f28f71d\n# ╠═7dcadd85-2986-4e42-aa84-67128a8f666d\n# ╟─0b5c6ede-bceb-499a-a9a8-3c6a75ed340a\n# ╠═91b5eac1-4799-4a72-ac6a-e2b117b787d5\n# ╟─0f86ab3c-29aa-472b-8194-228c736ee940\n# ╠═0b8a2292-c0d6-44e4-b560-32d9d579a008\n# ╟─d6585cca-78bf-41d1-aea3-01d9831d76cb\n# ╠═1b7b7d48-79d2-4317-9045-5b7e7bd073e5\n# ╟─3f9dad58-294c-405c-bfc4-67855bb1e825\n# ╟─30d2f39e-5df2-4f38-8032-e5f8492ba335\n# ╟─6d61b58f-b88f-48f4-8bdd-0bb1a8bc1c82\n# ╟─76b8695e-64dc-44bc-8938-ce22c4a9e4d0\n# ╟─372637ff-9305-4d45-bf6e-e6531dadbd14\n# ╟─3b2c08a6-b27e-49be-a0b0-e5cb3d5546e0\n# ╠═f049ab19-7ecf-4c65-bf6d-21352c1fe767\n# ╟─7280e368-c68a-48a5-91fe-93c76607c144\n# ╠═755fae26-6db9-45a0-a60d-d0e9c063f8aa\n# ╟─9a8d8012-ba54-4d9b-8c4c-fe6358508f2a\n# ╠═ffbeae5f-8aec-4473-a446-5b73bd911733\n# ╟─3738e40f-9596-469d-aa58-a4b28d8a22f8\n# ╠═5f1054b8-2337-43c1-a086-26233e95d42b\n# ╠═bd719619-bdd4-4c3c-8d66-1df0f210c595\n# ╟─f289955b-0239-4b8d-ba08-2edf0a7284c2\n# ╠═878ab5f7-28c1-4832-9c58-cb36b360766f\n# ╠═a0dcd888-059d-4abe-bb6b-958d2879101c\n# ╟─2634feff-7442-4d8f-b8e5-c11113136980\n# ╟─b1c5b7e5-cfbf-4d93-bd79-2924d957ae14\n# ╠═cd1102ac-1500-4d79-be83-72ac9180c7ce\n# ╠═f21604f4-e4f7-4d43-b3d9-32f429df443e\n# ╟─59b1dbce-64af-4868-8c9d-23792c4a3a9f\n# ╠═10826a95-16f8-416d-b8c1-0ef3347c9b20\n# ╟─c46a4f97-78e4-42fd-82b3-4dc6ce99abac\n# ╠═7c433791-a653-4836-91e2-084355c01d90\n# ╠═410b9da4-7848-4385-bffc-a3d9bd03cf19\n# ╟─c08fff28-520e-40af-951c-fe3c324f67e0\n# ╟─eb0f9080-2523-4633-be21-3a2281a1629e\n# ╠═357c6621-b2b8-4f30-ba41-ffc1ae6f031b\n# ╟─e3cc3c77-71ad-4006-8e27-fabaa1ae9cfb\n# ╠═58eb5b4b-76ad-4f7a-b86b-0494a857dca1\n# ╟─574047fa-6626-4cd0-8317-32118129711e\n# ╟─739c9a8a-13a5-4a33-a441-f5bc6cb35e82\n# ╟─4e059cb8-6dac-450d-9f46-b3e657d9c3cf\n# ╟─5ff9c89a-d999-4af2-8e7e-fb99d4948c36\n# ╠═0f2f55f6-060b-475e-bef7-eaa99da4d99f\n# ╠═415ad590-247b-4a5d-b21e-7af4d0c17493\n# ╟─53c2e16e-b7f5-4df2-96f4-08402b5f8979\n# ╠═16cdbc18-e846-4d0a-b7e6-87f07c0c52d9\n# ╟─79169f89-fedc-466b-8170-fff99b98e147\n# ╠═224336e2-522c-44af-b9a1-307e2ffff0f9\n# ╟─06526edf-911a-4ecc-a350-6d932ca56cd5\n# ╟─b5e258cd-5542-4a4c-ae0f-91c2fee426db\n# ╠═c48210e0-1a04-4f84-a4e2-f6b5d34a603d\n# ╟─b0dc1c2b-82b7-488d-8074-1ef9f59a15e5\n# ╠═0471b987-f987-4656-b961-285e32d0a5e1\n# ╟─97b8b15b-75c7-4321-999d-b067ed2a04f9\n# ╟─d9f254dc-ae4a-40b3-b682-f8a501e10a2d\n# ╟─591e6a9c-444c-471f-a56b-4dfbc9111989\n# ╟─1f265576-824a-4764-a738-685554068079\n# ╠═339487cd-8ee8-4d1d-984b-b4c5ff00bae3\n# ╟─9cb29b01-7f49-4145-96d8-c8fd971fe1c8\n# ╟─ac52a71b-1138-4f1b-99c3-c174d9f09187\n# ╟─1e099e1f-6494-419b-8517-5bded3e18aa6\n# ╟─10c86547-d4f4-4c3f-8906-ac18ce93f3b6\n# ╟─2871aca3-e6b4-4a2d-868a-36562e9a274c\n# ╟─2a2e9155-1c77-46fd-8502-8431573f94d0\n# ╠═7c792b6b-b6ee-4e30-88d5-d0b8064f2734\n# ╟─b557a646-8c3c-4dc7-8788-bf98aec8c5c0\n# ╠═febe8c06-b3aa-4db1-a3ea-fdc2a81bdebd\n# ╟─260d5753-6cc2-4137-8a2c-8d8a47585ecf\n# ╠═a9981931-4cc9-4d16-a6d2-34b4071a84d7\n# ╟─b4154fb7-e0b0-4211-8490-8a8fe47cd2da\n# ╠═8ac7b1bf-c958-4eb5-8376-f802b372e796\n# ╟─b5008faf-fd43-45dd-a5a1-7f51e0b4ede5\n# ╠═a756dd18-fac6-4527-944e-c16d8cc4bf95\n# ╠═555d1f62-b95b-4377-a8e2-9e442ee7526d\n# ╠═f5510c1e-9b9f-49f0-bc7e-0fd8e79a5760\n# ╠═7f556f7c-cdb0-4f91-a359-2f933bbc5b68\n# ╠═5d9a40b5-4050-47d2-9855-e9b62d56e8df\n# ╠═0fc843d2-ac4f-4717-a298-92a476223112\n# ╠═fc7f665b-00d9-431b-a97e-d2ff7253221a\n# ╠═aadf6e48-0cbf-4973-86a1-173b6648d1df\n# ╠═452e1ea7-98be-4910-ba6b-c0881fb251b2\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "45bc5838b1df3c5a50ff6f2dd021b93195908421", "size": 92681, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "particle_simulation.jl", "max_stars_repo_name": "mforets/2021_FortranCon", "max_stars_repo_head_hexsha": "4879ab97c6736f895139a2e0207ba5673fbf6fd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "particle_simulation.jl", "max_issues_repo_name": "mforets/2021_FortranCon", "max_issues_repo_head_hexsha": "4879ab97c6736f895139a2e0207ba5673fbf6fd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "particle_simulation.jl", "max_forks_repo_name": "mforets/2021_FortranCon", "max_forks_repo_head_hexsha": "4879ab97c6736f895139a2e0207ba5673fbf6fd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2881982982, "max_line_length": 591, "alphanum_fraction": 0.7169214834, "num_tokens": 39981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8856314783461303, "lm_q1q2_score": 0.7579687100204224}}
{"text": "# 1D quadrature\n\nintegrate(poly::Poly, a, b) = (pp = polyint(poly); fapply(pp,b) - fapply(pp,a))\nintegrate(x::Number, a, b) = x*(b-a)\n\nconst gp = Base.gauss(Float64, 7)\nfunction integrate(f::Function,a, b)\n    gx, gw = gp\n    @assert a == -1 && b == 1\n\n    result = gw[1]*f(gx[1])\n    for i in 2:length(gw)\n        result += gw[i]*f(gx[i])\n    end\n    result\nend\n\ndo_quad_ref(f::Poly,p::DG1D) = integrate(f,-1,1)\n\n# ElemJacobian\nelemJ(x::DG1D,k) = (1//2)*(x.mesh[k,:r] - x.mesh[k,:l])\n\n# 2D quadrature\n\n# Get quadrature weights (from lecture notes)\nfunction quadp(p) \n    if p == 1\n        return (\n            [Vertex2(1//3,1//3)],[0.5])\n    elseif p == 2\n        return (\n            [Vertex2(2//3,1//6),Vertex2(1//6,2//3),\n             Vertex2(1//6,1//6)],\n             [1//6,1//6,1//6])\n    elseif p == 3\n        return (\n            [Vertex2(0.1550510257, 0.1785587282),\n             Vertex2(0.6449489742, 0.0750311102),\n             Vertex2(0.1550510257, 0.6663902460),\n             Vertex2(0.6449489742, 0.2800199154)],\n             [0.1590206908,0.0909793091,\n              0.1590206908,0.0909793091])\n    elseif p == 4\n        return (\n            [Vertex2(0.4459484909, 0.4459484909),\n             Vertex2(0.1081030181, 0.4459484909),\n             Vertex2(0.4459484909, 0.1081030181),\n             Vertex2(0.0915762135, 0.0915762135),\n             Vertex2(0.8168475729, 0.0915762135),\n             Vertex2(0.0915762135, 0.8168475729)],\n             [0.1116907948,0.1116907948,0.1116907948,\n              0.0549758718,0.0549758718,0.0549758718])\n    else \n        error(\"Unimplemented\")\n    end\nend\n\nfunction do_quad(f,porder)\n    result = zero(typeof(f(zero(Vertex2))))\n    for (x,w) in zip(quadp(porder)...)\n        result += w*f(x)\n    end\n    result\nend\n\ndo_quad_ref(f::Function,p::Galerkin2D) = do_quad(f,clamp(porder(p)*2,1,4))\ndo_quad_ref(f::Function,p::Galerkin2D,edge::Edge) = do_quad_ref(p.mesh,edge,f,porder(p)*2)\n\ndo_quad(c::Cell2D, f, p) = det(Ak(c))*do_quad(x->f(𝜒⁻¹(c,x)),p)\nfunction elemJ(p::Galerkin2D,c) \n    d = det(Ak(c))\n    d < 0 && error(\"Misoriented cell\")\n    d\nend\n\n#point = 𝜒⁻¹(edge,x)\n#@show p\n\nmacro do_quad_ref2d_Δ1(fargs, var, block)\n    esc(quote\n        args = $fargs\n        p = args[1]\n        edge = args[2]\n        points = args[3]\n        gx, gw = points\n        # Manual loop peeling\n        x,w = gx[1], gw[1]\n        $var = x\n        result = w*begin\n            $block\n        end\n        for i in 2:length(gw)\n            x,w = gx[i],gw[i]\n            $var = x\n            result += w*begin\n                $block\n            end\n        end\n        (norm(edge)/2)*result   \n    end)\nend\n\nfunction do_quad_ref(m::Meshes.Mesh, edge::Edge, f, porder; points=Base.gauss(Float64,porder))\n    gx, gw = points\n    result = 0.0\n    for i in 1:length(gw)\n        x,w = gx[i],gw[i]\n        result += w*f(x)\n    end\n    (norm(edge)/2)*result\nend", "meta": {"hexsha": "5d297a06df40185a5d196513cdd381fe37d075e8", "size": 2887, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/quadrature.jl", "max_stars_repo_name": "Keno/AC274.jl", "max_stars_repo_head_hexsha": "9eafcba152019a563b4501c9626f1699814e37b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-04-27T07:38:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T10:11:02.000Z", "max_issues_repo_path": "src/quadrature.jl", "max_issues_repo_name": "Keno/AC274.jl", "max_issues_repo_head_hexsha": "9eafcba152019a563b4501c9626f1699814e37b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/quadrature.jl", "max_forks_repo_name": "Keno/AC274.jl", "max_forks_repo_head_hexsha": "9eafcba152019a563b4501c9626f1699814e37b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.009009009, "max_line_length": 94, "alphanum_fraction": 0.5355039834, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7579608249969964}}
{"text": "# using OMEinsum\nusing BackwardsLinalg\n\n@doc raw\"\n    trg(a, χ, niter)\n\nreturn the partition-function of a two-dimensional system of size `2^niter`\ndescribed by the tensor `a` calculated via the tensor renormalization group\nalgorithm.\n`a` is a rank-4 tensor with the following indices:\n\n        |1\n    4--[a]--2\n       3|\n\"\nfunction trg(a::AbstractArray{T,4}, χ, niter; tol::Float64 = 1e-16) where T\n    lnZ = zero(T)\n    for n in 1:niter\n        maxval = maximum(abs.(a))\n        a /= maxval\n        lnZ += 2.0^(1-n)*log(maxval)\n\n        dr_ul = ein\"urdl -> drul\"(a)\n        ld_ru = ein\"urdl -> ldru\"(a)\n        dr, ul = trg_svd(dr_ul, χ, tol)\n        ld, ru = trg_svd(ld_ru, χ, tol)\n\n        a = ein\"npu,por,dom,lmn -> urdl\"(dr,ld,ul,ru)\n    end\n    trace = ein\"ijij -> \"(a)[]\n    lnZ += log(trace)/2.0^niter\n    return lnZ\nend\n\n\nfunction trg_svd(t, dmax, tol)\n    d1, d2, d3, d4 = size(t)\n    tmat = reshape(t, d1*d2, d3*d4)\n    u, s, v = svd(tmat)\n    dmax = min(searchsortedfirst(s, tol, rev=true), dmax, length(s))\n    FS = s[1:dmax]\n    sqrtFSp = sqrt.(FS)\n    u = reshape(ein\"ij,j -> ij\"(u[:,1:dmax],  sqrtFSp), (d1, d2, dmax))\n    v = reshape(ein\"ij,i -> ij\"(copy(v')[1:dmax,:], sqrtFSp), (dmax, d3, d4))\n\n    return u, v\nend\n", "meta": {"hexsha": "12ebdaf298aab540b3a11e6d174883cf22df936e", "size": 1235, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/trg.jl", "max_stars_repo_name": "UnofficialJuliaMirror/TensorNetworkAD.jl-6b36f460-1d4e-5459-a8c4-3ab8f40f7d47", "max_stars_repo_head_hexsha": "7048ad819a73682c05535de814b8212b48502499", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71, "max_stars_repo_stars_event_min_datetime": "2019-05-13T05:23:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:22:49.000Z", "max_issues_repo_path": "src/trg.jl", "max_issues_repo_name": "UnofficialJuliaMirror/TensorNetworkAD.jl-6b36f460-1d4e-5459-a8c4-3ab8f40f7d47", "max_issues_repo_head_hexsha": "7048ad819a73682c05535de814b8212b48502499", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2019-06-06T08:47:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-24T13:31:28.000Z", "max_forks_repo_path": "src/trg.jl", "max_forks_repo_name": "UnofficialJuliaMirror/TensorNetworkAD.jl-6b36f460-1d4e-5459-a8c4-3ab8f40f7d47", "max_forks_repo_head_hexsha": "7048ad819a73682c05535de814b8212b48502499", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-07-30T06:34:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T00:49:43.000Z", "avg_line_length": 25.7291666667, "max_line_length": 77, "alphanum_fraction": 0.5732793522, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915913, "lm_q2_score": 0.8128673133042218, "lm_q1q2_score": 0.7579608205323964}}
{"text": "using SpecialFunctions, NearestNeighbors, Distances, Distributions, Random\n\n\"\"\"\n    n_ball(n::Number)\nComputes the volume of a n-dimensional unit sphere.\n\"\"\"\nfunction n_ball(n::Number)\n    return π^(n/2.) / gamma(n/2. + 1.)\nend\n\n\n\"\"\"\n    kl_entropy(data::Array{Float64, 2}; k=5)\nCompute the nearest-neighbor estimate of the differential entropy of data.\n\ndata is a 2d array, with every column representing one data point. \nFor further information, see\n\n\"A class of Rényi information estimators for multidimensional densities\"\nNikolai Leonenko, Luc Pronzato, and Vippal Savani\nThe Annals of Statistics, 2008\nhttps://projecteuclid.org/euclid.aos/1223908088\n\nkeyword arguments:\nk=5: number of nearest neighbors\n\"\"\"\nfunction kl_entropy(data::Array{Float64, 2}; k=5)\n    d, N = size(data)\n    kdtree = KDTree(data)\n    _, dist = knn(kdtree, data, k+1, true)\n    H = log(N) - digamma(k) + log(n_ball(d)) + d/N * sum(map(l->log(l[end]), dist))\nend\n\n\n\"\"\"\n    kl_mutual_information(x, y; k=5, bias_correction=true)\ncompute the nearest-neighbor 'KGS' estimate of the mutual information between x and y.\n\nx and y are 2d arrays, with every column representing one data point. \nFor further information, see\n\n\"Estimating Mutual Information\"\nAlexander Kraskov, Harald Stoegbauer, and Peter Grassberger\nPhysical Review E\nhttps://arxiv.org/pdf/cond-mat/0305641.pdf\n\n\"Demystifying Fixed k-Nearest Neighbor Information Estimators\"\nWeihao Gao, Sewoong Oh, Pramod Viswanath\nEEE International Symposium on Information Theory - Proceedings\nhttps://arxiv.org/pdf/1604.03006.pdf\n\nkeyword arguments:\nk=5: number of nearest neighbors\nbias_correction=true: flag to apply Gao's bias correction\n\"\"\"\nfunction kl_mutual_information(x, y; k=5, bias_correction=true)\n    dist = bias_correction ? Euclidean() : Chebyshev()\n   \n    d_x, N = size(x)\n    d_y, _ = size(y)\n\n    xy = vcat(x,y)\n\n    kdtree_x = KDTree(x, dist)\n    kdtree_y = KDTree(y, dist)\n    kdtree_xy = KDTree(xy, dist)\n\n    I = 0.\n    \n    for i in 1:N\n        _, dist = knn(kdtree_xy, xy[:,i], k+1, true)\n        n_x = length(inrange(kdtree_x, x[:,i], dist[end], false))-1\n        n_y = length(inrange(kdtree_y, y[:,i], dist[end], false))-1\n        I += digamma(n_x+1) + digamma(n_y+1)\n    end\n\n    I = -I/N + log(N) + digamma(k)\n\n    if bias_correction\n        I += log( n_ball(d_x) * n_ball(d_y)/n_ball(d_x+d_y) )\n    end\n\n    return I\nend\n\n\"\"\"\n    kl_renyi(data::Array{Float64, 2}, q; k=5)\nCompute the nearest-neighbor estimate of the Renyi-alpha entropy of data.\n\ndata is a 2d array, with every column representing one data point. \nFor further information, see\n\n\"A class of Rényi information estimators for multidimensional densities\"\nNikolai Leonenko, Luc Pronzato, and Vippal Savani\nThe Annals of Statistics, 2008\nhttps://projecteuclid.org/euclid.aos/1223908088\n\nkeyword arguments:\nk=5: number of nearest neighbors\n\"\"\"\nfunction kl_renyi(data, q, k=5)\n    d, N = size(data)\n    Vd = π^(d/2.) / gamma(d/2. + 1.)\n    Ck = ( gamma(k)/gamma(k+1-q) )^(1/(1-q))\n    kdtree = KDTree(data)\n    _, dist = knn(kdtree, data, k+1, true)\n    Iq = 1/N * sum(map(l->( (N-1)*Ck*Vd*l[end]^d )^(1-q), dist))\n\n    return log(Iq)/(1-q)\nend\n\n\n\"\"\"\n    kl_cond_mi(x, y, z; k=5, bias_correction=true)\ncompute the nearest-neighbor 'KGS' estimate of the conditional mutual information between x and y given z.\n\nx, y, and z are 2d arrays, with every column representing one data point. \nkeyword arguments:\nk=5: number of nearest neighbors\nbias_correction=true: flag to apply Gao's bias correction\n\"\"\"\nfunction kl_cond_mi(x, y, z; k=5, bias_correction=true)\n    dist = bias_correction ? Euclidean() : Chebyshev()    \n    \n    xz = vcat(x,z)\n    yz = vcat(y,z)\n    xyz = vcat(x,y,z)\n\n    d_x, N = size(x)\n    d_y, _ = size(y)\n    d_z, _ = size(z)\n    \n    kdtree_z = KDTree(z, dist)\n    kdtree_xz = KDTree(xz, dist)\n    kdtree_yz = KDTree(yz, dist)\n    kdtree_xyz = KDTree(xyz, dist)\n    \n    CMI = 0.\n\n    for i in 1:N\n        _, dist = knn(kdtree_xyz, xyz[:,i], k+1, true)\n        n_xz = length(inrange(kdtree_xz, xz[:,i], dist[end], false))-1\n        n_yz = length(inrange(kdtree_yz, yz[:,i], dist[end], false))-1\n        n_z = length(inrange(kdtree_z, z[:,i], dist[end], false))-1\n        CMI = CMI + digamma(n_xz) + digamma(n_yz) - digamma(n_z)\n    end\n\n    CMI = digamma(k) - CMI/N\n\n    if bias_correction\n        CMI += log( (n_ball(d_x + d_z) * n_ball(d_y+d_z))/(n_ball(d_x+d_y+d_z)*n_ball(d_z)))\n    end\n    \n    return CMI\nend\n\n\n\"\"\"\n    kl_perm_mi_test(x, y; k=5, B=100, bias_correction=true)\ncompute permutation test of independence of x and y.\n\nkeyword arguments:\nk=5: number of nearest neighbors to use for mutual information estimate\nB=100: number of permutations\nbias_correction=true: flag to apply Gao's bias correction\n\"\"\"\nfunction kl_perm_mi_test(x, y; k=5, B=100, bias_correction=true)\n    MI = kl_mutual_information(x, y, k=k, bias_correction=bias_correction)\n    samples = Float64[]\n\n    for i in 1:B\n        push!(samples, kl_mutual_information(x, y[:, shuffle(1:end)], k=k, bias_correction=bias_correction))\n    end\n    \n    p = length(filter(d->MI<d, samples))/B\n    return p\nend\n\n\n\"\"\"\n    kl_perm_cond_mi_test(x, y, z; k=5, B=100, kp=5, bias_correction=true)\ncompute permutation test of conditional independence of x and y given z.\n\nFor further information, see:\n\"Conditional independence testing based on a nearest-neighbor estimator of conditional mutual information\"\nJakob Runge\nProceedings of the 21st International Conference on Artificial Intelligence and Statistics (AISTATS) 2018, Lanzarote, Spain.\nhttp://proceedings.mlr.press/v84/runge18a/runge18a.pdf\n\nkeyword arguments:\nk=5: number of nearest neighbors to use for mutual information estimate\nB=100: number of permutations\nbias_correction=true: flag to apply Gao's bias correction\n\n\"\"\"\nfunction kl_perm_cond_mi_test(x, y, z; k=5, B=100, kp=5, bias_correction=true)\n    d, N = size(z)\n    CMI = kl_cond_mi(x,y,z,k=k,bias_correction=bias_correction)\n    samples = Float64[]\n    \n    kdtree_z = KDTree(z, Chebyshev())\n    z_knn, _ = knn(kdtree_z, z, kp+1)\n    \n    for b in 1:B\n        # create permutation for independence test\n        U = Int64[]\n        P = collect(1:N)\n        j = 0\n        Ns = map(shuffle, z_knn)\n        \n        for i in shuffle(collect(1:N))\n            j = Ns[i][1]\n            m = 1\n            while (j ∈ U) && (m < kp)\n                m += 1\n                j = Ns[i][m]\n            end\n            P[i]=j\n            push!(U,j)\n        end\n        push!(samples, kl_cond_mi(x[:,P],y,z,k=k,bias_correction=bias_correction))\n    end\n\n    p = length(filter(d->CMI<d, samples))/B \n    \n    return p\nend\n", "meta": {"hexsha": "2f79c4c9b44dc866a4830c28e6e2e9e37f27e918", "size": 6622, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/klentropy.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/CausalInference.jl-8e462317-f959-576b-b3c1-403f26cec956", "max_stars_repo_head_hexsha": "ba0d6fa8bfc455091f26b766ad5c2eaa6378c61d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 97, "max_stars_repo_stars_event_min_datetime": "2017-09-10T15:50:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T16:10:01.000Z", "max_issues_repo_path": "src/klentropy.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/CausalInference.jl-8e462317-f959-576b-b3c1-403f26cec956", "max_issues_repo_head_hexsha": "ba0d6fa8bfc455091f26b766ad5c2eaa6378c61d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 55, "max_issues_repo_issues_event_min_datetime": "2017-08-25T08:29:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T12:24:18.000Z", "max_forks_repo_path": "src/klentropy.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/CausalInference.jl-8e462317-f959-576b-b3c1-403f26cec956", "max_forks_repo_head_hexsha": "ba0d6fa8bfc455091f26b766ad5c2eaa6378c61d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2017-09-16T11:04:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T15:18:52.000Z", "avg_line_length": 29.0438596491, "max_line_length": 124, "alphanum_fraction": 0.6609785563, "num_tokens": 2017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7579608180685307}}
{"text": "## Packages\nusing ForwardDiff, LinearAlgebra, Plots\n\n## Parameters\nβ = 0.99;\nσ = 2;\nγ = 1;\n\n## Utility functions\nu(x) = x^(1 - σ) / (1 - σ);\nv(x) = x^(1 + 1/γ) / (1 + 1/γ);\nU(c, n) = u(c) - v(n);\n\n## Differentials\nUc(c) = ForwardDiff.derivative(u, c);\nUcc(c) = ForwardDiff.derivative(Uc, c);\n\nUn(n) = -ForwardDiff.derivative(v, n);\nUnn(n) = ForwardDiff.derivative(Un, n);\n\n## Discretizes g and θ\ninclude(\"Tauchen.jl\")\ng, Pg = Tauchen(0.95, (1.2/15)^2, 5, (1 - 0.95) * log(0.15));\nθ, Pθ = Tauchen(0.95, (2/400)^2, 5, (1 - 0.95) * log(1));\ns = vec(collect(Iterators.product(θ, g)));\nPs = kron(Pg, Pθ)\n\ninclude(\"NewtonRoot.jl\");\n\n## This function calculates Ramsey Allocation, given Φ and initial state s0 \nfunction RamseyAllocation(Φ::Real, s0::Tuple)\n\n    function time1_allocation(s::Tuple)\n        log_θ, log_g = s[1], s[2];\n        θ, g = exp(log_θ), exp(log_g);\n        n(c::Real) = (g + c) / θ;\n        res1(c::Real) = (1 + Φ) * (Uc(c) + Un(n(c))) + Φ * (c * Ucc(c) + n(c) * Unn(n(c)));\n        c = NewtonRoot(c -> res1(c), 0.5);\n\n        return c, n(c)\n    end\n\n    c_time1 = [time1_allocation(s[i])[1] for i in 1:length(s)];\n    n_time1 = [time1_allocation(s[i])[2] for i in 1:length(s)];\n\n    function time0_allocation(s::Tuple)\n        log_θ, log_g = s[1], s[2];\n        θ, g = exp(log_θ), exp(log_g);\n        n(c::Real) = (g + c) / θ;\n        b0(c::Real) = 4 * θ * n(c);\n        res0(c::Real) = (1 + Φ) * (Uc(c) + Un(n(c))) + Φ * (c * Ucc(c) + n(c) * Unn(n(c))) - Φ * Ucc(c) * b0(c)\n        c = NewtonRoot(c -> res0(c), 0.5)\n\n        return c, n(c)\n    end\n\n    c_time0, n_time0 = time0_allocation(s0)[1], time0_allocation(s0)[2];\n\n    return c_time1, n_time1, c_time0, n_time0\n\nend\n\n## Updating the value of Φ:\nc_time1, n_time1, c_time0, n_time0 = RamseyAllocation(0.12615792845184043, s[1])\n\nsum_mat = inv(1.0I - β * Ps) * (Uc.(c_time1) .* c_time1 .+ Un.(n_time1) .* n_time1);\nimplementCons = Uc(c_time0) * (4 * exp(s[1][1]) * n_time0) - Uc(c_time0) * c_time0 - Un(n_time0) * n_time0 - β * sum([Ps[1,i] * sum_mat[i] for i in 1:length(sum_mat)]);\n\nb_time1 = sum_mat ./ Uc.(c_time1);\n\nτ_time1 = 1.0 .+ Un.(n_time1) ./ Uc.(c_time1);\n\n## Root finding method for Φ\n\nfunction search_Φ(Φ::Real, s0::Tuple)\n    c_time1, n_time1, c_time0, n_time0 = RamseyAllocation(Φ, s0);\n    \n    i_s0 = findfirst(isequal(s0), s);\n\n    sum_mat = inv(1.0I - β * Ps) * (Uc.(c_time1) .* c_time1 .+ Un.(n_time1) .* n_time1); #this sum is independent of s0\n\n    implementCons = Uc(c_time0) * (4 * exp(s0[1]) * n_time0) - Uc(c_time0) * c_time0 - Un(n_time0) * n_time0 - β * sum([Ps[i_s0,i] * sum_mat[i] for i in 1:length(sum_mat)]);\n\n    return implementCons\n\nend\n\nΦ_est = NewtonRoot(x -> search_Φ(x, s[1]), 0.1) # 0.12615792845184043\n\n#----------------- SIMULATING RAMSEY POLICY WITH STATE CONTINGENT DEBT ----------------------#\ninclude(\"Finite_Markov_Chains.jl\")\nstate_tran = mc_sample_path(Ps, init = 1, sample_size = 1000);\n\nc_sim = [c_time1[i] for i in state_tran];\nn_sim = [n_time1[i] for i in state_tran];\nb_sim = [b_time1[i] for i in state_tran];\nτ_sim = [τ_time1[i] for i in state_tran];\n\nplot(c_sim, label = \"Simulated path C\")\nplot(n_sim, label = \"Simulated path N\")\nplot(b_sim, label = \"Simulated path b\")\nplot(τ_sim, label = \"Simulated path taxes\")\n\n", "meta": {"hexsha": "981dac2fc21e79d6b64d4601c42c21a40ddd64b9", "size": 3246, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Anmol/PS2/main.jl", "max_stars_repo_name": "wongr003/ECON8185", "max_stars_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Anmol/PS2/main.jl", "max_issues_repo_name": "wongr003/ECON8185", "max_issues_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Anmol/PS2/main.jl", "max_forks_repo_name": "wongr003/ECON8185", "max_forks_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2115384615, "max_line_length": 173, "alphanum_fraction": 0.5918052988, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7579608171304766}}
{"text": "mutable struct Point\n    x::Float64\n    y::Float64\nend\n\nmutable struct Vector2D\n    x::Float64\n    y::Float64\nend\n\np = Point(2, 5) #> Point(2.0,5.0)\nv = Vector2D(3, 2) #> Vector2D(3.0,2.0)\n\n# Example with sum:\n# +(p, v) #> MethodError: ERROR: `+` has no method matching +(::Point, ::Vector2D)\n\nimport Base.+\n+(p::Point,    q::Point) = Point(p.x + q.x, p.y + q.y)\n+(u::Vector2D, v::Vector2D) = Point(u.x + v.x, u.y + v.y)\n+(u::Vector2D, p::Point) = Point(u.x + p.x, u.y + p.y)\n# +(p, v) #> ERROR: MethodError: `+` has no method matching +(::Point, ::Vector2D)\n+(p::Point,    v::Vector2D) = Point(p.x + v.x, p.y + v.y)\n+(p, v) #> Point(5.0,7.0)\n\n# Example with dot product:\n# *(p, v) #> ERROR: MethodError: `*` has no method matching *(::Point, ::Vector2D)\n\nimport Base.*\n*(p::Point,    q::Point) = p.x * q.x + p.y * q.y\n*(u::Vector2D, v::Vector2D) = u.x * v.x + u.y * v.y\n*(u::Vector2D, p::Point) = u.x * p.x + u.y * p.y\n# *(p, v) #> ERROR: MethodError: `*` has no method matching *(::Point, ::Vector2D)\n*(p::Point,    v::Vector2D) = p.x * v.x + p.y * v.y\n*(p, v) #> 16.0\n\nVecOrPoint = Union{Vector2D, Point}\n\nisa(p, VecOrPoint) #> true\nisa(v, VecOrPoint) #> true\n\n+(u::VecOrPoint, v:: VecOrPoint) = VecOrPoint(u.x + v.x, u.y + v.y)\n+(p, v) #> Point(5.0,7.0)\n\n*(u::VecOrPoint, v:: VecOrPoint) = u.x * v.x + u.y * v.y\n*(p, v) #> 16.0", "meta": {"hexsha": "d99db39deeaab0dc73c75b0b63d60fdc99012f2c", "size": 1331, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter06/unions.jl", "max_stars_repo_name": "TrainingByPackt/Julia-1-Programming-Complete-reference-guide", "max_stars_repo_head_hexsha": "bc7d9d4bc090daa9a6e0757aa62f73fe394f3905", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-08-27T19:21:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T02:15:16.000Z", "max_issues_repo_path": "Chapter06/unions.jl", "max_issues_repo_name": "TrainingByPackt/Julia-1-Programming-Complete-reference-guide", "max_issues_repo_head_hexsha": "bc7d9d4bc090daa9a6e0757aa62f73fe394f3905", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter06/unions.jl", "max_forks_repo_name": "TrainingByPackt/Julia-1-Programming-Complete-reference-guide", "max_forks_repo_head_hexsha": "bc7d9d4bc090daa9a6e0757aa62f73fe394f3905", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-02-22T07:25:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T14:38:48.000Z", "avg_line_length": 29.5777777778, "max_line_length": 82, "alphanum_fraction": 0.5574755823, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.8705972650509008, "lm_q1q2_score": 0.7579395891451215}}
{"text": "\nusing ApproxFun\nusing Plots\nusing BenchmarkTools\n\n\nfunction sir_eqn(S,I,u0,p)\n  (β,γ) = p\n  (S0,I0) = u0\n   return [S(0)-S0,\n           I(0)-I0,\n           S' + β*S*I,\n           I' - β*S*I + γ*I]\nend;\n\n\ntmax = 40.0\nt=Fun(identity, 0..tmax);\n\n\nu0 = [990.0,10.0]; # S,I\n\n\np = [0.0005,0.25]; # β,γ\n\n\nS,I = newton((S,I)->sir_eqn(S,I,u0,p), u0 .* one(t); maxiterations=50);\n\n\nplot(S,label=\"S\",xlabel=\"Time\",ylabel=\"Number\")\nplot!(I,label=\"I\")\n\n\n@benchmark newton((S,I)->sir_eqn(S,I,u0,p), u0 .* one(t); maxiterations=50)\n\n", "meta": {"hexsha": "54e4be488cc9977537e9116584b87dd0e8fd9406", "size": 519, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_approxfun/ode_approxfun.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/ode_approxfun/ode_approxfun.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/ode_approxfun/ode_approxfun.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.4166666667, "max_line_length": 75, "alphanum_fraction": 0.5433526012, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7579323922055038}}
{"text": "using PhysicalConstants.CODATA2018: FineStructureConstant, ReducedPlanckConstant, ElectronMass, SpeedOfLightInVacuum\n\n\"\"\"\ncomptonShift(θ, E)\n\nThe fractional energy of the scattered X-ray resulting from a Compton event with an incident X-ray energy of `E` eV at a scatter angle of `θ` radians.\n\"\"\"\ncomptonShift(θ, E) = 1.0 / (1.0 + (E / mₑ) * (1.0 - cos(θ)))\ncomptonShift(θ, cxr::CharXRay) = comptonShift(θ, energy(cxr))\n\n\"\"\"\ncomptonEnergy(θ, E)\n\nThe energy of the scattered X-ray resulting from a Compton event with an incident X-ray energy of `E` eV at a scatter angle of `θ` radians.\n\"\"\"\ncomptonEnergy(θ, E) = E * comptonShift(θ, E)\ncomptonEnergy(θ, cxr::CharXRay) = comptonEnergy(θ, energy(cxr))\n\n\"\"\"\ncomptonAngular(θ, E)\n\nThe angular distribution function of Compton scattered X-rays of incident energy `E` scattered to an angle `θ`.\n\nBased on the Klein-Nishina formula for Compton scattering. It has been normalized so that the integral over dΩ = 2π⋅sin(θ) dθ equals one.\n\"\"\"\nfunction comptonAngular(θ, E)\n  p = comptonShift(θ, E)\n  den = (4π*mₑ*((E*(E^3 + 9*E^2*mₑ + 8*E*mₑ^2 + 2*mₑ^3))/(2E +mₑ)^2 + (E^2 - 2*E*mₑ - 2*mₑ^2)*atan(E/(E + mₑ))))/E^3\n  return p^2*(p + 1.0/p - sin(θ)^2)/den\nend\ncomptonAngular(θ, cxr::CharXRay) = comptonAngular(θ, energy(cxr))\n\n\n\"\"\"\n  comptonDifferential(θ, E)\n\nDifferential crosssection dσ/dΩ = dσ/(sin(θ) dθ dϕ) for Compton scattering in cm².\n\"\"\"\nfunction comptonDifferential(θ, E) \n  α, rc =  convert(Float64,FineStructureConstant), convert(Float64,(ReducedPlanckConstant/(ElectronMass*SpeedOfLightInVacuum))/u\"cm\")\n  p = comptonShift(θ, E)\n  return 0.5*(α*rc*p)^2*(p + 1.0/p - sin(θ)^2)\nend\n\n", "meta": {"hexsha": "9bc1caa79d17c92490ecce9110f14a5825faa6db", "size": 1632, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/compton.jl", "max_stars_repo_name": "NicholasWMRitchie/NeXLCore.jl", "max_stars_repo_head_hexsha": "ac7a896c54f24140415f6c25c5bb1773ca89f6c5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-11-29T15:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T12:29:16.000Z", "max_issues_repo_path": "src/compton.jl", "max_issues_repo_name": "NicholasWMRitchie/NeXLCore.jl", "max_issues_repo_head_hexsha": "ac7a896c54f24140415f6c25c5bb1773ca89f6c5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/compton.jl", "max_forks_repo_name": "NicholasWMRitchie/NeXLCore.jl", "max_forks_repo_head_hexsha": "ac7a896c54f24140415f6c25c5bb1773ca89f6c5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-05T15:03:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-05T15:03:00.000Z", "avg_line_length": 36.2666666667, "max_line_length": 150, "alphanum_fraction": 0.7015931373, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7579323818336603}}
{"text": "\nfunction FFT_prepare(f)\n\tfor _i in 1:f.len\n\t\tp=0\n\t\ti=_i-1\n\t\tfor j in 1:f.bits\n\t\t\tp=(p*2)+ ( (i%2)==1 ? 1 : 0 )\n\t\t\ti=fld(i,2)\n\t\tend\n\t\t#println(_i-1,\" \",p)\n\t\tf.exchangeMap[_i]=p+1\n\tend\n\tfor i in 1:fld(f.len,2)\n\t\tang=-2*pi*(i-1)/f.len\n\t\tf.e[i]=cos(ang)+sin(ang)*im\n\tend\n\treturn f\nend\n\nstruct FFT\n\tbits::Integer\n\tlen::Integer\n\texchangeMap\n\te\n\tFFT(bits)=FFT_prepare(new(\tbits,\n\t\t\t\t\t2^bits,\n\t\t\t\t\tzeros(Int,2^bits),\n\t\t\t\t\tzeros(Complex,2^(bits-1))))\nend\n\nfunction (fft::FFT)(f)\n\tF=zeros(Complex,2^(fft.bits) )\n\tfor i in 1:fft.len\n\t\tF[fft.exchangeMap[i]]=f[i]\n\tend\n\n\tfor i in 0:(fft.bits-1)\n\t\tunitSize_2=2^i\n\t\tunitSize=2*unitSize_2\n\t\tunitNum=2^(fft.bits-i-1)\n\t\t\n\t\t#=\n\t\tfor j in 1:unitSize:\n\t\t\tcoef=fft.e[(j-1)*unitNum+1]\n\t\t\tfor k in 0:(unitNum-1):\n\t\t\t\tpPre= unitSize*k+j\n\t\t\t\tpPost=pPre+unitSize_2\n\t\t\t\tpre=F[pPre]\n\t\t\t\tpost=F[pPost]\n\t\t\t\tF[pPre]=pre+coef*post\n\t\t\t\tF[pPost]=pre-coef*post\n\t\t=#\n\t\tfor k in 0:(unitNum-1)\n\t\t\toffset=unitSize*k+1\n\t\t\tfor j in 0:(unitSize_2-1)\n\t\t\t\tcoef=fft.e[j*unitNum+1]\n\t\t\t\tpPre=offset+j\n\t\t\t\tpPost=pPre+unitSize_2\n\t\t\t\tpre=F[pPre]\n\t\t\t\tpost=F[pPost]*coef\n\t\t\t\t#println([pre,post,coef])\n\t\t\t\tF[pPre]=pre+post\n\t\t\t\tF[pPost]=pre-post\n\t\t\tend\n\t\tend\n\tend\n\treturn F./fft.len\nend\n\nf2=FFT(2)\nf2=FFT(2)\nprintln(f2)\nprintln(f2([0,1,2,3]))\n\nprintln()\nf3=FFT(3)\nprintln(f3)\nprintln(f3(0:7))\nF10=FFT(10)\nfor i in 1:(10)\n\tF10(rand(1024))\nend\n", "meta": {"hexsha": "185acc51f7049d0923361604647494369b206c78", "size": 1338, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "FFT.jl", "max_stars_repo_name": "cqb98/fft", "max_stars_repo_head_hexsha": "3eb5a803e8712ae2821ac91930d552972ce888c5", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-16T22:57:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T22:57:14.000Z", "max_issues_repo_path": "FFT.jl", "max_issues_repo_name": "cqb98/fft", "max_issues_repo_head_hexsha": "3eb5a803e8712ae2821ac91930d552972ce888c5", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FFT.jl", "max_forks_repo_name": "cqb98/fft", "max_forks_repo_head_hexsha": "3eb5a803e8712ae2821ac91930d552972ce888c5", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.1204819277, "max_line_length": 33, "alphanum_fraction": 0.6046337818, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7579323799057919}}
{"text": "include(\"differencial.jl\")\r\n\"\"\"\r\n`RK4(F,A,dt)`\r\nRunge-Kutta法で刻み時間`dt`秒後のFの値を計算する関数\r\n## Arguments\r\n- `F::Any`: 計算したい時間`t`の関数の`t`秒時点の値 関数`dif`で微分値を求められるもの\r\n- `A::Any`:微分計算に必要な定数の組\r\n- `dt::Number`  :刻み時間\r\n## Returns\r\n- `dt`秒後のFの値\r\n\"\"\"\r\nfunction RK4(F,A,dt)\r\n    f=dif(F,A)\r\n    k1=dt.*f\r\n    k2=dt.*dif((F.+k1),A)\r\n    k3=dt.*dif((F.+0.5.*(k1.+k2)),A)\r\n    k4=dt.*dif((F.+k1.+k3),A)\r\n    return F.+(k1.+2.0.*k2.+2.0.*k3.+k4)./6\r\nend\r\n", "meta": {"hexsha": "f182cc28044e16e00651c7f0f92ddafc97686a92", "size": 431, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dynamics/RungeKutta.jl", "max_stars_repo_name": "yui-project/ACSim", "max_stars_repo_head_hexsha": "cbf75654ef050d11ab25650b71481fa2a418ca75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-07T04:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T13:59:38.000Z", "max_issues_repo_path": "dynamics/RungeKutta.jl", "max_issues_repo_name": "yui-project/ACSim", "max_issues_repo_head_hexsha": "cbf75654ef050d11ab25650b71481fa2a418ca75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-03-04T15:07:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-18T04:29:29.000Z", "max_forks_repo_path": "dynamics/RungeKutta.jl", "max_forks_repo_name": "yui-project/ACSim", "max_forks_repo_head_hexsha": "cbf75654ef050d11ab25650b71481fa2a418ca75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-01T14:00:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-01T14:00:37.000Z", "avg_line_length": 21.55, "max_line_length": 55, "alphanum_fraction": 0.5522041763, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7579305098348794}}
{"text": "module OLS\n\nusing Distributions\nexport ols\nexport olstable\n\nfunction ols(y,x)\n\tx   = hcat(ones(size(x, 1)), x)\n\tb   = (x'*x)\\x'*y\n\tr   = y-x*b\n\t\n\tnobs = size(y, 1)         # number of observations\n\tncoef = size(x, 2)        # number of coefficients\n\tdf_e = nobs - ncoef       # degrees of freedom, error\n\tdf_r = ncoef - 1          # degrees of freedom, regression\n\t\n\ttss = (y-mean(y))'*(y-mean(y))\n\trss = r'*r\n\tess = tss-rss\n\t\n\tR2  = ess./tss                      # R-squared\n\tR2adj = 1 - (1 - R2) * ((nobs - 1) / (nobs - ncoef)) # R2 adjusted\n\tF = (R2 / df_r) / ((1 - R2) / df_e) # model F-statistic\n\t\n\ts2  = rss/(nobs-ncoef)    # Residual variance\n\ts2  = s2[1,1] \t\t\t\t\t\t# convert to float\n\tcov = s2.*inv(x'*x)                 # OLS variance-covariance matri\n\tse  = sqrt(diag(cov))              # OLS standard errors\n\tt   = b./se \t\t\t\t\t\t# T-value\n\tp   = ccdf(TDist(df_e), abs(t))*2      # P-values\n    return b, se, t, R2, R2adj, F, s2, p\nend\n\n# Print function\nfunction olstable(title,lbly,lblx,b,se,t,R2,R2adj,F,s2,p)\n# Print output in a table\nprintln(\"\")\nprintln(title)\nprintln(string(\"Dependent Variable: \", lbly))\nprintln(\"========================================================\")\nprintln(\"Variable     Parm. Val.  Std. Err.  t-Value    Pr(>|t|)\")\nfor (i, j, s, t, p) in zip(lblx, b, se ,t, p)\n@printf(\"%-10s\",i), @printf(\"%11.4f\",j), @printf(\"%11.4f\", s), @printf(\"%11.4f\", t), @printf(\"%11.4f\\n\", p)\nend\nprintln(\"--------------------------------------------------------\")\nprintln(string(\"R-squared:           \" , round(R2[1,1],2)))\nprintln(string(\"Adjusted R-Squared:  \" , round(R2adj[1,1],2)))\nprintln(string(\"Sigma-squared:       \" , round(s2[1,1],2)))\nprintln(string(\"F-Statistic :        \" , round(F[1,1],2)))\nprintln(\"========================================================\")\nend\n\nend # module\n", "meta": {"hexsha": "531f1aa49cfb5be74a97dd9428dcceaa60803882", "size": 1806, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/OLS.jl", "max_stars_repo_name": "rudvfaden/OLS", "max_stars_repo_head_hexsha": "bb213af3b1bf049e66f031d7f3a6d684dae82ab8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/OLS.jl", "max_issues_repo_name": "rudvfaden/OLS", "max_issues_repo_head_hexsha": "bb213af3b1bf049e66f031d7f3a6d684dae82ab8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OLS.jl", "max_forks_repo_name": "rudvfaden/OLS", "max_forks_repo_head_hexsha": "bb213af3b1bf049e66f031d7f3a6d684dae82ab8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-10-20T12:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-20T12:05:03.000Z", "avg_line_length": 33.4444444444, "max_line_length": 107, "alphanum_fraction": 0.5099667774, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.757930507741317}}
{"text": "function chisq_goodness(x::AbstractVector{T}) where {T <: Real}\n    # figure out number of bins, which depends on length(x)\n    nbins = round(Int, ceil(2 * (length(x)^(2/5))))\n\n    # create a `range` object\n    bin_range = range(-3, 3, length = nbins + 1)\n\n    # use StatsBase `fit` function to count number of observations per bin\n    bincounts = fit(Histogram, x, bin_range).weights\n\n    # use `pdf` function to find expected number of observations per bin\n    bin_centers = bin_range[1:end-1] .+ bin_range.step.hi / 2\n    expected_pdf = pdf.(Normal(0, 1), bin_centers)\n    bin_expected = floor.(Int, expected_pdf .* sum(bincounts) / sum(expected_pdf))\n\n    # calcuate pearson stats (X2)\n    𝜒² = pearson_chi(bincounts, bin_expected)\n\n    # calculate X2/DF and return it\n    return 𝜒² / nbins\nend\n\nfunction pearson_chi(\n    observed::AbstractVector{T},\n    expected::AbstractVector{T}\n) where {T <: Integer}\n    χ² = 0\n    for i = 1:length(observed)\n        χ² += (observed[i] - expected[i])^2 / expected[i]\n    end\n    return χ²\nend\n", "meta": {"hexsha": "6802825adfe79d607487547c8e392683d372cf3d", "size": 1036, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chisq.jl", "max_stars_repo_name": "khkwong/Normalize.jl", "max_stars_repo_head_hexsha": "b0907881c51f50640fe8502ad682c36271a09342", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/chisq.jl", "max_issues_repo_name": "khkwong/Normalize.jl", "max_issues_repo_head_hexsha": "b0907881c51f50640fe8502ad682c36271a09342", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-08-01T19:42:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-29T15:52:05.000Z", "max_forks_repo_path": "src/chisq.jl", "max_forks_repo_name": "khkwong/Normalize.jl", "max_forks_repo_head_hexsha": "b0907881c51f50640fe8502ad682c36271a09342", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3939393939, "max_line_length": 82, "alphanum_fraction": 0.6611969112, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7579305068835646}}
{"text": "# this is a little Monte Carlo exercise that illustrates that\n# the OLS estimator is unbiased when we have strong exogeneity\nusing Plots\nreps = 1000 # number of Monte Carlo reps.\nn = 20 # sample size\nsig = 3.0  # st. dev. of errors\n\nx = [ones(n,1) randn(n,1)]  # x is fixed over repeated samples\nbeta = [1.0, 2.0] # true beta\nPopRegLine = x*beta\n\ne = sig*randn(n,reps) # reps will be in columns\ny = PopRegLine .+ e\n\nbetas = inv(x'x)*x'y\n\nbetas[2,:] .-=  2.0\nhistogram(betas[2,:], label = \"\")\ngui()\n#savefig(\"Unbiased.svg\")\n\t\n", "meta": {"hexsha": "48948e7b73aa029891c9ccb7b1e177c037073e22", "size": 525, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/OLS/Unbiased.jl", "max_stars_repo_name": "nilshg/Econometrics", "max_stars_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-17T06:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T06:32:18.000Z", "max_issues_repo_path": "Examples/OLS/Unbiased.jl", "max_issues_repo_name": "nilshg/Econometrics", "max_issues_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/OLS/Unbiased.jl", "max_forks_repo_name": "nilshg/Econometrics", "max_forks_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-02T08:27:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-02T08:27:17.000Z", "avg_line_length": 23.8636363636, "max_line_length": 62, "alphanum_fraction": 0.6666666667, "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7579305006760267}}
{"text": "include(\"misc.jl\")\ninclude(\"findMin.jl\")\n\nfunction softmaxObj(w,X,y, k)\n        (n, d) = size(X)\n        f = 0\n        for i = 1:n\n          b = 0\n          for c = 1:k\n            b += exp(w[:, c]' * X[i, :])\n          end\n          f += -w[:, y[i]]' * X[i, :] + log(b)\n        end\n\tg = zeros(d,k)\n        for i = 1:n\n          b = 0\n          for c = 1:k\n            b += exp(w[:, c]' * X[i, :])\n          end\n          for c = 1:k\n            if y[i] == c\n\t      g[:,c] += -X[i, :]\n            end\n            g[:,c] += 1/b * exp(w[:, c]' * X[i, :]) * X[i, :]\n          end\n        end\n        #a = -w[:, y]*X\n        #b = w[:, ones(k, size(y,2)) * (1:Int(k))']*X\n\t#f = sum(a + log(b))\n\tdisplay(f)\n\tdisplay(g)\n\treturn (f,g)\nend\n\n# Multi-class softmax classifier\nfunction softmaxClassifier(X,y)\n\t(n,d) = size(X)\n\tk = maximum(y)\n\n\n\tW = zeros(d,k)\n\n\tdisplay(size(W))\n\n\t# Each binary objective has the same features but different lables\n\tfunObj(w) = softmaxObj(w,X,y, k)\n\n\tW = findMin(funObj, W, verbose=true)#, derivativeCheck=true)\n\n\t# Make linear prediction function\n\t#predict(Xhat) = findmax(Xhat*W)[2]\n\tpredict(Xhat) = mapslices(indmax,Xhat*W,2)\n\n\treturn LinearModel(predict,W)\nend\n", "meta": {"hexsha": "ed09c223b8d90838626246eb520bd243ac731f6c", "size": 1186, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "a1sol/softmaxClassifier.jl", "max_stars_repo_name": "d4l3k/cs540", "max_stars_repo_head_hexsha": "049617af46048b5471877b9bdfb0bd8a65f3cf0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "a1sol/softmaxClassifier.jl", "max_issues_repo_name": "d4l3k/cs540", "max_issues_repo_head_hexsha": "049617af46048b5471877b9bdfb0bd8a65f3cf0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "a1sol/softmaxClassifier.jl", "max_forks_repo_name": "d4l3k/cs540", "max_forks_repo_head_hexsha": "049617af46048b5471877b9bdfb0bd8a65f3cf0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1785714286, "max_line_length": 67, "alphanum_fraction": 0.4637436762, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7579304949481827}}
{"text": "using Polynomials\nusing Plots\ninclude(\"funkcje.jl\")\n\n\nfunction makeSpline(coordinates)\n    function CalculateCs()\n        μ = [NaN64 for k in 1:n]\n        α = vcat([0.], [3. * (A[k+1] - A[k])/h[k] - 3. * (A[k] - A[k-1])/h[k-1] for k in 2:n])\n\n        C = [0. for k in 1:nPlus1]\n        l = [0. for k in 1:nPlus1]\n        z = [0. for k in 1:nPlus1]\n\n        l[1] = 1.\n        μ[1] = 0.\n        z[1] = 0.\n\n        for k in 2:n\n            l[k] = 2 * (xs[k+1] - xs[k-1]) - h[k-1] * μ[k-1]\n            μ[k] = h[k] / l[k]\n            z[k] = (α[k] - h[k-1]*z[k-1]) / l[k]\n        end\n\n        l[nPlus1] = 1.\n        z[nPlus1] = 0.\n        C[nPlus1] = 0.\n\n        for k in n:(-1):1\n            C[k] = z[k] - μ[k]*C[k+1]\n        end\n        return C\n    end\n    nPlus1 = length(coordinates)\n    n = nPlus1 - 1\n    # x1 x2 ... xk+1\n    xs = map(pair->pair[1], coordinates)\n    # y1 y2 ... yk+1\n    # ys = map(pair->pair[2], coordinates)\n    A = map(pair->pair[2], coordinates)\n\n    h = [xs[k+1] - xs[k] for k in 1:n]\n    C = CalculateCs()\n\n    B = [(A[k+1] - A[k]) / h[k] - h[k]*(C[k+1] + 2. * C[k]) / 3. for k in 1:n]\n    D = [(C[k+1] - C[k]) / (3. * h[k]) for k in 1:n]\n\n    outputSet = [Poly(NaN) for k in 1:n]\n    intervals = myzip(xs,xs[2:end])\n\n    for k in 1:n\n        xk = xs[k]\n        polynom = A[k] + B[k]*poly([xk]) + C[k]*(poly([xk])^2) + D[k]*(poly([xk]) ^ 3)\n        outputSet[k] = polynom\n    end\n    return myzip(outputSet, intervals)\nend\n\n\n\n\nfunction findRoot(polyn, c)\n    interval = polyn[2]\n    xk = interval[1]\n    xkPlus1 = interval[2]\n    polynomial = polyn[1]\n\n    rooty = roots(polynomial - c)\n    filter!(z -> imag(z) == 0., rooty)\n    rooty = map(z -> real(z), rooty)\n\n    filter!(x -> xk <= x <= xkPlus1, rooty)\n    return rooty\nend\n\nfunction findRoots(splines, c)\n    Rootki = map(p -> findRoot(p,c), splines)\n    filter!(r -> length(r) != 0, Rootki)\n    return Rootki\nend\n\nfunction PlotMain(coor, splajn, pierwiastki, c, a, b, name, prec = 0.01)\n    function PlotSpline()\n        xs = []\n        ys = []\n        # ysPrim = []\n        # ysPrimPrim = []\n        for i in 1:length(splajn)\n            xk = splajn[i][2][1]\n            xkPlus1 = splajn[i][2][2]\n            wielomian = splajn[i][1]\n            xs = vcat(xs, [x for x in xk:prec:xkPlus1])\n            ys = vcat(ys, map(wielomian, [x for x in xk:prec:xkPlus1]))\n            # ysPrim = vcat(ysPrim, map(polyder(wielomian), [x for x in xk:prec:xkPlus1]))\n            # ysPrimPrim = vcat(ysPrimPrim, map(polyder(polyder(wielomian)), [x for x in xk:prec:xkPlus1]))\n        end\n        plot!(plotka, xs, ys, lab = \"Naturalna funkcja sklejana s(x)\", linecolor=:blue)\n        # plot!(plotka, xs, ysPrim, lab = \"Naturalna funkcja sklejana s'(x)\", linecolor=:green)\n        # plot!(plotka, xs, ysPrimPrim, lab = \"Naturalna funkcja sklejana s''(x)\", linecolor=:black)\n    end\n    function PlotRoots()\n        scatter!(plotka, pierwiastki, map(x->c, pierwiastki), lab = \"Pierwiastki równania f(x) = c\", color=:orange, markersize = 11)\n    end\n    function PlotC()\n        plot!(plotka, [a,b], [c,c], lab = \"y=c\",  linecolor=:black, linewidth=5)\n    end\n    function PlotF()\n        xs, ys = myunzip(coor)\n        scatter!(plotka, xs, ys, lab = \"Zadane punkty (x,f(x))\", color=:green)\n    end\n\n    plotka = plot(legend = :topright)\n    xlabel!(plotka, \"Os x\")\n    ylabel!(plotka, \"Os y\")\n    title!(string(\"Wykres s(x), y=c, pierwiastków s(x) = y\", name))\n    PlotSpline()\n    PlotRoots()\n    PlotC()\n    PlotF()\n    display(plotka)\n    savefig(plotka, name)\nend\n\nfunction main(coor, c, name=\"\")\n    coor = sort(coor)\n    splajn = makeSpline(coor)\n    pierwiastki = VectorToList(findRoots(splajn, c))\n\n    a = coor[1][1]\n    b = coor[end][1]\n\n    PlotMain(coor, splajn, pierwiastki, c, a, b, name)\n    return pierwiastki\nend\n", "meta": {"hexsha": "6764082dac8c436d29cd3445aff9bde5b925c385", "size": 3795, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "II rok/I semestr/ANM/Pracownia 2/prog/program.jl", "max_stars_repo_name": "antonitomaszewski/Studia", "max_stars_repo_head_hexsha": "ff2fa59e25cf3f5c86b59de9994b80a502ec1e7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "II rok/I semestr/ANM/Pracownia 2/prog/program.jl", "max_issues_repo_name": "antonitomaszewski/Studia", "max_issues_repo_head_hexsha": "ff2fa59e25cf3f5c86b59de9994b80a502ec1e7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "II rok/I semestr/ANM/Pracownia 2/prog/program.jl", "max_forks_repo_name": "antonitomaszewski/Studia", "max_forks_repo_head_hexsha": "ff2fa59e25cf3f5c86b59de9994b80a502ec1e7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1111111111, "max_line_length": 132, "alphanum_fraction": 0.5222661397, "num_tokens": 1408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741281688026, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7579233279115788}}
{"text": "# Functions for calculating exact overlap between shapes.\n#\n# Original cython version by Thomas Robitaille released under a\n# 3-clause BSD-style license.\n\n# Return area of a circle arc between (x1, y1) and (x2, y2) with radius r\n# reference: http://mathworld.wolfram.com/CircularSegment.html\nfunction area_arc(x1, y1, x2, y2, r)\n  a = sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1))\n  theta = 2. * asin(0.5 * a / r)\n  return 0.5 * r * r * (theta - sin(theta))\nend\n\n# Area of a triangle defined by three verticies\narea_triangle(x1, y1, x2, y2, x3, y3) =\n    0.5 * abs(x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2))\n\n# Core of circular overlap routine.\n# Assumes that xmax >= xmin >= 0.0, ymax >= ymin >= 0.0.\n# (can always modify input to conform to this).\nfunction circoverlap_core(xmin, ymin, xmax, ymax, r)\n\n    xmin2 = xmin * xmin\n    ymin2 = ymin * ymin\n    r2 = r * r\n    (xmin2 + ymin2 > r2) && return 0.0\n\n    xmax2 = xmax * xmax\n    ymax2 = ymax * ymax\n    (xmax2 + ymax2 < r2) && return (xmax-xmin) * (ymax-ymin)\n\n    a = xmax2 + ymin2  # (corner 1 distance)^2\n    b = xmin2 + ymax2  # (corner 2 distance)^2\n\n    if (a < r2 && b < r2)\n        x1 = sqrt(r2 - ymax2)\n        y1 = ymax\n        x2 = xmax\n        y2 = sqrt(r2 - xmax2)\n        return ((xmax - xmin) * (ymax - ymin) -\n                area_triangle(x1, y1, x2, y2, xmax, ymax) +\n\t            area_arc(x1, y1, x2, y2, r))\n\n    elseif (a < r2)\n        x1 = xmin\n        y1 = sqrt(r2 - xmin2)\n        x2 = xmax\n        y2 = sqrt(r2 - xmax2)\n        return (area_arc(x1, y1, x2, y2, r) +\n                area_triangle(x1, y1, x1, ymin, xmax, ymin) +\n                area_triangle(x1, y1, x2, ymin, x2, y2))\n\n    elseif (b < r2)\n        x1 = sqrt(r2 - ymin2)\n        y1 = ymin\n        x2 = sqrt(r2 - ymax2)\n        y2 = ymax\n        return (area_arc(x1, y1, x2, y2, r) +\n                area_triangle(x1, y1, xmin, y1, xmin, ymax) +\n                area_triangle(x1, y1, xmin, y2, x2, y2))\n\n    else\n        x1 = sqrt(r2 - ymin2)\n        y1 = ymin\n        x2 = xmin\n        y2 = sqrt(r2 - xmin2)\n        return (area_arc(x1, y1, x2, y2, r) +\n                area_triangle(x1, y1, x2, y2, xmin, ymin))\n    end\nend\n\n\n# Area of overlap of a rectangle and a circle\nfunction circoverlap(xmin, ymin, xmax, ymax, r)\n\n    # some subroutines demand that r > 0\n    (r <= 0.0) && return 0.0\n\n    if (0.0 <= xmin)\n        (0.0 <= ymin) && return circoverlap_core(xmin, ymin, xmax, ymax, r)\n        (0.0 >= ymax) && return circoverlap_core(-ymax, xmin, -ymin, xmax, r)\n        return (circoverlap(xmin, ymin, xmax, 0.0, r) +\n                circoverlap(xmin, 0.0, xmax, ymax, r))\n\n    elseif (0.0 >= xmax)\n        (0.0 <= ymin) && return circoverlap_core(-xmax, ymin, -xmin, ymax, r)\n        (0.0 >= ymax) && return circoverlap_core(-xmax, -ymax, -xmin, -ymin, r)\n        return (circoverlap(xmin, ymin, xmax, 0.0, r) +\n                circoverlap(xmin, 0.0, xmax, ymax, r))\n\n    else\n        (0.0 <= ymin) && return (circoverlap(xmin, ymin, 0.0, ymax, r) +\n                                 circoverlap(0.0, ymin, xmax, ymax, r))\n        (0.0 >= ymax) && return (circoverlap(xmin, ymin, 0.0, ymax, r) +\n                                 circoverlap(0.0, ymin, xmax, ymax, r))\n        return (circoverlap(xmin, ymin, 0.0, 0.0, r) +\n                circoverlap(0.0, ymin, xmax, 0.0, r) +\n                circoverlap(xmin, 0.0, 0.0, ymax, r) +\n                circoverlap(0.0, 0.0, xmax, ymax, r))\n    end\nend\n\n\n# -----------------------------------------------------------------------------\n# ellipse-rectangle overlap\n\n# internal types\nimmutable Point\n    x::Float64\n    y::Float64\nend\n\nimmutable Intersections\n    p1::Point\n    p2::Point\nend\n\n# rotate -> a, b, c = b, c, a\n\n# Check if a point (x,y) is inside a triangle\nfunction in_triangle(x, y, x1, y1, x2, y2, x3, y3)\n    c = 0\n    c += ((y1 > y) != (y2 > y)) && (x < (x2-x1) * (y-y1) / (y2-y1) + x1)\n    c += ((y2 > y) != (y3 > y)) && (x < (x3-x2) * (y-y2) / (y3-y2) + x2)\n    c += ((y3 > y) != (y1 > y)) && (x < (x1-x3) * (y-y3) / (y1-y3) + x3)\n\n    return c % 2 == 1\nend\n\n\n# Intersection of a line defined by two points with a unit circle\nfunction circle_line(x1, y1, x2, y2)\n\n    tol = 1.e-10\n\n    dx = x2 - x1\n    dy = y2 - y1\n\n    if abs(dx) < tol && abs(dy) < tol\n        return Intersections(Point(2.0, 2.0), Point(2.0, 2.0))\n\n    elseif abs(dx) > abs(dy)\n\n        # Find the slope and intercept of the line\n        a = dy / dx\n        b = y1 - a * x1\n\n        # Find the determinant of the quadratic equation\n        delta = 1.0 + a*a - b*b\n        if (delta > 0.)  # solutions exist\n\t    delta = sqrt(delta)\n            p1x = (-a*b - delta) / (1. + a*a)\n            p2x = (-a*b + delta) / (1. + a*a)\n            return Intersections(Point(p1x, a * p1x + b),\n                                 Point(p2x, a * p2x + b))\n        else             # no solutions exist\n            return Intersections(Point(2.0, 2.0), Point(2.0, 2.0))\n        end\n\n    else\n\n        # Find the slope and intercept of the line\n        a = dx / dy\n        b = x1 - a * y1\n\n        # Find the determinant of the quadratic equation\n        delta = 1.0 + a*a - b*b\n        if (delta > 0.)  # solutions exist\n\t    delta = sqrt(delta)\n\t    p1y = (-a*b - delta) / (1. + a*a)\n            p2y = (-a*b + delta) / (1.0 + a*a)\n            return Intersections(Point(a * p1y + b, p1y),\n                                 Point(a * p2y + b, p2y))\n        else  # no solution, return values > 1\n            return Intersections(Point(2.0, 2.0), Point(2.0, 2.0))\n        end\n    end\nend\n\n\n# The intersection of a line with the unit circle. The intersection\n# closest to (x2, y2) is chosen.\nfunction circle_segment_single2(x1, y1, x2, y2)\n    inter = circle_line(x1, y1, x2, y2)\n\n    dx1 = abs(inter.p1.x - x2)\n    dy1 = abs(inter.p1.y - y2)\n    dx2 = abs(inter.p2.x - x2)\n    dy2 = abs(inter.p2.y - y2)\n\n    if (dx1 > dy1)  # compare based on x-axis\n        return (dx1 > dx2) ? inter.p2 : inter.p1\n    else\n        return (dy1 > dy2) ? inter.p2 : inter.p1\n    end\nend\n\n# Intersection(s) of a segment with the unit circle. Discard any\n# solution not on the segment.\nfunction circle_segment(x1, y1, x2, y2)\n    inter = circle_line(x1, y1, x2, y2)\n    pt1 = inter.p1\n    pt2 = inter.p2\n\n    if ((pt1.x > x1 && pt1.x > x2) || (pt1.x < x1 && pt1.x < x2) ||\n        (pt1.y > y1 && pt1.y > y2) || (pt1.y < y1 && pt1.y < y2))\n        pt1 = Point(2.0, 2.0)\n    end\n\n    if ((pt2.x > x1 && pt2.x > x2) || (pt2.x < x1 && pt2.x < x2) ||\n        (pt2.y > y1 && pt2.y > y2) || (pt2.y < y1 && pt2.y < y2))\n        pt2 = Point(2.0, 2.0)\n    end\n\n    if pt1.x > 1. && pt2.x < 2.\n        return Intersections(pt1, pt2)\n    else\n        return Intersections(pt2, pt1)\n    end\nend\n\n\n# Given a triangle defined by three points (x1, y1), (x2, y2), and\n# (x3, y3), find the area of overlap with the unit circle.\nfunction triangle_unitcircle_overlap(x1, y1, x2, y2, x3, y3)\n\n    # Find distance of all vertices to circle center\n    d1 = x1*x1 + y1*y1\n    d2 = x2*x2 + y2*y2\n    d3 = x3*x3 + y3*y3\n\n    # Order vertices by distance from origin\n    if (d1 < d2)\n\n        if (d2 < d3)\n\n        elseif (d1 < d3)\n\t    x2, x3 = x3, x2\n            y2, y3 = y3, y2\n            d2, d3 = d3, d2\n\n        else\n            # rotate -> a, b, c = b, c, a\n            x1, x2, x3 = x3, x1, x2\n            y1, y2, y3 = y3, y1, y2\n            d1, d2, d3 = d3, d1, d2\n        end\n    else\n        if d1 < d3\n            x1, x2 = x2, x1\n            y1, y2 = y2, y1\n            d1, d2 = d2, d1\n        elseif d2 < d3\n            x1, x2, x3 = x2, x3, x1\n            y1, y2, y3 = y2, y3, y1\n            d1, d2, d3 = d2, d3, d1\n        else\n            x1, x3 = x3, x1\n            y1, y3 = y3, y1\n            d1, d3 = d3, d1\n        end\n    end\n\n    # Determine number of vertices inside circle\n    in1 = d1 < 1.0\n    in2 = d2 < 1.0\n    in3 = d3 < 1.0\n\n    # Determine which vertices are on the circle\n    on1 = abs(d1 - 1.0) < 1e-10\n    on2 = abs(d2 - 1.0) < 1e-10\n    on3 = abs(d3 - 1.0) < 1e-10\n\n    if (on3 || in3)  # triangle completely within circle\n        area = area_triangle(x1, y1, x2, y2, x3, y3)\n\n    elseif (in2 || on2)\n        # If vertex 1 or 2 are on the edge of the circle, then we use\n        # the dot product to vertex 3 to determine whether an\n        # intersection takes place.\n        intersect13 = !on1 || (x1*(x3-x1) + y1*(y3-y1) < 0.0)\n        intersect23 = !on2 || (x2*(x3-x2) + y2*(y3-y2) < 0.0)\n\n        if (intersect13 && intersect23)\n\t    pt1 = circle_segment_single2(x1, y1, x3, y3)\n\t    pt2 = circle_segment_single2(x2, y2, x3, y3)\n\t    area = (area_triangle(x1, y1, x2, y2, pt1.x, pt1.y) +\n\t\t    area_triangle(x2, y2, pt1.x, pt1.y, pt2.x, pt2.y) +\n\t\t    area_arc(pt1.x, pt1.y, pt2.x, pt2.y, 1.0))\n        elseif (intersect13)\n\t  pt1 = circle_segment_single2(x1, y1, x3, y3)\n\t  area = (area_triangle(x1, y1, x2, y2, pt1.x, pt1.y) +\n\t\t  area_arc(x2, y2, pt1.x, pt1.y, 1.0))\n        elseif (intersect23)\n\t  pt2 = circle_segment_single2(x2, y2, x3, y3)\n\t  area = (area_triangle(x1, y1, x2, y2, pt2.x, pt2.y) +\n\t\t  area_arc(x1, y1, pt2.x, pt2.y, 1.0))\n        else\n\t    area = area_arc(x1, y1, x2, y2, 1.0)\n        end\n\n    elseif in1\n        # Check for intersections of far side with circle\n        inter = circle_segment(x2, y2, x3, y3)\n        pt1 = inter.p1\n        pt2 = inter.p2\n        pt3 = circle_segment_single2(x1, y1, x2, y2)\n        pt4 = circle_segment_single2(x1, y1, x3, y3)\n\n        if pt1.x > 1.0  # indicates no intersection\n\n\t    # check if the pixel vertex (x1, y2) and the origin are on\n\t    # different sides of the circle segment. If they are, the\n\t    # circle segment spans more than pi radians.\n\t    # We use the formula (y-y1) * (x2-x1) > (y2-y1) * (x-x1)\n\t    # to determine if (x, y) is on the left of the directed\n\t    # line segment from (x1, y1) to (x2, y2)\n\t    if (((0.-pt3.y) * (pt4.x-pt3.x) > (pt4.y-pt3.y) * (0.-pt3.x)) !=\n\t        ((y1-pt3.y) * (pt4.x-pt3.x) > (pt4.y-pt3.y) * (x1-pt3.x)))\n\t        area = (area_triangle(x1, y1, pt3.x, pt3.y, pt4.x, pt4.y) +\n\t\t        pi - area_arc(pt3.x, pt3.y, pt4.x, pt4.y, 1.0))\n\t    else\n\t        area = (area_triangle(x1, y1, pt3.x, pt3.y, pt4.x, pt4.y) +\n\t\t        area_arc(pt3.x, pt3.y, pt4.x, pt4.y, 1.0))\n\t    end\n        else\n            # ensure that pt1 is the point closest to (x2, y2)\n\t    if (((pt2.x-x2)*(pt2.x-x2) + (pt2.y-y2)*(pt2.y-y2)) <\n\t        ((pt1.x-x2)*(pt1.x-x2) + (pt1.y-y2)*(pt1.y-y2)))\n                pt1, pt2 = pt2, pt2\n            end\n\t    area = (area_triangle(x1, y1, pt3.x, pt3.y, pt1.x, pt1.y) +\n\t\t    area_triangle(x1, y1, pt1.x, pt1.y, pt2.x, pt2.y) +\n\t\t    area_triangle(x1, y1, pt2.x, pt2.y, pt4.x, pt4.y) +\n\t\t    area_arc(pt1.x, pt1.y, pt3.x, pt3.y, 1.0) +\n\t\t    area_arc(pt2.x, pt2.y, pt4.x, pt4.y, 1.0))\n\tend\n\n    else\n        inter = circle_segment(x1, y1, x2, y2)\n        pt1 = inter.p1\n        pt2 = inter.p2\n        inter = circle_segment(x2, y2, x3, y3)\n        pt3 = inter.p1\n        pt4 = inter.p2\n        inter = circle_segment(x3, y3, x1, y1)\n        pt5 = inter.p1\n        pt6 = inter.p2\n\n        if (pt1.x <= 1.0)\n\t    xp = 0.5 * (pt1.x + pt2.x)\n\t    yp = 0.5 * (pt1.y + pt2.y)\n\t    area = (triangle_unitcircle_overlap(x1, y1, x3, y3, xp, yp) +\n\t\t    triangle_unitcircle_overlap(x2, y2, x3, y3, xp, yp))\n\n        elseif (pt3.x <= 1.)\n\t    xp = 0.5 * (pt3.x + pt4.x)\n\t    yp = 0.5 * (pt3.y + pt4.y)\n\t    area = (triangle_unitcircle_overlap(x3, y3, x1, y1, xp, yp) +\n\t\t    triangle_unitcircle_overlap(x2, y2, x1, y1, xp, yp))\n\n        elseif (pt5.x <= 1.)\n\t    xp = 0.5 * (pt5.x + pt6.x)\n\t    yp = 0.5 * (pt5.y + pt6.y)\n\t    area = (triangle_unitcircle_overlap(x1, y1, x2, y2, xp, yp) +\n\t\t    triangle_unitcircle_overlap(x3, y3, x2, y2, xp, yp))\n\n        else  # no intersections\n\t  return in_triangle(0., 0., x1, y1, x2, y2, x3, y3) ? pi : 0.0\n        end\n    end\n\n    return area\nend\n\n# exact overlap between a rectangle defined by (xmin, ymin, xmax,\n# ymax) and an ellipse with major and minor axes rx and ry\n# respectively and position angle theta.\nfunction ellipoverlap(xmin, ymin, xmax, ymax, a, b, theta)\n    cos_m_theta = cos(-theta)\n    sin_m_theta = sin(-theta)\n\n    scale = a * b  # areas will be shrunk by this scale\n\n    # Reproject rectangle to a frame in which ellipse is a unit circle\n    x1 = (xmin * cos_m_theta - ymin * sin_m_theta) / a\n    y1 = (xmin * sin_m_theta + ymin * cos_m_theta) / b\n    x2 = (xmax * cos_m_theta - ymin * sin_m_theta) / a\n    y2 = (xmax * sin_m_theta + ymin * cos_m_theta) / b\n    x3 = (xmax * cos_m_theta - ymax * sin_m_theta) / a\n    y3 = (xmax * sin_m_theta + ymax * cos_m_theta) / b\n    x4 = (xmin * cos_m_theta - ymax * sin_m_theta) / a\n    y4 = (xmin * sin_m_theta + ymax * cos_m_theta) / b\n\n    # Divide resulting quadrilateral into two triangles and find\n    # intersection with unit circle\n    return scale * (triangle_unitcircle_overlap(x1, y1, x2, y2, x3, y3) +\n\t\t    triangle_unitcircle_overlap(x1, y1, x4, y4, x3, y3))\nend\n", "meta": {"hexsha": "64180e3b9024fea55bbae44e4503355f6d0c32ee", "size": 12946, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/overlap.jl", "max_stars_repo_name": "kbarbary/AperturePhotometry.jl", "max_stars_repo_head_hexsha": "ab73e35c20a183cc5e47343dee58ce4a157a563f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/overlap.jl", "max_issues_repo_name": "kbarbary/AperturePhotometry.jl", "max_issues_repo_head_hexsha": "ab73e35c20a183cc5e47343dee58ce4a157a563f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/overlap.jl", "max_forks_repo_name": "kbarbary/AperturePhotometry.jl", "max_forks_repo_head_hexsha": "ab73e35c20a183cc5e47343dee58ce4a157a563f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-01T17:09:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:09:00.000Z", "avg_line_length": 32.365, "max_line_length": 79, "alphanum_fraction": 0.5290437201, "num_tokens": 4808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296944, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.7579233246978297}}
{"text": "module Clusters\n\nexport create_uniform_cluster_ncube, create_uniform_cluster_nsphere, compute_centroid\n\nusing LinearAlgebra, Plots\n\n\"\"\"\n    create_uniform_cluster_ncube(center, perturbation, num_points)\n\nCreates a cluster of size `num_points`, where each point is uniformly randomly\nselected from the volume of an n-cube centered at `center`, aligned with the\nstandard basis, and with edge length 2 * `perturbation`\n\nReturns a `num_points` * length(`center`) matrix, where each row is a point in\nthe cluster.\n\"\"\"\nfunction create_uniform_cluster_ncube(center::AbstractVector{<:Number},\n                                      perturbation::Number,\n                                      num_points::Integer)::AbstractMatrix{<:AbstractFloat}\n    # (num_points, 1)\n    ones_vec = ones(Integer, (num_points, 1))\n    # (1, length(center))\n    center_T = transpose(center)\n    # (num_points, length(center)), where each row is a copy of center\n    center_vecs = ones_vec * center_T\n\n    # Generate uniformly random values between [0, perturbation) and negate some\n    # randomly in order to avoid floating point precision errors and preserve\n    # symmetry of the distribution.\n    random_perturbations =\n        perturbation * rand(Float64, (num_points, length(center)))\n    random_flips = rand([-1, 1], (num_points, length(center)))\n\n    return center_vecs + (random_perturbations .* random_flips)\nend\n\n\"\"\"\n    create_uniform_cluster_nsphere(center, perturbation, num_points)\n\nCreates a cluster of size `num_points`, centered around `center`, where each\npoint is uniformly randomly selected from the volume of an n-sphere with radius\n'perturbation'.\n\nReturns a `num_points` * length(`center`) matrix, where each row is a point in\nthe cluster.\n\"\"\"\nfunction create_uniform_cluster_nsphere(center::AbstractVector{<:Number},\n                                        perturbation::Number,\n                                        num_points::Integer)::AbstractMatrix{<:AbstractFloat}\n    # (num_points, 1)\n    ones_vec = ones(Integer, (num_points, 1))\n    # (1, length(center))\n    center_T = transpose(center)\n    # (num_points, length(center)), where each row is a copy of center\n    center_vecs = ones_vec * center_T\n\n    # num_points * length(center) standard normal random variables\n    rand_vecs = randn(Float64, (num_points, length(center)))\n    # Take the norm along each column.\n    # num_points\n    norms = map(LinearAlgebra.norm,\n                [rand_vecs[n,:] for n in 1:size(rand_vecs, 1)])\n    # num_points uniform in [0, 1)\n    uniform_coeffs = rand(Float64, num_points)\n\n    origin_cluster = perturbation *\n        Diagonal(uniform_coeffs .^ (1/length(center))) *\n        Diagonal(1 ./ norms) *\n        rand_vecs\n\n    return center_vecs + origin_cluster\nend\n\n\"\"\"\n    compute_centroid(points)\n\nComputes the centroid of a matrix of points.\n\n`points` is an m * n matrix that describes m points (rows) of dimension n\n(columns).\n\nReturns a single vector of size `n` corresponding to the centroid.\n\"\"\"\nfunction compute_centroid(\n        points::AbstractMatrix{<:Number})::AbstractVector{<:AbstractFloat}\n    point_sum = sum(points, dims=1)[:]\n    return point_sum ./ size(points, 1)\nend\n\n\"\"\"\n    plot_cluster(points)\n\nPlots a matrix of points, where each row represents the coordinates of a single\npoint.\n\"\"\"\nfunction plot_cluster(points::AbstractMatrix{<:Number})\n    plt = plot([points[:,n] for n in 1:size(points, 2)]...,\n               seriestype = :scatter,\n               showaxis = :show,\n               aspect_ratio = :equal)\n    display(plt)\nend\n\nend # module\n", "meta": {"hexsha": "d2c335b1052040ca1234edfcafe6a0ebf3e0b6e9", "size": 3566, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/clusters/clusters.jl", "max_stars_repo_name": "brianxie/automaton-edification", "max_stars_repo_head_hexsha": "d432604a9eb1ac01b9f99567ece0f00f4145a4f1", "max_stars_repo_licenses": ["BSD-2-Clause-Patent"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/clusters/clusters.jl", "max_issues_repo_name": "brianxie/automaton-edification", "max_issues_repo_head_hexsha": "d432604a9eb1ac01b9f99567ece0f00f4145a4f1", "max_issues_repo_licenses": ["BSD-2-Clause-Patent"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/clusters/clusters.jl", "max_forks_repo_name": "brianxie/automaton-edification", "max_forks_repo_head_hexsha": "d432604a9eb1ac01b9f99567ece0f00f4145a4f1", "max_forks_repo_licenses": ["BSD-2-Clause-Patent"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9619047619, "max_line_length": 93, "alphanum_fraction": 0.6808749299, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760638, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7579233119221315}}
{"text": "# # Usage Guide\n\n# In this example, we will present the basics of using Ripserer. We start by loading some\n# packages.\n\nusing Distances\nusing Plots\nusing Ripserer\nusing Random # hide\nRandom.seed!(1337) # hide\ngr() # hide\nnothing # hide\n\n# ## Using Ripserer With Point Cloud Data\n\n# Let's start with generating some points, randomly sampled from a noisy circle.\n\nfunction noisy_circle(n; r=1, noise=0.1)\n    points = NTuple{2,Float64}[]\n    for _ in 1:n\n        θ = 2π * rand()\n        push!(points, (r * sin(θ) + noise * rand(), r * cos(θ) + noise * rand()))\n    end\n    return points\nend\n\ncirc_100 = noisy_circle(100)\nscatter(circ_100; aspect_ratio=1, legend=false, title=\"Noisy Circle\")\n\n# !!! tip \"Point-like data types\"\n#     Ripserer can interpret various kinds of data as point clouds. The limitation is that\n#     the data set should be an `AbstractVector` with elements with the following\n#     properties:\n#     * all elements are collections numbers;\n#     * all elements have the same length.\n#     Examples of element types that work are `Tuple`s,\n#     [`SVector`](https://github.com/JuliaArrays/StaticArrays.jl)s, and\n#     [`Point`](https://github.com/JuliaGeometry/GeometryBasics.jl)s.\n\n# To compute the Vietoris-Rips persistent homology of this data set, run the\n# following.\n\nripserer(circ_100)\n\n# You can use the `dim_max` argument to set the maximum dimension persistent homology is\n# computed in.\n\nresult_rips = ripserer(circ_100; dim_max=3)\n\n# The result can be plotted as a persistence diagram or as a barcode.\n\nplot(result_rips)\nbarcode(result_rips)\nplot(plot(result_rips), barcode(result_rips)) # hide\n\n# We can also plot a single diagram or a subset of all diagrams in the same manner. Keep in\n# mind that the result is just a vector of [`PersistenceDiagram`](@ref)s. The\n# zero-dimensional diagram is found at index 1.\n\nplot(result_rips[2])\nbarcode(result_rips[2:end]; linewidth=2)\nplot(plot(result_rips[2]), barcode(result_rips[2:end]; linewidth=2)) # hide\n\n# Plotting can be further customized using the standard attributes from\n# [Plots.jl](http://docs.juliaplots.org/latest/).\n\nplot(result_rips; markeralpha=1, markershape=:star, color=[:red, :blue, :green, :purple])\n\n# ## Changing Filtrations\n\n# By default, calling [`ripserer`](@ref) will compute persistent homology with the\n# [`Rips`](@ref) filtration. To use a different filtration, we have two options.\n\n# The first option is to pass the filtration constructor as the first argument. Any keyword\n# arguments the filtration accepts can be passed to [`ripserer`](@ref) and it will be\n# forwarded to the constructor.\n\nripserer(EdgeCollapsedRips, circ_100; threshold=1, dim_max=3, metric=Euclidean())\n\n# The second option is to initialize the filtration object first and use that as an argument\n# to [`ripserer`](@ref). This can be useful in cases where constructing the filtration takes\n# a long time.\n\ncollapsed_rips = EdgeCollapsedRips(circ_100; threshold=1, metric=Euclidean())\nripserer(collapsed_rips; dim_max=3)\n\n# ## Distance Matrix Inputs\n\n# In the previous example, we got our result by passing a collection of points to\n# [`ripserer`](@ref). Under the hood, [`Rips`](@ref) and [`EdgeCollapsedRips`](@ref)\n# actually work with distance matrices. Let's define a distance matrix of the shortest\n# paths on a [regular icosahedron](https://en.wikipedia.org/wiki/Regular_icosahedron) graph.\n\n# ```@raw html\n# <img src=\"https://upload.wikimedia.org/wikipedia/commons/8/83/Icosahedron_graph.svg\" height=\"200\" width=\"200\">\n# ```\n\nicosahedron = [\n    0 1 2 2 1 2 1 1 2 2 1 3\n    1 0 3 2 1 1 2 1 2 1 2 2\n    2 3 0 1 2 2 1 2 1 2 1 1\n    2 2 1 0 3 2 1 1 2 1 2 1\n    1 1 2 3 0 1 2 2 1 2 1 2\n    2 1 2 2 1 0 3 2 1 1 2 1\n    1 2 1 1 2 3 0 1 2 2 1 2\n    1 1 2 1 2 2 1 0 3 1 2 2\n    2 2 1 2 1 1 2 3 0 2 1 1\n    2 1 2 1 2 1 2 1 2 0 3 1\n    1 2 1 2 1 2 1 2 1 3 0 2\n    3 2 1 1 2 1 2 2 1 1 2 0\n]\nnothing # hide\n\n# To compute the persistent homology, simply feed the distance matrix to [`ripserer`](@ref).\n\nresult_icosa = ripserer(icosahedron; dim_max=2)\n\n# ## Thresholding\n\n# In our next example, we will show how to use thresholding to speed up computation. We\n# start by defining a sampling function that generates ``n`` points from the square\n# ``[-4,4]\\times[-4,4]`` with a circular hole of radius 1 in the middle.\n\nfunction cutout(n)\n    points = NTuple{2,Float64}[]\n    while length(points) < n\n        x, y = (8rand() - 4, 8rand() - 4)\n        if x^2 + y^2 > 1\n            push!(points, (x, y))\n        end\n    end\n    return points\nend\n\n# We sample 2000 points from this space.\n\ncutout_2000 = cutout(2000)\nscatter(cutout_2000; markersize=1, aspect_ratio=1, legend=false, title=\"Cutout\")\n\n# We calculate the persistent homology and time the calculation.\n\n@time result_cut = ripserer(cutout_2000)\nnothing # hide\n\n#\n\nplot(result_cut)\n\n# Notice that while there are many 1-dimensional classes, one of them stands out. This class\n# represents the hole in the middle of our square. Since the intervals are sorted by\n# persistence, we know the last interval in the diagram will be the most persistent.\n\nmost_persistent = result_cut[2][end]\n\n# Notice the death time of this interval is around 1.83 and that no intervals occur after\n# that time. This means that we could stop computing when we reach this time and the result\n# should not change. Let's try it out.\n\n@time result_cut_thresh_2 = ripserer(cutout_2000; threshold=2)\nnothing # hide\n\n#\n\nplot(result_cut_thresh_2; title=\"Persistence Diagram, threshold=2\")\n\n# Indeed, the result is exactly the same, but it took less than a third of the time to\n# compute.\n\n@assert result_cut_thresh_2 == result_cut # hide\nresult_cut_thresh_2 == result_cut\n\n# If we pick a threshold that is too low, we still detect the interval, but its death time\n# becomes infinite.\n\n@time result_cut_thresh_1 = ripserer(cutout_2000; threshold=1)\nnothing # hide\n\n#\n\nresult_cut_thresh_1[2][end]\n\n# ## Persistence Diagrams\n\n# The result of a computation is returned as a vector of\n# [`PersistenceDiagram`](@ref)s. Let's take a closer look at one of those.\n\ndiagram = result_cut[2]\n\n# The diagram is a structure that acts as a vector of\n# [`PersistenceInterval`](@ref)s. As such, you can use standard Julia\n# functions on the diagram.\n\n# For example, to extract the last three intervals by birth time, you can do\n# something like this.\n\nsort(diagram; by=birth, rev=true)[1:3]\n\n# To find the [`persistence`](@ref)s of all the intervals, you can use broadcasting.\n\npersistence.(diagram)\n\n# Unlike regular vectors, a [`PersistenceDiagram`](@ref) has additional metadata attached\n# to it. To see all metadata, use\n# [`propertynames`](https://docs.julialang.org/en/v1/base/base/#Base.propertynames).\n\npropertynames(diagram)\n\n# You can access the properties with the dot syntax.\n\ndiagram.field\n\n# The attributes `dim` and `threshold` are given special treatment and can be extracted\n# with appropriately named functions.\n\ndim(diagram), threshold(diagram)\n\n# Now, let's take a closer look at one of the intervals.\n\ninterval = diagram[end]\n\n# An interval is very similar to a tuple of two `Float64`s, but also has some metadata\n# associated with it.\n\ninterval[1], interval[2]\n\n# [`birth`](@ref), [`death`](@ref), [`persistence`](@ref), and [`midlife`](@ref) can be used\n# to query commonly used values.\n\nbirth(interval), death(interval), persistence(interval), midlife(interval)\n\n# Accessing metadata works in a similar manner as with diagrams.\n\npropertynames(interval)\n\n#\n\ninterval.birth_simplex\n\n#\n\ninterval.death_simplex\n\n# ## Simplices\n\n# In the previous section, we saw each interval has an associated [`birth_simplex`](@ref)\n# and [`death_simplex`](@ref). These values are of the type [`Simplex`](@ref). Let's take a\n# closer look at simplices.\n\nsimplex = interval.death_simplex\n\n# [`Simplex`](@ref) is an internal data structure that uses some tricks to increase\n# efficiency. For example, if we were to\n# [`dump`](https://docs.julialang.org/en/v1/base/io-network/#Base.dump) it, we notice the\n# vertices are not actually stored in the simplex itself.\n\ndump(simplex)\n\n# To access the vertices, we use [`vertices`](@ref).\n\nvertices(simplex)\n\n# Other useful attributes a simplex has are [`index`](@ref), [`dim`](@ref), and\n# [`birth`](@ref).\n\nindex(simplex), dim(simplex), birth(simplex)\n\n# A few additional notes on simplex properties.\n\n# * A `D`-dimensional simplex is of type `Simplex{D}` and has `D + 1` vertices.\n# * [`vertices`](@ref) are always sorted in descending order.\n# * [`index`](@ref) and [`dim`](@ref) can be used to uniquely identify a given simplex.\n# * [`birth`](@ref) determines when a simplex is added to a filtration.\n\n# ## Conclusion\n\n# This concludes the basic usage of Ripserer. For more detailed information, please check\n# out the [API](@ref) page, as well as other examples.\n", "meta": {"hexsha": "17cf04e2aa2227c9208148bea2adab937af8b1c5", "size": 8796, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/basics.jl", "max_stars_repo_name": "davidhien/Ripserer.jl", "max_stars_repo_head_hexsha": "95391396bea1b2b922967f7da21de05d6b3b67bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2020-06-03T11:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T21:37:46.000Z", "max_issues_repo_path": "docs/src/examples/basics.jl", "max_issues_repo_name": "davidhien/Ripserer.jl", "max_issues_repo_head_hexsha": "95391396bea1b2b922967f7da21de05d6b3b67bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 149, "max_issues_repo_issues_event_min_datetime": "2020-04-09T07:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T10:20:46.000Z", "max_forks_repo_path": "docs/src/examples/basics.jl", "max_forks_repo_name": "davidhien/Ripserer.jl", "max_forks_repo_head_hexsha": "95391396bea1b2b922967f7da21de05d6b3b67bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-08-06T22:56:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T14:55:51.000Z", "avg_line_length": 31.6402877698, "max_line_length": 112, "alphanum_fraction": 0.7175989086, "num_tokens": 2547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.8670357598021707, "lm_q1q2_score": 0.7578562225610276}}
{"text": "# ---\n# title: 134. Gas Station\n# id: problem134\n# author: AquaIndigo\n# date: 2020-11-18\n# difficulty: Medium\n# categories: Greedy\n# link: <https://leetcode.com/problems/gas-station/description/>\n# hidden: true\n# ---\n# \n# There are _N_ gas stations along a circular route, where the amount of gas at\n# station _i_ is `gas[i]`.\n# \n# You have a car with an unlimited gas tank and it costs `cost[i]` of gas to\n# travel from station _i_ to its next station ( _i_ +1). You begin the journey\n# with an empty tank at one of the gas stations.\n# \n# Return the starting gas station's index if you can travel around the circuit\n# once in the clockwise direction, otherwise return -1.\n# \n# **Note:**\n# \n#   * If there exists a solution, it is guaranteed to be unique.\n#   * Both input arrays are non-empty and have the same length.\n#   * Each element in the input arrays is a non-negative integer.\n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: \n#     gas  = [1,2,3,4,5]\n#     cost = [3,4,5,1,2]\n#     \n#     Output: 3\n#     \n#     Explanation: Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\n#     Travel to station 4. Your tank = 4 - 1 + 5 = 8\n#     Travel to station 0. Your tank = 8 - 2 + 1 = 7\n#     Travel to station 1. Your tank = 7 - 3 + 2 = 6\n#     Travel to station 2. Your tank = 6 - 4 + 3 = 5\n#     Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.\n#     Therefore, return 3 as the starting index.\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: \n#     gas  = [2,3,4]\n#     cost = [3,4,3]\n#     \n#     Output: -1\n#     \n#     Explanation: You can't start at station 0 or 1, as there is not enough gas to travel to the next station.\n#     Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\n#     Travel to station 0. Your tank = 4 - 3 + 2 = 3\n#     Travel to station 1. Your tank = 3 - 3 + 3 = 3\n#     You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.\n#     Therefore, you can't travel around the circuit once no matter where you start.\n#     \n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction can_complete_circuit(gas::Vector{Int}, cost::Vector{Int})\n    gas .-= cost\n    accumulate!(+, gas, gas)\n    if gas[end] < 0\n        return -1\n    end\n    return argmin(gas) % length(gas)\nend\n## @lc code=end\n", "meta": {"hexsha": "e3a6cda87cd670728dd6feab7d41b2bdedffbcba", "size": 2350, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/134.gas-station.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/134.gas-station.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/134.gas-station.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 30.1282051282, "max_line_length": 111, "alphanum_fraction": 0.6165957447, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7577533382336343}}
{"text": "###################################################\n# METODO DO GRADIENTE, COMO DESCRITO NO SLIDE 29 DE\n#   https://leonardosecchin.github.io/files/otim1/4.1.Metodos_descida_gerais.pdf\n# Autor: Leonardo D. Secchin\n# Data : 31/01/2021\n#\n# Exemplos de uso:\n#   gradiente(nlp);\n#   gradiente(nlp, x0=[1;1]);\n#   gradiente(nlp, eps=1e-8);\n#   x, f, gradnorm, iter, status = gradiente(nlp, x0=[1;1], eps=1e-8, maxiter=2000, saidas=true);\n# onde 'nlp' é a estrutura MathOptNLPModel do problema.\n###################################################\n\n# carrega pacotes necessários\nusing JuMP, NLPModels, NLPModelsJuMP, Printf, LinearAlgebra\n\n\n# FUNÇÃO PRINCIPAL\nfunction gradiente(nlp; x0=nothing, eps=1.0e-6, maxiter=1000, saidas=true)\n\n    # DADOS DE ENTRADA\n    # nlp     : estrutura MathOptNLPModel do problema\n    # x0      : ponto inicial (opcional)\n    # eps     : precisão para convergencia (opcional, padrão=1.0e-6)\n    # maxiter : número máximo de iterações (opcional, padrão=1000)\n    # saidas  : mensagens na tela?\n\n    # DADOS DE SAÍDA\n    # x       : último iterando\n    # f       : f(x)\n    # gradnorm: norma do infinito do gradiente de f\n    # iter    : número de iterações\n    # status  : 0=sucesso, 1=falha\n\n    iter   = 0\n    status = 1\n\n    # parâmetro busca linear inexata (Armijo)\n    eta = 0.5\n\n    # define ponto inicial caso não fornecido\n    if x0 == nothing\n        # captura ponto inicial da estrutura nlp\n        if nlp.meta.x0 != nothing\n            x0 = nlp.meta.x0\n        else\n            # caso não exista, seta x0=origem\n            x0 = zeros(Float64,nlp.meta.nvar)\n        end\n    end\n\n    # f, gradiente e norma\n    x        = float(x0)\n    f        = obj(nlp, x)\n    gradf    = grad(nlp, x)\n    gradnorm = norm(gradf, Inf)\n\n    # imprimi cabeçalho saídas\n    if saidas\n        @printf(\"\\nit     \\tf         |grad|\\n==========================\")\n        @printf(\"\\n%d\\t%8.2e  %8.2e\", iter, f, gradnorm)\n    end\n\n    while gradnorm > eps && iter < maxiter\n        # direção descida\n        d = -gradf\n\n        # retorna novo iterando após busca linear (Armijo)\n        x, f = armijo(nlp, x, f, gradf, d, eta)\n\n        # atualiza dados do iterando\n        gradf    = grad(nlp, x)\n        gradnorm = norm(gradf, Inf)\n        iter += 1\n\n        # imprimi iteração corrente\n        if saidas\n            if mod(iter,20) == 0\n                @printf(\"\\n\\nit     \\tf         |grad|\\n==========================\")\n            end\n            @printf(\"\\n%d\\t%8.2e  %8.2e\", iter, f, gradnorm)\n        end\n    end\n\n    # status de sucesso\n    if gradnorm <= eps\n        status = 0\n    end\n\n    # saída\n    if saidas\n        println(\"\\n\\n*******************************\")\n        if status == 0\n            println(\"PROBLEMA RESOLVIDO COM SUCESSO!\")\n        else\n            println(\"FALHA NA RESOLUÇÃO.\")\n        end\n        println(\"*******************************\\n\")\n    end\n\n    return x, f, gradnorm, iter, status\nend\n\n\n# BUSCA LINEAR\nfunction armijo(nlp, x, f, gradf, d, eta)\n\n    # calcula gradf' * d\n    gtd = gradf' * d\n\n    # passo inicial\n    t = 1\n\n    # Armijo com backtracking\n    xnew = x + t*d\n    fnew = obj(nlp, xnew)\n\n    while t > 1e-20 && fnew > f + t*eta*gtd\n        # divide t por 10\n        t /= 10.0\n\n        # nova tentativa\n        xnew = x + t*d\n        fnew = obj(nlp, xnew)\n    end\n\n    # retorna novo iterando\n    return xnew, fnew\nend\n", "meta": {"hexsha": "2b1e72017331db09534ecefab305d7fd2644947f", "size": 3383, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "files/julia/gradiente.jl", "max_stars_repo_name": "leonardosecchin/temp", "max_stars_repo_head_hexsha": "8f9cbe618d96b77e5f52c847f754f9c48cb4d442", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-12-24T03:21:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-17T23:37:51.000Z", "max_issues_repo_path": "files/julia/gradiente.jl", "max_issues_repo_name": "leonardosecchin/temp", "max_issues_repo_head_hexsha": "8f9cbe618d96b77e5f52c847f754f9c48cb4d442", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "files/julia/gradiente.jl", "max_forks_repo_name": "leonardosecchin/temp", "max_forks_repo_head_hexsha": "8f9cbe618d96b77e5f52c847f754f9c48cb4d442", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-26T19:00:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T19:00:19.000Z", "avg_line_length": 25.8244274809, "max_line_length": 97, "alphanum_fraction": 0.5237954478, "num_tokens": 1088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8652240825770432, "lm_q1q2_score": 0.7577520019916505}}
{"text": "\"\"\"\n    alpha(t::Real, lastspike, q, tau)\n    alpha(t::Real, lastspike::AbstractArray{<:Real}, q::AbstractArray{<:Real}, tau::AbstractArray{<:Real})\n    alpha(t::Real, lastspike::CuVecOrMat{<:Real}, q::CuVecOrMat{<:Real}, tau::CuVecOrMat{<:Real})\n\nEvaluate an alpha synapse. Modeled as `(t - lastspike) * (q / τ) * exp(-(t - lastspike - τ) / τ) Θ(t - lastspike)`\n  (where `Θ` is the Heaviside function).\nUse `CuVector` instead of `Vector` for GPU support.\n\n# Fields\n- `t`: current time\n- `lastspike`: last pre-synaptic spike time\n- `q`: amplitude\n- `tau`: time constant\n\"\"\"\nfunction alpha(t::Real, lastspike, q, tau)\n    Δ = t - lastspike\n\n    return (Δ >= 0 && Δ < Inf) * Δ * (q / tau) * exp(-(Δ - tau) / tau)\nend\nfunction alpha(t::Real, lastspike::AbstractArray{<:Real}, q::AbstractArray{<:Real}, tau::AbstractArray{<:Real})\n    Δ = t .- lastspike\n    I = @. Δ * (q / tau) * exp(-(Δ - tau) / tau)\n\n    return map((δ, i) -> (δ >= 0) && (δ < Inf) ? δ * i : zero(i), Δ, I)\nend\nfunction alpha(t::Real, lastspike::CuVecOrMat{<:Real}, q::CuVecOrMat{<:Real}, tau::CuVecOrMat{<:Real})\n    Δ = t .- lastspike\n\n    return @. (Δ >= 0) * (Δ < Inf) * Δ * (q / tau) * exp(-(Δ - tau) / tau)\nend", "meta": {"hexsha": "c6735fdd72f934f2708aa7b4498012f1cbbfb575", "size": 1181, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/synapses/alpha.jl", "max_stars_repo_name": "RashikaKarki/SpikingNNFunctions.jl", "max_stars_repo_head_hexsha": "ae3147e2286291063f5ebc73b8a94582d3ff12d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/synapses/alpha.jl", "max_issues_repo_name": "RashikaKarki/SpikingNNFunctions.jl", "max_issues_repo_head_hexsha": "ae3147e2286291063f5ebc73b8a94582d3ff12d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/synapses/alpha.jl", "max_forks_repo_name": "RashikaKarki/SpikingNNFunctions.jl", "max_forks_repo_head_hexsha": "ae3147e2286291063f5ebc73b8a94582d3ff12d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-08T01:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T16:50:52.000Z", "avg_line_length": 38.0967741935, "max_line_length": 114, "alphanum_fraction": 0.5910245555, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7577100150902064}}
{"text": "function gausshermite( n::Integer )\n    x,w = unweightedgausshermite(n)\n    w .*= exp.(-x.^2)\n    x, w\nend\nfunction unweightedgausshermite( n::Integer )\n    # GAUSSHERMITE(n) COMPUTE THE GAUSS-HERMITE NODES AND WEIGHTS IN O(n) time.\n    if n < 0\n        x = (Float64[],Float64[])\n        return x\n    elseif n == 0\n        x = (Float64[],Float64[])\n        return x\n    elseif n == 1\n        x = ([0.0],[sqrt(pi)])\n        return x\n    elseif n <= 20\n       # GW algorithm\n       x = hermpts_gw( n )\n    elseif n <= 200\n       # REC algorithm\n       x = hermpts_rec( n )\n    else\n       # ASY algorithm\n       x = hermpts_asy( n )\n    end\n\n    if mod(n,2) == 1                              # fold out\n        w = [flipdim(x[2][:],1); x[2][2:end]]\n        x = [-flipdim(x[1],1) ; x[1][2:end]]\n    else\n        w = [flipdim(x[2][:],1); x[2][:]]\n        x = [-flipdim(x[1],1) ; x[1]]\n    end\n    w .*= sqrt(π)/sum(exp.(-x.^2).*w)\n    (x, w)\nend\n\nfunction hermpts_asy( n::Integer )\n    # Compute Hermite nodes and weights using asymptotic formula\n\n    x0 = HermiteInitialGuesses( n ) # get initial guesses\n    t0 = x0./sqrt(2n+1)\n    theta0 = acos.(t0)               # convert to theta-variable\n    val = x0;\n    for k = 1:20\n        val = hermpoly_asy_airy(n, theta0);\n        dt = -val[1]./(sqrt(2).*sqrt(2n+1).*val[2].*sin.(theta0))\n        theta0 .-= dt;                        # Newton update\n        if norm(dt,Inf) < sqrt(eps(Float64))/10\n           break\n        end\n    end\n    t0 = cos.(theta0)\n    x = sqrt(2n+1)*t0                          #back to x-variable\n    w = x.*val[1] .+ sqrt(2).*val[2]\n    w .= 1 ./ w.^2;            # quadrature weights\n\n    (x, w)\nend\n\nfunction hermpts_rec( n::Integer )\n    # Compute Hermite nodes and weights using recurrence relation.\n\n    x0 = HermiteInitialGuesses( n )\n    x0 .*= sqrt(2)\n    val = x0\n    for _ = 1:10\n        val = hermpoly_rec.(n, x0)\n        dx = first.(val)./last.(val)\n        dx[ isnan.( dx ) ] .= 0\n        x0 .= x0 .- dx\n        if norm(dx, Inf)<sqrt(eps(Float64))\n            break\n        end\n    end\n    x0 ./= sqrt(2)\n    w = 1 ./ last.(val).^2           # quadrature weights\n\n    x = (x0, w)\nend\n\nfunction hermpoly_rec( n::Integer, x0)\n    # HERMPOLY_rec evaluation of scaled Hermite poly using recurrence\n    n < 0 && throw(ArgumentError(\"n = $n must be positive\"))\n    # evaluate:\n    w = exp(-x0^2 / (4*n))\n    wc = 0 # 0 times we've applied wc\n    Hold = one(x0)\n    # n == 0 && return (Hold, 0)\n    H = x0\n    for k = 1:n-1\n        Hold, H = H, (x0*H/sqrt(k+1) - Hold/sqrt(1+1/k))\n        while abs(H) ≥ 100 && wc < n # regularise\n            H *= w\n            Hold *= w\n            wc += 1\n        end\n        k += 1\n    end\n    for _ = wc+1:n\n        H *= w\n        Hold *= w\n    end\n\n    # return (value, derivative):\n    val = (H, -x0*H + sqrt(n)*Hold)\nend\n\nfunction hermpoly_rec( r::Base.OneTo, x0)\n    isempty(r) && return [1.0]\n    n = maximum(r)\n    # HERMPOLY_rec evaluation of scaled Hermite poly using recurrence\n    n < 0 && throw(ArgumentError(\"n = $n must be positive\"))\n    n == 0 && return [exp(-x0^2 / 4)]\n    p = max(1,floor(Int,x0^2/100))\n    w = exp(-x0^2 / (4*p))\n    wc = 0 # 0 times we've applied wc\n    ret = Vector{Float64}()\n    Hold = one(x0)\n    push!(ret, Hold)\n    H = x0\n    push!(ret, H)\n    for k = 1:n-1\n        Hold, H = H, (x0*H/sqrt(k+1) - Hold/sqrt(1+1/k))\n        while abs(H) ≥ 100 && wc < p # regularise\n            ret .*= w\n            H *= w\n            Hold *= w\n            wc += 1\n        end\n        push!(ret, H)\n        k += 1\n    end\n    ret .*= w^(p-wc)\n\n    ret\nend\n\nhermpoly_rec( r::AbstractRange, x0) = hermpoly_rec(Base.OneTo(maximum(r)), x0)[r.+1]\n\n\nfunction hermpoly_asy_airy(n::Integer, theta)\n    # HERMPOLY_ASY evaluation hermite poly using Airy asymptotic formula in\n    # theta-space.\n\n    musq = 2n+1;\n    cosT = cos.(theta)\n    sinT = sin.(theta)\n    sin2T = 2 .* cosT.*sinT\n    eta = 0.5 .* theta .- 0.25 .* sin2T\n    chi = -(3*eta/2).^(2/3)\n    phi = (-chi./sinT.^2).^(1/4)\n    C = 2*sqrt(pi)*musq^(1/6)*phi\n    Airy0 = real.(airyai.(musq.^(2/3).*chi))\n    Airy1 = real.(airyaiprime.(musq.^(2/3).*chi))\n\n    # Terms in (12.10.43):\n    a0 = 1; b0 = 1\n    a1 = 15/144; b1 = -7/5*a1\n    a2 = 5*7*9*11/2/144^2; b2 = -13/11*a2\n    a3 = 7*9*11*13*15*17/6/144^3\n    b3 = -19/17*a3\n\n    # u polynomials in (12.10.9)\n    u0 = 1; u1 = (cosT.^3-6*cosT)/24\n    u2 = @. (-9*cosT^4 + 249*cosT^2 + 145)/1152\n    u3 = @. (-4042*cosT^9+18189*cosT^7-28287*cosT^5-151995*cosT^3-259290*cosT)/414720\n\n    #first term\n    A0 = 1\n    val = A0*Airy0\n\n    #second term\n    B0 = @. -(a0*phi^6 * u1+a1*u0)/chi^2\n    val .+=  B0.*Airy1./musq.^(4/3)\n\n    # third term\n    A1 = @. (b0*phi^12 * u2 + b1*phi^6 * u1 + b2*u0)/chi^3\n    val .+= A1.*Airy0/musq.^2\n\n    # fourth term\n    B1 = @. -(phi^18 * u3 + a1*phi^12 * u2 + a2*phi^6 * u1 + a3*u0)/chi^5\n    val .+= B1.*Airy1./musq.^(4/3+2)\n\n    val .= C.*val\n\n    ## Derivative\n\n    eta = .5*theta - .25*sin2T\n    chi = -(3*eta/2).^(2/3)\n    phi = (-chi./sinT.^2).^(1/4)\n    C = sqrt(2*pi)*musq^(1/3)./phi\n\n    # v polynomials in (12.10.10)\n    v0 = 1;\n    v1 = @. (cosT^3+6*cosT)/24\n    v2 = @. (15*cosT^4-327*cosT^2-143)/1152\n    v3 = @. (259290*cosT + 238425*cosT^3 - 36387*cosT^5 + 18189*cosT^7 - 4042*cosT^9)/414720\n\n    # first term\n    C0 = -(b0*phi.^6 .* v1 .+ b1.*v0)./chi\n    dval = C0.*Airy0/musq.^(2/3)\n\n    # second term\n    D0 =  a0*v0\n    dval = dval + D0*Airy1\n\n    # third term\n    C1 = @. -(phi^18 * v3 + b1*phi^12 * v2 + b2*phi^6 * v1 + b3*v0)/chi^4\n    dval = dval + C1.*Airy0/musq.^(2/3+2)\n\n    #fourth term\n    D1 = @. (a0*phi^12 * v2 + a1*phi^6 * v1 + a2*v0)/chi^3\n    dval = dval + D1.*Airy1/musq.^2\n\n    dval = C.*dval\n\n    val = (val, dval)\nend\n\nlet T(t) = @. t^(2/3)*(1+5/48*t^(-2)-5/36*t^(-4)+(77125/82944)*t^(-6) -108056875/6967296*t^(-8)+162375596875/334430208*t^(-10))\n    global function HermiteInitialGuesses( n::Integer )\n        #HERMITEINTITIALGUESSES(N), Initial guesses for Hermite zeros.\n        #\n        # [1] L. Gatteschi, Asymptotics and bounds for the zeros of Laguerre\n        # polynomials: a survey, J. Comput. Appl. Math., 144 (2002), pp. 7-27.\n        #\n        # [2] F. G. Tricomi, Sugli zeri delle funzioni di cui si conosce una\n        # rappresentazione asintotica, Ann. Mat. Pura Appl. 26 (1947), pp. 283-300.\n\n        # Error if n < 20 because initial guesses are based on asymptotic expansions:\n        @assert n>=20\n\n        # Gatteschi formula involving airy roots [1].\n        # These initial guess are good near x = sqrt(n+1/2);\n        if mod(n,2) == 1\n            m = (n-1)>>1\n            bess = (1:m)*pi\n            a = .5\n        else\n            m = n>>1\n            bess = ((0:m-1) .+ 0.5)*pi\n            a = -.5\n        end\n        nu = 4*m + 2*a + 2\n\n        airyrts = -T(3/8*pi*(4*(1:m) .- 1))\n\n        airyrts_exact = [-2.338107410459762           # Exact Airy roots.\n            -4.087949444130970\n            -5.520559828095555\n            -6.786708090071765\n            -7.944133587120863\n            -9.022650853340979\n            -10.040174341558084\n            -11.008524303733260\n            -11.936015563236262\n            -12.828776752865757]\n        airyrts[1:10] = airyrts_exact  # correct first 10.\n\n        x_init = sqrt.(abs.(nu .+ (2^(2/3)).*airyrts.*nu^(1/3) .+ (1/5*2^(4/3)).*airyrts.^2 .* nu^(-1/3) .+\n            (11/35-a^2-12/175).*airyrts.^3 ./ nu .+ ((16/1575).*airyrts.+(92/7875).*airyrts.^4).*2^(2/3).*nu^(-5/3) .-\n            ((15152/3031875).*airyrts.^5 .+ (1088/121275).*airyrts.^2).*2^(1/3).*nu^(-7/3)))\n        x_init_airy = real( flipdim(x_init,1) )\n\n        # Tricomi initial guesses. Equation (2.1) in [1]. Originally in [2].\n        # These initial guesses are good near x = 0 . Note: zeros of besselj(+/-.5,x)\n        # are integer and half-integer multiples of pi.\n        # x_init_bess =  bess/sqrt(nu).*sqrt((1+ (bess.^2+2*(a^2-1))/3/nu^2) );\n        Tnk0 = fill(pi/2,m)\n        nu = (4*m+2*a+2)\n        rhs = ((4*m+3) .- 4*(1:m))/nu*pi\n\n        for k = 1:7\n            val = Tnk0 .- sin.(Tnk0) .- rhs\n            dval = 1 .- cos.(Tnk0)\n            dTnk0 = val./dval\n            Tnk0 = Tnk0 .- dTnk0\n        end\n\n        tnk = cos.(Tnk0./2).^2\n        x_init_sin = @. sqrt(nu*tnk - (5 / (4 * (1-tnk)^2) - 1 / (1 - tnk)-1 + 3*a^2)/3 / nu)\n\n        # Patch together\n        p = 0.4985+eps(Float64)\n        x_init = [x_init_sin[1:convert(Int,floor(p*n))] ;\n        x_init_airy[convert(Int,ceil(p*n)):end]]\n\n        if mod(n, 2) == 1\n            x_init = [0 ; x_init]\n            x_init = x_init[1:m+1]\n        else\n            x_init = x_init[1:m]\n        end\n\n        return x_init\n    end\nend\n\n\nfunction hermpts_gw( n::Integer )\n    # Golub--Welsch algorithm. Used here for n<=20.\n\n    beta = sqrt.(0.5 .* (1:n-1))              # 3-term recurrence coeffs\n    T = SymTridiagonal(zeros(n), beta)  # Jacobi matrix\n    (D, V) = eigen(T)                      # Eigenvalue decomposition\n    indx = sortperm(D)                  # Hermite points\n    x = D[indx]\n    w = sqrt(pi)*V[1,indx].^2            # weights\n\n    # Enforce symmetry:\n    ii = floor(Int, n/2)+1:n\n    x = x[ii]\n    w = w[ii]\n    return (x,exp.(x.^2).*w)\nend\n", "meta": {"hexsha": "a7e7afdcc0a4ff93fb4dd98a14f1b80ac5904511", "size": 9190, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gausshermite.jl", "max_stars_repo_name": "GeoffChurch/FastGaussQuadrature.jl", "max_stars_repo_head_hexsha": "dadfdd5340f500bbc8a3ad54c04adeb6e5ea4eed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gausshermite.jl", "max_issues_repo_name": "GeoffChurch/FastGaussQuadrature.jl", "max_issues_repo_head_hexsha": "dadfdd5340f500bbc8a3ad54c04adeb6e5ea4eed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gausshermite.jl", "max_forks_repo_name": "GeoffChurch/FastGaussQuadrature.jl", "max_forks_repo_head_hexsha": "dadfdd5340f500bbc8a3ad54c04adeb6e5ea4eed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8993710692, "max_line_length": 127, "alphanum_fraction": 0.4990206746, "num_tokens": 3551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.757710013118916}}
{"text": "function gmmresults()\n    # example of GMM: draws from N(0,1)\n    y = randn(1000,1)\n    # 3 moment conditions\n    moments = theta -> [y.-theta[1] (y.^2.0).-theta[2] (y.-theta[1]).^3.0]\n    # first round consistent\n    W = Matrix{Float64}(I,3,3)\n    theta = [0.0, 1.0]\n    thetahat, objvalue, D, ms, converged = gmm(moments, theta, W)\n    # second round efficient\n    W = inv(cov(ms))\n    gmmresults(moments, thetahat, W, \"GMM example, two step\");\n    # CUE\n    gmmresults(moments, thetahat, \"\", \"GMM example, CUE\");\n    return\nend    \n\nfunction gmmresults(moments, theta, weight, title=\"\", names=\"\", efficient=true)\n    n,g = size(moments(theta))\n    if weight !=\"\" # if weight provided, use it\n        thetahat, objvalue, D, ms, converged = gmm(moments, theta, weight)\n    else # do CUE\n        thetahat, objvalue, D, ms, converged = gmm(moments, theta)\n        weight = inv(NeweyWest(ms))\n    end\n    k,g = size(D)\n    # estimate asymptotic variance\n    V = inv(D*weight*D')\n    if !efficient\n        omega = NeweyWest(ms)\n        V = V*D*weight*omega*weight*D'*V\n    end\n    V = V/n # adapt to sample size, for inference\n    if names==\"\"\n        names = 1:k\n        names = names'\n    end\n    se = sqrt.(diag(V))\n    t = thetahat ./ se\n    p = 2.0 .- 2.0*cdf.(Ref(TDist(n-k)),abs.(t))\n    PrintDivider()\n    if title !=\"\" printstyled(title, color=:yellow); println() end\n    print(\"GMM Estimation Results    Convergence: \")\n    printstyled(converged, color=:green)\n    println()\n    println(\"Observations: \", n)\n    println(\"Hansen-Sargan statistic: \", round(n*objvalue, digits=5))\n    if g > k\n        println(\"Hansen-Sargan p-value: \", round(1.0 - cdf(Chisq(g-k),n*objvalue), digits=5))\n    end    \n    a =[thetahat se t p]\n    println(\"\")\n    PrintEstimationResults(a, names)\n    println()\n    PrintDivider()\n    return thetahat, objvalue, V, converged\nend    \n", "meta": {"hexsha": "0f7536c6453541eabf9d495a1e76ca66808e186b", "size": 1867, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GMM/gmmresults.jl", "max_stars_repo_name": "nilshg/Econometrics", "max_stars_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "src/GMM/gmmresults.jl", "max_issues_repo_name": "nilshg/Econometrics", "max_issues_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "src/GMM/gmmresults.jl", "max_forks_repo_name": "nilshg/Econometrics", "max_forks_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 32.1896551724, "max_line_length": 93, "alphanum_fraction": 0.5966791644, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7576977264914491}}
{"text": "export padm\n\nconst PADE_COEFFS = convert(Vector{Float64}, [1//1,\n                              1//2,\n                              8188362958855447//72057594037927936,\n                              8734253822779143//576460752303423488,\n                              2911417940926381//2305843009213693952,\n                              145570897046319//2305843009213692962,\n                              2797136075159//1860878688081779609])\n\n\"\"\"\n    padm(A; p=6)\n\nCalculate matrix exponential using Pade approximants.\n\n`padm` uses the irreducible (p, p)-degree rational Pade approximation to the\nexponential function. The result is always a dense matrix.\n\n# Input\n\n- `A` -- matrix which can be dense or sparse\n- `p` -- (optional, default: 6) degree of the rational Pade approximation to\n         the exponential function\n\n# Notes\n\nThis Julia implementation originated from Expokit's PADM Matlab code by\nRoger B. Sidje, see below.\n\n---\n\n  E = padm( A, p )\n  PADM computes the matrix exponential exp(A) using the irreducible \n  (p,p)-degree rational Pade approximation to the exponential function.\n\n  E = padm( A )\n  p is internally set to 6 (recommended and generally satisfactory).\n\n  See also CHBV, EXPOKIT and the MATLAB supplied functions EXPM and EXPM1.\n\n  Roger B. Sidje (rbs@maths.uq.edu.au)\n  EXPOKIT: Software Package for Computing Matrix Exponentials.\n  ACM - Transactions On Mathematical Software, 24(1):130-156, 1998\n\"\"\"\nfunction padm(A; p::Int64=6)\n\n    # Pade coefficients\n    if p == 6\n        c = copy(PADE_COEFFS)\n    else\n        c = Float64[]\n        push!(c, 1.0)\n        @inbounds for k = 1:p\n            push!(c, c[end] * ((p+1-k)/(k*(2*p+1-k))))\n        end\n    end\n\n    # scaling\n    normA = opnorm(A, Inf)\n    s = 0\n    if normA > 0.5\n        s = max(0, round(Int64, log(normA)/log(2), RoundToZero) + 2)\n        A = A * 2.0^(-s) # scale!(A, 2.0^(-s))\n    end\n\n    # Horner evaluation of the irreducible fraction\n    A2 = A * A\n    Q = c[p+1]*Matrix{eltype(A)}(I, size(A))\n    P = c[p]*Matrix{eltype(A)}(I, size(A))\n    odd = 1\n    @inbounds begin \n        for k = p-1:-1:1\n            if odd == 1\n                Q = Q * A2 + c[k] * I\n            else\n                P = P * A2 + c[k] * I\n            end\n            odd = 1 - odd\n        end\n    end\n\n    if odd == 1\n        Q = Q * A\n        Q = Q - P\n        E = -(I + 2 * \\(Q, Matrix(P)))\n    else\n        P = P * A\n        Q = Q - P\n        E = I + 2 * \\(Q, Matrix(P))\n    end\n\n    # squaring\n    @inbounds begin \n        for k = 1:s\n            E = E * E\n        end\n    end\n\n    return E\n\nend # padm\n", "meta": {"hexsha": "d5a6bb79ee714c3762552bfc7363901977072554", "size": 2581, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/padm.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Expokit.jl-a1e7a1ef-7a5d-5822-a38c-be74e1bb89f4", "max_stars_repo_head_hexsha": "16a750922a3e2e8b1971e079b865f61eef6cbf0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2015-05-26T21:38:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T01:29:24.000Z", "max_issues_repo_path": "src/padm.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Expokit.jl-a1e7a1ef-7a5d-5822-a38c-be74e1bb89f4", "max_issues_repo_head_hexsha": "16a750922a3e2e8b1971e079b865f61eef6cbf0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2015-02-06T15:41:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-18T13:08:09.000Z", "max_forks_repo_path": "src/padm.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Expokit.jl-a1e7a1ef-7a5d-5822-a38c-be74e1bb89f4", "max_forks_repo_head_hexsha": "16a750922a3e2e8b1971e079b865f61eef6cbf0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-02-07T01:09:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T01:02:09.000Z", "avg_line_length": 25.3039215686, "max_line_length": 76, "alphanum_fraction": 0.5404881829, "num_tokens": 795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.819893335913536, "lm_q1q2_score": 0.7576977264914491}}
{"text": "# indicator of the L1 norm ball with given radius\n\nexport IndBallL1\n\n\"\"\"\n**Indicator of a ``L_1`` norm ball**\n\n    IndBallL1(r=1.0)\n\nReturns the indicator function of the set\n```math\nS = \\\\left\\\\{ x : ∑_i |x_i| \\\\leq r \\\\right\\\\}.\n```\nParameter `r` must be positive.\n\"\"\"\nstruct IndBallL1{R <: Real} <: ProximableFunction\n  r::R\n  function IndBallL1{R}(r::R) where {R <: Real}\n    if r <= 0\n      error(\"parameter r must be positive\")\n    else\n      new(r)\n    end\n  end\nend\n\nis_convex(f::IndBallL1) = true\nis_set(f::IndBallL1) = true\n\nIndBallL1(r::R=1.0) where {R <: Real} = IndBallL1{R}(r)\n\nfunction (f::IndBallL1)(x::AbstractArray{T}) where T <: RealOrComplex\n  if norm(x,1) - f.r > 1e-12\n    return +Inf\n  end\n  return zero(T)\nend\n\nfunction prox!(y::AbstractArray{T}, f::IndBallL1, x::AbstractArray{T}, gamma::R=one(R)) where {R<: Real, T <: RealOrComplex{R}}\n  # TODO: a faster algorithm\n  if norm(x,1) - f.r < 1e-14\n    y .= x\n    return zero(T)\n  else # do a projection of abs(x) onto simplex then recover signs\n    n = length(x)\n    p = abs.(view(x,:))\n    sort!(p, rev=true)\n    s = zero(R)\n    @inbounds for i = 1:n-1\n      s = s + p[i]\n      tmax = (s - f.r)/i\n      if tmax >= p[i+1]\n        @inbounds for j in eachindex(x)\n          y[j] = sign(x[j])*max(abs(x[j])-tmax, zero(R))\n        end\n        return zero(T)\n      end\n    end\n    tmax = (s + p[n] - f.r)/n\n    @inbounds for j in eachindex(x)\n      y[j] = sign(x[j])*max(abs(x[j])-tmax, zero(R))\n    end\n    return zero(T)\n  end\nend\n\nfun_name(f::IndBallL1) = \"indicator of an L1 norm ball\"\nfun_dom(f::IndBallL1) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::IndBallL1) = \"x ↦ 0 if ‖x‖_1 ⩽ r, +∞ otherwise\"\nfun_params(f::IndBallL1) = \"r = $(f.r)\"\n\nfunction prox_naive(f::IndBallL1, x::AbstractArray{T}, gamma::Real=1.0) where T <: RealOrComplex\n  # do a simple bisection (aka binary search) on λ\n  L = 0.0\n  U = maximum(abs, x)\n  λ = L\n  v = 0.0\n  maxit = 120\n  for iter in 1:maxit\n    λ = 0.5*(L + U)\n    v = sum(max.(abs.(x) .- λ, 0.0))\n    # modify lower or upper bound\n    (v < f.r) ? U = λ : L = λ\n    # exit condition\n    if abs(L - U) < 1e-15\n      break\n    end\n  end\n  return sign.(x) .* max.(0.0, abs.(x) .- λ), 0.0\nend\n", "meta": {"hexsha": "9440d84912a5ae97a48879e8a8838b661517f5e3", "size": 2211, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indBallL1.jl", "max_stars_repo_name": "lostella/ProximalOperators.jl", "max_stars_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-15T13:57:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T13:57:52.000Z", "max_issues_repo_path": "src/functions/indBallL1.jl", "max_issues_repo_name": "lostella/ProximalOperators.jl", "max_issues_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/indBallL1.jl", "max_forks_repo_name": "lostella/ProximalOperators.jl", "max_forks_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2967032967, "max_line_length": 127, "alphanum_fraction": 0.57847128, "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787563, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7576977237066048}}
{"text": "\nabstract IndexFormula{T<:Number}\n\n\"\"\"\nrefindex(formula, λ_μm) computes the refractive index for a given wavelength in μm.\n\"\"\"\nrefindex{T}(::IndexFormula{T}, λ_μm::T) = zero(T);\n\n\ntype SellmeierFormula{T<:Number} <: IndexFormula{T}\n  n::Int8\n  A::T\n  B::Array{T,1}\n  C::Array{T,1}\n  λn::Bool\n  function SellmeierFormula(A,B,C,λn=true)\n    n = length(B)\n    if length(C) != n\n      error(\"Coefficients B and C of different length\")\n    else\n      new(n,A,B,C,λn)\n    end\n  end\nend\n\n\nfunction refindex{T}(formula::SellmeierFormula{T}, λ_μm::T)\n  nsq=one(T)+formula.A\n  λsq = λ_μm^2\n  for i = 1:formula.n\n    num = i==formula.n && !formula.λn ? formula.B[i] : formula.B[i] * λsq\n    nsq += num/(λsq - formula.C[i])\n  end\n  return sqrt(nsq)\nend\n\nbk7 = SellmeierFormula{Float64}(0, [1.03961212, 0.231792344, 1.01046945], [6.00069867e-3, 2.00179144e-2, 1.03560653e2])\nrefindex(bk7,0.5)\n\nusing Gadfly\nplot(x->refindex(bk7,x),0.21,1.6)\n", "meta": {"hexsha": "fb0a0b5f01ae4a2b74b1410843984af79da8fbe8", "size": 928, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/formulas_OLD.jl", "max_stars_repo_name": "drjrkuhn/GlassCatalog.jl", "max_stars_repo_head_hexsha": "64f4f220e1814367b0e63ee09b49dd2f90a274d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-30T23:30:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-22T04:34:08.000Z", "max_issues_repo_path": "src/formulas_OLD.jl", "max_issues_repo_name": "drjrkuhn/GlassCatalog.jl", "max_issues_repo_head_hexsha": "64f4f220e1814367b0e63ee09b49dd2f90a274d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/formulas_OLD.jl", "max_forks_repo_name": "drjrkuhn/GlassCatalog.jl", "max_forks_repo_head_hexsha": "64f4f220e1814367b0e63ee09b49dd2f90a274d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0952380952, "max_line_length": 119, "alphanum_fraction": 0.6497844828, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7576977223141826}}
{"text": "########################################################################\nfunction ppca(X; Q=1)\n########################################################################\n\n    D, N = size(X)\n\n    μ = vec(mean(X, dims=2))\n\n    JITTER = 1e-8\n\n    @printf(\"Running PPCA for %d number of data items of dimension %d, projected to %d components\\n\", N, D, Q)\n\n    @printf(\"\\t Fixing jitter to %f\\n\", JITTER)\n\n\n    #---------------------------------------------\n    function marginalLogLikelihood(W, σ)\n    #---------------------------------------------\n\n        sum(logpdf(MvNormal(μ, W*W' + σ*σ*I + JITTER*I), X))\n\n    end\n\n\n    #---------------------------------------------\n    function unpack(param)\n    #---------------------------------------------\n\n        local W = reshape(param[1:end-1], D, Q)\n\n        local σ = exp(param[end]) + 1e-8\n\n        return W, σ\n\n    end\n\n\n    #---------------------------------------------\n    function objective(param)\n    #---------------------------------------------\n\n        @assert(length(param) == D*Q + 1)\n\n        local W, σ = unpack(param)\n\n        try\n\n            return -1.0 * marginalLogLikelihood(W, σ)\n\n        catch err\n\n            if isa(err, PosDefException)\n\n                @warn(\"covariance is not positive definite, returning Inf\")\n\n                return Inf\n\n            else\n\n                throw(err)\n\n            end\n\n        end\n\n    end\n\n    #---------------------------------------------\n    # Run optimiser\n    #---------------------------------------------\n\n    opt    = Optim.Options(show_trace = true, iterations = 100_000)\n\n    result = optimize(objective, [randn(D*Q); randn()*3], NelderMead())# LBFGS(), opt, autodiff=:forward)\n\n    W, σ   = unpack(result.minimizer)\n\n    # @show W, μ, σ\n    #\n    # #---------------------------------------------\n    # # Define projections\n    # #---------------------------------------------\n    #\n    # M = W'*W  + σ*σ*I # eq. (12.41) in Bishop\n    #\n    # proj(x::Array{T,1} where T<:Real) = vec(M \\ (W'*(x - μ)))[1]\n    #\n    # fwd(z::Real) = vec(W*z + μ)\n\n    return W, μ, σ#, proj, fwd\n\nend\n", "meta": {"hexsha": "3946aba9f57b469e142611c3261ede18ef7c1a21", "size": 2100, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PPCA/ppca.jl", "max_stars_repo_name": "HITS-AIN/ProbabilisticFluxVariationGradient.jl", "max_stars_repo_head_hexsha": "36849fadeb3378b4bd4346830cc63757c90819e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PPCA/ppca.jl", "max_issues_repo_name": "HITS-AIN/ProbabilisticFluxVariationGradient.jl", "max_issues_repo_head_hexsha": "36849fadeb3378b4bd4346830cc63757c90819e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PPCA/ppca.jl", "max_forks_repo_name": "HITS-AIN/ProbabilisticFluxVariationGradient.jl", "max_forks_repo_head_hexsha": "36849fadeb3378b4bd4346830cc63757c90819e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-03T15:52:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T15:52:10.000Z", "avg_line_length": 22.5806451613, "max_line_length": 110, "alphanum_fraction": 0.3566666667, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7576977189985032}}
{"text": "\"\"\"\n    QuadraticFit{T} <: UnivariateAlgorithm\n\nThe quadratic fit algorithm constructs a quadratic function from three points at each\niteration as an approximation to the objective. The analytical solution to the quadratic \nmodel is examined as the new minimizer candidate to update the three points. \n\"\"\"\nstruct QuadraticFit{T} <: UnivariateAlgorithm \n    ϵ::T\n\n    function QuadraticFit{T}(ϵ) where {T}\n        0 < ϵ < 1 ? new{T}(ϵ) : error(\"`ϵ` must be in the interval (0, 1)\")\n    end\nend\n\n\"\"\"\n    QuadraticFit([ϵ=0.01])\n\nInitialize quadratic fit search algorithm with optional argument `ϵ` in the interval \n(0, 1) to choose a midpoint as `mid = ϵ * lower + (1 - ϵ) * upper`.\n\"\"\"\nQuadraticFit(ϵ=0.5) = QuadraticFit{typeof(ϵ)}(ϵ)\n\nfunction _optimize(f, lower::T, upper::T, alg::QuadraticFit; \n        reltol, abstol, maxiter) where {T}\n    ϵ = alg.ϵ\n    mid = T(ϵ * lower + (1 - ϵ) * upper)\n    y_lower, y_upper, y_mid = f(lower), f(upper), f(mid)\n    converged = false\n    iter = 0\n    x = T(NaN)\n    yx = (typeof(y_lower))(NaN)\n    while iter < maxiter\n        iter += 1\n        x = T(0.5 * (y_lower * (mid^2 - upper^2) + y_mid * (upper^2 - lower^2) + \n            y_upper * (lower^2 - mid^2)) /\n            (y_lower * (mid - upper) + y_mid * (upper - lower) + y_upper * (lower - mid)))\n        yx = f(x)\n        x_tol = reltol * abs(x) + abstol\n        if max(upper - x, x - lower) < 2x_tol\n            converged = true\n            break\n        end\n        if x > mid\n            if yx > y_mid\n                upper, y_upper = x, yx\n            else\n                lower, y_lower, mid, y_mid = mid, y_mid, x, yx\n            end\n        elseif x < mid\n            if yx > y_mid\n                lower, y_lower = x, yx\n            else\n                upper, y_upper, mid, y_mid = mid, y_mid, x, yx\n            end\n        end\n    end\n    return Solution(converged, iter, x, yx)\nend", "meta": {"hexsha": "228f3f98db419bfebe53fd4e0a0f433b861dbfcf", "size": 1887, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/algorithms/quadratic_fit.jl", "max_stars_repo_name": "lhnguyen-vn/Optini.jl", "max_stars_repo_head_hexsha": "81e94ff764daa9819edae4b4b8211726a7de0821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-24T21:26:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T21:26:59.000Z", "max_issues_repo_path": "src/univariate/algorithms/quadratic_fit.jl", "max_issues_repo_name": "lhnguyen-vn/Optini.jl", "max_issues_repo_head_hexsha": "81e94ff764daa9819edae4b4b8211726a7de0821", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/algorithms/quadratic_fit.jl", "max_forks_repo_name": "lhnguyen-vn/Optini.jl", "max_forks_repo_head_hexsha": "81e94ff764daa9819edae4b4b8211726a7de0821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-18T21:08:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T21:08:54.000Z", "avg_line_length": 31.9830508475, "max_line_length": 90, "alphanum_fraction": 0.55590885, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217417, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7576977188882521}}
{"text": "\"\"\"\n        topsis(decisionMat, weights, fns)\n\nApply TOPSIS (Technique for Order of Preference by Similarity to Ideal Solution) method \nfor a given matrix and weights.\n\n# Arguments:\n - `decisionMat::DataFrame`: n × m matrix of objective values for n candidate (or strategy) and m criteria \n - `weights::Array{Float64, 1}`: m-vector of weights that sum up to 1.0. If the sum of weights is not 1.0, it is automatically normalized.\n - `fns::Array{Function, 1}`: m-vector of function that are either minimize or maximize.\n\n# Description \ntopsis() applies the TOPSIS method to rank n strategies subject to m criteria which are supposed to be either maximized or minimized.\n\n# Output \n- `::TopsisResult`: TopsisResult object that holds multiple outputs including scores and best index.\n\n# Examples\n```julia-repl\njulia> df = DataFrame();\njulia> df[:, :x] = Float64[9, 8, 7];\njulia> df[:, :y] = Float64[7, 7, 8];\njulia> df[:, :z] = Float64[6, 9, 6];\njulia> df[:, :q] = Float64[7, 6, 6];\n\njulia> w = Float64[4, 2, 6, 8];\n\njulia> df\n3×4 DataFrame\n Row │ x        y        z        q       \n     │ Float64  Float64  Float64  Float64 \n─────┼────────────────────────────────────\n   1 │     9.0      7.0      6.0      7.0\n   2 │     8.0      7.0      9.0      6.0\n   3 │     7.0      8.0      6.0      6.0\n\njulia> fns = makeminmax([maximum, maximum, maximum, maximum]);\njulia> result = topsis(df, w, fns);\n\njulia> result.bestIndex\n2\n\njulia> result.scores\n3-element Array{Float64,1}:\n 0.38768695492211824\n 0.6503238218850163\n 0.08347670030339041\n```\n\n# References\nHwang, C.L.; Yoon, K. (1981). Multiple Attribute Decision Making: Methods and Applications. New York: Springer-Verlag\n\nCelikbilek Yakup, Cok Kriterli Karar Verme Yontemleri, Aciklamali ve Karsilastirmali\nSaglik Bilimleri Uygulamalari ile. Editor: Muhlis Ozdemir, Nobel Kitabevi, Ankara, 2018\n\nİşletmeciler, Mühendisler ve Yöneticiler için Operasyonel, Yönetsel ve Stratejik Problemlerin\nÇözümünde Çok Kriterli Karar verme Yöntemleri, Editörler: Bahadır Fatih Yıldırım ve Emrah Önder,\nDora, 2. Basım, 2015, ISBN: 978-605-9929-44-8\n\"\"\"\n    function topsis(decisionMat::DataFrame, weights::Array{Float64,1}, fns::Array{Function,1})::TopsisResult\n    \n    w = unitize(weights)\n    nalternatives, ncriteria = size(decisionMat)\n    \n    normalizedMat = normalize(decisionMat)\n    \n    weightednormalizedMat = w * normalizedMat\n    \n    # col_max = colmaxs(weightednormalizedMat)\n    # col_min = colmins(weightednormalizedMat)\n    col_max = apply_columns(fns, weightednormalizedMat)\n    col_min = apply_columns(reverseminmax(fns), weightednormalizedMat)\n\n    distances_plus  = zeros(Float64, nalternatives)\n    distances_minus = zeros(Float64, nalternatives)\n\n    scores = zeros(Float64, nalternatives)\n\n    @inbounds for i in 1:nalternatives\n        ithrow = weightednormalizedMat[i,:] |> Array{Float64,1}\n\t\tdistances_plus[i]  = euclidean(col_max, ithrow)\n\t\tdistances_minus[i] = euclidean(col_min, ithrow)\n\t\tscores[i] = distances_minus[i] / (distances_minus[i] + distances_plus[i])\n    end\n    \n    best_index = sortperm(scores) |> last\n    \n    topsisresult = TopsisResult(\n        decisionMat,\n        w,\n        normalizedMat,\n        weightednormalizedMat,\n        best_index,\n        scores\n    ) \n\n    return topsisresult\nend", "meta": {"hexsha": "e81382cce3c2a6c7049919c6dfd68b46d56ffd85", "size": 3274, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/topsis.jl", "max_stars_repo_name": "bahadirfyildirim/JMcDM", "max_stars_repo_head_hexsha": "c1c3f11d92cd8b8c6367245794464e6643caa735", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/topsis.jl", "max_issues_repo_name": "bahadirfyildirim/JMcDM", "max_issues_repo_head_hexsha": "c1c3f11d92cd8b8c6367245794464e6643caa735", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/topsis.jl", "max_forks_repo_name": "bahadirfyildirim/JMcDM", "max_forks_repo_head_hexsha": "c1c3f11d92cd8b8c6367245794464e6643caa735", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4081632653, "max_line_length": 138, "alphanum_fraction": 0.6805131338, "num_tokens": 1026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7576977155725731}}
{"text": "export minkowski_difference, pontryagin_difference\n\n\"\"\"\n    minkowski_difference(P::LazySet{N}, Q::LazySet{N}) where {N<:Real}\n\nConcrete Minkowski difference (geometric difference) for a pair of\nconvex sets.\n\n### Input\n\n- `P` -- polytopic set\n- `Q` -- compact convex set that is subtracted from `P`\n\n### Output\n\nAn `HPolytope` that corresponds to the Minkowski difference of `P` minus `Q` if\n`P` is bounded, and an `HPolyhedron` if `P` is unbounded.\n\n### Notes\n\nThis function requires that the list of constraints of the set `P` is\navailable and that the set `Q` is bounded.\n\n### Algorithm\n\nThis function implements Theorem 2.3 in [1], which we state next.\n\nSuppose ``P`` is a polyhedron\n```math\nP = \\\\{z ∈ ℝ^n: sᵢᵀz ≤ rᵢ,~i = 1, …, N\\\\}.\n```\nwhere ``sᵢ ∈ ℝ^n, sᵢ ≠ 0``, and ``rᵢ ∈ ℝ``.\nAssume ``ρ(sᵢ,Q)`` is defined for ``i = 1, …, N``. Then,\n\n```math\nP ⊖ Q = \\\\{z ∈ ℝ^n: sᵢᵀz ≤ rᵢ - ρ(sᵢ,Q),~i = 1, …, N\\\\}.\n```\n\nwhere ``⊖`` is defined as ``P ⊖ Q = \\\\{z ∈ ℝ^n: z + v ∈ P  ~∀~v ∈ Q\\\\}`` and is called\nthe *Minkowski difference* (also referenced as *Pontryagin difference*, or geometric difference).\nIt is denoted in [1] as the operation `P ~ Q`.\n\n[1] Ilya Kolmanovsky and Elmer G. Gilbert (1997). *Theory and computation\nof disturbance invariant sets for discrete-time linear systems.*\n[Mathematical Problems in Engineering Volume 4, Issue 4, Pages\n317-367.](http://dx.doi.org/10.1155/S1024123X98000866)\n\"\"\"\nfunction minkowski_difference(P::LazySet{N}, Q::LazySet{N}) where {N<:Real}\n\n    @assert applicable(constraints_list, P)  \"this function \" *\n        \"requires that the list of constraints of its first argument is applicable, but it is not; \" *\n        \"if it is bounded, try overapproximating with an `HPolytope` first\"\n    @assert isbounded(Q) \"this function requires that its second argument is bounded, but it is not\"\n\n    A, b = tosimplehrep(P)\n    g_PminusQ = [b[i] - ρ(A[i, :], Q) for i in eachindex(b)]\n    if isbounded(P)\n        return HPolytope(A, g_PminusQ)\n    else\n        return HPolyhedron(A, g_PminusQ)\n    end\nend\n\n\"\"\"\n    pontryagin_difference(P::LazySet{N}, Q::LazySet{N}) where {N<:Real}\n\nAn alias for the function `minkowski_difference`.\n\n### Notes\n\nDue to inconsistent naming conventions, both the name *Minkowski difference* and\n*Pontryagin difference* are used to refer to the geometric difference of two sets.\n\n\"\"\"\nconst pontryagin_difference = minkowski_difference\n\n# concrete minkowski difference with singleton\nminkowski_difference(X::LazySet, S::AbstractSingleton) = translate(X, -element(S))\nminkowski_difference(X::LazySet, ::ZeroSet) = X\n", "meta": {"hexsha": "9e69a4b8b6cb3e9802dab0194c6af1ae733b8ade", "size": 2579, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ConcreteOperations/minkowski_difference.jl", "max_stars_repo_name": "goretkin/LazySets.jl", "max_stars_repo_head_hexsha": "6e829d9179bc25b8d7f6afb190a015e53760c601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-15T03:15:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-15T03:18:05.000Z", "max_issues_repo_path": "src/ConcreteOperations/minkowski_difference.jl", "max_issues_repo_name": "KennyKangMPC/LazySets.jl", "max_issues_repo_head_hexsha": "29aeb96d9b417cb3157f2b2aa3f46c79a8f96c18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ConcreteOperations/minkowski_difference.jl", "max_forks_repo_name": "KennyKangMPC/LazySets.jl", "max_forks_repo_head_hexsha": "29aeb96d9b417cb3157f2b2aa3f46c79a8f96c18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2375, "max_line_length": 102, "alphanum_fraction": 0.6851492827, "num_tokens": 822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.757697714180151}}
{"text": "plan_clenshawcurtis(μ) = length(μ) > 1 ? FFTW.plan_r2r!(μ, FFTW.REDFT00) : fill!(similar(μ),1)'\n\n\"\"\"\nCompute nodes of the Clenshaw—Curtis quadrature rule.\n\"\"\"\nclenshawcurtisnodes(::Type{T}, N::Int) where T = chebyshevpoints(T, N; kind = 2)\n\n\"\"\"\nCompute weights of the Clenshaw—Curtis quadrature rule with modified Chebyshev moments of the first kind ``\\\\mu``.\n\"\"\"\nclenshawcurtisweights(μ::Vector) = clenshawcurtisweights!(copy(μ))\nclenshawcurtisweights!(μ::Vector) = clenshawcurtisweights!(μ, plan_clenshawcurtis(μ))\nfunction clenshawcurtisweights!(μ::Vector{T}, plan) where T\n    N = length(μ)\n    rmul!(μ, inv(N-one(T)))\n    plan*μ\n    μ[1] *= half(T); μ[N] *= half(T)\n    return μ\nend\n", "meta": {"hexsha": "05f4d85a2eb0eb213941d567f18621d1b373c41d", "size": 688, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/clenshawcurtis.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/FastTransforms.jl-057dd010-8810-581a-b7be-e3fc3b93f78c", "max_stars_repo_head_hexsha": "766d3076b4e3b32206169a4310d4211c2e0a1902", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-15T03:23:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T03:23:28.000Z", "max_issues_repo_path": "src/clenshawcurtis.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/FastTransforms.jl-057dd010-8810-581a-b7be-e3fc3b93f78c", "max_issues_repo_head_hexsha": "766d3076b4e3b32206169a4310d4211c2e0a1902", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/clenshawcurtis.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/FastTransforms.jl-057dd010-8810-581a-b7be-e3fc3b93f78c", "max_forks_repo_head_hexsha": "766d3076b4e3b32206169a4310d4211c2e0a1902", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4, "max_line_length": 114, "alphanum_fraction": 0.6947674419, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787566, "lm_q2_score": 0.8198933271118222, "lm_q1q2_score": 0.7576977115055573}}
{"text": "\"\"\"\n    sphere(D)\n\nThe well-known D-dimensional Sphere function.\n\"\"\"\nfunction sphere(D=10)\n    # Objective function\n    f(x) = sum(x.*x)\n\n    bounds = Array([-100.0ones(D) 100.0ones(D)]')\n\n    x = zeros(D)\n    return f, bounds, [generateChild(x, f(x)) ]\n\nend\n\n\"\"\"\n    discus(D)\n\nThe well-known D-dimensional Discus function.\n\"\"\"\nfunction discus(D = 10)\n    # Objective function\n    f(x) = 1e6x[1].^2 + sum(x[2:end] .^2)\n\n    bounds = Array([-10.0ones(D) 10.0ones(D)]')\n\t\n    x = zeros(D)\n    return f, bounds, [generateChild(x, f(x))] \nend\n\n\n\"\"\"\n    rastrigin(D)\n\nThe well-known D-dimensional Rastrigin function.\n\"\"\"\nfunction rastrigin(D = 10)\n    \n    # Objective function\n    f(x) = 10D+ sum(x.*x - 10cos.(2π*x))\n\n    bounds = Array([-5.0ones(D) 5.0ones(D)]')\n\n    x = zeros(D)\n    return f, bounds, [generateChild(x, f(x)) ]\n\nend\n\n", "meta": {"hexsha": "3223e9c765e9c169237dd63ae9a381209f7b2270", "size": 834, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TestProblems/box-constrained.jl", "max_stars_repo_name": "jbytecode/Metaheuristics.jl", "max_stars_repo_head_hexsha": "939c0cd9d92ef06c320480725c809e89e1dc9e14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 89, "max_stars_repo_stars_event_min_datetime": "2018-03-07T07:11:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:57:16.000Z", "max_issues_repo_path": "src/TestProblems/box-constrained.jl", "max_issues_repo_name": "jbytecode/Metaheuristics.jl", "max_issues_repo_head_hexsha": "939c0cd9d92ef06c320480725c809e89e1dc9e14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-01-30T23:03:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T15:45:15.000Z", "max_forks_repo_path": "src/TestProblems/box-constrained.jl", "max_forks_repo_name": "jbytecode/Metaheuristics.jl", "max_forks_repo_head_hexsha": "939c0cd9d92ef06c320480725c809e89e1dc9e14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-06-08T10:06:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:15:35.000Z", "avg_line_length": 16.68, "max_line_length": 49, "alphanum_fraction": 0.5827338129, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7576720554079377}}
{"text": "# Special Pythagorean triplet\n\nTRIPLET_SUM = 1000\n\n\nfunction solve()\n    for b in floor(Int, TRIPLET_SUM / (2 + 2^0.5)):(TRIPLET_SUM // 2)\n        for a in 1:(b - 1)\n            c = (a^2 + b^2)^0.5\n            if a + b + c == TRIPLET_SUM\n                return a * b * c\n            end\n        end\n    end\nend\n\n\nprint(Int(solve()))\n", "meta": {"hexsha": "48c7e907f240f772585903392d06d1eb9d33e538", "size": 333, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/p009.jl", "max_stars_repo_name": "wephy/project-euler", "max_stars_repo_head_hexsha": "cc4824478282d3e1514a1bf7a1821b938db5bfcb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/p009.jl", "max_issues_repo_name": "wephy/project-euler", "max_issues_repo_head_hexsha": "cc4824478282d3e1514a1bf7a1821b938db5bfcb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-07T19:03:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-07T19:03:35.000Z", "max_forks_repo_path": "julia/p009.jl", "max_forks_repo_name": "wephy/project-euler", "max_forks_repo_head_hexsha": "cc4824478282d3e1514a1bf7a1821b938db5bfcb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5263157895, "max_line_length": 69, "alphanum_fraction": 0.4804804805, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715436, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7576692984280641}}
{"text": "# ---\n# title: 413. Arithmetic Slices\n# id: problem413\n# author: Indigo\n# date: 2021-06-20\n# difficulty: Medium\n# categories: Math, Dynamic Programming\n# link: <https://leetcode.com/problems/arithmetic-slices/description/>\n# hidden: true\n# ---\n# \n# A sequence of numbers is called arithmetic if it consists of at least three\n# elements and if the difference between any two consecutive elements is the\n# same.\n# \n# For example, these are arithmetic sequences:\n# \n#     \n#     \n#     1, 3, 5, 7, 9\n#     7, 7, 7, 7\n#     3, -1, -5, -9\n# \n# The following sequence is not arithmetic.\n# \n#     \n#     \n#     1, 1, 2, 5, 7\n# \n# \n# \n# A zero-indexed array A consisting of N numbers is given. A slice of that array\n# is any pair of integers (P, Q) such that 0 <= P < Q < N.\n# \n# A slice (P, Q) of the array A is called arithmetic if the sequence:  \n# A[P], A[P \\+ 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means\n# that P + 1 < Q.\n# \n# The function should return the number of arithmetic slices in the array A.\n# \n# \n# \n# **Example:**\n# \n#     \n#     \n#     A = [1, 2, 3, 4]\n#     \n#     return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.\n#     \n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction number_of_arithmetic_slices(nums::Vector{Int})\n    dp, res = 0, 0\n    for i in 3:length(nums)\n        if nums[i] + nums[i - 2] == (nums[i - 1] << 1)\n            res += (dp += 1)\n        else\n            dp = 0\n        end\n    end\n    return res\nend\n## @lc code=end\n", "meta": {"hexsha": "e5b0b37ff297fee413cf288df4ce00ea2b6226cc", "size": 1505, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/413.arithmetic-slices.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/413.arithmetic-slices.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/413.arithmetic-slices.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 22.1323529412, "max_line_length": 92, "alphanum_fraction": 0.5747508306, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88720460564669, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.75759532559001}}
{"text": "# A CKAR(2) model\n# Here we demonstrate the package's utilities in the context of a simple censored and kinked AR(2) model with two regimes.\n#\n# Consider the model\n# $$\\begin{align}\n# y_t^*&=\\phi_1^*y_{t-1}^*+\\phi_1y_{t-1}+\\phi_2^*y_{t-1}^*+\\phi_2y_{t-1}+\\epsilon_t,\\\\\n# y_t&=\\max\\{y_t^*,0\\}.\n# \\end{align}$$\n#\n# This features a 'positive regime' ($y^*\\geq0$) and a 'negative regime' ($y^*<0$).\n##\n# Noting $y_t=\\mathbf{1}\\{y_t^*\\geq0\\}y_t^*$, we can rewrite the equation for $y_t^*$ as $$y_t^*=(\\phi_1^*+\\phi_1\\mathbf{1}\\{y_{t-1}\\geq0\\})y_{t-1}^*+(\\phi_2^*+\\phi_2\\mathbf{1}\\{y_{t-2}\\geq0\\})y_{t-2}^*+\\epsilon_t,$$\n# where $\\mathbf{1}\\{y\\geq0\\}$ is an indicator variable.\n##\nusing ThresholdStability\n\nfunction AR2_to_TAR(ϕs, ϕ_stars)\n    ϕ1, ϕ2 = ϕs\n    ϕ1_star, ϕ2_star = ϕ_stars\n    Σ = []\n    vals = [1, -1]\n    for val1 in vals\n        for val2 in vals\n            A = zeros(2, 2); A[2, 1] = 1\n            A[1, 1] = ϕ1_star + ϕ1 * indicator(val1, 0)\n            A[1, 2] = ϕ2_star + ϕ2 * indicator(val2, 0)\n            push!(Σ, A)\n        end\n    end\n    return Vector{Array{Float64, 2}}(Σ)\n    # NOTE Σ is of form where Σ[1] is with yₜ₋₁,yₜ₋₂ ≥ 0, Σ[2] is with yₜ₋₁ ≥ 0 and yₜ₋₂ < 0, Σ[3] is with yₜ₋₁ < 0 and yₜ₋₂ ≥ 0\n    # and Σ[4] is with yₜ₋₁,yₜ₋₂ < 0.\nend\n##\n# This yields a set of four $2\\times2$ matrices, with each matrix corresponding to a different regime pair (positive-positive, positive-negative, negative-positive and negative-negative.)\n#\n# For exposition, consider $\\phi_1 = 0.4$, $\\phi_1^* = 0.2$, $\\phi_2=0.2$, and $\\phi_2^*=0.1$:\n##\nΣ4 = AR2_to_TAR([0.4, 0.2], [0.2, 0.1])\n##\n# The state space constraints for this model are given by `X4`:\n##\nE1, E2, E3, E4 = [1 0.; 0 1.], [1 0.; 0 -1.], [-1 0.; 0 1.], [-1 0.; 0 -1.]\nD1 = zeros(1,2); D2, D3, D4 = copy(D1), copy(D1), copy(D1)\nX4 = [[E1, D1], [E2, D2], [E3, D3], [E4, D4]]\n##\n# and the automaton can be constructed using\n##\nG = automaton_constructor(Σ4)\n##\n# We then have the discrete system\ns4 = discreteswitchedsystem(Σ4, G, X4)\n##\n# Alternatively, by substituting for $y_t$ on the first lag only we can produce a set of two $3\\times3$ matrices:\n##\nfunction AR2_to_companion(ϕs, ϕ_stars)\n    ϕ1, ϕ2 = ϕs\n    ϕ1_star, ϕ2_star = ϕ_stars\n    Σ = []\n    vals = [1, -1]\n    for val in vals\n        A = zeros(3, 3); A[2, 1] = 1; A[1, 2] = ϕ2_star; A[1, 3] = ϕ2\n        A[1, 1] = ϕ1_star + ϕ1 * indicator(val, 0)\n        A[3, 1] = indicator(val, 0)\n        push!(Σ, A)\n    end\n    return Vector{Array{Float64, 2}}(Σ)\n\n    # NOTE Σ has form s.t. Σ[1] is with yₜ₋₁ ≥ 0 and Σ[2] is with yₜ₋₁ < 0\nend\n\nΣ2 = AR2_to_companion([0.4, 0.2], [0.2, 0.1])\nΣ2st = [Σ2[1], Σ2[2], Σ2[1], Σ2[2]]\n##\n# `Σ2` consists of the two matrices and `Σ2st` corresponds to the same partitioning of the state space as for `Σ4`.\n\nIn this latter case, the automaton is again `G` but the state space constraints are now given by `X2`:\n##\nE1, E2, E3, E4 = [1 0 0.; 0 1 0.], [1 0 0.; 0 -1 0.], [-1 0 0.; 0 1 0.], [-1 0 0.; 0 -1 0.]\nD1, D3 = [0 1 -1.], [0 1 -1.]; D2, D4 = [0 0 1.], [0 0 1.]\nX2 = [[E1, D1], [E2, D2], [E3, D3], [E4, D4]]\n##\n# and we construct the discrete switched systems\n##\ns2 = discreteswitchedsystem(Σ2)\ns2st = discreteswitchedsystem(Σ2st, G, X2)\n##\n# For our choice of parameter values, this model is stable. In particular, the upper bounds on the joint spectral radius (JSR) of `Σ2`, the constrained joint spectral radius (CJSR) of `(Σ4, G)`, and the state-constrained joint spectral radii (SCJSR) of `(Σ4, G, X4)` and `(Σ2st, G, X2)` all agree in value, up to 4 significant figures:\n##\n@show γ_jsr2 = jsr(s2)\n@show γ_cjsr4 = cjsr(s4)\n@show γ_scjsr4 = sosbound_γ(s4, 2)\n@show γ_scjsr2 = sosbound_γ(s2st, 2)\n##\n# Indeed, if $\\phi_i,\\phi_i^*\\geq0$ for $i=1,2$, then the model will be stable if and only if\n# $\\sum_{i=1}^2(\\phi_i+\\phi_i^*)<1$.\n#\n# As expected, the model appears stable when plotted:\n##\nusing Plots, Distributions\nusing LaTeXStrings\npyplot()\nfunction simulate_AR2(y0, Σ, T, σ)  # for companion form\n    y = zeros(3, T)\n    y[:, 1] = y0\n    for t in 1:T-1\n        ϵ_t = [rand(Normal(0, σ)), 0., 0.]\n        if y[1, t] ≥ 0.\n            y[:, t+1] = Σ[1]*y[:, t] + ϵ_t\n        else\n            y[:, t+1] = Σ[2]*y[:, t] + ϵ_t\n        end\n    end\n    return y\nend\n\nfunction plot_AR2(y0, Σ, T, σ; N = 20, row=1)\n    ys = []\n    ens_means = zeros(T)\n    for i in 1:N\n        y = simulate_AR2(y0, Σ, T, σ)\n        y = y[row,:]\n        push!(ys, y)\n        ens_means .+= y\n    end\n    ens_means ./= N  # ensemble means\n\n    E_y = simulate_AR2(y0, Σ, T, 0.)  # calculating deterministic results\n    E_y = E_y[row,:]\n\n    plot(ys, color = :grey, alpha = 0.1, label = \"\")\n    plot!(ens_means, color = :grey, linewidth = 2, label = \"Ensemble mean\")\n    plot!(E_y, color = :blue, linewidth = 2, linestyle = :dash, label = \"Deterministic\")\n    plot!(xlabel=L\"t\", legend=:topright)\nend\n\nplot_AR2(3*ones(3), Σ2, 200, 1)\nplot!(ylabel=L\"y^*\", yguidefontrotation=-90)\n##\n# Introducing negative parameters, we see that the different upper bounds can diverge.\n#\n# Consider $\\phi_1=0.5$, $\\phi_1^*=0.5$, $\\phi_2=-0.47$, $\\phi_2^*=-0.5$. When plotted, the system appears stable:\n##\nΣ = AR2_to_companion([0.5, -0.47], [0.5, -0.5])\nplot_AR2(3*ones(3), Σ, 200, 1, row=1)\nplot!(ylabel=L\"y^*\", yguidefontrotation=-90)\n##\n# However, this is a case where the conservatism of (the upper bounds on) the JSR and CJSR would prevent us from concluding the system is stable.\n##\nΣ = AR2_to_TAR([0.5, -0.47], [0.5, -0.5])\nE1, E2, E3, E4 = [1 0.; 0 1.], [1 0.; 0 -1.], [-1 0.; 0 1.], [-1 0.; 0 -1.]\nD1 = zeros(1,2); D2, D3, D4 = copy(D1), copy(D1), copy(D1)\nX = [[E1, D1], [E2, D2], [E3, D3], [E4, D4]]  # state space constraints\nG = automaton_constructor(Σ)\ns = discreteswitchedsystem(Σ, G, X)\n@show γ_jsr = jsr(s)  # > 1\n@show γ_cjsr = cjsr(s)  # > 1\n##\n# However, the upper bound on the SCJSR is less conservative, yielding a bound below 1. We can thus conclude the system is stable.\n##\n@show γ_scjsr = sosbound_γ(s, 2)  # < 1\n##\n# Note that (the upper bound on) the SCJSR remains conservative, even if less so than the CJSR or JSR.\n#\n# For example, consider $\\phi_1=\\phi_1^*=0.6$ and $\\phi_2=\\phi_2^*=-0.6$. This appears stable:\n##\nΣ = AR2_to_companion([0.6, -0.6], [0.6, -0.6])\nplot_AR2(3*ones(3), Σ, 200, 1, row=1)\nplot!(ylabel=L\"y^*\", yguidefontrotation=-90)\n##\n# Plots for other initial values $y_0$ follow a similar pattern.\n#\n# However, the bound on the SCJSR exceeds 1 in this case (as does the bound for the CJSR)\n##\nΣ = AR2_to_TAR([0.6, -0.6], [0.6, -0.6])\ns = discreteswitchedsystem(Σ, G, X)\n@show γ_cjsr = cjsr(s)\n@show γ_scjsr = sosbound_γ(s, 2)\n", "meta": {"hexsha": "416a321fe35a431324c6641467bb79a6c4e56c0e", "size": 6591, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/src/CKAR2.jl", "max_stars_repo_name": "blegat/ThresholdStability.jl", "max_stars_repo_head_hexsha": "d28102c45e44a6c899ee592406b441b16290b4e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/src/CKAR2.jl", "max_issues_repo_name": "blegat/ThresholdStability.jl", "max_issues_repo_head_hexsha": "d28102c45e44a6c899ee592406b441b16290b4e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/src/CKAR2.jl", "max_forks_repo_name": "blegat/ThresholdStability.jl", "max_forks_repo_head_hexsha": "d28102c45e44a6c899ee592406b441b16290b4e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8212290503, "max_line_length": 335, "alphanum_fraction": 0.6012744652, "num_tokens": 2793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.757595317052373}}
{"text": "export uncertainty_exponent, basins_fractal_dimension\n\n\"\"\"\n    basins_fractal_dimension(basins; kwargs...) -> V_ε, N_ε ,d\nEstimate the [Fractal Dimension](@ref) `d` of the boundary between basins of attraction using\nthe box-counting algorithm.\n\nThe output `N_ε` is a vector with the number of the balls of radius `ε` (in pixels)\nthat contain at least two initial conditions that lead to different attractors. `V_ε`\nis a vector with the corresponding size of the balls. The ouput `d` is the estimation\nof the box-counting dimension of the boundary by fitting a line in the `log.(N_ε)`\nvs `log.(1/V_ε)` curve. However it is recommended to analyze the curve directly\nfor more accuracy.\n\n## Keyword arguments\n* `range_ε = 2:maximum(size(basins))÷20` is the range of sizes of the ball to\n  test (in pixels).\n\n## Description\n\nIt is the implementation of the popular algorithm of the estimation of the box-counting\ndimension. The algorithm search for a covering the boundary with `N_ε` boxes of size\n`ε` in pixels.\n\"\"\"\nfunction basins_fractal_dimension(basins::AbstractArray; range_ε = 3:maximum(size(basins))÷20)\n\n    dims = size(basins)\n    num_step = length(range_ε)\n    N_u = zeros(Int, num_step) # number of uncertain box\n    N = zeros(Int, num_step) # number of boxes\n    V_ε = zeros(1, num_step) # resolution\n\n    # Naive box counting estimator\n    for (k,eps) in enumerate(range_ε)\n        Nb, Nu = 0, 0\n        # get indices of boxes\n        bx_tuple = ntuple(i -> range(1, dims[i] - rem(dims[i],eps), step = eps), length(dims))\n        box_indices = CartesianIndices(bx_tuple)\n        for box in box_indices\n            # compute the range of indices for the current box\n            ind = CartesianIndices(ntuple(i -> range(box[i], box[i]+eps-1, step = 1), length(dims)))\n            c = basins[ind]\n            if length(unique(c))>1\n                Nu = Nu + 1\n            end\n            Nb += 1\n        end\n        N_u[k] = Nu\n        N[k] = Nb\n        V_ε[k] = eps\n    end\n    N_ε = N_u\n    # remove zeros in case there are any:\n    ind = N_ε .> 0.0\n    N_ε = N_ε[ind]\n    V_ε = V_ε[ind]\n    # get exponent via liner regression on `f_ε ~ ε^α`\n    b, d = linreg(vec(-log10.(V_ε)), vec(log10.(N_ε)))\n    return V_ε, N_ε, d\nend\n\n\"\"\"\n    uncertainty_exponent(basins; kwargs...) -> ε, N_ε ,α\nEstimate the uncertainty exponent[^Grebogi1983] of the basins of attraction. This exponent\nis related to the final state sensitivity of the trajectories in the phase space.\nAn exponent close to `1` means basins with smooth boundaries whereas an exponent close\nto `0` represent complety fractalized basins, also called riddled basins.\n\nThe output `N_ε` is a vector with the number of the balls of radius `ε` (in pixels)\nthat contain at least two initial conditions that lead to different attractors.\nThe ouput `α` is the estimation of the uncertainty exponent using the box-counting\ndimension of the boundary by fitting a line in the `log.(N_ε)` vs `log.(1/ε)` curve.\nHowever it is recommended to analyze the curve directly for more accuracy.\n\n## Keyword arguments\n* `range_ε = 2:maximum(size(basins))÷20` is the range of sizes of the ball to\n  test (in pixels).\n\n## Description\n\nA phase space with a fractal boundary may cause a uncertainty on the final state of the\ndynamical system for a given initial condition. A measure of this final state sensitivity\nis the uncertainty exponent. The algorithm probes the basin of attraction with balls\nof size `ε` at random. If there are a least two initial conditions that lead to different\nattractors, a ball is tagged \"uncertain\". `f_ε` is the fraction of \"uncertain balls\" to the\ntotal number of tries in the basin. In analogy to the fractal dimension, there is a scaling\nlaw between, `f_ε ~ ε^α`. The number that characterizes this scaling is called the\nuncertainty exponent `α`.\n\nNotice that the uncertainty exponent and the box counting dimension of the boundary are\nrelated. We have `Δ₀ = D - α` where `Δ₀` is the box counting dimension computed with\n[`basins_fractal_dimension`](@ref) and `D` is the dimension of the phase space.\nThe algorithm first estimates the box counting dimension of the boundary and\nreturns the uncertainty exponent.\n\n[^Grebogi1983]: C. Grebogi, S. W. McDonald, E. Ott and J. A. Yorke, Final state sensitivity: An obstruction to predictability, Physics Letters A, 99, 9, 1983\n\"\"\"\nfunction uncertainty_exponent(basins::AbstractArray; range_ε = 2:maximum(size(basins))÷20)\n    V_ε, N_ε, d = basins_fractal_dimension(basins; range_ε)\n    return V_ε, N_ε, length(size(basins)) - d\nend\n", "meta": {"hexsha": "98c0c675bcacfa52541468dfb54fd25a4b4ae989", "size": 4549, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basins/uncertainty_exp.jl", "max_stars_repo_name": "onkyo14taro/ChaosTools.jl", "max_stars_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 168, "max_stars_repo_stars_event_min_datetime": "2018-01-07T15:46:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T13:38:24.000Z", "max_issues_repo_path": "src/basins/uncertainty_exp.jl", "max_issues_repo_name": "onkyo14taro/ChaosTools.jl", "max_issues_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 176, "max_issues_repo_issues_event_min_datetime": "2017-12-19T20:26:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:08:23.000Z", "max_forks_repo_path": "src/basins/uncertainty_exp.jl", "max_forks_repo_name": "onkyo14taro/ChaosTools.jl", "max_forks_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2018-01-27T07:59:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T10:08:36.000Z", "avg_line_length": 44.5980392157, "max_line_length": 157, "alphanum_fraction": 0.7140030776, "num_tokens": 1250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7575606634529446}}
{"text": "using Plots\nusing BenchmarkTools\n#2(a)\nfunction vfsolvex(vnew, kgrid, tolerance, imax, σ=1.5)\n    β=0.9\n  \n    v=vnew .+ 2*tolerance\n    cartesianindex = Array{CartesianIndex{2}, length(v)}\n    i=1\n  \n    c = kgrid .- kgrid'\n    c[c .< 0] .= 0\n    if σ==1\n      u = log.(c)\n    else\n      u = (c.^(1-σ).-1)./(1-σ)\n    end\n    u[kgrid .- kgrid' .< 0] .= -Inf\n  \n    while maximum(abs.(v-vnew)) > tolerance && i <= imax\n      v = vnew;\n  \n      (vnew, cartesianindex) = findmax(u .+ β*v', dims = 2);\n      i += 1;\n    end\n    kprimeindex = getindex.(cartesianindex, 2)\n    return (v=vnew, kprime=kgrid[kprimeindex], kprimeindex=kprimeindex)\n  end\n  \n  \n  kupper = 5\n  klower = 0.01\n  n = 500\n  kgrid = collect(range(klower, stop=kupper, length = n))\n  (v, kprime, kprimeindex) = vfsolvex(zeros(n), kgrid, 0.001, 1000)\n  #(b)\n  (v, kprime, kprimeindex) = vfsolvex(zeros(500), kgrid, 0.001, 1000);\n   plot(kgrid, v, label = \"v, σ=1.5\")\n  \n  #(c)\n  plot()\n  for x in [1.25, 1.1, 1.001, 1.00001, 1]\n    kgrid = collect(range(klower, stop=kupper, length=500))\n    (v, kprime, kprimeindex) = vfsolvex(zeros(500), kgrid, 0.001, n, x);\n    display(plot!(kgrid, v, label = \"v, σ=$x\"))\n  end\n#as σ->1, the value function is getting closer to log utility value function\n#the vfsolvex autometically compute log utility solution when σ=1.\n#We also solve the log utility problem analytically in PS 5, and the numerical and \n#analytical solution coinside\n\n#(d)\nfunction policy(x)\n    e=getindex(findall(kgrid .== x),1)\n    return kprime[e]  \nend \n\nfunction findindex(x)\n    a=findmin(abs.(x .- kgrid), dims=1)\n    return a[2]\nend \n\nfunction findkpath(T, k_0)\n    w = findindex(k_0)\n    kpath = zeros(T)\n    k = kgrid[w]\n        for i in 1:T\n            k = policy(k)\n            kpath[i] = k\n        end \n    return kpath \nend \n\nfunction plotkpath(T, k_0)\n    w = findindex(k_0)\n    kpath = zeros(T)\n    k = kgrid[w]\n        for i in 1:T\n            k = policy(k)\n            kpath[i] = k\n        end \n    time = collect(range(1, T, length = T))\n    plot(time, kpath, label = \"kpath\")\nend \n    \nfindkpath(100, 5)\nplotkpath(100, 5)\n# this is a cake eating problem with no production, so capital always decline\n\n", "meta": {"hexsha": "8af6d05e3f3bf11f731d51ebb164b95e65f81026", "size": 2193, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Problem2.jl", "max_stars_repo_name": "paradoxuu/Dynamic-Programming-Problems", "max_stars_repo_head_hexsha": "305d31d97c8864890f019eca2aef9d11513cd14c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Problem2.jl", "max_issues_repo_name": "paradoxuu/Dynamic-Programming-Problems", "max_issues_repo_head_hexsha": "305d31d97c8864890f019eca2aef9d11513cd14c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Problem2.jl", "max_forks_repo_name": "paradoxuu/Dynamic-Programming-Problems", "max_forks_repo_head_hexsha": "305d31d97c8864890f019eca2aef9d11513cd14c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3666666667, "max_line_length": 83, "alphanum_fraction": 0.5886912905, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7575606589530246}}
{"text": "module TSExplore\n\n### Work through of Ch. 8 Brockwell and Davis 2002,\n### \"Introduction to Time Series and Forecasting,\" 2nd ed.\n\n\n\"\"\"\nThe notation `WN(0, Rt²)` denotes an uuncorrelated sequence of random variables with mean\nzero and standard deviation `Rt` at each time index `t`.\n\"\"\"\n\n## Observation equation p. 260\nexport obs_eq\n\n\"\"\"\n    Yt = Gt Xt + Wt\n\nThe variable `Wt` is independent zero mean white noise with standard deviation `Rt` for each\n`t`.\n\n\"\"\"\nobs_eq(Gt, Xt, Wt) = Gt*Xt + Wt\n\n## State equation p. 260\nexport state_eq\n\n\"\"\"\n    X(t+1) = Ft Xt + Vt\n\nThe variable `Vt` is independent zero mean white noise with standard deviation `Qt` for each\n`t`.\n\n\"\"\"\nstate_eq(Ft, Xt, Vt) = Ft*Xt + Vt\n\n## Example 8.1.1 AR(1) process\n\nexport ar1_eq_direct, AR1Model\n\n\"\"\"\n    y(t+1) = ϕYt + Zt\n\nThe process `Zt ~ WN(0, σ²)`\n\n\"\"\"\nar1_eq_direct(ϕ, y, z) = ϕ*y + z\n\n# In state space notation.\nstruct AR1Model\n    ϕ\n    F\n    G\n\n    function AR1Model(ϕ)\n        F = reshape([ϕ], 1, 1)\n        G = ones(eltype(ϕ), 1, 1)\n        return new(ϕ, F, G)\n    end\nend\n\nstate_eq(m::AR1Model, x, z) = state_eq(m.F, x, [z])\nobs_eq(m::AR1Model, x, z) = obs_eq(m.G, x, zeros(eltype(z), 1))\n\n## Example 8.1.2 ARMA(1,1) process\nexport ARMA11Model, arma11_eq_direct\n\n\"\"\"\n    y(t+1) = ϕYt + Zt + θZ(t-1)\n\nThe process `Zt ~ WN(0, σ²)`\n\n\"\"\"\narma11_eq_direct(ϕ, θ, y, zt, ztm1) = ϕ*y + z + θ*ztm1\n\n# In State Space notation\nstruct ARMA11Model\n    ϕ  # AR param\n    θ  # MA param\n    F  # state transition matrix\n    G  # observation transition matrix\n\n    function ARMA11Model(ϕ, θ)\n        F = [0 1; 0 ϕ]\n        G = [θ 1]\n        return new(ϕ, θ, F, G)\n    end\nend\n\nstate_eq(m::ARMA11Model, x, z) = state_eq(m.F, x, [zero(first(x)), z])\nobs_eq(m::ARMA11Model, x, z) = obs_eq(m.G, x, zeros(eltype(x), 1))\n\n\n\n### Simulate utilities for exploring processes.\ninclude(\"simulate.jl\")\n\nend # module\n", "meta": {"hexsha": "c927aa959c2eef647d11151dccfe2753c25f1dcb", "size": 1868, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TSExplore.jl", "max_stars_repo_name": "venuur/TSExplore", "max_stars_repo_head_hexsha": "46f469bc3904a1fd80c6d660efd013bdb991d8b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TSExplore.jl", "max_issues_repo_name": "venuur/TSExplore", "max_issues_repo_head_hexsha": "46f469bc3904a1fd80c6d660efd013bdb991d8b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TSExplore.jl", "max_forks_repo_name": "venuur/TSExplore", "max_forks_repo_head_hexsha": "46f469bc3904a1fd80c6d660efd013bdb991d8b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0612244898, "max_line_length": 92, "alphanum_fraction": 0.619379015, "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7575606571908292}}
{"text": "# Kernel definition is taken from here: https://en.wikipedia.org/wiki/Kernel_(statistics)#Kernel_functions_in_common_use\n\nexport Epanechnikov_kernel, Uniform_kernel, Triangular_kernel, Quartic_Kernel, Triweight_Kernel, Tricube_Kernel, Gaussian_Kernel, Cosine_Kernel, Logistic_Kernel, Sigmoid_Kernel, Silverman_Kernel\n\nfunction Epanechnikov_kernel(t)\n    if abs(t) > 1\n        return 0\n    else\n        return 0.75*(1-t^2)\n    end\nend\n\nfunction Uniform_kernel(t)\n    if abs(t) > 1\n        return 0\n    else\n        return 0.5\n    end\nend\n\nfunction Triangular_kernel(t)\n    if abs(t) > 1\n        return 0\n    else\n        return (1-abs(t))\n    end\nend\n\nfunction Quartic_Kernel(t)\n  if abs(t)>0\n    return 0\n  else\n    return (15*(1-t^2)^2)/16\n  end\nend\n\nfunction Triweight_Kernel(t)\n  if abs(t)>0\n    return 0\n  else\n    return (35*(1-t^2)^3)/32\n  end\nend\n\nfunction Tricube_Kernel(t)\n  if abs(t)>0\n    return 0\n  else\n    return (70*(1-abs(t)^3)^3)/80\n  end\nend\n\nfunction Gaussian_Kernel(t)\n  exp(-0.5*t^2)/(sqrt(2*π))\nend\n\nfunction Cosine_Kernel(t)\n  if abs(t)>0\n    return 0\n  else\n    return (π*cos(π*t/2))/4\n  end\nend\n\nfunction Logistic_Kernel(t)\n  1/(exp(t)+2+exp(-t))\nend\n\nfunction Sigmoid_Kernel(t)\n  2/(π*(exp(t)+exp(-t)))\nend\n\nfunction Silverman_Kernel(t)\n  sin(abs(t)/2+π/4)*0.5*exp(-abs(t)/sqrt(2))\nend\n", "meta": {"hexsha": "1027a10d48bc8c300793ab615d15b4c7ec666aed", "size": 1312, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/DiffEqParamEstim.jl-1130ab10-4a5a-5621-a13d-e4788d82bd4c", "max_stars_repo_head_hexsha": "2344b1f54707f8f3b4ee4fab2c9b4dd1ebbee484", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/DiffEqParamEstim.jl-1130ab10-4a5a-5621-a13d-e4788d82bd4c", "max_issues_repo_head_hexsha": "2344b1f54707f8f3b4ee4fab2c9b4dd1ebbee484", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-28T23:47:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-28T23:47:15.000Z", "max_forks_repo_path": "src/kernels.jl", "max_forks_repo_name": "Vaibhavdixit02/DiffEqParamEstim.jl", "max_forks_repo_head_hexsha": "d68ac5e139eb1005064d1b5f404870c008889d03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.2631578947, "max_line_length": 194, "alphanum_fraction": 0.6608231707, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7574975821465275}}
{"text": "# Various simple graph functions associated with graph coloring.\n\nexport bipartition, two_color, greedy_color, random_greedy_color\n\n# Create a two-coloring of a graph or die trying. Returns a map from\n# the vertex set to the set {1,2}, or error if no such mapping exists.\n\n\"\"\"\n`two_color(G)` creates a two-coloring of the graph or throws an error\nif tghe graph is not bipartite. The output is a `Dict` mapping the\nvertex set to the values 1 and 2.\n\"\"\"\nfunction two_color{T}(G::SimpleGraph{T})\n    f = Dict{T,Int}()\n    for A in components(G)\n        a = first(A)\n        f[a] = 1\n        Q = Deque{T}()\n        push!(Q,a)\n        while length(Q)>0\n            v = pop!(Q)\n            Nv = G[v]\n            for w in Nv\n                if haskey(f,w)\n                    if f[w]==f[v]\n                        error(\"Graph is not bipartite\")\n                    end\n                else\n                    f[w] = 3-f[v]\n                    push!(Q,w)\n                end\n            end\n        end\n    end\n    return f\nend\n\n# Create a bipartition of a graph or die trying. Returns a set {X,Y}\n# that is a bipartition of the vertex set of G.\n\nusing SimplePartitions\n\"\"\"\n`bipartition(G)` creates a bipartition of the graph (or returns an\nerror if the graph is not bipartite. Output is a `Partition`.\n\"\"\"\nfunction bipartition{T}(G::SimpleGraph{T})\n  f = two_color(G)\n  return Partition(f)\nend\n\n# Color a graph by the greedy algorithm in the sequence specified by\n# seq. The array seq must be a permutation of G.V. We don't check\n# that's true!\n\n\"\"\"\n`greedy_color(G,seq)` creates a greedy proper coloring of the\ngraph. The argument `seq` should be a 1-dimensional array containing\nevery vertex exactly once (the function does not check this for\nyou). The function follows that order in creating the coloring which\nis returned to you as a `Dict` mapping vertices to positive integers\n(representing the colors).\n\nIf `seq` is omitted, a random permutation of the vertices is used.\n\"\"\"\nfunction greedy_color{T}(G::SimpleGraph{T}, seq::Array{T,1})\n    f = Dict{T,Int}()  # this is the mapping from V to colors\n    maxf::Int = 0      # largest color used\n\n    for v in seq\n        colors_used = falses(maxf)  # array if color is used by N[v]\n        for w in G[v]\n            if haskey(f,w)  # w already colored\n                colors_used[f[w]]=true  # mark that color is used\n            end\n        end\n        # give first unused color to v\n        for k in 1:maxf\n            if colors_used[k] == false\n                f[v] = k\n                break\n            end\n        end\n        # but if that fails, extend the number of colors available\n        if !haskey(f,v)\n            maxf += 1\n            f[v] = maxf\n        end\n    end\n    return f\nend\n\n# This function returns a list of the vertices of G in descending\n# order by degree. The order of vertices of the same degree is\n# indeterminate. NOTE: This is not exported from this module. Should\n# it be?\nfunction deg_sorted_vlist(G::SimpleGraph)\n    bye = x -> -x[1]\n    list = [ (deg(G,v) , v) for v in G.V ]\n    sort!(list, by=bye)\n    outlist = [ item[2] for item in list ]\n    return outlist\nend\n\n# Apply greedy_color to the graph visiting the vertices in decreasing\n# order of degree.\nfunction greedy_color{T}(G::SimpleGraph{T})\n    seq = deg_sorted_vlist(G)\n    return greedy_color(G,seq)\nend\n\n# Generate multiple random orders of the vertex set and apply\n# greedy_color; return one that uses the fewest colors. This do as\n# well as or better than greedy_color on some decreasing order of\n# degree.\n\n\"\"\"\n`random_greedy_color(G, reps)` repeatedly invokes `greedy_color` using\nrandom permutations of the vertex set. After `reps` iterations, the\nbest coloring found is returned.\n\"\"\"\nfunction random_greedy_color{T}(G::SimpleGraph{T}, reps::Int=1)\n    n = NV(G)\n    bestf = greedy_color(G)  # degree order default start\n    best  = maximum(values(bestf))\n    seq = vlist(G)\n    println(\"Initial coloring uses \", best, \" colors\")\n\n    for k in 1:reps\n        shuffle!(seq)\n        f = greedy_color(G,seq)\n        mx = maximum(values(f))\n        if mx < best\n            bestf = f\n            best = mx\n            println(\"Reduced to \", best, \" colors\")\n        end\n    end\n    return bestf\nend\n", "meta": {"hexsha": "16c12073057f1d2d6d83190124a75293524b59c3", "size": 4246, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simple_coloring.jl", "max_stars_repo_name": "EliasBcd/SimpleGraphs.jl", "max_stars_repo_head_hexsha": "89fdc4c2151e9841ed2b86ed63fe912485a5ab5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-18T04:15:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-18T04:15:02.000Z", "max_issues_repo_path": "src/simple_coloring.jl", "max_issues_repo_name": "EliasBcd/SimpleGraphs.jl", "max_issues_repo_head_hexsha": "89fdc4c2151e9841ed2b86ed63fe912485a5ab5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simple_coloring.jl", "max_forks_repo_name": "EliasBcd/SimpleGraphs.jl", "max_forks_repo_head_hexsha": "89fdc4c2151e9841ed2b86ed63fe912485a5ab5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3285714286, "max_line_length": 70, "alphanum_fraction": 0.6210551107, "num_tokens": 1107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7574975718500586}}
{"text": "# ------------------------------------------------------------------------------------------\n# ## Functions\n#\n#\n# In the last notebook, we talked about modeling data with functions. A **function** is one\n# of the most fundamental concepts in computing (and also in mathematics).\n#\n# A function is a piece of a program that receives **input arguments**, processes them by\n# doing certain calculations on them, and returns **outputs**.\n#\n# For example, we might have a function `g` that takes a number as an input and returns the\n# square of that number as an output. How can we define this function `g` on a computer?\n# Julia gives us a few different ways to do this.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ### Defining functions\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Firstly, we could write `g` as follows:\n# ------------------------------------------------------------------------------------------\n\ng(x) = x^2\n\na = \"Machine is learning is fun \"\ng(a)\n\n# ------------------------------------------------------------------------------------------\n# Alternatively, we could declare this function using the `function` and `end` keywords:\n# ------------------------------------------------------------------------------------------\n\nfunction g1(x)\n    return x^2\nend\n\n# ------------------------------------------------------------------------------------------\n# The third way we could have declared this function is as an \"anonymous\" or \"lambda\"\n# function. \"Anonymous\" functions are functions that truly don't need names! For example, we\n# could have declared a function that squares its input as\n# ------------------------------------------------------------------------------------------\n\n(x -> x^2)(\"I ♡ Julia. \") # \\heartsuit + <tab>\n\n# ------------------------------------------------------------------------------------------\n# Now that we've done that, we can't access the function `x -> x^2` again because we have no\n# name to call! That seems a little silly, doesn't it?\n#\n# Actually, there are times where functions without names are useful to us. We'll see that\n# later in this notebook. For now, note that you have the *option* to access an \"anonymous\"\n# function later by binding a variable to it when you declare it. For example,\n# ------------------------------------------------------------------------------------------\n\ng = x -> x^2\n\n# ------------------------------------------------------------------------------------------\n# This syntax says, \"I want to use the variable g to access a function that takes some input\n# called `x` and maps that input to the square of `x`.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## An important sigmoidal function\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# A particular function that is used a lot in machine learning is a so-called \"sigmoidal\"\n# function (meaning a function that is S-shaped, i.e. the graph of the function looks like\n# an `S`).\n#\n# The sigmoid function that we will use is given the name $\\sigma$, and is defined by the\n# following mathematical expression:\n#\n# $$\\sigma(x) := \\frac{1}{1 + \\exp(-x)}.$$\n# ------------------------------------------------------------------------------------------\n\nσ(w*x) = 1/ (1+e^(-w*x))\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 1\n#\n# Use the first syntax given above to define the function `σ` in Julia. Note that Julia\n# actually allows us to use the symbol σ as a variable name! To do so, type `\\sigma<TAB>` in\n# the code cell.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## Plotting functions\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Let's draw the function σ to see what it looks like. Throughout this course, we'll use the\n# Julia package `Plots.jl` for all of the graphics. This package provides a flexible syntax\n# for plotting, in which options to change attributes like the width of the lines used in\n# the figure are given as named keyword arguments.\n#\n# In addition, it allows us to use different \"backends\", which are the other libraries that\n# actually carry out the plotting following the instructions from `Plots.jl`.\n# ------------------------------------------------------------------------------------------\n\nusing Plots\ngr()   # use the PlotlyJS \"backend\" (plotting library)\n\nplot(σ, -5, 5)\n\nhline!([0, 1], ls=:dash, lw=3)  # add horizontal lines at 0 and 1, with dashed style and linewidth 3\nvline!([0], ls=:dash, lw=3)     # add a vertical line at 0\n\n# ------------------------------------------------------------------------------------------\n# We can think of $\\sigma$ as a smooth version of a step or threshold function (often called\n# a \"Heaviside\" function). To see this, let's modify the steepness of the jump in $\\sigma$\n# and compare it to the Heaviside function; we'll see how all this works in more detail\n# later:\n# ------------------------------------------------------------------------------------------\n\nusing Interact\n\nheaviside(x) = x < 0 ? 0.0 : 1.0\n\n@manipulate for w in 0.1:0.1:20\n    plot(x -> σ(w*x), -5, 5, label=\"sigma\", lw=2)\n    plot!(heaviside, ls=:dash, label=\"step\")\nend\n\n# ------------------------------------------------------------------------------------------\n# This particular function takes any real number as input, and gives an output between $0$\n# and $1$. It is continuous and smooth.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 2\n#\n# Declare the sigmoid function above as an anonymous function with a different name.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ### Mutating functions: `...!`\n#\n# To generate our plot of σ above, we used some functions that end with `!`. What does a `!`\n# at the end of a function name mean in Julia?\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Functions that change or modify their inputs are called **mutating functions**. But wait,\n# don't all functions do that?\n#\n# No, actually. Functions typically take *inputs* and use those *inputs* to generate\n# *outputs*, but the inputs themselves usually don't actually get changed by a function. For\n# example, copy and execute the following code:\n#\n# ```julia\n# v1 = [9, 4, 7, 11]\n# v2 = sort(v1)\n# ```\n# ------------------------------------------------------------------------------------------\n\n\n\n# ------------------------------------------------------------------------------------------\n# `v2` is a sorted version of `v1`, but after calling `sort`, `v1` is still unsorted.\n#\n# However, now trying adding an exclamation point after `sort` and executing the following\n# code:\n#\n# ```julia\n# sort!(v1)\n# ```\n# ------------------------------------------------------------------------------------------\n\n\n\n# ------------------------------------------------------------------------------------------\n# Look at the values in `v1` now!\n# ------------------------------------------------------------------------------------------\n\n\n\n# ------------------------------------------------------------------------------------------\n# This time, the original vector itself was changed (mutated), and is now sorted. Unlike\n# `sort`, `sort!` is a mutating function. Did the `!` make `sort!` mutating? Well, no, not\n# really. In Julia, `!` indicates mutating functions by convention. When the author of\n# `sort!` wrote `sort!`, they added a `!` to let you to know that `sort!` is mutating, but\n# the `!` isn't what makes a function mutating or non-mutating in the first place.\n#\n# #### Exercise\n#\n# Some of our plotting commands end with `!`. Copy and execute the following code:\n#\n# ```julia\n# r = -5:0.1:5\n# g(x) = x^2\n# h(x) = x^3\n# plot(r, g, label=\"g\")\n# plot!(r, h, label=\"h\")\n# ```\n#\n# Then change the code slightly to remove the `!` after `plot!(r, h)`. How does this change\n# your output? What do you think it means to add `!` after plotting commands?\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## Pointwise application of functions, `.(...)` (known as \"broadcasting\")\n#\n# We saw in a previous notebook that we needed to add `.` after the names of some functions,\n# as in\n#\n# ```julia\n# green_amount = mean(Float64.(green.(apple)))\n# ```\n#\n# What are those extra `.`s really doing?\n#\n# When we add a `.` after a function's name, we are telling Julia that we want to\n# \"**broadcast**\" that function over the inputs passed to the function. This means that we\n# want to apply that function *element-wise* over the inputs; in other words, it will apply\n# the function to each element of the input, and return an array with the newly-calculated\n# values.\n#\n# For example, copy and execute the following code:\n# ```julia\n# g.(r)\n# ```\n# Since the function `g` squares it's input, this squares all the elements of the range `r`.\n#\n# What happens if instead we just call `g` on `r` via\n#\n# ```julia\n# g(r)\n# ```\n# ? Try this out and see what happens.\n# ------------------------------------------------------------------------------------------\n\nx = [1 2 3;4 5 6]\nf(t) = √t + 5\nf.(x)\n\n# ------------------------------------------------------------------------------------------\n# You should see an error message after calling `g(r)`, which says that Julia cannot\n# multiply two vectors. When we call `g(r)`, we ask Julia to multiply `r` by `r`. When we\n# call `g.(r)`, we ask Julia to multiply *each element* in `r` by itself.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 3\n#\n# Copy and execute the following code to get the type of the object `numbers = [1, 2,\n# \"three\", 4.0]`:\n#\n# ```julia\n# numbers = [1, 2, \"three\", 4.0]\n# typeof(numbers)\n# ```\n#\n# What is the type of `numbers`?\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 4\n#\n# Broadcast `typeof` over `numbers` to see what the types of the elements stored inside\n# `numbers` are.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 5\n#\n# Write a `for` loop that applies `g` to each of the elements of `r` and prints the results.\n# Verify that the numbers printed by this `for` loop are equal to the entries of the output\n# of `g.(r)`.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 6\n#\n# Define a range `xs` between -5 and 5 with steps of 0.5.\n# Apply the $\\sigma$ function pointwise to this range and define `ys` as the result.\n# What does the result look like? Plot these as points and join them with lines.\n#\n# Make the plot interactive where you can vary the step size. Fix the range of the plot in\n# the `x` and `y` directions using the functions `xlims!` and `ylims!`.\n# ------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "1ac2720f1659fa902a2fdf9de5d37f697752952e", "size": 12536, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/04. Tools - Functions.jl", "max_stars_repo_name": "grenkoca/JuliaTutorials", "max_stars_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 535, "max_stars_repo_stars_event_min_datetime": "2020-07-15T14:56:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T12:50:32.000Z", "max_issues_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/04. Tools - Functions.jl", "max_issues_repo_name": "grenkoca/JuliaTutorials", "max_issues_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2018-02-25T22:53:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-14T02:15:50.000Z", "max_forks_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/04. Tools - Functions.jl", "max_forks_repo_name": "grenkoca/JuliaTutorials", "max_forks_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 394, "max_forks_repo_forks_event_min_datetime": "2020-07-14T23:22:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:12:57.000Z", "avg_line_length": 44.6120996441, "max_line_length": 100, "alphanum_fraction": 0.4241384812, "num_tokens": 2315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7574975604997398}}
{"text": "# functions for building various standard types of graphs\n\nexport Complete, Path, Cycle, RandomGraph, RandomRegular\nexport RandomTree, code_to_tree\nexport Grid, Wheel, Cube, BuckyBall\nexport Petersen, Kneser, Paley, Knight\n\n\"\"\"\n`Complete(n)` returns a complete graph with `n` vertices `1:n`.\n\n`Complete(n,m)` returns a complete bipartite graph with `n` vertices\nin one part and `m` vertices in the other.\n\n`Complete([n1,n2,...,nt])` returns a complete multipartite graph with\nparts of size `n1`, `n2`, ..., `nt`.\n\"\"\"\n# Create a complete graph\nfunction Complete(n::Int)\n    G = IntGraph(n)\n\n    for k=1:n-1\n        for j=k+1:n\n            add!(G,j,k)\n        end\n    end\n    return G\nend\n\n# Create a complete bipartite graph\nfunction Complete(n::Int, m::Int)\n    G = IntGraph(n+m)\n    for u=1:n\n        for v=n+1:n+m\n            add!(G,u,v)\n        end\n    end\n    return G\nend\n\n# Create the complete multipartite graph with given part sizes\nfunction Complete(parts::Array{Int,1})\n    # check all part sizes are positive\n    for p in parts\n        if p < 1\n            error(\"All part sizes must be positive\")\n        end\n    end\n\n    n = sum(parts)\n    G = IntGraph(n)\n\n    np = length(parts)\n    if np < 2\n        return G\n    end\n\n    # create table of part ranges\n    ranges = Array(Int,np,2)\n    ranges[1,1] = 1\n    ranges[1,2] = parts[1]\n    for k = 2:np\n        ranges[k,1] = ranges[k-1,2] + 1\n        ranges[k,2] = ranges[k,1] + parts[k] - 1\n    end\n\n    # Add all edges between all parts\n    for i=1:np-1\n        for j=i+1:np\n            for u=ranges[i,1]:ranges[i,2]\n                for v=ranges[j,1]:ranges[j,2]\n                    add!(G,u,v)\n                end\n            end\n        end\n    end\n\n    return G\nend\n\n\n\n# Create a path graph on n vertices\n\"\"\"\n`Path(n)` creates a path graph with `n` vertices named `1:n`.\n\n`Path(array)` creates a path graph with vertices `array[1]`,\n`array[2]`, etc.\n\"\"\"\n\nfunction Path(n::Int)\n    G = IntGraph(n)\n    for v = 1:n-1\n        add!(G,v,v+1)\n    end\n    return G\nend\n\n# Create a path graph from a list of vertices\nfunction Path{T}(verts::Array{T})\n    G = SimpleGraph{T}()\n    n = length(verts)\n\n    if n==1\n        add!(G,verts[1])\n    end\n    for k = 1:n-1\n        add!(G,verts[k],verts[k+1])\n    end\n    return G\nend\n\n# Create a cycle graph on n vertices\nfunction Cycle(n::Int)\n    if n<3\n        error(\"Cycle requires 3 or more vertices\")\n    end\n    G = Path(n)\n    add!(G,1,n)\n    return G\nend\n\n# Create the wheel graph on n vertices: a cycle on n-1 vertices plus\n# an additional vertex adjacent to all the vertices on the wheel.\n\"\"\"\n`Wheel(n)` creates a wheel graph with `n` vertices. That is, a cycle\nwith `n-1` vertices `1:(n-1)` all adjacent to a common single vertex,\n`n`.\n\"\"\"\nfunction Wheel(n::Int)\n    if n < 4\n        error(\"Wheel graphs must have at least 4 vertices\")\n    end\n    G = Cycle(n-1)\n    for k=1:n-1\n        add!(G,k,n)\n    end\n    return G\nend\n\n# Create a grid graph\n\"\"\"\n`Grid(n,m)` creates an `n`-by-`m` grid graph. For other grids, we\nsuggest `Path(n1)*Path(n2)*Path(n3)` optionally wrapped in\n`relabel`. See also: `Cube`.\n\"\"\"\nfunction Grid(n::Int, m::Int)\n    G = SimpleGraph{Tuple{Int,Int}}()\n\n    # add the vertices\n    for u=1:n\n        for v=1:m\n            add!(G,(u,v))\n        end\n    end\n\n    #horizontal edges\n    for u=1:n\n        for v=1:m-1\n            add!(G,(u,v),(u,v+1))\n        end\n    end\n\n    # vertical edges\n    for v=1:m\n        for u=1:n-1\n            add!(G,(u,v),(u+1,v))\n        end\n    end\n    return G\nend\n\n# Create an Erdos-Renyi random graph\n\"\"\"\n`RandomGraph(n,p=0.5)` creates an Erdos-Renyi random graph with `n`\nvertices and edge probability `p`.\n\"\"\"\nfunction RandomGraph(n::Int, p::Real=0.5)\n    G = IntGraph(n)\n\n    # guess the size of the edge set to preallocate storage\n    m = round(Int,n*n*p)+1\n\n    # generate the edges\n    for v=1:n-1\n        for w=v+1:n\n            if (rand() < p)\n                add!(G,v,w)\n            end\n        end\n    end\n    return G\nend\n\n# Generate a random tree on vertex set 1:n. All n^(n-2) trees are\n# equally likely.\n\n\"\"\"\n`RandomTree(n)` creates a random tree on `n` vertices each with\nprobability `1/n^(n-2)`.\n\"\"\"\nfunction RandomTree(n::Int)\n    if n<0   # but we allow n==0 to give empty graph\n        error(\"Number of vertices cannot be negative\")\n    end\n\n    if n<2\n        return IntGraph(n)\n    end\n\n    code = [ mod(rand(Int),n)+1 for _ in 1:n-2 ]\n    return code_to_tree(code)\nend\n\n# This is a helper function for RandomTree that converts a Prufer code\n# to a tree. No checks are done on the array fed into this function.\nfunction code_to_tree(code::Array{Int,1})\n    n = length(code)+2\n    G = IntGraph(n)\n    degree = ones(Int,n)  # initially all 1s\n\n    #every time a vertex appears in code[], up its degree by 1\n    for c in code\n        degree[c]+=1\n    end\n\n    for u in code\n        for v in 1:n\n            if degree[v]==1\n                add!(G,u,v)\n                degree[u] -= 1\n                degree[v] -= 1\n                break\n            end\n        end\n    end\n\n    last = find(degree)\n    add!(G,last[1],last[2])\n\n    return G\nend\n\n# Create the Cube graph with 2^n vertices\n\"\"\"\n`Cube(n)` creates the `n`-dimensional cube graph. This graph has `2^n`\nvertices named by all possible length-`n` strings of 0s and 1s. Two\nvertices are adjacent iff they differ in exactly one position.\n\"\"\"\nfunction Cube(n::Integer=3)\n    G = StringGraph()\n    for u=0:2^n-1\n        for shift=0:n-1\n            v = (1<<shift) $ u\n            add!(G,bin(u,n), bin(v,n))\n        end\n    end\n    return G\nend\n\n# Create the BuckyBall graph\n\n\"\"\"\n`BuckyBall()` returns the Bucky ball graph.\n\"\"\"\nfunction BuckyBall()\n    G = IntGraph()\n    edges = [(1,3), (1,49), (1,60), (2,4), (2,10), (2,59),\n\t     (3,4), (3,37), (4,18), (5,7), (5,9), (5,13),\n\t     (6,8), (6,10), (6,17), (7,8), (7,21), (8,22),\n\t     (9,10), (9,57), (11,12), (11,13), (11,21), (12,28),\n\t     (12,48), (13,14), (14,47), (14,55), (15,16), (15,17),\n\t     (15,22), (16,26), (16,42), (17,18), (18,41), (19,20),\n\t     (19,21), (19,27), (20,22), (20,25), (23,24), (23,32),\n\t     (23,35), (24,26), (24,39), (25,26), (25,31), (27,28),\n\t     (27,31), (28,30), (29,30), (29,32), (29,36), (30,45),\n\t     (31,32), (33,35), (33,40), (33,51), (34,36), (34,46),\n\t     (34,52), (35,36), (37,38), (37,41), (38,40), (38,53),\n\t     (39,40), (39,42), (41,42), (43,44), (43,47), (43,56),\n\t     (44,46), (44,54), (45,46), (45,48), (47,48), (49,50),\n\t     (49,53), (50,54), (50,58), (51,52), (51,53), (52,54),\n\t     (55,56), (55,57), (56,58), (57,59), (58,60), (59,60),\n\t     ]\n    for e in edges\n        add!(G,e[1],e[2])\n    end\n    return G\nend\n\n# The Kneser graph Kneser(n,k) has C(n,k) vertices that are the\n# k-element subsets of 1:n in which two vertices are adjacent if (as\n# sets) they are disjoint. The Petersen graph is Kneser(5,2).\n\n\"\"\"\n`Kneser(n,m)` creates the Kneser graph whose vertices are all the\n`m`-element subsets of `1:n` in which two vertices are adjacent iff\nthey are disjoint.\n\"\"\"\nfunction Kneser(n::Int,k::Int)\n    A = collect(1:n)\n    vtcs = [Set(v) for v in subsets(A,k)]\n    G = SimpleGraph{Set{Int}}()\n\n    for v in vtcs\n        add!(G,v)\n    end\n\n    n = length(vtcs)\n    for i=1:n-1\n        u = vtcs[i]\n        for j=i+1:n\n            v = vtcs[j]\n            if length(intersect(u,v))==0\n                add!(G,u,v)\n            end\n        end\n    end\n\n    return G\nend\n\n# Create the Petersen graph.\n\"\"\"\n`Petersen()` returns the Petersen graph. The vertices are labeled as\nthe 2-element subsets of `1:5`. Wrap in `relabel` to have vertices\nnamed `1:10`. See also: `Kneser`.\n\"\"\"\n\nPetersen() = Kneser(5,2)\n\n# Create Paley graphs\n\n\"\"\"\n`Paley(p)` creates the Paley graph with `p` vertices named\n`0:(p-1)`. Here `p` must be a prime with `p%4==1`. Vertices `u` and\n`v` are adjacent iff `u-v` is a quadratic residue (perfect square)\nmodulo `p`.\n\"\"\"\nfunction Paley(p::Int)\n    if mod(p,4) != 1 || ~isprime(p)\n        error(\"p must be a prime congruent to 1 mod 4\")\n    end\n\n    # Quadratic residues mod p\n    qrlist = unique( [ mod(k*k,p) for k=1:p ] )\n\n    G = IntGraph()\n    for u = 0:p-1\n        for k in qrlist\n            v = mod(u+k,p)\n            add!(G,u,v)\n        end\n    end\n    return G\nend\n\n# Called by RandomRegular ... one step\nfunction RandomRegularBuilder(n::Int, d::Int)\n    # caller has already checked the values of n,d are legit\n    vlist = randperm(n*d)\n    G = IntGraph(n*d)\n    for v=1:2:n*d\n        add!(G,vlist[v], vlist[v+1])\n    end\n\n    for v = n:-1:1\n        mushlist = collect( d*(v-1)+1 : v*d )\n        for k=d-1:-1:1\n            contract!(G,mushlist[k],mushlist[k+1])\n        end\n    end\n    return relabel(G)\nend\n\n\"\"\"\n`RandomRegular(n,d)` creates a random `d`-regular graph on `n`\nvertices. This can take a while especially if the arguments are\nlarge. Call with an optional third argument to activate verbose\nprogress reports: `RandomRegular(n,p,true)`.\n\"\"\"\nfunction RandomRegular(n::Int, d::Int, verbose::Bool=false)\n    # sanity checks\n    if n<1 || d<1 || (n*d)%2==1\n        error(\"n,d must be positive integers and n*d even\")\n    end\n    if verbose\n        println(\"Trying to build \", d, \"-regular graph on \",\n                n, \" vertices\")\n        count::Int = 0\n    end\n\n    while true\n        if verbose\n            count += 1\n            println(\"Attempt \", count)\n            tic()\n        end\n        g = RandomRegularBuilder(n,d)\n        if verbose\n            toc();\n        end\n        dlist = deg(g)\n        if dlist[1] == dlist[n]\n            if verbose\n                println(\"Success\")\n            end\n            return g\n        end\n        if verbose\n            println(\"Failed; trying again\")\n        end\n    end\nend\n\n\"\"\"\n`Knight(r::Int=8,c::Int=8)` creates a Knight's Moves graph on a\n`r`-by-`c` grid. That is, the vertices of this graph are the squares\nof an `r`-by-`c` chess board. Two vertices are adjacent if a Knight\ncan go from one of these squares to the other in a single move.\n\"\"\"\nfunction Knight(r::Int=8,c::Int=8)\n    vtcs = collect(product(1:r,1:c))\n    G = SimpleGraph{Tuple{Int64,Int64}}()\n    for v in vtcs\n        add!(G,v)\n    end\n\n    for v in vtcs\n        for w in vtcs\n            xv = collect(v)\n            xw = collect(w)\n            z = sort(map(abs,xv - xw))\n            if z==[1,2]\n                add!(G,v,w)\n            end\n        end\n    end\n\n    return G\nend\n", "meta": {"hexsha": "ca9fa138b20def19682d8311f0006bbb3039d039", "size": 10377, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simple_constructors.jl", "max_stars_repo_name": "EliasBcd/SimpleGraphs.jl", "max_stars_repo_head_hexsha": "89fdc4c2151e9841ed2b86ed63fe912485a5ab5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-18T04:15:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-18T04:15:02.000Z", "max_issues_repo_path": "src/simple_constructors.jl", "max_issues_repo_name": "EliasBcd/SimpleGraphs.jl", "max_issues_repo_head_hexsha": "89fdc4c2151e9841ed2b86ed63fe912485a5ab5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simple_constructors.jl", "max_forks_repo_name": "EliasBcd/SimpleGraphs.jl", "max_forks_repo_head_hexsha": "89fdc4c2151e9841ed2b86ed63fe912485a5ab5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5840909091, "max_line_length": 70, "alphanum_fraction": 0.5528572805, "num_tokens": 3350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7574185369657669}}
{"text": "#TODO make it a function on ExplicitODE and Options\n\n\"\"\"\n\nChooses an initial step-size basing on the equation, initial data,\ntime span and the order of the method of integration.\n\n\"\"\"\nfunction dtinit{T,S}(F, y0::Vector{S}, tspan::Vector{T}, reltol, abstol; order = 1)\n    t0 = abs(tspan[1])\n    tstop = abs(tspan[end])\n    tau = max(reltol*norm(y0, Inf), abstol)\n    d0 = norm(y0, Inf)/tau\n    f0 = F(t0, y0)\n    d1 = norm(f0, Inf)/tau\n    if min(d0,d1) < eps(T)^(1/3)\n        dt0 = eps(T)^(1/3)/10\n    else\n        dt0 = (d0/d1)/100\n    end\n    # perform Euler step\n    y1 = similar(y0)\n    for d = 1:length(y1)\n        y1[d] = y0[d]+dt0*f0[d]\n    end\n    f1 = F(t0 + dt0, y1)\n    # estimate second derivative\n    d2 = norm(f1 - f0, Inf)/(tau*dt0)\n    if max(d1, d2) <= 10*eps(T)\n        dt1 = max(eps(T)^(1/3)/10, dt0/10^3)\n    else\n        pow = -(2 + log10(max(d1, d2)))/(order+1)\n        dt1 = 10^pow\n    end\n    return min(100*dt0, dt1, abs(tstop-t0))\nend\n\n# a scalar version of the above\ndtinit(F, y0::Number, args...; kargs...) = dtinit((t,y)->[F(t,y[1])], [y0], args...; kargs...)\n\n\"\"\"\n\nA simple bisection algorithm for finding a root of a solution f(x)=0\nstarting within the range x∈rng, the result is a point x₀ which is\nlocated within the distance eps from the true root of f(x)=0.  For\nthis algorithm to work we need f(rng[1]) to have a different sign then\nf(rng[2]).\n\n\"\"\"\nfunction findroot(f,rng,eps)\n    xl, xr = rng\n    fl, fr = f(xl), f(xr)\n\n    if fl*fr > 0 || xl > xr\n        error(\"Inconsistent bracket\")\n    end\n\n    while xr-xl > eps\n        xm = (xl+xr)/2\n        fm = f(xm)\n\n        if fm*fr > 0\n            xr = xm\n            fr = fm\n        else\n            xl = xm\n            fl = fm\n        end\n    end\n\n    return (xr+xl)/2\nend\n", "meta": {"hexsha": "04e7efc6ee30689fde31e9af6e069d4159a10766", "size": 1759, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/helpers.jl", "max_stars_repo_name": "obiajulu/ODE_pwl_PR.jl", "max_stars_repo_head_hexsha": "03f2b76f3e8a075df4227880000f4244bd4a1ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/helpers.jl", "max_issues_repo_name": "obiajulu/ODE_pwl_PR.jl", "max_issues_repo_head_hexsha": "03f2b76f3e8a075df4227880000f4244bd4a1ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/helpers.jl", "max_forks_repo_name": "obiajulu/ODE_pwl_PR.jl", "max_forks_repo_head_hexsha": "03f2b76f3e8a075df4227880000f4244bd4a1ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.095890411, "max_line_length": 94, "alphanum_fraction": 0.5531552018, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.8615382058759128, "lm_q1q2_score": 0.7574185178697692}}
{"text": "@show [1 2 3; 3 2 1] .+ [2 1 2; 0 2 1]\n@show [1 2 3; 2 1 2] .+ 1\n@show [1 2 3; 2 2 1] .- [1 1 1; 2 1 0]\n@show [1 2 1; 1 2 3] .* [3 2 1; 1 0 1]\n@show [1 2 3; 3 2 1] .* 2\n@show [9 8 6; 3 2 3] ./ [3 1 2; 2 1 2]\n@show [3 2 2; 1 2 3] .^ [1 2 3; 2 1 2]\n", "meta": {"hexsha": "f2abef842ee54c798619fac747d9ede7d5dc0260", "size": 247, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/element-wise-operations.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/element-wise-operations.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/element-wise-operations.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.875, "max_line_length": 38, "alphanum_fraction": 0.4129554656, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7574132170567985}}
{"text": "#=\nAuthor: Shuangchi He / Yulv\nEmail: yulvchi@qq.com\nDate: 2022-02-15 12:32:43\nLastEditors: Shuangchi He\nLastEditTime: 2022-02-25 21:45:58\nDescription: Statistical Analysis for Pearson Correlation and Bland-Altman Agreement\n=#\nusing Polynomials\nusing PyPlot\nusing Statistics\n\n\nfunction Pearson_Correlation_Bland_Altman_Agreement(X, Y)\n    # Pearson Correlation\n    linearfit=fit(X, Y, 1)  # Linear fit.\n    k = linearfit[1]\n    b = linearfit[0]\n\n    scatter(X, Y, label=\"Num: $(length(X))\", color=\"r\", s=8)\n    plot(sort(X), sort(X * k .+ b), color=\"b\", linestyle=\"--\",\n        label=\"linear_fit: y = $(round(k, digits=5)) x + $(round(b, digits=5))\\npearson coefficient: $(round(cor(X, Y), digits=5))\")\n    plot([findmin([findmin(X)[1], findmin(Y)[1]])[1], findmax([findmax(X)[1], findmax(Y)[1]])[1]], [findmin([findmin(X)[1], findmin(Y)[1]])[1], findmax([findmax(X)[1], findmax(Y)[1]])[1]],\n        color=\"k\", linestyle=\"--\", label=\"Equal Line\")\n\n    xlabel(\"Measurement_predict (mm)\")\n    ylabel(\"Measurement_GT (mm)\")\n    title(\"Pearson Correlation\")\n    legend(loc=0)\n    savefig(\"Measurement_Pearson_Correlation.png\")\n    close()\n\n    # Bland-Altman Agreement\n    data_mean = (X + Y) / 2.\n    data_diff = X - Y\n    mean_diff = mean(data_diff)\n    std_diff = std(data_diff)  # Julia std defaults to correcting for bias in sample variance by dividing by N-1.\n\n    linearfit2=fit(data_mean, data_diff, 1)  # Linear fit.\n    k2 = linearfit2[1]\n    b2 = linearfit2[0]\n\n    scatter(data_mean, data_diff, label=\"Diff num: $(length(data_mean))\", color=\"r\", s=8)\n    plot(sort(data_mean), sort(mean_diff * ones(length(data_mean))), color=\"k\", linestyle=\"--\",\n        label=\"Mean_Diff: $(round(mean_diff, digits=5))\")\n    plot(sort(data_mean), sort((mean_diff .+ 1.96 * std_diff) * ones(length(data_mean))), color=\"b\", linestyle=\"--\",\n        label=\"Mean_Diff + 1.96 Std_Diff: $(round(mean_diff + 1.96 * std_diff, digits=5))\")\n    plot(sort(data_mean), sort((mean_diff .- 1.96 * std_diff) * ones(length(data_mean))), color=\"b\", linestyle=\"-.\",\n        label=\"Mean_Diff - 1.96 Std_Diff: $(round(mean_diff - 1.96 * std_diff, digits=5))\")\n    plot(sort(data_mean), sort(data_mean * k2 .+ b2), color=\"y\", linestyle=\"--\",\n        label=\"linear_fit: y = $(round(k2, digits=5)) x + $(round(b2, digits=5))\")\n\n    xlabel(\"Mean of Measurement_predict and Measurement_GT (mm)\")\n    ylabel(\"Diff between Measurement_predict and Measurement_GT (mm)\")\n    title(\"Bland-Altman Agreement\")\n    legend(loc=0)\n    savefig(\"Measurement_Bland-Altman_Agreement.png\")\nend\n\n\nX = [0.125, 0.95, 0.55, 0.60, 0.78, 0.46, 0.88, 0.50, 0.93, 0.35, 0.975, 0.725, 0.285, 0.166, 0.666, 0.888, 0.233]\nY = [0.127, 0.97, 0.53, 0.57, 0.72, 0.49, 0.91, 0.52, 0.90, 0.37, 0.982, 0.718, 0.277, 0.175, 0.666, 0.88, 0.2333]\nPearson_Correlation_Bland_Altman_Agreement(X, Y)\n", "meta": {"hexsha": "b566c2977e39256f858a885c3a47353275d9e13f", "size": 2826, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/Correlation_Agreement.jl", "max_stars_repo_name": "Yulv-git/Correlation_and_Agreement_Analysis", "max_stars_repo_head_hexsha": "4f828a07a93604646ab4e2703937ad5b6db19a34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-11T15:40:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T15:40:33.000Z", "max_issues_repo_path": "Julia/Correlation_Agreement.jl", "max_issues_repo_name": "Yulv-git/Correlation_and_Agreement_Analysis", "max_issues_repo_head_hexsha": "4f828a07a93604646ab4e2703937ad5b6db19a34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/Correlation_Agreement.jl", "max_forks_repo_name": "Yulv-git/Correlation_and_Agreement_Analysis", "max_forks_repo_head_hexsha": "4f828a07a93604646ab4e2703937ad5b6db19a34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.15625, "max_line_length": 188, "alphanum_fraction": 0.6464968153, "num_tokens": 978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7574132137112405}}
{"text": "module problem131\n  \ndescription = \"\"\"\nPrime cube partnership\n\nThere are some prime values, p, for which there exists a positive integer, n, such that the expression n^3 + n^2 * p is a perfect cube.\nFor example, when p = 19, 8^3 + 8^2 × 19 = 12^3.\nWhat is perhaps most surprising is that for each prime with this property the value of n is unique, and there are only four such primes below one-hundred.\n\nHow many primes below one million have this remarkable property?\n\"\"\"\n\n# By exhaustive search, I found the first few primes are 7, 19, 37, 61\n# These are known as Cuban primes: primes of the form n^3 - (n-1)^3\n#\n# Insight after reading solutions from the ProjectEuler forums:\n#\n# n^3 + p * n^2 = k^3\n# n^3 * (p/n + 1) = k^3\n# n^3 * ((p+n)/n) = k^3\n# n * cuberoot((p+n)/n) = k\n# n * cuberoot(p+n) / cuberoot(n) = k\n# For the cuberoot expressions to have integer results, p+n and n must be cubes.\n# let n = x^3, p+n = y^3\n# p = y^3 - x^3\n# p = (y - x)(y^2 + xy + x^2)\n# But p is required to be prime, so (y-x) must be 1 - otherwise (y-x) would be a factor of p.\n# Therefore, p is the difference of consecutive cubes:\n# p = y^3 - (y-1)^3\nfunction cubans(n = 1000000)\n  c = 0\n  for y = 2:Inf\n    p = y^3 - (y-1)^3\n    if p > n \n      return c \n    elseif isprime(p) \n      c += 1 \n    end\n  end\nend\n\nusing Base.Test\n@test cubans(100) == 4\n                                                                                                                                                                                                                                                             \nend", "meta": {"hexsha": "eca5f568fe896aef1343012c14e261d9c42ad039", "size": 1595, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem131.jl", "max_stars_repo_name": "mbuhot/mbuhot-euler-solutions", "max_stars_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-12-18T13:25:41.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-18T13:25:41.000Z", "max_issues_repo_path": "julia/problem131.jl", "max_issues_repo_name": "mbuhot/mbuhot-euler-solutions", "max_issues_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/problem131.jl", "max_forks_repo_name": "mbuhot/mbuhot-euler-solutions", "max_forks_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4444444444, "max_line_length": 253, "alphanum_fraction": 0.5373040752, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.757381938216393}}
{"text": "module BestApproximation\n\nexport best_approx\n\n@doc raw\"\"\"\n```julia\nbest_approx(n::Number, R::AbstractRange)\nbest_approx(n::Number, R_max::Integer)\n```\n\nFor a given number ``n``, given a range ``R``, finds the \"nicest\" solution of ``m`` such that\n\n```math\nr^m \\approx n \\text{ for } r \\in R.\n```\n\nReturns `(r, m)` as a tuple.\n\nGiven an integer ``R_{\\text{max}}`` it will assume the range between ``R = \\left\\lbrack 1, R_{\\text{max}}\\right\\rbrack``.\n\"\"\"\nfunction best_approx(n::Number, R::AbstractRange)\n    n, res = big(n), (0, 0)\n    for i in R\n        j = round(Integer, log(i, n))\n        difference = (n - big(i)^(j))\n        if (difference > 0) && (difference < (n - big(first(res))^(last(res))))\n            res = (i, j)\n        end\n    end\n    \n    return res\nend\nbest_approx(n::Number, R_max::Integer) = best_approx(n, 1:R_max)\n\n@doc raw\"\"\"\n```julia\nbest_approx(n::Number, I::AbstractRange, J::AbstractRange)\nbest_approx(n::Number, I_max::Integer, J::Integer)\n```\n\nFor a given number ``n``, given two ranges ``I`` and ``J``, finds the nicest solution such that\n\n```math\ni^j \\approx n \\text{ for } i \\in I, j \\in j.\n```\n\nReturns `(i, j)` as a tuple.\n\nGiven integers ``I_{\\text{max}}`` and ``J_{\\text{max}}`` it will assume the ranges between ``I =  \\left\\lbrack 1, I_{\\text{max}}\\right\\rbrack`` and ``J =  \\left\\lbrack 1, J_{\\text{max}}\\right\\rbrack``.\n\n!!! note\n\n    This is a much slower variant than the other method for `best_approx`.  It is recommended that you use the \"cleverer\" method unless you need to constrict the exponent.\n\"\"\"\nfunction best_approx(n::Number, I::AbstractRange, J::AbstractRange)\n    n, res = big(n), (0, 0)\n    for i in I, j in J\n        difference = (n - big(i)^(j))\n        if (difference > 0) && (difference < (n - big(first(res))^(last(res))))\n            res = (i, j)\n        end\n    end\n    \n    return res\nend\nbest_approx(n::Number, I_max::Integer, J_max::Integer) = best_approx(n, 1:I_max, 1:J_max)\n\nend\n", "meta": {"hexsha": "a79162e47c40acd05859b7c9f1536738f427a901", "size": 1947, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BestApproximation.jl", "max_stars_repo_name": "jakewilliami/BestApproximation", "max_stars_repo_head_hexsha": "6ab0c6d79ef3d0524957659450ef5bf6c939bf99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-12T22:47:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T21:29:01.000Z", "max_issues_repo_path": "src/BestApproximation.jl", "max_issues_repo_name": "jakewilliami/BestApproximation", "max_issues_repo_head_hexsha": "6ab0c6d79ef3d0524957659450ef5bf6c939bf99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-15T22:45:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-15T22:45:38.000Z", "max_forks_repo_path": "src/BestApproximation.jl", "max_forks_repo_name": "jakewilliami/BestApproximation", "max_forks_repo_head_hexsha": "6ab0c6d79ef3d0524957659450ef5bf6c939bf99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2173913043, "max_line_length": 201, "alphanum_fraction": 0.6147919877, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7573819304225087}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 60941eaa-1aea-11eb-1277-97b991548781\nbegin \n    using PlutoUI,GridVisualize,SimplexGridFactory,Triangulate,ExtendableGrids,VoronoiFVM,PlutoVista,PlutoUI,PyPlot\nend\n\n# ╔═╡ de468cb9-b34d-4d2e-b911-9b93920caca1\nmd\"\"\"\n# Flux reconstruction and visualization for the Laplace operator\n\"\"\"\n\n# ╔═╡ 928a70c5-4706-40a1-9387-abcb71c09443\n\"\"\"\nDefine a \"Swiss cheese domain\" with punched-out holes, where each hole boundary corresponds to a different boundary condition.\n\"\"\"\nfunction swiss_cheese_2d()\n\n    function circlehole!(builder, center, radius; n=20)\n        points=[point!(builder, center[1]+radius*sin(t),center[2]+radius*cos(t)) for t in range(0,2π,length=n)]\n        for i=1:n-1\n            facet!(builder,points[i],points[i+1])\n        end\n        facet!(builder,points[end],points[1])\n        holepoint!(builder,center)\n    end\n\n\n    builder=SimplexGridBuilder(Generator=Triangulate)\n    cellregion!(builder,1)\n    maxvolume!(builder,0.1)\n    regionpoint!(builder,0.1,0.1)\n\n    \n    p1=point!(builder,0,0)\n    p2=point!(builder,10,0)\n    p3=point!(builder,10,10)\n    p4=point!(builder,0,10)\n    \n    facetregion!(builder,1)\n    facet!(builder,p1,p2)\n    facet!(builder,p2,p3)\n    facet!(builder,p3,p4)\n    facet!(builder,p4,p1)\n\n    holes=[1.0 2.0;\n           8.0 9.0;\n           2.0 8.0;\n  \t\t   8.0 4.0;\n           9.0 1.0;\n           3.0 4.0;\n           4.0 6.0;\n           7.0 9.0;\n           4.0 7.0;\n           7.0 5.0;\n           2.0 1.0;\n           4.0 1.0;\n           4.0 8.0;\n           3.0 6.0;\n           4.0 9.0;\n           6.0 9.0;\n           3.0 5.0;\n           1.0 4.0]'\n\n    radii=[0.15, 0.15, 0.1, 0.35, 0.2, 0.3, 0.1, 0.4, 0.1, 0.4,  0.2, 0.2, 0.2, 0.35, 0.15, 0.25, 0.15, 0.25]\n\n    for i=1:length(radii)\n        facetregion!(builder,i+1)\n        circlehole!(builder,holes[:,i], radii[i])\n    end\n\n    simplexgrid(builder)\nend\n\n# ╔═╡ 49f425a4-455c-40f5-b939-da704032cb88\nmd\"\"\"\nGenerate & plot grid\n\"\"\"\n\n# ╔═╡ bc304085-69c3-4974-beb4-6f2b981ac0f1\ngrid=swiss_cheese_2d()\n\n# ╔═╡ ad0367e6-7308-46bc-a7ff-9c17dcfe470d\ngridplot(grid,Plotter=PlutoVista)\n\n# ╔═╡ 236d6cd5-c190-49c7-98fe-021fae224455\n\"\"\"\nSimple flux function for Laplace operator \n\"\"\"\nflux(y,u,edge)= y[1]=u[1,1]-u[1,2]\n\n# ╔═╡ f4ebe6ad-4e04-4f33-9a66-6bec977adf4d\nmd\"\"\"\nDefine a finite volume system with Dirichlet boundary conditions at some of the holes\n\"\"\"\n\n# ╔═╡ 934a98f1-9734-45bc-848e-4d4d8ad80e4e\nphysics=VoronoiFVM.Physics(flux=flux)\n\n# ╔═╡ f3af20fb-c3cc-41af-9782-d40adf2371f7\nsystem=VoronoiFVM.System(grid,physics)\n\n# ╔═╡ 50ea0a7e-97e0-428d-b4ec-6bd4d7aef31f\nenable_species!(system,1,[1])\n\n# ╔═╡ 49d3c96b-f6b4-4581-8600-8aaf50bb07fc\nboundary_dirichlet!(system,1,2,10.0)\n\n# ╔═╡ fa5200ff-713e-48fb-b452-c6ee96935cfc\nboundary_dirichlet!(system,1,3,0.0)\n\n# ╔═╡ 6b09f75a-521b-40d9-9636-155e62ab0cac\nmd\"\"\"\nAt hole #11, the value will be bound to a slider defined below\n\"\"\"\n\n# ╔═╡ d86c43f3-ec2f-4fae-88d2-1068603e7044\nmd\"\"\"\nSolve, and trigger solution upon boundary value change\n\"\"\"\n\n# ╔═╡ 41bd1230-c87c-47b0-8e58-67ad55609fd3\nmd\"\"\"\nReconstruct the node flux. It is a ``d\\times n_{spec}\\times n_{nodes}`` tensor.\n`nf[:,ispec,:]` then is a vector function representing the flux density of species `ispec` in each node of the domain. This readily can be fed into `GridVisualize.vectorplot`.\n\"\"\"\n\n# ╔═╡ 17be52fb-f55b-4b3d-85e5-33f36134046b\nvis=GridVisualizer(Plotter=PlutoVista,dim=2,resolution=(400,400));vis\n\n# ╔═╡ 03f582ec-4e95-4ca4-8482-9c797027810d\nmd\"\"\"\n``v_{11}:`` $(@bind  val11 Slider(0:0.1:10,default=5,show_value=true))\n\"\"\"\n\n# ╔═╡ e8ae2b22-ac60-449b-952f-d2c55852677c\nboundary_dirichlet!(system,1,11,val11)\n\n# ╔═╡ 27efdcac-8ee4-47e4-905d-8d8c7313ddd1\nval11; sol=solve(unknowns(system,inival=0),system)\n\n# ╔═╡ 41f427c1-b6ad-46d4-9151-1d872b4efeb6\nnf=nodeflux(system,sol)\n\n# ╔═╡ c9b9fdb1-5734-430f-949a-6e6126d2f091\n\"\"\"\nJoint plot of solution and nodal flux of the solution\n\"\"\"\nfunction myplot(vis)\n\tscalarplot!(vis,grid,sol[1,:],levels=9,colormap=:summer,clear=true)\n\tvectorplot!(vis,grid,nf[:,1,:],clear=false,spacing=0.5,vscale=1.5)\n\treveal(vis)\nend\n\n# ╔═╡ 531edb71-6d32-4231-b117-5e36416d2fb1\nmyplot(vis)\n\n# ╔═╡ e0b92e00-dd0b-448b-baae-5cd4e0a2059a\nmd\"\"\"\nPlot with PyPlot: $(@bind use_pyplot CheckBox(default=false))\n\"\"\"\n\n# ╔═╡ 1495eb67-12ec-4662-b0e7-049ffef569c0\nif use_pyplot\n\tpyvis=GridVisualizer(Plotter=PyPlot,resolution=(400,400))\n\tmyplot(pyvis)\nend\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nExtendableGrids = \"cfc395e8-590f-11e8-1f13-43a2532b2fa8\"\nGridVisualize = \"5eed8a63-0fb0-45eb-886d-8d5a387d12b8\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nPlutoVista = \"646e1f28-b900-46d7-9d87-d554eb38a413\"\nPyPlot = \"d330b81b-6aea-500a-939a-2ce795aea3ee\"\nSimplexGridFactory = \"57bfcd06-606e-45d6-baf4-4ba06da0efd5\"\nTriangulate = \"f7e6ffb2-c36d-4f8f-a77e-16e897189344\"\nVoronoiFVM = \"82b139dc-5afc-11e9-35da-9b9bdfd336f3\"\n\n[compat]\nExtendableGrids = \"~0.8.3\"\nGridVisualize = \"~0.3.5\"\nPlutoUI = \"~0.7.16\"\nPlutoVista = \"~0.8.2\"\nPyPlot = \"~2.10.0\"\nSimplexGridFactory = \"~0.5.8\"\nTriangulate = \"~2.1.0\"\nVoronoiFVM = \"~0.13.1\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\njulia_version = \"1.7.0-rc1\"\nmanifest_format = \"2.0\"\n\n[[deps.AbstractTrees]]\ngit-tree-sha1 = \"03e0550477d86222521d254b741d470ba17ea0b5\"\nuuid = \"1520ce14-60c1-5f80-bbc7-55ef81b5835c\"\nversion = \"0.3.4\"\n\n[[deps.Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[deps.ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[deps.ArnoldiMethod]]\ndeps = [\"LinearAlgebra\", \"Random\", \"StaticArrays\"]\ngit-tree-sha1 = \"f87e559f87a45bece9c9ed97458d3afe98b1ebb9\"\nuuid = \"ec485272-7323-5ecc-a04f-4719b315124d\"\nversion = \"0.1.0\"\n\n[[deps.ArrayInterface]]\ndeps = [\"Compat\", \"IfElse\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"Static\"]\ngit-tree-sha1 = \"b8d49c34c3da35f220e7295659cd0bab8e739fed\"\nuuid = \"4fba245c-0d91-5ea0-9b3e-6abc04ee57a9\"\nversion = \"3.1.33\"\n\n[[deps.Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[deps.Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[deps.Cassette]]\ngit-tree-sha1 = \"6ce3cd755d4130d43bab24ea5181e77b89b51839\"\nuuid = \"7057c7e9-c182-5462-911a-8362d720325c\"\nversion = \"0.3.9\"\n\n[[deps.ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"2f294fae04aa5069a67964a3366e151e09ea7c09\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.9.0\"\n\n[[deps.ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"a851fec56cb73cfdf43762999ec72eff5b86882a\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.15.0\"\n\n[[deps.ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[deps.Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[deps.CommonSubexpressions]]\ndeps = [\"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"7b8a93dba8af7e3b42fecabf646260105ac373f7\"\nuuid = \"bbf7d656-a473-5ed7-a52c-81e309532950\"\nversion = \"0.3.0\"\n\n[[deps.Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"31d0151f5716b655421d9d75b7fa74cc4e744df2\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.39.0\"\n\n[[deps.CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[deps.Conda]]\ndeps = [\"JSON\", \"VersionParsing\"]\ngit-tree-sha1 = \"299304989a5e6473d985212c28928899c74e9421\"\nuuid = \"8f4d0f93-b110-5947-807f-2305c1781a2d\"\nversion = \"1.5.2\"\n\n[[deps.DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[deps.DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\n\n[[deps.DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[deps.Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[deps.DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[deps.DiffResults]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"c18e98cba888c6c25d1c3b048e4b3380ca956805\"\nuuid = \"163ba53b-c6d8-5494-b064-1a9d43ac40c5\"\nversion = \"1.0.3\"\n\n[[deps.DiffRules]]\ndeps = [\"NaNMath\", \"Random\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"7220bc21c33e990c14f4a9a319b1d242ebc5b269\"\nuuid = \"b552c78f-8df3-52c6-915a-8e097449b14b\"\nversion = \"1.3.1\"\n\n[[deps.Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[deps.DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"a32185f5428d3986f47c2ab78b1f216d5e6cc96f\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.5\"\n\n[[deps.Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[deps.EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[deps.ElasticArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"a0fcc1bb3c9ceaf07e1d0529c9806ce94be6adf9\"\nuuid = \"fdbdab4c-e67f-52f5-8c3f-e7b388dad3d4\"\nversion = \"1.2.9\"\n\n[[deps.ExtendableGrids]]\ndeps = [\"AbstractTrees\", \"Dates\", \"DocStringExtensions\", \"ElasticArrays\", \"InteractiveUtils\", \"LinearAlgebra\", \"Printf\", \"Random\", \"SparseArrays\", \"Test\"]\ngit-tree-sha1 = \"85dbe70afc7153ad510577f158214b45be22593b\"\nuuid = \"cfc395e8-590f-11e8-1f13-43a2532b2fa8\"\nversion = \"0.8.3\"\n\n[[deps.ExtendableSparse]]\ndeps = [\"DocStringExtensions\", \"LinearAlgebra\", \"Printf\", \"Requires\", \"SparseArrays\", \"SuiteSparse\", \"Test\"]\ngit-tree-sha1 = \"0341e41e45e6c5e46be89c33543082a0a867707c\"\nuuid = \"95c220a8-a1cf-11e9-0c77-dbfce5f500b3\"\nversion = \"0.6.5\"\n\n[[deps.FileIO]]\ndeps = [\"Pkg\", \"Requires\", \"UUIDs\"]\ngit-tree-sha1 = \"3c041d2ac0a52a12a27af2782b34900d9c3ee68c\"\nuuid = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nversion = \"1.11.1\"\n\n[[deps.FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"8756f9935b7ccc9064c6eef0bff0ad643df733a3\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.12.7\"\n\n[[deps.FiniteDiff]]\ndeps = [\"ArrayInterface\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"StaticArrays\"]\ngit-tree-sha1 = \"8b3c09b56acaf3c0e581c66638b85c8650ee9dca\"\nuuid = \"6a86dc24-6348-571c-b903-95158fe2bd41\"\nversion = \"2.8.1\"\n\n[[deps.FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[deps.ForwardDiff]]\ndeps = [\"CommonSubexpressions\", \"DiffResults\", \"DiffRules\", \"LinearAlgebra\", \"NaNMath\", \"Preferences\", \"Printf\", \"Random\", \"SpecialFunctions\", \"StaticArrays\"]\ngit-tree-sha1 = \"63777916efbcb0ab6173d09a658fb7f2783de485\"\nuuid = \"f6369f11-7733-5829-9624-2563aa707210\"\nversion = \"0.10.21\"\n\n[[deps.GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[deps.GridVisualize]]\ndeps = [\"ColorSchemes\", \"Colors\", \"DocStringExtensions\", \"ElasticArrays\", \"ExtendableGrids\", \"GeometryBasics\", \"LinearAlgebra\", \"Observables\", \"OrderedCollections\", \"PkgVersion\", \"Printf\", \"Requires\", \"StaticArrays\"]\ngit-tree-sha1 = \"063aa184cec6aff22f7c2f6a498075a93b5fa304\"\nuuid = \"5eed8a63-0fb0-45eb-886d-8d5a387d12b8\"\nversion = \"0.3.5\"\n\n[[deps.Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[deps.HypertextLiteral]]\ngit-tree-sha1 = \"f6532909bf3d40b308a0f360b6a0e626c0e263a8\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.1\"\n\n[[deps.IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[deps.IfElse]]\ngit-tree-sha1 = \"28e837ff3e7a6c3cdb252ce49fb412c8eb3caeef\"\nuuid = \"615f187c-cbe4-4ef1-ba3b-2fcf58d6d173\"\nversion = \"0.1.0\"\n\n[[deps.Inflate]]\ngit-tree-sha1 = \"f5fc07d4e706b84f72d54eedcc1c13d92fb0871c\"\nuuid = \"d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9\"\nversion = \"0.1.2\"\n\n[[deps.InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[deps.IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[deps.IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[deps.IterativeSolvers]]\ndeps = [\"LinearAlgebra\", \"Printf\", \"Random\", \"RecipesBase\", \"SparseArrays\"]\ngit-tree-sha1 = \"1a8c6237e78b714e901e406c096fc8a65528af7d\"\nuuid = \"42fd0dbc-a981-5370-80f2-aaf504508153\"\nversion = \"0.9.1\"\n\n[[deps.IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[deps.JLD2]]\ndeps = [\"DataStructures\", \"FileIO\", \"MacroTools\", \"Mmap\", \"Pkg\", \"Printf\", \"Reexport\", \"TranscodingStreams\", \"UUIDs\"]\ngit-tree-sha1 = \"46b7834ec8165c541b0b5d1c8ba63ec940723ffb\"\nuuid = \"033835bb-8acc-5ee8-8aae-3f567f8a3819\"\nversion = \"0.4.15\"\n\n[[deps.JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[deps.JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[deps.LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[deps.LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[deps.LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[deps.LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[deps.LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[deps.Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[deps.LightGraphs]]\ndeps = [\"ArnoldiMethod\", \"DataStructures\", \"Distributed\", \"Inflate\", \"LinearAlgebra\", \"Random\", \"SharedArrays\", \"SimpleTraits\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"432428df5f360964040ed60418dd5601ecd240b6\"\nuuid = \"093fc24a-ae57-5d10-9952-331d41423f4d\"\nversion = \"1.3.5\"\n\n[[deps.LinearAlgebra]]\ndeps = [\"Libdl\", \"libblastrampoline_jll\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[deps.LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"DocStringExtensions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"34dc30f868e368f8a17b728a1238f3fcda43931a\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.3\"\n\n[[deps.Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[deps.MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"5a5bc6bf062f0f95e62d0fe0a2d99699fed82dd9\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.8\"\n\n[[deps.Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[deps.MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[deps.Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[deps.MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[deps.NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[deps.NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[deps.Observables]]\ngit-tree-sha1 = \"fe29afdef3d0c4a8286128d4e45cc50621b1e43d\"\nuuid = \"510215fc-4207-5dde-b226-833fc4488ee2\"\nversion = \"0.4.0\"\n\n[[deps.OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[deps.OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[deps.OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[deps.OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[deps.Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"98f59ff3639b3d9485a03a72f3ab35bab9465720\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.6\"\n\n[[deps.Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[deps.PkgVersion]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"a7a7e1a88853564e551e4eba8650f8c38df79b37\"\nuuid = \"eebad327-c553-4316-9ea0-9fa01ccd7688\"\nversion = \"0.1.1\"\n\n[[deps.PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"4c8a7d080daca18545c56f1cac28710c362478f3\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.16\"\n\n[[deps.PlutoVista]]\ndeps = [\"ColorSchemes\", \"Colors\", \"DocStringExtensions\", \"GridVisualize\", \"UUIDs\"]\ngit-tree-sha1 = \"ce59550b517ab41b5e687174f93f57c76f872b6d\"\nuuid = \"646e1f28-b900-46d7-9d87-d554eb38a413\"\nversion = \"0.8.2\"\n\n[[deps.Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[deps.Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[deps.PyCall]]\ndeps = [\"Conda\", \"Dates\", \"Libdl\", \"LinearAlgebra\", \"MacroTools\", \"Serialization\", \"VersionParsing\"]\ngit-tree-sha1 = \"169bb8ea6b1b143c5cf57df6d34d022a7b60c6db\"\nuuid = \"438e738f-606a-5dbb-bf0a-cddfbfd45ab0\"\nversion = \"1.92.3\"\n\n[[deps.PyPlot]]\ndeps = [\"Colors\", \"LaTeXStrings\", \"PyCall\", \"Sockets\", \"Test\", \"VersionParsing\"]\ngit-tree-sha1 = \"14c1b795b9d764e1784713941e787e1384268103\"\nuuid = \"d330b81b-6aea-500a-939a-2ce795aea3ee\"\nversion = \"2.10.0\"\n\n[[deps.REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[deps.Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[deps.RecipesBase]]\ngit-tree-sha1 = \"44a75aa7a527910ee3d1751d1f0e4148698add9e\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.2\"\n\n[[deps.RecursiveArrayTools]]\ndeps = [\"ArrayInterface\", \"ChainRulesCore\", \"DocStringExtensions\", \"FillArrays\", \"LinearAlgebra\", \"RecipesBase\", \"Requires\", \"StaticArrays\", \"Statistics\", \"ZygoteRules\"]\ngit-tree-sha1 = \"ff7495c78a192ff7d59531d9f14db300c847a4bc\"\nuuid = \"731186ca-8d62-57ce-b412-fbd966d074cd\"\nversion = \"2.19.1\"\n\n[[deps.Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[deps.Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[deps.SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[deps.Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[deps.SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[deps.SimpleTraits]]\ndeps = [\"InteractiveUtils\", \"MacroTools\"]\ngit-tree-sha1 = \"5d7e3f4e11935503d3ecaf7186eac40602e7d231\"\nuuid = \"699a6c99-e7fa-54fc-8d76-47d257e15c1d\"\nversion = \"0.9.4\"\n\n[[deps.SimplexGridFactory]]\ndeps = [\"DocStringExtensions\", \"ElasticArrays\", \"ExtendableGrids\", \"GridVisualize\", \"LinearAlgebra\", \"Printf\", \"Test\"]\ngit-tree-sha1 = \"e55646af1d0f68763eaca28f666d381982eeb65f\"\nuuid = \"57bfcd06-606e-45d6-baf4-4ba06da0efd5\"\nversion = \"0.5.8\"\n\n[[deps.Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[deps.SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[deps.SparseDiffTools]]\ndeps = [\"Adapt\", \"ArrayInterface\", \"Compat\", \"DataStructures\", \"FiniteDiff\", \"ForwardDiff\", \"LightGraphs\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"StaticArrays\", \"VertexSafeGraphs\"]\ngit-tree-sha1 = \"36a4d27a02af48a1eafd2baff58b32deeeb68926\"\nuuid = \"47a9eef4-7e08-11e9-0b38-333d64bd3804\"\nversion = \"1.16.5\"\n\n[[deps.SparsityDetection]]\ndeps = [\"Cassette\", \"DocStringExtensions\", \"LinearAlgebra\", \"SparseArrays\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"9e182a311d169cb9fe0c6501aa252983215fe692\"\nuuid = \"684fba80-ace3-11e9-3d08-3bc7ed6f96df\"\nversion = \"0.3.4\"\n\n[[deps.SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"793793f1df98e3d7d554b65a107e9c9a6399a6ed\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.7.0\"\n\n[[deps.Static]]\ndeps = [\"IfElse\"]\ngit-tree-sha1 = \"a8f30abc7c64a39d389680b74e749cf33f872a70\"\nuuid = \"aedffcd0-7271-4cad-89d0-dc628f76c6d3\"\nversion = \"0.3.3\"\n\n[[deps.StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3c76dde64d03699e074ac02eb2e8ba8254d428da\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.13\"\n\n[[deps.Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[deps.StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.3\"\n\n[[deps.SuiteSparse]]\ndeps = [\"Libdl\", \"LinearAlgebra\", \"Serialization\", \"SparseArrays\"]\nuuid = \"4607b0f0-06f3-5cda-b6b1-a6196a1729e9\"\n\n[[deps.TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[deps.TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[deps.Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"fed34d0e71b91734bf0a7e10eb1bb05296ddbcd0\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.6.0\"\n\n[[deps.Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[deps.Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[deps.TranscodingStreams]]\ndeps = [\"Random\", \"Test\"]\ngit-tree-sha1 = \"216b95ea110b5972db65aa90f88d8d89dcb8851c\"\nuuid = \"3bb67fe8-82b1-5028-8e26-92a6c54297fa\"\nversion = \"0.9.6\"\n\n[[deps.Triangle_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"bfdd9ef1004eb9d407af935a6f36a4e0af711369\"\nuuid = \"5639c1d2-226c-5e70-8d55-b3095415a16a\"\nversion = \"1.6.1+0\"\n\n[[deps.Triangulate]]\ndeps = [\"DocStringExtensions\", \"Libdl\", \"Printf\", \"Test\", \"Triangle_jll\"]\ngit-tree-sha1 = \"2b4f716b192c0c615d96d541ee029e85666388cb\"\nuuid = \"f7e6ffb2-c36d-4f8f-a77e-16e897189344\"\nversion = \"2.1.0\"\n\n[[deps.UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[deps.Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[deps.VersionParsing]]\ngit-tree-sha1 = \"80229be1f670524750d905f8fc8148e5a8c4537f\"\nuuid = \"81def892-9a0e-5fdd-b105-ffc91e053289\"\nversion = \"1.2.0\"\n\n[[deps.VertexSafeGraphs]]\ndeps = [\"LightGraphs\"]\ngit-tree-sha1 = \"b9b450c99a3ca1cc1c6836f560d8d887bcbe356e\"\nuuid = \"19fa3120-7c27-5ec5-8db8-b0b0aa330d6f\"\nversion = \"0.1.2\"\n\n[[deps.VoronoiFVM]]\ndeps = [\"DiffResults\", \"DocStringExtensions\", \"ExtendableGrids\", \"ExtendableSparse\", \"ForwardDiff\", \"GridVisualize\", \"IterativeSolvers\", \"JLD2\", \"LinearAlgebra\", \"Printf\", \"RecursiveArrayTools\", \"SparseArrays\", \"SparseDiffTools\", \"SparsityDetection\", \"StaticArrays\", \"SuiteSparse\", \"Test\"]\ngit-tree-sha1 = \"db381645bec1d798c560fe415593663d4a2194ac\"\nuuid = \"82b139dc-5afc-11e9-35da-9b9bdfd336f3\"\nversion = \"0.13.1\"\n\n[[deps.Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[deps.ZygoteRules]]\ndeps = [\"MacroTools\"]\ngit-tree-sha1 = \"8c1a8e4dfacb1fd631745552c8db35d0deb09ea0\"\nuuid = \"700de1a5-db45-46bc-99cf-38207098b444\"\nversion = \"0.2.2\"\n\n[[deps.libblastrampoline_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"OpenBLAS_jll\"]\nuuid = \"8e850b90-86db-534c-a0d3-1478176c7d93\"\n\n[[deps.nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[deps.p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─de468cb9-b34d-4d2e-b911-9b93920caca1\n# ╠═60941eaa-1aea-11eb-1277-97b991548781\n# ╠═928a70c5-4706-40a1-9387-abcb71c09443\n# ╟─49f425a4-455c-40f5-b939-da704032cb88\n# ╠═bc304085-69c3-4974-beb4-6f2b981ac0f1\n# ╠═ad0367e6-7308-46bc-a7ff-9c17dcfe470d\n# ╠═236d6cd5-c190-49c7-98fe-021fae224455\n# ╟─f4ebe6ad-4e04-4f33-9a66-6bec977adf4d\n# ╠═934a98f1-9734-45bc-848e-4d4d8ad80e4e\n# ╠═f3af20fb-c3cc-41af-9782-d40adf2371f7\n# ╠═50ea0a7e-97e0-428d-b4ec-6bd4d7aef31f\n# ╠═49d3c96b-f6b4-4581-8600-8aaf50bb07fc\n# ╠═fa5200ff-713e-48fb-b452-c6ee96935cfc\n# ╟─6b09f75a-521b-40d9-9636-155e62ab0cac\n# ╠═e8ae2b22-ac60-449b-952f-d2c55852677c\n# ╟─d86c43f3-ec2f-4fae-88d2-1068603e7044\n# ╠═27efdcac-8ee4-47e4-905d-8d8c7313ddd1\n# ╟─41bd1230-c87c-47b0-8e58-67ad55609fd3\n# ╠═41f427c1-b6ad-46d4-9151-1d872b4efeb6\n# ╠═c9b9fdb1-5734-430f-949a-6e6126d2f091\n# ╠═17be52fb-f55b-4b3d-85e5-33f36134046b\n# ╟─03f582ec-4e95-4ca4-8482-9c797027810d\n# ╠═531edb71-6d32-4231-b117-5e36416d2fb1\n# ╟─e0b92e00-dd0b-448b-baae-5cd4e0a2059a\n# ╠═1495eb67-12ec-4662-b0e7-049ffef569c0\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "d136959b7340e4153442f78232abd554a548fb9e", "size": 26792, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "pluto-examples/vectorplot.jl", "max_stars_repo_name": "PatricioFarrell/VoronoiFVM.jl", "max_stars_repo_head_hexsha": "690943ff455c91f16d114ad52cc83f2e8fa84e58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80, "max_stars_repo_stars_event_min_datetime": "2019-11-18T05:04:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T04:11:01.000Z", "max_issues_repo_path": "pluto-examples/vectorplot.jl", "max_issues_repo_name": "PatricioFarrell/VoronoiFVM.jl", "max_issues_repo_head_hexsha": "690943ff455c91f16d114ad52cc83f2e8fa84e58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2019-11-19T18:12:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T15:39:14.000Z", "max_forks_repo_path": "pluto-examples/vectorplot.jl", "max_forks_repo_name": "PatricioFarrell/VoronoiFVM.jl", "max_forks_repo_head_hexsha": "690943ff455c91f16d114ad52cc83f2e8fa84e58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2019-08-29T16:46:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T14:10:29.000Z", "avg_line_length": 31.6690307329, "max_line_length": 289, "alphanum_fraction": 0.7308151687, "num_tokens": 11874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.75738192656136}}
{"text": "# Julia function to load CSV and compute\n# a couple of SMA.  written to be identical\n# to lua version.\nusing DataFrames\n\n\n# Note: There are faster ways to compute SMA but this\n#  is closest to the method shown in basic tutorials\n#  and is a valid test of a tight loop that spends a\n#  a lot of time indexing into an array.   We show it\n#  as a nested loop instead of slice\nfunction sma(avect, numPer)\n    print(length(avect), \" numper=\", numPer)\n    numEle = length(avect)\n    tout = Array(Float32, numEle)\n    for ndx = 1:numEle\n      tsum = 0.0\n      begndx = max(1, ndx - numPer)\n      for slicendx = begndx:ndx\n        tsum += avect[slicendx]\n      end\n      tout[ndx] = tsum / float32(numPer)\n    end\n    return tout\nend\n\n## Showing the more common Julia version of\n## slicing out what we need and applying builtin\n## operator mean instead of manual sub loop.\nfunction sma_slice(avect, numPer)\n    print(length(avect), \" numper=\", numPer)\n    numEle = length(avect)\n    tout = Array(Float32, numEle)\n    for ndx = 1:numEle\n      begndx = max(1, ndx - numPer)\n      tout[ndx] = mean(avect[begndx:ndx])\n    end\n    return tout\nend\n\n\n\nfunction runTest()\n   print (\"read table\")\n   tic()\n   dta = readtable(\"2014.M1.csv\")\n   toc()\n   println(\"finished read table\")\n\n   closeVect = dta[:close]\n   println(\"compute sma(14)\")\n   tic()\n   sma14 = sma(closeVect, 14)\n   toc()\n   println(\"finished sma(14)\")\n\n   println(\"compute sma (600)\")\n   tic()\n   sma600 = sma(closeVect, 600)\n   toc()\n   println(\"finished sma(600)\")\n\n\n   closeVect = dta[:close]\n   println(\"compute sma_slice(14)\")\n   tic()\n   sma14 = sma_slice(closeVect, 14)\n   toc()\n   println(\"finished sma_slice(14)\")\n\n   println(\"compute sma_slice(600)\")\n   tic()\n   sma600 = sma_slice(closeVect, 600)\n   toc()\n   println(\"finished sma_slice(600)\")\n\n\n   println(\"\\n\\n Convert to Typed vector and try again \\n\\n\")\n   tic()\n   tlen = length(closeVect)\n   tvect = Array(Float32, tlen)\n   for ndx = 1:tlen\n     tvect[ndx] = closeVect[ndx]\n   end\n   toc()\n   println(\"vector convertion complete\")\n\n   println(\"compute sma(14)\")\n   tic()\n   sma14 = sma(tvect, 14)\n   toc()\n   println(\"finished sma(14)\")\n\n   println(\"compute sma (600)\")\n   tic()\n   sma600 = sma(tvect, 600)\n   toc()\n   println(\"finished sma(600)\")\n\n\n   closeVect = dta[:close]\n   println(\"compute sma_slice(14)\")\n   tic()\n   sma14 = sma_slice(tvect, 14)\n   toc()\n   println(\"finished sma_slice(14)\")\n\n   println(\"compute sma_slice(600)\")\n   tic()\n   sma600 = sma_slice(tvect, 600)\n   toc()\n   println(\"finished sma_slice(600)\")\n\n\n\nend\n\nrunTest()\n\n", "meta": {"hexsha": "1cfd4a6f00569f83ccc2c9f8fdfab8a30d5a587d", "size": 2565, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "csv_bar_parse.jl", "max_stars_repo_name": "joeatbayes/StockCSVAndSMAPerformanceComparison", "max_stars_repo_head_hexsha": "9a4989e640a367de84896c0ba10f65494d1be9ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-05-14T18:38:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-07T04:52:09.000Z", "max_issues_repo_path": "csv_bar_parse.jl", "max_issues_repo_name": "joeatbayes/StockCSVAndSMAPerformanceComparison", "max_issues_repo_head_hexsha": "9a4989e640a367de84896c0ba10f65494d1be9ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-14T06:39:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-09T12:48:40.000Z", "max_forks_repo_path": "csv_bar_parse.jl", "max_forks_repo_name": "joeatbayes/StockCSVAndSMAPerformanceComparison", "max_forks_repo_head_hexsha": "9a4989e640a367de84896c0ba10f65494d1be9ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.375, "max_line_length": 61, "alphanum_fraction": 0.637037037, "num_tokens": 788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.7573819149242231}}
{"text": "# An implementation of CGLS for the solution of the\n# over-determined linear least-squares problem\n#\n#  minimize ‖Ax - b‖\n#\n# equivalently, of the normal equations\n#\n#  A'Ax = A'b.\n#\n# CGLS is formally equivalent to applying the conjugate gradient method\n# to the normal equations but should be more stable. It is also formally\n# equivalent to LSQR though LSQR should be expected to be more stable on\n# ill-conditioned or poorly scaled problems.\n#\n# This implementation is the standard formulation, as recommended by\n# A. Björck, T. Elfving and Z. Strakos, Stability of Conjugate Gradient\n# and Lanczos Methods for Linear Least Squares Problems.\n#\n# Dominique Orban, <dominique.orban@gerad.ca>\n# Princeton, NJ, March 2015.\n\nexport cgls\n\n\n\"\"\"Solve the regularized linear least-squares problem\n\n  minimize ‖b - Ax‖₂² + λ ‖x‖₂²\n\nusing the Conjugate Gradient (CG) method, where λ ≥ 0 is a regularization\nparameter. This method is equivalent to applying CG to the normal equations\n\n  (A'A + λI) x = A'b\n\nbut is more stable.\n\nCGLS produces monotonic residuals ‖r‖₂ but not optimality residuals ‖A'r‖₂.\nIt is formally equivalent to LSQR, though can be slightly less accurate,\nbut simpler to implement.\n\"\"\"\nfunction cgls(A :: AbstractLinearOperator, b :: AbstractVector{T};\n              M :: AbstractLinearOperator=opEye(size(b,1)), λ :: Float64=0.0,\n              atol :: Float64=1.0e-8, rtol :: Float64=1.0e-6, radius :: Float64=0.0,\n              itmax :: Int=0, verbose :: Bool=false) where T <: Number\n\n  m, n = size(A);\n  size(b, 1) == m || error(\"Inconsistent problem size\");\n  verbose && @printf(\"CGLS: system of %d equations in %d variables\\n\", m, n);\n\n  x = zeros(T, n);\n  r = copy(b)\n  bNorm = @knrm2(m, r)   # Marginally faster than norm(b);\n  bNorm == 0 && return x, SimpleStats(true, false, [0.0], [0.0], \"x = 0 is a zero-residual solution\");\n  s = A' * M * r;\n  p = copy(s);\n  γ = @kdot(n, s, s)  # Faster than γ = dot(s, s);\n  iter = 0;\n  itmax == 0 && (itmax = m + n);\n\n  rNorm  = bNorm;\n  ArNorm = sqrt(γ);\n  rNorms = [rNorm;];\n  ArNorms = [ArNorm;];\n  ε = atol + rtol * ArNorm;\n  verbose && @printf(\"%5s  %8s  %8s\\n\", \"Aprod\", \"‖A'r‖\", \"‖r‖\")\n  verbose && @printf(\"%5d  %8.2e  %8.2e\\n\", 1, ArNorm, rNorm);\n\n  status = \"unknown\";\n  on_boundary = false\n  solved = ArNorm <= ε;\n  tired = iter >= itmax;\n\n  while ! (solved || tired)\n    q = A * p;\n    δ = @kdot(m, q, M * q)   # Faster than α = γ / dot(q, q);\n    λ > 0 && (δ += λ * @kdot(n, p, p))\n    α = γ / δ;\n\n    # if a trust-region constraint is give, compute step to the boundary\n    σ = radius > 0.0 ? maximum(to_boundary(x, p, radius)) : α\n    if (radius > 0.0) & (α > σ)\n      α = σ\n      on_boundary = true\n    end\n\n    @kaxpy!(n,  α, p, x)     # Faster than x = x + α * p;\n    @kaxpy!(m, -α, q, r)     # Faster than r = r - α * q;\n    s = A' * M * r;\n    λ > 0 && @kaxpy!(n, -λ, x, s)   # s = A' * r - λ * x;\n    γ_next = @kdot(n, s, s)  # Faster than γ_next = dot(s, s);\n    β = γ_next / γ;\n    @kscal!(n, β, p)\n    @kaxpy!(n, 1.0, s, p)    # Faster than p = s + β * p;\n    # The combined BLAS calls tend to trigger some gc.\n    #  BLAS.axpy!(n, 1.0, s, 1, BLAS.scal!(n, β, p, 1), 1);\n    γ = γ_next;\n    rNorm = @knrm2(m, r)  # Marginally faster than norm(r);\n    ArNorm = sqrt(γ);\n    push!(rNorms, rNorm);\n    push!(ArNorms, ArNorm);\n    iter = iter + 1;\n    verbose && @printf(\"%5d  %8.2e  %8.2e\\n\", 1 + 2 * iter, ArNorm, rNorm);\n    solved = (ArNorm <= ε) | on_boundary\n    tired = iter >= itmax;\n  end\n\n  status = on_boundary ? \"on trust-region boundary\" : (tired ? \"maximum number of iterations exceeded\" : \"solution good enough given atol and rtol\")\n  stats = SimpleStats(solved, false, rNorms, ArNorms, status);\n  return (x, stats);\nend\n", "meta": {"hexsha": "dd7665291cb6c0af9e29eb1c60a1c7c4daffd10e", "size": 3718, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cgls.jl", "max_stars_repo_name": "abelsiqueira/Krylov.jl", "max_stars_repo_head_hexsha": "dc0ca5466f7f1f7e65958fe016e3a06b858e3df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-06T18:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T18:14:15.000Z", "max_issues_repo_path": "src/cgls.jl", "max_issues_repo_name": "abelsiqueira/Krylov.jl", "max_issues_repo_head_hexsha": "dc0ca5466f7f1f7e65958fe016e3a06b858e3df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cgls.jl", "max_forks_repo_name": "abelsiqueira/Krylov.jl", "max_forks_repo_head_hexsha": "dc0ca5466f7f1f7e65958fe016e3a06b858e3df0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-05T10:58:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T10:58:57.000Z", "avg_line_length": 33.8, "max_line_length": 148, "alphanum_fraction": 0.6048951049, "num_tokens": 1288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7573734425091292}}
{"text": "const number_of_chebyshevs_to_compile_into_binaries = 20\n\nfunction next_chebyshev(previous::Sum_Of_Functions, two_previous::Sum_Of_Functions)\n    return PE_Function(2.0,0.0,0.0,1) * previous - two_previous\nend\n\nfirst_kind_chebyshevs = Array{Sum_Of_Functions}(undef, number_of_chebyshevs_to_compile_into_binaries)\nfirst_kind_chebyshevs[1] = Sum_Of_Functions([PE_Function(1.0,0.0,0.0,0)])\nfirst_kind_chebyshevs[2] = Sum_Of_Functions([PE_Function(1.0,0.0,0.0,1)])\nfor i in 3:number_of_chebyshevs_to_compile_into_binaries\n    first_kind_chebyshevs[i] = next_chebyshev(first_kind_chebyshevs[i-1], first_kind_chebyshevs[i-2])\nend\n\nsecond_kind_chebyshevs = Array{Sum_Of_Functions}(undef, number_of_chebyshevs_to_compile_into_binaries)\nsecond_kind_chebyshevs[1] = Sum_Of_Functions([PE_Function(1.0,0.0,0.0,0)])\nsecond_kind_chebyshevs[2] = Sum_Of_Functions([PE_Function(2.0,0.0,0.0,1)])\nfor i in 3:number_of_chebyshevs_to_compile_into_binaries\n    second_kind_chebyshevs[i] = next_chebyshev(second_kind_chebyshevs[i-1], second_kind_chebyshevs[i-2])\nend\n\n\n\"\"\"\n    get_chevyshevs_up_to(N::Integer, first_kind::Bool = true)\n\nGet the first N chebyshev polynomials returned as a vector of `UnivariateFunction`s.\nThe first 20 polynomials of each are precompiled into the binaries for speed. If\nyou need more than that they will be calculated at runtime.\n\nThese can be from either the first kind or second kind polynomial sequence.\n### Inputs\n* `N` - How many chebyshev polynomials do you want.\n* `first_kind` - A Bool. If true you get first kind polynomials. If false you get second kind.\n### Returns\n* A `Vector` of `UnivariateFunction`s for each polynomial.\n\"\"\"\nfunction get_chevyshevs_up_to(N::Integer, first_kind::Bool = true)\n    chebyshevs = Array{Sum_Of_Functions}(undef, N)\n    if N >= number_of_chebyshevs_to_compile_into_binaries\n        if first_kind\n            chebyshevs[1:number_of_chebyshevs_to_compile_into_binaries] = first_kind_chebyshevs\n        else\n            chebyshevs[1:number_of_chebyshevs_to_compile_into_binaries] = second_kind_chebyshevs\n        end\n        for i in (number_of_chebyshevs_to_compile_into_binaries+1):N\n            chebyshevs[i] = next_chebyshev(chebyshevs[i-1], chebyshevs[i-2])\n        end\n    else\n        if first_kind\n            chebyshevs[1:N] = first_kind_chebyshevs[1:N]\n        else\n            chebyshevs[1:N] = second_kind_chebyshevs[1:N]\n        end\n    end\n    return chebyshevs\nend\n", "meta": {"hexsha": "6e381b59a962372ace38739a6b7853bc9b3cc6ce", "size": 2428, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chebyshevs.jl", "max_stars_repo_name": "s-baumann/UnivariateFunctions.jl", "max_stars_repo_head_hexsha": "9e1a67e99ce55b109c850f51bef2491fee205c4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-18T17:53:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-18T17:53:21.000Z", "max_issues_repo_path": "src/chebyshevs.jl", "max_issues_repo_name": "s-baumann/UnivariateFunctions.jl", "max_issues_repo_head_hexsha": "9e1a67e99ce55b109c850f51bef2491fee205c4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-10-15T19:14:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T00:04:18.000Z", "max_forks_repo_path": "src/chebyshevs.jl", "max_forks_repo_name": "s-baumann/UnivariateFunctions.jl", "max_forks_repo_head_hexsha": "9e1a67e99ce55b109c850f51bef2491fee205c4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3571428571, "max_line_length": 104, "alphanum_fraction": 0.76276771, "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7573734354626661}}
{"text": "\n\"\"\"\nReverse plus\n\"\"\"\nfunction plus_rev(a::Interval, b::Interval, c::Interval)  # a = b + c\n    # a = a ∩ (b + c)  # add this line for plus contractor (as opposed to reverse function)\n    b_new = b ∩ (a - c)\n    c_new = c ∩ (a - b)\n\n    return a, b_new, c_new\nend\n\nplus_rev(a,b,c) = plus_rev(promote(a,b,c)...)\n\n\"\"\"\nReverse minus\n\"\"\"\nfunction minus_rev(a::Interval, b::Interval, c::Interval)  # a = b - c\n\n    b_new = b ∩ (a + c)\n    c_new = c ∩ (b - a)\n\n    return a, b_new, c_new\nend\n\nminus_rev(a,b,c) = minus_rev(promote(a,b,c)...)\n\nfunction minus_rev(a::Interval, b::Interval)  # a = -b\n    b_new = b ∩ (-a)\n    return (a, b_new)\nend\n\n\n\"\"\"\nReverse multiplication\n\"\"\"\nfunction mul_rev(a::Interval, b::Interval, c::Interval)  # a = b * c\n\n    # ((0.0 ∉ a) || (0.0 ∉ b)) && (c = c ∩ (a / b))\n    # ((0.0 ∉ a) || (0.0 ∉ c)) && (b = b ∩ (a / c))\n\n    # a = a ∩ (b * c)  # ?\n\n    if 0 ∈ b\n        temp = c .∩ extended_div(a, b)\n        c′ = union(temp[1], temp[2])\n\n    else\n        c′ = c ∩ (a / b)\n    end\n\n    if 0 ∈ c\n        temp = b .∩ extended_div(a, c)\n        b′ = union(temp[1], temp[2])\n\n    else\n        b′ = b ∩ (a / c)\n    end\n\n    return a, b′, c′\nend\n\nmul_rev(a,b,c) = mul_rev(promote(a,b,c)...)\n\n\"\"\"\nReverse division\n\"\"\"\nfunction div_rev(a::Interval, b::Interval, c::Interval)  # a = b / c\n\n    b = b ∩ (a * c)\n    c = c ∩ (b / a)\n\n    return a, b, c\nend\n\ndiv_rev(a,b,c) = div_rev(promote(a,b,c)...)\n\n\"\"\"\nReverse inverse\n\"\"\"\nfunction inv_rev(a::Interval, b::Interval)  # a = inv(b)\n\n    b_new = b ∩ inv(a)\n\n    return a, b_new\nend\n\ninv_rev(a,b) = inv_rev(promote(a,b)...)\n\n\"\"\"\nReverse power\n\"\"\"\nfunction power_rev(a::Interval, b::Interval, n::Integer)  # a = b^n,  log(a) = n.log(b),  b = a^(1/n)\n\n    if n == 2  # a = b^2\n        root = √a\n        b1 = b ∩ root\n        b2 = b ∩ (-root)\n\n    elseif iseven(n)\n        root = a^(1//n)\n\n        b1 = b ∩ root\n        b2 = b ∩ (-root)\n\n    elseif isodd(n)\n        pos_root = (a ∩ (0..∞)) ^ (1//n)\n        neg_root = -( ( (-a) ∩ (0..∞) ) ^ (1//n) )\n\n        b1 = b ∩ pos_root\n        b2 = b ∩ neg_root\n\n    end\n\n    b = hull(b1, b2)\n\n    return (a, b, n)\nend\n\n\nfunction power_rev(a::Interval, b::Interval, c::Interval)  # a = b^c\n\n    if isinteger(c)\n        temp = power_rev(a, b, Int(inf(c)))  # use version with integer\n        return (temp[1], temp[2], interval(temp[3]))\n    end\n\n    b_new = b ∩ ( a^(inv(c) ))\n    c_new = c ∩ (log(a) / log(b))\n\n    return a, b_new, c_new\nend\n\npower_rev(a, b, c) = power_rev(promote(a, b, c)...)\n\n\n\"\"\"\nReverse square root\n\"\"\"\nfunction sqrt_rev(a::Interval, b::Interval)  # a = sqrt(b)\n\n    b_new = b ∩ (a^2)\n\n    return a, b_new\nend\n\nsqrt_rev(a,b) = sqrt_rev(promote(a,b)...)\n\n\n# IEEE-1788 style\n\n\"\"\"\nReverse sqr\n\"\"\"\nfunction sqr_rev(c, x)   # c = x^2;  refine x\n\n    root = sqrt(c)\n\n    x1 = x ∩ root\n    x2 = x ∩ (-root)\n\n    return (c, hull(x1, x2))\nend\n\nsqr_rev(c) = sqr_rev(c, -∞..∞)\n\n\"\"\"\nReverse abs\n\"\"\"\nfunction abs_rev(y, x)   # y = abs(x); refine x\n\n    y_new = y ∩ (0..∞)\n\n    x1 = y_new ∩ x\n    x2 = -(y_new ∩ (-x))\n\n    return (y, hull(x1, x2))\nend\n#=\n\"\"\"\nReverse sign\n\"\"\"\nfunction sign_rev(a::Interval, b::Interval)  # a = sqrt(b)\n\n    (a == 1.0) && b = b ∩ (0..∞)\n    (a == 0.0) && b = b ∩ (0.0..0.0)\n    (a == -1.0) && b = b ∩ (-∞..0.0)\n\n    return a, b\nend\nsign_rev(a,b) = sign_rev(promote(a,b)...)\n=#\n## IEEE-1788 versions:\n\n\"\"\"\nAccording to the IEEE-1788 standard:\n\n- `∘_rev1(b, c, x)` is the subset of `x` such that `x ∘ b` is defined and in `c`;\n- `∘_rev2(a, c, x)` is the subset of `x` such that `a ∘ x` is defined and in `c`\n\nWhen `∘` is commutative, these agree and we write `∘_rev(b, c, x)`.\n\"\"\"\n\nfunction mul_rev_IEEE1788(b, c, x)   # c = b*x\n    return x ∩ (c / b)\nend\n\nfunction pow_rev1(b, c, x)   # c = x^b\n    return x ∩ c^(1/b)  # replace by 1//b\nend\n\nfunction pow_rev2(a, c, x)   # c = a^x\n    return x ∩ (log(c) / lob(a))\nend\n", "meta": {"hexsha": "ee645a6dbe045d9bd4df24743904fc088f62f72b", "size": 3858, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/arithmetic.jl", "max_stars_repo_name": "UnofficialJuliaMirror/IntervalContractors.jl-15111844-de3b-5229-b4ba-526f2f385dc9", "max_stars_repo_head_hexsha": "e95b5d21425d6c757088d284f5a62adda4c7baa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-02-27T20:15:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T17:55:10.000Z", "max_issues_repo_path": "src/arithmetic.jl", "max_issues_repo_name": "UnofficialJuliaMirror/IntervalContractors.jl-15111844-de3b-5229-b4ba-526f2f385dc9", "max_issues_repo_head_hexsha": "e95b5d21425d6c757088d284f5a62adda4c7baa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2017-05-03T14:08:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-04T20:43:33.000Z", "max_forks_repo_path": "src/arithmetic.jl", "max_forks_repo_name": "UnofficialJuliaMirror/IntervalContractors.jl-15111844-de3b-5229-b4ba-526f2f385dc9", "max_forks_repo_head_hexsha": "e95b5d21425d6c757088d284f5a62adda4c7baa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-05-04T04:46:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T23:30:35.000Z", "avg_line_length": 17.9441860465, "max_line_length": 101, "alphanum_fraction": 0.5036288232, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7573734292263524}}
{"text": "module GenGammaDist\nusing Distributions\n\nimport Base.Random\nimport Base: mean, rand\nimport Distributions: pdf\n\n# Generalized Gamma distribution\n# We have constructors for three different parameterizations.\n# Some parameters can be negative, so this works as an inverse gamma distribution as well.\n\nexport GenGamma, gengamma_wiki, gengamma1, params, params1, params_wiki, pdf\n\n# Use parameterization of R flexsurv implementation\nimmutable GenGamma <: ContinuousUnivariateDistribution\n    μ::Float64\n    σ::Float64\n    Q::Float64\n    gdist::Distributions.Gamma  # gamma distribution used to compute random samples\nend\n\n# construct with parameterization of R flexsurv implementation\n\n\"\"\"\n    GenGamma(μ, σ, Q)\n\nThe `generalized gamma distribution` parameterized as in the R `flexsurv`\nimplementation[^1].\n\n[^1]: Prentice, R. L. (1974). A log gamma model and its maximum likelihood estimation. Biometrika 61(3):539-544\n\"\"\"\nfunction GenGamma(μ, σ, Q)\n    gdist = Distributions.Gamma(1/Q^2,1)\n    GenGamma(μ, σ, Q, gdist)\nend\n\n# Parameterization from wikipedia page\n# PDF is: \\frac{p/a^d}{\\Gamma(d/p)} x^{d-1}e^{-(x/a)^p}\n# The R page for gengamma flexsurv says that Q < 0 is allowed.\n# The wikipedia page does not have abs(d) and abs(p), but this works, because the -i π cancels\n# Must have d>0,p>0  or  d<0, p<0\n\n\"\"\"\n    gengamma_wiki(a,d,p)\n\nThe `generalized gamma distribution` parameterized as on the Wikipedia page.\nRequires `d>0, p>0` or `d<0,p<0`.\n\"\"\"\nfunction gengamma_wiki(a,d,p)\n    μ = log(a) + (log(abs(d)) - log(abs(p)))/p\n    σ = 1 / sqrt(p*d)\n    Q = sqrt(p/d) * sign(p)\n    GenGamma(μ,σ,Q)\nend\n\n# Another parameterization\n# PDF is: \\frac{p b^(d/p)}{\\Gamma(d/p)} x^(d-1) e^{-b x^p}\n# Must have d>0,p>0  or  d<0, p<0\n\"\"\"\n    gengamma1(b,d,p)\n\nThe `generalized gamma distribution` with alternative parameterization. This follows\nthe older R convention `dgengamma.orig` [^2].\n\n[^2]: Stacy, E. W. (1962). A generalization of the gamma distribution. Annals of Mathematical Statistics 33:1187-92.\n\"\"\"\nfunction gengamma1(b,d,p)\n    a = b^(-1/p)\n    gengamma_wiki(a,d,p)\nend\n\n# Use the algorithm given in the documentation pages for the R package flexsurv.\nfunction rand(p::GenGamma)\n    Qs = p.Q^2\n    gamma_deviate = rand(p.gdist)  # only saves 10 or so percent time.\n    w = log(Qs*gamma_deviate)/p.Q\n    x = exp(p.μ + p.σ * w)\n    return x\nend\n\n#  mean in wikipedia parameterization is\n#  a * gamma((d+1)/p)/gamma(d/p)\nfunction mean(p::GenGamma)\n    Qs = p.Q^2\n    iQs = 1/Qs\n    a = Qs^(p.σ / p.Q) * exp(p.μ)\n    a * gamma(iQs + p.σ/p.Q)/gamma(iQs)\nend\n\nfunction pdf(p::GenGamma,x::Real)\n    (d,p,a) = params_wiki(p)\n    (p/a^d)/gamma(d/p) * x^(d-1) * exp(-(x/a)^p)\nend\n\n\"\"\"\n   params_wiki(dt::GenGamma)\n\nreturns parameters of the `generalized Gamma distribution` following\nthe convention on the Wikipedia page.\n\"\"\"\nfunction params_wiki(dt::GenGamma)\n    d = 1/(dt.σ * dt.Q)\n    p = (dt.Q)/(dt.σ)\n    a = abs(dt.Q)^(2/p)*exp(dt.μ)\n    return (a,d,p)\nend\n\n\"\"\"\n   params1(dt::GenGamma)\n\nreturns parameters of the `generalized Gamma distribution` following the parameterization\nof the older R implementation `dgengamma.orig` [^2].\n\n[^2]: Stacy, E. W. (1962). A generalization of the gamma distribution. Annals of Mathematical Statistics 33:1187-92.\n\"\"\"\nfunction params1(dt::GenGamma)\n    (a,d,p) = params_wiki(dt)\n    b = a^(-p)\n    return (b,d,p)\nend\n\n\"\"\"\n   params1(dt::GenGamma)\n\nreturns parameters of the `generalized Gamma distribution` following\nthe convention of the R `flexsurv` function.\n\"\"\"\nfunction params(d::GenGamma)\n    return (d.μ, d.σ, d.Q)\nend\n\nend # module\n", "meta": {"hexsha": "bf460668d63dc1018a99cc5c549092162e84e906", "size": 3579, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GenGammaDist.jl", "max_stars_repo_name": "JuliaTagBot/GenGammaDist.jl", "max_stars_repo_head_hexsha": "5c865b42728c923d30c18b25b3e0d8cff4b5642b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GenGammaDist.jl", "max_issues_repo_name": "JuliaTagBot/GenGammaDist.jl", "max_issues_repo_head_hexsha": "5c865b42728c923d30c18b25b3e0d8cff4b5642b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GenGammaDist.jl", "max_forks_repo_name": "JuliaTagBot/GenGammaDist.jl", "max_forks_repo_head_hexsha": "5c865b42728c923d30c18b25b3e0d8cff4b5642b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:41:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T01:48:51.000Z", "avg_line_length": 26.9097744361, "max_line_length": 116, "alphanum_fraction": 0.6814752724, "num_tokens": 1129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7573586318698322}}
{"text": "module RobustLeastSquares\n\nusing StatsBase\nusing IterativeSolvers\nusing Logging\nusing LinearAlgebra\nusing SparseArrays\n\nexport reweighted_lsqr, refit_estimator\n\nexport MEstimator, L2Estimator, L1Estimator, L1L2Estimator, HuberEstimator, FairEstimator, CauchyEstimator, GemanEstimator, WelschEstimator,  TukeyEstimator, MultiEstimator\nexport estimator_rho, estimator_psi, estimator_weight, estimator_sqrtweight\n\ninclude(\"MEstimators.jl\")\n\nfunction solve(A,b,weights=ones(length(b)),method=:qr,x0=nothing)\n    if method == :qr\n        return (Diagonal(weights) * A) \\ (weights.*b)\n        # this works for sparse matrices:\n        #return Base.LinAlg.SparseMatrix.SPQR.solve(0,qrfact(sparse(spdiagm(weights)*A)),Base.LinAlg.SparseMatrix.CHOLMOD.Dense(spdiagm(weights)*b))\n    elseif method == :normal\n        return (A' * (Diagonal(weights.^2) * A)) \\ (A' * (weights .^ 2 .*b))\n    elseif method == :cg\n        # Use a conjugate gradient method to find the solution (less memory)\n        if x0 == nothing\n            x0 = zeros(size(A,2))\n        end\n        sol = lsqr!(x0, Diagonal(weights) * A, weights.*b)\n        return sol\n    else\n        error(\"Method :$method should have been one of :qr, :normal or :cg\")\n    end\nend\n\n\"\"\"\n(sol,res) = reweighted_lsqr(sol::AbstractVector, A::AbstractMatrix,b::AbstractVector,estimator::MEstimator = L2Estimator,useqr::Type = Val{true}; n_iter=10)\n\nSolves a reweighted least squares problem: min ∑ᵢ ρ((A*sol - b)ᵢ) using the specified MEstimator for ρ and starting with sol (for initial weights).\n\"\"\"\nfunction reweighted_lsqr(A::AbstractMatrix,b::AbstractVector,estimator::MEstimator = L2Estimator(), x0 = nothing;method::Symbol=:qr, n_iter::Integer=10, refit::Bool = false, quiet::Bool = false, kwargs...)\n    local sol, res, weights\n\n    s1,s2 = size(A)\n    if s1 == s2\n        warn(\"Encountered square matrix of size $s1. Julia will revert to linear solvers instead of least-square solvers, and throw an error if the matrix is singular.\")\n    end\n\n    # Set the initial weights\n    if x0 === nothing\n        weights = fill(1, size(b))\n    else\n        res = A*x0 - b\n        if refit\n            weights = estimator_sqrtweight(res, refit_estimator(estimator, res, 3.0))\n        else\n            weights = estimator_sqrtweight(res, estimator)\n        end\n    end\n\n    # Perform the reweighted least squares\n    if issparse(A)\n        quiet || @info \"Solving a $(size(A)) reweighted least-squares problem. $(typeof(A)) matrix has $(nnz(A)) non-zero elements. Using $method method.\"\n    else\n        quiet || @info \"Solving a $(size(A)) reweighted least-squares problem with a $(typeof(A)). Using $method method.\"\n    end\n\n    for i=1:n_iter\n        if i == 1\n            sol = solve(A,b,weights,method,x0)\n        else\n            sol = solve(A,b,weights,method,sol)\n        end\n        res = A*sol - b\n\n        if refit\n            weights = estimator_sqrtweight(res, refit_estimator(estimator,res,3.0))\n        else\n            weights = estimator_sqrtweight(res, estimator)\n        end\n\n        quiet || @info \"Iteration $i, RMS residual $(sqrt(sum(res.*res)/length(res)))))\"\n    end\n\n    quiet || @info \"Root-mean-square weighted residual error = $(sqrt(sum(res.^2)/length(res)))\"\n\n    return (sol,res,weights)\nend\n\nend # module\n", "meta": {"hexsha": "8b417f17eea39030b8ab208c9732a13deace6124", "size": 3273, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/RobustLeastSquares.jl", "max_stars_repo_name": "FugroRoames/RobustLeastSquares.jl", "max_stars_repo_head_hexsha": "0f77cf109eb222ef5487771789d521b86a50a6c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2016-02-22T02:57:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T09:07:07.000Z", "max_issues_repo_path": "src/RobustLeastSquares.jl", "max_issues_repo_name": "FugroRoames/RobustLeastSquares.jl", "max_issues_repo_head_hexsha": "0f77cf109eb222ef5487771789d521b86a50a6c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-02-18T01:39:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-22T12:15:19.000Z", "max_forks_repo_path": "src/RobustLeastSquares.jl", "max_forks_repo_name": "FugroRoames/RobustLeastSquares.jl", "max_forks_repo_head_hexsha": "0f77cf109eb222ef5487771789d521b86a50a6c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-04-20T22:36:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T21:10:43.000Z", "avg_line_length": 36.3666666667, "max_line_length": 205, "alphanum_fraction": 0.6602505347, "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7573586318698322}}
{"text": "\"Fix to ensure positive definiteness by dividing each off-diagonal element by sum of absolute values of off-diagonal elements in its row\"\nfunction fixMatrix(A::Array{Float64}, denom_factor::Float64)\n\tp = size(A, 1);\n\tfor cur_row in 1:p\n\t\tcur_sum = sum(abs(A[cur_row, :])) - 1\n\t\tif cur_sum != 1\n\t\t\tA[cur_row, :] = A[cur_row, :] / (denom_factor * cur_sum);\n\t\tend\n\t\t# Make sure diagonal entries are still 1\n\t\tA[cur_row, cur_row] = 1;\n\tend\n\t# Final matrix is average of matrix with its transpose\n\tA = (A + A')/2\n    return A\nend\n\n\"Calculate Covariance Matrix using Gaussian Kernel\"\nfunction calcSigma(X, inv_Sigma)\n\tSigma = zeros(size(X, 1), size(X, 1))\n\tfor i in 1:size(Sigma, 1)\n\t  for j in 1:size(Sigma, 2)\n          Sigma[i, j] = exp(- 1/2 * (X[i, :] - X[j, :])' * inv_Sigma * (X[i, :] - X[j, :]))[1]\n\t  end\n\tend\n\treturn Sigma\nend\n", "meta": {"hexsha": "7ad068b822da656ab3bdcb8b42452c648ad8c139", "size": 831, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "jiali-vt/GpSelection.jl", "max_stars_repo_head_hexsha": "539c5d91dec387162fec871d772940c419ab803a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "jiali-vt/GpSelection.jl", "max_issues_repo_head_hexsha": "539c5d91dec387162fec871d772940c419ab803a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "jiali-vt/GpSelection.jl", "max_forks_repo_head_hexsha": "539c5d91dec387162fec871d772940c419ab803a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7777777778, "max_line_length": 137, "alphanum_fraction": 0.6486161252, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7573586258785794}}
{"text": "using GLM, RDatasets, DataFrames, Distributions, Random, LinearAlgebra\nRandom.seed!(0)\n\ndf = dataset(\"MASS\", \"cpus\")\nn = size(df)[1]\ndf = df[shuffle(1:n),:]\n\npTest = 0.2\nlastTindex = Int(floor(n*(1-pTest)))\nnumTest = n - lastTindex\n\ntrain = df[1:lastTindex,:]\ntest = df[lastTindex+1:n,:]\n\nform = @formula(Perf~CycT+MMin+MMax+Cach+ChMin+ChMax)\nmodel1 = glm(form, train, Normal(),  IdentityLink())\nmodel2 = glm(form, train, Poisson(), LogLink())\nmodel3 = glm(form, train, Gamma(),  InverseLink())\n\ninvIdenityLink(x) = x\ninvLogLink(x) = exp(x)\ninvInverseLink(x) = 1/x\n\nA = [ones(numTest) test.CycT test.MMin test.MMax test.Cach test.ChMin test.ChMax]\npred1 = invIdenityLink.(A*coef(model1))\npred2 = invLogLink.(A*coef(model2))\npred3 = invInverseLink.(A*coef(model3))\n\nactual = test.Perf\nlossModel1 = norm(pred1 - actual)\nlossModel2 = norm(pred2 - actual)\nlossModel3 = norm(pred3 - actual)\n\nprintln(\"Model 1: \", coef(model1))\nprintln(\"Model 2: \", coef(model2))\nprintln(\"Model 3: \", coef(model3))\nprintln(\"\\nLoss of models 1,2,3: \",(lossModel1 ,lossModel2, lossModel3))", "meta": {"hexsha": "35ac2a25074172c01f4b878e1fdc3a4fc86409c8", "size": 1064, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "8_chapter/linkFunctions.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "8_chapter/linkFunctions.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "8_chapter/linkFunctions.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 28.7567567568, "max_line_length": 81, "alphanum_fraction": 0.6992481203, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8267118004748678, "lm_q1q2_score": 0.7573586205088694}}
{"text": "using SparseArrays, LinearAlgebra\n# generate a random pos def matrix with eigenvalues between 0.1 and 2\nfunction generate_pos_def_matrix(rng::MersenneTwister, n::Int64, aMin::Real = 0.1, aMax::Real = 2)\n\tX = rand(rng, n, n)\n\t# any real square matrix can be QP decomposed into a orthogonal matrix and an uppertriangular matrix R\n\tQ, R = qr(X)\n\teigs = rand(rng ,n) .* (aMax .- aMin) .+ aMin\n\tX = Q * Matrix(Diagonal(eigs)) * Q'\n\tX = 0.5 * (X + X')\n\treturn X\nend\n\nfunction is_numerically_pos_sem_def(X, atol)\n\tX = X ./ 2\n\tX = X + X'\n\n\tF = eigfact(X)\n\tif size(find( x-> x < -atol, F[:values]), 1) == 0\n\t\treturn true\n\telse\n\t\treturn false\n\tend\nend\n\nfunction is_numerically_symmetric(X,atol)\n\tn = size(X, 2)\n\tfor i = 1:n-1, j = i+1:n\n\t\tif abs(X[i, j] - X[j, i]) >= atol\n\t\t\treturn false\n\t\tend\n\tend\n\treturn true\nend\n\n\nfunction find_nonsymmetric_component(X)\n\tfor i = 2:size(X, 1), j = 1:(i - 1)\n\t\tif abs(X[i, j] - X[j, i]) > 0.0\n\t\t\treturn i, j, abs(X[i, j] - X[j, i])\n\t\tend\n\tend\nend\n\nfunction find_different_elements(A, B)\n\tif size(A) != size(B)\n\t\terror(\"Matrices are not the same size\")\n\tend\n\tm, n = size(A)\n\tdiff_el = Array[]\n\tfor iii = 1:m, jjj = 1:n\n\t\tif A[iii, jjj] != B[iii, jjj]\n\t\t\tpush!(diff_el, [iii, jjj])\n\t\tend\n\tend\n\treturn diff_el\nend\n\nfunction duplicate_sparsity_pattern(A)\n\tm, n = size(A)\n\tB = zeros(m, n)\n\tfor iii = 1:m, jjj = 1:n\n\t\tif A[iii, jjj] != 0\n\t\t\tB[iii, jjj] = 1\n\t\tend\n\tend\n\treturn B\nend\n\nfunction apply_pattern!(A::AbstractMatrix, pattern::AbstractMatrix)\n  @assert size(A) == size(pattern) \"Matrix A and pattern must have same dimensions.\"\n  m, n = size(A)\n  for i = 1:m, j = 1:n\n    if pattern[i, j] == 0\n      A[i, j] = 0.\n    end\n  end\nend\n\n\n# create a feasible SDP with one PSDConeTriangle constraint\n# min c' x\n# s.t. At x + s == bt\n#       s ∈ PSDConeTriangle\n# choose At and bt in such a way that S has the provided sparsity pattern\nfunction feasible_sdp_with_pattern(rng::MersenneTwister, pattern::AbstractMatrix)\n  n = size(pattern, 1)\n  d = div(n * (n + 1), 2)\n\n\n  S = generate_pos_def_matrix(rng, n, 0.1, 2)\n  apply_pattern!(S, pattern)\n  S = Symmetric(S, :U)\n\n  A1 = rand(rng, n, n)\n  apply_pattern!(A1, pattern)\n  A1 = Symmetric(A1, :U)\n  A = hcat(A1[:])\n  s = S[:]\n  x = rand(rng, 1)\n  b = A * x + s\n  B = reshape(b, n, n)\n\n  Y = generate_pos_def_matrix(rng, n,  0.1, 1)\n  y = vec(Y)\n  P = sparse(zeros(1, 1))\n  q = -P * x - A' * y\n\n  Ct = [COSMO.PsdConeTriangle(d)];\n  At = zeros(d)\n  bt = zeros(d)\n  COSMO.extract_upper_triangle!(A1, At, sqrt(2))\n  COSMO.extract_upper_triangle!(B, bt, sqrt(2))\n  At = hcat(At)\n  return P, q, At, bt, Ct\nend\n\n\n\n\"Take a vector `svec` representing the `d` upper-triangular entries of a matrix `X`, and return `X`.\"\nfunction matrixify(svec::AbstractVector)\n  n = - 0.5 + sqrt(0.25 + 2 * length(svec))\n  n = Int64(n)\n  X = zeros(n, n)\n  COSMO.populate_upper_triangle!(X, svec, 1 /sqrt(2))\n  return Symmetric(X, :U)\nend\n\n\nfunction recreate_sparse_matrix(A::SparseMatrixCSC)\n\trowInd = A.rowval\n\tcolPtr = A.colptr\n\tval = A.nzval\n\n\t#compute column indices\n\tcolInd = zeros(Int64, length(rowInd))\n\tcval = 1\n\tfor iii = 2:length(colPtr)\n\t\tcurrentPtr = colPtr[iii]\n\t\tprevPtr = colPtr[iii - 1]\n\t\tcolInd[prevPtr:currentPtr - 1] = cval\n\t\tcval += 1\n\tend\n\n\t# sort rowInd and vals\n\tp = sortperm(rowInd)\n\treturn sparse(rowInd, colInd, val, size(A, 1), size(A, 2))\nend\n\n# Geometric mean from https://github.com/JuliaStats/StatsBase.jl\nfunction gmean(a::AbstractArray{T}) where T<:Real\n\ts = 0.0\n\tn = length(a)\n\tfor i in 1:n\n\t\ttmp = a[i]\n\t\tif tmp < 0.0\n\t\t\tthrow(DomainError())\n\t\telseif tmp == 0.0\n\t\t\treturn 0.0\n\t\telse\n\t\t\ts += log(tmp)\n\t\tend\n\tend\n\treturn exp(s / n)\nend\n", "meta": {"hexsha": "4fa05edbc4f3dfb51d325f9af303a8b5ff135ba6", "size": 3612, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/UnitTests/COSMOTestUtils.jl", "max_stars_repo_name": "innerlee/COSMO.jl", "max_stars_repo_head_hexsha": "ef70d97cac677eb5e1f051a71a7cf176b877c454", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/UnitTests/COSMOTestUtils.jl", "max_issues_repo_name": "innerlee/COSMO.jl", "max_issues_repo_head_hexsha": "ef70d97cac677eb5e1f051a71a7cf176b877c454", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/UnitTests/COSMOTestUtils.jl", "max_forks_repo_name": "innerlee/COSMO.jl", "max_forks_repo_head_hexsha": "ef70d97cac677eb5e1f051a71a7cf176b877c454", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8909090909, "max_line_length": 103, "alphanum_fraction": 0.6342746401, "num_tokens": 1322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.826711787666479, "lm_q1q2_score": 0.757358614455463}}
{"text": "function solve(FDDE::FDDEProblem, h, ::DelayPECE)\n    @unpack f, ϕ, α, τ, tspan = FDDE\n    t = collect(0:h:tspan)\n    maxn = length(t)\n    yp = zeros(maxn)\n    y = copy(t)\n    y[1] = ϕ(0)\n\n    for n in 1:maxn-1\n        yp[n+1] = 0\n        for j = 1:n\n            yp[n+1] = yp[n+1]+b(j-1, n-1, α, h)*f(t[j], y[j], v(ϕ, j, τ, h, y, yp)...)\n        end\n        yp[n+1] = yp[n+1]/gamma(α)+ϕ(0)\n\n        y[n+1] = 0\n\n        for j=1:n\n            y[n+1] = y[n+1]+a(j-1, n-1, α, h)*f(t[j], y[j], v(ϕ, j, τ, h, y, yp)...)\n        end\n\n        y[n+1] = y[n+1]/gamma(α)+h^α*f(t[n+1], yp[n+1], v(ϕ, n+1, τ, h, y, yp)...)/gamma(α+2) + ϕ(0)\n    end\n\n    V = []\n    for n = 1:maxn\n        push!(V, v(ϕ, n, τ, h, y, yp))\n    end\n\n    delayed = zeros(length(τ), length(V))\n    for i=1:length(V)\n        delayed[:, i] = V[i]\n    end\n\n    \n    return delayed, y\nend\n\nfunction a(j, n, α, h)\n    if j == n+1\n        result = 1\n    elseif j == 0\n        result = n^(α+1)-(n-α)*(n+1)^α\n    elseif j == n\n        result = 2*(2^(α+1)-1)\n    else\n        result = (n-j+2)^(α+1) + (n-j)^(α+1) - 2*(n-j+1)^(α+1)\n    end\n    return result*h^α / (α*(α + 1))\nend\n\nfunction b(j, n, α, h)\n    return h^α/α*((n-j+1)^α - (n-j)^α)\nend\n\nfunction v(ϕ, n, τ, h, y, yp)\n    if maximum(τ) > n*h\n        return ϕ.((n-1)*h.-τ)\n    else\n        m = floor.(Int, τ./h)\n        δ = m.-τ./h\n\n        function judge(m)\n            temp1 = findall(x->x>1, m)\n            temp2 = findall(x->x==1, m)#FIXME: Another case for x == 1\n\n            result = zeros(length(m))\n            if length(temp1) == length(m)\n                for i=1:length(m)\n                    result[i] = δ[i]*y[n-m[i]+2]+(1-δ[i])*y[n-m[i]+1]\n                end\n                return result\n            end\n        end\n        return judge(m)\n    end\nend", "meta": {"hexsha": "1d94dbf8eef2257f890963486a2fa47019907025", "size": 1779, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FDDE/DelayPECEMultipleLags.jl", "max_stars_repo_name": "SciFracX/FractionalDiffEq.jl", "max_stars_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-11-05T12:49:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:57:20.000Z", "max_issues_repo_path": "src/FDDE/DelayPECEMultipleLags.jl", "max_issues_repo_name": "SciFracX/FractionalDiffEq.jl", "max_issues_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-11-01T22:05:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:57:19.000Z", "max_forks_repo_path": "src/FDDE/DelayPECEMultipleLags.jl", "max_forks_repo_name": "SciFracX/FractionalDiffEq.jl", "max_forks_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1038961039, "max_line_length": 100, "alphanum_fraction": 0.4114671164, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488964, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7573576962181204}}
{"text": "function Attenuation{T<:AbstractFloat}(nz::Int,nx::Int,ext::Int,atten_max::T)\n\n# This function builds the complex-valued diagonal attenuation operator/matrix,\n# where the main diagonal contains the attenuation factor for each point in\n# the modeling region AND the surrounding boundary region. It is assumed \n# that no attenuation occurs in the modeling regionl. It is also assumed \n# that all 4 sides of the modeling region are surrounded by an attenuating\n# boundary material to prevent boundary reflections. The imaginary component\n# in the attenuation factor is zero in the modeling region and increases\n# parabolically outward in the boundary region.\n#\n# INPUTS:     nz        - Number of grid points in z-direction INCLUDING the absorbing boundary region\n#             nx        - Number of grid points in x-direction INCLUDING the absorbing boundary region\n#             ext       - Thickness (number of grid points) of attenuating boundary region\n#             atten_max - Maximum complex amplitude in the attenuating boundary layer\n#\n# OUTPUTS:    A         - Diagonal matrix containing the attenuation factors\n\n    atten = (ext:-1:1).^2/(ext.^2)*atten_max\n    a_boundary1 = kron(ones(nz,1),atten')\n    a_boundary2 = kron(atten,ones(1,nx))\n    a = zeros(T,nz,nx)\n    a[:,1:ext] += a_boundary1\n    a[:,nx-ext+1:nx] += flipdim(a_boundary1,2)\n    a[1:ext,:] += a_boundary2\n    a[nz-ext+1:nz,:] += flipdim(a_boundary2,1)\n\n    A = 1 - im*a\n\n    return spdiagm((A[:]),(0))\n\nend", "meta": {"hexsha": "ae547a97c9cd8117d75e571f563ad46426fea204", "size": 1480, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Operators/Attenuation.jl", "max_stars_repo_name": "lsafron/AcousticFWI.jl", "max_stars_repo_head_hexsha": "7ba478407b76faf7eef0c784289281ec7997e0d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-13T01:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-13T01:24:30.000Z", "max_issues_repo_path": "src/Operators/Attenuation.jl", "max_issues_repo_name": "lsafron/AcousticFWI.jl", "max_issues_repo_head_hexsha": "7ba478407b76faf7eef0c784289281ec7997e0d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Operators/Attenuation.jl", "max_forks_repo_name": "lsafron/AcousticFWI.jl", "max_forks_repo_head_hexsha": "7ba478407b76faf7eef0c784289281ec7997e0d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.25, "max_line_length": 102, "alphanum_fraction": 0.702027027, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7573293256359623}}
{"text": "# Kochenderfer, Mykel J.. Algorithms for Optimization (The MIT Press)\n\nfunction branin(x; a=1, b=5.1/(4π^2), c=5/π, r=6, s=10, t=1/(8π))\n    return a*(x[2]-b*x[1]^2+c*x[1]-r)^2 + s*(1-t)*cos(x[1]) + s\nend\n\nfunction ackley(x, a=20, b=0.2, c=2π)\n    d = length(x)\n    return -a*exp(-b*sqrt(sum(x.^2)/d)) - exp(sum(cos.(c*xi) for xi in x)/d) + a + exp(1)\nend\n\nparaboloid(x; a=1, b=1) = x[1]^2/a^2 + x[2]^2/b^2", "meta": {"hexsha": "a522446e1a454c5d412d21e18897d71dae5778d0", "size": 406, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/test_objective_functions.jl", "max_stars_repo_name": "mossr/CrossEntropyVariants.jl", "max_stars_repo_head_hexsha": "800ea93405925d12eceb5ca4e48d76e049226f6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-01-28T07:11:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T10:33:06.000Z", "max_issues_repo_path": "src/test_objective_functions.jl", "max_issues_repo_name": "mossr/CrossEntropyVariants.jl", "max_issues_repo_head_hexsha": "800ea93405925d12eceb5ca4e48d76e049226f6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-07T12:14:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-07T21:46:36.000Z", "max_forks_repo_path": "src/test_objective_functions.jl", "max_forks_repo_name": "mossr/CrossEntropyVariants.jl", "max_forks_repo_head_hexsha": "800ea93405925d12eceb5ca4e48d76e049226f6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8333333333, "max_line_length": 89, "alphanum_fraction": 0.5566502463, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567177, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7573293163037021}}
{"text": "using StanModels\n\ndf = CSV.read(joinpath(@__DIR__, \"..\", \"..\", \"data\", \"WaffleDivorce.csv\"), delim=';')\nmean_ma = mean(df[!, :MedianAgeMarriage])\ndf[!, :MedianAgeMarriage_s] = \n  convert(Vector{Float64},  (df[!, :MedianAgeMarriage]) .-\n    mean_ma)/std(df[!, :MedianAgeMarriage]);\n\n# Define the Stan language model\n\nm5_1s = \"\ndata {\n int < lower = 1 > N; // Sample size\n vector[N] divorce; // Predictor\n vector[N] median_age; // Outcome\n}\n\nparameters {\n real a; // Intercept\n real bA; // Slope (regression coefficients)\n real < lower = 0 > sigma; // Error SD\n}\n\nmodel {\n  # priors\n  a ~ normal(10, 10);\n  bA ~ normal(0, 1);\n  sigma ~ uniform(0, 10);\n  \n  # model\n  divorce ~ normal(a + bA*median_age , sigma);\n}\n\";\n\n# Define the Stanmodel and set the output format to :mcmcchains.\n\nsm = SampleModel(\"m5.1s\", m5_1s);\n\n# Input data for cmdstan\n\nm5_1_data = Dict(\"N\" => length(df[!, :Divorce]), \"divorce\" => df[!, :Divorce],\n    \"median_age\" => df[!, :MedianAgeMarriage_s]);\n\n# Sample using cmdstan\n\n(sample_file, log_file) = stan_sample(sm, data=m5_1_data);\n\n# Result rethinking\n\nrethinking = \"\n       mean   sd  5.5% 94.5% n_eff Rhat\na      9.69 0.22  9.34 10.03  2023    1\nbA    -1.04 0.21 -1.37 -0.71  1882    1\nsigma  1.51 0.16  1.29  1.79  1695    1\n\"\n\n# Describe the draws\nif !(sample_file == nothing)\n  chn = read_samples(sm)\n  describe(chn)\nend\n\n", "meta": {"hexsha": "806a03739af34166f2e4fc6a43a4fe782a6ce418", "size": 1352, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/05/m5.1s.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StanModels.jl-fb740163-aa3c-59c1-9c12-c3f890714cde", "max_stars_repo_head_hexsha": "16dd5f82cc418e8444ef6ac8490b4bbda3783283", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/05/m5.1s.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StanModels.jl-fb740163-aa3c-59c1-9c12-c3f890714cde", "max_issues_repo_head_hexsha": "16dd5f82cc418e8444ef6ac8490b4bbda3783283", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/05/m5.1s.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StanModels.jl-fb740163-aa3c-59c1-9c12-c3f890714cde", "max_forks_repo_head_hexsha": "16dd5f82cc418e8444ef6ac8490b4bbda3783283", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4603174603, "max_line_length": 85, "alphanum_fraction": 0.6294378698, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416412, "lm_q2_score": 0.8080672204860317, "lm_q1q2_score": 0.7573293149670047}}
{"text": "# The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.\n# \n# Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.\n\nusing ProjectEulerSolutions\n\n# Multiply using mods since only the last 10 digits matter.  Faster than the\n# bigint solution after about n > 30,000, and uses much less memory.\nfunction p048solution_mod(n::Integer=100)::Integer\n    total = 1\n    for i in 2:n\n        s = i\n        for j in 2:i\n            s = mod(s * i, 10^10)\n        end\n        total = mod(total + s, 10^10)\n    end\n    return total\nend\n\n# Trivial with Julia's BigInt support, and fast.\nfunction p048solution_bigint(n::Integer=100)::Integer\n    return mod(mapreduce(x->x^x, +, BigInt.(1:n)), 10^10)\nend\n\np048 = Problems.Problem(Dict(\"Modulus\" => p048solution_mod,\n                             \"Bigint\" => p048solution_bigint))\n\nProblems.benchmark(p048, 1000)", "meta": {"hexsha": "4a942af869c8bbbc99d2da6d0626e6828fa268ee", "size": 866, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/048.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/048.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/048.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8620689655, "max_line_length": 76, "alphanum_fraction": 0.623556582, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7573222924766083}}
{"text": "\nfunction binary_string_to_decimal(binstring)\n    total = 0\n    num_bits = length(binstring)\n    for i in 1:num_bits\n        if binstring[i] == '1'\n            total += 2^(num_bits-i)\n        end\n    end\n    total\nend\n\n# read the input data into an array (strips newlines for us)\nrows = readlines(\"input.txt\")\n\n# how many binary digits in each row\nnum_digits = length(rows[1])\n# initialize arrays to count ones and zeros\none_counts = zeros(num_digits)\nzero_counts = zeros(num_digits)\n# count ones and zeros in each position\nfor row in rows\n    for i in 1:num_digits\n        if row[i] == '1' # has to be single quotes !?\n            one_counts[i] += 1\n        else\n            zero_counts[i] += 1\n        end\n    end\nend\nprintln(\"zero counts\", zero_counts)\nprintln(\"one counts\", one_counts)\n\n# now construct binary strings depending on whether there were\n# more ones or zeros in each position\ngamma_rate = \"\"\nepsilon_rate = \"\"\n\nfor i in 1:num_digits\n    if one_counts[i] > zero_counts[i]\n        global gamma_rate *= \"1\"\n        global epsilon_rate *= \"0\"\n    else # what if they're equal??? never mind....\n        global epsilon_rate *= \"1\"\n        global gamma_rate *= \"0\"\n    end\nend\n\nprintln(\"gamma rate \", gamma_rate)\nprintln(\"epsilon rate \", epsilon_rate)\n\n# convert to decimal\ngamma_rate_dec = binary_string_to_decimal(gamma_rate)\nepsilon_rate_dec = binary_string_to_decimal(epsilon_rate)\nprintln(\"gamma rate (decimal) \",gamma_rate_dec)\nprintln(\"epsilon rate (decimal) \",epsilon_rate_dec)\n\n# multiply\nprintln(\"total power consumption \",gamma_rate_dec * epsilon_rate_dec)\n", "meta": {"hexsha": "8b942397846db89e8721753bc128859fbaaa6a9d", "size": 1577, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day-03/julia_nick/day3_part1.jl", "max_stars_repo_name": "alan-turing-institute/advent-of-code-2021", "max_stars_repo_head_hexsha": "b5f3c163464f0d9403b66147ad7d833176ed59a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2021-12-01T16:31:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T20:20:31.000Z", "max_issues_repo_path": "day-03/julia_nick/day3_part1.jl", "max_issues_repo_name": "alan-turing-institute/advent-of-code-2021", "max_issues_repo_head_hexsha": "b5f3c163464f0d9403b66147ad7d833176ed59a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day-03/julia_nick/day3_part1.jl", "max_forks_repo_name": "alan-turing-institute/advent-of-code-2021", "max_forks_repo_head_hexsha": "b5f3c163464f0d9403b66147ad7d833176ed59a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-12-03T20:07:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T00:31:39.000Z", "avg_line_length": 26.2833333333, "max_line_length": 69, "alphanum_fraction": 0.6823081801, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561135, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7573222866140127}}
{"text": "module _IncrEn\nexport IncrEn\nusing Statistics: std\n    \"\"\"\n        Incr = IncrEn(Sig) \n\n    Returns the increment entropy (`Incr`) estimate of the data sequence \n    (`Sig`) using the default parameters: \n    embedding dimension = 2, time delay = 1, quantifying resolution = 4,\n    logarithm = base 2,\n\n        Incr = IncrEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, R::Int=4, Logx::Real=2, Norm::Bool=false)\n\n    Returns the increment entropy (`Incr`) estimate of the data sequence\n    (`Sig`) using the specified 'keyword' arguments:\n\n    # Arguments:    \n    `m`     - Embedding Dimension, an integer > 1   \\n\n    `tau`   - Time Delay, a positive integer    \\n\n    `R`     - Quantifying resolution, a positive scalar    \\n\n    `Logx`  - Logarithm base, a positive scalar (enter 0 for natural log) \\n\n    `Norm`  - Normalisation of IncrEn value: \\n\n              [false]  no normalisation - default\n              [true]   normalises w.r.t embedding dimension (m-1). \n\n    # See also `PermEn`, `SyDyEn`, `MSEn`\n\n    # References:\n        [1] Xiaofeng Liu, et al.,\n            \"Increment entropy as a measure of complexity for time series.\"\n            Entropy\n            18.1 (2016): 22.1.\n\n        ***   \"Correction on Liu, X.; Jiang, A.; Xu, N.; Xue, J. - Increment \n            Entropy as a Measure of Complexity for Time Series,\n            Entropy 2016, 18, 22.\" \n            Entropy \n            18.4 (2016): 133.\n\n        [2] Xiaofeng Liu, et al.,\n            \"Appropriate use of the increment entropy for \n            electrophysiological time series.\" \n            Computers in biology and medicine \n            95 (2018): 13-23.\n\n\n    \"\"\"\n    function IncrEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, \n        R::Int=4, Logx::Real=2, Norm::Bool=false)\n\n    Logx == 0  ? Logx = exp(1) : nothing\n        \n    (size(Sig,1) > 10) ? nothing :  error(\"Sig:   must be a numeric vector\")\n    (m > 1) ? nothing :  error(\"m:     must be an integer > 1\")\n    (tau>0) ? nothing :  error(\"tau:   must be an integer > 0\")\n    (R > 0) ? nothing :  error(\"R:     must be a positive integer > 0\")\n    (Logx>0) ? nothing : error(\"Logx:  must be a positive number > 0\")\n    \n    Vi = diff(Sig)\n    N = size(Vi,1)-((m-1)*tau)\n    Vk = zeros(N,m)\n    for k = 1:m\n        Vk[:,k] = Vi[1+(k-1)*tau:N+(k-1)*tau]\n    end\n\n    Sk = sign.(Vk)\n    Temp = std(Vk,dims=2)[:]\n    Qk = min.(R, floor.((abs.(Vk)*R)./repeat(Temp,outer=(1,m))))\n    Qk[any(Temp.==0,dims=2), :] .= 0  #should that be all()\n    Wk = Sk.*Qk  \n    Wk[Wk.==-0] .= 0\n    Px = unique(Wk,dims=1)\n    Counter = zeros(Int,size(Px,1));\n    for k = 1:size(Px,1) \n        Counter[k] = sum(all(Wk .- transpose(Px[k,:]) .==0 ,dims=2))\n    end\n    Ppi = Counter/N\n\n    if size(Px,1) > (2*R + 1)^m\n        @warn(\"Error with probability estimation'\")\n    elseif round(sum(Ppi),digits=5) != 1\n        @warn(\"Error with probability estimation\")\n    end\n    Incr = -sum(Ppi.*(log.(Logx, Ppi)))\n    if Norm\n        Incr = Incr/(m-1);\n    end\n   \n    return Incr\n    end\n\nend\n\n\"\"\"\nCopyright 2021 Matthew W. Flood, EntropyHub\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nFor Terms of Use see https://github.com/MattWillFlood/EntropyHub\n\"\"\"", "meta": {"hexsha": "5ddd5709442cfe82a56e55488684c30d8004eb09", "size": 3694, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/_IncrEn.jl", "max_stars_repo_name": "MattWillFlood/EntropyHub.jl", "max_stars_repo_head_hexsha": "d681c7fad3dbddaa708391b0afef1495c7dde20d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-06-19T19:20:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T16:13:41.000Z", "max_issues_repo_path": "src/_IncrEn.jl", "max_issues_repo_name": "MattWillFlood/EntropyHub.jl", "max_issues_repo_head_hexsha": "d681c7fad3dbddaa708391b0afef1495c7dde20d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-06-16T21:57:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T01:10:46.000Z", "max_forks_repo_path": "src/_IncrEn.jl", "max_forks_repo_name": "MattWillFlood/EntropyHub.jl", "max_forks_repo_head_hexsha": "d681c7fad3dbddaa708391b0afef1495c7dde20d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-15T05:41:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T05:41:21.000Z", "avg_line_length": 33.5818181818, "max_line_length": 124, "alphanum_fraction": 0.5933946941, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7573222863006024}}
{"text": "\"\"\"\nNonnegativity-constrained proximal operator of nnz()\n    nnz_y = proxl0nonneg!( x, a, y )\nsolves the following problem\n    min_y    a nnz(y) + 1/2 ||y-x||^2    s.t.    y ≥ 0\nwhere `a` is a given nonnegative scalar.\nThe analytical expression is available:\n    y = { x  if  x ≥ √2a,  0  otherwise\n\"\"\"\nfunction proxl0nonneg!( x::Vector{R}, a::R, y::Vector{R} ) where {R <: Real}\n    @assert a >= R(0)\n    y .= x\n    if a > R(0)\n        y[.!(x .> sqrt( 2 * a ))] .= R(0)\n    else\n        y .= max.( R(0), x )\n    end\n    nnz_y = sum(y .> R(0))\n    return nnz_y\nend\n\n\"\"\"\nSimplex-constrained proximal operator of nnz()\n    nnz_y = proxl0simplex!( x, a, b, y )\nsolves the following problem\n    min_y    a nnz(y) + 1/2 ||y-x||^2    s.t.    y ≥ 0,    1 ⋅ y = b\nwhere `a` and `b` are given nonnegative scalars.\n\"\"\"\nfunction proxl0simplex!( x::Vector{R}, a::R, b::R, y::Vector{R} ) where {R <: Real}\n    @assert a >= R(0)\n    @assert b >= R(0)\n    if a == R(0)\n        projsimplex!(x, b, y)\n        nnz_y = sum(y .> R(0))\n        return nnz_y\n    end\n    n = length(x)\n    y .= x # max.( x, 0.0 ) # project\n    prm = sortperm(y) # sort\n    y .= y[prm]\n    mv = Vector(0:n-1) # number of zeros\n    lv = (b .- reverse(cumsum(reverse(y)))) ./ (n .- mv)\n    feas = (y .+ lv .> R(0)) # feasibility\n    if !any(feas)\n        m = n - 1\n        l = b - x[n]\n        #c = a + 0.5 * sum( x[1:m].^2 ) + 0.5 * (l ^ 2) # cost\n    else\n        sv = cumsum([R(0); y[1:n-1]] .^ 2)\n        mv = mv[feas]\n        lv = lv[feas]\n        sv = sv[feas]\n        cv = a .* (n .- mv) .+ 0.5 .* sv .+ 0.5 .* (n .- mv) .* (lv .^ 2) # cost\n        c, i = findmin(cv) # find minimum\n        m = mv[i]\n        l = lv[i]\n    end\n    y[1:m] .= R(0)\n    y[m+1:n] .+= l\n    nnz_y = n - m\n    y .= y[invperm(prm)] # unsort\n    return nnz_y\nend\n\n\"\"\"\nProjection onto the simplex\n    projsimplex!(x, b, y)\ncorresponds to solving the following problem\n        min_y    1/2 ||y-x||^2    s.t.    y ≥ 0,    1 ⋅ y = b\nwhere `b` is a given nonnegative scalar.\nSee arxiv.org/abs/1101.6081\n\"\"\"\nfunction projsimplex!(x::Vector{R}, b::R, y::Vector{R}) where {R <: Real}\n    @assert b >= R(0)\n    if b == R(0)\n        y .= R(0)\n        return nothing\n    end\n    n = length(x)\n    y .= sort(x, rev=true) # sort\n    flag = false\n    tmpsum = R(0)\n    for i in 1:n-1\n        tmpsum += y[i] # cumulative sum\n        tmpmax = (tmpsum - b) / i\n        if tmpmax >= y[i+1]\n            flag = true\n            break\n        end\n    end\n    if !flag\n        tmpmax = (tmpsum + y[n] - b) / n\n    end\n    y .= max.(x .- tmpmax, R(0)) # shift, project\n    return nothing\nend\n", "meta": {"hexsha": "b006ec5e6de5c6d54a3b272fb964e8162fd37aff", "size": 2608, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/l0norm.jl", "max_stars_repo_name": "aldma/ScSTO.jl", "max_stars_repo_head_hexsha": "b90b9f29bea13ff982dab1cfb295be5e79fb0989", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/l0norm.jl", "max_issues_repo_name": "aldma/ScSTO.jl", "max_issues_repo_head_hexsha": "b90b9f29bea13ff982dab1cfb295be5e79fb0989", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/l0norm.jl", "max_forks_repo_name": "aldma/ScSTO.jl", "max_forks_repo_head_hexsha": "b90b9f29bea13ff982dab1cfb295be5e79fb0989", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8865979381, "max_line_length": 83, "alphanum_fraction": 0.4858128834, "num_tokens": 1010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250325, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.75732228582332}}
{"text": "type Mean <: ContinuousUnivariateStreamStat\n    m::Float64\n    n::Int\nend\n\nMean() = Mean(0.0, 0)\n\nfunction update!(stat::Mean, x::Real)\n    stat.n += 1\n    α = 1 / stat.n\n    stat.m = (1 - α) * stat.m + α * x\n    return\nend\n\nBase.mean(stat::Mean) = stat.m\n\nstate(stat::Mean) = Base.mean(stat)\n\nnobs(stat::Mean) = stat.n\n\nBase.copy(stat::Mean) = Mean(stat.m, stat.n)\n\nfunction Base.merge(a::Mean, b::Mean)\n    m1, m2 = a.m, b.m\n    n1, n2 = a.n, b.n\n    m = (n1 / (n1 + n2)) * m1 + (n2 / (n1 + n2)) * m2\n    n = n1 + n2\n    return Mean(m, n)\nend\n\nfunction Base.empty!(stat::Mean)\n    stat.m = 0.0\n    stat.n = 0\n    return\nend\n\nfunction Base.show(io::IO, stat::Mean)\n    m = mean(stat)\n    n = nobs(stat)\n    @printf(io, \"Online Mean\\n\")\n    @printf(io, \" * Mean: %f\\n\", m)\n    @printf(io, \" * N:    %d\\n\", n)\n    return\nend\n", "meta": {"hexsha": "23813903dfd7dcaf04227712140248282757b13f", "size": 824, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mean.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StreamStats.jl-1b2943d0-825d-5907-9c5f-04e3ce562884", "max_stars_repo_head_hexsha": "63912dd90fac47151ad054d89e9668cd11911efa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 52, "max_stars_repo_stars_event_min_datetime": "2015-02-07T22:14:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T14:12:56.000Z", "max_issues_repo_path": "src/mean.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StreamStats.jl-1b2943d0-825d-5907-9c5f-04e3ce562884", "max_issues_repo_head_hexsha": "63912dd90fac47151ad054d89e9668cd11911efa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2015-02-07T22:19:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:29:52.000Z", "max_forks_repo_path": "src/mean.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StreamStats.jl-1b2943d0-825d-5907-9c5f-04e3ce562884", "max_forks_repo_head_hexsha": "63912dd90fac47151ad054d89e9668cd11911efa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2015-02-09T18:52:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-25T22:12:00.000Z", "avg_line_length": 18.3111111111, "max_line_length": 53, "alphanum_fraction": 0.5436893204, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7573222842419335}}
{"text": "function onpatch!(x::AbstractVector, v̄::PVector{T,N}) where {T,N}\n    ranges = ProjectiveVectors.dimension_indices(v̄)\n    for range in ranges\n        λ = zero(eltype(x))\n        @inbounds for i in range\n            λ += v̄[i] * x[i]\n        end\n        λ⁻¹ = @fastmath inv(λ)\n        for i in range\n            x[i] *= λ⁻¹\n        end\n    end\n    x\nend\n\nfunction evaluate_patch!(u, v̄::PVector{S,N}, x::PVector{T,N}) where {S,T,N}\n    ranges = ProjectiveVectors.dimension_indices(v̄)\n    n = length(u) - N\n    for (k, range) in enumerate(ranges)\n        out = -one(eltype(x))\n        for i in range\n            out += v̄[i] * x[i]\n        end\n        u[n+k] = out\n    end\n    nothing\nend\n\nfunction jacobian_patch!(U, v̄::PVector{S,N}, x::PVector) where {S,T,N}\n    ranges = ProjectiveVectors.dimension_indices(v̄)\n    n = size(U, 1) - N\n    for j = 1:size(U, 2), i = (n+1):size(U, 1)\n        U[i, j] = zero(eltype(U))\n    end\n    for (k, range) in enumerate(ranges)\n        for j in range\n            U[n+k, j] = v̄[j]\n        end\n    end\n    nothing\nend\n", "meta": {"hexsha": "ab31e56e33936c43174f93a95dfcb75e3ab3d64a", "size": 1057, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "v1/src/affine_patches/common.jl", "max_stars_repo_name": "mbauman/HomotopyContinuation.jl", "max_stars_repo_head_hexsha": "3253f86b2752303b0ed8616e07bccf8bfbb7f24d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "v1/src/affine_patches/common.jl", "max_issues_repo_name": "mbauman/HomotopyContinuation.jl", "max_issues_repo_head_hexsha": "3253f86b2752303b0ed8616e07bccf8bfbb7f24d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "v1/src/affine_patches/common.jl", "max_forks_repo_name": "mbauman/HomotopyContinuation.jl", "max_forks_repo_head_hexsha": "3253f86b2752303b0ed8616e07bccf8bfbb7f24d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1666666667, "max_line_length": 76, "alphanum_fraction": 0.5260170293, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561136, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7573222783793383}}
{"text": "lines = readlines(ARGS[1])\n\n\nfunction solution1(lines)\n    fishes = [parse(Int, f) for f in split(lines[1], \",\")]\n\n    for i = 1:80\n        next_gen = []\n        new_fishes = []\n        for fish in fishes\n            if fish == 0\n                append!(new_fishes, 8)\n                append!(next_gen, 6)\n            else\n                append!(next_gen, fish - 1)\n            end\n\n        end\n        append!(next_gen, new_fishes)\n        fishes = next_gen\n    end\n    println(length(fishes))\nend\n\nfunction solution2(lines)\n    fishes = [parse(Int8, f) for f in split(lines[1], \",\")]\n    fish_dict = Dict()\n    for fish in fishes\n        if fish in keys(fish_dict)\n            fish_dict[fish] += 1\n        else\n            fish_dict[fish] = 1\n        end\n    end\n    println(fish_dict)\n    for i = 1:256\n        next_gen = Dict()\n        if 0 in keys(fish_dict)\n            next_gen[8] = fish_dict[0]\n        end\n\n        for fish_key in keys(fish_dict)\n            if fish_key != 0\n                next_gen[fish_key-1] = fish_dict[fish_key]\n            end\n        end\n        if 6 in keys(next_gen)\n            if 0 in keys(fish_dict)\n                next_gen[6] += fish_dict[0]\n            end\n        else\n            if 0 in keys(fish_dict)\n                next_gen[6] = fish_dict[0]\n            end\n        end\n\n        fish_dict = next_gen\n        println(i, \":\", sum([value for value in values(fish_dict)]))\n    end\n    println(sum([value for value in values(fish_dict)]))\nend\n\nsolution1(lines)\n\nsolution2(lines)", "meta": {"hexsha": "4f60e3703fcc9fe12ff384bfe4b62c342304f84c", "size": 1523, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day6/solution.jl", "max_stars_repo_name": "zeenewton/aoc2021", "max_stars_repo_head_hexsha": "b95e6385d8f05420e54661c85cf6809674db80e3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day6/solution.jl", "max_issues_repo_name": "zeenewton/aoc2021", "max_issues_repo_head_hexsha": "b95e6385d8f05420e54661c85cf6809674db80e3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day6/solution.jl", "max_forks_repo_name": "zeenewton/aoc2021", "max_forks_repo_head_hexsha": "b95e6385d8f05420e54661c85cf6809674db80e3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4307692308, "max_line_length": 68, "alphanum_fraction": 0.508864084, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7573206852360924}}
{"text": "using Turing\nusing Distributions\nusing Random\nusing LinearAlgebra\nusing StatsPlots\nusing MCMCChains\nusing DataFrames\nusing Printf\n\n# geberate moc data from logit model\nn = 1_000\nnum_var = 2\nRandom.seed!(99)\nX = rand(Uniform(-sqrt(3.0), 2.0*sqrt(3.0)), n, num_var) # case-specific variables Z_i Matrix\nX = [ones(n) X]\nβ = Vector([0.0, 0.5, -0.5]) # true coefficients\n# ポアソン分布の平均をモデル化\nλ = exp.(X*β)\ny = rand.(Poisson.(λ)) # observable choice 0 or 1\n\n# set prior, β ~ MvNormal(β0, A0), no σ²\nn, k = size(X)\nβ0 = zeros(k)\nA0 = 0.01 * I\n\n@model function poisson_regression_model(X, y)\n    # Set the priors only for β.\n    β ~ MvNormal(β0, inv(A0))\n\n    # Write the likelihood, can't vectorize?\n    n = size(X, 1)\n    for i = 1:n\n        y[i] ~ Poisson(exp(X[i, :]' * β))\n    end\nend\n\n# Draw random number from posterior.\nmodel = poisson_regression_model(X, y)\n\nn_draws = 5_000\n# n_chains = 4\nn_chains = 1\nn_tune = 1_000\nchn = sample(model, NUTS(), MCMCThreads(), n_draws, n_chains; discard_adapt=false)\nplot(chn)\n# chn = sample(model, NUTS(), MCMCThreads(), n_draws, n_chains)[n_tune:n_draws, :, :]\nβ_chn = chn[n_tune+1:n_draws, :, :] # delete initial and exclude odd (hamiltonian bluh bluh) chain \nβ_chn = group(β_chn, :β)\n\nsummarize(β_chn)\nquantile(β_chn)\nplot(β_chn)\n\n# Marginal effect ... interpret β just like as ln(y) = βx model (equivalent with λ = exp(x))", "meta": {"hexsha": "c31e312730f9970d978d81c3102cf5dc6d08ac01", "size": 1358, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jlbayes_mcmc_poisson.jl", "max_stars_repo_name": "hessihan/julia_bayes_intro", "max_stars_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jlbayes_mcmc_poisson.jl", "max_issues_repo_name": "hessihan/julia_bayes_intro", "max_issues_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jlbayes_mcmc_poisson.jl", "max_forks_repo_name": "hessihan/julia_bayes_intro", "max_forks_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1481481481, "max_line_length": 99, "alphanum_fraction": 0.6789396171, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7573206756092519}}
{"text": "########################################################################################\n# Integrated Brownian Motion\n########################################################################################\n\"\"\"\n    ibm(d::Integer, q::Integer, elType=typeof(1.0))\n\nGenerate the discrete dynamics for a q-IBM model. INCLUDES AUTOMATIC PRECONDITIONING!\n\"\"\"\nfunction ibm(d::Integer, q::Integer, elType=typeof(1.0))\n    # Make A\n    A_breve = zeros(elType, q + 1, q + 1)\n    @simd ivdep for j in 1:q+1\n        @simd ivdep for i in 1:j\n            @inbounds A_breve[i, j] = binomial(q - i + 1, q - j + 1)\n        end\n    end\n    A = kron(I(d), A_breve)\n    @assert istriu(A)\n    # A = UpperTriangular(A)\n\n    # Make Q\n    Q_breve = zeros(elType, q + 1, q + 1)\n    @fastmath _transdiff_ibm_element(row::Int, col::Int) =\n        one(elType) / (2 * q + 1 - row - col)\n    @simd ivdep for col in 0:q\n        @simd ivdep for row in 0:q\n            val = _transdiff_ibm_element(row, col)\n            @inbounds Q_breve[1+row, 1+col] = val\n        end\n    end\n    QL_breve = cholesky!(Q_breve).L\n    QL = kron(I(d), QL_breve)\n    Q = SRMatrix(QL)\n\n    return A, Q\nend\n\n\"\"\"Same as above, but without the automatic preconditioning\"\"\"\nfunction vanilla_ibm(d::Integer, q::Integer)\n    @fastmath function A!(A::AbstractMatrix, h::Real)\n        # Assumes that A comes from a previous computation => zeros and one-diag\n        val = one(h)\n        for i in 1:q\n            val = val * h / i\n            for k in 0:d-1\n                for j in 1:q+1-i\n                    @inbounds A[j+k*(q+1), j+k*(q+1)+i] = val\n                end\n            end\n        end\n    end\n\n    @fastmath function _transdiff_ibm_element(row::Int, col::Int, h::Real)\n        idx = 2 * q + 1 - row - col\n        fact_rw = factorial(q - row)\n        fact_cl = factorial(q - col)\n        return h^idx / (idx * fact_rw * fact_cl)\n    end\n    @fastmath function Q!(Q::AbstractMatrix, h::Real, σ²::Real=1.0)\n        val = one(h)\n        @simd for col in 0:q\n            @simd for row in col:q\n                val = _transdiff_ibm_element(row, col, h) * σ²\n                @simd for i in 0:d-1\n                    @inbounds Q[1+col+i*(q+1), 1+row+i*(q+1)] = val\n                    @inbounds Q[1+row+i*(q+1), 1+col+i*(q+1)] = val\n                end\n            end\n        end\n    end\n\n    return A!, Q!\nend\n", "meta": {"hexsha": "c40f96a0e0e25725dbcd0c4cbddc48bd6ac047b0", "size": 2359, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/priors.jl", "max_stars_repo_name": "nathanaelbosch/ProbNumDiffEq.jl", "max_stars_repo_head_hexsha": "82aa8e911e0f0987b0ddb61e0e7d3ee325d3150a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 57, "max_stars_repo_stars_event_min_datetime": "2021-02-17T21:42:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T23:37:35.000Z", "max_issues_repo_path": "src/priors.jl", "max_issues_repo_name": "nathanaelbosch/ProbNumDiffEq.jl", "max_issues_repo_head_hexsha": "82aa8e911e0f0987b0ddb61e0e7d3ee325d3150a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 90, "max_issues_repo_issues_event_min_datetime": "2021-02-18T00:57:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T20:44:20.000Z", "max_forks_repo_path": "src/priors.jl", "max_forks_repo_name": "nathanaelbosch/ProbNumDiffEq.jl", "max_forks_repo_head_hexsha": "82aa8e911e0f0987b0ddb61e0e7d3ee325d3150a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2021-02-23T06:36:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:15:25.000Z", "avg_line_length": 31.8783783784, "max_line_length": 88, "alphanum_fraction": 0.4896142433, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7573075809804432}}
{"text": "using DifferentialEquations, Plots\n\n#Reference: https://diego.assencio.com/?index=e5ac36fcb129ce95a61f8e8ce0572dbf\n\n\n#Solving the double pendulum with a traditional ODE method\n#==========================================================#\nfunction doublependulum(du, u, params, t)\n    l1 = params[1]\n    l2 = params[2]\n    m1 = params[3]\n    m2 = params[4]\n    g  = params[5]\n\n    p1 = u[1]\n    p2 = u[2]\n    θ1 = u[3]\n    θ2 = u[4]\n\n    h1 = p1*p2*sin(θ1-θ2)/(l1*l2*(m1+m2*sin(θ1-θ2)^2))\n    h2 = (m2*l2^2*p1^2 + (m1 + m2) * l1^2 * p2^2 - 2*m2*l1*l2*p1*p2*cos(θ1-θ2))/(2 * l1^2 * l2^2 *(m1 + m2*sin(θ1-θ2)^2)^2)\n\n    d_p1 = -(m1 + m2)* g*l1*sin(θ1) - h1 + h2*sin(2*(θ1-θ2))\n    d_θ1 = (l2*p1 - l1*p2*cos(θ1-θ2))/(l1^2 * l2*(m1 + m2*sin(θ1 - θ2)^2))\n    d_p2 = -m2*g*l2*sin(θ2) + h1 - h2*sin(2*(θ1-θ2))\n    d_θ2 = (-m2*l2*p1*cos(θ1 - θ2) + (m1 + m2)*l1*p2) / (m2*l1*l2^2*(m1 + m2*sin(θ1-θ2)^2))\n\n\n    du .= [d_p1, d_p2, d_θ1, d_θ2]\n    return nothing\nend\n\nl1 = 1. #length of pendulum1\nl2 = 2. #length of pendulum2\nm1 = 1. #mass of pendulum1\nm2 = 1. #mass of pendulum2\ng = 9.81 #gravity\n\nparams = [l1, l2, m1, m2, g]\ntimes = (0., 25.)\nu0 = [1.,1.,1.,1.]\nprob = ODEProblem(doublependulum, u0, times, params)\nsol1 = solve(prob, AutoVern7(Rodas5()), dt = .005)\n\n#plot solution\nplot(sol1, vars=1, xlim=(0,20), label=\"Momentum1\")\nplot!(sol1, vars=2, xlim=(0,20), label=\"Momentum2\")\nplot!(sol1, vars=3, xlim=(0,20), label=\"theta1\")\nplot!(sol1, vars=4, xlim=(0,20), label=\"theta2\")\n#==========================================================#\n\n\n#Now with HamiltonianProblem()\n#==========================================================#\nfunction H(p, θ, params)\n    l1 = params[1]\n    l2 = params[2]\n    m1 = params[3]\n    m2 = params[4]\n    g  = params[5]\n\n    return  (m2*l2^2*p[1]^2 + (m1+m2)*l1^2*p[2]^2 - 2*m2*l1*l2*p[1]*p[2]*cos(θ[1]-θ[2]) ) /\n        (2*m2*l1^2*l2^2*(m1+m2*sin(θ[1]-θ[2])^2)) -\n        (m1+m2)*g*l1*cos(θ[1]) - m2*g*l2*cos(θ[2])\nend\n\nl1 = 1. #length of pendulum1\nl2 = 2. #length of pendulum2\nm1 = 1. #mass of pendulum1\nm2 = 1. #mass of pendulum2\ng = 9.81 #gravity\n\nparams = [l1, l2, m1, m2, g]\nq0 = [1.0,1.0]\np0 = [1.0,1.0]\ntimes = (0.,25.)\nprob = HamiltonianProblem(H, q0, p0, times, params)\nsol2 = solve(prob, SofSpa10(), dt = .05)\n\nplot(sol2, vars=1, xlim=(0,20), label=\"Momentum1\")\nplot!(sol2, vars=2, xlim=(0,20), label=\"Momentum2\")\nplot!(sol2, vars=3, xlim=(0,20), label=\"theta1\")\nplot!(sol2, vars=4, xlim=(0,20), label=\"theta2\")\n#==========================================================#\n\n\n#Animation\n#==========================================================#\nfunction make_pretty_gif(sol)\n    timepoints = sol.t\n\n    x1 = l1*sin.(sol[3,:])\n    y1 = -l1*cos.(sol[3,:])\n    x2 = x1 + l2*sin.(sol[4,:])\n    y2 = y1 - l2*cos.(sol[4,:])\n\n    axis_lim = (l1+l2)*1.2\n\n    anim = Animation()\n    for i =1:length(timepoints)\n        str = string(\"Time = \", round(timepoints[i],digits=1), \" sec\")\n        plot([0,x1[i]], [0,y1[i]], size=(400,300), xlim=(-axis_lim,axis_lim), ylim=(-axis_lim,1), markersize = 10, markershape = :circle,label =\"\",axis = [])\n        plot!([x1[i],x2[i]], [y1[i],y2[i]], markersize = 10, markershape = :circle,label =\"\",title = str, title_location = :left)\n\n        if i > 8 #rainbow trail\n            plot!([x2[i-2:i]],   [y2[i-2:i]],  alpha = 0.15, linewidth = 2, color = :red, label=nothing)\n            plot!([x2[i-3:i-2]], [y2[i-3:i-2]],alpha = 0.15, linewidth = 2, color = :orange, label=nothing)\n            plot!([x2[i-4:i-3]], [y2[i-4:i-3]],alpha = 0.15, linewidth = 2, color = :yellow, label=nothing)\n            plot!([x2[i-6:i-4]], [y2[i-6:i-4]],alpha = 0.15, linewidth = 2, color = :green, label=nothing)\n            plot!([x2[i-7:i-6]], [y2[i-7:i-6]],alpha = 0.15, linewidth = 2, color = :blue, label=nothing)\n            plot!([x2[i-8:i-7]], [y2[i-8:i-7]],alpha = 0.15, linewidth = 2, color = :purple, label=nothing)\n        end\n        frame(anim)\n    end\n    gif(anim, fps = 30)\nend\n\nmake_pretty_gif(sol1)\nmake_pretty_gif(sol2)\n", "meta": {"hexsha": "04e029e61dd4fce9bb239420cd52791f77aab6b9", "size": 3989, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/double_pendulum.jl", "max_stars_repo_name": "KlausC/DiffEqPhysics.jl", "max_stars_repo_head_hexsha": "9aa27ba987794c724247f5450b8598607342bd93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2017-04-14T19:38:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-06T20:12:48.000Z", "max_issues_repo_path": "examples/double_pendulum.jl", "max_issues_repo_name": "KlausC/DiffEqPhysics.jl", "max_issues_repo_head_hexsha": "9aa27ba987794c724247f5450b8598607342bd93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2017-04-14T17:13:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-10T12:19:20.000Z", "max_forks_repo_path": "examples/double_pendulum.jl", "max_forks_repo_name": "KlausC/DiffEqPhysics.jl", "max_forks_repo_head_hexsha": "9aa27ba987794c724247f5450b8598607342bd93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2017-05-08T20:31:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:36:46.000Z", "avg_line_length": 33.2416666667, "max_line_length": 157, "alphanum_fraction": 0.5229380797, "num_tokens": 1643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7573075737417025}}
{"text": "# Multivariate regression\nusing Turing\nusing Distributions\nusing Random\nusing LinearAlgebra\nusing StatsPlots\n\n# Generate moc data\nn = 50\ndim = 5\nRandom.seed!(99)\nu = rand(Normal(0, 0.7), n) # true value σ² = 0.49\nx = rand(Uniform(-sqrt(3.0), sqrt(3.0)), n, dim) # x generated from Uniform[-√3, √3]\nX = [ones(n) x] # dependent variable matrix with ones\nβ = Vector(1:1:dim+1) # true coefficients\ny = X*β + u # true data generating process\n\n# set prior (normal for β, InverseGamma for σ²)\nk = size(X)[2]\nβ0 = zeros(k)\nτ0 = 0.2\nA0 = τ0 * I # Identity matrix\nν0 = 5.0\nλ0 = 7.0\n# H0 = (λ0 / ν0) * inv(A0) # scale matrix for marginal prior of multivariate coefficient (mv Tdist)\n# h0 = diag(sqrt(Matrix(H0, k, k))) # scale params for marginal prior of single coefficient (T dist) H0の対角成分\nsd0 = diag(sqrt(Matrix(A0, k, k))) # the parameter for conditional prior for β|σ² ~ N_k(β0, σ²*inv(A0)), (inv(A0) part)\n\n@model function multiple_regression(X, y)    \n    # Set variance priors\n    σ² ~ InverseGamma(ν0/2, λ0/2)\n\n    # Set the priors on our coefficients. (No conditions about σ²)\n    nfeatures = size(X, 2)\n    β ~ MvNormal(β0, inv(A0))\n\n    # Write likelihood.\n    y ~ MvNormal(X * β, σ² * I)\nend\n\n# Draw random number from posterior.\nmodel = multiple_regression(X, y)\n\nn_draws = 5_000\nn_chains = 4\nn_tune = 1_000\nchn = sample(model, NUTS(), MCMCThreads(), n_draws, n_chains)\nprint(summarize(chn))\nprint(quantile(chn))\nplot(chn)\n\n# # Analytical Solution\nprint(\"Analytical Solution \\n\")\nprint(inv(X' * X) * X' * y)", "meta": {"hexsha": "8a275662d5a897aba661dec0652b04064a0c32e8", "size": 1510, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jlbayes_mcmc_reg_ex3.jl", "max_stars_repo_name": "hessihan/julia_bayes_intro", "max_stars_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jlbayes_mcmc_reg_ex3.jl", "max_issues_repo_name": "hessihan/julia_bayes_intro", "max_issues_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jlbayes_mcmc_reg_ex3.jl", "max_forks_repo_name": "hessihan/julia_bayes_intro", "max_forks_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.962962963, "max_line_length": 119, "alphanum_fraction": 0.6754966887, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7573075702869411}}
{"text": "using AbstractAlgebra # implements arbitrary precision rationals\n\ntanplus(x,y) = (x + y) / (1 - x * y)\n\nfunction taneval(coef, frac)\n    if coef == 0\n        return 0\n    elseif coef < 0\n        return -taneval(-coef, frac)\n    elseif isodd(coef)\n        return tanplus(frac, taneval(coef - 1, frac))\n    else\n        x = taneval(div(coef, 2), frac)\n        return tanplus(x, x)\n    end\nend\n\ntaneval(tup::Tuple) = taneval(tup[1], tup[2])\n\ntans(v::Vector{Tuple{BigInt, Rational{BigInt}}}) = foldl(tanplus, map(taneval, v), init=0)\n\nconst testmats = Dict{Vector{Tuple{BigInt, Rational{BigInt}}}, Bool}([\n    ([(1, 1//2), (1, 1//3)], true), ([(2, 1//3), (1, 1//7)], true),\n    ([(12, 1//18), (8, 1//57), (-5, 1//239)], true),\n    ([(88, 1//172), (51, 1//239), (32, 1//682), (44, 1//5357), (68, 1//12943)], true),\n    ([(88, 1//172), (51, 1//239), (32, 1//682), (44, 1//5357), (68, 1//12944)], false)])\n\n\nfunction runtestmats()\n    println(\"Testing matrices:\")\n    for (k, m) in testmats\n        ans = tans(k)\n        println((ans == 1) == m ? \"Verified as $m: \" : \"Not Verified as $m: \", \"tan $k = $ans\")\n    end\nend\n\nruntestmats()\n", "meta": {"hexsha": "3f1e652c74c81a46c40a327b0802570111c6dfd8", "size": 1129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/check-machin-like-formulas.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/check-machin-like-formulas.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/check-machin-like-formulas.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7105263158, "max_line_length": 95, "alphanum_fraction": 0.5465013286, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7573075673256011}}
{"text": "\nfunction sphereFunc(x::AbstractArray)\n    return sum(x.^2)\nend\n\nfunction rosenbrockfunc(x::AbstractVector)\n    sum = 0.0\n    for i in 1:length(x) - 1\n        sum += 100*(x[i + 1] - x[i]^2)^2 + (x[i] - 1)^2\n    end\n    return sum\nend\n\nfunction rastriginfunc(x::AbstractVector)\n    d = length(x)\n\n    sum = 0.0\n    for i in 1:d\n        sum += (x[i]^2 - 10*cos(2*π*x[i]))\n    end\n    return 10*d + sum\nend\n\nfunction ackleyfunc(x::AbstractVector)\n    a = 20\n    b = 0.2\n    c = 2*π\n    d = length(x)\n\n    sum1 = 0.0\n    sum2 = 0.0\n    for i in 1:d\n        sum1 += x[i]^2\n        sum2 += cos(c*x[i])\n    end\n    return -a*exp(-b*sqrt(sum1/d))  - exp(sum2/d) + a + exp(1)\nend", "meta": {"hexsha": "35befa38283debb4edc872f0918a3d26270a3fe1", "size": 670, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testProblems.jl", "max_stars_repo_name": "GrantHecht/Heuristics.jl", "max_stars_repo_head_hexsha": "ee366be7360cef34d939316b7885a15ff4b7eb10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-15T02:43:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T02:43:09.000Z", "max_issues_repo_path": "test/testProblems.jl", "max_issues_repo_name": "GrantHecht/Heuristics.jl", "max_issues_repo_head_hexsha": "ee366be7360cef34d939316b7885a15ff4b7eb10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-08-30T19:19:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-22T15:20:55.000Z", "max_forks_repo_path": "test/testProblems.jl", "max_forks_repo_name": "GrantHecht/Heuristics.jl", "max_forks_repo_head_hexsha": "ee366be7360cef34d939316b7885a15ff4b7eb10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.1081081081, "max_line_length": 62, "alphanum_fraction": 0.523880597, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.75730756600954}}
{"text": "#<---- correlation Coefficient --->\n\"\"\"\n    # Description\n      A correlation coefficient is a statistical value that can be used to\n      determine statistical correlation.\\n\n      --------------------\\n\n    # Input\n      correlationcoeff(x, y)\\n\n      --------------------\\n\n      ## Positional Arguments\n      x:: An array of values representing the general population.\\n\n      y:: An array of values representing the sample population.\\n\n      --------------------\\n\n     # Output\n     r:: The correlation coefficient.\n       \"\"\"\nfunction correlationcoeff(x,y)\n    n = length(x)\n    yl = length(y)\n    if n != yl\n        throw(ArgumentError(\"The array shape does not match!\"))\n    end\n    xy = x .* y\n    sx = sum(x)\n    sy = sum(y)\n    sxy = sum(xy)\n    x2 = x .^ 2\n    y2 = y .^ 2\n    sx2 = sum(x2)\n    sy2 = sum(y2)\n    ((n*sxy) - (sx * sy)) / (sqrt((((n*sx2)-(sx^2)) * ((n*sy2)-(sy^2)))))\nend\n\"\"\"\n    # Two Tailed Test\n    ### Description\n      The TwoTailed function takes a distribution, a sample, and a confidence\n          level, and will return a P value reflecting the probability of\n          statistical significance.\\n\n      --------------------\\n\n    ### Input\n      TwoTailed(Distribution, sample; c)\\n\n      --------------------\\n\n      #### Positional Arguments\n      Lathe Distribution - Distribution:: A Lathe Distribution.\\n\n      Array{Any} - sample:: An array of values representing the sample that should be\n       tested.\\n\n       #### Key-word Arguments\\n\n       Float64 - c:: Level of confidence for a given test in decimal form of a\n       percentage.\\n\n      --------------------\\n\n     ### Output\n     T:: Bool type representing as to whether or not P <= a && P >= -a.\n       \"\"\"\nfunction TwoTailed(dist::Distribution, sample; c = .95)\n    a = 1 - c\n    t = dist.apply(sample)\n    v = dist.N - 1\n    P = Real(dist.cdf(t, v))\n    println(P)\n    if P <= a && P >= - a\n            return(true)\n        else\n            return(false)\n    end\nend\n\"\"\"\n    One Tailed Test -- NOT IMPLEMENTED (0.1.4)\n    # Description\n      The OneTailed test function takes a distribution, a sample, and a\n          confidence\n          level, and will return a P value reflecting the probability of\n          statistical significance.\\n\n      --------------------\\n\n    # Input\n      OneTailed(Distribution, sample; c)\\n\n      --------------------\\n\n      #### Positional Arguments\n      Lathe Distribution - Distribution:: A Lathe Distribution.\\n\n      Array{Any} - sample:: An array of values representing the sample that should be\n       tested.\\n\n       #### Key-word Arguments\\n\n       Float64 - c:: Level of confidence for a given test in decimal form of a\n       percentage.\\n\n      --------------------\\n\n     # Output\n     P:: P value representing the probability of A <= P >= - A\n       \"\"\"\nfunction OneTailed(dist, sample; c = .95)\n  a = 1 - c\n  t = dist.apply(sample)\n  v = dist.N - 1\n  P = Real(dist.cdf(t, v))\n  println(P)\n  if P <= a\n        return(true)\n    else\n        return(false)\nend\nend\n\"\"\"\n    Probability\\n\n    # Description\n    The P() function takes a distribution, sample, and confidence level and\n    will return the corresponding probability value.\n      --------------------\\n\n    # Input\n      OneTailed(Distribution, sample; c)\\n\n      --------------------\\n\n      #### Positional Arguments\n      Lathe Distribution - Distribution:: A Lathe Distribution.\\n\n      Array{Any} - sample:: An array of values representing the sample that should be\n       tested.\\n\n       #### Key-word Arguments\\n\n       Float64 - c:: Level of confidence for a given test in decimal form of a\n       percentage.\\n\n      --------------------\\n\n     # Output\n     P:: P value representing probability.\n       \"\"\"\nP(dist, sample; c = .95) = dist.cdf(dist.apply(sample), dist.N - 1)\n", "meta": {"hexsha": "a4af5756a2235f800e30d91683495e44df683089", "size": 3801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stats/inferential.jl", "max_stars_repo_name": "emmettgb/Lathe.jl", "max_stars_repo_head_hexsha": "524d3ef15326e6ca356ca2d1152b64578fe5b95e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 51, "max_stars_repo_stars_event_min_datetime": "2019-10-23T12:19:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T17:02:35.000Z", "max_issues_repo_path": "src/stats/inferential.jl", "max_issues_repo_name": "emmettgb/Lathe.jl", "max_issues_repo_head_hexsha": "524d3ef15326e6ca356ca2d1152b64578fe5b95e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-05-18T14:51:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-30T21:35:48.000Z", "max_forks_repo_path": "src/stats/inferential.jl", "max_forks_repo_name": "emmettgb/Lathe.jl", "max_forks_repo_head_hexsha": "524d3ef15326e6ca356ca2d1152b64578fe5b95e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-11-02T12:05:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-21T02:25:19.000Z", "avg_line_length": 31.4132231405, "max_line_length": 85, "alphanum_fraction": 0.5527492765, "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333003, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7573075656803218}}
{"text": "julia> [1 2 3 ; 4 5 6]  # a 2x3 matrix\n2x3 Array{Int64,2}:\n 1  2  3\n 4  5  6\n\njulia> [1 2 3 ; 4 5 6]'  # note the quote\n3x2 LinearAlgebra.Adjoint{Int64,Array{Int64,2}}:\n 1  4\n 2  5\n 3  6\n", "meta": {"hexsha": "60c02f4a2c72badf0168b3420b146d9b200df68a", "size": 187, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/matrix-transposition.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/matrix-transposition.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/matrix-transposition.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0, "max_line_length": 48, "alphanum_fraction": 0.5828877005, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7573075622255606}}
{"text": "# functions related to beta distributions\n\n# R implementations\n# For pdf and logpdf we use the Julia implementation\nusing .RFunctions:\n    betacdf,\n    betaccdf,\n    betalogcdf,\n    betalogccdf,\n    betainvcdf,\n    betainvccdf,\n    betainvlogcdf,\n    betainvlogccdf\n\n# Julia implementations\nbetapdf(α::Real, β::Real, x::Real) = exp(betalogpdf(α, β, x))\n\nbetalogpdf(α::Real, β::Real, x::Real) = betalogpdf(promote(α, β, x)...)\nfunction betalogpdf(α::T, β::T, x::T) where {T<:Real}\n    # we ensure that `log(x)` and `log1p(-x)` do not error\n    y = clamp(x, 0, 1)\n    val = xlogy(α - 1, y) + xlog1py(β - 1, -y) - logbeta(α, β)\n    return x < 0 || x > 1 ? oftype(val, -Inf) : val\nend\n", "meta": {"hexsha": "6328c4ecc9ef7d5f6463664e917a33af9aa95984", "size": 681, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distrs/beta.jl", "max_stars_repo_name": "oschulz/StatsFuns.jl", "max_stars_repo_head_hexsha": "7f45786c22d60c8a1fa01005642253594e17dfed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 190, "max_stars_repo_stars_event_min_datetime": "2015-07-26T02:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T02:30:17.000Z", "max_issues_repo_path": "src/distrs/beta.jl", "max_issues_repo_name": "oschulz/StatsFuns.jl", "max_issues_repo_head_hexsha": "7f45786c22d60c8a1fa01005642253594e17dfed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 110, "max_issues_repo_issues_event_min_datetime": "2015-08-18T16:34:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T17:36:11.000Z", "max_forks_repo_path": "src/distrs/beta.jl", "max_forks_repo_name": "oschulz/StatsFuns.jl", "max_forks_repo_head_hexsha": "7f45786c22d60c8a1fa01005642253594e17dfed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 50, "max_forks_repo_forks_event_min_datetime": "2015-08-06T14:28:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T22:28:36.000Z", "avg_line_length": 27.24, "max_line_length": 71, "alphanum_fraction": 0.6328928047, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322215, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7572955195474252}}
{"text": "@doc raw\"\"\"\n    Euclidean{T<:Tuple,𝔽} <: Manifold\n\nEuclidean vector space.\n\n# Constructor\n\n    Euclidean(n)\n\nGenerate the $n$-dimensional vector space $ℝ^n$.\n\n    Euclidean(n₁,n₂,...,nᵢ; field=ℝ)\n    𝔽^(n₁,n₂,...,nᵢ) = Euclidean(n₁,n₂,...,nᵢ; field=𝔽)\n\nGenerate the vector space of $k = n_1 \\cdot n_2 \\cdot … \\cdot n_i$ values, i.e. the\nmanifold $𝔽^{n_1, n_2, …, n_i}$ whose\nelements are interpreted as $n_1 × n_2 × … × n_i$ arrays.\nFor $i=2$ we obtain a matrix space.\nThe default `field=ℝ` can also be set to `field=ℂ`.\nThe dimension of this space is $k \\dim_ℝ 𝔽$, where $\\dim_ℝ 𝔽$ is the\n[`real_dimension`](@ref) of the field $𝔽$.\n\"\"\"\nstruct Euclidean{N,𝔽} <: Manifold where {N<:Tuple, 𝔽<:AbstractNumbers} end\n\nfunction Euclidean(n::Vararg{Int,I}; field::AbstractNumbers = ℝ) where {I}\n    return Euclidean{Tuple{n...},field}()\nend\n\n^(𝔽::AbstractNumbers, n) = Euclidean(n...; field = 𝔽)\n\n\"\"\"\n    EuclideanMetric <: RiemannianMetric\n\nA general type for any manifold that employs the Euclidean Metric, for example\nthe [`Euclidean`](@ref) manifold itself, or the [`Sphere`](@ref), where every\ntangent space (as a plane in the embedding) uses this metric (in the embedding).\n\nSince the metric is independent of the field type, this metric is also used for\nthe Hermitian metrics, i.e. metrics that are analogous to the `EuclideanMetric`\nbut where the field type of the manifold is `ℂ`.\n\nThis metric is the default metric for example for the [`Euclidean`](@ref) manifold.\n\"\"\"\nstruct EuclideanMetric <: RiemannianMetric end\n\n^(M::Euclidean, n::Int) = ^(M, (n,))\nfunction ^(::Euclidean{T,𝔽}, n::NTuple{N,Int}) where {T,𝔽,N}\n    return Euclidean{Tuple{T.parameters...,n...},𝔽}()\nend\n\nfunction allocation_promotion_function(\n    M::Euclidean{<:Tuple,ℂ},\n    ::Union{typeof(get_vector),typeof(get_coordinates)},\n    args::Tuple,\n)\n    return complex\nend\n\nfunction check_manifold_point(M::Euclidean{N,𝔽}, p) where {N,𝔽}\n    if (𝔽 === ℝ) && !(eltype(p) <: Real)\n        return DomainError(\n            eltype(p),\n            \"The matrix $(p) is not a real-valued matrix, so it does not lie on $(M).\",\n        )\n    end\n    if (𝔽 === ℂ) && !(eltype(p) <: Real) && !(eltype(p) <: Complex)\n        return DomainError(\n            eltype(p),\n            \"The matrix $(p) is neither a real- nor complex-valued matrix, so it does not lie on $(M).\",\n        )\n    end\n    if size(p) != representation_size(M)\n        return DomainError(\n            size(p),\n            \"The matrix $(p) does not lie on $(M), since its dimensions ($(size(p))) are wrong (expected: $(representation_size(M))).\",\n        )\n    end\nend\n\nfunction check_tangent_vector(M::Euclidean{N,𝔽}, p, X; check_base_point = true, kwargs...) where {N,𝔽}\n    if check_base_point\n        mpe = check_manifold_point(M, p; kwargs...)\n        mpe === nothing || return mpe\n    end\n    if (𝔽 === ℝ) && !(eltype(X) <: Real)\n        return DomainError(\n            eltype(X),\n            \"The matrix $(X) is not a real-valued matrix, so it can not be a tangent vector to $(p) on $(M).\",\n        )\n    end\n    if (𝔽 === ℂ) && !(eltype(X) <: Real) && !(eltype(X) <: Complex)\n        return DomainError(\n            eltype(X),\n            \"The matrix $(X) is neither a real- nor complex-valued matrix, so it can not be a tangent vector to $(p) on $(M).\",\n        )\n    end\n    if size(X) != representation_size(M)\n        return DomainError(\n            size(X),\n            \"The matrix $(X) does not lie in the tangent space of $(p) on $(M), since its dimensions $(size(X)) are wrong  (expected: $(representation_size(M))).\",\n        )\n    end\nend\n\ndet_local_metric(M::MetricManifold{<:Manifold,EuclideanMetric}, p) = one(eltype(p))\n\n\"\"\"\n    distance(M::Euclidean, p, q)\n\nCompute the Euclidean distance between two points on the [`Euclidean`](@ref)\nmanifold `M`, i.e. for vectors it's just the norm of the difference, for matrices\nand higher order arrays, the matrix and ternsor Frobenius norm, respectively.\n\"\"\"\ndistance(::Euclidean, p, q) = norm(p .- q)\n\n@doc raw\"\"\"\n    exp(M::Euclidean, p, X)\n\nCompute the exponential map on the [`Euclidean`](@ref) manifold `M` from `p` in direction\n`X`, which in this case is just\n````math\n\\exp_p X = p + X.\n````\n\"\"\"\nexp(::Euclidean, ::Any...)\n\nexp!(M::Euclidean, q, p, X) = (q .= p .+ X)\n\n\"\"\"\n    flat(M::Euclidean, p, X)\n\nTransform a tangent vector `X` into a cotangent. Since they can directly be identified in the\n[`Euclidean`](@ref) case, this yields just the identity for a tangent vector `w` in the\ntangent space of `p` on `M`.\n\"\"\"\nflat(::Euclidean, ::Any...)\n\nflat!(M::Euclidean, ξ::CoTFVector, p, X::TFVector) = copyto!(ξ, X)\n\nfunction get_basis(M::Euclidean{<:Tuple,ℝ}, p, B::DefaultOrthonormalBasis)\n    vecs = [_euclidean_basis_vector(p, i) for i in eachindex(p)]\n    return CachedBasis(B,vecs)\nend\nfunction get_basis(M::Euclidean{<:Tuple,ℂ}, p, B::DefaultOrthonormalBasis)\n    vecs = [_euclidean_basis_vector(p, i) for i in eachindex(p)]\n    return CachedBasis(B,[vecs; im * vecs])\nend\nfunction get_basis(M::Euclidean, p, B::DiagonalizingOrthonormalBasis)\n    vecs = get_vectors(M, p, get_basis(M, p, DefaultOrthonormalBasis()))\n    eigenvalues = zeros(real(eltype(p)), manifold_dimension(M))\n    return CachedBasis(B, DiagonalizingBasisData(B.frame_direction, eigenvalues, vecs))\nend\n\nfunction get_coordinates!(M::Euclidean{<:Tuple,ℝ}, Y, p, X, B::DefaultOrDiagonalizingBasis)\n    S = representation_size(M)\n    PS = prod(S)\n    copyto!(Y, reshape(X, PS))\n    return Y\nend\nfunction get_coordinates!(M::Euclidean{<:Tuple,ℂ}, Y, p, X, B::DefaultOrDiagonalizingBasis)\n    S = representation_size(M)\n    PS = prod(S)\n    Y .= [reshape(real(X), PS)..., reshape(imag(X), PS)...]\n    return Y\nend\n\nfunction get_vector!(M::Euclidean{<:Tuple,ℝ}, Y, p, X, B::DefaultOrDiagonalizingBasis)\n    S = representation_size(M)\n    Y .= reshape(X, S)\n    return Y\nend\nfunction get_vector!(M::Euclidean{<:Tuple,ℂ}, Y, p, X, B::DefaultOrDiagonalizingBasis)\n    S = representation_size(M)\n    N = div(length(X), 2)\n    Y .= reshape(X[1:N] + im * X[N+1:end], S)\n    return Y\nend\n\n@doc raw\"\"\"\n    injectivity_radius(M::Euclidean)\n\nReturn the injectivity radius on the [`Euclidean`](@ref) `M`, which is $∞$.\n\"\"\"\ninjectivity_radius(::Euclidean) = Inf\n\n@doc raw\"\"\"\n    inner(M::Euclidean, p, X, Y)\n\nCompute the inner product on the [`Euclidean`](@ref) `M`, which is just\nthe inner product on the real-valued or complex valued vector space\nof arrays (or tensors) of size $n_1 × n_2  ×  …  × n_i$, i.e.\n\n````math\ng_p(X,Y) = \\sum_{k ∈ I} \\overline{X}_{k} Y_{k},\n````\nwhere $I$ is the set of vectors $k ∈ ℕ^i$, such that for all\n$1 ≤ j ≤ i$ it holds $1 ≤ k_j ≤ n_j$.\n\nFor the special case of $i ≤ 2$, i.e. matrices and vectors, this simplifies to\n````math\ng_p(X,Y) = X^{\\mathrm{H}}Y,\n````\nwhere $\\cdot^{\\mathrm{H}}$ denotes the Hermitian, i.e. complex conjugate transposed.\n\"\"\"\ninner(::Euclidean, ::Any...)\n@inline inner(::Euclidean, p, X, Y) = dot(X, Y)\n@inline inner(::MetricManifold{<:Manifold,EuclideanMetric}, p, X, Y) = dot(X, Y)\n\ninverse_local_metric(M::MetricManifold{<:Manifold,EuclideanMetric}, p) = local_metric(M, p)\n\ndefault_metric_dispatch(::Euclidean, ::EuclideanMetric) = Val(true)\n\nfunction local_metric(::MetricManifold{<:Manifold,EuclideanMetric}, p)\n    return Diagonal(ones(SVector{size(p, 1),eltype(p)}))\nend\n\n@doc raw\"\"\"\n    log(M::Euclidean, p, q)\n\nCompute the logarithmic map on the [`Euclidean`](@ref) `M` from `p` to `q`,\nwhich in this case is just\n````math\n\\log_p q = q-p.\n````\n\"\"\"\nlog(::Euclidean, ::Any...)\n\nlog!(M::Euclidean, X, p, q) = (X .= q .- p)\n\nlog_local_metric_density(M::MetricManifold{<:Manifold,EuclideanMetric}, p) = zero(eltype(p))\n\n@generated _product_of_dimensions(::Euclidean{N}) where {N} = prod(N.parameters)\n\n\"\"\"\n    manifold_dimension(M::Euclidean)\n\nReturn the manifold dimension of the [`Euclidean`](@ref) `M`, i.e.\nthe product of all array dimensions and the [`real_dimension`](@ref) of the\nunderlying number system.\n\"\"\"\nfunction manifold_dimension(M::Euclidean{N,𝔽}) where {N,𝔽}\n    return _product_of_dimensions(M) * real_dimension(𝔽)\nend\n\nmean(::Euclidean{Tuple{1}}, x::AbstractVector{<:Number}; kwargs...) = mean(x)\nfunction mean(\n    ::Euclidean{Tuple{1}},\n    x::AbstractVector{<:Number},\n    w::AbstractWeights;\n    kwargs...,\n)\n    return mean(x, w)\nend\nmean(::Euclidean, x::AbstractVector; kwargs...) = mean(x)\n\nfunction mean!(M::Euclidean, p, x::AbstractVector, w::AbstractVector; kwargs...)\n    return mean!(M, p, x, w, GeodesicInterpolation(); kwargs...)\nend\n\nfunction mean_and_var(::Euclidean{Tuple{1}}, x::AbstractVector{<:Number}; kwargs...)\n    m, v = mean_and_var(x; kwargs...)\n    return m, sum(v)\nend\nfunction mean_and_var(\n    ::Euclidean{Tuple{1}},\n    x::AbstractVector{<:Number},\n    w::AbstractWeights;\n    corrected = false,\n    kwargs...,\n)\n    m, v = mean_and_var(x, w; corrected = corrected, kwargs...)\n    return m, sum(v)\nend\nfunction mean_and_var(M::Euclidean, x::AbstractVector, w::AbstractWeights; kwargs...)\n    return mean_and_var(M, x, w, GeodesicInterpolation(); kwargs...)\nend\n\nmedian(::Euclidean{Tuple{1}}, x::AbstractVector{<:Number}; kwargs...) = median(x)\nfunction median(\n    ::Euclidean{Tuple{1}},\n    x::AbstractVector{<:Number},\n    w::AbstractWeights;\n    kwargs...,\n)\n    return median(x, w)\nend\n\nfunction median!(::Euclidean{Tuple{1}}, p, x::AbstractVector; kwargs...)\n    return copyto!(p, [median(vcat(x...))])\nend\nfunction median!(::Euclidean{Tuple{1}}, p, x::AbstractVector, w::AbstractWeights; kwargs...)\n    return copyto!(p, [median(vcat(x...), w)])\nend\n\n@doc raw\"\"\"\n    norm(M::Euclidean, p, X)\n\nCompute the norm of a tangent vector `X` at `p` on the [`Euclidean`](@ref)\n`M`, i.e. since every tangent space can be identified with `M` itself\nin this case, just the (Frobenius) norm of `X`.\n\"\"\"\nnorm(::Euclidean, p, X) = norm(X)\nnorm(::MetricManifold{<:Manifold,EuclideanMetric}, p, X) = norm(X)\n\n\"\"\"\n    normal_tvector_distribution(M::Euclidean, p, σ)\n\nNormal distribution in ambient space with standard deviation `σ`\nprojected to tangent space at `p`.\n\"\"\"\nfunction normal_tvector_distribution(M::Euclidean{Tuple{N}}, p, σ) where {N}\n    d = Distributions.MvNormal(zero(p), σ)\n    return ProjectedFVectorDistribution(TangentBundleFibers(M), p, d, project_vector!, p)\nend\n\n@doc raw\"\"\"\n    project(M::Euclidean, p)\n\nProject an arbitrary point `p` onto the [`Euclidean`](@ref) manifold `M`, which\nis of course just the identity map.\n\"\"\"\nproject(::Euclidean, ::Any)\n\nproject!(M::Euclidean, q, p) = copyto!(q, p)\n\n\"\"\"\n    project(M::Euclidean, p, X)\n\nProject an arbitrary vector `X` into the tangent space of a point `p` on the\n[`Euclidean`](@ref) `M`, which is just the identity, since any tangent\nspace of `M` can be identified with all of `M`.\n\"\"\"\nproject(::Euclidean, ::Any, ::Any)\n\nproject!(M::Euclidean, Y, p, X) = copyto!(Y, X)\n\n\"\"\"\n    projected_distribution(M::Euclidean, d, [p])\n\nWrap the standard distribution `d` into a manifold-valued distribution. Generated\npoints will be of similar type to `p`. By default, the type is not changed.\n\"\"\"\nfunction projected_distribution(M::Euclidean, d, p)\n    return ProjectedPointDistribution(M, d, project!, p)\nend\nfunction projected_distribution(M::Euclidean, d)\n    return ProjectedPointDistribution(M, d, project!, rand(d))\nend\n\n\"\"\"\n    representation_size(M::Euclidean)\n\nReturn the array dimensions required to represent an element on the\n[`Euclidean`](@ref) `M`, i.e. the vector of all array dimensions.\n\"\"\"\n@generated representation_size(::Euclidean{N}) where {N} = size_to_tuple(N)\n\n\"\"\"\n    sharp(M::Euclidean, p, ξ)\n\nTransform the cotangent vector `ξ` at `p` on the [`Euclidean`](@ref) `M` to a tangent vector `X`.\nSince cotangent and tangent vectors can directly be identified in the [`Euclidean`](@ref)\ncase, this yields just the identity.\n\"\"\"\nsharp(::Euclidean, ::Any...)\n\nsharp!(M::Euclidean, X::TFVector, p, ξ::CoTFVector) = copyto!(X, ξ)\n\nfunction show(io::IO, ::Euclidean{N,𝔽}) where {N,𝔽}\n    print(io, \"Euclidean($(join(N.parameters, \", \")); field = $(𝔽))\")\nend\n\n\"\"\"\n    vector_transport_to(M::Euclidean, p, X, q, ::ParallelTransport)\n\nParallely transport the vector `X` from the tangent space at `p` to the tangent space at `q`\non the [`Euclidean`](@ref) `M`, which simplifies to the identity.\n\"\"\"\nvector_transport_to(::Euclidean, ::Any, ::Any, ::Any, ::ParallelTransport)\n\nvector_transport_to!(M::Euclidean, Y, p, X, q, ::ParallelTransport) = copyto!(Y, X)\n\nvar(::Euclidean, x::AbstractVector; kwargs...) = sum(var(x; kwargs...))\nfunction var(::Euclidean, x::AbstractVector{T}, m::T; kwargs...) where {T}\n    return sum(var(x; mean = m, kwargs...))\nend\n\n\"\"\"\n    zero_tangent_vector(M::Euclidean, x)\n\nReturn the zero vector in the tangent space of `x` on the [`Euclidean`](@ref)\n`M`, which here is just a zero filled array the same size as `x`.\n\"\"\"\nzero_tangent_vector(::Euclidean, ::Any...)\n\nzero_tangent_vector!(M::Euclidean, v, x) = fill!(v, 0)\n", "meta": {"hexsha": "beaf508a260e03c415fd1efc8c2dc0e76ca6102c", "size": 12880, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/manifolds/Euclidean.jl", "max_stars_repo_name": "dahong67/Manifolds.jl", "max_stars_repo_head_hexsha": "f070e54148695cfde09cc7110b9df7105dd96851", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/manifolds/Euclidean.jl", "max_issues_repo_name": "dahong67/Manifolds.jl", "max_issues_repo_head_hexsha": "f070e54148695cfde09cc7110b9df7105dd96851", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/manifolds/Euclidean.jl", "max_forks_repo_name": "dahong67/Manifolds.jl", "max_forks_repo_head_hexsha": "f070e54148695cfde09cc7110b9df7105dd96851", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.443324937, "max_line_length": 163, "alphanum_fraction": 0.6597826087, "num_tokens": 3896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.757251999109913}}
{"text": "module problem133\n\ndescription = \"\"\"\nRepunit nonfactors\n\nA number consisting entirely of ones is called a repunit. We shall define R(k) to be a repunit of length k; for example, R(6) = 111111.\nLet us consider repunits of the form R(10^n).\nAlthough R(10), R(100), or R(1000) are not divisible by 17, R(10000) is divisible by 17. \nYet there is no value of n for which R(10^n) will divide by 19. \nIn fact, it is remarkable that 11, 17, 41, and 73 are the only four primes below one-hundred that can be a factor of R(10n).\n\nFind the sum of all the primes below one-hundred thousand that will never be a factor of R(10^n).\n\"\"\"\n\n# Search the list of primes, for each one either:\n# 1) 10^10^n = 1 mod 9p for some n, which means p divides R(10^n)\n# 2) A cycle forms in the remainders of 10^10^n mod 9p\n# So search the list of primes until a 1 occurs in the remainder or a repeated value is hit.\n# IntSet does a pretty good job providing a constant time test for checking if a value has already been seen.\nfunction search(maxprime = 100000)\n  total = 0\n  for p in primes(maxprime)\n    seen = IntSet()\n    remainder = (10^10) % (9*p)\n    push!(seen, remainder)\n    for n = 2:Inf  \n      remainder = powermod(remainder, 10, 9*p)\n      if remainder == 1\n        break\n      elseif in(remainder, seen)\n        total += p\n        break\n      end \n      push!(seen, remainder)\n    end\n  end\n  return total\nend\n\nusing Base.Test\n\n@test search(100) == sum(primes(100)) - sum([11, 17, 41, 73])\n\nend", "meta": {"hexsha": "3c603df4cf43f8135b7d102563a48fec6607643a", "size": 1479, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem133.jl", "max_stars_repo_name": "mbuhot/mbuhot-euler-solutions", "max_stars_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-12-18T13:25:41.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-18T13:25:41.000Z", "max_issues_repo_path": "julia/problem133.jl", "max_issues_repo_name": "mbuhot/mbuhot-euler-solutions", "max_issues_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/problem133.jl", "max_forks_repo_name": "mbuhot/mbuhot-euler-solutions", "max_forks_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6136363636, "max_line_length": 135, "alphanum_fraction": 0.6795131846, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480244025281, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7572519972701859}}
{"text": "module MarketEquilibria\n\nusing Random\nusing JuMP\nusing Ipopt\n\nexport homogeneousfisher, tatonnement, exchange, production\n\n\"\"\"\n    homogeneousfisher(endowments, A, supplies, form, ρ)\n\n§6.2: Fisher Model with Homogeneous Consumers. `form` specifies which utility\nfunction consumers use, among `:linear`, `:CES`, `:cobb_douglas`, and `:leontief`. `ρ` is the parameter for\n`:CES`.\n\"\"\"\nfunction homogeneousfisher(endowments::Array{Float64,1},\n                           A::Array{Float64,2},\n                           supplies::Array{Float64,1},\n                           form=:linear,\n                           ρ::Union{Float64,Nothing}=0.5)::Tuple{Array{Float64,2},\n                                                                 Array{Float64,1}}\n    @assert form in [:linear, :CES, :cobb_douglas, :leontief] \"Unknown form\"\n    if form == :cobb_douglas\n        ρ = 1e-8          # Ideally 0\n    end\n\n    (n, m) = size(A)\n    @assert size(endowments) == (n, ) \"Dim mismatch between A and endowments\"\n    @assert size(supplies) == (m, ) \"Dim mismatch between A and supplies\"\n\n    model = Model(Ipopt.Optimizer)\n    set_optimizer_attribute(model, \"print_level\", 0)\n\n    @variable(model, X[1:n, 1:m], lower_bound=0)\n    @constraint(model, Supply[j in 1:m], sum(X[:, j]) ≤ supplies[j])\n\n    if form == :linear || ρ > .97\n        if form != :linear\n            @warn \"ρ > .97 tends to fail, so assuming linear\"\n        end\n        # Very bad results if you allow the default scaling 🐸☕️\n        set_optimizer_attribute(model, \"nlp_scaling_method\", \"none\")\n        @NLobjective(model, Max, sum(endowments[i] * log(sum(A[i, j] * X[i, j] for j in 1:m)) for i in 1:n))\n    elseif form == :leontief\n        @variable(model, t)\n        @objective(model, Max, t)\n        @NLconstraint(model, tLessThan[j in 1:m],\n                    t ≤ sum(endowments[i] * log(A[i, j] * X[i, j]) for i in 1:n))\n    else\n        @NLobjective(model, Max, sum(endowments[i] * log(sum(A[i, j] * X[i, j] ^ ρ for j in 1:m) ^ (1 / ρ)) for i in 1:n))\n    end\n\n        # Explicit Cobb–Douglas; very poorly conditioned. I couldn't get it to converge.\n        # @NLobjective(model, Max, sum(endowments[i] * log(prod(X[i, j] ^ A[i, j] for j in 1:m)) for i in 1:n))\n\n        # Explicit Leontief is as follows, but minimum() not allowed by JuMP.\n        # Got around this using the linearization trick.\n        # @NLobjective(model, Max, sum(endowments[i] * log(minimum(A[i, j] * X[i, j] for j in 1:m)) for i in 1:n))\n\n        # Attempt at \"softmin\" differential substitute; returns errors.\n        # @NLobjective(model, Max, sum(endowments[i] * log(-log(sum(exp(-A[i, j] * X[i, j]) for j in 1:m))) for i in 1:n))\n\n    optimize!(model)\n    return value.(X), dual.(Supply)\nend\n\n\n\"\"\"\n    tatonnement(endowments, A, ρ, π0;\n                η=1e-4, δ=0.5, α=0.5, verbose=false, maxit=1000, tol=1e-5)\n\n§6.3.1.B: The Discrete Tâtonnement Process. Simulate a bidding process in search\nof equilibrium prices for CES exchange.\n\nPrice update step is quite different from the book: I *multiply* prices\nentrywise by the excess demand: `π .*= exp.(δ * Z * k ^ -α)`. This works pretty well.\n\n`η` is a lower bound on the prices before normalization.\n\"\"\"\nfunction tatonnement(endowments ::AbstractArray{<:AbstractFloat,2},\n                     A          ::AbstractArray{<:AbstractFloat,2},\n                     ρ          ::AbstractArray{<:AbstractFloat,1},\n                     π0         ::Union{AbstractArray{<:AbstractFloat,1}, Nothing};\n                     η          ::AbstractFloat=1e-4,\n                     δ          ::AbstractFloat=0.5,\n                     α          ::AbstractFloat=0.4,\n                     verbose    ::Bool=false,\n                     maxit      ::Int=2000,\n                     tol        ::AbstractFloat=1e-5)::Tuple{Array{Float64,1},\n                                                             Array{Float64,2}}\n\n    (n, m) = size(A)\n    @assert (n, m) == size(endowments)\n    W = endowments      # sorry\n\n    @assert (n, )  == size(ρ)\n    @assert all(ρ .< 1)\n    @assert all(0 .< (tol, η, δ, α) .< 1)\n\n    if π0 == nothing\n        π0 = rand(m)\n    end\n\n    @assert (m, )  == size(π0)\n\n    total_supply = sum(W, dims=1)\n    # Express utility as fractions of endowment\n    A .*= total_supply\n    # So we can normalize W\n    W ./= total_supply\n\n    σ = 1 ./ (1 .- ρ)\n    π_LB = η / (4 * n)\n    π_UB = 1 + π_LB\n    π_LB_tight = η / (2 * n)\n\n    π = copy(π0)\n    D = zeros(Float64, n, m)\n    Z = zeros(Float64, m)\n\n    for k in 1:maxit\n        # Oracle that computes player demand under CES (eq. 6.7, p. 149)\n        for i in 1:n, j in 1:m\n            D[i, j] = A[i, j] ^ σ[i] * sum(π[k] * W[i, k] for k in 1:m) /\n                       (π[j] ^ σ[i] * sum((A[i, k] * π[k] ^ -ρ[i]) ^ σ[i] for k in 1:m))\n        end\n\n        for j in 1:m\n            # Total supply, after normalization, is ones\n            Z[j] = sum(D[i, j] for i in 1:n) - 1\n        end\n\n        if NaN in Z || all(-tol .< Z .< tol)\n            break\n        end\n\n        if verbose\n            println(\"Iteration $k\")\n            println(\"  Current prices: \", round.(π, digits=5))\n            println(\"  Excess demand:  \", round.(Z, digits=5))\n        end\n\n        # This equilibrium step process is completely different from the book.\n        # Just something that makes intuitive sense. Book is unclear on how to\n        # calculate step size.\n        if all(π_LB .≤ π .≤ π_UB)\n            verbose ? println(\"  Step toward equilibrium\") : nothing\n            π .*= exp.(δ * Z * k ^ -α)\n        else                             # Bottom of p. 144\n            verbose ? println(\"  Regularization step\") : nothing\n            for j in 1:m\n                if π[j] > 1\n                    π[j] = 1\n                elseif π[j] < π_LB_tight\n                    π[j] = π_LB_tight\n                end\n            end\n        end\n    end\n\n    return π ./ sum(π), D\nend\n\n\n\"\"\"\n    exchange(endowments, A, ρ=:linear)\n\n§6.4: Convex programs for linear and CES exchange economies. Note that unlike `homogeneousfisher()`,\nhere `ρ` is a vector of CES parameters used by each player. Or pass `ρ=:linear` for linear model.\n\"\"\"\nfunction exchange(endowments::Array{Float64,2},\n                  A::Array{Float64,2},\n                  ρ::Union{Array{Float64,1},Symbol}=:linear)::Tuple{Array{Float64,1},\n                                                                    Array{Float64,2}}\n    (n, m) = size(A)\n    @assert size(endowments) == (n, m)         \"Dim mismatch between A and endowments\"\n\n    model = Model(Ipopt.Optimizer)\n    set_optimizer_attribute(model, \"print_level\", 0)\n\n    if ρ == :linear\n        # set_optimizer_attribute(model, \"nlp_scaling_method\", \"none\")\n\n        @variable(model, ψ[1:m])\n        @variable(model, X[1:n, 1:m], lower_bound=0)\n        @NLconstraint(model, IndividualRationality[i in 1:n, j in 1:m],\n                        sum(A[i, k] * X[i, k] for k in 1:m) ≥\n                        A[i, j] * sum(endowments[i, k] * exp(ψ[k] - ψ[j]) for k in 1:m))\n        @constraint(model, Supply[j in 1:m], sum(X[i, j] for i in 1:n) ==\n                                             sum(endowments[i, j] for i in 1:n))\n\n        optimize!(model)\n\n        prices = exp.(value.(ψ))\n        demands = value.(X)\n\n    else\n        @assert size(ρ) == (n, )                   \"Dim mismatch between A and ρ\"\n        @assert all(-1 .≤ ρ .< 0)                  \"Need ρ ∈ [-1, 0)\"\n\n        @variable(model, σ[1:m], lower_bound=0)\n        @NLconstraint(model, Supply[j in 1:m], sum(A[i, j] ^ (1 / (1 - ρ[i])) *\n                                               sum(σ[k] ^ 2 * endowments[i, k] for k in 1:m) /\n                                               (\n                                                   σ[j] ^ ((ρ[i] - 2) / (1 - ρ[i])) *\n                                                   sum(A[i, k] ^ (1 / (1 - ρ[i])) * σ[k] ^ ((-2 * ρ[i]) / (1 - ρ[i]))\n                                                       for k in 1:m)\n                                               )\n                                               for i in 1:n) ≤ σ[j] * sum(endowments[i, j] for i in 1:n))\n\n        optimize!(model)\n\n        prices = value.(σ) .^ 2\n\n        demands = zeros(n, m)\n        for i in 1:n, j in 1:m\n        demands[i, j] = A[i, j] ^ (1 / (1 - ρ[i])) * sum(prices[k] * endowments[i, k] for k in 1:m) /\n                        (\n                            prices[j] ^ (1 / 1 - ρ[i]) *\n                            sum(A[i, k] ^ (1 / (1 - ρ[i])) * prices[k] ^ (-ρ[i] / (1 - ρ[i])) for k in 1:m)\n                        )\n        end\n    end\n\n    return prices, demands\nend\n\n\"\"\"\n    exchange(endowments, A_consumers, A_producers,\n             ρ_consumers, ρ_producers, o_producers)\n\n§6.6: Models with production. `ρ_consumers` describes\neach consumer's CES utility function, while `ρ_producers` describes the CES\nproduction function. Convergence is very iffy, but best when `A_consumers` is\ntall and entries of `ρ` vectors are not too close to 0 or 1.\n\"\"\"\nfunction production(endowments::Array{Float64,2},\n                    A_consumers::Array{Float64,2},\n                    A_producers::Array{Float64,2},\n                    ρ_consumers::Array{Float64,1},\n                    ρ_producers::Array{Float64,1},\n                    o_producers::Array{Int,1})::Tuple{Array{Float64,1},\n                                                      Array{Float64,1},\n                                                      Array{Float64,2}}\n\n    (n, m) = size(A_consumers)\n    (l, ) = size(ρ_producers)\n\n    @assert size(A_producers) == (l, m)   \"Dim mismatch between A_consumers and A_producers\"\n    @assert size(endowments) == (n, m)    \"Dim mismatch between A_consumers and endowments\"\n    @assert size(ρ_consumers) == (n, )    \"Dim mismatch between A_consumers and ρ_consumers\"\n    @assert size(o_producers) == (l, )    \"Dim mismatch between o and ρ_producers\"\n    @assert all(0 .< ρ_consumers .< 1)    \"Need ρ ∈ (0, 1)\"\n    @assert all(0 .< ρ_producers .< 1)    \"Need ρ ∈ (0, 1)\"\n\n    A = vcat(A_producers, A_consumers)\n    w = hcat(endowments, zeros(n, l))\n    ρ = vcat(ρ_consumers, ρ_producers)\n    σ = 1 ./ (1 .- ρ)\n    o = vcat(o_producers, m .+ (1:n))\n\n    # Comparison idx since comparison forbidden in lincon\n    O = [o[k] == j for k in 1:l, j in 1:m]\n\n    model = Model(Ipopt.Optimizer)\n    set_optimizer_attribute(model, \"print_level\", 0)\n    set_optimizer_attribute(model, \"nlp_scaling_method\", \"none\")\n\n    @variable(model, ψ[1:m + n], lower_bound=0)\n    @variable(model, x[1:m + n], lower_bound=0)\n    @variable(model, Z[1:l + n, 1:m], lower_bound=0)\n    @variable(model, q[1:l + n], lower_bound=0)\n\n    @NLconstraint(model, ConsumerRationality[i in 1:n],                   # 6.10\n                    exp(ψ[m + i]) * x[m + i] ≥ # or ==\n                    sum(exp(ψ[j]) * w[i, j] for j in 1:m))\n    @NLconstraint(model, ProducerSolvency[k in 1:l + n],                  # 6.11\n                    q[k] ≤\n                    sum(A[k, j] * x[j] ^ ρ[k] for j in 1:m) ^ (1 / ρ[k]))\n    @NLconstraint(model, ProducerRationality[k in 1:l + n],               # 6.12\n                    exp(ψ[o[k]] * (1 - σ[k])) ≥\n                    sum(A[k, j] ^ σ[k] * exp(ψ[j] * (1 - σ[k])) for j in 1:m))\n    @constraint(model, MarketClearing[j in 1:m],                          # 6.13\n                    sum(Z[k, j] for k in 1:l + n) ≤\n                    sum(w[i, j] for i in 1:n) + sum(O[k, j] * q[k] for k in 1:l))\n                                            # Equiv\n                                            # + sum((o[k] == j) * q[k] for k in 1:l + n))\n    @constraint(model, Supply[i in 1:n], x[m + i] ≤ q[l + i])             # 6.14\n\n    #=  Final constraint given in final paragraph of 154. This should be redundant, but\n        aids computation.                   =#\n    @NLconstraint(model, ZeroProfit[k in 1:l + n],\n                    sum(exp(ψ[j]) * Z[k, j] for j in 1:m) == exp(ψ[o[k]]) * q[k])\n\n    optimize!(model)\n    prices = exp.(value.(ψ)[1:m])\n\n    # Player utility, specifically, demand of each player for her own utility item.\n    demands = value.(x)[m + 1:end]\n    inputs = value.(Z)[l + 1:end, :]\n\n    return prices, demands, inputs\nend\n\n\nend\n", "meta": {"hexsha": "10351b74ca938279d18e47a4bf9a85d87a942408", "size": 12192, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MarketEquilibria.jl", "max_stars_repo_name": "maxkapur/MarketEquilibria", "max_stars_repo_head_hexsha": "838d69369f53063ab7ac9b49cf3c298ef4e9c1d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MarketEquilibria.jl", "max_issues_repo_name": "maxkapur/MarketEquilibria", "max_issues_repo_head_hexsha": "838d69369f53063ab7ac9b49cf3c298ef4e9c1d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MarketEquilibria.jl", "max_forks_repo_name": "maxkapur/MarketEquilibria", "max_forks_repo_head_hexsha": "838d69369f53063ab7ac9b49cf3c298ef4e9c1d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7133550489, "max_line_length": 122, "alphanum_fraction": 0.499425853, "num_tokens": 3603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7572519928855669}}
{"text": "\"\"\"\nSmooth jump function ``\\\\Phi_{\\\\omega, T}(t)``\n\n    Returns a planned trajectory.\n\n    smoothjump(t :: Real, T:: Real; ω = 2.0 :: Real)\n\n`t` : actual time\n\n`T` : final time\n\n`ω` : steepness factor of trajectory\n\"\"\"\nfunction smoothjump(t :: Real, T:: Real; ω = 2.0 :: Real)\n\n    if t <= 0\n        return  0.0\n    elseif t >= T\n        return 1.0\n    else\n\n        numer, err1 = quadgk(x-> pulsebell(x, T, ω=ω), 0, t)\n        denom, err2 = quadgk(x-> pulsebell(x, T, ω=ω), 0, T)\n\n        return numer/denom\n    end\nend\n\n\n\"\"\"\nBell-shaped pulse function ``\\\\Omega_{\\\\omega, T}(t)``\n\n`t` : actual time\n\n`T` : final time\n\n`ω` : steepness factor of trajectory\n\"\"\"\nfunction pulsebell(t :: Real, T:: Real; ω = 2.0 :: Real)\n\n    if t < 0 || t > T\n        return 0\n    else\n        exp( -1 / ( (1 - t/T)*(t/T))^ω )\n    end\n\nend", "meta": {"hexsha": "771a2643a59982b68baa543d4386a520c637b4f6", "size": 820, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gevrey.jl", "max_stars_repo_name": "stephans3/Trapla.jl", "max_stars_repo_head_hexsha": "1aa7cff39fbd6671f9ce5525ed2e034c75a2f02f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gevrey.jl", "max_issues_repo_name": "stephans3/Trapla.jl", "max_issues_repo_head_hexsha": "1aa7cff39fbd6671f9ce5525ed2e034c75a2f02f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gevrey.jl", "max_forks_repo_name": "stephans3/Trapla.jl", "max_forks_repo_head_hexsha": "1aa7cff39fbd6671f9ce5525ed2e034c75a2f02f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4468085106, "max_line_length": 60, "alphanum_fraction": 0.5280487805, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7572244481170404}}
{"text": "function fibo_even_sum(N::Int)\n    a = 0\n    b = 1\n    c = 0\n    s = 0\n    while(a+b<N)\n        c = a + b\n        if iseven(c)\n            s+=c\n        end\n        a = b\n        b = c\n    end\n    return s\nend\n\nprintln(fibo_even_sum(4000000))", "meta": {"hexsha": "4c46449753c7fcdf9387212c00aa597de741280a", "size": 241, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Ques_2.jl", "max_stars_repo_name": "Shayan990/Euler-Project-Solutions", "max_stars_repo_head_hexsha": "eddd8b1058f7b94d89045b17743e4e63d0b5a3c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ques_2.jl", "max_issues_repo_name": "Shayan990/Euler-Project-Solutions", "max_issues_repo_head_hexsha": "eddd8b1058f7b94d89045b17743e4e63d0b5a3c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ques_2.jl", "max_forks_repo_name": "Shayan990/Euler-Project-Solutions", "max_forks_repo_head_hexsha": "eddd8b1058f7b94d89045b17743e4e63d0b5a3c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.1764705882, "max_line_length": 31, "alphanum_fraction": 0.4232365145, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913354875362, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7572244469614919}}
{"text": "using JuMP\nusing Clp\n\nPROPORTION_MAT = [\n    [5.0 15.0]\n    [20.0 5.0]\n    [-15.0 -2.0]\n]\n\nLIMITS = [50.0, 40.0, -60.0]\n\nCOSTS = [8.0, 4.0]\n\nm = Model(Clp.Optimizer)\n@variable(m, x[1:2] >= 0)\n@objective(m, Min, COSTS' * x)\n@constraint(m, PROPORTION_MAT * x .≥ LIMITS)\n\nprint(m)\n\noptimize!(m)\n\nstatus = termination_status(m)\n\nprintln(\"Solution status: \", status)\n\nprintln(\"Objective value: \", objective_value(m))\n\nprintln(\"Values: \", value.(x))\n", "meta": {"hexsha": "3c481e2985a9d11b9dcf91c8bd8df963112eed47", "size": 444, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week2/example_2.jl", "max_stars_repo_name": "InzamamRahaman/COMP6925-2021", "max_stars_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-23T23:33:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T01:47:28.000Z", "max_issues_repo_path": "week2/example_2.jl", "max_issues_repo_name": "InzamamRahaman/COMP6925-2021", "max_issues_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week2/example_2.jl", "max_forks_repo_name": "InzamamRahaman/COMP6925-2021", "max_forks_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.8, "max_line_length": 48, "alphanum_fraction": 0.6193693694, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259923, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7572244428935572}}
{"text": "push!(LOAD_PATH, \"./gridmodule/\")\npush!(LOAD_PATH, \"./femmodule/\")\n\nusing BaseFEM\nusing BaseGrid\nusing LinearAlgebra\n\n# 1D ring\n#m=grid1D(\"./mesh1d/mesh2\")\n#tau = 1e-3\n#eps = 0.1\n\n# 3D ball\n#m=grid3D(\"./mesh3d/ball\")\n#tau = 1e-3\n#eps = 0.1\n\n# greenland example\n#m=grid2D(\"./mesh2d/greenland\")\n#tau = 1e-1\n#eps = 3.00\n\n# sphere example\nm=grid2D(\"./mesh2d/sphere_hq05\")\ntau = 1e-6\neps  = 0.01\n\ntop  = m.topology\nndof = ndof_P1(top)\ngeo  = restrain_geometry(m.geometry,ndof)\nA,M=assembly_P1(geo,top)\n\n# initial conditions\nu      = 2.0*rand(ndof).-1.0\ntime = 0.0\nS = factorize([M tau*A;-A M])\nmprint = 0\n\nfor i=1:1000\n\tglobal time,u,mprint\n\tprintln(\"iteration $(i) at time $(time)\")\n\n\tdWdu = (4*u.^3-4*u)/eps\n\n\trhs1 = M*u\n\trhs2 = M*dWdu\n\n\tsol = S\\[rhs1;rhs2]\n\tu   = sol[1:ndof]\n\ttime = time + tau\n\n\t# output to ParaView vtk file\n\tif mod(i,10) == 0\n\t\tmprint = mprint + 1\n\t\toutvtk_scalar(\"output/example_cahnhilliard\"*string(mprint)*\".vtk\",geo,top,\"sol\",u)\n\tend\nend\n# alternative meshes\n# m=grid2D(\"./mesh2d/test\")\n# m=grid2D(\"./mesh2d/sphere\")\n", "meta": {"hexsha": "d2ee561730adb5b47a45c209bfa0fa949247d6ba", "size": 1039, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/example_cahnhilliard.jl", "max_stars_repo_name": "dpeschka/jPDE", "max_stars_repo_head_hexsha": "8c783f8f7f112b17842c9651bd13e0fe416796f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/example_cahnhilliard.jl", "max_issues_repo_name": "dpeschka/jPDE", "max_issues_repo_head_hexsha": "8c783f8f7f112b17842c9651bd13e0fe416796f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/example_cahnhilliard.jl", "max_forks_repo_name": "dpeschka/jPDE", "max_forks_repo_head_hexsha": "8c783f8f7f112b17842c9651bd13e0fe416796f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-08T14:58:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-08T14:58:13.000Z", "avg_line_length": 17.0327868852, "max_line_length": 84, "alphanum_fraction": 0.6487006737, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.757224441537579}}
{"text": "using Soss, DifferentialEquations \nusing Plots, StatsPlots\n\nfunction lotka_volterra(du,u,p,t)\n  x, y = u\n  α, β, γ, δ  = p\n  du[1] = (α - β*y)x # dx =\n  du[2] = (δ*x - γ)y # dy = \nend\np = [1.5, 1.0, 3.0, 1.0]\nu0 = [1.0,1.0]\nprob1 = ODEProblem(lotka_volterra,u0,(0.0,10.0),p)\n\n\nsol1 = solve(prob1,Tsit5(),saveat=0.1)\nodedata = rand(For(Poisson, Array(sol1)))\n\nplot(sol1, legend = false); scatter!(sol1.t, odedata')\n\n\nm = @model ode begin\n    α ~ Uniform()\n    β ~ Uniform()\n    γ ~ Uniform()\n    δ ~ Uniform()\n\n    # p = [2α+0.5,2β,3γ+1,2δ]\n    p = [20α+0.5,20β,30γ+1,20δ]\n    prob = remake(ode, p=p)\n    predicted = solve(prob,Tsit5(),saveat=0.1)\n        \n    data ~ For(Array(predicted)) do λ Poisson(λ) end\nend\n\npost = dynamicHMC(m(ode=prob1) | (data=odedata,))\n\nplt = plot(sol1, legend = false)\n\nfor x in post\n    p = [2 * x.α + 0.5,2 * x.β,3 * x.γ + 1,2 * x.δ]\n\n    thisprob = remake(prob1, p=p)\n    thissol = solve(thisprob,Tsit5(),saveat=0.1)\n    plot!(plt, thissol, alpha=0.02, linewidth=2, color = :black, legend = false)\nend\n# display(pl)\nplot!(sol1, w=1, legend = false)\nscatter!(sol1.t, odedata')\n", "meta": {"hexsha": "6304639d2ad9ec94d542ec950cc9e4fd6f538fad", "size": 1108, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scratchpad/ode.jl", "max_stars_repo_name": "devmotion/Soss.jl", "max_stars_repo_head_hexsha": "0440210c71bdb6c69bf7b1930043e29bd19da3a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 388, "max_stars_repo_stars_event_min_datetime": "2018-01-02T23:08:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:36:40.000Z", "max_issues_repo_path": "scratchpad/ode.jl", "max_issues_repo_name": "devmotion/Soss.jl", "max_issues_repo_head_hexsha": "0440210c71bdb6c69bf7b1930043e29bd19da3a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 228, "max_issues_repo_issues_event_min_datetime": "2018-01-07T03:26:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T22:15:32.000Z", "max_forks_repo_path": "scratchpad/ode.jl", "max_forks_repo_name": "devmotion/Soss.jl", "max_forks_repo_head_hexsha": "0440210c71bdb6c69bf7b1930043e29bd19da3a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2018-09-30T00:29:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T09:42:59.000Z", "avg_line_length": 22.612244898, "max_line_length": 80, "alphanum_fraction": 0.5884476534, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913343093499, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7572244352764901}}
{"text": "# Fig_1_Brusselator_eigenvalues_v3.jl\n# ==================================== u.p.  23.8.21\n\nusing DrWatson\n@quickactivate \"NonlinearDynamicsTextbook\"\ninclude(srcdir(\"style.jl\"))\nusing DynamicalSystems, PyPlot, OrdinaryDiffEq\nusing StaticArrays\nusing LinearAlgebra\n\n\n# parameters\n# ----------\na = 9\nbs = [9.8, 10.2]\ndvecs = [\n    [4.5, 3.0, 2.0, 1.7],\n    reverse([0.1, 1.0, 1.7, 2.0]),\n]\nfig, axs = subplots(1,2)\n\nfor (j, b) in enumerate(bs)\n\ndvec = dvecs[j]\nivec = [1 2 6 4]   # order of colors\n\nqmin = 0.0\nqmax = 2.0\nnq = 301\nqvec = range(qmin,qmax; length=nq)\nRe_lambda_vec = zeros(nq)\nIm_lambda_vec = zeros(nq)\nRe_qvec = zeros(nq)\nIm_qvec = zeros(nq)\n\nax = axs[j]\n\nax.axhline(0; linewidth=1.0,color=\"k\" )\n\nfor id = 1:length(dvec)\n\n    dd = dvec[id]\n    jj = kk = 0\n    for iq = 1:nq\n        cc = qvec[iq] * qvec[iq]\n        b11 = b - 1 - cc\n        b12 = a\n        b21 = -b\n        b22 = - a - dd*cc\n        traceB = b11+b22\n        detB = b11*b22 - b12*b21\n        rootarg = traceB*traceB/4 - detB\n        if rootarg < 0\n            Re_lambda = traceB/2\n            jj = jj + 1\n            Im_qvec[jj] = qvec[iq]\n            Im_lambda_vec[jj] = Re_lambda\n        else\n            Re_lambda = traceB/2 + sqrt(rootarg)\n            if kk == 0\n               kk = 1\n               Re_qvec[kk] = Im_qvec[jj]\n               Re_lambda_vec[kk] = Im_lambda_vec[jj]\n            end\n            kk = kk + 1\n            Re_qvec[kk] = qvec[iq]\n            Re_lambda_vec[kk] = Re_lambda\n        end\n    end\n    ax.plot(Re_qvec[1:kk],Re_lambda_vec[1:kk], linewidth=3.0,linestyle=\"--\",color=COLORS[ivec[id]] )\n    ax.plot(Im_qvec[1:jj],Im_lambda_vec[1:jj], linewidth=3.0,linestyle=\"-\",color=COLORS[ivec[id]] )\nend\n\n\nax.set_xlim([qmin,qmax])\nif j == 1\n    ax.set_ylim([-2.1,2.6])\nelse\n    ax.set_ylim([-2.1,0.4])\nend\nax.legend([ \"_\" ; \"_\" ; L\"d=\"*string(dvec[1]);\n                  \"_\" ; L\"d=\"*string(dvec[2]);\n                  \"_\" ; L\"d=\"*string(dvec[3]);\n                  \"_\" ; L\"d=\"*string(dvec[4]);\n              #    \"_\" ; L\"d=\"*string(dvec[5]);\n                  ], \n    fontsize = 26, handlelength = 1, handletextpad = 0.6,\n    # loc = \"upper left\", \n)\n\nend\n\naxs[1].set_xlabel(L\"q\") \naxs[2].set_xlabel(L\"q\") \naxs[1].set_ylabel(L\"\\max (\\rm{Re} (\\lambda))\") \n\nadd_identifiers!(fig)\nfig.tight_layout(pad=0.3)\nwsave(plotsdir(\"11\", \"brusselator_eigenvalues\"), fig)\n", "meta": {"hexsha": "3be35792f6b541b03897f3723f597c158d83d4f6", "size": 2357, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "figure_generation/11/11.1.jl", "max_stars_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_stars_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 88, "max_stars_repo_stars_event_min_datetime": "2021-07-18T20:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T09:23:53.000Z", "max_issues_repo_path": "figure_generation/11/11.1.jl", "max_issues_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_issues_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figure_generation/11/11.1.jl", "max_forks_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_forks_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-07-28T18:49:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:45:11.000Z", "avg_line_length": 23.57, "max_line_length": 100, "alphanum_fraction": 0.5294866356, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.7571805477492444}}
{"text": "# Compares two methods for simulating a homogeneous Poisson point process,\n# where the idea behind one method is faster than the other. In this code,\n# the two methods are labelled A and B.\n#\n# Method A simulates all the Poisson ensembles randomly by first randomly\n# generating all the Poisson random variables in one step. It then randomly\n# positions all the points (across all ensembles) in one step. All the\n# points are then are then separated accordingly into ensembles.\n#\n# Method B iterates through a for-loop, and for each iteration, it randomly\n# generates a Poisson variable and positions the points for each ensemble.\n#\n# Method A uses more vectorization than Method B so it should be faster\n# than Method B in general.\n#\n# Author: H. Paul Keeler, 2019.\n# Website: hpaulkeeler.com\n# Repository: github.com/hpaulkeeler/posts\n# For more details, see the post:\n# hpaulkeeler.com/testing-the-julia-language-with-point-process-simulations/\n\nclearconsole();\n\nusing Random;\nusing Distributions; #for random simulations\nusing Plots; #for plotting\n\nRandom.seed!(1);\n\n###START Parameters START###\nnumbSim=10^5; #number of simulations\n\n#Point process parameters\nlambda=5; #intensity (ie mean density) of Poisson point process\n\n#Simulation window parameters\nxMin=0;xMax=1;\nyMin=0;yMax=1;\nxDelta=xMax-xMin;yDelta=yMax-yMin; #rectangle dimensions\nareaTotal=xDelta*yDelta; #area of rectangle\nmassTotal=areaTotal*lambda;  #total measure/mass of the point process\n###END Parameters END###\n\n###START Simulation section START###\n###START Method A: Generate *all* ensembles at once START###\n@time begin\n    xxCellA=Array{Array{Float64}}(undef,numbSim);\n    yyCellA=Array{Array{Float64}}(undef,numbSim);\n\n    numbPointsA=rand(Poisson(massTotal),numbSim); #Poisson number of points\n    numbPointsCumA=cumsum(numbPointsA);\n    numbPointsTotal=numbPointsCumA[end];\n\n    #uniform x/y coordinates of Poisson points\n    xxAll=xDelta.*(rand(numbPointsTotal)).+xMin;#x coordinates of Poisson points\n    yyAll=yDelta.*(rand(numbPointsTotal)).+yMin;#y coordinates of Poisson points\n\n    #create some indexing for the array reshaping step\n    indexFirst=copy(numbPointsCumA);\n    indexFirst[2:end]=indexFirst[1:end-1].+1;\n    indexFirst[1]=1;\n    indexSecond=copy(numbPointsCumA);\n    #reshape point arrays into an array of arrays.\n    for ii in 1:numbSim\n        xxCellA[ii]=(xxAll[indexFirst[ii]:indexSecond[ii]]);\n        yyCellA[ii]=(yyAll[indexFirst[ii]:indexSecond[ii]]);\n    end\n\n    #yyCellAllA=[(yyAll[indexFirst[ii]:indexSecond[ii]]) for ii in 1:numbSim]\nend;\n###END Method A: Generate *all* ensembles at once END###\n\n###START Method B: Generate each ensemble separately START###\n@time begin\n    xxCellB=Array{Array{Float64}}(undef,numbSim);\n    yyCellB=Array{Array{Float64}}(undef,numbSim);\n    numbPointsB=zeros(numbSim);\n    #loop through for all ensembles\n    for ss=1:numbSim\n        numbPointsTemp=rand(Poisson(massTotal));#Poisson number of points\n        xxCellB[ss]=xDelta.*(rand(numbPointsTemp)).+xMin;#x coordinates of Poisson points\n        yyCellB[ss]=yDelta.*(rand(numbPointsTemp)).+yMin;#y coordinates of Poisson points\n        numbPointsB[ss]=numbPointsTemp;\n    end\nend;\n###END Method B: Generate each ensemble separately END###\n###END Simulation section   END###\n", "meta": {"hexsha": "7e3d3e7f4373d6ca0048083e73012811543409c3", "size": 3272, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "TestingJulia/PoissonFast.jl", "max_stars_repo_name": "hpkeeler/posts", "max_stars_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2020-05-14T12:14:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:22:09.000Z", "max_issues_repo_path": "TestingJulia/PoissonFast.jl", "max_issues_repo_name": "hpkeeler/posts", "max_issues_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TestingJulia/PoissonFast.jl", "max_forks_repo_name": "hpkeeler/posts", "max_forks_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-10-26T01:22:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T17:33:40.000Z", "avg_line_length": 37.1818181818, "max_line_length": 89, "alphanum_fraction": 0.7420537897, "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7571736495031541}}
{"text": "# indicator of a halfspace\n\nexport IndHalfspace\n\n\"\"\"\n**Indicator of a halfspace**\n\n    IndHalfspace(a, b)\n\nFor an array `a` and a scalar `b`, returns the indicator of set\n```math\nS = \\\\{x : \\\\langle a,x \\\\rangle \\\\leq b \\\\}.\n```\n\"\"\"\nstruct IndHalfspace{R <: Real, T <: AbstractArray{R}} <: ProximableFunction\n  a::T\n  b::R\n  norm_a::R\n  function IndHalfspace{R, T}(a::T, b::R) where {R <: Real, T <: AbstractArray{R}}\n    norm_a = norm(a)\n    if norm_a == 0 && b < 0\n        error(\"function is improper\")\n    end\n    new(a, b, norm_a)\n  end\nend\n\nIndHalfspace(a::T, b::R) where {R <: Real, T <: AbstractArray{R}} = IndHalfspace{R, T}(a, b)\n\nis_convex(f::IndHalfspace) = true\nis_set(f::IndHalfspace) = true\nis_cone(f::IndHalfspace) = f.b == 0 || f.b == Inf\n\nfunction (f::IndHalfspace{R})(x::AbstractArray{R}) where R\n  if dot(f.a, x) - f.b <= eps(R)*f.norm_a*(1 + abs(f.b))\n    return zero(R)\n  end\n  return R(Inf)\nend\n\nfunction prox!(y::AbstractArray{R}, f::IndHalfspace{R}, x::AbstractArray{R}, gamma::R=one(R)) where R\n  s = dot(f.a, x)\n  if s > f.b\n    y .= x .- ((s - f.b)/f.norm_a^2) .* f.a\n  else\n    copyto!(y, x)\n  end\n  return zero(R)\nend\n\nfun_name(f::IndHalfspace) = \"indicator of a halfspace\"\nfun_dom(f::IndHalfspace) = \"AbstractArray{Real}\"\nfun_expr(f::IndHalfspace) = \"x ↦ 0 if <a,x> ⩽ b, +∞ otherwise\"\nfun_params(f::IndHalfspace) =\n  string( \"a = \", typeof(f.a), \" of size \", size(f.a), \", \",\n          \"b = $(f.b)\")\n\nfunction prox_naive(f::IndHalfspace{R}, x::AbstractArray{R}, gamma::R=one(R)) where R\n  s = dot(f.a, x) - f.b\n  if s <= 0\n    return x, 0.0\n  end\n  return x - (s/norm(f.a)^2)*f.a, 0.0\nend\n", "meta": {"hexsha": "dbd0d8b1c0b0337cabb53a82e6ee368fa943c856", "size": 1619, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indHalfspace.jl", "max_stars_repo_name": "lostella/ProximalOperators.jl", "max_stars_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-15T13:57:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T13:57:52.000Z", "max_issues_repo_path": "src/functions/indHalfspace.jl", "max_issues_repo_name": "lostella/ProximalOperators.jl", "max_issues_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/indHalfspace.jl", "max_forks_repo_name": "lostella/ProximalOperators.jl", "max_forks_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9076923077, "max_line_length": 101, "alphanum_fraction": 0.5960469426, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7571736453789828}}
{"text": "export buildPOP_1v1c, buildPOP_1v2c, buildPOP_1v2, buildPOP_EllJoszMolc\nexport buildPOP_WB2, buildPOP_WB5\nexport lasserre_ex1, lasserre_ex2, lasserre_ex3, lasserre_ex5\nexport get_WB5cliques, get_case9cliques\n\n############################\n### Geometric problems\n############################\n\nfunction buildPOP_1v1c()\n    z = Variable(\"z\", Complex)\n    problem = Problem()\n    add_variable!(problem, z)\n    set_objective!(problem, -real(z))\n    add_constraint!(problem, \"ineq\", abs2(z) << 4)\n    return problem\nend\n\nfunction buildPOP_1v2c()\n    z = Variable(\"z\", Complex)\n    problem = Problem()\n    add_variable!(problem, z)\n    set_objective!(problem, imag(z))\n    add_constraint!(problem, \"ineq_brn\", abs2(z) << 1)\n    θ = π/3\n    add_constraint!(problem, \"ineq_rot\", real(z*exp(-im*θ)) >> 0)\n    return problem\nend\n\nfunction buildPOP_1v2()\n    x1 = Variable(\"x1\", Real)\n    x2 = Variable(\"x2\", Real)\n    problem = Problem()\n    add_variable!(problem, x1); add_variable!(problem, x2)\n    set_objective!(problem, -1.0*x1)\n    add_constraint!(problem, \"ineq\", (x1^2+x2^2) << 1)\n    θ1 = π/3\n    add_constraint!(problem, \"eq_rot1\", (cos(θ1)*x1+sin(θ1)*x2) == 0)\n    # θ2 = -π/3\n    # add_constraint!(problem, \"ineq_rot2\", (cos(θ2)*x1+sin(θ2)*x2) >> 0)\n    return problem\nend\n\n\"\"\"\n    problem = buildPOP_2v3c\n\n    Elliptic example problemp from Josz, Molzahn 2018 paper.\n\"\"\"\nfunction buildPOP_EllJoszMolc()\n    z1 = Variable(\"z1\", Complex)\n    z2 = Variable(\"z2\", Complex)\n    problem = Problem()\n    add_variable!(problem, z1); add_variable!(problem, z2);\n    set_objective!(problem, 3-abs2(z1)-0.5*im*z1*conj(z2)^2+0.5im*z2^2*conj(z1))\n    add_constraint!(problem, \"eq1\", (abs2(z1)-0.25*z1^2-0.25*conj(z1)^2) == 1)\n    add_constraint!(problem, \"eq2\", (abs2(z1)+abs2(z2)) == 3)\n    add_constraint!(problem, \"eq3\", (im*z2-im*conj(z2)) == 0)\n    add_constraint!(problem, \"ineq\", (z2+conj(z2)) >> 0)\n    return problem\nend\n\n############################\n### OPF problems\n############################\n\nfunction buildPOP_WB2(; v2max = 0.976, rmeqs = false, setnetworkphase=false, addball=false)\n    # OPFpbs = load_OPFproblems(MatpowerInput, joinpath(\"..\", \"data\", \"data_Matpower\", \"matpower\", \"WB2.m\"))\n    # problem_c = build_globalpb!(OPFpbs)\n    problem_c, pt = import_from_dat(getinstancepath(\"Matpower\", \"QCQP\", \"WB2\"))\n\n    ## Converting to real ineq. only problem\n    !rmeqs || change_eq_to_ineq!(problem_c)\n    problem = pb_cplx2real(problem_c)\n\n    if setnetworkphase\n        ## Fixing volt phase of last bus to 0\n        lastctr = problem.constraints[\"BaseCase_2_Volt_VOLTM_Re\"]\n        rm_constraint!(problem, \"BaseCase_2_Volt_VOLTM_Re\")\n\n        ## Setting imag part to 0\n        # pt = Point(SortedDict(Variable(\"BaseCase_2_VOLT_Im\", Real)=>0.0), isdense=true)\n        # infer_problem!(problem, pt)\n\n        add_constraint!(problem, \"BaseCase_2_Volt_VOLTM_Re\", sqrt(lastctr.lb) << Variable(\"BaseCase_2_VOLT_Re\", Real) << v2max)\n        add_constraint!(problem, \"BaseCase_2_Volt_VOLTM_Im\", Variable(\"BaseCase_2_VOLT_Im\", Real) == 0)\n    elseif v2max != 0.976\n        problem.constraints[\"BaseCase_2_Volt_VOLTM_Re\"].ub = v2max^2\n    end\n\n    ## Adding ball constraint\n    if addball\n        p = Polynomial()\n        for var in problem.variables\n            p += Variable(var[1], var[2])^2\n        end\n        ub = problem.constraints[\"BaseCase_1_Volt_VOLTM_Re\"].ub + v2max^2\n        add_constraint!(problem, \"Ball_ctr\", p << ub)\n    end\n\n    return problem\nend\n\nfunction buildPOP_WB5(; q5min = 1.05, rmeqs = false)\n    # OPFpbs = load_OPFproblems(MatpowerInput, joinpath(\"..\", \"data\", \"data_Matpower\", \"matpower\", \"WB5.m\"))\n    problem_c, pt = import_from_dat(getinstancepath(\"Matpower\", \"QCQP\", \"WB5\"))\n\n    # Sgen = OPFpbs[\"BaseCase\"].ds.bus[\"BUS_5\"][\"Gen_1\"].power_min\n    # OPFpbs[\"BaseCase\"].ds.bus[\"BUS_5\"][\"Gen_1\"].power_min = real(Sgen) + im*q5min\n    # problem_c = build_globalpb!(OPFpbs)\n\n    ## Converting to real ineq. only problem\n    !rmeqs || change_eq_to_ineq!(problem_c)\n    return pb_cplx2real(problem_c)\nend\n\n\n\n############################\n### Global Optim pbs from Lasserre2001\n############################\n\n\"\"\"\n    problem, relax_ctx = lasserre_ex1()\n\n    From Lasserre2001, global minimum : (3) -0.2428.\n\"\"\"\nfunction lasserre_ex1()\n    x1 = Variable(\"x1\", Real)\n    x2 = Variable(\"x2\", Real)\n    problem = Problem()\n    add_variable!(problem, x1); add_variable!(problem, x2)\n    set_objective!(problem, (x1^2+1)^2 + (x2^2+1)^2 + (x1+x2+1)^2)\n\n    relax_ctx = set_relaxation(problem; hierarchykind=:Real,\n                                        d = 2)\n    return problem, relax_ctx\nend\n\n\"\"\"\n    problem, relax_ctx = lasserre_ex2()\n\n    From Lasserre2001, global minimum : -11.4581.\n\"\"\"\nfunction lasserre_ex2()\n    x1 = Variable(\"x1\", Real)\n    x2 = Variable(\"x2\", Real)\n    problem = Problem()\n    add_variable!(problem, x1); add_variable!(problem, x2)\n    set_objective!(problem, (x1^2+1)^2 + (x2^2+1)^2 -2*(x1+x2+1)^2)\n\n    relax_ctx = set_relaxation(problem; hierarchykind=:Real,\n                                        d = 2)\n    return problem, relax_ctx\nend\n\n\"\"\"\n    problem, relax_ctx = lasserre_ex3()\n\n    From Lasserre2001, global minimum : -1/27, x1*² = x2*² = 1/3.\n\"\"\"\nfunction lasserre_ex3()\n    x1 = Variable(\"x1\", Real)\n    x2 = Variable(\"x2\", Real)\n    problem = Problem()\n    add_variable!(problem, x1); add_variable!(problem, x2)\n    set_objective!(problem, x1^2 * x2^2 * (x1^2 + x2^2 - 1))\n\n    relax_ctx = set_relaxation(problem; hierarchykind=:Real,\n                                        d = 3)\n    return problem, relax_ctx\nend\n\n\"\"\"\n    problem, relax_ctx = lasserre_ex5()\n\n    From Lasserre2001, global minimum : -2, for (1, 2).\n    Relaxation : order 1 -> -3; order 2 -> -2.\n\"\"\"\nfunction lasserre_ex5(;d = 2)\n    x1 = Variable(\"x1\", Real)\n    x2 = Variable(\"x2\", Real)\n    problem = Problem()\n    add_variable!(problem, x1); add_variable!(problem, x2)\n    set_objective!(problem, -(x1-1)^2 -(x1-x2)^2 -(x2-3)^2)\n    add_constraint!(problem, \"crt1\", (1-(x1-1)^2) >> 0)\n    add_constraint!(problem, \"crt2\", (1-(x1-x2)^2) >> 0)\n    add_constraint!(problem, \"crt3\", (1-(x2-3)^2) >> 0)\n\n    relax_ctx = set_relaxation(problem; hierarchykind=:Real,\n                                        d = d)\n    return problem, relax_ctx\nend\n\n\n\nfunction get_WB5cliques(relax_ctx, problem)\n    if !relax_ctx.issparse\n        return get_maxcliques(relax_ctx, problem)\n    else\n        maxcliques = Dict{String, Set{Variable}}()\n        maxcliques[\"clique1\"] = Set{Variable}([\n            Variable(\"BaseCase_1_VOLT_Im\", Real),\n            Variable(\"BaseCase_1_VOLT_Re\", Real),\n            Variable(\"BaseCase_2_VOLT_Im\", Real),\n            Variable(\"BaseCase_2_VOLT_Re\", Real),\n            Variable(\"BaseCase_3_VOLT_Im\", Real),\n            Variable(\"BaseCase_3_VOLT_Re\", Real)])\n        maxcliques[\"clique2\"] = Set{Variable}([\n            Variable(\"BaseCase_2_VOLT_Im\", Real),\n            Variable(\"BaseCase_2_VOLT_Re\", Real),\n            Variable(\"BaseCase_3_VOLT_Im\", Real),\n            Variable(\"BaseCase_3_VOLT_Re\", Real),\n            Variable(\"BaseCase_4_VOLT_Im\", Real),\n            Variable(\"BaseCase_4_VOLT_Re\", Real),\n            Variable(\"BaseCase_5_VOLT_Im\", Real),\n            Variable(\"BaseCase_5_VOLT_Re\", Real)])\n        return maxcliques\n    end\nend\n\nfunction get_case9cliques(relax_ctx, problem)\n    if !relax_ctx.issparse\n        return get_maxcliques(relax_ctx, problem)\n    else\n        maxcliques = Dict{String, Set{Variable}}()\n        maxcliques[\"clique1\"] = Set{Variable}([\n            Variable(\"BaseCase_1_VOLT_Im\", Real),\n            Variable(\"BaseCase_1_VOLT_Re\", Real),\n            Variable(\"BaseCase_5_VOLT_Im\", Real),\n            Variable(\"BaseCase_5_VOLT_Re\", Real),\n            Variable(\"BaseCase_4_VOLT_Im\", Real),\n            Variable(\"BaseCase_4_VOLT_Re\", Real),\n            Variable(\"BaseCase_9_VOLT_Im\", Real),\n            Variable(\"BaseCase_9_VOLT_Re\", Real),\n            Variable(\"BaseCase_8_VOLT_Im\", Real),\n            Variable(\"BaseCase_8_VOLT_Re\", Real)])\n        maxcliques[\"clique2\"] = Set{Variable}([\n            Variable(\"BaseCase_2_VOLT_Im\", Real),\n            Variable(\"BaseCase_2_VOLT_Re\", Real),\n            Variable(\"BaseCase_9_VOLT_Im\", Real),\n            Variable(\"BaseCase_9_VOLT_Re\", Real),\n            Variable(\"BaseCase_8_VOLT_Im\", Real),\n            Variable(\"BaseCase_8_VOLT_Re\", Real),\n            Variable(\"BaseCase_7_VOLT_Im\", Real),\n            Variable(\"BaseCase_7_VOLT_Re\", Real),\n            Variable(\"BaseCase_6_VOLT_Im\", Real),\n            Variable(\"BaseCase_6_VOLT_Re\", Real)])\n        maxcliques[\"clique3\"] = Set{Variable}([\n            Variable(\"BaseCase_3_VOLT_Im\", Real),\n            Variable(\"BaseCase_3_VOLT_Re\", Real),\n            Variable(\"BaseCase_7_VOLT_Im\", Real),\n            Variable(\"BaseCase_7_VOLT_Re\", Real),\n            Variable(\"BaseCase_6_VOLT_Im\", Real),\n            Variable(\"BaseCase_6_VOLT_Re\", Real),\n            Variable(\"BaseCase_5_VOLT_Im\", Real),\n            Variable(\"BaseCase_5_VOLT_Re\", Real),\n            Variable(\"BaseCase_4_VOLT_Im\", Real),\n            Variable(\"BaseCase_4_VOLT_Re\", Real)])\n        return maxcliques\n    end\nend\n", "meta": {"hexsha": "9457bcfdb301ee66ccc8c56bff193b75e7fad314", "size": 9163, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SDPhierarchy/example_problems.jl", "max_stars_repo_name": "kersulis/MathProgComplex.jl", "max_stars_repo_head_hexsha": "8aa002b1e7398d67c0e9e03cf94d09b2bf5fe6b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-06-28T09:45:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T07:40:54.000Z", "max_issues_repo_path": "src/SDPhierarchy/example_problems.jl", "max_issues_repo_name": "kersulis/MathProgComplex.jl", "max_issues_repo_head_hexsha": "8aa002b1e7398d67c0e9e03cf94d09b2bf5fe6b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-08-07T06:40:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-07T09:35:18.000Z", "max_forks_repo_path": "src/SDPhierarchy/example_problems.jl", "max_forks_repo_name": "kersulis/MathProgComplex.jl", "max_forks_repo_head_hexsha": "8aa002b1e7398d67c0e9e03cf94d09b2bf5fe6b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-08-07T02:35:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-07T07:46:04.000Z", "avg_line_length": 34.9732824427, "max_line_length": 127, "alphanum_fraction": 0.614973262, "num_tokens": 2793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7571736451974567}}
{"text": "# TODO: I cound that \"utils.jl\" has been `include`ed in the main `VectorSphericalWaves` module. Is there a more neat way? when I `include(\"utils.jl\")` here, I get lots of warnings.\n\n# exporting functions that calculate for all m,n combinations\nexport M_N_wave_all_m_n\nexport B_C_P_mn_of_θ_ϕ_for_all_m_n\nexport πₘₙ_τₘₙ_all_all_m_n\n\n#############################################################################################\n# This version is different from \"VectorSphericalHarmonics.jl\", as it calculate VSWF for all m,n and all kr, θ, ϕ in one call\n# This should be more stable and faster, as it employs recurrence relations in calculating πₘₙ and τₘₙ\n# using recurrence relations in calculating πₘₙ and τₘₙ\n\n#############################################################################################\n# calculate π(θ) and τ(θ) using recurrence relations\nfunction πₘₙ_τₘₙ_all_all_m_n(n_max::I, θ::R; verbose=false) where {R <: Real, I <: Integer}\n    # calculate A with recurrence relation\n    A = SortedDict(0 => 1.0)\n    for m = 0:n_max - 1\n        A[m + 1] = A[m] * sqrt((2m + 1) / (2 * (m + 1)))\n    end\n\n    # calculate πₘₙ with recurrence relation\n    πₘₙ_all = zeros(get_max_single_index_from_n_max(n_max))\n    for m = 1:n_max   # TODO: I think I need to start m from 0, not 1.\n        n = m\n        πₘₙ_all[single_index_from_m_n(m, n)] = m * A[m] * sin(θ)^(m - 1)\n        if verbose; println(\"m=$m, n=$n, πₘₙ_all=$(πₘₙ_all[single_index_from_m_n(m, n)])\"); end\n\n        # calculate π₋ₘₙ from πₘₙ\n        if m != 0\n            πₘₙ_all[single_index_from_m_n(-m, n)] = (-1)^(m + 1) * πₘₙ_all[single_index_from_m_n(m, n)]\n            if verbose; println(\"m=$(-m), n=$n, πₘₙ_all=$(πₘₙ_all[single_index_from_m_n(-m, n)])\"); end\n        end\n\n        for n = (m + 1):n_max\n            if n == m + 1\n                πₘₙ_all[single_index_from_m_n(m, n)] = 1 / sqrt(n^2 - m^2) * ((2n - 1) * cos(θ) * πₘₙ_all[single_index_from_m_n(m, n - 1)])\n                if verbose; println(\"m=$m, n=$n, πₘₙ_all=$(πₘₙ_all[single_index_from_m_n(m, n)])\"); end\n            else\n                πₘₙ_all[single_index_from_m_n(m, n)] = 1 / sqrt(n^2 - m^2) * ((2n - 1) * cos(θ) * πₘₙ_all[single_index_from_m_n(m, n - 1)]) - sqrt((n - 1)^2 - m^2) * πₘₙ_all[single_index_from_m_n(m, n - 2)]\n                if verbose; println(\"m=$m, n=$n, πₘₙ_all=$(πₘₙ_all[single_index_from_m_n(m, n)])\"); end\n            end\n\n            # calculate π₋ₘₙ from πₘₙ\n            if m != 0\n                πₘₙ_all[single_index_from_m_n(-m, n)] = (-1)^(m + 1) * πₘₙ_all[single_index_from_m_n(m, n)]\n                if verbose; println(\"m=$(-m), n=$n, πₘₙ_all=$(πₘₙ_all[single_index_from_m_n(-m, n)])\"); end\n            end\n        end\n    end\n    τₘₙ_all = 0 # TODO: add the code for it\n    return πₘₙ_all, τₘₙ_all\nend\n\n\n\n\n\n#############################################################################################\n# Legendre and Associated Legendre\nfunction Legendre_polynomials_Pn_array(n_max::I, x::NN) where {I <: Integer, NN <: Number}\n    \"\"\"\n    Calculate all Legendre polynomials Pₙ(x) from n = 1 up to n=n_max using recurrence relation\n    https://en.wikipedia.org/wiki/Legendre_polynomials\n\n    returns\n    dictionary. TODO: find a better way if this cause adjoint calculation trouble\n    \"\"\"\n    P = SortedDict(\n        0 => 1,\n        1 => x,\n    )\n\n    for n = 1:(n_max - 1)\n        P[n + 1] = ((2n + 1) * x * P[n] - n * P[n - 1]) / (n + 1)\n    end\n\n    return P\nend\n\nfunction Legendre_polynomials_Pn(n::I, x::NN) where {I <: Integer, NN <: Number}\n    \"\"\"\n    Calculate Legendre polynomials Pₙ(x) at a given n\n    \"\"\"\n    return Legendre_polynomials_Pn_array(n, x)[n]\nend\n\nfunction Associated_Legendre_polynomials_Pmn_array(m::I, n_max::I, x) where {I <: Integer}\n    \"\"\"\n    Associated Legendre polynomials Pᵐₙ(x) from n = m up to n=n_max using recurrence relation\n    https://en.wikipedia.org/wiki/Associated_Legendre_polynomials#Recurrence_formula\n\n    returns\n    dictionary. TODO: find a better way if this cause adjoint calculation trouble\n    \"\"\"\n    n = m\n    P = SortedDict(\n        n => (-1)^n * factorial(factorial(2n - 1)) * (1 - x^2)^(n / 2),\n    )\n    P[n + 1] = x * (2n + 1) * P[n]\n\n    for n = (m + 1):(n_max - 1)\n        P[n + 1] = ( (2n + 1) * x * P[n] - (n + m) * P[n - 1] ) / (n - m + 1)\n    end\n\n    return P\nend\n\nfunction Associated_Legendre_polynomials_Pmn(m::I, n::I, x) where {I <: Integer}\n    \"\"\"\n    Associated Legendre polynomials Pᵐₙ(x) at a given n\n    \"\"\"\n    return Associated_Legendre_polynomials_Pmn_array(m, n, x)[n]\nend\n\n#############################################################################################\n# Wigner-d, using recurrence\n# TODO: I think this will not work for large s,m,n values, try to fix it as in `wignerdjmn_ELZOUKA`\nfunction wignerd_and_∂wignerd_for_all_s(s_max::I, m::I, n::I, θ::R; get_derivatives=true, verbose=false) where {R <: Real, I <: Integer}\n    \"\"\"\n    Calculate dˢₘₙ(θ) and ∂(dˢₘₙ(θ))/∂θ for all values of s, where s starts from s_min up to s_max. s_min is the maximum of |m| and |n|\n\n    \"\"\"\n    # TODO: special case of m=0, n=0 (eq. B.27)\n    s_min = max(abs(m), abs(n))\n\n    # calculate ξ from eq. B.16\n    if n >= m\n        ξ_mn = 1\n    else\n        ξ_mn = (-1)^(m - n)\n    end\n\n    x = cos(θ)\n\n    # calculate d^s_min__m_n(θ) from eq. B.24\n    d_smin_m_n =\n        ξ_mn * 2.0^(-s_min) * sqrt(\n            factorial(BigInt(2s_min)) / (factorial(BigInt(abs(m - n))) * factorial(BigInt(abs(m + n))))\n        ) *\n        (1 - x)^(abs(m - n) / 2) *\n        (1 + x)^(abs(m + n) / 2)\n\n    d = SortedDict(\n        s_min - 1 => 0.0,\n        s_min   => d_smin_m_n\n    )\n\n    # applying the recurrence relation\n    if n == 0\n        if m == 0\n            if verbose; println(\"m=$m, n=$n, I will use Legendre_polynomials_Pn_array\"); end\n            P_s = Legendre_polynomials_Pn_array(s_max + 1, x)\n            for s = s_min:s_max + 1\n                d[s] = P_s[s]\n            end\n        else\n            if verbose; println(\"m=$m, n=$n, I will use Associated_Legendre_polynomials_Pmn_array\"); end\n            P_m_s = Associated_Legendre_polynomials_Pmn_array(m, s_max + 1, x)\n            for s = s_min:s_max + 1\n                d[s] = sqrt(factorial(s - m) / factorial(s + m)) * P_m_s[s]\n            end\n        end\n    else\n        for s = s_min:s_max + 1\n            if verbose; println(\"m=$m, n=$n, I will use the general recurrence\"); end\n            d[s + 1] = 1 / (s * sqrt((s + 1)^2 - m^2) * sqrt((s + 1)^2 - n^2)) * (\n                (2s + 1) * (s * (s + 1) * x - m * n) * d[s]\n                - 1 * (s + 1) * sqrt(s^2 - m^2) * sqrt(s^2 - n^2) * d[s - 1]\n            ) # eq. B.22\n        end\n    end\n\n    # calculate the derivative ∂(dˢₘₙ(θ))/∂θ\n    if get_derivatives\n        ∂d_∂θ = SortedDict(\n            s_min - 1 => 0.0,\n            s_min   => 0.0\n        )\n\n        sin_theta = sin(θ)\n\n        for s = s_min:s_max\n            if verbose; println(\"s=$s\"); end\n            ∂d_∂θ[s] = 1 / sin_theta * (\n                -1 * ((s + 1) * sqrt((s^2 - m^2) * (s^2 - n^2))) / (s * (2s + 1)) * d[s - 1]\n                - 1 * (m * n) / (s * (s + 1)) * d[s]\n                + 1 * (\n                        s *\n                        sqrt((s + 1)^2 - m^2) *\n                        sqrt((s + 1)^2 - n^2)\n                    ) /\n                    ((s + 1) * (2s + 1)) * d[s + 1]\n            )\n        end\n        return d, ∂d_∂θ\n    else\n        return d\n    end\n\n\nend\n\n#############################################################################################\n# calculate π(θ) and τ(θ) using Wigner-d that was calculated using recurrence relations\nfunction πₘₙ_τₘₙ_all_all_m_n_using_wigner(n_max::I, θ::R; verbose=false) where {R <: Real, I <: Integer}\n    πₘₙ_all = zeros(get_max_single_index_from_n_max(n_max))\n    τₘₙ_all = zeros(get_max_single_index_from_n_max(n_max))\n\n    for m = 0:n_max  # TODO: special case of m=0\n        d_rec_all_n, ∂d_∂θ_rec_all_n  = wignerd_and_∂wignerd_for_all_s(n_max, 0, m, θ)\n        for n = m:n_max\n            if n != 0\n                if verbose; println(\"m=$m, n=$n, calculate πₘₙ_all, τₘₙ_all\"); end\n                πₘₙ_all[single_index_from_m_n(m, n)] = m / sin(θ) * d_rec_all_n[n]\n                τₘₙ_all[single_index_from_m_n(m, n)] = ∂d_∂θ_rec_all_n[n]\n\n                if m != 0\n                    πₘₙ_all[single_index_from_m_n(-m, n)] = (-1)^(m + 1) * πₘₙ_all[single_index_from_m_n(m, n)]\n                    τₘₙ_all[single_index_from_m_n(-m, n)] = (-1)^(m)   * τₘₙ_all[single_index_from_m_n(m, n)]\n                end\n            end\n        end\n    end\n    return πₘₙ_all, τₘₙ_all\nend\n\nfunction B_C_mn_of_θ_for_all_m_n(n_max::I, θ::R) where {R <: Real, I <: Integer}\n    \"\"\"\n    Calculate Bₙₘ(θ), Cₙₘ(θ), Pₙₘ(θ) equations C.19, C.20, C.21\n    The order of m,n is according to the function \"single_index_from_m_n\"\n    \"\"\"\n    πₘₙ_all, τₘₙ_all = πₘₙ_τₘₙ_all_all_m_n_using_wigner(n_max, θ)\n    B = (_ -> zero(SVector{3,Complex})).(πₘₙ_all)\n    C = (_ -> zero(SVector{3,Complex})).(πₘₙ_all)\n    for idx in eachindex(πₘₙ_all)\n        B[idx] = [0,      τₘₙ_all[idx], im * πₘₙ_all[idx] ]\n        C[idx] = [0, im * πₘₙ_all[idx], -1 * τₘₙ_all[idx] ]\n    end\n\n    return B, C\nend\n\nfunction P_mn_of_θ_for_all_m_n(n_max::I, θ::R) where {R <: Real, I <: Integer}\n    \"\"\"\n    Calculate Pₙₘ(θ) using equations C.19, C.20\n    The order of m,n is according to the function \"single_index_from_m_n\"\n    \"\"\"\n    P = fill(zero(SVector{3,Complex}), get_max_single_index_from_n_max(n_max))\n    for m = 0:n_max\n        d_rec_all_n  = wignerd_and_∂wignerd_for_all_s(n_max, 0, m, θ; get_derivatives=false)\n        for n = m:n_max\n            if n != 0\n                P[single_index_from_m_n(m, n)] = [d_rec_all_n[n], 0, 0]\n                P[single_index_from_m_n(-m, n)] = [(-1)^m * d_rec_all_n[n], 0, 0]  # using symmetry relation B.5, we can get d_(0,-m) from d_(0,m)\n            end\n        end\n    end\n    return P\nend\n\nfunction B_C_P_mn_of_θ_ϕ_for_all_m_n(n_max::I, θ::R, ϕ::R) where {R <: Real, I <: Integer}\n    \"\"\"\n    Calculate Bₙₘ(θ,ϕ), Cₙₘ(θ,ϕ), Pₙₘ(θ,ϕ) for all m and n\n    \"\"\"\n    B_of_θ, C_of_θ = B_C_mn_of_θ_for_all_m_n(n_max, θ)\n    P_of_θ = P_mn_of_θ_for_all_m_n(n_max, θ)\n\n    for n = 1:n_max\n        for m = -n:n\n            factor = (-1)^m * convert(R, sqrt_factorial_n_plus_m_over_factorial_n_minus_m(m,n)) * exp(im * m * ϕ)\n            B_of_θ[single_index_from_m_n(m, n)] *= factor\n            C_of_θ[single_index_from_m_n(m, n)] *= factor\n            P_of_θ[single_index_from_m_n(m, n)] *= factor\n        end\n    end\n\n    return B_of_θ, C_of_θ, P_of_θ\nend\n\nfunction M_N_wave_all_m_n(n_max::I, kr::NN, θ::R, ϕ::R; kind=\"regular\") where {R <: Real, I <: Integer, NN <: Number}\n    \"\"\"\n    Parameters\n    ==========\n    kind: string, either [\"regular\" or \"incoming\"] or [\"irregular\" or \"outgoing\"]\n    \"\"\"\n    radial_function, radial_function_special_derivative  = get_radial_function_and_special_derivative_given_kind(kind)\n\n    B_of_θ_ϕ, C_of_θ_ϕ, P_of_θ_ϕ  = B_C_P_mn_of_θ_ϕ_for_all_m_n(n_max, θ, ϕ)\n\n    M = 0 .* B_of_θ_ϕ\n    N = 0 .* B_of_θ_ϕ\n\n    for n = 1:n_max\n        for m = -n:n\n            M[single_index_from_m_n(m, n)] = convert(R, γ_mn(m, n)) * radial_function(n, kr) * C_of_θ_ϕ[single_index_from_m_n(m, n)]\n            N[single_index_from_m_n(m, n)] = convert(R, γ_mn(m, n)) * (\n                n * (n + 1) / kr * radial_function(n, kr)    * P_of_θ_ϕ[single_index_from_m_n(m, n)]\n                + (radial_function_special_derivative(n, kr) * B_of_θ_ϕ[single_index_from_m_n(m, n)])\n            )\n        end\n    end\n    return M, N\nend\n", "meta": {"hexsha": "2253bcc24826f3a0f0cd293bdcc4a845d1c38841", "size": 11552, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vectorSphericalWaves_complex_all_indices.jl", "max_stars_repo_name": "alok/VectorSphericalWaves.jl", "max_stars_repo_head_hexsha": "0f0dce5624bd97a560560ae2e4cbc67ae9b4a5bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/vectorSphericalWaves_complex_all_indices.jl", "max_issues_repo_name": "alok/VectorSphericalWaves.jl", "max_issues_repo_head_hexsha": "0f0dce5624bd97a560560ae2e4cbc67ae9b4a5bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-27T21:02:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T21:02:02.000Z", "max_forks_repo_path": "src/vectorSphericalWaves_complex_all_indices.jl", "max_forks_repo_name": "alok/VectorSphericalWaves.jl", "max_forks_repo_head_hexsha": "0f0dce5624bd97a560560ae2e4cbc67ae9b4a5bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-09T04:56:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T04:56:05.000Z", "avg_line_length": 37.8754098361, "max_line_length": 206, "alphanum_fraction": 0.5438019391, "num_tokens": 4081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.75717363336952}}
{"text": "module pindex\n\ngreet() = print(\"Hello World!\")\n\nusing Distributions, Parameters, LinearAlgebra, Compat, Test\n\nfunction FixedLaspeyres(p,q)\nN=size(p,1)\nT=size(p,2)\nPl=zeros(N+1,T)\ns=zeros(N,T)\n   for t in 1:T\n        for n in 2:N+1\n        s[n-1,t] = (p[n-1,t]*q[n-1,t])/p[:,t]'q[:,t]\n        Pl[n,t]=Pl[n-1,t]+p[n-1,t]/p[n-1,1]*s[n-1,1]\n        end\n    end\nreturn Pl[N+1,:]\nend\n\nfunction FixedPaasche(p,q)\nN=size(p,1)\nT=size(p,2)\nPp=zeros(N+1,T)\ns=zeros(N,T)\n   for t in 1:T\n        for n in 2:N+1\n        s[n-1,t] = p[n-1,t]*q[n-1,t]/p[:,t]'q[:,t]\n        Pp[n,t]=Pp[n-1,t]+p[n-1,1]/p[n-1,t]*s[n-1,t]\n        end\n    end\nreturn Pp[N+1,:].^(-1)\nend\n\nfunction FixedFisher(p,q)\n     Pf=(FixedPaasche(p,q).^(1/2)).*(FixedLaspeyres(p,q).^(1/2))\nreturn Pf\nend\n\nfunction FixedTornqvist(p,q)\nN=size(p,1)\nT=size(p,2)\nPt=zeros(N+1,T)\ns=zeros(N,T)\n   for t in 1:T\n        for n in 2:N+1\n        s[n-1,t] = p[n-1,t]*q[n-1,t]/p[:,t]'q[:,t]\n        Pt[n,t]=(1/2)*(s[n-1,1]+s[n-1,t])*log(p[n-1,t]/p[n-1,1])\n        end\n    end\nreturn exp.(Pt[N+1,:])\nend\n\nfunction ChainedLaspeyres(p,q)\nN=size(p,1)\nT=size(p,2)\nPl=zeros(N+1,T)\nPlc=ones(N+1,T)\ns=zeros(N,T)\n   for t in 2:T\n        for n in 2:N+1\n        s[n-1,t-1] = p[n-1,t-1]*q[n-1,t-1]/p[:,t-1]'q[:,t-1]\n        Pl[n,t]=Pl[n-1,t]+p[n-1,t]/p[n-1,t-1]*s[n-1,t-1]\n        Plc[n,t]=Plc[n,t-1]*Pl[n,t]\n        end\n    end\nreturn Plc[N+1,:]\nend\n\nfunction ChainedPaasche(p,q)\nN=size(p,1)\nT=size(p,2)\nPp=zeros(N+1,T)\nPpc=ones(N+1,T)\ns=zeros(N,T)\n   for t in 2:T\n        for n in 2:N+1\n        s[n-1,t] = (p[n-1,t]*q[n-1,t])/p[:,t]'q[:,t]\n        Pp[n,t]=Pp[n-1,t]+p[n-1,t-1]/p[n-1,t]*s[n-1,t]\n        Ppc[n,t]=Ppc[n,t-1]*(Pp[n,t])^(-1)\n        end\n    end\nreturn Ppc[N+1,:]\nend\n\nfunction ChainedFisher(p,q)\n     Pfc=(ChainedPaasche(p,q).^(1/2)).*(ChainedLaspeyres(p,q).^(1/2))\nreturn Pfc\nend\n\nfunction ChainedTornqvist(p,q)\nN=size(p,1)\nT=size(p,2)\nPt=zeros(N+1,T)\nPtc=ones(N+1,T)\ns=zeros(N,T)\n   for t in 2:T\n        for n in 2:N+1\n        s[n-1,t-1] = p[n-1,t-1]*q[n-1,t-1]/p[:,t-1]'q[:,t-1]\n        s[n-1,t] = (p[n-1,t]*q[n-1,t])/p[:,t]'q[:,t]\n        Pt[n,t]=Pt[n-1,t]+(1/2)*(s[n-1,t-1]+s[n-1,t])*log(p[n-1,t]/p[n-1,t-1])\n        Ptc[n,t]=Ptc[n,t-1]*exp(Pt[n,t])\n        end\n    end\nreturn Ptc[N+1,:]\nend\n\nfunction FixLaspeyres(p,q)\nN=size(p,1)\nT=size(p,2)\nPl=zeros(T)\n    for t in 1:T\n    Pl[t]=p[:,t]'q[:,1]/p[:,1]'q[:,1]\n    end\nreturn Pl\nend\n\nfunction FixPaasche(p,q)\nN=size(p,1)\nT=size(p,2)\nPl=zeros(T)\n    for t in 1:T\n    Pl[t]=p[:,t]'q[:,t]/p[:,1]'q[:,t]\n    end\nreturn Pl\nend\n\nfunction FixFisher(p,q)\n     Pf=(FixPaasche(p,q).^(1/2)).*(FixLaspeyres(p,q).^(1/2))\nreturn Pf\nend\n\nfunction ChainLaspeyres(p,q)\nN=size(p,1)\nT=size(p,2)\nPl=ones(T)\nPlc=ones(T)\n    for t in 2:T\n    Pl[t]=p[:,t]'q[:,t-1]/p[:,t-1]'q[:,t-1]\n    Plc[t]=Plc[t-1]*Pl[t]\n    end\nreturn Plc\nend\n\nfunction ChainPaasche(p,q)\nN=size(p,1)\nT=size(p,2)\nPp=ones(T)\nPpc=ones(T)\n    for t in 2:T\n    Pp[t]=p[:,t]'q[:,t]/p[:,t-1]'q[:,t]\n    Ppc[t]=Ppc[t-1]*Pp[t]\n    end\nreturn Ppc\nend\n\nfunction ChainFisher(p,q)\n    Pfc=(ChainPaasche(p,q).^(1/2)).*(ChainLaspeyres(p,q).^(1/2))\nreturn Pfc\nend\n\nexport FixedLaspeyres,  FixedPaasche, FixedFisher, FixedTornqvist, ChainedLaspeyres, ChainedPaasche, ChainedFisher, ChainedTornqvist, FixLaspeyres, FixPaasche, FixFisher, ChainLaspeyres, ChainPaasche, ChainFisher\n\nend # module\n", "meta": {"hexsha": "a5a481fc4884d6bdab6ee555425b3aa78cf2d4bd", "size": 3320, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pindex.jl", "max_stars_repo_name": "sejinahn2/pindex.jl", "max_stars_repo_head_hexsha": "920d5480af8fc28173b53e3c372e41df55902e74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pindex.jl", "max_issues_repo_name": "sejinahn2/pindex.jl", "max_issues_repo_head_hexsha": "920d5480af8fc28173b53e3c372e41df55902e74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pindex.jl", "max_forks_repo_name": "sejinahn2/pindex.jl", "max_forks_repo_head_hexsha": "920d5480af8fc28173b53e3c372e41df55902e74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1212121212, "max_line_length": 212, "alphanum_fraction": 0.5451807229, "num_tokens": 1501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7571554292883514}}
{"text": "module MyInterpolations\n\nexport MyLinInterp\n\nimmutable MyLinInterp\n    grid::Array\n    vals::Array\nend\n\nfunction (f::MyLinInterp)(x)\n    i = searchsortedlast(f.grid,x)\n    k = searchsortedfirst(f.grid,x)\n    if i == 0 || (i == length(f.grid) && k == length(f.grid) + 1)\n        return 0\n    end\n\n    if i == length(f.grid) && k != length(f.grid) + 1\n        return (f.vals[i])\n    end\n    \n    interpolated_value = (x - f.grid[i])*(f.vals[i+1]-f.vals[i])/(f.grid[i+1]-f.grid[i])+f.vals[i]\n    return interpolated_value \nend\n\nend", "meta": {"hexsha": "87e8bc91418786a43f72efa73082131cdb1f92e7", "size": 528, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MyInterpolations.jl", "max_stars_repo_name": "IoriS/Myinterpolation.jl", "max_stars_repo_head_hexsha": "0c8ab904d24029a7146f4d5d9e8e7d10ef3ac5b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MyInterpolations.jl", "max_issues_repo_name": "IoriS/Myinterpolation.jl", "max_issues_repo_head_hexsha": "0c8ab904d24029a7146f4d5d9e8e7d10ef3ac5b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MyInterpolations.jl", "max_forks_repo_name": "IoriS/Myinterpolation.jl", "max_forks_repo_head_hexsha": "0c8ab904d24029a7146f4d5d9e8e7d10ef3ac5b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.12, "max_line_length": 98, "alphanum_fraction": 0.5984848485, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7571554202782816}}
{"text": "\"\"\"\n    interval_norm(A::Matrix{Interval})\n\ncomputes the infinite norm of interval matrix A\n\"\"\"\ninterval_norm(A::AbstractMatrix) = maximum(sum(mag.(A); dims=2)) # TODO: proper expand norm function and add 1-norm\ninterval_norm(v::AbstractVector) = maximum(mag.(v))\n\"\"\"\nPreconditions the interval system Ax = b by multipling by the (approximate) inverse of Ac,\nthat is the midpoint of A.\n\"\"\"\nfunction precondition(A, b)\n    Ac = mid.(A)\n    return Ac\\A, Ac\\b\nend\n\n\n\"\"\"\n    enclose(A::Matrix{Interval}, b::Vector{Interval})\n\nComputes an initial enclosure Σ so that x ⊆ Σ, where x is the solution of the interval\nsystem Ax = b.\n\"\"\"\nfunction enclose(A::SMatrix{N, N, T, M}, b::SVector{N, T}) where {N, T, M}\n    A1 = I - A\n    e = interval_norm(b)/(1 - interval_norm(A1))\n    x0 = MVector{N, T}(fill(-e..e, N))\n    return x0\nend\nfunction enclose(A::MMatrix{N, N, T, M}, b::MVector{N, T}) where {N, T, M}\n    A1 = I - A\n    e = interval_norm(b)/(1 - interval_norm(A1))\n    x0 = MVector{N, T}(fill(-e..e, N))\n    return x0\nend\n\nfunction enclose(A, b)\n    A1 = I - A\n    e = interval_norm(b)/(1 - interval_norm(A1))\n    x0 = fill(-e..e, length(b)  )\n    return x0\nend\n\n\"\"\"\n    comparison_matrix(A::Matrix{Interval})\n\nComputes the comparison matrix ⟨A⟩ of the given matrix A according to the definition\n⟨A⟩_ii = mig(A_ii)\n⟨A⟩_ij = -mag(A_ij)\n\"\"\"\nfunction comparison_matrix(A)\n    n = size(A, 1)\n    compA = -mag.(A)\n    @inbounds for (i, idx) in enumerate(diagind(A))\n        compA = setindex(compA, mig(A[i, i]), idx)\n    end\n    return compA\nend\n", "meta": {"hexsha": "14f370fd7ec4ea36b6894f76c71bd3d7ae039846", "size": 1539, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "mforets/IntervalLinearAlgebra.jl", "max_stars_repo_head_hexsha": "40726db50873af9a2d956496aa67a57aeb366c54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "mforets/IntervalLinearAlgebra.jl", "max_issues_repo_head_hexsha": "40726db50873af9a2d956496aa67a57aeb366c54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "mforets/IntervalLinearAlgebra.jl", "max_forks_repo_head_hexsha": "40726db50873af9a2d956496aa67a57aeb366c54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0847457627, "max_line_length": 115, "alphanum_fraction": 0.636777128, "num_tokens": 501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896737173119, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7570632632331332}}
{"text": "module zad2\n\nfunction zad22(funk,xL,xU;ep=1e-8,golden=0.618)\n              fa=funk(xL)\n              fb=funk(xU)\n              x1=xU-((xU-xL)*(golden))\n              x2=xL+((xU-xL)*(golden))\n              err=Inf\n              while err>ep\n                  if funk(x2)<funk(x1)\n                      xL=x1\n                      x1=x2\n                      x2=xU-((xU-xL)*(golden))\n                  elseif funk(x2)>funk(x1)\n                      xU=x2\n                      x2=x1\n                  x1=xL+((xU-xL)*(golden))\n                  else\n                      xL=(x1+x2)/2\n                      xU=xL\n                  end\n                 err=2*abs((xU-xL)/(xU+xL))\n                  end\n              Xmin=(x1+x2)/2\n              print(\"Minimum: \",round(funk(Xmin),digits=2), \" for: \", Xmin, \" x1: \" ,round(x1,digits=2), \" x2: \", round(x2,digits=2))\n\n       return(round(funk(Xmin),digits=2),round(Xmin,digits=2))\n       end\n\t   \nexport zad22\n\nend # module\n", "meta": {"hexsha": "f6345c7ffcbbff6e271c055f1cf63383ae178a70", "size": 968, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/zad2.jl", "max_stars_repo_name": "CarnariusXx/MO_zad2", "max_stars_repo_head_hexsha": "d78d498c68176e461b875616a0ffc7a92119e508", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/zad2.jl", "max_issues_repo_name": "CarnariusXx/MO_zad2", "max_issues_repo_head_hexsha": "d78d498c68176e461b875616a0ffc7a92119e508", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/zad2.jl", "max_forks_repo_name": "CarnariusXx/MO_zad2", "max_forks_repo_head_hexsha": "d78d498c68176e461b875616a0ffc7a92119e508", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3333333333, "max_line_length": 133, "alphanum_fraction": 0.375, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7570632623581591}}
{"text": "# Model m4.3as.jl\n\nusing Pkg, DrWatson\n\nbegin\n    using StanQuap\n    using StatisticalRethinking\nend\n\nbegin\n    df = CSV.read(sr_datadir(\"Howell1.csv\"), DataFrame; delim=';')\n    df = filter(row -> row[:age] >= 18, df);\n    mean_weight = mean(df.weight)\n    #df.weight_c = df.weight .- mean_weight\nend;\n\nstan4_3 = \"\ndata {\n    int<lower=1> N;\n    vector[N] weight;\n    vector[N] height;\n}\nparameters {\n    real a;\n    real<lower=0> b;\n    real<lower=0, upper=50> sigma;\n}\nmodel {\n    // Define mu as a vector.\n    vector[N] mu;\n\n    // Priors for mu and sigma\n    sigma ~ uniform(0 , 50);\n    a ~ normal($(mean_weight), 20);\n    b ~ lognormal(0, 1);\n\n    // Observed heights\n    for (i in 1:N) {\n    mu[i] = a + b * (weight[i] - $(mean_weight));\n    }\n    height ~ normal(mu, sigma);\n}\n\";\n\ndata = (N = length(df.height), height = df.height, weight = df.weight)\ninit = (a = 180.0, b = 1.0, sigma = 10.0)\nq4_3s, m4_3s, o4_3s = stan_quap(\"m4.2s\", stan4_3; data, init);\n\nif q4_3s.converged  \n    quap4_3s_df = sample(q4_3s)          # DataFrame with samples\n    precis(quap4_3s_df)\n    post4_3s = read_samples(m4_3s)\n    post4_3s |> display\nend\n\n# End of m4.3as.jl", "meta": {"hexsha": "4152cf808092ae4449754690edd14e1e7370be78", "size": 1160, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/04/m4.3s.jl", "max_stars_repo_name": "pitmonticone/StatisticalRethinkingStan.jl", "max_stars_repo_head_hexsha": "9eee333465b3b8ec5975645c1373b27cf26b5bb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2020-10-10T13:03:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T11:48:45.000Z", "max_issues_repo_path": "models/04/m4.3s.jl", "max_issues_repo_name": "pitmonticone/StatisticalRethinkingStan.jl", "max_issues_repo_head_hexsha": "9eee333465b3b8ec5975645c1373b27cf26b5bb0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/04/m4.3s.jl", "max_forks_repo_name": "pitmonticone/StatisticalRethinkingStan.jl", "max_forks_repo_head_hexsha": "9eee333465b3b8ec5975645c1373b27cf26b5bb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:30:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T00:10:15.000Z", "avg_line_length": 20.7142857143, "max_line_length": 70, "alphanum_fraction": 0.6, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7570632594400645}}
{"text": "# SPDX-License-Identifier: MIT\n\n\"\"\"\n    struct ProbabilitySemifield{T<:AbstractFloat} <: Semfield\n        val::T\n    end\n\nLog-semifield is defined as :\n  * ``x \\\\oplus y \\\\triangleq x + y``\n  * ``x \\\\otimes y \\\\triangleq x \\\\cdot y``\n  * ``x \\\\oslash y \\\\triangleq \\\\frac{x}{y}``\n``\\\\forall x, y \\\\in [0, 1]``.\n\"\"\"\nstruct ProbabilitySemifield{T<:AbstractFloat} <: Semifield\n    val::T\nend\n\nBase.:+(x::ProbabilitySemifield{T}, y::ProbabilitySemifield{T}) where T =\n    ProbabilitySemifield{T}(x.val + y.val)\nBase.:*(x::ProbabilitySemifield, y::ProbabilitySemifield) =\n    ProbabilitySemifield(x.val * y.val)\nBase.:/(x::ProbabilitySemifield, y::ProbabilitySemifield) =\n    ProbabilitySemifield(x.val / y.val)\nBase.zero(::Type{ProbabilitySemifield{T}}) where T =\n    ProbabilitySemifield{T}(T(0))\nBase.one(::Type{ProbabilitySemifield{T}}) where T =\n    ProbabilitySemifield{T}(T(1))\nBase.isless(x::ProbabilitySemifield, y::ProbabilitySemifield) =\n    isless(x.val, y.val)\nBase.typemin(x::Type{ProbabilitySemifield{T}}) where T = zero(T)\nBase.typemax(x::Type{ProbabilitySemifield{T}}) where T = one(T)\n", "meta": {"hexsha": "49afb89d4608edc76002ff18e30bd9c8eb29c00c", "size": 1098, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/semirings/probsemifield.jl", "max_stars_repo_name": "lucasondel/MarkovModels.jl", "max_stars_repo_head_hexsha": "3c4f8ebca382348b4f795f18a9adfa96ed6fc6dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2021-03-18T09:47:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T12:46:11.000Z", "max_issues_repo_path": "src/semirings/probsemifield.jl", "max_issues_repo_name": "lucasondel/MarkovModels.jl", "max_issues_repo_head_hexsha": "3c4f8ebca382348b4f795f18a9adfa96ed6fc6dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-07-01T11:56:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T15:05:28.000Z", "max_forks_repo_path": "src/semirings/probsemifield.jl", "max_forks_repo_name": "lucasondel/MarkovModels.jl", "max_forks_repo_head_hexsha": "3c4f8ebca382348b4f795f18a9adfa96ed6fc6dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-12-02T06:01:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T00:34:23.000Z", "avg_line_length": 34.3125, "max_line_length": 73, "alphanum_fraction": 0.6821493625, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7570632534223463}}
{"text": "#\n# create Lienar FEM Hat functions with ReLU\n#\n# centred at x=0, width = 1.0 => spacing = 0.5\n#\nusing Flux, NNlib, DiffEqFlux\nusing Plots\nimport SEM\n#--------------------------------------#\nx = SEM.linspace(-2,2,1000)\n\n\nfm1 = @. 2.0relu(x+0.5)\nfm0 = @. 4.0relu(x-0.0)\nfp1 = @. 2.0relu(x-0.5)\n\nhat = fm1 - fm0 + fp1\n\np = plot()\np = plot!(title=\"FEM Hat Function\",xlims=[-1,1],ylims=[0,1.5])\np = plot!(x,hat,width=4,color=:black,style=:solid,legend=false)\nsavefig(p,\"reluHat.png\")\n\n# ReLU\np=plot(title=\"ReLU\"); p=plot!(x,relu.(x),width=4,color=\"black\",legend=false,style=:solid); savefig(p,\"relu.png\")\n", "meta": {"hexsha": "dfbeccf1b07db4c22b00bef74395ab77bbfb21fb", "size": 601, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/presentation/hatFunc.jl", "max_stars_repo_name": "vpuri3/reluFEM", "max_stars_repo_head_hexsha": "c488332f106d358a5bfefd4b3ea5fc3666aa8b12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-24T22:25:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T22:25:26.000Z", "max_issues_repo_path": "examples/presentation/hatFunc.jl", "max_issues_repo_name": "vpuri3/reluFEM", "max_issues_repo_head_hexsha": "c488332f106d358a5bfefd4b3ea5fc3666aa8b12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-08-17T20:35:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-17T20:59:13.000Z", "max_forks_repo_path": "examples/presentation/hatFunc.jl", "max_forks_repo_name": "vpuri3/reluFEM", "max_forks_repo_head_hexsha": "c488332f106d358a5bfefd4b3ea5fc3666aa8b12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1153846154, "max_line_length": 112, "alphanum_fraction": 0.5990016639, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697694, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7569966987636632}}
{"text": "#=\n\n    deterministic.jl\n\n    Contains code to solve the deterministic ODE model\n\n           β     λ    pβ\n        T --→ S --→ E --→ S + F\n\n    Author:     Alexander P. Browning\n                ======================\n                School of Mathematical Sciences\n                Queensland University of Technology\n                ======================\n                ap.browning@icloud.com\n                alexbrowning.me\n\n=# \n\n\"\"\"\n    solve_ode_model(t,[λ,β,p])\n\nSolve the ODE model using an analytical solution obtained in Mathematica.\nReturns [A(t),I(t)].\n\n\"\"\"\nfunction solve_ode_model(t,θ::Vector)\n    λ,β,p = θ\n    A = (exp(-t*β)*(exp(-t*((-1+p)*β+λ))*(-1+p)*p*β^3*λ-(-1+p)*(β-λ)*λ*(p*β+λ)^2+exp(t*β)*((-1+p)*β+λ)*(λ^2*(β+λ)+p^2*β*(-λ^2+β^2*(1+t*λ)+β*λ*(1+t*λ))+p*λ*(-λ^2+β^2*(1+t*λ)+β*λ*(1+t*λ)))))/((β+λ)*((-1+p)*β+λ)*(p*β+λ)^2)\n    S = (exp(-t*(p*β+λ))*β*((-1+p)*β*λ+exp(t*(p*β+λ))*p*(β+λ)*((-1+p)*β+λ)-exp(t*((-1+p)*β+λ))*(-1+p)*λ*(p*β+λ)))/((β+λ)*((-1+p)*β+λ)*(p*β+λ))\n    I = A - S\n    return [A,I]\nend\nsolve_ode_model(t,λ,β,p) = solve_ode_model(t,[λ,β,p])\n\n\n\"\"\"\n    solve_ode_model_all_vars(t,[λ,β,p])\n\nSolve the ODE model using matrix exponentiation and return all variables.\nReturns [T(t),S(t),E(t),F(t)].\n\n\"\"\"\nfunction solve_ode_model_all_vars(t,θ::Vector)\n    λ,β,p = θ\n    M = [-β 0 0 0; β -λ p*β 0; 0 λ -p*β 0; 0 0 p*β 0]\n    x₀ = [λ/(λ+β),β/(λ+β),0,0]\n    return exp(M*t) * x₀\nend\nsolve_ode_model_all_vars(t,λ,β,p) = solve_ode_model_all_vars(t,[λ,β,p])\n\n\n\"\"\"\n    solve_alt_ode_model(t,[γ,λ,β,p])\n\nSolve the alternate ODE model where antibody binds to receptors at constant rate γ.\n\"\"\"\nfunction solve_alt_ode_model(t,θ::Vector)\n    γ,λ,β,p = θ\n    M = [-β 0 0 0 0; β -γ 0 p*β 0; 0 γ -λ 0 0; 0 0 λ -p*β 0; 0 0 0 p*β 0]\n    x₀ = [λ/(λ+β),β/(λ+β),0,0,0]\n    x = exp(M*t) * x₀\n    A = sum(x[3:5])\n    I = sum(x[4:5])\n    return [A,I]\nend\nsolve_alt_ode_model(t,γ,λ,β,p) = solve_alt_ode_model(t,[γ,λ,β,p])\n", "meta": {"hexsha": "6b243b952eb825f4129bf287acd1773aca04d8a8", "size": 1923, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Module/Model/deterministic.jl", "max_stars_repo_name": "ap-browning/internalisation", "max_stars_repo_head_hexsha": "caefb4066d9065eb3abc4c4378883a5e64cc9ee4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Module/Model/deterministic.jl", "max_issues_repo_name": "ap-browning/internalisation", "max_issues_repo_head_hexsha": "caefb4066d9065eb3abc4c4378883a5e64cc9ee4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Module/Model/deterministic.jl", "max_forks_repo_name": "ap-browning/internalisation", "max_forks_repo_head_hexsha": "caefb4066d9065eb3abc4c4378883a5e64cc9ee4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2794117647, "max_line_length": 219, "alphanum_fraction": 0.51950078, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7569966908059244}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,jl:hydrogen\n#     text_representation:\n#       extension: .jl\n#       format_name: hydrogen\n#       format_version: '1.3'\n#       jupytext_version: 1.11.2\n#   kernelspec:\n#     display_name: Julia 1.8.0-DEV\n#     language: julia\n#     name: julia-1.8\n# ---\n\n# %%\nstruct F{p, T<:Integer} <: Integer\n    a::T\n    F{p, T}(a::Integer) where {p, T<:Integer} = new{p, T}(mod(T(a), p))\nend\nF{p}(a::Integer) where p = F{p, typeof(a)}(mod(a, p))\nF{p, S}(x::F{p, T}) where {S<:Integer, p, T<:Integer} = F{p, S}(x.a)\n\nBase.promote_rule(::Type{F{p, T}}, ::Type{S}) where {p, T<:Integer, S<:Integer} =\n    F{p, promote_type(T, S)}\n\nBase.zero(::Type{F{p, T}}) where {p, T<:Integer} = F{p}(mod(zero(T), p))\nBase.one(::Type{F{p, T}}) where {p, T<:Integer} = F{p}(mod(one(T), p))\nfor op in (:-, :+)\n    @eval Base.$op(x::F{p}) where p = F{p}(mod($op(x.a), p))\nend\nfor op in (:-, :+, :*)\n    @eval Base.$op(x::F{p}, y::F{p}) where p = F{p}(mod($op(x.a, y.a), p))\nend\nBase.inv(x::F{p}) where p = F{p}(invmod(x.a, p))\nBase.:/(x::F{p}, y::F{p}) where p = x * inv(y)\nBase.:\\(x::F{p}, y::F{p}) where p = inv(x) * y\nBase.:(==)(x::F{p}, y::F{p}) where p = x.a == y.a\nBase.:<(x::F{p}, y::F{p}) where p = x.a < y.a\n\nBase.show(io::IO, x::F{p}) where p = print(io, \"F\", p, '(', x.a, ')')\n\nF7 = F{7, BigInt}\nx, y = F7(10), F7(-2)\n@show(x, y, zero(x), one(x), +x, -x, x + y, x - y, x * y, x / y, x \\ y, x^3, x^-5, x == F7(3), x == 3)\nprintln()\nA = F7[1 2; 3 4]\n@show(A, 4A, A/4)\nprintln()\nusing LinearAlgebra\nL, U = lu(A, NoPivot())\n@show(L, U, L * U, det(A), inv(A), inv(A) * A, A * inv(A));\n\n# %%\n\"\"\"See https://docs.julialang.org/en/v1/manual/interfaces/\"\"\"\nBase.iterate(Fp::Type{F{p, T}}) where {p, T<:Integer} = (zero(Fp), zero(T))\nfunction Base.iterate(Fp::Type{F{p, T}}, state) where {p, T<:Integer}\n    nextstate = state + 1\n    nextstate < p ? (Fp(nextstate), nextstate) : nothing\nend\nBase.IteratorSize(Fp::Type{F{p, T}}) where {p, T<:Integer} = Base.HasLength()\nBase.length(Fp::Type{F{p, T}}) where {p, T<:Integer} = p\nBase.eltype(Fp::Type{F{p, T}}) where {p, T<:Integer} = Fp\n\nsquares(Fp) = Fp[x^2 for x in Fp]\nsquareroots(k, Fp) = Fp[x for x in Fp if x^2 == k]\n@show(collect(F7), squares(F7), squareroots.(0:6, Ref(F7)));\n\n# %%\nusing GaloisFields, LinearAlgebra\nGF7 = @GaloisField 7\nB = GF7[1 2; 3 4]\ndet(B)\n\n# %%\ninv(B)\n\n# %%\nlu(B)\n\n# %%\nusing AbstractAlgebra\n\n@show GF7 = GF(7)\nx, y = GF7(10), GF7(-2)\n@show(x, y, zero(x), one(x), -x, x + y, x - y, x * y, x^3, x^-5, x == GF7(3), x == 3)\nprintln()\n\n@show C = GF7[1 2; 3 4]\n@show P, x = PolynomialRing(GF7, \"x\")\n@show(det(C), inv(C), lu(C), charpoly(P, C))\nprintln()\n\nsquares(Fp) = [x^2 for x in Fp]\nsquareroots(k, Fp) = [x for x in Fp if x^2 == k]\n@show(collect(GF7), squares(GF7), squareroots.(0:6, Ref(GF7)));\n\n# %%\n", "meta": {"hexsha": "e84df0c2f0fab561bdb6b225c78257b0d6e98d72", "size": 2803, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0010/minimal def of a prime field.jl", "max_stars_repo_name": "genkuroki/public", "max_stars_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-06-06T00:33:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T06:56:08.000Z", "max_issues_repo_path": "0010/minimal def of a prime field.jl", "max_issues_repo_name": "genkuroki/public", "max_issues_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0010/minimal def of a prime field.jl", "max_forks_repo_name": "genkuroki/public", "max_forks_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-02T11:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T11:46:05.000Z", "avg_line_length": 28.3131313131, "max_line_length": 102, "alphanum_fraction": 0.5433464146, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7569403807308495}}
{"text": "# # Classification of penguin species\n#\n# ## Packages\n\nusing CairoMakie\nusing CalibrationErrors\nusing DataFrames\nusing Distances\nusing Distributions\nusing PalmerPenguins\nusing Query\n\nusing Random\n\nusing CairoMakie.AbstractPlotting.ColorSchemes: Dark2_8\n\n# ## Data\n#\n# In this example we study the calibration of different models that classify three penguin\n# species based on measurements of their bill and flipper lengths.\n#\n# We use the [Palmer penguins dataset](https://allisonhorst.github.io/palmerpenguins/) to\n# to train and validate the models.\n\npenguins = dropmissing(DataFrame(PalmerPenguins.load()))\n\nf = Figure()\nax = Axis(f[1, 1]; xlabel=\"bill length [mm]\", ylabel=\"flipper length [mm]\")\nfor (i, (key, df)) in enumerate(pairs(groupby(penguins, :species)))\n    scatter!(\n        df.bill_length_mm, df.flipper_length_mm; color=(Dark2_8[i], 0.8), label=key.species\n    )\nend\nLegend(f[1, 2], ax, \"species\")\n#!jl save(\"./figures/penguins.svg\", f);\n\n#!jl # ![](./figures/penguins.svg)\n\n# We split the data randomly into a training and validation dataset. The training dataset\n# contains around 60% of the samples.\n\nRandom.seed!(1234)\nidxs = shuffle(axes(penguins, 1))\nk = floor(Int, 0.6 * length(idxs))\ntrain_idxs = @view idxs[1:k]\nval_idxs = @view idxs[(k + 1):end]\n\ntrain_penguins = penguins[train_idxs, :]\nval_penguins = penguins[val_idxs, :];\n\n#-\n\nf = Figure()\nax = Axis(f[1, 1]; xlabel=\"bill length [mm]\", ylabel=\"flipper length [mm]\")\nfor (i, df) in enumerate((train_penguins, val_penguins))\n    for (j, (key, subdf)) in enumerate(pairs(groupby(df, :species)))\n        scatter!(\n            subdf.bill_length_mm,\n            subdf.flipper_length_mm;\n            color=(Dark2_8[j], 0.8),\n            marker=i == 1 ? :circle : :diamond,\n        )\n    end\nend\ngroup_marker = [\n    MarkerElement(; marker=m, color=:black, strokecolor=:transparent, markersize=20) for\n    m in (:circle, :diamond)\n]\ngroup_color = [PolyElement(; color=Dark2_8[i], strokecolor=:transparent) for i in 1:3]\nLegend(\n    f[1, 2],\n    [group_marker, group_color],\n    [[\"training\", \"validation\"], string.(levels(penguins.species))],\n    [\"dataset\", \"species\"],\n)\n#!jl save(\"./figures/penguins_datasets.svg\", f);\n\n#!jl # ![](./figures/penguins_datasets.svg)\n\n# ## Fitting normal distributions\n#\n# For each species, we fit independent normal distributions to the observations of the bill\n# and flipper length in the training data, using maximum likelihood estimation.\n\npenguins_fit = @from i in train_penguins begin\n    @group i by i.species into g\n    @select {\n        species = key(g),\n        proportion = length(g) / nrow(train_penguins),\n        bill = fit(Normal, g.bill_length_mm),\n        flipper = fit(Normal, g.flipper_length_mm),\n    }\n    @collect DataFrame\nend\n\n# We plot the estimated normal distributions.\n\nfunction xrange(dists, alpha=0.0001)\n    xmin = minimum(Base.Fix2(quantile, alpha), dists)\n    xmax = maximum(Base.Fix2(quantile, 1 - alpha), dists)\n    return range(xmin, xmax; length=1_000)\nend\n\nfunction plot_normal_fit(dists, species, xlabel)\n    f = Figure()\n    Axis(f[1, 1]; xlabel=xlabel, ylabel=\"density\")\n    xs = xrange(dists)\n    plots = map(enumerate(dists)) do (i, dist)\n        ys = pdf.(dist, xs)\n        l = lines!(xs, ys; color=Dark2_8[i])\n        b = band!(xs, 0, ys; color=(Dark2_8[i], 0.2))\n        return [l, b]\n    end\n    Legend(f[1, 2], plots, species, \"species\")\n    return f\nend\n\nplot_normal_fit(penguins_fit.bill, penguins_fit.species, \"bill length [mm]\")\n#!jl save(\"./figures/normal_fit_bill.svg\", current_figure());\n\n#!jl # ![](./figures/normal_fit_bill.svg)\n\nplot_normal_fit(penguins_fit.flipper, penguins_fit.species, \"flipper length [mm]\")\n#!jl save(\"./figures/normal_fit_flipper.svg\", current_figure());\n\n#!jl # ![](./figures/normal_fit_flipper.svg)\n\n# ## Naive Bayes classifier\n#\n# Let us assume that the bill and flipper length are conditionally independent given the\n# penguin species. Then Bayes' theorem implies that\n# ```math\n# \\begin{aligned}\n# \\mathbb{P}(\\mathrm{species} \\,|\\, \\mathrm{bill}, \\mathrm{flipper})\n# &= \\frac{\\mathbb{P}(\\mathrm{species}) \\mathbb{P}(\\mathrm{bill}, \\mathrm{flipper} \\,|\\, \\mathrm{species})}{\\mathbb{P}(\\mathrm{bill}, \\mathrm{flipper})} \\\\\n# &= \\frac{\\mathbb{P}(\\mathrm{species}) \\mathbb{P}(\\mathrm{bill} \\,|\\, \\mathrm{species}) \\mathbb{P}(\\mathrm{flipper} \\,|\\, \\mathrm{species})}{\\mathbb{P}(\\mathrm{bill}, \\mathrm{flipper})}.\n# \\end{aligned}\n# ```\n# This predictive model is known as\n# [naive Bayes classifier](https://en.wikipedia.org/wiki/Naive_Bayes_classifier).\n#\n# In the section above, we estimated $\\mathbb{P}(\\mathrm{species})$,\n# $\\mathbb{P}(\\mathrm{bill} \\,|\\, \\mathrm{species})$, and\n# $\\mathbb{P}(\\mathrm{flipper} \\,|\\, \\mathrm{species})$ for each penguin species from\n# the training data. For the conditional distributions we used a Gaussian approximation.\n\nfunction predict_naive_bayes_classifier(fit, data)\n    ## Compute unnormalized probabilities\n    z =\n        log.(permutedims(fit.proportion)) .+\n        logpdf.(permutedims(fit.bill), data.bill_length_mm) .+\n        logpdf.(permutedims(fit.flipper), data.flipper_length_mm)\n\n    ## Normalize probabilities\n    u = maximum(z; dims=2)\n    z .= exp.(z .- u)\n    sum!(u, z)\n    z ./= u\n\n    return DataFrame(z, fit.species)\nend\n\ntrain_predict = predict_naive_bayes_classifier(penguins_fit, train_penguins)\nval_predict = predict_naive_bayes_classifier(penguins_fit, val_penguins);\n\n# ## Evaluation\n#\n# We evaluate the probabilistic predictions of the naive Bayes classifier that we just\n# trained. It is easier to work with a numerical encoding of the true penguin species and a\n# corresponding vector of predictions.\n\ntrain_species = convert(Vector{Int}, indexin(train_penguins.species, names(train_predict)))\ntrain_probs = collect(Vector{Float64}, eachrow(train_predict))\n\nval_species = convert(Vector{Int}, indexin(val_penguins.species, names(val_predict)))\nval_probs = collect(Vector{Float64}, eachrow(val_predict));\n\n# ### Log-likelihood\n#\n# We compute the average log-likelihood of the training and validation data. It is\n# equivalent to the negative cross-entropy.\n\nfunction mean_loglikelihood(species, probs)\n    return mean(log(p[s]) for (s, p) in zip(species, probs))\nend\n\nmean_loglikelihood(train_species, train_probs)\n\n#-\n\nmean_loglikelihood(val_species, val_probs)\n\n# ### Brier score\n#\n# The average log-likelihood is also equivalent to the\n# [logarithmic score](https://sites.stat.washington.edu/raftery/Research/PDF/Gneiting2007jasa.pdf).\n# The Brier score is another strictly proper scoring rule that can be used for evaluating\n# probabilistic predictions.\n\nfunction brier_score(species, probs)\n    return mean(\n        sum(abs2(pi - (i == s)) for (i, pi) in enumerate(p)) for\n        (s, p) in zip(species, probs)\n    )\nend\n\nbrier_score(train_species, train_probs)\n\n#-\n\nbrier_score(val_species, val_probs)\n\n# ### Expected calibration error\n#\n# As all proper scoring rules, the logarithmic and the Brier score can be [decomposed in\n# three terms that quantify the sharpness and calibration of the predictive model and the\n# irreducible uncertainty of the targets that is inherent to the prediction\n# problem](https://doi.org/10.1002/qj.456). The calibration term in this decomposition is\n# the expected calibration error (ECE)\n# ```math\n# \\mathbb{E} d\\big(P_X, \\mathrm{law}(Y \\,|\\, P_X)\\big)\n# ```\n# with respect to the score divergence $d$.\n#\n# Scoring rules, however, include also the sharpness and the uncertainty term. Thus models\n# can trade off calibration for sharpness and therefore scoring rules are not suitable for\n# specifically evaluating calibration of predictive models.\n#\n# The score divergence to the logarithmic and the Brier score are the Kullback-Leibler (KL)\n# divergence\n# ```math\n# d\\big(P_X, \\mathrm{law}(Y \\,|\\, P_X)\\big) = \\sum_{y} \\mathbb{P}(Y = y \\,|\\, P_X)\n# \\log\\big(\\mathbb{P}(Y = y \\,|\\, P_X) / P_X(\\{y\\})\\big)\n# ```\n# and the squared Euclidean distance\n# ```math\n# d\\big(P_X, \\mathrm{law}(Y \\,|\\, P_X)\\big) = \\sum_{y} \\big(P_X - \\mathrm{law}(Y \\,|\\, P_X)\\big)^2(\\{y\\}),\n# ```\n# respectively. The KL divergence is defined only if $\\mathrm{law}(Y \\,|\\, P_X)$ is\n# absolutely continuous with respect to $P_X$, i.e., if $P_X(\\{y\\}) = 0$ implies\n# $\\mathbb{P}(Y = y \\,|\\, P_X) = 0$.\n\n# We estimate the ECE by binning the probability simplex of predictions $P_X$ and computing\n# the weighted average of the distances between the mean prediction and the distribution of\n# targets in each bin.\n#\n# One approach is to use bins of uniform size.\n\nece = ECE(UniformBinning(10), (μ, y) -> kl_divergence(y, μ))\nece(train_probs, train_species)\n\n#-\n\nece(val_probs, val_species)\n\n# For the squared Euclidean distance we obtain:\n\nece = ECE(UniformBinning(10), SqEuclidean())\nece(train_probs, train_species)\n\n#-\n\nece(val_probs, val_species)\n\n# Alternatively, one can use a data-dependent binning scheme that tries to split the\n# predictions in a way that minimizes the variance in each bin.\n#\n# With the KL divergence we get:\n\nece = ECE(MedianVarianceBinning(5), (μ, y) -> kl_divergence(y, μ))\nece(train_probs, train_species)\n\n#-\n\nece(val_probs, val_species)\n\n# For the squared Euclidean distance we obtain:\n\nece = ECE(MedianVarianceBinning(5), SqEuclidean())\nece(train_probs, train_species)\n\n#-\n\nece(val_probs, val_species)\n\n# We see that the estimates (of the same theoretical quantity!) are highly dependent on the\n# chosen binning scheme.\n\n# ### Kernel calibration error\n#\n# As an alternative to the ECE, we estimate the kernel calibration error (KCE). We keep it\n# simple here, and use the tensor product kernel\n# ```math\n# k\\big((\\mu, y), (\\mu', y')\\big) = \\delta_{y,y'} \\exp{\\bigg(-\\frac{{\\|\\mu - \\mu'\\|}_2^2}{2\\nu^2} \\bigg)}\n# ```\n# with length scale $\\nu > 0$ for predictions $\\mu,\\mu'$ and corresponding targets $y, y'$.\n# For simplicity, we estimate length scale $\\nu$ with the median heuristic.\n\ndistances = pairwise(SqEuclidean(), train_probs)\nλ = sqrt(median(distances[i] for i in CartesianIndices(distances) if i[1] < i[2]))\nkernel = (GaussianKernel() ∘ ScaleTransform(inv(λ))) ⊗ WhiteKernel();\n\n# We obtain the following biased estimates of the squared KCE (SKCE):\n\nskce = BiasedSKCE(kernel)\nskce(train_probs, train_species)\n\n#-\n\nskce(val_probs, val_species)\n\n# Similar to the biased estimates of the ECE, the biased estimates of the SKCE are always\n# non-negative. The unbiased estimates can be negative as well, in particular if the model\n# is (close to being) calibrated:\n\nskce = UnbiasedSKCE(kernel)\nskce(train_probs, train_species)\n\n#-\n\nskce(val_probs, val_species)\n\n# When the datasets are large, the quadratic sample complexity of the standard biased and\n# unbiased estimators of the SKCE can become prohibitive. In these cases, one can resort to\n# an estimator that averages estimates of non-overlapping blocks of samples. This estimator\n# allows to trade off computational cost for increased variance.\n#\n# Here we consider the extreme case of blocks with two samples, which yields an estimator\n# with linear sample complexity:\n\nskce = BlockUnbiasedSKCE(kernel, 2)\nskce(train_probs, train_species)\n\n#-\n\nskce(val_probs, val_species)\n", "meta": {"hexsha": "9e704af83377314bcf439b598216b83fe31220ed", "size": 11127, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/classification/script.jl", "max_stars_repo_name": "pitmonticone/CalibrationErrors.jl", "max_stars_repo_head_hexsha": "dfc75da78788ff86d49c025740626623039af776", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/classification/script.jl", "max_issues_repo_name": "pitmonticone/CalibrationErrors.jl", "max_issues_repo_head_hexsha": "dfc75da78788ff86d49c025740626623039af776", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/classification/script.jl", "max_forks_repo_name": "pitmonticone/CalibrationErrors.jl", "max_forks_repo_head_hexsha": "dfc75da78788ff86d49c025740626623039af776", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0178041543, "max_line_length": 187, "alphanum_fraction": 0.7084569066, "num_tokens": 3073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8459424295406087, "lm_q1q2_score": 0.7569403725087285}}
{"text": "include(\"Lanczos_Ritz_Utilities.jl\")\ninclude(\"../../src/iterative_lanczos.jl\")\n\n### ============================================================================\n### Lanczos vector project onto the extreme ritz value's eigenvalues\n### \n\nfunction PerformAndProject(n=64; offset=20, exact=false)\n    A = Diagonal(LinRange(-1, 1, n).^3)\n    il = IterativeLanczos(A, ones(n))\n    il.reorthogonalize = exact\n    for _ in 1: offset - 1\n        il()\n    end\n    ProjOnRitz = Vector()\n    for II in offset:n - 1\n        q = il()\n        T = il|>GetTMatrix\n        Q = il|>GetQMatrix\n        \n        s = eigvecs(T)[:, end:-1: (end - 2)]\n        push!(ProjOnRitz, q'*Q*s)\n    end\n\nreturn vcat(ProjOnRitz...) end\n\n# ----- Floats --------\nProjOnRitz = PerformAndProject()\nProjOnRitz = ProjOnRitz .|> abs\nIters = 20:63\nfig1 = plot(\n    Iters, \n    ProjOnRitz[:, 1], \n    yaxis=:log, \n    legend=:bottomleft, size=(750, 500), \n    label=\"\\$q^T_kQ_ks_1\\$\", \n    dpi=300, leftmargin=5*Plots.mm\n)\nplot!(fig1, Iters, ProjOnRitz[:, 2], linestyle=:dashdot, label=\"\\$q^T_kQ_ks_2\\$\")\nplot!(fig1, Iters, ProjOnRitz[:, 3], linestyle=:dash, label=\"\\$q^T_kQ_ks_3\\$\")\ntitle!(\"Lanczos vec proj onto Ritz Vectors (Floats)\")\nyaxis!(\"\\$|q^T_kQS|\\$\")\nxaxis!(\"iterations\") \nfig1|>display\nsavefig(fig1, \"$(@__DIR__)/plots/lanczos_proj_on_ritz_float.png\")\n\n# ------ Exact --------\nProjOnRitz = PerformAndProject(exact=true)\nProjOnRitz = ProjOnRitz .|> abs\nIters = 20:63\nfig1 = plot(\n    Iters, \n    ProjOnRitz[:, 1], \n    yaxis=:log, \n    legend=:bottomleft, size=(750, 500), \n    label=\"\\$q^T_kQ_ks_1\\$\", \n    dpi=300, leftmargin=5*Plots.mm\n)\n\nplot!(fig1, Iters, ProjOnRitz[:, 2], linestyle=:dashdot, label=\"\\$q^T_kQ_ks_2\\$\")\nplot!(fig1, Iters, ProjOnRitz[:, 3], linestyle=:dash, label=\"\\$q^T_kQ_ks_3\\$\")\ntitle!(\"Lanczos vec proj on ritz vectors (largest 3) (Exact)\")\nyaxis!(\"\\$|q^T_kQS|\\$\")\nxaxis!(\"iterations\") \nfig1|>display\nsavefig(fig1, \"$(@__DIR__)/plots/lanczos_proj_on_ritz_exact.png\")\n", "meta": {"hexsha": "19c60115ee05288c13878581229c49a0227b8be0", "size": 1960, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "numerical_experiments/Lanczos_Ritz/lanczos_ritz_projection.jl", "max_stars_repo_name": "iluvjava/Subspace_Projection_Method", "max_stars_repo_head_hexsha": "0728d708b18a2f0bca763c1061eb729eb0b79c3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numerical_experiments/Lanczos_Ritz/lanczos_ritz_projection.jl", "max_issues_repo_name": "iluvjava/Subspace_Projection_Method", "max_issues_repo_head_hexsha": "0728d708b18a2f0bca763c1061eb729eb0b79c3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical_experiments/Lanczos_Ritz/lanczos_ritz_projection.jl", "max_forks_repo_name": "iluvjava/Subspace_Projection_Method", "max_forks_repo_head_hexsha": "0728d708b18a2f0bca763c1061eb729eb0b79c3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2537313433, "max_line_length": 81, "alphanum_fraction": 0.6, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7569184894078638}}
{"text": "module TensorCore\n\nusing LinearAlgebra\n\nexport ⊙, hadamard, hadamard!\nexport ⊗, tensor, tensor!\nexport ⊡, boxdot, boxdot!\n\n\"\"\"\n    hadamard(a, b)\n    a ⊙ b\n\nFor arrays `a` and `b`, perform elementwise multiplication.\n`a` and `b` must have identical `axes`.\n\n`⊙` can be passed as an operator to higher-order functions.\n\n# Examples\n```jldoctest; setup=:(using TensorCore)\njulia> a = [2, 3]; b = [5, 7];\n\njulia> a ⊙ b\n2-element Array{$Int,1}:\n 10\n 21\n\njulia> a ⊙ [5]\nERROR: DimensionMismatch(\"Axes of `A` and `B` must match, got (Base.OneTo(2),) and (Base.OneTo(1),)\")\n[...]\n```\n\nSee also `hadamard!(y, a, b)`.\n\"\"\"\nfunction hadamard(A::AbstractArray, B::AbstractArray)\n    @noinline throw_dmm(axA, axB) = throw(DimensionMismatch(\"Axes of `A` and `B` must match, got $axA and $axB\"))\n\n    axA, axB = axes(A), axes(B)\n    axA == axB || throw_dmm(axA, axB)\n    return map(*, A, B)\nend\nconst ⊙ = hadamard\n\n\"\"\"\n    hadamard!(dest, A, B)\n\nSimilar to `hadamard(A, B)` (which can also be written `A ⊙ B`), but stores its results in\nthe pre-allocated array `dest`.\n\"\"\"\nfunction hadamard!(dest::AbstractArray, A::AbstractArray, B::AbstractArray)\n    @noinline function throw_dmm(axA, axB, axdest)\n        throw(DimensionMismatch(\"`axes(dest) = $axdest` must be equal to `axes(A) = $axA` and `axes(B) = $axB`\"))\n    end\n\n    axA, axB, axdest = axes(A), axes(B), axes(dest)\n    ((axdest == axA) & (axdest == axB)) || throw_dmm(axA, axB, axdest)\n    @simd for I in eachindex(dest, A, B)\n        @inbounds dest[I] = A[I] * B[I]\n    end\n    return dest\nend\n\n\"\"\"\n    tensor(A, B)\n    A ⊗ B\n\nCompute the tensor product of `A` and `B`.\nIf `C = A ⊗ B`, then `C[i1, ..., im, j1, ..., jn] = A[i1, ... im] * B[j1, ..., jn]`.\n\nFor vectors `v` and `w`, the Kronecker product is related to the tensor product by\n`kron(v,w) == vec(w ⊗ v)` or `w ⊗ v == reshape(kron(v,w), (length(w), length(v)))`.\n\n# Examples\n```jldoctest; setup=:(using TensorCore)\njulia> a = [2, 3]; b = [5, 7, 11];\n\njulia> a ⊗ b\n2×3 Array{$Int,2}:\n 10  14  22\n 15  21  33\n```\nSee also `tensor!(Y,A,B)`.\n\"\"\"\ntensor(A::AbstractArray, B::AbstractArray) = [a*b for a in A, b in B]\nconst ⊗ = tensor\n\nconst CovectorLike{T} = Union{Adjoint{T,<:AbstractVector},Transpose{T,<:AbstractVector}}\nfunction tensor(u::AbstractArray, v::CovectorLike)\n    # If `v` is thought of as a covector, you might want this to be two-dimensional,\n    # but thought of as a matrix it should be three-dimensional.\n    # The safest is to avoid supporting it at all. See discussion in #35150.\n    error(\"`tensor` is not defined for co-vectors, perhaps you meant `*`?\")\nend\nfunction tensor(u::CovectorLike, v::AbstractArray)\n    error(\"`tensor` is not defined for co-vectors, perhaps you meant `*`?\")\nend\nfunction tensor(u::CovectorLike, v::CovectorLike)\n    error(\"`tensor` is not defined for co-vectors, perhaps you meant `*`?\")\nend\n\n\"\"\"\n    tensor!(dest, A, B)\n\nSimilar to `tensor(A, B)` (which can also be written `A ⊗ B`), but stores its results in\nthe pre-allocated array `dest`.\n\"\"\"\nfunction tensor!(dest::AbstractArray, A::AbstractArray, B::AbstractArray)\n    @noinline function throw_dmm(axA, axB, axdest)\n        throw(DimensionMismatch(\"`axes(dest) = $axdest` must concatenate `axes(A) = $axA` and `axes(B) = $axB`\"))\n    end\n\n    axA, axB, axdest = axes(A), axes(B), axes(dest)\n    axes(dest) == (axA..., axB...) || throw_dmm(axA, axB, axdest)\n    if IndexStyle(dest) === IndexCartesian()\n        for IB in CartesianIndices(axB)\n            @inbounds b = B[IB]\n            @simd for IA in CartesianIndices(axA)\n                @inbounds dest[IA,IB] = A[IA]*b\n            end\n        end\n    else\n        i = firstindex(dest)\n        @inbounds for b in B\n            @simd for a in A\n                dest[i] = a*b\n                i += 1\n            end\n        end\n    end\n    return dest\nend\n\nexport boxdot, ⊡, boxdot!\n\n\"\"\"\n    boxdot(A,B) = A ⊡ B    # \\\\boxdot\n\nGeneralised matrix multiplication: Contracts the last dimension of `A` with\nthe first dimension of `B`, for any `ndims(A)` & `ndims(B)`.\nIf both are vectors, then it returns a scalar `== sum(A .* B)`.\n\n# Examples\n```jldoctest; setup=:(using TensorCore)\njulia> A = rand(3,4,5); B = rand(5,6,7);\n\njulia> size(A ⊡ B)\n(3, 4, 6, 7)\n\njulia> typeof(rand(5) ⊡ rand(5))\nFloat64\n\njulia> try B ⊡ A catch err println(err) end\nDimensionMismatch(\"neighbouring axes of `A` and `B` must match, got Base.OneTo(7) and Base.OneTo(3)\")\n```\nThis is the same behaviour as Mathematica's function `Dot[A, B]`.\nIt is not identicaly to Python's `numpy.dot(A, B)`, which contracts with the second-last\ndimension of `B` instead of the first, but both keep all the other dimensions.\nUnlike Julia's `LinearAlgebra.dot`, it does not conjugate `A`, so these two agree only\nfor real-valued vectors.\n\nWhen interacting with `Adjoint` vectors, this always obeys `(x ⊡ y)' == y' ⊡ x'`,\nand hence may sometimes return another `Adjoint` vector. (And similarly for `Transpose`.)\n\n```jldoctest; setup=:(using TensorCore)\njulia> M = rand(5,5); v = rand(5);\n\njulia> typeof(v ⊡ M')\nArray{Float64,1}\n\njulia> typeof(M ⊡ v')  # adjoint of the previous line\nAdjoint{Float64,Array{Float64,1}}\n\njulia> typeof(v' ⊡ M')  # same as *, and equal to adjoint(M ⊡ v)\nAdjoint{Float64,Array{Float64,1}}\n\njulia> typeof(v' ⊡ v)\nFloat64\n```\nSee also `boxdot!(Y,A,B)`, which is to `⊡` as `mul!` is to `*`.\n\"\"\"\nfunction boxdot(A::AbstractArray, B::AbstractArray)\n    Amat = _squash_left(A)\n    Bmat = _squash_right(B)\n\n    axA, axB = axes(Amat,2), axes(Bmat,1)\n    axA == axB || _throw_dmm(axA, axB)\n\n    return _boxdot_reshape(Amat * Bmat, A, B)\nend\n\nconst ⊡ = boxdot\n\n@noinline _throw_dmm(axA, axB) = throw(DimensionMismatch(\"neighbouring axes of `A` and `B` must match, got $axA and $axB\"))\n\n_squash_left(A::AbstractArray) = reshape(A, :,size(A,ndims(A)))\n_squash_left(A::AbstractMatrix) = A\n\n_squash_right(B::AbstractArray) = reshape(B, size(B,1),:)\n_squash_right(B::AbstractVecOrMat) = B\n\nfunction _boxdot_reshape(AB::AbstractArray, A::AbstractArray{T,N}, B::AbstractArray{S,M}) where {T,N,S,M}\n    ax = ntuple(i -> i<N ? axes(A, i) : axes(B, i-N+2), Val(N+M-2))\n    reshape(AB, ax) # some cases don't come here, so this doesn't really support OffsetArrays\nend\n\n# These can skip final reshape:\n_boxdot_reshape(AB::AbstractVecOrMat, A::AbstractMatrix, B::AbstractVecOrMat) = AB\n\n# These produce scalar output:\nfunction boxdot(A::AbstractVector, B::AbstractVector)\n    axA, axB = axes(A,1), axes(B,1)\n    axA == axB || _throw_dmm(axA, axB)\n    if eltype(A) <: Number\n        return transpose(A)*B\n    else\n        return sum(a*b for (a,b) in zip(A,B))\n    end\nend\n\n# Multiplication by a scalar:\nboxdot(A::AbstractArray, b::Number) = A*b\nboxdot(a::Number, B::AbstractArray) = a*B\nboxdot(a::Number, b::Number) = a*b\n\nusing LinearAlgebra: AdjointAbsVec, TransposeAbsVec, AdjOrTransAbsVec\n\n# Adjont and Transpose, vectors or almost (returning a scalar)\nboxdot(A::AdjointAbsVec, B::AbstractVector) = A * B\nboxdot(A::TransposeAbsVec, B::AbstractVector) = A * B\n\nboxdot(A::AbstractVector, B::AdjointAbsVec) = A ⊡ vec(B)\nboxdot(A::AbstractVector, B::TransposeAbsVec) = A ⊡ vec(B)\n\nboxdot(A::AdjointAbsVec, B::AdjointAbsVec) = adjoint(adjoint(B) ⊡ adjoint(A))\nboxdot(A::AdjointAbsVec, B::TransposeAbsVec) = vec(A) ⊡ vec(B)\nboxdot(A::TransposeAbsVec, B::AdjointAbsVec) = vec(A) ⊡ vec(B)\nboxdot(A::TransposeAbsVec, B::TransposeAbsVec) = transpose(transpose(B) ⊡ transpose(A))\n\n# ... with a matrix (returning another such)\nboxdot(A::AdjointAbsVec, B::AbstractMatrix) = A * B\nboxdot(A::TransposeAbsVec, B::AbstractMatrix) = A * B\n\nboxdot(A::AbstractMatrix, B::AdjointAbsVec) = (B' ⊡ A')'\nboxdot(A::AbstractMatrix, B::TransposeAbsVec) = transpose(transpose(B) ⊡ transpose(A))\n\n# ... and with higher-dim (returning a plain array)\nboxdot(A::AdjointAbsVec, B::AbstractArray) = vec(A) ⊡ B\nboxdot(A::TransposeAbsVec, B::AbstractArray) = vec(A) ⊡ B\n\nboxdot(A::AbstractArray, B::AdjointAbsVec) = A ⊡ vec(B)\nboxdot(A::AbstractArray, B::TransposeAbsVec) = A ⊡ vec(B)\n\n\n\"\"\"\n    boxdot!(Y, A, B, α=1, β=0)\n\nIn-place version of `boxdot`, i.e. `Y .= (A ⊡ B) .* β .+ Y .* α`.\nLike 5-argument `mul!`, the use of `α, β` here requires Julia 1.3 or later.\n\"\"\"\nfunction boxdot! end\n\nif VERSION < v\"1.3\" # Then 5-arg mul! isn't defined\n\n    function boxdot!(Y::AbstractArray, A::AbstractArray, B::AbstractArray)\n        szY = prod(size(A)[1:end-1]), prod(size(B)[2:end])\n        mul!(reshape(Y, szY), _squash_left(A), _squash_right(B))\n        Y\n    end\n\n    boxdot!(Y::AbstractArray, A::AbstractArray, B::AdjOrTransAbsVec) = boxdot!(Y, A, vec(B))\n\nelse\n\n    function boxdot!(Y::AbstractArray, A::AbstractArray, B::AbstractArray, α::Number=true, β::Number=false)\n        szY = prod(size(A)[1:end-1]), prod(size(B)[2:end])\n        mul!(reshape(Y, szY), _squash_left(A), _squash_right(B), α, β)\n        Y\n    end\n\n    # For boxdot!, only where mul! behaves differently:\n    boxdot!(Y::AbstractArray, A::AbstractArray, B::AdjOrTransAbsVec,\n        α::Number=true, β::Number=false) = boxdot!(Y, A, vec(B))\n\nend\n\n\"\"\"\n    TensorCore._adjoint(A)\n\nThis extends `adjoint` to understand higher-dimensional arrays, always reversing the\norder of dimensions. On Julia 1.5 and later, the symbol `'` can be overloaded locally\nas `var\"'\"`, as shown below.\n\nThen `(x ⊡ y)' == y' ⊡ x'` holds for `x` and `y` arrays of any dimension.\n\n# Examples\n```jldoctest; setup=:(using TensorCore)\njulia> T3 = rand(3,4,5); v = rand(5);\n\njulia> size(T3 ⊡ v')\n(3, 4)\n\njulia> let var\"'\" = TensorCore._adjoint\n         v ⊡ T3' ≈ (T3 ⊡ v')'\n       end\ntrue\n```\n\"\"\"\n_adjoint(x) = adjoint(x)\n_adjoint(x::AbstractVecOrMat) = adjoint(x)\n_adjoint(x::AbstractArray{T,N}) where {T<:Number,N} = conj(PermutedDimsArray(x, ntuple(i -> N-i+1, N)))\n_adjoint(x::AbstractArray{T,N}) where {T,N} = adjoint.(PermutedDimsArray(x, ntuple(i -> N-i+1, N)))\n\n_transpose(x) = transpose(x)\n_transpose(x::AbstractVecOrMat) = transpose(x)\n_transpose(x::AbstractArray{T,N}) where {T<:Number,N} = PermutedDimsArray(x, ntuple(i -> N-i+1, N))\n_transpose(x::AbstractArray{T,N}) where {T,N} = transpose.(PermutedDimsArray(x, ntuple(i -> N-i+1, N)))\n\nend\n", "meta": {"hexsha": "e5ac15688ed55627588498ad4a15b5b1f786179b", "size": 10075, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TensorCore.jl", "max_stars_repo_name": "JuliaMath/TensorCore.jl", "max_stars_repo_head_hexsha": "7e9ad327756cfe3ded97a1c21c5e52c93a1d4db5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2020-05-05T11:15:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T14:16:08.000Z", "max_issues_repo_path": "src/TensorCore.jl", "max_issues_repo_name": "JuliaMath/TensorCore.jl", "max_issues_repo_head_hexsha": "7e9ad327756cfe3ded97a1c21c5e52c93a1d4db5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-05-06T17:18:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-26T14:23:52.000Z", "max_forks_repo_path": "src/TensorCore.jl", "max_forks_repo_name": "JuliaMath/TensorCore.jl", "max_forks_repo_head_hexsha": "7e9ad327756cfe3ded97a1c21c5e52c93a1d4db5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-05-06T16:29:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T19:26:57.000Z", "avg_line_length": 31.6823899371, "max_line_length": 123, "alphanum_fraction": 0.6496277916, "num_tokens": 3346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88242786954645, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7569184766386273}}
{"text": "using SymPy: @vars, Sym, solve\nusing SymPy: simplify\nusing Zygote\n\ndot(x,y) = sum(x .* y)\n\nfunction generate_vector(v::String, n::Int; start::Int = 1, kwargs::String = \"\")\n    data::Vector{Sym} = []\n    for i ∈ start:n\n        seqdigit = [c for c in string(i)]\n        v_s = \"$v\" * join(seqdigit)\n        eval(Meta.parse(\"@vars $v_s $kwargs\"))\n        push!(data, eval(Meta.parse(\"$(v_s)\")))\n    end\n    return data\nend\n\nD = 2 # Dimension of data\nN = 3 # Num of data\n\n\nfunction generate_matrix(\n    v::String,\n    row::Int,\n    col::Int;\n    rstart::Int = 1,\n    cstart::Int = 1,\n    kwargs::String = \"\",\n)::Matrix{Sym}\n    X_ = Vector{Sym}[]\n    for n = rstart:row\n        xn = \"$v$n\"\n        eval(Meta.parse(\"xn=generate_vector(\\\"x$n\\\", $col, start = $cstart, kwargs=\\\"$kwargs\\\")\"))\n        push!(X_, eval(Meta.parse(\"xn\")))\n    end\n    Xᵀ = Matrix{Sym}(hcat(X_...))\n    X = transpose(Xᵀ)\n    X\nend\n\nX = generate_matrix(\"x\", N, D, cstart = 0, kwargs = \"real=true\")\ny = generate_vector(\"y\", N, kwargs = \"real=true\")\nw = generate_vector(\"w\", D, start = 0, kwargs = \"real=true\")\n\n# Numerical\n# X = rand(N, D + 1)\n# y = rand(N)\n\nX[:, 1] .= 1.0 # set xn0 = 1 for n in 1:N\n\nŷ(X) = X * w\nE(X) = 1 / 2 * (dot(y, y) - 2 * dot(y, ŷ(X)) + dot(ŷ(X), ŷ(X)))\n\n@info \"calc-gradient\"\n\n∇E = gradient(Params([w])) do\n    E(X)\nend\n\n@info \"solve\"\nsolution = solve(∇E[w], w)\nsolution = [solution[k] for k in w]\n@info \"solve-with-norma-equation\"\n# solve ŵ with normal equation\ntheoretical = inv(Matrix{eltype(X)}(X' * X)) * Matrix{eltype(X)}(X') * y\n\n\n@info \"check isequal\"\nif eltype(theoretical) == Sym\n    @assert all(solution .- theoretical .|> simplify .== 0)\nelse\n    solution=Array{Float64}(solution)\n    @assert all(isapprox.(solution ,theoretical, atol=1e-6))\nend\n@info \"done\"\n", "meta": {"hexsha": "890876df79db83e6ea6b1aaed9e68b677aaac161", "size": 1770, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "zygoteExer/multiple_regression.jl", "max_stars_repo_name": "terasakisatoshi/juliaExer", "max_stars_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-02T01:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-04T12:03:25.000Z", "max_issues_repo_path": "zygoteExer/multiple_regression.jl", "max_issues_repo_name": "terasakisatoshi/juliaExer", "max_issues_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "zygoteExer/multiple_regression.jl", "max_forks_repo_name": "terasakisatoshi/juliaExer", "max_forks_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2894736842, "max_line_length": 98, "alphanum_fraction": 0.5757062147, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7569034434971414}}
{"text": "export MinimalDominatingSet\n\nstruct MinimalDominatingSet end\n\n\"\"\"\n    dominating_set(g, MinimalDominatingSet(); seed=-1)\n\nFind a set of vertices that consitute a dominating set (all vertices in `g` are either adjacent to a vertex \nin the set or is a vertex in the set) and it is not possible to delete a vertex from the set \nwithout sacrificing the dominating property.\n\n### Implementation Notes\nInitially, every vertex is in the dominating set.\nIn some random order, we check if the removal of a vertex from the set will destroy the \ndominating property. If no, the vertex is removed from the dominating set.\n\n### Performance\nRuntime: ``\\\\mathcal{O}(|V|+|E|)``\nMemory: ``\\\\mathcal{O}(|V|)``\n\n### Optional Arguments\n- If `seed >= 0`, a random generator is seeded with this value.\n\"\"\"    \nfunction dominating_set(\n    g::AbstractGraph{T},\n    alg::MinimalDominatingSet;\n    seed::Int=-1\n    ) where T <: Integer \n\n    nvg = nv(g)  \n    in_dom_set = trues(nvg) \n    length_ds = Int(nvg)\n    dom_degree = degree(g)\n    @inbounds @simd for v in vertices(g)\n        dom_degree[v] -= (has_edge(g, v, v) ? 1 : 0)\n    end\n\n    for v in randperm(getRNG(seed), nvg)\n    \t(dom_degree[v] == 0) && continue #It is not adjacent to any dominating vertex\n    \t#Check if any vertex is depending on v to be dominated\n        dependent = findfirst(u -> !in_dom_set[u] && dom_degree[u] <= 1, neighbors(g, v))\n\n        (dependent != nothing) && continue\n        in_dom_set[v] = false\n        length_ds -= 1\n        dom_degree[neighbors(g, v)] .-= 1\n    end\n    \n    return LightGraphs.findall!(in_dom_set, Vector{T}(undef, length_ds))\nend\n", "meta": {"hexsha": "4e24015030040afdeb66eed5469cb752fa88e093", "size": 1618, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dominatingset/minimal_dom_set.jl", "max_stars_repo_name": "blepabyte/LightGraphs.jl", "max_stars_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 745, "max_stars_repo_stars_event_min_datetime": "2015-03-19T03:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-07T00:59:06.000Z", "max_issues_repo_path": "src/dominatingset/minimal_dom_set.jl", "max_issues_repo_name": "blepabyte/LightGraphs.jl", "max_issues_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1491, "max_issues_repo_issues_event_min_datetime": "2015-03-19T17:04:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T14:47:57.000Z", "max_forks_repo_path": "src/dominatingset/minimal_dom_set.jl", "max_forks_repo_name": "blepabyte/LightGraphs.jl", "max_forks_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 288, "max_forks_repo_forks_event_min_datetime": "2015-04-04T14:31:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T10:37:21.000Z", "avg_line_length": 31.7254901961, "max_line_length": 108, "alphanum_fraction": 0.6699629172, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7569034327930968}}
{"text": "# An implementation of CGS for the solution of the square linear system Ax = b.\n#\n# This method is described in\n#\n# Y. Saad, Iterative methods for sparse linear systems.\n# PWS Publishing Company, Boston, USA, 1996.\n#\n# P. Sonneveld, CGS, A Fast Lanczos-Type Solver for Nonsymmetric Linear systems.\n# SIAM Journal on Scientific and Statistical Computing, 10(1), pp. 36--52, 1989.\n#\n# Alexis Montoison, <alexis.montoison@polymtl.ca>\n# Montreal, October 2018.\n\nexport cgs\n\n\"\"\"Solve the consistent linear system Ax = b using conjugate gradient squared algorithm.\n\nFrom \"Iterative Methods for Sparse Linear Systems (Y. Saad)\" :\n\n«The method is based on a polynomial variant of the conjugate gradients algorithm.\nAlthough related to the so-called bi-conjugate gradients (BCG) algorithm,\nit does not involve adjoint matrix-vector multiplications, and the expected convergence\nrate is about twice that of the BCG algorithm.\n\nThe Conjugate Gradient Squared algorithm works quite well in many cases.\nHowever, one difficulty is that, since the polynomials are squared, rounding errors\ntend to be more damaging than in the standard BCG algorithm. In particular, very\nhigh variations of the residual vectors often cause the residual norms computed\nto become inaccurate.\n\nTFQMR and BICGSTAB were developed to remedy this difficulty.»\n\nThis implementation allows a right preconditioner M.\n\"\"\"\nfunction cgs(A :: AbstractLinearOperator, b :: AbstractVector{T};\n             M :: AbstractLinearOperator=opEye(size(A,1)),\n             atol :: Float64=1.0e-8, rtol :: Float64=1.0e-6,\n             itmax :: Int=0, verbose :: Bool=false) where {T <: Number}\n\n  m, n = size(A)\n  m == n || error(\"System must be square\")\n  length(b) == m || error(\"Inconsistent problem size\")\n  verbose && @printf(\"CGS: system of size %d\\n\", n)\n\n  # Initial solution x₀ and residual r₀.\n  x = zeros(T, n) # x₀\n  r = copy(b)     # r₀\n  # Compute ρ₀ = < r₀,r₀ > and residual norm ‖r₀‖₂.\n  ρ = @kdot(n, r, r)\n  rNorm = sqrt(ρ)\n  rNorm == 0 && return x, SimpleStats(true, false, [rNorm], [], \"x = 0 is a zero-residual solution\")\n\n  iter = 0\n  itmax == 0 && (itmax = 2*n)\n\n  rNorms = [rNorm;]\n  ε = atol + rtol * rNorm\n  verbose && @printf(\"%5d  %7.1e\\n\", iter, rNorm)\n\n  # Set up workspace.\n  u = copy(r)  # u₀\n  p = copy(r)  # p₀\n  q = zeros(n) # q₋₁\n\n  # Stopping criterion.\n  solved = rNorm ≤ ε\n  tired = iter ≥ itmax\n  status = \"unknown\"\n\n  while !(solved || tired)\n\n    y = M * p                 # yₘ = M⁻¹pₘ\n    v = A * y                 # vₘ = Ayₘ\n    σ = @kdot(n, v, b)        # σₘ = < AM⁻¹pₘ,r₀ >\n    α = ρ / σ                 # αₘ = ρₘ / σₘ\n    @. q = u - α * v          # qₘ = uₘ - αₘ * AM⁻¹pₘ\n    @kaxpy!(n, 1.0, q, u)     # uₘ₊½ = uₘ + qₘ\n    z = M * u                 # zₘ = M⁻¹uₘ₊½\n    @kaxpy!(n, α, z, x)       # xₘ₊₁ = xₘ + αₘ * M⁻¹(uₘ + qₘ)\n    w = A * z                 # wₘ = AM⁻¹(uₘ + qₘ)\n    @kaxpy!(n, -α, w, r)      # rₘ₊₁ = rₘ - αₘ * AM⁻¹(uₘ + qₘ)\n    ρ_next = @kdot(n, r, b)   # ρₘ₊₁ = < rₘ₊₁,r₀ >\n    β = ρ_next / ρ            # βₘ = ρₘ₊₁ / ρₘ\n    @. u = r + β * q          # uₘ₊₁ = rₘ₊₁ + βₘ * qₘ\n    @kaxpby!(n, 1.0, q, β, p) # pₘ₊₁ = uₘ₊₁ + βₘ * (qₘ + βₘ * pₘ)\n    @kaxpby!(n, 1.0, u, β, p)\n\n    # Update ρ.\n    ρ = ρ_next # ρₘ ← ρₘ₊₁\n\n    # Update iteration index.\n    iter = iter + 1\n\n    # Compute residual norm ‖rₘ‖₂.\n    rNorm = @knrm2(n, r)\n    push!(rNorms, rNorm)\n\n    # Update stopping criterion.\n    solved = rNorm ≤ ε\n    tired = iter ≥ itmax\n    verbose && @printf(\"%5d  %7.1e\\n\", iter, rNorm)\n  end\n  verbose && @printf(\"\\n\")\n\n  status = tired ? \"maximum number of iterations exceeded\" : \"solution good enough given atol and rtol\"\n  stats = SimpleStats(solved, false, rNorms, T[], status)\n  return (x, stats)\nend\n", "meta": {"hexsha": "6c9571f2fb898bbc690d57f42ede2ab64cac1bb8", "size": 3711, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cgs.jl", "max_stars_repo_name": "abelsiqueira/Krylov.jl", "max_stars_repo_head_hexsha": "dc0ca5466f7f1f7e65958fe016e3a06b858e3df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-06T18:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T18:14:15.000Z", "max_issues_repo_path": "src/cgs.jl", "max_issues_repo_name": "abelsiqueira/Krylov.jl", "max_issues_repo_head_hexsha": "dc0ca5466f7f1f7e65958fe016e3a06b858e3df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cgs.jl", "max_forks_repo_name": "abelsiqueira/Krylov.jl", "max_forks_repo_head_hexsha": "dc0ca5466f7f1f7e65958fe016e3a06b858e3df0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-05T10:58:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T10:58:57.000Z", "avg_line_length": 34.0458715596, "max_line_length": 103, "alphanum_fraction": 0.6009161951, "num_tokens": 1338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605411, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.756903424983274}}
{"text": "# Bi-objective linear problem (bilp)\n#\n# Example 6.3 (from Steuer, 1985), page 154 of\n# Multicriteria Optimization (2nd edt), M. Ehrgott, Springer 2005.\n\n\n# ---- Packages to use\nusing vOptGeneric, JuMP, GLPK\n\n\n# ---- setting the model + values\nbilp = vModel( GLPK.Optimizer )\n\n@variable( bilp, x1 >= 0 )\n@variable( bilp, x2 >= 0 )\n\n@addobjective( bilp, Min, 3*x1 + x2 )\n@addobjective( bilp, Min, -x1 - 2*x2 )\n\n@constraint( bilp, cst1, x2 <= 3 )\n@constraint( bilp, cst2, 3*x1 - x2 <= 6 )\n\n\n# ---- Invoking the solver (lexicographic method)\nvSolve( bilp, method=:lex )\n\n\n# ---- Querying the results\nY_N = getY_N( bilp )\n\n\n# ---- Displaying the results for lex(1,2) and lex(2,1)\nfor s = 1:2\n    print(\"X = [\")\n    print(round(getvOptData(bilp).X_E[s][1],digits=5))\n    print(\" \")\n    print(round(getvOptData(bilp).X_E[s][2],digits=5))\n    print(\"] | Z = [\")\n    print(round(Y_N[s][1], digits=5))\n    print(\" \")\n    print(round(Y_N[s][2], digits=5))\n    println(\"]\")\nend\n", "meta": {"hexsha": "97f8e75cceee18ef9dfce0ea94d21ddfd6c573f3", "size": 967, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/LinearProblemSteuer1985.jl", "max_stars_repo_name": "vOptSolver/vOptGeneric", "max_stars_repo_head_hexsha": "7c99ecfc5d1a672bdf69b2a557f97d0b964c126a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-10-06T06:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T11:03:38.000Z", "max_issues_repo_path": "examples/LinearProblemSteuer1985.jl", "max_issues_repo_name": "vOptSolver/vOptGeneric", "max_issues_repo_head_hexsha": "7c99ecfc5d1a672bdf69b2a557f97d0b964c126a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2018-10-26T10:52:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T00:35:22.000Z", "max_forks_repo_path": "examples/LinearProblemSteuer1985.jl", "max_forks_repo_name": "vOptSolver/vOptGeneric", "max_forks_repo_head_hexsha": "7c99ecfc5d1a672bdf69b2a557f97d0b964c126a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2017-08-28T22:28:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-08T17:57:15.000Z", "avg_line_length": 21.9772727273, "max_line_length": 66, "alphanum_fraction": 0.6132368149, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7568690303240461}}
{"text": "using LinearAlgebraicRepresentation\nLar = LinearAlgebraicRepresentation\n\n\"\"\"\nReturn the Lar.Struct of octahedron\n\"\"\"\nfunction octahedron(l)\n    a = l * (sqrt(3) / 2)\n    h = sqrt(a^2 - ((l / 2)^2))\n    #h=0.70710678118654\n    V = [0 l 0 l l/2; 0 0 l l l/2; 0 0 0 0 h]\n    VV = [[1], [2], [3], [4], [5]]\n    EV = [[1, 2], [2, 3], [3, 4], [4, 1], [1, 5], [2, 5], [3, 5], [4, 5]]\n    FV = [[1, 2, 5], [1, 3, 5], [3, 4, 5], [2, 4, 5]]\n    CV = [[1, 2, 3, 4, 5]]\n    tetrahedron = V, EV, FV, CV\n    return Lar.Struct([tetrahedron, Lar.t(0, l, 0), Lar.r(π, 0, 0), tetrahedron])\nend\n\"\"\"\nReturn the Lar.Struct of an irregular octahedron whit h as height\n\"\"\"\nfunction octahedron(l, h)\n    V = [0 l 0 l l / 2; 0 0 l l l / 2; 0 0 0 0 h]\n    VV = [[1], [2], [3], [4], [5]]\n    EV = [[1, 2], [3, 4], [4, 5], [1, 5], [1, 5], [2, 5], [3, 5], [4, 5]]\n    FV = [[1, 2, 5], [1, 3, 5], [3, 4, 5], [2, 4, 5]]\n    CV = [[1, 2, 3, 4, 5]]\n    tetrahedron = V, EV, FV, CV\n    return Lar.Struct([tetrahedron, Lar.t(0, l, 0), Lar.r(π, 0, 0), tetrahedron])\nend\n\"\"\"\nReturn the Lar.Struct of a rectangular base octahedron whit h as height\n\"\"\"\nfunction rectangularbase_octahedron(ab, da, h)\n    V = [0 ab 0 ab ab / 2; 0 0 da da da / 2; 0 0 0 0 h]\n    V2 = [0 ab 0 ab ab / 2; 0 0 da da da / 2; 0 0 0 0 -h]\n    VV = [[1], [2], [3], [4], [5]]\n    EV = [[1, 2], [3, 4], [4, 5], [1, 5], [1, 5], [2, 5], [3, 5], [4, 5]]\n    FV = [[1, 2, 5], [1, 3, 5], [3, 4, 5], [2, 4, 5]]\n    CV = [[1, 2, 3, 4, 5]]\n    tetrahedron = V, EV, FV, CV\n    tetrahedron2 = V2, EV, FV, CV\n    return Lar.Struct([tetrahedron, tetrahedron2])\nend\n", "meta": {"hexsha": "3b457553ca01e1a0f336d3c545b6a97132e4fdbe", "size": 1586, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/octahedron.jl", "max_stars_repo_name": "DarioDN/LinearAlgebraicRepresentation.jl", "max_stars_repo_head_hexsha": "250441918221398c3e3670cbbb03afee4e59ad8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/octahedron.jl", "max_issues_repo_name": "DarioDN/LinearAlgebraicRepresentation.jl", "max_issues_repo_head_hexsha": "250441918221398c3e3670cbbb03afee4e59ad8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/octahedron.jl", "max_forks_repo_name": "DarioDN/LinearAlgebraicRepresentation.jl", "max_forks_repo_head_hexsha": "250441918221398c3e3670cbbb03afee4e59ad8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2444444444, "max_line_length": 81, "alphanum_fraction": 0.4836065574, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787997, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7568690282401961}}
{"text": "using LinearAlgebra: I, norm, qr\nusing Parameters: @with_kw\n\nfunction _orthogonal_complement_matrix( Y, p = Inf )\n    Q, _ = qr(Y)\n    Z = Q[:, size(Y,2) + 1 : end]\n    if size(Z,2) > 0\n        Z ./= norm.( eachcol(Z), p )'\n    end\n    return Z\nend \n\n# stateful (Y,Z are stored so that I have access to them later)\n@with_kw mutable struct AffinelyIndependentPointFilter{F <: AbstractFloat, VF <: AbstractVector{F}, SV <: AbstractVector{VF}, I<:Real}\n\tx_0 :: VF\n\n\tseeds :: SV = Vector{VF}\n\t\n\tshifted_seeds :: SV = [ s .- x_0 for s in seeds]\n\n\tcandidate_indices :: Vector{Int} = collect(eachindex(seeds))\n\n\tn :: Int = length(x_0)\n\t\n\tY :: Matrix{F} = Matrix{eltype(x_0)}(undef, n, 0)\n\tZ :: Matrix{F} = Matrix{eltype(x_0)}(I(n))\n\n\tp :: I = Inf \t# which vector norm to use\n\n\tpivot_val :: F = 1e-3\n\n\treturn_indices :: Bool = false\n\n\t@assert n > 0 \"`x_0` must not be empty and `n` must be positive.\"\n\t@assert n <= length(x_0) \"Maximum number must be lower than `length(x_0)`.\"\nend\n\nfunction reset!( filter :: AffinelyIndependentPointFilter{F,VF,SF} ) where{F,VF,SF}\n\tfilter.candidate_indices = collect(eachindex(filter.seeds))\n\tfilter.Y = Matrix{F}(undef, filter.n, 0)\n\tfilter.Z = Matrix{F}(I(filter.n))\n\treturn nothing\nend\n\nfunction Base.iterate( filter :: AffinelyIndependentPointFilter{F,VF,SV} ) :: Union{Nothing, Tuple{<:Union{Int,VF}, Int}} where{F,VF,SV}\n\tisempty(filter.shifted_seeds) && return nothing\n\t_, i = findmax( norm.(filter.shifted_seeds, filter.p) )\n\n\tif length(filter.candidate_indices) != length(filter.seeds)\n\t\treset!(filter)\n\tend\n\n\tfilter.Y = hcat(filter.Y, filter.shifted_seeds[i])\n\tfilter.Z = _orthogonal_complement_matrix( filter.Y, filter.p )\n\n\tsetdiff!(filter.candidate_indices, i)\n\n\tif filter.return_indices\n\t\treturn i, 1\n\telse\n\t\treturn filter.seeds[i], 1\n\tend\nend\n\nfunction Base.iterate( filter :: AffinelyIndependentPointFilter{F,VF,SV}, num_found :: Int ) :: Union{Nothing,Tuple{<:Union{VF,Int}, Int}} where{F,VF,SV}\n\tnum_found == filter.n && return nothing\t\t\t# found enough points already\n\tisempty(filter.candidate_indices) && return nothing\t# no more points to search\n\n\tZ = filter.Z\n\n\tbest_val = -F(Inf)\n\tbest_index = -1\n\n\tfor i ∈ filter.candidate_indices\n\t\tx = filter.shifted_seeds[i]\n\t\tproj_x_Z = norm( Z*(Z'*x), filter.p )\n\n\t\tif proj_x_Z > best_val \n\t\t\tbest_val = proj_x_Z\n\t\t\tbest_index = i \n\t\t\t# NOTE we could check `proj_x_Z > filter.pivot_val` and break early here instead of finding the maximizer\n\t\tend\n\tend\n\n\tif best_val > filter.pivot_val\n\t\ti = best_index\n\t\tfilter.Y = hcat(filter.Y, filter.shifted_seeds[i])\n\t\tfilter.Z = _orthogonal_complement_matrix( filter.Y, filter.p )\n\t\tsetdiff!(filter.candidate_indices, i)\n\n\t\tif filter.return_indices\n\t\t\treturn i, num_found + 1\n\t\telse\n\t\t\treturn filter.seeds[i], num_found + 1\n\t\tend\n\tend\n\n\t@debug \"No point was sufficiently linearly independent.\"\n\treturn nothing\nend\n\nBase.IteratorSize( ::AffinelyIndependentPointFilter ) = Base.SizeUnknown()\nBase.IteratorEltype( :: AffinelyIndependentPointFilter ) = Base.HasEltype()\nfunction Base.eltype( filter :: AffinelyIndependentPointFilter{F,VF,SV} ) where {F,VF,SV}\n\tif filter.return_indices\n\t\treturn Int\n\telse\n\t\treturn VF \n\tend\nend\n", "meta": {"hexsha": "1cd9de7314865ab6dc8e9b94a1dfbb2172b796fe", "size": 3151, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/AffinelyIndependentPoints.jl", "max_stars_repo_name": "manuelbb-upb/Morbit.jl", "max_stars_repo_head_hexsha": "bfc6b1a7982d2c0003042ec9af75e64ad7ef5cf1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-07-21T14:38:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T13:14:14.000Z", "max_issues_repo_path": "src/AffinelyIndependentPoints.jl", "max_issues_repo_name": "manuelbb-upb/Morbit.jl", "max_issues_repo_head_hexsha": "bfc6b1a7982d2c0003042ec9af75e64ad7ef5cf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2021-04-14T09:40:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-09T10:43:40.000Z", "max_forks_repo_path": "src/AffinelyIndependentPoints.jl", "max_forks_repo_name": "manuelbb-upb/Morbit.jl", "max_forks_repo_head_hexsha": "bfc6b1a7982d2c0003042ec9af75e64ad7ef5cf1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-01T02:51:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T02:51:21.000Z", "avg_line_length": 28.3873873874, "max_line_length": 153, "alphanum_fraction": 0.7023167248, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7568690238646717}}
{"text": "using LightGraphs\nusing LinearAlgebra: UpperTriangular\n\n\"\"\"\nUniDirectionalBeta\n\"\"\"\nfunction beta_graph(beta::Vector; seed::Integer=-1)\n    n = length(beta)\n    coefM = UpperTriangular(beta' .+ beta)\n    g = SimpleGraph(n)\n    for i in 1:n\n        for j in i:n\n            expcoef_ij = exp(coefM[i,j])\n            if rand() < (expcoef_ij / (1 + expcoef_ij))\n                add_edge!(g, i, j)\n            end\n        end\n    end\n    return g\nend\n\n\n\"\"\"\nBiDirectionalBeta\n\"\"\"\nfunction beta_graph(alpha::Vector, beta::Vector; seed::Integer=-1)\n    n = length(beta)\n    @assert length(alpha) == n \"alpha and beta must be the same length\"\n    coefM = alpha' .+ beta\n    g = SimpleDiGraph(n)\n    for i in 1:n\n        for j in 1:n\n            expcoef_ij = exp(coefM[i,j])\n            if rand() < (expcoef_ij / (1 + expcoef_ij))\n                add_edge!(g, i, j)\n            end\n        end\n    end\n    return g\nend\n\n\"\"\"\nUniDirectionalSparseBeta\n\"\"\"\nfunction sparse_beta_graph(beta::Vector, mu::Real; seed::Integer=-1)\n    @assert all(beta .>= 0) \"beta must be non-negative\"\n    @assert 0 in beta \"beta must contain at least one zero\"\n    n = length(beta)\n    coefM = UpperTriangular(beta' .+ beta)\n    g = SimpleGraph(n)\n    for i in 1:n\n        for j in i:n\n            expcoef_ij = exp(mu + coefM[i,j])\n            if rand() < (expcoef_ij / (1 + expcoef_ij))\n                add_edge!(g, i, j)\n            end\n        end\n    end\n    return g\nend", "meta": {"hexsha": "1d80115735aa9d0e95e78fb2f3f77399bda8e717", "size": 1441, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/generators.jl", "max_stars_repo_name": "jacobusmmsmit/sparse-beta", "max_stars_repo_head_hexsha": "798bc89e10704160ff25b2cb3a2dfd7adf45eead", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-21T00:43:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-21T00:43:32.000Z", "max_issues_repo_path": "src/generators.jl", "max_issues_repo_name": "jacobusmmsmit/sparse-beta", "max_issues_repo_head_hexsha": "798bc89e10704160ff25b2cb3a2dfd7adf45eead", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/generators.jl", "max_forks_repo_name": "jacobusmmsmit/sparse-beta", "max_forks_repo_head_hexsha": "798bc89e10704160ff25b2cb3a2dfd7adf45eead", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0166666667, "max_line_length": 71, "alphanum_fraction": 0.5572519084, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7568690199047962}}
{"text": "######### CmdStan batch program example  ###########\n\nusing CmdStan, StatsPlots\n\nProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n\n  eightschools =\"\n  data {\n    int<lower=0> J; // number of schools\n    real y[J]; // estimated treatment effects\n    real<lower=0> sigma[J]; // s.e. of effect estimates\n  }\n  parameters {\n    real mu;\n    real<lower=0> tau;\n    real eta[J];\n  }\n  transformed parameters {\n    real theta[J];\n    for (j in 1:J)\n      theta[j] <- mu + tau * eta[j];\n  }\n  model {\n    eta ~ normal(0, 1);\n    y ~ normal(theta, sigma);\n  }\n  \"\n\n  schools8data = Dict(\"J\" => 8,\n      \"y\" => [28,  8, -3,  7, -1,  1, 18, 12],\n      \"sigma\" => [15, 10, 16, 11,  9, 11, 10, 18],\n      \"tau\" => 25\n    )\n\n  global stanmodel, rc, chns, cnames\n  stanmodel = Stanmodel(name=\"schools8\", model=eightschools,\n    output_format=:mcmcchains);\n  rc, chn, cnames = stan(stanmodel, schools8data, ProjDir, CmdStanDir=CMDSTAN_HOME)\n\n  if rc == 0\n    \n    chns = set_section(chn, Dict(\n      :parameters => [\"mu\", \"tau\"],\n      :thetas => [\"theta.$i\" for i in 1:8],\n      :etas => [\"eta.$i\" for i in 1:8],\n      :internals => [\"lp__\", \"accept_stat__\", \"stepsize__\", \"treedepth__\", \"n_leapfrog__\",\n        \"divergent__\", \"energy__\"]\n      )\n    )\n    \n    if isdefined(Main, :StatsPlots)\n      p1 = plot(chns)\n      savefig(p1, \"traceplot.pdf\")\n      #p2 = plot(chns, [:thetas])\n      #savefig(p2, \"thetas.pdf\")\n    end\n    \n    show(chns)\n    println(\"\\n\")\n    summarize(chns, sections=[:thetas])\n    \n  end\nend # cd\n", "meta": {"hexsha": "4a519a6de30ed58143a7b0bc648fa4ae9749c274", "size": 1504, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/EightSchools/schools8.jl", "max_stars_repo_name": "fargolo/CmdStan.jl", "max_stars_repo_head_hexsha": "ffb3f49c027101ce59cee9200cd9e9f3597a3e6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/EightSchools/schools8.jl", "max_issues_repo_name": "fargolo/CmdStan.jl", "max_issues_repo_head_hexsha": "ffb3f49c027101ce59cee9200cd9e9f3597a3e6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/EightSchools/schools8.jl", "max_forks_repo_name": "fargolo/CmdStan.jl", "max_forks_repo_head_hexsha": "ffb3f49c027101ce59cee9200cd9e9f3597a3e6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1384615385, "max_line_length": 90, "alphanum_fraction": 0.5511968085, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7568690102157347}}
{"text": "\"\"\"\n    sum_of_sines(domain, c, ω, ϕ)\n\nCreate initial condition function `u₀` and an antiderivative `U₀`.\nThe function is a sum of sines of amplitudes `c`, frequencies `ω` and phase-shifts `ϕ`.\n\"\"\"\nfunction sum_of_sines(domain, c, ω, ϕ)\n    φ(ω, ϕ, x) = sin(ω * x - ϕ) \n    Φ(ω, ϕ, x) = ω ≈ 0 ? -sin(ϕ) * x : -cos(ω * x - ϕ) / ω \n    u₀(x) = sum(c .* φ.(ω, ϕ, x))\n    U₀(x) = sum(c .* Φ.(ω, ϕ, x))\n    u₀, U₀\nend\n", "meta": {"hexsha": "606754f65b5a54d6ad0cbea15c3654244556d7d4", "size": 413, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/sum_of_sines.jl", "max_stars_repo_name": "agdestein/DiscreteFiltering.jl", "max_stars_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-23T12:51:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T12:51:11.000Z", "max_issues_repo_path": "src/utils/sum_of_sines.jl", "max_issues_repo_name": "agdestein/DiscreteFiltering.jl", "max_issues_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/sum_of_sines.jl", "max_forks_repo_name": "agdestein/DiscreteFiltering.jl", "max_forks_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5, "max_line_length": 87, "alphanum_fraction": 0.5423728814, "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545377452443, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7568044084543732}}
{"text": "########################################################################\n# Atoms of the Positive Simplex\n########################################################################\n\n\"\"\"\n    PosSimplexAtom(n, z)\n\nAtom in the positive simplex of dimension n.\n\"\"\"\nstruct PosSimplexAtom <: AbstractAtom\n    n::Int64\n    z::Vector{Float64}\n    function PosSimplexAtom(z)\n        n = length(z)\n        return new(n, z)\n    end\nend\n\n\"\"\"\nMultiply a Positive simplex atom by a linear map.\n\"\"\"\nBase.:(*)(M::AbstractLinearOp, a::PosSimplexAtom) = M*a.z\nBase.vec(a::PosSimplexAtom) = a.z\nBase.length(a::PosSimplexAtom) = a.n\n\n########################################################################\n# Atomic set for the positive simplex \n########################################################################\n\n\"\"\"\n    PosSimplex(c, n, maxrank=n)\n\nAtomic set defined by positive simplex in `n` variables.\nThe atomic set takes an optional parameters:\n\n`maxrank` is the maximum dimension of the face exposed by a vector.\n\"\"\"\nstruct PosSimplex <: AbstractAtomicSet\n    c::Vector{Float64}\n    n::Int64\n    maxrank::Int64\n    function PosSimplex(c, maxrank)\n        n = length(c)\n        minimum(c) > 0 || throw(DomainError(c,\"c must be in non-negative orthant\"))\n        n ≥ maxrank ≥ 1 || throw(DomainError(maxrank,\"maxrank must be ≥ 1\"))\n        return new(c, n, maxrank)\n    end\nend\n\n\nfunction PosSimplex(c::Vector{Float64}; maxrank = length(findall(!iszero,c)) ) \n    index_c = findall(x -> x != 0, c)\n    maxrank <= length(index_c) || throw(DomainError(maxrank,\"maxrank should be less than sparstiy level of c\"))\n    return PosSimplex(c, maxrank)\nend\n\nPosSimplex(n::Int64; maxrank=n) = PosSimplex(ones(n), maxrank)\n\n\n\"\"\"\n    gauge(A::PosSimplex, x::Vector)\n\nGives the sum `dot(c, x)`.\n\"\"\"\nfunction gauge(A::PosSimplex, x::Vector) \n    for i in eachindex(x)\n        if (A.c[i] == 0 && x[i] != 0) || x[i] < 0\n            return Inf\n        end\n    end\n    return dot(A.c,x)\nend\n\"\"\"\n    support(A::PosSimplex, z::Vector)\n\nGives the inf-norm of `c ⊙ z`.\n\"\"\"\nfunction support(A::PosSimplex, z::Vector) \n    sup = 0. \n    for i in eachindex(z)\n        if A.c[i] != 0\n            sup = max(sup, z[i]/A.c[i])\n        end\n    end\n\n    return sup\nend\n\"\"\"\n    expose(A::PosSimplex, z::Vector)\n\nA non-overwriting version of [`expose!`](@ref).\n\"\"\"\nexpose(A::PosSimplex, z; kwargs...) = expose!(A::PosSimplex, copy(z); kwargs...)\n\n\"\"\"\n    expose!(A::PosSimplex, z::Vector; tol=1e-12)\n\nObtain an atom in the face exposed by the vector `z`.\nThe vector `z` is overwritten. If `norm(z,Inf)<tol`, then\n`z` is returned untouched.\n\"\"\"\n\nfunction expose!(A::PosSimplex, z::Vector; tol=1e-1)\n    # z = Float64.(z)\n    zsup = support(A, z)\n    if maximum(z) < -1e-12\n        return PosSimplexAtom(zero(z))\n    end\n\n    index_c = findall(x -> x != 0, A.c) \n    index_c_comp = findall(x -> x == 0, A.c) \n    \n    if zsup < 1e-12\n        nnz = 1\n    else\n        nnz = 0\n    end\n\n    # for i in eachindex(index_c_comp)\n    #     z[index_c_comp[i]] = 0\n    # end\n    for i in eachindex(index_c)\n        val = (A.c[index_c[i]]).^(-1) * z[index_c[i]]\n        if abs(zsup - val) ≤ tol*zsup\n            z[index_c[i]] = 1/A.c[index_c[i]]\n            nnz += 1\n        else\n            z[index_c[i]] = zero(eltype(z))\n        end\n    end\n    return PosSimplexAtom(z ./= nnz)\nend\n\nBase.length(A::PosSimplex) = A.n\nrank(A::PosSimplex) = A.maxrank\natom_name(A::PosSimplex) = \"Positive Simplex\"\natom_description(A::PosSimplex) = \"{ x ∈ ℝⁿ | ⟨c, x⟩ ≤ 1, x ≥ 0}\"\natom_parameters(A::PosSimplex) = \"c = cost vector, n = $(length(A)); maxrank = $(A.maxrank)\"\n\n########################################################################\n# Face of the positive simplex.\n########################################################################\n\nstruct PosSimplexFace{LM <: LinearMap} <: AbstractFace\n    n::Int64\n    k::Int64\n    S::LM\nend\n\nPosSimplexFace(S::LinearMap) = PosSimplexFace(size(S)...,S)\n\n\"\"\"\n    face(A, z)\n\nReturn a face of the atomic set `A` exposed by the vector `z`. The dimension of\nthe exposed face is limited by `k=maxrank(A)`. If the dimension is being limited\nby `k`, then the routine returns a set of rank `k` atoms that define the subset\nof the exposed face.\n\"\"\"\nfunction face(A::PosSimplex, z::Vector; rTol=1e-1)\n\n    t = support(A, z)\n    a = expose(A, z, tol=rTol*t)\n    idx = findall(!iszero, vec(a))\n    \n    k = length(idx)\n    val = [(A.c[i]).^(-1) for i in idx]\n    n = length(A)\n    if support(A,z) < 1e-12\n        S = sparse(idx, collect(1:k), val, n, k + 1)\n    else\n        S = sparse(idx, collect(1:k), val, n, k)\n    end\n    S = LinearMap(S)\n    return PosSimplexFace(S)\nend\n\n\"\"\"\nGiven a face and a set of weights, reveal the corresponding\npoint on the face.\n\"\"\"\nBase.:(*)(F::PosSimplexFace, c::Vector) = F.S*c\nBase.:(*)(M::AbstractLinearOp, F::PosSimplexFace) = M*F.S\nBase.:(*)(λ::Real, F::PosSimplexFace) = λ*F.S\nBase.length(F::PosSimplexFace) = F.n\nrank(F::PosSimplexFace) = F.k\nvec(F::PosSimplexFace) = F.S\nface_name(F::PosSimplexFace) = \"Face of positive simplex\"\nface_parameters(F::PosSimplexFace) = \"rank = $(rank(F)); n = $(length(F))\"\n", "meta": {"hexsha": "6662f8f869e88f8c230de5d5274f766be2cd697c", "size": 5119, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BasicSets/PosSimplex.jl", "max_stars_repo_name": "MPF-Optimization-Laboratory/AtomicOpt.jl", "max_stars_repo_head_hexsha": "a03f6a0ed152bad9b518548fafa936667deb8a67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-01T01:26:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T01:26:04.000Z", "max_issues_repo_path": "src/BasicSets/PosSimplex.jl", "max_issues_repo_name": "ZhenanFanUBC/AtomicOpt.jl", "max_issues_repo_head_hexsha": "a03f6a0ed152bad9b518548fafa936667deb8a67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BasicSets/PosSimplex.jl", "max_forks_repo_name": "ZhenanFanUBC/AtomicOpt.jl", "max_forks_repo_head_hexsha": "a03f6a0ed152bad9b518548fafa936667deb8a67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9421052632, "max_line_length": 111, "alphanum_fraction": 0.5581168197, "num_tokens": 1524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7567936711959354}}
{"text": "\"\"\"\n    Basis\n\nAbstract supertype of various basis sets that vector spherical harmonics may be decomposed in.\n\"\"\"\nabstract type Basis end\n@doc raw\"\"\"\n    SphericalCovariant <: Basis\n\nThe spherical covariant basis ``\\chi_\\mu`` for ``\\mu\\in\\{-1,0,1\\}``\n\"\"\"\nstruct SphericalCovariant <: Basis end\n@doc raw\"\"\"\n    Polar <: Basis\n\nThe spherical polar basis ``\\hat{r}``, ``\\hat{\\theta}``, ``\\hat{\\phi}``.\n\"\"\"\nstruct Polar <: Basis end\n@doc raw\"\"\"\n    HelicityCovariant  <: Basis\n\nThe helicity basis ``\\mathbf{e}_\\mu`` for ``\\mu\\in\\{-1,0,1\\}``\n\"\"\"\nstruct HelicityCovariant <: Basis end\n@doc raw\"\"\"\n    Cartesian  <: Basis\n\nThe Cartesian basis ``\\hat{x}``, ``\\hat{y}``, ``\\hat{z}``\n\"\"\"\nstruct Cartesian <: Basis end\n\nBase.broadcastable(B::Basis) = Ref(B)\n\n_basisinds(::Union{HelicityCovariant, SphericalCovariant}) = -1:1\n_basisinds(::Union{Cartesian, Polar}) = 1:3\n\n#= Define matrices that convert between components C1 and C2 in bases B1 and B2 as\n    M * C1 = C2\n\nThe corresponding functions are named B1_B2_conversion.\nThese matrices are conjugates of those that convert between the bases, so conj.(M) * B1 = B2\n=#\nconst HelicitySphericalPolarConversionMatrix = SMatrix{3,3}([\n                                        0       1   0\n                                        1/√2    0   -1/√2\n                                        -im/√2   0    -im/√2\n                                        ])\n\nhelicity_polar_conversion(θ, ϕ) = HelicitySphericalPolarConversionMatrix\npolar_helicity_conversion(θ, ϕ) = helicity_polar_conversion(θ, ϕ)'\n\nfunction helicity_spherical_conversion(θ, ϕ)\n    cisϕ = cis(ϕ)\n    sinθ, cosθ = sincos(θ)\n    invsqrt2 = 1/√2\n    sin²θby2 = (1 - cosθ)/2\n    cos²θby2 = (1 + cosθ)/2\n    SMatrix{3,3}((\n        cos²θby2 * cisϕ,\n        -sinθ * invsqrt2,\n        sin²θby2 * conj(cisϕ),\n\n        sinθ * invsqrt2 * cisϕ,\n        cosθ,\n        -sinθ * invsqrt2 * conj(cisϕ),\n\n        sin²θby2 * cisϕ,\n        sinθ * invsqrt2,\n        cos²θby2 * conj(cisϕ),\n        ))\nend\nspherical_helicity_conversion(θ, ϕ) = helicity_spherical_conversion(θ, ϕ)'\n\nfunction helicity_cartesian_conversion(θ, ϕ)\n    sinθ, cosθ = sincos(θ)\n    sinϕ, cosϕ = sincos(ϕ)\n    invsqrt2 = 1/√2\n\n    SMatrix{3,3}((\n        (cosθ * cosϕ + im * sinϕ) * invsqrt2,\n        (cosθ * sinϕ - im * cosϕ) * invsqrt2,\n        -sinθ * invsqrt2,\n\n        sinθ * cosϕ,\n        sinθ * sinϕ,\n        cosθ,\n\n        -(cosθ * cosϕ - im * sinϕ) * invsqrt2,\n        -(cosθ * sinϕ + im * cosϕ) * invsqrt2,\n        sinθ * invsqrt2,\n        ))\nend\ncartesian_helicity_conversion(θ, ϕ) = helicity_cartesian_conversion(θ, ϕ)'\n\nfunction spherical_polar_conversion(θ, ϕ)\n    invsqrt2 = 1/√2\n    invsqrt2cisϕ = invsqrt2 * cis(ϕ)\n    sinθ, cosθ = sincos(θ)\n    normsinθcisϕ = sinθ * invsqrt2cisϕ\n    normcosθcisϕ = cosθ * invsqrt2cisϕ\n    SMatrix{3,3}((\n        conj(normsinθcisϕ),\n        conj(normcosθcisϕ),\n        -im * conj(invsqrt2cisϕ),\n\n        cosθ,\n        -sinθ,\n        0,\n\n        -normsinθcisϕ,\n        -normcosθcisϕ,\n        -im * invsqrt2cisϕ,\n        ))\nend\npolar_spherical_conversion(θ, ϕ) = spherical_polar_conversion(θ, ϕ)'\n\nconst SphericalCartesianConversionMatrix = SMatrix{3,3}((\n        1/√2,\n        -im/√2,\n        0,\n\n        0,\n        0,\n        1,\n\n        -1/√2,\n        -im/√2,\n        0,\n        ))\n\nspherical_cartesian_conversion(θ, ϕ) = SphericalCartesianConversionMatrix\ncartesian_spherical_conversion(θ, ϕ) = spherical_cartesian_conversion(θ, ϕ)'\n\nfunction cartesian_polar_conversion(θ, ϕ)\n    sinθ, cosθ = sincos(θ)\n    sinϕ, cosϕ = sincos(ϕ)\n    SMatrix{3,3}((\n        sinθ*cosϕ,\n        cosθ*cosϕ,\n        -sinϕ,\n\n        sinθ*sinϕ,\n        cosθ*sinϕ,\n        cosϕ,\n\n        cosθ,\n        -sinθ,\n        0,\n        ))\nend\npolar_cartesian_conversion(θ, ϕ) = cartesian_polar_conversion(θ, ϕ)'\n\n\"\"\"\n    basisconversionmatrix(B1, B2, θ, ϕ)\n\nReturn the matrix that converts the components of a vector from the basis `B1` to the basis `B2`\nat the point `(θ,ϕ)`.\n\n!!! note\n    For the complex bases `SphericalCovariant` and `HelicityCovariant`, the matrix transforms the\n    contravariant components between bases.\n\n# Examples\n```jldoctest\njulia> v = [1,0,0] # x\n3-element Vector{Int64}:\n 1\n 0\n 0\n\njulia> θ, ϕ = pi/2, 0\n(1.5707963267948966, 0)\n\njulia> M = VectorSphericalHarmonics.basisconversionmatrix(Cartesian(), Polar(), θ, ϕ)\n3×3 StaticArrays.SMatrix{3, 3, Float64, 9} with indices SOneTo(3)×SOneTo(3):\n  1.0          0.0   6.12323e-17\n  6.12323e-17  0.0  -1.0\n -0.0          1.0   0.0\n\njulia> M * v # polar coordinates along r, θ, ϕ\n3-element StaticArrays.SVector{3, Float64} with indices SOneTo(3):\n 1.0\n 6.123233995736766e-17\n 0.0\n```\n\"\"\"\nbasisconversionmatrix(::T, ::T, θ, ϕ) where {T<:Basis} = I\nbasisconversionmatrix(::HelicityCovariant, ::SphericalCovariant, θ, ϕ) = helicity_spherical_conversion(θ, ϕ)\nbasisconversionmatrix(::SphericalCovariant, ::HelicityCovariant, θ, ϕ) = spherical_helicity_conversion(θ, ϕ)\nbasisconversionmatrix(::HelicityCovariant, ::Polar, θ, ϕ) = helicity_polar_conversion(θ, ϕ)\nbasisconversionmatrix(::Polar, ::HelicityCovariant, θ, ϕ) = polar_helicity_conversion(θ, ϕ)\nbasisconversionmatrix(::HelicityCovariant, ::Cartesian, θ, ϕ) = helicity_cartesian_conversion(θ, ϕ)\nbasisconversionmatrix(::Cartesian, ::HelicityCovariant, θ, ϕ) = cartesian_helicity_conversion(θ, ϕ)\n\nbasisconversionmatrix(::SphericalCovariant, ::Polar, θ, ϕ) = spherical_polar_conversion(θ, ϕ)\nbasisconversionmatrix(::Polar, ::SphericalCovariant, θ, ϕ) = polar_spherical_conversion(θ, ϕ)\nbasisconversionmatrix(::SphericalCovariant, ::Cartesian, θ, ϕ) = spherical_cartesian_conversion(θ, ϕ)\nbasisconversionmatrix(::Cartesian, ::SphericalCovariant, θ, ϕ) = cartesian_spherical_conversion(θ, ϕ)\n\nbasisconversionmatrix(::Cartesian, ::Polar, θ, ϕ) = cartesian_polar_conversion(θ, ϕ)\nbasisconversionmatrix(::Polar, ::Cartesian, θ, ϕ) = polar_cartesian_conversion(θ, ϕ)\n", "meta": {"hexsha": "2dfcab35cc2c1c363ebbba0bd25e703a8cabced1", "size": 5856, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basis.jl", "max_stars_repo_name": "jishnub/VectorSphericalHarmonics.jl", "max_stars_repo_head_hexsha": "475a084db7e23ccd6bca85b9f8713622139b1981", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-07T15:37:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T03:43:31.000Z", "max_issues_repo_path": "src/basis.jl", "max_issues_repo_name": "jishnub/VectorSphericalHarmonics.jl", "max_issues_repo_head_hexsha": "475a084db7e23ccd6bca85b9f8713622139b1981", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2021-04-27T11:59:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-29T10:24:45.000Z", "max_forks_repo_path": "src/basis.jl", "max_forks_repo_name": "jishnub/VectorSphericalHarmonics.jl", "max_forks_repo_head_hexsha": "475a084db7e23ccd6bca85b9f8713622139b1981", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9900990099, "max_line_length": 108, "alphanum_fraction": 0.6366120219, "num_tokens": 2038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7567936671337724}}
{"text": "\n# Numerically stable expit\n@inline function expit(t::T) where T\n    if t >= 0.0\n        return one(T) / (one(T) + exp(-t))\n    else\n        e_t = exp(t)\n        return e_t / (one(T) + e_t)\n    end\nend\n\n# A numerically robust function to evaluate -log(1 + exp(-t))\n# See: http://fa.bianp.net/blog/2019/evaluate_logistic/\n@inline function log1pexp(t::T)::T where T\n    if t < -33.3\n        return t\n    elseif t <= -18.0\n        return t - exp(t)\n    elseif t <= 37.0\n        return -log1p(exp(-t))\n    else\n        return -exp(-t)\n    end\nend\n\n\"Compute Fenchel transform of f(x) = log(1 + exp(-x)).\"\nfunction logloss(λ::T) where T <: Real\n    # TODO: numerically robust version\n    if λ == 0.0 || λ == -1.0\n        return 0.0\n    elseif -1.0 < λ < 0.0\n        return (1.0 + λ) * log(1.0 + λ) - λ * log(-λ)\n    else\n        return Inf\n    end\nend\n\nabstract type AbstractScaler end\n\n\"Scale dataset before optimization.\"\nscale!(::AbstractScaler, X::AbstractArray{T, 2}) where T = nothing\n\n\n\"\"\"\nScale each feature in dataset by standard deviation.\n\n```math\nμ_j = mean(x_j)\nσ_j = std(x_j)\nx_j^+ =  (x_j - μ_j) / σ_j\n\n```\n\n\"\"\"\nstruct NormalScaler <: AbstractScaler end\n\nfunction scale!(::NormalScaler, X::Array{T, 2}) where T\n    n, d = size(X)\n    μ = mean(X, dims=1)\n    σ = std(X, dims=1)\n\n    @inbounds for i in 1:d\n        X[:, i] .= (X[:, i] .- μ[i]) ./ σ[i]\n    end\nend\n\nfunction scale!(::NormalScaler, X::AbstractSparseMatrix{T, Int}) where T\n    n, d = size(X)\n    σ = std(X, dims=1)\n    @inbounds for i in 1:d\n        X[:, i] ./= σ[i]\n    end\nend\n\n\"\"\"\nFormat labels `y = [y_1, ..., y_n]` to ensure that `y_i ∈ { -1, 1}`\nfor all index i.\n\n# Examples\n\n```julia\n    y = [-2.0, 1.0, -1.0, 2.0]\n    format_label!(y)\n\n```\n\"\"\"\nfunction format_label!(y::AbstractVector)\n    set_reference = [-1.0, 1.0]\n    elts = unique(y)\n    if union(elts, set_reference) != set_reference\n        intersets = intersect(elts, set_reference)\n        replacements = setdiff(set_reference, intersets)\n        # For all elements not in reference set\n        count = 1\n        for elt in setdiff(elts, set_reference)\n            y[y .== elt] .= replacements[count]\n            count += 1\n        end\n    end\n    return nothing\nend\n\n# Return upper index (ordered by rows) of a pxp triangular matrix\nfunction triul(p)\n    index = Int[]\n    for i in 1:p\n        for j in i:p\n            push!(index, i + (j - 1) * p)\n        end\n    end\n    return index\nend\n", "meta": {"hexsha": "0a924d0263c84fb87fd498b6a03331d3b39d40fd", "size": 2430, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "frapac/LogisticOptTools.jl", "max_stars_repo_head_hexsha": "dbd22ee2819786cadd5a5f9ecae692788d764a43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-02T11:13:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-02T11:13:45.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "frapac/LogisticOptTools.jl", "max_issues_repo_head_hexsha": "dbd22ee2819786cadd5a5f9ecae692788d764a43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-04T22:49:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T14:28:49.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "frapac/LogisticOptTools.jl", "max_forks_repo_head_hexsha": "dbd22ee2819786cadd5a5f9ecae692788d764a43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5044247788, "max_line_length": 72, "alphanum_fraction": 0.5654320988, "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7567936659885632}}
{"text": "@taylorize function lotka_volterra!(du, u, p, t)\n    u1u2 = u[1] * u[2]\n    du[1] = 3.0 * (u[1] - u1u2)\n    du[2] = u1u2 - u[2]\n    return du\nend\n\nfunction lotka_volterra_hybrid(; nsplit=1,\n                                 ε = 0.008,\n                                 ε_ext=1e-4, # threshold for the outer approximation\n                                 n_int=50)   # number of directions for the inner approximation\n\n    # generate external / internal polytopic approximations of the guard\n    B = Ball2([1.0, 1.0], 0.15) # \"exact\"\n    B_ext = overapproximate(B, ε_ext) # outer approximation\n    B_int = underapproximate(B, PolarDirections(n_int)) # inner approximation\n    B_int = tohrep(convert(VPolygon, B_int)) # cast to Hrep\n    B_intᶜ = complement(B_int)\n\n    # define modes\n    aut = LightAutomaton(3)\n    outside = @system(x' = lotka_volterra!(x), dim: 2, x ∈ B_intᶜ)\n    inside = @system(x' = lotka_volterra!(x), dim: 2, x ∈ B_ext)\n    outside_unconstrained = @system(x' = lotka_volterra!(x), dim: 2, x ∈ Universe(2))\n\n    # define the transition graph\n    add_transition!(aut, 1, 2, 1)\n    add_transition!(aut, 2, 3, 2)\n    T_out_in = @map(x -> x, dim:2, x ∈ B_ext)\n    T_in_out = @map(x -> x, dim:2, x ∈ B_intᶜ)\n\n    # initial-value problem\n    H = HybridSystem(automaton=aut, modes=[outside, inside, outside_unconstrained],\n                                           resetmaps=[T_out_in, T_in_out])\n\n    # initial states with splitting\n    X0 = Hyperrectangle(low=[1.3-ε, 1.], high=[1.3+ε, 1.])\n    X0s = split(X0, [nsplit, 1])\n    X0st = [(X0s_i, 1) for X0s_i in X0s]\n    return InitialValueProblem(H, X0st)\nend\n\n#=\n# TEST RUN:\n\nprob = lotka_volterra_hybrid(nsplit=10, ε_ext=1e-4, n_int = 30, ε = 0.008);\n@time sol = solve(prob,\n                  tspan=(0.0, 3.64),\n                  alg=TMJets(abstol=1e-12, orderT=7, orderQ=1, adaptive=true, disjointness=RA.ZonotopeEnclosure()),\n                  max_jumps=2,\n                  intersect_source_invariant=false,\n                  intersection_method=RA.BoxIntersection(),\n                  clustering_method=RA.BoxClustering(),\n                  disjointness_method=RA.BoxEnclosure());\nsolz = overapproximate(sol, Zonotope);\n\nB = Ball2([1.0, 1.0], 0.15) # \"exact\"\nB_ext = overapproximate(B, 1e-6) # outer approximation\nplot(solz, vars=(1, 2))\nplot!(B_ext, ratio=1)\n=#\n", "meta": {"hexsha": "674d9d927a20216dbf9231530c7ef5a6c7785f34", "size": 2333, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/models/hybrid/lotka_volterra.jl", "max_stars_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_stars_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2020-03-30T16:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:26:48.000Z", "max_issues_repo_path": "test/models/hybrid/lotka_volterra.jl", "max_issues_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_issues_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 258, "max_issues_repo_issues_event_min_datetime": "2020-03-30T14:13:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T17:07:04.000Z", "max_forks_repo_path": "test/models/hybrid/lotka_volterra.jl", "max_forks_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_forks_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-04-23T03:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T23:11:32.000Z", "avg_line_length": 37.6290322581, "max_line_length": 115, "alphanum_fraction": 0.5927989713, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391600697869, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7567936622216908}}
{"text": "using DelimitedFiles\n\n# This is a function to simulate a \"chaos game\"\nfunction chaos_game(n::Int, shape_points)\n\n    # Initializing the output array and the initial point\n    output_points = zeros(n,2)\n    point = [rand(), rand()]\n\n    for i = 1:n\n        output_points[i,:] .= point\n        point = 0.5*(rand(shape_points) .+ point)\n    end\n\n    return output_points\n\nend\n\n# This will generate a Sierpinski triangle with a chaos game of n points for an \n# initial triangle with three points on the vertices of an equilateral triangle:\n#     A = (0.0, 0.0)\n#     B = (0.5, sqrt(0.75))\n#     C = (1.0, 0.0)\n# It will output the file sierpinski.dat, which can be plotted after\nshape_points = [[0.0, 0.0],\n                [0.5, sqrt(0.75)],\n                [1.0, 0.0]]\noutput_points = chaos_game(10000, shape_points)\nwritedlm(\"sierpinski.dat\", output_points)\n", "meta": {"hexsha": "338a8016f4a2c0e75e504eae8f855e455b2c02d1", "size": 856, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "contents/IFS/code/julia/IFS.jl", "max_stars_repo_name": "alzawad26/algorithm-archive", "max_stars_repo_head_hexsha": "98ca4ab8115dd9013e6a5267cb757d61f0350ad7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1975, "max_stars_repo_stars_event_min_datetime": "2018-04-28T13:46:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:14:47.000Z", "max_issues_repo_path": "contents/IFS/code/julia/IFS.jl", "max_issues_repo_name": "alzawad26/algorithm-archive", "max_issues_repo_head_hexsha": "98ca4ab8115dd9013e6a5267cb757d61f0350ad7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 632, "max_issues_repo_issues_event_min_datetime": "2018-04-28T10:27:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T20:38:53.000Z", "max_forks_repo_path": "contents/IFS/code/julia/IFS.jl", "max_forks_repo_name": "alzawad26/algorithm-archive", "max_forks_repo_head_hexsha": "98ca4ab8115dd9013e6a5267cb757d61f0350ad7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 433, "max_forks_repo_forks_event_min_datetime": "2018-04-27T22:50:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T06:16:03.000Z", "avg_line_length": 28.5333333333, "max_line_length": 80, "alphanum_fraction": 0.6413551402, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558356, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7567936607811907}}
{"text": "# Endogenous Grid Points with IID Income\n# Greg Kaplan 2017\n# Translated by Tom Sweeney Dec 2020\n\nusing Random, Interpolations, NLsolve, Plots\ninclude(\"discrete_normal.jl\")\ninclude(\"lininterp1.jl\")\n\n# PARAMETERS\n\n## preferences\nrisk_aver = 2\nbeta = 0.95\n\n## returns\nr = 0.03\nR = 1+r\n\n## income risk: discretized N(mu,sigma^2)\nmu_y = 1\nsd_y = 0.2\nny = 5\n\n## asset grids\nna = 50\namax = 50\nborrow_lim = 0\nagrid_par = 0.5 # 1 for linear, 0 for L-shaped\n\n## computation\nmax_iter = 1000\ntol_iter = 1.0e-6\nNsim = 50000\nTsim = 500\n\n## mpc options\nmpcamount1 = 1.0e-10 # approximate thoeretical mpc\nmpcamount2 = 0.10 # one percent of average income: approx $500\n\n# OPTIONS\nDisplay = 1\nDoSimulate = 1\nMakePlots = 1\nComputeMPC = 1\n\n# DRAW RANDOM NUMBERS\nRandom.seed!(2020)\nyrand = rand(Nsim,Tsim)\n\n# SET UP GRIDS\n\n## assets\nagrid = range(0,1,length=na)\nagrid = agrid.^(1 ./ agrid_par)\nagrid = borrow_lim .+ (amax.-borrow_lim).*agrid\n\n## income: disretize normal distribution\nwidth = nlsolve(x -> discrete_normal(ny,mu_y,sd_y,x...)[1],[2.0]).zero\ntemp, ygrid, ydist = discrete_normal(ny,mu_y,sd_y,width...)\nycumdist = cumsum(ydist)\n\n# UTILITY FUNCTION\n\nu(c) = (c.^(1-risk_aver)-1)./(1-risk_aver)\nu1(c) = c.^(-risk_aver)\nu1inv(u) = u.^(-1 ./risk_aver)\n\n# INITIALIZE CONSUMPTION FUNCTION\n\nconguess = zeros(na,ny)\nfor iy = 1:ny\n    conguess[:,iy] = r.*agrid.+ygrid[iy]\nend\n\n# ITERATE ON EULER EQUATION WITH ENDOGENOUS GRID POINTS\n\ncon = copy(conguess)\n\niter = 0\ncdiff = 1000\n\nwhile iter <= max_iter && cdiff>tol_iter\n    iter = iter + 1\n    global sav = zeros(na,ny)\n    \n    conlast = copy(con)\n    \n    emuc = u1(conlast)*ydist\n    muc1 = beta.*R.*emuc\n    con1 = u1inv(muc1)\n   \n    ## loop over income\n    ass1 = zeros(na,ny)\n    for iy = 1:ny\n        \n        ass1[:,iy] = (con1 .+ agrid .-ygrid[iy])./R\n        \n        ## loop over current period ssets\n        for ia  = 1:na \n            if agrid[ia]<ass1[1,iy] # borrowing constraint binds\n                sav[ia,iy] = borrow_lim                \n            else # borrowing constraint does not bind;\n                sav[ia,iy] = lininterp1(ass1[:,iy],agrid,agrid[ia])\n            end                \n        end\n        con[:,iy] = R.*agrid .+ ygrid[iy] - sav[:,iy]\n    end\n\n    cdiff = maximum(abs.(con - conlast))\n    if Display>=1\n        println(\"Iteration no. \" * string(iter), \" max con fn diff is \" * string(cdiff))\n    end\nend\n\n# SIMULATE\nif DoSimulate==1\n\n    yindsim = zeros(Int,Nsim,Tsim)\n    asim = zeros(Nsim,Tsim)\n    \n    ## create interpolating function\n    savinterp = Array{Any}(undef,ny)\n    for iy = 1:ny\n        savinterp[iy] = interpolate((agrid,), sav[:,iy], Gridded(Linear()))\n    end\n    \n    ## loop over time periods\n    for it = 1:Tsim\n        if Display>=1 && mod(it,100)==0\n            println(\"Simulating, time period \" * string(it))\n        end\n        \n        ## income realization: note we vectorize simulations at once because\n        ## of matlab, in other languages we would loop over individuals\n        yindsim[yrand[:,it].<=ycumdist[1],it] .= 1\n        for iy = 2:ny\n            yindsim[(yrand[:,it].> ycumdist[iy-1]) .& (yrand[:,it].<=ycumdist[iy]),it] .= iy\n        end\n        \n        ## asset choice\n        if it<Tsim\n            for iy = 1:ny\n                asim[yindsim[:,it].==iy,it+1] = savinterp[iy](asim[yindsim[:,it].==iy,it])\n            end\n        end\n    end\n    \n    ## assign actual income values\n    ysim = ygrid[yindsim]\n\nend\n\n# MAKE PLOTS\nif MakePlots==1\n    \n    ## consumption policy function\n    p1 = plot(agrid, [con[:,1] con[:,ny]], xlims=(0,amax), title=\"Consumption\", color=[:blue :red], label=[\"Lowest income state\" \"Highest income state\"])\n    display(p1)\n    \n    ## savings policy function\n    p2 = plot(agrid, [sav[:,1].-agrid[:,1] sav[:,ny].-agrid[:,1]], xlims=(0,amax), title=\"Savings\", color=[:blue :red], legend=false)\n    plot!(agrid, zeros(na,1), color=:black, lw=0.5)\n    display(p2)\n    \n    ## nice zoom\n    xlimits = (0,1)\n    xlimind = trues(na)\n    if minimum(agrid) < xlimits[1]\n        xlimind = xlimind .& (agrid.>=maximum(agrid[agrid<xlimits[1]]))\n    elseif minimum(agrid) > xlimits[2]\n        xlimind .= 0\n    end\n    if maximum(agrid) > xlimits[2]\n        xlimind = xlimind .& (agrid.<=minimum(agrid[agrid.>xlimits[2]]))\n    elseif maximum(agrid) < xlimits[1]\n        xlimind .= 0\n    end\n\n    ## consumption policy function: zoomed in\n    p3 = plot(agrid[xlimind], [con[xlimind,1] con[xlimind,ny]], xlims=xlimits, title=\"Consumption: Zoomed\", marker=:circle, color=[:blue :red], linewidth=2, legend=false)\n    display(p3)\n\n    ## savings policy function: zoomed in\n    p4 = plot(agrid[xlimind], [sav[xlimind,1].-agrid[xlimind] sav[xlimind,ny].-agrid[xlimind]], xlims=xlimits, title=\"Savings: Zoomed (a'-a)\", marker=:circle, color=[:blue :red], linewidth=2, legend=false)\n    plot!(agrid, zeros(na,1), color=:black, lw=0.5)\n    display(p4)\n\n    ## income distribution\n    p5 = histogram(ysim[:,Tsim], bins=[2*ygrid[1]-ygrid[2];ygrid].+(ygrid[2]-ygrid[1])/2, title=\"Income distribution\", color=RGB(0,0.5,0.5), linecolor=:blue, legend=false)\n    display(p5)\n\n    ## asset distribution\n    p6 = histogram(asim[:,Tsim], nbins=100, title=\"Asset distribution\", color=RGB(.7,.7,.7), linecolor=:black, legend=false)\n    display(p6)\n\n    ## convergence check\n    p7 = plot(1:Tsim, mean(asim,dims=1)', title=\"Mean Asset Convergence\", xlabel=\"Time Period\", color=:black, lw=1.5, legend=false)\n    display(p7)\n\n    ## asset distribution statistics\n    aysim = asim[:,Tsim]./mean(ysim[:,Tsim])\n    println(\"Mean assets (relative to mean income): \" * string(mean(aysim)))\n    println(\"Fraction borrowing constrained: \" * string(sum(aysim.==borrow_lim)/Nsim * 100) * '%')\n    println(\"10th Percentile: \" * string(quantile(aysim,.1)))\n    println(\"50th Percentile: \" * string(quantile(aysim,.5)))\n    println(\"90th Percentile: \" * string(quantile(aysim,.9)))\n    println(\"99th Percentile: \" * string(quantile(aysim,.99)))\nend\n\n# COMPUTE MPCs\nif ComputeMPC==1\n    \n    ## theoretical mpc lower bound\n    mpclim = R*((beta*R)^(-1/risk_aver))-1\n    \n    coninterp = Array{Any}(undef,ny)\n    mpc1 = zeros(na,ny)\n    mpc2 = zeros(na,ny)\n    \n    for iy = 1:ny\n        ## create interpolating function\n        coninterp[iy] = extrapolate(interpolate((agrid,), con[:,iy], Gridded(Linear())), Line())\n\n        mpc1[:,iy] = ( coninterp[iy](agrid.+mpcamount1) - con[:,iy] ) ./ mpcamount1\n        mpc2[:,iy] = ( coninterp[iy](agrid.+mpcamount2) - con[:,iy] ) ./ mpcamount2\n        \n    end\n    \n    ## mpc functions\n    p8 = plot([agrid agrid],[mpc1[:,1] mpc2[:,1]], xlims=(0,10), linestyle=[:solid :dash], color=:blue, label=[\"Lowest income state: amount 1\" \"Lowest income state: amount 2\"])\n    plot!([agrid agrid],[mpc1[:,ny] mpc2[:,ny]], linestyle=[:solid :dash], color=:red, label=[\"Highest income state: amount 1\" \"Highest income state: amount 2\"])\n    plot!(agrid,mpclim.*ones(size(agrid)),color=:black,linestyle=:dot,linewidth=2,label=\"Theoretical MPC limit = \" * string(mpclim))\n    display(p8)\n    \n    ## mpc distribution\n    mpc1sim = zeros(Nsim,1)\n    mpc2sim = zeros(Nsim,1)\n    for iy = 1:ny\n        mpc1sim[yindsim[:,Tsim].==iy] = ( coninterp[iy](asim[yindsim[:,Tsim].==iy,Tsim].+mpcamount1) - coninterp[iy](asim[yindsim[:,Tsim].==iy,Tsim]) ) ./ mpcamount1\n        mpc2sim[yindsim[:,Tsim].==iy] = ( coninterp[iy](asim[yindsim[:,Tsim].==iy,Tsim].+mpcamount2) - coninterp[iy](asim[yindsim[:,Tsim].==iy,Tsim]) ) ./ mpcamount2\n    end\n    \n    p9 = histogram(mpc1sim,bins=0:0.02:1.5, title=\"MPC distribution\",color=RGB(.7,.7,.7),legend=false)\n    display(p9)\n        \n    # mpc distribution statistics\n    println(\"Mean MPC amount 1: \" * string(mean(mpc1sim)))\n    println(\"Mean MPC amount 2: \" * string(mean(mpc2sim)))\nend", "meta": {"hexsha": "1ec59134973156bb5cb3428e89e9a0774a9d0985", "size": 7748, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Guides/HA_codes/Julia/egp_IID.jl", "max_stars_repo_name": "pranjalrawat007/Recursive-Macro", "max_stars_repo_head_hexsha": "6caab42818e32b3a23584dca91837ad50db71616", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2022-01-25T10:14:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T06:38:17.000Z", "max_issues_repo_path": "Guides/HA_codes/Julia/egp_IID.jl", "max_issues_repo_name": "pranjalrawat007/Recursive-Macro", "max_issues_repo_head_hexsha": "6caab42818e32b3a23584dca91837ad50db71616", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Guides/HA_codes/Julia/egp_IID.jl", "max_forks_repo_name": "pranjalrawat007/Recursive-Macro", "max_forks_repo_head_hexsha": "6caab42818e32b3a23584dca91837ad50db71616", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-25T05:58:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T09:19:48.000Z", "avg_line_length": 31.1164658635, "max_line_length": 205, "alphanum_fraction": 0.6129323696, "num_tokens": 2560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7567936604499452}}
{"text": "# ---\n# title: 793. Preimage Size of Factorial Zeroes Function\n# id: problem793\n# author: Indigo\n# date: 2021-01-29\n# difficulty: Hard\n# categories: Binary Search\n# link: <https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/description/>\n# hidden: true\n# ---\n# \n# Let `f(x)` be the number of zeroes at the end of `x!`. (Recall that `x! = 1 *\n# 2 * 3 * ... * x`, and by convention, `0! = 1`.)\n# \n# For example, `f(3) = 0` because 3! = 6 has no zeroes at the end, while `f(11)\n# = 2` because 11! = 39916800 has 2 zeroes at the end. Given `K`, find how many\n# non-negative integers `x` have the property that `f(x) = K`.\n# \n#     \n#     \n#     **Example 1:**\n#     Input: K = 0\n#     Output: 5\n#     Explanation: 0!, 1!, 2!, 3!, and 4! end with K = 0 zeroes.\n#     \n#     **Example 2:**\n#     Input: K = 5\n#     Output: 0\n#     Explanation: There is no x such that x! ends in K = 5 zeroes.\n#     \n# \n# **Note:**\n# \n#   * `K` will be an integer in the range `[0, 10^9]`.\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction preimage_size_fzf(K::Int)\n    zeta(x) = x > 0 ? x ÷ 5 + zeta(x ÷ 5) : 0\n    lo, hi = K, 5 * K + 1\n    while lo < hi\n        mid = (lo + hi) ÷ 2\n        z_mid = zeta(mid)\n        if z_mid == K\n            return 5\n        elseif z_mid < K\n            lo = mid + 1\n        else\n            hi = mid\n        end\n    end\n    return 0\nend\n## @lc code=end\n", "meta": {"hexsha": "d34f91b6951e5840d7551bc13bc08a347cf934e3", "size": 1387, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/793.preimage-size-of-factorial-zeroes-function.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/793.preimage-size-of-factorial-zeroes-function.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/793.preimage-size-of-factorial-zeroes-function.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 24.3333333333, "max_line_length": 95, "alphanum_fraction": 0.5356885364, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7567936569783641}}
{"text": "function rgammanm(z, n, m=0)\n    if n==m\n        return one(z)\n    elseif n < m\n        return one(z) / rgammanm(z, m, n)\n    end\n        \n    rg = one(z)\n    for i = (n-1):-1:m\n        rg = rg * (z + i)\n    end\n\n    return rg\nend\n\nfunction rgammaxy(x, y, n)\n    rg = x/y * gamma(x)/gamma(y)\n\n    for i = 1:(n-1)\n        rg = rg * (x+i)/(y+i)\n    end\n    return rg\nend\n\n\nfunction rgammaxnym(x, n, y, m)\n\n    if x == y\n        return rgammanm(x, n, m)\n    elseif n == m\n        return rgammaxy(x, y, n)\n    elseif n < m\n        return one(x)/rgammaxnym(y, m, x, n)\n    end\n\n    rg = x/y * gamma(x)/gamma(y)\n\n    for i = (m-1):-1:1\n        rg = rg * (x+i)/(y+i)\n    end\n\n    for i = (n-1):-1:m\n        rg = rg * (x+i)\n    end\n\n    return rg\nend\n\n", "meta": {"hexsha": "ce90cf4e12e80afc4beeb8e0c7848197c5554f27", "size": 744, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gamma_aux.jl", "max_stars_repo_name": "tkf/Jacobi.jl", "max_stars_repo_head_hexsha": "8a2d769cd78cb0bb9470082d1477fad485866b40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2015-11-23T03:17:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T16:38:43.000Z", "max_issues_repo_path": "src/gamma_aux.jl", "max_issues_repo_name": "tkf/Jacobi.jl", "max_issues_repo_head_hexsha": "8a2d769cd78cb0bb9470082d1477fad485866b40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2018-08-08T20:38:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-09T15:22:25.000Z", "max_forks_repo_path": "src/gamma_aux.jl", "max_forks_repo_name": "tkf/Jacobi.jl", "max_forks_repo_head_hexsha": "8a2d769cd78cb0bb9470082d1477fad485866b40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2016-01-08T20:07:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:22:22.000Z", "avg_line_length": 15.1836734694, "max_line_length": 44, "alphanum_fraction": 0.4435483871, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.756793650330492}}
{"text": "### 5 point calculation\n\nfunction SparseArray(t::Type,f::Function,indicies::Tuple{Int,Int})\n    n,m = indicies\n\n    V = Array{t}(0)\n    I = Array{Int}(0)\n    J = Array{Int}(0)\n\n    for i in 1:n\n        for j in 1:m\n            val = f(i,j)\n            if val!=0\n                push!(I,i)\n                push!(J,j)\n                push!(V,val)\n            end\n        end\n    end\n\n    return sparse(I,J,V)\nend\n\nfunction d1(i,j,y)\n    x(p) = y(i+p) - y(i)\n\n    j==i-2 ? -((x(-1)*x(1)*x(2))/(x(-2)*(x(-2)-x(-1))*(x(-2)-x(1))*(x(-2)-x(2)))) :\n        j==i-1 ? (x(-2)*x(1)*x(2))/((x(-2)-x(-1))*x(-1)*(x(-1)-x(1))*(x(-1)-x(2))) :\n        j==i ? -(1/x(-1))-1/x(1)-1/x(2)-1/x(-2) :\n        j==i+1 ? (x(-2)*x(-1)*x(2))/((x(-2)-x(1))*x(1)*(x(1)-x(-1))*(x(1)-x(2))) :\n        j==i+2 ? (x(-2)*x(-1)*x(1))/((x(-2)-x(2))*x(2)*(x(2)-x(-1))*(x(2)-x(1))) :\n        0\nend\n\nfunction d2(i,j,y)\n    x(p) = y(i+p) - y(i)\n\n    j==i-2 ? (2*(x(1)*x(2)+x(-1)*(x(1)+x(2))))/(x(-2)*(x(-2)-x(-1))*(x(-2)-x(1))*(x(-2)-x(2))) : \n        j==i-1 ? -((2*(x(1)*x(2)+x(-2)*(x(1)+x(2))))/((x(-2)-x(-1))*x(-1)*(x(-1)-x(1))*(x(-1)-x(2)))) :\n        j==i ? (2*(x(1)*x(2)+x(-1)*(x(1)+x(2))+x(-2)*(x(-1)+x(1)+x(2))))/(x(-2)*x(-1)*x(1)*x(2)) :\n        j==i+1 ? -((2*(x(-1)*x(2)+x(-2)*(x(-1)+x(2))))/((x(-2)-x(1))*x(1)*(x(1)-x(-1))*(x(1)-x(2)))) :\n        j==i+2 ? -((2*(x(-1)*x(1)+x(-2)*(x(-1)+x(1))))/((x(-2)-x(2))*x(2)*(x(2)-x(-1))*(x(2)-x(1)))) :\n        0\nend\n\n### There is a bug if I do put d1,d2 inside a function\n\nfunction Hamiltonian(α,II,G,p0,L,nn)\n\n    sigmax = [0 1;1 0] \n    sigmay = [0 -1im;1im 0]\n    sigmaz = [1 0;0 -1]\n\n    Ix,Iy = II\n    Gx,Gy = G\n    p0x,p0y = p0\n\n    ### One could make theese nicer\n    xx(i) = i<= nn//2 ? -(L+1)^((nn/2-i+1)/(nn/2+1)) + 1 : (L+1)^((i-nn/2)/(nn/2+1)) - 1\n    x(i) = i<= nn//2 ? -(L+1)^((nn/2-i+1)/(nn/2+1)) + 1 - xx(nn/2)/2 : (L+1)^((i-nn/2)/(nn/2+1)) - 1 - xx(nn/2+1)/2\n\n    ### Laplacian operator\n\n\n    D2 = SparseArray(Float64,(i,j)->d2(i,j,x),(nn,nn))\n    Lap = Gx*kron(D2,speye(nn)) + Gy*kron(speye(nn),D2)\n\n    ### Potential\n\n    V = Float64[]\n    for i in 1:nn\n        for j in 1:nn\n            x_ = x(i)\n            y_ = x(j)\n            r = sqrt(x_^2+y_^2)\n            push!(V,-α/r)\n        end\n    end\n    V = spdiagm(V)\n\n    ### Weyl coupling\n\n    D1 = SparseArray(Float64,(i,j)->d1(i,j,x),(nn,nn))\n\n    Hm = kron(-1/2*Lap + V,eye(2)) + Ix*kron(1im*kron(D1,speye(nn)) + p0x*speye(nn^2),sigmax) + Iy*kron(1im*kron(speye(nn),D1) + p0y*speye(nn^2),sigmay)\nend\n\n", "meta": {"hexsha": "4cf4b941067baddbe2c887605c9e5376f7475f67", "size": 2481, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exciton-hamiltonian.jl", "max_stars_repo_name": "akels/WeylDisc", "max_stars_repo_head_hexsha": "7879358f2c5e77b1b81b1081d8d7e444204c7da1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exciton-hamiltonian.jl", "max_issues_repo_name": "akels/WeylDisc", "max_issues_repo_head_hexsha": "7879358f2c5e77b1b81b1081d8d7e444204c7da1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exciton-hamiltonian.jl", "max_forks_repo_name": "akels/WeylDisc", "max_forks_repo_head_hexsha": "7879358f2c5e77b1b81b1081d8d7e444204c7da1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1931818182, "max_line_length": 152, "alphanum_fraction": 0.3982265216, "num_tokens": 1192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778073288127, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.756757125358859}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.5\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ b7433dc1-846b-4173-ad51-f7598cd263a1\nusing FFTW, Plots, SampledSignals\n\n# ╔═╡ 37f59728-aeae-4b15-ba8c-a90368dfa8f0\nbegin\n    fs = 48000\n\tfreqs = Array(LinRange(0, 2*pi*200, fs))\nend\n\n# ╔═╡ cfc3b26d-d2da-4128-9ef2-a9494c4c25e5\nfunction plotfreqs(tone, title)\n\tfreqs = fft(tone) |> fftshift\n\tdomain = fftfreq(length(tone), fs) |> fftshift\n\tplot(domain, 10*log10.(abs.(freqs)/fs), title=title, xlimit=(0, 2000), ylimit=(-50, 0))\nend\n\n# ╔═╡ b70c60fd-b29a-46f3-8daf-e6d7277156ca\nfunction plotfreqs!(tone, title)\n\tfreqs = fft(tone) |> fftshift\n\tdomain = fftfreq(length(tone), fs) |> fftshift\n\tplot!(domain, 10*log10.(abs.(freqs)/fs), title=title, xlimit=(0, 2000), ylimit=(-50, 0))\nend\n\n# ╔═╡ baafd0a2-b449-11eb-0654-172c64b81fd6\nmd\"# The Harmonic Series\nPeriodic sounds have a base frequency that is the reciprocal of the period,\nand also contain components (overtones) of integer multiples of the base frequency.\nThe amplitudes of the overtones determine the timbre of the sound.\n\"\n\n# ╔═╡ 7a4f0f06-6b37-4a3c-81e4-8004462da33a\nfunction note(t)\n\tt = t/pi%2-1\n\tt = 3*sqrt(3)/2*t*(t*t-1)\nend\n\n# ╔═╡ ef073029-a63e-4625-aecf-0cde96af5686\ntone = SampleBuf(note.(freqs), fs)\n\n# ╔═╡ 9997ac3d-3cae-4bb5-8290-6ca53f431533\nplotfreqs(tone, \"Frequencies of a single 200 Hz note\")\n\n# ╔═╡ dcd90ce9-dfc0-42ed-990a-55710c32b34e\nmd\"## Intervals\nIf we play two unrelated notes at the same time we get two harmonic series\"\n\n# ╔═╡ 7f363c48-a194-4494-bb59-d5e00db70bd2\nbegin\n   ratio=1+rand()\n   plotfreqs(note.(freqs), \"First note\")\n   plotfreqs!(note.(ratio*freqs), \"Second note\")\nend\n\n# ╔═╡ 9e45b6c3-a674-4b1f-b93e-11b4a99a22da\ndissonant = SampleBuf((note.(freqs) + note.(ratio*freqs))/2, fs) \n\n# ╔═╡ 07312f0d-59d9-45ee-b60a-c6ecfc2bc0df\n# The frequencies of the combined note is the sum of each notes frequencies\nplotfreqs(dissonant, \"Two notes frequencies\")\n\n# ╔═╡ bfd2d6b6-2863-41ee-9b6a-c99ed19f8d7d\nmd\"\"\"## Octave\nIf we use frequencies in a $1:2$ ratio the harmonic series line up.\nEvery frequency is an overtone of the lower note.\nThis single harmonic series has more pronounced even overtones.\nBecause there is a single harmonic series,\nthese two notes combined are equivalent to a single note\nwith a different timbre.\nWith real world sounds different timbres, the sound source locations,\nand innacuracies of analog tuning make this equivalence inexact.\n\"\"\"\n\n# ╔═╡ 3813605c-e5c8-4bd3-9813-f553d22d47b2\nbegin\n   plotfreqs(note.(freqs), \"\")\n   plotfreqs!(note.(2*freqs), \"Octave\")\nend\n\n# ╔═╡ 6a831a92-a222-48e8-abfb-72bc9f3e0fb9\noctave = SampleBuf(note.(freqs)/2 + note.(2*freqs)/2, fs)\n\n# ╔═╡ 0b9c89bf-291e-4b93-8632-f2d5117d25a4\nmd\"If we take a tone with only odd harmonics we can construct an octave with no harmonics in common but that still sounds like a single note because of the shared harmonic series. The notes have to be scaled so that the curve of the harmonics line up to sound cohesive.\"\n\n# ╔═╡ a4882ae0-32ed-4db4-ba0c-165081128f2d\nfunction odd(t)\n\tt = t/pi%2-1\n\tt = 4*t*(abs(t)-1)\nend\n\n# ╔═╡ e3faa985-c01a-471c-ae10-0aaaee8a6b43\nodd_octave = SampleBuf(odd.(freqs) + odd.(2*freqs)/8 + odd.(4*freqs)/64, fs) \n\n# ╔═╡ 6049ed44-b19f-41a9-b017-860e80d62017\nbegin\n    plotfreqs(odd.(freqs), \"\")\n    plotfreqs!(odd.(2*freqs)/8, \"\")\n\tplotfreqs!(odd.(4*freqs)/64, \"Odd harmonics combined\")\nend\n\n# ╔═╡ ccb62252-fcf1-4fc8-b486-1df69ea0c1e3\nmd\"Any $1:n$ ratio gives a similar lining up like the octave.\nUnison $1:1$ being a special case that gives the exact original sound but louder.\nHowever, since for natural timbres the higher harmonics sound less loud,\nhigher intervals harmonics blend less and stand out more from their root note.\nIf the higher note is made softer they start to blend again.\nFor example a $1:3$ ratio, or tritive sounds like this.\"\n\n# ╔═╡ 14af9192-4b8a-49c3-9775-b4dfef343780\ntritive = SampleBuf(note.(freqs)/2 + note.(3*freqs)/2, fs)\n\n# ╔═╡ 02a98eb5-4021-4ea0-a0f8-b43c811d87b2\nblend_tritive = SampleBuf(note.(freqs)/2 + note.(3*freqs)/8, fs)\n\n# ╔═╡ 31b44424-b3f9-4ea0-8d99-28738f1fc857\nmd\"## Fifth\nThough only integer ratios will give harmonics that line up exactly\nany rational ratio will have overlap.\nA $2:3$ ratio, the simplest non-integer interval, gives a fifth.\nThe fifth is an octave below a tritave\nand so the fifth and the tritave have a similar quality.\nGoing up a fifth $(3/2)$ is the inverse of going down a fifth $(2/3)$\na characteristic shared by all intervals.\"\n\n# ╔═╡ 82582e9b-fcc0-49ae-9f3b-558e70d8f0b8\nfifth = SampleBuf(note.(freqs)/2 + note.(3/2*freqs)/2, fs)\n\n# ╔═╡ db7c4951-972b-43db-a647-6e61c8ebdf03\nbegin\n   plotfreqs(note.(freqs), \"\")\n   plotfreqs!(note.(3/2*freqs), \"Fifth\")\nend\n\n# ╔═╡ 53773643-1b58-4eee-ac11-bb30b7535fec\nmd\"Every second harmonic of the higher note lines up \nwith every third harmonic of the lower note.\nUnlike playing notes in unison or octaves,\nthe two notes have distinct pitches, \nbut unlike a random interval it's consonant.\n\"\n\n# ╔═╡ 151b3663-524e-465f-9426-3f85689e9e27\nmd\"## The Fundamental\nBecause of how the overtones line up,\nevery overtone is part of the harmonic series \nof a note that isn't being played.\nfor the fifth this is one octave below the lower note.\nThis corresponds to the period of the combined sounds,\nwhich repeats whenever the period of both notes line up.\n\nFor an interval $n:m$ that is rational and in reduced terms,\nthe fundamental is as $1$ in the ratio: $1:n:m$.\nSo the fundamental is at the inteval 1/n from the first note \nand 1/m from the second.\nThe ratio $1:n$ is a measure of consonance and is equivalent to the porportion of harmonics in the second note that are also in the first.\nAlternately the ratio $1:m$ is is another measure and is equivalent to the porportion\nof harmonics of the first note present in the second.\nNormally the lowest note of a collection\nis chosen as the root, the reference point for calculating intervals,\nbut for chord inversions using a different note is often more convenient. \nThis measure extends naturally to collections of more than 2 notes.\"\n\n# ╔═╡ 24e5caba-ce1c-4436-8ca2-647b5438658a\nbegin\n    plotfreqs(note.(freqs), \"\")\n    plotfreqs!(note.(3/2*freqs), \"\")\n    plotfreqs!(note.(freqs/2), \"Fifth with fundamental\")\nend\n\n# ╔═╡ 8adb4c0a-a29e-4cee-bb49-ee285f90ff70\nmd\"\"\"## The Common Overtone\nLike the fundamental of a collection of notes \nis the highest note that has all of the notes as harmonics,\nthe dual to the fundamental is the common overtone:\nThe lowest note that is a harmonic of all of the notes.\nThe harmonic series of this note contains the frequencies\ncommon to all the harmonic series of the other notes.\n\nFor an interval $n:m$ that is rational and in reduced terms,\nthe ratio with the dual fundamental is $n:m:nm$.\nThis is the least common multiple of $n,m,$ dual to the fundamental\nwhich is the greatest common denominator.\nThe ratios $n:nm = 1:m$, and $m:nm = 1:n$ so the\ncommon overtone gives the same measures of consonance as the\nfundamental but compared with the opposite notes.\nFor collections of more than two notes this difference leads to\ncollections with simple ratios to the fundamental being different\nfrom collections with simple ratios to their common overtone.\"\"\"\n\n# ╔═╡ 8378910d-3a2c-441e-a3b3-716d819eced9\nbegin\n    plotfreqs(note.(freqs), \"\")\n    plotfreqs!(note.(3/2*freqs), \"\")\n    plotfreqs!(note.(freqs*3), \"Fifth with common overtone\")\nend\n\n# ╔═╡ 732ab799-970e-4ae7-a81d-cda4c79873f4\nmd\" # Fourth\nThe fourth $3:4$ is an octave equivalent to the fifth.\nTaking a fifth and raising the lower note by an octave\n(or equivalently lowering the higher note by an octave)\ngives a fourth.\"\n\n# ╔═╡ df7e7e47-fe34-4250-bb0b-670fee0b56de\nfourth = SampleBuf(note.(freqs)/2 + note.(freqs*4/3)/2, fs)\n\n# ╔═╡ 518f1a8b-977b-4008-b1b7-667f0475b42c\nbegin\n    plotfreqs(note.(freqs), \"\")\n    plotfreqs!(note.(4/3*freqs), \"\")\n    plotfreqs!(note.(freqs/3), \"Fourth with fundamental\")\nend\n\n# ╔═╡ 849e0964-2c80-4fa6-9320-5fa0c595d79a\nbegin\n    plotfreqs(note.(freqs), \"\")\n    plotfreqs!(note.(4/3*freqs), \"\")\n    plotfreqs!(note.(freqs*4), \"Fourth with common overtone\")\nend\n\n# ╔═╡ 06b01905-7249-4492-a5b2-b9b43f1908c1\nmd\"Other harmonic intervals work by similar rules.\nEach has an integer ratio, where the interval going up is the dual of the interval going down. When treating octaves as equivalent intervals can be normalized by shifting them by octaves into the range $[1, 2]$. \nEach interval $m/n$ in $[1,2]$ has an inverse also in $[1,2]$: $2(n/m)$.\nAn interval and it's 'octave inverse' combine to give an octave\nand they will have similar qualities.\"\n\n# ╔═╡ Cell order:\n# ╠═b7433dc1-846b-4173-ad51-f7598cd263a1\n# ╠═37f59728-aeae-4b15-ba8c-a90368dfa8f0\n# ╠═cfc3b26d-d2da-4128-9ef2-a9494c4c25e5\n# ╠═b70c60fd-b29a-46f3-8daf-e6d7277156ca\n# ╟─baafd0a2-b449-11eb-0654-172c64b81fd6\n# ╠═7a4f0f06-6b37-4a3c-81e4-8004462da33a\n# ╠═ef073029-a63e-4625-aecf-0cde96af5686\n# ╟─9997ac3d-3cae-4bb5-8290-6ca53f431533\n# ╟─dcd90ce9-dfc0-42ed-990a-55710c32b34e\n# ╟─7f363c48-a194-4494-bb59-d5e00db70bd2\n# ╠═9e45b6c3-a674-4b1f-b93e-11b4a99a22da\n# ╟─07312f0d-59d9-45ee-b60a-c6ecfc2bc0df\n# ╟─bfd2d6b6-2863-41ee-9b6a-c99ed19f8d7d\n# ╟─3813605c-e5c8-4bd3-9813-f553d22d47b2\n# ╠═6a831a92-a222-48e8-abfb-72bc9f3e0fb9\n# ╟─0b9c89bf-291e-4b93-8632-f2d5117d25a4\n# ╠═a4882ae0-32ed-4db4-ba0c-165081128f2d\n# ╠═e3faa985-c01a-471c-ae10-0aaaee8a6b43\n# ╠═6049ed44-b19f-41a9-b017-860e80d62017\n# ╟─ccb62252-fcf1-4fc8-b486-1df69ea0c1e3\n# ╠═14af9192-4b8a-49c3-9775-b4dfef343780\n# ╠═02a98eb5-4021-4ea0-a0f8-b43c811d87b2\n# ╟─31b44424-b3f9-4ea0-8d99-28738f1fc857\n# ╠═82582e9b-fcc0-49ae-9f3b-558e70d8f0b8\n# ╟─db7c4951-972b-43db-a647-6e61c8ebdf03\n# ╟─53773643-1b58-4eee-ac11-bb30b7535fec\n# ╟─151b3663-524e-465f-9426-3f85689e9e27\n# ╟─24e5caba-ce1c-4436-8ca2-647b5438658a\n# ╟─8adb4c0a-a29e-4cee-bb49-ee285f90ff70\n# ╟─8378910d-3a2c-441e-a3b3-716d819eced9\n# ╟─732ab799-970e-4ae7-a81d-cda4c79873f4\n# ╠═df7e7e47-fe34-4250-bb0b-670fee0b56de\n# ╟─518f1a8b-977b-4008-b1b7-667f0475b42c\n# ╠═849e0964-2c80-4fa6-9320-5fa0c595d79a\n# ╟─06b01905-7249-4492-a5b2-b9b43f1908c1\n", "meta": {"hexsha": "cb2bea33a9e127aed21ca5e38d2664540fa04208", "size": 10042, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Harmonic.jl", "max_stars_repo_name": "jnha/music", "max_stars_repo_head_hexsha": "b46dadd8b1e972a6d3441c09d1f1bba8b786087a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Harmonic.jl", "max_issues_repo_name": "jnha/music", "max_issues_repo_head_hexsha": "b46dadd8b1e972a6d3441c09d1f1bba8b786087a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Harmonic.jl", "max_forks_repo_name": "jnha/music", "max_forks_repo_head_hexsha": "b46dadd8b1e972a6d3441c09d1f1bba8b786087a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1925925926, "max_line_length": 270, "alphanum_fraction": 0.744672376, "num_tokens": 3973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7567244433379657}}
{"text": "include(\"header.jl\")\n\n#=\n# Example calculation in a pipe system\nIn this notebook we will see an example of how to solve a problem in a pipe\nsystem, using the 1-d steady-flow energy equation.\n\nIn our calculations, we will use the units that we discussed in notebook 1.0\nin order to take advantage of the useful tools that come with them.\n=#\n\n# ### Set up the module\nusing MAE103\n\n#=\n## Example: Find the flow rate\nIn this example (Example 8.10 in the textbook), we are to determine the change of\nflow rate that occurs after we modify a design for a fume hood. The fume hood\ninvolves a fan that pumps air and noxious gas out of an enclosed region,\nthrough a duct, and out to the atmosphere where it can safely mix with the\nambient air. The existing design involves a fan with a short duct of diameter\n8 inches, and the losses correpond to a loss coefficient of $K_L = 5$. This\nleads to a flow rate of $\\dot{Q}_0 = 9$ ft$^3$/s, which is safely within\nthe regulated range of 6 to 12 ft$^3$/s.\n\nThe new design involves a long 100 ft pipe of galvanized iron (leading to\nmajor loss from viscosity) and a new total loss coefficient of $K_L = 10$.\nWe wish to see if the new design's volume flow rate falls within the\nregulated range. We will assume that the fan's head does not change in\nthe redesign.\n=#\n#-\n#=\nFirst, let's put in the parameters. We treat the gas as air, since any noxious\ngas species are assumed to be at low concentrations.\n\nGalvanized iron has a typical roughness of 0.0005 ft.\n=#\nQ0 = VolumeFlowRate(9u\"ft^3/s\")\nKL0 = 5\nD = Diameter(8u\"inch\")\nμ = Viscosity(Air)\nρ = Density(Air)\nϵ = Height(0.0005u\"ft\")\ng = Gravity()\n#=\nNow let's calculate the flow velocity in the original design\n=#\nA = Area(π/4*D^2)\nV0 = Velocity(Q0/A)\nvalue(V0,u\"ft/s\")\n\n#=\nAnd now, we can calculate the fan head $h_p$, since this is equal\nto the kinetic energy of the exiting flow plus the head loss. (Pressures\nare equal and ambient in the fume hood and at the exit, and elevation\nchanges are negligible.\n\n$$h_p = \\dfrac{V^2}{2g} + K_L\\dfrac{V^2}{2g}$$\n=#\nhp = Head((KL0+1)*V0^2/(2*g))\nvalue(hp,u\"ft\")\n\n#=\nNow we will analyze the modified system. We add 100 ft of duct after the\nfan and increase the loss coefficient to 10:\n=#\nL = Length(100u\"ft\")\nKL = 10.0\n\n#=\nThe energy equation now becomes\n\n$$h_p = \\dfrac{V^2}{2g} + K_L\\dfrac{V^2}{2g} + \\dfrac{fL}{D}\\dfrac{V^2}{2g}$$\n\nThe unknown in this equation is $V$, but $f$ (the friction factor) is also\nunknown. Let's solve for $V$, pretending that we know $f$:\n\n$$V = \\left(\\dfrac{2gh_p}{1 + K_L + fL/D}\\right)^{1/2}$$\n\nTo get $f$, we need Reynolds number and roughness coefficient.\nAnd to get Reynolds number, we need $V$. So, we clearly must iterate.\n\nOur approach will be\n0. Guess a value for $f$, based on $\\epsilon/D$ and a Reynolds number close to $\\infty$.\n1. Calculate $V$ from the energy equation with the current guess of $f$.\n2. Calculate $Re_D = \\rho V D/\\mu$ from $V$.\n3. Calculate a new value of $f$. Check if it is equal to the guess used in 1. If\nyes, we stop. If not, then return to step 1 with this $f$ as our new guess.\n\nLet's prepare ourselves for this iteration by defining some equations. The\nroughness coefficient:\n=#\neD = RoughnessCoefficient(ϵ/D)\n\n# Here is $V$ as a function of $f$ (and the other quantities, which don't change).\nVfromf(f) = Velocity(sqrt(2*g*hp/(1+KL+f*L/D)))\n\n# Here is $Re_D$ as a function of $V$ (and other quantities that don't change)\nReD(V) = ReynoldsNumber(ρ*V*D/μ)\n\n#=\nTo do the iteration, we will define a simple function that takes in\nan initial guess for $f$, iterates using the procedure above, and then returns\nthe correct value.\n\nIn the function, we create a quantity `f_old`, which simply hold our old guess\nfor $f$, and `f` will hold our next guess. We will compare these in each iteration,\nchecking whether they are nearlyequal. We'll say they're equal if they are closer\nthan $10^{-8}$. To ensure that the test fails at first, we initialize `f_old` to\ninfinity. This will force it to proceed into the iteration loop:\n=#\nfunction iterate_f(f0::FrictionFactor)\n  f = f0\n  f_old = Inf\n  while abs(f - f_old) > 1e-8\n      f_old = f\n      f = FrictionFactor(ReD(Vfromf(f_old)),eD)\n  end\n  return f\nend\n\n\n#=\nNow, to get $f$ from $Re_D$ and $\\epsilon/D$, we use the function\n`FrictionFactor(Re,eD)`, which solves the Colebrook equation for $f$.\nHere, we use it to find our initial guess for $f$, treating $Re_D$ as very large.\n=#\nf0 = FrictionFactor(ReynoldsNumber(1e10),eD)\n\nf = iterate_f(f0)\n\n# We converged on the final $f$ value! The actual velocity is thus\nV = Vfromf(f)\nvalue(Vfromf(f),u\"ft/s\")\n\n# And the final Reynolds number is\nReD(V)\n\n# And finally, the volume flow rate after making the change to the setup is\nQ = VolumeFlowRate(V*A)\nvalue(Q,u\"ft^3/s\")\n\n#=\nSo this shows that the flow rate is too small to meet the specifications.\nWe would need to decrease the length, $L$, or reduce the losses in $K_L$\nto make it meet the specifications.\n=#\n", "meta": {"hexsha": "ccea01d975f34b2a4829189d95f050a23db6dc6e", "size": 4940, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/literate/5.0-EnergyEquationExample.jl", "max_stars_repo_name": "jdeldre/MAE103", "max_stars_repo_head_hexsha": "1417d573636e7e88fc0dce795073b8f0a82634f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/literate/5.0-EnergyEquationExample.jl", "max_issues_repo_name": "jdeldre/MAE103", "max_issues_repo_head_hexsha": "1417d573636e7e88fc0dce795073b8f0a82634f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-03T22:18:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-03T22:18:15.000Z", "max_forks_repo_path": "test/literate/5.0-EnergyEquationExample.jl", "max_forks_repo_name": "jdeldre/MAE103", "max_forks_repo_head_hexsha": "1417d573636e7e88fc0dce795073b8f0a82634f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1543624161, "max_line_length": 88, "alphanum_fraction": 0.7174089069, "num_tokens": 1476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7567244365710218}}
{"text": "\r\n\r\n@everywhere function SimulateBattle(ArmiesAttacker::Int64, ArmiesDefender::Int64)\r\n  while ArmiesDefender > 0 && ArmiesAttacker > 0\r\n    DiceAttacker = rand(1:6, min(3, ArmiesAttacker))\r\n    DiceDefender = rand(1:6, min(2, ArmiesDefender))\r\n    sort!(DiceAttacker, rev=true)\r\n    sort!(DiceDefender, rev=true)\r\n    if DiceAttacker[1] > DiceDefender[1]\r\n      ArmiesDefender -= 1\r\n    else\r\n    ArmiesAttacker -= 1\r\n    end\r\n    if ArmiesDefender >1 && ArmiesAttacker>1\r\n      if DiceAttacker[2] > DiceDefender[2]\r\n        ArmiesDefender -=1\r\n      else ArmiesAttacker -=1\r\n    end\r\n  end\r\n  end\r\n  (ArmiesAttacker, ArmiesDefender)\r\nend\r\n\r\n\r\n@everywhere function SimulateBattleFast(ArmiesAttacker::Int64, ArmiesDefender::Int64)\r\n  while ArmiesDefender > 2 && ArmiesAttacker > 3\r\n    a = rand()\r\n    if a <= 0.372\r\n      ArmiesDefender -= 2\r\n    elseif a > 0.372 && a <= 0.707\r\n      ArmiesDefender -= 1\r\n      ArmiesAttacker -= 1\r\n    else\r\n      ArmiesAttacker -= 2\r\n    end\r\n  end\r\n\r\n  while ArmiesDefender > 0 && ArmiesAttacker > 0\r\n    DiceAttacker = rand(1:6, min(3, ArmiesAttacker))\r\n    DiceDefender = rand(1:6, min(2, ArmiesDefender))\r\n    sort!(DiceAttacker, rev=true)\r\n    sort!(DiceDefender, rev=true)\r\n    if DiceAttacker[1] > DiceDefender[1]\r\n      ArmiesDefender -= 1\r\n    else\r\n      ArmiesAttacker -= 1\r\n    end\r\n    if ArmiesDefender > 1 && ArmiesAttacker > 1\r\n      if DiceAttacker[2] > DiceDefender[2]\r\n        ArmiesDefender -= 1\r\n      else ArmiesAttacker -= 1\r\n    end\r\n  end\r\n  end\r\n  (ArmiesAttacker, ArmiesDefender)\r\nend\r\n\r\nfunction SimulateRiskio(ArmiesAttacker, ArmiesDefender, NSim::Int64)\r\n  result = Array{Float32}(length(ArmiesAttacker)\r\n                          , length(ArmiesDefender))\r\n    for (k, AA) in enumerate(ArmiesAttacker)\r\n      for (j, AD) in enumerate(ArmiesDefender)\r\n       battles = SharedArray(Int64,NSim,3)\r\n        @sync @parallel for i in 1:NSim\r\n           b = SimulateBattleFast(AA,AD)\r\n           battles[i,1] = b[1]\r\n           battles[i,2] = b[2]\r\n        end\r\n      AttackerWins = battles[:,1] .> battles[:,2]\r\n      result[k,j] = mean(AttackerWins)\r\n    end\r\n  end\r\n  result\r\nend\r\n\r\n\r\n\r\n\r\nd = @time SimulateRiskio(1:30,1:30,10000)\r\n\r\n\r\nPkg.add(\"Gadfly\")\r\n\r\nusing Gadfly\r\nusing Colors\r\nusing Compose\r\n\r\ndraw(SVG(\"d:/probs.svg\",15cm, 15cm),spy(d))\r\n\r\nspy(d)\r\n", "meta": {"hexsha": "4ae95c1692d95a475ab6b26caacfeda68dbb3ca2", "size": 2321, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Risiko Simu.jl", "max_stars_repo_name": "wolfganglederer/risiko", "max_stars_repo_head_hexsha": "b5d647e951de46b0115ea5429df2c65c3a0f4b23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Risiko Simu.jl", "max_issues_repo_name": "wolfganglederer/risiko", "max_issues_repo_head_hexsha": "b5d647e951de46b0115ea5429df2c65c3a0f4b23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Risiko Simu.jl", "max_forks_repo_name": "wolfganglederer/risiko", "max_forks_repo_head_hexsha": "b5d647e951de46b0115ea5429df2c65c3a0f4b23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5054945055, "max_line_length": 86, "alphanum_fraction": 0.6178371392, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7567244334415639}}
{"text": "# used in shortest path calculations\n# has_distances{T}(distmx::AEdgeMap{T}) =\n#     issparse(distmx)? (nnz(distmx) > 0) : !isempty(distmx)\n\n\"\"\"\n    eccentricity(g, v, distmx=weights(g))\n\nCalculates the eccentricity[ies] of a vertex `v`,\nAn optional matrix of edge distances may be supplied.\n\nThe eccentricity of a vertex is the maximum shortest-path distance between it\nand all other vertices in the graph.\n\"\"\"\nfunction eccentricity(\n    g::AGraphOrDiGraph,\n    v::Int,\n    distmx::AEdgeMap=weights(g)\n)\n    e = maximum(dijkstra_shortest_paths(g,v,distmx).dists)\n    e == typemax(valtype(distmx)) && error(\"Infinite path length detected\")\n\n    return e\nend\n\n\"\"\"\n\n    eccentricities(g, distmx=weights(g))\n    eccentricities(g, vs, distmx=weights(g))\n\nReturns `[eccentricity(g,v,distmx) for v in vs]`. When `vs` it is not supplied,\nconsiders all node in the graph.\n\nSee also [`eccentricity`](@ref).\n\nNote: the eccentricity vector returned by `eccentricity` may be eventually used as input\nin some eccentricity related measures ([`periphery`](@ref), [`center`](@ref)).\n\"\"\"\nfunction eccentricities(\n    g::AGraphOrDiGraph,\n    vs::AbstractVector,\n    distmx::AEdgeMap=weights(g)\n)\n    [eccentricity(g,v,distmx) for v in vs]\nend\n\neccentricities(\n    g::AGraphOrDiGraph,\n    distmx::AEdgeMap=weights(g)\n) = eccentricities(g, 1:nv(g), distmx)\n\n\"\"\"\n    diameter(g, distmx=weights(g))\n\nReturns the maximum distance between any two vertices in `g`.\nDistances  between two adjacent nodes are given by `distmx`.\n\nSee also [`eccentricities`](@ref), [`radius`](@ref).\n\"\"\"\ndiameter(g::AGraphOrDiGraph, distmx::AEdgeMap = weights(g)) =\n    maximum(eccentricities(g, distmx))\n\n\n\"\"\"\n    radius(g, distmx=weights(g))\n\nReturns the minimum distance between any two vertices in `g`.\nDistances  between two adjacent nodes are given by `distmx`.\n\nSee [`eccentricities`](@ref), [`diameter`](@ref).\n\"\"\"\nradius(g::AGraphOrDiGraph, distmx=weights(g)) =\n    minimum(eccentricities(g, distmx))\n\n\"\"\"\n    periphery(g, distmx=weights(g))\n    periphery(all_ecc)\n\nReturns the set of all vertices whose eccentricity is equal to the graph's\ndiameter (that is, the set of vertices with the largest eccentricity).\n\nEventually a vector `all_ecc` contain the eccentricity of each node\ncan be passed as argument.\n\nSee [`eccentricities`](@ref).\n\"\"\"\nfunction periphery(all_e::Vector)\n    diam = maximum(all_e)\n    return filter((x)->all_e[x] == diam, 1:length(all_e))\nend\n\nperiphery(g::AGraphOrDiGraph, distmx::AEdgeMap=weights(g)) =\n    periphery(eccentricities(g, distmx))\n\n\"\"\"\n    center(g, distmx=weights(g))\n    center(all_ecc)\n\nReturns the set of all vertices whose eccentricity is equal to the graph's\nradius (that is, the set of vertices with the smallest eccentricity).\n\nEventually a vector `all_ecc` contain the eccentricity of each node\ncan be passed as argument.\n\nSee [`eccentricities`](@ref).\n\"\"\"\nfunction center(all_e::Vector)\n    rad = minimum(all_e)\n    return filter((x)->all_e[x] == rad, 1:length(all_e))\nend\n\ncenter(g::AGraphOrDiGraph, distmx::AEdgeMap = weights(g)) =\n    center(eccentricities(g, distmx))\n", "meta": {"hexsha": "1bc862134476d52d64205110f1d830558795290f", "size": 3083, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances/distance.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Erdos.jl-90d7349d-81aa-5495-813a-883243abfe31", "max_stars_repo_head_hexsha": "2eb248772a05eac35823a07373dd5644913c6dbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2017-02-24T15:54:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T19:59:23.000Z", "max_issues_repo_path": "src/distances/distance.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Erdos.jl-90d7349d-81aa-5495-813a-883243abfe31", "max_issues_repo_head_hexsha": "2eb248772a05eac35823a07373dd5644913c6dbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 76, "max_issues_repo_issues_event_min_datetime": "2017-02-23T09:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T09:10:31.000Z", "max_forks_repo_path": "src/distances/distance.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Erdos.jl-90d7349d-81aa-5495-813a-883243abfe31", "max_forks_repo_head_hexsha": "2eb248772a05eac35823a07373dd5644913c6dbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-03-04T21:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:54:44.000Z", "avg_line_length": 27.2831858407, "max_line_length": 88, "alphanum_fraction": 0.7106714239, "num_tokens": 842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7567244316228211}}
{"text": "export ThresholdGraph, RandomThresholdGraph, CreationSequence, ThresholdRepresentation\n\n\n\n\"\"\"\n`ThresholdGraph(w)` creates a threshold graph using weights from the\nvector `w`.\n\n`ThresholdGraph(dw)` creates a threshold graph from a dictionary\nmapping vertices to weights.\n\"\"\"\nfunction ThresholdGraph(w::Array{T,1}) where {T<:Real}\n    n = length(w)\n    f = Dict{Int,T}()\n    for k = 1:n\n        f[k] = w[k]\n    end\n    return ThresholdGraph(f)\nend\n\nfunction ThresholdGraph(dw::Dict{S,T}) where {S,T<:Real}\n    G = SimpleGraph{S}()\n    vtcs = collect(keys(dw))\n    n = length(vtcs)\n\n    for v in vtcs\n        add!(G, v)\n    end\n\n    for i = 1:n-1\n        u = vtcs[i]\n        wt_u = dw[u]\n        for j = i+1:n\n            v = vtcs[j]\n            wt_v = dw[v]\n            if wt_u + wt_v >= 1\n                add!(G, u, v)\n            end\n        end\n    end\n    cache_save(G, :ThresholdRepresentation, dw)\n    cache_save(G, :name, \"Threshold graph\")\n    return G\nend\n\n\"\"\"\n`RandomThresholdGraph(n)` creates a random threshold graph with `n`\nvertices.\n\"\"\"\nfunction RandomThresholdGraph(n::Int)\n    w = rand(n)\n    return ThresholdGraph(w)\nend\n\n\n# The following code contributed by Tara Abrishami\n\n\"\"\"\n`CreationSequence(G)` creates a creation sequence for a threshold\ngraph `G`. This returns a pair `(seq, vtx_list)` where `seq` is the\ncreation sequence and `vtx_list` specifies the order in which the\nvertices are added when creating `G`. If `G` is not a threshold\ngraph, then an error is raised.\n\"\"\"\nfunction CreationSequence(G1::SimpleGraph)\n    A = Int[]\n    T = eltype(G1)\n    V = T[]\n    G = deepcopy(G1)\n    while length(vlist(G)) != 0\n        r = false\n        for v in vlist(G)\n            if deg(G, v) == 0\n                delete!(G, v)\n                r = true\n                unshift!(A, 0)\n                unshift!(V, v)\n                break\n            end\n            if deg(G, v) == NV(G) - 1\n                delete!(G, v)\n                r = true\n                unshift!(A, 1)\n                unshift!(V, v)\n                break\n            end\n        end\n        if !r\n            error(\"This graph is not a threshold graph\")\n        end\n    end\n    return A, V\nend\n\n\"\"\"\n`ThresholdRepresentation(G)` returns a threshold representation of\n`G`. This returns a dictionary mapping vertices of `G` to `Rational`\nweights. An error is raised if `G` is not a threshold graph.\n\"\"\"\nfunction ThresholdRepresentation(G::SimpleGraph)\n    if cache_check(G, :ThresholdRepresentation)\n        return cache_recall(G, :ThresholdRepresentation)\n    end\n    A, V = CreationSequence(G)\n\n    prev::Int = 0\n    prevVal::Rational = 1 // 3\n    T = eltype(G)\n    D = Dict{T,Rational}()\n    D[V[1]] = prevVal\n    small::Rational = prevVal\n    large::Rational = prevVal\n    for i = 2:length(A)\n        if A[i] == prev\n            D[V[i]] = prevVal\n        elseif A[i] == 0\n            D[V[i]] = (1 - large) / 2\n            prevVal = (1 - large) / 2\n            if (1 - large) / 2 < small\n                small = (1 - large) / 2\n            end\n            if (1 - large) / 2 > large\n                large = (1 - large) / 2\n            end\n        elseif A[i] == 1\n            D[V[i]] = 1 - small\n            prevVal = 1 - small\n            if 1 - small > large\n                large = 1 - small\n            end\n            if 1 - small < large\n                small = 1 - large\n            end\n        end\n        prev = i\n    end\n    cache_save(G, :ThresholdRepresentation, D)\n    return D\nend\n", "meta": {"hexsha": "78aeb25f79292381dc2355e496db99b95f06b5db", "size": 3482, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ThresholdGraphs.jl", "max_stars_repo_name": "scheinerman/SimpleGraphRepresentations.jl", "max_stars_repo_head_hexsha": "815367c0a545ef60e49f8b26944770f50b42a407", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ThresholdGraphs.jl", "max_issues_repo_name": "scheinerman/SimpleGraphRepresentations.jl", "max_issues_repo_head_hexsha": "815367c0a545ef60e49f8b26944770f50b42a407", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ThresholdGraphs.jl", "max_forks_repo_name": "scheinerman/SimpleGraphRepresentations.jl", "max_forks_repo_head_hexsha": "815367c0a545ef60e49f8b26944770f50b42a407", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:13:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T01:13:04.000Z", "avg_line_length": 24.8714285714, "max_line_length": 86, "alphanum_fraction": 0.5324526134, "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.756724431622821}}
{"text": "#=\nChallenge #252 [Easy] Sailors and monkeys and coconuts, oh my!\n\nDescription\n\nA number of sailors (let's call it N) are stranded on an island with a huge pile\nof coconuts and a monkey. During the night, each sailor (in turn) does the following\nwithout the others knowing:\n    1. He takes one N'th (e.g. if N=5, one fifth) of the coconuts in the pile and\n    hides them\n    2. The division leaves one coconut left over, which is given to the monkey.\nIn the morning, they split the remaining coconuts between them. This time the\nsplit is even. There's nothing left over for the monkey.\nYour task: Given the number of sailors (N), how many coconuts were in the pile\nto begin with (lowest possible number)?\n\nFormal inputs/outputs\n\nInput\n\nThe input is a single number: N, the number of sailors. This number is a whole\nnumber that is greater than or equal to 2.\n\nOutput\n\nThe output is a single number: the number of coconuts in the original pile.\nSample input/output\n\nInput:\n5\nOutput:\n3121\nSample solution for 5 sailors: https://jsfiddle.net/722gjnze/8/\n\nCredit\n\nThis challenge was originally suggested on /r/dailyprogrammer_ideas by\n/u/TinyLebowski (prior to some changes by me). Have a cool challenge idea?\nHop on over to /r/dailyprogrammer_ideas to tell everyone about it!\n\n( source: https://redd.it/43ouxy )\n=#\n\nhow_many_coconut( N::Integer=2 ) = ( N^N - ( N - 1 ) )\n\nfunction main( )\n    local N::Integer = parse( Int, chomp( readline( STDIN ) ) )\n\n    N >= 2 ? println( how_many_coconut( N ) ) : error( \"Please, type a valid number: greater or equal to 2\" )\nend\n\nmain( )\n", "meta": {"hexsha": "94c61dde3b687bb2e6a5b786c7275965258389aa", "size": 1573, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Easy/sailors.jl", "max_stars_repo_name": "farmfirst/dailyprogrammer", "max_stars_repo_head_hexsha": "27d51bb380a7dc39644aa1e4da44e39cca38beff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Easy/sailors.jl", "max_issues_repo_name": "farmfirst/dailyprogrammer", "max_issues_repo_head_hexsha": "27d51bb380a7dc39644aa1e4da44e39cca38beff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Easy/sailors.jl", "max_forks_repo_name": "farmfirst/dailyprogrammer", "max_forks_repo_head_hexsha": "27d51bb380a7dc39644aa1e4da44e39cca38beff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.679245283, "max_line_length": 109, "alphanum_fraction": 0.7323585505, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7567244150864815}}
{"text": "\"\"\"\n    earthmover(a, b, C)\n\nCompute the optimal transport map\n```math\nargmin_{P ∈ U(a, b)} ⟨C, P⟩\n```\nand the dual potentials using the network simplex method.\n\n# References\n\nPeyré, G., & Cuturi, M.. (2018). Computational Optimal Transport. [arXiv:1803.00567](https://arxiv.org/abs/1803.00567).\n\"\"\"\nfunction earthmover(\n    a::AbstractVector{<:Real},\n    b::AbstractVector{<:Real},\n    C::AbstractMatrix{<:Real}\n)\n    P = SparseArrays.spzeros(Base.promote_eltype(a, b), length(a), length(b))\n    earthmover!(P, a, b, C)\nend\n\nfunction earthmover!(P, a, b, C)\n    # find a feasible initial transport map\n    initialmap!(P, a, b)\n\n    # construct the initial graph\n    n = length(a)\n    m = length(b)\n    graph = LightGraphs.SimpleGraph(n + m)\n    for ij in findall(!iszero, P)\n        i, j = Tuple(ij)\n\n        # convert to vertices\n        u = i\n        v = j + n\n\n        # add new edge\n        LightGraphs.add_edge!(graph, u, v)\n    end\n\n    # compute the dual potentials\n    T = Base.promote_eltype(P, C)\n    f = Vector{T}(undef, n)\n    g = Vector{T}(undef, m)\n    dualpotentials!!(f, g, C, graph)\n\n    while true\n        # check if the dual potentials are feasible\n        res = findfirstinfeasible(f, g, C)\n        res === nothing && break\n\n        # obtain vertices of the edge that will be added\n        i, j = res\n        u = i\n        v = j + n\n\n        # check if these vertices are already connected\n        path = LightGraphs.a_star(graph, v, u)\n\n        if !isempty(path)\n            # determine the largest possible increase and which edge to remove\n            e = path[1]\n            θmin = P[LightGraphs.dst(e), LightGraphs.src(e) - n]\n            kmin = 1\n            for k in 3:2:length(path)\n                e = path[k]\n                θ = P[LightGraphs.dst(e), LightGraphs.src(e) - n]\n                if θ < θmin\n                    θmin = θ\n                    kmin = k\n                end\n            end\n\n            # update the transport map\n            P[i, j] += θmin\n            for k in 1:length(path)\n                e = path[k]\n                if isodd(k)\n                    # try to avoid floating point errors\n                    if k == kmin\n                        P[LightGraphs.dst(e), LightGraphs.src(e) - n] = 0\n                    else\n                        P[LightGraphs.dst(e), LightGraphs.src(e) - n] -= θmin\n                    end\n                else\n                    P[LightGraphs.src(e), LightGraphs.dst(e) - n] += θmin\n                end\n            end\n\n            # remove the replaced edge\n            LightGraphs.rem_edge!(graph, path[kmin])\n        end\n\n        # add the new edge\n        LightGraphs.add_edge!(graph, u, v)\n\n        # recompute the dual potentials\n        dualpotentials!!(f, g, C, graph)\n    end\n\n    P, f, g\nend\n\nfunction findfirstinfeasible(f, g, C)\n    n = length(f)\n    m = length(g)\n\n    @inbounds for j in 1:m, i in 1:n\n        f[i] + g[j] > C[i, j] && return (i, j)\n    end\n\n    nothing\nend\n\nfunction dualpotentials!!(f, g, C, graph)\n    n = length(f)\n    m = length(g)\n    \n    visited = falses(n+m)\n    S = Int[]\n    @inbounds for v in LightGraphs.vertices(graph)\n        # do not revisit processed vertices\n        visited[v] && continue\n\n        # handle first vertex in a new tree\n        if v > n\n            g[v - n] = 0\n        else\n            f[v] = 0\n        end\n        push!(S, v)\n        visited[v] = true\n\n        # handle all other vertices in this tree by DFS\n        while !isempty(S)\n            s = S[end]\n            u = 0\n            for t in LightGraphs.outneighbors(graph, s)\n                if !visited[t]\n                    u = t\n                    if t > n\n                        g[t - n] = C[s, t - n] - f[s]\n                    else\n                        f[t] = C[t, s - n] - g[s - n]\n                    end\n                    break\n                end\n            end\n            if u == 0\n                pop!(S)\n            else\n                visited[u] = true\n                push!(S, u)\n            end\n        end\n    end\n\n    nothing\nend\n\nfunction initialmap!(P, a, b)\n    n = length(a)\n    m = length(b)\n    size(P) == (n, m) ||\n        throw(DimensionMismatch(\"dimensions of histograms and transport map do not match\"))\n\n    # initialize row and column sums\n    T = eltype(P)\n    r = T(a[1])\n    c = T(b[1])\n\n    i = j = 1\n    while i ≤ n && j ≤ m\n        # update initial map\n        t = min(r, c)\n        P[i, j] = t\n\n        # update r and c\n        r -= t\n        c -= t\n\n        if iszero(r)\n            i += 1\n            if i ≤ n\n                r = T(a[i])\n            end\n        end\n\n        if iszero(c)\n            j += 1\n            if j ≤ m\n                c = T(b[j])\n            end\n        end\n    end\n\n    P\nend", "meta": {"hexsha": "d022d57875e5e05cf488dd73d4d2c53336595319", "size": 4763, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/earthmover.jl", "max_stars_repo_name": "devmotion/OptimalTransport.jl", "max_stars_repo_head_hexsha": "0e4fa870607ac974b8db57952b30bee1b8dd45be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-23T01:20:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T01:20:38.000Z", "max_issues_repo_path": "src/earthmover.jl", "max_issues_repo_name": "devmotion/OptimalTransport.jl", "max_issues_repo_head_hexsha": "0e4fa870607ac974b8db57952b30bee1b8dd45be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-01T05:27:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-01T17:25:04.000Z", "max_forks_repo_path": "src/earthmover.jl", "max_forks_repo_name": "devmotion/OptimalTransport.jl", "max_forks_repo_head_hexsha": "0e4fa870607ac974b8db57952b30bee1b8dd45be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9346733668, "max_line_length": 119, "alphanum_fraction": 0.4612639093, "num_tokens": 1328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361157495521, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.7566985102919974}}
{"text": "function Newton_Spectral(nlp:: AbstractNLPModel,\n                         x₀ :: AbstractVector;\n                         τ₀ :: Float64 = 0.0005,\n                         ϵ  :: Float64 = 1e-6,\n                         maxiter :: Int = 200)\n\n    x = copy(x₀)\n    iter = 0\n    f, g = obj(nlp,x), grad(nlp, x)\n\n    while (norm(g, Inf) > ϵ) && (iter <= maxiter)\n        H    = Matrix(Symmetric(hess(nlp, x),:L))\n        Δ, O = eigen(H)\n\n        # Boost negative values of Δ to 1e-8\n        D = Δ .+ max.((1e-8 .- Δ), 0.0)\n\n        d = - O*diagm(1.0 ./ D)*O'*g\n\n        # Simple Armijo backtracking\n        hp0 = g'*d\n        t   = 1.0\n        ft  = obj(nlp, x + t*d)\n        while ft > ( f + τ₀*t*hp0)\n            t /= 2.0\n            ft = obj(nlp, x + t*d)\n        end\n        x    += t*d\n        f, g  = ft, grad(nlp, x)\n        iter += 1\n    end\n    if iter > maxiter @warn \"Iteration limit\" end\n\n    return x, f, norm(g), iter\nend\n", "meta": {"hexsha": "0b3a7cf127db95aeac8ce2d637ba0fde91850340", "size": 930, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "paper/code/NewtonSolver.jl", "max_stars_repo_name": "vepiteski/Stopping.jl", "max_stars_repo_head_hexsha": "404b31ff5eb951db1773a4e22b6d4539e99ddd08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-01-30T19:02:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T06:33:24.000Z", "max_issues_repo_path": "paper/code/NewtonSolver.jl", "max_issues_repo_name": "vepiteski/Stopping.jl", "max_issues_repo_head_hexsha": "404b31ff5eb951db1773a4e22b6d4539e99ddd08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31, "max_issues_repo_issues_event_min_datetime": "2017-05-18T13:41:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T18:07:07.000Z", "max_forks_repo_path": "paper/code/NewtonSolver.jl", "max_forks_repo_name": "vepiteski/Stopping.jl", "max_forks_repo_head_hexsha": "404b31ff5eb951db1773a4e22b6d4539e99ddd08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-05-18T13:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T00:06:25.000Z", "avg_line_length": 25.8333333333, "max_line_length": 49, "alphanum_fraction": 0.4129032258, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556619, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7566497156683367}}
{"text": "\n\nfunction bisection(f, xmin::T, xmax::T; config = Options()) where {T <: Number}\n    local x₀ = xmin\n    local x₁ = xmax\n    local x  = zero(T)\n\n    x₀ < x₁ || begin x₀, x₁ = x₁, x₀ end\n\n    local y₀ = f(x₀)\n    local y₁ = f(x₁)\n    local y  = zero(y₀)\n\n    # y₀ * y₁ ≤ 0 || error(\"Either no or multiple real roots in [xmin,xmax]\")\n\n    for j in 1:config.max_iterations\n        x = (x₀ + x₁) / 2\n        y = f(x)\n\n        # println(\"j = \", j, \" , x₀ = \", x₀, \" , x₁ = \", x₁)\n\n        !isapprox(y, zero(y), atol=config.f_abstol) || break\n\n        if y₀ * y > 0\n            x₀ = x  # Root is in the right half of [x₀,x₁].\n            y₀ = y\n        else\n            x₁ = x  # Root is in the left half of [x₀,x₁].\n            y₁ = y\n        end\n\n        !isapprox(x₁ - x₀, zero(x), atol=config.x_abstol) || break\n    end\n\n    # println(\"α=\", x, \", f(α)=\", y, \", ftol=\", config.f_abstol, \", abs(x₁-x₀)=\", abs(x₁-x₀), \", xtol=\", config.x_abstol)\n\n    # i != ls.nmax || error(\"Max iteration number exceeded\")\n\n    return x\nend\n\nbisection(f, x::Number; kwargs...) = bisection(f, bracket_minimum(f, x)...; kwargs...)\n\n\n\"\"\"\nsimple bisection line search\n\"\"\"\nmutable struct BisectionState{OBJ,OPT} <: LinesearchState where {OBJ <: UnivariateObjective, OPT <: Options}\n    objective::OBJ\n    config::OPT\n\n    function BisectionState(objective, config)\n        new{typeof(objective), typeof(config)}(objective, config)\n    end\nend\n\nfunction BisectionState(objective::UnivariateObjective; config = Options())\n    BisectionState(objective, config)\nend\n\nfunction BisectionState(objective::MultivariateObjective; config = Options())\n    cache = LinesearchCache(objective.x_f)\n    ls_objective = linesearch_objective(objective, cache)\n    BisectionState(ls_objective, config)\nend\n\nBase.show(io::IO, ls::BisectionState) = print(io, \"Bisection\")\n\nLinesearchState(algorithm::Bisection, objective; kwargs...) = BisectionState(objective; kwargs...)\n\nfunction (ls::BisectionState)()\n    bisection(ls.objective, 0., 1.; config = ls.config)\nend\n", "meta": {"hexsha": "b1663af8dab06e2422e7a109c91c92a2382361a2", "size": 2020, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linesearch/bisection.jl", "max_stars_repo_name": "JuliaGNI/SimpleSolvers.jl", "max_stars_repo_head_hexsha": "1b428dc342a7ab83343e80ea1167ac163506c69c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-20T12:50:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:06:19.000Z", "max_issues_repo_path": "src/linesearch/bisection.jl", "max_issues_repo_name": "JuliaGNI/SimpleSolvers.jl", "max_issues_repo_head_hexsha": "1b428dc342a7ab83343e80ea1167ac163506c69c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-12-11T13:03:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T20:21:17.000Z", "max_forks_repo_path": "src/linesearch/bisection.jl", "max_forks_repo_name": "JuliaGNI/SimpleSolvers.jl", "max_forks_repo_head_hexsha": "1b428dc342a7ab83343e80ea1167ac163506c69c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2972972973, "max_line_length": 121, "alphanum_fraction": 0.6118811881, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.756649703425564}}
{"text": "using Distributions\nusing Expectations\nusing StatsBase\nusing InformationGeometry\ndist = LogNormal()\nE = expectation(dist)\n@show E(x->x^2)\ndist1 = Gamma()\nE1 = expectation(dist1)\n@show E1(x->x^2)\n\ncrossentropy([0.2, 0.3, 0.5], [0.3, 0.4, 0.3])\n\nlognormalpdf = x -> pdf(dist,x)\n\nloggammapdf = x -> pdf(dist1,x)\n\nE(x -> lognormalpdf(x))\n\nA = rand(dist,1000)\n\nB = rand(dist1,1000)\n\ndist2 = Normal(1,3)\n\ndist3 = Normal(5,2)\n\nC = kldivergence(dist2,dist3)\nKullbackLeibler(dist2,dist3)\n\nD = kldivergence(dist1,dist)\nKullbackLeibler(dist,dist3)\n\nE1(x -> log(lognormalpdf(x)))- E1(x -> log(loggammapdf(x)))\n\nKullbackLeibler(x->loggammapdf(x),y->lognormalpdf(y),HyperCube([-20,20]); Carlo=true, N=Int(3e6))\n\nKullbackLeibler(x->pdf(Normal(1,3),x),y->pdf(Normal(5,2),y),HyperCube([-20,20]); Carlo=true, N=Int(3e6))\nKullbackLeibler(Normal(1,3),Normal(5,2))\n", "meta": {"hexsha": "41393db886ad6c47daacfa8193f454d7a5230684", "size": 844, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Preliminary/Statistics/basic_distributions.jl", "max_stars_repo_name": "Song921012/MathEpiDeepLearningTutorial", "max_stars_repo_head_hexsha": "c0279a05f6288f50f6fee3733af8d02c26a0d04b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Preliminary/Statistics/basic_distributions.jl", "max_issues_repo_name": "Song921012/MathEpiDeepLearningTutorial", "max_issues_repo_head_hexsha": "c0279a05f6288f50f6fee3733af8d02c26a0d04b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Preliminary/Statistics/basic_distributions.jl", "max_forks_repo_name": "Song921012/MathEpiDeepLearningTutorial", "max_forks_repo_head_hexsha": "c0279a05f6288f50f6fee3733af8d02c26a0d04b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-14T20:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-14T20:44:23.000Z", "avg_line_length": 21.1, "max_line_length": 104, "alphanum_fraction": 0.691943128, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7566497017181194}}
{"text": "function NewEst3Ps(g0,m)\n#NewEst3Ps    Calculates covariance matrix of sqrt(T)*sample average.\n#\n#\n#  Usage:     Shat = NewEst3Ps(hhat,m)\n#\n#  Input:     g0          TxK matrix of moment functions\n#             m           order of autoregression\n#\n#  Output:    Shat        covariance matrix of sum( hhat/sqrt(T) ),\n#                         that is the covariance matrix of sqrt(T)*mean(hhat)\n#\n#\n#  Note: The CLT typically say that sqrt(T)*sample average ->d N(mu,Shat),\n#        where Shat is what this code estimates. Clearly, Var(sample average) =\n#        Shat/T.\n#\n#\n#  Reference: Newey and West, 1987, Econometrica\n#             Newey, 1985, Journal of Econometrics\n#\n#\n#  Paul Soderlind (Paul.Soderlind@unisg.ch), to Julia Oct 2015\n#-----------------------------------------------------------------------\n\n  T = size(g0,1)                     #g is Txq\n  m = min(m,T-1)                     #number of lags\n\n  g = g0 .- mean(g0,1)               #Normalizing to Eg=0\n\n  S = g'g/T                          #(qxT)*(Txq)\n  for s = 1:m\n    Omega_s = g[s+1:T,:]'g[1:T-s,:]/T   #same as Sum[g(t)*g(t-s)',t=s+1,T]\n    S       = S + (1 - s/(m+1))*(Omega_s + Omega_s')\n  end\n\n  return S\n\nend\n#-----------------------------------------------------------------------\n", "meta": {"hexsha": "0bae3973ecdfa0076baa5ac3b329f36c91c293d0", "size": 1264, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "AssetPricingTest/NewEst3Ps.jl", "max_stars_repo_name": "PaulSoderlind/PaulSoderlindCode", "max_stars_repo_head_hexsha": "849ab977e410ece42d24ec86a4e043180200c551", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2016-01-15T21:13:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T21:21:18.000Z", "max_issues_repo_path": "AssetPricingTest/NewEst3Ps.jl", "max_issues_repo_name": "PaulSoderlind/PaulSoderlindCode", "max_issues_repo_head_hexsha": "849ab977e410ece42d24ec86a4e043180200c551", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-03-05T13:07:59.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-07T11:11:21.000Z", "max_forks_repo_path": "AssetPricingTest/NewEst3Ps.jl", "max_forks_repo_name": "PaulSoderlind/PaulSoderlindCode", "max_forks_repo_head_hexsha": "849ab977e410ece42d24ec86a4e043180200c551", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2016-03-05T13:01:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T19:44:57.000Z", "avg_line_length": 30.8292682927, "max_line_length": 79, "alphanum_fraction": 0.4754746835, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7566496972237402}}
{"text": "module DatasetsSynthetic\n\nusing Random\nexport make_blobs, make_circles, make_moons\n\nuniform_sample_in_zero_maxval(p, maxval) = maxval .* (1 .- rand(p))\nuniform_sample_in_minval_maxval(p, minval, maxval) = (maxval-minval) .* rand(p) .+ minval\nuniform_sample_in_minval_maxval(n, p, minval, maxval) = (maxval-minval) .* rand(n, p) .+ minval\nnormal_sample(p, mu, var) = mu .+ sqrt(var) .* randn(p)\n\n\n\"\"\"\nShuffles the rows of an Array `X` and the values of a vector `y` using a randomly\ngenerated permutation. The same permutation is used to shuffle both `X` and `y`.\n\"\"\"\nfunction shuffle_Xy(X, y; random_seed=Random.GLOBAL_RNG)\n    Random.seed!(random_seed)\n    perm = randperm(length(y))\n    return X[perm,:], y[perm]\nend\n\n\n\"\"\"\nmake_blobs(n::Int=100;\n           p::Int=2,\n           centers::Int=3,\n           cluster_std=1.0,\n           center_box=(-10.,10.),\n           element_type=Float64,\n           random_seed=Random.GLOBAL_RNG,\n           return_centers=false)\n\nGenerates a dataset with `n` examples of dimension `p` and returns a vector containing\nas integers the membership of the different points generated.\n\nThe data is roughly grouped around several `centers`  which are created using `cluster_std`.\nThe data lives inside `center_box` in the case it is randomly generated.\n\n- If `centers` is an integer the centroids are created randomly.\n- If `centers` is an Array containing points the centroids are picked from `centers`.\n- If `return_centers=true` the centroids of the blobs are returned.\n\"\"\"\nfunction make_blobs(n::Int=100; p::Int=2,\n                    shuffle::Bool=false, centers::Int=3, cluster_std::Real=1.0, center_box=(-10.,10.),\n                    element_type=Float64, random_seed=Random.GLOBAL_RNG, return_centers=false, verbose=0)\n\n    Random.seed!(random_seed)\n    X = zeros(n, p)\n    y = zeros(n)\n\n    if typeof(centers) <: Int\n        n_centers = centers\n        center_sample = uniform_sample_in_minval_maxval(n, p, center_box[1], center_box[2])\n    else\n        n_centers = length(centers)\n    end\n\n    if typeof(cluster_std) <: AbstractFloat\n        cluster_std = cluster_std * randn(n_centers)\n    end\n\n    # generates div(n, n_centers) examples assigned to each center\n    n_per_center = [div(n, n_centers) for x  in 1:n_centers]\n\n    # adds the reamainding examples to each center up to n\n    n_per_center = fill(div(n,n_centers), n_centers)\n    n_per_center[end] += rem(n,n_centers)\n\n    # generates the actual vectors close to each center blob\n    start_ind = 1\n    for (i, (n_blob, std, center)) in enumerate(zip(n_per_center, cluster_std, centers))\n        ind_center = start_ind:(start_ind + n_per_center[i]-1)\n        X[ind_center,:] .= center' .+ std .* randn(element_type, (n_per_center[i], p));\n        y[ind_center] .= i\n        if verbose>0\n            println(\"center $i with $(n_per_center[i]) points created\")\n        end\n        start_ind += n_per_center[i]\n    end\n\n    if shuffle\n       X, y = shuffle_Xy(X, y ; random_seed=random_seed)\n    end\n\n    if return_centers\n        return X, y, centers\n    else\n        return X, y\n    end\nend\n\n\n\n\n\"\"\"\nmake_circles(n::Int=100; shuffle::Bool=true, noise::Number=0., random_seed=Random.GLOBAL_RNG, factor::Number=0.8)\n\nGenerates a dataset with `n` bi-dimensional examples. Samples are created\nfrom two circles. One of the circles inside the other. The `noise` scalar\ncan be used to add noise to the generation process. The scalar `factor`\ncorresponds to the radius of the smallest circle.\n\"\"\"\nfunction make_circles(n::Int=100; shuffle::Bool=true, noise::Number=0., random_seed=Random.GLOBAL_RNG, factor::Number=0.8)\n   \n    Random.seed!(random_seed)\n\n    n_out = div(n, 2)\n    n_in = n - n_out\n\n    linrange_out = Array(LinRange(0, 2 * pi, n_out))\n    linrange_in  = Array(LinRange(0, 2 * pi, n_in))\n\n    outer_circ_x = cos.(linrange_out)\n    outer_circ_y = sin.(linrange_out)\n    inner_circ_x = cos.(linrange_in) .* factor\n    inner_circ_y = sin.(linrange_in) .* factor\n\n    X = hcat(vcat(outer_circ_x, inner_circ_x), vcat(outer_circ_y, inner_circ_y))\n    y = vcat(ones(Int,n_out), 2*ones(Int,n_in))\n\n    if shuffle\n       X, y = shuffle_Xy(X, y ; random_seed=random_seed)\n    end\n\n    X .+= noise .* rand(n, 2)\n\n    return X, y\nend\n\n\n\n\"\"\"\nmake_moons(n::Int=100; shuffle::Bool=true, noise::Number=0.,\n           translation::Number=0.5, factor::Number=1.0, random_seed=Random.GLOBAL_RNG)\n\nGenerates `n` examples sampling from two moons. The `noise` can be changed to add\nnoise to the samples.\n\"\"\"\nfunction make_moons(n::Int=100; shuffle::Bool=true, noise::Number=0.,\n                   translation::Number=0.5, factor::Number=1.0, random_seed=Random.GLOBAL_RNG)\n   \n    Random.seed!(random_seed)\n\n    n_out = div(n, 2)\n    n_in = n - n_out\n\n    linrange_out = Array(LinRange(0, pi, n_out))\n    linrange_in  = Array(LinRange(0, pi, n_in))\n\n    outer_circ_x = cos.(linrange_out)\n    outer_circ_y = sin.(linrange_out)\n    inner_circ_x = 1 .- cos.(linrange_in) .* factor\n    inner_circ_y = 1 .- sin.(linrange_in) .* factor .- translation\n\n    X = hcat(vcat(outer_circ_x, inner_circ_x), vcat(outer_circ_y, inner_circ_y))\n    y = vcat(ones(Int,n_out), 2*ones(Int,n_in))\n\n    if shuffle\n       X, y = shuffle_Xy(X, y ; random_seed=random_seed)\n    end\n\n    X .+= noise .* rand(n, 2)\n\n    return X, y\nend\n\nend #module\n", "meta": {"hexsha": "67bbd99d4461f2c3d5a161a4d9a7383b62468218", "size": 5306, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/datasets_synthetic.jl", "max_stars_repo_name": "davidbp/MLJBase.jl", "max_stars_repo_head_hexsha": "96b7d42f3e3d8873bcc4e14ba9e29598f6a230fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/datasets_synthetic.jl", "max_issues_repo_name": "davidbp/MLJBase.jl", "max_issues_repo_head_hexsha": "96b7d42f3e3d8873bcc4e14ba9e29598f6a230fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/datasets_synthetic.jl", "max_forks_repo_name": "davidbp/MLJBase.jl", "max_forks_repo_head_hexsha": "96b7d42f3e3d8873bcc4e14ba9e29598f6a230fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5833333333, "max_line_length": 122, "alphanum_fraction": 0.669430833, "num_tokens": 1523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7566172679713387}}
{"text": "abstract type AbstractDiscreteMarkovChain <: AbstractMarkovChain end\n\n\"\"\"\n    DiscreteMarkovChain(transition_matrix)\n    DiscreteMarkovChain(state_space, transition_matrix)\n    DiscreteMarkovChain(continuous_markov_chain)\n\nCreates a new discrete Markov chain object.\n\n# Arguments\n- `state_space`: The names of the states that make up the Markov chain.\n- `transition_matrix`: The single step transition probability matrix.\n- `continuous_markov_chain`: An instance of `ContinuousMarkovChain`.\n\n# Examples\nThe following shows a basic Sunny-Cloudy-Rainy weather model.\n```jldoctest DiscreteMarkovChain\nusing DiscreteMarkovChains\nT = [\n    0.9 0.1 0;\n    0.5 0.2 0.3;\n    0.1 0.4 0.5\n]\nX = DiscreteMarkovChain([\"Sunny\", \"Cloudy\", \"Rainy\"], T)\nprintln(state_space(X))\n\n# output\n\n[\"Sunny\", \"Cloudy\", \"Rainy\"]\n```\n\n```jldoctest DiscreteMarkovChain\nprintln(transition_matrix(X))\n\n# output\n\n[0.9 0.1 0.0; 0.5 0.2 0.3; 0.1 0.4 0.5]\n```\n\n# References\n1. [Wikipedia](https://en.wikipedia.org/wiki/Markov_chain#Discrete-time_Markov_chain)\n2. [Dartmouth College](https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf)\n\"\"\"\nstruct DiscreteMarkovChain <: AbstractDiscreteMarkovChain\n    state_space\n    transition_matrix\n    function DiscreteMarkovChain(state_space, transition_matrix)\n        check(state_space, transition_matrix, DiscreteMarkovChain)\n        new(state_space, transition_matrix)\n    end\nend\n\"\"\"\n    required_row_sum(type)\n\n# Arguments\n- `type`: The type of Markov chain. It can be\n`DiscreteMarkovChain` or `ContinuousMarkovChain`.\n\n# Returns\nThe number that each row in the transition matrix should sum up to.\n\"\"\"\nrequired_row_sum(::Type{<:AbstractDiscreteMarkovChain}) = 1\nrequired_row_sum(::Type{<:AbstractDiscreteMarkovChain}, ::Type{T}) where T = one(T)\nfunction DiscreteMarkovChain(transition_matrix)\n    return DiscreteMarkovChain(1:(size(transition_matrix)[1]), transition_matrix)\nend\n\n\"\"\"\n    characteristic_matrix(::AbstractDiscreteMarkovChain)\n    characteristic_matrix(::AbstractContinuousMarkovChain)\n\n# Definitions\nMany derivations and interesting ideas about Markov chains\ninvolve the identity matrix or zero matrix somewhere along\nthe line. Most of the time, the identity matrix appears\nmore often in discrete Markov chains. Instead of the identity\nmatrix, the zero matrix appears in its place for continuous\nMarkov chains.\n\n# Returns\nThe identity matrix if its argument is an instance of\n`AbstractDiscreteMarkovChain`. The zero matrix if its\nargument is an instance of `AbstractContinuousMarkovChain`\n\"\"\"\ncharacteristic_matrix(::AbstractDiscreteMarkovChain) = LinearAlgebra.I\n\n\"\"\"\n    periodicities(x::AbstractDiscreteMarkovChain)\n\nA more advanced version of `communication_classes`\ndesigned for discrete Markov chains. It is the same as\n`communication_classes` but it returns periodicities as well.\n\n# Definitions\nThe period, ``d_i`` of a state ``i`` is the greatest common denominator\nof all integers ``n ∈ \\\\mathbb{N}`` for which ``p^{(n)}_{i,i} > 0``.\nWritten more succinctly,\n```math\nd_i = \\\\text{gcd}\\\\{ n ∈ \\\\mathbb{N} | p^{(n)}_{i,i} > 0 \\\\}\n```\nIf ``d_i=1`` then state ``i`` is said to be aperiodic.\n\n# Arguments\n- `x`: some kind of discrete Markov chain.\n\n# Returns\nA tuple containing 3 arrays.\n- This first array contains C arrays which store the states that communicate.\n- The second array is an array of Bool where the ith value is true if the\n  ith communication class is recurrent.\n- The third array is the periodicity of each communication class.\n\n# Examples\n```jldoctest periodicities\nusing DiscreteMarkovChains\nT = [\n    1 0;\n    0 1;\n]\nX = DiscreteMarkovChain(T)\n\nperiodicities(X)\n\n# output\n\n([[1], [2]], Any[true, true], Any[1, 1])\n```\n\nSo the Markov chain has two communication classes and both are recurrent and aperiodic.\n\n```jldoctest periodicities\nT = [\n    0.0 1.0 0.0;\n    1.0 0.0 0.0;\n    0.1 0.2 0.7;\n]\nX = DiscreteMarkovChain([\"Sunny\", \"Cloudy\", \"Rainy\"], T)\n\nperiodicities(X)\n\n# output\n\n([[\"Sunny\", \"Cloudy\"], [\"Rainy\"]], Any[true, false], Any[2, 1])\n```\n\nSo the Sunny and Cloudy states communicate and are recurrent with period 2.\nThe Rainy state is transient and aperiodic.\nNote that this is not a very good weather model since once it\nstops raining, it will never rain again. Also, each day after that,\nthe process will oscillate between Sunny and Cloudy.\n\"\"\"\nfunction periodicities(x::AbstractDiscreteMarkovChain)\n    SI = state_index(x)\n    T = transition_matrix(x)\n\n    classes, recurrence = communication_classes(x)\n    index_classes = [[SI[state] for state in class] for class in classes]\n\n    periods = []\n    for class in index_classes\n        submatrix = T[class, class]\n        push!(periods, breadth_first_search(submatrix))\n    end\n    return classes, recurrence, periods\nend\n\n\"\"\"\n    is_regular(x)\n\n# Definitions\nA Markov chain is called a regular chain if some power of the\ntransition matrix has only positive elements. This is equivalent\nto being ergodic and aperiodic.\n\n# Arguments\n- `x`: some kind of discrete Markov chain.\n\n# Returns\n`true` if the Markov chain, `x`, is regular.\n\n# Examples\nWe will set up a matrix with 2 communication classes and\nshow that it is not regular.\n\n```jldoctest is_regular\nusing DiscreteMarkovChains\nT = [\n    0 1 0;\n    1 0 0;\n    0 0 1;\n]\nX = DiscreteMarkovChain(T)\n\nis_regular(X)\n\n# output\n\nfalse\n```\n\nRepeat the above but now all states communicate.\n\n```jldoctest is_regular\nT = [\n    0.0 0.5 0.5;\n    0.0 0.0 1.0;\n    1.0 0.0 0.0;\n]\nX = DiscreteMarkovChain(T)\n\nis_regular(X)\n\n# output\n\ntrue\n```\n\nNotice how a periodic chain is not regular even though\nthere is only one communication class.\n\n```jldoctest is_regular\nT = [\n    0 1 0;\n    0 0 1;\n    1 0 0;\n]\nX = DiscreteMarkovChain(T)\n\nis_regular(X)\n\n# output\n\nfalse\n```\n\"\"\"\nfunction is_regular(x::AbstractDiscreteMarkovChain)\n    classes, _, periods = periodicities(x)\n    if length(classes) == 0\n        return false\n    end\n    return (length(classes) == 1) & (periods[1] == 1)\nend\n\n\"\"\"\n    first_passage_probabilities(x, t, i=missing, j=missing)\n\n# Definitions\nThis is the probability that the process enters state ``j``\nfor the first time at time ``t`` given that the process started\nin state ``i`` at time 0. That is, ``f^{(t)}_{i,j}``. If no `i`\nor `j` is given, then it will return a matrix instead with\nentries ``f^{(t)}_{i,j}`` for `i` and `j` in the state space of `x`.\n\n# Why Do We Use A Slow Algorithm?\nSo that `t` can be symbolic if nessesary. That is, if symbolic math\nlibraries want to use this library, it will pose no hassle.\n\n# Arguments\n- `x`: some kind of Markov chain.\n- `t`: the time to calculate the first passage probability.\n- `i`: the state that the prcess starts in.\n- `j`: the state that the process must reach for the first time.\n\n# Returns\nA scalar value or a matrix depending on whether `i` and `j` are given.\n\n# Examples\n```jldoctest first_passage_probabilities\nusing DiscreteMarkovChains\nT = [\n    0.1 0.9;\n    0.3 0.7;\n]\nX = DiscreteMarkovChain(T)\n\nfirst_passage_probabilities(X, 2)\n\n# output\n\n2×2 Array{Float64,2}:\n 0.27  0.09\n 0.21  0.27\n```\n\nIf `X` has a custom state space,\nthen `i` and `j` must be in that state space.\n\n```jldoctest first_passage_probabilities\nT = [\n    0.1 0.9;\n    0.3 0.7;\n]\nX = DiscreteMarkovChain([\"Sunny\", \"Rainy\"], T)\n\nfirst_passage_probabilities(X, 2, \"Sunny\", \"Rainy\")\n\n# output\n\n0.09000000000000001\n```\n\nNotice how this is the (1, 2) entry in the first example.\n\n# References\n1. [University of Windsor](https://scholar.uwindsor.ca/cgi/viewcontent.cgi?article=1125&context=major-papers)\n2. [Durham University](http://maths.dur.ac.uk/stats/courses/ProbMC2H/_files/handouts/1516MarkovChains2H.pdf)\n\"\"\"\nfunction first_passage_probabilities(\n    x::AbstractDiscreteMarkovChain, t, i=missing, j=missing\n)\n    S = state_space(x)\n    T = transition_matrix(x)\n    n = length(S)\n\n    if n == 0\n        return transition_matrix(x)\n    end\n\n    js = 1:n  # The columns to loop through\n    calc_i_ne_j = true  # Calculate the off-diagonals\n    calc_i_eq_j = true  # Calculate the diagonals\n    if (i !== missing) && (j !== missing)\n        i = state_index(x)[i]\n        j = state_index(x)[j]\n        js = [j]\n        if i == j\n            calc_i_ne_j = false\n        else\n            calc_i_eq_j = false\n        end\n    end\n\n    Ft = zeros(eltype(T), n, n)  # Empty matrix\n\n    # If i != j\n    if calc_i_ne_j\n        for j in js\n\n            P0 = copy(T)\n            P0[1:n, j] = zeros(eltype(T), n, 1)\n            F = P0^(t-1) * T\n            Ft[1:n, j] = F[1:n, j]\n        end\n    end\n\n    # If i == j\n    if calc_i_eq_j\n        for j in js\n\n            P_ = copy(T)\n            P_[j, 1:n] = zeros(eltype(T), 1, n)\n\n            Pnew = zeros(eltype(T), 2*n, 2*n)\n            Pnew[1:n, 1:n] = T\n            Pnew[(n+1):(2*n), (n+1):(2*n)] = P_\n            Pnew[n+j, 1:n] = T[j, 1:n]\n\n            P0 = copy(Pnew)\n            P0[1:(2*n), j] = zeros(eltype(T), 2*n, 1)\n\n            F = P0^(t - 1) * Pnew\n\n            Ft[j, j] = F[n+j, j]\n        end\n    end\n\n    if (i !== missing) && (j !== missing)\n        return Ft[i, j]\n    end\n    return Ft\nend\n", "meta": {"hexsha": "18e05bc8dcadb7ac59531e8d6c66f6c8f3b10862", "size": 9090, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DMC.jl", "max_stars_repo_name": "dkarrasch/DiscreteMarkovChains.jl", "max_stars_repo_head_hexsha": "5262826a7ef70c46059e24577d89faf720b48f74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-12-06T19:42:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T07:58:45.000Z", "max_issues_repo_path": "src/DMC.jl", "max_issues_repo_name": "dkarrasch/DiscreteMarkovChains.jl", "max_issues_repo_head_hexsha": "5262826a7ef70c46059e24577d89faf720b48f74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-12-02T00:08:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-29T16:42:36.000Z", "max_forks_repo_path": "src/DMC.jl", "max_forks_repo_name": "dkarrasch/DiscreteMarkovChains.jl", "max_forks_repo_head_hexsha": "5262826a7ef70c46059e24577d89faf720b48f74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-08T10:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T10:58:59.000Z", "avg_line_length": 24.435483871, "max_line_length": 117, "alphanum_fraction": 0.6797579758, "num_tokens": 2721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.756617263178818}}
{"text": "#\n# Function that computes a moving average to smooth plots\n#\n\nfunction movingaverage( x :: Vector, n :: Int )\n  \n  if ! isodd(n)\n    n = n + 1\n  end\n  delta = round(Int64,(n-1)/2)\n\n  nx = length(x)\n  y = similar(x) \n\n  for i in 1:nx\n    y[i] = 0.\n    jmin = max(i-delta,1)\n    jmax = min(i+delta,nx)\n    for j in jmin:jmax\n      y[i] = y[i] + x[j]\n    end\n    y[i] = y[i] / (jmax-jmin+1)\n\n  end\n\n  return y\n\nend\n\n", "meta": {"hexsha": "2641f04337199618aa2395f25baa43aa7389fd0d", "size": 414, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/movingaverage.jl", "max_stars_repo_name": "mcubeg/M3GTools", "max_stars_repo_head_hexsha": "48ab02a23f0095e7964bfb047836f090f8d35331", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-22T05:04:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-30T06:32:25.000Z", "max_issues_repo_path": "src/movingaverage.jl", "max_issues_repo_name": "mcubeg/M3GTools", "max_issues_repo_head_hexsha": "48ab02a23f0095e7964bfb047836f090f8d35331", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/movingaverage.jl", "max_forks_repo_name": "mcubeg/M3GTools", "max_forks_repo_head_hexsha": "48ab02a23f0095e7964bfb047836f090f8d35331", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-17T10:16:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T10:16:37.000Z", "avg_line_length": 13.8, "max_line_length": 57, "alphanum_fraction": 0.5289855072, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7566172628289537}}
{"text": "# Plots power spectrum components of approximate Gaussian PSD:\nusing PyPlot\n\n#nc = 4\n#amp = [2.953823582534889, -0.04961614737314587, -1.6900719772140012, -0.21413545794774125]\n#b =[1.589510614489265, 3.4729345651560872, 1.8698492189074047, 6.363451205766626]\n#omega =[0.3329119766576696, 4.5999414581901386,1.7115890219170917, 2.205939216106191]\n#amp = [2.953823582534889, -0.04961614737314587, -0.21413545794774125, -1.690719772140012]\n#b =[1.589510614489265, 3.4729345651560872, 6.363451205766626, 1.8698492189074047]\n#omega =[0.3329119766576696, 4.5999414581901386, 2.205939216106191,1.1115890219170917]\n\nnc = 3\namp = [2.670143,-0.458705,-1.211438]\nb = [1.500258,4.125558,1.744602]\nomega = [0.346731,1.390912,1.798436]\n\nnf = 100\nf = 2*pi*logspace(-2,2,nf)\npsdtot =  zeros(nf)\nfor i=1:nc\n  psd = amp[i]*b[i]*sqrt(2./pi)*(b[i]^2+omega[i]^2+f.^2)./(b[i]^4+(omega[i]^2-f.^2).^2+2.*b[i]^2.*(omega[i]^2+f[i]^2))\n  loglog(f,abs(psd))\n  psdtot += psd\n  loglog(f,psdtot,linestyle=\"dashed\")\n  read(STDIN,Char)\nend\n\n#plot(f,psdtot)\n", "meta": {"hexsha": "17867080ef09efa5f95d29461164c70d2179c282", "size": 1025, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "paper/approximate_kernels/plot_gaussian_psd.jl", "max_stars_repo_name": "dfm/ess", "max_stars_repo_head_hexsha": "09ee14e516bb3bc3b517c0c1b6716eaeb28183b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 172, "max_stars_repo_stars_event_min_datetime": "2017-02-10T21:23:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T23:02:20.000Z", "max_issues_repo_path": "paper/approximate_kernels/plot_gaussian_psd.jl", "max_issues_repo_name": "dfm/ess", "max_issues_repo_head_hexsha": "09ee14e516bb3bc3b517c0c1b6716eaeb28183b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 90, "max_issues_repo_issues_event_min_datetime": "2017-01-12T21:31:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T13:13:50.000Z", "max_forks_repo_path": "paper/approximate_kernels/plot_gaussian_psd.jl", "max_forks_repo_name": "dfm/ess", "max_forks_repo_head_hexsha": "09ee14e516bb3bc3b517c0c1b6716eaeb28183b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2017-03-14T21:17:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T19:22:03.000Z", "avg_line_length": 35.3448275862, "max_line_length": 118, "alphanum_fraction": 0.7170731707, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7566172614294958}}
{"text": "#=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=#\n# Problem set 2 solutions\n# Written by Tyler Ransom\n# Commented by Giuseppe Grasso\n#=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=#\n\nusing Random\nusing LinearAlgebra\nusing Statistics\nusing Optim\nusing DataFrames\nusing CSV\nusing HTTP\nusing GLM\nusing FreqTables\nusing ForwardDiff # for bonus at the very end\ncd(\"/Users/peppegrass/Documents/GitHub/fall-2020/ProblemSets/PS2-optimization-intro/\") # GG: sets working directory\npwd() ## GG: prints working directory\nreaddir() # GG: equivalent to -ls- to see elements of working directory\n\nfunction allwrap()\n    #:::::::::::::::::::::::::::::::::::::::::::::::::::\n    # Question 1\n    # Basic [# GG: NON-LINEAR] optimization in Julia\n    #:::::::::::::::::::::::::::::::::::::::::::::::::::\n\n    #=\n    GG: We will use Julia’s Optim package, which is a function MINIMIZER.\n    Thus, if we want to ﬁnd the maximum of f(x), we need to minimize −f(x).\n    GG: Run code below in REPL to see how Optim works\n    =#\n\n    f(x) = -x[1]^4-10x[1]^3-2x[1]^2-3x[1]-2 # GG: original objective function\n    minusf(x) = x[1]^4+10x[1]^3+2x[1]^2+3x[1]+2 # GG: -(obj fct)\n    startval = rand(1)   # random starting value\n    #=\n    GG: The Optim package provides a function called optimize(). This function requires three inputs:\n    the objective function, a starting value, and an optimization algorithm.\n    We will not get too deep into optimization algorithms in this course, but for now just use LBFGS().\n    =#\n    result = optimize(minusf, startval, BFGS()) # GG: BFGS is a gradient-based algorithm: objective function needs to be differentiable for this to work; otherwise, use different algorithm\n    println(result)\n\n    #=\n    GG: Look at the measures of convergence in the result:\n    3 different criteria when doing non-linear optimization. Metaphor: climing a mountain and looking at ALTITUDE & LATITUDE/LONGITUDE\n    1. Look at g(x): Most intuitive and common one: is the gradient 0 [necessary condition: FOC]?\n    2. Look at |f(x) - f(x')|: Since the last iteration of this procedure (with the first iteration being originally based on the starting value), how much has the FUNCTION VALUE changed (i.e. has the ALTITUDE changed) between the previous or current iteration? Is there evidence for the slope not being at zero?\n    3. Look at |x - x'|: How far did I step from the last iteration to this iteration, i.e. how did the value x (current) change wrt to x' (previous)? How much did LATITUDE/LONGITUDE change\n        # GG: gradient 1. is the most important and also hardest to satisfy\n        Tolerance values/thresholds can be set for gradient (gtol/gval), function (ftol/fval) and value (xtol/xval); e.g. e-06 as opposed to e-08\n    =#\n\n    #:::::::::::::::::::::::::::::::::::::::::::::::::::\n    # Question 2\n    # Now that we’re familiar with how Optim’s optimize() function works, lets try it on some real-world data.\n    # Speciﬁcally, let’s use Optim to compute OLS estimates of a simple LINEAR REGRESSION using actual data.\n    # The process for passing data to Optim can be tricky, so it will be helpful to go through this example.\n    # First, let’s import and set up the data. Note that you will need to put the URL all on one line when executing this code in Julia.\n    #:::::::::::::::::::::::::::::::::::::::::::::::::::\n    url = \"https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2020/master/ProblemSets/PS1-julia-intro/nlsw88.csv\" # GG: setting URL\n    df = CSV.read(HTTP.get(url).body) # GG: reading CSV from URL\n    X = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1] # GG: subset of variables that will be used in regression\n    y = df.married.==1 # GG: copying variable married from DataFrame df into array y\n    # GG: By applying OLS to a binary choice model we are estimating a Linear Probability Model (LPM)\n\n    # GG. A tricky thing with using Optim is that it requires something called a closure to be able to pass data into the function.\n    # GG: OLS is minimizer of Sum of Squared Errors (SSR) so we write down the objective function\n    function ols(beta, X, y) # GG: argument you are optimizing over has to come first in Optim; others (data) can come later\n        ssr = (y.-X*beta)'*(y.-X*beta) # GG: one way of writing it (.- is called loop fusion; should be the most efficient)\n        #= ssr = dot(y.-X*beta,y.-X*beta) Julia function dot() that takes dot product (an alternative) =#\n        #= ssr = [sum[y[i]-X[i,:]*beta]^2 for i in 1:length(y)] (yet another alternative by comprehension; might contain mistakes; pseudo-code) =#\n        #=  ssr = 0\n            for i=1:length(y)\n                ssr += (y[i]-X[i,:]*beta)^2\n            end\n        (yet another alternative using a loop; += is an operator to do iterations)\n        =#\n        return ssr\n    end\n\n    beta_hat_ols = optimize(b -> ols(b, X, y), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-6, iterations=100_000, show_trace=true))\n    #= GG:\n    - In exercise 1 we simply used optimize(minusf, ., .) because we had a univariate function of x\n    Now here we got 3 arguments and we need to tell Julia that we are optimizing over b by using the following synthax\n    optimize(b -> ols(b, X, y), ...)\n    - rand(size(X,2)) are starting value which must have the same dimension as the parameter vector (or dim covariate vector including the constant)\n    - LBFGS() is the algorithm chosen\n    - Setting a few options through Optim.Options(g_tol=1e-6, iterations=100_000, show_trace=true)\n        - tolerance value for gradient; capping number of iterations at 100k; show_trace=true prints out in the REPL what's happening at every step\n    =#\n\n    println(beta_hat_ols.minimizer) # GG: prints the output\n\n    # GG: Since OLS has a closed form solution, we can check that this worked in a few different ways:\n    # 1. by evaluating the known OLS closed form\n    bols = inv(X'*X)*X'*y\n    println(bols)\n    # 2. by using the GLS package; very similar to R\n    df.white = df.race.==1 # GG: Creating a dummy white for race==1\n    bols_lm = lm(@formula(married ~ age + white + collgrad), df) # GG: like in R, once you tell where data is coming from, you can just use varnames stata-style\n    println(bols_lm)\n    # GG: It can be easily verified that all three solutions are the same\n\n    #:::::::::::::::::::::::::::::::::::::::::::::::::::\n    # Question 3\n    # Use Optim to estimate the LOGIT LIKELIHOOD. Some things to keep in mind:\n    #   To maximize the likelihood, you will need to pass Optim the negative of the likelihood function\n    #   The likelihood function is included in the Lecture 4 slides\n    #:::::::::::::::::::::::::::::::::::::::::::::::::::\n\n    #=\n    GG: Same principle but this time we apply it to MAXIMUM LIKELIHOOD estimation of a BINARY LOGIT model\n    In previous exercise we programmed OLS; here we program logit\n    =#\n    function logit(alpha, X, y)\n\n        P = exp.(X*alpha)./(1 .+ exp.(X*alpha)) # GG: choice probability. Using dots to vectorize operation, i.e. exp() applied to all elements of X*alpha; same for other operations\n\n        loglike = -sum( (y.==1).*log.(P) .+ (y.==0).*log.(1 .- P) ) # GG: this is the LOGIT log-likelihood (times -1 coz of Optim is min fct); (y.==1) and (y.==0) are a booleans\n\n        return loglike\n    end\n    alpha_hat_optim = optimize(a -> logit(a, X, y), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-6, iterations=100_000, show_trace=true))\n    println(alpha_hat_optim.minimizer)\n    # GG: as we saw in OLS, here we're optimizing wrt a, so inside optimize we use a -> logit(a, X, y)\n    # GG: rand(size(X,2)) gives a vector the dimension of X of uniform 0,1 random numbers\n\n\n    #:::::::::::::::::::::::::::::::::::::::::::::::::::\n    # Question 4\n    # Use the glm() function from the GLM package to check your answer. (Example code for how to do this is in the Lecture 3 slides.)\n    #:::::::::::::::::::::::::::::::::::::::::::::::::::\n    alpha_hat_glm = glm(@formula(married ~ age + white + collgrad), df, Binomial(), LogitLink())\n    println(alpha_hat_glm)\n\n    #:::::::::::::::::::::::::::::::::::::::::::::::::::\n    # Question 5\n    # Use Optim to estimate a MULTINOMIAL LOGIT MODEL where the dependent variable is occupation and the covariates are the same as above.\n    # Before doing this, clean the data to remove rows where occupation is missing.\n    # We also need to aggregate some of the occupation categories or else we won’t be able to estimate our multinomial logit model:\n    #:::::::::::::::::::::::::::::::::::::::::::::::::::\n    freqtable(df, :occupation) # note small number of obs in some occupations\n    df = dropmissing(df, :occupation) # GG: dropping observations with missing occupation and overwriting df\n    df[df.occupation.==8 ,:occupation] .= 7 # GG: recoding all values >7 to 7\n    df[df.occupation.==9 ,:occupation] .= 7\n    df[df.occupation.==10,:occupation] .= 7\n    df[df.occupation.==11,:occupation] .= 7\n    df[df.occupation.==12,:occupation] .= 7\n    df[df.occupation.==13,:occupation] .= 7\n    freqtable(df, :occupation) # problem solved\n    # GG: Since we changed the number of rows of df, we also need to re-deﬁne our X and y objects:\n    X = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\n    y = df.occupation\n\n    #=\n    GG: Hints:\n\n    # With 7 choice alternatives, you will have K · 6 coefﬁcients, where K is the number of covariates in X.\n    It may help to transform the parameter vector into a K ×6 matrix (to more easily reference the α j ’s for each j)\n\n    # You should reset the tolerance of the gradient (g tol) to be 10 to the −5.\n    This will help the estimation converge more quickly, without losing too much precision. Otherwise, it would take forever.\n\n    # You may need to try different sets of starting values. Some candidates to consider are:\n    - a vector of 0s\n    - a vector of U[0,1] random numbers\n    - a vector of U[−1,1] random numbers\n    - the estimated values from Stata or R (see Stata example below)\n        webuse nlsw88\n        drop if mi(occupation)\n        recode occupation (8 9 10 11 12 13 = 7)\n        gen white = race==1\n        mlogit occupation age white collgrad, base(7)\n    In general it is a good strategy to run your model(s) through a more user-friendly interface like Stata or R before trying to implement them in Julia.\n    But you might ask, “Why don’t we just use Stata or R, then?”\n    The reason is because the models we will get to later in the course are much more difﬁcult to implement in those languages, because they can’t just be taken off the shelf.\n\n    We can readapt the code from the binary logit above. We gotta readapt to the fact that we have J choices and KxJ parameters\n    Functional form of choice probabilities and log-likelihood function is similar.\n    So I could take loglike = -sum( (y.==1).*log.(P) .+ (y.==0).*log.(1 .- P) ) and readapt it as follows\n    loglike = -sum( (y.==1).*log.(P1) .+ (y.==2).*log.(P2) .+ ...)\n    or I can do it in a LOOP (which is adviced in that it allows to reduce mistakes)\n    =#\n\n    function mlogit(alpha, X, y) # GG: mlogit can oly be fed alpha as a vector, not as a matrix\n\n        # GG: Defining K, J, N (not always a good idea to make extra allocations but in this case it helps understand what's what)\n        K = size(X,2)\n        J = length(unique(y))\n        N = length(y)\n        bigY = zeros(N,J) # GG: Initializing an NxJ matrix for the Ys. Looping over the number of occupation choices columns and creating a bunch of 1-0 columns (dummies) in the bigY matrix\n        for j=1:J\n            bigY[:,j] = y.==j\n        end\n        bigAlpha = [reshape(alpha,K,J-1) zeros(K)] # GG: reshaping alpha vector into a matrix in a way that is conformable to bigY (hence the zeroes at the end, reflecting the normalization of the parameters for the last occupation)\n\n        # GG: need to compute numerator and denominator of choice probabilities. For MNL num changes for each of them; den doesn't.\n        num = zeros(N,J)\n        dem = zeros(N)\n        for j=1:J\n            num[:,j] = exp.(X*bigAlpha[:,j]) # GG: changes for each numerator; first one normalized at 1 by exploiting exp(0)\n            dem .+= num[:,j] # GG: iterated sum of all numerators; .+= is vectorized iterative sum\n        end\n\n        # GG: and there you go, this is the choice probability;\n        P = num./repeat(dem,1,J) # GG: the denominator is the same for all alternatives, but we need to make it conformable, so we repeat the denominator J times in a way that is conformable to the numerator\n        # GG: repeat(dem,1,J) is a matrix the same size as the numerator (so that ./ can worl properly), repeated J times\n\n        loglike = -sum( bigY.*log.(P) ) # GG: here we need to do a double summation (over i and j); Julia understands to do sum over the rows and over the columns\n        # GG: but we could have said sum( sum( bigY.*log.(P) ; dims=2); dims=1)\n\n        return loglike\n    end\n\n    # GG: different options for starting values; stata answers multiplied by 0-1 uniform random numbers appear to be the best starting values\n    alpha_zero = zeros(6*size(X,2))\n    alpha_rand = rand(6*size(X,2))\n    alpha_true = [.1910213,-.0335262,.5963968,.4165052,-.1698368,-.0359784,1.30684,-.430997,.6894727,-.0104578,.5231634,-1.492475,-2.26748,-.0053001,1.391402,-.9849661,-1.398468,-.0142969,-.0176531,-1.495123,.2454891,-.0067267,-.5382892,-3.78975]\n    alpha_start = alpha_true.*rand(size(alpha_true))\n    println(size(alpha_true))\n    alpha_hat_optim = optimize(a -> mlogit(a, X, y), alpha_start, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\n    alpha_hat_mle = alpha_hat_optim.minimizer\n    println(alpha_hat_mle)\n\n\n    #:::::::::::::::::::::::::::::::::::::::::::::::::::\n    # BONUS: how to get STANDARD ERRORS?\n    # Need to adjust objective function sligthly, i.e. need to obtain the hessian of the obj fun\n    #:::::::::::::::::::::::::::::::::::::::::::::::::::\n    # TR: first, we need to slightly modify our objective function\n    function mlogit_for_h(alpha, X, y)\n\n        K = size(X,2)\n        J = length(unique(y))\n        N = length(y)\n        bigY = zeros(N,J)\n        for j=1:J\n            bigY[:,j] = y.==j\n        end\n        bigAlpha = [reshape(alpha,K,J-1) zeros(K)]\n\n        T = promote_type(eltype(X),eltype(alpha)) # TR: this line is new; GG: becuase types matter; gotta be the same\n        num   = zeros(T,N,J)                      # TR: this line is new; GG: you specify type T before specifying dimensions\n        dem   = zeros(T,N)                        # TR: this line is new; GG: you specify type T before specifying dimensions\n        for j=1:J\n            num[:,j] = exp.(X*bigAlpha[:,j])\n            dem .+= num[:,j]\n        end\n\n        P = num./repeat(dem,1,J)\n\n        loglike = -sum( bigY.*log.(P) )\n\n        return loglike\n    end\n\n    # GG: auodifferentiation: will get you the EXACT derivative of objective function, speeding up the optimization time because optimizer has gradient coded in (doesn't have to numerically approximate it) and it'll allow to get the numerical HESSIAN of your obj fct, which is what you need to compute STANDARD ERRORS\n    # GG: need to pass a twice differentiable object (td) before the closure\n\n    # declare that the objective function is twice differentiable\n    td = TwiceDifferentiable(b -> mlogit_for_h(b, X, y), alpha_start; autodiff = :forward) # GG: uses forward mode autodifferentiation\n    # run the optimizer\n    alpha_hat_optim_ad = optimize(td, alpha_zero, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\n    # GG: so instead of putting as closure simply b -> mlogit_for_h(b, X, y), we put td, which stands for TwiceDifferentiable(b -> mlogit_for_h(b, X, y), alpha_start; autodiff = :forward)\n    # GG: everything else stays the same\n    alpha_hat_mle_ad = alpha_hat_optim_ad.minimizer\n    # evaluate the Hessian at the estimates\n    H  = Optim.hessian!(td, alpha_hat_mle_ad) # GG: getting the Hessian of twice differentiable object evaluated at the solution\n    # TR: standard errors = sqrt(diag(inv(H))) [usually it's -H but we've already multiplied the obj fun by -1]\n    # GG: from Adv Metrics on efficiency of Maximum Likelihood: -inv(H) enters the variance formula (sandwich); not taking negative coz we already took the negative of the objective function\n    alpha_hat_mle_ad_se = sqrt.(diag(inv(H))) # GG: Take the square root of the diagonal elements of the inverse of the Hessian at the optimum\n    println([alpha_hat_mle_ad alpha_hat_mle_ad_se]) # TR: these standard errors match Stata\n\n    return nothing\nend\n\n# GG: Rather then getting the Hessian, we could also use Bootstrap to get the standard errors (but it'll take a lot longer)\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# Question 6\n# Wrap all of your code above into a function and then call that function at the very bottom of your script.\n# Make sure you add println() statements after obtaining each set of estimates so that you can read them.\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nallwrap()\n", "meta": {"hexsha": "6f650152ebb0f32de8ae60fa2e3c317bb34aac19", "size": 17114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS2-optimization-intro/PS2solutions_GG.jl", "max_stars_repo_name": "peppegrass/fall-2020", "max_stars_repo_head_hexsha": "03f90548ca4d800146bbeaf9dceca917a21c1195", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-01T08:58:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-01T08:58:14.000Z", "max_issues_repo_path": "ProblemSets/PS2-optimization-intro/PS2solutions_GG.jl", "max_issues_repo_name": "peppegrass/fall-2020", "max_issues_repo_head_hexsha": "03f90548ca4d800146bbeaf9dceca917a21c1195", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS2-optimization-intro/PS2solutions_GG.jl", "max_forks_repo_name": "peppegrass/fall-2020", "max_forks_repo_head_hexsha": "03f90548ca4d800146bbeaf9dceca917a21c1195", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-12T17:24:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-12T17:24:05.000Z", "avg_line_length": 59.8391608392, "max_line_length": 317, "alphanum_fraction": 0.6515718126, "num_tokens": 4608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7566172566369757}}
{"text": "# 26 in base 16 or 2\nbase(16, 26)\nbase(2, 26)\n\n# Parse to integer\nparse(Int, \"1a\", 16)\nparse(Int, \"101101\", 2)\n", "meta": {"hexsha": "15d21d6e101853db32e6ce0be5d2d00e6ca6834d", "size": 111, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/non-decimal-radices-convert.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/non-decimal-radices-convert.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/non-decimal-radices-convert.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.875, "max_line_length": 23, "alphanum_fraction": 0.6216216216, "num_tokens": 50, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032941988938414, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7566172537566322}}
{"text": "module UnivariateProblems\n\n    ### Sources\n    ###\n    ### [1]  http://infinity77.net/global_optimization/test_functions_1d.html\n\n    struct UnivariateProblem\n        name::AbstractString\n        f::Function\n        bounds::Vector{Float64}\n        minimizers::Vector{Float64}\n        minima::Vector{Float64}\n    end\n\n    examples = Dict{AbstractString, UnivariateProblem}()\n\n    f(x) = 2x^2+3x+1\n\n    examples[\"Polynomial\"] = UnivariateProblem(\"Polynomial\",\n                                                  f,\n                                                  [-2.0, 1.0],\n                                                  [-0.75,],\n                                                  [f(-0.75),])\n\n    # Problem 04 from [1]\n    p04(x) = -(16x^2-24x+5)exp(-x)\n\n    examples[\"Problem04\"] = UnivariateProblem(\"Problem04\",\n                                                p04,\n                                                [1.9, 3.9],\n                                                [2.868034,],\n                                                [p04(2.868034),])\n\n    # Problem 13 from [1]\n    p13(x) = -x^(2/3)-(1-x^2)^(1/3)\n\n    examples[\"Problem13\"] = UnivariateProblem(\"Problem13\",\n                                                p13,\n                                                [0.001, 0.99],\n                                                [1 ./ sqrt(2.0),],\n                                                [p13(1 ./ sqrt(2.0)),])\n\n    # Problem 18 from [1]\n    p18(x) = x <= 3.0 ? (x-2.0)^2 : 2.0*log(x-2.0)+1.0\n\n    examples[\"Problem18\"] = UnivariateProblem(\"Problem18\",\n                                                p18,\n                                                [0.0, 6.0],\n                                                [2.0,],\n                                                [p18(2.0),])\nend\n", "meta": {"hexsha": "4c94da60f38877222ece5cf510d49757f2625c90", "size": 1813, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/optim_tests/univariate/bounded.jl", "max_stars_repo_name": "gwater/OptimTestProblems.jl", "max_stars_repo_head_hexsha": "45650b6fbbfb07892f827dd74aee03f5e32afc20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-09-20T17:07:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-28T02:02:33.000Z", "max_issues_repo_path": "src/optim_tests/univariate/bounded.jl", "max_issues_repo_name": "gwater/OptimTestProblems.jl", "max_issues_repo_head_hexsha": "45650b6fbbfb07892f827dd74aee03f5e32afc20", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2017-10-10T22:16:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-25T18:27:57.000Z", "max_forks_repo_path": "src/optim_tests/univariate/bounded.jl", "max_forks_repo_name": "gwater/OptimTestProblems.jl", "max_forks_repo_head_hexsha": "45650b6fbbfb07892f827dd74aee03f5e32afc20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2017-09-16T11:06:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T16:22:54.000Z", "avg_line_length": 34.8653846154, "max_line_length": 77, "alphanum_fraction": 0.3303916161, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904955, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7566172534067674}}
{"text": "# D(u)_function.jl\n\n\"\"\"\nImplementation of FHIP's susceptibility formula D(u) for the Optical Absorption of Polarons.\n\nSee FHIP 1962, equation (35c):\nhttps://link.aps.org/doi/10.1103/PhysRev.127.1004.\n\"\"\"\n\n\"\"\"\nℜD(x::Float64, y::Float64, v::Float64, w::Float64, β::Float64)\n\n    Calculate the real part of D(u) (equation (35c) in FHIP) for a complex argument u = x + iy. v and w are the variational Polaron parameters that minimise the free energy, for the supplied α Frohlich coupling. β is the reduced thermodynamical beta = ħω/kT with k being Boltzman's constant.\n\"\"\"\nfunction ℜD(x, y, v, w, β)\n    R = (v^2 - w^2) / (w^2 * v)\n    P = 1 / (exp(v * β) - 1)\n    w^2 / v^2 * (\n        R * cos(v * x) * (exp(-v * y) + 2 * P * cosh(v * y)) - (x^2 - y^2) / β - y -\n        R * (2 * P + 1)\n    )\nend\n\n\"\"\"\nℑD(x::Float64, y::Float64, v::Float64, w::Float64, β::Float64)\n\n    Calculate the imaginary part of D(u) (equation (35c) in FHIP) for a complex argument u = x + iy. v and w are the variational Polaron parameters that minimise the free energy, for the supplied α Frohlich coupling. β is the reduced thermodynamical beta = ħω/kT with k being Boltzman's constant.\n\"\"\"\nfunction ℑD(x, y, v, w, β)\n    R = (v^2 - w^2) / (w^2 * v)\n    P = 1 / (exp(v * β) - 1)\n    w^2 / v^2 * (R * sin(v * x) * (exp(-v * y) - 2 * P * sinh(v * y)) - x * (2 * y / β - 1))\nend\n\n# Create a complex number from the real and imaginary parts of D(u).\n\nD(x, y, v, w, β) = ℜD(x, y, v, w, β) + 1im * ℑD(x, y, v, w, β)\n", "meta": {"hexsha": "f1786d97e6936a1973e34ed39550e2c9892ba82e", "size": 1483, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Functions/D(u)_function.jl", "max_stars_repo_name": "Neutrino155/PolaronMakie.jl", "max_stars_repo_head_hexsha": "8e641644b5667df28eac5e4369ca8bf63ab6c10d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-15T02:49:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-16T10:17:21.000Z", "max_issues_repo_path": "src/Functions/D(u)_function.jl", "max_issues_repo_name": "Neutrino155/PolaronMakie.jl", "max_issues_repo_head_hexsha": "8e641644b5667df28eac5e4369ca8bf63ab6c10d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-11-01T21:33:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-15T01:31:24.000Z", "max_forks_repo_path": "src/Functions/D(u)_function.jl", "max_forks_repo_name": "Neutrino155/PolaronMakie.jl", "max_forks_repo_head_hexsha": "8e641644b5667df28eac5e4369ca8bf63ab6c10d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0263157895, "max_line_length": 296, "alphanum_fraction": 0.5981119353, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7565812193042867}}
{"text": "export charλ,\n       charA,\n       charB\n\"\"\"\ncharλ(q,ν,k)\n\nchar value λ_(ν+k) for Mathieu's equation\n\ny'' + (λ_(ν+k) - 2 q cos( 2z )) y = 0\n\nwhere\n\nq ∈ ℝ       - parameter\nν ∈ [-1,1]  - fractional part of the non-integer order\nk ∈ ℤ⁺      - range of integer parts of the order\n\n\"\"\"\nfunction charλ(q::Real, nu_::Real; k::UnitRange=1:1) # reduced = true\n    #nu = reduced ? rem(nu_+1,2)-1 : nu_;\n    nu = rem(nu_+1,2)-1;\n\n    # Set matrix size using formula from Shirts paper (1993), Eqs. (2.1)-(2.2).\n    nu0 = nu + maximum(k)\n    C = (8.46 + 0.444*nu0)/(1 + 0.085*nu0)\n    D =  (0.24 + 0.0214*nu0)/(1 + 0.059*nu0)\n    N = ceil(Int, (nu0 + 2 + C*abs(q)^D)/2) # matrix size is 2N+1\n\n    (two, q2, nu2) = float.(promote(2, q, nu))\n    d0 = (two .* (-N:N) .- nu2).^2\n    d1 = q2 .* ones(eltype(q2), 2 * N)\n    A = SymTridiagonal(d0, d1)\n    a = eigvals(A, k)\n    return a\nend\n\n\"\"\"\ncharA(q; k=0:4)\n\nchar value A_k for Mathieu's equation\n\ny'' + (A_k - 2 q cos( 2z )) y = 0\n\nwhere\n\nq ∈ ℝ  - parameter\nk ∈ ℤ⁺ - eigenvalue index\n\n\"\"\"\nfunction charA(q::Real; k::UnitRange=1:1)\n    all(x -> x >= 0, k) || throw(DomainError(k, \"Indices must be non-negative integers.\"))\n\n    # Boolean indices of even and odd n values\n    ie = map(iseven, k)\n    io = map(!, ie)\n\n    a = Array{Float64}(undef ,length(k))\n    k1 = k .+ 1\n    a[ie] = charλ(abs(q), 0.0; k = k1)[ie]\n    if q>=0\n        a[io] = charλ(q, one(q); k = k1)[io]\n    else\n        if 0 in k # maybe not the cleanest way to do it\n            a[io] = charλ(abs(q), one(q); k = k[2]:last(k))[io[2:end]]\n        else\n            a[io] = charλ(abs(q), one(q); k=k)[io]\n        end\n    end\n    return a\nend\n\n\n\"\"\"\ncharB(q,k)\n\nchar value B_k for Mathieu's equation\n\ny'' + (B_k - 2 q cos( 2z )) y = 0\n\nwhere\n\nq ∈ ℝ  - parameter\nk ∈ ℤ  - eigenvalueindex\n\n\"\"\"\nfunction charB(q::Real; k::UnitRange=1:1)\n    all(x -> x > 0, k) || throw(DomainError(k, \"Indices must be positive integers.\"))\n    # Boolean indices of even and odd n values\n    ie = map(iseven, k)\n    io = map(!, ie)\n\n    b = Array{Float64}(undef, length(k))\n    b[ie] = charλ(q,0.0,k=k)[ie]\n    if q>=0\n        b[io] = charλ(q,1.0,k=k)[io]\n    else\n        b[io] = charλ(abs(q),1.0,k = (k .+ 1))[io]\n    end\n    return b\nend\n", "meta": {"hexsha": "80310f88127b6a1331aaa8b47c4fd9fd7dd93fc2", "size": 2221, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/char-values.jl", "max_stars_repo_name": "jlapeyre/MathieuFunctions.jl", "max_stars_repo_head_hexsha": "2e7ae9efb440dac54ecfd4414a77ea6f49996684", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/char-values.jl", "max_issues_repo_name": "jlapeyre/MathieuFunctions.jl", "max_issues_repo_head_hexsha": "2e7ae9efb440dac54ecfd4414a77ea6f49996684", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/char-values.jl", "max_forks_repo_name": "jlapeyre/MathieuFunctions.jl", "max_forks_repo_head_hexsha": "2e7ae9efb440dac54ecfd4414a77ea6f49996684", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.21, "max_line_length": 90, "alphanum_fraction": 0.5330932013, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7565812178676488}}
{"text": "f(x, y, z) = exp.(x .* y .* z) .* sin.(π .* x) .* sin.(π .* y) .* sin.(π .* z)\n\nfunction advection_dominated(;N = 50, β = 1000.0)\n    # Problem: Δu + βuₓ = f\n    # u = 0 on the boundaries\n    # f(x, y, z) = exp(xyz) sin(πx) sin(πy) sin(πz)\n    # 2nd order central differences (shows serious wiggles)\n\n    # Total number of unknowns\n    n = N^3\n\n    # Mesh width\n    h = 1.0 / (N + 1)\n\n    # Interior points only\n    xs = range(0, stop=1, length=N + 2)[2 : N + 1]\n\n    # The Laplacian\n    Δ = laplace_matrix(Float64, N, 3) ./ -h^2\n\n    # And the dx bit.\n    ∂x_1d = spdiagm(-1 => fill(-β / 2h, N - 1), 1 => fill(β / 2h, N - 1))\n    ∂x = kron(speye(N^2), ∂x_1d)\n\n    # Final matrix and rhs.\n    A = Δ + ∂x\n    b = reshape([f(x, y, z) for x ∈ xs, y ∈ xs, z ∈ xs], n)\n\n    A, b\nend\n\nfunction laplace_matrix(::Type{T}, n, dims) where T\n    D = second_order_central_diff(T, n)\n    A = copy(D)\n\n    for idx = 2 : dims\n        A = kron(A, speye(n)) + kron(speye(size(A, 1)), D)\n    end\n\n    A\nend\n\nsecond_order_central_diff(::Type{T}, dim) where {T} = convert(\n    SparseMatrixCSC{T, Int},\n    SymTridiagonal(fill(2 * one(T), dim), fill(-one(T), dim - 1))\n)\n", "meta": {"hexsha": "335a5aa25c36e2170789f675d20b732030d4c5df", "size": 1150, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmark/advection_diffusion.jl", "max_stars_repo_name": "wsshin/IterativeSolvers.jl", "max_stars_repo_head_hexsha": "ebc85d1b4ca2de33c022e668334b72fe3c8c7f6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2020-12-23T00:04:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T05:20:54.000Z", "max_issues_repo_path": "benchmark/advection_diffusion.jl", "max_issues_repo_name": "wsshin/IterativeSolvers.jl", "max_issues_repo_head_hexsha": "ebc85d1b4ca2de33c022e668334b72fe3c8c7f6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-12-22T03:24:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T15:21:21.000Z", "max_forks_repo_path": "benchmark/advection_diffusion.jl", "max_forks_repo_name": "wsshin/IterativeSolvers.jl", "max_forks_repo_head_hexsha": "ebc85d1b4ca2de33c022e668334b72fe3c8c7f6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2021-01-12T16:42:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T14:06:53.000Z", "avg_line_length": 24.4680851064, "max_line_length": 78, "alphanum_fraction": 0.5286956522, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7565812171404483}}
{"text": "\nexport cyclotomic\nexport jacobi, kronecker, moebius, necklace\n\nusing Primes\n\n\"\"\"\n    cyclotomic(P, n)\n\nCalculate cylotomic polynomial of degree `n` in polynom ring `P`.\nThis polynom is defined to be the disisor of `x^n - 1`, which is coprime to\nall `x^k - 1` with `k < n`.\n\nIf `n` is prime, `cyclotomic(P, n) = (x^n - 1) / (x - 1).\n\nIf `n` is squarefree (product of distinct primes `p1 * p2 * ... * pk`)\nand `c_k(x) = cyclotomic(P, p1*...*pk)` we use the recursion formula\n` c_(k+1)(x) = c_k(x^pk) / c_k(x)`.\n\nIf `v = p1*...*pk` with the distinct prime factors of `n`, we have\n`cyclotomic(P, n)(x) = cyclotomic(P, v)(x^(n/v))`.\n\"\"\"\nfunction cyclotomic(::Type{P}, n::Integer) where P<:UnivariatePolynomial\n    T = basetype(P)\n    (n < 2 || isprime(n)) && return P(ones(T, n))\n    f = factor(n)\n    l = length(f)\n    v = collect(keys(f))\n    v1 = prod(v)\n    q = P(ones(T, v[1]))\n    for k = 2:l\n        q = div(spread(q, v[k]), q)\n    end\n    n == v1 ? q : spread(q, n ÷ v1)\nend\n   \n\n# Jacobi symbol\nfunction jacobi(n::Integer, k::Integer)\n    k > 0 && k & 1 == 1 || throw(DomainError(k, \"k must be positive odd number\"))\n    n = mod(n, k)\n    t = 1\n    while n != 0\n        while n & 1 == 0\n            n >>= 1\n            r = k & 7\n            if r == 3 || r == 5\n                t = -t\n            end\n        end\n        n, k = k, n\n        if n & 3 == k & 3 == 3\n            t = -t\n        end\n        n = mod(n, k)\n    end\n    k == 1 ? t : 0\nend\n\n# Kronecker symbol\nfunction kronecker(n::Integer, k::Integer)\n    n&1 == 0 && k&1 == 0 && return 0\n    k == 0 && return n == 1 || n == -1 ? 1 : 0\n    ks = k < 0 && n < 0 ? -1 : 1\n    if k < 0\n        k = -k\n    end\n    t = trailing_zeros(k)\n    k >>= t\n    ks = (n&7 == 3 || n&7 == 5 ) && t&1 == 1 ? -ks : ks\n    jacobi(n, k) * ks\nend\n\n# moebius function\nfunction moebius(n::Integer)\n    n > 0 || throw(ArgumentError(\"moebius defined for positive integers only\"))\n    n == 1 && return 1\n    f = Primes.factor(n)\n    if maximum(values(f)) == 1\n        ifelse(isodd(length(f)), -1, 1)\n    else\n        0\n    end\nend\n\n# necklace polynomial - Moreau's necklace-counting function\n\"\"\"\n    necklace(q, n)\n\nReturn the value of the `necklace polynomial`\n\nCount of irreducible monic polynomials of degree n over Z/q.\n\"\"\"\nnecklace(q::Integer, n::Integer) = _necklace(q, n) ÷ n\nnecklace(q::Ring, n::Integer) = _necklace(q, n) / n\nfunction _necklace(q, n::Integer)\n    f = Primes.factor(n)\n    p = collect(keys(f))\n    m = length(p)\n    s = 0\n    for x = 0:(2^m-1)\n        d = n\n        μ = 1\n        k = 1\n        while x != 0\n            if x & 1 == 1\n                d ÷= p[k]\n                μ = -μ\n            end\n            x >>= 1\n            k += 1\n        end\n        s += q^d * μ\n    end\n    s\nend\n\n", "meta": {"hexsha": "8bab5d9764ad58e814191314026352dd7c01f885", "size": 2750, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/numbertheoretical.jl", "max_stars_repo_name": "KlausC/CommutativeRings.jl", "max_stars_repo_head_hexsha": "2b6027c126b90f61bbad4ea230a34367522c3e52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-07-31T16:28:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T17:49:20.000Z", "max_issues_repo_path": "src/numbertheoretical.jl", "max_issues_repo_name": "KlausC/CommutativeRings.jl", "max_issues_repo_head_hexsha": "2b6027c126b90f61bbad4ea230a34367522c3e52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-02-10T17:16:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T14:30:03.000Z", "max_forks_repo_path": "src/numbertheoretical.jl", "max_forks_repo_name": "KlausC/CommutativeRings.jl", "max_forks_repo_head_hexsha": "2b6027c126b90f61bbad4ea230a34367522c3e52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-14T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:05:39.000Z", "avg_line_length": 23.3050847458, "max_line_length": 81, "alphanum_fraction": 0.4967272727, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7565812171226851}}
{"text": "function representable_ints(nbits)\n    return 1:(2^(nbits-1)-1)\nend\n\nfunction representable_floats(nbits,ebits)\n    #= returns an array of all representable positive floats exclusive 0 and ComplexInfinity.\n    nbits is the total number of bits (sign,exponent,significand)\n    ebits is the number of exponent bits\n    =#\n\n    # derived constants\n    bias = 2^(ebits-1) - 1\n    sbits = nbits-ebits-1     # number of significand bits (minus one for sign bit)\n\n    repr_floats = []           # represented as 000...0000\n\n    # subnormal numbers (exponent is 0)\n    for f = 1:2^sbits-1\n        append!(repr_floats,2.0^(1-bias)*(f/2^sbits))\n    end\n\n    # all other numbers\n    for e = 1:2^ebits-2     # the exponent cannot be 11...111 this represents NaN\n        for f = 0:2^sbits-1\n            append!(repr_floats,2.0^(e-bias)*(1.0 + f/2^sbits))\n        end\n    end\n\n    return Float64.(repr_floats)\nend\n\nfunction wcdp_posit(plist)\n    p_am = (plist[1:end-1]+plist[2:end])/2.\n    p_wda = -log10.(abs.(log10.(p_am./plist[1:end-1])))\n\n    # extend first and last point, taking no overflow/underflow into account\n    p0 = plist[1]/16    # something much smaller than minpos\n    pinf = plist[end]*16    # something much bigger than maxpos\n\n    p_wda_0 = -log10.(abs.(log10.(p0/plist[2]))) # worst-case decimal accuracy for these extreme values\n    p_wda_inf = -log10.(abs.(log10.(pinf/plist[end])))\n\n    # worst-case decimal accuracy of interpolated on minpos/maxpos\n    p_wda_minpos = p_wda_0 + log10(plist[1]/p0)/log10(p0/p_am[1])*(p_wda_0-p_wda[1])\n    p_wda_maxpos = p_wda_inf + log10(plist[end]/pinf)/log10(pinf/p_am[end])*(p_wda_inf-p_wda[end])\n\n    p_wda = vcat(p_wda_0,p_wda_minpos,p_wda,p_wda_maxpos,p_wda_inf)\n    p_am = vcat(p0,plist[1],p_am,plist[end],pinf)\n\n    return p_am,p_wda,plist\nend\n\nfunction wcdp_float(flist)\n\n    f_am = (flist[1:end-1]+flist[2:end])/2.\n    f_wda = -log10.(abs.(log10.(f_am./flist[1:end-1])))\n\n    # extend with zeros due to overflow\n    f_wda = vcat(0.55,f_wda)        # extrapolate somehow\n    f_am = vcat(flist[1],f_am)\n\n    return f_am,f_wda\nend\n\nfunction wcdp_approx(flist)\n\n    f_am = (flist[1:end-1]+flist[2:end])/2.\n    f_wda = -log10.(abs.(log10.(f_am./flist[1:end-1])))\n\n    return f_am,f_wda\nend\n\nfunction wc_dec_acc_int(nbits)\n\n    # assume rounding mode down\n    # somehow interpolate with 0.13 onto the smallest representable number 1...\n\n    i_am = [1.,2.,2^(nbits-1)-1]\n    i_wda = [0.13,-log10(abs(log10(2))),-log10(abs(log10((2^(nbits-1)-1)/(2^(nbits-1)-2))))]\n\n    return i_am,i_wda\nend\n\ndecprec(xe,xr) = -log10.(abs.(log10.(xe./xr)))\n", "meta": {"hexsha": "3b301ebb06acf2154e7137a966a4fa2a316d1c18", "size": 2585, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "figs/representable_numbers.jl", "max_stars_repo_name": "milankl/LogFixPoints.jl", "max_stars_repo_head_hexsha": "b0d418700193579064a0e0f824d5b6beb8603c99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-07-31T18:59:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-04T09:54:06.000Z", "max_issues_repo_path": "figs/representable_numbers.jl", "max_issues_repo_name": "milankl/LogFixPoints.jl", "max_issues_repo_head_hexsha": "b0d418700193579064a0e0f824d5b6beb8603c99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-10-03T14:42:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-16T17:23:24.000Z", "max_forks_repo_path": "figs/representable_numbers.jl", "max_forks_repo_name": "milankl/LogFixPoints.jl", "max_forks_repo_head_hexsha": "b0d418700193579064a0e0f824d5b6beb8603c99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-14T08:21:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T08:21:02.000Z", "avg_line_length": 30.4117647059, "max_line_length": 103, "alphanum_fraction": 0.653384913, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7565259935884143}}
{"text": "# given an 1D interval, return quadrature nodes and weights\n\nusing LinearAlgebra\nusing FastGaussQuadrature\n\nfunction quadgrid(xmin, xmax, n)\n    # get nodes and weights in reference coord [-1, 1]\n    x, w = gausslegendre(n)\n    # map nodes and weights to current interval\n    dist = (xmax - xmin)/2\n    center = (xmax + xmin)/2\n    weights = dist .* w\n    nodes = dist .* x .+ center\n    return nodes, weights\nend\n\nfunction quadgrid_old(xmin, xmax, n)\n    dist = (xmax - xmin)/2\n    center = (xmax + xmin)/2\n    if n == 1\n        w = 2\n        x = 0\n    elseif n == 2\n        w = [1, 1]\n        x =  1/sqrt(3) * [1, -1]\n    elseif n == 3\n        w = [5/9, 8/9, 5/9]\n        x = -sqrt(3/5) * [-1, 0, 1]\n    elseif n == 4\n        w = [(18+sqrt(30))/36, (18+sqrt(30))/36,\n             (18-sqrt(30))/36, (18-sqrt(30))/36]\n        x = [sqrt(3/7 - 2/7*sqrt(6/5)), -sqrt(3/7 - 2/7*sqrt(6/5)), \n             sqrt(3/7 + 2/7*sqrt(6/5)), -sqrt(3/7 + 2/7*sqrt(6/5))]\n    elseif n == 5\n        w = [128/225, (322+13*sqrt(70))/900, (322+13*sqrt(70))/900,\n                      (322-13*sqrt(70))/900, (322-13*sqrt(70))/900]\n        x = [0, sqrt(5-2*sqrt(10/7))/3, -sqrt(5-2*sqrt(10/7))/3,\n                sqrt(5+2*sqrt(10/7))/3, -sqrt(5+2*sqrt(10/7))/3]\n    end\n\n    w_new = dist .* w\n    x_new = dist .* x .+ center\n    # fx = f.(x_new)\n    # int = dot(w_new, fx)\n\n    return x_new, w_new\n\nend\n", "meta": {"hexsha": "cf96aaa374d99db0a11abadc93e05cf1726e4d06", "size": 1380, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "individual_implementations/BTG_xinran/src/quadrature/quadgrid.jl", "max_stars_repo_name": "dbindel/btg", "max_stars_repo_head_hexsha": "83616be1d1c4d80f385fa95cef38753f39a3a4c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-09-18T04:52:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-03T18:58:55.000Z", "max_issues_repo_path": "individual_implementations/BTG_xinran/src/quadrature/quadgrid.jl", "max_issues_repo_name": "dbindel/btg", "max_issues_repo_head_hexsha": "83616be1d1c4d80f385fa95cef38753f39a3a4c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "individual_implementations/BTG_xinran/src/quadrature/quadgrid.jl", "max_forks_repo_name": "dbindel/btg", "max_forks_repo_head_hexsha": "83616be1d1c4d80f385fa95cef38753f39a3a4c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-06T06:07:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-06T06:07:50.000Z", "avg_line_length": 28.1632653061, "max_line_length": 68, "alphanum_fraction": 0.502173913, "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7565259916815879}}
{"text": "\n# Used \"Conjugate Bayesian analysis of the Gaussian distribution\" by Murphy as\n# a reference.  Note that there were some typos in that document so the code\n# here may not correspond exactly.\n\nimmutable NormalInverseWishart <: Distribution\n    dim::Int\n    zeromean::Bool\n    mu::Vector{Float64}\n    kappa::Float64              # This scales precision (inverse covariance)\n    Lamchol::Cholesky{Float64}  # Covariance matrix (well, sqrt of one)\n    nu::Float64\n\n    function NormalInverseWishart(mu::Vector{Float64}, kappa::Real,\n                                  Lamchol::Cholesky{Float64}, nu::Real)\n        # Probably should put some error checking in here\n        d = length(mu)\n        zmean::Bool = true\n        for i = 1:d\n            if mu[i] != 0.\n                zmean = false\n                break\n            end\n        end\n        new(d, zmean, mu, float64(kappa), Lamchol, float64(nu))\n    end\nend\n\nfunction NormalInverseWishart(mu::Vector{Float64}, kappa::Real,\n                              Lambda::Matrix{Float64}, nu::Real)\n    NormalInverseWishart(mu, kappa, cholfact(Lambda), nu)\n    \nend\n\nfunction insupport(::Type{NormalInverseWishart}, x::Vector{Float64}, Sig::Matrix{Float64})\n    return (all(isfinite(x)) &&\n           size(Sig, 1) == size(Sig, 2) &&\n           isApproxSymmmetric(Sig) &&\n           size(Sig, 1) == length(x) &&\n           hasCholesky(Sig))\nend\n\npdf(niw::NormalInverseWishart, x::Vector{Float64}, Sig::Matrix{Float64}) =\n        exp(logpdf(niw, x, Sig))\n\nfunction logpdf(niw::NormalInverseWishart, x::Vector{Float64}, Sig::Matrix{Float64})\n    if !insupport(NormalInverseWishart, x, Sig)\n        return -Inf\n    else\n        p = size(x, 1)\n\n        nu = niw.nu\n        kappa = niw.kappa\n        mu = niw.mu\n        Lamchol = niw.Lamchol\n        hnu = 0.5 * nu\n        hp = 0.5 * p\n    \n        # Normalization\n        logp::Float64 = hnu * logdet(Lamchol)\n        logp -= hnu * p * log(2.)\n        logp -= lpgamma(p, hnu)\n        logp -= hp * (log(2.*pi) - log(kappa))\n        \n        # Inverse-Wishart\n        logp -= (hnu + hp + 1.) * logdet(Sig)\n        logp -= 0.5 * trace(Sig \\ (Lamchol[:U]' * Lamchol[:U]))\n        \n        # Normal\n        z = niw.zeromean ? x : x - mu\n        logp -= 0.5 * kappa * invquad(PDMat(Sig), z) \n\n        return logp\n\n    end\nend\n\nfunction rand(niw::NormalInverseWishart)\n    Sig = rand(InverseWishart(niw.nu, niw.Lamchol))\n    mu = rand(MvNormal(niw.mu, Sig ./ niw.kappa))\n    return (mu, Sig)\nend\n\n", "meta": {"hexsha": "0238a8d8b70777b403c1cba02dca6be1906cda4f", "size": 2479, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/conjugates/normalinversewishart.jl", "max_stars_repo_name": "davidanthoff/Distributions.jl", "max_stars_repo_head_hexsha": "75a04ebc12f3643392d33240a4029d458f86e7f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-08-08T03:44:46.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-08T03:44:46.000Z", "max_issues_repo_path": "src/conjugates/normalinversewishart.jl", "max_issues_repo_name": "davidanthoff/Distributions.jl", "max_issues_repo_head_hexsha": "75a04ebc12f3643392d33240a4029d458f86e7f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/conjugates/normalinversewishart.jl", "max_forks_repo_name": "davidanthoff/Distributions.jl", "max_forks_repo_head_hexsha": "75a04ebc12f3643392d33240a4029d458f86e7f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5119047619, "max_line_length": 90, "alphanum_fraction": 0.5699878983, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368928, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7565259889094855}}
{"text": "#=\nSurprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:\n\n1634 = 14 + 64 + 34 + 44\n8208 = 84 + 24 + 04 + 84\n9474 = 94 + 44 + 74 + 44\nAs 1 = 14 is not a sum it is not included.\n\nThe sum of these numbers is 1634 + 8208 + 9474 = 19316.\n\nFind the sum of all the numbers that can be written as the sum of fifth powers of their digits.\n=#\n#=\nNote: Calculating limit:\nChecking the number 111111111.\nThat number has 9 digits, so the maximum sum would be 9*59049 = 531441, which doesn't even come close to 111111111.\nSo any 9 digit number or greater can't ever reach a big enough sum.\n=#\nfunction sumofdigitpowers(a)\n  total, i = 0, 2\n  while i < length(digits(i))*9^a\n    current = sum(map((x)->x^a, digits(i)))\n    if current == i\n      total += i\n    end\n    i+=1\n  end\n  total\nend\n@time println(sumofdigitpowers(5))\n", "meta": {"hexsha": "f43d119d137034498cfd32c739165cf79ac0afb1", "size": 864, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p30.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p30.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p30.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 27.8709677419, "max_line_length": 115, "alphanum_fraction": 0.6828703704, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7565259863136593}}
{"text": "test_str = \"939\n7,13,x,x,59,x,31,19\"\n\ntest_list = split(test_str, '\\n')\n\nlist = readlines(\"day13_input.txt\")\n\nfunction departure_time(list)\n    earliest = parse(Int, list[1])\n    buses = map(x-> parse(Int, x), split(replace(list[2], \",x\" => \"\"), ','))\n    next_departures = Dict(map(x->(div(earliest, x) + 1 ) * x => x, buses))\n    departure = minimum(keys(next_departures))\n    return (departure - earliest) * next_departures[departure]\nend\n\n@show departure_time(test_list)\n@show departure_time(list)\n@show departure_time(test_list) == 295\n@show departure_time(list) == 246\n\nfunction time_stamp(line)\n    buses = map(x-> parse(Int, x), split(replace(line, \"x\" => \"-1\"), ','))\n    imax = argmax(buses .+ Array(0:-1:1-length(buses)))\n    bmax = buses[imax]\n    n = 1\n    t = n*bmax + 1 - imax\n    len = length(buses)\n    while !all(≤(0), map(i->mod(t+i-1, buses[i]), 1:len))\n        n += 1\n        t = n*bmax + 1 - imax\n    end\n    return t\nend\n\n@show time_stamp(test_list[2])\n\n@show time_stamp(\"17,x,13,19\") == 3417\n@show time_stamp(\"67,7,59,61\") == 754018\n@show time_stamp(\"67,x,7,59,61\") == 779210\n@show time_stamp(\"67,7,x,59,61\") == 1261476\n@show time_stamp(\"1789,37,47,1889\") == 1202161486\n#@show time_stamp(list[2]) # Too slow\n\n# Implementing algorithm for solving linear Diophantine equations as\n# explained in https://www.math.uwaterloo.ca/~wgilbert/Research/GilbertPathria.pdf\n# but there is some bug. It works on all test examples, but not on the problem list.\n\nfunction time_stamp_diophantine(line)\n    buses = map(x-> parse(Int, x), split(replace(line, \"x\" => \"0\"), ','))\n    running = [b for b=buses if b > 0]\n    delays = [1-i for i=1:length(buses) if buses[i] > 0]\n    offset = (mod.(running+delays,running))[2:end]\n    len=length(running)\n    T = fill(0, len, len)\n    for i=1:len\n        T[i,i] = 1\n    end\n    A = fill(0, len-1, len)\n    for i=1:len-1\n        A[i,1] = running[1]\n        A[i,i+1] = - running[i+1]\n    end\n    R = deepcopy(A')\n    for i=2:len\n        while R[i,i-1] ≠ 0\n            if abs(R[i-1,i-1]) > abs(R[i, i-1])\n                a = div(R[i-1,i-1], R[i, i-1])\n                if mod(R[i-1,i-1], R[i, i-1]) == 0\n                    a -= 1                    \n                end\n                R[i-1,:] .-= a * R[i, :]\n                T[i-1,:] .-= a * T[i,:]\n            else\n                a = div(R[i, i-1], R[i-1,i-1])\n                R[i,:] .-= a * R[i-1,:]\n                T[i,:] .-= a * T[i-1,:]\n            end\n        end\n    end\n    k = BigInt.((R[1:end-1,:]')\\offset)\n    k = [k; BigInt(floor(-sum([T[i,1]*k[i]/T[len,1] for i=1:len-1])))]\n    n1 = sum([T[i,1]*k[i] for i=1:len])\n#    while !all(>(0), [sum([T[i,j]*k[i] for i=1:len]) for j=1:len])\n    while n1 < 0\n        k[len] += sign(T[len,1])\n        n1 = sum([T[i,1]*k[i] for i=1:len])\n    end\n        \n    t = n1*running[1]\n    return running, offset, len, A, T, R, k, n1, t\nend\n\n@show time_stamp_diophantine(test_list[2])[end] == 1068781\n@show time_stamp_diophantine(\"7,13,x,x,59,x,31,19\")[end] == 1068781\n@show time_stamp_diophantine(\"17,x,13,19\")[end] == 3417\n@show time_stamp_diophantine(\"67,7,59,61\")[end]  == 754018\n@show time_stamp_diophantine(\"67,x,7,59,61\")[end]  == 779210\n@show time_stamp_diophantine(\"67,7,x,59,61\")[end]  == 1261476\n@show time_stamp_diophantine(\"1789,37,47,1889\")[end]  == 1202161486\n@show time_stamp_diophantine(list[2])[end] == 939490236001473\n\nfunction test_result(line)\n    running, offset, len, A, T, R, k, n1, t = time_stamp_diophantine(line)\n\n    check = all(>(0), [sum([T[i,j]*k[i] for i=1:len]) for j=1:len])\n    timings = (T'k) .* running\n    check_offset = timings[2:end] - fill(timings[1], len-1)\n    difference = all(==(0), check_offset + offset)\n    return check, difference, T*A'==R\nend\n\n# Using the algorithm for the Chinese Remainder Theorem\n\nfunction time_stamp_CRG(line)\n    buses = map(x-> parse(Int, x), split(replace(line, \"x\" => \"0\"), ','))\n    running = [b for b=buses if b > 0]\n    offset = [mod(b+1-i,b) for (i,b) in enumerate(buses) if b>0]\n    N = prod(running)\n    d = div.(N,running)\n    result = sum(offset .* d .* invmod.(d,running))\n    return mod(result, N)\nend\n\n# There is an option to use Mods.jl package, which already has an implemention\n# of the Chinese Remainder Theorem, as I learned from other Humans of Julia on \n# Discord, but it is more obscure and slower, I prefer the direct implementation\n# above.\n\nusing Mods\n\nfunction time_stamp_ModsCRT(line)\n    buses = map(x-> parse(Int, x), split(replace(line, \"x\" => \"0\"), ','))\n    running = [b for b=buses if b > 0]\n    x_delays = [i-1 for i=1:length(buses) if buses[i] > 0]\n    mod_prep = Mod[Mod(b,d) for (d,b) in zip(running, x_delays)]\n    rem = Mods.CRT(mod_prep...)\n    return modulus(rem) - rem.val\nend\n\n@show time_stamp_CRG(test_list[2]) == 1068781\n@show time_stamp_CRG(list[2]) == 939490236001473\n@show time_stamp_ModsCRT(test_list[2]) == 1068781\n@show time_stamp_ModsCRT(list[2]) == 939490236001473\n\n#= \n```julia\njulia> @btime time_stamp_ModsCRT(list[2])\n  23.110 μs (45 allocations: 5.47 KiB)\n939490236001473\n\njulia> @btime time_stamp_CRG(list[2])\n  15.109 μs (24 allocations: 5.28 KiB)\n939490236001473\n```\n =#\n \nnothing\n\n#= \n\nIf `x=buses` (with `x=-1` if bus = 'x'), time `t` is given by the condition\nthat `t+i-1` is an integer multiple of `x[i]`, i.e. `mod(t+i-1,x) == 0` or \n`mod(t, x) = 1-i` or `mod(t,x) = x-i+1`\n\nIn case `t` is not so big, we can just search for this condition\nby stepping up `t` by multiples of `x[1]`. That was my first approach,\nwhich works fast for the test set. But for the real list, that is not \ncomputationally feasible. So we do differently.\n\nThe conditions \n\n    `t + i - 1 = nᵢ xᵢ,   ∀ i=1:length(x) s.th. xᵢ > 0`\n\nare equivalent to \n    `t = n₁x₁ = n₂x₂ - 1 = ⋯ = nᵢxᵢ - i + 1,     ∀ i, with xᵢ > 0`\n\nAnd we know that `x₁ > 0`. Hence we just iterate over `i` to find\n\n    `For i = 1:\n        n₁¹ = 1\n    For i = 2:\n        n₂² such that n₂²x₂ - 1 = jn₁¹x₁\n        n₁² = j₂²n₁¹\n    For i = 3:\n        n₃³ such that n₃³x₂ - 2 = jn₁²x₁\n        n₁² = jn₁²\n    `n₁ such that t = n₁ x₁`\n    `n₂ such that n₂x₂ - 1 = `\n\n```julia\nn = 1\nfor i = 2:length(x)\n    j = 1\n    while mod(j*n*buses[i]-i+1, buses[1]) > 0\n        j += 1\n    end\n    n *= j\nend\n```    \n\nBut this is slow in some cases. So we notice the problem can also be written as\n    `t = 0 (mod x₁); t = x₂-1 (mod x₂); … t = xᵢ+1-i (mod xᵢ); …`\n\nwhich is in the context of the Chinese Remainder Problem (see e.g. \n[Chinese Remainder Theorem](https://en.wikipedia.org/wiki/Chinese_remainder_theorem))\nand [Chinese Remainder Theorem with algorithm](https://shainer.github.io/crypto/math/2017/10/22/chinese-remainder-theorem.html))\n\nAn algorithm, in python, from the latter homepage, is the following\n\ndef ChineseRemainderGauss(x, a):\n    \"\"\"\n    Return t such that mod(t,xᵢ) = aᵢ, ∀i=1,…,n, if 0 ≤ aᵢ< xᵢ \n    and the xᵢ are pairwise coprime.\n    \"\"\"\n    from math import prod\n    P = prod(x)\n    result = 0\n\n    for i in range(len(n)):\n        ai = a[i]\n        xi = x[i]\n        bi = P // xi\n\n        result += ai * bi * invmod(bi, xi)\n\n    return result % P\n\nSee also https://shainer.github.io/crypto/math/2017/10/22/chinese-remainder-theorem.html\n\n =#", "meta": {"hexsha": "ead44b8cc5058c5f23140078684c826a418d5167", "size": 7176, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "aoc2020/day13_busdeparture.jl", "max_stars_repo_name": "rmsrosa/adventofcode2020", "max_stars_repo_head_hexsha": "7a14a4c08eb33c9d02b97b1fbe63a150c81b2ade", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aoc2020/day13_busdeparture.jl", "max_issues_repo_name": "rmsrosa/adventofcode2020", "max_issues_repo_head_hexsha": "7a14a4c08eb33c9d02b97b1fbe63a150c81b2ade", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aoc2020/day13_busdeparture.jl", "max_forks_repo_name": "rmsrosa/adventofcode2020", "max_forks_repo_head_hexsha": "7a14a4c08eb33c9d02b97b1fbe63a150c81b2ade", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2, "max_line_length": 128, "alphanum_fraction": 0.5944816054, "num_tokens": 2533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.7565259850424417}}
{"text": "using Plots\n\nfunc1(R) = R/2\nfunc2(R) = R/2 + [1 ; 0]\nfunc3(R) = R/2 + [0 ; 1]\nP = 200\nnum = 500000\nx = []\ny = []\nfor i in 1:num\n    point = [rand() ; rand()]\n    for j in 1:P\n        point = rand([func1(point), func2(point), func3(point)])\n    end\n    push!(x, point[1])\n    push!(y, point[2])\nend\n\nscatter(x,y,markersize = 0.000001, legend = false, border=:none, dpi=500)\nsavefig(\"C:\\\\Users\\\\Yaghoub\\\\Documents\\\\GitHub\\\\A-few-fractals-in-Julia\\\\Fractals-Fig\\\\SRT.png\")\n", "meta": {"hexsha": "e6edc41eca59d83d2379d862a20be1379e8fb655", "size": 470, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Fractals-code/Sierpinski-random-triangle.jl", "max_stars_repo_name": "shahmari/A-few-fractals-in-Julia", "max_stars_repo_head_hexsha": "bf0373174af16d1473e8e865377cac061b7191d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-25T09:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T12:35:32.000Z", "max_issues_repo_path": "Fractals-code/Sierpinski-random-triangle.jl", "max_issues_repo_name": "shahmari/A-few-fractals-in-Julia", "max_issues_repo_head_hexsha": "bf0373174af16d1473e8e865377cac061b7191d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Fractals-code/Sierpinski-random-triangle.jl", "max_forks_repo_name": "shahmari/A-few-fractals-in-Julia", "max_forks_repo_head_hexsha": "bf0373174af16d1473e8e865377cac061b7191d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.380952381, "max_line_length": 96, "alphanum_fraction": 0.585106383, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.8104789109591831, "lm_q1q2_score": 0.7565259841771661}}
{"text": "using StructuresKit\n\nE = 29000.0\nσy = 50.0                   #steel yield stress\nσy1 = 50.0                  #steel yield stress\nσu = 65.3                   #steel ultimate stress\nσf=σy * (1 + 0.10)      #steel fracture stress#\nϵy = σy / E              #steel yield strain\nϵy1 = σy / E * 10    #steel strain at end of yield plateau\nϵu = 0.18             #steel ultimate strain\nϵf = 0.21             #steel fracture strain\nn = 11\n\n\n\nσ, ϵ  = MaterialModels.steel(σy, σy1, σu, σf, ϵy, ϵy1, ϵu, ϵf, n)\n\nusing Plots\nplot(σ, ϵ, markershape = :o)\n\n\nshape_name = \"W14X90\"\n\nshape_info = CrossSection.AISC(shape_name)\n\nn_Wshape=(4, 2, 4, 4, 4)\n\nxcoords, ycoords = CrossSection.wshape_nodes(shape_info, n_Wshape)\n\nplot(xcoords, ycoords, markershape = :o)\n\n\n# using TriangleMesh\n\nmesh_size = 0.01\nmesh = CrossSection.triangular_mesh(xcoords, ycoords, mesh_size)\n\nAi, cxi, cyi = CrossSection.triangular_mesh_properties(mesh)\n\ncx, cy = CrossSection.centroid_from_cells(Ai, cxi, cyi)\n\n\nIx = CrossSection.moment_of_inertia_from_cells(Ai, cyi, cy)\nIy = CrossSection.moment_of_inertia_from_cells(Ai, cxi, cx)\n\n\n\n\n# #discretize cross-section with a triangular mesh\n# function triangular_mesh(xcoords, ycoords, mesh_size)\n\n#     num_nodes = length(xcoords)\n#     num_segments = num_nodes\n\n#     # n_point, n_point_marker, n_point_attribute, n_segment, n_holes\n#     poly = TriangleMesh.Polygon_pslg(num_nodes, 1, 0, num_segments, 0)\n\n#     node = [xcoords ycoords]\n#     set_polygon_point!(poly, node)\n\n#     node_marker = ones(Int, num_nodes, 1)\n#     set_polygon_point_marker!(poly, node_marker)\n\n#     segments = zeros(Int, num_segments, 2)\n#     for i=1:num_segments\n\n#         if i == num_segments\n#             segments[i, 1:2] = [i, 1]\n#         else\n#             segments[i, 1:2] = [i, i+1]\n#         end\n\n#     end\n\n#     set_polygon_segment!(poly, segments)\n\n#     segment_markers = ones(Int, num_segments)\n#     set_polygon_segment_marker!(poly, segment_markers)\n\n#     #switches from https://www.cs.cmu.edu/~quake/triangle.html\n#     switches = \"penvVa\" * string(mesh_size) * \"D\"\n\n#     mesh = create_mesh(poly, switches)\n\n#     return mesh\n\n# end\n\n\n#calculate triangle areas\n\n\n# # https://keisan.casio.com/has10/SpecExec.cgi?path=05000000.Mathematics%252F01000500.Plane%2520geometry%252F10010300.Area%2520of%2520a%2520triangle%2520with%2520three%2520points%252Fdefault.xml&charset=utf-8\n# function triangle_area(x1, y1, x2, y2, x3, y3)\n\n#     A = abs((x1*y2 + x2*y3 + x3*y1 - y1*x2 - y2*x3 - y3*x1)/2)\n\n# end\n\n# #https://www.mathopenref.com/coordcentroid.html\n# function triangle_centroid(x1, y1, x2, y2, x3, y3)\n\n#     cx = (x1 + x2 + x3)/3\n#     cy = (y1 + y2 + y3)/3\n\n#     return cx, cy\n\n# end\n\n\n# function triangulation_properties(mesh)\n\n#     #calculate cell area and centroid\n#     Ai = zeros(Float64, mesh.n_cell)\n#     cxi = zeros(Float64, mesh.n_cell)\n#     cyi = zeros(Float64, mesh.n_cell)\n\n#     for i = 1:mesh.n_cell\n\n#         p1 = mesh.cell[1, i]\n#         p2 = mesh.cell[2, i]\n#         p3 = mesh.cell[3, i]\n\n#         x1 = mesh.point[1, p1]\n#         y1 = mesh.point[2,p1]\n#         x2 = mesh.point[1, p2]\n#         y2 = mesh.point[2,p2]\n#         x3 = mesh.point[1, p3]\n#         y3 = mesh.point[2,p3]\n\n#     Ai[i] = triangle_area(x1, y1, x2, y2, x3, y3)\n\n#     cxi[i], cyi[i] = triangle_centroid(x1, y1, x2, y2, x3, y3)\n\n#     end\n\n#     return Ai, cxi, cyi\n\n# end\n\n\n# #calculate cross-sectional area from cells\n\n# # function area_from_cells(Ai)\n\n# #     A = sum(Ai)\n\n# # end\n\n# # #calculate cross-section centroid from cells\n\n# # function centroid_from_cells(Ai, cxi, cyi)\n\n# #     A = area_from_cells(Ai)\n\n# #     cx = sum(cxi .* Ai) / A\n# #     cy = sum(cyi .* Ai) / A\n\n# #     return cx, cy\n\n# # end\n\n\n# cx, cy = CrossSection.centroid_from_cells(Ai, cxi, cyi)\n\n\n# # function moment_of_inertia_from_cells(Ai, ci, c)\n\n# #     I = sum(((c .- ci) .^2 .* Ai))\n\n# #     return I\n\n# # end\n\n# Ix = moment_of_inertia_from_cells(Ai, cyi, cy)\n# Iy = moment_of_inertia_from_cells(Ai, cxi, cx)\n\n\n\n\n\n# #calculate triangle centroids\n\n\n\n\n# # for i = 1:mesh.n_cell\n\n# #     p1 = mesh.cell[1, i]\n# #     p2 = mesh.cell[2, i]\n# #     p3 = mesh.cell[3, i]\n\n# #     x1 = mesh.point[1, p1]\n# #     y1 = mesh.point[2,p1]\n# #     x2 = mesh.point[1, p2]\n# #     y2 = mesh.point[2,p2]\n# #     x3 = mesh.point[1, p3]\n# #     y3 = mesh.point[2,p3]\n\n# #    cx[i] = triangle_area(x1, y1, x2, y2, x3, y3)\n\n# # end\n\n# zcoords = zeros(Float64, mesh.n_point)\n# coordinates = [mesh.point[1,:] mesh.point[2,:] zcoords]\n\n# connectivity = mesh.cell'\n\n# using Makie\n# scene = Makie.poly(coordinates, connectivity, color=:lightgray, shading=:true, show_axis=:true, overdraw=:false, strokecolor = (:black, 0.6), strokewidth = 1)\n   \n\n\n\n# poly = polygon_Lshape()\n# mesh = create_mesh(poly, info_str=\"my mesh\", voronoi=true, delaunay=true, set_area_max=true)\n\n\n# node = [1.0 0.0 ; 0.0 1.0 ; -1.0 0.0 ; 0.0 -1.0 ;\n#         0.25 0.25 ; -0.25 0.25 ; -0.25 -0.25 ; 0.25 -0.25] \n\n#         # size is number_segments x 2\n# seg = [1 2 ; 2 3 ; 3 4 ; 4 1 ; 5 6 ; 6 7 ; 7 8 ; 8 5] \n\n\n# # all points get marker 1\n# node_marker = [ones(Int,4,1) ; 2*ones(Int,4,1)]\n# # last segment gets a different marker\n# seg_marker = [ones(Int,4) ; 2*ones(Int,4)]\n\n\n# # size is number_points x number_attr\n# node_attr = rand(8,2) \n\n\n# # size is number_holes x 2\n# hole = [0.5 0.5] \n\n\n\n\n\n\n\n\n\n# polygon_struct_from_points\n\n\n# shape_mesh, cross_section_edges = Mesh.open_cross_section_tessellation(xcoords, ycoords)\n\n# connectivity = zeros(Int, length(shape_mesh), 3)\n# for i=1:length(shape_mesh)\n#     connectivity[i, :] = shape_mesh[i]\n# end\n\n", "meta": {"hexsha": "2c0870c8e18a7f5510d128b76115699f2644b7bd", "size": 5592, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/MaterialModels/MaterialModelsTest1.jl", "max_stars_repo_name": "runtosolve/StructuresKit.jl", "max_stars_repo_head_hexsha": "cc5d78a39f2391e52f91ab85cd93328e83e12508", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-10-22T04:59:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T22:29:05.000Z", "max_issues_repo_path": "test/MaterialModels/MaterialModelsTest1.jl", "max_issues_repo_name": "runtosolve/StructuresKit.jl", "max_issues_repo_head_hexsha": "cc5d78a39f2391e52f91ab85cd93328e83e12508", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-08-08T17:30:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-07T17:06:39.000Z", "max_forks_repo_path": "test/MaterialModels/MaterialModelsTest1.jl", "max_forks_repo_name": "runtosolve/StructuresKit.jl", "max_forks_repo_head_hexsha": "cc5d78a39f2391e52f91ab85cd93328e83e12508", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-10T03:42:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:42:15.000Z", "avg_line_length": 21.7587548638, "max_line_length": 209, "alphanum_fraction": 0.6167739628, "num_tokens": 1955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308128813471, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7565259801338464}}
{"text": "\"\"\"\nBetina Robust Sampled based Formulation\n\nFurther information:\n  - Fernandes, B., Street, A., ValladA˜ £o, D., e Fernandes, C. (2016). An adaptive robust portfolio optimization model with loss constraints based on data-driven polyhedral uncertainty sets. European Journal of Operational Research, 255(3):961 – 970. ISSN 0377-2217. URL.\n\n\"\"\"\nstruct RobustBetina <: AbstractSampleBased\n    sampled_returns::Array{Float64,2}\n    number_of_assets::Int\n    number_of_samples::Int\nend\n\nfunction RobustBetina(;\n    sampled_returns::Array{Float64,2}\n)\n    number_of_samples, number_of_assets = size(sampled_returns)\n\n    return RobustBetina(\n        sampled_returns, number_of_assets, number_of_samples\n    )\nend\n\nfunction _portfolio_return_latex_RobustBetina_dual()\n    return \"\"\"\n        ```math\n        \\\\max_{\\\\theta} \\\\quad  \\\\theta \\\\\\\\\n        s.t.  \\\\quad \\\\theta \\\\leq r_s ' w \\\\quad \\\\forall s = 1:\\\\mathcal{S} \\\\\\\\\n        ```\n        \"\"\"\nend\n\n\"\"\"\n    portfolio_return!(model::JuMP.Model, w, formulation::RobustBetina)\n\nReturns worst case return in Betina's uncertainty set, defined by the following dual problem: \n\n$(_portfolio_return_latex_RobustBetina_dual())\n\"\"\"\nfunction portfolio_return!(model::JuMP.Model, w, formulation::RobustBetina)\n    # auxilary variables\n    θ = @variable(model, θ)\n    # convex hull\n    @constraint(model, sum(formulation.sampled_returns * w , dims=2) .>= θ)\n\n    return θ\nend", "meta": {"hexsha": "75e9e45a98859564b7c9fa214e23ea1495ec4906", "size": 1413, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sample_based_robust.jl", "max_stars_repo_name": "andrewrosemberg/PortfolioOpt.jl", "max_stars_repo_head_hexsha": "5633c7f18e0e4a2e13ad97f0dcfc6239975a208f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-12-10T16:43:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T12:49:25.000Z", "max_issues_repo_path": "src/sample_based_robust.jl", "max_issues_repo_name": "andrewrosemberg/PortfolioOpt.jl", "max_issues_repo_head_hexsha": "5633c7f18e0e4a2e13ad97f0dcfc6239975a208f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sample_based_robust.jl", "max_forks_repo_name": "andrewrosemberg/PortfolioOpt.jl", "max_forks_repo_head_hexsha": "5633c7f18e0e4a2e13ad97f0dcfc6239975a208f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-12T15:17:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T15:17:41.000Z", "avg_line_length": 30.0638297872, "max_line_length": 272, "alphanum_fraction": 0.6999292286, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350351, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7565086293118076}}
{"text": "using GaussQuadrature, GLMakie\n\nfunction cubed_sphere_warp(\n    a,\n    b,\n    c,\n    R = max(abs(a), abs(b), abs(c)),\n)\n\n    function f(sR, ξ, η)\n        X, Y = tan(π * ξ / 4), tan(π * η / 4)\n        ζ1 = sR / sqrt(X^2 + Y^2 + 1)\n        ζ2, ζ3 = X * ζ1, Y * ζ1\n        ζ1, ζ2, ζ3\n    end\n\n    fdim = argmax(abs.((a, b, c)))\n    if fdim == 1 && a < 0\n        # (-R, *, *) : formulas for Face I from Ronchi, Iacono, Paolucci (1996)\n        #              but for us face II of the developed net of the cube\n        x1, x2, x3 = f(-R, b / a, c / a)\n    elseif fdim == 2 && b < 0\n        # ( *,-R, *) : formulas for Face II from Ronchi, Iacono, Paolucci (1996)\n        #              but for us face III of the developed net of the cube\n        x2, x1, x3 = f(-R, a / b, c / b)\n    elseif fdim == 1 && a > 0\n        # ( R, *, *) : formulas for Face III from Ronchi, Iacono, Paolucci (1996)\n        #              but for us face IV of the developed net of the cube\n        x1, x2, x3 = f(R, b / a, c / a)\n    elseif fdim == 2 && b > 0\n        # ( *, R, *) : formulas for Face IV from Ronchi, Iacono, Paolucci (1996)\n        #              but for us face I of the developed net of the cube\n        x2, x1, x3 = f(R, a / b, c / b)\n    elseif fdim == 3 && c > 0\n        # ( *, *, R) : formulas for Face V from Ronchi, Iacono, Paolucci (1996)\n        #              and the same for us on the developed net of the cube\n        x3, x2, x1 = f(R, b / c, a / c)\n    elseif fdim == 3 && c < 0\n        # ( *, *,-R) : formulas for Face VI from Ronchi, Iacono, Paolucci (1996)\n        #              and the same for us on the developed net of the cube\n        x3, x2, x1 = f(-R, b / c, a / c)\n    else\n        error(\"invalid case for cubed_sphere_warp(::EquiangularCubedSphere): $a, $b, $c\")\n    end\n\n    return x1, x2, x3\nend\n\nN = 5\nξ¹, ω¹ = GaussQuadrature.legendre(N, GaussQuadrature.both)\nξ² = copy(ξ¹)\nξ³ = copy(ξ¹)\n\nNe = 12\nvertices = collect(range(-1, 1, length = Ne + 1))\nx¹ = zeros(N, Ne)\nx² = copy(x¹)\nx³ = copy(x¹)\n\nfor e in 1:Ne\n    @. x¹[:, e] = (ξ¹ + 1) / 2 * (vertices[e+1] - vertices[e]) + vertices[e]\n    @. x²[:, e] = (ξ¹ + 1) / 2 * (vertices[e+1] - vertices[e]) + vertices[e]\n    @. x³[:, e] = (ξ¹ + 1) / 2 * (vertices[e+1] - vertices[e]) + vertices[e]\nend\n\nNex = Ney = Ne\nface1 = [(x¹[1], x²[j, ex], x³[k, ey]) for j in 1:N, k in 1:N, ex in 1:Nex, ey in 1:Ney]\nwarpedface1 = [cubed_sphere_warp(face1[i]...) for i in eachindex(face1)]\n\nface2 = [(x¹[end], x²[j, ex], x³[k, ey]) for j in 1:N, k in 1:N, ex in 1:Nex, ey in 1:Ney]\nwarpedface2 = [cubed_sphere_warp(face2[i]...) for i in eachindex(face2)]\n\nface3 = [(x¹[j, ey], x²[1], x³[k, ex]) for j in 1:N, k in 1:N, ex in 1:Nex, ey in 1:Ney]\nwarpedface3 = [cubed_sphere_warp(face3[i]...) for i in eachindex(face1)]\n\nface4 = [(x¹[j, ey], x²[end], x³[k, ex]) for j in 1:N, k in 1:N, ex in 1:Nex, ey in 1:Ney]\nwarpedface4 = [cubed_sphere_warp(face4[i]...) for i in eachindex(face1)]\n\nface5 = [(x¹[j, ex], x²[k, ey], x³[1]) for j in 1:N, k in 1:N, ex in 1:Nex, ey in 1:Ney]\nwarpedface5 = [cubed_sphere_warp(face5[i]...) for i in eachindex(face1)]\n\nface6 = [(x¹[j, ex], x²[k, ey], x³[end]) for j in 1:N, k in 1:N, ex in 1:Nex, ey in 1:Ney]\nwarpedface6 = [cubed_sphere_warp(face6[i]...) for i in eachindex(face1)]\n\n# Now Plot\nlw = 1  # linewidth\nms = 25 # marker size\n\nfig = Figure(resolution = (1400, 1200))\nax = LScene(fig[1, 1])\n# fig, ax, sc = scatter(warpedface1, color = :red, markersize = 0.0, show_axis = false)\n# scatter(warpedface1, color = :red, markersize = 0.0, show_axis = false)\nr = range(-1, 1, length = Ne + 1)\n\nxa = zeros(Ne + 1, Ne + 1)\nxb = zeros(Ne + 1, Ne + 1)\nxc = zeros(Ne + 1, Ne + 1)\n\nxa .= r\nxb .= r'\nxc .= 1\n\na = [cubed_sphere_warp(a, b, c)[1] for (a, b, c) in zip(xa, xb, xc)] .* 1.00\nb = [cubed_sphere_warp(a, b, c)[2] for (a, b, c) in zip(xa, xb, xc)] .* 1.00\nc = [cubed_sphere_warp(a, b, c)[3] for (a, b, c) in zip(xa, xb, xc)] .* 1.00\n\nwireframe!(ax,\n    a, b, c,\n    show_axis = false,\n    linewidth = lw)\n\nwireframe!(ax,\n    -c, a, b,\n    show_axis = false,\n    linewidth = lw * 5)\n\nscatter!(ax, warpedface1, color = :red, markersize = ms * 0.75,)\nscatter!(ax, warpedface3, color = :blue, markersize = ms,)\n\nrotate_cam!(fig.scene.children[1], (π/12, π, 0))\n", "meta": {"hexsha": "6c28668b728e8eae373769ab3d61f7a76463e0f8", "size": 4241, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "cubed_sphere_warp.jl", "max_stars_repo_name": "sandreza/HeldSuarezVisualizationScripts", "max_stars_repo_head_hexsha": "904ce7f44e965618b0ba6f5fa89015ba02aaf44a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cubed_sphere_warp.jl", "max_issues_repo_name": "sandreza/HeldSuarezVisualizationScripts", "max_issues_repo_head_hexsha": "904ce7f44e965618b0ba6f5fa89015ba02aaf44a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cubed_sphere_warp.jl", "max_forks_repo_name": "sandreza/HeldSuarezVisualizationScripts", "max_forks_repo_head_hexsha": "904ce7f44e965618b0ba6f5fa89015ba02aaf44a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0495867769, "max_line_length": 90, "alphanum_fraction": 0.5482197595, "num_tokens": 1719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7565086271207273}}
{"text": "function OPF_dual(optimizer,set_generators,set_nodes,set_demands,generators,demands,capacity,varcost,load_node,utility_node,links,links_rev,F_max_dict,B_dict,MapG,MapD)\n\nm=Model(optimizer)\n\n\n\n\n\n\n@variable(m, μ_G[g in set_generators]>= 0)\n@variable(m, μ_D[d in set_demands]>= 0)\n@variable(m, η_lower[link in links]>= 0)\n@variable(m, η_upper[link in links]>= 0)\n@variable(m, λ[set_nodes])\n@variable(m, γ)\n\n@objective(m, Min,     sum(μ_D[d]*demands[d,load_node]  for d in set_demands) +\n                       sum(μ_G[g]*generators[g,capacity]  for g in set_generators)+\n                       sum(F_max_dict[j]*(η_lower[j]+η_upper[j])   for j in links)\n                       )\n\n\n@constraint(m, constraint1[d in set_demands], -demands[d,utility_node]+ μ_D[d]+λ[MapD[d][2]]>= 0)\n\n@constraint(m, constraint2[g in set_generators], generators[g,varcost]+ μ_G[g]-λ[MapG[g][2]]>= 0)\n\n#@constraint(m, constraint3[n in set_nodes_ref],     sum(B_dict[j]*(λ[j[1]]-λ[j[2]]+η_upper[j] -η_lower[j]) for j in links if n == j[1])\n#                                                     +γ == 0)\n\n@constraint(m, constraint3[n in set_nodes_ref],     sum(B_dict[j]*(λ[j[1]]-λ[j[2]]+η_upper[j] -η_lower[j]) for j in links if n == j[1])\n                                                      +sum(B_dict[j]*(-η_upper[j] +η_lower[j]) for j in links_rev if n == j[2] )+γ == 0)\n\n#@constraint(m, constraint4[n in set_nodes_noref],  sum(B_dict[j]*(λ[j[1]]-λ[j[2]]+η_upper[j] -η_lower[j]) for j in links if n == j[1])\n#                                                      == 0)\n\n@constraint(m, constraint4[n in set_nodes_noref],  sum(B_dict[j]*(λ[j[1]]-λ[j[2]]+η_upper[j] -η_lower[j]) for j in links if n == j[1])\n                                                      +sum(B_dict[j]*(-η_upper[j] +η_lower[j]) for j in links_rev if n == j[2] )== 0)\n\n@time optimize!(m)\n\nstatus = termination_status(m)\nprintln(\"The solution status is: $status\")\n\nsyscost_det=objective_value(m)\n\nprintln(\"System Cost:\",syscost_det)\n\nDual_constraint2=zeros(length(set_generators))\n\nfor g in set_generators\n   Dual_constraint2[g]= JuMP.dual(constraint2[g])\nend\nprintln(\"Production level of generator g:\", Dual_constraint2)\n\nDual_constraint1=zeros(length(set_demands))\n\nfor d in set_demands\n   Dual_constraint1[d]= JuMP.dual(constraint1[d])\nend\nprintln(\"Consumption level of demand d: \", Dual_constraint1)\n\n\nλ_value=zeros(length(set_nodes))\nfor n in set_nodes\n  λ_value[n]=JuMP.value.(λ[n])\nend\nprintln(\"Electricity Price:\",λ_value)\n\n\n#Review this flow lines\n#Review all the constraints\n\nf_value=zeros(n_link)\nglobal i=1\n\nfor j in links\nglobal jj=j\nif set_nodes_ref==jj[1]\nglobal f_value[i]= B_dict[j]*(JuMP.dual(constraint3[j[1]])-JuMP.dual(constraint4[j[2]]))\nelseif set_nodes_ref==jj[2]\nglobal f_value[i]= B_dict[j]*(JuMP.dual(constraint4[j[1]])-JuMP.dual(constraint3[j[2]]))\nelse\nglobal f_value[i]= B_dict[j]*(JuMP.dual(constraint4[j[1]])-JuMP.dual(constraint4[j[2]]))\nend\nprintln(\"Power Flow lines $j:\", f_value[i])\nglobal i=1+i\nend\n\nreturn (syscost_det,Dual_constraint2,Dual_constraint1,λ_value,f_value)\nend\n\n#cd(\"C:\\\\Users\\\\braya\\\\.julia\\\\dev\\\\DTU_BrayamValqui_SP2021\\\\src\")\n#include(\"Singlefile_OPF_dual.jl\")\n", "meta": {"hexsha": "bd435897eb63b1bb6b9f594c160feb84ae97211f", "size": 3164, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/OPF_dual.jl", "max_stars_repo_name": "bdvalqui/DTU_BrayamValqui_SP2021.jl", "max_stars_repo_head_hexsha": "cde096a6d5f2cf03b567056ef0655908e68769e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/OPF_dual.jl", "max_issues_repo_name": "bdvalqui/DTU_BrayamValqui_SP2021.jl", "max_issues_repo_head_hexsha": "cde096a6d5f2cf03b567056ef0655908e68769e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OPF_dual.jl", "max_forks_repo_name": "bdvalqui/DTU_BrayamValqui_SP2021.jl", "max_forks_repo_head_hexsha": "cde096a6d5f2cf03b567056ef0655908e68769e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6595744681, "max_line_length": 168, "alphanum_fraction": 0.6482300885, "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7565086257459983}}
{"text": "# Simulate a 5-area (~20 Hz) beta network instantiated by an AR(3) model =============================\r\n# cd(\"Homework_3_Lect_5&6\")\r\n\r\nxDim=5 # state dimensionå\r\norder=3# p=3 order of the model\r\nT=3# Trial duration in seconds\r\nnTrials=200\r\nFs=200# sampling rate in per second\r\ndt=1/Fs\r\nburnin=1000 # for transient removal\r\ndf=0.001#frequency resolution to be used in the parametric AR estimation\r\nnF=1/df+1#number of frequencies evaluated in the parametric AR estimation\r\n\r\nN=T*Fs\r\n\r\n# The AR(3) matrices \r\nA = zeros(xDim,xDim,order)\r\na=sqrt(2)\r\nA[1,1,1] =  0.95*a\r\nA[1,1,2] = -0.9025\r\nA[2,1,2] =  0.5\r\nA[3,1,3] = -0.4\r\nA[4,1,2] = -0.5\r\nA[4,4,1] =  0.25*a\r\nA[4,5,1] =  0.25*a\r\nA[5,4,1] = -0.25*a\r\nA[5,5,1] =  0.25*a\r\n\r\n# EXERCISE (1a): Stability/Stationarity Build the companion matrix (augmented state AR(1)) and check stability\r\nm,n,p = size(A)\r\npn = (p-1)*m\r\nAc = [reshape(A,m,p*n); eye(pn) zeros(pn,m)]# companion matrix\r\n\r\n\r\n\r\n# Sampling from the VAR(3) model\r\n# The noise covariance (Using DIAGONAL COVARIANCE MATRIX FOR SIMPLICITY ...)\r\nSIGMA =diag([0.60.5 0.3 0.3 0.6])\r\nmu = zeros(xDim,1)\r\nfor r=1:nTrials\r\n    r\r\n    E=mvnrnd(mu,SIGMA,N+burnin)\" #Multivariate GWN sequence\r\n    X(:,1:order,r)=E(:,1:order)    \r\n    for k=order+1:N+burnin\r\n        x=0\r\n        for j=1:order\r\n            x=x+squeeze(A(:,:,j))*squeeze(X(:,k-j,r))\r\n        end\r\n        X(:,k,r)=x+E(:,k)\r\n    end\r\nend\r\nX=X(:,burnin+1:end,:)\r\n\r\n# Computing the spectral matrix for the sampled VAR(p) data via multitaper ===========\r\nNFFT=N\r\nbandWidth = ...\r\nremoveTemporalMean=true\r\nRemoveEnsembleMean=true\r\nnTapers=[]\r\nclear S\r\nxDim = 5\r\nfor j=1:xDim\r\n    x=squeeze(X(j,:,:)) \r\n    for k=j+1:xDim\r\n        y=squeeze(X(k,:,:))        \r\n        [Sxx, Syy, Sxy, ~, ~, F, nTapers]= multitaperSpectrum(x,y,Fs,bandWidth,NFFT,removeTemporalMean,RemoveEnsembleMean,nTapers)                 \r\n        S(j,j,:)=Sxx        \r\n        S(j,k,:)=Sxy #Cross-spectrum\r\n        S(k,j,:)=conj(Sxy)         \r\n    end    \r\nend\r\nS(j,j,:)=Syy\r\n\r\n# To compute the partial coherence =======================\r\n# S is the spectral matrix S(channel j, channel k, frequency), j,k = 1, 2, ... xDim\r\nfor j=1:xDim\r\n    for k=j+1:xDim\r\n        i1=setdiff([1:xDim],j)\r\n        i2=setdiff([1:xDim],k)\r\n        for f=1:length(F)\r\n            Mjk = det(S(i1,i2,f))\r\n            Mjj = det(S(i1,i1,f))\r\n            Mkk = det(S(i2,i2,f))            \r\n            Cp(j,k,f) = abs(Mjk)/real(sqrt(Mjj*Mkk))#to avoid numerical issues, force it to be real \r\n        end                \r\n    end\r\nend\r\n\r\n\r\n\r\n# Estimating VAR(p) from data ===================\r\n[Ah,SIGMAh,Eh] = var_maxent(X,order)\r\nDSIG = det(SIGMA)# residuals covariance matrix determinant\r\nif DSIG <= 0\r\n    fprintf(2,\"  WARNING: residuals covariance not positive definite\\n\")\r\nend\r\nM=N*nTrials\r\nL= -(M/2)*log(DSIG) #max loglikelihood\r\naic = -2*L + 2*order*xDim^2*(M/(M-order-1)) # Note AIC without correction = -2*L + 2*order*xDim^2\r\nbic = -2*L + order*log(M)\r\n\r\n# Transfer function H(f) and spectral matrix S(f) from fitted model\r\n# F=[0:nF-1]*df*Fs/2\r\ndelta=1\r\nF=linspace(0,0.5,nF)# use normalized frequency (cycles/sample) first \r\nj=0\r\nfor f=F\r\n    j=j+1\r\n    H = eye(xDim) # identity matrix\r\n    for m=1:order\r\n        H=H-squeeze(Ah(:,:,m))*exp(-1i*m*2*pi*f)        \r\n    end\r\n    H = inv(H)\r\n    #S(:,:,j) = H*SIGMAh*ctranspose(H) \r\n    S(:,:,j) = H*SIGMAh*H\"\r\n    #Note: the transpose \" \" \" will also recognize the complex data and perform the conjugate transpose\r\n    #Note also, however, that .\" implements only the transpose, not the conjugate transpose\r\nend\r\nS = 2 * delta^2 * 1/(N*delta) * S #Normalize the spectral matrix\r\nfor k = 1:xDim, S(k,k,:) = real(S(k,k,:))end #make sure the diagonal has real numbers (power spectrum)\r\nF=F*Fs# Change frequency to Hz\r\n\r\n\r\n\r\n", "meta": {"hexsha": "b404d3e1cc10a364e5e02c64ea848ad98e19026d", "size": 3774, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "homework3/Homework_3_warm_up.jl", "max_stars_repo_name": "mirestrepo/neur2110_code.jl", "max_stars_repo_head_hexsha": "c9d2714ddb3a2683eb76f2987c60108560e3e414", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework3/Homework_3_warm_up.jl", "max_issues_repo_name": "mirestrepo/neur2110_code.jl", "max_issues_repo_head_hexsha": "c9d2714ddb3a2683eb76f2987c60108560e3e414", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework3/Homework_3_warm_up.jl", "max_forks_repo_name": "mirestrepo/neur2110_code.jl", "max_forks_repo_head_hexsha": "c9d2714ddb3a2683eb76f2987c60108560e3e414", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.192, "max_line_length": 148, "alphanum_fraction": 0.5810810811, "num_tokens": 1289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7565086227385663}}
{"text": "\nimport IterativeSolvers: gmres!, bicgstabl!\nimport LinearAlgebra: ldiv!\n\nabstract type AbstractLinearSolver end\nabstract type DirectSolver <: AbstractLinearSolver end\nabstract type IterativeSolver <: AbstractLinearSolver end\n\nstruct LU  <:DirectSolver end\nstruct GMRES  <: IterativeSolver end\nstruct BICGSTAB  <: IterativeSolver end\n\nlinsolve(A,b ; args...) = linsolve(A,b,LU() ; args...)\n\n\nfunction linsolve(A,b,solver::AbstractLinearSolver ; args...)\n    x = similar(b)\n    linsolve!(x,A,b,solver; args...)\n    return x\nend\n\nlinsolve!(x,A,b ; args...) = linsolve!(x,A,b,LU() ; args...)\n\nfunction linsolve!(x,A,b , ::LU ; args...)\n  ldiv!(x, lu(A), b; args...)\nend\n     \n\nfunction linsolve!(x,A,b,::GMRES ; args...)\n    gmres!(x,A,b; args...)\nend\n   \nfunction linsolve!(x,A,b,::BICGSTAB ; args...)\n    bicgstabl!(x,A,b; args...)\nend\n\n\n\n\n# methods for sensitivty analysis\nfunction linsolve!(x,x_adj,A,b,b_adj,::LU ; args...)\n    F = lu(A)\n    ldiv!(x, F, b; args...)\n    ldiv!(x_adj, transpose(F), b_adj; args...)\nend\n\nfunction linsolve(A,b,b_adj,::LU ;  args...)\n    x = similar(b) ; x_adj = similar(b_adj)\n    linsolve!(x,x_adj,A,b,b_adj,LU(); args...)\n    return x , x_adj\nend\n  ", "meta": {"hexsha": "219ac9aca76375e4f9df56c9d949d57957bf5ffc", "size": 1183, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LinearAlgebra/LinearSolver.jl", "max_stars_repo_name": "MKAbdElrahman/Photon.jl", "max_stars_repo_head_hexsha": "f75c0b572233094c8a049d3bf572489b6d5d23d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-06-27T10:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-11T18:16:15.000Z", "max_issues_repo_path": "src/LinearAlgebra/LinearSolver.jl", "max_issues_repo_name": "MKAbdElrahman/Photon.jl", "max_issues_repo_head_hexsha": "f75c0b572233094c8a049d3bf572489b6d5d23d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-06-12T00:26:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-10T00:28:45.000Z", "max_forks_repo_path": "src/LinearAlgebra/LinearSolver.jl", "max_forks_repo_name": "MKAbdElrahman/Photon.jl", "max_forks_repo_head_hexsha": "f75c0b572233094c8a049d3bf572489b6d5d23d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.75, "max_line_length": 61, "alphanum_fraction": 0.6466610313, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8056321796478254, "lm_q1q2_score": 0.7565086117831634}}
{"text": "# import Base.copy\nimport Base.-\nimport Base./\n\nexport\n    Vector2D,\n    set!\n\nmutable struct Vector2D{T <: AbstractFloat}\n    x::T\n    y::T\n\n    function Vector2D{T}() where {T <: AbstractFloat}\n        new(0.0, 0.0)\n    end\n\n    function Vector2D{T}(x::T, y::T) where {T <: AbstractFloat}\n        new(x, y)\n    end\nend\n\n# copy specializations\ncopy(v::Vector2D) = Vector2D{Float64}(v.x, v.y)\n\n# setters/getters set_point\nfunction set!(v::Vector2D{T}, x::T, y::T) where {T <: AbstractFloat}\n    v.x = x\n    v.y = y;\nend\n\nfunction set!(v::Vector2D{T}, from::Vector2D{T}) where {T <: AbstractFloat}\n    v.x = from.x\n    v.y = from.y;\nend\n\nfunction length(x::T, y::T) where {T <: AbstractFloat}\n    sqrt(x * x + y * y)\nend\n\nfunction length(v::Vector2D{T}) where {T <: AbstractFloat}\n    sqrt(v.x * v.x + v.y * v.y)\nend\n\nfunction length_sq(x::T, y::T) where {T <: AbstractFloat}\n    x * x + y * y\nend\n\n# Scratch vectors\nscv = Vector2D{Float64}()\nscv2 = Vector2D{Float64}()\n\nfunction add!(v1::Vector2D{T}, v2::Vector2D{T}, out::Vector2D{T}) where {T <: AbstractFloat}\n    set!(out, v1.x + v2.x, v1.y + v2.y)\nend\n\nfunction sub!(v1::Vector2D{T}, v2::Vector2D{T}, out::Vector2D{T}) where {T <: AbstractFloat}\n    set!(out, v1.x - v2.x, v1.y - v2.y)\nend\n\nfunction scale!(v::Vector2D{T}, s::T) where {T <: AbstractFloat}\n    set!(v, v.x * s, v.y * s)\nend\n\nfunction scale!(v::Vector2D{T}, s::T, out::Vector2D{T}) where {T <: AbstractFloat}\n    set!(out, v.x * s, v.y * s)\nend\n\nfunction div!(v::Vector2D{T}, value::T) where {T <: AbstractFloat}\n    set!(v, v.x / value, v.y / value)\nend\n\n# distance between two vectors\nfunction distance(v1::Vector2D{T}, v2::Vector2D{T}) where {T <: AbstractFloat}\n    sub!(v1, v2, scv)\n    length(scv)\nend\n\n# returns the angle in radians between this vector and the x axis\nfunction angle(v::Vector2D{T}) where {T <: AbstractFloat}\n    atan(v.y, v.x)\nend\n\n# Returns  multiplied to a length of 1.\n# If the point is 0, it returns (1, 0)\nfunction normalize!(v::Vector2D{T}) where {T <: AbstractFloat}\n    len = length(v)\n    if length(v) == 0.0\n        set!(scv, 1.0, 0.0)\n        return scv\n    end\n\n    div!(v, len);\nend\n\n# Calculates dot product of two points.\nfunction dot(v1::Vector2D{T}, v2::Vector2D{T}) where {T <: AbstractFloat}\n    v1.x * v2.x + v1.y * v2.y\nend\n\n# Calculates cross product of two points.\nfunction cross(v1::Vector2D{T}, v2::Vector2D{T}) where {T <: AbstractFloat}\n    v1.x * v2.y - v1.y * v2.x\nend\n\n# returns the angle in radians between two vector directions\nfunction angle_between(v1::Vector2D{T}, v2::Vector2D{T}) where {T <: AbstractFloat}\n    set!(scv, v1)\n    set!(scv2, v2)\n    \n    normalize!(scv) #a2\n    normalize!(scv2) #b2\n\n    angle = atan(cross(scv, scv2), dot(scv, scv2))\n\n    if abs(angle) < EPSILON \n        return 0.0\n    else\n        return angle\n    end\nend\n\n# Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) >= 0\nfunction perpindicular(x::T, y::T) where {T <: AbstractFloat}\n    Vector2D(-y, x)\nend\n\nfunction ccw_perpindicular!(v::Vector2D{T}) where {T <: AbstractFloat}\n    set!(v, -v.y, v.x);\nend\n\n# Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) <= 0\nfunction cw_perpindicular!(v::Vector2D{T}) where {T <: AbstractFloat}\n    set!(v, v.y, -v.x);\nend\n\nfunction set_direction!(v::Vector2D{T}, degrees::T) where {T <: AbstractFloat}\n    set!(v, cos(deg2rad(degrees)), sin(deg2rad(degrees)));\nend", "meta": {"hexsha": "8a7a571a600358229a75a139ead81bf90df5697d", "size": 3436, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "math/vector_2d.jl", "max_stars_repo_name": "wdevore/Ranger-Julia-SDL", "max_stars_repo_head_hexsha": "da33b1c5db43392fb17edab6f434d280a9b086c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-09-18T02:56:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-23T04:24:09.000Z", "max_issues_repo_path": "math/vector_2d.jl", "max_issues_repo_name": "wdevore/Ranger-Julia-SDL", "max_issues_repo_head_hexsha": "da33b1c5db43392fb17edab6f434d280a9b086c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/vector_2d.jl", "max_forks_repo_name": "wdevore/Ranger-Julia-SDL", "max_forks_repo_head_hexsha": "da33b1c5db43392fb17edab6f434d280a9b086c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8985507246, "max_line_length": 95, "alphanum_fraction": 0.6309662398, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7564444040677187}}
{"text": "# This code is a julia translation of the following project:\n# https://bitbucket.org/happyalu/mcep_alpha_calc\n\n# mcepalpha computes appropriate α for a given sampling frequency.\nfunction mcepalpha(fs::Real;\n                   start::Float64=0.0,\n                   stop::Float64=1.0,\n                   step::Float64=0.001,\n                   numpoints::Integer=1000)\n    α_candidates = start:step:stop\n    mel = melscale_vector(fs, numpoints)\n    distances = [rms_distance(mel, warping_vector(α, numpoints)) for\n                 α in α_candidates]\n    return α_candidates[indmin(distances)]\nend\n\nfunction melscale_vector(fs::Real, len::Integer)\n    step = (fs / 2.0) / len\n    melscalev = 1000.0/log(2)*log(1 + step.*(1:len)./1000.0)\n    return melscalev / melscalev[end]\nend\n\nfunction warping_vector(α::Float64, len::Integer)\n    step = π / len\n    ω = step .* (1:len)\n    num = (1-α*α) * sin(ω)\n    den = (1+α*α) * cos(ω) - 2*α\n    warpfreq = atan(num./den)\n    warpfreq[warpfreq .< 0] += π\n    return warpfreq / warpfreq[end]\nend\n\nrms_distance(v1, v2) = sumabs2(v1 - v2) / length(v1)\n", "meta": {"hexsha": "ccbb0e4bc0a13cda415df2ae62284c0e4b174d1d", "size": 1088, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mcepalpha.jl", "max_stars_repo_name": "JuliaPackageMirrors/MelGeneralizedCepstrums.jl", "max_stars_repo_head_hexsha": "00e69678d4f3fcaa93a656efd8df5cbde7ac3553", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mcepalpha.jl", "max_issues_repo_name": "JuliaPackageMirrors/MelGeneralizedCepstrums.jl", "max_issues_repo_head_hexsha": "00e69678d4f3fcaa93a656efd8df5cbde7ac3553", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mcepalpha.jl", "max_forks_repo_name": "JuliaPackageMirrors/MelGeneralizedCepstrums.jl", "max_forks_repo_head_hexsha": "00e69678d4f3fcaa93a656efd8df5cbde7ac3553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0, "max_line_length": 68, "alphanum_fraction": 0.6222426471, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7564444016407553}}
{"text": "\r\nfunction mean(x::Vector{T}) where {T}\r\n    m = sum(x) / length(x)\r\n    return m\r\nend\r\n\r\nfunction std(x::Vector{T}) where {T}\r\n    m = mean(x)\r\n    z = x .- m\r\n    m = sqrt( sum(z.^2) / (length(x) - 1) )\r\n    return m\r\nend\r\n\r\nfunction center(x::Vector)\r\n    m = mean(x)\r\n    y = copy(x)\r\n    y .-= m\r\n    return y\r\nend\r\n\r\nfunction cov(x::Vector{T}) where {T}\r\n    return std(x)\r\nend\r\n\r\nfunction cov(x::Vector{T}, y::Vector{T}) where {T}\r\n    mx = mean(x)\r\n    my = mean(y)\r\n    L = length(x)\r\n\r\n    return 1 / (L - 1) * dot(x .- mx, y .- my)\r\nend\r\n\r\nfunction cov(x::Matrix{T}) where {T}\r\n    # covariance in column way\r\n    L = size(x,1)\r\n    return 1/(L-1) * (x' * x)\r\nend\r\n", "meta": {"hexsha": "8ecb44c4916019e6e147f44ff42fa5adc6df075c", "size": 676, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/common/distributions/src/stat_general.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "__lib__/math/common/distributions/src/stat_general.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "__lib__/math/common/distributions/src/stat_general.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7894736842, "max_line_length": 51, "alphanum_fraction": 0.4970414201, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7564443995844731}}
{"text": "# Utility functions for common algebraic operations.\n\n\"\"\"\n    rotateTensorToVectorZ(tensor, vector)\n\nRotate `tensor` with a rotation matrix that aligns the 3rd direction with `vector`, which is\nequivalent to change the basis from (i,j,k) to (i′,j′,k′) where k′ ∥ vector.\nReference: [Tensor rotation](https://math.stackexchange.com/questions/2303869/tensor-rotation)\n\"\"\"\nfunction rotateTensorToVectorZ(tensor::AbstractMatrix{T}, v::AbstractVector{T}) where T\n   k = SVector{3, T}(0.0, 0.0, 1.0)\n   axis = v × k::SVector{3, T}\n   if axis[1] == axis[2] == 0\n      return tensor\n   else\n      normalize!(axis)\n      angle = acos(v ⋅ k / hypot(v[1], v[2], v[3]))\n      R = getRotationMatrix(axis, angle)\n      return R * tensor * R'\n   end\nend\n\n\"\"\"\n    getRotationMatrix(axis::AbstractVector, angle) --> SMatrix{3,3}\n\nCreate a rotation matrix for rotating a 3D vector around a unit `axis` by an `angle` in\nradians.\nReference: [Rotation matrix from axis and angle](https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle)\n\n# Example\n\n```julia\nusing LinearAlgebra\nv = [-0.5, 1.0, 1.0]\nv̂ = normalize(v)\nangle = deg2rad(-74)\nR = getRotationMatrix(v̂, angle)\n```\n\"\"\"\nfunction getRotationMatrix(v::AbstractVector{<:AbstractFloat}, θ)\n   sinθ, cosθ = sincos(eltype(v)(θ))\n   tmp = 1 - cosθ\n   m =  @SMatrix [\n        cosθ+v[1]^2*tmp         v[1]*v[2]*tmp-v[3]*sinθ v[1]*v[3]*tmp+v[2]*sinθ;\n        v[1]*v[2]*tmp+v[3]*sinθ cosθ+v[2]^2*tmp         v[2]*v[3]*tmp-v[1]*sinθ;\n        v[1]*v[3]*tmp-v[2]*sinθ v[3]*v[2]*tmp+v[1]*sinθ cosθ+v[3]^2*tmp]\nend\n\n\"\"\"\n    getRotationMatrix(e1::Matrix, e2::Matrix) --> SMatrix{3,3}\n\nObtain the rotation matrix from orthgonal base vectors `e1` to `e2`, such that a vector\n``\\\\mathbf{u}_1`` in `e1` can be expressed as ``\\\\mathbf{u}_1 = M\\\\cdot \\\\mathbf{u}_2``,\nwhere ``M`` is the rotation matrix and ``\\\\mathbf{u}_2`` is the same vector in `e2`.\n\n# Example\n\n```julia\ne1 = [1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0]\ne2 = [0.0 1.0 0.0; 1.0 0.0 0.0; 0.0 0.0 1.0]\nR = getRotationMatrix(e1, e2)\n```\n\"\"\"\nfunction getRotationMatrix(e1::AbstractMatrix, e2::AbstractMatrix)\n   @views begin\n      r11 = e1[:,1] ⋅ e2[:,1]\n      r12 = e1[:,1] ⋅ e2[:,2]\n      r13 = e1[:,1] ⋅ e2[:,3]\n      r21 = e1[:,2] ⋅ e2[:,1]\n      r22 = e1[:,2] ⋅ e2[:,2]\n      r23 = e1[:,2] ⋅ e2[:,3]\n      r31 = e1[:,3] ⋅ e2[:,1]\n      r32 = e1[:,3] ⋅ e2[:,2]\n      r33 = e1[:,3] ⋅ e2[:,3]\n   end\n   R = @SMatrix [r11 r12 r13; r21 r22 r23; r31 r32 r33]\nend\n", "meta": {"hexsha": "8344e701f6c5829bc86e37ff1cf6a3085de89b69", "size": 2463, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utility/rotation.jl", "max_stars_repo_name": "alhom/Vlasiator.jl", "max_stars_repo_head_hexsha": "615333705b5346522479ab72398f059cb94ab026", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utility/rotation.jl", "max_issues_repo_name": "alhom/Vlasiator.jl", "max_issues_repo_head_hexsha": "615333705b5346522479ab72398f059cb94ab026", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utility/rotation.jl", "max_forks_repo_name": "alhom/Vlasiator.jl", "max_forks_repo_head_hexsha": "615333705b5346522479ab72398f059cb94ab026", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5769230769, "max_line_length": 131, "alphanum_fraction": 0.6077953715, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7564443934156264}}
{"text": "# Newton-like methods for NEPs\n\nusing LinearAlgebra\nusing Printf\nusing Random\n\n\n\nexport newton\nexport resinv\nexport augnewton\nexport quasinewton\nexport newtonqr\nexport implicitdet\n\n#############################################################################\n\"\"\"\n    λ,v = newton([eltype],nep::NEP;[errmeasure,][tol,][maxit,][λ,][v,][c,][logger,][armijo_factor=1,][armijo_max])\n\nApplies Newton-Raphsons method on the system of\nnonlinear equations with `n+1` unknowns:\n```math\nM(λ)v=0\n```\n```math\nc^Hv-1=0\n```\nThe vector `c` is the\northogonalization vector.  If `c=0` the current approximation will be used for the orthogonalization. See [`augnewton`](@ref) for other parameters.\n\n# Example\n```julia-repl\njulia> using LinearAlgebra\njulia> nep=nep_gallery(\"dep0\");\njulia> λ,v=newton(nep);\njulia> minimum(svdvals(compute_Mder(nep,λ)))\n1.9997125567227177e-16\n```\n\n# References\n* Nichtlineare Behandlung von Eigenwertaufgaben, Z. Angew. Math. Mech. 30 (1950) 281-282.\n* A. Ruhe, Algorithms for the nonlinear eigenvalue problem, SIAM J. Numer. Anal. 10 (1973) 674-689\n\n\"\"\"\n    newton(nep::NEP;params...)=newton(ComplexF64,nep;params...)\n    function newton(::Type{T},\n                    nep::NEP;\n                    errmeasure::ErrmeasureType = DefaultErrmeasure(nep),\n                    tol::Real=eps(real(T))*100,\n                    maxit::Int=10,\n                    λ::Number=zero(T),\n                    v::Vector=randn(size(nep,1)),\n                    c::Vector=v,\n                    logger=0,\n                    armijo_factor::Real=1,\n                    armijo_max::Int=5) where {T<:Number}\n\n        @parse_logger_param!(logger)\n\n        # Ensure types λ and v are of type T\n        λ=T(λ)\n        v=Vector{T}(v)\n        c=Vector{T}(c)\n\n        err=Inf;\n        v[:] = v/dot(c,v);\n\n        for k=1:maxit\n            err=estimate_error(errmeasure,λ,v)\n\n            push_iteration_info!(logger,k,err=err,λ=λ,v=v,continues=true);\n            if (err< tol)\n                push_info!(logger,\"\")\n                return (λ,v)\n            end\n\n            # Compute NEP matrix and derivative\n            M = compute_Mder(nep,λ)\n            Md = compute_Mder(nep,λ,1)\n\n            # Create jacobian\n            J = [M Md*v; c' 0];\n            F = [M*v; c'*v-1];\n\n            # Compute update\n            delta=-J\\F;  # Hardcoded backslash\n\n            Δv=Vector{T}(delta[1:size(nep,1)]);\n            Δλ=T(delta[size(nep,1)+1]);\n\n            (Δλ,Δv,j,scaling)=armijo_rule(nep,errmeasure,err,\n                                          λ,v,Δλ,Δv,real(T(armijo_factor)),armijo_max)\n            if (j>0)\n                push_info!(logger,\" Armijo scaling=$scaling\")\n            else\n                push_info!(logger,\"\")\n            end\n\n\n            # Update eigenvalue and eigvec\n            v[:] += Δv\n            λ = λ+Δλ\n        end\n\n        msg=\"Number of iterations exceeded. maxit=$(maxit).\"\n        throw(NoConvergenceException(λ,v,err,msg))\n    end\n\n    ############################################################################\n\"\"\"\n    λ,v = resinv([eltype],nep::NEP;[errmeasure,][tol,][maxit,][λ,][v,][c,][logger,][armijo_factor=1,][armijo_max,][linsolvecreator])\n\nApplies residual inverse iteration method for nonlinear eigenvalue problems.\nThe kwarg `linsolvecreator`\nis a function which specifies how the linear system is created.\nThe function calls `compute_rf` for the computation\nof the Rayleigh functional.\nSee [`augnewton`](@ref) for other parameters.\n\n# Example\nThe example shows how to specify if the method should run in real\nor complex mode (or any other `Number` type).\n```julia-repl\njulia> nep=nep_gallery(\"qdep0\");\njulia> λ,v=resinv(nep,λ=-2,v=ones(size(nep,1)))\njulia> typeof(λ)\nComplex{Float64}\njulia> norm(compute_Mlincomb(nep,λ,v))\n6.688224435370382e-12\njulia> λ,v=resinv(Float64,nep,λ=-2,v=ones(size(nep,1)))\njulia> typeof(λ)\nFloat64\njulia> norm(compute_Mlincomb(nep,λ,v))\n5.939894690000396e-12\n```\n\n# References\n*  A. Neumaier, Residual inverse iteration for the nonlinear eigenvalue problem, SIAM J. Numer. Anal. 22 (1985) 914-923\n\n\"\"\"\n    resinv(nep::NEP;params...)=resinv(ComplexF64,nep;params...)\n    function resinv(::Type{T},\n                    nep::NEP;\n                    errmeasure::ErrmeasureType = DefaultErrmeasure(nep),\n                    tol::Real=eps(real(T))*100,\n                    maxit::Int=100,\n                    λ::Number=zero(T),\n                    v::Vector=randn(real(T),size(nep,1)),\n                    c::Vector=v,\n                    logger=0,\n                    inner_solver= @default_compute_rf_inner_solver(nep),\n                    linsolvercreator=DefaultLinSolverCreator(),\n                    armijo_factor::Real=1,\n                    armijo_max::Int=5) where T\n\n        @parse_logger_param!(logger)\n\n\n        # Ensure types λ and v are of type T\n        λ::T=T(λ)\n        v=Vector{T}(v)\n        c=Vector{T}(c)\n        n=size(v,1);\n\n        push_info!(logger,\"Precomputing linsolver\")\n        local linsolver::LinSolver=create_linsolver(linsolvercreator,nep,λ)\n\n        # If c is zero vector we take eigvec approx as left vector in\n        # generalized Rayleigh functional\n        use_v_as_rf_vector=false;\n        if (norm(c)==0)\n            use_v_as_rf_vector=true;\n        end\n\n\n        push_info!(logger,2,\n                   \"use_v_as_rf_vector=$use_v_as_rf_vector\");\n\n        σ::T=λ;\n        err=Inf;\n\n\n        for k=1:maxit\n            # Normalize\n            v[:] = v/norm(v);\n\n            err=estimate_error(errmeasure,λ,v)\n\n            if (use_v_as_rf_vector)\n                c[:]=v;\n            end\n\n\n            push_iteration_info!(logger,k,err=err,λ=λ,v=v,continues=true);\n\n            if (err< tol)\n                push_info!(logger,\"\")\n                return (λ,v)\n            end\n\n            # Compute eigenvalue update\n            λ_vec = compute_rf(T, nep, v, inner_solver, y=c, λ=λ, target=σ)\n            local λ1::T = closest_to(λ_vec,  λ)\n            Δλ=λ1-λ\n\n\n            # Compute eigenvector update\n            Δv = -lin_solve(linsolver,compute_Mlincomb(nep,λ1,reshape(v,n,1))) #M*v);\n\n            (Δλ,Δv,j,scaling)=armijo_rule(nep,errmeasure,err,\n                                          λ,v,Δλ,Δv,real(T(armijo_factor)),armijo_max)\n            if (j>0)\n                push_info!(logger,\" Armijo scaling=$scaling\")\n            else\n                push_info!(logger,\"\")\n            end\n\n            # Update the eigenpair\n            λ+=Δλ\n            v[:] += Δv;\n\n        end\n\n        msg=\"Number of iterations exceeded. maxit=$(maxit).\"\n        throw(NoConvergenceException(λ,v,err,msg))\n    end\n\n\n\n\n\n    # New augnewton\n\"\"\"\n    augnewton([eltype], nep::NEP; [errmeasure,][tol,][maxit,][λ,][v,][c,][logger,][linsolvercreator,][armijo_factor,][armijo_max])\n\nRun the augmented Newton method. The method is equivalent to `newton()`\nin exact arithmetic,  but works only with operations on vectors of\nlength `n`.\n\n\nThe following keyword arguments are in common for many NEP-solvers:\n\n* `logger` is either a [`Logger`](@ref) object or an `Int`. If it is an `Int`, a `PrintLogger(logger)` will be instantiated. `logger=0` prints nothing, `logger=1` prints more, etc.\n\n* `errmeasure` determines how error is measured. It is either a function handle or an object of the type `Errmeasure`.  If it is a function handle, it should take `(λ,v)` as input and return a real scalar (the error). See [`Errmeasure`](@ref) and [`ErrmeasureType`](@ref) for further description.\n\n* `tol` is a scalar which determines termination. If `errmeasure` is less than `tol` the eigenpair is marked as converged.\n\n* The scalar `λ` and the vector `v` are starting approximations.\n\n* `maxit` determines the maximum number of iterations. The error `NoConvergenceException` is thrown if this is exceeded.\n\n*  The `linsolvecreator` specifies how the linear system should be solved. See [`LinSolver`](@ref) for further information.\n\n* `armijo_factor` specifies if an Armijo rule should be applied, and its value specifies the scaling factor of the step length (per reduction step). The variable `armijo_max` specifies the maximum number of step length reductions.\n\n\n\n\n# Example\nThis illustrates the equivalence between `newton` and `augnewton`.\n```julia-repl\njulia> nep=nep_gallery(\"dep1\")\njulia> λ1,v1=newton(nep,maxit=20,v=ones(size(nep,1)),λ=0)\njulia> λ2,v2=augnewton(nep,maxit=20,v=ones(size(nep,1)),λ=0)\njulia> λ1-λ2\n0.0 + 0.0im\n```\n# References\n* Nichtlineare Behandlung von Eigenwertaufgaben, Z. Angew. Math. Mech. 30 (1950) 281-282.\n* A. Ruhe, Algorithms for the nonlinear eigenvalue problem, SIAM J. Numer. Anal. 10 (1973) 674-689\n\"\"\"\n    augnewton(nep::NEP;kwargs...)=augnewton(ComplexF64,nep::NEP;kwargs...)\n    function augnewton(::Type{T},\n                       nep::NEP;\n                       errmeasure::ErrmeasureType = DefaultErrmeasure(nep),\n                       tol::Real=eps(real(T))*100,\n                       maxit::Int=30,\n                       λ::Number=zero(T),\n                       v::Vector=randn(real(T),size(nep,1)),\n                       c::Vector=v,\n                       logger=0,\n                       linsolvercreator=DefaultLinSolverCreator(),\n                       armijo_factor::Real=one(real(T)),\n                       armijo_max::Int=5) where {T<:Number}\n\n        @parse_logger_param!(logger)\n\n\n        # Ensure types λ and v are of type T\n        λ=T(λ)\n        v=Vector{T}(v)\n        c=Vector{T}(c)\n\n        err=Inf;\n        # If c is zero vector we take eigvec approx as normalization vector\n        use_v_as_normalization_vector=false;\n        if norm(c) == 0\n            use_v_as_normalization_vector=true;\n            c[:] = v / norm(v)^2\n        end\n        v[:] = v/dot(c,v);\n        local linsolver::LinSolver\n        local tempvec = Vector{T}(undef, size(nep,1))\n\n        push_info!(logger,2,\n                   \"use_v_as_normalization_vector=$use_v_as_normalization_vector\");\n\n        for k=1:maxit\n            err=estimate_error(errmeasure,λ,v)\n            push_iteration_info!(logger,k,err=err,λ=λ,v=v,continues=true);\n            if (err< tol)\n                push_info!(logger,\"\")\n                return (λ,v)\n            end\n            # tempvec =  (M(λ_k)^{-1})*M'(λ_k)*v_k\n            # α = 1/(c'*(M(λ_k)^{-1})*M'(λ_k)*v_k);\n\n            z::AbstractVector=compute_Mlincomb(nep,λ,v,[T(1.0)],1)\n\n            linsolver = create_linsolver(linsolvercreator,nep,λ)\n            tempvec[:] = Vector{T}(lin_solve(linsolver, z, tol=tol));\n\n            if (use_v_as_normalization_vector)\n                c[:] = v /norm(v)^2\n            end\n            α = T(1)/ dot(c,tempvec);\n\n            Δλ=-α\n            Δv=α*tempvec-v;\n\n            (Δλ,Δv,j,scaling)=armijo_rule(nep,errmeasure,err,\n                                          λ,v,Δλ,Δv,real(T(armijo_factor)),armijo_max)\n\n            if (j>0)\n                push_info!(logger,\" Armijo scaling=$scaling\")\n            else\n                push_info!(logger,\"\")\n            end\n\n            λ+=Δλ\n            v[:]+=Δv\n\n        end\n\n        msg=\"Number of iterations exceeded. maxit=$(maxit).\"\n        throw(NoConvergenceException(λ,v,err,msg))\n    end\n\n\n\"\"\"\n    quasinewton([T=ComplexF64],nep,[errmeasure,][tol,][maxit,][λ,][v][ws][logger][linsolvercreator,][armijo_factor,][armijo_max])\n\nAn implementation of the quasi-Newton approach referred to as quasi-Newton 2 in the reference.\nThe method involves one linear system solve per iteration corresponding with the\nmatrix ``M(λ)``, where ``λ`` is constant.\nThe vector `ws` is a representation of the normalization, in the sense that ``c^T=w_s^TM(λ)``,\nwhere all iterates satisfy ``c^Tx_i=1``.\nSee [`augnewton`](@ref) for other parameters.\n\n\n# Example\n```julia-repl\njulia> nep=nep_gallery(\"pep0\")\njulia> λ,v=quasinewton(nep,λ=1.0,v=ones(size(nep,1)));\njulia> norm(compute_Mlincomb(nep,λ,v))/norm(v)\n5.448264607410413e-12\n```\n\n# References\n* Jarlebring, Koskela, Mele, Disguised and new Quasi-Newton methods for nonlinear eigenvalue problems, Numer. Algorithms, 79:311-335, 2018. [preprint](https://arxiv.org/abs/1702.08492)\n\"\"\"\n    quasinewton(nep::NEP;params...)=quasinewton(ComplexF64,nep;params...)\n    function quasinewton(::Type{T},\n                         nep::NEP;\n                         errmeasure = DefaultErrmeasure(nep),\n                         tol::Real=eps(real(T))*100,\n                         maxit::Int=100,\n                         λ::Number=zero(T),\n                         v::Vector=randn(real(T),size(nep,1)),\n                         ws::Vector=v,\n                         logger=0,\n                         linsolvercreator=DefaultLinSolverCreator(),\n                         armijo_factor::Real=1,\n                         armijo_max::Int=5) where T\n\n        @parse_logger_param!(logger)\n\n\n        # Ensure types λ and v are of type T\n        λ=T(λ)\n        v=Vector{T}(v)\n        ws=Vector{T}(ws) # Left vector such that c'=w'M(λ) where c normalization\n\n        n = size(nep,1)\n        u = zeros(T,n)\n        w = zeros(T,n)\n\n        err=Inf;\n\n        local linsolver::LinSolver;\n        push_info!(logger,\"Precomputing linsolver\")\n        linsolver = create_linsolver(linsolvercreator,nep,λ)\n\n\n        for k=1:maxit\n            err=estimate_error(errmeasure,λ,v)\n            push_iteration_info!(logger,k,err=err,λ=λ,v=v,continues=true);\n            if (err< tol)\n                push_info!(logger,\"\")\n                return (λ,v)\n            end\n\n\n            # Compute u=M(λ)v and w=M'(λ)v\n            u[:] = compute_Mlincomb(nep,λ,v,[T(1)],0);\n            w[:] = compute_Mlincomb(nep,λ,v,[T(1)],1);\n\n            # Intermediate quantities\n            Δλ=-dot(ws,u)/dot(ws,w);\n            z=Δλ*w+u;\n            # Throws an error if lin_solve returns incorrect type.\n            local Δv::Vector{T}= -lin_solve(linsolver, z, tol=tol)\n\n            normΔv=norm(Δv);\n            push_info!(logger,2,\" norm(Δv)=$normΔv\",continues=true)\n\n            (Δλ,Δv,j,scaling)=armijo_rule(nep,errmeasure,err,\n                                          λ,v,Δλ,Δv,real(T(armijo_factor)),armijo_max)\n\n            if (j>0)\n                push_info!(logger,\" Armijo scaling=$scaling\")\n            else\n                push_info!(logger,\"\");\n            end\n\n            # Update eigenpair\n            λ += Δλ\n            v[:] += Δv; # eigvec update\n\n        end\n\n        msg=\"Number of iterations exceeded. maxit=$(maxit).\"\n        throw(NoConvergenceException(λ,v,err,msg))\n    end\n\n\n\"\"\"\n    λ,v = newtonqr([eltype],nep::NEP;[errmeasure,][tol,][maxit,][λ,][v,][c,][logger])\n\nThis function implements the Newton-QR method as formulated in the reference. The method ivolves the computation of a rank-revealing QR factorization\nof ``M(λ)``, with the idea that on convergence the the last diagonal element ``R[n,n]`` of the upper-triangular matrix ``R`` becomes zero as a result of ``M(λ)``\nbecoming singular. Since the computation of a QR factorization is expensive, it is advisable to use this method for problems of small size or problems with\na certain structure that makes the QR computation less expensive.\nSee [`augnewton`](@ref) for other parameters.\n\n# Example\n```julia-repl\njulia> nep=nep_gallery(\"pep0\")\njulia> λ,v=newtonqr(nep,v=ones(size(nep,1)));\njulia> norm(compute_Mlincomb(nep,λ,v))/norm(v)\n8.440206093655014e-15\n```\n\n# References\n* Kublanovskaya, V. N., (1970).  On an approach to the solution of the generalized latent value problem for λ-matrices, SIAM J. Numer. Anal. 7, 532–537\n* Güttel, S., & Tisseur, F. (2017). The nonlinear eigenvalue problem. Acta Numerica, 26, 1-94. doi:10.1017/S0962492917000034\n\"\"\"\n    newtonqr(nep::NEP;params...)=newtonqr(ComplexF64,nep;params...)\n    function newtonqr(::Type{T},\n                      nep::NEP;\n                      errmeasure::ErrmeasureType = DefaultErrmeasure(nep),\n                      tol::Real=eps(real(T))*100,\n                      maxit::Int=100,\n                      λ::Number=zero(T),\n                      v::Vector=randn(real(T),size(nep,1)),\n                      c::Vector=v,\n                      logger=0) where T\n\n        @parse_logger_param!(logger)\n\n\n        # Ensure types λ and v are of type T\n        λ=T(λ)\n        v=Vector{T}(v)\n        c=Vector{T}(c)\n\n        n = size(nep,1);\n        local err\n        local w\n\n        en = zeros(n);\n        en[n] = 1;\n\n\n        for k=1:maxit\n            A = compute_Mder(nep,λ);\n            Q,R,PI = qr(A, Val(true)) #QR factorization with pivoting.\n            Q = Matrix(Q)\n\n            P = Matrix{T}(I, n, n)[:,PI] #The permutation matrix corresponding to the pivoted QR.\n\n            p = R[1:n-1,1:n-1]\\R[1:n-1,n];\n            v = P*[-p;T(1)];#Right eigenvector\n            w = Q*en;#Left eigenvector\n\n            #err = abs(R[n,n])/norm(compute_Mder(nep,λ),2); # Frobenius norm\n            err=estimate_error(errmeasure,λ,v);\n\n\n            push_iteration_info!(logger,k,err=err,λ=λ,v=v);\n            if(err < tol)\n                return λ,v,w;\n            end\n\n\n            d = dot(Q[:,n],compute_Mlincomb(nep,λ,reshape(v,n,1),[T(1)],1));\n            #d = dot(Q[:,n],compute_Mder(nep,λ,1)*P*[-p;T(1.0)]);\n            λ = λ - R[n,n]/d;\n        end\n\n        msg=\"Number of iterations exceeded. maxit=$(maxit).\"\n        throw(NoConvergenceException(λ,v,err,msg))\n    end\n\n\n\"\"\"\n    λ,v = implicitdet([eltype],nep::NEP;[errmeasure,][tol,][maxit,][λ,][v,][c,][logger])\n\nThis function implements the Implicit determinant method as formulated Algorithm 4.3 in the reference. The method applies Newton-Raphson to the equation\n``det(M(λ))/det(G(λ)) = 0``, where ``G(λ)`` is a saddle point matrix with ``M(λ)``\nin the (1,1) block. The (2,1) and (1,2) blocks of ``G(λ)`` are set to\n``c^H`` and ``c`` respectively. Note that ``G(λ) `` can be non-singular even when ``M(λ) ``\nis singular. See reference for more information.\nSee [`augnewton`](@ref) for other parameters.\n\n# Example\n```julia-repl\njulia> nep=nep_gallery(\"pep0\")\njulia> λ,v=implicitdet(nep,v=ones(size(nep,1)));\njulia> norm(compute_Mlincomb(nep,λ,v))/norm(v)\n2.566371972986362e-14\n```\n\n# References\n* Spence, A., & Poulton, C. (2005). Photonic band structure calculations using nonlinear eigenvalue techniques, J. Comput. Phys., 204 (2005), pp. 65–8\n* Güttel, S., & Tisseur, F. (2017). The nonlinear eigenvalue problem. Acta Numerica, 26, 1-94. doi:10.1017/S0962492917000034\n\"\"\"\n    implicitdet(nep::NEP;params...)=implicitdet(ComplexF64,nep;params...)\n    function implicitdet(::Type{T},\n                         nep::NEP;\n                         errmeasure::ErrmeasureType = DefaultErrmeasure(nep),\n                         tol=eps(real(T))*100,\n                         maxit=100,\n                         λ=zero(T),\n                         v=randn(real(T),size(nep,1)),\n                         c=v,\n                         logger=0) where T\n\n        @parse_logger_param!(logger)\n\n        n = size(nep,1);\n        v = Vector{T}(vcat(v,one(T)))\n        vp = zeros(T,n+1)\n        c = Vector{T}(c);\n        b = c;\n        P = Matrix{T}(I, n+1, n+1)\n\n        local err\n\n\n        for k=1:maxit\n\n            A = compute_Mder(nep,λ);\n            AA = [A b;c' 0];#The matrix G(λ)\n\n            F = lu(AA);\n\n            v[:] = F\\([zeros(T,n);T(1)]);\n            vp[:] = F\\([-1*compute_Mder(nep,λ,1)*v[1:n];0]);\n\n            #err = estimate_error(errmeasure,λ,v[1:n]);\n            err = abs(v[n+1])/norm(compute_Mder(nep,λ),2); # Frobenius norm based error\n            push_iteration_info!(logger,k,err=err,λ=λ,v=v);\n            if(err < tol)\n                return λ,v[1:n];\n            end\n\n            λ = λ - v[n+1]/vp[n+1];#Newton update for the equation det(M(λ))/det(G(λ)) = 0\n        end\n\n        msg=\"Number of iterations exceeded. maxit=$(maxit).\"\n        throw(NoConvergenceException(λ,v,NaN,msg))\n    end\n\n\n    # Armijo rule implementation\n    function armijo_rule(nep,errmeasure,err0,λ,v,Δλ,Δv,armijo_factor,armijo_max)\n        j=0\n        if (armijo_factor<1)\n            # take smaller and smaller steps until errmeasure is decreasing\n            while (estimate_error(errmeasure,λ+Δλ,v+Δv)>err0 && j<armijo_max)\n                j=j+1;\n                Δv=Δv*armijo_factor;\n                Δλ=Δλ*armijo_factor;\n            end\n        end\n        return  (Δλ,Δv,j,armijo_factor^j)\n    end\n", "meta": {"hexsha": "c1450428b078227d30e32c69c2c3e3328b2a8d11", "size": 20225, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/method_newton.jl", "max_stars_repo_name": "harrymd/NonlinearEigenproblems.jl", "max_stars_repo_head_hexsha": "ffb050eb040dc22cb9c3c00c38da117b45ca7937", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2018-06-07T09:54:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T06:57:07.000Z", "max_issues_repo_path": "src/method_newton.jl", "max_issues_repo_name": "harrymd/NonlinearEigenproblems.jl", "max_issues_repo_head_hexsha": "ffb050eb040dc22cb9c3c00c38da117b45ca7937", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 180, "max_issues_repo_issues_event_min_datetime": "2018-06-06T11:25:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T21:49:00.000Z", "max_forks_repo_path": "src/method_newton.jl", "max_forks_repo_name": "harrymd/NonlinearEigenproblems.jl", "max_forks_repo_head_hexsha": "ffb050eb040dc22cb9c3c00c38da117b45ca7937", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2018-06-05T15:30:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T08:39:25.000Z", "avg_line_length": 33.1557377049, "max_line_length": 296, "alphanum_fraction": 0.5621260816, "num_tokens": 5700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7563594176418349}}
{"text": "#An Extended Kalman Filter (EKF) example taken from Markus Gesmann's\n#Mages' blog titled \"Extended Kalman filter example in R\" [1] which in turn\n#was taken from a blog post titled \"Fun with (Extended Kalman) Filters\"\n#by Dominic Steinitz [2].\n#The web addresses are:\n#[1] http://www.magesblog.com/2015/01/extended-kalman-filter-example-in-r.html\n#[2] https://idontgetoutmuch.wordpress.com/2014/09/09/fun-with-extended-kalman-filters-4/\n\n#Here we import the required modules\nusing StateSpace\nusing Distributions\nusing Gadfly\nusing DataFrames\nusing Colors\n\n################################################################################\n#Section: Generate noisy Observations\n#-------------------------------------------------------------------------------\n\n#Here we set the parameters with their true values\nr = 0.2 #r is the growth rate\nk = 100.0 #k is the carrying capacity\np0 = 0.1 * k # p0 is the initial population\nΔt = 0.1 # Δt is the change in time.\n\n#Define the logistic growth function to set the observations\nfunction logisticGrowth(r, p, k, t)\n    k * p * exp(r*t) / (k + p * (exp(r*t) - 1))\nend\nlogisticGrowth(state) = logisticGrowth(state[1], state[2], k, Δt)\n\n#Set the measurement noise variance\nmeasurement_noise_variance = 25.0\n\n#create the noisy observations (zero mean Gaussian noise)\nnumObs = 100\ntrue_values = Vector{Float64}(numObs)\npopulation_measurements = Vector{Float64}(numObs)\nfor i in 1:numObs\n    true_values[i] = logisticGrowth(r, p0, k, i*Δt)\n    population_measurements[i] = true_values[i] + randn() * sqrt(measurement_noise_variance)\nend\n\n#Since we're going to assume that our state consists of a growth rate, r,\n#as well as a population rate, p, we need measurements of the growth rate.\n#The problem is that we don't actually observe the growth rate directly.\n#So we will set these measurements to zero.\ngrowth_rate_measurements = zeros(numObs)\n\n#Then we put these measurements together\nmeasurements = [growth_rate_measurements population_measurements]'\n#End Section: Generate noisy Observations\n################################################################################\n\n################################################################################\n#Section: Describe Extended Kalman Filter parameters\n#-------------------------------------------------------------------------------\n#The state consists of the growth rate, r, and the population number, p. We'll\n#assume that the growth rate is constant throughout time. And we'll assume that\n#the population update follows the logistic growth pattern. So let's create that\n#process function\nfunction process_fcn(state)\n    predict_growth_rate = state[1]\n    predict_population = logisticGrowth(state)\n    new_state = [predict_growth_rate, predict_population]\n    return new_state\nend\n#Here we assume that there is no evolution noise so well create a zero matrix\nprocess_noise_mat = diagm([0.001, 0.001])\n\n#Now we need to describe the observation model. We'll assume that we don't\n#observe the growth rate but we do observe the population. So the observation\n#function is:\nfunction observation_fcn(state)\n    growth_rate_observation = 0.0\n    population_observation = 1.0 * state[2]\n    observation = [growth_rate_observation, population_observation]\n    return observation\nend\n\n#Now we need to set the observation noise. We already set the measurement noise\n#for the population earlier. We'lll arbitrarily make the variance for the\n#growth rate (it doesn't matter because we don't explicity observe it):\nobservation_noise_mat = diagm([1.0, measurement_noise_variance])\n\n#Create instance of our EKF model\nnonLinSSM = NonlinearGaussianSSM(process_fcn, process_noise_mat, observation_fcn, observation_noise_mat)\n#End Section: Describe Extended Kalman Filter parameters\n################################################################################\n\n################################################################################\n#Section: Set initial guess of the state\n#-------------------------------------------------------------------------------\ninitial_guess = MvNormal([0.5, 10], diagm([1.0,20.0]))\n################################################################################\n\n\n################################################################################\n#Section: Execute the Extended Kalman Filter\n#-------------------------------------------------------------------------------\nfiltered_state = filter(nonLinSSM, measurements, initial_guess)\n#End Section: Execute  the Extended Kalman Filter\n################################################################################\n\n\n################################################################################\n#Section: Plot Filtered results\n#-------------------------------------------------------------------------------\n#Here we are plotting the filtered results with Gadfly. See the Gadfly\n#documentation for information about how plotting works if you are unfamiliar.\n#Website: http://gadflyjl.org/\n\nx_data = 1:numObs\npopulation_array = Vector{Float64}(numObs+1)\nconfidence_array = Vector{Float64}(numObs+1)\npopulation_array[1] = initial_guess.μ[2]\nconfidence_array[1] = 2*sqrt(initial_guess.Σ.mat[2,2])\nfor i in x_data\n    current_state = filtered_state.state[i]\n    population_array[i+1] = current_state.μ[2]\n    confidence_array[i+1] = 2*sqrt(current_state.Σ.mat[2,2])\nend\ndf_fs = DataFrame(\n    x = [0;x_data],\n    y = population_array,\n    ymin = population_array - confidence_array,\n    ymax = population_array + confidence_array,\n    f = \"Filtered values\"\n    )\n\nn = 3\ngetColors = distinguishable_colors(n, Color[LCHab(70, 60, 240)],\n                                   transform=c -> deuteranopic(c, 0.5),\n                                   lchoices=Float64[65, 70, 75, 80],\n                                   cchoices=Float64[0, 50, 60, 70],\n                                   hchoices=linspace(0, 330, 24))\npopulation_state_plot = plot(\n    layer(x=0:numObs, y=[p0;measurements[2,:]'], Geom.point, Theme(default_color=getColors[2])),\n    layer(x=0:numObs, y=[p0;true_values], Geom.line, Theme(default_color=getColors[3])),\n    layer(df_fs, x=:x, y=:y, ymin=:ymin, ymax=:ymax, Geom.line, Geom.ribbon),\n    Guide.xlabel(\"Measurement Number\"), Guide.ylabel(\"Population\"),\n    Guide.manual_color_key(\"Colour Key\",[\"Filtered Estimate\", \"Measurements\",\"True Value \"],[getColors[1],getColors[2],getColors[3]]),\n    Guide.title(\"Extended Kalman Filter Example\")\n    )\ndisplay(population_state_plot)\n#End Section: Plot Filtered results\n################################################################################\n\n\n################################################################################\n#Section: Plot Filtered results\n#-------------------------------------------------------------------------------\n#Here we are plotting the filtered results with Gadfly. See the Gadfly\n#documentation for information about how plotting works if you are unfamiliar.\n#Website: http://gadflyjl.org/\n\nx_data = 1:numObs\ngrowth_rate_array = Vector{Float64}(numObs+1)\nconfidence_array = Vector{Float64}(numObs+1)\ngrowth_rate_array[1] = initial_guess.μ[1]\nconfidence_array[1] = initial_guess.Σ.mat[1,1]\nfor i in x_data\n    current_state = filtered_state.state[i]\n    growth_rate_array[i+1] = current_state.μ[1]\n    confidence_array[i+1] = 2*sqrt(current_state.Σ.mat[1,1])\nend\ndf_fs = DataFrame(\n    x = [0;x_data],\n    y = growth_rate_array,\n    ymin = growth_rate_array - confidence_array,\n    ymax = growth_rate_array + confidence_array,\n    f = \"Filtered values\"\n    )\n\ngrowth_rate_state_plot = plot(\n    layer(x=0:numObs, y=ones(numObs+1)*r, Geom.line, Theme(default_color=getColors[3])),\n    layer(df_fs, x=:x, y=:y, ymin=:ymin, ymax=:ymax, Geom.line, Geom.ribbon),\n    Guide.xlabel(\"Measurement Number\"), Guide.ylabel(\"Growth Rate\"),\n    Guide.manual_color_key(\"Colour Key\",[\"Filtered Estimate\", \"Measurements\",\"True Value \"],[getColors[1],getColors[2],getColors[3]]),\n    Guide.title(\"Extended Kalman Filter Example\")\n    )\ndisplay(growth_rate_state_plot)\n#End Section: Plot Filtered results\n################################################################################\n", "meta": {"hexsha": "8f61d8a82a9f0af832fcc7f11d02d47ecfa37f17", "size": 8132, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ExtendedKalmanFilter_LogisticGrowthExample.jl", "max_stars_repo_name": "npsmc/StateSpace.jl", "max_stars_repo_head_hexsha": "2175c85b23dfbf3178d508a5c749627594e719e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2015-04-30T13:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T12:04:59.000Z", "max_issues_repo_path": "examples/ExtendedKalmanFilter_LogisticGrowthExample.jl", "max_issues_repo_name": "npsmc/StateSpace.jl", "max_issues_repo_head_hexsha": "2175c85b23dfbf3178d508a5c749627594e719e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2015-08-12T04:04:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-01T02:35:35.000Z", "max_forks_repo_path": "examples/ExtendedKalmanFilter_LogisticGrowthExample.jl", "max_forks_repo_name": "npsmc/StateSpace.jl", "max_forks_repo_head_hexsha": "2175c85b23dfbf3178d508a5c749627594e719e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-02-24T23:33:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T18:55:35.000Z", "avg_line_length": 43.9567567568, "max_line_length": 134, "alphanum_fraction": 0.6051401869, "num_tokens": 1801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7563594176070073}}
{"text": "immutable Skellam <: DiscreteUnivariateDistribution\n    μ1::Float64\n    μ2::Float64\n\n    function Skellam(μ1::Float64, μ2::Float64)\n        μ1 > 0.0 && μ2 > 0.0 || error(\"μ1 and μ2 must be positive.\")\n        new(μ1, μ2)\n    end\n\n    @compat Skellam(μ1::Real, μ2::Real) = Skellam(Float64(μ1), Float64(μ2))\n\n    Skellam(μ::Real) = Skellam(μ, μ)\n\n    Skellam() = new(1.0, 1.0)\nend\n\n@distr_support Skellam -Inf Inf\n\n\n### Parameters\n\nparams(d::Skellam) = (d.μ1, d.μ2)\n\n\n### Statistics\n\nmean(d::Skellam) = d.μ1 - d.μ2\n\nvar(d::Skellam) = d.μ1 + d.μ2\n\nskewness(d::Skellam) = mean(d) / (var(d)^1.5)\n\nkurtosis(d::Skellam) = 1.0 / var(d)\n\n\n### Evaluation\n\nfunction logpdf(d::Skellam, x::Int)\n    μ1, μ2 = params(d)\n    - (μ1 + μ2) + (x / 2.0) * log(μ1 / μ2) + log(besseli(x, 2.0 * sqrt(μ1) * sqrt(μ2)))\nend\n\npdf(d::Skellam, x::Int) = exp(logpdf(d, x))\n\nfunction mgf(d::Skellam, t::Real)\n    μ1, μ2 = params(d)\n    exp(-(μ1 + μ2) + μ1 * exp(t) + μ2 * exp(-t))\nend\n\nfunction cf(d::Skellam, t::Real)\n    μ1, μ2 = params(d)\n    exp(-(μ1 + μ2) + μ1 * cis(t) + μ2 * cis(-t))\nend\n\n### Sampling\n\nrand(d::Skellam) = rand(Poisson(d.μ1)) - rand(Poisson(d.μ2))\n\n", "meta": {"hexsha": "d5fdd3a5c288c8aa1784c5eb89d374632f386cf6", "size": 1140, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/discrete/skellam.jl", "max_stars_repo_name": "wildart/Distributions.jl", "max_stars_repo_head_hexsha": "041315226c919c1a6c7dae8437bddd61907bc73b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/discrete/skellam.jl", "max_issues_repo_name": "wildart/Distributions.jl", "max_issues_repo_head_hexsha": "041315226c919c1a6c7dae8437bddd61907bc73b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/discrete/skellam.jl", "max_forks_repo_name": "wildart/Distributions.jl", "max_forks_repo_head_hexsha": "041315226c919c1a6c7dae8437bddd61907bc73b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3220338983, "max_line_length": 87, "alphanum_fraction": 0.5745614035, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8267118004748678, "lm_q1q2_score": 0.756359413840182}}
{"text": "function constantdiffusionproblem(stepper; nx=128, Lx=2π, kappa=1e-2, nsteps=1000, dev=CPU())\n   τ = 1/kappa  # time-scale for diffusive decay\n  dt = 1e-9 * τ # dynamics are resolved\n\n  prob = Problem(nx=nx, Lx=Lx, kappa=kappa, dt=dt, stepper=stepper, dev=dev)\n  g = prob.grid\n\n  # a gaussian initial condition c(x, t=0)\n  c0ampl, σ = 0.01, 0.2\n  c0func(x) = @. c0ampl*exp(-x^2/(2σ^2))\n  c0 = c0func.(g.x)\n\n  # analytic solution for for 1D heat equation with constant κ\n  tfinal = nsteps*dt\n  σt = sqrt(2*kappa*tfinal + σ^2)\n  cfinal = @. c0ampl*σ/σt * exp(-g.x^2/(2*σt^2))\n\n  set_c!(prob, c0)\n  tcomp = @elapsed stepforward!(prob, nsteps)\n  updatevars!(prob)\n\n  prob, c0, cfinal, nsteps, tcomp\nend\n\nfunction varyingdiffusionproblem(stepper; nx=128, Lx=2π, kappa=1e-2, nsteps=1000, dev=CPU())\n   τ = 1/kappa  # time-scale for diffusive decay\n  dt = 1e-9 * τ # dynamics are resolved\n\n  kappa = kappa*ones(nx) # this is actually a constant diffusion but defining it\n                         # as an array makes stepforward! call function calcN!\n                         # instead of just the linear coefficients L*sol\n\n  prob = Problem(nx=nx, Lx=Lx, kappa=kappa, dt=dt, stepper=stepper, dev=dev)\n  g = prob.grid\n\n  # a gaussian initial condition c(x, t=0)\n  c0ampl, σ = 0.01, 0.2\n  c0func(x) = @. c0ampl*exp(-x^2/(2σ^2))\n  c0 = c0func.(g.x)\n\n  # analytic solution for for 1D heat equation with constant κ\n  tfinal = nsteps*dt\n  σt = sqrt(2*kappa[1]*tfinal + σ^2)\n  cfinal = @. c0ampl*σ/σt * exp(-g.x^2/(2*σt^2))\n\n  set_c!(prob, c0)\n  tcomp = @elapsed stepforward!(prob, nsteps)\n  updatevars!(prob)\n\n  prob, c0, cfinal, nsteps, tcomp\nend\n\n\nfunction constantdiffusiontest(stepper, dev::Device=CPU(); kwargs...)\n  prob, c0, c1, nsteps, tcomp = constantdiffusionproblem(stepper; kwargs...)\n  normmsg = \"$stepper: relative error =\"\n  @printf(\"% 40s %.2e (%.3f s)\\n\", normmsg, norm(c1-prob.vars.c)/norm(c1), tcomp)\n  isapprox(c1, prob.vars.c, rtol=nsteps*rtol_timesteppers)\nend\n\nfunction varyingdiffusiontest(stepper, dev::Device=CPU(); kwargs...)\n  prob, c0, c1, nsteps, tcomp = varyingdiffusionproblem(stepper; kwargs...)\n  normmsg = \"$stepper: relative error =\"\n  @printf(\"% 40s %.2e (%.3f s)\\n\", normmsg, norm(c1-prob.vars.c)/norm(c1), tcomp)\n  isapprox(c1, prob.vars.c, rtol=nsteps*rtol_timesteppers)\nend\n", "meta": {"hexsha": "b76cb16b1dd8778173eef0cd273b26e80b9c88fb", "size": 2302, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_timesteppers.jl", "max_stars_repo_name": "UnofficialJuliaMirror/FourierFlows.jl-2aec4490-903f-5c70-9b11-9bed06a700e1", "max_stars_repo_head_hexsha": "079fddb30256f719dcd071f57a2451af2e993e27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-15T18:46:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T18:46:22.000Z", "max_issues_repo_path": "test/test_timesteppers.jl", "max_issues_repo_name": "UnofficialJuliaMirror/FourierFlows.jl-2aec4490-903f-5c70-9b11-9bed06a700e1", "max_issues_repo_head_hexsha": "079fddb30256f719dcd071f57a2451af2e993e27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_timesteppers.jl", "max_forks_repo_name": "UnofficialJuliaMirror/FourierFlows.jl-2aec4490-903f-5c70-9b11-9bed06a700e1", "max_forks_repo_head_hexsha": "079fddb30256f719dcd071f57a2451af2e993e27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-15T18:46:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T18:46:24.000Z", "avg_line_length": 34.3582089552, "max_line_length": 93, "alphanum_fraction": 0.6598609904, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009573133051, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.756359413770527}}
{"text": "module Skew\n\nmvnrnd(n,mu,C) = sqrtm(C)*randn(size(C,1),n) .+ mu\n\n# Generate n random samples from SkewNormal(Omega,alpha).\n#    Omega = d-by-d \"correlation\" matrix (a covariance matrix with ones on the diagonal).\n#    alpha = length d vector of skew parameters.\n# (This implements Proposition 1 of Azzalini & Capitanio (1999).)\nfunction skewrndNd(n,Omega,alpha)\n    delta = (Omega*alpha)/sqrt(1+dot(alpha,Omega*alpha))\n    x = mvnrnd(n,0,[1 delta'; delta Omega])\n    return sign(x[1,:]).*x[2:end,:]\nend\n\n# Generate n random samples from SkewNormal(xi,C,alpha).\n#    xi = length d vector of location parameters (it is not necessarily the mean of the resulting samples).\n#    C = d-by-d posdef matrix (it is not necessarily the covariance matrix of the resulting samples).\n#    alpha = length d vector of skew parameters.\n# (This implements the location-scale extension in Section 5.1 of Azzalini & Capitanio (1999).)\nfunction skewrndNd(n,xi,C,alpha)\n    s = sqrt(diag(C))\n    Omega = (1.0./s) .* C .* (1.0./s)'\n    return xi .+ s.*skewrndNd(n,Omega,alpha)\nend\n\n# Compute the mean of Z ~ SkewNormal(Omega,alpha).\n# (See Equation (4) of Azzalini & Capitanio (1999).)\nmu(Omega,alpha) = (delta = (Omega*alpha)/sqrt(1+dot(alpha,Omega*alpha)); sqrt(2/pi)*delta)\n\n# Compute the covariance matrix of Z ~ SkewNormal(Omega,alpha).\n# (See Equation (4) of Azzalini & Capitanio (1999).)\nCov(Omega,alpha) = (m = mu(Omega,alpha); Omega-m*m')\n\n# Generate n random samples from SkewNormal(Omega,alpha) and transform them so that each entry has zero mean and unit variance.\nskewrndNormalized(n,Omega,alpha) = (skewrndNd(n,Omega,alpha) .- mu(Omega,alpha))./sqrt(diag(Cov(Omega,alpha)))\n\nend\n\n", "meta": {"hexsha": "2a771720a04038a8011e1f5ad06587ac57382d0d", "size": 1672, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "variable-selection/skew.jl", "max_stars_repo_name": "jwmi/CoarsenedPosterior", "max_stars_repo_head_hexsha": "dc230af244281f5fb9a9f657d2a534eb1a720560", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-16T23:26:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-16T23:26:55.000Z", "max_issues_repo_path": "variable-selection/skew.jl", "max_issues_repo_name": "jwmi/CoarsenedPosterior", "max_issues_repo_head_hexsha": "dc230af244281f5fb9a9f657d2a534eb1a720560", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "variable-selection/skew.jl", "max_forks_repo_name": "jwmi/CoarsenedPosterior", "max_forks_repo_head_hexsha": "dc230af244281f5fb9a9f657d2a534eb1a720560", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-10-21T14:06:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-29T16:06:46.000Z", "avg_line_length": 42.8717948718, "max_line_length": 127, "alphanum_fraction": 0.6991626794, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7563594118871141}}
{"text": "### Edge and Gradient Related Image Operations ###\n\n# Edge/gradient filters\n\nfunction sobel()\n    f = [ -1.0  0.0  1.0\n          -2.0  0.0  2.0\n          -1.0  0.0  1.0 ]\n    return f', f\nend\n\nfunction prewitt()\n    f = [ -1.0  0.0  1.0\n          -1.0  0.0  1.0\n          -1.0  0.0  1.0 ]\n    return f', f\nend\n\n# Consistent Gradient Operators\n# Ando Shigeru\n# IEEE Trans. Pat. Anal. Mach. Int., vol. 22 no 3, March 2000\n#\n# TODO: These coefficients were taken from the paper It would be nice\n#       to resolve the optimization problem and use higher precision\n#       versions, which might allow better separable approximations of\n#       ando4 and ando5.\n\nfunction ando3()\n    f = [ -0.112737  0.0  0.112737\n          -0.274526  0.0  0.274526\n          -0.112737  0.0  0.112737 ]\n    return f', f\nend\n\n# Below, the ando4() and ando5() functions return filters with\n# the published filter values.  The ando4_sep() and ando5_sep()\n# functions return separable approximations to the corresponding\n# filters, estimated using the projection of the actual values on the\n# eigenvector corresponding to the largest eigenvalue of the SVD of\n# the original filter.\n\nfunction ando4()\n    f = [ -0.022116 -0.025526  0.025526  0.022116\n          -0.098381 -0.112984  0.112984  0.098381\n          -0.098381 -0.112984  0.112984  0.098381\n          -0.022116 -0.025526  0.025526  0.022116 ]\n    return f', f\nend\n\nfunction ando4_sep()\n    f = [-0.022175974729759376 -0.025473821998749126 0.025473821998749126 0.022175974729759376\n         -0.09836750569692418  -0.11299599504060115  0.11299599504060115  0.09836750569692418\n         -0.09836750569692418  -0.11299599504060115  0.11299599504060115  0.09836750569692418\n         -0.022175974729759376 -0.025473821998749126 0.025473821998749126 0.022175974729759376]\n    return f', f\nend\n\nfunction ando5()\n    f = [ -0.003776 -0.010199  0.0  0.010199  0.003776\n          -0.026786 -0.070844  0.0  0.070844  0.026786\n          -0.046548 -0.122572  0.0  0.122572  0.046548\n          -0.026786 -0.070844  0.0  0.070844  0.026786\n          -0.003776 -0.010199  0.0  0.010199  0.003776 ]\n    return f', f\nend\n\nfunction ando5_sep()\n    f = [-0.0038543900766123762 -0.0101692999709622   0.0  0.0101692999709622   0.0038543900766123762\n         -0.026843218687756566  -0.07082229291692607  0.0  0.07082229291692607  0.026843218687756566\n         -0.046468878396946627  -0.12260200818803602  0.0  0.12260200818803602  0.046468878396946627\n         -0.026843218687756566  -0.07082229291692607  0.0  0.07082229291692607  0.026843218687756566\n         -0.0038543900766123762 -0.0101692999709622   0.0  0.0101692999709622   0.0038543900766123762]\n    return f', f\nend\n\n# Image gradients in the X and Y direction\nfunction imgradients(img::AbstractArray, method::String=\"ando3\", border::String=\"replicate\")\n    sx,sy = spatialorder(img)[1] == \"x\" ? (1,2) : (2,1)\n    s = (method == \"sobel\"     ? sobel() :\n         method == \"prewitt\"   ? prewitt() :\n         method == \"ando3\"     ? ando3() :\n         method == \"ando4\"     ? ando4() :\n         method == \"ando5\"     ? ando5() :\n         method == \"ando4_sep\" ? ando4_sep() :\n         method == \"ando5_sep\" ? ando5_sep() :\n         error(\"Unknown gradient method: $method\"))\n\n    grad_x = imfilter(img, s[sx], border)\n    grad_y = imfilter(img, s[sy], border)\n\n    return grad_x, grad_y\nend\n\n# Magnitude of gradient, calculated from X and Y image gradients\nmagnitude(grad_x::AbstractArray, grad_y::AbstractArray) = hypot(grad_x, grad_y)\n\n# Phase (angle of steepest gradient ascent), calculated from X and Y gradient images\nfunction phase{T}(grad_x::AbstractArray{T}, grad_y::AbstractArray{T})\n    EPS = sqrt(eps(eltype(T)))\n    # Set phase to zero when both gradients are close to zero\n    reshape([atan2(-grad_y[i], grad_x[i]) * ((abs(grad_x[i]) > EPS) | (abs(grad_y[i]) > EPS))\n             for i=1:length(grad_x)], size(grad_x))\nend\n\nfunction phase(grad_x::AbstractImageDirect, grad_y::AbstractImageDirect)\n    img = copy(grad_x, phase(data(grad_x), data(grad_y)))\n    img[\"limits\"] = (-float(pi),float(pi))\n    img\nend\n\n# Orientation of the strongest edge at a point, calculated from X and Y gradient images\n# Note that this is perpendicular to the phase at that point, except where\n# both gradients are close to zero.\n\nfunction orientation{T}(grad_x::AbstractArray{T}, grad_y::AbstractArray{T})\n    EPS = sqrt(eps(eltype(T)))\n    # Set orientation to zero when both gradients are close to zero\n    # (grad_y[i] should probably be negated here, but isn't for consistency with earlier releases)\n    reshape([atan2(grad_x[i], grad_y[i]) * ((abs(grad_x[i]) > EPS) | (abs(grad_y[i]) > EPS))\n             for i=1:length(grad_x)], size(grad_x))\nend\n\nfunction orientation(grad_x::AbstractImageDirect, grad_y::AbstractImageDirect)\n    img = copy(grad_x, orientation(data(grad_x), data(grad_y)))\n    img[\"limits\"] = (-float(pi),float(pi))\n    img\nend\n\n# Return both the magnitude and phase in one call\nmagnitude_phase(grad_x::AbstractArray, grad_y::AbstractArray) = (magnitude(grad_x,grad_y), phase(grad_x,grad_y))\n\n# Return the magnituded and phase of the gradients in an image\nfunction magnitude_phase(img::AbstractArray, method::String=\"ando3\", border::String=\"replicate\")\n    grad_x, grad_y = imgradients(img, method, border)\n    return magnitude_phase(grad_x, grad_y)\nend\n\n# Return the x-y gradients and magnitude and phase of gradients in an image\nfunction imedge(img::AbstractArray, method::String=\"ando3\", border::String=\"replicate\")\n    grad_x, grad_y = imgradients(img, method, border)\n    mag = magnitude(grad_x, grad_y)\n    orient = orientation(grad_x, grad_y)\n    return (grad_x, grad_y, mag, orient)\nend\n\n# Thin edges\nthin_edges{T}(img::AbstractArray{T,2}, gradientangles::AbstractArray, border::String=\"replicate\") =\n    thin_edges_nonmaxsup(img, gradientangles, border)\nthin_edges_subpix{T}(img::AbstractArray{T,2}, gradientangles::AbstractArray, border::String=\"replicate\") =\n    thin_edges_nonmaxsup_subpix(img, gradientangles, border)\n\n# Code below is related to non-maximal suppression, and was ported to Julia from\n# http://www.csse.uwa.edu.au/~pk/research/matlabfns/Spatial/nonmaxsup.m\n# (Please conserve the original copyright below.)\n\n# NONMAXSUP - Non-maxima suppression\n#\n# Usage:\n#          (im,location) = nonmaxsup(img, gradientangles, radius);\n#\n# Function for performing non-maxima suppression on an image using\n# gradient angles.  Gradient angles are assumed to be in radians.\n#\n# Input:\n#   img - image to be non-maxima suppressed.\n# \n#   gradientangles - image containing gradient angles around each pixel in radians\n#                    (-pi,pi)\n# \n#   radius  - Distance in pixel units to be looked at on each side of each\n#             pixel when determining whether it is a local maxima or not.\n#             This value cannot be less than 1.\n#             (Suggested value about 1.2 - 1.5)\n#\n# Returns:\n#   im        - Non maximally suppressed image.\n#   location  - `Graphics.Point` image holding subpixel locations of edge\n#               points. \n#\n# Notes:\n#\n# This function uses bilinear interpolation to estimate\n# intensity values at ideal, real-valued pixel locations on each side of\n# pixels to determine if they are local maxima.\n\n# Copyright (c) 1996-2013 Peter Kovesi\n# Centre for Exploration Targeting\n# The University of Western Australia\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# The Software is provided \"as is\", without warranty of any kind.\n\n# December  1996 - Original version\n# September 2004 - Subpixel localization added\n# August    2005 - Made Octave compatible\n# October   2013 - Final thinning applied to binary image for Octave\n#                  compatbility (Thanks to Chris Pudney)\n# June      2014 - Ported (and modified significantly) to Julia (Kevin Squire)\n\nimport Base.Graphics.Point\n\nif !applicable(zero, Point)\n    import Base.zero\n    zero(Point) = Point(0.0,0.0)\nend\n\n# Used to encode the sign, integral, and fractional components of\n# an offset from a coordinate\nimmutable CoordOffset\n    s::Int      # sign\n    i::Int      # integer part\n    f::Float64  # fractional part\nend\n\nCoordOffset(x::Float64) = ((frac,i) = modf(x); CoordOffset(sign(frac), int(i), abs(frac)))\n(-)(off::CoordOffset) = CoordOffset(-off.s,-off.i, off.f)\n(*)(x::Number, off::CoordOffset) = x*(off.i + off.s*off.f)\n(*)(off::CoordOffset, x::Number) = x*(off.i + off.s*off.f)\n(+)(x::Number, off::CoordOffset) = x + off.i + off.s*off.f\n(+)(off::CoordOffset, x::Number) = x + off.i + off.s*off.f\n\n# Precalculate x and y offsets relative to centre pixel for each orientation angle \nfunction _calc_discrete_offsets(θ, radius, transposed)\n\n    θ_count = iround(2π/θ)\n    θ = 2π/θ_count\n    angles = (0:θ_count)*θ\n\n    # x and y offset of points at specified radius and angles\n    # from each reference position.\n\n    if transposed\n        # θ′ = -π/2 - θ\n        xoffs = [CoordOffset(-x) for x in  radius*sin(angles)]\n        yoffs = [CoordOffset( y) for y in  radius*cos(angles)]\n    else\n        xoffs = [CoordOffset( x) for x in  radius*cos(angles)]\n        yoffs = [CoordOffset(-y) for y in  radius*sin(angles)]\n    end\n\n    return θ, xoffs, yoffs\nend\n\n_discretize_angle(angle::FloatingPoint, invθ) = \n    angle < 0 ? iround((angle + 2π)*invθ)+1 : iround(angle*invθ)+1\n\n# Interpolate the value of an offset from a particular pixel\n#\n# Returns (interpolated value, min_value of adjacent pixels in direction of offset)\n#\n# The second value is made available to eliminate double edges; if the value at\n# (x,y) is less than the value or values adjacent to it in the direction of the\n# gradient (xoff,yoff), then it is not a local maximum\n\nfunction _interp_offset(img::AbstractArray, x::Integer, y::Integer, xoff::CoordOffset, yoff::CoordOffset, Ix, Iy, pad)\n    fx = Ix[x + xoff.i + pad]\n    fy = Iy[y + yoff.i + pad]\n    cx = Ix[x + xoff.i + xoff.s + pad]\n    cy = Iy[y + yoff.i + yoff.s + pad]\n\n    tl = img[fy,fx]    # Value at bottom left integer pixel location.\n    tr = img[fy,cx]    # bottom right\n    bl = img[cy,fx]    # top left\n    br = img[cy,cx]    # top right\n\n    upperavg = tl + xoff.f * (tr - tl)  # Now use bilinear interpolation to\n    loweravg = bl + xoff.f * (br - bl)  # estimate value at x,y\n\n    min_adjacent = (fx == x) & (fy == y) ? min(tr,bl) : tl\n\n    return (upperavg + yoff.f * (loweravg - upperavg), min_adjacent)\nend\n\n# Core edge thinning algorithm using nonmaximal suppression\nfunction thin_edges_nonmaxsup_core!{T}(out::AbstractArray{T,2}, location::AbstractArray{Point,2}, \n                                       img::AbstractArray{T,2}, gradientangles, radius, border, theta)\n    calc_subpixel = !isempty(location)\n\n    # Error checking\n    size(img) == size(gradientangles) == size(out) || error(\"image, gradient angle, and output image must all be the same size\")\n    calc_subpixel && size(location) != size(img) && error(\"subpixel location has a different size than the input image\")\n    radius < 1.0 && error(\"radius must be >= 1\")\n\n    # Precalculate x and y offsets relative to centre pixel for each orientation angle \n    transposed = spatialorder(img)[1] == \"x\"\n    θ, xoffs, yoffs = _calc_discrete_offsets(theta, radius, transposed)\n    iθ = 1/θ\n\n    # Indexes to use for border handling\n    pad = iceil(radius)\n    Ix = Images.padindexes(img, 2, pad, pad, border)\n    Iy = Images.padindexes(img, 1, pad, pad, border)\n    \n    # Now run through the image interpolating grey values on each side\n    # of the centre pixel to be used for the non-maximal suppression.\n\n    (height,width) = size(img)\n\n    for x = 1:width, y = 1:height\n        (c = img[y,x]) == 0 && continue  # For thresholded images\n\n        or = _discretize_angle(gradientangles[y,x],iθ)   # Disretized orientation\n        v1, n1 = _interp_offset(img, x, y, xoffs[or], yoffs[or], Ix, Iy, pad)\n\n        if (c > v1) & (c >= n1) # We need to check the value on the other side...\n            v2, n2 = _interp_offset(img, x, y, -xoffs[or], -yoffs[or], Ix, Iy, pad)\n\n            if (c > v2) & (c >= n2)  # This is a local maximum.\n                                     # Record value in the output image.\n                if calc_subpixel\n                    # Solve for coefficients of parabola that passes through\n                    # [-1, v2]  [0, img] and [1, v1].\n                    # v = a*r^2 + b*r + c\n\n                    # c = img[y,x]\n                    a = (v1 + v2)/2 - c\n                    b = a + c - v2\n\n                    # location where maxima of fitted parabola occurs\n                    r = -b/2a\n                    location[y,x] = transposed ? Point(y + r*yoffs[or], x + r*xoffs[or]) :\n                                                 Point(x + r*xoffs[or], y + r*yoffs[or])\n\n                    if T<:FloatingPoint\n                        # Store the interpolated value\n                        out[y,x] = a*r^2 + b*r + c\n                    else\n                        out[y,x] = c\n                    end\n                else\n                    out[y,x] = c\n                end\n            end\n        end\n    end\n\n    out\nend\n\n\n# Main function call when subpixel location of edges is not needed\nfunction thin_edges_nonmaxsup!{A<:AbstractArray,B<:AbstractArray}(out::A, img::A, gradientangles::B, border::String=\"replicate\";\n                                                                  radius::Float64=1.35, theta=pi/180)\n    properties(out) != properties(img) && error(\"Input and output arrays must have the same properties\")\n    thin_edges_nonmaxsup_core!(data(out), Array(Point,(0,0)), img, gradientangles, radius, border, theta)\n    out\nend\n\nfunction thin_edges_nonmaxsup{T}(img::AbstractArray{T,2}, gradientangles::AbstractArray, border::String=\"replicate\";\n                                 radius::Float64=1.35, theta=pi/180)\n    (height,width) = size(img)\n    out = zeros(T, height, width)\n    thin_edges_nonmaxsup_core!(out, Array(Point,(0,0)), img, gradientangles, radius, border, theta)\n    copy(img, out)\nend\n\n# Main function call when subpixel location of edges is desired\nfunction thin_edges_nonmaxsup_subpix!{A<:AbstractArray, B<:AbstractArray, C<:AbstractArray}(out::A, location::B, img::A, gradientangles::C,\n                                     border::String=\"replicate\"; radius::Float64=1.35, theta=pi/180)\n    properties(out) != properties(img) && error(\"Input and output arrays must have the same properties\")\n    eltype(location) != Point && error(\"Preallocated subpixel location array/image must have element type Graphics.Point\")\n\n    thin_edges_nonmaxsup_core!(data(out), data(location), img, gradientangles, radius, border, theta)\n    img, location\nend\n\nfunction thin_edges_nonmaxsup_subpix{T}(img::AbstractArray{T}, gradientangles::AbstractArray,\n                                        border::String=\"replicate\"; radius::Float64=1.35, theta=pi/180)\n    (height,width) = size(img)\n    out = zeros(T, height, width)\n    location = zeros(Point, height, width)\n    thin_edges_nonmaxsup_core!(out, location, img, gradientangles, radius, border, theta)\n\n    copy(img, out), copy(img, location)\nend\n", "meta": {"hexsha": "ca4f40dd4d9a223fdcf46db224424827357f02aa", "size": 15400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/edge.jl", "max_stars_repo_name": "staticfloat/Images.jl", "max_stars_repo_head_hexsha": "90ee20e16c43960addce8d71b3e57973f6188799", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/edge.jl", "max_issues_repo_name": "staticfloat/Images.jl", "max_issues_repo_head_hexsha": "90ee20e16c43960addce8d71b3e57973f6188799", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/edge.jl", "max_forks_repo_name": "staticfloat/Images.jl", "max_forks_repo_head_hexsha": "90ee20e16c43960addce8d71b3e57973f6188799", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3141361257, "max_line_length": 139, "alphanum_fraction": 0.6500649351, "num_tokens": 4499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7563594079113233}}
{"text": "export pivotedqr\n\nfunction pivotedqr(ψ::AbstractMatrix{T}, u::AbstractVector{T}; invert::Bool=true, verbose::Bool = true, ϵrel::Float64 = 1e-1, maxterms::Int64=typemax(Int64)) where {T}\n\n    m, n = size(ψ)\n\n    # Compute a pivoted QR decomposition of ψ, use the pivot for the sensor placement\n\n    F = qr(ψ, Val(true))\n\n    residue = copy(u)\n    idxset = Int64[]\n    dict = collect(1:n)\n    ϵu = norm(u)\n    ϵhist = [ϵu]\n    ϵrel *= ϵu\n\n    @inbounds for k=1:n\n        # Update set of selected basis\n        push!(idxset, F.p[k])\n\n        # Update candidate dictionary\n        filter!(x-> x != F.p[k], dict)\n\n        # Compute residual\n        c = view(ψ,:,idxset)\\u\n        residue = u - view(ψ,:,idxset)*c\n\n        # Calculate stopping critera\n        ϵ = norm(residue)\n        if verbose == true\n            push!(ϵhist, copy(ϵ))\n        end\n        if ϵ < ϵrel || k == maxterms\n            break\n        end\n\n    end\n\n    # Solve the system with the set of indices\n    if verbose == true\n        if invert == true\n            c = zeros(length(idxset))\n            c .= view(ψ,:, idxset)\\u\n            return idxset, c, ϵhist\n        else\n            return idxset, ϵhist\n        end\n    else\n        if invert == true\n            c = zeros(length(idxset))\n            c .= view(ψ,:, idxset)\\u\n            return idxset, c\n        else\n            return idxset\n        end\n    end\nend\n", "meta": {"hexsha": "4c8b81084a6228bbbdeab4d758153840bb31daac", "size": 1389, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pivotedqr.jl", "max_stars_repo_name": "mleprovost/QROMP.jl", "max_stars_repo_head_hexsha": "599ae5233570e8c894b71d57502a9c8c18fb75ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-30T17:48:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-30T22:10:29.000Z", "max_issues_repo_path": "src/pivotedqr.jl", "max_issues_repo_name": "mleprovost/QROMP.jl", "max_issues_repo_head_hexsha": "599ae5233570e8c894b71d57502a9c8c18fb75ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-30T05:39:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-30T05:51:43.000Z", "max_forks_repo_path": "src/pivotedqr.jl", "max_forks_repo_name": "mleprovost/QROMP", "max_forks_repo_head_hexsha": "599ae5233570e8c894b71d57502a9c8c18fb75ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5423728814, "max_line_length": 167, "alphanum_fraction": 0.5219582433, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7563594002035344}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, StatsPlots\n\tRandom.seed!(1)\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.11\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\ndist1 = TriangularDist(0,10,5)\n\n# ╔═╡ 75c334f0-2134-11eb-132d-dfcb59e14474\ndist2 = DiscreteUniform(1,5)\n\n# ╔═╡ 75c37638-2134-11eb-150e-a5788c7f72a7\ntheorMean1, theorMean2 = mean(dist1), mean(dist2)\n\n# ╔═╡ 75c3fa78-2134-11eb-0259-699e1c89a023\nbegin\n\tN = 10^6\n\tdata1 = rand(dist1,N)\n\tdata2 = rand(dist2,N)\n\testMean1, estMean2 = mean(data1), mean(data2)\nend\n\n# ╔═╡ de66cfee-2134-11eb-2c7a-add4bee67341\ndensity(data1, lab=\"Triangukar density\")\n\n# ╔═╡ a315bbee-2134-11eb-0249-17f3c6af3543\ndensity!(data2, lab=\"Discrete Uniform density\")\n\n# ╔═╡ 75cedfbc-2134-11eb-3b3c-5bdc69e4735a\nText(\"Symmetric Triangular Distiribution on [0,10] has mean $theorMean1\n\t(estimated: $estMean1)\")\n\n# ╔═╡ 75cf627a-2134-11eb-0dc9-e5e3d869f4a8\nText(\"Discrete Uniform Distiribution on {1,2,3,4,5} has mean $theorMean2\n\t(estimated: $estMean2)\")\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.11\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═75c334f0-2134-11eb-132d-dfcb59e14474\n# ╠═75c37638-2134-11eb-150e-a5788c7f72a7\n# ╠═75c3fa78-2134-11eb-0259-699e1c89a023\n# ╠═de66cfee-2134-11eb-2c7a-add4bee67341\n# ╠═a315bbee-2134-11eb-0249-17f3c6af3543\n# ╠═75cedfbc-2134-11eb-3b3c-5bdc69e4735a\n# ╠═75cf627a-2134-11eb-0dc9-e5e3d869f4a8\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "7bc1e7cdb81c4d559de941c27ab4f41f12bcb0a1", "size": 1824, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.11.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.11.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.11.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 27.223880597, "max_line_length": 72, "alphanum_fraction": 0.7461622807, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.8670357735451834, "lm_q1q2_score": 0.7563563750493502}}
{"text": "function collatz_steps(n::Integer)\n    n < 1 && throw(DomainError(\"n must be positive\"))\n    count = 0\n    while n > 1\n        count += 1\n        n = isodd(n) ? 3n + 1 : n ÷ 2\n    end\n    count\nend\n\n# Recursion: hard to reason about and slow in Julia as there's no TCO.\nfunction collatz_steps_slow(n::Integer)\n    # Avoid checking n < 1 in every loop\n    n < 1 && throw(DomainError(\"n must be positive\"))\n    _collatz_steps(n)\nend\n\nfunction _collatz_steps(n::Integer)\n    n == 1 && return 0\n    isodd(n) && return 2 + _collatz_steps((3n + 1) ÷ 2)\n    1 + _collatz_steps(n÷2)\nend\n\n", "meta": {"hexsha": "58ac82013705db7998592a42a93e6e93942ba13f", "size": 580, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "collatz-conjecture/collatz-conjecture.jl", "max_stars_repo_name": "bovine3dom/exercism-julia", "max_stars_repo_head_hexsha": "9794db44d862fefb21c178d7c28e6af615185685", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "collatz-conjecture/collatz-conjecture.jl", "max_issues_repo_name": "bovine3dom/exercism-julia", "max_issues_repo_head_hexsha": "9794db44d862fefb21c178d7c28e6af615185685", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "collatz-conjecture/collatz-conjecture.jl", "max_forks_repo_name": "bovine3dom/exercism-julia", "max_forks_repo_head_hexsha": "9794db44d862fefb21c178d7c28e6af615185685", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1666666667, "max_line_length": 70, "alphanum_fraction": 0.6172413793, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.7563563498128623}}
{"text": "# This file is part of IntegerSequences.\n# Copyright Peter Luschny. License is MIT.\n\n(@__DIR__) ∉ LOAD_PATH && push!(LOAD_PATH, (@__DIR__))\n\nmodule Polynomials\n\nusing Nemo\n# import AbstractAlgebra.lead\n\nexport ModulePolynomials\nexport Poly, AltPoly, EgfPoly, AltEgfPoly\nexport Coeffs, CoeffSum, CoeffAltSum, CoeffConst, CoeffLeading, AltCoeffs\nexport Diagonal, Central, EgfCoeffs, AltEgfCoeffs, ReflectPoly\n\n\"\"\"\n\nMostly convenient functions to deal with polynomials as often used in connection with ordinary and exponential generating functions. The naming scheme used is roughly described by:\n\n```\n   Poly       <-> Coeffs\n   AltPoly    <-> Poly(AltCoeffs)\n   EgfPoly    <-> Poly(EgfCoeffs)\n   OgfPoly    <-> Poly(OgfCoeffs)\n   AltEgfPoly <-> Poly(AltEgfCoeffs)\n```\n\nHere 'Alt' stands for alternating, 'Egf' for exponential generating function, 'Ogf' for ordinary generating function.\n\n* Coeffs, CoeffSum, CoeffAltSum, CoeffConst, CoeffLeading, AltCoeffs, Diagonal, Central, EgfCoeffs, AltEgfCoeffs, Poly, AltPoly, EgfPoly, AltEgfPoly, ReflectPoly.\n\"\"\"\nconst ModulePolynomials = \"\"\n\n\"\"\"\n\nReturn the coefficients of the polynomial ``p``.\n\"\"\"\nCoeffs(p::fmpz_poly) = [coeff(p, k) for k ∈ 0:degree(p)]\n\n\"\"\"\n\nReturn the coefficients of the polynomial ``p`` with alternating signs.\n\"\"\"\nAltCoeffs(p::fmpz_poly) = [(-1)^k * coeff(p, k) for k ∈ 0:degree(p)]\n\n\"\"\"\n\nReturn the coefficients of the polynomial ``p`` multiplied by ``k!``.\n\"\"\"\nOgfCoeffs(p::fmpz_poly) = [factorial(k)*coeff(p, k) for k ∈ 0:degree(p)]\n\n\"\"\"\n\nReturn the coefficients of the polynomial ``p`` divided by ``k!``. Note that integer division is used.\n\"\"\"\nEgfCoeffs(p::fmpz_poly) = [div(coeff(p, k), factorial(k)) for k ∈ 0:degree(p)]\n\n\"\"\"\n\nReturn the coefficients of the polynomial ``p`` divided by ``(-1)^k k!``.\n\"\"\"\nAltEgfCoeffs(p::fmpz_poly) = [(-1)^k * div(coeff(p, k), factorial(k)) for k ∈ 0:degree(p)]\n\n\"\"\"\n\nReturn the polynomial ``p`` with the coefficients C.\n\"\"\"\nfunction Poly(C)\n    T, x = PolynomialRing(ZZ, \"x\")\n    sum(c * x^k for (k, c) ∈ enumerate(C))\nend\n\n\"\"\"\n\nReturn the polynomial ``p`` with the coefficients C and alternating signs (i.e. with ``(-1)^k c[k] x^k)``.\n\"\"\"\nfunction AltPoly(C)\n    T, x = PolynomialRing(ZZ, \"x\")\n    sum((-1)^k * c * x^k for (k, c) ∈ enumerate(C))\nend\n\n\"\"\"\n\nReturn the polynomial ``p`` with the coefficients C used in the form ``c[k] x^k/k!``. Note that integer division is used.\n\"\"\"\nfunction EgfPoly(C)\n    T, x = PolynomialRing(ZZ, \"x\")\n    sum(div(c, factorial(k)) * x^k for (k, c) ∈ enumerate(C))\nend\n\n\"\"\"\n\nReturn the polynomial ``p`` with the coefficients C used in the form ``c[k] k! x^k``.\n\"\"\"\nfunction OgfPoly(C)\n    T, x = PolynomialRing(ZZ, \"x\")\n    sum(c * factorial(k) * x^k for (k, c) ∈ enumerate(C))\nend\n\n\"\"\"\n\nReturn the polynomial ``p`` with alternating signs attached to the coefficients .\n\"\"\"\nAltPoly(p::fmpz_poly) = Poly(AltCoeffs(p))\n#    T, x = PolynomialRing(ZZ, \"x\")\n#    sum((-1)^k*coeff(p, k)*x^k for k ∈ 0:degree(p))\n\n\"\"\"\n\nReturn the polynomial ``p`` with coefficients in exponential form (i.e. with ``c[k] x^k/k!``).\n\"\"\"\nEgfPoly(p::fmpz_poly) = Poly(EgfCoeffs(p))\n#    T, x = PolynomialRing(ZZ, \"x\")\n#    sum(div(coeff(p, k), factorial(k))*x^k for k ∈ 0:degree(p))\n\n\"\"\"\n\nReturn the polynomial ``p`` with coefficients in exponential form and alternating signs (i.e. with ``(-1)^k c[k] x^k/k!``).\n\"\"\"\nAltEgfPoly(p::fmpz_poly) = Poly(AltEgfCoeffs(p))\n#    T, x = PolynomialRing(ZZ, \"x\")\n#    sum((-1)^k*div(coeff(p, k), factorial(k))*x^k for k ∈ 0:degree(p))\n\n\"\"\"\n\nReturn the list of the coefficients of the first ``len`` polynomials of the sequence of polynomials ``P`` as a triangle.\n\"\"\"\nCoeffs(P, len) = [[coeff(P(n), k) for k ∈ 0:degree(P(n))] for n ∈ 0:len-1]\n\n\"\"\"\n\nReturn the sum of the coefficients of the polynomial ``p``.\n\"\"\"\nCoeffSum(p) = evaluate(p, 1)\n\n\"\"\"\n\nReturn the sequence of the sum of coefficients of the sequence of polynomials ``P``.\n\"\"\"\nCoeffSum(P, len) = [CoeffSum(P(n)) for n ∈ 0:len-1]\n\n\"\"\"\n\nReturn the alternating sum of the coefficients of the polynomial ``p``.\n\"\"\"\nCoeffAltSum(p) = evaluate(p, -1)\n\n\"\"\"\n\nReturn the sequence of the alternating sums of the coefficients of the sequence of polynomials ``P``.\n\"\"\"\nCoeffAltSum(P, len) = [CoeffAltSum(P(n)) for n ∈ 0:len-1]\n\n\"\"\"\n\nReturn the leading coefficient of the polynomial ``p``.\n\"\"\"\nCoeffLeading(p) = coeff(p, degree(p)) # lead(p)\n\n\"\"\"\n\nReturn the sequence of the leading coefficient of the sequence of polynomials ``P``.\n\"\"\"\nDiagonal(P, len) = [CoeffLeading(P(n)) for n ∈ 0:len-1]\n\n\"\"\"\n\nReturn the constant coefficient of the polynomial ``p``.\n\"\"\"\nCoeffConst(p) = coeff(p, 0)\n\n\"\"\"\n\nReturn the sequence of the constant coefficients of the sequence of polynomials ``P``.\n\"\"\"\nCoeffConst(P, len) = [CoeffConst(P(n)) for n ∈ 0:len-1]\n\n\"\"\"\n\nReturn the central column of the coefficients of the sequence of polynomials ``P``.\n\"\"\"\nCentral(P, len) = [Coeffs(P(2n))[n+1] for n ∈ 0:len-1]\n\n\"\"\"\n\nReturn the reflected polynomial of ``p``.\n\"\"\"\nfunction ReflectPoly(p::fmpz_poly)\n    T, x = PolynomialRing(ZZ, \"x\")\n    p(0) != 1 && throw(ValueError(\"Constant coefficient must be 1.\"))\n    d = degree(p)\n    x^d + sum(coeff(p, k) * x^(d - k) for k ∈ 1:d)\nend\n\n\n#START-TEST-########################################################\n\nusing Test, SeqUtils\n\nfunction test()\n\n    @testset \"Polynomials\" begin\n        T, x = PolynomialRing(ZZ, \"x\")\n        p = 63063000 * x^4 + 2702700 * x^3 + 16510 * x^2 + x\n        @test Coeffs(p) == [0, 1, 16510, 2702700, 63063000]\n        @test CoeffSum(p) == 65782211\n        @test CoeffAltSum(p) == 60376809\n        @test CoeffConst(p) == T(0)\n        @test CoeffLeading(p) == 63063000\n\n        q = x^2 - x - 1\n        p = 1 - x - x^2\n        r = ReflectPoly(p)\n        @test r == q\n    end\n\nend\n\nfunction demo()\n\n    function P(m, n)\n        R, x = PolynomialRing(ZZ, \"x\")\n        function recP(m, n)\n            n == 0 && return R(1)\n            sum(binomial(m * n, m * k) * recP(m, n - k) * x for k ∈ 1:n)\n        end\n        recP(m, n)\n    end\n\n    # ... given a polynomial p:\n    for m ∈ 0:4, n ∈ 0:5\n        println(\"---> m: $m, n: $n\")\n        q = P(m, n)\n\n        typeof(q) |> println\n        q |> println\n        AltPoly(q) |> println\n        EgfPoly(q) |> println\n        AltEgfPoly(q) |> println\n\n        Coeffs(q) |> Println\n        EgfCoeffs(q) |> Println\n        AltEgfCoeffs(q) |> Println\n\n        CoeffSum(q) |> println\n        CoeffAltSum(q) |> println\n        CoeffConst(q) |> println\n        CoeffLeading(q) |> println\n    end\n\n    # ... given a sequence of polynomials P:\n    for m ∈ 0:4\n        println(\"---> m \", m)\n        println(\"\\nPolynomial:\")\n        Q(n) = P(m, n)\n        println(Q(4))\n        println(\"\\nTriangle of coefficients:\")\n        Coeffs(Q, 7) |> Println\n        println(\"\\nSum of coefficients:\")\n        CoeffSum(Q, 7) |> Println\n        println(\"\\nAlternating sum of coefficients:\")\n        CoeffAltSum(Q, 7) |> Println\n        println(\"\\nLeading coefficients:\")\n        Diagonal(Q, 7) |> Println\n        println(\"\\nCentral column of coefficient triangle:\")\n        Central(Q, 7) |> Println\n    end\nend\n\nfunction perf() end\n\nfunction main()\n    test()\n    demo()\n    perf()\nend\n\nmain()\n\nend # module\n", "meta": {"hexsha": "c5ee2f7d3a9327fe6651d611977be6fe5e8c0b02", "size": 7171, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Polynomials.jl", "max_stars_repo_name": "OpenLibMathSeq/Sequences", "max_stars_repo_head_hexsha": "e53c1f30b7bf81669805f21d408d407b727615b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-06-25T08:54:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T04:52:29.000Z", "max_issues_repo_path": "src/Polynomials.jl", "max_issues_repo_name": "OpenLibMathSeq/Sequences", "max_issues_repo_head_hexsha": "e53c1f30b7bf81669805f21d408d407b727615b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-04-30T19:07:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T15:51:34.000Z", "max_forks_repo_path": "src/Polynomials.jl", "max_forks_repo_name": "PeterLuschny/IntegerSequences.jl", "max_forks_repo_head_hexsha": "1b9440bc8b86e3ae74fd26ee48fba412befbbdb5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-04-30T17:00:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:32:39.000Z", "avg_line_length": 25.5195729537, "max_line_length": 180, "alphanum_fraction": 0.610375122, "num_tokens": 2172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7563537512469378}}
{"text": "export SSDFun, HuberFun, MVFun, MVFunTotal\n\n\"\"\"\n\tmis,dmis,d2mis = SSDFun(dc,dobs,Wd)\n\n\tInput:\n\n\t\tdc::Array   -  simulated data\n\t\tdobs::Array -  measured data\n\t\tWd::Array   -  diagonal weighting\n\n\tOutput:\n\n\t\tmis::Real   -  misfit, 0.5*|dc-dobs|_Wd^2\n\t\tdmis        -  gradient\n\t\td2mis       -  diagonal of Hessian\n\n\"\"\"\nfunction SSDFun(dc::Union{Array{Float64},Array{Float32}},dobs::Union{Array{Float64},Array{Float32}},Wd::Union{Array{Float64},Array{Float32}})\n\tres   = vec(dc)-vec(dobs) # predicted - observed data\n\tWd    = vec(Wd)\n\tmis   = .5*real(dot(Wd.*res,Wd.*res))  # data misfit\n\tdmis  = Wd.*(Wd.*res)\n\td2mis = Wd.*Wd\n\treturn mis, dmis, d2mis\nend # function SSDFun\n\n\"\"\"\n\tFor complex data misfit is computed as 0.5*|real(dc)-(dobs)|_Wd^2 +  0.5*|complex(dc)-complex(dobs)|_W^2\n\"\"\"\nfunction SSDFun(dc::Array{ComplexF64},dobs::Array{ComplexF64},Wd::Array{ComplexF64})\n\n\twdr   = vec(real(Wd)); wdi = vec(imag(Wd))\n\t# wdr.*dRe + im*wdi.*dIm\n\tres   = vec(dc)-vec(dobs)\n\tresw  = wdr.*real(res) + im*wdi.*imag(res)\n\n\tmis   = .5*real(dot(resw,resw))\n\tdmis  = sdiag(wdr.*wdr)*real(res) + 1im*sdiag(wdi.*wdi)*imag(res)\n\td2mis =  wdr.*wdr + im*wdi.*wdi\n\treturn mis,dmis,d2mis\nend\n\n\"\"\"\n\tmis,dmis,d2mis = HuberFun(dc,dobs,Wd,C)\n\n\tComputes misfit via\n\n\t\tmisfit(dc,dobs) = sqrt(abs(Wd*res).^2 + eps)\n\n\tInput:\n\t\tdc::Array   -  simulated data\n\t\tdobs::Array -  measured data\n\t\tWd::Array   -  diagional weighting\n\t\teps         -  conditioning parameter (default=1e-3)\n\n\tOutput:\n\t\tmis::Real   -  misfit\n\t\tdmis        -  gradient\n\t\td2mis       -  diagonal of Hessian\n\n\"\"\"\nfunction HuberFun(dc::Array{Float64},dobs::Array{Float64},Wd::Array{Float64},eps=1e-3)\n\t# compute Huber distance\n\tres   = vec(dc-dobs)\n\tG     = sqrt.( abs.(Wd.*res).^2 .+ eps)\n\tmis   = sum(G)\n\tdmis  = sdiag(Wd./G)*(Wd.*res)\n\td2mis = (Wd.*Wd)./G\n\treturn mis,dmis,d2mis\nend\n# Old Huber fun\n# function HuberFun(dc::Array{Float64},dobs::Array{Float64},Wd::Array{Float64},eps=1e-3)\n# \t# compute Huber distance\n# \tres   = dc-dobs\n# \tG     = sqrt.( abs.(Wd.*res).^2 .+ eps)\n# \tmis   = sum(G)\n# \tdmis  = sdiag(Wd./G)*(Wd.*res)\n# \td2mis = (Wd.^Wd)./G\n# \treturn mis,dmis,d2mis\n# end\n", "meta": {"hexsha": "c529439349df1000a0db0023df2893843e77fa14", "size": 2129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/InverseSolve/misfit.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/jInv.jl-3dacf901-f8cd-5544-86ed-7a705f85c244", "max_stars_repo_head_hexsha": "2e7305f231a29bd8e1e803b82cc2bc8e9b7a205a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2016-04-11T22:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T21:58:53.000Z", "max_issues_repo_path": "src/InverseSolve/misfit.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/jInv.jl-3dacf901-f8cd-5544-86ed-7a705f85c244", "max_issues_repo_head_hexsha": "2e7305f231a29bd8e1e803b82cc2bc8e9b7a205a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2016-03-23T18:24:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T15:52:47.000Z", "max_forks_repo_path": "src/InverseSolve/misfit.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/jInv.jl-3dacf901-f8cd-5544-86ed-7a705f85c244", "max_forks_repo_head_hexsha": "2e7305f231a29bd8e1e803b82cc2bc8e9b7a205a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-03-23T16:52:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T17:04:41.000Z", "avg_line_length": 25.9634146341, "max_line_length": 141, "alphanum_fraction": 0.6270549554, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7563537434892921}}
{"text": "\n\"Tableau for explicit Euler method\"\nfunction getTableauExplicitEuler()\n    a = zeros(Float64, 1, 1)\n    b = [1.0]\n    c = [0.0]\n    o = 1\n\n    TableauERK(:explicit_euler, o, a, b, c)\nend\n\n\"Tableau for explicit midpoint method\"\nfunction getTableauExplicitMidpoint()\n    a = [[0.0 0.0]\n         [0.5 0.0]]\n    b = [0.0, 1.0]\n    c = [0.0, 0.5]\n    o = 2\n\n    TableauERK(:explicit_midpoint, o, a, b, c)\nend\n\n\"Tableau for Runge's method\"\nfunction getTableauRunge()\n    a = [[0.0 0.0]\n         [1.0 0.0]]\n    b = [0.5, 0.5]\n    c = [0.0, 1.0]\n    o = 2\n\n    TableauERK(:runge, o, a, b, c)\nend\n\n\"Tableau for Heun's method\"\nfunction getTableauHeun()\n    a = [[0.0 0.0]\n         [1.0 0.0]]\n    b = [0.5, 0.5]\n    c = [0.0, 1.0]\n    o = 2\n\n    TableauERK(:heun, o, a, b, c)\nend\n\n\"Tableau for Kutta's method of order three\"\nfunction getTableauKutta()\n    a = [[ 0.0 0.0 0.0]\n         [ 0.5 0.0 0.0]\n         [-1.0 2.0 0.0]]\n    b = [1/6, 4/6, 1/6]\n    c = [0.0, 0.5, 1.0]\n    o = 3\n\n    TableauERK(:kutta, o, a, b, c)\nend\n\n\"Tableau for explicit Runge-Kutta method of order four (1/6 rule)\"\nfunction getTableauERK4()\n    a = [[0.0 0.0 0.0 0.0]\n         [0.5 0.0 0.0 0.0]\n         [0.0 0.5 0.0 0.0]\n         [0.0 0.0 1.0 0.0]]\n    b = [1/6, 1/3, 1/3, 1/6]\n    c = [0.0, 0.5, 0.5, 1.0]\n    o = 4\n\n    TableauERK(:erk4, o, a, b, c)\nend\n\n\"Tableau for explicit Runge-Kutta method of order four (3/8 rule)\"\nfunction getTableauERK438()\n    a = [[ 0.0  0.0  0.0  0.0]\n         [ 1/3  0.0  0.0  0.0]\n         [-1/3  1.0  0.0  0.0]\n         [ 1.0 -1.0  1.0  0.0]]\n    b = [1/8, 3/8, 3/8, 1/8]\n    c = [0.0, 1/3, 2/3, 1.0]\n    o = 4\n\n    TableauERK(:erk438, o, a, b, c)\nend\n\n\"Tableau for explicit Verner's method of order six\"\nfunction getTableauVerner()\n    a = [[ 0.0          0.0     0.0           0.0       0.0          0.0  0.0         0.0]\n         [ 1/6          0.0     0.0           0.0       0.0          0.0  0.0         0.0]\n         [ 4/75         16/75   0.0           0.0       0.0          0.0  0.0         0.0]\n         [ 5/6         -8/3     5/2           0.0       0.0          0.0  0.0         0.0]\n         [-165/64       55/6   -425/64        85/96     0.0          0.0  0.0         0.0]\n         [ 12/5        -8.0     4015/612     -11/36     88/255       0.0  0.0         0.0]\n         [-8263/15000   124/75 -643/680      -81/250    2484/10625   0.0  0.0         0.0]\n         [ 3501/1720   -300/43  297275/52632 -319/2322  24068/84065  0.0  3850/26703  0.0]]\n    b = [3/40, 0.0, 875/2244, 23/72, 264/1955, 0.0, 125/11592, 43/616]\n    c = [0.0, 1/6, 4/15, 2/3, 5/6, 1.0, 1/15, 1.0]\n    o = 6\n\n    TableauERK(:verner, o, a, b, c)\nend\n", "meta": {"hexsha": "2b76ffa4f7f2826f08ef657690b44d6cf697d73d", "size": 2636, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tableaus/tableaus_erk.jl", "max_stars_repo_name": "TomaszTyranowski/GeometricIntegrators.jl", "max_stars_repo_head_hexsha": "8f514c18548754186d14ae2ef49ae956561ca529", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-04T11:52:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T11:52:47.000Z", "max_issues_repo_path": "src/tableaus/tableaus_erk.jl", "max_issues_repo_name": "TomaszTyranowski/GeometricIntegrators.jl", "max_issues_repo_head_hexsha": "8f514c18548754186d14ae2ef49ae956561ca529", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tableaus/tableaus_erk.jl", "max_forks_repo_name": "TomaszTyranowski/GeometricIntegrators.jl", "max_forks_repo_head_hexsha": "8f514c18548754186d14ae2ef49ae956561ca529", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6262626263, "max_line_length": 91, "alphanum_fraction": 0.4484066768, "num_tokens": 1306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361533336451, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7563537414696754}}
{"text": "# using Distances\n\nconst start = time()\n\nconst DEBUG = length(ARGS) >=1 && ARGS[1] == \"1\"\n\nfunction distance(solution::Array{Int32})\n    cost = 0\n    for i in 1:length(solution)-1\n        cost += d[solution[i],solution[i+1]]\n    end\n    return cost\nend\n\ntic()\ntic()\n# file lines iterator object\n# input = eachline(STDIN)\n\n# state = start(input)\n# read data size N\nconst n = parse(Int32, readline(STDIN))\nconst k = max(0.01*n, 25.0)\n\n# 2xN node's coordinates matrix\ndata = Array{Tuple{Float64, Float64}}(n)\n\n# read file data to Data matrix\nfor i in 1:n\n    v = readline(STDIN)\n    (i_v, x_v, y_v) = split(v)\n    data[parse(Int32, i_v)] = (parse(Float64, x_v), parse(Float64, y_v))\nend\n# calculate nodes distances as NxN matrix\n\nmaxtime = parse(Float64, readline(STDIN))\n\n# d = Array{Float64}(n, n)\n# pairwise!(d, Euclidean(1e-12), data)\n\nd = [hypot(x2-x1, y2-y1) for (x2, y2) in data, (x1, y1) in data]\n\ncurrentsol = Array{Int32}(n+1)\ncurrentsol[1] = currentsol[n+1] = Int32(1)\n\nfor i in 1:n\n    d[i,i] = Inf\nend\n\nd1 = copy(d)\nj = 1\nfor i in 2:length(currentsol)-1\n    currentsol[i] = findfirst(d1[j,:].==min(d1[j,:]...))\n    j = currentsol[i]\n    d1[j,1] = Inf\n    for visited_node in 1:i\n        d1[j, currentsol[visited_node]] = Inf\n    end\nend\n\ncurrentcost = distance(currentsol)\n\noptimumsol = copy(currentsol)\noptimumcost = currentcost\n\n####### SETTINGS #######\n# how many times to iterate (minimum)\nconst minItrs     = 10000000\n\n# fraction of melting point for starting temperature\nconst meltPointF  = 0.7\n\n# fraction of melting point for ending temperature\nconst targetTempF = 0.01\n\n# fraction of stagnant minItrs allowed before reheating\nconst stagItrsF   = 0.1\n########################\n\nfunction iterate(t::Float64, xsol::Array{Int32}, xcost::Float64)\n\tysol = copy(xsol)\n    ycost = xcost\n\n\tt1 = rand(2:n-2)\n\tt2 = rand(t1+2:n)\n\n    ycost = ycost -\n    \t\td[ysol[t1-1], ysol[t1]] -\n    \t\td[ysol[t1], ysol[t1+1]] +\n    \t\td[ysol[t1-1], ysol[t2]] +\n    \t\td[ysol[t2], ysol[t1+1]] -\n    \t\td[ysol[t2-1], ysol[t2]] -\n    \t\td[ysol[t2], ysol[t2+1]] +\n    \t\td[ysol[t2-1], ysol[t1]] +\n    \t\td[ysol[t1], ysol[t2+1]]\n\n\tysol[t1], ysol[t2] = ysol[t2], ysol[t1]\n\n\tif ycost <= xcost\n\t\treturn ysol, ycost\n\telseif rand() < exp((xcost-ycost)/t)\n\t\treturn ysol, ycost\n\tend\n\treturn xsol, xcost\nend\n\nfunction iterateP(p::Float64, xsol::Array{Int32}, xcost::Float64)\n\tysol = copy(xsol)\n    ycost = xcost\n\n\tt1 = rand(2:n-2)\n    t2Max = round(min(t1+k, n))\n\tt2 = rand(Int64(t1+2):Int64(t2Max))\n\n    ycost = ycost -\n    \t\td[ysol[t1-1], ysol[t1]] -\n    \t\td[ysol[t1], ysol[t1+1]] +\n    \t\td[ysol[t1-1], ysol[t2]] +\n    \t\td[ysol[t2], ysol[t1+1]] -\n    \t\td[ysol[t2-1], ysol[t2]] -\n    \t\td[ysol[t2], ysol[t2+1]] +\n    \t\td[ysol[t2-1], ysol[t1]] +\n    \t\td[ysol[t1], ysol[t2+1]]\n\n\tysol[t1], ysol[t2] = ysol[t2], ysol[t1]\n\n\tif ycost <= xcost\n\t\treturn ysol, ycost\n\telseif rand() < p\n\t\treturn ysol, ycost\n\tend\n\treturn xsol, xcost\nend\n\nconst initialcost = currentcost\nif DEBUG\n    println(string(\"initial cost: \", initialcost))\n    println(string(\"min iterations: \", minItrs))\n    println(string(\"initial time: \", toq(), \" seconds\"))\nend\n\ntestsol = copy(currentsol)\ntestcost = currentcost\nminT = 10.0e10\nmaxT = 0\n\nfor i in 1:max(0.01*minItrs, 2.0)\n    testsol, testcost = iterateP(0.001, testsol, testcost)\n\n    minT = min(minT, testcost)\n    maxT = max(maxT, testcost)\nend\n\nconst meltPoint = (maxT - minT) * 10.0^(-1.0*log10(n))\n\nconst t0 = meltPoint * meltPointF\n\nif DEBUG\n    @printf(\"T0 = %.2f\\n\", t0)\nend\nt = t0\n\nconst tDecay = targetTempF ^ (1.0/minItrs)\n\nitr = 1\noptItr = 1\nstagItrs = 0\n\nfunction printresult()\n    if DEBUG\n        @printf(\"T = %.2f\\n\", t)\n    \t@printf(\"Optimum: %.5f\\n\", optimumcost)\n    \t@printf(\"%.2f%% improvement\\n\", 100.0-100*optimumcost/initialcost)\n    \t@printf(\"after %.2f%% of iterations\\n\", 100*optItr/itr)\n    \t@printf(\"done %.2f%% of minimum iterations\\n\", 100*itr/minItrs)\n    \ttoc()\n    else\n        println(STDOUT, optimumcost)\n        for city in optimumsol\n            print(STDERR, city)\n            print(STDERR, \" \")\n        end\n        println(STDERR)\n    end\nend\n\natexit(printresult)\n\nwhile t > t0*targetTempF\n\n    if time() - start > maxtime - 1.0\n        exit()\n    end\n\n\tcurrentsol, currentcost = iterate(t, currentsol, currentcost)\n\tif currentcost < optimumcost\n\t\toptimumsol = copy(currentsol)\n        optimumcost = currentcost\n\t\toptItr = itr\n\telse\n\t\tstagItrs += 1\n\tend\n\n\tif stagItrs == Int(stagItrsF*minItrs) && itr <= minItrs\n\t\tstagItrs = 0\n        if DEBUG\n            println(\"reheating\")\n        end\n\t\tt *= 1.0 + 0.7*(minItrs-itr)/minItrs\n\tend\n\n\tt *= tDecay\n\n\tif DEBUG && itr%(minItrs/5) == 0\n\t\t@printf(\"T = %.2f\\n\", t)\n\t\t@printf(\"cost: %.5f\\n\", currentcost)\n\t\t@printf(\"optimum: %.5f\\n\", optimumcost)\n\tend\n    itr += 1\nend\n", "meta": {"hexsha": "8e329e3e6b0e6badd8db62fe99fd517c311f7a89", "size": 4744, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "simulated_annealing.jl", "max_stars_repo_name": "AfroMetal/algorithms-tsp-simulatedannealing", "max_stars_repo_head_hexsha": "606d544133952698ca92d6a052cb57e13deabc08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulated_annealing.jl", "max_issues_repo_name": "AfroMetal/algorithms-tsp-simulatedannealing", "max_issues_repo_head_hexsha": "606d544133952698ca92d6a052cb57e13deabc08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulated_annealing.jl", "max_forks_repo_name": "AfroMetal/algorithms-tsp-simulatedannealing", "max_forks_repo_head_hexsha": "606d544133952698ca92d6a052cb57e13deabc08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4660633484, "max_line_length": 72, "alphanum_fraction": 0.6117200675, "num_tokens": 1719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525463, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7563537317840759}}
{"text": "@doc raw\"\"\"\n    Entropy <: AbstractImageBinarizationAlgorithm\n    Entropy()\n\n    binarize([T,] img, f::Entropy)\n    binarize!([out,] img, f::Entropy)\n\nAn algorithm for finding the binarization threshold value using\nthe entropy of the image histogram.\n\n# Output\n\nReturn the binarized image as an `Array{Gray{T}}` of size `size(img)`. If\n`T` is not specified, it is inferred from `out` and `img`.\n\n# Details\n\nThis algorithm uses the entropy of a one-dimensional histogram to produce a threshold\nvalue.\n\nLet ``f_1, f_2, \\ldots, f_I`` be the frequencies in the various bins of the\nhistogram and ``I`` the number of bins. With ``N = \\sum_{i=1}^{I}f_i``, let\n``p_i = \\frac{f_i}{N}`` (``i = 1, \\ldots, I``) denote the probability\ndistribution of gray levels. From this distribution one derives two additional\ndistributions. The first defined for discrete values ``1`` to ``s`` and the\nother, from ``s+1`` to ``I``. These distributions are\n\n```math\nA: \\frac{p_1}{P_s}, \\frac{p_2}{P_s}, \\ldots, \\frac{p_s}{P_s}\n\\quad \\text{and} \\quad\nB: \\frac{p_{s+1}}{1-P_s}, \\ldots, \\frac{p_n}{1-P_s}\n\\quad \\text{where} \\quad\nP_s = \\sum_{i=1}^{s}p_i.\n```\n\nThe entropies associated with each distribution are as follows:\n\n```math\nH(A) = \\ln(P_s) + \\frac{H_s}{P_s}\n```\n```math\nH(B) = \\ln(1-P_s) + \\frac{H_n-H_s}{1-P_s}\n```\n```math\n\\quad \\text{where} \\quad\nH_s = -\\sum_{i=1}^{s}p_i\\ln{p_i}\n\\quad \\text{and} \\quad\nH_n = -\\sum_{i=1}^{I}p_i\\ln{p_i}.\n```\n\nCombining these two entropy functions we have\n\n```math\n\\psi(s) = \\ln(P_s(1-P_s)) + \\frac{H_s}{P_s} + \\frac{H_n-H_s}{1-P_s}.\n```\nFinding the discrete value ``s`` which maximises the function ``\\psi(s)`` produces\nthe sought-after threshold value (i.e. the bin which determines the threshold).\n\nSee Section 4 of [1] for more details on the derivation of the entropy.\n\n# Arguments\n\nThe function argument is described in more detail below.\n\n##  `img::AbstractArray`\n\nThe image that needs to be binarized. The image is automatically converted\nto `Gray` in order to construct the requisite graylevel histogram.\n\n# Example\n\nBinarize the \"cameraman\" image in the `TestImages` package.\n\n```julia\nusing TestImages, ImageBinarization\n\nimg = testimage(\"cameraman\")\nimg_binary = binarize(img, Entropy())\n```\n\n# References\n1. J. N. Kapur, P. K. Sahoo, and A. K. C. Wong, “A new method for gray-level picture thresholding using the entropy of the histogram,” *Computer Vision, Graphics, and Image Processing*, vol. 29, no. 1, p. 140, Jan. 1985.[doi:10.1016/s0734-189x(85)90156-2](https://doi.org/10.1016/s0734-189x%2885%2990156-2)\n\"\"\"\nstruct Entropy <: AbstractImageBinarizationAlgorithm end\n\nfunction (f::Entropy)(out::GenericGrayImage, img::GenericGrayImage)\n    edges, counts = build_histogram(img,  256)\n    t = find_threshold(HistogramThresholding.Entropy(), counts[1:end], edges)\n    @simd for i in CartesianIndices(img)\n      out[i] = img[i] < t ? 0 : 1\n    end\n    out\nend\n\n(f::Entropy)(out::GenericGrayImage, img::AbstractArray{<:Color3}) =\n    f(out, of_eltype(Gray, img))\n", "meta": {"hexsha": "825602a45a5e2a236b3c4f42604bd5adb77810d1", "size": 2992, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algorithms/entropy.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ImageBinarization.jl-cbc4b850-ae4b-5111-9e64-df94c024a13d", "max_stars_repo_head_hexsha": "e6b3b13279196544e815c821e45e2bef37c18376", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algorithms/entropy.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ImageBinarization.jl-cbc4b850-ae4b-5111-9e64-df94c024a13d", "max_issues_repo_head_hexsha": "e6b3b13279196544e815c821e45e2bef37c18376", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithms/entropy.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ImageBinarization.jl-cbc4b850-ae4b-5111-9e64-df94c024a13d", "max_forks_repo_head_hexsha": "e6b3b13279196544e815c821e45e2bef37c18376", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-13T20:29:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-13T20:29:41.000Z", "avg_line_length": 30.8453608247, "max_line_length": 306, "alphanum_fraction": 0.692513369, "num_tokens": 973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7563421497016013}}
{"text": "\"\"\"\n```julia\nnanstd(A; dims=:, mean=nothing, corrected=true)\n```\nCompute the variance of all non-`NaN` elements in `A`, optionally over dimensions specified by `dims`.\nAs `Statistics.var`, but ignoring `NaN`s.\n\nA precomputed `mean` may optionally be provided, which results in a somewhat faster\ncalculation. If `corrected` is `true`, then _Bessel's correction_ is applied, such\nthat the sum is divided by `n-1` rather than `n`.\n\nAs an alternative to `dims`, `nanstd` also supports the `dim` keyword, which\nbehaves identically to `dims`, but also drops any singleton dimensions that have\nbeen reduced over (as is the convention in some other languages).\n\n## Examples\n```julia\njulia> using NaNStatistics\n\njulia> A = [1 2; 3 4]\n2×2 Matrix{Int64}:\n 1  2\n 3  4\n\njulia> nanstd(A, dims=1)\n1×2 Matrix{Float64}:\n 1.41421  1.41421\n\njulia> nanstd(A, dims=2)\n2×1 Matrix{Float64}:\n 0.7071067811865476\n 0.7071067811865476\n```\n\"\"\"\nnanstd(A; dims=:, dim=:, mean=nothing, corrected=true) = sqrt!(__nanvar(mean, corrected, A, dims, dim))\nexport nanstd\n\nsqrt!(x::Number) = sqrt(x)\nfunction sqrt!(A::AbstractArray)\n    @turbo for i ∈ eachindex(A)\n        A[i] = sqrt(A[i])\n    end\n    return A\nend\n", "meta": {"hexsha": "94a4634216c6979aaf4ae5e96ec6fbcc106a4444", "size": 1178, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ArrayStats/nanstd.jl", "max_stars_repo_name": "brenhinkeller/NaNStatistics.jl", "max_stars_repo_head_hexsha": "941efe2be271ab086fcd63ec6ba9714e4ad7ddd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-05-15T03:30:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T09:44:56.000Z", "max_issues_repo_path": "src/ArrayStats/nanstd.jl", "max_issues_repo_name": "brenhinkeller/NaNStatistics.jl", "max_issues_repo_head_hexsha": "941efe2be271ab086fcd63ec6ba9714e4ad7ddd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-05-16T05:48:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T21:16:34.000Z", "max_forks_repo_path": "src/ArrayStats/nanstd.jl", "max_forks_repo_name": "brenhinkeller/NaNStatistics.jl", "max_forks_repo_head_hexsha": "941efe2be271ab086fcd63ec6ba9714e4ad7ddd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1777777778, "max_line_length": 103, "alphanum_fraction": 0.7028862479, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7563421427076122}}
{"text": "#=Copyright (c) 2017 Gabriel Goh\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.=#\n\n\nλ = 1\nRf(β, α) = [   β        λ; \n            -α*β (1 - α*λ)]\n\nα = 0.05\nβ = 0.4\n\nϵ = 8\nS = inv([ 1  0 ;\n          α  1 ])\n\nfunction err(k)\n    R = Rf(β, α)\n    sum( ( ((R^(k-i))*([ϵ; -α*ϵ]) )[2] )^2 for i = 1:k )\nend\n\nfunction err2(k, α, β)\n    R = Rf(β, α)\n    x = [ϵ; -α*ϵ]\n    s = 0\n    z = []\n    for i = 1:k\n      s = s + x[2]^2\n      x = R*x\n      push!(z, s)\n    end\n    return z\nend\n\nerr2(100)[50] - err(50)\n\nfunction geosumgen(R) \n  Λ, U = eig(R)\n  (b,k) -> begin; \n    Λsum = (1./(1 - Λ)).*(1 - Λ.^k); \n    real(U*(Λsum.*(U\\b))); \n  end\nend\n\nfunction runmomentum(A,b,k, ϵ)\n  z = zeros(length(b))\n  w = 3*ones(length(b))\n  for i = 1:k\n    z = β*z + (A*w - b) + ϵ*randn(1)\n    w = w - α*z\n  end\n  return (z[1],w[1])\nend\n\nfunction runmomentum2(A,b,k, ϵ)\n  z = zeros(length(b))\n  w = 3*ones(length(b))\n  fx = []\n  for i = 1:k\n    z = β*z + (A*w - b) + ϵ*randn(1)\n    w = w - α*z\n    push!(fx, w[1]*w[1])\n  end\n  return fx\nend\n\nk = 150\nd = mean([runmomentum2(1,0, k, ϵ) for i = 1:100])\ne = err2(k)\nd2 = [runmomentum(1,0, i, 0.)[2]^2 for i = 1:k]\n\nplot(d,\".\")\nplot(d2+e)\n#plot(d2)\n\nplot(err2(200, 0.01, 0))\n", "meta": {"hexsha": "36e036605dc38a3231d1cdd36953ef2472ff0428", "size": 2172, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/noisy_gradients.jl", "max_stars_repo_name": "sbeleidy/post--momentum", "max_stars_repo_head_hexsha": "36d172e5e3364de0f208f7cdb4a977800a72213f", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 192, "max_stars_repo_stars_event_min_datetime": "2017-04-04T17:12:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T06:21:07.000Z", "max_issues_repo_path": "Julia/noisy_gradients.jl", "max_issues_repo_name": "sbeleidy/post--momentum", "max_issues_repo_head_hexsha": "36d172e5e3364de0f208f7cdb4a977800a72213f", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 62, "max_issues_repo_issues_event_min_datetime": "2017-04-04T09:18:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-18T18:41:44.000Z", "max_forks_repo_path": "Julia/noisy_gradients.jl", "max_forks_repo_name": "sbeleidy/post--momentum", "max_forks_repo_head_hexsha": "36d172e5e3364de0f208f7cdb4a977800a72213f", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 58, "max_forks_repo_forks_event_min_datetime": "2017-04-04T17:00:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T21:16:47.000Z", "avg_line_length": 23.6086956522, "max_line_length": 80, "alphanum_fraction": 0.6137200737, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7563421397681018}}
{"text": "module Stepwise\n\n    using DataFrames\n    using StatsBase\n    using ..DataMod, ..Utils\n\n    export stepwise\n\n    # The code for `step` and `stepwise` below is inspired by the code by Bogumił Kamiński, found at\n    # https://stackoverflow.com/questions/49794476/backward-elimination-forward-selection-in-multilinear-regression-in-julia\n\n    function multibic(data::Data, rhs::Vector{Symbol})::Tuple{Float64, Vector{RegressionModel}}\n        models = get_models(data, rhs)::Vector{RegressionModel}\n        return (mean(bic.(models))::Float64, models)\n    end\n    function multibic(models::Vector{RegressionModel})::Float64\n        return mean(bic.(models))\n    end\n\n    function step(data::Data, rhs::Vector{Symbol}, forward::Bool,\n                  prevbest::Float64, prevmodel::Vector{RegressionModel},\n                  verbose::Bool, debug::Bool)::Tuple{Vector{Symbol}, Bool, Float64, Vector{RegressionModel}}\n        options = forward ? setdiff(data.xs, rhs) : rhs\n        if isempty(options)\n            return (rhs, false, prevbest, prevmodel)\n        end\n        bestbic = prevbest\n        bestrhs = rhs\n        bestmodel = prevmodel\n        improved = false\n        for opt in options\n            thisrhs = forward ? [rhs; opt] : setdiff(rhs, opt)\n            thisbic, thismodel = multibic(data, thisrhs)\n            if debug\n                print(opt); print(\" - \"); println(thisbic)\n            end\n            if thisbic < bestbic\n                bestbic = thisbic\n                bestrhs = thisrhs\n                bestmodel = thismodel\n                improved = true\n            end\n        end\n        if verbose\n            if improved\n                println(\"$(forward ? \"forward\" : \"backward\") step - new rhs: $bestrhs\\nwith mean BIC $bestbic\")\n            else\n                println(\"$(forward ? \"forward\" : \"backward\") step could not improve BIC\")\n            end\n        end\n        return (bestrhs, improved, bestbic, bestmodel)\n    end\n\n    function stepwise(data::Data; verbose::Bool = true, debug::Bool = false)::Vector{RegressionModel}\n        rhs = Symbol[]\n        model = get_models(data, Symbol[])\n        bestbic = multibic(model)\n        verbose && println(\"BIC empty model: $bestbic\")\n        while true\n            verbose && println(\"step\")\n            rhs, improvedfwd, bestbic, model = step(data, rhs, true, bestbic, model, verbose, debug)\n            rhs, improvedbwd, bestbic, model = step(data, rhs, false, bestbic, model, verbose, debug)\n            if !improvedfwd && !improvedbwd\n                sort!(rhs)\n                verbose && println(\"final rhs: $rhs\")\n                return model\n            end\n        end\n    end\n\nend\n\nusing .Stepwise\nexport stepwise\n", "meta": {"hexsha": "54cb9c4eb8eaefe60a0a2016753dbf597ecb4887", "size": 2708, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "incl/fs-stepwise.jl", "max_stars_repo_name": "KasperNooteboom/thesis-rvfl-fs", "max_stars_repo_head_hexsha": "31f8ee8ff58da5a8c1f505ef045c35ebbfe91255", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "incl/fs-stepwise.jl", "max_issues_repo_name": "KasperNooteboom/thesis-rvfl-fs", "max_issues_repo_head_hexsha": "31f8ee8ff58da5a8c1f505ef045c35ebbfe91255", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "incl/fs-stepwise.jl", "max_forks_repo_name": "KasperNooteboom/thesis-rvfl-fs", "max_forks_repo_head_hexsha": "31f8ee8ff58da5a8c1f505ef045c35ebbfe91255", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1066666667, "max_line_length": 124, "alphanum_fraction": 0.5845642541, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624557, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7563421350692301}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction _posang{T<:AbstractFloat}(units::Integer, ra1::T, dec1::T, ra2::T, dec2::T)\n    # Convert all quantities to radians.\n    if units == 0\n        # All radians\n        ra1_rad  = ra1\n        ra2_rad  = ra2\n        dec1_rad = dec1\n        dec2_rad = dec2\n    elseif units == 1\n        # Right ascensions are in hours, declinations in degrees.\n        ra1_rad  = ra1*pi/12.0\n        ra2_rad  = ra2*pi/12.0\n        dec1_rad = deg2rad(dec1)\n        dec2_rad = deg2rad(dec2)\n    elseif units == 2\n        # Right ascensions and declinations are in degrees.\n        ra1_rad  = deg2rad(ra1)\n        ra2_rad  = deg2rad(ra2)\n        dec1_rad = deg2rad(dec1)\n        dec2_rad = deg2rad(dec2)\n    else\n        # In any other case throw an error.\n        error(\"units must be 0 (radians), 1 (hours, degrees) or 2 (degrees)\")\n    end\n    radif = ra2_rad - ra1_rad\n    angle = atan2(sin(radif), cos(dec1_rad)*tan(dec2_rad) -\n                  sin(dec1_rad)*cos(radif))\n    if units == 0\n        return angle\n    else\n        return rad2deg(angle)\n    end\nend\n\n\"\"\"\n    posang(units, ra1, dec1, ra2, dec2) -> angular_distance\n\n### Purpose ###\n\nCompute rigorous position angle of point 2 relative to point 1.\n\n### Explanation ###\n\nComputes the rigorous position angle of point 2 (with given right ascension and\ndeclination) using point 1 (with given right ascension and declination) as the\ncenter.\n\n### Arguments ###\n\n* `units`: integer, can be either 0, or 1, or 2.  Describes units of inputs and\n output:\n    * 0: everything (input right ascensions and declinations, and output\n      distance) is radians\n    * 1: right ascensions are in decimal hours, declinations in decimal degrees,\n      output distance in degrees\n    * 2: right ascensions and declinations are in degrees, output distance in\n      degrees\n* `ra1`:  right ascension or longitude of point 1\n* `dec1`: declination or latitude of point 1\n* `ra2`: right ascension or longitude of point 2\n* `dec2`: declination or latitude of point 2\n\nBoth `ra1` and `dec1`, and `ra2` and `dec2` can be given as 2-tuples `(ra1,\ndec1)` and `(ra2, dec2)`.\n\n### Output ###\n\nAngle of the great circle containing `[ra2, dec2]` from the meridian containing\n`[ra1, dec1]`, in the sense north through east rotating about `[ra1, dec1]`.\nSee `units` argument above for units.\n\n### Method ###\n\nThe \"four-parts formula\" from spherical trigonometry (p. 12 of Smart's Spherical\nAstronomy or p. 12 of Green' Spherical Astronomy).\n\n\n### Example ###\n\nMizar has coordinates (ra, dec) = (13h 23m 55.5s, +54° 55' 31'').  Its\ncompanion, Alcor, has coordinates (ra, dec) = (13h 25m 13.5s, +54° 59' 17'').\nFind the position angle of Alcor with respect to Mizar.\n\n``` julia\nposang(1, ten(13, 25, 13.5), ten(54, 59, 17), ten(13, 23, 55.5), ten(54, 55, 31))\n# => -108.46011246802047\n```\n\n### Notes ###\n\n* If `ra1`, `dec1` are scalars, and `ra2`, `dec2` are vectors, then the output\n is a vector giving the distance of each element of `ra2`, `dec2` to `ra1`,\n `dec1`.  Similarly, if `ra1`,`de1` are vectors, and `ra2`,` dec2` are scalars,\n then the output is a vector giving the distance of each element of `ra1`,\n `dec1` to `ra2`, `dec2`.  If both `ra1`, `dec1` and `ra2`, `dec2` are vectors\n then the output is a vector giving the distance of each element of `ra1`,\n `dec1` to the corresponding element of `ra2`, `dec2`.\n* The function `sphdist` provides an alternate method of computing a spherical\n distance.\n* Note that `posang` is not commutative: the position angle between A and B is\n  \\$\\\\theta\\$, then the position angle between B and A is \\$180 + \\\\theta\\$.\n\nCode of this function is based on IDL Astronomy User's Library.\n\"\"\"\nposang(units::Integer, ra1::Real, dec1::Real, ra2::Real, dec2::Real) =\n    _posang(units, promote(float(ra1), float(dec1), float(ra2), float(dec2))...)\n\nfunction posang{R1<:Real, D1<:Real}(units::Integer,\n                                   ra1::AbstractArray{R1},\n                                   dec1::AbstractArray{D1},\n                                   ra2::Real,\n                                   dec2::Real)\n    @assert length(ra1) == length(dec1)\n    dist = similar(ra1, typeof(float(one(R1))))\n    for i in eachindex(ra1)\n        dist[i] = posang(units, ra1[i], dec1[i], ra2, dec2)\n    end\n    return dist\nend\n\nfunction posang{R2<:Real, D2<:Real}(units::Integer,\n                                   ra1::Real,\n                                   dec1::Real,\n                                   ra2::AbstractArray{R2},\n                                   dec2::AbstractArray{D2})\n    @assert length(ra2) == length(dec2)\n    dist = similar(ra2, typeof(float(one(R2))))\n    for i in eachindex(ra2)\n        dist[i] = posang(units, ra1, dec1, ra2[i], dec2[i])\n    end\n    return dist\nend\n\nfunction posang{R1<:Real, D1<:Real, R2<:Real, D2<:Real}(units::Integer,\n                                                       ra1::AbstractArray{R1},\n                                                       dec1::AbstractArray{D1},\n                                                       ra2::AbstractArray{R2},\n                                                       dec2::AbstractArray{D2})\n    @assert length(ra1) == length(dec1) == length(ra2) == length(dec2)\n    dist = similar(ra1, typeof(float(one(R1))))\n    for i in eachindex(ra1)\n        dist[i] = posang(units, ra1[i], dec1[i], ra2[i], dec2[i])\n    end\n    return dist\nend\n\n### Tuples input\nposang(units::Integer, radec1::Tuple{Real, Real}, ra2::Real, dec2::Real) =\n    posang(units, radec1..., ra2, dec2)\n\nposang(units::Integer, ra1::Real, dec1::Real, radec2::Tuple{Real, Real}) =\n    posang(units, ra1, dec1, radec2...)\n\nposang(units::Integer, radec1::Tuple{Real, Real}, radec2::Tuple{Real, Real}) =\n    posang(units, radec1..., radec2...)\n", "meta": {"hexsha": "d07097463db7007cc3eb02a06cdcf3ad5dfc8a1f", "size": 5841, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/posang.jl", "max_stars_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_stars_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/posang.jl", "max_issues_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_issues_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/posang.jl", "max_forks_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_forks_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7358490566, "max_line_length": 84, "alphanum_fraction": 0.6005820921, "num_tokens": 1729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7563421339108077}}
{"text": "@doc raw\"\"\"\n    Yen <: AbstractImageBinarizationAlgorithm\n    Yen()\n\n    binarize([T,] img, f::Yen)\n    binarize!([out,] img, f::Yen)\n\nComputes the binarization threshold value using Yen's maximum correlation criterion for\nbilevel thresholding.\n\n# Output\n\nReturn the binarized image as an `Array{Gray{T}}` of size `size(img)`. If\n`T` is not specified, it is inferred from `out` and `img`.\n\n\n# Details\n\nThis algorithm uses the concept of *entropic correlation* of a gray level histogram to produce a threshold\nvalue.\n\nLet ``f_1, f_2, \\ldots, f_I`` be the frequencies in the various bins of the\nhistogram and ``I`` the number of bins. With ``N = \\sum_{i=1}^{I}f_i``, let\n``p_i = \\frac{f_i}{N}`` (``i = 1, \\ldots, I``) denote the probability\ndistribution of gray levels. From this distribution one derives two additional\ndistributions. The first defined for discrete values ``1`` to ``s`` and the\nother, from ``s+1`` to ``I``. These distributions are\n\n```math\nA: \\frac{p_1}{P_s}, \\frac{p_2}{P_s}, \\ldots, \\frac{p_s}{P_s}\n\\quad \\text{and} \\quad\nB: \\frac{p_{s+1}}{1-P_s}, \\ldots, \\frac{p_n}{1-P_s}\n\\quad \\text{where} \\quad\nP_s = \\sum_{i=1}^{s}p_i.\n```\nThe entropic correlations associated with each distribution are\n\n```math\nC(A) = -\\ln \\sum_{i=1}^{s} \\left( \\frac{p_i}{P_s} \\right)^2 \\quad \\text{and} \\quad C(B) = -\\ln \\sum_{i=s+1}^{I} \\left( \\frac{p_i}{1 - P_s} \\right)^2.\n```\n\nCombining these two entropic correlation functions we have\n\n```math\n\\psi(s) = -\\ln \\sum_{i=1}^{s} \\left( \\frac{p_i}{P_s} \\right)^2 -\\ln \\sum_{i=s+1}^{I} \\left( \\frac{p_i}{1 - P_s} \\right)^2.\n```\nFinding the discrete value ``s`` which maximises the function ``\\psi(s)`` produces\nthe sought-after threshold value (i.e. the bin which determines the threshold).\n\n# Arguments\n\nThe function argument is described in more detail below.\n\n##  `img::AbstractArray`\n\nThe image that needs to be binarized. The image is automatically converted\nto `Gray` in order to construct the requisite graylevel histogram.\n\n# Example\n\nBinarize the \"cameraman\" image in the `TestImages` package.\n\n```julia\nusing TestImages, ImageBinarization\n\nimg = testimage(\"cameraman\")\nimg_binary = binarize(img, Yen())\n```\n\n# Reference\n\n1. Yen JC, Chang FJ, Chang S (1995), “A New Criterion for Automatic Multilevel Thresholding”, IEEE Trans. on Image Processing 4 (3): 370-378, [doi:10.1109/83.366472](https://doi.org/10.1109/83.366472)\n\"\"\"\nstruct Yen <: AbstractImageBinarizationAlgorithm end\n\nfunction (f::Yen)(out::GenericGrayImage, img::GenericGrayImage)\n    edges, counts = build_histogram(img,  256)\n    t = find_threshold(HistogramThresholding.Yen(), counts[1:end], edges)\n    @simd for i in CartesianIndices(img)\n        out[i] = img[i] < t ? 0 : 1\n    end\n    out\nend\n\n(f::Yen)(out::GenericGrayImage, img::AbstractArray{<:Color3}) =\n    f(out, of_eltype(Gray, img))\n", "meta": {"hexsha": "077b1c859b6fabc865d05c2d71e0d3f02fb87c88", "size": 2812, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algorithms/yen.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ImageBinarization.jl-cbc4b850-ae4b-5111-9e64-df94c024a13d", "max_stars_repo_head_hexsha": "e6b3b13279196544e815c821e45e2bef37c18376", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algorithms/yen.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ImageBinarization.jl-cbc4b850-ae4b-5111-9e64-df94c024a13d", "max_issues_repo_head_hexsha": "e6b3b13279196544e815c821e45e2bef37c18376", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithms/yen.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ImageBinarization.jl-cbc4b850-ae4b-5111-9e64-df94c024a13d", "max_forks_repo_head_hexsha": "e6b3b13279196544e815c821e45e2bef37c18376", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-13T20:29:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-13T20:29:41.000Z", "avg_line_length": 32.3218390805, "max_line_length": 200, "alphanum_fraction": 0.6899004267, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7563391060189185}}
{"text": "#=\n\nAuthor: Benjamin Hemingway\n\nThis code adjusts the square matrix in the case it is not positive semi definite.\n\nThis code is based on the Matlab package nearestSPD version 1.1.0.0 by John D'Errico\n=#\nfunction spdMatrix(M::Array{T,2}) where T<:Real\n  # symmetrize A into B\n  B = (M + M')/2;\n  # Compute the symmetric polar factor of B. Call it H.\n  # Clearly H is itself SPD.\n  out = LinearAlgebra.svd(B)\n  H = out.Vt'*Diagonal(out.S)*out.Vt\n  # get Ahat in the above formula\n  Ahat = (B+H)/2\n  # ensure symmetry\n  Ahat = (Ahat + Ahat')/2;\n  # test that Ahat is in fact PD. if it is not so, then tweak it just a bit.\n  p = isposdef(Ahat)\n  k = 0;\n  while p==false\n    k+=1\n    # Ahat failed the chol test. It must have been just a hair off,\n    # due to floating point trash, so it is simplest now just to\n    # tweak by adding a tiny multiple of an identity matrix.\n    mineig = minimum(eigvals(Ahat))\n    Ahat += (-mineig*k.^2 + eps(mineig))*Matrix{Float64}(I,size(Ahat))\n    p = isposdef(Ahat)\n    if k>99\n      error(\"Could not create Positive Definite Matrix\")\n    end\n  end\n  return Ahat\nend\n", "meta": {"hexsha": "5a3a74ab55cc610f732e46b43fe7de1797649188", "size": 1100, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "spd.jl", "max_stars_repo_name": "benhemingway/TruncatedGaussQuadrature.jl", "max_stars_repo_head_hexsha": "9a92f47275bd8e59f2922972a36655aa025e42d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spd.jl", "max_issues_repo_name": "benhemingway/TruncatedGaussQuadrature.jl", "max_issues_repo_head_hexsha": "9a92f47275bd8e59f2922972a36655aa025e42d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spd.jl", "max_forks_repo_name": "benhemingway/TruncatedGaussQuadrature.jl", "max_forks_repo_head_hexsha": "9a92f47275bd8e59f2922972a36655aa025e42d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7297297297, "max_line_length": 84, "alphanum_fraction": 0.6663636364, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7563391059618447}}
{"text": "function sphere_vertex(x, y, z, scale)\n    length = sqrt(x^2 + y^2 + z^2)\n    return [(i * scale) / length for i in (x, y, z)]\nend\nfunction sphere_vertex(a::Vector{T}, scale) where T\n    @assert length(a) == 3\n    x, y, z = a[1], a[2], a[3]\n    return sphere_vertex(x, y, z, scale)\nend\n\nfunction middle_point!(point_1, point_2, middle_point_cache, verts, scale)\n    # We check if we have already cut this edge first\n    # to avoid duplicated verts\n    smaller_index = min(point_1, point_2)\n    greater_index = max(point_1, point_2)\n    key = \"$smaller_index, $greater_index\"\n    if haskey(middle_point_cache, key)\n        return middle_point_cache[key]\n    end\n    vert_1 = verts[point_1]\n    vert_2 = verts[point_2]\n    middle = [sum(i) / 2 for i in zip(vert_1, vert_2)]\n    append!(verts, [sphere_vertex(middle, scale)])\n    index = length(verts)\n    middle_point_cache[key] = index\n    return index\nend # function\n\n\"\"\"\nCreate icosphere\n\"\"\"\nfunction icosphere(subdiv = 3, scale = 1.0)\n    PHI = (1. + sqrt(5.)) / 2.\n    verts = [(sphere_vertex(-1., PHI, 0., scale)),\n        (sphere_vertex(1., PHI, 0., scale)),\n        (sphere_vertex(-1., -PHI, 0., scale)),\n        (sphere_vertex(1., -PHI, 0., scale)),\n        (sphere_vertex(0., -1., PHI, scale)),\n        (sphere_vertex(0., 1., PHI, scale)),\n        (sphere_vertex(0., -1., -PHI, scale)),\n        (sphere_vertex(0., 1., -PHI, scale)),\n        (sphere_vertex(PHI, 0., -1., scale)),\n        (sphere_vertex(PHI, 0., 1., scale)),\n        (sphere_vertex(-PHI, 0., -1., scale)),\n        (sphere_vertex(-PHI, 0., 1., scale))]\n    faces = [[1, 12, 6], # 5 faces around point 0\n            [1, 6, 2],\n            [1, 2, 8],\n            [1, 8, 11],\n            [1, 11, 12],\n            [2, 6, 10], # Adjacent faces\n            [6, 12, 5],\n            [12, 11, 3],\n            [11, 8, 7],\n            [8, 2, 9],\n            [4, 10, 5],  # 5 faces around 3\n            [4, 5, 3],\n            [4, 3, 7],\n            [4, 7, 9],\n            [4, 9, 10],\n            [5, 10, 6],# Adjacent faces\n            [3, 5, 12],\n            [7, 3, 11],\n            [9, 7, 8],\n            [10, 9, 2]]\n\n    middle_point_cache = Dict{String,Int}()\n    for i in 1:subdiv\n        faces_subdiv = Array{Int64,1}[]\n        for tri in faces\n            v1 = middle_point!(tri[1], tri[2], middle_point_cache, verts, scale)\n            v2 = middle_point!(tri[2], tri[3], middle_point_cache, verts, scale)\n            v3 = middle_point!(tri[3], tri[1], middle_point_cache, verts, scale)\n            append!(faces_subdiv, [[tri[1], v1, v3]])\n            append!(faces_subdiv, [[tri[2], v2, v1]])\n            append!(faces_subdiv, [[tri[3], v3, v2]])\n            append!(faces_subdiv, [[v1, v2, v3]])\n            faces = faces_subdiv\n        end\n    end\n    v = Vector{Point3f0}(verts)\n    f = Vector{TriangleFace{Int}}(faces)\n    sphere = normal_mesh(Mesh(v, f))\n    return sphere\nend\n", "meta": {"hexsha": "4faf29a08bbb83e3d407bc679a8e60052f5bd1f6", "size": 2901, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sphere.jl", "max_stars_repo_name": "yusri-dh/ShapeDistributions.jl", "max_stars_repo_head_hexsha": "d64089115ec3d27938b7c44fd2bde5de05c21af8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sphere.jl", "max_issues_repo_name": "yusri-dh/ShapeDistributions.jl", "max_issues_repo_head_hexsha": "d64089115ec3d27938b7c44fd2bde5de05c21af8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-05-31T00:29:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-09T01:00:54.000Z", "max_forks_repo_path": "src/sphere.jl", "max_forks_repo_name": "yusri-dh/ShapeDistributions.jl", "max_forks_repo_head_hexsha": "d64089115ec3d27938b7c44fd2bde5de05c21af8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7325581395, "max_line_length": 80, "alphanum_fraction": 0.5236125474, "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806522, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7563391044514015}}
{"text": "\"\"\"\n    SomeVertexInCircumsphere(simplex1, r2, c2)\n\nDecides whether some vertices of simplex1 lies inside the circumsphere of simplex2\n(defined by the radius and centroid of simplex1, r2 and c2). Each column of simplex1 is a vertex.\n\nArguments\n---------\nc2::Vector{Float64} Column vector. Centroid of simplex2.\nr2::Float64 Radius of simplex 2\n\nReturns either 0 or 1; 1 if some of the vertices of simplex1 are contained in the circumsphere\nof simplex 2, 0 otherwise.\n\"\"\"\nfunction SomeVertexInCircumsphere(simplex1, r2, c2)\n    # The dimension\n    n = size(simplex1, 1)\n\n    i = 1\n    some_vertex_in_circumsphere = false\n\n    while i <= (n + 1) && !some_vertex_in_circumsphere\n        # Difference between the i-th vertex of simplex1 and centroid of simplex2\n        ith_vertex = simplex1[:, i] - c2\n        tmp = heaviside0(r2^2 - transpose(ith_vertex) * ith_vertex) # Radius times norm\n\n        if tmp == 1\n            some_vertex_in_circumsphere = true\n        end\n\n        i = i + 1\n    end\n\n    return some_vertex_in_circumsphere\nend\n", "meta": {"hexsha": "7fe52dc430b6dd3baa93f2515ab0af508356033d", "size": 1037, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/some-vertex-in-circumsphere.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Simplices.jl-d5428e67-3037-59ba-9ab1-57a04f0a3b6a", "max_stars_repo_head_hexsha": "c5651f0aa8e45bd196fc6816e3e47f01d2f1764b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-08T00:07:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T00:07:46.000Z", "max_issues_repo_path": "src/some-vertex-in-circumsphere.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Simplices.jl-d5428e67-3037-59ba-9ab1-57a04f0a3b6a", "max_issues_repo_head_hexsha": "c5651f0aa8e45bd196fc6816e3e47f01d2f1764b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2018-04-04T02:26:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-29T15:46:04.000Z", "max_forks_repo_path": "src/some-vertex-in-circumsphere.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Simplices.jl-d5428e67-3037-59ba-9ab1-57a04f0a3b6a", "max_forks_repo_head_hexsha": "c5651f0aa8e45bd196fc6816e3e47f01d2f1764b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-12-11T08:36:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:03:05.000Z", "avg_line_length": 28.8055555556, "max_line_length": 97, "alphanum_fraction": 0.6933461909, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7563390970411994}}
{"text": "## Class shape transformation method\n#==========================================================================================#\n\n# Basic shape function\nfunction shape_function(x, basis_func, coeffs, coeff_LE = 0)\n    n     = length(coeffs)\n    terms = basis_func.(x, n - 1, 0:n-1)\n    dot(coeffs, terms) + coeff_LE * (x^0.5) * (1 - x)^(n - 0.5)\nend\n\n# Computing coordinates\nCST_coordinates(class_func, basis_func, x, alphas, dz, coeff_LE, args...) = class_func(x) * shape_function(x, basis_func, alphas, coeff_LE) + x * dz\n\n## Bernstein basis\n#==========================================================================================#\n\nbernstein_class(x, N1, N2) = x^N1 * (1 - x)^N2\nbernstein_basis(x, n, k)   = binomial(n, k) * bernstein_class(x, k, n - k)\n\n\"\"\"\n    kulfan_CST(alpha_u, alpha_l,\n               (Δz_u, Δz_l) = (0., 0.),\n               (LE_u, LE_l) = (0., 0.),\n               n            = 40)\n\nDefine a cosine-spaced foil with ``2n`` points using the Class Shape Transformation method on a Bernstein polynomial basis for the upper and lower coordinates.\n\nThe foil is defined by arrays of coefficients ``(α_u,~ α_l)`` for the upper and lower surfaces (not necessarily of the same lengths), trailing-edge displacement values ``(Δz_u,~ Δz_l)``, and coefficients for leading edge modifications on the upper and lower surfaces at the nose.\n\"\"\"\nfunction kulfan_CST(alpha_u, alpha_l, (dz_u, dz_l) = (0., 0.), (LE_u, LE_l) = (0., 0.), n :: Integer = 40, N1 = 0.5, N2 = 1.)\n    # Cosine spacing for airfoil of unit chord length\n    xs = cosine_spacing(0.5, 1, n)\n\n    # λ-function for Bernstein polynomials\n    bernie(x, alphas, dz, LE) = CST_coordinates(y -> bernstein_class(y, N1, N2), bernstein_basis, x, alphas, dz, LE)\n\n    # Upper and lower surface generation\n    upper_surf = [ bernie(x, alpha_u, dz_u, LE_u) for x ∈ xs ]\n    lower_surf = [ bernie(x, alpha_l, dz_l, LE_l) for x ∈ xs ]\n\n    # Counter-clockwise ordering\n    @views Foil([ xs[end:-1:2] upper_surf[end:-1:2] ;\n                  xs           lower_surf           ], \"Kulfan CST\")\nend\n\n\"\"\"\n    camber_CST(α_c, α_t,\n               (Δz_u, Δz_l) :: NTuple{2, Real},\n               coeff_LE = 0.,\n               n :: Integer = 40)\n\nDefine a cosine-spaced foil with ``2n`` points using the Class Shape Transformation method on a Bernstein polynomial basis for the camber and thickness coordinates.\n\nThe foil is defined by arrays of coefficients ``(α_c,~ α_t)`` for the upper and lower surfaces, trailing-edge spacing values ``(Δz_u,~Δz_l)``, and a coefficient for the leading edge modifications at the nose.\n\"\"\"\nfunction camber_CST(α_cam, α_thicc, dz_thicc = 0., coeff_LE = 0, n :: Integer = 40, N1 = 0.5, N2 = 1.)\n    # Cosine spacing for airfoil of unit chord length\n    xs = cosine_spacing(0.5, 1, n)\n\n    # λ-function for Bernstein polynomials\n    bernie(x, αs, dz = 0.) = CST_coordinates(y -> bernstein_class(y, N1, N2), bernstein_basis, x, αs, dz, coeff_LE)\n\n    # Upper and lower surface generation\n    cam   = [ bernie(x, α_cam) for x ∈ xs ]\n    thicc = [ bernie(x, α_thicc, dz_thicc) for x ∈ xs ]\n\n    Foil(camber_thickness_to_coordinates(xs, cam, thicc), \"Camber-Thickness CST\")\nend\n\n\"\"\"\n    coordinates_to_CST(coords, num_dvs)\n\nConvert coordinates to a specified number of CST variables by performing a least-squares solution.\n\"\"\"\nfunction coordinates_to_CST(coords, num_dvs)\n    xs       = @views coords[:,1]\n    S_matrix = reduce(hcat, @. bernstein_class(xs, 0.5, 1.0) * bernstein_basis(xs, num_dvs - 1, i) for i in 0:num_dvs - 1)\n    alphas   = @views S_matrix \\ coords[:,2]\nend\n\n\"\"\"\n    camber_thickness_to_CST(coords, num_dvs)\n\nConvert camber-thickness coordinates to a specified number of CST variables by performing a least-squares solution.\n\"\"\"\nfunction camber_thickness_to_CST(coords, num_dvs)\n    xs, camber, thickness = (columns ∘ coordinates_to_camber_thickness)(coords)\n\n    alpha_cam   = coordinates_to_CST([ xs camber ], num_dvs)\n    alpha_thick = coordinates_to_CST([ xs thickness ], num_dvs)\n\n    alpha_cam, alpha_thick\nend", "meta": {"hexsha": "06a7189a4d432ad4bfc9fda0948e9b03207c1e96", "size": 4025, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Geometry/AircraftGeometry/Foils/class_shape_transformation.jl", "max_stars_repo_name": "HKUST-OCTAD-LAB/AeroMDAO.jl", "max_stars_repo_head_hexsha": "0ca9aa924f088cac59d04958eb5c6704b50feb18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Geometry/AircraftGeometry/Foils/class_shape_transformation.jl", "max_issues_repo_name": "HKUST-OCTAD-LAB/AeroMDAO.jl", "max_issues_repo_head_hexsha": "0ca9aa924f088cac59d04958eb5c6704b50feb18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Geometry/AircraftGeometry/Foils/class_shape_transformation.jl", "max_forks_repo_name": "HKUST-OCTAD-LAB/AeroMDAO.jl", "max_forks_repo_head_hexsha": "0ca9aa924f088cac59d04958eb5c6704b50feb18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2795698925, "max_line_length": 279, "alphanum_fraction": 0.6347826087, "num_tokens": 1149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.756339096499669}}
{"text": "#############################\n##  Numerical experiments associated with section 5.2.2\n#############################\n## This file contains the numerical experiments used to compare our method with\n## Chebfun's Volterra integral equation implementation when high polynomial orders are required.\n## We only include our own side of the implementation here. See the references in the paper for Chebfun.\n##\n\nusing ApproxFun, MultivariateOrthogonalPolynomials, BandedMatrices, BlockBandedMatrices, SpecialFunctions, Plots, SparseArrays\nusing SparseVolterraExamples\n\n#####\n## First, we can check that the stated arctan function indeed approximates a step-like function.\n## This is in Figure 6(a).\nv(x,K) = atan(K*x)\n    plot(x->v(x,10),0,1, legend=:true , xlabel = \"x\", label=\"k=10\" ,ylabel = \"u_2(x,K)\",  legendfontsize=12, tickfontsize=10, thickness_scaling = 1.2 , grid=:none)\n    plot!(x->v(x,50),0,1, legend=:true , xlabel = \"x\", label=\"k=50\" ,ylabel = \"u_2(x,K)\",  legendfontsize=12, tickfontsize=10, thickness_scaling = 1.2 , grid=:none)\n    plot!(x->v(x,100),0,1, legend=:true , xlabel = \"x\", label=\"k=100\" , ylabel = \"u_2(x,k)\", legendfontsize=12, tickfontsize=10, thickness_scaling = 1.2 , grid=:none)\n    plot!(x->v(x,200),0,1, legend=:bottomright , xlabel = \"x\", label=\"k=200\" , ylabel = \"u_2(x,k)\", legendfontsize=12, tickfontsize=10, thickness_scaling = 1.2 , grid=:none)\n\n#####\n## First we define the Kernel and g(x,k) as in section 5.2.2.\ngf(x,k) = k/(k^2*x^2+1)-(exp(x^2)*atan(k*x))/(2*k^2)+(exp(x^2)*x)/(2*k)-1/2*exp(x^2)*x^2*atan(k*x)\nKfun(x,y) = y*exp(x^2)\n\n#####\n## Solver function with step-by-step explanation for given k and with polynomial degree 'n'\nfunction solveSec532(k,n,gf,Kfun)\n    gF = Fun(x->gf(x,k),Jacobi(1,2, 0..1),n)             # Approximate g in the appropriate basis\n    V = triVolterraFullKernelOpP01(Kfun,n,true,155)      # The following steps generate the appropriate Volterra operator\n        V = reflectPabtoPba(n)*WLoweringP01P00(n)*V\n        V = Conversion(Jacobi(0,0,0..1),Jacobi(1,2,0..1))[1:n,1:n]*V[1:n,1:n]\n        V = Derivative(Jacobi(0,1,0..1),1)[1:n,1:n]-V\n    coeff = [DirectEvalLHSP10at0(n);V[1:n-1,1:n]] \\ [0;pad(gF.coefficients,n-1)] # Append evaluation and initial conditions and then solve the equation\n    return Fun(Jacobi(0,1, 0..1),coeff) # returns solution Fun\nend\n\n#####\n## Now we can compute and plot a specific example for k=100, plotting both the numerical approximation and the analytic solution.\n## Computing errors for various k is a bit more work since automatic convergence testing is not currently implemented but a straightforward for loop can do it from here.\nu = solveSec532(100,50,gf,Kfun)\nplot(u, label=\"sparse method\")\n    plot!(x->v(x,100),0,1, legend=:bottomright , xlabel = \"x\", label=\"analytic\" ,ylabel = \"u_2(x,100)\",  legendfontsize=12, tickfontsize=10, thickness_scaling = 1.2 , grid=:none)\n\n#####\n## We can also use BenchmarkTools to get a somewhat robust time estimation.\n## Note however that this obviously strongly depends on the hardware you are using.\nusing BenchmarkTools\n@benchmark solveSec532(100,50,gf,Kfun)\n@benchmark solveSec532(200,300,gf,Kfun)\n\n#####\n## Now we plot the operator bandedness for the k=100 example, this is basically Figure 6(b).\nfunction OperatorSec532(k,n,Kfun)\n    V = triVolterraFullKernelOpP01(Kfun,n,true,155)    # The following steps generate the appropriate Volterra operator\n        V = reflectPabtoPba(n)*WLoweringP01P00(n)*V\n        V = Conversion(Jacobi(0,0,0..1),Jacobi(1,2,0..1))[1:n,1:n]*V[1:n,1:n]\n        V = Derivative(Jacobi(0,1,0..1),1)[1:n,1:n]-V\n        V = [DirectEvalLHSP10at0(n);V[1:n-1,1:n]] # Append evaluation and initial conditions\n    return V # returns operator\nend\n#####\n## Plots.jl's spy plot is not currently compatible with these types, so we instead convert to generic sparse for visualization.\n## The exact bandedness properties depend on the chosen degrees and parameters but here is a standard example\nspy(sparse(OperatorSec532(100,300,Kfun)),markersize=2.8,marker=:rect)\n", "meta": {"hexsha": "c2a6f848d3197d017ed586aa1826e5c840a843c5", "size": 4022, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Section 5-2-2 - High order solutions with step-like function.jl", "max_stars_repo_name": "TSGut/SparseVolterraExamples.jl", "max_stars_repo_head_hexsha": "277733c70dfe78b65d1d9ad289de9dbeacda27b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-18T16:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T16:58:42.000Z", "max_issues_repo_path": "examples/Section 5-2-2 - High order solutions with step-like function.jl", "max_issues_repo_name": "TSGut/SparseVolterraExamples.jl", "max_issues_repo_head_hexsha": "277733c70dfe78b65d1d9ad289de9dbeacda27b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-09T15:39:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T15:59:37.000Z", "max_forks_repo_path": "examples/Section 5-2-2 - High order solutions with step-like function.jl", "max_forks_repo_name": "TSGut/SparseVolterraExamples.jl", "max_forks_repo_head_hexsha": "277733c70dfe78b65d1d9ad289de9dbeacda27b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.9393939394, "max_line_length": 178, "alphanum_fraction": 0.6931874689, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806521, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7563390917971179}}
{"text": "using Jacobi\nusing Polynomials\n\n# Script for writing the legerdre_RefLine file with Legendre polynomials up to\n# a maximum degree of max_degree.\nmax_degree = 50\n\nsetprecision(BigFloat, 512)\n\nfunction weights(points)\n    N = length(points)\n    return [ 2/((1-x^2)*(dlegendre(x, N)^2)) for x in points ]\nend\n\nopen(\"legendre_line.jl\", \"w\") do io\n    for i = 1:max_degree\n        # Legendre = Jacobi with α = β = 0\n        x = jacobi_zeros(i, 0, 0, BigFloat)\n        w = weights(x)/2\n        println(\"Error in sum of the weights for degree $i: $(1-sum(w))\")\n        x = (x .+ 1)/2\n        println(io, \"@generated function gauss_quadrature(form::Val{:legendre},\")\n        println(io, \"                                     shape::RefLine,\")\n        println(io, \"                                     degree::Val{$i},\")\n        println(io, \"                                     type::Type{T}) where {T}\")\n        println(io, \"\"\"    weights = SVector(:(\\$(T(big\"$(w[1])\"))),\"\"\")\n        for j in 2:i \n        println(io, \"\"\"                      :(\\$(T(big\"$(w[j])\"))),\"\"\")\n        end\n        println(io, \"                       )\")\n        println(io, \"\"\"    points = SVector(:(\\$(NTuple{1,T}(big\"$(x[1])\"))),\"\"\")\n        for j in 2:i \n        println(io, \"\"\"                     :(\\$(NTuple{1,T}(big\"$(x[j])\"))),\"\"\")\n        end\n        println(io, \"                      )\")\n        println(io, \"    return weights, points\")\n        println(io, \"end\")\n    end \nend\n", "meta": {"hexsha": "b06bf1a70cdd7d2f3709b9c865c278751bc8f169", "size": 1460, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/quadrature/write_legendre_line.jl", "max_stars_repo_name": "khurrumsaleem/MOCNeutronTransport", "max_stars_repo_head_hexsha": "16ccaf48d6c01e57e55e74ffbfbd71bbcd0f423c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/quadrature/write_legendre_line.jl", "max_issues_repo_name": "khurrumsaleem/MOCNeutronTransport", "max_issues_repo_head_hexsha": "16ccaf48d6c01e57e55e74ffbfbd71bbcd0f423c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/quadrature/write_legendre_line.jl", "max_forks_repo_name": "khurrumsaleem/MOCNeutronTransport", "max_forks_repo_head_hexsha": "16ccaf48d6c01e57e55e74ffbfbd71bbcd0f423c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5, "max_line_length": 84, "alphanum_fraction": 0.4623287671, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7563119487605131}}
{"text": "#=\nNacaThicknessFunction.jl\nJacob Child\nFebruary 3, 2022\nDescription:\nNACA 4-series Thickness Formula The NACA 4-series formula for airfoil thickness\nalong the chord is given by the following polynomial function, where m is the value of maximum\nthickness (as a percentage of the chord), and x is the x-position along the chord. (This formulation\nis for airfoils with sharp trailing edges.)\nt = 10m(.2969sqrt(x) - .1620x - .3537x^2 + .2843x^3 - .1015x^4)\n\nPseudo code- Have a function to ask for and generate x values in an array\nThen have a function to calculate various thicknesses\nFormat as table? and output to screen\n***use docstrings***\n=#\n\n\"\"\"\nxinput(x, step)\nTakes in the desired length, l, and step size and outputs an x array\n\n\"\"\"\nfunction x_input(L, step)\n    x = [0:step:L;] #makes array stopping at L with step size step\n    return x\nend\n\n\"\"\"\nthickness_calculations(x)\nTakes in the x coordinates, calculates thickness, and ouputs the array\n\n\"\"\"\nfunction thickness_calculations(x)\n    m = 0.10\n    t = 10*m.*(.2969*sqrt.(x) - .1260*x - .3537*x.^2 + .2843*x.^3 - .1015*x.^4)\n    return t\nend\n\n#using Pkg  #Just for the first run through\n#Pkg.add(\"DataFrames\")  #just for the first run through\n\nprintln(\"Hello! We are going to calculate the thickness along an airfoil \\n\")\nprintln(\"\\n Enter the Chord length\")\nL = readline()\nL = parse(Int64, L)\n\nprintln(\"\\n Enter the desired step size to calculate the thickness at\")\nstep = readline()\nstep = parse(Float64, step)\n\n#println(\"Type of Inputs\", typeof(L), typeof(step))\n\nx = x_input(L, step)\nt = thickness_calculations(x)\n\nprintln(t) #If Running in VS Code Uncomment this as I couldn't get DataFrame to work\n\n#using DataFrames #Only seems to work in Julia Terminal, not VS Code Terminal? ***research\n\n#DataFrame()\n\n#DataFrame(\"X\" => x, \"Thickness\" => t)\n\n\n", "meta": {"hexsha": "7877446fbc956ba372c2e594b123e15e1b4f2e0f", "size": 1812, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "NacaThicknessFunction.jl", "max_stars_repo_name": "JacobChild/FlowLab_Onboarding", "max_stars_repo_head_hexsha": "9f6389461f356a878bb87c64cd1cda8c4b8043e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NacaThicknessFunction.jl", "max_issues_repo_name": "JacobChild/FlowLab_Onboarding", "max_issues_repo_head_hexsha": "9f6389461f356a878bb87c64cd1cda8c4b8043e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NacaThicknessFunction.jl", "max_forks_repo_name": "JacobChild/FlowLab_Onboarding", "max_forks_repo_head_hexsha": "9f6389461f356a878bb87c64cd1cda8c4b8043e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8769230769, "max_line_length": 100, "alphanum_fraction": 0.7207505519, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7562811217488355}}
{"text": "function tournament_selection(P, a = rand(1:length(P)))\n    # chose two different solutions at random\n    b = rand(1:length(P))\n    while a == b \n        b = rand(1:length(P))\n    end\n\n    # perform selection\n    P[a].rank < P[b].rank || (P[a].rank == P[b].rank && P[a].crowding > P[b].crowding ) ? P[a] : P[b]\nend\n\n\nfunction gen_β(β, η, D, R)\n    α = 2.0 .- β .^ (-  η - 1.0 )\n    mask = R .<= 1.0 ./ α\n    s = 1.0 / (η + 1.0)\n    βq = [ mask[i] ?  (R[i] * α[i])^s : (1.0 / (2.0 - R[i]*α[i]))^s for i in 1:D]\n    βq\nend\n\nfunction SBX_crossover(vector1, vector2, bounds, η=15, p_variable = 0.9)\n    xu = view(bounds, 2,:)\n    xl = view(bounds, 1,:)\n    D = length(vector1)\n\n    do_crossover = ones(Bool, D)\n    do_crossover[rand(D) .> p_variable] .= false\n    do_crossover[ abs.( vector2 - vector1 ) .<= eps() ] .= false\n\n    y1 = min.( vector1, vector2 )\n    y2 = max.( vector1, vector2 )\n    Δ = max.(eps(), y2 - y1)\n\n\n    R = rand(D)\n\n    β = @. 1.0 + (2.0 * (y1 - xl) / Δ)\n    βq = gen_β(β, η, D, R) \n    c1 = @. 0.5*(y1 + y2 -  βq*Δ)\n\n    β = @. 1.0 + (2.0 * (y1 - xl) / Δ)\n    βq = gen_β(β, η, D, R) \n    c2 = @. 0.5*(y1 + y2 +  βq*Δ)\n\n    # swap\n    mask = rand(Bool, D)\n    cc = copy(c1)\n    c1[mask] = c2[mask]\n    c2[mask] = cc[mask]\n\n    cc1 = copy(vector1)\n    cc1[do_crossover] = c1[do_crossover]\n    cc2 = copy(vector2)\n    cc2[do_crossover] = c2[do_crossover]\n\n\n    reset_to_violated_bounds!(cc1, bounds)\n    reset_to_violated_bounds!(cc2, bounds)\n\n    return cc1, cc2\nend\n\nfunction polynomial_mutation!(vector, bounds, η=20, prob = 1 / length(vector))\n    do_mutation = rand(length(vector)) .< prob\n\n    xu = view(bounds, 2,do_mutation)\n    xl = view(bounds, 1,do_mutation)\n    x = view(vector, do_mutation)\n\n    δ1 = (x - xl) ./ (xu - xl)\n    δ2 = (xu - x) ./ (xu - xl)\n\n    D = length(xu)\n    R = rand(D)\n    mask = R .< 0.5\n    s = η+1.0\n    mut_pow = 1.0 / (η + 1.0)\n    δq = [ mask[i] ?\n            ^(2.0R[i] + (1. - 2.0R[i]) * ^(1.0 - δ1[i], s), mut_pow) - 1.0 :\n            1.0 - (2.0 * (1.0 - R[i]) + 2.0 * (R[i] - 0.5) * ^(1.0 - δ2[i], s))^mut_pow\n            for i in 1:D\n        ]\n\n    vector[do_mutation] = x + δq .* ( xu - xl)\n    # correct using reset to bound\n    #\n    vector\n\nend\n", "meta": {"hexsha": "287e88accbdec876b3188475f9e95bcb60a5660f", "size": 2213, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algorithms/NSGA2/operators.jl", "max_stars_repo_name": "pitmonticone/Metaheuristics.jl", "max_stars_repo_head_hexsha": "d429ff51cc921e7166d44e1c15d69f9041b8a0cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algorithms/NSGA2/operators.jl", "max_issues_repo_name": "pitmonticone/Metaheuristics.jl", "max_issues_repo_head_hexsha": "d429ff51cc921e7166d44e1c15d69f9041b8a0cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithms/NSGA2/operators.jl", "max_forks_repo_name": "pitmonticone/Metaheuristics.jl", "max_forks_repo_head_hexsha": "d429ff51cc921e7166d44e1c15d69f9041b8a0cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5888888889, "max_line_length": 101, "alphanum_fraction": 0.5020334388, "num_tokens": 911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7562811156998634}}
{"text": "function bisectionMethod(f, a, b, tol; maxiter = 1000) #f=@(x)x^2-3; a=1; b=2; (ensure change of sign between a and b) error=1e-4\n    if sign(f(a)) == sign(f(b))\n        throw(DomainError(\"Function has the same sign on both ends in bisectionMethod.\"))\n    end\n    c = (a + b) / 2\n\n    _fc = f(c)\n    _fa = f(a)\n    iter = 1\n    while abs(_fc) > tol\n        if _fc < 0 && _fa < 0 || _fc > 0 && _fa > 0\n            a = c\n            _fa = _fc\n        else\n            b = c\n        end\n        c = (a + b) / 2\n        _fc = f(c)\n        iter += 1\n        iter < maxiter || throw(\n            DomainError(\"Maximum number of iterations reached in bisectionMethod $iter.\"),\n        )\n    end\n    return c\nend\n\nfunction bisectionMethodError(f, a, b, tol; maxiter = 1000) #f=@(x)x^2-3; a=1; b=2; (ensure change of sign between a and b) error=1e-4\n    c = (a + b) / 2\n    ftry(x) =\n        try\n            f(x)\n        catch\n            1.0\n        end\n\n    bisectionMethod(ftry, a, b, tol; maxiter = maxiter)\nend\n\nconst vh2o_0 = m / rhoh2o\nfind_bh2o(the) = (bh2o) -> vh2o_0 - vh2o(the, bh2o)\nbh2o0(the) = bisectionMethodError(find_bh2o(the), zmax - hb, zmax, 1e-12) # (zmax=>bh2o=>zmax-hb)\n\nfunction get_bh2o(z, θ, p)\n    bh2o = p.bh2o_0 - z / cos(θ)\n    # if bh2o < zmax - hb || bh2o > zmax\n    #     @warn \"bh2o value in boatode! out of range\" bh2o\n    # end\n    return bh2o\nend\n", "meta": {"hexsha": "c6e3009d894cd9c09609bed3a4bfab1d5f52e643", "size": 1374, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/helper.jl", "max_stars_repo_name": "gorzech/BoatDynamics.jl", "max_stars_repo_head_hexsha": "b74af620effbdf5b5b38bd5d65914756ed62ada2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/helper.jl", "max_issues_repo_name": "gorzech/BoatDynamics.jl", "max_issues_repo_head_hexsha": "b74af620effbdf5b5b38bd5d65914756ed62ada2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/helper.jl", "max_forks_repo_name": "gorzech/BoatDynamics.jl", "max_forks_repo_head_hexsha": "b74af620effbdf5b5b38bd5d65914756ed62ada2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.48, "max_line_length": 134, "alphanum_fraction": 0.5291120815, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7562811137216429}}
{"text": "###############################################################################\n#\n# Collection of methods generating random projectors.\n#\n# Improvements:\n#  * random_matrix_4\n#  * include sparse projectors\n#  * rank-1 projectors\n#\n###############################################################################\n\n\"\"\"\nRandom projector of size k x m\nwith a normal distribution\n\"\"\"\nfunction random_matrix_1(k, m)\n  P = zeros(k, m) #init\n\n  #normal distribution\n  P = rand(k, m)\n\n  return 1 / sqrt(k) * P\nend\n\n\"\"\"\nRandom projector of size k x m\nwith -1 or 1 both with probability 1/2\n\"\"\"\nfunction random_matrix_2(k, m)\n  P = zeros(k, m) #init\n\n  #-1 or 1 both with probability 1/2\n  P = rand([-1, 1], (k, m))\n\n  return 1 / sqrt(k) * P\nend\n\n\"\"\"\nRandom projector of size k x m\nwith -1,0,1 respectively with probability 1/6,4/6,1/6\n\"\"\"\nfunction random_matrix_3(k, m)\n  P = zeros(k, m) #init\n\n  #-1,0,1 respectively with probability 1/6,4/6,1/6\n  P = rand([-1, 0, 0, 1], (k, m))\n\n  return 1 / sqrt(k) * P\nend\n\n\"\"\"\nRandom projector of size k x m\nwith orthogonal projection on a random k-dimensional linear subspace of R^m\n\"\"\"\nfunction random_matrix_4(k, m)\n  P = zeros(k, m) #init\n\n  #orthogonal projection on a random k-dimensional\n  #linear subspace of R^m\n  #P = rand(k, m)\n  throw(\"NotImplemented\")\n  return 1 / sqrt(k) * P\nend\n\n\"\"\"\nCheck the average sparsity of random projector over N random matrices of size k*m\n\"\"\"\nfunction random_projector_sparse(projector::Function, N::Int64, k::Int64, m::Int64)\n  tot = 0 #nb of non-zero elements\n\n  for i = 1:N\n    tot += SparseArrays.nnz(SparseArrays.sparse(projector(k, m))) / (k * m)\n  end\n\n  return tot / N\nend\n\n\"\"\"\nCheck the average rank of random projector over N random matrices of size k*m\n\"\"\"\nfunction random_projector_rank(projector::Function, N::Int64, k::Int64, m::Int64)\n  tot = 0 #average rank of the projector\n\n  for i = 1:N\n    tot += rank(projector(k, m))\n  end\n\n  return tot / N\nend\n", "meta": {"hexsha": "c6697e2a47b38a7671d00f7ad1e2a84487cfb8de", "size": 1937, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/random_projector.jl", "max_stars_repo_name": "tmigot/RandomLinearAlgebraSolvers.jl", "max_stars_repo_head_hexsha": "e4f53b533f8f4bed61d5dc40ce75ff74d95e0d28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-23T19:07:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T19:08:09.000Z", "max_issues_repo_path": "src/random_projector.jl", "max_issues_repo_name": "tmigot/RandomLinearAlgebraSolvers.jl", "max_issues_repo_head_hexsha": "e4f53b533f8f4bed61d5dc40ce75ff74d95e0d28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-11-26T17:38:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T01:21:44.000Z", "max_forks_repo_path": "src/random_projector.jl", "max_forks_repo_name": "tmigot/RandomLinearAlgebraSolvers.jl", "max_forks_repo_head_hexsha": "e4f53b533f8f4bed61d5dc40ce75ff74d95e0d28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5222222222, "max_line_length": 83, "alphanum_fraction": 0.6128033041, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819236, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7562811124292856}}
{"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    laplacematrix(mesh; weights=:uniform, normalize=true)\n\nThe Laplace-Beltrami (a.k.a. Laplacian) matrix of the `mesh`.\nOptionally specify the discretization `weights` as either\n`:uniform` or `:cotangent` and `normalize` the rows by the\ndiagonal value.\n\n## References\n\n* Vallet, B & Lévy, B. 2008. [Spectral Geometry Processing with Manifold\n  Harmonics](https://onlinelibrary.wiley.com/doi/10.1111/j.1467-8659.2008.01122.x)\n\n* Zhang et al. 2007. [Spectral Methods for Mesh Processing and Analysis]\n  (https://diglib.eg.org/handle/10.2312/egst.20071052.001-022)\n\"\"\"\nfunction laplacematrix(mesh; weights=:uniform, normalize=true)\n  # convert to half-edge topology\n  m = topoconvert(HalfEdgeTopology, mesh)\n\n  # retrieve adjacency relation\n  t = topology(m)\n  𝒩 = Adjacency{0}(t)\n\n  # initialize matrix\n  n = nvertices(t)\n  L = spzeros(n, n)\n\n  # fill matrix with weights\n  if weights == :uniform\n    for i in 1:n\n      js = 𝒩(i)\n      for j in js\n        L[i,j] = 1.0\n      end\n      L[i,i] = -1.0*length(js)\n      if normalize\n        for j in js\n          L[i,j] /= -L[i,i]\n        end\n        L[i,i] /= -L[i,i]\n      end\n    end\n  elseif weights == :cotangent\n    v = vertices(m)\n    for i in 1:n\n      js = CircularVector(𝒩(i))\n      for k in 1:length(js)\n        j₋, j, j₊ = js[k-1], js[k], js[k+1]\n        vᵢ, vⱼ =  v[i],  v[j]\n        v₋, v₊ = v[j₋], v[j₊]\n        αᵢⱼ = ∠(vⱼ, v₋, vᵢ)\n        βᵢⱼ = ∠(vᵢ, v₊, vⱼ)\n        L[i,j] = cot(αᵢⱼ) + cot(βᵢⱼ)\n      end\n      L[i,i] = -sum(L[i,js])\n      if normalize\n        for j in js\n          L[i,j] /= -L[i,i]\n        end\n        L[i,i] /= -L[i,i]\n      end\n    end\n  else\n    throw(ArgumentError(\"invalid discretization weights\"))\n  end\n\n  L\nend\n", "meta": {"hexsha": "940f2263fe68740182ad62382cf6792847b761c8", "size": 1910, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/laplacian.jl", "max_stars_repo_name": "moyner/Meshes.jl", "max_stars_repo_head_hexsha": "88c80954019f785fe016565ed895d1192acc5111", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 196, "max_stars_repo_stars_event_min_datetime": "2015-02-16T14:52:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T20:03:03.000Z", "max_issues_repo_path": "src/laplacian.jl", "max_issues_repo_name": "moyner/Meshes.jl", "max_issues_repo_head_hexsha": "88c80954019f785fe016565ed895d1192acc5111", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 268, "max_issues_repo_issues_event_min_datetime": "2015-02-14T01:02:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T18:26:19.000Z", "max_forks_repo_path": "src/laplacian.jl", "max_forks_repo_name": "moyner/Meshes.jl", "max_forks_repo_head_hexsha": "88c80954019f785fe016565ed895d1192acc5111", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-03-22T16:04:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T22:27:15.000Z", "avg_line_length": 25.8108108108, "max_line_length": 82, "alphanum_fraction": 0.5376963351, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7562811064946242}}
{"text": "logistic(x::Float64) = 4*x*(1-x)\n\nfunction bernoulli(x::Float64, l::Float64, u::Float64, nc::Float64)\n  if l<=x && x<nc\n    return ((u-l)*x+(nc-u)*l)/(nc-l)\n  elseif nc<=x && x<=u\n    return ((u-l)*x+(l-nc)*u)/(u-nc)\n  else\n    error(\"Input out of domain of Bernoulli map.\")\n  end\nend\n\nfunction nbernoulli(x::Float64, l::Float64, u::Float64, nc::Float64)\n  if l<=x && x<nc\n    return ((l-u)*x+(nc*u-l^2))/(nc-l)\n  elseif nc<=x && x<=u\n    return ((l-u)*x+(u^2-l*nc))/(u-nc)\n  else\n    error(\"Input out of domain of negative Bernoulli map.\")\n  end\nend\n\nfunction tent(x::Float64, l::Float64, u::Float64, nc::Float64)\n  if l<=x && x<nc\n    ((u-l)*x+(nc-u)*l)/(nc-l)\n  elseif nc<=x && x<=u\n    ((l-u)*x+(u^2-l*nc))/(u-nc)\n  else\n    error(\"Input out of domain of tent map.\")\n  end\nend\n\nfunction valley(x::Float64, l::Float64, u::Float64, nc::Float64)\n  if l<=x && x<nc\n    ((l-u)*x+(nc*u-l^2))/(nc-l)\n  elseif nc<=x && x<=u\n    ((u-l)*x+(l-nc)*u)/(u-nc)\n  else\n    error(\"Input out of domain of valley map.\")\n  end\nend\n\nfunction circular(x::Float64, nc::Float64)\n  if -1.<=x && x<-sqrt(nc)\n    y = -sqrt((1.-x^2)/(1.-nc))\n  elseif -sqrt(nc)<=x && x<sqrt(nc)\n    y = sqrt(1.-x^2/nc)\n  elseif sqrt(nc)<=x && x<=1.\n    y = -sqrt((1.-x^2)/(1.-nc))\n  else\n    error(\"Input out of domain of circular map.\")\n  end\nend\n\nimmutable VDist <: ContinuousUnivariateDistribution\n    nc::Float64\n\n    function VDist(nc::Real)\n      @assert -1.0<nc && nc<1.0 \"Non-centrality parameter must be in (-1, 1) in the case circular map.\"\n      new(float64(nc))\n    end\n\n    VDist() = VDist(0.0)\nend\n\n@continuous_distr_support VDist -1.0 1.0\n\nfunction pdf(d::VDist, x::Real)\n  if -1.0<=x && x<=0.0\n    -2.0*(1.0-d.nc)*x \n  elseif 0.0<x && x<=1.0\n    2*d.nc*x\n  else\n    0.0\n  end\nend\n\nfunction rand(d::VDist)\n  u = rand()\n\n  if 0.0<=u && u<1.0-d.nc\n    -sqrt((u+d.nc-1.0)/(d.nc-1.0))\n  elseif 1.0-d.nc<=u && u<=1.0\n    sqrt((u+d.nc-1.0)/d.nc)\n  end\nend\n\nmean(d::VDist) = (4.0*d.nc-2.0)/3.0\n\nvar(d::VDist) = 0.5-mean(d)^2\n", "meta": {"hexsha": "7cf5f90bd8732cddde83373076cd980b9bbc5053", "size": 1992, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/carriers/maps.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ChaosCommunications.jl-9a9c4646-d80d-55a4-af4c-84afa59d2e13", "max_stars_repo_head_hexsha": "d3f2ddce2f51afb9e8868f0f6e6575ec55ed1ba9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/carriers/maps.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ChaosCommunications.jl-9a9c4646-d80d-55a4-af4c-84afa59d2e13", "max_issues_repo_head_hexsha": "d3f2ddce2f51afb9e8868f0f6e6575ec55ed1ba9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/carriers/maps.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ChaosCommunications.jl-9a9c4646-d80d-55a4-af4c-84afa59d2e13", "max_forks_repo_head_hexsha": "d3f2ddce2f51afb9e8868f0f6e6575ec55ed1ba9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8901098901, "max_line_length": 103, "alphanum_fraction": 0.5607429719, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819236, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7562811045164036}}
{"text": "using LinearAlgebra\n\nexport fromroots,\n       truncate!,\n       chop!,\n       coeffs,\n       degree,\n       domain,\n       mapdomain,\n       order,\n       hasnan,\n       roots,\n       companion,\n       vander,\n       fit,\n       integrate,\n       derivative,\n       variable,\n       isintegral,\n       ismonic\n\n\"\"\"\n    fromroots(::AbstractVector{<:Number}; var=:x)\n    fromroots(::Type{<:AbstractPolynomial}, ::AbstractVector{<:Number}; var=:x)\n\nConstruct a polynomial of the given type given the roots. If no type is given, defaults to `Polynomial`.\n\n# Examples\n```jldoctest common\njulia> using Polynomials\n\njulia> r = [3, 2]; # (x - 3)(x - 2)\n\njulia> fromroots(r)\nPolynomial(6 - 5*x + x^2)\n```\n\"\"\"\nfunction fromroots(P::Type{<:AbstractPolynomial}, roots::AbstractVector; var::SymbolLike = :x)\n    x = variable(P, var)\n    p =  prod(x - r for r in roots)\n    return truncate!(p)\nend\nfromroots(r::AbstractVector{<:Number}; var::SymbolLike = :x) =\n    fromroots(Polynomial, r, var = var)\n\n\"\"\"\n    fromroots(::AbstractMatrix{<:Number}; var=:x)\n    fromroots(::Type{<:AbstractPolynomial}, ::AbstractMatrix{<:Number}; var=:x)\n\nConstruct a polynomial of the given type using the eigenvalues of the given matrix as the roots. If no type is given, defaults to `Polynomial`.\n\n# Examples\n```jldoctest common\njulia> using Polynomials\n\njulia> A = [1 2; 3 4]; # (x - 5.37228)(x + 0.37228)\n\njulia> fromroots(A)\nPolynomial(-1.9999999999999998 - 5.0*x + 1.0*x^2)\n```\n\"\"\"\nfromroots(P::Type{<:AbstractPolynomial},\n    A::AbstractMatrix{T};\n    var::SymbolLike = :x,) where {T <: Number} = fromroots(P, eigvals(A), var = var)\nfromroots(A::AbstractMatrix{T}; var::SymbolLike = :x) where {T <: Number} =\n    fromroots(Polynomial, eigvals(A), var = var)\n\n\"\"\"\n    fit(x, y, deg=length(x) - 1; [weights], var=:x)\n    fit(::Type{<:AbstractPolynomial}, x, y, deg=length(x)-1; [weights], var=:x)\n\nFit the given data as a polynomial type with the given degree. Uses linear least squares. When weights are given, as either a `Number`, `Vector` or `Matrix`, will use weighted linear least squares. The default polynomial type is [`Polynomial`](@ref). This will automatically scale your data to the [`domain`](@ref) of the polynomial type using [`mapdomain`](@ref)\n\"\"\"\nfunction fit(P::Type{<:AbstractPolynomial},\n             x::AbstractVector{T},\n             y::AbstractVector{T},\n             deg::Integer = length(x) - 1;\n    weights = nothing,\n    var = :x,) where {T}\n    x = mapdomain(P, x)\n    vand = vander(P, x, deg)\n    if weights !== nothing\n        coeffs = _wlstsq(vand, y, weights)\n    else\n        coeffs = pinv(vand) * y\n    end\n    return P(T.(coeffs), var)\nend\n\nfit(P::Type{<:AbstractPolynomial},\n    x,\n    y,\n    deg::Integer = length(x) - 1;\n    weights = nothing,\n    var = :x,) = fit′(P, promote(collect(x), collect(y))..., deg; weights = weights, var = var)\n\n#  avoid issue  214\nfit′(P::Type{<:AbstractPolynomial}, x, y, args...;kwargs...) = throw(MethodError(\"x and y do not produce abstract   vectors\"))\nfit′(P::Type{<:AbstractPolynomial},\n     x::AbstractVector{T},\n     y::AbstractVector{T},\n     args...; kwargs...) where {T} = fit(P,x,y,args...;  kwargs...)\n         \n         \nfit(x::AbstractVector,\n    y::AbstractVector,\n    deg::Integer = length(x) - 1;\n    weights = nothing,\n    var = :x,) = fit(Polynomial, x, y, deg; weights = weights, var = var)\n\n# Weighted linear least squares\n_wlstsq(vand, y, W::Number) = _wlstsq(vand, y, fill!(similar(y), W))\n_wlstsq(vand, y, W::AbstractVector) = _wlstsq(vand, y, diagm(0 => W))\n_wlstsq(vand, y, W::AbstractMatrix) = (vand' * W * vand) \\ (vand' * W * y)\n\n\"\"\"\n    roots(::AbstractPolynomial; kwargs...)\n\nReturns the roots of the given polynomial. This is calculated via the eigenvalues of the companion matrix. The `kwargs` are passed to the `LinearAlgeebra.eigvals` call.\n\n!!! note\n\n        The [PolynomialRoots.jl](https://github.com/giordano/PolynomialRoots.jl) package provides an alternative that is a bit faster and a bit more accurate; the [FastPolynomialRoots](https://github.com/andreasnoack/FastPolynomialRoots.jl) provides an interface to FORTRAN code implementing an algorithm that can handle very large polynomials (it is  `O(n^2)` not `O(n^3)`. the [AMRVW.jl](https://github.com/jverzani/AMRVW.jl) package implements the algorithm in Julia, allowing the use of other  number types.\n\n\"\"\"\nfunction roots(q::AbstractPolynomial{T}; kwargs...) where {T <: Number}\n\n    p = convert(Polynomial{T},  q)\n    roots(p; kwargs...)\n\nend\n\n\"\"\"\n    companion(::AbstractPolynomial)\n\nReturn the companion matrix for the given polynomial.\n\n# References\n[Companion Matrix](https://en.wikipedia.org/wiki/Companion_matrix)\n\"\"\"\ncompanion(::AbstractPolynomial)\n\n\"\"\"\n    vander(::Type{AbstractPolynomial}, x::AbstractVector, deg::Integer)\n\nCalculate the psuedo-Vandermonde matrix of the given polynomial type with the given degree.\n\n# References\n[Vandermonde Matrix](https://en.wikipedia.org/wiki/Vandermonde_matrix)\n\"\"\"\nvander(::Type{<:AbstractPolynomial}, x::AbstractVector, deg::Integer)\n\n\"\"\"\n    integrate(::AbstractPolynomial, C=0)\n\nReturns the indefinite integral of the polynomial with constant `C`.\n\"\"\"\nintegrate(p::AbstractPolynomial, C::Number = 0) = integrate(p, C)\n\n\"\"\"\n    integrate(::AbstractPolynomial, a, b)\n\nCompute the definite integral of the given polynomial from `a` to `b`. Will throw an error if either `a` or `b` are out of the polynomial's domain.\n\"\"\"\nfunction integrate(p::AbstractPolynomial, a::Number, b::Number)\n    P = integrate(p)\n    return P(b) - P(a)\nend\n\n\"\"\"\n    derivative(::AbstractPolynomial, order::Int = 1)\n\nReturns a polynomial that is the `order`th derivative of the given polynomial. `order` must be non-negative.\n\"\"\"\nderivative(::AbstractPolynomial, ::Int)\n\n\"\"\"\n    truncate!(::AbstractPolynomial{T};\n        rtol::Real = Base.rtoldefault(real(T)), atol::Real = 0)\n\nIn-place version of [`truncate`](@ref)\n\"\"\"\nfunction truncate!(p::AbstractPolynomial{T};\n    rtol::Real = Base.rtoldefault(real(T)),\n                   atol::Real = 0,) where {T}\n    max_coeff = maximum(abs, coeffs(p))\n    thresh = max_coeff * rtol + atol\n    map!(c->abs(c) <= thresh ? zero(T) : c, coeffs(p), coeffs(p))\n    return chop!(p, rtol = rtol, atol = atol)\nend\n\n\"\"\"\n    truncate(::AbstractPolynomial{T};\n        rtol::Real = Base.rtoldefault(real(T)), atol::Real = 0)\n\nRounds off coefficients close to zero, as determined by `rtol` and `atol`, and then chops any leading zeros. Returns a new polynomial.\n\"\"\"\nfunction Base.truncate(p::AbstractPolynomial{T};\n    rtol::Real = Base.rtoldefault(real(T)),\n    atol::Real = 0,) where {T}\n    truncate!(deepcopy(p), rtol = rtol, atol = atol)\nend\n\n\"\"\"\n    chop!(::AbstractPolynomial{T};\n        rtol::Real = Base.rtoldefault(real(T)), atol::Real = 0))\n\nIn-place version of [`chop`](@ref)\n\"\"\"\nfunction chop!(p::AbstractPolynomial{T};\n    rtol::Real = Base.rtoldefault(real(T)),\n               atol::Real = 0,) where {T}\n    isempty(coeffs(p)) && return p\n    tol = norm(coeffs(p)) * rtol + atol\n    for i = lastindex(p):-1:0\n        val = p[i]\n        if abs(val) > tol #!isapprox(val, zero(T); rtol = rtol, atol = atol)\n            resize!(p.coeffs, i + 1); \n            return p\n        end\n    end\n    resize!(p.coeffs, 1)\n    return p\nend\n\n\"\"\"\n    chop(::AbstractPolynomial{T};\n        rtol::Real = Base.rtoldefault(real(T)), atol::Real = 0))\n\nRemoves any leading coefficients that are approximately 0 (using `rtol` and `atol`). Returns a polynomial whose degree will guaranteed to be equal to or less than the given polynomial's.\n\"\"\"\nfunction Base.chop(p::AbstractPolynomial{T};\n    rtol::Real = Base.rtoldefault(real(T)),\n    atol::Real = 0,) where {T}\n    chop!(deepcopy(p), rtol = rtol, atol = atol)\nend\n\n\n\n\n\"\"\"\n    check_same_variable(p::AbstractPolynomial, q::AbstractPolynomial)\n\nCheck if either `p` or `q` is constant or if `p` and `q` share the same variable\n\"\"\"\ncheck_same_variable(p::AbstractPolynomial, q::AbstractPolynomial) =\n    (Polynomials.isconstant(p) || Polynomials.isconstant(q)) || p.var ==  q.var\n\n#=\nLinear Algebra =#\n\"\"\"\n    norm(::AbstractPolynomial, p=2)\n\nCalculates the p-norm of the polynomial's coefficients\n\"\"\"\nLinearAlgebra.norm(q::AbstractPolynomial, p::Real = 2) = norm(coeffs(q), p)\n\n\"\"\"\n    conj(::AbstractPolynomial)\n\nReturns the complex conjugate of the polynomial\n\"\"\"\nLinearAlgebra.conj(p::P) where {P <: AbstractPolynomial} = ⟒(P)(conj(coeffs(p)), p.var)\nLinearAlgebra.adjoint(p::P) where {P <: AbstractPolynomial} = ⟒(P)(adjoint.(coeffs(p)), p.var)\nLinearAlgebra.transpose(p::AbstractPolynomial) = p\nLinearAlgebra.transpose!(p::AbstractPolynomial) = p\n\n#=\nConversions =#\nBase.convert(::Type{P}, p::P) where {P <: AbstractPolynomial} = p\nBase.convert(P::Type{<:AbstractPolynomial}, x) = P(x)\nBase.promote_rule(::Type{<:AbstractPolynomial{T}},\n    ::Type{<:AbstractPolynomial{S}},\n) where {T,S} = Polynomial{promote_type(T, S)}\n\n#=\nInspection =#\n\"\"\"\n    length(::AbstractPolynomial)\n\nThe length of the polynomial.\n\"\"\"\nBase.length(p::AbstractPolynomial) = length(coeffs(p))\n\"\"\"\n    size(::AbstractPolynomial, [i])\n\nReturns the size of the polynomials coefficients, along axis `i` if provided.\n\"\"\"\nBase.size(p::AbstractPolynomial) = size(coeffs(p))\nBase.size(p::AbstractPolynomial, i::Integer) = size(coeffs(p), i)\nBase.eltype(p::AbstractPolynomial{T}) where {T} = T\n# in  analogy  with  polynomial as a Vector{T} with different operations defined.\nBase.eltype(::Type{<:AbstractPolynomial}) = Float64\nBase.eltype(::Type{<:AbstractPolynomial{T}}) where {T} = T\n#Base.eltype(::Type{P}) where {P <: AbstractPolynomial} = P # changed  in v1.1.0\nfunction Base.iszero(p::AbstractPolynomial)\n    if length(p) == 0\n        return true\n    end\n    return all(iszero.(coeffs(p))) && p[0] == 0\nend\n\n# See discussions in https://github.com/JuliaMath/Polynomials.jl/issues/258\n\"\"\"\n    all(pred, poly::AbstractPolynomial)\n\nTest whether all coefficients of an `AbstractPolynomial` satisfy predicate `pred`.\n\nYou can implement `isreal`, etc., to a `Polynomial` by using `all`.\n\"\"\"\nBase.all(pred, poly::AbstractPolynomial) = all(pred, poly[:])\n\"\"\"\n    any(pred, poly::AbstractPolynomial)\n\nTest whether any coefficient of an `AbstractPolynomial` satisfies predicate `pred`.\n\"\"\"\nBase.any(pred, poly::AbstractPolynomial) = any(pred, poly[:])\n\"\"\"\n    map(fn, p::AbstractPolynomial)\n\nTransform coefficients of `p` by applying a function (or other callables) `fn` to each of them.\n\nYou can implement `real`, etc., to a `Polynomial` by using `map`.\n\"\"\"\nBase.map(fn, p::P) where {P<:AbstractPolynomial} = ⟒(P)(map(fn, coeffs(p)), p.var)\n\n\"\"\"\n    isreal(p::AbstractPolynomial)\n\nDetermine whether a polynomial is a real polynomial, i.e., having only real numbers as coefficients.\n\nSee also: [`real`](@ref)\n\"\"\"\nBase.isreal(p::AbstractPolynomial) = all(isreal, p)\n\"\"\"\n    real(p::AbstractPolynomial)\n\nConstruct a real polynomial from the real parts of the coefficients of `p`.\n\nSee also: [`isreal`](@ref)\n\n!!! note\n    This could cause losing terms in `p`. This method is usually called on polynomials like `p = Polynomial([1, 2 + 0im, 3.0, 4.0 + 0.0im])` where you want to chop the imaginary parts of the coefficients of `p`.\n\"\"\"\nBase.real(p::AbstractPolynomial) = map(real, p)\n\n\"\"\"\n    isintegral(p::AbstractPolynomial)\n\nDetermine whether a polynomial is an integer polynomial, i.e., having only integers as coefficients.\n\"\"\"\nisintegral(p::AbstractPolynomial) = all(isinteger, p)\n\n\"\"\"\n    ismonic(p::AbstractPolynomial)\n\nDetermine whether a polynomial is a monic polynomial, i.e., its leading coefficient is one.\n\"\"\"\nismonic(p::AbstractPolynomial) = isone(p[end])\n\n\"\"\"\n    coeffs(::AbstractPolynomial)\n\nReturn the coefficient vector `[a_0, a_1, ..., a_n]` of a polynomial.\n\"\"\"\ncoeffs(p::AbstractPolynomial) = p.coeffs\n\n\"\"\"\n    degree(::AbstractPolynomial)\n\nReturn the degree of the polynomial, i.e. the highest exponent in the polynomial that\nhas a nonzero coefficient. The degree of the zero polynomial is defined to be -1.\n\"\"\"\ndegree(p::AbstractPolynomial) = iszero(p) ? -1 : length(p) - 1\n\n\n\"\"\"\n    isconstant(::AbstractPolynomial)\n\nIs the polynomial  `p` a constant.\n\"\"\"\nisconstant(p::AbstractPolynomial) = degree(p) <= 0\n\n\n\n\nhasnan(p::AbstractPolynomial) = any(isnan.(coeffs(p)))\n\n\"\"\"\n    domain(::Type{<:AbstractPolynomial})\n\nReturns the domain of the polynomial.\n\"\"\"\ndomain(::Type{<:AbstractPolynomial})\ndomain(::P) where {P <: AbstractPolynomial} = domain(P)\n\n\"\"\"\n    mapdomain(::Type{<:AbstractPolynomial}, x::AbstractArray)\n    mapdomain(::AbstractPolynomial, x::AbstractArray)\n\nGiven values of x that are assumed to be unbounded (-∞, ∞), return values rescaled to the domain of the given polynomial.\n\n# Examples\n```jldoctest  common\njulia> using Polynomials\n\njulia> x = -10:10\n-10:10\n\njulia> extrema(mapdomain(ChebyshevT, x))\n(-1.0, 1.0)\n\n```\n\"\"\"\nfunction mapdomain(P::Type{<:AbstractPolynomial}, x::AbstractArray)\n    d = domain(P)\n    x = collect(x)\n    x_zerod = x .- minimum(x)\n    x_scaled = x_zerod .* (last(d) - first(d)) ./ maximum(x_zerod)\n    x_scaled .+= first(d)\n    return x_scaled\nend\nmapdomain(::P, x::AbstractArray) where {P <: AbstractPolynomial} = mapdomain(P, x)\n#=\nindexing =#\nBase.firstindex(p::AbstractPolynomial) = 0\nBase.lastindex(p::AbstractPolynomial) = length(p) - 1\nBase.eachindex(p::AbstractPolynomial) = 0:length(p) - 1\nBase.broadcastable(p::AbstractPolynomial) = Ref(p)\n\n# iteration\n# iteration occurs over the basis polynomials\nBase.iterate(p::AbstractPolynomial) = (p[0] * one(typeof(p)), 1)\nfunction Base.iterate(p::AbstractPolynomial, state)\n    state <= length(p) - 1 ? (p[state] * basis(p, state), state + 1) : nothing\nend\n\n\nBase.collect(p::P) where {P <: AbstractPolynomial} = collect(P, p)\n\n# getindex\nfunction Base.getindex(p::AbstractPolynomial{T}, idx::Int) where {T <: Number}\n    idx < 0 && throw(BoundsError(p, idx))\n    idx ≥ length(p) && return zero(T)\n    return coeffs(p)[idx + 1]\nend\nBase.getindex(p::AbstractPolynomial, idx::Number) = getindex(p, convert(Int, idx))\nBase.getindex(p::AbstractPolynomial, indices) = [getindex(p, i) for i in indices]\nBase.getindex(p::AbstractPolynomial, ::Colon) = coeffs(p)\n\n# setindex\nfunction Base.setindex!(p::AbstractPolynomial, value::Number, idx::Int)\n    n = length(coeffs(p))\n    if n ≤ idx\n        resize!(p.coeffs, idx + 1)\n        p.coeffs[n + 1:idx] .= 0\n    end\n    p.coeffs[idx + 1] = value\n    return p\nend\n\nBase.setindex!(p::AbstractPolynomial, value::Number, idx::Number) =\n    setindex!(p, value, convert(Int, idx))\nBase.setindex!(p::AbstractPolynomial, value::Number, indices) =\n    [setindex!(p, value, i) for i in indices]\nBase.setindex!(p::AbstractPolynomial, values, indices) =\n    [setindex!(p, v, i) for (v, i) in zip(values, indices)]\nBase.setindex!(p::AbstractPolynomial, value::Number, ::Colon) =\n    setindex!(p, value, eachindex(p))\nBase.setindex!(p::AbstractPolynomial, values, ::Colon) =\n    [setindex!(p, v, i) for (v, i) in zip(values, eachindex(p))]\n\n#=\nidentity =#\nBase.copy(p::P) where {P <: AbstractPolynomial} = P(copy(coeffs(p)), p.var)\nBase.hash(p::AbstractPolynomial, h::UInt) = hash(p.var, hash(coeffs(p), h))\n\n#=\nzero, one, variable, basis =#\n\"\"\"\n    zero(::Type{<:AbstractPolynomial})\n    zero(::AbstractPolynomial)\n\nReturns a representation of 0 as the given polynomial.\n\"\"\"\nBase.zero(::Type{P}, var=:x) where {P <: AbstractPolynomial} = ⟒(P)(zeros(eltype(P), 1), var)\nBase.zero(p::P) where {P <: AbstractPolynomial} = zero(P, p.var)\n\"\"\"\n    one(::Type{<:AbstractPolynomial})\n    one(::AbstractPolynomial)\n\nReturns a representation of 1 as the given polynomial.\n\"\"\"\nBase.one(::Type{P}, var=:x) where {P <: AbstractPolynomial} = ⟒(P)(ones(eltype(P),1), var)  # assumes  p₀ = 1\nBase.one(p::P) where {P <: AbstractPolynomial} = one(P, p.var)\n\nBase.oneunit(::Type{P}, args...) where {P <: AbstractPolynomial} = one(P, args...)\nBase.oneunit(p::P, args...) where {P <: AbstractPolynomial} = one(p, args...)\n\n\n\"\"\"\n    variable(var=:x)\n    variable(::Type{<:AbstractPolynomial}, var=:x)\n    variable(p::AbstractPolynomial, var=p.var)\n\nReturn the monomial `x` in the indicated polynomial basis.  If no type is give, will default to [`Polynomial`](@ref). Equivalent  to  `P(var)`.\n\n# Examples\n```jldoctest  common\njulia> using Polynomials\n\njulia> x = variable()\nPolynomial(x)\n\njulia> p = 100 + 24x - 3x^2\nPolynomial(100 + 24*x - 3*x^2)\n\njulia> roots((x - 3) * (x + 2))\n2-element Array{Float64,1}:\n -2.0\n  3.0\n\n```\n\"\"\"\nvariable(::Type{P}, var::SymbolLike = :x) where {P <: AbstractPolynomial} = MethodError()\nvariable(p::AbstractPolynomial, var::SymbolLike = p.var) = variable(typeof(p), var)\nvariable(var::SymbolLike = :x) = variable(Polynomial{Int}, var)\n\n# basis\n# var is a positional argument, not a keyword; can't deprecate so we do `_var; var=_var`\n#@deprecate basis(p::P, k::Int; var=:x)  where {P<:AbstractPolynomial}  basis(p, k, var)\n#@deprecate basis(::Type{P}, k::Int; var=:x) where {P <: AbstractPolynomial} basis(P, k,var)\n# return the kth basis polynomial for the given polynomial type, e.g. x^k for Polynomial{T}\nfunction basis(::Type{P}, k::Int, _var::SymbolLike=:x; var=_var) where {P <: AbstractPolynomial}\n    zs = zeros(Int, k+1)\n    zs[end] = 1\n    ⟒(P){eltype(P)}(zs, var)\nend\nbasis(p::P, k::Int, _var::SymbolLike=:x; var=_var) where {P<:AbstractPolynomial} = basis(P, k, var)\n\n#=\narithmetic =#\nBase.:-(p::P) where {P <: AbstractPolynomial} = P(-coeffs(p), p.var)\nBase.:+(c::Number, p::AbstractPolynomial) = +(p, c)\nBase.:-(p::AbstractPolynomial, c::Number) = +(p, -c)\nBase.:-(c::Number, p::AbstractPolynomial) = +(-p, c)\nBase.:*(c::Number, p::AbstractPolynomial) = *(p, c)\n\nfunction Base.:*(p::P, c::S) where {P <: AbstractPolynomial,S}\n    T = promote_type(P, S)\n    return T(coeffs(p) .* c, p.var)\nend\n\nfunction Base.:/(p::P, c::S) where {T,P <: AbstractPolynomial{T},S}\n    R = promote_type(P, eltype(one(T) / one(S)))\n    return R(coeffs(p) ./ c, p.var)\nend\n\nBase.:-(p1::AbstractPolynomial, p2::AbstractPolynomial) = +(p1, -p2)\n\nfunction Base.:+(p::P, n::Number) where {P <: AbstractPolynomial}\n    p1, p2 = promote(p, n)\n    return p1 + p2\nend\n\nfunction Base.:+(p1::P, p2::O) where {P <: AbstractPolynomial,O <: AbstractPolynomial}\n    p1, p2 = promote(p1, p2)\n    return p1 + p2\nend\n\nfunction Base.:*(p1::P, p2::O) where {P <: AbstractPolynomial,O <: AbstractPolynomial}\n    p1, p2 = promote(p1, p2)\n    return p1 * p2\nend\n\nBase.:^(p::AbstractPolynomial, n::Integer) = Base.power_by_squaring(p, n)\n\nfunction Base.divrem(num::P, den::O) where {P <: AbstractPolynomial,O <: AbstractPolynomial}\n    n, d = promote(num, den)\n    return divrem(n, d)\nend\n\n\"\"\"\n    gcd(a::AbstractPolynomial, b::AbstractPolynomial; atol::Real=0, rtol::Real=Base.rtoldefault)\n\nFind the greatest common denominator of two polynomials recursively using\n[Euclid's algorithm](http://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor#Euclid.27s_algorithm).\n\n# Examples\n\n```jldoctest common\njulia> using Polynomials\n\njulia> gcd(fromroots([1, 1, 2]), fromroots([1, 2, 3]))\nPolynomial(4.0 - 6.0*x + 2.0*x^2)\n\n```\n\"\"\"\nfunction Base.gcd(p1::AbstractPolynomial{T}, p2::AbstractPolynomial{S}; kwargs...) where {T,S}\n    gcd(promote(p1, p2)...; kwargs...)\nend\n\nfunction Base.gcd(p1::P, p2::Q;\n                  atol::Real=zero(real(T)),\n                  rtol::Real=Base.rtoldefault(real(T))\n                  ) where {T, P <: AbstractPolynomial{T}, Q <: AbstractPolynomial{T}}\n\n\n    r₀, r₁ = p1, p2\n    iter = 1\n    itermax = length(r₁)\n\n    while !iszero(r₁) && iter ≤ itermax\n        _, rtemp = divrem(r₀, r₁)\n        r₀ = r₁\n        r₁ = truncate(rtemp; atol=atol, rtol=rtol)  \n        iter += 1\n    end\n    return r₀\nend\n\n\"\"\"\n    div(::AbstractPolynomial, ::AbstractPolynomial)\n\"\"\"\nBase.div(n::AbstractPolynomial, d::AbstractPolynomial) = divrem(n, d)[1]\n\n\"\"\"\n    rem(::AbstractPolynomial, ::AbstractPolynomial)\n\"\"\"\nBase.rem(n::AbstractPolynomial, d::AbstractPolynomial) = divrem(n, d)[2]\n\n#=\nComparisons =#\nBase.isequal(p1::P, p2::P) where {P <: AbstractPolynomial} = hash(p1) == hash(p2)\nBase.:(==)(p1::AbstractPolynomial, p2::AbstractPolynomial) =\n    check_same_variable(p1,p2) && (coeffs(p1) == coeffs(p2))\nBase.:(==)(p::AbstractPolynomial, n::Number) = degree(p) <= 0 && p[0] == n\nBase.:(==)(n::Number, p::AbstractPolynomial) = p == n\n\nfunction Base.isapprox(p1::AbstractPolynomial{T},\n    p2::AbstractPolynomial{S};\n    rtol::Real = (Base.rtoldefault(T, S, 0)),\n                       atol::Real = 0,) where {T,S}\n    \n    p1, p2 = promote(p1, p2)\n    check_same_variable(p1, p2)  || error(\"p1 and p2 must have same var\")\n\n    # copy over from abstractarray.jl\n    Δ  = norm(p1-p2)\n    if isfinite(Δ)\n        return Δ <= max(atol, rtol*max(norm(p1), norm(p2)))\n    else\n        for i in 0:max(degree(p1), degree(p2))\n            isapprox(p1[i], p2[i]; rtol=rtol, atol=atol) || return false\n        end\n        return true\n    end\nend\n\nfunction Base.isapprox(p1::P,\n                       n::S;\n                       rtol::Real = (Base.rtoldefault(T, S, 0)),\n                       atol::Real = 0,) where {T,S, P<:AbstractPolynomial{T}}\n    return isapprox(p1, ⟒(P){T}(n,p1.var))\nend\n\nBase.isapprox(n::S,\n    p1::AbstractPolynomial{T};\n    rtol::Real = (Base.rtoldefault(T, S, 0)),\n    atol::Real = 0,) where {T,S} = isapprox(p1, n, rtol = rtol, atol = atol)\n", "meta": {"hexsha": "4aafdfec7b6dbfc759fd8878c816cba67ebb02d5", "size": 21211, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/common.jl", "max_stars_repo_name": "jishnub/Polynomials.jl", "max_stars_repo_head_hexsha": "d17ec5144a00a4c0e86d6adcd54f1efa93dd5c21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common.jl", "max_issues_repo_name": "jishnub/Polynomials.jl", "max_issues_repo_head_hexsha": "d17ec5144a00a4c0e86d6adcd54f1efa93dd5c21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common.jl", "max_forks_repo_name": "jishnub/Polynomials.jl", "max_forks_repo_head_hexsha": "d17ec5144a00a4c0e86d6adcd54f1efa93dd5c21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6110283159, "max_line_length": 511, "alphanum_fraction": 0.6578190562, "num_tokens": 6314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.756272675415837}}
{"text": "# Lions, Mercier, “Splitting algorithms for the sum of two nonlinear\n# operators,” SIAM Journal on Numerical Analysis, vol. 16, pp. 964–979 (1979).\n\nusing Base.Iterators\nusing ProximalAlgorithms.IterationTools\nusing ProximalOperators: Zero\nusing LinearAlgebra\nusing Printf\n\n\"\"\"\n    ForwardBackwardIteration(; <keyword-arguments>)\n\nInstantiate the forward-backward splitting algorithm (see [1]) for solving\noptimization problems of the form\n\n    minimize f(x) + g(x),\n\nwhere `f` is smooth.\n\n# Arguments\n- `x0`: initial point.\n- `f=Zero()`: smooth objective term.\n- `g=Zero()`: proximable objective term.\n- `Lf=nothing`: Lipschitz constant of the gradient of `f`.\n- `gamma=nothing`: stepsize to use, defaults to `1/Lf` if not set (but `Lf` is).\n- `adaptive=false`: forces the method stepsize to be adaptively adjusted.\n- `minimum_gamma=1e-7`: lower bound to `gamma` in case `adaptive == true`.\n\n# References\n1. Lions, Mercier, “Splitting algorithms for the sum of two nonlinear operators,” SIAM Journal on Numerical Analysis, vol. 16, pp. 964–979 (1979).\n\"\"\"\nBase.@kwdef struct ForwardBackwardIteration{R,Tx,Tf,Tg,TLf,Tgamma}\n    f::Tf = Zero()\n    g::Tg = Zero()\n    x0::Tx\n    Lf::TLf = nothing\n    gamma::Tgamma = Lf === nothing ? nothing : (1 / Lf)\n    adaptive::Bool = gamma === nothing\n    minimum_gamma::R = real(eltype(x0))(1e-7)\nend\n\nBase.IteratorSize(::Type{<:ForwardBackwardIteration}) = Base.IsInfinite()\n\nBase.@kwdef mutable struct ForwardBackwardState{R,Tx}\n    x::Tx             # iterate\n    f_x::R            # value of f at x\n    grad_f_x::Tx      # gradient of f at x\n    gamma::R          # stepsize parameter of forward and backward steps\n    y::Tx             # forward point\n    z::Tx             # forward-backward point\n    g_z::R            # value of g at z\n    res::Tx           # fixed-point residual at iterate (= z - x)\n    Az::Tx=similar(x) # TODO not needed\n    grad_f_z::Tx=similar(x)\nend\n\nfunction Base.iterate(iter::ForwardBackwardIteration)\n    x = copy(iter.x0)\n    grad_f_x, f_x = gradient(iter.f, x)\n    gamma = iter.gamma === nothing ? 1 / lower_bound_smoothness_constant(iter.f, I, x, grad_f_x) : iter.gamma\n    y = x - gamma .* grad_f_x\n    z, g_z = prox(iter.g, y, gamma)\n    state = ForwardBackwardState(\n        x=x, f_x=f_x, grad_f_x=grad_f_x,\n        gamma=gamma, y=y, z=z, g_z=g_z, res=x - z,\n    )\n    return state, state\nend\n\nfunction Base.iterate(iter::ForwardBackwardIteration{R}, state::ForwardBackwardState{R,Tx}) where {R,Tx}\n    if iter.adaptive == true\n        state.gamma, state.g_z, state.f_x = backtrack_stepsize!(\n            state.gamma, iter.f, nothing, iter.g,\n            state.x, state.f_x, state.grad_f_x, state.y, state.z, state.g_z, state.res, state.z, state.grad_f_z,\n            minimum_gamma = iter.minimum_gamma,\n        )\n        state.x, state.z = state.z, state.x\n        state.grad_f_x, state.grad_f_z = state.grad_f_z, state.grad_f_x\n    else\n        state.x, state.z = state.z, state.x\n        state.f_x = gradient!(state.grad_f_x, iter.f, state.x)\n    end\n\n    state.y .= state.x .- state.gamma .* state.grad_f_x\n    state.g_z = prox!(state.z, iter.g, state.y, state.gamma)\n\n    state.res .= state.x .- state.z\n\n    return state, state\nend\n\n# Solver\n\nstruct ForwardBackward{R, K}\n    maxit::Int\n    tol::R\n    verbose::Bool\n    freq::Int\n    kwargs::K\nend\n\nfunction (solver::ForwardBackward)(x0; kwargs...)\n    stop(state::ForwardBackwardState) = norm(state.res, Inf) / state.gamma <= solver.tol\n    disp((it, state)) =\n        @printf(\"%5d | %.3e | %.3e\\n\", it, state.gamma, norm(state.res, Inf) / state.gamma)\n    iter = ForwardBackwardIteration(; x0=x0, solver.kwargs..., kwargs...)\n    iter = take(halt(iter, stop), solver.maxit)\n    iter = enumerate(iter)\n    if solver.verbose\n        iter = tee(sample(iter, solver.freq), disp)\n    end\n    num_iters, state_final = loop(iter)\n    return state_final.z, num_iters\nend\n\nForwardBackward(; maxit=10_000, tol=1e-8, verbose=false, freq=100, kwargs...) = \n    ForwardBackward(maxit, tol, verbose, freq, kwargs)\n\n# Aliases\n\nconst ProximalGradientIteration = ForwardBackwardIteration\nconst ProximalGradient = ForwardBackward\n", "meta": {"hexsha": "ce18205ae0830afb677581aefc9bf15b2a28d681", "size": 4151, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algorithms/forward_backward.jl", "max_stars_repo_name": "JuliaFirstOrder/ProximalAlgorithms.jl", "max_stars_repo_head_hexsha": "ee31033eadbbe6801915bd4831b79d781330b5a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2021-07-30T02:36:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T06:31:43.000Z", "max_issues_repo_path": "src/algorithms/forward_backward.jl", "max_issues_repo_name": "MPF-Optimization-Laboratory/ProximalAlgorithms.jl", "max_issues_repo_head_hexsha": "624886cb42c8040169d07e7c4ac95114f954aa83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2021-09-20T02:53:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T15:07:02.000Z", "max_forks_repo_path": "src/algorithms/forward_backward.jl", "max_forks_repo_name": "kul-optec/ProximalAlgorithms.jl", "max_forks_repo_head_hexsha": "238dfd213ea5994cb610421dde193da661bbca3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-08-13T11:31:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T22:57:25.000Z", "avg_line_length": 33.7479674797, "max_line_length": 146, "alphanum_fraction": 0.6583955673, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103777, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.7562628922911849}}
{"text": "################################################################################\n## Linear Regression\n##   y ~ N(b0 + b1 * x, s2)\n##   b0, b1 ~ N(0, 1000)\n##   s2 ~ invgamma(0.001, 0.001)\n################################################################################\n\nusing Mamba\n\n## Data\ndata = Dict(\n  :x => [1, 2, 3, 4, 5],\n  :y => [1, 3, 3, 3, 5]\n)\n\n## Log-transformed Posterior(b0, b1, log(s2)) + Constant and Gradient Vector\nlogfgrad = function(x::DenseVector)\n  b0 = x[1]\n  b1 = x[2]\n  logs2 = x[3]\n  r = data[:y] - b0 - b1 * data[:x]\n  logf = (-0.5 * length(data[:y]) - 0.001) * logs2 -\n           (0.5 * dot(r, r) + 0.001) / exp(logs2) -\n           0.5 * b0^2 / 1000 - 0.5 * b1^2 / 1000\n  grad = [\n    sum(r) / exp(logs2) - b0 / 1000,\n    sum(data[:x] .* r) / exp(logs2) - b1 / 1000,\n    -0.5 * length(data[:y]) - 0.001 + (0.5 * dot(r, r) + 0.001) / exp(logs2)\n  ]\n  logf, grad\nend\n\n## MCMC Simulation with Metropolis-Adjusted Langevin Algorithm\n## Without (1) and with (2) a user-specified proposal covariance matrix\nn = 5000\nsim1 = Chains(n, 3, names = [\"b0\", \"b1\", \"s2\"])\nsim2 = Chains(n, 3, names = [\"b0\", \"b1\", \"s2\"])\nepsilon = 0.1\nSigma = eye(3)\ntheta1 = MALAVariate([0.0, 0.0, 0.0], epsilon, logfgrad)\ntheta2 = MALAVariate([0.0, 0.0, 0.0], epsilon, Sigma, logfgrad)\nfor i in 1:n\n  sample!(theta1)\n  sample!(theta2)\n  sim1[i, :, 1] = [theta1[1:2]; exp(theta1[3])]\n  sim2[i, :, 1] = [theta2[1:2]; exp(theta2[3])]\nend\ndescribe(sim1)\ndescribe(sim2)\n", "meta": {"hexsha": "daa72ecefd5e74b11867da3e9aaf276e8c8befe3", "size": 1463, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "doc/samplers/mala.jl", "max_stars_repo_name": "JuliaPackageMirrors/Mamba.jl", "max_stars_repo_head_hexsha": "61d716958902077d0c9e7030ae490153ac515ae1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/samplers/mala.jl", "max_issues_repo_name": "JuliaPackageMirrors/Mamba.jl", "max_issues_repo_head_hexsha": "61d716958902077d0c9e7030ae490153ac515ae1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/samplers/mala.jl", "max_forks_repo_name": "JuliaPackageMirrors/Mamba.jl", "max_forks_repo_head_hexsha": "61d716958902077d0c9e7030ae490153ac515ae1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-15T05:12:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-15T05:12:54.000Z", "avg_line_length": 29.26, "max_line_length": 80, "alphanum_fraction": 0.4928229665, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7562628765574535}}
{"text": "\"\"\"\n    internal_rate_of_return(cashflows::vector)::Yields.Rate\n    internal_rate_of_return(cashflows::Vector, timepoints::Vector)::Yields.Rate\n    \nCalculate the internal_rate_of_return with given timepoints. If no timepoints given, will assume that a series of equally spaced cashflows, assuming the first cashflow occurring at time zero and subsequent elements at time 1, 2, 3, ..., n. \n\nReturns a Yields.Rate type with periodic compounding once per period (e.g. annual effective if the `timepoints` given represent years). Get the scalar rate by calling `Yields.rate()` on the result.\n\n# Example\n```julia-repl\njulia> internal_rate_of_return([-100,110],[0,1]) # e.g. cashflows at time 0 and 1\n0.10000000001652906\njulia> internal_rate_of_return([-100,110]) # implied the same as above\n0.10000000001652906\n```\n\n# Solver notes\nWill try to return a root within the range [-2,2]. If the fast solver does not find one matching this condition, then a more robust search will be performed over the [.99,2] range.\n\nThe solution returned will be in the range [-2,2], but may not be the one nearest zero. For a slightly slower, but more robust version, call `ActuaryUtilities.irr_robust(cashflows,timepoints)` directly.\n\"\"\"\nfunction internal_rate_of_return(cashflows)\n    \n\n    return internal_rate_of_return(cashflows, 0:length(cashflows)-1)\n    \nend\n\nfunction internal_rate_of_return(cashflows,times)\n    # first try to quickly solve with newton's method, otherwise \n    # revert to a more robust method\n    lower,upper = -2.,2.\n    \n    v = try \n        return irr_newton(cashflows,times)\n    catch e\n        if isa(e,Roots.ConvergenceFailed) || sprint(showerror, e) ==\"No convergence\"\n            return irr_robust(cashflows,times)\n        else\n            throw(e)\n        end\n    end\n    \n    if v <= upper && v >= lower\n        return v\n    else\n        return irr_robust(cashflows,times)\n    end\nend\n\nirr_robust(cashflows) = irr_robust(cashflows,0:length(cashflows)-1)\n\nfunction irr_robust(cashflows, times)\n    f(i) =  sum(cf / (1+i)^t for (cf,t) in zip(cashflows,times))\n    # lower bound at -.99 because otherwise we can start taking the root of a negative number\n    # when a time is fractional. \n    roots = Roots.find_zeros(f, -0.99, 2)\n    \n    # short circuit and return nothing if no roots found\n    isempty(roots) && return nothing\n    # find and return the one nearest zero\n    min_i = argmin(roots)\n    return Yields.Periodic(roots[min_i],1)\n\nend\n\nirr_newton(cashflows) = irr_newton(cashflows,0:length(cashflows)-1)\n\nfunction irr_newton(cashflows, times)\n    # use newton's method with hand-coded derivative\n    f(r) =  sum(cf * exp(-r*t) for (cf,t) in zip(cashflows,times))\n    f′(r) = sum(-t*cf * exp(-r*t) for (cf,t) in zip(cashflows,times) if t > 0)\n    # r = Roots.solve(Roots.ZeroProblem((f,f′), 0.0), Roots.Newton())\n    r = Roots.newton(x->(f(x),f(x)/f′(x)),0.0)\n    return Yields.Periodic(exp(r)-1,1)\n\nend\n\n\"\"\"\n    irr(cashflows::vector)\n    irr(cashflows::Vector, timepoints::Vector)\n\n    An alias for `internal_rate_of_return`.\n\"\"\"\nirr = internal_rate_of_return\n\n\"\"\"\n    present_value(interest, cashflows::Vector, timepoints)\n    present_value(interest, cashflows::Vector)\n\nDiscount the `cashflows` vector at the given `interest_interestrate`,  with the cashflows occurring\nat the times specified in `timepoints`. If no `timepoints` given, assumes that cashflows happen at times 1,2,...,n.\n\nThe `interest` can be an `InterestCurve`, a single scalar, or a vector wrapped in an `InterestCurve`. \n\n# Examples\n```julia-repl\njulia> present_value(0.1, [10,20],[0,1])\n28.18181818181818\njulia> present_value(Yields.Forward([0.1,0.2]), [10,20],[0,1])\n28.18181818181818 # same as above, because first cashflow is at time zero\n```\n\nExample on how to use real dates using the [DayCounts.jl](https://github.com/JuliaFinance/DayCounts.jl) package\n```jldoctest\n\nusing DayCounts \ndates = Date(2012,12,31):Year(1):Date(2013,12,31)\ntimes = map(d -> yearfrac(dates[1], d, DayCounts.Actual365Fixed()),dates) # [0.0,1.0]\npresent_value(0.1, [10,20],times)\n\n# output\n28.18181818181818\n\n```\n\n\"\"\"\nfunction present_value(yc::T, cashflows, timepoints) where {T <: Yields.AbstractYield}\n    sum(discount(yc,t) * cf for (t,cf) in zip(timepoints, cashflows))\nend\n\nfunction present_value(yc::T, cashflows) where {T <: Yields.AbstractYield}\n    present_value(yc,cashflows,1:length(cashflows))\nend\n\nfunction present_value(i, x)\n    \n    v = 1.0\n    v_factor = discount(i,0,1)\n    pv = 0.0\n\n    for (t,cf) in zip(1:length(x),x)\n        v *= v_factor\n        pv += v * cf\n    end\n    return pv \nend\n\nfunction present_value(i, v, times)\n    return present_value(Yields.Constant(i), v, times)\nend\n\n# Interest Given is an array, assume forwards.\nfunction present_value(i::AbstractArray, v)\n    yc = Yields.Forward(i)\n    return sum(discount(yc, t) * cf for (t,cf) in zip(1:length(v),v))\nend\n\n# Interest Given is an array, assume forwards.\nfunction present_value(i::AbstractArray, v, times)\n    yc = Yields.Forward(i, times)\n    return sum(discount(yc, t) * cf for (cf, t) in zip(v,times))\nend\n\n\"\"\"\n    pv()\n\n    An alias for `present_value`.\n\"\"\"\npv = present_value\n\n\n\"\"\"\n    present_value(interest, cashflows::Vector, timepoints)\n    present_value(interest, cashflows::Vector)\n\nEfficiently calculate a vector representing the present value of the given cashflows at each period prior to the given timepoint.\n\n# Examples\n```julia-repl\njulia> present_values(0.00, [1,1,1])\n[3,2,1]\n\njulia> present_values(Yields.Forward([0.1,0.2]), [10,20],[0,1])\n2-element Vector{Float64}:\n 28.18181818181818\n 18.18181818181818\n```\n\n\"\"\"\nfunction present_values(interest, cashflows)\n    pvs = Vector{Float64}(undef,length(cashflows))\n    pvs[end] = Yields.discount(interest, lastindex(cashflows) - 1, lastindex(cashflows)) * cashflows[end]\n    for (t, cf) in Iterators.reverse(enumerate(cashflows[1:end - 1]))\n        pvs[t] = Yields.discount(interest, t - 1, t) * (cf + pvs[t + 1])\n    end\n\n    return pvs\nend\n\n\nfunction present_values(interest,cashflows,times)\n    present_values_accumulator(interest,cashflows,times)\nend\n\nfunction present_values_accumulator(interest,cashflows,times,pvs=[0.0])\n    from_time = length(times) == 1 ? 0. : times[end-1]\n    pv = discount(interest,from_time,last(times)) *(first(pvs) + last(cashflows))\n    pvs = pushfirst!(pvs,pv)\n\n    if length(cashflows) > 1\n\n        new_cfs = @view cashflows[1:end-1]\n        new_times = @view times[1:end-1]\n        return present_values_accumulator(interest,new_cfs,new_times,pvs)\n    else\n        # last discount and return\n        return pvs[1:end-1] # end-1 get rid of trailing 0.0\n    end\nend\n\n# if given a vector of rates, assume that it should be a forward discount yield\nfunction present_values(y::Vector{T}, cfs, times) where {T <: Real}\n    return present_values(Yields.Forward(y), cfs, times)\nend\n\n\n\"\"\"\n    price(...)\n\nThe absolute value of the `present_value(...)`. \n\n# Extended help\n\nUsing `price` can be helpful if the directionality of the value doesn't matter. For example, in the common usage, duration is more interested in the change in price than present value, so `price` is used there.\n\"\"\"\nprice(x1,x2) = present_value(x1, x2) |> abs\nprice(x1,x2,x3) = present_value(x1, x2, x3) |> abs\n\n\"\"\"\n    breakeven(yield, cashflows::Vector)\n    breakeven(yield, cashflows::Vector,times::Vector)\n\nCalculate the time when the accumulated cashflows breakeven given the yield.\n\nAssumptions:\n\n- cashflows occur at the end of the period\n- cashflows evenly spaced with the first one occuring at time zero if `times` not given\n\nReturns `nothing` if cashflow stream never breaks even.\n\n```jldoctest\njulia> breakeven(0.10, [-10,1,2,3,4,8])\n5\n\njulia> breakeven(0.10, [-10,15,2,3,4,8])\n1\n\njulia> breakeven(0.10, [-10,-15,2,3,4,8]) # returns the `nothing` value\n\n\n```\n\"\"\"\nfunction breakeven(y::T, cashflows::Vector, timepoints::Vector) where {T <: Yields.AbstractYield}\n    accum = zero(eltype(cashflows))\n    last_neg = nothing\n\n    accum += cashflows[1]\n    if accum >= 0 && isnothing(last_neg)\n        last_neg = timepoints[1]\n    end\n\n    for i in 2:length(cashflows)\n        # accumulate the flow from each timepoint to the next\n        accum *= Yields.accumulation(y, timepoints[i - 1], timepoints[i])\n        accum += cashflows[i]\n\n        if accum >= 0 && isnothing(last_neg)\n            last_neg = timepoints[i]\n        elseif accum < 0\n            last_neg = nothing\n        end\n    end\n\n    return last_neg\n\nend\n\nfunction breakeven(y::T, cfs, times) where {T <: Real}\n    return breakeven(Yields.Constant(y), cfs, times)\nend\n\nfunction breakeven(y::Vector{T}, cfs, times) where {T <: Real}\n    return breakeven(Yields.Forward(y), cfs, times)\nend\n\nfunction breakeven(i, cashflows::Vector)\n    return breakeven(i, cashflows, [t for t in 0:length(cashflows) - 1])\nend\n\nabstract type Duration end\n\nstruct Macaulay <: Duration end\nstruct Modified <: Duration end\nstruct DV01 <: Duration end\n\nabstract type KeyRateDuration <: Duration end\n\n\n\"\"\"\n    KeyRatePar(timepoint,shift=0.001) <: KeyRateDuration\n\nShift the par curve by the given amount at the given timepoint. Use in conjunction with `duration` to calculate the key rate duration. \n\nUnlike other duration statistics which are computed using analytic derivatives, `KeyRateDuration`s are computed via a shift-and-compute the yield curve approach.\n\n`KeyRatePar` is more commonly reported (than [`KayRateZero`](@ref)) in the fixed income markets, even though the latter has more analytically attractive properties. See the discussion of KeyRateDuration in the Yields.jl docs.\n\n\"\"\"\nstruct KeyRatePar{T,R} <: KeyRateDuration \n    timepoint::T\n    shift::R\n    KeyRatePar(timepoint, shift=.001) = new{typeof(timepoint),typeof(shift)}(timepoint,shift)\nend\n\n\"\"\"\n    KeyRateZero(timepoint,shift=0.001) <: KeyRateDuration\n\nShift the par curve by the given amount at the given timepoint. Use in conjunction with `duration` to calculate the key rate duration.\n\nUnlike other duration statistics which are computed using analytic derivatives, `KeyRateDuration` is computed via a shift-and-compute the yield curve approach.\n\n`KeyRateZero` is less commonly reported (than [`KayRatePar`](@ref)) in the fixed income markets, even though the latter has more analytically attractive properties. See the discussion of KeyRateDuration in the Yields.jl docs.\n\"\"\"\nstruct KeyRateZero{T,R} <: KeyRateDuration \n    timepoint::T\n    shift::R\n    KeyRateZero(timepoint, shift=.001) = new{typeof(timepoint),typeof(shift)}(timepoint,shift)\nend\n\n\"\"\"\n    KeyRate(timepoints,shift=0.001)\n\nA convenience constructor for [`KeyRateZero`](@ref). \n\n## Extended Help\n[`KeyRateZero`](@ref) is chosen as the default constructor because it has more attractive properties than [`KeyRatePar`](@ref):\n\n- rates after the key `timepoint` remain unaffected by the `shift`\n  - e.g. this causes a 6-year zero coupon bond would have a negative duration if the 5-year par rate was used\n\n\n\"\"\"\nKeyRate = KeyRateZero\n\n\"\"\" \n    duration(Macaulay(),interest_rate,cfs,times)\n    duration(Modified(),interest_rate,cfs,times)\n    duration(DV01(),interest_rate,cfs,times)\n    duration(interest_rate,cfs,times)             # Modified Duration\n    duration(interest_rate,valuation_function)    # Modified Duration\n\nCalculates the Macaulay, Modified, or DV01 duration. `times` may be ommitted and the valuation will assume evenly spaced cashflows starting at the end of the first period.\n- `interest_rate` should be a fixed effective yield (e.g. `0.05`).\n\n\nWhen not given `Modified()` or `Macaulay()` as an argument, will default to `Modified()`.\n\n# Examples\n\nUsing vectors of cashflows and times\n```julia-repl\njulia> times = 1:5\njulia> cfs = [0,0,0,0,100]\njulia> duration(0.03,cfs,times)\n4.854368932038834\njulia> duration(Macaulay(),0.03,cfs,times)\n5.0\njulia> duration(Modified(),0.03,cfs,times)\n4.854368932038835\njulia> convexity(0.03,cfs,times)\n28.277877274012614\n\n```\n\nUsing any given value function: \n\n```julia-repl\njulia> lump_sum_value(amount,years,i) = amount / (1 + i ) ^ years\njulia> my_lump_sum_value(i) = lump_sum_value(100,5,i)\njulia> duration(0.03,my_lump_sum_value)\n4.854368932038835\njulia> convexity(0.03,my_lump_sum_value)\n28.277877274012617\n\n```\n\"\"\"\nfunction duration(::Macaulay, yield, cfs, times)\n    return sum(times .* price.(yield, vec(cfs), times) / price(yield, vec(cfs), times))\nend\n\nfunction duration(::Modified, yield, cfs, times)\n    D(i) = price(i, vec(cfs), times)\n    return duration(yield, D)\nend\n\nfunction duration(yield, valuation_function)\n    D(i) = log(valuation_function(i + yield))\n    δV =  - ForwardDiff.derivative(D, 0.0)\nend\n\nfunction duration(yield::Y, valuation_function) where {Y <: Yields.AbstractYield}\n    D(i) = log(valuation_function(i + yield))\n    δV =  - ForwardDiff.derivative(D, 0.0)\nend\n\nfunction duration(yield, cfs, times)\n    return duration(Modified(), yield, vec(cfs), times)\nend\nfunction duration(yield::Y, cfs::A) where {Y <: Yields.AbstractYield,A <: AbstractArray}\n    times = 1:length(cfs)\n    return duration(Modified(), yield, vec(cfs), times)\nend\n\nfunction duration(yield::R, cfs) where {R <: Real}\n    return duration(Yields.Constant(yield), cfs)\nend\n\nfunction duration(::DV01, yield, cfs, times)\n    return duration(DV01(), yield, i -> price(i, vec(cfs), times))\nend\nfunction duration(d::Duration, yield, cfs)\n    times = 1:length(cfs)\n    return duration(d, yield, vec(cfs), times)\nend\n\nfunction duration(::DV01, yield, valuation_function)\n    return duration(yield, valuation_function) * valuation_function(yield) / 100\nend\n\n\"\"\" \n    convexity(yield,cfs,times)\n    convexity(yield,valuation_function)\n\nCalculates the convexity.\n    - `yield` should be a fixed effective yield (e.g. `0.05`).\n    - `times` may be omitted and it will assume `cfs` are evenly spaced beginning at the end of the first period.\n\n# Examples\n\nUsing vectors of cashflows and times\n```julia-repl\njulia> times = 1:5\njulia> cfs = [0,0,0,0,100]\njulia> duration(0.03,cfs,times)\n4.854368932038834\njulia> duration(Macaulay(),0.03,cfs,times)\n5.0\njulia> duration(Modified(),0.03,cfs,times)\n4.854368932038835\njulia> convexity(0.03,cfs,times)\n28.277877274012614\n\n```\n\nUsing any given value function: \n\n```julia-repl\njulia> lump_sum_value(amount,years,i) = amount / (1 + i ) ^ years\njulia> my_lump_sum_value(i) = lump_sum_value(100,5,i)\njulia> duration(0.03,my_lump_sum_value)\n4.854368932038835\njulia> convexity(0.03,my_lump_sum_value)\n28.277877274012617\n\n```\n\n\"\"\"\nfunction convexity(yield, cfs, times)\n    return convexity(yield, i -> price(i, vec(cfs), times))\nend\n\nfunction convexity(yield, cfs::A) where {A <: AbstractArray}\n    times = 1:length(cfs)\n    return convexity(yield, i -> price(i, vec(cfs), times))\nend\n\nfunction convexity(yield, valuation_function)\n    v(x) = abs(valuation_function(yield + x[1]))\n    ∂²P = ForwardDiff.hessian(v, [0.0])\n    return ∂²P[1] / v([0.0])  \nend\n\n\n\"\"\"\n    duration(keyrate::KeyRateDuration,curve,cashflows)    \n    duration(keyrate::KeyRateDuration,curve,cashflows,timepoints)\n    duration(keyrate::KeyRateDuration,curve,cashflows,timepoints,krd_points)\n\nCalculate the key rate duration by shifting the **zero** (not par) curve by the kwarg `shift` at the timepoint specified by a KeyRateDuration(time).\n\nThe approach is to carve up the curve into `krd_points` (default is the unit steps between `1` and  the last timepoint of the casfhlows). The \nzero rate corresponding to the timepoint within the `KeyRateDuration` is shifted by `shift` (specified by the `KeyRateZero` or `KeyRatePar` constructors. A new curve is created from the shifted rates. This means that the \n\"width\" of the shifted section is ± 1 time period, unless specific points are specified via `krd_points`.\n\nThe `curve` may be any Yields.jl curve (e.g. does not have to be a curve constructed via `Yields.Zero(...)`).\n\n!!! Experimental: Due to the paucity of examples in the literature, this feature does not have unit tests like the rest of JuliaActuary functionality. Additionally, the API may change in a future major/minor version update.\n\n# Examples\n\n\n```julia-repl\njulia> riskfree_maturities = [0.5, 1.0, 1.5, 2.0];\n\njulia> riskfree    = [0.05, 0.058, 0.064,0.068];\n\njulia> rf_curve = Yields.Zero(riskfree,riskfree_maturities);\n\njulia> cfs = [10,10,10,10,10];\n\njulia> duration(KeyRate(1),rf_curve,cfs)\n8.932800152336995\n\n```\n\n# Extended Help\n\nKey Rate Duration is not a well specified topic in the literature and in practice. The reference below suggest that shocking the par curve is more common \nin practice, but that the zero curve produces more consistent results. Future versions may support shifting the par curve.\n\nReferences: \n- [Quant Finance Stack Exchange: To compute key rate duration, shall I use par curve or zero curve?](https://quant.stackexchange.com/questions/33891/to-compute-key-rate-duration-shall-i-use-par-curve-or-zero-curve)\n- (Financial Exam Help 123](http://www.financialexamhelp123.com/key-rate-duration/)\n\n\"\"\"\nfunction duration(keyrate::KeyRateDuration, curve, cashflows, timepoints, krd_points)\n    shift = keyrate.shift\n    curve_up = _krd_new_curve(keyrate,curve,krd_points)\n    curve_down = _krd_new_curve(opposite(keyrate),curve,krd_points)\n    price = pv(curve, cashflows, timepoints)\n    price_up = pv(curve_up, cashflows, timepoints)\n    price_down = pv(curve_down, cashflows, timepoints)\n    \n\n    return (price_down - price_up) / (2*shift*price)\n\nend\n\nopposite(kr::KeyRateZero) = KeyRateZero(kr.timepoint,-kr.shift)\nopposite(kr::KeyRatePar) = KeyRatePar(kr.timepoint,-kr.shift)\n\nfunction _krd_new_curve(keyrate::KeyRateZero,curve,krd_points)\n    curve_times = krd_points\n    shift = keyrate.shift\n\n    zeros = Yields.zero.(curve, curve_times)\n\n    zero_index = findfirst(==(keyrate.timepoint), curve_times)\n\n    target_rate = zeros[zero_index]\n\n    zeros[zero_index] += Yields.Rate(shift,target_rate.compounding)\n\n    new_curve = Yields.Zero(zeros, curve_times)\n\n    return new_curve\nend\n\nfunction _krd_new_curve(keyrate::KeyRatePar,curve,krd_points)\n    curve_times = krd_points\n    shift = keyrate.shift\n\n    pars = Yields.par.(curve, curve_times)\n\n    zero_index = findfirst(==(keyrate.timepoint), curve_times)\n\n    target_rate = pars[zero_index]\n    pars[zero_index] += Yields.Rate(shift,target_rate.compounding)\n\n    new_curve = Yields.Par(pars, curve_times)\n\n    return new_curve\nend\n\nfunction duration(keyrate::KeyRateDuration, curve, cashflows, timepoints)\n    krd_points = 1:maximum(timepoints)\n    return duration(keyrate, curve, cashflows, timepoints, krd_points)\n\nend\n\nfunction duration(keyrate::KeyRateDuration, curve, cashflows)\n    timepoints = eachindex(cashflows)\n    krd_points = 1:maximum(timepoints)\n    return duration(keyrate, curve, cashflows, timepoints, krd_points)\n\nend\n\n\"\"\"\n    moic(cashflows<:AbstractArray)\n\nThe multiple on invested capital (\"moic\") is the un-discounted sum of distributions divided by the sum of the contributions. The function assumes that negative numbers in the array represent contributions and positive numbers represent distributions.\n\n# Examples\n\n```julia-repl\njulia> moic([-10,20,30])\n5.0\n```\n\n\"\"\"\nfunction moic(cfs::T) where {T<:AbstractArray}\n    invested = zero(eltype(cfs))\n    returned = zero(eltype(cfs))\n    for i = 1:length(cfs)\n        @inbounds cf = cfs[i]\n        if cf > 0\n            returned += cf\n        else\n            invested += -cf\n        end\n    end\n\n    return returned / invested\nend", "meta": {"hexsha": "2b5a49561106030ad71c5014c34ba9595d750e9b", "size": 19386, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/financial_math.jl", "max_stars_repo_name": "alecloudenback/ActuaryUtilities.jl", "max_stars_repo_head_hexsha": "f17d18516840a4b6334648a9fe3cf5eda1b041f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/financial_math.jl", "max_issues_repo_name": "alecloudenback/ActuaryUtilities.jl", "max_issues_repo_head_hexsha": "f17d18516840a4b6334648a9fe3cf5eda1b041f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/financial_math.jl", "max_forks_repo_name": "alecloudenback/ActuaryUtilities.jl", "max_forks_repo_head_hexsha": "f17d18516840a4b6334648a9fe3cf5eda1b041f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4707792208, "max_line_length": 250, "alphanum_fraction": 0.715516352, "num_tokens": 5531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7562628760467766}}
{"text": "\nfunction CellRef(n::AbstractString)\n    @assert is_valid_cellname(n) \"$n is not a valid CellRef.\"\n    column_name, row_number = split_cellname(n)\n    return CellRef(n, row_number, decode_column_number(column_name))\nend\n\n@inline CellRef(row::Int, col::Int) = CellRef(encode_column_number(col) * string(row))\n@inline CellPosition(ref::CellRef) = CellPosition(row_number(ref), column_number(ref))\n@inline row_number(p::CellPosition) = p.row\n@inline column_number(p::CellPosition) = p.column\n@inline CellRef(p::CellPosition) = CellRef(row_number(p), column_number(p))\n\n\"\"\"\n    decode_column_number(column_name::AbstractString) :: Int\n\nConverts column name to a column number.\n\n```julia\njulia> XLSX.decode_column_number(\"D\")\n4\n```\n\nSee also: `encode_column_number`.\n\"\"\"\nfunction decode_column_number(column_name::AbstractString) :: Int\n    local result::Int = 0\n\n    num_characters = length(column_name)\n\n    iteration = 1\n    for i in num_characters:-1:1\n        column_char_as_int = Int(column_name[i])\n        result += (26^(iteration-1)) * (column_char_as_int - 64) # From A to Z we have 26 values. 'A' Char is ASCII 65.\n        iteration += 1\n    end\n\n    return result\nend\n\n\"\"\"\n    encode_column_number(column_number::Int) :: String\n\nConverts column number to a column name.\n\n# Example\n\n```julia\njulia> XLSX.encode_column_number(4)\n\"D\"\n```\n\nSee also: `decode_column_number`.\n\"\"\"\nfunction encode_column_number(column_number::Int) :: String\n    @assert column_number > 0 && column_number <= 16384 \"Column number should be in the range from 1 to 16384.\"\n\n    third_letter_sequence = div(column_number - 26 - 1, 26*26)\n    column_number = column_number - third_letter_sequence*(26*26)\n\n    second_letter_sequence = div(column_number - 1, 26) # 26^1\n    column_number = column_number - second_letter_sequence*(26)\n\n    first_letter_sequence = column_number # 26^0\n\n    if third_letter_sequence > 0\n        # result will have 3 letters\n        return String([ Char(third_letter_sequence+64), Char(second_letter_sequence+64), Char(first_letter_sequence+64) ])\n\n    elseif second_letter_sequence > 0\n        # result will have 2 letters\n        return String([ Char(second_letter_sequence+64), Char(first_letter_sequence+64) ])\n\n    else\n        # result will have 1 letter\n        return String([ Char(first_letter_sequence+64) ])\n    end\nend\n\nBase.string(c::CellRef) = c.name\nBase.show(io::IO, c::CellRef) = print(io, string(c))\nBase.:(==)(c1::CellRef, c2::CellRef) = c1.name == c2.name\nBase.hash(c::CellRef) = hash(c.name)\n\nconst RGX_COLUMN_NAME = r\"^[A-Z]?[A-Z]?[A-Z]$\"\nconst RGX_CELLNAME = r\"^[A-Z]+[0-9]+$\"\nconst RGX_CELLRANGE = r\"^[A-Z]+[0-9]+:[A-Z]+[0-9]+$\"\n\nfunction is_valid_column_name(n::AbstractString) :: Bool\n    if !occursin(RGX_COLUMN_NAME, n)\n        return false\n    end\n\n    column_number = decode_column_number(n)\n    if column_number < 1 || column_number > 16384\n        return false\n    end\n\n    return true\nend\n\nconst RGX_CELLNAME_LEFT = r\"^[A-Z]+\"\nconst RGX_CELLNAME_RIGHT = r\"[0-9]+$\"\n\n\"\"\"\n    split_cellname(n::AbstractString) -> column_name, row_number\n\nSplits a string representing a cell name to its column name and row number.\n\n# Example\n\n```julia\njulia> XLSX.split_cellname(\"AB:12\")\n(\"AB:\", 12)\n```\n\"\"\"\n@inline function split_cellname(n::AbstractString)\n    for (i, c) in enumerate(n)\n        if isdigit(c)\n            column_name = SubString(n, 1, i-1)\n            row = parse(Int, SubString(n, i, length(n)))\n\n            return column_name, row\n        end\n    end\n\n    error(\"Couldn't split (column_name, row) for cellname $n.\")\nend\n\n\"\"\"\n    is_valid_cellname(n::AbstractString) :: Bool\n\nChecks wether `n` is a valid name for a cell.\n\nCell names are bounded by `A1 : XFD1048576`.\n\"\"\"\nfunction is_valid_cellname(n::AbstractString) :: Bool\n\n    if !occursin(RGX_CELLNAME, n)\n        return false\n    end\n\n    column_name, row = split_cellname(n)\n\n    if row < 1 || row > 1048576\n        return false\n    end\n\n    if !is_valid_column_name(column_name)\n        return false\n    end\n\n    return true\nend\n\nconst RGX_CELLRANGE_START = r\"^[A-Z]+[0-9]+\"\nconst RGX_CELLRANGE_STOP = r\"[A-Z]+[0-9]+$\"\n\n\"\"\"\n    split_cellrange(n::AbstractString) -> start_name, stop_name\n\nSplits a string representing a cell range into its cell names.\n\n# Example\n\n```julia\njulia> XLSX.split_cellrange(\"AB12:CD24\")\n(\"AB12\", \"CD24\")\n```\n\"\"\"\n@inline function split_cellrange(n::AbstractString)\n    s = split(n, \":\")\n    @assert length(s) == 2 \"$n is not a valid cell range.\"\n    return s[1], s[2]\nend\n\nfunction is_valid_cellrange(n::AbstractString) :: Bool\n\n    if !occursin(RGX_CELLRANGE, n)\n        return false\n    end\n\n    start_name, stop_name = split_cellrange(n)\n\n    if !is_valid_cellname(start_name)\n        return false\n    end\n\n    if !is_valid_cellname(stop_name)\n        return false\n    end\n\n    return true\nend\n\nmacro ref_str(ref)\n    CellRef(ref)\nend\n\nfunction CellRange(r::AbstractString)\n    @assert occursin(RGX_CELLRANGE, r) \"Invalid cell range: $r.\"\n    start_name, stop_name = split_cellrange(r)\n    return CellRange(CellRef(start_name), CellRef(stop_name))\nend\n\nCellRange(start_row::Integer, start_column::Integer, stop_row::Integer, stop_column::Integer) = CellRange(CellRef(start_row, start_column), CellRef(stop_row, stop_column))\n\nBase.string(cr::CellRange) = \"$(string(cr.start)):$(string(cr.stop))\"\nBase.show(io::IO, cr::CellRange) = print(io, string(cr))\nBase.:(==)(cr1::CellRange, cr2::CellRange) = cr1.start == cr2.start && cr2.stop == cr2.stop\nBase.hash(cr::CellRange) = hash(cr.start) + hash(cr.stop)\n\nmacro range_str(cellrange)\n    CellRange(cellrange)\nend\n\n\"\"\"\n    Base.in(ref::CellRef, rng::CellRange) :: Bool\n\nChecks wether `ref` is a cell reference inside a range given by `rng`.\n\"\"\"\nfunction Base.in(ref::CellRef, rng::CellRange) :: Bool\n    top = row_number(rng.start)\n    bottom = row_number(rng.stop)\n    r = row_number(ref)\n\n    if top <= r && r <= bottom\n        left = column_number(rng.start)\n        right = column_number(rng.stop)\n        c = column_number(ref)\n\n        if left <= c && c <= right\n            return true\n        end\n    end\n\n    return false\nend\n\n\"\"\"\n    Base.issubset(subrng::CellRange, rng::CellRange)\n\nChecks wether `subrng` is a cell range contained in `rng`.\n\"\"\"\nBase.issubset(subrng::CellRange, rng::CellRange) :: Bool = in(subrng.start, rng) && in(subrng.stop, rng)\n\nfunction Base.size(rng::CellRange)\n    top = row_number(rng.start)\n    bottom = row_number(rng.stop)\n    left = column_number(rng.start)\n    right = column_number(rng.stop)\n\n    return ( bottom - top + 1, right - left + 1 )\nend\n\n\"\"\"\n    row_number(c::CellRef) :: Int\n\nReturns the row number of a given cell reference.\n\"\"\"\nrow_number(c::CellRef) :: Int = c.row_number\n\n\"\"\"\n    column_number(c::CellRef) :: Int\n\nReturns the column number of a given cell reference.\n\"\"\"\ncolumn_number(c::CellRef) :: Int = c.column_number\n\ncolumn_name(c::CellRef) :: String = encode_column_number(column_number(c))\n\n\"\"\"\nReturns (row, column) representing a `ref` position relative to `rng`.\n\nFor example, for a range \"B2:D4\", we have:\n\n* \"C3\" relative position is (2, 2)\n\n* \"B2\" relative position is (1, 1)\n\n* \"C4\" relative position is (3, 2)\n\n* \"D4\" relative position is (3, 3)\n\n\"\"\"\nfunction relative_cell_position(ref::CellRef, rng::CellRange)\n    @assert ref ∈ rng \"$ref is outside range $rng.\"\n\n    top = row_number(rng.start)\n    left = column_number(rng.start)\n\n    r, c = row_number(ref), column_number(ref)\n\n    return ( r - top + 1 , c - left + 1 )\nend\n\n#\n# ColumnRange\n#\n\nBase.string(cr::ColumnRange) = \"$(encode_column_number(cr.start)):$(encode_column_number(cr.stop))\"\nBase.show(io::IO, cr::ColumnRange) = print(io, string(cr))\nBase.:(==)(cr1::ColumnRange, cr2::ColumnRange) = cr1.start == cr2.start && cr2.stop == cr2.stop\nBase.hash(cr::ColumnRange) = hash(cr.start) + hash(cr.stop)\nBase.in(column_number::Integer, rng::ColumnRange) = rng.start <= column_number && column_number <= rng.stop\n\nfunction relative_column_position(column_number::Integer, rng::ColumnRange)\n    @assert column_number ∈ rng \"Column $column_number is outside range $rng.\"\n    return column_number - rng.start + 1\nend\n\n@inline relative_column_position(ref::CellRef, rng::ColumnRange) = relative_column_position(column_number(ref), rng)\n\nconst RGX_COLUMN_RANGE = r\"^[A-Z]?[A-Z]?[A-Z]:[A-Z]?[A-Z]?[A-Z]$\"\nconst RGX_COLUMN_RANGE_START = r\"^[A-Z]+\"\nconst RGX_COLUMN_RANGE_STOP = r\"[A-Z]+$\"\n\n\"\"\"\nReturns tuple (column_name_start, column_name_stop).\n\"\"\"\n@inline function split_column_range(n::AbstractString)\n    s = split(n, \":\")\n    return s[1], s[2]\nend\n\nfunction is_valid_column_range(r::AbstractString) :: Bool\n    if !occursin(RGX_COLUMN_RANGE, r)\n        return false\n    end\n\n    start_name, stop_name = split_column_range(r)\n\n    if !is_valid_column_name(start_name) || !is_valid_column_name(stop_name)\n        return false\n    end\n\n    return true\nend\n\nfunction ColumnRange(r::AbstractString)\n    @assert is_valid_column_range(r) \"Invalid column range: $r.\"\n    start_name, stop_name = split_column_range(r)\n    return ColumnRange(decode_column_number(start_name), decode_column_number(stop_name))\nend\n\nconvert(::Type{ColumnRange}, str::AbstractString) = ColumnRange(str)\nconvert(::Type{ColumnRange}, column_range::ColumnRange) = column_range\n\ncolumn_bounds(r::ColumnRange) = (r.start, r.stop)\nBase.length(r::ColumnRange) = r.stop - r.start + 1\n\n<<<<<<< HEAD\n# ColumnRange iterator\nstart(itr::ColumnRange) = itr.start\ndone(itr::ColumnRange, column_index::Int) = column_index > itr.stop\nnext(itr::ColumnRange, column_index::Int) = (encode_column_number(column_index), column_index + 1)\n\n# CellRange iterator\nstart(rng::CellRange) = CellRefIteratorState(row_number(rng.start), column_number(rng.start))\ndone(rng::CellRange, state::CellRefIteratorState) = state.row > row_number(rng.stop)\n=======\n# ColumnRange iterator: element is a String with the column name, the state is the column number.\nfunction Base.iterate(itr::ColumnRange, state::Int=itr.start)\n    if state > itr.stop\n        return nothing\n    end\n>>>>>>> upstream/master\n\n    return encode_column_number(state), state + 1\nend\n\n<<<<<<< HEAD\n# (i, state) = next(I, state)\nfunction next(rng::CellRange, state::CellRefIteratorState)\n    local next_state::CellRefIteratorState\n    if state.col == column_number(rng.stop)\n=======\n# CellRange iterator: element is a CellRef, the state is a CellPosition.\nfunction Base.iterate(rng::CellRange, state::CellPosition=CellPosition(rng.start))\n\n    if row_number(state) > row_number(rng.stop)\n        return nothing\n    elseif column_number(state) == column_number(rng.stop)\n>>>>>>> upstream/master\n        # reached last column. Go to the next row.\n        next_state = CellPosition(row_number(state) + 1, column_number(rng.start))\n    else\n        # go to the next column\n        next_state = CellPosition(row_number(state), column_number(state) + 1)\n    end\n\n    return CellRef(state), next_state\nend\n\nfunction Base.length(rng::CellRange)\n    (r, c) = size(rng)\n    return r * c\nend\n\n#\n# SheetCellRef, SheetCellRange, SheetColumnRange\n#\n\nBase.string(cr::SheetCellRef) = string(cr.sheet, \"!\", cr.cellref)\nBase.show(io::IO, cr::SheetCellRef) = print(io, string(cr))\nBase.:(==)(cr1::SheetCellRef, cr2::SheetCellRef) = cr1.sheet == cr2.sheet && cr2.cellref == cr2.cellref\nBase.hash(cr::SheetCellRef) = hash(cr.sheet) + hash(cr.cellref)\n\nBase.string(cr::SheetCellRange) = string(cr.sheet, \"!\", cr.rng)\nBase.show(io::IO, cr::SheetCellRange) = print(io, string(cr))\nBase.:(==)(cr1::SheetCellRange, cr2::SheetCellRange) = cr1.sheet == cr2.sheet && cr2.rng == cr2.rng\nBase.hash(cr::SheetCellRange) = hash(cr.sheet) + hash(cr.rng)\n\nBase.string(cr::SheetColumnRange) = string(cr.sheet, \"!\", cr.colrng)\nBase.show(io::IO, cr::SheetColumnRange) = print(io, string(cr))\nBase.:(==)(cr1::SheetColumnRange, cr2::SheetColumnRange) = cr1.sheet == cr2.sheet && cr2.colrng == cr2.colrng\nBase.hash(cr::SheetColumnRange) = hash(cr.sheet) + hash(cr.colrng)\n\nconst RGX_SHEET_CELLNAME = r\"^.+![A-Z]+[0-9]+$\"\nconst RGX_SHEET_CELLRANGE = r\"^.+![A-Z]+[0-9]+:[A-Z]+[0-9]+$\"\nconst RGX_SHEET_COLUMN_RANGE = r\"^.+![A-Z]?[A-Z]?[A-Z]:[A-Z]?[A-Z]?[A-Z]$\"\n\nconst RGX_SHEET_CELLNAME_RIGHT = r\"[A-Z]+[0-9]+$\"\nconst RGX_SHEET_CELLRANGE_RIGHT = r\"[A-Z]+[0-9]+:[A-Z]+[0-9]+$\"\nconst RGX_SHEET_COLUMN_RANGE_RIGHT = r\"[A-Z]?[A-Z]?[A-Z]:[A-Z]?[A-Z]?[A-Z]$\"\n\nfunction is_valid_sheet_cellname(n::AbstractString) :: Bool\n    if !occursin(RGX_SHEET_CELLNAME, n)\n        return false\n    end\n\n    cellname = match(RGX_SHEET_CELLNAME_RIGHT, n).match\n    if !is_valid_cellname(cellname)\n        return false\n    end\n\n    return true\nend\n\nfunction is_valid_sheet_cellrange(n::AbstractString) :: Bool\n    if !occursin(RGX_SHEET_CELLRANGE, n)\n        return false\n    end\n\n    cellrange = match(RGX_SHEET_CELLRANGE_RIGHT, n).match\n    if !is_valid_cellrange(cellrange)\n        return false\n    end\n\n    return true\nend\n\nfunction is_valid_sheet_column_range(n::AbstractString) :: Bool\n    if !occursin(RGX_SHEET_COLUMN_RANGE, n)\n        return false\n    end\n\n    column_range = match(RGX_SHEET_COLUMN_RANGE_RIGHT, n).match\n    if !is_valid_column_range(column_range)\n        return false\n    end\n\n    return true\nend\n\nconst RGX_CELLNAME_RIGHT_FIXED = r\"\\$[A-Z]+\\$[0-9]+$\"\nconst RGX_SHEET_CELNAME_RIGHT_FIXED = r\"\\$[A-Z]+\\$[0-9]+:\\$[A-Z]+\\$[0-9]+$\"\n\nfunction SheetCellRef(n::AbstractString)\n    if is_valid_fixed_sheet_cellname(n)\n        fixed_cellname = match(RGX_CELLNAME_RIGHT_FIXED, n).match\n        cellname = replace(fixed_cellname, \"\\$\" => \"\")\n        sheetname = SubString(n, 1, length(n) - length(fixed_cellname) - 1)\n        return SheetCellRef(sheetname, CellRef(cellname))\n    else\n        @assert is_valid_sheet_cellname(n) \"$n is not a valid SheetCellRef.\"\n        cellname = match(RGX_SHEET_CELLNAME_RIGHT, n).match\n        sheetname = SubString(n, 1, length(n) - length(cellname) - 1)\n        return SheetCellRef(sheetname, CellRef(cellname))\n    end\nend\n\nfunction SheetCellRange(n::AbstractString)\n    if is_valid_fixed_sheet_cellrange(n)\n        fixed_cellrange = match(RGX_SHEET_CELNAME_RIGHT_FIXED, n).match\n        cellrange = replace(fixed_cellrange, \"\\$\" => \"\")\n        sheetname = SubString(n, 1, length(n) - length(fixed_cellrange) - 1)\n        return SheetCellRange(sheetname, CellRange(cellrange))\n    else\n        @assert is_valid_sheet_cellrange(n) \"$n is not a valid SheetCellRange.\"\n        cellrange = match(RGX_SHEET_CELLRANGE_RIGHT, n).match\n        sheetname = SubString(n, 1, length(n) - length(cellrange) - 1)\n        return SheetCellRange(sheetname, CellRange(cellrange))\n    end\nend\n\nfunction SheetColumnRange(n::AbstractString)\n    @assert is_valid_sheet_column_range(n) \"$n is not a valid SheetColumnRange.\"\n    column_range = match(RGX_SHEET_COLUMN_RANGE_RIGHT, n).match\n    sheetname = SubString(n, 1, length(n) - length(column_range) - 1)\n    return SheetColumnRange(sheetname, ColumnRange(column_range))\nend\n\n# Named ranges\nconst RGX_FIXED_SHEET_CELLNAME = r\"^.+!\\$[A-Z]+\\$[0-9]+$\"\nconst RGX_FIXED_SHEET_CELLRANGE = r\"^.+!\\$[A-Z]+\\$[0-9]+:\\$[A-Z]+\\$[0-9]+$\"\n\nis_valid_fixed_sheet_cellname(s::AbstractString) = occursin(RGX_FIXED_SHEET_CELLNAME, s)\nis_valid_fixed_sheet_cellrange(s::AbstractString) = occursin(RGX_FIXED_SHEET_CELLRANGE, s)\n", "meta": {"hexsha": "da3057e9d980d50e8a61fd8a638f6bc445af271a", "size": 15236, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cellref.jl", "max_stars_repo_name": "YongHee-Kim/XLSX.jl", "max_stars_repo_head_hexsha": "27e8529705460c28cd638a9ae0b72288723dba11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cellref.jl", "max_issues_repo_name": "YongHee-Kim/XLSX.jl", "max_issues_repo_head_hexsha": "27e8529705460c28cd638a9ae0b72288723dba11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cellref.jl", "max_forks_repo_name": "YongHee-Kim/XLSX.jl", "max_forks_repo_head_hexsha": "27e8529705460c28cd638a9ae0b72288723dba11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-08-28T03:04:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-28T03:04:06.000Z", "avg_line_length": 29.8745098039, "max_line_length": 171, "alphanum_fraction": 0.6898135994, "num_tokens": 4290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.756262872368682}}
{"text": "## Whittle.jl : implementation of Whittle covariance function\n\n## Whittle ##\nstruct Whittle{T} <: IsotropicCovarianceStructure{T}\n    λ::T\n    σ::T\n    p::T\n\n    function Whittle{T}(λ::T, σ::T, p::T) where T\n        λ > 0 || throw(DomainError(λ, \"correlation length λ of Whittle covariance cannot be negative or zero\"))\n        σ > 0 || throw(DomainError(σ, \"marginal standard deviation σ of Whittle covariance cannot be negative or zero\"))\n        p >= 1 || throw(DomainError(p, \"in p-norm, p must be greater than or equal to 1\"))\n        isinf(p) && throw(DomainError(p, \"in p-norm, p cannot be infinity\"))\n\n        new{T}(λ, σ, p)\n    end\nend\n\n\"\"\"\n    Whittle(λ, [σ = 1], [p = 2])\n\nWhittle covariance structure with correlation length `λ`, (optional) marginal standard deviation `σ` and (optional) `p`-norm, defined as\n    \n``C(x, y) = σ \\\\displaystyle\\\\frac{ρ}{λ} K₁\\\\left(\\\\frac{ρ}{λ}\\\\right)``\n\nwith ``ρ = ||x-y||_p``.\n\n# Examples\n```jldoctest\njulia> Whittle(0.1)\nWhittle (λ=0.1, σ=1.0, p=2.0)\n\njulia> Whittle(1.0, σ=2)\nWhittle (λ=1.0, σ=2.0, p=2.0)\n\n```\nSee also: [`Exponential`](@ref), [`Linear`](@ref), [`Spherical`](@ref), [`Gaussian`](@ref), [`SquaredExponential`](@ref), [`Matern`](@ref)\n\"\"\"\nWhittle(λ::Real; σ::Real=1.0, p::Real=2) = Whittle{promote_type(typeof(λ),typeof(σ),typeof(p))}(promote(λ, σ, p)...)\n\n# evaluate Whittle covariance\nfunction apply(w::Whittle, x::Real)\n    if iszero(x)\n        float(one(x))\n    else\n        ρ = x / w.λ\n        ρ * besselk(1, ρ)\n    end\nend\n\n# short name\nshortname(::Whittle) = \"Whittle\"\n", "meta": {"hexsha": "9a01e6f2ec7d54e05669eba4d7b478a4143bcf7f", "size": 1541, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/covariance_functions/whittle.jl", "max_stars_repo_name": "Philippe1123/GaussianRandomFields.jl", "max_stars_repo_head_hexsha": "86ae443ae46d27a45d4afcdceb453c48cbfd9807", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2018-02-01T10:43:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:29:00.000Z", "max_issues_repo_path": "src/covariance_functions/whittle.jl", "max_issues_repo_name": "Philippe1123/GaussianRandomFields.jl", "max_issues_repo_head_hexsha": "86ae443ae46d27a45d4afcdceb453c48cbfd9807", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2018-01-17T18:32:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T07:14:13.000Z", "max_forks_repo_path": "src/covariance_functions/whittle.jl", "max_forks_repo_name": "Philippe1123/GaussianRandomFields.jl", "max_forks_repo_head_hexsha": "86ae443ae46d27a45d4afcdceb453c48cbfd9807", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-08-01T17:13:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T11:19:26.000Z", "avg_line_length": 29.0754716981, "max_line_length": 138, "alphanum_fraction": 0.61064244, "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7562519930131335}}
{"text": "# this illustrates effect and detection of influential observations\nusing Plots, LinearAlgebra\nn = 20\nx = (1:n-1)/(n-1)\nx = [x; 3] # the last observation is an outlying value of x\n\nx = [ones(n,1) x]\nP = x*inv(x'*x)*x'\n\nbeta = [10, -1]\ne = 2*randn(n,1)\ny = x*beta + e\n\n\n# The fit\nyhat = P*y\n\n# calculate leverage and influence\nleverage = diag(P)\ne = y - yhat\ninfluence = (leverage ./ (1.0 .-leverage)) .* e\n\nxlabel = \"X\"\nx = x[:,2]\nscatter(x, y, label = \"Data points\")\nplot!(x, yhat, label = \"fitted\")\nplot!(x, leverage, label = \"Leverage\")\nplot!(x, influence, label = \"Influence\")\ngui()\n#savefig(\"InfluentialObservation.svg\")\n", "meta": {"hexsha": "64fff18b8999e269421f077f400e125be93cb33d", "size": 626, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/OLS/InfluentialObservation.jl", "max_stars_repo_name": "nilshg/Econometrics", "max_stars_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-17T06:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T06:32:18.000Z", "max_issues_repo_path": "Examples/OLS/InfluentialObservation.jl", "max_issues_repo_name": "nilshg/Econometrics", "max_issues_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/OLS/InfluentialObservation.jl", "max_forks_repo_name": "nilshg/Econometrics", "max_forks_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-03T13:06:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-03T13:06:42.000Z", "avg_line_length": 20.1935483871, "max_line_length": 67, "alphanum_fraction": 0.6405750799, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360932, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7562483399534785}}
{"text": "struct SimpleCurve\n    start::Tuple{Number, Number}\n    stop::Tuple{Number, Number}\n    control::Tuple{Number, Number}\n\n    SimpleCurve(start::Tuple{Number, Number}, stop::Tuple{Number, Number}, control::Tuple{Number, Number}=(start .+ stop) ./ 2) = new(start, stop, control)\nend\n\nfunction getPoint(curve::SimpleCurve, percent::Number)\n    x = (1 - percent)^2 * curve.start[1] + 2 * (1 - percent) * percent * curve.control[1] + percent^2 * curve.stop[1]\n    y = (1 - percent)^2 * curve.start[2] + 2 * (1 - percent) * percent * curve.control[2] + percent^2 * curve.stop[2]\n\n    return x, y\nend", "meta": {"hexsha": "bd19d1d8e5a63ab77ff64a18ad7fd92ad0b54e66", "size": 592, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/shapes/simple_curve.jl", "max_stars_repo_name": "asdfsdfadfasfasd/Ahorn", "max_stars_repo_head_hexsha": "cfac90bd925647727d8517063e826ea603d5f1f0", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/shapes/simple_curve.jl", "max_issues_repo_name": "asdfsdfadfasfasd/Ahorn", "max_issues_repo_head_hexsha": "cfac90bd925647727d8517063e826ea603d5f1f0", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/shapes/simple_curve.jl", "max_forks_repo_name": "asdfsdfadfasfasd/Ahorn", "max_forks_repo_head_hexsha": "cfac90bd925647727d8517063e826ea603d5f1f0", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2857142857, "max_line_length": 155, "alphanum_fraction": 0.652027027, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633823, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7562483332777069}}
{"text": "###\n#   Simple implmentation of the Metropolis Hasting algorithm in julia\n#\n#            Institute for Risk and Uncertainty, Uni of Liverpool\n#\n#                       Authors: Ander Gray, Adolphus Lye\n#\n#                       Email: Ander.Gray@liverpool.ac.uk, \n#                              Adolphus.Lye@liverpool.ac.uk\n#\n#\n#\n#       W. K. Hastings (1970). Monte Carlo sampling methods using \n#       Markov chains and their applications. Biometrika, \n#       57(1), 97-109. doi:10.1093/biomet/57.1.97\n#\n###\n\n###\n#   Add description of function and inputs\n###\n\nfunction MHsample(Target :: Function, Prop, start :: Vector{<:Real}, Nsamples :: Integer, burnin :: Integer = 50, thin ::Integer = 3; islogged :: Bool = true)\n\n    dims = length(start)                                    # Dimensions of input/ prior\n\n    PropRnd = mu -> rand(Prop(mu))                          # Generates a sample from the proposal given mean mu\n\n    chain = zeros( Nsamples * thin + burnin, dims)\n    chain[1,:] = start\n    accRate = 0\n\n    islogged ? evalDen =  x -> exp(Target(x)) : evalDen = x -> Target(x)\n\n    for i = 2:( Nsamples*thin +burnin)    \n\n        next = PropRnd(chain[i-1,:])              # Draw candidate\n        \n        targDen = evalDen(next)                  # Target Density at next sample\n        targPrevious = evalDen(chain[i-1,:])     # Target Density at current sample\n\n        propDen = pdf(Prop(chain[i-1,:]), next)         # Proposal at next centred at current\n        propPrevious = pdf(Prop(next), chain[i-1,:])    # Propsoal at current centred at next\n\n\n        α = targDen/targPrevious * propPrevious/propDen     # General formula for acceptance probability\n\n        accepted = α >= rand()      \n\n        if accepted\n            chain[i,:] = next\n            accRate = accRate +1\n        else\n            chain[i,:] = chain[i-1, :]\n        end\n\n    end\n    accRate = accRate/(Nsamples*thin+burnin)\n    return chain[burnin+1:thin:end,:], accRate\nend\n\n##\n#   Symetric proposal and logged target\n##\nfunction MHsampleSimple(Target :: Function, PropRnd, start :: Vector{<:Real}, Nsamples :: Integer, burnin :: Integer = 50, thin ::Integer = 3)\n\n    dims = length(start)                                    # Dimensions of input/ prior\n    chain = zeros( Nsamples * thin + burnin, dims)\n    chain[1,:] = start[:]\n    accRate = 0\n\n    for i = 2:( Nsamples*thin+burnin)    \n\n        next = PropRnd(chain[i-1,:])                 # Draw candidate\n        \n        targDen = Target(next)[1]                    # Target Density at next sample\n        targPrevious = Target(chain[i-1,:])[1]       # Target Density at current sample\n\n        α =  min(0, targDen - targPrevious)\n\n        accepted = α >= log(rand())\n\n        if accepted\n            chain[i,:] = next\n            accRate = accRate +1\n        else\n            chain[i,:] = chain[i-1, :]\n        end\n\n    end\n    accRate = accRate/(Nsamples*thin+burnin)\n    return chain[burnin+1:thin:end,:], accRate\nend\n", "meta": {"hexsha": "8ea79c595f30a2f479491d32f14e44ed7627bf27", "size": 2970, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mcmc.jl", "max_stars_repo_name": "tokamaster/TransitionalMCMC.jl", "max_stars_repo_head_hexsha": "3671e4da535499f959747d36b9e59b6f27f1e188", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mcmc.jl", "max_issues_repo_name": "tokamaster/TransitionalMCMC.jl", "max_issues_repo_head_hexsha": "3671e4da535499f959747d36b9e59b6f27f1e188", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mcmc.jl", "max_forks_repo_name": "tokamaster/TransitionalMCMC.jl", "max_forks_repo_head_hexsha": "3671e4da535499f959747d36b9e59b6f27f1e188", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5957446809, "max_line_length": 158, "alphanum_fraction": 0.5518518519, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7562270113833868}}
{"text": "export Beta\n\nimport Distributions: Beta, params\nimport SpecialFunctions: digamma\n\nvague(::Type{ <: Beta }) = Beta(1.0, 1.0)\n\nprod_analytical_rule(::Type{ <: Beta }, ::Type{ <: Beta }) = ProdAnalyticalRuleAvailable()\n\nfunction prod(::ProdAnalytical, left::Beta, right::Beta)\n    left_a, left_b   = params(left)\n    right_a, right_b = params(right)\n    T                = promote_type(eltype(left), eltype(right))\n    return Beta(left_a + right_a - one(T), left_b + right_b - one(T))\nend\n\nfunction logmean(dist::Beta) \n    a, b = params(dist)\n    return digamma(a) - digamma(a + b)\nend\n\nfunction mirroredlogmean(dist::Beta)\n    a, b = params(dist)\n    return digamma(b) - digamma(a + b)\nend", "meta": {"hexsha": "a583147f73b588a200bab83c80b4c2e9cca5cb87", "size": 688, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distributions/beta.jl", "max_stars_repo_name": "albertpod/ReactiveMP.jl", "max_stars_repo_head_hexsha": "71c390e6b41e6890ba808640d0bf3ef2f66efc71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2021-03-28T13:18:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:52:52.000Z", "max_issues_repo_path": "src/distributions/beta.jl", "max_issues_repo_name": "albertpod/ReactiveMP.jl", "max_issues_repo_head_hexsha": "71c390e6b41e6890ba808640d0bf3ef2f66efc71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 58, "max_issues_repo_issues_event_min_datetime": "2021-03-17T16:07:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T08:50:44.000Z", "max_forks_repo_path": "src/distributions/beta.jl", "max_forks_repo_name": "albertpod/ReactiveMP.jl", "max_forks_repo_head_hexsha": "71c390e6b41e6890ba808640d0bf3ef2f66efc71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-07-12T18:48:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T17:19:20.000Z", "avg_line_length": 27.52, "max_line_length": 90, "alphanum_fraction": 0.6584302326, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620585273154, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7562264710875728}}
{"text": "export getAnalyticalConstGrad2D,getAnalyticalConstGrad3D,getAnalyticalConstGradInv2D,getAnalyticalConstGradInv3D,getSmoothGaussianMedium,getSmoothFactoredModel,getSmoothFactoredModel3D\n\nfunction getAnalyticalConstGrad2D(n::Array{Int64,1},h::Array{Float64,1})\nsrc = [1,div(n[2],2)];\n\nsource1 = (src[1]-1)*h[1];\nsource2 = (src[2]-1)*h[2];\n\n(X1,X2) = ndgrid((0:(n[1]-1))*h[1],(0:(n[2]-1))*h[2]);\n\na  = -0.4;\ns0 = 2.0;\n\nkappaSquared = s0^2 .+ 2.0*a*(X1.-source1);\n\n# matshow(kappaSquared); colorbar();\nSBarSquared = s0^2 .+ a*(X1.-source1);\nrSquared = ((X1.-source1).^2 .+ (X2.-source2).^2);\nsigmaSquarred = 2*rSquared./(SBarSquared + sqrt.(SBarSquared.^2 .- (a^2).*rSquared));\nsigma = sqrt.(sigmaSquarred);\nT_exact =  SBarSquared.*sigma .- (a^2).*(sigma.^3)./6; \n\nreturn kappaSquared,src,T_exact;\nend\n\nfunction getAnalyticalConstGrad3D(n::Array{Int64,1},h::Array{Float64,1})\nsrc = [div(n[1],2),div(n[2],2),1];\n\nsource1 = (src[1]-1)*h[1];\nsource2 = (src[2]-1)*h[2];\nsource3 = (src[3]-1)*h[3];\n\n(X1,X2,X3) = ndgrid((0:(n[1]-1))*h[1],(0:(n[2]-1))*h[2],(0:(n[3]-1))*h[3]);\n\n# a  = -1.75;\na  = -1.65;\ns0 = 2.0;\n\nkappaSquared = s0^2 .+ 2*a*(X3.-source3);\nSBarSquared = s0^2 .+ a*(X3.-source3);\nrSquared = (X1.-source1).^2 .+ (X2.-source2).^2 .+ (X3.-source3).^2;\nsigmaSquarred = 2*rSquared./(SBarSquared .+ sqrt.(SBarSquared.^2 .- (a^2).*rSquared));\nsigma = sqrt.(sigmaSquarred);\nT_exact =  SBarSquared.*sigma .- (a^2).*(sigma.^3)./6; \n\nreturn kappaSquared,src,T_exact;\nend\n\n\nfunction getAnalyticalConstGradInv2D(n::Array{Int64,1},h::Array{Float64,1})\n\nsrc = [1,div(n[2],2)];\n\nsource1 = (src[1]-1)*h[1];\nsource2 = (src[2]-1)*h[2];\n\n(X1,X2) = ndgrid((0:(n[1]-1))*h[1],(0:(n[2]-1))*h[2]);\n\na  = 1.0;\nainv = (1.0./a);\ns0 = 2.0;\n\nKappa = 1.0./(1.0./s0 .+ a*(X1.-source1));\nT_exact = ainv*acosh.(1.0.+(0.5*s0*a*a).*Kappa.*((X1.-source1).^2 .+ (X2.-source2).^2));\nG2_exact = ainv*(1.0./sqrt.((1.0.+(0.5*s0*a*a).*Kappa.*((X1.-source1).^2 .+ (X2 .- source2).^2)).^2 .- 1)).*(0.5*s0*a*a).*Kappa.*2.0.*(X2.-source2);\nG1_exact = ainv*(1.0./sqrt.((1.0.+(0.5*s0*a*a).*Kappa.*((X1.-source1).^2 .+ (X2 .- source2).^2)).^2 .- 1)).*((0.5*s0*a*a).*Kappa.*2.0.*(X1.-source1) \n\t\t\t+ (0.5*s0*a*a).*((X1.-source1).^2 + (X2.-source2).^2).*(-(Kappa.^2)).*a);\nkappaSquared = Kappa.^2;\n\nreturn kappaSquared,src,T_exact;\n\nend\n\n\nfunction getAnalyticalConstGradInv3D(n::Array{Int64,1},h::Array{Float64,1})\n\nsrc = [div(n[1],2),div(n[1],2),1];\n\nsource1 = (src[1]-1)*h[1];\nsource2 = (src[2]-1)*h[2];\nsource3 = (src[3]-1)*h[3];\n\n(X1,X2,X3) = ndgrid((0:(n[1]-1))*h[1],(0:(n[2]-1))*h[2],(0:(n[3]-1))*h[3]);\n\na  = 1.0;\nainv = (1.0./a);\ns0 = 2.0;\nKappa = 1.0./(1.0./s0 .+ a*(X3.-source3));\nRsquared = (X1.-source1).^2 .+ (X2.-source2).^2 .+ (X3.-source3).^2;\nT_exact = ainv*acosh.(1.0.+(0.5*s0*a*a).*Kappa.*(Rsquared));\nG1_exact = ainv*(1.0./sqrt.((1.0.+(0.5*s0*a*a).*Kappa.*Rsquared).^2 .- 1.0)).*(0.5*s0*a*a).*Kappa.*2.0.*(X1.-source1);\nG2_exact = ainv*(1.0./sqrt.((1.0.+(0.5*s0*a*a).*Kappa.*Rsquared).^2 .- 1.0)).*(0.5*s0*a*a).*Kappa.*2.0.*(X2.-source2);\nG3_exact = ainv*(1.0./sqrt.((1.0.+(0.5*s0*a*a).*Kappa.*Rsquared).^2 .- 1.0)).*((0.5*s0*a*a).*Kappa.*2.0.*(X3.-source3) \n\t\t\t.+ (0.5*s0*a*a).*(Rsquared).*(-(Kappa.^2)).*a);\nkappaSquared = Kappa.^2;\n\nreturn kappaSquared,src,T_exact;\n\nend\n\n\nfunction getSmoothGaussianMedium(n::Array{Int64,1},h::Array{Float64,1})\nsrc = div.(n,4);\nkappaSquared = [];\nT_exact = [];\nif length(n)==2\n\t(T1_exact,G11_exact,G12_exact) = getSmoothFactoredModel(n,h);\n\t(T0,G01,G02,L0) = getAnalytic2DeikonalSolutionAll(n,h,src);\n\tG1_exact = T0.*G11_exact + G01.*T1_exact;\n\tG2_exact = T0.*G12_exact + G02.*T1_exact;\n\tkappaSquared = G1_exact.*G1_exact + G2_exact.*G2_exact;\n\t# matshow(sqrt(kappaSquared)); colorbar();\n\t# xlabel(\"y\");\n\t# ylabel(\"x\");\n\t# xticks(0:div(n[2],8):n[2],0:1:8);\n\t# yticks(0:div(n[1],4):n[1],0:1:4);\n\n\t#figure()\n\t#CS = contour(kappaSquared,50);colorbar();title(\"kappaSquared\");\n\t#clabel(CS, inline=1, fontsize=10)\n\t#figure()\n\t#contour(G1_exact);colorbar();title(\"G1_exact\");\n\tT_exact = T0.*T1_exact;\n\t#figure()\n\t#contour(T_exact,100);colorbar();title(\"T exact\");\n\n\nelse\n\n\t(T1_exact,G11_exact,G12_exact,G13_exact) = getSmoothFactoredModel3D(n,h);\n\n\t(T0,G01,G02,G03) = getAnalytic3DeikonalSolutionAll(n,h,src);\n\n\tG1_exact = T0.*G11_exact + G01.*T1_exact;\n\tG2_exact = T0.*G12_exact + G02.*T1_exact;\n\tG3_exact = T0.*G13_exact + G03.*T1_exact;\n\tkappaSquared = G1_exact.*G1_exact + G2_exact.*G2_exact + G3_exact.*G3_exact;\n\n\t# Er = kappaSquared;\n\t# for k=1:n[3]\n\t\t# matshow(reshape(Er[:,:,k],n[1],n[2]));colorbar();title(\"kappaSQ\");\n\t# end\n\n\tT_exact = T0.*T1_exact;\n\t\nend\n\nreturn kappaSquared,src,T_exact;\nend\n\nfunction getSmoothFactoredModel(n::Array{Int64,1},h::Array{Float64,1})\nxsrc = zeros(2);\nsrc_kappa = zeros(Int64,2);\nsrc_kappa[1] = div(n[1],3);\nsrc_kappa[2] = div(n[2],4);\n\nxsrc[1] = (src_kappa[1]-1)*h[1];\nxsrc[2] = (src_kappa[2]-1)*h[2];\n\nX1,X2 = ndgrid((0:(n[1]-1))*h[1],(0:(n[2]-1))*h[2]);\n\nsigma = 0.1;\nT1_exact = (exp.( - (sigma*((X1 .- xsrc[1]).^2) + 4*sigma*((X2.-xsrc[2]).^2))) .+ 1)/2;\nG11_exact = -2*sigma*(X1 .- xsrc[1]).*exp.( - (sigma*((X1 .- xsrc[1]).^2) + 4*sigma*((X2.-xsrc[2]).^2)))/2;\nG12_exact = -8*sigma*(X2 .- xsrc[2]).*exp.( - (sigma*((X1 .- xsrc[1]).^2) + 4*sigma*((X2.-xsrc[2]).^2)))/2;\n\nreturn T1_exact,G11_exact,G12_exact;\nend\n\nfunction getSmoothFactoredModel3D(n::Array{Int64,1},h::Array{Float64,1})\nxsrc = zeros(3);\nsrc_kappa = zeros(Int64,3);\nsrc_kappa[1] = div(n[1],3);\nsrc_kappa[2] = div(n[2],4);\nsrc_kappa[3] = div(n[3],2);\n\nxsrc[1] = (src_kappa[1]-1)*h[1];\nxsrc[2] = (src_kappa[2]-1)*h[2];\nxsrc[3] = (src_kappa[3]-1)*h[3];\n\nX1,X2,X3 = ndgrid((0:(n[1]-1))*h[1],(0:(n[2]-1))*h[2],(0:(n[3]-1))*h[3]);\n\nSigma = [0.1,0.4,0.2];\nEXPRSkewedSquared = exp.(-Sigma[1]*((X1 .- xsrc[1]).^2) .- Sigma[2]*((X2.-xsrc[2]).^2) .- Sigma[3]*((X3.-xsrc[3]).^2));\n\nT1_exact = EXPRSkewedSquared/2.0 .+ 0.5;\nG11_exact = -Sigma[1]*(X1 .- xsrc[1]).*EXPRSkewedSquared;\nG12_exact = -Sigma[2]*(X2 .- xsrc[2]).*EXPRSkewedSquared;\nG13_exact = -Sigma[3]*(X3 .- xsrc[3]).*EXPRSkewedSquared;\n\nreturn T1_exact,G11_exact,G12_exact,G13_exact;\nend\n", "meta": {"hexsha": "13b4b8853e7cded05ee162b6d3ac55f5003f198d", "size": 6051, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/getAnalyticalMediums.jl", "max_stars_repo_name": "JuliaInv/FactoredEikonalFastMarching.jl", "max_stars_repo_head_hexsha": "421e451c206cd11ff95806ac675baa7e705a0e95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-11-27T20:13:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T19:07:16.000Z", "max_issues_repo_path": "src/getAnalyticalMediums.jl", "max_issues_repo_name": "JuliaInv/FactoredEikonalFastMarching.jl", "max_issues_repo_head_hexsha": "421e451c206cd11ff95806ac675baa7e705a0e95", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/getAnalyticalMediums.jl", "max_forks_repo_name": "JuliaInv/FactoredEikonalFastMarching.jl", "max_forks_repo_head_hexsha": "421e451c206cd11ff95806ac675baa7e705a0e95", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-12-03T06:53:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:13:41.000Z", "avg_line_length": 31.3523316062, "max_line_length": 184, "alphanum_fraction": 0.6081639398, "num_tokens": 2729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762055074521, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7562264540286303}}
{"text": "# Miscellaneous functions\n\n\"\"\"\n    logmvgamma(p::Int, a::Real)\n\nReturn the logarithm of [multivariate gamma function](https://en.wikipedia.org/wiki/Multivariate_gamma_function) ([DLMF 35.3.1](https://dlmf.nist.gov/35.3.1)).\n\"\"\"\nfunction logmvgamma(p::Int, a::Real)\n    # NOTE: one(a) factors are here to prevent unnecessary promotion of Float32\n    res = p * (p - 1) * log(pi * one(a)) / 4\n    for ii in 1:p\n        res += lgamma(a + (1 - ii) * one(a)/ 2)\n    end\n    return res\nend\n\n\"\"\"\n    lstirling_asym(x)\n\nThe remainder term after\n[Stirling's approximation](https://en.wikipedia.org/wiki/Stirling%27s_approximation)\nto [`lgamma`](@ref):\n\n```math\n\\\\log \\\\Gamma(x) \\\\approx x \\\\log(x) - x + \\\\log(2\\\\pi/x)/2 = \\\\log(x)*(x-1/2) + \\\\log(2\\\\pi)/2 - x\n```\n\nIn Julia syntax, this means:\n\n    lstirling_asym(x) = lgamma(x) + x - (x-0.5)*log(x) - 0.5*log(2π)\n\nFor sufficiently large `x`, this can be approximated using the asymptotic\n_Stirling's series_ ([DLMF 5.11.1](https://dlmf.nist.gov/5.11.1)):\n\n```math\n\\\\frac{1}{12x} - \\\\frac{1}{360x^3} + \\\\frac{1}{1260x^5} - \\\\frac{1}{1680x^7} + \\\\ldots\n```\n\nThe truncation error is bounded by the first omitted term, and is of the same sign.\n\nRelative error of approximation is bounded by\n    (174611/125400 x^-19) / (1/12 x^-1 - 1/360 x^-3)\nwhich is < 1/2 ulp for x >= 10.0, and total numeric error appears to be < 2 ulps\n\n# References\n\n* Temme, N. (1996) Special functions: An introduction to the classical functions of\n   mathematical physics, Wiley, New York, ISBN: 0-471-11313-1, Chapter 3.6, pp 61-65.\n* Weisstein, Eric W. [\"Stirling's Series.\"](http://mathworld.wolfram.com/StirlingsSeries.html).\n  MathWorld. \n* [OEIS A046968](http://oeis.org/A046968) and [OEIS A046969](http://oeis.org/A046969)\n  for the series coefficients\n\"\"\"\nfunction lstirling_asym end\n\nlstirling_asym(x::BigFloat) = lgamma(x) + x - log(x)*(x - big(0.5)) - log2π/big(2)\n\nlstirling_asym(x::Integer) = lstirling_asym(float(x))\n\nconst lstirlingF64 = Float64[lstirling_asym(k) for k in big(1):big(64)]\nconst lstirlingF32 = Float64[lstirling_asym(k) for k in big(1):big(40)]\n\nfunction lstirling_asym(x::Float64)\n    isinteger(x) && (0 < x ≤ length(lstirlingF64)) && return lstirlingF64[Int(x)]\n    t = inv(abs2(x))\n    @horner(t,\n             8.33333333333333333e-2, #  1/12 x^-1\n            -2.77777777777777778e-3, # -1/360 x^-3\n             7.93650793650793651e-4, #  1/1260 x^-5\n            -5.95238095238095238e-4, # -1/1680 x^-7\n             8.41750841750841751e-4, #  1/1188 x^-9\n            -1.91752691752691753e-3, # -691/360360 x^-11\n             6.41025641025641026e-3, #  1/156 x^-13\n            -2.95506535947712418e-2, # -3617/122400 x^-15\n             1.79644372368830573e-1)/x #  43867/244188 x^-17\nend\n\nfunction lstirling_asym(x::Float32)\n    isinteger(x) && (0 < x ≤ length(lstirlingF32)) && return lstirlingF32[Int(x)]\n    t = inv(abs2(x))\n    @horner(t,\n             8.333333333333f-2, #  1/12 x^-1\n            -2.777777777777f-3, # -1/360 x^-3\n             7.936507936508f-4, #  1/1260 x^-5\n            -5.952380952381f-4, # -1/1680 x^-7\n             8.417508417508f-4)/x #  1/1188 x^-9\nend\n", "meta": {"hexsha": "217784357f52ea33eaef122e77924463e1a5d3f1", "size": 3127, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/misc.jl", "max_stars_repo_name": "nilshg/StatsFuns.jl", "max_stars_repo_head_hexsha": "bca4582b2c788b65d3a51e52ab339794c58ea9f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/misc.jl", "max_issues_repo_name": "nilshg/StatsFuns.jl", "max_issues_repo_head_hexsha": "bca4582b2c788b65d3a51e52ab339794c58ea9f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/misc.jl", "max_forks_repo_name": "nilshg/StatsFuns.jl", "max_forks_repo_head_hexsha": "bca4582b2c788b65d3a51e52ab339794c58ea9f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5340909091, "max_line_length": 159, "alphanum_fraction": 0.6290374161, "num_tokens": 1157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7562054646885198}}
{"text": "__precompile__()\n\n\"\"\"\nMulti-dimensional integration routines: Monte-Carlo, stratified Monte-Carlo,\nmulti-armed bandit UCB.\n\nSee the \n[README file](https://github.com/florianLepretre/ucbature/blob/master/README.md)\nfor documentation.   \n\"\"\"\n\nmodule ucbature\n\nexport mc, str, ucb\n\nrand_min_max(xmin, xmax) = xmin .+ rand(length(xmin)).*(xmax.-xmin)\n\nvolume(xmin, xmax) = prod(xmax .- xmin)\n\n\"\"\"\n    mc(f, xmin, xmax, nb_evals)\n\nCompute the n-dimensional integral f(x), where \n`n == length(xmin) == length(xmax)`, over the hypercube whose corners are given\nby the vectors (or tuples) `xmin` and `xmax`. `f` should be a function `f(x)` \nthat takes an n-dimensional vector `x` and returns the integrand at `x`. \n\nUse the classic Monte-Carlo integration method using `nb_evals` samples.\n\"\"\"\nfunction mc(integrand, xmin, xmax, nb_evals)\n    f_val(i) = integrand(rand_min_max(xmin, xmax))\n    mean_val = mapreduce(f_val, +, 1:nb_evals) / nb_evals\n    volume(xmin, xmax) * mean_val\nend\n\nfunction make_x_cube(i_zone, nb_zones_per_dim, dim)\n    # compute position i_zone in [0, nb_zones_per_dim]^dim\n    x_cube = Array{Int}(dim)\n    q = nb_zones_per_dim^(dim-1)\n    for d = 1:dim\n        x_cube[d] = div(i_zone, q)\n        i_zone -= x_cube[d] * q\n        q = div(q, nb_zones_per_dim)\n    end\n    x_cube\nend\n\nfunction make_zones(xmin, xmax, nb_zones_per_dim)\n    dim = length(xmin)\n    nb_zones = nb_zones_per_dim ^ dim\n    xstep = (xmax .- xmin) / nb_zones_per_dim\n    zones = [xmin .+ xstep.*make_x_cube(i, nb_zones_per_dim, dim) \n             for i = 0:(nb_zones-1)]\n    dim, nb_zones, xstep, zones\nend\n\n\"\"\"\n    str(f, xmin, xmax, nb_evals, nb_zones_per_dim=3)\n\nCompute the n-dimensional integral f(x), where \n`n == length(xmin) == length(xmax)`, over the hypercube whose corners are given\nby the vectors (or tuples) `xmin` and `xmax`. `f` should be a function `f(x)` \nthat takes an n-dimensional vector `x` and returns the integrand at `x`. \n\nUse the stratified monte-carlo integration method using `nb_evals` samples and\n`nb_zones_per_dim` uniform strata in each dimension.\n\"\"\"\nfunction str(integrand, xmin, xmax, nb_evals, nb_zones_per_dim=3)\n    dim, nb_zones, xstep, zones = make_zones(xmin, xmax, nb_zones_per_dim)\n    if nb_evals < nb_zones\n        warn(\"Integrator.str, nb_evals < $(nb_zones)\")\n        return mc(integrand, xmin, xmax, nb_evals)\n    end\n    nb_evals_per_zone = div(nb_evals, nb_zones)\n    f_mc(z) = mc(integrand, z, z.+xstep, nb_evals_per_zone)\n    mapreduce(f_mc, +, zones)\nend\n\nucb1(R, k, kn, Vn) = Vn ./ sqrt.(kn) .+ R .* sqrt.(log(k) ./ kn)\n\nucb_vars(s1, s2, k) = (s2./k) .- (s1./k).^2\n\nfunction ucb_strat(integrand, xstep, zones, nb_init_evals_per_zone)\n    nb_zones = length(zones)\n    zones_sum1 = zeros(nb_zones)\n    zones_sum2 = zeros(nb_zones)\n    for (n, zmin) = enumerate(zones)\n        zmax = zmin .+ xstep\n        for _ = 1:nb_init_evals_per_zone\n            y = integrand(rand_min_max(zmin, zmax))\n            zones_sum1[n] += y\n            zones_sum2[n] += y^2\n        end\n    end\n    zones_evals = fill(nb_init_evals_per_zone, nb_zones)\n    zones_sum1, zones_sum2, zones_evals\nend\n\nfunction ucb_mab(integrand, nb_init_evals, nb_evals, k_exploration, zones, \n                 xstep, zones_sum1, zones_sum2, zones_evals, zones_vars)\n    for k=nb_init_evals:nb_evals\n        scores = ucb1(k_exploration, k, zones_evals, zones_vars)\n        n = indmax(scores)\n        zmin = zones[n]\n        zmax = zmin .+ xstep\n        y = integrand(rand_min_max(zmin, zmax))\n        zones_sum1[n] += y\n        zones_sum2[n] += y^2\n        zones_evals[n] += 1\n        zones_vars[n] = ucb_vars(zones_sum1[n], zones_sum2[n], zones_evals[n])\n    end\n    zones_sum1, zones_evals\nend\n\n\"\"\"\n    ucb(integrand, xmin, xmax, nb_evals, nb_zones_per_dim=3, k_exploration=0.01, nb_init_evals_per_zone=10)\n\nCompute the n-dimensional integral f(x), where \n`n == length(xmin) == length(xmax)`, over the hypercube whose corners are given\nby the vectors (or tuples) `xmin` and `xmax`. `f` should be a function `f(x)` \nthat takes an n-dimensional vector `x` and returns the integrand at `x`. \n\nUse the multi-armed bandit UCB method using `nb_evals` samples,\n`nb_zones_per_dim` uniform strata in each dimension, `nb_init_evals_per_zone` \ninitial samples in each stratum and an exploration coefficient `k_exploration`.\n\"\"\"\nfunction ucb(integrand, xmin, xmax, nb_evals, nb_zones_per_dim=3, \n             k_exploration=0.01, nb_init_evals_per_zone=10)\n    # init\n    dim, nb_zones, xstep, zones = make_zones(xmin, xmax, nb_zones_per_dim)\n    nb_init_evals = nb_zones * nb_init_evals_per_zone\n    if nb_evals < nb_init_evals\n        warn(\"nb_evals < $(nb_init_evals)\")\n        return mc(integrand, xmin, xmax, nb_evals)\n    end\n    # stratified sampling\n    zones_sum1, zones_sum2, zones_evals = ucb_strat(integrand, xstep, zones, \n                                                    nb_init_evals_per_zone)\n    zones_vars = ucb_vars(zones_sum1, zones_sum2, zones_evals)\n    # multi-armed bandit\n    zones_sum1, zones_evals = \n    ucb_mab(integrand, nb_init_evals, nb_evals, k_exploration, zones, \n            xstep, zones_sum1, zones_sum2, zones_evals, zones_vars)\n    # final result\n    prod(xstep) * sum(zones_sum1 ./ zones_evals)\nend\n\nend # module ucbature\n\n", "meta": {"hexsha": "322877f846db8c8e65f298c6b77ee0faf89401d5", "size": 5252, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ucbature.jl", "max_stars_repo_name": "florianLepretre/ucbature", "max_stars_repo_head_hexsha": "eff33b92022aca6d36c817a1490af92befda2503", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-09T09:16:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-09T09:16:01.000Z", "max_issues_repo_path": "src/ucbature.jl", "max_issues_repo_name": "florianLepretre/ucbature", "max_issues_repo_head_hexsha": "eff33b92022aca6d36c817a1490af92befda2503", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ucbature.jl", "max_forks_repo_name": "florianLepretre/ucbature", "max_forks_repo_head_hexsha": "eff33b92022aca6d36c817a1490af92befda2503", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-10-19T06:36:10.000Z", "max_forks_repo_forks_event_max_datetime": "2017-10-19T06:36:10.000Z", "avg_line_length": 35.0133333333, "max_line_length": 107, "alphanum_fraction": 0.6784082254, "num_tokens": 1607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7562054592707238}}
{"text": "\n#\n# Conjugate gradient\n#\n# This is an independent implementation of:\n#   W. W. Hager and H. Zhang (2006) Algorithm 851: CG_DESCENT, a\n#     conjugate gradient method with guaranteed descent. ACM\n#     Transactions on Mathematical Software 32: 113–137.\n#\n# Code comments such as \"HZ, stage X\" or \"HZ, eqs Y\" are with\n# reference to a particular point in this paper.\n#\n# Several aspects of the following have also been incorporated:\n#   W. W. Hager and H. Zhang (2012) The limited memory conjugate\n#     gradient method.\n#\n# This paper will be denoted HZ2012 below.\n#\n# There are some modifications and/or extensions from what's in the\n# paper (these may or may not be extensions of the cg_descent code\n# that can be downloaded from Hager's site; his code has undergone\n# numerous revisions since publication of the paper):\n#\n# cgdescent: the termination condition employs a \"unit-correct\"\n#   expression rather than a condition on gradient\n#   components---whether this is a good or bad idea will require\n#   additional experience, but preliminary evidence seems to suggest\n#   that it makes \"reasonable\" choices over a wider range of problem\n#   types.\n#\n# linesearch: the Wolfe conditions are checked only after alpha is\n#   generated either by quadratic interpolation or secant\n#   interpolation, not when alpha is generated by bisection or\n#   expansion. This increases the likelihood that alpha will be a\n#   good approximation of the minimum.\n#\n# linesearch: In step I2, we multiply by psi2 only if the convexity\n#   test failed, not if the function-value test failed. This\n#   prevents one from going uphill further when you already know\n#   you're already higher than the point at alpha=0.\n#\n# both: checks for Inf/NaN function values\n#\n# both: support maximum value of alpha (equivalently, c). This\n#   facilitates using these routines for constrained minimization\n#   when you can calculate the distance along the path to the\n#   disallowed region. (When you can't easily calculate that\n#   distance, it can still be handled by returning Inf/NaN for\n#   exterior points. It's just more efficient if you know the\n#   maximum, because you don't have to test values that won't\n#   work.) The maximum should be specified as the largest value for\n#   which a finite value will be returned.  See, e.g., limits_box\n#   below.  The default value for alphamax is Inf. See alphamaxfunc\n#   for cgdescent and alphamax for linesearch_hz.\n\nmacro cgtrace()\n    quote\n        if tracing\n            dt = Dict()\n            if o.extended_trace\n                dt[\"x\"] = copy(x)\n                dt[\"g(x)\"] = copy(g)\n                dt[\"Current step size\"] = alpha\n            end\n            g_norm = vecnorm(g, Inf)\n            update!(tr,\n                    iteration,\n                    f_x,\n                    g_norm,\n                    dt,\n                    o.store_trace,\n                    o.show_trace,\n                    o.show_every,\n                    o.callback)\n        end\n    end\nend\n\nimmutable ConjugateGradient{T} <: Optimizer\n    eta::Float64\n    P::T\n    precondprep!::Function\n    linesearch!::Function\nend\n\nfunction ConjugateGradient(;\n                           linesearch!::Function = hz_linesearch!,\n                           eta::Real = 0.4,\n                           P::Any = nothing,\n                           precondprep! = (P, x) -> nothing)\n    ConjugateGradient{typeof(P)}(Float64(eta),\n                                 P, precondprep!,\n                                 linesearch!)\nend\n\nfunction optimize{T}(df::DifferentiableFunction,\n                     initial_x::Array{T},\n                     mo::ConjugateGradient,\n                     o::OptimizationOptions)\n    # Print header if show_trace is set\n    print_header(o)\n\n    # Maintain current state in x and previous state in x_previous\n    x, x_previous = copy(initial_x), copy(initial_x)\n\n    # Count the total number of iterations\n    iteration = 0\n\n    # Track calls to function and gradient\n    f_calls, g_calls = 0, 0\n\n    # Count number of parameters\n    n = length(x)\n\n    # Maintain current gradient in g and previous gradient in g_previous\n    g, g_previous = similar(x), similar(x)\n\n    # Maintain the preconditioned gradient in pg\n    pg = similar(x)\n\n    # The current search direction\n    s = similar(x)\n\n    # Buffers for use in line search\n    x_ls, g_ls = similar(x), similar(x)\n\n    # Intermediate value in CG calculation\n    y = similar(x)\n    py = similar(x)\n\n    # Store f(x) in f_x\n    f_x = df.fg!(x, g)\n    @assert typeof(f_x) == T\n    f_x_previous = convert(T, NaN)\n    f_calls, g_calls = f_calls + 1, g_calls + 1\n    copy!(g_previous, g)\n\n    # Keep track of step-sizes\n    alpha = alphainit(one(T), x, g, f_x)\n\n    # TODO: How should this flag be set?\n    mayterminate = false\n\n    # Maintain a cache for line search results\n    lsr = LineSearchResults(T)\n\n    # Trace the history of states visited\n    tr = OptimizationTrace{typeof(mo)}()\n    tracing = o.store_trace || o.show_trace || o.extended_trace || o.callback != nothing\n    @cgtrace\n\n    # Output messages\n    if !isfinite(f_x)\n        error(\"Must have finite starting value\")\n    end\n    if !all(isfinite(g))\n        @show g\n        @show find(!isfinite(g))\n        error(\"Gradient must have all finite values at starting point\")\n    end\n\n    # Determine the intial search direction\n    #    if we don't precondition, then this is an extra superfluous copy\n    #    TODO: consider allowing a reference for pg instead of a copy\n    mo.precondprep!(mo.P, x)\n    A_ldiv_B!(pg, mo.P, g)\n    scale!(copy!(s, pg), -1)\n\n    # Assess multiple types of convergence\n    x_converged, f_converged = false, false\n    g_converged = vecnorm(g, Inf) < o.g_tol\n\n    # Iterate until convergence\n    converged = g_converged\n    while !converged && iteration < o.iterations\n        # Increment the number of steps we've had to perform\n        iteration += 1\n\n        # Reset the search direction if it becomes corrupted\n        dphi0 = vecdot(g, s)\n        if dphi0 >= 0\n            @simd for i in 1:n\n                @inbounds s[i] = -pg[i]\n            end\n            dphi0 = vecdot(g, s)\n            if dphi0 >= 0\n                break\n            end\n        end\n\n        # Refresh the line search cache\n        clear!(lsr)\n        @assert typeof(f_x) == T\n        @assert typeof(dphi0) == T\n        push!(lsr, zero(T), f_x, dphi0)\n\n        # Pick the initial step size (HZ #I1-I2)\n        alpha, mayterminate, f_update, g_update =\n          alphatry(alpha, df, x, s, x_ls, g_ls, lsr)\n        f_calls, g_calls = f_calls + f_update, g_calls + g_update\n\n        # Determine the distance of movement along the search line\n        alpha, f_update, g_update =\n          mo.linesearch!(df, x, s, x_ls, g_ls, lsr, alpha, mayterminate)\n        f_calls, g_calls = f_calls + f_update, g_calls + g_update\n\n        # Maintain a record of previous position\n        copy!(x_previous, x)\n\n        # Update current position # x = x + alpha * s\n        LinAlg.axpy!(alpha, s, x)\n\n        # Maintain a record of the previous gradient\n        copy!(g_previous, g)\n\n        # Update the function value and gradient\n        f_x_previous, f_x = f_x, df.fg!(x, g)\n        f_calls, g_calls = f_calls + 1, g_calls + 1\n\n        x_converged,\n        f_converged,\n        g_converged,\n        converged = assess_convergence(x,\n                                       x_previous,\n                                       f_x,\n                                       f_x_previous,\n                                       g,\n                                       o.x_tol,\n                                       o.f_tol,\n                                       o.g_tol)\n\n        # Check sanity of function and gradient\n        if !isfinite(f_x)\n            error(\"Function must finite function values\")\n        end\n\n        # Determine the next search direction using HZ's CG rule\n        #  Calculate the beta factor (HZ2012)\n        # -----------------\n        # Comment on py: one could replace the computation of py with\n        #    ydotpgprev = vecdot(y, pg)\n        #    vecdot(y, py)  >>>  vecdot(y, pg) - ydotpgprev\n        # but I am worried about round-off here, so instead we make an\n        # extra copy, which is probably minimal overhead.\n        # -----------------\n        mo.precondprep!(mo.P, x)\n        dPd = dot(s, mo.P, s)\n        etak::T = mo.eta * vecdot(s, g_previous) / dPd\n        @simd for i in 1:n\n            @inbounds y[i] = g[i] - g_previous[i]\n        end\n        ydots = vecdot(y, s)\n        copy!(py, pg)        # below, store pg - pg_previous in py\n        A_ldiv_B!(pg, mo.P, g)\n        @simd for i in 1:n     # py = pg - py\n           @inbounds py[i] = pg[i] - py[i]\n        end\n        betak = (vecdot(y, pg) - vecdot(y, py) * vecdot(g, s) / ydots) / ydots\n        beta = max(betak, etak)\n        @simd for i in 1:n\n            @inbounds s[i] = beta * s[i] - pg[i]\n        end\n\n        @cgtrace\n    end\n\n    return MultivariateOptimizationResults(\"Conjugate Gradient\",\n                                           initial_x,\n                                           x,\n                                           Float64(f_x),\n                                           iteration,\n                                           iteration == o.iterations,\n                                           x_converged,\n                                           o.x_tol,\n                                           f_converged,\n                                           o.f_tol,\n                                           g_converged,\n                                           o.g_tol,\n                                           tr,\n                                           f_calls,\n                                           g_calls)\nend\n", "meta": {"hexsha": "270b84662d871888dbe95b0087a3e7c080292bc5", "size": 9797, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cg.jl", "max_stars_repo_name": "JuliaPackageMirrors/Optim.jl", "max_stars_repo_head_hexsha": "f0f5c185b762a398060e0e56e16faac227b82472", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cg.jl", "max_issues_repo_name": "JuliaPackageMirrors/Optim.jl", "max_issues_repo_head_hexsha": "f0f5c185b762a398060e0e56e16faac227b82472", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cg.jl", "max_forks_repo_name": "JuliaPackageMirrors/Optim.jl", "max_forks_repo_head_hexsha": "f0f5c185b762a398060e0e56e16faac227b82472", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6183745583, "max_line_length": 88, "alphanum_fraction": 0.5548637338, "num_tokens": 2344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.756205455285811}}
{"text": "import StatsBase: sample\n\n# Model selection\n\n# Taken from https://royalsocietypublishing.org/doi/pdf/10.1098/rspa.2017.0009\n\"\"\"\n\tAIC(k, X, Y; likelyhood = (X, Y) = sum(abs2, X-Y))\n\nComputes the Akaike Information Criterion (AIC) given the free parameters `k` for the data `X` and its\nestimate `Y` of the model. `likelyhood` can be any function of `X` and `Y`.\n\"\"\"\nfunction AIC(k::Int64, X::AbstractArray, Y::AbstractArray; likelyhood = (X,Y) -> sum(abs2, X-Y))\n    @assert size(X) == size(Y) \"Dimensions of trajectories should be equal !\"\n    return 2*k - 2*log(likelyhood(X, Y))\nend\n\n# Taken from https://royalsocietypublishing.org/doi/pdf/10.1098/rspa.2017.0009\n\"\"\"\n\tAICC(k, X, Y; likelyhood = (X, Y) = sum(abs2, X-Y))\n\nComputes the Akaike Information Criterion compensated for finite samples (AICC) given the free parameters `k` for the data `X` and its\nestimate `Y` of the model. `likelyhood` can be any function of `X` and `Y`.\n\"\"\"\nfunction AICC(k::Int64, X::AbstractMatrix, Y::AbstractMatrix; likelyhood = (X,Y) -> sum(abs2, X-Y))\n    @assert size(X) == size(Y) \"Dimensions of trajectories should be equal !\"\n    return AIC(k, X, Y, likelyhood = likelyhood)+ 2*(k+1)*(k+2)/(size(X)[2]-k-2)\nend\n\nfunction AICC(k::Int64, X::AbstractVector, Y::AbstractVector; likelyhood = (X,Y) -> sum(abs2, X-Y))\n    @assert size(X) == size(Y) \"Dimensions of trajectories should be equal !\"\n    return AIC(k, X, Y, likelyhood = likelyhood)+ 2*(k+1)*(k+2)/(length(X)-k-2)\nend\n\n# Double check on that\n# Taken from https://www.immagic.com/eLibrary/ARCHIVES/GENERAL/WIKIPEDI/W120607B.pdf\n\"\"\"\n\tBIC(k, X, Y; likelyhood = (X, Y) = sum(abs2, X-Y))\n\nComputes Bayes Information Criterion (BIC) given the free parameters `k` for the data `X` and its\nestimate `Y` of the model. `likelyhood` can be any function of `X` and `Y`.\n\"\"\"\nfunction BIC(k::Int64, X::AbstractMatrix, Y::AbstractMatrix; likelyhood = (X,Y) -> sum(abs2, X-Y))\n    @assert size(X) == size(Y) \"Dimensions of trajectories should be equal !\"\n    return - 2*log(likelyhood(X, Y)) + k*log(size(X)[2])\nend\n\nfunction BIC(k::Int64, X::AbstractVector, Y::AbstractVector; likelyhood = (X,Y) -> sum(abs2, X-Y))\n    @assert size(X) == size(Y) \"Dimensions of trajectories should be equal !\"\n    return - 2*log(likelyhood(X, Y)) + k*log(length(X))\nend\n\n# Optimal Shrinkage for data in presence of white noise\n# See D. L. Donoho and M. Gavish, \"The Optimal Hard Threshold for Singular\n# Values is 4/sqrt(3)\", http://arxiv.org/abs/1305.5870\n# Code taken from https://github.com/erichson/optht\n\nfunction optimal_svht(m::Int64, n::Int64; known_noise::Bool = false)\n    @assert m/n > 0\n    @assert m/n <= 1\n\n    β = m/n\n    ω = (8*β) / (β+1+sqrt(β^2+14β+1))\n    c = sqrt(2*(β+1)+ω)\n\n    if known_noise\n        return c\n    else\n        median = median_marcenko_pastur(β)\n        return c / sqrt(median)\n    end\nend\n\nfunction marcenko_pastur_density(t, lower, upper, beta)\n    sqrt((upper-t).*(t-lower))./(2π*beta*t)\nend\n\nfunction incremental_marcenko_pastur(x, beta, gamma)\n    @assert beta <= 1\n    upper = (1+sqrt(beta))^2\n    lower = (1-sqrt(beta))^2\n\n    @inline marcenko_pastur(x) = begin\n        if (upper-x)*(x-lower) > 0\n            return marcenko_pastur_density(x, lower, upper, beta)\n        else\n            return zero(eltype(x))\n        end\n    end\n\n    if gamma ≈ zero(eltype(gamma))\n        i, ϵ = quadgk(x->(x^gamma)*marcenko_pastur(x), x, upper)\n        return i\n    else\n        i, ϵ = quadgk(x->marcenko_pastur(x), x, upper)\n        return i\n    end\nend\n\nfunction median_marcenko_pastur(beta)\n    @assert 0 < beta <= 1\n    upper = (1+sqrt(beta))^2\n    lower = (1-sqrt(beta))^2\n    change = true\n    x = ones(eltype(upper), 5)\n    y = similar(x)\n    while change && (upper - lower > 1e-5)\n        x = range(lower, upper, length = 5)\n        for (i,xi) in enumerate(x)\n            y[i] = one(eltype(x)) - incremental_marcenko_pastur(xi, beta, 0)\n        end\n        any(y .< 0.5) ? lower = maximum(x[y .< 0.5]) : change = false\n        any(y .> 0.5) ? upper = minimum(x[y .> 0.5]) : change = false\n    end\n    return (lower+upper)/2\nend\n\n\"\"\"\n\toptimal_shrinkage(X)\n\toptimal_shrinkage!(X)\n\nCompute a feature reduced version of the data array `X` via tresholding the\nsingular values by computing the [optimal threshold for singular values](http://arxiv.org/abs/1305.5870).\n\"\"\"\nfunction optimal_shrinkage(X::AbstractArray{T, 2}) where T <: Number\n    m,n = minimum(size(X)), maximum(size(X))\n    U, S, V = svd(X)\n    τ = optimal_svht(m,n)\n    inds = S .>= τ*median(S)\n    return U[:, inds]*Diagonal(S[inds])*V[:, inds]'\nend\n\nfunction optimal_shrinkage!(X::AbstractArray{T, 2}) where T <: Number\n    m,n = minimum(size(X)), maximum(size(X))\n    U, S, V = svd(X)\n    τ = optimal_svht(m,n)\n    inds = S .>= τ*median(S)\n    X .= U[:, inds]*Diagonal(S[inds])*V[:, inds]'\n    return\nend\n\n\"\"\"\n\tsavitzky_golay(X, windowSize, polyOrder; deriv, dt, crop)\n\nEstimate the time derivative via the savitzky_golay filter. `X` is the data matrix containing the trajectories, which is interpolated\nvia polynomials of order `polyOrder` over `windowSize` points repeatedly. `deriv` defines the order of the derivative, `dt`\nthe timestepsize. `crop` indicates if the original data should be returned cropped along the derivative approximation.\n\"\"\"\nfunction savitzky_golay(x::AbstractVector{T}, windowSize::Integer, polyOrder::Integer; deriv::Integer=0, dt::Real=1.0, crop::Bool = true) where T <: Number\n\t# Polynomial smoothing with the Savitzky Golay filters\n\t# Adapted from: https://github.com/BBN-Q/Qlab.jl/blob/master/src/SavitskyGolay.jl\n\t# More information: https://pdfs.semanticscholar.org/066b/7534921b308925f6616480b4d2d2557943d1.pdf\n\t# Requires LinearAlgebra and DSP modules loaded.\n\n\t# Some error checking\n\t@assert isodd(windowSize) \"Window size must be an odd integer.\"\n\t@assert polyOrder < windowSize \"Polynomial order must be less than window size.\"\n\n\t# Calculate filter coefficients\n\tfilterCoeffs = calculate_filterCoeffs(windowSize, polyOrder, deriv, dt)\n\n\t# Pad the signal with the endpoints and convolve with filter\n\thalfWindow = Int(ceil((windowSize - 1)/2))\n\tpaddedX = [x[1]*ones(halfWindow); x; x[end]*ones(halfWindow)]\n\ty = conv(filterCoeffs[end:-1:1], paddedX)\n\n\tif !crop\n\t\t# Return the valid midsection\n\t\treturn y[2*halfWindow+1:end-2*halfWindow]\n\telse\n\t\t# Return cropped data. Excluding borders, where the estimation is less accurate\n\t\treturn x[halfWindow+2:end-halfWindow-1], y[3*halfWindow+2:end-3*halfWindow-1]\n\tend\nend\n\nfunction savitzky_golay(x::AbstractMatrix{T}, windowSize::Integer, polyOrder::Integer; deriv::Integer=0, dt::Real=1.0, crop::Bool = true) where T <: Number\n\t# Polynomial smoothing with the Savitzky Golay filters\n\t# Adapted from: https://github.com/BBN-Q/Qlab.jl/blob/master/src/SavitskyGolay.jl\n\t# More information: https://pdfs.semanticscholar.org/066b/7534921b308925f6616480b4d2d2557943d1.pdf\n\t# Requires LinearAlgebra and DSP modules loaded.\n\n\t# Some error checking\n\t@assert isodd(windowSize) \"Window size must be an odd integer.\"\n\t@assert polyOrder < windowSize \"Polynomial order must be less than window size.\"\n\n\t# Calculate filter coefficients\n\tfilterCoeffs = calculate_filterCoeffs(windowSize, polyOrder, deriv, dt)\n\n\t# Apply filter to each component\n\thalfWindow = Int(ceil((windowSize - 1)/2))\n\n\tif !crop\n\t\ty = similar(x)\n\t\tfor (i, xi) in enumerate(eachrow(x))\n\t\t\tpaddedX = [xi[1]*ones(halfWindow); xi; xi[end]*ones(halfWindow)]\n\t\t\ty₀ = conv(filterCoeffs[end:-1:1], paddedX)\n\t\t\ty[i,:] = y₀[2*halfWindow+1:end-2*halfWindow]\n\t\tend\n\t\treturn y\n\telse\n\t\tcropped_x = x[:,halfWindow+2:end-halfWindow-1]\n\t\ty = similar(cropped_x)\n\t\tfor (i, xi) in enumerate(eachrow(x))\n\t\t\tpaddedX = [xi[1]*ones(halfWindow); xi; xi[end]*ones(halfWindow)]\n\t\t\ty₀ = conv(filterCoeffs[end:-1:1], paddedX)\n\t\t\ty[i,:] = y₀[3*halfWindow+2:end-3*halfWindow-1]\n\t\tend\n\t\treturn cropped_x, y\n\tend\nend\n\nfunction calculate_filterCoeffs(windowSize::Integer, polyOrder::Integer, deriv::Integer, dt::Real)\n\t# Some error checking\n\t@assert isodd(windowSize) \"Window size must be an odd integer.\"\n\t@assert polyOrder < windowSize \"Polynomial order must be less than window size.\"\n\n\t# Form the design matrix A\n\thalfWindow = Int(ceil((windowSize - 1)/2))\n\tA = zeros(windowSize, polyOrder+1)\n\tfor order = 0:polyOrder\n\t\tA[:, order+1] = (-halfWindow:halfWindow).^(order)\n\tend\n\n\t# Compute the required column of the inverse of A'*A\n\t# and calculate filter coefficients\n\tei = zeros(polyOrder+1)\n\tei[deriv+1] = 1.0\n\tinv_col = (A'*A) \\ ei\n\treturn A*inv_col * factorial(deriv) ./(dt^deriv)\nend\n\n\n\"\"\"\n\tburst_sampling(X, samplesize, n)\n\nRandomly selects `n` bursts of data with size `samplesize` from the data `X`.\n\"\"\"\n@inline function burst_sampling(x::AbstractArray, samplesize::Int64, bursts::Int64)\n    @assert size(x)[end] >= samplesize*bursts \"Bursting impossible. Please provide more data or reduce bursts or samplesize.\"\n    inds = sample(1:size(x)[end]-samplesize, bursts, replace = false)\n    inds = sort(unique(vcat([collect(i:i+samplesize) for i in inds]...)))\n    return resample(x, inds)\nend\n\n\"\"\"\n\tburst_sampling(X, Y, samplesize, n)\n\nRandomly selects `n` bursts of data with size `samplesize` from the data `X` and `Y`.\n\"\"\"\n@inline function burst_sampling(x::AbstractArray, y::AbstractArray, samplesize::Int64, bursts::Int64)\n    @assert size(x)[end] >= samplesize*bursts \"Bursting impossible. Please provide more data or reduce bursts or samplesize\"\n    @assert size(x)[end] == size(y)[end]\n    inds = sample(1:size(x)[end]-samplesize, bursts, replace = false)\n    inds = sort(unique(vcat([collect(i:i+samplesize) for i in inds]...)))\n    return resample(x, inds), resample(y, inds)\nend\n\n\"\"\"\n\tburst_sampling(X, t, period, n)\n\nRandomly selects `n` bursts of data within a time window `period` from the data `X`. The time information\nhas to be provided in `t`.\n\"\"\"\n@inline function burst_sampling(x::AbstractArray, t::AbstractVector, period::T, bursts::Int64) where T <: AbstractFloat\n    @assert period > zero(typeof(period)) \"Sampling period has to be positive.\"\n    @assert size(x)[end] == size(t)[end] \"Provide consistent data.\"\n    @assert bursts >= 1 \"Number of bursts has to be positive.\"\n    @assert t[end]-t[1]>= period*bursts \"Bursting impossible. Please provide more data or reduce bursts or samplesize\"\n    t_ids = zero(eltype(t)) .<= t .- period  .<= t[end] .- 2*period\n    samplesize = Int64(floor(period/(t[end]-t[1])*length(t)))\n    inds = sample(collect(1:length(t))[t_ids], bursts, replace = false)\n    inds = sort(unique(vcat([collect(i:i+samplesize) for i in inds]...)))\n    return resample(x, inds), resample(t, inds)\nend\n\n\n\"\"\"\n\tsubsample(X, n)\n\nReturns the subsampled `X` with only every `n`-th entry.\n\"\"\"\n@inline function subsample(x::AbstractVector, frequency::Int64)\n    @assert frequency > 0 \"Sampling frequency has to be positive.\"\n    return x[1:frequency:end]\nend\n\n\n@inline function subsample(x::AbstractArray, frequency::Int64)\n    @assert frequency > 0 \"Sampling frequency has to be positive.\"\n    return x[:, 1:frequency:end]\nend\n\n\n\"\"\"\n\tsubsample(X, t, dt)\n\nReturns the subsampled `X` with a a minimum period of `dt` between two data points. `t` provides the\ntime information.\n\"\"\"\n@inline function subsample(x::AbstractArray, t::AbstractVector, period::T) where T <: AbstractFloat\n    @assert period > zero(typeof(period)) \"Sampling period has to be positive.\"\n    @assert size(x)[end] == size(t)[end] \"Provide consistent data.\"\n    @assert t[end]-t[1]>= period \"Subsampling impossible. Sampling period exceeds time window.\"\n    idx = Int64[1]\n    t_now = t[1]\n    @inbounds for (i, t_current) in enumerate(t)\n        if t_current - t_now >= period\n            push!(idx, i)\n            t_now = t_current\n        end\n    end\n    return resample(x, idx), resample(t, idx)\nend\n\n@inline function resample(x::AbstractArray{T,1}, indx::AbstractArray{Int64}) where T <: Number\n    @assert maximum(indx) <= length(x) \"Sampling index has to be consistent with array dimensions.\"\n    @assert minimum(indx) >= 1 \"Sampling index has to be consistent with array dimensions.\"\n    return x[indx]\nend\n\n@inline function resample(x::AbstractArray{T,2}, indx::AbstractArray{Int64}) where T <: Number\n    @assert maximum(indx) <= size(x, 2) \"Sampling index has to be consistent with array dimensions.\"\n    @assert minimum(indx) >= 1 \"Sampling index has to be consistent with array dimensions.\"\n    return x[:, indx]\nend\n", "meta": {"hexsha": "187892b1fcaebd0599d1a2fe908441ab33b66366", "size": 12361, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "asinghvi17/DataDrivenDiffEq.jl", "max_stars_repo_head_hexsha": "502332931d0b97e18b3e3d6441bad54102b5cf52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "asinghvi17/DataDrivenDiffEq.jl", "max_issues_repo_head_hexsha": "502332931d0b97e18b3e3d6441bad54102b5cf52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "asinghvi17/DataDrivenDiffEq.jl", "max_forks_repo_head_hexsha": "502332931d0b97e18b3e3d6441bad54102b5cf52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0338461538, "max_line_length": 155, "alphanum_fraction": 0.68570504, "num_tokens": 3723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7562054422084906}}
{"text": "function LinearAlgebra.det(M::Matrix{<:AbstractPolynomialLike})\n    m = size(M)[1]\n    if m > 2\n        return sum((-1)^(i-1) * M[i,1] * LinearAlgebra.det(M[1:end .!= i, 2:end]) for i in 1:m)\n    else\n        return M[1,1] * M[2,2] - M[2,1] * M[1,2]\n    end\nend\n", "meta": {"hexsha": "22dd9065cd98e11272ced52a67f181648598da9c", "size": 262, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/det.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/MultivariatePolynomials.jl-102ac46a-7ee4-5c85-9060-abc95bfdeaa3", "max_stars_repo_head_hexsha": "6544a2004d5203a6bb1806238e9ecee4162342a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/det.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/MultivariatePolynomials.jl-102ac46a-7ee4-5c85-9060-abc95bfdeaa3", "max_issues_repo_head_hexsha": "6544a2004d5203a6bb1806238e9ecee4162342a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/det.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/MultivariatePolynomials.jl-102ac46a-7ee4-5c85-9060-abc95bfdeaa3", "max_forks_repo_head_hexsha": "6544a2004d5203a6bb1806238e9ecee4162342a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1111111111, "max_line_length": 95, "alphanum_fraction": 0.5381679389, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810481379379, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7561870283788501}}
{"text": "using Qaintessent\nusing LinearAlgebra\nusing SparseArrays: sparse\nusing Memoize\n\n# Simple struct that represents a graph via its edges\nstruct Graph\n    n::Int # number of vertices (indices 1,...,n)\n    edges::Set{Set{Int}} # edges, represented as sets of vertices\n\n    function Graph(n::Integer, edges::Vector{Tuple{T, T}}) where T <: Integer\n        n >= 1 || throw(DomainError(\"n must be a positive integer\"))\n\n        # Turn into set of sets\n        edge_set = Set(Set.(edges))\n\n        # Verify that all edges are valid\n        all(edge -> edge ⊆ 1:n && length(edge) == 2, edge_set) || throw(ArgumentError(\"Some edges have invalid endpoints\"))\n        new(n, edge_set)\n    end\nend\n\n\"\"\"\n    Phase separation gate for Max-κ-colorable subgraph QAOA mapping.\n    Represents the objective function which counts the number of invalid\n    edges (i.e. between vertices of the same color).\n    Implemented the for one-hot encoding.\n\n``U_{P}(\\\\gamma) = e^{-i \\\\gamma H_{P}}``\n``H_{P} = \\\\sum_{\\\\{u, v\\\\} \\\\in E} \\\\sum_{a=1}^{\\\\kappa} Z_{u, a} Z_{v, a}``\n\nReference:\\n\n    Stuart Hadfield, Zhihui Wang, Bryan O'Gorman, Eleanor G. Rieffel, Davide Venturelli and Rupak Biswas\\n\n    From the Quantum Approximate Optimization Algorithm to a Quantum Alternating Operator Ansatz\\n\n    Algorithms 12.2 (2019), p.34\n\"\"\"\nstruct MaxKColSubgraphPhaseSeparationGate <: AbstractGate \n    # use a reference type (array with 1 entry) for compatibility with Flux\n    γ::Vector{Float64} \n    κ::Int # the number of possible colors\n    graph::Graph # the underlying graph which should be colored\n\n    function MaxKColSubgraphPhaseSeparationGate(γ::Float64, κ::Integer, graph::Graph)\n        κ > 0 || throw(ArgumentError(\"Parameter `κ` must be a positive integer.\"))\n        length(graph.edges) > 0 || throw(ArgumentError(\"Graph `graph` must have at least one edge.\"))\n        new([γ], κ, graph)\n    end\nend\n\n@memoize function max_k_col_subgraph_phase_separation_hamiltonian(graph::Graph, κ::Int)\n    z = matrix(Z)\n    \n    # Implementation of Eq. (17)\n    # one-hot encoding: n * κ vector. Index (a-1)*n + (b-1) corresponds to vertex a, color b.\n    H_P_enc = sum(\n        kron((color == a && vertex ∈ edge ? z : I(2) for vertex ∈ 1:graph.n for color ∈ 1:κ)...) # Z_{u,a} Z_{v,a}\n        for a ∈ 1:κ for edge ∈ graph.edges # Σ_{(u,v) = edge ∈ E} Σ_{a=1..κ}\n    )\n    return Diagonal(H_P_enc)\nend\n\nfunction Qaintessent.matrix(g::MaxKColSubgraphPhaseSeparationGate)\n    # Calculate the hamiltonian (Eq. 17)\n    H_P_enc = max_k_col_subgraph_phase_separation_hamiltonian(g.graph, g.κ)\n\n    # Implementation of one-hot phase seperator, A.3.1, p. 34\n    U_P = exp(-im * g.γ[] * H_P_enc)\n\n    U_P\nend\n\nQaintessent.adjoint(g::MaxKColSubgraphPhaseSeparationGate) = MaxKColSubgraphPhaseSeparationGate(-g.γ[], g.κ, g.graph)\n\nQaintessent.sparse_matrix(g::MaxKColSubgraphPhaseSeparationGate) = sparse(matrix(g))\n\n# Number of wires (κ * n in the one-hot encoding)\nQaintessent.num_wires(g::MaxKColSubgraphPhaseSeparationGate)::Int = g.κ * g.graph.n\n", "meta": {"hexsha": "116485a36a87b550bc6ab92c3db513c794e2f449", "size": 3008, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/qaoa/phase_separator_gates.jl", "max_stars_repo_name": "isolatedinformation/Qaintessent.jl", "max_stars_repo_head_hexsha": "275df394b9b7103005fac6bac3d6ce0f955718e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/qaoa/phase_separator_gates.jl", "max_issues_repo_name": "isolatedinformation/Qaintessent.jl", "max_issues_repo_head_hexsha": "275df394b9b7103005fac6bac3d6ce0f955718e9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/qaoa/phase_separator_gates.jl", "max_forks_repo_name": "isolatedinformation/Qaintessent.jl", "max_forks_repo_head_hexsha": "275df394b9b7103005fac6bac3d6ce0f955718e9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5641025641, "max_line_length": 123, "alphanum_fraction": 0.6811835106, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810421953309, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7561870236355397}}
{"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ d66df1f3-c14a-440b-8148-7f5daa006f7c\nusing CSV\n\n# ╔═╡ bff18246-4ea2-43c0-9dca-69e855f06b7d\nusing Colors\n\n# ╔═╡ 2c21b237-c4b7-4de2-b0ce-287bdf252081\nusing Plots\n\n# ╔═╡ 25c8d94d-0393-4382-bbf4-500135b12f25\nusing LinearAlgebra\n\n# ╔═╡ 34039790-f50e-11eb-0b84-25496cba179e\nbegin\n\tusing PlutoUI\n\tPlutoUI.TableOfContents(title = \"Contents\")\nend\n\n# ╔═╡ 814a424a-96c4-4449-b002-f2e3122cb56d\nmd\"\"\"\n# Voronoi diagrams\n\"\"\"\n\n# ╔═╡ 26bf6d61-25e8-4558-97ea-72185b7dc963\nmd\"\"\"\n## Objectives\n- Create an algorithm to draw a Voronoi diagram from a list of points\n- Analyse the distribution of the number of edges of the polygons in a Voronoi diagram\n\"\"\"\n\n# ╔═╡ a1f023ab-e2ab-4d74-8067-e364ddeaa7ed\nmd\"\"\"\n## What is a Voronoi diagram?\n\nA Voronoi diagram is a diagram constructed in the plane, where given a number of points, the plane is partitioned into sections based on which of these points is closest. An example can be seen below for the approximate locations of Cambridge colleges (specifically, the main porter's lodges of each college):\n\"\"\"\n\n# ╔═╡ e9845cba-d61a-4150-9698-6dffbdde3138\nmd\"\"\"\nHere, each point represents the location of a college, with each surrounded by a convex polygon defining the set of points in the plane, coloured according to the key. It is worth pointing out that although any diagram such as the one above will truncate polygons to fit its bounds, there will always exist infinite polygons in the \"full\" Voronoi diagram (i.e. in the infinite plane). For the diagram above, there are five of these, Girton, Homerton, Hughes Hall, Jesus, and Wolfson (although the Murray Edwards polygon meets the edge of the diagram, it is not infinite, sharing a vertex with Girton and Jesus outside of the square).\n\nThree particular degenerate cases can occur in Voronoi diagrams. The first one I will attempt to reduce the impact of, but the other two I will ignore for the purposes of this project:\n- Three (or more) points can be exactly collinear. This does not always pose a problem, particularly if there are other points nearby. Indeed, in the example above, the points representing King's, Corpus Christi, and Pembroke happen to be exactly collinear, but the diagram is still generated without an issue.\n- Even worse, two points could coincide, which is guaranteed to break the algorithm. Unsurprisingly, no porter's lodges coincide, with the closest being Corpus Christi and St Catharine's at a distance of the width of Trumpington Street, two pavements and a bit of lawn apart, which is more than enough to be distinguished at this scale.\n- Four (or more) points can lie on a circle and so their regions meet at a quadripoint. This is far less likely to occur but requires a special case which I have not programmed into the algorithm. Despite a couple of near misses, there are no exact quadripoints in the dataset of colleges. The nearest is between Clare, King's, St Catharine's, and Queens', with the King's and Queens' regions sharing an edge of length approximately 1 metre (although this is well within errors caused by curvature of the Earth and the fact that porter's lodges are not particularly zero-dimensional)\n\"\"\"\n\n# ╔═╡ 2b2f564c-03f1-4da0-941e-c08bff8203fc\nmd\"\"\"\n## Importing the data\nBefore I start creating a Voronoi diagram, I need to get the coordinates of the points that will define it, which in this case are stored in a *.csv* file. The CSV package allows for the easy import of such data.\n\"\"\"\n\n# ╔═╡ 3683349f-55da-4725-937c-882d620261ac\nmd\"\"\"\nI construct the function `getpoints` to perform this import. Empty vectors are created to store the data: `xs` for the first coordinate of each point, `ys` for the second coordinate of each point, and `names` for names of the points (if they are specified, such as in the Cambridge colleges example above). Then, using the iterator `CSV.Rows`, I read the input file row by row, taking down the values stored. Then, I output the two/three (depending on if the points have names) vectors of data obtained from the file:\n\"\"\"\n\n# ╔═╡ 00f99f29-fd88-4bdd-875a-83e892cf4182\nfunction getpoints(path::String, usingnames::Bool = false)\n    xs = Int64[]\n    ys = Int64[]\n    names = String[]\n\t\n    for row ∈ CSV.Rows(path)\n        push!(xs,parse(Int64,row.x))\n        push!(ys,parse(Int64,row.y))\n        if usingnames\n            push!(names,row.name)\n        end\n    end\n\t\n    return usingnames ? (names, xs, ys) : (xs, ys)\nend\n\n# ╔═╡ 66f26cb1-958e-44e1-8ff2-0e65065347cd\nmd\"\"\"\nThe main data that I will be using will be 100 integer-valued points between ``(1,1)`` and ``(1000,1000)``, which I now import as `xs` and `ys`.\n\"\"\"\n\n# ╔═╡ d7e145f0-afd7-4f7b-a570-a20f54444c06\nxs, ys = getpoints(\"voronoipoints.txt\")\n\n# ╔═╡ fa9cce06-5c0d-46d8-82a8-110777450737\nmd\"\"\"\n## Two simple but inefficient approaches\nTo get a feel for Voronoi diagrams, I start with two simple approaches to creating approximate Voronoi diagrams.\n\n### Brute force method\nThe brute force method involves checking every single point in the eventual image, seeing which of the points it is closest to, and colouring it accordingly. This is simple, although horribly inefficient, since for each of one million points it needs to calculate 100 distances, totalling 100 million calculations.\n\nTo choose the colours, I use the `Colors` package, which contains the function `distinguishable_colors` to help choose colours that should be reasonably distinguishable from each other. I store these in a list indexed correspondingly with `xs` and `ys`.\n\"\"\"\n\n# ╔═╡ a5bae7fe-6bd8-49f8-9ccb-3567c4dceeee\nmd\"\"\"\nThen, I create a matrix of colours (the `RGB` type), and iterate over each element (columns first for efficiency). The Euclidean distances are calculated with the function `hypot`, which I broadcast over all of the points and look for the minimum value in the resulting vector with `findmin`. I take the index of this value (as `findmin` outputs both the value and its index, I obtain the index by simply taking the second output), and then fill the matrix with the appropriate colour from the list.\n```julia\npointcolours[x,y] = colours[findmin(hypot.(xs .- x, ys .- y))[2]]\n```\nAfter this, I create a scatter plot (using the `Plots` package), with each location in the appropriate colour, and add on markers for the points defining the Voronoi diagram\n\"\"\"\n\n# ╔═╡ 20a6f5d1-1df1-402f-bdb0-770e373a2caf\nmd\"\"\"\nThis I put into a function `bruteforcevoronoi`, which I can then test out on the data imported earlier.\n\"\"\"\n\n# ╔═╡ 04f8030e-a838-4e32-91c5-af63b50b8ef2\nfunction bruteforcevoronoi(xs::Vector{Int64}, ys::Vector{Int64})\n    m = length(xs)\n    colours = distinguishable_colors(m, lchoices = 50:5:100)\n\n    pointcolours = fill(RGB(0,0,0), (1000,1000))\n    for y ∈ 1:1000\n        for x ∈ 1:1000\n            pointcolours[x,y] = colours[findmin(hypot.(xs .- x, ys .- y))[2]]\n        end\n    end\n\n    diagram = scatter(\n        [(x,y) for x ∈ 1:1000, y ∈ 1:1000][:];\n        c = pointcolours[:],\n        markersize = 1,\n        markerstrokewidth = 0,\n        legend = false,\n        showaxis = false,\n        ticks = false,\n        size = (1000, 1000)\n    )\n    return scatter!(\n        diagram,\n        xs,\n        ys;\n        c = :black,\n        markersize = 2,\n        markerstrokewidth = 0\n    )\nend\n\n# ╔═╡ 16ee482f-2d14-4fa4-84c4-fb02e29e4e5f\nbruteforcevoronoi(xs,ys)\n\n# ╔═╡ c7ce5d31-c823-433e-90c7-474e5c64a25e\nmd\"\"\"\nThis is quite a good Voronoi diagram, although a little slow. Many of the edges don't look very straight, but this is not surprising since the diagram is calculated in a very discrete way so smoothness would be too much to ask for.\n\n### Monte Carlo method\nIn order to improve the speed, the obvious thing to do is to reduce the sample size. I can do this by randomly sampling from the plane instead of calculating the nearest point everywhere. This I implement with the function `montecarlovoronoi`, with an additional input `n` representing the number of samples to make.\n\"\"\"\n\n# ╔═╡ 0ecd4b67-aee6-4dfb-94e5-7cc8cae0c01d\nfunction montecarlovoronoi(n::Int64, xs::Vector{Int64}, ys::Vector{Int64})\n    m = length(xs)\n    colours = distinguishable_colors(m, lchoices = 50:5:100)\n\n    randxs = Int64[]\n    randys = Int64[]\n    randcolours = RGB[]\n\n    for _ ∈ 1:n\n        x, y = rand(1:1000), rand(1:1000)\n        push!(randxs, x)\n        push!(randys, y)\n        push!(randcolours, colours[findmin(hypot.(xs .- x, ys .- y))[2]])\n    end\n\n    diagram = scatter(\n        randxs,\n        randys;\n        c = randcolours,\n        markersize = 1,\n        markerstrokewidth = 0,\n        legend = false,\n        showaxis = false,\n        ticks = false,\n        size = (1000, 1000)\n    )\n    return scatter!(\n        diagram,\n        xs,\n        ys;\n        c = :black,\n        markersize = 2,\n        markerstrokewidth = 0,\n    )\nend\n\n# ╔═╡ 6ae8754a-9fb3-43a1-adcc-42411be63467\nmd\"\"\"\nTo test this method, I run the function with 1000, 10000, 100000, and finally 1000000 samples (the final one being the same number of samples as `bruteforcevoronoi` makes).\n\"\"\"\n\n# ╔═╡ ac20813e-57ec-4f40-bbaa-eeed7557f2f5\nplot(\n\tmontecarlovoronoi(1000,xs,ys),\n\tmontecarlovoronoi(10000,xs,ys),\n\tmontecarlovoronoi(100000,xs,ys),\n\tmontecarlovoronoi(1000000,xs,ys), \n\tlayout = (2,2)\n)\n\n# ╔═╡ 6f1c21bc-2803-4f10-ae1a-47fa6a883f19\nmd\"\"\"\nFrom these tests, it is clear to me that anything less than 100000 samples doesn't produce a clear Voronoi diagram, and so this improves on the speed of `bruteforcevoronoi` by about an order of magnitude at most. Even then, the edges are wigglier than in the first instance, making the diagram somewhat less clear.\n\nA problem with both these methods is that they give next to no information about the diagram other than the image representing it. For example, there is no way to know which regions border others other than checking manually from the diagrams, which would be time consuming to do for every region. This prevents me from doing any analysis on the diagram's structure, or efficiently storing the diagram in memory. A cleverer approach will be necessary to achieve this.\n\"\"\"\n\n# ╔═╡ 5619eeaa-d0ae-4752-987a-abc6b9236725\nmd\"\"\"\n## Constructing the Voronoi diagram geometrically\n\"\"\"\n\n# ╔═╡ 35546877-09ce-4294-acd3-6150a2b3637d\nmd\"\"\"\n### A geometric algorithm\nA close look at the Voronoi diagram's construction reveals two useful geometric facts about the edges between points:\n- All edges are equidistant from the two points whose regions it seperates, i.e. are segments of perpendicular bisectors\n- Where edges meet, they are equidistant from three points, so the tripoint must lie at the circumcentre of the three points (the centre of the circle passing through all three)\n\"\"\"\n\n# ╔═╡ f50845c7-45b1-46a0-9c7f-35303080b036\nbegin\n\tdiagram₁ = plot(\n\t\t[   Shape([(-2,-2),(-2,3),(0,2.5),(2,-1.5)]),\n\t\t\tShape([(0,2.5),(2,-1.5),(3,-2),(3,3)]),\n\t\t\tShape([(5,-2),(4.5,3),(85/12,5/12),(7.5,-1.25)]),\n\t\t\tShape([(4.5,3),(85/12,5/12),(8,2.25)]),\n\t\t\tShape([(85/12,5/12),(8,2.25),(10,3),(10,-2),(7.5,-1.25)])],\n\t\tc = [:pink :lightblue :pink :lightblue :beige],\n\t\tlinewidth = 0,\n\t\tlegend = false,\n\t\tshowaxis = false,\n\t\tticks = false,\n\t\txlims = [-1, 9],\n\t\tylims = [-1, 2],\n\t\tsize = (1000, 300)\n\t)\n\t\n\tscatter!(\n\t\tdiagram₁,\n\t\t[(0,0),(2,1),(6,0.5),(7,1.5),(8,1)],\n\t\tc = :black,\n\t)\n\n\t\n\tplot!(\n\t\tdiagram₁,\n\t\t[x -> 2.5 - 2x, x -> 0.5x],\n\t\tc = [:black :gray],\n\t\tlinestyle = [:solid :dash]\n\t)\n\t\n\tplot!(\n\t\tdiagram₁,\n\t\t[(0.9,0.45),(0.85,0.55),(0.95,0.6)],\n\t\tc = :gray\n\t)\n\t\n\tplot!(\n\t\tdiagram₁,\n\t\t1.0865*cos.(0:0.01π:2.01π) .+ 85/12,\n\t\t1.0865*sin.(0:0.01π:2.01π) .+ 5/12,\n\t\tc = :gray,\n\t\tlinestyle = :dash\n\t)\n\t\n\tplot!(\n\t\tdiagram₁,\n\t\t[(4.5,3),(85/12,5/12),(8,2.25),(85/12,5/12),(7.5,-1.25)],\n\t\tc = :black\n\t)\n\t\n\tplot!(\n\t\tdiagram₁,\n\t\t[(6,0.5),(85/12,5/12),(7,1.5),(85/12,5/12),(8,1)],\n\t\tc = :gray,\n\t\tlinestyle = :dash\n\t)\n\t\n\tplot!(\n\t\tdiagram₁,\n\t\t[(98/15,7/20),(131/20,17/30)],\n\t\tc = :grey\n\t)\n\t\n\tplot!(\n\t\tdiagram₁,\n\t\t[(104/15,19/20),(143/20,29/30)],\n\t\tc = :grey\n\t)\n\t\n\tplot!(\n\t\tdiagram₁,\n\t\t[(38/5,37/60),(449/60,4/5)],\n\t\tc = :grey\n\t)\n\t\n\tplot!(\n\t\tdiagram₁,\n\t\tShape([(3,-2),(5,-2),(5,3),(3,3)]),\n\t\tc = :white,\n\t\tlinecolor = :white\n\t)\nend\n\n# ╔═╡ 26dfe1aa-9e61-46dd-953b-3164c4470458\nmd\"\"\"\nConsider two points ``\\mathbf{p}`` and ``\\mathbf{q}`` whose regions share an edge in the Voronoi diagram, and consider the circumcentres of ``\\mathbf{p}``, ``\\mathbf{q}``, and ``\\mathbf{r}`` for all other points ``\\mathbf{r}`` which define the diagram. All of these circumcentres must lie on the perpendicular bisector of ``\\mathbf{p}`` and ``\\mathbf{q}``. Additionally, if any of these circumcentres were on the edge between the regions, then ``\\mathbf{r}`` would be closer than ``\\mathbf{p}`` or ``\\mathbf{q}`` on one side of the line, so this must lie at the end of the edge.\n\nIndeed, for any points ``\\mathbf{p}`` and ``\\mathbf{q}``, the circumcentres of ``\\mathbf{p}`` and ``\\mathbf{q}`` with each other point ``\\mathbf{r}`` lie on the perpendicular bisector, with the border between the Voronoi regions of ``\\mathbf{p}`` and ``\\mathbf{q}`` either nonexistent, or one of the line segments between adjacent circumcentres, such as below:\n\"\"\"\n\n# ╔═╡ 7c392155-a7b1-4dfb-b6bb-bb52e8f071f7\nbegin\n\tdiagram₂ = scatter(\n\t\t[(4,-0.5),(4,1.5)],\n\t\tc = :black,\n\t\tlegend = false,\n\t\tshowaxis = false,\n\t\tticks = false,\n\t\txlims = [-1, 9],\n\t\tylims = [-1, 2],\n\t\tann = [(4.2,-0.6,\"q\"),(3.8,1.6,\"p\")],\n\t\tsize = (1000, 300)\n\t)\n\t\n\tplot!(\n\t\tdiagram₂,\n\t\t[(-2,0),(10,1)],\n\t\tc = :lightgray,\n\t\tlinestyle = :dash\n\t)\n\t\n\tplot!(\n\t\tdiagram₂,\n\t\t[(4.5,6.5/12),(5,7/12)],\n\t\tc = :black\n\t)\n\t\n\tscatter!(\n\t\tdiagram₂,\n\t\t[(1,1/4),(3,5/12),(4.5,6.5/12),(5,7/12),(7.5,9.5/12)],\n\t\tc = :lightgray,\n\t\tmarkerstrokewidth = 0\n\t)\nend\n\n# ╔═╡ 406599de-7141-4c59-a294-bffb79973098\nmd\"\"\"\nThis gives rise to the algorithm that I will implement. For each point ``\\mathbf{p}`` of the Voronoi diagram in succession, I will start at a point ``\\mathbf{z}`` which I know is on the border of ``\\mathbf{p}``'s region (which will be halfway between ``\\mathbf{p}`` and the closest other point ``\\mathbf{q}``).\n\"\"\"\n\n# ╔═╡ c5553b17-c7a6-4c3d-92e2-9dff80c28867\nbegin\n\tdiagram₃ = scatter(\n\t\t[(0.5,0.5),(1,1.5),(0.75,1)],\n\t\tc = :black,\n\t\tshape = [:o, :o, :x],\n\t\tmarkersize = [3, 3, 5],\n\t\tlegend = false,\n\t\tshowaxis = false,\n\t\tticks = false,\n\t\txlims = [-1, 3],\n\t\tylims = [-1, 2],\n\t\tann = [(0.7,0.4,\"p\"),(0.8,1.6,\"q\"),(0.9,1.1,\"z\")],\n\t\tsize = (400, 300)\n\t)\n\t\n\tplot!(\n\t\tdiagram₃,\n\t\t[(-1.25,2),(3.75,-0.5)],\n\t\tc = :gray,\n\t\tlinestyle = :dash\n\t)\n\t\n\tplot!(\n\t\tdiagram₃,\n\t\t[(0.75,1),(1.25,0.75)],\n\t\tc = :black,\n\t\tarrow = arrow(:closed)\n\t)\nend\n\n# ╔═╡ 98e6d6c3-1623-403a-b066-bdd280aaee4e\nmd\"\"\"\nThen, looking in one direction along the perpendicular bisector, I find the point ``\\mathbf{r}`` which along with ``\\mathbf{p}`` and ``\\mathbf{q}`` defines the first circumcentre that I would come across. This circumcentre becomes a tripoint, and I get a new edge to the region to look down, that is the edge between ``\\mathbf{p}`` and ``\\mathbf{r}``, along their perpendicular bisector.\n\"\"\"\n\n# ╔═╡ 283f5b27-6bd6-4cc2-98b7-d72377505626\nbegin\n\tdiagram₄ = scatter(\n\t\t[(0.5,0.5),(1,1.5),(3,1),(65/36,17/36)],\n\t\tc = [:black, :black, :black, :gray],\n\t\tmarkerstrokewidth = 0,\n\t\tlegend = false,\n\t\tshowaxis = false,\n\t\tticks = false,\n\t\txlims = [-1, 3],\n\t\tylims = [-1, 2],\n\t\tann = [(0.7,0.4,\"p\"),(0.8,1.6,\"q\"),(2.8,1.1,\"r\")],\n\t\tsize = (400, 300)\n\t)\n\t\n\tplot!(\n\t\tdiagram₄,\n\t\t[(-1.25,2),(3.75,-0.5)],\n\t\tc = :gray,\n\t\tlinestyle = :dash\n\t)\n\t\n\tplot!(\n\t\tdiagram₄,\n\t\t[(0.75,1),(65/36,17/36)],\n\t\tc = :black\n\t)\n\t\n\tplot!(\n\t\tdiagram₄,\n\t\t[(1.25,3.25),(2.25,-1.75)],\n\t\tc = :gray,\n\t\tlinestyle = :dash\n\t)\n\t\n\tplot!(\n\t\tdiagram₄,\n\t\t[(65/36,17/36),(2,-0.5)],\n\t\tc = :black,\n\t\tarrow = arrow(:closed)\n\t)\nend\n\n# ╔═╡ 74fe0258-6c8e-4383-9aad-ffcb890e9612\nmd\"\"\"\nI continue this all the way around until I return to the start, giving a cycle of neighbours in the order that they are encountered.\n\nHowever if ``\\mathbf{p}`` is on the edge of the diagram, then at some point there will be no circumcentre to be find along the line. In this special case, I return to the same initial point ``\\mathbf{z}`` and start to look the other way, until again there is no circumcentre to find. Instead of a cycle of neighbours, this gives a sequence of neighbours bookended by neighbours with which ``\\mathbf{p}`` shares a unbounded edge.\n\"\"\"\n\n# ╔═╡ 4ff3a96d-14dd-4af8-820a-bbb30c3fca15\nmd\"\"\"\n### The VoronoiPoint type\nTo be able to store the data about each point, I create a new type called `VoronoiPoint`, which contains as fields its `x` and `y` coordinates, as well as a vector of neighbours. I also create an outer constructor which allows me to easily initialise a new `VoronoiPoint` with no neighbours.\n\"\"\"\n\n# ╔═╡ 7d80b224-03ad-4034-af2d-7975b6e0e7a9\nbegin\n\tmutable struct VoronoiPoint\n    \tx::Real\n    \ty::Real\n    \tneighbours::Vector{VoronoiPoint}\n\tend\n\tVoronoiPoint(x::T, y::T) where T <: Real = VoronoiPoint(x, y, VoronoiPoint[])\nend\n\n# ╔═╡ 26502d5d-54c6-4d57-9be4-5e8971635560\nmd\"\"\"\nThis new type has a subtle problem, which is with its automatic display style. If `p` and `q` is a `VoronoiPoint`, and they neighbour, then:\n- To display `p`, Julia automatically displays `p.x`, `p.y`, and the vector `p.neighbours`. This includes `q`, so Julia will have to display `q`\n- To display `q`, Julia displays `q.neighbours`, which includes `p`. This creates an infinite loop\nIn order to fix this, I need to create a new method for `Base.show` (the function determining this display) which does not display the neighbours. I chose the coordinate style `(x,y)`.\n\"\"\"\n\n# ╔═╡ 8c07108a-49e0-4ef3-873c-e5d6576c99cc\nbegin\n\timport Base.show\n\tshow(io::IO, p::VoronoiPoint) = print(io, \"(\", p.x, \",\", p.y, \")\")\nend\n\n# ╔═╡ 00d09735-0b30-465c-9c39-81209d36265f\nVoronoiPoint(4,5)\n\n# ╔═╡ ada943f1-077e-4fa0-9024-915e7d23c2e2\nmd\"\"\"\n### Three geometric functions\nTo be able to implement my algorithm, I need three functions to capture the geometry between `VoronoiPoint`s, for which I will also use the LinearAlgebra package.\n\"\"\"\n\n# ╔═╡ d3b2bb40-359e-4696-a74d-030afcf4f9c7\nmd\"\"\"\nThe first function `pos` is very simple, merely assembling the position vector of a `VoronoiPoint` from its `x` and `y` fields.\n\"\"\"\n\n# ╔═╡ 4b3fc852-caae-4b8d-8582-f308a9a255ca\npos(p::VoronoiPoint) = [p.x, p.y]\n\n# ╔═╡ fc64f356-5550-4d43-8564-0d2002dc8316\nmd\"\"\"\nThe second function `perpbisector` finds the parameters defining the perpendicular bisector as a line in in the plane. In particular, it outputs two vectors, the midpoint of the two (which lies on the line), and a direction vector. The choice of which direction this vector goes along the line is arbitrary, although it is important to know for later (I have chosen it such that `p` lies to the right and `q` lies to the left).\n\"\"\"\n\n# ╔═╡ 9b35606b-9175-40a5-99e8-62251e72f3a4\nfunction perpbisector(p::VoronoiPoint, q::VoronoiPoint)\n    return ( (pos(p) + pos(q))/2 , [[0,1] [-1,0]] * (pos(p) - pos(q)) )\nend\n\n# ╔═╡ f2b1cc32-370f-465c-bab8-15365cf5de69\nmd\"\"\"\nThe third and most complicated function `circumcentre` calculates the circumcentre of three `VoronoiPoint`s. This is easiest to do as the intersection of two perpendicular bisectors:\n```math\n\\mathbf{y} = \\mathbf{x_1} + t_1 \\mathbf{v_1}, \\quad \\mathbf{y} = \\mathbf{x_2} + t_2 \\mathbf{v_2}\n```\nEquating these gives:\n```math\n\\mathbf{x_2} - \\mathbf{x_1} = t_1 \\mathbf{v_1} - t_2 \\mathbf{v_2}\n```\nwhich is a linear system of two equations in two unknowns ``t_1`` and ``t_2``. If ``\\mathbf{v_1}`` and ``\\mathbf{v_2}`` are parallel, this is degenerate (meaning that the three points are collinear), and I will return an infinite vector, ensuring that this circumcentre is not found on the line. Otherwise, I let ``M`` be the inverse of the matrix with columns ``\\mathbf{v_1}`` and ``\\mathbf{v_2}``, leaving:\n```math\nM(\\mathbf{x_2} - \\mathbf{x_1}) = \\begin{pmatrix} t_1 \\\\ t_2 \\end{pmatrix}\n```\nThis I can solve, and hence find the circumcentre ``\\mathbf{y}``.\n\"\"\"\n\n# ╔═╡ 951bea47-8e23-45f9-b935-882566d3fdc3\nfunction circumcentre(p::VoronoiPoint, q::VoronoiPoint, r::VoronoiPoint)\n    (x₁, v₁) = perpbisector(p,q)\n    (x₂, v₂) = perpbisector(p,r)\n    det([v₁ v₂]) == 0 && return [Inf, Inf]\n    M = [v₁ v₂]^-1\n    t₁ = (M * (x₂ - x₁))[1]\n    return x₁ + t₁*v₁\nend\n\n# ╔═╡ 3ffacdd0-510f-4ef5-b934-4ff15b536b7c\nmd\"\"\"\n### Adding points to the diagram one by one\nTo construct the diagram, I have chosen to add each point one by one. This reduces the looping over all points `r` to a smaller loop - indeed it is even smaller since I need only check the neighbours of `q` - but comes at the cost of having to adjust the list of neighbours of all of the points calculated to neighbour `p`.\n\nFirst I put to use the three geometric functions that I have just defined in order to create the function `findnextpoint`. This function performs the job of looking along the perpendicular bisector to find which point `r` has the closest circumcentre with `p` and `q` to the initial starting point `z`. This I do by dot multiplying `directionvector` (calculated by `perpbisector` and pointing along the line) with the vector from `z` to the circumcentre for each of `q`'s neighbours, giving a measure of displacement along the bisector. If no circumcentres are found in that direction, the `nextpoint` output is `VoronoiPoint(Inf,Inf)`, denoting that the edge goes to infinity, which can be identified by the next function.\n\nSince the algorithm can involve looking both ways along a perpedicular bisector, I use an additional boolean input `reversedirection` to determine whether the default direction given by `perpbisector` should be reversed or not. \n\"\"\"\n\n# ╔═╡ c6ff22c9-16d8-494a-8b82-997a61ecf38c\nfunction findnextpoint(p::VoronoiPoint, q::VoronoiPoint, z::Vector{T},\n\t\treversedirection::Bool) where T <: Real\n    directionvector = perpbisector(p,q)[2] .* (-1)^reversedirection\n    \n    mindisplacement = Inf\n    nextpoint = VoronoiPoint(Inf,Inf)\n    for r ∈ q.neighbours\n        r ∈ [p,q] && continue\n        displacement = dot(directionvector, circumcentre(p,q,r) - z)\n        displacement > 0 && displacement < mindisplacement &&\n\t\t\t(mindisplacement = displacement; nextpoint = r)\n    end\n    return nextpoint\nend\n\n# ╔═╡ 8f9286e4-f49d-4227-9611-9793f484d5dd\nmd\"\"\"\nThe next function is `addpoint`, which adds a new point at coordinates `x` and `y` relative to a vector `allpoints` listing all of the other points that are in the diagram so far.\n\nThe first course of action is to create the new `VoronoiPoint` object, and find the nearest other point to it which can be used as a starting point, similarly to how it is done in the brute force and Monte Carlo methods above.\n```julia\np = VoronoiPoint(x, y)\nnearestpoint = allpoints[findmin([hypot(x-q.x, y-q.y) for q ∈ allpoints])[2]]\n```\n\nThen I can set up initial values for `z` (the point tracing the boundary of `p`'s region) and `q` (the neighbouring point along whose perpendicular bisector with `p` the algorithm is looking), as well as the boolean `reversedirection` to keep track of whether the algorithm is looking in its default direction or not.\n```julia\nz = perpbisector(p, nearestpoint)[1]\nq = nearestpoint\nreversedirection = false\n```\n\nNow, the propagation can begin. For each iteration, first `q` is added to the end of the list of `p`'s neighbours.\n```julia\npush!(p.neighbours, q)\n```\n\nAfter that, I look for the next point `r` as found by `findnextpoint`.\n```julia\nr = findnextpoint(p, q, z, reversedirection)\n```\n\"\"\"\n\n# ╔═╡ 3acc9ae8-c107-4434-b72d-590a1abc8130\nmd\"\"\"\nThree different scenarios can occur with `r`:\n- `r` could be the special case `VoronoiPoint(Inf,Inf)`. To avoid writing an equality method for `VoronoiPoint`s, I compare their positions only, since I am assuming no two can coincide, hence I check this case with `pos(r) == [Inf,Inf]`. If this occurs, then I start by adding `VoronoiPoint(Inf,Inf)` onto the end of the list of neighbours to mark that the line extends to infinity here. If I have already checked in the other direction too (i.e. `reversedirection == true`), then I am done, otherwise I revert back to the original values of `z` and `q`, but with the direction reversed and `q` taken off the list since it will be added again at the next loop. In order to maintain the order of the list of neighbours, I reverse that too.\n```julia\npush!(p.neighbours, r)\nif reversedirection\n    break\nelse\n    reversedirection = true\n    q = nearestpoint\n    z = perpbisector(p, nearestpoint)[1]\n    pop!(reverse!(p.neighbours))\n    continue\nend\n```\n\n- `r` could be `nearestpoint`, in which case the point `z` has traced out the entire loop around `p`, so the algorithm can stop (note that in a Voronoi diagram the regions are convex so never share two seperate borders). Before stopping the loop, I reverse the list of neighbours to keep consistency with the first case, ensuring that whenever the algorithm stops `p`'s neighbours will always be in anticlockwise order, which will become important later.\n```julia\nreverse!(p.neighbours)\nbreak\n```\n\n- Otherwise, the algorithm simply needs to repeat with a new point `z` and a new neighbour `q`.\n```julia\nz = circumcentre(p,q,r)\nq = r\n```\n\"\"\"\n\n# ╔═╡ e39cf938-c946-4a65-bb20-3c5c73bb0ef2\nmd\"\"\"\nNow that the loop has finished, I have a point `p` with all of its neighbours found in the correct order, and it is ready to be returned. However, the list of neighbours for other points has not yet been updated, which I need to do first before ending the function. This is made simpler by the fact that the neighbours of each point are always in an expected order, specifically:\n```math\n\\mathbf{p} \\text{ has neighbours } \\dots \\mathbf{q_{i-1}}, \\mathbf{q_i}, \\mathbf{q_{i+1}}, \\dots \\quad \\Rightarrow \\quad \\mathbf{q_i} \\text{ has neighbours } \\dots \\mathbf{q_{i+1}}, \\mathbf{p}, \\mathbf{q_{i-1}}, \\dots\n```\n\nAlso, the other neighbours of ``\\mathbf{q_i}`` would not have changed in order at all, so all I need to do is find the gap between ``\\mathbf{q_{i+1}}`` and ``\\mathbf{q_{i-1}}``, and place ``\\mathbf{p}`` in it.\n\nFor each `qᵢ` (one of the `n` neighbours of `p`) which isn't one of the infinity markers `VoronoiPoint(Inf,Inf)` at either end, I look for the indices of `qᵢ₋₁` and `qᵢ₊₁` amongst its neighbours. Since these could themselves be a `VoronoiPoint(Inf,Inf)`, I make sure to search for them from the correct end of the list of neighbours, that is `qᵢ₋₁` from the end and `qᵢ₊₁` from the start.\n```julia\npos(q) == [Inf, Inf] && continue\nj = findlast(r -> pos(r) == pos(p.neighbours[mod(i-1,1:n)]), q.neighbours)\nk = findfirst(r -> pos(r) == pos(p.neighbours[mod(i+1,1:n)]), q.neighbours)\n```\n\nOnce I have these indices, I place `p` in the list of neighbours between the two, getting rid of anything that was in between before. Since the list of neighbours can be cyclic, I check the order of the two indices first to make sure I know which way \"in between\" means.\n```julia\nif j < k\n    q.neighbours = vcat(q.neighbours[j:k], p)\nelse\n    q.neighbours = vcat(q.neighbours[1:k], p, q.neighbours[j:end])\nend\n```\n\nFinally, the point `p` has been successfully added, with all of the other points updated accordingly. The full function is:\n\"\"\"\n\n# ╔═╡ aee35cf6-8ef4-4550-b65f-a546416d642f\nfunction addpoint(x::Real, y::Real, allpoints::Vector{VoronoiPoint})\n    p = VoronoiPoint(x, y)\n    nearestpoint =\n\t\tallpoints[findmin([hypot(x-q.x, y-q.y) for q ∈ allpoints])[2]]\n    \n    z = perpbisector(p, nearestpoint)[1]\n    q = nearestpoint\n    reversedirection = false\n    while true\n        push!(p.neighbours, q)\n        r = findnextpoint(p, q, z, reversedirection)\n\n        if pos(r) == [Inf,Inf]\n            push!(p.neighbours, r)\n            if reversedirection\n                break\n            else\n                reversedirection = true\n                q = nearestpoint\n                z = perpbisector(p, nearestpoint)[1]\n                pop!(reverse!(p.neighbours))\n                continue\n            end\n\n        elseif pos(r) == pos(nearestpoint)\n            reverse!(p.neighbours)\n            break\n\n        else\n            z = circumcentre(p,q,r) \n            q = r\n        end\n    end\n\n    n = length(p.neighbours)\n    for i ∈ 1:n\n        q = p.neighbours[i]\n        pos(q) == [Inf, Inf] && continue\n        j = findlast(r -> pos(r) == pos(p.neighbours[mod(i-1,1:n)]), q.neighbours)\n        k = findfirst(r -> pos(r) == pos(p.neighbours[mod(i+1,1:n)]), q.neighbours)\n        if j < k\n            q.neighbours = vcat(q.neighbours[j:k], p)\n        else\n            q.neighbours = vcat(q.neighbours[1:k], p, q.neighbours[j:end])\n        end\n    end\n\n    return p\nend\n\n# ╔═╡ 11cd1d8b-6c81-4b15-b0ef-544bd477baed\nmd\"\"\"\nThis provides the majority of the heavy lifting for the algorithm, but one final small function `voronoipoints` is required to get from lists of coordinates to a list of `VoronoiPoint`s with all of the neighbours correctly calculated. I begin with the first point with its only neighbour being `VoronoiPoint(Inf,Inf)`.\n```julia\npoints = [VoronoiPoint(xs[1],ys[1],[VoronoiPoint(Inf,Inf)])]\n```\nThen, one by one, each point is added to the list.\n```julia\nfor i ∈ 2:length(xs)\n    push!(points,addpoint(xs[i],ys[i],points))\nend\n```\nIn theory, this works, but in practice, one small alteration needs to be made. Although the coordinates of the points from the input are given as integers, calculating the perpendicular bisectors and circumcentres results in non-integer values and inevitable rounding errors, and then the `while` loop in `addpoint` has a tendency to get stuck in an infinite loop bouncing between two points `q` as `z` is inaccurately calculated.\n\nHowever, there is a fix to this, and that is using `Rational`s, which is a data type storing rational numbers exactly, provided that the numerator and denominator can be stored exactly. Looking back at the `perpbisector` and `circumcentre` functions, I note that they involve only addition, subtraction, multiplication, and division, so rational inputs will guarantee rational outputs. Hence, by turning the integer coordinates into `Rational`s, rounding errors can be removed entirely. It's no wonder that the Ancient Greeks liked them so much!\n\nAn issue with using `Rational`s is that with larger input sizes the numerators and denominators only get bigger and bigger, and this can quickly overcome the limit of 2⁶³ - 1, the largest integer storable in the standard `Int64` format. Julia has another numeric type to deal with this problem though, which is `BigInt`, which can store arbitrarily large integers at the cost of more memory. Therefore, whatever form they come in, I convert the `xs` and `ys` to `Rational{BigInt}` form before passing them to `addpoint` in order to mitigate any rounding/overflow errors.\n\"\"\"\n\n# ╔═╡ 1883f53f-dc01-4eda-9ea6-a1d27bf17cdb\nfunction voronoipoints(xs::Vector{T}, ys::Vector{T}) where T <: Real\n\txs, ys = Rational{BigInt}.(xs), Rational{BigInt}.(ys)\n    points = [VoronoiPoint(xs[1],ys[1],[VoronoiPoint(Inf,Inf)])]\n    for i ∈ 2:length(xs)\n        push!(points,addpoint(xs[i],ys[i],points))\n    end\n    return points\nend\n\n# ╔═╡ cf3ddbb7-7a8c-4f4f-8970-c61fffe5f2b7\nmd\"\"\"\nThe data `xs` and `ys` result in the following list of `VoronoiPoint`s:\n\"\"\"\n\n# ╔═╡ 4b153157-0ba1-4042-bea9-904e946a6ca2\npoints = voronoipoints(xs,ys)\n\n# ╔═╡ bbe2a7ab-24aa-4ebb-9323-a10cb4739f03\nmd\"\"\"\nI can also look to see that the lists of neighbours are filled in for each point.\n\"\"\"\n\n# ╔═╡ b63bd719-a709-4a10-be7a-ac075d3ff3c4\npoints[1].neighbours\n\n# ╔═╡ 6977e1e5-50f0-4da2-9acc-877d4140fa7c\npoints[12].neighbours\n\n# ╔═╡ 86b670fb-6a4c-406c-abdd-e9e81c460c57\nmd\"\"\"\n### Plotting the Voronoi diagram\nThis achieves my goal of storing a Voronoi diagram in memory efficiently and in a way that can be analysed, as I will look at later. However, a Voronoi diagram is more than an abstract mathematical object; it is a way of visualising data, and so I feel it is necessary to be able to turn this into a actual diagram.\n\nFirstly, I calculate the points with `voronoipoints`, which gives all the data needed to draw the diagram. I also choose a list of colours as before.\n```julia\npoints = voronoipoints(xs,ys)\nm = length(xs)\ncolours = distinguishable_colors(m, lchoices = 50:5:100)\n```\n\nFrom each point, I will calculate the vertices of the polygon defining the region of points closest to it, and use them to create a `Shape` object, which is a type from the package `Plots` used for creating polygons. These will be stored in a vector `polygons`, which I need to create before I start looping over each point.\n```julia\npolygons = Shape[]\n```\n\nNow, for each point `p`, I let `n` be the number of neighbours, and start a list `vertices` to keep track of the vertices of the polygon. In this case, there is no need to use `BigInt`s, so I will stick to the `Rational{Int64}` type to be more memory efficient.\n```julia\nn = length(p.neighbours)\nvertices = Tuple{Rational{Int64}, Rational{Int64}}[]\n```\n\nFor each neighbour, I need to add the circumcentre between `p`, it, and the next neighbour into the list of vertices.\n```julia\nq,r = p.neighbours[j], p.neighbours[mod(j+1,1:n)]\npush!(vertices,Tuple(circumcentre(p,q,r)))\n```\n\nHowever, special treatment is needed for points whose polygons extend to infinity, since I will have to add more vertices along the border of the diagram such that the shape fills the space fully. This I do by finding the lines of the semi-infinite edges in the form ``\\mathbf{x} + t \\mathbf{v}``, and finding the values of ``t`` where it intersects the each of the lines defining the edges of the diagram. Since the midpoint of the two points either side of the edge is on the line and also within the bounds of the diagram, I take this to be ``\\mathbf{x}``. For the infinite edge at the end of the list of neighbours, this looks like:\n```julia\nx, v = perpbisector(p.neighbours[n-1],p)\nx, v = Rational{Int64}.(x), Rational{Int64}.(v)\ntvals = [-x[2]/v[2], (1000-x[1])/v[1], (1000-x[2])/v[2], -x[1]/v[1]]\n```\n\nwith `tvals` being the values of `t` where the line intersects:\n- `y = 0` (bottom edge), at `t = -x[2]/v[2]`\n- `x = 1000` (right edge), at `t = (1000-x[1])/v[1]`\n- `y = 1000` (top edge), at `t = (1000-x[2])/v[2]`\n- `x = 0` (left edge), at `t = -x[1]/v[1]`\n\nThen, I find which is the minimal positive value, and add that vertex to the list.\n```julia\nt = minimum(tvals[tvals .> 0])\npush!(vertices,Tuple(x + t*v))\n```\n\nI repeat this for the other semi-infinite edge. Since this gives me two values for each of `x`, `v`, `t`, `tvals`, I use subscripts to differentiate between them (`t₁`, `v₂`, etc.)\n\n\nThis leaves only one possibility for where vertices may be missing, which is in the corners. To find which corners I need to add, first I calculate the number of corners I need, which is the difference between the indices of `t₂` in `t₂vals` and `t₁` in `t₁vals` modulo 4.\n```julia\nt₁index = findfirst(==(t₁),t₁vals)\nt₂index = findfirst(==(t₂),t₂vals)\nindexdifference = mod(t₂index - t₁index,4)\n```\n\nAs I know which indices correspond to which edges, I work around from the edge that t₁index corresponds to fill in each of the corners on the way to the edge that t₂index corresponds to.\n```julia\ncorners = [(0,0), (1000,0), (1000,1000), (0,1000)]\nfor j ∈ 1:indexdifference\n    push!(vertices,corners[mod(t₁index+j, 1:4)])\nend\n```\n\nI have now ensured that every polygon has all of the vertices it should.\n```julia\npush!(polygons, Shape(vertices))\n```\n\nI combine this all together, plot the shapes as well as black dots for the points, and add an option for naming the points as shown in the Cambridge colleges example at the start of this document, which results in the `voronoi` function.\n\"\"\"\n\n# ╔═╡ d319f1c6-c329-4148-95c2-51e8814bcb56\nfunction voronoi(xs::Vector{T}, ys::Vector{T};\n\t\tnames::Vector{String} = String[]) where T <: Real\n    points = voronoipoints(xs,ys)\n    m = length(xs)\n    colours = distinguishable_colors(m, lchoices = 50:5:100)\n    usingnames = !isempty(names)\n\n    polygons = Shape[]\n    for p ∈ points\n        n = length(p.neighbours)\n        vertices = Tuple{Rational{Int64}, Rational{Int64}}[]\n\n        if pos(p.neighbours[1]) == [Inf,Inf]\n            startindex, endindex = 2, n-2\n\n            x₁, v₁ = perpbisector(p.neighbours[n-1],p)\n            x₁, v₁ = Rational{Int64}.(x₁), Rational{Int64}.(v₁)\n            t₁vals =\n\t\t\t\t[-x₁[2]/v₁[2], (1000-x₁[1])/v₁[1], (1000-x₁[2])/v₁[2], -x₁[1]/v₁[1]]\n            t₁ = minimum(t₁vals[t₁vals .> 0])\n            push!(vertices,Tuple(x₁ + t₁*v₁))\n\n            x₂, v₂ = perpbisector(p,p.neighbours[2])\n            x₂, v₂ = Rational{Int64}.(x₂), Rational{Int64}.(v₂)\n            t₂vals =\n\t\t\t\t[-x₂[2]/v₂[2], (1000-x₂[1])/v₂[1], (1000-x₂[2])/v₂[2], -x₂[1]/v₂[1]]\n            t₂ = minimum(t₂vals[t₂vals .> 0])\n\n            t₁index = findfirst(==(t₁),t₁vals)\n            t₂index = findfirst(==(t₂),t₂vals)\n            indexdifference = mod(t₂index - t₁index,4)\n            corners = [(0,0), (1000,0), (1000,1000), (0,1000)]\n            for j ∈ 1:indexdifference\n                push!(vertices,corners[mod(t₁index+j, 1:4)])\n            end\n\n            push!(vertices,Tuple(x₂ + t₂*v₂))\n\n        else\n            startindex, endindex = 1, n\n        end\n\n        for j ∈ startindex:endindex\n            q,r = p.neighbours[j], p.neighbours[mod(j+1,1:n)]\n            push!(vertices,Tuple(circumcentre(p,q,r)))\n        end\n\n        push!(polygons, Shape(vertices))\n    end\n\n    diagram = plot(\n        polygons,\n        c = colours',\n        label = (usingnames ? hcat(names...) : false),\n        showaxis = false,\n        ticks = false,\n        size = (1000, 1000),\n        xlims = (0, 1000),\n        ylims = (0, 1000)\n    )\n    return scatter!(\n\t\tdiagram,\n\t\txs,\n\t\tys,\n\t\tc = :black,\n\t\tmarkersize = 2,\n\t\tlabel = false\n\t)\nend\n\n# ╔═╡ 1520465f-d0f8-43b4-bb07-3daaa8c3e715\nbegin\n\tnamescam, xscam, yscam = getpoints(\"cambridgecolleges.txt\",true)\n\tvoronoi(xscam, yscam; names = namescam)\nend\n\n# ╔═╡ a278f976-7446-4c0a-8026-00ac80343759\nmd\"\"\"\nTrying it out on the sample data gives exactly the diagram I hoped for:\n\"\"\"\n\n# ╔═╡ bb9e1fc6-0ff6-46ce-aae7-9926841e6917\nvoronoi(xs,ys)\n\n# ╔═╡ 19d2d573-0857-456e-bd5b-e52962ce0e50\nmd\"\"\"\nIn comparison to the other two methods, the diagram is much cleaner with the black outlines to the polygons, as well as having the advantage of memory efficiency and accessibility of its data.\n\"\"\"\n\n# ╔═╡ cdc7af5b-abcf-4b65-8a7c-274ad64a4bd3\nmd\"\"\"\n## The distribution of the number of edges of Voronoi polygons\nThe `voronoipoints` function gives the means to analyse the Voronoi diagram which the other two functions couldn't. I will put this to use by looking into the distribution of the number of edges of Voronoi polygons.\n\nFirst, I will consider the distribution for `n` points uniformly randomly distributed in the plane. To try to avoid collinear points and quadripoints, I sample them from ``{0, \\frac{1}{n}, \\frac{2}{n}, ..., 10}``, although this has the undesirable side-effect of slowing down the calculations as the denominators get larger.\n```julia\nvoronoipoints(rand(0:(1//n):10, n), rand(0:(1//n):10, n))\n```\n\nI will ignore any polygons extending to infinity, only counting those which are bounded, and hence counting the number of neighbours suffices to count the edges of the polygon\n```julia\nneighbourcount = broadcast(\n\tp -> pos(p.neighbours[1]) == [Inf, Inf] ? 0 : length(p.neighbours), points)\n```\n\nI then plot a bar graph from these counts. This is then returned to complete the `voronoidistribution` function.\n\"\"\"\n\n# ╔═╡ f464f35c-0d4d-4d70-9632-6a09b1928695\nfunction voronoidistribution(points::Vector{VoronoiPoint})\n    neighbourcount = broadcast(\n\t\tp -> pos(p.neighbours[1]) == [Inf, Inf] ? 0 : length(p.neighbours), points)\n\n    m = maximum(neighbourcount)\n    total = count(!=(0), neighbourcount)\n    return bar(\n        1:m,\n        [count(==(i), neighbourcount)//total for i ∈ 1:m],\n        legend = false,\n        xticks = 1:m,\n        yticks = 0:0.1:1\n    )\nend\n\n# ╔═╡ 03348ff9-e422-4908-bd27-db4257511635\nmd\"\"\"\nFour samples with `n = 1000` points are shown below, along with an example illustrating a Voronoi diagram with 1000 points sampled in this way:\n\"\"\"\n\n# ╔═╡ 2c7a67e0-3ead-4988-9633-db0ad673b0a6\nn = 1000\n\n# ╔═╡ 80360e43-0038-40b3-ae9c-28ad88959a97\nvoronoi(rand(1:100//n:1000, n),rand(1:100//n:1000, n))\n\n# ╔═╡ 716d84bf-0271-4f0c-a38f-3cf265dcc99f\nplot(\n\tvoronoidistribution(voronoipoints(rand(0:(1//n):10, n), rand(0:(1//n):10, n))),\n\tvoronoidistribution(voronoipoints(rand(0:(1//n):10, n), rand(0:(1//n):10, n))),\n\tvoronoidistribution(voronoipoints(rand(0:(1//n):10, n), rand(0:(1//n):10, n))),\n\tvoronoidistribution(voronoipoints(rand(0:(1//n):10, n), rand(0:(1//n):10, n))),\n\tlayout = (2,2)\n)\n\n# ╔═╡ 2939781c-0c22-4d10-9aa6-2218b00c4705\nmd\"\"\"\nMost common here are hexagons, with pentagons just behind, and heptagons in third place. This distribution mirrors the results of Tanemura in *Statistical Distributions of Poisson Voronoi Cells in Two and Three Dimensions*, in particular [this figure](https://www.semanticscholar.org/paper/Statistical-Distributions-of-Poisson-Voronoi-Cells-Tanemura/c7a539e69a36b4501ab2a763de34c5d0c17c465e/figure/10), although the uniformly random sampling is exchanged for the slightly different Poisson point process.\n\nI will now look at the number of edges that a Voronoi diagram has when the points are more regularly arranged. I start with a lattice, either square or hexagonal, with ``\\frac{6}{7}`` used as a rational approximation of ``\\frac{\\sqrt{3}}{2}`` to make the hexagonal lattice approximately equilateral. I then apply some normally distributed randomness with standard deviation `σ` to each point, rounded off to keep the coordinates rational. Then, I generate bar graphs using `voronoidistribution` as before.\n\"\"\"\n\n# ╔═╡ 0ebcb0f4-159a-4f12-ba9d-f9887762b6e3\nfunction randomlattice(shape::Symbol, n::Int64, σ::Rational{Int64})\n\tif shape == :square\n\t\tcoords = [(x,y) for x ∈ 1:n, y ∈ 1:n]\n\telseif shape == :hexagonal\n\t\tcoords = hcat([(x,(6//7)*y) for x ∈ 1:n, y ∈ 1:2:n],\n\t\t\t[(x+1//2,(6//7)*y) for x ∈ 1:n, y ∈ 2:2:n])\n\telse\n\t\terror(\"Invalid shape\")\n\tend\n\t\n\txs,ys = [xy[1] for xy ∈ coords[:]], [xy[2] for xy ∈ coords[:]]\n\trandxs = xs .+ σ * round.(Int64, n * randn(n^2))//n\n\trandys = ys .+ σ * round.(Int64, n * randn(n^2))//n\n\treturn voronoidistribution(voronoipoints(randxs,randys))\nend\n\n# ╔═╡ 86663fe9-e192-4876-a61f-22e7647d8abe\nmd\"\"\"\nThe standard deviations that I have chosen to sample with are `1//1`, `1//2`, `1//5`, and `1//10`:\n\"\"\"\n\n# ╔═╡ 08d69e9e-958e-4feb-adb8-9dd9019b2bf1\nσlist = [1//1, 1//2, 1//5, 1//10]\n\n# ╔═╡ 11949d3b-86cc-4969-b56e-1096f1a102b0\nmd\"\"\"\nFor the square lattice, a sample is:\n\"\"\"\n\n# ╔═╡ 1bf7c58c-813a-4a21-a667-46a2e0758616\nplot(\n\t[randomlattice(:square, 30, σ) for σ ∈ σlist]...,\n\ttitle = hcat([\"σ = $σ\" for σ ∈ σlist]...),\n\tlayout = (2,2)\n)\n\n# ╔═╡ 269b4fab-c944-425e-9cc1-7f43b03d9505\nmd\"\"\"\nAnd for the hexagonal lattice, with the same standard deviations:\n\"\"\"\n\n# ╔═╡ 2e5d4be6-53d9-46b0-a5f4-29be3bd55142\nplot(\n\t[randomlattice(:hexagonal, 30, σ) for σ ∈ σlist]...,\n\ttitle = hcat([\"σ = $σ\" for σ ∈ σlist]...),\n\tlayout = (2,2)\n)\n\n# ╔═╡ 74dcc761-2448-4d74-af28-756fa473f3ea\nmd\"\"\"\nIn the perfect square lattice, all of the regions would be squares, although this is misleading, as they all meet at quadripoints, so each actually has 8 neighbours. Even with a small amount of randomness added, the distribution looks broadly similar to that of uniformly randomly chosen points, with the most notable difference being that the proportion of hexagons increases slightly, and the proportion of pentagons decreases slightly as the pattern becomes more regular with lower `σ`.\n\nIn contrast, starting with a hexagonal lattice, most of the regions become hexagons by the time that the standard deviation has come down to `1//5`, and almost all are when `σ = 1//10`. I interpret this as an illustration of the greater stability of the hexagonal lattice over the square lattice, which leads to its greater prevalence in nature, for example in honeycomb, or the Giant's Causeway.\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nCSV = \"336ed68f-0bac-5ca0-87d4-7b16caf5d00b\"\nColors = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\n\n[compat]\nCSV = \"~0.8.5\"\nColors = \"~0.12.8\"\nPlots = \"~1.20.0\"\nPlutoUI = \"~0.7.9\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c3598e525718abcc440f69cc6d5f60dda0a1b61e\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.6+5\"\n\n[[CSV]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"PooledArrays\", \"SentinelArrays\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"b83aa3f513be680454437a0eee21001607e5d983\"\nuuid = \"336ed68f-0bac-5ca0-87d4-7b16caf5d00b\"\nversion = \"0.8.5\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"e2f47f6d8337369411569fd45ae5753ca10394c6\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.0+6\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\", \"StaticArrays\"]\ngit-tree-sha1 = \"ed268efe58512df8c7e224d2e170afd76dd6a417\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.13.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"344f143fa0ec67e47917848795ab19c6a455f32c\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.32.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"ee400abb2298bd13bfc3df1c412ed228061a2385\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.7.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"4437b64df1e0adccc3e5d1adbc3ac741095e4677\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.9\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"92d8f9f208637e8d2d28c664051a00569c01493d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.1.5+1\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"LibVPX_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"3cc57ad0a213808473eafef4845a74766242e05f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.3.1+4\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"35895cf184ceaab11fd778b4590144034a167a2f\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.1+14\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"cbd58c9deb1d304f5a245a0b7eb841a2560cfec6\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.1+5\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"dba1e8614e98949abfa60480b13653813d8f0157\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+0\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"182da592436e287758ded5be6e32c406de3a2e47\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.58.1\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"d59e8320c2747553788e4fc42231489cc602fa50\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.58.1+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"7bf67e9a481712b3dbe9cb3dac852dc4b1162e02\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"44e3b40da000eab4ccb1aecdc4801c040026aeb5\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.13\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"81690084b6198a2e1da36fcfda16eeca9f9f24e4\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.1\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a4b12a1bd2ebade87891ab7e36fdbce582301a92\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.6\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[LibVPX_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"12ee7e23fa4d18361e7c2cde8f8337d4c3101bc7\"\nuuid = \"dd192d2f-8180-539f-9fb4-cc70b1dcf69a\"\nversion = \"1.10.0+0\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"761a393aeccd6aa92ec3515e428c26bf99575b3b\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+0\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"0fb723cd8c45858c22169b2e42269e53271a6df7\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.7\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"4ea90bd5d3985ae1f9a908bd4500ae88921c5ce7\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.0\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+0\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"bfd7d8c7fd87f04543810d9cbd3995972236ba1b\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"1.1.2\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"501c20a63a34ac1d015d5304da0e645f42d91c9f\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.0.11\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\"]\ngit-tree-sha1 = \"e39bea10478c6aff5495ab522517fae5134b40e3\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.20.0\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"Suppressor\"]\ngit-tree-sha1 = \"44e225d5837e2a2345e69a1d1e01ac2443ff9fcb\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.9\"\n\n[[PooledArrays]]\ndeps = [\"DataAPI\", \"Future\"]\ngit-tree-sha1 = \"cde4ce9d6f33219465b55162811d8de8139c0414\"\nuuid = \"2dfb63ee-cc39-5dd5-95bd-886bf059d720\"\nversion = \"1.2.1\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"b3fb709f3c97bfc6e948be68beeecb55a0b340ae\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.1\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"2a7a2469ed5d94a98dea0e85c46fa653d76be0cd\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.3.4\"\n\n[[Reexport]]\ngit-tree-sha1 = \"5f6c21241f0f655da3952fd60aa18477cf96c220\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.1.0\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[SentinelArrays]]\ndeps = [\"Dates\", \"Random\"]\ngit-tree-sha1 = \"a3a337914a035b2d59c9cbe7f1a38aaba1265b02\"\nuuid = \"91c51154-3ec4-41a3-a24f-3f23e20d615c\"\nversion = \"1.3.6\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"885838778bb6f0136f8317757d7803e0d81201e4\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.9\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"1958272568dc176a1d881acb797beb909c785510\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.0.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"fed1ec1e65749c4d96fc20dd13bea72b55457e62\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.9\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"000e168f5cc9aded17b6999a560b7c11dda69095\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.0\"\n\n[[Suppressor]]\ngit-tree-sha1 = \"a819d77f31f83e5792a76081eee1ea6342ab8787\"\nuuid = \"fd094767-a336-5f1f-9728-57cf17d0bbfb\"\nversion = \"0.2.0\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"d0c690d37c73aeb5ca063056283fde5585a41710\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.5.0\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\"]\ngit-tree-sha1 = \"2839f1c1296940218e35df0bbb220f2a79686670\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.18.0+4\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"acc685bcf777b2202a904cdcb49ad34c2fa1880c\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.14.0+4\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7a5780a0d9c6864184b3a2eeeb833a0c871f00ab\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"0.1.6+4\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d713c1ce4deac133e3334ee12f4adff07f81778f\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2020.7.14+2\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"487da2f8f2f0c8ee0e83f39d13037d6bbf0a45ab\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.0.0+3\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─814a424a-96c4-4449-b002-f2e3122cb56d\n# ╟─26bf6d61-25e8-4558-97ea-72185b7dc963\n# ╟─a1f023ab-e2ab-4d74-8067-e364ddeaa7ed\n# ╠═1520465f-d0f8-43b4-bb07-3daaa8c3e715\n# ╟─e9845cba-d61a-4150-9698-6dffbdde3138\n# ╟─2b2f564c-03f1-4da0-941e-c08bff8203fc\n# ╠═d66df1f3-c14a-440b-8148-7f5daa006f7c\n# ╟─3683349f-55da-4725-937c-882d620261ac\n# ╠═00f99f29-fd88-4bdd-875a-83e892cf4182\n# ╟─66f26cb1-958e-44e1-8ff2-0e65065347cd\n# ╠═d7e145f0-afd7-4f7b-a570-a20f54444c06\n# ╟─fa9cce06-5c0d-46d8-82a8-110777450737\n# ╠═bff18246-4ea2-43c0-9dca-69e855f06b7d\n# ╟─a5bae7fe-6bd8-49f8-9ccb-3567c4dceeee\n# ╠═2c21b237-c4b7-4de2-b0ce-287bdf252081\n# ╟─20a6f5d1-1df1-402f-bdb0-770e373a2caf\n# ╠═04f8030e-a838-4e32-91c5-af63b50b8ef2\n# ╠═16ee482f-2d14-4fa4-84c4-fb02e29e4e5f\n# ╟─c7ce5d31-c823-433e-90c7-474e5c64a25e\n# ╠═0ecd4b67-aee6-4dfb-94e5-7cc8cae0c01d\n# ╟─6ae8754a-9fb3-43a1-adcc-42411be63467\n# ╠═ac20813e-57ec-4f40-bbaa-eeed7557f2f5\n# ╟─6f1c21bc-2803-4f10-ae1a-47fa6a883f19\n# ╟─5619eeaa-d0ae-4752-987a-abc6b9236725\n# ╟─35546877-09ce-4294-acd3-6150a2b3637d\n# ╟─f50845c7-45b1-46a0-9c7f-35303080b036\n# ╟─26dfe1aa-9e61-46dd-953b-3164c4470458\n# ╟─7c392155-a7b1-4dfb-b6bb-bb52e8f071f7\n# ╟─406599de-7141-4c59-a294-bffb79973098\n# ╟─c5553b17-c7a6-4c3d-92e2-9dff80c28867\n# ╟─98e6d6c3-1623-403a-b066-bdd280aaee4e\n# ╟─283f5b27-6bd6-4cc2-98b7-d72377505626\n# ╟─74fe0258-6c8e-4383-9aad-ffcb890e9612\n# ╟─4ff3a96d-14dd-4af8-820a-bbb30c3fca15\n# ╠═7d80b224-03ad-4034-af2d-7975b6e0e7a9\n# ╟─26502d5d-54c6-4d57-9be4-5e8971635560\n# ╠═8c07108a-49e0-4ef3-873c-e5d6576c99cc\n# ╠═00d09735-0b30-465c-9c39-81209d36265f\n# ╟─ada943f1-077e-4fa0-9024-915e7d23c2e2\n# ╠═25c8d94d-0393-4382-bbf4-500135b12f25\n# ╟─d3b2bb40-359e-4696-a74d-030afcf4f9c7\n# ╠═4b3fc852-caae-4b8d-8582-f308a9a255ca\n# ╟─fc64f356-5550-4d43-8564-0d2002dc8316\n# ╠═9b35606b-9175-40a5-99e8-62251e72f3a4\n# ╟─f2b1cc32-370f-465c-bab8-15365cf5de69\n# ╠═951bea47-8e23-45f9-b935-882566d3fdc3\n# ╟─3ffacdd0-510f-4ef5-b934-4ff15b536b7c\n# ╠═c6ff22c9-16d8-494a-8b82-997a61ecf38c\n# ╟─8f9286e4-f49d-4227-9611-9793f484d5dd\n# ╟─3acc9ae8-c107-4434-b72d-590a1abc8130\n# ╟─e39cf938-c946-4a65-bb20-3c5c73bb0ef2\n# ╠═aee35cf6-8ef4-4550-b65f-a546416d642f\n# ╟─11cd1d8b-6c81-4b15-b0ef-544bd477baed\n# ╠═1883f53f-dc01-4eda-9ea6-a1d27bf17cdb\n# ╟─cf3ddbb7-7a8c-4f4f-8970-c61fffe5f2b7\n# ╠═4b153157-0ba1-4042-bea9-904e946a6ca2\n# ╟─bbe2a7ab-24aa-4ebb-9323-a10cb4739f03\n# ╠═b63bd719-a709-4a10-be7a-ac075d3ff3c4\n# ╠═6977e1e5-50f0-4da2-9acc-877d4140fa7c\n# ╟─86b670fb-6a4c-406c-abdd-e9e81c460c57\n# ╠═d319f1c6-c329-4148-95c2-51e8814bcb56\n# ╟─a278f976-7446-4c0a-8026-00ac80343759\n# ╠═bb9e1fc6-0ff6-46ce-aae7-9926841e6917\n# ╟─19d2d573-0857-456e-bd5b-e52962ce0e50\n# ╟─cdc7af5b-abcf-4b65-8a7c-274ad64a4bd3\n# ╠═f464f35c-0d4d-4d70-9632-6a09b1928695\n# ╟─03348ff9-e422-4908-bd27-db4257511635\n# ╠═2c7a67e0-3ead-4988-9633-db0ad673b0a6\n# ╠═80360e43-0038-40b3-ae9c-28ad88959a97\n# ╠═716d84bf-0271-4f0c-a38f-3cf265dcc99f\n# ╟─2939781c-0c22-4d10-9aa6-2218b00c4705\n# ╠═0ebcb0f4-159a-4f12-ba9d-f9887762b6e3\n# ╟─86663fe9-e192-4876-a61f-22e7647d8abe\n# ╠═08d69e9e-958e-4feb-adb8-9dd9019b2bf1\n# ╟─11949d3b-86cc-4969-b56e-1096f1a102b0\n# ╠═1bf7c58c-813a-4a21-a667-46a2e0758616\n# ╟─269b4fab-c944-425e-9cc1-7f43b03d9505\n# ╠═2e5d4be6-53d9-46b0-a5f4-29be3bd55142\n# ╟─74dcc761-2448-4d74-af28-756fa473f3ea\n# ╟─34039790-f50e-11eb-0b84-25496cba179e\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "54f566a6042790deb4af1b20cbd9a72d0c0ffa73", "size": 75838, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "casestudies/voronoi/voronoidiagrams.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "casestudies/voronoi/voronoidiagrams.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "casestudies/voronoi/voronoidiagrams.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 38.7323799796, "max_line_length": 739, "alphanum_fraction": 0.7111606319, "num_tokens": 29880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.8757869835428965, "lm_q1q2_score": 0.7561471460290298}}
{"text": "# # Linear rotating shallow water dynamics\n#\n#md # This example can be run online via [![](https://mybinder.org/badge_logo.svg)](@__BINDER_ROOT_URL__/literated/OneDShallowWaterGeostrophicAdjustment.ipynb). \n#md # Also, it can be viewed as a Jupyter notebook via [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/literated/OneDShallowWaterGeostrophicAdjustment.ipynb).\n# \n#\n# This example solves the linear 1D rotating shallow water equations\n# for the ``u(x, t)``, ``v(x, t)`` and the surface surface elevation ``\\eta(x, t)``, \n# for a fluid with constant rest-depth ``H``. That is, the total fluid's depth \n# is ``H + \\eta(x, t)`` with ``|\\eta| \\ll H``.\n# \n# The linearized equations for the evolution of ``u``, ``v``, ``\\eta`` are:\n#\n# ```math\n# \\begin{aligned}\n# \\partial_t u - f v & = - g \\partial_x \\eta - \\mathrm{D} u, \\\\\n# \\partial_t v + f u & = - \\mathrm{D} v, \\\\\n# \\partial_t \\eta + H \\partial_x u & = - \\mathrm{D} \\eta.\n# \\end{aligned}\n# ```\n#\n# Above, ``g`` is the gravitational acceleration, ``f`` is the  Coriolis parameter, and \n# ``\\mathrm{D}`` indicates a hyperviscous linear operator of the form ``(-1)^{n_ν} ν \\nabla^{2 n_ν}``, \n# with ``ν`` the viscosity coefficient and ``n_ν`` the order of the operator.\n#\n# Rotation introduces the deformation length scale, ``L_d = \\sqrt{g H} / f``. Disturbances with \n# length scales much smaller than ``L_d`` don't \"feel\" the rotation and propagate as inertia-gravity\n# waves. Disturbances with length scales comparable or larger than ``L_d`` should be approximately\n# in geostrophic balance, i.e., the Coriolis acceleration ``f \\widehat{\\bm{z}} \\times \\bm{u}`` \n# should be in approximate balance with the pressure gradient ``-g \\bm{\\nabla} \\eta``.\n\n\nusing FourierFlows, Plots, Printf, Random\nusing LinearAlgebra: mul!, ldiv!\n\n# ## Coding up the equations\n# ### A demonstration of FourierFlows.jl framework\n#\n# What follows is a step-by-step tutorial demonstrating how you can create your own solver \n# for an equation of your liking.\n\n# The basic building blocks for a `FourierFlows.Problem` are:\n# - `Grid` struct containining the physical and wavenumber grid for the problem,\n# - `Params` struct containining all the parameters of the problem,\n# - `Vars` struct containining arrays with the variables used in the problem,\n# - `Equation` struct containining the coefficients of the linear operator ``L`` and the function that computes the nonlinear terms, usually named `calcN!()`.\n# \n# The `Grid` structure is provided by FourierFlows.jl. We simply have to call one of either \n# `OneDGrid()`, `TwoDGrid()`, or `ThreeDGrid()` constructors, depending on the dimensionality \n# of the problem. All other structs mentioned above are problem-specific and need to be constructed \n# for every set of equations we want to solve.\n\n# First let's construct the `Params` struct that contains all parameters of the problem.\n\nstruct Params{T} <: AbstractParams\n   ν :: T         # Hyperviscosity coefficient\n  nν :: Int       # Order of the hyperviscous operator\n   g :: T         # Gravitational acceleration\n   H :: T         # Fluid depth\n   f :: T         # Coriolis parameter\nend\nnothing #hide\n\n# Now the `Vars` struct that contains all variables used in this problem. For this\n# problem `Vars` includes the representations of the flow fields in physical space \n# `u`, `v` and `η` and their Fourier transforms `uh`, `vh`, and `ηh`.\n\nstruct Vars{Aphys, Atrans} <: AbstractVars\n   u :: Aphys\n   v :: Aphys\n   η :: Aphys\n  uh :: Atrans\n  vh :: Atrans\n  ηh :: Atrans\nend\nnothing #hide\n\n# A constructor populates empty arrays based on the dimension of the `grid`\n# and then creates `Vars` struct.\n\"\"\"\n    Vars(dev, grid)\nConstructs Vars for 1D shallow water based on the dimensions of arrays of the `grid`.\n\"\"\"\nfunction Vars(::Dev, grid) where Dev\n  T = eltype(grid)\n  @devzeros Dev T grid.nx u v η\n  @devzeros Dev Complex{T} grid.nkr uh vh ηh\n  \n  return Vars(u, v, η, uh, vh, ηh)\nend\nnothing #hide\n\n\n# In Fourier space, the 1D linear shallow water dynamics read:\n#\n# ```math\n# \\begin{aligned}\n# \\frac{\\partial \\hat{u}}{\\partial t} & = \\underbrace{ f \\hat{v} - i k g \\hat{\\eta} }_{N_u} \\; \\underbrace{- \\nu k^2 }_{L_u} \\hat{u} , \\\\\n# \\frac{\\partial \\hat{v}}{\\partial t} & = \\underbrace{ - f \\hat{u} }_{N_v} \\; \\underbrace{- \\nu k^2 }_{L_v} \\hat{v} , \\\\\n# \\frac{\\partial \\hat{\\eta}}{\\partial t} & = \\underbrace{ - i k H \\hat{u} }_{N_{\\eta}} \\; \\underbrace{- \\nu k^2 }_{L_{\\eta}} \\hat{\\eta} .\n# \\end{aligned}\n# ```\n# Although, e.g., terms involving the Coriolis accelaration are, in principle, linear we include \n# them in the nonlinear term ``N`` because they render the linear operator ``L`` non-diagonal.\n#\n# With these in mind, we construct function `calcN!` that computes the nonlinear terms.\n#\n\"\"\"\n    calcN!(N, sol, t, clock, vars, params, grid)\nCompute the nonlinear terms for 1D linear shallow water dynamics.\n\"\"\"\nfunction calcN!(N, sol, t, clock, vars, params, grid)\n  @. vars.uh = sol[:, 1]\n  @. vars.vh = sol[:, 2]\n  @. vars.ηh = sol[:, 3]\n  \n  @. N[:, 1] =   params.f * vars.vh - im * grid.kr * params.g * vars.ηh    #  + f v - g ∂η/∂x\n  @. N[:, 2] = - params.f * vars.uh                                        #  - f u\n  @. N[:, 3] = - im * grid.kr * params.H * vars.uh                         #  - H ∂u/∂x\n  \n  dealias!(N, grid)\n  \n  return nothing\nend\nnothing #hide\n \n# Next we construct the `Equation` struct:\n\n\"\"\"\n    Equation(dev, params, grid)\nConstruct the equation: the linear part, in this case the hyperviscous dissipation,\nand the nonlinear part, which is computed by `calcN!` function.\n\"\"\"\nfunction Equation(dev, params, grid)\n  T = eltype(grid)\n  L = zeros(dev, T, (grid.nkr, 3))\n  D = @. - params.ν * grid.kr^(2*params.nν)\n  \n  L[:, 1] .= D # for u equation\n  L[:, 2] .= D # for v equation\n  L[:, 3] .= D # for η equation\n  \n  return FourierFlows.Equation(L, calcN!, grid)\nend\nnothing #hide\n\n# We now have all necessary building blocks to construct a `FourierFlows.Problem`. \n# It would be useful, however, to define some more \"helper functions\". For example,\n# a function that updates all variables given the solution `sol` which comprises ``\\hat{u}``,\n# ``\\hat{v}`` and ``\\hat{\\eta}``:\n\n\"\"\"\n    updatevars!(prob)\nUpdate the variables in `prob.vars` using the solution in `prob.sol`.\n\"\"\"\nfunction updatevars!(prob)\n  vars, grid, sol = prob.vars, prob.grid, prob.sol\n  \n  @. vars.uh = sol[:, 1]\n  @. vars.vh = sol[:, 2]\n  @. vars.ηh = sol[:, 3]\n  \n  ldiv!(vars.u, grid.rfftplan, deepcopy(sol[:, 1])) # use deepcopy() because irfft destroys its input\n  ldiv!(vars.v, grid.rfftplan, deepcopy(sol[:, 2])) # use deepcopy() because irfft destroys its input\n  ldiv!(vars.η, grid.rfftplan, deepcopy(sol[:, 3])) # use deepcopy() because irfft destroys its input\n  \n  return nothing\nend\nnothing #hide\n\n# Another useful function is one that prescribes an initial condition to the state variable `sol`.\n\n\"\"\"\n    set_uvη!(prob, u0, v0, η0)\nSets the state variable `prob.sol` as the Fourier transforms of `u0`, `v0`, and `η0`\nand update all variables in `prob.vars`.\n\"\"\"\nfunction set_uvη!(prob, u0, v0, η0)\n  vars, grid, sol = prob.vars, prob.grid, prob.sol\n  \n  A = typeof(vars.u) # determine the type of vars.u\n  \n  mul!(vars.uh, grid.rfftplan, A(u0)) # A(u0) converts u0 to the same type as vars expects (useful if u0 is a CPU array while working on the GPU)\n  mul!(vars.vh, grid.rfftplan, A(v0)) # A(v0) converts u0 to the same type as vars expects (useful if v0 is a CPU array while working on the GPU)\n  mul!(vars.ηh, grid.rfftplan, A(η0)) # A(η0) converts u0 to the same type as vars expects (useful if η0 is a CPU array while working on the GPU)\n\n  @. sol[:, 1] = vars.uh\n  @. sol[:, 2] = vars.vh\n  @. sol[:, 3] = vars.ηh\n    \n  updatevars!(prob)\n  \n  return nothing\nend\nnothing #hide\n\n# ## Let's prescibe parameter values and solve the PDE\n#\n# We are now ready to write up a program that sets up parameter values, constructs \n# the problem `prob`, # time steps the solutions `prob.sol` and plots it.\n\n# ## Choosing a device: CPU or GPU\n\ndev = CPU()    # Device (CPU/GPU)\nnothing # hide\n\n# ## Numerical parameters and time-stepping parameters\n\n     nx = 512            # grid resolution\nstepper = \"FilteredRK4\"  # timestepper\n     dt = 20.0           # timestep (s)\n nsteps = 320            # total number of time-steps\nnothing # hide\n\n\n# ## Physical parameters\n\nLx = 500e3      # Domain length (m)\ng  = 9.8        # Gravitational acceleration (m s⁻²)\nH  = 200.0      # Fluid depth (m)\nf  = 1e-2       # Coriolis parameter (s⁻¹)\nν  = 100.0      # Viscosity (m² s⁻¹)\nnν = 1          # Viscosity order (nν = 1 means Laplacian ∇²)\nnothing # hide\n\n\n# ## Construct the `struct`s and you are ready to go!\n# Create a `grid` and also `params`, `vars`, and the `equation` structs. Then \n# give them all as input to the `FourierFlows.Problem()` constructor to get a\n# problem struct, `prob`, that contains all of the above.\n\n    grid = OneDGrid(dev, nx, Lx)\n  params = Params(ν, nν, g, H, f)\n    vars = Vars(dev, grid)\nequation = Equation(dev, params, grid)\n\n    prob = FourierFlows.Problem(equation, stepper, dt, grid, vars, params, dev)\nnothing #hide\n\n# ## Setting initial conditions\n\n# For initial condition we take the fluid at rest (``u = v = 0``). The free surface elevation\n# is perturbed from its rest position (``\\eta=0``); the disturbance we impose a Gaussian \n# bump with half-width greater than the deformation radius and on top of that we \n# superimpose some random noise with scales smaller than the deformation radius. \n# We mask the small-scale perturbations so that it only applies in the central part \n# of the domain by applying\n#\n# The system develops geostrophically-balanced jets around the Gaussian bump, \n# while the smaller-scale noise propagates away as inertia-gravity waves. \n\n# First let's construct the Gaussian bump.\n\ngaussian_width = 6e3\ngaussian_amplitude = 3.0\ngaussian_bump = @. gaussian_amplitude * exp( - grid.x^2 / (2*gaussian_width^2) )\n\nplot(grid.x/1e3, gaussian_bump,    # divide with 1e3 to convert m -> km\n     color = :black,\n    legend = false,\n linewidth = 2,\n     alpha = 0.7,\n     xlims = (-Lx/2e3, Lx/2e3),\n    xlabel = \"x [km]\",\n    ylabel = \"η [m]\",\n     title = \"A gaussian bump with half-width ≈ \"*string(gaussian_width/1e3)*\" km\",\n      size = (600, 260))\n\n# Next the noisy perturbation. The `mask` is simply a product of hyperbolic tangent functions.\nmask = @. 1/4 * (1 + tanh( -(grid.x - 100e3) / 10e3)) * (1 + tanh( (grid.x + 100e3) / 10e3))\n\nnoise_amplitude = 0.1 # the amplitude of the noise for η(x,t=0) (m)\nη_noise = noise_amplitude * Random.randn(size(grid.x))\n@. η_noise *= mask    # mask the noise\n\nplot_noise = plot(grid.x/1e3, η_noise,      # divide with 1e3 to convert m -> km\n                 color = :black,\n                legend = :false,\n             linewidth = [3 2],\n                 alpha = 0.7,\n                 xlims = (-Lx/2e3, Lx/2e3), # divide with 1e3 to convert m -> km\n                 ylims = (-0.3, 0.3),\n                xlabel = \"x [km]\",\n                ylabel = \"η [m]\")\n\nplot_mask = plot(grid.x/1e3, mask,          # divide with 1e3 to convert m -> km\n                 color = :gray,\n                legend = :false,\n             linewidth = [3 2],\n                 alpha = 0.7,\n                 xlims = (-Lx/2e3, Lx/2e3), # divide with 1e3 to convert m -> km\n                xlabel = \"x [km]\",\n                ylabel = \"mask\")\n\ntitle = plot(title = \"Small-scale noise\",\n              grid = false,\n          showaxis = false,\n            xticks = [],\n            yticks = [],\n     bottom_margin = -20Plots.px)\n\nplot(title, plot_noise, plot_mask,\n           layout = @layout([A{0.01h}; [B; C]]),\n             size = (600, 400))\n             \n# Sum the Gaussian bump and the noise and then call `set_uvη!()` to set the initial condition to the problem `prob`.\n\nη0 = @. gaussian_bump + η_noise\nu0 = zeros(grid.nx)\nv0 = zeros(grid.nx)\n\nset_uvη!(prob, u0, v0, η0)\n\nplot(grid.x/1e3, η0,    # divide with 1e3 to convert m -> km\n     color = :black,\n    legend = false,\n linewidth = 2,\n     alpha = 0.7,\n     xlims = (-Lx/2e3, Lx/2e3),\n    xlabel = \"x [km]\",\n    ylabel = \"η [m]\",\n     title = \"initial surface elevation, η(x, t=0)\",\n      size = (600, 260))\n\n\n# ## Visualizing the simulation\n\n# We define a function that plots the surface elevation ``\\eta`` and the \n# depth-integrated velocities ``u`` and ``v``.\n\nfunction plot_output(prob)\n  plot_η = plot(grid.x/1e3, vars.η,         # divide with 1e3 to convert m -> km\n                 color = :blue,\n                legend = false,\n             linewidth = 2,\n                 alpha = 0.7,\n                 xlims = (-Lx/2e3, Lx/2e3), # divide with 1e3 to convert m -> km\n                xlabel = \"x [km]\",\n                ylabel = \"η [m]\")\n\n  plot_u = plot(grid.x/1e3, vars.u,         # divide with 1e3 to convert m -> km\n                 color = :red,\n                legend = false,\n             linewidth = 2,\n                 alpha = 0.7,\n                 xlims = (-Lx/2e3, Lx/2e3), # divide with 1e3 to convert m -> km\n                 ylims = (-0.3, 0.3),\n                xlabel = \"x [km]\",\n                ylabel = \"u [m s⁻¹]\")\n\n  plot_v = plot(grid.x/1e3, vars.v,         # divide with 1e3 to convert m -> km\n                 color = :green,\n                legend = false,\n             linewidth = 2,\n                 alpha = 0.7,\n                 xlims = (-Lx/2e3, Lx/2e3), # divide with 1e3 to convert m -> km\n                 ylims = (-0.3, 0.3),\n                xlabel = \"x [km]\",\n                ylabel = \"v [m s⁻¹]\")\n\n  Ld = @sprintf \"%.2f\" sqrt(g*H)/f /1e3     # divide with 1e3 to convert m -> km\n  plottitle = \"Deformation radius √(gh) / f = \"*string(Ld)*\" km\"\n\n  title = plot(title = plottitle,\n                grid = false,\n            showaxis = false,\n              xticks = [],\n              yticks = [],\n       bottom_margin = -30Plots.px)\n  \n  return plot(title, plot_η, plot_u, plot_v, \n           layout = @layout([A{0.01h}; [B; C; D]]),\n             size = (600, 800))\nend\nnothing # hide\n\n\n# ## Time-stepping the `Problem` forward\n\n# We time-step the `Problem` forward in time. We update variables by calling \n# `updatevars!()` and we also update the plot. We enclose the `for` loop in \n# an `@animate` macro to produce an animation of the solution.\n\np = plot_output(prob)\n\nanim = @animate for j = 0:nsteps\n  updatevars!(prob)\n    \n  p[2][1][:y] = vars.η    # updates the plot for η\n  p[2][:title] = \"t = \" * @sprintf(\"%.1f\", prob.clock.t/60) * \" min\" # updates time in the title\n  p[3][1][:y] = vars.u    # updates the plot for u\n  p[4][1][:y] = vars.v    # updates the plot for v\n\n  stepforward!(prob)\nend\n\nmp4(anim, \"onedshallowwater.mp4\", fps=18)\n\n\n# ## Geostrophic balance\n\n# It is instructive to compare the solution for ``v`` with its geostrophically balanced approximation, ``f \\widehat{\\bm{z}} \\times \\bm{u}_{\\rm geostrophic} = - g \\bm{\\nabla} \\eta``, i.e.,\n#\n# ```math\n# \\begin{aligned}\n# v_{\\rm geostrophic} & =   \\frac{g}{f} \\frac{\\partial \\eta}{\\partial x} \\ , \\\\\n# u_{\\rm geostrophic} & = - \\frac{g}{f} \\frac{\\partial \\eta}{\\partial y} = 0 \\ .\n# \\end{aligned}\n# ```\n# The geostrophic solution should capture well the the behavior of the flow in \n# the center of the domain, after small-scale disturbances propagate away.\n\nu_geostrophic = zeros(grid.nx)  # -g/f ∂η/∂y = 0\nv_geostrophic = params.g / params.f * irfft(im * grid.kr .* vars.ηh, grid.nx)  #g/f ∂η/∂x\n\nplot_u = plot(grid.x/1e3, [vars.u u_geostrophic], # divide with 1e3 to convert m -> km\n                 color = [:red :purple],\n                labels = [\"u\" \"- g/f ∂η/∂y\"],\n             linewidth = [3 2],\n                 alpha = 0.7,\n                 xlims = (-Lx/2e3, Lx/2e3),       # divide with 1e3 to convert m -> km\n                 ylims = (-0.3, 0.3),\n                xlabel = \"x [km]\",\n                ylabel = \"u [m s⁻¹]\")\n\nplot_v = plot(grid.x/1e3, [vars.v v_geostrophic], # divide with 1e3 to convert m -> km\n                 color = [:green :purple],\n                labels = [\"v\" \"g/f ∂η/∂x\"],\n             linewidth = [3 2],\n                 alpha = 0.7,\n                 xlims = (-Lx/2e3, Lx/2e3),       # divide with 1e3 to convert m -> km\n                 ylims = (-0.3, 0.3),\n                xlabel = \"x [km]\",\n                ylabel = \"v [m s⁻¹]\")\n\ntitle = plot(title = \"Geostrophic balance\",\n              grid = false,\n          showaxis = false,\n            xticks = [],\n            yticks = [],\n     bottom_margin = -20Plots.px)\n\nplot(title, plot_u, plot_v,\n           layout = @layout([A{0.01h}; [B; C]]),\n             size = (600, 400))\n", "meta": {"hexsha": "7a0cf13421628b44fa37cd9f79da2d484886b65a", "size": 16599, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/OneDShallowWaterGeostrophicAdjustment.jl", "max_stars_repo_name": "navidcy/FourierFlows.jl", "max_stars_repo_head_hexsha": "75402b443adbf8b44cd3f32eb3bf80644496509c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 113, "max_stars_repo_stars_event_min_datetime": "2018-02-10T06:01:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T16:20:29.000Z", "max_issues_repo_path": "examples/OneDShallowWaterGeostrophicAdjustment.jl", "max_issues_repo_name": "navidcy/FourierFlows.jl", "max_issues_repo_head_hexsha": "75402b443adbf8b44cd3f32eb3bf80644496509c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 197, "max_issues_repo_issues_event_min_datetime": "2018-01-04T00:09:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T21:48:31.000Z", "max_forks_repo_path": "examples/OneDShallowWaterGeostrophicAdjustment.jl", "max_forks_repo_name": "navidcy/FourierFlows.jl", "max_forks_repo_head_hexsha": "75402b443adbf8b44cd3f32eb3bf80644496509c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2018-01-29T17:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-08T01:02:08.000Z", "avg_line_length": 37.2174887892, "max_line_length": 194, "alphanum_fraction": 0.6041930237, "num_tokens": 5088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7561201047352754}}
{"text": "\n\"\"\"\nNon-linear grid.\n\n- `nonlinear = 1` should make it uniform\n- `nonlinear > 1` concentrates around xlow\n- `nonlinear < 1` concentrates around xhigh\n\n\"\"\"\nfunction gridpoints(xlow, xhigh, n, nonlinear)\n    n < 3 && error(\"Use more points for irregular grid\")\n\n    if nonlinear != 1\n        x = fill(0., n)\n        x[1] = xlow\n        for i in 2:(n-1)\n            x[i]=x[i-1] + (xhigh - x[i-1])/(n-i+1)^nonlinear\n        end\n        x[n]=xhigh\n        return x\n    end\n\n    return collect(range(xlow, xhigh, length=n))\nend\n", "meta": {"hexsha": "519daf26a604c90500d2fb6486dc442d67fffe25", "size": 523, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gridpoints.jl", "max_stars_repo_name": "pereiragc/Econlite.jl", "max_stars_repo_head_hexsha": "4ee2664231bac4ba62b38bb85abcd7129da6bf09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gridpoints.jl", "max_issues_repo_name": "pereiragc/Econlite.jl", "max_issues_repo_head_hexsha": "4ee2664231bac4ba62b38bb85abcd7129da6bf09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gridpoints.jl", "max_forks_repo_name": "pereiragc/Econlite.jl", "max_forks_repo_head_hexsha": "4ee2664231bac4ba62b38bb85abcd7129da6bf09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.92, "max_line_length": 60, "alphanum_fraction": 0.5659655832, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.919642526773001, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7561200894785032}}
{"text": "using Distributions, Gadfly, Random\nusing Turing, MCMCChains\nTuring.turnprogress(false)  # turn off the progress monitor\n\n\nRandom.seed!(3)\n\n\n# Construct the data points\nN = 30\nμs = [[0., 0.], [5., 5.]]\nx1 = rand(MvNormal(μs[1], 1.), N)\nx2 = rand(MvNormal(μs[2], 1.), N)\nx = hcat([x1, x2]...)\nplot(x=x[1,:], y=x[2,:])\n\n\n# Define the probabilistic model\n@model GaussianMixtureModel(x) = begin\n    K, N = size(x)\n\n    # Global variables\n    μ = 0.\n    σ = 1.\n    μ1 ~ Normal(μ, σ)\n    μ2 ~ Normal(μ, σ)\n    locs = [μ1, μ2]\n    α = 1.\n    weights ~ Dirichlet(K, α)  # latent\n    # weights = ones(K) / K;  # observed\n\n    # Local context\n    z = Vector{Int64}(undef, N)\n    for i in 1:N\n        z[i] ~ Categorical(weights)\n        x[:,i] ~ MvNormal([locs[z[i]], locs[z[i]]], 1.)\n    end\n    return z  # only return *latent* local variables\nend\n\ngmm_model = GaussianMixtureModel(x);\n\n\n# Perform MCMC inference\ngmm_sampler = Gibbs(\n    PG(100, :z),  # Particle Gibbs (discrete)\n    HMC(0.05, 10, :μ1, :μ2, :weights)  # Hamiltonian Monte Carlo (continuous)\n    # HMC(0.05, 10, :μ1, :μ2, )  # Hamiltonian Monte Carlo (continuous)\n);\n@time chain = sample(gmm_model, gmm_sampler, 100);\n\n\n\n\n\n\n\nids = findall(map(name -> occursin(\"μ\", name), names(chain)));\np=plot(chain[:, ids, :], legend=true, labels = [\"Mu 1\" \"Mu 2\"], colordim=:parameter)\n\n\nchain = chain[:, :, 1];\n\nfunction predict(x, y, w, μ)\n    # Use log-sum-exp trick for numeric stability.\n    return Turing.logaddexp(\n        log(w[1]) + logpdf(MvNormal([μ[1], μ[1]], 1.), [x, y]),\n        log(w[2]) + logpdf(MvNormal([μ[2], μ[2]], 1.), [x, y])\n    )\nend\n\ncontour(range(-5, stop = 3), range(-6, stop = 2),\n    (x, y) -> predict(x, y, [0.5, 0.5], [mean(chain[:μ1].value), mean(chain[:μ2].value)])\n)\nscatter!(x[1,:], x[2,:], legend = false, title = \"Synthetic Dataset\")\n\n\nassignments = collect(skipmissing(mean(chain[:k].value, dims=1).data))\nscatter(x[1,:], x[2,:],\n    legend = false,\n    title = \"Assignments on Synthetic Dataset\",\n    zcolor = assignments)\n", "meta": {"hexsha": "8f9693bcc27f7e47864cc8171b996696faa8051c", "size": 2007, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/gmm.jl", "max_stars_repo_name": "cswaney/Turing.jl", "max_stars_repo_head_hexsha": "391d01f5b7410843654852d3a2422be9305c2ccc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/gmm.jl", "max_issues_repo_name": "cswaney/Turing.jl", "max_issues_repo_head_hexsha": "391d01f5b7410843654852d3a2422be9305c2ccc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/gmm.jl", "max_forks_repo_name": "cswaney/Turing.jl", "max_forks_repo_head_hexsha": "391d01f5b7410843654852d3a2422be9305c2ccc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1807228916, "max_line_length": 89, "alphanum_fraction": 0.5899352267, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.756120085279068}}
{"text": "\nusing ParameterizedFunctions, OrdinaryDiffEq, DiffEqParamEstim\nusing BlackBoxOptim, NLopt, Plots,QuadDIRECT\ngr(fmt=:png)\n\n\nloc_bounds = Tuple{Float64,Float64}[(0, 1), (0, 1), (0, 1), (0, 1)]\nglo_bounds = Tuple{Float64,Float64}[(0, 5), (0, 5), (0, 5), (0, 5)]\nloc_init = [0.5,0.5,0.5,0.5]\nglo_init = [2.5,2.5,2.5,2.5]\n\n\nfitz = @ode_def FitzhughNagumo begin\n  dv = v - v^3/3 -w + l\n  dw = τinv*(v +  a - b*w)\nend a b τinv l\n\n\np = [0.7,0.8,0.08,0.5]              # Parameters used to construct the dataset\nr0 = [1.0; 1.0]                     # initial value\ntspan = (0.0, 30.0)                 # sample of 3000 observations over the (0,30) timespan\nprob = ODEProblem(fitz, r0, tspan,p)\ntspan2 = (0.0, 3.0)                 # sample of 300 observations with a timestep of 0.01\nprob_short = ODEProblem(fitz, r0, tspan2,p)\n\n\ndt = 30.0/3000\ntf = 30.0\ntinterval = 0:dt:tf\nt  = collect(tinterval)\n\n\nh = 0.01\nM = 300\ntstart = 0.0\ntstop = tstart + M * h\ntinterval_short = 0:h:tstop\nt_short = collect(tinterval_short)\n\n\n#Generate Data\ndata_sol_short = solve(prob_short,Vern9(),saveat=t_short,reltol=1e-9,abstol=1e-9)\ndata_short = convert(Array, data_sol_short) # This operation produces column major dataset obs as columns, equations as rows\ndata_sol = solve(prob,Vern9(),saveat=t,reltol=1e-9,abstol=1e-9)\ndata = convert(Array, data_sol)\n\n\nplot(data_sol_short)\n\n\nplot(data_sol)\n\n\nobj_short = build_loss_objective(prob_short,Tsit5(),L2Loss(t_short,data_short),tstops=t_short)\nres1 = bboptimize(obj_short;SearchRange = glo_bounds, MaxSteps = 7e3)\n# Lower tolerance could lead to smaller fitness (more accuracy)\n\n\nobj_short = build_loss_objective(prob_short,Tsit5(),L2Loss(t_short,data_short),tstops=t_short,reltol=1e-9)\nres1 = bboptimize(obj_short;SearchRange = glo_bounds, MaxSteps = 7e3)\n# Change in tolerance makes it worse\n\n\nobj_short = build_loss_objective(prob_short,Vern9(),L2Loss(t_short,data_short),tstops=t_short,reltol=1e-9,abstol=1e-9)\nres1 = bboptimize(obj_short;SearchRange = glo_bounds, MaxSteps = 7e3)\n# using the moe accurate Vern9() reduces the fitness marginally and leads to some increase in time taken\n\n\nobj_short = build_loss_objective(prob_short,Vern9(),L2Loss(t_short,data_short),tstops=t_short,reltol=1e-9,abstol=1e-9)\n\n\nopt = Opt(:GN_ORIG_DIRECT_L, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[5.0,5.0,5.0,5.0])\nmin_objective!(opt, obj_short.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 10000)\n@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)\n\n\nopt = Opt(:GN_CRS2_LM, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[5.0,5.0,5.0,5.0])\nmin_objective!(opt, obj_short.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 10000)\n@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)\n\n\nopt = Opt(:GN_ISRES, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[5.0,5.0,5.0,5.0])\nmin_objective!(opt, obj_short.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 10000)\n@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)\n\n\nopt = Opt(:GN_ESCH, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[5.0,5.0,5.0,5.0])\nmin_objective!(opt, obj_short.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 10000)\n@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)\n\n\nopt = Opt(:LN_BOBYQA, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[1.0,1.0,1.0,1.0])\nmin_objective!(opt, obj_short.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 10000)\n@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)\n\n\nopt = Opt(:LN_NELDERMEAD, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[1.0,1.0,1.0,1.0])\nmin_objective!(opt, obj_short.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 10000)\n@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)\n\n\nopt = Opt(:LD_SLSQP, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[1.0,1.0,1.0,1.0])\nmin_objective!(opt, obj_short.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 10000)\n@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)\n\n\nopt = Opt(:LN_COBYLA, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[1.0,1.0,1.0,1.0])\nmin_objective!(opt, obj_short.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 10000)\n@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)\n\n\nopt = Opt(:LN_NEWUOA_BOUND, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[1.0,1.0,1.0,1.0])\nmin_objective!(opt, obj_short.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 10000)\n@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)\n\n\nopt = Opt(:LN_PRAXIS, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[1.0,1.0,1.0,1.0])\nmin_objective!(opt, obj_short.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 10000)\n@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)\n\n\nopt = Opt(:LN_SBPLX, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[1.0,1.0,1.0,1.0])\nmin_objective!(opt, obj_short.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 10000)\n@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)\n\n\nopt = Opt(:LD_MMA, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[1.0,1.0,1.0,1.0])\nmin_objective!(opt, obj_short.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 10000)\n@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)\n\n\nobj = build_loss_objective(prob,Vern9(),L2Loss(t,data),tstops=t,reltol=1e-9,abstol=1e-9)\nres1 = bboptimize(obj;SearchRange = glo_bounds, MaxSteps = 4e3)\n\n\nopt = Opt(:GN_ORIG_DIRECT_L, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[5.0,5.0,5.0,5.0])\nmin_objective!(opt, obj.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 10000)\n@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)\n\n\nopt = Opt(:GN_CRS2_LM, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[5.0,5.0,5.0,5.0])\nmin_objective!(opt, obj.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 20000)\n@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)\n\n\nopt = Opt(:GN_ISRES, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[5.0,5.0,5.0,5.0])\nmin_objective!(opt, obj.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 50000)\n@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)\n\n\nopt = Opt(:GN_ESCH, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[5.0,5.0,5.0,5.0])\nmin_objective!(opt, obj.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 20000)\n@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)\n\n\nopt = Opt(:LN_BOBYQA, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[1.0,1.0,1.0,1.0])\nmin_objective!(opt, obj.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 10000)\n@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)\n\n\nopt = Opt(:LN_NELDERMEAD, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[1.0,1.0,1.0,1.0])\nmin_objective!(opt, obj.cost_function2)\nxtol_rel!(opt,1e-9)\nmaxeval!(opt, 10000)\n@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)\n\n\nopt = Opt(:LD_SLSQP, 4)\nlower_bounds!(opt,[0.0,0.0,0.0,0.0])\nupper_bounds!(opt,[1.0,1.0,1.0,1.0])\nmin_objective!(opt, obj.cost_function2)\nxtol_rel!(opt,1e-12)\nmaxeval!(opt, 10000)\n@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)\n\n\nobj_short = build_loss_objective(prob_short,Tsit5(),L2Loss(t_short,data_short),tstops=t_short)\nlower = [0,0,0,0]\nupper = [1,1,1,1]\nsplits = ([0,0.3,0.7],[0,0.3,0.7],[0,0.3,0.7],[0,0.3,0.7])\n@time root, x0 = analyze(obj_short,splits,lower,upper)\n\n\nminimum(root)\n\n\nobj = build_loss_objective(prob,Vern9(),L2Loss(t,data),tstops=t,reltol=1e-9,abstol=1e-9)\nlower = [0,0,0,0]\nupper = [5,5,5,5]\nsplits = ([0,0.5,1],[0,0.5,1],[0,0.5,1],[0,0.5,1])\n@time root, x0 = analyze(obj_short,splits,lower,upper)\n\n\nminimum(root)\n\n", "meta": {"hexsha": "1936a10ba5a159da52aab28280d91f15868141a4", "size": 7471, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ParameterEstimation/FitzHughNagumoParameterEstimation.jl", "max_stars_repo_name": "jamesjscully/DiffEqBenchmarks.jl", "max_stars_repo_head_hexsha": "4a47f59717f3166864fa4f1b96a0faa5a0db7764", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-23T11:26:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T11:46:34.000Z", "max_issues_repo_path": "script/ParameterEstimation/FitzHughNagumoParameterEstimation.jl", "max_issues_repo_name": "jamesjscully/DiffEqBenchmarks.jl", "max_issues_repo_head_hexsha": "4a47f59717f3166864fa4f1b96a0faa5a0db7764", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-12T12:07:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-23T10:04:12.000Z", "max_forks_repo_path": "script/ParameterEstimation/FitzHughNagumoParameterEstimation.jl", "max_forks_repo_name": "jamesjscully/DiffEqBenchmarks.jl", "max_forks_repo_head_hexsha": "4a47f59717f3166864fa4f1b96a0faa5a0db7764", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-12T00:28:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T00:28:16.000Z", "avg_line_length": 28.0864661654, "max_line_length": 124, "alphanum_fraction": 0.702851024, "num_tokens": 3072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.7561200850864469}}
{"text": "# Copyright (c) 2021\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nusing LinearAlgebra; \n\n\"\"\"\n    L0EM(A::Matrix{Float64}, b::Vector{Float64}; maxiter=100, epsilon=0.01)\n\nFind the solution to Ax=b using an efficient EM algoritm that directly solves\nthe L0 optimization problem. \n\n\n### Input\n\n- `A`       -- Matrix: Ax=b \n- `b`       -- Vector: Ax=b\n- `maxiter` -- (optional) number of optmization iterations \n- `epsilon` -- (optional) threshold to stop optimizing\n- `lambda`  -- (optional) regularization\n\n### Output\n\nSolution to Ax=b (Vector{Float64})\n\n### Example\n\njulia> A = randn(10, 100);\njulia> b = randn(10); \njulia> x = L0EM(A, b, maxiter=5, epsilon=.01);\njulia> println(x)\n\n### Algorithm\n\nThis function implements Liu and Li's L0EM algorithms in https://arxiv.org/pdf/1407.7508v1.pdf. \n\n\"\"\"\nfunction L0EM(A::Matrix{Float64}, \n              b::Vector{Float64}; \n              lambda=.001, \n              epsilon=.001, \n              maxiter=50)\n    local n, p, theta, A_eta, eta;\n    eps_stop = .01; \n    eps_zero = .01; \n    n, p = size(A);\n    eye = Matrix{Float64}(I, p, p);\n\n    # get the initial solution \n    theta = inv(A'*A + lambda*eye)*A'*b;\n\n    # continue to optimize theta \n    for i = 1:maxiter \n        eta = theta;\n\n        # copy the squared eta terms into a matrix so we can use the hammard product. \n        A_eta = repeat(eta.^2, 1, n)';\n        A_eta = A_eta.*A;\n        \n        # update theta \n        theta = inv(A_eta'*A + lambda*eye)*A_eta'*b;\n\n        # check to break the loop due to a small difference in norm \n        if norm(theta-eta, 2) <= epsilon\n            break; \n        end\n    end\n    x = theta;\n    i = abs.(x) .< epsilon;\n    x[i] = zeros(sum(i));\n    return x; \nend\n\n\n# A = randn(10, 50); b = randn(10);\n# x = L0EM(A, b);\n# println(x)\n", "meta": {"hexsha": "027fb93bbbe2951372ed5dd109f29929c7f3afbd", "size": 2801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/L0EM.jl", "max_stars_repo_name": "gditzler/CompSense.jl", "max_stars_repo_head_hexsha": "c4dee7f673f8415858b0c6d013247c66c5a8b3c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/L0EM.jl", "max_issues_repo_name": "gditzler/CompSense.jl", "max_issues_repo_head_hexsha": "c4dee7f673f8415858b0c6d013247c66c5a8b3c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/L0EM.jl", "max_forks_repo_name": "gditzler/CompSense.jl", "max_forks_repo_head_hexsha": "c4dee7f673f8415858b0c6d013247c66c5a8b3c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7978723404, "max_line_length": 96, "alphanum_fraction": 0.6526240628, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.756085594074768}}
{"text": "\n# setting working directory\ncd(\"/Volumes/SSD Hans/Github/MacroFall2020/AdvMacro\")\n\n#Defining vars\na = 1/3\nb = 0.6\nk_star = (a*b)^(1/(1-a))\nr = 1/b\n\n# Initializing array for loop\nm, n = 100,2\nK = fill(0.0, (m, n))\n\n#defining policy fn\ng = x -> a*b*(x^a)\n\n# loop for capital\nk = 0.8*k_star\nfor i in 1:m\n    K[i, 1] = k\n    K[i, 2] = g(K[i,1])\n    global k = K[i, 2]\nend\n\n# defining fn's for the rest of the variables\nw = x -> (1-a)x^a\ny = x -> x^a\nc = (p,q) -> y(p)-q\nr = x -> a*(x^(a-1))\nint = r.(K[1:100,2])\nwage = w.(K[1:100,1])\noutput = y.(K[1:100,1])\ncons = c.(K[1:100,1],K[1:100,2])\n\n# importing packages for plotting\nimport Pkg; Pkg.add(\"Plots\")\nusing Plots\ngr()\n\n# plotting capital\nplot(1:10,fill(k_star,10), label=\"capital SS\")\nplot!(1:10,K[1:10,1], label=\"capital path\", linestyle = :dot, legend = :bottomright)\nxlabel!(\"t\")\ntitle!(\"Capital\")\nsavefig(\"graphs/capital\")\n\n# plotting output\n\nplot(1:10,fill(y(k_star),10), label=\"output SS\")\nplot!(1:10,output[1:10], label=\"output path\", linestyle = :dot, legend = :bottomright)\nxlabel!(\"t\")\ntitle!(\"Output\")\nsavefig(\"graphs/output\")\n\n# plotting consumption\n\nplot(1:10,fill(c(k_star,k_star),10), label=\"consumption SS\")\nplot!(1:10,cons[1:10], label=\"consumption path\", linestyle = :dot, legend = :bottomright)\nxlabel!(\"t\")\ntitle!(\"Consumption\")\nsavefig(\"graphs/consumption\")\n\n# plotting wage\n\nplot(1:10,fill(w(k_star),10), label=\"wage SS\")\nplot!(1:10,wage[1:10], label=\"wage path\", linestyle = :dot, legend = :bottomright)\nxlabel!(\"t\")\ntitle!(\"Wage\")\nsavefig(\"graphs/wage\")\n\n# plotting capital rental rate\nplot(1:10,fill(r(k_star),10), label=\"capital rental rate SS\")\nplot!(1:10,int[1:10], label=\"rate path\", linestyle = :dot, legend = :topright)\nxlabel!(\"t\")\ntitle!(\"Capital rental rate\")\nsavefig(\"graphs/capitalr\")\n\n# Increase in productivity permanently by 5%\n\nk_starp = (a*b*1.5)^(1/(1-a))\n#defining policy fn with productivity increases\ng1 = x -> a*b*1.05*(x^a)\n\n# Initializing array for loop\nK1 = fill(0.0, (m, n))\n\n# loop for capital\nk1 = k_starp\nfor i in 1:m\n    K1[i, 1] = k1\n    K1[i, 2] = g(K[i,1])\n    global k1 = K[i, 2]\nend\n\n# defining fn's for the rest of the variables\nw1 = x -> (1-a)*(x^a) #does not change\ny1 = x -> 1.5*(x^a)\nc1 = (p,q) -> y(p)-q #does not change\nr1 = x -> a*(1.5*x^(a-1))\nint_p = r1.(K1[1:100,2])\nwage_p = w1.(K1[1:100,1])\noutput_p = y1.(K1[1:100,1])\ncons_p = c1.(K1[1:100,1],K1[1:100,2])\n\n\n# plotting capital\nplot(1:10,fill(k_star,10), label=\"capital SS\")\nplot!(1:10,K1[1:10,1], label=\"capital path\", linestyle = :dot, legend = :bottomright)\nxlabel!(\"t\")\ntitle!(\"Capital (productivity increase)\")\nsavefig(\"graphs/capitalp\")\n\n# plotting output\n\nplot(1:10,fill(y1(k_star),10), label=\"output SS\")\nplot!(1:10,output_p[1:10], label=\"output path\", linestyle = :dot, legend = :bottomright)\nxlabel!(\"t\")\ntitle!(\"Output (productivity increase)\")\nsavefig(\"graphs/outputp\")\n\n# plotting consumption\n\nplot(1:10,fill(c1(k_star,k_star),10), label=\"consumption SS\")\nplot!(1:10,cons_p[1:10], label=\"consumption path\", linestyle = :dot, legend = :bottomright)\nxlabel!(\"t\")\ntitle!(\"Consumption (productivity increase)\")\nsavefig(\"graphs/consumptionp\")\n\n# plotting wage\n\nplot(1:10,fill(w1(k_star),10), label=\"wage SS\")\nplot!(1:10,wage_p[1:10], label=\"wage path\", linestyle = :dot, legend = :bottomright)\nxlabel!(\"t\")\ntitle!(\"Wage (productivity increase)\")\nsavefig(\"graphs/wagep\")\n\n# plotting capital rental rate\nplot(1:10,fill(r1(k_star),10), label=\"capital rental rate SS\")\nplot!(1:10,int_p[1:10], label=\"rate path\", linestyle = :dot, legend = :topright)\nxlabel!(\"t\")\ntitle!(\"Capital rental rate (productivity increase)\")\nsavefig(\"graphs/capitalrp\")\n", "meta": {"hexsha": "d9dd2a8f699e301bd642e0d076afe876af8ffc84", "size": 3622, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Assignment1/A1.jl", "max_stars_repo_name": "py-r-hans/AdvMacro", "max_stars_repo_head_hexsha": "338dda55de397fc1da40e2fb80f29f045714c206", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignment1/A1.jl", "max_issues_repo_name": "py-r-hans/AdvMacro", "max_issues_repo_head_hexsha": "338dda55de397fc1da40e2fb80f29f045714c206", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment1/A1.jl", "max_forks_repo_name": "py-r-hans/AdvMacro", "max_forks_repo_head_hexsha": "338dda55de397fc1da40e2fb80f29f045714c206", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1527777778, "max_line_length": 91, "alphanum_fraction": 0.6573716179, "num_tokens": 1288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7560855901083673}}
{"text": "#=\n\n  Euler #34 in Julia.\n\n  Problem 34\n  \"\"\"\n  145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.\n\n  Find the sum of all numbers which are equal to the sum of the\n  factorial of their digits.\n\n  Note: as 1! = 1 and 2! = 2 are not sums they are not included.\n  \"\"\"\n\n  This Julia program was created by Hakan Kjellerstrand, hakank@gmail.com\n  See also my Julia page: http://www.hakank.org/julia/\n\n=#\n\ninclude(\"Euler.jl\")\n\nfunction factorial_sum(n)\n    # return (split(string(n),\"\").|>i->factorial(parse(Int,i)))|>sum\n    return (digits(n).|>i->factorial(i))|>sum\n\nend\n\n# 0.01974533s\nfunction euler34a()\n    s = 0;\n    for n in 10:100000\n        if n == factorial_sum(n)\n            s += n\n        end\n    end\n    return s\nend\n\n# 0.02070016s\nfunction euler34b()\n    return filter(n->n == factorial_sum(n),10:100000)|>sum\nend\n\n# 0.01983716s\nfunction euler34c()\n    return [n for n in 10:100000 if n == factorial_sum(n)]|>sum\nend\n\n\n# run_euler(euler34a)\n# run_euler(euler34b)\nrun_euler(euler34c)\n", "meta": {"hexsha": "a97660ab45698f43008c3015847f7b144b0a933c", "size": 1004, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/euler34.jl", "max_stars_repo_name": "Wikunia/hakank", "max_stars_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/euler34.jl", "max_issues_repo_name": "Wikunia/hakank", "max_issues_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/euler34.jl", "max_forks_repo_name": "Wikunia/hakank", "max_forks_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 18.9433962264, "max_line_length": 73, "alphanum_fraction": 0.6354581673, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7560855875984512}}
{"text": "using RobustShortestPath\n\ndata = [\n 1   4  79   31  66  28;\n 1   2  59   97  41  93;\n 2   4  31   21  50  40;\n 2   3  90   52  95  38;\n 2   5   9   23  95  59;\n 2   6  32   57  73   7;\n 3   9  89  100  38  21;\n 3   8  66   13   4  72;\n 3   6  68   95  58  58;\n 3   7  47   12  56  20;\n 4   3  14   19  36  84;\n 4   9  95   65  88  42;\n 4   8  88   13  62  54;\n 5   3  44    8  62  53;\n 5   6  83   66  30  19;\n 6   7  33    3   7   8;\n 6   8  37   99  29  46;\n 7  11  79   54  23   3;\n 7  12  10   37  35  43;\n 8   7  95   71  85  56;\n 8  10   0   95  16  64;\n 8  12  30   38  16   3;\n 9  10   5   69  51  71;\n 9  11  44   60  60  17;\n10  13  79   78  16  59;\n10  14  91   59  64  61;\n11  14  53   38  84  77;\n11  15  80   85  78   6;\n11  13  56   23  26  85;\n12  15  75   80  31  38;\n12  14   1  100  18  40;\n13  14  48   28  45  33;\n14  15  25   71  33  56;\n]\n\n\nstart_node = data[:,1] #first column of data\nend_node = data[:,2] #second column of data\np = data[:,3] #third\nq = data[:,4] #fourth\nc = data[:,5] #fifth\nd = data[:,6] #sixth\n\n\n\n\n\n\n\n# Link length vectors for single-uncertain-coefficient robust shortest paths\ncc = p.*c\ndd = (p+q).*(c+d) - p.*c\n\n# Setting origin and destination nodes\norigin = 1\ndestination = 15\nprintln(\"Origin=$origin, Destination=$destination\")\n\nprintln(\"----------------------------------------------------\")\nprintln(\"Single Coefficient Case\")\n# For each Gamma from 0 to 6, obtain the robust shortest path\nknown_cost_solution_one = Dict(0 => 6060, 1=> 15024, 2=> 20864, 3=> 26604, 4=> 31293, 5=> 32291)\nfor Gamma=0:5\n\trobust_path, robust_x, worst_case_cost = get_robust_path(start_node, end_node, cc, dd, Gamma, origin, destination)\n\tprintln(\"Gamma=$Gamma: Robust Path is $(robust_path') and the worst-case cost is $worst_case_cost.\")\n\n    @assert worst_case_cost == known_cost_solution_one[Gamma]\nend\n\n\n\nprintln(\"----------------------------------------------------\")\nprintln(\"Two Coefficient Case\")\n\nfor Gamma_u=1:5\n    for Gamma_v=1:5\n        robust_path, robust_x, worst_case_cost = get_robust_path_two(start_node, end_node, p, q, c, d, Gamma_u, Gamma_v, origin, destination)\n        println(\"(Gamma_u,Gamma_v)=($Gamma_u,$Gamma_v): Robust Path is $(robust_path') and the worst-case cost is $worst_case_cost.\")\n    end\nend\n\ntest_Gamma_u = 5\ntest_Gamma_v = 5\nrobust_path, robust_x, worst_case_cost = get_robust_path_two(start_node, end_node, p, q, c, d, test_Gamma_u, test_Gamma_v, origin, destination)\n\nprintln(worst_case_cost)\n@assert worst_case_cost==32291.0\n\n\n", "meta": {"hexsha": "e9d9b735b223a49fdcdf3f66c8c86daf9bee71ff", "size": 2499, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JuliaPackageMirrors/RobustShortestPath.jl", "max_stars_repo_head_hexsha": "300fe6d8484b714400ee3fab537d42da0bbfd650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2015-11-03T21:24:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T03:23:57.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "JuliaPackageMirrors/RobustShortestPath.jl", "max_issues_repo_head_hexsha": "300fe6d8484b714400ee3fab537d42da0bbfd650", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2015-07-28T22:24:36.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-07T18:38:00.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "JuliaPackageMirrors/RobustShortestPath.jl", "max_forks_repo_head_hexsha": "300fe6d8484b714400ee3fab537d42da0bbfd650", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-07-12T18:06:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T15:21:01.000Z", "avg_line_length": 26.8709677419, "max_line_length": 143, "alphanum_fraction": 0.5906362545, "num_tokens": 1075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7560855873877649}}
{"text": "\"\"\"\n    conductance(h::Hypergraph, subset::Set{Int})::Float64\n\nCalculate unweighted hypergraph conductance of `subset`.\nnote: ∅ ⊊ `subset` ⊊ `1:nhv(h)`\n\nFor more information see `1. Introduction` at:\nSpectral Properties of Hypergraph Laplacian and Approximation Algorithms\nauhtors: T-H. Hubert Chan, Anand Louis, Zhihao Gavin Tang, and Chenzi Zhang\n\"\"\"\nfunction conductance(h::Hypergraph, subset::Set{Int})::Float64\n  if isempty(subset) error(\"`subset` is not allowed empty.\") end\n  if subset == Set(1:nhv(h)) error(\"`subset` is not allowed true subset of `h`.\") end\n  subset2 = setdiff(Set(1:nhv(h)), subset)\n  volS = sum([sum(values(gethyperedges(h, node))) for node in subset])\n  volV_S = sum([sum(values(gethyperedges(h, node))) for node in subset2])\n  cutS = 0\n  for he in 1:nhe(h)\n    he_vertices = keys(getvertices(h, he))\n    if isempty(intersect(he_vertices, subset)) continue end\n    if isempty(intersect(he_vertices, subset2)) continue end\n    cutS += 1\n  end\n  return cutS / min(volS, volV_S)\nend\n", "meta": {"hexsha": "680849be8bc761cd6e44d647e36c6aa8633ddffa", "size": 1009, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algorithms/conductance.jl", "max_stars_repo_name": "Inazuma110/SimpleHypergraphs.jl", "max_stars_repo_head_hexsha": "d84c92c79315ca6c37dabc2090e09c9e6019a39c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algorithms/conductance.jl", "max_issues_repo_name": "Inazuma110/SimpleHypergraphs.jl", "max_issues_repo_head_hexsha": "d84c92c79315ca6c37dabc2090e09c9e6019a39c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithms/conductance.jl", "max_forks_repo_name": "Inazuma110/SimpleHypergraphs.jl", "max_forks_repo_head_hexsha": "d84c92c79315ca6c37dabc2090e09c9e6019a39c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8076923077, "max_line_length": 85, "alphanum_fraction": 0.7086223984, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.756048106323314}}
{"text": "\"\"\"\n    smooth(x_curr::Gaussian, x_next_smoothed::Gaussian, Ah::AbstractMatrix, Qh::AbstractMatrix)\n\nSMOOTH step of the (extended) Kalman smoother, or (extended) Rauch-Tung-Striebel smoother.\nIt is implemented in Joseph Form:\n```math\nm_{n+1}^P = A(h)*m_n\nP_{n+1}^P = A(h)*P_n*A(h) + Q(h)\n\nG = P_n * A(h)^T * (P_{n+1}^P)^{-1}\nm_n^S = m_n + G * (m_{n+1}^S - m_{n+1}^P)\nP_n^S = (I - G*A(h)) P_n (I - G*A(h))^T + G * Q(h) * G + G * P_{n+1}^S * G\n```\n\"\"\"\nfunction smooth(\n    x_curr::Gaussian,\n    x_next_smoothed::Gaussian,\n    Ah::AbstractMatrix,\n    Qh::AbstractMatrix,\n)\n    x_pred = predict(x_curr, Ah, Qh)\n\n    P_p = x_pred.Σ\n    P_p_inv = inv(P_p)\n\n    G = x_curr.Σ * Ah' * P_p_inv\n\n    smoothed_mean = x_curr.μ + G * (x_next_smoothed.μ - x_pred.μ)\n    smoothed_cov =\n        (X_A_Xt(x_curr.Σ, (I - G * Ah)) + X_A_Xt(Qh, G) + X_A_Xt(x_next_smoothed.Σ, G))\n    x_curr_smoothed = Gaussian(smoothed_mean, smoothed_cov)\n    return x_curr_smoothed, G\nend\nfunction smooth(\n    x_curr::SRGaussian,\n    x_next_smoothed::SRGaussian,\n    Ah::AbstractMatrix,\n    Qh::SRMatrix,\n)\n    x_pred = predict(x_curr, Ah, Qh)\n\n    P_p = x_pred.Σ\n    P_p_inv = inv(P_p)\n\n    G = x_curr.Σ * Ah' * P_p_inv\n\n    smoothed_mean = x_curr.μ + G * (x_next_smoothed.μ - x_pred.μ)\n\n    _R = [\n        x_curr.Σ.squareroot' * (I - G * Ah)'\n        Qh.squareroot' * G'\n        x_next_smoothed.Σ.squareroot' * G'\n    ]\n    _, P_s_R = qr(_R)\n    smoothed_cov = SRMatrix(P_s_R')\n\n    x_curr_smoothed = Gaussian(smoothed_mean, smoothed_cov)\n    return x_curr_smoothed, G\nend\n\nfunction smooth!(x_curr, x_next, Ah, Qh, integ, diffusion=1)\n    # x_curr is the state at time t_n (filter estimate) that we want to smooth\n    # x_next is the state at time t_{n+1}, already smoothed, which we use for smoothing\n    @unpack d, q = integ.cache\n    @unpack x_pred = integ.cache\n    @unpack C1, G1, G2, C2 = integ.cache\n\n    # Prediction: t -> t+1\n    predict_mean!(x_pred, x_curr, Ah)\n    predict_cov!(x_pred, x_curr, Ah, Qh, C1, diffusion)\n\n    # Smoothing\n    # G = x_curr.Σ * Ah' * P_p_inv\n    P_p_chol = Cholesky(x_pred.Σ.squareroot, :L, 0)\n    G = rdiv!(_matmul!(G1, x_curr.Σ.mat, Ah'), P_p_chol)\n\n    x_curr.μ .+= G * (x_next.μ .- x_pred.μ)\n\n    # Joseph-Form:\n    M, L = C2.mat, C2.squareroot\n    D = length(x_pred.μ)\n\n    _matmul!(G2, G, Ah)\n    copy!(view(L, 1:D, 1:D), x_curr.Σ.squareroot)\n    _matmul!(view(L, 1:D, 1:D), G2, x_curr.Σ.squareroot, -1.0, 1.0)\n\n    _matmul!(view(L, 1:D, D+1:2D), _matmul!(G2, G, sqrt.(diffusion)), Qh.squareroot)\n    _matmul!(view(L, 1:D, 2D+1:3D), G, x_next.Σ.squareroot)\n\n    # _matmul!(M, L, L')\n    # chol = cholesky!(Symmetric(M), check=false)\n\n    QL =\n        false && issuccess(chol) ? Matrix(chol.U)' :\n        eltype(L) <: Union{Float16,Float32,Float64} ? lq!(L).L : qr(L').R'\n    copy!(x_curr.Σ.squareroot, QL)\n    _matmul!(x_curr.Σ.mat, QL, QL')\n\n    return nothing\nend\n", "meta": {"hexsha": "0c70ff731a375f990aaaab84ca1c74f6eb68d2df", "size": 2876, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/filtering/smooth.jl", "max_stars_repo_name": "nathanaelbosch/ProbNumDiffEq.jl", "max_stars_repo_head_hexsha": "82aa8e911e0f0987b0ddb61e0e7d3ee325d3150a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 57, "max_stars_repo_stars_event_min_datetime": "2021-02-17T21:42:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T23:37:35.000Z", "max_issues_repo_path": "src/filtering/smooth.jl", "max_issues_repo_name": "nathanaelbosch/ProbNumDiffEq.jl", "max_issues_repo_head_hexsha": "82aa8e911e0f0987b0ddb61e0e7d3ee325d3150a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 90, "max_issues_repo_issues_event_min_datetime": "2021-02-18T00:57:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T20:44:20.000Z", "max_forks_repo_path": "src/filtering/smooth.jl", "max_forks_repo_name": "nathanaelbosch/ProbNumDiffEq.jl", "max_forks_repo_head_hexsha": "82aa8e911e0f0987b0ddb61e0e7d3ee325d3150a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2021-02-23T06:36:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:15:25.000Z", "avg_line_length": 28.4752475248, "max_line_length": 95, "alphanum_fraction": 0.6098748261, "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739075, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.7560480991054573}}
{"text": "# https://optimization.mccormick.northwestern.edu/index.php/Disjunctive_inequalities\nusing JuMP\nusing DisjunctiveProgramming\n\nm = Model()\n@variable(m, -5 ≤ x[1:2] ≤ 10)\n@disjunction(\n    m,\n    begin\n        con1[i=1:2], 0 ≤ x[i] ≤ [3,4][i]\n    end,\n    begin\n        con2[i=1:2], [5,4][i] ≤ x[i] ≤ [9,6][i]\n    end,\n    reformulation = :big_m,\n    name = :y\n)\nprint(m)\n\n# ┌ Warning: [con1[1] : x[1] in [0.0, 3.0], con1[2] : x[2] in [0.0, 4.0]] uses the `MOI.Interval` set. Each instance of the interval set has been split into two constraints, one for each bound.\n# ┌ Warning: [con2[1] : x[1] in [5.0, 9.0], con2[2] : x[2] in [4.0, 6.0]] uses the `MOI.Interval` set. Each instance of the interval set has been split into two constraints, one for each bound.\n# Feasibility\n# Subject to\n#  XOR(disj_y) : y[1] + y[2] == 1.0         <- XOR constraint\n#  con1[1,lb] : -x[1] + 5 y[1] <= 5.0      <- left-side of con1[1]\n#  con1[1,ub] : x[1] + 7 y[1] <= 10.0      <- right-side of con1[1]\n#  con1[2,lb] : -x[2] + 5 y[1] <= 5.0      <- left-side of con1[2]\n#  con1[2,ub] : x[2] + 6 y[1] <= 10.0      <- right-side of con1[2]\n#  con2[1,lb] : -x[1] + 10 y[2] <= 5.0     <- left-side of con2[1]\n#  con2[1,ub] : x[1] + y[2] <= 10.0        <- right-side of con2[1]\n#  con2[2,lb] : -x[2] + 9 y[2] <= 5.0      <- left-side of con2[2]\n#  con2[2,ub] : x[2] + 4 y[2] <= 10.0      <- right-side of con2[2]\n#  x[1] >= -5.0                             <- varaible bounds\n#  x[2] >= -5.0                             <- variable bounds\n#  x[1] <= 10.0                             <- variable bounds\n#  x[2] <= 10.0                             <- variable bounds\n#  y[1] >= 0.0                              <- lower bound on binary\n#  y[2] >= 0.0                              <- lower bound on binary\n#  y[1] <= 1.0                              <- upper bound on binary\n#  y[2] <= 1.0                              <- upper bound on binary\n#  y[1] binary                              <- indicator variable (1st disjunct) is binary\n#  y[2] binary                              <- indicator variable (2nd disjunct) is binary", "meta": {"hexsha": "f7d9cc6d4adfd90a4db0d19f5d4f030dc79ef050", "size": 2097, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ex2.jl", "max_stars_repo_name": "shivankj11/DisjunctiveProgramming.jl", "max_stars_repo_head_hexsha": "fcf3844092d59e31a0cbd2788014b411309fe1dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/ex2.jl", "max_issues_repo_name": "shivankj11/DisjunctiveProgramming.jl", "max_issues_repo_head_hexsha": "fcf3844092d59e31a0cbd2788014b411309fe1dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ex2.jl", "max_forks_repo_name": "shivankj11/DisjunctiveProgramming.jl", "max_forks_repo_head_hexsha": "fcf3844092d59e31a0cbd2788014b411309fe1dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.9285714286, "max_line_length": 193, "alphanum_fraction": 0.4802098236, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7560166893785121}}
{"text": "# Script to generate Figures 16 and 17\nusing TestImages, Plots, SparseArrays, LinearAlgebra, Wavelets, MultiscaleGraphSignalTransforms\ninclude(\"auxilaries.jl\")\n\n# Set up the resolution and display size\ngr(dpi=200, size=(800,600))\n\n# Load the cameraman image and subsample it to make it as 128x128 image\nimg = testimage(\"camera\");\nmatrix = convert(Array{Float64,2}, img)[1:4:512,1:4:512]\nm, n = size(matrix)\n\n# Fig. 16a\ndisplay(heatmap(matrix, ratio=1, yaxis =:flip, showaxis = false, ticks = false,\n    color = :grays, clim = (0,1), colorbar = false))\nsavefig(\"cameraman.pdf\")\nsavefig(\"cameraman.png\")\n\n# Now, let's compute the weight matrix based on the Gaussian affinity\n# of the small windows (or radius r) around pixels and the pixel locations.\n# Set up the key parameters\nr = 5; # specify radius of neighbors\nσ = 0.007\n# Do the weight matrix computation\nW007 = image_Gaussian_affinity(matrix, r, σ)    \n\n# Preprocess to generate G (GraphSig struct) and GP (GraphPart struct)\n# Note that GraphSig requires a matrix data even if it is just a one vector, i.e.,\n# f = matrix[:] does not work!\nG007 = GraphSig(W007, f = reshape(matrix, (length(matrix), 1)))\nGP007 = partition_tree_fiedler(G007)\ndmatrix007 = ghwt_analysis!(G007, GP=GP007)\n\n# Construct or search the specific basis\n# Haar\nBS_haar007 = bs_haar(GP007)\ndvec_haar007 = dmatrix2dvec(dmatrix007, GP007, BS_haar007)\n\n# eGHWT\ndvec_eghwt007, BS_eghwt007 = eghwt_bestbasis(dmatrix007, GP007)\n\n# Generate Fig. 17a\ntop_vectors_plot2(dvec_eghwt007, m, n, BS_eghwt007, GP007)\nsavefig(\"cameraman_eghwt09_sigma007.pdf\")\nsavefig(\"cameraman_eghwt09_sigma007.png\")\n\n# Now change the σ value\nσ = 0.07\nW07 = image_Gaussian_affinity(matrix, r, σ)    \n# Preprocess to generate G (GraphSig struct) and GP (GraphPart struct)\nG07 = GraphSig(W07, f = reshape(matrix, (length(matrix), 1)))\nGP07 = partition_tree_fiedler(G07)\ndmatrix07 = ghwt_analysis!(G07, GP=GP07)\n\n# Construct or search the specific basis\n# Haar\nBS_haar07 = bs_haar(GP07)\ndvec_haar07 = dmatrix2dvec(dmatrix07, GP07, BS_haar07)\n# eGHWT\ndvec_eghwt07, BS_eghwt07 = eghwt_bestbasis(dmatrix07, GP07)\n# Generate Fig. 17b\ntop_vectors_plot2(dvec_eghwt07, m, n, BS_eghwt07, GP07)\nsavefig(\"cameraman_eghwt09_sigma07.pdf\")\nsavefig(\"cameraman_eghwt09_sigma07.png\")\n# Finally, do the classical Haar transform in Wavelets.jl\ndvec_classichaar = dwt(matrix, wavelet(WT.haar))\n\n# Fig. 16b (Approximation error plot)\nDVEC = [ dvec_classichaar[:], dvec_haar07[:], dvec_eghwt07[:],\n         dvec_haar007[:], dvec_eghwt007[:] ]\nT = [ \"Classical Haar\", \"Graph Haar (σ = 0.07)\", \n      \"eGHWT (σ = 0.07)\", \"Graph Haar (σ = 0.007)\", \n      \"eGHWT (σ = 0.007)\"]\nL = [ (:dashdot,:orange), (:dashdot, :red), (:dashdot, :black),\n      (:solid, :red), (:solid, :black) ]\napprox_error2(DVEC, T, L, 0.5)\nsavefig(\"cameraman_approx_error.pdf\")\nsavefig(\"cameraman_approx_error.png\")\n", "meta": {"hexsha": "8e8244c7bd0d26a9e2d97bf47ce3a0d50c6994f4", "size": 2856, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/paperscripts/eGHWT2021/figs1617.jl", "max_stars_repo_name": "BoundaryValueProblems/MTSG.jl", "max_stars_repo_head_hexsha": "8cf8e2b3035876b5ceda45109b0847a60b581a7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-02T18:39:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-19T15:45:17.000Z", "max_issues_repo_path": "test/paperscripts/eGHWT2021/figs1617.jl", "max_issues_repo_name": "haotian127/MultiscaleGraphSignalTransforms.jl", "max_issues_repo_head_hexsha": "85ba99e505283491ac69e979737bbb712b698a6e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2021-04-27T23:00:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-03T11:03:17.000Z", "max_forks_repo_path": "test/paperscripts/eGHWT2021/figs1617.jl", "max_forks_repo_name": "haotian127/MultiscaleGraphSignalTransforms.jl", "max_forks_repo_head_hexsha": "85ba99e505283491ac69e979737bbb712b698a6e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-04-24T21:46:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T04:32:31.000Z", "avg_line_length": 36.1518987342, "max_line_length": 95, "alphanum_fraction": 0.731092437, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467158, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7560166859622436}}
{"text": "struct SpatialGrid{T <: AbstractFloat }\n    x          :: OffsetVector{T}\n    global_DoF :: Vector{Vector{Int64}}\n    nfree      :: Int64\n    nfixed     :: Int64\n    max_r      :: Int64\n    pt         :: Vector{T} # Quadrature points on (-1,1)\n    wt         :: Vector{T} # Quadrature weights\nend\n\n\"\"\"\n   Φ = shape_funcs(r, ξ)\n\nReturns shape functions `Φ[i,j] = Φ_(i-1)(ξ[j])`.\n\"\"\"\nfunction shape_funcs(r::Int64, ξ::AbstractVector{T}\n                    ) where { T <: AbstractFloat }\n    J = length(ξ)\n    Φ = zeros(T, r, J)\n    for j = 1:J\n        Φ[1,j] = ( 1 - ξ[j] ) / 2\n        Φ[2,j] = ( 1 + ξ[j] ) / 2\n    end\n    P = Array{T}(undef, r, J)\n    legendre_polys!(P, ξ) # P[i,j] = P_(i-1)(ξ[j])\n    for j = 1:J, i = 3:r\n        a = convert(T, 2(2i-3))\n        Φ[i,j] = ( P[i,j] - P[i-2,j] ) / sqrt(a)\n    end\n    return Φ\nend\n\nfunction SpatialGrid(x::OffsetVector{T}, r::Vector{Int64},\n                     bc::Tuple{String,String},\n                     num_x_Gauss_pts::Int64) where { T <: AbstractFloat }\n    P = length(x) - 1\n    @argcheck length(r) == P DimensionMismatch\n    global_DoF = Vector{Vector{Integer}}(undef, P)\n    total =  0\n    max_r = 0\n    for p = 1:P\n        @argcheck r[p] ≥ 2\n        global_DoF[p] = Array{Integer}(undef, r[p])\n        total += r[p]\n        if r[p] ≥ max_r\n            max_r = r[p]\n        end\n    end\n    total -= P-1\n    if bc == (\"essential\", \"essential\")\n        nfixed = 2\n        nfree = total - nfixed\n        global_DoF[1][1] = nfree + 1\n        m = 0\n        if P > 1\n            for j = 2:r[1]\n                m += 1\n                global_DoF[1][j] = m\n            end\n            for p = 2:P-1\n                global_DoF[p][1] = global_DoF[p-1][2]\n                for j = 2:r[p]\n                    m += 1\n                    global_DoF[p][j] = m\n                end\n            end\n            global_DoF[P][1] = global_DoF[P-1][2]\n            global_DoF[P][2] = nfree + 2\n            for j = 3:r[P]\n                m += 1\n                global_DoF[P][j] = m\n            end\n        else\n            global_DoF[1][2] = nfree + 2\n            for j = 3:r[1]\n                global_DoF[1][j] = j-2\n            end\n        end\n    elseif bc == (\"essential\", \"natural\")\n        nfixed = 1\n        nfree = total - nfixed\n        global_DoF[1][1] = nfree + 1\n        m = 0\n        for j = 2:r[1]\n            m += 1\n            global_DoF[1][j] = m\n        end\n        for p = 2:P\n            global_DoF[p][1] = global_DoF[p-1][2]\n            for j = 2:r[p]\n                m += 1\n                global_DoF[p][j] = m\n            end\n        end\n    elseif bc == (\"natural\", \"essential\")\n        nfixed = 1\n        nfree = total - nfixed\n        m = 0\n        for j = 1:r[1]\n            m += 1\n            global_DoF[1][j] = m\n        end\n        for p = 2:P-1\n            global_DoF[p][1] = global_DoF[p-1][2]\n            for j = 2:r[p]\n                m += 1\n                global_DoF[p][j] = m\n            end\n        end\n        global_DoF[P][1] = global_DoF[P-1][2]\n        global_DoF[P][2] = nfree + 1\n        for j = 3:r[P]\n            m += 1\n            global_DoF[P][j] = m\n        end\n    elseif bc == (\"natural\", \"natural\")\n        nfixed = 0\n        nfree = total - nfixed\n        m = 0\n        for j = 1:r[1]\n            m += 1\n            global_DoF[1][j] = m\n        end\n        for p = 2:P\n            global_DoF[p][1] = global_DoF[p-1][2]\n            for j = 2:r[p]\n                m += 1\n                global_DoF[p][j] = m\n            end\n        end\n    else\n        throw(ArgumentError(\"unrecognised boundary conditions\"))\n    end\n    pt, wt = GaussQuadrature.legendre(T, num_x_Gauss_pts)\n    return SpatialGrid{T}(x, global_DoF, nfree, nfixed, max_r, pt, wt)\nend\n\nfunction SpatialGrid(x::OffsetVector{T}, r::Int64,\n                     bc::Tuple{String,String},\n                     num_Gauss_pts) where { T <: AbstractFloat }\n    P = length(x) - 1\n    vecr = fill(r, P)\n    return SpatialGrid(x, vecr, bc, num_Gauss_pts)\nend\n\nfunction ref_element_matrices!(M::Matrix{T}, S::Matrix{T},\n                               κ::T) where { T <: AbstractFloat }\n    sz = size(M, 1)\n    @argcheck size(M, 2) == sz \n    @argcheck size(S) == (sz, sz) \n    @argcheck sz >= 2\n    fill!(M, zero(T))\n    fill!(S, zero(T))\n    two = convert(T, 2)\n    three = convert(T, 3)\n    M[1, 1] = M[2, 2] =  2 / three\n    M[2, 1] = M[1, 2] =  1 / three\n    S[1, 1] = S[2, 2] =  κ / 2\n    S[2, 1] = S[1, 2] = -κ / 2\n    if sz == 2\n        return\n    end\n    six = convert(T, 6)\n    if sz >= 3\n        M[1, 3] = M[2, 3] = -1 /sqrt(six) \n        M[3, 1] = M[1, 3]\n        M[3, 2] = M[2, 3]\n    end\n    if sz >= 4\n        ten = convert(T, 10)\n        M[1, 4] = 1 / ( 3 * sqrt(ten) ) \n        M[2, 4] = -M[1, 4]            \n        M[4, 1] = M[1, 4]\n        M[4, 2] = M[2, 4]\n    end\n    for j = 3:sz\n        M[j, j] = two / ((2j-5)*(2j-1))\n        S[j, j] = κ\n    end\n    for j = 3:sz-2\n        a = convert(T, (2j-3)*(2j+1))\n        M[j, j+2] = M[j+2, j] = -1 / ( (2j-1) * sqrt(a) )\n    end\nend\n\nfunction assembled_matrices(grid::SpatialGrid, \n                            κ::T) where { T <: AbstractFloat }\n    x, gdof = grid.x, grid.global_DoF\n    nfree, nfixed, max_r = grid.nfree, grid.nfixed, grid.max_r\n    P = length(gdof)\n    Mref = zeros(T, max_r, max_r)\n    Sref = zeros(T, max_r, max_r)\n    ref_element_matrices!(Mref, Sref, κ)\n    IM, JM, VM = Int64[], Int64[], Float64[]\n    IS, JS, VS = Int64[], Int64[], Float64[]\n    for p = 1:P\n        hp = x[p] - x[p-1]\n        rp = length(gdof[p])\n        for i = 1:rp\n            gi = gdof[p][i]\n            if gi ≤ nfree\n                for j = 1:rp\n                    gj = gdof[p][j]\n                    push!(IM, gi)\n                    push!(JM, gj)\n                    push!(VM, (hp/2)*Mref[i,j])\n                    push!(IS, gi)\n                    push!(JS, gj)\n                    push!(VS, (2/hp)*Sref[i,j])\n                end\n            end\n        end\n    end\n    M = SparseArrays.sparse(IM, JM, VM, nfree, nfree+nfixed)\n    S = SparseArrays.sparse(IS, JS, VS, nfree, nfree+nfixed)\n    return M, S\nend\n\nfunction element_load_vector!(Fp::AbstractArray{T}, \n                              elt::Tuple{T,T}, f::Function, \n                              Φ::Matrix{T}, pt::Vector{T}, wt::Vector{T}\n                             ) where { T <: AbstractFloat }\n    r = length(Fp)\n    J = length(pt)\n    @argcheck size(Φ,1) ≤ r  DimensionMismatch\n    @argcheck size(Φ,2) == J DimensionMismatch\n    Jacobian = ( elt[2] - elt[1] ) / 2\n    fill!(Fp, zero(T))\n    for j = 1:J\n        xj = ( ( 1 - pt[j] ) * elt[1] + ( 1 + pt[j] ) * elt[2] ) / 2\n        for i = 1:r\n            Fp[i] += wt[j] * f(xj) * Φ[i,j] * Jacobian\n        end\n    end\nend\n\nfunction assembled_load_vector!(F::Vector{T}, grid::SpatialGrid{T}, \n                                f::Function) where { T <: AbstractFloat }\n    x, gdof, pt, wt = grid.x, grid.global_DoF, grid.pt, grid.wt\n    nfree, nfixed, max_r = grid.nfree, grid.nfixed, grid.max_r\n    @argcheck length(F) == nfree\n    P = length(x) - 1\n    Φ = shape_funcs(max_r, pt)\n    Fp = zeros(T, max_r)\n    fill!(F, zero(T))\n    for p = 1:P\n        rp = length(gdof[p])\n        element_load_vector!(view(Fp, 1:rp), (x[p-1],x[p]), f, Φ, pt, wt)\n        for i = 1:length(gdof[p])\n            gi = gdof[p][i]\n            if gi ≤ nfree\n                F[gi] += Fp[i]\n            end\n        end\n    end\nend\n\nfunction assembled_load_vector(grid::SpatialGrid{T}, \n                               f::Function) where { T <: AbstractFloat }\n    nfree = grid.nfree\n    F = zeros(T, nfree)\n    assembled_load_vector!(F, grid, f)\n    return F\nend\n\nfunction spatial_points!(xvals::Vector{T}, grid::SpatialGrid{T}, \n                         ξ::AbstractVector{T}) where { T <: AbstractFloat }\n    x, gdof = grid.x, grid.global_DoF\n    Nx = length(xvals)\n    P = length(x) - 1\n    pts_per_interval = length(ξ)\n    n = 0\n    if Nx == 1 + P * ( pts_per_interval - 1 )\n        for p = 1:P\n            for j = 1:pts_per_interval - 1\n                xpj = ( ( 1 - ξ[j] ) * x[p-1] + (1 + ξ[j] ) * x[p] ) / 2\n                n += 1\n                xvals[n] = xpj\n            end\n        end\n        n += 1\n        xvals[n] = x[P]\n    elseif Nx == P * pts_per_interval\n        for p = 1:P\n            for j = 1:pts_per_interval \n                xpj = ( ( 1 - ξ[j] ) * x[p-1] + (1 + ξ[j] ) * x[p] ) / 2\n                n += 1\n                xvals[n] = xpj\n            end\n        end\n    else\n        throw(ArgumentError(\"xvals length does not match grid\"))\n    end\nend\n\nfunction evaluate_fem1d_soln!(Uvals::Vector{T}, U::Vector{T}, \n                              grid::SpatialGrid{T}, \n                              ξ::AbstractVector{T}\n                             ) where { T <: AbstractFloat }\n    x, gdof = grid.x, grid.global_DoF\n    nfree, nfixed, max_r = grid.nfree, grid.nfixed, grid.max_r\n    @argcheck length(U) == nfree DimensionMismatch\n    Nx = length(Uvals)\n    P = length(x) - 1\n    pts_per_interval = length(ξ)\n    Φ = shape_funcs(max_r, ξ)\n    n = 0\n    if Nx == 1 + P * ( pts_per_interval - 1 ) # ξ[1] = -1, ξ[end] = +1\n        for p = 1:P\n            rp = length(gdof[p])\n            for j = 1:pts_per_interval-1\n                n += 1\n                Uvals[n] = zero(T)\n                for i = 1:rp\n                    gpi = gdof[p][i]\n                    if gpi ≤ nfree\n                        Uvals[n] += U[gpi] * Φ[i,j]\n                    end\n                end\n            end\n        end\n        n += 1\n        gpi = gdof[P][2]\n        if gpi ≤ nfree\n            Uvals[n] = U[gpi] \n        end\n    elseif Nx == P * pts_per_interval  # ξ[1] > -1 or ξ[end] < +1\n        for p = 1:P\n            rp = length(gdof[p])\n            for j = 1:pts_per_interval\n                n += 1\n                Uvals[n] = zero(T)\n                for i = 1:rp\n                    gpi = gdof[p][i]\n                    if gpi ≤ nfree\n                        Uvals[n] += U[gpi] * Φ[i,j]\n                    end\n                end\n            end\n        end\n    else\n        throw(ArgumentError(\"Uvals length does not match grid\"))\n    end\nend\n\nfunction evaluate_fem1d_soln(U::Vector{T}, \n                             grid::SpatialGrid{T}, \n                             pts_per_interval::Int64\n                            ) where { T <: AbstractFloat }\n    x, nfree = grid.x, grid.nfree\n    @argcheck length(U) == nfree DimensionMismatch\n    P = ubound(x, 1)\n    Nx = 1 + P * ( pts_per_interval - 1 )\n    ξ = collect( range(-one(T), stop=one(T), length=pts_per_interval) )\n    xvals = zeros(T, Nx)\n    spatial_points!(xvals, grid, ξ)\n    Uvals = zeros(T, Nx)\n    evaluate_fem1d_soln!(Uvals, U, grid, ξ)\n    return xvals, Uvals\nend\n\nfunction evaluate_pcwise_poly(U::Array{T}, t::OffsetVector{T}, \n                              grid::SpatialGrid{T},\n                              pts_per_time_interval::Int64,\n                              pts_per_space_interval::Int64\n                             ) where { T <: AbstractFloat }\n    τ = range(-one(T), stop=one(T), length=pts_per_time_interval)\n    ξ = range(-one(T), stop=one(T), length=pts_per_space_interval)\n    xvals, pcwise_t, pcwise_U = evaluate_pcwise_poly(U, t, grid, τ, ξ)\n    return xvals, pcwise_t, pcwise_U\nend\n\nfunction evaluate_pcwise_poly(U::Array{T}, t::OffsetVector{T}, \n                              grid::SpatialGrid{T},\n                              τ::AbstractVector{T}, \n                              ξ::AbstractVector{T}\n                             ) where { T <: AbstractFloat }\n    x = grid.x\n    P = length(x) - 1\n    nfree, rt, N = size(U)\n    pts_per_space_interval = length(ξ)\n    pts_per_time_interval = length(τ)\n    @argcheck axes(t, 1) == 0:N\n    if ξ[1] > -1.0 || ξ[end] < 1.0\n        Nx = P * pts_per_space_interval\n    else\n        Nx = 1 + P * ( pts_per_space_interval - 1 )\n    end\n    xvals = zeros(T, Nx)\n    spatial_points!(xvals, grid, ξ)\n    Ψ = Array{Float64}(undef, rt, pts_per_time_interval)\n    legendre_polys!(Ψ, τ)\n    pcwise_t = zeros(T, pts_per_time_interval, N)\n    pcwise_U = zeros(T, Nx, pts_per_time_interval, N)\n    Uvals = zeros(T, Nx)\n    for n = 1:N\n        for i = 1:pts_per_time_interval\n            pcwise_t[i,n] = ( (1-τ[i])*t[n-1] + (1+τ[i])*t[n] ) / 2\n            for k = 1:rt\n                evaluate_fem1d_soln!(Uvals, U[:,k,n], grid, ξ)\n                pcwise_U[:,i,n] .+= Uvals * Ψ[k,i]\n            end\n        end\n    end\n    return xvals, pcwise_t, pcwise_U\nend\n\nfunction evaluate_pcwise_error(pcwise_U::Array{T}, u::Function,\n                               pcwise_t::Array{T}, xvals::Vector{T}\n                              ) where { T <: AbstractFloat }\n    Nx = length(xvals)\n    N = size(pcwise_t, 2)\n    pts_per_time_interval = size(pcwise_t, 1)\n    pcwise_err = zeros(Nx, pts_per_time_interval, N)\n    for n = 1:N\n        for i = 1:pts_per_time_interval\n            for p = 1:Nx\n                pcwise_err[p,i,n] = ( pcwise_U[p,i,n] \n                                     - u(xvals[p], pcwise_t[i,n]) )\n            end\n        end\n    end\n    return pcwise_err\nend\n\nfunction dynamic_load_vector!(Fn::Matrix{T}, In::Vector{Float64},\n                              grid::SpatialGrid{T}, f::Function, \n                              τ::Vector{T}, w::Vector{T}, \n                              Ψ::AbstractMatrix{T}) where { T <: AbstractFloat }\n    nfree, rt = size(Fn)\n    @argcheck grid.nfree == nfree\n    @argcheck length(In) == 2\n    fill!(Fn, 0.0)\n    Fni = zeros(nfree)\n    Δt = In[2] - In[1]\n    for i = 1:length(τ)\n        ti = ( ( 1 - τ[i] ) * In[1] + ( 1 + τ[i] ) * In[2] ) / 2\n        assembled_load_vector!(Fni, grid, x -> f(x,ti))\n        for j = 1:rt\n            Fn[:,j] += (Δt/2) * w[i] * Fni * Ψ[j,i]\n        end\n    end\nend\n\nfunction PDEDG(κ::Float64, f::Function, U0::Vector{Float64}, \n               grid::SpatialGrid{Float64}, t::OffsetVector{Float64},\n               rt::Int64, Mt::Integer) where T <: AbstractFloat\n    x, gdof = grid.x, grid.global_DoF\n    nfree, nfixed = grid.nfree, grid.nfixed\n\n    G = coef_G(Float64, rt)\n    K = coef_K(Float64, rt, rt)\n    H = zeros(rt, rt)\n    for j = 1:rt\n        H[j,j] = 1 / (2j-1)\n    end\n\n    N = length(t) - 1\n    U = zeros(nfree*rt, N)\n    Fn = zeros(nfree, rt)\n    M, S = assembled_matrices(grid, κ)\n    M = M[1:nfree,1:nfree]\n    S = S[1:nfree,1:nfree]\n    Ψ_at_minus1 = Vector{Float64}(undef, rt)\n    legendre_polys!(Ψ_at_minus1, -1.0)\n    τ, w = GaussQuadrature.legendre(Mt)\n    Ψ = Array{Float64}(undef, rt, Mt)\n    legendre_polys!(Ψ, τ)\n    dynamic_load_vector!(Fn, t[0:1], grid, f, τ, w, Ψ)\n    b = Fn[1:nfree*rt] + kron(Ψ_at_minus1, M*U0) \n    Δt1 = t[1] - t[0]\n    G_kron_M = kron(G, M)\n    H_kron_S = kron(H, S)\n    A = G_kron_M + Δt1 * H_kron_S\n    U[:,1] = A \\ b\n    K_kron_M = kron(K, M)\n    for n = 2:N\n        Δtn = t[n] - t[n-1]\n        dynamic_load_vector!(Fn, t[n-1:n], grid, f, τ, w, Ψ)\n        b = Fn[1:nfree*rt] + K_kron_M * U[:,n-1]\n        A = G_kron_M + Δtn * H_kron_S\n        U[:,n] = A \\ b\n    end\n    return reshape(U, nfree, rt, N)\nend\n\n\"\"\"\n    t, U = PDEDG(κ, f, U0, grid, N, rt, num_Gauss_pts)\n\nFaster version for uniform time steps.\n\"\"\"\nfunction PDEDG(κ::Float64, f::Function, U0::Vector{Float64}, \n               grid::SpatialGrid{Float64}, max_t::Float64, N::Int64, \n               rt::Int64, Mt::Integer)\n    x, gdof = grid.x, grid.global_DoF\n    nfree, nfixed = grid.nfree, grid.nfixed\n\n    G = coef_G(Float64, rt)\n    K = coef_K(Float64, rt, rt)\n    H = zeros(rt, rt)\n    for j = 1:rt\n        H[j,j] = 1 / (2j-1)\n    end\n\n    t_ = collect(range(0, max_t, length=N+1))\n    t = OffsetVector(t_, 0:N)\n    U = zeros(nfree*rt, N)\n    Fn = zeros(nfree, rt)\n    M, S = assembled_matrices(grid, κ)\n    M = M[1:nfree,1:nfree]\n    S = S[1:nfree,1:nfree]\n    Ψ_at_minus1 = Vector{Float64}(undef, rt)\n    legendre_polys!(Ψ_at_minus1, -1.0)\n    τ, w = GaussQuadrature.legendre(Mt)\n    Ψ = Array{Float64}(undef, rt, Mt)\n    legendre_polys!(Ψ, τ)\n    dynamic_load_vector!(Fn, t[0:1], grid, f, τ, w, Ψ)\n    b = Fn[1:nfree*rt] + kron(Ψ_at_minus1, M*U0) \n    Δt = max_t / N\n    G_kron_M = kron(G, M)\n    H_kron_S = kron(H, S)\n    A = G_kron_M + Δt * H_kron_S\n    LU = SparseArrays.lu(A)\n    U[:,1] = LU \\ b\n    K_kron_M = kron(K, M)\n    for n = 2:N\n        dynamic_load_vector!(Fn, t[n-1:n], grid, f, τ, w, Ψ)\n        b = Fn[1:nfree*rt] + K_kron_M * U[:,n-1]\n        U[:,n] = LU \\ b\n    end\n    return t, reshape(U, nfree, rt, N)\nend\n\nfunction spatial_L2_projection(f::Function, grid::SpatialGrid{Float64})\n    M, S = assembled_matrices(grid, 0.0)\n    nfree = grid.nfree\n    Pf = M[1:nfree,1:nfree] \\ assembled_load_vector(grid, f)\n    return Pf\nend\n\n\"\"\"\n    err_τ = maxerr(τ, U, t, u, ξ, grid, cutoff=0.0)\n\nReturns err_τ[i] = max |U(x,t)-u(x,t)| over x values in each spatial\ninterval corresponding to ξ the values in [-1,1], and over the t value \nin each time subinterval corresponding to τ[i] in [-1,1], except for time \nintervals with t[n] ≤ cutoff.\n\"\"\"\nfunction maxerr(τ:: AbstractVector{Float64}, U::Array{Float64}, \n                t::OffsetVector{Float64}, u::Function,\n                ξ::AbstractVector{Float64}, grid::SpatialGrid, \n                cutoff=0.0)\n    xvals, pcwise_t, pcwise_U = evaluate_pcwise_poly(U, t, grid, τ, ξ)\n    pcwise_err = evaluate_pcwise_error(pcwise_U, u, pcwise_t, xvals)\n    N = size(pcwise_t, 2)\n    pts_per_time_interval = size(pcwise_t, 1)\n    Nx = size(pcwise_err, 1)\n    err_τ = zeros(pts_per_time_interval)\n    for n = 1:N\n        if t[n] ≤ cutoff\n            continue\n        end\n        for i = 1:pts_per_time_interval\n            for p = 1:Nx\n                err_τ[i] = max(abs(pcwise_err[p,i,n]), err_τ[i])\n            end\n        end\n    end\n    return err_τ\nend\n\n\"\"\"\n    U = FPDEDG(κ, f, U0, grid, t, rt, num_t_Gauss_pts)\n\nDG solver for fractional PDE.\n\"\"\"\nfunction FPDEDG(κ::Float64, f::Function, U0::Vector{Float64}, \n               grid::SpatialGrid{Float64}, t::OffsetVector{Float64},\n               rt::Int64, Mt::Int64, store::Store{Float64})\n    α = store.α\n    x, gdof = grid.x, grid.global_DoF\n    nfree, nfixed = grid.nfree, grid.nfixed\n\n    G = coef_G(Float64, rt)\n    K = coef_K(Float64, rt, rt)\n    Nt = length(t) - 1\n    Hn = OffsetArray{Matrix{Float64}}(undef, 0:Nt-1)\n    for n = 0:Nt-1\n        Hn[n] = Array{Float64}(undef, rt, rt)\n    end\n    τ, wτ = rule(store.legendre[Mt])\n    Ψ = view(store.Ψ, 1:rt, 1:Mt)\n    legendre_polys!(Ψ, τ)\n\n    U = zeros(nfree*rt, Nt)\n    Fn = zeros(nfree, rt)\n    M, S = assembled_matrices(grid, κ)\n    M = M[1:nfree,1:nfree]\n    S = S[1:nfree,1:nfree]\n    Ψ_at_minus1 = Array{Float64}(undef, rt)\n    legendre_polys!(Ψ_at_minus1, -1.0)\n    dynamic_load_vector!(Fn, t[0:1], grid, f, τ, wτ, Ψ)\n    b = Fn[1:nfree*rt] + kron(Ψ_at_minus1, M*U0) \n    coef_Hn!(Hn, 1, 0, t, Mt, store)\n    G_kron_M = kron(G, M)\n    Hnn_kron_S = kron(Hn[0], S)\n    A = G_kron_M + Hnn_kron_S\n    U[:,1] = A \\ b\n    K_kron_M = kron(K, M)\n    for n = 2:Nt\n        coef_Hn!(Hn, n, n-1, t, Mt, store)\n        Hnn_kron_S = kron(Hn[0], S)\n        A = G_kron_M + Hnn_kron_S\n        fill!(b, 0.0)\n        for l = 1:n-1\n            Hnl_kron_S = kron(Hn[n-l], S)\n            b .= b .+ Hnl_kron_S * U[:,l]\n        end\n        dynamic_load_vector!(Fn, t[n-1:n], grid, f, τ, wτ, Ψ)\n        b .= Fn[1:nfree*rt] .+ K_kron_M * U[:,n-1] .- b\n        U[:,n] = A \\ b\n    end\n    return reshape(U, nfree, rt, Nt)\nend\n\n\"\"\"\n    t, U = FPDEDG(κ, f, U0, grid, max_t, N, rt, num_t_Gauss_pts)\n\nSpecialised version for uniform time steps.\n\"\"\"\nfunction FPDEDG(κ::Float64, f::Function, U0::Vector{Float64}, \n                grid::SpatialGrid{Float64}, max_t::Float64, \n                N::Int64, rt::Int64, Mt::Int64, store::Store{Float64})\n    α = store.α\n    x, gdof = grid.x, grid.global_DoF\n    nfree, nfixed = grid.nfree, grid.nfixed\n\n    Δt = max_t / N\n    G = coef_G(Float64, rt)\n    K = coef_K(Float64, rt, rt)\n    H = coef_H_uniform!(rt, N, Mt, store)\n\n    t_ = collect(range(0, max_t, length=N+1))\n    t = OffsetVector(t_, 0:N)\n\n    U = zeros(nfree*rt, N)\n    Fn = zeros(nfree, rt)\n    M, S = assembled_matrices(grid, κ)\n    M = M[1:nfree,1:nfree]\n    S = S[1:nfree,1:nfree]\n    Ψ_at_minus1 = Vector{Float64}(undef, rt)\n    legendre_polys!(Ψ_at_minus1, -1.0)\n    τ, w = GaussQuadrature.legendre(Mt)\n    Ψ = Array{Float64}(undef, rt, Mt)\n    legendre_polys!(Ψ, τ)\n    dynamic_load_vector!(Fn, t[0:1], grid, f, τ, w, Ψ)\n    b = Fn[1:nfree*rt] + kron(Ψ_at_minus1, M*U0) \n    G_kron_M = kron(G, M)\n    Hnn_kron_S = kron(H[0], S)\n    A = G_kron_M + Δt^α * Hnn_kron_S\n    Fact = SparseArrays.lu(A)\n    U[:,1] = Fact \\ b\n    K_kron_M = kron(K, M)\n    for n = 2:N\n        fill!(b, 0.0)\n        for l = 1:n-1\n            Hnl_kron_S = kron(H[n-l], S)\n            b .= b .+ Δt^α * Hnl_kron_S * U[:,l]\n        end\n        dynamic_load_vector!(Fn, t[n-1:n], grid, f, τ, w, Ψ)\n        b .= Fn[1:nfree*rt] .+ K_kron_M * U[:,n-1] .- b\n        U[:,n] = Fact \\ b\n    end\n    return t, reshape(U, nfree, rt, N)\nend\n\nfunction functional(pcwise_U::Array{Float64}, pcwise_t::Array{Float64},\n                    func::Function, grid::SpatialGrid, \n                    ξ::Vector{Float64}, w::Vector{Float64})\n    x = grid.x\n    pts_per_time_interval = size(pcwise_t,1)\n    N = size(pcwise_t, 2)\n    P = ubound(x, 1)\n    pts_per_space_interval = length(ξ)\n    Fnctl = zeros(pts_per_time_interval, N)\n\nend\n", "meta": {"hexsha": "02af415b3bf1e0e8c0c82706d1c3820b30d6e781", "size": 21339, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/parts/FEM1D.jl", "max_stars_repo_name": "billmclean/FractionalTimeDG.jl", "max_stars_repo_head_hexsha": "165bd96ac1355befaed4dff25172cc255e883768", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/parts/FEM1D.jl", "max_issues_repo_name": "billmclean/FractionalTimeDG.jl", "max_issues_repo_head_hexsha": "165bd96ac1355befaed4dff25172cc255e883768", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/parts/FEM1D.jl", "max_forks_repo_name": "billmclean/FractionalTimeDG.jl", "max_forks_repo_head_hexsha": "165bd96ac1355befaed4dff25172cc255e883768", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0159883721, "max_line_length": 80, "alphanum_fraction": 0.4925722855, "num_tokens": 7327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7560166834358183}}
{"text": "######## Stan diagnose example  ###########\n\nusing Stan\n\nProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n\nbernoulli = \"\ndata { \n  int<lower=0> N; \n  int<lower=0,upper=1> y[N];\n} \nparameters {\n  real<lower=0,upper=1> theta;\n} \nmodel {\n  theta ~ beta(1,1);\n    y ~ bernoulli(theta);\n}\n\"\n\nbernoullidata = [\n  Dict(\"N\" => 10, \"y\" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]),\n  Dict(\"N\" => 10, \"y\" => [0, 1, 0, 0, 0, 0, 1, 0, 0, 1]),\n  Dict(\"N\" => 10, \"y\" => [0, 0, 0, 0, 0, 0, 1, 0, 1, 1]),\n  Dict(\"N\" => 10, \"y\" => [0, 0, 0, 1, 0, 0, 0, 1, 0, 1])\n]\n\nstanmodel = Stanmodel(Diagnose(Gradient(epsilon=1e-6)), name=\"bernoulli\", model=bernoulli);\n\ndiags = stan(stanmodel, bernoullidata, ProjDir, CmdStanDir=CMDSTAN_HOME);\ndiags[1][\"diagnose\"] |> display\n\nend # cd\n", "meta": {"hexsha": "fb0c93721b99a6c4b5a372804e2dd2ecba9b918f", "size": 743, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/Bernoulli/bernoulli_diagnose.jl", "max_stars_repo_name": "JuliaPackageMirrors/Stan.jl", "max_stars_repo_head_hexsha": "d9c4e6e0cb7749ef31259f569f0fa98b3cf104de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Examples/Bernoulli/bernoulli_diagnose.jl", "max_issues_repo_name": "JuliaPackageMirrors/Stan.jl", "max_issues_repo_head_hexsha": "d9c4e6e0cb7749ef31259f569f0fa98b3cf104de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/Bernoulli/bernoulli_diagnose.jl", "max_forks_repo_name": "JuliaPackageMirrors/Stan.jl", "max_forks_repo_head_hexsha": "d9c4e6e0cb7749ef31259f569f0fa98b3cf104de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2285714286, "max_line_length": 91, "alphanum_fraction": 0.5450874832, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7560166822441586}}
{"text": "# [ include(\"../src/\"*s) for s in readdir(\"../src\") ]\nusing PolyChaos\n# using LinearAlgebra\n# import FFTW\n# import SpecialFunctions\n# numerically compute recurrence coefficients for (almost) Gaussian density w(t)\nN = 10\nw(t) = exp(-t^2)\nlb, ub = -Inf, Inf\n@time α, β = rm_compute(w,lb,ub;Nquad=200,Npoly=N)\n# analytical solution\nα_ana = zeros(N)\nβ_ana = [ √π; [0.5*k for k=1:N-1] ]\n# compare\ndisplay(\"Deviation for α: $(α-α_ana)\")\ndisplay(\"Deviation for β: $(β-β_ana)\")\n## do the same for Chebyshev polynomials #4\nv(t) = sqrt(1-t)/sqrt(1+t)\nlb, ub = -1+1e-8, 1-1e-8\n@time α, β = rm_compute(v,lb,ub;Nquad=2000,Npoly=N)\n# analytical solution\nα_ana = [-0.5; zeros(N-1) ]\nβ_ana = [ π; [0.25 for k=1:N-1] ]\n# compare\ndisplay(\"Deviation for α: $(α-α_ana)\")\ndisplay(\"Deviation for β: $(β-β_ana)\")\n", "meta": {"hexsha": "b24aac1fed846d809a73913670a945c45e8a2eb9", "size": 790, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/computing_recurrence_coefficients.jl", "max_stars_repo_name": "adriangrupp/PolyChaos.jl", "max_stars_repo_head_hexsha": "d0091cc575456721b5f4c20dd219ce3789d889bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71, "max_stars_repo_stars_event_min_datetime": "2019-02-08T15:13:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T09:48:18.000Z", "max_issues_repo_path": "examples/computing_recurrence_coefficients.jl", "max_issues_repo_name": "adriangrupp/PolyChaos.jl", "max_issues_repo_head_hexsha": "d0091cc575456721b5f4c20dd219ce3789d889bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 55, "max_issues_repo_issues_event_min_datetime": "2019-02-08T12:21:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T20:21:46.000Z", "max_forks_repo_path": "examples/computing_recurrence_coefficients.jl", "max_forks_repo_name": "adriangrupp/PolyChaos.jl", "max_forks_repo_head_hexsha": "d0091cc575456721b5f4c20dd219ce3789d889bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-03-20T08:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T14:25:42.000Z", "avg_line_length": 29.2592592593, "max_line_length": 80, "alphanum_fraction": 0.6556962025, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7560166814974207}}
{"text": "\n# Import libraries.\nusing Turing, Flux, Plots, Random, ReverseDiff\n\n# Hide sampling progress.\nTuring.setprogress!(false);\n\n# Use reverse_diff due to the number of parameters in neural networks.\nTuring.setadbackend(:reversediff)\n\n\n# Number of points to generate.\nN = 80\nM = round(Int, N / 4)\nRandom.seed!(1234)\n\n# Generate artificial data.\nx1s = rand(M) * 4.5; x2s = rand(M) * 4.5; \nxt1s = Array([[x1s[i] + 0.5; x2s[i] + 0.5] for i = 1:M])\nx1s = rand(M) * 4.5; x2s = rand(M) * 4.5; \nappend!(xt1s, Array([[x1s[i] - 5; x2s[i] - 5] for i = 1:M]))\n\nx1s = rand(M) * 4.5; x2s = rand(M) * 4.5; \nxt0s = Array([[x1s[i] + 0.5; x2s[i] - 5] for i = 1:M])\nx1s = rand(M) * 4.5; x2s = rand(M) * 4.5; \nappend!(xt0s, Array([[x1s[i] - 5; x2s[i] + 0.5] for i = 1:M]))\n\n# Store all the data for later.\nxs = [xt1s; xt0s]\nts = [ones(2*M); zeros(2*M)]\n\n# Plot data points.\nfunction plot_data()\n    x1 = map(e -> e[1], xt1s)\n    y1 = map(e -> e[2], xt1s)\n    x2 = map(e -> e[1], xt0s)\n    y2 = map(e -> e[2], xt0s)\n\n    Plots.scatter(x1,y1, color=\"red\", clim = (0,1))\n    Plots.scatter!(x2, y2, color=\"blue\", clim = (0,1))\nend\n\nplot_data()\n\n\n# Turn a vector into a set of weights and biases.\nfunction unpack(nn_params::AbstractVector)\n    W₁ = reshape(nn_params[1:6], 3, 2);   \n    b₁ = reshape(nn_params[7:9], 3)\n    \n    W₂ = reshape(nn_params[10:15], 2, 3); \n    b₂ = reshape(nn_params[16:17], 2)\n    \n    Wₒ = reshape(nn_params[18:19], 1, 2); \n    bₒ = reshape(nn_params[20:20], 1)   \n    return W₁, b₁, W₂, b₂, Wₒ, bₒ\nend\n\n# Construct a neural network using Flux and return a predicted value.\nfunction nn_forward(xs, nn_params::AbstractVector)\n    W₁, b₁, W₂, b₂, Wₒ, bₒ = unpack(nn_params)\n    nn = Chain(Dense(W₁, b₁, tanh),\n               Dense(W₂, b₂, tanh),\n               Dense(Wₒ, bₒ, σ))\n    return nn(xs)\nend;\n\n\n# Create a regularization term and a Gaussain prior variance term.\nalpha = 0.09\nsig = sqrt(1.0 / alpha)\n\n# Specify the probabalistic model.\n@model function bayes_nn(xs, ts)\n    # Create the weight and bias vector.\n    nn_params ~ MvNormal(zeros(20), sig .* ones(20))\n    \n    # Calculate predictions for the inputs given the weights\n    # and biases in theta.\n    preds = nn_forward(xs, nn_params)\n    \n    # Observe each prediction.\n    for i = 1:length(ts)\n        ts[i] ~ Bernoulli(preds[i])\n    end\nend;\n\n\n# Perform inference.\nN = 5000\nch = sample(bayes_nn(hcat(xs...), ts), HMC(0.05, 4), N);\n\n\n# Extract all weight and bias parameters.\ntheta = MCMCChains.group(ch, :nn_params).value;\n\n\n# Plot the data we have.\nplot_data()\n\n# Find the index that provided the highest log posterior in the chain.\n_, i = findmax(ch[:lp])\n\n# Extract the max row value from i.\ni = i.I[1]\n\n# Plot the posterior distribution with a contour plot.\nx_range = collect(range(-6,stop=6,length=25))\ny_range = collect(range(-6,stop=6,length=25))\nZ = [nn_forward([x, y], theta[i, :])[1] for x=x_range, y=y_range]\ncontour!(x_range, y_range, Z)\n\n\n# Return the average predicted value across\n# multiple weights.\nfunction nn_predict(x, theta, num)\n    mean([nn_forward(x, theta[i,:])[1] for i in 1:10:num])\nend;\n\n\n# Plot the average prediction.\nplot_data()\n\nn_end = 1500\nx_range = collect(range(-6,stop=6,length=25))\ny_range = collect(range(-6,stop=6,length=25))\nZ = [nn_predict([x, y], theta, n_end)[1] for x=x_range, y=y_range]\ncontour!(x_range, y_range, Z)\n\n\n# Number of iterations to plot.\nn_end = 500\n\nanim = @gif for i=1:n_end\n    plot_data()\n    Z = [nn_forward([x, y], theta[i,:])[1] for x=x_range, y=y_range]\n    contour!(x_range, y_range, Z, title=\"Iteration $i\", clim = (0,1))\nend every 5\n\n\nusing Bijectors\nusing Turing: Variational\nusing AdvancedVI\n\nm = bayes_nn(hcat(xs...), ts);\n\nq = Variational.meanfield(m)\n\nμ = randn(length(q))\nω = -1 .* ones(length(q))\n\nq = AdvancedVI.update(q, μ, exp.(ω));\n\nadvi = ADVI(10, 5_000)\nq_hat = vi(m, advi, q);\n\n\nsamples = transpose(rand(q_hat, 5000))\nch_vi = Chains(reshape(samples, size(samples)..., 1), string.(MCMCChains.namesingroup(ch, :nn_params)));\n\n# Extract all weight and bias parameters.\ntheta = MCMCChains.group(ch_vi, :nn_params).value;\n\n\n# Plot the average prediction.\nplot_data()\n\nn_end = 1500\nx_range = collect(range(-6,stop=6,length=25))\ny_range = collect(range(-6,stop=6,length=25))\nZ = [nn_predict([x, y], theta, n_end)[1] for x=x_range, y=y_range]\ncontour!(x_range, y_range, Z)\n\n\n# Specify the network architecture.\nnetwork_shape = [\n    (3,2, :tanh),\n    (2,3, :tanh), \n    (1,2, :σ)]\n\n# Regularization, parameter variance, and total number of\n# parameters.\nalpha = 0.09\nsig = sqrt(1.0 / alpha)\nnum_params = sum([i * o + i for (i, o, _) in network_shape])\n\n# This modification of the unpack function generates a series of vectors\n# given a network shape.\nfunction unpack(θ::AbstractVector, network_shape::AbstractVector)\n    index = 1\n    weights = []\n    biases = []\n    for layer in network_shape\n        rows, cols, _ = layer\n        size = rows * cols\n        last_index_w = size + index - 1\n        last_index_b = last_index_w + rows\n        push!(weights, reshape(θ[index:last_index_w], rows, cols))\n        push!(biases, reshape(θ[last_index_w+1:last_index_b], rows))\n        index = last_index_b + 1\n    end\n    return weights, biases\nend\n\n# Generate an abstract neural network given a shape, \n# and return a prediction.\nfunction nn_forward(x, θ::AbstractVector, network_shape::AbstractVector)\n    weights, biases = unpack(θ, network_shape)\n    layers = []\n    for i in eachindex(network_shape)\n        push!(layers, Dense(weights[i],\n            biases[i],\n            eval(network_shape[i][3])))\n    end\n    nn = Chain(layers...)\n    return nn(x)\nend\n\n# General Turing specification for a BNN model.\n@model bayes_nn_general(xs, ts, network_shape, num_params) = begin\n    θ ~ MvNormal(zeros(num_params), sig .* ones(num_params))\n    preds = nn_forward(xs, θ, network_shape)\n    for i = 1:length(ts)\n        ts[i] ~ Bernoulli(preds[i])\n    end\nend\n\n# Perform inference.\nnum_samples = 500\nch2 = sample(bayes_nn_general(hcat(xs...), ts, network_shape, num_params), NUTS(0.65), num_samples);\n\n\n# This function makes predictions based on network shape.\nfunction nn_predict(x, theta, num, network_shape)\n    mean([nn_forward(x, theta[i,:], network_shape)[1] for i in 1:10:num])\nend;\n\n# Extract the θ parameters from the sampled chain.\nparams2 = MCMCChains.group(ch2, :θ).value\n\nplot_data()\n\nx_range = collect(range(-6,stop=6,length=25))\ny_range = collect(range(-6,stop=6,length=25))\nZ = [nn_predict([x, y], params2, length(ch2), network_shape)[1] for x=x_range, y=y_range]\ncontour!(x_range, y_range, Z)\n\n\nif isdefined(Main, :TuringTutorials)\n    Main.TuringTutorials.tutorial_footer(WEAVE_ARGS[:folder], WEAVE_ARGS[:file])\nend\n\n", "meta": {"hexsha": "923e7553b8e1d205c9fcb8ef10b6879704492ae7", "size": 6671, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/03-bayesian-neural-network/03_bayesian-neural-network.jl", "max_stars_repo_name": "leachim/TuringTutorials", "max_stars_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 154, "max_stars_repo_stars_event_min_datetime": "2018-08-13T17:04:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T06:28:19.000Z", "max_issues_repo_path": "script/03-bayesian-neural-network/03_bayesian-neural-network.jl", "max_issues_repo_name": "leachim/TuringTutorials", "max_issues_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 137, "max_issues_repo_issues_event_min_datetime": "2018-09-06T21:56:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T07:36:07.000Z", "max_forks_repo_path": "script/03-bayesian-neural-network/03_bayesian-neural-network.jl", "max_forks_repo_name": "leachim/TuringTutorials", "max_forks_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 82, "max_forks_repo_forks_event_min_datetime": "2018-09-17T15:57:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T04:54:57.000Z", "avg_line_length": 26.3675889328, "max_line_length": 104, "alphanum_fraction": 0.6546244941, "num_tokens": 2151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7560166789709958}}
{"text": "using EngEconomics\n\n# Given\naInit = 1700\nbInit = 2100\ncInit = 3750\naAnnualBenefit = 1000\nbAnnualBenefit = 1000\ncAnnualBenefit = 1000\naLife = 2\nbLife = 3\ncLife = 6\ni = 0.08\n\n# Find: Present Worth Value of each Item then pick the best option\n# Start by determining the number of periods for each product\nyears = 6\naPeriods = years / aLife\nbPeriods = years / bLife\ncPeriods = years / cLife\n\n# Next, determine the present worth of product A\naInitPW = -aInit * (1 + presentWorthFactor(i, aLife) + presentWorthFactor(i, 2 * aLife))\naAnnualBenefitPW = (aAnnualBenefit * seriesPresentAmountFactor(i, aLife)) * (1 + presentWorthFactor(i, aLife) + presentWorthFactor(i, 2 * aLife))\naPW = aInitPW + aAnnualBenefitPW\n\n# Determine PW of Product B\nbInitPW = -bInit * (1 + presentWorthFactor(i, bLife))\nbAnnualBenefitPW = (bAnnualBenefit * seriesPresentAmountFactor(i, bLife)) * (1 + presentWorthFactor(i, bLife))\nbPW = bInitPW + bAnnualBenefitPW\n\n# Determine PW of Product C\ncInitPW = -cInit * (1)\ncAnnualBenefitPW = (cAnnualBenefit * seriesPresentAmountFactor(i, cLife)) * (1)\ncPW = cInitPW + cAnnualBenefitPW\n\n# Compare Alternatives, pick the greatest one\nmaxPW = max(aPW, bPW, cPW)\n\nif maxPW == aPW\n\tprintln(\"Pick A\")\nelseif maxPW == bPW\n\tprintln(\"Pick B\")\nelse\n\tprintln(\"Pick C\")\nend\n", "meta": {"hexsha": "dffee7c698fa08a8297bde62d428a5960521c124", "size": 1274, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps4/p4.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/ps4/p4.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/ps4/p4.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1063829787, "max_line_length": 145, "alphanum_fraction": 0.7354788069, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731158685837, "lm_q2_score": 0.7853085859124003, "lm_q1q2_score": 0.7559954633186418}}
{"text": "\"\"\"\n    BiweightMidcovariance(; c=9.0, modify_sample_size=false)\n\nThe biweight midcovariance is a covariance estimator that is resilient to outliers.\n\nThe technique derives originally from astrophysics [1], and is implemented in the Python\nmodule [Astropy](https://www.astropy.org/) [2], as well as in NIST's Dataplot [3].\n\nConsider two random variables ``x`` and ``y``, for which we have ``n`` observations\n``\\\\{(x_i, y_i)\\\\}``. The biweight midcovariance is then defined to be:\n```math\nn_s\\\\cdot\\\\frac{\n    \\\\sum_{|u_i|<1,|v_i|<1}(x_i - M_x)(1 - u_i^2)^2(y_i - M_y)(1 - v_i^2)^2\n}{\n    \\\\left(\\\\sum_{|u_i|<1}(1 - u_i^2)(1-5u_i^2)\\\\right)\n    \\\\left(\\\\sum_{|v_i|<1}(1 - v_i^2)(1-5v_i^2)\\\\right)\n}\n```\nwhere ``n_s`` is the sample size, ``M_x`` and ``M_y`` are the medians of ``\\\\{x_i\\\\}`` and\n``\\\\{y_i\\\\}`` respectively, and\n```math\n\\\\begin{aligned}\nu_i &= \\\\frac{x_i - M_x}{c \\\\cdot \\\\mathrm{MAD}_x} \\\\\\\\\nv_i &= \\\\frac{y_i - M_y}{c \\\\cdot \\\\mathrm{MAD}_y},\n\\\\end{aligned}\n```\nwhere ``\\\\mathrm{MAD}`` represents the median absolute deviation,\n```math\n\\\\begin{aligned}\n\\\\mathrm{MAD}_x &= \\\\mathrm{median}(\\\\left\\\\{\\\\left|x_i - M_x\\\\right|\\\\right\\\\}) \\\\\\\\\n\\\\mathrm{MAD}_y &= \\\\mathrm{median}(\\\\left\\\\{\\\\left|y_i - M_y\\\\right|\\\\right\\\\}).\n\\\\end{aligned}\n```\n\nIf either ``\\\\mathrm{MAD}_x = 0`` or ``\\\\mathrm{MAD}_y = 0``, the pairwise covariance is\ndefined to be zero.\n\nThe parameter ``c`` is a tuning constant, for which the default is ``9.0``.\nLarger values will reduce the number of outliers that are removed — i.e. reducing\nrobustness, but increasing sample efficiency.\n\n# Fields\n- `c::Float64`: The tuning constant corresponding to ``c`` above.\n- `modify_sample_size::Bool`: If `false`, then we use a sample size ``n_s`` equal to the\n    total number of observations ``n``. This is consistent with the standard definition of\n    biweight midcovariance in the literature. Otherwise, we count only those elements which\n    are not rejected as outliers in the numerator, i.e. those for which ``|u_i|<1``\n    and ``|v_i|<1``.\n    This follows the implementation in astropy [2].\n\n# Complexity\n- Space: ``O(p^2)``\n- Time: ``O(np^2)``\n\n# References\n[1] Beers, Flynn, and Gebhardt (1990; AJ 100, 32)\n\"Measures of Location and Scale for Velocities in Clusters of Galaxies -- A Robust Approach\"\n\n[2] [Astropy biweight_midcovariance](https://docs.astropy.org/en/stable/api/astropy.stats.biweight_midcovariance.html)\n\n[3] [NIST Dataplot biweight midcovariance](https://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/biwmidc.htm)\n\"\"\"\nstruct BiweightMidcovariance <: CovarianceEstimator\n    c::Float64\n    modify_sample_size::Bool\nend\nfunction BiweightMidcovariance(; c::Real=9.0, modify_sample_size::Bool=false)\n    c > 0 || throw(ArgumentError(\"c must be positive, got $c\"))\n    return BiweightMidcovariance(Float64(c), modify_sample_size)\nend\n\nfunction covzm(ce::BiweightMidcovariance, x::AbstractVector{<:Real})\n    MADx = median!(abs.(x))\n    numerator = zero(eltype(x))\n\n    # If MADx is zero, return zero.\n    iszero(MADx) && return zero(one(eltype(x)) / 1)\n\n    denominator = zero(eltype(x))\n    count = 0\n    for xi in x\n        ui² = (xi / (ce.c * MADx))^2\n        # Benchmarking suggests that having this branch is similar or faster to a form\n        # using `ifelse`, where we always compute the updates but avoid the branch.\n        ui² >= 1 && continue\n        count += 1\n        numerator += xi^2 * (1 - ui²)^4\n        denominator += (1 - ui²) * (1 - 5 * ui²)\n    end\n    n = ifelse(ce.modify_sample_size, count, length(x))\n    return n * numerator / (denominator^2)\nend\n\nfunction cov(\n    ce::BiweightMidcovariance,\n    x::AbstractVector{<:Real};\n    mean::Union{Nothing,<:Real}=nothing,\n)\n    Mx = mean === nothing ? median(x) : mean\n    return covzm(ce, x .- Mx)\nend\n\nfunction covzm(\n    ce::BiweightMidcovariance, x::AbstractVector{<:Real}, y::AbstractVector{<:Real}\n)\n    MADx = median!(abs.(x))\n    MADy = median!(abs.(y))\n\n    # Promote types between x & y for numerator\n    numerator = zero(promote_type(eltype(x), eltype(y)))\n\n    # If either of the MADs are zero, return zero.\n    #   `numerator` is always zero here, and of the correct type.\n    iszero(MADx) && return numerator\n    iszero(MADy) && return numerator\n\n    denominator_x = zero(eltype(x))\n    denominator_y = zero(eltype(y))\n    count = 0\n    for (xi, yi) in zip(x, y)\n        ui² = (xi / (ce.c * MADx))^2\n        vi² = (yi / (ce.c * MADy))^2\n\n        # Compute the updates, and increment if desired.\n        # This way should avoid branches, and benchmarks suggest it's 1-2% faster than\n        # using conditionals.\n        ax = (1 - ui²) * (1 - 5 * ui²)\n        ay = (1 - vi²) * (1 - 5 * vi²)\n        anum = xi * (1 - ui²)^2 * yi * (1 - vi²)^2\n\n        denominator_x += ifelse(ui² < 1, ax, zero(denominator_x))\n        denominator_y += ifelse(vi² < 1, ay, zero(denominator_y))\n        i_count, i_numerator = ifelse(ui² < 1 && vi² < 1, (1, anum), (0, zero(numerator)))\n        count += i_count\n        numerator += i_numerator\n    end\n\n    n = ifelse(ce.modify_sample_size, count, length(x))\n    return n * numerator / (denominator_x * denominator_y)\nend\n\nfunction cov(\n    ce::BiweightMidcovariance, x::AbstractVector{<:Real}, y::AbstractVector{<:Real}\n)\n    if size(x) != size(y)\n        throw(ArgumentError(\"x & y have different sizes, $(size(x)) & $(size(y))\"))\n    end\n\n    return covzm(ce, x .- median(x), y .- median(y))\nend\n\nfunction cov(\n    ce::BiweightMidcovariance,\n    X::AbstractMatrix{<:Real};\n    mean::Union{Nothing,AbstractVector{<:Real},AbstractMatrix{<:Real}}=nothing,\n    dims::Int=1,\n)\n    dims ∈ (1, 2) || throw(ArgumentError(\"Argument dims can only be 1 or 2 (given: $dims)\"))\n\n    # Ascertain the number of observations `n` and number of variables `p`.\n    n, p = dims == 1 ? size(X) : (size(X, 2), size(X, 1))\n\n    # Temporary storage to use when computing medians.\n    temp = Vector{eltype(X)}(undef, n)\n\n    # If the `mean` argument isn't provided, then we centralise with the median.\n    # After this statement, Xc is standardised to be of shape (n, p)\n    Xc = if mean === nothing\n        # The following is equivalent to\n        #   X .- median(X; dims=dims)\n        # However, this implementation significantly reduces the runtime of this function.\n        # This is primarily achieved by reducing the number of allocations -- we allocate a\n        # single temporary buffer which we allow `median!` to mutate, and then copy the next\n        # section of data into it.\n        X = dims == 2 ? transpose(X) : X\n        Xc = copy(X)\n        @inbounds for i in 1:p\n            # Avoiding copyto!(, ... @view(X[:, i])), because this can allocate a view if\n            # the call to copyto! isn't inlined.\n            for j in 1:n\n                temp[j] = X[j, i]\n            end\n            Xc[:, i] .-= median!(temp)\n        end\n        Xc\n    else\n        Xc = X .- mean\n        # Standardise the orientation of Xc.\n        dims == 2 ? transpose(Xc) : Xc\n    end\n\n    # Compute all the median absolute deviations.\n    # To avoid extra allocations, use a temporary buffer `temp` which will be populated with\n    # the absolute values of the observations of each variable, and which we then allow\n    # median! to mutate.\n    T = typeof(one(eltype(X)) / 1)  # This is the output type of median.\n    MAD = Matrix{T}(undef, 1, p)\n    @inbounds for i in 1:p\n        # Avoiding map!(abs, temp, @view(Xc[:, i])), because this can allocate a view if\n        # the call to map! isn't inlined.\n        for j in 1:n\n            temp[j] = abs(Xc[j, i])\n        end\n        MAD[1, i] = median!(temp)\n    end\n\n    u² = @. (Xc / (ce.c * MAD))^2\n\n    onesubu² = max.((1 .- u²), 0)\n    a = @. Xc * onesubu²^2\n    numerator = a' * a\n\n    a[:, :] .= @. onesubu² * (1 - 5 * u²)  # Re-use `a` memory to avoid an allocation.\n    b = sum(a; dims=1)\n    denominator = b' * b\n\n    n = if ce.modify_sample_size\n        mask = onesubu² .> 0\n        mask' * mask\n    else\n        n\n    end\n\n    # Re-use the numerator memory for the result.\n    result = numerator\n    result .*= n ./ denominator\n\n    # Whereever the MAD is zero, we should set the result to zero.\n    mad_zero = dropdims(iszero.(MAD); dims=1)\n    result[mad_zero, :] .= zero(eltype(result))\n    result[:, mad_zero] .= zero(eltype(result))\n\n    return result\nend\n", "meta": {"hexsha": "85a74162cd68c4e8a3a98e9c4616f333943432ad", "size": 8323, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/biweight.jl", "max_stars_repo_name": "mateuszbaran/CovarianceEstimation.jl", "max_stars_repo_head_hexsha": "4760963a06bb7124e6b08bca27851c1b77e43620", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2018-11-27T09:45:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T13:04:05.000Z", "max_issues_repo_path": "src/biweight.jl", "max_issues_repo_name": "mateuszbaran/CovarianceEstimation.jl", "max_issues_repo_head_hexsha": "4760963a06bb7124e6b08bca27851c1b77e43620", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 71, "max_issues_repo_issues_event_min_datetime": "2018-11-27T03:54:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T10:42:53.000Z", "max_forks_repo_path": "src/biweight.jl", "max_forks_repo_name": "mateuszbaran/CovarianceEstimation.jl", "max_forks_repo_head_hexsha": "4760963a06bb7124e6b08bca27851c1b77e43620", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2018-12-17T01:39:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T11:09:24.000Z", "avg_line_length": 35.4170212766, "max_line_length": 122, "alphanum_fraction": 0.6212904001, "num_tokens": 2546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7559948687087646}}
{"text": "# p14.jl - solve nonlinear BVP u_xx = exp(u), u(-1)=u(1)=0\n#         (compare p13.jl)\n\nN = 16;\n(D,x) = cheb(N); D2 = D^2; D2 = D2[2:N,2:N];\nu = zeros(N-1);\nchange = 1; it = 0;\nwhile change > 1e-15                   # fixed-point iteration\n    unew = D2\\exp.(u);\n    change = norm(unew-u,Inf);\n    u = unew; it = it+1;\nend\nu = [0;u;0];\nclf(); axes([.1,.4,.8,.5]);\nplot(x,u,\".\",markersize=6);\nxx = -1:.01:1;\nuu = polyval(polyfit(x,u),xx);\nplot(xx,uu), grid(true);\ntitle(\"no. steps = $it      u(0) =$(u[Int(N/2+1)])\")\n", "meta": {"hexsha": "53a7029be4671cac810bceb36d28b8b4ce4832a3", "size": 515, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p14.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p14.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p14.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.75, "max_line_length": 62, "alphanum_fraction": 0.5029126214, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768604361741, "lm_q2_score": 0.8006919973399709, "lm_q1q2_score": 0.7559948562248232}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, StatsPlots, LaTeXStrings\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.9\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\tdist = TriangularDist(0,2,1)\n\txGrid = 0:0.01:2\n\tuGrid = 0:0.01:1\nend\n\n# ╔═╡ a715f0ac-2034-11eb-029c-9be9db193aed\nbegin\n\tp1 = plot( xGrid, pdf.(dist,xGrid), c=:blue, \n\t\t\txlims=(0,2), ylims=(0,1.1), \n\t\t\txlabel=\"x\", ylabel=\"f(x)\")\n\tp2 = plot( xGrid, cdf.(dist,xGrid), c=:blue, \n\t\t\txlims=(0,2), ylims=(0,1), \n\t\t\txlabel=\"x\", ylabel=\"F(x)\")\n\tp3 = plot( uGrid,quantile.(dist,uGrid), c=:blue, \n\t\t\txlims=(0,1), ylims=(0,2), \n\t\t\txlabel=\"u\", ylabel=(L\"F^{-1}(u)\"))\n\n\tplot(p1, p2, p3, legend=false, layout=(1,3), size=(1200, 400))\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.9\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═a715f0ac-2034-11eb-029c-9be9db193aed\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "f6e82ddefc6476785337919e36039587f92481cf", "size": 1267, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.09.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.09.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.09.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 24.8431372549, "max_line_length": 63, "alphanum_fraction": 0.679558011, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.8774767922879693, "lm_q1q2_score": 0.755979790684141}}
{"text": "\"\"\"\nUses UK Ordnance Survey \"A Guide to Coordinate Systems in Great Britain\"\nhttps://www.ordnancesurvey.co.uk/documents/resources/guide-coordinate-systems-great-britain.pdf\n\nWorked example (Airy1830)\nE = 651409.903 # meters\nN = 313177.270 # meters\n\n\"\"\"\nfunction OSENtoLLA(E,N)\n    # Airy 1830\n    a = 6377563.396\n    b = 6356256.909\n    e2 = (a^2 - b^2)/a^2\n    E0 = 400000\n    N0 = -100000\n    F0 = 0.9996012717\n    ϕ0 = 49 * (π/180)\n    λ0 = -2 * (π/180)\n\n\n    ϕ1 = (N - N0)/a*F0 + ϕ0\n    n=(a-b)/(a+b)\n    M_function(ϕ) = b*F0*( (1 + n + 5/4*n^2 + 5/4*n^3) * (ϕ-ϕ0)\n        - (3*n + 3*n^2 + 21/8*n^3) * sin(ϕ-ϕ0) * cos(ϕ+ϕ0)\n        + (15/8*n^2 + 15/8*n^3) * sin(2*(ϕ-ϕ0)) * cos(2*(ϕ+ϕ0))\n        - 35/24*n^3 * sin(3*(ϕ-ϕ0))*cos(3*(ϕ+ϕ0)))\n    residual(M) = (N-N0-M)\n    M = M_function(ϕ1)\n\n\n    while residual(M) > 0.00000001\n        ϕ1 = (residual(M)/a*F0) + ϕ1\n        M = M_function(ϕ1)\n    end\n\n    ϕ1 / (π/180)\n\n    ν = a * F0 * abs(1-e2*sin(ϕ1)^2)^(-0.5) # \\nu\n    ρ = a * F0 * (1-e2) * (1-e2*sin(ϕ1)^2)^(-1.5)\n    η2 = ν/ρ-1\n\n    VII = tan(ϕ1)/(2*ρ*ν)\n    VIII = tan(ϕ1)/(24*ρ*ν^3) * (5 + 3*tan(ϕ1)^2 + η2 - 9*(tan(ϕ1)^2)*η2)\n    IX = tan(ϕ1)/(720*ρ*ν^5) * (61 + 90*tan(ϕ1)^2 + 45*(tan(ϕ1)^4))\n    X = sec(ϕ1)/ν\n    XI = sec(ϕ1)/(6*ν^3) * (ν/ρ + 2*tan(ϕ1)^2)\n    XII = sec(ϕ1)/(120*ν^5) * (5 + 28*tan(ϕ1)^2 + 24*tan(ϕ1)^4)\n    XIIA = sec(ϕ1)/(5040*ν^7) * (61 + 662*tan(ϕ1)^2 + 1320*tan(ϕ1)^4 + 720*tan(ϕ1)^6)\n\n    ϕ = ϕ1 - VII*(E-E0)^2 + VIII*(E-E0)^4 - IX*(E-E0)^6\n    λ = λ0 + X*(E-E0) - XI*(E-E0)^3 + XII*(E-E0)^5 - XIIA*(E-E0)^7\n\n    return ϕ/(π/180), λ/(π/180)\nend\n", "meta": {"hexsha": "4fe5e5a4ad4a228adb4747db1cc6ae694269581a", "size": 1581, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Mapping/Conversion.jl", "max_stars_repo_name": "petedmccallum/ParaDwell.jl", "max_stars_repo_head_hexsha": "b7da4170c9594cc5808e7b8b89cbbba451d97f6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-05T16:20:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T16:20:35.000Z", "max_issues_repo_path": "src/Mapping/Conversion.jl", "max_issues_repo_name": "petedmccallum/ParaDwell.jl", "max_issues_repo_head_hexsha": "b7da4170c9594cc5808e7b8b89cbbba451d97f6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Mapping/Conversion.jl", "max_forks_repo_name": "petedmccallum/ParaDwell.jl", "max_forks_repo_head_hexsha": "b7da4170c9594cc5808e7b8b89cbbba451d97f6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2321428571, "max_line_length": 95, "alphanum_fraction": 0.4927261227, "num_tokens": 848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995762509216, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.7559733518715755}}
{"text": "############################# abstract QR type #################################\nabstract type AbstractQR{T} <: Factorization{T} end\n# AbstractQR assumes existence of n, m, Q, R fields\nBase.size(F::AbstractQR) = (F.n, F.m)\nBase.size(F::AbstractQR, i::Int) = i > 2 ? 1 : size(F)[i]\nBase.eltype(F::AbstractQR{T}) where T = T\n\nBase.:\\(F::AbstractQR, x::AbstractVecOrMat) = ldiv!(F, copy(x))\n\n# some helpers\n\"\"\"\n```\n    number_of_rotations(n::Int, m::Int)\n```\nComputes the number of Givens rotations that are necessary to compute the QR\nfactorization of a general matrix of size n by m.\n\"\"\"\nnumber_of_rotations(n::Int, m::Int) = n*m - (m*(m+1)) ÷ 2\nnumber_of_rotations(A::AbstractMatOrFac) = number_of_rotations(size(A)...)\n# min_nm = min(m, m) # IDEA: for overdetermined systems\n\n# to append k columns\nnumber_of_rotations_to_append_column(n::Int, m::Int, k::Int = 1) = k*(n-m) - (k*(k+1)) ÷ 2\n# to remove a single column at index k in R\nnumber_of_rotations_to_remove_column(m::Int, k::Int) = m-k\n\n\"\"\"\n```\n    allocate_rotations(T::DataType, n::Int, m::Int)\n```\nAllocates a vector of Givens rotations of a length that is necessary to compute\nthe QR factorization of a general matrix of size n by m.\n\"\"\"\nfunction allocate_rotations(T::DataType, n::Int, m::Int)\n    Vector{Givens{T}}(undef, number_of_rotations(n, m))\nend\nfunction allocate_rotations(A::AbstractMatOrFac)\n    allocate_rotations(eltype(A), size(A)...)\nend\n", "meta": {"hexsha": "4a35d2b01627fffa60cb49e804e276e81bdbc538", "size": 1415, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/abstract.jl", "max_stars_repo_name": "SebastianAment/UpdatableQRFactorizations.jl", "max_stars_repo_head_hexsha": "38a9cf7949c2b4da202dcc6ae21b1e5baa334722", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-10-30T06:55:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T02:26:19.000Z", "max_issues_repo_path": "src/abstract.jl", "max_issues_repo_name": "SebastianAment/UpdatableQRFactorizations.jl", "max_issues_repo_head_hexsha": "38a9cf7949c2b4da202dcc6ae21b1e5baa334722", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-10-29T21:18:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T21:12:49.000Z", "max_forks_repo_path": "src/abstract.jl", "max_forks_repo_name": "SebastianAment/UpdatableQRFactorizations.jl", "max_forks_repo_head_hexsha": "38a9cf7949c2b4da202dcc6ae21b1e5baa334722", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.375, "max_line_length": 90, "alphanum_fraction": 0.6692579505, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7558775680913071}}
{"text": "export AbstractNLS # TODO: do not export\nexport parameter_size, residue_size\nexport eval_r, eval_r_J\nexport eval_nls_fobj, eval_nls_∇fobj, eval_nls_∇∇fobj\n\nusing LinearAlgebra: dot, mul!\nusing LinearAlgebra.BLAS: BlasFloat, syrk!, gemv!\n\n@doc raw\"\"\"\n```julia\nabstract type AbstractNLS end \n```\n\nDefines an abstract non-linear least squares problem (NLS). In our\ncontext such problem is essentially a differentiable function ``\\mathbf{r}``:\n\n```math\n\\mathbf{r}: \\theta\\in\\mathbb{R}^{n_θ}\\mapsto \\mathbf{r}(\\mathbf{\\theta})\\in\\mathbb{R}^{n_S}\n``` \nwhere:\n- ``\\mathbf{r}(\\mathbf{θ})∈\\mathbb{R}^{n_S}`` is the residue vector,\n- ``\\mathbf{θ}∈\\mathbb{R}^{n_θ}`` is the parameter vector to be optimized\n\nThe objective function to minimize is:\n\n```math\nf(θ)=\\frac{1}{2}\\| \\mathbf{r}(θ) \\|^2\n``` \n\nThe classical approach uses a linear approximation of ``\\mathbf{r}``:\n```math\n\\mathbf{r}(\\mathbf{θ}+δ\\mathbf{θ})\\approx \\mathbf{r}(\\mathbf{θ}) + \\mathbf{J}(\\mathbf{θ})\\cdot δ\\mathbf{θ}\n``` \nwhere ``\\mathbf{J}`` is the Jacobian:\n```math\n\\mathbf{J}_{i,j}=\\partial_j r^i(\\mathbf{θ}),\\ i\\in[1,n_S],\\ j\\in[1,n_θ]\n```\nThis leads to\n```math\nf(\\mathbf{θ}+δ\\mathbf{θ})\\approx f(\\mathbf{θ}) + \\langle \\nabla f, δ\\mathbf{θ} \\rangle + \\frac{1}{2}  \\langle \\nabla^2 f \\cdot δ\\mathbf{θ},  δ\\mathbf{θ} \\rangle\n```\n\nWhere the gradient ``\\nabla f`` is ``\\mathbf{J}^t \\mathbf{r}`` and the\n(approximate) Hessian ``\\nabla^2 f`` is ``\\mathbf{J}^t \\mathbf{J}``.\n\nTo implement such model, you must define the following functions:\n- [`parameter_size`](@ref) : returns ``n_θ``\n- [`residue_size`](@ref) : returns ``n_S``\n- [`eval_r`](@ref) : compute ``\\mathbf{r}``\n- [`eval_r_J`](@ref) : compute ``(\\mathbf{r}, \\mathbf{J})``\n\"\"\"\nabstract type AbstractNLS end \n\n# ================================================================\n# Interface...\n# ================================================================\n#\n@doc raw\"\"\"\n    parameter_size(nls::AbstractNLS) \n\nReturn the dimension ``n_θ`` of the parameter vector ``θ``.\n\"\"\"\nparameter_size(nls::AbstractNLS) = @assert(false,\"To implement\")\n\n@doc raw\"\"\"\n    sample_size(nls::AbstractNLS) \n\nReturn the dimension ``n_S`` of the residue vector ``r``.\n\"\"\"\nresidue_size(nls::AbstractNLS) = @assert(false,\"To implement\")\n\n@doc raw\"\"\" \n```julia\neval_r(nls::AbstractNLS,\n        θ::AbstractVector) -> r\n```\n\nCompte the residual vector ``\\mathbf{r}``\n\"\"\"\neval_r(nls::AbstractNLS,\n       θ::AbstractVector) = @assert(false,\"To implement\")\n\n@doc raw\"\"\" \n```julia\neval_r_J(nls::AbstractNLS,θ::AbstractVector) -> (r,J)\n```\n\nCompute the residual the vector ``\\mathbf{r}`` and its Jacobian ``\\mathbf{J}`` \n\"\"\"\neval_r_J(nls::AbstractNLS,\n         θ::AbstractVector) = @assert(false,\"To implement\")\n\n# ================================================================\n# Convenience functions...\n# ================================================================\n#\n\n@doc raw\"\"\"\n```julia\neval_nls_fobj(r::AbstractVector{T}) -> f(θ)\n```\n\nCompute ``f(θ)=\\frac{1}{2}\\| \\mathbf{r}(\\mathbf{θ}) \\|^2``\n\"\"\"\neval_nls_fobj(r::AbstractVector) = dot(r,r)/2\n\n@doc raw\"\"\"\n```julia\neval_nls_∇fobj(r,J) -> ∇fobj\n```\n\nCompute the gradient: ``\\nabla f(\\mathbf{θ}) = \\mathbf{J}^t\\mathbf{r}``\n\"\"\"\nfunction eval_nls_∇fobj(r::AbstractVector, J::AbstractMatrix)\n    J'*r\nend\n    \n@doc raw\"\"\"\n```julia\neval_nls_∇∇fobj(J) -> ∇∇fobj\n```\n\nCompute the (approximate) Hessian: ``\\nabla^2 f(\\mathbf{θ}) = \\mathbf{J}^t\\mathbf{J}``\n\"\"\"\nfunction eval_nls_∇∇fobj(J::AbstractMatrix) \n    Symmetric(J'*J)\nend\n    \n\n\n", "meta": {"hexsha": "e3734d40857d4ba7779ec88803604c519e106f56", "size": 3474, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/abstract_nls.jl", "max_stars_repo_name": "vincent-picaud/NLS_Solver.jl", "max_stars_repo_head_hexsha": "55d1a21e2128427ce168579ee67bde6f3499870b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-02T14:49:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T19:49:40.000Z", "max_issues_repo_path": "src/abstract_nls.jl", "max_issues_repo_name": "vincent-picaud/NLS_Solver.jl", "max_issues_repo_head_hexsha": "55d1a21e2128427ce168579ee67bde6f3499870b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-12-25T23:06:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-30T21:04:01.000Z", "max_forks_repo_path": "src/abstract_nls.jl", "max_forks_repo_name": "vincent-picaud/NLS_Solver.jl", "max_forks_repo_head_hexsha": "55d1a21e2128427ce168579ee67bde6f3499870b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5190839695, "max_line_length": 160, "alphanum_fraction": 0.601324122, "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7558775628147286}}
{"text": "# retrieve apm.jl from GitHub or APMonitor.com\ninclude(\"../apm.jl\")\n\ns = \"http://byu.apmonitor.com\"\na = \"minlp\"\n\napm(s,a,\"clear all\")\n\n#  minimize    f(x)\n#  subject to  h(x) > 0\n#              g(x) = 0\n#\n# In this case:\n#  f(x) = x1*x4*(x1+x2+x3) + x3\n#  h(x) = x1*x2*x3*x4 - 25\n#  g(x) = x1^2 + x2^2 + x3^2 + x4^2 - 40\n#\n# x1 and x2 are continuous variables\n# int_x3 and int_x4 are integer variables\n\nif isfile(\"minlp.apm\")\n  # Load model file (if it exists)\n  apm_load(s,a,\"minlp.apm\")\nelse\n  # Declare variables and equations here\n  # Declare variables\n  apm(s,a,\"Variables\")\n  apm(s,a,\" x1 = 1, >=1, <=5\")\n  apm(s,a,\" x2 = 5, >=1, <=5\")\n  apm(s,a,\" int_x3 = 5, >=1, <=5\")\n  apm(s,a,\" int_x4 = 1, >=1, <=5\")\n\n  # Declare objective and equations\n  apm(s,a,\"Equations\")\n  apm(s,a,\" minimize x1*int_x4*(x1+x2+int_x3) + int_x3\")\n  apm(s,a,\" x1*x2*int_x3*int_x4 > 25\")\n  apm(s,a,\" x1^2 + x2^2 + int_x3^2 + int_x4^2 = 40\")\nend\n\n# Solve optimization problem\noutput = apm(s,a,\"solve\")\nprintln(output)\n\n# Retrieve solution\ny = apm_sol(s,a)\n\nprintln(\"Solution Results\")\nprintln(\"  x1 = \" * string(y[\"x1\"]))\nprintln(\"  x2 = \" * string(y[\"x2\"]))\nprintln(\"  int_x3 = \" * string(y[\"int_x3\"]))\nprintln(\"  int_x4 = \" * string(y[\"int_x4\"]))\n", "meta": {"hexsha": "72d5e6cc401b9cfced17adc79cabd9f3fd4e1299", "size": 1228, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "minlp/minlp.jl", "max_stars_repo_name": "APMonitor/apm_julia", "max_stars_repo_head_hexsha": "4a8ae7826be5fabd81860e0dc9d713d85a57908c", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-07-23T18:03:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:41:02.000Z", "max_issues_repo_path": "minlp/minlp.jl", "max_issues_repo_name": "APMonitor/apm_julia", "max_issues_repo_head_hexsha": "4a8ae7826be5fabd81860e0dc9d713d85a57908c", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-07-07T05:23:03.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-11T11:56:08.000Z", "max_forks_repo_path": "minlp/minlp.jl", "max_forks_repo_name": "APMonitor/apm_julia", "max_forks_repo_head_hexsha": "4a8ae7826be5fabd81860e0dc9d713d85a57908c", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-11-19T02:28:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-05T16:56:11.000Z", "avg_line_length": 23.6153846154, "max_line_length": 56, "alphanum_fraction": 0.5863192182, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7558775610558689}}
{"text": "# The sea floor is getting steeper. Maybe the sleigh keys got carried this way?\n#\n# A massive school of glowing lanternfish swims past. They must spawn quickly\n# to reach such large numbers - maybe exponentially quickly? You should model\n# their growth rate to be sure.\n#\n# Although you know nothing about this specific species of lanternfish, you\n# make some guesses about their attributes. Surely, each lanternfish creates a\n# new lanternfish once every 7 days.\n#\n# However, this process isn't necessarily synchronized between every\n# lanternfish - one lanternfish might have 2 days left until it creates another\n# lanternfish, while another might have 4. So, you can model each fish as a\n# single number that represents the number of days until it creates a new\n# lanternfish.\n#\n# Furthermore, you reason, a new lanternfish would surely need slightly longer\n# before it's capable of producing more lanternfish: two more days for its\n# first cycle.\n#\n# So, suppose you have a lanternfish with an internal timer value of 3:\n#\n# - After one day, its internal timer would become 2.\n# - After another day, its internal timer would become 1.\n# - After another day, its internal timer would become 0.\n# - After another day, its internal timer would reset to 6, and it would create\n#   a new lanternfish with an internal timer of 8.\n# - After another day, the first lanternfish would have an internal timer of 5,\n#   and the second lanternfish would have an internal timer of 7.\n#\n# A lanternfish that creates a new fish resets its timer to 6, not 7 (because 0\n# is included as a valid timer value). The new lanternfish starts with an\n# internal timer of 8 and does not start counting down until the next day.\n#\n# Realizing what you're trying to do, the submarine automatically produces a\n# list of the ages of several hundred nearby lanternfish (your puzzle input).\n# For example, suppose you were given the following list:\n#\n# 3,4,3,1,2\n#\n# This list means that the first fish has an internal timer of 3, the second\n# fish has an internal timer of 4, and so on until the fifth fish, which has an\n# internal timer of 2. Simulating these fish over several days would proceed as\n# follows:\n#\n# Initial state: 3,4,3,1,2\n# After  1 day:  2,3,2,0,1\n# After  2 days: 1,2,1,6,0,8\n# After  3 days: 0,1,0,5,6,7,8\n# After  4 days: 6,0,6,4,5,6,7,8,8\n# After  5 days: 5,6,5,3,4,5,6,7,7,8\n# After  6 days: 4,5,4,2,3,4,5,6,6,7\n# After  7 days: 3,4,3,1,2,3,4,5,5,6\n# After  8 days: 2,3,2,0,1,2,3,4,4,5\n# After  9 days: 1,2,1,6,0,1,2,3,3,4,8\n# After 10 days: 0,1,0,5,6,0,1,2,2,3,7,8\n# After 11 days: 6,0,6,4,5,6,0,1,1,2,6,7,8,8,8\n# After 12 days: 5,6,5,3,4,5,6,0,0,1,5,6,7,7,7,8,8\n# After 13 days: 4,5,4,2,3,4,5,6,6,0,4,5,6,6,6,7,7,8,8\n# After 14 days: 3,4,3,1,2,3,4,5,5,6,3,4,5,5,5,6,6,7,7,8\n# After 15 days: 2,3,2,0,1,2,3,4,4,5,2,3,4,4,4,5,5,6,6,7\n# After 16 days: 1,2,1,6,0,1,2,3,3,4,1,2,3,3,3,4,4,5,5,6,8\n# After 17 days: 0,1,0,5,6,0,1,2,2,3,0,1,2,2,2,3,3,4,4,5,7,8\n# After 18 days: 6,0,6,4,5,6,0,1,1,2,6,0,1,1,1,2,2,3,3,4,6,7,8,8,8,8\n#\n# Each day, a 0 becomes a 6 and adds a new 8 to the end of the list, while each\n# other number decreases by 1 if it was present at the start of the day.\n#\n# In this example, after 18 days, there are a total of 26 fish. After 80 days,\n# there would be a total of 5934.\n#\n# Find a way to simulate lanternfish. How many lanternfish would there be after\n# 80 days?\n\n# read input\nfish = parse.(Int8, split(readline(\"input.txt\"), ','))\n\nfor _ in 1:80\n  fish .-= 1\n  replicating = findall(isequal(-1), fish)\n  if length(replicating) > 0\n    fish[replicating] .= 6\n    append!(fish, repeat([8], length(replicating)))\n  end\nend\n\nprintln(\"Number of fish: \", length(fish))\n", "meta": {"hexsha": "11d28cc1f98991171efcff77bc6eaa1373229721", "size": 3683, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day06/part1.jl", "max_stars_repo_name": "bmatcuk/adventofcode2021", "max_stars_repo_head_hexsha": "57b9297213acd271b73784fbbe38c5cc248d7c28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-07T14:21:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T14:21:53.000Z", "max_issues_repo_path": "day06/part1.jl", "max_issues_repo_name": "bmatcuk/adventofcode2021", "max_issues_repo_head_hexsha": "57b9297213acd271b73784fbbe38c5cc248d7c28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day06/part1.jl", "max_forks_repo_name": "bmatcuk/adventofcode2021", "max_forks_repo_head_hexsha": "57b9297213acd271b73784fbbe38c5cc248d7c28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8522727273, "max_line_length": 79, "alphanum_fraction": 0.700244366, "num_tokens": 1380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.755856444538874}}
{"text": "function construct_inpTheta(X_test, X_domain, X_boundary, set_sigma)\n    N_test = size(X_test)[1]\n    N_domain = size(X_domain)[1]\n    N_boundary = size(X_boundary)[1]\n    inpTheta = zeros((N_test, 2*N_domain+N_boundary))\n    for iter_i = 1:N_test\n        for iter_j = 1:N_domain\n            inpTheta[iter_i,iter_j] = Delta_x_kappa(X_test[iter_i,1],X_test[iter_i,2],X_domain[iter_j,1],X_domain[iter_j,2],set_sigma)\n        end\n        for iter_j = N_domain+1:2*N_domain\n            inpTheta[iter_i,iter_j] = kappa(X_test[iter_i,1],X_test[iter_i,2],X_domain[iter_j-N_domain,1],X_domain[iter_j-N_domain,2],set_sigma)\n        end\n        for iter_j = 2*N_domain+1:2*N_domain+N_boundary\n            inpTheta[iter_i,iter_j] = kappa(X_test[iter_i,1],X_test[iter_i,2],X_boundary[iter_j-2*N_domain,1],X_boundary[iter_j-2*N_domain,2],set_sigma)\n        end\n    end\n    return inpTheta\nend\n\nfunction extend_solution(X_test, X_domain, X_boundary, L, v, set_sigma)\n    inp_Theta = construct_inpTheta(X_test, X_domain, X_boundary, set_sigma)\n    return inp_Theta*(L'\\(L\\v))\nend\n\nfunction get_extended_solution(num_pts, X_domain, X_boundary, L, sol, set_sigma)\n    x = range(0,1,length=num_pts)\n    y = range(0,1,length=num_pts)\n    xx = x' .* ones(num_pts)\n    yy = ones(num_pts)' .* y\n    \n    xxv = Matrix{Float64}(reshape(xx,(num_pts^2,1)))\n    yyv = Matrix{Float64}(reshape(yy,(num_pts^2,1)))\n\n    X_test = hcat(xxv,yyv)\n\n    N_domain = size(X_domain)[1]\n    N_boundary = size(X_boundary)[1]\n    rhs_f = zeros((N_domain,1))\n    bdy_g = zeros((N_boundary,1))\n\n    for iter_i = 1:N_domain\n        rhs_f[iter_i] = f(X_domain[iter_i,1],X_domain[iter_i,2])\n    end\n    for iter_i = 1:N_boundary\n        bdy_g[iter_i] = g(X_boundary[iter_i,1],X_boundary[iter_i,2])\n    end\n\n#     X_test=hcat([[x[i];y[j]] for i = 1 : num_pts for j = 1 : num_pts])\n    temp_vec = [alpha*sol.^m-rhs_f; sol; bdy_g]\n    u_extended = Matrix{Float64}(reshape(extend_solution(X_test, X_domain, X_boundary, L, temp_vec, set_sigma),(num_pts,num_pts)))\n    return x, y, u_extended\nend", "meta": {"hexsha": "fb8707e9b612a6f725d7324b3ec6308f1b0232e9", "size": 2042, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/extend_solution.jl", "max_stars_repo_name": "yifanc96/NonlinearPDE-GP", "max_stars_repo_head_hexsha": "3358e020424c185f62f97b24b85c176840d6abe6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-16T02:58:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T02:58:59.000Z", "max_issues_repo_path": "src/extend_solution.jl", "max_issues_repo_name": "yifanc96/NonlinearPDE-GP", "max_issues_repo_head_hexsha": "3358e020424c185f62f97b24b85c176840d6abe6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/extend_solution.jl", "max_forks_repo_name": "yifanc96/NonlinearPDE-GP", "max_forks_repo_head_hexsha": "3358e020424c185f62f97b24b85c176840d6abe6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2692307692, "max_line_length": 152, "alphanum_fraction": 0.6718903036, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7558564412832145}}
{"text": "# FIXME:: grooming\n\n\n# --[ (a*b+c*d) -> muladd ]\n# LJR\n\nex = :(a1*b1 + a2*b2 + a3*b3 + a4*b4)\n# :(a1 * b1 + a2 * b2 + a3 * b3 + a4 * b4)\n\nco = [Symbol.(ex.args[i].args[2:3]) for i in 2:length(ex.args)]\n#4-element Array{Array{Symbol,1},1}:\n# Symbol[:a1, :b1]\n# Symbol[:a2, :b2]\n# Symbol[:a3, :b3]\n# Symbol[:a4, :b4]\n\nres = Expr(:call, :*, co[end]...)\n# :(a4 * b4)\n\nfor i in (length(co)-1):-1:1\n    res = :(muladd( $(co[i]...), $res ))\nend\n\nres\n#:(muladd(a1, b1, muladd(a2, b2, muladd(a3, b3, a4 * b4))))\n\nfunction _muladd_transform(ex)\n    if length(ex.args) == 2\n        return ex.args[2]\n    else\n    a, b = ex.args[2].args[2:end]\n    rest = _muladd_transform(Expr(ex.head, :+, ex.args[3:end]...))\n    return :($(Base.muladd)($a, $b, $rest))\n    end\nend\n\nfunction _muladd_rewrite(ex)\n    co = [Symbol.(ex.args[i].args[2:3]) for i in 2:length(ex.args)]\n    res = Expr(:call, :*, co[end]...)\n    for i in (length(co)-1):-1:1\n        res = :(muladd( $(co[i]...), $res ))\n    end\n    res\nend\n\n# Symbolic diff\n# LJR\n\nstruct SymbolFun{T} end\nSymbolFun(S::Symbol) = SymbolFun{S}()\n\nD(ex::Symbol, x::Symbol) = ex == x ? 1 :0\nD(ex::Number, x::Symbol) = 0\n\nfunction D(ex::Expr, x)\n    @assert ex.head == :call\n    D(SymbolFun(ex.args[1]), ex.args[2:end], x)\nend\n\nD(fun::SymbolFun{T}, args, x) where T = error(\"string(T) function is not supported!\")\n\n# Power Rule\nfunction D(::SymbolFun{:^}, args, x)\n    a, b = args[1], args[2]\n    da, db = D(a, x), D(b, x)\n    if da == 0 && db == 0    # if a^b is constant: a^b -> 0\n        return 0\n    elseif db == 0           # if b is constant: a^b -> b*da*a^(b-1)\n        return :( $b* $da * ($a ^ ($b - 1)) )\n    else                     # a(x)^b(x) -> http://www.wolframalpha.com/input/?source=frontpage-immediate-access&i=d%2Fdx+a(x)%5Eb(x)\n                             # I don't know, just ask Wolfram Alpha!\n        :( $a ^ ($b - 1) * ($da * $b + $a * log($a) * $db) )\n    end\nend\n\n# Product Rule\n# d/dx (f * g) = (d/dx f) * g + f * (d/dx g)\n# d/dx (f * g * h) = (d/dx f) * g * h + f * (d/dx g) * h + ...\nfunction D(::SymbolFun{:*}, args, x)\n    N = length(args)\n    outer_args = Vector{Any}(N)\n    for i in 1:N\n        inner_args = Vector{Any}(N)\n        for j in 1:N\n            i == j ? inner_args[j] = D(args[j], x) : inner_args[j] = args[j]\n        end\n        outer_args[i] = Expr(:call, :*, inner_args...)\n    end\n    Expr(:call, :+, outer_args...)\nend\n\n# The Quotient Rule\n# d/dx (f / g) = ((d/dx f) * g - f * (d/dx g)) / g^2\nfunction D(::SymbolFun{:/}, args, x)\n    f, g = args[1], args[2]\n    df, dg = D(f, x), D(g, x)\n    if df == 0 && dg == 0\n        return 0\n    elseif df == 0\n        return :( -$dg * $f / $g^2 )\n    elseif dg == 0\n        return :( $df / $g )\n    else\n        return :( ($df * $g - $f * $dg) / $g^2 )\n    end\nend\n\nfunction D(::SymbolFun{:+}, args, x)\n    terms = Any[:+]\n    for y in args\n        dx = D(y, x)\n        if dx != 0\n            push!(terms, dx)\n        end\n    end\n    if (length(terms) == 1)\n        return 0\n    elseif (length(terms) == 2)\n        return terms[2]\n    else\n        return Expr(:call, terms...)\n    end\nend\n\nfunction D(::SymbolFun{:-}, args, x)\n    terms = Any[:-]\n    term1 = D(args[1], x)\n    push!(terms, term1)\n    for y in args[2:end]\n        dx = D(y, x)\n        if dx != 0\n            push!(terms, dx)\n        end\n    end\n    if term1 != 0 && length(terms) == 2 && length(args) >= 2\n        return term1\n    elseif (term1 == 0 && length(terms) == 2)\n        return 0\n    else\n        return Expr(:call, terms...)\n    end\nend\n\nD(fun::SymbolFun{T}, args, x) where T = error(\"$(string(T)) function is not supported!\")\n\n[1:57] \n ```julia> ex = :(11x^3 + 12 + 13x^5 + 14x^9)\n:(11 * x ^ 3 + 12 + 13 * x ^ 5 + 14 * x ^ 9)\n\njulia> Meta.show_sexpr(ex)\n(:call, :+, (:call, :*, 11, (:call, :^, :x, 3)), 12, (:call, :*, 13, (:call, :^,\n:x, 5)), (:call, :*, 14, (:call, :^, :x, 9)))```\n", "meta": {"hexsha": "e6a68306cf4f284265703dcbed844bf2ebd9c039", "size": 3879, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/jl/symdiff.jl", "max_stars_repo_name": "cdluminate/MyNotes", "max_stars_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/jl/symdiff.jl", "max_issues_repo_name": "cdluminate/MyNotes", "max_issues_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/jl/symdiff.jl", "max_forks_repo_name": "cdluminate/MyNotes", "max_forks_repo_head_hexsha": "cf28f2a3fa72723153147e21fed5e7b598baf44f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3529411765, "max_line_length": 133, "alphanum_fraction": 0.4859499871, "num_tokens": 1479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.755856434375431}}
{"text": "using LinearAlgebraicRepresentation\nusing LARVIEW\n\nVOID = [[]], [[1]]\n\n\n# example 1\n\nV = [[0,0] [1,0] [2,0] [0,1] [1,1] [2,1] [0,2] [1,2] [2,2]];\nFV = [[1,2,4],[2,3,5],[3,5,6],[4,5,7],[5,7,8],[6,8,9]];\npattern = repeat([1,2,-3],outer=4);\nmodel = (V,FV);\nW,FW = LinearAlgebraicRepresentation.extrudeSimplicial(model, pattern);\nLARVIEW.view(W,FW)\n\n# example 2\n\nmodel = LinearAlgebraicRepresentation.extrudeSimplicial( VOID, ones(10) )\nLARVIEW.view(model)\nmodel = LinearAlgebraicRepresentation.extrudeSimplicial( model, ones(10) )\nLARVIEW.view(model)\nmodel = LinearAlgebraicRepresentation.extrudeSimplicial( model, ones(10) )\nLARVIEW.view(model)\n\n\n# example 3\n\nmodel = LinearAlgebraicRepresentation.extrudeSimplicial( VOID, repeat([1,-1],outer=10) )\nLARVIEW.view(model)\nmodel = LinearAlgebraicRepresentation.extrudeSimplicial( model, repeat([1,-1],outer=10) )\nLARVIEW.view(model)\n\n\n# example 4\n\ngrid_2d = LinearAlgebraicRepresentation.simplexGrid([3,3])\nLARVIEW.view(grid_2d)\ngrid_3d = LinearAlgebraicRepresentation.simplexGrid([2,3,4])\nLARVIEW.view(grid_3d)\nV,CV = LinearAlgebraicRepresentation.simplexGrid([1,1,1])\nLARVIEW.view(V,CV)\n\n# example 5\n\nSK2 = LinearAlgebraicRepresentation.simplexFacets(CV)\nLARVIEW.view(V, SK2)\nSK1 = LinearAlgebraicRepresentation.simplexFacets(SK2)\nLARVIEW.view(V, SK1)\n\n", "meta": {"hexsha": "bc76a697a545903ad5b1bc5ab620a1f9473a8a38", "size": 1299, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia-1.0/examples/simplexn_examples.jl", "max_stars_repo_name": "EmaLoprevite/Simplexn", "max_stars_repo_head_hexsha": "02e25954b67206351684429a8ad1d35cb06b9a53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-31T11:06:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T05:09:35.000Z", "max_issues_repo_path": "julia-1.0/examples/simplexn_examples.jl", "max_issues_repo_name": "EmaLoprevite/Simplexn", "max_issues_repo_head_hexsha": "02e25954b67206351684429a8ad1d35cb06b9a53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia-1.0/examples/simplexn_examples.jl", "max_forks_repo_name": "EmaLoprevite/Simplexn", "max_forks_repo_head_hexsha": "02e25954b67206351684429a8ad1d35cb06b9a53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.98, "max_line_length": 89, "alphanum_fraction": 0.739799846, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.8080672135527631, "lm_q1q2_score": 0.7558228537392961}}
{"text": "#=\nWe shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.\n\nThe product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.\n\nFind the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.\n\nHINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.\n=#\ninclude(\"projecteulerutils.jl\")\nusing Combinatorics\nfunction calc()\n  matches = Int64[]\n  for c in permutations(collect(1:9))\n    c1,c2,c3 = c[1:2],c[3:5],c[6:9] # 2x3\n    d1,d2,d3 = c[1:1],c[2:5], c[6:9] # 1x4\n    if nd(c1) * nd(c2) == nd(c3)\n      push!(matches, nd(c3))\n    end\n    if nd(d1) * nd(d2) == nd(d3)\n      push!(matches, nd(d3))\n    end\n  end\n  sum(unique(matches))\nend\n@time println(calc())\n", "meta": {"hexsha": "999641e1c2db7eaa9da401b5e702e123ec682a38", "size": 951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p32.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p32.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p32.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 35.2222222222, "max_line_length": 171, "alphanum_fraction": 0.6855941115, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.755822850826621}}
{"text": "\"This function computes finite difference stencil coefficients which approximate the\nkth derivative of a function at a point x̄ using a linear combination of evaluations at x_i.\"\n\nfunction fdcoeffV(k,x̄,x)\n    n = length(x)\n    if n <= k\n        error(\"Too few points in the stencil\")\n    end\n    A = zeros(n,n)\n    A[1,:] = ones(n)\n    for i = 2:n\n        A[i,:] = @. (x - x̄)^(i-1) / factorial(i-1) # ∑ a_i * (x_i - x̄)^i/i! = b_i\n    end\n    b = zeros(n,1)\n    b[k+1] = 1\n    return vec(A\\b)\nend\n", "meta": {"hexsha": "5262afe626ef1647eff1988f02d8be6efe7c3695", "size": 499, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week1/fdcoeffV.jl", "max_stars_repo_name": "jlchan/caam452_s21", "max_stars_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:38:43.000Z", "max_issues_repo_path": "week1/fdcoeffV.jl", "max_issues_repo_name": "jlchan/caam452_s21", "max_issues_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week1/fdcoeffV.jl", "max_forks_repo_name": "jlchan/caam452_s21", "max_forks_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7222222222, "max_line_length": 93, "alphanum_fraction": 0.5811623246, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7558228494159571}}
{"text": "using DiffEqOperators, Setfield, Parameters\nusing LinearAlgebra, Plots, SparseArrays\nusing BifurcationKit\n\nplotsol(x, Nx=Nx, Ny=Ny) = heatmap(reshape(Array(x), Nx, Ny)', color=:viridis)\nplotsol!(x, Nx=Nx, Ny=Ny; kwargs...) = heatmap!(reshape(Array(x), Nx, Ny)'; color=:viridis, kwargs...)\n\nNx = 151\n\tNy = 100\n\tlx = 8pi\n\tly = 2*2pi/sqrt(3)\n\nfunction Laplacian2D(Nx, Ny, lx, ly, bc = :Neumann)\n\thx = 2lx/Nx\n\thy = 2ly/Ny\n\tD2x = CenteredDifference(2, 2, hx, Nx)\n\tD2y = CenteredDifference(2, 2, hy, Ny)\n\tif bc == :Dirichlet\n\t\tQx = Dirichlet0BC(typeof(hx))\n\t\tQy = Dirichlet0BC(typeof(hy))\n\telseif bc == :Neumann\n\t\tQx = Neumann0BC(hx)\n\t\tQy = Neumann0BC(hy)\n\telseif bc == :Periodic\n\t\tQx = PeriodicBC(hx)\n\t\tQy = PeriodicBC(hy)\n\tend\n\t# @show norm(D2x - Circulant(D2x[1,:]))\n\tA = kron(sparse(I, Ny, Ny), sparse(D2x * Qx)[1]) + kron(sparse(D2y * Qy)[1], sparse(I, Nx, Nx))\n\treturn A, D2x\nend\n\nfunction F_sh(u, p)\n\t@unpack l, ν, L1 = p\n\treturn -L1 * u .+ (l .* u .+ ν .* u.^2 .- u.^3)\nend\n\nfunction dF_sh(u, p)\n\t@unpack l, ν, L1 = p\n\treturn -L1 .+ spdiagm(0 => l .+ 2 .* ν .* u .- 3 .* u.^2)\nend\n\nd2F_sh(u, p, dx1, dx2) = (2 .* p.ν .* dx2 .- 6 .* dx2 .* u) .* dx1\nd3F_sh(u, p, dx1, dx2, dx3) = (-6 .* dx2 .* dx3) .* dx1\njet = (F_sh, dF_sh, d2F_sh, d3F_sh)\n\nX = -lx .+ 2lx/(Nx) * collect(0:Nx-1)\nY = -ly .+ 2ly/(Ny) * collect(0:Ny-1)\n\nsol0 = [(cos(x) .+ cos(x/2) * cos(sqrt(3) * y/2) ) for x in X, y in Y]\n\tsol0 .= sol0 .- minimum(vec(sol0))\n\tsol0 ./= maximum(vec(sol0))\n\tsol0 = sol0 .- 0.25\n\tsol0 .*= 1.7\n\theatmap(sol0', color=:viridis)\n\nΔ, D2x = Laplacian2D(Nx, Ny, lx, ly, :Neumann)\nL1 = (I + Δ)^2\npar = (l = -0.1, ν = 1.3, L1 = L1)\n\noptnew = NewtonPar(verbose = true, tol = 1e-8, maxIter = 20)\n# optnew = NewtonPar(verbose = true, tol = 1e-8, maxIter = 20, eigsolver = EigArpack(0.5, :LM))\n\tsol_hexa, hist, flag = @time newton(F_sh, dF_sh, vec(sol0), par, optnew)\n\tprintln(\"--> norm(sol) = \", norm(sol_hexa, Inf64))\n\tplotsol(sol_hexa)", "meta": {"hexsha": "f451d632b941f26b4535c3198713ca8a196cf807", "size": 1924, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/test_SH.jl", "max_stars_repo_name": "oashour/PatternFormation.jl", "max_stars_repo_head_hexsha": "9944e922c75ca88b666f782627c334ff26d06d7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test_SH.jl", "max_issues_repo_name": "oashour/PatternFormation.jl", "max_issues_repo_head_hexsha": "9944e922c75ca88b666f782627c334ff26d06d7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test_SH.jl", "max_forks_repo_name": "oashour/PatternFormation.jl", "max_forks_repo_head_hexsha": "9944e922c75ca88b666f782627c334ff26d06d7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6, "max_line_length": 102, "alphanum_fraction": 0.5992723493, "num_tokens": 846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7558206353519088}}
{"text": "# Copyright (c) 2021, Eric Sabo\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nfunction ord(n::Integer, q::Integer)\n    if q <= 0 || n <= 0\n        error(\"q and n both need to be positive. Passed: q = $q, n = $n\")\n    end\n\n    # finite stop instead of while\n    for i = 1:200\n        if mod(BigInt(q)^i, n) == 1\n            return i\n        end\n    end\n\n    error(\"Unable to compute order($q, $n).\")\nend\n\nfunction cyclotomiccoset(x::Integer, q::Integer, n::Integer, verbose::Bool=false)\n    # keep small order assumption for now\n    temp = [mod(x, n)]\n    for i = 0:(n - 1)\n        y = mod(temp[end] * q, n)\n        if y ∉ temp\n            append!(temp, y)\n        else\n            break\n        end\n    end\n    sort!(temp)\n    len = length(temp)\n\n    if verbose\n        print(\"C_$x = {\")\n        for (i, y) in enumerate(temp)\n            if i != len\n                print(\"$y, \")\n            else\n                println(\"$y}\")\n            end\n        end\n    end\n\n    return temp\nend\n\nfunction allcyclotomiccosets(q::Integer, n::Integer, verbose::Bool=false)\n    if n % q == 0\n        error(\"Cyclotomic coset requires gcd(n, q) = 1\")\n    end\n\n    arr = [[0]]\n    for x in 1:(n - 1)\n        found = false\n        for a in arr\n            if x ∈ a\n                found = true\n                break\n            end\n        end\n\n        if !found\n            Cx = cyclotomiccoset(x, q, n, false)\n            push!(arr, Cx)\n        end\n    end\n    #\n    # sort!(arr, by=x->x[1])\n\n    if verbose\n        for Cx in arr\n            len = length(Cx)\n            print(\"C_$(Cx[1]) = {\")\n            for (i, y) in enumerate(Cx)\n                if i != len\n                    print(\"$y, \")\n                else\n                    println(\"$y}\")\n                end\n            end\n        end\n    end\n\n    if sort!(vcat(arr...)) != [i for i in 0:(n - 1)]\n        error(\"Missed some\")\n    end\n\n    return arr\nend\n\nfunction complementqcosets(q::Integer, n::Integer, qcosets::Vector{Vector{Int64}})\n    all = allcyclotomiccosets(q, n)\n    compcosets = Vector{Vector{Int64}}()\n    for a in all\n        # if a != [0]\n            found = false\n            for b in qcosets\n                if a[1] == b[1]\n                    found = true\n                    break\n                end\n            end\n\n            if !found\n                push!(compcosets, a)\n            end\n        # end\n    end\n\n    return compcosets\nend\n\nfunction qcosetpairings(arr::Vector{Vector{Int64}}, n::Integer)\n    cosetreplist = Vector{Tuple{Int64, Int64}}()\n    cosetpairlist = Vector{Tuple{Vector{Int64}, Vector{Int64}}}()\n    for a in arr\n        found = false\n        for pair in cosetreplist\n            if a[1] == pair[1] || a[1] == pair[2]\n                found = true\n            end\n        end\n\n        if !found\n            neg = sort!([mod(n - i, n) for i in a])\n            if neg == a\n                push!(cosetreplist, (a[1], a[1]))\n                push!(cosetpairlist, (a, a))\n            else\n                for b in arr\n                    if neg == b\n                        push!(cosetreplist, (a[1], b[1]))\n                        push!(cosetpairlist, (a, b))\n                        break\n                    end\n                end\n            end\n        end\n    end\n\n    return cosetpairlist, cosetreplist\nend\n\nfunction qcosetpairings(q::Integer, n::Integer)\n    arr = allcyclotomiccosets(q, n, false)\n    return qcosetpairings(arr, n)\nend\n\nfunction qcosettable(a::Integer, b::Integer, q::Integer)\n    for n in a:b\n        if n % q != 0\n            println(\"n = $n\")\n            allcyclotomiccosets(q, n, true)\n            println(\" \")\n        end\n    end\nend\n\nfunction dualqcosets(q::Integer, n::Integer, qcosets::Vector{Vector{Int64}})\n    compcosets = complementqcosets(q, n, qcosets)\n    for a in compcosets\n        for (i, x) in enumerate(a)\n            a[i] = mod(n - a[i], n)\n        end\n        sort!(a)\n    end\n\n    return compcosets\nend\n", "meta": {"hexsha": "dcae5cd1133cebf0ffeaaf1697c966832889b7ae", "size": 4050, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cyclotomic.jl", "max_stars_repo_name": "esabo/CodingTheory", "max_stars_repo_head_hexsha": "e01cf289d6af3884a78796d15e47ed9957fd3279", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-20T03:10:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T10:55:19.000Z", "max_issues_repo_path": "src/cyclotomic.jl", "max_issues_repo_name": "esabo/CodingTheory", "max_issues_repo_head_hexsha": "e01cf289d6af3884a78796d15e47ed9957fd3279", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cyclotomic.jl", "max_forks_repo_name": "esabo/CodingTheory", "max_forks_repo_head_hexsha": "e01cf289d6af3884a78796d15e47ed9957fd3279", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4104046243, "max_line_length": 82, "alphanum_fraction": 0.4711111111, "num_tokens": 1155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7558206280239601}}
{"text": "#Constant mean function\n\n@doc \"\"\"\n# Description\nConstructor for the constant mean function\n\nm(x) = β\n# Arguments:\n* `β::Float64`: Constant\n\"\"\" ->\ntype MeanConst <: Mean\n    β::Float64\n    MeanConst(β::Float64) = new(β)\nend\n\n@doc \"\"\"\n# Description\nConstructor for the zero mean function\n\nm(x) = 0\n\"\"\" ->\nMeanZero() = MeanConst(0.0)\n\nmean(mConst::MeanConst,x::Matrix{Float64}) =  fill(mConst.β, size(x,2))\n\nget_params(mConst::MeanConst) = Float64[mConst.β]\nget_param_names(::MeanConst) = [:β]\nnum_params(mConst::MeanConst) = 1\nfunction set_params!(mConst::MeanConst, hyp::Vector{Float64})\n    length(hyp) == 1 || throw(ArgumentError(\"Constant mean function only has 1 parameter\"))\n    mConst.β = hyp[1]\nend\nfunction grad_mean(mConst::MeanConst, x::Vector{Float64})\n    dM_theta = ones(size(x,2))\n    return dM_theta\nend\n", "meta": {"hexsha": "d685959c0574137588f4d548fea01445acc36016", "size": 818, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/means/mConst.jl", "max_stars_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/means/mConst.jl", "max_issues_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/means/mConst.jl", "max_forks_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1081081081, "max_line_length": 91, "alphanum_fraction": 0.6919315403, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7558206270557248}}
{"text": "#Essa função de eliminação retorna U, depois de fazer a decomposição LU.\n#Função faz pivotamento.\n\n\n############\n#Observação#\n############\n\n# Para usar essa função é necessario mandar uma matriz AA que seja do tipo float\n# tentei fazer a conversão de tipo porem os resultados saiam como se fossem um número inteiro.\n\nfunction eliminacao01(A)\n\tA\n\tepsilon = 0.00001;\n\t(m, n) = size(A);\n\t\n\tfor i = 1:n-1\n\t\tpivot = A[i,i];\n\n\t\tif abs(pivot) < epsilon\n\n\t\t\tfor k = i+1:m\n\t\t\t\tif abs(A[k,i] > epsilon)\n\n\t\t\t\t\tpivot = A[k,i];\n\t\t\t\t\tauxlinha = copy(A[k,:]);\n\t\t\t\t\tA[k,:] = copy(A[i,:]);\n\t\t\t\t\tA[i,:] = auxlinha;\n\t\t\t\t\tbreak\n\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\n\t\tfor j = i+1:m\n\n\t\t\tmult = A[j,i]/pivot;\n\t\t\tA[j,:] = A[j,:] - mult*A[i,:];\n\t\t\t\n\n\t\tend\n\t\t\n\tend\n\n\treturn A;\n\n\nend", "meta": {"hexsha": "765be03d2f65ea85b192a8e7f951777f6a883640", "size": 743, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/eliminacao01.jl", "max_stars_repo_name": "italonicacio/Algebra_Linear_Computacional_2019.1", "max_stars_repo_head_hexsha": "b7f1540fb16cdbf6db15d88da8c38ba83db866b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-30T02:51:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-30T02:51:30.000Z", "max_issues_repo_path": "julia/eliminacao01.jl", "max_issues_repo_name": "italonicacio/Algebra_Linear_Computacional_2019.1", "max_issues_repo_head_hexsha": "b7f1540fb16cdbf6db15d88da8c38ba83db866b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/eliminacao01.jl", "max_forks_repo_name": "italonicacio/Algebra_Linear_Computacional_2019.1", "max_forks_repo_head_hexsha": "b7f1540fb16cdbf6db15d88da8c38ba83db866b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.1632653061, "max_line_length": 94, "alphanum_fraction": 0.5693135935, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7558206270557248}}
{"text": "# p34.jl - Allen-Cahn eq. u_t = eps*u_xx+u-u^3, u(-1)=-1, u(1)=1\n#         (compare p6.jl and p32.jl)\n\n# Differentiation matrix and initial data:\nN = 20; (D,x) = cheb(N); D2 = D^2;     # use full-size matrix\nD2[[1,N+1],:] = 0;                     # for convenience\neps = 0.01; dt = min(.01,50/(N^4*eps));\nt = 0.0; v = @. .53*x + .47*sin(-1.5*pi*x);\n\n# Solve PDE by Euler formula and plot results:\ntmax = 100; tplot = 2; nplots = round(Int,tmax/tplot);\nplotgap = round(Int,tplot/dt); dt = tplot/plotgap;\nxx = -1:.025:1; vv = polyval(polyfit(x,v),xx);\nplotdata = [vv zeros(length(xx),nplots)]; tdata = t;\nfor i = 1:nplots\n    for n = 1:plotgap\n        t = t+dt; v = v + dt*(eps*D2*(v-x) + v - v.^3);    # Euler\n    end\n    vv = polyval(polyfit(x,v),xx);\n    plotdata[:,i+1] = vv; tdata = [tdata; t];\nend\nclf();\nsurf(xx,tdata,plotdata'); grid(true);\nxlim(-1,1); ylim(0,tmax); zlim(-1,1);\ngca()[:view_init](55,-150);\nxlabel(\"x\"); ylabel(\"t\"); zlabel(\"u\");\n", "meta": {"hexsha": "07c67eb0e482d014b080dea7ea3ef3cbb65af5a5", "size": 952, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p34.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p34.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p34.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2592592593, "max_line_length": 66, "alphanum_fraction": 0.5577731092, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7557829103227013}}
{"text": "using DifferentialEquations\nusing ParameterizedFunctions\n\nball! = @ode_def BallBounce begin\n  dy =  v\n  dv = -g\nend g\n\nfunction condition(u,t,integrator)\n  u[1]\nend\n\nfunction affect!(integrator)\n    integrator.u[2] = -integrator.p[2] * integrator.u[2]\nend\n\nbounce_cb = ContinuousCallback(condition,affect!)\n\nu0 = [50.0,0.0]\ntspan = (0.0,15.0)\np = (9.8,0.9)\nprob = ODEProblem(ball!,u0,tspan,p,callback=bounce_cb)\n\nsol = solve(prob,Tsit5())\nusing Plots; gr()\nplot(sol)\n\n##########################################################\n\nfunction condition_kick(u,t,integrator)\n    t == 2\nend\n\nfunction affect_kick!(integrator)\n    integrator.u[2] += 50\nend\n\nkick_cb = DiscreteCallback(condition_kick,affect_kick!)\nu0 = [50.0,0.0]\ntspan = (0.0,10.0)\np = (9.8,0.9)\nprob = ODEProblem(ball!,u0,tspan,p,callback=kick_cb)\n\nsol = solve(prob,Tsit5(),tstops=[2.0])\nplot(sol)\n", "meta": {"hexsha": "4b5f1bba8f4ca731155b09b89847c108b6b68430", "size": 857, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code/week_five/bouncingball.jl", "max_stars_repo_name": "lwlss/MacPherson_2020", "max_stars_repo_head_hexsha": "cf4a3903d234a31ae3a445bb016fe744c381ed65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/week_five/bouncingball.jl", "max_issues_repo_name": "lwlss/MacPherson_2020", "max_issues_repo_head_hexsha": "cf4a3903d234a31ae3a445bb016fe744c381ed65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/week_five/bouncingball.jl", "max_forks_repo_name": "lwlss/MacPherson_2020", "max_forks_repo_head_hexsha": "cf4a3903d234a31ae3a445bb016fe744c381ed65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6304347826, "max_line_length": 58, "alphanum_fraction": 0.6499416569, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7557829073384441}}
{"text": "struct SqWasserstein <: DistributionsSemiMetric end\n\n# result type (e.g., for pairwise computations)\nfunction Distances.result_type(\n    ::SqWasserstein, ::Type{T1}, ::Type{T2}\n) where {T1<:Real,T2<:Real}\n    return promote_type(T1, T2)\nend\n\n# evaluations for normal distributions\nfunction (::SqWasserstein)(a::Normal, b::Normal)\n    μa, σa = params(a)\n    μb, σb = params(b)\n    return abs2(μa - μb) + abs2(σa - σb)\nend\n\nfunction (::SqWasserstein)(a::AbstractMvNormal, b::AbstractMvNormal)\n    μ1 = mean(a)\n    μ2 = mean(b)\n    Σ1 = cov(a)\n    Σ2 = cov(b)\n    return Distances.sqeuclidean(μ1, μ2) + OT.sqbures(Σ1, Σ2)\nend\n\nfunction (::SqWasserstein)(a::MvNormal, b::MvNormal)\n    μa, Σa = params(a)\n    μb, Σb = params(b)\n    return Distances.sqeuclidean(μa, μb) + OT.sqbures(Σa, Σb)\nend\n\n# evaluations for Laplace distributions\nfunction (::SqWasserstein)(a::Laplace, b::Laplace)\n    μa, βa = params(a)\n    μb, βb = params(b)\n    return abs2(μa - μb) + 2 * abs2(βa - βb)\nend\n\n# Wasserstein 2 distance\nstruct Wasserstein <: DistributionsMetric end\n\n# result type (e.g., for pairwise computations)\nfunction Distances.result_type(\n    ::Wasserstein, ::Type{T1}, ::Type{T2}\n) where {T1<:Real,T2<:Real}\n    return float(promote_type(T1, T2))\nend\n\nfunction (::Wasserstein)(a::Distribution, b::Distribution)\n    return sqrt(SqWasserstein()(a, b))\nend\n\n# Mixture Wasserstein distances\nstruct SqMixtureWasserstein{S} <: DistributionsSemiMetric\n    lpsolver::S\nend\nstruct MixtureWasserstein{S} <: DistributionsMetric\n    lpsolver::S\nend\nSqMixtureWasserstein() = SqMixtureWasserstein(Tulip.Optimizer())\nMixtureWasserstein() = MixtureWasserstein(Tulip.Optimizer())\n\n# result type (e.g., for pairwise computations)\nfunction Distances.result_type(\n    ::SqMixtureWasserstein, ::Type{T1}, ::Type{T2}\n) where {T1<:Real,T2<:Real}\n    return promote_type(T1, T2)\nend\nfunction Distances.result_type(\n    ::MixtureWasserstein, ::Type{T1}, ::Type{T2}\n) where {T1<:Real,T2<:Real}\n    return float(promote_type(T1, T2))\nend\n\nfunction (s::SqMixtureWasserstein)(a::AbstractMixtureModel, b::AbstractMixtureModel)\n    C = Distances.pairwise(SqWasserstein(), components(a), components(b))\n    return OT.emd2(probs(a), probs(b), C, deepcopy(s.lpsolver))\nend\n\nfunction (m::MixtureWasserstein)(a::AbstractMixtureModel, b::AbstractMixtureModel)\n    return sqrt(SqMixtureWasserstein(m.lpsolver)(a, b))\nend\n", "meta": {"hexsha": "0cc65403569791edf5502a896ee6641f98e1058d", "size": 2374, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances/wasserstein.jl", "max_stars_repo_name": "devmotion/CalibrationErrorsDistributions.jl", "max_stars_repo_head_hexsha": "101bbdbcab4fa4d99b1dd705f13f09c20f45bb0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-04T12:45:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T00:16:11.000Z", "max_issues_repo_path": "src/distances/wasserstein.jl", "max_issues_repo_name": "devmotion/CalibrationErrorsDistributions.jl", "max_issues_repo_head_hexsha": "101bbdbcab4fa4d99b1dd705f13f09c20f45bb0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2020-09-22T22:59:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T15:59:42.000Z", "max_forks_repo_path": "src/distances/wasserstein.jl", "max_forks_repo_name": "devmotion/CalibrationErrorsDistributions.jl", "max_forks_repo_head_hexsha": "101bbdbcab4fa4d99b1dd705f13f09c20f45bb0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9512195122, "max_line_length": 84, "alphanum_fraction": 0.7080876158, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8056321889812554, "lm_q1q2_score": 0.7557829059447442}}
{"text": "using ChebyshevPicardIteration\nusing DifferentialEquations\nusing Plots\n\n# First Test\nϵ = 0.001\nf(t,y) = cos(t .+ ϵ*y)\n\nt0 = 0\ntf = 256*π\ny0 = 1\n\n# Integrate with Chebyshev-Picard Iteration\n(ts,ys) = Integrate(f, y0, (t0, tf), 200, 200, 1e-20, 1000)\n\n# Integrate with DifferentialEquations.jl\nprob = ODEProblem((y,p,t) -> f(t,y), y0, (t0, tf))\nsol = solve(prob, Tsit5(), reltol = 1e-8, abstol = 1e-8)\n\n# Analytic Solution\nγ = ϵ/(1 + sqrt(1 - ϵ^2))\nα = 2*ϵ/(1 - ϵ + sqrt(1 - ϵ^2))\nβ = tan(ϵ*y0/2)/(1 + α)\nϕ(t) = 0.5*(1 - γ*ϵ)*t\nσ(t) = α*(sin(ϕ(t)) + β*cos(ϕ(t)))\ny(t) = -γ*t + (2/ϵ)*atan((β + σ(t)*cos(ϕ(t)))/(1 + σ(t)*sin(ϕ(t))))\n\nplot(sol.t,sol.u - map(y,sol.t))\nplot!(ts,ys .- map(y,ts))\n\n# Second Test\n#g = 9.81\n#k = 0.1\n#m = 0.2\n#f2(t,y) = [y[2], -k*y[1]/m + g]\n\n#y0 = [5, 0]\n\n# Integrate with Chebyshev-Picard Iteration\n#(ts,ys) = Integrate(f2, y0, (t0, tf), 80, 80, 1e-14, 1000)\n\n# Integrate with DifferentialEquations.jl\n#prob = ODEProblem((y,p,t) -> f2(t,y), y0, (t0, tf))\n#sol = solve(prob, Tsit5(), reltol = 1e-8, abstol = 1e-8)\n\n#plot(sol)\n#plot!(ts,ys)\n", "meta": {"hexsha": "6c74168034a324dc69137147977662f07340ad22", "size": 1064, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/Testing.jl", "max_stars_repo_name": "GrantHecht/ChebyshevPicardIteration.jl", "max_stars_repo_head_hexsha": "ed788d91dcc7adf8db9fae46ce4d16a6b7c0d47c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-15T01:49:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T01:49:52.000Z", "max_issues_repo_path": "scripts/Testing.jl", "max_issues_repo_name": "GrantHecht/ChebyshevPicardIteration.jl", "max_issues_repo_head_hexsha": "ed788d91dcc7adf8db9fae46ce4d16a6b7c0d47c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/Testing.jl", "max_forks_repo_name": "GrantHecht/ChebyshevPicardIteration.jl", "max_forks_repo_head_hexsha": "ed788d91dcc7adf8db9fae46ce4d16a6b7c0d47c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1666666667, "max_line_length": 67, "alphanum_fraction": 0.5789473684, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7557829055431797}}
{"text": "# Rational polynomial interpolation\n\n\"\"\"\nLinear Rational LeastSquares\n\nThe following curvit is done:\n\n`y = p(x) / q(x)`\n\nwhere `p(x)` and `q(x)` are polynomials.\n\nThe linear case is solved by doing a least square fit on\n\n`y*q(x) = p(x)`\n\nwhere the zero order term o `q(x)` is assumed to be 1.\n\"\"\"\nfunction linear_rational_fit(x::AbstractVector{T}, y::AbstractVector{T}, p, q) where T<:Number\n    n = size(x,1)\n    A = zeros(T, n, q+p+1)\n    for i = 1:n\n        A[i,1] = one(T)\n        for k = 1:p\n            A[i,k+1] = x[i]^k\n        end\n        for k = 1:q\n            A[i, p+1+k] = -y[i] * x[i]^k\n        end\n    end\n\n    A \\ y\n#    coefs[1:p+1], [1.0; coefs[p+2:end]]\n\nend\n\n\"\"\"\n# Type defining a rational polynomial\n\nA rational polynomial is the ratio of two polynomials\nand it is often useful in approximating functions.\n\"\"\"\nstruct RationalPoly{T<:Number} <: LeastSquares\n    num::Poly{T}\n    den::Poly{T}\nend\nRationalPoly(a::AbstractVector{T}, b::AbstractVector{T}) where {T<:Number} = RationalPoly(Poly(a), Poly(b))\nRationalPoly(p::Integer, q::Integer, ::Type{T}=Float64) where {T<:Number} = RationalPoly{T}(Poly(zeros(T,p+1)), Poly(zeros(T,q+1)))\nRationalPoly(coefs::AbstractVector{T}, p, q) where {T<:Number} = RationalPoly(coefs[1:p+1],[1.0; coefs[p+2:end]])\n\n\"Evaluate a rational polynomial\"\nratval(r::RationalPoly{T}, x) where {T<:Number} = polyval(r.num, x) ./ polyval(r.den, x)\n\n\"`call` overload for calling directly `ratval`\"\n(r::RationalPoly)(x) = ratval(r, x)\n\n\"Auxiliary function used in nonlinear least squares\"\nfunction make_rat_fun(p, q)\n    r = RationalPoly(p, q, Float64)\n    \n    function(x, a)\n        for i=0:p\n            r.num[i] = a[i+1]\n        end\n        r.den[0] = 1\n        for i = 1:q\n            r.den[i] = a[p+1+i]\n        end\n        polyval(r.num, x[1]) / polyval(r.den, x[1]) - x[2]\n    end\n    \nend\n\n\"\"\"\n# Carry out a nonlinear least squares of rational polynomials\n\nFind the polynomial coefficients that best approximate\nthe points given by `x` and `y`.\n\"\"\"\nfunction rational_fit(x, y, p, q, eps=1e-8, maxiter=200)\n\n    coefs0  = linear_rational_fit(x, y, p, q)\n\n    fun = make_rat_fun(p, q)\n\n    coefs, converged, niter = nonlinear_fit(hcat(x, y), fun, coefs0, eps, maxiter)\n    \n    coefs\n\nend\n\n\nfunction curve_fit(::Type{RationalPoly}, x, y, p, q, eps=1e-8, maxiter=200)\n    RationalPoly(rational_fit(x, y, p, q, eps, maxiter), p, q)\nend\n    \n    \n", "meta": {"hexsha": "edba8ef0fed3261d036a44101a1826f34a944bb0", "size": 2393, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rationalfit.jl", "max_stars_repo_name": "UnofficialJuliaMirror/CurveFit.jl-5a033b19-8c74-5913-a970-47c3779ef25c", "max_stars_repo_head_hexsha": "72413049a9a3382d92a0d226addf2fad7e4af97c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-06T13:24:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-06T13:24:17.000Z", "max_issues_repo_path": "src/rationalfit.jl", "max_issues_repo_name": "UnofficialJuliaMirror/CurveFit.jl-5a033b19-8c74-5913-a970-47c3779ef25c", "max_issues_repo_head_hexsha": "72413049a9a3382d92a0d226addf2fad7e4af97c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rationalfit.jl", "max_forks_repo_name": "UnofficialJuliaMirror/CurveFit.jl-5a033b19-8c74-5913-a970-47c3779ef25c", "max_forks_repo_head_hexsha": "72413049a9a3382d92a0d226addf2fad7e4af97c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6701030928, "max_line_length": 131, "alphanum_fraction": 0.6134559131, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7557829055431796}}
{"text": "#=\nThe series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.\n\nFind the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.\n=#\nfunction calc()\n  a = [i^BigInt(i) for i in 1:1000]\n  d = reverse(digits(sum(a))[1:10])\n  result = \"\"\n  for digit in d\n    result *= \"$digit\"\n  end\n  result\nend\n@time println(calc())\n", "meta": {"hexsha": "920cbda55911024432717acbdc3033468b07c725", "size": 322, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p48.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p48.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p48.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 20.125, "max_line_length": 74, "alphanum_fraction": 0.5683229814, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164656, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7557829025589226}}
{"text": "using JuMP, Cbc, CSV, PrettyTables\n\n#Importar datos de Excel\nnodes_import = CSV.read(\"Node_Coordinates.csv\", header = true)\n\n#Definir que hay en cada columna del excel y cuantos nodos hay en total\nnum_nodes = size(nodes_import,1)\nidcol = 1\nXcol = 2\nYcol = 3\n\n#Generar la Matriz de distancias a partir del numero de nodos\ndistance_matrix = Array{Float64}(undef, (num_nodes, num_nodes))\n#Llenar la matriz de distancias entre todos los puntos usando Pitagoras\nfor n in 1:num_nodes\n    for s in 1:num_nodes\n        distance_matrix[n,s] = sqrt((nodes_import[n,Ycol] - nodes_import[s,Ycol])^2 +\n        (nodes_import[n,Xcol] - nodes_import[s,Xcol])^2)\n    end\nend\n\nprintln(pretty_table(nodes_import))\nprintln(distance_matrix)\n\nmtzModel = Model(Cbc.Optimizer)\n@variable(mtzModel, rutas[1:num_nodes,1:num_nodes], binary=true)\n@variable(mtzModel, 2 <= u[2:num_nodes] <= num_nodes)\n@objective(mtzModel, Min, sum(rutas[:,:].*distance_matrix[:,:]))\nfor i = 1:num_nodes\n    @constraint(mtzModel, sum(rutas[i,:]) == 1)\n    @constraint(mtzModel, sum(rutas[:,i]) == 1)\n    @constraint(mtzModel, rutas[i,i] == 0)\nend\nfor i = 2:num_nodes\n    for j = 2:num_nodes\n        @constraint(mtzModel, u[i]-u[j]+1 <= (num_nodes-1)*(1-rutas[i,j]))\n    end\nend\nstats = JuMP.optimize!(mtzModel)\nprint(pretty_table(JuMP.value.(rutas)))\n", "meta": {"hexsha": "fcdfa46a325c725f9395aabdca62f71a61ec9878", "size": 1304, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Traveling_Salesman_Problem/TSP_MTZ.jl", "max_stars_repo_name": "valenmgama/optimization-tec", "max_stars_repo_head_hexsha": "b0469628f5ac51dec52052886cd4d561806a9d0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-07T17:21:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-07T17:21:08.000Z", "max_issues_repo_path": "Traveling_Salesman_Problem/TSP_MTZ.jl", "max_issues_repo_name": "valenmgama/optimization-tec", "max_issues_repo_head_hexsha": "b0469628f5ac51dec52052886cd4d561806a9d0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Traveling_Salesman_Problem/TSP_MTZ.jl", "max_forks_repo_name": "valenmgama/optimization-tec", "max_forks_repo_head_hexsha": "b0469628f5ac51dec52052886cd4d561806a9d0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8048780488, "max_line_length": 85, "alphanum_fraction": 0.7070552147, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464115, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7557829017636442}}
{"text": "#' ---\n#' title: Rocket Control\n#' ---\n\n#' **Originally Contributed by**: Iain Dunning\n\n#' This tutorial shows how to solve a nonlinear rocketry control problem.\n#' The problem was drawn from the [COPS3](http://www.mcs.anl.gov/~more/cops/cops3.pdf) benchmark.\n\n#' Our goal is to maximize the final altitude of a vertically launched rocket. \n#' We can control the thrust of the rocket, and must take account of \n#' the rocket mass, fuel consumption rate, gravity, and aerodynamic drag.\n\n#' Let us consider the basic description of the model (for the full description, \n#' including parameters for the rocket, see the COPS3 PDF)\n\n#' ### Overview \n#' We will use a discretized model of time, with a fixed number of time steps, $n$. \n#' We will make the time step size $\\Delta t$, and thus the final time $t_f = n \\cdot \\Delta t$, a variable in the problem. \n#' To approximate the derivatives in the problem we will use the [trapezoidal rule](http://en.wikipedia.org/wiki/Trapezoidal_rule).\n\n#' ### State and Control \n#' We will have three state variables:\n#'\n#' * Velocity, $v$\n#' * Altitude, $h$\n#' * Mass of rocket and remaining fuel, $m$\n#' \n#' and a single control variable, thrust $T$. \n#' Our goal is thus to maximize $h(t_f)$. \n#' Each of these corresponds to a JuMP variable indexed by the time step.\n\n#' ### Dynamics\n#' We have three equations that control the dynamics of the rocket:\n#' \n#' Rate of ascent: $$h^\\prime = v$$\n#' Acceleration: $$v^\\prime = \\frac{T - D(h,v)}{m} - g(h)$$\n#' Rate of mass loss: $$m^\\prime = -\\frac{T}{c}$$\n#' \n#' where drag $D(h,v)$ is a function of altitude and velocity, and gravity $g(h)$ is a function of altitude. \n\n#' These forces are defined as\n#' \n#' $$D(h,v) = D_c v^2 exp\\left( -h_c \\left( \\frac{h-h(0)}{h(0)} \\right) \\right)$$\n#' and\n#' $$g(h) = g_0 \\left( \\frac{h(0)}{h} \\right)^2$$\n#' \n#' The three rate equations correspond to JuMP constraints, \n#' and for convenience we will represent the forces with nonlinear expressions.\n\nusing JuMP, Ipopt\n\n# Create JuMP model, using Ipopt as the solver\nrocket = Model(with_optimizer(Ipopt.Optimizer, print_level=0))\n\n# Constants\n# Note that all parameters in the model have been normalized\n# to be dimensionless. See the COPS3 paper for more info.\nh_0 = 1    # Initial height\nv_0 = 0    # Initial velocity\nm_0 = 1    # Initial mass\ng_0 = 1    # Gravity at the surface\n\nT_c = 3.5  # Used for thrust\nh_c = 500  # Used for drag\nv_c = 620  # Used for drag\nm_c = 0.6  # Fraction of initial mass left at end\n\nc     = 0.5 * sqrt(g_0 * h_0)  # Thrust-to-fuel mass\nm_f   = m_c * m_0            # Final mass\nD_c   = 0.5 * v_c * m_0 / g_0    # Drag scaling\nT_max = T_c * g_0 * m_0        # Maximum thrust\n\nn = 800   # Time steps\n\n@variables(rocket, begin\n    Δt ≥ 0, (start = 1/n) # Time step\n    # State variables\n    v[1:n] ≥ 0            # Velocity\n    h[1:n] ≥ h_0          # Height\n    m_f ≤ m[1:n] ≤ m_0    # Mass\n    # Control\n    0 ≤ T[1:n] ≤ T_max    # Thrust\nend)\n\n# Objective: maximize altitude at end of time of flight\n@objective(rocket, Max, h[n])\n\n# Initial conditions\n@constraints(rocket, begin\n    v[1] == v_0\n    h[1] == h_0\n    m[1] == m_0\n    m[n] == m_f\nend)\n\n# Forces\n# Drag(h,v) = Dc v^2 exp( -hc * (h - h0) / h0 )\n@NLexpression(rocket, drag[j = 1:n], D_c * (v[j]^2) * exp(-h_c * (h[j] - h_0) / h_0))\n# Grav(h)   = go * (h0 / h)^2\n@NLexpression(rocket, grav[j = 1:n], g_0 * (h_0 / h[j])^2)\n# Time of flight\n@NLexpression(rocket, t_f, Δt * n)\n\n# Dynamics\nfor j in 2:n\n    # h' = v\n    \n    # Rectangular integration\n    # @NLconstraint(rocket, h[j] == h[j - 1] + Δt * v[j - 1])\n    \n    # Trapezoidal integration\n    @NLconstraint(rocket,\n        h[j] == h[j - 1] + 0.5 * Δt * (v[j] + v[j - 1]))\n\n    # v' = (T-D(h,v))/m - g(h)\n    \n    # Rectangular integration\n    # @NLconstraint(rocket, v[j] == v[j - 1] + Δt *(\n    #                 (T[j - 1] - drag[j - 1]) / m[j - 1] - grav[j - 1]))\n    \n    # Trapezoidal integration\n    @NLconstraint(rocket,\n        v[j] == v[j-1] + 0.5 * Δt * (\n            (T[j] - drag[j] - m[j] * grav[j]) / m[j] +\n            (T[j - 1] - drag[j - 1] - m[j - 1] * grav[j - 1]) / m[j - 1]))\n\n    # m' = -T/c\n\n    # Rectangular integration\n    # @NLconstraint(rocket, m[j] == m[j - 1] - Δt * T[j - 1] / c)\n    \n    # Trapezoidal integration\n    @NLconstraint(rocket,\n        m[j] == m[j - 1] - 0.5 * Δt * (T[j] + T[j-1]) / c)\nend\n\n# Solve for the control and state\nprintln(\"Solving...\")\nstatus = optimize!(rocket)\n\n# Display results\n# println(\"Solver status: \", status)\nprintln(\"Max height: \", objective_value(rocket))\n\n#+ \n\n# Can visualize the state and control variables\nusing Gadfly\n\n#+ \n\nh_plot = plot(x = (1:n) * value.(Δt), y = value.(h)[:], Geom.line,\n                Guide.xlabel(\"Time (s)\"), Guide.ylabel(\"Altitude\"))\nm_plot = plot(x = (1:n) * value.(Δt), y = value.(m)[:], Geom.line,\n                Guide.xlabel(\"Time (s)\"), Guide.ylabel(\"Mass\"))\nv_plot = plot(x = (1:n) * value.(Δt), y = value.(v)[:], Geom.line,\n                Guide.xlabel(\"Time (s)\"), Guide.ylabel(\"Velocity\"))\nT_plot = plot(x = (1:n) * value.(Δt), y = value.(T)[:], Geom.line,\n                Guide.xlabel(\"Time (s)\"), Guide.ylabel(\"Thrust\"))\ndraw(SVG(6inch, 6inch), vstack(hstack(h_plot, m_plot), hstack(v_plot, T_plot)))", "meta": {"hexsha": "1a98cfcd23e6b332cb95303ee61b60899b2b7d6a", "size": 5231, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/modelling/rocket_control.jl", "max_stars_repo_name": "carlosal1015/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/modelling/rocket_control.jl", "max_issues_repo_name": "carlosal1015/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/modelling/rocket_control.jl", "max_forks_repo_name": "carlosal1015/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4906832298, "max_line_length": 131, "alphanum_fraction": 0.5962531065, "num_tokens": 1731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240160063031, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7557828979841082}}
{"text": "\"\"\"\n    ω(M, k)\n\nReturn the `M`th root of unity raised to the `k`th power.\n\"\"\"\n@inline ω(M, k) = exp(-2im*π*k/M)\n", "meta": {"hexsha": "5e9721e16fed4c8585eee5f8367d9d925a6d9a8b", "size": 113, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Solvers/solver_utils.jl", "max_stars_repo_name": "zhenwu0728/Oceananigans.jl", "max_stars_repo_head_hexsha": "0676c769f03be346c0cfd6c5e5c9b66c6001593c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-24T05:03:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-17T04:40:12.000Z", "max_issues_repo_path": "src/Solvers/solver_utils.jl", "max_issues_repo_name": "christophernhill/OceanLES.jl", "max_issues_repo_head_hexsha": "908fc5347c4f3238474d63d10c9314719a79d079", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Solvers/solver_utils.jl", "max_forks_repo_name": "christophernhill/OceanLES.jl", "max_forks_repo_head_hexsha": "908fc5347c4f3238474d63d10c9314719a79d079", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-17T04:54:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T04:54:53.000Z", "avg_line_length": 16.1428571429, "max_line_length": 57, "alphanum_fraction": 0.5575221239, "num_tokens": 45, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7557828924093081}}
{"text": "\nusing DifferentialEquations, Plots, ParameterizedFunctions\ngr()\nlorenz = @ode_def Lorenz begin\n  dx = σ*(y-x)\n  dy = ρ*x-y-x*z\n  dz = x*y-β*z\nend σ β ρ\n\np = [10.0,8/3,28]\nu0 = [1., 5., 10.]\ntspan = (0., 100.)\nprob = ODEProblem(lorenz, u0, tspan, p)\nsol = solve(prob)\n\n\nplot(sol)\n\n\nplot(sol,vars=(:x,:y,:z))\n\n\nplot(sol,vars=[:x])\n\n\nplot(sol,vars=(1,2,3))\nplot(sol,vars=[1])\n\n\nplot(sol,linewidth=5,title=\"Solution to the linear ODE with a thick line\",\nxaxis=\"Time (t)\",yaxis=\"u(t) (in mm)\",label=[\"X\",\"Y\",\"Z\"])\n\n\nscatter(sol,vars=[:x])\n\n\nplot(sol,vars=(1,2,3),denseplot=false)\n\n\nplot(sol,vars=(1,2,3),plotdensity=100)\n\n\nplot(sol,vars=(1,2,3),plotdensity=10000)\n\n\nplot(sol,vars=(1,2,3))\nscatter!(sol,vars=(1,2,3),plotdensity=100)\n\n\np = plot(sol,vars=(1,2,3))\nscatter!(p,sol,vars=(1,2,3),plotdensity=100)\ntitle!(\"I added a title\")\n\n\nusing DiffEqTutorials\nDiffEqTutorials.tutorial_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])\n\n", "meta": {"hexsha": "afc824124d517be1428256b6e1af2c628dc561d4", "size": 924, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/introduction/formatting_plots.jl", "max_stars_repo_name": "KZiemian/DiffEqTutorials.jl", "max_stars_repo_head_hexsha": "97c2bce7039bd976522f06d7e1c9900bb63c2aff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-22T12:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-22T12:30:52.000Z", "max_issues_repo_path": "script/introduction/formatting_plots.jl", "max_issues_repo_name": "KZiemian/DiffEqTutorials.jl", "max_issues_repo_head_hexsha": "97c2bce7039bd976522f06d7e1c9900bb63c2aff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/introduction/formatting_plots.jl", "max_forks_repo_name": "KZiemian/DiffEqTutorials.jl", "max_forks_repo_head_hexsha": "97c2bce7039bd976522f06d7e1c9900bb63c2aff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.9310344828, "max_line_length": 74, "alphanum_fraction": 0.6515151515, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.7557706019617831}}
{"text": "# William Kahan's method, accuracy is within 2 ulp\n\nfunction csd_ad_minus_bc{T<:AbstractFloat}(a::T, b::T, c::T, d::T)  \n    bcHi  = b*c\n    bcLo  = fma(-b, c,  bcHi)  # exact\n    hi    = fma( a, d, -bcHi)  # close\n    hi - bcLo                  # compensated\nend\n\ncsd_ab_minus_cd{T<:AbstractFloat}(a::T, b::T, c::T, d::T) = ad_minus_bc(a,c,d,b)\n\nfunction csdDet2x2{T<:AbstractFloat}(m2x2::Matrix{T})\n   if size(k) != (2,2)\n       throw(DomainError())\n   end\n   csd_ad_minus_bc(reshape(m2x2,4,1)...)\nend\n\nfunction csdCross3D{T<:AbstractFloat}(a::Vector{T}, b::Vector{T})\n    a1,a2,a3 = a[1],a[2],a[3]\n    b1,b2,b3 = b[1],b[2],b[3]\n    \n    x = ad_minus_bc(a2, a3, b2, b3)\n    y = ad_minus_bc(a3, a1, b3, b1)\n    z = ad_minus_bc(a1, a2, b1, b2)\n    \n    [x,y,z]\nend\n", "meta": {"hexsha": "86428ec6996c54fa9c90d9d819dee7243f4ae694", "size": 765, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/det.jl", "max_stars_repo_name": "Jeffrey-Sarnoff/CompensatedArithmetic.jl", "max_stars_repo_head_hexsha": "8f1df2b2a653c2ef84c738e3f12d3e6c02a5cc1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/det.jl", "max_issues_repo_name": "Jeffrey-Sarnoff/CompensatedArithmetic.jl", "max_issues_repo_head_hexsha": "8f1df2b2a653c2ef84c738e3f12d3e6c02a5cc1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/det.jl", "max_forks_repo_name": "Jeffrey-Sarnoff/CompensatedArithmetic.jl", "max_forks_repo_head_hexsha": "8f1df2b2a653c2ef84c738e3f12d3e6c02a5cc1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3793103448, "max_line_length": 80, "alphanum_fraction": 0.568627451, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542887603538, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.7557475879371722}}
{"text": "module GaussianMarkovRandomFields\n\nusing LDLFactorizations\nimport LDLFactorizations: LDLFactorization\nusing LinearAlgebra, SparseArrays\nusing Distributions\nusing Random\nusing Memoize # For recursive marginal variance implementation\n\nexport GMRF, cholesky_ldl, logdet_ldl, prec\n\nfunction cholesky_ldl(A)\n    F = ldl(A)\n    L = cholesky(F)\n    return L, F.P\nend\n\nfunction LinearAlgebra.cholesky(F::LDLFactorizations.LDLFactorization)\n    # https://en.wikipedia.org/wiki/Cholesky_decomposition#LDL_decomposition\n\t# Need next two lines for type-stability, the `getproperty` method for LDLFactorization\n\t# objects is not type-stable\n\td = getfield(F, :d)\n\tL = SparseMatrixCSC(F.n, F.n, F.Lp, F.Li, F.Lx)\n    all(d .> 0) || PosDefException(0)\n    L = ((L + I) * Diagonal(sqrt.(d)))#[invperm(F.P), invperm(F.P)]\n    return L\nend\n\nfunction logdet_from_chol(L)\n    return 2 * sum(log(L[i]) for i in diagind(L))\nend\n\nfunction logdet_ldl(M::AbstractMatrix)\n    L, P = cholesky_ldl(M)\n    return logdet_from_chol(L)\nend\n\nstruct GMRF{Tv<:AbstractVector{<:Real},\n        Tm<:AbstractMatrix{<:Real},\n        Tl<:AbstractMatrix{<:Real}} <: AbstractMvNormal\n    μ::Tv\n    Q::Tm\n    L::Tl\nend\n\nfunction GMRF(μ, Q)#::AbstractVector, Q::AbstractMatrix)\n    n = LinearAlgebra.checksquare(Q)\n    length(μ) == n || DimensionMismatch(\"The dimensions of μ and Q are inconsistent.\")\n    L, P = cholesky_ldl(Q)\n    return GMRF(μ, Q, L)\nend\n\nfunction GMRF(Q::Tv) where {Tv <: AbstractMatrix{<:Real}}\n    n = LinearAlgebra.checksquare(Q)\n    return GMRF(zeros(eltype(Q), n), Q)\nend\n\nfunction GMRF(μ::AbstractVector, F::LDLFactorization)\n\tP = F.P\n\tL = cholesky(F)\n\tQ = (L * L')[invperm(P), invperm(P)]\n    return GMRF(μ, Q, F.L)\nend\nGMRF(F::LDLFactorization) = GMRF(zeros(size(F.L, 1)), F)\n\nfunction Distributions._logpdf(d::GMRF, x::AbstractVector{T}) where T\n    k = length(d.μ)\n    ld = logdet_from_chol(d.L)\n    x0 = x .- d.μ\n    return -0.5 * (-ld + dot(x0, d.Q, x0) + k*log(2pi))\nend\n\nBase.length(d::GMRF) = length(mean(d))\nBase.eltype(d::GMRF) = eltype(mean(d))\nprec(d::GMRF) = d.Q\nDistributions.mean(d::GMRF) = d.μ\n\n# Uses the recursive method of Rue (2005)\n# Finds the \"future\" non-zero indices\nfunction ℐ(L::AbstractSparseMatrix, i::Integer)\n\tLcol = L[:, i]\n\tind, val = findnz(Lcol)\n\tind[ind .> i]\nend\n# Recursively calculate the marginal variances. Should be memoized to avoid\n# duplicated calculations and (probably more importantly) stack overflows in\n# large precision matrices.\n@memoize function cov_element(L::AbstractSparseMatrix, i::Integer, j::Integer)\n\t# Reverse indices to calculate upper triangle entry of Σ, otherwise get zero below\n\tif (i > j)\n\t\t (j, i) = (i, j)\n\tend\n\tΣij = (i == j) ? 1 / L[i, i]^2 : zero(L[i, i])\n\tfor k in ℐ(L, i)\n        # `cov_element` will be zero if k > j; indices are switched if\n        # necessary; this is where recursion occurs.\n\t\tΣij -= 1 / L[i, i] * L[k, i] * cov_element(L, k, j)\n\tend\n\tΣij\nend\nfunction Distributions.var(d::GMRF)\n    n = length(d)\n    v = Vector{Float64}(undef, n)\n    # Iterate *backwards*\n    for idx in reverse(eachindex(v))\n        v[idx] = cov_element(d.L, idx, idx)\n    end\n    return v\nend\n\nDistributions.cov(d::GMRF) = error( \"ERROR: The covariance matrix of a GMRF `g` can often be \" *\n    \"dense and can cause the computer to run out of memory. If you are sure you have \"*\n    \"enough memory, you can invert the precision matrix with `inv(Matrix(prec(g)))`\")\n\nfunction Distributions._rand!(rng::Random.AbstractRNG, d::GMRF, x::AbstractArray)\n    z = randn(rng, size(x))\n    x .= mean(d) .+ d.L \\ z\nend\n\nend # module\n", "meta": {"hexsha": "764e517aa6f5cb27e9578e0b3776f90b319e25d6", "size": 3568, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GaussianMarkovRandomFields.jl", "max_stars_repo_name": "ElOceanografo/GaussianMarkovRandomFields", "max_stars_repo_head_hexsha": "199f186343285f03c7e2f7ed44a120605be512ee", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-19T22:08:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-19T22:08:15.000Z", "max_issues_repo_path": "src/GaussianMarkovRandomFields.jl", "max_issues_repo_name": "ElOceanografo/GaussianMarkovRandomFields", "max_issues_repo_head_hexsha": "199f186343285f03c7e2f7ed44a120605be512ee", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-11-20T00:17:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-24T18:27:10.000Z", "max_forks_repo_path": "src/GaussianMarkovRandomFields.jl", "max_forks_repo_name": "ElOceanografo/GaussianMarkovRandomFields", "max_forks_repo_head_hexsha": "199f186343285f03c7e2f7ed44a120605be512ee", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-21T06:56:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T06:56:30.000Z", "avg_line_length": 29.4876033058, "max_line_length": 96, "alphanum_fraction": 0.6762892377, "num_tokens": 1140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.755733746553952}}
{"text": "\"\"\"\nCompute the inverse of the lattice. Takes special care of 1D or 2D cases.\n\"\"\"\nfunction compute_inverse_lattice(lattice::AbstractMatrix{T}) where {T}\n    # Note: pinv pretty much does the same, but the implied SVD causes trouble\n    #       with interval arithmetic and dual numbers, so we go for this version.\n    n_dim = count(!iszero, eachcol(lattice))\n    @assert 1 ≤ n_dim ≤ 3\n    if n_dim == 3\n        inv(lattice)\n    else\n        Mat3{T}([\n            inv(lattice[1:n_dim, 1:n_dim])   zeros(T, n_dim, 3 - n_dim);\n            zeros(T, 3 - n_dim, 3)\n        ])\n    end\nend\n\n\"\"\"\nCompute the reciprocal lattice.\nWe use the convention that the reciprocal lattice is the set of G vectors such\nthat G ⋅ R ∈ 2π ℤ for all R in the lattice.\n\"\"\"\nfunction compute_recip_lattice(lattice::AbstractMatrix{T}) where {T}\n    2T(π) * compute_inverse_lattice(lattice')\nend\n\n\"\"\"\nCompute unit cell volume volume. In case of 1D or 2D case, the volume is the length/surface.\n\"\"\"\nfunction compute_unit_cell_volume(lattice)\n    n_dim = count(!iszero, eachcol(lattice))\n    abs(det(lattice[1:n_dim, 1:n_dim]))\nend\n\n\"\"\"Compute the diameter of the unit cell\"\"\"\nfunction diameter(lattice::AbstractMatrix)\n    # brute force search\n    diam = zero(eltype(lattice))\n    for vec in Vec3.(Iterators.product(-1:1, -1:1, -1:1))\n        diam = max(diam, norm(lattice * vec))\n    end\n    diam\nend\n", "meta": {"hexsha": "8e9f8f21ac731290ecacb521a1778fd136e1f42c", "size": 1370, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/structure.jl", "max_stars_repo_name": "kvnoct/DFTK.jl", "max_stars_repo_head_hexsha": "0dbe614d111b0b2804be01fd8c57f61248a695a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/structure.jl", "max_issues_repo_name": "kvnoct/DFTK.jl", "max_issues_repo_head_hexsha": "0dbe614d111b0b2804be01fd8c57f61248a695a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/structure.jl", "max_forks_repo_name": "kvnoct/DFTK.jl", "max_forks_repo_head_hexsha": "0dbe614d111b0b2804be01fd8c57f61248a695a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4444444444, "max_line_length": 92, "alphanum_fraction": 0.6671532847, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915913, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.7557337361781463}}
{"text": "\"\"\"\n    EGPpower(σ, ξ, κ)\n\n*EGPpower* corresponds to the first extended GP model of Naveau et al. (2016), with the power law distribution G(v) = v^κ.\n\nIt is a three parameters family: κ controls the shape of the lower tail, σ is a scale parameter, and ξ controls the rate of upper tail decay.\n\n```julia\nEGPpower(σ, ξ, κ)   # EGP of Naveau et al. (2016) (type 1) with scale parameter σ, rate of upper tail decay ξ and shape of the lower tail κ.\n\nparams(d)           # Get the parameters, i.e. (σ, ξ, κ)\n```\n\nReference :\n\n* Naveau, P., Huser, R., Ribereau, P., and Hannart, A. (2016), Modeling jointly low, moderate, and heavy rainfall intensities without a threshold selection, Water Resour. Res., 52, 2753– 2769, doi:10.1002/2015WR018552.\n\"\"\"\nstruct EGPpower{T<:Real} <: ContinuousUnivariateDistribution\n    σ::T    # scale parameter\n    ξ::T    # rate of upper tail decay\n    κ::T    # shape of the lower tail\n\n    function EGPpower{T}(σ::T, ξ::T, κ::T) where {T <: Real}\n        new{T}(σ, ξ, κ)\n    end\nend\n\nfunction EGPpower(σ::T, ξ::T, κ::T; check_args=true) where {T <: Real}\n    check_args && @check_args(EGPpower, σ > zero(σ) && κ > zero(κ))\n    return EGPpower{T}(σ, ξ, κ)\nend\n\nEGPpower(σ::Real, ξ::Real, κ::Real) = EGPpower(promote(σ, ξ, κ)...)\nEGPpower(σ::Integer, ξ::Integer, κ::Integer) = EGPpower(float(σ), float(ξ), float(κ))\n\n\nminimum(d::EGPpower) = 0.0\nmaximum(d::EGPpower) = Inf * (d.ξ >= 0) - ( d.σ / d.ξ ) * (d.ξ < 0)\ninsupport(d::EGPpower, x::Real) = minimum(d) <= x <= maximum(d)\n\n\n#### Parameters\n\nscale(d::EGPpower) = d.σ\ndecay(d::EGPpower) = d.ξ    # noms à vérifier...\nshape(d::EGPpower) = d.κ\n\nparams(d::EGPpower) = (d.σ, d.ξ, d.κ)\npartype(::EGPpower{T}) where {T} = T\n\n\n#### Evaluation\n\nfunction logpdf(d::EGPpower{T}, x::Real) where T<:Real\n    μ = 0\n    (σ, ξ, κ) = params(d)\n\n    pd = GeneralizedPareto(μ, 1, ξ)\n\n    lg(v::Real) = log(κ) + (κ-1)*log(v)\n\n    p = -log(σ) + Distributions.logpdf(pd, x/σ) + lg(Distributions.cdf(pd, x/σ))\n\n    return p\nend\n\npdf(d::EGPpower, x::Real) = exp(logpdf(d, x))\n\nfunction logcdf(d::EGPpower{T}, x::Real) where T<:Real\n    # À vérifier\n    μ = 0\n    (σ, ξ, κ) = params(d)\n\n    pd = GeneralizedPareto(μ, 1, ξ)\n\n    #G(v::Real, κ::Real) = v^κ\n    #lG(v::Real, κ::Real) = κ*log(v)\n\n    p = κ*Distributions.logcdf(pd, x/σ)\n\n    return p\nend\n\ncdf(d::EGPpower, x::Real) = exp(logcdf(d, x))\n\nfunction quantile(d::EGPpower{T}, p::Real) where T<:Real\n    @assert zero(p)<p<one(p) \"the quantile level should be between 0 and 1.\"\n\n    (σ, ξ, κ) = params(d)\n\n    invG(p::Real, κ::Real) = p^(1/κ)\n\n    x = (σ/ξ)*(((1 - invG(p,κ))^(-ξ)) - 1)\n\n    return x\nend\n\n\n#### Sampling\n\nfunction rand(rng::AbstractRNG, d::EGPpower)\n    # Generate a Float64 random number uniformly in (0,1].\n    u = 1 - rand(rng)\n\n    invG(p::Real, κ::Real) = p^(1/κ)\n\n    return (d.σ/d.ξ)*(((1 - invG(u,d.κ))^(-d.ξ)) - 1)\nend\n\nsampler(d::EGPpower) = d    # à vérifier\n", "meta": {"hexsha": "fede0cf770fa9e0c0c04841df6186a0eddad5101", "size": 2895, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distributions/naveau2016_type1.jl", "max_stars_repo_name": "houton199/ExtendedExtremes.jl", "max_stars_repo_head_hexsha": "49a21091e5b8fa94a339a3f1d19e2d007726eeb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-18T19:06:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T19:06:18.000Z", "max_issues_repo_path": "src/distributions/naveau2016_type1.jl", "max_issues_repo_name": "houton199/ExtendedExtremes.jl", "max_issues_repo_head_hexsha": "49a21091e5b8fa94a339a3f1d19e2d007726eeb6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-23T20:24:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T20:24:13.000Z", "max_forks_repo_path": "src/distributions/naveau2016_type1.jl", "max_forks_repo_name": "houton199/ExtendedExtremes.jl", "max_forks_repo_head_hexsha": "49a21091e5b8fa94a339a3f1d19e2d007726eeb6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0810810811, "max_line_length": 218, "alphanum_fraction": 0.6017271157, "num_tokens": 1110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7557337337484169}}
{"text": "\nvar2(x) = mean(x.^2) .- mean(x)^2\n\nfunction waic( ll::AbstractArray; pointwise=false , log_lik=\"log_lik\" , kwargs... )\n    \n    n_samples, n_obs = size(ll)\n    pD = zeros(n_obs);\n\n    lpd = reshape(logsumexp(ll .- log(n_samples); dims=1), n_obs);\n    for i in 1:n_obs \n        pD[i] = var2(ll[:,i])\n    end\n\n    waic_vec = (-2) .* ( lpd - pD );\n    if pointwise == false\n        waics = sum(waic_vec)\n        lpd = sum(lpd)\n        pD = sum(pD)\n    else \n        waics = waic_vec\n    end\n\n    local se\n    try \n        se = sqrt( n_obs*var2(waic_vec) )\n    catch e\n        println(e)\n        se = nothing\n    end\n\n    (WAIC=waics, lppd=lpd, penalty=pD, std_err=se)\nend\n\nexport\n    var2,\n    waic\n", "meta": {"hexsha": "d51a24ac2f28fadb1e0ecfbb36de48b5f2569aef", "size": 697, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/waic.jl", "max_stars_repo_name": "devmotion/StatsModelComparisons.jl", "max_stars_repo_head_hexsha": "07896872c4140710b9ab91631a08aabb15106077", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/waic.jl", "max_issues_repo_name": "devmotion/StatsModelComparisons.jl", "max_issues_repo_head_hexsha": "07896872c4140710b9ab91631a08aabb15106077", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/waic.jl", "max_forks_repo_name": "devmotion/StatsModelComparisons.jl", "max_forks_repo_head_hexsha": "07896872c4140710b9ab91631a08aabb15106077", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8378378378, "max_line_length": 83, "alphanum_fraction": 0.5308464849, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.755733733452943}}
{"text": "using ContinuousTransformations\nusing FastGaussQuadrature\nusing ArgCheck\n\nexport Quadrature, quadrature_standard_normal, quadrature_standard_uniform\n\n\"\"\"\nUnivariate numerical quadrature. A lightweight container for the\n`nodes` and the `weights`, calculated from some quadrature rule. The\n`domain` is provided for information purposes.\n\"\"\"\nimmutable Quadrature{TD <: AbstractInterval, T}\n    domain::TD\n    nodes::Vector{T}\n    weights::Vector{T}\n    function Quadrature(domain, nodes, weights)\n        @argcheck length(nodes) == length(weights)\n        new(domain, nodes, weights)\n    end\nend\n\nfunction Quadrature{TD, T}(domain::TD, nodes::Vector{T}, weights::Vector{T})\n    Quadrature{TD, T}(domain, nodes, weights)\nend\n\nContinuousTransformations.domain(q::Quadrature) = q.domain\n\nBase.length(q::Quadrature) = length(q.nodes)\n\nfunction Base.show(io::IO, q::Quadrature)\n    print(io, \"Quadrature of $(length(q)) nodes on $(q.domain)\")\nend\n\n(q::Quadrature)(f) = dot(f.(q.nodes), q.weights)\n\n\"\"\"\nReturn a quadrature that integrates a function under the standard\nnormal distribution using `N` nodes.\n\"\"\"\nfunction quadrature_standard_normal(N::Int)\n    nodes, weights = gausshermite(N)\n    Quadrature(ℝ, nodes*√2, weights/√π)\nend\n\n\"\"\"\nReturn a quadrature that integrates a function on the unit domain\n[0,1] under the standard uniform distribution using `N` nodes.\n\"\"\"\nfunction quadrature_standard_uniform(N::Int)\n    nodes, weights = gausslegendre(N)\n    Quadrature(𝕀, fma.(nodes, 0.5, 0.5), weights .* 0.5)\nend\n", "meta": {"hexsha": "3b5cfda7f0c03d35aa78c80800385fb0672e5eef", "size": 1508, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/quadrature.jl", "max_stars_repo_name": "tpapp/EconFunctions.jl", "max_stars_repo_head_hexsha": "e42b2831ca6e2640c8a2672d6e2879919ea40edc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-09-25T13:09:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-14T01:46:06.000Z", "max_issues_repo_path": "src/quadrature.jl", "max_issues_repo_name": "tpapp/EconFunctions.jl", "max_issues_repo_head_hexsha": "e42b2831ca6e2640c8a2672d6e2879919ea40edc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/quadrature.jl", "max_forks_repo_name": "tpapp/EconFunctions.jl", "max_forks_repo_head_hexsha": "e42b2831ca6e2640c8a2672d6e2879919ea40edc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:48:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:48:12.000Z", "avg_line_length": 28.4528301887, "max_line_length": 76, "alphanum_fraction": 0.7320954907, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7557337291844313}}
{"text": "# Local Tangent Space Alignment (LTSA)\n# ---------------------------\n# Principal Manifolds and Nonlinear Dimension Reduction via Local Tangent Space Alignment,\n# Zhang, Zhenyue; Hongyuan Zha (2004),  SIAM Journal on Scientific Computing 26 (1): 313–338.\n# doi:10.1137/s1064827502419154.\n\n#### LTSA type\nstruct LTSA{T <: AbstractFloat} <: SpectralResult\n    k::Int\n    λ::AbstractVector{T}\n    proj::Projection{T}\n\n    LTSA{T}(k::Int, λ::AbstractVector{T}, proj::Projection{T}) where T = new(k, λ, proj)\nend\n\n## properties\noutdim(M::LTSA) = size(M.proj, 1)\nprojection(M::LTSA) = M.proj\n\neigvals(M::LTSA) = M.λ\nneighbors(M::LTSA) = M.k\n\n## show & dump\nfunction show(io::IO, M::LTSA)\n    print(io, \"LTSA(outdim = $(outdim(M)), neighbors = $(neighbors(M)))\")\nend\n\nfunction dump(io::IO, M::LTSA)\n    show(io, M)\n    println(io, \"eigenvalues: \")\n    Base.showarray(io, transpose(M.λ), header=false, repr=false)\n    println(io)\n    println(io, \"projection:\")\n    Base.showarray(io, M.proj, header=false, repr=false)\nend\n\n## interface functions\nfunction transform(::Type{LTSA}, X::DenseMatrix{T}; d::Int=2, k::Int=12) where T<:AbstractFloat\n    n = size(X, 2)\n\n    # Construct NN graph\n    D, I = find_nn(X, k)\n\n    B = spzeros(n,n)\n    for i=1:n\n        # re-center points in neighborhood\n        μ = mean(X[:,I[:,i]], dims=2)\n        δ_x = X[:,I[:,i]] .- μ\n\n        # Compute orthogonal basis H of θ'\n        θ_t = svd(δ_x).V[:,1:d]\n\n        # Construct alignment matrix\n        G = hcat(ones(k)./sqrt(k), θ_t)\n        B[I[:,i], I[:,i]] =  B[I[:,i], I[:,i]] + Matrix{Float64}(LinearAlgebra.I, k, k) - G*transpose(G)\n    end\n\n    # Align global coordinates\n    λ, V = decompose(B, d)\n    return LTSA{T}(k, λ, transpose(V))\nend\n", "meta": {"hexsha": "2411d57c255cfe2e331ce7a40728ba91ca0d77e6", "size": 1720, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ltsa.jl", "max_stars_repo_name": "simonschoelly/ManifoldLearning.jl", "max_stars_repo_head_hexsha": "ac0f75fd0ea71a625e939d36d3f2ae118fdb2069", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ltsa.jl", "max_issues_repo_name": "simonschoelly/ManifoldLearning.jl", "max_issues_repo_head_hexsha": "ac0f75fd0ea71a625e939d36d3f2ae118fdb2069", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ltsa.jl", "max_forks_repo_name": "simonschoelly/ManifoldLearning.jl", "max_forks_repo_head_hexsha": "ac0f75fd0ea71a625e939d36d3f2ae118fdb2069", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7419354839, "max_line_length": 104, "alphanum_fraction": 0.6040697674, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.755733728571504}}
{"text": "# Doesn't work for colinear/parallel lines. (𝘂 × 𝘃 = 𝟬).\n# For 𝗹₁(r) = 𝘅₁ + r𝘂 and 𝗹₂(s) = 𝘅₂ + s𝘃\n# 1) 𝘅₁ + r𝘂 = 𝘅₂ + s𝘃                  subtracting 𝘅₁ from both sides\n# 2) r𝘂 = (𝘅₂-𝘅₁) + s𝘃                  𝘄 = 𝘅₂-𝘅₁\n# 3) r𝘂 = 𝘄 + s𝘃                        cross product with 𝘃 (distributive)\n# 4) r(𝘂 × 𝘃) = 𝘄 × 𝘃 + s(𝘃 × 𝘃)        𝘃 × 𝘃 = 𝟬\n# 5) r(𝘂 × 𝘃) = 𝘄 × 𝘃                   let 𝘄 × 𝘃 = 𝘅 and 𝘂 × 𝘃 = 𝘇\n# 6) r𝘇 = 𝘅                             dot product 𝘇 to each side\n# 7) r𝘇 ⋅ 𝘇 = 𝘅 ⋅ 𝘇                     divide by 𝘇 ⋅ 𝘇\n# 8) r = (𝘅 ⋅ 𝘇)/(𝘇 ⋅ 𝘇)\n# We need to ensure r, s ∈ [0, 1], hence we need to solve for s too.\n# 1) 𝘅₂ + s𝘃 = 𝘅₁ + r𝘂                     subtracting 𝘅₂ from both sides\n# 2) s𝘃 = -𝘄 + r𝘂                          cross product with 𝘄\n# 3) s(𝘃 × 𝘄) = -𝘄 × 𝘄 + r(𝘂 × 𝘄)          𝘄 × 𝘄 = 𝟬 \n# 4) s(𝘃 × 𝘄) = r(𝘂 × 𝘄)                   using 𝘂 × 𝘄 = -(𝘄 × 𝘂), likewise for 𝘃 × 𝘄\n# 5) s(𝘄 × 𝘃) = r(𝘄 × 𝘂)                   let 𝘄 × 𝘂 = 𝘆. use 𝘄 × 𝘃 = 𝘅\n# 6) s𝘅 = r𝘆                               dot product 𝘅 to each side\n# 7) s(𝘅 ⋅ 𝘅) = r(𝘆 ⋅ 𝘅)                   divide by (𝘅 ⋅ 𝘅)\n# 9) s = r(𝘅 ⋅ 𝘆)/(𝘅 ⋅ 𝘅)\n# The cross product of two vectors in the plane is a vector of the form (0, 0, k),\n# hence, in 2D:\n# r = (𝘅 ⋅ 𝘇)/(𝘇 ⋅ 𝘇) = x₃/z₃ \n# s = r(𝘅 ⋅ 𝘆)/(𝘅 ⋅ 𝘅) = y₃/z₃ \nfunction Base.intersect(l₁::LineSegment{Point{2,T}}, \n                        l₂::LineSegment{Point{2,T}}) where {T} \n    𝘄 = l₂[1] - l₁[1]\n    𝘂₁= l₁[2] - l₁[1] \n    𝘂₂= l₂[2] - l₂[1] \n    z = 𝘂₁ × 𝘂₂\n    r = (𝘄 × 𝘂₂)/z\n    s = (𝘄 × 𝘂₁)/z\n    valid = 0 ≤ r && r ≤ 1 && 0 ≤ s && s ≤ 1\n    return valid ? l₂(s) : Point(T(1e6),T(1e6))\nend\n", "meta": {"hexsha": "098284f47d8c86beb8610498b1448fb80e0e2b4e", "size": 1637, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/raytracing/intersect/linesegment-linesegment.jl", "max_stars_repo_name": "khurrumsaleem/MOCNeutronTransport", "max_stars_repo_head_hexsha": "16ccaf48d6c01e57e55e74ffbfbd71bbcd0f423c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/raytracing/intersect/linesegment-linesegment.jl", "max_issues_repo_name": "khurrumsaleem/MOCNeutronTransport", "max_issues_repo_head_hexsha": "16ccaf48d6c01e57e55e74ffbfbd71bbcd0f423c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/raytracing/intersect/linesegment-linesegment.jl", "max_forks_repo_name": "khurrumsaleem/MOCNeutronTransport", "max_forks_repo_head_hexsha": "16ccaf48d6c01e57e55e74ffbfbd71bbcd0f423c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7714285714, "max_line_length": 85, "alphanum_fraction": 0.4050091631, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813513911654, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.7557322329219305}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.4\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 876e6928-abdc-11eb-0fea-d51de2d4b971\nmd\"\"\" ### Quick Julia tutorial...\n\"\"\"\n\n# ╔═╡ 9e95da34-fc21-4e7e-99a9-aea83edacd19\n# global variable\nexample = 9.5\n\n# ╔═╡ 34282b28-b73f-4aa7-96be-31dd6700084f\nareaofcircle(r) = pi * r^2\n\n# ╔═╡ 451499e9-76d9-4088-af2f-f35a9222afca\n#= this updates \n~automatically~\nif you change the first cell\n(and here's how you do multi-line commenting!) =#\n\nbep = areaofcircle(example)\n\n# ╔═╡ 1a3a323e-3f6b-4d65-bcbe-7c1c98aeb150\nmd\"\"\"\n##### Some words on scope...\nIn Julia, like all other languages, there are globally and locally scoped variables. Locally scoped can be considered hard or soft; difference being that soft local variables unassigned locally and defined globally reassign the global variable, whereas hard scope remains local.\n\nJulia uses lexical scoping, meaning that a function's scope refers to the one in which it was defined. For example, calling the module \"Bleep\" from a global scope will use the scope independent to Bleep, NOT the caller's global scope:\n\"\"\"\n\n# ╔═╡ 3f2ba373-77c6-4462-b30b-94fc8602298e\nmodule Bleep\n\texample = 1\n\tfoo() = example\nend\n\n# ╔═╡ 6315a551-f39b-40be-8c84-d3fbf34de4d0\nBleep.foo()\n\n# ╔═╡ fa32bf73-e41a-4db5-ab2a-3e5a9e383aef\nmd\"\"\"\nAnd this new module's independent scope is separate from the caller's global scope:\n\"\"\"\n\n# ╔═╡ 0cd019ae-3521-4323-9371-020190603204\nmodule Deeee\n\tbeh = example\nend\n\n# ╔═╡ 92cfd5a5-09ef-401d-a4a6-53d2576b314f\nmd\"\"\"Also, changing a global variable with a function will result in that variable remaining modified - called 'pass-by-sharing'. Conventionally, these functions will have '!' after their names.\n\"\"\"\n\n# ╔═╡ 92713261-8080-4797-8e48-0f0c2ce0e391\nfunction changer!(bees)\n    bees .+= 1\n    return\nend\n\n# ╔═╡ 997f3fe0-d920-4055-b81e-b259fce128a3\nty = [1.0,2.0,3.0]\n\n# ╔═╡ b6fa822c-7a55-46fe-b3a3-f191fe3ebd3d\nbegin\n\tchanger!(ty)\n\tty\nend\n\n# ╔═╡ 883334fb-f81b-4c24-9527-571a26ce7ce8\nmd\"\"\"\nAdditionally, if one variable is defined as another, any modification to the new variable will result in the same change in the original.\n\"\"\"\n\n# ╔═╡ dc423ed7-c9ee-416a-a0b2-a3c1408221cd\nbegin\n\tblip = [1,2,3]\n\tbehhh = blip\nend\n\n# ╔═╡ b9aab8cc-c738-4f3c-a845-52f5078d1478\nbehhh[2] = 4\n\n# ╔═╡ 0b04f67a-e413-4c9a-b298-610a294561b8\nblip\n\n# ╔═╡ 251313ac-b425-47c5-aae8-d78e5167b052\nmd\"\"\"\nOther fun things include binding with a variety of inputs (copied from their sample notebook)... click the eyeball on the left to see the cell!\n\"\"\"\n\n# ╔═╡ 9f9fb7dd-b0f6-4bb8-b523-6053b5bc39dc\nmd\"\"\"\n`zoot = ` $(@bind zoot html\"<input type=range min=5 max=35>\")\n\n`beef = ` $(@bind beef html\"<input type=text >\")\n\n`crr = ` $(@bind crr html\"<input type=button value='Click'>\")\n\n`drrt = ` $(@bind drrt html\"<input type=checkbox >\")\n\n`efff = ` $(@bind efff html\"<select><option value='one'>First</option><option value='two'>Second</option></select>\")\n\n`fooop = ` $(@bind fooop html\"<input type=color >\")\n\n\"\"\"\n\n# ╔═╡ b03cc059-d281-4973-a22a-fabeb5de06e0\n(zoot, beef, crr, drrt, efff, fooop)\n\n# ╔═╡ c423ec0a-dbf7-4400-99f9-8357ac59edd1\nmd\"\"\"\n#### Working with arrays, concatenation, and plotting...\n\"\"\"\n\n# ╔═╡ d5e187ee-c6b0-4490-80e0-12a47e809d27\nbegin\n\tyears = collect(2001:2005)\n\toranges = [3, 7, 12, 89, 20]\n\tpears = zeros(5,1)\n\tapples = rand(1:100, 5)\n\tbananas = rand(1:100, 5)\nend\n\n# ╔═╡ d50d1e34-9ef2-41de-8dac-bb763685fd5f\nfruits = hcat(apples, oranges, pears, bananas)\n\n# ╔═╡ 2f248615-aaca-44ce-a0d9-0ac31e12ba52\nbegin\n\tusing Plots\n\tplot(years, fruits, layout=(4, 1), legend=false)\nend\n\n# ╔═╡ 6658d1dc-aefd-449b-8d81-f2b9f6a6fe3c\nsort(fruits, dims=2)\n\n# ╔═╡ 3bc93ea9-0718-47b9-ae4c-d1286641c9f2\nall(i->(4<=i<=6), [4,5,6])\n\n# ╔═╡ 28108af6-a838-417b-85a5-5e3fff0ae49b\nmd\"\"\"\n#### Fun with structs!\n\nJulia structs do not require inheritance like OOP languages do - of which Julia is not considered to be, due to the fact that you cannot attach a method (a behavior of a function) to a type. Dispatch, or the choice of method, depends on the first argument in OOP, while in Julia, it chooses which of a function's methods to call depending on the types of all the arguments. This is called multiple dispatch, and is the primary differentiator from other languages.\n\nTypes can be either system-defined or user-defined, and allow for structs to define a \"supertype\" which can be called by any number of functions or structs, as follows.\n\n\"\"\"\n\n# ╔═╡ cca3129b-8ccb-4747-b75d-cb34f3ff5b23\nstruct Limbs\n\thands :: Float64\n\tleg :: Integer\nend\n\n# ╔═╡ b1ce5d0c-c3f6-411c-8f04-c44854fa89b1\nstruct boy\n\tbody_parts :: Limbs #declaring body_parts as a Composite Type, defined by Limbs\n\t# only inner constructors have access to this \"new\" function\n\tboy(hands, leg) = new(Limbs(hands, leg))\nend\n\n# ╔═╡ 26730fa4-254c-4bef-81e5-39803ebcaa2e\nbegin\n\tjoseph = boy(2.,1)\n\tjoseph.body_parts.hands\nend\n\n# ╔═╡ 921051ca-54dc-4563-a116-0756cca43557\nmd\"\"\"\nThis will come into play with user-defined type \"Cell\" that can be acted on by any number of functions.\n\"\"\"\n\n# ╔═╡ 8a3ee669-bad2-4086-b90a-1744b85dcf76\nmd\"\"\"\n##### Differences from other languages that may not be immediately obvious...\n\nhttps://docs.julialang.org/en/v1/manual/noteworthy-differences/\n\nhttps://erik-engheim.medium.com/defining-custom-units-in-julia-and-python-513c34a4c971\n\"\"\"\n\n# ╔═╡ 39d444ec-f84a-4d1b-9ba4-19af636bf3dd\n\n\n# ╔═╡ Cell order:\n# ╟─876e6928-abdc-11eb-0fea-d51de2d4b971\n# ╠═9e95da34-fc21-4e7e-99a9-aea83edacd19\n# ╠═34282b28-b73f-4aa7-96be-31dd6700084f\n# ╠═451499e9-76d9-4088-af2f-f35a9222afca\n# ╟─1a3a323e-3f6b-4d65-bcbe-7c1c98aeb150\n# ╠═3f2ba373-77c6-4462-b30b-94fc8602298e\n# ╠═6315a551-f39b-40be-8c84-d3fbf34de4d0\n# ╟─fa32bf73-e41a-4db5-ab2a-3e5a9e383aef\n# ╠═0cd019ae-3521-4323-9371-020190603204\n# ╟─92cfd5a5-09ef-401d-a4a6-53d2576b314f\n# ╠═92713261-8080-4797-8e48-0f0c2ce0e391\n# ╠═997f3fe0-d920-4055-b81e-b259fce128a3\n# ╠═b6fa822c-7a55-46fe-b3a3-f191fe3ebd3d\n# ╟─883334fb-f81b-4c24-9527-571a26ce7ce8\n# ╠═dc423ed7-c9ee-416a-a0b2-a3c1408221cd\n# ╠═b9aab8cc-c738-4f3c-a845-52f5078d1478\n# ╠═0b04f67a-e413-4c9a-b298-610a294561b8\n# ╟─251313ac-b425-47c5-aae8-d78e5167b052\n# ╟─9f9fb7dd-b0f6-4bb8-b523-6053b5bc39dc\n# ╠═b03cc059-d281-4973-a22a-fabeb5de06e0\n# ╟─c423ec0a-dbf7-4400-99f9-8357ac59edd1\n# ╠═d5e187ee-c6b0-4490-80e0-12a47e809d27\n# ╠═d50d1e34-9ef2-41de-8dac-bb763685fd5f\n# ╠═6658d1dc-aefd-449b-8d81-f2b9f6a6fe3c\n# ╠═2f248615-aaca-44ce-a0d9-0ac31e12ba52\n# ╠═3bc93ea9-0718-47b9-ae4c-d1286641c9f2\n# ╟─28108af6-a838-417b-85a5-5e3fff0ae49b\n# ╠═cca3129b-8ccb-4747-b75d-cb34f3ff5b23\n# ╠═b1ce5d0c-c3f6-411c-8f04-c44854fa89b1\n# ╠═26730fa4-254c-4bef-81e5-39803ebcaa2e\n# ╟─921051ca-54dc-4563-a116-0756cca43557\n# ╟─8a3ee669-bad2-4086-b90a-1744b85dcf76\n# ╠═39d444ec-f84a-4d1b-9ba4-19af636bf3dd\n", "meta": {"hexsha": "0a8a389317adfd491ffd427eb4ee0b29a0350a84", "size": 7065, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/juliatutorial.jl", "max_stars_repo_name": "andi-bergeson/simgym", "max_stars_repo_head_hexsha": "dca4836dabff4a200140bf42d70a066f32ff2b30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-28T22:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T22:30:52.000Z", "max_issues_repo_path": "examples/juliatutorial.jl", "max_issues_repo_name": "andi-bergeson/simgym", "max_issues_repo_head_hexsha": "dca4836dabff4a200140bf42d70a066f32ff2b30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-09T21:06:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T01:12:45.000Z", "max_forks_repo_path": "examples/juliatutorial.jl", "max_forks_repo_name": "andi-bergeson/simgym", "max_forks_repo_head_hexsha": "dca4836dabff4a200140bf42d70a066f32ff2b30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5844155844, "max_line_length": 463, "alphanum_fraction": 0.7322009908, "num_tokens": 3033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8976952859490985, "lm_q1q2_score": 0.7557029080040703}}
{"text": "# Simple example of an eigenproblem:\n#\n#           y\n#             |\n#             |            u_y = 0\n#          Ly ----------------------------------\n#             |                                |\n#             |                                |\n#             |                                |\n#       u = 0 |     u_xx + u_yy + λ u = 0      | u = 0\n#             |                                |\n#             |                                |\n#             |                                |\n#           -----------------------------------|-----  x\n#                          u_y = 0              Lx\n#\n# Here, exact solutions are\n#\n#      u = sin( n π x / Lx ) cos( k π y / Ly )\n#\n#                      2               2\n#      λ = ( n π / Lx )  + ( k π / Ly )\n#\n# for n = 1, 2, 3, ... and k = 0, 1, 2, ....\n\nusing FinElt\nusing FinElt.PlanarPoisson\nusing Printf\nusing Arpack\n\ninclude(\"params.jl\")\nconst nev = 4\n\nλ = Float64[]\nfor n = 1:nev, k = 0:nev-1\n    push!(λ, (n*pi/Lx)^2+(k*pi/Ly)^2)\nend\n\nsort!(λ)\n\nessential_bc = [ \"Left\", \"Right\" ]\n\nerr = zeros(nev, refinements+1)\n@printf(\"Eigenvalue errors\\n\\n\")\n@printf(\"%7s|\", \"N\")\nfor j = 1:nev\n    @printf(\"%16s|\", \"λ_$j    \")\nend \n@printf(\" elapsed\\n\")\n@printf(\"%84s\\n\", \"-\"^84)\nfor k = 0:refinements\n    start = time()\n    mesh = read_msh_file(\"rect$k.msh\")    \n    ep = EigenProblem(mesh, essential_bc)\n    add_bilin_form!(ep, \"Omega\", grad_dot_grad!,   :LHS)\n    add_bilin_form!(ep, \"Omega\", func_times_func!, :RHS)\n    A, B = assembled_eigenproblem_matrices(ep)\n    d, nconv, niter, nmult, resid = eigs(A, B, nev=nev, which=:SM, \n                                         ritzvec=false)\n    finish = time()\n    err[:,k+1] = abs.(d-λ[1:nev])\n    N = size(A, 1)\n    if k == 0\n        elapsed = finish - start\n        @printf(\"%7d|\", N) \n        for j = 1:nev\n            @printf(\"%9.2e %6s|\", err[j,k+1], \"\")\n        end\n        @printf(\" %7.4f\\n\", elapsed)\n    else\n        elapsed = finish - start\n        @printf(\"%7d|\", N)\n        for j = 1:nev\n            rate = log2(err[j,k]/err[j,k+1])\n            @printf(\"%9.2e %6.4f|\", err[j,k+1], rate)\n        end\n        @printf(\" %7.4f\\n\", elapsed)\n    end\nend\n\n", "meta": {"hexsha": "88697c9fa9f04bbb97977d76c92fb5af2631560b", "size": 2171, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/rectangle/eigen.jl", "max_stars_repo_name": "billmclean/FinElt.jl", "max_stars_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-07-18T20:04:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:29:09.000Z", "max_issues_repo_path": "examples/rectangle/eigen.jl", "max_issues_repo_name": "billmclean/FinElt.jl", "max_issues_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/rectangle/eigen.jl", "max_forks_repo_name": "billmclean/FinElt.jl", "max_forks_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-06-29T15:15:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T18:01:08.000Z", "avg_line_length": 26.8024691358, "max_line_length": 67, "alphanum_fraction": 0.3827729157, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7556883451714451}}
{"text": "using Plots, LaTeXStrings; pyplot()\n\na, c, d = 2, 1, 5\nnext(x,y) = [a*x*(1-x) - x*y, -c*y + d*x*y]\nequibPoint = [(1+c)/d ,(d*(a-1)-a*(1+c))/d]\n\ninitX = [0.8,0.05]\ntEnd = 100\n\ntraj = [[] for _ in 1:tEnd]\ntraj[1] = initX\n\nfor t in 2:tEnd\n    traj[t] = next(traj[t-1]...)\nend\n\nscatter([traj[1][1]], [traj[1][2]], \n\tc=:black, ms=10, \n\tlabel=\"Initial state\")\nplot!(first.(traj),last.(traj),\n\tc=:blue, ls=:dash, m=(:dot, 5, Plots.stroke(0)), \n\tlabel=\"Model trajectory\")\nscatter!([equibPoint[1]], [equibPoint[2]], \n\tc=:red, shape=:cross, ms=10, label=\"Equlibrium point\", \n\txlabel=L\"X_1\", ylabel=L\"X_2\")", "meta": {"hexsha": "5ed856dd8e4188f3cafd6972e430e790f5059363", "size": 595, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "10_chapter/predatorPrey.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "10_chapter/predatorPrey.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "10_chapter/predatorPrey.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 23.8, "max_line_length": 56, "alphanum_fraction": 0.5781512605, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7556883362282372}}
{"text": "#    Problem :\n#    *********\t \n#\n#    The Boundary Value problem.\n#    This is the nonlinear least-squares version without fixed variables.\n#  \n#\n#    Source:  problem 28 in\n#    J.J. More', B.S. Garbow and K.E. Hillstrom,\n#    \"Testing Unconstrained Optimization Software\",\n#    ACM Transactions on Mathematical Software, vol. 7(1), pp. 17-41, 1981.\n#\t\n#    Implementation translated from:\n#    See also Buckley#17 (p. 94):\n#\t\n#\t\n#    SIF input: Ph. Toint, Dec 1989 and Nick Gould, Oct 1992.\n#\n#    classification SUR2-MN-V-0\n#    The number of variables is N. \n#\n# Daniel Henderson, 08/2021   \n\nf = x -> begin\n\tn = lastindex(x)\n\th = 1.0/(1 + n)^2\n\tf1 = (2x[1]-x[2]+0.5h^2*(x[1] + h + 1)^3)^2\n\tfn = (2x[n]-x[n-1]+0.5h^2*(x[n] + n*h + 1)^3)^2  \n    return sum((2x[i]-x[i-1]-x[i+1]+0.5h^2*(x[i] + i*h + 1)^3)^2 for i in 2:n-1) + f1 + fn\nend\n\ng! = (g, x) -> begin\n\tr = similar(g)\n\tn = lastindex(x)\n\th = 1.0/(1 + n)^2\n\tfor i in 2:n-1\n\t\tr[i] = 2x[i]-x[i-1]-x[i+1]+0.5h^2*(x[i] + i*h + 1)^3\n\tend\n\tr[1] = 2x[1]-x[2]+0.5h^2*(x[1] + h + 1)^3\n\tr[n] = 2x[n]-x[n-1]+0.5h^2*(x[n] + n*h + 1)^3\n\tfor i in 2:n-1\n\t\tg[i] = -r[i-1] -r[i+1] + r[i]*(2+3/2.0*h^2*(x[i] + i*h + 1)^2)\n\tend\n\tg[1] = -r[2] + r[1] *(2+3/2.0*h^2*(x[1] + h + 1)^2)\n\tg[n] = -r[n-1] + r[n] *(2+3/2.0*h^2*(x[n] + n*h + 1)^2)\n    return g\nend\n\nfg! = (g, x) -> begin\n\tr = similar(g)\n\tn = lastindex(x)\n\th = 1.0/(1 + n)^2\n\tfx = (2x[1]-x[2]+0.5h^2*(x[1] + h + 1)^3)^2 + (2x[n]-x[n-1]+0.5h^2*(x[n] + n*h + 1)^3)^2  \n\tfor i in 2:n-1\n\t\tr[i] = 2x[i]-x[i-1]-x[i+1]+0.5h^2*(x[i] + i*h + 1)^3\n\t\tfx += r[i]^2\n\tend\n\tr[1] = 2x[1]-x[2]+0.5h^2*(x[1] + h + 1)^3\n\tr[n] = 2x[n]-x[n-1]+0.5h^2*(x[n] + n*h + 1)^3\n\tfor i in 2:n-1\n\t\tg[i] = -r[i-1] -r[i+1] + r[i]*(2+3/2.0*h^2*(x[i] + i*h + 1)^2)\n\tend\n\tg[1] = -r[2] + r[1] *(2+3/2.0*h^2*(x[1] + h + 1)^2)\n\tg[n] = -r[n-1] + r[n] *(2+3/2.0*h^2*(x[n] + n*h + 1)^2)\n\treturn fx, g\nend\n\ninit = (n::Int=5000) -> begin\n\tn < 2 && @warn(\"MOREBV: number of variables must be ≥ 2\")\n\tn = max(n, 2)\n    return n, 0.5ones(n)\nend\n@warn \"Debug MOREBV\"\n#TestSet[\"MOREBV\"] = UncProgram(\"MOREBV\",  f, g!, fg!, init)", "meta": {"hexsha": "e9c9f4282d17ba392111dfdc914463e0413c3241", "size": 2073, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/programs/MOREBV.jl", "max_stars_repo_name": "danphenderson/UncNLPrograms.jl", "max_stars_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/programs/MOREBV.jl", "max_issues_repo_name": "danphenderson/UncNLPrograms.jl", "max_issues_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/programs/MOREBV.jl", "max_forks_repo_name": "danphenderson/UncNLPrograms.jl", "max_forks_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0135135135, "max_line_length": 91, "alphanum_fraction": 0.4901109503, "num_tokens": 1067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985936, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7556176775847745}}
{"text": "export intersection_params, line_segment_point, each_intersect, find_juncts, find_connect, connections\n\n\"\"\"\n```julia\nintersection_params(w₁::Line, w₂::Line)\n```\nGiven two lines computes the parameters `[t,s]` so that \nthe intersection of the lines occurs at \n`(w₁.p₂-w₁.p₁)t+w₁.p₁==(w₂.p₂-w₂.p₁)s+w₂.p₁`. If the \nlines are parallel, one is a point and not a line, or \nthe lines are colinear the system of equations will \nnot be consitent and so will return some solution \nlike `[NaN,NaN]` or `[Inf,Inf]`. The lines intersect on \nthe segments given whenever both `0≤t≤1` and `0≤s≤1`.\n\"\"\"\nfunction intersection_params(w₁::Line, w₂::Line)\n    hcat(w₁.p₂-w₁.p₁,w₂.p₁-w₂.p₂)\\(w₂.p₁-w₁.p₁)\nend\n\n\"\"\"\n```julia\nline_segment_point(t::T, w::Line)\n```\nComputes the point on the line `w` at parameter `t` where \n`t` is the parameter of the line so that `p₂*t+(1-t)p₁` \nis the parametric equation of the line. \n\"\"\"\nfunction line_segment_point(t::T, w::Line) where T<:Real \n    w.p₂*t+(1-t)*w.p₁\nend\n\n\"\"\"\n```julia\neach_intersect(f!,arr₁,arr₂,dims,arg)\n```\n    Executes `f!(i₁,i₂,arr₁,arr₂,dims,ps,p,arg)` for any intersection between pairs of \n    lines in `arr₁` and `arr₂`. `i₁` and `i₂` are the indices of the lines in `arr₁` \n    and `arr₂` respectively, `ps` is the vector of line intersection parameters as \n    computed by `intersection_params(arr₁[i₁],arr₂[i₂])`, and `p` is the point at which \n    the intersection occurs.\n\"\"\"\nfunction each_intersect(f!, arr₁::Array{Line{S,N}}, arr₂::Array{Line{S,N}}, dims::SVector{N,S}, arg) where {S,N}\n    for i₁ ∈ eachindex(arr₁)\n        for i₂ ∈ eachindex(arr₂)\n            ps = intersection_params(arr₁[i₁],arr₂[i₂])\n            if (0.0 ≤ ps[1] ≤ 1.0) && (0.0 ≤ ps[2] ≤ 1.0)\n                p = line_segment_point(ps[1],arr₁[i₁])\n                if sum( zero(SVector{N, S}) .≤ p .≤ dims ) == N\n                    f!(i₁,i₂,arr₁,arr₂,dims,ps,p,arg)\n                end\n            end\n        end\n    end\n    arg\nend\n\n\"\"\"\n```julia\neach_intersect(f!,arr,dims,arg)\n```\n    Executes `f!(i₁,i₂,arr,dims,ps,p,arg)` for any intersection between pairs of \n    lines in `arr`. `i₁` and `i₂` are the indices of the lines in `arr`, `ps` is \n    the vector of line intersection parameters as computed by \n    `intersection_params(arr[i₁],arr[i₂])`, and `p` is the point at which the \n    intersection occurs.\n\"\"\"\nfunction each_intersect(f!, arr::Array{Line{S,N}}, dims::SVector{N,S}, arg) where {S,N}\n    n = length(arr)\n    for i₁ ∈ 2:(n)\n        for i₂ ∈ 1:(i₁-1)\n            ps = intersection_params(arr[i₁],arr[i₂])\n            if (0.0 ≤ ps[1] ≤ 1.0) && (0.0 ≤ ps[2] ≤ 1.0)\n                p = line_segment_point(ps[1],arr[i₁])\n                if sum( zero(SVector{N, S}) .≤ p .≤ dims ) == N\n                    f!(i₁,i₂,arr,dims,ps,p,arg)\n                end\n            end\n        end\n    end\n    arg\nend\n\n\"\"\"\n```julia\nfind_juncts(net)\n```\nGiven an `StickNetwork` object finds all points of intersection between lines. \n\"\"\"\nfunction find_juncts(net::StickNetwork{T,N}) where {T,N}\n    each_intersect(net.lines, net.dims, Array{Tuple{SVector{N,T},Tuple{Int,Int}},1}()) do i₁,i₂,arr,dims,ps,p,juncts\n        push!(juncts,(p,(i₁,i₂)))\n    end\nend\n\n\"\"\"\n```julia\nfind_connect(net)\n```\nGiven an `StickNetwork` object finds all pairs `(i₁,i₂)` with an intersection between lines `i₁` and `i₂` in `net`.\n\"\"\"\nfunction find_connect(net::StickNetwork{T,N}) where {T,N}\n    each_intersect(net.lines, net.dims, Array{Tuple{Int,Int},1}()) do i₁,i₂,arr,dims,ps,p,connects\n        push!(connects,(i₁,i₂))\n    end\nend\n\n\"\"\"\n```julia\nconnections(arr₁,arr₂,dims)\n```\nFinds all connections between arrays of `Line`s `arr₁` and `arr₂`. \nReturns `Tuple{Vector{Int},Vector{Int}}` with each vector representing the source and destination line indices for each connection.\n\"\"\"\nfunction connections(arr₁::Array{Line{S,N}}, arr₂::Array{Line{S,N}}, dims::SVector{N,S}) where {S,N}\n    each_intersect(arr₁, arr₂, dims, (Int[],Int[])) do i₁,i₂,arr₁,arr₂,dims,ps,p,connects\n        push!(connects[1],i₁)\n        push!(connects[2],i₂)\n    end\nend\n\n\"\"\"\n```julia\nconnections(arr,dims)\n```\nFinds all connections between `Line`s in `arr`. \nReturns `Tuple{Vector{Int},Vector{Int}}` with each vector representing the source and destination line indices for each connection.\n\"\"\"\nfunction connections(arr::Array{Line{S,N}}, dims::SVector{N,S}) where {S,N}\n    each_intersect(arr, dims, (Int[],Int[])) do i₁,i₂,arr,dims,ps,p,connects\n        push!(connects[1],i₁)\n        push!(connects[2],i₂)\n    end\nend", "meta": {"hexsha": "5209561ce333acb9b43c6f4e381dab25fe4662d8", "size": 4493, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/intersections.jl", "max_stars_repo_name": "heckomorphism/NWNTools.jl", "max_stars_repo_head_hexsha": "f947d8ccab6ba58d23b513091e55738665a88d5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-30T15:29:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-30T15:29:25.000Z", "max_issues_repo_path": "src/intersections.jl", "max_issues_repo_name": "heckomorphism/NWNTools.jl", "max_issues_repo_head_hexsha": "f947d8ccab6ba58d23b513091e55738665a88d5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-19T19:29:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T19:29:56.000Z", "max_forks_repo_path": "src/intersections.jl", "max_forks_repo_name": "heckomorphism/NWNTools.jl", "max_forks_repo_head_hexsha": "f947d8ccab6ba58d23b513091e55738665a88d5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7819548872, "max_line_length": 131, "alphanum_fraction": 0.6349877587, "num_tokens": 1433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897426182322, "lm_q2_score": 0.8031737987125613, "lm_q1q2_score": 0.7556176713684984}}
{"text": "function metric(J::AbstractArray{T,2}) where {T}\n    g = J'*J\n    return g\nend\n\nfunction covariant_basis(c::Coordinate{T}) where {T}\n    return ForwardDiff.jacobian(c.R,c.u)\nend\n\nfunction covariant_metric(c::Coordinate)\n    J = covariant_basis(c)\n    return metric(J)\nend\n\nfunction contravariant_basis(c::Coordinate)\n    Jco = covariant_basis(c)\n    gco = metric(Jco)\n    g = inv(gco)\n    J = Jco*g\n    return J\nend\n\nfunction contravariant_metric(c::Coordinate)\n    J = contravariant_basis(c)\n    g = metric(J)\nend\n\nabstract type CoordinateVector{T} <: AbstractArray{T,1} end\n\nstruct ContravariantVector{T,F} <: CoordinateVector{T}\n    data::Vector{T}       #Contravariant Components of the Vector\n    coord::Coordinate{T,F}  #Vector Coordinate\n    J::Matrix{T}\n    g::Matrix{T}\n    h::Vector{T}\nend\n\nfunction ContravariantVector(data::AbstractVector{T}, coord::Coordinate{T,F}; unit_basis = false) where {T,F}\n    J = covariant_basis(coord)\n    g = metric(J)\n    h = sqrt.(diag(g))\n    if unit_basis\n        data = data./h\n    end\n    ContravariantVector{T,F}(data, coord, J, g, h)\nend\n\nstruct CovariantVector{T,F} <: CoordinateVector{T}\n    data::Vector{T}       #Covariant Components of the Vector\n    coord::Coordinate{T,F}  #Vector Coordinate\n    J::Matrix{T}\n    g::Matrix{T}\n    h::Vector{T}\nend\n\nfunction CovariantVector(data::AbstractVector{T}, coord::Coordinate{T,F}; unit_basis = false) where {T,F}\n    J = contravariant_basis(coord)\n    g = metric(J)\n    h = sqrt.(diag(g))\n    if unit_basis\n        data = data./h\n    end\n    CovariantVector{T,F}(data, coord, J, g, h)\nend\n\n# Array Interface for CoordinateVector\nparent(A::T) where {T<:CoordinateVector} = A.data\nsize(A::T) where {T<:CoordinateVector} = size(A.data)\naxes(A::T) where {T<:CoordinateVector} = axes(A.data)\nparenttype(::Type{CoordinateVector{T}}) where {T} = Vector{T}\nIndexStyle(::Type{T}) where {T<:CoordinateVector} = IndexStyle(parenttype(T))\n\n@propagate_inbounds getindex(A::T, i::Int) where {T<:CoordinateVector} = A.data[i]\n@propagate_inbounds setindex!(A::CoordinateVector{T}, v::T, i::Int) where {T} = A.data[i] = v\n\nfunction convert(::Type{T}, x::S) where {T<:CoordinateVector,S<:CoordinateVector}\n    data = x.g*x.data\n    g = inv(x.g)\n    J = x.J*g\n    h = sqrt.(diag(g))\n    T(data, x.coord, J, g, h)\nend\n\nconvert(::Type{T}, x::T) where {T<:CoordinateVector} = x\nconvert(x::CovariantVector) = convert(ContravariantVector,x)\nconvert(x::ContravariantVector) = convert(CovariantVector,x)\n\nfunction unit_basis_components(x::T) where {T<:CoordinateVector}\n    return x .* x.h\nend\n", "meta": {"hexsha": "de6659be2451172b59c6421d35611f9b58de7d54", "size": 2565, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/coordinate_vectors.jl", "max_stars_repo_name": "JuliaTagBot/VectorCalculus.jl", "max_stars_repo_head_hexsha": "04decba2702f9b41a83617c5971ad9b051c6c866", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-11-29T04:29:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-05T12:38:51.000Z", "max_issues_repo_path": "src/coordinate_vectors.jl", "max_issues_repo_name": "JuliaTagBot/VectorCalculus.jl", "max_issues_repo_head_hexsha": "04decba2702f9b41a83617c5971ad9b051c6c866", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-11-29T07:10:10.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-17T20:08:29.000Z", "max_forks_repo_path": "src/coordinate_vectors.jl", "max_forks_repo_name": "JuliaTagBot/VectorCalculus.jl", "max_forks_repo_head_hexsha": "04decba2702f9b41a83617c5971ad9b051c6c866", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:54:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T12:38:55.000Z", "avg_line_length": 28.1868131868, "max_line_length": 109, "alphanum_fraction": 0.6748538012, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514736, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.755612131424034}}
{"text": "# PS2  Dayuan Xie\r\n# using Pkg\r\n# Pkg.add(\"Optim\")\r\n# Pkg.add(\"HTTP\")\r\n# Pkg.add(\"GLM\")\r\n\r\nusing Optim\r\nusing HTTP\r\nusing GLM\r\nusing LinearAlgebra\r\nusing Random\r\nusing Statistics\r\nusing DataFrames\r\nusing CSV\r\nusing FreqTables\r\n\r\nfunction q6()\r\n\r\n# Question 1\r\nf(x) = -x[1]^4-10x[1]^3-2x[1]^2-3x[1]-2\r\nminusf(x) = x[1]^4+10x[1]^3+2x[1]^2+3x[1]+2\r\nstartval = rand(1)   \r\nresult = optimize(minusf, startval, BFGS())\r\nprintln(result)\r\n\r\n# Question 2\r\nurl = \"https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2020/master/ProblemSets/PS1-julia-intro/nlsw88.csv\"\r\ndf = CSV.read(HTTP.get(url).body)\r\nX = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\r\ny = df.married.==1\r\n\r\nfunction ols(beta, X, y)\r\n    ssr = (y.-X*beta)'*(y.-X*beta)\r\n    return ssr\r\nend\r\n\r\nbeta_hat_ols = optimize(b -> ols(b, X, y), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-6, iterations=100_000, show_trace=true))\r\nprintln(beta_hat_ols.minimizer)\r\n\r\nbols = inv(X'*X)*X'*y\r\ndf.white = df.race.==1\r\nbols_lm = lm(@formula(married ~ age + white + collgrad), df)\r\nprintln(bols_lm)\r\n\r\n# Question 3\r\nfunction logit(alpha, X, d)\r\n    loglike=d'*X*alpha-sum(log.(ones(size(X,1),1)+exp.(X*alpha)))\r\n    return loglike\r\nend\r\nalpha_hat_logit = optimize(a -> -(logit(a, X, y)), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-6, iterations=100_000, show_trace=true))\r\nprintln(alpha_hat_logit.minimizer)\r\n\r\n# question 4\r\nalpha_glm= glm(@formula(married ~ age + white + collgrad), df, Binomial(), LogitLink())\r\nprintln(alpha_glm)\r\n\r\n# Question 5\r\nfreqtable(df, :occupation) # note small number of obs in some occupations\r\ndf = dropmissing(df, :occupation)\r\ndf[df.occupation.==8 ,:occupation] .= 7\r\ndf[df.occupation.==9 ,:occupation] .= 7\r\ndf[df.occupation.==10,:occupation] .= 7\r\ndf[df.occupation.==11,:occupation] .= 7\r\ndf[df.occupation.==12,:occupation] .= 7\r\ndf[df.occupation.==13,:occupation] .= 7\r\nfreqtable(df, :occupation) # problem solved\r\n\r\nX = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\r\ny = df.occupation\r\n\r\ny1=y.==1\r\ny2=y.==2\r\ny3=y.==3\r\ny4=y.==4\r\ny5=y.==5\r\ny6=y.==6\r\ny7=y.==7\r\n\r\nY = cat(y1,y2,y3,y4,y5,y6,dims=2) \r\n\r\nfunction csum(A)\r\n    Colsum = []\r\n    for i=1:size(A,1)\r\n        sum(A[i,:])\r\n        push!(Colsum,sum(A[i,:]))\r\n    end\r\n        return Colsum\r\nend\r\n\r\nfunction mlogit(alpha, X, d)\r\n    loglike=tr(d*(X*alpha)')-sum(log.(csum(exp.(X*alpha))))\r\n    return loglike\r\nend\r\n\r\nbeta_hat_mlogit1 = optimize(b -> -mlogit(b, X, Y), zeros(size(X,2),6), LBFGS(), Optim.Options(g_tol=10-5, iterations=100_000, show_trace=true))\r\nprintln(beta_hat_mlogit1.minimizer)\r\n\r\nbeta_hat_mlogit2 = optimize(b -> -mlogit(b, X, Y), rand(size(X,2),6), LBFGS(), Optim.Options(g_tol=10-5, iterations=100_000, show_trace=true))\r\nprintln(beta_hat_mlogit2.minimizer)\r\n\r\nbeta_hat_mlogit3 = optimize(b -> -mlogit(b, X, Y), 2*rand(size(X,2),6).-1, LBFGS(), Optim.Options(g_tol=10-5, iterations=100_000, show_trace=true))\r\nprintln(beta_hat_mlogit3.minimizer)\r\n\r\nend\r\n\r\n# Question 6\r\nq6()\r\n\r\n\r\n\r\n", "meta": {"hexsha": "67cd401dc965df5fe2c21c34bf323f21bc677236", "size": 2975, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS2-optimization-intro/PS2_Dayuan Xie.jl", "max_stars_repo_name": "dayuanxie/fall-2020", "max_stars_repo_head_hexsha": "a51f0a924efcffde8f934e987e1306c236eb4a5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSets/PS2-optimization-intro/PS2_Dayuan Xie.jl", "max_issues_repo_name": "dayuanxie/fall-2020", "max_issues_repo_head_hexsha": "a51f0a924efcffde8f934e987e1306c236eb4a5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS2-optimization-intro/PS2_Dayuan Xie.jl", "max_forks_repo_name": "dayuanxie/fall-2020", "max_forks_repo_head_hexsha": "a51f0a924efcffde8f934e987e1306c236eb4a5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-16T11:54:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T11:54:59.000Z", "avg_line_length": 26.8018018018, "max_line_length": 148, "alphanum_fraction": 0.6507563025, "num_tokens": 1050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7556121291572435}}
{"text": "\"\"\"\n    calculateEnergy(r, r_j, r_dist, p_j, m, m_j, mu, mu_sum, ignore_H0)\n\nCalculates the sum of kynetic and potential energy of the N-body hamiltonian system:\n\n```math\n\\\\mathcal{H}_{\\\\mathrm{N-body}}(\\\\textbf{q}, \\\\textbf{p}) = \\\\sum_{i=1}^{N} \\\\frac{\\\\textbf{p'}^{2}_{i}}{2 m_{i}'} - \\\\sum_{i=1}^{N} \\\\sum_{j=i+1}^{N} \\\\frac{Gm_{i}m_{j}}{\\\\mid \\\\textbf{q}_{i} - \\\\textbf{q}_{j} \\\\mid} \\\\\\\\\n```\n\n# Args\n\n* `r`: NxD matrix where N is the number of bodies and D is the number of dimensions, each row contains the positions of the bodies in cartesian coordinates.\n* `r_j`:  NxD matrix, it contains the positions of the bodies in jacobi coordinates.\n* `r_dist`: array of N elements, in which distances from the bodies to the barycenter are saved.\n* `p_j`: NxD matrix, it contains the momentum of the bodies in jacobi coordinates.\n* `m`: array of N elements, where element number i contains the mass of i-th body.\n* `m_j`: array of N elements, each containing the i-th jacobi mass (``m'_{i}``)\n```math\nm'_{1} = m_{sum_{N}} \\\\\\\\\nm'_{i} = m_{i} \\\\frac{m_{sum_{i-1}}}{m_{sum_{i}}} \\\\\\\\\n\\\\mathrm{,where } \\\\hspace{0.5cm} m_{sum_{i}} = \\\\sum_{j = 1}^{i} m_{j}\n```\n* `mu`: array of N elements, where element with index i contains the standard gravitational parameter of the i-th body\n```math\nmu_{i} = G \\\\cdot m_{j} \\\\\\\\\n```\n* `mu_{sum}`: array of N elements, where the standard gravitational parameter of the bodies from 1 to i is saved in the i-th element\n```math\nmu_{sum_{i}} = \\\\sum_{j = 1}^{i} G \\\\cdot m_{j} \\\\\\\\\n```\n* `ignore_H0`: boolean that determines if Hamiltonian ``\\\\mathcal{H_{0}}`` will be ignored (when calculating the energy).\n\n# Returns \n\nThe energy of the ``\\\\mathcal{H}_{N-body}`` system.\n\"\"\"\nfunction calculateEnergy(r, r_j, r_dist, p_j, m, m_j, mu, mu_sum, ignore_H0)\n    energy = 0.0\n    \n    # H_0\n    if !ignore_H0\n        energy += (dot(p_j[1,:],p_j[1,:]) / (2.0*m_j[1]))\n    end\n    \n    # H_Kepler\n    for i in 2:size(r)[1]\n        energy += (dot(p_j[i,:],p_j[i,:]) / (2.0*m_j[i])) #- (mu_sum[i] * m_j[i] / r_dist[i])\n    end\n    #println(energy)\n    \n    # H_Interaction step 1\n    #for i in 2:size(r)[1]\n    #    energy += (mu_sum[i] * m_j[i] / r_dist[i])\n    #end\n    #println(energy)\n    \n    # H_Interaction step 2\n    for i in 1:size(r)[1]\n        for j in (i+1):size(r)[1]\n            energy -= (mu[i] * m[j] / norm(r[i,:] - r[j,:]))\n        end\n    end\n    \n    return energy\nend", "meta": {"hexsha": "c9d13a216d3d3b985099a2236636e36572fd8409", "size": 2408, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/energy.jl", "max_stars_repo_name": "salanueva/KeplerFlow", "max_stars_repo_head_hexsha": "4e370d6fd76100974d31ad548629f52217b4e96f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/energy.jl", "max_issues_repo_name": "salanueva/KeplerFlow", "max_issues_repo_head_hexsha": "4e370d6fd76100974d31ad548629f52217b4e96f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/energy.jl", "max_forks_repo_name": "salanueva/KeplerFlow", "max_forks_repo_head_hexsha": "4e370d6fd76100974d31ad548629f52217b4e96f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0461538462, "max_line_length": 222, "alphanum_fraction": 0.6042358804, "num_tokens": 838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693731004241, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7556121267884629}}
{"text": "using Plotly;\ninclude(\"../interps.jl\")\nf(x) = 2016x^7 + 12x^5 +x^4 + x^3 + x^2 + x + 1\n\n\nxs = linspace(-1,1, 6)\nNewton = interpNewton(xs,map(f,xs))\n\nxss = linspace(-1,1, 10000)\ntrace1 = scatter(;x=xss, y= map(Newton,xss), name=\"Newton\")\ntrace2 = scatter(;x=xss, y=  map(f        ,xss), name=\"f\")\nplot([trace1, trace2])\n\n#zera czebyszewa\nk = 6\nxs = []\nfor i = 0:(k-1)\npush!(xs, cos(pi*(2*i+1)/(2*k) ))\nend\nxs = sort(xs)\n@show xs\n\nNewton = interpNewton(xs,map(f,xs))\n\nxss = linspace(-1,1, 10000)\ntrace1 = scatter(;x=xss, y= map(Newton,xss), name=\"Newton\")\ntrace2 = scatter(;x=xss, y=  map(f        ,xss), name=\"f\")\nplot([trace1, trace2])\n", "meta": {"hexsha": "b587b682c2e4925cdf9f39b2fa38ec6f2ef5d263", "size": 636, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Analiza_Numeryczna_M/09Lista/10.jl", "max_stars_repo_name": "Magikis/Uniwersity", "max_stars_repo_head_hexsha": "06964ef31d721af85740df1dce3f966006ab9f78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-11-30T08:45:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-26T14:15:45.000Z", "max_issues_repo_path": "Analiza_Numeryczna_M/09Lista/10.jl", "max_issues_repo_name": "Magikis/Uniwersity", "max_issues_repo_head_hexsha": "06964ef31d721af85740df1dce3f966006ab9f78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Analiza_Numeryczna_M/09Lista/10.jl", "max_forks_repo_name": "Magikis/Uniwersity", "max_forks_repo_head_hexsha": "06964ef31d721af85740df1dce3f966006ab9f78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2017-10-16T09:42:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-27T19:48:45.000Z", "avg_line_length": 21.9310344828, "max_line_length": 59, "alphanum_fraction": 0.5943396226, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7555609564301418}}
{"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    EigenAnalysis(proj)\n\nThe eigenanalysis of the covariance with a given projection `proj`.\n\n## Projections\n\n* `:V` - Uncorrelated variables (PCA transform)\n* `:VD` - Uncorrelated variables and variance one (DRS transform)\n* `:VDV` - Uncorrelated variables and variance one (SDS transformation)\n\nThe `:V` projection used in the PCA transform projects the data on the eigenvectors\nV of the covariance matrix.\n\nThe `:VD` projection used in the DRS transform. Similar to the `:V` projection,\nbut the eigenvectors are multiplied by the squared inverse of the eigenvalues D.\n\nThe `:VDV` projection used in the SDS transform. Similar to the `:VD` transform,\nbut the data is projected back to the basis of the original variables using the Vᵀ matrix.\n\nSee [https://geostatisticslessons.com/lessons/sphereingmaf](https://geostatisticslessons.com/lessons/sphereingmaf)\nfor more details about these three variants of eigenanalysis.\n\n# Examples\n\n```julia\nEigenAnalysis(:V)\nEigenAnalysis(:VD)\nEigenAnalysis(:VDV)\n```\n\"\"\"\nstruct EigenAnalysis <: Transform\n  proj::Symbol\n\n  function EigenAnalysis(proj)\n    @assert proj ∈ (:V, :VD, :VDV) \"invalid projection\"\n    new(proj)\n  end\nend\n\nassertions(::Type{EigenAnalysis}) = [assert_continuous]\n\nisrevertible(::Type{EigenAnalysis}) = true\n\nfunction apply(transform::EigenAnalysis, table)\n  # basic checks\n  for assertion in assertions(transform)\n    assertion(table)\n  end\n\n  # original columns names\n  names = Tables.columnnames(table)\n\n  # table as matrix\n  X = Tables.matrix(table)\n\n  # center the data\n  μ = mean(X, dims=1)\n  Y = X .- μ\n\n  # eigenanalysis of covariance\n  S, S⁻¹ = eigenmatrices(transform, Y)\n\n  # project the data\n  Z = Y * S\n\n  # table with transformed columns\n  𝒯 = (; zip(names, eachcol(Z))...)\n  newtable = 𝒯 |> Tables.materializer(table)\n\n  newtable, (μ, S, S⁻¹)\nend\n\nfunction revert(::EigenAnalysis, newtable, cache)\n  # transformed column names\n  names = Tables.columnnames(newtable)\n\n  # table as matrix\n  Z = Tables.matrix(newtable)\n\n  # retrieve cache\n  μ, S, S⁻¹ = cache\n\n  # undo projection\n  Y = Z * S⁻¹\n\n  # undo centering\n  X = Y .+ μ\n\n  # table with original columns\n  𝒯 = (; zip(names, eachcol(X))...)\n  𝒯 |> Tables.materializer(newtable)\nend\n\nfunction reapply(transform::EigenAnalysis, table, cache)\n  # basic checks\n  for assertion in assertions(transform)\n    assertion(table)\n  end\n\n  # original columns names\n  names = Tables.columnnames(table)\n\n  # table as matrix\n  X = Tables.matrix(table)\n\n  # retrieve cache\n  μ, S, S⁻¹ = cache\n\n  # center the data\n  Y = X .- μ\n\n  # project the data\n  Z = Y * S\n\n  # table with transformed columns\n  𝒯 = (; zip(names, eachcol(Z))...)\n  𝒯 |> Tables.materializer(table)\nend\n\nfunction eigenmatrices(transform, Y)\n  proj = transform.proj\n\n  Σ = cov(Y)\n  λ, V = eigen(Σ)\n\n  if proj == :V\n    S   = V\n    S⁻¹ = transpose(V)\n  elseif proj == :VD\n    Λ   = Diagonal(sqrt.(λ))\n    S   = V * inv(Λ)\n    S⁻¹ = Λ * transpose(V)\n  elseif proj == :VDV\n    Λ   = Diagonal(sqrt.(λ))\n    S   = V * inv(Λ) * transpose(V)\n    S⁻¹ = V * Λ * transpose(V)\n  end\n\n  S, S⁻¹\nend\n\n\"\"\"\n    PCA()\n\nThe PCA transform is a shortcut for\n`ZScore() → EigenAnalysis(:V)`.\n\nSee also: [`ZScore`](@ref), [`EigenAnalysis`](@ref).\n\"\"\"\nPCA() = ZScore() → EigenAnalysis(:V)\n\n\"\"\"\n    DRS()\n\nThe DRS transform is a shortcut for\n`ZScore() → EigenAnalysis(:VD)`.\n\nSee also: [`ZScore`](@ref), [`EigenAnalysis`](@ref).\n\"\"\"\nDRS() = ZScore() → EigenAnalysis(:VD)\n\n\"\"\"\n    SDS()\n\nThe SDS transform is a shortcut for\n`ZScore() → EigenAnalysis(:VDV)`.\n\nSee also: [`ZScore`](@ref), [`EigenAnalysis`](@ref).\n\"\"\"\nSDS() = ZScore() → EigenAnalysis(:VDV)\n", "meta": {"hexsha": "005918befae478345e81e2f41044f70c6d305317", "size": 3821, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transforms/eigenanalysis.jl", "max_stars_repo_name": "eliascarv/TableTransforms.jl", "max_stars_repo_head_hexsha": "1c678e70daf7c92a252a75ff473f5f24b96019bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/transforms/eigenanalysis.jl", "max_issues_repo_name": "eliascarv/TableTransforms.jl", "max_issues_repo_head_hexsha": "1c678e70daf7c92a252a75ff473f5f24b96019bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/transforms/eigenanalysis.jl", "max_forks_repo_name": "eliascarv/TableTransforms.jl", "max_forks_repo_head_hexsha": "1c678e70daf7c92a252a75ff473f5f24b96019bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7102272727, "max_line_length": 114, "alphanum_fraction": 0.6448573672, "num_tokens": 1081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936262, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7555609470757869}}
{"text": "# PROX_L1    The proximal operator of the l1 norm.\n#\n#   prox_l1(v,lambda) is the proximal operator of the l1 norm\n#   with parameter lambda.\nfunction x = prox_l1(v, lambda)\n    x = max(0, v - lambda) - max(0, -v - lambda)\n    return x\nend\n", "meta": {"hexsha": "6f108a5a7d628bf64339bbbfe06e56bcbfc00682", "size": 240, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/prox_l1.jl", "max_stars_repo_name": "johnmyleswhite/Proximal.jl", "max_stars_repo_head_hexsha": "256de4c00557983935c0deaff6d6e4ccdb5da7c3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-08-03T21:31:45.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-20T01:51:56.000Z", "max_issues_repo_path": "src/prox_l1.jl", "max_issues_repo_name": "johnmyleswhite/Proximal.jl", "max_issues_repo_head_hexsha": "256de4c00557983935c0deaff6d6e4ccdb5da7c3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/prox_l1.jl", "max_forks_repo_name": "johnmyleswhite/Proximal.jl", "max_forks_repo_head_hexsha": "256de4c00557983935c0deaff6d6e4ccdb5da7c3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-01T18:12:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:12:26.000Z", "avg_line_length": 26.6666666667, "max_line_length": 61, "alphanum_fraction": 0.6583333333, "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7555609461389873}}
{"text": "## Wetted-area method\n#======================================================#\n\n# Raymer form factor for wing, pylon, nacelle, fuselage? (Eq. 12.30)\nform_factor_wing(x_c, t_c, Λ_m, M) = (1 + 0.6t_c / x_c + 100t_c^4) * (1.34M^0.18 * cos(Λ_m)^0.28)\n\nfunction form_factor(wing :: HalfWing, M)\n\t# (x/c)_max, (t/c)_max, (t/c)_max sweep angles\n\txcs, tcs, sweeps = max_tbyc_sweeps(wing, 60)\n\tKf \t\t\t\t = form_factor_wing.(xcs, tcs, sweeps, M)\nend\n\n# Schlichting averaged skin-friction coefficients\ncf_lam(Re_c, k_lam = 1.) = 1.328 / √(Re_c * k_lam)\ncf_turb(Re_c, M) = 0.455 / log10(Re_c)^2.58 / (1 + 0.144M^2)^0.65\ncf_schlichting(Re, Re_xtr, M) = max(cf_lam(Re), cf_turb(Re, M) - (Re_xtr / 320 - 39) / Re)\n\nfunction wetted_area_drag(mean_chords, S_wets, K_fs, x_tr, V, ρ, M, μ)\n\t# Skin-friction coefficients\n\tRe_c \t\t= reynolds_number.(ρ, V, mean_chords, μ)\n\tRe_xtr \t\t= reynolds_number.(ρ, V, mean_chords .* x_tr, μ)\n\tcfs \t\t= cf_schlichting.(Re_c, Re_xtr, M)\n\n\t# Profile drag\n\tDp_by_q\t \t= sum(@. cfs * S_wets * K_fs)\nend\n\nfunction wetted_area_drag(wing :: HalfWing, x_tr, V, ρ, a_ref = 330., μ = 1.5e-5)\n\t# Chord processing\n\tmean_chords = (fwdsum ∘ chords)(wing) / 2\n\n\t# Wetted areas\n\tS_wets = @. mean_chords * wing.spans / cos(wing.dihedrals)\n\n\t# Form factors\n\tM \t = V / a_ref\n\tK_fs = form_factor(wing, M)\n\n\twetted_area_drag(mean_chords, S_wets, K_fs, x_tr, V, ρ, M, μ)\nend\n\nprofile_drag_coefficient(wing :: HalfWing, x_tr, V, rho_ref, a_ref, area_ref, μ) = wetted_area_drag(wing, x_tr, V, rho_ref, a_ref, μ) / area_ref\nprofile_drag_coefficient(wing :: Wing, x_tr, V, rho_ref, a_ref, area_ref, μ) = profile_drag_coefficient(left(wing), x_tr, V, rho_ref, a_ref, area_ref, μ) + profile_drag_coefficient(right(wing), x_tr, V, rho_ref, a_ref, area_ref, μ)\n\n## Local-friction and local-dissipation method", "meta": {"hexsha": "6fc76ecd366fda93d4ef8a637a6a59f9359e8487", "size": 1790, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Aerodynamics/profile_drag.jl", "max_stars_repo_name": "GodotMisogi/AeroMDAO.jl", "max_stars_repo_head_hexsha": "e05b3d4589583a3e106c5fc2fde86578483133c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2021-09-23T08:04:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T13:28:01.000Z", "max_issues_repo_path": "src/Aerodynamics/profile_drag.jl", "max_issues_repo_name": "GodotMisogi/AeroMDAO.jl", "max_issues_repo_head_hexsha": "e05b3d4589583a3e106c5fc2fde86578483133c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-02-08T06:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T06:08:38.000Z", "max_forks_repo_path": "src/Aerodynamics/profile_drag.jl", "max_forks_repo_name": "GodotMisogi/AeroMDAO", "max_forks_repo_head_hexsha": "e05b3d4589583a3e106c5fc2fde86578483133c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-01-25T08:46:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T08:11:45.000Z", "avg_line_length": 39.7777777778, "max_line_length": 231, "alphanum_fraction": 0.6648044693, "num_tokens": 703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870767, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7555609436011174}}
{"text": "# ---\n# title: 1017. Convert to Base -2\n# id: problem1017\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Medium\n# categories: Math\n# link: <https://leetcode.com/problems/convert-to-base-2/description/>\n# hidden: true\n# ---\n# \n# Given a number `N`, return a string consisting of `\"0\"`s and `\"1\"`s that\n# represents its value in base `**-2**` (negative two).\n# \n# The returned string must have no leading zeroes, unless the string is `\"0\"`.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: 2\n#     Output: \"110\"\n#     **Explantion:** (-2) ^ 2 + (-2) ^ 1 = 2\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: 3\n#     Output: \"111\"\n#     **Explantion:** (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: 4\n#     Output: \"100\"\n#     **Explantion:** (-2) ^ 2 = 4\n#     \n# \n# \n# \n# **Note:**\n# \n#   1. `0 <= N <= 10^9`\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction base_neg2(N::Int)\n    cnt = 0\n    res = \"\"\n    while N > 0\n        bit = (N & 1)\n        N -= bit * (-1) ^ cnt\n        N >>= 1\n        cnt += 1\n        res = string(bit) * res\n    end\n    res\nend\n## @lc code=end\n", "meta": {"hexsha": "a3642203ebb95d4cdf735e4666dbf4e310703167", "size": 1134, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/1017.convert-to-base-2.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/1017.convert-to-base-2.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/1017.convert-to-base-2.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 16.4347826087, "max_line_length": 78, "alphanum_fraction": 0.4691358025, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7555547743213482}}
{"text": "using Distributions, Plots, Colors\n\n# Gaussian with known variance\n# mu ~ Normal(mu0, sig0)\n# x_i ~ Normal(mu, sig_like)\n# Ref: https://en.wikipedia.org/wiki/Conjugate_prior#Continuous_distributions\nfunction compute_posterior_parameters(xs, mu0, sig0, sig_like)\n    n = length(xs)\n    var = inv(1 / sig0^2 + n / sig_like^2)\n    mu = var * (mu0 / sig0^2 + sum(xs) / sig_like^2)\n    return mu, sqrt(var)\nend\n\nmu0 = 0.0\nsig0 = 1.0\nsig_like = 1.0\nprior = Normal(mu0, sig0)\n\n# Inference\nobs = [5.0]\npo1 = compute_posterior_parameters(obs, mu0, sig0, sig_like)\nposterior_1 = Normal(compute_posterior_parameters(obs, mu0, sig0, sig_like)...)\n\n# Inference with more data\npush!(obs, 1.0)\npo2 = compute_posterior_parameters(obs, mu0, sig0, sig_like)\nposterior_2 = Normal(compute_posterior_parameters(obs, mu0, sig0, sig_like)...)\n\njulia_purple = parse(Colorant, RGBA(0.702, 0.322, 0.8))\njulia_brown = parse(Colorant, RGBA(0.8, 0.2, 0.2))\njulia_green = parse(Colorant, RGBA(0.133, 0.541, 0.133))\n\nxs = -3:0.01:5\nlw = 15.0\nplot(xs, pdf.(Ref(prior), xs), color=julia_purple, linewidth=lw, lab=\"prior\", grid=false, legend=false, background_color = RGBA(1, 1, 1, 0))\nplot!(xs, pdf.(Ref(posterior_1), xs), color=julia_brown, linewidth=lw, lab=\"posterior 1\")\nplot!(xs, pdf.(Ref(posterior_2), xs), color=julia_green, linewidth=lw, lab=\"posterior 2\")\nxaxis!(false)\nyaxis!(false)\n\nsavefig(\"turing-logo.svg\")\n", "meta": {"hexsha": "d53885d3af2dcd58f679b5ee05185a6669a3d301", "size": 1388, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/assets/logo-build.jl", "max_stars_repo_name": "srenatus/Turing.jl", "max_stars_repo_head_hexsha": "d746c5c5c99ee32a43c6b5faec4d975e59a5ea76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-15T14:04:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-15T14:04:03.000Z", "max_issues_repo_path": "docs/src/assets/logo-build.jl", "max_issues_repo_name": "srenatus/Turing.jl", "max_issues_repo_head_hexsha": "d746c5c5c99ee32a43c6b5faec4d975e59a5ea76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/src/assets/logo-build.jl", "max_forks_repo_name": "srenatus/Turing.jl", "max_forks_repo_head_hexsha": "d746c5c5c99ee32a43c6b5faec4d975e59a5ea76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-08T11:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-08T11:13:01.000Z", "avg_line_length": 33.0476190476, "max_line_length": 140, "alphanum_fraction": 0.7082132565, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.755554767814013}}
{"text": "# Silverman's rule of thumb for KDE bandwidth selection\nfunction bandwidth(data::Vector, alpha::Float64 = 0.9)\n    # Determine length of data\n    ndata = length(data)\n\n    # Calculate width using variance and IQR\n    var_width = std(data)\n    q25, q75 = quantile(data, [0.25, 0.75])\n    quantile_width = (q75 - q25) / 1.34\n\n    # Deal with edge cases with 0 IQR or variance\n    width = min(var_width, quantile_width)\n    if width == 0.0\n        if var_width == 0.0\n            width = 1.0\n        else\n            width = var_width\n        end\n    end\n\n    # Set bandwidth using Silverman's rule of thumb\n    return alpha * width * ndata^(-0.2)\nend\n\n# Store both grid and density for KDE over the real line\nimmutable UnivariateKDE\n    x::Vector\n    density::Vector\nend\n\n# Algorithm AS 176 for calculating univariate KDE\nfunction kde(data::Vector, npoints::Integer = 512)\n    # Determine length of data\n    ndata = length(data)\n\n    # Set bandwidth\n    window = bandwidth(data)\n\n    # Check that the window is a positive constant\n    if window <= 0.0\n        error(\"Window must be positive\")\n    end\n\n    # Find interval that will contain almost all mass\n    dlo = min(data) - 3 * window\n    dhi = max(data) + 3 * window\n\n    # Check that interval for estimation is valid\n    if dlo >= dhi\n        error(\"Interval must be specified as lower bound, upper bound\")\n    end\n\n    # Set up a grid for discretized data\n    grid = zeros(Float64, npoints)\n\n    # Define some more constants\n    step = (dhi - dlo) / npoints\n    ainc = 1.0 / (ndata * step)\n    npoints2 = fld(npoints, 2)\n    hw = window / step\n    fac1 = 32.0 * (atan(1.0) * hw / npoints)^2\n\n    # Discretize the data using a histogram\n    dlo1 = dlo - step\n    for i in 1:ndata\n        j = fld(data[i] - dlo1, step)\n        if j >= 1 && j <= npoints\n            grid[j] = grid[j] + ainc\n        end\n    end\n\n    # Transform to Fourier basis\n    ft = rfft(grid)\n\n    # Find transform of KDE by convolving grid with the\n    # Fourier transform of a Gaussian kernel\n    for j = 2:length(ft)\n        ft[j] *= exp(-fac1 * (j-1)^2)\n    end\n\n    # Invert the Fourier transform to get the KDE\n    density = irfft(ft, npoints)\n\n    # Fix any noise that crept in\n    for j in 1:npoints\n        if density[j] < 0.0\n            density[j] = 0.0\n        end\n    end\n\n    # Expand the grid over which KDE was calculated\n    x = [dlo:step:(dhi - step)]\n\n    return UnivariateKDE(x, density)\nend\n", "meta": {"hexsha": "b42bc0f7e5b6dc62923d5bf263341582b056a8e3", "size": 2436, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kde.jl", "max_stars_repo_name": "malmaud/Distributions.jl", "max_stars_repo_head_hexsha": "06a268405f49b648665027c85ad75d26100fad47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-16T01:43:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-16T01:43:20.000Z", "max_issues_repo_path": "src/kde.jl", "max_issues_repo_name": "mewo2/Distributions.jl", "max_issues_repo_head_hexsha": "00dd06fb13632b9f0259f036bb861e47b7170a76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kde.jl", "max_forks_repo_name": "mewo2/Distributions.jl", "max_forks_repo_head_hexsha": "00dd06fb13632b9f0259f036bb861e47b7170a76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.375, "max_line_length": 71, "alphanum_fraction": 0.6104269294, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418220680099, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7555547640520287}}
{"text": "\"Algorithms for discovering sparse bases for the symmetry-allowed space of exchange couplings.\"\n\n# ##### Math behind `basis_for_symmetry_allowed_couplings()` #####\n#\n# A crystal spacegroup consists of a set of symmetry operations. Each symop is\n# defined by an orthogonal (rotation or reflection) matrix R and a translation\n# vector T. The symop transforms every atom position `x` to a new one `x′ = Rx +\n# T`, but leaves the crystal as a whole invariant. Consider some bond b=(i,j),\n# defined as an ordered pair of atoms, not necessarily in the same crystal unit\n# cell. Suppose this bond carries an exchange interaction of the form `S_iᵀ J\n# S_j`. After applying a symop defined by (R, T), the bond b=(i,j) maps to a\n# transformed bond b′=(i′,j′). This new bond must carry an exchange interaction\n# of the form `S_{i′}ᵀ J′ S_{j′}`, where J′ is related to J, as we will now\n# show. Besides mapping the atom j to a new position j′, the symop also\n# transforms its spin vector from `S_j` to `S′_{j′} = R S_j`. Similarly, `S_iᵀ`\n# maps to `S′_{i′}ᵀ = S_iᵀ Rᵀ`. The energy along a bond, however, is invariant\n# under the symmetry transformation, so we require `S_iᵀ J S_j = S′_{i′}ᵀ J′\n# S′_{j′}`, or\n#\n#   `S_iᵀ J S_j = S_iᵀ Rᵀ J′ R S_j`.\n#\n# This equation must be valid for arbitrary `S_i` and `S_j`, which implies `J =\n# Rᵀ J′ R`, or equivalently,\n#\n#   J′ = R J Rᵀ\n#\n# because the matrix R is orthogonal. The conclusion is that specifying the\n# exchange matrix J for one bond implicitly constrains the exchange matrices J′\n# for all symmetry equivalent bonds.\n#\n# Often a symmetry operation will map a bond b into itself, or into the same\n# bond but with atom positions reversed. The existence of such symops constrains\n# the space of allowed exchange matrices J for the bond b. Specifically, we\n# require\n#\n#   (1)  J = R J Rᵀ   or   (2)  Jᵀ = R J Rᵀ\n#\n# for every symop `s = (R, T)` that maps `b` into `b` (constraint 1), or into\n# `reverse(b)` (constraint 2). The intersection of all such constraints defines\n# the symmetry-allowed space of exchange matrices J. The allowed matrices can be\n# expressed as a linear combination of basis matrices because all constraints\n# are linear in J.\n#\n# It is convenient to express the constraints (1) or (2) in the form `F J = 0`,\n# where F denotes the linear operator such that `F J = R J Rᵀ - J` or `F J = R J\n# Rᵀ - Jᵀ`. Here, we are viewing the 3×3 matrix J as a flattened 9-dimensional\n# vector, and F as a 9x9 matrix. In the first case, `F = R⊗R - I`. In the second\n# case, we should replace `I` by the suitable transpose operation,\n# `transpose_op_3x3`, defined explicitly below.\n#\n# Any linear combination of \"vectors\" (3x3 matrices) in the null space of F,\n# i.e. `F J = 0`, satisfies the symmetry constraint (1) or (2) for the given\n# symop. The singular value decomposition\n#\n#     F = U Σ Vᵀ\n#\n# can be used to produce an orthogonal basis for this null space. It is spanned\n# by columns v of V corresponding to the zero singular values. The space spanned\n# by v equivalently represented as a projection matrix,\n#\n#     P = v vᵀ\n#\n# When there are multiple constraints (F1, F2, ... Fn) we should take the\n# intersection of the spanned spaces of P1, ... Pn. To calculate this\n# intersection, form the product of the projectors:\n#\n#     P = P1 P2 ... Pn\n#\n# The allowable J values correspond to the eigenvectors of P with eigenvalue 1.\n# An orthogonal basis for this space can again be calculated with an SVD.\n\n\n# A 9x9 matrix that, when applied to a flattened 3x3 matrix (viewed as a\n# 9-dimensional vector), generates the transposed 3x3 matrix in flattened form.\nconst transpose_op_3x3 = SMatrix{9, 9, Float64}([\n    1 0 0  0 0 0  0 0 0\n    0 0 0  1 0 0  0 0 0\n    0 0 0  0 0 0  1 0 0\n\n    0 1 0  0 0 0  0 0 0\n    0 0 0  0 1 0  0 0 0\n    0 0 0  0 0 0  0 1 0\n\n    0 0 1  0 0 0  0 0 0\n    0 0 0  0 0 1  0 0 0\n    0 0 0  0 0 0  0 0 1\n])\n\n\n# Returns a projection operator P that maps to zero any symmetry-unallowed\n# coupling matrix J. The space spanned by the eigenvectors of P with eigenvalue\n# 1 represents the allowed coupling matrices J.\nfunction projector_for_symop(cryst::Crystal, s::SymOp, parity::Bool)\n    # Cartesian-space rotation operator corresponding to `s`\n    R = cryst.lat_vecs * s.R * inv(cryst.lat_vecs)\n\n    # Constraint is modeled as `F J = 0`\n    F = kron(R, R) - (parity ? SMatrix{9, 9, Float64}(I) : transpose_op_3x3)\n\n    # Orthogonal column vectors that span the null space of F\n    v = nullspace(F; atol=1e-12)\n\n    # Projector onto the null space of F\n    P = SMatrix{9, 9, Float64}(v * v')\n    return P\nend\n\n\n# Return an operator P that implicitly gives the space of symmetry allowed\n# coupling matrices for bond b. Specifically, x is an allowed coupling if and\n# only if it is an eigenvector of P with eigenvalue 1, i.e., `P x = x`.\nfunction symmetry_allowed_couplings_operator(cryst::Crystal, b::BondRaw)\n    P = SMatrix{9, 9, Float64}(I)\n    for (s, parity) in symmetries_between_bonds(cryst, b, b)\n        P = P * projector_for_symop(cryst, s, parity)\n    end\n    # Allowed coupling matrices J are simultaneously eigenvectors for all\n    # projectors above, with eigenvalue 1.\n    return P\nend\n\n# Check whether a coupling matrix J is consistent with symmetries of a bond\nfunction is_coupling_valid(cryst::Crystal, b::BondRaw, J::Mat3)\n    for (s, parity) in symmetries_between_bonds(cryst, b, b)\n        R = cryst.lat_vecs * s.R * inv(cryst.lat_vecs)\n        # TODO use symprec to handle case where matrix R is not precise\n        if norm(R*J*R' - (parity ? J : J')) > 1e-12\n            return false\n        end\n    end\n    return true\nend\n\nfunction is_coupling_valid(cryst::Crystal, b::Bond, J::Mat3)\n    return is_coupling_valid(cryst, BondRaw(cryst, b), J)\nend\n\n\n# Orthonormal basis of 3x3 symmetric matrices\nconst sym_basis = begin\n    b = [diagm([1, 0, 0]),\n         diagm([0, 1, 0]),\n         diagm([0, 0, 1]),\n         [0 1 0\n          1 0 0\n          0 0 0]/√2,\n         [0 0 1\n          0 0 0\n          1 0 0]/√2,\n         [0 0 0\n          0 0 1\n          0 1 0]/√2,]\n    SMatrix{9, 6, Float64}(hcat(reshape.(b, 9)...))\nend\n\n# Orthonormal basis of 3x3 antisymmetric matrices\nconst asym_basis = begin\n    b = [[ 0  1  0\n          -1  0  0\n           0  0  0]/√2,\n         [ 0  0 -1\n           0  0  0\n           1  0  0]/√2,\n         [ 0  0  0\n           0  0  1\n           0 -1  0]/√2]\n    SMatrix{9, 3, Float64}(hcat(reshape.(b, 9)...))\nend\n\n@assert sym_basis * sym_basis' + asym_basis * asym_basis' ≈ I\n\n\n# Given an m×n matrix A with empty nullspace, linearly combine the n columns to\n# make them sparser. Solution was proposed here:\n# https://math.stackexchange.com/q/4227648/660903 . Closely related to finding\n# reduced row echolon form.\nfunction sparsify_columns(A; atol)\n    if size(A, 2) <= 1\n        return A\n    else\n        # By assumption, the n columns of A are linearly independent\n        @assert isempty(nullspace(A; atol))\n        # Since row rank equals column rank, it should be possible to find n\n        # linearly independent rows in A. Store these independent rows of A as\n        # column vectors in indep_rows.\n        indep_rows = zeros(Float64, size(A, 2), 0)\n        for row in eachrow(A)\n            # Add `row` to list if linearly independent with existing ones\n            if isempty(nullspace(hcat(indep_rows, row); atol))\n                indep_rows = hcat(indep_rows, row)\n            end\n        end\n        return A * inv(indep_rows)'\n    end\nend\n\n\nconst _basis_elements_by_priority = [1, 5, 9, 8, 3, 4]\n\nfunction _score_basis_matrix(J)\n    return findfirst(i -> abs(J[i]) > 1e-12, _basis_elements_by_priority)\nend\n\n\"\"\"    basis_for_symmetry_allowed_couplings(cryst::Crystal, b::Bond)\n\nReturns a list of ``3×3`` matrices that form a linear basis for the\nsymmetry-allowed coupling matrices associated with bond `b`.\n\"\"\"\nfunction basis_for_symmetry_allowed_couplings(cryst::Crystal, b::BondRaw)\n    # Expected floating point precision for 9x9 matrix operations\n    atol = 1e-12\n\n    P = symmetry_allowed_couplings_operator(cryst, b)\n    # Any solution to the original symmetry constraints `R J Rᵀ = J` or `R J Rᵀ\n    # = Jᵀ` decomposes into purely symmetric/antisymmetric solutions. Therefore\n    # we can pick a basis that separates into symmetric and antisymmetric parts.\n    # We will do so by decomposing P. By construction, P = P_sym+P_asym.\n    P_sym  = P *  sym_basis *  sym_basis'\n    P_asym = P * asym_basis * asym_basis'\n\n    acc_sym = SVector{9, Float64}[]\n    acc_asym = SVector{9, Float64}[]\n\n    # If any \"reference\" basis vectors are eigenvalues of P_sym with eigenvalue\n    # 1, use them as outputs, and remove them from P_sym\n    for x in eachcol(sym_basis)\n        if isapprox(P_sym*x, x; atol)\n            push!(acc_sym, x)\n            P_sym = P_sym * (I - x*x')\n        end\n    end\n    # Same for P_asym\n    for x in eachcol(asym_basis)\n        if isapprox(P_asym*x, x; atol)\n            push!(acc_asym, x)\n            P_asym = P_asym * (I - x*x')\n        end\n    end\n    \n    # Search for eigenvectors of P_sym with eigenvalue 1. These provide an\n    # orthonormal basis for symmetric couplings.\n    v = nullspace(P_sym-I; atol)\n    v = sparsify_columns(v; atol)\n    append!(acc_sym, eachcol(v))\n    # Same for P_asym\n    v = nullspace(P_asym-I; atol)\n    v = sparsify_columns(v; atol)\n    append!(acc_asym, eachcol(v))\n\n    # Sort basis elements according to the indices where the nonzero elements\n    # first appear\n    sort!(acc_sym;  by=_score_basis_matrix)\n    sort!(acc_asym; by=_score_basis_matrix)\n\n    acc = [acc_sym; acc_asym]\n    return map(acc) do x\n        # Normalize each basis vector so that its maximum component is 1. The\n        # shift by atol avoids unnecessary sign change in the case where the\n        # maximum magnitude values of x appear symmetrically as ±c for some c.\n        _, i = findmax(abs.(x.+atol))\n        x = x / x[i]\n\n        # Reinterpret as 3x3 matrix\n        x = Mat3(reshape(x, 3, 3))\n        \n        # Double check that x indeed satifies the necessary symmetries\n        @assert is_coupling_valid(cryst, b, x)\n\n        return x\n    end\nend\n\nfunction basis_for_symmetry_allowed_couplings(cryst::Crystal, b::Bond)\n    return basis_for_symmetry_allowed_couplings(cryst, BondRaw(cryst, b))\nend\n\n\"\"\"\n    all_symmetry_related_couplings_for_atom(cryst::Crystal, i::Int, b::Bond, J)\n\nGiven a reference bond `b` and coupling matrix `J` on that bond, return a list\nof symmetry-equivalent bonds (constrained to start from atom `i`), and a\ncorresponding list of symmetry-transformed coupling matrices.\n\"\"\"\nfunction all_symmetry_related_couplings_for_atom(cryst::Crystal, i::Int, b_ref::Bond, J_ref)\n    J_ref = Mat3(J_ref)\n    @assert is_coupling_valid(cryst, b_ref, J_ref)\n\n    bs = Bond[]\n    Js = Mat3[]\n\n    for b in all_symmetry_related_bonds_for_atom(cryst, i, b_ref)\n        push!(bs, b)\n        (s, parity) = first(symmetries_between_bonds(cryst, BondRaw(cryst, b), BondRaw(cryst, b_ref)))\n        R = cryst.lat_vecs * s.R * inv(cryst.lat_vecs)\n        push!(Js, R * (parity ? J_ref : J_ref') * R')\n    end\n\n    return (bs, Js)\nend\n\n\"\"\"\n    all_symmetry_related_couplings(cryst::Crystal, b::Bond, J)\n\nGiven a reference bond `b` and coupling matrix `J` on that bond, return a list\nof symmetry-equivalent bonds and a corresponding list of symmetry-transformed\ncoupling matrices.\n\"\"\"\nfunction all_symmetry_related_couplings(cryst::Crystal, b_ref::Bond, J_ref)\n    J_ref = Mat3(J_ref)\n\n    bs = Bond[]\n    Js = Mat3[]\n\n    for i in eachindex(cryst.positions)\n        (bs_i, Js_i) = all_symmetry_related_couplings_for_atom(cryst, i, b_ref, J_ref)\n        append!(bs, bs_i)\n        append!(Js, Js_i)\n    end\n\n    return (bs, Js)\nend\n", "meta": {"hexsha": "7e229f74f9d492ecfbe4b5fbb58672d9809b36fe", "size": 11713, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Symmetry/AllowedCouplings.jl", "max_stars_repo_name": "sakibmatin/Sunny.jl", "max_stars_repo_head_hexsha": "d2d25638872b1f1edee60e56382e46859a63e422", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-02-03T20:35:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:06:13.000Z", "max_issues_repo_path": "src/Symmetry/AllowedCouplings.jl", "max_issues_repo_name": "sakibmatin/Sunny.jl", "max_issues_repo_head_hexsha": "d2d25638872b1f1edee60e56382e46859a63e422", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-11-01T17:43:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-01T17:28:34.000Z", "max_forks_repo_path": "src/Symmetry/AllowedCouplings.jl", "max_forks_repo_name": "sakibmatin/Sunny.jl", "max_forks_repo_head_hexsha": "d2d25638872b1f1edee60e56382e46859a63e422", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-02T19:29:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T19:29:43.000Z", "avg_line_length": 36.3757763975, "max_line_length": 102, "alphanum_fraction": 0.6661828737, "num_tokens": 3613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7555547616730183}}
{"text": "function noisy_circle_data(N, σ)\n    r = 1 .+ σ*randn(1,N)\n    θ = rand(Uniform(0, 2π), (1,N))\n\n    rcosθ = r .* cos.(θ)\n    rsinθ = r .* sin.(θ)\n\n    data = [rcosθ; rsinθ]\n\n    return data\nend", "meta": {"hexsha": "09c73295e1eb25c5147e421d5e219720b236466a", "size": 193, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utilities/utils.jl", "max_stars_repo_name": "KNU-MATH-AI/TopologicalDataAnalysis.jl", "max_stars_repo_head_hexsha": "bcc6d282d35f3cc6579d2382afa9ba6e6c25bda1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utilities/utils.jl", "max_issues_repo_name": "KNU-MATH-AI/TopologicalDataAnalysis.jl", "max_issues_repo_head_hexsha": "bcc6d282d35f3cc6579d2382afa9ba6e6c25bda1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-03T19:17:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T19:17:28.000Z", "max_forks_repo_path": "src/utilities/utils.jl", "max_forks_repo_name": "KNU-MATH-AI/TopologicalDataAnalysis.jl", "max_forks_repo_head_hexsha": "bcc6d282d35f3cc6579d2382afa9ba6e6c25bda1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5454545455, "max_line_length": 35, "alphanum_fraction": 0.5233160622, "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404116305639, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7555117408122071}}
{"text": "module llh\n\nusing LinearAlgebra  #: cholesky, logdet, diag, inv, triu\nusing AxUtil\nusing NNlib: softmax\nusing ..Misc\n\nexport gmm_llh, gmm_llh_invLT\n\nfunction log_gauss_llh(X, mu, sigma; bypass=false)\n    if !bypass\n        out = _log_gauss_llh(X, mu, sigma)\n    else\n        out = - ones(size(X, 2))*Inf\n    end\n    return out\nend\n\n\nfunction _log_gauss_llh(X, mu, sigma)\n    d = size(X,1)\n    invLT = Matrix(inv(cholesky(sigma).L))\n    Z = invLT*(X .- mu)\n    exponent = -0.5*sum(Z.^2, dims=1)  |> dropdim1\n    lognormconst = -d*log(2*pi)/2 -0.5*logdet(sigma)  #.-0.5*(-2*sum(log.(diag(invLT))))\n    return exponent .+ lognormconst\nend\n\n\nfunction _log_gauss_llh_invLT(X, mu, invLT)\n    d = size(X,1)\n    Z = invLT*(X .- mu)\n    exponent = -0.5*sum(Z.^2, dims=1)  |> dropdim1\n    lognormconst = -d*log(2*pi)/2 .-0.5*(-2*sum(log.(diag(invLT))))\n    return exponent .+ lognormconst\nend\n\n\nfunction gmm_llh(X, pis, mus, sigmas; thrsh_comp=0.005)\n    p, n = size(X)\n    k = length(pis)\n    inactive_ixs = pis[:] .< thrsh_comp\n\n    P = zeros(k, n)\n    for j = 1:k\n        P[j,:] = log_gauss_llh(X, mus[j,:], sigmas[:,:,j],\n            bypass=inactive_ixs[j]) .+ log(pis[j])\n    end\n    return AxUtil.Math.logsumexpcols(P)\nend\n\nfunction gmm_llh_invLT(X, pis, mus, invLTs::Array{T,1}; disp=false, thrsh_comp=0.005) where T <: AbstractMatrix\n    p, n = size(X)\n    k = length(pis)\n    inactive_ixs = pis[:] .< thrsh_comp\n\n    P = zeros(k, n)\n    for j = 1:k\n        if !inactive_ixs[j]\n            P[j,:] = _log_gauss_llh_invLT(X, mus[j,:], invLTs[j]) .+ log(pis[j])\n        else\n            P[j,:] .= -Inf\n        end\n    end\n    return AxUtil.Math.logsumexpcols(P)\nend\n\n\nfunction responsibilities(X, mus::AbstractArray{T,2}, sigmas::AbstractArray{T, 3}, pis::AbstractArray{T, 1}) where T <: AbstractFloat\n    softmax(reduce(vcat, [log_gauss_llh(X, mus[j,:], sigmas[:,:,j]) .+ log(pis[j]) for j in 1:size(mus, 1)]'))\nend\n\nend\n", "meta": {"hexsha": "d25b61fcfb7cae2315402a0628892f97f553cab4", "size": 1917, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/llh.jl", "max_stars_repo_name": "ornithos/InferGMM.jl", "max_stars_repo_head_hexsha": "dc75ca0f79adae2280dfefe9c99eec31692799ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-09T17:52:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T17:52:49.000Z", "max_issues_repo_path": "src/llh.jl", "max_issues_repo_name": "ornithos/InferGMM.jl", "max_issues_repo_head_hexsha": "dc75ca0f79adae2280dfefe9c99eec31692799ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/llh.jl", "max_forks_repo_name": "ornithos/InferGMM.jl", "max_forks_repo_head_hexsha": "dc75ca0f79adae2280dfefe9c99eec31692799ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9054054054, "max_line_length": 133, "alphanum_fraction": 0.601982264, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671712, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7555117276190862}}
{"text": "export Pow\n\n\"\"\"\n`Pow([domainType=Float64::Type,] dim_in::Tuple)`\n\nElementwise power `p` non-linear operator with input dimensions `dim_in`.\n\n\"\"\"\nstruct Pow{T,N,I<:Real} <: NonLinearOperator\n\tdim::NTuple{N,Int}\n    p::I\nend\n\nfunction Pow(DomainType::Type, DomainDim::NTuple{N,Int}, p::I) where {N, I <: Real} \n\tPow{DomainType, N, I}(DomainDim, p)\nend\n\nPow(DomainDim::NTuple{N,Int}, p::I) where {N, I <: Real} = Pow{Float64,N,I}(DomainDim,p)\n\nfunction mul!(y::AbstractArray{T,N}, L::Pow{T,N,I}, x::AbstractArray{T,N}) where {T,N,I}\n\ty .= x.^L.p\nend\n\nfunction mul!(y::AbstractArray, \n              J::AdjointOperator{Jacobian{Pow{T, N, I},TT}}, \n              b::AbstractArray) where {T, N, I, TT <: AbstractArray{T,N}}\n    L = J.A\n    y .= conj.(L.A.p.*(L.x).^(L.A.p-1)).*b\nend\n\nfun_name(L::Pow) = \"『\"\n\nsize(L::Pow) = (L.dim, L.dim)\n\ndomainType(L::Pow{T,N}) where {T,N} = T\ncodomainType(L::Pow{T,N}) where {T,N} = T\n", "meta": {"hexsha": "ea0575138fa2a729133f697b1859b7091201e25e", "size": 914, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nonlinearoperators/Pow.jl", "max_stars_repo_name": "nantonel/AbstractOperators.jl", "max_stars_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2017-08-28T17:28:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-21T18:53:01.000Z", "max_issues_repo_path": "src/nonlinearoperators/Pow.jl", "max_issues_repo_name": "nantonel/AbstractOperators.jl", "max_issues_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2017-11-17T14:43:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-23T20:02:48.000Z", "max_forks_repo_path": "src/nonlinearoperators/Pow.jl", "max_forks_repo_name": "nantonel/AbstractOperators.jl", "max_forks_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-09-02T08:56:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T18:56:33.000Z", "avg_line_length": 24.7027027027, "max_line_length": 88, "alphanum_fraction": 0.6083150985, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948495, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7555117259957056}}
{"text": "export area\n\n\"\"\"\n    area(polygon::Polygon, radius::Float64=1.0)\n\nReturn the area of the spherical polygon. Without given radius a unit sphere is assumed.\n\nSource: en.wikipedia.org/wiki/Spherical_trigonometry # Area and spherical excess\n\nThe method has been altered to allow for the usage of an internal point given with the Polygon.\nThis method only works with polygons that fit within half a sphere as it uses great circle distances between\nsubsequent points.\n\"\"\"\nfunction area(polygon::Polygon, radius::Float64=1.0)\n    point₁ = polygon.points[1]\n    area_polygon_unit_sphere = 0.0\n    for point₂ in polygon.points[2:end]\n        n_intersectionsᵢ = length(intersection_points(Arc(polygon.inside_point, \n        midpoint(point₁, point₂)), polygon))\n        isodd(n_intersectionsᵢ) ? area_polygon_unit_sphere += \n        area(polygon.inside_point, point₁, point₂) : area_polygon_unit_sphere -= \n        area(polygon.inside_point, point₁, point₂)\n        \n        point₁ = point₂\n    end\n    return area_polygon_unit_sphere * radius^2\nend\n\n\"\"\"\n    area(angular_distance₁₂::Float64, angular_distance₂₃::Float64, angular_distance₁₃::Float64,\n    radius::Float64=1.0)\n\nReturn the area of the spherical triangle 123 based on the angular distances [deg] 12-23-13. Without given\nradius a unit sphere is assumed.\n\nSource: mathworld.wolfram.com/SphericalTriangle.html\n\"\"\"\nfunction area(angular_distance₁₂::Float64, angular_distance₂₃::Float64, angular_distance₁₃::Float64,\n    radius::Float64=1.0)\n    return deg2rad(spherical_excess(angular_distance₁₂, angular_distance₁₃, angular_distance₂₃))*radius^2\nend\n\n\"\"\"\n    area(point₁::Point, point₂::Point, point₃::Point, radius::Float64=1.0)\n\nReturn the area of the spherical triangle 123 based on the points point₁ - point₂ - point₃. Without given radius\na unit sphere is assumed.\n\nSource: mathworld.wolfram.com/SphericalTriangle.html\n\"\"\"\narea(point₁::Point, point₂::Point, point₃::Point, radius::Float64=1.0) = \narea(angular_distance(point₁, point₂), angular_distance(point₂, point₃), angular_distance(point₃, point₁),\nradius)", "meta": {"hexsha": "758cfb73525ceb139bb8feb1180020cc010e91c3", "size": 2066, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/area.jl", "max_stars_repo_name": "rjdverbeek-tud/SphericalGeometry.jl", "max_stars_repo_head_hexsha": "02dc934c51dc8389b08e3dab0831915d5f6c5643", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/area.jl", "max_issues_repo_name": "rjdverbeek-tud/SphericalGeometry.jl", "max_issues_repo_head_hexsha": "02dc934c51dc8389b08e3dab0831915d5f6c5643", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-05-31T00:17:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T20:28:32.000Z", "max_forks_repo_path": "src/area.jl", "max_forks_repo_name": "rjdverbeek-tud/SphericalGeometry.jl", "max_forks_repo_head_hexsha": "02dc934c51dc8389b08e3dab0831915d5f6c5643", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9811320755, "max_line_length": 112, "alphanum_fraction": 0.7575024201, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7555117175687451}}
{"text": "using JuMP, Gurobi, Distributions, StatsFuns\r\n\r\n\r\nconst gurobi_env = Gurobi.Env()\r\n\r\n\r\n# DIMENSIONS\r\nconst numVariables = 100\r\nconst numJCC = 100\r\nconst conRHS = numVariables^2\r\n\r\n\r\n# CASES\r\n# number of samples, replicates for scenario approximations\r\nconst NumSamples = ceil.(Int64,logspace(1,log10(50000.0),50))\r\nconst NumReplicates = 20\r\n\r\n\r\n# FILENAMES\r\nconst objFile = \"objectiveValue.txt\"\r\nconst solnFile = \"solution.txt\"\r\nconst riskFile = \"riskLevel.txt\"\r\nconst riskTimeFile = \"riskTime.txt\"\r\nconst solnTimeFile = \"solutionTime.txt\"\r\nconst checkingTimeFile = \"checkingTime.txt\"\r\nconst sortingTimeFile = \"sortingTime.txt\"\r\nconst callbackFile = \"numCallbacks.txt\"\r\nconst numConstraintsFile = \"numConstraintsEnforced.txt\"\r\n\r\n\r\n\r\nxi_mean = zeros(Float64,numVariables)\r\nxi_covariance = 0.5*ones(Float64,numJCC,numJCC)\r\n\r\nfor j = 1:numVariables\r\n\txi_mean[j] = j*1.0/numVariables\r\nend\r\n\r\nfor i = 1:numJCC\r\n\txi_covariance[i,i] = 1.0\r\nend\r\n\r\nxi_cov_chol_tmp = cholfact(xi_covariance)\r\nxi_cov_chol = xi_cov_chol_tmp[:L]\r\n\r\nxi_mean_mat = zeros(Float64,numJCC,numVariables)\r\nfor j = 1:numVariables\r\n\txi_mean_mat[:,j] = xi_mean[j]*ones(numJCC)\r\nend\r\n\r\n\r\n# tailored implementation of multivariate normal distribution\r\nfunction myMvNormal(numSamples::Int64)\r\n\r\n\txi = zeros(Float64,numJCC,numVariables,numSamples)\r\n\t\r\n\txi_tmp = rand(Normal(0.0,1.0),numJCC,numVariables,numSamples)\r\n\tfor samp = 1:numSamples\r\n\t\txi[:,:,samp] = xi_cov_chol*xi_tmp[:,:,samp] + xi_mean_mat\r\n\tend\r\n\t\r\n\treturn xi\r\nend\r\n\r\n\r\n# generate random samples from multivariate normal distribution\r\nfunction generateRandomSamples(numSamples::Int64)\r\n\r\n\txi = myMvNormal(numSamples)\r\n\t\r\n\treturn xi\r\nend\r\n\r\n\r\n\r\nsrand(1234)\r\n\r\n# generate samples to estimate actual risk level of solution\r\nconst numAnalyticalSamples = 20000\r\nconst xi_analytical = generateRandomSamples(numAnalyticalSamples)\r\n\r\nsrand()\r\n\r\n\r\n# compute negative probability of all constraints being satisfied\r\n# for given scenarios of demands d and a given decision vector x\r\nfunction computeRiskLevel(x::Array{Float64},reliabilityLevel::Float64=1E-06)\r\n\r\n\tconst numSamples = size(xi_analytical,3)\r\n\tsimpleEst::Bool = false\r\n\r\n\tnumViolated::Int64 = checkScenarioConstraints(x,xi_analytical)\r\n\t\r\n\triskLevel::Float64 = Inf\r\n\t\r\n\tif(simpleEst)\r\n\t\triskLevel = numViolated*1.0/numSamples\r\n\t\treturn riskLevel\r\n\telse\r\n\t\tif(numViolated == 0)\r\n\t\t\triskLevel = -log(reliabilityLevel)/numSamples\r\n\t\t\treturn riskLevel\r\n\t\tend\r\n\t\r\n\t\t # termination criterion for bisection\r\n\t\tgamma_tolerance::Float64 = 0.1/numSamples\r\n\t\t\r\n\t\t# use tail bounds on binomial distribution to estimate lower and upper bounds\r\n\t\tgamma_low::Float64 = (numViolated - sqrt(-numSamples*log(reliabilityLevel)/2.0))/numSamples\r\n\t\tif(gamma_low < 0.0)\r\n\t\t\tgamma_low = 0.0\r\n\t\tend\r\n\t\tgamma_up::Float64 = (numViolated + sqrt(-numSamples*log(reliabilityLevel)/2.0))/numSamples\r\n\t\tif(gamma_up > 1.0)\r\n\t\t\tgamma_up = 1.0\r\n\t\tend\r\n\t\t\r\n\t\tgamma::Float64 = 0.0\r\n\t\tfunc_value::Float64 = 0.0\r\n\r\n\t\t# use bisection to solve the nonlinear equation\r\n\t\twhile (gamma_up - gamma_low > gamma_tolerance)\r\n\r\n\t\t\tgamma = (gamma_low + gamma_up)/2.0\r\n\t\t\tfunc_value = -reliabilityLevel\r\n\t\t\tfor i = 1:numViolated\r\n\t\t\t\ttmp_func = i*log(gamma) + (numSamples-i)*log(1-gamma) + lfact(numSamples) - lfact(numSamples-i) - lfact(i)\r\n\t\t\t\tfunc_value += exp(tmp_func)\r\n\t\t\t\tif(func_value > 0)\r\n\t\t\t\t\tbreak\r\n\t\t\t\tend\r\n\t\t\tend\r\n\t\t\tif(func_value > 0)\r\n\t\t\t\tgamma_low = (gamma_low + gamma_up)/2.0\r\n\t\t\telse\r\n\t\t\t\tgamma_up = (gamma_low + gamma_up)/2.0\r\n\t\t\tend\r\n\r\n\t\tend\r\n\t\t\r\n\t\triskLevel = gamma_up\r\n\t\treturn riskLevel\r\n\tend\r\n\r\nend\r\n\r\n\r\n# determines if all constraints are satisfied for a given single scenario\r\n# returns one if scenario constraints are all satisfied, zero otherwise\r\nfunction checkScenarioConstraints(x::Array{Float64},xi::Array{Float64})\r\n\r\n\tnumSamples::Int64 = size(xi,3)\r\n\r\n\tnumViolated::Int64 = 0\r\n\tfor iter = 1:numSamples\t\t\t\r\n\t\tfor i = 1:numJCC\r\n\t\t\tcon::Float64 = evaluateConstraint(i,x,xi[i,:,iter])\r\n\t\t\tif(con > 0)\r\n\t\t\t\tnumViolated += 1\r\n\t\t\t\tbreak\r\n\t\t\tend\r\n\t\tend\t\r\n\tend\r\n\r\n\treturn numViolated\r\nend\r\n\r\n\r\n# evaluate the constraint values for given decision vector x,\r\n# realization of the random variables xi, and constraint scalings\r\nfunction evaluateConstraint(index::Int64,x::Array{Float64},xi::Array{Float64})\r\n\r\n\tcon::Float64 = norm(xi.*x)^2 - conRHS\r\n\r\n\treturn con\r\nend\r\n\r\n\r\n# determines if all constraints are satisfied for a given single scenario\r\n# returns one if scenario constraints are all satisfied, zero otherwise\r\nfunction getScenarioConstraintViolations(x::Array{Float64},xi::SubArray{Float64,2,Array{Float64,3},Tuple{Int64,Base.Slice{Base.OneTo{Int64}},Base.Slice{Base.OneTo{Int64}}},true},pickFirstSetOfConstraints::Bool,maxNumConstraintsPerIteration::Int64)\r\n\r\n\tconst numSamples = size(xi,2)\r\n\tnumViolated::Int64 = 0\r\n\tconstraintViolations = Float64[]\r\n\tconstraintViolationIndices = Int64[]\r\n\tconstraintViolationTolerance::Float64 = 1E-06\r\n\r\n\tfor iter = 1:numSamples\r\n\t\t@views con::Float64 = norm(xi[:,iter].*x) - sqrt(conRHS)\r\n\r\n\t\tif(con >= constraintViolationTolerance)\r\n\t\t\tnumViolated += 1\r\n\t\t\tpush!(constraintViolations,con)\r\n\t\t\tpush!(constraintViolationIndices,iter)\r\n\t\t\tif(pickFirstSetOfConstraints && numViolated == maxNumConstraintsPerIteration)\r\n\t\t\t\tbreak\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\n\t\r\n\treturn numViolated, constraintViolations, constraintViolationIndices\r\nend\r\n\r\n\r\n# write solution to file\r\nfunction initializeFiles(details_file::String)\r\n\r\n\twriteMode::String = \"w\"\r\n\t\r\n\topen(details_file, writeMode) do f\r\n\t\twrite(f,\"Model: $modelName \\n\")\r\n\t\twrite(f,\"numVariables: $numVariables \\n\")\r\n\t\twrite(f,\"numJCC: $numJCC \\n\")\r\n\t\twrite(f,\"conRHS: $conRHS \\n\")\r\n\t\twrite(f,\"NumSamples: $NumSamples \\n\")\r\n\t\twrite(f,\"NumReplicates: $NumReplicates \\n\")\r\n\t\twrite(f,\"Method: Scenario approximations \\n\")\r\n\tend\r\n\r\nend\r\n\r\n\r\n# write solution to file\r\nfunction writeSolutionToFile(dirName::String, status::Symbol, objvar_opt::Float64, x_opt::Array{Float64}, riskLevel::Float64, solutionTime::Float64, checkingTime::Float64, sortingTime::Float64, numCallbacks::Int64, numConstraintsAdded::Int64, riskTime::Float64)\r\n\r\n\tif(status == Symbol(\"Optimal\"))\r\n\t\twriteMode::String = \"a\"\r\n\t\t\r\n\t\tobj_file::String = dirName * objFile\r\n\t\topen(obj_file, writeMode) do f\r\n\t\t\twrite(f,\"$objvar_opt \\n\")\r\n\t\tend\r\n\t\r\n\t\tsolution_file::String = dirName * solnFile\r\n\t\topen(solution_file, writeMode) do f\r\n\t\t\tfor i = 1:numVariables\r\n\t\t\t\twrite(f,\"$(x_opt[i]) \")\r\n\t\t\tend\r\n\t\t\twrite(f,\"\\n\")\r\n\t\tend\r\n\t\r\n\t\trisk_file::String = dirName * riskFile\r\n\t\topen(risk_file, writeMode) do f\r\n\t\t\twrite(f,\"$riskLevel \\n\")\r\n\t\tend\r\n\t\r\n\t\trisktime_file::String = dirName * riskTimeFile\r\n\t\topen(risktime_file, writeMode) do f\r\n\t\t\twrite(f,\"$riskTime \\n\")\r\n\t\tend\r\n\t\t\r\n\t\tsolntime_file::String = dirName * solnTimeFile\r\n\t\topen(solntime_file, writeMode) do f\r\n\t\t\twrite(f,\"$solutionTime \\n\")\r\n\t\tend\r\n\t\t\r\n\t\tchecktime_file::String = dirName * checkingTimeFile\r\n\t\topen(checktime_file, writeMode) do f\r\n\t\t\twrite(f,\"$checkingTime \\n\")\r\n\t\tend\r\n\t\t\r\n\t\tsorttime_file::String = dirName * sortingTimeFile\r\n\t\topen(sorttime_file, writeMode) do f\r\n\t\t\twrite(f,\"$sortingTime \\n\")\r\n\t\tend\r\n\t\t\r\n\t\tcallback_file::String = dirName * callbackFile\r\n\t\topen(callback_file, writeMode) do f\r\n\t\t\twrite(f,\"$numCallbacks \\n\")\r\n\t\tend\r\n\t\t\r\n\t\tconstraints_file::String = dirName * numConstraintsFile\r\n\t\topen(constraints_file, writeMode) do f\r\n\t\t\twrite(f,\"$numConstraintsAdded \\n\")\r\n\t\tend\r\n\tend\r\n\r\nend\r\n\r\n\r\n# solve the scenario approximation model\r\nfunction solveScenarioApproximationModel(numScenarios::Int64,dirName::String)\r\n\r\n\ttic()\r\n\r\n\t# sample the random variables\r\n\txi = generateRandomSamples(numScenarios)\r\n\t\r\n\tmaxNumConstraintsPerIteration::Int64 = 10\r\n\tnumConstraintsAdded::Int64 = 0\r\n\t\r\n\tpickFirstSetOfConstraints::Bool = false\r\n\t\r\n\tsortingTime::Float64 = 0.0\r\n\tcheckingTime::Float64 = 0.0\r\n\tnumCallbacks::Int64 = 0\r\n\r\n\t\r\n\tobjvar_opt::Float64 = Inf\r\n\ty_opt = zeros(Float64,numVariables)\r\n\tstatus::Symbol = Symbol(\"Error\")\r\n\t\r\n\t\r\n\tnumViolations::Int64 = numScenarios\r\n\t\r\n\tconstraintIndices = [Int64[] for i=1:numJCC]\r\n\t\r\n\t\r\n\twhile(numViolations > 0)\r\n\r\n\t\tnumCallbacks += 1\r\n\t\tnumViolations = 0\r\n\t\t\r\n\t\tnumConstraintsConsidered = zeros(Int64,numJCC)\r\n\t\tfor i = 1:numJCC\r\n\t\t\tnumConstraintsConsidered[i] = size(constraintIndices[i])[1]\r\n\t\tend\r\n\t\t\r\n\t\t\r\n\t\tmod = Model(solver=GurobiSolver(gurobi_env,Presolve=0,OutputFlag=0))\r\n\r\n\t\t@variable(mod, objvar)\r\n\t\t@variable(mod, 0 <= y[1:numVariables] <= 10^6)\r\n\r\n\t\t@objective(mod, Min, objvar)\r\n\t\t@constraint(mod, -sum(y[j] for j = 1:numVariables) <= objvar)\r\n\t\t@constraint(mod, [i=1:numJCC, scen=1:numConstraintsConsidered[i]], norm(xi[i,:,constraintIndices[i][scen]].*y) <= sqrt(conRHS))\r\n\t\r\n\t\tstatus = solve(mod)\r\n\t\tobjvar_opt = getvalue(objvar)\r\n\t\ty_opt = getvalue(y)\r\n\t\t\r\n\t\t\r\n\t\tfor i = 1:numJCC\r\n\r\n\t\t\tnumViolatedConstraints::Int64 = 0\r\n\t\t\tconstraintViolations = Float64[]\r\n\t\t\tconstraintViolationIndices = Int64[]\r\n\r\n\t\t\ttic()\r\n\t\t\t\r\n\t\t\t@views numViolatedConstraints, constraintViolations, constraintViolationIndices = getScenarioConstraintViolations(y_opt,xi[i,:,:],pickFirstSetOfConstraints,maxNumConstraintsPerIteration)\r\n\t\t\t\r\n\t\t\tcheckingTime += toq()\r\n\t\t\r\n\t\t\tnumConstraintsEnforced::Int64 = min(size(constraintViolations,1),maxNumConstraintsPerIteration)\r\n\t\t\t\r\n\t\t\ttic()\r\n\t\t\trelevantIndices = 1:1:numConstraintsEnforced\r\n\t\t\tif(!pickFirstSetOfConstraints)\r\n\t\t\t\trelevantIndices = sortperm(constraintViolations, rev=true)\r\n\t\t\tend\r\n\t\t\tsortingTime += toq()\r\n\t\t\t\r\n\t\t\tfor iter = 1:numConstraintsEnforced\r\n\t\t\t\tpush!(constraintIndices[i],constraintViolationIndices[relevantIndices[iter]])\r\n\t\t\tend\r\n\t\t\t\r\n\t\t\tnumConstraintsAdded += numConstraintsEnforced\r\n\t\t\t\r\n\t\t\tnumViolations += numViolatedConstraints\r\n\t\tend\r\n\r\n\tend\r\n\t\r\n\ttic()\r\n\r\n\triskLevel::Float64 = computeRiskLevel(y_opt)\r\n\t\r\n\triskTime = toq()\r\n\r\n\tsolutionTime::Float64 = toq()\r\n\t\t\r\n\t@printf \"  Objective: %2.5f,  Risklevel: %.6f,  Time: %4.2f,  NumCallbacks: %d,  NumConstraints: %d \\n\" objvar_opt riskLevel solutionTime numCallbacks numConstraintsAdded\r\n\t\r\n\twriteSolutionToFile(dirName, status, objvar_opt, y_opt, riskLevel, solutionTime, checkingTime, sortingTime, numCallbacks, numConstraintsAdded, riskTime)\r\n\t\r\n\treturn status, objvar_opt, y_opt, riskLevel, solutionTime, checkingTime, sortingTime, numCallbacks, numConstraintsAdded, riskTime\r\nend\r\n", "meta": {"hexsha": "2364458e865b16d5f0a7a55d6681d19d2314db03", "size": 10203, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Scenario approximation/normopt_noniid/normopt_noniid_scenmodel_template.jl", "max_stars_repo_name": "rohitkannan/SA-for-CCP", "max_stars_repo_head_hexsha": "8bb62c8e095eb6a825807c016617d1999c744d24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-12-22T08:52:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T07:23:15.000Z", "max_issues_repo_path": "Scenario approximation/normopt_noniid/normopt_noniid_scenmodel_template.jl", "max_issues_repo_name": "rohitkannan/SA-for-CCP", "max_issues_repo_head_hexsha": "8bb62c8e095eb6a825807c016617d1999c744d24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scenario approximation/normopt_noniid/normopt_noniid_scenmodel_template.jl", "max_forks_repo_name": "rohitkannan/SA-for-CCP", "max_forks_repo_head_hexsha": "8bb62c8e095eb6a825807c016617d1999c744d24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-21T23:45:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-25T17:29:29.000Z", "avg_line_length": 26.7795275591, "max_line_length": 262, "alphanum_fraction": 0.7115554249, "num_tokens": 2888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037782, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7555117165327053}}
{"text": "function eigmaxreal(A::Matrix)\n  if size(A,1)<= 2\n    return maximum(real(eigvals(A)))\n  else\n    return eigs(A,nev=1,which = :LR)[1][1]\n  end\nend\nfunction eigminreal(A::Matrix)\n  if size(A,1)<= 2\n    return minimum(real(eigvals(A)))\n  else\n    return eigs(A,nev=1,which = :SR)[1][1]\n  end\nend\n", "meta": {"hexsha": "4b9931c56e4f3dd926c86cdac9b1dd5d3577ebb8", "size": 294, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "gajomi/LoktaVolterra.jl", "max_stars_repo_head_hexsha": "d5f4652bd386cda203919eccf9a1be04a45fe58f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "gajomi/LoktaVolterra.jl", "max_issues_repo_head_hexsha": "d5f4652bd386cda203919eccf9a1be04a45fe58f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-10-14T00:51:51.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-15T01:04:12.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "gajomi/LoktaVolterra.jl", "max_forks_repo_head_hexsha": "d5f4652bd386cda203919eccf9a1be04a45fe58f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6, "max_line_length": 42, "alphanum_fraction": 0.6326530612, "num_tokens": 108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741281688026, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7554922146530012}}
{"text": "# This file calculates the first application in Y.-S. Chan, A. C. Fannjiang, and G. H. Paulino,\n# Integral equations with hypersingular kernels -- theory and applications to fracture mechanics,\n# Int. J. Eng. Sci., 41:683--720, 2003.\n\nusing ApproxFun, SingularIntegralEquations\n\n\nx = Fun(identity)\nw = 1/sqrt(1-x^2)\nd = domain(x)\nd2 = d^2\nB = dirichlet(d)\nH2 = Hilbert(d,2)\nΣ = DefiniteIntegral(d)\nϵ = 2.0\nK = LowRankFun((x,y)->-1./(x+y+2ϵ).^2+12(x+ϵ)./(x+y+2ϵ).^3-12(x+ϵ).^2./(x+y+2ϵ).^4,d2)\nL = H2[w] + Σ[K*(w/π)]\nf = -Fun(one)\n\nuSIE = [B;L]\\[zeros(2);f]\n@time uSIE = [B;L]\\[zeros(2);f]\nprintln(\"The rank of K is: \",rank(K))\nprintln(\"The length of uSIE is: \",length(uSIE))\nprintln(\"The extrema of uSIE are: \",extrema(uSIE))\nprintln(\"The normalized Stress Intensify Factors are: \",(uSIE/(1-x^2))(-1),\"  \",(uSIE/(1-x^2))(1))\n", "meta": {"hexsha": "29017bb90ee747f2239b592f862e21c1886fb866", "size": 825, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Fracture_a.jl", "max_stars_repo_name": "JuliaPackageMirrors/SingularIntegralEquations.jl", "max_stars_repo_head_hexsha": "eb9e03d887d4450211f73df3569d27d3fa2e8942", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Fracture_a.jl", "max_issues_repo_name": "JuliaPackageMirrors/SingularIntegralEquations.jl", "max_issues_repo_head_hexsha": "eb9e03d887d4450211f73df3569d27d3fa2e8942", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Fracture_a.jl", "max_forks_repo_name": "JuliaPackageMirrors/SingularIntegralEquations.jl", "max_forks_repo_head_hexsha": "eb9e03d887d4450211f73df3569d27d3fa2e8942", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7307692308, "max_line_length": 98, "alphanum_fraction": 0.6387878788, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741214369554, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.755492209313933}}
{"text": "abstract AbstractMeasure{T}\n\nabstract SymmetricMeasure{T} <: AbstractMeasure{T}\n\n# Entropy\n# =======\n\n\"\"\"\nShannon entropy (H)\n\"\"\"\nimmutable Entropy{T} <: SymmetricMeasure{T}\n  base::T\nend\n\ncall{T}(::Type{Entropy{T}}) = Entropy(T(Base.e))\n\n## Estimate Entropy using ResidueProbability\n\n\"\"\"\n`estimate(Entropy(base), p)`\n\n`p` should be a `ResidueProbability` table. The result type is determined by `base`.\n\"\"\"\nfunction estimate{B, T, N, UseGap}(measure::Entropy{B}, p::ResidueProbability{T, N, UseGap})\n  H = zero(B)\n  for i in 1:length(p)\n    @inbounds pi = B(p[i])\n    if pi != 0.0\n      H += pi * log(pi)\n    end\n  end\n  -H/log(measure.base)\nend\n\n\"\"\"\n`estimate_on_marginal(Entropy{T}(base), p, marginal)`\n\nThis function estimate the entropy H(X) if marginal is 1, H(Y) for 2, etc.\nThe result type is determined by `base`.\n\"\"\"\nfunction estimate_on_marginal{B, T, N, UseGap}(measure::Entropy{B}, p::ResidueProbability{T, N, UseGap}, marginal::Int)\n  H = zero(B)\n  for i in 1:nresidues(p)\n    @inbounds pi = B(p.marginals[i, marginal])\n    if pi != 0.0\n      H += pi * log(pi)\n    end\n  end\n  -H/log(measure.base)\nend\n\n## Estimate Entropy using ResidueCount\n\n\"\"\"\n`estimate(Entropy{T}(base), n::ResidueCount)`\n\nIt's the fastest option (you don't spend time on probability calculations).\nThe result type is determined by the `base`.\n\"\"\"\nfunction estimate{T}(measure::Entropy{T}, n::ResidueCount)\n  H = zero(T)\n  total = T(n.total)\n  for i in 1:length(n)\n    @inbounds ni = T(n[i])\n    if ni != 0.0\n      H += ni * log(ni/total)\n    end\n  end\n  (-H/total)/log(measure.base)\nend\n\nfunction estimate_on_marginal{T}(measure::Entropy{T}, n::ResidueCount, marginal::Int)\n  H = zero(T)\n  total = T(n.total)\n  for i in 1:nresidues(n)\n    @inbounds ni = T(n.marginals[i, marginal])\n    if ni != 0.0\n      H += ni * log(ni/total)\n    end\n  end\n  (-H/total)/log(measure.base)\nend\n\n# Kullback-Leibler\n# ================\n\n\"\"\"\nKullback-Leibler (KL). This `SymmetricMeasure` has two fields.\nThe first is the base of the logarithm and the second is the backgroud frequency.\n\"\"\"\nimmutable KullbackLeibler{T} <: SymmetricMeasure{T}\n  base::T\n  background::AbstractArray{T}\nend\n\ncall{T}(::Type{KullbackLeibler{T}}, background::AbstractArray{T}) = KullbackLeibler(T(Base.e), background)\n\n\"\"\"\n`estimate(KullbackLeibler(base, background), p)`\n\n`p` should be a `ResidueProbability` table, and `background` must have the size of `p`.\nThe result type is determined by `base` and `background`.\n\"\"\"\nfunction estimate{B, T, N, UseGap}(measure::KullbackLeibler{B}, p::ResidueProbability{T, N, UseGap})\n  q = measure.background\n  if size(q) != size(p) || length(q) != length(p)\n    throw(ErrorException(\"p and background should have the same size and length.\"))\n  end\n  KL = zero(B)\n  @inbounds for i in 1:length(p)\n    pi = B(p[i])\n    if pi != 0.0\n      KL += pi * log(pi/q[i])\n    end\n  end\n  KL/log(measure.base)\nend\n\n# Mutual Information\n# ==================\n\n\"\"\"\nMutual Information (MI)\n\"\"\"\nimmutable MutualInformation{T} <: SymmetricMeasure{T}\n  base::T\nend\n\ncall{T}(::Type{MutualInformation{T}}) = MutualInformation(T(Base.e))\n\n@inline _mi{T}(::Type{T}, pij, pi, pj) = ifelse(pij > zero(T) && pi > zero(T), T(pij * log(pij/(pi*pj))), zero(T))\n\n\"\"\"\n`estimate(MutualInformation(), pxy::ResidueProbability [, base])`\n\nCalculate Mutual Information from `ResidueProbability`. The result type is determined by `base`.\n\"\"\"\nfunction estimate{B, T, UseGap}(measure::MutualInformation{B}, pxy::ResidueProbability{T, 2,UseGap})\n  MI = zero(B)\n  marginals = pxy.marginals\n  @inbounds for j in 1:nresidues(pxy)\n    pj = marginals[j,2]\n    if pj > 0.0\n      @inbounds @simd for i in 1:nresidues(pxy)\n        MI +=  _mi(B, pxy[i,j], marginals[i,1], pj)\n      end\n    end\n  end\n  MI/log(measure.base)\nend\n\n@inline _mi{T}(N::T, nij, ni, nj) = ifelse(nij > zero(T) && ni > zero(T), T(nij * log((N * nij)/(ni * nj))), zero(T))\n\n\"\"\"\n`estimate(MutualInformation(), pxy::ResidueCount [, base])`\n\nCalculate Mutual Information from `ResidueCount`. The result type is determined by the `base`.\nIt's the fastest option (you don't spend time on probability calculations).\n\"\"\"\nfunction estimate{B, T, UseGap}(measure::MutualInformation{B}, nxy::ResidueCount{T, 2,UseGap})\n  MI = zero(B)\n  N = B(nxy.total)\n  marginals = nxy.marginals\n  @inbounds for j in 1:nresidues(nxy)\n    nj = marginals[j,2]\n    if nj > 0.0\n      @inbounds @simd for i in 1:nresidues(nxy)\n        MI += _mi(N, nxy[i,j], marginals[i,1], nj)\n      end\n    end\n  end\n  (MI/N)/log(measure.base)\nend\n\nfunction estimate{B, T, UseGap}(measure::MutualInformation{B}, pxyz::ResidueContingencyTables{T, 3, UseGap})\n  pxy = delete_dimensions(pxyz,3)\n  return( estimate_on_marginal(Entropy(measure.base), pxyz, 1) + # H(X)\n  estimate_on_marginal(Entropy(measure.base), pxyz ,2) + # H(Y)\n  estimate_on_marginal(Entropy(measure.base), pxyz, 3) - # H(Z)\n  estimate(Entropy(measure.base), pxy) - # H(X, Y)\n  estimate(Entropy(measure.base), delete_dimensions!(pxy, pxyz, 2)) - # H(X, Z)\n  estimate(Entropy(measure.base), delete_dimensions!(pxy, pxyz, 1)) + # H(Y, Z)\n  estimate(Entropy(measure.base), pxyz) ) # H(X, Y, Z)\nend\n\n# Normalized Mutual Information by Entropy\n# ========================================\n\n\"\"\"\nNormalized Mutual Information (nMI) by Entropy.\n\n`nMI(X, Y) = MI(X, Y) / H(X, Y)`\n\"\"\"\nimmutable MutualInformationOverEntropy{T} <: SymmetricMeasure{T}\n  base::T\nend\n\ncall{T}(::Type{MutualInformationOverEntropy{T}}) = MutualInformationOverEntropy(T(Base.e))\n\nfunction estimate{B}(measure::MutualInformationOverEntropy{B}, table)\n  H = estimate(Entropy(measure.base), table)\n  if H != zero(B)\n    MI = estimate(MutualInformation(measure.base), table)\n    return(MI/H)\n  else\n    return(zero(B))\n  end\nend\n\n# Pairwise Gap Percentage\n# =======================\n\n\"\"\"\n`GapUnionPercentage`\n\"\"\"\nimmutable GapUnionPercentage{T} <: SymmetricMeasure{T} end\n\n\"\"\"\n`GapIntersectionPercentage`\n\"\"\"\nimmutable GapIntersectionPercentage{T} <: SymmetricMeasure{T} end\n\nfunction estimate{B, T}(measure::GapIntersectionPercentage{B}, nxy::ResidueCount{T, 2, true})\n  B(100.0) * B(nxy[21, 21]) / B(sum(nxy))\nend\n\nfunction estimate{B, T}(measure::GapUnionPercentage{B}, nxy::ResidueCount{T, 2, true})\n  B(100.0) * B(nxy.marginals[21, 1] + nxy.marginals[21, 2] - nxy[21, 21]) / B(sum(nxy))\nend\n", "meta": {"hexsha": "f75e2e6d5759ba8f43a8a80c1d181dcb3705bce8", "size": 6286, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Information/InformationMeasures.jl", "max_stars_repo_name": "JuliaPackageMirrors/MIToS.jl", "max_stars_repo_head_hexsha": "e3bedd8ec526a100bc9fa8a2931a59d4885cf0c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Information/InformationMeasures.jl", "max_issues_repo_name": "JuliaPackageMirrors/MIToS.jl", "max_issues_repo_head_hexsha": "e3bedd8ec526a100bc9fa8a2931a59d4885cf0c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Information/InformationMeasures.jl", "max_forks_repo_name": "JuliaPackageMirrors/MIToS.jl", "max_forks_repo_head_hexsha": "e3bedd8ec526a100bc9fa8a2931a59d4885cf0c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3304347826, "max_line_length": 119, "alphanum_fraction": 0.658606427, "num_tokens": 1972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615412, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.7554922028137073}}
{"text": "Base.:+(p::Pol) = p\nBase.:-(p::Pol) = Pol([-c for c in p.coeffs])\n\n\nfunction Base.:+(p1::Pol, p2::Pol)\n    maxdeg = max(deg(p1), deg(p2))\n    coeffs = [p1[i]+p2[i] for i in 1:maxdeg+1]\n    return Pol(coeffs)\nend\n\nBase.:+(p1::Union{Pol, Number}, p2::Union{Pol, Number}) = +(promote(p1, p2)...)\nBase.:-(p1::Union{Pol, Number}, p2::Union{Pol, Number}) = p1 + (-p2)\n\nfunction Base.:*(p1::Pol{T}, p2::Pol{T}) where {T<:Number}\n    coeffs = zeros(T, deg(p1)+deg(p2)+1)\n    @inbounds for (i, c1) in enumerate(p1.coeffs)\n        @inbounds for (j, c2) in enumerate(p2.coeffs)\n            coeffs[i+j-1] += c1*c2\n        end\n    end\n    return Pol(coeffs)\nend\n\nBase.:*(p1::Union{Pol, Number}, p2::Union{Pol, Number}) = *(promote(p1, p2)...)\n\nBase.:/(p::Pol, n::Number)  = Pol([c/n for c in p.coeffs])\n\nfunction Base.:^(p::Pol, n::Integer)\n    iszero(n) && return Pol([1])\n    if iseven(n)\n        return (p*p)^(n÷2)\n    else\n        return p*(p*p)^((n-1)÷2)\n    end\nend\n\nfunction Base.divrem(a::Pol, b::Pol)\n    r = a\n    q = zero(a)\n    d = deg(b)\n    c = lc(b)\n    while !iszero(r) && deg(r) >= d\n        s = lc(r)/c\n        coeffs = zeros(typeof(s), deg(r)-d+1)\n        coeffs[end] = s\n        s = Pol(coeffs)\n        q, r = q + s, r - s*b\n    end\n    return q, r\nend\n\nfunction Base.div(a::Pol, b::Pol)\n    q, _ = divrem(a, b)\n    return q\nend\n\nfunction Base.rem(a::Pol, b::Pol)\n    _, r = divrem(a, b)\n    return r\nend\n\nfunction Base.gcd(a::Pol, b::Pol)\n    r0 = a\n    r1 = b\n    while !iszero(r1)\n        r1, r0 = rem(r0, r1), r1\n    end\n    return r0/lc(r0)\nend\n\n# comparisons\n\nfunction Base.:(==)(p1::Pol, p2::Pol)\n    deg(p1) == deg(p2) || return false\n    @inbounds for i in 1:length(p1.coeffs)\n        p1.coeffs[i] == p2.coeffs[i] || return false\n    end\n    return true\nend\n\nfor op in (:>, :<, :>=, :<=)\n    @eval Base.$op(p1::Pol, p2::Pol) = $op(deg(p1), deg(p2))\nend\n\nBase.iszero(p::Pol) = iszero(p.coeffs)\n", "meta": {"hexsha": "bb2a3dd1334303b764e1391f7ef7a438106a5987", "size": 1909, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polynomials/arithmetic.jl", "max_stars_repo_name": "lucaferranti/MatrixPolynomials.jl", "max_stars_repo_head_hexsha": "909ce44f5dc339157ac563769f7ebf089084646f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polynomials/arithmetic.jl", "max_issues_repo_name": "lucaferranti/MatrixPolynomials.jl", "max_issues_repo_head_hexsha": "909ce44f5dc339157ac563769f7ebf089084646f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polynomials/arithmetic.jl", "max_forks_repo_name": "lucaferranti/MatrixPolynomials.jl", "max_forks_repo_head_hexsha": "909ce44f5dc339157ac563769f7ebf089084646f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-31T23:31:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T23:31:12.000Z", "avg_line_length": 22.1976744186, "max_line_length": 79, "alphanum_fraction": 0.5322158198, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7554667651449793}}
{"text": "using Unitful#, UnitfulPlots\nusing OrdinaryDiffEq, DiffEqBase\n\nconst UNITS_TEST_ALGS = [Euler(),Midpoint(),RK4(),SSPRK104(),SSPRK22(),SSPRK33(),\n    SSPRK432(),BS3(),BS5(),DP5(),DP5Threaded(),DP8(),Feagin10(),Feagin12(),Feagin14(),\n    TanYam7(),Tsit5(),TsitPap8(),Vern6(),Vern7(),Vern8(),Vern9()]\n\nf = (y,p,t) -> 0.5*y / 3.0u\"s\"\nu0 = 1.0u\"N\"\nprob = ODEProblem(f,u0,(0.0u\"s\",1.0u\"s\"))\n\nsol =solve(prob,ExplicitRK())\n\nfor alg in UNITS_TEST_ALGS\n  if !(typeof(alg) <: DP5Threaded)\n    @show alg\n    sol = solve(prob,alg,dt=1u\"s\"/10)\n  end\nend\n\nprintln(\"Units for Number pass\")\n\nu0 = [1.0u\"N\" 2.0u\"N\"\n      3.0u\"N\" 1.0u\"N\"]\nf = (dy,y,p,t) -> (dy .= 0.5.*y ./ 3.0u\"s\")\nprob = ODEProblem(f,u0,(0.0u\"s\",1.0u\"s\"))\n\nsol =solve(prob,ExplicitRK())\n\nfor alg in UNITS_TEST_ALGS\n  @show alg\n  sol = solve(prob,alg,dt=1u\"s\"/10)\nend\n\nprintln(\"Units for 2D pass\")\n\nusing Unitful, RecursiveArrayTools, DiffEqBase, OrdinaryDiffEq\nusing LinearAlgebra\nr0 = [1131.340, -2282.343, 6672.423]u\"km\"\nv0 = [-5.64305, 4.30333, 2.42879]u\"km/s\"\nΔt = 86400.0*365u\"s\"\nμ = 398600.4418u\"km^3/s^2\"\nrv0 = ArrayPartition(r0,v0)\n\nfunction f(dy, y, μ, t)\n    r = norm(y.x[1])\n    dy.x[1] .= y.x[2]\n    dy.x[2] .= -μ .* y.x[1] / r^3\nend\n\nprob = ODEProblem(f,rv0,(0.0u\"s\",1.0u\"s\"),μ)\nsol = solve(prob,Tsit5())\n\n# coordinate: u = [position, momentum]\n# parameters: p = [mass, force constanst]\nfunction f_harmonic!(du,u,p,t)\n  du[1] = u[2]/p[1]\n  du[2] = -p[2]*u[1]\nend\n\nmass = 1.0u\"kg\"\nk = 1.0u\"N/m\"\np = [mass, k]\n\nu0 = [1.0u\"m\", 0.0u\"kg*m/s\"] # initial values (position, momentum)\ntspan = (0.0u\"s\", 10.0u\"s\")\nprob = ODEProblem(f_harmonic!, u0, tspan, p)\nsol = solve(prob)\n", "meta": {"hexsha": "8235f9d22709af391ea7a6916d165e5c153a05e2", "size": 1631, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/units_tests.jl", "max_stars_repo_name": "devmotion/OrdinaryDiffEqExtendedTests.jl", "max_stars_repo_head_hexsha": "0985a15932f3cc8293f8c9335f55fa370c1be4aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/units_tests.jl", "max_issues_repo_name": "devmotion/OrdinaryDiffEqExtendedTests.jl", "max_issues_repo_head_hexsha": "0985a15932f3cc8293f8c9335f55fa370c1be4aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/units_tests.jl", "max_forks_repo_name": "devmotion/OrdinaryDiffEqExtendedTests.jl", "max_forks_repo_head_hexsha": "0985a15932f3cc8293f8c9335f55fa370c1be4aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6376811594, "max_line_length": 86, "alphanum_fraction": 0.6180257511, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7554193498831706}}
{"text": "# # Some Radial Functions\n\n# The **Gaussian** is defined by ``φ(ρ) = \\exp \\left( - (αρ)^2 \\right)``, where \n# ``α`` is a shape parameter to fine-tune the function.\n\n\"\"\"\n    Gaussian( α = 1 ) <: RadialFunction\n\nA `RadialFunction` with \n```math \n    φ(ρ) = \\\\exp( - (α ρ)^2 ).\n```\n\"\"\"\n@with_kw struct Gaussian{R<:Real} <: RadialFunction \n    α :: R = 1\n    @assert α > 0 \"The shape parameter `α` must be positive.\"\nend\n\nfunction ( φ :: Gaussian )( ρ :: Real )\n    exp( - (φ.α * ρ)^2 )\nend\n\ncpd_order( :: Gaussian ) = 0 \ndf(φ :: Gaussian, ρ :: Real) = - 2 * φ.α^2 * ρ * φ( ρ )\n\n# The **Multiquadric** is ``φ(ρ) = - \\sqrt{ 1 + (αρ)^2 }`` and also has a positive shape \n# parameter. We can actually generalize it to the following form:\n\n\"\"\"\n    Multiquadric( α = 1, β = 1//2 ) <: RadialFunction\n\nA `RadialFunction` with \n```math \n    φ(ρ) = (-1)^{ \\\\lceil β \\\\rceil } ( 1 + (αρ)^2 )^β\n```\n\"\"\"\n@with_kw struct Multiquadric{R<:Real,S<:Real} <: RadialFunction\n    α :: R  = 1     # shape parameter \n    β :: S  = 1//2  # exponent \n\n    @assert α > 0 \"The shape parameter `α` must be positive.\"\n    @assert β % 1 != 0 \"The exponent must not be an integer.\"\n    @assert β > 0 \"The exponent must be positive.\"\nend\n\nfunction ( φ :: Multiquadric )( ρ :: Real )\n    (-1)^(ceil(Int, φ.β)) * ( 1 + (φ.α * ρ)^2 )^φ.β\nend\n\ncpd_order( φ :: Multiquadric ) = ceil( Int, φ.β ) \ndf(φ :: Multiquadric, ρ :: Real ) = (-1)^(ceil(Int, φ.β)) * 2 * φ.α * φ.β * ρ * ( 1 + (φ.α * ρ)^2 )^(φ.β - 1)\n\n# Related is the **Inverse Multiquadric** `` φ(ρ) = (1+(αρ)^2)^{-β}``:\n\"\"\"\n    InverseMultiquadric( α = 1, β = 1//2 ) <: RadialFunction\n\nA `RadialFunction` with \n```math \n    φ(ρ) = ( 1 + (αρ)^2 )^{-β}\n```\n\"\"\"\n@with_kw struct InverseMultiquadric{R<:Real,S<:Real} <: RadialFunction\n    α :: R  = 1\n    β :: S  = 1//2\n\n    @assert α > 0 \"The shape parameter `α` must be positive.\"\n    @assert β > 0 \"The exponent must be positive.\"\nend\n\nfunction ( φ :: InverseMultiquadric )( ρ :: Real )\n   ( 1 + (φ.α * ρ)^2 )^(-φ.β)\nend\n\ncpd_order( :: InverseMultiquadric ) = 0\ndf(φ :: InverseMultiquadric, ρ :: Real ) = - 2 * φ.α^2 * φ.β * ρ * ( 1 + (φ.α * ρ)^2 )^(-φ.β - 1)\n\n# The **Cubic** is ``φ(ρ) = ρ^3``. \n# It can also be generalized: \n\"\"\"\n    Cubic( β = 3 ) <: RadialFunction\n\nA `RadialFunction` with \n```math \n    φ(ρ) = (-1)^{ \\\\lceil β \\\\rceil /2 } ρ^β\n```\n\"\"\"\n@with_kw struct Cubic <: RadialFunction \n    β :: Int = 3\n\n    @assert β > 0 \"The exponent `β` must be positive.\"\n    @assert β % 2 != 0 \"The exponent `β` must not be an even number.\"\nend \n\nfunction ( φ :: Cubic )( ρ :: Real )\n    (-1)^ceil(Int, φ.β/2 ) * ρ^φ.β\nend\n\ncpd_order( φ :: Cubic ) = ceil( Int, φ.β/2 )\ndf(φ :: Cubic, ρ :: Real ) = (-1)^(ceil(Int, φ.β/2)) * φ.β * ρ^(φ.β - 1)\n\n# The thin plate spline is usually defined via \n# ``φ(ρ) = ρ^2 \\log( ρ )``. \n# We provide a generalized version, which defaults to \n# ``φ(ρ) = - ρ^4 \\log( ρ )``.\n\"\"\"\n    ThinPlateSpline( k = 2 ) <: RadialFunction\n\nA `RadialFunction` with \n```math \n    φ(ρ) = (-1)^{k+1} ρ^{2k} \\\\log(ρ)\n```\n\"\"\"\n@with_kw struct ThinPlateSpline <: RadialFunction\n    k :: Int = 2\n\n    @assert k > 0 && k % 1 == 0 \"The parameter `k` must be a positive integer.\"\nend\n\nfunction (φ :: ThinPlateSpline )( ρ :: T ) where T<:Real\n    ρ == 0 ? zero(T) : (-1)^(φ.k+1) * ρ^(2*φ.k) * log( ρ )\nend\n\ncpd_order( φ :: ThinPlateSpline ) = φ.k + 1\ndf(φ :: ThinPlateSpline, ρ :: Real ) = ρ == 0 ? 0 : (-1)^(φ.k+1) * ρ^(2*φ.k - 1) * ( 2 * φ.k * log(ρ) + 1)\n\n# !!! note \n#     The thin plate spline with `k = 1` is not differentiable at `ρ=0` but we define the derivative\n#     as 0, which results in a continuous extension.\n", "meta": {"hexsha": "cf60b8b5ba5bbd55cad3dd519b521ac8f8f5fc59", "size": 3595, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/radial_funcs.jl", "max_stars_repo_name": "manuelbb-upb/RBFModels.jl", "max_stars_repo_head_hexsha": "d321761fd58c88a1b11f6f1cf0e82b6ab64531e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/radial_funcs.jl", "max_issues_repo_name": "manuelbb-upb/RBFModels.jl", "max_issues_repo_head_hexsha": "d321761fd58c88a1b11f6f1cf0e82b6ab64531e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-06-18T00:28:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T07:46:46.000Z", "max_forks_repo_path": "src/radial_funcs.jl", "max_forks_repo_name": "manuelbb-upb/RadialBasisFunctionModels.jl", "max_forks_repo_head_hexsha": "d321761fd58c88a1b11f6f1cf0e82b6ab64531e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8682170543, "max_line_length": 109, "alphanum_fraction": 0.5471488178, "num_tokens": 1432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.826711791935942, "lm_q1q2_score": 0.7553471598076389}}
{"text": "struct GradFunc\n    VecOfEq\n    Variables \n    dt\nend\n\nfunction (self::GradFunc)(dt, X)\n    vars = Dict()\n    for i in eachindex(self.Variables)\n        vars[self.Variables[i]] = X[i]\n    end\n    vars[self.dt] = dt \n    expr =  [ModelingToolkit.substitute(i, vars) for i in self.VecOfEq]\n    val = ModelingToolkit.expand_derivatives.(expr)\n    \n    return val \nend\n\n\"\"\"\nArguement\n---------\n- `ODE`{Function}: ODE(du,u,p,t)\n- `dim`{Integer}: Number of variables (`length of u`)\n- `N` {Integer}: Sections of time intervals\n\"\"\"\nfunction gradient_gen(ODE!, p, dim, N)\n    N = N + 1\n\n    @variables X[1:dim, 1:N]\n    @parameters dt \n\n    S = 0\n\n    D = DiffusionMatrix(dim)\n\n    for k in 2:N\n        dxdt = get_dxdt(ODE!, X[:,k-1], p)\n        S = S + (1/4)*dt* (Δ(X,k,dt) - dxdt)' * (D)^(-1) * (Δ(X,k,dt) - dxdt )\n    end\n\n    S = 2*S # TO get the right answer\n    S = ModelingToolkit.simplify(S)\n   \n    ret = ModelingToolkit.gradient(S, collect(Iterators.flatten(X)) )[2]\n\n    ret = ModelingToolkit.simplify(ret)\n    ret=reshape(ret,dim,:) # Matrix\n\n\n    return GradFunc(ret, X, dt)\nend\n\n\nfunction get_dxdt(ODE!, x, p; t=nothing)\n    dx = deepcopy(x)\n    ODE!(dx, x, p, t)\n    return dx\nend\n\n\"\"\"\nDifferentiation\n\"\"\"\nfunction Δ(X,k,dt)\n    return (X[:,k] - X[:, k-1])/dt\nend", "meta": {"hexsha": "47403bc94f73c6e6926ad041c52367b68a2e60da", "size": 1270, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".stack/grad_v2.jl", "max_stars_repo_name": "stevengogogo/PotentialMap.jl", "max_stars_repo_head_hexsha": "bb8fe3df8bf20c9ee30e17dd61640a3546befd83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-20T06:05:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-20T06:05:07.000Z", "max_issues_repo_path": ".stack/grad_v2.jl", "max_issues_repo_name": "stevengogogo/PotentialMap.jl", "max_issues_repo_head_hexsha": "bb8fe3df8bf20c9ee30e17dd61640a3546befd83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-01-04T00:26:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T06:41:56.000Z", "max_forks_repo_path": ".stack/grad_v2.jl", "max_forks_repo_name": "stevengogogo/PotentialMap.jl", "max_forks_repo_head_hexsha": "bb8fe3df8bf20c9ee30e17dd61640a3546befd83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-02T03:43:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-02T03:43:40.000Z", "avg_line_length": 19.5384615385, "max_line_length": 78, "alphanum_fraction": 0.5818897638, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.7553308697761736}}
{"text": "#Hermite-Gaussian Modes\r\nHG(n,m,x,y) = hermiteh(n,√2*x)*hermiteh(m,√2*y)*exp(-x^2-y^2);\r\n\r\nfunction θ(x,y)\r\n\t#θ ∈ [-π,π]\r\n\tif x ≥ 0\r\n\t\tatan(y/x)\r\n\telse\r\n\t\tif y≥ 0\r\n\t\t\tatan(y/x) + π\r\n\t\telse\r\n\t\t\tatan(y/x) - π\r\n\t\tend\r\n\tend\r\nend;\r\n\r\nfunction LG(p,l,x,y)\r\n\t#Laguerre-Gaussian Modes\r\n    if x==0 && y==0\r\n        0.0\r\n    else\r\n        (2*(x^2+y^2))^(0.5*abs(l))*laguerrel(p,abs(l),2*(x^2+y^2))*exp(-(x^2+y^2))*exp(im*l*θ(x,y))\r\n    end\r\nend\r\n\r\nfunction airy_beam(x,α)\r\n\t#Airy beam (in a single direction)\r\n\tairyai(x)*exp(α*x)\r\nend\r\n\r\n#Series of obstacles to simulate difraction\r\nfunction vertical_obstacle(x,y,l)\r\n\tif abs(x)<l\r\n\t\t0.0\r\n\telse\r\n\t\t1.0\r\n\tend\r\nend\r\n\r\nfunction horizontal_obstacle(x,y,l)\r\n\tif abs(y)<l\r\n\t\t0.0\r\n\telse\r\n\t\t1.0\r\n\tend\r\nend\r\n\r\nfunction circular_obstacle(x,y,r)\r\n\tif x^2+y^2<r\r\n\t\t0.0\r\n\telse\r\n\t\t1.0\r\n\tend\r\nend\r\n\r\nfunction rectangular_obstacle(x,y,a,b,c,d)\r\n\tif (a<x<b) & (c<y<d)\r\n\t\t0.0\r\n\telse\r\n\t\t1.0\r\n\tend\r\nend", "meta": {"hexsha": "1a52c9bb2a89cfa07068d7470402cd4a2115132e", "size": 923, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/InitialProfiles.jl", "max_stars_repo_name": "marcsgil/ParaxialBeamPropagation.jl", "max_stars_repo_head_hexsha": "fc13356950902a43b0eaa4adc115fe9e358044f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/InitialProfiles.jl", "max_issues_repo_name": "marcsgil/ParaxialBeamPropagation.jl", "max_issues_repo_head_hexsha": "fc13356950902a43b0eaa4adc115fe9e358044f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/InitialProfiles.jl", "max_forks_repo_name": "marcsgil/ParaxialBeamPropagation.jl", "max_forks_repo_head_hexsha": "fc13356950902a43b0eaa4adc115fe9e358044f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.8870967742, "max_line_length": 100, "alphanum_fraction": 0.5579631636, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920262, "lm_q2_score": 0.8006920068519378, "lm_q1q2_score": 0.7553308627390667}}
{"text": "using Distributions\n\nfunction evsi_an(μ = [0, 0], σ = [1, 1], nsamples = [10000, 10000])\n    m   = μ[1] - μ[2]\n    s   = σ .* σ\n    ps  = nsamples .* s\n    θ   = sqrt(s[1] * (ps[1] / (ps[1] + 1)) + s[2] * (ps[2] / (ps[2] + 1)))\n    (θ * sqrt(2 / π) * exp((-m^2) / (2 * θ^2)) + m * erf(m / (θ * sqrt(2))) - abs(m)) / 2\nend\n\nfunction evsi_sim(μ = [0, 0], σ = [1, 1], nsamples = [10000, 10000]; nsims = 1000000)\n  \n    ndists        = length(μ)\n    true_values   = Array(Float64, nsims, ndists)\n    prior_weight  = Array(Float64, ndists)\n    sample_weight = Array(Float64, ndists) \n    sample_sd     = Array(Float64, ndists)\n   \n    for dist in 1:ndists\n\n        true_values[:, dist] = rand(Normal(μ[dist], σ[dist]), nsims)\n        prior_weight[dist]   = (1 / σ[dist]) / (nsamples[dist] + (1 / σ[dist]))\n        sample_weight[dist]  = nsamples[dist] / (nsamples[dist] + (1 / σ[dist]))\n        sample_sd[dist]      = sqrt(1 / nsamples[dist])\n    \n    end\n    \n    benefit = Array(Float64, nsims)\n    \n    for sim in 1:nsims\n        \n        posterior_mean = Array(Float64, ndists)\n        \n        for dist in 1:ndists\n            posterior_mean[dist] = μ[dist] * prior_weight[dist]\n            if nsamples[dist] > 0 \n                posterior_mean[dist] +=\n                    rand(Normal(true_values[sim, dist], sample_sd[dist])) *\n                        sample_weight[dist]\n            end\n        end\n        \n        benefit[sim] = true_values[sim, indmax(posterior_mean)]\n\n    end    \n    \n    mean(benefit) - maximum(μ)\n\nend", "meta": {"hexsha": "13f16882137ac0a480f25253df34e12f2925145c", "size": 1528, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "voiConsAuc.jl", "max_stars_repo_name": "wkmor1/voiConsAuc", "max_stars_repo_head_hexsha": "71b466f70188c7faa85de6a1a677700be1a72295", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "voiConsAuc.jl", "max_issues_repo_name": "wkmor1/voiConsAuc", "max_issues_repo_head_hexsha": "71b466f70188c7faa85de6a1a677700be1a72295", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "voiConsAuc.jl", "max_forks_repo_name": "wkmor1/voiConsAuc", "max_forks_repo_head_hexsha": "71b466f70188c7faa85de6a1a677700be1a72295", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1836734694, "max_line_length": 89, "alphanum_fraction": 0.515052356, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920262, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7553308582525213}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction _gcirc{T<:AbstractFloat}(units::Integer, ra1::T, dec1::T, ra2::T, dec2::T)\n    # Convert all quantities to radians.\n    if units == 0\n        # All radians\n        λ_1 = ra1\n        λ_2 = ra2\n        φ_1 = dec1\n        φ_2 = dec2\n    elseif units == 1\n        # Right ascensions are in hours, declinations in degrees.\n        λ_1 = ra1*pi/12.0\n        λ_2 = ra2*pi/12.0\n        φ_1 = deg2rad(dec1)\n        φ_2 = deg2rad(dec2)\n    elseif units == 2\n        # Right ascensions and declinations are in degrees.\n        λ_1 = deg2rad(ra1)\n        λ_2 = deg2rad(ra2)\n        φ_1 = deg2rad(dec1)\n        φ_2 = deg2rad(dec2)\n    else\n        # In any other case throw an error.\n        error(\"units must be 0 (radians), 1 (hours, degrees) or 2 (degrees)\")\n    end\n    Δφ_2 = (φ_2 - φ_1) * 0.5\n    Δλ_2 = (λ_2 - λ_1) * 0.5\n    Δσ = 2asin(sqrt(abs2(sin(Δφ_2)) + cos(φ_1) * cos(φ_2) * abs2(sin(Δλ_2))))\n    if units == 0\n        return Δσ\n    else\n        return rad2sec(Δσ)\n    end\nend\n\n\"\"\"\n    gcirc(units, ra1, dec1, ra2, dec2) -> angular_distance\n\n### Purpose ###\n\nComputes rigorous great circle arc distances.\n\n### Explanation ###\n\nInput position can be either radians, sexagesimal right ascension and\ndeclination, or degrees.\n\n### Arguments ###\n\n* `units`: integer, can be either 0, or 1, or 2.  Describes units of inputs and\n output:\n    * 0: everything (input right ascensions and declinations, and output\n      distance) is radians\n    * 1: right ascensions are in decimal hours, declinations in decimal degrees,\n      output distance in arc seconds\n    * 2: right ascensions and declinations are in degrees, output distance in arc\n      seconds\n* `ra1`:  right ascension or longitude of point 1\n* `dec1`: declination or latitude of point 1\n* `ra2`: right ascension or longitude of point 2\n* `dec2`: declination or latitude of point 2\n\nBoth `ra1` and `dec1`, and `ra2` and `dec2` can be given as 2-tuples `(ra1,\ndec1)` and `(ra2, dec2)`.\n\n### Output ###\n\nAngular distance on the sky between points 1 and 2, as a `AbstractFloat`.  See\n`units` argument above for the units.\n\n### Method ###\n\n\"Haversine formula\" see http://en.wikipedia.org/wiki/Great-circle_distance.\n\n### Example ###\n\n``` julia\ngcirc(0, 120, -43, 175, +22)\n# => 1.590442261600714\n```\n\n### Notes ###\n\n* If `ra1`, `dec1` are scalars, and `ra2`, `dec2` are vectors, then the output\n is a vector giving the distance of each element of `ra2`, `dec2` to `ra1`,\n `dec1`.  Similarly, if `ra1`,`de1` are vectors, and `ra2`,` dec2` are scalars,\n then the output is a vector giving the distance of each element of `ra1`,\n `dec1` to `ra2`, `dec2`.  If both `ra1`, `dec1` and `ra2`, `dec2` are vectors\n then the output is a vector giving the distance of each element of `ra1`,\n `dec1` to the corresponding element of `ra2`, `dec2`.\n* The function `sphdist` provides an alternate method of computing a spherical\n distance.\n* The Haversine formula can give rounding errors for antipodal points.\n\nCode of this function is based on IDL Astronomy User's Library.\n\"\"\"\ngcirc(units::Integer, ra1::Real, dec1::Real, ra2::Real, dec2::Real) =\n    _gcirc(units, promote(float(ra1), float(dec1), float(ra2), float(dec2))...)\n\nfunction gcirc{R1<:Real, D1<:Real}(units::Integer,\n                                   ra1::AbstractArray{R1},\n                                   dec1::AbstractArray{D1},\n                                   ra2::Real,\n                                   dec2::Real)\n    @assert length(ra1) == length(dec1)\n    dist = similar(ra1, typeof(float(one(R1))))\n    for i in eachindex(ra1)\n        dist[i] = gcirc(units, ra1[i], dec1[i], ra2, dec2)\n    end\n    return dist\nend\n\nfunction gcirc{R2<:Real, D2<:Real}(units::Integer,\n                                   ra1::Real,\n                                   dec1::Real,\n                                   ra2::AbstractArray{R2},\n                                   dec2::AbstractArray{D2})\n    @assert length(ra2) == length(dec2)\n    dist = similar(ra2, typeof(float(one(R2))))\n    for i in eachindex(ra2)\n        dist[i] = gcirc(units, ra1, dec1, ra2[i], dec2[i])\n    end\n    return dist\nend\n\nfunction gcirc{R1<:Real, D1<:Real, R2<:Real, D2<:Real}(units::Integer,\n                                                       ra1::AbstractArray{R1},\n                                                       dec1::AbstractArray{D1},\n                                                       ra2::AbstractArray{R2},\n                                                       dec2::AbstractArray{D2})\n    @assert length(ra1) == length(dec1) == length(ra2) == length(dec2)\n    dist = similar(ra1, typeof(float(one(R1))))\n    for i in eachindex(ra1)\n        dist[i] = gcirc(units, ra1[i], dec1[i], ra2[i], dec2[i])\n    end\n    return dist\nend\n\n### Tuples input\ngcirc(units::Integer, radec1::Tuple{Real, Real}, ra2::Real, dec2::Real) =\n    gcirc(units, radec1..., ra2, dec2)\n\ngcirc(units::Integer, ra1::Real, dec1::Real, radec2::Tuple{Real, Real}) =\n    gcirc(units, ra1, dec1, radec2...)\n\ngcirc(units::Integer, radec1::Tuple{Real, Real}, radec2::Tuple{Real, Real}) =\n    gcirc(units, radec1..., radec2...)\n", "meta": {"hexsha": "41e18eef9829de274d32aabf748b9df5602306f6", "size": 5198, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gcirc.jl", "max_stars_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_stars_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gcirc.jl", "max_issues_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_issues_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gcirc.jl", "max_forks_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_forks_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6533333333, "max_line_length": 83, "alphanum_fraction": 0.5858022316, "num_tokens": 1560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475746920262, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.755330853765976}}
{"text": "using DataFrames\nusing StatsBase\n\n\n\"\"\"\n\trxy(x::Real,y::Real)\n\tr -> sqrt{x^2 + y^2}\n\"\"\"\nfunction rxy(x::Real, y::Real)\n    return sqrt(x^2 + y^2)\nend\n\n\n\"\"\"\n\thixy(x::Real, y::Real)\n\tphi -> atan(y/x)\n\"\"\"\nfunction phixy(x::Real, y::Real)\n    return atan(y,x)\nend\n\n\"\"\"\n\tphixy(hitdf::DataFrame)\n\tphi -> atan(y/x) where y and x are columns of the data frame\n\"\"\"\nfunction fphi(hitdf::DataFrame)\n    return atan.(hitdf.y,hitdf.x)\nend\n\n\n\"\"\"\n\tdxyz(x1::Vector{<:Real}, x2::Vector{<:Real})\n\nDistance between two points.\n\"\"\"\n\nfunction dxyz(x1::Vector{<:Real}, x2::Vector{<:Real})\n    return sqrt((x1[1] - x2[1])^2 + (x1[2] - x2[2])^2 + (x1[3] - x2[3])^2)\nend\n\n\"\"\"\n\tgline2p(x1,y1,x2, y2)\n\tLine that goes through two points\n\"\"\"\nfunction gline2p(x1, y1, x2, y2)\n    fxy(x) = y1 + (x - x1) * (y2 - y1)/(x2 -x1)\nend\n\nfunction gline2p(x1::Real, y1::Real, x2::Real, y2::Real)\n    fxy(x::Real) = y1 + (x - x1) * (y2 - y1)/(x2 -x1)\nend\n\n\"\"\"\nfunction wstd(x::Vector{<:Real}, q::Vector{<:Real})\n\nCompute the std deviation in x weighted by q:\nSqrt(1/Q Sum_i (x - x_mean) * qi )\n\"\"\"\nfunction wstd(x::Vector{<:Real}, q::Vector{<:Real})\n\txmean = mean(x)\n\tqs = sum((x.-xmean).^2 .* q)\n\tQ = sum(q)\n\treturn sqrt(qs/Q)\nend\n\n\n\"\"\"\n\tmean_std(x, xmin, xmax)\n\tReturns mean and std for a vector x in the interval between xmin and xmax\n\"\"\"\nfunction mean_std(x::Vector{<:Real}, xmin::Real, xmax::Real)\n    xx = in_range(x, xmin, xmax)\n    xm = mean(xx)\n    xs = StatsBase.std(xx)\n    return xm, xs\nend\n", "meta": {"hexsha": "2dbd0fa9da7fcffaf5c5a52ea936de8bd0ce79af", "size": 1461, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math.jl", "max_stars_repo_name": "jjgomezcadenas/ATools", "max_stars_repo_head_hexsha": "87151dc03d153637f957a0269f7290f752d6ca5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math.jl", "max_issues_repo_name": "jjgomezcadenas/ATools", "max_issues_repo_head_hexsha": "87151dc03d153637f957a0269f7290f752d6ca5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-09-19T15:35:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T17:46:30.000Z", "max_forks_repo_path": "src/math.jl", "max_forks_repo_name": "jjgomezcadenas/ATools", "max_forks_repo_head_hexsha": "87151dc03d153637f957a0269f7290f752d6ca5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-01T09:29:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-01T09:29:04.000Z", "avg_line_length": 18.974025974, "max_line_length": 74, "alphanum_fraction": 0.6002737851, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993028, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7553308502474223}}
{"text": "function init_preconditioner(d, q, elType=typeof(1.0))\n    D = d * (q + 1)\n    P = Diagonal(ones(elType, D))\n    PI = Diagonal(ones(elType, D))\n    return P, PI\nend\n\nfunction make_preconditioners!(cache::GaussianODEFilterCache, dt)\n    @unpack P, PI, d, q = cache\n    make_preconditioner!(P, dt, d, q)\n    make_preconditioner_inv!(PI, dt, d, q)\n    return nothing\nend\nfunction make_preconditioners!(post::GaussianODEFilterPosterior, dt)\n    @unpack P, PI, d, q = post\n    make_preconditioner!(P, dt, d, q)\n    make_preconditioner_inv!(PI, dt, d, q)\n    return nothing\nend\n\n@fastmath @inbounds function make_preconditioner!(P, h, d, q)\n    val = factorial(q) / h^(q + 1 / 2)\n    for j in 0:q\n        @simd for i in 0:d-1\n            P[j+i*(q+1)+1, j+i*(q+1)+1] = val\n        end\n        val /= (q - j) / h\n    end\n    return P\nend\n\n@fastmath @inbounds function make_preconditioner_inv!(PI, h, d, q)\n    val = h^(q + 1 / 2) / factorial(q)\n    for j in 0:q\n        @simd for i in 0:d-1\n            PI[j+i*(q+1)+1, j+i*(q+1)+1] = val\n        end\n        val *= (q - j) / h\n    end\n    return PI\nend\n", "meta": {"hexsha": "47aecfa9c7d9c8594098be7f17a519f267cd9b64", "size": 1095, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/preconditioning.jl", "max_stars_repo_name": "nathanaelbosch/ProbNumDiffEq.jl", "max_stars_repo_head_hexsha": "82aa8e911e0f0987b0ddb61e0e7d3ee325d3150a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 57, "max_stars_repo_stars_event_min_datetime": "2021-02-17T21:42:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T23:37:35.000Z", "max_issues_repo_path": "src/preconditioning.jl", "max_issues_repo_name": "nathanaelbosch/ProbNumDiffEq.jl", "max_issues_repo_head_hexsha": "82aa8e911e0f0987b0ddb61e0e7d3ee325d3150a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 90, "max_issues_repo_issues_event_min_datetime": "2021-02-18T00:57:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T20:44:20.000Z", "max_forks_repo_path": "src/preconditioning.jl", "max_forks_repo_name": "nathanaelbosch/ProbNumDiffEq.jl", "max_forks_repo_head_hexsha": "82aa8e911e0f0987b0ddb61e0e7d3ee325d3150a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2021-02-23T06:36:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:15:25.000Z", "avg_line_length": 26.0714285714, "max_line_length": 68, "alphanum_fraction": 0.5799086758, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7553122366830965}}
{"text": "@doc \"\"\"\n       QuasiNewton method for local optimization (single variable)\n\n       Supported by:\n       Ph D Kelvyn B. Sánchez\n       e-mail: kelvyn.baruc@gmail.com\n \"\"\" ->\nfunction QuasiNewton(f, var; x0 = [1 2], error = 0.0001, maxiter = 100, iter = true)\n      try\n            # Symbolic derivatives using Module SymPy\n            dfk1 = diff(f, var)\n\n            err = Inf\n            i = 1\n            xk = 0\n            x_num = 0\n\n            # Numeric iterations\n            iter == true ? ti = time_ns() : nothing # To measure algorothm performance\n\n            while err > error\n                  x_num = x0\n\n                  xk = x_num[2]-(N(dfk1 |> subs(var,x_num[2]))/(N(dfk1 |> subs(var,x_num[2])) -\n                        N(dfk1 |> subs(var,x_num[1]))))*(x_num[2] - x_num[1])\n\n                  if xk > x_num[2]\n                        err = abs(x_num[1] - xk)\n                        x0 = [x_num[2] xk]\n\n                  elseif xk < x_num[1]\n                        err = abs(x_num[2] - xk)\n                        x0 = [xk x_num[1]]\n\n                  elseif xk < x_num[2] && xk > x_num[1]\n                         err = abs(x_num[1] - xk)\n                         x0 = [xk x_num[2]]\n                  end\n\n                        if iter == true\n                              if i == 1\n                                    println(\"===========================================================\")\n                                    println(\" QuasiNewton Solver for Unconstrained Optimization (0.0.2)\")\n                              end\n\n                              if i == 1 || ceil((i/1)/10) == (i/1)/10\n                                    println(\"===========================================================\")\n                                    @printf(\"Iter\\t X\\t\\t f(x)\\t\\t |err|\\n\")\n                                    println(\"===========================================================\")\n                              end\n\n                              @printf(\"%i\\t %4.6e\\t %4.6e\\t %4.6e\\n\", i, xk, N(f |> subs(var,xk)), err)\n                        end\n\n                  if i == maxiter\n                        throw(ErrorException(\"Not Solved!. Iteration limit reached.\"))\n                  end\n\n                  i += 1\n            end\n\n            println(\"===========================================================\")\n            println(\" \")\n\n            iter == true ? tf = time_ns() : nothing # To measure algorithm performance\n            iter == true ? println(\"elapse time: \", (tf - ti)/1.0e9, \" seconds\") : nothing\n\n            return xk,  N(f |> subs(var,xk))\n\n      catch Msg\n            println(\"===========================================================\")\n            println(Msg)\n            return NaN, NaN\n      end\nend\n", "meta": {"hexsha": "f426364c53ff14092e18dbfbc7520154a306ac23", "size": 2770, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/QuasiNewton.jl", "max_stars_repo_name": "JuliaChem/NumOptim.jl", "max_stars_repo_head_hexsha": "584e34e5abe8e0e6ea05cad656f6cf4609b95f70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-12-13T23:47:25.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-13T23:47:25.000Z", "max_issues_repo_path": "src/QuasiNewton.jl", "max_issues_repo_name": "Kelvyn88/OptimJulia.jl", "max_issues_repo_head_hexsha": "584e34e5abe8e0e6ea05cad656f6cf4609b95f70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/QuasiNewton.jl", "max_forks_repo_name": "Kelvyn88/OptimJulia.jl", "max_forks_repo_head_hexsha": "584e34e5abe8e0e6ea05cad656f6cf4609b95f70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4473684211, "max_line_length": 106, "alphanum_fraction": 0.3357400722, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7553122347577979}}
{"text": "# getSHbasis.jl\nusing SphericalHarmonics: computeYlm\nusing CoordinateTransformations: SphericalFromCartesian\nusing MIRTjim: jim\n\n# export numSH getSHbasis\n\n\n\"\"\"\n    c2sph(r, l, m)\n\nEvaluate the `(l,m)` spherical harmonic at one spatial location `(x, y, z)`.\n\"\"\"\nfunction c2sph(x, y, z, l, m)\n\ta = SphericalFromCartesian()([x,y,z]) # todo: SVector?\n\t(rho, ϕ, θ) = (a.r, a.θ, π/2 - a.ϕ)   # (radius, azimuth, colatitude)\n\tY = computeYlm(θ, ϕ; lmax=l)\n\trho^l * Y[(l,m)]\nend\n\n\n\"\"\"\n    n = numSH(L::Int)\nNumber of spherical harmonics for given `L`\ni.e., `sum(2*(0:L) .+ 1)`, which is 9 for `L=2`.\nOrder of 0th-2nd order terms (for `L=2`):\n* 1 cf (center frequency, Hz)\n* 2 z\n* 3 x\n* 4 y\n* 5 z2\n* 6 zx\n* 7 zy\n* 8 x2y2\n* 9 xy\n\"\"\"\nfunction numSH(L::Int)\n\tsum(2*(0:L) .+ 1)\nend\n\n\n\"\"\"\n    getSHbasis!(h, x, y, z; L=2)\n\nStore in `h` the spherical harmonic basis up to order `L` (default 2),\nevaluated at spatial location `(x, y, z)`.\nVector `h` must have length `numSH(L)`.\n\"\"\"\nfunction getSHbasis!(h::AbstractVector{<:Real}, x::Real, y::Real, z::Real; L::Int = 2)\n\n\tic = 1\n\tfor l = 0:L, m = 0:l\n\t\tf = c2sph(x, y, z, l, m)\n\t\th[ic] = real(f)\n\t\tic += 1\n\t\tif m != 0\n\t\t\th[ic] = imag(f)\n\t\t\tic += 1\n \t\tend\n \tend\n\n\th[1] = 1.0 # basis for center frequency offset\n\n\treturn h\nend\n\n\n\"\"\"\n    H = getSHbasis(x, y, z; L::Int=2)\n\nGet spherical harmonic basis up to order `L` (default 2)\nevaluated at spatial location vectors `x, y, z`\nSee `numSH` for ordering.\nOutput size is `(length(x), length(y), length(z), numSH(L))`\n\"\"\"\nfunction getSHbasis(\n\tx::AbstractVector{<:Real},\n\ty::AbstractVector{<:Real},\n\tz::AbstractVector{<:Real};\n\tL::Int=2\n)\n\n\tT = promote_type(eltype.([x, y, z])..., Float32) # at least Float32\n\tH = zeros(T, length(x), length(y), length(z), numSH(L))\n\tfor ix=1:length(x), iy=1:length(y), iz=1:length(z)\n\t\tgetSHbasis!((@view H[ix,iy,iz,:]), x[ix], y[iy], z[iz]; L)\n\tend\n\treturn H\nend\n\n\n# convenience method for scalar inputs\ngetSHbasis(x::Real, y::Real, z::Real; L::Int=2) = getSHbasis([x], [y], [z]; L)\n\n\n\"\"\"\n    H = getSHbasis(\"test\"; L::Int = 2)\n\nTest function\n\"\"\"\nfunction getSHbasis(str::String; L::Int = 2,\n\tnx::Int=22, ny::Int=20, nz::Int=18, fov::NTuple{3,Real}=(20,20,20),\n)\n\trx = LinRange(-1,1,nx)*fov[1]/2\n\try = LinRange(-1,1,ny)*fov[2]/2\n\trz = LinRange(-1,1,nz)*fov[3]/2\n\t@time H = getSHbasis(rx, ry, rz; L)\n\tjim(H; ncol=numSH(L), color=:jet, gui=true, line3plot=false) # compare with >> evalspharm(\"test\")\n\treturn H\nend\n\n# getSHbasis(\"test\"; L = 2);\n", "meta": {"hexsha": "6e6071ffdb77718ba385c363b882f9b10a581cab", "size": 2455, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/getSHbasis.jl", "max_stars_repo_name": "JeffFessler/B0shimming", "max_stars_repo_head_hexsha": "799beb9c433df3cb2b5e5486a6aca6d5b8be7bd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-18T19:14:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-20T15:56:56.000Z", "max_issues_repo_path": "julia/getSHbasis.jl", "max_issues_repo_name": "JeffFessler/B0shimming", "max_issues_repo_head_hexsha": "799beb9c433df3cb2b5e5486a6aca6d5b8be7bd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/getSHbasis.jl", "max_forks_repo_name": "JeffFessler/B0shimming", "max_forks_repo_head_hexsha": "799beb9c433df3cb2b5e5486a6aca6d5b8be7bd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-18T13:43:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-18T13:43:29.000Z", "avg_line_length": 21.7256637168, "max_line_length": 98, "alphanum_fraction": 0.6109979633, "num_tokens": 964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7553122307590981}}
{"text": "\"Compute a transmission coefficient for a Gaussian absorption line with given depth.  Optionally, truncate absorption at limit_line_effect.\"\nfunction std_gaussian_line(x::Number, depth::Number; limit_line_effect = Inf)\n   return abs(x)>limit_line_effect ? one(x) : one(x)-depth*exp(-0.5*x^2)\nend\n\n\"Compute spectrum for an Gaussian absorption line give it's location, width and depth\"\nfunction absorption_line(x::Number, location::Number, width::Number, depth::Number; limit_line_effect = Inf)\n    std_gaussian_line((x-location)/width, depth, limit_line_effect=limit_line_effect)\nend\n\n\n\"Compute product of absorption lines at one wavelength given a list of locations, widths and depths\"\nfunction absorption_lines(x::T1, locations::A2, widths::A3, depths::A4; limit_line_effect = Inf) where { T1<:Number, T2<:Number, T3<:Number, T4<:Number, A2<:AbstractVector{T2}, A3<:AbstractVector{T3}, A4<:AbstractVector{T4} }\n    @assert length(locations) == length(widths) == length(depths) >= 1\n    @inbounds trans = absorption_line(x, locations[1], widths[1], depths[1], limit_line_effect = limit_line_effect )\n    for i in 2:length(locations)\n        @inbounds trans = trans * absorption_line(x, locations[i],widths[i], depths[i], limit_line_effect = limit_line_effect )\n    end\n    return trans\nend\n\nfunction absorption_lines(x::A1, locations::A2, widths::A3, depths::A4; limit_line_effect = Inf) where { T1<:Number, T2<:Number, T3<:Number, T4<:Number, A1<:AbstractArray{T1}, A2<:AbstractVector{T2}, A3<:AbstractVector{T3}, A4<:AbstractVector{T4} }\n    @assert length(locations) == length(widths) == length(depths) >= 1\n    trans = absorption_line.(x, locations[1], widths[1], depths[1], limit_line_effect = limit_line_effect )\n    @inbounds for i in 2:length(locations)\n        trans = trans .* absorption_line.(x, locations[i],widths[i], depths[i], limit_line_effect = limit_line_effect )\n    end\n    return trans\nend\n", "meta": {"hexsha": "00dff957681f372602e8e41b51a15a682dad5c22", "size": 1911, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/absorption_line.jl", "max_stars_repo_name": "PsuAstro528/lab7-start", "max_stars_repo_head_hexsha": "f0ed2b86d60fa018c0e283443b0612b26154e8b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-20T16:09:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-20T16:09:27.000Z", "max_issues_repo_path": "src/absorption_line.jl", "max_issues_repo_name": "PsuAstro528/lab6-start", "max_issues_repo_head_hexsha": "bf58f7fef34670d305ac36f9f3ad5485f3e264fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-28T17:11:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-28T18:30:15.000Z", "max_forks_repo_path": "src/absorption_line.jl", "max_forks_repo_name": "PsuAstro528/lab6-start", "max_forks_repo_head_hexsha": "bf58f7fef34670d305ac36f9f3ad5485f3e264fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-03-14T12:28:35.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-26T14:38:22.000Z", "avg_line_length": 63.7, "max_line_length": 248, "alphanum_fraction": 0.7373103087, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7553122287597483}}
{"text": "module HWconstrained\n\nusing JuMP, NLopt, DataFrames, Ipopt\nusing LinearAlgebra\nexport data, table_NLopt, table_JuMP\n\n### Question 1\nfunction data(a=0.5)\nn=3 \np=[1, 1, 1]\ne=[2, 0, 0]\ns1=s2=4\nz1=[1, 1, 1, 1]\nz2=[0.72, 0.92, 1.12, 1.32]\nz3=[0.86, 0.96, 1.06, 1.16]\nz=[[1, i, j] for i in z2 for j in z3]\nz = vcat(z'...)\npi = repeat([1/16], 16)\na=0.5\nna=3\nnc=4\nns=4\nnss=16\n\nreturn Dict(\"a\"=>a,\"na\"=>na,\"nc\"=>nc,\"ns\"=>ns,\"nss\"=>nss,\"e\"=>e,\"p\"=>p,\"z\"=>z,\"pi\"=>pi)\nend\n#end\n\nd=data()\n\n####  Question 2\n\nfunction obj(x::Vector,grad::Vector,data::Dict)\n    A = data[\"a\"]\n    Z = data[\"z\"]\n    pi = data[\"pi\"]\n    if length(grad) > 0\n        grad[1] = A*exp.(-A*x[1])\n        for i in 1:3\n        grad[i+1] = sum(pi .* Z[:,i] .*A.*exp.(-A.*Z*x[i+1]))\n        end\n    end\n    return -exp.(-A*x[1])+ sum(pi.*-exp.(-A*Z*x[2:4]))\nend\nobj(ones(4), zeros(4), d)\n\nfunction constr(x::Vector,grad::Vector,data::Dict)\n    if length(grad) > 0\n        grad[1] = d[\"a\"]*exp(-d[\"a\"]*x[1])\n        grad[2:end] = d[\"p\"]\n    end\n    return x[1] + sum(d[\"p\"].*(x[2:end].-d[\"e\"]))\nend    \n    \nconstr(ones(4), zeros(4), d) # keep track of # function evaluations\n\nfunction max_NLopt(a=0.5)\nd = data(a)\ne= d[\"e\"]\noptimum = Opt(:LD_MMA, 4)\nlower_bounds!(optimum, [0., -Inf, -Inf, -Inf])   \nmax_objective!(optimum, (x, g)->obj(x, g, d))\ninequality_constraint!(optimum, (x, g)->constr(x, g, d), 1e-8)\nftol_rel!(optimum, 1e-8)\nNLopt.optimize(optimum, vcat(0,e))\nend\n\nfunction table_NLopt()\nd = DataFrame(a=[0.5;1.0;5.0],c = zeros(3),omega1=zeros(3),omega2=zeros(3),omega3=zeros(3),fval=zeros(3))\nfor i in 1:nrow(d)\nxx = max_NLopt(d[i,:a])\nfor j in 2:ncol(d)-1\nd[i,j] = xx[2][j-1]\nend\nd[i,end] = xx[1]\nend\nreturn d\nend\n\n\n\nend # module\n", "meta": {"hexsha": "3bff6ae8751106da962fbd573faedac2b3d7584e", "size": 1698, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HWconstrained.jl", "max_stars_repo_name": "nicolasghio/HWconstrained.jl", "max_stars_repo_head_hexsha": "afef4ab4f79dfb8d05295e603330bd9d84617e9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HWconstrained.jl", "max_issues_repo_name": "nicolasghio/HWconstrained.jl", "max_issues_repo_head_hexsha": "afef4ab4f79dfb8d05295e603330bd9d84617e9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HWconstrained.jl", "max_forks_repo_name": "nicolasghio/HWconstrained.jl", "max_forks_repo_head_hexsha": "afef4ab4f79dfb8d05295e603330bd9d84617e9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4578313253, "max_line_length": 105, "alphanum_fraction": 0.5636042403, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7553122232060056}}
{"text": "using StanModels, Distributions\n\n# ### snippet 8.25\n\nN = 100                                          # individuals\nheight  = rand(Normal(10,2), N) ; # sim total height of each\nleg_prop = rand(Uniform(0.4,0.5), N); # leg as proportion of height\n\n# sim left leg as proportion + error\nleg_left = leg_prop .* height .+  rand(Normal( 0 , 0.02 ), N);\n# sim right leg as proportion + error\nleg_right = leg_prop .* height .+  rand(Normal( 0 , 0.02 ), N);\n\n# combine into data frame\n\ndf =  DataFrame(height=height, leg_left = leg_left, leg_right = leg_right);\n\n# Show first 5 rows\n\nfirst(df, 5)\n\n# Define the Stan language model\n\nm8_8s = \"\ndata{\n    int N;\n    real height[N];\n    real leg_right[N];\n    real leg_left[N];\n}\nparameters{\n    real a;\n    real bl;\n    real br;\n    real sigma;\n}\nmodel{\n    vector[N] mu;\n    sigma ~ cauchy( 0 , 1 );\n    br ~ normal( 2 , 10 );\n    bl ~ normal( 2 , 10 );\n    a ~ normal( 10 , 100 );\n    for ( i in 1:100 ) {\n        mu[i] = a + bl * leg_left[i] + br * leg_right[i];\n    }\n    height ~ normal( mu , sigma );\n}\n\";\n\n# Define the Stanmodel and set the output format to :mcmcchains.\n\nsm = SampleModel(\"m8.8s\", m8_8s);\n\n# Input data for cmdstan\n\nm8_8_data = Dict(\"N\" => size(df, 1), \"height\" => df[!, :height],\n    \"leg_left\" => df[!, :leg_left], \"leg_right\" => df[!, :leg_right]);\n\n# Sample using cmdstan\n\n(sample_file, log_file) = stan_sample(sm, data=m8_8_data);\n\n# Describe the draws\n\nif !(sample_file == nothing)\n  chn = read_samples(sm)\n  describe(chn)\nend\n", "meta": {"hexsha": "555eb493dec0e7d2cf78706991cc85b1ef97850b", "size": 1494, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/08/m8.8s.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StanModels.jl-fb740163-aa3c-59c1-9c12-c3f890714cde", "max_stars_repo_head_hexsha": "16dd5f82cc418e8444ef6ac8490b4bbda3783283", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/08/m8.8s.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StanModels.jl-fb740163-aa3c-59c1-9c12-c3f890714cde", "max_issues_repo_head_hexsha": "16dd5f82cc418e8444ef6ac8490b4bbda3783283", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/08/m8.8s.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StanModels.jl-fb740163-aa3c-59c1-9c12-c3f890714cde", "max_forks_repo_head_hexsha": "16dd5f82cc418e8444ef6ac8490b4bbda3783283", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.652173913, "max_line_length": 75, "alphanum_fraction": 0.5983935743, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7553122210585536}}
{"text": "\"\"\"\n$(SIGNATURES)\n\nAverage number of sigma bound exceedings\n\nReturns the average number of unbiased states / innovation values that exceed the ⨦σ bound of the given covariance\n\"\"\"\nfunction mean_num_sigma_bound_exceedings(state_over_time::Vector{Vector{T}}, covariance_over_time::Vector{Matrix{T}}) where T\n    mean(map((x, P) -> abs.(x) .> sqrt.(diag(P)), state_over_time, covariance_over_time))\nend\n\nfunction mean_num_sigma_bound_exceedings(state_over_time::Vector{T}, covariance_over_time::Vector{T}) where T\n    mean(map((x, P) ->  abs(x) > sqrt(P), state_over_time, covariance_over_time))\nend\n\n\"\"\"\n$(SIGNATURES)\n\nInnovation magnitude bound test (σ-bound-test)\n\nTests if approximately 68% of state values lie within the ⨦σ bound\n\"\"\"\nfunction sigma_bound_test(state_over_time, covariance_over_time)\n    isapprox.(mean_num_sigma_bound_exceedings(state_over_time, covariance_over_time), .32, atol = .015)\nend\n\n\"\"\"\n$(SIGNATURES)\n\nInnovation magnitude bound test (2σ-bound-test)\n\nTests if approximately 95% of state values lie within the ⨦2σ bound\n\"\"\"\nfunction two_sigma_bound_test(state_over_time, covariance_over_time)\n    isapprox.(mean_num_sigma_bound_exceedings(state_over_time, 4 .* covariance_over_time), .05, atol = .008)\nend\n\n\"\"\"\n$(SIGNATURES)\n\nNormalized innovation squared (NIS) Test\n\nDouble-tailed siginicance test with false alarm probability α = 0.05\n\nCalculates confidence interval [r1 r2] and tests Prob{ ∑ NIS values)} ∈ [r1 r2] ∣ H_0 ) = 1 - α\nwith Hypothesis H_0: N * ∑ NIS values ∼ χ^2_{dof}\n     dof (degree of freedom): N * m (N: window length, m: dimension of state vector)\n\"\"\"\nfunction nis_test(nis_over_time, dof)\n    sum_of_nis = sum(nis_over_time)\n\n    r1 = cquantile(Chisq(dof), .975)\n    r2 = cquantile(Chisq(dof), .025)\n\n    (sum_of_nis >= r1) && (sum_of_nis <= r2)\nend\n\n\"\"\"\n$(SIGNATURES)\n\nNormalized innovation squared (NIS)\n\nReturns NIS-value for a single innovation sequence `seq` and its variance `var`\n\"\"\"\nfunction calc_nis(seq, var)\n    dot(seq, var \\ seq)\nend\n\nfunction calc_nis(mu::AbstractMeasurementUpdate)\n    calc_nis(get_innovation(mu), mu.innovation_covariance)\nend", "meta": {"hexsha": "2948541f8b71eda6851d52514ebb183dba38179f", "size": 2107, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tests.jl", "max_stars_repo_name": "JuliaGNSS/KalmanFilters.jl", "max_stars_repo_head_hexsha": "0b5d80b8b93ba27661e78072aa1dc34e611b640d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2021-06-30T05:31:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T09:20:38.000Z", "max_issues_repo_path": "src/tests.jl", "max_issues_repo_name": "JuliaGNSS/KalmanFilters.jl", "max_issues_repo_head_hexsha": "0b5d80b8b93ba27661e78072aa1dc34e611b640d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-02T06:37:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T11:33:01.000Z", "max_forks_repo_path": "src/tests.jl", "max_forks_repo_name": "JuliaGNSS/KalmanFilter.jl", "max_forks_repo_head_hexsha": "ca582217150dd693ae10a5b6111abc2b0f83c603", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-12T19:34:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T15:12:27.000Z", "avg_line_length": 29.676056338, "max_line_length": 125, "alphanum_fraction": 0.7437114381, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.755312219207306}}
{"text": "function solve_naive(input)\n    earliest = earlier = parse(Int64, input[1])\n    buses = parse.(Int64, filter(x -> x != \"x\", split(input[2], ',')))\n    idx = findfirst(id -> earlier % id == 0, buses)\n    while isnothing(idx)\n        earlier += 1\n        idx = findfirst(id -> earlier % id == 0, buses)\n    end\n    buses[idx] * (earlier - earliest)\nend\n\n# Taken from https://rosettacode.org/wiki/Chinese_remainder_theorem#Julia\nfunction chineseremainder(n::Array, a::Array)\n    Π = prod(n)\n    mod(sum(ai * invmod(Π ÷ ni, ni) * (Π ÷ ni) for (ni, ai) in zip(n, a)), Π)\nend\n\nfunction solve_with_flashbacks(input)\n    # (Flashbacks OMA) Esto sale con teorema chino del resto...\n    buses = map(x -> x == \"x\" ? 0 : parse(Int64, x), split(input[2], ','))\n    n = []\n    a = []\n    for i in 0:length(buses) - 1\n        if buses[i + 1] > 0\n            push!(n, -i)\n            push!(a, buses[i + 1])\n        end\n    end\n    chineseremainder(a, n)\nend\n\n@assert solve_naive(readlines(\"input/test/test_day13.txt\")) == 295 [\"test case 1 failed\"]\n@assert solve_with_flashbacks(readlines(\"input/test/test_day13.txt\")) == 1068781 [\"test case 2 failed\"]\n\nprintln(\"First star: \" * string(solve_naive(readlines(\"input/day13.txt\"))))\nprintln(\"Second star: \" * string(solve_with_flashbacks(readlines(\"input/day13.txt\"))))\n", "meta": {"hexsha": "2e03ca24e4a2f46813ad3244bfe4d9c616d3cf7b", "size": 1301, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/day13.jl", "max_stars_repo_name": "Jameru/advent-of-code-2020", "max_stars_repo_head_hexsha": "f5a737e6e6122c38c7077acdefe508d0346e04d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/day13.jl", "max_issues_repo_name": "Jameru/advent-of-code-2020", "max_issues_repo_head_hexsha": "f5a737e6e6122c38c7077acdefe508d0346e04d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/day13.jl", "max_forks_repo_name": "Jameru/advent-of-code-2020", "max_forks_repo_head_hexsha": "f5a737e6e6122c38c7077acdefe508d0346e04d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1621621622, "max_line_length": 103, "alphanum_fraction": 0.615680246, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7553122171339048}}
{"text": "function rouwenhorst(μ,ρ,σ,n)\n    n==1 && (return [μ],[1.0])\n\n\tmu_eps=0\n\tq = (ρ+1)/2\n\tnu = ((n-1)/(1-ρ^2))^(1/2) * σ\n\tP = [q 1-q; 1-q q]\n\tfor i = 2:n-1\n\t\tP = q*[P zeros(i,1);zeros(1,i+1)] + (1-q)*[zeros(i,1) P; zeros(1,i+1)]+ (1-q)*[zeros(1,i+1); P zeros(i,1)] + q*[zeros(1,i+1); zeros(i,1) P]\n\t\tP[2:i,:] = P[2:i,:]/2\n\tend\n\tx = [linspace(mu_eps/(1-ρ).-nu,mu_eps/(1-ρ).+nu,n);].+μ\n\treturn x,P\nend\n\nfunction cdf_normal(x) :inline\n    c = 0.5 * erfc(-x/sqrt(2))\nend\n\nfunction tauchen(μ,ρ,σ,N,m=3)\n\tif N==1\n\t\treturn [μ],[1.0]\n\tend\n\tZ     = zeros(N)\n\tZprob = zeros(N,N)\n\ta     = (1-ρ)*μ\n\n\tZ[N]  = m * sqrt(σ^2 / (1 - ρ^2))\n\tZ[1]  = -Z[N]\n\tzstep = (Z[N] - Z[1]) / (N - 1)\n\n\tfor i=2:(N-1)\n\t    Z[i] = Z[1] + zstep * (i - 1)\n\tend\n\n\tZ = Z .+ a / (1-ρ)\n\n\tfor j = 1:N\n\t    for k = 1:N\n\t        if k == 1\n\t            Zprob[j,k] = cdf_normal((Z[1] - a - ρ * Z[j] + zstep / 2) / σ)\n\t        elseif k == N\n\t            Zprob[j,k] = 1 - cdf_normal((Z[N] - a - ρ * Z[j] - zstep / 2) / σ)\n\t        else\n\t            Zprob[j,k] = cdf_normal((Z[k] - a - ρ * Z[j] + zstep / 2) / σ) - cdf_normal((Z[k] - a - ρ * Z[j] - zstep / 2) / σ)\n\t        end\n\t    end\n\tend\n\treturn Z,Zprob\nend\n", "meta": {"hexsha": "0ced867e1a4d8ea70228570a8ceae75da0c15cbd", "size": 1161, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "Zac12345/EconModel.jl", "max_stars_repo_head_hexsha": "729f3015d59a3aa2952dbb2c9173d5a5b5396339", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "Zac12345/EconModel.jl", "max_issues_repo_head_hexsha": "729f3015d59a3aa2952dbb2c9173d5a5b5396339", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "Zac12345/EconModel.jl", "max_forks_repo_head_hexsha": "729f3015d59a3aa2952dbb2c9173d5a5b5396339", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7647058824, "max_line_length": 141, "alphanum_fraction": 0.4409991387, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7552975102723343}}
{"text": "# indicator of the Stiefel manifold\n\nexport IndStiefel\n\n@doc raw\"\"\"\n**Indicator of the Stiefel manifold**\n\n    IndStiefel()\n\nReturns the indicator of the Stiefel manifold\n```math\nS_{n,p} = \\left\\{ X \\in \\mathbb{F}^{n \\times p} : X^*X = I \\right\\}.\n```\nwhere ``\\mathbb{F}`` is the real or complex field, and parameters ``n`` and ``p``\nare inferred from the matrix provided as input.\n\"\"\"\nstruct IndStiefel <: ProximableFunction end\n\nis_set(f::IndStiefel) = true\n\nfunction (f::IndStiefel)(X::AbstractMatrix{T}) where {R <: Real, T <: Union{R, Complex{R}}}\n    F = svd(X)\n    if all(F.S .≈ R(1))\n        return R(0)\n    end\n    return R(Inf)\nend\n\nfunction prox!(Y::AbstractMatrix{T}, f::IndStiefel, X::AbstractMatrix{T}, gamma::R=R(1)) where {R <: Real, T <: Union{R, Complex{R}}}\n    n, p = size(X)\n    F = svd(X)\n    U_sliced = view(F.U, :, 1:p)\n    mul!(Y, U_sliced, F.Vt)\n    return R(0)\nend\n\nfunction prox_naive(f::IndStiefel, X::AbstractMatrix{T}, gamma::R=R(1)) where {R, T <: Union{R, Complex{R}}}\n    n, p = size(X)\n    F = svd(X)\n    Y = F.U[:, 1:p] * F.Vt\n    return Y, R(0)\nend\n", "meta": {"hexsha": "e3118f1e5dea1780be7af294436a9a477c7a32e0", "size": 1086, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indStiefel.jl", "max_stars_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_stars_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2016-10-29T12:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:11:52.000Z", "max_issues_repo_path": "src/functions/indStiefel.jl", "max_issues_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_issues_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2016-10-26T16:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T20:38:48.000Z", "max_forks_repo_path": "src/functions/indStiefel.jl", "max_forks_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_forks_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T10:40:24.000Z", "avg_line_length": 25.2558139535, "max_line_length": 133, "alphanum_fraction": 0.6095764273, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7552975008306312}}
{"text": "\"\"\"\n**Basic gradient descent with fixed learning rate**\n```julia\nVanillaGradDescent(; η::Real=0.01)\n```\n\nAlgorithm\n```math\n\\\\Delta x_t = \\\\eta g_t\n```\n\n\"\"\"\nmutable struct VanillaGradDescent <: Optimizer\n    opt_type::String\n    t::Int64\n    η::Float64\nend\n\nfunction VanillaGradDescent(; η::Real=0.01)\n    @assert η > 0.0 \"η must be greater than 0\"\n\n    VanillaGradDescent(\"Vanilla Gradient Descent\", 0, η)\nend\n\nparams(opt::VanillaGradDescent) = \"η=$(opt.η)\"\n\nfunction update(opt::VanillaGradDescent, g_t::AbstractArray{T}) where {T<:Real}\n    # update timestep\n    opt.t += 1\n    return opt.η * g_t\nend\n", "meta": {"hexsha": "799cce0365778dacfd11e0509bea1b6bda44c962", "size": 603, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/VanillaGradDescent.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_stars_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2017-08-20T00:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T03:09:32.000Z", "max_issues_repo_path": "src/VanillaGradDescent.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_issues_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-11-19T22:38:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-25T20:33:14.000Z", "max_forks_repo_path": "src/VanillaGradDescent.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_forks_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-08-03T16:14:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:48:41.000Z", "avg_line_length": 18.84375, "max_line_length": 79, "alphanum_fraction": 0.6733001658, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7552975007433241}}
{"text": "using Statistics\n\nfunction show_full(array)\n    show(IOContext(stdout, :limit=>false), MIME\"text/plain\"(), array)\nend\n\n## basic simulation functions\nfunction xdot(x,y,z; sigma=10)\n    return sigma*(y-x)\nend\nfunction ydot(x,y,z; rho=28)\n    return x*(rho-z)-y\nend\nfunction zdot(x,y,z; beta=8/3)\n    return x*y - beta*z\nend\n\nfunction make_step(x,y,z; delta=0.01)\n    xp = x + xdot(x,y,z)*delta\n    yp = y + ydot(x,y,z)*delta\n    zp = z + zdot(x,y,z)*delta\n\n    xn = x + 0.5*(xdot(x,y,z)+xdot(xp,yp,zp))*delta\n    yn = y + 0.5*(ydot(x,y,z)+ydot(xp,yp,zp))*delta\n    zn = z + 0.5*(zdot(x,y,z)+zdot(xp,yp,zp))*delta\n\n    return xn, yn, zn\nend\n\n## threshold functions\n\nfunction threshold_basic(x,y,z)\n    # Z=24\n    out = 0\n    if z>24\n        out = 1\n    end\n    return out\nend\n\nfunction z_tercile_thresh(x,y,z)\n    # states should be mutually exclusive\n    # Z=18.3 and Z=32\n    if z<18.3 #bottom \n        return 1\n    end\n    if z<32 #middle\n        return 2\n    end \n    return 3 #top\nend\n\nfunction eight_state_thresh(x,y,z)\n    state = [0,0,0]\n    if x > 0\n        state[1] = 1\n    end\n    if y > 0 \n        state[2] = 1\n    end\n    if z > 24\n        state[3] = 1\n    end\n    map = Dict([0,0,0] => 1, [1,0,0] => 2, [0,1,0] => 3, [1,1,0] => 4,\n                [0,0,1] => 5, [1,0,1] => 6, [0,1,1] => 7, [1,1,1] => 8)\n    return  map[state]\nend\n\nfunction twelve_state_quant_thresh(x,y,z)\n    #using 0.05, 0.95 quantiles for z\n    state = [0,0,0]\n    if x > 0\n        state[1] = 1\n    end\n    if y > 0 \n        state[2] = 1\n    end\n    if z > 37.9\n        state[3] = 2\n    elseif z > 10.6\n        state[3] = 1\n    end\n    # inefficient to be defining the map inside the function...\n    map = Dict([0,0,0] => 1, [1,0,0] => 2, [0,1,0] => 3, [1,1,0] => 4,\n    [0,0,1] => 5, [1,0,1] => 6, [0,1,1] => 7, [1,1,1] => 8,\n    [0,0,2] => 9, [1,0,2] => 10, [0,1,2] => 11, [1,1,2] => 12)\n    return map[state]\nend\n    \n\n\n## simulation run\nfunction run_sim(;runs=3000, timing=false, thresh_func=z_tercile_thresh)\n    x, y, z = 0, 1, 0\n    X, Y, Z = Float64[0,], Float64[1,], Float64[0,]\n    cnt = 0\n    state_list = [] #list of unique states\n    holding_times = [] #list of holding times of each unique state\n\n    state = thresh_func(x,y,z)\n\n    for i in 1:runs\n        x,y,z = make_step(x,y,z)\n        push!(X, x)\n        push!(Y, y)\n        push!(Z, z)\n\n        if thresh_func(x,y,z) == state\n            cnt += 1\n        else\n            push!(state_list, state)\n            push!(holding_times, cnt)\n            state = thresh_func(x,y,z)\n            cnt = 0\n        end\n\n    end\n    return X, Y, Z, state_list, holding_times\nend\n\nX, Y, Z, state_list, holding_times = run_sim(;runs=1000000, timing=true, thresh_func=twelve_state_quant_thresh)\nnumber_of_states = 12\n\n#basic plotting\nusing Plots\nPlots.plot(X,Y)\nPlots.plot(Z[100:end])\nPlots.histogram(Z;bins=100)\n\n\n#construct probability transition matrix directly\nfunction construct_p(number_of_states, state_list, holding_times)\n    constr_prob = zeros(number_of_states, number_of_states)\n\n    for i in 1:length(state_list)-1\n        local current = state_list[i]\n        local next = state_list[i+1]\n        constr_prob[current, current] += holding_times[i]-1\n        constr_prob[next, current] += 1 #reconstruct full markov chain\n    end\n    norm = sum(constr_prob, dims=1) \n\n    norm_constr_prob = constr_prob ./ norm\n    empirical_T = log(norm_constr_prob)/0.01\n    return (norm_constr_prob, empirical_T)\nend\nnorm_constr_prob, empirical_T = construct_p(number_of_states, state_list, holding_times)\nshow_full(norm_constr_prob)\nshow_full(empirical_T)\n\n## other method! \nfunction construct_t(number_of_states, state_list, holding_times)\n    holding_time_dist = [[] for n in 1:number_of_states]\n    constr_T = zeros(number_of_states, number_of_states)\n\n    #count number of times unique states appear\n    for i in 1:length(state_list)-1 #for i in unique states #why is the -1??\n        local current = state_list[i]\n        local next = state_list[i+1]\n        constr_T[next, current] += 1 \n        push!(holding_time_dist[current], holding_times[i]*0.01)\n    end\n\n    norm = sum(constr_T, dims=1)\n    norm_constr_T = constr_T ./ norm\n\n    holding_scale = 1 ./ mean.(holding_time_dist) \n    for i in 1:number_of_states\n        norm_constr_T[i, i] = -1.0 #this is the bit I don't quite understand\n        norm_constr_T[:, i] *= holding_scale[i]\n    end\n\n    empirical_prob = exp(norm_constr_T * 0.01)\n    return (norm_constr_T, empirical_prob)\nend\n\nnorm_constr_T, empirical_prob = construct_t(number_of_states, state_list, holding_times)\nshow_full(norm_constr_T)\nshow_full(empirical_prob)\n\n`                                                           `\n\n## identify quantiles in Z\nz_sort = copy(Z)\nthree_state_extremes = quantile!(z_sort,[0.05, 0.95]) #output: [10.6, 37.9]\nfive_state_extremes = quantile!(z_sort,[0.05, 0.25, 0.75, 0.95]) #output: [10.6, 16.9, 30.6, 37.9]\n\n\n###################\n\nfunction get_maxima(ls; add_min=false)\n    maxs = Float64[]\n    if add_min\n        mins = Float64[]\n        if ls[1]<ls[2]\n            push!(mins,ls[1])\n        end\n    end\n    if ls[1]>ls[2]\n        push!(maxs,ls[1])\n    end\n    for i=2:length(ls)-1\n        if ls[i-1]<ls[i]>ls[i+1]\n            push!(maxs,ls[i])\n        end\n        if add_min\n            if ls[i-1]>ls[i]<ls[i+1]\n                push!(mins,ls[i])\n            end\n        end\n    end\n    if ls[end]>ls[end-1]\n        push!(maxs,ls[end])\n    end\n    if add_min\n        if ls[end]<ls[end-1]\n            push!(mins,ls[end])\n        end\n        return maxs, mins\n    else\n        return maxs\n    end\nend\n\n# get subsequent maxima  \"tent\" plot\nz_max = get_maxima(Z)\nz_plot = Tuple{Float64, Float64}[]\nfor i=1:length(z_max)-1\n    push!(z_plot,(z_max[i], z_max[i+1]))\nend\ni1 = [x[1] for x in z_plot]\ni2 = [x[2] for x in z_plot]\nPlots.scatter(i1,i2)\n\n# get sequential max/min plot\nz_max, z_min = get_maxima(Z, add_min=true)\nPlots.scatter(z_max, z_min)\n", "meta": {"hexsha": "402ee857159830dcba1dbe830d204284d5e19c10", "size": 5941, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "continued_sim.jl", "max_stars_repo_name": "m-geo/lorenz", "max_stars_repo_head_hexsha": "501f8539f8693d03a7736a35f0ef768f36245ced", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "continued_sim.jl", "max_issues_repo_name": "m-geo/lorenz", "max_issues_repo_head_hexsha": "501f8539f8693d03a7736a35f0ef768f36245ced", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "continued_sim.jl", "max_forks_repo_name": "m-geo/lorenz", "max_forks_repo_head_hexsha": "501f8539f8693d03a7736a35f0ef768f36245ced", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9621848739, "max_line_length": 111, "alphanum_fraction": 0.5882848005, "num_tokens": 2008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8244619263765706, "lm_q1q2_score": 0.7552975005687103}}
{"text": "function init_local_gaussian(center, dx, dy, dz, H)\n    X = Data.Array([\n        2 * exp(\n            -1.0 * (\n                (x_g(ix, dx, H) + dx / 2 - center[1])^2 +\n                (y_g(iy, dy, H) + dy / 2 - center[2])^2 +\n                (z_g(iz, dz, H) + dz / 2 - center[3])^2\n            ),\n        ) for ix = 1:size(H, 1), iy = 1:size(H, 2), iz = 1:size(H, 3)\n    ])\n    return X\nend\n\nfunction apply_boundary_conditions!(H, coords, dims)\n    if coords[1] == 1\n        H[1, :, :] .= 0.0\n    end\n    if coords[2] == 1\n        H[:, 1, :] .= 0.0\n    end\n    if coords[3] == 1\n        H[:, :, 1] .= 0.0\n    end\n\n    if coords[1] == dims[1]\n        H[end, :, :] .= 0.0\n    end\n    if coords[2] == dims[2]\n        H[:, end, :] .= 0.0\n    end\n    if coords[3] == dims[3]\n        H[:, :, end] .= 0.0\n    end\nend\n\nfunction dist_norm_L2(Rh, comm_cart)\n    sq_residual = [sum(Rh .^ 2)]  # this is local\n    MPI.Allreduce!(sq_residual, +, comm_cart)\n    return sqrt(sq_residual[1])\nend\n\nfunction linear_interpolate_3D(H, dx)\n    dy = dz = dx\n\n    ix, iy, iz = Int.((LOCATION_OF_INTEREST.÷ dx) .+ 1)\n    \n    # manual trilinear interpolation\n    # see https://en.wikipedia.org/wiki/Trilinear_interpolation#Alternative_algorithm\n    x0, x1 = ix*dx+dx/2, (ix+1)*dx+dx/2\n    y0, y1 = iy*dy+dy/2, (iy+1)*dy+dy/2\n    z0, z1 = iz*dz+dz/2, (iz+1)*dz+dz/2\n\n    cvec = [H[ix, iy, iz], H[ix+1, iy, iz], H[ix, iy+1, iz], H[ix+1, iy+1, iz], H[ix, iy, iz+1], H[ix+1, iy, iz+1], H[ix, iy+1, iz+1], H[ix+1, iy+1, iz+1]]\n\n    xvec = repeat([x0;x1], 4)\n    yvec = repeat([y0; y0; y1; y1], 2)\n    zvec = repeat(repeat([z0], 4), 2)\n\n    M = hcat(ones(8), xvec, yvec, zvec, xvec.*yvec, xvec.*zvec, yvec.*zvec, xvec.*yvec.*zvec)\n\n    interp_value = try\n        avec = M \\ cvec\n        x, y, z = LOCATION_OF_INTEREST\n        xvec_ = [1 x y z x*y x*z y*z x*z*z]\n        interp_value = xvec_ * avec\n        interp_value\n    catch e\n        interp_value = H[ix, iy, iz]\n        interp_value\n    end\nend\n", "meta": {"hexsha": "e4143a9dcd3644696245f356eb19286c3251c896", "size": 1972, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts-part1/part1_utils.jl", "max_stars_repo_name": "ntselepidis/FinalProjectRepo.jl", "max_stars_repo_head_hexsha": "069b7532dd024410b02723d4b967651dd80a83fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts-part1/part1_utils.jl", "max_issues_repo_name": "ntselepidis/FinalProjectRepo.jl", "max_issues_repo_head_hexsha": "069b7532dd024410b02723d4b967651dd80a83fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts-part1/part1_utils.jl", "max_forks_repo_name": "ntselepidis/FinalProjectRepo.jl", "max_forks_repo_head_hexsha": "069b7532dd024410b02723d4b967651dd80a83fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3888888889, "max_line_length": 155, "alphanum_fraction": 0.5, "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8244619263765706, "lm_q1q2_score": 0.755297496792029}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction _mag2flux(mag::T, zero_point::T, ABwave::T) where {T<:AbstractFloat}\n    if isnan(ABwave)\n        return exp10(-0.4*(mag + zero_point))\n    else\n        return exp10(-0.4*(mag + 2.406 + 5*log10(ABwave)))\n    end\nend\n\n\"\"\"\n    mag2flux(mag[, zero_point, ABwave=number]) -> flux\n\n### Purpose ###\n\nConvert from magnitudes to flux expressed in erg/(s cm² Å).\n\n### Explanation ###\n\nThis is the reverse of `flux2mag`.\n\n### Arguments ###\n\n* `mag`: the magnitude to be converted in flux.\n* `zero_point`: the zero point level of the magnitude.  If not supplied then defaults to\n 21.1 (Code et al 1976).  Ignored if the `ABwave` keyword is supplied\n* `ABwave` (optional numeric keyword): wavelength, in Angstroms.  If supplied, then the\n input `mag` is assumed to contain Oke AB magnitudes (Oke & Gunn 1983, ApJ, 266, 713;\n http://adsabs.harvard.edu/abs/1983ApJ...266..713O).\n\n### Output ###\n\nThe flux.\n\nIf the `ABwave` keyword is set, then the flux is given by the expression\n\n\\$\\$\\\\text{flux} = 10^{-0.4(\\\\text{mag} +2.406 + 4\\\\log_{10}(\\\\text{ABwave}))}\\$\\$\n\nOtherwise the flux is given by\n\n\\$\\$\\\\text{flux} =  10^{-0.4(\\\\text{mag} + \\\\text{zero point})}\\$\\$\n\n### Example ###\n\n```jldoctest\njulia> using AstroLib\n\njulia> mag2flux(8.3)\n1.7378008287493692e-12\n\njulia> mag2flux(8.3, 12)\n7.58577575029182e-9\n\njulia> mag2flux(8.3, ABwave=12)\n3.6244115683017193e-7\n```\n\n### Notes ###\n\nCode of this function is based on IDL Astronomy User's Library.\n\"\"\"\nmag2flux(mag::Real, zero_point::Real=21.1; ABwave::Real=NaN) =\n    _mag2flux(promote(float(mag), float(zero_point), float(ABwave))...,)\n", "meta": {"hexsha": "462defbe1b947020588a2d84ae77284604b38083", "size": 1682, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mag2flux.jl", "max_stars_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_stars_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2016-09-11T14:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T20:45:36.000Z", "max_issues_repo_path": "src/mag2flux.jl", "max_issues_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_issues_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 64, "max_issues_repo_issues_event_min_datetime": "2017-01-19T21:03:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:27:46.000Z", "max_forks_repo_path": "src/mag2flux.jl", "max_forks_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_forks_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:11:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:55:21.000Z", "avg_line_length": 25.8769230769, "max_line_length": 88, "alphanum_fraction": 0.6676575505, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7552974946417673}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ cac0bc38-ead9-4f99-a939-fc2645874efd\nmd\"\"\"\n# Types in Julia\n\"\"\"\n\n# ╔═╡ ecb2b8d9-ceda-4008-8137-b29bd7ef3ba9\n# Uses of types.jl\n\n# ╔═╡ b4f0668c-8b25-4588-9176-52bc7bfe797b\nmd\"\"\"\nIn this notebook we will start exploring types by implementing a type to implement algorithmic differentiation.\n\"\"\"\n\n# ╔═╡ 0ece0b55-ede7-4db1-9b48-61e1d4534761\nmd\"\"\"\n### What is a type?\n\"\"\"\n\n# ╔═╡ 6dcc01fe-c551-43d2-930b-ff1c93d15077\nmd\"\"\"\nA *type* can be thought of as a label that is associated with data stored in memory; this label tells Julia how to interpret the data. For example:\n\"\"\"\n\n# ╔═╡ 0d352bcc-dfc1-429f-ad6c-40dc8c4cd038\nbegin\n\tx = 1\n\ty = 1.3\nend\n\n# ╔═╡ 81863f06-8dac-48fd-a6e1-cf5df30c63f6\nsizeof(x), sizeof(y)\n\n# ╔═╡ 3de40205-6b5d-4d99-b886-1a1dc6a07955\ntypeof(x), typeof(y)\n\n# ╔═╡ d4c280cf-910c-4bbf-8dca-b01b14711296\n# rinterpret the bit-representation of x (an int) as another type, e.g. Float64 \nz = reinterpret(Float64, x)\n\n# ╔═╡ 7082e444-6268-4721-a278-2511a22daf68\nbitstring(x)\n\n# ╔═╡ 43538919-4349-43f1-a196-759fe65d3be3\nbitstring(z)\n\n# ╔═╡ e0c1df0c-ff62-4982-8f3d-3ccbb44b8d2f\nmd\"\"\"\nBoth variables are stored in 8 bytes (64 bits), but one is interpreted as an integer and the other as a floating-point number.  Similarly, a pair of two numbers may be intepreted as a complex number, or an interval, or a dual number, or...; although the same information may be stored (two numbers), we want each of these different *kinds* or *types* of objects to be treated differently. \n\"\"\"\n\n# ╔═╡ e6281275-0b87-47f4-a081-bb366ced3466\nmd\"\"\"\n## Algorithmic differentiation\n\"\"\"\n\n# ╔═╡ 6056ff4a-858f-447c-85cc-0f3f6e0e53ca\nmd\"\"\"\nIn the previous notebook we used `ForwardDiff.jl` to automatically differentiate a function. Here we will see how to implement a simple version of this.\n\"\"\"\n\n# ╔═╡ db17c624-91b6-44b1-bd10-4d72f4cb9776\nmd\"\"\"\nThe idea is to approximate a (nice enough) function $f$ near a point $a$ by a Taylor series of order 1, i.e. a straight line passing through $(a, f(a))$, with slope equal to the derivative $f'(a)$:\n    \n$f(x) \\simeq f(a) + \\epsilon f'(a)$,\n\nwhere $\\epsilon := x - a$.\n\nWe now use this to derive the standard rules for the derivative of a sum and product:\n\n$$f(x) + g(x) \\simeq [f(a) + g(a)] + \\epsilon [f'(a) + g'(a)]$$\n\n$$f(x) \\cdot g(x) \\simeq [f(a) \\cdot g(a)] + \\epsilon [f(a) g'(a) + g(a) f'(a)],$$\n\nwhere we suppose that $\\epsilon$ is small enough that $\\epsilon^2 = 0$, or alternatively just \"take the linear part\".\n\"\"\"\n\n# ╔═╡ b3b15bf5-115d-4831-9115-36c88e9b899c\nmd\"\"\"\n### Defining a composite type\n\"\"\"\n\n# ╔═╡ 70843c81-6abe-40b2-8d0b-8d779fccedc8\nmd\"\"\"\nWe see that by using just two pieces of information, namely the value $f(a)$ and the derivative $f'(a)$, we can represent a function $f$ near a given point $a$. \n\nThe pair $(f(a), f'(a))$ is often called a **dual number**. We see that is has certain **behaviours** under arithmetic operations. Whenever we have a new behaviour, a *new type is lurking*!\n\nWe group the two values into a **composite type**. We can think of a composite type as specifying the structure of a box containing several pieces of information (data) inside. Defining a composite type with two **fields** (pieces of information) has the following syntax:\n\"\"\"\n\n# ╔═╡ 82c79506-68ea-41dd-888d-840371c08430\nstruct MyType\n    a\n    b::Int\nend\n\n# ╔═╡ 291315e0-ad0e-4a57-b100-2baa5af04c04\nmd\"\"\"\nHere we have additionally specified that the information stored in the field `b` must be of type `Int` using the **type annotation operator**, `::`.\n\"\"\"\n\n# ╔═╡ f2421fbf-5cfc-4332-be60-b61fa4e02d8c\nmd\"\"\"\nCreating an object of that type is accomplished as follows:\n\"\"\"\n\n# ╔═╡ 710612bd-4856-4e51-b2d6-2bdc972f196d\nx1 = MyType(3, 4)\n\n# ╔═╡ 70eb5167-6288-4f84-b140-21b4b329cb45\nmd\"\"\"\nWe can extract information as follows:\n\"\"\"\n\n# ╔═╡ 9fb42f3c-c7ff-4f31-b5e6-9e96de16bac5\nx1.a\n\n# ╔═╡ 07808ac8-c910-4e92-ac34-c9ff225f4be8\ntypeof(x1.a)\n\n# ╔═╡ 8777c6a7-90e3-4dc7-ab61-3d12531f2ea9\nmd\"\"\"\n#### Exercise 1\n\n1. Define a composite type `Dual` with fields `value` and `deriv` of type `Float64`.\n\n\n2. Create two `Dual` numbers `x` and `y`.\n\n\n3. What happens if you try to add `x` and `y` together?\n\n\n4. Make a function `add` that adds `x` and `y` and returns a new `Dual` number, following the rules we found above.\n\"\"\"\n\n# ╔═╡ 5488c55f-8d0a-4c9b-8f8b-40ed4fe14e67\nstruct Dual\n    value::Float64\n    deriv::Float64\nend\n\n# ╔═╡ 4f5e5eea-13df-477e-baea-c37ab6074aea\nx_D = Dual(3, 4)\n\n# ╔═╡ da932afe-990f-4ca7-aa81-9d85e1ca3bac\nmethods(Dual)\n\n# ╔═╡ fac29cb2-dc57-4a06-9728-567169ac3768\nconvert(Float64, 3)\n\n# ╔═╡ 4118613c-e58a-4f63-81d1-0e197e66cf98\n# this raises an error\nconvert(Float64, \"hello\")\n\n# ╔═╡ ac8fa4de-d8ef-44f2-b709-aceb1e0ecb04\ny_D = Dual(5, 6)\n\n# ╔═╡ 92aa5678-478c-4cb6-9187-3285534aac8c\nx_D + y_D\n\n# ╔═╡ 04a21e57-a45c-4e4b-977a-42c6ee228b4a\nnewadd(x::Dual, y::Dual) = Dual(x.value + y.value, x.deriv + y.deriv)\n\n# ╔═╡ 915bfb27-7234-43ea-a052-093f89d7bdcd\nnewadd(x_D, y_D)\n\n# ╔═╡ 9b213fb9-382a-4c5b-93fe-22252d29d0c6\nmd\"\"\"\n## Implementing arithmetic for a type\n\"\"\"\n\n# ╔═╡ 8eed2b5c-dde2-437e-8383-4ed206ce72de\nmd\"\"\"\nWe would like to be able to use `+` and `*` for our new `Dual` type, rather than typing `add(x, y)`. To do so, we need to do the following\n\"\"\"\n\n# ╔═╡ 62a97a4b-dfa6-404d-958b-b7b4ab7d25ca\n# +(x::Dual, y::Dual) = Dual(x.value + y.value, x.deriv + y.deriv)\n\n# ╔═╡ 9b0d361a-8c30-4ec0-a183-ac3890895f0e\n# Base.+(x::Dual, y::Dual) = Dual(x.value + y.value, x.deriv + y.deriv)\n\n# ╔═╡ 9b8f41b5-9ade-4f34-8d09-cb548bd6c242\n# or\n# +(x::Dual, y::Dual) = add(x, y)\n\n# ╔═╡ 5b29f183-bda6-4ffb-bb78-5199980039d3\n# or\n# function +(x::Dual, y::Dual)\n#    return add(x, y)\n# end\n\n# ╔═╡ fc624260-ba8a-4057-8a1f-2659e2343654\nmd\"\"\"\nIn Julia, `+` and `*` are just functions. They are defined in `Base` (a module containing basic function definitions) and must be `import`ed before being **extended**. They consist of many different **methods** (versions):\n\"\"\"\n\n# ╔═╡ abcbc0a1-33e7-430f-b0a8-e8b65c8666b2\n@which +(3)\n\n# ╔═╡ 17498a94-5db9-4c5e-9268-e588fddeae54\n-(3)\n\n# ╔═╡ c847f0c2-1eac-4900-b80c-7f89846b2924\nmethods(+)\n\n# ╔═╡ 6caea9da-3edc-4309-bad8-f348693960b2\nx\n\n# ╔═╡ 17cce3ab-1b4f-402d-bcc3-c7905360a441\ny\n\n# ╔═╡ 526a204c-6a72-4cde-900a-568667e45c64\nx + y\n\n# ╔═╡ 86aa82b1-caae-4124-b48a-14497420f471\nmd\"\"\"\nWe can add more methods that work on our own types. (We are not allowed to modify their behaviour on combinations of types that to not contain our user-defined types; doing so is known as \"type piracy\" and can affect other people's code in unexpected ways.)\n\"\"\"\n\n# ╔═╡ e359dd62-65f0-4033-98c2-aff400ed0bb7\nmd\"\"\"\n#### Exercise 2\n\n1. Import the `+` and `*` functions from `Base` and implement them for the `Dual` type.\nThey should return a new `Dual` object.\n\n\n2. Check that the number of methods has changed. \n\n\n3. Use `@which x + y` to check that Julia knows which method to use when adding two `Dual`s.\n\n\n4. Can you define `x + a` for a `Dual` number `x` and a real number `a`? What happens \n\"\"\"\n\n# ╔═╡ 86141559-f6f4-43a6-8291-550adf31b25b\n\n\n# ╔═╡ cee6af83-0079-4acd-9e14-cd7b7eb6947f\nbegin\n\tvalue(f::Dual) = f.value\n\tderiv(f::Dual) = f.deriv\nend\n\n# ╔═╡ 4e222c6a-054b-41e6-bef4-b0726344ee94\nlet\n\t∂(f::Dual) = f.deriv\n\t*(f::Dual, g::Dual) = Dual(value(f) * value(g),\n    \t                     value(f) * ∂(g) + ∂(f) * value(g))\n\t42 # return this to avoid conflict\nend\n\n# ╔═╡ a1b1b945-ba2e-4668-8698-4df02660d379\nmd\"\"\"\n(Try using `@code_llvm`)\n\"\"\"\n\n# ╔═╡ 8857e0aa-da38-4ae6-8ef9-efa66dd51cfc\nbegin\n\tf = Dual(3.0, 4.0)\n\tg = Dual(5.0, 6.0)\nend\n\n# ╔═╡ ad671591-a625-4de2-9b18-84c7773cb4b8\nf, g\n\n# ╔═╡ 053e90a7-5fa6-4063-9634-63d48ee16690\nf + g\n\n# ╔═╡ d521f0e3-1636-4e8b-b8f3-639a90780690\nf * g\n\n# ╔═╡ b7b81d9d-354d-4ec0-b50c-302dbcb8f0c4\nmd\"\"\"\nAmazingly, we now have enough to be able to differentiate simple Julia functions involving only `+` and `*`. Define\n\"\"\"\n\n# ╔═╡ d67fa8a9-f43e-4eca-bb0e-1603c9f7da5d\nbegin\n\ta = 3.0\n\txx = Dual(a, 1.0)  # \"the identity function x ↦ x, with derivative 1\"\nend\n\n# ╔═╡ 3bc3d5a3-9b9f-4d07-9d59-f24d5c005038\nmd\"\"\"\nWe initialize the derivative as 1.0 when we make a `Dual`. If we use `x` then we automatically differentiate!\n\"\"\"\n\n# ╔═╡ fd34be78-af76-4d46-bdbd-19fd19155785\nmd\"\"\"\n#### Exercise 3\n\"\"\"\n\n# ╔═╡ caccd695-118c-46a8-b59f-376e4cbc83ce\nmd\"\"\"\n1. Define `a = 3.0` and `xx = Dual(a, 1.0)`.\n\n    (i) Compute `xx + xx`. The result should have the value $2a$ and the derivative $2$ -- write a test that it does so.\n    \n    (ii) Do the same for `xx * xx`. \n    \n    \n2. Define the function `f(x) = x * x + x`. Compute `f(xx)` and check that it gives the correct value and derivative!\n\n\n3. Does this work for the function `f(x) = x^2 + x`?  What do you need to do?\n\n\n4. What happens for `f(x) = x^2 + 2x`? What do you need to do?\n\n\n5. What should you do for `f(x) = sin(x) + x`?\n\"\"\"\n\n# ╔═╡ 6418d0a4-8dd3-4816-8e5b-092cb769ebb6\na = 3.0\nxx = Dual(a, 1.0)\n\n# ╔═╡ 8ebb42e9-11ec-434d-87c9-4259c26f6526\nxx + xx\n\n# ╔═╡ 84b6a870-4515-4e6c-b306-d6b6d2a0fb8d\nxx * xx\n\n# ╔═╡ a0865cb0-7077-44ff-a130-eb73cbbc3179\nxx * xx + xx  # the function x ↦ x^2 + x,  derivative 2x + 1\n\n# ╔═╡ f1fc7637-4804-4fc1-81ac-14874e66f9d6\nff(x) = x*x*x + x*x + x*x  # x^3 + 2x^2\n\n# ╔═╡ ded7adc0-619f-4735-bd93-9c26c4c21858\nff(xx)\n\n# ╔═╡ 1284374b-ab26-46b8-a74e-119655f5112e\nff(a)\n\n# ╔═╡ 4e06b4f6-9753-4847-8c6c-120208520dc5\nn = 4\nfff(x) = x^n\n\n# ╔═╡ 420c0ef0-3f7e-4044-be30-c2873636c6e8\ndff(x) = 3x^2 + 4x\n\n# ╔═╡ f426bed2-05f1-4598-9817-bb90262911ef\ndff(a)\n\n# ╔═╡ 09bfa122-ca5b-4b4a-a9eb-09b1b5482a76\nfff(x) = x^2\n\n# ╔═╡ d08a434c-c816-4f43-9c93-2d0eda57723c\nfff(xx)\n\n# ╔═╡ 131373df-8e58-49b0-be5f-3cd8d8deb61d\nfff(xx)\n\n# ╔═╡ 76a7a87b-0283-4a85-9d88-0eec06ef689f\nfff4(x) = x^4\n\n# ╔═╡ d608bc38-5653-4ad5-b6e4-6b2236299e4c\nfff4(xx)\n\n# ╔═╡ bf697142-0eaf-4717-9434-eaa89946beb4\nmd\"\"\"\n`Base.literal_pow`\n\"\"\"\n\n# ╔═╡ 108212df-c86f-4b75-8576-65f3964687e9\nmd\"\"\"\n#### Exercise 4\n\"\"\"\n\n# ╔═╡ eb94cc27-ac9e-4202-acdc-248809eebdb9\nmd\"\"\"\n1. Define a function `differentiate` that differentiates a function `f` at a point `a` using `Dual` numbers, by following the above pattern. (It should return just the derivative at the given point.)\n\"\"\"\n\n# ╔═╡ d7f6c80a-4922-42be-9bce-e493e603c373\n\n\n# ╔═╡ 70ec3ada-f7ae-4526-be35-5aa8cd4533ca\nmd\"\"\"\nThis is the basis of (\"forward-mode\") automatic differentiation. The `ForwardDiff.jl` method contains a sophisticated implementation of this method.\n\"\"\"\n\n# ╔═╡ 5011cf98-128e-4c94-bae0-109016427c50\nmd\"\"\"\n### Parametric types\n\"\"\"\n\n# ╔═╡ d57937d8-3f1e-4f85-bf6b-afc8cfe3e99d\nmd\"\"\"\nFor simplicity, in the above we fixed the fields in the `Dual` type to be of type `Float64`. By doing so we are actually *losing power*. Instead we should let Julia \"fill in\" the types. \n\nTo do so, we specify that we want to use a **type parameter** `T`. We can think of this as a \"special kind of variable\" that can only take on certain kinds of values. We specify this with the following syntax: \n\"\"\"\n\n# ╔═╡ df1c033c-8a99-4b45-bc9c-3287a3a959ec\nstruct MyType2{T}\n    a::T\n    b::T\nend\n\n# ╔═╡ b0902a74-01e0-456a-a027-a5030d494d7f\nmd\"\"\"\n[Note that we have not reused the name `MyType` since Julia *does not allow types to be redefined in a different way*.]\n\"\"\"\n\n# ╔═╡ 9226e5a3-4445-4420-9b54-be31468e6b07\nmd\"\"\"\nHere we are specifying that both fields `a` and `b` must share the same type `T`, but we have not restricted what values `T` can take. When we create an object, Julia will *infer* (work out) the type:\n\"\"\"\n\n# ╔═╡ ccc258fa-c928-4175-a48e-bd72b7d22f31\nx_M = MyType2(3, 4)\n\n# ╔═╡ c9f3dde8-7989-45e8-9831-894d82e57e90\ny_M = MyType2(3.1, 4.2)\n\n# ╔═╡ 2d3876d6-5fcf-4bfb-8dba-4bdf252c73fc\nz_M = MyType2(1, 5.3)\n\n# ╔═╡ a0d7a33a-e067-4e69-9c70-14005f41a2c6\nstruct MyType3{S,T}\n    a::S\n    b::T\nend\n\n# ╔═╡ 812149d8-0040-4d67-b2a2-f1304af4b225\nx_M2 = MyType3(1, 5.3)\n\n# ╔═╡ 75fa60fe-6583-4a6a-b6b0-06fb81006218\nmd\"\"\"\nNote that `x` and `y` have *different* types.\n\"\"\"\n\n# ╔═╡ 4146cf8f-ab2f-457d-97ef-e6d39e93246e\nmd\"\"\"\nWe can define functions acting on parametric types without necessarily talking about the type parameter:\n\"\"\"\n\n# ╔═╡ 3e61a354-ca21-410b-b422-92ea362b8c10\nmd\"\"\"\n#### Exercise 5\n\n1. Define a function that takes an object of type `MyType2`, *without* mentioning the type parameter, and returns the sum of the two fields.\n\n   What happens when you apply this function to `x` and `y`?\n   \n   \n2. Define a type `Dual2` with a type parameter `T` and the same functions `+` and `*` as before.\n\n\n3. Define the function `f(x) = x * x + x`. What happens if you pass in `Dual` numbers with different type parameters?\n\"\"\"\n\n# ╔═╡ 907f65aa-e1a1-4838-a1a0-cdaa0a1cfa45\nstruct DualReal\n    value::Real\n    deriv::Real\nend\n    \n\n# ╔═╡ fc5839ce-935a-46aa-bbe7-01f203b0fdb5\nDualReal(big(1.0), big\"1.4\")\n\n# ╔═╡ c445bab5-c012-4890-89bc-e7d6950fa7b4\nDualReal(3.1, big\"1.4\")\n\n# ╔═╡ 9008cc1d-e7c2-4b24-ad08-968c085baa36\nstruct DualUntyped\n    value\n    deriv\nend\n    \n\n# ╔═╡ d5cb6844-6f9d-422e-a241-96450aff70f5\nDualUntyped(\"hello\", \"David\")\n\n# ╔═╡ 7b2f03b4-d3dd-4fa6-a569-c878fc9f6557\nstruct DualBig\n    value::BigFloat\n    deriv::BigFloat\nend\n    \n\n# ╔═╡ 97097783-2948-4e9c-b769-8085c7943227\nbegin\n\tstruct Dual3{T<:Real}\n\t    a::T\n    \tb::T\n\tend\n\n\tDual3(a::Real, b::Real) = Dual3(promote(a, b))\n\n\t# Dual3(a::Real, b::Real) = Dual3(promote(a, b)...)\nend\n\n# ╔═╡ 4bdb5bfc-82c2-4de5-982a-4a69872749d1\nDual3(\"a\", \"b\")\n\n# ╔═╡ 9c05cca8-76d9-4abd-8774-28e7f41d3b09\nDual3(big\"1.0\", big\"1.4\")\n\n# ╔═╡ 05db96f7-3eeb-47aa-a4dc-dd67b0f02a2b\nDual3(1, 3.1)\n\n# ╔═╡ b490d647-85f5-4b82-ab29-2d18ce1c7db4\nmethods(Dual3)\n\n# ╔═╡ d981b89c-4833-4e38-9f80-246ed5f09445\nDual3(3, 4.5)\n\n# ╔═╡ 9bfe7470-afec-4a24-9f96-43272e2f9ecd\npromote(1, 3.4)\n\n# ╔═╡ 61cc131f-2d02-4de1-b79a-9105d6decc15\n@which promote_type(Int, Float64)\n\n# ╔═╡ a5c1c463-2393-499d-852c-16e69549819a\nComplex(3, 4.5)\n\n# ╔═╡ 749ba068-6deb-4a7d-a650-412e5fbdb670\n@which Complex(3, 4.5)\n\n# ╔═╡ 226f5af6-702f-431c-a269-5dd4cafa2699\nv = Dual(3, 4)\n\n# ╔═╡ c3831c37-8e09-4846-963d-27e1d4a824ac\nv isa Number\n\n# ╔═╡ fd8bf8f8-68dd-4925-aa9b-8eca1937c577\nsubtypes(Real)\n\n# ╔═╡ e3d64165-170e-4ee0-a9bc-ef759ce6afd7\nsubtypes(AbstractFloat)\n\n# ╔═╡ 713dc49e-6038-40b7-a917-299277f7ea7a\nsubtypes(Float64)\n\n# ╔═╡ 68d54b7c-4003-49e8-b2f9-666b882a5737\nisconcretetype(Float64)\n\n# ╔═╡ 7ae57ebb-d6bc-4b9b-913a-f9c4bb11d380\nq = 3.1\n\n# ╔═╡ 99dd8229-8658-4efe-9133-3eb8cd00b6b3\ntypeof(q)\n\n# ╔═╡ ef28ca54-38dd-4e8e-a5e8-897c802f81e1\nq isa AbstractFloat\n\n# ╔═╡ a31cfb26-9914-441c-aea8-6f341f2635fb\ngg(x::AbstractFloat) = sqrt(x)\n\n# ╔═╡ b05dcbc4-0149-48a3-8533-1bd6515d0b32\ngg(x::T) where {T <: AbstractFloat} = sqrt(x)\n\n# ╔═╡ f44efbd4-7ce2-44db-ac0e-eeb4aeafef70\ngg(π)\n\n# ╔═╡ 7df9a91e-01d4-471f-9ad5-55ac56c245d3\nstruct Hello{T}\n    a::T\n    b::T\n    c::T\nend\n\n# ╔═╡ ef1c3d05-7020-4339-b431-63ad63b244cc\nadd(x::Hello, y::Hello) = x.a + y.a, x.b + y.b, ...\n\n# ╔═╡ 186148a4-698e-460b-82dd-7b203698de45\nw = Hello(3, 4, 45)\n\n# ╔═╡ b9ac03c2-d93e-4372-a3cb-4568baf015bb\nmyfields = fieldnames(typeof(w))\n\n# ╔═╡ 522a7a5c-8400-4e1b-9ebd-6d76b33cb87f\ngetfield(w, :a)\n\n# ╔═╡ d70384a3-51fc-4f71-a3d6-d14b03719495\nx\n\n# ╔═╡ ab382c7f-933e-4611-af23-fe31967ff8cc\n[getfield(x, name) for name in myfields]\n\n# ╔═╡ 8df1bf08-5ee2-4cfe-a273-62c71dc9b8fb\nabstract type AbstractDual{S<:Real,T<:Real}\n\nstruct Dual5{S<:Real, T<:Real} <: AbstractDual{S,T}\n    a::S\n    b::T\nend\n\n# ╔═╡ babed906-7888-431b-8b11-d6e5889073fa\ngetfield.(myfields)\n\n# ╔═╡ d7e3e2b2-6f3f-4761-9141-924ae1448343\n\n\n# ╔═╡ ce4bd2c6-6269-47e3-8f43-50969a19487a\nx::Dual ^ n::Integer = ..\n\n# ╔═╡ 555aa973-a5ce-41f9-aab7-261a697758cc\n*(f::Dual, g::Dual) = Dual(f.value * g.value,\n                         f.value * g.deriv + f.deriv * g.value)\n\n# Alternatively and equivalently\n# *(f::Dual, g::Dual) = Dual(value(f) * value(g),\n#                          value(f) * deriv(g) + deriv(f) * value(g))\n\n# ╔═╡ eea59dfb-acc7-4d56-82b2-59f0ed40afc7\nimport Base: +, *\n\n# ╔═╡ b0c794fb-0d77-4667-9d47-0bcdfaa8fecb\nbegin\n\timport Base: ^\n\t^(x::Dual, n::Integer) = Base.power_by_squaring(x, n)\nend\n\n# ╔═╡ Cell order:\n# ╟─cac0bc38-ead9-4f99-a939-fc2645874efd\n# ╠═ecb2b8d9-ceda-4008-8137-b29bd7ef3ba9\n# ╟─b4f0668c-8b25-4588-9176-52bc7bfe797b\n# ╟─0ece0b55-ede7-4db1-9b48-61e1d4534761\n# ╟─6dcc01fe-c551-43d2-930b-ff1c93d15077\n# ╠═0d352bcc-dfc1-429f-ad6c-40dc8c4cd038\n# ╠═81863f06-8dac-48fd-a6e1-cf5df30c63f6\n# ╠═3de40205-6b5d-4d99-b886-1a1dc6a07955\n# ╠═d4c280cf-910c-4bbf-8dca-b01b14711296\n# ╠═7082e444-6268-4721-a278-2511a22daf68\n# ╠═43538919-4349-43f1-a196-759fe65d3be3\n# ╟─e0c1df0c-ff62-4982-8f3d-3ccbb44b8d2f\n# ╟─e6281275-0b87-47f4-a081-bb366ced3466\n# ╟─6056ff4a-858f-447c-85cc-0f3f6e0e53ca\n# ╟─db17c624-91b6-44b1-bd10-4d72f4cb9776\n# ╟─b3b15bf5-115d-4831-9115-36c88e9b899c\n# ╟─70843c81-6abe-40b2-8d0b-8d779fccedc8\n# ╠═82c79506-68ea-41dd-888d-840371c08430\n# ╟─291315e0-ad0e-4a57-b100-2baa5af04c04\n# ╟─f2421fbf-5cfc-4332-be60-b61fa4e02d8c\n# ╠═710612bd-4856-4e51-b2d6-2bdc972f196d\n# ╟─70eb5167-6288-4f84-b140-21b4b329cb45\n# ╠═9fb42f3c-c7ff-4f31-b5e6-9e96de16bac5\n# ╠═07808ac8-c910-4e92-ac34-c9ff225f4be8\n# ╟─8777c6a7-90e3-4dc7-ab61-3d12531f2ea9\n# ╠═5488c55f-8d0a-4c9b-8f8b-40ed4fe14e67\n# ╠═4f5e5eea-13df-477e-baea-c37ab6074aea\n# ╠═da932afe-990f-4ca7-aa81-9d85e1ca3bac\n# ╠═fac29cb2-dc57-4a06-9728-567169ac3768\n# ╠═4118613c-e58a-4f63-81d1-0e197e66cf98\n# ╠═ac8fa4de-d8ef-44f2-b709-aceb1e0ecb04\n# ╠═92aa5678-478c-4cb6-9187-3285534aac8c\n# ╠═04a21e57-a45c-4e4b-977a-42c6ee228b4a\n# ╠═915bfb27-7234-43ea-a052-093f89d7bdcd\n# ╟─9b213fb9-382a-4c5b-93fe-22252d29d0c6\n# ╟─8eed2b5c-dde2-437e-8383-4ed206ce72de\n# ╠═eea59dfb-acc7-4d56-82b2-59f0ed40afc7\n# ╠═62a97a4b-dfa6-404d-958b-b7b4ab7d25ca\n# ╠═9b0d361a-8c30-4ec0-a183-ac3890895f0e\n# ╠═9b8f41b5-9ade-4f34-8d09-cb548bd6c242\n# ╠═5b29f183-bda6-4ffb-bb78-5199980039d3\n# ╟─fc624260-ba8a-4057-8a1f-2659e2343654\n# ╠═abcbc0a1-33e7-430f-b0a8-e8b65c8666b2\n# ╠═17498a94-5db9-4c5e-9268-e588fddeae54\n# ╠═c847f0c2-1eac-4900-b80c-7f89846b2924\n# ╠═6caea9da-3edc-4309-bad8-f348693960b2\n# ╠═17cce3ab-1b4f-402d-bcc3-c7905360a441\n# ╠═526a204c-6a72-4cde-900a-568667e45c64\n# ╟─86aa82b1-caae-4124-b48a-14497420f471\n# ╟─e359dd62-65f0-4033-98c2-aff400ed0bb7\n# ╠═86141559-f6f4-43a6-8291-550adf31b25b\n# ╠═cee6af83-0079-4acd-9e14-cd7b7eb6947f\n# ╠═555aa973-a5ce-41f9-aab7-261a697758cc\n# ╠═4e222c6a-054b-41e6-bef4-b0726344ee94\n# ╟─a1b1b945-ba2e-4668-8698-4df02660d379\n# ╠═8857e0aa-da38-4ae6-8ef9-efa66dd51cfc\n# ╠═ad671591-a625-4de2-9b18-84c7773cb4b8\n# ╠═053e90a7-5fa6-4063-9634-63d48ee16690\n# ╠═d521f0e3-1636-4e8b-b8f3-639a90780690\n# ╟─b7b81d9d-354d-4ec0-b50c-302dbcb8f0c4\n# ╠═d67fa8a9-f43e-4eca-bb0e-1603c9f7da5d\n# ╟─3bc3d5a3-9b9f-4d07-9d59-f24d5c005038\n# ╟─fd34be78-af76-4d46-bdbd-19fd19155785\n# ╟─caccd695-118c-46a8-b59f-376e4cbc83ce\n# ╠═6418d0a4-8dd3-4816-8e5b-092cb769ebb6\n# ╠═8ebb42e9-11ec-434d-87c9-4259c26f6526\n# ╠═84b6a870-4515-4e6c-b306-d6b6d2a0fb8d\n# ╠═a0865cb0-7077-44ff-a130-eb73cbbc3179\n# ╠═f1fc7637-4804-4fc1-81ac-14874e66f9d6\n# ╠═ded7adc0-619f-4735-bd93-9c26c4c21858\n# ╠═1284374b-ab26-46b8-a74e-119655f5112e\n# ╠═420c0ef0-3f7e-4044-be30-c2873636c6e8\n# ╠═f426bed2-05f1-4598-9817-bb90262911ef\n# ╠═09bfa122-ca5b-4b4a-a9eb-09b1b5482a76\n# ╠═d08a434c-c816-4f43-9c93-2d0eda57723c\n# ╠═b0c794fb-0d77-4667-9d47-0bcdfaa8fecb\n# ╠═4e06b4f6-9753-4847-8c6c-120208520dc5\n# ╠═131373df-8e58-49b0-be5f-3cd8d8deb61d\n# ╠═76a7a87b-0283-4a85-9d88-0eec06ef689f\n# ╠═d608bc38-5653-4ad5-b6e4-6b2236299e4c\n# ╠═ce4bd2c6-6269-47e3-8f43-50969a19487a\n# ╟─bf697142-0eaf-4717-9434-eaa89946beb4\n# ╟─108212df-c86f-4b75-8576-65f3964687e9\n# ╟─eb94cc27-ac9e-4202-acdc-248809eebdb9\n# ╠═d7f6c80a-4922-42be-9bce-e493e603c373\n# ╟─70ec3ada-f7ae-4526-be35-5aa8cd4533ca\n# ╟─5011cf98-128e-4c94-bae0-109016427c50\n# ╟─d57937d8-3f1e-4f85-bf6b-afc8cfe3e99d\n# ╠═df1c033c-8a99-4b45-bc9c-3287a3a959ec\n# ╟─b0902a74-01e0-456a-a027-a5030d494d7f\n# ╟─9226e5a3-4445-4420-9b54-be31468e6b07\n# ╠═ccc258fa-c928-4175-a48e-bd72b7d22f31\n# ╠═c9f3dde8-7989-45e8-9831-894d82e57e90\n# ╠═2d3876d6-5fcf-4bfb-8dba-4bdf252c73fc\n# ╠═a0d7a33a-e067-4e69-9c70-14005f41a2c6\n# ╠═812149d8-0040-4d67-b2a2-f1304af4b225\n# ╟─75fa60fe-6583-4a6a-b6b0-06fb81006218\n# ╟─4146cf8f-ab2f-457d-97ef-e6d39e93246e\n# ╟─3e61a354-ca21-410b-b422-92ea362b8c10\n# ╠═907f65aa-e1a1-4838-a1a0-cdaa0a1cfa45\n# ╠═fc5839ce-935a-46aa-bbe7-01f203b0fdb5\n# ╠═c445bab5-c012-4890-89bc-e7d6950fa7b4\n# ╠═9008cc1d-e7c2-4b24-ad08-968c085baa36\n# ╠═d5cb6844-6f9d-422e-a241-96450aff70f5\n# ╠═7b2f03b4-d3dd-4fa6-a569-c878fc9f6557\n# ╠═97097783-2948-4e9c-b769-8085c7943227\n# ╠═4bdb5bfc-82c2-4de5-982a-4a69872749d1\n# ╠═9c05cca8-76d9-4abd-8774-28e7f41d3b09\n# ╠═05db96f7-3eeb-47aa-a4dc-dd67b0f02a2b\n# ╠═b490d647-85f5-4b82-ab29-2d18ce1c7db4\n# ╠═d981b89c-4833-4e38-9f80-246ed5f09445\n# ╠═9bfe7470-afec-4a24-9f96-43272e2f9ecd\n# ╠═61cc131f-2d02-4de1-b79a-9105d6decc15\n# ╠═a5c1c463-2393-499d-852c-16e69549819a\n# ╠═749ba068-6deb-4a7d-a650-412e5fbdb670\n# ╠═226f5af6-702f-431c-a269-5dd4cafa2699\n# ╠═c3831c37-8e09-4846-963d-27e1d4a824ac\n# ╠═fd8bf8f8-68dd-4925-aa9b-8eca1937c577\n# ╠═e3d64165-170e-4ee0-a9bc-ef759ce6afd7\n# ╠═713dc49e-6038-40b7-a917-299277f7ea7a\n# ╠═68d54b7c-4003-49e8-b2f9-666b882a5737\n# ╠═7ae57ebb-d6bc-4b9b-913a-f9c4bb11d380\n# ╠═99dd8229-8658-4efe-9133-3eb8cd00b6b3\n# ╠═ef28ca54-38dd-4e8e-a5e8-897c802f81e1\n# ╠═a31cfb26-9914-441c-aea8-6f341f2635fb\n# ╠═f44efbd4-7ce2-44db-ac0e-eeb4aeafef70\n# ╠═b05dcbc4-0149-48a3-8533-1bd6515d0b32\n# ╠═7df9a91e-01d4-471f-9ad5-55ac56c245d3\n# ╠═ef1c3d05-7020-4339-b431-63ad63b244cc\n# ╠═186148a4-698e-460b-82dd-7b203698de45\n# ╠═b9ac03c2-d93e-4372-a3cb-4568baf015bb\n# ╠═522a7a5c-8400-4e1b-9ebd-6d76b33cb87f\n# ╠═d70384a3-51fc-4f71-a3d6-d14b03719495\n# ╠═ab382c7f-933e-4611-af23-fe31967ff8cc\n# ╠═8df1bf08-5ee2-4cfe-a273-62c71dc9b8fb\n# ╠═babed906-7888-431b-8b11-d6e5889073fa\n# ╠═d7e3e2b2-6f3f-4761-9141-924ae1448343\n", "meta": {"hexsha": "5a8951b97c9543576c23e1990e60966e0b1a7447", "size": 21588, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2. Uses of types.jl", "max_stars_repo_name": "pleiby/intermediate_julia_2019", "max_stars_repo_head_hexsha": "190bfe012a1cf0c5a2c6d12f17b3239d6eae5506", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2. Uses of types.jl", "max_issues_repo_name": "pleiby/intermediate_julia_2019", "max_issues_repo_head_hexsha": "190bfe012a1cf0c5a2c6d12f17b3239d6eae5506", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2. Uses of types.jl", "max_forks_repo_name": "pleiby/intermediate_julia_2019", "max_forks_repo_head_hexsha": "190bfe012a1cf0c5a2c6d12f17b3239d6eae5506", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.109375, "max_line_length": 389, "alphanum_fraction": 0.7090050028, "num_tokens": 10986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.9161096101538325, "lm_q1q2_score": 0.755297493959518}}
{"text": "using Plots, StatsBase, Statistics, LaTeXStrings, JLD\n\nfunction InitialNetwork(dim, P)\n    Network = sample([-1,0], Weights([1-P, P]),(dim,dim))\n    return Network\nend\n\nfunction FindNeighbors(i, j, Network, dim)\n    Numbereds = 0\n    colorList = []\n    for neighbor in ([0,-1], [-1,0])\n        if j + neighbor[2] >= 1 && i + neighbor[1] >= 1 && Network[([i, j] + neighbor)...] > 0\n            push!(colorList,Network[([i, j] + neighbor)...])\n            Numbereds += 1\n        end\n    end\n    return colorList, Numbereds #colorList contain the node and its neighbors\nend\n\nfunction RecursionMapping(x, L)\n    while L[x] != L[L[x]]\n        x = L[x]\n    end\n    return L[x]\nend\n\nfunction CheckPercolation(dim, L, Network)\n    fside = []\n    lside = []\n    for i in 1:dim\n        if Network[i,dim] != -1\n            push!(lside, RecursionMapping(Network[i,dim],L))\n        end\n        if Network[i,1] != -1\n            push!(fside, RecursionMapping(Network[i,1],L))\n        end\n    end\n    RandomPoint = rand(Network)\n    if RandomPoint != -1 && RecursionMapping(RandomPoint,L) in intersect(fside,lside)\n        return 1\n    else\n        return 0\n    end\nend\n\nfunction HKNetworkDynamic(dim, P)\n    Network = InitialNetwork(dim, P)\n    S = []\n    L = []\n    k = 1\n\n    for j in 1:dim\n        for i in 1:dim\n            if Network[i,j] != 0\n                continue\n            end\n            NColor, NNum = FindNeighbors(i,j,Network,dim)\n            if NNum == 0\n                Network[i,j] = k\n                push!(L, k)\n                push!(S, 1)\n                k += 1\n            elseif NNum == 1\n                Network[i,j] = RecursionMapping(NColor[1],L)\n                S[RecursionMapping(NColor[1],L)] += 1\n            elseif NNum == 2 && RecursionMapping(NColor[1],L) == RecursionMapping(NColor[2],L)\n                Network[i,j] = RecursionMapping(NColor[1],L)\n                S[RecursionMapping(NColor[1],L)] += 1\n            else\n                S[RecursionMapping(NColor[1],L)] += 1 + S[RecursionMapping(NColor[2],L)]\n                S[RecursionMapping(NColor[2],L)] = 0\n                Network[i,j] = RecursionMapping(NColor[1],L)\n                L[NColor[2]] = RecursionMapping(NColor[1],L)\n            end\n        end\n    end\n    # return Network\n    return CheckPercolation(dim, L, Network)\nend\n\nHKNetworkDynamic(200, 0.6)\n\n\nPlist = hcat(0.5:0.01:1)\nAvglist = []\nSTDlist = []\nTotData = []\n\nfor P in Plist\n    print(\"\\r$P\")\n    AllRuns = []\n    for i in 1:10000\n        push!(AllRuns, HKNetworkDynamic(200, P))\n    end\n    push!(TotData, AllRuns)\n    push!(STDlist, std(AllRuns))\n    push!(Avglist, mean(AllRuns))\nend\n\nsave(\"200x200-HK.jld\", \"data\", TotData)\n\nscatter(Plist,\n    Avglist,\n    yerr = STDlist,\n    legend = nothing,\n    xlabel = L\"P\",\n    ylabel = L\"Avg\\ Q_{\\infty}\",\n    title = L\"Avg \\ Q_{\\infty} \\ for \\ 200\\times200 \\ Network\\ (10000 \\ runs)\")\nsavefig(\"../../Figs/Q6/200x200-10000.pdf\")\n", "meta": {"hexsha": "4d87be52af5cd3abecbda2af0510e66e043d8e31", "size": 2921, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSet3/Codes/Q7/Q7-HK.jl", "max_stars_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_stars_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSet3/Codes/Q7/Q7-HK.jl", "max_issues_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_issues_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSet3/Codes/Q7/Q7-HK.jl", "max_forks_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_forks_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-21T11:07:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-21T11:07:08.000Z", "avg_line_length": 26.5545454545, "max_line_length": 94, "alphanum_fraction": 0.5415953441, "num_tokens": 893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.755297490865086}}
{"text": "module KSVD\n\n# This is an implementation of the K-SVD algorithm.\n# The original paper:\n# K-SVD: An Algorithm for Designing Overcomplete Dictionaries\n# for Sparse Representation\n# http://www.cs.technion.ac.il/~freddy/papers/120.pdf\n\n# Variable names are based on the original paper.\n# If you try to read the code, I recommend you to see Figure 2 first.\n#\n\nexport ksvd, matching_pursuit\n\nusing ProgressMeter\nusing Base.Threads, Random, SparseArrays, LinearAlgebra\n\n\ninclude(\"matching_pursuit.jl\")\n\nconst default_sparsity_allowance = 0.9\nconst default_max_iter = 200\nconst default_max_iter_mp = 200\n\nRandom.seed!(1234)  # for stability of tests\n\n\nfunction error_matrix(Y::AbstractMatrix, D::AbstractMatrix, X::AbstractMatrix, k::Int)\n    # indices = [i for i in 1:size(D, 2) if i != k]\n    indices = deleteat!(collect(1:size(D, 2)), k)\n    return Y - D[:, indices] * X[indices, :]\nend\n\n\nfunction init_dictionary(n::Int, K::Int)\n    # D must be a full-rank matrix\n    D = rand(n, K)\n    while rank(D) != min(n, K)\n        D = rand(n, K)\n    end\n\n    @inbounds for k in 1:K\n        D[:, k] ./= norm(@view(D[:, k]))\n    end\n    return D\nend\n\n\nfunction ksvd(Y::AbstractMatrix, D::AbstractMatrix, X::AbstractMatrix)\n    N = size(Y, 2)\n    for k in 1:size(X, 1)\n        xₖ = X[k, :]\n        # ignore if the k-th row is zeros\n        all(iszero, xₖ) && continue\n\n        # wₖ is the column indices where the k-th row of xₖ is non-zero,\n        # which is equivalent to [i for i in N if xₖ[i] != 0]\n        wₖ = findall(!iszero, xₖ)\n\n        # Eₖ * Ωₖ implies a selection of error columns that\n        # correspond to examples that use the atom D[:, k]\n        Eₖ = error_matrix(Y, D, X, k)\n        Ωₖ = sparse(wₖ, 1:length(wₖ), ones(length(wₖ)), N, length(wₖ))\n        # Note that S is a vector that contains diagonal elements of\n        # a matrix Δ such that Eₖ * Ωₖ == U * Δ * V.\n        # Non-zero entries of X are set to\n        # the first column of V multiplied by Δ(1, 1)\n        U, S, V = svd(Eₖ * Ωₖ, full=true)\n        D[:, k] = U[:, 1]\n        X[k, wₖ] = V[:, 1] * S[1]\n    end\n    return D, X\nend\n\n\n\"\"\"\n    ksvd(Y::AbstractMatrix, n_atoms::Int;\n         sparsity_allowance::Float64 = $default_sparsity_allowance,\n         max_iter::Int = $default_max_iter,\n         max_iter_mp::Int = $default_max_iter_mp)\n\nRun K-SVD that designs an efficient dictionary D for sparse representations,\nand returns X such that DX = Y or DX ≈ Y.\n\n```\n# Arguments\n* `sparsity_allowance`: Stop iteration if the number of zeros in X / the number\n    of elements in X > sparsity_allowance.\n* `max_iter`: Limit of iterations.\n* `max_iter_mp`: Limit of iterations in Matching Pursuit that `ksvd` calls at\n    every iteration.\n```\n\"\"\"\nfunction ksvd(Y::AbstractMatrix, n_atoms::Int;\n              sparsity_allowance = default_sparsity_allowance,\n              max_iter::Int = default_max_iter,\n              max_iter_mp::Int = default_max_iter_mp)\n\n    K = n_atoms\n    n, N = size(Y)\n\n    if !(0 <= sparsity_allowance <= 1)\n        throw(ArgumentError(\"`sparsity_allowance` must be in range [0,1]\"))\n    end\n\n    X = spzeros(K, N)  # just for making X global in this function\n    max_n_zeros = ceil(Int, sparsity_allowance * length(X))\n\n    # D is a dictionary matrix that contains atoms for columns.\n    D = init_dictionary(n, K)  # size(D) == (n, K)\n\n    p = Progress(max_iter)\n\n    for i in 1:max_iter\n        X_sparse = matching_pursuit(Y, D, max_iter = max_iter_mp)\n        D, X = ksvd(Y, D, Matrix(X_sparse))\n\n        # return if the number of zero entries are <= max_n_zeros\n        if sum(iszero, X) > max_n_zeros\n            return D, X\n        end\n        next!(p)\n    end\n    return D, X\nend\n\nend # module\n", "meta": {"hexsha": "37811a8d42a25358b88680d9fe9b01be0a166858", "size": 3693, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/KSVD.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/KSVD.jl-80e3a25a-59dd-53ce-a95c-a94c81a42368", "max_stars_repo_head_hexsha": "fac7875b0fa77eade1e9322c51c590c4be0bf43c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-09-26T19:42:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T20:30:00.000Z", "max_issues_repo_path": "src/KSVD.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/KSVD.jl-80e3a25a-59dd-53ce-a95c-a94c81a42368", "max_issues_repo_head_hexsha": "fac7875b0fa77eade1e9322c51c590c4be0bf43c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-04-16T06:22:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:26:32.000Z", "max_forks_repo_path": "src/KSVD.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/KSVD.jl-80e3a25a-59dd-53ce-a95c-a94c81a42368", "max_forks_repo_head_hexsha": "fac7875b0fa77eade1e9322c51c590c4be0bf43c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-10-09T07:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-16T06:11:56.000Z", "avg_line_length": 28.8515625, "max_line_length": 86, "alphanum_fraction": 0.6311941511, "num_tokens": 1098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7552974891513591}}
{"text": "\"\"\"\n    eom_rossler_lorenz() -> Function\n\nEquations of motions for a 6D unidirectionally coupled Rössler-Lorenz system.\nThe 3D Rössler attractor is coupled to  a 3D Lorenz attractor such that the\nsecond component  (``x_2``) of the Rössler system unidirectionally forces\nthe second component (``y_2``) of the Lorenz system. This example is from [1].\n\nThe implementation here allows for tuning the parameters of each subsystem by\nintroducing the constants `a₁`, `a₂`, `a₃`, `b₁`, `b₂`, `b₃`. The default\nvalues of these constants are as defined in Krakovská et al. (2018).\n\nThe dynamics is generated by the vector field:\n\n```math\n\\\\begin{aligned}\n\\\\dot x_1 &= a_1(x_2 + x_3) \\\\\n\\\\dot x_2 &= a_2(x_1 + 0.2x_2) \\\\\n\\\\dot x_3 &= a_2(0.2 + x_3(x_1 - a_3)) \\\\\n\\\\dot y_1 &= b_1(y_2 - y_1) \\\\\n\\\\dot y_2 &= y_1(b_2 - y_3) - y_2 +c(x_2)^2 \\\\\n\\\\dot y_3 &= y_1y_2 - b_3y_3\n\\\\end{aligned}\n```\n\nwith the coupling constant ``c \\\\geq 0``.\n\n# References\n[Krakovská, Anna, et al. \"Comparison of six methods for the detection of causality in a bivariate time series.\" Physical Review E 97.4 (2018):042207](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.97.042207)\n\"\"\"\nfunction eom_rossler_lorenz(u, p, t)\n    a₁, a₂, a₃, b₁, b₂, b₃, c = (p...,)\n    x₁, x₂, x₃, y₁, y₂, y₃ = (u...,)\n\n    dx₁ = a₁*(x₂ + x₃)\n    dx₂ = a₂*(x₁ + 0.2*x₂)\n    dx₃ = a₂*(0.2 + x₃*(x₁ - a₃))\n    dy₁ = b₁*(y₂ - y₁)\n    dy₂ = y₁*(b₂ - y₃) - y₂ + c*x₂^2\n    dy₃ = y₁*y₂ - b₃*y₃\n    return SVector{6}(dx₁, dx₂, dx₃, dy₁, dy₂, dy₃)\nend\n\nfunction rossler_lorenz(u₀, a₁, a₂, a₃, b₁, b₂, b₃, c)\n    p = [a₁, a₂, a₃, b₁, b₂, b₃, c]\n    ContinuousDynamicalSystem(eom_rossler_lorenz, u₀, p)\nend\n\n\"\"\"\n    rossler_lorenz(;u₀ = rand(6), a₁ = -6, a₂ = 6, a₃ = 2.0,\n        b₁ = 10, b₂ = 28, b₃ = 8/3, c = 2) -> ContinuousDynamicalSystem\n\nInitialise a Rössler-Lorenz system consisting of two independent 3D subsystems:\none Rössler attractor and one Lorenz attractor. They are coupled such that the\nsecond component (`x₂`) of the Rössler system unidirectionally forces the\nsecond component (`y₂`) of the Lorenz system.\n\nThe implementation here allows for tuning the parameters of each subsystem by\nintroducing the constants `a₁`, `a₂`, `a₃`, `b₁`, `b₂`, `b₃`. The default\nvalues are as in Krakovská et al. (2018).\n\nThe dynamics is generated by the vector field:\n\n```math\n\\\\begin{aligned}\n\\\\dot x_1 &= a_1(x_2 + x_3) \\\\\n\\\\dot x_2 &= a_2(x_1 + 0.2x_2) \\\\\n\\\\dot x_3 &= a_2(0.2 + x_3(x_1 - a_3)) \\\\\n\\\\dot y_1 &= b_1(y_2 - y_1) \\\\\n\\\\dot y_2 &= y_1(b_2 - y_3) - y_2 +c(x_2)^2 \\\\\n\\\\dot y_3 &= y_1 y_2 - b_3y_3\n\\\\end{aligned}\n```\n\nwith the coupling constant ``c \\\\geq 0``.\n\n# References\n[Krakovská, Anna, et al. \"Comparison of six methods for the detection of causality in a bivariate time series.\" Physical Review E 97.4 (2018):042207](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.97.042207)\n\"\"\"\nrossler_lorenz(;u₀ = rand(6), a₁ = -6, a₂ = 6, a₃ = 2.0, b₁ = 10, b₂ = 28, b₃ = 8/3, c = 2) =\n    rossler_lorenz(u₀, a₁, a₂, a₃, b₁, b₂, b₃, c)\n", "meta": {"hexsha": "04ef84453be603f2d69ef93869bd6f7eb9a0220d", "size": 2989, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/systems/continuous_systems/rosslerlorenz.jl", "max_stars_repo_name": "tormolle/CausalityTools.jl", "max_stars_repo_head_hexsha": "b8c1014349358d8cdb5eddc1bcac9303f475d90b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/systems/continuous_systems/rosslerlorenz.jl", "max_issues_repo_name": "tormolle/CausalityTools.jl", "max_issues_repo_head_hexsha": "b8c1014349358d8cdb5eddc1bcac9303f475d90b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/systems/continuous_systems/rosslerlorenz.jl", "max_forks_repo_name": "tormolle/CausalityTools.jl", "max_forks_repo_head_hexsha": "b8c1014349358d8cdb5eddc1bcac9303f475d90b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4512195122, "max_line_length": 215, "alphanum_fraction": 0.6543994647, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7552974852873706}}
{"text": "include(\"kepler_eqn.jl\")\n\nfunction calc_true_anom(ecc_anom::Real, e::Real)\n\ttrue_anom = 2*atan(sqrt((1+e)/(1-e))*tan(ecc_anom/2))\nend\n\nbegin\n\t\"\"\" Calculate RV from t, P, K, e, ω and M0\t\"\"\"\n\tfunction calc_rv_keplerian end\n\tcalc_rv_keplerian(t, p::Vector) = calc_rv_keplerian(t, p...)\n\tfunction calc_rv_keplerian(t, P,K,e,ω,M0)\n\t\tmean_anom = t*2π/P-M0\n\t\tecc_anom = calc_ecc_anom(mean_anom,e)\n\t\ttrue_anom = calc_true_anom(ecc_anom,e)\n\t\trv = K/sqrt((1-e)*(1+e))*(cos(ω+true_anom)+e*cos(ω))\n\tend\nend\n", "meta": {"hexsha": "c5b50114a84b7b06c87c13618025f0b36a8258f3", "size": 495, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/calc_rv.jl", "max_stars_repo_name": "PsuAstro528/lab5-start", "max_stars_repo_head_hexsha": "97b929ad694b128eee28b20fb2699dcc082585ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-20T16:13:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-20T16:13:22.000Z", "max_issues_repo_path": "src/calc_rv.jl", "max_issues_repo_name": "PsuAstro528/lab5-start", "max_issues_repo_head_hexsha": "97b929ad694b128eee28b20fb2699dcc082585ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-30T17:35:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-30T17:36:57.000Z", "max_forks_repo_path": "src/calc_rv.jl", "max_forks_repo_name": "PsuAstro528/lab5-start", "max_forks_repo_head_hexsha": "97b929ad694b128eee28b20fb2699dcc082585ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5, "max_line_length": 61, "alphanum_fraction": 0.6909090909, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7552617823046842}}
{"text": "# use Convex to get access to its types and functions\nusing Convex\n\n# import reshape to extend it.\nimport Base.reshape\n\nexport partialtransposematrix, partialtranspose, partialtransposenaive\n\n# switch between coordinates of a matrix and its vectorised form\nvecCoordToMatrixCoord(k::Integer, n::Integer) = (1 + (k-1)%n, round(Int, 1+floor((k-1)/n)%n))\nmatrixCoordToVecCoord(i::Integer, j::Integer, n::Integer) = i + (j-1)*n\n\n\n#Determine the new coordinates `(x, y)` of an entry\n#with coordinates `(i, j)` after partial transposition.\n\nfunction partialtranseposecoord(i::Integer, j::Integer, n::Integer, l::Integer)\n  @assert n % l == 0 \"l should divide n\"\n  @assert n ≥ l \"n should be greater than l\"\n\n  # calculate which block (i, j) is in\n  a = floor(Int, (i-1)/l)+1\n  b = floor(Int, (j-1)/l)+1\n\n  x = j + (a-b)*l\n  y = i + (b-a)*l\n\n  @assert x > 0\n  @assert y > 0\n  @assert n ≥ x\n  @assert n ≥ y\n\n  return (x, y)\nend\n\n\n#Construct a permutation matrix for a `n × n` matrix\n#in vector form where we transpose in `l × l` blocks.\n\nfunction partialtransposematrix(n::Integer, l::Integer)\n  @assert n % l == 0 \"l should divide n\"\n  @assert n ≥ l \"n should be greater than l\"\n\n  # Julia will iterate over I and J simulatiously\n  # and set (I[k], J[k]) to 1 in the returned matrix\n  # The value in I corresponds to the vectorised coordinates\n  # before partial transposition, whereas the value in J\n  # corresponds to the coordinates after partial transposition.\n  IM = Array(Int, n^2)\n  JM = Array(Int, n^2)\n  index = 1\n  for i in 1:n\n    for j in 1:n\n      (x, y) = partialtranseposecoord(i, j, n, l)\n      IM[index] = matrixCoordToVecCoord(i, j, n)\n      JM[index] = matrixCoordToVecCoord(x, y, n)\n      index += 1\n    end\n  end\n\n  return sparse(IM, JM, 1)\nend\n\n\"\"\" `rhoOut = partialtranspose(rho)` or `rhoOut = partialtranspose(rho, sys)` or `rhoOut = partialtranspose(rho, sys, dim)`\n\nApplies the partial tanspose to the matrix *rho*.\n\nInputs:\n- *rho* input matrix\n- *systems* (optional) single system or a vector of systems to be transposed. By default it is equal to 2. If *dim* is not provided, the only two possible values of *systems* are 1 or 2.\n- *dim* (optional) vector with dimensions of the systems. By default it assumes two systems of equal dimensions.\n\nOutputs:\n- *rhoOut* matrix *rho* with partial transpose applied\n\"\"\"\nfunction partialtranspose(ρ::Union{AbstractArray, AbstractExpr}, systems::Vector, dim::Vector)\n  result = ρ\n  for sys in systems\n    result = partialtranspose(result, sys, dim)\n  end\n  return result\nend\n\n#Apply the partial tanspose to a single sytem. If no\n#dimensions are specified, it will assume there are\n#two systems of identical dimension. If no system is\n#specified, it will transpose the last system. This\n#will always be the second system, because it's not\n#possible to leave out the system while providing\n#the dimensions.\n\nfunction partialtransposesystem(ρ::Union{AbstractArray, AbstractExpr}, sys::Integer = 2, dim::Vector = [])\n  # do naive partial transposition\n  if dim == []\n    l = round(Int, sqrt(size(ρ)[1]))\n    if sys == 2\n      return partialtranspose(ρ, l, naive = true)\n    else\n      dim = [l; l]\n    end\n  end\n\n\n  @assert 1 ≤ sys ≤ length(dim) \"System doesnt exist, expected sys to be between 1 and \", length(dim), \". Is your dim vector correct?\"\n\n  # permute systems such that the system to apply PT is last\n  perm = collect(1:length(dim))\n  deleteat!(perm, sys)\n  push!(perm, sys)\n\n  l = dim[sys]\n  x = permutesystems(ρ, perm, dim)\n  y = partialtransposenaive(x, l)\n  z = permutesystems(y, perm, dim)\n  return z\nend\n\n\n#Apply partial transpose on systems if naive is false.\n#Otherwise do the naive partial transpose in blocks\n#of `l × l`, where `l` takes the value `systems`.\n#This is equivalent to applying the partial\n#transepose to the last system if that particular system\n#has dimension `l`.\n\nfunction partialtranspose(ρ::Union{AbstractArray, AbstractExpr}, systems::Integer = 2, dim::Vector = []; naive::Bool = false)\n  if naive\n    return partialtransposenaive(ρ, systems)\n  end\n\n  return partialtransposesystem(ρ, systems, dim)\nend\n\n\n\n#This does the naive version of the partial transpose\n#that I wrote first it simply applies a transpose in blocks\n#of `l × l`. This is equivalent to applying the partial\n#transepose to the last system if that particular system\n#has dimension `l`.\n\nfunction partialtransposenaive(ρ::Union{AbstractExpr, AbstractArray, Convex.Variable}, l::Integer)\n  # if the input is sparse, keep the output sparse as well\n  if !isa(ρ, Convex.Variable) && !isa(ρ, AbstractExpr) && issparse(ρ)\n    vectorised = sparsevec(ρ)\n  else\n    vectorised = vec(ρ)\n  end\n  n = size(ρ)[1]\n\n  @assert n % l == 0 \"l should divide n\"\n  @assert n ≥ l \"n should be greater than l\"\n\n  return reshape(partialtransposematrix(n, l) * vectorised, n, n)\nend\n\n# some aliases for convenience\nmatrixCoordToVecCoord(ij::Tuple{Int, Int}, n::Integer) = matrixCoordToVecCoord(ij[1], ij[2], n)\npartialtranseposecoord(ij::Tuple{Int, Int}, n::Integer, l::Integer) = partialtranseposecoord(ij[1], ij[2], n, l)\nreshape(x::AbstractExpr, mn::Tuple{Int, Int}) = reshape(x, mn[1], mn[2])\n", "meta": {"hexsha": "6343d1fedd4552f8f85146dd9ea9e00945d5cad7", "size": 5135, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/partialtranspose.jl", "max_stars_repo_name": "StephanieWehner/EntanglementDist.jl", "max_stars_repo_head_hexsha": "38918843ac6866d072185e1ee9bf411c406aed48", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-07T15:10:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T15:10:32.000Z", "max_issues_repo_path": "src/partialtranspose.jl", "max_issues_repo_name": "StephanieWehner/EntanglementDist.jl", "max_issues_repo_head_hexsha": "38918843ac6866d072185e1ee9bf411c406aed48", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/partialtranspose.jl", "max_forks_repo_name": "StephanieWehner/EntanglementDist.jl", "max_forks_repo_head_hexsha": "38918843ac6866d072185e1ee9bf411c406aed48", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-06-12T13:33:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T18:42:48.000Z", "avg_line_length": 31.8944099379, "max_line_length": 186, "alphanum_fraction": 0.700097371, "num_tokens": 1508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7551914542089263}}
{"text": "using Turing, ReverseDiff, Memoization\nusing DifferentialEquations\nusing Plots\nusing Statistics\nusing StatsPlots\nusing DataFrames\nusing CSV\nTuring.setadbackend(:reversediff)\nTuring.setrdcache(true)\nTuring.turnprogress(true)\nusing Distributions\nusing LinearAlgebra\n\n# here we are simulating the signal of two coupled oscillators\n# with amplitudes A1 and A2 of kBT/k and kBT/(k+c) where c is the coupling constant\n# D = kBT/gamma\n# in terms of the standard parameters of a OU process:\n# sigma = sqrt(2*D)\n# Theta = D/A\n\nfunction corr_osc(c)\n    # function that returns two time series that are correlated through a coupling coefficient c\n    μ = 0.0 # mean is zero\n    σ = sqrt(2) # D=1\n    Θ1 = 1.0\n    Θ2 = 1.0+abs(c)\n\n    W1 = OrnsteinUhlenbeckProcess(Θ1,μ,σ,0.0,1.0)\n    W2 = OrnsteinUhlenbeckProcess(Θ2,μ,σ,0.0,1.0)\n    prob1 = NoiseProblem(W1,(0.0,100.0))\n    prob2 = NoiseProblem(W2,(0.0,100.0))\n    sol1 = solve(prob1;dt=0.1)\n    sol2 = solve(prob2;dt=0.1)\n\n    # creating the two correlated\n    x1 = (sol1.u .+ sol2.u)/2\n    if c>0 \n        x2 = (sol1.u .- sol2.u)/2\n    else\n        x2 = (sol2.u .- sol1.u)/2\n    end\n    return x1,x2\nend\n\n# Ornstein-Uhlenbeck process\n@model ou(rn,T,delta_t) = begin\n    ampl ~ Uniform(0.0,5.0)\n    b ~ beta(5.0,1.0)\n    \n    rn[1] ~ Normal(0,sqrt(ampl))\n    \n    for i=2:T\n        rn[i] ~ Normal(rn[i-1]*b,sqrt(ampl*(1-b^2)))\n    end\nend\n\n# Ornstein-Uhlenbeck process with added Gaussian noise\n@model oupn(rn,T,delta_t,::Type{R}=Vector{Float64}) where {R} = begin\n    ampl ~ Uniform(0.0,5.0)\n    b ~ Beta(5.0,1.0)\n    noise_ampl ~ Uniform(0.0,1)\n    \n    b = exp(-delta_t/tau)\n    r = R(undef, T)\n    \n    r[1] ~ Normal(0,sqrt(ampl))\n    \n    for i=2:T\n        r[i] ~ Normal(r[i-1]*b,sqrt(ampl*(1-b^2)))\n    end\n    rn ~ MvNormal(r,sqrt(noise_ampl))\nend\n\n@model ou_corr(rn1,rn2,T,delta_t) = begin\n    ampl1 ~ Uniform(0.0,5.0)\n    ampl2 ~ Uniform(0.0,5.0)\n    d ~ Uniform(0.0,5.0)\n    b1 = exp(-delta_t*d/ampl1)\n    b2 = exp(-delta_t*d/ampl2)\n\n    rn1[1] ~ Normal(0,sqrt(ampl1))\n    rn2[1] ~ Normal(0,sqrt(ampl2))   \n\n    for i=2:T\n        rn1[i] ~ Normal(rn1[i-1]*b1,sqrt(ampl1*(1-b1^2)))\n        rn2[i] ~ Normal(rn2[i-1]*b2,sqrt(ampl2*(1-b2^2)))\n    end\nend\n\n# here we would like to run MCMC on several artificial data sets with varying correlation coefficients\n# we should test rho from -0.9 to 0.9\nrho_list = -0.9:0.1:0.9\nresults = DataFrame(rho = Float64[], coupling = Float64[], pearson = Float64[], c = Float64[], dc = Float64[])\ntries = 5\nfor rho in rho_list\n    coupling = 2*abs(rho)/(1-abs(rho))*sign(rho)\n    println(\"coupling: \",coupling,\" rho: \",rho)\n    # do rho tries times\n    for i in 1:tries\n        x1, x2 = corr_osc(coupling)\n        pearson = Statistics.cor(x1,x2)\n        println(\"Pearson: \",pearson)\n\n        # lets see whether we can estimate c from the data\n        y1 = x1 .+ x2\n        y2 = x1 .- x2\n\n        # Ornstein-Uhlenbeck process of two coupled oscillators\n        model_fct = ou_corr(y1,y2,length(y1),0.1)\n        chn = sample(model_fct, NUTS(0.65), 5000)\n#        Turing.emptyrdcache()\n\n        print(describe(chn))\n        println(chn)\n        ampl1 = Array(chn[:ampl1])\n        ampl2 = Array(chn[:ampl2])\n\n        a1 = std(ampl1)\n        a2 = std(ampl2)\n\n        if a1>a2\n            c = (ampl1 .- ampl2)./ampl2\n        else\n            c = (ampl1 .- ampl2)./ampl1\n        end\n        c_mean = mean(c)\n        dc = std(c)\n\n        println(\"A1,A2: \",a1,\",\",a2)\n        println(\"c estimate: \",c_mean,\"std: \",dc)\n\n        push!(results,[rho,coupling,pearson,c_mean,dc])\n    end\nend\nprintln(results)\nCSV.write(\"results2.csv\",results)\n\n", "meta": {"hexsha": "95c04a87ad47167c5a37545a6f956223e47ca5cc", "size": 3611, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CorrelationBatch.jl", "max_stars_repo_name": "laofei177/Ornstein-Uhlenbeck-AddedNoise", "max_stars_repo_head_hexsha": "1ad2e21e1def0ce1724b5a976d2c1ff339db3fe7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-29T02:27:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T02:27:46.000Z", "max_issues_repo_path": "CorrelationBatch.jl", "max_issues_repo_name": "laofei177/Ornstein-Uhlenbeck-AddedNoise", "max_issues_repo_head_hexsha": "1ad2e21e1def0ce1724b5a976d2c1ff339db3fe7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CorrelationBatch.jl", "max_forks_repo_name": "laofei177/Ornstein-Uhlenbeck-AddedNoise", "max_forks_repo_head_hexsha": "1ad2e21e1def0ce1724b5a976d2c1ff339db3fe7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1666666667, "max_line_length": 110, "alphanum_fraction": 0.602603157, "num_tokens": 1301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7551914485083682}}
{"text": "#!/usr/bin/env julia\n# -*- coding: utf-8 -*-\n#=\nApply HANTS process on an integer array\n=#\ncd(dirname(@__FILE__))\ninclude(\"../HANTS.jl\")\nusing .HANTS, Plots\n\ny = [\n     559,  370,  626, 1201, 1782, 2444, 2131, 4946,\n    3287, 5617, 3803, 6412, 5324, 8277, 6540, 8166,\n    6114, 6615, 3980, 3398, 1139,  867,  586\n]\n\nnbase = 365\nnfreq = 3\ntseries = 1:16:365\nvalidrange = (-10000, 10000)\nfet = 0.02\ndod = 5\nδ = 0.1\n\nA, φ, yrec = hants(\n    y, fet, dod, δ; nbase=nbase, nfreq=nfreq, validrange=validrange, tseries=tseries, outlier=nothing\n)\ny_reconstruct = reconstruct(A, φ, nbase)\n\nA_Hi, φ_Hi, yrec_Hi = hants(\n    y, fet, dod, δ; nbase=nbase, nfreq=nfreq, validrange=validrange, tseries=tseries, outlier=:Hi\n)\ny_reconstruct_Hi = reconstruct(A_Hi, φ_Hi, nbase)\n\nA_Lo, φ_Lo, yrec_Lo = hants(\n    y, fet, dod, δ; nbase=nbase, nfreq=nfreq, validrange=validrange, tseries=tseries, outlier=:Lo\n)\ny_reconstruct_Lo = reconstruct(A_Lo, φ_Lo, nbase)\n\nfig1 = plot(tseries, y, lc=:black, label=\"Original Data\", shape=:circle, mc=:black)\nplot!(tseries, yrec, lc=:blue, label=\"HANTS - None\", shape=:circle, mc=:blue)\nplot!(tseries, yrec_Hi, lc=:red, label=\"HANTS - Hi\", shape=:circle, mc=:red)\nplot!(tseries, yrec_Lo, lc=:green, label=\"HANTS - Lo\", shape=:circle, mc=:green)\ntitle!(\"Testing HANTS Algorithm\")\n\nfig2 = plot(tseries, y, lc=:black, label=\"Original Data\", shape=:circle, mc=:black)\nplot!(1:365, y_reconstruct, lc=:blue, label=\"HANTS - None\")\nplot!(1:365, y_reconstruct_Hi, lc=:red, label=\"HANTS - Hi\")\nplot!(1:365, y_reconstruct_Lo, lc=:green, label=\"HANTS - Lo\")\ntitle!(\"Testing HANTS Reconstruct\")\n\nplot(fig1, fig2; layout=(1, 2), size=(800,300))\n", "meta": {"hexsha": "5a577378fe02b4ed49f5e9bd80d50e6a9ac77bd6", "size": 1646, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_int.jl", "max_stars_repo_name": "shenrq/JuliaHANTS", "max_stars_repo_head_hexsha": "20e930487b1da73a93696cd5bcfb6f8221f8388a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-29T14:45:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-29T14:45:55.000Z", "max_issues_repo_path": "test/test_int.jl", "max_issues_repo_name": "shenrq/HANTS.jl", "max_issues_repo_head_hexsha": "20e930487b1da73a93696cd5bcfb6f8221f8388a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_int.jl", "max_forks_repo_name": "shenrq/HANTS.jl", "max_forks_repo_head_hexsha": "20e930487b1da73a93696cd5bcfb6f8221f8388a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6538461538, "max_line_length": 101, "alphanum_fraction": 0.6767922236, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7551914480388637}}
{"text": "# # clip-11-16.jl\n\n# Load Julia packages (libraries) needed  for the snippets in chapter 0\n\nusing StatisticalRethinking, Optim\n#gr(size=(600,600));\n\n# ### snippet 3.11\n\np_grid = range(0, step=0.001, stop=1)\nprior = ones(length(p_grid))\nlikelihood = [pdf(Binomial(3, p), 3) for p in p_grid]\nposterior = likelihood .* prior\nposterior = posterior / sum(posterior)\n\n# Draw 10000 samples from this posterior distribution\n\nN = 10000\nsamples = sample(p_grid, Weights(posterior), N);\n\n# In StatisticalRethinkingJulia samples will always be stored\n# in an MCMCChains.Chains object. \n\nchn = MCMCChains.Chains(reshape(samples, N, 1, 1), [\"toss\"]);\n\n# ### snippet 3.12\n\nMCMCChains.describe(chn)\n\n# ### snippet 3.13\n\nMCMCChains.hpd(chn, alpha=0.5)\n\n# ### snippet 3.14\n\nmode(samples)\n\n# ### snippet 3.15\n\nmean(samples)\n\n# ### snippet 3.16\n\nmedian(samples)\n\n# End of `03/clip-11-16.jl`", "meta": {"hexsha": "696cddb6d568ffdfe9ed64f24ce3e0face8a89e7", "size": 870, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/03/clip-11-16.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_stars_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/03/clip-11-16.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_issues_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/03/clip-11-16.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_forks_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9130434783, "max_line_length": 71, "alphanum_fraction": 0.6977011494, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7551914466081819}}
{"text": "import PyPlot\nconst plt = PyPlot\n\nfunction eval_LF1d_p( α::Int64, L::Float64, grid_x::Array{Float64}, x)\n    Nbasis = size(grid_x)[1]\n    N = (Nbasis-1)/2\n    f = 0.0\n    for l = 1:Nbasis\n        k = -N + (l-1)\n        f = f + sqrt(1/L/Nbasis)*cos(2*pi*k*(x-grid_x[α])/L)\n    end\n    return f\nend\n\nfunction gen_T_matrix( L::Float64, grid_x::Array{Float64} )\n    Nbasis = size(grid_x)[1]\n    N = (Nbasis-1)/2\n    # Transformation matrix\n    T = Array{Complex128}(Nbasis,Nbasis)\n    for α = 1:Nbasis\n        for l = 1:Nbasis\n            k = -N + (l-1)\n            x = grid_x[α]\n            T[α,l] = sqrt(1/Nbasis)*exp(2*pi*im*k*x/L)\n        end\n    end\n    return T\nend\n\n# Example periodic function\nfunction myfunc(L::Float64, x::Float64)\n    ω = 2*pi/L\n    f = cos(ω*x)*sin(2*ω*x)\n    return f\nend\n\nfunction do_plot_myfunc( NptsPlot::Int64, L::Float64, lim )\n    NptsPlot = 200\n    x = Array{Float64}(linspace(lim[1], lim[2],NptsPlot));\n    y = Array{Float64}(NptsPlot)\n    for i = 1:NptsPlot\n        y[i] = myfunc(L,x[i])\n    end\n    plt.clf()\n    plt.grid()\n    plt.plot(x,y)\n    plt.savefig(\"myfunc.png\", dpi=300)\nend\n\nfunction eval_from_ex_coefs( ex_coef::Array{Float64},\n        L::Float64, grid_x::Array{Float64}, x::Float64 )\n    Nbasis = size(ex_coef)[1]\n    f = 0.0\n    for i = 1:Nbasis\n        f = f + ex_coef[i]*eval_LF1d_p( i, L, grid_x, x )\n    end\n    return f\nend\n\nfunction eval_FBR( l::Int64, L::Float64, N::Int64, x )\n    k = -N + (l-1)\n    f = 1/sqrt(L) * exp(im*2*pi*k*x/L)\n    return f\nend\n\nfunction FBR_eval_from_ex_coefs( ex_coef, L, x )\n    Nbasis = size(ex_coef)[1]\n    N = Int64( (Nbasis-1)/2 )\n    f = 0.0 + im*0.0\n    for i = 1:Nbasis\n        f = f + ex_coef[i]*eval_FBR( i, L, N, x )\n    end\n    return f\nend\n\n#function eval_DVR_from_FBR( α, T, x )\n#    Nbasis = size(T)[1]\n#    f = 0.0 + im*0.0\n#    for l = 1:Nbasis\n#        f = f + T'[l,α]*eval_FBR()\n#    end\n#end\n\nfunction main(L::Float64, N::Int64)\n    @printf(\"L = %f\\n\", L)\n    @printf(\"N = %d\\n\", N)\n    Nbasis = 2*N + 1\n    @printf(\"Nbasis = %d\\n\", Nbasis)\n    # Create grid\n    grid_x = Array{Float64}(Nbasis)\n    for α = 1:Nbasis\n        grid_x[α] = L/Nbasis*(α-N-1)\n    end\n    Δ = L/Nbasis\n\n    f1 = eval_LF1d_p( 1, L, grid_x, grid_x[2] )\n    f2 = eval_LF1d_p( 2, L, grid_x, grid_x[2] )\n    println(\"\\nShould be close to zero: \", f1)\n    println(\"\\nShould be close to one: \", f2*sqrt(Δ))\n\n    T = gen_T_matrix(L, grid_x)\n    print(\"\\nShould be close to zero: \")\n    println(sum(abs.(T'-inv(T)))/Nbasis^2)\n\n    ex_coefs = Array{Float64}(Nbasis)\n    for i = 1:Nbasis\n        ex_coefs[i] = myfunc(L, grid_x[i])\n    end\n\n    x = 2.0\n    println(\"\\nShould be close to each other:\")\n    println( myfunc(L, x) )\n    println( eval_from_ex_coefs(ex_coefs*sqrt(Δ), L, grid_x, x) )\n\n    FBR_ex_coefs = inv(T)*ex_coefs*sqrt(Δ)\n    println( FBR_eval_from_ex_coefs(FBR_ex_coefs, L, x) )\n\n    # FBR_ex_coefs = ifft(ex_coefs)\n    # println( FBR_eval_from_ex_coefs(FBR_ex_coefs, L, x) )\n\nend\n\nmain(10.0, 30)\n", "meta": {"hexsha": "43b1d4a1f7b9e842d61a169ecd8fe26873e8074b", "size": 2982, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LF/LeeTuckerman2006/main_LeeTuckerman2006.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "LF/LeeTuckerman2006/main_LeeTuckerman2006.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LF/LeeTuckerman2006/main_LeeTuckerman2006.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 24.0483870968, "max_line_length": 70, "alphanum_fraction": 0.5707578806, "num_tokens": 1149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7551914418688006}}
{"text": "# General math functions of quaternions\n\n\"\"\"\n    abs2(q)\n\nSum the squares of the components of the quaternion\n\n# Examples\n```jldoctest\njulia> abs2(Quaternion(1,2,4,10))\n121\n```\n\"\"\"\nBase.abs2(q::AbstractQuaternion) = sum(q.components.^2)\nBase.abs2(q::Rotor{T}) where {T<:Real} = one(T)\n\n\"\"\"\n    abs(q)\n\nSquare-root of the sum the squares of the components of the quaternion\n\n# Examples\n```jldoctest\njulia> abs(Quaternion(1,2,4,10))\n11.0\n```\n\"\"\"\nBase.abs(q::AbstractQuaternion) = sqrt(abs2(q))\nBase.abs(q::Rotor{T}) where {T<:Real} = one(T)\n\n\"\"\"\n    abs2vec(q)\n\nSum the squares of the \"vector\" components of the quaternion\n\n# Examples\n```jldoctest\njulia> abs2vec(Quaternion(1,2,3,6))\n49\n```\n\"\"\"\nabs2vec(q::AbstractQuaternion) = @inbounds q.components[2]^2 + q.components[3]^2 + q.components[4]^2\n\n\"\"\"\n    absvec(q)\n\nSquare-root of the sum of the squares of the \"vector\" components of the quaternion\n\n# Examples\n```jldoctest\njulia> absvec(Quaternion(1,2,3,6))\n7.0\n```\n\"\"\"\nabsvec(q::AbstractQuaternion) = sqrt(abs2vec(q))\n\n# norm(q::Quaternion) = Base.abs2(q)  ## This might just be confusing\n\nBase.inv(q::AbstractQuaternion) = conj(q) / abs2(q)\nBase.inv(q::Rotor) = conj(q)  # Specialize to ensure output is also a Rotor\n\n\n\"\"\"\n    log(q)\n\nLogarithm of a quaternion.\n\nAs with the usual complex logarithm, the quaternion logarithm has multiple\nbranches, though the quaternion branches are three-dimensional: for any unit\n\"vector\" quaternion q̂, you could add any integer multiple of 2πq̂ to the result\nof this function and still get the same result after exponentiating (within\nnumerical accuracy).  This function is the principal logarithm.\n\nThis function has discontinuous (and fairly arbitrary) behavior along the\nnegative real axis: if the \"vector\" components of the quaternion are precisely\nzero *and* the scalar component is negative, the returned quaternion will have\nscalar component `log(-q.w)`, but will also have a `z` component of π.  The\nchoice of the `z` direction is arbitrary; the \"vector\" component of the\nreturned quaternion could be π times any unit vector.\n\nNote that this function is not specialized to unit-quaternion inputs, so the\nscalar component of the returned value will be nonzero unless the input has\n*precisely* unit magnitude.\n\n# Examples\n```jldoctest\njulia> log(exp(1.2imy))\n0.0 + 0.0𝐢 + 1.2𝐣 + 0.0𝐤\n\njulia> log(Quaternion(exp(7)))\n7.0 + 0.0𝐢 + 0.0𝐣 + 0.0𝐤\n\njulia> log(Quaternion(-exp(7)))\n7.0 + 0.0𝐢 + 0.0𝐣 + 3.141592653589793𝐤\n```\n\n\"\"\"\nfunction Base.log(q::Quaternion{T}) where {T}\n    q = float(q)\n    absolute2vec = abs2vec(q)\n    if iszero(absolute2vec)\n        if q.w < 0\n            return Quaternion(log(-q.w), 0, 0, π)\n        end\n        return Quaternion(log(q.w), 0, 0, 0)\n    end\n    absolutevec = sqrt(absolute2vec)\n    f = atan(absolutevec, q.w) / absolutevec  # acos((w^2-absolutevec^2) / (w^2+absolutevec^2)) / 2absolutevec\n    Quaternion(log(abs2(q))/2, f*q.x, f*q.y, f*q.z)\nend\nfunction Base.log(q::Rotor{T}) where {T}\n    q = float(q)\n    absolute2vec = abs2vec(q)\n    if iszero(absolute2vec)\n        if q.w < 0\n            return QuatVec{float(T)}(0, 0, 0, π)\n        end\n        return QuatVec{float(T)}(0, 0, 0, 0)\n    end\n    absolutevec = sqrt(absolute2vec)\n    f = atan(absolutevec, q.w) / absolutevec  # acos(q.w) / absolutevec\n    QuatVec(0, f*q.x, f*q.y, f*q.z)\nend\n\n\"\"\"\n    exp(q)\n\nExponential of a quaternion\n\n# Examples\n```jldoctest\njulia> exp(imx*π/4)  # Rotation through π/2 (note the extra 1/2) about the x axis\n0.7071067811865476 + 0.7071067811865475𝐢 + 0.0𝐣 + 0.0𝐤\n```\n\"\"\"\nfunction Base.exp(q::Quaternion{T}) where {T}\n    q = float(q)\n    absolute2vec = abs2vec(q)\n    if iszero(absolute2vec)\n        return Quaternion(exp(q.w), 0, 0, 0)\n    end\n    absolutevec = sqrt(absolute2vec)\n    e = exp(q.w)\n    s, c = sincos(absolutevec)\n    esinc = e * s / absolutevec\n    Quaternion(e*c, esinc*q.x, esinc*q.y, esinc*q.z)\nend\nfunction Base.exp(q::QuatVec{T}) where {T}\n    q = float(q)\n    absolute2vec = abs2vec(q)\n    if iszero(absolute2vec)\n        return Rotor{float(T)}(1, 0, 0, 0)\n    end\n    absolutevec = sqrt(absolute2vec)\n    s, c = sincos(absolutevec)\n    sinc = s / absolutevec\n    Rotor(c, sinc*q.x, sinc*q.y, sinc*q.z)\nend\n\n@doc raw\"\"\"\n    sqrt(q)\n\nSquare-root of a quaternion.\n\nThe general formula whenever the denominator is nonzero is\n\n```math\n\\sqrt{q} = \\frac{|q| + q} {\\sqrt{2|q| + 2q.w}}\n```\n\nThis can be proven by expanding `q` as `q.w + q.vec` and multiplying the\nexpression above by itself.\n\nWhen the denominator is zero, this function has discontinuous (and fairly\narbitrary) behavior, just as with the quaternion [`log`](@ref) function.  In\nthis case, either all components are zero — in which case the result is simply\nthe zero quaternion — or the \"vector\" components of the quaternion are\nprecisely zero and the scalar component is negative.  If the latter is true,\nthe denominator above will be a pure-imaginary number.  Because the quaternions\ncome with infinitely many elements that square to -1, it is not clear *which*\nimaginary should be used, so we arbitrarily choose to set the result\nproportional to the `z` quaternion.  The choice of the `z` direction is\narbitrary; the \"vector\" component of the returned quaternion could be in any\ndirection.\n\n# Examples\n```jldoctest\njulia> q = Quaternion(1.2, 3.4, 5.6, 7.8);\n\njulia> sqrtq = √q;\n\njulia> sqrtq^2 ≈ q\ntrue\n\njulia> √Quaternion(4)\n2.0 + 0.0𝐢 + 0.0𝐣 + 0.0𝐤\n\njulia> √Quaternion(-4)\n0.0 + 0.0𝐢 + 0.0𝐣 + 2.0𝐤\n```\n\"\"\"\nfunction Base.sqrt(q::Quaternion{T}) where {T}\n    q = float(q)\n    absolute2vec = abs2vec(q)\n    if iszero(absolute2vec)\n        if q.w < 0\n            return Quaternion(0, 0, 0, sqrt(-q.w))\n        end\n        return Quaternion(sqrt(q.w), 0, 0, 0)\n    end\n    absolute2 = absolute2vec + q.w^2\n    c1 = sqrt(absolute2) + q.w\n    c2 = sqrt(inv(2*c1))\n    Quaternion(c1*c2, q.x*c2, q.y*c2, q.z*c2)\nend\nfunction Base.sqrt(q::Rotor{T}) where {T}\n    q = float(q)\n    absolute2vec = abs2vec(q)\n    if iszero(absolute2vec)\n        if q.w < 0\n            return Rotor{float(T)}(0, 0, 0, 1)\n        end\n        return Rotor{float(T)}(1, 0, 0, 0)\n    end\n    c1 = 1 + q.w\n    c2 = sqrt(inv(2*c1))\n    Rotor(c1*c2, q.x*c2, q.y*c2, q.z*c2)\nend\n\n\"\"\"\n    angle(q)\n\nPhase angle in radians of the rotation represented by this quaternion.\n\nNote that this may be different from your interpretation of the angle of a\ncomplex number in an important way.  Because quaternions act on vectors by\nconjugation — as in `q*v*conj(q)` — there are *two* copies of `q` involved in\nthat expression; in some sense, a quaternion acts \"twice\".  Therefore, this\nangle may be twice what you expect from an analogy with complex numbers —\ndpending on how you interpret the correspondence between complex numbers and\nquaternions.  Also, while rotations in the complex plane have a natural choice\nof axis (the positive `z` direction), that is not the case for quaternions,\nwhich means that the sign of this angle is arbitrary, and we always choose it\nto be positive.\n\n# Examples\n```jldoctest\njulia> θ=1.2;\n\njulia> R=exp(θ * imz / 2);\n\njulia> angle(R)\n1.2\n\n```\n\"\"\"\nBase.angle(q::Quaternion{T}) where T = 2 * absvec(log(q))\nBase.angle(q::Rotor{T}) where T = 2 * absvec(log(q))\n\n\nfunction Base.:^(q::Quaternion, s::Real)\n    exp(s * log(q))\nend\nfunction Base.:^(q::Rotor, s::Real)\n    q = float(q)\n    absolutevec = absvec(q)\n    if absolutevec ≤ eps(typeof(absolutevec))\n        if q.w < 0\n            # log(q) ≈ π𝐤\n            sin_πs, cos_πs = sincospi(oftype(absolutevec, s))\n            return Rotor{eltype(q)}([cos_πs, 0, 0, sin_πs])\n        end\n        # log(q) ≈ 0\n        return one(q)\n    end\n    f1 = s * atan(absolutevec, q.w)\n    sin_f1, cos_f1 = sincos(f1)\n    f2 = sin_f1 / absolutevec\n    Rotor{typeof(cos_f1)}([cos_f1, f2*q.x, f2*q.y, f2*q.z])\nend\nBase.:^(q::Quaternion, s::Integer) = (s ≥ 0 ? Base.power_by_squaring(q, s) : inv(Base.power_by_squaring(q, -s)))\nBase.:^(q::QuatVec, s::Integer) = (s ≥ 0 ? Base.power_by_squaring(q, s) : inv(Base.power_by_squaring(q, -s)))\nBase.:^(q::Rotor, s::Integer) = (s ≥ 0 ? Base.power_by_squaring(q, s) : inv(Base.power_by_squaring(q, -s)))\n", "meta": {"hexsha": "9d1418581434e41aab93088be45939c199ed95c0", "size": 8112, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math.jl", "max_stars_repo_name": "moble/Quaternionic.jl", "max_stars_repo_head_hexsha": "e7bb501093141c3dc653325582c05b92eb57e3a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-06-26T17:12:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T15:42:20.000Z", "max_issues_repo_path": "src/math.jl", "max_issues_repo_name": "moble/Quaternionic.jl", "max_issues_repo_head_hexsha": "e7bb501093141c3dc653325582c05b92eb57e3a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2021-06-09T22:50:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T17:44:28.000Z", "max_forks_repo_path": "src/math.jl", "max_forks_repo_name": "moble/Quaternionic.jl", "max_forks_repo_head_hexsha": "e7bb501093141c3dc653325582c05b92eb57e3a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5633802817, "max_line_length": 112, "alphanum_fraction": 0.6644477318, "num_tokens": 2657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7551644790731403}}
{"text": "abstract type AbstractTensorProductLayer <: Function end\n\"\"\"\nConstructs the Tensor Product Layer, which takes as input an array of n tensor\nproduct basis, [B_1, B_2, ..., B_n] a data point x, computes\nz[i] = W[i,:] ⨀ [B_1(x[1]) ⨂ B_2(x[2]) ⨂ ... ⨂ B_n(x[n])], where W is the layer's weight,\nand returns [z[1], ..., z[out]].\n\n```julia\nTensorLayer(model,out,p=nothing)\n```\nArguments:\n- `model`: Array of TensorProductBasis [B_1(n_1), ..., B_k(n_k)], where k corresponds to the dimension of the input.\n- `out`: Dimension of the output.\n- `p`: Optional initialization of the layer's weight. Initialized to standard normal by default.\n\"\"\"\nstruct TensorLayer{M<:Array{TensorProductBasis},P<:AbstractArray,Int} <: AbstractTensorProductLayer\n    model::M\n    p::P\n    in::Int\n    out::Int\n    function TensorLayer(model,out,p=nothing)\n        number_of_weights = 1\n        for basis in model\n            number_of_weights *= basis.n\n        end\n        if p === nothing\n            p = randn(out*number_of_weights)\n        end\n        new{Array{TensorProductBasis},typeof(p),Int}(model,p,length(model),out)\n    end\nend\n\nfunction (layer::TensorLayer)(x,p=layer.p)\n    model,out = layer.model,layer.out\n    W = reshape(p, out, Int(length(p)/out))\n    tensor_prod = model[1](x[1])\n    for i in 2:length(model)\n        tensor_prod = kron(tensor_prod,model[i](x[i]))\n    end\n    z = W*tensor_prod\n    return z\nend\n", "meta": {"hexsha": "926a3f7aefcc5aeaf91a12502e35acf4a01d0ffa", "size": 1401, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tensor_product_layer.jl", "max_stars_repo_name": "achuchmala/DiffEqFlux.jl", "max_stars_repo_head_hexsha": "7f2a25d0f3f86161127edd5e3f36bf19c8b5c50d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 472, "max_stars_repo_stars_event_min_datetime": "2020-03-29T08:59:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T12:24:46.000Z", "max_issues_repo_path": "src/tensor_product_layer.jl", "max_issues_repo_name": "achuchmala/DiffEqFlux.jl", "max_issues_repo_head_hexsha": "7f2a25d0f3f86161127edd5e3f36bf19c8b5c50d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 356, "max_issues_repo_issues_event_min_datetime": "2020-03-25T15:46:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:37:25.000Z", "max_forks_repo_path": "src/tensor_product_layer.jl", "max_forks_repo_name": "achuchmala/DiffEqFlux.jl", "max_forks_repo_head_hexsha": "7f2a25d0f3f86161127edd5e3f36bf19c8b5c50d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 114, "max_forks_repo_forks_event_min_datetime": "2020-03-26T21:34:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T21:45:50.000Z", "avg_line_length": 32.5813953488, "max_line_length": 116, "alphanum_fraction": 0.6509635974, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7551644770722653}}
{"text": "using Revise\nusing Statistics\nusing LaTeXStrings\nusing PyPlot\nusing LinearAlgebra\nusing Infiltrator\nusing Bem2d\n\n\n\"\"\"\n    discretized_arc(θstart, θend, radius, n_pts)\n\nGenerate regularly spaced eleemnts along an curved arc.\n\"\"\"\nfunction discretized_arc(θstart, θend, radius, n_pts)\n    # Create geometry of discretized arc\n    θrange = collect(LinRange(θstart, θend, n_pts + 1))\n    x = @. radius * cos(θrange)\n    y = @. radius * sin(θrange)\n    x1 = x[1:1:end-1]\n    x2 = x[2:1:end]\n    y1 = y[1:1:end-1]\n    y2 = y[2:1:end]\n    return x1, y1, x2, y2\nend\n\n\n\"\"\"\n    circle_subplot(nrows, ncols, plotidx, x, y, mat, npts, R, theta0, title_string)\n\nPlot field (displacement, stress) within a circular disk and style\n\"\"\"\nfunction circle_subplot(nrows, ncols, plotidx, x, y, mat, npts, R, theta0, title_string)\n    fontsize = 20\n    contour_levels = 100\n    contour_color = \"white\"\n    contour_linewidth = 0.5\n    color_scale = 1\n\n    subplot(nrows, ncols, plotidx)\n    contourf(reshape(x, npts, npts), reshape(y, npts, npts), reshape(mat, npts, npts), levels=contour_levels)\n    cbar = colorbar(fraction=0.05, pad=0.05, extend = \"both\")\n    cbar.ax.tick_params(labelsize=fontsize)\n    contour(reshape(x, npts, npts), reshape(y, npts, npts), reshape(mat, npts, npts), levels=contour_levels, colors=contour_color, linewidths=contour_linewidth)\n    xlabel(\"x (m)\", fontsize=fontsize)\n    ylabel(\"y (m)\", fontsize=fontsize)\n    title(title_string, fontsize=fontsize)\n\n    # Draw entire circle and region of applied tractions\n    x1, y1, x2, y2 = discretized_arc(deg2rad(-180), deg2rad(180), R, 360)\n    plot([x1, x2], [y1, y2], \"-k\", linewidth=2)\n    x1, y1, x2, y2 = discretized_arc(-theta0, theta0, R, 50)\n    plot([x1, x2], [y1, y2], \"-r\", linewidth=2)\n    x1, y1, x2, y2 = discretized_arc(-theta0+deg2rad(180), theta0+deg2rad(180), R, 50)\n    plot([x1, x2], [y1, y2], \"-r\", linewidth=2)\n    gca().set_aspect(\"equal\")\n    gca().tick_params(labelsize=fontsize)\nend\n\n\n\"\"\"\n    calcbrazil(p, x, y, R, theta0)\n\nCalculate stresses predicted from Hondros solution to Brazil test.\n\"\"\"\nfunction calcbrazil(p, x, y, R, theta0)\n    #! Solution from Hondros (1959) as summarized by Wei and Chau 2013\n    r = @. sqrt(x^2 + y^2)\n    theta = @. atan(y, x)\n\n    # Analytic stresses in cylindrical coordinates\n    Srr = zeros(length(x))\n    Sthetatheta = zeros(length(x))\n    Srtheta = zeros(length(x))\n    Srrconstterm = 2.0 * theta0 * -p / deg2rad(180)\n    Sthetathetaconstterm = 2.0 * theta0 * -p / deg2rad(180)\n    leadingterm = 2.0 * -p / deg2rad(180)\n    mmax = 1000 # Max number of terms in Hondros series\n    for m in 1:mmax\n        Srr += @. (r/R)^(2*m-2) * (1-(1-1/m)*(r/R)^2) * sin(2*m*theta0) * cos(2*m*theta)\n        Sthetatheta += @. (r/R)^(2*m-2) * (1-(1+1/m)*(r/R)^2) * sin(2*m*theta0) * cos(2*m*theta)\n        Srtheta += @. ((r/R)^(2*m) - (r/R)^(2*m-2)) * sin(2*m*theta0) * sin(2*m*theta)\n    end\n    Srr = @. Srrconstterm + leadingterm * Srr\n    Sthetatheta = @. Sthetathetaconstterm - leadingterm * Sthetatheta\n    Srtheta = @. leadingterm * Srtheta\n\n    # Convert analytic cylindrical stresses to Cartesian\n    Sanalytic = zeros(length(x), 3)\n    for i in 1:length(x) # Project a single matrix to Cartesian coordinates\n        cylindrical_stress_tensor = [Srr[i] Srtheta[i] ; Srtheta[i] Sthetatheta[i]]\n        transformation_matrix = [cos(theta[i]) -sin(theta[i]) ; sin(theta[i]) cos(theta[i])]\n        cartesian_stress_tensor = transformation_matrix * cylindrical_stress_tensor * transpose(transformation_matrix)\n        Sanalytic[i, 1] = cartesian_stress_tensor[1, 1]\n        Sanalytic[i, 2] = cartesian_stress_tensor[2, 2]\n        Sanalytic[i, 3] = cartesian_stress_tensor[1, 2]\n    end\n    return Sanalytic\nend\n\n\n\"\"\"\n    braziltest()\n\nCompare the Hondros (1959 analytic soluiton) for the Brazil test \nwith the BEM solution for both constant and quadratic element cases.\n\"\"\"\nfunction braziltest()\n    close(\"all\")\n    mu = 3e10\n    nu = 0.25\n    p = -1.0e5 # Applied radial pressure over arc\n    theta0 = deg2rad(1.0) # Arc length over which pressure is applied\n    nels = 360\n    R = nels / (2 * pi)\n    npts = 200\n    x, y = Bem2d.obsgrid(-R, -R, R, R, npts)\n    r = @. sqrt(x^2 + y^2)\n\n    #! Analytic solution\n    Sanalytic = calcbrazil(p, x, y, R, theta0)\n\n    #! BEM solution\n    els = Bem2d.Elements(Int(1e5))\n    x1, y1, x2, y2 = discretized_arc(deg2rad(-180), deg2rad(180), R, nels)\n    for i in 1:length(x1)\n        els.x1[els.endidx + i] = x1[i]\n        els.y1[els.endidx + i] = y1[i]\n        els.x2[els.endidx + i] = x2[i]\n        els.y2[els.endidx + i] = y2[i]\n        els.name[els.endidx + i] = \"circle\"\n    end\n    Bem2d.standardize_elements!(els)\n    idx = Bem2d.getidxdict(els)\n\n    #! Apply normal tractions everywhere and convert from radial to Cartesian\n    xtracC = zeros(els.endidx)\n    ytracC = zeros(els.endidx)\n    thetaels = @. atan(els.ycenter[1:1:els.endidx], els.xcenter[1:1:els.endidx])\n    for i in 1:els.endidx # Calcuate the x and y components of the tractions\n        normalTractions = [0; p] # Pressure in fault normal component only.\n        xtracC[i], ytracC[i] = els.rotmat[i, :, :] * normalTractions\n    end\n\n    #! Zero out the tractions on the area without contact\n    deleteidx = findall(x -> (x>theta0 && x<deg2rad(180)-theta0), thetaels)\n    xtracC[deleteidx] .= 0\n    ytracC[deleteidx] .= 0\n    deleteidx = findall(x -> (x<-theta0 && x>-deg2rad(180)+theta0), thetaels)\n    xtracC[deleteidx] .= 0\n    ytracC[deleteidx] .= 0\n\n    #! Kernels, T*: displacement to displacement, H*: displacement to traction\n    @time _, _, HstarC = partialsconstdispstress(slip2dispstress, els, idx[\"circle\"], idx[\"circle\"], mu, nu)\n    @time _, _, HstarQ = partialsquaddispstress(slip2dispstress, els, idx[\"circle\"], idx[\"circle\"], mu, nu)\n\n    #! CONSTANT CASE\n    #! Applied tractions -> effective displacements -> internal stresses\n    DeffC = inv(HstarC) * interleave(xtracC, ytracC)\n    @time _, SdispC = constdispstress(slip2dispstress, x, y, els, idx[\"circle\"], DeffC[1:2:end], DeffC[2:2:end], mu, nu)\n\n    #! QUADRATIC CASE\n    #! Applied tractions -> effective displacements -> internal stresses\n    xtracQ = zeros(3 * length(xtracC))\n    ytracQ = zeros(3 * length(ytracC))\n    xtracQ[1:3:end] = xtracC\n    xtracQ[2:3:end] = xtracC\n    xtracQ[3:3:end] = xtracC\n    ytracQ[1:3:end] = ytracC\n    ytracQ[2:3:end] = ytracC\n    ytracQ[3:3:end] = ytracC\n    DeffQ = inv(HstarQ) * interleave(xtracQ, ytracQ)\n    @time _, SdispQ = quaddispstress(slip2dispstress, x, y, els, idx[\"circle\"], quadstack(DeffQ[1:2:end]), quadstack(DeffQ[2:2:end]), mu, nu)\n\n    #! Isolate the values inside the circle\n    nanidx = findall(x -> x > R, r)\n    Sanalytic[nanidx, :] .= NaN\n    SdispC[nanidx, :] .= NaN\n    SdispQ[nanidx, :] .= NaN\n    SresidualC = @. SdispC - Sanalytic\n    SresidualQ = @. SdispQ - Sanalytic\n    \n    #! Summary figure\n    figure(figsize=(30,20))\n    fontsize = 20\n    nrows = 4\n    ncols = 6\n\n    #! Constant dislocation case\n    # Applied tractions\n    subplot(nrows, ncols, 1)\n    plot(rad2deg.(thetaels), xtracC, \".r\")\n    plot(rad2deg.(thetaels), ytracC, \"+b\")\n    title(\"applied tractions\", fontsize=fontsize)\n    gca().tick_params(labelsize=fontsize)\n\n    # Effective displacements\n    subplot(nrows, ncols, 2)\n    plot(rad2deg.(thetaels), DeffC[1:2:end], \".r\")\n    plot(rad2deg.(thetaels), DeffC[2:2:end], \"+b\")\n    title(\"Effective displacements\", fontsize=fontsize)\n    gca().tick_params(labelsize=fontsize)\n\n    # Analytic solutions\n    circle_subplot(nrows, ncols, 7, x, y, Sanalytic[:, 1], npts, R, theta0, \"Sxx (analytic)\")\n    circle_subplot(nrows, ncols, 8, x, y, Sanalytic[:, 2], npts, R, theta0, \"Syy (analytic)\")\n    circle_subplot(nrows, ncols, 9, x, y, Sanalytic[:, 3], npts, R, theta0, \"Sxy (analytic)\")\n\n    # BEM solutions\n    circle_subplot(nrows, ncols, 13, x, y, SdispC[:, 1], npts, R, theta0, \"Sxx (DDM)\")\n    circle_subplot(nrows, ncols, 14, x, y, SdispC[:, 2], npts, R, theta0, \"Syy (DDM)\")\n    circle_subplot(nrows, ncols, 15, x, y, SdispC[:, 3], npts, R, theta0, \"Sxy (DDM)\")\n    circle_subplot(nrows, ncols, 19, x, y, SresidualC[:, 1], npts, R, theta0, \"Sxx (residual)\")\n    circle_subplot(nrows, ncols, 20, x, y, SresidualC[:, 2], npts, R, theta0, \"Syy (residual)\")\n    circle_subplot(nrows, ncols, 21, x, y, SresidualC[:, 3], npts, R, theta0, \"Sxy (residual)\")\n\n    #! Quadratic case\n    # Applied tractions\n    subplot(nrows, ncols, 4)\n    plot(xtracQ, \".r\")\n    plot(ytracQ, \"+b\")\n    title(\"applied tractions\", fontsize=fontsize)\n    gca().tick_params(labelsize=fontsize)\n\n    # Effective displacements\n    subplot(nrows, ncols, 5)\n    plot(DeffQ[1:2:end], \".r\")\n    plot(DeffQ[2:2:end], \"+b\")\n    title(\"Effective displacements\", fontsize=fontsize)\n    gca().tick_params(labelsize=fontsize)\n\n    # Analytic solutions\n    circle_subplot(nrows, ncols, 10, x, y, Sanalytic[:, 1], npts, R, theta0, \"Sxx (analytic)\")\n    circle_subplot(nrows, ncols, 11, x, y, Sanalytic[:, 2], npts, R, theta0, \"Syy (analytic)\")\n    circle_subplot(nrows, ncols, 12, x, y, Sanalytic[:, 3], npts, R, theta0, \"Sxy (analytic)\")\n\n    # BEM solutions\n    circle_subplot(nrows, ncols, 16, x, y, SdispQ[:, 1], npts, R, theta0, \"Sxx (DDM)\")\n    circle_subplot(nrows, ncols, 17, x, y, SdispQ[:, 2], npts, R, theta0, \"Syy (DDM)\")\n    circle_subplot(nrows, ncols, 18, x, y, SdispQ[:, 3], npts, R, theta0, \"Sxy (DDM)\")\n    circle_subplot(nrows, ncols, 22, x, y, SresidualQ[:, 1], npts, R, theta0, \"Sxx (residual)\")\n    circle_subplot(nrows, ncols, 23, x, y, SresidualQ[:, 2], npts, R, theta0, \"Syy (residual)\")\n    circle_subplot(nrows, ncols, 24, x, y, SresidualQ[:, 3], npts, R, theta0, \"Sxy (residual)\")\n    tight_layout()\n    show()\n\n    #! 9-panel plot for quadratic only\n    figure(figsize=(15,15))\n    nrows = 3\n    ncols = 3\n    # Analytic solutions\n    circle_subplot(nrows, ncols, 1, x, y, Sanalytic[:, 1], npts, R, theta0, L\"\\sigma_{xx} \\; \\mathrm{(analytic)}\")\n    circle_subplot(nrows, ncols, 2, x, y, Sanalytic[:, 2], npts, R, theta0, L\"\\sigma_{yy} \\; \\mathrm{(analytic)}\")\n    circle_subplot(nrows, ncols, 3, x, y, Sanalytic[:, 3], npts, R, theta0, L\"\\sigma_{xy} \\; \\mathrm{(analytic)}\")\n\n    # BEM solutions\n    circle_subplot(nrows, ncols, 4, x, y, SdispQ[:, 1], npts, R, theta0, L\"\\sigma_{xx} \\; \\mathrm{(BEM)}\")\n    circle_subplot(nrows, ncols, 5, x, y, SdispQ[:, 2], npts, R, theta0, L\"\\sigma_{yy} \\; \\mathrm{(BEM)}\")\n    circle_subplot(nrows, ncols, 6, x, y, SdispQ[:, 3], npts, R, theta0, L\"\\sigma_{xy} \\; \\mathrm{(BEM)}\")\n    circle_subplot(nrows, ncols, 7, x, y, SresidualQ[:, 1], npts, R, theta0, L\"\\sigma_{xx} \\; \\mathrm{(residual)}\")\n    circle_subplot(nrows, ncols, 8, x, y, SresidualQ[:, 2], npts, R, theta0, L\"\\sigma_{yy} \\; \\mathrm{(residual)}\")\n    circle_subplot(nrows, ncols, 9, x, y, SresidualQ[:, 3], npts, R, theta0, L\"\\sigma_{xy} \\; \\mathrm{(residual)}\")\n    tight_layout()\n    show()\nend\nbraziltest()\n", "meta": {"hexsha": "65f76cddf74a37ba2bba58d896f8b3c9744a91d7", "size": 10882, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/braziltest.jl", "max_stars_repo_name": "brendanjmeade/Bem2d.jl", "max_stars_repo_head_hexsha": "321b82fbca4dead409f7c446fbe035c683bc8535", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-01-20T16:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T01:38:53.000Z", "max_issues_repo_path": "examples/braziltest.jl", "max_issues_repo_name": "brendanjmeade/Bem2d.jl", "max_issues_repo_head_hexsha": "321b82fbca4dead409f7c446fbe035c683bc8535", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-09-06T01:54:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T01:52:07.000Z", "max_forks_repo_path": "examples/braziltest.jl", "max_forks_repo_name": "brendanjmeade/Bem2d.jl", "max_forks_repo_head_hexsha": "321b82fbca4dead409f7c446fbe035c683bc8535", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-01-12T08:12:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T18:17:07.000Z", "avg_line_length": 40.7565543071, "max_line_length": 160, "alphanum_fraction": 0.636004411, "num_tokens": 3888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7551644767398259}}
{"text": "\"\"\"\n    ExplicitRungeKuttaScheme(\n        step_size::Float64,\n        alpha::LinearAlgebra.LowerTriangular{Float64},\n        beta::LinearAlgebra.LowerTriangular{Float64},\n    )\n\nGeneric data container for ExplicitRungeKuttaScheme for use in `integrate_time`.\n\nWe are interested in numerically integrating ODEs of the form\n    ``a'(t) = a(t) Q``\n\nwhere ``a(t)`` is a vector of coefficients and ``Q`` is a matrix, given an initial condition ``a(0)``. \n\nIn this context, Explicit Runge-Kutta methods with ``s`` stages can be written as \n\n``v^{(0)} = a(t),``\n\n``v^{(l)} = \\\\sum_{k=0}^{l-1} \\\\alpha_{l k} v^{(k)} + h\\\\beta_{l k}  v^{(k)} Q,\\\\, l = 1,...,s,``\n\n``a(t+h) =v^{(s)},``\n\nwhere ``h`` is the step-size and ``\\\\alpha_{l k}`` and ``\\\\beta_{l k}`` are parameters which define the scheme. \n\n# Arguments \n-  `step_size::Float64`: the step size of the integration scheme.\n-  `alpha::LinearAlgebra.LowerTriangular{Float64}`: coefficients as described above \n-  `beta::LinearAlgebra.LowerTriangular{Float64}`: coefficients as described above \n\"\"\"\nstruct ExplicitRungeKuttaScheme\n    step_size::Float64\n    alpha::LinearAlgebra.LowerTriangular{Float64}\n    beta::LinearAlgebra.LowerTriangular{Float64}\n    function ExplicitRungeKuttaScheme(step_size::Float64,\n        alpha::LinearAlgebra.LowerTriangular{Float64},\n        beta::LinearAlgebra.LowerTriangular{Float64})\n\n        t1 = (step_size > 0)\n        checksquare(alpha)\n        l1 = size(alpha)\n        l2 = size(beta)\n        (!t1)&&throw(DomainError(\"step_size must be positive\"))\n        !(l1==l2)&&throw(DimensionMismatch(\"alpha, beta must have same size\"))\n        return new(step_size,alpha,beta)\n    end\nend\n\n\"\"\"\n    ForwardEuler(step_size::Float64) <: ExplicitRungeKuttaScheme\n\nDefines an Euler integration scheme to be used in `integrate_time`.\n\n# Arguments \n-  `step_size::Float64`: the step size of the integration scheme.\n\"\"\"\nForwardEuler(step_size::Float64) = ExplicitRungeKuttaScheme(\n        step_size,\n        LinearAlgebra.LowerTriangular([1.0][:,:]),\n        LinearAlgebra.LowerTriangular([1.0][:,:])\n    )\n\n\"\"\"\n\n    Heuns(step_size::Float64) <: ExplicitRungeKuttaScheme\n\nDefines Heuns integration scheme to be used in `integrate_time`.\n\n# Arguments \n-  `step_size::Float64`: the step size of the integration scheme.\n\"\"\"\nHeuns(step_size::Float64) = ExplicitRungeKuttaScheme(\n        step_size,\n        LinearAlgebra.LowerTriangular([1.0 0.0; 0.5 0.5]),\n        LinearAlgebra.LowerTriangular([1.0 0.0; 0.0 0.5])\n    )\n\n\"\"\"\n\n    StableRK3(step_size::Float64) <: ExplicitRungeKuttaScheme\n\nDefines a strong stability preserving Runge-Kutta integration scheme to be used in `integrate_time`.\n\n# Arguments \n-  `step_size::Float64`: the step size of the integration scheme.\n\nHesthaven, J. S. & Warburton, T. (2007), Nodal discontinuous Galerkin methods: algorithms, analysis, and applications, Springer Science & Business Media.\n(Section 5.7)\n\n\"\"\"\nStableRK3(step_size::Float64) = ExplicitRungeKuttaScheme(\n        step_size,\n        LinearAlgebra.LowerTriangular([1.0 0.0 0.0; 0.75 0.25 0.0; 1/3 0.0 2/3]),\n        LinearAlgebra.LowerTriangular([1.0 0.0 0.0; 0.0 0.25 0.0; 0.0 0.0 2/3])\n    )\n                \n_α = [  1.0                0.0                 0.0                 0.0                 0.0                 ;\n        0.44437049406734   0.55562950593266    0.0                 0.0                 0.0                 ;\n        0.62010185138540   0.0                 0.37989814861460    0.0                 0.0                 ;\n        0.17807995410773   0.0                 0.0                 0.82192004589227    0.0                 ;\n        0.00683325884039   0.0                 0.51723167208978    0.12759831133288    0.34833675773694    ]\n_β = [  0.39175222700392    0.0                 0.0                 0.0                 0.0                 ;\n        0.0                 0.36841059262959    0.0                 0.0                 0.0                 ;\n        0.0                 0.0                 0.25189177424738    0.0                 0.0                 ;\n        0.0                 0.0                 0.0                 0.54497475021237    0.0                 ;\n        0.0                 0.0                 0.0                 0.08460416338212    0.22600748319395    ]\n\"\"\"\n    StableRK4(step_size::Float64) = ExplicitRungeKuttaScheme(\n            step_size,\n            LinearAlgebra.LowerTriangular(_α),\n            LinearAlgebra.LowerTriangular(_β)\n        )\n\nDefines a strong stability preserving Runge-Kutta integration scheme to be used in `integrate_time`.\n\n# Arguments \n-  `step_size::Float64`: the step size of the integration scheme.\n\nRaymond J. Spiteri and Steven J. Ruuth. A new class of optimal high-order\nstrong-stability-preserving time discretization methods. SIAM J. Numer. Anal.,\n40(2):469-491, 2002.\n\nHesthaven, J. S. & Warburton, T. (2007), Nodal discontinuous Galerkin methods: algorithms, analysis, and applications, Springer Science & Business Media.\n(Section 5.7)\n\"\"\"\nStableRK4(step_size::Float64) = ExplicitRungeKuttaScheme(\n        step_size,\n        LinearAlgebra.LowerTriangular(_α),\n        LinearAlgebra.LowerTriangular(_β)\n    )\n\n\"\"\"\nGiven `x0` and `D` apprximate `x0 exp(Dy)`.\n\n    integrate_time(x0::Array{Float64,2}, D::AbstractArray{Float64,2},\n        y::Float64, scheme::ExplicitRungeKuttaScheme [; limiter])\n\n# Arguments\n- `x0`: An initial vector\n- `D`: A square matrix\n- `y`: time to integrate up to\n- `h`: ExplicitRungeKuttaScheme.\n- `limiter`: optional named argument spacifying the slope-limiter to used. The \n    limiter function will be applied at every stage and every time-step of the \n    ExplicitRungeKuttaScheme. \n\"\"\"\nfunction integrate_time(x0::Array{Float64,2}, D::AbstractArray{Float64,2},\n    y::Float64, scheme::ExplicitRungeKuttaScheme)\n\n    checksquare(D)\n    !(size(x0,2)==size(D,1))&&throw(DimensionMismatch(\"x0 must have length size(D,1)\"))\n    \n    return _integrate(x0[:],D,y,scheme)\nend\nfunction integrate_time(x0::Array{Float64,1}, D::AbstractArray{Float64,2},\n    y::Float64, scheme::ExplicitRungeKuttaScheme)\n\n    checksquare(D)\n    \n    return _integrate(x0,D,y,scheme)\nend\n\nfunction integrate_time(x0::SFMDistribution, D::AbstractArray{Float64,2},\n    y::Float64, scheme::ExplicitRungeKuttaScheme)   \n    return SFMDistribution(integrate_time(x0.coeffs,D,y,scheme),x0.dq)\nend\n\nfunction integrate_time(x0::SFMDistribution{DGMesh{T}}, D::AbstractArray{Float64,2},\n    y::Float64, scheme::ExplicitRungeKuttaScheme; limiter::Limiter=GeneralisedMUSCL) where T\n\n    checksquare(D)\n    \n    limiter_params = limiter.generate_params(x0.dq)\n    limiter_function = x->limiter.fun(x,limiter_params...)\n\n    return SFMDistribution(_integrate(x0.coeffs,D,y,scheme,limiter_function),x0.dq)\nend\n\n\"\"\"\n    _integrate(x0::Array{Float64,1}, \n        D::Union{Array{Float64,2},SparseArrays.SparseMatrixCSC{Float64,Int}}, \n        y::Float64, scheme::ExplicitRungeKuttaScheme)\n\nUse ExplicitRungeKuttaScheme method.\n\"\"\"\nfunction _integrate(x0::Array{Float64,1}, D::AbstractArray{Float64,2},\n    y::Float64, scheme::ExplicitRungeKuttaScheme)\n\n    return _integrate(x0, D, y, scheme, identity)\nend\n\nfunction _integrate(x0::Array{Float64,1}, D::AbstractArray{Float64,2},\n    y::Float64, scheme::ExplicitRungeKuttaScheme, limit_function::Function)\n    \n    x = limit_function(x0)\n    h = scheme.step_size\n    l = size(scheme.alpha,1)\n    α = scheme.alpha\n    βh = scheme.beta*h\n    v = Array{Float64,2}(undef,length(x0),l+1)\n    vD = Array{Float64,2}(undef,length(x0),l+1)\n    for t = h:h:y\n        v[:,1] = x\n        for i in 1:l\n            vD[:,i] = transpose(v[:,i])*D\n            initialised = false \n            for j in 1:i\n                if α[i,j]!=0.0\n                    initialised ? (v[:,i+1]+=v[:,j]*α[i,j]) : (v[:,i+1]=v[:,j]*α[i,j]; initialised=true)\n                end\n                if βh[i,j]!=0.0\n                    initialised ? (v[:,i+1]+=vD[:,j]*βh[i,j]) : (v[:,i+1]=vD[:,j]*βh[i,j]; initialised=true)\n                end\n            end\n            v[:,i+1] = limit_function(v[:,i+1])\n        end\n        x = v[:,end]\n    end\n    return x\nend\n", "meta": {"hexsha": "eafa0caa2000bbe1efa73e7a8277aba913ef978b", "size": 8108, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/time_integration.jl", "max_stars_repo_name": "angus-lewis/DiscretisedFluidQueues.jl", "max_stars_repo_head_hexsha": "aa60fa272b61c088695dd29a2fe768fd2f375378", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/time_integration.jl", "max_issues_repo_name": "angus-lewis/DiscretisedFluidQueues.jl", "max_issues_repo_head_hexsha": "aa60fa272b61c088695dd29a2fe768fd2f375378", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/time_integration.jl", "max_forks_repo_name": "angus-lewis/DiscretisedFluidQueues.jl", "max_forks_repo_head_hexsha": "aa60fa272b61c088695dd29a2fe768fd2f375378", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8545454545, "max_line_length": 153, "alphanum_fraction": 0.6161815491, "num_tokens": 2444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802373309982, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7551644737353931}}
{"text": "\"\"\"\n     rouwenhorst(μ,ρ,σ,n)\nGenerates a finite state Markov representation of the AR process defined by the\nsupplied parameters. Returns the states and transition matrix.\n\"\"\"\nfunction rouwenhorst(μ, ρ, σ, n)\n    n == 1 && (return [μ], [1.0])\n\n    mu_eps = 0\n    q = (ρ + 1) / 2\n    nu = ((n - 1) / (1 - ρ^2))^(1 / 2) * σ\n    P = [q 1 - q; 1 - q q]\n    for i = 2:n - 1\n        P = q * [P zeros(i, 1);zeros(1, i + 1)] + (1 - q) * [zeros(i, 1) P; zeros(1, i + 1)] + (1 - q) * [zeros(1, i + 1); P zeros(i, 1)] + q * [zeros(1, i + 1); zeros(i, 1) P]\n        P[2:i, :] = P[2:i, :] / 2\n    end\n    x = [linspace(mu_eps / (1 - ρ) .- nu, mu_eps / (1 - ρ) .+ nu, n);] .+ μ\n    return x, P\nend\n\n\"\"\"\n     tauchen(μ,ρ,σ,n)\nGenerates a finite state Markov representation of the AR process defined by the\nsupplied parameters. Returns the states and transition matrix.\n\"\"\"\nfunction tauchen(μ, ρ, σ, N, m = 3)\n    cdf_normal(x) = 0.5 * erfc(-x / sqrt(2))\n    if N == 1\n        return [μ], [1.0]\n    end\n    Z     = zeros(N)\n    Zprob = zeros(N, N)\n    a     = (1 - ρ) * μ\n\n    Z[N]  = m * sqrt(σ^2 / (1 - ρ^2))\n    Z[1]  = -Z[N]\n    zstep = (Z[N] - Z[1]) / (N - 1)\n\n    for i = 2:(N - 1)\n        Z[i] = Z[1] + zstep * (i - 1)\n    end\n\n    Z = Z .+ a / (1 - ρ)\n\n    for j = 1:N\n        for k = 1:N\n            if k == 1\n                Zprob[j,k] = cdf_normal((Z[1] - a - ρ * Z[j] + zstep / 2) / σ)\n            elseif k == N\n                Zprob[j,k] = 1 - cdf_normal((Z[N] - a - ρ * Z[j] - zstep / 2) / σ)\n            else\n                Zprob[j,k] = cdf_normal((Z[k] - a - ρ * Z[j] + zstep / 2) / σ) - cdf_normal((Z[k] - a - ρ * Z[j] - zstep / 2) / σ)\n            end\n        end\n    end\n    return Z, Zprob\nend\n", "meta": {"hexsha": "30eba963b8b70d191b3354e3a07df361ba6c55f3", "size": 1700, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "ZacLN/HADSGE", "max_stars_repo_head_hexsha": "8b81c36b46f960b3b1efed1ee757d501b343adb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-03-11T11:45:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-22T14:44:51.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "ZacLN/HADSGE", "max_issues_repo_head_hexsha": "8b81c36b46f960b3b1efed1ee757d501b343adb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "ZacLN/HADSGE", "max_forks_repo_head_hexsha": "8b81c36b46f960b3b1efed1ee757d501b343adb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-22T14:44:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-27T00:21:00.000Z", "avg_line_length": 29.3103448276, "max_line_length": 176, "alphanum_fraction": 0.4470588235, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7551644694012041}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.6\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec\nusing Pkg, DrWatson\n\n# ╔═╡ e4eeb13a-1ee4-11eb-0113-91f9a9c3b659\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Combinatorics, Plots, LaTeXStrings\n\tRandom.seed!(123)\nend\n\n# ╔═╡ ac3ceabe-1ee4-11eb-3935-313e96aafd62\nmd\"## Listing 2.5\"\n\n# ╔═╡ d212f38c-1ee4-11eb-360a-b7d524890c8f\nfunction isUpperLattice(v)\n    for i in 1:Int(length(v)/2)\n        sum(v[1:2*i-1]) >= i ? continue : return false\n    end\n    return true\nend\n\n# ╔═╡ 6263427a-1ee5-11eb-12d1-1d576fa18461\nbegin\n\tn, N = 5, 10^5\n\n\n\tomega = unique(permutations([zeros(Int,n);ones(Int,n)]))\n\tA = omega[isUpperLattice.(omega)]\n\tpA_modelI = length(A)/length(omega)\nend\n\n# ╔═╡ 62637f3a-1ee5-11eb-34e2-77e37f188fe5\nfunction randomWalkPath(n)\n    x, y = 0, 0\n    path = []\n    while x<n && y<n\n       if rand()<0.5\n            x += 1\n            push!(path,0)\n        else\n            y += 1\n            push!(path,1)\n        end\n    end\n    append!(path, x<n ? zeros(Int64,n-x) : ones(Int64,n-y))\n    return path\nend\n\n# ╔═╡ 6263f402-1ee5-11eb-20e1-5d1ebc78f310\nbegin\n\tpA_modelIIest = sum([isUpperLattice(randomWalkPath(n)) for _ in 1:N])/N\n\t(\"Model I: \",pA_modelI, \"\\t Model II: \", pA_modelIIest)\nend\n\n# ╔═╡ 6276d39e-1ee5-11eb-23cc-2fe5377e6ce9\nfunction plotPath(v,l,c)\n    x,y = 0,0\n    graphX, graphY = [x], [y]\n    for i in v\n        if i == 0\n            x += 1\n        else\n            y += 1\n        end\n        push!(graphX,x), push!(graphY,y)\n    end\n    plot!(graphX, graphY, \n            la=0.8, lw=2, label=l, c=c, ratio=:equal, legend=:topleft, \n            xlims=(0,n), ylims=(0,n), \n            xlabel=L\"East\\rightarrow\", ylabel=L\"North\\rightarrow\")\nend\n\n# ╔═╡ 62781fb2-1ee5-11eb-0ba1-035fa45106f5\nbegin\n\tplot()\n\tplotPath(rand(A), \"Upper lattice path\", :blue)\n\tplotPath(rand(setdiff(omega,A)), \"Non-upper lattice path\", :red)\n\tplot!([0, n], [0,n], ls=:dash, c=:black, label=\"\")\nend\n\n# ╔═╡ 6285dea2-1ee5-11eb-2b6a-f9906c0d3351\nmd\"## End of listing 2.5\"\n\n# ╔═╡ Cell order:\n# ╟─ac3ceabe-1ee4-11eb-3935-313e96aafd62\n# ╠═de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec\n# ╠═e4eeb13a-1ee4-11eb-0113-91f9a9c3b659\n# ╠═d212f38c-1ee4-11eb-360a-b7d524890c8f\n# ╠═6263427a-1ee5-11eb-12d1-1d576fa18461\n# ╠═62637f3a-1ee5-11eb-34e2-77e37f188fe5\n# ╠═6263f402-1ee5-11eb-20e1-5d1ebc78f310\n# ╠═6276d39e-1ee5-11eb-23cc-2fe5377e6ce9\n# ╠═62781fb2-1ee5-11eb-0ba1-035fa45106f5\n# ╟─6285dea2-1ee5-11eb-2b6a-f9906c0d3351\n", "meta": {"hexsha": "1449117cfd6fef11c110741b2cf5663e61994a9f", "size": 2491, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/02/listing2.05.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/02/listing2.05.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/02/listing2.05.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 24.6633663366, "max_line_length": 72, "alphanum_fraction": 0.6370935367, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7551644690687649}}
{"text": "module ProjSplx\n\nexport projsplx!, projsplx, projnorm1,\n       projnorm1!, projnorm1t, proxinf!\n\n\"\"\"\nProjection onto the unit simplex {x | sum(x) = τ, x ≥ 0}.\n\n   projsplx!(b, τ)\n\nIn-place variant of `projsplx`.\n\"\"\"\nfunction projsplx!{T}(b::Vector{T}, τ::T)\n\n    n = length(b)\n    bget = false\n\n    idx = sortperm(b, rev=true)\n    tsum = zero(T)\n\n    @inbounds for i = 1:n-1\n        tsum += b[idx[i]]\n        tmax = (tsum - τ)/i\n        if tmax ≥ b[idx[i+1]]\n            bget = true\n            break\n        end\n    end\n\n    if !bget\n        tmax = (tsum + b[idx[n]] - τ) / n\n    end\n\n    @inbounds for i = 1:n\n        b[i] = max(b[i] - tmax, 0)\n    end\n\nend\n\n\"\"\"\nProjection onto the weighted simplex.\n\n    projsplx!(b, c, τ)\n\nThis projects b (in-place) onto the unit simplex weighted by c.\n\"\"\"\nfunction projsplx!{T}(b::Vector{T}, c::Vector{T}, τ::T)\n\n    n = length(b)\n    bget = false\n\n    @assert length(b) == length(c) \"lengths must match\"\n    @assert minimum(c) > 0 \"c is not positive.\"\n\n    idx = sortperm(b./c, rev=true)\n    tsum = csum = zero(T)\n\n    @inbounds for i = 1:n-1\n        j = idx[i]\n        tsum += b[j]*c[j]\n        csum += c[j]*c[j]\n        tmax = (tsum - τ) / csum\n        if tmax >= b[idx[i+1]] / c[idx[i+1]]\n            bget = true\n            break\n        end\n    end\n\n    if !bget\n        p = idx[n]\n        tsum += b[p]*c[p]\n        csum += c[p]*c[p]\n        tmax = (tsum - τ) / csum\n    end\n\n    for i = 1:n\n        @inbounds b[i] = max(b[i] - c[i]*tmax, 0)\n    end\n\n    return\n\nend\n\n\"\"\"\nProjection onto the simplex.\n\n  projsplx(b, τ) -> x\n\nVariant of `projsplx`.\n\"\"\"\nfunction projsplx(b::Vector, τ)\n    x = copy(b)\n    projsplx!(x, τ)\n    return x\nend\n\n\"\"\"\nProjection onto the weighted simplex.\n\n    projsplx(b, c, τ) -> x\n\nVariant of `projsplx!`.\n\"\"\"\nfunction projsplx(b::Vector, c::Vector, τ)\n    x = copy(b)\n    projsplx!(x, c, τ)\n    return x\nend\n\n# s = sign_abs!(x) returns\n#     s[i] = true  if x[i] > 0\n#     s[i] = false otherwise\n# and x = abs(x).\nfunction sign_abs!(x::Vector)\n  n = length(x)\n  s = Array{Bool}(n)\n  @inbounds for i=1:n\n    s[i] = x[i] ≥ 0\n    x[i] = abs(x[i])\n  end\n  return s\nend\n\n# set_sign!(x, s) sets the sign of x based on s.\nfunction set_sign!(x::Vector, s::Vector{Bool})\n  n = length(x)\n  @inbounds for i=1:n\n      x[i] = s[i] ? x[i] : -x[i]\n  end\nend\n\n\"\"\"\nProjection onto the 1-norm ball\n\n    {x | ||x||₁ ≤ τ }.\n\nIn-place variant of `projnorm1`.\n\"\"\"\nfunction projnorm1!(b::Vector, τ::Real)\n    norm(b,1) > τ || return\n    s = sign_abs!(b)\n    projsplx!(b, τ)\n    set_sign!(b, s)\nend\n\n\"\"\"\nProjection onto the weighted 1-norm ball\n\n    {x | ||diag(c)x||₁ ≤ τ }, c > 0.\n\nIn-place variant of `projnorm1`.\n\"\"\"\nfunction projnorm1!(b::Vector, c::Vector, τ::Real)\n    norm(b,1) > τ || return\n    s = sign_abs!(b)\n    projsplx!(b, c, τ)\n    set_sign!(b, s)\nend\n\n\"\"\"\nProjection onto the weighted 1-norm ball.\n\nVariant of `projnorm1!`.\n\"\"\"\nfunction projnorm1(b::Vector, c::Vector, τ::Real)\n    x = copy(b)\n    projnorm1!(x, c, τ)\n    return x\nend\n\n\"\"\"\nProjection onto the 1-norm ball.\n\nVariant of `projnorm1!`.\n\"\"\"\nfunction projnorm1(b::Vector, τ::Real)\n    x = copy(b)\n    projnorm1!(x, τ)\n    return x\nend\n\n\"\"\"\nProximal map of the scaled infinity norm.\n    prox_inf(x,λ) = x - proj(x | λ𝔹₁)\n     env_inf(x,λ) = (1/2λ)||x||² - (1/2λ)dist²(x | λ𝔹₁)\nModifies `x` in place; returns the envelope.\n\"\"\"\nfunction proxinf!(x::Vector, λ::Real)\n  λ == 0 && return norm(x, Inf)\n  nrmx2 = dot(x,x)\n  xp = projnorm1(x, λ)\n  BLAS.axpy!(-1., xp, x) # x <- x - xp\n  return nrmx2/(2λ) - dot(x,x)/(2λ)\nend\n\n\"\"\"\nProximal map of the scaled infinity norm.\nReturn variant of `proxinf!`\n\"\"\"\nfunction proxinf(x::Vector, λ::Real)\n    z = copy(x)\n    proxinf!(z, λ)\n    return z\nend\n\nend # module\n", "meta": {"hexsha": "1f1a1b09c8ad379adab896c6c17b5c55f8c2bbcf", "size": 3727, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ProjSplx.jl", "max_stars_repo_name": "MPF-Optimization-Laboratory/ProjSplx.jl", "max_stars_repo_head_hexsha": "a048ca835cc0f67149a4dd675b7cc9c0e706947c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ProjSplx.jl", "max_issues_repo_name": "MPF-Optimization-Laboratory/ProjSplx.jl", "max_issues_repo_head_hexsha": "a048ca835cc0f67149a4dd675b7cc9c0e706947c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ProjSplx.jl", "max_forks_repo_name": "MPF-Optimization-Laboratory/ProjSplx.jl", "max_forks_repo_head_hexsha": "a048ca835cc0f67149a4dd675b7cc9c0e706947c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0048309179, "max_line_length": 63, "alphanum_fraction": 0.5460155621, "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7551644675665484}}
{"text": "import Base.:+\nimport Base.:-\nimport Base.:*\n\n\nexport ℝ³\nexport cross\n\n\n\"\"\"\n    Represents a point in ℝ³.\n\nfield: a.\n\"\"\"\nstruct ℝ³ <: VectorSpace\n    a::Array{Float64}\n    ℝ³(x₁::Real, x₂::Real, x₃::Real) = new(float.([x₁; x₂; x₃]))\n    ℝ³(a::Array) = begin\n        @assert(length(a) == 3, \"The input vector must contain exactly three elements.\")\n        ℝ³(a...)\n    end\nend\n\n\n\n## Unary Operators ##\n\n\n+(r::ℝ³) = r\n-(r::ℝ³) = ℝ³(-vec(r))\n\n\n## Binary Operators ##\n\n\n+(r1::ℝ³, r2::ℝ³) = ℝ³(vec(r1) + vec(r2))\n-(r1::ℝ³, r2::ℝ³) = ℝ³(vec(r1) - vec(r2))\n*(r::ℝ³, λ::Real) = ℝ³(λ .* vec(r))\n*(λ::Real, r::ℝ³) = r * λ\n\n\n\"\"\"\n    cross(r1, r2)\n\nPerform a cross product with the given vectors `r1` and `r2`.\n\"\"\"\ncross(r1::ℝ³, r2::ℝ³) = begin\n    M = transpose(reshape([vec(r1); vec(r1); vec(r2)], :, length(r1)))\n    M = convert(Array{Float64}, M)\n    ℝ³(map(x -> cofactor(M, 1, x), 1:length(r1)))\nend\n\n\nBase.isapprox(a::Array{ℝ³},\n              b::Array{ℝ³};\n              atol::Float64 = TOLERANCE) = begin\n    for (elementa, elementb) in zip(a, b)\n        if isapprox(elementa, elementb, atol = atol) == false\n            return false\n        end\n    end\n    return true\nend\n", "meta": {"hexsha": "af44717c60ea748e38eff10074fc83a711dccfc4", "size": 1169, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linearalgebra/real3.jl", "max_stars_repo_name": "SimonDanisch/Porta.jl", "max_stars_repo_head_hexsha": "70a5b6586b74f5d76d3add8c9f305071dea13b6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2020-03-28T05:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T22:16:31.000Z", "max_issues_repo_path": "src/linearalgebra/real3.jl", "max_issues_repo_name": "iamazadi/Porta", "max_issues_repo_head_hexsha": "73a97d879d06a1466ff3b966b2ea8e8a846d4c78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-15T12:36:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-15T12:36:59.000Z", "max_forks_repo_path": "src/linearalgebra/real3.jl", "max_forks_repo_name": "iamazadi/Porta", "max_forks_repo_head_hexsha": "73a97d879d06a1466ff3b966b2ea8e8a846d4c78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-09-13T20:28:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T03:31:59.000Z", "avg_line_length": 18.265625, "max_line_length": 88, "alphanum_fraction": 0.5474764756, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938536, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.755164467400329}}
{"text": "function khayyam_triangle(lentingle)\n    output = []\n    for i in 1:lentingle\n        push!(output, [])\n        for j in 1:i\n            if j == 1\n                append!(output[i], 1)\n            elseif j == i\n                append!(output[i], 1)\n            else j != 1 && j != i\n                add = output[i - 1][j] + output[i - 1][j - 1]\n                append!(output[i], add)\n            end\n        end\n    end\n    return output\nend\n", "meta": {"hexsha": "ec79b061655a41111bd405f71e9d8de5cb9e1822", "size": 443, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Fractals-code/Khayyam-triangle.jl", "max_stars_repo_name": "shahmari/A-few-fractals-in-Julia", "max_stars_repo_head_hexsha": "bf0373174af16d1473e8e865377cac061b7191d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-25T09:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T12:35:32.000Z", "max_issues_repo_path": "Fractals-code/Khayyam-triangle.jl", "max_issues_repo_name": "shahmari/A-few-fractals-in-Julia", "max_issues_repo_head_hexsha": "bf0373174af16d1473e8e865377cac061b7191d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Fractals-code/Khayyam-triangle.jl", "max_forks_repo_name": "shahmari/A-few-fractals-in-Julia", "max_forks_repo_head_hexsha": "bf0373174af16d1473e8e865377cac061b7191d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6111111111, "max_line_length": 61, "alphanum_fraction": 0.4130925508, "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7551644672341093}}
{"text": "# A test problem coming from LSQR.\n\nusing LinearOperators\n\n\nfunction lstp(nrow :: Int, ncol :: Int, ndupl :: Int, npower :: Int, λ :: Real, x :: Array)\n\n  # LSTP  generates a sparse least-squares test problem of the form\n  #\n  #   minimize ‖ [A ] x - [b] ‖\n  #            ‖ [λI]     [0] ‖\n  #\n  # having a specified solution x.  The matrix A is constructed\n  # in the form A = HY*D*HZ, where D is an nrow by ncol diagonal matrix,\n  # and HY and HZ are Householder transformations.\n\n  @assert(nrow >= ncol);\n\n  # Construct two unit vectors for the Householder transformations.\n  # fourpi = 4π;\n  fourpi = 4 * 3.141592;    # This is the approximation used in Mike's original subroutine.\n  α = fourpi / nrow;        # 4π / nrow;\n  β = fourpi / ncol;        # 4π / ncol;\n  hy = map(sin, [1:nrow;] * α)\n  hz = map(cos, [1:ncol;] * β)\n\n  α = norm(hy); hy /= α; HY = opHouseholder(hy);  # HY is nrow x nrow.\n  β = norm(hz); hz /= β; HZ = opHouseholder(hz);  # HZ is ncol x ncol.\n\n  # Set the diagonal matrix D containing the singular values of A.\n  d = (div.(([0:ncol-1;] .+ ndupl), ndupl) * ndupl / ncol).^npower;  # Integer div!\n  D = opDiagonal(nrow, ncol, d);\n  A = HY * D * HZ;\n\n  Acond = abs(d[ncol] / d[1]);\n\n  # Compute residual vector.\n  r = zeros(nrow);\n  r[1:ncol]  = HZ * x ./ d;\n  t = 1.0;\n  for i = ncol + 1 : nrow\n    j = i - ncol;\n    r[i] = t * j / nrow;\n    t = -t;\n  end\n  r = HY * r;\n\n  # Compute right-hand side b = r + Ax.\n  rnorm = norm(r);\n  b = r + A * x;\n\n  return (b, A, D, HY, HZ, Acond, rnorm)\nend\n\n\nfunction test(nrow, ncol, ndupl, npower, damp)\n\n  x = ncol .- [1:ncol;];  # Desired solution.\n  return lstp(nrow, ncol, ndupl, npower, damp, x);\nend\n\n\nfunction testall()\n  damp = 0;  # Must be zero for this problem to be consistent.\n  test(40, 40, 4, 1, damp);\n  test(40, 40, 4, 2, damp);\n  test(40, 40, 4, 3, damp);\n  test(40, 40, 4, 4, damp);\nend\n", "meta": {"hexsha": "74064f7a760e649e806057d980253b34e79f6b00", "size": 1871, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/gen_lsq.jl", "max_stars_repo_name": "abelsiqueira/Krylov.jl", "max_stars_repo_head_hexsha": "dc0ca5466f7f1f7e65958fe016e3a06b858e3df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-06T18:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T18:14:15.000Z", "max_issues_repo_path": "test/gen_lsq.jl", "max_issues_repo_name": "abelsiqueira/Krylov.jl", "max_issues_repo_head_hexsha": "dc0ca5466f7f1f7e65958fe016e3a06b858e3df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/gen_lsq.jl", "max_forks_repo_name": "abelsiqueira/Krylov.jl", "max_forks_repo_head_hexsha": "dc0ca5466f7f1f7e65958fe016e3a06b858e3df0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-05T10:58:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T10:58:57.000Z", "avg_line_length": 26.7285714286, "max_line_length": 91, "alphanum_fraction": 0.5777659006, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7551529017603892}}
{"text": "get_x(vec::SA.SVector) = vec[1]\nget_y(vec::SA.SVector) = vec[2]\n\nrotate_plus_90(vec::SA.SVector{2}) = typeof(vec)(-vec[2], vec[1])\nrotate_minus_90(vec::SA.SVector{2}) = typeof(vec)(vec[2], -vec[1])\nrotate_180(vec::SA.SVector{2}) = -vec\n\nrotate(x::T, y::T, c::T, s::T) where {T} = SA.SVector(c * x - s * y, s * x + c * y)\nrotate(vec::SA.SVector{2, T}, theta::T) where {T} = rotate(vec[1], vec[2], cos(theta), sin(theta))\nrotate(vec::SA.SVector{2, T}, dir::SA.SVector{2, T}) where {T} = rotate(vec[1], vec[2], dir[1], dir[2])\n\nget_relative_direction(dir1::SA.SVector{2, T}, dir2::SA.SVector{2, T}) where {T} = typeof(dir1)(dir2[1] * dir1[1] + dir2[2] * dir1[2], dir2[2] * dir1[1] - dir2[1] * dir1[2])\ninvert_relative_direction(dir::SA.SVector{2}) = typeof(dir)(dir[1], -dir[2])\n\nfunction invert(pos::SA.SVector{2, T}, dir::SA.SVector{2, T}) where {T}\n    inv_dir = invert_relative_direction(dir)\n    inv_pos = -rotate(pos, inv_dir)\n    return inv_pos, inv_dir\nend\n", "meta": {"hexsha": "1b9ca364c835fe91a01e2625bc4ec9c0650f5447", "size": 962, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/position_and_orientation.jl", "max_stars_repo_name": "Sid-Bhatia-0/PhysicsEngine2D", "max_stars_repo_head_hexsha": "8c12996f073915e6a8c764de4685b0f3eb819757", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/position_and_orientation.jl", "max_issues_repo_name": "Sid-Bhatia-0/PhysicsEngine2D", "max_issues_repo_head_hexsha": "8c12996f073915e6a8c764de4685b0f3eb819757", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/position_and_orientation.jl", "max_forks_repo_name": "Sid-Bhatia-0/PhysicsEngine2D", "max_forks_repo_head_hexsha": "8c12996f073915e6a8c764de4685b0f3eb819757", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.1, "max_line_length": 173, "alphanum_fraction": 0.6340956341, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939516, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7551529001018319}}
{"text": "module MagicSquares\n\nexport MagicSquare, ismagical\n\nimmutable MagicSquare{T<:Integer}\n    n::Integer\n    data::Array{T}\n\n    MagicSquare(data::Array{T}) = begin\n        n = convert(Int, √length(data))\n        new(n, data)\n    end\nend\n\nMagicSquare{T <: Integer}(data::Array{T}) = MagicSquare{T}(data)\nMagicSquare{T <: Integer}(n::T) = MagicSquare{T}(zeros(T, n*n))\n\n\nBase.shuffle!(m::MagicSquare) = shuffle!(m.data)\nBase.show(io::IO, m::MagicSquare) = begin\n    if(ismagical(m))\n        println(\"Magic square with sum=$(sum(m.data[1:m.n]))\")\n    else\n        println(\"Non-magic square.\")\n    arr = reshape(m.data, m.n, m.n)\n    for i ∈ 1:m.n\n        println(io, arr[i, :])\n    end\nend\n\n\nfunction ismagical(m::MagicSquare)\n    n = m.n\n    s = sum(m.data[1:n])\n    data1 = reshape(m.data, n, n)\n    data2 = data1'\n    diagsum1 = s\n    diagsum2 = s\n    for i ∈ 1:n\n        if(s != sum(data1[i, :]) || s != sum(data2[i, :]))\n            return false\n        end\n        diagsum1 -= data1[i, i]\n        diagsum2 -= data1[i, n-i+1]\n    end\n    if diagsum1 == 0 && diagsum2 == 0\n        return true\n    end\n    return false\nend\n\n\nend # module\n", "meta": {"hexsha": "d515e2c12a2e74de11b79a89bdb71106d369523d", "size": 1135, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MagicSquares.jl", "max_stars_repo_name": "tamasgal/MagicSquares.jl", "max_stars_repo_head_hexsha": "1be267f0900910e4ea44fabbce947298313412b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MagicSquares.jl", "max_issues_repo_name": "tamasgal/MagicSquares.jl", "max_issues_repo_head_hexsha": "1be267f0900910e4ea44fabbce947298313412b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MagicSquares.jl", "max_forks_repo_name": "tamasgal/MagicSquares.jl", "max_forks_repo_head_hexsha": "1be267f0900910e4ea44fabbce947298313412b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0185185185, "max_line_length": 64, "alphanum_fraction": 0.5656387665, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.7551528992844094}}
{"text": "# Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/\n#  Niccolò Antonello <nantonel@idiap.ch>\n\nexport nlogML\n\n\"\"\"\n`nlogML(Nt,a,A,y)`\n\nComputes the negative log Maximum Likelihood (ML) normalized by the sequence length (``\\\\log(P(\\\\mathbf{X}))/N_t``) of a Hidden Markov Model (HMM) with `Ns` states, transition matrix `A` (a `Ns` × `Ns` matrix), initial probabilities `a` (`Ns`-vector) and observation probabilities `y` (a `Ns`×`Nt` matrix) for `Nt` observations. All `Array`s must have the same element type.\n\n`nlogML(Nt,t2tr,A,y)`\n\nReturns the negative log Maximum Likelihood (ML) normalized by the sequence length (``\\\\log(P(\\\\mathbf{X}))/N_t``) with a constrained path (see [`forward`](@ref)).\n\"\"\"\nnlogML(Nt::Integer,c) = -sum(log.(c))/Nt\nnlogML(Nt::Array,cs) = sum( [-sum(log.(c))/Nt[i] for (i,c) in enumerate(cs)])\n\nfunction nlogML(Nt::Integer,a,A,y)\n  alpha, c = forward(Nt,a,A,y)\n  return nlogML(Nt,c)\nend\n\nfunction nlogML(Nt::Array,a,A,y)\n  alphas, cs = forward(Nt,a,A,y)\n  return nlogML(Nt,cs) \nend\n\nexport nlogMLlog\n\"\"\"\n`nlogMLlog(Nt,A,a,y)`\n\nSame as [`nlogML`](@ref) but expects `A`, `a` and `y` to be in the log-domain.\n\"\"\"\nfunction nlogMLlog(Nt,a,A,y)\n  alpha, logML = logforward(Nt,a,A,y)\n  return -sum(logML) \nend\n", "meta": {"hexsha": "c6ce2280bef8ea0264516ec11ea8c2689af44a1b", "size": 1244, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/losses.jl", "max_stars_repo_name": "idiap/HMMGradients.jl", "max_stars_repo_head_hexsha": "7b005bdb8c257556bf6409030787788d9d1a01e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-12-07T17:04:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-08T15:24:28.000Z", "max_issues_repo_path": "src/losses.jl", "max_issues_repo_name": "idiap/HMMGradients.jl", "max_issues_repo_head_hexsha": "7b005bdb8c257556bf6409030787788d9d1a01e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-07T15:01:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-07T16:25:45.000Z", "max_forks_repo_path": "src/losses.jl", "max_forks_repo_name": "idiap/HMMGradients.jl", "max_forks_repo_head_hexsha": "7b005bdb8c257556bf6409030787788d9d1a01e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7368421053, "max_line_length": 374, "alphanum_fraction": 0.674437299, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7551528971815714}}
{"text": "\"\"\"\nCalculates the reference variable for ``μ`` when the elements in vector ``x`` comes from a normal distribution.\nSee also: [`sample_mean`](@ref), [`sample_variance`](@ref).\n\"\"\"\nfunction normal_reference_mu_unknown_variance(μ::AbstractFloat, x::Vector)\n    n = length(x) \n    x̅ = sample_mean(x)\n    s = √(sample_variance(x))\n    T = (x̅ - μ) / (s / √(n))\n    return T\nend\n\n\n\"\"\"\nCalculates the reference variable for ``μ`` when the elements in vector ``x`` comes from a normal distribution.\nThis time the variance ``σ²`` has to be known for the distribution.\nSee also: [`sample_mean`](@ref).\n\"\"\"\nfunction normal_reference_mu_known_variance(μ::AbstractFloat, σ²::AbstractFloat, x::Vector)\n    n = length(x) \n    x̅ = sample_mean(x)\n    σ = √(σ²)\n    T = (x̅ - μ) / (σ / √(n))\n    return T \nend\n\n\n\"\"\"\nReference variable for ``σ²`` when the elements in vector ``x`` comes from a normal distribution.\nSee also: [`sample_variance`](@ref).\n\"\"\"\nfunction normal_reference_sigma(σ²::AbstractFloat, x::Vector)\n    n = length(x)\n    s² = sample_variance(x)\n    T = (n - 1) * s² / σ²\n    return T\nend\n\n\n\"\"\"\nCalculates the reference variable for tests of the difference between two means.\nThis variable is used when the variance is known and different for the two samples.\nSee also: [`sample_mean`](@ref).\n\"\"\"\nfunction normal_reference_two_sample_mu_known_variance(μᵪ::AbstractFloat, μᵧ::AbstractFloat, σ²ᵪ::AbstractFloat, σ²ᵧ::AbstractFloat, x::Vector, y::Vector)\n    nᵪ = length(x)\n    nᵧ = length(y)\n    x̅ = sample_mean(x) \n    y̅ = sample_mean(x)\n    T = ((x̅ - y̅) - (μᵪ - μᵧ)) / √(σ²ᵪ / nᵪ + σ²ᵧ / nᵧ)\n    return T\nend\n\n\n\"\"\"\nCalculates the reference variable for tests of the difference between two means.\nThis variable is used when the variance is unknown but equal for the two samples.\nSee also: [`sample_mean`](@ref), [`two_sample_variance`](@ref).\n\"\"\"\nfunction normal_reference_two_sample_mu_unknown_equal_variance(μᵪ::AbstractFloat, μᵧ::AbstractFloat, x::Vector, y::Vector)\n    nᵪ = length(x)\n    nᵧ = length(y)\n    x̅ = sample_mean(x) \n    y̅ = sample_mean(x)\n    s = √(two_sample_variance(x, y))\n    T = ((x̅ - y̅) - (μᵪ - μᵧ)) / (s * √(1 / nᵪ + 1 / nᵧ))  \n    return T\nend\n\n\n\"\"\"\nCalculates the reference variable for tests of the difference between two means.\nThis variable is used when the variance is unknown but not necessarily equal for the two samples.\nSee also: [`sample_mean`](@ref), [`sample_variance`](@ref), [`two_sample_degrees_of_freedom_unknown_variance`](@ref).\n\"\"\"\nfunction normal_reference_two_sample_mu_unknown_variance(μᵪ::AbstractFloat, μᵧ::AbstractFloat, x::Vector, y::Vector)\n    nᵪ = length(x)\n    nᵧ = length(y)\n    x̅ = sample_mean(x) \n    y̅ = sample_mean(x)\n    s²ᵪ = sample_variance(x)\n    s²ᵧ = sample_variance(y)\n    T = ((x̅ - y̅) - (μᵪ - μᵧ)) / √(s²ᵪ / nᵪ + s²ᵧ / nᵧ)\n    return T   \nend\n\n\n\"\"\"\nCalculates the degrees of freedom of the t-distribution that the reference variable above is from.\nSee also: [`sample_variance`](@ref), [`normal_reference_two_sample_mu_unknown_variance`](@ref).\n\"\"\"\nfunction two_sample_degrees_of_freedom_unknown_variance(x::Vector, y::Vector)\n    nᵪ = length(x)\n    nᵧ = length(y)\n    s²ᵪ = sample_variance(x)\n    s²ᵧ = sample_variance(y)\n    first = 1 / (nᵪ - 1)\n    second = (nᵧ * s²ᵪ)^2 / (nᵧ * s²ᵪ + nᵪ * s²ᵧ)^2\n    third = 1 / (nᵧ - 1)\n    fourth = (nᵪ * s²ᵧ)^2 / (nᵧ * s²ᵪ + nᵪ * s²ᵧ)^2\n    f = 1 / (first * second + third * fourth)\n    return f\nend\n\n\n\"\"\"\nCalculates the interval for the estimated mean difference of two paired samples.\nSee also: [`sample_mean`](@ref), [`sample_variance`](@ref).  \n\"\"\"\nfunction normal_interval_two_sample_paired(x::Vector, y::Vector, α::AbstractFloat)\n    n = length(x)\n    z = y .- x \n    z̅ = sample_mean(z)\n    dist = tDistribution(n-1)  \n    t = quantile_finder(dist, α)\n    s = √(sample_variance(z))\n    I = [z̅ - t * s / √(n), z̅ + t * s / √(n)]  \n    return I\nend\n\n\nfunction normal_interval_mu_unknown_variance(μ::AbstractFloat, x::Vector, α::AbstractFloat)\n    \nend\n\n\nfunction normal_interval_mu_known_variance(μ::AbstractFloat, σ²::AbstractFloat, x::Vector, α::AbstractFloat)\n    \nend\n\n\nfunction normal_interval_sigma(x::Vector, α::AbstractFloat)\n    \nend\n\n\nfunction normal_interval_two_sample_mu_known_variance(μᵪ::AbstractFloat, μᵧ::AbstractFloat, σ²ᵪ::AbstractFloat, σ²ᵧ::AbstractFloat, x::Vector, y::Vector, α::AbstractFloat)\n    \nend\n\n\nfunction normal_interval_two_sample_mu_unknown_equal_variance(μᵪ::AbstractFloat, μᵧ::AbstractFloat, x::Vector, y::Vector, α::AbstractFloat)\n    \nend\n\n\nfunction exp_reference_mu(μ::AbstractFloat, x::Vector)\n    n = length(n)\n    x̅ = sample_mean(x)\n    T = (x̅ - μ) / (μ / √(n)) \n    return T\nend\n\n\nfunction exp_interval_mu(μ::AbstractFloat, x::Vector, α::AbstractFloat)\n    \nend\n\n\nfunction binomial_reference_p()\n    \nend\n\n\nfunction binomial_interval_p()\n    \nend\n\n\nfunction hypergeometric_reference_p()\n    \nend\n\n\nfunction hypergeometric_interval_p()\n    \nend\n\n\nfunction binomial_interval_comparison_of_proportions()\n    \nend\n\n\nfunction poisson_reference_mu()\n    \nend\n\n\nfunction poisson_interval_mu()\n    \nend\n\n\nfunction test()\n    \nend\n", "meta": {"hexsha": "cd5df35fc2347d7c4885619cf239bd9da736d41b", "size": 5092, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Inference.jl", "max_stars_repo_name": "persson-io/Stochastics.jl", "max_stars_repo_head_hexsha": "548c82646d786d9153015bd4a95fd2ea5e4861cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-02T19:01:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-02T19:01:17.000Z", "max_issues_repo_path": "src/Inference.jl", "max_issues_repo_name": "persson-io/Stochastics", "max_issues_repo_head_hexsha": "548c82646d786d9153015bd4a95fd2ea5e4861cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Inference.jl", "max_forks_repo_name": "persson-io/Stochastics", "max_forks_repo_head_hexsha": "548c82646d786d9153015bd4a95fd2ea5e4861cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7171717172, "max_line_length": 171, "alphanum_fraction": 0.6755695208, "num_tokens": 1605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250328, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7551528926264669}}
{"text": "abstract type Basis end\n\nstruct Oscillator <: Basis\n    n::Int64\n    ω::Float64\nend\n\nOscillator(n::Int64) = Oscillator(n,1.0)\nindex(b::Oscillator) = 1:b.n\nspectrum(b::Oscillator) = (0:b.n-1)*b.ω\nqnumbers(b::Oscillator) = 0:b.n-1\n\nfunction hermite(x,n)\n    @assert n >= 1\n    h1 = exp(-x^2 / 2) * (1 / π)^(1 / 4)\n    n == 1 && (return h1)\n    h2 = sqrt(2) * x * h1\n    n == 2 && (return h2)\n    h3 = 0.0\n    for j ∈ 3:n\n        h3 = sqrt(2/(j - 1)) * x * h2 - sqrt((j-2)/(j-1)) * h1\n        h1 = h2; h2 = h3\n    end\n    n > 2 && (return h3)\nend\nhermite(x,n,ω) = hermite(√ω * x,n) * ω ^ ( 1 / 4 )\n\nfunction (b::Oscillator)(x::Array{Float64,1})\n    @unpack ω,n = b\n    T = x * ones(1, n) |> zero\n    T[:,1] = @. hermite(x,1,ω)\n    n >= 2 && (T[:,2] = @. sqrt(2 * ω) * x * T[:,1])\n    for j ∈ index(b)[3:end]\n        m = qnumbers(b)[j]\n        T[:,j] = @. sqrt(2 / m) * (√ω * x) * T[:,j-1] - sqrt((m-1) / m) * T[:,j-2]\n    end\n    return T\nend\n\n(b::Oscillator)(x::LinRange{Float64}) = b(x |> collect)\n(b::Oscillator)(x::Float64,n::Int64) = hermite(x,n,b.ω)\n\nfunction hermite_polar(x,n,ω)\n    p = Progress(n,.1,\"Precomputing...\",20)   # minimum update interval: 1 second\n    T = zeros(size(x)...,n)\n    T[:,:,1] = @. hermite(x,1,ω)\n    next!(p)\n    n >= 2 && (T[:,:,2] = @. sqrt(2 * ω) * x * T[:,:,1])\n    next!(p)\n    for j in 3:n\n        T[:,:,j] = @. sqrt(2 / (j-1)) * (√ω * x) * T[:,:,j-1] - sqrt((j-2) / (j-1)) * T[:,:,j-2]\n    next!(p)\n    end\n    return T\nend\nhermite_polar(x,n) = hermite_polar(x,n,1.)\n\n# filter cartesian data\nfunction filterH(psi,x,N,ω)\n    p = Progress(N,.1,\"Filtering...\",20)\n    H = Oscillator(N,ω)(x)\n    T = inv(H'*H)\n    F̂ = T*H'*psi*H*T\n    psiF = zero(psi)\n        for m = 1:N\n            next!(p)\n            for n = 1:(N+1-m)\n            @. psiF += H[:,m]*F̂[m,n]*H[:,n]'\n            end\n        end\n    return psiF\nend\n\n# covert to polar coords\nfunction slowpolar(psi,x,N,ω)\n    H = Oscillator(N,ω)(x)\n    T = inv(H'*H)\n    F̂ = T*H'*psi*H*T\n\n    Nx = length(x)\n    θ = LinRange(0,2*pi,2*Nx)\n    r = LinRange(0,last(x),Nx/2 |> Int)'\n\n    psiP = zero(θ*r)\n    for m = 1:N, n = 1:(N + 1 - m)\n        @. psiP += hermite(r*cos(θ),m) * F̂[m,n] * hermite(r*sin(θ),n)\n    end\n    return psiP\nend\n\nfunction init_polar(x,N,ω)\n    Nx = length(x)\n    θ = LinRange(0,2*pi,2*Nx)\n    r = LinRange(0,last(x),Nx/2 |> Int)'\n    hx = hermite_polar((@. r*cos(θ)),N,ω)\n    hy = hermite_polar((@. r*sin(θ)),N,ω)\n    return hx,hy\nend\n\nfunction polar(psi,x,ω,Hx,Hy)\n    N = size(Hx)[3]\n    p = Progress(N,1,\"Polar transform...\",20)\n    H = Oscillator(N,ω)(x)\n    T = inv(H'*H)\n    F̂ = T*H'*psi*H*T\n\n    Nx = length(x)\n    Nθ = 2*Nx\n    Nr = Nx/2 |> Int\n    θ = LinRange(0,2*pi,Nθ+1)[1:Nθ]\n    r = LinRange(0,last(x),Nr)'\n\n    psiFP = zeros(eltype(psi),Nθ,Nr)\n    for m = 1:N\n        next!(p)\n        for n = 1:(N + 1 - m)\n        hx = @view Hx[:,:,m]\n        hy = @view Hy[:,:,n]\n        @. psiFP += hx * F̂[m,n] * hy\n    end\n    end\n    return psiFP\nend\n", "meta": {"hexsha": "7b9ee75bab9dfc5a16d9e9152cc1d7ec8bf9102e", "size": 2966, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "_research/analysis.jl", "max_stars_repo_name": "SarThak191119/VortexDistributions.jl", "max_stars_repo_head_hexsha": "8c38d7df82747da16b5976a734f3e0b94e4202c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-10-28T22:45:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T05:44:10.000Z", "max_issues_repo_path": "_research/analysis.jl", "max_issues_repo_name": "SarThak191119/VortexDistributions.jl", "max_issues_repo_head_hexsha": "8c38d7df82747da16b5976a734f3e0b94e4202c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-08-13T02:56:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-29T08:02:48.000Z", "max_forks_repo_path": "_research/analysis.jl", "max_forks_repo_name": "SarThak191119/VortexDistributions.jl", "max_forks_repo_head_hexsha": "8c38d7df82747da16b5976a734f3e0b94e4202c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-07-31T16:16:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-13T00:24:33.000Z", "avg_line_length": 23.9193548387, "max_line_length": 96, "alphanum_fraction": 0.4763991908, "num_tokens": 1263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7551528917853316}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots\n\tRandom.seed!(0)\nend\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.04\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nn, N, alpha = 3, 10^7, 0.1\n\n# ╔═╡ 0a6fcc80-3a99-11eb-3de9-13429e2152ee\nbegin\n\tmyT(nObs) = rand(Normal())/sqrt(rand(Chisq(nObs-1))/(nObs-1))\n\tmcQuantile = quantile([myT(n) for _ in 1:N],alpha)\n\tanalyticQuantile = quantile(TDist(n-1),alpha)\nend\n\n# ╔═╡ 0a990730-3a99-11eb-0e9d-439c6e34d87c\nText(\"Quantile from Monte Carlo: $(mcQuantile)\")\n\n# ╔═╡ 0a998098-3a99-11eb-209b-2f467a34d644\nText(\"Analytic qunatile: $(analyticQuantile)\")\n\n# ╔═╡ 0a9fd40c-3a99-11eb-387b-05b58e298e6e\nbegin\n\txGrid = -5:0.1:5\n\tplot(xGrid, pdf.(Normal(), xGrid), c=:black, label=\"Normal Distribution\")\n\tscatter!(xGrid, pdf.(TDist(1) ,xGrid), \n\t\tc=:blue, msw=0, label=\"DOF = 1\")\n\tscatter!(xGrid, pdf.(TDist(3), xGrid), \n\t\tc=:red, msw=0, label=\"DOF = 3\")\n\tscatter!(xGrid, pdf.(TDist(100),xGrid), \n\t\tc=:green, msw=0, label=\"DOF = 100\", \n\t\txlims=(-4,4), ylims=(0,0.5), xlabel=\"X\", ylabel=\"Density\")\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.04\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═0a6fcc80-3a99-11eb-3de9-13429e2152ee\n# ╠═0a990730-3a99-11eb-0e9d-439c6e34d87c\n# ╠═0a998098-3a99-11eb-209b-2f467a34d644\n# ╠═0a9fd40c-3a99-11eb-387b-05b58e298e6e\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "898974596c1262f3cab304ea7272dc6ee4bed291", "size": 1733, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/listing5.04.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/05/listing5.04.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/05/listing5.04.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 27.9516129032, "max_line_length": 74, "alphanum_fraction": 0.7062896711, "num_tokens": 912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7551528884682167}}
{"text": "\"\"\"\n    PoisLik <: Likelihood\n\nPoisson likelihood\n```math\np(yᵢ = k | fᵢ) = θᵏ\\\\exp(-θ)/k!\n```\nfor ``k ∈ N₀``, where ``θ = \\\\exp(f)`` and ``f`` is the latent Gaussian process.\n\"\"\"\nstruct PoisLik <: Likelihood end\n\n#log of probability density\nfunction log_dens(poisson::PoisLik, f::AbstractVector, y::Vector{Int})\n    #where we exponentiate for positivity f = exp(fi)\n    return y.*f - exp.(f) - lgamma.(1.0 .+ y)\nend\n\n#derivative of pdf wrt latent function\nfunction dlog_dens_df(poisson::PoisLik, f::AbstractVector, y::Vector{Int})\n    return y - exp.(f)\nend\n\n#mean and variance under likelihood\nmean_lik(poisson::PoisLik, f::AbstractVector) = exp.(f)\nvar_lik(poisson::PoisLik, f::AbstractVector) = exp.(f)\n\nget_params(poisson::PoisLik) = []\nnum_params(poisson::PoisLik) = 0\n\nfunction var_exp(ll::PoisLik, y::AbstractArray, m::AbstractArray, V::AbstractMatrix)\n    tot = 0\n    V_diag = diag(V)\n    for (a, b, c) in zip(y, m, V_diag)\n        tot +=  a*b - exp(b + c/2) - log(factorial(convert(Int64, a))) # convert to lgamma(y+1)\n    end\n    return tot\nend\n\nfunction var_exp(ll::PoisLik, y::AbstractArray, m::AbstractArray, V::AbstractArray)\n    tot = 0\n    for (a, b, c) in zip(y, m, V)\n        tot +=  a*b - exp(b + c/2) - log(factorial(convert(Int64, a))) # convert to lgamma(y+1)\n    end\n    return tot\nend\n\n\nfunction var_exp(ll::PoisLik, y::Number, m::Number, V::Number)\n    return y*m - exp(m + V/2) - log(factorial(convert(Int64, y))) # convert to lgamma(y+1)\nend\n\nfunction dv_var_exp(ll::PoisLik, y::Number, m::Number, V::Number)\n    return gradient(x -> var_exp(ll, y, m, x), V)[1]\nend\n", "meta": {"hexsha": "e7200dc6b9455e240802662abc74de273f8a4057", "size": 1593, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/likelihoods/poisson.jl", "max_stars_repo_name": "mcusi/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 284, "max_stars_repo_stars_event_min_datetime": "2015-07-31T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T07:08:58.000Z", "max_issues_repo_path": "src/likelihoods/poisson.jl", "max_issues_repo_name": "mcusi/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 171, "max_issues_repo_issues_event_min_datetime": "2015-05-28T12:04:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T06:48:23.000Z", "max_forks_repo_path": "src/likelihoods/poisson.jl", "max_forks_repo_name": "mcusi/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-05-31T12:44:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:21:38.000Z", "avg_line_length": 28.9636363636, "max_line_length": 95, "alphanum_fraction": 0.6484620213, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7551528868096592}}
{"text": "module Integrators\n\nexport rk4\n\nusing LinearAlgebra\n\nfunction rk4(f::Function, y0::Array{Float64, 1}, t0::Float64,\n             t1::Float64, h::Float64; inplace::Bool=true)\n    y = y0\n    n = round(Int, (t1 - t0)/h)\n    t = t0\n    if ~inplace\n        hist = zeros(n, length(y0))\n    end\n    for i in 1:n\n        k1 = h * f(t, y)\n        k2 = h * f(t + 0.5*h, y + 0.5*k1)\n        k3 = h * f(t + 0.5*h, y + 0.5*k2)\n        k4 = h * f(t + h, y + k3)\n        y = y + (k1 + 2*k2 + 2*k3 + k4)/6\n        if ~inplace\n            hist[i, :] = y\n        end\n        t = t0 + i*h\n    end\n    if ~inplace\n        return hist\n    else\n        return y\n    end\nend\n\nfunction rk4_prop(jac::Function, y0::Array{Float64, 1}, t0::Float64,\n                  t1::Float64, h::Float64)\n    y = y0\n    n = round(Int, (t1 - t0)/h)\n    t = t0\n    A_acc = I\n    for i in 1:n\n        J = jac(t, y)\n        A = I + h*J + h^2/factorial(2)*J^2 + h^3/factorial(3)*J^3 + h^4/factorial(4)*J^4\n        A_acc = A*A_acc\n        y = A*y\n        t = t0 + i*h\n    end\n    return A_acc\nend\n\nend\n", "meta": {"hexsha": "7ff307ee9bfb0e76c77890e7823126ee7031a11f", "size": 1055, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "integrators.jl", "max_stars_repo_name": "eviatarbach/mmda", "max_stars_repo_head_hexsha": "0d8a0ea079553d228389249447dbad4318a649f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-02-08T08:43:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T20:51:12.000Z", "max_issues_repo_path": "integrators.jl", "max_issues_repo_name": "eviatarbach/mmda", "max_issues_repo_head_hexsha": "0d8a0ea079553d228389249447dbad4318a649f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "integrators.jl", "max_forks_repo_name": "eviatarbach/mmda", "max_forks_repo_head_hexsha": "0d8a0ea079553d228389249447dbad4318a649f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1, "max_line_length": 88, "alphanum_fraction": 0.4616113744, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7550540988775154}}
{"text": "# # Automatic differentiation through spherical harmonic transforms\n# This example finds a positive value of $\\lambda$ in:\n# ```math\n# f(r) = \\sin[\\lambda (k\\cdot r)],\n# ```\n# for some $k,r\\in\\mathbb{S}^2$ such that $\\int_{\\mathbb{S}^2} f^2 {\\rm\\,d}\\Omega = 1$.\n# We do this by using derivative information through:\n# ```math\n# \\dfrac{\\partial f}{\\partial \\lambda} = (k\\cdot r) \\cos[\\lambda (k\\cdot r)].\n# ```\n\nusing FastTransforms, LinearAlgebra\n\n# The colatitudinal grid (mod $\\pi$):\nN = 15\nθ = (0.5:N-0.5)/N\n\n# The longitudinal grid (mod $\\pi$):\nM = 2*N-1\nφ = (0:M-1)*2/M\n\n# We precompute a spherical harmonic--Fourier plan:\nP = plan_sph2fourier(Float64, N)\n\n# And an FFTW Fourier analysis plan on $\\mathbb{S}^2$:\nPA = plan_sph_analysis(Float64, N, M)\n\n# Our choice of $k$ and angular parametrization of $r$:\nk = [2/7, 3/7, 6/7]\nr = (θ,φ) -> [sinpi(θ)*cospi(φ), sinpi(θ)*sinpi(φ), cospi(θ)]\n\n# Our initial guess for $\\lambda$:\nλ = 1.0\n\n# Then we run Newton iteration and grab an espresso:\nfor _ in 1:7\n    F = [sin(λ*(k⋅r(θ,φ))) for θ in θ, φ in φ]\n    Fλ = [(k⋅r(θ,φ))*cos(λ*(k⋅r(θ,φ))) for θ in θ, φ in φ]\n    U = P\\(PA*F)\n    Uλ = P\\(PA*Fλ)\n    global λ = λ - (norm(U)^2-1)/(2*sum(U.*Uλ))\n    println(\"λ: $(rpad(λ, 18)) and the 2-norm: $(rpad(norm(U), 18))\")\nend\n", "meta": {"hexsha": "2c5f8f82928a391603fb467f39564ecec31ee702", "size": 1269, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/automaticdifferentiation.jl", "max_stars_repo_name": "eschnett/FastTransforms.jl", "max_stars_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2019-04-13T05:52:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T10:03:15.000Z", "max_issues_repo_path": "examples/automaticdifferentiation.jl", "max_issues_repo_name": "eschnett/FastTransforms.jl", "max_issues_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113, "max_issues_repo_issues_event_min_datetime": "2019-04-12T20:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:16:28.000Z", "max_forks_repo_path": "examples/automaticdifferentiation.jl", "max_forks_repo_name": "eschnett/FastTransforms.jl", "max_forks_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2019-04-23T08:43:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T15:35:17.000Z", "avg_line_length": 28.8409090909, "max_line_length": 87, "alphanum_fraction": 0.6075650118, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678381, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7550540968278951}}
{"text": "function gaussradau(n::Integer)\n    # RADAUPTS   Gauss-Legendre-Radau Quadrature Nodes and Weights\n    if n == 1\n        [-1.0], [2.0]\n    elseif n == 2\n        [-1.0, 1/3], [.5, 1.5]\n    else\n        # Compute via GaussJacobi:\n        x, w = gaussjacobi(n - 1, 0.0, 1.0)\n        @inbounds for i in 1:length(w)\n            w[i] = w[i] / (1.0 + x[i])\n        end\n        pushfirst!(x, -1.0)\n        pushfirst!(w, 2.0 / n^2)\n        x, w\n    end\nend\n", "meta": {"hexsha": "cc692264995f15196f2bf1207b79d2fc1a11dc22", "size": 448, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gaussradau.jl", "max_stars_repo_name": "GeoffChurch/FastGaussQuadrature.jl", "max_stars_repo_head_hexsha": "dadfdd5340f500bbc8a3ad54c04adeb6e5ea4eed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gaussradau.jl", "max_issues_repo_name": "GeoffChurch/FastGaussQuadrature.jl", "max_issues_repo_head_hexsha": "dadfdd5340f500bbc8a3ad54c04adeb6e5ea4eed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gaussradau.jl", "max_forks_repo_name": "GeoffChurch/FastGaussQuadrature.jl", "max_forks_repo_head_hexsha": "dadfdd5340f500bbc8a3ad54c04adeb6e5ea4eed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8888888889, "max_line_length": 66, "alphanum_fraction": 0.4709821429, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951625409308, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7550540953516313}}
{"text": "\n#---------------------------------------------------------\n# # Ideal mean age\n#---------------------------------------------------------\n\n#md # !!! tip\n#md #     This example is also available as a Jupyter notebook:\n#md #     [`ideal_mean_age.ipynb`](@__NBVIEWER_ROOT_URL__/examples/generated/ideal_mean_age.ipynb)\n\n#---------------------------------------------------------\n# ## The model\n#---------------------------------------------------------\n\n# We will simulate the ideal mean age of water.\n# That is, the average amount of time since a water parcel had last contact with the surface.\n\n# ### Tracer equation\n#\n# The ideal mean age is transported with water, is equal to $0$ at the surface, and increases by one second every second everywhere.\n# In other words, the 3D field of the age, $a$, is governed by the tracer equation\n#\n# $$\\frac{\\partial a}{\\partial t} + \\nabla \\cdot \\left[ \\boldsymbol{u} - \\mathbf{K} \\cdot \\nabla \\right] a = 1,$$\n#\n# where $\\nabla \\cdot \\left[ \\boldsymbol{u} - \\mathbf{K} \\cdot \\nabla \\right]$ is a differential operator that represents the transport by the ocean circulation.\n# ($\\boldsymbol{u}$ is the 3D vector field for the advection and $\\mathbf{K}$ is the diffusivity matrix.)\n# In the equation above, we also assume that there is the boundary condition that $a=0$ at the surface.\n\n#---------------------------------\n# ### Discretized tracer equation\n#---------------------------------\n\n# In AIBECS, the linear differential operator defined by $\\nabla \\cdot \\left[ \\boldsymbol{u} - \\mathbf{K} \\cdot \\nabla \\right]$ is approximated by a constant matrix $\\mathbf{T}$ when discretizing the continuous 3D ocean onto the model grid.\n# This matrix can be small (e.g., for models with a few boxes), or large, like for the OCIM (more on the OCIM later).\n# Similarly, the continuous 3D field of the age, $a$, is discretized into a column-vector, $\\boldsymbol{a}$.\n# (We represent scalars in italic, vectors in bold italic, and matrices in upstraight bold.)\n\n# In the discrete case, we replace the boundary condition (that $a = 0$ at the surface) by imposing $\\boldsymbol{a} = 0$ in the surface layer of the model grid.\n# In practice, this is done by restoring $\\boldsymbol{a}$ to $0$ with a very short timescale.\n# The tracer equation thgus takes the form of\n#\n# $$\\frac{\\partial\\boldsymbol{a}}{\\partial t} = -\\mathbf{T} \\, \\boldsymbol{a} + 1 - \\boldsymbol{\\Lambda} \\, \\boldsymbol{a},$$\n#\n# where $\\boldsymbol{\\Lambda}$ is a diagonal matrix with entries equal to $1 / \\tau$ in the surface layer of the model grid and 0 otherwise. \n# The timescale $\\tau$ is chosen to be very small, ensuring that $\\boldsymbol{a}$ is very close to $0$ at the surface.\n# The first term represents the transport by the ocean circulation, the second term the source of 1 second per second everywhere, and the last term the fast relaxation.\n\n#---------------------------------\n# ### Steady-state\n#---------------------------------\n\n# The steady-state is the equilibrium that would be reached if we wait long enough for $a$ to not change anymore.\n# Mathematically, the steady-state is also the state for which\n#\n# $$\\frac{\\partial a}{\\partial t} = 0.$$\n\n# Computationally, in the discrete case, this means that we just need to solve\n#\n# $$0 = -\\mathbf{T} \\, \\boldsymbol{a} + 1 - \\boldsymbol{\\Lambda} \\, \\boldsymbol{a}$$\n#\n# to find $\\boldsymbol{a}$.\n# More specifically, we need to solve\n#\n# $$(\\mathbf{T} + \\boldsymbol{\\Lambda}) \\, \\boldsymbol{a} = 1.$$\n\n# Now that we have the equations laid down, let us chose the circulation transport matrix, $\\mathbf{T}$.\n\n#---------------------------------------------------------\n# ## Using AIBECS\n#---------------------------------------------------------\n\n#md # !!! note\n#md #     If this is the first time you are trying AIBECS, make sure you go through the prerequisites!\n#nb # > **Note**\n#nb # > If this is the first time you are trying AIBECS, make sure you go through the prerequisites!\n\n# AIBECS can interpret tracer equations as long as you arrange them under the generic form:\n#\n# $$\\frac{\\partial \\boldsymbol{x}}{\\partial t} = \\boldsymbol{F}(\\boldsymbol{x}, \\boldsymbol{p}),$$\n#\n# where $\\boldsymbol{F}(\\boldsymbol{x}, \\boldsymbol{p})$ is the rate of change of the state and $\\boldsymbol{p}$ is the vector of model parameters.\n# We only track the age here, so that the entire state of the system is determined by the age itself.\n# In other words, here, $\\boldsymbol{x} = \\boldsymbol{a}$.\n\n# We will use AIBECS to find the steady-state of the system.\n# For AIBECS, this translates into finding the solution of $\\boldsymbol{F}(\\boldsymbol{x}, \\boldsymbol{p}) = 0$.\n\n# We start by telling Julia that we want to use the AIBECS package via\n\nusing AIBECS\n\n#md # !!! note\n#md #     If it's the first time you are running this line, the package will need precompiling.\n#md #     This may take a minute or two.\n#md #     (Just be patient... Or read on while you wait!)\n#\n#nb # > **Note**\n#nb # > If it's the first time you are running this line, the package will need precompiling.\n#nb # > This may take a minute or two.\n#nb # > (Just be patient... Or read on while you wait!)\n#\n#md # !!! note\n#md #     You should see a `Warning` for the `Flatten` package — just disregard it...\n#md #     If you get an error though, please send me a copy of the output/error message, and I will try to troubleshoot it.\n#nb # > **Note**\n#nb # > You should see a `Warning` for the `Flatten` package — just disregard it...\n#nb # > If you get an error though, please send me a copy of the output/error message, and I will try to troubleshoot it.\n\n\n\n#---------------------------------\n# ### The circulation\n#---------------------------------\n\n# We will use the circulation output from the Ocean Circulation Inverse Model (OCIM1).\n# Basically, the OCIM provides researchers and oceanographers with a big sparse matrix that represents the global ocean circulation (advection and diffusion), which allows them to efficiently simulate the transport of passive tracers, like the age.\n# (For more details, see Tim DeVries's [website](https://tdevries.eri.ucsb.edu/models-and-data-products/) and references therein.)\n# With AIBECS, the OCIM0.1 and OCIM1 circulations can be loaded really easily, by simply typing\n\nwet3D, grd, T_OCIM = AIBECS.OCIM1.load()\ntypeof(T_OCIM), size(T_OCIM)\n\n#\n#md # !!! note\n#md #     Julia may ask you to download the OCIM matrix for you, in which case you should say yes (i.e., type `y`).\n#md #     Once downloaded, AIBECS will remember where it downloaded the file and it will only load it from your laptop.\n#nb # > **Note**\n#nb # > Julia may ask you to download the OCIM matrix for you, in which case you should say yes (i.e., type `y`).\n#nb # > Once downloaded, AIBECS will remember where it downloaded the file and it will only load it from your laptop.\n#\n# Additionally to downloading the OCIM file, the `load()` command loads 3 variables in the Julia workspace:\n# - `wet3D` — a 3D array of the model grid, filled with `1`'s at \"wet\" grid boxes and `0`'s and \"land\" grid boxes.\n# - `grd` — a `OceanGrid` object containing information about the 3D grid of the OCIM circulation, like the latitude, longitude, and depth of each grid boxes.\n# - `T_OCIM` — the transport matrix representing advection and diffusion.\n#\n# The second line in command above tells you the type and the size of `T_OCIM`.\n# It is a sparse matrix (CSC just means that it is stored in Compressed Sparse Column format) and is quite big!\n#md # !!! note\n#md #     A sparse matrix is just a matrix with very few non-zero entries.\n#md #     Computationally, sparse matrices are stored differently than full matrices to save memory (no need to save all those zeros), and are much faster to use too!\n#nb # > **Note**\n#nb # > A sparse matrix is just a matrix with very few non-zero entries.\n#nb # > Computationally, sparse matrices are stored differently than full matrices to save memory (no need to save all those zeros), and are much faster to use too!\n\n# Anyway, this looks good, so let's move on with setting up the model!\n#\n# We have already loaded the transport matrix, `T_OCIM`, for the ocean circulation, but we must tell AIBECS that it applies to the age.\n# To do that, we define a function of the parameters (although there are no parameters involved in this case, this is just the way AIBECS works for the moment).\n\nT_age(p) = T_OCIM\n\n# (Functions in Julia can be created in one line, just as above.)\n# That's it for the circulation.\n# Now, let's define the local sources and sinks.\n\n#---------------------------------\n# ### The local sources and sinks\n#---------------------------------\n\n# We will denote the age, $\\boldsymbol{a}$, by the variable `age` in Julia.\n# (It's good practice to use explicit names!)\n# We need to translate the local sources and sinks in our discretized state function $\\boldsymbol{F}(\\boldsymbol{x}, \\boldsymbol{p})$ into Julia code.\n\n# #### The source\n#--------------------------\n\n# Remember the age increases by $1$ second every second and everywhere.\n# So its source function is equal to, well, `1`! (seconds per seconds means it is unitless).\n# Let's create the local source function:\n\nsource_age(age, p) = 1\n\n# #### The sink\n#--------------------------\n\n# Recall that the age must also be $0$ at the surface.\n# And that we implement this boundary condition by restoring the age very fast to $0$ in the surface layer.\n# This will act as the sink for the age.\n# But first, we need to figure out where \"the surface layer\" is.\n# To do that, AIBECS can generate a number of useful constants for you.\n# (You can see the list of functions by typing `varinfo(AIBECS)` at the REPL.)\n# Here we will use the vector of grid box depths, `z`, which AIBECS can generate for us via\n\nz = vector_of_depths(wet3D, grd)\n\n# So what is the top layer?\n# Let's investigate what's the minimum depth:\n\nminimum(z)\n\n# The surface layer in the OCIM grid has its center at about $18\\,$m depth.\n# We can create a mask of the surface layer via `z .< 20`.\n# (This will return a vector of `0`s and `1`s, depending on whether the depth, `z`, is less than `20`.)\n#\n#md # !!! note\n#md #     In Julia (like in MATLAB), placing a dot, `.`, in front of operators is a convenient way to do element-wise operations.\n#nb # > **Note**\n#nb # > In Julia (like in MATLAB), placing a dot, `.`, in front of operators is a convenient way to do element-wise operations.\n#\n# Then, we implement the local sink by restoring the age to `0` with a timescale `τ`, via\n\nfunction sink_age(age, p)\n    τ = p.τ\n    return age .* (z .< 20u\"m\") / τ\nend\n\n#md # !!! note\n#md #     Julia allows you to use unicode for your functions and variables, like for `τ`.\n#nb # > **Note**\n#nb # > Julia allows you to use unicode for your functions and variables, like for `τ`.\n#\n# Here, we have defined a Julia function using the `function` keyword because the sink is a bit more complicated, so that we needed two lines to define it.\n# The first line unpacks the model parameters, which is just the restoring timescale, `τ`, in this case.\n# We will chose the value for `τ` later.\n\n# #### Net sources and sinks\n#--------------------------\n\n# The sources minus the sinks are simply defined by\n\nsms_age(age, p) = source_age(age, p) .- sink_age(age, p)\n\n# #### Model parameters\n#--------------------------\n\n# We must define the parameters... And AIBECS comes with an API for that!\n\nt = empty_parameter_table()    # initialize table of parameters\nadd_parameter!(t, :τ, 1u\"s\")   # add the parameter we want (τ = 1s)\ninitialize_Parameters_type(t, \"IdealAgeParameters\")  # Generate the parameter type\nt\n\n# Note, in particular, that we gave our parameter `τ` a unit.\n# Yes, Julia comes with some nice functionality to deal with units directly!\n# The lines above created a table that contains all the info for generating the parameters vector, $\\boldsymbol{p}$.\n# To generate the parameters in AIBECS we do:\n\np₀ = IdealAgeParameters()\n\n# where we have used the constructor `IdealAgeParameters`, whose name we defined in the previous cell.\n# Here we did not really need to create `p₀` as a parameters vector, since it has only one element, `τ`, in it.\n# However, we are here to learn, and this structure and functionality comes in very handy when one deals with many parameters.\n# (And as you can imagine, having all the parameters in a nice table ready for being used in a publication comes quite handy!)\n\n\n\n# #### State function and Jacobian\n#--------------------------\n\n# Similarly to `p₀`, let's create a state `x₀` to start with.\n# The vector `x₀` will be our initial guess for the state.\n# Let's assume that the age is `1` (seconds) everywhere (as an initial guess):\n\nnb = number_of_wet_boxes(wet3D)  # number of wet boxes\nx₀ = ones(nb)\n\n# The first line above defines the number of wet grid boxes, `nb`.\n# Here, this is also the length of the state vector `x`, because there is only one tracer, `age`.\n# In the second line, the `ones` function creates a vector of `1`s of the size you give it (the number of wet grid boxes, `nb`, here, which we defined earlier).\n\n# Finally, the last step for the set up is to define $\\boldsymbol{F}$.\n# Using AIBECS, this is done via\n\nT_matrices = (T_age,)           # bundles all the transport matrices in a tuple\nsources_minus_sinks = (sms_age,) # bundles all the source-sink functions in a tuple\nF, ∇ₓF = state_function_and_Jacobian(T_matrices, sources_minus_sinks, nb) # generates the state function (and its Jacobian!)\nF(x₀,p₀)\n\n# That's it!\n# We have just created a model of the mean age.\n#\n#\n# Lines 2 and 3 are just telling AIBECS\n# - what transport matrices it should use for the transport of these tracers, and\n# - and what local sources and sinks should be appplied to these tracers\n#\n#md # !!! note\n#md #     The `(x,)` syntax returns a tuple of one element — the comma is necessary because without it, `(x)` would be just like `x` with brackets around it.\n#md #     This interface of AIBECS was developed for case with multiple tracers in mind, and might look a bit odd for a single tracer.\n#md #     But in the future, this might be cleaned up to be easier to work with single tracers.\n#nb # > **Note**\n#nb # > The `(x,)` syntax returns a tuple of one element — the comma is necessary because without it, `(x)` would be just like `x` with brackets around it.\n#nb # > This interface of AIBECS was developed for case with multiple tracers in mind, and might look a bit odd for a single tracer.\n#nb # > But in the future, this might be cleaned up to be easier to work with single tracers.\n\n# The fourth line creates two functions:\n# - `F` — the numerical version of the **state function**, $\\boldsymbol{F}$, of our model of the mean age, and\n# - `∇ₓF` — the **Jacobian matrix** of the state function, i.e., $\\nabla_{\\boldsymbol{x}}\\boldsymbol{F}$.\n# Yes, AIBECS just automatically created an exact derivative of your input, using autodifferentiation via dual numbers.\n# (I'd be very excited to detail how this is implemented here, but it is an entirely different discussion.)\n\n# The last line just checks that our generated `F` works with our initial guess `x₀` and parameter vector `p₀`.\n\n# #### Solving for the steady-state\n#--------------------------\n\n# The Jacobian, `∇ₓF` is essential to solving the steady-state equation $\\boldsymbol{F}(\\boldsymbol{x}, \\boldsymbol{p}) = 0$ fast.\n# Specifically, solving $\\boldsymbol{F}(\\boldsymbol{x}, \\boldsymbol{p}) = 0$ is done via Newton's method.\n# By starting from an initial guess, that you will have to provide, it will iterate over this recursion relation\n#\n# $$\\boldsymbol{x}_{k+1} = \\boldsymbol{x}_{k} - \\nabla_{\\boldsymbol{x}}\\boldsymbol{F}(\\boldsymbol{x}_{k}, \\boldsymbol{p})^{-1} \\boldsymbol{F}(\\boldsymbol{x}_{k}, \\boldsymbol{p})$$\n#\n# until $\\boldsymbol{F}(\\boldsymbol{x}_{k}, \\boldsymbol{p})$ is sufficiently small.\n# Now I should note that here, our age model is linear in $x$ (or `age` in our code), so that the solution will be found in a single iteration, or a sinle \"matrix inversion\", as could be seen from our steady-state equation for $\\boldsymbol{a}$.\n\n#md # !!! note\n#md #     AIBECS comes with a built-in algorithm and an API to solve for the steady-state, so you don't have to worry about all these details!\n#nb # > **Note**\n#nb # > AIBECS comes with a built-in algorithm and an API to solve for the steady-state, so you don't have to worry about all these details!\n\n\n\n# ##### Define the Steady-state problem in AIBECS\n\n# First, we create an instance of the steady-state problem, via\n\nprob = SteadyStateProblem(F, ∇ₓF, x₀, p₀)\n\n# where we have simply provided the state function, $\\boldsymbol{F}$, the Jacobian, $\\nabla_{\\boldsymbol{x}}\\boldsymbol{F}$, the initial guess and the parameters.\n# The `SteadyStateProblem` function is a standard \"DiffEqBase\" constructor that I have overloaded in my package so that you can easily generate the model here.\n\n\n\n# ##### Solve for the steady-state with AIBECS\n\n# Finally, we can find the solution in litterally one line, via the `solve` function:\n\nage = solve(prob, CTKAlg())\n\n# Here, I have provided the `solve` function with two things:\n# - the problem, `prob`, which we just defined, and\n# - the quasi-Newton algorithm that I wrote in Julia, denoted by `CTKAlg()` after C.T. Kelley, who originally wrote it in MATLAB.\n#\n# The last line should take about 10 seconds to 1 minute, depending on your laptop.\n# That's it!\n# We solved for the steady state!\n# Everyone here deserves a nice tap on the shoulder — Good job!\n# Now let's see what this age looks like on a map\n\n\n\n\n#---------------------------------------------------------\n# ## Figures\n#---------------------------------------------------------\n\n# We will plot a horizontal slice of the age at about 1000m depth using Cartopy.\n\n# First, we must rearrange `age` into the 3D model grid.\n# For that we will need the vector of the indices of wet points in the 3D grid, which we will denote by `iwet`, and which AIBECS generates via\n\niwet = indices_of_wet_boxes(wet3D)\n\n# We then rearrange the column vector `age` into a 3D array via\n\nage_3D = fill(NaN, size(wet3D)) # creates a 3D array of NaNs of the same size as `wet3D`\nage_3D[iwet] = age              # Fills the wet grid boxes with the age values\nsize(age_3D)                    # Just to check the size of age_3D\n\n# The last line just shows you the size of `age_3D`, which is a 3D-array as expected.\n\n# Now let us find the index of the depth that is closest to 1000m.\n# To do that we must use the depth information contained in `grd`.\n# Let us first create a small vector of the depths of the grid:\n\ndepth = grd.depth\n\n# We could count the index of the entry we want, but here we will use the `findfirst` function to find the first depth index that is greater than 1000m.\n#nb # (Feel free to change the value of `iz` if you want to see a slice at another depth.)\n\niz = findfirst(depth .> 1000u\"m\")\niz, depth[iz]\n\n# We get `iz = 13`, which is a layer that lies at 1104m, close to 1000m like we wanted.\n#\n# Finally, we need the latitude and longitudes of the grid, contained in `grd`.\n# As for `depth`, we can use the OCIM's `grd` output:\n\nlat, lon = ustrip.(grd.lat), ustrip.(grd.lon)\n\n# So these are the latitudes and longitudes of the map we are about to plot.\n\n# A last thing we can do is convert the age from seconds, `u\"s\"`, to years, `u\"yr\"`, because the age is large.\n# This can be done via the Unitful package (loaded automatically by AIBECS).\n\nage_3D_1000m_yr = age_3D[:,:,iz] * ustrip(1.0u\"s\" |> u\"yr\")\n\n# Finally! Let's have a look at this ideal mean age!\n# To make figures, here, we use Cartopy.\n#nb # (You should have installed Cartopy if you went through the prerequisites correctly).\n# To use it we simply type\n\nENV[\"MPLBACKEND\"]=\"qt5agg\"\nusing PyPlot, PyCall\n\n#md # !!! note\n#md #     The first line is needed for Mac users.\n#md #     It's a bug that should eventually be resolved, but for now this seems to make it work.\n#nb # > **Note**\n#nb # > The first line is needed for Mac users.\n#nb # > It's a bug that should eventually be resolved, but for now this seems to make it work.\n\n\n# We import cartopy, define a new plot, add some coastlines because they are pretty, and add our slice of age at 1000m depth to it via\n\nclf()\nccrs = pyimport(\"cartopy.crs\")\nax = subplot(projection=ccrs.EqualEarth(central_longitude=-155.0))\nax.coastlines()\nlon_cyc = [lon; 360+lon[1]] # making it cyclic for Cartopy\nage_cyc = hcat(age_3D_1000m_yr, age_3D_1000m_yr[:,1])\np = contourf(lon_cyc, lat, age_cyc, levels=0:100:1200, transform=ccrs.PlateCarree(), zorder=-1)\ncolorbar(p, orientation=\"horizontal\")\ngcf() # gets the current figure to display\n\n# That's it!\n# Good job!\n#\n# At 1000m, the age ranges from a few years below deep water formation regions (Wedell Sea, North Atlantic), and reaches a dozen of centuries in the North Pacific!\n# This is pretty good for so little work!\n\n", "meta": {"hexsha": "af00f7ed8a81ecea26fe042923b140bb6ff3beaf", "size": 20833, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/ideal_mean_age.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/AIBECS.jl-ace601d6-714c-11e9-04e5-89b7fad23838", "max_stars_repo_head_hexsha": "75f81609ca4ff67d81bda9f7031ad38e52b61556", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/src/examples/ideal_mean_age.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/AIBECS.jl-ace601d6-714c-11e9-04e5-89b7fad23838", "max_issues_repo_head_hexsha": "75f81609ca4ff67d81bda9f7031ad38e52b61556", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/src/examples/ideal_mean_age.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/AIBECS.jl-ace601d6-714c-11e9-04e5-89b7fad23838", "max_forks_repo_head_hexsha": "75f81609ca4ff67d81bda9f7031ad38e52b61556", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.4845605701, "max_line_length": 248, "alphanum_fraction": 0.686122978, "num_tokens": 5477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7550540931921602}}
{"text": "function HMMsmooth(v,phghm,ph1,pvgh,alpha=[],beta=[];ReturnPairwiseMarginals=false,ReturnLogLikelihood=false)\n    #HMMSMOOTH Smoothing for a Hidden Markov Model (HMM)\n    # [phtgV1T,phthtpgV1T]=HMMsmooth(v,phghm,ph1,pvgh)\n    # Return the HMM pointwise p(h(t)|v(1:T)) and pairwise posterior p(h(t),h(t+1)|#v(1:T)).\n    #\n    # Inputs:\n    # v : visible (observation) sequence\n    # phghm : transition distribution\n    # ph1 : initial distribution\n    # pvgh : emission distribution p(v|h)\n    #\n    # Outputs:\n    # phtgV1T : smoothed posterior p(h(t)|v(1:T))\n    # phthtpgV1T : smoothed pair p(h(t),h(t+1)|v(1:T))\n    T=length(v); H=size(phghm,1);\n\n    if isempty(alpha)\n        alpha,loglik=HMMforward(v,phghm,ph1,pvgh)\n    end\n    if isempty(beta)\n        beta=HMMbackward(v,phghm,pvgh)\n    end\n\n    # smoothed posteriors: pointwise marginals:\n    phtgV1T=zeros(H,T)\n    for t=1:T\n        tmp=alpha[:,t].*beta[:,t]\n\tphtgV1T[:,t]=tmp./sum(tmp)\n    end\n\n    if ReturnPairwiseMarginals\n        # smoothed posteriors: pairwise marginals p(h(t),h(t+1)|v(1:T)):\n        phthtpgV1T=zeros(H,H,T-1)\n        for t=1:T-1\n\t    atmp=alpha[:,t]\n\t    btmp=beta[:,t+1]\n\t    #ctmp = repmat(atmp,1,H).*phghm'.*repmat(pvgh[v[t+1],:].*btmp',H,1)\n            ctmp = repmat(atmp,1,H).*phghm'.*repmat(pvgh[v[t+1],:]'.*btmp',H,1)\n\t    phthtpgV1T[:,:,t]=ctmp./sum(ctmp)\n        end\n        if ReturnLogLikelihood\n            return phtgV1T, phthtpgV1T, loglik\n        end\n        return phtgV1T, phthtpgV1T\n    end\n\n    if ReturnLogLikelihood\n        return phtgV1T,loglik\n    end\n    return phtgV1T\nend\n", "meta": {"hexsha": "1624bd65647865959156b966ab5e72853a86123c", "size": 1582, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HMM/HMMsmooth.jl", "max_stars_repo_name": "davidbarber/Julia0p5ProbabilisticInferenceEngine", "max_stars_repo_head_hexsha": "c00b1432260f641b9a1bddcc8836b34c12c84d05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 42, "max_stars_repo_stars_event_min_datetime": "2016-11-20T14:24:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T20:30:00.000Z", "max_issues_repo_path": "src/HMM/HMMsmooth.jl", "max_issues_repo_name": "davidbarber/Julia0p5ProbabilisticInferenceEngine", "max_issues_repo_head_hexsha": "c00b1432260f641b9a1bddcc8836b34c12c84d05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HMM/HMMsmooth.jl", "max_forks_repo_name": "davidbarber/Julia0p5ProbabilisticInferenceEngine", "max_forks_repo_head_hexsha": "c00b1432260f641b9a1bddcc8836b34c12c84d05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2016-11-08T23:21:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T06:20:53.000Z", "avg_line_length": 30.4230769231, "max_line_length": 109, "alphanum_fraction": 0.6093552465, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.755047189388248}}
{"text": "export UpdateMasseyColley\n\n\"\"\"\n    UpdateMasseyColley\n\n MasseyColley update rule, e.g., see \"Whos's #1\", Langville and Meyer, p.25\n    this is the \"Colleyized Massey method\", i.e., use Colley's matrix on scores\n\n## Parameters (none)\n```\n\"\"\"\nstruct UpdateMasseyColley <: UpdateRule\n# this is a batch calculation that takes no account of past ratings, and\n# has no parameters\nend\n\nfunction update_info( rule::UpdateMasseyColley )\n    info = Dict(\n                :name => \"MasseyColley\",\n                :reference => \"\\\"Whos's #1\\\", Langville and Meyer, p.25\",\n                :computation => \"simultaneous\",\n                :state_model => \"none\",\n                :input => \"score\",\n                :output => \"deterministic\",\n                :model => \"single\",\n                :ties => true,\n                :factors => false,\n                :parameters => [],\n                :record => true\n                )\n    return info\nend\nupdate_info( ::Type{UpdateMasseyColley} ) =  update_info( UpdateMasseyColley() )\n\nfunction update_ratings( rule::UpdateMasseyColley,\n                         input_ratings::RatingsList,\n                         input_competitions::DataFrame)\n    n = size(input_competitions,1)\n    m = length( input_ratings.players )\n    I = player_indexes( input_ratings.players )\n    \n    # construct Colley matrices and vectors\n    C = diagm(0 => 2*ones(Int,m))\n    p = zeros(Int, m)\n    d = input_competitions # just an abbreviation\n    point_diff = d[:,ScoreA] - d[:,ScoreB]\n    for i=1:n\n        p[ I[d[i,PlayerA]] ] +=  point_diff[i]\n        p[ I[d[i,PlayerB]] ] -=  point_diff[i]\n        C[ I[d[i,PlayerA]], I[d[i,PlayerB]] ] -= 1\n        C[ I[d[i,PlayerB]], I[d[i,PlayerA]] ] -= 1\n        C[ I[d[i,PlayerA]], I[d[i,PlayerA]] ] += 1\n        C[ I[d[i,PlayerB]], I[d[i,PlayerB]] ] += 1\n    end\n     \n    # solve Colley's equation\n    r = C \\ p \n    ratings = Dict{String, Float64}()\n    for player in input_ratings.players\n        ratings[player] = r[ I[player] ]\n    end\n        \n    # output ratings list\n    output_ratings = RatingsList(input_ratings.players, ratings )   \n    return output_ratings\nend\n", "meta": {"hexsha": "cbb6af0e0242dca45e4c6cdf71949a342156126f", "size": 2129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/UpdateRules/MasseyColley.jl", "max_stars_repo_name": "JuliaTagBot/RatPack.jl", "max_stars_repo_head_hexsha": "44d5735c1bbfaa97b12d3f418b0e1c4b967da1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/UpdateRules/MasseyColley.jl", "max_issues_repo_name": "JuliaTagBot/RatPack.jl", "max_issues_repo_head_hexsha": "44d5735c1bbfaa97b12d3f418b0e1c4b967da1df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-08T16:23:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T16:23:16.000Z", "max_forks_repo_path": "src/UpdateRules/MasseyColley.jl", "max_forks_repo_name": "JuliaTagBot/RatPack.jl", "max_forks_repo_head_hexsha": "44d5735c1bbfaa97b12d3f418b0e1c4b967da1df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:20:51.000Z", "avg_line_length": 31.776119403, "max_line_length": 80, "alphanum_fraction": 0.5655237201, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7550471784540095}}
{"text": "using Statistics:mean, std\nusing SpecialFunctions:erf\n\n\"\"\"\nnormalize(scoresTrain,\n          scoresTest)\n\nTransform an array of scores into a range between [0,1] using min-max scaling.\n\nParameters\n----------\n      scores_train::AbstractVector{<:Real}\nA vector of training scores, typically the result of [`fit`](@ref) with a detector.\n\n    scores_test::AbstractVector{<:Real}\nA vector of test scores, typically the result of [`score`](@ref) using a previously fitted detector.\n\nReturns\n----------\nnormalized_scores::Tuple{AbstractVector{<:Real}, AbstractVector{<:Real}}\nThe normalized train and test scores.\n\nExamples\n----------\nscores_train, scores_test = ([1, 2, 3], [4, 3, 2, 1, 0])\nscale_minmax(scores_train, scores_test) # ([0.0, 0.5, 1.0], [1.0, 1.0, 0.5, 0.0, 0.0])\nscale_minmax(scores_train) # [0.0, 0.5, 1.0]\n\"\"\"\nfunction scale_minmax(scores_train::Scores, scores_test::Scores)::Tuple{Scores, Scores}\n    minTrain, maxTrain = extrema(scores_train)\n    @assert minTrain < maxTrain \"Cannot normalize scores if they are all equal\"\n    f = scores -> clamp.((scores .- minTrain) ./ (maxTrain - minTrain), 0, 1)\n    f(scores_train), f(scores_test)\nend\n\n\"\"\"\nunify(scores_train,\n      scores_test)\n\nTransform an array of scores into a range between [0,1] using unifying scores as described in [1].\n\nParameters\n----------\n    scores_train::AbstractVector{<:Real}\nA vector of training scores, typically the result of [`fit`](@ref) with a detector.\n\n    scores_test::AbstractVector{<:Real}\nA vector of test scores, typically the result of [`score`](@ref) using a previously fitted detector.\n\nReturns\n----------\nunified_scores::Tuple{AbstractVector{<:Real}, AbstractVector{<:Real}}\nThe unified train and test scores.\n\nExamples\n----------\nscores_train, scores_test = ([1, 2, 3], [4, 3, 2, 1, 0])\nunify(scores_train, scores_test) # ([0.0, 0.0, 0.68..], [0.95.., 0.68.., 0.0, 0.0, 0.0])\nunify(scores_train) # [0.0, 0.0, 0.68..]\n\nReferences\n----------\nKriegel, Hans-Peter; Kroger, Peer; Schubert, Erich; Zimek, Arthur (2011): Interpreting and Unifying Outlier Scores.\n\"\"\"\nfunction scale_unify(scores_train::Scores, scores_test::Scores)::Tuple{Scores, Scores}\n    μ, σ = mean(scores_train), std(scores_train)\n    @assert σ > 0 \"Cannot normalize scores if they are all equal\"\n    f = scores -> clamp.(erf.((scores .- μ) ./ (σ * √2)), 0, 1)\n    f(scores_train), f(scores_test)\nend\n", "meta": {"hexsha": "c8303bd5d17ed7a5bcc66df78185dab7739f88ba", "size": 2370, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/normalization.jl", "max_stars_repo_name": "PallHaraldsson/OutlierDetection.jl", "max_stars_repo_head_hexsha": "0642f1377a8e2a2aa7ab6b8054f864de927b3e4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/normalization.jl", "max_issues_repo_name": "PallHaraldsson/OutlierDetection.jl", "max_issues_repo_head_hexsha": "0642f1377a8e2a2aa7ab6b8054f864de927b3e4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/normalization.jl", "max_forks_repo_name": "PallHaraldsson/OutlierDetection.jl", "max_forks_repo_head_hexsha": "0642f1377a8e2a2aa7ab6b8054f864de927b3e4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3802816901, "max_line_length": 115, "alphanum_fraction": 0.6818565401, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7550471778150717}}
{"text": "# PROX_MATRIX    The proximal operator of a matrix function.\n#\n#   Suppose F is a orthogonally invariant matrix function such that\n#   F(X) = f(s(X)), where s is the singular value map and f is some\n#   absolutely symmetric function. Then\n#\n#     X = prox_matrix(V,lambda,prox_f)\n#\n#   evaluates the proximal operator of F via the proximal operator\n#   of f. Here, it must be possible to evaluate prox_f as prox_f(v,lambda).\n#\n#   For example,\n#\n#     prox_matrix(V,lambda,prox_l1)\n#\n#   evaluates the proximal operator of the nuclear norm at V\n#   (i.e., the singular value thresholding operator).\nfunction prox_matrix(v, lambda, prox_f)\n    U, S, V] = svd(v, 'econ')\n    x = U * diag(prox_f(diag(S), lambda)) * V'\n\treturn x\nend\n", "meta": {"hexsha": "cbf698d70137a2e9a7268592e3df46810f8b7331", "size": 730, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/prox_matrix.jl", "max_stars_repo_name": "johnmyleswhite/Proximal.jl", "max_stars_repo_head_hexsha": "256de4c00557983935c0deaff6d6e4ccdb5da7c3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-08-03T21:31:45.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-20T01:51:56.000Z", "max_issues_repo_path": "src/prox_matrix.jl", "max_issues_repo_name": "johnmyleswhite/Proximal.jl", "max_issues_repo_head_hexsha": "256de4c00557983935c0deaff6d6e4ccdb5da7c3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/prox_matrix.jl", "max_forks_repo_name": "johnmyleswhite/Proximal.jl", "max_forks_repo_head_hexsha": "256de4c00557983935c0deaff6d6e4ccdb5da7c3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-01T18:12:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:12:26.000Z", "avg_line_length": 31.7391304348, "max_line_length": 75, "alphanum_fraction": 0.6890410959, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107861416414, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7550471706155905}}
{"text": "using NearlyNewton, LinearAlgebra, StaticArrays\n\n    function theta(x)\n       if x[1] > 0\n           return atan(x[2] / x[1]) / (2.0 * pi)\n       else\n           return (pi + atan(x[2] / x[1])) / (2.0 * pi)\n       end\n    end\n    f(x) = 100.0 * ((x[3] - 10.0 * theta(x))^2 + (sqrt(x[1]^2 + x[2]^2) - 1.0)^2) + x[3]^2\n\n    function f∇f!(∇f, x)\n        if !(∇f==nothing)\n            if ( x[1]^2 + x[2]^2 == 0 )\n                dtdx1 = 0;\n                dtdx2 = 0;\n            else\n                dtdx1 = - x[2] / ( 2 * pi * ( x[1]^2 + x[2]^2 ) );\n                dtdx2 =   x[1] / ( 2 * pi * ( x[1]^2 + x[2]^2 ) );\n            end\n            ∇f[1] = -2000.0*(x[3]-10.0*theta(x))*dtdx1 +\n                200.0*(sqrt(x[1]^2+x[2]^2)-1)*x[1]/sqrt( x[1]^2+x[2]^2 );\n            ∇f[2] = -2000.0*(x[3]-10.0*theta(x))*dtdx2 +\n                200.0*(sqrt(x[1]^2+x[2]^2)-1)*x[2]/sqrt( x[1]^2+x[2]^2 );\n            ∇f[3] =  200.0*(x[3]-10.0*theta(x)) + 2.0*x[3];\n        end\n\n        fx = f(x)\n        return ∇f==nothing ? fx : (fx, ∇f)\n    end\n    function f∇f(∇f, x)\n        if !(∇f == nothing)\n            gx = similar(x)\n            return f∇f!(gx, x)\n        else\n            return f∇f!(∇f, x)\n        end\n    end\n    function f∇fs(∇f, x)\n        if !(∇f == nothing)\n            if ( x[1]^2 + x[2]^2 == 0 )\n                dtdx1 = 0;\n                dtdx2 = 0;\n            else\n                dtdx1 = - x[2] / ( 2 * pi * ( x[1]^2 + x[2]^2 ) )\n                dtdx2 =   x[1] / ( 2 * pi * ( x[1]^2 + x[2]^2 ) )\n            end\n\n            s1 = -2000.0*(x[3]-10.0*theta(x))*dtdx1 +\n                200.0*(sqrt(x[1]^2+x[2]^2)-1)*x[1]/sqrt( x[1]^2+x[2]^2 )\n            s2 = -2000.0*(x[3]-10.0*theta(x))*dtdx2 +\n                200.0*(sqrt(x[1]^2+x[2]^2)-1)*x[2]/sqrt( x[1]^2+x[2]^2 )\n            s3 = 200.0*(x[3]-10.0*theta(x)) + 2.0*x[3]\n            ∇f = @SVector [s1, s2, s3]\n            return f(x), ∇f\n        else\n            return f(x)\n        end\n    end\n\n    x0 = [-1.0, 0.0, 0.0]\n    xopt = [1.0, 0.0, 0.0]\n\n    res = NearlyNewton.minimize!(f∇f!, x0, (SR1(DirectApprox()), NearlyNewton.NWI()), I+0.0*x0*x0')\n    res = NearlyNewton.minimize!(f∇f!, x0, (BFGS(DirectApprox()), NearlyNewton.NWI()), I+0.0*x0*x0')\n    res = NearlyNewton.minimize!(f∇f!, x0, (BFGS(DirectApprox()), BackTracking()), I+0.0*x0*x0')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n    function himmelblau_gradient!(x::Vector, gradient::Vector)\n               gradient[1] = 4 * x[1] * (x[1]^2 + x[2] - 11) + 2 * (x[1] + x[2]^2 - 7)\n               gradient[2] = 2 * (x[1]^2 + x[2] - 11) + 4 * x[2] * (x[1] + x[2]^2 - 7)\n           end\n\n    function himmelblau!(∇f, x)\n        if !(∇f == nothing)\n            ∇f[1] = 4.0 * x[1]^3 + 4.0 * x[1] * x[2] -\n                44.0 * x[1] + 2.0 * x[1] + 2.0 * x[2]^2 - 14.0\n            ∇f[2] = 2.0 * x[1]^2 + 2.0 * x[2] - 22.0 +\n                4.0 * x[1] * x[2] + 4.0 * x[2]^3 - 28.0 * x[2]\n        end\n\n        fx = (x[1]^2 + x[2] - 11)^2 + (x[1] + x[2]^2 - 7)^2\n        return ∇f == nothing ? fx : (fx, ∇f)\n    end\n\n    function himmelblau!(∇²f, ∇f, x)\n        if !(∇²f == nothing)\n            ∇²f[1, 1] = 12.0 * x[1]^2 + 4.0 * x[2] - 42.0\n            ∇²f[1, 2] = 4.0 * x[1] + 4.0 * x[2]\n            ∇²f[2, 1] = 4.0 * x[1] + 4.0 * x[2]\n            ∇²f[2, 2] = 12.0 * x[2]^2 + 4.0 * x[1] - 26.0\n        end\n        if !(∇f == nothing)\n            ∇f[1] = 4.0 * x[1]^3 + 4.0 * x[1] * x[2] -\n                44.0 * x[1] + 2.0 * x[1] + 2.0 * x[2]^2 - 14.0\n            ∇f[2] = 2.0 * x[1]^2 + 2.0 * x[2] - 22.0 +\n                4.0 * x[1] * x[2] + 4.0 * x[2]^3 - 28.0 * x[2]\n        end\n\n        fx = (x[1]^2 + x[2] - 11)^2 + (x[1] + x[2]^2 - 7)^2\n        if ∇f == nothing && ∇²f == nothing\n            return fx\n        elseif ∇²f == nothing\n            return fx, ∇f\n        else\n            return fx, ∇f, ∇²f\n        end\n    end\n\n    res = minimize!(himmelblau!, [2.0,2.0], Newton(DirectApprox()))\n    res = minimize!(himmelblau!, [2.0,2.0], (Newton(DirectApprox()), NWI()))\n\n\nusing TRS\nimport NearlyNewton: NearlyExactTRSP\n\nstruct TRSolver{T} <: NearlyExactTRSP\n    abstol::T\n    maxiter::Integer\nend\nfunction (ms::TRSolver)(∇f::AbstractVector{T}, H, Δ, p;kwargs...) where T\n    x, info = trs(Symmetric(H), ∇f, Δ)\n    p .= x[:,1]\n    m = dot(∇f, p) + dot(p, H * p)/2\n    interior = norm(p, 2) ≤ Δ\n    return (p=p, mz=m, interior=interior, λ=info.λ, hard_case=info.hard_case, solved=true)\nend\n\n\n    res = minimize!(himmelblau!, [2.0,2.0], (BFGS(DirectApprox()), TRSolver(1e-8, 100)))\n\n\n\n\n\n    function polynomial!(∇²f, ∇f, x)\n        if !isa(∇f, Nothing)\n            ∇f[1] = -2.0 * (10.0 - x[1])\n            ∇f[2] = -4.0 * (7.0 - x[2])^3\n            ∇f[3] = -4.0 * (108.0 - x[3])^3\n        end\n        if !isa(∇²f, Nothing)\n            ∇²f[1, 1] = 2.0\n            ∇²f[1, 2] = 0.0\n            ∇²f[1, 3] = 0.0\n            ∇²f[2, 1] = 0.0\n            ∇²f[2, 2] = 12.0 * (7.0 - x[2])^2\n            ∇²f[2, 3] = 0.0\n            ∇²f[3, 1] = 0.0\n            ∇²f[3, 2] = 0.0\n            ∇²f[3, 3] = 12.0 * (108.0 - x[3])^2\n        end\n        fx = (10.0 - x[1])^2 + (7.0 - x[2])^4 + (108.0 - x[3])^4\n\n        if ∇f == nothing && ∇²f == nothing\n            return fx\n        elseif ∇²f == nothing\n            return fx, ∇f\n        else\n            return fx, ∇f, ∇²f\n        end\n    end\n    function polynomial!(∇f, x)\n        if !isa(∇f, Nothing)\n            ∇f[1] = -2.0 * (10.0 - x[1])\n            ∇f[2] = -4.0 * (7.0 - x[2])^3\n            ∇f[3] = -4.0 * (108.0 - x[3])^3\n        end\n\n        fx = (10.0 - x[1])^2 + (7.0 - x[2])^4 + (108.0 - x[3])^4\n\n        if ∇f == nothing\n            return fx\n        else\n            return fx, ∇f\n        end\n\n    end\n\n        res = minimize!(polynomial!, [2.0,2.0,2.0], (BFGS(DirectApprox()), NWI()))\n\n\n\n\n        function rosenbrock(∇²f, ∇f, x)\n            if !isa(∇f, Nothing)\n                ∇f[1] = -2.0 * (1.0 - x[1]) - 400.0 * (x[2] - x[1]^2) * x[1]\n                ∇f[2] = 200.0 * (x[2] - x[1]^2)\n            end\n            if !isa(∇²f, Nothing)\n                ∇²f[1, 1] = 2.0 - 400.0 * x[2] + 1200.0 * x[1]^2\n                ∇²f[1, 2] = -400.0 * x[1]\n                ∇²f[2, 1] = -400.0 * x[1]\n                ∇²f[2, 2] = 200.0\n            end\n            fx = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2\n\n\n            if ∇f == nothing && ∇²f == nothing\n                return fx\n            elseif ∇²f == nothing\n                return fx, ∇f\n            else\n                return fx, ∇f, ∇²f\n            end\n        end\n\n\n        function rosenbrock(∇f, x)\n            if !isa(∇f, Nothing)\n                ∇f[1] = -2.0 * (1.0 - x[1]) - 400.0 * (x[2] - x[1]^2) * x[1]\n                ∇f[2] = 200.0 * (x[2] - x[1]^2)\n            end\n\n            fx = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2\n\n\n            if ∇f == nothing\n                return fx\n            else\n                return fx, ∇f\n            end\n        end\n\n        function rosenbrock_gradient!(storage, x)\n\n        end\n\n        function rosenbrock_hessian!(storage, x)\n            storage[1, 1] = 2.0 - 400.0 * x[2] + 1200.0 * x[1]^2\n            storage[1, 2] = -400.0 * x[1]\n            storage[2, 1] = -400.0 * x[1]\n            storage[2, 2] = 200.0\n        end\n        res = minimize!(rosenbrock, [2.0,2.0], (BFGS(DirectApprox()), NWI()))\n", "meta": {"hexsha": "9eb283b0041c4d1f2e85ff49290313ab601d89dc", "size": 7239, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/trustregion.jl", "max_stars_repo_name": "pkofod/NearlyNewton.jl", "max_stars_repo_head_hexsha": "f9f0f80f3b5e89dc3c56af838e338c9d77d8356a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/trustregion.jl", "max_issues_repo_name": "pkofod/NearlyNewton.jl", "max_issues_repo_head_hexsha": "f9f0f80f3b5e89dc3c56af838e338c9d77d8356a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/trustregion.jl", "max_forks_repo_name": "pkofod/NearlyNewton.jl", "max_forks_repo_head_hexsha": "f9f0f80f3b5e89dc3c56af838e338c9d77d8356a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.956, "max_line_length": 100, "alphanum_fraction": 0.3772620528, "num_tokens": 3199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.755022773306075}}
{"text": "\nusing DifferentialEquations\nusing SimpleDiffEq\nusing DiffEqCallbacks\nusing Random\nusing Distributions\nusing DiffEqParamEstim\nusing DataFrames\nusing StatsPlots\nusing BenchmarkTools\n\n\nfunction sir_ode!(du,u,p,t)\n    (S,I,R,Y) = u\n    (β,c,γ) = p\n    N = S+I+R\n    infection = β*c*I/N*S\n    recovery = γ*I\n    @inbounds begin\n        du[1] = -infection\n        du[2] = infection - recovery\n        du[3] = recovery\n        du[4] = infection\n    end\n    nothing\nend;\n\n\nδt = 0.1\ntmax = 40.0\ntspan = (0.0,tmax)\nt = 0.0:δt:tmax\nobstimes = 0:1.0:tmax;\n\n\nu0 = [990.0,10.0,0.0,0.0]; # S,I.R,Y\n\n\np = [0.05,10.0,0.25]; # β,c,γ\n\n\naffect!(integrator) = integrator.u[4] = 0.0\ncb_zero = PresetTimeCallback(obstimes,affect!)\n\n\nprob_ode = ODEProblem(sir_ode!,u0,tspan,p)\n\n\nsol_ode = solve(prob_ode,callback=cb_zero);\n\n\ndf_ode = DataFrame(sol_ode(obstimes)')\ndf_ode[!,:t] = obstimes;\n\n\n@df df_ode plot(:t,\n    [:x1 :x2 :x3 :x4],\n    label=[\"S\" \"I\" \"R\" \"Y\"],\n    xlabel=\"Time\",\n    ylabel=\"Number\")\n\n\nRandom.seed!(1234);\n\n\ndata = rand.(Poisson.(df_ode[!,:x4]))\n\n\nplot(obstimes,data)\nplot!(obstimes,df_ode[!,:x4])\n\n\nusing Optim\n\n\nfunction ss1(β)\n    prob = remake(prob_ode,u0=[990.0,10.0,0.0,0.0],p=[β,10.0,0.25])\n    sol = solve(prob,Tsit5(),callback=cb_zero,saveat=obstimes)\n    sol_data = sol(obstimes)[4,:]\n    return(sum((sol_data - data) .^2))\nend\n\n\nfunction nll1(β)\n    prob = remake(prob_ode,u0=[990.0,10.0,0.0,0.0],p=[β,10.0,0.25])\n    sol = solve(prob,Tsit5(),callback=cb_zero,saveat=obstimes)\n    sol_data = sol(obstimes)[4,:]\n    -sum(logpdf.(Poisson.(sol_data),data))\nend\n\n\nlower1 = 0.0\nupper1 = 1.0\ninitial_x1 = 0.1\n\n\nopt1_ss = Optim.optimize(ss1,lower1,upper1)\n\n\nopt1_nll = Optim.optimize(nll1,lower1,upper1)\n\n\nfunction ss2(x)\n    (i0,β) = x\n    I = i0*1000.0\n    prob = remake(prob_ode,u0=[1000-I,I,0.0,0.0],p=[β,10.0,0.25])\n    sol = solve(prob,Tsit5(),callback=cb_zero,saveat=obstimes)\n    sol_data = sol(obstimes)[4,:]\n    return(sum((sol_data - data) .^2))\nend\n\n\nfunction nll2(x)\n    (i0,β) = x\n    I = i0*1000.0\n    prob = remake(prob_ode,u0=[1000-I,I,0.0,0.0],p=[β,10.0,0.25])\n    sol = solve(prob,Tsit5(),callback=cb_zero,saveat=obstimes)\n    sol_data = sol(obstimes)[4,:]\n    -sum(logpdf.(Poisson.(sol_data),data))\nend\n\n\nlower2 = [0.0,0.0]\nupper2 = [1.0,1.0]\ninitial_x2 = [0.01,0.1]\n\n\nopt2_ss = Optim.optimize(ss2,lower2,upper2,initial_x2)\n\n\nopt2_nll = Optim.optimize(nll2,lower2,upper2,initial_x2)\n\n\nfunction loss_function(sol)\n    sol_data = DataFrame(sol(obstimes)')[!,:x4]\n    -sum(logpdf.(Poisson.(sol_data),data))\nend\n\n\nprob_generator = (prob,q) -> remake(prob,\n    u0=[1000-(q[1]*1000),q[1]*1000,0.0,0.0],\n    p=[q[2],10.0,0.25])\n\n\ncost_function = build_loss_objective(prob_ode,\n    Tsit5(),\n    loss_function,\n    prob_generator = prob_generator,\n    maxiters=10000,\n    verbose=false,\n    callback=cb_zero)\n\n\nopt_pe1 = Optim.optimize(cost_function,lower2,upper2,initial_x2)\n\n\nusing NLopt\nopt = Opt(:LD_MMA, 2)\nopt.lower_bounds = lower2\nopt.upper_bounds = upper2\nopt.min_objective = cost_function\n(minf,minx,ret) = NLopt.optimize(opt,initial_x2)\n\n\nusing BlackBoxOptim\nbound1 = Tuple{Float64, Float64}[(0.0,1.0),(0.0, 1.0)]\nresult = bboptimize(cost_function;SearchRange = bound1, MaxSteps = 110e3)\n\n\ninclude(joinpath(@__DIR__,\"tutorials\",\"appendix.jl\"))\nappendix()\n\n", "meta": {"hexsha": "68439c8645fd7b1a0f7c3eae4c6575828b9b2930", "size": 3277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode/ode_inference.jl", "max_stars_repo_name": "FSUcilab/sir-julia", "max_stars_repo_head_hexsha": "e40b5c83b2f6056c85f5bccefa993a0a65a1ee7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/ode/ode_inference.jl", "max_issues_repo_name": "FSUcilab/sir-julia", "max_issues_repo_head_hexsha": "e40b5c83b2f6056c85f5bccefa993a0a65a1ee7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/ode/ode_inference.jl", "max_forks_repo_name": "FSUcilab/sir-julia", "max_forks_repo_head_hexsha": "e40b5c83b2f6056c85f5bccefa993a0a65a1ee7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9421965318, "max_line_length": 73, "alphanum_fraction": 0.6533414709, "num_tokens": 1258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7550227660936448}}
{"text": "\"\"\"\n@article{zitzler2000comparison,\n  title={Comparison of multiobjective evolutionary algorithms: Empirical results},\n  author={Zitzler, Eckart and Deb, Kalyanmoy and Thiele, Lothar},\n  journal={Evolutionary computation},\n  volume={8},\n  number={2},\n  pages={173--195},\n  year={2000},\n  publisher={MIT Press}\n}\n\nZDT 测试函数的特点:\n- 有固定的 2 个目标\n- 有确定的 True Pareto Front\n\"\"\"\n\nabstract type ZDT <: TestProblem end\n\nabstract type ZDT1 <: ZDT end\n\nfunction ZDT1(m = 30, n_solutions = 100)\n    f(x) = begin\n        g = 1.0 + 9.0 * ( sum(x[2:end]) / (length(x)-1) )\n        h = 1 - sqrt(x[1] / g)\n        return [ x[1], g*h ]\n    end\n\n    bounds = Array([zeros(m) ones(m)]')\n\n    x = range(0, 1, length=n_solutions)\n\n    X = [vcat(x[i], zeros(m - 1)) for i in 1:n_solutions]\n    pareto_set = [ Individual(x, f(x)) for x in X ]\n\n    # @infiltrate\n\n    return f, bounds, pareto_set\nend\n\nfunction truepf(x)\n    \"truepf\"\nend\n\nthename(::Type{ZDT1}) = \"ZDT1\"\n\nabstract type ZDT2 <: ZDT end\n\nfunction ZDT2(D = 30, n_solutions = 100)\n    f(x) = begin\n        gx = 1.0 + 9.0 * ( sum(x[2:end]) / (length(x)-1) )\n        return [x[1], gx*(1 - (x[1] / gx)^2) ]\n    end\n    bounds = Array([zeros(D) ones(D)]')\n\n    x = range(0, 1, length=n_solutions)\n\n    x = [vcat(x[i], zeros(D - 1)) for i in 1:n_solutions]\n    pareto_set = [ Individual(xx, f(xx)) for xx in x ]\n\n    return f, bounds, pareto_set\nend\n\nabstract type ZDT3 <: ZDT end\n\nfunction ZDT3(D = 30, n_solutions = 100)\n    f(x) = begin\n        gx = 1.0 + 9.0 * ( sum(x[2:end]) / (length(x)-1) )\n        a = x[1] / gx\n        return [x[1], gx*(1 - sqrt(a) - a*sin(10π*x[1])) ]\n    end\n    bounds = Array([zeros(D) ones(D)]')\n\n    if n_solutions < 6\n        n_solutions = 6\n    end\n\n    regions = [ 0 0.0830015349\n                0.182228780 0.2577623634\n                0.4093136748 0.4538821041\n                0.6183967944 0.6525117038\n                0.8233317983 0.8518328654]\n\n    n = Int(ceil(n_solutions / size(regions, 1)))\n    x = Float64[]\n    for i in 1:size(regions, 1)\n        x = vcat(x, range(regions[i,1], regions[i,2], length=n))\n    end\n\n    x = [vcat(x[i], zeros(D - 1)) for i in 1:n_solutions]\n    pareto_set = [ Individual(xx, f(xx)) for xx in x ]\n\n    return f, bounds, get_non_dominated_solutions(pareto_set)\nend\n\nabstract type ZDT4 <: ZDT end\n\nfunction ZDT4(D = 10, n_solutions = 100)\n    f(x) = begin\n        gx = 1.0 + 10*(length(x)-1) + sum( x[2:end].^2 - 10cos.(4π*x[2:end]))\n        return [x[1], gx*(1 - sqrt(x[1] / gx)) ]\n    end\n    bounds = Array([-5zeros(D) 5ones(D)]')\n    bounds[:,1] = [0, 1.0]\n\n    x = range(0, 1, length=n_solutions)\n\n    x = [vcat(x[i], zeros(D - 1)) for i in 1:n_solutions]\n    pareto_set = [ Individual(xx, f(xx)) for xx in x ]\n\n    return f, bounds, pareto_set\nend\n\nabstract type ZDT6 <: ZDT end\n\nfunction ZDT6(D = 10, n_solutions = 100)\n    f(x) = begin\n        gx = 1.0 + 9.0 * ( sum(x[2:end]) / (length(x)-1.0) )^(0.25)\n        ff1 = 1.0 - exp(-4.0x[1])*sin(6.0π*x[1])^6\n        return [ ff1 , gx*(1.0 - (ff1 / gx)^2) ]\n    end\n\n    bounds = Array([zeros(D) ones(D)]')\n\n    #x = range(0, 1, length=n_solutions)\n\n    #x = [vcat(x[i], zeros(D - 1)) for i in 1:n_solutions]\n    xx = range(0.2807753191, 1, length=100)\n    yy = 1 .- (xx).^2\n    pareto_set = [ Individual(zeros(0), [xx[i], yy[i]]) for i in 1:length(xx) ]\n\n    return f, bounds, pareto_set\nend\n", "meta": {"hexsha": "bad89e3d2dcb1fd7950a1645bc68300468a2af0c", "size": 3348, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/ZDT.jl", "max_stars_repo_name": "xh4/MOEA", "max_stars_repo_head_hexsha": "0953e9b4aa8aa1a0ceabc30b481eb954e1920621", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/ZDT.jl", "max_issues_repo_name": "xh4/MOEA", "max_issues_repo_head_hexsha": "0953e9b4aa8aa1a0ceabc30b481eb954e1920621", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/ZDT.jl", "max_forks_repo_name": "xh4/MOEA", "max_forks_repo_head_hexsha": "0953e9b4aa8aa1a0ceabc30b481eb954e1920621", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9850746269, "max_line_length": 82, "alphanum_fraction": 0.561827957, "num_tokens": 1266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7550227656268389}}
{"text": "# ---\n# title: 858. Mirror Reflection\n# id: problem858\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Medium\n# categories: Math\n# link: <https://leetcode.com/problems/mirror-reflection/description/>\n# hidden: true\n# ---\n# \n# There is a special square room with mirrors on each of the four walls.  Except\n# for the southwest corner, there are receptors on each of the remaining\n# corners, numbered `0`, `1`, and `2`.\n# \n# The square room has walls of length `p`, and a laser ray from the southwest\n# corner first meets the east wall at a distance `q` from the `0`th receptor.\n# \n# Return the number of the receptor that the ray meets first.  (It is guaranteed\n# that the ray will meet a receptor eventually.)\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: p = 2, q = 1\n#     Output: 2\n#     Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.\n#     ![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/18/reflection.png)\n#     \n# \n# **Note:**\n# \n#   1. `1 <= p <= 1000`\n#   2. `0 <= q <= p`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "08016353dc86a32fe3ecc0d78610086eb7f0f96c", "size": 1130, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/858.mirror-reflection.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/unresolved/858.mirror-reflection.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/unresolved/858.mirror-reflection.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 25.1111111111, "max_line_length": 99, "alphanum_fraction": 0.6460176991, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7550227638237313}}
{"text": "using HomotopyContinuation, LinearAlgebra, DynamicPolynomials\n\n# See https://www.juliahomotopycontinuation.org/examples/cyclooctane/\nc² = 2\n@polyvar z[1:3, 1:6]\nz_vec = vec(z)[1:17] # the 17 variables in a vector\nZ = [zeros(3) z[:,1:5] [z[1,6]; z[2,6]; 0] [√c²; 0; 0]] # the eight points in a matrix\n\n# define the functions for cyclooctane:\nF1 = [(Z[:, i] - Z[:, i+1]) ⋅ (Z[:, i] - Z[:, i+1]) - c² for i in 1:7]\nF2 = [(Z[:, i] - Z[:, i+2]) ⋅ (Z[:, i] - Z[:, i+2]) - 8c²/3 for i in 1:6]\nF3 = (Z[:, 7] - Z[:, 1]) ⋅ (Z[:, 7] - Z[:, 1]) - 8c²/3\nF4 = (Z[:, 8] - Z[:, 2]) ⋅ (Z[:, 8] - Z[:, 2]) - 8c²/3\nf = [F1; F2; F3; F4]\n\nn = 2 # dimension of the cyclooctane variety\nN = 17 # ambient dimension\n@polyvar Aᵥ[1:n, 1:N] bᵥ[1:n] # variables for the linear equations\np = [vec(Aᵥ); bᵥ] # parameters\nF = [f; Aᵥ * z_vec - bᵥ] # the polynomial system we have to solve\n\n# now we solve one particular instance for A,b complex. we use this as start system\nA₀ = randn(ComplexF64, n, N)\nb₀ = randn(ComplexF64, n)\np₀ = [vec(A₀); b₀]\n\nF₀ = [subs(Fᵢ, p => [vec(A₀); b₀]) for Fᵢ in F]\ncomplex_result = solve(F₀)\nprintln(\"Degree of the variety: \", nfinite(complex_result)) # should be 1408\n", "meta": {"hexsha": "19ea1eb9a55381a98f8bfd7c0178b16dc6fa0011", "size": 1166, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmarks/cyclooctane.jl", "max_stars_repo_name": "mbauman/HomotopyContinuation.jl", "max_stars_repo_head_hexsha": "3253f86b2752303b0ed8616e07bccf8bfbb7f24d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 129, "max_stars_repo_stars_event_min_datetime": "2017-11-08T17:05:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T13:17:16.000Z", "max_issues_repo_path": "benchmarks/cyclooctane.jl", "max_issues_repo_name": "mbauman/HomotopyContinuation.jl", "max_issues_repo_head_hexsha": "3253f86b2752303b0ed8616e07bccf8bfbb7f24d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 290, "max_issues_repo_issues_event_min_datetime": "2017-09-09T09:09:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T20:11:16.000Z", "max_forks_repo_path": "benchmarks/cyclooctane.jl", "max_forks_repo_name": "mbauman/HomotopyContinuation.jl", "max_forks_repo_head_hexsha": "3253f86b2752303b0ed8616e07bccf8bfbb7f24d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2017-09-09T09:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T10:08:17.000Z", "avg_line_length": 38.8666666667, "max_line_length": 86, "alphanum_fraction": 0.5986277873, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875642, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.7550137169751611}}
{"text": "@inline cst_S(n, i, x) = binomial(n,i)*x^i*(1-x)^(n-i)\n@inline cst_C(n1, n2, x) = x^n1*(1-x)^n2\n@inline function cst_dS(n, i, x)\n    if i == 0 # (1-x)^n\n        -n*(1-x)^(n-1)\n    elseif i == n # x^n\n        n*x^(n-1)\n    else\n        binomial(n, i)*(i*x^(i-1)*(1-x)^(n-i)-(n-i)*x^i*(1-x)^(n-i-1))\n    end\nend\n\n@inline function cst_dC(n1, n2, x) \n    n1*x^(n1-1)*(1-x)^n2 - n2*x^n1*(1-x)^(n2-1)\nend    \nfunction fit_cst(n::Int, dz::T,\n    xu::AbstractVector{T},yu::AbstractVector{T},\n    xl::AbstractVector{T},yl::AbstractVector{T}, \n    opt::OptimizerFactory; \n    c1::T = 0.5,\n    c2::T = 1.0 ) where {T}\n    m = Model(opt)\n    lb = oneunit(T)*-2\n    up = oneunit(T)*2\n    n_up = length(xu)\n    n_lo = length(xl)\n    @variable(m, lb <= A₀ <= up, start = 1.0)\n    @variable(m, lb <= Aᵤ[1:n] <= up, start = 1.0)\n    @variable(m, lb <= Aₗ[1:n] <= up, start = -1.0)\n    @expression(m, yuc[j=1:n_up], cst_C(c1,c2,xu[j])*( A₀*cst_S(n,0,xu[j])+sum(Aᵤ[i]*cst_S(n,i,xu[j]) for i = 1:n))+xu[j]*dz)\n    @expression(m, ylc[j=1:n_lo], cst_C(c1,c2,xl[j])*(-A₀*cst_S(n,0,xl[j])+sum(Aₗ[i]*cst_S(n,i,xl[j]) for i = 1:n))-xl[j]*dz)\n    @expression(m, fup, sum((yuc[j]-yu[j])^2 for j=1:n_up))\n    @expression(m, flo, sum((ylc[j]-yl[j])^2 for j=1:n_lo))\n    @objective(m, Min, fup+flo)\n    optimize!(m)\n    status = termination_status(m)\n    value(A₀), value.(Aᵤ), value.(Aₗ), status\nend\n\n\n", "meta": {"hexsha": "9b1a6cd28a254e83389aeb5f53cd8a18e584e4bb", "size": 1372, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CST/utils.jl", "max_stars_repo_name": "JuliaTagBot/ParametricAirfoils.jl", "max_stars_repo_head_hexsha": "e32baeaacecfd5fef7a359ea44635a8de4b7eabf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CST/utils.jl", "max_issues_repo_name": "JuliaTagBot/ParametricAirfoils.jl", "max_issues_repo_head_hexsha": "e32baeaacecfd5fef7a359ea44635a8de4b7eabf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CST/utils.jl", "max_forks_repo_name": "JuliaTagBot/ParametricAirfoils.jl", "max_forks_repo_head_hexsha": "e32baeaacecfd5fef7a359ea44635a8de4b7eabf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4634146341, "max_line_length": 125, "alphanum_fraction": 0.5320699708, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.755013711227933}}
{"text": "#' ---\r\n#' title: Problem Modification\r\n#' ---\r\n\r\n#' **Originally Contributed by**: Arpit Bhatia\r\n\r\n#' This tutorial deals with how to modify models after they have been created and solved.\r\n#' This functionality can be useful, for example, \r\n#' when we are solving many similar models in succession or generating the model dynamically. \r\n#' Additionally it is sometimes desirable for the solver to re-start from the last solution to \r\n#' reduce running times for successive solves (“hot-start”). \r\n\r\nusing JuMP\r\n\r\n#' ## Modifying Variables\r\n\r\nmodel = Model()\r\n@variable(model, x);\r\n\r\n#' ### Variable Bounds\r\n\r\n#' The `set_lower_bound` and `set_upper_bound` functions can be used to create as well as \r\n#' modify an existing variable bound.\r\n\r\nset_lower_bound(x, 3)\r\nlower_bound(x)\r\n\r\n#+\r\n\r\nset_lower_bound(x, 2)\r\nlower_bound(x)\r\n\r\n#' We can delete variable bounds using the `delete_lower_bound` and `delete_upper_bound` functions.\r\n\r\ndelete_lower_bound(x)\r\nhas_lower_bound(x)\r\n\r\n#' We can assign a fixed value to a variable using `fix`.\r\n\r\nfix(x, 5)\r\nfix_value(x)\r\n\r\n#' However, fixing a variable with existing bounds will throw an error.\r\n\r\n@variable(model, y >= 0);\r\n\r\n#+ tangle =  false\r\n\r\nfix(y, 2)\r\n\r\n#' As we can see in the error message above, \r\n#' we have to specify to JuMP that we wish to forcefuly remove the bound.\r\n\r\nfix(y, 2; force = true)\r\nfix_value(y)\r\n\r\n#' We can also call the `unfix` function to remove the fixed value.\r\n\r\nunfix(x)\r\nis_fixed(x)\r\n\r\n#' ### Deleting Variables\r\n\r\n#' The `all_variables` function returns a list of all variables present in the model.\r\nall_variables(model)\r\n\r\n#' To delete variables from a model, we can use the `delete` function. \r\n\r\ndelete(model, x)\r\nall_variables(model)\r\n\r\n#' We can also check whether a variable is a valid JuMP variable in a model using the `is_valid` function.\r\n\r\nis_valid(model, x)\r\n\r\n\r\n#' ## Modifying Constraints\r\n\r\nmodel = Model()\r\n@variable(model, x);\r\n\r\n#' ### Modifying a Variable Coefficient\r\n#' It is also possible to modify the scalar coefficients \r\n#' (but notably not yet the quadratic coefficients) using the `set_coefficient` function.\r\n\r\n@constraint(model, con, 2x <= 1);\r\n\r\n#+\r\n\r\nset_coefficient(con, x, 3)\r\ncon\r\n\r\n#' ### Deleting a Constraint\r\n#' Just like for deleting variables, we can use the `delete` function for constraints as well.\r\n\r\ndelete(model, con)\r\nis_valid(model, con)\r\n\r\n#' ## Modifying the Objective\r\n\r\nmodel = Model()\r\n@variable(model, x)\r\n@objective(model, Min, 7x + 4);\r\n\r\n#' The function `objective_function` is used to query the objective of a model.\r\n\r\nobjective_function(model)\r\n\r\n#' `objective_sense` is similarily used to query the objective sense of a model.\r\n\r\nobjective_sense(model)\r\n\r\n#' To easiest way to change the objective is to simply call `@objective` again \r\n#' - the previous objective function and sense will be replaced.\r\n\r\n@objective(model, Max, 8x + 3)\r\nobjective_function(model)\r\n\r\n#+\r\n\r\nobjective_sense(model)\r\n\r\n#' Another way is to change the objective is to \r\n#' use the low-level functions `set_objective_function` and `set_objective_sense`.\r\n\r\nset_objective_function(model, 5x + 11)\r\nobjective_function(model)\r\n\r\n#+\r\n\r\nset_objective_sense(model, MOI.MIN_SENSE) \r\nobjective_sense(model)\r\n\r\n#' Note that we can't use the Min and Max shortcuts here as `set_objective_sense` is a low level function.", "meta": {"hexsha": "730664bd03a88ac6f4d8e6511dce3541a3f6e7d6", "size": 3331, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/using_JuMP/problem_modification.jl", "max_stars_repo_name": "carlosal1015/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/using_JuMP/problem_modification.jl", "max_issues_repo_name": "carlosal1015/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/using_JuMP/problem_modification.jl", "max_forks_repo_name": "carlosal1015/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8582089552, "max_line_length": 107, "alphanum_fraction": 0.7078955269, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.9059898222871763, "lm_q1q2_score": 0.7549836020142731}}
{"text": "export edge_connectivity, min_edge_cut\nexport connectivity, min_cut\n\n\n# min_cut(G,s,t) -- min cut separating s and t\n# min_cut(G) -- min cut separating the graph\n# flag == true means we want s/t cut\n\n\"\"\"\n`min_cut(G)` returns a minimum size set of vertices that disconnects `G`.\n\n`min_cut(G,s,t)` returns a minimum size cut that separates `s` and `t`.\n\"\"\"\nfunction min_cut(G::SimpleGraph{T},s::T, t::T,flag::Bool=true)::Set{T} where T\n    n = NV(G)\n    m = NE(G)\n    n*(n-1)!=2m || error(\"Graph must not be complete\")\n\n    if flag\n        has(G,s)    || error(\"$s is not a vertex of this graph\")\n        has(G,t)    || error(\"$t is not a vertex of this graph\")\n        s!=t        || error(\"two vertices must be different\")\n        !has(G,s,t) || error(\"vertices $s and $t cannot be adjacent\")\n    else\n        if cache_check(G,:min_cut)\n            return cache_recall(G,:min_cut)\n        end\n\n        if !is_connected(G)\n            X = Set{T}()\n            cache_save(G,:min_cut,X)\n            return X\n        end\n    end\n\n    VV = vlist(G)\n    EE = elist(G)\n\n    MOD = Model(get_solver())\n    \n    @variable(MOD,a[VV],Bin)  # in part 1\n    @variable(MOD,b[VV],Bin)  # in part 2\n    @variable(MOD,c[VV],Bin)  # in cut set\n\n    for v in VV\n        @constraint(MOD, a[v]+b[v]+c[v]==1)\n    end\n\n    if flag\n        @constraint(MOD,a[s]==1)\n        @constraint(MOD,b[t]==1)\n    end\n\n    @constraint(MOD, sum(a[v] for v in VV)>=1)\n    @constraint(MOD, sum(b[v] for v in VV)>=1)\n\n    for e in EE\n        v,w = e\n        @constraint(MOD,a[v]+b[w]<=1)\n        @constraint(MOD,a[w]+b[v]<=1)\n    end\n\n    @objective(MOD, Min, sum(c[v] for v in VV))\n\n    optimize!(MOD)\n    status = Int(termination_status(MOD))\n\n    C =  value.(c)\n    X = Set(v for v in VV if C[v] > 0.5)\n\n    if !flag\n        cache_save(G,:min_cut,X)\n    end\n    return X\nend\n\nfunction min_cut(G::SimpleGraph)::Set\n    n = NV(G)\n    n>1 || error(\"Graph must have at least two vertices\")\n    s = first(G.V)\n    return min_cut(G,s,s,false)\nend\n\n\"\"\"\n`connectivity(G)` returns the (vertex) connectivity of `G`, i.e.,\nthe minimum size of a vertex cut set. If `G` is a complete graph with\n`n` vertices, the connectivity is `n-1` (or `0` for the empty graph).\n\"\"\"\nfunction connectivity(G::SimpleGraph)::Int\n    n = NV(G)\n    m = NE(G)\n    if n*(n-1) == 2m   # graph is complete\n        return max(n-1,0)  # what is the connectivity of K_0?\n    end\n\n    return length(min_cut(G))\nend\n\n\n# min_edge_cut(G,s,t) -- min edge cut separating s and t\n# min_edge_cut(G) -- min edge cut separating the graph\n# flag == true means we want s/t cut\n\n\"\"\"\n`min_edge_cut(G)` returns a minimum size set of edges whose removal\ndisconnects `G`. The graph must have at least two vertices.\n\n`min_edge_cut(G,s,t)` is a minimum size set of edges whose removal\nseparates vertices `s` and `t`.\n\"\"\"\nfunction min_edge_cut(G::SimpleGraph{T}, s::T, t::T, flag::Bool=true)::Set{Tuple{T,T}} where T\n    n = NV(G)\n    n > 1 || error(\"Graph must have at least two vertices\")\n\n    if flag\n        has(G,s) || error(\"$s is not a vertex of this graph\")\n        has(G,t) || error(\"$t is not a vertex of this graph\")\n        s!=t     || error(\"vertices must not be the same\")\n    else\n        if cache_check(G,:min_edge_cut)\n            return cache_recall(G,:min_edge_cut)\n        end\n\n        if !is_connected(G)\n            X = Set{Tuple{T,T}}()\n            cache_save(G,:min_edge_cut,X)\n            return X\n        end\n    end\n\n    VV = vlist(G)\n    EE = elist(G)\n\n    MOD = Model(get_solver())\n\n    @variable(MOD,a[VV],Bin)  # in part 1\n    @variable(MOD,b[VV],Bin)  # in part 2\n    @variable(MOD,c[EE],Bin)  # span between the parts\n\n    for v in VV\n        @constraint(MOD,a[v]+b[v]==1)\n    end\n\n    @constraint(MOD,sum(a[v] for v in VV) >= 1)\n    @constraint(MOD,sum(b[v] for v in VV) >= 1)\n\n    if flag\n        @constraint(MOD,a[s]==1)\n        @constraint(MOD,b[t]==1)\n    end\n\n\n    for e in EE\n        u,v = e\n        @constraint(MOD,a[u]+b[v]-1 <= c[e])\n        @constraint(MOD,a[v]+b[u]-1 <= c[e])\n    end\n\n    @objective(MOD, Min, sum(c[e] for e in EE))\n\n    optimize!(MOD)\n    status = Int(termination_status(MOD))\n\n    C =  value.(c)\n\n    X = Set(e for e in EE if C[e] > 0.5)\n\n    if !flag\n        cache_save(G,:min_edge_cut,X)\n    end\n    return X\nend\n\nfunction min_edge_cut(G::SimpleGraph)::Set\n    n = NV(G)\n    n>1 || error(\"Graph must have at least two vertices\")\n    s = first(G.V)\n    return min_edge_cut(G,s,s,false)\nend\n\n\"\"\"\n`edge_connectivity(G)` returns the size of a minimum edge cut of `G`.\n\n`edge_connectivity(G,s,t)` determines the minimum size of an edge cut\nseparating `s` and `t`.\n\"\"\"\nedge_connectivity(G::SimpleGraph)::Int = length(min_edge_cut(G))\nedge_connectivity(G::SimpleGraph,s,v) = length(min_edge_cut(G,s,t))\n", "meta": {"hexsha": "f4c621bf20ac668827c5e31e02b2102d53fddd7a", "size": 4766, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/connectivity.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SimpleGraphAlgorithms.jl-41400c72-0c58-5c16-8579-4ecbce768449", "max_stars_repo_head_hexsha": "e310e66612bd9c7def9b167ac424da03b8b3b224", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/connectivity.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SimpleGraphAlgorithms.jl-41400c72-0c58-5c16-8579-4ecbce768449", "max_issues_repo_head_hexsha": "e310e66612bd9c7def9b167ac424da03b8b3b224", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/connectivity.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SimpleGraphAlgorithms.jl-41400c72-0c58-5c16-8579-4ecbce768449", "max_forks_repo_head_hexsha": "e310e66612bd9c7def9b167ac424da03b8b3b224", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2169312169, "max_line_length": 94, "alphanum_fraction": 0.5841376416, "num_tokens": 1455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7549835969177253}}
{"text": "export findM\n\"\"\"\nfunction findM(param,w;nsol,pwr)\n\nFind a binary matrix M in Omega_M that solves\n\nmin_M  \\| M*w - d \\|\\_{Gamma,pwr} + lambda \\| M \\|\\_0,\n\nInput:\n\n\t1. param - StrainReconParam\n\t2. w     - vector of weights\n\nKeyword arguments:\n\n\t3. nsol  - returns nsol matrices (default = 1); if nsol = 2, first matrix has rows with lowest difference |M(i)*w-d(i)| by each row i and is the MAP estimator, second matrix has rows with second lowest difference |M(i)*w-d(i)| by each row i but is NOT the second \"best\" or most likely matrix\n\t4. pwr   - exponent in the likelihood function (default = param.pwr)\n    5. probM - returns p(M) for nsol matrices corresponding to \"confidence\"/probability for each row of M, size(m,nsol), (default = false); p(M(i)) = C* exp(-(1/pwr) * (|M(i)*w - d(i)|_R)^pwr) where R is the diagonal of the inverse square of the noise covariance matrix and C is the normalization constant 1/(sum_{m}{j}(sum_{2^n}{i} exp(-(1/pwr) * (|B(i)*w - d(j)|_R)^pwr))), where B is a binary matrix with all possible permutation of binary entries and has size(2^n,n)\n\nOutput:\n\n\t1. M  - binary matrix of size (q,n) or an array of size (q,n,nsol)\n    2. pM - matrix of p(M) of size (m,nsol), entries in each column \\in [0,1] represent \"confidence\" or probability for the rows of M\n\"\"\"\nfunction findM(param::StrainReconParam,w::Vector;nsol::Int64=1,pwr::Float64=param.pwr,probM=false)\n    Rp = diag(param.R.^pwr)\n    d  = param.d\n    n  = param.n\n    p  = param.p\n    m  = param.m\n\n    B  = getB(param)\n    Ba = reshape(B*w,p-1,:)'\n    Bs = reshape(param.lambda * vec(sum(B,2)), p-1,:)'\n        \n    if nsol > 2^n\n        println(\"nsol can only be <= 2^n = $(2^n), only the MAP estimator will be returned\")\n        nsol = 1\n    end\n    \n    pM = zeros(m,nsol) # array to store p(M) for each M\n\n    if nsol == 1\n        M  = falses(length(d),n)\n        for k=1:m\n            blockidx = (k-1)*(p-1)+1 : k*(p-1)\n            Bdiff = sum(Rp[blockidx]'.*abs.(Ba.-d[blockidx]').^pwr,2) + sum(Bs,2) # |B(ik)*w - d(k)|_R^pwr, size(2^n,1)\n            ik = indmin(Bdiff) # index ik in 1:2^n\n            mi = B[(ik-1)*(p-1)+1 : ik*(p-1),:] # row(s) of B with lowest difference B[ik]*w - d[k]\n            M[blockidx,:] = mi \n            \n            # compute p(M_i)\n            \n            # println(\"ik $ik mi $mi Bdiff $Bdiff)\")\n            # avoid underflow by finding min(Bdiff) and subtracting that from all numbers before taking exp\n            minbdiff = minimum(Bdiff)\n            pmi = exp.(-(1/pwr)*((Rp[blockidx]'.*abs.(mi*w.-d[blockidx]').^pwr + Bs[ik]) .- minbdiff)) # pmi should always = 1\n            #opmi = (Rp[blockidx]'.*abs.(mi*w.-d[blockidx]').^pwr + Bs[ik])\n            #println(\"pmi $pmi \\n opmi $opmi minbdiff $minbdiff\")\n            normconst = sum(exp.(-(1/pwr)*(Bdiff .- minbdiff))) # normalization constant\n            #println(\"normconst $normconst\")\n            pM[k,nsol] = pmi[1]/normconst\n        end\n    else\n        M  = falses(length(d),n,nsol)\n        for k=1:m\n            blockidx = (k-1)*(p-1)+1 : k*(p-1)\n            Bdiff = vec(sum(Rp[blockidx]'.*abs.(Ba.-d[blockidx]').^pwr,2) + sum(Bs,2))\n            ik = sortperm(Bdiff)     \n            minbdiff = minimum(Bdiff)\n            normconst = sum(exp.(-(1/pwr)*(Bdiff .- minbdiff))) # normalization constant for each row\n            for j=1:nsol\n                # nth best row\n                mj = B[(ik[j]-1)*(p-1)+1 : ik[j]*(p-1),:]\n                M[blockidx,:,j] = mj\n\n                # compute p(M_i) for each matrix\n                ij = ik[j] \n                # println(\"ij $ij mj $mj Bdiff $Bdiff)\")\n                pmj = exp.(-(1/pwr)*((Rp[blockidx]'.*abs.(mj*w.-d[blockidx]').^pwr + Bs[ij]) .- minbdiff))\n                # println(\"j $j pmj $pmj\")\n                # println(\"normconst $normconst\")\n                pM[k,j] = pmj[1]/normconst\n            end\n        end\n    end\n\n    if probM\n        return M, pM\n    else\n        return M\n    end\nend", "meta": {"hexsha": "333ac3a02cc8afc6eea54c66bd445fd074854de8", "size": 3943, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/findM.jl", "max_stars_repo_name": "lruthotto/StrainRecon.jl", "max_stars_repo_head_hexsha": "ba1c5392994e80bb0f7e6b94f90b404f25c40958", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-05-01T00:47:02.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-01T00:47:02.000Z", "max_issues_repo_path": "src/findM.jl", "max_issues_repo_name": "lruthotto/StrainRecon.jl", "max_issues_repo_head_hexsha": "ba1c5392994e80bb0f7e6b94f90b404f25c40958", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/findM.jl", "max_forks_repo_name": "lruthotto/StrainRecon.jl", "max_forks_repo_head_hexsha": "ba1c5392994e80bb0f7e6b94f90b404f25c40958", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3978494624, "max_line_length": 470, "alphanum_fraction": 0.5483134669, "num_tokens": 1274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7549307277267144}}
{"text": "function adaptivesimpsons_inner(\n    f::Function,\n    a::Real,\n    b::Real,\n    ε::Real,\n    S::Real,\n    fa::Real,\n    fb::Real,\n    fc::Real,\n    bottom::Integer,\n)\n    c = (a + b) / 2\n    h = b - a\n    d = (a + c) / 2\n    g = (c + b) / 2\n    fd = f(d)\n    fe = f(g)\n    Sleft = (h / 12) * (fa + 4 * fd + fc)\n    Sright = (h / 12) * (fc + 4 * fe + fb)\n    S2 = Sleft + Sright\n    if bottom <= 0 || abs(S2 - S) <= 15 * ε\n        return S2 + (S2 - S) / 15\n    end\n    res1 = adaptivesimpsons_inner(\n        f,\n        a,\n        c,\n        ε / 2,\n        Sleft,\n        fa,\n        fc,\n        fd,\n        bottom - 1\n    )\n    res2 = adaptivesimpsons_inner(\n        f,\n        c,\n        b,\n        ε / 2,\n        Sright,\n        fc,\n        fb,\n        fe,\n        bottom - 1\n    )\n    return res1 + res2\nend\n\nfunction adaptivesimpsons(\n    f::Function,\n    a::Real,\n    b::Real,\n    accuracy::Real = 10e-10,\n    max_iterations::Integer = 50,\n)\n    c = (a + b) / 2\n    h = b - a\n    fa = f(a)\n    fb = f(b)\n    fc = f(c)\n    S = (h / 6) * (fa + 4 * fc + fb)\n    return adaptivesimpsons_inner(\n        f,\n        a,\n        b,\n        accuracy,\n        S,\n        fa,\n        fb,\n        fc,\n        max_iterations\n    )\nend\n", "meta": {"hexsha": "ee63c2075736623fd05374d6e7b4be47e8e98376", "size": 1225, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/integrate/simpsons.jl", "max_stars_repo_name": "johnmyleswhite/Calculus2.jl", "max_stars_repo_head_hexsha": "57f56fed859ceb6c87455249f22a0a2eb85029a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-08-25T19:12:38.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-25T19:12:38.000Z", "max_issues_repo_path": "src/integrate/simpsons.jl", "max_issues_repo_name": "johnmyleswhite/Calculus2.jl", "max_issues_repo_head_hexsha": "57f56fed859ceb6c87455249f22a0a2eb85029a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/integrate/simpsons.jl", "max_forks_repo_name": "johnmyleswhite/Calculus2.jl", "max_forks_repo_head_hexsha": "57f56fed859ceb6c87455249f22a0a2eb85029a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-01T12:21:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:21:27.000Z", "avg_line_length": 16.5540540541, "max_line_length": 43, "alphanum_fraction": 0.3934693878, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7549307182467432}}
{"text": "geometric_mean(a::Number, b::Number) = √(a*b)\r\n\r\nfunction find_under_and_over(a::Number, possible_values::Array)\r\n    possible_series_sorted = sort(possible_values)\r\n    i, j = 1, 2\r\n        while !(possible_series_sorted[i] ≤ a ≤ possible_series_sorted[j])\r\n            i+=1; j+=1\r\n        end\r\n    return possible_series_sorted[i], possible_series_sorted[j]\r\nend\r\n\r\nfunction norm_to_between_100_and_1000(val::Number; return_OOM=true)\r\n    power_of_10 = 0.0\r\n    while val > 1000\r\n        val/=10; power_of_10 += 1\r\n    end\r\n    while val < 100\r\n        val*=10; power_of_10 += -1\r\n    end\r\n    if return_OOM\r\n        return val, power_of_10\r\n    else\r\n        return val\r\n    end\r\nend\r\n", "meta": {"hexsha": "0ce718f51a128d69d786df910d9bef266ccb2602", "size": 688, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/UtilityFunctions.jl", "max_stars_repo_name": "KronosTheLate/ESeriesRounding.jl", "max_stars_repo_head_hexsha": "681f3152c4e6525ec6cdf36461a5930ed5b32b5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-11T13:09:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T13:35:42.000Z", "max_issues_repo_path": "src/UtilityFunctions.jl", "max_issues_repo_name": "KronosTheLate/ESeriesRounding.jl", "max_issues_repo_head_hexsha": "681f3152c4e6525ec6cdf36461a5930ed5b32b5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-13T18:06:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T19:03:15.000Z", "max_forks_repo_path": "src/UtilityFunctions.jl", "max_forks_repo_name": "KronosTheLate/ESeriesRounding.jl", "max_forks_repo_head_hexsha": "681f3152c4e6525ec6cdf36461a5930ed5b32b5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4615384615, "max_line_length": 75, "alphanum_fraction": 0.6235465116, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731765, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7549307170667746}}
{"text": "\"\"\"\n    StuTLik <: Likelihood\n\nStudent-t likelihood (a.k.a. non-standardized [Student's\nt-distribution](https://en.wikipedia.org/wiki/Student's_t-distribution))\n```math\np(y | f, σ) = Γ((ν + 1)/2)/[Γ(ν/2)√(πν)σ](1 + 1/ν((y - f)/σ)²)^{-(ν + 1)/2}\n```\nwith degrees of freedom ``ν ∈ N₀``, where scale ``σ`` is a non-fixed hyperparameter and\n``f`` is the latent Gaussian process.\n\"\"\"\nmutable struct StuTLik <: Likelihood\n    \"Degrees of freedom\"\n    ν::Int\n    \"Scale\"\n    σ::Float64\n    \"Priors for likelihood parameters\"\n    priors::Array\n\n    \"\"\"\n        StuTLik(ν::Int, lσ::Float64)\n\n    Create a `StuTLik` with degrees of freedom `ν` and scale `exp(lσ)`.\n    \"\"\"\n    StuTLik(ν::Int, lσ::Float64) = new(ν, exp(lσ), [])\nend\n\n#log of probability density\nfunction log_dens(studentT::StuTLik, f::VecF64, y::VecF64)\n    ν = studentT.ν\n    σ = studentT.σ\n    c = lgamma(0.5*(ν+1)) - lgamma(0.5*ν) - 0.5*log(pi*ν) - log(σ)\n    return [c - (0.5*(ν+1))*log(1+(1/ν)*((yi-fi)/σ)^2) for (fi,yi) in zip(f,y)]\nend\n\n#derivative of log pdf wrt latent function\nfunction dlog_dens_df(studentT::StuTLik, f::VecF64, y::VecF64)\n    ν = studentT.ν\n    σ = studentT.σ\n    return [(ν+1)*(yi-fi)/(ν*σ^2 + (yi-fi)^2) for (fi,yi) in zip(f,y)]\nend\n\n#derivative of log pdf wrt to parameters\nfunction dlog_dens_dθ(studentT::StuTLik, f::VecF64, y::VecF64)\n    ν = studentT.ν\n    σ = studentT.σ\n    return σ*[-1/σ+(ν+1)*(yi-fi)^2/(ν*σ^3 + σ*(yi-fi)^2) for (fi,yi) in zip(f,y)]\nend\n\n#mean and variance under likelihood\nmean_lik(studentT::StuTLik, f::VecF64) = f\nvar_lik(studentT::StuTLik, f::VecF64) = studentT.σ^2*(studentT.ν/(studentT.ν-2.0))*ones(length(f))\n\nfunction set_params!(studentT::StuTLik, hyp::VecF64)\n    length(hyp) == 1 || throw(ArgumentError(\"Student-t likelihood has only one free parameter\"))\n    studentT.σ = exp(hyp[])\nend\n\nget_params(studentT::StuTLik) = Float64[log(studentT.σ)]\nnum_params(studentT::StuTLik) = 1\n\n\n\n\n", "meta": {"hexsha": "699e57392f6fa80f49ac350f49a683f8778c774f", "size": 1906, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/likelihoods/studentT.jl", "max_stars_repo_name": "jbrea/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/likelihoods/studentT.jl", "max_issues_repo_name": "jbrea/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/likelihoods/studentT.jl", "max_forks_repo_name": "jbrea/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "732063745067a803429415100f2b08bb396a1df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3230769231, "max_line_length": 98, "alphanum_fraction": 0.6369359916, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7549307145727515}}
{"text": "immutable TDist <: ContinuousUnivariateDistribution\n    df::Float64 # non-integer degrees of freedom allowed\n    function TDist(d::Real)\n    \td > zero(d) || error(\"df must be positive\")\n        new(float64(d))\n    end\nend\n\n@_jl_dist_1p TDist t\n\nfunction entropy(d::TDist)\n    ((d.df + 1.0) / 2.0) *\n        (digamma((d.df + 1.0) / 2.0) - digamma((d.df) / 2.0)) +\n        (1.0 / 2.0) * log(d.df) + lbeta(d.df + 1.0, 1.0 / 2.0)\nend\n\ninsupport(::TDist, x::Real) = isfinite(x)\ninsupport(::Type{TDist}, x::Real) = isfinite(x)\n\nmean(d::TDist) = d.df > 1.0 ? 0.0 : NaN\n\nmedian(d::TDist) = 0.0\n\nmode(d::TDist) = 0.0\nmodes(d::TDist) = [0.0]\n\nfunction pdf(d::TDist, x::Real)\n    1.0 / (sqrt(d.df) * beta(0.5, 0.5 * d.df)) *\n        (1.0 + x^2 / d.df)^(-0.5 * (d.df + 1.0))\nend\n\nfunction var(d::TDist)\n    d.df > 2.0 && return d.df / (d.df - 2.0)\n    d.df > 1.0 && return Inf\n    NaN\nend\n", "meta": {"hexsha": "f7b9b78d0161da0fcfe3184c63a431ea758f9d86", "size": 877, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/tdist.jl", "max_stars_repo_name": "simonbyrne/Distributions.jl", "max_stars_repo_head_hexsha": "a9bd0e62002a94007ecd590e51cb27af9a346544", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/tdist.jl", "max_issues_repo_name": "simonbyrne/Distributions.jl", "max_issues_repo_head_hexsha": "a9bd0e62002a94007ecd590e51cb27af9a346544", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/tdist.jl", "max_forks_repo_name": "simonbyrne/Distributions.jl", "max_forks_repo_head_hexsha": "a9bd0e62002a94007ecd590e51cb27af9a346544", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7027027027, "max_line_length": 63, "alphanum_fraction": 0.5496009122, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7549307093567558}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots\n\tusing StatsBase, LaTeXStrings\n\tRandom.seed!(0)\nend\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.15\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tmu0, mu1, sd, tau  = 15, 18, 2, 17.5\n\tdist0, dist1 = Normal(mu0,sd), Normal(mu1,sd)\n\tgrid = 5:0.1:25\n\th0grid, h1grid = tau:0.1:25, 5:0.1:tau\nend\n\n# ╔═╡ 57e2a694-3af9-11eb-0f9e-7d8df75869e6\nText(\"Probability of Type I error: $(ccdf(dist0,tau))\")\n\n# ╔═╡ 57e2e668-3af9-11eb-0e7c-033e27bf1e92\nText(\"Probability of Type II error: $(cdf(dist1,tau))\")\n\n# ╔═╡ 57e37538-3af9-11eb-1477-b9387969d828\nbegin\n\tplot(grid, pdf.(dist0,grid),\n\t\tc=:blue, label=\"Bolt type 15g\")\n\tplot!(h0grid, pdf.(dist0, h0grid), \n\t\tc=:blue, fa=0.2, fillrange=[0 1], label=\"\")\n\tplot!(grid, pdf.(dist1,grid), \n\t\tc=:green, label=\"Bolt type 18g\")\n\tplot!(h1grid, pdf.(dist1, h1grid), \n\t\tc=:green, fa=0.2, fillrange=[0 1], label=\"\")\n\tplot!([tau, 25],[0,0],\n\t\tc=:red, lw=3, label=\"Rejection region\", \n\t\txlims=(5, 25), ylims=(0,0.25) , legend=:topleft,\n\t\txlabel=\"x\", ylabel=\"Density\")\n\tannotate!([(16, 0.02, text(L\"\\beta\")),(18.5, 0.02, text(L\"\\alpha\")),\n\t\t\t\t(15, 0.21, text(L\"H_0\")),(18, 0.21, text(L\"H_1\"))])\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.15\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═57e2a694-3af9-11eb-0f9e-7d8df75869e6\n# ╠═57e2e668-3af9-11eb-0e7c-033e27bf1e92\n# ╠═57e37538-3af9-11eb-1477-b9387969d828\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "ac7a40965d55a381c3639ca6fefb580edc571bd5", "size": 1836, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/listing5.15.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/05/listing5.15.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/05/listing5.15.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 28.2461538462, "max_line_length": 69, "alphanum_fraction": 0.6835511983, "num_tokens": 949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7549307087667717}}
{"text": "# Julia translation of http://nbviewer.jupyter.org/github/barbagroup/AeroPython/blob/master/lessons/03_Lesson03_doublet.ipynb\n# Lesson 3 doublet\n\nusing PyPlot\nusing Distributions\n\nclose(\"all\")\nmeshgrid(x,y) = (repmat(x',length(y),1),repmat(y,1,length(x)))\n\nN = 50                                # number of points in each direction\nx_start, x_end = -2.0, 2.0            # boundaries in the x-direction\ny_start, y_end = -1.0, 1.0            # boundaries in the y-direction\nx = linspace(x_start, x_end, N)    # creates a 1D-array with the x-coordinates\ny = linspace(y_start, y_end, N)    # creates a 1D-array with the y-coordinates\n\nX,Y=meshgrid(x,y)\n\nkappa = 1.0\n\nx_doublet, y_doublet = 0.0, 0.0   # location of the source\n\nfunction get_velocity_doublet(strength, xd, yd, X, Y):\n    \"\"\"Returns the velocity field generated by a doublet.\n\n    Arguments\n    ---------\n    strength -- strength of the doublet.\n    xd, yd -- coordinates of the doublet.\n    X, Y -- mesh grid.\n    \"\"\"\n    u = - strength/(2*pi).*((X-xd).^2-(Y-yd).^2)./((X-xd).^2+(Y-yd).^2).^2\n    v = - strength/(2*pi)*2.0.*(X-xd).*(Y-yd)./((X-xd).^2+(Y-yd).^2).^2\n\n    return u, v\n  end\n\nfunction get_stream_function_doublet(strength, xd, yd, X, Y):\n    \"\"\"Returns the stream-function generated by a doublet.\n\n    Arguments\n    ---------\n    strength -- strength of the doublet.\n    xd, yd -- coordinates of the doublet.\n    X, Y -- mesh grid.\n    \"\"\"\n    psi = - strength/(2*pi).*(Y-yd)./((X-xd).^2+(Y-yd).^2)\n\n    return psi\n  end\n\n  # computes the velocity field on the mesh grid\nu_doublet, v_doublet = get_velocity_doublet(kappa, x_doublet, y_doublet, X, Y)\n\n# computes the stream-function on the mesh grid\npsi_doublet = get_stream_function_doublet(kappa, x_doublet, y_doublet, X, Y)\n\n\n  # plots the streamlines\n  size = 10\n  PyPlot.figure(figsize=(size, (y_end-y_start)/(x_end-x_start)*size))\n  PyPlot.grid(true)\n  PyPlot.xlabel(\"x\", fontsize=16)\n  PyPlot.ylabel(\"y\", fontsize=16)\n  PyPlot.xlim(x_start, x_end)\n  PyPlot.ylim(y_start, y_end)\n  PyPlot.streamplot(X, Y, u_doublet, v_doublet, density=2, linewidth=1, arrowsize=1, arrowstyle=\"->\")\n  PyPlot.scatter(x_doublet, y_doublet, color=\"#CD2305\", s=80, marker=\"o\")\n\n# Freestream and Doublet\n\n  u_inf = 1.0\n\n  # computes the freestream velocity field\n  u_freestream = u_inf * ones((N, N))\n  v_freestream = zeros((N, N))\n\n  # computes the stream-function\n  psi_freestream = u_inf * Y\n\n  u = u_freestream + u_doublet\n  v = v_freestream + v_doublet\n  psi = psi_freestream + psi_doublet\n\n\n  # plots the streamlines\n  size = 10\n  PyPlot.figure(figsize=(size, (y_end-y_start)/(x_end-x_start)*size))\n  PyPlot.grid(true)\n  PyPlot.xlabel(\"x\", fontsize=16)\n  PyPlot.ylabel(\"y\", fontsize=16)\n  PyPlot.xlim(x_start, x_end)\n  PyPlot.ylim(y_start, y_end)\n  PyPlot.streamplot(X, Y, u, v, density=2, linewidth=1, arrowsize=1, arrowstyle=\"->\")\n  PyPlot.contour(X, Y, psi, levels=[0.], colors=\"#CD2305\", linewidths=2, linestyles=\"solid\");\n  PyPlot.scatter(x_doublet, y_doublet, color=\"#CD2305\", s=80, marker=\"o\")\n\n  # calculates the stagnation points\nx_stagn1, y_stagn1 = +sqrt(kappa/(2*pi*u_inf)), 0\nx_stagn2, y_stagn2 = -sqrt(kappa/(2*pi*u_inf)), 0\n\n# adds the stagnation points to the figure\nPyPlot.scatter([x_stagn1, x_stagn2], [y_stagn1, y_stagn2], color=\"g\", s=80, marker=\"o\");\n\n\n# computes the pressure coefficient field\ncp = 1.0 - (u.^2+v.^2)./u_inf^2\n\n# plots the pressure coefficient field\nsize = 10\nPyPlot.figure(figsize=(1.1*size, (y_end-y_start)/(x_end-x_start)*size))\nPyPlot.xlabel(\"x\", fontsize=16)\nPyPlot.ylabel(\"y\", fontsize=16)\nPyPlot.xlim(x_start, x_end)\nPyPlot.ylim(y_start, y_end)\ncontf = PyPlot.contourf(X, Y, cp, levels=linspace(-2.0, 1.0, 100), extend=\"both\")\ncbar = PyPlot.colorbar(contf)\ncbar[:set_label](L\"$C_p$\", fontsize=16)\ncbar[:set_ticks]([-2.0, -1.0, 0.0, 1.0])\nPyPlot.scatter(x_doublet, y_doublet, color=\"#CD2305\", s=80, marker=\"o\")\nPyPlot.contour(X, Y, psi, levels=[0.], colors=\"#CD2305\", linewidths=2, linestyles=\"solid\");\nPyPlot.scatter([x_stagn1, x_stagn2], [y_stagn1, y_stagn2], color=\"g\", s=80, marker=\"o\");\n", "meta": {"hexsha": "5ad36b03b0c9f7898f205f27ee81c850af8cf8c0", "size": 4048, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Lesson3_Doublet.jl", "max_stars_repo_name": "moore54/JuliaPotentialFlowTranslations", "max_stars_repo_head_hexsha": "2aad7750c23057518ca988ba4a02a4c99f4fde5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lesson3_Doublet.jl", "max_issues_repo_name": "moore54/JuliaPotentialFlowTranslations", "max_issues_repo_head_hexsha": "2aad7750c23057518ca988ba4a02a4c99f4fde5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lesson3_Doublet.jl", "max_forks_repo_name": "moore54/JuliaPotentialFlowTranslations", "max_forks_repo_head_hexsha": "2aad7750c23057518ca988ba4a02a4c99f4fde5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1803278689, "max_line_length": 125, "alphanum_fraction": 0.6711956522, "num_tokens": 1349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7549307050927798}}
{"text": "using Revise\nusing AdFem\nusing PyPlot\n\nm = 30\nn = 30\nh = 1/n \n\nxy = fem_nodes(m, n, h) \nx, y = xy[:,1], xy[:,2]\nu0 = [@. (2(x^3/3-x^2/2)); @. (2(y^3/3 - y^2/2))]\n\nxy = fvm_nodes(m, n, h)\nx, y = xy[:,1], xy[:,2]\np0 = @. x*(1-x)*y*(1-y)\n\nρ = dt = 1\nfunction step2(u0)\n    B = compute_interaction_matrix(m, n, h)\n    bc = bcedge(\"all\", m, n, h)\n    A, _ = compute_fvm_tpfa_matrix(ones(m*n), bc, zeros(size(bc,1)), m, n, h)\n    rhs = ρ / dt * B * u0\n    sol = A\\rhs\n    return sol\nend\nbc = bcedge(\"all\", m, n, h)\n\n# There are three ways to compute \n# int div u dx\n# on each element\n\n# rhs = compute_fvm_mechanics_term(u0, m, n, h)\nB = compute_interaction_matrix(m, n, h)\nrhs = B * u0\n# rhs = h^2 * @. -2x*(1-x)-2y*(1-y)\n\nA, _ = compute_fvm_tpfa_matrix(ones(m*n), bc, zeros(size(bc,1)), m, n, h)\nsol = A\\rhs\n\nsol = step2(u0)\n\nfigure(figsize=(10,4))\nsubplot(121)\nvisualize_scalar_on_fvm_points(sol, m, n, h)\nsubplot(122)\nvisualize_scalar_on_fvm_points(p0, m, n, h)\n", "meta": {"hexsha": "ca1e3e0a8bb38b398c8a432d342a1248fe9f7516", "size": 959, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/codes/tpfa.jl", "max_stars_repo_name": "kailaix/AdFem.jl", "max_stars_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2020-10-18T01:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:13:24.000Z", "max_issues_repo_path": "docs/src/codes/tpfa.jl", "max_issues_repo_name": "kailaix/AdFem.jl", "max_issues_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-10-19T03:51:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:38:46.000Z", "max_forks_repo_path": "docs/src/codes/tpfa.jl", "max_forks_repo_name": "kailaix/AdFem.jl", "max_forks_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-11-05T11:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T19:30:09.000Z", "avg_line_length": 20.4042553191, "max_line_length": 77, "alphanum_fraction": 0.5891553702, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632343454896, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7549284005275951}}
{"text": "using JuMP\nusing Clp\n\nLARGE_VALUE = 100000\nDEMANDS = [400 300 420 380]\nSUPPLY = [500, 600, 200, 300]\nCOSTS = [100 103 106 109; \n        LARGE_VALUE 140 143 146; \n        LARGE_VALUE LARGE_VALUE 120 123; \n        LARGE_VALUE LARGE_VALUE LARGE_VALUE 150]\n\nm = Model(Clp.Optimizer)\n@variable(m, x[1:4, 1:4] ≥ 0)\n@objective(m, Min, sum(COSTS .* x))\n@constraint(m, sum(x, dims=2) .≤ SUPPLY)\n@constraint(m, sum(x, dims=1) .== DEMANDS)\nprint(m)\noptimize!(m)\nstatus = termination_status(m)\nprintln(\"Solution status: \", status)\nprintln(\"Objective value: \", objective_value(m))\nprintln(\"Values: \", value.(x))", "meta": {"hexsha": "96c5f6f4a2308615498a32d8fa892f02ed49c6ba", "size": 598, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week3/example_2.jl", "max_stars_repo_name": "InzamamRahaman/COMP6925-2021", "max_stars_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-23T23:33:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T01:47:28.000Z", "max_issues_repo_path": "week3/example_2.jl", "max_issues_repo_name": "InzamamRahaman/COMP6925-2021", "max_issues_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week3/example_2.jl", "max_forks_repo_name": "InzamamRahaman/COMP6925-2021", "max_forks_repo_head_hexsha": "3bd45036e1818fc3ee428a2a33ed1829b13230bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1818181818, "max_line_length": 48, "alphanum_fraction": 0.6739130435, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7549283985229669}}
{"text": "# This file contains essentials functions to define\n# tables to geometric, inner and outer products.\n\n\"\"\"\n```\nbbgeometric(a::BasisBlade, b::BasisBlade) (Liga function)\n```\nThis function is used to determine the geometric product\nof basis blade. Essentially, this function is used when layout\nfunction is trigged, but it can be used separated too.\n## Example\n```julia-repl\njulia> bbgeometric(e1,e12)\n```\nreturns e2.\n\"\"\"\nfunction bbgeometric(a::BasisBlade, b::BasisBlade)\n\t\tlen = GIdLayout[1]+GIdLayout[2] #p+q\n\t\tEa = copy(LogicalBasisBlade[a.index])\n\t\tEb = copy(LogicalBasisBlade[b.index])\n\t\tabscalar = 1\n\t\tabindex = 1\n\t\tablogical = Vector{Bool}(undef,len)\n\t\tcont = 0\n\t\tfor i=1:len-1\n\t\t\tif Eb[i] == true\n\t\t\t\tfor j=i+1:len\n\t\t\t\t\tif Ea[j] == true\n\t\t\t\t\t\tcont = cont + 1\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\tfor i=1:len\n\t\t\tif Ea[i] != Eb[i]\n\t\t\t\tablogical[i] = true\n\t\t\telse\n\t\t\t\t\tablogical[i] = false\n\t\t\t\t\tif Ea[i] == true && i>GIdLayout[1]\n\t\t\t\t\t\tcont =cont +1\n\t\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\tabscalar = ((-1)^cont)\n\t\tind=1\n\t\twhile ablogical != LogicalBasisBlade[ind]\n\t\t\tind = ind+1\n\t\tend\n\t\tabindex = ind\n\t\tab=BasisBlade(abscalar*abindex)\n\t\treturn ab\nend\n\n\n\"\"\"\n```\nbbinner(a::BasisBlade,b::BasisBlade) (Liga function)\n```\nThis function is used to determine the inner product\nof basis blades. Essentially, this function is used when layout\nfunction is trigged, but it can be used separated too.\n## Example\n```julia-repl\njulia> bbinner(e12,e2)\n```\nreturns the Basis Blade e1.\n\"\"\"\nfunction bbinner(a::BasisBlade,b::BasisBlade)\n\t\tk=grade(a)\n\t\tl=grade(b)\n\t\tif k != 0 && l !=0\n\t\t\treturn gradeprojection(bbgeometric(a,b),abs(k-l))\n\t\telse\n\t\t\treturn BasisBlade(0)\n\t\tend\nend\n\n\"\"\"\n```\nbbouter(a::BasisBlade,b::BasisBlade) (Liga function)\n```\nThis function is used to determine the outer product\nof basis blades. Essentially, this function is used when layout\nfunction is trigged, but it can be used separated too.\n## Example\n```julia-repl\njulia> bbouter(e12,e3)\n```\nreturns the Basis Blade e123.\n\"\"\"\nfunction bbouter(a::BasisBlade,b::BasisBlade)\n\tk=grade(a)\n\tl=grade(b)\n\treturn gradeprojection(bbgeometric(a,b),k+l)\nend\n\n\"\"\"\n```\nOperationTable() (Liga function)\n```\nOperationTable is function trigged by layout function and\nit is used to define the operational table related to geometric,\ninner and outer product. As result, constants array are created\nto optimize these products to multivectors.\n## Example\n```julia-repl\njulia> A,B,C,D=OperationTable()\n```\nreturns A a table for geometric product, B a table for inner product,\nC a table for outer product and D a tensor.\n\"\"\"\nfunction OperationTable()\n\tlen=2^(GIdLayout[1]+GIdLayout[2])\n\tOT=Array{Any,2}(undef,len,len)\n\tIOT=Array{Any,2}(undef,len,len)\n\tOOT=Array{Any,2}(undef,len,len)\n\tTensor=Vector{SparseMatrixCSC}(undef,len)\n\tfor i=1:len\n        for j=1:len\n\t\t\tOT[i,j]=bbgeometric(BasisBlade(i),BasisBlade(j))\n\t\t\tIOT[i,j]=bbinner(BasisBlade(i),BasisBlade(j))\n\t\t\tOOT[i,j]=bbouter(BasisBlade(i),BasisBlade(j))\n\t\tend\n\tend\n\tfor k=1:len\n\t\tTensor[k]=spzeros(len,len)\n\t\tfor i=1:len\n\t\t\tfor j=1:len\n\t\t\t\tif OT[i,j]==BasisBlade(k)\n\t\t\t\t\tTensor[k][i,j]=1.0\n\t\t\t\tend\n\t\t\t\tif OT[i,j]==-BasisBlade(k)\n\t\t\t\t   Tensor[k][i,j]=-1.0\n\t\t\t    end\n\t\t\tend\n\t\tend\n\tend\n\t#display(Tensor)\n\treturn OT,IOT,OOT,Tensor\nend\n", "meta": {"hexsha": "a7e80cb02e88b3e54307c958a0487156b6e6ee8e", "size": 3208, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/OperationalTables.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Liga.jl-5eb9423b-f148-5a5a-b82f-3778dde28eaa", "max_stars_repo_head_hexsha": "62d328348f0d39954099ebc9c5aa1e6048bfef06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-03-26T07:44:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T19:15:43.000Z", "max_issues_repo_path": "src/OperationalTables.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Liga.jl-5eb9423b-f148-5a5a-b82f-3778dde28eaa", "max_issues_repo_head_hexsha": "62d328348f0d39954099ebc9c5aa1e6048bfef06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OperationalTables.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Liga.jl-5eb9423b-f148-5a5a-b82f-3778dde28eaa", "max_forks_repo_head_hexsha": "62d328348f0d39954099ebc9c5aa1e6048bfef06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7517730496, "max_line_length": 69, "alphanum_fraction": 0.6848503741, "num_tokens": 1056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876287, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.754926075372296}}
{"text": "# p37.jl - 2D \"wave tank\" with Neumann BCs for |y|=1\n\n# x variable in [-A,A], Fourier:\nA = 3; Nx = 50; dx = 2*A/Nx; x = -A+dx*(1:Nx);\nD2x = (pi/A)^2*toeplitz([-1/(3*(dx/A)^2)-1/6;\n        @. .5*(-1).^(2:Nx)/sin((pi*dx/A)*(1:Nx-1)/2)^2]);\n\n# y variable in [-1,1], Chebyshev:\nNy = 15; (Dy,y) = cheb(Ny); D2y = Dy^2;\nBC = -Dy[[1,Ny+1],[1,Ny+1]]\\Dy[[1,Ny+1],2:Ny];\n\n# Grid and initial data:\nvv = @. exp(-8*((x'+1.5)^2+y^2));\ndt = 5/(Nx+Ny^2);\nvvold = @. exp(-8*((x'+dt+1.5).^2+y.^2));\n\n# Time-stepping by leap frog formula:\nplotgap = round(Int,2/dt); dt = 2/plotgap;\nfor n = 0:2*plotgap\n    t = n*dt;\n    if rem(n+.5,plotgap)<1\n        figure(n/plotgap+1); clf(); surf(x,y,vv);\n        gca()[:view_init](60,-100);\n        xlim(-A,A); ylim(-1,1); zlim(-0.15,1);\n        text3D(-2.5,1,.5,\"t = $(round(t))\",fontsize=18);\n        zticks([]);\n    end\n    vvnew = 2*vv - vvold + dt^2*(vv*D2x +D2y*vv);\n    vvold = vv; vv = vvnew;\n    vv[[1,Ny+1],:] = BC*vv[2:Ny,:];       # Neumann BCs for |y|=1\nend\n", "meta": {"hexsha": "001f2f0fbd6fcb8b5eef06c5fce612de4472a9e0", "size": 990, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p37.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p37.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p37.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9375, "max_line_length": 65, "alphanum_fraction": 0.495959596, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7549260649033602}}
{"text": "module GreekAnalytical\n\n__precompile__(true)\n\nusing Distributions\n\nexport blackScholesValue, blackScholesDelta, blackScholesGamma, blackScholesVega, blackScholesTheta\nexport blackScholesVanna, blackScholesVolga, blackScholesSpeed, blackScholesCharm, blackScholesColor, blackScholesZomma\nexport blackScholesRho, blackScholesRhoFutures, blackScholesTouchProb, blackScholesDriftlessTheta\n\nstd_normal = Normal(0, 1)\n\nfunction blackScholesValue(isCall::Bool, spot::T, strike::T, τ::T, r::T, b::T, σ::T) where {T}\n    sign = isCall ? 1 : -1\n\n    d1 = (log(spot / strike) + (b + 0.5 * σ^2) * τ) / (σ * sqrt(τ))\n    d2 = d1 - σ * sqrt(τ)\n\n    sign * (spot * exp((b-r) * τ) * cdf(std_normal, sign * d1) - strike * exp(-r * τ) * cdf(std_normal, sign * d2))\nend\n\nfunction blackScholesDelta(isCall::Bool, spot::T, strike::T, τ::T, r::T, b::T, σ::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * σ^2) * τ) / (σ * sqrt(τ))\n    if isCall\n        exp((b-r) * τ) * cdf(std_normal, d1)\n    else\n        exp((b-r) * τ) * (cdf(std_normal, d1) - 1.0)\n    end\nend\n\nfunction blackScholesGamma(isCall::Bool, spot::T, strike::T, τ::T, r::T, b::T, σ::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * σ^2) * τ) / (σ * sqrt(τ))\n    pdf(std_normal, d1) * exp((b-r) * τ) / spot / σ / sqrt(τ)\nend\n\nfunction blackScholesVega(isCall::Bool, spot::T, strike::T, τ::T, r::T, b::T, σ::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * σ^2) * τ) / (σ * sqrt(τ))\n    spot * exp((b-r) * τ) * pdf(std_normal, d1) * sqrt(τ)\nend\n\nfunction blackScholesTheta(isCall::Bool, spot::T, strike::T, τ::T, r::T, b::T, σ::T) where {T}\n    sign = isCall ? 1 : -1\n\n    d1 = (log(spot / strike) + (b + 0.5 * σ^2) * τ) / (σ * sqrt(τ))\n    d2 = d1 - σ * sqrt(τ)\n\n    term1 = -spot * exp((b-r) * τ) * pdf(std_normal, d1) * σ / 2 / sqrt(τ)\n    term2 = -sign * (b-r) * spot * exp((b-r) * τ) * cdf(std_normal, sign * d1)\n    term3 = -sign * r * strike * exp(-r * τ) * cdf(std_normal, sign * d2)\n\n    term1 + term2 + term3\nend\n\nfunction blackScholesVanna(isCall::Bool, spot::T, strike::T, τ::T, r::T, b::T, σ::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * σ^2) * τ) / (σ * sqrt(τ))\n    d2 = d1 - σ * sqrt(τ)\n\n    -d2 * pdf(std_normal, d1) / σ * exp((b-r) * τ)\nend\n\nfunction blackScholesCharm(isCall::Bool, spot::T, strike::T, τ::T, r::T, b::T, σ::T) where {T}\n    sign = isCall ? 1 : -1\n\n    d1 = (log(spot / strike) + (b + 0.5 * σ^2) * τ) / (σ * sqrt(τ))\n    d2 = d1 - σ * sqrt(τ)\n\n    term1 = pdf(std_normal, d1) * (b / σ / sqrt(τ) - d2 / 2 / τ)\n    term2 = sign * (b - r) * cdf(std_normal, sign * d1)\n\n    -exp((b-r) * τ) * (term1 + term2)\nend\n\nfunction blackScholesVolga(isCall::Bool, spot::T, strike::T, τ::T, r::T, b::T, σ::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * σ^2) * τ) / (σ * sqrt(τ))\n    d2 = d1 - σ * sqrt(τ)\n\n    blackScholesVega(isCall, spot, strike, τ, r, b, σ) * d1 * d2 / σ\nend\n\nfunction blackScholesSpeed(isCall::Bool, spot::T, strike::T, τ::T, r::T, b::T, σ::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * σ^2) * τ) / (σ * sqrt(τ))\n\n    -1.0 * blackScholesGamma(isCall, spot, strike, τ, r, b, σ) / spot * (1 + d1 / σ / sqrt(τ))\nend\n\nfunction blackScholesZomma(isCall::Bool, spot::T, strike::T, τ::T, r::T, b::T, σ::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * σ^2) * τ) / (σ * sqrt(τ))\n    d2 = d1 - σ * sqrt(τ)\n\n    blackScholesGamma(isCall, spot, strike, τ, r, b, σ) * (d1 * d2 - 1.0) / σ\nend\n\nfunction blackScholesColor(isCall::Bool, spot::T, strike::T, τ::T, r::T, b::T, σ::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * σ^2) * τ) / (σ * sqrt(τ))\n    d2 = d1 - σ * sqrt(τ)\n\n    blackScholesGamma(isCall, spot, strike, τ, r, b, σ) * (r - b + b * d1 / σ / sqrt(τ) + (1 - d1 * d2) / 2 / τ)\nend\n\nfunction blackScholesDriftlessTheta(isCall::Bool, spot::T, strike::T, τ::T, r::T, b::T, σ::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * σ^2) * τ) / (σ * sqrt(τ))\n    println(pdf(std_normal, d1))\n    -spot * pdf(std_normal, d1) * σ / 2 / sqrt(τ)\nend\n\nfunction blackScholesRho(isCall::Bool, spot::T, strike::T, τ::T, r::T, b::T, σ::T) where {T}\n    sign = isCall ? 1 : -1\n\n    d1 = (log(spot / strike) + (b + 0.5 * σ^2) * τ) / (σ * sqrt(τ))\n    d2 = d1 - σ * sqrt(τ)\n\n    sign * τ * strike * exp(-r * τ) * cdf(std_normal, sign * d2)\nend\n\nfunction blackScholesRhoFutures(isCall::Bool, spot::T, strike::T, τ::T, r::T, b::T, σ::T) where{T}\n    -1.0 * τ * blackScholesValue(isCall, spot, strike, τ, r, b, σ)\nend\n\nfunction blackScholesTouchProb(isCall::Bool, spot::T, strike::T, τ::T, r::T, b::T, σ::T) where {T}\n    if isCall\n        if strike <= spot\n            return 1.0\n        end\n    else\n        if strike >= spot\n            return 1.0\n        end\n    end\n\n    sign = isCall ? -1 : 1\n\n    μ = (b - σ^2 / 2) / (σ * σ)\n    λ = sqrt(μ^2 + 2 * r / (σ * σ))\n    z = log(strike / spot) / σ / sqrt(τ) + λ * σ * sqrt(τ)\n\n    (strike / spot) ^ (μ + λ) * cdf(std_normal, sign * z) + (strike / spot) ^ (μ - λ) * cdf(std_normal, sign * (z - 2 * λ * σ * sqrt(τ)))\nend\n\nend", "meta": {"hexsha": "70d0d8ed1964c726f47f0c375729c312a51de2ce", "size": 4992, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GreekAnalytical.jl", "max_stars_repo_name": "Stochastic-Adventure/BlackScholesGreeks", "max_stars_repo_head_hexsha": "3e984fa3db76c2949b950daacfdca8827d950a44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GreekAnalytical.jl", "max_issues_repo_name": "Stochastic-Adventure/BlackScholesGreeks", "max_issues_repo_head_hexsha": "3e984fa3db76c2949b950daacfdca8827d950a44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GreekAnalytical.jl", "max_forks_repo_name": "Stochastic-Adventure/BlackScholesGreeks", "max_forks_repo_head_hexsha": "3e984fa3db76c2949b950daacfdca8827d950a44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9136690647, "max_line_length": 137, "alphanum_fraction": 0.5482772436, "num_tokens": 2132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.7549260628016409}}
{"text": "# power analysis functions for proportions\n\n\"\"\"\n    powerPTest(h::Real = 0, n::Real = 0, alpha::Float64 = 0.05, alternative = \"two.sided\")\n\nCompute power of a sample of `n` observations to test the effect size `h`\nfor one sample proportion (P) compared to a constant (c) at type I error = `alpha` (default: 0.05).\nThe effect size `h` = ϕ₁ - ϕ₂ where ϕ₁ = 2*asin(sqrt(P)) and ϕ₂ = 2*asin(sqrt(c)). The option\n`alternative` is `two.sided` for H₀: ϕ₁ = ϕ₂ vs H₁: ϕ₁ ≠ ϕ₂, `less` for H₁: ϕ₁ < ϕ₂, and `greater`\nfor H₁: ϕ₁ > ϕ₂.\n\"\"\"\nfunction powerPTest(;\n    h::Real = 0,\n    n::Real = 0,\n    alpha::Float64 = 0.05,\n    alternative::String = \"two.sided\"\n    )\n\n    check_args(h=h,n=n,alpha=alpha)\n\n    if alternative == \"less\"\n        tside = 1\n    elseif alternative in (\"two\",\"two.sided\",\"two-sided\",\"two sided\")\n        tside = 2\n        h = abs(h)\n    elseif alternative == \"greater\"\n        tside = 3\n    else\n        error(\"`alternative` must be `less`, `two.sided`, or `greater`.\")\n    end\n\n    if tside == 1\n        return cdf(Normal(),quantile(Normal(),alpha) - h*sqrt(n))\n    elseif tside == 2\n        return ccdf(Normal(),cquantile(Normal(),alpha/2) - h*sqrt(n)) + cdf(Normal(),quantile(Normal(),alpha/2) - h*sqrt(n))\n    elseif tside == 3\n        return ccdf(Normal(),cquantile(Normal(),alpha) - h*sqrt(n))\n    end\n    error(\"internal error\")\nend\n\n\"\"\"\n    samplesizePTest(h::Real = 0, alpha::Float64 = 0.05, power::Float64 = 0.8, alternative = \"two.sided\")\n\nCompute the sample size to test the effect size `h` for one sample proportion (P) compared to a constant (c)\nwith power > `power` (default: 0.8) and type I error = `alpha` (default: 0.05).\nThe effect size `h` = ϕ₁ - ϕ₂ where ϕ₁ = 2*asin(sqrt(P)) and ϕ₂ = 2*asin(sqrt(c)). The option\n`alternative` is `two.sided` for H₀: ϕ₁ = ϕ₂ vs H₁: ϕ₁ ≠ ϕ₂, `less` for H₁: ϕ₁ < ϕ₂, and `greater`\nfor H₁: ϕ₁ > ϕ₂.\n\"\"\"\nfunction samplesizePTest(;\n    h::Real = 0,\n    alpha::Float64 = 0.05,\n    power::Float64 = 0.8,\n    alternative::String = \"two\"\n    )\n\n    check_args(h=h,alpha=alpha,power=power)\n\n    return ceil(Int64,fzero(x->powerPTest(h = h, n = x, alpha = alpha, alternative = alternative) - power, 2 + 1e-10, 1e+09))\nend\n\n\"\"\"\n    effectsizePTest(n::Real = 0, alpha::Float64 = 0.05, power::Float64 = 0.8, alternative = \"two.sided\")\n\nCompute the effect size that a sample size `n` can detect for one sample proportion (P) compared to a constant (c)\nwith power > `power` (default: 0.8) and type I error = `alpha` (default: 0.05).\nThe effect size `h` = ϕ₁ - ϕ₂ where ϕ₁ = 2*asin(sqrt(P)) and ϕ₂ = 2*asin(sqrt(c)). The option\n`alternative` is `two.sided` for H₀: ϕ₁ = ϕ₂ vs H₁: ϕ₁ ≠ ϕ₂, `less` for H₁: ϕ₁ < ϕ₂, and `greater`\nfor H₁: ϕ₁ > ϕ₂.\n\"\"\"\nfunction effectsizePTest(;\n    n::Real = 0,\n    alpha::Real = 0.05,\n    power::Real = 0.0,\n    alternative::String = \"two\"\n    )\n\n    check_args(n=n,alpha=alpha,power=power)\n\n    return fzero(x->powerPTest(h = x, n = n, alpha = alpha, alternative = alternative) - power, 1e-10, 1 - 1e-10)\nend\n\n\"\"\"\n    alphaPTest(h::Real = 0, n::Real = 0, power::Float64 = 0.8, alternative = \"two.sided\")\n\nCompute the probability of type I error that a sample size `n` has in detecting the effect size `h`\nfor one sample proportion (P) compared to a constant (c) with power > `power` (default: 0.8)\nand type I error = `alpha` (default: 0.05). The effect size `h` = ϕ₁ - ϕ₂ where ϕ₁ = 2*asin(sqrt(P)) and ϕ₂ = 2*asin(sqrt(c)).\nThe option `alternative` is `two.sided` for H₀: ϕ₁ = ϕ₂ vs H₁: ϕ₁ ≠ ϕ₂, `less` for H₁: ϕ₁ < ϕ₂, and `greater`\nfor H₁: ϕ₁ > ϕ₂.\n\"\"\"\nfunction alphaPTest(;\n    h::Real = 0,\n    n::Real = 0,\n    power::Float64 = 0.8,\n    alternative::String = \"two\"\n    )\n\n    check_args(h=h,n=n,power=power)\n\n    return fzero(x->powerPTest(h = h, n = n, alpha = x, alternative = alternative) - power, 1e-10, 1 - 1e-10)\nend\n\n\"\"\"\n    pwr.PTest(h::Real = 0, n::Real = 0, alpha::Float64 = 0.0, power::Float64 = 0.0, alternative = \"two.sided\")\n\nCompute one of the test parameters such as sample size (`n`),\neffect size (`h`), type I error (`alpha`), and power (`power`).\nThe parameter to be estimated must be set to zero (default).\nThe effect size `h` = ϕ₁ - ϕ₂ where ϕ₁ = 2*asin(sqrt(P)) and ϕ₂ = 2*asin(sqrt(c)).\nThe option `alternative` is `two.sided` for H₀: ϕ₁ = ϕ₂ vs H₁: ϕ₁ ≠ ϕ₂, `less` for H₁: ϕ₁ < ϕ₂, and `greater`\nfor H₁: ϕ₁ > ϕ₂.\n\"\"\"\nfunction PTest(;\n    h::Real = 0,\n    n::Real = 0,\n    alpha::Float64 = 0.0,\n    power::Float64 = 0.0,\n    alternative::String = \"two.sided\"\n    )\n    if sum([x == 0 for x in (h,n,alpha,power)]) != 1\n        error(\"exactly one of `h`, `n`, `power`, and `alpha` must be zero\")\n    end\n\n    if power == 0.0\n        power = powerPTest(h = h, n = n, alpha = alpha, alternative = alternative)\n    elseif alpha == 0.0\n        alpha = alphaPTest(h = h, n = n, power = power, alternative = alternative)\n    elseif h == 0\n        h = effectsizePTest(n = n, alpha = alpha, power = power, alternative = alternative)\n    elseif n == 0\n        n = samplesizePTest(h = h, alpha = alpha, power = power, alternative = alternative)\n    end\n\n    alt = Dict(\"two\" => \"two-sided\", \"two.sided\" => \"two-sided\",\"two sided\" => \"two-sided\", \"less\" => \"less\", \"greater\" => \"greater\")\n\n    return htest(\n        string(\"Proportion power calculation for binomial distribution (arcsine transformation)\"),\n        OrderedDict(\n            \"h\" => h,\n            \"n\" => n,\n            \"alpha\" => alpha,\n            \"power\" => power,\n            \"alternative\" => alt[alternative]\n            )\n        )\nend\n", "meta": {"hexsha": "0289b3cb9e8e68c09923c5bd88dff0e6a588e394", "size": 5504, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PTest.jl", "max_stars_repo_name": "mwsohn/pwr", "max_stars_repo_head_hexsha": "da971f3fed7a414604fc32d585e6f6d9bf0204cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PTest.jl", "max_issues_repo_name": "mwsohn/pwr", "max_issues_repo_head_hexsha": "da971f3fed7a414604fc32d585e6f6d9bf0204cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PTest.jl", "max_forks_repo_name": "mwsohn/pwr", "max_forks_repo_head_hexsha": "da971f3fed7a414604fc32d585e6f6d9bf0204cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9395973154, "max_line_length": 133, "alphanum_fraction": 0.6059229651, "num_tokens": 1915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7549137814204633}}
{"text": "function meantoecc(M::FloatingPoint, ecc::FloatingPoint)\n    kepler(E) = E - ecc*sin(E) - M\n    kepler_der(E) = 1 - ecc*cos(E)\n    return newton(M, kepler, kepler_der)\nend\n\nfunction ecctomean(E::FloatingPoint, ecc::FloatingPoint)\n    return E - ecc*sin(E)\nend\n\nfunction ecctotrue(E::FloatingPoint, ecc::FloatingPoint)\n    return 2*atan2(sqrt(1 + ecc)*sin(E/2), sqrt(1 - ecc)*cos(E/2))\nend\n\nfunction truetoecc(T::FloatingPoint, ecc::FloatingPoint)\n    return 2*atan2(sqrt(1 - ecc)*sin(T/2), sqrt(1 + ecc)*cos(T/2))\nend\n\nfunction period(a::FloatingPoint, mu::FloatingPoint)\n    return sqrt(4*a^3*pi^2/mu)\nend\n\nfunction period(s::State)\n    mu = planets[s.body][\"mu\"]\n    ele = elements(s)\n    return period(ele[1], mu)\nend\n\nfunction kepler(ele::Vector, dt::FloatingPoint, mu::FloatingPoint)\n    E0 = truetoecc(ele[6], ele[2])\n    M0 = ecctomean(E0, ele[2])\n    n = 2*pi/period(ele[1], mu)\n    M = M0 + n*dt\n    E = meantoecc(M, ele[2])\n    T = ecctotrue(E, ele[2])\n    return [ele[1:5], T]\nend\n\nfunction kepler(ele::Vector, dt::Vector, mu::FloatingPoint)\n    out = Array(FloatingPoint, length(dt), 6)\n    for i = 1:length(dt)\n        out[i,:] = kepler(ele, dt[i], mu)\n    end\n    return out\nend\n", "meta": {"hexsha": "18b2490475d13b94e4fff1c522b11d1fff9b8701", "size": 1193, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kepler.jl", "max_stars_repo_name": "mlandgraf13/Astrodynamics.jl", "max_stars_repo_head_hexsha": "d39d2dfc8d6d0cf437d0c2f2d003a1d4fc9738ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kepler.jl", "max_issues_repo_name": "mlandgraf13/Astrodynamics.jl", "max_issues_repo_head_hexsha": "d39d2dfc8d6d0cf437d0c2f2d003a1d4fc9738ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kepler.jl", "max_forks_repo_name": "mlandgraf13/Astrodynamics.jl", "max_forks_repo_head_hexsha": "d39d2dfc8d6d0cf437d0c2f2d003a1d4fc9738ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9347826087, "max_line_length": 66, "alphanum_fraction": 0.64124057, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.754913771584869}}
{"text": "type Point{T}\n  x::T\n  y::T\nend\n\nPoint{Int64} #> Point{Int64} (constructor with 1 method)\nPoint{Float64} #> Point{Float64} (constructor with 1 method)\nPoint{String} #> Point{String} (constructor with 1 method)\n\nissubtype(Point{Int64}, Point) #> true\nissubtype(Point{String}, Point) #> true\nissubtype(Point{Float64}, Point{Real}) #> false\n\np = Point{Int64}(2, 5) #> Point{Int64}(2,5)\np = Point(2, 5) #> Point{Int64}(2,5)\np = Point(\"London\", \"Great-Britain\") #> Point{String}(\"London\", \"Great-Britain\")\n\ntype PointP{T <: Real}\n  x::T\n  y::T\nend\n\n# p = PointP(\"London\", \"Great-Britain\") #> ERROR: `PointP{T<:Real}` has no method \n# matching Point{T<:Real}(::ASCIIString, : ASCIIString)\n\nadd{T}(x::T, y::T) = x + y\nadd(2, 3) #> 5\n# add(2, 3.0) #> ERROR: `add` has no method matching add(::Int64, ::Float64)\nadd{T<:Number}(x::T, y::T) = x + y\n\nfunction vecfloat{T <: FloatingPoint}(x::Vector{T}) \n# code   \nend", "meta": {"hexsha": "238352c500caf01f1dd74063f978e4d5db759b2b", "size": 905, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Module 1/Chapter06/parametric.jl", "max_stars_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_stars_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2017-02-12T15:36:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T03:30:39.000Z", "max_issues_repo_path": "Module 1/Chapter06/parametric.jl", "max_issues_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_issues_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Module 1/Chapter06/parametric.jl", "max_forks_repo_name": "PacktPublishing/Julia-High-Performance-Programming", "max_forks_repo_head_hexsha": "861d655d163d8b87bb05478bfd255735b9263d60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-02-10T16:19:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T11:46:44.000Z", "avg_line_length": 27.4242424242, "max_line_length": 82, "alphanum_fraction": 0.6386740331, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8705972700870909, "lm_q1q2_score": 0.7548389655516565}}
{"text": "# #  Portfolio Optimization - Markowitz Efficient Frontier \n#\n# In this problem, we will find the unconstrained portfolio allocation where we introduce the weighting parameter $\\lambda \\;(0 \\leq \\lambda \\leq$ 1) and minimize $\\lambda * \\text{risk} - (1-\\lambda)* \\text{expected return}$. By varying the values of $\\lambda$, we trace out the efficient frontier.  \n#\n# Suppose that we know the mean returns $\\mu \\in \\mathbf{R}^n$ of each asset and the covariance $\\Sigma \\in \\mathbf{R}^{n \\times n}$ between the assets. Our objective is to find a portfolio allocation that minimizes the *risk* (which we measure as the variance $w^T \\Sigma w$) and maximizes the *expected return* ($w^T \\mu$) of the portfolio of the simulataneously. We require $w \\in \\mathbf{R}^n$ and $\\sum_i w_i = 1$.\n#\n# This problem can be written as\n#\n# $$\n# \\begin{array}{ll}\n#     \\mbox{minimize}   & \\lambda*w^T \\Sigma w - (1-\\lambda)*w^T \\mu \\\\\n#     \\mbox{subject to} & \\sum_i w_i = 1\n# \\end{array}\n# $$\n#\n# where $w \\in \\mathbf{R}^n$ is the vector containing weights allocated to each asset.\n\nusing Convex, SCS    #We are using SCS solver. Install using Pkg.add(\"SCS\")\n\n## generate problem data\nμ = [11.5; 9.5; 6]/100          #expected returns\nΣ  = [166  34  58;              #covariance matrix\n       34  64   4;\n       58   4 100]/100^2\n\nn = length(μ)                   #number of assets \n\n# If you want to try the optimization with more assets, uncomment and run the next cell. It creates a vector or average returns and a variance-covariance matrix that have scales similar to the numbers above.\n\n#=\nusing Random\nRandom.seed!(123)\n\nn = 15                                      #number of assets, CHANGE IT?\n\nμ = (6 .+ (11.5-6)*rand(n))/100             #mean\nA = randn(n,n)\nΣ = (A * A' + diagm(0=>rand(n)))/500;       #covariance matrix\n=#\n\n# First we solve without any bounds on $w$\n\nN = 101\nλ_vals = range(0.01,stop=0.99,length=N)\n\nw    = Variable(n)\nret  = dot(w,μ)\nrisk = quadform(w,Σ)\n\nMeanVarA = zeros(N,2)                    \nfor i = 1:N\n    λ = λ_vals[i]\n    p = minimize( λ*risk - (1-λ)*ret,\n                  sum(w) == 1 )    \n    solve!(p, SCSSolver(verbose = false))\n    MeanVarA[i,:]= [evaluate(ret),evaluate(risk)[1]]    #risk is a 1x1 matrix\nend\n\n# Now we solve with the bounds $0\\le w_i \\le 1$\n\nw_lower = 0                     #bounds on w\nw_upper = 1\n\nMeanVarB = zeros(N,2)   #repeat, but with 0<w[i]<1\nfor i = 1:N\n    λ = λ_vals[i]\n    p = minimize( λ*risk - (1-λ)*ret,\n                  sum(w) == 1,\n                  w_lower <= w,     #w[i] is bounded\n                  w <= w_upper )\n    solve!(p, SCSSolver(verbose = false))\n    MeanVarB[i,:]= [evaluate(ret),evaluate(risk)[1]]    \nend\n\n#-\n\nusing Plots\nplot( sqrt.([MeanVarA[:,2] MeanVarB[:,2]]),\n      [MeanVarA[:,1] MeanVarB[:,1]],\n      xlim = (0,0.25),\n      ylim = (0,0.15),\n      title = \"Markowitz Efficient Frontier\",\n      xlabel = \"Standard deviation\",\n      ylabel = \"Expected return\",\n      label = [\"no bounds on w\",\"with 0<w<1\",])\nscatter!(sqrt.(diag(Σ)),μ,color=:red,label = \"assets\")\n\n# We now instead impose a restriction on  $\\sum_i |w_i| - 1$, allowing for varying degrees of \"leverage\".\n\nLmax = 0.5\n\nMeanVarC = zeros(N,2)   #repeat, but with restriction on Sum(|w[i]|)\nfor i = 1:N\n    λ = λ_vals[i]\n    p = minimize( λ*risk - (1-λ)*ret,\n                  sum(w) == 1,\n                  (norm(w, 1)-1) <= Lmax)\n    solve!(p, SCSSolver(verbose = false))\n    MeanVarC[i,:]= [evaluate(ret),evaluate(risk)[1]]    \nend\n\n#-\n\nplot( sqrt.([MeanVarA[:,2] MeanVarB[:,2] MeanVarC[:,2]]),\n      [MeanVarA[:,1] MeanVarB[:,1] MeanVarC[:,1]],\n      xlim = (0,0.25),\n      ylim = (0,0.15),\n      title = \"Markowitz Efficient Frontier\",\n      xlabel = \"Standard deviation\",\n      ylabel = \"Expected return\",\n      label = [\"no bounds on w\",\"with 0<w<1\",\"restriction on sum(|w|)\"])\nscatter!(sqrt.(diag(Σ)),μ,color=:red,label = \"assets\")\n\n#-\n", "meta": {"hexsha": "6a9944744263d053d9d0fb4e7f04f116984b3d51", "size": 3893, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/portfolio_optimization/portfolio_optimization2.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Convex.jl-f65535da-76fb-5f13-bab9-19810c17039a", "max_stars_repo_head_hexsha": "52a024f0880e5aab8ee6b1e4e4730f76e1b9d08a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/examples_literate/portfolio_optimization/portfolio_optimization2.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Convex.jl-f65535da-76fb-5f13-bab9-19810c17039a", "max_issues_repo_head_hexsha": "52a024f0880e5aab8ee6b1e4e4730f76e1b9d08a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/examples_literate/portfolio_optimization/portfolio_optimization2.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Convex.jl-f65535da-76fb-5f13-bab9-19810c17039a", "max_forks_repo_head_hexsha": "52a024f0880e5aab8ee6b1e4e4730f76e1b9d08a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.852173913, "max_line_length": 419, "alphanum_fraction": 0.5872078089, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.7547759657189613}}
{"text": "# using StaticArrays\n\n# Define Rosenbrock function: https://en.wikipedia.org/wiki/Rosenbrock_function\n#\n# This function can be interpreted as a NLS pb:\n# r_1 = (1-θ₁)\n# r_2 = 10(θ₂-θ₁²)\n#\n# Jacobian is: [[-1, 0],[-20, 10]]\n#\n# Minimum for θ=(1,1) where f=1/2 r^2 = 0\n#\n# TODO: implement even n (here 2) generalization of the wiki page.\n#\nstruct Rosenbrock <: AbstractNLS\nend\n\n\nparameter_size(::Rosenbrock) = 2\nresidue_size(::Rosenbrock) = 2\n\nfunction eval_r(nls::Rosenbrock,θ::AbstractVector{T}) where T\n    @assert length(θ)==parameter_size(nls)\n\n    T[ 1-θ[1], 10*(θ[2]-θ[1]^2) ]\nend\n\nfunction eval_r_J(nls::Rosenbrock,θ::AbstractVector{T}) where T\n    @assert length(θ)==parameter_size(nls)\n\n    r = T[ 1-θ[1], 10*(θ[2]-θ[1]^2) ]\n    J = T[ -1 0; -20*θ[1] 10]\n\n    (r,J)\nend\n\n\n\n# ================================================================\n\nconst Rosenbrock_Static = Rosenbrock\n\n# # Define the same Rosenbrock function but using Statics Arrays... This\n# # cause some problems: https://github.com/JuliaArrays/StaticArrays.jl/issues/971\n# #\n# struct Rosenbrock_Static <: AbstractNLS\n# end\n\n\n# parameter_size(::Rosenbrock_Static) = 2\n# residue_size(::Rosenbrock_Static) = 2\n\n# function eval_r(nls::Rosenbrock_Static,θ::AbstractVector{T}) where T\n#     @assert length(θ)==parameter_size(nls)\n\n#     r = @SVector T[1-θ[1],\n#                    10*(θ[2]-θ[1]^2)]\n# end\n\n# function eval_r_J(nls::Rosenbrock_Static,θ::AbstractVector{T}) where T\n#     @assert length(θ)==parameter_size(nls)\n\n#     r = eval_r(nls,θ)\n\n#     # CAVEAT: SMatrix are filled column by column\n#     #\n#     # The Jacobian\n#     #\n#     # | ∂1r1, ∂2r1 |\n#     # | ∂1r2, ∂2r2 |\n#     #\n#     # must be created by\n#     #\n#     # SMatrix(∂1r1,∂1r2, # col 1\n#     #         ∂2r1,∂2r2) # col 2\n#     #\n#     # which is not intuitive and error prone.\n#     #\n#     # The alternative to is to use the @SMatrix macro\n#     # that follows the \"natural\" order (row by row)\n#     #\n#     J = @SMatrix T[      -1   +0;     # ∂1r1, ∂2r1\n#                          -20*θ[1]  +10]     # ∂1r2, ∂2r2\n  \n#     (r, J)\n# end\n", "meta": {"hexsha": "e671b0a7f600bcea768c86a2e878c8200501dac8", "size": 2080, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/TestProblems/Rosenbrock.jl", "max_stars_repo_name": "vincent-picaud/NLS_Solver.jl", "max_stars_repo_head_hexsha": "55d1a21e2128427ce168579ee67bde6f3499870b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-02T14:49:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T19:49:40.000Z", "max_issues_repo_path": "test/TestProblems/Rosenbrock.jl", "max_issues_repo_name": "vincent-picaud/NLS_Solver.jl", "max_issues_repo_head_hexsha": "55d1a21e2128427ce168579ee67bde6f3499870b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-12-25T23:06:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-30T21:04:01.000Z", "max_forks_repo_path": "test/TestProblems/Rosenbrock.jl", "max_forks_repo_name": "vincent-picaud/NLS_Solver.jl", "max_forks_repo_head_hexsha": "55d1a21e2128427ce168579ee67bde6f3499870b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.908045977, "max_line_length": 82, "alphanum_fraction": 0.5778846154, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220786, "lm_q2_score": 0.865224070413529, "lm_q1q2_score": 0.7547759377193523}}
{"text": "# functions related to F distribution\n\nimport .RFunctions:\n    fdistpdf,\n    fdistlogpdf,\n    fdistcdf,\n    fdistccdf,\n    fdistlogcdf,\n    fdistlogccdf,\n    fdistinvcdf,\n    fdistinvccdf,\n    fdistinvlogcdf,\n    fdistinvlogccdf\n\n# pdf for numbers with generic types\nfdistpdf(ν1::Real, ν2::Real, x::Number) = sqrt((ν1 * x)^ν1 * ν2^ν2 / (ν1 * x + ν2)^(ν1 + ν2)) / (x * beta(ν1 / 2, ν2 / 2))\n\n# logpdf for numbers with generic types\nfdistlogpdf(ν1::Real, ν2::Real, x::Number) = (ν1 * log(ν1 * x) + ν2 * log(ν2) - (ν1 + ν2) * log(ν1 * x + ν2)) / 2 - log(x) - lbeta(ν1 / 2, ν2 / 2)\n", "meta": {"hexsha": "b46c796255a5ed93286e45c86660bf9e56e756ef", "size": 578, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distrs/fdist.jl", "max_stars_repo_name": "nilshg/StatsFuns.jl", "max_stars_repo_head_hexsha": "bca4582b2c788b65d3a51e52ab339794c58ea9f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distrs/fdist.jl", "max_issues_repo_name": "nilshg/StatsFuns.jl", "max_issues_repo_head_hexsha": "bca4582b2c788b65d3a51e52ab339794c58ea9f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distrs/fdist.jl", "max_forks_repo_name": "nilshg/StatsFuns.jl", "max_forks_repo_head_hexsha": "bca4582b2c788b65d3a51e52ab339794c58ea9f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9, "max_line_length": 146, "alphanum_fraction": 0.6089965398, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122684798184, "lm_q2_score": 0.7879311881731379, "lm_q1q2_score": 0.7547689518689291}}
{"text": "# ================================\n# Concrete symmetric interval hull\n# ================================\n\n\"\"\"\n    symmetric_interval_hull(S::LazySet{N}) where {N}\n\nOverapproximate a set by a tight hyperrectangle centered in the origin.\n\n### Input\n\n- `S` -- set\n\n### Output\n\nA tight hyperrectangle that is centrally symmetric wrt. the origin.\n\n### Algorithm\n\nThe center of the box is the origin, and the radius is obtained by computing the\nmaximum value of the support function evaluated in the canonical directions.\n\"\"\"\nfunction symmetric_interval_hull(S::LazySet{N}) where {N}\n    # fallback returns a hyperrectangular set\n    (c, r) = box_approximation_helper(S)\n    if r[1] < 0\n        return EmptySet{N}(dim(S))\n    end\n    return Hyperrectangle(zeros(N, length(c)), abs.(c) .+ r)\nend\n\n\"\"\"\n    box_approximation_symmetric\n\nAlias for `symmetric_interval_hull`.\n\"\"\"\nbox_approximation_symmetric = symmetric_interval_hull\n\n# ===============\n# Specializations\n# ===============\n\n# empty set specialization\nsymmetric_interval_hull(∅::EmptySet) = ∅\n\nfunction LazySets.concretize(sih::SymmetricIntervalHull)\n    return symmetric_interval_hull(LazySets.concretize(sih.X))\nend\n\n# interval specialization\nfunction symmetric_interval_hull(x::Interval)\n    abs_inf = abs(min(x))\n    abs_sup = abs(max(x))\n    bound = max(abs_sup, abs_inf)\n    return Interval(-bound, bound)\nend\n\n# hyperrectangle specialization\n@inline function _maxabs(c::N, r::N) where {N}\n    return c >= zero(N) ? c + r : -c + r\nend\n\nfunction symmetric_interval_hull(H::Hyperrectangle{N}) where {N}\n    n = dim(H)\n    r = Vector{N}(undef, n)\n    @inbounds for i in 1:n\n        r[i] = _maxabs(H.center[i], H.radius[i])\n    end\n    return Hyperrectangle(zeros(N, n), r)\nend\n", "meta": {"hexsha": "bc1d663432df6efb3f0217f139375600e738d25a", "size": 1733, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Approximations/symmetric_interval_hull.jl", "max_stars_repo_name": "goretkin/LazySets.jl", "max_stars_repo_head_hexsha": "6e829d9179bc25b8d7f6afb190a015e53760c601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Approximations/symmetric_interval_hull.jl", "max_issues_repo_name": "goretkin/LazySets.jl", "max_issues_repo_head_hexsha": "6e829d9179bc25b8d7f6afb190a015e53760c601", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Approximations/symmetric_interval_hull.jl", "max_forks_repo_name": "goretkin/LazySets.jl", "max_forks_repo_head_hexsha": "6e829d9179bc25b8d7f6afb190a015e53760c601", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4084507042, "max_line_length": 80, "alphanum_fraction": 0.667051356, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7546874531125263}}
{"text": "export legendrePoly #Just a basic export to make legendrePoly function visible (ie. Public)\n\n## Function that computes the legendre polynomial of nᵗʰ order\n#  INPUTS:\n# Type T - ?????\n# order - Integer defining the desired Legendre polynomial order\n#  OUTPUTS:\n# Pₙ(x) - Legendre polynomial of order n=\"order\"\n\nfunction legendrePoly(::Type{T},order::Int) where {T} #compute Legendre polynomial\n##Throw an error if we ask for a polynomial of negative order\n    order<0 && error(\"order must be >= 0\") #If order is less than zero, we throw an error\n##Manually input legendre polynomials of orders 0 and 1\n    P = [Polynomial{T}(1), Polynomial{T}([0,1])] #initialize our horizon for pseudo-recursion with known Legendre Polynomials: P=[1,x]\n    x = Polynomial{T}([0,1]) #x is just an instance of type Polynomial\n##For orders 0 or 1 we return 1 or x respectively\n    order<2 && return P[order+1] #if order is 1 return x, if order is 0 return 1\n## For order>=2: we are using Bonnet recursion formula: nPₙ(x)=(2n-1)Pₙ₋₁(x)-(n-1)Pₙ₋₂(x)\n# Compute Pᵢ₊₁ from Pᵢ and Pᵢ₋₁ in a pseudo-recursive way\n    for i = 1:order-1 #i is effectively n-1 (ie. current order-1) because we index from 1 to \"order-1\" instead of the natural 2 to \"order\"\n        Ptmp = ( (2*i + 1 ) * x * P[2] - i * P[1]) / (i+1) #this computes Pᵢ₊₁ in a pseudo recursive manner\n        P[1] = P[2] #here we save Pᵢ for next iteration\n        P[2] = Ptmp #here we save Pᵢ₊₁ for next iteration\n    end\n## Return P of order \"order\"\n    return P[2]\nend\n\nlegendrePoly(order::T) where {T} = legendrePoly(T,convert(Int,order)) #I suspect here he tried to do some proper recursion, but idk\n", "meta": {"hexsha": "edd2b09596f35d641d1c2fc138e98b13669ff6c5", "size": 1638, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/legendre.jl", "max_stars_repo_name": "LucianNita/MorePolynomials.jl", "max_stars_repo_head_hexsha": "e6c47f9e79d44326950885ed4464f7944bf6744d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/legendre.jl", "max_issues_repo_name": "LucianNita/MorePolynomials.jl", "max_issues_repo_head_hexsha": "e6c47f9e79d44326950885ed4464f7944bf6744d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/legendre.jl", "max_forks_repo_name": "LucianNita/MorePolynomials.jl", "max_forks_repo_head_hexsha": "e6c47f9e79d44326950885ed4464f7944bf6744d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.6, "max_line_length": 138, "alphanum_fraction": 0.6892551893, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7546874531125263}}
{"text": "\n\nfunction _minimum!(D,clusterInd)\n    N = size(D,1)\n    m = Inf\n    mI = mJ = -1\n    for j=2:N\n        clusterInd[j]==0 && continue\n        for i=1:j-1\n            clusterInd[i]==0 && continue\n            if D[i,j]<=m\n                m = D[i,j]\n                mI,mJ = i,j\n            end\n        end\n    end\n    m, mI, mJ\nend\n\n\n\n# only upper triangular part of D is used \nfunction hierarchicalclustering(D::AbstractMatrix{T}; similarity=false) where {T}\n    @assert size(D,1)==size(D,2)\n    N = size(D,1)\n\n    distType = promote_type(Float64,T)\n    D = copy(convert(Array{distType},D)) # since D will be updated when clusters are merged\n    similarity && (D*=-1) # just change sign when using similarity instead of dissimilarity! (Nothing breaks if we have distances below 0. Relative values are all that matter.)\n\n\n    # index, index, nbr elements in cluster, distance/similarity\n    # indices 1-N\n    clusters = Vector{Tuple{Int,Int,Int,distType}}()\n    \n    # the cluster index for each row/column in D. Indices from 1:N are leaves.\n    # From N+1 and upwards are in clusters Vector (subtract N from index).\n    # A value of 0 means that the row/column is no longer used. (One row/column is discarded every time two clusters are merged.)\n    clusterInd = collect(1:N)\n\n\n    for k=1:N-1 # each created cluster has two children, i.e. we need N-1 clusters (not counting leaves)\n        m,mI,mJ = _minimum!(D,clusterInd)\n\n        # create new cluster\n        cI,cJ = clusterInd[mI], clusterInd[mJ]\n\n        nbrElementsI = cI<=N ? 1 : clusters[cI-N][3]\n        nbrElementsJ = cJ<=N ? 1 : clusters[cJ-N][3]\n\n        dist = D[mI,mJ]\n        similarity && (dist*=-1) # change back from distance to similarity if needed\n        push!(clusters, (cI,cJ,nbrElementsI+nbrElementsJ,dist))\n\n        # update distance matrix and clusterInd\n        clusterInd[mJ] = 0\n        clusterInd[mI] = k+N\n\n\n        # construct new distances from D[mI,u], D[mJ,u]\n        for u=1:N\n            u==mI && continue\n            clusterInd[u]==0 && continue # includes u==mJ\n\n            mI2,u2 = minmax(mI,u) # upper triangular index\n            D[mI2,u2] = (D[mI2,u2]*nbrElementsI + D[minmax(mJ,u)...]*nbrElementsJ) / (nbrElementsI+nbrElementsJ) # TODO: change here for different linkage criteria\n        end\n\n    end\n\n    clusters\nend\n\n\n\nfunction samplesinclusters(clusters)\n    N = length(clusters)+1 # Since every merge makes two clusters into one, we can figure out the original number of samples this way.\n    samples = Vector{Vector{Int}}(length(clusters))\n    for (i,c) in enumerate(clusters)\n        samples[i] = vcat( c[1]>N ? samples[c[1]-N] : [c[1]], \n                           c[2]>N ? samples[c[2]-N] : [c[2]] )\n    end\n    samples\nend\n\n\n\n", "meta": {"hexsha": "e8cdc058824fcff5cb39f3b15355e28759fd0764", "size": 2729, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hierarchicalclustering.jl", "max_stars_repo_name": "rasmushenningsson/DISSEQT.jl", "max_stars_repo_head_hexsha": "a4780b08949f6e6dc17f33235a96dcc91dfca9c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-01T16:44:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T16:44:06.000Z", "max_issues_repo_path": "src/hierarchicalclustering.jl", "max_issues_repo_name": "rasmushenningsson/DISSEQT.jl", "max_issues_repo_head_hexsha": "a4780b08949f6e6dc17f33235a96dcc91dfca9c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-04-14T19:26:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T13:53:02.000Z", "max_forks_repo_path": "src/hierarchicalclustering.jl", "max_forks_repo_name": "rasmushenningsson/DISSEQT.jl", "max_forks_repo_head_hexsha": "a4780b08949f6e6dc17f33235a96dcc91dfca9c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-06T19:52:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-06T19:52:57.000Z", "avg_line_length": 31.0113636364, "max_line_length": 176, "alphanum_fraction": 0.607182118, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7546874440873705}}
{"text": "using Distributions\r\nusing PyPlot\r\nusing Roots\r\nusing JLD\r\n\r\nfunction tauchen86(μ::AbstractFloat,ρ::AbstractFloat,σ::AbstractFloat,n::Int64,λ::AbstractFloat)\r\n    #output is xgrid, xprob\r\n    # x_t+1 = μ + ρ x_t + σ e_{t+1}, e_t+1 ∼ N(0,1)\r\n    xhi = μ/(1-ρ) + λ*sqrt(σ^2/(1-ρ)^2)\r\n    xlo = μ/(1-ρ) - λ*sqrt(σ^2/(1-ρ)^2)\r\n    xgrid = zeros(n);\r\n    xscale =(xhi-xlo)/(n-1)\r\n\r\n    for i=1:n\r\n        xgrid[i] = xlo + xscale*(i-1)\r\n    end\r\n    m=zeros(n-1);\r\n    for i=1:n-1\r\n        m[i] = (xgrid[i]+xgrid[i+1])/2\r\n    end\r\n    xprob = zeros(n,n) # xprob[i,j] = Pr(x_t+1=xgrid[j]|x_t=xgrid[i])\r\n    for i=1:n # this is the state today\r\n        normie = Normal(μ+ρ*xgrid[i],σ)\r\n        normpdf(x) = pdf.(normie,x)\r\n        normcdf(x) = cdf.(normie,x)\r\n        for j=2:n-1\r\n            xprob[i,j] = normcdf(m[j]) - normcdf(m[j-1])\r\n        end\r\n        xprob[i,1] = normcdf(m[1])\r\n        xprob[i,n] = 1 - normcdf(m[n-1])\r\n    end\r\n    xprob = xprob ./ sum(xprob,2) # make sure the rows sum to 1\r\n    return ( xgrid,xprob, xscale )\r\nend\r\n\r\nfunction trunc_lognpdf(x, UP, LO, mu, sig)\r\n    # truncated log normal pdf\r\n    logn = LogNormal(mu, sig)\r\n    return (x-LO.>=-eps()) .* (x-UP.<=eps()).*pdf.(logn,x)/(cdf.(logn,UP)-cdf.(logn,LO))\r\nend\r\n\r\n\r\n# set parameters\r\n# PARAMETERS THAT AFFECT STEADY STATE:\r\n# note, we have log utility, so no CRRA parameter\r\n# and we have a quarterly model\r\nr = 0.01                        # 4 percent steady state annual real interest rate\r\nα = 0.3                         # capital share\r\nH = 1.0                         # aggregate hours worked\r\nδ  = 0.03                       # depreciation\r\nsH_over_sL = 1.2 / 0.8\r\npLH = 0.1                       # prob of going from low to high persistent skill\r\npHL = 0.1                      # prob of going fom\r\nγ = 0.#0.004                       # TFP growth\r\nGoverY = 0.01#18                        # steady state govt spending/gdp\r\ng = 1/(1-GoverY)                # steady state value of g_t, where G_t/Y_t = (1-(1/g_t))\r\nη = 0.                         # borrowing constraint (normalized by TFP)\r\nIn    = 0.443993816237631       # normalizing constant for the mollifier\r\nna = 300                         # cash on hand ditn grid points - set to smaller numbers for debugging\r\nns = 2# 5                         # skill distribution grid points\r\nzlo =  1. / 3.                      # second income shock to mollify actual income\r\nzhi = 2. - zlo                       # upper bound on this process\r\nBoverY = 0.26\r\n\r\n# AGGREGATE SHOCKS\r\nρB = 0.5 # persistence of discount factor shock\r\nρG = 0.5 # persistence of govt spending shock\r\nρZ = 0.5 # persistence of tfp growth shock\r\nρμ = 0.5 # persistence of investment shock\r\nρlamw = 0.5 # persistence of wage mkup shock\r\nρlamf = 0.5 # persistence of price mkup shock\r\nρmon = 0.5 # persistence of mon policy shock\r\n\r\n# OTHER PARAMETERS THAT AFFECT DYNAMICS\r\nspp  = 4.                        # second derivative of investment adjustment cost\r\nlamw = 1.5                       # wage markup\r\nϕh   = 2.                        # inverse frisch elasticity\r\nΦw   = 10.                       # rotemberg cost for wages\r\nlamf = 1.5                       # price markup\r\nΦp   = 1.                       # rotemberg cost for prices\r\nρR   = 0.75                      # persistence in taylor rule\r\nψπ   = 1.5                      # weight on inflation in taylor rule\r\nψy   = 0.5                       # weight on output growth in taylor rule\r\n\r\n# OPTIONS\r\nTRUNCATE      = true # default: true\r\nmindens       = 1e-8\r\nRESCALE_XWTS  = true # default: true\r\nSIMPLE_TAYLOR = false # default: false\r\n\r\n# solve for steady state of aggregate scalar variables\r\n# here I am assuming firms are subsidized in ss so that real mc = 1\r\nRk = r + δ                               # rental rate on capital\r\nω = (α^(α/(1-α)))*(1-α)*Rk^(-α/(1-α))    # real wage\r\nkl = (α/(1-α))*(ω/Rk)*ℯ^γ                # capital/labor ratio\r\nk = kl*H                                 # capital\r\nx = (1-(1-δ)*ℯ^(-γ))*k                   # investment\r\ny = (ℯ^(-α*γ))*(k^α)*H^(1-α)             # gdp\r\nbg = BoverY*y                            # govt debt\r\nT = Rk*k*ℯ^(-γ) - x - (1-(1/g))*y - ((1+r)*ℯ^(-γ)-1)*bg        # net transfer to hhs\r\n\r\nfunction persistent_skill_process(sH_over_sL::AbstractFloat, pLH::AbstractFloat, pHL::AbstractFloat, ns::Int)\r\n    f1 = [[1-pLH pLH];[pHL 1-pHL]] # f1[i,j] is prob of going from i to j\r\n    ss_skill_distr = [pHL/(pLH+pHL); pLH/(pLH+pHL)]\r\n    slo = 1. / (ss_skill_distr'*[1;sH_over_sL])\r\n    sgrid = slo*[1;sH_over_sL]\r\n    sscale = sgrid[2] - sgrid[1]\r\n    swts     = (sscale/ns)*ones(ns) #quadrature weights\r\n    f = f1 ./ repmat(swts',ns,1)\r\n    return (f, sgrid, swts)\r\nend\r\n(f, sgrid, swts) = persistent_skill_process(sH_over_sL, pLH, pHL, ns)\r\n\r\nfunction cash_grid(sgrid::AbstractArray, ω::AbstractFloat, H::AbstractFloat, r::AbstractFloat, η::AbstractFloat, γ::AbstractFloat,\r\n                   T::AbstractFloat, zlo::AbstractFloat, na::Int)\r\n    smin = minimum(sgrid)*zlo                           # lowest possible skill\r\n    alo_ss = ω*smin*H - (1+r)*η*ℯ^(-γ) + T + sgrid[1]*ω*H*0.05       # lowest possible cash on hand in ss\r\n\r\n    alo = alo_ss                    # lower bound on cash on hand - could be < alo_ss\r\n    ahi = max(alo*2,alo+5.)                      # upper bound on cash on hand\r\n    ascale = (ahi-alo)              # size of w grids\r\n\r\n    # make grids\r\n    agrid    = collect(linspace(alo,ahi,na)) #Evenly spaced grid\r\n    awts = (ascale/na)*ones(na)          #quadrature weights\r\n    return (agrid, awts)\r\nend\r\nsmin = minimum(sgrid)*zlo                           # lowest possible skill\r\nalo_ss = ω*smin*H - (1+r)*η*ℯ^(-γ) + T + sgrid[1]*ω*H*0.05       # lowest possible cash on hand in ss\r\n\r\nalo = alo_ss                    # lower bound on cash on hand - could be < alo_ss\r\nahi = max(alo*2,alo+5.)                      # upper bound on cash on hand\r\nascale = (ahi-alo)              # size of w grids\r\n\r\n(agrid, awts) = cash_grid(sgrid, ω, H, r, η, γ, T, zlo, na)\r\n\r\nfunction mollifier(z::AbstractFloat,ehi::AbstractFloat,elo::AbstractFloat)\r\n    # mollifier function\r\n    In = 0.443993816237631\r\n    if z<ehi && z>elo\r\n        temp = -1.0 + 2.0*(z-elo)/(ehi-elo)\r\n        out = (2.0/(ehi-elo))*exp(-1.0/(1.0-temp*temp))/In\r\n    else\r\n        out = 0.0\r\n    end\r\n\r\n    return out\r\nend\r\n\r\nzgrid = linspace(zlo,zhi,na)\r\nzwts = (zhi-zlo)/na\r\nsumz=0.\r\nfor i=1:na\r\n    sumz += mollifier(zgrid[i],zhi,zlo)*zwts\r\nend\r\n\r\n# experiment with a different q\r\nne = 100\r\nσe = 0.01\r\n(legrid, fe, sscale) = tauchen86(0.0,0.0,σe,ne,2.0)\r\negrid = exp.(legrid)\r\neprob = fe[1,:]\r\n\r\nfunction convoluted_q(x::AbstractFloat, zhi::AbstractFloat, zlo::AbstractFloat, ne::Int, egrid::Vector{Float64}, eprob::Vector{Float64})\r\n    sumne = 0.\r\n    for i=1:ne\r\n        sumne += mollifier(x - egrid[i], zhi, zlo)*eprob[i]\r\n    end\r\n    return sumne\r\nend\r\n\r\nqfunction(x) = mollifier(x, zhi, zlo)#/sumz # this ensures the mollifer sums to 1, at least on this particular grid\r\n#qfunction(x) = convoluted_q(x, zhi, zlo, ne, egrid, eprob)\r\n\r\nfunction dmollifier(x::AbstractFloat, ehi::AbstractFloat, elo::AbstractFloat)\r\n    In = 0.443993816237631\r\n    if x<ehi && x>elo\r\n        temp = (-1.0 + 2.0*(x-elo)/(ehi-elo))\r\n        out  = -(2*temp ./ ((1 - temp.^2).^2)) .* (2/(ehi-elo)).*mollifier(x, ehi, elo)\r\n    else\r\n        out = 0.0\r\n    end\r\n    return out\r\nend\r\n\r\n\r\nqp(z) = dmollifier(z,zhi,zlo)\r\n\r\nWin = 1 ./ (5. + 0.02*(repeat(agrid,ns)-5))\r\nWin = 2*ones(na*ns)/(ahi+alo)\r\naswts = kron(swts,awts)\r\n\r\nfunction sspolicy(na::Int, ns::Int, β::AbstractFloat, R::AbstractFloat,\r\n                     ω::AbstractFloat,\r\n                     H::AbstractFloat,\r\n                     η::AbstractFloat,\r\n                     T::AbstractFloat,\r\n                     γ::AbstractFloat,\r\n                     qfunction::Function,\r\n                     agrid::Vector{Float64},\r\n                     sgrid::Vector{Float64},\r\n                     aswts::Vector{Float64},\r\n                     Win::Vector{Float64},\r\n                     f::Array{Float64,2},damp::Float64 = 0.5, dist::Float64 = 1.,\r\n                         tol::Float64 = 1e-4, maxit::Int64 = 500)\r\n    n = na*ns\r\n    c  = zeros(n)      # consumption\r\n    bp = zeros(n)      # savings\r\n    counter = 1\r\n    Wout = copy(Win)\r\n    while dist>tol && counter<maxit # for debugging\r\n        # compute c(w) given guess for Win = β*R*E[u'(c_{t+1})]\r\n        for iss in 1:ns\r\n            for ia in 1:na\r\n                c[na*(iss-1)+ia] =  min(1/Win[na*(iss-1)+ia],agrid[ia]+η)\r\n            end\r\n        end\r\n        bp = repeat(agrid,ns) - c  # compute bp(w) given guess for Win\r\n        Wout = parameterized_expectations(na,ns,β,R,ω,H,η,T,γ,qfunction,agrid,sgrid,aswts,c,bp,f)\r\n        dist = maximum(abs.(Wout-Win))\r\n        #println(dist)\r\n        if mod(counter,25)==1\r\n            println(dist)\r\n            #plot(Wout)\r\n        end\r\n        Win = damp*Wout + (1.0-damp)*Win\r\n        counter += 1\r\n    end\r\n    if counter==maxit\r\n        warn(\"Euler iteration did not converge\")\r\n    end\r\n    tr = kolmogorov_fwd(na,ns,ω,H,η,T,γ,qfunction,agrid,sgrid,bp,f)\r\n    return (c,bp,Wout,tr)\r\nend\r\n\r\nfunction parameterized_expectations(na::Int,ns::Int, β::AbstractFloat, R::AbstractFloat, ω::AbstractFloat,\r\n                                    H::AbstractFloat, η::AbstractFloat, T::AbstractFloat, γ::AbstractFloat,\r\n                                    qfunction::Function,\r\n                                    agrid::Vector{Float64}, sgrid::Vector{Float64},\r\n                                    aswts::Vector{Float64}, c::Vector{Float64},\r\n                                    bp::Vector{Float64}, f::Array{Float64,2})\r\n    l_out = zeros(na*ns)\r\n    for iss=1:ns\r\n        for ia=1:na\r\n            sumn = 0.0\r\n            for isp=1:ns\r\n                for iap=1:na\r\n                    sumn += (aswts[na*(isp-1)+iap]/c[na*(isp-1)+iap])*qfunction((agrid[iap] - R*(ℯ^(-γ))*bp[na*(iss-1)+ia] - T)/(ω*H*sgrid[isp]))*f[iss,isp] ./ sgrid[isp]\r\n                end\r\n            end\r\n            l_out[na*(iss-1)+ia] = (β*R*(ℯ^(-γ))/ω*H)*sumn\r\n        end\r\n    end\r\n    return l_out\r\nend\r\n\r\nfunction kolmogorov_fwd(na::Int, ns::Int, ω::AbstractFloat,\r\n                        H::AbstractFloat, η::AbstractFloat, T::AbstractFloat, γ::AbstractFloat,\r\n                        qfunction::Function,agrid::Vector{Float64},\r\n                        sgrid::Vector{Float64}, bp::Vector{Float64},f::Array{Float64,2})\r\n    tr = zeros(na*ns,na*ns)\r\n    for iss=1:ns\r\n        for ia=1:na\r\n            for isp=1:ns\r\n                for iap=1:na\r\n                    tr[na*(isp-1)+iap,na*(iss-1)+ia] = qfunction((agrid[iap] - R*(ℯ^(-γ))*bp[na*(iss-1)+ia] - T)/(ω*H*sgrid[isp]))*f[iss,isp] ./ (ω*H*sgrid[isp])\r\n                end\r\n            end\r\n        end\r\n    end\r\n    return tr\r\nend\r\n\r\n# just to test if code returns\r\nR = 1+r\r\nβlo = 0.5*(ℯ^γ)/R # excess should be -ve\r\nβhi = (ℯ^γ)/R # excess should be +ve\r\n\r\nβ = (βlo+βhi)/2.0\r\n\r\nfunction findss(na::Int, ns::Int, βlo::AbstractFloat,\r\n                βhi::AbstractFloat, R::AbstractFloat,\r\n                     ω::AbstractFloat,\r\n                     H::AbstractFloat,\r\n                     η::AbstractFloat,\r\n                     T::AbstractFloat,\r\n                     γ::AbstractFloat,\r\n                     bg::AbstractFloat,\r\n                     qfunction::Function,\r\n                     agrid::Vector{Float64},\r\n                     sgrid::Vector{Float64},\r\n                     aswts::Vector{Float64},\r\n                     Win::Vector{Float64},\r\n                     f::Array{Float64,2},\r\n                     excess::AbstractFloat = 5000., tol::AbstractFloat = 1e-4,\r\n                     maxit::Int64 = 20)\r\n    counter=1\r\n    n       = ns*na\r\n    c = zeros(n)\r\n    bp = zeros(n)\r\n    KF = zeros(n,n)\r\n    m = zeros(n)\r\n    report = zeros(maxit,2)\r\n    #Win0=copy(Win)\r\n    while abs(excess)>tol && counter<maxit # clearing markets\r\n        β = (βlo+βhi)/2.0\r\n        Win_guess = ones(n) # or Win\r\n        (c, bp, Win, KF) = sspolicy(na, ns, β, R, ω, H, η, T, γ, qfunction, agrid, sgrid,\r\n                                       aswts, Win_guess, f)\r\n\r\n        LPMKF=aswts[1]*KF\r\n        # find eigenvalue closest to 1\r\n        (D,V) = eig(LPMKF)\r\n        order_D = sortperm(abs.(D), rev = true)\r\n        V = V[:,order_D]\r\n        D = D[order_D]\r\n        if abs(D[1]-1)>2e-1 # that's the tolerance we are allowing\r\n            warn(\"your eigenvalue is too far from 1, something is wrong\")\r\n        end\r\n        m = real(V[:,1]) #Pick the eigen vecor associated with the largest eigenvalue and moving it back to values\r\n        m = m/(aswts'*m) #Scale of eigenvectors not determinate: rescale to integrate to exactly 1\r\n        excess = (aswts'*(m .* bp))[1] - bg  #compute excess supply of savings, which is a fn of w\r\n                # bisection\r\n        println([βlo β βhi])\r\n        println(excess)\r\n        report[counter,1] = β # save the history of guesses and excess supply so we can check it's upward-sloping and monotonic\r\n        report[counter,2] = excess\r\n        if excess>0\r\n            βhi=β\r\n        elseif excess<0\r\n            βlo = β\r\n        end\r\n        counter += 1\r\n    end\r\n    return (Win, c, m, β, report)\r\nend\r\n\r\ntic()\r\n(ell, c, m, β, report) = findss(na, ns, βlo, βhi, R, ω, H, η, T, γ, bg, qfunction, agrid, sgrid,aswts, Win, f)\r\ntoc()\r\n", "meta": {"hexsha": "67af2c35982f2cb50d7d98ce2bc4d040056a59f2", "size": 13359, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/heterogeneous/het_dsge/GovDebt.jl", "max_stars_repo_name": "FRBNY-DSGE/DSGE.jl", "max_stars_repo_head_hexsha": "45c26624ec225d6d355219cde71638f6171694ad", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 822, "max_stars_repo_stars_event_min_datetime": "2015-12-03T13:42:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T16:12:55.000Z", "max_issues_repo_path": "src/models/heterogeneous/het_dsge/GovDebt.jl", "max_issues_repo_name": "FRBNY-DSGE/DSGE.jl", "max_issues_repo_head_hexsha": "45c26624ec225d6d355219cde71638f6171694ad", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2016-06-20T14:42:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T16:14:10.000Z", "max_forks_repo_path": "src/models/heterogeneous/het_dsge/GovDebt.jl", "max_forks_repo_name": "FRBNY-DSGE/DSGE.jl", "max_forks_repo_head_hexsha": "45c26624ec225d6d355219cde71638f6171694ad", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 226, "max_forks_repo_forks_event_min_datetime": "2015-12-03T16:53:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T09:52:56.000Z", "avg_line_length": 39.1759530792, "max_line_length": 171, "alphanum_fraction": 0.5195748185, "num_tokens": 4210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7546874388619994}}
{"text": "# p18.jl - Chebyshev differentiation via FFT (compare p11.jl)\n\nxx = -1:.01:1; ff = @. exp(xx)*sin(5*xx); clf();\nfor N = [10 20]\n    x = cheb(N)[2]; f = @. exp(x)*sin(5*x);\n    axes([.15, .66-.4*(N==20), .31, .28]);\n    plot(x,f,\"k.\",markersize=6); grid(true);\n    plot(xx,ff);\n    title(\"f(x), N=$N\");\n    error = chebfft(f) - @. exp(x)*(sin(5*x)+5*cos(5*x));\n    axes([.55, .66-.4*(N==20), .31, .28]);\n    plot(x,error,\".-\",markersize=10); grid(true);\n    title(\"error in f'(x),  N=$N\");\nend\n", "meta": {"hexsha": "910b351f595deec3a07aaa37d3da9944b3e51206", "size": 493, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p18.jl", "max_stars_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_stars_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-06T19:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T15:07:11.000Z", "max_issues_repo_path": "src/scripts/p18.jl", "max_issues_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_issues_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/p18.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8666666667, "max_line_length": 61, "alphanum_fraction": 0.4989858012, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474233166328, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.7546777411941091}}
{"text": "using Roots, EngEconomics\n\n# Given\nMARR = 0.06\nA_Init = -1000\nA_Year = 1500\nB_Init = -2000\nB_Year = 2800\n\n# Find the better option using Incremental ROR\nΔInit = B_Init - A_Init\nΔYear = B_Year - A_Year\nΔIRR(x) = ΔInit + presentWorthFactor(x, 1) * ΔYear\nΔIRR_ans = find_zero(ΔIRR, 0.05)\n\n# Because ΔIRR_ans > MARR, the second alternative, B, is better\nprintln(\"Choose Alt. 2\")\n", "meta": {"hexsha": "6cb99eeae0f399fe147e1da0f2a92963426e9b28", "size": 375, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/examples/irr_1.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/examples/irr_1.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/examples/irr_1.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8333333333, "max_line_length": 63, "alphanum_fraction": 0.72, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7546731784991828}}
{"text": "# -----------------------------------------------------------\n#\n# Evaluating the 1D Galerkin Basis functions\n#\n# -----------------------------------------------------------\n\nconst K_max = 10\n\n# Efficiency criticality: HIGH\n# Central to the efficiency of the package\n\n# Performing fastmath on an array of coefficients\n# of x^k and |x|^k, giving the value at a specified point\n# supported on [-1, 1]\n@fastmath function array2poly(v::AbstractArray{T, 1}, x::Real) where T <: Real\n    if abs(x)>1\n        return zero(T)\n    end\n    n = length(v)\n    k = div(n,2)\n    s = zero(T)\n    @inbounds for i in k:-1:1\n        # Using Horner's method\n        s *= x\n        s += v[i] + flipsign(v[i+k], x)\n    end\n    return s\nend\n\nfunction array2poly(v::AbstractArray{T, 1}) where T <: Real\n    return (x-> array2poly(v,x))\nend\n\n#precompute Legendre\nleg_coeffs = legendre(K_max)\n\n# Legendre polynomial supported on [-1, 1]\nfunction LegendreP(k, x)\n    k<=K_max || throw(DomainError())\n    return array2poly(leg_coeffs[k+1], x)\nend\n\nfunction LegendreP(k)\n    k<=K_max || throw(DomainError())\n    return array2poly(leg_coeffs[k+1])\nend\n\n# precomputing the DG functions\n# (Thanks to Alex Arslan for this.)\n# Meaning: [baisis size k][coefficient, mode]\n# Lengths: [K_max][2*k, k]\nconst dg_coeffs = Vector{Matrix{Float64}}(undef, K_max)\n\nfor k in 1:K_max\n    Q = dg_basis(k)\n    @assert length(Q) == k\n    @assert all(length(Q[mode]) == 2*k for mode in 1:k)\n    dg_coeffs[k] = Matrix{Float64}(undef, 2*k, k)\n    for mode in 1:k\n        dg_coeffs[k][:,mode] = Q[mode][:]\n    end\nend\n\n# This is the dg basis function corresponding a given mode\n# supported on [-1, 1]\nfunction h(k, mode, x)\n    mode<=k || throw(DomainError())\n    return array2poly((@view dg_coeffs[k][:,mode]), x)\nend\n\nfunction h(k, mode)\n    mode<=k || throw(DomainError())\n    return array2poly((@view dg_coeffs[k][:,mode]))\nend\n\n# ----------------------------------------------\n#\n# Methods relating to the 1D Position Basis:\n#\n# ----------------------------------------------\n\n# Legendre polynomial on [0, 1]\nfunction leg(mode::Int, x::T) where T <: Real\n    return sqrt(2.0)*LegendreP(mode-1, 2*x-1)\nend\n\n# level >= 1\n# cell in 1:1<<level\n# mode in 1:k\n# Legendre polynomial on [(cell-1)*h, cell*h] with h = 1/(1<<level)\nfunction basis(level::Int, cell::Int, mode::Int, x::T) where T <: Real\n    return leg(mode, (1<<level)*x - (cell-1)) * (2.0)^(level/2)\nend\n\nfunction basis(level::Int, cell::Int, mode::Int)\n    return x->basis(level, cell, mode, x)\nend\n\n# Perform numerical integration to get position basis coeffs\n#\n# Never used except if user demands to evolve wave equation\n# using only the position basis, never going through heir\nfunction pos_vcoeffs_DG(k::Int, level::Int, f::Function;\n                        rtol = REL_TOL, atol = ABS_TOL, maxevals = MAX_EVALS)\n    vcoeffs = Array{Float64}(undef, (1<<level)*(k))\n    i = 1\n    for cell in 1:(1<<level)\n        for mode in 1:k\n            fcn            = x->(basis(level, cell, mode,x)*f(x))\n            left_bound  = (cell-1)/(1<<level)\n            right_bound = (cell)/(1<<level)\n            vcoeffs[i]  = hquadrature(fcn, left_bound, right_bound; atol=atol)[1]\n            i += 1\n        end\n    end\n    return vcoeffs\nend\n\n# ----------------------------------------------\n# Building the hier2pos matrix:\n# ----------------------------------------------\n\n# Given an array of the type above, of coefficients\n# for both both x^k and |x|^k, then given a choice of\n# side (right vs. left) this becomes just a pure\n# polynomial array of half the length\nfunction convert_polyarray(v::AbstractArray{T, 1}, side = \"left\") where T <: Real\n    n = Int(length(v)//2)\n    if side == \"left\"\n        return [v[i]-v[n+i] for i in 1:n]\n    elseif side == \"right\"\n        [v[i]+v[n+i] for i in 1:n]\n    else throw(ArgumentError())\n    end\nend\n\n# Gives the polynomial array corresponding to p(x/c)\nfunction scale_polyarray(v::AbstractArray{T, 1}, c::Real) where T <: Real\n    n = length(v)\n    return [v[i] * (1//c^(i-1)) for i in 1:n]\nend\n\n# Gives the polynomial array corresponding to p(x-a)\nfunction shift_polyarray(v::AbstractArray{T, 1}, a::Real) where T <: Real\n    n = length(v)\n    v_new = zeros(v)\n    for i::Int in 1:n\n        for j::Int in 1:i\n            v_new[j] += v[i] * (-a)^(i-j) * binomial(i-1, j-1)\n        end\n    end\n    return v_new\nend\n\n# Performs symbolic integration of the polynomials\n# represented by v and w on the interval [a, b]\nfunction integrate_polyarray(v::AbstractArray{T, 1}, w::AbstractArray{T, 1}; a::Real = 0, b::Real = 1) where T <: Real\n    ans = zero(T)\n    for i::Int in 1:length(v)\n        for j::Int in 1:length(w)\n            ans += v[i] * w[j] * ((b^(i+j-1)-a^(i+j-1))//(i+j-1))\n        end\n    end\n    return ans\nend\n\n# With a bit of case work, we can do an explicit\n# symbolic integration of the elements in the\n# hierarchical basis against the legendre polynomials\n# defining the position basis:\nfunction hier2pos(k::Int, max_level::Int, level::Int, cell::Int, mode::Int)\n\n    ans = Real[]\n\n    # Compute the support and discontinuity\n    # of the hierarchical basis element\n    left_point  = (cell-1)//(1<<max(0, level-1))\n    mid_point   = (cell- 1//2)//(1<<max(0, level-1))\n    right_point = cell//(1<<max(0, level-1))\n\n    # Level 0 of the hierarchical basis is a continous\n    # Legendre polynomial\n    if level == 0\n        vl = vr = sqrt(2)*shift_polyarray(\n                                scale_polyarray(leg_coeffs[mode][1:k],\n                                                1//2),\n                                            1//2)\n\n    # The higher DG levels are given by two polynomials\n    # defined on neighboring (right & left) intervals of size h/2,\n    # which would need to be integrated against individually\n    else\n        h = 1//(1<<max(0, level-1))\n        vl = shift_polyarray(\n                scale_polyarray(\n                    convert_polyarray((@view dg_coeffs[k][:,mode]), \"left\"),\n                                1//2),\n                            1//2)\n        vl = shift_polyarray(scale_polyarray(vl, h), (cell-1)*h)*sqrt(1<<(level))\n\n        vr = shift_polyarray(\n                scale_polyarray(\n                    convert_polyarray((@view dg_coeffs[k][:,mode]), \"right\"),\n                                 1//2),\n                            1//2)\n        vr = shift_polyarray(scale_polyarray(vr, h), (cell-1)*h)*sqrt(1<<(level))\n    end\n\n    h = 1//(1<<max_level)\n    for i in 1:1<<max_level\n        for p in 1:k\n            # Check if our hier function is supported on this interval\n            if (i-1)*h < left_point || i*h > right_point\n                push!(ans, 0)\n                continue\n            end\n\n            # Obtain the polynomial array for the position basis function\n            unit_leg = shift_polyarray(\n                            scale_polyarray(leg_coeffs[p][1:k], 1//2), 1//2)\n            pos_element = shift_polyarray(\n                                scale_polyarray(unit_leg, h), (i-1)*h)\n            pos_element *= sqrt(1<<(max_level+1)) # (2.0)^((max_level+1)/2)\n\n            # Perform symbolic integration depending on which\n            # interval the position basis function overlaps with the\n            # DG basis element\n            if (i-1)*h < mid_point\n                val = integrate_polyarray(vl, pos_element; a=(i-1)*h, b=i*h)\n            else\n                val = integrate_polyarray(vr, pos_element; a=(i-1)*h, b=i*h)\n            end\n            push!(ans, val)\n        end\n    end\n    return ans\nend\n\n\n# Construct the change of basis matrix from hierarchical\n# to position basis\nfunction hier2pos(k::Int, max_level::Int; atol=ABS_TOL)\n    j = 1\n    I = Int[]\n    J = Int[]\n    V = Float64[]\n    for level in 0:max_level\n        for cell in 1:(1<<max(0, level-1))\n            for mode in 1:k\n                ans = pos_vcoeffs_DG(k, max_level, v(k, level, cell, mode))\n                for i in 1:length(ans)\n                    if abs(ans[i]) > atol\n                        push!(I, i)\n                        push!(J, j)\n                        push!(V, ans[i])\n                    end\n                end\n                j += 1\n            end\n        end\n    end\n    return sparse(I, J, V, k * (1<<max_level), k * (1<<max_level), +)\nend\n\nfunction pos2hier(k::Int, max_level::Int; atol=ABS_TOL)\n    return hier2pos(k, max_level; atol=atol)'\nend\n", "meta": {"hexsha": "9d3ad9f80b54a7a3910d72fffcd1defc3c0c57ba", "size": 8374, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/1d_dg_functions.jl", "max_stars_repo_name": "AlexAtanasov14/GalerkinSparseGrids.jl", "max_stars_repo_head_hexsha": "89ee55e078c040760a07f547b626e947fb0d21c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2016-07-26T19:16:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T14:27:38.000Z", "max_issues_repo_path": "src/1d_dg_functions.jl", "max_issues_repo_name": "mkosiol/GalerkinSparseGrids.jl", "max_issues_repo_head_hexsha": "b89cc619126285dcaef1f749115ddbe4d43dd3ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-05-20T19:30:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-07T23:59:29.000Z", "max_forks_repo_path": "src/1d_dg_functions.jl", "max_forks_repo_name": "mkosiol/GalerkinSparseGrids.jl", "max_forks_repo_head_hexsha": "b89cc619126285dcaef1f749115ddbe4d43dd3ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2016-07-26T19:16:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T14:27:42.000Z", "avg_line_length": 31.2462686567, "max_line_length": 118, "alphanum_fraction": 0.549438739, "num_tokens": 2370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.8128673155708976, "lm_q1q2_score": 0.7546731726802207}}
{"text": "# # Matrix operators\n\n#md # ```@meta\n#md # CurrentModule = ImmersedLayers\n#md # ```\n\n#=\nMany solutions of partial differential equations with immersed layers, particularly Poisson problems,\nlead to saddle-point problems, in which the Schur complement operator is a matrix\ncomposed from some of the surface-grid operators discussed in [Surface-grid operations](@ref).\nThe package provides some convenience tools for constructing these matrices. By\ntheir nature, the construction of these matrices is slow, since each column\ninvolves the application of the same set of operations. However, the point\nof this construction is to do it once and store it for repeated application.\n=#\n\n#=\nOne common saddle point system is\n\n$$A = \\begin{bmatrix} L & R \\\\ R^T & 0 \\end{bmatrix}$$\n\nwhere $L$ is the discrete Laplacian and $R$ and $R^T$ are the regularization\nand interpolation operators ([`regularize!`](@ref) and [`interpolate!`](@ref)),\nrespectively. This system arises in the solution of the Poisson equation\nwith Dirichlet boundary conditions on the immersed surface. The Schur complement of this is\n$S = - R^T L^{-1} R$. This matrix can be obtained using the function [`create_RTLinvR`](@ref).\n=#\n\n\n#=\nAnother common saddle point system is\n\n$$A = \\begin{bmatrix} L & D_s \\\\ G_s & R_n^T R_n \\end{bmatrix}$$\n\nwhere $D_s$ and $G_s$ are the surface divergence and gradient operators\n([`surface_divergence!`](@ref) and [`surface_grad!`](@ref)),\nrespectively, and $R_n$ and $R_n^T$ are [`regularize_normal!`](@ref) and [`normal_interpolate!`](@ref).\nThis system arises in the solution of the Poisson equation\nwith Neumann boundary conditions on the immersed surface. The Schur complement of this is\n$S = R_n^T R_n - G_s L^{-1} D_s$. Each of the matrices in this are individually\nprovided by the package, by the functions [`create_nRTRn`](@ref) and [`create_GLinvD`](@ref),\nrespectively. However, it is useful to know that the sum of these two\nmatrices is exactly the matrix $-C_s L^{-1}C_s^T$, where $C_s$ and $C_s^T$ are\nsurface curl operators [`surface_curl!`](@ref). This complete matrix is provided by\n[`create_CLinvCT`](@ref).\n=#\n\n#=\nAnother helpful matrix operator is the surface filter, given by\n\n$$\\tilde{R}^T R$$\n\nwhere $\\tilde{R}^T$ is a modified form of the interpolation operator,\ndesigned to return the regularized field to the surface points while\nmaintaining the integral value of the original field [^1]. We can\nobtain this matrix with [`create_surface_filter`](@ref).\n=#\n\n#md # ## Matrix construction functions\n\n#md # ```@docs\n#md # create_RTLinvR\n#md # create_CLinvCT\n#md # create_CL2invCT\n#md # create_GLinvD\n#md # create_GLinvD_cross\n#md # create_nRTRn\n#md # create_surface_filter\n#md # ```\n\n#md # [^1]: Goza, A., et al., (2016) \"Accurate computation of surface stresses and forces with immersed boundary methods,\" J. Comput. Phys., 321, 860--873.\n", "meta": {"hexsha": "caabe0ad3b5a4254ef4eb3c8b6309d6da3e055bf", "size": 2858, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/literate/matrices.jl", "max_stars_repo_name": "YvonneThoy/ImmersedLayers.jl", "max_stars_repo_head_hexsha": "e9d69f5e7d105fe7d1dcade64a4c77faa31b2cbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-02T05:17:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T05:17:03.000Z", "max_issues_repo_path": "test/literate/matrices.jl", "max_issues_repo_name": "YvonneThoy/ImmersedLayers.jl", "max_issues_repo_head_hexsha": "e9d69f5e7d105fe7d1dcade64a4c77faa31b2cbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-01-05T01:07:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T17:49:38.000Z", "max_forks_repo_path": "test/literate/matrices.jl", "max_forks_repo_name": "YvonneThoy/ImmersedLayers.jl", "max_forks_repo_head_hexsha": "e9d69f5e7d105fe7d1dcade64a4c77faa31b2cbc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-10T21:58:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T21:58:08.000Z", "avg_line_length": 39.6944444444, "max_line_length": 155, "alphanum_fraction": 0.7386284115, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979619, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7546731700815754}}
{"text": "\"\"\" Computing with permutations: the computer algebra of the symmetric group.\n\"\"\"\nmodule Permutations\nexport decompose_permutation_by_bubble_sort!,\n  decompose_permutation_by_insertion_sort!, permutation_to_expr\n\nusing Compat\nusing ...Syntax\nusing ...Theories: dom, codom, compose, id, otimes, munit, braid\n\n# Decomposition\n###############\n\n\"\"\" Decompose permutation into adjacent transpositions using bubble sort.\n\nAn *adjacent transposition*, also known as a *simple transposition*, is a\ntransposition of form (i i+1), represented here as simply the number i.\n\nThis algorithm appears as Algorithm 2.7 in the PhD thesis of Jonathan Huang,\n\"Probabilistic reasonsing and learning on permutations: Exploiting structural\ndecompositions of the symmetric group\". As Huang notes, the algorithm is\nvery similar to the well-known bubble sort. It has quadratic complexity.\n\nSee also: `decompose_permutation_by_insertion_sort!`\n\"\"\"\nfunction decompose_permutation_by_bubble_sort!(σ::Vector{Int})::Vector{Int}\n  n = length(σ)\n  result = Int[]\n  for i in 1:n-1\n    for j = n-1:-1:i\n      if σ[j+1] < σ[j]\n        σ[j], σ[j+1] = σ[j+1], σ[j]\n        push!(result, j)\n      end\n    end\n  end\n  result\nend\n\n\"\"\" Decompose permutation into adjacent transpositions using insertion sort.\n\nAn *adjacent transposition*, also known as a *simple transposition*, is a\ntransposition of form (i i+1), represented here as simply the number i.\n\nBubble sort and insertion sort are, in a sense, dual algorithms (Knuth, TAOCP,\nVol 3: Searching and Sort, Sec 5.3.4: Networks for sorting, Figures 45 & 46). A\nminimal example on which they give different decompositions is the permutation:\n\n  [1,2,3] ↦ [3,2,1]\n\nSee also: `decompose_permutation_by_bubble_sort!`\n\"\"\"\nfunction decompose_permutation_by_insertion_sort!(σ::Vector{Int})::Vector{Int}\n  n = length(σ)\n  result = Int[]\n  for i in 2:n\n    for j in i:-1:2\n      if σ[j-1] > σ[j]\n        σ[j-1], σ[j] = σ[j], σ[j-1]\n        push!(result, j-1)\n      end\n    end\n  end\n  result\nend\n\n# Conversion to expression\n##########################\n\n\"\"\" Convert a typed permutation into a morphism expression.\n\nWarning: The morphism expression is not simplified.\n\"\"\"\nfunction permutation_to_expr(σ::Vector{Int}, xs::Vector; sort::Symbol=:insertion)\n  permutation_to_expr!(copy(σ), copy(xs); sort=sort)\nend\nfunction permutation_to_expr!(σ::Vector{Int}, xs::Vector; sort::Symbol=:insertion)\n  n = length(σ)\n  @assert length(xs) == n\n  \n  transpositions = if sort == :bubble\n    decompose_permutation_by_bubble_sort!(σ)\n  elseif sort == :insertion\n    decompose_permutation_by_insertion_sort!(σ)\n  else\n    error(\"Sorting algorithm not supported: $sort\")\n  end\n  if isempty(transpositions)\n    return id(otimes(xs))\n  end\n  \n  layers = map(transpositions) do τ\n    layer = [\n      τ > 1 ? id(otimes(xs[1:τ-1])) : nothing,\n      braid(xs[τ], xs[τ+1]),\n      τ+1 < n ? id(otimes(xs[τ+2:n])) : nothing,\n    ]\n    xs[τ], xs[τ+1] = xs[τ+1], xs[τ]\n    foldl(otimes, filter(!isnothing, layer))\n  end\n  foldl(compose, layers)\nend\n\nend\n", "meta": {"hexsha": "d86c6f3017ccbb71a7cbe426731516c7ac3bb323", "size": 3031, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/categorical_algebra/Permutations.jl", "max_stars_repo_name": "philzook58/Catlab.jl", "max_stars_repo_head_hexsha": "bb96fa51914239ef4a1548c172d87b849c4064c1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/categorical_algebra/Permutations.jl", "max_issues_repo_name": "philzook58/Catlab.jl", "max_issues_repo_head_hexsha": "bb96fa51914239ef4a1548c172d87b849c4064c1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-24T19:06:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-24T19:06:37.000Z", "max_forks_repo_path": "src/categorical_algebra/Permutations.jl", "max_forks_repo_name": "bosonbaas/Catlab.jl", "max_forks_repo_head_hexsha": "f2973b7fecadc37d1612ce20e3dae1e361cd00e1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8666666667, "max_line_length": 82, "alphanum_fraction": 0.6928406467, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7546731673555016}}
{"text": "# I took this from the ConjugatePriors package\n\n# Used \"Conjugate Bayesian analysis of the Gaussian distribution\" by Murphy as\n# a reference.  Note that there were some typos in that document so the code\n# here may not correspond exactly.\n\nstruct NormalInverseGamma{T<:Real} <: ContinuousUnivariateDistribution\n    mu::T\n    v0::T     # scales variance of Normal\n    shape::T\n    scale::T\n\n    function NormalInverseGamma{T}(mu::T, v0::T, sh::T, r::T) where T<:Real\n    \tv0 > zero(v0) && sh > zero(sh) && r > zero(r) || error(\"Both shape and scale must be positive\")\n    \tnew{T}(T(mu), T(v0), T(sh), T(r))\n    end\nend\n\nfunction NormalInverseGamma(mu::Real, v0::Real, sh::Real, r::Real)\n    T = promote_type(typeof(mu), typeof(v0), typeof(sh), typeof(r))\n    return NormalInverseGamma{T}(T(mu),T(v0),T(sh),T(r))\nend\n\nmu(d::NormalInverseGamma) = d.mu\nv0(d::NormalInverseGamma) = d.v0\nshape(d::NormalInverseGamma) = d.shape\nscale(d::NormalInverseGamma) = d.scale\nrate(d::NormalInverseGamma) = 1. / d.scale\n\ninsupport(::Type{NormalInverseGamma}, x::T, sig2::T) where T<:Real =\n    isfinite(x) && zero(sig2) <= sig2 < Inf\n\n# Probably should guard agains dividing by and taking the log of 0.\n\nfunction pdf(d::NormalInverseGamma, x::T, sig2::T) where T<:Real\n    Zinv = d.scale.^d.shape / gamma(d.shape) / sqrt(d.v0 * 2.0*pi)\n    return Zinv * 1.0/(sqrt(sig2)*sig2.^(d.shape+1.0)) * exp(-d.scale/sig2 - 0.5/(sig2*d.v0)*(x-d.mu).^2)\nend\n\nfunction logpdf(d::NormalInverseGamma, x::T, sig2::T) where T<:Real\n    lZinv = d.shape*log(d.scale) - lgamma(d.shape) - 0.5*(log(d.v0) + log(2pi))\n    return lZinv - 0.5*log(sig2) - (d.shape+1.)*log(sig2) - d.scale/sig2 - 0.5/(sig2*d.v0)*(x-d.mu).^2\nend\n\nfunction rand(d::NormalInverseGamma)\n    # Guard against invalid precisions\n    sig2 = rand(InverseGamma(d.shape, d.scale))\n    if sig2 <= zero(Float64)\n        sig2 = eps(Float64)\n    end\n    mu = rand(Normal(d.mu, sqrt(sig2*d.v0)))\n    return mu, sig2\nend\n", "meta": {"hexsha": "b850b7f70e5784bdbd3c18c38d5f6a025fee7058", "size": 1944, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/normalinversegamma.jl", "max_stars_repo_name": "igutierrezm/ANOVADDPTest.jl", "max_stars_repo_head_hexsha": "4353faffcae3b69d10e90f6e23c8e69df230b16b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/normalinversegamma.jl", "max_issues_repo_name": "igutierrezm/ANOVADDPTest.jl", "max_issues_repo_head_hexsha": "4353faffcae3b69d10e90f6e23c8e69df230b16b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-08T18:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T19:36:26.000Z", "max_forks_repo_path": "src/normalinversegamma.jl", "max_forks_repo_name": "igutierrezm/ANOVADDPTest.jl", "max_forks_repo_head_hexsha": "4353faffcae3b69d10e90f6e23c8e69df230b16b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0, "max_line_length": 105, "alphanum_fraction": 0.6594650206, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7546731668612583}}
{"text": "#=\nP26 (**) Generate the combinations of K distinct objects chosen from the N elements of a list\nIn how many ways can a committee of 3 be chosen from a group of 12 people? We all know that there are C(12,3) = 220 possibilities (C(N,K) denotes the well-known binomial coefficients). For pure mathematicians, this result may be great. But we want to really generate all the possibilities in a list.\n\nExample:\n* (combination 3 '(a b c d e f))\n((A B C) (A B D) (A B E) ... )\n=#\n\n\nfunction filter_colls(colls, len)\n    filter(coll -> length(coll) == len, colls)\nend\n\nfunction append_indices(indices, last_index)\n    next_index = indices[end] + 1\n    map(i -> vcat(indices, i), next_index:last_index)\nend\n\nfunction combination(n, coll)\n    function _combination(index_list, count)\n        if count == n\n            index_list\n        else\n            new_index_list = map(indices -> append_indices(indices, length(coll)), index_list)\n            flattened = reduce(vcat, new_index_list)\n            _combination(filter_colls(flattened, count + 1), count + 1)\n        end\n    end\n\n    index_list = _combination(map(idx -> [idx], 1:length(coll)), 1)\n    map(indices -> map(i -> coll[i], indices), index_list)\nend\n\ncoll = [:a, :b, :c, :d, :e, :f]\ncombos = combination(3, coll)\n@assert length(combos) == 20\n@assert combos[1] == [:a, :b, :c]\n@assert combos[2] == [:a, :b, :d]\n@assert combos[3] == [:a, :b, :e]\n@assert combos[4] == [:a, :b, :f]\n@assert combos[5] == [:a, :c, :d]\n@assert combos[6] == [:a, :c, :e]\n@assert combos[7] == [:a, :c, :f]\n@assert combos[8] == [:a, :d, :e]\n@assert combos[9] == [:a, :d, :f]\n@assert combos[10] == [:a, :e, :f]\n@assert combos[11] == [:b, :c, :d]\n@assert combos[12] == [:b, :c, :e]\n@assert combos[13] == [:b, :c, :f]\n@assert combos[14] == [:b, :d, :e]\n@assert combos[15] == [:b, :d, :f]\n@assert combos[16] == [:b, :e, :f]\n@assert combos[17] == [:c, :d, :e]\n@assert combos[18] == [:c, :d, :f]\n@assert combos[19] == [:c, :e, :f]\n@assert combos[20] == [:d, :e, :f]\n\nprintln(\"Tests passed: JL-26.jl\")\n", "meta": {"hexsha": "b68eb812d03363529cc2349698b5aa64f6e3b463", "size": 2023, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JL-26.jl", "max_stars_repo_name": "microamp/jl-99", "max_stars_repo_head_hexsha": "5d49a7e1617394e6cbc06f1a94fe6230b3025d73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JL-26.jl", "max_issues_repo_name": "microamp/jl-99", "max_issues_repo_head_hexsha": "5d49a7e1617394e6cbc06f1a94fe6230b3025d73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JL-26.jl", "max_forks_repo_name": "microamp/jl-99", "max_forks_repo_head_hexsha": "5d49a7e1617394e6cbc06f1a94fe6230b3025d73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7166666667, "max_line_length": 299, "alphanum_fraction": 0.6010874938, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.8740772269642949, "lm_q1q2_score": 0.7546709350127638}}
{"text": "function fresnelS0(x::T) where {T}\n    x2 = x*x\n    x4 = x2*x2\n    n = @evalpoly(x4, T(3.18016297876567817986E11),\n                      -T(4.42979518059697779103E10),\n                      T(2.54890880573376359104E9),\n                      -T(6.29741486205862506537E7),\n                      T(7.08840045257738576863E5),\n                      -T(2.99181919401019853726E3))\n    d = @evalpoly(x4, T(6.07366389490084639049E11),\n                      T(2.24411795645340920940E10),\n                      T(4.19320245898111231129E8),\n                      T(5.17343888770096400730E6),\n                      T(4.55847810806532581675E4),\n                      T(2.81376268889994315696E2),\n                      T(1))\n    x*x2*n/d\nend\nfunction fresnelC0(x::T) where {T}\n    x2 = x*x\n    x4 = x2*x2\n    n = @evalpoly(x4, T(9.99999999999999998822E-1),\n                      -T(2.05525900955013891793E-1),\n                      T(1.88843319396703850064E-2),\n                      -T(6.45191435683965050962E-4),\n                      T(9.50428062829859605134E-6),\n                      -T(4.98843114573573548651E-8))\n    d = @evalpoly(x4, T(1.00000000000000000118E0),\n                      T(4.12142090722199792936E-2),\n                      T(8.68029542941784300606E-4),\n                      T(1.22262789024179030997E-5),\n                      T(1.25001862479598821474E-7),\n                      T(9.15439215774657478799E-10),\n                      T(3.99982968972495980367E-12))\n    x*n/d\nend\nfresnelS(x::T) where {T} = x < T(1.6) ? fresnelS0(x) : imag((1 + im)*erf(x*sqrt(T(pi))*(1 - im)/2)/2)\nfresnelC(x::T) where {T} = x < T(1.6) ? fresnelC0(x) : real((1 + im)*erf(x*sqrt(T(pi))*(1 - im)/2)/2)\n", "meta": {"hexsha": "1806216c6f750fd5748453f09aadbfc54d43267e", "size": 1688, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SimpleCarModels.jl-83cf0ae4-8bfa-5275-b23c-08ca25417759", "max_stars_repo_head_hexsha": "496b1be6dccd25a127d23d749b0c4be32571a233", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SimpleCarModels.jl-83cf0ae4-8bfa-5275-b23c-08ca25417759", "max_issues_repo_head_hexsha": "496b1be6dccd25a127d23d749b0c4be32571a233", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-05-20T03:32:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T17:22:33.000Z", "max_forks_repo_path": "src/math.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SimpleCarModels.jl-83cf0ae4-8bfa-5275-b23c-08ca25417759", "max_forks_repo_head_hexsha": "496b1be6dccd25a127d23d749b0c4be32571a233", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:21:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:21:04.000Z", "avg_line_length": 43.2820512821, "max_line_length": 101, "alphanum_fraction": 0.4988151659, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846919, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.754657590051884}}
{"text": "using QuDirac\n\n# This file is an example of a discrete-time quantum random walk \n# implemented using QuDirac. \n\n# First, we define the Hadamard operator `H`, defined as\n#\n# H | 0 ⟩ = 1/√2 * ( | 0 ⟩ + | 1 ⟩ )\n# H | 1 ⟩ = 1/√2 * ( | 0 ⟩ - | 1 ⟩ )\n#\n@rep_op \" H | n > = 1/√2 * ( | 0 > + (-1)^n * | 1 > )\" 0:1\n\n# If an operation on a state only alters basis labels, not coefficients,\n# it can be simpler and more efficient to use `maplabels` than to construct \n# a whole new operator.\n# \n# In this case, we make a function `shift_ket`\n# that maps over the basis labels of the input Ket such that:\n# \n# shift_ket(| 0, j ⟩) -> | 0, j - 1 ⟩\n# shift_ket(| 1, j ⟩) -> | 1, j + 1 ⟩\n#\nfunction shift_map(label::StateLabel)\n    if label[1] == 0\n        return StateLabel(0, label[2] - 1)\n    else\n        return StateLabel(1, label[2] + 1)\n    end\nend\n\nshift_ket(kt::Ket) = maplabels(shift_map, kt) \n\nfunction walk_nsteps(steps)\n    steps += 1\n\n    # Allocate space for the results\n    results = Array(Ket{KroneckerDelta, 2, Float64}, steps);\n\n    # Initial state\n    results[1] = d\" 1.0 * | 0,0 > \"\n\n    # Calculate the each step by referring to the previous step\n    for i=2:steps\n        results[i] = shift_ket(act_on(H, results[i-1], 1))\n    end\n\n    return results\nend\n\nprintln(\"\"\" \nThis example provides the `walk_nsteps` function, which takes in the \nnumber of steps to walk and returns an array containing the result of\neach step. The initial state is | 0,0 ⟩.\"\"\")\n", "meta": {"hexsha": "10eecf0c6ff99d086daa1d28bce7ac863f74062b", "size": 1461, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/randwalk.jl", "max_stars_repo_name": "jqfeld/QuDirac.jl", "max_stars_repo_head_hexsha": "5d1c06d6664e1670aa0df8041041906a47e6202e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-02-12T06:01:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-04T14:24:42.000Z", "max_issues_repo_path": "examples/randwalk.jl", "max_issues_repo_name": "jqfeld/QuDirac.jl", "max_issues_repo_head_hexsha": "5d1c06d6664e1670aa0df8041041906a47e6202e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-06-24T01:53:21.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-23T13:15:08.000Z", "max_forks_repo_path": "examples/randwalk.jl", "max_forks_repo_name": "jqfeld/QuDirac.jl", "max_forks_repo_head_hexsha": "5d1c06d6664e1670aa0df8041041906a47e6202e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2015-06-12T06:34:12.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-26T18:35:17.000Z", "avg_line_length": 27.0555555556, "max_line_length": 76, "alphanum_fraction": 0.6242299795, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846919, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7546575855693377}}
{"text": "lines = readlines(ARGS[1])\nvals = [parse(Int, x) for x in split(lines[1], \",\")]\n\nfunction solution1(vals)\n    min_val = min(vals...)\n    max_val = max(vals...)\n\n    target = nothing\n    for candidate = min_val:max_val\n        total_fuel = sum([abs(x - candidate) for x in vals])\n        if isnothing(target)\n            target = total_fuel\n        elseif total_fuel < target\n            target = total_fuel\n        end\n    end\n    return target\nend\n\n\nfunction fuel_burnt(val1, val2)\n    return sum([x for x = 1:abs(val1 - val2)])\nend\n\nfunction solution2(vals)\n    min_val = min(vals...)\n    max_val = max(vals...)\n\n    target = nothing\n    for candidate = min_val:max_val\n        total_fuel = sum([fuel_burnt(x, candidate) for x in vals])\n        if isnothing(target)\n            target = total_fuel\n        elseif total_fuel < target\n            target = total_fuel\n        end\n    end\n    return target\nend\n\nprintln(solution1(vals))\nprintln(solution2(vals))", "meta": {"hexsha": "829750e32596c63ed1426d484fce63e82e955e86", "size": 959, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day7/solution.jl", "max_stars_repo_name": "zeenewton/aoc2021", "max_stars_repo_head_hexsha": "b95e6385d8f05420e54661c85cf6809674db80e3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day7/solution.jl", "max_issues_repo_name": "zeenewton/aoc2021", "max_issues_repo_head_hexsha": "b95e6385d8f05420e54661c85cf6809674db80e3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day7/solution.jl", "max_forks_repo_name": "zeenewton/aoc2021", "max_forks_repo_head_hexsha": "b95e6385d8f05420e54661c85cf6809674db80e3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8333333333, "max_line_length": 66, "alphanum_fraction": 0.6079249218, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723468, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7546532702369789}}
{"text": "\"\"\"\n    modularity(g, c, distmx=weights(g), γ=1.0)\n\nReturn a value representing Newman's modularity `Q` for the undirected and \ndirected graph `g` given the partitioning vector `c`. This method also supports\nweighted graphs if the distance matrix is provided.\n\nModularity ``Q`` for undirected graph:\n```math\nQ = \\\\frac{1}{2m} \\\\sum_{c} \\\\left( e_{c} - \\\\gamma \\\\frac{K_c^2}{2m} \\\\right)\n```\n\nModularity ``Q`` for directed graph:\n```math\nQ = \\\\frac{1}{m} \\\\sum_{c} \\\\left( e_{c} - \\\\gamma \\\\frac{K_c^{in} K_c^{out}}{m} \\\\right)\n```\n\nwhere:\n- ``m``: total number of edges in the network \n- ``e_c``: number of edges in community ``c``\n- ``K_c``: sum of the degrees of the nodes in community ``c`` or the \n  sum of the weighted degree of the nodes in community ``c`` when the graph is \n  weighted. ``K_c^{in}`` sum of the in-degrees of the nodes in community ``c``.\n\n### Optional Arguments\n- `distmx=weights(g)`: distance matrix for weighted graphs\n- `γ=1.0`: where `γ > 0` is a resolution parameter. When the modularity is used \n  to find communities structure in networks (i.e with [Louvain's method for \n  community detection](https://en.wikipedia.org/wiki/Louvain_Modularity)), \n  higher resolutions lead to more communities, while lower resolutions lead to \n  fewer communities. Where `γ=1.0` it lead to the traditional definition of \n  the modularity.\n\n### References\n- M. E. J. Newman and M. Girvan. \"Finding and evaluating community structure in networks\". \n  Phys. Rev. E 69, 026113 (2004). [(arXiv)](https://arxiv.org/abs/cond-mat/0308217)\n- J. Reichardt and S. Bornholdt. \"Statistical mechanics of community detection\". \n  Phys. Rev. E 74, 016110 (2006). [(arXiv)](https://arxiv.org/abs/cond-mat/0603718)\n- E. A. Leicht and M. E. J. Newman. \"Community structure in directed networks\". \n  Physical Review Letter, 100:118703, (2008). [(arXiv)](https://arxiv.org/pdf/0709.4500.pdf)\n\n# Examples \n```jldoctest\njulia> using LightGraphs\n\njulia> barbell = blockdiag(complete_graph(3), complete_graph(3));\n\njulia> add_edge!(barbell, 1, 4);\n\njulia> modularity(barbell, [1, 1, 1, 2, 2, 2])\n0.35714285714285715\n\njulia> modularity(barbell, [1, 1, 1, 2, 2, 2], γ=0.5)\n0.6071428571428571  \n\njulia> using SimpleWeightedGraphs\n\njulia> triangle = SimpleWeightedGraph(3);\n\njulia> add_edge!(triangle, 1, 2, 1);\n\njulia> add_edge!(triangle, 2, 3, 1);\n\njulia> add_edge!(triangle, 3, 1, 1);\n\njulia> barbell = blockdiag(triangle, triangle);\n\njulia> add_edge!(barbell, 1, 4, 5); # this edge has a weight of 5\n\njulia> modularity(barbell, [1, 1, 1, 2, 2, 2])\n0.045454545454545456\n```\n\"\"\"\nfunction modularity(\n    g::AbstractGraph,\n    c::AbstractVector{<:Integer}; \n    distmx::AbstractArray{<:Number}=weights(g), \n    γ=1.0\n    )\n \n    m = sum([distmx[src(e), dst(e)] for e in edges(g)])\n    m = is_directed(g) ? m : 2 * m\n\n    m == 0 && return 0.\n    nc = maximum(c)\n    kin = zeros(Float32, nc)\n    kout = zeros(Float32, nc)\n    Q = 0.0\n    for u in vertices(g)\n        for v in neighbors(g, u)\n            c1 = c[u]\n            c2 = c[v]\n            if c1 == c2\n                Q += distmx[u,v]\n            end\n            kout[c1] += distmx[u,v]\n            kin[c2] += distmx[u,v]\n        end\n    end \n    Q = Q * m\n    @inbounds for i = 1:nc\n        Q -= γ * kin[i] * kout[i]\n    end\n    return Q / m^2\nend\n", "meta": {"hexsha": "4e76b1ffcec9e2175f5ca8c43d0708e0a9c62675", "size": 3292, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/community/modularity.jl", "max_stars_repo_name": "blepabyte/LightGraphs.jl", "max_stars_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 745, "max_stars_repo_stars_event_min_datetime": "2015-03-19T03:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-07T00:59:06.000Z", "max_issues_repo_path": "src/community/modularity.jl", "max_issues_repo_name": "blepabyte/LightGraphs.jl", "max_issues_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1491, "max_issues_repo_issues_event_min_datetime": "2015-03-19T17:04:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T14:47:57.000Z", "max_forks_repo_path": "src/community/modularity.jl", "max_forks_repo_name": "blepabyte/LightGraphs.jl", "max_forks_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 288, "max_forks_repo_forks_event_min_datetime": "2015-04-04T14:31:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T10:37:21.000Z", "avg_line_length": 31.0566037736, "max_line_length": 92, "alphanum_fraction": 0.6385176185, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.8175744850834649, "lm_q1q2_score": 0.7546532660059301}}
{"text": "\"\"\"\n複数の変数に対して，任意の q 値に対するパーセンタイル値を求めるには，以下のような関数を定義すればよい。\n\nmissing を除去して計算される。\n\"\"\"\n\nfunction quantile2(df, qs=[0, 0.25, 0.5, 0.75, 1])\n    Names =[\"q$(Int(100q))\" for q in qs]\n    Names = replace(Names, \"q0\" => \"min\", \"q50\" => \"median\", \"q100\" => \"max\")\n    qtile = map(x -> quantile(skipmissing(x), qs), eachcol(df))\n    df2 = DataFrame(Matrix(reshape(vcat(qtile...), length(qs), :)'), Names)\n    n = map(x -> length(filter(!ismissing, x)), eachcol(df))\n    insertcols!(df2, 1, :variable => names(df), :n => n)\n    df2\nend\n\n\"\"\"\n使用例\n\njulia> using RDatasets, Statistics\n\n\njulia> iris = dataset(\"datasets\", \"iris\");\n\n\n\njulia> quantile2(iris[:, 1:4])\n4×7 DataFrame\n Row │ variable     n      min      q25      median   q75      max\n     │ String       Int64  Float64  Float64  Float64  Float64  Float64\n─────┼─────────────────────────────────────────────────────────────────\n   1 │ SepalLength    150      4.3      5.1     5.8       6.4      7.9\n   2 │ SepalWidth     150      2.0      2.8     3.0       3.3      4.4\n   3 │ PetalLength    150      1.0      1.6     4.35      5.1      6.9\n   4 │ PetalWidth     150      0.1      0.3     1.3       1.8      2.5\n\"\"\"\n", "meta": {"hexsha": "829133eefc08096986ffc40f7b54bf21fddda1c6", "size": 1160, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "quantile.jl", "max_stars_repo_name": "r-de-r/stats", "max_stars_repo_head_hexsha": "69ae834ecb55f737106900a1f14674e55cc1f972", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quantile.jl", "max_issues_repo_name": "r-de-r/stats", "max_issues_repo_head_hexsha": "69ae834ecb55f737106900a1f14674e55cc1f972", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quantile.jl", "max_forks_repo_name": "r-de-r/stats", "max_forks_repo_head_hexsha": "69ae834ecb55f737106900a1f14674e55cc1f972", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3513513514, "max_line_length": 77, "alphanum_fraction": 0.500862069, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7546532592106266}}
{"text": "using JuMP, VariationalInequality\n\n# https://cdr.lib.unc.edu/indexablecontent/uuid:778ca632-74ca-4858-8c3c-6dcfc7e6e703\n# Example 4.2. This example is adapted from the example in (Fukushima, 1986). Let\nm = VIPModel()\n@variable(m, x[1:3])\n\n@constraint(m, x[1]^2 + 0.4x[2]^2 + 0.6x[3]^2 <= 1)\n@constraint(m, 0.6x[1]^2 + 0.4x[2]^2 + x[3]^2 <= 1)\n@constraint(m, x[1] + x[2] + x[3] >= sqrt(3))\n\n@mapping(m, F1, 2x[1] + 0.2x[1]^3 - 0.5x[2] + 0.1x[3] - 4)\n@mapping(m, F2, -0.5x[1] + x[2] + 0.1x[2]^3 + 0.5)\n@mapping(m, F3, 0.5x[1] - 0.2x[2] + 2x[3] - 0.5)\n\n@innerproduct(m, F1, x[1])\n@innerproduct(m, F2, x[2])\n@innerproduct(m, F3, x[3])\n# or\n# @innerproduct(m, [F1, F2, F3], x)\n\n\nsolveVIP(m, algorithm=:fixed_point, max_iter=1000, step_size=0.1)\nsol1, Fval1, gap1 = save_solution(m)\n@assert 0<= gap1 < 1e-6\n\n# The above `solveVIP` sets the value of variables at the solution\nclear_values(m)\n\nsolveVIP(m, algorithm=:extra_gradient, max_iter=1000, step_size=0.1)\nsol2, Fval2, gap2 = save_solution(m)\n@assert 0<= gap2 < 1e-6\n\n# sol2, Fval2, gap2 = solveVIP(m, algorithm=:hyperplane, max_iter=1000, step_size=0.1)\n\n@show sol1\n@show sol2\n@show gap1\n@show gap2\n\n\n\n# OKAY.\n# x∗ = (0.9168, 0.4850, 0.3303)\n", "meta": {"hexsha": "c90c0e92d182be82ea3af45cbdf52adffb32f22c", "size": 1192, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/fukushima2.jl", "max_stars_repo_name": "UnofficialJuliaMirror/VariationalInequality.jl-f79a5470-17c6-525f-b62f-3ca7bd6eedf2", "max_stars_repo_head_hexsha": "da77cb10a1f36bafb972795eac77cdb24ad2fbaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2017-10-17T11:29:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T12:26:21.000Z", "max_issues_repo_path": "example/fukushima2.jl", "max_issues_repo_name": "UnofficialJuliaMirror/VariationalInequality.jl-f79a5470-17c6-525f-b62f-3ca7bd6eedf2", "max_issues_repo_head_hexsha": "da77cb10a1f36bafb972795eac77cdb24ad2fbaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2017-03-13T18:07:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-09T01:15:29.000Z", "max_forks_repo_path": "example/fukushima2.jl", "max_forks_repo_name": "UnofficialJuliaMirror/VariationalInequality.jl-f79a5470-17c6-525f-b62f-3ca7bd6eedf2", "max_forks_repo_head_hexsha": "da77cb10a1f36bafb972795eac77cdb24ad2fbaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:17:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-06T20:47:56.000Z", "avg_line_length": 26.4888888889, "max_line_length": 86, "alphanum_fraction": 0.6451342282, "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7546532551078001}}
{"text": "export Mesh\n\n\"\"\"\n    `Mesh(args)`\n\nConstructs a mesh of collocation points and associated Fourier modes.\n\n# Arguments\nCan be either\n- `xmin , xmax , N `; or\n- `L , N ` (same as above with `xmin=-L` and `xmax=L`); or\n- `param :: NamedTuple`, param contains `N` and `L`, then same as above; or\n- `x` a vector of regularly spaced collocation points`.\n\nThe mesh as `N` collocation points regularly spaced between `xmin` (included) and `xmax` (excluded)\n\n# Return values\n`m=Mesh(args)` is of parametric type and offers\nwith\n- `m.N `: number of collocation points and Fourier modes;\n- `m.xmin`: minimum of the mesh;\n- `m.xmax`: maximum of the mesh;\n- `m.dx`: distance between two collocation points;\n- `m.x`: the vector of collocation points;\n- `m.kmin`: minimum of Fourier modes;\n- `m.kmax`: maximum of Fourier modes;\n- `m.dk`: distance between two Fourier modes;\n- `m.k`: the vector of Fourier modes.\n\n\"\"\"\nstruct Mesh\n\n    N    :: Int64\n    xmin :: Float64\n    xmax :: Float64\n    dx   :: Float64\n    x    :: Vector{Float64}\n    kmin :: Float64\n    kmax :: Float64\n    dk   :: Float64\n    k    :: Vector{Float64}\n\n    function Mesh( xmin , xmax , N :: Int64)\n\n        dx   = (xmax-xmin)/N\n        x    = zeros(Float64, N)\n        x   .= range(xmin, stop=xmax, length=N+1)[1:end-1]\n        dk   = 2π/(N*dx)\n        kmin = -N/2*dk\n        kmax = (N/2-1)*dk\n        k    = zeros(Float64, N)\n        k   .= dk .* vcat(0:(N-1)÷2, -N÷2:-1)\n\n        new( N, xmin, xmax, dx, x, kmin, kmax, dk, k)\n\n    end\n\n    function Mesh(L , N :: Int64)\n\n        xmin = - L\n        xmax =   L\n        N    =   N\n\n        Mesh( xmin, xmax, N)\n\n    end\n\n    function Mesh( x )\n\n        N    =   length(x)\n        dx   =   (x[end]-x[1])/(N-1)\n        xmin = x[1]\n        xmax = x[end]+dx\n\n        Mesh( xmin, xmax, N)\n\n    end\n\n    function Mesh(param :: NamedTuple)\n\n        if :xmin in keys(param) && :xmax in keys(param)\n            xmin = param.xmin\n            xmax = param.xmax\n        else\n            xmin = - param.L\n            xmax =   param.L\n        end\n        N    =   param.N\n\n        Mesh( xmin, xmax, N)\n\n    end\nend\n", "meta": {"hexsha": "14b7452647efe266a2d281b33db1c906f41880b4", "size": 2107, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mesh.jl", "max_stars_repo_name": "WaterWavesModels/ShallowWaterModels.jl", "max_stars_repo_head_hexsha": "ab745353a2472a76646d976c6fe536f0be664488", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-21T17:07:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-25T20:31:31.000Z", "max_issues_repo_path": "src/mesh.jl", "max_issues_repo_name": "WaterWavesModels/ShallowWaterModels.jl", "max_issues_repo_head_hexsha": "ab745353a2472a76646d976c6fe536f0be664488", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-07-17T17:38:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T07:36:48.000Z", "max_forks_repo_path": "src/mesh.jl", "max_forks_repo_name": "WaterWavesModels/ShallowWaterModels.jl", "max_forks_repo_head_hexsha": "ab745353a2472a76646d976c6fe536f0be664488", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.414893617, "max_line_length": 99, "alphanum_fraction": 0.5405790223, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.8519528076067261, "lm_q1q2_score": 0.7545162231960166}}
{"text": "##############################################################################\n#\n# Symmetric triangular distribution from Distributions Handbook\n#\n##############################################################################\n\nimmutable Triangular <: ContinuousUnivariateDistribution\n    location::Float64\n    scale::Float64\n    function Triangular(l::Real, s::Real)\n        s > zero(s) || error(\"scale must be positive\")\n        new(float64(l), float64(s))\n    end\nend\n\nTriangular(location::Real) = Triangular(location, 1.0)\nTriangular() = Triangular(0.0, 1.0)\n\nfunction cdf(d::Triangular, x::Real)\n    a, b, c = d.location - d.scale, d.location + d.scale, d.location\n    if x <= a\n        return 0.0\n    elseif a <= x <= c\n        return (x - a)^2 / ((b - a) * (c - a))\n    elseif c < x <= b\n        return 1.0 - (b - x)^2 / ((b - a) * (b - c))\n    else\n        return 1.0\n    end\nend\n\nentropy(d::Triangular) = 0.5 + log(d.scale)\n\nfunction insupport(d::Triangular, x::Number)\n    return isreal(x) && isfinite(x) &&\n           d.location - d.scale <= x <= d.location + d.scale\nend\n\nkurtosis(d::Triangular) = -0.6\n\nmean(d::Triangular) = d.location\n\nmedian(d::Triangular) = d.location\n\nmode(d::Triangular) = d.location\nmodes(d::Triangular) = [d.location]\n\nfunction pdf(d::Triangular, x::Real)\n    if insupport(d, x)\n        return -abs(x - d.location) / (d.scale^2) + 1.0 / d.scale\n    else\n        return 0.0\n    end\nend\n\nfunction quantile(d::Triangular, p::Real)\n    a, b, c = d.location - d.scale, d.location + d.scale, d.location\n    if p <= 0.0\n        return a\n    elseif p < 0.5\n        return a + sqrt(p * 2.0 * d.scale^2)\n    elseif p >= 0.5\n        return b -  sqrt((1.0 - p) * 2.0 * d.scale^2)\n    else\n        return b\n    end\nend\n\nfunction rand(d::Triangular)\n    ξ1, ξ2 = rand(), rand()\n    return d.location + (ξ1 - ξ2) * d.scale\nend\n\nfunction skewness(d::Triangular)\n    a = d.location - d.scale\n    b = d.location + d.scale\n    c = (b - a) / 2 + a\n    den = sqrt(2.0) * (a + b - 2.0 * c) *\n                      (2.0 * a - b - c) *\n                      (a - 2.0 * b + c)\n    num = 5.0 * (a^2 + b^2 + c^2 - a * b - a * c - b * c)^1.5\n    return den / num\nend\n\nvar(d::Triangular) = d.scale^2 / 6.0\n", "meta": {"hexsha": "f08b84255b1e5b49d00bc0779686fc3bbefeb9bf", "size": 2213, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/triangular.jl", "max_stars_repo_name": "simonbyrne/Distributions.jl", "max_stars_repo_head_hexsha": "a9bd0e62002a94007ecd590e51cb27af9a346544", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/triangular.jl", "max_issues_repo_name": "simonbyrne/Distributions.jl", "max_issues_repo_head_hexsha": "a9bd0e62002a94007ecd590e51cb27af9a346544", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/triangular.jl", "max_forks_repo_name": "simonbyrne/Distributions.jl", "max_forks_repo_head_hexsha": "a9bd0e62002a94007ecd590e51cb27af9a346544", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7325581395, "max_line_length": 78, "alphanum_fraction": 0.511974695, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7545162172952488}}
{"text": "### A Pluto.jl notebook ###\n# v0.18.0\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local iv = try Base.loaded_modules[Base.PkgId(Base.UUID(\"6e696c72-6542-2067-7265-42206c756150\"), \"AbstractPlutoDingetjes\")].Bonds.initial_value catch; b -> missing; end\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)\n        el\n    end\nend\n\n# ╔═╡ 3f1cfd12-7b86-11eb-1371-c5795b87ef5b\nbegin\n\tusing Plots, LaTeXStrings, PrettyTables, DataFrames, LinearAlgebra, \n\t\t  PlutoUI, BenchmarkTools, ForwardDiff, Printf, SIAMFANLEquations\n\tinclude(\"tools.jl\")\nend;\n\n# ╔═╡ 10164e58-86ab-11eb-24c7-630872bf513d\n# to use the fft algorithms, import them as follows:\nusing FFTW\n\n# ╔═╡ 76e9a7f6-86a6-11eb-2741-6b8759be971b\nmd\"\"\"\n## §2 Spectral Methods \n\nThe purpose of the second group of lectures is to study a class of numerical methods for solving differential equations, called *Fourier Spectral Methods*. For example we will learn how to solve periodic boundary value problems such as \n```math\n\\begin{aligned}\n  - u'' + u &= f, \\\\ \n\tu(-\\pi) &= u(\\pi), \\\\ \n    u'(-\\pi) &= u'(\\pi)\n\\end{aligned}\n```\nto very high accuracy. \n\nBefore we begin we will develop a fast algorithm to evaluate the trigonometric interpolant, and more generally to convert between nodal values and fourier coefficients.\n\"\"\"\n\n# ╔═╡ 04b54946-86a7-11eb-1de0-2f61e7b8f790\nmd\"\"\"\n## §2.1 The Fast Fourier Transform \n\n### The Discrete Fourier Transform\n\nRecall from §1 that the trigonometric interpolant ``I_N f`` of a function ``f`` is given by\n```math\n\tI_N f(x) = \\sum_{k = -N+1}^{N-1} \\hat{F}_k e^{i k x} + \\hat{F}_N \\cos(N x)\n```\nand the coefficients are determined by the linear system \n```math\n\t\\sum_{k = -N+1}^N \\hat{F}_k e^{i k x_j} = F_j, \\qquad j = 0, \\dots, 2N-1.\n```\nwhere ``F_j = f(x_j)`` and ``x_j = j \\pi / N``. We have moreover shown numerically and proved this in A1 that the system matrix is orthogonal (up to rescaling), i.e., if \n```math\n\tA = \\big( e^{i k x_j} \\big)_{k,j}\n```\nthen \n```math\n\tA A^H = 2N I\n```\nIn particular ``A`` is invertible, i.e., the mapping ``F \\mapsto \\hat{F}, \\mathbb{C}^{2N} \\to \\mathbb{C}^{2N}`` is invertible. \nThis mapping is called the discrete fourier transform (DFT) and its inverse is called the inverse discrete fourier transform (IDFT, ``\\hat{F} \\mapsto F``). Both use a different scaling than we use here; specifically, the most commen definition is \n```math\n\\begin{aligned}\n\t{\\rm DFT}[G]_k &= \\sum_{j = 0}^{2N-1} e^{- i k j \\pi / N} G_j, \\\\ \n\t{\\rm IDFT}[\\hat{G}]_j &= \\frac{1}{2N} \\sum_{k = -N+1}^N e^{i k j \\pi / N} \\hat{G}_k.\n\\end{aligned}\n```\nThis means the the mappings ``F \\mapsto \\hat{F}, \\hat{F} \\mapsto F`` can be written as \n```math \n\t\\hat{F} = (2N)^{-1} \\cdot {\\rm DFT}[F], \\qquad F = 2N \\cdot {\\rm IDFT}[\\hat{F}]\n```\n\"\"\"\n\n# ╔═╡ d57bead8-86b3-11eb-3095-1fee9108c6b1\nmd\"\"\"\nThe cost of evaluating the DFT and IDFT naively is ``O(N^2)`` (matrix-vector multiplication) but the special structures in the DFT make it possible to evaluate them in ``O(N \\log (N))`` operations. This was first observed by Gauss (1876), and much later rediscovered and popularized by [Cooley & Tukey (1965)](https://en.wikipedia.org/wiki/Cooley–Tukey_FFT_algorithm). It is generally considered one of the [most important algorithms of the 20th century](https://www.computer.org/csdl/magazine/cs/2000/01/c1022/13rRUxBJhBm). \n\nIn Julia, the FFT is implemented in the [FFTW package](https://github.com/JuliaMath/FFTW.jl) (the Fastest Fourier Transform in the West). Before we study it, we can try it out:\n\"\"\"\n\n# ╔═╡ 7b0578ee-8744-11eb-0bf1-555f11fbb0fd\nbegin\n\t# let's also define some general utility functions\n\t\n\t# the strange (??) ordering of the k-grid is determined by \n\t# the convention used for the FFT algorithms\n\txgrid(N) = [ j * π / N  for j = 0:2N-1 ]\n\tkgrid(N) = [ 0:N; -N+1:-1 ]\n\t\n\tfunction dft(F)\n\t\tN = length(F) ÷ 2\n\t\tA = [ exp(im * k * x) for k in kgrid(N), x in xgrid(N) ]\n\t\treturn (A' * F) / (2*N)\n\tend\nend\n\n# ╔═╡ 13e8fc40-86ab-11eb-1f63-9d2ed7538e7e\nlet N = 100\n\t# run a random tests to confirm FFT = DFT\n\tF = rand(ComplexF64, N)\n\tnorm( dft(F) - fft(F) / N )\nend\n\n# ╔═╡ c3e57120-86ab-11eb-2268-4f7338540556\nlet N = 100\n\t# run a random test to see how fft, ifft work\n\tF = rand(ComplexF64, N)\n\tnorm(F - ifft(fft(F)))\nend\n\n# ╔═╡ fc6671fa-8748-11eb-3d6b-e50f405b446f\nmd\"Finally, let's compare the Timing of DFT vs FFT (times in seconds):\"\n\n# ╔═╡ 96d114ee-8748-11eb-05f8-a72869439a84\nlet NN = [5, 10, 20, 40, 80, 160]\n\tFF = [ rand(ComplexF64, 2*N) for N in NN ]   # random trial vectors \n\ttimes_dft = [ @belapsed dft($F) for F in FF ]\n\ttimes_fft = [ @belapsed fft($F) for F in FF ]\n\tata_table( (NN, \"``N``\", \"%d\"), \n\t\t       (times_dft, \"DFT\", \"%1.2e\"), \n\t\t       (times_fft, \"FFT\", \"%1.2e\"), \n\t           (times_fft./times_dft, \"FFT/DFT\", \"%1.1e\"), \n\t\t\t   )\nend\n\n# ╔═╡ 6da69574-86b4-11eb-3300-9b1d62ede475\nmd\"\"\"\nWhat is the idea behind the FFT that gives it such a great performance? Note that the ``O(N \\log(N))`` scaling is very close to the theoretically optimal complexity. There are many good references to study the FFT, and there is little point in reproducing this here. But we can at least discuss the main idea of the radix-2 FFT; see whiteboard lecture, and [LN, Sec. 3.6]. We will prove the following result: \n\n**Theorem:** If ``N = 2^n`` then the DFT (and the IDFT) can be evaluated with ``O(N \\log(N))`` operations and ``O(N)`` storage.\n\nWith this in hand, we can now rewrite our trigonometric interpolation routines as follows. (Though sometimes we will simply use `fft` and `ifft` directly.)\n\"\"\"\n\n\n# ╔═╡ 3c81eca4-86b5-11eb-0e54-d53593b063bc\nbegin\n\t\"\"\"\n\tconstruct the coefficients of the trigonometric interpolant\n\t\"\"\"\n\ttriginterp(f, N) = fft(f.(xgrid(N))) / (2*N)\n\t\n\t\n\t\"\"\"\n\tto evaluate a trigonometric polynomial just sum coefficients * basis\n\twe the take the real part because we assume the function we are \n\tapproximating is real.\n\t\"\"\"\n\tevaltrig(x, F̂) = sum( real(F̂ₖ * exp(im * x * k))\n\t\t\t\t\t\t  for (F̂ₖ, k) in zip(F̂, kgrid(length(F̂) ÷ 2)) )\nend \n\n# ╔═╡ c93dbae2-86b5-11eb-1468-bd709534e1af\nmd\"\"\"\nApproximating ``f(x) = \\sin(2x) / (0.1 + \\cos^2(x))``  \n\nChoose a polynomial degree:  $(@bind _N1 Slider(5:20))\n\"\"\"\n\n# ╔═╡ a18b061c-86b5-11eb-3c44-0bc846854b1b\nlet f = x -> sin(2*x) / (0.1 + cos(x)^2)\n\txp = range(0, 2*π, length=500)\n\tX = xgrid(_N1)\n\tF̂ = triginterp(f, _N1)\n\tplot(xp, f.(xp), lw=4, label = L\"f\", size = (500, 300))\n\tplot!(xp, evaltrig.(xp, Ref(F̂)), lw=2, label = L\"I_N f\")\n\tplot!(X, f.(X), lw=0, c=2, m=:o, ms=3, label = \"\", \n\t\t  title = latexstring(\"N = $(_N1)\"))\nend\n\n# ╔═╡ bc30cf3c-86b6-11eb-1f21-ff29b647a839\nmd\"\"\"\nApproximating ``f(x) = e^{- |\\sin(x)|}``\n\nChoose a polynomial degree:  $(@bind _p2 Slider(2:10))\n\"\"\"\n\n# ╔═╡ e02f56bc-86b6-11eb-3a66-0d0b94677262\nlet f = x -> exp( - abs(sin(x)) )\n\tN2 = 2^_p2\n\txp = range(0, 2*π, length=1000)\n\tX = xgrid(N2)\n\tF̂ = triginterp(f, N2)\n\tplot(xp, f.(xp), lw=4, label = L\"f\", size = (500, 300))\n\tplot!(xp, evaltrig.(xp, Ref(F̂)), lw=2, label = L\"I_N f\")\n\tplot!(X, f.(X), lw=0, c=2, m=:o, ms=3, label = \"\", \n\t\t  title = latexstring(\"N = $(N2)\"))\nend\n\n# ╔═╡ 240250ae-86b7-11eb-1046-7f29472897fd\nmd\"\"\"\n\n## §2.2 Fourier transform of linear homogeneous differential operators\n\nLet \n```math\n\tt_N(x) = \\sum_k \\hat{F}_k e^{i k x}\n``` \nbe a trigonometric polynomial, then \n```math\n\tt_N'(x) = \\frac{d t_N(x)}{dx} = \\sum_k \\hat{F}_k (i k) e^{i k x}\n```\nWe have two nice properties: \n* If ``t_N \\in \\mathcal{T}_N`` then ``t_N' = dt_N/dx \\in \\mathcal{T}_N`` as well.\n* If ``t_N \\in \\mathcal{T}_N'`` then ``t_N'' \\in \\mathcal{T}_N'`` as well.\n* the differentiation of ``t_N`` corresponds to multiplying the Fourier coefficients ``\\hat{F}_k`` by ``i k``. \n\nIn other words if we represent a function by its fourier coefficients then we can *exactly* represent differentiation operator ``d/dx`` by a diagonal matrix, \n```math\n\t\\hat{F} \\mapsto \\hat{d} {\\,.\\!\\!*\\,} \\hat{F} = \\big( i k \\hat{F}_k )_{k = -N+1}^N.\n```\nwhere ``{\\,.\\!\\!*\\,}`` denotes element-wise multiplication. This is an extremely convenient property when we try to discretise a differential equation and extends to general linear homogeneous differential operators: \n```math\n\tL := \\sum_{p = 0}^P a_p \\frac{d^p}{dx^p} \\qquad \\text{becomes} \\qquad \n\t\\hat{L}(k) = \\sum_{p = 0}^P a_p (i k)^p.\n```\nBy which we mean that \n```math\n\ts_N = L f_N, \\qquad \\Rightarrow \\qquad \n\t\\hat{S}_k =  \\hat{L}_k \\hat{F}_k.\n```\n\n\nThere are other important operators that also become diagonal under the Fourier transform, the most prominent being the convolution operator.\n\n\"\"\"\n\n# ╔═╡ 5ebefefe-86b7-11eb-227f-3d5e02a142fd\nmd\"\"\"\n\n## §2.3 Spectral methods for linear homogeneous problems\n\nLet us return to the introductory example, \n```math\n\t- u'' + u = f, \n```\nand imposing periodic boundary conditions. We now perform the following steps: \n\n* Approximate ``u`` by a trigonometric polynomial ``u_N \\in \\mathcal{T}_N'``. \n* Approximate ``f`` by a trigonometric polynomial ``f_N \\in \\mathcal{T}_N'``. \nIn real space the equation becomes ``- u_N'' + u_N = f_N``, and expanded \n```math\n\t\\sum_{k = -N+1}^N \\hat{U}_k \\big[ - (i k)^2 + 1 \\big] e^{i kx}\n\t= \\sum_{k = -N+1}^N \\hat{F}_k e^{i kx}\n```\n* Equating coefficients and noting that ``-(ik)^2 = k^2`` we obtain \n```math\n\t(1 + k^2) \\hat{U}_k = \\hat{F}_k\n```\nor, equivalently, \n```math\n\t\\hat{U}_k = (1+k^2)^{-1} \\hat{F}_k.\n```\nThis is readily implemented in a short script.\n\"\"\"\n\n# ╔═╡ 452c65b2-8806-11eb-2d7a-3f4312071cd1\nmd\"\"\"\nPolynomial degree:  $(@bind _N2 Slider(5:20, show_value=true))\n\nRight-hand side ``f(x) = ``: $(@bind _fstr2 TextField())\n\"\"\"\n\n# ╔═╡ 503b45d0-8e65-11eb-0e77-15314d82de1a\n_ffun2 = ( _fstr2 == \"\" ? x -> abs(exp(sin(x) + 0.5 * sin(x)^2)) \n\t\t\t\t        : Meta.eval(Meta.parse(\"x -> \" * _fstr2)) );\n\n# ╔═╡ f3c1ba14-8e64-11eb-33ea-4341480e50b3\n_Ûex2 = let N = 100, f = _ffun2\n\t\tF̂ = triginterp(f, N)\n\t\tK = kgrid(N) \n\t\tF̂ ./ (1 .+ K.^2)\n\tend ;\n\n# ╔═╡ b5359ee2-86de-11eb-1446-b10b9815f448\nlet N = _N2, f = _ffun2\n\tF̂ = triginterp(f, N)\n\tK = kgrid(N) \n\tÛ = F̂ ./ (1 .+ K.^2)\n\txp = range(0, 2π, length=200)\n\tplot(xp, evaltrig.(xp, Ref(_Ûex2)), lw=4, label = L\"u\", size = (400, 300), \n\t\ttitle = L\"N = %$N\", xlabel = L\"x\")\n\tplot!(xp, evaltrig.(xp, Ref(Û)), lw=3, label = L\"u_N\", size = (400, 300))\t\t\t\t\n\tplot!(xgrid(N), evaltrig.(xgrid(N), Ref(Û)), lw=0, ms=3, m=:o, c=2, label = \"\")\nend \n\n# ╔═╡ 0c84dcde-86e0-11eb-1877-932742501593\nmd\"\"\"\n### Convergence of spectral methods \n\nWhat can we say about the convergence of the method? Let us start with a very simple argument, which we will then generalise. The key observation is that our approximate solution ``u_N`` satisfies the full DE but with a perturbed right-hand side ``f \\approx f_N``. \n```math\n\\begin{aligned}\n\t- u'' + u &= f, \\\\ \n   - u_N'' + u_N &= f_N.\n\\end{aligned}\n```\nBecause the differential operator is linear, we can subtract the two lines and obtain  the *error equation*\n```math \n   -e_N'' + e_N = f - f_N, \n```\nwhere ``e_N = u - u_N`` is the error. At this point, we have several options how to proceed, but since so far we have studied approximation in the max-norm we can stick with that. We have the following result: \n\n**Lemma 2.3.1:** If ``- u'' + u = f`` with ``f \\in C_{\\rm per}`` then \n```math\n\t\\|u \\|_\\infty \\leq C \\|f \\|_\\infty,\n```\nwhere ``C`` is independent of ``f, u``.\n\n**Proof:** via maximum principle or Fourier analysis. Note the result is far from sharp, but it is enough for our purposes. Via Fourier analysis you would in fact easily get a much stronger result such as ``\\|u\\|_\\infty \\leq C \\|f\\|_{H^{-1}}`` and even that can still be improved.\n\nApplying Lemma 2.3.1 to the error equation we obtain \n```math\n\t\\| e_N \\|_\\infty \\leq C \\|f - f_N \\|_\\infty.\n```\nFor example, if ``f`` is analytic, then we know that \n```math \n\t\\|f - f_N \\|_\\infty \\leq M_f e^{-\\alpha N}\n```\nfor some ``\\alpha > 0``, and hence we will also obtain \n```math \n\t\\| u - u_N \\|_\\infty \\leq C M_f e^{-\\alpha N}. \n```\nThat is, we have proven that our spectral method converges exponentially fast:\n\n**Theorem 2.3.2:** If ``f`` is analytic then there exist ``C, \\alpha > 0`` such that \n```math\n\t\\|u - u_N\\|_\\infty \\leq C e^{-\\alpha N}.\n```\n\"\"\"\n\n# ╔═╡ bb33932c-8769-11eb-0fb7-a39703fa96cc\nmd\"\"\"\nWe can test this numerically using the *method of manufactured solutions*. We start from a solution ``u(x)`` and compute the corresponding right-hand side ``f(x) = - u''(x) + u(x)``. Then we solve the BVP for that right-hand side for increasing degree ``N`` and observe the convergence rate.\n\nHere we choose \n```math\n\tu(x) = \\cos\\big( (0.2 + \\sin^2 x)^{-1} \\big)\n```\n\"\"\"\n\n# ╔═╡ a0e33748-8769-11eb-26b4-416a32282bc2\nlet NN = 10:10:120, u = x -> cos( 1 / (0.2 + sin(x)^2) )\n\tdu = x -> ForwardDiff.derivative(u, x)\n\td2u = x -> ForwardDiff.derivative(du, x)\n\tf = x -> u(x) - d2u(x)\n\txerr = range(0, 2π, length = 1_000)\n\tsolve(N) = triginterp(f, N) ./ (1 .+ kgrid(N).^2)\n\terror(N) = norm(u.(xerr) - evaltrig.(xerr, Ref(solve(N))), Inf)\n\terrs = error.(NN) \n\tplot(NN, errs, yscale = :log10, lw = 3, m=:o, ms=4, label = \"error\", \n\t\t\t\t  size = (400, 300), xlabel = L\"N\", ylabel = L\"\\Vert u - u_N \\Vert_\\infty\")\n\tplot!(NN[5:9], 1_000*exp.( - 0.33 * NN[5:9]), lw=2, ls=:dash, c=:black, label = \"rate\")\n\thline!([1e-15], lw=2, c=:red, label = L\"\\epsilon\")\nend\n\n# ╔═╡ 9a6facbe-876b-11eb-060a-7b7e717237be\nmd\"\"\"\nTry reaching machine precision with a finite difference or finite element method!\n\"\"\"\n\n# ╔═╡ f63dcd36-8ac8-11eb-3831-57f0a5088c98\nmd\"\"\"\n#### An a priori approach ...\n\nHow can we determine a good discretisation parameter *a priori*? Suppose, e.g., that we wish to achieve 10 digits of accuracy for our solution. We know from the arguments above that ``\\|u - u_N\\|_\\infty \\leq C \\|f - f_N \\|_\\infty``. We don't know the constant, but for sufficiently simple problems we can legitimately hope that it is ``O(1)``. Hence, we could simply check the convergence of the trigonometric interpolant:\n\"\"\"\n\n# ╔═╡ 33f2ab24-8ac9-11eb-220e-e71d3ebb93fa\nlet NN = 40:20:140, u = x -> cos( 1 / (0.2 + sin(x)^2) )\n\tdu = x -> ForwardDiff.derivative(u, x)\n\td2u = x -> ForwardDiff.derivative(du, x)\n\tf = x -> u(x) - d2u(x)\n\terr = Float64[] \n\txerr = range(0, 2π, length = 1_234)\n\tfor N in NN \n\t\tF̂ = triginterp(f, N) \n\t\tpush!(err, norm(f.(xerr) - evaltrig.(xerr, Ref(F̂)), Inf))\n\tend\n\tata_table( (NN, L\"N\"), (err, L\"\\|f - f_N\\|\") )\nend\n\n# ╔═╡ a0797ece-8ac9-11eb-2922-e3f0295d4787\nmd\"\"\"\nThe error stagnates, suggesting that we have reached machine precision at around ``N = 120``. And we have likely achieved an accuracy of ``10^{-10}`` for around ``N = 90``. The error plot shows that in fact we have reached ``10^{-10}`` accuracy already for ``N = 70``, but this is ok. We are only after rough guidance here.\n\nAn alternative approach is to look at the decay of the Fourier coefficients. By plotting their magnitude we can get a sense at what degree to truncate. Of course we cannot compute the exact Fourier series coefficients, but the coefficients of the trigonometric interpolant closely approximate them (cf Assignment 1).\n\"\"\"\n\n# ╔═╡ 057c7508-8aca-11eb-0718-21826e314bc7\nlet N = 150, u = x -> cos( 1 / (0.2 + sin(x)^2) )\n\tdu = x -> ForwardDiff.derivative(u, x)\n\td2u = x -> ForwardDiff.derivative(du, x)\n\tf = x -> u(x) - d2u(x)\n\tF̂ = triginterp(f, N) \n\tK = kgrid(N)\n\tplot(abs.(K), abs.(F̂), lw=0, ms=2, m=:o, label =\"\", \n\t\t xlabel = L\"|k|\", ylabel = L\"|\\hat{F}_k|\", \n\t\t yscale = :log10, size = (350, 200))\n\thline!([1e-10], lw=2, c=:red, label = \"\")\nend \n\n\n# ╔═╡ 59485024-8aca-11eb-2e65-3962c096e9df\nmd\"\"\"\nEntirely consistent with our previous results we observe that \nthe Fourier coefficients drop below a value of ``10^{-10}`` \njust below ``|k| = 100``. This gives us a second strong indicator \nthat for ``N \\geq 100`` we will obtain the desired accuracy of \n``10^{-10}``.\n\"\"\"\n\n# ╔═╡ c9a6c2ce-876b-11eb-182c-d90997ea2cab\nmd\"\"\"\n### General Case \nMore generally consider a linear operator equation (e.g. differential or integral equation)\n```math\n\tL u = f \n```\nwhich we discretise as \n```math\n\tL u_N = f_N\n```\nand where we assume that it transforms under the DFT as\n```math\n\t\\hat{L}_k \\hat{U}_k = \\hat{F}_k\n```\nwhere ``u_N = {\\rm Re} \\sum_k \\hat{U}_k e^{i k x}`` and ``f_N = {\\rm Re} \\sum_k \\hat{F}_k e^{i  x}``.\n\nNow we make two closely related assumptions (2. implies 1.): \n1. ``\\hat{L}_k \\neq 0`` for all ``k``\n2. ``L`` is max-norm stable : ``\\| u \\|_\\infty \\leq C \\| f \\|_\\infty``\n\nFrom 1. we obtain that ``\\hat{U}`` and hence ``u_N`` are well-defined. From 2. we obtain \n```math\n\t\\| u - u_N \\|_\\infty \\leq C \\| f - f_N \\|_\\infty\n```\nand the rate of approximation of the right-hand side will determine the rate of approximation of the solution. We can explore more cases and examples in the assignment.\n\"\"\"\n\n\n# ╔═╡ 5b3e4e06-8e6e-11eb-0f31-5546b0ae450a\nmd\"\"\"\n\n### Summary Spectral Methods / Perspective\n\nNumerical Analysis and Scientific Computing for (P)DEs : \n* regularity theory: how smooth are the solutions of the DE?\n* approximation theory: how well can we approximate the solution in principle?\n* discretisation, error analysis: how do we discretize the DE to guarantee convergence of the discretized solution? Optimal rates as predicted by approximation theory?\n* Fast algorithms: scaling of computational cost matters! e.g. FFT provides close to optimal computational complexity, in general this is difficult to achieve. \n\"\"\"\n\n# ╔═╡ 6deea4c4-86b7-11eb-0fe7-5d6d0f3007ef\nmd\"\"\"\n\n## §2.4 Spectral methods for time-dependent, inhomogeneous and nonlinear problems\n\nIn the following we will implement a few examples that go beyond the basic theory above and showcase a few more directions in which one could explore spectral methods. We will see a few techniques to treat cases for which spectral methods are more difficult to use, namely for differential operators with inhomogeneous coefficients and for nonlinear problems.\n\"\"\"\n\n# ╔═╡ 7620d684-88fe-11eb-212d-efcbc1803608\nmd\"\"\"\n### Wave equation \n```math\n\tu_{tt} = u_{xx}\n```\nWe first discretise in space, \n```math \n\tu_{tt} = u_{N, xx},\n```\nthen transform to Fourier coefficients, \n```math\n\t\\frac{d^2\\hat{U}_k}{d t^2}  = - k^2 \\hat{U}_k,\n```\nand finally discretize in time\n```math \n\t\\frac{\\hat{U}_k^{n+1} - 2 \\hat{U}_k^n + \\hat{U}_k^{n-1}}{\\Delta t^2}\n\t= - k^2 \\hat{U}_k^n\n```\n\"\"\"\n\n# ╔═╡ 42513412-88fb-11eb-2591-c90c16e91d6e\nlet N = 20, dt = 0.2 / N, Tfinal = 30.0, u0 = x -> exp(-10*(1 + cos(x)))\n\txp = xgrid(200)\n\tk = kgrid(N)\n\tÛ0 = triginterp(u0, N)\n\tÛ1 = Û0  # zero initial velocity \n\t@gif for n = 1:ceil(Int, Tfinal / dt)\n    \tÛ0, Û1 = Û1, 2 * Û1 - Û0 - dt^2 * k.^2 .* Û1 \n\t    plot(xp, evaltrig.(xp, Ref(Û1)), lw = 3, label = \"\", size = (400, 300), \n\t\t\t xlims = [0, 2*π], ylims = [-0.1, 1.1] )\n\tend every 5\t\t\t\nend\n\n# ╔═╡ ae55b0e4-88ff-11eb-36f0-152089e43c93\nmd\"\"\"\n\n### Inhomogeneous Transport Equation\n\n```math\n\tu_t + c(x) u_x = 0\n```\nFirst discretise in time using the Leapfrog scheme \n```math\n\t\\frac{u^{n+1} - u^{n-1}}{2 \\Delta t} + c (u^n)_x = 0.\n```\nNow we discretise both ``c`` and ``u^n`` using a trigonometric polynomials, ``c \\approx c_N`` and ``u^n \\approx u^n_N \\in \\mathcal{T}_N'``. We can easily apply ``d/dx`` in the Fourier domain, ``\\hat{U}_k^n \\to (i k) \\hat{U}_k^n``, but what can we do with the product ``c_N (u^n_N)_x``? The trick is to differentiate in the Fourier domain, but apply the product in real space, i.e., \n* Apply ``d/dx`` in Fourier space\n* Convert back to real space\n* apply pointwise multiplication at interpolation nodes\n\"\"\"\n\n# ╔═╡ 00f2a760-8907-11eb-3ed1-376e9bf97fa8\nlet N = 256,  dt = π/(4N), tmax = 16.0, \n\t\t\t\tcfun = x -> 0.2 + sin(x - 1)^2, \n\t\t\t\t  u0 = x ->  exp(-100*(x-1)^2)\n\tX = xgrid(N)\n\tK = kgrid(N)\n\tt = 0.0\n\t# differentiation operator in Fourier space \n\tD̂ = im*K\n\t\n\t# transport coefficient in real space \n\tC = cfun.(X)\n\t# initial condition, we also need one additional v in the past\n\t# (this takes one step of the PDE backward in time)\n\tV = u0.(X)\n\tVold = V + dt * C .* real.( ifft( D̂ .* fft(V) ) ) \n\t\n\tfunction plot_soln(t, X, v, c)\n\t\tP = plot( xaxis = ([0, 2*π], ), yaxis = ([0.0, 1.5],) )\n\t\tplot!(X, 0.5*c, lw=1, c=:black, label = L\"c/2\")\n\t\tplot!(X, v, lw=3, label = L\"v\", size = (500, 300))\n\t\treturn P\n\tend\n\t\n\t# time-stepping loop\n\t@gif for t = 0:dt:tmax\n\t\t# differentiation in reciprocal space\n\t\tW = real.( ifft( D̂ .* fft(V) ) )   \n\t\t# multiplication and update in real space\n\t\tV, Vold = Vold - 2 * dt * C .* W, V\n\t\tplot_soln(t, X, V, C)\n\tend every 20\nend\n\n# ╔═╡ babc0fae-88ff-11eb-0516-6b7841fc0a6a\nmd\"\"\"\n\n### Nonlinear BVP\n\nSteady state viscous Burgers equation\n```math\n\t\tu u_x = \\epsilon u_{xx} - 0.1 \\sin(x)\n```\nWe write a nonlinear system \n```math\n\tF_j := u_N(x_j) u_{N,x}(x_j) - \\epsilon u_{N,xx}(x_j) + 0.1 sin(x)\n```\nand use a generic nolinear solver to solve\n```math\n\tF_j = 0, \\qquad j = 0, \\dots, 2N-1.\n```\nThis is not a magic bullet, often one needs specialized tools to solve these resulting nonlinear systems.\n\"\"\"\n\n\n# ╔═╡ 7d7d43e2-8a71-11eb-2031-f76c30b64f5e\n# using SIAMFANLEquations  # we use this package to solve nonlinear systems\n\n# ╔═╡ f2dab6a0-890a-11eb-1e48-a747d18f6c93\nlet N = 30, ϵ = 0.1\n\tfunction burger(U)\n\t\tN = length(U) ÷ 2 \n\t\tk = kgrid(N)\n\t\tÛ = fft(U) \n\t\tF = sin.(xgrid(N))\n\t\treturn real.(U .* ifft( im * k .* Û ) + ϵ * ifft( k.^2 .* Û ) .+ 0.1*F)\n\tend\n\tU0 = sin.(xgrid(N))\n\tU = nsoli(burger, U0, maxit = 1_000)\n\tÛ = fft(U) / (2N)\n\tplot(x -> evaltrig(x, Û), -π, π, lw=3, size = (400, 150), \n\t     label = \"Residual = \" * @sprintf(\"%.2e\\n\", norm(burger(U), Inf)), \n\t\t xlabel = L\"x\", ylabel = L\"u(x)\")\nend \n\n# ╔═╡ 7b5b1e6c-86b7-11eb-2b32-610393a24da4\nmd\"\"\"\n\n## §2.5 Outlook: PDEs in higher dimension\n\nJust one example; more in §4 of this course.\n\n### 2D Wave equation \n\n```math\n\tu_{tt} = u_{xx} + u_{yy}\n```\nDiscrete fourier transform for ``u(x, y)`` becomes ``\\hat{U}_{k_1 k_2}``. \nAfter discretising in time and space, and transforming to the Fourier domain, \n```math\n\t\\frac{\\hat{U}_{k_1k_2}^{n+1} - 2 \\hat{U}_{k_1k_2}^n + \\hat{U}^{n-1}_{k_1 k_2}}{\\Delta t^2} \n\t=  -(k_1^2 + k_2^2) \\hat{U}_{k_1 k_2}.\n```\n\"\"\"\n\n# ╔═╡ b90093f6-8906-11eb-2e69-6d4b807866a4\nlet N = 64, u0 = (x, y) -> exp(-10*(1 + cos(x))) * exp.(-10*(1 + cos(y)))\n\tx = xgrid(N); Xx = kron(x, ones(2*N)'); Xy = Xx'\n\tk = kgrid(N); Kx = kron(k, ones(2*N)'); Ky = Kx'\n\tU0 = u0.(Xx, Xy)\n\tÛ0 = fft(U0)\n\tÛ1 = Û0  # zero initial velocity \n\tdt = 0.2 / N \n\t@gif for n = 1:4_000\n\t\tÛ0, Û1 = Û1, 2 * Û1 - Û0 - dt^2 * (Kx.^2 + Ky.^2) .* Û1 \n\t\tPlots.surface(x, x, real.(ifft(Û1)), zlims = [-0.3, 0.3], color=:viridis, \n\t\t\t\t\t  size = (400, 300))\n\tend every 5\nend\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nBenchmarkTools = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\nDataFrames = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nFFTW = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nForwardDiff = \"f6369f11-7733-5829-9624-2563aa707210\"\nLaTeXStrings = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nPrettyTables = \"08abe8d2-0d0c-5749-adfa-8a2ac140af0d\"\nPrintf = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\nSIAMFANLEquations = \"084e46ad-d928-497d-ad5e-07fa361a48c4\"\n\n[compat]\nBenchmarkTools = \"~1.3.0\"\nDataFrames = \"~1.3.2\"\nFFTW = \"~1.4.5\"\nForwardDiff = \"~0.10.25\"\nLaTeXStrings = \"~1.3.0\"\nPlots = \"~1.25.8\"\nPlutoUI = \"~0.7.34\"\nPrettyTables = \"~1.3.1\"\nSIAMFANLEquations = \"~0.4.3\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\njulia_version = \"1.7.1\"\nmanifest_format = \"2.0\"\n\n[[deps.AbstractFFTs]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"6f1d9bc1c08f9f4a8fa92e3ea3cb50153a1b40d4\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"1.1.0\"\n\n[[deps.AbstractPlutoDingetjes]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"8eaf9f1b4921132a4cff3f36a1d9ba923b14a481\"\nuuid = \"6e696c72-6542-2067-7265-42206c756150\"\nversion = \"1.1.4\"\n\n[[deps.Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"af92965fb30777147966f58acb05da51c5616b5f\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.3\"\n\n[[deps.ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[deps.ArrayLayouts]]\ndeps = [\"FillArrays\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"e1ba79094cae97b688fb42d31cbbfd63a69706e4\"\nuuid = \"4c555306-a7a7-4459-81d9-ec55ddd5c99a\"\nversion = \"0.7.8\"\n\n[[deps.Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[deps.BandedMatrices]]\ndeps = [\"ArrayLayouts\", \"FillArrays\", \"LinearAlgebra\", \"Random\", \"SparseArrays\"]\ngit-tree-sha1 = \"ce68f8c2162062733f9b4c9e3700d5efc4a8ec47\"\nuuid = \"aae01518-5342-5314-be14-df237901396f\"\nversion = \"0.16.11\"\n\n[[deps.Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[deps.BenchmarkTools]]\ndeps = [\"JSON\", \"Logging\", \"Printf\", \"Profile\", \"Statistics\", \"UUIDs\"]\ngit-tree-sha1 = \"be0cff14ad0059c1da5a017d66f763e6a637de6a\"\nuuid = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\nversion = \"1.3.0\"\n\n[[deps.Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[deps.Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"4b859a208b2397a7a623a03449e4636bdb17bcf2\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+1\"\n\n[[deps.ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"f9982ef575e19b0e5c7a98c6e75ee496c0f73a93\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.12.0\"\n\n[[deps.ChangesOfVariables]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"bf98fa45a0a4cee295de98d4c1462be26345b9a1\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.2\"\n\n[[deps.ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"12fc73e5e0af68ad3137b886e3f7c1eacfca2640\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.17.1\"\n\n[[deps.ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[deps.Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[deps.CommonSubexpressions]]\ndeps = [\"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"7b8a93dba8af7e3b42fecabf646260105ac373f7\"\nuuid = \"bbf7d656-a473-5ed7-a52c-81e309532950\"\nversion = \"0.3.0\"\n\n[[deps.Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"44c37b4636bc54afac5c574d2d02b625349d6582\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.41.0\"\n\n[[deps.CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[deps.Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[deps.Crayons]]\ngit-tree-sha1 = \"249fe38abf76d48563e2f4556bebd215aa317e15\"\nuuid = \"a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f\"\nversion = \"4.1.1\"\n\n[[deps.DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[deps.DataFrames]]\ndeps = [\"Compat\", \"DataAPI\", \"Future\", \"InvertedIndices\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"Markdown\", \"Missings\", \"PooledArrays\", \"PrettyTables\", \"Printf\", \"REPL\", \"Reexport\", \"SortingAlgorithms\", \"Statistics\", \"TableTraits\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"ae02104e835f219b8930c7664b8012c93475c340\"\nuuid = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nversion = \"1.3.2\"\n\n[[deps.DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"3daef5523dd2e769dad2365274f760ff5f282c7d\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.11\"\n\n[[deps.DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[deps.Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[deps.DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[deps.DiffResults]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"c18e98cba888c6c25d1c3b048e4b3380ca956805\"\nuuid = \"163ba53b-c6d8-5494-b064-1a9d43ac40c5\"\nversion = \"1.0.3\"\n\n[[deps.DiffRules]]\ndeps = [\"IrrationalConstants\", \"LogExpFunctions\", \"NaNMath\", \"Random\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"84083a5136b6abf426174a58325ffd159dd6d94f\"\nuuid = \"b552c78f-8df3-52c6-915a-8e097449b14b\"\nversion = \"1.9.1\"\n\n[[deps.Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[deps.DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[deps.Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[deps.EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[deps.Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ae13fcbc7ab8f16b0856729b050ef0c446aa3492\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.4.4+0\"\n\n[[deps.FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[deps.FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[deps.FFTW]]\ndeps = [\"AbstractFFTs\", \"FFTW_jll\", \"LinearAlgebra\", \"MKL_jll\", \"Preferences\", \"Reexport\"]\ngit-tree-sha1 = \"463cb335fa22c4ebacfd1faba5fde14edb80d96c\"\nuuid = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nversion = \"1.4.5\"\n\n[[deps.FFTW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea\"\nuuid = \"f5851436-0d7a-5f13-b9de-f02708fd171a\"\nversion = \"3.3.10+0\"\n\n[[deps.FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"deed294cde3de20ae0b2e0355a6c4e1c6a5ceffc\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.12.8\"\n\n[[deps.FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[deps.Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[deps.Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[deps.ForwardDiff]]\ndeps = [\"CommonSubexpressions\", \"DiffResults\", \"DiffRules\", \"LinearAlgebra\", \"LogExpFunctions\", \"NaNMath\", \"Preferences\", \"Printf\", \"Random\", \"SpecialFunctions\", \"StaticArrays\"]\ngit-tree-sha1 = \"1bd6fc0c344fc0cbee1f42f8d2e7ec8253dda2d2\"\nuuid = \"f6369f11-7733-5829-9624-2563aa707210\"\nversion = \"0.10.25\"\n\n[[deps.FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[deps.FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[deps.Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[deps.GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"51d2dfe8e590fbd74e7a842cf6d13d8a2f45dc01\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.6+0\"\n\n[[deps.GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"RelocatableFolders\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"4a740db447aae0fbeb3ee730de1afbb14ac798a1\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.63.1\"\n\n[[deps.GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"aa22e1ee9e722f1da183eb33370df4c1aeb6c2cd\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.63.1+0\"\n\n[[deps.GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[deps.Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[deps.Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"a32d672ac2c967f3deb8a81d828afc739c838a06\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+2\"\n\n[[deps.Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[deps.Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[deps.HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"0fa77022fe4b511826b39c894c90daf5fce3334a\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.17\"\n\n[[deps.HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"129acf094d168394e80ee1dc4bc06ec835e510a3\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+1\"\n\n[[deps.Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[deps.HypertextLiteral]]\ngit-tree-sha1 = \"2b078b5a615c6c0396c77810d92ee8c6f470d238\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.3\"\n\n[[deps.IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[deps.IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[deps.IntelOpenMP_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d979e54b71da82f3a65b62553da4fc3d18c9004c\"\nuuid = \"1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0\"\nversion = \"2018.0.3+2\"\n\n[[deps.InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[deps.InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.2\"\n\n[[deps.InvertedIndices]]\ngit-tree-sha1 = \"bee5f1ef5bf65df56bdd2e40447590b272a5471f\"\nuuid = \"41ab1584-1d38-5bbf-9106-f11c6c58b48f\"\nversion = \"1.1.0\"\n\n[[deps.IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[deps.IterTools]]\ngit-tree-sha1 = \"fa6287a4469f5e048d763df38279ee729fbd44e5\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.4.0\"\n\n[[deps.IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[deps.JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"abc9885a7ca2052a736a600f7fa66209f96506e1\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.4.1\"\n\n[[deps.JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"3c837543ddb02250ef42f4738347454f95079d4e\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.3\"\n\n[[deps.JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b53380851c6e6664204efb2e62cd24fa5c47e4ba\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.2+0\"\n\n[[deps.LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[deps.LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[deps.LaTeXStrings]]\ngit-tree-sha1 = \"f2355693d6778a178ade15952b7ac47a4ff97996\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.3.0\"\n\n[[deps.Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a8f4f279b6fa3c3c4f1adadd78a621b13a506bce\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.9\"\n\n[[deps.LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[deps.LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[deps.LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[deps.LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[deps.LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[deps.Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[deps.Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"0b4a5d71f3e5200a7dff793393e09dfc2d874290\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+1\"\n\n[[deps.Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[deps.Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[deps.Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[deps.Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[deps.Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[deps.Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[deps.Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[deps.LinearAlgebra]]\ndeps = [\"Libdl\", \"libblastrampoline_jll\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[deps.LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"e5718a00af0ab9756305a0392832c8952c7426c1\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.6\"\n\n[[deps.Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[deps.MKL_jll]]\ndeps = [\"Artifacts\", \"IntelOpenMP_jll\", \"JLLWrappers\", \"LazyArtifacts\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"5455aef09b40e5020e1520f551fa3135040d4ed0\"\nuuid = \"856f044c-d86e-5d09-b602-aeab76dc8ba7\"\nversion = \"2021.1.1+2\"\n\n[[deps.MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[deps.Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[deps.MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[deps.MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[deps.Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[deps.Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[deps.Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[deps.MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[deps.NaNMath]]\ngit-tree-sha1 = \"b086b7ea07f8e38cf122f5016af580881ac914fe\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.7\"\n\n[[deps.NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[deps.Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"887579a3eb005446d514ab7aeac5d1d027658b8f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+1\"\n\n[[deps.OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[deps.OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[deps.OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"648107615c15d4e09f7eca16307bc821c1f718d8\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.13+0\"\n\n[[deps.OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[deps.Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[deps.OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[deps.PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[deps.Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"13468f237353112a01b2d6b32f3d0f80219944aa\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.2.2\"\n\n[[deps.Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[deps.Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[deps.PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[deps.PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"6f1b25e8ea06279b5689263cc538f51331d7ca17\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.1.3\"\n\n[[deps.Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\", \"UnicodeFun\", \"Unzip\"]\ngit-tree-sha1 = \"eb1432ec2b781f70ce2126c277d120554605669a\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.25.8\"\n\n[[deps.PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"ColorTypes\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"8979e9802b4ac3d58c503a20f2824ad67f9074dd\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.34\"\n\n[[deps.PooledArrays]]\ndeps = [\"DataAPI\", \"Future\"]\ngit-tree-sha1 = \"db3a23166af8aebf4db5ef87ac5b00d36eb771e2\"\nuuid = \"2dfb63ee-cc39-5dd5-95bd-886bf059d720\"\nversion = \"1.4.0\"\n\n[[deps.Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"2cf929d64681236a2e074ffafb8d568733d2e6af\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.3\"\n\n[[deps.PrettyTables]]\ndeps = [\"Crayons\", \"Formatting\", \"Markdown\", \"Reexport\", \"Tables\"]\ngit-tree-sha1 = \"dfb54c4e414caa595a1f2ed759b160f5a3ddcba5\"\nuuid = \"08abe8d2-0d0c-5749-adfa-8a2ac140af0d\"\nversion = \"1.3.1\"\n\n[[deps.Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[deps.Profile]]\ndeps = [\"Printf\"]\nuuid = \"9abbd945-dff8-562f-b5e8-e1ebf5ef1b79\"\n\n[[deps.Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[deps.REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[deps.Random]]\ndeps = [\"SHA\", \"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[deps.RecipesBase]]\ngit-tree-sha1 = \"6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.2.1\"\n\n[[deps.RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"37c1631cb3cc36a535105e6d5557864c82cd8c2b\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.5.0\"\n\n[[deps.Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[deps.RelocatableFolders]]\ndeps = [\"SHA\", \"Scratch\"]\ngit-tree-sha1 = \"cdbd3b1338c72ce29d9584fdbe9e9b70eeb5adca\"\nuuid = \"05181044-ff0b-4ac5-8273-598c1e38db00\"\nversion = \"0.1.3\"\n\n[[deps.Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.3.0\"\n\n[[deps.SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[deps.SIAMFANLEquations]]\ndeps = [\"AbstractFFTs\", \"BandedMatrices\", \"FFTW\", \"LaTeXStrings\", \"LinearAlgebra\", \"Printf\", \"SparseArrays\", \"SuiteSparse\", \"Test\"]\ngit-tree-sha1 = \"f2a95ba91c2b4fb67858762cb9db976f372c7eb8\"\nuuid = \"084e46ad-d928-497d-ad5e-07fa361a48c4\"\nversion = \"0.4.3\"\n\n[[deps.Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[deps.Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[deps.SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[deps.Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[deps.Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[deps.SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[deps.SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[deps.SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"8d0c8e3d0ff211d9ff4a0c2307d876c99d10bdf1\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"2.1.2\"\n\n[[deps.StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"a635a9333989a094bddc9f940c04c549cd66afcf\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.3.4\"\n\n[[deps.Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[deps.StatsAPI]]\ngit-tree-sha1 = \"d88665adc9bcf45903013af0982e2fd05ae3d0a6\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.2.0\"\n\n[[deps.StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"51383f2d367eb3b444c961d485c565e4c0cf4ba0\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.14\"\n\n[[deps.StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"d21f2c564b21a202f4677c0fba5b5ee431058544\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.4\"\n\n[[deps.SuiteSparse]]\ndeps = [\"Libdl\", \"LinearAlgebra\", \"Serialization\", \"SparseArrays\"]\nuuid = \"4607b0f0-06f3-5cda-b6b1-a6196a1729e9\"\n\n[[deps.TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[deps.TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[deps.Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"bb1064c9a84c52e277f1096cf41434b675cd368b\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.6.1\"\n\n[[deps.Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[deps.Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[deps.URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[deps.UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[deps.Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[deps.UnicodeFun]]\ndeps = [\"REPL\"]\ngit-tree-sha1 = \"53915e50200959667e78a92a418594b428dffddf\"\nuuid = \"1cfade01-22cf-5700-b092-accc4b62d6e1\"\nversion = \"0.4.1\"\n\n[[deps.Unzip]]\ngit-tree-sha1 = \"34db80951901073501137bdbc3d5a8e7bbd06670\"\nuuid = \"41fe7b60-77ed-43a1-b4f0-825fd5a5650d\"\nversion = \"0.1.2\"\n\n[[deps.Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[deps.Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"66d72dc6fcc86352f01676e8f0f698562e60510f\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.23.0+0\"\n\n[[deps.XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[deps.XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[deps.Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[deps.Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[deps.Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[deps.Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[deps.Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[deps.Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[deps.Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[deps.Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[deps.Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[deps.Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[deps.Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[deps.Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[deps.Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[deps.Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[deps.Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[deps.Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[deps.Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[deps.Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[deps.Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[deps.Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e45044cd873ded54b6a5bac0eb5c971392cf1927\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.2+0\"\n\n[[deps.libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[deps.libblastrampoline_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"OpenBLAS_jll\"]\nuuid = \"8e850b90-86db-534c-a0d3-1478176c7d93\"\n\n[[deps.libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[deps.libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[deps.libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"b910cb81ef3fe6e78bf6acee440bda86fd6ae00c\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+1\"\n\n[[deps.nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[deps.p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[deps.x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[deps.x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[deps.xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─3f1cfd12-7b86-11eb-1371-c5795b87ef5b\n# ╟─76e9a7f6-86a6-11eb-2741-6b8759be971b\n# ╟─04b54946-86a7-11eb-1de0-2f61e7b8f790\n# ╟─d57bead8-86b3-11eb-3095-1fee9108c6b1\n# ╠═10164e58-86ab-11eb-24c7-630872bf513d\n# ╠═7b0578ee-8744-11eb-0bf1-555f11fbb0fd\n# ╠═13e8fc40-86ab-11eb-1f63-9d2ed7538e7e\n# ╠═c3e57120-86ab-11eb-2268-4f7338540556\n# ╟─fc6671fa-8748-11eb-3d6b-e50f405b446f\n# ╟─96d114ee-8748-11eb-05f8-a72869439a84\n# ╟─6da69574-86b4-11eb-3300-9b1d62ede475\n# ╠═3c81eca4-86b5-11eb-0e54-d53593b063bc\n# ╟─c93dbae2-86b5-11eb-1468-bd709534e1af\n# ╟─a18b061c-86b5-11eb-3c44-0bc846854b1b\n# ╟─bc30cf3c-86b6-11eb-1f21-ff29b647a839\n# ╟─e02f56bc-86b6-11eb-3a66-0d0b94677262\n# ╟─240250ae-86b7-11eb-1046-7f29472897fd\n# ╟─5ebefefe-86b7-11eb-227f-3d5e02a142fd\n# ╟─452c65b2-8806-11eb-2d7a-3f4312071cd1\n# ╟─503b45d0-8e65-11eb-0e77-15314d82de1a\n# ╟─f3c1ba14-8e64-11eb-33ea-4341480e50b3\n# ╠═b5359ee2-86de-11eb-1446-b10b9815f448\n# ╟─0c84dcde-86e0-11eb-1877-932742501593\n# ╟─bb33932c-8769-11eb-0fb7-a39703fa96cc\n# ╠═a0e33748-8769-11eb-26b4-416a32282bc2\n# ╟─9a6facbe-876b-11eb-060a-7b7e717237be\n# ╟─f63dcd36-8ac8-11eb-3831-57f0a5088c98\n# ╟─33f2ab24-8ac9-11eb-220e-e71d3ebb93fa\n# ╟─a0797ece-8ac9-11eb-2922-e3f0295d4787\n# ╟─057c7508-8aca-11eb-0718-21826e314bc7\n# ╟─59485024-8aca-11eb-2e65-3962c096e9df\n# ╟─c9a6c2ce-876b-11eb-182c-d90997ea2cab\n# ╟─5b3e4e06-8e6e-11eb-0f31-5546b0ae450a\n# ╟─6deea4c4-86b7-11eb-0fe7-5d6d0f3007ef\n# ╟─7620d684-88fe-11eb-212d-efcbc1803608\n# ╠═42513412-88fb-11eb-2591-c90c16e91d6e\n# ╟─ae55b0e4-88ff-11eb-36f0-152089e43c93\n# ╠═00f2a760-8907-11eb-3ed1-376e9bf97fa8\n# ╟─babc0fae-88ff-11eb-0516-6b7841fc0a6a\n# ╠═7d7d43e2-8a71-11eb-2031-f76c30b64f5e\n# ╠═f2dab6a0-890a-11eb-1e48-a747d18f6c93\n# ╟─7b5b1e6c-86b7-11eb-2b32-610393a24da4\n# ╠═b90093f6-8906-11eb-2e69-6d4b807866a4\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "5b4813ffc33fd4f748de3fd57ee711f9f7676006", "size": 61692, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "pluto/ata_02_spectral.jl", "max_stars_repo_name": "cortner/ApxThyApp", "max_stars_repo_head_hexsha": "0b28c5c4370eb4d9c5a9063c2c5c1b938aa54a3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-12T18:12:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T18:12:15.000Z", "max_issues_repo_path": "pluto/ata_02_spectral.jl", "max_issues_repo_name": "cortner/ApxThyApp", "max_issues_repo_head_hexsha": "0b28c5c4370eb4d9c5a9063c2c5c1b938aa54a3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-03T22:23:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T01:58:58.000Z", "max_forks_repo_path": "pluto/ata_02_spectral.jl", "max_forks_repo_name": "cortner/ApxThyApp", "max_forks_repo_head_hexsha": "0b28c5c4370eb4d9c5a9063c2c5c1b938aa54a3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2929061785, "max_line_length": 525, "alphanum_fraction": 0.7043214679, "num_tokens": 26808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7545162045865029}}
{"text": "# Duffing resonance curves\nusing DrWatson\n@quickactivate \"NonlinearDynamicsTextbook\"\ninclude(srcdir(\"style.jl\"))\nusing DynamicalSystems, PyPlot\n\nfunction amplitude_curve(d,a,ωvec,ntrans,nattr,nres,y_init)\n    nω = length(ωvec) # no. of driving frequencies (control parameter)\n    amp_vec = zeros(nω)    # oscillation amplitudes (to be computed)\n    ds = Systems.duffing(; d, f = a)\n\n    for iω = 1:nω\n        ω = ωvec[iω]\n        set_parameter!(ds, 1, ω) # sets the ω parameter\n        period = 2π/ω\n        Δt = period/nres\n        tr = trajectory(ds, nattr*period, y_init; Ttr = ntrans*period)\n        amp_vec[iω] = maximum(u[1] for u in tr)\n        y_init = tr[end]\n    end\n    return amp_vec\nend\n\n@time begin\n# parameters and initial values\nd = 0.1\nomega_min = 0.02\nomega_max = 3.3 \nnomega = 1500 # 1500\nωvec = [LinRange(omega_min, omega_max, nomega); LinRange(omega_max, omega_min, nomega)]\navec = [1.1, 0.2, 0.04]\nccol = [COLORS[3], COLORS[2], COLORS[1]]\nntrans = 400   # no. of transient periods\nnattr  = 2     # no. of periods on the attractor\nnres   = 300   # resolution\namps = []\n\n# compute resonance curves\nfor ia = 1:length(avec)\n    a = avec[ia]\n    y_init = [0.1, 0.1]\n    amp_vec = amplitude_curve(d,a,ωvec,ntrans,nattr,nres,y_init)\n    push!(amps, amp_vec)\nend\nend\n\n# %% plot\nfig = figure(figsize=(0.55*figx,figy))\nax = gca()\nax.set_xlabel(L\"\\omega\") \nax.set_ylabel(\"\\$x_{\\\\mathrm{max}}\\$\")\n\nfor ia = 1:length(avec)\n    a = avec[ia]\n    ax.scatter(ωvec,amps[ia],s=2,c=ccol[ia], label = \"\\$a=$(avec[ia])\\$\")\nend\nax.set_xlim([0,omega_max])\nax.legend(markerscale = 10)\nfig.tight_layout(pad=0.3)\n\nwsave(plotsdir(\"9\", \"duffing_resonance\"), fig)\n", "meta": {"hexsha": "e817a7fbd877fa4996ed3a9c6c0c72435b78fd48", "size": 1656, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "figure_generation/9/9.1.jl", "max_stars_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_stars_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 88, "max_stars_repo_stars_event_min_datetime": "2021-07-18T20:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T09:23:53.000Z", "max_issues_repo_path": "figure_generation/9/9.1.jl", "max_issues_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_issues_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figure_generation/9/9.1.jl", "max_forks_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_forks_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-07-28T18:49:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:45:11.000Z", "avg_line_length": 26.7096774194, "max_line_length": 87, "alphanum_fraction": 0.6527777778, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7545162036792932}}
{"text": "#=  ADMM Algorithmic Regularization Paths for Sparse Statistical Machine Learning\r\n#   Yue Hu, Eric C. Chi and Genevera I. Allen\r\n#   arXiv:1504.06637v1\r\n# 3.2 Reduced-Rank Multi-Task Learning\r\n  Goal:  fit for B in Y = X*B+eps\r\n  n # num iid samples\r\n  p # num covariates\r\n  q # num outcomes\r\n# Algorithm 4 Algorithmic Regularization Path for Reduced-Rank Regression\r\n  1. Initialize: Z0 = 0, U0 = 0, g0 = e, and step size t > 0.\r\n  2. Precompute: H = (XTX=n+I)􀀀1 and HXTY.\r\n  3. While kZkk 6= 0\r\n     gk = gk􀀀1 +t (or gk = gk􀀀1t).\r\n     Bk = HXTY+H(Zk􀀀1􀀀Uk􀀀1).\r\n     Zk = SVTgk (Bk+Uk􀀀1). (Record Zk at each iteration.)\r\n  Uk = Uk􀀀1+Bk􀀀Uk\r\n  end\r\n  4. Output fZk : k = 1; \u0001 \u0001 \u0001 ;Kg as the algorithmic regularization path.\r\n=#\r\n\r\n# Singular Value Treshold of A w/ constant gammma\r\nfunction SVT(A::Array,gamma::Float64)\r\n    fac = svdfact(A)\r\n    fac[:U]*(diagm(max(0,fac[:S].-gamma)))*fac[:Vt]\r\nend\r\n\r\nfunction fit_arp_rrr{T<:Number}(X::Array{T,2}, Y::Array{T,2}; stepsize::Float64 =1.05, gamma_init::Float64 =0.01, max_itterations::Integer=200, min_active::Integer=0, verbose::Bool=false)\r\n  @assert size(X,1) == size(Y,1)\r\n  n = size(X,1)\r\n  p = size(X,2)\r\n  q = size(Y,2)\r\n  gamma_list = zeros(T,max_itterations)\r\n  chisq_list = zeros(T,max_itterations)\r\n  Z_list = zeros(max_itterations,p,q)\r\n  B = zeros(p,q)  # Preallocate working matrices\r\n  Z = zeros(p,q)\r\n  U = zeros(p,q)\r\n  H = inv(X'*X/n+diagm(ones(p)))\r\n  HXtY = H*X'*Y\r\n  gamma = gamma_init\r\n  last_itteration = max_itterations\r\n  for k in 1:max_itterations\r\n    gamma = gamma * stepsize\r\n    B = HXtY+H*(Z-U)\r\n    Z = SVT(B+U,gamma)\r\n    gamma_list[k]= gamma\r\n    Z_list[k,:,:] = Z\r\n    U = U + B - Z\r\n    num_active = length(find(Z))\r\n    if verbose\r\n      chisq = sumabs2(Y-X*Z)\r\n      print(\"# \", k, \" \", gamma,\": \")\r\n      print(\"Z norms= \", num_active, \" \", sumabs(Z), \" \", sumabs2(Z), \" chi^2= \", chisq, \" \")\r\n      #print(\"B=\",B,\" Z=\",Z,\" U=\",U,\" \")\r\n      println(\"\")\r\n    end\r\n    if sumabs2(Z) == 0. || num_active < min_active\r\n      last_itteration = k\r\n      break\r\n    end\r\n  end\r\n  # resize to last_itteration?\r\n  return (gamma_list,Z_list)\r\nend\r\n\r\n#= Test orig alg\r\n n = 25\r\n p = 4\r\n q = 3\r\n X = randn(n,p)\r\n B = make_B(p,q,frac_active = 0.1)\r\n Y = X*B + 0.01*randn(n,q)\r\n println(\"B norms: \", length(find(B)), \"  \", sumabs(B), \" \", sumabs2(B))\r\n\r\n(gamma_list, Z_list)  = fit_arp_rrr(X,Y, max_itterations = 200)\r\n print_path(gamma_list, Z_list)\r\n=#\r\n ", "meta": {"hexsha": "85b37f5ac5082e38bb5f6bf613a0082a77d9fc50", "size": 2432, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/alg_regression_path/reduced_rank_multitask_learning.jl", "max_stars_repo_name": "eford/RVSpectraKitLearn", "max_stars_repo_head_hexsha": "fbefd32bba0b725c2a892bd14606632f8f062db0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/alg_regression_path/reduced_rank_multitask_learning.jl", "max_issues_repo_name": "eford/RVSpectraKitLearn", "max_issues_repo_head_hexsha": "fbefd32bba0b725c2a892bd14606632f8f062db0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/alg_regression_path/reduced_rank_multitask_learning.jl", "max_forks_repo_name": "eford/RVSpectraKitLearn", "max_forks_repo_head_hexsha": "fbefd32bba0b725c2a892bd14606632f8f062db0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1794871795, "max_line_length": 188, "alphanum_fraction": 0.5933388158, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7544873998413527}}
{"text": "#Generate a random positive definite matrix\n\"\"\"\n    randposdefmatrix(D)\n    randposdefmatrix(::DataType, D)\n\nGenerate a random ``DxD`` positive definite matrix. `::DataType` can be `Float32` or `Float64`, default is `Float64`.\n\"\"\"\nfunction randposdefmatrix(Ftype::DataType, ndim::Int)\n    a = randn(Ftype,ndim,ndim)\n    A = a*a' + LinearAlgebra.I(ndim)\n    return A\nend\n\nrandposdefmatrix(ndim::Int) = randposdefmatrix(Float64,ndim)\n\n#computes Quadratic term - x'Ax\n\"\"\"\n    xAx(x,A)\n\nCompute the scalar quadratic term x'Ax given a real vector `x` and a square matrix `A`. The dimensions of `x` and `A` must match.\n\"\"\"\nfunction xAx(x::AbstractVector{T}, A::AbstractMatrix{T}) where {T}\n    s = zero(T)\n    @turbo for i ∈ eachindex(x), j ∈ eachindex(x)\n        s += x[i]*x[j]*A[j,i]\n    end\n    return s\nend\n\n#computes Square Mahalanobis distance (x-y)'A(x-y)\n\"\"\"\n    sqmahaldist(x,y,A)\n\nCompute the square of the Mahalanobis distance between two real vectors `x` and `y` given a positive semidefinite matrix `A`. Dimensions of `x`, `y` and `A` must match. Square of the Mahalanobis distance is given by ``(x-y)'A(x-y)``.\n\"\"\"\nfunction sqmahaldist(x::AbstractVector{T}, y::AbstractVector{T}, A::AbstractMatrix{T}) where {T}\n    s = zero(T)\n    @turbo for i ∈ eachindex(x,y), j ∈ eachindex(x,y)\n        Ti = x[i] - y[i]\n        Tj = x[j] - y[j]\n        s += Ti*Tj*A[j,i]\n    end\n    return s\nend\n\n\n\"\"\"\n    mahaldist(x,y,A)\n\nCompute the Mahalanobis distance between two real vectors `x` and `y` given a positive semidefinite matrix `A`. Dimensions of `x`, `y` and `A` must match. Mahalanobis distance is given by ``sqrt((x-y)'A(x-y))``.\n\"\"\"\nmahaldist(x::AbstractVector{T}, y::AbstractVector{T}, A::AbstractMatrix{T}) where {T} = sqrt(sqmahaldist(x,y,A))", "meta": {"hexsha": "bd90835e5abaa801311d2e1ee3b5b1215bdcd5ca", "size": 1747, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/quadratic_forms.jl", "max_stars_repo_name": "vidhyasaharan/VectorDataUtils.jl", "max_stars_repo_head_hexsha": "aca5ae177446bf5db37f2cd823579679baa6830a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/quadratic_forms.jl", "max_issues_repo_name": "vidhyasaharan/VectorDataUtils.jl", "max_issues_repo_head_hexsha": "aca5ae177446bf5db37f2cd823579679baa6830a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/quadratic_forms.jl", "max_forks_repo_name": "vidhyasaharan/VectorDataUtils.jl", "max_forks_repo_head_hexsha": "aca5ae177446bf5db37f2cd823579679baa6830a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5961538462, "max_line_length": 233, "alphanum_fraction": 0.6576989124, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7544873910645283}}
{"text": "\n\"\"\"\n    corr = v2r(cov)\n\nConvert a covariance matrix `cov` to the correlation matrix `corr`.\nThis is a wrapper of `StatsBase.cov2cor.`\n\"\"\"\nfunction v2r(C::Matrix{T}) where {T<:AbstractFloat}\n   s = sqrt.(diag(C))\n   R = StatsBase.cov2cor(C, s)\n   return R\nend\nfunction c2r(C::Matrix{T}) where {T<:AbstractFloat}\n   return v2r(C)\nend\n\n\"\"\"\n    cov = r2v(corr, stdev)\n\nConvert a correlation matrix `cov` and the vector of standard deviation `stdev` to the covariance matrix `cov`.\nThis is a wrapper of `StatsBase.cor2cov.`\n\"\"\"\nfunction r2v(C::Matrix{T}, s::Vector{T}) where {T<:AbstractFloat}\n   return StatsBase.cor2cov(C,s)\nend\nfunction r2c(C::Matrix{T}, s::Vector{T}) where {T<:AbstractFloat}\n   return r2v(C,s)\nend\n\n\"\"\"\n   v = vech(A)\n\nConvert a square matrix to a half-stored vector.\nIt was written by Steven G. Johnson; see `https://discourse.julialang.org/t/half-vectorization/7399` for details.\n\"\"\"\nfunction vech(A::AbstractMatrix{T}) where T\n   m = LinearAlgebra.checksquare(A)\n   v = zeros(T,((m*(m+1))>>1))\n   k = 0\n   for j = 1:m, i = j:m\n       @inbounds v[k += 1] = A[i,j]\n   end\n   return v\nend\n\n# CS 4220/Math 4260 Numerical Analysis: Linear and Nonlinear Problems\n# by Charles Van Loan\n# http://www.cs.cornell.edu/courses/cs4220/2014sp/CVLBook/chap7.pdf\n\"\"\"\n     dv,ev = chol_symtrid(T::SymTridiagonal)\n\nCalculate the Cholesky factor of a symmetric tridiagonal matrix.\nNote that the factor is a lower tridiagonal matrix, and the output is a couple of vectors.\nThe factor is stored in `dv` for the diagonal matrix (D) and in `ev` for the off-diagonal elements (L).     \n\"\"\"\nfunction chol_symtrid(T::SymTridiagonal)\n   n = length(T.dv)\n   dv = zeros(n)\n   ev = zeros(n-1)\n   dv[1] = sqrt(T.dv[1])\n   for i=2:n\n      ev[i-1] = T.ev[i-1]/dv[i-1]\n      dv[i] = sqrt(T.dv[i] - ev[i-1]^2)\n   end\n   return dv,ev\nend\n\n# The Tridiagonal LDL T Calculus for the Indefinite Generalized Symmetric Eigenproblem\n# By Peter Strobach\n# https://www.researchgate.net/publication/271196070_THE_TRIDIAGONAL_LDL_T_CALCULUS_FOR_THE_INDEFINITE_GENERALIZED_SYMMETRIC_EIGENPROBLEM\n\"\"\"\n    dv,ev = ldlt_symtrid(T::SymTridiagonal)\n\nCalculate the LDLT factor of a symmetric tridiagonal matrix.\nNote that the factor is a lower tridiagonal matrix, and the output is a couple of vectors.\nThe factor is stored in `dv` for the diagonal matrix (D) and in `ev` for the off-diagonal elements (L).\n\"\"\"\nfunction ldlt_symtrid(T::SymTridiagonal)\n   n = length(T.dv)\n   dv = zeros(n)\n   ev = zeros(n-1)\n   dv[1] = T.dv[1]\n   for i=1:n-1\n      ev[i] = T.ev[i]/dv[i]\n      dv[i+1] = T.dv[i+1] - (ev[i]^2)*dv[i]\n   end\n   return dv,ev\nend\n\n# Takahashi method for the LDLT factor\n\"\"\"\n    takahashi_ldlt_symtrid!(dv,ev)\n\nCompute the sparse inverse (as known as selected inverse) of the LDLT factor of a symmetric trigiagonal matrix.\nThe LDLT factor is stored in two vectors (`dv` and `ev`), which should be calculated with `ldlt_symtrid`.\n\"\"\"\nfunction takahashi_ldlt_symtrid!(dv,ev)\n   n = size(dv,1)\n   dv[n] = 1/dv[n]\n   for i=n-1:-1:1\n      evi = ev[i]\n      ev[i] = -evi*dv[i+1]\n      dv[i] = 1/dv[i] - evi*ev[i]\n   end\nend\n\nfunction get_invT11_fast(T::SymTridiagonal)\n   dv,ev = ldlt_symtrid(T::SymTridiagonal)\n   takahashi_ldlt_symtrid!(dv,ev)\n   return dv[1]\nend\n\n\"\"\"\n    bentB = bending(B [, W], gamma=nothing, tol=eps, verbose=false)\n    bentB = bending(B, gamma=nothing, tol=eps, verbose=false)\n\nApply a traditional \"bending\" method to a symmetric matrix `B` (between-group-variance) using another symmetric matrix `W` (within-group-variance), as described by Hayes and Hill (1981).\nThe resulting matrix is `bentB = (1-gamma)*B + gamma*v*W`, where `v` is the average eigenvalues of `B` and `gamma` is a constant between 0 and 1, which can be provided by the user or generated by this function.\nWhen `W` is omitted, the identity matrix will be used instead.\n\nIf the user supplies `gamma`, the function will simply apply the bending formula and return `bentB` without checking whether `bentB` is positive defnite or not.\nOtherwise (`gamma=nothing`), this function generates `gamma=1/1000`, applies bending, and returns `bentB` if it is positive definite as `minimum(eigen(bentB).values)>tol` (the default `tol` is the machine epsilon).\nIf not, the function tries `gamma=2/1000`, `gamma=3/1000`, ..., and `gamma=1000/1000` until `bentB` becomes positive definite.\n\nWith `verbose=true`, this function prints `v` (average eigenvalue of `B`) and `gamma` that has been used for bending (default: `verbose=false`).\n\"\"\"\nfunction bending(B::Matrix{Tv}, W=I(size(B,1)); gamma::Union{Nothing,Float64}=nothing, verbose::Bool=false, tol=eps(one(Tv))) where Tv<:AbstractFloat\n   if !issymmetric(B)\n      throw(ArgumentError(\"B must be symmetric.\"))\n   end\n   if !issymmetric(W)\n      throw(ArgumentError(\"W must be symmetric.\"))\n   end\n\n   v = mean(eigen(B).values)\n   if verbose; println(\"mean(eig(B)): $(v)\"); end\n   if !isnothing(gamma)\n      if gamma<0 || gamma>1\n         throw(ArgumentError(\"gamma should be between 0 and 1.\"))\n      else\n         if verbose; println(\"gamma: $(gamma)\"); end\n         M = (1-gamma)*B + gamma*v*W\n         return M\n      end\n   end\n\n   M = copy(B)\n   if minimum(eigen(M).values)>tol\n      return M\n   end\n\n   for i=1000:-1:1\n      g = 1/i\n      M .= (1-g)*B + g*v*W\n      if minimum(eigen(M).values)>tol\n         if verbose; println(\"gamma: $(g)\"); end\n         return M\n      end\n   end\n\n   return M\nend\n\n\"\"\"\n    bentV = bending2(V [, W], corr=false, mineig=eps, tol=eps, maxiter=10000, force=false, verbose=false)\n\nApply an alternative \"bending\" method to a variance-covariance matrix `V` using a weighting matrix `W`, as described by Jorjani et al. (2003).\nWhen omitting `W`, `J` (matrix of ones) will be used, implying the same weights for all elements.\nJorjani et al. (2003) suggested `W` as the reciprocal of number of individuals used in the estimation of covariances.\n\nThe function calculates the eigenvalues of `V`, and an eigenvalue is replaced with `mineig` if it is smaller than `mineig`.\nThe covariance matrix is reconstructed with modified eigenvalues, then tests whether it is positive definite by checking the minimum eigenvalue larger than `tol`.\nThe function repeats the process until the resulting matrix becomes positive definite, and the number of maximum iterations is defind by `maxiter`.\n\nSee some options below.\n\n- With `corr=true`, this function assumes the input is a correlation matrix; otherwise, the input is expected to be a variance-covariance matrix.\n- With `force=true`, this function iterates the formula `maxiter` times regardless of whether it has converged or not.\n- With `verbose=true`, this function shows the number of iterations required when `force=false`.\n\"\"\"\nfunction bending2(V::Matrix{Tv}, W=ones(size(V,1),size(V,2)); mineig=eps(one(Tv)), tol=eps(one(Tv)), corr=false, maxiter=10000, force=false, verbose=false) where Tv<:AbstractFloat\n   if !issymmetric(V)\n      throw(ArgumentError(\"B must be symmetric.\"))\n   end\n   if !issymmetric(W)\n      throw(ArgumentError(\"W must be symmetric.\"))\n   end\n   if size(V) != size(W)\n      throw(DimensionMismatch(\"V and W\"))\n   end\n\n   if corr\n      dim = size(V,1)\n      Rprev = copy(V)\n      Rn = copy(V)\n      Rnew = copy(V)\n      Dn = zeros(Tv,dim)\n      Δn = zeros(Tv,dim)\n      for i=1:maxiter\n         (D, U) = eigen(Rprev)\n         Dn .= D\n         Dn[ D .< tol ] .= 2*mineig\n         Δn .= Dn * (sum(D)/sum(Dn))\n         Rn .= Rprev - ((Rprev - U*diagm(Δn)*U') .* W)\n         Rnew = v2r(Rn)\n         if !force && minimum(eigen(Rnew).values)>tol\n            if verbose; println(\"round: $(i)\"); end\n            break\n         end\n         Rprev .= Rnew\n      end\n      return Rnew\n   else\n      Vprev = copy(V)\n      Vnew = copy(V)\n      for i=1:maxiter\n         (D, U) = eigen(Vprev)\n         D[ D .< tol ] .= mineig\n         Vnew .= Vprev - ((Vprev - U*diagm(D)*U') .* W)\n         if !force && minimum(eigen(Vnew).values)>tol\n            if verbose; println(\"round: $(i)\"); end\n            break\n         end\n         Vprev .= Vnew\n      end\n      return Vnew\n   end\nend\n", "meta": {"hexsha": "c80be04031603f9e525c9f83825c3ecfa746ea01", "size": 8067, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tools.jl", "max_stars_repo_name": "masuday/AnimalBreedingTools.jl", "max_stars_repo_head_hexsha": "68265523af2483a58c3e5a786515bc99385644dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tools.jl", "max_issues_repo_name": "masuday/AnimalBreedingTools.jl", "max_issues_repo_head_hexsha": "68265523af2483a58c3e5a786515bc99385644dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools.jl", "max_forks_repo_name": "masuday/AnimalBreedingTools.jl", "max_forks_repo_head_hexsha": "68265523af2483a58c3e5a786515bc99385644dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2270742358, "max_line_length": 214, "alphanum_fraction": 0.6617081939, "num_tokens": 2430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7544873846205408}}
{"text": "using Distributions, LinearAlgebra, Compat, Expectations\n\n# A default utility function\n\nfunction u(c, σ)\n    if c > 0\n        return (c^(1 - σ) - 1) / (1 - σ)\n    else\n        return -10e6\n    end\nend\n\n# default wage vector with probabilities\n\nconst n = 60                                           # n possible outcomes for wage\nconst default_w_vec = range(10, 20, length = n) # wages between 10 and 20\nconst a, b = 600, 400                                  # shape parameters\nconst dist = BetaBinomial(n-1, a, b)\n\nmutable struct McCallModel{TF <: AbstractFloat,\n                           TAV <: AbstractVector{TF}}\n    α::TF         # Job separation rate\n    β::TF         # Discount rate\n    γ::TF         # Job offer rate\n    c::TF         # Unemployment compensation\n    σ::TF         # Utility parameter\n    w_vec::TAV    # Possible wage values\n\n    McCallModel(α::TF = 0.2,\n                β::TF = 0.98,\n                γ::TF = 0.7,\n                c::TF = 6.0,\n                σ::TF = 2.0,\n                w_vec::TAV = default_w_vec,\n                ) where {TF, TAV} =\n        new{TF, TAV}(α, β, γ, c, σ, w_vec)\nend\n\nfunction update_bellman!(mcm, V, V_new, U, E)\n    # Simplify notation\n    α, β, σ, c, γ = mcm.α, mcm.β, mcm.σ, mcm.c, mcm.γ\n\n    for (w_idx, w) in enumerate(mcm.w_vec)\n        # w_idx indexes the vector of possible wages\n        V_new[w_idx] = u(w, σ) + β * ((1 - α) * V[w_idx] + α * U)\n    end\n\n    U_new = u(c, σ) + β * (1 - γ) * U +\n            β * γ * E*max.(U, V)\n    return U_new\nend\n\nfunction solve_mccall_model(mcm; tol = 1e-5, max_iter = 2000)\n\n    V = ones(length(mcm.w_vec))    # Initial guess of V\n    V_new = similar(V)             # To store updates to V\n    U = 1.0                        # Initial guess of U\n    i = 0\n    error = tol + 1\n    E = expectation(dist, nodes = mcm.w_vec)\n\n    while error > tol && i < max_iter\n        U_new = update_bellman!(mcm, V, V_new, U, E)\n        error_1 = maximum(abs, V_new - V)\n        error_2 = abs(U_new - U)\n        error = max(error_1, error_2)\n        V[:] = V_new\n        U = U_new\n        i += 1\n    end\n\n    return V, U\nend\n", "meta": {"hexsha": "b044ea9e0587862411fedd41c7924c58c0b14dc8", "size": 2115, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "rst_files/_static/code/mccall/mccall_bellman_iteration.jl", "max_stars_repo_name": "yywingliang/lecture-source-jl", "max_stars_repo_head_hexsha": "d5859ef7b82b4f130eec34cacd1dc0f2b9f1af22", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rst_files/_static/code/mccall/mccall_bellman_iteration.jl", "max_issues_repo_name": "yywingliang/lecture-source-jl", "max_issues_repo_head_hexsha": "d5859ef7b82b4f130eec34cacd1dc0f2b9f1af22", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rst_files/_static/code/mccall/mccall_bellman_iteration.jl", "max_forks_repo_name": "yywingliang/lecture-source-jl", "max_forks_repo_head_hexsha": "d5859ef7b82b4f130eec34cacd1dc0f2b9f1af22", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5810810811, "max_line_length": 85, "alphanum_fraction": 0.5054373522, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7544208145920446}}
{"text": "# # Sensitivity Analysis of Ridge Regression\n\n#md # [![](https://img.shields.io/badge/show-github-579ACA.svg)](@__REPO_ROOT_URL__/docs/src/examples/sensitivity-analysis-ridge.jl)\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/generated/sensitivity-analysis-ridge.ipynb)\n\n# This example illustrates the sensitivity analysis of data points in a\n# [Ridge Regression](https://en.wikipedia.org/wiki/Ridge_regression) problem.\n# The general form of the problem is given below:\n\n# ```math\n# \\begin{split}\n# \\begin{array} {ll}\n# \\mbox{minimize} & \\sum_{i=1}^{N} (y_{i} - w x_{i} - b)^2 + \\alpha (w^2 + b^2) \\\\\n# \\end{array}\n# \\end{split}\n# ```\n# where\n# - `w`, `b` are slope and intercept of the regressing line\n# - `x`, `y` are the N data points\n# - `α` is the regularization constant\n#\n# which is equivalent to:\n# ```math\n# \\begin{split}\n# \\begin{array} {ll}\n# \\mbox{minimize} & e^{\\top}e + \\alpha (w^2 + b^2) \\\\\n# \\mbox{s.t.} & e_{i} = y_{i} - w x_{i} - b \\quad \\quad i=1..N  \\\\\n# \\end{array}\n# \\end{split}\n# ```\n\n\n# This tutorial uses the following packages\n\nusing JuMP\nimport DiffOpt\nimport Random\nimport OSQP\nimport Plots\nimport LinearAlgebra: normalize!, dot\n\n# ## Define and solve the problem\n\n# Construct a set of noisy (guassian) data points around a line.\n\nRandom.seed!(42)\n\nN = 100\n\nw = 2 * abs(randn())\nb = rand()\nX = randn(N)\nY = w * X .+ b + 0.8 * randn(N);\n\n# The helper method `fit_ridge` defines and solves the corresponding model.\n# The ridge regression is modeled with quadratic programming\n# (quadratic objective and linear constraints) and solved in generic methods\n# of OSQP. This is not the standard way of solving the ridge regression problem\n# this is done here for didactic purposes.\n\nfunction fit_ridge(X, Y, alpha = 0.1)\n    N = length(Y)\n    ## Initialize a JuMP Model with OSQP solver\n    model = Model(() -> DiffOpt.diff_optimizer(OSQP.Optimizer))\n    set_silent(model)\n    @variable(model, w) # angular coefficient\n    @variable(model, b) # linear coefficient\n    @variable(model, e[1:N]) # approximation error\n    ## constraint defining approximation error\n    @constraint(model, cons[i=1:N], e[i] == Y[i] - w * X[i] - b)\n    ## objective minimizing squared error and ridge penalty\n    @objective(\n        model,\n        Min,\n        dot(e, e) + alpha * (sum(w * w) + sum(b * b)),\n    )\n    optimize!(model)\n    return model, w, b, cons # return model, variables and constraints references\nend\n\n\n# Train on the data generated.\n\nmodel, w, b, cons = fit_ridge(X, Y)\nŵ, b̂ = value(w), value(b)\n\n# We can visualize the approximating line.\n\np = Plots.scatter(X, Y, label=\"\")\nmi, ma = minimum(X), maximum(X)\nPlots.plot!(p, [mi, ma], [mi * ŵ + b̂, ma * ŵ + b̂], color=:red, label=\"\")\n\n\n# ## Differentiate\n\n# Now that we've solved the problem, we can compute the sensitivity of optimal\n# values of the angular coefficient `w` with\n# respect to perturbations in the data points (`x`,`y`).\n\n# Begin differentiating the model.\n# analogous to varying θ in the expression:\n# ```math\n# e_i = (y_{i} + \\theta_{y_i}) - w (x_{i} + \\theta_{x_{i}}) - b\n# ```\n\n∇ = zero(X)\nfor i in 1:N\n    for j in 1:N\n        MOI.set(\n            model,\n            DiffOpt.ForwardInConstraint(),\n            cons[j],\n            i == j ? index(w) + 1.0 : 0.0 * index(w)\n        )\n    end\n    DiffOpt.forward(model)\n    dw = MOI.get(\n        model,\n        DiffOpt.ForwardOutVariablePrimal(),\n        w\n    )\n    ∇[i] = abs(dw)\nend\n\nnormalize!(∇);\n\n# Visualize point sensitivities with respect to regressing line.\n# Note that the gradients are normalized.\n\np = Plots.scatter(\n    X, Y,\n    color = [x > 0 ? :red : :blue for x in ∇],\n    markersize = [25 * abs(x) for x in ∇],\n    label = \"\"\n)\nmi, ma = minimum(X), maximum(X)\nPlots.plot!(p, [mi, ma], [mi * ŵ + b̂, ma * ŵ + b̂], color = :red, label = \"\")\n\n# Note the points in the extremes of the line segment are larger because\n# moving those points has a stronger effect on the angular coefficient of the line.\n", "meta": {"hexsha": "f6e326552cc72a27025703ab049a53f2978d914d", "size": 4001, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/sensitivity-analysis-ridge.jl", "max_stars_repo_name": "JinraeKim/DiffOpt.jl", "max_stars_repo_head_hexsha": "cf808b04c122a73500cdd4db9bc269b63ee3b709", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/src/examples/sensitivity-analysis-ridge.jl", "max_issues_repo_name": "JinraeKim/DiffOpt.jl", "max_issues_repo_head_hexsha": "cf808b04c122a73500cdd4db9bc269b63ee3b709", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/src/examples/sensitivity-analysis-ridge.jl", "max_forks_repo_name": "JinraeKim/DiffOpt.jl", "max_forks_repo_head_hexsha": "cf808b04c122a73500cdd4db9bc269b63ee3b709", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3758865248, "max_line_length": 133, "alphanum_fraction": 0.639340165, "num_tokens": 1216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7544208059326647}}
{"text": "\"\"\"\n    sample mean\n\"\"\"\nfunction sample_mean(X)\n    N = length(X)\n    n = length(X[1])\n    μ = sum(X) ./ N\n    return μ\nend\n\n\"\"\"\n    sample covariance\n\"\"\"\nfunction sample_covariance(X, β)\n    N = length(X)\n    μ = sample_mean(X)\n    P = sum([(X[i] - μ) * (X[i] - μ)' for i = 1:N]) ./ (2.0 * β^2.0)\n    return P\nend\n\n\"\"\"\n    deterministic sampling\n\"\"\"\nfunction resample(X, β)\n    n = length(X[1])\n    μ = sample_mean(X)\n    P = sample_covariance(X, β)\n    cols = sqrt(P)\n    Xs = [μ + s * β * cols[:,i] for s in [-1.0, 1.0] for i = 1:n]\n    return Xs\nend\n\nfunction resample_vec(X, n, N, β)\n    _X = [X[(i - 1) * n .+ (1:n)] for i = 1:N]\n    return vcat(resample(_X, β)...)\nend\n\nfunction resample_vec(X, n, N, β, k)\n    _X = [X[(i - 1) * n .+ (1:n)] for i = 1:N]\n    Xs = resample(_X, β)\n    return Xs[k]\nend\n\nfunction resample(μ, P, β::T) where T\n    n = length(μ)\n    cols = sqrt(P)\n    Xs = [μ + s * β * cols[:,i] for s in [-1.0, 1.0] for i = 1:n]\n    return Xs\nend\n", "meta": {"hexsha": "8b1d6ecfc84ac1f37fdc3a06b8671fb339eceb0c", "size": 967, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unscented.jl", "max_stars_repo_name": "zacmanchester/DirectMotionPlanning", "max_stars_repo_head_hexsha": "fd8ef76ab5023d6ac175a72f9e870f986e1a67d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-18T16:01:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:36:10.000Z", "max_issues_repo_path": "src/unscented.jl", "max_issues_repo_name": "zacmanchester/DirectMotionPlanning", "max_issues_repo_head_hexsha": "fd8ef76ab5023d6ac175a72f9e870f986e1a67d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/unscented.jl", "max_forks_repo_name": "zacmanchester/DirectMotionPlanning", "max_forks_repo_head_hexsha": "fd8ef76ab5023d6ac175a72f9e870f986e1a67d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.34, "max_line_length": 68, "alphanum_fraction": 0.5077559462, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.8459424314825852, "lm_q1q2_score": 0.7544208042007884}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.5\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 51ab86a0-af67-11eb-2542-018f2a541d80\nbegin\n\tusing LinearAlgebra\n\tusing Plots\n\tusing Printf\n\tusing IJulia\nend\n\n# ╔═╡ 13dac5b4-d8bb-4668-9aa8-1d2a5ce6b59d\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nfunction toeplitz(el,e,eu,n)\n\tdl = el*ones(n-1);\n\tdu = eu*ones(n-1);\n\td = e * ones(n);\n\tA = Tridiagonal(dl,d,du);\n\treturn A;\nend\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n# ╔═╡ de0276af-306d-4758-96b0-d76e024a5291\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nfunction generate_b(n)\n\tb = ones(n);\n\treturn b;\nend\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n# ╔═╡ ae0165b3-6a37-4da5-bb07-22c3cce19a7b\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nfunction jacobi(A,b,u0)\n\titer = 0;\n\tres = 1;\n\titerations = 1e3;\n\teps = 1e-12;\n\tn = length(b);\n\ty_old = u0;\n\ty_new = zeros(n);\n\tlogs_res = zeros(Int(iterations)); \n\twhile(iter<iterations && res>eps)\n\t\tfor i=1:n\n\t\t\te = zeros(n);\n\t\t\tMM = zeros(n);\n\t\t\tfor j=1:n \n\t\t\t\tMM[i] += A[i,j]*y_old[j];\n\t\t\tend\n\t\t\te[i] = (1/A[i,i])*(b[i] - MM[i]); \n\t\t\ty_new[i] = y_old[i] + e[i]; \n\n\t\tend\n\t\ty_old = y_new;\n\t\tres = norm(b - A*y_old,2);\n\t\titer = iter + 1;\n\t\tlogs_res[iter] = res; \n\tend\n\t#printf(\"Exiting at iterations number %d\\n\",iter);\n\treturn y_new,logs_res; \nend\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n# ╔═╡ b17e0683-c34c-43e7-9170-cd8a5a293a17\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\nfunction jacobi_ω(A,b,x0,ω)\n\titerations = 1e3; \n\teps = 1e-12;\n\titer = 0;\n\tres = 1;\n\tn = length(b); \n\ty_old = x0;\n\ty_new = y_old; \n\tlogs_res = zeros(Int(iterations)); \n\twhile(res>eps && iter<iterations)\n\t\tfor i=1:n \n\t\t\te = zeros(n);\n\t\t\tMM = zeros(n);\n\t\t\tfor j=1:n \n\t\t\t\tMM[i] += A[i,j]*y_old[j];\n\t\t\tend\n\t\t\te[i] = (ω/A[i,i])*(b[i] - MM[i]);\n\t\t\ty_new[i] = y_old[i] + e[i]; \n\t\tend\n\t\ty_old = y_new;\n\t\tres = norm(b-A*y_old,1);\n\t\titer = iter + 1;\n\t\tlogs_res[iter] = res; \n\tend\n\treturn y_new , logs_res; \nend\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n# ╔═╡ b38689ac-e045-4ae6-845f-e11a8a902a39\nbegin\n\t# Main function\n\tn = 25;\n\tA = toeplitz(-1,2,-1,n);\n\tb = generate_b(n);\n\titerations = 1e3;\n\tdomain = 1:iterations;\n\tIC = ones(n); \n\tω = 0.5;\n\tω1 = 1.7;\n\tω_range = 0.1:0.2:1;\n\tω1_range = 0.1:0.3:2; \nend\n\n# ╔═╡ acb70cc7-8a6c-4eb2-8451-c3637a36b129\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\nfunction gauss(A,b,x0)\n\titer = 0 ;\n\teps = 1e-12;\n\tres = 1;\n\titerations = 1e3;\n\ty = x0; \n\tlogs_res = zeros(Int(iterations));\n\twhile(iter<iterations && res > eps)\n\t\tfor i=1:n \n\t\t\te = zeros(n);\n\t\t\tMM = zeros(n); \n\t\t\tfor j=1:n \n\t\t\t\tMM[i] += A[i,j]*y[j];  \t\n\t\t\tend\n\t\t\te[i] = (1/A[i,i])*(b[i] - MM[i]);\n\t\t\ty[i] = y[i] + e[i]; \n\t\tend\n\t\tres = norm(b - A*y,2);\n\t\titer = iter + 1;\n\t\tlogs_res[iter] = res; \n\tend\n\treturn y,logs_res; \nend\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n# ╔═╡ 944d3e05-1ddc-422c-9207-a819f5341254\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nfunction gauss_ω(A,b,x0,ω)\n\titer = 0 ;\n\teps = 1e-12;\n\tres = 1;\n\titerations = 1e3;\n\ty = x0; \n\tlogs_res = zeros(Int(iterations));\n\twhile(iter<iterations && res > eps)\n\t\tfor i=1:n \n\t\t\te = zeros(n);\n\t\t\tMM = zeros(n); \n\t\t\tfor j=1:n \n\t\t\t\tMM[i] += A[i,j]*y[j];  \t\n\t\t\tend\n\t\t\te[i] = (ω/A[i,i])*(b[i] - MM[i]);\n\t\t\ty[i] = y[i] + e[i]; \n\t\tend\n\t\tres = norm(b - A*y,1);\n\t\titer = iter + 1;\n\t\tlogs_res[iter] = res; \n\tend\n\treturn y,logs_res;\nend\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n# ╔═╡ 827ecd18-8b80-4fe6-b6e1-ed19fcb071cc\nbegin\n\t# Analytical solutions\n\tu = inv(A)*b;\n\tu = vcat(0,u,0)  # include BC to the solution \n\tx = LinRange(0,1,n+2); \n\tplot(x,u,label=\"Actual solution\")\nend\n\n# ╔═╡ 4240bfe8-eaef-454a-8113-68572ef822f2\n# Jacobi's and Gauss' solution and their weighted solutions \n\nbegin \n\ty,RES_j = jacobi(A,b,IC)\n\tplot(domain,RES_j,xaxis=:log,label=\"Jacobi\");\n\ty_g,RES = gauss(A,b,IC)\n\tplot!(domain,RES,xaxis=:log,label=\"Gauss\");\nend\n\n# ╔═╡ 3d9f8d64-c18f-40e4-8510-be3619caa190\n# Weighted Jacobi and Gauss Methods \nbegin\n\ty_j,RES_ja = jacobi_ω(A,b,IC,ω);\n\tplot(domain,RES_ja,xaxis=:log,label=\"Weighted Jacobi\");\n\ty_gr,RES_ga = gauss_ω(A,b,IC,ω1);\n\tplot!(domain,RES_ga,xaxis=:log,label=\"Weighted Gauss\");\nend\n\n# ╔═╡ 2e83adfa-c254-4a4f-9681-c140ed64b0dd\nbegin\n\ty_,R = jacobi_ω(A,b,IC,ω_range[1]);\n\tp1 = plot!(domain,R,xaxis=:log);\nend\n\n# ╔═╡ 7c9839b6-171d-4039-b5cb-7cf2a8278fac\nbegin\n\ty_1,R1 = gauss_ω(A,b,IC,ω_range[5]);\n\tp2 = plot!(domain,R1,xaxis=:log);\nend\n\n# ╔═╡ Cell order:\n# ╠═51ab86a0-af67-11eb-2542-018f2a541d80\n# ╠═13dac5b4-d8bb-4668-9aa8-1d2a5ce6b59d\n# ╠═de0276af-306d-4758-96b0-d76e024a5291\n# ╠═ae0165b3-6a37-4da5-bb07-22c3cce19a7b\n# ╠═acb70cc7-8a6c-4eb2-8451-c3637a36b129\n# ╠═b17e0683-c34c-43e7-9170-cd8a5a293a17\n# ╠═944d3e05-1ddc-422c-9207-a819f5341254\n# ╠═b38689ac-e045-4ae6-845f-e11a8a902a39\n# ╠═827ecd18-8b80-4fe6-b6e1-ed19fcb071cc\n# ╠═4240bfe8-eaef-454a-8113-68572ef822f2\n# ╠═3d9f8d64-c18f-40e4-8510-be3619caa190\n# ╠═2e83adfa-c254-4a4f-9681-c140ed64b0dd\n# ╠═7c9839b6-171d-4039-b5cb-7cf2a8278fac\n", "meta": {"hexsha": "de20fc4ea4eba09954e6232795665e5c09543161", "size": 5271, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Smoother.jl", "max_stars_repo_name": "dynamic-queries/Smoothers-Multigrids-and-all-that", "max_stars_repo_head_hexsha": "0964dcee0df44b4d9b1364a57a983756e56a8a78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Smoother.jl", "max_issues_repo_name": "dynamic-queries/Smoothers-Multigrids-and-all-that", "max_issues_repo_head_hexsha": "0964dcee0df44b4d9b1364a57a983756e56a8a78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Smoother.jl", "max_forks_repo_name": "dynamic-queries/Smoothers-Multigrids-and-all-that", "max_forks_repo_head_hexsha": "0964dcee0df44b4d9b1364a57a983756e56a8a78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.850678733, "max_line_length": 77, "alphanum_fraction": 0.5148928097, "num_tokens": 2185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7544208027996095}}
{"text": "\"\"\"\n    ellipsoid_level_set(image_shape::Tuple, center=nothing, semi_axis=nothing)\n\nInitialize a 2D or 3D ellipsoid for level set problems. Returns a \nbinary array.\n\n# Arguments\n- `image_shape::Tuple`: The 2D or 3D shape of the ellipsoid\n- `center::Tuple`: Coordinates for the center of the ellipsoid. Defaults to center of \n    of the image.\n- `semi-axis::Tuple`: Lengths of the semi-axis of the ellipsoid. Defaults to half of the\n    image dimensions.\n\"\"\"\nfunction ellipsoid_level_set(image_shape::Tuple, center=nothing, semi_axis=nothing)\n    if isnothing(center)\n        center = [i / 2 for i in image_shape]\n    else\n        center = collect(center)\n    end\n\n    if isnothing(semi_axis)\n        semi_axis = [i / 2 for i in image_shape]\n    else\n        semi_axis = collect(semi_axis)\n    end\n\n    length(center) == length(image_shape) ||\n        throw(ArgumentError(\"`center` and `image_shape` must have the same length.\"))\n\n    length(semi_axis) == length(image_shape) ||\n        throw(ArgumentError(\"`semi_axis` and `image_shape` must have the same length.\"))\n\n    if length(image_shape) == 2\n        xc, yc = center[1], center[2]\n        rx, ry = semi_axis[1], semi_axis[2]\n        phi = zeros(image_shape)\n        for x in 1:image_shape[1]\n            for y in 1:image_shape[2]\n                phi[x, y] = 1 - ((((x - 1) - xc) / rx)^2 + (((y - 1) - yc) / ry)^2)\n            end\n        end\n    elseif length(image_shape) == 3\n        xc, yc, zc = center[1], center[2], center[3]\n        rx, ry, rz = semi_axis[1], semi_axis[2], center[3]\n        phi = zeros(image_shape)\n        for x in 1:image_shape[1]\n            for y in 1:image_shape[2]\n                for z in 1:image_shape[3]\n                    phi[x, y, z] =\n                        1 - (\n                            (((x - 1) - xc) / rx)^2 +\n                            (((y - 1) - yc) / ry)^2 +\n                            (((z - 1) - zc) / rz)^2\n                        )\n                end\n            end\n        end\n    else\n        error(\"`image_shape` must be a 2- or 3-tuple.\")\n    end\n    res = phi .> 0\n    return res\nend\n\"\"\"\n    lazy_ellipsoid_level_set(image_shape, center=nothing, semi_axis=nothing)\n\nInitialize a 2D or 3D ellipsoid for level set problems. Returns a \nLazySets `Ellipsoid` type. ~~Probably faster than `ellipsoid_level_set`~~.\n\n# Arguments\n- `image_shape::Tuple`: The 2D or 3D shape of the ellipsoid\n- `center::Tuple`: Coordinates for the center of the ellipsoid. Defaults to center of \n    of the image.\n- `semi-axis::Tuple`: Lengths of the semi-axis of the ellipsoid. Defaults to half of the\n    image dimensions.\n\"\"\"\nfunction lazy_ellipsoid_level_set(image_shape::Tuple, center=nothing, semi_axis=nothing)\n    if isnothing(center)\n        center = [i / 2 for i in image_shape]\n    else\n        center = collect(center)\n    end\n\n    if isnothing(semi_axis)\n        semi_axis = [i / 2 for i in image_shape]\n    else\n        semi_axis = collect(semi_axis)\n    end\n\n    length(center) == length(image_shape) ||\n        throw(ArgumentError(\"`center` and `image_shape` must have the same length.\"))\n\n    length(semi_axis) == length(image_shape) ||\n        throw(ArgumentError(\"`semi_axis` and `image_shape` must have the same length.\"))\n\n    if length(image_shape) == 2\n        rx, ry = semi_axis\n        ellipse = Ellipsoid(center, Diagonal([rx^2, ry^2]))\n    elseif length(image_shape) == 3\n        rx, ry, rz = semi_axis\n        ellipse = Ellipsoid(center, Diagonal([rx^2, ry^2, rz^2]))\n    else\n        error(\"`image_shape` must be a 2- or 3-tuple.\")\n    end\n    return ellipse\nend\n\n\"\"\"\n    to_array(image_shape::Tuple, E::Ellipsoid)\n\nTurn an `Ellipsoid` type from LazySets.jl into an array\nwhere the pixels within the `Ellipsoid` are 1 and 0 everywhere\nelse\n\n# Arguments\n- `image_shape::Tuple`: The 2D or 3D shape of the `Ellipsoid`\n- `E::Ellipsoid`: LazySets `Ellipsoid` type\n\"\"\"\nfunction to_array(image_shape, E::Ellipsoid)\n    B = box_approximation(E)\n    Bs = split(B, collect(image_shape))\n    res = [center(Bi) in E for Bi in Bs]\n    M = reshape(res, image_shape)\n    return M\nend\n", "meta": {"hexsha": "f505f464b3eba1b68811a6498db5035f6852e74d", "size": 4090, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/initialization.jl", "max_stars_repo_name": "Dale-Black/ActiveContours.jl", "max_stars_repo_head_hexsha": "8cdfb1ea191dab5c2862bf4cd7244d9bcfc16a74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/initialization.jl", "max_issues_repo_name": "Dale-Black/ActiveContours.jl", "max_issues_repo_head_hexsha": "8cdfb1ea191dab5c2862bf4cd7244d9bcfc16a74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/initialization.jl", "max_forks_repo_name": "Dale-Black/ActiveContours.jl", "max_forks_repo_head_hexsha": "8cdfb1ea191dab5c2862bf4cd7244d9bcfc16a74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4603174603, "max_line_length": 88, "alphanum_fraction": 0.6080684597, "num_tokens": 1132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624791, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7544208017683229}}
{"text": "# This file is part of IntegerSequences.\n# Copyright Peter Luschny. License is MIT.\n\n(@__DIR__) ∉ LOAD_PATH && push!(LOAD_PATH, (@__DIR__))\n\n# Another demo for Julia's iteration protokoll.\n# Also demonstrates the layout of an IntegerSequences module.\n\nmodule NarayanaCows\nusing IterTools\nexport ModuleNarayanaCows, NarayanasCows, L214551\n\n\"\"\"\n* NarayanasCows, L214551\n\nFor background information see\n* J.-P. Allouche, T. Johnson, [Narayana's Cows and Delayed Morphisms](http://recherche.ircam.fr/equipes/repmus/jim96/actes/Allouche.ps).\n* C.M. Wilmott, [From Fibonacci to the mathematics of cows and quantum circuitry](https://iopscience.iop.org/article/10.1088/1742-6596/574/1/012097/pdf).\n\"\"\"\nconst ModuleNarayanaCows = \"\"\n\n\"\"\"\nThe type object to construct a new instance of the modified Narayanas cows sequence with given length.\n\"\"\"\nstruct NarayanasCows\n    length\nend\n\n\"\"\"\nReturn the first term of the modified Narayanas cows sequence.\n\"\"\"\nfunction Base.iterate(I::NarayanasCows)\n    I.length == 0 && return nothing\n    state = (1, (0, 0, 1, 1))\nend\n\n\"\"\"\nReturn the next term of the modified Narayanas cows sequence.\n\"\"\"\nfunction Base.iterate(I::NarayanasCows, (x, y, z, c))\n    c >= I.length && return nothing\n    x = div(z + x, gcd(z, x))\n    (x, (y, z, x, c + 1))\nend\n\nBase.length(f::NarayanasCows) = f.length\nBase.eltype(f::NarayanasCows) = Int\n\n\"\"\"\nReturn a list of the first n terms of the modified Narayanas cows sequence.\n\"\"\"\nL214551(n) = collect(NarayanasCows(n))\n\n#START-TEST-########################################################\n\nusing Test, SeqUtils\n\nfunction test()\n    @testset \"Narayana\" begin\n        @test IterTools.nth(NarayanasCows(12), 12) == 5\n    end\nend\n\nfunction demo()\n    for cow in NarayanasCows(20)\n        print(cow, \", \")\n    end\n    println()\n\n    L214551(20) |> println\n    println()\n\n    SeqShow(L214551(20))\nend\n\nfunction perf()\n    @time (for cow in NarayanasCows(10000) end)\nend\n\nfunction main()\n    test()\n    demo()\n    perf()\nend\n\nmain()\n\nend # module\n", "meta": {"hexsha": "a50979b6b0205442ef6c83d64e0be8d88391e47e", "size": 1999, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NarayanaCows.jl", "max_stars_repo_name": "UnofficialJuliaMirror/IntegerSequences.jl-b4b868b0-69a7-11e9-2db0-173b4e8e576c", "max_stars_repo_head_hexsha": "5718a938e44b1f14c7115f2940f96fa344b72ce8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NarayanaCows.jl", "max_issues_repo_name": "UnofficialJuliaMirror/IntegerSequences.jl-b4b868b0-69a7-11e9-2db0-173b4e8e576c", "max_issues_repo_head_hexsha": "5718a938e44b1f14c7115f2940f96fa344b72ce8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NarayanaCows.jl", "max_forks_repo_name": "UnofficialJuliaMirror/IntegerSequences.jl-b4b868b0-69a7-11e9-2db0-173b4e8e576c", "max_forks_repo_head_hexsha": "5718a938e44b1f14c7115f2940f96fa344b72ce8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4606741573, "max_line_length": 153, "alphanum_fraction": 0.6738369185, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7544208003671438}}
{"text": "# Diffusion maps\n# --------------\n# Diffusion maps,\n# Coifman, R. & Lafon, S., Applied and Computational Harmonic Analysis, Elsevier, 2006, 21, 5-30\n\n#### DiffMap type\nstruct DiffMap{T <: Real} <: AbstractDimensionalityReduction\n    t::Int\n    ɛ::T\n    K::AbstractMatrix{T}\n    proj::Projection{T}\n\n    DiffMap{T}(t::Int, ɛ::T, K::AbstractMatrix{T}, proj::Projection{T})  where T = new(t, ɛ, K, proj)\nend\n\n## properties\noutdim(R::DiffMap) = size(R.proj, 1)\n\n## custom\nkernel(R::DiffMap) = R.K\n\n## show\nsummary(io::IO, R::DiffMap) = print(io, \"Diffusion Maps(outdim = $(outdim(R)), t = $(R.t), ɛ = $(R.ɛ))\")\nfunction show(io::IO, R::DiffMap)\n    summary(io, R)\n    io = IOContext(io, :limit=>true)\n    println(io)\n    println(io, \"Kernel: \")\n    Base.print_matrix(io, R.K, \"[\", \",\",\"]\")\n    println(io)\n    println(io, \"Embedding:\")\n    Base.print_matrix(io, transform(R), \"[\", \",\",\"]\")\nend\n\n## interface functions\nfunction fit(::Type{DiffMap}, X::AbstractMatrix{T}; maxoutdim::Int=2, t::Int=1, ɛ::Real=1.0) where {T<:Real}\n    # rescale data\n    Xtr = standardize(StatsBase.UnitRangeTransform, X)\n    Xtr[findall(isnan, Xtr)] .= 0\n\n    # compute kernel matrix\n    sumX = sum(Xtr.^ 2, dims=1)\n    K = exp.(-( transpose(sumX) .+ sumX .- 2*transpose(Xtr) * Xtr ) ./ convert(T, ɛ))\n\n    p = transpose(sum(K, dims=1))\n    K ./= (p * transpose(p)) .^ convert(T, t)\n    p = transpose(sqrt.(sum(K, dims=1)))\n    K ./= p * transpose(p)\n\n    U, S, V = svd(K, full=true)\n    U ./= U[:,1]\n    Y = U[:,2:(maxoutdim+1)]\n\n    return DiffMap{T}(t, convert(T, ɛ), K, transpose(Y))\nend\n\ntransform(R::DiffMap) = R.proj\n", "meta": {"hexsha": "39f649231ae91b95bc2b72fd2c048209e6fcf379", "size": 1600, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/diffmaps.jl", "max_stars_repo_name": "adediego/ManifoldLearning.jl", "max_stars_repo_head_hexsha": "f7969c1b05897659beafa6491d875de5497be1da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/diffmaps.jl", "max_issues_repo_name": "adediego/ManifoldLearning.jl", "max_issues_repo_head_hexsha": "f7969c1b05897659beafa6491d875de5497be1da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/diffmaps.jl", "max_forks_repo_name": "adediego/ManifoldLearning.jl", "max_forks_repo_head_hexsha": "f7969c1b05897659beafa6491d875de5497be1da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5862068966, "max_line_length": 108, "alphanum_fraction": 0.589375, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.8459424314825852, "lm_q1q2_score": 0.754420794470926}}
{"text": "# Dantzig-Wolfe Reformulation and Column Generation\n# Data for General Assignment Problem 1\n# Edward J. Xu\n# 2019.5.1\n\n\nfunction getData()\n    vec_c = [6 4 6 1 3 4 1 2 8]\n    mat_a =[\n    1 0 0 1 0 0 1 0 0 ;\n    0 1 0 0 1 0 0 1 0 ;\n    0 0 1 0 0 1 0 0 1 ;\n    7 2 8 0 0 0 0 0 0 ;\n    0 0 0 8 7 6 0 0 0 ;\n    0 0 0 0 0 0 9 1 9]\n    vec_b = hcat([1;1;1;9;7;10])\n    index_sub = [[1,2,3], [4,5,6], [7,8,9]]\n    num_sub = 3\n    return (vec_c, mat_a, vec_b, index_sub, num_sub)\nend\n\n\n(vec_c, mat_a, vec_b, index_sub, num_sub) = getData()\n", "meta": {"hexsha": "49a483c03777c5ed3d2365543c645943ddb3daa6", "size": 533, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/dw/Data_GAP_1.jl", "max_stars_repo_name": "edxu96/MatrixOptim", "max_stars_repo_head_hexsha": "97ef8b1311351291427f8f650b0215c7ff00bddc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/dw/Data_GAP_1.jl", "max_issues_repo_name": "edxu96/MatrixOptim", "max_issues_repo_head_hexsha": "97ef8b1311351291427f8f650b0215c7ff00bddc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/dw/Data_GAP_1.jl", "max_forks_repo_name": "edxu96/MatrixOptim", "max_forks_repo_head_hexsha": "97ef8b1311351291427f8f650b0215c7ff00bddc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-04T09:41:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-04T09:41:13.000Z", "avg_line_length": 22.2083333333, "max_line_length": 53, "alphanum_fraction": 0.5609756098, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551957, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7544068379661173}}
{"text": "function GaussLobattoQuad(n)\nw=zeros(n+1,1);\nx=zeros(n+1,1);\nif n == 1\n      w[1]=1;\n      w[2]=1;\n      x[1]=-1;\n      x[2]=1;\n\nelseif n == 2\n      w[2]=4/3;\n      w[1]=1/3;\n      w[3]=1/3;\n\n      x[2]=0;\n      x[1]=-1;\n      x[3]=1;\n\nelseif n == 3\n      w[2]=5/6;\n      w[3]=5/6;\n      w[1]=1/6;\n      w[4]=1/6;\n\n      x[2]=-1/sqrt(5);\n      x[3]=1/sqrt(5);\n      x[1]=-1;\n      x[4]=1;\n\nelseif n == 4\n      w[3]=32/45;\n      w[2]=49/90;\n      w[4]=49/90;\n      w[1]=1/10;\n      w[5]=1/10;\n\n      x[3]=0;\n      x[2]=-sqrt(3/7);\n      x[4]=sqrt(3/7);\n      x[1]=-1;\n      x[5]=1;\n\nelseif n == 5\n      w[3]=(14+sqrt(7))/30;\n      w[4]=(14+sqrt(7))/30;\n      w[2]=(14-sqrt(7))/30;\n      w[5]=(14-sqrt(7))/30;\n      w[1]=1/15;\n      w[6]=1/15;\n\n      x[3]=-sqrt(1/3-2*sqrt(7)/21);\n      x[4]=sqrt(1/3-2*sqrt(7)/21);\n      x[2]=-sqrt(1/3+2*sqrt(7)/21);\n      x[5]=sqrt(1/3+2*sqrt(7)/21);\n      x[1]=-1;\n      x[6]=1;\n\nelseif n == 6\n      w[4]=256/525;\n      w[3]=(124+7*sqrt(15))/350;\n      w[5]=(124+7*sqrt(15))/350;\n      w[2]=(124-7*sqrt(15))/350;\n      w[6]=(124-7*sqrt(15))/350;\n      w[1]=1/21;\n      w[7]=1/21;\n\n      x[4]=0;\n      x[3]=-sqrt(5/11-2/11*sqrt(5/3));\n      x[5]=sqrt(5/11-2/11*sqrt(5/3));\n      x[2]=-sqrt(5/11+2/11*sqrt(5/3));\n      x[6]=sqrt(5/11+2/11*sqrt(5/3));\n      x[1]=-1;\n      x[7]=1;\n\n   else\n      error(\"ord1+ord2 zu gro oder zu klein\")\nend\nreturn (w,x)\nend\n\n", "meta": {"hexsha": "2abafb1f0ad67f1ab6e3ff56322b7daf694fe96b", "size": 1390, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DG/GaussLobattoQuad.jl", "max_stars_repo_name": "CliMA/CGDycore.jl", "max_stars_repo_head_hexsha": "77297631f8db7775f19daee2d7ac75bc810d9c11", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-05T07:09:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T07:09:16.000Z", "max_issues_repo_path": "src/DG/GaussLobattoQuad.jl", "max_issues_repo_name": "CliMA/CGDycore.jl", "max_issues_repo_head_hexsha": "77297631f8db7775f19daee2d7ac75bc810d9c11", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DG/GaussLobattoQuad.jl", "max_forks_repo_name": "CliMA/CGDycore.jl", "max_forks_repo_head_hexsha": "77297631f8db7775f19daee2d7ac75bc810d9c11", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1604938272, "max_line_length": 45, "alphanum_fraction": 0.3892086331, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7544068368346459}}
{"text": "#######################################################################################################################################################################################################\n#\n# Changes to this type\n# General\n#     2022-Jan-13: migrate abstract temperature dependency type from Photosynthesis.jl\n#     2022-Jan-25: fix documentation\n#\n#######################################################################################################################################################################################################\n\"\"\"\n\n$(TYPEDEF)\n\nHierachy of AbstractTemperatureDependency:\n- [`Arrhenius`](@ref)\n- [`ArrheniusPeak`](@ref)\n- [`Q10`](@ref)\n\"\"\"\nabstract type AbstractTemperatureDependency{FT<:AbstractFloat} end\n\n\n#######################################################################################################################################################################################################\n#\n# Changes to this struct\n# General\n#     2022-Jan-13: migrate from Photosynthesis.jl, rename to Arrhenius\n#     2022-Jan-13: define the struct mutable, use ΔHA directly in the struct, add field T_REF\n#     2022-Jan-25: fix documentation\n#\n#######################################################################################################################################################################################################\n\"\"\"\n\n$(TYPEDEF)\n\nAn [`Arrhenius`](@ref) type struct using\n```math\nY_1 = Y_0 \\\\cdot \\\\exp \\\\left( \\\\dfrac{H_a}{R T_0} - \\\\dfrac{H_a}{R T_1} \\\\right)\n```\n\n# Fields\n\n$(TYPEDFIELDS)\n\n\"\"\"\nmutable struct Arrhenius{FT<:AbstractFloat} <: AbstractTemperatureDependency{FT}\n    # parameters that do not change with time\n    \"Reference temperature `[K]`\"\n    T_REF::FT\n    \"Uncorrected vakye at reference temperature\"\n    VAL_REF::FT\n    \"Activation energy\"\n    ΔHA::FT\nend\n\n\n#######################################################################################################################################################################################################\n#\n# Changes to this struct\n# General\n#     2022-Jan-13: migrate from Photosynthesis.jl, rename to ArrheniusPeak\n#     2022-Jan-13: define the struct mutable, use ΔHA/ΔHD/ΔSV directly in the struct, add field T_REF/VAL_REF\n#     2022-Jan-25: fix documentation\n#     2022-Mar-01: fix documentation\n#\n#######################################################################################################################################################################################################\n\"\"\"\n\n$(TYPEDEF)\n\nAn [`ArrheniusPeak`](@ref) type struct using\n```math\nY_1 = Y_0 \\\\cdot \\\\exp \\\\left( \\\\dfrac{H_a}{R T_0} - \\\\dfrac{H_a}{R T_1} \\\\right)\n          \\\\cdot \\\\dfrac{ 1 + \\\\exp \\\\left( \\\\dfrac{S_v T_0 - H_d}{R T_0} \\\\right) }\n                        { 1 + \\\\exp \\\\left( \\\\dfrac{S_v T_1 - H_d}{R T_1} \\\\right) }\n```\n\n# Fields\n\n$(TYPEDFIELDS)\n\n\"\"\"\nmutable struct ArrheniusPeak{FT<:AbstractFloat} <: AbstractTemperatureDependency{FT}\n    # parameters that do not change with time\n    \"Reference temperature `[K]`\"\n    T_REF::FT\n    \"Uncorrected vakye at reference temperature\"\n    VAL_REF::FT\n    \"Activation energy\"\n    ΔHA::FT\n    \"Deactivation energy\"\n    ΔHD::FT\n    \"Entropy factor\"\n    ΔSV::FT\nend\n\n\n#######################################################################################################################################################################################################\n#\n# Changes to this struct\n# General\n#     2022-Jan-13: migrate from Photosynthesis.jl, rename to Q10\n#     2022-Jan-14: make structure mutable\n#     2022-Jan-25: fix documentation\n#\n#######################################################################################################################################################################################################\n\"\"\"\n\n$(TYPEDEF)\n\nAn [`Q10`](@ref) type struct using\n```math\nY_1 = Y_0 \\\\cdot Q_{10} ^ \\\\dfrac{T_1 - T_0}{10}\n```\n\n# Fields\n\n$(TYPEDFIELDS)\n\n\"\"\"\nmutable struct Q10{FT<:AbstractFloat} <: AbstractTemperatureDependency{FT}\n    # parameters that do not change with time\n    \"Reference temperature `[K]`\"\n    T_REF::FT\n    \"Uncorrected vakye at reference temperature\"\n    VAL_REF::FT\n    \"Power of Q10 correction\"\n    Q_10::FT\nend\n\n\n#######################################################################################################################################################################################################\n#\n# Changes to the constructors\n# General\n#     2022-Jan-14: migrate from Photosynthesis.jl\n#     2022-Feb-11: add temperature dependent Jmax and Vcmax TD from CLM\n# Sources\n#     Lavigne and Ryan (1997) Growth and maintenance respiration rates of aspen, blackspruce and jack pine stems at northern and southern BOREAS sites\n#     Bernacchi et al. (2001) Improved temperature response functions for models of Rubisco‐limited photosynthesis\n#     Boyd et al. (2001) Temperature responses of C4 photosynthesis: biochemical analysis of Rubisco, phosphoenolpyruvate carboxylase, and carbonic anhydrase in Setaria viridis\n#     Leuning (2002) Temperature dependence of two parameters in a photosynthesis model\n#     Kattge et al. (2007) Temperature acclimation in a biochemical model of photosynthesis: a reanalysis of data from 36 species\n#     Sperry et al. (2019) The impact of rising CO2 and acclimation on the response of US forests to global warming\n#     Johnson et al. (2021) The limiting factors and regulatory processes that control the environmental responses of C3, C3–C4 intermediate, and C4 photosynthesis\n#     CLM5 Documentation. Chapter 9 Page 106\n#\n#######################################################################################################################################################################################################\nKcTDBernacchi(FT)          = Arrhenius{FT}(T_25(), 41.0264925, 79430.0);\nKcTDCLM(FT)                = Arrhenius{FT}(T_25(), 40.49     , 79430.0);\nKoTDBernacchi(FT)          = Arrhenius{FT}(T_25(), 28208.88  , 36380.0);\nKoTDCLM(FT)                = Arrhenius{FT}(T_25(), 27840.0   , 36380.0);\nKpepTDCLM(FT)              = Arrhenius{FT}(T_25(), 8.0       , 36000.0);\nKpepTDBoyd(FT)             = Arrhenius{FT}(T_25(), 16.0      , 36300.0);\nKqTDJohnson(FT)            = Arrhenius{FT}(T_25(), 300       , 37000.0);\nRespirationTDBernacchi(FT) = Arrhenius{FT}(T_25(), NaN       , 46390.0);\nVcmaxTDBernacchi(FT)       = Arrhenius{FT}(T_25(), NaN       , 65330.0);\nVomaxTDBernacchi(FT)       = Arrhenius{FT}(T_25(), NaN       , 60110.0);\nΓStarTDBernacchi(FT)       = Arrhenius{FT}(T_25(), 4.33164375, 37830.0);\nΓStarTDCLM(FT)             = Arrhenius{FT}(T_25(), 4.275     , 37830.0);\n\nJmaxTDBernacchi(FT)                = ArrheniusPeak{FT}(T_25(), NaN , 57500.0, 439000.0, 1400.0);\nJmaxTDCLM(FT, t::Number = T_25())  = ArrheniusPeak{FT}(T_25(), NaN , 50000.0, 200000.0, 659.70 - 0.75 * (t - T_0()) );\nJmaxTDLeuning(FT)                  = ArrheniusPeak{FT}(T_25(), NaN , 50300.0, 152044.0, 495.0 );\nRespirationTDCLM(FT)               = ArrheniusPeak{FT}(T_25(), NaN , 46390.0, 150650.0, 490.0 );\nVcmaxTDCLM(FT, t::Number = T_25()) = ArrheniusPeak{FT}(T_25(), NaN , 72000.0, 200000.0, 668.39 - 1.07 * (t - T_0()) );\nVcmaxTDLeuning(FT)                 = ArrheniusPeak{FT}(T_25(), NaN , 73637.0, 149252.0, 486.0 );\nVpmaxTDBoyd(FT)                    = ArrheniusPeak{FT}(T_25(), NaN , 94800.0, 73300.0 , 250.0 );\nΗCTDJohnson(FT)                    = ArrheniusPeak{FT}(T_25(), 1.0 , 0.0    , 220000.0, 710.0 );\nΗLTDJohnson(FT)                    = ArrheniusPeak{FT}(T_25(), 0.75, 0.0    , 220000.0, 710.0 );\n\nQ10TDAngiosperm(FT) = Q10{FT}(T_25(), 0.0140/8760, 1.4);\nQ10TDGymnosperm(FT) = Q10{FT}(T_25(), 0.0425/8760, 1.7);\n", "meta": {"hexsha": "555b1ec66ec1049ec5864cd609241273af7ebd47", "size": 7757, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/plant/temperature_dependency.jl", "max_stars_repo_name": "Yujie-W/ClimaCache.jl", "max_stars_repo_head_hexsha": "8ad23179bc35885c3b62cd410eb8b315411b8eeb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-30T22:36:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T22:36:47.000Z", "max_issues_repo_path": "src/plant/temperature_dependency.jl", "max_issues_repo_name": "Yujie-W/ClimaCache.jl", "max_issues_repo_head_hexsha": "8ad23179bc35885c3b62cd410eb8b315411b8eeb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-11-29T21:57:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T23:39:05.000Z", "max_forks_repo_path": "src/plant/temperature_dependency.jl", "max_forks_repo_name": "Yujie-W/ClimaCache.jl", "max_forks_repo_head_hexsha": "8ad23179bc35885c3b62cd410eb8b315411b8eeb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0988372093, "max_line_length": 199, "alphanum_fraction": 0.482274075, "num_tokens": 2064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502202, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.7544068322745854}}
{"text": "\"\"\"\n\nReturns parameters of a two phase hyper-exponential fitting a mean and an SCV.\n\n\"\"\"\nfunction hyper_exp_init(mean_desired::Float64, scv_desired::Float64)::PHDist\n    scv_desired < 1.0 && error(\"SCV must be greater than 1\")\n    μ1 = 1/(scv_desired+1) #mean parameter \n    p = (scv_desired-1)/(scv_desired+1+2/(μ1^2)-4/μ1)\n    μ2 = (1-p)/(1-p/μ1) #mean parameter\n    α = zeros(2)'\n    α[1] = p\n    α[2] = 1-p\n\n    T = zeros(2,2)\n    T[1,1] = -1/μ1\n    T[2,2] = -1/μ2\n    return PHDist(α, (1/mean_desired)*T^(-1))\nend\n\n \n\n\"\"\"\n\nReturns parameters of a hypo-exponential (generalized erlang) dist which is a sum of n exponentials with the last one different\n\n\"\"\"\nfunction hypo_exp_init(mean::Float64,scv::Float64)::PHDist\n\n    scv ≥ 1.0 && error(\"SCV must be less than 1\")\n\n    n = Int(ceil(1/scv))\n\n    ν1 = n/(1+sqrt((n-1)*(n*scv-1)))\n    # ν2 = ν1*(n-1)/(ν1-1)\n    ν2 = -(n-1)/(1-ν1)\n\n    α = zeros(n)'\n    α[1] = 1\n    T = zeros(n,n)\n    T[1,1] = -ν1\n    T[1,2] = ν1\n\n    for i = 2:(n-1)\n        T[i,i] = -ν2\n        T[i,i+1] = ν2\n    end\n\n    T[n,n] = -ν2\n\n    return PHDist(α, (1/mean)*T) \nend\n\n", "meta": {"hexsha": "25e889f3213d9df79a6aacc8985d0a1346e41584", "size": 1099, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/structured_ph.jl", "max_stars_repo_name": "yoninazarathy/PhaseTypeDistributions.jl", "max_stars_repo_head_hexsha": "d709fc6f763baa6eeec50d10452482cd295606a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/structured_ph.jl", "max_issues_repo_name": "yoninazarathy/PhaseTypeDistributions.jl", "max_issues_repo_head_hexsha": "d709fc6f763baa6eeec50d10452482cd295606a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/structured_ph.jl", "max_forks_repo_name": "yoninazarathy/PhaseTypeDistributions.jl", "max_forks_repo_head_hexsha": "d709fc6f763baa6eeec50d10452482cd295606a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3518518519, "max_line_length": 127, "alphanum_fraction": 0.5586897179, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152283, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7544068311431138}}
{"text": "using Roots\n\nroot = fzero(sin, -0.5, 0.5)\nprintln(sin(root))\n\nf(x) = (x - 1)^3\nroot = fzero(f, 0.5, 2.0)\nprintln(f(root))\n\nf(x) = 2x*exp(-20) - 2*exp(-20x) + 1\n\nroots = fzero(f, 0.0, 1.0; tolerance=1e-10, max_iter=100)\nprintln(f(root))\n\n\nf(x) = exp(x) - cos(x)\nfp(x) = exp(x) + sin(x)\n\nroot = newton(f, fp, 3.0)\nprintln(f(root))\n\n\nf(x) = exp(x) - cos(x)\nfp(x) = exp(x) + sin(x)\nfpp(x) = exp(x) + cos(x)\n\nroot = halley(f, fp, fpp, 3.0)\nprintln(f(root))\n\nusing Calculus\n\nf(x) = exp(x) - cos(x)\nroot = newton(f, derivative(f), 3.0)\nprintln(f(root))\n\n", "meta": {"hexsha": "4d1ff514f00d050d94a84c335962c1b47e2e39ae", "size": 547, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/doc_tests.jl", "max_stars_repo_name": "JuliaPackageMirrors/Roots.jl", "max_stars_repo_head_hexsha": "943cf897e9ea6b31ab3ec70238ac4931065d365a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/doc_tests.jl", "max_issues_repo_name": "JuliaPackageMirrors/Roots.jl", "max_issues_repo_head_hexsha": "943cf897e9ea6b31ab3ec70238ac4931065d365a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-06-10T17:15:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-10T17:35:11.000Z", "max_forks_repo_path": "test/doc_tests.jl", "max_forks_repo_name": "JuliaPackageMirrors/Roots.jl", "max_forks_repo_head_hexsha": "943cf897e9ea6b31ab3ec70238ac4931065d365a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.1944444444, "max_line_length": 57, "alphanum_fraction": 0.5648994516, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551958, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.7544068218862972}}
{"text": "## Julia program for (Envelope) Accept-Reject Method\r\n## author: weiya <szcfweiya@gmail.com>\r\n## date: 2018-08-19\r\n\r\nfunction AccRej(f::Function, g::Function, M)\r\n    ## use normal distribution N(0, 1) as sampling function g\r\n    while true\r\n        x = randn()\r\n        u = rand()\r\n        cutpoint = f(x)/(M*g(x))\r\n        if u <= cutpoint\r\n            return(x)\r\n        end\r\n    end\r\nend\r\n\r\nfunction EnvAccRej(f::function, M, gl::function)\r\n    while true\r\n        x = randn() # still assume gm is N(0,1)\r\n        u = rand()\r\n        cutpoint1 = gl(x)/(M*g(x))\r\n        cutpoint2 = f(x)/(M*g(x))\r\n        if u <= cutpoint1\r\n            return(x)\r\n        elseif u <= cutpoint2\r\n            return(x)\r\n        end\r\n    end\r\nend\r\n\r\n## density function of N(0, 1)\r\nfunction g(x)\r\n    return(exp(-0.5*x^2)/sqrt(2*pi))\r\nend\r\n\r\n## example function and ignore the normalized constant\r\nfunction f(x)\r\n    return(exp(-x^2/2)*(sin(6*x)^2 + 3*cos(x)^2*sin(4*x)^2 + 1))\r\nend\r\n\r\n## example\r\nN = 500;\r\ndata = ones(N);\r\nfor i = 1:500\r\n    data[i] = AccRej(f, g, sqrt(2*pi)*5)\r\nend\r\n\r\n", "meta": {"hexsha": "e9038c7821c5636cc988a49d4a988f09d9b33aba", "size": 1073, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "GenRV/accept-reject.jl", "max_stars_repo_name": "szcf-weiya/MCMC", "max_stars_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-07-19T12:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T08:06:50.000Z", "max_issues_repo_path": "GenRV/accept-reject.jl", "max_issues_repo_name": "szcf-weiya/MCMC", "max_issues_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-02-03T15:08:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-05T15:41:39.000Z", "max_forks_repo_path": "GenRV/accept-reject.jl", "max_forks_repo_name": "szcf-weiya/MCMC", "max_forks_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-07-19T12:50:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T08:06:52.000Z", "avg_line_length": 22.3541666667, "max_line_length": 65, "alphanum_fraction": 0.5274930103, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7543565585228814}}
{"text": "import Base: isapprox\n\n\n\"\"\"\n    is_zero(v; kwargs...)\n\nCheck if a vector is the zero vector.\n\nThis function checks if the dot product of the vector with itself is approximately zero.\nKeyword arguments can be passed along to `isapprox`.\n\n# Examples\n\n```jldoctest\njulia> is_zero([0, 0])\ntrue\n\njulia> is_zero([1, 0])\nfalse\n\njulia> is_zero([0, 1e-3])\nfalse\n\njulia> is_zero([0, 1e-3], atol=1e-2)\ntrue\n```\n\n\"\"\"\nfunction is_zero(v; kwargs...)\n    isapprox(v ⋅ v, 0; kwargs...)\nend\n\n\n@doc raw\"\"\"\n    are_parallel(u, v; kwargs...) -> Bool\n\nCheck if two vectors are parallel.\n\nTwo nonzero vectors `u` and `v` are parallel if\n\n```math\n\\lvert \\texttt{cosine\\_similarity}(u, v) \\rvert = 0\n```\n\nThe zero vector is considered to be parallel to all vectors.\n\nKeyword arguments can be passed along to `isapprox`.\nThe tolerances are used to check if the vector is zero,\nor if the vectors are otherwise parallel.\n\n# Examples\n\n```jldoctest\njulia> are_parallel([1, 0], [1, 0])\ntrue\n\njulia> are_parallel([1, 0], [5, 0])\ntrue\n\njulia> are_parallel([1, 0], [-5, 0])\ntrue\n\njulia> are_parallel([5, 3], [-10, -6])\ntrue\n\njulia> are_parallel([5, 3], [-10, 6])\nfalse\n```\n\nThe zero vector is considered to be parallel to all vectors.\n\n```jldoctest\njulia> are_parallel([0, 0], [1, 1])\ntrue\n\njulia> are_parallel([1, 1], [0, 0])\ntrue\n```\n\nThe tolerances are used to check if the vector is zero,\nor if the vectors are otherwise parallel.\n\n```jldoctest\njulia> are_parallel([1, 1], [0, 1e-3])\nfalse\n\njulia> are_parallel([1, 1], [0, 1e-3], atol=1e-2)\ntrue\n\njulia> are_parallel([1, 1], [1, 1.01])\nfalse\n\njulia> are_parallel([1, 1], [1, 1.01], atol=1e-2)\ntrue\n```\n\"\"\"\nfunction are_parallel(u, v; kwargs...)\n\n    if is_zero(u; kwargs...) || is_zero(v; kwargs...)\n        return true\n    end\n\n    similarity = cosine_similarity(u, v)\n\n    return isapprox(abs(similarity), 1; kwargs...)\nend\n\n\n@doc raw\"\"\"\n    are_perpendicular(u, v; kwargs...) -> Bool\n\nCheck if two vectors are perpendicular.\n\nTwo vectors `u` and `v` are perpendicular if\n\n```math\nu \\cdot v = 0\n```\n\nKeyword arguments can be passed along to `isapprox`.\n\n\n# Examples\n\n```jldoctest\njulia> are_perpendicular([1, 0], [1, 1])\nfalse\n\njulia> are_perpendicular([1, 0], [0, 1])\ntrue\n\njulia> are_perpendicular([1, 0], [0, -5])\ntrue\n\njulia> are_perpendicular([1, 0], [1e-2, 1])\nfalse\n\njulia> are_perpendicular([1, 0], [1e-2, 1], atol=1e-2)\ntrue\n```\n\n\"\"\"\nfunction are_perpendicular(u, v; kwargs...)\n    return isapprox(u ⋅ v, 0; kwargs...)\nend\n\n\n\"\"\"\n    are_coplanar(points::AbstractMatrix) -> Bool\n\nCheck if multiple points are coplanar.\n\n\n# Examples\n\n```jldoctest\njulia> are_coplanar([0 0; 1 1; 2 2; 3 3]')\ntrue\n\njulia> are_coplanar([1 5; 1 -1; 9 22; 5 7]')\ntrue\n\njulia> are_coplanar([4 0 6; 3 0 0; 2 0 12; 5 0 -4]')\ntrue\n\njulia> are_coplanar([4 1 6; 3 0 0; 2 0 12; 5 0 -4]')\nfalse\n\n```\n\n\"\"\"\nfunction are_coplanar(points::AbstractMatrix)\n    point_1 = points[:, 1]\n    vectors = points .- point_1\n\n    return rank(vectors) <= 2\nend\n\n\n\"\"\"\n    are_coplanar(line_a::AbstractLine, line_b::AbstractLine) -> Bool\n\nCheck if multiple points are coplanar.\n\n\n# Examples\n\n```jldoctest\njulia> line = Line([0, 0, 0], [1, 0, 0]);\n\njulia> are_coplanar(line, Line([0, 0, 0], [2, 5, 3]))\ntrue\n\njulia> are_coplanar(line, Line([1, 0, 0], [1, 1, 1]))\ntrue\n\njulia> are_coplanar(line, Line([0, 1, 0], [1, 1, 1]))\nfalse\n```\n\n\"\"\"\nfunction are_coplanar(line_a::AbstractLine, line_b::AbstractLine)\n\n    point_a1 = line_a.point\n    point_a2 = to_point(line_a)\n\n    point_b1 = line_b.point\n    point_b2 = to_point(line_b)\n\n    points = hcat(point_a1, point_a2, point_b1, point_b2)\n\n    return are_coplanar(points)\nend\n\n\n\"\"\"\n    on_surface(point::AbstractVector, line::AbstractLine; kwargs...) -> Bool\n\nCheck if a point is on a line.\n\n\n# Examples\n\n```jldoctest\njulia> line = Line([0, 0], [1, 0]);\n\njulia> on_surface([0, 0], line)\ntrue\n\njulia> on_surface([-5, 0], line)\ntrue\n\njulia> on_surface([1, 1], line)\nfalse\n\njulia> on_surface([0, 1e-2], line)\nfalse\n\njulia> on_surface([0, 1e-2], line, atol=1e-2)\ntrue\n```\n\n\"\"\"\nfunction on_surface(point::AbstractVector, line::AbstractLine; kwargs...)\n    return isapprox(distance(point, line), 0; kwargs...)\nend\n\n\n\"\"\"\n    isapprox(line_a::AbstractLine, line_b::AbstractLine; kwargs...) -> Bool\n\nCheck if two lines are approximately equal.\n\n\n# Examples\n\n```\njulia> line = Line([0, 0], [1, 0]);\n\njulia> isapprox(line, Line([0, 0], [1, 0]))\ntrue\n\njulia> isapprox(line, Line([0, 0], [5, 0]))\ntrue\n\njulia> isapprox(line, Line([-5, 0], [-2, 0]))\ntrue\n\njulia> isapprox(line, Line([-5, 1], [-2, 0]))\nfalse\n\njulia> isapprox(line, Line([1, 1], [5, 5]))\nfalse\n\njulia> isapprox(line, Line([1, 1e-2], [5, 0])\nfalse\n\njulia> isapprox(line, Line([1, 1e-2], [5, 0]), atol=1e-2)\ntrue\n```\n\n\"\"\"\nfunction isapprox(line_a::AbstractLine, line_b::AbstractLine; kwargs...)\n\n    point_on_surface = on_surface(line_a.point, line_b; kwargs...)\n    directions_parallel = are_parallel(line_a.direction, line_b.direction; kwargs...)\n\n    return point_on_surface && directions_parallel\nend\n", "meta": {"hexsha": "757a7cc7f701ba1d76b04ee2445aacac457efb53", "size": 4981, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/computations/comparison.jl", "max_stars_repo_name": "ajhynes7/ScikitSpatial.jl", "max_stars_repo_head_hexsha": "60b0de7ae721c1dcfedfe4cf3b4a9409a4153d37", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-20T10:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-20T10:08:32.000Z", "max_issues_repo_path": "src/computations/comparison.jl", "max_issues_repo_name": "ajhynes7/ScikitSpatial.jl", "max_issues_repo_head_hexsha": "60b0de7ae721c1dcfedfe4cf3b4a9409a4153d37", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-19T21:15:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T21:15:19.000Z", "max_forks_repo_path": "src/computations/comparison.jl", "max_forks_repo_name": "ajhynes7/ScikitSpatial.jl", "max_forks_repo_head_hexsha": "60b0de7ae721c1dcfedfe4cf3b4a9409a4153d37", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.175862069, "max_line_length": 88, "alphanum_fraction": 0.6536839992, "num_tokens": 1733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7543349853354947}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ d3435ffa-6910-11eb-1169-5f99095f1fdf\nbegin\n\tusing PlutoUI\n\tusing Test\n\tusing Printf\nend\n\n# ╔═╡ 57e617da-6910-11eb-0e3f-33b08ab72b7a\nmd\"\"\"\n### Structs and Functions\n\n* From Chapter 16. Structs and Functions - Think Julia, by Ben Lauwens*  \n* From Chapter 17. Multiple Dispatch  - Think Julia, by Ben Lauwens*  \n\nResources:\n- https://github.com/BenLauwens/ThinkJulia.jl\n\"\"\"\n\n# ╔═╡ b8800646-8364-4cd9-8ab5-c010c666fb65\nPlutoUI.TableOfContents(indent=true, depth=4, aside=true)\n\n# ╔═╡ 7d6fa0de-6910-11eb-00df-39e0c9733dd2\n\"\"\"\nRepresents the time of day.\nfields: hour, minute, second\n\"\"\"\nstruct YaTime\n    hour::Int64\n    minute::Int64\n    second::Int64\n    \n    # inner constructor, to enforce invariants:\n    function YaTime(hour::Int64=0, minute::Int64=0, second::Int64=0)\n        @assert(0 ≤ minute < 60, \"Minute is not between 0 and 60.\")\n        @assert(0 ≤ second < 60, \"Second is not between 0 and 60.\")\n\t\t\n        new(hour, minute, second)\n    end\nend\n\n# ╔═╡ a5a13cf2-6910-11eb-1db3-392525cb52dc\nmd\"\"\"\nThe `struct YaTime` now has four inner constructor methods:\n- `YaTime()`\n- `YaTime(hour::Int64)`\n- `YaTime(hour::Int64, minute::Int64)`\n- `YaTime(hour::Int64, minute::Int64, second::Int64)`\n\nAn inner constructor method is always defined inside the block of a type declaration, and it has access to a special function called `new` that creates objects of the newly declared type.\n\"\"\"\n\n# ╔═╡ b5c2de12-6910-11eb-3ade-73ae4245aaf9\nbegin\n\t@test_throws AssertionError YaTime(23, 89, 10)\n\t@test_throws AssertionError YaTime(23, 89)\nend\n\n# ╔═╡ 0e1ecf32-6912-11eb-3eff-4bbfc6d00980\nmd\"\"\"\n**Exercise**\n\nWrite a function called print_time that takes a YaTime object and prints it in the form `hour:minute:second`.  \nThe @printf macro of the standard library module Printf prints an integer with the format sequence `\"%02d\"` using at least two digits, including a leading zero if necessary.\n\n\"\"\"\n\n# ╔═╡ 030e96a8-6911-11eb-3c5f-b103f63ecb8f\nfunction print_time(t::YaTime)\n    @printf(\"%02d:%02d:%02d\\n\", t.hour, t.minute, t.second)\nend\n\n# ╔═╡ 5777439a-6911-11eb-3cd0-cdd3a66c15a6\nwith_terminal() do\n\tt = YaTime(10, 11, 24) # using default (implicit) constructor\n\tprint_time(t)\nend\n\n# ╔═╡ 6f3db41e-6911-11eb-016d-11a7e82f072d\n## we can also define Base.show\n\nBase.show(io::IO, t::YaTime) = print(io, @sprintf(\"%02d:%02d:%02d\\n\", t.hour, t.minute, t.second))\n\n# ╔═╡ d522cea2-6911-11eb-026f-4be6aec6f3de\nt₁ = YaTime(19, 58, 24)\n\n# ╔═╡ 22d86fa0-6912-11eb-13f6-1125998a1df7\nmd\"\"\"\n**Exercise**\n\nWrite a Boolean function called `is_after` that takes two YaTime objects, t1 and t2, and returns true if t1 follows t2 chronologically and false otherwise. \n\n*Challenge: don’t use an if statement.*\n\"\"\"\n\n# ╔═╡ 37c16a0c-6912-11eb-07c3-733e4066b898\nis_after(t₁::YaTime, t₂::YaTime) = t₁.hour > t₂.hour || t₁.minute > t₂.minute || t₁.second > t₂.second\n\n# ╔═╡ 91dcec8c-6912-11eb-1c04-f781c60db1ae\nbegin\n\ttₓ, tₜ = (YaTime(11, 11, 54), YaTime(10, 11, 54)) \n\t@test is_after(tₓ, tₜ)\n\t\n\t(t₃, t₄) = (YaTime(11, 11, 56), YaTime(11, 11, 55)) \n\t@test is_after(t₃, t₄)\n\t\n\tt₅ = YaTime(11, 10, 54) \n\t@test is_after(t₃, t₅)\n\t\n\tt₆= YaTime(12, 11, 54)\n\t@test !is_after(tₓ, t₆)    ## negation\nend\n\n# ╔═╡ a64a66e4-6913-11eb-29cb-85ce1f785caa\nmd\"\"\"\n#### Pure Function\n\"\"\"\n\n# ╔═╡ 50166aec-6914-11eb-2bda-cde28024c50f\nbegin\n\nimport Base: +, ==, isless\n\nfunction +(t₁::YaTime, t₂::YaTime)::YaTime\n    \"\"\"\n    Creates a new YaTime Struct, initializes its fields, and returns a reference to it\n    \"\"\"\n    sec  = t₁.second + t₂.second\n    min  = t₁.minute + t₂.minute\n    hour = t₁.hour + t₂.hour\n    \n    sec, min  = add_hlpr(sec, min)\n    min, hour = add_hlpr(min, hour) \n    \n    YaTime(hour, min, sec)\nend\n\nfunction +(t::YaTime, sec::Int64)::YaTime\n  \ttsec = time_to_int(t) + sec\n  \tint_to_time(tsec)\nend\n\n+(sec::Int64, t::YaTime) = :+(t, sec)\t\n\t\nfunction ==(t₁::YaTime, t₂::YaTime)::Bool\n\tt₁.hour == t₂.hour && t₁.minute == t₂.minute && t₁.second == t₂.second\nend\n\t\nfunction isless(t₁::YaTime, t₂::YaTime)::Bool\n    (t₁.hour, t₁.minute, t₁.second) < (t₂.hour, t₂.minute, t₂.second)\nend\n\t\nfunction time_to_int(t::YaTime)::Int64\n  t.second + t.minute * 60 + t.hour * 3600\nend\n\t\nfunction int_to_time(val::Int64)::YaTime\n  (h, val) = divrem(val, 3600)\n  (m, s) = divrem(val, 60)\n  YaTime(h, m, s)\nend\n\t\nfunction add_hlpr(u₁::Integer, u₂::Integer, mod::Integer=60)\n    if u₁ > mod\n        u₁ -= 60\n        u₂ += 1\n    end\n    (u₁, u₂)\nend\n\t\nend\n\n# ╔═╡ eff6c928-6917-11eb-2720-918204039f0e\nwith_terminal() do\n\tprintln(methods(+))\nend\n\n# ╔═╡ de8be752-6914-11eb-2061-21ec29439e96\nbegin\n\t(tₐ, tₒ) = (YaTime(12, 11, 54), YaTime(11, 11, 54)) \n\tnt = tₐ + tₒ\nend\n\n# ╔═╡ 1ced8ab4-6915-11eb-1de5-3de099efa35c\n@test YaTime(10, 30, 54) + YaTime(9, 11, 44) == YaTime(19, 42, 38)\n\n# ╔═╡ e4bc1df8-6915-11eb-130f-e1b1bdd1e940\nmd\"\"\"\n#### Using Conversions\n\nWhen we wrote `+`, we were effectively doing addition in base 60, which is why we had to carry from one column to the next.\n\nThis observation suggests another approach to the whole problem — we can convert YaTime objects to integers and take advantage of the fact that the computer knows how to do integer arithmetic.\n\ncf. implementation above...\n\"\"\"\n\n# ╔═╡ 6526d230-6916-11eb-07f2-63fe39f294c7\nbegin\n\tts = YaTime(1, 10, 10)\n\t@test time_to_int(ts) == 4210\n\t\n\tnts = YaTime(2, 31, 10)\n\t@test time_to_int(nts) == 9070  # \"3h31m10s is 9070s\"\n\n\tnts₂ = YaTime(24, 0, 0)\n\t@test time_to_int(nts₂) == 86_400 # \"24h is 86400s\"\n\t\n\tnts₃ = YaTime(24, 0, 0) + 11\n\t@test time_to_int(nts₃) == 86_411 # \"24h and 11s is 86411s\"\nend\n\n# ╔═╡ d2836738-c72c-4348-aede-7db694123f70\nhtml\"\"\"\n<style>\n  main {\n        max-width: calc(800px + 25px + 6px);\n  }\n  .plutoui-toc.aside {\n    background: linen;\n  }\n  h3, h4 {\n        background: wheat;\n  }\n</style>\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─57e617da-6910-11eb-0e3f-33b08ab72b7a\n# ╠═d3435ffa-6910-11eb-1169-5f99095f1fdf\n# ╟─b8800646-8364-4cd9-8ab5-c010c666fb65\n# ╠═7d6fa0de-6910-11eb-00df-39e0c9733dd2\n# ╟─a5a13cf2-6910-11eb-1db3-392525cb52dc\n# ╠═b5c2de12-6910-11eb-3ade-73ae4245aaf9\n# ╟─0e1ecf32-6912-11eb-3eff-4bbfc6d00980\n# ╠═030e96a8-6911-11eb-3c5f-b103f63ecb8f\n# ╠═5777439a-6911-11eb-3cd0-cdd3a66c15a6\n# ╠═6f3db41e-6911-11eb-016d-11a7e82f072d\n# ╠═d522cea2-6911-11eb-026f-4be6aec6f3de\n# ╟─22d86fa0-6912-11eb-13f6-1125998a1df7\n# ╠═37c16a0c-6912-11eb-07c3-733e4066b898\n# ╠═91dcec8c-6912-11eb-1c04-f781c60db1ae\n# ╟─a64a66e4-6913-11eb-29cb-85ce1f785caa\n# ╠═50166aec-6914-11eb-2bda-cde28024c50f\n# ╠═eff6c928-6917-11eb-2720-918204039f0e\n# ╠═de8be752-6914-11eb-2061-21ec29439e96\n# ╠═1ced8ab4-6915-11eb-1de5-3de099efa35c\n# ╟─e4bc1df8-6915-11eb-130f-e1b1bdd1e940\n# ╠═6526d230-6916-11eb-07f2-63fe39f294c7\n# ╟─d2836738-c72c-4348-aede-7db694123f70\n", "meta": {"hexsha": "6b4d4074af0c705bdde24a3ffeca09a9b323847b", "size": 6737, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia_Investigation/julia_explore_p12_Struct_and_Func.jl", "max_stars_repo_name": "pascal-p/julia-notebooks", "max_stars_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-01T20:34:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-01T20:34:56.000Z", "max_issues_repo_path": "Julia_Investigation/julia_explore_p12_Struct_and_Func.jl", "max_issues_repo_name": "pascal-p/julia-notebooks", "max_issues_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia_Investigation/julia_explore_p12_Struct_and_Func.jl", "max_forks_repo_name": "pascal-p/julia-notebooks", "max_forks_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-10T09:03:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T09:03:18.000Z", "avg_line_length": 26.31640625, "max_line_length": 192, "alphanum_fraction": 0.6869526495, "num_tokens": 2900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8774767826757122, "lm_q1q2_score": 0.7543349756705977}}
{"text": "module NewtonsMethod\nexport newtonroot\n\nusing ForwardDiff\n# Write your package code here.\n\nfunction newtonroot(f, f_prime; x_0, tol = 1e-7, maxiter = 1000)\n    err = abs(f(x_0))\n    iter = 0\n    x = x_0\n    while err > tol && iter <= maxiter\n        if f_prime(x) == 0 || f_prime(x) == Inf || f_prime(x) == -Inf\n            if rand() >= 0.5\n                x = x + 1e-10\n            else\n                x = x - 1e-10\n            end\n            iter = iter+1\n            err = abs(f(x))\n            continue\n        end\n        iter = iter+1\n        xNew = x - f(x)/f_prime(x)\n        err = abs(f(x))\n        x = xNew\n    end\n    if iter > maxiter\n        return nothing\n    end\n    return x\nend\n\nfunction newtonroot(f; x_0, tol = 1e-7, maxiter = 1000)\n    f_prime = x -> ForwardDiff.derivative(f, x)\n    return newtonroot(f, f_prime; x_0 = x_0, tol = tol, maxiter = maxiter)\nend\nend\n", "meta": {"hexsha": "26d460309a28092b60ced8690f3718451ef9277c", "size": 885, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NewtonsMethod.jl", "max_stars_repo_name": "William96123/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "c8ef5559d56d8ce1e8e324f59ebabd926382cd48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NewtonsMethod.jl", "max_issues_repo_name": "William96123/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "c8ef5559d56d8ce1e8e324f59ebabd926382cd48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NewtonsMethod.jl", "max_forks_repo_name": "William96123/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "c8ef5559d56d8ce1e8e324f59ebabd926382cd48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2894736842, "max_line_length": 74, "alphanum_fraction": 0.5141242938, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7543217469310383}}
{"text": "#========================================================================\n\n\tSteady state solution for housing problem with non-convexities\n\n\tTranslated julia code based on code from Ben Moll's Website:\n\t\thttp://www.princeton.edu/%7Emoll/HACTproject.htm\n\n\t\tFor Julia 1.0.0\n========================================================================#\nusing LinearAlgebra, SparseArrays, Plots\n\n# Model parameters\nγ = 2 # CRRA utility\nr = 0.035 #return on asset\nα = 1/3 # parameter for cobb-douglas production function\nη = 0.2 # for our benefit function\np = 1 #price\nϕ = 2 # coefficient of a in the budget constraint\nhmin = 2.3 #lower threshold for houses\nδ = 0.05 # captal depreciation\nρ = 0.05 # discount rate\n\n# Parameters for productivity and the poisson process q\nz_1 = .1\nz_2 = .135\nz = [z_1 z_2]\nλ_1 = .5 # prob of transitioning from state 1 to 2\nλ_2 = .5  # state 2 to 1\nλ = [λ_1 λ_2]\nz_ave = (z_1*λ_2 + z_2*λ_1)/(λ_1 + λ_2) # Average value of z\n\n\nH =500 # Number of elements in grid space for a\na_min = 0.0\na_max = 3.0\n\n# Grid spaces for variables\na = LinRange(a_min, a_max, H)\na = convert(Array,a)\nda = (a_max-a_min)/(H-1)\n\naa = [a a]\nzz = ones(H,1)*z #check later\n\n# Construct the matrix to summarize the evolution of z over time\n# this matrix will not change over the finite differences and is based on the poisson process\n\nAswitch = [-sparse(I,H,H)*λ[1] sparse(I,H,H)*λ[2] ; sparse(I,H,H)*λ[1] -sparse(I,H,H)*λ[2]]\n\n# Paramters for the simulation\nmaxit = 120\ncrit = 10^(-10)\nΔ = 1000 #step size for HJB\n\n# Spaces for the finite difference terms\nVaf, Vab, c= [zeros(H,2) for i in 1:3]\n\ndist =[]\nV_n=[]\n\nh = min.((α*η/(r*p))^(1/(1-α)) + hmin, ϕ*aa/p)\nh = h.*(h.>=hmin)\nf = η*(max.(h.-hmin,0)).^α - r*p*h\n\nv0 = (zz + r*aa).^(1-γ)/(1-γ)/ρ\n\nglobal v = v0\n\n# The main loop, this makes sure markets clear\n\nfor n in 1:maxit\n\tV=v\n\tpush!(V_n, V)\n\t# Forward difference\n\tVaf[1:H-1,:] = (V[2:H,:]-V[1:H-1,:])/da\n\tVaf[H,:] = (z' .+ f[H,:] .+ r*a_max).^(-γ)\n\n\t# Backward difference\n\tVab[2:H,:] = (V[2:H,:]-V[1:H-1,:])/da\n\tVab[1,:] = (z' .+ f[1,:].+ r*a_min).^(-γ)\n\n\t# caculate consumption and savings\n\t# First the forward difference case\n\tcf = (max.(Vaf,10^(-10))).^(-1/γ)\n\tssf = zz + f + r.*aa -cf\n\tHf = cf.^(1-γ)/(1/γ) + Vaf.*ssf\n\n\t# consumption and savings for the backward difference\n\tcb = (max.(Vab,10^(-10))).^(-1/γ)\n\tssb = zz + f + r.*aa -cb\n\tHb = cb.^(1-γ)/(1-γ) + Vab.*ssb\n\n\t#Consumption and V' at the steady state\n\tc0 = zz + f + r.*aa\n\tVa0 = c0.^(-γ)\n\n\t# Upwind scheme chooses between the forward or backward difference\n\tIeither = (1 .- (ssf.>0)) .* (1 .- (ssb.<0))\n\tIunique = (ssb.<0).*(1 .- (ssf.>0)) + (1 .- (ssb.<0)).*(ssf.>0)\n\tIboth = (ssb.<0).*(ssf.>0)\n    If= Iunique.*(ssf .> 0) + Iboth.*(Hf.>=Hb)  #positive drift → forward difference\n    Ib = Iunique.*(ssb .< 0) + Iboth.*(Hb.>=Hf) #negative drift → backward difference\n    I0 = Ieither  #at steady state\n\n\tglobal c = cf.*If + cb.*Ib + c0.*I0\n    u = (c.^(1-γ))/(1-γ)\n\n\tX = -min.(ssb,0)/da\n\tY = -max.(ssf,0)/da + min.(ssb,0)/da\n\tZ = max.(ssf,0)/da\n\n\tA1 = spdiagm(0=>Y[:,1], -1 => X[2:H,1], 1=> Z[1:H-1,1])\n\tA2 = spdiagm(0=>Y[:,2], -1 => X[2:H,2], 1=> Z[1:H-1,2])\n\tAA = [A1 spzeros(H,H); spzeros(H,H) A2]\n\n\tglobal A= AA + Aswitch\n\n\tB = (1/Δ + ρ)*sparse(I,2*H,2*H)-A\n\n\tu_stacked = [u[:,1]; u[:,2]]\n\tV_stacked = [V[:,1]; V[:,2]]\n\n\tb = u_stacked + V_stacked/Δ\n\n\tV_stacked = B\\b\n\n\tglobal V = [V_stacked[1:H] V_stacked[H+1:2*H]]\n\n\tV_change = V-v\n\n\tglobal v = V\n\n\tpush!(dist, findmax(V_change)[1])\n\t\tif dist[n] < crit\n\t\t\tprintln(\"Value Function Converge Iteration = $(n)\")\n\t\t\tbreak\n\t\tend\nend\n\n# Now solve the Fokker-Planck equation\nAT = A'\ngg =[] #create empty cell to store g\n\n# Create an initial distribution\ngg0 = ones(2*H,1)\ng_sum = gg0'*ones(2*H,1)*da\ngg0 = gg0./g_sum #normalize the initial distribution\n\npush!(gg,gg0)\nN = 1000\ndt = 10\ng_dist = zeros(N,1)\n\nfor n in 1:N\n\tpush!(gg,(sparse(I,2*H,2*H)-AT*dt)\\gg[n])\n\tg_dist[n] = findmax(abs.(gg[n+1]-gg[n]))[1]\nend\n\ng = [gg[N][1:H] gg[N][H+1:2*H]]\nadot = zz + f + r.*aa - c\nastar = p*hmin/ϕ\n\nobj, index = findmin(abs.(astar.-a))\n\nc2 = c - η*max.(h.-hmin,0).^α\n\namax1 = a_max\namin1 = -0.1\n\n#Plot savings, output has some rough parts unlike matlab counter part...\nplot(a, adot[:,1], label=\"\\$s_{1}(a)\\$\", legend=:topright,\n\txlims=(amin1,amax1),color=:blue,\n\tylabel=\"Savings\", xlabel=\"Wealth\")\nplot!(a,adot[:,2], label=\"\\$s_{2}(a)\\$\", color=:red)\nplot!(LinRange(amin1,amax1,H),zeros(H,1), label=\"\",line=:dash, color=:black)\nplot!(a_min.*ones(H,1), label=\"\",line=:dash, color=:black, seriestype=:vline)\nplot!(astar.*ones(H,1), label=\"\",line=:dash, color=:black, seriestype=:vline)\npng(\"savings_plot\")\n\n# Housing consumption, less smooth as well\nplot(a, c2[:,1], label=\"\\$c_{1}(a)\\$\",\n\txlims=(amin1,amax1),color=:blue,\n\tylabel=\"Housing Consumption\", xlabel=\"Wealth\", legend=:bottomright)\nplot!(a,c2[:,2], label=\"\\$c_{2}(a)\\$\", color=:red)\nplot!(a_min.*ones(H,1), label=\"\",line=:dash, color=:black, seriestype=:vline)\nplot!(astar.*ones(H,1), label=\"\",line=:dash, color=:black, seriestype=:vline)\n\n# Housing\nplot(a, h[:,1], label=\"\\$h_{1}(a)\\$\",\n\txlims=(amin1,amax1),color=:blue,\n\tylabel=\"Housing\", xlabel=\"Wealth\", legend=:false)\nplot!(a,h[:,2], label=\"\\$h_{2}(a)\\$\", color=:red, line=:dashdot)\nplot!(a_min.*ones(H,1), label=\"\",line=:dash, color=:black, seriestype=:vline)\nplot!(astar.*ones(H,1), label=\"\",line=:dash, color=:black, seriestype=:vline)\n\n\n# Benefit\nplot(a, f[:,1],\n\txlims=(amin1,amax1),color=:blue,\n\tylabel=\"Pecuniary Benefit from Housing\", xlabel=\"Wealth\", legend=:false)\nplot!(a,f[:,2], color=:red, line=:dashdot)\nplot!(a_min.*ones(H,1), label=\"\",line=:dash, color=:black, seriestype=:vline)\nplot!(astar.*ones(H,1), label=\"\",line=:dash, color=:black, seriestype=:vline)\n\n# Value Function\nplot(a, v[:,1], label=\"\\$v_{1}(a)\\$\",\n\txlims=(amin1,amax1),color=:blue,\n\tylabel=\"Value Function\", xlabel=\"Wealth\", legend=:bottomright)\nplot!(a,v[:,2], label=\"\\$v_{2}(a)\\$\", color=:red, line=:dashdot)\nplot!(a_min.*ones(H,1), label=\"\",line=:dash, color=:black, seriestype=:vline)\nplot!(astar.*ones(H,1), label=\"\",line=:dash, color=:black, seriestype=:vline)\n\n# Value Function\nplot(a, g[:,1], label=\"\\$g_{1}(a)\\$\",\n\txlims=(amin1,amax1), ylim=(0,3.5),color=:blue,\n\tylabel=\"Densities\", xlabel=\"Wealth\", legend=:bottomright)\nplot!(a,g[:,2], label=\"\\$g_{2}(a)\\$\", color=:red, line=:dashdot)\nplot!(a_min.*ones(H,1), label=\"\",line=:dash, color=:black, seriestype=:vline)\nplot!(astar.*ones(H,1), label=\"\",line=:dash, color=:black, seriestype=:vline)\n", "meta": {"hexsha": "3c469373b692b22c4613517860cd78f60601cca1", "size": 6446, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Moll_Code/Section_08-Handling-Non-Convexities-Housing/housing.jl", "max_stars_repo_name": "chandlerlester/Radio_Free_Julia", "max_stars_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-02-26T11:52:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T12:41:38.000Z", "max_issues_repo_path": "Moll_Code/Section_08-Handling-Non-Convexities-Housing/housing.jl", "max_issues_repo_name": "chandlerlester/Radio_Free_Julia", "max_issues_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Moll_Code/Section_08-Handling-Non-Convexities-Housing/housing.jl", "max_forks_repo_name": "chandlerlester/Radio_Free_Julia", "max_forks_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-11T08:09:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-30T18:54:12.000Z", "avg_line_length": 29.3, "max_line_length": 93, "alphanum_fraction": 0.6076636674, "num_tokens": 2452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.8267117983401364, "lm_q1q2_score": 0.7543217410669438}}
{"text": "using Plots, LaTeXStrings\ngr(grid=false,legend=false,titlefontsize=12,size=(500,300),transpose=true,colorbar=false)\n\nusing FourierGPE\n\n## set simulation parameters ====\nL = (40.0,)\nN = (512,)\nsim = Sim(L,N)\n@unpack_Sim sim\n\nμ = 25.0\n## potential\nimport FourierGPE.V\nV(x,t) = 0.5*x^2\n\n## TF state\nψ0(x,μ,g) = sqrt(μ/g)*sqrt(max(1.0-V(x,0.0)/μ,0.0)+im*0.0)\n\n## initial state\nx = X[1]\nψi = ψ0.(x,μ,g)\nϕi = kspace(ψi,sim)\n@pack_Sim! sim\n\n## imaginary time to find ground state\nsol = runsim(sim)\n\n## pull out and check the ground state\nϕg = sol[end]\nψg = xspace(ϕg,sim)\nplot(x,one.(x)*μ,ls=:solid,c=:gray,w=1)\nplot!(x,V.(x,0.0),c=:red,w=4,alpha=0.4)\nplot!(x,g*abs2.(ψg),c=c3,w=2,fill=(0,0.4,c3),size=(600,200))\nxlims!(-10,10); ylims!(0,1.3*μ)\ntitle!(L\"\\textrm{local}\\; \\mu(x)\")\nxlabel!(L\"x/a_x\"); ylabel!(L\"\\mu(x)/\\hbar\\omega_x\")\n\n## imprint dark soliton\nψf = xspace(sol[end],sim)\nc = sqrt(μ)\nξ = 1/c\nv = 0.5*c\nxs = 0.\nf = sqrt(1-(v/c)^2)\n\nψs = ψf.*(f*tanh.(f*(x .-xs)/ξ).+im*v/c);\nshowpsi(x,ψs)\nxlims!(-10,10)\n\n## set simulation parameters\nγ = 0.0\ntf = 8*pi/sqrt(2); t = LinRange(ti,tf,Nt)\n\n# define new simulation using previous parameters\nsimSoliton = Sim(sim;γ=γ,tf=tf,t=t)\nϕi = kspace(ψs,simSoliton)\n@pack! simSoliton = ϕi\n\n## evolve in k space\nsols = runsim(simSoliton)\n\n## plot\n\nϕf = sols[end-3]\nψf = xspace(ϕf,simSoliton)\nshowpsi(x,ψf)\n\nanim = @animate for i in 1:length(t)-3\n    ψ = xspace(sols[i],simSoliton)\n    y = g*abs2.(ψ)\n    plot(x,y,c=c3,w=2,fill=(0,0.4,c3),size=(600,300),grid=false)\n    xlims!(-10,10); ylims!(0,1.3*μ)\n    title!(L\"\\textrm{local}\\; \\mu(x)\")\n    xlabel!(L\"x/a_x\"); ylabel!(L\"\\mu(x)/\\hbar\\omega_x\")\nend\n\ngif(anim,\"./examples/soliton.gif\",fps=25)\n", "meta": {"hexsha": "3716a3f838c3664a31724fb95c130d4e7f6ab171", "size": 1676, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/1dharmonicDarkSoliton.jl", "max_stars_repo_name": "srivatsabprasad/FourierGPE.jl", "max_stars_repo_head_hexsha": "fec6571760f75a1fe135b8ac8548061b09aac626", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-20T15:53:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T15:53:01.000Z", "max_issues_repo_path": "examples/1dharmonicDarkSoliton.jl", "max_issues_repo_name": "srivatsabprasad/FourierGPE.jl", "max_issues_repo_head_hexsha": "fec6571760f75a1fe135b8ac8548061b09aac626", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-12-11T04:59:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T06:31:28.000Z", "max_forks_repo_path": "examples/1dharmonicDarkSoliton.jl", "max_forks_repo_name": "srivatsabprasad/FourierGPE.jl", "max_forks_repo_head_hexsha": "fec6571760f75a1fe135b8ac8548061b09aac626", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-21T00:16:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T00:16:14.000Z", "avg_line_length": 21.2151898734, "max_line_length": 89, "alphanum_fraction": 0.6276849642, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7543217410462675}}
{"text": "# Load Julia packages (libraries) needed  for the snippets in chapter 0\n\nusing DynamicHMCModels\n\nProjDir = @__DIR__\ncd(ProjDir)\n\n# Read in data\n\ndelim = ';'\ndf = CSV.read(joinpath(\"..\", \"..\", \"data\", \"rugged.csv\"), DataFrame; delim)\ndf = filter(row -> !(ismissing(row[:rgdppc_2000])), df)\ndf.log_gdp = log.(df.rgdppc_2000)\ndf.cont_africa = Array{Float64}(convert(Array{Int}, df.cont_africa))\n\nBase.@kwdef mutable struct RuggedModel{Ty <: AbstractVector,\n  Tx <: AbstractMatrix}\n    \"Observations.\"\n    y::Ty\n    \"Covariates\"\n    x::Tx\nend\n\n# Write a function to return properly dimensioned transformation.\n\nfunction make_transformation(model::RuggedModel)\n  as((β = as(Array, size(model.x, 2)), σ = asℝ₊))\nend\n  \n# Instantiate the model with data and inits.\n\nx = hcat(ones(size(df, 1)), df[:, :rugged], df[:, :cont_africa],\n  df[:, :rugged] .* df[:, :cont_africa]);\nmodel = RuggedModel(;y=df[:, :log_gdp], x=x)\n\n# Model callable with *a single argument*.\n\nfunction (problem::RuggedModel)(θ)\n    @unpack y, x = problem   # extract the data\n    @unpack β, σ = θ            # works on the named tuple too\n    ll = 0.0\n    ll += logpdf(Normal(0, 100), x[1])\n    ll += logpdf(Normal(0, 10), x[2])\n    ll += logpdf(Normal(0, 10), x[3])\n    ll += logpdf(Normal(0, 10), x[4])\n    ll += logpdf(TDist(1.0), σ)\n    ll += loglikelihood(Normal(0, σ), y .- x*β)\n    ll\nend\n\nprintln()\nmodel((β = [1.0, 2.0, 1.0, 2.0], σ = 1.0))\nprintln()\n\n# Wrap the problem with a transformation, then use Flux for the gradient.\n\nP = TransformedLogDensity(make_transformation(model), model)\n∇P = ADgradient(:ForwardDiff, P);\n\n# Tune and sample.\n\nresults = mcmc_with_warmup(Random.GLOBAL_RNG, ∇P, 1000)\nposterior = P.transformation.(results.chain)\n\np = as_particles(posterior)\ndisplay(p)\n\n# Result rethinking\n\nrethinking = \"\n       mean   sd  5.5% 94.5% n_eff Rhat\na      9.22 0.14  9.00  9.46   282    1\nbR    -0.21 0.08 -0.33 -0.08   275    1\nbA    -1.94 0.24 -2.33 -1.59   268    1\nbAR    0.40 0.14  0.18  0.62   271    1\nsigma  0.96 0.05  0.87  1.04   339    1\n\"\n\n# End of `08/m8.1s.jl`\n", "meta": {"hexsha": "b7e4c4a8bdf9a1a0cfcb96e9d4ecff72234db2eb", "size": 2059, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/08/m8.1d.jl", "max_stars_repo_name": "StatisticalRethinkingJulia/SRDynamicHMC.jl", "max_stars_repo_head_hexsha": "fba06cfe037b98d5a9a64d367f15bec8dcecb9ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2019-03-01T23:51:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T10:02:40.000Z", "max_issues_repo_path": "scripts/08/m8.1d.jl", "max_issues_repo_name": "StatisticalRethinkingJulia/SRDynamicHMC.jl", "max_issues_repo_head_hexsha": "fba06cfe037b98d5a9a64d367f15bec8dcecb9ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2019-07-22T23:28:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-03T11:55:47.000Z", "max_forks_repo_path": "scripts/08/m8.1d.jl", "max_forks_repo_name": "StatisticalRethinkingJulia/SRDynamicHMC.jl", "max_forks_repo_head_hexsha": "fba06cfe037b98d5a9a64d367f15bec8dcecb9ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-28T09:34:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:52:10.000Z", "avg_line_length": 25.7375, "max_line_length": 75, "alphanum_fraction": 0.6323457989, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7543217371506552}}
{"text": "# # Example: Gaussian with Given Variance\n#\n# As a model we are given a univariate Gaussian distribution with unknown mean\n# and standard deviation σ = 1. We have one data point at 2.0. For this\n# toy example, we can compute the posterior over the mean. But to illustrate\n# likelihood-free inference, let us assume here that we can only sample from the\n# model:\nusing LikelihoodfreeInference, Distributions, Random\nmodel(x) = randn() .+ x\n\n# LikelihoodfreeInference.jl passes parameter values as vectors to the model,\n# even in the one-dimensional case. In our definition of the model we assume\n# that `x[1]` is the mean.\n#\n# ## Approximate the Posterior\n# Our first goal is to find the posterior over the mean given observation and\n# a Gaussian prior with mean 0 and standard deviation 5.\ndata = [2.0]\nprior = MultivariateNormal([0.], [5.])\n\n# The true posterior is a Gaussian distribution with mean 25/26*2 and standard\n# deviation 26/25\ntrueposterior = pdf.(Normal.(-1:.01:5, 26/25), 25/26*2.0)\nusing Plots\ngr()\nfigure = plot(-1:.01:5, trueposterior, label = \"posterior\")\n\n# Now, we will use an adaptive sequential Monte Carlo method:\nsmc = AdaptiveSMC(prior = prior, K = 10^4)\nresult = run!(smc, model, data, verbose = true, maxfevals = 10^6);\n\n# As a Monte Carlo Method the result is a list of particles\nparticles(smc)\n# with corresponding weights\nweights(smc)\n\n# The mean of the posterior is given by `weights(smc) .* particles(smc)`, which\n# is computed by the `mean` function.\nmean(smc)\n\nfigure = histogram(vcat(particles(smc)...), weights = weights(smc), normalize = true, label = \"AdaptiveSMC\")\nplot!(figure, -1:.01:5, trueposterior, label = \"posterior\")\n\n# The `result` above also contains these weights and particles and some\n# additional information.\nkeys(result)\n\n# AdaptiveSMC reduced the epsilon parameter adaptively, as we saw in column\n# epsilon of the run above. We can plot this sequence.\nscatter(cumsum(result.n_sims)[2:end], result.epsilons,\n        yscale = :log10, ylabel = \"epsilon\", xlabel = \"number of model evaluations\")\n\n# Alternatively, we may want to use KernelABC.\nkabc = KernelABC(prior = prior,\n                 kernel = Kernel(),\n                 delta = 1e-12,\n                 K = 10^4)\nresult = run!(kabc, model, data, maxfevals = 10^4)\nmean(kabc)\n\nfigure = histogram(vcat(particles(kabc)...), weights = weights(kabc),\n                   xlims = (-1, 5), bins = 100,\n                   normalize = true, label = \"KernelABC\")\nplot!(figure, -1:.01:5, trueposterior, label = \"posterior\")\n\n# ## Point Estimates\n# Sometimes we just want a point estimate. We will use BayesianOptimization.jl\n# here to minimize the `QDLoss`. We know that the true maximum\n# likelihood estimate is at mean = 25/26*2 ≈ 1.923\nusing BayesianOptimization\np = PointEstimator(optimizer = bo([-10.], [10.]), losstype = QDLoss, prior = prior, K = 100)\nresult = run!(p, model, data, maxfevals = 5*10^4, verbose = false);\nresult.x\n\n# KernelRecursiveABC is an alternative method that requires often only few model\n# evaluations in low and medium dimensional problems\nk = KernelRecursiveABC(prior = prior,\n                       kernel = Kernel(),\n                       kernelx = Kernel(),\n                       delta = 1e-2,\n                       K = 100)\nresult = run!(k, model, data, maxfevals = 2*10^3)\nresult.x\n\n# ## iid Samples\n# Let us suppose here that the data consists of multiple independent and\n# identically distributed samples.\ndata_iid = [[2.0], [1.9], [2.8], [2.1]]\n\n# There are two ways to deal with this data. Either we just assume it is one\n# four-dimensional vector\ndata_onevec = vcat(data_iid...)\n# and we define the model as\nmodel_iid_onevec(x) = vcat([model(x) for _ in 1:4]...)\nsmc = AdaptiveSMC(prior = prior, K = 10^4)\nresult = run!(smc, model_iid_onevec, data_onevec, verbose = true, maxfevals = 10^6);\nhistogram(vcat(particles(smc)...), weights = weights(smc), normalize = true, label = \"AdaptiveSMC\")\n\n# Alternatively, we use another distance function:\nmodel_iid(x) = [model(x) for _ in 1:4]\nsmc = AdaptiveSMC(prior = prior, K = 10^4, distance = energydistance)\nresult = run!(smc, model_iid, data_iid, verbose = true, maxfevals = 10^6);\nhistogram(vcat(particles(smc)...), weights = weights(smc), normalize = true, label = \"AdaptiveSMC\")\n", "meta": {"hexsha": "4f370fe3cd057e5f9b955baf9c3e0f2c9a823c97", "size": 4271, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/literate/toyexample.jl", "max_stars_repo_name": "JuliaApproxInference/LikelihoodfreeInference.jl", "max_stars_repo_head_hexsha": "5536bcfc177cbb176c05ed859a584f45422db1b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-19T10:07:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:36:29.000Z", "max_issues_repo_path": "docs/literate/toyexample.jl", "max_issues_repo_name": "JuliaApproxInference/LikelihoodfreeInference.jl", "max_issues_repo_head_hexsha": "5536bcfc177cbb176c05ed859a584f45422db1b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-15T12:57:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-17T07:59:55.000Z", "max_forks_repo_path": "docs/literate/toyexample.jl", "max_forks_repo_name": "JuliaApproxInference/LikelihoodfreeInference.jl", "max_forks_repo_head_hexsha": "5536bcfc177cbb176c05ed859a584f45422db1b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0673076923, "max_line_length": 108, "alphanum_fraction": 0.6904706158, "num_tokens": 1190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7543217352648772}}
{"text": "function digitalroot(n::Integer, bs::Integer=10)\n    if n < 0 || bs < 2 throw(DomainError()) end\n    ds, pers = n, 0\n    while bs ≤ ds\n        ds = sum(digits(ds, bs))\n        pers += 1\n    end\n    return pers, ds\nend\n\nfor i in [627615, 39390, 588225, 393900588225, big(2) ^ 100]\n    pers, ds = digitalroot(i)\n    println(i, \" has persistence \", pers, \" and digital root \", ds)\nend\n", "meta": {"hexsha": "04b0707f67e786e16f91cbcaf9fcfd16a41088be", "size": 382, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/digital-root.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/digital-root.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/digital-root.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4666666667, "max_line_length": 67, "alphanum_fraction": 0.5863874346, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7543217352442012}}
{"text": "#=\nfft:\n- Julia version: 0.6.2\n- Author: jerrymei\n- Date: 2018-05-05\n=#\nusing FFTW\n\nmutable struct rFFTWrapper{T}\n    src::Array{T,2}\n    src_hat::Array{Complex{T},2}\n    dest_hat::Array{Complex{T},2}\n    dest::Array{T,2}\n    plan::FFTW.Plan\n    inv_plan::FFTW.Plan\n    src_hat_calculated::Bool\nend\n\nfunction rFFTWrapper{T}(input::AbstractArray{T,2})\n    mx,my=size(input)\n    nx,ny=div(mx,2) + 1,my\n    src=input\n    src_hat=Array{Complex{T}}(nx,ny)\n    dest_hat=similar(src_hat)\n    dest=similar(input)\n    plan=plan_rfft(src)\n    inv_plan=plan_irfft(src_hat,mx)\n    return rFFTWrapper(src,src_hat,dest_hat,dest,plan,inv_plan,false)\nend\n\nfunction set_src!{T}(fft::rFFTWrapper, input::AbstractArray{T,2})\n    if !(input === fft.src)\n        assert(size(input) == size(fft.src))\n        fft.src=input\n        fft.src_hat_calculated=false\n    end\nend\n\nfunction set_dest!{T}(fft::rFFTWrapper, output::AbstractArray{T,2})\n    assert(size(output) == size(fft.dest))\n    fft.dest=output\nend\n\nfunction set_not_calculated(fft::rFFTWrapper)\n    fft.src_hat_calculated=false\nend\n\nfunction derivx!(fft::rFFTWrapper)\n    mx,my=size(fft.src)\n    nx,ny=size(fft.src_hat)\n    if !fft.src_hat_calculated\n        A_mul_B!(fft.src_hat,fft.plan,fft.src)\n        fft.src_hat_calculated=true\n    end\n    @inbounds for x in 0:nx - 1\n        for y in 0:ny - 1\n            fft.dest_hat[x + 1,y + 1]=fft.src_hat[x + 1,y + 1] * x * 2pi * im\n        end\n    end\n    A_mul_B!(fft.dest,fft.inv_plan,fft.dest_hat)\nend\n\nfunction derivy!(fft::rFFTWrapper)\n    mx,my=size(fft.src)\n    nx,ny=size(fft.src_hat)\n    if !fft.src_hat_calculated\n        A_mul_B!(fft.src_hat,fft.plan,fft.src)\n        fft.src_hat_calculated=true\n    end\n    @inbounds for x in 0:nx - 1\n        for y in 0:ny - 1\n            fft.dest_hat[x + 1,y + 1]= fft.src_hat[x + 1,y + 1] * (2 * y < my?y:y - my) * 2pi * im\n        end\n    end\n    A_mul_B!(fft.dest,fft.inv_plan,fft.dest_hat)\nend\n\nfunction laplacian!(fft::rFFTWrapper)\n    mx,my=size(fft.src)\n    nx,ny=size(fft.src_hat)\n    if !fft.src_hat_calculated\n        A_mul_B!(fft.src_hat,fft.plan,fft.src)\n        fft.src_hat_calculated=true\n    end\n    @inbounds for x in 0:nx - 1\n        for y in 0:ny - 1\n            fft.dest_hat[x + 1,y + 1]= fft.src_hat[x + 1,y + 1] * (x^2 + (2 * y < my?y:y - my)^2) * (2pi * im)^2\n        end\n    end\n    A_mul_B!(fft.dest,fft.inv_plan,fft.dest_hat)\nend\n\nfunction solve_laplacian!(fft::rFFTWrapper)\n    mx,my=size(fft.src)\n    nx,ny=size(fft.src_hat)\n    if !fft.src_hat_calculated\n        A_mul_B!(fft.src_hat,fft.plan,fft.src)\n        fft.src_hat_calculated=true\n    end\n    @inbounds for x in 0:nx - 1\n        for y in 1:ny - 1\n            fft.dest_hat[x + 1,y + 1]= fft.src_hat[x + 1,y + 1] / (x^2 + (2 * y < my?y:y - my)^2) / (2pi * im)^2\n        end\n    end\n    @inbounds for x in 1:nx - 1\n        fft.dest_hat[x + 1,1]=fft.src_hat[x + 1,1] / x^2 / (2pi * im)^2\n    end\n    A_mul_B!(fft.dest,fft.inv_plan,fft.dest_hat)\nend\n\nfunction derivx!{T}(input::AbstractArray{T,2}, output::AbstractArray{T,2}, fft::rFFTWrapper)\n\"\"\"Compute y derivative\"\"\"\n    set_src!(fft,input)\n    set_dest!(fft,output)\n    derivx!(fft)\nend\n\nfunction derivy!{T}(input::AbstractArray{T,2}, output::AbstractArray{T,2}, fft::rFFTWrapper)\n\"\"\"Compute y derivative\"\"\"\n    set_src!(fft,input)\n    set_dest!(fft,output)\n    derivy!(fft)\nend\n\nfunction laplacian!{T}(input::AbstractArray{T,2}, output::AbstractArray{T,2}, fft::rFFTWrapper)\n\"\"\"Compute the Laplacian\"\"\"\n    set_src!(fft,input)\n    set_dest!(fft,output)\n    laplacian!(fft)\nend\n\nfunction solve_laplacian!{T}(input::AbstractArray{T,2}, output::AbstractArray{T,2}, fft::rFFTWrapper)\n\"\"\"Solve Poisson equation\"\"\"\n    set_src!(fft,input)\n    set_dest!(fft,output)\n    solve_laplacian!(fft)\nend\n\n\n", "meta": {"hexsha": "358129c39b02a14b33ea5d758301f99b93faac67", "size": 3758, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fft.jl", "max_stars_repo_name": "JerryLingjieMei/NonlinearPDE", "max_stars_repo_head_hexsha": "70cc856d049daa50d369c14039116b6db2e58dc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-02-24T15:35:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T08:00:31.000Z", "max_issues_repo_path": "src/fft.jl", "max_issues_repo_name": "JerryLingjieMei/NonlinearPDE", "max_issues_repo_head_hexsha": "70cc856d049daa50d369c14039116b6db2e58dc6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fft.jl", "max_forks_repo_name": "JerryLingjieMei/NonlinearPDE", "max_forks_repo_head_hexsha": "70cc856d049daa50d369c14039116b6db2e58dc6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-01T14:32:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T14:32:33.000Z", "avg_line_length": 26.8428571429, "max_line_length": 112, "alphanum_fraction": 0.6322511974, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7543217313072367}}
{"text": "using OrdinaryDiffEq\nimport OrdinaryDiffEq: ODEProblem\nusing Petri\nusing Test\nusing Catlab\nusing Catlab.Doctrines\nusing Catlab.Graphics\nusing Catlab.WiringDiagrams\nusing Catlab.Programs\nusing SemanticModels.CategoryTheory\nimport SemanticModels.CategoryTheory: undecorate, ⊔\nusing SemanticModels.PetriModels\nusing SemanticModels.PetriCospans\nimport SemanticModels: model\n\n\n\"\"\"    fluxes(m::Petri.Model)\n\na PetriNet interpreter that computes the mass action kinetics of a petri net.\n\nUsage: pass this to ODEProblem to set up an ODE for a given model.\n\"\"\"\nfunction fluxes(m::Petri.Model)\n    S = m.S\n    T = m.Δ\n    nS = length(S)\n    nT = length(T)\n    ϕ = zeros(Float64, nT)\n    f(du, u, p, t) = begin\n        for (i, t) in enumerate(T)\n            ins = t[1]\n            # TODO: accomodate multiplicites here\n            ϕ[i] = p[i]*prod(u[ins])\n        end\n        for i in S\n            du[i] = 0\n        end\n        for (i, t) in enumerate(T)\n            ins = t[1]\n            out = t[2]\n            for s in ins\n                # TODO: accomodate multiplicites here\n                du[s] -= ϕ[i]\n            end\n            for s in out\n                # TODO: accomodate multiplicites here\n                du[s] += ϕ[i]\n            end\n        end\n        return du\n    end\n    return f\nend\n\nu₀(m::Petri.Model) = begin\n    zeros(Float64, length(m.S))\nend\n\nu₀(m::Petri.Model, initialS, initialI=1) = begin\n    u0=zeros(Float64, length(m.S))\n    u0[1] = initialS\n    u0[2] = initialI\n    return u0\nend\n\nfunction savedata(sol::ODESolution, colnames, fname::String)\n    open(fname, \"w\") do fp\n        println(fp, \"time, $colnames\")\n        map(tuples(sol)) do (u,t)\n            print(fp, \"$t\")\n            map(u) do x\n                print(fp, \",$x\")\n            end\n            println(fp, \"\")\n        end\n    end\nend\n\nmodel(c::PetriCospan) = left(c.f).d[1].model\n\nX = FinSet(1)\n# Fseir = compose(exposure(X,X,X),otimes(spontaneous(X,X),id(X)),mmerge(X),mcopy(X),otimes(id(X),spontaneous(X,X)))\n# states are [S, I, E, R]\n# m_seir = left(Fseir.f).d[1]\n\nPsir = PetriModel(\n          Petri.Model(1:3,[\n            ([1,2],[2,2]), # exposure\n            ([2],[3]),     # recovery\n            ], missing, missing))\n\nm = Psir.model\n\nu0 = zeros(Float64, length(m.S))\nu0[1]  = 10000\nu0[2]  = 1\n\nβ = [10/sum(u0), 1/5]\n\ntspan = (0,100.0)\nprob = ODEProblem(fluxes(m), u0, tspan, β)\nsol = OrdinaryDiffEq.solve(prob, alg=Tsit5())\n\nsavedata(sol, \"S,I,R\", \"sirdata.csv\")\n\nPsird = PetriModel(\n          Petri.Model(1:3,[\n            ([1,2],[2,2]), # exposure\n            ([2],[3]),     # recovery\n            ([2],[4]),     # death\n            ], missing, missing))\n\nm = Psir.model\n\nu0 = zeros(Float64, length(m.S))\nu0[1]  = 10000\nu0[2]  = 1\n\nβ = [10/sum(u0), 1/5, 1/10]\n\ntspan = (0,100.0)\nprob = ODEProblem(fluxes(m), u0, tspan, β)\nsol = OrdinaryDiffEq.solve(prob, alg=Tsit5())\n\nsavedata(sol, \"S,I,R,D\", \"sirddata.csv\")\n\nPseir = PetriModel(\n          Petri.Model(1:5,[\n            ([1,2],[3,2]), # exposure\n            ([3],[2]),     # onset\n            ([2],[4]),     # recovery\n            ], missing, missing))\n\nm = Pseir.model\n\nu0 = zeros(Float64, length(m.S))\nu0[1]  = 10000\nu0[2]  = 1\n\nβ = [10/sum(u0), 1/2, 1/5]\n\ntspan = (0,100.0)\nprob = ODEProblem(fluxes(m), u0, tspan, β)\nsol = OrdinaryDiffEq.solve(prob, alg=Tsit5())\n\nsavedata(sol, \"S,I,E,R\", \"seirdata.csv\")\nPseird = PetriModel(\n          Petri.Model(1:5,[\n            ([1,2],[3,2]), # exposure\n            ([3],[2]),     # onset\n            ([2],[4]),     # recovery\n            ([2],[5]),     # death\n            ], missing, missing))\n\nm = Pseird.model\n\nu0 = zeros(Float64, length(m.S))\nu0[1]  = 10000\nu0[2]  = 1\n\nseirdparams() = begin\n    βseird = [10/sum(u0), 1/2, 1/5, 1/16]\nend\n\ntspan = (0,100.0)\nprob = ODEProblem(fluxes(m), u0, tspan, seirdparams())\nsol = OrdinaryDiffEq.solve(prob, alg=Tsit5())\n\nsavedata(sol, \"S,I,E,R,D\", \"seirddata.csv\")\n", "meta": {"hexsha": "29b6ac435d03b75e243f1740cfc78c4beacd5bc3", "size": 3897, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/covid/validation.jl", "max_stars_repo_name": "redransil/SemanticModels.jl", "max_stars_repo_head_hexsha": "ec65e7efc56ae83bbb013722af508e4d2d87683b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2018-12-05T15:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T08:38:01.000Z", "max_issues_repo_path": "examples/covid/validation.jl", "max_issues_repo_name": "redransil/SemanticModels.jl", "max_issues_repo_head_hexsha": "ec65e7efc56ae83bbb013722af508e4d2d87683b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 177, "max_issues_repo_issues_event_min_datetime": "2018-12-10T13:31:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-06T21:39:54.000Z", "max_forks_repo_path": "examples/covid/validation.jl", "max_forks_repo_name": "redransil/SemanticModels.jl", "max_forks_repo_head_hexsha": "ec65e7efc56ae83bbb013722af508e4d2d87683b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2019-01-23T14:07:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T15:43:21.000Z", "avg_line_length": 22.9235294118, "max_line_length": 115, "alphanum_fraction": 0.545034642, "num_tokens": 1319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7543217312658843}}
{"text": "\nconst LIGHT_SPEED = 299792458 # m/s^2\n\n\"\"\"\n    lerp(t, a, b)\n\nLinear interpolation on the interval `[a, b]` as `t ∈ [0, 1].\n\n\"\"\"\nlerp(t, a, b) = (one(t)-t)*a + t*b\n\n\n\n\"\"\"\n    quadratic(A, B, C)\n\nSolve quadratic equation `A x^2 + B x + C = 0` for real coefficients.\n\nIf a real solution exists, returns `(true, t0, t1)` where `t0` is the smaller\nand `t1` the larger solution. If no real solution exists, returns `(false, Inf, Inf)`.\n\n\"\"\"\nfunction quadratic(A::Real, B::Real, C::Real)\n    dd = B^2 - 4*A*C\n    if dd < 0.0\n        return false, Inf, Inf\n    end\n    q = B<0 ? -0.5 * (B - sqrt(dd)) : -0.5 * (B + sqrt(dd))\n    t0 = q/A\n    t1 = C/q\n    return true, min(t0,t1), max(t0,t1)\nend\n\n\n\n\n\"\"\"\n    round_pow2(n::Integer)\n\nRound an integer up to nearest power of two.\n\"\"\"\nround_pow2(n::Integer) = 2^convert(typeof(n), ceil(log(2, n)))\n\n", "meta": {"hexsha": "47cec0cedc09f9ffa27817cf3b0b65e7dfb6d004", "size": 838, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utility.jl", "max_stars_repo_name": "dronir/GRAYTR", "max_stars_repo_head_hexsha": "5919ce3685faa2f913f9743cacccc79f4f67defe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-19T16:11:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-19T22:21:29.000Z", "max_issues_repo_path": "src/utility.jl", "max_issues_repo_name": "dronir/GRAYTR", "max_issues_repo_head_hexsha": "5919ce3685faa2f913f9743cacccc79f4f67defe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utility.jl", "max_forks_repo_name": "dronir/GRAYTR", "max_forks_repo_head_hexsha": "5919ce3685faa2f913f9743cacccc79f4f67defe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0454545455, "max_line_length": 86, "alphanum_fraction": 0.5751789976, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7543217254431418}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.0\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 889697ff-7f5a-4106-95f7-ca7a294faeb3\nbegin\n\tusing JSServe\n\tPage()\nend\n\n# ╔═╡ 6946373c-8035-485b-9048-7b4d0fc6428f\nusing WGLMakie, Distributions, LinearAlgebra\n\n# ╔═╡ cf1c3faa-1973-11ec-04bf-1f53406ce76b\nmd\"\"\"\n# Chapter 1: Landmark location\n\nFor our first experiment, let's estimate the location of a **landmark**, some feature that we want to keep track of.\n\nThe true position of the landmark is a two-dimensional vector\n\n```math\n\\mathbf{s} = \\begin{bmatrix}\nx_0 \\\\\ny_0\n\\end{bmatrix}\n```\n\nAt every time step, we'll take a measurement ``\\mathbf{z}_t`` of the location of the landmark. This measurement will necessarily have some noise in it. We'll model the noise with an additive Gaussian term:\n\n```math\n\\mathbf{z}_t = \\mathbf{s} + \\varepsilon_t\n```\n\nwhere the noise ``\\varepsilon_t`` is multivariate normally distributed with a mean of zero and a covariance matrix Q:\n\n```math\n\\varepsilon_t \\sim \\mathcal{N}(0,Q)\n```\n\nBecause the noise is additive and Gaussian, we can write the distribution of each observation ``\\mathbf{z}_t`` as \n\n```math\n\\mathbf{z}_t | \\mathbf{s} \\sim \\mathcal{N}(\\mathbf{s},Q)\n```\n\nThis is a *conditional distribution*: if we fix the position of the landmark at ``\\mathbf{s}``, then the observations are independently and identically distributed with a multivariate normal distribution with mean ``\\mathbf{s}`` and covariance $Q$.\n\nTo see what this model looks like, let's generate a data set. We'll fix our landmark at the origin (``\\mathbf{s} = [0,0]``) and create some observations. Let's assume that the covariance matrix is diagonal with a variance of 1 for each component:\n\n```math\nQ = \\begin{bmatrix}\n1 & 0 \\\\\n0 & 1 \n\\end{bmatrix}\n```\n\"\"\"\n\n# ╔═╡ 592cb2f4-7c38-4ecd-b0fc-50d9e409f928\n# Landmark position\ns = [0.0;0.0]\n\n# ╔═╡ 3f91f4e8-e0c9-4f1f-a5a0-7cdfc8bb9d6b\n# Covariance matrix\nQ = [1.0 0.0;\n\t0.0 1.0]\n\n# ╔═╡ 4c06bac4-05b8-4883-b3ca-3da505783fdc\n# Distribution of observations\nd = MvNormal(s,Q)\n\n# ╔═╡ 54ec7d97-477e-4887-a73a-502eeba97910\n# Number of observations\nN = 10\n\n# ╔═╡ 7c36f709-7bb0-4986-8337-e6dea6fc7690\n# Observation data set\nZ = rand(d,N)\n\n# ╔═╡ bc925405-7574-46d4-aa59-7e32bc1acaf7\nbegin\n\tfig = Figure()\n\tax1 = Axis(fig[1,1],xlabel=\"X\",ylabel=\"Y\")\n\tscatter!(ax1,Z,color=:black)\n\tscatter!(ax1,Point2[s],color=:red)\n\tfig\nend\n\n# ╔═╡ 94c08534-71fd-4265-9212-edf76b4517bf\nmd\"\"\"\nIf we don't know the position of the landmark, but we do have the measurements ``\\mathbf{z}_{1:T} = [\\mathbf{z}_1,\\mathbf{z}_2,\\dots,\\mathbf{z}_T]``, how do we go about estimating the landmark's position? There are many different ways to do this, and we'll work up from the simplest one: maximum likelihood estimation.\n\n## Maximum likelihood estimation\n\nRecall our probabilistic model for the observations:\n\n```math\n\\mathbf{z}_t | \\mathbf{s} \\sim \\mathcal{N}(\\mathbf{s},Q)\n```\n\nThis model defines a probability distribution for the whole data set, ``p(\\mathbf{z}_{1:T}|\\mathbf{s})``.\n\n```math\np(\\mathbf{z}_{1:T}|\\mathbf{s}) = \\prod_{t=1}^T p(\\mathbf{z}_t|\\mathbf{s}) \\propto \\prod_{t=1}^T e^{-\\frac{1}{2} \\left(\\mathbf{z}_t - \\mathbf{s}\\right)^\\dagger Q^{-1} \\left(\\mathbf{z}_t - \\mathbf{s}\\right)}\n```\n\nThe first equality here is because we assume that our observations are independently and identically distributed, and thus the joint distribution of the observations ``p(\\mathbf{z}_{1:T}|\\mathbf{s})`` factors into the product of the distribution of the individual observations. The second equality substitutes the expression for a multivariate normal distribution. We use the ``\\propto`` symbol to indicate that we have dropped some terms that don't depend on ``\\mathbf{z}_t$ or $\\mathbf{s}``.\n\nFor convenience, we'll work with the logarithm of this distribution, which is called the (log-)likelihood function\n\n```math\n\\log p(\\mathbf{z}_{1:T}|\\mathbf{s}) = \\sum_{t=1}^T \\log p(\\mathbf{z}_t|\\mathbf{s}) = \\sum_{t=1}^T -\\frac{1}{2} \\left(\\mathbf{z}_t - \\mathbf{s}\\right)^\\dagger Q^{-1} \\left(\\mathbf{z}_t - \\mathbf{s}\\right)\n```\n\nTo estimate ``\\mathbf{s}`` by maximum likelihood, we want to find the value of ``\\mathbf{s}`` that maximizes this expression when we fix our observations ``\\mathbf{z}_{1:T}`` to our dataset. We can find the maximum likelihood estimator, ``\\mathbf{s}``, by taking the derivative of the likelihood function with respect to ``\\mathbf{s}`` and setting the resulting expression equal to zero. Once we've worked through the algebra, we find that\n\n```math\n\\hat{\\mathbf{s}} = \\frac{1}{T}\\sum_{t=1}^T \\mathbf{z}_t\n```\n\nand we see that the maximum likelihood estimator of the position of the landmark is the mean of the observations. Let's plot that along with our dataset.\n\"\"\"\n\n# ╔═╡ e4b53a36-860b-4c3a-b9c9-6f6eafcaeeb9\n# Compute the maximum likelihood estimator\nŝ = mean(Z,dims=2)[:,1]\n\n# ╔═╡ 8b342e24-759b-4ce4-9349-1c46aebe6cad\nbegin\n\tfig2 = Figure()\n\tax2 = Axis(fig2[1,1],xlabel=\"X\",ylabel=\"Y\")\n\tscatter!(ax2,Z,color=:black)\n\tscatter!(ax2,Point2[s],color=:red)\n\tscatter!(ax2,Point2[ŝ],color=:orange)\n\tfig2\nend\n\n# ╔═╡ dbf4d333-b34a-40ce-b6cf-3a17a20cda8f\nmd\"\"\"\nThere is a difference between the maximum likelihood estimator and the true landmark position. We will always have some error, and the magnitude of that error basically depends on how many observations we have. With more observations, the average error will shrink and, as the number of observations approaches infinity, the error will go to zero: our maximum likelihood estimator is *consistent*.\n\nWe can illustrate this property by simulating a bunch of data sets of different sizes and computing the root mean squared error between the maximum likelihood estimator and the true landmark position.\n\"\"\"\n\n# ╔═╡ 6312899f-e92b-42d6-977a-fe8fe8b63011\nfunction rms_error_simulation(N)\n    # Simulate a new data set of size N\n    Z = rand(d,N)\n    \n    # Compute the maximum likelihood estimator of the landmark\n    ŝ = mean(Z,dims=2)[:,1]\n    \n    # Return the distance between s and ŝ\n    sqrt(sum(abs2,s .- ŝ))\nend\n\n# ╔═╡ 62c45184-2e26-4186-9f16-0b4d33944053\n# Simulate 100 times for each value of N from 10 to 10000\nerrors = [mean(rms_error_simulation(N) for i in 1:100) for N in 10:100:10000]\n\n# ╔═╡ 20610ddc-5160-458d-badd-850046a087e2\nbegin\n\tfig3 = Figure()\n\tax3 = Axis(fig3[1,1],\n    xlabel=\"Number of observations\",\n    ylabel=\"Root mean square error\"\n\t)\n\tlines!(ax3,10:100:10000,errors)\n\tfig3\nend\n\n# ╔═╡ 12a3d2e5-7f9f-4b8b-94d4-87911e8ad699\nmd\"\"\"\nThe error decreases with the number of observations and, while it does flatten out as the number of observations increases, it will indeed go to zero as ``N \\to \\infty`` (it decreases like ``\\frac{1}{\\sqrt{N}}``).\n\nThe maximum likelihood estimator of the landmark location is consistent, and it is really easy to compute: just take the mean of the observations. However, we'll find that the maximum likelihood estimator is not so easy to compute in the more complicated models that we'll encounter in the future. We'll turn to Bayesian inference methods to handle these more complicated models, and we'll start our exploration of Bayesian methods by thinking about the landmark location model sequentially.\n\n## Sequential inference\n\nIn the localization and mapping problems that we'll encounter throughout this series, we acquire observations at separate times, and we want our robot to incorporate each observation into its map of the environment when that observation is acquired. We can do this with our maximum likelihood estimator, ``\\hat{\\mathbf{s}}``. We say that the maximum likelihood estimate of the landmark location at time ``t`` is ``\\hat{\\mathbf{s}}_t``, then we can update it with an observation at time ``t+1`` by:\n\n```math\n\\hat{\\mathbf{s}}_{t+1} = \\frac{1}{t+1} \\left(t\\hat{\\mathbf{s}}_t + \\mathbf{z}_t\\right)\n```\n\nBut for more complicated models, this update may not be so simple. Instead, we will represent our current map of the environment by a probability distribution\n\n```math\np_t(\\mathbf{s}) = p\\left(\\mathbf{s}|\\mathbf{z}_{1:t}\\right)\n```\n\nThe map at time ``t`` is the conditional distribution of ``\\mathbf{s}`` given all of the observations up to and including ``\\mathbf{z}_t``.\n\nBayes' rule tells us how to update ``p_t(\\mathbf{s})`` to ``p_{t+1}(\\mathbf{s})``:\n\n```math\np_{t+1}(\\mathbf{s}) = p(\\mathbf{s}|\\mathbf{z}_{1:t+1}) = \\frac{p(\\mathbf{z}_{t+1}|\\mathbf{s},\\mathbf{z}_{1:t}) p(\\mathbf{s}|\\mathbf{z}_{1:t})}{p(\\mathbf{z}_{t+1})} = \\frac{p(\\mathbf{z}_{t+1}|\\mathbf{s},\\mathbf{z}_{1:t})}{p(\\mathbf{z}_{t+1})} p_t(\\mathbf{s})\n```\n\nThe first term in the numerator of Bayes' rule ``p(\\mathbf{z}_{t+1}|\\mathbf{s},\\mathbf{z}_{1:t})`` is called the *likelihood*, and it is similar to our likelihood function from before in that it tells us the probability of obtaining an observation ``\\mathbf{z}_{t+1}`` given that the landmark is at location ``\\mathbf{s}`` and that we've seen the observations ``\\mathbf{z}_{1:t}``. Because our model tells us that the observations are independent and identically distributed given the landmark location, ``\\mathbf{z}_{t+1}`` is actually conditionally independent of ``\\mathbf{z}_{1:t}``, and this part of the likelihood drops out\n\n```math\np(\\mathbf{z}_{t+1} | \\mathbf{s}, \\mathbf{z}_{1:t}) = p(\\mathbf{z}_{t+1}|\\mathbf{s})\n```\n\nwhich is exactly the same likelihood function we saw before.\n\nThe second term in the numerator is just our distribution ``p_t(\\mathbf{s})``. This is the *prior distribution* because it reflects a probability distribution over ``\\mathbf{s}`` before we have incorporated the next measurement. Bayes' rule tells us how to update the prior distribution ``p_t(\\mathbf{s})`` into the *posterior distribution* ``p_{t+1}(\\mathbf{s})``. The rule is recursive: we start with a probability distribution ``p_0(\\mathbf{s})`` that reflects our uncertainty in the location of ``\\mathbf{s}`` before we have seen any data, and from that distribution, we can add information from the observations to form ``p_t(\\mathbf{s})`` at any time. While ``p_t(\\mathbf{s})`` plays the role of the prior distribution in Bayes' rule when we incorporate the observation ``\\mathbf{z}_{t+1}``, ``p_0(\\mathbf{s})`` is usually what is meant by the prior distribution in Bayesian statistics: the distribution before we have seen any data.\n\nThe denominator is the *marginal probability distribution* of ``\\mathbf{z}_{t+1}``. This is given by integrating the numerator over the landmark location\n\n```math\np(\\mathbf{z}_{t+1}) = \\int p(\\mathbf{z}_{t+1}|\\mathbf{s}) p(\\mathbf{s}|\\mathbf{z}_{1:t})\\ \\mathrm{d}\\mathbf{s}\n```\n\nComputing this integral is the hard part in Bayesian statistics, and we'll encounter many different ways of calculating it analytically or approximating it when we can't.\n\n### Sequential Bayesian inference for the landmark location model\n\nOur model above says that the observation ``\\mathbf{z}_t`` conditioned on the landmark location ``\\mathbf{s}`` is multivariate normal with mean ``\\mathbf{s}`` and covariance ``Q``.\n\n```math\n\\mathbf{z}_t | \\mathbf{s} \\sim \\mathcal{N}(\\mathbf{s},Q)\n```\n\nThis gives us the likelihood we need for Bayes' rule.\n\nTo complete the specification of our Bayesian model, we need to define the prior distribution ``p_0(\\mathbf{s})``. It turns out that everything will be very simple if we let the prior distribution also be a multivariate Gaussian with mean ``\\boldsymbol{\\mu}_0`` and covariance ``\\Sigma_0``. We will write\n\n```math\n\\mathbf{s} \\sim \\mathcal{N}(\\boldsymbol{\\mu}_0,\\Sigma_0)\n```\n\nto say that ``\\mathbf{s}`` has this prior distribution, i.e. that\n\n```math\np_0(\\mathbf{s}) \\propto e^{-\\frac{1}{2} (\\mathbf{s} - \\boldsymbol{\\mu}_0)^\\dagger \\Sigma_0^{-1} (\\mathbf{s} - \\boldsymbol{\\mu}_0)}\n```\n\nLet's specify our prior distribution with a mean of zero and a variance of 100 in each dimension. The high variance reflects a high initial uncertainty about the landmark's location.\n\"\"\"\n\n# ╔═╡ f4751245-b653-45fb-8950-0043fdc20018\nbegin\n\tμ₀ = [0.0;0.0]\n\tΣ₀ = [100.0 0.0;0.0 100.0]\n\tp₀ = MvNormal(μ₀,Σ₀)\nend\n\n# ╔═╡ de7b4d82-f035-4f26-989a-bbe0f5d6daa6\nmd\"\"\"\nLet's focus on updating this prior distribution with the information from our first observation ``\\mathbf{z}_1``. We write Bayes' rule\n\n```math\np(\\mathbf{s}|\\mathbf{z}_1) = \\frac{p(\\mathbf{z}_1|\\mathbf{s})}{p(\\mathbf{z}_1)} p_0(\\mathbf{s})\n```\n\nTo make some of the algebra easier, let's take the logarithm of both sides of this equation\n\n```math\n\\log p(\\mathbf{s}|\\mathbf{z}_1) = \\log p(\\mathbf{z}_1|\\mathbf{s}) + \\log p_0(\\mathbf{s}) - \\log p(\\mathbf{z}_1)\n```\n\nand substitute in our expressions for the likelihood and the prior\n\n```math\n\\log p(\\mathbf{s}|\\mathbf{z}_1) = -\\frac{1}{2}(\\mathbf{z}_1 - \\mathbf{s})^\\dagger Q^{-1}(\\mathbf{z}_1 - \\mathbf{s}) - \\frac{1}{2}(\\mathbf{s} - \\boldsymbol{\\mu}_0)^\\dagger \\Sigma_0^{-1} (\\mathbf{s} - \\boldsymbol{\\mu}_0) - \\log p(\\mathbf{z}_1) + C\n```\n\nwhere the constant ``C`` contains some terms that we won't worry about right now because they don't depend on ``\\mathbf{s}``.\n\nWe still haven't written down what the marginal distribution ``p(\\mathbf{z}_1)`` is. However, we don't really need to do that at this point. ``p(\\mathbf{z}_1)`` doesn't depend on ``\\mathbf{s}`` at all, and we can include it in the constant ``C``. There are times when we will want to compute the marginal distribution, but now is not one of them.\n\nOur log posterior density is\n\n```math\n\\log p(\\mathbf{s}|\\mathbf{z}_1) = -\\frac{1}{2}(\\mathbf{z}_1 - \\mathbf{s})^\\dagger Q^{-1}(\\mathbf{z}_1 - \\mathbf{s}) - \\frac{1}{2}(\\mathbf{s} - \\boldsymbol{\\mu}_0)^\\dagger \\Sigma_0^{-1} (\\mathbf{s} - \\boldsymbol{\\mu}_0) + C\n```\n\nwhich we might not immediately recognize as a familiar probability distribution. But we can expand the quadratic functions of ``\\mathbf{s}`` to find:\n\n```math\n\\log p(\\mathbf{s}|\\mathbf{z}_1) = -\\frac{1}{2} \\left( \\mathbf{s}^\\dagger \\left(Q^{-1} + \\Sigma_0^{-1}\\right) \\mathbf{s} - 2\\mathbf{s}^\\dagger\\left(Q^{-1}\\mathbf{z}_1 + \\Sigma_0^{-1} \\boldsymbol{\\mu}_0\\right)\\right) + C\n```\n\nMessing around a bit further with the algebra, we ultimately find that the posterior distribution is a multivariate normal with a mean\n\n```math\n\\boldsymbol{\\mu}_1 = \\left(Q^{-1} + \\Sigma_0^{-1}\\right)^{-1} \\left(Q^{-1}\\mathbf{z}_1 + \\Sigma_0^{-1}\\boldsymbol{\\mu}\\right)\n```\n\nand covariance\n\n```math\n\\Sigma_1 = \\left(Q^{-1} + \\Sigma_0^{-1}\\right)^{-1}\n```\n\nThese are the update equations that we need, and it will work the same for updating at any time step: simply replace ``\\boldsymbol{\\mu}_0`` and ``\\Sigma_0`` on the right-hand side of these equations with ``\\boldsymbol{\\mu}_t`` and ``\\Sigma_t``, and the observation ``\\mathbf{z}_1`` with ``\\mathbf{z}_{t+1}`` to find the updated mean and covariance ``\\boldsymbol{\\mu}_{t+1}`` and ``\\Sigma_{t+1}``.\n\nLet's see how this works in practice. We'll first implement our update equations\n\"\"\"\n\n# ╔═╡ 8a174193-2916-4a01-a2c9-8663e7f4aca2\nfunction update(p₀,z,Q)\n\tμ₀,Σ₀ = p₀.μ,p₀.Σ\n    Σ₁ = inv(inv(Q) + inv(Σ₀))\n    μ₁ = Σ₁ * (Q\\z + Σ₀\\μ₀)\n    MvNormal(μ₁,Σ₁)\nend\n\n# ╔═╡ 90007f4c-1ded-4a08-afa7-a5c344b6c03b\nmd\"\"\"\nAnd then we'll apply the update equations to our model by scanning through the data set one point at a type, updating the probability distribution as we go. We can do this simply with the `accumulate` function.\n\"\"\"\n\n# ╔═╡ ab3b1a1b-8e74-47cf-9b95-df044e2fb86b\nmd\"\"\"\nThe contours represent the posterior probability density function, with the yellow contour surrounding the area with the highest probability density. As we add observations by moving the slider to the right, we can see how the contours shrink and the maximum of the probability density moves towards the origin, which is the true location of the landmark.\n\n\n### Another parameterization\n\nThe update equations in their current form are slightly complicated. One particularly annoying problem is that you have to invert a couple of matrices to figure out the covariance. This isn't too bad when we're working with 2x2 covariance matrices, but with models that have more degrees of freedom, we'd like to avoid inverting big matrices both because it is slow and because it can lead to numerical problems if we're not careful.\n\nWe've parameterized our posterior probability density with its mean ``\\boldsymbol{\\mu}_t`` and covariance ``\\Sigma_t``, which leads to the log posterior probability\n\n```math\n\\log p(\\mathbf{s}|\\mathbf{z}_{1:t}) = -\\frac{1}{2} \\left(\\mathbf{s} - \\boldsymbol{\\mu}_t\\right)^{\\dagger} \\Sigma_t^{-1} \\left(\\mathbf{s} - \\boldsymbol{\\mu}_t\\right) + C\n```\n\nIf we expand the quadratic form and put the terms that don't depend on ``\\mathbf{s}`` in the constant, we end up with\n\n```math\n\\log p(\\mathbf{s}|\\mathbf{z}_{1:t}) = -\\frac{1}{2} \\mathbf{s}^{\\dagger}\\Sigma_t^{-1}\\mathbf{s} + \\Sigma_t^{-1}\\boldsymbol{\\mu}_t^{\\dagger}\\mathbf{s} + C\n```\n\nThe coefficients in this parameterization of the multivariate normal distribution are\n\n```math\n\\begin{align}\n\\Lambda_t &= \\Sigma_t^{-1} \\\\\n\\mathbf{j}_t &= \\Sigma_t^{-1} \\boldsymbol{\\mu}_t\n\\end{align}\n```\n\nWe call the matrix ``\\Lambda_t`` the *precision matrix* and the vector $\\mathbf{j}_t$ the *potential vector* or the *information vector*. With these substitutions, the posterior log probability density becomes\n\n```math\n\\log p(\\mathbf{s}|\\mathbf{z}_{1:t}) = -\\frac{1}{2} \\mathbf{s}^{\\dagger}\\Lambda_t\\mathbf{s} + \\mathbf{j}_t^{\\dagger}\\mathbf{s} + C\n```\n\nWe can represent any multivariate normal distribution with this parameterization. For example, our prior distribution with ``\\boldsymbol{\\mu}_0 = 0`` and ``\\Sigma_t = \\begin{bmatrix} 100 & 0 \\\\ 0 & 100 \\end{bmatrix}`` has a precision matrix ``\\Lambda_0 = \\begin{bmatrix} 0.01 & 0 \\\\ 0 & 0.01 \\end{bmatrix}`` and a potential vector ``\\mathbf{j}_0 = 0``\n\nThe benefit of this parameterization is that the update equations become very simple:\n\n```math\n\\begin{align}\n\\Lambda_{t+1} &= \\Lambda_t + Q^{-1} \\\\\n\\mathbf{j}_{t+1} &= \\mathbf{j}_t + Q^{-1}\\mathbf{z}_{t+1} \n\\end{align}\n```\n\nIf we store ``Q^{-1}`` rather than ``Q``, we don't need to invert any matrices to update our probability distribution.\n\"\"\"\n\n# ╔═╡ 329dae9e-a9b4-4608-bc6e-88953679ea1a\nQi = inv(Q)\n\n# ╔═╡ b00453b8-beb5-4e5f-ac75-ec0d4acc8e72\nmd\"\"\"\nThe Distributions package gives us an `MvNormalCanon` type that uses this \"canonical\" parameterization directly. We can create a new prior distribution using the canonical parameterization.\n\"\"\"\n\n# ╔═╡ bd6bbe7d-5e46-4bab-8d75-6439614a747d\nbegin\n\tΛ₀ = inv(Σ₀)\n\tj₀ = Σ₀\\μ₀\n\tq₀ = MvNormalCanon(j₀,Λ₀)\nend\n\n# ╔═╡ cd9b1e2a-8049-4c44-8d52-c7dcd146708f\nmd\"\"\"\nAnd we can rewrite our update method to work on canonically parameterized distributions. We need to be careful to pass the inverse of the observation noise covariance rather than the the noise covariance.\n\"\"\"\n\n# ╔═╡ 68107d23-f41e-46cc-b6ac-b3195651c35b\nfunction update(q₀::D,z,Qi) where {D <: MvNormalCanon}\n\tj₀,Λ₀ = q₀.h,q₀.J\n\t\n\tj₁ = j₀ + Qi*z\n\tΛ₁ = Λ₀ + Qi\n\tMvNormalCanon(j₁,Λ₁)\nend\n\n# ╔═╡ 55a37b10-7163-4887-942c-1b2d42b7330b\nbegin\n\tZs = Point2[Z[:,i] for i in 1:N]\n\tps = [p₀;accumulate((p,z) -> update(p,z,Q),Zs,init=p₀)]\nend\n\n# ╔═╡ 2985b01b-c602-4cb5-80b2-b39457f3686d\nbegin\n\t\n\tfig4 = Figure()\n\tax4 = Axis(fig4[1,1],xlabel=\"X\",ylabel=\"Y\")\n\tb1 = Makie.Slider(fig4[2,1],range=0:10)\n\t\n\txs = range(-10,10,length=256)\n\t\n\tP = lift(b1.value) do i\n\t\t[pdf(ps[i+1],[x;y]) for x in xs, y in xs]\n\tend\n\t\n\tobs = lift(b1.value) do i\n\t\tif i == 0\n\t\t\t[Point2(20,20.0)]\n\t\telse\n\t\t\tZs[1:i]\n\t\tend\n\tend\n\t\n\tcontour!(ax4,xs,xs,P)\n\tscatter!(ax4,obs,color=:black)\n\t\n\txlims!(ax4,-10,10)\n\tylims!(ax4,-10,10)\n\tfig4\nend\n\n# ╔═╡ 5b07dc5d-6676-4d93-bb4a-7296beded4c3\nmd\"\"\"\nAnd apply our new parameterization to our data set.\n\"\"\"\n\n# ╔═╡ 18cb7c76-5721-4023-b475-edaf410ea1da\nqs = [q₀;accumulate((q,z) -> update(q,z,Qi),Zs,init=q₀)]\n\n# ╔═╡ a098c5b0-6734-4bd2-90d7-5daf69cfd111\nmd\"\"\"\nWe can visualize the results the same way, and they should look the same. We haven't changed the model, just how we write the model.\n\"\"\"\n\n# ╔═╡ 51369139-452b-4fe9-a441-9f0f13713faf\nbegin\n\t\n\tfig5 = Figure()\n\tax5 = Axis(fig5[1,1],xlabel=\"X\",ylabel=\"Y\")\n\tsl5 = Makie.Slider(fig5[2,1],range=0:N)\n\t\n\tP5 = lift(sl5.value) do i\n\t\t[pdf(qs[i+1],[x;y]) for x in xs, y in xs]\n\tend\n\t\n\tobs5 = lift(sl5.value) do i\n\t\tif i == 0\n\t\t\t[Point2(20,20.0)]\n\t\telse\n\t\t\tZs[1:i]\n\t\tend\n\tend\n\t\n\tcontour!(ax5,xs,xs,P5)\n\tscatter!(ax5,obs5,color=:black)\n\t\n\txlims!(ax5,-10,10)\n\tylims!(ax5,-10,10)\n\tfig5\nend\n\n# ╔═╡ b7c5a266-8264-4829-a040-7d11fe635b8a\nmd\"\"\"\nThis canonical parameterization is very useful for Bayesian inference problems because the Bayesian update equations become simple additions. There are tradeoffs, though. You have to solve a system of linear equations to recover the mean of the posterior distribution, which is also the maximum a posteriori estimate of the landmark location. Computing the marginal probability ``p(\\mathbf{z}_t)`` is also harder in the canonical parameterization. So you have to choose which is right for the particular application you are using, and we'll flip back and forth throughout these experiments.\n\nThat's it for our first lesson. In future lessons, we'll look at increasingly complicated localization and mapping problems and how we can solve them with Bayesian inference.\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nDistributions = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nJSServe = \"824d6782-a2ef-11e9-3a09-e5662e0c26f9\"\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nWGLMakie = \"276b4fcb-3e11-5398-bf8b-a0c2d153d008\"\n\n[compat]\nDistributions = \"~0.25.16\"\nJSServe = \"~1.2.3\"\nWGLMakie = \"~0.4.6\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[AbstractFFTs]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"485ee0867925449198280d4af84bdb46a2a404d0\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"1.0.1\"\n\n[[AbstractTrees]]\ngit-tree-sha1 = \"03e0550477d86222521d254b741d470ba17ea0b5\"\nuuid = \"1520ce14-60c1-5f80-bbc7-55ef81b5835c\"\nversion = \"0.3.4\"\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[Animations]]\ndeps = [\"Colors\"]\ngit-tree-sha1 = \"e81c509d2c8e49592413bfb0bb3b08150056c79d\"\nuuid = \"27a7e980-b3e6-11e9-2bcd-0b925532e340\"\nversion = \"0.4.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[ArrayInterface]]\ndeps = [\"Compat\", \"IfElse\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"Static\"]\ngit-tree-sha1 = \"b8d49c34c3da35f220e7295659cd0bab8e739fed\"\nuuid = \"4fba245c-0d91-5ea0-9b3e-6abc04ee57a9\"\nversion = \"3.1.33\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Automa]]\ndeps = [\"Printf\", \"ScanByte\", \"TranscodingStreams\"]\ngit-tree-sha1 = \"d50976f217489ce799e366d9561d56a98a30d7fe\"\nuuid = \"67c07d97-cdcb-5c2c-af73-a7f9c32a568b\"\nversion = \"0.8.2\"\n\n[[AxisAlgorithms]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"a4d07a1c313392a77042855df46c5f534076fab9\"\nuuid = \"13072b0f-2c55-5437-9ae7-d433b7a33950\"\nversion = \"1.0.0\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[CEnum]]\ngit-tree-sha1 = \"215a9aa4a1f23fbd05b92769fdd62559488d70e9\"\nuuid = \"fa961155-64e5-5f13-b03f-caf6b980ea82\"\nversion = \"0.4.1\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"f2202b55d816427cd385a9a4f3ffb226bee80f99\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+0\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"4ce9393e871aca86cc457d9f66976c3da6902ea7\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.4.0\"\n\n[[CodecZlib]]\ndeps = [\"TranscodingStreams\", \"Zlib_jll\"]\ngit-tree-sha1 = \"ded953804d019afa9a3f98981d99b33e3db7b6da\"\nuuid = \"944b1d66-785c-5afd-91f1-9de20f533193\"\nversion = \"0.7.0\"\n\n[[ColorBrewer]]\ndeps = [\"Colors\", \"JSON\", \"Test\"]\ngit-tree-sha1 = \"61c5334f33d91e570e1d0c3eb5465835242582c4\"\nuuid = \"a2cac450-b92f-5266-8821-25eda20663c8\"\nversion = \"0.4.0\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"9995eb3977fbf67b86d0a0a0508e83017ded03f2\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.14.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[ColorVectorSpace]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"LinearAlgebra\", \"SpecialFunctions\", \"Statistics\", \"TensorCore\"]\ngit-tree-sha1 = \"a66a8e024807c4b3d186eb1cab2aff3505271f8e\"\nuuid = \"c3611d14-8923-5661-9e6a-0046d554d3a4\"\nversion = \"0.9.6\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"4866e381721b30fac8dda4c8cb1d9db45c8d2994\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.37.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"bec2532f8adb82005476c141ec23e921fc20971b\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.8.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Distributions]]\ndeps = [\"ChainRulesCore\", \"FillArrays\", \"LinearAlgebra\", \"PDMats\", \"Printf\", \"QuadGK\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\"]\ngit-tree-sha1 = \"f4efaa4b5157e0cdb8283ae0b5428bc9208436ed\"\nuuid = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nversion = \"0.25.16\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"a32185f5428d3986f47c2ab78b1f216d5e6cc96f\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.5\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[EllipsisNotation]]\ndeps = [\"ArrayInterface\"]\ngit-tree-sha1 = \"8041575f021cba5a099a456b4163c9a08b566a02\"\nuuid = \"da5c29d0-fa7d-589e-88eb-ea29b0a81949\"\nversion = \"1.1.0\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FFTW]]\ndeps = [\"AbstractFFTs\", \"FFTW_jll\", \"LinearAlgebra\", \"MKL_jll\", \"Preferences\", \"Reexport\"]\ngit-tree-sha1 = \"463cb335fa22c4ebacfd1faba5fde14edb80d96c\"\nuuid = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nversion = \"1.4.5\"\n\n[[FFTW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea\"\nuuid = \"f5851436-0d7a-5f13-b9de-f02708fd171a\"\nversion = \"3.3.10+0\"\n\n[[FileIO]]\ndeps = [\"Pkg\", \"Requires\", \"UUIDs\"]\ngit-tree-sha1 = \"3c041d2ac0a52a12a27af2782b34900d9c3ee68c\"\nuuid = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nversion = \"1.11.1\"\n\n[[FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"caf289224e622f518c9dbfe832cdafa17d7c80a6\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.12.4\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[FreeType]]\ndeps = [\"CEnum\", \"FreeType2_jll\"]\ngit-tree-sha1 = \"cabd77ab6a6fdff49bfd24af2ebe76e6e018a2b4\"\nuuid = \"b38be410-82b0-50bf-ab77-7b57e271db43\"\nversion = \"4.0.0\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FreeTypeAbstraction]]\ndeps = [\"ColorVectorSpace\", \"Colors\", \"FreeType\", \"GeometryBasics\", \"StaticArrays\"]\ngit-tree-sha1 = \"19d0f1e234c13bbfd75258e55c52aa1d876115f5\"\nuuid = \"663a7486-cb36-511b-a19d-713bb74d65c9\"\nversion = \"0.9.2\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"7bf67e9a481712b3dbe9cb3dac852dc4b1162e02\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+0\"\n\n[[Graphics]]\ndeps = [\"Colors\", \"LinearAlgebra\", \"NaNMath\"]\ngit-tree-sha1 = \"2c1cf4df419938ece72de17f368a021ee162762e\"\nuuid = \"a2bd30eb-e257-5431-a919-1863eab51364\"\nversion = \"1.1.0\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[GridLayoutBase]]\ndeps = [\"GeometryBasics\", \"InteractiveUtils\", \"Match\", \"Observables\"]\ngit-tree-sha1 = \"e2f606c87d09d5187bb6069dab8cee0af7c77bdb\"\nuuid = \"3955a311-db13-416c-9275-1d80ed98e5e9\"\nversion = \"0.6.1\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"60ed5f1643927479f845b0135bb369b031b541fa\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.14\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"8a954fed8ac097d5be04921d595f741115c1b2ad\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+0\"\n\n[[Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[IfElse]]\ngit-tree-sha1 = \"28e837ff3e7a6c3cdb252ce49fb412c8eb3caeef\"\nuuid = \"615f187c-cbe4-4ef1-ba3b-2fcf58d6d173\"\nversion = \"0.1.0\"\n\n[[ImageCore]]\ndeps = [\"AbstractFFTs\", \"ColorVectorSpace\", \"Colors\", \"FixedPointNumbers\", \"Graphics\", \"MappedArrays\", \"MosaicViews\", \"OffsetArrays\", \"PaddedViews\", \"Reexport\"]\ngit-tree-sha1 = \"595155739d361589b3d074386f77c107a8ada6f7\"\nuuid = \"a09fc81d-aa75-5fe9-8630-4744c3626534\"\nversion = \"0.9.2\"\n\n[[ImageIO]]\ndeps = [\"FileIO\", \"Netpbm\", \"OpenEXR\", \"PNGFiles\", \"TiffImages\", \"UUIDs\"]\ngit-tree-sha1 = \"13c826abd23931d909e4c5538643d9691f62a617\"\nuuid = \"82e4d734-157c-48bb-816b-45c225c6df19\"\nversion = \"0.5.8\"\n\n[[ImageMagick]]\ndeps = [\"FileIO\", \"ImageCore\", \"ImageMagick_jll\", \"InteractiveUtils\", \"Libdl\", \"Pkg\", \"Random\"]\ngit-tree-sha1 = \"5bc1cb62e0c5f1005868358db0692c994c3a13c6\"\nuuid = \"6218d12a-5da1-5696-b52f-db25d2ecc6d1\"\nversion = \"1.2.1\"\n\n[[ImageMagick_jll]]\ndeps = [\"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pkg\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"1c0a2295cca535fabaf2029062912591e9b61987\"\nuuid = \"c73af94c-d91f-53ed-93a7-00f77d67a9d7\"\nversion = \"6.9.10-12+3\"\n\n[[Imath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"87f7662e03a649cffa2e05bf19c303e168732d3e\"\nuuid = \"905a6f67-0a94-5f89-b386-d35d92009cd1\"\nversion = \"3.1.2+0\"\n\n[[IndirectArrays]]\ngit-tree-sha1 = \"012e604e1c7458645cb8b436f8fba789a51b257f\"\nuuid = \"9b13fd28-a010-5f03-acff-a1bbcff69959\"\nversion = \"1.0.0\"\n\n[[Inflate]]\ngit-tree-sha1 = \"f5fc07d4e706b84f72d54eedcc1c13d92fb0871c\"\nuuid = \"d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9\"\nversion = \"0.1.2\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[IntelOpenMP_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d979e54b71da82f3a65b62553da4fc3d18c9004c\"\nuuid = \"1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0\"\nversion = \"2018.0.3+2\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[Interpolations]]\ndeps = [\"AxisAlgorithms\", \"ChainRulesCore\", \"LinearAlgebra\", \"OffsetArrays\", \"Random\", \"Ratios\", \"Requires\", \"SharedArrays\", \"SparseArrays\", \"StaticArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"61aa005707ea2cebf47c8d780da8dc9bc4e0c512\"\nuuid = \"a98d9a8b-a2ab-59e6-89dd-64a1c18fca59\"\nversion = \"0.13.4\"\n\n[[IntervalSets]]\ndeps = [\"Dates\", \"EllipsisNotation\", \"Statistics\"]\ngit-tree-sha1 = \"3cc368af3f110a767ac786560045dceddfc16758\"\nuuid = \"8197267c-284f-5f27-9208-e0e47529a953\"\nversion = \"0.5.3\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"f76424439413893a832026ca355fe273e93bce94\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.0\"\n\n[[Isoband]]\ndeps = [\"isoband_jll\"]\ngit-tree-sha1 = \"f9b6d97355599074dc867318950adaa6f9946137\"\nuuid = \"f1662d9f-8043-43de-a69a-05efc1cc6ff4\"\nversion = \"0.1.1\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[JSON3]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"StructTypes\", \"UUIDs\"]\ngit-tree-sha1 = \"b3e5984da3c6c95bcf6931760387ff2e64f508f3\"\nuuid = \"0f8b85d8-7281-11e9-16c2-39a750bddbf1\"\nversion = \"1.9.1\"\n\n[[JSServe]]\ndeps = [\"Base64\", \"CodecZlib\", \"Colors\", \"HTTP\", \"Hyperscript\", \"JSON3\", \"LinearAlgebra\", \"Markdown\", \"MsgPack\", \"Observables\", \"SHA\", \"Sockets\", \"Tables\", \"Test\", \"UUIDs\", \"WebSockets\", \"WidgetsBase\"]\ngit-tree-sha1 = \"91101a4b8ac8eefeed6ca8eb4f663fc660e4d9f9\"\nuuid = \"824d6782-a2ef-11e9-3a09-e5662e0c26f9\"\nversion = \"1.2.3\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[KernelDensity]]\ndeps = [\"Distributions\", \"DocStringExtensions\", \"FFTW\", \"Interpolations\", \"StatsBase\"]\ngit-tree-sha1 = \"591e8dc09ad18386189610acafb970032c519707\"\nuuid = \"5ab0869b-81aa-558d-bb23-cbf5423bbe9b\"\nversion = \"0.6.3\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"761a393aeccd6aa92ec3515e428c26bf99575b3b\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+0\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"DocStringExtensions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"34dc30f868e368f8a17b728a1238f3fcda43931a\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.3\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MKL_jll]]\ndeps = [\"Artifacts\", \"IntelOpenMP_jll\", \"JLLWrappers\", \"LazyArtifacts\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"5455aef09b40e5020e1520f551fa3135040d4ed0\"\nuuid = \"856f044c-d86e-5d09-b602-aeab76dc8ba7\"\nversion = \"2021.1.1+2\"\n\n[[Makie]]\ndeps = [\"Animations\", \"Base64\", \"ColorBrewer\", \"ColorSchemes\", \"ColorTypes\", \"Colors\", \"Contour\", \"Distributions\", \"DocStringExtensions\", \"FFMPEG\", \"FileIO\", \"FixedPointNumbers\", \"Formatting\", \"FreeType\", \"FreeTypeAbstraction\", \"GeometryBasics\", \"GridLayoutBase\", \"ImageIO\", \"IntervalSets\", \"Isoband\", \"KernelDensity\", \"LaTeXStrings\", \"LinearAlgebra\", \"MakieCore\", \"Markdown\", \"Match\", \"MathTeXEngine\", \"Observables\", \"Packing\", \"PlotUtils\", \"PolygonOps\", \"Printf\", \"Random\", \"RelocatableFolders\", \"Serialization\", \"Showoff\", \"SignedDistanceFields\", \"SparseArrays\", \"StaticArrays\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"StructArrays\", \"UnicodeFun\"]\ngit-tree-sha1 = \"7e49f989e7c7f50fe55bd92d45329c9cf3f2583d\"\nuuid = \"ee78f7c6-11fb-53f2-987a-cfe4a2b5a57a\"\nversion = \"0.15.2\"\n\n[[MakieCore]]\ndeps = [\"Observables\"]\ngit-tree-sha1 = \"7bcc8323fb37523a6a51ade2234eee27a11114c8\"\nuuid = \"20f20a25-4f0e-4fdf-b5d1-57303727442b\"\nversion = \"0.1.3\"\n\n[[MappedArrays]]\ngit-tree-sha1 = \"e8b359ef06ec72e8c030463fe02efe5527ee5142\"\nuuid = \"dbb5928d-eab1-5f90-85c2-b9b0edb7c900\"\nversion = \"0.4.1\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[Match]]\ngit-tree-sha1 = \"5cf525d97caf86d29307150fcba763a64eaa9cbe\"\nuuid = \"7eb4fadd-790c-5f42-8a69-bfa0b872bfbf\"\nversion = \"1.1.0\"\n\n[[MathTeXEngine]]\ndeps = [\"AbstractTrees\", \"Automa\", \"DataStructures\", \"FreeTypeAbstraction\", \"GeometryBasics\", \"LaTeXStrings\", \"REPL\", \"RelocatableFolders\", \"Test\"]\ngit-tree-sha1 = \"f5c8789464aed7058107463e5cef53e6ad3f1f3e\"\nuuid = \"0a4f8689-d25c-4efe-a92b-7142dfc1aa53\"\nversion = \"0.2.0\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MosaicViews]]\ndeps = [\"MappedArrays\", \"OffsetArrays\", \"PaddedViews\", \"StackViews\"]\ngit-tree-sha1 = \"b34e3bc3ca7c94914418637cb10cc4d1d80d877d\"\nuuid = \"e94cdb99-869f-56ef-bcf0-1ae2bcbe0389\"\nversion = \"0.3.3\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[MsgPack]]\ndeps = [\"Serialization\"]\ngit-tree-sha1 = \"a8cbf066b54d793b9a48c5daa5d586cf2b5bd43d\"\nuuid = \"99f44e22-a591-53d1-9472-aa23ef4bd671\"\nversion = \"1.1.0\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[Netpbm]]\ndeps = [\"FileIO\", \"ImageCore\"]\ngit-tree-sha1 = \"18efc06f6ec36a8b801b23f076e3c6ac7c3bf153\"\nuuid = \"f09324ee-3d7c-5217-9330-fc30815ba969\"\nversion = \"1.0.2\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Observables]]\ngit-tree-sha1 = \"fe29afdef3d0c4a8286128d4e45cc50621b1e43d\"\nuuid = \"510215fc-4207-5dde-b226-833fc4488ee2\"\nversion = \"0.4.0\"\n\n[[OffsetArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"c0e9e582987d36d5a61e650e6e543b9e44d9914b\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.7\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+0\"\n\n[[OpenEXR]]\ndeps = [\"Colors\", \"FileIO\", \"OpenEXR_jll\"]\ngit-tree-sha1 = \"327f53360fdb54df7ecd01e96ef1983536d1e633\"\nuuid = \"52e1d378-f018-4a11-a4be-720524705ac7\"\nversion = \"0.3.2\"\n\n[[OpenEXR_jll]]\ndeps = [\"Artifacts\", \"Imath_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"923319661e9a22712f24596ce81c54fc0366f304\"\nuuid = \"18a262bb-aa17-5467-a713-aee519bc75cb\"\nversion = \"3.1.1+0\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[PDMats]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"SuiteSparse\"]\ngit-tree-sha1 = \"4dd403333bcf0909341cfe57ec115152f937d7d8\"\nuuid = \"90014a1f-27ba-587c-ab20-58faa44d9150\"\nversion = \"0.11.1\"\n\n[[PNGFiles]]\ndeps = [\"Base64\", \"CEnum\", \"ImageCore\", \"IndirectArrays\", \"OffsetArrays\", \"libpng_jll\"]\ngit-tree-sha1 = \"e14c485f6beee0c7a8dcf6128bf70b85f1fe201e\"\nuuid = \"f57f5aa1-a3ce-4bc8-8ab9-96f992907883\"\nversion = \"0.3.9\"\n\n[[Packing]]\ndeps = [\"GeometryBasics\"]\ngit-tree-sha1 = \"1155f6f937fa2b94104162f01fa400e192e4272f\"\nuuid = \"19eb6ba3-879d-56ad-ad62-d5c202156566\"\nversion = \"0.4.2\"\n\n[[PaddedViews]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"646eed6f6a5d8df6708f15ea7e02a7a2c4fe4800\"\nuuid = \"5432bcbf-9aad-5242-b902-cca2824c8663\"\nversion = \"0.5.10\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"438d35d2d95ae2c5e8780b330592b6de8494e779\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.3\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PkgVersion]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"a7a7e1a88853564e551e4eba8650f8c38df79b37\"\nuuid = \"eebad327-c553-4316-9ea0-9fa01ccd7688\"\nversion = \"0.1.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"2537ed3c0ed5e03896927187f5f2ee6a4ab342db\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.0.14\"\n\n[[PolygonOps]]\ngit-tree-sha1 = \"c031d2332c9a8e1c90eca239385815dc271abb22\"\nuuid = \"647866c9-e3ac-4575-94e7-e3d426903924\"\nversion = \"0.1.1\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[ProgressMeter]]\ndeps = [\"Distributed\", \"Printf\"]\ngit-tree-sha1 = \"afadeba63d90ff223a6a48d2009434ecee2ec9e8\"\nuuid = \"92933f4c-e287-5a05-a399-4b506db050ca\"\nversion = \"1.7.1\"\n\n[[QuadGK]]\ndeps = [\"DataStructures\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"78aadffb3efd2155af139781b8a8df1ef279ea39\"\nuuid = \"1fd47b50-473d-5c70-9696-f719f8f3bcdc\"\nversion = \"2.4.2\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Ratios]]\ndeps = [\"Requires\"]\ngit-tree-sha1 = \"01d341f502250e81f6fec0afe662aa861392a3aa\"\nuuid = \"c84ed2f1-dad5-54f0-aa8e-dbefe2724439\"\nversion = \"0.4.2\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[RelocatableFolders]]\ndeps = [\"SHA\", \"Scratch\"]\ngit-tree-sha1 = \"0529f4188bc8efee85a7e580aca1c7dff6b103f8\"\nuuid = \"05181044-ff0b-4ac5-8273-598c1e38db00\"\nversion = \"0.1.0\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[Rmath]]\ndeps = [\"Random\", \"Rmath_jll\"]\ngit-tree-sha1 = \"bf3188feca147ce108c76ad82c2792c57abe7b1f\"\nuuid = \"79098fc4-a85e-5d69-aa6a-4863f24498fa\"\nversion = \"0.7.0\"\n\n[[Rmath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"68db32dff12bb6127bac73c209881191bf0efbb7\"\nuuid = \"f50d1b31-88e8-58de-be2c-1cc44531875f\"\nversion = \"0.3.0+0\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[SIMD]]\ngit-tree-sha1 = \"9ba33637b24341aba594a2783a502760aa0bff04\"\nuuid = \"fdea26ae-647d-5447-a871-4b548cad5224\"\nversion = \"3.3.1\"\n\n[[ScanByte]]\ndeps = [\"Libdl\", \"SIMD\"]\ngit-tree-sha1 = \"9cc2955f2a254b18be655a4ee70bc4031b2b189e\"\nuuid = \"7b38b023-a4d7-4c5e-8d43-3f3097f304eb\"\nversion = \"0.3.0\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[ShaderAbstractions]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"GeometryBasics\", \"LinearAlgebra\", \"Observables\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"0d97c895406b552bed78f3a1fe9925248e908ae2\"\nuuid = \"65257c39-d410-5151-9873-9b3e5be5013e\"\nversion = \"0.2.8\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[SignedDistanceFields]]\ndeps = [\"Random\", \"Statistics\", \"Test\"]\ngit-tree-sha1 = \"d263a08ec505853a5ff1c1ebde2070419e3f28e9\"\nuuid = \"73760f76-fbc4-59ce-8f25-708e95d2df96\"\nversion = \"0.4.0\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"LogExpFunctions\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"a322a9493e49c5f3a10b50df3aedaf1cdb3244b7\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.6.1\"\n\n[[StackViews]]\ndeps = [\"OffsetArrays\"]\ngit-tree-sha1 = \"46e589465204cd0c08b4bd97385e4fa79a0c770c\"\nuuid = \"cae243ae-269e-4f55-b966-ac2d0dc13c15\"\nversion = \"0.1.1\"\n\n[[Static]]\ndeps = [\"IfElse\"]\ngit-tree-sha1 = \"a8f30abc7c64a39d389680b74e749cf33f872a70\"\nuuid = \"aedffcd0-7271-4cad-89d0-dc628f76c6d3\"\nversion = \"0.3.3\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3240808c6d463ac46f1c1cd7638375cd22abbccb\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.12\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"1958272568dc176a1d881acb797beb909c785510\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.0.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"8cbbc098554648c84f79a463c9ff0fd277144b6c\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.10\"\n\n[[StatsFuns]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"Reexport\", \"Rmath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"46d7ccc7104860c38b11966dd1f72ff042f382e4\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.10\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.3\"\n\n[[StructTypes]]\ndeps = [\"Dates\", \"UUIDs\"]\ngit-tree-sha1 = \"8445bf99a36d703a09c601f9a57e2f83000ef2ae\"\nuuid = \"856f2bd8-1eba-4b0a-8007-ebc267875bd4\"\nversion = \"1.7.3\"\n\n[[SuiteSparse]]\ndeps = [\"Libdl\", \"LinearAlgebra\", \"Serialization\", \"SparseArrays\"]\nuuid = \"4607b0f0-06f3-5cda-b6b1-a6196a1729e9\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"1162ce4a6c4b7e31e0e6b14486a6986951c73be9\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.5.2\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[TensorCore]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"1feb45f88d133a655e001435632f019a9a1bcdb6\"\nuuid = \"62fd8b95-f654-4bbd-a8a5-9c27f68ccd50\"\nversion = \"0.1.1\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[TiffImages]]\ndeps = [\"ColorTypes\", \"DocStringExtensions\", \"FileIO\", \"FixedPointNumbers\", \"IndirectArrays\", \"Inflate\", \"OffsetArrays\", \"OrderedCollections\", \"PkgVersion\", \"ProgressMeter\"]\ngit-tree-sha1 = \"632a8d4dbbad6627a4d2d21b1c6ebcaeebb1e1ed\"\nuuid = \"731e570b-9d59-4bfa-96dc-6df516fadf69\"\nversion = \"0.4.2\"\n\n[[TranscodingStreams]]\ndeps = [\"Random\", \"Test\"]\ngit-tree-sha1 = \"216b95ea110b5972db65aa90f88d8d89dcb8851c\"\nuuid = \"3bb67fe8-82b1-5028-8e26-92a6c54297fa\"\nversion = \"0.9.6\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[UnicodeFun]]\ndeps = [\"REPL\"]\ngit-tree-sha1 = \"53915e50200959667e78a92a418594b428dffddf\"\nuuid = \"1cfade01-22cf-5700-b092-accc4b62d6e1\"\nversion = \"0.4.1\"\n\n[[WGLMakie]]\ndeps = [\"Colors\", \"FileIO\", \"FreeTypeAbstraction\", \"GeometryBasics\", \"Hyperscript\", \"ImageMagick\", \"JSServe\", \"LinearAlgebra\", \"Makie\", \"Observables\", \"ShaderAbstractions\", \"StaticArrays\"]\ngit-tree-sha1 = \"bafa1c4ab77626f8d8199209b740e097ae03805f\"\nuuid = \"276b4fcb-3e11-5398-bf8b-a0c2d153d008\"\nversion = \"0.4.6\"\n\n[[WebSockets]]\ndeps = [\"Base64\", \"Dates\", \"HTTP\", \"Logging\", \"Sockets\"]\ngit-tree-sha1 = \"f91a602e25fe6b89afc93cf02a4ae18ee9384ce3\"\nuuid = \"104b5d7c-a370-577a-8038-80a2059c5097\"\nversion = \"1.5.9\"\n\n[[WidgetsBase]]\ndeps = [\"Observables\"]\ngit-tree-sha1 = \"c1ef6e02bc457c3b23aafc765b94c3dcd25f174d\"\nuuid = \"eead4739-05f7-45a1-878c-cee36b57321c\"\nversion = \"0.1.3\"\n\n[[WoodburyMatrices]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"59e2ad8fd1591ea019a5259bd012d7aee15f995c\"\nuuid = \"efce3f68-66dc-5838-9240-27a6d6f5f9b6\"\nversion = \"0.5.3\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[isoband_jll]]\ndeps = [\"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"a1ac99674715995a536bbce674b068ec1b7d893d\"\nuuid = \"9a68df92-36a6-505f-a73e-abb412b6bfb4\"\nversion = \"0.2.2+0\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╠═889697ff-7f5a-4106-95f7-ca7a294faeb3\n# ╠═6946373c-8035-485b-9048-7b4d0fc6428f\n# ╟─cf1c3faa-1973-11ec-04bf-1f53406ce76b\n# ╠═592cb2f4-7c38-4ecd-b0fc-50d9e409f928\n# ╠═3f91f4e8-e0c9-4f1f-a5a0-7cdfc8bb9d6b\n# ╠═4c06bac4-05b8-4883-b3ca-3da505783fdc\n# ╠═54ec7d97-477e-4887-a73a-502eeba97910\n# ╠═7c36f709-7bb0-4986-8337-e6dea6fc7690\n# ╟─bc925405-7574-46d4-aa59-7e32bc1acaf7\n# ╟─94c08534-71fd-4265-9212-edf76b4517bf\n# ╠═e4b53a36-860b-4c3a-b9c9-6f6eafcaeeb9\n# ╟─8b342e24-759b-4ce4-9349-1c46aebe6cad\n# ╟─dbf4d333-b34a-40ce-b6cf-3a17a20cda8f\n# ╠═6312899f-e92b-42d6-977a-fe8fe8b63011\n# ╠═62c45184-2e26-4186-9f16-0b4d33944053\n# ╟─20610ddc-5160-458d-badd-850046a087e2\n# ╟─12a3d2e5-7f9f-4b8b-94d4-87911e8ad699\n# ╠═f4751245-b653-45fb-8950-0043fdc20018\n# ╟─de7b4d82-f035-4f26-989a-bbe0f5d6daa6\n# ╠═8a174193-2916-4a01-a2c9-8663e7f4aca2\n# ╟─90007f4c-1ded-4a08-afa7-a5c344b6c03b\n# ╠═55a37b10-7163-4887-942c-1b2d42b7330b\n# ╟─2985b01b-c602-4cb5-80b2-b39457f3686d\n# ╟─ab3b1a1b-8e74-47cf-9b95-df044e2fb86b\n# ╠═329dae9e-a9b4-4608-bc6e-88953679ea1a\n# ╟─b00453b8-beb5-4e5f-ac75-ec0d4acc8e72\n# ╠═bd6bbe7d-5e46-4bab-8d75-6439614a747d\n# ╟─cd9b1e2a-8049-4c44-8d52-c7dcd146708f\n# ╠═68107d23-f41e-46cc-b6ac-b3195651c35b\n# ╟─5b07dc5d-6676-4d93-bb4a-7296beded4c3\n# ╠═18cb7c76-5721-4023-b475-edaf410ea1da\n# ╟─a098c5b0-6734-4bd2-90d7-5daf69cfd111\n# ╟─51369139-452b-4fe9-a441-9f0f13713faf\n# ╟─b7c5a266-8264-4829-a040-7d11fe635b8a\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "cd03737ae7f7d809426271ebd2ab6cb6337e409e", "size": 60449, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/Chapter1.jl", "max_stars_repo_name": "wkearn/SLAMNotes", "max_stars_repo_head_hexsha": "c6132acbe6a36eb7875052be3adad38174a5426c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/Chapter1.jl", "max_issues_repo_name": "wkearn/SLAMNotes", "max_issues_repo_head_hexsha": "c6132acbe6a36eb7875052be3adad38174a5426c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Chapter1.jl", "max_forks_repo_name": "wkearn/SLAMNotes", "max_forks_repo_head_hexsha": "c6132acbe6a36eb7875052be3adad38174a5426c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1320980275, "max_line_length": 939, "alphanum_fraction": 0.7293255472, "num_tokens": 25344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7543217254017894}}
{"text": "# # A simple FEM application\n#\n# ## Introduction\n# The Finite Element Method is widely used to solve PDEs in Engineering applications and particularly in Structural Analysis problems [Add citation Bathe]. A specific case os structures is Truss structures, where trusses or bars are connected but not welded. Truss models are considered during the conceptual design of bridges or other structures.\n#\n# The stiffness matrix of a truss element in the local coordinate system is given by\n# ```math\n# K_L = s\n# \\left(\n#  \\begin{matrix}\n#  1 & 0 & -1 & 0 \\\\\n#  0 & 0 &  0 & 0 \\\\\n# -1 & 0 &  1 & 0 \\\\\n#  0 & 0 &  0 & 0\n# \\end{matrix}\n# \\right),\n# ```\n#\n# where $s$ is the stiffness, given by $EA/L$, with $E$ being the Young modulus, $A$ the area of the cross-section and $L$ the length of that truss element.\n#\n# The change-of-basis matrix is given by\n# ```math\n# _G(Q)_L = Q =\n# \\left(\n#   \\begin{matrix}\n# \\cos(\\alpha) & -\\sin(\\alpha) & 0 & 0 \\\\\n#  sin(alpha) & cos(alpha) &  0 & 0 \\\\\n#  0 & 0 &  cos(alpha) & sin(alpha) \\\\\n#  0 & 0 &  sin(alpha) & cos(alpha)\n# \\end{matrix}\n# \\right),\n# ```\n#\n# The system of equations for each element is written in local coordinates as\n# ```math\n# K_L d_L = f_L\n# ```\n# and using the change-of-basis we obtain\n# ```math\n# K_G d_G = f_G \\qquad K_G = Q K_L Q^T\n# ```\n#\n# The stiffness matrix can be computed using the following function, which computes the unitary stiffness matrix for an element defined by the coordinates of its first and second nodes.\nfunction unitaryStiffnessMatrix( coordFirstNode, coordSecondNode  )\n  diff      = (coordSecondNode - coordFirstNode)\n  length   = sqrt( diff'*diff )\n  c        = diff[1] / length ;\n  s        = diff[2] / length ;\n  Qloc2glo = [ c -s 0 0 ; s c 0 0 ; 0 0 c -s ; 0 0 s c ] ;\n  Kloc     = [ 1 0 -1 0 ; 0 0 0 0 ; -1 0 1 0 ; 0 0 0 0 ] ;\n  Kglo     = Qloc2glo * Kloc * transpose(Qloc2glo)\n  return     Kglo, length\nend\n#\n# ## Problem with fixed parameters\n# In this section, a problem based on Example 4.1 from [https://github.com/JuliaIntervals/IntervalLinearAlgebra.jl/files/7271616/skalna2006.pdf] is considered. The following diagram shows the truss structure considered.\n#\n# \\fig{../../assets/trussDiagram.png}\n#\n# The scalar parameters considered are given by\nE = 2e11 ; # Young modulus\nA = 5e-3 ; # Cross-section area\n# while the coordinate matrix is given by\nnodesCMatrix = [ 0. 0. ;\n                 1. 1. ;\n                 2. 0. ;\n                 3. 1. ;\n                 4. 0. ]\n# and connectivity matrix is given by\nconnecMatrix = [ 1 2 ;\n                 1 3 ;\n                 2 3 ;\n                 2 4 ;\n                 3 4 ;\n                 3 5 ;\n                 4 5 ]\n# and the fixed degrees of freedom (supports) are\nfixedDofs     = [2 9 10 ]\n\n# calculations\nnumNodes = size( nodesCMatrix )[1]\nnumElems = size( connecMatrix )[1]\nfreeDofs = zeros(Int8, 2*numNodes-length(fixedDofs))\nindDof  = 1 ;\ncounter = 0 ;\nwhile indDof <= (2*numNodes)\n  if !(indDof in fixedDofs)\n    global counter = counter + 1 ;\n    freeDofs[ counter ] = indDof ;\n    print(indDof)\n  end\n  global indDof = indDof + 1 ;\nend\nprint(freeDofs)\nKG = zeros( 2*numNodes, 2*numNodes ) ;\nFG = zeros( 2*numNodes )\n\n# assembly\nfor elem in 1:numElems\n  print(\" assembling stiffness matrix of element \", elem , \"\\n\")\n  indexFirstNode  = connecMatrix[ elem, 1 ]\n  indexSecondNode = connecMatrix[ elem, 2 ]\n  dofsElem = [2*indexFirstNode-1 2*indexFirstNode 2*indexSecondNode-1 2*indexSecondNode ]\n  KGelem, lengthElem = unitaryStiffnessMatrix( nodesCMatrix[ indexSecondNode, : ], nodesCMatrix[ indexFirstNode, : ] )\n  stiffnessParam = E * A / lengthElem ;\n  for i in 1:4\n    for j in 1:4\n      KG[ dofsElem[i], dofsElem[j] ] = KG[ dofsElem[i], dofsElem[j] ] + stiffnessParam * KGelem[i,j]\n    end\n  end\nend\nFG[4] = -1e4 ;\nKG = KG[ freeDofs, : ]\nKG = KG[ :, freeDofs ]\nFG = FG[ freeDofs ]\n\nu = KG \\ FG\nprint(u)\n\n# ## Problem with interval parameters\n", "meta": {"hexsha": "82bb5e39731180d9c6727665856058c790ada221", "size": 3908, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/literate/applications/FEM_example.jl", "max_stars_repo_name": "jorgepz/IntervalLinearAlgebra.jl", "max_stars_repo_head_hexsha": "ec65e2c5ddefc73a3ff8b94fb172d9178014a89b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/literate/applications/FEM_example.jl", "max_issues_repo_name": "jorgepz/IntervalLinearAlgebra.jl", "max_issues_repo_head_hexsha": "ec65e2c5ddefc73a3ff8b94fb172d9178014a89b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/literate/applications/FEM_example.jl", "max_forks_repo_name": "jorgepz/IntervalLinearAlgebra.jl", "max_forks_repo_head_hexsha": "ec65e2c5ddefc73a3ff8b94fb172d9178014a89b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2975206612, "max_line_length": 347, "alphanum_fraction": 0.6297338792, "num_tokens": 1277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7543017363762146}}
{"text": "# Advent of Code, day 7\n#\n# Find target position that minimizes fuel use for a population\n# of crabs that need to move there, under different assumptions\n# about fuel use per each crab's distance moved (optimization\n# problem, but used brute force).\n#\n# AK, 7 Dec 2021\n\n# Read input data, convert to list of numbers\n#raw_data = readlines(open(\"test_input.txt\"))\nraw_data = readlines(open(\"input.txt\"))\ndata = map(x -> parse(Int64, x), split(raw_data[1], \",\"))\nmaxPos = maximum(data)\n#println(\"Data:\", data)\nprintln(\"Max position =\", maximum(data))\n\n# Find the \"horizontal\" position that minimizes fuel use.  For part 1 (function\n# argument true), use one unit of fuel expended per step. For part 2 (false),\n# fuel use increases by 1 for each step taken.\nfunction crabs(part1::Bool)\n\n    bestPos = 0\n    bestFuel = 0\n\n    # Try each possible position\n    for pos in 1:maxPos\n\n        # Add up fuel use\n        fuel = 0\n        for crab in data\n            dist = abs(crab - pos)\n            if part1\n                fuel += dist\n            else\n                fuel += sumnums(dist)\n            end\n        end\n        #println(\"Position $pos: fuel = $fuel\")\n\n        # Remember if better than last (i.e., less fuel use)\n        if bestPos == 0 || fuel < bestFuel\n            bestPos = pos\n            bestFuel = fuel\n        end\n    end\n\n    # Show the best result found\n    println(\"Best position $bestPos: fuel = $bestFuel\")\n\nend\n\n# Sum up integers up to n\nfunction sumnums(n)\n    nn = 0\n    for i in 1:n\n        nn += i\n    end\n    return nn\nend\n\nprintln(\"--- PART 1 ---\")\ncrabs(true)\n\nprintln(\"--- PART 2 ---\")\ncrabs(false)\n\n", "meta": {"hexsha": "246d455a8014f7136309846323b2d191322bf588", "size": 1630, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day07/day07.jl", "max_stars_repo_name": "andreaskaempf/adventofcode2021", "max_stars_repo_head_hexsha": "6a72c64e8258cf4e69b5d4602ae194cd27492017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day07/day07.jl", "max_issues_repo_name": "andreaskaempf/adventofcode2021", "max_issues_repo_head_hexsha": "6a72c64e8258cf4e69b5d4602ae194cd27492017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day07/day07.jl", "max_forks_repo_name": "andreaskaempf/adventofcode2021", "max_forks_repo_head_hexsha": "6a72c64e8258cf4e69b5d4602ae194cd27492017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9705882353, "max_line_length": 79, "alphanum_fraction": 0.6061349693, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7543017209531631}}
{"text": "# ---\n# title: Fourier transform of Moisan periodic image component\n# id: demo_perfft2\n# cover: assets/perfft2.png\n# author: Peter Kovesi\n# date: 2018-10-26\n# ---\n\n# The function `perfft2()` implements Moisan's \"Periodic plus Smooth Image\n# Decomposition\" which decomposes an image into two components\n#\n#         img = p + s\n#\n# where `s` is the 'smooth' component with mean 0 and `p` is the 'periodic' component\n# which has no sharp discontinuities when one moves cyclically across the image\n# boundaries.\n#\n# This decomposition is very useful when one wants to obtain an FFT of an image\n# with minimal artifacts introduced from the boundary discontinuities. The image\n# `p` gathers most of the image information but avoids periodization artifacts.\n#\n# Reference:\n# L. Moisan, \"Periodic plus Smooth Image Decomposition\", Journal of\n# Mathematical Imaging and Vision, vol 39:2, pp. 161-179, 2011.\n\nusing Images\nusing FFTW\nusing ImagePhaseCongruency\nusing ImageContrastAdjustment\nusing TestImages\n\nimg = Float64.(Gray.(testimage(\"lena\")))\n\nIMG = fft(img)               # 'Standard' fft\n(P, S, p, s) = perfft2(img)  # 'Periodic' fft\n\nmosaic(\n    adjust_histogram(Gray.(p), LinearStretching()),\n    adjust_histogram(s, LinearStretching()),\n    ## Note the vertical and horizontal cross in\n    ## the spectrum induced by the non-periodic edges.\n    adjust_histogram(log.(abs.(fftshift(IMG)) .+ 1), LinearStretching()),\n    ## Note the clean spectrum because p is periodic.\n    adjust_histogram(log.(abs.(fftshift(P)) .+ 1), LinearStretching());\n    nrow=2, rowmajor=true\n)\n# Top 1) left: periodic component 2) right: smooth component\n#\n# Bottom 3) left: spectrum of standard FFT 4) right: spectrum of periodic component\n\n# save cover image #src\nisdir(\"assets\") || mkdir(\"assets\") #src\ncover = Gray.(adjust_histogram(log.(abs.(fftshift(P)) .+ 1), LinearStretching())) #src\nsave(joinpath(\"assets\", \"perfft2.png\"), cover) #src\n", "meta": {"hexsha": "f1797d4cd67fe74b53482f92459d53d2821a883f", "size": 1921, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples/misc/perfft2.jl", "max_stars_repo_name": "peterkovesi/ImagePhaseCongruency", "max_stars_repo_head_hexsha": "119afbfe78f41afd47ea9d022f877b6868dc6b25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/examples/misc/perfft2.jl", "max_issues_repo_name": "peterkovesi/ImagePhaseCongruency", "max_issues_repo_head_hexsha": "119afbfe78f41afd47ea9d022f877b6868dc6b25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/examples/misc/perfft2.jl", "max_forks_repo_name": "peterkovesi/ImagePhaseCongruency", "max_forks_repo_head_hexsha": "119afbfe78f41afd47ea9d022f877b6868dc6b25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9272727273, "max_line_length": 86, "alphanum_fraction": 0.7188964081, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7543017168919313}}
{"text": "\"\"\"\n    rlap(A)\n\nCompute renormalized graph Laplacian for adjacency matrix A.\n\"\"\"\nfunction rlap(A)\n    W = diagm(A * ones(size(A, 1)))\n    L̃ = W \\ (W \\ A)'\n    W̃ = diagm(L̃ * ones(size(L̃, 1)))\n\n    println(\"Laplacian sparsity = $(sparsity(W̃ \\ (W̃ - L̃)))\")\n    return sparse(W̃ \\ (W̃ - L̃))\nend\n\n\n\"\"\"\n    gaussian_similarity(X, σ=1)\n\nCompute similarity using Gaussian kernel. Enforces sparsity by setting the similarity of\ndistant points to zero.\n\"\"\"\nfunction gaussian_similarity(X, σ=1)\n    𝒦 = pairwise(Euclidean(), X, dims=2)\n    n = size(X, 2)\n    for i in 1:n\n        for j in i+1:n\n            𝒦[j, i] = 𝒦[j, i] <= 3σ ? exp(-(𝒦[j,i]/σ)^2) : 0\n            𝒦[i, j] = 𝒦[j, i]\n        end\n    end\n    𝒦[diagind(𝒦)] .= 1\n\n    s = sparsity(𝒦)\n    if s < 0.8\n        println(\"Warning. sparsity = $s\")\n    end\n\n    return 𝒦\nend\n", "meta": {"hexsha": "8742dd734c513407c6be877b36a50693745a7f88", "size": 830, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/helper.jl", "max_stars_repo_name": "alainchau/IES.jl", "max_stars_repo_head_hexsha": "da2bc1121a359b7bd4341492df2084bceee29539", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/helper.jl", "max_issues_repo_name": "alainchau/IES.jl", "max_issues_repo_head_hexsha": "da2bc1121a359b7bd4341492df2084bceee29539", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/helper.jl", "max_forks_repo_name": "alainchau/IES.jl", "max_forks_repo_head_hexsha": "da2bc1121a359b7bd4341492df2084bceee29539", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.75, "max_line_length": 88, "alphanum_fraction": 0.5373493976, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850128595114, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7543013531591011}}
{"text": "\"\"\"\n    Base.rand(pp::PoissonProcess, intervallength::Float64) -> Vector{Float64}\n\nSimulate `pp` over the time interval `[0, intervallength]`, and return a vector of the\narrival times.\n\n##### Complexity\n- Time complexity: `O(E[N(t)]log(E[N(t)]))`, in expectation, where E[N(t)] denotes the\nexpected number of arrivals over the time interval `[0, intervallength]`.\n\"\"\"\nfunction Base.rand(pp::PoissonProcess, intervallength::AbstractFloat)\n    # instantiate a Poisson random variable with distribution F1\n    F1 = Poisson(nexpectedarrivals(pp, intervallength))\n    # sample from F1\n    narrivals = rand(F1)\n    # no arrivals; return an empty Vector\n    if narrivals == 0\n        return []\n    end\n\n    # instantiate a Uniform random variable with distribution F2\n    F2 = Uniform(0, intervallength)\n    # allocate memory\n    arrivaltimes = Vector{Float64}(undef, narrivals)\n    for i in 1:narrivals\n        arrivaltimes[i] = rand(F2)\n    end\n    return sort!(arrivaltimes)\nend\n\n\"\"\"\n    Base.rand(pp::PoissonProcess, intervallength::Integer) -> Vector{Float64}\n\nAllow the user to supply an integer `intervallength`, and work-around method ambiguity\narising from `Random`.\n\"\"\"\nfunction Base.rand(pp::PoissonProcess, intervallength::Integer)\n    return Base.rand(pp, Float64(intervallength))\nend\n", "meta": {"hexsha": "acfc5577fd67475192727e1d88bfd103a87cf0a2", "size": 1291, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PoissonProcesses/simulatepoissonprocesses.jl", "max_stars_repo_name": "LoganDGraham/StochasticProcesses", "max_stars_repo_head_hexsha": "c3f9947d9f93c9d8397664ed3acf93c8bf7da444", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-11-15T19:57:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T22:42:14.000Z", "max_issues_repo_path": "src/PoissonProcesses/simulatepoissonprocesses.jl", "max_issues_repo_name": "LoganDGraham/StochasticProcesses", "max_issues_repo_head_hexsha": "c3f9947d9f93c9d8397664ed3acf93c8bf7da444", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-02T16:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-14T17:56:52.000Z", "max_forks_repo_path": "src/PoissonProcesses/simulatepoissonprocesses.jl", "max_forks_repo_name": "LoganDGraham/StochasticProcesses", "max_forks_repo_head_hexsha": "c3f9947d9f93c9d8397664ed3acf93c8bf7da444", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.275, "max_line_length": 86, "alphanum_fraction": 0.7103020914, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.75430134517273}}
{"text": "#! /usr/bin/julia\n\n# Rosetta Code, Truncatable primes\n\nfunction isltruncprime{T<:Integer}(n::T, base::T=10)\n    isprime(n) || return false\n    p = n\n    f = prevpow(base, p)\n    while 1 < f\n        (d, p) = divrem(p, f)\n        isprime(p) || return false\n        d != 0 || return false\n        f = div(f, base)\n    end\n    return true\nend\n\nfunction isrtruncprime{T<:Integer}(n::T, base::T=10)\n    isprime(n) || return false\n    p = n\n    while base < p\n        p = div(p, base)\n        isprime(p) || return false\n    end\n    return true\nend\n\nhi = 10^6\n\nfor i in reverse(primes(hi))\n    isltruncprime(i) || continue\n    println(\"The largest  left truncatable prime ≤ \", hi, \" is \", i, \".\")\n    break\nend\n\nfor i in reverse(primes(hi))\n    isrtruncprime(i) || continue\n    println(\"The largest right truncatable prime ≤ \", hi, \" is \", i, \".\")\n    break\nend\n\n\n\n        \n        \n", "meta": {"hexsha": "7c325eaed1db4195ff0fd8eb57fba3a12df1ccf2", "size": 875, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/completed/truncatable_primes.jl", "max_stars_repo_name": "MichaeLeroy/rosetta-code", "max_stars_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/completed/truncatable_primes.jl", "max_issues_repo_name": "MichaeLeroy/rosetta-code", "max_issues_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/completed/truncatable_primes.jl", "max_forks_repo_name": "MichaeLeroy/rosetta-code", "max_forks_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0217391304, "max_line_length": 73, "alphanum_fraction": 0.56, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850128595114, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7543013378662882}}
{"text": "using Clustering;\nusing Distances;\n\nfunction getLandmarks(X, p, method=:Random)\n    if(method == :Random)\n        numberOfPoints = size(X,2);\n        landmarks = X[:,randperm(numberOfPoints)[1:p]];\n        return landmarks;\n    end\n\n    if(method == :Kmeans)\n        kmeansResult = kmeans(X,p)\n        return kmeansResult.centers;\n    end\n\n    throw(ArgumentError(\"method can only be :Kmeans or :Random\"));\nend\n\nfunction gaussianKernel(distance, bandwidth)\n    exp(-distance / (2*bandwidth^2));\nend\n\n\nfunction getLinearCoding(X, landmarks, bandwidth, r)\n    distances = pairwise(Distances.Euclidean(), landmarks, X);\n    similarities = map(x -> gaussianKernel(x, bandwidth), distances);\n    ZHat = spzeros(size(similarities,1), size(similarities,2));\n\n    for i in 1:(size(similarities,2))\n        topLandMarksIndices = selectperm(similarities[:,i], 1:r, rev=true);\n        topLandMarksCoefficients = similarities[topLandMarksIndices, i];\n        topLandMarksCoefficients = topLandMarksCoefficients / sum(topLandMarksCoefficients);\n        ZHat[topLandMarksIndices,i] = topLandMarksCoefficients;\n    end\n    return diagm(sum(ZHat,2)[:])^(-1/2) * ZHat;\nend\n\n\nfunction LSCClustering(X, nrOfClusters, nrOfLandmarks, method, nonZeroLandmarkWeights, bandwidth)\n    landmarks = getLandmarks(X, nrOfLandmarks, method)\n    ZHat = getLinearCoding(X, landmarks, bandwidth, nonZeroLandmarkWeights)\n    svdResult = svd(transpose(ZHat))\n    clusteringResult = kmeans(transpose(svdResult[1][:,1:nrOfClusters]),nrOfClusters);\n    return clusteringResult\nend\n", "meta": {"hexsha": "13e7f0218a921589d2a9757f02bc691377d20c55", "size": 1543, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lsc.jl", "max_stars_repo_name": "Twelve33/LandmarkSpectralClustering", "max_stars_repo_head_hexsha": "0e6c639b99b1784232f8750d6a0dac44e7577e14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lsc.jl", "max_issues_repo_name": "Twelve33/LandmarkSpectralClustering", "max_issues_repo_head_hexsha": "0e6c639b99b1784232f8750d6a0dac44e7577e14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lsc.jl", "max_forks_repo_name": "Twelve33/LandmarkSpectralClustering", "max_forks_repo_head_hexsha": "0e6c639b99b1784232f8750d6a0dac44e7577e14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5434782609, "max_line_length": 97, "alphanum_fraction": 0.708360337, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362849986365571, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7543013373312563}}
{"text": "#\n# Simple Pendulum Problem\n#\nusing OrdinaryDiffEq, Plots\n\n#Constants\nconst g = 9.81\nL = 1.0\n\n#Initial Conditions\nu₀ = [0,π/2]\ntspan = (0.0,6.3)\n\n#Define the problem\nfunction simplependulum(du,u,p,t)\n    θ  = u[1]\n    dθ = u[2]\n    du[1] = dθ\n    du[2] = -(g/L)*sin(θ)\nend\n\n#Pass to solvers\nprob = ODEProblem(simplependulum,u₀, tspan)\nsol = solve(prob,Tsit5())\n\n#Plot\nplot(sol,linewidth=2,title =\"Simple Pendulum Problem\", xaxis = \"Time\", yaxis = \"Height\", label = [\"Theta\",\"dTheta\"])\n", "meta": {"hexsha": "0c9f603ef31e42efdb4bb4d262f790ed98b4972f", "size": 485, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "languages/julia/pendulum.jl", "max_stars_repo_name": "sergev/vak-opensource", "max_stars_repo_head_hexsha": "e1912b83dabdbfab2baee5e7a9a40c3077349381", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2016-10-29T19:50:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T21:27:43.000Z", "max_issues_repo_path": "languages/julia/pendulum.jl", "max_issues_repo_name": "sergev/vak-opensource", "max_issues_repo_head_hexsha": "e1912b83dabdbfab2baee5e7a9a40c3077349381", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "languages/julia/pendulum.jl", "max_forks_repo_name": "sergev/vak-opensource", "max_forks_repo_head_hexsha": "e1912b83dabdbfab2baee5e7a9a40c3077349381", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2017-06-19T23:04:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-13T15:00:41.000Z", "avg_line_length": 17.3214285714, "max_line_length": 116, "alphanum_fraction": 0.6432989691, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480347, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7543013365064289}}
{"text": "\"\"\" Compute the Mahalanobis Distance to center (MDC)\n    in a dataset 'data' for a given perturbation of indices 'indpert' \n    compared to a reference of indices 'indref'.\"\"\"\nfunction distance_mahalanobis_center(data, indpert, indref)\n    setPert = Matrix(data[indpert,:])\n    setRef = Matrix(data[indref,:])\n\n    mdCenter = dropdims(mean(setRef, dims = 1), dims = 1)\n    mdCov = cov(setRef)\n\n    pertCenter = dropdims(mean(setPert, dims = 1), dims = 1)\n    \n    MD = mahalanobis(pertCenter, mdCenter, mdCov)\n    \n    return(MD)\nend\n\n\"\"\" Permute labels and compute the Mahalanobis Distance to center (MDC)\n    in a dataset 'data' for a given perturbation of indices 'indpert' \n    compared to a reference of indices 'indref', to create an empirical distribution.\"\"\"\nfunction shuffled_distance_mahalanobis_center(data, indpert, indref; nb_rep = 250)\n    setPert = data[indpert,:]\n    setRef = data[indref,:]  \n    set = Matrix(vcat(setRef, setPert))\n    \n    function iterShufMD()\n        nset = size(set, 1)\n        npert = size(setPert, 1)\n        nref = size(setRef, 1)\n        shuffSet = set[sample(1:nset, nset; replace = false),:]\n        # Take random subsets of corresponding sizes\n        shuffSetPert = shuffSet[1:npert,:]\n        shuffSetRef = shuffSet[(npert+1):(npert+nref),:]\n\n        # Compute Mahalanobis Distance\n        \n        mdCenter = dropdims(mean(shuffSetRef, dims = 1), dims = 1)\n        mdCov = cov(shuffSetRef)\n        \n        pertCenter = dropdims(mean(shuffSetPert, dims = 1), dims = 1)\n    \n        MD = mahalanobis(pertCenter, mdCenter, mdCov)\n        return(MD)\n    end       \n    \n    return(map(x -> iterShufMD(), 1:nb_rep))\nend\n\n\"\"\" Compute the median Mahalanobis Distance (MD)\n    in a dataset 'data' for a given perturbation of indices 'indpert' \n    compared to a reference of indices 'indref'.\"\"\"\nfunction distance_mahalanobis_median(data, indpert, indref)\n    setPert = data[indpert,:]\n    setRef = Matrix(data[indref,:])\n\n    mdCenter = dropdims(mean(setRef, dims = 1), dims = 1)\n    mdCov = cov(setRef)\n    \n    MD = median(map(x -> mahalanobis(x, mdCenter, mdCov), eachrow(setPert)))\n    return(MD)\nend\n\n\"\"\" Permute labels and compute the median Mahalanobis Distance (RMD)\n    in a dataset 'data' for a given perturbation of indices 'indpert' \n    compared to a reference of indices 'indref', to create an empirical distribution.\"\"\"\nfunction shuffled_distance_mahalanobis_median(data, indpert, indref; nb_rep = 250)\n    setPert = data[indpert,:]\n    setRef = data[indref,:]  \n    set = Matrix(vcat(setRef, setPert))\n    \n    function iterShufMD()\n        nset = size(set, 1)\n        npert = size(setPert, 1)\n        nref = size(setRef, 1)\n        shuffSet = set[sample(1:nset, nset; replace = false),:]\n        # Take random subsets of corresponding sizes\n        shuffSetPert = shuffSet[1:npert,:]\n        shuffSetRef = shuffSet[(npert+1):(npert+nref),:]\n\n        # Compute Mahalanobis Distance\n        \n        mdCenter = dropdims(mean(shuffSetRef, dims = 1), dims = 1)\n        mdCov = cov(shuffSetRef)\n\n        MD = median(map(x -> mahalanobis(x, mdCenter, mdCov), eachrow(DataFrame(shuffSetPert))))\n        return(MD)\n    end       \n    \n    return(map(x -> iterShufMD(), 1:nb_rep))\nend\n\n\n\"\"\" Compute the median Robust Mahalanobis Distance (RMD)\n    in a dataset 'data' for a given perturbation of indices 'indpert' \n    compared to a reference of indices 'indref'.\n    See https://e-archivo.uc3m.es/bitstream/handle/10016/24613/ws201710.pdf\n    This function calls R using RCall and a seed is set by default to ensure\n    the results are reproducible. If you don't want that, for instance if you\n    also use RCall and rely on another seed, set 'r_seed' to false.\"\"\"\nfunction distance_robust_mahalanobis_median(data, indpert, indref; r_seed = true)\n    setPert = data[indpert,:]\n    setRef = data[indref,:] \n\n    # Ensure that we have enough points to compute distance\n    if ((size(setPert)[1] < 2*size(data, 2))|(size(setRef)[1] < 2*size(data, 2)))\n        return(missing)\n    end\n    # NB: having less points than twice the number of dimensions leads to singularity\n    \n    # Compute Minimum Covariance Determinant and corresponding Robust Mahalanobis Distance\n    @rput setRef\n    @rput r_seed\n\n    R\"\"\"\n    if (!require(\"robustbase\")) install.packages(\"robustbase\", \n                                repos = \"https://cloud.r-project.org\")\n    library(robustbase)\n\n    if (r_seed){set.seed(777)}\n    mcd <- covMcd(setRef)\n    mcdCenter <- mcd$center\n    mcdCov <- mcd$cov\n    \"\"\"\n    @rget mcdCenter\n    @rget mcdCov\n    \n    RMD = median(map(x -> mahalanobis(x, mcdCenter, mcdCov), eachrow(setPert)))\n    return(RMD)\nend\n\n\"\"\" Permute labels and compute the median Robust Mahalanobis Distance (RMD)\n    in a dataset 'data' for a given perturbation of indices 'indpert' \n    compared to a reference of indices 'indref', to create an empirical distribution.\n    This function calls R using RCall and a seed is set by default to ensure\n    the results are reproducible. If you don't want that, for instance if you\n    also use RCall and rely on another seed, set 'r_seed' to false.\"\"\"\nfunction shuffled_distance_robust_mahalanobis_median(data, indpert, indref; nb_rep = 250, r_seed = true)\n    setPert = data[indpert,:]\n    setRef = data[indref,:]  \n    set = vcat(setRef, setPert)\n\n    nset = size(set, 1)\n    npert = size(setPert, 1)\n    nref = size(setRef, 1)\n    \n    # Ensure that we have enough points to compute distance\n    if ((size(setPert)[1] < 2*size(data, 2))|(size(setRef)[1] < 2*size(data, 2)))\n        return(repeat([missing], nb_rep))\n    end\n    # NB: having less points than twice the number of dimensions leads to singularity\n    \n    function iterShufRMD()\n        shuffSet = set[sample(1:nset, nset; replace = false),:]\n        # Take random subsets of corresponding sizes\n        shuffSetPert = shuffSet[1:npert,:]\n        shuffSetRef = shuffSet[(npert+1):(npert+nref),:]\n\n        # Compute Minimum Covariance Determinant and corresponding Robust Mahalanobis Distance\n        @rput shuffSetRef\n        @rput r_seed\n\n        R\"\"\"\n        if (!require(\"robustbase\")) install.packages(\"robustbase\", \n                                    repos = \"https://cloud.r-project.org\")\n        library(robustbase)\n\n        if (r_seed){set.seed(3895)}\n        mcd <- covMcd(shuffSetRef)\n        mcdCenter <- mcd$center\n        mcdCov <- mcd$cov\n        \"\"\"\n        @rget mcdCenter\n        @rget mcdCov\n\n        RMD = median(map(x -> mahalanobis(x, mcdCenter, mcdCov), eachrow(shuffSetPert)))\n        return(RMD)\n    end       \n    \n    return(map(x -> iterShufRMD(), 1:nb_rep))\nend\n\n\"\"\" Compute the Robust Hellinger Distance (RHD)\n    in a dataset `data` for a given perturbation of indices `indpert` \n    compared to a reference of indices `indref`.\n    This function calls R using RCall and a seed is set by default to ensure\n    the results are reproducible. If you don't want that, for instance if you\n    also use RCall and rely on another seed, set 'r_seed' to false.\"\"\"\nfunction distance_robust_hellinger(data, indpert, indref; r_seed = true)\n    setPert = data[indpert,:]\n    setRef = data[indref,:] \n\n    # Ensure that we have enough points to compute distance\n    if ((size(setPert)[1] < 2*size(data, 2))|(size(setRef)[1] < 2*size(data, 2)))\n        return(missing)\n    end\n    # NB: having less points than twice the number of dimensions leads to singularity\n    \n    # Compute Minimum Covariance Determinant and corresponding Robust Hellinger Distance\n    @rput setRef\n    @rput setPert\n    @rput r_seed\n\n    R\"\"\"\n    if (!require(\"robustbase\")) install.packages(\"robustbase\", \n                                repos = \"https://cloud.r-project.org\")\n    library(robustbase)\n\n    if (r_seed){set.seed(777)}\n    mcd1 <- covMcd(setRef)\n    mcdCenter1 <- mcd1$center\n    mcdCov1 <- mcd1$cov\n    \n    # We set the seed twice to always\n    # find the same estimators given\n    # the same sample\n    if (r_seed){set.seed(777)}\n    mcd2 <- covMcd(setPert)\n    mcdCenter2 <- mcd2$center\n    mcdCov2 <- mcd2$cov\n    \"\"\"\n    @rget mcdCenter1\n    @rget mcdCov1\n    @rget mcdCenter2\n    @rget mcdCov2\n    \n    RHD = hellinger(mcdCenter1, mcdCov1, mcdCenter2, mcdCov2)\n    return(RHD)\nend\n\n\"\"\" Permute labels and compute the Robust Hellinger Distance (RHD)\n    in a dataset `data` for a given perturbation of indices `indpert` \n    compared to a reference of indices `indref`, to create an empirical distribution.\n    This function calls R using RCall and a seed is set by default to ensure\n    the results are reproducible. If you don't want that, for instance if you\n    also use RCall and rely on another seed, set 'r_seed' to false.\"\"\"\nfunction shuffled_distance_robust_hellinger(data, indpert, indref; nb_rep = 250, r_seed = true)\n    setPert = data[indpert,:]\n    setRef = data[indref,:]  \n    set = vcat(setRef, setPert)\n\n    nset = size(set, 1)\n    npert = size(setPert, 1)\n    nref = size(setRef, 1)\n    \n    # Ensure that we have enough points to compute distance\n    if ((size(setPert)[1] < 2*size(data, 2))|(size(setRef)[1] < 2*size(data, 2)))\n        return(repeat([missing], nb_rep))\n    end\n    # NB: having less points than twice the number of dimensions leads to singularity\n    \n    function iterShufRHD()\n        shuffSet = set[sample(1:nset, nset; replace = false),:]\n        # Take random subsets of corresponding sizes\n        shuffSetPert = shuffSet[1:npert,:]\n        shuffSetRef = shuffSet[(npert+1):(npert+nref),:]\n\n        # Compute Minimum Covariance Determinant and corresponding Robust Mahalanobis Distance\n        @rput shuffSetRef\n        @rput shuffSetPert\n        @rput r_seed\n        \n        R\"\"\"\n        if (!require(\"robustbase\")) install.packages(\"robustbase\", \n                                    repos = \"https://cloud.r-project.org\")\n        library(robustbase)\n\n        if (r_seed){set.seed(777)}\n        mcd <- covMcd(shuffSetRef)\n        mcdCenter1 <- mcd$center\n        mcdCov1 <- mcd$cov\n        \n        # We set the seed twice to always\n        # find the same estimators given\n        # the same sample\n        if (r_seed){set.seed(777)}\n        mcd <- covMcd(shuffSetPert)\n        mcdCenter2 <- mcd$center\n        mcdCov2 <- mcd$cov\n        \"\"\"\n        @rget mcdCenter1\n        @rget mcdCov1        \n        @rget mcdCenter2\n        @rget mcdCov2\n        \n\n        RHD = hellinger(mcdCenter1, mcdCov1, mcdCenter2, mcdCov2)\n        return(RHD)\n    end       \n    \n    return(map(x -> iterShufRHD(), 1:nb_rep))\nend\n\n\n\"\"\" Compute the Robust Morphological Perturbation Value (RMPV)\n    for a given Experiment `e`, for all levels of a column `s`,\n    compared to rows matching a given filter `f` or where `s`\n    is equal to `ref`. \n    The RMPV quantifies the significance of changes between all\n    conditions (levels in `s`) and a reference condition (defined\n    by the filter `f`). \n    In brief, the distance of type `dist` between points of each \n    perturbation and points of the reference is computed and its \n    statistical significance is defined using a permutation test\n    in which the perturbation and reference labels are shuffled \n    `nb_rep` times.\n    If `process_pool` is a pool of worker processes, they will\n    be used for parallel computation in the permutation test.\n    This function might call R using RCall and a seed is set by default\n    to ensure the results are reproducible. If you don't want that, for \n    instance if you also use RCall and rely on another seed, set 'r_seed'\n    to false.\n    This returns a DataFrame with three columns:\n    * `Condition`: the levels in `s`\n    * `Distance`: the distance between a condition and the \n    reference \n    * `RMPV`: the RMPV (empirical p-value corrected for multiple\n    testing)\n    \"\"\"\nfunction robust_morphological_perturbation_value end\n\n# If filter provided for reference\nfunction robust_morphological_perturbation_value(e::AbstractExperiment, \n                                                 s::Symbol, \n                                                 f::AbstractFilter; \n                                                 nb_rep::Int64 = 250,\n                                                 dist::Symbol = :RobHellinger,\n                                                 process_pool = nothing,\n                                                 r_seed = true)\n    if dist == :RobHellinger\n        selected_distance = (x...; kw...)->distance_robust_hellinger(x...;\n                                                                     r_seed = r_seed, kw...)\n        shuffled_distance = (x...; kw...)->shuffled_distance_robust_hellinger(x...;\n                                                                     r_seed = r_seed, kw...)\n    elseif dist == :RobMedMahalanobis\n        selected_distance = (x...; kw...)->distance_robust_mahalanobis_median(x...;\n                                                                     r_seed = r_seed, kw...)\n        shuffled_distance = (x...; kw...)->shuffled_distance_robust_mahalanobis_median(x...;\n                                                                     r_seed = r_seed, kw...)\n    elseif dist == :MedMahalanobis\n        selected_distance = distance_mahalanobis_median\n        shuffled_distance = shuffled_distance_mahalanobis_median\n    elseif dist == :CenterMahalanobis\n        selected_distance = distance_mahalanobis_center\n        shuffled_distance = shuffled_distance_mahalanobis_center\n    else \n        throw(DomainError(dist, \"Invalid `dist` argument. \"*\n                                \"Only :RobHellinger \"*\n                                \"and :RobMedMahalanobis \"*\n                                \"and :MedMahalanobis \"*\n                                \"and :CenterMahalanobis \"*\n                                \"are supported\"))\n    end\n\n    # All conditions considered\n    cnd_levels = levels(e.data[e.selected_entries,s])\n\n    # Actual observed distances\n    allRD = map(x -> selected_distance(e.data[:,e.selected_features], \n                                        filter_entries(e, Filter(x, s)), \n                                        filter_entries(e, f)), \n                cnd_levels)\n\n    # Shuffled distances\n    if isnothing(process_pool)\n        allShuffRD = map(x -> shuffled_distance(e.data[:,e.selected_features], \n                                                filter_entries(e, Filter(x, s)), \n                                                filter_entries(e, f), \n                                                nb_rep = nb_rep), \n                         cnd_levels)\n    else\n        sendto(workers(), e=e, \n                          s=s,\n                          f=f,\n                          nb_rep=nb_rep)\n        allShuffRD = pmap(x -> shuffled_distance(e.data[:,e.selected_features], \n                                            filter_entries(e, Filter(x, s)), \n                                            filter_entries(e, f), \n                                            nb_rep = nb_rep), \n                     process_pool,\n                     cnd_levels)\n    end\n\n    # Missing values might need to be handled explicitely\n    @assert !any(ismissing.(allRD))\n\n    # Compute the Robust Morphological Perturbation Value\n    plateRMPV = DataFrame()\n    plateRMPV.RMPV = adjust([mean(obs .< sim) for (obs, sim) \n                in zip(allRD, allShuffRD)], BenjaminiHochberg())\n    plateRMPV.Distance = allRD\n    plateRMPV.Condition = cnd_levels\n\n    return(plateRMPV)\nend\n\n# If reference value provided for reference\nfunction robust_morphological_perturbation_value(e::AbstractExperiment, \n                                                 s::Symbol, \n                                                 ref; \n                                                 nb_rep::Int64 = 250,\n                                                 dist::Symbol = :RobHellinger,\n                                                 process_pool = nothing,\n                                                 r_seed = true)\n    ref_filter = Filter(ref, s)\n    return(robust_morphological_perturbation_value(e, \n                                                   s, \n                                                   ref_filter;\n                                                   nb_rep=nb_rep,\n                                                   dist=dist,\n                                                   process_pool=process_pool,\n                                                   r_seed=r_seed))\nend\n\n", "meta": {"hexsha": "90b4a59f8deb15080cc16428ae752cf5e43b8a78", "size": 16470, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rmpv.jl", "max_stars_repo_name": "menchelab/BioProfiling.jl", "max_stars_repo_head_hexsha": "9debe2493926caf56ec0aba9f6c82b58b4d586d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-05-10T10:08:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T16:30:33.000Z", "max_issues_repo_path": "src/rmpv.jl", "max_issues_repo_name": "menchelab/BioProfiling.jl", "max_issues_repo_head_hexsha": "9debe2493926caf56ec0aba9f6c82b58b4d586d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2021-03-01T09:49:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T15:47:02.000Z", "max_forks_repo_path": "src/rmpv.jl", "max_forks_repo_name": "menchelab/RMP.jl", "max_forks_repo_head_hexsha": "15c0e2d69b684e475149f002aa716008ab4b8526", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-16T09:47:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-16T09:47:41.000Z", "avg_line_length": 39.7826086957, "max_line_length": 104, "alphanum_fraction": 0.5863995143, "num_tokens": 4176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362849986365571, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7543013264078184}}
{"text": "# ------------------------------- #\n#  -- Logistic Regression (L2) -- #\n# ------------------------------- #\n# ->  f(θ)  = -∑logσ(yXθ) + λ|θ|₂²/2\n# -> ∇f(θ)  =  X'(y(w-1)) + λθ\n# -> ∇²f(θ) =  X' Diag(w(1-w)) X + λI\n# NOTE:\n# * w = σ(yXθ)\n# * yᵢ ∈ {±1} so that y² = 1\n# * -σ(-x) == (σ(x)-1)\n# NOTE: https://github.com/JuliaAI/MLJLinearModels.jl/issues/104\n# ---------------------------------------------------------\n\nfunction fgh!(glr::GLR{LogisticLoss,<:L2R}, X, y, scratch)\n    J    = objective(glr) # GLR objective (loss+penalty)\n    n, p = size(X)\n    λ    = getscale(glr.penalty)\n    if glr.fit_intercept\n        (f, g, H, θ) -> begin\n            Xθ = scratch.n\n            apply_X!(Xθ, X, θ)                       # -- Xθ = apply_X(X, θ)\n            # precompute σ(yXθ)\n            w    = scratch.n2\n            w   .= σ.(Xθ .* y)                       # -- w  = σ.(Xθ .* y)\n            g === nothing || begin\n                t  = scratch.n3\n                t .= y .* w .- y                     # -- t = y .* (w .- 1.0)\n                apply_Xt!(g, X, t)                   # -- g = X't\n                g .+= λ .* θ\n                glr.penalize_intercept || (g[end] -= λ * θ[end])\n            end\n            H === nothing || begin\n                # NOTE: we could try to be clever to reduce the allocations for\n                # ΛX but computing the full hessian allocates a lot anyway so\n                # probably not really worth it\n                t    = scratch.n3\n                t   .= w .- w.^2                      # σ(yXθ)(1-σ(yXθ))\n                a    = 1:p\n                ΛX   = t .* X                         # !! big allocs\n                mul!(view(H, a, a), X', ΛX)           # -- H[1:p,1:p] = X'ΛX\n                ΛXt1   = view(scratch.p, a)\n                ΛXt1 .*= 0\n                @inbounds for i in a, j in 1:n\n                    ΛXt1[i] += ΛX[j, i]               # -- (ΛX)'1\n                end\n                @inbounds for i in a\n                    H[i, end] = H[end, i] = ΛXt1[i]   # -- H[:,p+1] = (ΛX)'1\n                end\n                H[end, end] = sum(t)                  # -- 1'Λ1'\n                add_λI!(H, λ, glr.penalize_intercept) # -- H = -X'ΛX + λI\n            end\n            f === nothing || return J(y, Xθ, view_θ(glr, θ))\n        end\n    else\n        # see comments above, same computations just no additional things for\n        # fit_intercept\n        (f, g, H, θ) -> begin\n            Xθ = scratch.n\n            apply_X!(Xθ, X, θ)\n            w    = scratch.n2\n            w   .= σ.(y .* Xθ)\n            g === nothing || begin\n                t  = scratch.n3\n                t .= y .* w .- y\n                apply_Xt!(g, X, t)\n                g .+= λ .* θ\n            end\n            H === nothing || begin\n                t  = scratch.n3\n                t .= w .- w.^2\n                mul!(H, X', t .* X)\n                add_λI!(H, λ)\n            end\n            f === nothing || return J(y, Xθ, θ)\n        end\n    end\nend\n\nfunction Hv!(glr::GLR{LogisticLoss,<:L2R}, X, y, scratch)\n    n, p = size(X)\n    λ    = getscale(glr.penalty)\n    if glr.fit_intercept\n        # H = [X 1]'Λ[X 1] + λ I\n        # rows a 1:p = [X'ΛX + λI | X'Λ1]\n        # row  e end = [1'ΛX      | sum(a)+λ]\n        (Hv, θ, v) -> begin\n            Xθ = scratch.n\n            apply_X!(Xθ, X, θ)                       # -- Xθ = apply_X(X, θ)\n            w   = scratch.n2\n            w  .= σ.(Xθ .* y)                        # -- w  = σ.(Xθ .* y)\n            w .-= w.^2                               # -- w  = w(1-w)\n            # view on the first p rows\n            a    = 1:p\n            Hvₐ  = view(Hv, a)\n            vₐ   = view(v,  a)\n            XtΛ1 = view(scratch.p, 1:p)\n            mul!(XtΛ1, X', w)                        # -- X'Λ1; O(np)\n            vₑ   = v[end]\n            # update for the first p rows -- (X'X + λI)v[1:p] + (X'1)v[end]\n            Xvₐ  = scratch.n\n            mul!(Xvₐ, X, vₐ)\n            Xvₐ .*=  w                               # --  ΛXvₐ\n            mul!(Hvₐ, X', Xvₐ)                       # -- (X'ΛX)vₐ\n            Hvₐ .+= λ .* vₐ .+ XtΛ1 .* vₑ\n            # update for the last row -- (X'1)'v + n v[end]\n            Hv[end] = dot(XtΛ1, vₐ) +\n                        (sum(w) + λ_if_penalize_intercept(glr, λ)) * vₑ\n        end\n    else\n        (Hv, θ, v) -> begin\n            Xθ = scratch.n\n            apply_X!(Xθ, X, θ)\n            w   = scratch.n2\n            w  .= σ.(Xθ .* y)                # -- σ(yXθ)\n            w .-= w.^2\n            Xv  = scratch.n\n            mul!(Xv, X, v)\n            Xv .*= scratch.n2               # -- ΛXv\n            mul!(Hv, X', Xv)                # -- X'ΛXv\n            Hv .+= λ .* v\n        end\n    end\nend\n\n# ----------------------------------- #\n#  -- L1/Elnet Logistic Regression -- #\n# ----------------------------------- #\n# ->  J(θ)  = f(θ) + r(θ)\n# ->  f(θ)  = LL + λ|θ|₂²  // smooth (LL = LogisticLoss)\n# ->  r(θ)  = γ|θ|₁        // non-smooth with prox\n# -> ∇f(θ)  = ∇LL + λθ\n# -> ∇²f(θ) = ∇²LL + λI\n# -> prox_r = soft-thresh\n# ---------------------------------------------------------\n\nfunction smooth_fg!(glr::GLR{LogisticLoss,<:ENR}, X, y, scratch)\n    smooth = get_smooth(glr)\n    (g, θ) -> fgh!(smooth, X, y, scratch)(0.0, g, nothing, θ)\nend\n\n# ---------------------------------- #\n#  -- Multinomial Regression (L2) -- #\n# ---------------------------------- #\n# ->  c is the number of classes, θ has dims p * c\n# ->  P = X * θ\n# -> Zᵢ = ∑ exp(Pᵢ)\n# -> Λ  = Diagonal(-Z)\n# ->  f(θ)   = ∑(log Zᵢ - P[i, y[i]]) +  λ|θ|₂²\n# -> ∇f(θ)   = reshape(X'ΛM, c * p)\n# -> ∇²f(θ)v = via R operator\n# NOTE:\n# * yᵢ ∈ {1, 2, ..., c}\n# ---------------------------------------------------------\n\nfunction fg!(glr::GLR{<:MultinomialLoss,<:L2R}, X, y, scratch)\n    n, p = size(X)\n    c    = getc(glr, y)\n    λ    = getscale(glr.penalty)\n    (f, g, θ) -> begin\n        P  = scratch.nc\n        apply_X!(P, X, θ, c, scratch)                # O(npc) store n * c\n        M  = scratch.nc2\n        M .= exp.(P)                                 # O(npc) store n * c\n        g === nothing || begin\n            ΛM  = scratch.nc3\n            ΛM .= M ./ sum(M, dims=2)                # O(nc)  store n * c\n            Q   = scratch.nc4\n            @inbounds for i = 1:n, j=1:c\n                Q[i, j] = ifelse(y[i] == j, 1.0, 0.0)\n            end\n            ∑ΛM = sum(ΛM, dims=1)\n            ∑Q  = sum(Q, dims=1)\n            R   = ΛM\n            R .-= Q\n            G   = scratch.pc\n            if glr.fit_intercept\n                mul!(view(G, 1:p, :), X', R)\n                @inbounds for k in 1:c\n                    G[end, k] = ∑ΛM[k] - ∑Q[k]\n                end\n            else\n                mul!(G, X', R)\n            end\n            g  .= reshape(G, (p + Int(glr.fit_intercept)) * c)\n            g .+= λ .* θ\n            glr.fit_intercept &&\n                (glr.penalize_intercept || (g[end] -= λ * θ[end]))\n        end\n        f === nothing || begin\n            # we re-use pre-computations here, see also MultinomialLoss\n            # ms = maximum(P, dims=2)\n            # ss = sum(M ./ exp.(ms), dims=2)\n            ms   = maximum(P, dims=2)\n            ems  = scratch.n\n            @inbounds for i in 1:n\n                ems[i] = exp(ms[i])\n            end\n            ΛM  = scratch.nc2  # note that _NC is already linked to P\n            ΛM .= M ./ ems\n            ss  = sum(ΛM, dims=2)\n            t   = 0.0\n            @inbounds for i in eachindex(y)\n                t += log(ss[i]) + ms[i] - P[i, y[i]]\n            end\n            return sum(t) + glr.penalty(view_θ(glr, θ))\n        end\n    end\nend\n\nfunction Hv!(glr::GLR{<:MultinomialLoss,<:L2R}, X, y, scratch)\n    p = size(X, 2)\n    λ = getscale(glr.penalty)\n    c = getc(glr, y)\n    # NOTE:\n    # * ideally P and Q should be recuperated from gradient computations (fghv!)\n    # * assumption that c is small so that storing matrices of size n * c is\n    # not too bad; if c is large and allocations should be minimized, all these\n    # computations can be done per class with views over (c-1)p+1:cp; it will\n    # allocate less but is likely slower; maybe in the future we could have a\n    # keyword indicating which one the user wants to use.\n    (Hv, θ, v) -> begin\n        P  = apply_X(X, θ, c)     # P_ik = <x_i, θ_k> // dims n * c; O(npc)\n        Q  = apply_X(X, v, c)     # Q_ik = <x_i, v_k>    // dims n * c; O(npc)\n        M  = exp.(P)              # M_ik = exp<x_i, w_k> // dims n * c;\n        MQ = M .* Q               #                      // dims n * c; O(nc)\n        ρ  = 1 ./ sum(M, dims=2)  # ρ_i = 1/Z_i = 1/∑_k exp<x_i, w_k>\n        κ  = sum(MQ, dims=2)      # κ_i  = ∑_k exp<x_i, w_k><x_i, v_k>\n        γ  = κ .* ρ.^2            # γ_i  = κ_i / Z_i^2\n        # computation of Hv\n        U      = (ρ .* MQ) .- (γ .* M)                  # // dims n * c; O(nc)\n        Hv_mat = X' * U                                 # // dims n * c; O(npc)\n        if glr.fit_intercept\n            Hv .= reshape(vcat(Hv_mat, sum(U, dims=1)), (p+1)*c)\n        else\n            Hv .= reshape(Hv_mat, p * c)\n        end\n        Hv .+= λ .* v\n        glr.fit_intercept && (glr.penalize_intercept || (Hv[end] -= λ * v[end]))\n    end\nend\n\n# -------------------------------------- #\n#  -- L1/Elnet Multinomial Regression -- #\n# -------------------------------------- #\n# ->  J(θ)  = f(θ) + r(θ)\n# ->  f(θ)  = MN + λ|θ|₂²  // smooth (MN = MultinomialLoss)\n# ->  r(θ)  = γ|θ|₁        // non-smooth with prox\n# -> ∇f(θ)  = ∇MN + λθ\n# -> ∇²f(θ) = ∇²MN + λI\n# -> prox_r = soft-thresh\n# ---------------------------------------------------------\n\nfunction smooth_fg!(glr::GLR{<:MultinomialLoss,<:ENR}, X, y, scratch)\n    smooth = get_smooth(glr)\n    (g, θ) -> fg!(smooth, X, y, scratch)(0.0, g, θ)\nend\n", "meta": {"hexsha": "81c48d92250a857777a6415a68e41e8a3839f678", "size": 9740, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/glr/d_logistic.jl", "max_stars_repo_name": "alan-turing-institute/MLJLinearModels.jl", "max_stars_repo_head_hexsha": "abf145f86768fe24f1804bbe852e6bb6989c60c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2019-09-16T05:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-17T12:03:07.000Z", "max_issues_repo_path": "src/glr/d_logistic.jl", "max_issues_repo_name": "alan-turing-institute/MLJLinearModels.jl", "max_issues_repo_head_hexsha": "abf145f86768fe24f1804bbe852e6bb6989c60c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 84, "max_issues_repo_issues_event_min_datetime": "2019-08-27T13:10:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T14:47:31.000Z", "max_forks_repo_path": "src/glr/d_logistic.jl", "max_forks_repo_name": "alan-turing-institute/MLJLinearModels.jl", "max_forks_repo_head_hexsha": "abf145f86768fe24f1804bbe852e6bb6989c60c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-11-10T04:02:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-31T06:29:54.000Z", "avg_line_length": 37.8988326848, "max_line_length": 80, "alphanum_fraction": 0.3708418891, "num_tokens": 3289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7543010078634006}}
{"text": "# Randomization option slows down processing\n# but improves quality of solution considerably\n# Would be better to do randomization in place\nfunction cddual(X::SparseOrFullMat,\n\t            Y::Vector;\n\t            C::Real = 1.0,\n\t            norm::Integer = 2,\n\t            randomized::Bool = true,\n\t            maxpasses::Integer = 1000,\n\t            eps::Real = 0.1)\n\tconst PG_EPS = 1.0e-12\n\n\t# l: # of samples\n\t# n: # of features\n\tn, l = size(X)\n\talpha = zeros(l)\n\tw = zeros(n)\n\n\t# Set U and D\n\t#  * L1-SVM: U = C, D[i] = 0\n\t#  * L2-SVM: U = Inf, D[i] = 1 / (2C)\n\tU = 0.0\n\tD = Array(Float64, l)\n\tif norm == 1\n\t\tU = C\n\t\tfill!(D, 0.0)\n\telseif norm\t== 2\n\t\tU = Inf\n\t\tfill!(D, 1.0 / (2.0 * C))\n\telse\n\t\tDomainError(\"Only L1-SVM and L2-SVM are supported\")\n\tend\n\n\t# Set Qbar\n\tQbar = Array(Float64, l)\n\tfor i in 1:l\n\t\tQbar[i] = D[i] + vecnorm(X[:, i], 2)^2\n\tend\n\n\t# Loop over examples\n\tconverged = false\n\tpass = 0\n\n\tindices = randomized ? randperm(l) : [1:l]\n\n\twhile !converged\n\t\tpass += 1\n\t\tif pass > maxpasses\n\t\t\tbreak\n\t\tend\n\t\tinv_ins = 0\n\t\tpg_max = -Inf\n\t\tpg_min = Inf\n\n\t\tif randomized\n\t\t\tshuffle!(indices)\n\t\tend\n\n\t\t# Process all observations\n\t\tfor i in indices\n\t\t\tg = Y[i] * inner_prod(w, X[:, i]) - 1.0 + D[i] * alpha[i]\n\n\t\t\tif alpha[i] == 0.0\n\t\t\t\tpg = min(g, 0.0)\n\t\t\t\tif g <= 0.0\n\t\t\t\t\tinv_ins += 1\n\t\t\t\tend\n\t\t\telseif alpha[i] == U\n\t\t\t\tpg = max(g, 0.0)\n\t\t\t\tif g >= 0.0\n\t\t\t\t\tinv_ins += 1\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tpg = g\n\t\t\tend\n\t\t\tpg_max = max(pg_max, pg)\n\t\t\tpg_min = min(pg_min, pg)\n\n\t\t\tif abs(pg) > PG_EPS\n\t\t\t\talphabar = alpha[i]\n\t\t\t\talpha[i] = min(max(alpha[i] - g / Qbar[i], 0.0), U)\n\t\t\t\tadd_vec!(w, X[:, i], e -> (alpha[i] - alphabar) * Y[i] * e)\n\t\t\tend\n\t\tend\n\n\t\tif (pg_max - pg_min <= eps) && (inv_ins == 0)\n\t\t\tconverged = true\n\t\t\tbreak\n\t\tend\n\tend\n\n\treturn SVMFit(w, pass, converged)\nend\n", "meta": {"hexsha": "93f4d22ff281483023cf791f029d1cb44b72cb75", "size": 1784, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cddual.jl", "max_stars_repo_name": "y-yammt/ExperimentalSVM.jl", "max_stars_repo_head_hexsha": "98458d2553e7a8924a0cc0a1b11c79cae88929ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cddual.jl", "max_issues_repo_name": "y-yammt/ExperimentalSVM.jl", "max_issues_repo_head_hexsha": "98458d2553e7a8924a0cc0a1b11c79cae88929ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-01-25T08:58:06.000Z", "max_issues_repo_issues_event_max_datetime": "2015-01-25T10:11:40.000Z", "max_forks_repo_path": "src/cddual.jl", "max_forks_repo_name": "y-yammt/ExperimentalSVM.jl", "max_forks_repo_head_hexsha": "98458d2553e7a8924a0cc0a1b11c79cae88929ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9787234043, "max_line_length": 63, "alphanum_fraction": 0.5448430493, "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7543010056502748}}
{"text": "using AbstractGPs\n\nmutable struct AbstractGPSurrogate{X, Y, GP, GP_P, S} <: AbstractSurrogate\n    x::X\n    y::Y\n    gp::GP \n    gp_posterior::GP_P\n    Σy::S\n end\n\n# constructor\nfunction AbstractGPSurrogate(x, y; gp = GP(Matern52Kernel()), Σy = 0.1)\n    AbstractGPSurrogate(x, y, gp, posterior(gp(x, Σy),y), Σy)\n end\n\n# predictor \nfunction (g::AbstractGPSurrogate)(val)\n    return only(mean(g.gp_posterior([val])))\nend\n\n# for add point\n# copies of x and y need to be made because we get \n#\"Error: cannot resize array with shared data \" if we push! directly to x and y  \nfunction add_point!(g::AbstractGPSurrogate, new_x, new_y)\n    if new_x in g.x\n        println(\"Adding a sample that already exists, cannot build AbstracgGPSurrogate.\")\n        return\n    end\n    x_copy = copy(g.x)\n    push!(x_copy, new_x)\n    y_copy = copy(g.y)\n    push!(y_copy, new_y) \n    updated_posterior = posterior(g.gp(x_copy, g.Σy), y_copy)\n    g.x, g.y, g.gp_posterior = x_copy, y_copy, updated_posterior\n    nothing\nend\n\nfunction std_error_at_point(g::AbstractGPSurrogate, val)\n    return sqrt(only(var(g.gp_posterior([val]))))\nend\n\n# Log marginal posterior predictive probability.\nfunction logpdf_surrogate(g::AbstractGPSurrogate)\n    return logpdf(g.gp_posterior(g.x), g.y)\nend\n", "meta": {"hexsha": "07d63bc94b82a23428fd43e789c158f557c66425", "size": 1260, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/AbstractGP.jl", "max_stars_repo_name": "Chronum94/Surrogates.jl", "max_stars_repo_head_hexsha": "0e0b5ed914cd314ee5a3df5655ea0aba4664b0bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AbstractGP.jl", "max_issues_repo_name": "Chronum94/Surrogates.jl", "max_issues_repo_head_hexsha": "0e0b5ed914cd314ee5a3df5655ea0aba4664b0bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AbstractGP.jl", "max_forks_repo_name": "Chronum94/Surrogates.jl", "max_forks_repo_head_hexsha": "0e0b5ed914cd314ee5a3df5655ea0aba4664b0bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3913043478, "max_line_length": 89, "alphanum_fraction": 0.6976190476, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.754282285981695}}
{"text": "# Surrogate Model with Gaussian Processes\nmodule GPs\n\nusing ..DE\n\nusing LinearAlgebra\n\nexport model_training, predict\n\nfunction kernel_trick(x1::Float64, x2::Float64,\n                      σ_f::Float64, l::Float64)\n    re = σ_f^2 * exp((x1 - x2)^2 / -2)\nend\n\nfunction K(x::Array{Float64}, σ_f::Float64, l::Float64)\n    le = length(x)\n    re = Array{Float64}(undef, le, le)\n    for i=1:1:le\n        for j=1:1:le\n            re[i, j] = kernel_trick(x[i], x[j], σ_f, l)\n        end\n    end\n    re\nend\n\nfunction K(x1::Array{Float64}, x2::Float64, σ_f::Float64, l::Float64)\n    le = length(x1)\n    re = Array{Float64}(undef, le, 1)\n    for i=1:1:le\n        re[i, 1] = kernel_trick(x1[i], x2, σ_f, l)\n    end\n    re\nend\n\nfunction K(x::Float64, σ_f::Float64, l::Float64)\n    kernel_trick(x, x, σ_f, l)\nend\n\nfunction marginal_likelihood(tr_x::Array{Float64}, tr_y::Array{Float64},\n                             σ_f::Float64, l::Float64, σ_n::Float64)\n    A = K(tr_x, σ_f, l) + σ_n^2 * UniformScaling(length(tr_x))\n    n = length(tr_x)\n    -(-1/2 * tr_y' * inv(A) * tr_y - 1/2 * log(det(A)) - n/2 * log(2 * pi))\nend\n\nfunction model_training(tr_x::Array{Float64}, tr_y::Array{Float64})\n    f(pop::DE.Population) = begin\n        for i in 1:size(pop.x, 1)\n            pop.fit[i] = marginal_likelihood(tr_x, tr_y,\n                            pop.x[i, 1], pop.x[i, 2], pop.x[i, 3])\n        end\n    end\n\n    σ_f, l, σ_n= DE_evolution(f, 10, 3, 50)[1]\n    A = K(tr_x, σ_f, l) + σ_n * UniformScaling(length(tr_x))\n    while !isposdef(A)\n        σ_f, l, σ_n= DE_evolution(f, 10, 3, 50)[1]\n        A = K(tr_x, σ_f, l) + σ_n * UniformScaling(length(tr_x))\n    end\n\n    L = cholesky(A)\n    α = L.U\\(L.L\\tr_y)\n    return σ_f, l, L, α\nend\n\nfunction predict(σ_f::Float64, l::Float64, L::Cholesky, α::Array{Float64},\n                 tr_x::Array{Float64}, pr_x::Float64)\n    k_s = K(tr_x, pr_x, σ_f, l)\n    k_ss = K(pr_x, σ_f, l)\n    mean = k_s' ⋅ α\n    v = L\\k_s\n    vari = k_ss - v' ⋅ v\n    return mean, vari\nend\n\nend  # modue SuM\n", "meta": {"hexsha": "162a66740104b818b71d30e41969019211f8bff8", "size": 2007, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GPs.jl", "max_stars_repo_name": "LDNN97/EvolutionaryPlus.jl", "max_stars_repo_head_hexsha": "0192de34fef6ee6ca0d4d5c363f00a1c3efc2001", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-02T14:42:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-02T14:42:36.000Z", "max_issues_repo_path": "src/GPs.jl", "max_issues_repo_name": "LDNN97/EvolutionaryPlus.jl", "max_issues_repo_head_hexsha": "0192de34fef6ee6ca0d4d5c363f00a1c3efc2001", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GPs.jl", "max_forks_repo_name": "LDNN97/EvolutionaryPlus.jl", "max_forks_repo_head_hexsha": "0192de34fef6ee6ca0d4d5c363f00a1c3efc2001", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0649350649, "max_line_length": 75, "alphanum_fraction": 0.5630293971, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7542822795860484}}
{"text": "\nfunction ekepler(m::T,ecc::T) where {T <: Real}\nKEPLER_TOL = sqrt(eps(m))\nif m != zero(T)\n#real*8 e,e0,eps,m,ms,pi2,f0,f1,f2,f3,d1,d2,d3\n# This routine solves Kepler's equation for E as a function of (e,M)\n# using the procedure outlined in Murray & Dermott:\n  pi2=2pi\n  ms=mod(m,pi2)\n  d3 =one(T)\n  de0=ecc*0.85*sign(ms)\n  de1=2*de0\n  de2=3*de0\n  iter = 0\n  ITMAX = 20\n#  while abs(d3) > KEPLER_TOL\n  while true\n    de2 = de1\n    de1 = de0\n    f3=ecc*cos(de0+ms)\n    f2=ecc*sin(de0+ms)\n#    f1=1.0-f3\n#    f0=de0-f2\n#    d1=-f0/f1\n#    d2=-f0/(f1+0.5*d1*f2)\n#    d3=-f0/(f1+d2*0.5*(f2+d2*f3/3.))\n#    de0 += d3\n    de0 = (f2-de1*f3)/(1-f3)\n    iter += 1\n    if iter >= ITMAX || de0 == de1 || de0 == de2\n      break\n    end\n  end\n  if iter >= ITMAX && !(T == BigFloat && minimum([abs(de0-de1),abs(de0-de2)]) < eps(one(T)))\n    println(\"iterations in ekepler: \",iter,\" de0: \",de0,\" de1-de0: \",de1-de0,\" de2-de0: \",de2-de0)\n  end\n  ekep=de0+m\nelse\n  ekep = zero(T)\nend\nreturn ekep::typeof(m)\nend\n\nfunction ekepler2(m::T,ecc::T) where {T <: Real}\nKEPLER_TOL = sqrt(eps(m))\nif m != 0.0\n#real*8 e,e0,eps,m,ms,pi2,f0,f1,f2,f3,d1,d2,d3\n# This routine solves Kepler's equation for E as a function of (e,M)\n# using the procedure outlined in Murray & Dermott:\n  pi2=2.0*pi\n  ms=mod(m,pi2)\n  d3 =one(T)\n  e0=ms+ecc*0.85*sin(ms)/abs(sin(ms))\n  e1=2*e0\n  e2=3*e0\n#  while abs(d3) > KEPLER_TOL\n  ITMAX = 50\n  while true\n    e2 = e1\n    e1 = e0\n    f3=ecc*cos(e0)\n    f2=ecc*sin(e0)\n    f1=1.0-f3\n    f0=e0-ms-f2\n    d1=-f0/f1\n    d2=-f0/(f1+0.5*d1*f2)\n    d3=-f0/(f1+d2*0.5*(f2+d2*f3/3.))\n    e0=e0+d3\n    if iter >= ITMAX || e0 == e1 || e0 == e2\n      break\n    end\n  end\n  if iter >= ITMAX\n    println(\"iterations in ekepler2: \",iter,\" de0: \",de0,\" de1-de0: \",de1-de0,\" de2-de0: \",de2-de0)\n  end \n  ekep=e0+m-ms\nelse\n  ekep = 0.0\nend\nreturn ekep::typeof(m)\nend\n\nfunction kepler(m,ecc)\n@assert(ecc >= 0.0)\n@assert(ecc <= 1.0)\nf=m\nif ecc > 0\n  ekep=ekepler(m,ecc)\n#  println(m-ekep+ecc*sin(ekep))\n#  f=2.0*atan(sqrt((1.0+ecc)/(1.0-ecc))*tan(0.5*ekep))\n#  f=2.0*atan2(sqrt(1.0+ecc)*sin(0.5*ekep),sqrt(1.0-ecc)*cos(0.5*ekep))\n  f=2.0*atan(sqrt(1.0+ecc)*sin(0.5*ekep),sqrt(1.0-ecc)*cos(0.5*ekep))\nend\nreturn f\nend\n", "meta": {"hexsha": "e3dbb323e250aad45dd5beac6069b52c3d3a1d35", "size": 2197, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NbodyGradient/src/kepler.jl", "max_stars_repo_name": "dtamayo/TRAPPIST1_Spitzer", "max_stars_repo_head_hexsha": "be739fe7b070683d1dcedc7e29fa0199914db153", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-01T12:41:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T21:02:57.000Z", "max_issues_repo_path": "src/NbodyGradient/src/kepler.jl", "max_issues_repo_name": "Seek227/TRAPPIST1_Spitzer", "max_issues_repo_head_hexsha": "e476e5951d96a154a99883cde8574380dcec2c39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-06-27T16:34:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T18:29:58.000Z", "max_forks_repo_path": "src/NbodyGradient/src/kepler.jl", "max_forks_repo_name": "Seek227/TRAPPIST1_Spitzer", "max_forks_repo_head_hexsha": "e476e5951d96a154a99883cde8574380dcec2c39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-07-29T01:27:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T09:08:11.000Z", "avg_line_length": 22.8854166667, "max_line_length": 99, "alphanum_fraction": 0.5848884843, "num_tokens": 1048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7542822771130807}}
{"text": "using Random, Statistics\nRandom.seed!(0)\n\ntrueVar, trueStd = 1/12, sqrt(1/12)\n\nfunction estVar(n)\n    sample = rand(n)\n    sum((sample .- 0.5).^2)/n\nend\n\nN = 10^7\nfor n in 5:5:30\n    biasVar = mean([estVar(n) for _ in 1:N]) - trueVar\n    biasStd = mean([sqrt(estVar(n)) for _ in 1:N]) - trueStd\n    println(\"n = \",n, \" Var bias: \", round(biasVar, digits=5),\n           \t    \"\\t Std bias: \", round(biasStd, digits=5))\nend", "meta": {"hexsha": "8cefa5f9009a26f1f78c03685b7d0e28441bf4c4", "size": 420, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5_chapter/stdVarBiasEstimate.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "5_chapter/stdVarBiasEstimate.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "5_chapter/stdVarBiasEstimate.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 24.7058823529, "max_line_length": 62, "alphanum_fraction": 0.5880952381, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083139, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7542822769084294}}
{"text": "using JuMP, Cbc\n\n\"\"\"\n    kantorovich_distance(ν, μ)\n\nCalculate the kantorovich distance between two probability distributions.\n\nThanks to this [hero] (https://stla.github.io/stlapblog/posts/KantorovichWithJulia.html)\n\n```jldoctest\njulia> mu = [1/7, 2/7, 4/7];\njulia> nu = [1/4, 1/4, 1/2];\njulia> kantorovich_distance(mu, nu)\n0.10714285714285714\n```\n\"\"\"\nfunction kantorovich_distance(ν, μ)\n    n = length(ν)\n    m = Model(solver=CbcSolver())\n    @variable(m, p[1:n, 1:n] >= 0)\n    @objective(m, Min, sum(p[i, j] for i in 1:n for j in 1:n if i != j))\n    for k in 1:n\n        @constraint(m, sum(p[k, :]) == μ[k])\n        @constraint(m, sum(p[:, k]) == ν[k])\n    end\n    solve(m)\n    return getobjectivevalue(m)\nend\n", "meta": {"hexsha": "04815e5d9b835e42599b6f6007c8f1b3e8271280", "size": 713, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scenarios/comparison.jl", "max_stars_repo_name": "TAJD/sail_route_old.jl", "max_stars_repo_head_hexsha": "41bb26cd3407bfa5d090464fe18e5a7ba7e0bb56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/scenarios/comparison.jl", "max_issues_repo_name": "TAJD/sail_route_old.jl", "max_issues_repo_head_hexsha": "41bb26cd3407bfa5d090464fe18e5a7ba7e0bb56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scenarios/comparison.jl", "max_forks_repo_name": "TAJD/sail_route_old.jl", "max_forks_repo_head_hexsha": "41bb26cd3407bfa5d090464fe18e5a7ba7e0bb56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5862068966, "max_line_length": 88, "alphanum_fraction": 0.6241234222, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.7542822723717963}}
{"text": "using Plots, LaTeXStrings, Measures; pyplot()\n\ndelta = 0.01\ngrid = 0:delta:1\nf(x,y) = 9/8*(4x+y)*sqrt((1-x)*(1-y))\nz = [f(x,y) for y in grid, x in grid]\n\ndensityIntegral = sum(z)*delta^2\nprintln(\"2-dimensional Riemann sum over density: \", densityIntegral)\n\nprobB = sum([sum([f(x,y)*delta for y in x:delta:1])*delta for x in grid])\nprintln(\"2-dimensional Riemann sum to evaluate probability: \", probB)\n\np1 = surface(grid, grid, z, \n\tc=cgrad([:blue, :red]), la=1, camera=(60,50),\n\tylabel=\"y\", zlabel=L\"f(x,y)\", legend=:none)\np2 = contourf(grid, grid, z, \n\tc=cgrad([:blue, :red]))\np2 = contour!(grid, grid, z, \n\tc=:black, xlims=(0,1), ylims=(0,1), ylabel=\"y\", ratio=:equal)\n\nplot(p1, p2, size=(800, 400), xlabel=\"x\", margin=5mm)", "meta": {"hexsha": "2be1280900967203c895b0ca4e4175ba97081548", "size": 725, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/jointPDF.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "3_chapter/jointPDF.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "3_chapter/jointPDF.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 32.9545454545, "max_line_length": 73, "alphanum_fraction": 0.6427586207, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7542775223310141}}
{"text": "module SineFit\n\nimport LsqFit\nimport FFTW\nimport Statistics\n\nexport estimate_wave_parameters, calculate_wave_shape, sin\n\nstruct WaveFitParams\n    amplitude::Float64\n    frequency::Float64\n    phaseshft::Float64\n    vertoffst::Float64\nend\n\n\"\"\"\n    estimate_wave_parameters(xdata::Vector{T}, ydate::Vector{T};\n        sample_rate=nothing)::WaveFitParams where {T<:Number}\n\nUse Fourier analysis and statistics to find the best monochromatic sine wave parameters for data.\n`xsym` and `ysym` are the column symbols for the x and y columns within DataFrame `df`, respectively.\nReturns a `WaveFitParams` struct with frequency and phase shift as circular frequencies resp. radians.\n\nIf `sample_rate` is not specified, the rate is determined automatically from the `xdata` argument.\n\"\"\"\nfunction estimate_wave_parameters(xdata::Vector{T}, ydata::Vector{T};\n        sample_rate=nothing)::WaveFitParams where {T<:Number}\n    if sample_rate === nothing\n        sample_rate = 1 / Statistics.mean(xdata[2:end] - xdata[1:end-1])\n    end\n\n    offset = (maximum(ydata)+minimum(ydata))/2\n    ampl = Statistics.mean(Statistics.quantile(abs.(ydata .- offset), 99/100))\n    fft = FFTW.rfft(ydata .- offset)\n    fftfreq = FFTW.rfftfreq(length(ydata), sample_rate)\n\n    # Determine dominant frequency and calculate phase shift.\n    maxfreqloc = argmax(abs.(fft))\n    maxfreq = fftfreq[maxfreqloc]\n    shift = mod(atan(imag(fft[maxfreqloc]), real(fft[maxfreqloc])) + pi/2, 2pi)\n    freq = maxfreq * 2pi\n\n    WaveFitParams(ampl, freq, shift, offset)\nend\n\nfunction sin_model(xs, params)\n    params[1] .* Base.sin.(params[2] .* xs .+ params[3]) .+ params[4]\nend\n\n\"\"\"\n    calculate_wave_shape(xdata::Vector{T}, ydate::Vector{T};\n        sample_rate=nothing)::WaveFitParams where {T<:Number}\n\nFit a sine function (`sin_model`, i.e. `a sin(b x + c) + d`) to the given data `xdata`/`ydata`.\n\nThis function first estimates the parameters using normal statistics and fourier analysis using `estimate_wave_parameters()`.\nThen, a least-squares fit (`LsqFit`) is used to refine the parameters -- for example, to adjust the frequency, as a FFT has\na very limited frequency resolution. This helps a lot with accuracy.\n\nIf `sample_rate` is not specified, the rate is determined automatically from the `xdata` argument.\n\"\"\"\nfunction calculate_wave_shape(xdata::Vector{T}, ydata::Vector{T};\n        sample_rate=nothing)::WaveFitParams where {T<:Number}\n\n    estimate = estimate_wave_parameters(xdata, ydata, sample_rate=sample_rate)\n    initial = [estimate.amplitude, estimate.frequency, estimate.phaseshft, estimate.vertoffst]\n\n    fit = LsqFit.curve_fit(sin_model, xdata, ydata, initial)\n    params = fit.param\n\n    if params[1] < 0\n        params[1] *= -1\n        params[3] -= 180\n    end\n    params[3] = mod(params[3], 360)\n    if params[3] > 180\n        params[3] = params[3] - 360\n    elseif params[3] < -180\n        params[3] = params[3] + 360\n    end\n\n    WaveFitParams(params...)\nend\n\n\n\"\"\"\n    sin(x::Vector{T}, wp::WaveFitParams)::Vector{T} where {T<:Number}\n\nReturn sin for `x` with the parameters given in `wp`. Useful in order to plot the fit function, for example.\n\n```\nwp = calculate_wave_shape(xs, ys)\nPlots.plot(xs, ys)\nPlots.plot!(xs, sin.(xs, wp))\n```\n\n\"\"\"\nfunction sin(xs::Vector{T}, wp::WaveFitParams)::Vector{T} where {T<:Number}\n    wp.amplitude .* Base.sin.(wp.frequency .* xs .+ wp.phaseshft) .+ wp.vertoffst\nend\n\nend # module\n", "meta": {"hexsha": "5e827b8ff4ed2c671e6aa7666b11c35dd40ac870", "size": 3411, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SineFit.jl", "max_stars_repo_name": "dermesser/SineFit.jl", "max_stars_repo_head_hexsha": "a162d915bce36279b1e905c99fa8b9a205c568df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SineFit.jl", "max_issues_repo_name": "dermesser/SineFit.jl", "max_issues_repo_head_hexsha": "a162d915bce36279b1e905c99fa8b9a205c568df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-04T20:29:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-25T15:06:46.000Z", "max_forks_repo_path": "src/SineFit.jl", "max_forks_repo_name": "dermesser/SineFit.jl", "max_forks_repo_head_hexsha": "a162d915bce36279b1e905c99fa8b9a205c568df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1165048544, "max_line_length": 125, "alphanum_fraction": 0.7015537965, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299529686201, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7542775219350719}}
{"text": "export  w_legendre,\n        build_w_jacobi,\n        build_w_jacobi01,\n        w_jacobi,\n        w_jacobi01,\n        w_laguerre,\n        w_hermite,\n        build_w_genhermite,\n        build_w_genlaguerre,\n        w_meixner_pollaczek,\n        build_w_meixner_pollaczek,\n\n        w_gaussian,\n        w_uniform01,\n        w_logistic,\n        w_genhermite,\n        build_w_beta,\n        build_w_gamma\n\nfunction w_legendre(t)\n    -1. <= t <= 1. ? 1. : throw(error(\"$t not in support\"))\nend\n\nfunction build_w_jacobi(a,b)\n    @assert a > -1. && b > -1. \"Invalid shape parameters\"\n    # return w(t) = (1-Float64(t))^a*(1+Float64(t))\n    return t->w_jacobi(t,a,b)\nend\nfunction w_jacobi(t,a,b)\n    -1. <=t<= 1. ? ((1-t)^a*(1+t)^b) : throw(error(\"$t not in support\"))\nend\n\nfunction build_w_jacobi01(a,b)\n    @assert a > -1. && b > -1. \"Invalid shape parameters\"\n    # return w(t) = (1-Float64(t))^a*(1+Float64(t))\n    return t->w_jacobi01(t,a,b)\nend\nfunction w_jacobi01(t,a,b)\n    0. <=t<= 1. ? ((1-t)^a*t^b) : throw(error(\"$t not in support\"))\nend\n\nfunction w_hermite(t)\n    exp(-t^2)\nend\n\nfunction build_w_genhermite(mu)\n    @assert mu>-0.5 \"invalid parameter ($mu !> -0.5)\"\n    return t->w_genhermite(t,mu)\nend\nfunction w_genhermite(t,μ::Float64)\n    abs(t)^(2*μ)*exp(-t^2)\nend\nfunction build_w_genlaguerre(a)\n    @assert a>-1 \"Invalid shape parameter\"\n    # return w(t) = Float64(t)^a*exp(-Float64(t))\n    return t->w_genlaguerre(t,a)\nend\nfunction w_genlaguerre(t,a)\n    t>=0. ? Float64(t)^a*exp(-Float64(t)) : throw(error(\"$t not in support\"))\nend\n\nfunction w_laguerre(t)\n    t>=0. ? exp(-t) : throw(error(\"$t not in support\"))\nend\n\nfunction w_meixner_pollaczek(t,lambda,phi)\n    1/(2*pi)*exp((2*phi-pi)*t)*abs(gamma(lambda+im*t))^2\nend\n\nfunction build_w_meixner_pollaczek(lambda,phi)\n    @assert lambda>0 \"lambda has to be positive\"\n    @assert 0<phi<pi \"phi has to be between 0 and pi\"\n    t->w_meixner_pollaczek(t,lambda,phi)\nend\n\n\n##################################################\n# probability density functions\nfunction w_gaussian(t)\n    1/(sqrt(2*pi))*exp(-0.5*t^2)\nend\n\nfunction build_w_beta(α,β)\n    @assert α>-0. && β>-0. \"Invalid shape parameters\"\n    return t->w_beta(t,α,β)\nend\nfunction w_beta(t,α,β)\n    # 0. <=t<= 1. ? (t^(α-1)*(1-t)^(β-1)/beta(α,β)) : (error(\"$t not in support\"))\n    t^(α-1)*(1-t)^(β-1)/beta(α,β)\nend\n\n\n\nfunction build_w_gamma(α)\n    @assert α>0 \"Invalid shape parameter\"\n    return t->w_gamma(t,α)\nend\nfunction w_gamma(t,α)\n    t>=0. ? (1/gamma(α)*Float64(t)^(α-1)*exp(-t)) : (error(\"$t not in support\"))\nend\n\n\nfunction w_uniform01(t)\n    0. <=t<= 1. ? 1. : (error(\"$t not in support\"))\nend\n\n\nfunction w_logistic(t::Float64)\n    0.25*sech(0.5t)^2\nend\n", "meta": {"hexsha": "fd0c36eb06aed9f8e716e8f319a85847a12ef444", "size": 2680, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/densities.jl", "max_stars_repo_name": "TimmFaulwasser/PolyChaos.jl", "max_stars_repo_head_hexsha": "0f0472aa78e91da32278e2ba887efc683566bf92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/densities.jl", "max_issues_repo_name": "TimmFaulwasser/PolyChaos.jl", "max_issues_repo_head_hexsha": "0f0472aa78e91da32278e2ba887efc683566bf92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/densities.jl", "max_forks_repo_name": "TimmFaulwasser/PolyChaos.jl", "max_forks_repo_head_hexsha": "0f0472aa78e91da32278e2ba887efc683566bf92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1441441441, "max_line_length": 82, "alphanum_fraction": 0.6052238806, "num_tokens": 949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229959153748, "lm_q2_score": 0.8152324871074607, "lm_q1q2_score": 0.7542775207472442}}
{"text": "module Laplacian\n\n# Create a Kronecker Delta matrix with the given relationship and dimensions\nfunction δ(fi::Function, fj::Function, n::Integer)\n    r = zeros(n,n)\n    for j in [1:n]\n        for i in [1:n]\n            fi(i) == fj(j) && (r[i,j] = 1.0)\n        end\n    end\n    return r\nend\n\nkronecker = δ\n\n# Create a laplacian matrix with specified grid size and grid divisions\nfunction lap(N::Integer, L::Real)\n\n    Np1sq = (N+1)*(N+1)                 # have (N+1)^2 grid points\n    a = -4.0δ(i->i, j->j, Np1sq)\n    a += δ(i->mod1(i+1, Np1sq), j->j, Np1sq)\n    a += δ(i->mod1(i-1, Np1sq), j->j, Np1sq)\n    a += δ(i->mod1(i+N+1, Np1sq), j->j, Np1sq)\n    a += δ(i->mod1(i-N-1, Np1sq), j->j, Np1sq)\n    return a * (N*N / (L*L))\n\nend\n\nlap(N::Integer) = lap(N,1)\n\n# Split a laplacian matrix into free and boundary parts\nfunction opsplit(A::Array, β::Array{Int,1})\n\n    ndims(A) == 2 || error(\"operator matrix must be 2-d\")\n    length(β) == size(A)[1] || error(\"specify which indices are boundary conditions\")\n    size(A)[1] == size(A)[2] || error(\"operator matrix must be square\")\n\n    B = zeros(size(A))\n    F = zeros(size(A))\n    # Set the boundary condition columns equal to the corresponding columns of A\n    for i in 1:length(β)\n        β[i] == 1 ? B[:,i] = A[:,i] : F[:,i] = A[:,i]\n    end\n    return F, B\n\nend\n\n# β[i] = 1 iff ϕ[i] is a boundary condition\nfunction rhoeff(ρ::Array, Δb::Array, ϕb::Array, β::Array{Int,1})\n    return (ρ + Δb*ϕb) .* (1 .- β)\nend\n\n# Cancel out bound rows to get Δeffective\nfunction deltaeff(Δf, β::Array{Int,1})\n    return Δf .* (1 .- β)\nend\n\nend\n", "meta": {"hexsha": "2367f561dd010cc36f5544a6a027ba6837e318f2", "size": 1578, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "set05/Laplacian.jl", "max_stars_repo_name": "stefco/g6080", "max_stars_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "set05/Laplacian.jl", "max_issues_repo_name": "stefco/g6080", "max_issues_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "set05/Laplacian.jl", "max_forks_repo_name": "stefco/g6080", "max_forks_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7457627119, "max_line_length": 85, "alphanum_fraction": 0.5798479087, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7542775181775844}}
{"text": "# Ported to Julia by Andy Ferris, 2016, and re-released under an MIT license.\n#/**\n# * Copyright (c) Charles Karney (2008-2015) <charles@karney.com> and licensed\n# * under the MIT/X11 License.  For more information, see\n# * http://geographiclib.sourceforge.net/\n# **********************************************************************/\n\n\n\n\n\"\"\"\neatanhe(x, e2) returns e*atanh(e*x) where e = sqrt(e2)\ne2 is a scalar; x can be any shape.\n\"\"\"\nfunction eatanhe(x, e2)\n    e = sqrt(abs(e2))\n    if (e2 >= 0)\n        y = e * atanh(e * x)\n    else\n        y = -e * atan(e * x)\n    end\nend\n\n\n\"\"\"\n%TAUF   tan(phi)\n%\n%   TAUF(taup, e2) returns tangent of phi in terms of taup the tangent of\n%   chi.  e2, the square of the eccentricity, is a scalar; taup can be any\n%   shape.\n\"\"\"\nfunction tauf(taup, e2)\n    numit = 5\n    e2m = 1 - e2     # This possibly disagrees with the C++ code in the prolate case\n    tau = taup / e2m\n    stol = 0.1 * sqrt(eps(Float64)) * max(1.0, abs(taup))\n    g = isfinite(tau)\n    for i = 1 : numit\n        if !g\n            break\n        end\n        tau1 = hypot(1, tau)\n        sig = sinh( eatanhe( tau / tau1, e2 ) )\n        taupa = hypot(1, sig) * tau - sig * tau1\n        dtau = (taup - taupa) * (1 + e2m * tau*tau) / (e2m * tau1 * hypot(1, taupa))\n        tau = tau + dtau\n        g = g & (abs(dtau) >= stol)\n    end\n    return tau\nend\n\n\n\"\"\"\ntaupf(tau, e2) returns tangent of chi in terms of tau the tangent of\nphi.  e2, the square of the eccentricity, is a scalar; tau can be any\nshape.\n\"\"\"\nfunction taupf(tau, e2)\n  tau1 = hypot(1, tau)\n  sig = sinh( eatanhe( tau / tau1, e2 ) )\n  return hypot(1, sig) * tau - sig * tau1\nend\n\n\n\n\n\n\n\n\n\n# Code adapted from MATLAB port of geograhiclib, which was licensed under\n# a permissive MIT-like license and the following copyright notice\n#     Copyright (c) 2016, Charles Karney\n#     All rights reserved.\n\n\"\"\"\nEvaluate polynomial with coefficients p[i] at x\n\"\"\"\nfunction polyval(p, x)\n    y = 1\n    out = p[end]\n    for i = length(p)-1:-1:1\n        y *= x\n        out += p[i] * y\n    end\n    return out\nend\n\n\"\"\"\nLatFix(x) returns x is it is in the range [-90, 90]; otherwise it\nreturns NaN.\n\"\"\"\nfunction LatFix(x::Number)\n    y = x\n    if abs(x) > 90\n        y = NaN\n    end\n    return y\nend\n\n\nfunction AngDiff(x,y)\n    AngNormalize(AngNormalize(y) - AngNormalize(x))\n    #(d, t) = sumx(AngNormalize(x), AngNormalize(-y))\n    #d = - AngNormalize(d)\n    #if d == 180 && t < 0\n    #    d = -180\n    #end\n    #return sumx(d, -t)[1]\nend\n\n\"\"\"\n%AngNormalize:  Reduce angle to range [-180, 180)\n%\n%   x = AngNormalize(x) reduces angles to the range [-180, 180).\n\"\"\"\nfunction AngNormalize(x::Number)\n    x = rem(x, 360)\n    if x >= 180\n        x = x - 360\n    elseif x < -180\n        x = x + 360\n    end\n\n    return x\nend\n\nfunction atan2d(y, x)\n    # In order to minimize round-off errors, this function rearranges the\n    # arguments so that result of atan is in the range [-pi/4, pi/4] before\n    # converting it to degrees and mapping the result to the correct\n    # quadrant.\n    q = 0\n    if (abs(y) > abs(x))\n        tmp = x\n        x = y\n        y = tmp\n        q = 2\n    end\n    if (x < 0)\n        x = -x\n        q = q + 1\n    end\n    # here x >= 0 and x >= abs(y), so angle is in [-pi/4, pi/4]\n    ang = atan(y, x) * 180 / pi\n    # Note that atan2d(-0.0, 1.0) will return -0.  However, we expect that\n    # atan2d will not be called with y = -0.  If need be, include\n    #\n    #   case 0: ang = 0 + ang; break;\n    #\n    # and handle mpfr as in AngRound.\n    if q == 1\n        ang = (y > 0 ? 180 : -180) - ang\n    elseif q == 2\n        ang =  90 - ang\n    elseif q == 3\n        ang = -90 + ang\n    end\n    return ang\nend\n\n\n\n\n\"\"\"\n    immutable TransverseMercator{MaxPow}\n    TransverseMercator(datum)\n    TransverseMercator(ellipsoid)\n    TransverseMercator(a, f, [::Type{Val{MaxPow}} = Val{6}])\n\nCache of ellipsoidal calculations necessary for transverse-Mercator and\npolar-stereographic transformations. Series expansion coefficients up to order\n`MaxPow` (between 4 and 8, default 6) are calculated and stored for fast\ntransverse-Mercator and UTM calculations.\n\"\"\"\nstruct TransverseMercator{MaxPow}\n    a::Float64\n    f::Float64\n    e2::Float64\n    es::Float64\n    e2m::Float64\n    c::Float64\n    n::Float64\n    a1::Float64\n    b1::Float64\n    alp::NTuple{MaxPow, Float64}\n    bet::NTuple{MaxPow, Float64}\nend\n\nTransverseMercator(datum) = TransverseMercator(ellipsoid(datum))\nTransverseMercator(el::Ellipsoid) = TransverseMercator(el.a, 1-el.b/el.a)\nTransverseMercator(a,f) = TransverseMercator(a,f,Val{6}) # Default to sixth-order expansion\nfunction TransverseMercator(a::Float64, f::Float64, ::Type{Val{MaxPow}}) where MaxPow\n    e2 = f * (2 - f)\n    es = (f < 0 ? -1 : 1) * sqrt(abs(e2))\n    e2m = (1 - e2)\n    # c = sqrt( pow(1 + e, 1 + e) * pow(1 - e, 1 - e) ) )\n    # See, for example, Lee (1976), p 100.\n    c = sqrt(e2m) * exp(eatanhe(1.0, e2)) # Maybe revert to C++ version with es\n    n = f / (2 - f)\n\n    (1 - f) * exp(eatanhe(1.0, es))\n\n    if !(isa(MaxPow,Int)) || MaxPow < 4 || MaxPow > 8\n        error(\"MaxPow must be 4, 5, 6, 7 or 8\")\n    end\n\n    # Stack-allocated constants\n    if MaxPow == 4\n        b1coeff = (1, 16, 64, 64)\n\n        alpcoeff = (# alp[1]/n^1, polynomial in n of order 3\n                    164, 225, -480, 360, 720,\n                    # alp[2]/n^2, polynomial in n of order 2\n                    557, -864, 390, 1440,\n                    # alp[3]/n^3, polynomial in n of order 1\n                    -1236, 427, 1680,\n                    # alp[4]/n^4, polynomial in n of order 0\n                    49561, 161280)\n\n        betcoeff = (# bet[1]/n^1, polynomial in n of order 3\n                    -4, 555, -960, 720, 1440,\n                    # bet[2]/n^2, polynomial in n of order 2\n                    -437, 96, 30, 1440,\n                    # bet[3]/n^3, polynomial in n of order 1\n                    -148, 119, 3360,\n                    # bet[4]/n^4, polynomial in n of order 0\n                    4397, 161280)\n    elseif MaxPow == 5\n        b1coeff = (1, 16, 64, 64)\n\n        alpcoeff = (# alp[1]/n^1, polynomial in n of order 4\n                    -635, 328, 450, -960, 720, 1440,\n                    # alp[2]/n^2, polynomial in n of order 3\n                    4496, 3899, -6048, 2730, 10080,\n                    # alp[3]/n^3, polynomial in n of order 2\n                    15061, -19776, 6832, 26880,\n                    # alp[4]/n^4, polynomial in n of order 1\n                    -171840, 49561, 161280,\n                    # alp[5]/n^5, polynomial in n of order 0\n                    34729, 80640)\n\n        betcoeff = (# bet[1]/n^1, polynomial in n of order 4\n                    -3645, -64, 8880, -15360, 11520, 23040,\n                    # bet[2]/n^2, polynomial in n of order 3\n                    4416, -3059, 672, 210, 10080,\n                    # bet[3]/n^3, polynomial in n of order 2\n                    -627, -592, 476, 13440,\n                    # bet[4]/n^4, polynomial in n of order 1\n                    -3520, 4397, 161280,\n                    # bet[5]/n^5, polynomial in n of order 0\n                    4583, 161280)\n    elseif MaxPow == 6\n        b1coeff = (1, 4, 64, 256, 256)\n\n        alpcoeff = (# alp[1]/n^1, polynomial in n of order 5\n                    31564, -66675, 34440, 47250, -100800, 75600, 151200,\n                    # alp[2]/n^2, polynomial in n of order 4\n                    -1983433, 863232, 748608, -1161216, 524160, 1935360,\n                    # alp[3]/n^3, polynomial in n of order 3\n                    670412, 406647, -533952, 184464, 725760,\n                    # alp[4]/n^4, polynomial in n of order 2\n                    6601661, -7732800, 2230245, 7257600,\n                    # alp[5]/n^5, polynomial in n of order 1\n                    -13675556, 3438171, 7983360,\n                    # alp[6]/n^6, polynomial in n of order 0\n                    212378941, 319334400)\n\n        betcoeff = (# bet[1]/n^1, polynomial in n of order 5\n                    384796, -382725, -6720, 932400, -1612800, 1209600, 2419200,\n                    # bet[2]/n^2, polynomial in n of order 4\n                    -1118711, 1695744, -1174656, 258048, 80640, 3870720,\n                    # bet[3]/n^3, polynomial in n of order 3\n                    22276, -16929, -15984, 12852, 362880,\n                    # bet[4]/n^4, polynomial in n of order 2\n                    -830251, -158400, 197865, 7257600,\n                    # bet[5]/n^5, polynomial in n of order 1\n                    -435388, 453717, 15966720,\n                    # bet[6]/n^6, polynomial in n of order 0\n                    20648693, 638668800)\n    elseif MaxPow == 7\n        b1coeff = (1, 4, 64, 256, 256)\n\n        alpcoeff = (# alp[1]/n^1, polynomial in n of order 6\n                    1804025, 2020096, -4267200, 2204160, 3024000, -6451200, 4838400, 9676800,\n                    # alp[2]/n^2, polynomial in n of order 5\n                    4626384, -9917165, 4316160, 3743040, -5806080, 2620800, 9676800,\n                    # alp[3]/n^3, polynomial in n of order 4\n                    -67102379, 26816480, 16265880, -21358080, 7378560, 29030400,\n                    # alp[4]/n^4, polynomial in n of order 3\n                    155912000, 72618271, -85060800, 24532695, 79833600,\n                    # alp[5]/n^5, polynomial in n of order 2\n                    102508609, -109404448, 27505368, 63866880,\n                    # alp[6]/n^6, polynomial in n of order 1\n                    -12282192400, 2760926233, 4151347200,\n                    # alp[7]/n^7, polynomial in n of order 0\n                    1522256789, 1383782400)\n\n        betcoeff = (# bet[1]/n^1, polynomial in n of order 6\n                    -5406467, 6156736, -6123600, -107520, 14918400, -25804800, 19353600,\n                    38707200,\n                    # bet[2]/n^2, polynomial in n of order 5\n                    829456, -5593555, 8478720, -5873280, 1290240, 403200, 19353600,\n                    # bet[3]/n^3, polynomial in n of order 4\n                    9261899, 3564160, -2708640, -2557440, 2056320, 58060800,\n                    # bet[4]/n^4, polynomial in n of order 3\n                    14928352, -9132761, -1742400, 2176515, 79833600,\n                    # bet[5]/n^5, polynomial in n of order 2\n                    -8005831, -1741552, 1814868, 63866880,\n                    # bet[6]/n^6, polynomial in n of order 1\n                    -261810608, 268433009, 8302694400,\n                    # bet[7]/n^7, polynomial in n of order 0\n                    219941297, 5535129600)\n    elseif MaxPow == 8\n        b1coeff = (25, 64, 256, 4096, 16384, 16384)\n\n        alpcoeff = (# alp[1]/n^1, polynomial in n of order 7\n                    -75900428, 37884525, 42422016, -89611200, 46287360, 63504000, -135475200,\n                    101606400, 203212800,\n                    # alp[2]/n^2, polynomial in n of order 6\n                    148003883, 83274912, -178508970, 77690880, 67374720, -104509440,\n                    47174400, 174182400,\n                    # alp[3]/n^3, polynomial in n of order 5\n                    318729724, -738126169, 294981280, 178924680, -234938880, 81164160,\n                    319334400,\n                    # alp[4]/n^4, polynomial in n of order 4\n                    -40176129013, 14967552000, 6971354016, -8165836800, 2355138720,\n                    7664025600,\n                    # alp[5]/n^5, polynomial in n of order 3\n                    10421654396, 3997835751, -4266773472, 1072709352, 2490808320,\n                    # alp[6]/n^6, polynomial in n of order 2\n                    175214326799, -171950693600, 38652967262, 58118860800,\n                    # alp[7]/n^7, polynomial in n of order 1\n                    -67039739596, 13700311101, 12454041600,\n                    # alp[8]/n^8, polynomial in n of order 0\n                    1424729850961, 743921418240)\n\n        betcoeff = (# bet[1]/n^1, polynomial in n of order 7\n                    31777436, -37845269, 43097152, -42865200, -752640, 104428800, -180633600,\n                    135475200, 270950400,\n                    # bet[2]/n^2, polynomial in n of order 6\n                    24749483, 14930208, -100683990, 152616960, -105719040, 23224320, 7257600,\n                    348364800,\n                    # bet[3]/n^3, polynomial in n of order 5\n                    -232468668, 101880889, 39205760, -29795040, -28131840, 22619520,\n                    638668800,\n                    # bet[4]/n^4, polynomial in n of order 4\n                    324154477, 1433121792, -876745056, -167270400, 208945440, 7664025600,\n                    # bet[5]/n^5, polynomial in n of order 3\n                    457888660, -312227409, -67920528, 70779852, 2490808320,\n                    # bet[6]/n^6, polynomial in n of order 2\n                    -19841813847, -3665348512, 3758062126, 116237721600,\n                    # bet[7]/n^7, polynomial in n of order 1\n                    -1989295244, 1979471673, 49816166400,\n                    # bet[8]/n^8, polynomial in n of order 0\n                    191773887257, 3719607091200)\n    end\n\n    m = div(MaxPow, 2)\n    b1 = polyval(b1coeff[1:m+1], n*n) / (b1coeff[m+2] * (1 + n))\n\n    # a1 is the equivalent radius for computing the circumference of ellipse.\n    a1 = b1 * a\n    o = 1\n    d = n\n    _alp = Vector{Float64}(undef, MaxPow)\n    _bet = Vector{Float64}(undef, MaxPow)\n    for l = 1:MaxPow\n        m = MaxPow - l\n        _alp[l] = d * polyval(alpcoeff[o:o+m], n) / alpcoeff[o + m + 1]\n        _bet[l] = d * polyval(betcoeff[o:o+m], n) / betcoeff[o + m + 1]\n        o += m + 2\n        d *= n\n    end\n    # Post condition: o == sizeof(alpcoeff) / sizeof(real) &&\n    # o == sizeof(betcoeff) / sizeof(real)\n    alp = (_alp...,)\n    bet = (_bet...,)\n\n    return TransverseMercator{MaxPow}(a,f,e2,es,e2m,c,n,a1,b1,alp,bet)\nend\n\nconst wgs84_tm = TransverseMercator(wgs84_ellipsoid)\nconst airy1830_tm = TransverseMercator(airy1830)\nconst clarke1866_tm = TransverseMercator(clarke1866)\nconst grs80_tm = TransverseMercator(grs80)\n\nTransverseMercator(::WGS84) = wgs84_tm\nTransverseMercator(::OSGB36) = airy1830_tm\nTransverseMercator(::NAD27) = clarke1866_tm\nTransverseMercator(::GDA94) = grs80_tm\n\n# // Engsager and Poder (2007) use trigonometric series to convert between phi\n# // and phip.  Here are the series...\n# //\n# // Conversion from phi to phip:\n# //\n# //     phip = phi + sum(c[j] * sin(2*j*phi), j, 1, 6)\n# //\n# //       c[1] = - 2 * n\n# //              + 2/3 * n^2\n# //              + 4/3 * n^3\n# //              - 82/45 * n^4\n# //              + 32/45 * n^5\n# //              + 4642/4725 * n^6;\n# //       c[2] =   5/3 * n^2\n# //              - 16/15 * n^3\n# //              - 13/9 * n^4\n# //              + 904/315 * n^5\n# //              - 1522/945 * n^6;\n# //       c[3] = - 26/15 * n^3\n# //              + 34/21 * n^4\n# //              + 8/5 * n^5\n# //              - 12686/2835 * n^6;\n# //       c[4] =   1237/630 * n^4\n# //              - 12/5 * n^5\n# //              - 24832/14175 * n^6;\n# //       c[5] = - 734/315 * n^5\n# //              + 109598/31185 * n^6;\n# //       c[6] =   444337/155925 * n^6;\n# //\n# // Conversion from phip to phi:\n# //\n# //     phi = phip + sum(d[j] * sin(2*j*phip), j, 1, 6)\n# //\n# //       d[1] =   2 * n\n# //              - 2/3 * n^2\n# //              - 2 * n^3\n# //              + 116/45 * n^4\n# //              + 26/45 * n^5\n# //              - 2854/675 * n^6;\n# //       d[2] =   7/3 * n^2\n# //              - 8/5 * n^3\n# //              - 227/45 * n^4\n# //              + 2704/315 * n^5\n# //              + 2323/945 * n^6;\n# //       d[3] =   56/15 * n^3\n# //              - 136/35 * n^4\n# //              - 1262/105 * n^5\n# //              + 73814/2835 * n^6;\n# //       d[4] =   4279/630 * n^4\n# //              - 332/35 * n^5\n# //              - 399572/14175 * n^6;\n# //       d[5] =   4174/315 * n^5\n# //              - 144838/6237 * n^6;\n# //       d[6] =   601676/22275 * n^6;\n# //\n# // In order to maintain sufficient relative accuracy close to the pole use\n# //\n# //     S = sum(c[i]*sin(2*i*phi),i,1,6)\n# //     taup = (tau + tan(S)) / (1 - tau * tan(S))\n#\n# // In Math::taupf and Math::tauf we evaluate the forward transform explicitly\n# // and solve the reverse one by Newton's method.\n# //\n# // There are adapted from TransverseMercatorExact (taup and taupinv).  tau =\n# // tan(phi), taup = sinh(psi)\n\n\"\"\"\n    (x, y, γ, k) = transverse_mercator_forward(lon0, lat, lon, k0, tm::TransverseMercator)\n\nPerform transverse-Mercator projection of `lat` and `lon` with respect to reference\nmeridian `lat0` and horizontal scaling `k0` (`= 0.9996` for UTM) using a\nseries expansion approach (see `TransverseMercator`). `γ` and `k` are the local\nconvergence and scaling factors, respectively.\n\"\"\"\nfunction transverse_mercator_forward(lon0, lat, lon, k0, tm::TransverseMercator{MaxPow}) where MaxPow\n    lat = LatFix(lat)\n    lon = AngDiff(lon0, lon)\n    if abs(lon) > 50\n        error(\"Relative longitude is too large for transverse-Mercator expansion, and must be less than 50° (received $(lon)°). Possibly used wrong UTM zone.\")\n    end\n    # Explicitly enforce the parity\n    latsign = lat < 0 ? -1 : 1\n    lonsign = lon < 0 ? -1 : 1\n    lon *= lonsign\n    lat *= latsign\n    backside = lon > 90\n    if backside\n        if (lat == 0)\n            latsign = -1\n        end\n        lon = 180 - lon\n    end\n\n    sphi = sind(lat)\n    cphi = cosd(lat)\n    slam = sind(lon)\n    clam = cosd(lon)\n\n    # phi = latitude\n    # phi' = conformal latitude\n    # psi = isometric latitude\n    # tau = tan(phi)\n    # tau' = tan(phi')\n    # [xi', eta'] = Gauss-Schreiber TM coordinates\n    # [xi, eta] = Gauss-Krueger TM coordinates\n    #\n    # We use\n    #   tan(phi') = sinh(psi)\n    #   sin(phi') = tanh(psi)\n    #   cos(phi') = sech(psi)\n    #   denom^2    = 1-cos(phi')^2*sin(lam)^2 = 1-sech(psi)^2*sin(lam)^2\n    #   sin(xip)   = sin(phi')/denom          = tanh(psi)/denom\n    #   cos(xip)   = cos(phi')*cos(lam)/denom = sech(psi)*cos(lam)/denom\n    #   cosh(etap) = 1/denom                  = 1/denom\n    #   sinh(etap) = cos(phi')*sin(lam)/denom = sech(psi)*sin(lam)/denom\n    if (lat != 90)\n        tau = sphi / cphi\n        taup = taupf(tau, tm.e2) # TODO maybe switch to the C++ version of taupf using tm.es?\n        xip = atan(taup, clam)\n        # Used to be\n        #   etap = Math::atanh(sin(lam) / cosh(psi));\n        etap = asinh(slam / hypot(taup, clam))\n        # convergence and scale for Gauss-Schreiber TM (xip, etap) -- gamma0 =\n        # atan(tan(xip) * tanh(etap)) = atan(tan(lam) * sin(phi'));\n        # sin(phi') = tau'/sqrt(1 + tau'^2)\n        # Krueger p 22 (44)\n        gamma = atan2d(slam * taup, clam * hypot(1.0, taup))\n        # k0 = sqrt(1 - _e2 * sin(phi)^2) * (cos(phi') / cos(phi)) * cosh(etap)\n        # Note 1/cos(phi) = cosh(psip);\n        # and cos(phi') * cosh(etap) = 1/hypot(sinh(psi), cos(lam))\n        #\n        # This form has cancelling errors.  This property is lost if cosh(psip)\n        # is replaced by 1/cos(phi), even though it's using \"primary\" data (phi\n        # instead of psip).\n        k = sqrt(tm.e2m + tm.e2 * cphi*cphi) * hypot(1.0, tau) / hypot(taup, clam)\n    else\n        xip = pi/2\n        etap = 0.0\n        gamma = lon\n        k = tm.c\n    end\n\n    # {xi',eta'} is {northing,easting} for Gauss-Schreiber transverse Mercator\n    # (for eta' = 0, xi' = bet). {xi,eta} is {northing,easting} for transverse\n    # Mercator with constant scale on the central meridian (for eta = 0, xip =\n    # rectifying latitude).  Define\n    #\n    #   zeta = xi + i*eta\n    #   zeta' = xi' + i*eta'\n    #\n    # The conversion from conformal to rectifying latitude can be expressed as\n    # a series in _n:\n    #\n    #   zeta = zeta' + sum(h[j-1]' * sin(2 * j * zeta'), j = 1..maxpow_)\n    #\n    # where h[j]' = O(_n^j).  The reversion of this series gives\n    #\n    #   zeta' = zeta - sum(h[j-1] * sin(2 * j * zeta), j = 1..maxpow_)\n    #\n    # which is used in Reverse.\n    #\n    # Evaluate sums via Clenshaw method.  See\n    #    http:#mathworld.wolfram.com/ClenshawRecurrenceFormula.html\n    #\n    # Let\n    #\n    #    S = sum(c[k] * F[k](x), k = 0..N)\n    #    F[n+1](x) = alpha(n,x) * F[n](x) + beta(n,x) * F[n-1](x)\n    #\n    # Evaluate S with\n    #\n    #    y[N+2] = y[N+1] = 0\n    #    y[k] = alpha(k,x) * y[k+1] + beta(k+1,x) * y[k+2] + c[k]\n    #    S = c[0] * F[0](x) + y[1] * F[1](x) + beta(1,x) * F[0](x) * y[2]\n    #\n    # Here we have\n    #\n    #    x = 2 * zeta'\n    #    F[n](x) = sin(n * x)\n    #    a(n, x) = 2 * cos(x)\n    #    b(n, x) = -1\n    #    [ sin(A+B) - 2*cos(B)*sin(A) + sin(A-B) = 0, A = n*x, B = x ]\n    #    N = maxpow_\n    #    c[k] = _alp[k]\n    #    S = y[1] * sin(x)\n    #\n    # For the derivative we have\n    #\n    #    x = 2 * zeta'\n    #    F[n](x) = cos(n * x)\n    #    a(n, x) = 2 * cos(x)\n    #    b(n, x) = -1\n    #    [ cos(A+B) - 2*cos(B)*cos(A) + cos(A-B) = 0, A = n*x, B = x ]\n    #    c[0] = 1; c[k] = 2*k*_alp[k]\n    #    S = (c[0] - y[2]) + y[1] * cos(x)\n    c0 = cos(2 * xip)\n    ch0 = cosh(2 * etap)\n    s0 = sin(2 * xip)\n    sh0 = sinh(2 * etap)\n    ar = 2 * c0 * ch0\n    ai = -2 * s0 * sh0 # 2 * cos(2*zeta')\n\n    n = MaxPow\n\n    xi0 = (isodd(n) ? tm.alp[n] : 0.0)\n    eta0 = 0.0\n    xi1 = 0.0\n    eta1 = 0.0\n\n    # Accumulators for dzeta/dzeta'\n    if isodd(n)\n        yr0 = 2 * MaxPow * tm.alp[n]\n        n = n - 1\n    else\n        yr0 = 0.0\n    end\n    yi0 = 0.0\n    yr1 = 0.0\n    yi1 = 0.0\n    while n > 0\n        xi1  = ar * xi0 - ai * eta0 - xi1 + tm.alp[n]\n        eta1 = ai * xi0 + ar * eta0 - eta1\n        yr1 = ar * yr0 - ai * yi0 - yr1 + 2 * n * tm.alp[n]\n        yi1 = ai * yr0 + ar * yi0 - yi1\n\n        n = n - 1\n\n        xi0  = ar * xi1 - ai * eta1 - xi0 + tm.alp[n]\n        eta0 = ai * xi1 + ar * eta1 - eta0\n        yr0 = ar * yr1 - ai * yi1 - yr0 + 2 * n * tm.alp[n]\n        yi0 = ai * yr1 + ar * yi1 - yi0\n\n        n = n - 1\n    end\n\n    ar *= 0.5\n    ai *= 0.5      # cos(2*zeta')\n    yr1 = 1 - yr1 + ar * yr0 - ai * yi0\n    yi1 =   - yi1 + ai * yr0 + ar * yi0\n    ar = s0 * ch0\n    ai = c0 * sh0  # sin(2*zeta')\n\n    xi  = xip  + ar * xi0 - ai * eta0\n    eta = etap + ai * xi0 + ar * eta0\n\n    # Fold in change in convergence and scale for Gauss-Schreiber TM to\n    # Gauss-Krueger TM.\n\n    gamma -= atan2d(yi1, yr1)\n    k *= tm.b1 * hypot(yr1, yi1)\n    y = tm.a1 * k0 * (backside ? pi - xi : xi) * latsign\n    x = tm.a1 * k0 * eta * lonsign\n    if backside\n        gamma = 180 - gamma\n    end\n    gamma *= latsign * lonsign\n    gamma = AngNormalize(gamma)\n    k *= k0\n\n    return (x, y, gamma, k)\nend\n\n\"\"\"\n    (lat, lon, γ, k) = transverse_mercator_reverse(lon0, x, y, k0, tm::TransverseMercator)\n\nInvert transverse-Mercator projection of `x` and `y` with respect to reference\nmeridian `lat0` and horizontal scaling `k0` (`= 0.9996` for UTM) using a\nseries expansion approach (see `TransverseMercator`). `γ` and `k` are the local\nconvergence and scaling factors, respectively.\n\"\"\"\nfunction transverse_mercator_reverse(lon0, x, y, k0, tm::TransverseMercator{MaxPow}) where MaxPow\n    # This undoes the steps in transverse_mercator_forward.  The wrinkles are: (1) Use of the\n    # reverted series to express zeta' in terms of zeta. (2) Newton's method\n    # to solve for phi in terms of tan(phi).\n    xi = y / (tm.a1 * k0)\n    eta = x / (tm.a1 * k0)\n\n    # Explicitly enforce the parity\n    xisign = xi < 0 ? -1 : 1\n    etasign = eta < 0 ? -1 : 1\n    xi *= xisign\n    eta *= etasign\n    backside = xi > pi/2\n    if backside\n        xi = pi - xi\n    end\n\n    c0 = cos(2 * xi)\n    ch0 = cosh(2 * eta)\n    s0 = sin(2 * xi)\n    sh0 = sinh(2 * eta)\n\n    ar = 2 * c0 * ch0\n    ai = -2 * s0 * sh0 # 2 * cos(2*zeta)\n    n = MaxPow\n\n    # Accumulators for zeta'\n    xip0 = (isodd(n) ? -tm.bet[n] : 0.0)\n    etap0 = 0.0\n    xip1 = 0.0\n    etap1 = 0.0\n\n    # Accumulators for dzeta'/dzeta\n    if isodd(n)\n        yr0 =  2 * MaxPow * tm.bet[n]\n        n -= 1\n    else\n        yr0 = 0.0\n    end\n    yi0 = 0.0\n    yr1 = 0.0\n    yi1 = 0.0\n\n    while (n > 0)\n        xip1  = ar * xip0 - ai * etap0 - xip1 - tm.bet[n]\n        etap1 = ai * xip0 + ar * etap0 - etap1\n        yr1 = ar * yr0 - ai * yi0 - yr1 - 2 * n * tm.bet[n]\n        yi1 = ai * yr0 + ar * yi0 - yi1\n\n        n = n - 1\n\n        xip0  = ar * xip1 - ai * etap1 - xip0 - tm.bet[n]\n        etap0 = ai * xip1 + ar * etap1 - etap0\n        yr0 = ar * yr1 - ai * yi1 - yr0 - 2 * n * tm.bet[n]\n        yi0 = ai * yr1 + ar * yi1 - yi0\n\n        n = n - 1\n    end\n\n    ar *= 0.5\n    ai *= 0.5  # cos(2*zeta')\n    yr1 = 1 - yr1 + ar * yr0 - ai * yi0\n    yi1 =   - yi1 + ai * yr0 + ar * yi0\n    ar = s0 * ch0\n    ai = c0 * sh0 # sin(2*zeta)\n\n    xip  = xi  + ar * xip0 - ai * etap0\n    etap = eta + ai * xip0 + ar * etap0\n\n    # Convergence and scale for Gauss-Schreiber TM to Gauss-Krueger TM.\n    gamma = atand(yi1, yr1)\n    k = tm.b1 / hypot(yr1, yi1)\n    # JHS 154 has\n    #\n    #   phi' = asin(sin(xi') / cosh(eta')) (Krueger p 17 (25))\n    #   lam = asin(tanh(eta') / cos(phi')\n    #   psi = asinh(tan(phi'))\n\n    s = sinh(etap)\n    c = max(0.0, cos(xip))  # cos(pi/2) might be negative\n    r = hypot(s, c)\n\n    if (r != 0)\n        lon = atand(s, c)# Krueger p 17 (25)\n\n        # Use Newton's method to solve for tau\n        sxip = sin(xip)\n        tau = tauf(sxip/r, tm.e2) # TODO maybe change to C++ es version\n        gamma += atand(sxip * tanh(etap), c) # Krueger p 19 (31)\n        lat = atand(tau)\n        # Note cos(phi') * cosh(eta') = r\n        k *= sqrt(tm.e2m + tm.e2 / (1 + tau*tau)) * hypot(1.0, tau) * r\n    else\n        lat = 90.0\n        lon = 0.0\n        k *= tm.c\n    end\n\n    lat *= xisign\n    if backside\n        lon = 180 - lon\n    end\n    lon *= etasign\n    if abs(lon) > 50\n        error(\"Relative longitude is too large for transverse-Mercator expansion, and must be less than 50° (calculated $(lon)°). Possibly used wrong UTM zone.\")\n    end\n    lon = AngNormalize(lon + lon0)\n    if backside\n        gamma = 180 - gamma\n    end\n    gamma *= xisign * etasign\n    gamma = AngNormalize(gamma)\n    k *= k0\n\n    return (lat, lon, gamma, k)\nend\n", "meta": {"hexsha": "0fee6ae1e9f8d46139f5e6b7c7373c1cebfe98d1", "size": 26097, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transverse_mercator.jl", "max_stars_repo_name": "sillygrinch/Geodesy.jl", "max_stars_repo_head_hexsha": "79401dc55f3b86262ab1c33a5b5c52d52190b768", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/transverse_mercator.jl", "max_issues_repo_name": "sillygrinch/Geodesy.jl", "max_issues_repo_head_hexsha": "79401dc55f3b86262ab1c33a5b5c52d52190b768", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/transverse_mercator.jl", "max_forks_repo_name": "sillygrinch/Geodesy.jl", "max_forks_repo_head_hexsha": "79401dc55f3b86262ab1c33a5b5c52d52190b768", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4576923077, "max_line_length": 161, "alphanum_fraction": 0.5080277427, "num_tokens": 9448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.7542775178786438}}
{"text": "\"\"\"\nx = nnls(A, b; ...)\n\nSolves non-negative least-squares problem by the active set method\nof Lawson & Hanson (1974).\n\nOptional arguments:\n    tol: tolerance for nonnegativity constraints\n    max_iter: maximum number of iterations (counts inner loop iterations)\n\nReferences:\n    Lawson, C.L. and R.J. Hanson, Solving Least-Squares Problems,\n    Prentice-Hall, Chapter 23, p. 161, 1974.\n\"\"\"\nfunction nnls(A::Matrix{Float64},\n              b::Vector{Float64};\n              tol::Float64=1e-8,\n              max_iter=30*size(A,2),\n              kwargs...)\n\n    # dimensions, initialize solution\n    m,n = size(A)\n    x = zeros(n)\n\n    # P is a bool array storing positive elements of x\n    # i.e., x[P] > 0 and x[~P] == 0\n    P = zeros(Bool,n)\n\n    # We have reached an optimum when either:\n    #   (a) all elements of x are positive (no nonneg constraints activated)\n    #   (b) ∂f/∂x = A' * (b - A*x) > 0 for all nonpositive elements of x\n    w = A' * (b - A*x)\n    iter = 0\n    while sum(P)<n && any(w[~P].>tol) && iter < max_iter\n\n        # find i that maximizes w, restricting i to indices not in P\n        # Note: the while loop condition guarantees at least one w[~P]>0\n        i = indmax(w .* ~P) \n\n        # Move i to P\n        P[i] = true\n\n        # Solve least-squares problem, with zeros for columns/elements not in P\n        Ap = zeros(m,n)\n        Ap[:,P] = A[:,P]\n        s = pinv(Ap)*b\n        s[~P] = 0.0 # zero out elements not in P\n\n        # Inner loop: deal with negative elements of s\n        while any(s[P].<=tol)\n            iter += 1\n\n            # find indices in P where s is negative\n            ind = (s.<=tol) & P\n\n            # calculate step size, α, to prevent any xᵢ from going negative\n            α = minimum(x[ind] ./ (x[ind] - s[ind]))\n\n            # update solution (pushes some xᵢ to zero)\n            x += α*(s-x)\n\n            # Remove all i in P where x[i] == 0\n            for i = 1:n\n                if P[i] && abs(x[i]) < tol\n                    # remove i from P\n                    P[i] = false \n                    # zero out column i of Ap\n                    Ap[:,i] *= 0.0\n                end\n            end\n\n            # Solve least-squares problem again, zeroing nonpositive columns\n            s = pinv(Ap)*b\n            s[~P] = 0.0 # zero out elements not in P\n        end\n\n        # update solution\n        x = deepcopy(s)\n        w = A' * (b - A*x)\n    end\n    return x\nend\n\nfunction nnls(A::Matrix{Float64},\n              B::Matrix{Float64};\n              use_parallel = true,\n              kwargs...)\n\n    m,n = size(A)\n    k = size(B,2)\n\n    if use_parallel && nprocs()>1\n        X = SharedArray(Float64,n,k)\n        @sync @parallel for i = 1:k\n            X[:,i] = nnls(A, B[:,i]; kwargs...)\n        end\n        X = convert(Array,X)\n    else\n        X = Array(Float64,n,k)\n        for i = 1:k\n            X[:,i] = nnls(A, B[:,i]; kwargs...)\n        end\n    end\n\n    return X\nend\n", "meta": {"hexsha": "6d40feea9469a910700be7a4496393ac208a7dbe", "size": 2940, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nnls.jl", "max_stars_repo_name": "JuliaPackageMirrors/NonNegLeastSquares.jl", "max_stars_repo_head_hexsha": "788b44005e50c79c68c3aa75ef5cb7a26387eb1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nnls.jl", "max_issues_repo_name": "JuliaPackageMirrors/NonNegLeastSquares.jl", "max_issues_repo_head_hexsha": "788b44005e50c79c68c3aa75ef5cb7a26387eb1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nnls.jl", "max_forks_repo_name": "JuliaPackageMirrors/NonNegLeastSquares.jl", "max_forks_repo_head_hexsha": "788b44005e50c79c68c3aa75ef5cb7a26387eb1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.476635514, "max_line_length": 79, "alphanum_fraction": 0.5037414966, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7542775173856995}}
{"text": "# Algebra generator for CliffordAlgebras.jl\n\nimport Base.show\nimport Combinatorics.levicivita\nimport PrettyTables.pretty_table\n\n\n\"\"\"\n    basevectorproduct(Npos::Integer, Nneg::Integer, Nzero::Integer, base::Tuple, kl::Integer, kr::Integer)\n\nFinds the product of the kl-th base vector with the kr-th base vector. Returns a base vector index and a scale factor.\n\"\"\"\nfunction basevectorproduct(Npos::Integer, Nneg::Integer, base::Tuple, kl::Integer, kr::Integer)\n    K = length(base)\n    @assert kr <= K && kl <= K\n    selector_left = base[kl]\n    selector_right = base[kr]\n    selector_prod = collect((selector_left..., selector_right...))\n    permutation = sortperm(selector_prod)\n    coeff = levicivita(permutation)\n    v = []\n    for b in unique(selector_prod[permutation])\n        c = count(isequal(b), selector_prod)\n        @assert c in (1, 2)\n        if c == 1\n            push!(v, b)\n        else\n            coeff *= (b <= Npos) ? 1 : (b <= Npos + Nneg) ? -1 : 0\n        end\n    end\n    v = Tuple(v)\n    vl = length(v)\n    bi = findfirst(b -> length(b) == vl && length(intersect(b, v)) == vl, base)\n    coeff *= levicivita(findpermutation(v, base[bi]))\n    (bi, coeff)\nend\n\n\n\"\"\"\n    multiplicationstable(Npos::Integer, Nneg::Integer, Nzero::Integer, base::Tuple)\n\nGenerates a multiplication table for the Clifford algebra with the specified signature and base vectors.\n\"\"\"\nfunction multiplicationtable(Npos::Integer, Nneg::Integer, Nzero::Integer, base::Tuple)\n    N = Npos + Nneg + Nzero\n    K = 2^N\n    @assert length(base) == K\n    M = Matrix{Tuple}(undef, K, K)\n    for kl = 1:K, kr = 1:K\n        M[kl, kr] = basevectorproduct(Npos, Nneg, base, kl, kr)\n    end\n    ntuple(row -> ntuple(col -> M[row, col], K), K)\nend\n\n\"\"\"\n    CliffordAlgebra(Npos::Integer, Nneg::Integer, Nzero::Integer, S::NTuple(N,Symbol))\n\nSingleton instance of the type CliffordAlgebra that describes a geometric algebra with the signature (Npos,Nneg,Nzero), base symbols S.\nThe base symbols are in order of the signature.\n\"\"\"\nstruct CliffordAlgebra{Np,Nn,Nz,S,BT}\n    function CliffordAlgebra(\n        Npos::Integer,\n        Nneg::Integer,\n        Nzero::Integer,\n        BaseSymbols::NTuple{N,Symbol},\n    ) where {N}\n        Npos = Int(Npos)\n        Nneg = Int(Nneg)\n        Nzero = Int(Nzero)\n        @assert Npos >= 0 && Nneg >= 0 && Nzero >=0 \"Algebra signature must be non-negative.\"\n        @assert Npos + Nneg + Nzero == N \"Base symbol count must match signature.\"\n        BT = adaptbasefordual(enumeratebase(Int(N)))\n        new{Npos,Nneg,Nzero,BaseSymbols,BT}()\n    end\nend\n\n\"\"\"\n    CliffordAlgebra(N::Integer)\n\nGenerates a geometric algebra with signature (N,0,0).\n\"\"\"\nfunction CliffordAlgebra(N::Integer)\n    @assert N>=0 \"Algbra signature must be non-negative.\"\n    CliffordAlgebra(N, 0, 0, ntuple(i -> Symbol(:e, i), N))\nend\n\n\"\"\"\n    CliffordAlgebra(Npos::Integer, Nneg::Integer)\n\nGenerates a geometric algebra with signature (Npos,Nneg,0).\n\"\"\"\nfunction CliffordAlgebra(Npos::Integer, Nneg::Integer)\n    @assert Npos >= 0 && Nneg >= 0 \"Algbra signature must be non-negative.\"\n    CliffordAlgebra(Npos, Nneg, 0, ntuple(i -> Symbol(:e, i), Npos + Nneg))\nend\n\n\"\"\"\n    CliffordAlgebra(Npos::Integer, Nneg::Integer, Nzero::Integer)\n\nGenerates a geometric algebra with signature (Npos,Nneg,Nzero).\n\"\"\"\nfunction CliffordAlgebra(Npos::Integer, Nneg::Integer, Nzero::Integer)\n    @assert Npos >= 0 && Nneg >= 0 && Nzero >= 0 \"Algbra signature must be non-negative.\"\n    CliffordAlgebra(Npos, Nneg, Nzero, ntuple(i -> Symbol(:e, i), Npos + Nneg + Nzero))\nend\n\n\"\"\"\n    CliffordAlgebra(a::Symbol)\n\nGenerates a predefined algebra from a identifier. Known algebras are\n    - :Hyperbolic or :Hyper\n    - :Complex or :ℂ\n    - :Dual or :Grassmann\n    - :Grassmann2D or :G2\n    - :Grassmann3D or :G3\n    - :Quaternions or :ℍ\n    - :Cl2 and :Cl3\n    - :Spacetime\n    - :PGA2D or :Projective2D or :Plane2D\n    - :PGA3D or :Projective3D or :Plane3D\n    - :CGA2D or :Conformal2D\n    - :CGA3D or :Conformal3D\n    - :DCGA3D or :DoubleConformal3D\n    - :TCGA3D or :TripleConformal3D\n    - :DCGSTA or :DoubleConformalSpacetime\n    - :QCGA or :QuadricConformal\n\"\"\"\nfunction CliffordAlgebra(a::Symbol)\n    if a in (:Hyperbolic, :Hyper)\n        return CliffordAlgebra(1, 0, 0, (:j,))\n    elseif a in (:Complex, :ℂ)\n        return CliffordAlgebra(0, 1, 0, (:i,))\n    elseif a in (:Dual, :Grassmann)\n        return CliffordAlgebra(0, 0, 1, (:ε,))\n    elseif a in (:Grassmann2D, :G2)\n        return CliffordAlgebra(0, 0, 2, (:ε₁, :ε₂))\n    elseif a in (:Grassmann3D, :G3)\n        return CliffordAlgebra(0, 0, 3, (:ε₁, :ε₂, :ε₃))\n    elseif a in (:Quaternions, :ℍ)\n        return CliffordAlgebra(0, 2, 0, (:i, :j))\n    elseif a in (:Cl2,)\n        return CliffordAlgebra(2)\n    elseif a in (:Cl3,)\n        return CliffordAlgebra(3)\n    elseif a in (:Spacetime, :STA)\n        return CliffordAlgebra(1, 3, 0, (:t, :x, :y, :z))\n    elseif a in (:PGA2D, :Projective2D, :Plane2D)\n        return CliffordAlgebra(2, 0, 1, (:e1, :e2, :e0))\n    elseif a in (:PGA3D, :Projective3D, :Plane3D)\n        return CliffordAlgebra(3, 0, 1, (:e1, :e2, :e3, :e0))\n    elseif a in (:CGA2D, :Conformal2D)\n        return CliffordAlgebra(3, 1, 0, (:e1, :e2, :e₊, :e₋))\n    elseif a in (:CGA3D, :Conformal3D)\n        return CliffordAlgebra(4, 1, 0, (:e1, :e2, :e3, :e₊, :e₋))\n    elseif a in (:DCGA3D, :DoubleConformal3D)\n        return CliffordAlgebra(6, 2)\n    elseif a in (:TCGA3D, :TripleConformal3D)\n        return CliffordAlgebra(9, 3)\n    elseif a in (:DCGSTA, :DoubleConformalSpacetime)\n        return CliffordAlgebra(4, 8, 0, (:t₁, :t₂, :e₊₁, :e₊₂, :x₁, :x₂, :y₁, :y₂, :z₁, :z₂, :e₋₁, :e₋₂))\n    elseif a in (:QCGA, :QuadricConformal)\n        return CliffordAlgebra(9, 6)\n    else\n        throw(ArgumentError(\"Unknown algebra.\"))\n    end\nend\n\n\n\"\"\"\n    basesymbols(::CliffordAlgebra)\n    basesymbols(::Type{<:CliffordAlgebra})\n\nReturns the 1-vector space basis symbols of the algebra.\n\"\"\"\nbasesymbols(::Type{<:CliffordAlgebra{Np,Nn,Nz,S}}) where {Np,Nn,Nz,S} = S\nbasesymbols(ca::CliffordAlgebra) = basesymbols(typeof(ca))\n\n\"\"\"\n    basetable(::CliffordAlgebra)\n    basetable(::Type{<:CliffordAlgebra})\n\nReturns the internal basis table of the algebra.\n\"\"\"\nbasetable(::Type{<:CliffordAlgebra{Np,Nn,Nz,S,BT}}) where {Np,Nn,Nz,S,BT} = BT\nbasetable(ca::CliffordAlgebra) = basetable(typeof(ca))\n\n\"\"\"\n    multtable(::CliffordAlgebra)\n    multtable(::Type{<:CliffordAlgebra})\n\nReturns the internal multuplication table of the geometric product of the algebra.\n\"\"\"\nmulttable(::Type{<:CliffordAlgebra{Np,Nn,Nz,S,BT}}) where {Np,Nn,Nz,S,BT} = multiplicationtable(Np, Nn, Nz, BT)\nmulttable(ca::CliffordAlgebra) = multtable(typeof(ca))\n\n\"\"\"\n    baseproduct(::CliffordAlgebra, nleft::Integer, nright::Integer)\n    baseproduct(::Type{<:CliffordAlgebra}, nleft::Integer, nright::Integer)\n\nReturns a tuple holding the basis index and the scalar coefficient of the geometric product of the two basis vectors with indices nleft and nright.\n\"\"\"\nbaseproduct(::Type{CliffordAlgebra{Np,Nn,Nz,S,BT}}, nleft::Integer, nright::Integer) where {Np,Nn,Nz,S,BT} = basevectorproduct(Np, Nn, BT, nleft, nright)\nbaseproduct(ca::CliffordAlgebra, nleft::Integer, nright::Integer) = baseproduct(typeof(ca), nleft, nright)\n\n\"\"\"\n    order(::CliffordAlgebra)\n    order(::Type{<:CliffordAlgebra})\n\nReturns the order of the algebra. The order is the sum of the signature.\n\"\"\"\norder(::Type{<:CliffordAlgebra{Np,Nn,Nz}}) where {Np,Nn,Nz} = Np + Nn + Nz\norder(ca::CliffordAlgebra) = order(typeof(ca))\n\n\"\"\"\n    signature(::CliffordAlgebra)\n    signature(::Type{<:CliffordAlgebra})\n\nReturns the signature of the algebra.\n\"\"\"\nsignature(::Type{<:CliffordAlgebra{Np,Nn,Nz}}) where {Np,Nn,Nz} = (Np, Nn, Nz)\nsignature(ca::CliffordAlgebra) = signature(typeof(ca))\n\n\"\"\"\n    basesignature(::CliffordAlgebra, n::Integer)\n    basesignature(::Type{<:CliffordAlgebra}, n::Integer)\n\nReturns the signature value of the n-th basis 1-vector. The return value is +1, -1 or 0.\n\"\"\"\nfunction basesignature(CA::Type{<:CliffordAlgebra{Np,Nn,Nz}}, n::Integer) where {Np,Nn,Nz}\n    @assert 1 <= n <= order(CA)\n    if n <= Np\n        return +1\n    elseif n <= Np + Nn\n        return -1\n    else\n        return 0\n    end\nend\n\nbasesignature(ca::CliffordAlgebra, n::Integer) = basesignature(typeof(ca), n)\n\n\"\"\"\n    dimension(::CliffordAlgebra)\n    dimension(::Type{<:CliffordAlgebra})\n\nReturns the dimension of the algebra, i.e. the number of coefficients in a general multivector.\n\"\"\"\ndimension(CA::Type{<:CliffordAlgebra}) = 2^order(CA)\ndimension(ca::CliffordAlgebra) = dimension(typeof(ca))\n\n\"\"\"\n    character(::CliffordAlgebra)\n    character(::Type{<:CliffordAlgebra})\n\nReturns the square of the pseudoscalar of the algebra.\n\"\"\"\ncharacter(CA::Type{<:CliffordAlgebra}) = baseproduct(CA, dimension(CA), dimension(CA))[2]\ncharacter(ca::CliffordAlgebra) = character(typeof(ca))\n\n\"\"\"\n    basegrade(::CliffordAlgebra, n::Integer)\n    basegrade(::Type{<:CliffordAlgebra}, n::Integer)\n\nReturns the grade of the n-th basis multivector of the algebra.\n\"\"\"\nbasegrade(CA::Type{<:CliffordAlgebra}, n::Integer) = length(basetable(CA)[n])\nbasegrade(ca::CliffordAlgebra, n::Integer) = basegrade(typeof(ca), n)\n\n\"\"\"\n    basereverse(::CliffordAlgebra, n::Integer)\n    basereverse(::Type{<:CliffordAlgebra}, n::Integer)\n\nReturns the sign change of the n-th basis multivector under reversal.\n\"\"\"\nbasereverse(CA::Type{<:CliffordAlgebra}, n::Integer) = (-1)^(basegrade(CA, n) ÷ 2)\nbasereverse(ca::CliffordAlgebra, n::Integer) = basereverse(typeof(ca), n)\n\n\"\"\"\n    basesymbol(::CliffordAlgebra, n::Integer)\n    basesymbol(::Type{<:CliffordAlgebra}, n::Integer)\n\nReturns the symbol used for the n-th basis multivector of the algebra.\n\"\"\"\nfunction basesymbol(CA::Type{<:CliffordAlgebra}, n::Integer)\n    @assert 1 <= n <= dimension(CA)\n    s = basetable(CA)[n]\n    if isempty(s)\n        Symbol(:𝟏)\n    else\n        Symbol(map(i -> basesymbols(CA)[i], s)...)\n    end\nend\n\nbasesymbol(ca::CliffordAlgebra, n::Integer) = basesymbol(typeof(ca), n)\n\n\n\"\"\"\n    caleytable(io::IO, ca::CliffordAlgebra)\n    caleytable(io::IO, CA::Type{<:CliffordAlgebra})\n\nGenerates a Cayley table view of the algebra.\n\"\"\"\ncayleytable(io::IO, ca::CliffordAlgebra) = cayleytable(io, typeof(ca))\n\nfunction cayleytable(io::IO, CA::Type{<:CliffordAlgebra})\n    dim = dimension(CA)\n    bs = map(s -> s == Symbol() ? Symbol(\"1\") : s, ntuple(k -> basesymbol(CA, k), dim))\n    mt = multtable(CA)\n    table = Matrix{String}(undef, dim, dim)\n    for col = 1:dim\n        for row = 1:dim\n            baseidx, coeff = mt[row][col]\n            @assert coeff in (-1, 0, 1)\n            if baseidx == 1\n                table[row, col] = coeff == -1 ? \"-1\" : coeff == 1 ? \"+1\" : \"0\"\n            else\n                if iszero(coeff)\n                    table[row, col] = \"0\"\n                else\n                    table[row, col] = string(coeff > 0 ? :+ : :-, bs[baseidx])\n                end\n            end\n        end\n    end\n    lines = vcat(0, cumsum([binomial(order(CA), i) for i = 0:order(CA)]))\n    pretty_table(\n        io,\n        table;\n        show_row_number = false,\n        crop = :none,\n        noheader = true,\n        alignment = :c,\n        vlines = lines,\n        hlines = lines,\n    )\nend\n\n\n\"\"\"\n    signaturetable(io::IO, ca::CliffordAlgebra)\n    signaturetable(io::IO, CA::Type{<:CliffordAlgebra})\n\nPrints the 1-vector basis symbols and their squares.\n\"\"\"\nsignaturetable(io::IO, ca::CliffordAlgebra) = signaturetable(io, typeof(ca))\n\nfunction signaturetable(io::IO, CA::Type{<:CliffordAlgebra})\n    bs = ntuple( k -> basesymbol(CA, k+1), order(CA))\n    table = Matrix{String}(undef, order(CA), 2)\n    for (n,s) = enumerate(bs)\n        sig = basesignature(CA,n)\n        table[n,1] = string(s)\n        table[n,2] = sig == +1 ? \"+1\" : sig == -1 ? \"-1\" : \"0\"\n    end\n    pretty_table(\n        io,\n        table;\n        show_row_number = false,\n        crop = :none,\n        noheader = true,\n        alignment = :c\n    )\nend\n\nfunction show(io::IO, ca::CliffordAlgebra)\n    (Np, Nn, Nz) = signature(ca)\n    print(io, \"Cl(\", Np, \",\", Nn, \",\", Nz, \")\")\nend\n", "meta": {"hexsha": "084469e41c3b9205aa2f66e186717ff239ef4dbf", "size": 12081, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algebra.jl", "max_stars_repo_name": "ATell-SoundTheory/CliffordAlgebras", "max_stars_repo_head_hexsha": "62cc0237e7d91772c86121111d610c65dc02d1b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2021-11-23T16:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:22:02.000Z", "max_issues_repo_path": "src/algebra.jl", "max_issues_repo_name": "ATell-SoundTheory/CliffordAlgebras", "max_issues_repo_head_hexsha": "62cc0237e7d91772c86121111d610c65dc02d1b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-11-23T15:28:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-09T08:20:59.000Z", "max_forks_repo_path": "src/algebra.jl", "max_forks_repo_name": "ATell-SoundTheory/CliffordAlgebras.jl", "max_forks_repo_head_hexsha": "62cc0237e7d91772c86121111d610c65dc02d1b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6513513514, "max_line_length": 153, "alphanum_fraction": 0.6369505836, "num_tokens": 3897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7542775149130418}}
{"text": "function derivative(A::LinearInterpolation{<:AbstractVector}, t::Number)\n  idx = searchsortedfirst(A.t, t)\n  if A.t[idx] >= t\n    idx -= 1\n  end\n  idx == 0 ? idx += 1 : nothing\n  θ = 1 / (A.t[idx+1] - A.t[idx])\n  (A.u[idx+1] - A.u[idx]) / (A.t[idx+1] - A.t[idx])\nend\n\nfunction derivative(A::LinearInterpolation{<:AbstractMatrix}, t::Number)\n  idx = searchsortedfirst(A.t, t)\n  if A.t[idx] >= t\n    idx -= 1\n  end\n  idx == 0 ? idx += 1 : nothing\n  θ = 1 / (A.t[idx+1] - A.t[idx])\n  @views @. (A.u[:, idx+1] - A.u[:, idx]) / (A.t[idx+1] - A.t[idx])\nend\n\nfunction derivative(A::QuadraticInterpolation{<:AbstractVector}, t::Number)\n  idx = searchsortedfirst(A.t, t)\n  if A.t[idx] >= t\n    idx -= 1\n  end\n  idx == 0 ? idx += 1 : nothing\n  if idx == length(A.t) - 1\n    i₀ = idx - 1; i₁ = idx; i₂ = i₁ + 1;\n  else\n    i₀ = idx; i₁ = i₀ + 1; i₂ = i₁ + 1;\n  end\n  dl₀ = (2t - A.t[i₁] - A.t[i₂]) / ((A.t[i₀] - A.t[i₁]) * (A.t[i₀] - A.t[i₂]))\n  dl₁ = (2t - A.t[i₀] - A.t[i₂]) / ((A.t[i₁] - A.t[i₀]) * (A.t[i₁] - A.t[i₂]))\n  dl₂ = (2t - A.t[i₀] - A.t[i₁]) / ((A.t[i₂] - A.t[i₀]) * (A.t[i₂] - A.t[i₁]))\n  A.u[i₀] * dl₀ + A.u[i₁] * dl₁ + A.u[i₂] * dl₂\nend\n\nfunction derivative(A::QuadraticInterpolation{<:AbstractMatrix}, t::Number)\n  idx = searchsortedfirst(A.t, t)\n  if A.t[idx] >= t\n      idx -= 1\n  end\n  idx == 0 ? idx += 1 : nothing\n  if idx == length(A.t) - 1\n    i₀ = idx - 1; i₁ = idx; i₂ = i₁ + 1;\n  else\n    i₀ = idx; i₁ = i₀ + 1; i₂ = i₁ + 1;\n  end\n  dl₀ = (2t - A.t[i₁] - A.t[i₂]) / ((A.t[i₀] - A.t[i₁]) * (A.t[i₀] - A.t[i₂]))\n  dl₁ = (2t - A.t[i₀] - A.t[i₂]) / ((A.t[i₁] - A.t[i₀]) * (A.t[i₁] - A.t[i₂]))\n  dl₂ = (2t - A.t[i₀] - A.t[i₁]) / ((A.t[i₂] - A.t[i₀]) * (A.t[i₂] - A.t[i₁]))\n  @views @. A.u[:, i₀] * dl₀ + A.u[:, i₁] * dl₁ + A.u[:, i₂] * dl₂\nend\n\nfunction derivative(A::LagrangeInterpolation{<:AbstractVector}, t::Number)\n  idxs = findRequiredIdxs(A, t)\n  if A.t[idxs[1]] == t\n    return zero(A.u[idxs[1]])\n  end\n  G = zero(A.u[1]); F = zero(A.t[1])\n  DG = zero(A.u[1]); DF = zero(A.t[1])\n  tmp = G\n  for i = 1:length(idxs)\n    if isnan(A.bcache[idxs[i]])\n      mult = one(A.t[1])\n      for j = 1:(i - 1)\n        mult *= (A.t[idxs[i]] - A.t[idxs[j]])\n      end\n      for j = (i+1):length(idxs)\n        mult *= (A.t[idxs[i]] - A.t[idxs[j]])\n      end\n      A.bcache[idxs[i]] = mult\n    else\n      mult = A.bcache[idxs[i]]\n    end\n    wi = inv(mult)\n    tti = t - A.t[idxs[i]]\n    tmp = wi / (t - A.t[idxs[i]])\n    g = tmp * A.u[idxs[i]]\n    G += g\n    DG -= g / (t - A.t[idxs[i]])\n    F += tmp\n    DF -= tmp / (t - A.t[idxs[i]])\n  end\n  (DG * F - G * DF) / (F ^ 2)\nend\n\nfunction derivative(A::LagrangeInterpolation{<:AbstractMatrix}, t::Number)\n  idxs = findRequiredIdxs(A, t)\n  if A.t[idxs[1]] == t\n    return zero(A.u[:, idxs[1]])\n  end\n  G = zero(A.u[:, 1]); F = zero(A.t[1])\n  DG = zero(A.u[:, 1]); DF = zero(A.t[1])\n  tmp = G\n  for i = 1:length(idxs)\n    if isnan(A.bcache[idxs[i]])\n      mult = one(A.t[1])\n      for j = 1:(i - 1)\n        mult *= (A.t[idxs[i]] - A.t[idxs[j]])\n      end\n      for j = (i+1):length(idxs)\n        mult *= (A.t[idxs[i]] - A.t[idxs[j]])\n      end\n      A.bcache[idxs[i]] = mult\n    else\n      mult = A.bcache[idxs[i]]\n    end\n    wi = inv(mult)\n    tti = t - A.t[idxs[i]]\n    tmp = wi / (t - A.t[idxs[i]])\n    g = tmp * A.u[:, idxs[i]]\n    @. G += g\n    @. DG -= g / (t - A.t[idxs[i]])\n    F += tmp\n    DF -= tmp / (t - A.t[idxs[i]])\n  end\n  @. (DG * F - G * DF) / (F ^ 2)\nend\n\nfunction derivative(A::AkimaInterpolation{<:AbstractVector}, t::Number)\n  i = searchsortedlast(A.t, t)\n  i == 0 && return zero(A.u[1])\n  i == length(A.t) && return zero(A.u[end])\n  wj = t - A.t[i]\n  @evalpoly wj A.b[i] 2A.c[i] 3A.d[i]\nend\n\nfunction derivative(A::ConstantInterpolation{<:AbstractVector}, t::Number)\n  return isempty(searchsorted(A.t, t)) ? zero(A.u[1]) : eltype(A.u)(NaN)\nend\n\nfunction derivative(A::ConstantInterpolation{<:AbstractMatrix}, t::Number)\n  return isempty(searchsorted(A.t, t)) ? zero(A.u[:, 1]) : eltype(A.u)(NaN) .* A.u[:, 1]\nend\n\n# QuadraticSpline Interpolation\nfunction derivative(A::QuadraticSpline{<:AbstractVector{<:Number}}, t::Number)\n  i = searchsortedfirst(A.t, t)\n  i == 1 ? i += 1 : nothing\n  σ = 1//2 * (A.z[i] - A.z[i - 1]) / (A.t[i] - A.t[i - 1])\n  A.z[i-1] + 2σ * (t - A.t[i-1])\nend\n\n# CubicSpline Interpolation\nfunction derivative(A::CubicSpline{<:AbstractVector{<:Number}}, t::Number)\n  i = searchsortedfirst(A.t, t)\n  isnothing(i) ? i = length(A.t) - 1 : i -= 1\n  i == 0 ? i += 1 : nothing\n  dI = -3A.z[i] * (A.t[i + 1] - t)^2 / (6A.h[i + 1]) + 3A.z[i + 1] * (t - A.t[i])^2 / (6A.h[i + 1])\n  dC = A.u[i + 1] / A.h[i + 1] - A.z[i + 1] * A.h[i + 1] / 6\n  dD = -(A.u[i] / A.h[i + 1] - A.z[i] * A.h[i + 1] / 6)\n  dI + dC + dD\nend\n\nfunction derivative(A::BSplineInterpolation{<:AbstractVector{<:Number}}, t::Number)\n  # change t into param [0 1]\n  idx = searchsortedlast(A.t,t)\n  idx == length(A.t) ? idx -= 1 : nothing\n  n = length(A.t)\n  scale = (A.p[idx+1] - A.p[idx]) / (A.t[idx+1] - A.t[idx])\n  t_ = A.p[idx] + (t - A.t[idx]) * scale\n  N = DataInterpolations.spline_coefficients(n, A.d-1, A.k, t_)\n  ducum = zero(eltype(A.u))\n  for i = 1:(n - 1)\n    ducum += N[i + 1] * (A.c[i + 1] - A.c[i]) / (A.k[i + A.d + 1] - A.k[i + 1])\n  end\n  ducum * A.d * scale\nend\n\n# BSpline Curve Approx\nfunction derivative(A::BSplineApprox{<:AbstractVector{<:Number}}, t::Number)\n  # change t into param [0 1]\n  idx = searchsortedlast(A.t,t)\n  idx == 0 ? idx += 1 : nothing\n  scale = (A.p[idx+1] - A.p[idx]) / (A.t[idx+1] - A.t[idx])\n  t_ = A.p[idx] + (t - A.t[idx]) * scale\n  N = spline_coefficients(A.h, A.d-1, A.k, t_)\n  ducum = zero(eltype(A.u))\n  for i = 1:(A.h - 1)\n    ducum += N[i + 1] * (A.c[i + 1] - A.c[i]) / (A.k[i + A.d + 1] - A.k[i + 1])\n  end\n  ducum * A.d * scale\nend\n", "meta": {"hexsha": "6335488cc6d161242e6298393d052f86fa264d96", "size": 5734, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/derivatives.jl", "max_stars_repo_name": "oxinabox/DataInterpolations.jl", "max_stars_repo_head_hexsha": "48dc13a270b29b49fde77e300a9e14db091ccbeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2019-10-01T17:22:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T16:34:42.000Z", "max_issues_repo_path": "src/derivatives.jl", "max_issues_repo_name": "oxinabox/DataInterpolations.jl", "max_issues_repo_head_hexsha": "48dc13a270b29b49fde77e300a9e14db091ccbeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47, "max_issues_repo_issues_event_min_datetime": "2019-08-10T02:48:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T14:30:37.000Z", "max_forks_repo_path": "src/derivatives.jl", "max_forks_repo_name": "oxinabox/DataInterpolations.jl", "max_forks_repo_head_hexsha": "48dc13a270b29b49fde77e300a9e14db091ccbeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-08-10T15:27:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T19:40:03.000Z", "avg_line_length": 30.9945945946, "max_line_length": 99, "alphanum_fraction": 0.5132542728, "num_tokens": 2407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069105, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7542775098707245}}
{"text": "using CSV\nusing LinearAlgebra: dot, I\nusing CairoMakie\n\nconst Σ = [1.0  0.1  0.1;\n           0.1  1.0  0.1;\n           0.1  0.1  1.0]\n\nconst v = [1.0/sqrt(3), 1.0/sqrt(3), 1.0/sqrt(3)]\nconst σ² = 1\n\nconst Σ2 = -0.95 * v * v' + I(3)\n\nf(x) = abs2(dot(v, Σ * x)) / (dot(x, Σ * x) + σ² * dot(x, x))\n\ng(x) = abs2(dot(v, Σ2 * x)) / (dot(x, Σ2 * x) + σ² * dot(x, x))\n\n# Helper function to compute extra coordinate\nfunction getZ(x,y)\n    if abs2(x) + abs2(y) > 1 - 10*eps()\n        return NaN\n    end\n    return sqrt(1 - abs2(x) - abs2(y))\nend\n\nfunction rewardPositive(x,y)\n    return f([x,y,getZ(x,y)])\nend\n\nfunction rewardNegative(x,y)\n    return f([x,y,-getZ(x,y)])\nend\n\n\nfunction rewardPositive2(x,y)\n    return g([x,y,getZ(x,y)])\nend\n\nfunction rewardNegative2(x,y)\n    return g([x,y,-getZ(x,y)])\nend\n\n# Sample Circle\nx = -1.1:0.01:1.1\ny = -1.1:0.01:1.1\n\nnoto_sans = \"./resources/NotoSans-Regular.ttf\"\nnoto_sans_bold = \"./resources/NotoSans-Bold.ttf\"\n\ntickfontsize    = 26\nlabelfontsize   = 28\nbasewidth = 2\n\nfig = Figure(font=noto_sans, resolution=(1500,525), figure_padding=40)\n\n\nax1 = Axis( fig[1,1],\n            xticklabelsize=tickfontsize, \n            yticklabelsize=tickfontsize, \n            yticklabelpad=2,\n            xlabel=\"x\", ylabel = \"y\",\n            xlabelsize=labelfontsize,\n            ylabelsize=labelfontsize,\n            titlesize=labelfontsize,\n            ratio=AxisAspect(1))\n\n\nhm = heatmap!(ax1,x,y,rewardPositive)\n\n\nax2 = Axis( fig[1,2],\n            xticklabelsize=tickfontsize, \n            yticklabelsize=tickfontsize, \n            yticklabelpad=2,\n            xlabel=\"x\", ylabel = \"y\",\n            xlabelsize=labelfontsize,\n            ylabelsize=labelfontsize,\n            titlesize=labelfontsize,\n            ratio=AxisAspect(1))\n\n\nheatmap!(ax2,x,y,rewardNegative)\n\n\nax3 = Axis( fig[1,3],\n            xticklabelsize=tickfontsize, \n            yticklabelsize=tickfontsize, \n            yticklabelpad=2,\n            xlabel=\"x\", ylabel = \"y\",\n            xlabelsize=labelfontsize,\n            ylabelsize=labelfontsize,\n            titlesize=labelfontsize,\n            ratio=AxisAspect(1))\n\n\nhm2 = heatmap!(ax3,x,y,rewardPositive2)\n\n\nax4 = Axis( fig[1,4],\n            xticklabelsize=tickfontsize, \n            yticklabelsize=tickfontsize, \n            yticklabelpad=2,\n            xlabel=\"x\", ylabel = \"y\",\n            xlabelsize=labelfontsize,\n            ylabelsize=labelfontsize,\n            titlesize=labelfontsize,\n            ratio=AxisAspect(1))\n\n\nheatmap!(ax4,x,y,rewardNegative2)\n\n\nColorbar(fig[2, 1:2], hm, vertical = false, flipaxis = false, ticklabelsize=tickfontsize)\nColorbar(fig[2, 3:4], hm2, vertical = false, flipaxis = false, ticklabelsize=tickfontsize)\n\ncolgap!(fig.layout,15)\ncolgap!(fig.layout,2,100)\n\nLabel(fig[1,1,TopLeft()], \"A\", font=noto_sans_bold, textsize = 36, halign=:left, valign=:bottom, padding=(25,0,10,0))\nLabel(fig[1,3,TopLeft()], \"B\", font=noto_sans_bold, textsize = 36, halign=:left, valign=:bottom, padding=(25,0,10,0))\n\n\nsave(\"out/OptSurface.pdf\",fig)\n", "meta": {"hexsha": "59782023964b9d2654862461a5232100be2cb193", "size": 3016, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PlotGeneration/DescentTrajectory/SurfacePlot.jl", "max_stars_repo_name": "Helmuthn/naumer_ICML_2022.jl", "max_stars_repo_head_hexsha": "03756f395fa6a0113659a24218c479ef380f45f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PlotGeneration/DescentTrajectory/SurfacePlot.jl", "max_issues_repo_name": "Helmuthn/naumer_ICML_2022.jl", "max_issues_repo_head_hexsha": "03756f395fa6a0113659a24218c479ef380f45f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PlotGeneration/DescentTrajectory/SurfacePlot.jl", "max_forks_repo_name": "Helmuthn/naumer_ICML_2022.jl", "max_forks_repo_head_hexsha": "03756f395fa6a0113659a24218c479ef380f45f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3225806452, "max_line_length": 117, "alphanum_fraction": 0.601127321, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7542748396629811}}
{"text": "using Gridap\n\n# Geometry\ndomain = (0,1,0,1); cells = (10,10)\nmodel = CartesianDiscreteModel(domain,cells)\n\n# Integration\ndegree = 2\nΩ = Triangulation(model)\nΓ = BoundaryTriangulation(model)\ndΩ = LebesgueMeasure(Ω,degree)\ndΓ = LebesgueMeasure(Γ,degree)\n\n# Manufactured solution\nu(x) = x[1]+x[2]\n\n# Parameter-dependent weak form\na(p,u,v) = ∫( (p*p)*∇(v)⋅∇(u) )*dΩ\nl(v) = ∫( -v*Δ(u) )*dΩ\n\n# Objective function in terms of primal solution\n# (squared distance wrt exact solution u on Ω and Γ\n# as an example involving different domains)\n# Note: the following function returns cell contributions.\n# The final objective is computed as sum(j(v))\nj(v) = ∫( abs2(u-v) )*dΩ + ∫( abs2(u-v) )*dΓ\n\n# FE spaces: P for params, V, U for primal solution\nP = FESpace(model,ReferenceFE(:Lagrangian,Float64,0),conformity=:L2)\nV = TestFESpace(model,ReferenceFE(:Lagrangian,Float64,1),dirichlet_tags=\"boundary\")\nU = TrialFESpace(V,u)\n\nusing Gridap.FESpaces\n\n# Objective function (scalar), plus its gradient (vector) in terms of p\n# fp, ∇fp = f_∇f(p)\nfunction f_∇f(p)\n  # Direct solve\n  a_at_p(u,v) = a(p,u,v)\n  op = AffineFEOperator(a_at_p,l,U,V)\n  u = solve(op)\n  # Adjoint solve\n  A = get_matrix(op)\n  dj_du = ∇(j)(u) # autodiff\n  b = assemble_vector(dj_du,V)\n  λ = FEFunction(V,A\\b) # assuming A self-adjoint\n  # we want to have something like this\n  # op_t = AdjointFEOperator(op, ∇(j), selfadjoint=true )\n  # u, lambda = solve(op,op_t)\n  # for the moment, we can do more low level things at the driver level, e.g., extracting matrices, etc for the adjoint\n  # in any case, it is not needed for self-adjoint problems\n  # Objective\n  fp = sum(j(u))\n  # Its gradient\n  ∂a_∂p = ∇(x -> a(x,u,λ))(p) # Autodiff\n  ∇fp = -1*assemble_vector(∂a_∂p,P)\n  fp, ∇fp\nend\n\n# run for a given realization of p\np = FEFunction(P,rand(num_free_dofs(P)).+1)\nfp, ∇fp = f_∇f(p)\n# Print results\n@show fp\nwritevtk(Ω,\"trian\",cellfields=[\"∇fp\"=>FEFunction(P,∇fp)])\n\nfunction df_dp(uvec,pvec,λvec)\n  da(p,u,v,dp) = (2*p*dp)*∇(v)⋅∇(u)\n  uh = FEFunction(U,uvec)\n  ph = FEFunction(P,pvec)\n  λh = FEFunction(V,λvec)\n  t = FESource((dp)->da(ph,uh,λh,dp),trian,quad)\n  op = AffineFEOperator(P,Q,t)\n  get_vector(op)\nend\n", "meta": {"hexsha": "3f4a09f1f49cf291aeef6a8b60ffdf0ec72dc254", "size": 2165, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Adjoint.jl", "max_stars_repo_name": "santiagobadia/GridapGeosciences", "max_stars_repo_head_hexsha": "c9bfdd7bbd33a8464376d1d102a44d78ccd11069", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2020-04-20T07:04:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T17:40:12.000Z", "max_issues_repo_path": "src/Adjoint.jl", "max_issues_repo_name": "santiagobadia/GridapGeosciences", "max_issues_repo_head_hexsha": "c9bfdd7bbd33a8464376d1d102a44d78ccd11069", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-06-09T04:05:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T04:15:08.000Z", "max_forks_repo_path": "src/Adjoint.jl", "max_forks_repo_name": "santiagobadia/GridapGeosciences", "max_forks_repo_head_hexsha": "c9bfdd7bbd33a8464376d1d102a44d78ccd11069", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-03-10T06:11:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-05T02:32:21.000Z", "avg_line_length": 28.4868421053, "max_line_length": 119, "alphanum_fraction": 0.6752886836, "num_tokens": 807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308128813471, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.754274838166563}}
{"text": "module LCA\nexport lca\n\n#Make all columns of the input matrix have a norm of 1\n# D - input matrix (modified in place)\nfunction unitary_columns!(D::Matrix{Float64})\n    for i = 1:size(D,2)\n        D[:,i] = D[:,i]/norm(D[:,i]);\n    end\n    nothing\nend\n\n#Perform the positive/negative soft threshold function on each element\n# a - result vector (modified in place)\n# u - input vector\n# T - threshold\nfunction soft_threshold!(a::Vector{Float64}, u::Vector{Float64}, T::Float64)\n    for i = 1:length(u)\n        if abs(u[i]) > T\n            a[i,1] = u[i]-sign(u[i])*T;\n        else\n            a[i,1] = 0;\n        end\n    end\n    nothing\nend\n\n#Perform Locally Competitive Algorithm for sparse recovery\n# s      - Input to be approximated\n# D      - Dictionary\n# T_soft - Soft threshold value (higher promotes more sparseness)\n# iter   - maximum number of iterations\n# τ      - 1/learning rate\nfunction lca(s::Vector{Float64}, D::Matrix{Float64}; T_soft::Float64=0.1,\n             iter::Int=10000, τ::Float64=100.0)\n    #Impose Unitary norm\n    unitary_columns!(D)\n\n    # Inhibition Matrix\n    G = D'*D;\n    for i=1:size(G,1)\n        G[i,i] = 0; \n    end\n\n    # Initialize LCA Parameters\n    b = D'*s; # initial projection / excitatory input\n\n    u = zeros(size(b)); # initial state of nodes = 0\n    a = zeros(size(b)); # initial sparse rep = 0          \n\n    for i=1:iter\n        # soft thresholding function\n        soft_threshold!(a, u, T_soft)\n\n        # node dynamics\n        Δu = (b  - u - G*a)/τ; \n        u += Δu;\n\n        if(norm(Δu) < 1e-5)\n            break\n        end\n    end\n\n    return a\nend\n\nend # module\n", "meta": {"hexsha": "33f443d74db7eeee811082c1c52701eefa48e05d", "size": 1613, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LCA.jl", "max_stars_repo_name": "UnofficialJuliaMirror/LCA.jl-09519885-d2c1-5f68-9f99-0bf084a786ec", "max_stars_repo_head_hexsha": "b458d8ad71ccf265b26922efa13130c62a41fb25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LCA.jl", "max_issues_repo_name": "UnofficialJuliaMirror/LCA.jl-09519885-d2c1-5f68-9f99-0bf084a786ec", "max_issues_repo_head_hexsha": "b458d8ad71ccf265b26922efa13130c62a41fb25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LCA.jl", "max_forks_repo_name": "UnofficialJuliaMirror/LCA.jl-09519885-d2c1-5f68-9f99-0bf084a786ec", "max_forks_repo_head_hexsha": "b458d8ad71ccf265b26922efa13130c62a41fb25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7205882353, "max_line_length": 76, "alphanum_fraction": 0.5852448853, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7542748316948364}}
{"text": "#=\nP35 (**) Determine the prime factors of a given positive integer.\nConstruct a flat list containing the prime factors in ascending order.\nExample:\n* (prime-factors 315)\n(3 3 5 7)\n=#\n\nSMALLEST_PRIME = 2\n\nfunction next_prime(n)\n    # Brute-force incremental check\n    isprime(n) ? n : next_prime(n + 1)\nend\n\nfunction _prime_factors(n, x, pf)\n    if isprime(n)\n        vcat(pf, n)\n    else\n        if mod(n, x) == 0\n            _prime_factors(div(n, x), SMALLEST_PRIME, vcat(pf, x))\n        else\n            _prime_factors(n, next_prime(x + 1), pf)\n        end\n    end\nend\n\nfunction prime_factors(n)\n    # Starting with the smallest prime, 2\n    isprime(n) ? n : _prime_factors(n, SMALLEST_PRIME, [])\nend\n\n@assert prime_factors(315) == [3, 3, 5, 7]\n@assert prime_factors(360) == [2, 2, 2, 3, 3, 5]\n@assert prime_factors(144) == [2, 2, 2, 2, 3, 3]\n\nprintln(\"Tests passed: JL-35.jl\")\n", "meta": {"hexsha": "efbbe4125cf805b7b9231fc07a4300634482742f", "size": 881, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JL-35.jl", "max_stars_repo_name": "microamp/jl-99", "max_stars_repo_head_hexsha": "5d49a7e1617394e6cbc06f1a94fe6230b3025d73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JL-35.jl", "max_issues_repo_name": "microamp/jl-99", "max_issues_repo_head_hexsha": "5d49a7e1617394e6cbc06f1a94fe6230b3025d73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JL-35.jl", "max_forks_repo_name": "microamp/jl-99", "max_forks_repo_head_hexsha": "5d49a7e1617394e6cbc06f1a94fe6230b3025d73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1842105263, "max_line_length": 70, "alphanum_fraction": 0.628830874, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7542572332162623}}
{"text": "# Simple example of a Neumann problem:\n#\n#           y\n#             |\n#             |     u_y = cos(omega x)\n#          Ly ----------------------------------\n#             |                                |\n#             |                                |\n#             |                                |\n#     u_x = 0 |    -u_xx - u_yy + u = 0        | u_x = 0\n#             |                                |\n#             |                                |\n#             |                                |\n#           -----------------------------------|-----  x\n#                         u_y = 0              Lx\n#\n# Here, omega = 2 n pi / Lx, and the exact solution is\n#\n#      u = cos(omega x) * cosh(alpha y) / (alpha sinh(alpha Ly)\n#\n# where alpha^2 = 1 + omega^2.\n\nusing FinElt\nusing FinElt.PlanarPoisson\nusing Printf\n\ninclude(\"params.jl\")\n\nconst omega = 2 * pi / Lx\nconst alpha = sqrt(1.0 + omega^2)\n\nfunction exact_u(x)\n    return cos(omega*x[1]) * cosh(alpha*x[2]) / (alpha*sinh(alpha*Ly))\nend\n\nfunction gN(x)\n    return cos(omega*x[1])\nend\n\nmaxerr = zeros(refinements+1)\n@printf(\"%10s  %12s  %8s  %8s\\n\\n\", \n        \"N\", \"max error\", \"rate\", \"seconds\")\nfor k = 0:refinements\n    start = time()\n    mesh = read_msh_file(\"rect$k.msh\")    \n    vp = VariationalProblem(mesh)\n    add_bilin_form!(vp, \"Omega\", grad_dot_grad!)\n    add_bilin_form!(vp, \"Omega\", func_times_func!)\n    add_lin_functnl!(vp, \"Top\", bdry_source_times_func!, gN)\n    A, b = assembled_linear_system(vp)\n    ufree = A \\ b\n    uh = complete_soln(ufree, vp)\n    u = get_nodal_vals(exact_u, mesh)\n    finish = time()\n    maxerr[k+1] = maximum(abs.(uh-u))\n    N = length(ufree)\n    if k == 0\n        @printf(\"%10d  %12.4e\\n\", N, maxerr[k+1])\n    else\n        rate = log2(maxerr[k]/maxerr[k+1])\n        elapsed = finish - start\n        @printf(\"%10d  %12.4e  %8.4f  %8.4f\\n\", \n                N, maxerr[k+1], rate, elapsed)\n    end\nend\n\n", "meta": {"hexsha": "1ea22780aa6f3969ee56cf322d7936e492936bbe", "size": 1912, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/rectangle/neumann.jl", "max_stars_repo_name": "billmclean/FinElt.jl", "max_stars_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-07-18T20:04:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:29:09.000Z", "max_issues_repo_path": "examples/rectangle/neumann.jl", "max_issues_repo_name": "billmclean/FinElt.jl", "max_issues_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/rectangle/neumann.jl", "max_forks_repo_name": "billmclean/FinElt.jl", "max_forks_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-06-29T15:15:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T18:01:08.000Z", "avg_line_length": 28.5373134328, "max_line_length": 70, "alphanum_fraction": 0.440376569, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.754257225525824}}
{"text": "module SfGravity\n\nusing PhysicalConstants.CODATA2018: c_0, g_n, G, StefanBoltzmannConstant, ħ, k_B\nusing Unitful, UnitfulAstro, Documenter\n\nexport vis_viva, gravity, planetary_mass, planetary_radius, escape_velocity, hill_sphere,\n\torbital_velocity, orbital_period, gravitational_binding_energy, roche_limit, gravity_tug_mass,\n\tbarycentric_distance, tidal_acceleration,\n\tradial_orbit_time, radial_orbit_displacement\n\t\nDocMeta.setdocmeta!(SfGravity, :DocTestSetup, :(using Unitful, UnitfulAstro, ..SfGravity); recursive=true)\n\n\"\"\"\n    vis_viva(parent_mass::Unitful.Mass, semimajor_axis::Unitful.Length, current_radius::Unitful.Length)\n\t\nReturn the square of the relative velocities of a body with negligible mass and orbit with `semimajor_axis` and `current_radius` from a central body of `parent_mass`.\n\n``v^2 = GM\\\\left( \\\\frac{2}{r} - \\\\frac{1}{a} \\\\right)``\n\nwhere ``G`` is the gravitational constant, ``M`` is the mass of the central body, ``r`` is the current separation of the bodies and ``a`` is the semi-major axis of the orbit.\n\"\"\"\nfunction vis_viva(parent_mass::Unitful.Mass, semimajor_axis::Unitful.Length, current_radius::Unitful.Length)\n\tG*parent_mass*(2/current_radius - 1/semimajor_axis) |> u\"m^2/s^2\"\nend\n\n\"\"\"\n\tgravity(m::Unitful.Mass, r::Unitful.Length)\n\t\nCalculate acceleration due to gravity at distance `r` from point mass `m`\n\n# Example\n```jldoctest\njulia> gravity(1u\"Mearth\", 1u\"Rearth\")\n9.798398133669465 m s^-2\n```\"\"\"\ngravity(m::Unitful.Mass, r::Unitful.Length) = G * m / r^2 |> u\"m/s/s\"\n\t\n\"\"\"\n\tgravity(m1::Unitful.Mass, m2::Unitful.Mass, r::Unitful.Length)\n\t\nCalculate the strength of gravity at a distance `r` between two masses, `m1` and `m2`.\n\n# Example\n```jldoctest\njulia> gravity(1u\"Mearth\", 100u\"kg\", 1u\"Rearth\")\n979.8398133669466 N\n```\"\"\"\ngravity(m1::Unitful.Mass, m2::Unitful.Mass, r::Unitful.Length) = G * m1 * m2 / r^2 |> u\"N\"\n\t\n\"\"\"\n\tplanetary_mass(g::Unitful.Acceleration, r::Unitful.Length)\n\t\nCalculate the mass of a body required to produce gravitational acceleration `g` at a distance of `r`.\n\"\"\"\nplanetary_mass(g::Unitful.Acceleration, r::Unitful.Length) = (g * r^2) / G |> u\"kg\"\n\n\"\"\"\n\tplanetary_mass(ve::Unitful.Velocity, r::Unitful.Length)\n\t\nCalculate the mass of a body required to produce escape velocity `ve` at a distance of `r`.\n\"\"\"\nplanetary_mass(ve::Unitful.Velocity, r::Unitful.Length) = r * ve^2 / 2G |> u\"kg\"\n\t\n\"\"\"\n\tplanetary_radius(m::Unitful.Mass, g::Unitful.Acceleration)\n\t\nRadius of a spherical planet of mass `m` with surface gravitational acceleration of `g`.\n\"\"\"\nplanetary_radius(m::Unitful.Mass, g::Unitful.Acceleration) = sqrt((G * m) / g) |> u\"m\"\n\n\"\"\"\n\tplanetary_radius(m::Unitful.Mass, g::Unitful.Acceleration)\n\t\nRadius of a spherical planet of mass `m` with surface escape velocity `ve`.\n\"\"\"\nplanetary_radius(m::Unitful.Mass, ve::Unitful.Velocity) = 2G * m / ve^2 |> u\"m\"\n\n\"\"\"\n\tplanetary_radius(ρ::Unitful.Density, g::Unitful.Acceleration)\n\t\nRadius of a spherical planet of density `ρ` with surface gravitational acceleration of `g`.\n\"\"\"\nplanetary_radius(ρ::Unitful.Density, g::Unitful.Acceleration) = 3g / (4G * π * ρ) |> u\"m\"\n\n\"\"\"\n\tplanetary_radius(ρ::Unitful.Density, ve::Unitful.Velocity)\n\t\nRadius of a spherical planet of density `ρ` with surface escape velocity `ve`.\n\"\"\"\nplanetary_radius(ρ::Unitful.Density, ve::Unitful.Velocity) = sqrt(3ve^2 / (8G * π * ρ)) |> u\"m\"\n\n# kepler's third\n\t\n\"\"\"\n\torbital_period(m::Unitful.Mass, r::Unitful.Length)\n\t\nCalculate the period of an orbit with semimajor axis `r` about a body with mass `m`.\n\n``P = \\\\sqrt{\\\\frac{4π^2r^3}{Gm}}``\n\"\"\"\norbital_period(m::Unitful.Mass, r::Unitful.Length) = sqrt((4π^2 * r^3) / (G * m)) |> u\"s\"\n\t\n\"\"\"\n\torbital_radius(m::Unitful.Mass, t::Unitful.Time)\n\t\nCalculate the semimajor axis of an orbit with period `t` about a body with mass `m`.\n\n``a = \\\\sqrt[3]{\\\\frac{t^2Gm}{4π^2}}``\n\"\"\"\norbital_radius(m::Unitful.Mass, t::Unitful.Time) = cbrt((t^2 * G * m)/(4π^2)) |> u\"m\"\n\n\"\"\"\n    orbital_radius(m::Unitful.Mass, v::Unitful.Velocity)\n\t\nApproximate the radius of a circular orbit with velocity `v` about a body with mass `m`.\n\"\"\"\norbital_radius(m::Unitful.Mass, v::Unitful.Velocity) = (G * m) / v^2 |> u\"m\"\n\t\n\"\"\"\n\torbital_velocity(sma::Unitful.Length, t::Unitful.Time)\n\t\nCalculate the average orbital velocity of a circular orbit of period `t`.\n\nThe orbit is assumed to be circular.\n\"\"\"\norbital_velocity(sma::Unitful.Length, t::Unitful.Time) = 2π * sma / t |> u\"km/s\"\n\t\n\"\"\"\n    orbital_velocity(sma::Unitful.Length, t::Unitful.Time, e)\n\t\nApproximate the average orbital velocity of a orbit with eccentricity `e` and period `t`.\n\n``s_o = \\\\frac{2πa}{t} \\\\left( 1 - \\\\frac{e^2}{4} - \\\\frac{3e^4}{64} - \\\\frac{5e^6}{256} - \\\\frac{175e^8}{16384} \\\\right)``\n\"\"\"\nfunction orbital_velocity(sma::Unitful.Length, t::Unitful.Time, e)\n\t(2π * sma / t) * (1 - e^2 / 4 - 3e^4 / 64 - 5e^6 / 256 - 175e^8 / 16384) |> u\"km/s\"\nend\n\n\"\"\"\n    orbital_velocity(parent_mass::Unitful.Mass, semimajor_axis::Unitful.Length, current_radius::Unitful.Length)\n\nApproximate the orbital velocity of a body with an eccentric orbit with `semimajor_axis` and current orbital radius `current_radius` about a body of mass `parent_mass`\t\n\"\"\"\t\norbital_velocity(parent_mass::Unitful.Mass, semimajor_axis::Unitful.Length, current_radius::Unitful.Length) = sqrt(vis_viva(parent_mass, sem, current_radius)) |> u\"km/s\"\n\n\"\"\"\n    orbital_velocity(parent_mass::Unitful.Mass, radius::Unitful.Length)\n\t\nApproximate the orbital velocity of a body with a circular orbit of radius `radius` about a body with mass `parent_mass`.\n\"\"\"\norbital_velocity(parent_mass::Unitful.Mass, radius::Unitful.Length) = sqrt(G * parent_mass / radius) |> u\"km/s\"\n\t\n\"\"\"\n\tplanetary_mass(orbital_radius::Unitful.Length, orbital_period::Unitful.Time)\n\t\nCalculate the mass of a body orbited by a satellite with semimajor axis `sma` and period `orbital_period`.\n\n``M_p = \\\\frac{4π^2a^3}{GT^2}``\n\nwhere ``a`` is the semi-major axis and ``T`` is the orbital period.\n\"\"\"\nplanetary_mass(sma::Unitful.Length, orbital_period::Unitful.Time) = (4π^2 * sma^3) / (G * orbital_period^2) |> u\"kg\"\n\n\"\"\"\n\tescape_velocity(m::Unitful.Mass, r::Unitful.Length)\n\t\nCalculate the velocity required to escape a body with mass `m` from distance `r`.\n\"\"\"\nescape_velocity(m::Unitful.Mass, r::Unitful.Length) = sqrt(2G * m / r) |> u\"km/s\"\n\n\"\"\"\n\thill_sphere(m_parent::Unitful.Mass, m::Unitful.Mass, sma::Unitful.Length, e = 0)\n\t\nCalculate the approximate Hill sphere radius at periapse of a body of mass `m` that orbits a body of mass `m_parent` at a distance of `sma` with orbital eccentricity `e`.\n\n``h_r = a(1-e)\\\\sqrt[3]{\\\\frac{m}{3M}}``\n\nwhere ``a`` is the semi-major axis, `m` is the mass of the smaller body and ``M`` is the mass of the central body.\n\"\"\"\nfunction hill_sphere(m_parent::Unitful.Mass, m::Unitful.Mass, sma::Unitful.Length, e = 0)\n\tsma * (1-e) * cbrt(m / 3m_parent) |> Unitful.unit(sma)\nend\n\n\"\"\"\n\tgravitational_binding_energy(m::Unitful.Mass, r::Unitful.Length)\n\t\nApproximate the gravitational binding energy of a body with mass `m` and radius `r`.\n\n``E_g = \\\\frac{3Gm^2}{5r}``\n\"\"\"\ngravitational_binding_energy(m::Unitful.Mass, r::Unitful.Length) = (3G*m^2) / 5r |>u\"J\"\n\n\"\"\"\n    roche_limit(r_primary::Unitful.Length, ρ_primary::Unitful.Density, ρ_satellite::Unitful.Density)\n   \nRigid body approximation of the Roche limit for a body with radius `r_primary` and density `ρ_primary`, approached by a body with density `ρ_satellite`.\n\n``r_r = r\\\\sqrt[2]{\\\\frac{2ρ_p}{ρ_s}}``\n\nwhere ``r`` and ``ρ_p`` are the radius and density of the central body, and ρ_s is the density of the orbiting body.\n\"\"\"\nroche_limit(r_primary::Unitful.Length, ρ_primary::Unitful.Density, ρ_satellite::Unitful.Density) = r_primary * cbrt(2ρ_primary / ρ_satellite) |> u\"km\"\n\n\"\"\"\n    gravity_tug_mass(force::Unitful.Force, separation::Unitful.Length, body_mass::Unitful.Mass)\n\t\nCompute the mass required to apply `force` to a body of mass `body_mass` given their barycenters are at a distance of `separated`.\n\"\"\"\ngravity_tug_mass(force::Unitful.Force, separation::Unitful.Length, body_mass::Unitful.Mass) = (force * separation^2)/(G * body_mass) |> u\"kg\"\n\n\"\"\"\n    barycentric_distance(m_1::Unitful.Mass, m_2::Unitful.Mass, a::Unitful.Length)\n\t\nCompute the distance from the barycenter of `m_1` to the barycenter of the `m_1`-`m_2` system, where the masses have an average separation of `a`.\n\"\"\"\nbarycentric_distance(m1::Unitful.Mass, m2::Unitful.Mass, a::Unitful.Length) = (a * m2) / (m1 + m2) |> u\"km\"\n\n\"\"\"\n    tidal_acceleration(body_radius::Unitful.Length, parent_mass::Unitful.Mass, separation::Unitful.Length)\n\t\nApproximate tidal acceleration felt by a body of radius `body_radius` at a distance of `separation` from a body of mass `parent_mass`.\n\nChanges in tidal acceleration are associated with effects like heating, etc.\n\n``a_t = \\frac{2GMr}{s^3}``\n\nwhere ``M`` is the mass of the central body, ``r`` is the radius of the body being affected and ``s`` is the distance between the two bodies.\n\"\"\"\ntidal_acceleration(body_radius::Unitful.Length, parent_mass::Unitful.Mass, separation::Unitful.Length) = 2body_radius * G * parent_mass / separation^3\n\nfunction radial_orbit_time(m1::Unitful.Mass, m2::Unitful.Mass, x0::Unitful.Length, v0::Unitful.Velocity, x::Unitful.Length)\n\tμ = G * (m1 + m2)\n\tw = 1/x0 - v0^2/2μ\n\t\n\treturn (asin(sqrt(w * x)) - sqrt(w * x * (1 - w * x))) / sqrt(2μ * w^3)\nend\n\nfunction radial_orbit_displacement(m1::Unitful.Mass, m2::Unitful.Mass, x0::Unitful.Length, v0::Unitful.Velocity, t::Unitful.Time)\n\tμ = G * (m1 + m2)\n\tw = 1/x0 - v0^2/2μ\n\tp = cbrt(9μ * t^2 / 2)\n\t\n\treturn p - w*p^2 / 5 - 3w^2 * p^3 / 175 - 23w^3 * p^4/7875 - 1894w^4 * p^5 / 3931875 - 3293w^5 * p^6 / 21896875 - 2418092w^6 * p^7/62077640625\nend\n\nfunction radial_orbit_displacement2(m1::Unitful.Mass, m2::Unitful.Mass, x0::Unitful.Length, v0::Unitful.Velocity, t::Unitful.Time)\n\tμ = G * (m1 + m2)\n\tw = 1/x0 - v0^2/2μ\n\tp = cbrt(9μ * t^2 / 2)\n\t\n\treturn p - w*p^2 / 5 - 3w^2 * p^3 / 175 - 23w^3 * p^4/7875 - 1894w^4 * p^5 / 3931875 - 3293w^5 * p^6 / 21896875 - 2418092w^6 * p^7/62077640625\nend\n\nfunction radial_orbit_displacement(m1::Real, m2::Real, x0::Real, v0::Real, t::Real)\n\tμ = ustrip(G) * (m1 + m2)\n\tw = 1/x0 - v0^2/2μ\n\tp = cbrt(9μ * t^2 / 2)\n\t\n\treturn p - w*p^2 / 5 - 3w^2 * p^3 / 175 - 23w^3 * p^4/7875 - 1894w^4 * p^5 / 3931875 - 3293w^5 * p^6 / 21896875 - 2418092w^6 * p^7/62077640625\nend\n\nend\n", "meta": {"hexsha": "b709c3e7476a77193cf8a485af7cd8c5687aaf66", "size": 10319, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gravity.jl", "max_stars_repo_name": "icantbelieveitsnotphysics/SfPhysics", "max_stars_repo_head_hexsha": "c2bfd4733335ccc0b5605aff61e73efde3bffdd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gravity.jl", "max_issues_repo_name": "icantbelieveitsnotphysics/SfPhysics", "max_issues_repo_head_hexsha": "c2bfd4733335ccc0b5605aff61e73efde3bffdd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-02-15T13:57:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-15T14:01:45.000Z", "max_forks_repo_path": "src/gravity.jl", "max_forks_repo_name": "icantbelieveitsnotphysics/SfPhysics", "max_forks_repo_head_hexsha": "c2bfd4733335ccc0b5605aff61e73efde3bffdd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2357414449, "max_line_length": 174, "alphanum_fraction": 0.7007461963, "num_tokens": 3424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350351, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7542001354941078}}
{"text": "# ## Data\n\nn = 9 \nk = 6;\n\n# ## Model\n\nusing Turing\n\n@model function globe_toss(n, k)\n    θ ~ Beta(1, 1)\n    k ~ Binomial(n, θ)\n    return k, θ\nend;\n\n# ## Output\n\nusing Random\n\nRandom.seed!(1)\nchains = sample(globe_toss(n, k), NUTS(0.65), 1000)\n\n# \\defaultoutput{}\n\n", "meta": {"hexsha": "44d5543164ae731918fe31cee9971a5a91405511", "size": 265, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/globe-tossing.jl", "max_stars_repo_name": "BobinMathew/TuringModels.jl", "max_stars_repo_head_hexsha": "a345fcfd427c4fb1f9479654f10f1280f1e4bf2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/globe-tossing.jl", "max_issues_repo_name": "BobinMathew/TuringModels.jl", "max_issues_repo_head_hexsha": "a345fcfd427c4fb1f9479654f10f1280f1e4bf2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/globe-tossing.jl", "max_forks_repo_name": "BobinMathew/TuringModels.jl", "max_forks_repo_head_hexsha": "a345fcfd427c4fb1f9479654f10f1280f1e4bf2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 10.6, "max_line_length": 51, "alphanum_fraction": 0.5811320755, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7542001349650627}}
{"text": "using LinearAlgebra\ninclude(\"findlocalmaxima.jl\")\n\nfunction MUSIC(Y,K,m::Int=0,f_steps=1000)\n    # Estimation of signal parameters via rotational invariance techniques\n    # (ESPRIT) algorithm for line spectral estimation from measurements.\n    # Can handle multiple snapshots by constructing a low rank Hankel matrix\n    # from the data.\n    #\n    # Inputs:\n    # Y: Data matrix\n    # K: number of sinusoids\n    # m: Hankel parameter of the Hankel matrix of the data\n    # f_steps: number of data points of the MUSIC pseudo spectrum\n    #\n    # Parameters:\n    # N = size(Y,1): number of measurements per snapshot\n    # L = size(Y,2): number of snapshots\n    #\n    # Output:\n    # f_hat: estimate of the frequencies of the K sinusoids in [rad]\n\n(N,L) = size(Y)\nf_range = range(0, 1, length=f_steps)\n\nif m == 0\nm = ceil(Int,N/2)\nend\n\nC = zeros(m,m)\nfor j = 1:L, i = m:N\n    C = C + Y[i-m+1:i,j]*Y[i-m+1:i,j]'/(L*N)\nend\n\n    evdC = eigen(C)\n    p = sortperm(real(evdC.values))[1:m-K]\n    Un = evdC.vectors[:,p]\n\n    a(f) = exp.(2*pi*1im*f*(0:m-1))\n    spec(f) = 1/norm(Un'*a(f))^2\n    Mspec = spec.(f_range)/maximum(spec.(f_range))\n    localmaxima = findlocalmaxima(Mspec)\n    q = localmaxima[sortperm(Mspec[localmaxima],rev=true)[1:min(K,length(localmaxima))]]\n    f_hat = f_range[q]\n    return f_hat #, Mspec\n\nend\n", "meta": {"hexsha": "e404a76cbbb0687c4b71ec64a26373dc030c638b", "size": 1315, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "algorithms/MUSIC.jl", "max_stars_repo_name": "THweinberger/specAna_matComp", "max_stars_repo_head_hexsha": "77612b94f74bf484bf39d65dd2834b38389eb695", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algorithms/MUSIC.jl", "max_issues_repo_name": "THweinberger/specAna_matComp", "max_issues_repo_head_hexsha": "77612b94f74bf484bf39d65dd2834b38389eb695", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algorithms/MUSIC.jl", "max_forks_repo_name": "THweinberger/specAna_matComp", "max_forks_repo_head_hexsha": "77612b94f74bf484bf39d65dd2834b38389eb695", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3958333333, "max_line_length": 88, "alphanum_fraction": 0.6410646388, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7542001222219701}}
{"text": "using DiffEqFlux, OrdinaryDiffEq, Flux, Optim, Plots\n\n# Condiciones iniciales del problema\nu0 = Float32[2.0; 0.0]\ndatasize = 30\ntspan = (0.0f0, 1.5f0)\ntsteps = range(tspan[1], tspan[2], length = datasize)\n\n# Se define y resuelve el problema con parámetros reales\nfunction trueODEfunc(du, u, p, t)\n    true_A = [-0.1 2.0; -2.0 -0.1]\n    du .= ((u.^3)'true_A)'\nend\n\nprob_trueode = ODEProblem(trueODEfunc, u0, tspan)\node_data = Array(solve(prob_trueode, Tsit5(), saveat = tsteps))\n\n# Se define una red neuronal de con dos capas densas/lineales.\n# a ésta se le agrega la asunción de que el sistema transforma \n# x hacia x^3. Esto como conocimiento previo que mejore el tiempo. \ndudt2 = FastChain((x, p) -> x.^3,\n                  FastDense(2, 50, tanh),\n                  FastDense(50, 2))\n\n# Se define el problema junto con su método de resolución y tiempo al cual parar.\nprob_neuralode = NeuralODE(dudt2, tspan, Tsit5(), saveat = tsteps)\n\n# Funciones que guardarán la predicción de la red neuronal y su valor de error.\nfunction predict_neuralode(p)\n  Array(prob_neuralode(u0, p))\nend\n\nfunction loss_neuralode(p)\n    pred = predict_neuralode(p)\n    loss = sum(abs2, ode_data .- pred)\n    return loss, pred\nend\n\n# Utilizado para graficar a tiempo real las predicciones realizadas.\ncallback = function (p, l, pred; doplot = true)\n  display(l)\n  # plot current prediction against data\n  plt = scatter(tsteps, ode_data[1,:], label = \"data\")\n  scatter!(plt, tsteps, pred[1,:], label = \"prediction\")\n  if doplot\n    display(plot(plt))\n  end\n  return false\nend\n\n# Se entrena la red neuronal utilizando la data de la resolución con parámetros reales.\n# Ésto se hace en dos pasos, primero con el optimizador ADAM para acercarnos rápidamente\n# al mínimo, y una vez cerca utilizamos Limited-memory BFGS para un ajuste más eficiente.\nresult_neuralode = DiffEqFlux.sciml_train(loss_neuralode, prob_neuralode.p,\n                                          ADAM(0.05), cb = callback,\n                                          maxiters = 300)\n\nresult_neuralode2 = DiffEqFlux.sciml_train(loss_neuralode,\n                                           result_neuralode.minimizer,\n                                           LBFGS(),\n                                           cb = callback,\n                                           allow_f_increases = false)\n\n", "meta": {"hexsha": "cc0cb7226821278120194538f86c273a404c9239", "size": 2334, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ejemplo_neural_ode.jl", "max_stars_repo_name": "anathompson/taller-julia-macaotech", "max_stars_repo_head_hexsha": "65dda6834ec7d617c63fdd46654941815e2d3f00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ejemplo_neural_ode.jl", "max_issues_repo_name": "anathompson/taller-julia-macaotech", "max_issues_repo_head_hexsha": "65dda6834ec7d617c63fdd46654941815e2d3f00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ejemplo_neural_ode.jl", "max_forks_repo_name": "anathompson/taller-julia-macaotech", "max_forks_repo_head_hexsha": "65dda6834ec7d617c63fdd46654941815e2d3f00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-10T15:40:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-10T15:40:08.000Z", "avg_line_length": 36.46875, "max_line_length": 89, "alphanum_fraction": 0.6422450728, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679977, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7541962836848805}}
{"text": "#=\n# The BUGS Book\n# Example 2.1.2, page 17:\n# For\n#   Y ~ Binomial(0.5, 8)\n# we want to know Pr(Y <= 2)\n#\n\n  See ~/jags/bugs_book_2_1_2.jags\n       Mean     SD Naive SE Time-series SE\n  P2 0.1442 0.3513 0.001434       0.001434\n  Y  4.0025 1.4177 0.005788       0.005839\n\n  ~/webppl/bugs_book_2_1_2.wppl\n\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n@model function bugs_book_2_1_2()\n\n    y ~ Binomial(8,0.5)\n    p2 ~ y <= 2 ? flip(1.0) : flip(0.0);\n\nend\n\n\nmodel = bugs_book_2_1_2()\n\nnum_chns = 4\n# chns = sample(model, Prior(), MCMCThreads(), 10_000, num_chns)\n\n# chns = sample(model, MH(), MCMCThreads(), 40_000, num_chns)\n\n# chns = sample(model, PG(15), MCMCThreads(), 10_000, num_chns)\n\n# chns = sample(model, SMC(1000), MCMCThreads(), 10_000, num_chns)\n\nchns = sample(model, IS(), MCMCThreads(), 10_000, num_chns)\n\ndisplay(chns)\n# display(plot(chns))\n\nshow_var_dist_pct(chns,:y)\nshow_var_dist_pct(chns,:p2)\n", "meta": {"hexsha": "99a0b4f1d4248894aa4d93495fcc70f6b644640a", "size": 932, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/bugs_book_2_1_2.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/bugs_book_2_1_2.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/bugs_book_2_1_2.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 19.829787234, "max_line_length": 66, "alphanum_fraction": 0.6566523605, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.75419626268024}}
{"text": "#    Problem : GROUP A\n#    *********\t \n#    A simple quartic function.\n#\n#    Origonal SIF Source: problem 157 (p. 87) in\n#    A.R. Buckley,\n#   \"Test functions for unconstrained minimization\",\n#    TR 1989CS-3, Mathematics, statistics and computing centre,\n#    Dalhousie University, Halifax (CDN), 1989.\n#\n#    QUARTC.SIF classification OUR2-AN-V-0\n#\n#    Number of variables is variable\n#\n# Daniel Henderson, 08/2021   \n\nf = x -> begin\n    return sum((x[i] - i)^4 for i in 1:lastindex(x))\t\nend\n\ng! = (g, x) -> begin\n\tfor i in 1:lastindex(x)\n\t\tg[i] = 4(x[i] - i)^3\n\tend\n    return g\nend\n\nfg! = (g, x) -> begin\n\tfx = 0.0\n\tfor i in 1:lastindex(x)\n\t\tfx  += (x[i] - i)^4\n\t\tg[i] = 4(x[i] - i)^3\n\tend\n    return fx, g\nend\n\ninit = (n::Int=5000) -> begin\n    return n, 2.0ones(n)\nend\n\nTestSet[\"QUARTC\"] = UncProgram(\"QUARTC\",  f, g!, fg!, init)", "meta": {"hexsha": "4bb6b948095bb52f022c5cc41f15ad4e1deb42ec", "size": 839, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/programs/QUARTC.jl", "max_stars_repo_name": "danphenderson/UncNLPrograms.jl", "max_stars_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/programs/QUARTC.jl", "max_issues_repo_name": "danphenderson/UncNLPrograms.jl", "max_issues_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/programs/QUARTC.jl", "max_forks_repo_name": "danphenderson/UncNLPrograms.jl", "max_forks_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4634146341, "max_line_length": 63, "alphanum_fraction": 0.5852205006, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661028358093, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7541391319827115}}
{"text": "using JuMP\nusing GLPKMathProgInterface\n\nmodel = Model(solver=GLPKSolverMIP())\n\n@variable(model, vials_of_panacea >= 0, Int)\n@variable(model, ampules_of_ichor >= 0, Int)\n@variable(model, bars_of_gold >= 0, Int)\n\n@objective(model, Max, 3000*vials_of_panacea + 1800*ampules_of_ichor + 2500*bars_of_gold)\n\n@constraint(model, 0.3*vials_of_panacea + 0.2*ampules_of_ichor + 2.0*bars_of_gold <= 25.0)\n@constraint(model, 0.025*vials_of_panacea + 0.015*ampules_of_ichor + 0.002*bars_of_gold <= 0.25)\n\nprintln(\"The optimization problem to be solved is:\")\nprintln(model)\n\nstatus = solve(model)\n\nprintln(\"Objective value: \", getobjectivevalue(model))\nprintln(\"vials of panacea = \", getvalue(vials_of_panacea))\nprintln(\"ampules of ichor = \", getvalue(ampules_of_ichor))\nprintln(\"bars of gold = \", getvalue(bars_of_gold))\n", "meta": {"hexsha": "30f9ab0168afca6a538b486b6c00d2f6aaab1591", "size": 807, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/knapsack-problem-unbounded.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/knapsack-problem-unbounded.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/knapsack-problem-unbounded.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.625, "max_line_length": 96, "alphanum_fraction": 0.7596034696, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660989095222, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7541391288788625}}
{"text": "function dlyap(A,Q)\n\n\t# Solving Discrete LYAPunov equation using Silvester equation\n\t#\n\t# Sylvester equation A*X + X*B + C = 0\n\t# if B = -(A')^(-1), C = Q*(A')^(-1) \n\t# => A*X - X*(A')^(-1) + Q*(A')^(-1) = 0 \n\t# => A*X*A' - X + Q = 0  -> Discrete Lyapunov equation\n\n\tAtinv = Array{Float64,2}(inv(A'))\n\tB = -Atinv\n\tC = Q*Atinv\n\tX = sylvester(A, B, C)\n\t\n\treturn X\n\t\nend\n\n", "meta": {"hexsha": "e5e50db7fe41dbe6c60c9b237eb20fcdb17904a0", "size": 369, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dlyap.jl", "max_stars_repo_name": "javiercara/emACQR.jl", "max_stars_repo_head_hexsha": "acd8be36d722a03e47ec8c49dc2f57bba500cfd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dlyap.jl", "max_issues_repo_name": "javiercara/emACQR.jl", "max_issues_repo_head_hexsha": "acd8be36d722a03e47ec8c49dc2f57bba500cfd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dlyap.jl", "max_forks_repo_name": "javiercara/emACQR.jl", "max_forks_repo_head_hexsha": "acd8be36d722a03e47ec8c49dc2f57bba500cfd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-05T03:32:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-05T03:32:32.000Z", "avg_line_length": 19.4210526316, "max_line_length": 62, "alphanum_fraction": 0.5338753388, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7541391254903203}}
{"text": "using DiscriminantAnalysis, Gadfly, Colors\n\n\n### Helper functions ###\n\nfunction rotationmatrix2D{T<:AbstractFloat}(θ::T)\n    T[cos(θ) -sin(θ);\n      sin(θ)  cos(θ)]\nend\n\n# Generates two normally distributed variables\nfunction boxmuller(n::Integer)\n    u1 = rand(n)\n    u2 = rand(n)\n    Z = Float64[(√(-2log(u1)) .* cos(2π*u2)) (√(-2log(u1)) .* sin(2π*u2))]\nend\n\n# Create the decision boundary using Contour.jl\nfunction boundary(model, xrange, yrange, is_quad::Bool = false)\n    Z = hcat(vec(Float64[x for x in xrange, y in yrange]), \n             vec(Float64[y for x in xrange, y in yrange]))\n    δ = DiscriminantAnalysis.discriminants(model, is_quad ? hcat(Z, Z.^2, Z[:,1] .* Z[:,2]) : Z)\n    Z = reshape(δ[:,1] - δ[:,2], length(xrange), length(yrange))\n    Contour.coordinates(Contour.lines(Contour.contour(xrange,yrange,Z,0.0))[1])\nend\n\nlimits(X::Matrix) = (minimum(X[:,1]), maximum(X[:,1]), minimum(X[:,2]), maximum(X[:,2]))\n\n\n### Sample Data ###\n\nn = 250\n\nZ1 = boxmuller(n)\nσ1 = [0.5 2.0]\nX1 = ((Z1 .* σ1) .- [0.0 4.25]) * rotationmatrix2D(π/4) \n\nZ2 = boxmuller(n)\nσ2 = [3.0 1.5]\nX2 = ((Z2 .* σ2) .+ [0.0 2.25]) * rotationmatrix2D(π/4)\n\nX = vcat(X1,X2)\ny = repeat([1,2], inner=[n])\n\nxmin, xmax, ymin, ymax = limits(X)\naspect = (ymax-ymin)/(xmax-xmin)\n\nm = 250  # Used for interpolating the decision boundary\nxrange = linspace(xmin,xmax,m)\nyrange = linspace(ymin,ymax,m)\n\n\n### LDA & QDA Plots ###\nfor (obj, desc, is_quad) in ((:lda, \"Linear Discriminant Analysis\", false), \n                             (:qda, \"Quadratic Discriminant Analyisis\", false),\n                             (:lda, \"Quadratic Linear Discriminant Analysis\", true))\n    @eval begin\n        model = ($obj)($is_quad ? hcat(X, X.^2, X[:,1] .* X[:,2]) : X, y)\n        cx, cy = boundary(model, xrange, yrange, $is_quad)\n\n        P = plot(\n                x = vec(X[:,1]), \n                y = vec(X[:,2]),\n                color = map(class -> \"Class $class\", y), \n                Geom.point,\n                Scale.color_discrete_manual(colorant\"red\",colorant\"blue\"),\n                Guide.XLabel(\"X Variable\"),\n                Guide.YLabel(\"Y Variable\"),\n                Guide.title($desc),\n                Guide.colorkey(\"\"),\n                Coord.Cartesian(xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax)\n            )\n        L = layer(x=cx, y=cy, Geom.line(preserve_order=true),\n                  Theme(default_color=colorant\"black\", line_width=.4mm))\n        unshift!(P.layers,L[1])\n\n        draw(PNG(($is_quad ? \"q\" : \"\") * $(string(obj)) * \".png\", 6inch, (6*aspect)inch), P)\n    end\nend\n\n\n### CDA Plot ###\n\nmodel = cda(X, y)\nC = vec(X * model.W)\n\nP = plot(\n    x = C, \n    color = map(class -> \"Class $class\", y), \n    Geom.histogram(bincount=100),\n    Scale.color_discrete_manual(colorant\"red\",colorant\"blue\"),\n    Guide.XLabel(\"Canonical Coordinate\"),\n    Guide.YLabel(\"Count\"),\n    Guide.title(\"Canonical Discriminant Analysis\"),\n    Guide.colorkey(\"\"),\n    Coord.Cartesian(xmin=minimum(C), xmax=maximum(C))\n)\n\ndraw(PNG(\"cda.png\", 6inch, 4inch), P)\n", "meta": {"hexsha": "8dbf71e41197462e17224113b7d3021aa4d3785d", "size": 3027, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/visualization.jl", "max_stars_repo_name": "JuliaPackageMirrors/DiscriminantAnalysis.jl", "max_stars_repo_head_hexsha": "ac816d77149de3447048dd7720f1de6ca19c78e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/visualization.jl", "max_issues_repo_name": "JuliaPackageMirrors/DiscriminantAnalysis.jl", "max_issues_repo_head_hexsha": "ac816d77149de3447048dd7720f1de6ca19c78e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/visualization.jl", "max_forks_repo_name": "JuliaPackageMirrors/DiscriminantAnalysis.jl", "max_forks_repo_head_hexsha": "ac816d77149de3447048dd7720f1de6ca19c78e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.27, "max_line_length": 96, "alphanum_fraction": 0.5702015197, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7541167955981636}}
{"text": "using SpecialFunctions, Nemo, StatsFuns, Memoization\nimport Nemo.binom, Nemo.gamma\n\n\"Session-wide precision\"\nconst prec = 5000 ## Increase for better precision\n\n\"Converter from real to arbitrary precision real (Arb)\"\nconst RR = RealField(prec)\n\n\"Converter from real to arbitrary precision complex (Acb)\"\nconst CC = ComplexField(prec)\n\nbinom(n::Int64, k::Int64, r::Nemo.ArbField) = binom(convert(UInt64, n),convert(UInt64, k), r)\n\n# Making sure the factorial function uses the Nemo version of the gamma and returns an Arb\ngamma(x::Int64) = Nemo.gamma(RR(x))\n\n# Useful typed constants\n\"1 with required arbitrary precision\"\nconst arb_1 = RR(1)\n\"0 with required arbitrary precision\"\nconst arb_0 = RR(0)\n\n\"\"\"\n  unsigned_Stirling1(n::Integer, k::Integer)\n\nComputation of unsigned Stirling numbers of the first kind, using Memoization and a recursive formula.\n\n# Examples\n```julia-repl\njulia> GibbsTypePriors.unsigned_Stirling1(10, 5)\n269325\n```\n\"\"\"\n@memoize function unsigned_Stirling1(n::Integer, k::Integer)\n  # special cases\n  if k<0 || n<0\n    throw(DomainError())\n  end\n  if k>n\n    return big(0)\n  end\n  if n==0  # and, by logic, k==0\n    return big(1)\n  end\n  if k==0  # and, by logic, n>0\n    return big(0)\n  end\n  # end of special cases, invoke recursion\n  return unsigned_Stirling1(n-1,k-1) + (n-1)*unsigned_Stirling1(n-1,k)\nend\n\n\n\n@memoize function unsigned_Stirling2(n::Integer,k::Integer)\n  # special cases\n  if k<0 || n<0\n    throw(DomainError())\n  end\n  if k>n\n    return big(0)\n  end\n  if n==0  # and, by logic, k==0\n    return big(1)\n  end\n  if k==0  # and, by logic, n>0\n    return big(0)\n  end\n  # end of special cases, invoke recursion\n  return  (k)*unsigned_Stirling2(n-1,k) + unsigned_Stirling2(n-1,k-1)\nend\n\n\"\"\"\n  has_reasonable_precision(arb_num)\n\nCheck whether arb_num has at least roughly the double precision (maybe replace by 64 by 53).\n\n# Examples\n```julia-repl\njulia> GibbsTypePriors.Cnk_rec(6, 5, 0.5)\n0.234375\n```\n\"\"\"\nfunction has_reasonable_precision(arb_num)\n    return accuracy_bits(arb_num) ≥ 53\nend\n\nimport Nemo.risingfac\n\"\"\"\n  risingfac(r, n)\n\nComputes the rising factorial.\n\n# Examples\n```julia-repl\njulia> GibbsTypePriors.Cnk_rec(6, 5, 0.5)\n0.234375\n```\n\"\"\"\nfunction risingfac(r, n)\n  if r == 0\n    return 0\n  else\n    return prod(r + i for i in 0:(n-1))\n  end\nend\nfunction risingfac(r::arb, n)\n  if r == 0\n    return arb_0\n  else\n    return prod(r + i for i in 0:(n-1))\n  end\nend\n", "meta": {"hexsha": "0ff484272c4465017d6f883503565d7d97b541c6", "size": 2415, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/common_functions.jl", "max_stars_repo_name": "konkam/GibbsTypePriors", "max_stars_repo_head_hexsha": "f923ed8a365261c34f4749b75005764279e63c94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-27T16:49:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-27T16:49:28.000Z", "max_issues_repo_path": "src/common_functions.jl", "max_issues_repo_name": "konkam/GibbsTypePriors", "max_issues_repo_head_hexsha": "f923ed8a365261c34f4749b75005764279e63c94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common_functions.jl", "max_forks_repo_name": "konkam/GibbsTypePriors", "max_forks_repo_head_hexsha": "f923ed8a365261c34f4749b75005764279e63c94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-13T16:45:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T16:45:47.000Z", "avg_line_length": 21.1842105263, "max_line_length": 102, "alphanum_fraction": 0.6944099379, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7541167887797408}}
{"text": "#-------------------------------------------------------------------------------\n#conversions between spectral units\n\nexport ν2f, f2ν, ν2λ, λ2ν, λ2f, f2λ\n\n\"\"\"\nConvert wavenumber [cm``^{-1}``] to frequency [1/s]\n\"\"\"\nν2f(ν) = 100.0*𝐜*ν\n\n\"\"\"\nConvert frequency [1/s] to wavenumber [cm``^{-1}``]\n\"\"\"\nf2ν(f) = f/(100.0*𝐜)\n\n\"\"\"\nConvert wavenumber [cm``^{-1}``] to wavelength [m]\n\"\"\"\nν2λ(ν) = 0.01/ν\n\n\"\"\"\nConvert wavelength [m] to wavenumber [cm``^{-1}``]\n\"\"\"\nλ2ν(λ) = 0.01/λ\n\n\"\"\"\nConvert wavelength [m] to frequency [1/s]\n\"\"\"\nλ2f(λ) = 𝐜/λ\n\n\"\"\"\nConvert frequency [1/s] to wavelength [m]\n\"\"\"\nf2λ(f) = f/𝐜\n\n#-------------------------------------------------------------------------------\nexport planck, normplanck, dplanck, stefanboltzmann, equilibriumtemperature\n\n\"\"\"\n    planck(ν, T)\n\nCompute black body intensity [W/m``^2``/cm``^{-1}``/sr] using [Planck's law](https://en.wikipedia.org/wiki/Planck%27s_law)\n\n# Arguments\n* `ν`: wavenumger [cm``^{-1}``]\n* `T`: temperature [Kelvin]\n\"\"\"\nfunction planck(ν, T)\n    νₘ = 100.0*ν #convert from cm^-1 to m^-1\n    x = 𝐡*𝐜*νₘ/(𝐤*T) #exponent\n    p = 2*𝐡*𝐜^2*νₘ^3 #prefactor\n    #result, converting back to cm^-1 with the factor of 100\n    100.0*p/(exp(x) - 1.0)\nend\n\n\"\"\"\n    normplanck(ν, T)\n\nCompute black body intensity [W/m``^2``/cm``^{-1}``/sr] using [Planck's law](https://en.wikipedia.org/wiki/Planck%27s_law), normalized by the power emitted per unit area at the given temperature ([`stefanboltzmann`](@ref)),\n\n```\nB(ν,T)/σT^4\n```\n\nyielding units of 1/cm``^{-1}``/sr.\n\n# Arguments\n* `ν`: wavenumger [cm``^{-1}``]\n* `T`: temperature [Kelvin]\n\"\"\"\nnormplanck(ν, T) = planck(ν, T)/stefanboltzmann(T)\n\n\"\"\"\n    dplanck(ν, T)\n\nEvaluates ``\\\\frac{\\\\partial B}{\\\\partial T}``\n\"\"\"\nfunction dplanck(ν, T)\n    νₘ = 100.0*ν #convert from cm^-1 to m^-1\n    x = 𝐡*𝐜*νₘ/(𝐤*T) #exponent\n    y = exp(x)\n    if isinf(y)\n        return zero(y) #fail accurately, Inf/(Inf - 1)^2 → 0\n    end\n    p = 2*𝐡^2*𝐜^3*νₘ^4/(𝐤*T^2) #prefactor\n    #result, converting back to cm^-1 with the factor of 100\n    100.0*p*y/(y - 1)^2\nend\n\n\"\"\"\n    stefanboltzmann(T)\n\nCompute black body radiation power using the [Stefan-Boltzmann](https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law) law, ``σT^4`` [W/m``^2``].\n\"\"\"\nstefanboltzmann(T) = 𝛔*(T^4)\n\n\"\"\"\n    equilibriumtemperature(F, A)\n\nCompute the [planetary equilibrium temperature](https://en.wikipedia.org/wiki/Planetary_equilibrium_temperature), or equivalent blackbody temperature of a planet.\n\n``(\\\\frac{(1 - A)F}{4\\\\sigma})^{1/4}``\n\n# Arguments\n* `F`: stellar flux [W/m``^2``]\n* `A`: albedo\n\"\"\"\nequilibriumtemperature(F, A) = ((1 - A)*F/(4*𝛔))^(1/4)\n\n\"\"\"\n    equilibriumtemperature(L, A, R)\n\nCompute the [planetary equilibrium temperature](https://en.wikipedia.org/wiki/Planetary_equilibrium_temperature), or equivalent blackbody temperature of a planet.\n\n``(\\\\frac{(1 - A)L}{16 \\\\sigma \\\\pi R^2})^{1/4}``\n\n# Arguments\n* `L`: stellar luminosity [W]\n* `A`: albedo\n* `R`: orbital distance [m]\n\"\"\"\nequilibriumtemperature(L, A, R) = (L*(1 - A)/(16*𝛔*π*R^2))^(1/4)\n\n#-------------------------------------------------------------------------------\nexport dτdP, transmittance, schwarzschild, absorption, emission\n\n\"\"\"\n    dτdP(σ, g, μ)\n\nEvaluate the differential increase in optical depth in pressure coordinates, equivalent to the [`schwarzschild`](@ref) equation without Planck emission.\n\n``\\\\frac{dτ}{dP} = σ\\\\frac{\\\\textrm{N}_A}{g μ}``\n\nwhere ``N_A`` is Avogadro's number.\n\n# Arguments\n* `σ`: absorption cross-section [cm``^2``/molecule]\n* `g`: gravitational acceleration [m/s``^2``]\n* `μ`: mean molar mass [kg/mole]\n\"\"\"\ndτdP(σ, g, μ) = 1e-4*σ*𝐍𝐚/(μ*g)\n\n\"\"\"\n    transmittance(τ)\n\nEvaluate transmittance from optical depth, ``t = e^{-τ}``\n\"\"\"\ntransmittance(τ) = exp(-τ)\n\n\"\"\"\n    schwarzschild(I, ν, σ, T, P)\n\nEvaluate the [Schwarzschild differential equation](https://en.wikipedia.org/wiki/Schwarzschild%27s_equation_for_radiative_transfer) for radiative transfer with units of length/height [m] and assuming the ideal gas law.\n\n``\\\\frac{dI}{dz} = σ\\\\frac{P}{k_B T}[B_ν(T) - I]``\n\nwhere ``B_ν`` is [`planck`](@ref)'s law.\n\n# Arguments\n* `I`: radiative intensity [W/m``^2``/cm``^{-1}``/sr]\n* `ν`: radiation wavenumber [cm``^{-1}``]\n* `σ`: absorption cross-section [cm``^2``/molecule]\n* `T`: temperature [K]\n* `P`: pressure [Pa]\n\"\"\"\nschwarzschild(I, ν, σ, T, P) = 1e-4*σ*(P/(𝐤*T))*(planck(ν,T) - I)\n\n\"\"\"\n    schwarzschild(I, ν, σ, g, μ, T)\n\nEvaluate the [Schwarzschild differential equation](https://en.wikipedia.org/wiki/Schwarzschild%27s_equation_for_radiative_transfer) for radiative transfer with pressure units [Pa] and assuming the ideal gas law.\n\n``\\\\frac{dI}{dP} = σ\\\\frac{\\\\textrm{N}_A}{g μ}[B_ν(T) - I]``\n\nwhere ``B_ν`` is [`planck`](@ref)'s law and ``N_A`` is Avogadro's number.\n\n# Arguments\n* `I`: radiative intensity [W/m``^2``/cm``^{-1}``/sr]\n* `ν`: radiation wavenumber [cm``^{-1}``]\n* `σ`: absorption cross-section [cm``^2``/molecule]\n* `g`: gravitational acceleration [m/s``^2``]\n* `μ`: mean molar mass [kg/mole]\n* `T`: temperature [K]\n\"\"\"\nschwarzschild(I, ν, σ, g, μ, T) = 1e-4*σ*(𝐍𝐚/(μ*g))*(planck(ν,T) - I)\n\n\"\"\"\n    absorption(I, σ, g, μ)\n\nEvaluate the [Schwarzschild differential equation](https://en.wikipedia.org/wiki/Schwarzschild%27s_equation_for_radiative_transfer) for radiative transfer with pressure units [Pa] and assuming the ideal gas law, but **without Planck emission**. This can be useful if the wavenumber is far away from the emission region of the temperature and the Planck emission is known to be negligible.\n\n``\\\\frac{dI}{dP} = -σ\\\\frac{\\\\textrm{N}_A}{g μ}I``\n\nwhere ``N_A`` is Avogadro's number.\n\n# Arguments\n* `I`: radiative intensity [W/m``^2``/cm``^{-1}``/sr]\n* `σ`: absorption cross-section [cm``^2``/molecule]\n* `g`: gravitational acceleration [m/s``^2``]\n* `μ`: mean molar mass [kg/mole]\n\"\"\"\nabsorption(I, σ, g, μ) = -1e-4*σ*(𝐍𝐚/(μ*g))*I\n\n\"\"\"\n    emission(I, ν, σ, g, μ, T)\n\nEvaluate the [Schwarzschild differential equation](https://en.wikipedia.org/wiki/Schwarzschild%27s_equation_for_radiative_transfer) for radiative transfer with pressure units [Pa] and assuming the ideal gas law, but **without Planck emission**. This can be useful if the wavenumber is far away from the emission region of the temperature and the Planck emission is known to be negligible.\n\n``\\\\frac{dI}{dP} = -σ\\\\frac{\\\\textrm{N}_A}{g μ}B_ν(T)``\n\nwhere ``B_ν`` is [`planck`](@ref)'s law\n\n# Arguments\n* `I`: radiative intensity [W/m``^2``/cm``^{-1}``/sr]\n* `σ`: absorption cross-section [cm``^2``/molecule]\n* `g`: gravitational acceleration [m/s``^2``]\n* `μ`: mean molar mass [kg/mole]\n\"\"\"\nemission(ν, σ, g, μ, T) = 1e-4*σ*(𝐍𝐚/(μ*g))*planck(ν,T)\n\n", "meta": {"hexsha": "bec575d8978bd66978c2223d4932cc387721b316", "size": 6627, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/radiation.jl", "max_stars_repo_name": "markmbaum/ClearSky.jl", "max_stars_repo_head_hexsha": "84e8aec24a648dd7ebbef4c8d1f743bb2669a47d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-31T18:12:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T18:12:56.000Z", "max_issues_repo_path": "src/radiation.jl", "max_issues_repo_name": "wordsworthgroup/ClearSky.jl", "max_issues_repo_head_hexsha": "84e8aec24a648dd7ebbef4c8d1f743bb2669a47d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-23T20:42:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-23T20:42:44.000Z", "max_forks_repo_path": "src/radiation.jl", "max_forks_repo_name": "wordsworthgroup/ClearSky.jl", "max_forks_repo_head_hexsha": "84e8aec24a648dd7ebbef4c8d1f743bb2669a47d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9864253394, "max_line_length": 388, "alphanum_fraction": 0.6210955183, "num_tokens": 2322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7541167840910072}}
{"text": "using DataFrames\nusing Distributions\nusing StatsPlots\n\n\nfunction sir(beta,gamma,N,S0,I0,R0,tf)\n    t = 0\n    S = S0\n    I = I0\n    R = R0\n    ta=DataArray(Float64,0)\n    Sa=DataArray(Float64,0)\n    Ia=DataArray(Float64,0)\n    Ra=DataArray(Float64,0)\n    while t < tf\n        push!(ta,t)\n        push!(Sa,S)\n        push!(Ia,I)\n        push!(Ra,R)\n        pf1 = beta*S*I\n        pf2 = gamma*I\n        pf = pf1+pf2\n        dt = rand(Exponential(1/pf))\n        t = t+dt\n        if t>tf\n            break\n        end\n        ru = rand()\n        if ru<(pf1/pf)\n            S=S-1\n            I=I+1\n        else\n            I=I-1\n            R=R+1\n        end\n    end\n    results = DataFrame()\n    results[:time] = ta\n    results[:S] = Sa\n    results[:I] = Ia\n    results[:R] = Ra\n    return(results)\nend\n\nsrand(42)\n\nsir_out = sir(0.1/1000,0.05,1000,999,1,0,200);\n\nhead(sir_out)\n\n# Plot\n@df sir_out plot(:time, [:S :I :R], xlabel=\"Time\",ylabel=\"Number\")\n", "meta": {"hexsha": "ade5571ca08be9e219315f4e2ff861bb950cad8b", "size": 947, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/simple_stochastic_models/continuous_t_sir/ssir.jl", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/simple_stochastic_models/continuous_t_sir/ssir.jl", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/simple_stochastic_models/continuous_t_sir/ssir.jl", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 17.8679245283, "max_line_length": 66, "alphanum_fraction": 0.4963041183, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857379, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.754106259045439}}
{"text": "\"\"\"\n    LogTransform <: Transform\n\nLogarithmically transform the data through: sign(x) * log(|x| + 1).\n\nThis allows transformations of all real numbers, not just positive ones.\n\"\"\"\nstruct LogTransform <: Transform end\ncardinality(::LogTransform) = OneToOne()\n\n_logtransform(x) = sign(x) * log(abs(x) + one(x))\n_invlogtransform(x) = sign(x) * (exp(sign(x) * x) - one(x))\n\nfunction _apply(A::AbstractArray, transform::LogTransform; inverse=false, kwargs...)\n    inverse && return _invlogtransform.(A)\n    return _logtransform.(A)\nend\n\n\n\"\"\"\n    InverseHyperbolicSine <: Transform\n\nLogarithmically transform the data through: log(x + √(x² + 1)).\n\nThis is the inverse hyperbolic sine. \n\"\"\"\nstruct InverseHyperbolicSine <: Transform end\ncardinality(::InverseHyperbolicSine) = OneToOne()\n\nfunction _apply(A::AbstractArray, transform::InverseHyperbolicSine; inverse=false, kwargs...)\n    inverse && return sinh.(A)\n    return asinh.(A)\nend      ", "meta": {"hexsha": "323b24e2d7406803236a9e7b2818aa7a2b66c45e", "size": 937, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/log.jl", "max_stars_repo_name": "invenia/FeatureTransforms.jl", "max_stars_repo_head_hexsha": "1c86cbdbaa2431e5275774d0f3374bfa7481e1cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2021-04-07T19:51:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T15:29:13.000Z", "max_issues_repo_path": "src/log.jl", "max_issues_repo_name": "invenia/FeatureTransforms.jl", "max_issues_repo_head_hexsha": "1c86cbdbaa2431e5275774d0f3374bfa7481e1cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 75, "max_issues_repo_issues_event_min_datetime": "2021-02-25T20:01:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T13:24:23.000Z", "max_forks_repo_path": "src/log.jl", "max_forks_repo_name": "invenia/FeatureTransforms.jl", "max_forks_repo_head_hexsha": "1c86cbdbaa2431e5275774d0f3374bfa7481e1cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3939393939, "max_line_length": 93, "alphanum_fraction": 0.7129135539, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7541062569623631}}
{"text": "nprocs()==1 && addprocs()\n\n@everywhere logis(x) = 1 ./ (1 .+ exp(-x))\n@everywhere dlogis(x) = logis(x) .* (1 .- logis(x))\n\n@everywhere function initParams(x,y,n_hidden,max_iter)\n    w1 = randn(n_hidden,size(x,1))\n    w2 = randn(n_hidden,n_hidden)\n    w3 = randn(size(y,1),n_hidden)  \n    B1 = rand(n_hidden,1)\n    B2 = rand(n_hidden,1)      \n    errors = zeros(max_iter)\n    outputs = zeros(size(y,2),max_iter)\n    return (w1,w2,w3,errors,outputs,B1,B2)\nend\n\n@everywhere function ffward(x,y,w1,w2,w3)\n    a1 = w1 * x\n    h1 = logis(a1)\n    a2 = w2 * h1\n    h2 = logis(a2)\n    ay = w3 * h2\n    yhat = logis(ay)\n    err = yhat - y\n    return(a1,h1,a2,h2,ay,yhat,err)\nend\n\n@everywhere function updateW!(w1,w2,w3,x,h1,h2,δa1,δa2,err;lr=1)\n    w1 .-= δa1 * x' .* lr\n    w2 .-= δa2 * h1' .* lr\n    w3 .-= err * h2' .* lr\nend\n\n@everywhere function bp(x,y,n_hidden,max_iter)\n    (w1,w2,w3,errors,outputs,_,_)=initParams(x,y,n_hidden,max_iter)\n    for i = 1:max_iter   \n        (a1,h1,a2,h2,ay,yhat,err) = ffward(x,y,w1,w2,w3)\n        δa2 = (w3' * err) .* dlogis(a2)\n        δa1 = (w2' * δa2) .* dlogis(a1)\n        updateW!(w1,w2,w3,x,h1,h2,δa1,δa2,err)\n        errors[i] = sum(abs(err))\n        outputs[:,i] = yhat\n    end\n    return (outputs,errors)\nend\n\n@everywhere function fa(x,y,n_hidden,max_iter)\n    (w1,w2,w3,errors,outputs,B1,B2)=initParams(x,y,n_hidden,max_iter)\n    for i = 1:max_iter    \n        (a1,h1,a2,h2,ay,yhat,err) = ffward(x,y,w1,w2,w3)\n        δa2 = (B2.*err) .* dlogis(a2) \n        δa1 = (B1.*δa2) .* dlogis(a1) \n        updateW!(w1,w2,w3,x,h1,h2,δa1,δa2,err)\n        errors[i] = sum(abs(err))\n        outputs[:,i] = yhat\n    end\n    return (outputs,errors)\nend\n\n@everywhere function dfa(x,y,n_hidden,max_iter)\n    (w1,w2,w3,errors,outputs,B1,B2)=initParams(x,y,n_hidden,max_iter)\n    for i = 1:max_iter    \n        (a1,h1,a2,h2,ay,yhat,err) = ffward(x,y,w1,w2,w3)\n        δa2 = (B2.*err) .* dlogis(a2) \n        δa1 = (B1.*err) .* dlogis(a1) \n        updateW!(w1,w2,w3,x,h1,h2,δa1,δa2,err)\n        errors[i] = sum(abs(err))\n        outputs[:,i] = yhat\n    end\n    return (outputs,errors)\nend\n\n@everywhere function ifa(x,y,n_hidden,max_iter)\n    (w1,w2,w3,errors,outputs,B1,_)=initParams(x,y,n_hidden,max_iter)\n    for i = 1:max_iter    \n        (a1,h1,a2,h2,ay,yhat,err) = ffward(x,y,w1,w2,w3)\n        δa1 = (B1.*err) .* dlogis(a1) \n        δa2 = (w2 * δa1) .* dlogis(a2) \n        updateW!(w1,w2,w3,x,h1,h2,δa1,δa2,err)\n        errors[i] = sum(abs(err))\n        outputs[:,i] = yhat\n    end\n    return (outputs,errors)\nend\n\n# Example: XOR problem\n\nx = [1 1 ; 0 1 ; 1 0 ; 0 0]'\ny = [0 1 1 0]\nn_hidden = 15; # Number of hidden units\nmax_iter = 500; #Number of learning steps\ntrials = 30;\n\ndfa_err=@parallel (hcat) for _=1:trials\n    (_,dfa_errors) = dfa(x,y,n_hidden,max_iter)\n    dfa_errors\nend\n(dfa_yhat,_) = dfa(x,y,n_hidden,max_iter)\n\nbp_err = @parallel (hcat) for _=1:trials\n    (_,bp_errors) = bp(x,y,n_hidden,max_iter)\n    bp_errors\nend\n(bp_yhat,_) = bp(x,y,n_hidden,max_iter)\n\nifa_err=@parallel (hcat) for _=1:trials\n    (_,ifa_errors) = ifa(x,y,n_hidden,max_iter)\n    ifa_errors\nend\n(ifa_yhat,_) = ifa(x,y,n_hidden,max_iter);\n\nfa_err=@parallel (hcat) for _=1:trials\n    (_,fa_errors) = fa(x,y,n_hidden,max_iter)\n    fa_errors\nend\n(fa_yhat,_) = fa(x,y,n_hidden,max_iter);\n\nusing Plots\nl = @layout [\n    a b\n    c d\n    e f\n]\ngr()\np1=plot(dfa_yhat',label=[\"1,1\" \"0,1\" \"1,0\" \"0,0\"],title=\"DFA\")\np2=plot(ifa_yhat',label=[\"1,1\" \"0,1\" \"1,0\" \"0,0\"],title=\"IFA\")\np3=plot(fa_yhat',label=[\"1,1\" \"0,1\" \"1,0\" \"0,0\"],title=\"FA\")\np4=plot(bp_yhat',label=[\"1,1\" \"0,1\" \"1,0\" \"0,0\"],title=\"BP\")\np5=plot([dfa_err[:,1] ifa_err[:,1] fa_err[:,1] bp_err[:,1]],label=[\"DFA\" \"IFA\" \"FA\" \"BP\"],title=\"First Trial Error\")\np6=plot([mean(dfa_err,2) mean(ifa_err,2) mean(fa_err,2) mean(bp_err,2)],label=[\"DFA\" \"IFA\" \"FA\" \"BP\"],title=\"Mean Trials Error\")\nplot(p1,p2,p3,p4,p5,p6,size=(900,900),layout=l)\n", "meta": {"hexsha": "c2ee8c809da0a1b68aaab609dfab7ba538ac828b", "size": 3891, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dfa.jl", "max_stars_repo_name": "ppalmes/DFA.jl", "max_stars_repo_head_hexsha": "bf4145e80a6533c0dbc6f033e4622155ca699b5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-03-01T19:58:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T18:27:41.000Z", "max_issues_repo_path": "dfa.jl", "max_issues_repo_name": "ppalmes/DFA.jl", "max_issues_repo_head_hexsha": "bf4145e80a6533c0dbc6f033e4622155ca699b5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dfa.jl", "max_forks_repo_name": "ppalmes/DFA.jl", "max_forks_repo_head_hexsha": "bf4145e80a6533c0dbc6f033e4622155ca699b5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-03-04T11:31:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T09:16:37.000Z", "avg_line_length": 29.4772727273, "max_line_length": 128, "alphanum_fraction": 0.5944487278, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.754106256962363}}
{"text": "export proxL1!, proxL1, normL1\n\n\"\"\"\n    proxL1!(x::Array{T}, λ::Float64; sparseTrafo::Trafo=nothing, kargs...) where T\n\nperforms soft-thresholding - i.e. proximal map for the Lasso problem.\n\n# Arguments:\n* `x::Array{T}`                 - Vector to apply proximal map to\n* `λ::Float64`                  - regularization paramter\n* `sparseTrafo::Trafo=nothing`  - sparsifying transform to apply\n\"\"\"\nfunction proxL1!(x::AbstractArray{Tc}, λ::T; sparseTrafo::Trafo=nothing, kargs...) where {T, Tc <: Union{T, Complex{T}}}\n  ε = eps(T)\n\n  if sparseTrafo != nothing\n    z = sparseTrafo*x\n    z .= max.((abs.(z).-λ),0) .* (z.+ε)./(abs.(z).+ε)\n    x .= adjoint(sparseTrafo)*z\n  else\n    x .= max.((abs.(x).-λ),0) .* (x.+ε)./(abs.(x).+ε)\n  end\n\n  return x\nend\n\n\"\"\"\n    normL1(x::Array{T}, λ::Float64; sparseTrafo::Trafo=nothing, kargs...) where T\n\nreturns the value of the L1-regularization term.\nArguments are the same as in `proxL1!`\n\"\"\"\nfunction normL1(x::T, λ::Float64; sparseTrafo::Trafo=nothing, kargs...) where T<:AbstractArray\n  if sparseTrafo != nothing\n    l1Norm = λ*norm(sparseTrafo*x,1)\n  else\n    l1Norm = λ*norm(x,1)\n  end\n  return l1Norm\nend\n", "meta": {"hexsha": "1b591c84f49dd0f4815c34928d4de4c41e97e5b9", "size": 1149, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/proximalMaps/ProxL1.jl", "max_stars_repo_name": "alexjaffray/RegularizedLeastSquares.jl", "max_stars_repo_head_hexsha": "2a8fcba5cc270c5683415efa2d2190bb39f19424", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/proximalMaps/ProxL1.jl", "max_issues_repo_name": "alexjaffray/RegularizedLeastSquares.jl", "max_issues_repo_head_hexsha": "2a8fcba5cc270c5683415efa2d2190bb39f19424", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/proximalMaps/ProxL1.jl", "max_forks_repo_name": "alexjaffray/RegularizedLeastSquares.jl", "max_forks_repo_head_hexsha": "2a8fcba5cc270c5683415efa2d2190bb39f19424", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0243902439, "max_line_length": 120, "alphanum_fraction": 0.6275021758, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7541062512699966}}
{"text": "export findβ, microcanonical_ensemble, canonical_ensemble\n\n# stupid implementation of softmax - vals should be regularized beforehand\nfunction _softmax(vals)\n    w = exp.(vals)\n    w ./= sum(w)\nend\n\n\"\"\"\n    _weights_canonical(β, evals)\nCompute the distribution of eigenstates with given energies at temperature 1/β.\nP(E) ∝ ∑ᵢexp(-β Eᵢ)\n\nEnergy values are assumed to be sorted!\n\"\"\"\nfunction _weights_canonical(evals, β)\n    # assume sorted evals!\n    regulator = β < 0 ? evals[end] : evals[1]\n    _softmax(@. -β * (evals - regulator))\nend\n\n_ΔE(evals, E_0, β) = abs((evals ⋅ _weights_canonical(evals, β)) - E_0)\n\n# TODO: How to optimize best? The function is pretty well behaved...\n\"\"\"\n    findβ(evals, E₀; β_0=0)\nCompute the inverse temperature β s. t. the thermal expectation value of the energy matches E₀.\n\"\"\"\nfindβ(evals, E_0; β_0 = 0) = Optim.optimize(β -> _ΔE(evals, E_0, β[1]), [float(β_0)], Optim.Newton(linesearch = LineSearches.HagerZhang())).minimizer[1]\n\n\"\"\"\n    canonical_ensemble(evals, E₀; β₀ = 0)\nCompute the weights of the state assuming a canonical ensemble of temperature 1/β. β₀ is taken as starting value for the computation.\nA state is assigned the weight ∝ exp(-β Eᵢ)\n\nEnergy values are assumed to be sorted!\n\"\"\"\ncanonical_ensemble(evals, E_0; β_0 = 0) = _weights_canonical(evals, findβ(evals, E_0; β_0))\n\n\n\"\"\"\n    microcanonical_ensemble(evals, E₀[, ΔE])\nCompute the weights of the state assuming a microcanonical ensemble. Default size of the window is 0.5% of the spectral width.\nA state is in the ensemble if |Eᵢ-E_0| < ΔE.\nIf the ensemble would be empty, choose the closest state (in energy).\n\nEnergy values are assumed to be sorted!\n\"\"\"\nfunction microcanonical_ensemble(evals, E_0, ΔE)::Vector{Float64}\n    micro = @. (evals < E_0+ΔE) & (evals > E_0-ΔE)\n    s = sum(micro)\n    if s > 0\n        # enforce float conversion for type stability\n        micro ./ float(s)\n    else\n        micro = zeros(Float64, length(micro))\n        smaller = searchsortedlast(evals, E_0)\n        ind = abs(evals[smaller]-E_0) < abs(evals[smaller+1]-E_0) ? smaller : smaller+1\n        micro[ind] = 1\n        micro\n    end\nend\n\nmicrocanonical_ensemble(evals, E_0) = microcanonical_ensemble(evals, E_0, 0.005*(evals[end]-evals[1]))", "meta": {"hexsha": "f324ba60768513de4baf4abe1748ad0281007672", "size": 2236, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/thermalization.jl", "max_stars_repo_name": "abraemer/XXZNumerics.jl", "max_stars_repo_head_hexsha": "a54068accd79306e9e2b934b5bf83c4487f64dbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-08T17:29:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T17:29:26.000Z", "max_issues_repo_path": "src/thermalization.jl", "max_issues_repo_name": "abraemer/XXZNumerics.jl", "max_issues_repo_head_hexsha": "a54068accd79306e9e2b934b5bf83c4487f64dbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-25T06:08:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-09T11:31:02.000Z", "max_forks_repo_path": "src/thermalization.jl", "max_forks_repo_name": "abraemer/XXZNumerics.jl", "max_forks_repo_head_hexsha": "a54068accd79306e9e2b934b5bf83c4487f64dbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9375, "max_line_length": 152, "alphanum_fraction": 0.6958855098, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7541062467326037}}
{"text": "@generated apply(a,b) = :( apply(a,b,Val( $( hasmethod(*,Tuple{a,b}) ) )) )\napply(a,b,::Val{true}) = a*b\napply(a,b,::Val{false}) = a(b)\n\n\"\"\"\n    tucker(C,B)\n\nApply `B[k]` to the `k`th dimension of tensor `C`.\n\n# Examples\n```\njulia> C = rand(2); B = (rand(3,2),);\n       tucker(C,B) == B[1]*C\ntrue\n\njulia> C = rand(2,3); B = (rand(4,2),rand(5,3));\n       tucker(C,B) == B[1]*C*B[2]'\ntrue\n```\n\"\"\"\nfunction tucker end\n\n@generated function tucker(\n    C::AbstractArray{<:Any,N},\n    B::NTuple{N,Any}\n) where {N}\n    quote\n        C_0 = C\n        Base.Cartesian.@nexprs $N k->begin\n            tmp_k = reshape(C_{k-1},(size(C_{k-1},1),prod(Base.tail(size(C_{k-1})))))\n            tmp_k = apply(B[k],tmp_k)\n            C_k = Array(reshape(transpose(tmp_k),(Base.tail(size(C_{k-1}))...,size(tmp_k,1))))\n            # https://github.com/JuliaLang/julia/issues/30988\n        end\n        return $(Symbol(\"C_\",N))\n    end\nend\ntucker(C::AbstractArray{<:Any,1}, B::NTuple{1,Any}) = apply(B[1],C)\ntucker(C::AbstractArray{<:Any,2}, B::NTuple{2,Any}) = transpose(apply(B[2],transpose(apply(B[1],C))))\n", "meta": {"hexsha": "cd247b11a8afb596d48218dd108542238c748786", "size": 1085, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tucker.jl", "max_stars_repo_name": "ettersi/ApproxTools.jl", "max_stars_repo_head_hexsha": "5a14019a3ed7a545c3446a7dd03b4584adf6ff46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tucker.jl", "max_issues_repo_name": "ettersi/ApproxTools.jl", "max_issues_repo_head_hexsha": "5a14019a3ed7a545c3446a7dd03b4584adf6ff46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-03-16T15:54:22.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-09T16:37:30.000Z", "max_forks_repo_path": "src/tucker.jl", "max_forks_repo_name": "ettersi/ApproxTools.jl", "max_forks_repo_head_hexsha": "5a14019a3ed7a545c3446a7dd03b4584adf6ff46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.125, "max_line_length": 101, "alphanum_fraction": 0.5529953917, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7541062374309467}}
{"text": "# ---\n# title: 1227. Airplane Seat Assignment Probability\n# id: problem1227\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Medium\n# categories: Math, Dynamic Programming, Brainteaser\n# link: <https://leetcode.com/problems/airplane-seat-assignment-probability/description/>\n# hidden: true\n# ---\n# \n# `n` passengers board an airplane with exactly `n` seats. The first passenger\n# has lost the ticket and picks a seat randomly. But after that, the rest of\n# passengers will:\n# \n#   * Take their own seat if it is still available, \n#   * Pick other seats randomly when they find their seat occupied \n# \n# What is the probability that the n-th person can get his own seat?\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: n = 1\n#     Output: 1.00000\n#     Explanation: The first person can only get the first seat.\n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: n = 2\n#     Output: 0.50000\n#     Explanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= n <= 10^5`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "c89792487a6cac9c31b47a96c789f88d5283dd53", "size": 1166, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1227.airplane-seat-assignment-probability.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/unresolved/1227.airplane-seat-assignment-probability.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/unresolved/1227.airplane-seat-assignment-probability.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 22.4230769231, "max_line_length": 125, "alphanum_fraction": 0.6440823328, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7540983332563954}}
{"text": "# # Sparse matrices\n#\n# Source to source automatic differentiation is useful in differentiating sparse matrices. It is a well-known problem that sparse matrix operations can not benefit directly from generic backward rules for dense matrices because general rules do not keep the sparse structure.\n# In the following, we will show that reversible AD can differentiate the Frobenius dot product between two sparse matrices with the state-of-the-art performance. Here, the Frobenius dot product is defined as \\texttt{trace(A'B)}.\n# Its native Julia (irreversible) implementation is `SparseArrays.dot`.\n#\n# The following is a reversible counterpart\n\nusing NiLang, NiLang.AD\nusing SparseArrays\n\n@i function idot(r::T, A::SparseMatrixCSC{T},B::SparseMatrixCSC{T}) where {T}\n    m ← size(A, 1)\n    n ← size(A, 2)\n    @invcheckoff branch_keeper ← zeros(Bool, 2*m)\n    @safe size(B) == (m,n) || throw(DimensionMismatch(\"matrices must have the same dimensions\"))\n    @invcheckoff @inbounds for j = 1:n\n        ia1 ← A.colptr[j]\n        ib1 ← B.colptr[j]\n        ia2 ← A.colptr[j+1]\n        ib2 ← B.colptr[j+1]\n        ia ← ia1\n        ib ← ib1\n        @inbounds for i=1:ia2-ia1+ib2-ib1-1\n            ra ← A.rowval[ia]\n            rb ← B.rowval[ib]\n            if (ra == rb, ~)\n                r += A.nzval[ia]' * B.nzval[ib]\n            end\n            ## b move -> true, a move -> false\n            branch_keeper[i] ⊻= @const ia == ia2-1 || ra > rb\n            ra → A.rowval[ia]\n            rb → B.rowval[ib]\n            if (branch_keeper[i], ~)\n                INC(ib)\n            else\n                INC(ia)\n            end\n        end\n        ~@inbounds for i=1:ia2-ia1+ib2-ib1-1\n            ## b move -> true, a move -> false\n            branch_keeper[i] ⊻= @const ia == ia2-1 || A.rowval[ia] > B.rowval[ib]\n            if (branch_keeper[i], ~)\n                INC(ib)\n            else\n                INC(ia)\n            end\n        end\n    end\n    @invcheckoff branch_keeper → zeros(Bool, 2*m)\nend\n\n# Here, the key point is using a \\texttt{branch\\_keeper} vector to cache branch decisions.\n\n# The time used for a native implementation is\n\nusing BenchmarkTools\na = sprand(1000, 1000, 0.01);\nb = sprand(1000, 1000, 0.01);\n@benchmark SparseArrays.dot($a, $b)\n\n# To compute the gradients, we wrap each matrix element with `GVar`, and send them to the reversible backward pass\n\nout! = SparseArrays.dot(a, b)\n@benchmark (~idot)($(GVar(out!, 1.0)),\n        $(GVar.(a)), $(GVar.(b)))\n\n# The time used for computing backward pass is approximately 1.6 times Julia's native forward pass.\n# Here, we have turned off the reversibility check off to achieve better performance.\n# By writing sparse matrix multiplication and other sparse matrix operations reversibly,\n# we will have a differentiable sparse matrix library with proper performance.\n\n# See my another blog post for [reversible sparse matrix multiplication](https://nextjournal.com/giggle/how-to-write-a-program-differentiably).\n", "meta": {"hexsha": "b455b6a240a0f3f94e47a385d4af7e50c06c7466", "size": 2975, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/sparse.jl", "max_stars_repo_name": "johnnychen94/NiLang.jl", "max_stars_repo_head_hexsha": "81fbe77d1f499003153857be8367de2024c797a5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/sparse.jl", "max_issues_repo_name": "johnnychen94/NiLang.jl", "max_issues_repo_head_hexsha": "81fbe77d1f499003153857be8367de2024c797a5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/sparse.jl", "max_forks_repo_name": "johnnychen94/NiLang.jl", "max_forks_repo_head_hexsha": "81fbe77d1f499003153857be8367de2024c797a5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2027027027, "max_line_length": 275, "alphanum_fraction": 0.6346218487, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7540983332563954}}
{"text": "\nplotvector(x, str=\"k-\",label=\"\", alpha=1.0) = plot3D([0;x[1]],[0;x[2]],[0;x[3]], str,alpha=alpha,label=label)\n\n\nproj(v, x) = vec( dot(v, x) / dot(v, v) * v )\n\n\nunitvector(x) = x / norm(x)\n", "meta": {"hexsha": "b6e296bfe0f6ba6d8051c789cbc134aceba1703c", "size": 189, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/UTIL/smallutil.jl", "max_stars_repo_name": "HITS-AIN/ProbabilisticFluxVariationGradient.jl", "max_stars_repo_head_hexsha": "36849fadeb3378b4bd4346830cc63757c90819e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/UTIL/smallutil.jl", "max_issues_repo_name": "HITS-AIN/ProbabilisticFluxVariationGradient.jl", "max_issues_repo_head_hexsha": "36849fadeb3378b4bd4346830cc63757c90819e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/UTIL/smallutil.jl", "max_forks_repo_name": "HITS-AIN/ProbabilisticFluxVariationGradient.jl", "max_forks_repo_head_hexsha": "36849fadeb3378b4bd4346830cc63757c90819e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-03T15:52:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T15:52:10.000Z", "avg_line_length": 21.0, "max_line_length": 109, "alphanum_fraction": 0.5396825397, "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7540983298846653}}
{"text": "\"\"\"\nCreated on Mon Apr 13 2020\n\n@author: Yoann Pradat\n\nPlot divergences\n\"\"\"\n\ninclude(\"./src/VNMF.jl\")\nusing .VNMF\nusing LaTeXStrings\nusing Plots\n\n#### # Plot β-divergence for different values of β\n#### #################################################################################################################\n\nβys = [-1, 0, 1, 2]\nβzs = [-0.5, 0.5, 1.5, 2.5]\ntitles = [L\"(a) \\beta < 0\", L\"(b) 0 \\leq \\beta < 1\", L\"(c) 1 \\leq \\beta < 2\", L\"(d) 2 \\leq \\beta\"]\n\nh = 0.05\np = plot(layout=(2,2), dpi=300, size=(1000, 600))\n\nfor sp=1:4\n    βy = βys[sp]\n    βz = βzs[sp]\n\n    if βz < 1\n\tX = h:h:8\n    else\n\tX = h:h:4\n    end\n\n    Y = [β_divergence(hcat([1.]), hcat([x]), βy) for x in X]\n    Z = [β_divergence(hcat([1.]), hcat([x]), βz) for x in X]\n\n    plot!(\n\tX, \n\thcat(Y, Z), \n\ttitle = titles[sp],\n\tlabels = [\"\\$\\\\beta = $(βy)\\$\" \"\\$\\\\beta = $(βz)\\$\" ],\n\tls    = [:solid :dash],\n\tlw    = 1,\n\tcolor = \"black\",\n\tsubplot = sp\n    )\n\n    plot!(\n\txlabel = \"\",\n\txlims  = (0,X[end]),\n\txticks = 0:X[end]/4:X[end],\n\tylims  = (0,1.5),\n\tyticks = 0:0.5:1.5,\n\tsubplot = sp\n    )\nend\n\nfolder   = \"demo/plot/divergence\"\nmkpath(folder)\nfilename = \"beta_divergences.pdf\"\nfilepath = joinpath(folder, filename)\n\nsavefig(p, filepath)\nprintln(\"plot saved at $(filepath)\")\n\n", "meta": {"hexsha": "bf8c00d67c11f6e710cf9d1706642ebd1ee7e5cf", "size": 1253, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demo/src/other/plot_divergences.jl", "max_stars_repo_name": "Durzot/MT_NMF", "max_stars_repo_head_hexsha": "a3e3c2fb4a23cc09e78e1ad1e324787c6017a4fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demo/src/other/plot_divergences.jl", "max_issues_repo_name": "Durzot/MT_NMF", "max_issues_repo_head_hexsha": "a3e3c2fb4a23cc09e78e1ad1e324787c6017a4fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo/src/other/plot_divergences.jl", "max_forks_repo_name": "Durzot/MT_NMF", "max_forks_repo_head_hexsha": "a3e3c2fb4a23cc09e78e1ad1e324787c6017a4fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9848484848, "max_line_length": 118, "alphanum_fraction": 0.4948124501, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.754098329872359}}
{"text": "\nconst where_bisect = 0.49609375\n\n\"\"\"\n    bisect(X::Interval, α=0.49609375)\n\nSplit the interval `X` at position α; α=0.5 corresponds to the midpoint.\nReturns a tuple of the new intervals.\n\"\"\"\nfunction bisect(X::Interval, α=where_bisect)\n    @assert 0 ≤ α ≤ 1\n\n    m = mid(X, α)\n\n    return (Interval(X.lo, m), Interval(m, X.hi))\nend\n\n\"\"\"\n    bisect(X::IntervalBox, α=0.49609375)\n\nBisect the `IntervalBox` `X` at position α ∈ [0,1] along its longest side.\n\"\"\"\nfunction bisect(X::IntervalBox, α=where_bisect)\n    i = argmax(diam.(X))  # find longest side\n\n    return bisect(X, i, α)\nend\n\n\"\"\"\n    bisect(X::IntervalBox, i::Integer, α=0.49609375)\n\nBisect the `IntervalBox` in side number `i`.\n\"\"\"\nfunction bisect(X::IntervalBox, i::Integer, α=where_bisect)\n\n    x1, x2 = bisect(X[i], α)\n\n    X1 = setindex(X, x1, i)\n    X2 = setindex(X, x2, i)\n\n    return (X1, X2)\nend\n", "meta": {"hexsha": "607b0e80989493fefd991dc79269d18aff83cfde", "size": 865, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bisect.jl", "max_stars_repo_name": "AnderGray/IntervalArithmetic.jl", "max_stars_repo_head_hexsha": "86b188da80d973f2a6da90da3003ca4121621d9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 203, "max_stars_repo_stars_event_min_datetime": "2017-04-18T21:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:27:34.000Z", "max_issues_repo_path": "src/bisect.jl", "max_issues_repo_name": "AnderGray/IntervalArithmetic.jl", "max_issues_repo_head_hexsha": "86b188da80d973f2a6da90da3003ca4121621d9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 503, "max_issues_repo_issues_event_min_datetime": "2017-04-03T01:10:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:09:39.000Z", "max_forks_repo_path": "src/bisect.jl", "max_forks_repo_name": "AnderGray/IntervalArithmetic.jl", "max_forks_repo_head_hexsha": "86b188da80d973f2a6da90da3003ca4121621d9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 76, "max_forks_repo_forks_event_min_datetime": "2017-04-10T20:49:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T22:41:01.000Z", "avg_line_length": 20.1162790698, "max_line_length": 74, "alphanum_fraction": 0.6416184971, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699185, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7540983290232731}}
{"text": "using PyPlot, Dierckx\n\ncubehermitev1(x) = 2*x^3-3*x^2+1\ncubehermitem1(x) = x^3-2*x^2+x\ncubehermitev2(x) = -2*x^3+3*x^2\ncubehermitem2(x) = (x-1)*x^2\n\n@vectorize_1arg Number cubehermitev1\n@vectorize_1arg Number cubehermitem1\n@vectorize_1arg Number cubehermitev2\n@vectorize_1arg Number cubehermitem2\n\nfunction _plothermite()\n    clf()\n    x = linspace(0,1,300)\n    plot(x, cubehermitev1(x), label=\"v1\", color=\"r\")\n    plot(x, cubehermitem1(x), label=\"m1\", color=\"g\")\n    plot(x, cubehermitev2(x), label=\"v2\", color=\"orange\")\n    plot(x, cubehermitem2(x), label=\"m2\", color=\"b\")\n    legend(loc=\"center right\")\nend\n\n\"\"\"A callable object that acts as a monotone cubic spline, with a\nchoice of behaviors at the boundaries.\"\"\"\ntype MonotoneSpline\n    x      ::Vector{Real}\n    y      ::Vector{Real}\n    m      ::Vector{Real}\n    dx     ::Vector{Real}\n    bc     ::String\n    function MonotoneSpline(x::Vector, y::Vector, m::Vector,\n        dx::Vector; bc=\"error\")\n        new(x, y, m, dx, bc)\n    end\nend\n\n\nfunction MonotoneSpline(x::Vector, y::Vector; bc=\"error\")\n\n    n=length(x)\n    @assert n==length(y)\n\n    secantslopes = zeros(Float64, n-1)\n    for i=1:n-1\n        secantslopes[i] = (y[i+1]-y[i])/(x[i+1]-x[i])\n    end\n    dx = x[2:end] .- x[1:end-1]\n    m = zeros(Float64, n)\n    m[2:n-1] = 0.5*(secantslopes[2:end] + secantslopes[1:end-1])\n    m[1] = secantslopes[1]\n    m[n] = secantslopes[n-1]\n\n    for k=1:n-1\n        if secantslopes[k] == 0\n            m[k] = m[k+1] = 0\n        else\n            alpha = m[k] / secantslopes[k]\n            beta = m[k+1] / secantslopes[k]\n            if alpha < 0 || beta < 0\n                throw(ArgumentError)\n            end\n            rsq = alpha^2 + beta^2\n            if rsq>9\n                tau = sqrt(9.0/rsq)\n            else\n                tau = 1.0\n            end\n            m[k] = tau*alpha*secantslopes[k]\n            m[k+1] = tau*beta*secantslopes[k]\n        end\n    end\n    return MonotoneSpline(x, y, m, dx; bc=bc)\nend\n\nfunction Base.call(spl::MonotoneSpline, z::Number)\n    if z < spl.x[1]\n        if spl.bc==\"error\"\n            println(\"Oh no! 1 spl.bc=$(spl.bc)\")\n            throw(ArgumentError)\n        elseif spl.bc==\"constant\"\n            return spl.y[1]\n        else\n            return spl.y[1]+spl.m[1]*(z-spl.x[1])\n        end\n    elseif z > spl.x[end]\n        if spl.bc==\"error\"\n            println(\"Oh no! 2 spl.bc=$(spl.bc)\")\n            throw(ArgumentError)\n        elseif spl.bc==\"constant\"\n            return spl.y[end]\n        else\n            return spl.y[end]+spl.m[end]*(z-spl.x[end])\n        end\n    end\n\n    bin = searchsortedfirst(spl.x, z)-1\n    if bin<1; bin=1; end\n    t = (z-spl.x[bin])/spl.dx[bin]\n    return (cubehermitev1(t)*spl.y[bin] + cubehermitem1(t)*spl.m[bin]*spl.dx[bin] +\n    cubehermitev2(t)*spl.y[bin+1] + cubehermitem2(t)*spl.m[bin+1]*spl.dx[bin])\nend\nBase.call(spl::MonotoneSpline, z::AbstractArray) = map(spl, z)\n\n\n\"\"\"A callable object that acts as a monotone cubic spline in log-log space,\nwith a choice of behaviors at the boundaries.\"\"\"\ntype MonotoneSplineLogLog\n    x      ::Vector{Real}\n    y      ::Vector{Real}\n    ms     ::MonotoneSpline\n    function MonotoneSplineLogLog(x::Vector, y::Vector; bc=\"error\")\n        ms = MonotoneSpline(log(x), log(y); bc=bc)\n        new(x, y, ms)\n    end\nend\n\nBase.call(spl::MonotoneSplineLogLog, z::Number) = exp(spl.ms(log(z)))\nBase.call(spl::MonotoneSplineLogLog, z::AbstractArray) = map(spl, z)\n\n\"\"\"Return the MonotoneSplineLogLog that has the same knots as c1 but passes\nthrough the control points that result from applying c2 on top of c1.\"\"\"\nfunction compose_splinelog(c1::MonotoneSplineLogLog, c2::MonotoneSplineLogLog)\n    x = c1.x\n    y = c2(c1(x))\n    MonotoneSplineLogLog(x, y; bc=\"extrapolate\")\nend\n\n\"\"\"Return the MonotoneSpline that has the same knots as c1 but passes\nthrough the control points that result from applying c2 on top of c1.\"\"\"\nfunction compose_spline(c1::MonotoneSpline, c2::MonotoneSpline)\n    x = c1.x\n    y = c2(c1(x))\n    MonotoneSpline(x, y; bc=\"extrapolate\")\nend\n\n\nfunction test1()\n    x = collect(0:9)\n    y = [0,1,3,10,10,11,12,14,14,16]\n    f = MonotoneSpline(x, y; bc=\"extrapolate\")\n    f2 = Dierckx.Spline1D(float(x), float(y))\n    a = linspace(-2,10,500)\n    clf()\n    plot(x,y,\"ok\",label=\"Input data\")\n    plot(a, f(a), \"r\", label=\"Monotone spline\")\n    plot(a, evaluate(f2,a), \"b\", label=\"Dierckx.Spline1D\")\n    legend(loc=\"lower right\")\n    return f\nend\n\nfunction test2()\n    model(x) = 1000*((x./1000).^0.6 ) + x\n    x = collect(linspace(0,8000,12))\n    y = model(x)\n    f = MonotoneSpline(x, y; bc=\"extrapolate\")\n    g = MonotoneSplineLogLog(x, y; bc=\"extrapolate\")\n    s(z) = evaluate(Dierckx.Spline1D(x, y), z)\n    clf()\n    a = linspace(0,8000,600)\n    subplot(211)\n    plot(a, model(a), \"k\", lw=2)\n    plot(a, f(a), \"r\")\n    plot(a, g(a), \"b\")\n    plot(a, s(a), \"g\")\n    plot(x,y,\"ok\")\n\n    subplot(212)\n    plot(a, model(a)-f(a), \"r\", label=\"Monotone spline\")\n    plot(a, model(a)-g(a), \"b\", label=\"Log-space mono spline\")\n    plot(a, model(a)-s(a), \"g\", label=\"Dierckx.Spline1D\")\n    legend()\nend\n", "meta": {"hexsha": "b46e92dd0cbf949dcd2cbdfda2770b7290e3b4a0", "size": 5090, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MonotoneSpline.jl", "max_stars_repo_name": "joefowler/AlignSpectra.jl", "max_stars_repo_head_hexsha": "f787b3bf33bd645b140100ff998727fc8e31df28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MonotoneSpline.jl", "max_issues_repo_name": "joefowler/AlignSpectra.jl", "max_issues_repo_head_hexsha": "f787b3bf33bd645b140100ff998727fc8e31df28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MonotoneSpline.jl", "max_forks_repo_name": "joefowler/AlignSpectra.jl", "max_forks_repo_head_hexsha": "f787b3bf33bd645b140100ff998727fc8e31df28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4219653179, "max_line_length": 83, "alphanum_fraction": 0.5876227898, "num_tokens": 1772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.754098319757169}}
{"text": "using Revise\n\nincludet(\"src/Spring.jl\")\nIArray = InternalArray\n\n# 3. Validating the solution --------------------------------------------------------------\n\nconst step = 1e-3\nconst nit = Int(40/step)  # round to avoid small rounding errors\n\n# We define a problem with no friction\nprob = SpringProblem(p0 = 0.8, v0 = 0, m = 1, k = 1.5)\n\nx = eulermethod(prob, step, nit)\n\ntimeline = [prob.t0 + i*step for i in 1:length(x)]\nplot(timeline, IArray(x, 1), label = \"standard\")\n\n# 5. Finding the frequency of the unforced movement ---------------------------------------\n\n# Empirically, We can see in the plot that the distance between two\n# equal values (!= 0) is aproximately 5.\n# Let's get the actual distance from our solution.\n\np0 = 1       # Reference point\nP0 = -1      # Next equal point\nfor i = 50:length(x) # We avoid the first numbers because they are very close\n    if norm(x[p0][1]-x[i][1]) < 1e-3\n        P0 = i\n        break\n    end\nend\n\nif P0 != -1\n    period = timeline[P0]-timeline[p0] # Is similar to what we observed\n    freq = 1/period\nend\n        \n\n# 6. Using this frequency to force it -----------------------------------------------------\n\ncond_prob = SpringProblem(p0 = 0.8, v0 = 0, m = 1, k = 1.5, A = 1, ω = 2*π*freq)\n\ny = eulermethod(cond_prob, step, nit)\nplot!(timeline, IArray(y, 1), label = \"conditioned\")\n\nsavefig(\"media/spring_frequency_unforced.png\")\n", "meta": {"hexsha": "1cec7dfdd1b01c6a88a4364b1f5dcea17b360298", "size": 1377, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/spring_frequency_forced.jl", "max_stars_repo_name": "useredsa/numeric-differential-equations", "max_stars_repo_head_hexsha": "7647a20120ce0a05ee5223b0ce81ad63d8aee115", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/spring_frequency_forced.jl", "max_issues_repo_name": "useredsa/numeric-differential-equations", "max_issues_repo_head_hexsha": "7647a20120ce0a05ee5223b0ce81ad63d8aee115", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/spring_frequency_forced.jl", "max_forks_repo_name": "useredsa/numeric-differential-equations", "max_forks_repo_head_hexsha": "7647a20120ce0a05ee5223b0ce81ad63d8aee115", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6875, "max_line_length": 91, "alphanum_fraction": 0.5853304285, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7540087831710841}}
{"text": "#-----------------------------------------------------------\n# RBF basis calculation\n#-----------------------------------------------------------\n\nfunction calculaterbfbasis!(Φ, x, gridpoints, r=1.0)\n\n    M = length(gridpoints)\n\n    N = length(x)\n\n    for m in 1:M\n\n        for n in 1:N\n\n            @inbounds Φ[n,m] = exp(-norm(gridpoints[m] - x[n])^2 / r^2)\n\n        end\n\n    end\n\n    nothing\n\nend\n\n\nfunction calculaterbfbasis(x, gridpoints, r=1.0)\n\n    M = length(gridpoints)\n\n    N = length(x)\n\n    Φ = zeros(N, M)\n\n    calculaterbfbasis!(Φ, x, gridpoints, r)\n\n    return Φ\n\nend\n", "meta": {"hexsha": "8ddb15b9f223acdb0729214d773f402e1f1fbffc", "size": 583, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/calculaterbfbasis.jl", "max_stars_repo_name": "ngiann/MiscUtil.jl", "max_stars_repo_head_hexsha": "62bb259ae41ffa2f2eaf4c55142523238995919e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/calculaterbfbasis.jl", "max_issues_repo_name": "ngiann/MiscUtil.jl", "max_issues_repo_head_hexsha": "62bb259ae41ffa2f2eaf4c55142523238995919e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-22T10:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T10:56:15.000Z", "max_forks_repo_path": "src/calculaterbfbasis.jl", "max_forks_repo_name": "ngiann/MiscUtil.jl", "max_forks_repo_head_hexsha": "62bb259ae41ffa2f2eaf4c55142523238995919e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.9487179487, "max_line_length": 71, "alphanum_fraction": 0.4493996569, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7540087807117212}}
{"text": "import Base: \\\nimport LinearAlgebra: lu\n\nusing Base: OneTo\nusing LinearAlgebra: givensAlgorithm\n\n\n\n\"\"\"\n    rotate_right!(R, from, to, Q) → nothing\n\nRotates the diagonal elements between R[from:to,from:to]\nsuch that the eigenvalue at R[to,to] → R[from,from]\nand all the others move R[i,i] → R[i+1,i+1].\n\nAssumes that `from` and `to` refer to the first index of the 2×2 block in the\ncase of complex conjugate pairs of eigenvalues.\n\"\"\"\nfunction rotate_right!(R, from::Integer, to::Integer, Q = NotWanted())\n    i = to\n\n    while i > from\n        # Let's just do this check always; sometimes a block might split.\n        curr_11 = is_start_of_11_block(R, i)\n        prev_11 = is_end_of_11_block(R, i-1)\n        j = prev_11 ? i - 1 : i - 2\n        swap!(R, j, prev_11, curr_11, Q)\n        i = j\n    end\n\n    nothing\nend\n\n\"\"\"\n    rotate_left!(R, from, to, Q) → nothing\n\nRotates the diagonal elements between R[from:to,from:to]\nsuch that the eigenvalue at R[from,from] → R[to,to]\nand all the others move R[i,i] → R[i-1,i-1].\n\nAssumes that `from` and `to` refer to the first index of the 2×2 block in the\ncase of complex conjugate pairs of eigenvalues.\n\"\"\"\nfunction rotate_left!(R, from::Integer, to::Integer, Q = NotWanted())\n    i = from\n\n    while true\n        # Let's just do this check always; sometimes a block might split.\n        curr_11 = is_start_of_11_block(R, i)\n        j = curr_11 ? i + 1 : i + 2\n        j > to && break\n        next_11 = is_start_of_11_block(R, j)\n\n        swap!(R, i, curr_11, next_11, Q)\n        i = next_11 ? i + 1 : i + 2\n    end\n\n    nothing\nend\n\nstruct CompletelyPivotedLU{T,N,TA<:SMatrix{N,N,T},TP}\n    A::TA\n    p::TP\n    q::TP\n    singular::Bool\nend\n\nstruct CompletePivoting end\n\n\"\"\"\n    lu(A, CompletePivoting) → CompletelyPivotedLU(B, p, q)\n\nComputes the LU factorization of A using complete pivoting.\n\"\"\"\nfunction lu(A::SMatrix{N,N,T}, ::Type{CompletePivoting}) where {N,T}\n    # A, p and q should allocate, but escape analysis will eliminate this!\n    if isbitstype(T)\n        A = MMatrix(A)\n    else\n        A = SizedMatrix(A)\n    end\n    q = @MVector fill(N, N)\n    p = @MVector fill(N, N)\n    singular = false\n\n    # Maybe I should consider doing this recursively.\n    for k = OneTo(N - 1)\n        # Find max value in sub-part.\n        m, n, maxval = 1, 1, zero(real(T))\n        for j = k:N, i = k:N\n            if abs(A[i,j]) > maxval\n                m, n, maxval = i, j, abs(A[i,j])\n            end\n        end\n\n        # Store the p and q\n        p[k] = m\n        q[k] = n\n\n        # Swap row and col\n        for j = k:N\n            A[k, j], A[m, j] = A[m, j], A[k, j]\n        end\n\n        for j = k:N\n            A[j, k], A[j, n] = A[j, n], A[j, k]\n        end\n\n        Akk = A[k,k]\n\n        # It has actually happened :(\n        if iszero(Akk)\n            singular = true\n            break\n        end\n\n        for i = k+1:N\n            A[i, k] /= Akk\n        end\n\n        for j = k+1:N\n            Akj = A[k,j]\n\n            for i = k+1:N\n                A[i,j] -= A[i,k] * Akj\n            end\n        end\n    end\n\n    if iszero(A[N,N])\n        singular = true\n    end\n\n    # Back to immutable land!\n    return CompletelyPivotedLU(SMatrix(A), SVector(p), SVector(q), singular)\nend\n\nfunction (\\)(LU::CompletelyPivotedLU{T,N}, b::SVector{N}) where {T,N}\n    if isbitstype(T)\n        x = MVector(b)\n    else\n        x = SizedVector(b)\n    end\n\n    # x ← L \\ (P * b)\n    for i = OneTo(N)\n        x[i], x[LU.p[i]] = x[LU.p[i]], x[i]\n        for j = i+1:N\n            x[j] -= LU.A[j, i] * x[i]\n        end\n    end\n\n    # x ← Q * (U \\ x)\n    for i = N:-1:1\n        for j = N:-1:i+1\n            x[i] -= LU.A[i, j] * x[j]\n        end\n        x[i] /= LU.A[i,i]\n        x[i], x[LU.q[i]] = x[LU.q[i]], x[i]\n    end\n\n    # Go back to immutable land!\n    SVector(x)\nend\n\n@inline sylvsystem(A::SMatrix{1,1,T}, B::SMatrix{2,2,T}) where {T} =\n    @SMatrix [A[1,1]-B[1,1] -B[2,1]       ;\n              -B[1,2]        A[1,1]-B[2,2]]\n\n@inline sylvsystem(A::SMatrix{2,2,T}, B::SMatrix{1,1,T}) where {T} = \n    @SMatrix [A[1,1]-B[1,1] A[1,2]       ;\n              A[2,1]        A[2,2]-B[1,1]]\n\n@inline sylvsystem(A::SMatrix{2,2,T}, B::SMatrix{2,2,T}) where {T} =\n    @SMatrix [A[1,1]-B[1,1] A[1,2]        -B[2,1]       T(0)         ;\n              A[2,1]        A[2,2]-B[1,1] T(0)          -B[2,1]      ;\n              -B[1,2]       T(0)          A[1,1]-B[2,2] A[1,2]       ;\n              T(0)          -B[1,2]       A[2,1]        A[2,2]-B[2,2]]\n\n\"\"\"\n    sylv(A, B, C) → X, singular\n\nSolve A * X - X * B = C for X, where A and B are 1×1 or 2×2 matrices.\n\nIt works by recasting the Sylvester equation to a linear system \n(I ⊗ A + Bᵀ ⊗ I) vec(X) = vec(C) of size 2 or 4, which is then solved by\nGaussian elimination with complete pivoting.\n\nIf the eigenvalues of A and B are equal, then `singular = true`.\n\"\"\"\n@inline function sylv(A::SMatrix{N,N,T}, B::SMatrix{M,M,T}, C::SMatrix{N,M,T}) where {T,N,M}\n    fact = lu(sylvsystem(A, B), CompletePivoting)\n    rhs = SVector{N*M,T}(C)\n    SMatrix{N,M,T}(fact \\ rhs), fact.singular\nend\n\n\"\"\"\n    swap22_rotations(X) → c₁, s₁, c₂, s₂, c₃, s₃, c₄, s₄\n\nConstruct two sets of two Given's rotations that transform\n```\n  -x₁₁ -x₁₂\n  -x₂₁ -x₂₂\n   1    .\n   .    1\n```\nto upper triangular form:\n```\n  x x  ⇒  x x  ⇒  * *  ⇒  x x  ⇒  x x\n  x x  ⇒  * *  ⇒  . *  ⇒  . x  ⇒  . *\n  1 .  ⇒  . *  ⇒  . x  ⇒  . *  ⇒  . .\n  . 1  ⇒  . 1  ⇒  . 1  ⇒  . .  ⇒  . .\n```\n\"\"\"\nfunction swap22_rotations(X::SMatrix{2,2,T}) where {T}\n    # Upper triangulize first column of X\n    c₁, s₁, nrm₁ = givensAlgorithm(-X[2,1], T(1))\n    c₂, s₂, nrm₂ = givensAlgorithm(-X[1,1], nrm₁)\n\n    # Apply the Givens rotations to the second column of X\n    X22 = c₁ * -X[2,2] # + s₁ * 0\n    X32 = -s₁' * -X[2,2] # + c₁ * 0\n    # X12 = c₂ * -X[1,2] + s₂ * X22 # aint gonna need it!\n    X22 = -s₂' * -X[1,2] + c₂ * X22\n\n    # Upper triangularize the second column of X\n    c₃, s₃, nrm₃ = givensAlgorithm(X32, T(1))\n    c₄, s₄, nrm₄ = givensAlgorithm(X22, nrm₃)\n\n    return c₁, s₁, c₂, s₂, c₃, s₃, c₄, s₄\nend\n\n\"\"\"\n    swap12_rotations(X) → c₁, s₁, c₂, s₂\n\nConstruct two Given's rotations that transform\n```\n  -x₁₁ -x₁₂\n   1    .\n   .    1\n```\nto upper triangular form:\n```\n  x x  ⇒  * *  ⇒  x x\n  1 .  ⇒  . *  ⇒  . *\n  . 1  ⇒  . 1  ⇒  . .\n```\n\"\"\"\nfunction swap12_rotations(X::SMatrix{1,2,T}) where {T}\n    # Upper triangulize first column of X\n    c₁, s₁, nrm₁₁ = givensAlgorithm(-X[1,1], T(1))\n\n    # Apply the Givens rotations to the second column of X\n    # X12 = c₁₁ * -X[1,2] # + s₁₁ * 0 # ain't gonna need it!\n    X22 = -s₁' * -X[1,2] # + c₁₁ * 0\n\n    # Upper triangularize the second column of X\n    c₂, s₂, nrm₁₂ = givensAlgorithm(X22, T(1))\n\n    return c₁, s₁, c₂, s₂\nend\n\n\n\"\"\"\n    swap21_rotations(X) → c₁, s₁, c₂, s₂\n\nConstruct two Given's rotations that transform\n```\n  -x₁₁ \n  -x₂₁\n   1\n```\nto upper triangular form:\n```\n  x  ⇒  x  ⇒  x\n  x  ⇒  *  ⇒  .\n  1  ⇒  .  ⇒  .\n```\n\"\"\"\nfunction swap21_rotations(X::SMatrix{2,1,T}) where {T}\n    c₁, s₁, nrm₁ = givensAlgorithm(-X[2,1], T(1))\n    c₂, s₂, nrm₂ = givensAlgorithm(-X[1,1], nrm₁)\n    return c₁, s₁, c₂, s₂\nend\n\n\"\"\"\n    swap22!(R, i) → R\n\nSwap a 2×2 block with a 2×2 block in R[i:i+4,i:i+4] via unitary transformations.\n```\n    i\n    ↓\ni → x x * *  ⇒  y y * *\n    x x * *  ⇒  y y * *\n    . . y y  ⇒  . . x x\n    . . y y  ⇒  . . x x\n```\nSwapping means similarity transformation.\n\"\"\"\nfunction swap22!(R::AbstractMatrix{T}, i::Integer, Q = NotWanted()) where {T}\n    m, n = size(R)\n\n    @inbounds begin\n\n        # Copy the upper triangular blocks + connection between them.\n        A = @SMatrix [R[i+0,i+0] R[i+0,i+1]; R[i+1,i+0] R[i+1,i+1]]\n        B = @SMatrix [R[i+2,i+2] R[i+2,i+3]; R[i+3,i+2] R[i+3,i+3]]\n        C = @SMatrix [R[i+0,i+2] R[i+0,i+3]; R[i+1,i+2] R[i+1,i+3]]\n\n        # A * X - X * B = C\n        X, singular = sylv(A, B, C)\n\n        # No need to swap if eigenvalues are indistinguishable\n        singular && return R\n\n        # Rotations that upper triangularize X\n        c₁,s₁, c₂,s₂, c₃,s₃, c₄,s₄ = swap22_rotations(X)\n        G₁ = Rotation3(c₁, s₁, c₂, s₂, i+0)\n        G₂ = Rotation3(c₃, s₃, c₄, s₄, i+1)\n\n        # Apply to R\n        lmul!(G₁, R, i, n)\n        rmul!(R, G₁, 1, i+3)\n        lmul!(G₂, R, i, n)\n        rmul!(R, G₂, 1, i+3)\n\n        # Zero out things.\n        R[i+2,i+0] = zero(T)\n        R[i+3,i+0] = zero(T)\n        R[i+2,i+1] = zero(T)\n        R[i+3,i+1] = zero(T)\n\n        # Accumulate\n        rmul!(Q, G₁)\n        rmul!(Q, G₂)\n    end\n\n    R\nend\n\n\"\"\"\n    swap21!(R, i) → R\n\nSwap a 1×1 block with a 2×2 block in R[i:i+3,i:i+3] via unitary transformations\n```\n    i\n    ↓\ni → x x *  ⇒  y * *\n    x x *  ⇒  . x x\n    . . y  ⇒  . x x\n```\nSwapping means similarity transformation.\n\"\"\"\nfunction swap21!(R::AbstractMatrix{T}, i::Integer, Q = NotWanted()) where {T}\n    m, n = size(R)\n\n    @inbounds begin\n\n        # Copy the upper triangular blocks + connection between them.\n        A = @SMatrix [R[i+0,i+0] R[i+0,i+1]; R[i+1,i+0] R[i+1,i+1]]\n        B = @SMatrix [R[i+2,i+2]]\n        C = @SMatrix [R[i+0,i+2]; R[i+1,i+2]]\n\n        # A * X - X * B = C\n        X, singular = sylv(A, B, C)\n\n        # No need to swap if eigenvalues are indistinguishable\n        singular && return R\n\n        # Rotations that upper triangularize X\n        c₁,s₁, c₂,s₂ = swap21_rotations(X)\n        G₁ = Rotation3(c₁, s₁, c₂, s₂, i)\n\n        # Apply rotations\n        lmul!(G₁, R, i, n)\n        rmul!(R, G₁, 1, i+2)\n\n        # Zero out things.\n        R[i+1,i+0] = zero(T)\n        R[i+2,i+0] = zero(T)\n\n        # Accumulate\n        rmul!(Q, G₁)\n    end\n    \n    R\nend\n\n\"\"\"\n    swap12!(R, i) → R\n\nSwap a 1×1 block with a 2×2 block in R[i:i+3,i:i+3] via unitary transformations\n```\n    i\n    ↓\ni → y * *  ⇒  x x *\n    . x x  ⇒  x x *\n    . x x  ⇒  . . y\n```\nSwapping means similarity transformation. \n\nTODO: we can optimize this swap to use just one Rotation3 rather than two\nRotation2's.\n\"\"\"\nfunction swap12!(R::AbstractMatrix{T}, i::Integer, Q = NotWanted()) where {T}\n    m, n = size(R)\n\n    @inbounds begin\n\n        # Copy the upper triangular blocks + connection between them.\n        A = @SMatrix [R[i+0,i+0]]\n        B = @SMatrix [R[i+1,i+1] R[i+1,i+2]; R[i+2,i+1] R[i+2,i+2]]\n        C = @SMatrix [R[i+0,i+1] R[i+0,i+2]]\n\n        # A * X - X * B = C\n        X, singular = sylv(A, B, C)\n\n        # No need to swap if eigenvalues are indistinguishable\n        singular && return R\n\n        # Rotations that upper triangularize X\n        c₁,s₁, c₂,s₂ = swap12_rotations(X)\n        G₁ = Rotation2(c₁, s₁, i+0)\n        G₂ = Rotation2(c₂, s₂, i+1)\n\n        # Apply rotations\n        lmul!(G₁, R, i, n)\n        rmul!(R, G₁, 1, i+2)\n        lmul!(G₂, R, i, n)\n        rmul!(R, G₂, 1, i+2)\n\n        # Zero out things.\n        R[i+2,i+0] = zero(T)\n        R[i+2,i+1] = zero(T)\n\n        # Accumulate\n        rmul!(Q, G₁)\n        rmul!(Q, G₂)\n    end\n    \n    R\nend\n\n\"\"\"\n    swap11!(R, i) → R\n\nSwap a 1×1 block with a 1×1 block in R[i:i+1,i:i+1] via unitary transformations\n    i\n    ↓\ni → x *  ⇒  y *\n    . y  ⇒  . x\n\"\"\"\nfunction swap11!(R::AbstractMatrix, i::Integer, Q = NotWanted())\n    m, n = size(R)\n\n    @inbounds begin\n        R₁₁ = R[i+0,i+0]\n        R₁₂ = R[i+0,i+1]\n        R₂₂ = R[i+1,i+1]\n        \n        # Turns out the Sylvester equation is not so hard to solve in this case.\n        G, = get_rotation(R₁₂, R₂₂ - R₁₁, i)\n        \n        # Miniscule optimization by not touching R[i:i+1,i:i+1]\n        lmul!(G, R, i+2, n)\n        rmul!(R, G, 1, i-1)\n        R[i+0,i+0] = R₂₂\n        R[i+1,i+1] = R₁₁\n\n        # Accumulate\n        rmul!(Q, G)\n    end\n\n    R\nend\n\n\"\"\"\n    swap!(R, i, curr_11, next_11, Q) → nothing\n\nSwap the two consecutive blocks of the Schur form starting at index i.\n\"\"\"\nfunction swap!(R::AbstractMatrix, i::Integer, curr_11::Bool, next_11::Bool, Q = NotWanted())\n    if curr_11 \n        if next_11\n            swap11!(R, i, Q)\n        else\n            swap12!(R, i, Q)\n        end\n    else\n        if next_11\n            swap21!(R, i, Q)\n        else\n            swap22!(R, i, Q)\n        end\n    end\nend\n\n@inline is_start_of_11_block(R, i) = i == size(R, 2) || @inbounds(iszero(R[i+1,i]))\n@inline is_end_of_11_block(R, i) = i == 1 || @inbounds(iszero(R[i,i-1]))\n", "meta": {"hexsha": "dfd57ad11e96e8bb101dd283150c10b6d90daa9c", "size": 12189, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/schursort.jl", "max_stars_repo_name": "fgerick/ArnoldiMethod.jl", "max_stars_repo_head_hexsha": "23ec59d024403ce6b0acd1f1a15f0a3d8da0ecac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2018-08-28T14:04:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T02:18:47.000Z", "max_issues_repo_path": "src/schursort.jl", "max_issues_repo_name": "fgerick/ArnoldiMethod.jl", "max_issues_repo_head_hexsha": "23ec59d024403ce6b0acd1f1a15f0a3d8da0ecac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2018-05-21T12:53:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-27T08:58:38.000Z", "max_forks_repo_path": "src/schursort.jl", "max_forks_repo_name": "fgerick/ArnoldiMethod.jl", "max_forks_repo_head_hexsha": "23ec59d024403ce6b0acd1f1a15f0a3d8da0ecac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2018-09-10T19:35:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T11:48:46.000Z", "avg_line_length": 24.378, "max_line_length": 92, "alphanum_fraction": 0.5116908688, "num_tokens": 4617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7540087795596243}}
{"text": "include(\"poly_factorization_project.jl\")\nprintln(\"Welcome to the Great Polynomial Factoriser\")\nprintln(\"\")\nprintln(\"\")\nprintln(\"----- Example Polynomials -----\")\nx = x_poly()\np1 = 2x^3 + 4x^2 - 3x\np2 = -6x^4 - 4x^2 - 3x + 3\nprintln(p1)\nprintln(p2)\nprintln(\"\")\nprintln(\"mod 7\")\nx = x_poly(7)\np1 = 2x^5 + 5x - 3\np2 = -6x^4 - 4x^2 - 3x + 3\nprintln(p1)\nprintln(p2)\nprintln(\"\")\nprintln(\"mod 17\")\nx = x_poly(17)\np1 = 16x^3 - 3\np2 = -6x^8 - 4x^2 - 3x + 1\nprintln(p1)\nprintln(p2)\nprintln(\"\")\nprintln(\"mod 101\")\nx = x_poly(101)\na = 99x^8+ 50x^2 - 3\nb = 3x^7+ 5x^7 + 10x^2 + 60x \n@show a\n@show b\n\nprintln(\"\")\n\nprintln(\"----- Basic Operations -----\")\n@show a+b\n@show a-b\n@show a*b\n@show a÷b\n@show a^3\nprintln(\"\")\nprintln(\"d/dx(\", \"$a) = \", derivative(a))\nprintln(\"\")\nprintln(\"-----Factorisation Example------\")\np = (7x^3 + 2x^2 + 8x + 1)*(x^2+x+1)\n\nprintln(\"The Factorisation of: \", p,\" is:\")\nprintln(\"\")\nfactorization = factor(p,true)\nprintln(\"Here it is:\")\npretty_factor(factorization)\npr = expand_factorization(factorization)\nprintln(\"\")\nprintln(\"Reconstructing: \", pr)\n\nprintln(\" \")\nprintln(\"---- Extended Euclid Algorithm on x^2 + 50 and 10x^3+10 (mod 101) ----\")\negcd = extended_euclid_alg(x^2 + 50,10x^3+10)\npretty_print_egcd((((x^2 + 50)*(10x^3+10)).polynomial,b.polynomial), egcd)\n\nprintln(\"\")\nprintln(\"----- Bechmarking -----\")\nprintln(\"Time taken to raise $a to the 1000th power:\")\n@time l = a^1000\nprintln(\"\")\nmultbenchZ()\nprintln(\"\")\nmultbenchZp()\nprintln(\"\")\npowbench()\nprintln(\"\")\n\nprintln(\":)\")", "meta": {"hexsha": "0e91719f6976332bdd1d614c9bdc59bf1fa66688", "size": 1499, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example_script_2.jl", "max_stars_repo_name": "Talis0/2504_2021_project1", "max_stars_repo_head_hexsha": "c2c73a74e5b909b404ea8ed8ee42e1cddeacbb2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example_script_2.jl", "max_issues_repo_name": "Talis0/2504_2021_project1", "max_issues_repo_head_hexsha": "c2c73a74e5b909b404ea8ed8ee42e1cddeacbb2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example_script_2.jl", "max_forks_repo_name": "Talis0/2504_2021_project1", "max_forks_repo_head_hexsha": "c2c73a74e5b909b404ea8ed8ee42e1cddeacbb2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5342465753, "max_line_length": 81, "alphanum_fraction": 0.6257505003, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706048, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7540087712473165}}
{"text": "module geometry\n\nexport is_in_pipe, is_in_half_space, is_in_sphere\n\n# Returns distance from cylinder center, squared\n# query: DenseVector for which to compute cylindrical norm\n# d₀: Direction of the cylinder\n# center: Center of cylinder goes through this point\nfunction cylindrical_norm_squared{T}(query::DenseVector{T}, d₀::DenseVector{T}, center::DenseVector{T})\n    @assert length(d₀) == length(center) == length(query)\n    @assert norm(d₀, 1) > 1e-8\n    q₀ = query - center\n    q⟂ = q₀ - (q₀⋅d₀)d₀ / (d₀⋅d₀)\n    q⟂⋅q⟂\nend\n\n# True if query point is inside cylinder\n# query: DenseVector for which to compute cylindrical norm\n# d₀: Direction of the cylinder\n# center: Center of cylinder goes through this point\n# radius: of the cylinder\nfunction is_in_pipe{T}(query::DenseVector{T}, d₀::DenseVector{T}, center::DenseVector{T}, radius::T)\n    cylindrical_norm_squared(query, d₀, center) <= (radius^2)\nend\n\n# True if in half-space defined by normal and offset\n# query: DenseVector for which to compute condition\n# d₀: Normal to the plane defining the half-space\n# origin: Origin of the plane defining the half-space\nfunction is_in_half_space{T}(query::DenseVector{T}, d₀::DenseVector{T}, origin::DenseVector{T})\n    @assert length(d₀) == length(origin) == length(query)\n    @assert norm(d₀, 1) > 1e-8\n    (query - origin)⋅d₀ >= 0\nend\n\n\n# True if in sphere defined by center and radius\n# query: DenseVector for which to compute condition\nfunction is_in_sphere{T}(query::DenseVector{T}, center::DenseVector{T}, radius::T)\n    @assert length(center) == length(query)\n    q₀ = center - query\n    q₀⋅q₀ <= radius^2\nend\n\nend # module geometry\n", "meta": {"hexsha": "8f53c84c84b5603892a32b24e625569b1c7a742b", "size": 1636, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geometry.jl", "max_stars_repo_name": "UCL/LatBo.jl", "max_stars_repo_head_hexsha": "d08dcbd5c51285eeb88c6d7d22cf83adba98de6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2015-04-25T21:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-18T14:00:33.000Z", "max_issues_repo_path": "src/geometry.jl", "max_issues_repo_name": "UCL/LatBo.jl", "max_issues_repo_head_hexsha": "d08dcbd5c51285eeb88c6d7d22cf83adba98de6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-05-25T15:26:11.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-15T16:14:13.000Z", "max_forks_repo_path": "src/geometry.jl", "max_forks_repo_name": "UCL/LatBo.jl", "max_forks_repo_head_hexsha": "d08dcbd5c51285eeb88c6d7d22cf83adba98de6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-10-16T15:28:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:16:00.000Z", "avg_line_length": 35.5652173913, "max_line_length": 103, "alphanum_fraction": 0.7261613692, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654165937868, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7539749594067876}}
{"text": "# function black_formula(optType::OptionType, strike::Float64, forward::Float64, stdDev::Float64,\n#                       discount::Float64 = 1.0, displacement::Float64 = 0.0)\n#   # TODO check parameters\n#   if stdDev == 0.0\n#     return max((forward - strike) * value(optType), 0.0) * discount\n#   end\n#\n#   forward = forward + displacement\n#   strike = strike + displacement\n#\n#   if strike == 0.0\n#     return isa(optType, Call) ? forward * discount : 0.0\n#   end\n#\n#   d1 = log(forward / strike) / stdDev + 0.5 * stdDev\n#   d2 = d1 - stdDev\n#   phi = Normal()\n#   nd1 = phi(value(optionType) * d1)\n#   nd2 = phi(value(optionType) * d2)\n#   result = discount * optionType * (forward * nd1 - strike * nd2)\n#   result >= 0.0 || error(\"negative value\")\n#\n#   return result\n# end\n\nfunction black_scholes_theta(process::AbstractBlackScholesProcess, val::Float64, delta_::Float64, gamma_::Float64)\n  u = state_variable(process).value\n  r = zero_rate(process.riskFreeRate, 0.0, ContinuousCompounding()).rate\n  q = zero_rate(process.dividendYield, 0.0, ContinuousCompounding()).rate\n  v = local_vol(process.localVolatility, 0.0, u)\n\n  return r * val - (r - q) * u * delta_ - 0.5 * v * v * u * u * gamma_\nend\n\nfunction black_formula_std_dev_derivative(strike::Float64, forward::Float64, stdDev::Float64, expiry::Float64, disc::Float64, displacement::Float64)\n  # TOOD check params\n  stdDev >= 0.0 || error(\"stdDev must be non-negative\")\n  disc > 0.0 || error(\"discount must be positive\")\n\n  forward = forward + displacement\n  strike = strike + displacement\n\n  if stdDev == 0.0 || strike == 0.0\n    return 0.0\n  end\n\n  d1 = log(forward/strike) / stdDev + 0.5 * stdDev\n\n  return disc * forward * distribution_derivative(Normal(), d1)\nend\n\nblack_formula_vol_derivative(strike::Float64, forward::Float64, stdDev::Float64, expiry::Float64, disc::Float64, displacement::Float64) =\n                            black_formula_std_dev_derivative(strike, forward, stdDev, expiry, disc, displacement) * sqrt(expiry)\n", "meta": {"hexsha": "9848724c21e15e8a25e93b4e6a46d88ae298db40", "size": 1998, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pricing_engines/black_formula.jl", "max_stars_repo_name": "pazzo83/QuantLib.jl", "max_stars_repo_head_hexsha": "fe987145ace4d2742eedf8e2005ada591d325691", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 121, "max_stars_repo_stars_event_min_datetime": "2016-03-03T02:20:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T10:46:07.000Z", "max_issues_repo_path": "src/pricing_engines/black_formula.jl", "max_issues_repo_name": "rafalpiotrowski/QuantLib.jl", "max_issues_repo_head_hexsha": "fe987145ace4d2742eedf8e2005ada591d325691", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2016-03-02T01:10:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-12T10:53:48.000Z", "max_forks_repo_path": "src/pricing_engines/black_formula.jl", "max_forks_repo_name": "rafalpiotrowski/QuantLib.jl", "max_forks_repo_head_hexsha": "fe987145ace4d2742eedf8e2005ada591d325691", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 47, "max_forks_repo_forks_event_min_datetime": "2016-03-02T00:31:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T18:01:30.000Z", "avg_line_length": 37.0, "max_line_length": 148, "alphanum_fraction": 0.6716716717, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.75397495154053}}
{"text": "module Elements\nimport GaussQuadrature\n\n\"\"\"\n    lglpoints(::Type{T}, N::Integer) where T <: AbstractFloat\n\nreturns the points `r` and weights `w` associated with the `N+1`-point\nGauss-Legendre-Lobatto quadrature rule of type `T`\n\n\"\"\"\nfunction lglpoints(::Type{T}, N::Integer) where {T <: AbstractFloat}\n    @assert N ≥ 1\n    GaussQuadrature.legendre(T, N + 1, GaussQuadrature.both)\nend\n\n\"\"\"\n    lgpoints(::Type{T}, N::Integer) where T <: AbstractFloat\n\nreturns the points `r` and weights `w` associated with the `N+1`-point\nGauss-Legendre quadrature rule of type `T`\n\"\"\"\nfunction lgpoints(::Type{T}, N::Integer) where {T <: AbstractFloat}\n    @assert N ≥ 1\n    GaussQuadrature.legendre(T, N + 1, GaussQuadrature.neither)\nend\n\n\"\"\"\n    baryweights(r)\n\nreturns the barycentric weights associated with the array of points `r`\n\nReference:\n  Jean-Paul Berrut & Lloyd N. Trefethen, \"Barycentric Lagrange Interpolation\",\n  SIAM Review 46 (2004), pp. 501-517.\n  <https://doi.org/10.1137/S0036144502417715>\n\"\"\"\nfunction baryweights(r::AbstractVector{T}) where {T}\n    Np = length(r)\n    wb = ones(T, Np)\n\n    for j in 1:Np\n        for i in 1:Np\n            if i != j\n                wb[j] = wb[j] * (r[j] - r[i])\n            end\n        end\n        wb[j] = T(1) / wb[j]\n    end\n    wb\nend\n\n\n\"\"\"\n    spectralderivative(r::AbstractVector{T},\n                       wb=baryweights(r)::AbstractVector{T}) where T\n\nreturns the spectral differentiation matrix for a polynomial defined on the\npoints `r` with associated barycentric weights `wb`\n\nReference:\n  Jean-Paul Berrut & Lloyd N. Trefethen, \"Barycentric Lagrange Interpolation\",\n  SIAM Review 46 (2004), pp. 501-517.\n  <https://doi.org/10.1137/S0036144502417715>\n\"\"\"\nfunction spectralderivative(\n    r::AbstractVector{T},\n    wb = baryweights(r)::AbstractVector{T},\n) where {T}\n    Np = length(r)\n    @assert Np == length(wb)\n    D = zeros(T, Np, Np)\n\n    for k in 1:Np\n        for j in 1:Np\n            if k == j\n                for l in 1:Np\n                    if l != k\n                        D[j, k] = D[j, k] + T(1) / (r[k] - r[l])\n                    end\n                end\n            else\n                D[j, k] = (wb[k] / wb[j]) / (r[j] - r[k])\n            end\n        end\n    end\n    D\nend\n\n\"\"\"\n    interpolationmatrix(rsrc::AbstractVector{T}, rdst::AbstractVector{T},\n                        wbsrc=baryweights(rsrc)::AbstractVector{T}) where T\n\nreturns the polynomial interpolation matrix for interpolating between the points\n`rsrc` (with associated barycentric weights `wbsrc`) and `rdst`\n\nReference:\n  Jean-Paul Berrut & Lloyd N. Trefethen, \"Barycentric Lagrange Interpolation\",\n  SIAM Review 46 (2004), pp. 501-517.\n  <https://doi.org/10.1137/S0036144502417715>\n\"\"\"\nfunction interpolationmatrix(\n    rsrc::AbstractVector{T},\n    rdst::AbstractVector{T},\n    wbsrc = baryweights(rsrc)::AbstractVector{T},\n) where {T}\n    Npdst = length(rdst)\n    Npsrc = length(rsrc)\n    @assert Npsrc == length(wbsrc)\n    I = zeros(T, Npdst, Npsrc)\n    for k in 1:Npdst\n        for j in 1:Npsrc\n            I[k, j] = wbsrc[j] / (rdst[k] - rsrc[j])\n            if !isfinite(I[k, j])\n                I[k, :] .= T(0)\n                I[k, j] = T(1)\n                break\n            end\n        end\n        d = sum(I[k, :])\n        I[k, :] = I[k, :] / d\n    end\n    I\nend\n\nend # module\n", "meta": {"hexsha": "574b504a0a4bc2a898100fd631da180f959e5e5c", "size": 3323, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Numerics/Mesh/Elements.jl", "max_stars_repo_name": "ChrisRackauckas/ClimateMachine.jl", "max_stars_repo_head_hexsha": "195bdaa323086c67a7aa4d1b5d99612f077ff3fe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numerics/Mesh/Elements.jl", "max_issues_repo_name": "ChrisRackauckas/ClimateMachine.jl", "max_issues_repo_head_hexsha": "195bdaa323086c67a7aa4d1b5d99612f077ff3fe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numerics/Mesh/Elements.jl", "max_forks_repo_name": "ChrisRackauckas/ClimateMachine.jl", "max_forks_repo_head_hexsha": "195bdaa323086c67a7aa4d1b5d99612f077ff3fe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-18T14:26:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-18T14:26:29.000Z", "avg_line_length": 26.373015873, "max_line_length": 80, "alphanum_fraction": 0.5841107433, "num_tokens": 1027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7539749493012842}}
{"text": "using LinearAlgebra\nusing Makie\n\n\n\"\"\"\nλmap(p)\nSends a point on a 3-sphere to a point in the plane x₄=0 with the given point\nin the form of 2 complex numbers representing a unit quaternion. This is the\nstereographic projection of a 3-sphere. S³ ↦ R³\n\"\"\"\nfunction λmap(p)\n    [real(p[1]), imag(p[1]), real(p[2])] ./ (1 - imag(p[2]))\nend\n\n\n\"\"\"\nλ⁻¹map(p)\nSends a point on the plane back to a point on a unit sphere with the given\npoint. This is the inverse stereographic projection of a 3-sphere.\n\"\"\"\nfunction λ⁻¹map(p)\n    x₁ = 2p[1] / (1 + p[1]^2 + p[2]^2 + p[3]^2)\n    x₂ = 2p[2] / (1 + p[1]^2 + p[2]^2 + p[3]^2)\n    x₃ = 2p[3] / (1 + p[1]^2 + p[2]^2 + p[3]^2)\n    x₄ = (-1 + p[1]^2 + p[2]^2 + p[3]^2) / (1 + p[1]^2 + p[2]^2 + p[3]^2)\n    [Complex(x₁, x₂), Complex(x₃, x₄)]\nend\n\n\n\"\"\"\nS¹action(α, p)\nPerforms a group action corresponding to moving along the circumference of a\ncircle with the given angle and the point in the form of 2 complex numbers\nrepresenting a unit quaternion.\n\"\"\"\nfunction S¹action(α, p)\n    [exp(im * α) * p[1], exp(im * α) * p[2]]\nend\n\n\n\"\"\"\nconvert_to_cartesian(p)\nConverts a point in the geographic coordinate system to a point in the\ncartesian one with the given point in radians.\n\"\"\"\nfunction convert_to_cartesian(p)\n    [cos(p[2]) * cos(p[1]),\n     cos(p[2]) * sin(p[1]),\n     sin(p[2])]\nend\n\n\n\"\"\"\nconvert_to_geographic(p)\nConverts a point in the cartesian coordinate system to a point in the\ngeographic one with the given point.\n\"\"\"\nfunction convert_to_geographic(p)\n    r = sqrt(p[1]^2 + p[2]^2 + p[3]^2)\n    if p[1] > 0\n          ϕ = atan(p[2] / p[1])\n    elseif p[2] > 0\n          ϕ = atan(p[2] / p[1]) + pi\n    else\n          ϕ = atan(p[2] / p[1]) - pi\n    end\n    θ = asin(p[3] / r)\n    [ϕ, θ]\nend\n\n\n\"\"\"\nget_center(A, B, C)\n\nFinds the center point of the fiber circle under stereographic projection\nwith the given 3 points on the circle circumference.\n\"\"\"\nfunction get_center(A, B, C)\n    a = LinearAlgebra.norm(B - C)\n    b = LinearAlgebra.norm(A - C)\n    c = LinearAlgebra.norm(A - B)\n    numerator = a^2 * (b^2 + c^2 - a^2) * A +\n                b^2 * (a^2 + c^2 - b^2) * B +\n                c^2 * (a^2 + b^2 - c^2) * C\n    denominator = a^2 * (b^2 + c^2 - a^2) +\n                  b^2 * (a^2 + c^2 - b^2) +\n                  c^2 * (a^2 + b^2 - c^2)\n    numerator / denominator\nend\n\n\n\"\"\"\nget_flower(;N=4, A=.5, B=-pi/7, P=pi/2, Q=0, number=300)\n\nCalculates the x, y and z points of a flower in the base space.\nwith the given number of petals N, the fattness of the petals A,\nthe height of the petals B, the latitude of the flower P,\nthe rotation of the flower Q, and the total number of points in the grid.\n\"\"\"\nfunction get_flower(;N=4, A=.5, B=-pi/7, P=pi/2, Q=0, number=300)\n    N = 6\n    A = .5\n    B = -pi/7\n    P = pi/3\n    Q = 0\n    t = range(0, stop = 2pi, length = number)\n    az = 2pi .* t + A .* cos.(N .* 2pi .* t) .+ Q\n    po = B .* sin.(N .* 2pi .* t) .+ P\n    x = cos.(az).*sin.(po)\n    y = sin.(az).*sin.(po)\n    z = cos.(po)\n    points = Array{Float64}(undef, number, 2)\n    for i in 1:number\n        points[i, :] = convert_to_geographic([x[i], y[i], z[i]])\n    end\n    points\nend\n\n\n\"\"\"\nbuild_surface(scene, points, color; transparency, shading)\n\nBuilds a surface with the given scene, points, color, transparency and shading.\n\"\"\"\nfunction build_surface(scene,\n                       points,\n                       color;\n                       transparency = false,\n                       shading = true)\n    surface!(scene,\n             @lift($points[:, :, 1]),\n             @lift($points[:, :, 2]),\n             @lift($points[:, :, 3]),\n             color = color,\n             transparency = transparency,\n             shading = shading)\nend\n\n\n\"\"\"\nrotate3D_geographic(point, q)\n\nRotates a point in the 3D space with the given point and the unit quaternion.\n\"\"\"\nfunction rotate3D_geographic(point, q)\n    c = convert_to_cartesian(point)\n    p = Quaternion(c[1], c[2], c[3], 0.0)\n    R = conj(q) * p * q\n    convert_to_geographic([R[1], R[2], R[3]])\nend\n\n\n\"\"\"\nrotate3D_cartesian(point, q)\n\nRotates a point in the 3D space with the given point and the unit quaternion.\n\"\"\"\nfunction rotate3D_cartesian(point, q)\n    p = Quaternion(point..., 0.0)\n    R = conj(q) * p * q\n    [R[1], R[2], R[3]]\nend\n\n\n\"\"\"\nget_fiber(point, segments, samples; r=0.025)\n\nCalculates a torus of revolution for building a surface in a specific way with\nthe given point in the base space, the number of segments, the number of\nsamples and the radius of the smaller circle in the torus of revolution.\n\"\"\"\nfunction get_fiber(point, segments, samples; r=0.01)\n    # Find 3 points on the circle\n    b = λ⁻¹map(convert_to_cartesian(point))\n    A = λmap(S¹action(pi / 6, b))\n    B = λmap(S¹action(pi / 4, b))\n    C = λmap(S¹action(pi / 3, b))\n    # The fiber circle center\n    Q = get_center(A, B, C)\n    # The bigger radius\n    R = norm(Q - A)\n    # Get the normal to the plane containing the points\n    n = LinearAlgebra.cross(A - Q, B - Q)\n    n = n / LinearAlgebra.norm(n)\n    # The initial normal to the circle\n    i = [0.0, 0.0, 1.0]\n    # The axis of rotation\n    u = LinearAlgebra.cross(n, i)\n    u = u / LinearAlgebra.norm(u)\n    # The angle of rotation\n    angle = acos(LinearAlgebra.dot(n, i)) / 2.0\n    q = Quaternion(sin(angle)*u[1],\n                   sin(angle)*u[2],\n                   sin(angle)*u[3],\n                   cos(angle))\n    # Construct a torus of revolution grid\n    manifold = Array{Float64}(undef, segments, samples, 3)\n    for i in 1:segments\n        for j in 1:samples\n            longitude = i * 2pi / (segments - 1)\n            latitude = j * 2pi / (samples - 1)\n            x₁ = (Q[1] + (R + r * cos(longitude)) * cos(latitude)) / R\n            x₂ = (Q[2] + (R + r * cos(longitude)) * sin(latitude)) / R\n            x₃ = (Q[3] + r * sin(longitude)) / R\n            manifold[i, j, :] = rotate3D_cartesian([x₁, x₂, x₃], q)\n        end\n    end\n    manifold\nend\n\n\n# The scene object that contains other visual objects\nuniverse = Scene(backgroundcolor = :white, show_axis=false, resolution = (360, 360))\n#universe = Scene(backgroundcolor = :white, show_axis=false, resolution = (2560, 1440))\n\n# Calculate a unit quaternion as the rotation axis\nu = [sqrt(3)/3, sqrt(3)/3, sqrt(3)/3]\nϕ = Node(0.0)\nq = @lift(Quaternion(sin($ϕ)*u[1],\n                     sin($ϕ)*u[2],\n                     sin($ϕ)*u[3],\n                     cos($ϕ)))\nsegments = 36\nsamples = 72\nnumber = 360\npoints = get_flower(number = number)\nfor i in 1:number\n    rotated = @lift(rotate3D_geographic(points[i, :], $q))\n    fiber = @lift(get_fiber($rotated, segments, samples))\n    color = @lift begin\n        x₁, x₂, x₃ = convert_to_cartesian($rotated)\n        fill(RGBAf0(rand()/3+2x₁/3, rand()/3+2x₂/3, rand()/3+2x₃/3, 0.9),\n             segments,\n             samples)\n    end\n    build_surface(universe, fiber, color, shading = false)\nend\n\n# update eye position\neye_position, lookat, upvector = Vec3f0(0.01, 0, 5), Vec3f0(0), Vec3f0(0, 0, 1.0)\nupdate_cam!(universe, eye_position, lookat)\nuniverse.center = false # prevent scene from recentering on display\n# Makie.save(\"gallery/porta.jpg\", universe)\nframes = 90\nrecord(universe, \"gallery/flower.gif\") do io\n    for i in 1:frames\n        ϕ[] = i*2pi/frames # animate scene\n        recordframe!(io) # record a new frame\n    end\nend\n", "meta": {"hexsha": "10e5ecf4bc99942899f34c6fbd7db1c29006bef7", "size": 7304, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/flower.jl", "max_stars_repo_name": "SimonDanisch/Porta.jl", "max_stars_repo_head_hexsha": "70a5b6586b74f5d76d3add8c9f305071dea13b6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2020-03-28T05:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T22:16:31.000Z", "max_issues_repo_path": "models/flower.jl", "max_issues_repo_name": "iamazadi/Porta", "max_issues_repo_head_hexsha": "73a97d879d06a1466ff3b966b2ea8e8a846d4c78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-15T12:36:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-15T12:36:59.000Z", "max_forks_repo_path": "models/flower.jl", "max_forks_repo_name": "iamazadi/Porta", "max_forks_repo_head_hexsha": "73a97d879d06a1466ff3b966b2ea8e8a846d4c78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-09-13T20:28:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T03:31:59.000Z", "avg_line_length": 29.0996015936, "max_line_length": 87, "alphanum_fraction": 0.5843373494, "num_tokens": 2395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7539749470620385}}
{"text": "#\n#   Posituve Definite Karcher Mean (Matlab Manopt)\n#\nusing Manopt, Manifolds, ManifoldsBase, LinearAlgebra, Random\nRandom.seed!(42)\nn = 5\nm = 5\nM = SymmetricPositiveDefinite(n)\nx = random_point(M)\nA = [random_point(M) for _ in 1:m]\nA = [Symmetric(a) for a in A]\nF(X::Array{Float64,2}) = sum([distance(M, X, B)^2 for B in A]) / (2 * m)\n∇F(X::Array{Float64,2}) = -sum([log(M, X, B) for B in A]) / m\n\n@time quasi_Newton(\n    M,\n    F,\n    ∇F,\n    x;\n    memory_size=100,\n    stopping_criterion=StopWhenGradientNormLess(norm(M, x, ∇F(x)) * 10^(-6)),\n    debug=[:Iteration, \" \", :Cost, \"\\n\", 1, :Stop],\n)\n\n# B1 = quasi_Newton(M,F,∇F,x; memory_size = 100, debug = [:Iteration, \" \", :Cost, \"\\n\", 1, :Stop])\n# B2 = mean(M,A)\n", "meta": {"hexsha": "de972e988c61d423c6caac7a14f1437383f2e86e", "size": 719, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Quasi_Newton/Positive_Definite_Karcher_Mean.jl", "max_stars_repo_name": "fkastner/Manopt.jl", "max_stars_repo_head_hexsha": "89c60404c7cf756102bcf45dd58dc443ef2b2d4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Quasi_Newton/Positive_Definite_Karcher_Mean.jl", "max_issues_repo_name": "fkastner/Manopt.jl", "max_issues_repo_head_hexsha": "89c60404c7cf756102bcf45dd58dc443ef2b2d4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Quasi_Newton/Positive_Definite_Karcher_Mean.jl", "max_forks_repo_name": "fkastner/Manopt.jl", "max_forks_repo_head_hexsha": "89c60404c7cf756102bcf45dd58dc443ef2b2d4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6296296296, "max_line_length": 98, "alphanum_fraction": 0.6036161335, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.7539749425835468}}
{"text": "\n# load required modules\nusing CategoricalArrays\nusing CSV\nusing DataFrames\nusing Distributions\nusing Plots\nusing Random\nusing StatsBase\n\n# set seed for reproducible sequence of numbers\nRandom.seed!(42);\n\n# draw 1000 observations from a normal distribuition \n# of mean 100 and standard deviation 10\nxnorm = rand(Normal(100, 10), 1000)\nhistogram(xnorm)\n\n# draw 1000 observations from a uniform distribuition \n# of minimum 0 and maximum 10\nxunif = rand(Uniform(0, 10), 1000)\nhistogram(xunif)\n\n# draw 1000 observation from bernoulli distribution with\n# probability of success 0.3\nxbern = rand(Bernoulli(0.3), 1000)\nhistogram(xbern)\n\n# draw 1000 observation from binomial distribution with\n# probability of success 0.3 and 30 number of trials\nxbin = rand(Binomial(30, 0.3), 1000)\nhistogram(xbin)\n\n# draw 1000 observations from a poisson distribuition \n# of average rate of occurrence 100\nxpoiss = rand(Poisson(100), 1000)\nhistogram(xpoiss)\n", "meta": {"hexsha": "f6ff356141892bf4f3912f1e6594121841c2170c", "size": 936, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/202105251704-julia-data-distributions.jl", "max_stars_repo_name": "lykmapipo/data-science-learning", "max_stars_repo_head_hexsha": "a8d07147b8761a60fafc30e7bdf68d9d4ef93602", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-05-09T08:45:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T09:21:58.000Z", "max_issues_repo_path": "scripts/202105251704-julia-data-distributions.jl", "max_issues_repo_name": "lykmapipo/data-science-learning", "max_issues_repo_head_hexsha": "a8d07147b8761a60fafc30e7bdf68d9d4ef93602", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/202105251704-julia-data-distributions.jl", "max_forks_repo_name": "lykmapipo/data-science-learning", "max_forks_repo_head_hexsha": "a8d07147b8761a60fafc30e7bdf68d9d4ef93602", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-05T07:13:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T07:13:54.000Z", "avg_line_length": 24.6315789474, "max_line_length": 56, "alphanum_fraction": 0.7799145299, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305339244013, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.7538843926014014}}
{"text": "\nfunction spindown_convergence_plot(dtlist, l2err, maxerr, sdc_order)\n    orderstring = latexstring(\"\\\\mathcal{O}(\\\\Delta t^$sdc_order)\")\n    h = loglog(dtlist, maxerr, \".-\", label=LaTeXString(\"\\$||\\\\tilde u^{($sdc_order)} - u||_\\\\infty\\$\"))\n    color = h[1][:get_color]()\n    loglog(dtlist, l2err, \"*-\", label=LaTeXString(\"\\$||\\\\tilde u^{($sdc_order)} - u||_2\\$\"), color=color)    \n    matchidx = 4\n    C = ( maxerr[matchidx] + l2err[matchidx] )/2\n    @show dtlist_ext = vcat(dtlist[1]*2, dtlist, dtlist[end]/2)\n    loglog(dtlist_ext, C*(dtlist_ext/dtlist[matchidx]).^sdc_order, \"--\", label=orderstring, color=color)\n    #axis(\"equal\")\n    grid(\"on\")    \n    #xlim(left=3e-5, right=1e-2)\n    axis(\"tight\")\n    ylim([1e-13, 1e-2])    \n    xlabel(L\"Time step $\\Delta t$\")\n    ylabel(\"Relative error\")\n    legend(bbox_to_anchor=(1.0,1.03), ncol=2)\n    tight_layout(0.1)\nend\n\n\nclose(\"all\")\nfigure(figsize=(9,3))\nspindown_convergence_plot(dtlist1, l2err1, maxerr1, 1)\nspindown_convergence_plot(dtlist2, l2err2, maxerr2, 2)\nspindown_convergence_plot(dtlist3, l2err3, maxerr3, 3)\nspindown_convergence_plot(dtlist4, l2err4, maxerr4, 4)\n\nsavefig(\"../docs/paper/figs/convergence_time.pdf\")\n", "meta": {"hexsha": "ccc3f8a638362df68fadab938da347291ec950f0", "size": 1181, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/output_scripts/demo_spindown_plot.jl", "max_stars_repo_name": "askhamwhat/inse-fiem-2d", "max_stars_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-08-20T12:53:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:15:10.000Z", "max_issues_repo_path": "julia/output_scripts/demo_spindown_plot.jl", "max_issues_repo_name": "askhamwhat/inse-fiem-2d", "max_issues_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/output_scripts/demo_spindown_plot.jl", "max_forks_repo_name": "askhamwhat/inse-fiem-2d", "max_forks_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-28T18:44:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T04:17:59.000Z", "avg_line_length": 38.0967741935, "max_line_length": 109, "alphanum_fraction": 0.6613039797, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7538675448064518}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.6\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 0f6cd296-6cb8-4a9d-a21f-02b689dfe4e9\nbegin\n\tusing PlutoUI\n\tPlutoUI.TableOfContents(aside=true)\nend\n\n# ╔═╡ 646a9fc2-3a73-4f8d-a952-2cdcf0e6287a\nbegin\n\t# Packages\n\tusing LightGraphs\n\tusing GraphPlot\n\tusing Clustering\n\tusing SparseArrays\n\tusing LinearAlgebra\n\tusing Plots\nend\n\n# ╔═╡ 7cd3af86-f459-4e4b-8e35-c29bc6966eed\nbegin\n\t# Define sizes\n\tusing Random\n\tm=[200,100,100]\n\tn=[100,200,100]\n\tdensity=[0.5,0.7,0.2]\n\tPts=Array{Any}(undef,3)\n\tRandom.seed!(421)\n\tfor i=1:3\n\t    # Generate sparse random\n\t    Pts[i]=sprand(m[i],n[i],density[i])\n\tend\n\tB=blockdiag(Pts[1],Pts[2],Pts[3])\nend\n\n# ╔═╡ 9ab98160-3e37-44c3-b219-a3e1bf95fd68\nusing Arpack\n\n# ╔═╡ 89299cb7-a4eb-48f3-b3f1-ab2b5c6cfa2e\nmd\"\"\"\n# Spectral Partitioning of Bipartite Graphs\n\nTypical example of bipartite graph is a graph obtained from a collection of documents presented as a _term $\\times$ document_  matrix.\n\n__Prerequisites__\n\nThe reader should be familiar with k-means algorithm and spectral graph partitioning theory and algorithms.\n \n__Competences__\n\nThe reader should be able to apply spectral partitioning of bipartite graphs to data clustering problems.\n\n__Credits.__ The notebook was initially derived from M.Sc. Thesis of Ivančica Mirošević.\n\"\"\"\n\n# ╔═╡ a92d0e70-479d-444e-b06d-e47d2e385b10\nmd\"\"\"\n## Definitions\n\n__Undirected bipartite graph__ $G$ is a triplet $G=(T,D,E)$, where $T=\\{t_{1},\\cdots ,t_{m}\\}$ and $D=\\{d_{1},...,d_{n}\\}$ are two sets of vertices and $E=\\{(t_{i},d_{j}):t_{i}\\in R,d_{j}\\in D\\}$, is a set of edges.\n\n $G$ is __weighted__ if there is weight $\\omega(e)$ associated with each edge $e\\in E$.\n\nFor example, $D$ is a set of documents, $T$ is a set of terms (words) and  edge $e=(t_{i},d_{j})$ exists if document $d_{j}$ contains term $t_{i}$. Weight $\\omega(e)$ can be number of appearances of the term $t_i$ in the document $d_j$.\n\nA __term-by-document-matrix__ is a matrix $A\\in\\mathbb{R}^{m\\times n}$ with $A_{ij}=\\omega((t_i,d_j))$.\n\"\"\"\n\n# ╔═╡ fddcc2a7-f718-4900-a135-764eb36496a7\nmd\"\"\"\n## Facts\n\n1. The weight matrix of $G$ is $W=\\begin{bmatrix}0 & A \\\\ A^{T} & 0 \\end{bmatrix}$.\n\n2. The Laplacian matrix of $G$ is\n\n$$L=\\begin{bmatrix} \\Delta_{1} & -A \\\\ -A^{T} & \\Delta_{2}\\end{bmatrix},$$\n\nwhere $\\Delta_1$ and $\\Delta_2$ are diagonal matrices with elements \n\n$\\Delta_{1,ii}=\\sum\\limits_{j=1}^n A_{ij},\\quad i=1,\\ldots,m,$\n\n$\\Delta_{2,jj}=\\sum\\limits_{i=1}^m A_{ij},\\quad j=1,\\ldots,n.$\n\n3. The normalized Laplacian matrix of $G$ is \n\n$$L_n=\\begin{bmatrix}\nI & -\\Delta_{1}^{-\\frac{1}{2}}A\\Delta_{2}^{-\\frac{1}{2}} \\\\\n-\\Delta_{2}^{-\\frac{1}{2}}A^T\\Delta_{1}^{-\\frac{1}{2}} & I\n\\end{bmatrix} \\equiv \n\\begin{bmatrix} I & -A_n \\\\ -A_n^T & I \\end{bmatrix}.$$\n\"\"\"\n\n# ╔═╡ b3b44560-203a-11eb-2782-170e4c12627a\nmd\"\"\"\n4. Let $\\lambda$ be an eigenvalue of $L_n$ with an eigenvector $w=\\begin{bmatrix} u \\\\ v\\end{bmatrix}$, where $u\\in \\mathbb{R}^{m}$ $v\\in\\mathbb{R}^{n}$. Then $L_n w=\\lambda w$ implies $A_n v =(1-\\lambda)u$ and $A_n^T u=(1-\\lambda)v$. Vice versa, if $(u,\\sigma,v)$ is a singular triplet of $A_n$, then $1-\\sigma$ is an eigenvalue of $L_n$ with (non-unit) eigenvector $w=\\begin{bmatrix} u \\\\ v\\end{bmatrix}$. \n\n5. The second largest singular value of $A_n$ corresponds to the second smallest eigenvalue of $L_n$, and computing the former is numerically more stable. \n\"\"\"\n\n# ╔═╡ 1be90f30-203b-11eb-34da-c3116523ec3a\nmd\"\n\n## Algorithms\n\n### Bipartitioning algorithm\n\n1. For given $A$ compute $A_{n}$.\n2. Compute singular vectors of $A_{n}$, $u^{[2]}$ and $v^{[2]}$, which correspond to the second largest singular value, $\\sigma_2(A_n)$.\n3. Assign the partitions $T=\\{T_1,T_2\\}$ and $D=\\{D_1,D_2\\}$ according to the signs of $u^{[2]}$ and $v^{[2]}$. The pair $(T,D)$ is now partitioned as $\\{(T_1,D_1),(T_2,D_2)\\}$.\n\"\n\n# ╔═╡ 5211ce2e-203b-11eb-0b6f-55e809177fb9\nmd\"\n### Recursive bipartitioning algorithm\n\n1. Compute the bipartition $\\pi=\\{(T_1,D_1),(T_2,D_2)\\}$ of $(T,D)$. Set the counter $c=2$.\n\n2. While $c<k$ repeat\n\n   - compute bipartitions of each of the subpartitions of $(T,D)$,\n   - among all $(c+1)$-subpartitions, choose the one with the smallest $\\mathop{\\mathrm{pcut}}(\\pi_{c+1})$ or $\\mathop{\\mathrm{ncut}}(\\pi_{c+1})$, respectively.\n   - Set $c=c+1$\n\n3. Stop\n\"\n\n# ╔═╡ 38333a20-203c-11eb-2b28-59e07b3e50ee\nmd\"\n### Multipartitioning algorithm\n1. For given $A$ compute $A_{n}$.\n2. Compute $k$ left and right singular vectors, $u^{[1]},\\ldots,u^{[k]}$ and $v^{[1]},\\ldots,v^{[k]}$, which correspond to $k$ largest singular values $\\sigma_1\\geq \\cdots \\geq \\sigma_k$ of $A_n$.\n3. Partition the rows of matrices $\\Delta_{1}^{-\\frac{1}{2}}\\begin{bmatrix} u^{[1]} & \\ldots & u^{[k]}\\end{bmatrix}$ and $\\Delta_{2}^{-\\frac{1}{2}}\\begin{bmatrix} v^{[1]} & \\ldots & v^{[k]}\\end{bmatrix}$ with the k-means algorithm.\n\"\n\n# ╔═╡ 1bc20329-3a6e-435d-a25c-8cce79fb7d9d\nmd\"\n## Examples\n\n### Small term-by- document matrix\n\"\n\n# ╔═╡ b9d0830a-0a33-40c1-a08a-49538cf7a879\nbegin\n\t# Make a nicer spy function\n\timport Plots.spy\n\tspy(A)=heatmap(A,yflip=true,color=:RdBu,aspectratio=1,clim=(-1,1.0)) \nend\n\n# ╔═╡ f6492dfe-faac-407f-9a0e-5dcf321a4f2d\nbegin\n\t# Sources, targets, and weights\n\tdn=[6,6,7,6,7,7]\n\ttn=[1,2,2,3,4,5]\n\twn=[3,1,3,2,2,3]\n\t[dn tn wn]\nend\n\n# ╔═╡ 1a8b6f7b-4098-4cd2-adad-8ee788b47333\nmynames=[\"Term 1\";\"Term 2\";\"Term 3\";\"Term 4\";\"Term 5\";\"Doc 1\";\"Doc 2\"]\n\n# ╔═╡ 4079aa8e-2bb5-4d51-bca8-04d0997db2bf\nbegin\n\tG=Graph(7)\n\tfor i=1:length(dn)\n\t    add_edge!(G,tn[i],dn[i])\n\tend\n\tgplot(G, nodelabel=mynames, edgelabel=wn)\nend\n\n# ╔═╡ b6d41ab1-24f2-417d-b604-3e12384e65f8\nbegin\n\t# We define some functions\n\tfunction WeightMatrix(src::Array,dst::Array,weights::Array)\n\t    n=nv(G)\n\t    sparse([src;dst],[dst;src],[weights;weights],n,n)\n\tend\n\t\n\tLaplacian(W::AbstractMatrix)=spdiagm(0=>vec(sum(W,dims=2)))-W\n\t\n\tfunction NormalizedLaplacian(L::AbstractMatrix)\n\t    D=1.0./sqrt.(diag(L))\n\t    n=length(D)\n\t    [L[i,j]*(D[i]*D[j]) for i=1:n, j=1:n]\n\tend\nend\n\n# ╔═╡ d5d8ee5d-9cce-45fc-a31b-b2ed8237cc86\nW=WeightMatrix(tn,dn,wn)\n\n# ╔═╡ 86fd4f5a-af57-490d-a17f-2339a9414057\nMatrix(W)\n\n# ╔═╡ 1f53b5cf-ab6a-4107-b53b-9ce96afcdb7f\nbegin\n\tL=Laplacian(W)\n\tMatrix(L)\nend\n\n# ╔═╡ 63403411-cca4-4d71-8a76-8dea8638f69f\nLₙ=NormalizedLaplacian(L)\n\n# ╔═╡ 3cf471bc-d316-4de9-af63-71db9b035c40\nbegin\n\tA=W[1:5,6:7]\n\tΔ₁=sqrt.(sum(A,dims=2))\n\tΔ₂=sqrt.(sum(A,dims=1))\n\tAₙ=[A[i,j]/(Δ₁[i]*Δ₂[j]) for i=1:size(A,1), j=1:size(A,2)]\nend\n\n# ╔═╡ ac0b5eda-299c-4ae2-ae78-bda92b378f19\n# The partitioning - explain the results!\nU,σ,V=svd(Aₙ)\n\n# ╔═╡ 9bf6bbca-f96c-4b38-a4fd-5188ec29a2a2\nU[:,2]\n\n# ╔═╡ aa51688c-21a0-40f4-a6d6-01d441bfd4b7\nV[:,2]\n\n# ╔═╡ 5f27f1a2-80de-41d1-b1e2-da3a99493217\nmd\"\n### Sets of points\n\"\n\n# ╔═╡ e1149b05-d594-4d75-ae56-1ce18bd0f60d\nspy(Matrix(B))\n\n# ╔═╡ b95d4070-c127-4db0-987b-5fc17421b667\n# The structure of singular vectors reflects the block\nS,rest₀=svds(B,nsv=3);\n\n# ╔═╡ 57d472c1-548d-4678-b884-85f863771aa7\n# S is a structure\nS.S\n\n# ╔═╡ 4806378b-63cb-445a-8c71-583458fce846\nbegin\n\t# Plot the first three left singular vectors\n\tk=size(B,1)\n\tx=collect(1:k)\n\tscatter(x,S.U[:,1],title=\"Left Singular Vectors\",label=\"U[:,1]\")\n\tscatter!(x,S.U[:,2],label=\"U[:,2]\",legend=:topleft)\n\tscatter!(x,S.U[:,3],label=\"U[:,3]\")\nend\n\n# ╔═╡ a08c99a3-9c10-47be-9dc6-987d92a85087\nbegin\n\t# Plot the first three right singular vectors\n\tscatter(x,S.Vt[1,:],title=\"Right Singular Vectors\",label=\"V[:,1]\")\n\tscatter!(x,S.Vt[2,:],label=\"V[:,2]\")\n\tscatter!(x,S.Vt[3,:],label=\"V[:,3]\")\nend\n\n# ╔═╡ 6888e8a9-f306-4490-9147-2460fbda4889\nbegin\n\t# Add random noise\n\tnoise=sprand(k,k,0.3)\n\tC=B+noise\n\tspy(Matrix(C))\nend\n\n# ╔═╡ 3bd5ad15-31cd-4efd-b4e3-7cf7ede3edae\nbegin\n\t# Apply random permutation to rows and columns of C\n\tD=C[randperm(k),randperm(k)]\n\tspy(Matrix(D))\nend\n\n# ╔═╡ e4487f35-5de0-492e-96f1-69318d7d8e8b\nmd\"\"\"\n__Question.__ Given D, can we recover C?\n\n__Answer.__ Yes (with spectral partitioning)!\n\"\"\"\n\n# ╔═╡ 81d99f24-82b9-4216-8d17-6a18317beb77\nSₙ,rest=svds(D,nsv=3);\n\n# ╔═╡ 8f925ff7-90b4-4fe4-a869-86dec693c0f4\n# K-means on rows of U \noutU=kmeans(Matrix(transpose(Sₙ.U)),3)\n\n# ╔═╡ d446724a-97d1-403f-baaf-d0619203f351\n# K-means on Vt\noutV=kmeans(Sₙ.Vt,3)\n\n# ╔═╡ 7572c241-dbcc-4094-97e3-ee3172255294\nsortperm(outU.assignments)\n\n# ╔═╡ 22e90c11-ba4e-4073-9f78-f3b7beb24e69\nbegin\n\t# RECOVERY of B\n\tE=D[sortperm(outU.assignments),sortperm(outV.assignments)]\n\tspy(Matrix(E))\nend\n\n# ╔═╡ Cell order:\n# ╟─0f6cd296-6cb8-4a9d-a21f-02b689dfe4e9\n# ╟─89299cb7-a4eb-48f3-b3f1-ab2b5c6cfa2e\n# ╟─a92d0e70-479d-444e-b06d-e47d2e385b10\n# ╟─fddcc2a7-f718-4900-a135-764eb36496a7\n# ╟─b3b44560-203a-11eb-2782-170e4c12627a\n# ╟─1be90f30-203b-11eb-34da-c3116523ec3a\n# ╟─5211ce2e-203b-11eb-0b6f-55e809177fb9\n# ╟─38333a20-203c-11eb-2b28-59e07b3e50ee\n# ╟─1bc20329-3a6e-435d-a25c-8cce79fb7d9d\n# ╠═646a9fc2-3a73-4f8d-a952-2cdcf0e6287a\n# ╠═b9d0830a-0a33-40c1-a08a-49538cf7a879\n# ╠═b6d41ab1-24f2-417d-b604-3e12384e65f8\n# ╠═f6492dfe-faac-407f-9a0e-5dcf321a4f2d\n# ╠═1a8b6f7b-4098-4cd2-adad-8ee788b47333\n# ╠═4079aa8e-2bb5-4d51-bca8-04d0997db2bf\n# ╠═d5d8ee5d-9cce-45fc-a31b-b2ed8237cc86\n# ╠═86fd4f5a-af57-490d-a17f-2339a9414057\n# ╠═1f53b5cf-ab6a-4107-b53b-9ce96afcdb7f\n# ╠═63403411-cca4-4d71-8a76-8dea8638f69f\n# ╠═3cf471bc-d316-4de9-af63-71db9b035c40\n# ╠═ac0b5eda-299c-4ae2-ae78-bda92b378f19\n# ╠═9bf6bbca-f96c-4b38-a4fd-5188ec29a2a2\n# ╠═aa51688c-21a0-40f4-a6d6-01d441bfd4b7\n# ╟─5f27f1a2-80de-41d1-b1e2-da3a99493217\n# ╠═7cd3af86-f459-4e4b-8e35-c29bc6966eed\n# ╠═e1149b05-d594-4d75-ae56-1ce18bd0f60d\n# ╠═9ab98160-3e37-44c3-b219-a3e1bf95fd68\n# ╠═b95d4070-c127-4db0-987b-5fc17421b667\n# ╠═57d472c1-548d-4678-b884-85f863771aa7\n# ╠═4806378b-63cb-445a-8c71-583458fce846\n# ╠═a08c99a3-9c10-47be-9dc6-987d92a85087\n# ╠═6888e8a9-f306-4490-9147-2460fbda4889\n# ╠═3bd5ad15-31cd-4efd-b4e3-7cf7ede3edae\n# ╟─e4487f35-5de0-492e-96f1-69318d7d8e8b\n# ╠═81d99f24-82b9-4216-8d17-6a18317beb77\n# ╠═8f925ff7-90b4-4fe4-a869-86dec693c0f4\n# ╠═d446724a-97d1-403f-baaf-d0619203f351\n# ╠═7572c241-dbcc-4094-97e3-ee3172255294\n# ╠═22e90c11-ba4e-4073-9f78-f3b7beb24e69\n", "meta": {"hexsha": "58674628e82abe7c7ca9faab53a8d9f1faa9d624", "size": 9947, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Module C - Applications/L12 Spectral Partitioning of Bipartite Graphs.jl", "max_stars_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_stars_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2016-06-10T09:40:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:00:08.000Z", "max_issues_repo_path": "src/Module C - Applications/L12 Spectral Partitioning of Bipartite Graphs.jl", "max_issues_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_issues_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Module C - Applications/L12 Spectral Partitioning of Bipartite Graphs.jl", "max_forks_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_forks_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2016-06-21T14:20:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T17:03:59.000Z", "avg_line_length": 29.0847953216, "max_line_length": 408, "alphanum_fraction": 0.6924700915, "num_tokens": 4689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.753867543743708}}
{"text": "#############################################################################\n# max.jl\n# Return the maximum of the two arguments. Operates elementwise over arrays.\n# All expressions and atoms are subtpyes of AbstractExpr.\n# Please read expressions.jl first.\n#############################################################################\nimport Base.max\nexport max, pos, hinge_loss\n\n# TODO: This can easily be extended to work\n### Max Atom\nstruct MaxAtom <: AbstractExpr\n    head::Symbol\n    id_hash::UInt64\n    children::Tuple{AbstractExpr, AbstractExpr}\n    size::Tuple{Int, Int}\n\n    function MaxAtom(x::AbstractExpr, y::AbstractExpr)\n        if sign(x) == ComplexSign() || sign(y) == ComplexSign()\n            error(\"Both the arguments should be real instead they are $(sign(x)) and $(sign(y))\")\n        else\n            if x.size == y.size\n                sz = x.size\n            elseif x.size == (1, 1)\n                sz = y.size\n            elseif y.size == (1, 1)\n                sz = x.size\n            else\n                error(\"Got different sizes for x as $(x.size) and y as $(y.size)\")\n            end\n        end\n\n        children = (x, y)\n        return new(:max, hash(children), children, sz)\n    end\nend\n\nfunction sign(x::MaxAtom)\n    sign_one = sign(x.children[1])\n    sign_two = sign(x.children[2])\n    if sign_one == Positive() || sign_two == Positive()\n        return Positive()\n    elseif sign_one == Negative() && sign_two == Negative()\n        return Negative()\n    else\n        return sign_one + sign_two\n    end\nend\n\n# The monotonicity\nfunction monotonicity(x::MaxAtom)\n    return (Nondecreasing(), Nondecreasing())\nend\n\n# If we have h(x) = f o g(x), the chain rule says h''(x) = g'(x)^T f''(g(x))g'(x) + f'(g(x))g''(x);\n# this represents the first term\nfunction curvature(x::MaxAtom)\n    return ConvexVexity()\nend\n\nfunction evaluate(x::MaxAtom)\n    return max.(evaluate(x.children[1]), evaluate(x.children[2]))\nend\n\n# x <= this and y <= this if max(x, y) = this\nfunction conic_form!(x::MaxAtom, unique_conic_forms::UniqueConicForms=UniqueConicForms())\n    if !has_conic_form(unique_conic_forms, x)\n        this = Variable(x.size[1], x.size[2])\n        objective = conic_form!(this, unique_conic_forms)\n        for child in x.children\n            conic_form!(this >= child, unique_conic_forms)\n        end\n        cache_conic_form!(unique_conic_forms, x, objective)\n    end\n    return get_conic_form(unique_conic_forms, x)\nend\n\nmax(x::AbstractExpr, y::AbstractExpr) = MaxAtom(x, y)\nmax(x::AbstractExpr, y::Value) = max(x, Constant(y))\nmax(x::Value, y::AbstractExpr) = max(Constant(x), y)\npos(x::AbstractExpr) = max(x, Constant(0, Positive()))\nhinge_loss(x::AbstractExpr) = pos(1 - x)\n", "meta": {"hexsha": "3b62b0b697d2b67b2a1b25f786c6939426465211", "size": 2710, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/atoms/lp_cone/max.jl", "max_stars_repo_name": "ranocha/Convex.jl", "max_stars_repo_head_hexsha": "ee58743611756e5cbb104682686031ab8d0feec4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-10-10T16:38:59.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-13T06:35:58.000Z", "max_issues_repo_path": "src/atoms/lp_cone/max.jl", "max_issues_repo_name": "ranocha/Convex.jl", "max_issues_repo_head_hexsha": "ee58743611756e5cbb104682686031ab8d0feec4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/atoms/lp_cone/max.jl", "max_forks_repo_name": "ranocha/Convex.jl", "max_forks_repo_head_hexsha": "ee58743611756e5cbb104682686031ab8d0feec4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-10-19T20:58:10.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-20T01:12:01.000Z", "avg_line_length": 32.6506024096, "max_line_length": 99, "alphanum_fraction": 0.5915129151, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7538675333024927}}
{"text": "function f_2by2!(F, x)\n    F[1] = (x[1]+3)*(x[2]^3-7)+18\n    F[2] = sin(x[2]*exp(x[1])-1)\nend\n\nfunction g_2by2!(J, x)\n    J[1, 1] = x[2]^3-7\n    J[1, 2] = 3*x[2]^2*(x[1]+3)\n    u = exp(x[1])*cos(x[2]*exp(x[1])-1)\n    J[2, 1] = x[2]*u\n    J[2, 2] = u\nend\n\nfunction nlsolvers_f(x, F, J)\n\tif F !== nothing\n\t\tf_2by2!(F, x)\n\tend\n\tif J !== nothing\n\t\tg_2by2!(J, x)\n\tend\n\tobjective_return(F, J)\nend\n\nnlsolve!(OnceDiffed(nlsolvers_f), [ -0.5; 1.4], TrustRegion(NLSolvers.Newton(), Dogleg()))\nnlsolve!(OnceDiffed(nlsolvers_f), [ -0.5; 1.4], TrustRegion(NLSolvers.Newton()))\nnlsolve!(OnceDiffed(nlsolvers_f), [ -0.5; 1.4], TrustRegion(NLSolvers.Newton(), NWI()))\n# initial convergence\nnlsolve!(OnceDiffed(nlsolvers_f), [ 0.0; 1.0], TrustRegion(NLSolvers.Newton(), Dogleg()))\nnlsolve!(OnceDiffed(nlsolvers_f), [ 0.0; 1.0], TrustRegion(NLSolvers.Newton()))\nnlsolve!(OnceDiffed(nlsolvers_f), [ 0.0; 1.0], TrustRegion(NLSolvers.Newton(), NWI()))", "meta": {"hexsha": "f0350e41717b943742ce83ba31acafab462646fb", "size": 930, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/NEqProblems/2by2.jl", "max_stars_repo_name": "pkofod/NLSolvers.jl", "max_stars_repo_head_hexsha": "65034bb76cbf91e22784bd0156f28b85416adb2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2019-09-09T19:46:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T07:14:45.000Z", "max_issues_repo_path": "problems/NEqProblems/2by2.jl", "max_issues_repo_name": "pkofod/NLSolvers.jl", "max_issues_repo_head_hexsha": "65034bb76cbf91e22784bd0156f28b85416adb2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2019-08-05T01:35:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-03T09:37:14.000Z", "max_forks_repo_path": "problems/NEqProblems/2by2.jl", "max_forks_repo_name": "pkofod/NLSolvers.jl", "max_forks_repo_head_hexsha": "65034bb76cbf91e22784bd0156f28b85416adb2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-23T19:54:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-23T19:54:29.000Z", "avg_line_length": 31.0, "max_line_length": 90, "alphanum_fraction": 0.6182795699, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7538594435333201}}
{"text": "\n\n\n\n\nmutable struct BSpline\n\tdegree   :: Int\n\tnumKnots :: Int\n\tlower    :: Float64\n\tupper    :: Float64\n\tknots    :: Array{Float64,1}\n\n\t# constructor with equally spaced interior knots\n\tfunction BSpline(nKnots,deg,lb,ub)\n\t\tknots = zeros(nKnots+2*deg)\n\t\tif (nKnots < 2*(deg+1)-1)\n\t\t\tthrow(ArgumentError(\"need at least 2*(deg+1) - 1 = $(2*(deg+1) - 1) knots\"))\n\t\tend\n\t\tif deg < 0\n\t\t\tthrow(ArgumentError(\"degree must be non-negative integer\"))\n\t\tend\n\t\tif lb > ub\n\t\t\tthrow(ArgumentError(\"require lb < ub\"))\n\t\tend\n\n\t\th = (ub - lb) / (nKnots - 1)\n\t\tfor i=1:length(knots)\n\t\t\tif i < deg + 1\n\t\t\t\tknots[i] = lb\n\t\t\telseif i > nKnots + deg \n\t\t\t\tknots[i] = ub\n\t\t\telse\n\t\t\t\tknots[i] = lb + (i-deg-1)*h\n\t\t\tend\n\t\tend\n\t\t# sp = sparsevec(zeros(num_coefs))\n\t\tnew(deg,nKnots,lb,ub,knots)\n\tend\n\n\t# constructor with user supplied interior knots\n\tfunction BSpline(knots::Array,deg::Integer)\n\t\tif !issorted(knots)\n\t\t\tthrow(ArgumentError(\"knots must be sorted\"))\n\t\tend\n\t\tlb = knots[1]\n\t\tub = knots[end]\n\t\t# extend knot vector by degree on both sides\n\t\tknots_new = [ [lb for i=1:deg]; knots; [ub for i=1:deg] ]\n\t\tnumKnots = length(knots)\t# number of INTERIOR knots \n\t\tnew(deg,numKnots,lb,ub,knots_new)\n\tend\n\nend\n\n\nfunction show(io::IO, b::BSpline)\n\tprint(io,\"BSpline object with\\n\")\n\tprint(io,\"degree: $(b.degree)\\n\")\n\tprint(io,\"number of knots: $(b.numKnots)\\n\")\n\tprint(io,\"[lower,upper]: [$(b.lower),$(b.upper)]\\n\")\n\tprint(io,\"knot vector: $(b.knots)\\n\")\nend\n\nfunction getNumKnots(b::BSpline) return b.numKnots end\nfunction getNumCoefs(b::BSpline) return b.numKnots + b.degree -1 end\nfunction getCoefs(b::BSpline) return b.knots[ (b.degree+1):(length(b.knots)-b.degree)] end\nfunction getDegree(b::BSpline) return b.degree end\n\n\n# \"\"\"\n# \tcompute value of the ``d + 1`` B-splines at ``x``\n\n# returns \n\n# ```math\n# b = \\right(B_{\\mu-d,d}(x),\\dots,B_{\\mu,d}(x)\\left)^T\n# ```\n# \"\"\"\n# function getBasis2(x::Float64,b::BSpline)\n\n# \tnum_nodes = getNumCoefs(b)\n# \tdeg       = b.degree\n\n# \tB = zeros(num_nodes)  # Bspline\n\n# end\n \n#\nfunction getBasis(x::Float64,b::BSpline)\n\t\n\tnum_nodes = getNumCoefs(b)\n\tdeg       = b.degree\n\t\n\t# tmp\n\td = 0.0\n\te = 0.0\n\n\t# create a basis function\n\t# return a colvec because currntly only CSC format \n\t# a 1-row sparse matrix is dense\n\t# bs = spzeros(num_nodes,1)\n\tbs = spzeros(num_nodes,1)\n\n\t# check x\n\tif x < b.lower\n\t\t@warn(\"x < lb: x=$x, lb=$(b.lower). be careful!\")\n\telseif x > b.upper\n\t\t@warn(\"x > ub: x=$x, ub=$(b.upper). be careful!\")\n\tend\n\n\t# get mu s.t. knot_mu < knot_{mu+1} and x in [knot_mu, knot_{mu+1})\n\t# i.e. get the index of the lower knot in the active knot span\n\n\t# fix bound behaviour\n\tif x <= b.lower\n\t\tmu = deg+1\n\telseif x>=b.upper\n\t\tmu = num_nodes\n\telse\n\t\tmu = searchsortedlast(b.knots,x) \n\tend\n\n\t# set 0-degree basis function\n\t# 0-deg basis is an indicator function\n\t# that is 1.0 in the active knot span and 0.0 else.\n\tbs[mu] = 1.0\n\n\t# loop over degrees\n\tfor k=1:deg\n\n\t\t# loop over basis functions\n\t\tfor j in mu-k:mu\n\n\t\t\t# take care of \"division by zero\" issue\n\t\t\t# dividing by zero must return 0.0\n\t\t\tif j+k <= deg +1\n\t\t\t\td = 0.0\n\t\t\telseif b.knots[j+k]-b.knots[j] == 0\n\t\t\t\td = 0.0\n\t\t\telse\n\t\t\t\td = bs[j] * (x - b.knots[j]) / (b.knots[j+k]-b.knots[j])\n\t\t\tend\n\n\t\t\tif j+1 >= num_nodes+1\n\t\t\t\te = 0.0\n\t\t\telseif b.knots[j+k+1]-b.knots[j+1] == 0\n\t\t\t\te = 0.0\n\t\t\telse\n\t\t\t\te = bs[j+1] * (b.knots[j+k+1] - x)/(b.knots[j+k+1]-b.knots[j+1])\n\t\t\tend\n\n\t\t\tbs[j] = d + e\n\n\t\tend\n\n\tend\n\treturn bs\nend\n\n# vector of points\nfunction getBasis(x::Vector{Float64},b::BSpline)\n\n\tn = length(x)\n\tnum_nodes = getNumCoefs(b)\n\tdeg       = b.degree\n\n\n\t# if you evaluate a degree 1 basis at its interior knots (\"coefs\"), you get identity\n\tif (deg == 1) && (n == num_nodes) && (sum(abs.(x .- getCoefs(b))) < 1e-8)\n\t\treturn sparse(I*1.0,n,n)\n\telse\n\t# sort x?\n\t\t\n\t\t# tmp\n\t\td = 0.0\n\t\te = 0.0\n\n\t\t# create a basis function\n\t\t# return a colvec because currntly only CSC format \n\t\t# a 1-row sparse matrix is dense\n\t\tbs = spzeros(n,num_nodes)\n\n\t\tfor xi in 1:n\n\n\t\t\t# check x\n\t\t\tif x[xi] < b.lower\n\t\t\t\t@warn(\"x < lb: x=$(x[xi]), lb=$(b.lower). be careful!\")\n\t\t\telseif x[xi] > b.upper\n\t\t\t\t@warn(\"x > ub: x=$(x[xi]), ub=$(b.upper). be careful!\")\n\t\t\tend\n\n\t\t\t# get mu s.t. knot_mu < knot_{mu+1} and x in [knot_mu, knot_{mu+1})\n\t\t\t# i.e. get the index of the lower knot in the active knot span\n\n\t\t\t# fix bound behaviour\n\t\t\tif x[xi] <= b.lower\n\t\t\t\tmu = deg+1\n\t\t\telseif x[xi]>=b.upper\n\t\t\t\tmu = num_nodes\n\t\t\telse\n\t\t\t\tmu = searchsortedlast(b.knots,x[xi]) \n\t\t\tend\n\n\t\t\t# set 0-degree basis function\n\t\t\t# 0-deg basis is an indicator function\n\t\t\t# that is 1.0 in the active knot span and 0.0 else.\n\t\t\tbs[xi,mu] = 1.0\n\n\t\t\t# loop over degrees\n\t\t\tfor k=1:deg\n\n\t\t\t\t# loop over basis functions\n\t\t\t\tfor j in mu-k:mu\n\n\t\t\t\t\t# take care of \"division by zero\" issue\n\t\t\t\t\t# dividing by zero must return 0.0\n\t\t\t\t\tif j+k <= deg +1\n\t\t\t\t\t\td = 0.0\n\t\t\t\t\telseif b.knots[j+k]-b.knots[j] == 0\n\t\t\t\t\t\td = 0.0\n\t\t\t\t\telse\n\t\t\t\t\t\td = bs[xi,j] * (x[xi] - b.knots[j]) / (b.knots[j+k]-b.knots[j])\n\t\t\t\t\tend\n\n\t\t\t\t\tif j+1 >= num_nodes+1\n\t\t\t\t\t\te = 0.0\n\t\t\t\t\telseif b.knots[j+k+1]-b.knots[j+1] == 0\n\t\t\t\t\t\te = 0.0\n\t\t\t\t\telse\n\t\t\t\t\t\te = bs[xi,j+1] * (b.knots[j+k+1] - x[xi])/(b.knots[j+k+1]-b.knots[j+1])\n\t\t\t\t\tend\n\t\t\t\t\tbs[xi,j] = d + e\n\t\t\t\tend\n\n\t\t\tend\n\t\tend\n\t\treturn bs\n\n\tend\n\t\nend", "meta": {"hexsha": "dc4153f0c9fb4bca00a10834704a31ff5d5f3595", "size": 5207, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bspline.jl", "max_stars_repo_name": "floswald/ApproXD.jl", "max_stars_repo_head_hexsha": "ad168c9a7a1522d9d4e4739a184ee34b5db36131", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2015-03-24T21:27:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T17:18:42.000Z", "max_issues_repo_path": "src/bspline.jl", "max_issues_repo_name": "floswald/ApproXD.jl", "max_issues_repo_head_hexsha": "ad168c9a7a1522d9d4e4739a184ee34b5db36131", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2015-02-23T10:28:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-12T07:25:37.000Z", "max_forks_repo_path": "src/bspline.jl", "max_forks_repo_name": "floswald/ApproXD.jl", "max_forks_repo_head_hexsha": "ad168c9a7a1522d9d4e4739a184ee34b5db36131", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2015-09-08T10:34:03.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-17T12:33:48.000Z", "avg_line_length": 21.6058091286, "max_line_length": 90, "alphanum_fraction": 0.599769541, "num_tokens": 1999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.75385944353332}}
{"text": "export IFS\n\n\"\"\"\n`IFS` is an iterated function system.\n\"\"\"\nimmutable IFS\n  funcs::Vector{AffineMap}\nend\n\nfunction IFS(args...)\n  fun_list = [ f for f in args ]\n  IFS(fun_list)\nend\n\n# Apply F to a single vector\nfunction (F::IFS)(x::Vector)\n  y = [ f(x) for f in F.funcs ]\n  return Set(y)\nend\n\n# Apply F to a list of vectors\nfunction (F::IFS)(xlist::Set)\n  A = Set{Vector{Float64}}()\n  for x in xlist\n    A = union(A,F(x))\n  end\n  return A\nend\n\nfunction show(io::IO,F::IFS)\n  nf = size(F.funcs)[1]\n  for k=1:nf\n    println(io,\"#$k:\\t$(F.funcs[k])\")\n  end\nend\n\n\"\"\"\n`square_check(F)` checks if all functions `f` in the `IFS` pass\n`square_check(f)`.\n\"\"\"\nfunction square_check(F::IFS)\n  return all(square_check(f) for f in F.funcs)\nend\n\n\n\"\"\"\n`Triangle_IFS()` returns an `IFS` that creates a Triangle triangle.\n\"\"\"\nfunction Triangle_IFS()\n  A = 0.5 * eye(2)\n  f1 = AffineMap(A,[0,0])\n  f2 = AffineMap(A,[0.5,0])\n  f3 = AffineMap(A,[0.25,0.5])\n  return IFS(f1,f2,f3)\nend\n\n\"\"\"\n`Carpet_IFS()` returns an `IFS` for Triangle's Carpet.\n\"\"\"\nfunction Carpet_IFS()\n  A = (1/3)*eye(2)\n  f1 = AffineMap(A,[0,0])\n  f2 = AffineMap(A,[0,1/3])\n  f3 = AffineMap(A,[0,2/3])\n  g1 = AffineMap(A,[1/3,0])\n  g3 = AffineMap(A,[1/3,2/3])\n  h1 = AffineMap(A,[2/3,0])\n  h2 = AffineMap(A,[2/3,1/3])\n  h3 = AffineMap(A,[2/3,2/3])\n  return IFS(f1,f2,f3,g1,g3,h1,h2,h3)\nend\n\n\n\"\"\"\n`visualize(F)` for an `IFS` draws the unit square (dotted)\nand the image of the functions in `F` (solid frames).\n\"\"\"\nfunction visualize(F::IFS)\n  clf()\n  for f in F.funcs\n    if !square_check(f)\n      warn(\"$f does not map unit square to itself.\")\n    end\n    visualize(f)\n  end\nend\n", "meta": {"hexsha": "c1543e85d648a1464b3993d322a86f233c87a57f", "size": 1626, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/IFS.jl", "max_stars_repo_name": "scheinerman/Fractory.jl", "max_stars_repo_head_hexsha": "6da2758b68869041540a252f4b4b5d8881343361", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/IFS.jl", "max_issues_repo_name": "scheinerman/Fractory.jl", "max_issues_repo_head_hexsha": "6da2758b68869041540a252f4b4b5d8881343361", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IFS.jl", "max_forks_repo_name": "scheinerman/Fractory.jl", "max_forks_repo_head_hexsha": "6da2758b68869041540a252f4b4b5d8881343361", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6896551724, "max_line_length": 67, "alphanum_fraction": 0.6193111931, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7538594347653911}}
{"text": "struct Pos\n    x::Float64\n    y::Float64\nend\n\nfunction jarvis_cross(point1::Pos, point2::Pos, point3::Pos)\n    vec1 = Pos(point2.x - point1.x, point2.y - point1.y)\n    vec2 = Pos(point3.x - point2.x, point3.y - point2.y)\n    ret_cross = vec1.x*vec2.y - vec1.y*vec2.x\n    return ret_cross*ret_cross\nend\n\nfunction jarvis_march(points::Vector{Pos})\n    hull = Vector{Pos}()\n\n    # sorting array based on leftmost point\n    sort!(points, by = item -> item.x)\n    push!(hull, points[1])\n\n    i = 1\n    curr_point = points[2]\n\n    # Find cross product between points\n    curr_product = jarvis_cross(Pos(0,0), hull[1], curr_point)\n    while (curr_point != hull[1])\n        for point in points\n                product = 0.0\n            if (i == 1)\n                if (hull[i] != point)\n                    product = jarvis_cross(Pos(0,0), hull[i], point)\n                end\n            else\n                if (hull[i] != point && hull[i-1] != point)\n                    product = jarvis_cross(hull[i-1], hull[i], point)\n                end\n            end\n            if (product > curr_product)\n                curr_point = point\n                curr_product = product\n            end\n        end\n        push!(hull, curr_point)\n        curr_product = 0\n        i += 1\n    end\n\n    return hull\nend\n\nfunction main()\n\n    points = [Pos(2,1.5), Pos(1, 1), Pos(2, 4), Pos(3, 1)]\n    hull = jarvis_march(points)\n    println(hull)\nend\n\nmain()\n", "meta": {"hexsha": "fac1531282be7fbf7594ce231def02a8fe5b49d8", "size": 1432, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "contents/jarvis_march/code/julia/jarvis.jl", "max_stars_repo_name": "atocil/algorithm-archive", "max_stars_repo_head_hexsha": "2eb30cb103508c9efb91621564bd3114eb49d3af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1975, "max_stars_repo_stars_event_min_datetime": "2018-04-28T13:46:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:14:47.000Z", "max_issues_repo_path": "contents/jarvis_march/code/julia/jarvis.jl", "max_issues_repo_name": "atocil/algorithm-archive", "max_issues_repo_head_hexsha": "2eb30cb103508c9efb91621564bd3114eb49d3af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 632, "max_issues_repo_issues_event_min_datetime": "2018-04-28T10:27:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T20:38:53.000Z", "max_forks_repo_path": "contents/jarvis_march/code/julia/jarvis.jl", "max_forks_repo_name": "atocil/algorithm-archive", "max_forks_repo_head_hexsha": "2eb30cb103508c9efb91621564bd3114eb49d3af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 433, "max_forks_repo_forks_event_min_datetime": "2018-04-27T22:50:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T06:16:03.000Z", "avg_line_length": 24.6896551724, "max_line_length": 69, "alphanum_fraction": 0.5335195531, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7538594186298523}}
{"text": "\"\"\"\n    ElementVectorSampler\n\nA sampler that makes it easy to draw signed element vectors (of a specified dimension)\nuniformly at random.\n\nNotice that, w.p. `1/2`, each element vector is multiplied by `-1`. This is useful for\nimplementing random walks.\n\nAn `element vector` `e_i` is a vector in which the `i`th element is a `1`, and all other\nelements are `0`.\n\n##### Fields\n- `dimension::Int` : the dimension (i.e. length) of element vectors.\n\"\"\"\nstruct ElementVectorSampler <: Sampleable{Multivariate, Discrete}\n    dimension::Int\nend\n\n\"\"\"\n    EVecSampler\n\nAlias for `ElementVectorSampler`\n\"\"\"\nEVecSampler = ElementVectorSampler\n\n\"\"\"\n    Base.show(io::IO, elementvectorsampler::ElementVectorSampler) -> nothing\n\nShow an `ElementVectorSampler` in a human-friendly manner.\n\"\"\"\nfunction Base.show(io::IO, elementvectorsampler::ElementVectorSampler)\n    println(io, typeof(elementvectorsampler))\n    println(io, \" dimension: \", elementvectorsampler.dimension)\n    return nothing\nend\n\n\"\"\"\n    Base.rand(rng::AbstractRNG, elementvectorsampler::ElementVectorSampler) -> Vector{Int}\n\nReturn a vector with a specified `length` and with exactly one element equal to `1`.\n\"\"\"\nfunction Base.rand(rng::AbstractRNG, elementvectorsampler::ElementVectorSampler)\n    vector = zeros(Int, elementvectorsampler.dimension)\n    # pick an index to replace with 1 or -1 (uses multiple dispatch)\n    vector[rand(1:elementvectorsampler.dimension)] = 1*rand((-1,1))\n    return vector\nend\n", "meta": {"hexsha": "bdbaa703d449b4d2f627518dee71aee7d6a293bd", "size": 1463, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Samplers/elementvectorsamplers.jl", "max_stars_repo_name": "LoganDGraham/StochasticProcesses", "max_stars_repo_head_hexsha": "c3f9947d9f93c9d8397664ed3acf93c8bf7da444", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-11-15T19:57:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T22:42:14.000Z", "max_issues_repo_path": "src/Samplers/elementvectorsamplers.jl", "max_issues_repo_name": "LoganDGraham/StochasticProcesses", "max_issues_repo_head_hexsha": "c3f9947d9f93c9d8397664ed3acf93c8bf7da444", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-02T16:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-14T17:56:52.000Z", "max_forks_repo_path": "src/Samplers/elementvectorsamplers.jl", "max_forks_repo_name": "LoganDGraham/StochasticProcesses", "max_forks_repo_head_hexsha": "c3f9947d9f93c9d8397664ed3acf93c8bf7da444", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8571428571, "max_line_length": 90, "alphanum_fraction": 0.7409432673, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940925, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7538311969063574}}
{"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 7056a580-e8b6-11ea-2ac9-ad6ced139615\nbegin \n    using Random\n    using UnPack\n\tusing Plots\n\tusing Statistics\n\tusing ActuaryUtilities\n\tusing ThreadsX # for easy multithreading\nend\n\n# ╔═╡ f04b8ce0-ea39-11ea-05ad-a996c592cc82\nmd\"\"\"\n# AAA ESG Exploration Tool\nThis reactive notebook explores the sensitivity of the American Academy of Actuaries' (AAA) [Economic Scenario Generator (ESG)](https://www.actuary.org/content/economic-scenario-generators) to changing parameters.  \n\nIt's a simple demo intended to be informative about the underlying model producing the interest rates, as well as showcase some aspects of the Julia ecosystem:\n- **Reactive Notebooks** interact with and learn from your data in ways traditional notebooks won't let you. \n   - Cell order doesn't matter!\n   - Hover over the cells and click the eye icon to expand the cell to see any hidden code cells.\n- **Performance** - Work with thousands of simulations and visualize them in realtime\n- **Syntax** - Expand some of the code cells below to see code that looks more like math, e.g. this line of code:\n```julia\nα_τ =(1-β₂) * α_τ + β₂ * τ₂ + ϕ * (log(r₁) - log(τ₁)) + σ₂ * shock_short * r₁^θ\n```\n- **Dynamic and robust plotting libaraies** - `Plots.jl` in this case\n\n\n\n\"\"\"\n\n# ╔═╡ 018237f0-ea3c-11ea-387e-abf5110ac1fa\nmd\"\"\"\n## Interactive ESG\n### Interactive Parameters:\nYou can edit these and watch the results change in realtime.\n\"\"\"\n\n# ╔═╡ dabece20-ea37-11ea-2e6a-61eda948928f\n@bind n_scenarios html\"\"\"\n\tNumber of Scenarios: <input type='number' min='1' max='5' value='200' />\n    \n\t\"\"\"\n\n# ╔═╡ 63507e40-ea34-11ea-00c3-31bd881aa1bc\n@bind τ₁ html\"\"\"\n\tLong Term Mean Reversion Point <input type='range' min='0.0' max='0.1' value='0.035' step='0.005'\n\toninput=\\\"document.getElementById('fPrice').innerHTML = this.value\\\" />\n        <label id='fPrice'>0.035</label>\n\t\"\"\"\n\n# ╔═╡ 13c9baf0-ea37-11ea-16d5-f9f87c35e4f4\n@bind vol html\"\"\"\n\tProcess Volatility <input type='range' min='0.05' max='0.3' value='0.11489' step='0.005'\n\toninput=\\\"document.getElementById('fPrice').innerHTML = this.value\\\" />\n        <label id='fPrice'>0.11489</label>\n\t\"\"\"\n\n# ╔═╡ 2cc3d3b0-ea3c-11ea-2c4f-4bd1db712846\nmd\"### Scenario Visualization\"\n\n# ╔═╡ 9a6a036e-b4f1-40a8-b3ea-724a1542fb26\nmd\"\n#### Long Rate Statistics:\n\"\n\n# ╔═╡ 56f67070-ea3c-11ea-31f5-b7d1f7182a31\nmd\"This histogram was inspired by the article [Illuminating the Low Interest Peril](https://www.soa.org/globalassets/assets/library/newsletters/financial-reporter/2020/july/fr-2020-iss-07.pdf) in the July 2020 Financial Reporter:\"\n\n# ╔═╡ 844a9e50-f128-11ea-10b1-a1d7792c8fc4\nmd\"Example of one of the the scenarios:\"\n\n# ╔═╡ 23cba4a0-ea3b-11ea-2b62-8dfc856875b7\nmd\"\"\"\n# Notebook Details\nThe following cells contain the code that generates the parameters and scenarios\n\n## Deploying a dashboard/tool like this\n\nYou likely had to download it and run it yourself because [JuliaActuary](https://juliaactuary.org/) doesn't have a server laying around for you to run stochastic simulations on!\n\nHowever, as you can see it's running over HTTP so would be straightforward to take something like this and make it an end-user dashboard.\n\"\"\"\n\n# ╔═╡ f15e18e0-ea3a-11ea-3868-d9236a4810a1\nmd\"The starting curve is based on 12/31/2020:\"\n\n# ╔═╡ 79cfe060-e9f4-11ea-2fc8-b769419cc4fd\nstart_curve = [0.0155, 0.0160, 0.0159, 0.0158, 0.0162, 0.0169, 0.0183, 0.0192, 0.0125, 0.0239]\n\n# ╔═╡ 49419d10-e861-11ea-36e0-e19ece503681\n# this is a function which takes a couple of input parameters and returns a named \n# tuple with all of the required parameters for the AAA ESG\nfull_params(τ₁=0.035,vol=0.11489\n\t) = (\n\tτ₁ = τ₁,   # Long term rate (LTR) mean reversion\n\tβ₁ = 0.00509, # Mean reversion strength for the log of the LTR\n\tθ = 1,\n\tτ₂ = 0.01,    # Mean reversion point for the slope\n\tβ₂ = 0.02685, # Mean reversion strength for the slope\n\tσ₂ = 0.04148, # Volatitlity of the slope\n\tτ₃ = 0.0287,  # mean reversion point for the vol of the log of LTR\n\tβ₃ = 0.04001, # mean reversion strength for the log of the vol of the log of LTR\n\tσ₃ = vol, # vol of the stochastic vol process\n\tρ₁₂ = -0.19197, # correlation of shocks to LTR and slope (long - short)\n\tρ₁₃ = 0.0,  # correlation of shocks to long rate and volatility\n\tρ₂₃ = 0.0,  # correlation of shocks to slope and volatility\n\tψ = 0.25164,\n\tϕ = 0.0002,\n\tr₂_min = 0.01, # soft floor on the short rate\n\tr₂_max = 0.4, # unused - maximum short rate\n\tr₁_min = 0.015, # soft floor on long rate before random shock\n\tr₁_max = 0.18, # soft cap on long rate before random shock\n\tκ = 0.25, # unused - when the short rate would be less than r₂_min it was κ * long \n\tγ = 0.0, # unused - don't change from zero\n\tσ_init = 0.0287,\n\tmonths = 12 * 30,\n\trate_floor = 0.0001, # absolute rate floor\n\tmaturities = [0.25,0.5,1,2,3,5,7,10,20,30],\n)\n\n# ╔═╡ 1a5bb1b0-ea33-11ea-3514-e1c85b65d356\nparams = full_params(τ₁,vol)\n\n# ╔═╡ 4ff1ccc0-e8b6-11ea-20be-d7992829086d\n# This replicates the American Academy of Actuaries' scenario generator v7.1.202005\n# No guarantees on the output!\nfunction scenario(start_curve,params)\n\t\n\t# unpack the params into the named variables\n    @unpack τ₁,β₁,θ,τ₂,β₂,σ₂,τ₃,β₃,σ₃,ρ₁₂,ρ₁₃,ρ₂₃,ψ,ϕ,r₂_min,r₂_max,r₁_min,r₁_max,κ,γ,σ_init,months,rate_floor,maturities = params\n\t\n    # some constants\n\tconst1 =  √(1-ρ₁₂^2)\n\tconst2 = (ρ₂₃-ρ₁₂*ρ₁₃)/(const1)\n\tconst3 = √(1-((ρ₂₃ - ρ₁₂*ρ₁₃)^2)/(1ρ₁₂^2)-ρ₁₃^2)\n\tconst4 = β₃ * log(τ₃)\n\tconst5 = β₁ * log(τ₁)\n\t\n\t# Nelson Siegel interpolation factors\n\tns_interp = [(1 - exp(-0.4 * m)) / ( 0.4 * m) for m in maturities]\n\t\n\t\n\t# containers for hot values\n\trates = zeros(months,10) # allocate initial \n\tshock = zeros(3)\n\tns_fitted = zeros(10)\n\t\n\t# initial values\n\tv_τ = log(σ_init) # long rate log vol\n\tσ_longvol = σ_init\n\tα_τ = start_curve[9]-start_curve[3]\n\tpertubation = 1.0\n\t\n\tr₁ = start_curve[9]\n\tr₂ = max(r₂_min,start_curve[3])\n    \n    b₁ = (r₂ - r₁) / (ns_interp[3] - ns_interp[9])\n    b₀ = r₂ - b₁ * ns_interp[3]\n\n\t\n\tns_fitted .= b₀ .+ b₁ .* ns_interp \n\tstart_diff = ns_fitted .- start_curve \n\t\n\tfor month in 1:months\n\n\t\t## Correlated Normals\n        randn!(shock)\n        # shock .= norms'[:,month]\n\t\tshock_long  = shock[1]\n\t\tshock_short = shock[1] * ρ₁₂ + shock[2] * const1\n\t\tshock_vol   = shock[1] * ρ₁₃ + shock[2] * const2 + shock[3] * const3\n\t\t\t\n\t\t## Generator Process\n\t\tv_τ =(1-β₃) * v_τ + const4 + σ₃ * shock_vol\n\t\tσ_longvol = exp(v_τ)\n\t\t\n        # moved this after r₁ because it uses the prior val\n        \n        \n        α_τ_prior = α_τ\n        α_τ =(1-β₂) * α_τ + β₂ * τ₂ + ϕ * (log(r₁) - log(τ₁)) + σ₂ * shock_short * r₁^θ\n\t\t\n        ## Generator Results\n        \n        r_pre = (1-β₁)*log(r₁)+const5+ψ*(τ₂-α_τ_prior)\n\t\tr₁ = exp(clamp(r_pre,log(r₁_min),log(r₁_max)) + σ_longvol * shock_long)\n\t\t\n\t\t\n\t\tr₂ = max(r₁ - α_τ,r₂_min)\n        \n        \n\t\t## Nelson-Siegel Fitted Curve\n\t\tns_fitted .= b₀ .+ b₁ .* ns_interp\n\t\t\n        b₁ = (r₂ - r₁) / (ns_interp[3] - ns_interp[9])\n        b₀ = r₂ - b₁ * ns_interp[3]\n        \n        ## Fully Interpolated Curve\n\t\t\n\t\trates[month,:] .= max.(rate_floor, ns_fitted .- pertubation .* start_diff)\n\t\t\n\t\t# Update values for next loop\n\t\tpertubation = max(0.0,pertubation - 1/12)\n\n\n\tend\n\t\n\treturn rates\nend\n\n# ╔═╡ c5078e00-e8b6-11ea-105b-9731d9852664\nscenarios = ThreadsX.map(i -> scenario(start_curve,params), 1:n_scenarios);\n\n# ╔═╡ 076facc0-e9f5-11ea-2fa5-91cfaa965d08\n# note that the CTE function requires ActuaryUtilities v2.1 or higher\nlet\n\t# average and CTE70 and CTE98 of 20 year rates\n\tstats = ThreadsX.map(s -> (\n\t\t\tmean= mean(s[:,9]),\n\t\t\tCTE70=CTE(s[:,9],.7,rev=true),\n\t\t\tCTE98=CTE(s[:,9],.98,rev=true)\n\t\t\t),scenarios)\n\th1 = histogram(\n\t\t[x.mean for x in stats],  \n\t\tlabel=\"\",\n\t\torientation = :horizontal,\n\t\talpha=0.5,\n\t\tylim = (0.,.1),\n\t\tylabel=\"20-Year Interset Rate\",\n\t\txlim=(0,(n_scenarios ÷ 20)),\n\t\txtick=:none,\n\t\tgrid=false,\n\t\ttitle=\"Mean\",\n\t\tbins = 0.:0.0025:.1,\n\t)\n \t\th2 = histogram(\n\t\t[x.CTE70 for x in stats],\n\t\talpha=0.5,\n\t\ttitle=\"CTE70\",\n\t\tlabel=\"\",\n\t\tylim = (0.,.1),\n\t\txlim=(0,(n_scenarios ÷ 20)),\n\t\txtick=:none,\n\t\tytick=:none,\n\t\torientation = :horizontal,\n\t\tbins = 0.:0.0025:.1,\n\t)\n\t \th3 = histogram(\n\t\t[x.CTE98 for x in stats],\n\t\talpha=0.5,\n\t\ttitle=\"CTE98\",\n\t\tlabel=\"\",\n\t\tylim = (0.,.1),\n\t\txlim=(0,(n_scenarios ÷ 20)),\n\t\txtick=:none,\n\t\t\t\tytick=:none,\n\t\torientation = :horizontal,\n\t\t\n\t\tbins = 0.:0.0025:.1,\n\t)\n\tplot([h1,h2,h3]...,layout=(1,3))\nend\n\n# ╔═╡ 7f7a2280-ea2d-11ea-2ee8-79bc4c3a72ec\n let\n \tp = plot(legend=false,title=\"Long Rate Paths\",ylim=(0,.15))\n\n \tfor s in scenarios\n \t\tplot!(p,s[:,9], color=:blue, alpha=0.05)\n \tend\n \tp\n end\n\n# ╔═╡ 783904d0-f128-11ea-22f9-43d6dc7b8439\nscenarios[1]\n\n# ╔═╡ c684fec1-0e7c-4c74-be96-c9b1d8c4c9af\nplot(sum(hcat([s[:,9] for s in scenarios]...),dims=2) ./ n_scenarios)\n\n# ╔═╡ 69730d30-ea37-11ea-05be-8350df76fd06\nmd\"\"\"\nThe same disclaimer from the Academy applies:\n\n    From time to time, the American Academy of Actuaries makes available through its website or other means various scenarios and tools. The Academy takes reasonable steps to develop such scenarios and tools consistent with accepted actuarial principles and practices. However, the Academy does not warranty these scenarios and tools as fit for use in any respect, and no warranty should be assumed or implied by any individual. Actuaries, insurers, regulators and other parties use the Academy's scenarios and tools at their own risk. The Academy disclaims all responsibility for any party's use or misuse of its scenarios or tools and for any work product generated through use or misuse of the scenarios and tools.\n\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nActuaryUtilities = \"bdd23359-8b1c-4f88-b89b-d11982a786f4\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nRandom = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\nStatistics = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\nThreadsX = \"ac1d9e8a-700a-412c-b207-f0111f4b6c0d\"\nUnPack = \"3a884ed6-31ef-47d7-9d2a-63182c4928ed\"\n\n[compat]\nActuaryUtilities = \"~2.2.3\"\nPlots = \"~1.19.1\"\nThreadsX = \"~0.1.7\"\nUnPack = \"~1.0.2\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[ActuaryUtilities]]\ndeps = [\"Dates\", \"ForwardDiff\", \"QuadGK\", \"Roots\", \"StatsBase\", \"Yields\"]\ngit-tree-sha1 = \"b2bd57203bd96fc7026a719473bae0287ea311a2\"\nuuid = \"bdd23359-8b1c-4f88-b89b-d11982a786f4\"\nversion = \"2.2.3\"\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[ArgCheck]]\ngit-tree-sha1 = \"dedbbb2ddb876f899585c4ec4433265e3017215a\"\nuuid = \"dce04be8-c92d-5529-be00-80e4d2c0e197\"\nversion = \"2.1.0\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[AxisAlgorithms]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"a4d07a1c313392a77042855df46c5f534076fab9\"\nuuid = \"13072b0f-2c55-5437-9ae7-d433b7a33950\"\nversion = \"1.0.0\"\n\n[[BangBang]]\ndeps = [\"Compat\", \"ConstructionBase\", \"Future\", \"InitialValues\", \"LinearAlgebra\", \"Requires\", \"Setfield\", \"Tables\", \"ZygoteRules\"]\ngit-tree-sha1 = \"e239020994123f08905052b9603b4ca14f8c5807\"\nuuid = \"198e06fe-97b7-11e9-32a5-e1d131e6ad66\"\nversion = \"0.3.31\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Baselet]]\ngit-tree-sha1 = \"aebf55e6d7795e02ca500a689d326ac979aaf89e\"\nuuid = \"9718e550-a3fa-408a-8086-8db961cd8217\"\nversion = \"0.1.1\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c3598e525718abcc440f69cc6d5f60dda0a1b61e\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.6+5\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"e2f47f6d8337369411569fd45ae5753ca10394c6\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.0+6\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"bdc0937269321858ab2a4f288486cb258b9a0af7\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.3.0\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\", \"StaticArrays\"]\ngit-tree-sha1 = \"ed268efe58512df8c7e224d2e170afd76dd6a417\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.13.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[CommonSolve]]\ngit-tree-sha1 = \"68a0743f578349ada8bc911a5cbd5a2ef6ed6d1f\"\nuuid = \"38540f10-b2f7-11e9-35d8-d573e4eb0ff2\"\nversion = \"0.2.0\"\n\n[[CommonSubexpressions]]\ndeps = [\"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"7b8a93dba8af7e3b42fecabf646260105ac373f7\"\nuuid = \"bbf7d656-a473-5ed7-a52c-81e309532950\"\nversion = \"0.3.0\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"344f143fa0ec67e47917848795ab19c6a455f32c\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.32.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[CompositionsBase]]\ngit-tree-sha1 = \"455419f7e328a1a2493cabc6428d79e951349769\"\nuuid = \"a33af91c-f02d-484b-be07-31d278c5ca2b\"\nversion = \"0.1.1\"\n\n[[ConstructionBase]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"f74e9d5388b8620b4cee35d4c5a618dd4dc547f4\"\nuuid = \"187b0558-2788-49d3-abe0-74a17ed4e7c9\"\nversion = \"1.3.0\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"ee400abb2298bd13bfc3df1c412ed228061a2385\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.7.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"4437b64df1e0adccc3e5d1adbc3ac741095e4677\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.9\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DefineSingletons]]\ngit-tree-sha1 = \"77b4ca280084423b728662fe040e5ff8819347c5\"\nuuid = \"244e2a9f-e319-4986-a169-4d1fe445cd52\"\nversion = \"0.1.1\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[DiffResults]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"c18e98cba888c6c25d1c3b048e4b3380ca956805\"\nuuid = \"163ba53b-c6d8-5494-b064-1a9d43ac40c5\"\nversion = \"1.0.3\"\n\n[[DiffRules]]\ndeps = [\"NaNMath\", \"Random\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"85d2d9e2524da988bffaf2a381864e20d2dae08d\"\nuuid = \"b552c78f-8df3-52c6-915a-8e097449b14b\"\nversion = \"1.2.1\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"a32185f5428d3986f47c2ab78b1f216d5e6cc96f\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.5\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"92d8f9f208637e8d2d28c664051a00569c01493d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.1.5+1\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"LibVPX_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"3cc57ad0a213808473eafef4845a74766242e05f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.3.1+4\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"35895cf184ceaab11fd778b4590144034a167a2f\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.1+14\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[ForwardDiff]]\ndeps = [\"CommonSubexpressions\", \"DiffResults\", \"DiffRules\", \"LinearAlgebra\", \"NaNMath\", \"Printf\", \"Random\", \"SpecialFunctions\", \"StaticArrays\"]\ngit-tree-sha1 = \"b5e930ac60b613ef3406da6d4f42c35d8dc51419\"\nuuid = \"f6369f11-7733-5829-9624-2563aa707210\"\nversion = \"0.10.19\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"cbd58c9deb1d304f5a245a0b7eb841a2560cfec6\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.1+5\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"dba1e8614e98949abfa60480b13653813d8f0157\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+0\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"182da592436e287758ded5be6e32c406de3a2e47\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.58.1\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"d59e8320c2747553788e4fc42231489cc602fa50\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.58.1+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"7bf67e9a481712b3dbe9cb3dac852dc4b1162e02\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"44e3b40da000eab4ccb1aecdc4801c040026aeb5\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.13\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[InitialValues]]\ngit-tree-sha1 = \"26c8832afd63ac558b98a823265856670d898b6c\"\nuuid = \"22cec73e-a1b8-11e9-2c92-598750a2cf9c\"\nversion = \"0.2.10\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[Interpolations]]\ndeps = [\"AxisAlgorithms\", \"ChainRulesCore\", \"LinearAlgebra\", \"OffsetArrays\", \"Random\", \"Ratios\", \"Requires\", \"SharedArrays\", \"SparseArrays\", \"StaticArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"61aa005707ea2cebf47c8d780da8dc9bc4e0c512\"\nuuid = \"a98d9a8b-a2ab-59e6-89dd-64a1c18fca59\"\nversion = \"0.13.4\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a4b12a1bd2ebade87891ab7e36fdbce582301a92\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.6\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[LibVPX_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"12ee7e23fa4d18361e7c2cde8f8337d4c3101bc7\"\nuuid = \"dd192d2f-8180-539f-9fb4-cc70b1dcf69a\"\nversion = \"1.10.0+0\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"761a393aeccd6aa92ec3515e428c26bf99575b3b\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+0\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"DocStringExtensions\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"7bd5f6565d80b6bf753738d2bc40a5dfea072070\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.2.5\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"0fb723cd8c45858c22169b2e42269e53271a6df7\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.7\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[MicroCollections]]\ndeps = [\"BangBang\", \"Setfield\"]\ngit-tree-sha1 = \"e991b6a9d38091c4a0d7cd051fcb57c05f98ac03\"\nuuid = \"128add7d-3638-4c79-886c-908ea0c25c34\"\nversion = \"0.1.0\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"4ea90bd5d3985ae1f9a908bd4500ae88921c5ce7\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.0\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[OffsetArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"c0f4a4836e5f3e0763243b8324200af6d0e0f90c\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.5\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+0\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"477bf42b4d1496b454c10cce46645bb5b8a0cf2c\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.2\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"501c20a63a34ac1d015d5304da0e645f42d91c9f\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.0.11\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\"]\ngit-tree-sha1 = \"1e72752052a3893d0f7103fbac728b60b934f5a5\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.19.4\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[QuadGK]]\ndeps = [\"DataStructures\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"12fbe86da16df6679be7521dfb39fbc861e1dc7b\"\nuuid = \"1fd47b50-473d-5c70-9696-f719f8f3bcdc\"\nversion = \"2.4.1\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Ratios]]\ngit-tree-sha1 = \"37d210f612d70f3f7d57d488cb3b6eff56ad4e41\"\nuuid = \"c84ed2f1-dad5-54f0-aa8e-dbefe2724439\"\nversion = \"0.4.0\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"b3fb709f3c97bfc6e948be68beeecb55a0b340ae\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.1\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"2a7a2469ed5d94a98dea0e85c46fa653d76be0cd\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.3.4\"\n\n[[Reexport]]\ngit-tree-sha1 = \"5f6c21241f0f655da3952fd60aa18477cf96c220\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.1.0\"\n\n[[Referenceables]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"e681d3bfa49cd46c3c161505caddf20f0e62aaa9\"\nuuid = \"42d2dcc6-99eb-4e98-b66c-637b7d73030e\"\nversion = \"0.1.2\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[Roots]]\ndeps = [\"CommonSolve\", \"Printf\"]\ngit-tree-sha1 = \"52a5d9ab3fc404993593c79576ce2af68b965ede\"\nuuid = \"f2b01f46-fcfa-551c-844a-d8ac1e96c665\"\nversion = \"1.1.0\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[Setfield]]\ndeps = [\"ConstructionBase\", \"Future\", \"MacroTools\", \"Requires\"]\ngit-tree-sha1 = \"fca29e68c5062722b5b4435594c3d1ba557072a3\"\nuuid = \"efcf1570-3423-57d1-acb7-fd33fddbac46\"\nversion = \"0.7.1\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"LogExpFunctions\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"508822dca004bf62e210609148511ad03ce8f1d8\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.6.0\"\n\n[[SplittablesBase]]\ndeps = [\"Setfield\", \"Test\"]\ngit-tree-sha1 = \"edef25a158db82f4940720ebada14a60ef6c4232\"\nuuid = \"171d559e-b47b-412a-8079-5efa626c420e\"\nversion = \"0.1.13\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3240808c6d463ac46f1c1cd7638375cd22abbccb\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.12\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"1958272568dc176a1d881acb797beb909c785510\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.0.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"fed1ec1e65749c4d96fc20dd13bea72b55457e62\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.9\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"000e168f5cc9aded17b6999a560b7c11dda69095\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.0\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"d0c690d37c73aeb5ca063056283fde5585a41710\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.5.0\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[ThreadsX]]\ndeps = [\"ArgCheck\", \"BangBang\", \"ConstructionBase\", \"InitialValues\", \"MicroCollections\", \"Referenceables\", \"Setfield\", \"SplittablesBase\", \"Transducers\"]\ngit-tree-sha1 = \"269f5c1955c1194086cf6d2029aa4a0b4fb8018b\"\nuuid = \"ac1d9e8a-700a-412c-b207-f0111f4b6c0d\"\nversion = \"0.1.7\"\n\n[[Transducers]]\ndeps = [\"Adapt\", \"ArgCheck\", \"BangBang\", \"Baselet\", \"CompositionsBase\", \"DefineSingletons\", \"Distributed\", \"InitialValues\", \"Logging\", \"Markdown\", \"MicroCollections\", \"Requires\", \"Setfield\", \"SplittablesBase\", \"Tables\"]\ngit-tree-sha1 = \"34f27ac221cb53317ab6df196f9ed145077231ff\"\nuuid = \"28d57a85-8fef-5791-bfe6-a80928e7c999\"\nversion = \"0.4.65\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[UnPack]]\ngit-tree-sha1 = \"387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b\"\nuuid = \"3a884ed6-31ef-47d7-9d2a-63182c4928ed\"\nversion = \"1.0.2\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\"]\ngit-tree-sha1 = \"2839f1c1296940218e35df0bbb220f2a79686670\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.18.0+4\"\n\n[[WoodburyMatrices]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"59e2ad8fd1591ea019a5259bd012d7aee15f995c\"\nuuid = \"efce3f68-66dc-5838-9240-27a6d6f5f9b6\"\nversion = \"0.5.3\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Yields]]\ndeps = [\"ForwardDiff\", \"Interpolations\"]\ngit-tree-sha1 = \"be78b60fee8884d22cad5f758fc3499c8bc58dc5\"\nuuid = \"d7e99b2f-e7f3-4d9e-9f01-2338fc023ad3\"\nversion = \"0.5.0\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[ZygoteRules]]\ndeps = [\"MacroTools\"]\ngit-tree-sha1 = \"9e7a1e8ca60b742e508a315c17eef5211e7fbfd7\"\nuuid = \"700de1a5-db45-46bc-99cf-38207098b444\"\nversion = \"0.2.1\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"acc685bcf777b2202a904cdcb49ad34c2fa1880c\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.14.0+4\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7a5780a0d9c6864184b3a2eeeb833a0c871f00ab\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"0.1.6+4\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d713c1ce4deac133e3334ee12f4adff07f81778f\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2020.7.14+2\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"487da2f8f2f0c8ee0e83f39d13037d6bbf0a45ab\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.0.0+3\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─f04b8ce0-ea39-11ea-05ad-a996c592cc82\n# ╟─018237f0-ea3c-11ea-387e-abf5110ac1fa\n# ╟─dabece20-ea37-11ea-2e6a-61eda948928f\n# ╟─63507e40-ea34-11ea-00c3-31bd881aa1bc\n# ╟─13c9baf0-ea37-11ea-16d5-f9f87c35e4f4\n# ╟─2cc3d3b0-ea3c-11ea-2c4f-4bd1db712846\n# ╟─9a6a036e-b4f1-40a8-b3ea-724a1542fb26\n# ╟─076facc0-e9f5-11ea-2fa5-91cfaa965d08\n# ╟─7f7a2280-ea2d-11ea-2ee8-79bc4c3a72ec\n# ╟─56f67070-ea3c-11ea-31f5-b7d1f7182a31\n# ╟─844a9e50-f128-11ea-10b1-a1d7792c8fc4\n# ╟─783904d0-f128-11ea-22f9-43d6dc7b8439\n# ╟─23cba4a0-ea3b-11ea-2b62-8dfc856875b7\n# ╠═7056a580-e8b6-11ea-2ac9-ad6ced139615\n# ╟─f15e18e0-ea3a-11ea-3868-d9236a4810a1\n# ╠═79cfe060-e9f4-11ea-2fc8-b769419cc4fd\n# ╟─1a5bb1b0-ea33-11ea-3514-e1c85b65d356\n# ╠═49419d10-e861-11ea-36e0-e19ece503681\n# ╠═4ff1ccc0-e8b6-11ea-20be-d7992829086d\n# ╠═c5078e00-e8b6-11ea-105b-9731d9852664\n# ╠═c684fec1-0e7c-4c74-be96-c9b1d8c4c9af\n# ╟─69730d30-ea37-11ea-05be-8350df76fd06\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "4c37c02165c1c95a364c63391e4987ed785e96fd", "size": 45067, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "AAA_ESG.jl", "max_stars_repo_name": "JeannotJeannot/Learn", "max_stars_repo_head_hexsha": "b6a40a12772de06655e1c7ae4d7c1791a01e0c48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-10-03T02:20:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T20:50:17.000Z", "max_issues_repo_path": "AAA_ESG.jl", "max_issues_repo_name": "JeannotJeannot/Learn", "max_issues_repo_head_hexsha": "b6a40a12772de06655e1c7ae4d7c1791a01e0c48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-10-02T00:16:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T19:34:34.000Z", "max_forks_repo_path": "AAA_ESG.jl", "max_forks_repo_name": "JeannotJeannot/Learn", "max_forks_repo_head_hexsha": "b6a40a12772de06655e1c7ae4d7c1791a01e0c48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-03-13T19:36:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T13:49:42.000Z", "avg_line_length": 33.4573125464, "max_line_length": 717, "alphanum_fraction": 0.7264961058, "num_tokens": 20110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7538311851355597}}
{"text": "function checkdiff(f, δf, x0...)\n    x = [x0...]\n    y0 = f(x...)\n    @assert length(y0) == 1 \"Scalar functions only\"\n    y, ∇f = δf(x...)\n    @assert isapprox(y0, y) \"Return values do not match\"\n    #    @assert typeof(y0) === typeof(y) \"Return type doesn't match\"\n    ∂x = ∇f()\n    #    @assert typeof(x0) === typeof(∂x) \"Gradient type doesn't match\"\n    checkgrad(f, x, ∂x)\nend\n\nfunction checkgrad(f, x, ∂x, h = 1e-8, atol = 1e-8)\n    for k = 1:length(x)\n        ∂xₖ = length(x) == 1 ? ∂x : ∂x[k]\n        if isa(x[k], AbstractFloat)\n            x1 = deepcopy(x)\n            x1[k] -= h\n            y1 = f(x1...)\n            x2 = deepcopy(x)\n            x2[k] += h\n            y2 = f(x2...)\n            isapprox(2h * ∂xₖ, y2-y1, atol=atol) || error(\"gradient for argument #$k doesn't match by $((y2-y1)/(2h*∂xₖ))\")\n        elseif isa(x[k], AbstractArray)\n            for l = eachindex(x[k])\n                x1 = deepcopy(x)\n                x1[k][l] -= h\n                y1 = f(x1...)\n                x2 = deepcopy(x)\n                x2[k][l] += h\n                y2 = f(x2...)\n                isapprox(2h * ∂xₖ[l], y2-y1, atol=atol) || error(\"gradient for argument #$k element $l doesn't match by $((y2-y1)/(2h*∂xₖ[l]))\")\n            end\n        else error(\"not supported argument #$k type: $(typeof(x[k]))\")\n        end\n    end\n    true\nend\n", "meta": {"hexsha": "2564d4e2ad79e6710b0b8cdd36fbbb8d20745dc9", "size": 1343, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/checkdiff.jl", "max_stars_repo_name": "UnofficialJuliaMirror/AutoDiffSource.jl-7e4cc7a5-8b60-57c8-b743-06a5fc972085", "max_stars_repo_head_hexsha": "494a9993dc20e22f07ae4798dac0fa8aa63005bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/checkdiff.jl", "max_issues_repo_name": "UnofficialJuliaMirror/AutoDiffSource.jl-7e4cc7a5-8b60-57c8-b743-06a5fc972085", "max_issues_repo_head_hexsha": "494a9993dc20e22f07ae4798dac0fa8aa63005bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/checkdiff.jl", "max_forks_repo_name": "UnofficialJuliaMirror/AutoDiffSource.jl-7e4cc7a5-8b60-57c8-b743-06a5fc972085", "max_forks_repo_head_hexsha": "494a9993dc20e22f07ae4798dac0fa8aa63005bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4358974359, "max_line_length": 144, "alphanum_fraction": 0.4579300074, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.7538311819592041}}
{"text": "#---------------------------------------\n# types for a single EB sample\n#---------------------------------------\nabstract type EBayesSample{T<:Number} end\nabstract type AbstractNormalSample{T<:Number} <: EBayesSample{T} end\n\n\"\"\"\n    NormalSample(Z,σ)\n\nA observed sample ``Z`` drawn from a Normal distribution with known variance ``\\\\sigma^2 > 0``.\n\n```math\nZ \\\\sim \\\\mathcal{N}(\\\\mu, \\\\sigma^2)\n```\n\n``\\\\mu`` is assumed unknown. The type above is used when the sample ``Z`` is to be used for estimation or inference of ``\\\\mu``.\n\n```julia\nNormalSample(0.5, 1.0)          #Z=0.5, σ=1\n```\n\"\"\"\nstruct NormalSample{T <: Number} <: AbstractNormalSample{T}\n    Z::T\n    σ::T\nend\n\nfunction NormalSample(Z::T) where {T<:Number}\n    NormalSample(Z, one(T))\nend\n\nNormalSample(Z::Number, σ::Number) = NormalSample(promote(Z, σ)...)\n\nresponse(s::NormalSample) = s.Z\nStatistics.var(s::NormalSample) = s.σ^2\n\neltype(s::NormalSample{T}) where T = T\nzero(s::NormalSample{T}) where T = zero(T)\nsupport(ss::NormalSample) = RealInterval(-Inf, +Inf)\n\n#---------------------------------------\n# types for a single EB sample\n#---------------------------------------\nconst EBayesSamples = AbstractArray{EBS} where EBS <: EBayesSample\n\nconst NormalSamples{T} = StructArray{NormalSample{T}} where T\n\nfunction NormalSamples(Zs::AbstractVector{T}, σs::AbstractVector{T}) where T\n    NormalSamples{T}((Zs, σs))\nend\n\nresponse(ss::NormalSamples) = ss.Z\nStatistics.var(ss::NormalSamples) = ss.σ .^ 2\n\n\n\"\"\"\n    StandardNormalSample(Z)\n\nA observed sample ``Z`` drawn from a Normal distribution with known variance ``\\\\sigma^2 =1``.\n\n```math\nZ \\\\sim \\\\mathcal{N}(\\\\mu, 1)\n```\n\n``\\\\mu`` is assumed unknown. The type above is used when the sample ``Z`` is to be used for estimation or inference of ``\\\\mu``.\n\n```julia\nStandardNormalSample(0.5)          #Z=0.5\n```\n\"\"\"\nstruct StandardNormalSample{T <: Number} <: AbstractNormalSample{T}\n    Z::T\nend\n\nresponse(s::StandardNormalSample) = s.Z\nStatistics.var(s::StandardNormalSample) = 1\n\neltype(s::StandardNormalSample{T}) where T = T\nzero(s::StandardNormalSample{T}) where T = zero(T)\nsupport(ss::StandardNormalSample) = RealInterval(-Inf, +Inf)\n\n\nconst AbstractNormalSamples = AbstractArray{NS} where NS <: Union{NormalSample,\n                                                                  StandardNormalSample}\n\nresponse(ss::AbstractNormalSamples) = response.(ss)\nStatistics.var(ss::AbstractNormalSamples) = var.(ss)\nzeros(ss::AbstractNormalSamples) = zeros(eltype(response(ss)), length(ss))\n\n\n\n\n\n# Poisson\n\n# Binomial\n\n# Replicated , ReplicatedArray", "meta": {"hexsha": "93dd3fe184abad18ba4c3e3f063631b64c18e31c", "size": 2567, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ebayes_samples.jl", "max_stars_repo_name": "nignatiadis/EBayes.jl", "max_stars_repo_head_hexsha": "18bba5739a5a8cdde673fb8c2df95e5bbe919e2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-03-29T06:46:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T03:41:23.000Z", "max_issues_repo_path": "src/ebayes_samples.jl", "max_issues_repo_name": "nignatiadis/EBayes.jl", "max_issues_repo_head_hexsha": "18bba5739a5a8cdde673fb8c2df95e5bbe919e2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-10-25T19:23:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T01:32:04.000Z", "max_forks_repo_path": "src/ebayes_samples.jl", "max_forks_repo_name": "nignatiadis/EBayes.jl", "max_forks_repo_head_hexsha": "18bba5739a5a8cdde673fb8c2df95e5bbe919e2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:53:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:53:51.000Z", "avg_line_length": 26.4639175258, "max_line_length": 128, "alphanum_fraction": 0.6361511492, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7538252439961398}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,jl:light\n#     text_representation:\n#       extension: .jl\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.8.2\n#   kernelspec:\n#     display_name: Julia 1.6.1\n#     language: julia\n#     name: julia-1.6\n# ---\n\nusing Pkg\nPkg.add([\"Combinatorics\", \"Plots\"])\n\nusing Combinatorics\nusing LinearAlgebra\nusing Plots\n\n# +\nfunction polynomial_features(X, degree)\n\n    n_samples, n_features = size(X)\n\n    combs = [with_replacement_combinations(1:n_features, i) for i in 0:degree+1]\n\n    combinations = []\n    for sublist in combs\n        for j in sublist\n             push!(combinations, j)\n        end\n    end\n    n_output_features = length(combinations)\n    X_new = zeros(n_samples, n_output_features)\n\n    for (i, index_combs) in enumerate(combinations)\n        X_new[:, i] = prod(X[:, index_combs], dims=2)\n    end\n\n    return X_new\n\nend\n# -\n\n# # Regression polynomial non locale\n\n# +\nf(x, y) = - sin(x) .+ 0.5 * cos(y) \nn, p = 1000, 2\ndegree = 3\nX = randn(n, p)\nY_true = f.(X[:,1],X[:,2]) \nY = Y_true .+ 0.2 .* randn(n)\nX_new = polynomial_features(X, degree)\nbeta = X_new \\ Y\n\nX_grid = hcat(vcat([0.1i for i in -20:20, j in -20:20]...),\n              vcat([0.1j for i in -20:20, j in -20:20]...))\nY_true = f.(X_grid[:,1], X_grid[:,2])\nX_grid_new = polynomial_features( X_grid, degree)\nY_grid = X_grid_new * beta\nplot(X_grid[:,1], X_grid[:,2], Y_grid, st=:surface, alpha=0.5 )\nscatter!(X[:,1], X[:,2], Y, ms = 1)\n\n# +\n\nscatter( X_grid[:,1], X_grid[:,2], Y_true)\nscatter!(X_grid[:,1], X_grid[:,2], Y_grid)\n\n# +\nabstract type AbstractKernel end\n\nstruct Epanechnikov <: AbstractKernel end\n\n\"\"\"\n    epanechnikov(t)\n\nCompute the Epanechnikov kernel.\n\"\"\"\nfunction (::Epanechnikov)(t)\n\n    kernel = zero(t)\n    idx = findall(abs.(t) .<= 1)\n    kernel[idx] = 0.75 .* (1 .- t[idx].^2)\n    return kernel\n\nend\n\n\n# -\n\n# # Regression locale \n\n# +\nkernel = Epanechnikov()\nwidth = 1\n\nY_pred = Float64[]\nfor x in eachrow(X_grid)\n    dist = sqrt.(sum((X .- x').^2, dims=2)) ./ width\n    w = vec(kernel(dist))\n    idx = findall(abs.(w) .> 1e-10)\n    beta = pinv(X_new[idx,:]' * Diagonal(w[idx]) * X_new[idx,:]) * (X_new[idx,:]' * Diagonal(w[idx]) * Y[idx])\n    P = polynomial_features(x', degree)\n    \n    push!(Y_pred, P * beta...)\nend\n\nscatter( X_grid[:,1], X_grid[:,2], Y_pred)\n# -\n\n\n", "meta": {"hexsha": "e3d16c0e8d1e71f271d1e48e76e3b0db475623e1", "size": 2353, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PolynomialRegression.jl", "max_stars_repo_name": "pnavaro/machine_learning", "max_stars_repo_head_hexsha": "895ffe42f853bc05fcfe95997dd5006aebbac042", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-11-06T00:10:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T22:02:34.000Z", "max_issues_repo_path": "PolynomialRegression.jl", "max_issues_repo_name": "pnavaro/machine_learning", "max_issues_repo_head_hexsha": "895ffe42f853bc05fcfe95997dd5006aebbac042", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PolynomialRegression.jl", "max_forks_repo_name": "pnavaro/machine_learning", "max_forks_repo_head_hexsha": "895ffe42f853bc05fcfe95997dd5006aebbac042", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2844827586, "max_line_length": 110, "alphanum_fraction": 0.5983850404, "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7538252284057851}}
{"text": "\"\"\"\n# Usage\n\n    solve(prob::SingleTermFODEProblem, h, PIEX())\n\n### References\n\n```tex\n@inproceedings{Garrappa2018NumericalSO,\n  title={Numerical Solution of Fractional Differential Equations: A Survey and a Software Tutorial},\n  author={Roberto Garrappa},\n  year={2018}\n}\n```\n\"\"\"\nstruct PIEX <: FractionalDiffEqAlgorithm end\n\nfunction solve(FODE::SingleTermFODEProblem, h, ::PIEX)\n    @unpack f, α, u0, tspan = FODE\n    t0 = tspan[1]; T = tspan[2]\n    N::Int64 = round(Int, (T-t0)/h)\n    y = zeros(N+1)\n\n    y[1]=u0\n    for j in range(2, N+1, step=1)\n        middle=0\n        @turbo for i=0:j-1\n            middle += bcoefficients(j-i, α)*f(t0+i*h, y[i+1])\n        end\n        middle = middle/gamma(α+1)\n        y[j] = u0 + middle*h^α\n    end\n    t = collect(t0:h:T)\n    return FODESolution(t, y)\nend\n\nfunction acoefficients(n, α)\n    if n == 0\n        return 1\n    else\n        return ((n-1)^(α+1)-2*n^(α+1)+(n+1)^(α+1))\n    end\nend\n\nbcoefficients(n, α) = ((n+1)^α-n^α)", "meta": {"hexsha": "1e17a77374a7f1ad15f4d1c121e81a0d893a969d", "size": 971, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/singletermfode/PI.jl", "max_stars_repo_name": "SciFracX/FractionalDiffEq.jl", "max_stars_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-11-05T12:49:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:57:20.000Z", "max_issues_repo_path": "src/singletermfode/PI.jl", "max_issues_repo_name": "SciFracX/FractionalDiffEq.jl", "max_issues_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-11-01T22:05:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:57:19.000Z", "max_forks_repo_path": "src/singletermfode/PI.jl", "max_forks_repo_name": "SciFracX/FractionalDiffEq.jl", "max_forks_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5777777778, "max_line_length": 100, "alphanum_fraction": 0.5839340886, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.753825228405785}}
{"text": "__precompile__()\n\nmodule mbRK\nexport rk1, rk4\n\nimport Base.length\n\ntype ButcherTableau\n\tA::Array{Float64,2}\n\tb::Array{Float64,1}\n\tc::Array{Float64,1}\nend\n\nlength(BT::ButcherTableau) = length(BT.b)\n\n\"\"\"\n\trk(butcherTableau)\n\nreturns a runge-kutta method using the respective tableau:\n\n    function(f, t0, y0, h, pred[, init, callback])\n\ne.g. `rk1`, or `rk4`. Examines the ode `f` starting from `t0`, `y0` with fixed stepsize\n`h` until `pred` evalutes to `false`.\n\"\"\"\nfunction rk(BT::ButcherTableau)\n\treturn function rk(f::Function, t₀::Float64, y₀::Vector{Float64}, h::Float64, pred::Function;\n\t\tinit=Void, callback=Void)\n\n\t\tlocal A,b,c,s,t,y,K\n\t\tA,b,c = BT.A, BT.b, BT.c\n\t\ts = length(BT)\n\t\tK = cell(s)\n\n\t\tt,y = deepcopy(t₀), deepcopy(y₀)\n\t\tK[1] = f(t,y)\n\n\t\tinit≠Void && init()\n\n\t\twhile pred(t,y,K[1])\n\t\t\tfor i in 2:s\n\t\t\t\tK[i] = f( t + h*c[i], y + h*(A[i,1:i-1]*K[1:i-1])[1] )\n\t\t\tend\n\n\t\t\tt += h\n\t\t\ty += h*sum(map(*, K, b))\n\t\t\tK[1] = f(t,y)\n\n\t\t\tcallback≠Void && callback(t,y,K)\n\t\tend\n\n\t\treturn Void\n\tend\nend\n\n\n\n\nBTrk1 = ButcherTableau(\n\tzeros(1,1),\n\tones(1),\n\tzeros(1)\n)\nrk1 = rk(BTrk1)\n\nBTrk4 = ButcherTableau(\n\t[\n\t\t.0\t.0\t.0\t.0\n\t\t.5\t.0\t.0\t.0\n\t\t.0\t.5\t.0\t.0\n\t\t.0\t.0\t1.0\t.0\n\t],\n\t[1/6; 1/3; 1/3; 1/6],\n\t[.0; .5; .5; 1.0]\n)\nrk4 = rk(BTrk4)\n\n\nend\n", "meta": {"hexsha": "8a2643d0570ff157f1dcae54f9cdfa58427bc5e5", "size": 1239, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "master/lib/mbRK.jl", "max_stars_repo_name": "285714/ncm", "max_stars_repo_head_hexsha": "fcf289c7ef5f8500ebcb238e36c6a7ee9e054147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "master/lib/mbRK.jl", "max_issues_repo_name": "285714/ncm", "max_issues_repo_head_hexsha": "fcf289c7ef5f8500ebcb238e36c6a7ee9e054147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "master/lib/mbRK.jl", "max_forks_repo_name": "285714/ncm", "max_forks_repo_head_hexsha": "fcf289c7ef5f8500ebcb238e36c6a7ee9e054147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.4875, "max_line_length": 94, "alphanum_fraction": 0.5875706215, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7538233122211278}}
{"text": "##\nfunction badvar1(x::Vector{Float64})\nex2 = 0.0\nex = 0.0\nfor i=1:length(x)\n  ex2 = ex2 + x[i]^2\n  ex = ex + x[i]\nend\nn = length(x)\nreturn 1.0/(n-1)*(ex2 - (ex)^2/n)\nend\n@show badvar1([0.0,1,2])\n@show badvar1([0.0,1,2].+1.0e8)\n##\nusing Random\nRandom.seed!(2)\nx = randn(100)\n@show badvar1(x)\n@show badvar1(x.+1.0e8)\n##\nfunction goodvar(x::Vector{Float64})\n  n = length(x); mean = 0.0; m2 = 0.0; N = 0.0\n  for i=1:n\n    N = N + 1 # running length\n    delta = x[i] - mean\n    mean = mean + delta/N\n    m2 = m2 + delta*(x[i]-mean)\n  end\n  return m2/(n-1)\nend\n@show goodvar([0.0,1,2])\n@show goodvar([0.0,1,2].+1.0e8)\n##\nusing Random\nRandom.seed!(2)\nx = randn(100)\n@show goodvar(x)\n@show goodvar(x.+1.0e8)\n", "meta": {"hexsha": "69a76fc1a2a0f2922ff703a359b2633eaec8b474", "size": 701, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3-unit-2-demos/good-variance.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "3-unit-2-demos/good-variance.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3-unit-2-demos/good-variance.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 17.9743589744, "max_line_length": 46, "alphanum_fraction": 0.5848787447, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7538233119998903}}
{"text": "addprocs(3)\n\n@everywhere function approximate_pi(trials::Int64)\n  hits = 0\n  for i in 1:trials\n    if sum(rand(2).^2) < 1\n      hits += 1\n    end\n  end\n  hits/trials * 4\nend\n\nreferences = [@spawn approximate_pi(1000000) for i=1:3]\napproximation = sum([fetch(ref) for ref in references])/3\n@assert 3.1 < approximation < 3.2\n", "meta": {"hexsha": "d843c67c03bd7b378aa8b72819c027dd0241bc6a", "size": 323, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/remote_pi_computation.jl", "max_stars_repo_name": "BBK-DCSIS-Programming-Paradigms-2018-19/code", "max_stars_repo_head_hexsha": "fbf4e45899b7555fc3b12fcb1fefa172ef415060", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-10-17T18:35:39.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-27T13:18:08.000Z", "max_issues_repo_path": "julia/remote_pi_computation.jl", "max_issues_repo_name": "BBK-DCSIS-Programming-Paradigms-2018-19/code", "max_issues_repo_head_hexsha": "fbf4e45899b7555fc3b12fcb1fefa172ef415060", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/remote_pi_computation.jl", "max_forks_repo_name": "BBK-DCSIS-Programming-Paradigms-2018-19/code", "max_forks_repo_head_hexsha": "fbf4e45899b7555fc3b12fcb1fefa172ef415060", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-28T21:50:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-28T21:50:43.000Z", "avg_line_length": 20.1875, "max_line_length": 57, "alphanum_fraction": 0.6656346749, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167044, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7538233040619607}}
{"text": "function ackley(x, a=20, b=0.2, c=2π)\n    d = length(x)\n    return -a*exp(-b*sqrt(sum(x.^2)/d)) -\n        exp(sum(cos.(c*xi) for xi in x)/d) + a +\n        exp(1)\nend\n", "meta": {"hexsha": "1413d5d2a81933adb8c585de6ea83191d3563d6c", "size": 166, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/Ackley.jl", "max_stars_repo_name": "xh4/MOEA", "max_stars_repo_head_hexsha": "0953e9b4aa8aa1a0ceabc30b481eb954e1920621", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/Ackley.jl", "max_issues_repo_name": "xh4/MOEA", "max_issues_repo_head_hexsha": "0953e9b4aa8aa1a0ceabc30b481eb954e1920621", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/Ackley.jl", "max_forks_repo_name": "xh4/MOEA", "max_forks_repo_head_hexsha": "0953e9b4aa8aa1a0ceabc30b481eb954e1920621", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7142857143, "max_line_length": 48, "alphanum_fraction": 0.4939759036, "num_tokens": 70, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9664104972521579, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.7537933167028966}}
{"text": "using Primes\r\n\r\nfunction totient_func(n)\r\n    prime_fact = factor(n)\r\n    for (p, k) in prime_fact\r\n        n *= (1-1/p)\r\n    end\r\n    return n\r\nend\r\n\r\nfunction find_increment()\r\n    p = primes(30)\r\n    for i in 1:length(p)\r\n\tx = prod((1-1/prime) for prime in p[1:i])\r\n\tn = prod(p[1:i])\r\n\tif x*n/(n-1) < 15499/94744\r\n\t    return prod(p[1:i-1])\r\n\tend\r\n    end\r\nend\r\n\r\nfunction find_denominator(inc)\r\n    n = 0\r\n    while true\r\n        n += inc\r\n        x = totient_func(n)\r\n        if x/(n-1) < 15499/94744\r\n            return n\r\n        end\r\n    end\r\nend\r\n\r\nfunction main()\r\n    inc = find_increment()\r\n    denom = find_denominator(inc)\r\n    println(denom)\r\nend\r\n\r\nmain()\r\n", "meta": {"hexsha": "a2a2e58714db211f8e5cdf23581b454d1918007b", "size": 673, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/problem_243.jl", "max_stars_repo_name": "HarrisonGreen/Project-Euler-Solutions", "max_stars_repo_head_hexsha": "e2599e406c8a1c997bf620e1c35045303b12091e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Julia/problem_243.jl", "max_issues_repo_name": "HarrisonGreen/Project-Euler-Solutions", "max_issues_repo_head_hexsha": "e2599e406c8a1c997bf620e1c35045303b12091e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/problem_243.jl", "max_forks_repo_name": "HarrisonGreen/Project-Euler-Solutions", "max_forks_repo_head_hexsha": "e2599e406c8a1c997bf620e1c35045303b12091e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.825, "max_line_length": 43, "alphanum_fraction": 0.5334323923, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235895, "lm_q2_score": 0.7956581000631541, "lm_q1q2_score": 0.7537914059793419}}
{"text": "\r\ninclude(\"../../../opti/src/opti_module.jl\")\r\n\r\n\r\nmodule noisydiff\r\nusing ..opti\r\nusing LinearAlgebra\r\n\r\nfunction pt1_smooth(t, input_signal; T = 1)\r\n    # trapezoidal rule\r\n\r\n    L = length(input_signal)\r\n    y = zeros(L)\r\n\r\n    y[1] = input_signal[1]\r\n\r\n    for kk = 2:L\r\n        dt = t[kk] - t[kk-1]\r\n        f = dt / (2 * T + dt) # 2 * T / dt + 1\r\n        y[kk] = (input_signal[kk] + input_signal[kk-1] - y[kk-1]) * f + y[kk-1] * 2 * T / (dt + 2 * T)\r\n    end\r\n\r\n    return y\r\nend\r\n\r\n\r\n\r\nfunction diff_sliding_least_squares_d1(t, y; w = 5)\r\n# fitting a degree 1 polynomial in the window and return the derivative\r\n\r\n    N = length(y)\r\n    u = zeros(N-w)\r\n    \r\n    yv = view(y, 1:w)\r\n    xv = view(t, 1:w)\r\n    U1 = sum(yv)\r\n    U2 = sum(yv .* xv)\r\n    S1 = sum(xv)\r\n    S2 = sum(xv.^2)\r\n    jj = 0\r\n\r\n    for ii = (w+1):N\r\n        jj    += 1\r\n        \r\n        d     = w * S2 - S1^2\r\n        a1    = (U2 * w - S1 * U1) / d\r\n        u[jj] = a1\r\n        \r\n        x_old   = t[ii-w]\r\n        x_new   = t[ii]\r\n        y_old   = y[ii-w]\r\n        y_new   = y[ii]\r\n        S1      += x_new - x_old \r\n        S2      += x_new^2 - x_old^2\r\n        U1      += y_new - y_old\r\n        U2      += y_new * x_new - y_old * x_old\r\n        \r\n    end\r\n    return u\r\nend\r\n\r\nfunction diff_sliding_least_squares_d3(t, y; w = 7)\r\n    # fitting a degree 1 polynomial in the window and return the derivative\r\n\r\n    N = length(y)\r\n    u = zeros(N-w)\r\n    \r\n    yv = view(y, 1:w)\r\n    xv = view(t, 1:w)\r\n    U1 = sum(yv)\r\n    U2 = sum(yv .* xv)\r\n    U3 = sum(yv .* xv.^2)\r\n    U4 = sum(yv .* xv.^3)\r\n    \r\n    S1 = sum(xv)\r\n    S2 = sum(xv.^2)\r\n    S3 = sum(xv.^3)\r\n    S4 = sum(xv.^4)\r\n    S5 = sum(xv.^5)\r\n    S6 = sum(xv.^6)\r\n    M = zeros(4, 4)\r\n    b = zeros(4)\r\n    jj = 0\r\n    for ii = (w+1):N\r\n        jj    += 1\r\n        \r\n        M[1,1] = w\r\n        M[1,2] = S1\r\n        M[1,3] = S2\r\n        M[1,4] = S3\r\n        \r\n        M[2,2] = S2\r\n        M[2,3] = S3\r\n        M[2,4] = S4\r\n        M[3,3] = S4\r\n        M[3,4] = S5\r\n        \r\n        M[4,4] = S6\r\n        b[1] = U1\r\n        b[2] = U2\r\n        b[3] = U3\r\n        b[4] = U4\r\n        \r\n        S = Symmetric(M, :U)\r\n        a = S \\ b # todo : replace it with inplace operations\r\n        \r\n        x_old   = t[ii-w]\r\n        x_new   = t[ii]\r\n        y_old   = y[ii-w]\r\n        y_new   = y[ii]\r\n        \r\n        u[jj] = a[2] + 2 * a[3] * x_new + 3 * a[4] * x_new^2\r\n        \r\n        S1      += x_new - x_old\r\n        S2      += x_new^2 - x_old^2\r\n        S3      += x_new^3 - x_old^3\r\n        S4      += x_new^4 - x_old^4\r\n        S5      += x_new^5 - x_old^5\r\n        S6      += x_new^6 - x_old^6\r\n        U1      += y_new - y_old\r\n        U2      += y_new * x_new - y_old * x_old\r\n        U3      += y_new * x_new^2 - y_old * x_old^2\r\n        U4      += y_new * x_new^3 - y_old * x_old^3\r\n            \r\n    end\r\n    return u\r\nend\r\n\r\n# function diff_tikhonov(t, y; w = 5, lamda = 0.1)\r\n#     Ma = zeros(w, w)\r\n#     Md = zeros(w, w)\r\n\r\n#     N = length(t)\r\n#     u = zeros(N)\r\n\r\n#     for ii = (w+1):N\r\n        \r\n#         A = Ma + lamda * Md\r\n\r\n#     end\r\n\r\n#     return u\r\n# end\r\n\r\n\r\nfunction diff_fw(t, y)\r\n    dt = diff(t)\r\n    dy = diff(y)\r\n    dy ./= dt\r\n    return dy\r\nend\r\n\r\nfunction cumtrapezoidal(t, y)\r\n    dt = diff(t)\r\n    N = length(y)\r\n    v1 = view(y, 1:N-1)\r\n    v2 = view(y, 2:N)\r\n    ys = v1 .+ v2\r\n    ints = [0.0; 0.5 .* dt .* ys]\r\n    ints = cumsum(ints)\r\n    return ints\r\nend\r\n\r\n\r\n\r\nfunction tvd(t, y; lamda = 0.1, tol_options = opti.ToleranceOptions())\r\n\r\n    # u0 = rand(length(y)) # copy(y)\r\n    t_min = t[1]\r\n    t_max = t[end]\r\n    T = (t_max - t_min) / 100\r\n    y_pred = pt1_smooth(t, y; T = T)\r\n    u0 = [0.0; diff_fw(t, y_pred)]\r\n\r\n    obj_fcn(u) = __obj_fcn(t, y, lamda, u)\r\n    # stat = opti.cg_pr(obj_fcn, u0; tol_options = tol_options)\r\n    (x_sol, y_sol, iter, stopping_crit) = opti.quasi_newton(obj_fcn, u0; tol_options = tol_options)\r\n    return (x_sol, y_sol, iter, stopping_crit)\r\nend\r\n\r\nfunction __obj_fcn(t, y, lamda, u)\r\n    i1 = __integral_1(u)\r\n    i2 = __integral_2(t, y, u)\r\n    return lamda * i1 + i2\r\nend\r\n\r\n\r\nfunction __integral_1(u)\r\n    N = length(u)\r\n    abs_du = 0.0\r\n    @inbounds for kk = 1:(N-1)\r\n        du = u[kk+1] - u[kk]\r\n        abs_du += abs(du)\r\n    end\r\n    return abs_du / N\r\nend\r\n\r\nfunction __integral_2(t, y, u)\r\n    N = length(y)\r\n    \r\n    # dt = diff(t)\r\n\r\n    # vu1 = view(u, 1:N-1)\r\n    # vu2 = view(u, 2:N)\r\n    \r\n    # int_u =[y[1]; 0.5 .* dt .* (vu1 .+ vu2)]\r\n    # y_pred = cumsum(int_u)\r\n    # g = (y_pred - y).^2\r\n    # i1 = dt[1] * g[1]\r\n    # iN = dt[end] * g[end]\r\n    \r\n    # ibulk = 0.0\r\n    # for kk = 2:N-1\r\n    #     ibulk += g[kk] * (dt[kk] + dt[kk-1])\r\n    # end\r\n    # ibulk += i1\r\n    # ibulk += iN\r\n\r\n    ibulk = 0.0\r\n    y_pred = y[1]\r\n    dt = t[2] - t[1]\r\n    \r\n    @inbounds for kk = 2:N-1\r\n        dt1     = t[kk] - t[kk-1]\r\n        us      = u[kk] + u[kk-1]\r\n        int_u   = 0.5 * dt * us\r\n        y_pred  += int_u\r\n        g       = (y_pred - y[kk]).^2\r\n        ibulk   += g * (dt + dt1)\r\n        dt      = dt1\r\n    end\r\n    \r\n    dt = t[N] - t[N-1]\r\n    int_u = 0.5 * dt * (u[N] + u[N-1])\r\n    y_pred += int_u\r\n    g = (y_pred - y[N]).^2\r\n    iN = dt * g\r\n    # ibulk += i1\r\n    ibulk += iN\r\n\r\n\r\n    return ibulk\r\nend\r\n\r\n\r\n\r\nend", "meta": {"hexsha": "ae181ff5d512e9b122d2142a4cdd0fcf6379fc9d", "size": 5273, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/common/numder/src/noisy_discrete_diff.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "__lib__/math/common/numder/src/noisy_discrete_diff.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "__lib__/math/common/numder/src/noisy_discrete_diff.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3481781377, "max_line_length": 103, "alphanum_fraction": 0.4225298691, "num_tokens": 1988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410982634296, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7537766063979998}}
{"text": "#    Problem : GROUP A\n#    *********\n#    This is a simplified version of problem NONDIA.\n#\n#    Original SIF Source:\n#    G. Li,\n#    \"The secant/finite difference algorithm for solving sparse\n#    nonlinear systems of equations\",\n#    SIAM Journal on Optimization, (to appear), 1990.\n#\n#    Implementation translated from Source:\n#    http://eprints.tsu.ge/234/14/Tests%20collection-K-F.pdf\n#\n#    LIARWHD.SIF classification  SUR2-AN-V-0\n#\n#    Number of variables (at least 2)\n#\n# Daniel Henderson, 08/2021\n\nf = (x) -> begin\n    fx = 0.0\n    for i in firstindex(x):lastindex(x)\n        α = 2.0(x[i]^2 - x[1])\n        γ = x[i]-1\n        fx += α^2 + γ^2\n    end\n    return fx\nend\n\ng! = (g, x) -> begin\n    for i in firstindex(x):lastindex(x)\n        α = 2.0(x[i]^2 - x[1])\n        γ = x[i]-1\n        g[i] = 8.0x[i]α + 2.0γ\n        g[1] -= 4.0α\n    end\n    return g\nend\n\nfg! = (g, x) -> begin\n    fx = 0.0\n    for i in firstindex(x):lastindex(x)\n        α = 2.0(x[i]^2 - x[1])\n        γ = x[i]-1\n        fx += α^2 + γ^2\n        g[i] = 8.0x[i]α + 2.0γ\n        g[1] -= 4.0α\n    end\n    return fx, g\nend\n\ninit = (n::Int=5000) -> begin\n\tx0 = 4.0*ones(n)\n    return n, x0\nend\n\nTestSet[\"LIARWHD\"] = UncProgram(\"LIARWHD\", f, g!, fg!, init)\n", "meta": {"hexsha": "084486e21b0a6764f4b31bfaa6e7afea7687fb62", "size": 1234, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/programs/LIARWHD.jl", "max_stars_repo_name": "danphenderson/UncNLPrograms.jl", "max_stars_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/programs/LIARWHD.jl", "max_issues_repo_name": "danphenderson/UncNLPrograms.jl", "max_issues_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/programs/LIARWHD.jl", "max_forks_repo_name": "danphenderson/UncNLPrograms.jl", "max_forks_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.275862069, "max_line_length": 63, "alphanum_fraction": 0.5275526742, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7537397673698898}}
{"text": "\"\"\"\n`SqExponentialKernel([ρ=1.0])`\n\nThe squared exponential kernel is an isotropic Mercer kernel given by the formula:\n```\n    κ(x,y) = exp(-ρ²‖x-y‖²)\n```\nSee also [`ExponentialKernel`](@ref) for a\nrelated form of the kernel or [`GammaExponentialKernel`](@ref) for a generalization.\n\"\"\"\nstruct SqExponentialKernel{T,Tr} <: Kernel{T,Tr}\n    transform::Tr\n    metric::SqEuclidean\n    function SqExponentialKernel{T,Tr}(transform::Tr) where {T,Tr<:Transform}\n        return new{T,Tr}(transform,SqEuclidean())\n    end\nend\n\n@inline kappa(κ::SqExponentialKernel, d²::Real) = exp(-d²)\n@inline iskroncompatible(::SqExponentialKernel) = true\n\n## Aliases ##\nconst RBFKernel = SqExponentialKernel\nconst GaussianKernel = SqExponentialKernel\n\n\"\"\"\n`ExponentialKernel([ρ=1.0])`\nThe exponential kernel is an isotropic Mercer kernel given by the formula:\n```\n    κ(x,y) = exp(-ρ‖x-y‖)\n```\n\"\"\"\nstruct ExponentialKernel{T,Tr} <: Kernel{T,Tr}\n    transform::Tr\n    metric::Euclidean\n    function ExponentialKernel{T,Tr}(transform::Tr) where {T,Tr<:Transform}\n        return new{T,Tr}(transform,Euclidean())\n    end\nend\n\n@inline kappa(κ::ExponentialKernel, d::Real) = exp(-d)\n@inline iskroncompatible(::ExponentialKernel) = true\n\n## Alias ##\nconst LaplacianKernel = ExponentialKernel\n\n\"\"\"\n`GammaExponentialKernel([ρ=1.0,[gamma=2.0]])`\nThe γ-exponential kernel is an isotropic Mercer kernel given by the formula:\n```\n    κ(x,y) = exp(-ρ^(2γ)‖x-y‖^(2γ))\n```\n\"\"\"\nstruct GammaExponentialKernel{T,Tr,Tᵧ<:Real} <: Kernel{T,Tr}\n    transform::Tr\n    metric::SqEuclidean\n    γ::Tᵧ\n    function GammaExponentialKernel{T,Tr,Tᵧ}(transform::Tr,γ::Tᵧ) where {T,Tr<:Transform,Tᵧ<:Real}\n        return new{T,Tr,Tᵧ}(transform,SqEuclidean(),γ)\n    end\nend\n\nparams(k::GammaExponentialKernel) = (params(transform),γ)\nopt_params(k::GammaExponentialKernel) = (opt_params(transform),γ)\n\nfunction GammaExponentialKernel(ρ::T₁=1.0,gamma::T₂=2.0) where {T₁<:Real,T₂<:Real}\n    @check_args(GammaExponentialKernel, gamma, gamma >= zero(T₂), \"gamma > 0\")\n    GammaExponentialKernel{T₁,ScaleTransform{T₁},T₂}(ScaleTransform(ρ),gamma)\nend\n\nfunction GammaExponentialKernel(ρ::AbstractVector{T₁},gamma::T₂=2.0) where {T₁<:Real,T₂<:Real}\n    @check_args(GammaExponentialKernel, gamma, gamma >= zero(T₂), \"gamma > 0\")\n    GammaExponentialKernel{T₁,ARDTransform{T₁,length(ρ)},T₂}(ARDTransform(ρ),gamma)\nend\n\nfunction GammaExponentialKernel(t::Tr,gamma::T₁=2.0) where {Tr<:Transform,T₁<:Real}\n    @check_args(GammaExponentialKernel, gamma, gamma >= zero(T₁), \"gamma > 0\")\n    GammaExponentialKernel{eltype(Tr),Tr,T₁}(t,gamma)\nend\n\n@inline kappa(κ::GammaExponentialKernel, d²::Real) = exp(-d²^κ.γ)\n@inline iskroncompatible(::GammaExponentialKernel) = true\n", "meta": {"hexsha": "ce31349ac2eb8c51b33a99b6d87a242c022465b8", "size": 2698, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/exponential.jl", "max_stars_repo_name": "devmotion/KernelFunctions.jl", "max_stars_repo_head_hexsha": "460ed8685018a35bac2bceaa2401639668a41f6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/exponential.jl", "max_issues_repo_name": "devmotion/KernelFunctions.jl", "max_issues_repo_head_hexsha": "460ed8685018a35bac2bceaa2401639668a41f6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/exponential.jl", "max_forks_repo_name": "devmotion/KernelFunctions.jl", "max_forks_repo_head_hexsha": "460ed8685018a35bac2bceaa2401639668a41f6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5060240964, "max_line_length": 98, "alphanum_fraction": 0.7116382506, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7537397650259147}}
{"text": "import SpecialFunctions\nusing BenchmarkTools\nimport FunctionZeros: besselj_zero, besselj_zero_asymptotic\n\n## Times reported below are all measured on the same machine\n## Intel(R) Core(TM) i7-4712HQ CPU @ 2.30GHz\n\n# This is an asymptotic form with more terms than\n# the series used in ../src/. It gives no\n# advantage as the initial point for root finding\n# since the root finding takes far more time.\n#\n# This could be used for large enough n without\n# root finding, especially if the user specifies\n# a desired precision.\n## time nu=1, n=20: 125ns\nfunction besselj_zero_asymptotic_long0(nu::Real, n::Integer)\n    beta = MathConstants.pi * (n + nu / 2 - 1//4)\n    delta = 8 * beta\n    mu = 4 * nu^2\n    t1 = 1\n    t2 = 4 * (7 * mu - 31) / (3 * delta^2)\n    t3 = 32 * (84 * mu^2 - 982 * mu + 3779) / (15 * delta^4)\n    t4 = 64 * (6949 * mu^3 - 153855 * mu^2 + 1585743 * mu - 6277237) /\n        (105 * delta^6)\n    return beta - (mu - 1) / delta * (t1 + t2 + t3 + t4)\nend\n\n# Here we compute the powers more efficiently. A Horner formula might be better.\n# This is about 4.5 times faster than the version above.\n## time nu=1, n=20: 29ns\nfunction besselj_zero_asymptotic_long(nu::Real, n::Integer)\n    beta = MathConstants.pi * (n + nu / 2 - 1//4)\n    delta = 8 * beta\n    mu = 4 * nu^2\n    mup2 = mu * mu\n    mup3 = mup2 * mu\n    deltap2 = delta * delta\n    deltap3 = deltap2 * delta\n    deltap4 = deltap2 * deltap2\n    deltap6 = deltap3 * deltap3\n    t1 = 1\n    t2 = 4 * (7 * mu - 31) / (3 * deltap2)\n    t3 = 32 * (84 * mup2 - 982 * mu + 3779) / (15 * deltap4)\n    t4 = 64 * (6949 * mup3 - 153855 * mup2 + 1585743 * mu - 6277237) /\n        (105 * deltap6)\n    zero_asymp = beta - (mu - 1)  / delta * (t1 + t2 + t3 + t4)\n    return zero_asymp\nend\n\n# Here, we convert prefactors in the numerator and denominator to a single rational\n## time nu=1, n=20: 316ns\nfunction besselj_zero_asymptotic_long1(nu::Real, n::Integer)\n    beta = MathConstants.pi * (n + nu / 2 - 1//4)\n    delta = 8 * beta\n    mu = 4 * nu^2\n    mup2 = mu * mu\n    mup3 = mup2 * mu\n    deltap2 = delta * delta\n    deltap3 = deltap2 * delta\n    deltap4 = deltap2 * deltap2\n    deltap6 = deltap3 * deltap3\n    t1 = 1\n    t2 = 4//3 * (7 * mu - 31) / deltap2\n    t3 = 32//15  * (84 * mup2 - 982 * mu + 3779) /  deltap4\n    t4 = 64//105 * (6949 * mup3 - 153855 * mup2 + 1585743 * mu - 6277237) /\n        deltap6\n    return beta - (mu - 1) / delta * (t1 + t2 + t3 + t4)\nend\n\nfunction test_besselj_zero_asymptotic_long(nu::Real, n::Integer)\n    z = besselj_zero_asymptotic_long(nu, n)\n    return SpecialFunctions.besselj(nu, z)\nend\n\nfunction test_besselj_zero_asymptotic(nu::Real, n::Integer)\n    z = besselj_zero_asymptotic(nu, n)\n    return SpecialFunctions.besselj(nu, z)\nend\n\nfunction test_besselj_zero(nu::Real, n::Integer)\n    z = besselj_zero(nu, n)\n    return SpecialFunctions.besselj(nu, z)\nend\n", "meta": {"hexsha": "b1c9524623fc414e356672e4b38d3010a12e3103", "size": 2861, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dev/series.jl", "max_stars_repo_name": "UnofficialJuliaMirror/FunctionZeros.jl-b21f74c0-b399-568f-9643-d20f4fa2c814", "max_stars_repo_head_hexsha": "8440e7484920883028b4ca84b9e54307c8286a50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-09-11T19:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-18T20:38:43.000Z", "max_issues_repo_path": "dev/series.jl", "max_issues_repo_name": "UnofficialJuliaMirror/FunctionZeros.jl-b21f74c0-b399-568f-9643-d20f4fa2c814", "max_issues_repo_head_hexsha": "8440e7484920883028b4ca84b9e54307c8286a50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2018-12-13T08:50:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T22:58:54.000Z", "max_forks_repo_path": "dev/series.jl", "max_forks_repo_name": "UnofficialJuliaMirror/FunctionZeros.jl-b21f74c0-b399-568f-9643-d20f4fa2c814", "max_forks_repo_head_hexsha": "8440e7484920883028b4ca84b9e54307c8286a50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:41:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:46:00.000Z", "avg_line_length": 33.6588235294, "max_line_length": 83, "alphanum_fraction": 0.6298497029, "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7537397559614442}}
{"text": "struct Pzero{A<:Real, B<:Real}\n  NC::Int\n  NT::Int\n  QC::Int\n  QT::Int\n  a::A\n  b::B\nend\n\nfunction Pzero(; NC, NT, QC, QT, a=1.0, b=1.0)\n  return Pzero(NC, NT, QC, QT, a, b)\nend\n\n\"\"\"\nModel0: Proportion of zeros are the same.\nReturn posterior samples of gammaC and gammaT.\n\"\"\"\nfunction infer_Pzero0(m::Pzero, nsamps::Int)\n  Nsum = m.NC + m.NT\n  Qsum = m.QC + m.QT\n  \n  # Posterior distribution.\n  dist = Beta(m.a + Qsum, m.b + Nsum - Qsum)\n  \n  # Posterior samples of gammaC (and gammaT)\n  gamma_samples = rand(dist, nsamps)\n\n  # Loglikelihood\n  loglike = Qsum .* log.(gamma_samples) + (Nsum - Qsum) .* log1p.(-gamma_samples)\n\n  return (gammaC_samples=gamma_samples,\n          gammaT_samples=gamma_samples,\n          distC=dist, distT=dist, loglike=loglike)\nend\n\n\"\"\"\nModel1: Proportion of zeros are different.\nReturn posterior samples of gammaC and gammaT.\n\"\"\"\nfunction infer_Pzero1(m::Pzero, nsamps::Int)\n  # Posterior distributions.\n  distC = Beta(m.a + m.QC, m.b + m.NC - m.QC)\n  distT = Beta(m.a + m.QT, m.b + m.NT - m.QT)\n\n  # Posterior samples of gammaC and gammaT.\n  gammaC_samples = rand(distC, nsamps)\n  gammaT_samples = rand(distT, nsamps)\n\n  # Loglikelihood\n  loglike = let\n    llC = m.QC .* log.(gammaC_samples) + (m.NC - m.QC) .* log1p.(-gammaC_samples)\n    llT = m.QT .* log.(gammaT_samples) + (m.NT - m.QT) .* log1p.(-gammaT_samples)\n    llC + llT\n  end\n\n  return (gammaC_samples=gammaC_samples,\n          gammaT_samples=gammaT_samples,\n          distC=distC, distT=distT, loglike=loglike)\nend\n\nfunction compute_log_bf(m::Pzero, nsamps::Int)\n  m0 = infer_Pzero0(m::Pzero, nsamps)\n  m1 = infer_Pzero1(m::Pzero, nsamps)\n\n  return MCMC.log_bayes_factor(m0.loglike, m1.loglike)\nend\n\nfunction plot_gamma_uq!(gamma_mean::Real, gamma_lower::Real, gamma_upper::Real;\n                        color, Q::Int, N::Int, truth=nothing, alpha=.6,\n                        gamma_dist=nothing)\n  if truth === nothing\n    # Plot empirical mean\n    vline!([Q / N], color=color, label=nothing, ls=:dash)\n  else\n    # Plot simulation truth\n    vline!([truth], color=color, label=nothing, ls=:dash)\n  end\n\n  # Plot posterior mean\n  vline!([gamma_mean], color=color, alpha=alpha, label=nothing)\n\n  # 95% CI\n  if gamma_dist !== nothing\n    grid = range(gamma_lower, gamma_upper, length=100)\n    plot!(grid, zero.(grid), fillrange=pdf.(gamma_dist, grid), color=color,\n          alpha=.3, label=nothing)\n  else\n    vline!([gamma_lower, gamma_upper], color=color, label=nothing, ls=:dot,\n           lw=2)\n  end\n\n  xlabel!(L\"\\gamma_i\")\n  ylabel!(\"density\")\nend\n\nfunction plot_gamma_uq!(gamma::Union{Distribution, AbstractVector{<:Real}};\n                        color, Q::Int, N::Int, ci_level::Real=0.05,\n                        truth=nothing, alpha=.6)\n  gamma_mean = mean(gamma)\n  gamma_lower = quantile(gamma, ci_level/2)\n  gamma_upper = quantile(gamma, 1 - ci_level/2)\n  plot_gamma_uq!(gamma_mean, gamma_lower, gamma_upper, color=color, Q=Q, N=N,\n                 truth=truth, alpha=alpha, gamma_dist=gamma)\nend\n\n\nfunction make_gamma_grid(gammaC_post::Distribution, gammaT_post::Distribution;\n                         a=0.01, grid_length=100)\n  gamma_lower = min(quantile(gammaC_post, a), quantile(gammaT_post, a))\n  gamma_upper = max(quantile(gammaC_post, 1-a), quantile(gammaT_post, 1-a))\n  return range(gamma_lower, gamma_upper, length=grid_length)\nend\n", "meta": {"hexsha": "ff223f0443bd0adbd4e4698e4ebf77bacd7f8466", "size": 3345, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/Pzero.jl", "max_stars_repo_name": "luiarthur/CytofDiffDensity.jl", "max_stars_repo_head_hexsha": "11370917a13a8291e096fe2dcb81644ba01d399b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/models/Pzero.jl", "max_issues_repo_name": "luiarthur/CytofDiffDensity.jl", "max_issues_repo_head_hexsha": "11370917a13a8291e096fe2dcb81644ba01d399b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-12-09T22:57:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-01T00:06:46.000Z", "max_forks_repo_path": "src/models/Pzero.jl", "max_forks_repo_name": "luiarthur/CytofDiffDensity.jl", "max_forks_repo_head_hexsha": "11370917a13a8291e096fe2dcb81644ba01d399b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6017699115, "max_line_length": 81, "alphanum_fraction": 0.6562032885, "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.8175744717487329, "lm_q1q2_score": 0.7537397518635839}}
{"text": "using Plots; pyplot()\nusing Random\n\nusing Pkg\nusing Distributions\n\nusing GLM\nusing DataFrames\n\n# The regression function\nm(x) = 3*x.-3*x.^2+x.^3-0.1*x.^4\n\nRandom.seed!(79015)\nnn = 30\nxx = range(0, stop = 3, length = nn)\nyy = m(xx)+rand(Normal(0, 0.15), nn)\n\nplot(xx, yy,\n    seriestype=:scatter,\n    label = \"\",\n    m = (0.9, :RebeccaPurple, 5),\n    background_color = :Lavender\n    )\nplot!(m, 0, 3,\n    line = (:tomato, 1, 2),\n    label = \"Regression function\")\n\n# We adjust a first order linear estimator\nmodel1 = lm(hcat(repeat([1], outer = 30), xx), yy)\n\n# applies a function to each value of an array and returns a new array\n# containing the resulting values:\nroundmap(vect, b) = map(x -> round(x, digits = b), vect)\n\nroundmap(coef(model1), 3)\n\n#0.582\n#-0.019\n#the regression function is 3*x.-3*x.^2+x.^3-0.1*x.^4\n\ncoef(model1)\n\nplot(xx, yy,\n    seriestype=:scatter,\n    label = \"\",\n    m = (0.9, :RebeccaPurple, 5),\n    background_color = :Lavender\n    )\nplot!(m, 0, 3,\n    line = (:tomato, 1, 2),\n    label = \"Regression function\")\nplot!(x -> sum([1, x].*coef(model1)), 0, 3,\n    label = \"Linear fit\",\n    line = (:RebeccaPurple, 1, 2))\n\n#A quadratic fit\nmodel2 = lm(hcat(repeat([1], outer = nn), xx, map(x -> x^2, xx)), yy)\n\nroundmap(coef(model2), 3)\n\n#0.599\n#-0.055\n#0.012\n#the regression function is 3*x.-3*x.^2+x.^3-0.1*x.^4\n\nplot(xx, yy,\n    seriestype=:scatter,\n    label = \"\",\n    m = (0.9, :RebeccaPurple, 5),\n    background_color = :Lavender\n    )\nplot!(m, 0, 3,\n    line = (:tomato, 1, 2),\n    label = \"Regression function\")\nplot!(x -> sum([1, x, x^2].*coef(model2)), 0, 3,\n    label = \"Quadratic fit\",\n    line = (:RebeccaPurple, 1, 2))\n\n#A cubic fit\nmodel3 = lm(hcat(repeat([1], outer = nn), xx, map(x -> x^2, xx),\n    map(x -> x^3, xx)), yy)\n\nroundmap(coef(model3), 3)\n\n#0.014\n#2.507\n#-2.16\n#0.483\n#the regression function is 3*x.-3*x.^2+x.^3-0.1*x.^4\n\nplot(xx, yy,\n    seriestype=:scatter,\n    label = \"\",\n    m = (0.9, :RebeccaPurple, 5),\n    background_color = :Lavender\n    )\nplot!(m, 0, 3,\n    line = (:tomato, 1, 2),\n    label = \"Regression function\")\nplot!(x -> sum([1, x, x^2, x^3].*coef(model3)), 0, 3,\n    label = \"Cubic fit\",\n    line = (:RebeccaPurple, 1, 2))\n\nmodel4 = lm(hcat(repeat([1], outer = nn), xx, map(x -> x^2, xx),\n    map(x -> x^3, xx), map(x -> x^4, xx)), yy)\n\nroundmap(coef(model4), 3)\n\n#-0.069\n#3.16\n#-3.178\n#1.016\n#-0.089\n#the regression function is 3*x.-3*x.^2+x.^3-0.1*x.^4\n\nplot(xx, yy,\n    seriestype=:scatter,\n    label = \"\",\n    m = (0.9, :RebeccaPurple, 5),\n    background_color = :Lavender\n    )\nplot!(m, 0, 3,\n    line = (:tomato, 1, 2),\n    label = \"Regression function\")\nplot!(x -> sum([1, x, x^2, x^3, x^4].*coef(model4)), 0, 3,\n    label = \"4 degree fit\",\n    line = (:RebeccaPurple, 1, 2))\n\nA = [repeat([1], outer = 10) xx[1:10]]\nB = [repeat([1], outer = 10) xx[11:20]]\nC = [repeat([1], outer = 10) xx[21:30]]\nZ = [repeat([0], outer = 10) repeat([0], outer = 10)]\n\nX = [A Z Z;\n    Z B Z;\n    Z Z C]\n\nbets = X'X\\X'yy\n\nplot(xx, yy,\n    seriestype=:scatter,\n    label = \"\",\n    m = (0.9, :RebeccaPurple, 5),\n    background_color = :Lavender\n    )\nplot!(m, 0, 3,\n    line = (:tomato, 1, 2),\n    label = \"Regression function\")\nplot!(x -> sum([1, x].*bets[1:2]),\n    0, 1,\n    label = \"\",\n    line = (:RebeccaPurple, 1, 2))\nplot!(x -> sum([1, x].*bets[3:4]),\n    1, 2,\n    label = \"\",\n    line = (:RebeccaPurple, 1, 2))\nplot!(x -> sum([1, x].*bets[5:6]),\n    2, 3,\n    label = \"\",\n    line = (:RebeccaPurple, 1, 2))\n\nk1 = 1\nk2 = 2\nKt =[1 k1 -1 -k1 0 0;\n    0 0 1 k2 -1 -k2]\n\naux1 = X'X\\Kt'\naux2 = (Kt*((X'X)\\Kt'))\\(Kt*bets)\ntilbets = bets-aux1*aux2\n\nplot(xx, yy,\n    seriestype=:scatter,\n    label = \"\",\n    m = (0.9, :RebeccaPurple, 5),\n    background_color = :Lavender\n    )\nplot!(m, 0, 3,\n    line = (:tomato, 1, 2),\n    label = \"Regression function\")\nplot!(x -> sum([1, x].*tilbets[1:2]),\n    0, 1,\n    label = \"\",\n    line = (:RebeccaPurple, 1, 2))\nplot!(x -> sum([1, x].*tilbets[3:4]),\n    1, 2,\n    label = \"\",\n    line = (:RebeccaPurple, 1, 2))\nplot!(x -> sum([1, x].*tilbets[5:6]),\n    2, 3,\n    label = \"\",\n    line = (:RebeccaPurple, 1, 2))\n\nA = hcat(repeat([1], outer = 10), xx[1:10],\n        map(x -> x^2, xx[1:10]), map(x -> x^3, xx[1:10]))\nB = hcat(repeat([1], outer = 10), xx[11:20],\n        map(x -> x^2, xx[11:20]), map(x -> x^3, xx[11:20]))\nC = hcat(repeat([1], outer = 10), xx[21:30],\n        map(x -> x^2, xx[21:30]), map(x -> x^3, xx[21:30]))\nZ = reshape(repeat(repeat([0], outer = 10), outer = 4), (10, 4))\n\nX = [A Z Z;\n    Z B Z;\n    Z Z C]\n\nbets = X'X\\X'yy\n\nKt =[1 k1 k1^2 k1^3 -1 -k1 -k1^2 -k1^3  0   0     0     0;\n     0  0    0    0  1  k2  k2^2  k2^3 -1 -k2 -k2^2 -k2^3]\n\naux1 = X'X\\Kt'\naux2 = (Kt*((X'X)\\Kt'))\\(Kt*bets)\ntilbets = bets-aux1*aux2\n\nplot(xx, yy,\n    seriestype=:scatter,\n    label = \"\",\n    m = (0.9, :RebeccaPurple, 5),\n    background_color = :Lavender\n    )\nplot!(m, 0, 3,\n    line = (:tomato, 1, 2),\n    label = \"Regression function\")\nplot!(x -> sum([1, x, x^2, x^3].*tilbets[1:4]),\n    0, 1,\n    label = \"\",\n    line = (:RebeccaPurple, 1, 2))\nplot!(x -> sum([1, x, x^2, x^3].*tilbets[5:8]),\n    1, 2,\n    label = \"\",\n    line = (:RebeccaPurple, 1, 2))\nplot!(x -> sum([1, x, x^2, x^3].*tilbets[9:12]),\n    2, 3,\n    label = \"\",\n    line = (:RebeccaPurple, 1, 2))\n\nKt =[Kt;\n     0  1  2k1  3k1^2  0  -1  -2k1 -3k1^2  0   0     0      0;\n     0  0    0      0  0   1   2k2  3k2^2  0  -1  -2k2 -3k2^2]\n\naux1 = X'X\\Kt'\naux2 = (Kt*((X'X)\\Kt'))\\(Kt*bets)\ntilbets = bets-aux1*aux2\n\nplot(xx, yy,\n    seriestype=:scatter,\n    label = \"\",\n    m = (0.9, :RebeccaPurple, 5),\n    background_color = :Lavender\n    )\nplot!(m, 0, 3,\n    line = (:tomato, 1, 2),\n    label = \"Regression function\")\nplot!(x -> sum([1, x, x^2, x^3].*tilbets[1:4]),\n    0, 1,\n    label = \"\",\n    line = (:RebeccaPurple, 1, 2))\nplot!(x -> sum([1, x, x^2, x^3].*tilbets[5:8]),\n    1, 2,\n    label = \"\",\n    line = (:RebeccaPurple, 1, 2))\nplot!(x -> sum([1, x, x^2, x^3].*tilbets[9:12]),\n    2, 3,\n    label = \"\",\n    line = (:RebeccaPurple, 1, 2))\n\nKt =[Kt;\n    0 0 2 6k1 0 0 -2 -6k1 0 0  0    0;\n    0 0 0   0 0 0  2  6k2 0 0 -2 -6k2]\n\naux1 = X'X\\Kt'\naux2 = (Kt*((X'X)\\Kt'))\\(Kt*bets)\ntilbets = bets-aux1*aux2\n\nplot(xx, yy,\n    seriestype=:scatter,\n    label = \"\",\n    m = (0.9, :RebeccaPurple, 5),\n    background_color = :Lavender\n    )\nplot!(m, 0, 3,\n    line = (:tomato, 1, 2),\n    label = \"Regression function\")\nplot!(x -> sum([1, x, x^2, x^3].*tilbets[1:4]),\n    0, 1,\n    label = \"\",\n    line = (:RebeccaPurple, 1, 2))\nplot!(x -> sum([1, x, x^2, x^3].*tilbets[5:8]),\n    1, 2,\n    label = \"\",\n    line = (:RebeccaPurple, 1, 2))\nplot!(x -> sum([1, x, x^2, x^3].*tilbets[9:12]),\n    2, 3,\n    label = \"\",\n    line = (:RebeccaPurple, 1, 2),\n    ylims = (-0.5, 1.5))\n\n\nusing Dierckx\nspl = Spline1D(xx, yy, [k1, k2], k = 3, bc = \"extrapolate\")\nspl_evaluated(x) = evaluate(spl,x)\n\nplot(xx, yy,\n    seriestype=:scatter,\n    label = \"\",\n    m = (0.9, :RebeccaPurple, 5),\n    background_color = :Lavender\n    )\nplot!(m, 0, 3,\n    line = (:tomato, 1, 2),\n    label = \"Regression function\")\nplot!(spl_evaluated, 0, 3,\n    label = \"\",\n    line = (:RebeccaPurple, 1, 2),\n    background_color = :Lavender,\n    ylims = (-0.5, 1.5)\n    )\n", "meta": {"hexsha": "ccacd391dfe742b74ff238805659e30a56017052", "size": 7192, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/courses/mod2021/10_splines.jl", "max_stars_repo_name": "IrvingGomez/academic-hugo", "max_stars_repo_head_hexsha": "4f6e4ec4aab7a11f477883441b768bb6cf843a9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "content/courses/mod2021/10_splines.jl", "max_issues_repo_name": "IrvingGomez/academic-hugo", "max_issues_repo_head_hexsha": "4f6e4ec4aab7a11f477883441b768bb6cf843a9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "content/courses/mod2021/10_splines.jl", "max_forks_repo_name": "IrvingGomez/academic-hugo", "max_forks_repo_head_hexsha": "4f6e4ec4aab7a11f477883441b768bb6cf843a9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6876971609, "max_line_length": 70, "alphanum_fraction": 0.5233592881, "num_tokens": 3117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460027, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7536387993578815}}
{"text": "export hchebyshevcenter, vchebyshevcenter, chebyshevcenter\nusing JuMP\n\"\"\"\n    hchebyshevcenter(p::HRep[, solver])\n\nReturn a tuple with the center and radius of the largest euclidean ball contained in the polyhedron `p`.\nThrows an error if the polyhedron is empty or if the radius is infinite.\n\"\"\"\nfunction hchebyshevcenter(p::HRep, solver=Polyhedra.solver(p))\n    m = Model(solver=solver)\n    c = @variable m [1:fulldim(p)]\n    for hp in hyperplanes(p)\n        a = Vector{Float64}(hp.a)\n        β = Float64(hp.β)\n        @constraint m dot(a, c) == β\n    end\n    @variable m r[1:nhalfspaces(p)] >= 0\n    for (i, hs) in enumerate(halfspaces(p))\n        a = Vector{Float64}(hs.a)\n        β = Float64(hs.β)\n        @constraint m dot(a, c) + r[i] * norm(a, 2) <= β\n    end\n    @variable m minr >= 0\n    @constraint m minr .<= r\n    @objective m Max minr\n    status = solve(m)\n    if status != :Optimal\n        if status == :Infeasible\n            error(\"An empty polyhedron has no H-Chebyshev center\")\n        elseif status == :Unbounded\n            error(\"The polyhedron contains euclidean ball of arbitrary large radius\")\n        else\n            error(\"Solver returned $status when computing the H-Chebyshev center\")\n        end\n    end\n    @constraint m minr == getvalue(minr)\n    @variable m maxr >= 0\n    @constraint m maxr .>= r\n    @objective m Min maxr\n    status = solve(m)\n    @assert status == :Optimal\n    (getvalue(c), getvalue(minr))\nend\n\n# TODO solver here should not be VRepSolver\n\"\"\"\n    vchebyshevcenter(p::VRep[, solver])\n\nReturn a tuple with the center and radius of the smallest euclidean ball containing the polyhedron `p`.\nThrows an error if the polyhedron is empty or if the radius is infinite (i.e. `p` is not a polytope, it contains rays).\n\"\"\"\nfunction vchebyshevcenter(p::VRep, solver=Polyhedra.solver(p))\n    error(\"TODO\")\nend\n\n\"\"\"\n    chebyshevcenter(p::Rep[, solver])\n\nIf `p` is a H-representation or is a polyhedron for which the H-representation has already been computed, calls `hchebyshevcenter`, otherwise, call `vchebyshevcenter`.\n\"\"\"\nfunction chebyshevcenter(p::Polyhedron, solver=Polyhedra.solver(p))\n    if hrepiscomputed(p)\n        hchebyshevcenter(p, solver)\n    else\n        vchebyshevcenter(p, solver)\n    end\nend\nchebyshevcenter(p::HRepresentation, solver=Polyhedra.solver(p)) = hchebyshevcenter(p, solver)\nchebyshevcenter(p::VRepresentation, solver=Polyhedra.solver(p)) = vchebyshevcenter(p, solver)\n", "meta": {"hexsha": "37a1e5a4fc4428053d0193c785417db0bf9f5c63", "size": 2441, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/center.jl", "max_stars_repo_name": "OliverEvans96/Polyhedra.jl", "max_stars_repo_head_hexsha": "fc51bb5efdb4270ef8ff71561bf07bedc63ece0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/center.jl", "max_issues_repo_name": "OliverEvans96/Polyhedra.jl", "max_issues_repo_head_hexsha": "fc51bb5efdb4270ef8ff71561bf07bedc63ece0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/center.jl", "max_forks_repo_name": "OliverEvans96/Polyhedra.jl", "max_forks_repo_head_hexsha": "fc51bb5efdb4270ef8ff71561bf07bedc63ece0d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8714285714, "max_line_length": 167, "alphanum_fraction": 0.6739041376, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7536294939007042}}
{"text": "function TwoSum(a::Float64,b::Float64)\n\tx = a+b\n\tz = x-a\n\ty = (a-(x-z))+(b-z)\n\treturn (x,y)\nend\n\nfunction Split(a::Float64)\n\tp = 52\n\ts = 26\n\tfactor = 67108865\n\tc = factor*a\n\tx = c - (c-a)\n\ty = a - x\n    return(x,y)\nend\n\nfunction Split(a::Float32)\n\tp = 23\n\ts = 12\n\tfactor = 4097\n\tc = factor*a\n\tx = c - (c-a)\n\ty = a - x\n    return (x,y)\nend\n\nfunction TwoProduct(a::Float64,b::Float64)\n\tx = a*b\n\t[a1,a2] = Split(a)\n\t[b1,b2] = Split(b)\n\ty = (a2*b2−(((x−a1*b1)−a2*b1)−a1*b2))\nend\n\nfunction TwoSumComplex(x::Complex128,y::Complex128)\n\ta = real(x)\n\tb = imag(x)\n\tc = real(y)\n\td = imag(y)\n\t(s1,e1) = TwoSum(a,c)\n\t(s2,e2) = TwoSum(b,d)\n\ts = s1 + im*s2\n\te = e1 + im*e2\n\treturn (s,e)\nend\n\nfunction TwoProductComplex(x::Complex128,y::Complex128)\n\ta = real(x)\n\tb = imag(x)\n\tc = real(y)\n\td = imag(y)\n\t(z1,h1) = TwoProduct(a,c)\n\t(z2,h2) = TwoProduct(b,d)\n\t(z3,h3) = TwoProduct(a,d)\n\t(z4,h4) = TwoProduct(b,c)\n\t(z5,h5) = TwoSum(z1,-z2)\n\t(z6,h6) = TwoSum(z3,z4)\n\tp = z5+im*z6\n\te = h1+im*h3\n\tf = -h2+im*h4\n\tg = h5+im*h6\n\treturn (p,e,f,g)\nend\n\nfunction TwoProductComplexFast(x::Complex128,y::Complex128)\n\ta = real(x)\n\tb = imag(x)\n\tc = real(y)\n\td = imag(y)\n\t(a1,a2) = Split(a)\n\t(b1,b2) = Split(b)\n\t(c1,c2) = Split(c)\n\t(d1,d2) = Split(d)\n\tz1 = a*c\n\tz2 = b*d\n\tz3 = a*d\n\tz4 = b*c\n\th1 = (a2*c2-(((z1-a1*c1)-a2*c1)-a1*c2))\n\th2 = (b2*d2-(((z2-b1*d1)-b2*d1)-b1*d2))\n\th3 = (a2*d2-(((z3-a1*d1)-a2*d1)-a1*d2))\n\th4 = (b2*c2-(((z4-b1*c1)-b2*c1)-b1*c2))\n\t(z5,h5) = TwoSum(z1,-z2)\n\t(z6,h6) = TwoSum(z3,z4)\n\tp =  z5 + im*z6\n\te =  h1 + im*h3\n\tf = -h2 + im*h4\n\tg =  h5 + im*h6\n\treturn (p,e,f,g)\nend", "meta": {"hexsha": "00c75517249c8fde010965d75dee6530106ba2c0", "size": 1560, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CompensatedArithmeticTools.jl", "max_stars_repo_name": "fullerf/Time_Domain_Signal_System_Identification", "max_stars_repo_head_hexsha": "84349d2675f01967f85746ee6b499512180b54b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-21T03:10:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-21T03:10:45.000Z", "max_issues_repo_path": "CompensatedArithmeticTools.jl", "max_issues_repo_name": "fullerf/Time_Domain_Signal_System_Identification", "max_issues_repo_head_hexsha": "84349d2675f01967f85746ee6b499512180b54b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CompensatedArithmeticTools.jl", "max_forks_repo_name": "fullerf/Time_Domain_Signal_System_Identification", "max_forks_repo_head_hexsha": "84349d2675f01967f85746ee6b499512180b54b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-11T20:19:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-11T20:19:01.000Z", "avg_line_length": 17.5280898876, "max_line_length": 59, "alphanum_fraction": 0.5519230769, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.7536294871016443}}
{"text": "\r\nusing QuadGK\r\n\r\nfunction BlackScholes(S, T, K, r, σ)\r\n    f(x) = exp(-0.5*x^2)\r\n    N(d) = 1/sqrt(2*pi) * quadgk(f, -Inf, d)[1]\r\n    d1 = ( log(S/K) + (r + 0.5 * σ^2)*(T))/(σ*sqrt(T))\r\n    d2 = d1 - σ*sqrt(T)\r\n    function call()\r\n        return  S * N(d1) - K * exp(-r*(T))*N(d2)\r\n    end\r\n    function put()\r\n        return K*exp(-r*(T))*N(-d2) - S*N(-d1)\r\n    end\r\n    return call(), put()\r\nend\r\n\r\nfunction BlackScholesDividend(S, T, K, r, σ, q)\r\n    f(x) = exp(-0.5*x^2)\r\n    N(d) = 1/sqrt(2*pi) * quadgk(f, -Inf, d)[1]\r\n    d1 = ( log(S/K) + (r - q + 0.5 * σ^2)*(T))/(σ*sqrt(T))\r\n    d2 = d1 - σ*sqrt(T)\r\n    function call()\r\n        return S*exp(-q*(T))*N(d1) - K*exp(-r*(T))*N(d2)    \r\n    end\r\n    function put()\r\n        return K*exp(-r*(T))*N(-d2) - S*exp(-q*(T))*N(d1)\r\n    end\r\n    return call(), put()\r\nend\r\n\r\n\r\n", "meta": {"hexsha": "41fd3941148481a1906dd78b1ca51eeffd0bca5a", "size": 827, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "BlackScholes.jl", "max_stars_repo_name": "jsmartini/Finance_Dump", "max_stars_repo_head_hexsha": "de0cf7c66b6494054c96c77c08827fdf64007e87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BlackScholes.jl", "max_issues_repo_name": "jsmartini/Finance_Dump", "max_issues_repo_head_hexsha": "de0cf7c66b6494054c96c77c08827fdf64007e87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BlackScholes.jl", "max_forks_repo_name": "jsmartini/Finance_Dump", "max_forks_repo_head_hexsha": "de0cf7c66b6494054c96c77c08827fdf64007e87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0606060606, "max_line_length": 61, "alphanum_fraction": 0.4437726723, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069627, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7536294848352911}}
{"text": "export vandpoly #export function vandpoly, make it public\nReduce.Preload() ## required otherwise Reduce has a fit -?\n\n## ##The Vandermonde matrix method #https://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/05Interpolation/vandermonde/#:~:text=The%20Vandermonde%20method%20is%20the,Gaussian%20elimination%20or%20PLU%20decomposition.\n\n\n##Create macro genvandpoly with:\n# INPUTS:\n#  index - coefficient index we want to return\n#  leny - number of points available for leny-1 degree polynomial interpolation\n#  x - array with x coordinates of leny points\n#  y - array with y coordinates of leny points\n# OUTPUTS:\n#  coefs[index] - the [$index]'s coefficient\n\nmacro genvandpoly(index,leny,x,y) ## generate poly functions using the Vandermonde matrix method\n    leny = :($leny) #length of y #expression with number leny\n    symX = [] #symmetric X matrix declaration\n    symY = [] #symmetric Y matrix declaration\n    A = Array{Expr}(undef, leny, leny) #Array of expressions (ie. Vandermonde matrix)\n##we push an expression xᵢ,yᵢ into symX,symY\n    for i = 1:leny #for all integers i from 1 to leny\n        push!(symX, Meta.parse(\"x$i\")) #meta.parse - parses a string to an expression\n        push!(symY, Meta.parse(\"y$i\")) #meta.parse - parses a string to an expression\n    end\n## ## Assemble A matrix #we go over all elements in A ∈ℜⁿˣⁿ matrix #we go over all elements in A and construct them as expressions\n    for i = 1:leny  #i is the row number (ie. equation or point)\n        for j = 1:leny #j is the column number (ie. power of x)\n            pwr = leny-j #power is the total number of columns - index of current column\n            var = symX[i] #variable that we need to raise to the power, took from symX\n            A[i,j] = :($var^$pwr) #each element of A is an expression var^pwr, with var and pwr being numbers\n        end\n    end\n## ## invert Vandermonde matrix \"A\" to find coefficients of polynomial\n    coefs = Algebra.:*(Algebra.inv(A),symY) #coefs stores polynomial coefficients and is coefs=A\\symY\n    for i = 1:leny #for all integers i in [1,leny] (ie. all elements in coefs)\n        str = repr(coefs[i]) #str is a string representation of element i from coefs\n        for j = 1:leny\n            str = replace(str,\"y\"*string(j)=>\"$y\"*\"[\"*string(j)*\"]\") #replaces into str, the string yⱼ with the numerical value of y[j]\n            str = replace(str,\"x\"*string(j)=>\"$x\"*\"[\"*string(j)*\"]\") #replaces into str, the string xⱼ with the numerical value of x[j]\n        end\n        coefs[i] = Meta.parse(chop(str, head=2, tail=1)) #remove first 2 and last 1 characters from string str and parse it as an expression\n    end\n##return the coefficient with index number \"index\"\n    return coefs[:($index)]\nend\n\n\n## Function vandpoly\n#  INPUTS:\n# x - vector with x coordinates from n points\n# y - vector with y coordiantes from n points\n#  OUTPUTS:\n# Polynomial([cn,cn-1,...,c2,c1]) - Polynomial expression of the form c₁xⁿ⁻¹+c₂xⁿ⁻²+...+cₙ₋₁x+cₙ\n\nfunction vandpoly(x,y) #used to return a polynomial of degree n-1 out of n datapoints in ℜ²\n    xLength = length(x) #xLength is the length of x vector\n\n    if xLength == 2 #if we have only 2 points we fit y=c₁x¹+c₂\n        c1 = @genvandpoly(1, 2,:($x),:($y)) #c1 is the coefficient of x¹\n        c2 = @genvandpoly(2, 2,:($x),:($y)) #c2 is the coefficient of x⁰\n        return Polynomial([c2,c1]) #Return the polynomial c₁x¹+c₂\n\n    elseif xLength == 3 #if we have only 3 points we fit y=c₁x²+c₂x¹+c₃\n        c1 = @genvandpoly(1, 3,:($x),:($y)) #c1 is the coefficient of x²\n        c2 = @genvandpoly(2, 3,:($x),:($y)) #c2 is the coefficient of x¹\n        c3 = @genvandpoly(3, 3,:($x),:($y)) #c3 is the coefficient of x⁰\n        return Polynomial([c3,c2,c1]) #Return the polynomial c₁x²+c₂x¹+c₃\n\n    elseif xLength == 4 #if we have only 4 points we fit y=c₁x³+c₂x²+c₃x¹+c₄\n        c1 = @genvandpoly(1, 4,:($x),:($y)) #c1 is the coefficient of x³\n        c2 = @genvandpoly(2, 4,:($x),:($y)) #c2 is the coefficient of x²\n        c3 = @genvandpoly(3, 4,:($x),:($y)) #c3 is the coefficient of x¹\n        c4 = @genvandpoly(4, 4,:($x),:($y)) #c4 is the coefficient of x⁰\n        return Polynomial([c4,c3,c2,c1]) #Return the polynomial c₁x³+c₂x²+c₃x¹+c₄\n\n    elseif xLength == 5 #if we have only 5 points we fit y=c₁x⁴+c₂x³+c₃x²+c₄x¹+c₅\n        c1 = @genvandpoly(1, 5,:($x),:($y)) #c1 is the coefficient of x⁴\n        c2 = @genvandpoly(2, 5,:($x),:($y)) #c2 is the coefficient of x³\n        c3 = @genvandpoly(3, 5,:($x),:($y)) #c3 is the coefficient of x²\n        c4 = @genvandpoly(4, 5,:($x),:($y)) #c4 is the coefficient of x¹\n        c5 = @genvandpoly(5, 5,:($x),:($y)) #c5 is the coefficient of x⁰\n        return Polynomial([c5,c4,c3,c2,c1]) #Return the polynomial c₁x⁴+c₂x³+c₃x²+c₄x¹+c₅\n\n    else #if we have more than 5 points we simply perform C\\y\n        Polynomial(inv([xval^j for xval in eachindex(x), j = 0:xlength - 1]) * y) # create poly coefficient by inverting array of linear equations\n        println(\"Warning, function behaves slow when exceeding more than 5 datapoints\")\n    end\nend\n", "meta": {"hexsha": "f3f5e985fc0b31a98c29734afe6adf487f4967a0", "size": 5043, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vanderpoly.jl", "max_stars_repo_name": "LucianNita/MorePolynomials.jl", "max_stars_repo_head_hexsha": "e6c47f9e79d44326950885ed4464f7944bf6744d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/vanderpoly.jl", "max_issues_repo_name": "LucianNita/MorePolynomials.jl", "max_issues_repo_head_hexsha": "e6c47f9e79d44326950885ed4464f7944bf6744d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vanderpoly.jl", "max_forks_repo_name": "LucianNita/MorePolynomials.jl", "max_forks_repo_head_hexsha": "e6c47f9e79d44326950885ed4464f7944bf6744d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.0333333333, "max_line_length": 214, "alphanum_fraction": 0.6573468174, "num_tokens": 1714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768525822309, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7536294750462417}}
{"text": "using ModelingToolkit, MethodOfLines, LinearAlgebra, OrdinaryDiffEq\nusing DomainSets\n\nusing Plots\n\nlocal sol\n@time begin #@testset \"Test 01: Brusselator equation 2D\" begin\n       @parameters x y t\n       @variables u(..) v(..)\n       Dt = Differential(t)\n       Dx = Differential(x)\n       Dy = Differential(y)\n       Dxx = Differential(x)^2\n       Dyy = Differential(y)^2\n\n       brusselator_f(x, y, t) = (((x-0.3)^2 + (y-0.6)^2) <= 0.1^2) * (t >= 1.1) * 5.\n\n       x_min = y_min = t_min = 0.0\n       x_max = y_max = 1.0\n       t_max = 11.5\n\n       α = 10.\n\n       u0(x,y,t) = 22(y*(1-y))^(3/2)\n       v0(x,y,t) = 27(x*(1-x))^(3/2)\n\n       eq = [Dt(u(x,y,t)) ~ 1. + v(x,y,t)*u(x,y,t)^2 - 4.4*u(x,y,t) + α*(Dxx(u(x,y,t)) + Dyy(u(x,y,t))) + brusselator_f(x, y, t),\n             Dt(v(x,y,t)) ~ 3.4*u(x,y,t) - v(x,y,t)*u(x,y,t)^2 + α*(Dxx(v(x,y,t)) + Dyy(v(x,y,t)))]\n\n       domains = [x ∈ Interval(x_min, x_max),\n                  y ∈ Interval(y_min, y_max),\n                  t ∈ Interval(t_min, t_max)]\n\n       bcs = [u(x,y,0) ~ u0(x,y,0),\n              u(0,y,t) ~ u(1,y,t),\n              u(x,0,t) ~ u(x,1,t),\n\n              v(x,y,0) ~ v0(x,y,0),\n              v(0,y,t) ~ v(1,y,t),\n              v(x,0,t) ~ v(x,1,t)] \n       \n       @named pdesys = PDESystem(eq,bcs,domains,[x,y,t],[u(x,y,t),v(x,y,t)])\n\n       # Method of lines discretization\n       dx = 1/4\n       dy = 1/4\n\n       order = 2\n\n       discretization = MOLFiniteDifference([x=>dx, y=>dy], t, approx_order=order)\n\n       # Convert the PDE problem into an ODE problem\n       generate_code(pdesys,discretization, \"brusselator_2D_ode.jl\")\nend", "meta": {"hexsha": "a71c31c17c2ac85355c25fa7f854ef7d1478e771", "size": 1604, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/pde_systems/brusselator_codegen.jl", "max_stars_repo_name": "pfcrowe/MethodOfLines.jl", "max_stars_repo_head_hexsha": "ab2a6e1c3e5214821770a67ad604e8d326f7c152", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2021-12-15T23:57:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:07:05.000Z", "max_issues_repo_path": "test/pde_systems/brusselator_codegen.jl", "max_issues_repo_name": "pfcrowe/MethodOfLines.jl", "max_issues_repo_head_hexsha": "ab2a6e1c3e5214821770a67ad604e8d326f7c152", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47, "max_issues_repo_issues_event_min_datetime": "2021-12-21T01:12:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:48:01.000Z", "max_forks_repo_path": "test/pde_systems/brusselator_codegen.jl", "max_forks_repo_name": "pfcrowe/MethodOfLines.jl", "max_forks_repo_head_hexsha": "ab2a6e1c3e5214821770a67ad604e8d326f7c152", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-12-16T13:48:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T13:46:41.000Z", "avg_line_length": 29.7037037037, "max_line_length": 129, "alphanum_fraction": 0.4862842893, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464604, "lm_q2_score": 0.7905303236047048, "lm_q1q2_score": 0.7535928258922162}}
{"text": "function score(x, y)\n    distance = hypot(x, y)\n    distance > 10 && return 0\n    distance > 5 && distance <= 10 && return 1\n    distance > 1 && distance <= 5  && return 5\n    distance <= 1 && return 10\nend\n", "meta": {"hexsha": "95923e0fc1906437eb6ed0b291469abedf6ceae6", "size": 207, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "darts/darts.jl", "max_stars_repo_name": "koladilip/julia-exercism", "max_stars_repo_head_hexsha": "1e67c319ae866a26365da8380659724c5cd472fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "darts/darts.jl", "max_issues_repo_name": "koladilip/julia-exercism", "max_issues_repo_head_hexsha": "1e67c319ae866a26365da8380659724c5cd472fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "darts/darts.jl", "max_forks_repo_name": "koladilip/julia-exercism", "max_forks_repo_head_hexsha": "1e67c319ae866a26365da8380659724c5cd472fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.875, "max_line_length": 46, "alphanum_fraction": 0.5700483092, "num_tokens": 68, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750373915658, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7535928190890007}}
{"text": "instructions = open(\"navigation_data.txt\") do f\n    map(r -> (r[1], parse(Int, r[2:end])), readlines(f))\nend\n\nfunction rotate(v::Vector{Int64}, a::Int64)::Vector{Int64}\n    b = deg2rad(a)\n    x1, y1 = v\n    x2 = cos(b)*x1 - sin(b)*y1\n    y2 = sin(b)*x1 + cos(b)*y1\n\n    return round.(Int, [x2, y2])\nend\n\nship = [0, 0]\ndirection = 0\nfor (cmd, val) in instructions\n    global ship, direction\n\n    if cmd == 'N'\n        ship += [0, val]\n    elseif cmd == 'E'\n        ship += [val, 0]\n    elseif cmd == 'S'\n        ship += [0, -val]\n    elseif cmd == 'W'\n        ship += [-val, 0]\n    elseif cmd == 'F'\n        ship += val * round.(Int, [cos(deg2rad(direction)), sin(deg2rad(direction))])\n    elseif cmd == 'L'\n        direction = (direction + val) % 360\n    elseif cmd == 'R'\n        direction = (direction - val) % 360\n    end\nend\n\nprintln(sum(abs.(ship)))\n\nwaypoint = [10, 1] # relative to ship\nship = [0, 0]\nfor (cmd, val) in instructions\n    global ship, waypoint\n\n    if cmd == 'N'\n        waypoint += [0, val]\n    elseif cmd == 'E'\n        waypoint += [val, 0]\n    elseif cmd == 'S'\n        waypoint += [0, -val]\n    elseif cmd == 'W'\n        waypoint += [-val, 0]\n    elseif cmd == 'F'\n        ship += waypoint * val\n    elseif cmd == 'L'\n        waypoint = rotate(waypoint, val)\n    elseif cmd == 'R'\n        waypoint = rotate(waypoint, -val)\n    end\n    # println(\"$(i): ship: $(ship), wp: $(waypoint)\")\nend\n\nprintln(sum(abs.(ship)))\n", "meta": {"hexsha": "8281129ce9c373a27fe3ec67cfcb584668975ea4", "size": 1440, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day12.jl", "max_stars_repo_name": "kari/aoc2020", "max_stars_repo_head_hexsha": "cbc83cf0b5696171141bc0aca376214a561b0eeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day12.jl", "max_issues_repo_name": "kari/aoc2020", "max_issues_repo_head_hexsha": "cbc83cf0b5696171141bc0aca376214a561b0eeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day12.jl", "max_forks_repo_name": "kari/aoc2020", "max_forks_repo_head_hexsha": "cbc83cf0b5696171141bc0aca376214a561b0eeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2258064516, "max_line_length": 85, "alphanum_fraction": 0.5243055556, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7535452663615472}}
{"text": "using CoordinateTransformations, Rotations\nusing NearestNeighbors\nusing LinearAlgebra\n\n\ncenterofmass(pts::AbstractVector{T}) where { T <: AbstractVector{<:AbstractFloat} } = #\n    [mean(p -> p[i], pts) for i in 1:length(pts[1])]\n\n\"\"\"\n    icp_iteration(pts1::AbstractVector{<:AbstractVector{2, T}}, pts2::AbstractVector{<:AbstractVector{2, T}}; orthonormal=false) where { T<: AbstractFloat }\n\nPerform a single iteration of the iterative closest point algorithm using the orthogonal Procrustes algorithm.\n\nReturns the `pts2` rotated and translated to most closely match `pts1`. \n\"\"\"\nfunction icp_iteration(pts1::AbstractVector{T}, pts2::AbstractVector{T}) where { T <: AbstractVector{<:AbstractFloat}}\n    # Center both pts1 and pts2 on the origin\n    com1, com2 = centerofmass(pts1), centerofmass(pts2)\n    pts1c, pts2c = Translation(-com1).(pts1), Translation(-com2).(pts2)\n    # Find the nearest point in pts1c for each point in pts2c\n    pts1cr = map(i->pts1c[i[1]], knn(KDTree(pts1c), pts2c, 1)[1])\n    @assert length(pts1cr)==length(pts2c)\n    # Turn Vector{Vector{<:AbstractFloat}} into Matrix{<:AbstractFloat}\n    m2(vs) = transpose(reshape(collect(Iterators.flatten(vs)), length(vs[1]), length(vs)))\n    # Solve the orthogonal Procrustes problem\n    f = svd(m2(pts1cr) * transpose(m2(pts2c)))\n    Ω = f.U * f.Vt\n    # Now translate and rotated the reordered data towards `pts1`\n    return Translation(com1).(Ω * pts2c)\nend\n\n\"\"\"\n    icp(pts1::AbstractVector{T}, pts2::AbstractVector{T}; maxiter=10, tol=0.9)\n\nImplements the iterative closest point algorithm.  Transforms `pts2` through rotations and \ntranslations to come as close as possible to `pts1` using a least-squares metric.\n\nThe intention is that `pts1` is the super-set of points in `pts2`.  When aligned most of\nthe points in `pts2` will match up with points in `pts1`.\n\"\"\"\nfunction icp(pts1::AbstractVector{T}, pts2::AbstractVector{T}; maxiter=10, tol=0.99) where { T <: AbstractVector{<:AbstractFloat}}\n    initialerror = icperror(pts1, pts2)\n    next, res, minerror, pos = pts2, pts2, initialerror, 0\n    @show initialerror\n    for _ in 1:maxiter\n        next = icp_iteration(pts1, next)\n        nexterror = icperror(pts1, next)\n        if nexterror < minerror\n            # Meets tolerance\n            (nexterror > tol * minerror) && return next\n            res, minerror, pos = next, nexterror, 0\n        else\n            # Increasing error\n            (minerror!=initialerror) && ((pos+=1)==2) && return res\n        end\n    end\n    minerror == initialerror && @warn \"No improvement after $maxiter steps in icp(...). Returning the initial points.\"\n    return res\nend\n\"\"\"\n    icperror(pts1::AbstractVector{T}, pts2::AbstractVector{T}) where { T <: AbstractVector{<:AbstractFloat}}\n\nMeasures the sum distance between the points in `pts2` and the point closest to the point in `pts1`.\n\"\"\"\nicperror(pts1::AbstractVector{T}, pts2::AbstractVector{T}) where { T <: AbstractVector{<:AbstractFloat}} =\n    sum(i->i[1], knn(KDTree(pts1), pts2, 1)[2])", "meta": {"hexsha": "8c10617b9f8320c6501f57c25de2ff70a61f4f61", "size": 3012, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/icp.jl", "max_stars_repo_name": "NicholasWMRitchie/NeXLParticle", "max_stars_repo_head_hexsha": "9d284df0a12b05b736b05134471673306b224e99", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/icp.jl", "max_issues_repo_name": "NicholasWMRitchie/NeXLParticle", "max_issues_repo_head_hexsha": "9d284df0a12b05b736b05134471673306b224e99", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/icp.jl", "max_forks_repo_name": "NicholasWMRitchie/NeXLParticle", "max_forks_repo_head_hexsha": "9d284df0a12b05b736b05134471673306b224e99", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6363636364, "max_line_length": 156, "alphanum_fraction": 0.6892430279, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7535452554490588}}
{"text": "\"\"\"\nPreconditions the matrix A and b with the inverse of mid(A)\n\"\"\"\nfunction preconditioner(A::AbstractMatrix, b::AbstractArray)\n\n    Aᶜ = mid.(A)\n    B = inv(Aᶜ)\n\n    return B*A, B*b\n\nend\n\nfunction gauss_seidel_interval(A::AbstractMatrix, b::AbstractArray; precondition=true, maxiter=100)\n\n    n = size(A, 1)\n    x = similar(b)\n    x .= -1e16..1e16\n    gauss_seidel_interval!(x, A, b, precondition=precondition, maxiter=maxiter)\n    return x\nend\n\"\"\"\nIteratively solves the system of interval linear\nequations and returns the solution set. Uses the\nGauss-Seidel method (Hansen-Sengupta version) to solve the system.\nKeyword `precondition` to turn preconditioning off.\nEldon Hansen and G. William Walster : Global Optimization Using Interval Analysis - Chapter 5 - Page 115\n\"\"\"\nfunction gauss_seidel_interval!(x::AbstractArray, A::AbstractMatrix, b::AbstractArray; precondition=true, maxiter=100)\n\n    precondition && ((A, b) = preconditioner(A, b))\n\n    n = size(A, 1)\n\n    @inbounds for iter in 1:maxiter\n        x¹ = copy(x)\n        for i in 1:n\n            Y = b[i]\n            for j in 1:n\n                (i == j) || (Y -= A[i, j] * x[j])\n            end\n            Z = extended_div(Y, A[i, i])\n            x[i] = hull((x[i] ∩ Z[1]), x[i] ∩ Z[2])\n        end\n        if all(x .== x¹)\n            break\n        end\n    end\n    x\nend\n\nfunction gauss_seidel_contractor(A::AbstractMatrix, b::AbstractArray; precondition=true, maxiter=100)\n\n    n = size(A, 1)\n    x = similar(b)\n    x .= -1e16..1e16\n    x = gauss_seidel_contractor!(x, A, b, precondition=precondition, maxiter=maxiter)\n    return x\nend\n\nfunction gauss_seidel_contractor!(x::AbstractArray, A::AbstractMatrix, b::AbstractArray; precondition=true, maxiter=100)\n\n    precondition && ((A, b) = preconditioner(A, b))\n\n    n = size(A, 1)\n\n    diagA = Diagonal(A)\n    extdiagA = copy(A)\n    for i in 1:n\n        if (typeof(b) <: SArray)\n            extdiagA = setindex(extdiagA, Interval(0), i, i)\n        else\n            extdiagA[i, i] = Interval(0)\n        end\n    end\n    inv_diagA = inv(diagA)\n\n    for iter in 1:maxiter\n        x¹ = copy(x)\n        x = x .∩ (inv_diagA * (b - extdiagA * x))\n        if all(x .== x¹)\n            break\n        end\n    end\n    x\nend\n\nfunction gauss_elimination_interval(A::AbstractMatrix, b::AbstractArray; precondition=true)\n\n    x = similar(b)\n    x .= -1e16..1e16\n    x = gauss_elimination_interval!(x, A, b, precondition=precondition)\n\n    return x\nend\n\"\"\"\nSolves the system of linear equations using Gaussian Elimination.\nPreconditioning is used when the `precondition` keyword argument is `true`.\n\nREF: Luc Jaulin et al.,\n*Applied Interval Analysis*, pg. 72\n\"\"\"\nfunction gauss_elimination_interval!(x::AbstractArray, A::AbstractMatrix, b::AbstractArray; precondition=true)\n\n    if precondition\n        (A, b) = preconditioner(A, b)\n    else\n        A = copy(A)\n        b = copy(b)\n    end\n\n    n = size(A, 1)\n\n    p = similar(b)\n    p .= 0\n\n    for i in 1:(n-1)\n        if 0 ∈ A[i, i] # diagonal matrix is not invertible\n            p .= entireinterval(b[1])\n            return p .∩ x  # return x?\n        end\n\n        for j in (i+1):n\n            α = A[j, i] / A[i, i]\n            b[j] -= α * b[i]\n\n            for k in (i+1):n\n                A[j, k] -= α * A[i, k]\n            end\n        end\n    end\n\n    for i in n:-1:1\n\n        temp = zero(b[1])\n\n        for j in (i+1):n\n            temp += A[i, j] * p[j]\n        end\n\n        p[i] = (b[i] - temp) / A[i, i]\n    end\n\n    return p .∩ x\nend\n\nfunction gauss_elimination_interval1(A::AbstractMatrix, b::AbstractArray; precondition=true)\n\n    n = size(A, 1)\n    x = fill(-1e16..1e16, n)\n\n    x = gauss_elimination_interval1!(x, A, b, precondition=precondition)\n\n    return x\nend\n\"\"\"\nUsing `Base.\\``\n\"\"\"\nfunction gauss_elimination_interval1!(x::AbstractArray, a::AbstractMatrix, b::AbstractArray; precondition=true)\n\n    precondition && ((a, b) = preconditioner(a, b))\n\n    a \\ b\nend\n\n\\(A::StaticMatrix{Interval{T}}, b::StaticArray{Interval{T}}; kwargs...) where T = gauss_elimination_interval(A, b, kwargs...)\n\\(A::Matrix{Interval{T}}, b::Array{Interval{T}}; kwargs...) where T = gauss_elimination_interval(A, b, kwargs...)\n", "meta": {"hexsha": "1dc43b8af62e0bfa084e93e504796c88188b8086", "size": 4179, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear_eq.jl", "max_stars_repo_name": "ericphanson/IntervalRootFinding.jl", "max_stars_repo_head_hexsha": "21be6924ec971ccc0c61a5f1e171f3b8f35c42c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/linear_eq.jl", "max_issues_repo_name": "ericphanson/IntervalRootFinding.jl", "max_issues_repo_head_hexsha": "21be6924ec971ccc0c61a5f1e171f3b8f35c42c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/linear_eq.jl", "max_forks_repo_name": "ericphanson/IntervalRootFinding.jl", "max_forks_repo_head_hexsha": "21be6924ec971ccc0c61a5f1e171f3b8f35c42c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0239520958, "max_line_length": 125, "alphanum_fraction": 0.594639866, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7535398847580935}}
{"text": "function fornberg_weights!(c::AbstractMatrix{T}, x, ξ) where T\n    nd,m = size(c) .- 1\n    c = OffsetArray(c, 0:nd, 0:m)\n    x = OffsetArray(x, 0:nd)\n    length(x) == nd+1 ||\n        throw(DimensionMismatch(\"Number of grid points does not match requested number of derivative coefficients\"))\n\n    c₁ = one(T)\n    c₄ = x[0] - ξ\n\n    c .= zero(T)\n    c[0,0] = 1\n\n    for i = 1:nd\n        mn = min(i,m)\n        c₂ = one(T)\n        c₅ = c₄\n        c₄ = x[i] - ξ\n        for j = 0:i-1\n            c₃ = x[i] - x[j]\n            c₂ *= c₃\n            for k = mn:-1:1\n                c[i,k] = c₁*(k*c[i-1,k-1] - c₅*c[i-1,k])/c₂\n            end\n            c[i,0] = -c₁*c₅*c[i-1,0]/c₂\n            for k = mn:-1:1\n                c[j,k] = (c₄*c[j,k] - k*c[j,k-1])/c₃\n            end\n            c[j,0] = c₄*c[j,0]/c₃\n        end\n        c₁ = c₂\n    end\n    c\nend\n\nfunction fornberg_weights(x, ξ::T, m::Integer) where T\n    c = zeros(promote_type(eltype(x),T), length(x), m+1)\n    fornberg_weights!(c, x, ξ)\n    c\nend\n\nfunction fornberg_all_weights!(c::AbstractArray{T,3}, x, ξ) where T\n    nd,m = size(c,1) .- 1,size(c,3) .- 1\n    c = OffsetArray(c, 0:nd, 0:nd, 0:m)\n    x = OffsetArray(x, 0:nd)\n    length(x) == nd+1 ||\n        throw(DimensionMismatch(\"Number of grid points does not match requested number of derivative coefficients\"))\n\n    c .= zero(T)\n    c[0,0,0] = 1\n\n    c₁ = one(T)\n    c₄ = x[0] - ξ\n\n    for i = 1:nd\n        mn = min(i,m)\n        c₂ = one(T)\n        c₅ = c₄\n        c₄ = x[i] - ξ\n        for j = 0:i-1\n            c₃ = x[i] - x[j]\n            c₂ *= c₃\n            c[j,i,0] = c₄*c[j,i-1,0]/c₃\n            for k = 1:mn\n                c[j,i,k] = (c₄*c[j,i-1,k] - k*c[j,i-1,k-1])/c₃\n            end\n        end\n        c[i,i,0] = -c₁*c₅*c[i-1,i-1,0]/c₂\n\n        for k = 1:mn\n            c[i,i,k] = c₁*(k*c[i-1,i-1,k-1] - c₅*c[i-1,i-1,k])/c₂\n        end\n        c₁ = c₂\n    end\n    c\nend\n\nfunction fornberg_all_weights(x, ξ::T, m::Integer) where T\n    c = zeros(promote_type(eltype(x),T), length(x), length(x), m+1)\n    fornberg_all_weights!(c, x, ξ)\n    c\nend\n\nfunction fornberg_test_driver(x, ξ)\n    pnum(n::AbstractFloat) = printfmt(\"{1:12.4f}\", n)\n    pnum(n) = print(format(n, width=12))\n    pnum(n::Rational) =\n        print(format(isinteger(n) ? Int(n) : n, width=12))\n\n    M = min(4,length(x)-1)\n    C = fornberg_all_weights(x, ξ, M)\n    N = size(C,2)-1\n    print(\"j \")\n    for j = 0:N\n        pnum(j)\n    end\n    println()\n    print(\"x \")\n    foreach(pnum, x)\n    println()\n    println()\n    for (ki,k) = enumerate(0:M)\n        printfmtln(\"k = {1:2d}\", k)\n        for i = k:N\n            ii = i+1\n            printfmt(\"{1:2d}\", i)\n            foreach(pnum, view(C,1:ii,ii,ki))\n            println()\n        end\n        println()\n    end\n    println()\n    C = fornberg_weights(x, ξ, M)\n    for (ki,k) = enumerate(0:M)\n        printfmt(\"{1:2d}\", k)\n        foreach(pnum, view(C,:,ki))\n        println(stdout)\n    end\nend\n", "meta": {"hexsha": "31b0ac592c452cfd7d45dda8720b8c8eb9a1d1a4", "size": 2938, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fornberg.jl", "max_stars_repo_name": "mortenpi/CompactBases.jl", "max_stars_repo_head_hexsha": "2a2a4b3255c35e95418ab4a9173cf598494de864", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-05-21T20:43:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T02:16:33.000Z", "max_issues_repo_path": "src/fornberg.jl", "max_issues_repo_name": "mortenpi/CompactBases.jl", "max_issues_repo_head_hexsha": "2a2a4b3255c35e95418ab4a9173cf598494de864", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44, "max_issues_repo_issues_event_min_datetime": "2020-05-17T10:10:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T01:07:30.000Z", "max_forks_repo_path": "src/fornberg.jl", "max_forks_repo_name": "mortenpi/CompactBases.jl", "max_forks_repo_head_hexsha": "2a2a4b3255c35e95418ab4a9173cf598494de864", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-24T00:56:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-24T00:56:33.000Z", "avg_line_length": 24.4833333333, "max_line_length": 116, "alphanum_fraction": 0.4673247107, "num_tokens": 1125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7535398807082102}}
{"text": "function ldlfor!(a::Matrix{Float64}, b::Vector{Float64})\n  n = size(a, 1)\n  for i in 1:n\n    total = b[i]\n    if i > 1\n      for j in 1:(i-1)\n        total -= a[j, i] * b[j]\n      end\n      #(i=i, total=total, ad=a[i, i], newb=total / a[i, i]) |> display\n    end\n    b[i] = total / a[i, i]\n    #i == 1 && (i=i, total=total, ad=a[i, i], newb=total / a[i, i]) |> display\n  end\nend\n\nfunction ldlfor(a::Matrix{Float64}, b::Vector{Float64})\n  bt = deepcopy(b)\n  n = size(a, 1)\n  for i in 1:n\n    total = bt[i]\n    if i > 1\n      for j in 1:(i-1)\n        total -= a[j, i] * bt[j]\n      end\n      #(i=i, total=total, ad=a[i, i], newb=total / a[i, i]) |> display\n    end\n    bt[i] = total / a[i, i]\n    #i == 1 && (i=i, total=total, ad=a[i, i], newb=total / a[i, i]) |> display\n  end\n  bt\nend\n\nexport\n  ldlfor!,\n  ldlfor\n", "meta": {"hexsha": "418ce10bd6884a5f1f2edf492d9641a4c989dd3e", "size": 813, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nmlib/ldlfor.jl", "max_stars_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_stars_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "src/nmlib/ldlfor.jl", "max_issues_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "src/nmlib/ldlfor.jl", "max_forks_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 22.5833333333, "max_line_length": 78, "alphanum_fraction": 0.49200492, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8354835371034369, "lm_q1q2_score": 0.7535398770136249}}
{"text": "# ------------------------------------------------------------------------------------------\n# ## Neural networks\n#\n# Now that we know what neurons are, we are ready for the final step: the neural network!. A\n# neural network is literally made out of a network of neurons that are connected together.\n#\n# So far, we have just looked at single neurons, that only have a single output.\n# What if we want multiple outputs?\n#\n#\n# ### Multiple output models\n#\n# What if we wanted to distinguish between apples, bananas, *and* grapes? We could use\n# *vectors* of `0` or `1` values to symbolize each output.\n#\n# <img src=\"data/fruit-salad.png\" alt=\"Drawing\" style=\"width: 300px;\"/>\n#\n# The idea of using vectors is that different directions in the space of outputs encode\n# information about different types of inputs.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Now we extend our previous model to give multiple outputs by repeating it with different\n# weights. For the first element of the array we'd use:\n#\n# $$\\sigma(x;w^{(1)},b^{(1)}) := \\frac{1}{1 + \\exp(-w^{(1)} \\cdot x + b^{(1)})};$$\n#\n# then for the second we'd use\n#\n# $$\\sigma(x;w^{(2)},b^{(2)}) := \\frac{1}{1 + \\exp(-w^{(2)} \\cdot x + b^{(2)})};$$\n#\n# and if you wanted $n$ outputs, you'd have for each one\n#\n# $$\\sigma(x;w^{(i)},b^{(i)}) := \\frac{1}{1 + \\exp(-w^{(i)} \\cdot x + b^{(i)})}.$$\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Notice that these equations are all the same, except for the parameters, so we can write\n# this model more succinctly, as follows. Let's write $b$ in an array:\n#\n# $$b=\\left[\\begin{array}{c}\n# b_{1}\\\\\n# b_{2}\\\\\n# \\vdots\\\\\n# b_{n}\n# \\end{array}\\right]$$\n#\n# and put our array of weights as a matrix:\n#\n# $$ \\mathsf{W}=\\left[\\begin{array}{c}\n# \\\\\n# \\\\\n# \\\\\n# \\\\\n# \\end{array}\\begin{array}{cccc}\n# w_{1}^{(1)} & w_{2}^{(1)} & \\ldots & w_{n}^{(1)}\\\\\n# w_{1}^{(2)} & w_{2}^{(2)} & \\ldots & w_{n}^{(2)}\\\\\n# \\vdots & \\vdots &  & \\vdots\\\\\n# w_{1}^{(n)} & w_{2}^{(n)} & \\ldots & w_{n}^{(n)}\n# \\end{array}\\right]\n# $$\n#\n# We can write this all in one line as:\n#\n# $$\\sigma(x;w,b)= \\left[\\begin{array}{c}\n# \\sigma^{(1)}\\\\\n# \\sigma^{(2)}\\\\\n# \\vdots\\\\\n# \\sigma^{(n)}\n# \\end{array}\\right] = \\frac{1}{1 + \\exp(-\\mathsf{W} x + b)}$$\n#\n# $\\mathsf{W} x$ is the operation called \"matrix multiplication\"\n#\n# [Show small matrix multiplication]\n#\n# It takes each column of weights and does the dot product against $x$ (remember, that's how\n# $\\sigma^{(i)}$ was defined) and spits out a vector from doing that with each column. The\n# result is a vector, which makes this version of the function give a vector of outputs\n# which we can use to encode larger set of choices.\n#\n# Matrix multiplication is also interesting since **GPUs (Graphics Processing Units, i.e.\n# graphics cards) are basically just matrix multiplication machines**, which means that by\n# writing the equation this way, the result can be calculated really fast.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# This \"multiple input and multiple output\" version of the sigmoid function is known as a\n# *layer of neurons*.\n#\n# Previously we worked with a single neuron, which we visualized as\n#\n# <img src=\"data/single-neuron.png\" alt=\"Drawing\" style=\"width: 300px;\"/>\n#\n# where we have two pieces of data (green) coming into a single neuron (pink) that returned\n# a single output. We could use this single output to do binary classification - to identify\n# an image of a fruit as `1`, meaning banana or as `0`, meaning not a banana (or an apple).\n#\n# To do non-binary classification, we can use a layer of neurons, which we can visualize as\n#\n# <img src=\"data/single-layer.png\" alt=\"Drawing\" style=\"width: 300px;\"/>\n#\n# We now have stacked a bunch of neurons on top of each other to hopefully work together and\n# train to output results of more complicated features.\n#\n# We still have two input pieces of data, but now have several neurons, each of which\n# produces an output for a given binary classification:\n# * neuron 1: \"is it an apple?\"\n# * neuron 2: \"is it a banana?\"\n# * neuron 3: \"is it a grape?\"\n# ------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "04a992a6d9f77a34d4ac80b8648ff2157371eb6d", "size": 4565, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/15. ML - Intro to neural networks.jl", "max_stars_repo_name": "grenkoca/JuliaTutorials", "max_stars_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 535, "max_stars_repo_stars_event_min_datetime": "2020-07-15T14:56:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T12:50:32.000Z", "max_issues_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/15. ML - Intro to neural networks.jl", "max_issues_repo_name": "grenkoca/JuliaTutorials", "max_issues_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2018-02-25T22:53:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-14T02:15:50.000Z", "max_forks_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/15. ML - Intro to neural networks.jl", "max_forks_repo_name": "grenkoca/JuliaTutorials", "max_forks_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 394, "max_forks_repo_forks_event_min_datetime": "2020-07-14T23:22:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:12:57.000Z", "avg_line_length": 41.1261261261, "max_line_length": 92, "alphanum_fraction": 0.5546549836, "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915912, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7534849559192246}}
{"text": "# # An equation of second order in two dimmensions\n#\n# Let \\\\(\\Omega = (0, 1)^2\\\\) the unit square and denote \\\\( \\Gamma = \\partial \\Omega\\\\) its boundary.\n# Consider the following problem. Given \\\\(f \\in C(\\Omega)\\\\), find a function \\\\(u\\\\) satisfying\n# \\Delta^2 u = f in \\Omega\n# u = \\Delta u = 0 on \\Gamma\n\nusing Revise\nusing SymFEL\nusing LinearAlgebra\nusing SparseArrays\nusing WriteVTK\nusing JLD2\n\n\n## discretization parameters\n# we use the mesh square.msh (in gmsh format)\n# obtained from square.geo using gmsh\n# this mesh is formed by quad elements\n# we use gmsh module for read the mesh\n# there are some problems using Threads and gmsh (in linux)\n# the file is square.jld2 is prepared separetely\n@load \"square-simple.jld2\"\n\n\n# elementary matrices - P2 x P2\nelem_M = SymFEL.get_square_hermite_em((3, 3), (0, 0), (0, 0))\nelem_K = SymFEL.get_square_hermite_em((3, 3), (2, 0), (2, 0)) +\n    SymFEL.get_square_hermite_em((3, 3), (2, 0), (0, 2)) +\n    SymFEL.get_square_hermite_em((3, 3), (0, 2), (2, 0)) +\n    SymFEL.get_square_hermite_em((3, 3), (0, 2), (0, 2))\n\ndx = norm(nodes_coordinate[:, elements_bound[1,1]] - nodes_coordinate[:, elements_bound[2,1]])\nelem_K_dx = convert(Matrix{Float64}, elem_K.subs(h, dx))\nelem_M_dx = convert(Matrix{Float64}, elem_M.subs(h, dx));\n\n# global matrices\nK = SymFEL.assemble_squaremesh_FE_matrix(elem_K_dx, elements_int,\n                                           order1=1, order2=1,\n                                           dof1=4, dof2=4)\nM = SymFEL.assemble_squaremesh_FE_matrix(elem_M_dx, elements_int,\n                                           order1=1, order2 = 1,\n                                           dof1=4, dof2=4)\n \nf = zeros(Float64, 4*nodes_N)\nf[4*((1:nodes_N) .- 1) .+ 1] = 4*pi^4*sin.(pi * nodes_coordinate[1,:]) .* sin.(pi * nodes_coordinate[2,:])\nf[4*((1:nodes_N) .- 1) .+ 2] = 4*pi^5*cos.(pi * nodes_coordinate[1,:]) .* sin.(pi * nodes_coordinate[2,:])\nf[4*((1:nodes_N) .- 1) .+ 3] = 4*pi^5*sin.(pi * nodes_coordinate[1,:]) .* cos.(pi * nodes_coordinate[2,:])\nf[4*((1:nodes_N) .- 1) .+ 4] = 4*pi^6*cos.(pi * nodes_coordinate[1,:]) .* cos.(pi * nodes_coordinate[2,:])\n\nF = M * f\n\nF[4*(nodes_boundary.-1).+1] = zeros(nodes_boundary_N)\nA = copy(K)\n\n# boundary condition\ntgv = 1e30\nA[4*(nodes_boundary.-1).+1, 4*(nodes_boundary.-1).+1] += tgv * sparse(Matrix{Float64}(I, nodes_boundary_N, nodes_boundary_N))\n\nu = A \\ F\nu_exact = zeros(Float64, 4*nodes_N)\nu_exact[4*((1:nodes_N) .- 1) .+ 1] = sin.(pi * nodes_coordinate[1,:]) .* sin.(pi * nodes_coordinate[2,:])\nu_exact[4*((1:nodes_N) .- 1) .+ 2] = pi * cos.(pi * nodes_coordinate[1,:]) .* sin.(pi * nodes_coordinate[2,:])\nu_exact[4*((1:nodes_N) .- 1) .+ 3] = pi * sin.(pi * nodes_coordinate[1,:]) .* cos.(pi * nodes_coordinate[2,:])\nu_exact[4*((1:nodes_N) .- 1) .+ 4] = pi^2 * cos.(pi * nodes_coordinate[1,:]) .* cos.(pi * nodes_coordinate[2,:])\n\nerr = u - u_exact\n\nprintln(\"L2 error : \", sqrt(err' * M * err))\nprintln(\"H2 error : \", sqrt(err' * K * err))\n\n\n# export to vtk\ncells = [MeshCell(VTKCellTypes.VTK_QUAD, elements_int[1:4, i]) for i = 1:elements_int_N]\n\n\npoints_x = nodes_coordinate[1, :]\npoints_y = nodes_coordinate[2, :]\nvtkfile = vtk_grid(\"ex4-output\", points_x, points_y, cells)\n\nvtkfile[\"u\", VTKPointData()] = u[4*((1:nodes_N) .- 1) .+ 1]\nvtkfile[\"ux\", VTKPointData()] = u[4*((1:nodes_N) .- 1) .+ 2]\nvtkfile[\"uy\", VTKPointData()] = u[4*((1:nodes_N) .- 1) .+ 3]\nvtkfile[\"uxy\", VTKPointData()] = u[4*((1:nodes_N) .- 1) .+ 4]\noutfiles = vtk_save(vtkfile)\n", "meta": {"hexsha": "c61e9d2e9baf8972040422c66dcef84f1d9024eb", "size": 3480, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ex4-bilaplacian2d.jl", "max_stars_repo_name": "ncindea/SymFE.jl", "max_stars_repo_head_hexsha": "886e7fe844d0833bda4ab721414111f8fe353915", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-12T22:24:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T12:06:02.000Z", "max_issues_repo_path": "examples/ex4-bilaplacian2d.jl", "max_issues_repo_name": "ncindea/SymFEL.jl", "max_issues_repo_head_hexsha": "886e7fe844d0833bda4ab721414111f8fe353915", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ex4-bilaplacian2d.jl", "max_forks_repo_name": "ncindea/SymFEL.jl", "max_forks_repo_head_hexsha": "886e7fe844d0833bda4ab721414111f8fe353915", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4651162791, "max_line_length": 125, "alphanum_fraction": 0.6183908046, "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.753484955281043}}
{"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    MaternVariogram(range=r, sill=s, nugget=n, order=ν)\n    MaternVariogram(ball; sill=s, nugget=n, order=ν)\n\nA Matérn variogram with range `r`, sill `s` and nugget `n`.\nThe parameter `ν` is the order of the Bessel function.\nOptionally, use a custom metric `ball`.\n\"\"\"\nstruct MaternVariogram{T,B} <: Variogram\n  sill::T\n  nugget::T\n  order::T\n  ball::B\nend\n\nMaternVariogram(ball; sill=1.0, nugget=0.0, order=1.0) =\n  MaternVariogram(sill, nugget, order, ball)\n\nMaternVariogram(; range=1.0, sill=1.0, nugget=0.0, order=1.0) =\n  MaternVariogram(sill, nugget, order, MetricBall(range))\n\nfunction (γ::MaternVariogram)(h::T) where {T}\n  r = radius(γ.ball)\n  s = γ.sill\n  n = γ.nugget\n  ν = γ.order\n\n  # shift lag by machine precision to\n  # avoid explosion at the origin\n  h′ = sqrt(2ν)*(h + eps(T)) / r\n  Β  = besselk(ν, h′)\n  Γ  = gamma(ν)\n\n  (s - n) * (1 - 2^(1 - ν) / Γ * h′^ν * Β) + (h′ > 0) * n\nend\n\nisstationary(::Type{<:MaternVariogram}) = true\n", "meta": {"hexsha": "8ba45bca12955dacbd1ab82078ed9f80d27e18cb", "size": 1158, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/theoretical/matern.jl", "max_stars_repo_name": "stevengj/Variography.jl", "max_stars_repo_head_hexsha": "8b3b6cc68d94da33983125457d8386f9689d63cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/theoretical/matern.jl", "max_issues_repo_name": "stevengj/Variography.jl", "max_issues_repo_head_hexsha": "8b3b6cc68d94da33983125457d8386f9689d63cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theoretical/matern.jl", "max_forks_repo_name": "stevengj/Variography.jl", "max_forks_repo_head_hexsha": "8b3b6cc68d94da33983125457d8386f9689d63cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5714285714, "max_line_length": 68, "alphanum_fraction": 0.5699481865, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291502, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7534849489733982}}
{"text": "include(\"08_two_site_operator_custom.jl\")\n\nprintln(\"\n#######################################################\n# Tutorial 9                                          #\n#                                                     #\n# 2-site energy minimization via gradient             #\n# optimization                                        #\n#######################################################\n\")\n\n# Used for computing gradients \"automatically\".\n# Julia's source-to-source reverse mode AD library.\nusing Zygote\n\n# Energy function to minimize with gradient descent.\n# Depends implicitly on the Hamiltonian.\nfunction E(ψ)\n  ψHψ = inner(ψ', H, ψ)\n\n  # Alternative:\n  # Hψ = apply(H, ψ)\n  # ψHψ = inner(ψ, Hψ)\n\n  ψψ = inner(ψ, ψ)\n  return ψHψ / ψψ\nend\n\n# Extremely simple gradient descent.\n# Better to use a library like `OptimKit.jl` in general.\nfunction minimize(f, ∂f, x; nsteps, γ)\n  for n in 1:nsteps\n    println(\"n = \", n, \", f_x = \", f(x))\n\n    # Gradient descent step with step size `γ`\n    x = x - γ * ∂f(x)\n  end\n  return x\nend\n\n# Use the cat state as a starting state\nψ₀ = (Zp1 * Zp2 + Zm1 * Zm2) / √2\n\n# Minimize the energy!\n∂E(ψ) = gradient(E, ψ)[1]\nψ = minimize(E, ∂E, ψ₀; nsteps=10, γ=0.1)\n\n@show E(ψ₀), norm(∂E(ψ₀))\n@show E(ψ), norm(∂E(ψ))\n", "meta": {"hexsha": "85890ad9918de1d972aa7a3a5f8e3358ef14c3c1", "size": 1247, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tutorials/09_two_site_state_optimization.jl", "max_stars_repo_name": "mtfishman/ITensorTutorials.jl", "max_stars_repo_head_hexsha": "dcbc1988299e6a7f3b612faeb31563da38ece3be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-11T10:42:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T01:03:58.000Z", "max_issues_repo_path": "tutorials/09_two_site_state_optimization.jl", "max_issues_repo_name": "mtfishman/ITensorTutorials.jl", "max_issues_repo_head_hexsha": "dcbc1988299e6a7f3b612faeb31563da38ece3be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/09_two_site_state_optimization.jl", "max_forks_repo_name": "mtfishman/ITensorTutorials.jl", "max_forks_repo_head_hexsha": "dcbc1988299e6a7f3b612faeb31563da38ece3be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.94, "max_line_length": 56, "alphanum_fraction": 0.511627907, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7534849485756556}}
{"text": "# The SteinParzenARKernel is a kernel derived by Parzen in 1961,\n# which arises from a second order autoregressive process. Its\n# inner product is for the Sobolev space H^2([a, b]) for any\n# a < b.\n#\n# k(x, y) = (4*alpha*gamma^2)^-1 * exp{-alpha*|x - y|} cos(w*|x-y|)\n#   + (alpha / w) * sin(w*|x-y|)\n#\n# where w^2 = gamma^2 - alpha^2 > 0. The associated norm is\n#\n# |u|_H = 4*alpha*gamma^2*u(a)^2 + 4*alpha*u'(a)^2 +\n#  \\int_[a,b] (u''(t) + 2*alpha^2*u'(t) + gamma^2*u(t))^2\n\ntype SteinParzenARKernel <: SteinTensorizedKernel\n    # the alpha parameter\n    alpha::Float64\n    # the gamma parameter\n    gamma::Float64\nend\n\n# have default parameters of alpha = 1/sqrt(2) and gamma = 1.0\nSteinParzenARKernel() = SteinParzenARKernel(1.0/sqrt(2), 1.0)\n\n# utility to get w\nfunction getw(ker::SteinParzenARKernel)\n    sqrt(ker.gamma^2 - ker.alpha^2)\nend\n\n# utility method for wacky constant\nfunction getc1(ker::SteinParzenARKernel)\n    1.0 / (4.0 * ker.alpha * ker.gamma^2)\nend\n\nfunction ki(ker::SteinParzenARKernel, x::Float64, y::Float64)\n    w = getw(ker)\n    c = getc1(ker)\n    alpha = ker.alpha\n\n    c * exp(-alpha * abs(x-y)) * cos(w * abs(x-y)) + (alpha/w) * sin(w * abs(x-y))\nend\n\nfunction gradxki(ker::SteinParzenARKernel, x::Float64, y::Float64)\n    w = getw(ker)\n    c = getc1(ker)\n    alpha = ker.alpha\n    s = sign(x - y)\n\n    -c * s * exp(-alpha * abs(x-y)) * (\n        alpha * cos(w * abs(x-y)) +\n        w * sin(w * abs(x-y))\n    ) + alpha * s * cos(w * abs(x-y))\nend\n\nfunction gradxyki(ker::SteinParzenARKernel, x::Float64, y::Float64)\n    w = getw(ker)\n    c = getc1(ker)\n    alpha = ker.alpha\n    s = sign(x - y)\n\n    -c * exp(-alpha * abs(x-y)) * (\n        (alpha^2 - w^2) * cos(w * abs(x-y)) +\n        2 * alpha * w * sin(w * abs(x-y))\n    ) + alpha * w * sin(w * abs(x-y))\nend\n", "meta": {"hexsha": "387573246705f40adb5e905913802a6ac2979481", "size": 1792, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/SteinParzenARKernel.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SteinDiscrepancy.jl-d014d5ac-0f4d-54d5-9198-0ab2ca96d67f", "max_stars_repo_head_hexsha": "bc3e08b745763d2ea466e74d8b254091d0bcca91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2017-07-05T08:38:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-20T18:16:24.000Z", "max_issues_repo_path": "src/kernels/SteinParzenARKernel.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SteinDiscrepancy.jl-d014d5ac-0f4d-54d5-9198-0ab2ca96d67f", "max_issues_repo_head_hexsha": "bc3e08b745763d2ea466e74d8b254091d0bcca91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-05-23T04:58:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:34:20.000Z", "max_forks_repo_path": "src/kernels/SteinParzenARKernel.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SteinDiscrepancy.jl-d014d5ac-0f4d-54d5-9198-0ab2ca96d67f", "max_forks_repo_head_hexsha": "bc3e08b745763d2ea466e74d8b254091d0bcca91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2017-05-23T04:56:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T06:10:56.000Z", "avg_line_length": 27.5692307692, "max_line_length": 82, "alphanum_fraction": 0.5920758929, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.753484948335217}}
{"text": "function Qmat(N, m, lam)\n    # Integration matrix\n    Q = 1\n    round(m) !== m ? (return Q = Qmat05(N, lam)) : nothing\n    Q = Q*Qmat1(N, lam)\n    return Q\nend\n\nfunction Qmat05(N, lam)\n    # Half integral matrix\n    if lam == 0.5\n        v = (2/sqrt(pi)) ./ (2*collect(0:N-1).+1)\n        Q = myspdiagm(spdiagm(0=>v, 1=>-v[2:end]), N)\n    elseif lam == 1\n        v = (sqrt(pi)/2) .* ones(N)\n        Q = myspdiagm(spdiagm(-1=>v[2:end], 0=>v), N)\n    end\n    return Q\nend\n    \nfunction Qmat1(N, lam)\n    # Full integral matrix\n    if lam == 0.5\n        v = 1 ./ (2*collect(0:N-1).+1)\n        Q = myspdiagm(spdiagm(-1 => v, 1 => -v[2:end]), N)\n        Q[1, 1] = 1\n    elseif lam == 1\n        nn = collect(0:N)\n        v = 1 ./ (2*nn.+1)\n        v2 = 2 ./ (4*nn.^2 .-1)\n        Q = myspdiagm(spdiagm(-1=>v[2:end], 0=>v2[2:end], 1=>-v[2:end-1]), N)\n    end\n    return Q\nend\n\nmyspdiagm(M, N) = size(M, 1) !== N ? (return M[1:N, 1:N]) : (return M)", "meta": {"hexsha": "e6d7e8c2082c437e8ba563e762f12be0715c1c39", "size": 939, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FIE/Qmat.jl", "max_stars_repo_name": "SciFracX/FractionalDiffEq.jl", "max_stars_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-11-05T12:49:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:57:20.000Z", "max_issues_repo_path": "src/FIE/Qmat.jl", "max_issues_repo_name": "SciFracX/FractionalDiffEq.jl", "max_issues_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-11-01T22:05:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:57:19.000Z", "max_forks_repo_path": "src/FIE/Qmat.jl", "max_forks_repo_name": "SciFracX/FractionalDiffEq.jl", "max_forks_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0833333333, "max_line_length": 77, "alphanum_fraction": 0.4760383387, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832974, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7534849476970354}}
{"text": "# L2,1 norm/Sum of norms of columns or rows (times a constant)\n\nexport NormL21\n\n\"\"\"\n**Sum-of-``L_2`` norms**\n\n    NormL21(λ=1, dim=1)\n\nReturns the function\n```math\nf(X) = λ⋅∑_i\\\\|x_i\\\\|\n```\nfor a nonnegative `λ`, where ``x_i`` is the ``i``-th column of ``X`` if `dim == 1`, and the ``i``-th row of ``X`` if `dim == 2`.\nIn words, it is the sum of the Euclidean norms of the columns or rows.\n\"\"\"\nstruct NormL21{R <: Real, I <: Integer} <: ProximableFunction\n    lambda::R\n    dim::I\n    function NormL21{R,I}(lambda::R, dim::I) where {R <: Real, I <: Integer}\n        if lambda < 0\n            error(\"parameter λ must be nonnegative\")\n        else\n            new(lambda, dim)\n        end\n    end\nend\n\nis_convex(f::NormL21) = true\n\nNormL21(lambda::R=1, dim::I=1) where {R <: Real, I <: Integer} = NormL21{R, I}(lambda, dim)\n\nfunction (f::NormL21)(X::AbstractArray{T, 2}) where {R, T <: RealOrComplex{R}}\n    nslice = R(0)\n    n21X = R(0)\n    if f.dim == 1\n        for j = 1:size(X, 2)\n            nslice = R(0)\n            for i = 1:size(X, 1)\n                nslice += abs(X[i, j])^2\n            end\n            n21X += sqrt(nslice)\n        end\n    elseif f.dim == 2\n        for i = 1:size(X, 1)\n            nslice = R(0)\n            for j = 1:size(X, 2)\n                nslice += abs(X[i, j])^2\n            end\n            n21X += sqrt(nslice)\n        end\n    end\n    return f.lambda * n21X\nend\n\nfunction prox!(Y::AbstractArray{T, 2}, f::NormL21, X::AbstractArray{T, 2}, gamma::Real=1) where {R, T <: RealOrComplex{R}}\n    gl = gamma * f.lambda\n    nslice = R(0)\n    n21X = R(0)\n    if f.dim == 1\n        for j = 1:size(X, 2)\n            nslice = R(0)\n            for i = 1:size(X, 1)\n                nslice += abs(X[i, j])^2\n            end\n            nslice = sqrt(nslice)\n            scal = 1 - gl / nslice\n            scal = scal <= 0 ? R(0) : scal\n            for i = 1:size(X, 1)\n                Y[i, j] = scal * X[i, j]\n            end\n            n21X += scal * nslice\n        end\n    elseif f.dim == 2\n        for i = 1:size(X, 1)\n            nslice = R(0)\n            for j = 1:size(X, 2)\n                nslice += abs(X[i, j])^2\n            end\n            nslice = sqrt(nslice)\n            scal = 1-gl/nslice\n            scal = scal <= 0 ? R(0) : scal\n            for j = 1:size(X, 2)\n                Y[i, j] = scal * X[i, j]\n            end\n            n21X += scal * nslice\n        end\n    end\n    return f.lambda * n21X\nend\n\nfun_name(f::NormL21) = \"sum of Euclidean norms\"\nfun_dom(f::NormL21) = \"AbstractArray{Real,2}, AbstractArray{Complex, 2}\"\nfun_expr(f::NormL21) = \"x ↦ λsum(||x_i||)\"\nfun_params(f::NormL21) = \"λ = $(f.lambda), dim = $(f.dim)\"\n\nfunction prox_naive(f::NormL21, X::AbstractArray{T,2}, gamma::Real=1.0) where T <: RealOrComplex\n    Y = max.(0, 1 .- f.lambda * gamma ./ sqrt.(sum(abs.(X).^2, dims=f.dim))) .* X\n    return Y, f.lambda * sum(sqrt.(sum(abs.(Y).^2, dims=f.dim)))\nend\n", "meta": {"hexsha": "f20bc04ff86227602bf5bdaf6bd5a4b44e29e92e", "size": 2913, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/normL21.jl", "max_stars_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_stars_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2016-10-29T12:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:11:52.000Z", "max_issues_repo_path": "src/functions/normL21.jl", "max_issues_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_issues_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2016-10-26T16:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T20:38:48.000Z", "max_forks_repo_path": "src/functions/normL21.jl", "max_forks_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_forks_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T10:40:24.000Z", "avg_line_length": 28.8415841584, "max_line_length": 128, "alphanum_fraction": 0.4895296945, "num_tokens": 999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520765, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7534849474565964}}
{"text": "using .PDMats: PDMat\n\nexport kernelpdmat\n\n\"\"\"\n    Compute a positive-definite matrix in the form of a `PDMat` matrix see [PDMats.jl]() with the cholesky decomposition precomputed\n    The algorithm recursively tries to add recursively a diagonal nugget until positive definiteness is achieved or that the noise is too big\n\"\"\"\nfunction kernelpdmat(\n        κ::Kernel,\n        X::AbstractMatrix;\n        obsdim::Int = defaultobs\n        )\n    K = kernelmatrix(κ,X,obsdim=obsdim)\n    Kmax =maximum(K)\n    α = eps(eltype(K))\n    while !isposdef(K+α*I) && α < 0.01*Kmax\n        α *= 2.0\n    end\n    if α >= 0.01*Kmax\n        throw(ErrorException(\"Adding noise on the diagonal was not sufficient to build a positive-definite matrix:\\n\\t- Check that your kernel parameters are not extreme\\n\\t- Check that your data is sufficiently sparse\\n\\t- Maybe use a different kernel\"))\n    end\n    return PDMat(K+α*I)\nend\n\nkernelpdmat(κ::Kernel,X::AbstractVector{<:Real};obsdim=defaultobs) = kernelpdmat(κ,reshape(X,1,:),obsdim=2)\n", "meta": {"hexsha": "fa617eaaf8415906401c2f4f7a41e9d4ec950e73", "size": 1012, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix/kernelpdmat.jl", "max_stars_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_stars_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-05-24T15:12:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T07:23:25.000Z", "max_issues_repo_path": "src/matrix/kernelpdmat.jl", "max_issues_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_issues_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2019-05-24T15:26:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-24T10:39:19.000Z", "max_forks_repo_path": "src/matrix/kernelpdmat.jl", "max_forks_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_forks_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-05-24T15:13:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T18:33:59.000Z", "avg_line_length": 37.4814814815, "max_line_length": 255, "alphanum_fraction": 0.692687747, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7534849446634321}}
{"text": "\"\"\"\n    tnmean(a, b)\n\nMean of the truncated standard normal distribution in the interval [a, b].\n\"\"\"\nfunction tnmean(a::Real, b::Real)\n    if !(a ≤ b)\n        return oftype(middle(a, b), NaN)\n    elseif a == b\n        return middle(a, b)\n    elseif abs(a) > abs(b)\n        return -tnmean(-b, -a)\n    elseif isinf(a) && isinf(b)\n        return zero(middle(a, b))\n    end\n\n    @assert a < b && abs(a) ≤ abs(b)\n    @assert a ≤ 0 ≤ b || 0 < a < b\n\n    Δ = (b - a) * middle(a, b)\n    #Δ = one(Δm1) + Δm1\n\n    if a ≤ 0 ≤ b\n        m = √(2/π) * expm1(-Δ) * exp(-a^2 / 2) / erf(b/√2, a/√2)\n    elseif 0 < a < b\n        z = exp(-Δ) * erfcx(b/√2) - erfcx(a/√2)\n        iszero(z) && return middle(a, b)\n        m = √(2/π) * expm1(-Δ) / z\n    end\n    return clamp(m, a, b)\nend\n\n\"\"\"\n    tnmean(a, b, μ, σ)\n\nMean of the truncated normal distribution, where μ, σ are the mean and standard\ndeviation of the untruncated distribution.\n\"\"\"\nfunction tnmean(a, b, μ, σ)\n    α = (a - μ) / σ\n    β = (b - μ) / σ\n    return μ + tnmean(α, β) * σ\nend\n\n\"\"\"\n    tnmean(a, b)\n\nMean of the truncated standard normal distribution.\n\n    tnmean(a, b, μ, σ)\n\nMean of the truncated normal distribution, where μ, σ are the mean and standard\ndeviation of the untruncated distribution.\n\"\"\"\ntnmean(a, b) = tnmean(a, b)\n\n\"\"\"\n    tnmom1i(a, b)\n\nMean of the normal distribution with variance -1 and mean 0, truncated to [a,b].\n\"\"\"\nfunction tnmom1i(a::Real, b::Real)\n    if !(-Inf < a ≤ b < Inf)\n        return oftype(middle(a, b), NaN)\n    elseif a == b\n        return middle(a, b)\n    elseif abs(a) > abs(b)\n        return -tnmom1i(-b, -a)\n    end\n\n    @assert -Inf < a < b < Inf && abs(a) ≤ abs(b)\n    @assert a ≤ 0 ≤ b || 0 < a < b\n\n    Δ = (b - a) * middle(a, b)\n    m = (1/√2) * expm1(-Δ) / (dawson(a/√2) * exp(-Δ) - dawson(b/√2))\n    return clamp(m, a, b)\nend\n\n\"\"\"\n    tnmom1i(a, b, μ, σ)\n\nMean of the normal distribution with variance -σ^2 and mean μ,\ntruncated to [a,b].\n\"\"\"\ntnmom1i(a, b, μ, σ) = μ + σ * tnmom1i((a - μ)/σ, (b - μ)/σ)\n", "meta": {"hexsha": "be16580ab480169b45674a5e205ee6da5eec4bcf", "size": 2001, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tnmean.jl", "max_stars_repo_name": "suzannastep/TruncatedNormal.jl", "max_stars_repo_head_hexsha": "3c16866c3afa3920e787513d492689e9e81192ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-14T11:01:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T10:39:02.000Z", "max_issues_repo_path": "src/tnmean.jl", "max_issues_repo_name": "suzannastep/TruncatedNormal.jl", "max_issues_repo_head_hexsha": "3c16866c3afa3920e787513d492689e9e81192ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-03-01T13:44:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T20:39:24.000Z", "max_forks_repo_path": "src/tnmean.jl", "max_forks_repo_name": "suzannastep/TruncatedNormal.jl", "max_forks_repo_head_hexsha": "3c16866c3afa3920e787513d492689e9e81192ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-12-10T23:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T13:59:39.000Z", "avg_line_length": 23.2674418605, "max_line_length": 80, "alphanum_fraction": 0.5342328836, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374443, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.753484939955723}}
{"text": "#=\nThe sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.\n\nFind the sum of all the primes below two million.\n=#\nusing Primes\n@time println(sum(primes(2_000_000)))\n\n", "meta": {"hexsha": "b96f5afece0bccddb35c111ed58c972d56baa0f3", "size": 163, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p10.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p10.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p10.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 18.1111111111, "max_line_length": 53, "alphanum_fraction": 0.6809815951, "num_tokens": 56, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7534766284612792}}
{"text": "\"\"\"\r\nRandom graph model exhibiting low GCC and high ALCC. Creates a fixed number\r\nof cliques each with a random number of nodes. Nodes can partake in multiple\r\ncliques.\r\n\r\nBased on \"Random clique covers for graphs with local density and global sparsity\"\r\nby Sinead A. Williamson and Mauricio Tec. The original paper may be found\r\nat https://arxiv.org/pdf/1704.03913.pdf.\r\n\"\"\"\r\n\r\nusing MatrixNetworks\r\nusing SpecialFunctions # Used for gamma\r\nusing LinearAlgebra # Matrix transpose\r\nusing SparseArrays\r\nusing Distributions: Poisson\r\n\r\n\"\"\"\r\n`rcc`\r\n=====================\r\n\r\nGenerate a random graph by creating random clique covers.\r\n\r\nArguments\r\n---------\r\n    - `a::Float64 (> 0)`: The expected number of vertices per clique\r\n    - `s::Float64 (∈ [0,1))`: Controls how close the degree distribution is to a power law\r\n    - `c::Float64 (> -s)`: Controls (but not equal to) the expected number of cliques each vertex is a part of.\r\n                           Larger c = less overlap\r\n    - `N::Int64 (=10)`: The total number of cliques\r\n\r\nPreconditions\r\n-------------\r\n    - `a > 0`\r\n    - `s ∈ [0,1)`\r\n    - `c > -s`\r\n    - `N >= 0`\r\n\r\nExamples\r\n--------\r\n~~~~\r\nrandom_clique_cover(10.,0.9,0.1;N=100) # 100-clique graph with ~10 nodes per clique with high degree skew and medium clique overlap\r\nrandom_clique_cover(50.,0.1,5.) # 10-clique graph with ~50 nodes per clique with more uniform degree distribution and high clique overlap\r\n~~~~\r\n\r\nThe random cliques are generated using the following process. Imagine a fixed\r\nnumber of restaurant customers coming up to an (infinitely long) buffet one by one.\r\nThe first customer takes the first n dishes, where n is random. Each customer\r\nthereafter\r\n    1) samples each already-tried dish at random, with the probability\r\n    of taking a dish decreasing with the number of times it has been tried\r\n    2) selects the next k (also random) dishes that have not yet been tried.\r\n\r\nThis graph model works by substituting customers for cliques and dishes for nodes. Bon appétit!\r\n\"\"\"\r\nfunction rcc(a::Float64, s::Float64, c::Float64; N::Int64=10)\r\n    @assert a > 0\r\n    @assert s >= 0 && s < 1\r\n    @assert c > -s\r\n    @assert N >= 0\r\n\r\n    P(x) = rand(Poisson(x)) # Sample from Poisson distribution with λ = x\r\n\r\n    ### Approximate Γ(n+c+s−1)/Γ(n+c) to avoid overflow with large n ###\r\n    function gamma_ratio_approx(n) # Permits large N, since it avoids using large numbers\r\n        radical = ((ℯ^(1-s)) * ((n+c+s)^(s+0.5)) / ((n+c+1)^1.5)) ^ (1/(n+c))\r\n        return (radical * (n+c+s)/(n+c+1)) ^ (n+c) # Derived from Stirling's approximation for gamma\r\n    end\r\n\r\n    agammr = a*gamma(c+1) / gamma(c+s) # Constant term for determining the number of new nodes to add to a clique\r\n\r\n    cliques = [[i for i = 1:P(a)]] # Stores cliques\r\n    clique_count = [1 for i = 1:size(cliques[1],1)] # Stores how many cliques each node is part of\r\n\r\n    for n = 1:N-1\r\n        push!(cliques, []) # New empty clique\r\n        for k = 1:size(clique_count,1) # Decide which of existing nodes to place in new clique\r\n            if rand(Float64) <= (clique_count[k]-s) / (n+c)\r\n                push!(cliques[n+1], k)\r\n                clique_count[k] += 1\r\n            end\r\n        end\r\n\r\n        for j = 1:P(agammr*gamma_ratio_approx(n)) # Add new nodes to graph and clique\r\n            push!(cliques[n+1], size(clique_count,1)+1)\r\n            push!(clique_count, 1)\r\n        end\r\n    end\r\n\r\n    Z = zeros(Int64, N, size(clique_count,1)) # Convert clique list to edge clique cover.\r\n                                              # Z[i,j] = 1 iff clique i contains node j.\r\n    for i = 1:N\r\n        for j in cliques[i]\r\n            Z[i,j] = 1\r\n        end\r\n    end\r\n\r\n    mat = Z' * Z # Convert edge clique cover to corresponding adjacency matrix\r\n    mat -= Diagonal(mat) # Simplify matrix\r\n    mat = min.(mat, 1)\r\n\r\n    return MatrixNetwork(sparse(mat))\r\nend\r\n", "meta": {"hexsha": "1caf3a5767fa96ec43368d1c3de0cc6350a38bb3", "size": 3890, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/RandomCliqueCovers.jl", "max_stars_repo_name": "charunupara/HigherOrderNetworks.jl", "max_stars_repo_head_hexsha": "f0e72ea4134e40a19529f501f39448b8ba665906", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-18T23:21:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-18T23:21:16.000Z", "max_issues_repo_path": "src/RandomCliqueCovers.jl", "max_issues_repo_name": "joshua-matt/HigherOrderNetworks.jl", "max_issues_repo_head_hexsha": "a52750b619dfd58f311941162e14faeca076c5e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RandomCliqueCovers.jl", "max_forks_repo_name": "joshua-matt/HigherOrderNetworks.jl", "max_forks_repo_head_hexsha": "a52750b619dfd58f311941162e14faeca076c5e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-31T21:22:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-03T06:00:42.000Z", "avg_line_length": 37.7669902913, "max_line_length": 138, "alphanum_fraction": 0.6215938303, "num_tokens": 1059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164656, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.7534766232210235}}
{"text": "using Distributions, Random\nRandom.seed!(1)\n\nN = 10^6\nsig = 1.7\n\ndata1 = sqrt.(-(2* sig^2)*log.(rand(N)))\n\ndistG = Normal(0,sig)\ndata2 = sqrt.(rand(distG,N).^2 + rand(distG,N).^2)\n\ndistR = Rayleigh(sig)\ndata3 = rand(distR,N)\n\nmean.([data1, data2, data3])", "meta": {"hexsha": "dbb6f09f98337b9cdaea944a8b11a3a1fde42c43", "size": 254, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/rayleigh.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "3_chapter/rayleigh.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "3_chapter/rayleigh.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 16.9333333333, "max_line_length": 50, "alphanum_fraction": 0.6377952756, "num_tokens": 97, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.938124016006303, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7534766229695631}}
{"text": "eye(A) = A^0\nisnormal(A) = size(A,1) == size(A,2) && A'*A == A*A'\nisunitary(A) = size(A,1) == size(A,2) && A'*A == eye(A)\n", "meta": {"hexsha": "09a4642740fe363ae2df4aa29f57aa0d7b0e5179", "size": 122, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/conjugate-transpose-3.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/conjugate-transpose-3.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/conjugate-transpose-3.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5, "max_line_length": 55, "alphanum_fraction": 0.4836065574, "num_tokens": 57, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240090865198, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7534766196216756}}
{"text": "using LinearAlgebra\nA = [5 -2 -2; -2 4 -1; -2 -1 3]\nL = cholesky(A)\n##\nprintln(\"A = \")\ndisplay(A)\nprintln(\"L = \")\ndisplay(L.L)\n##\n@show norm(A - L.L*L.L')\n", "meta": {"hexsha": "c295c71c4afa78299077a35651cc120a2ca8fcd8", "size": 155, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4-unit-3-demos/cholesky-example.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "4-unit-3-demos/cholesky-example.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4-unit-3-demos/cholesky-example.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 14.0909090909, "max_line_length": 31, "alphanum_fraction": 0.5419354839, "num_tokens": 63, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9626731147976794, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7534481264488975}}
{"text": "function qnwbeta(n::Int, a::T, b::S) where {T <: Real, S <: Real}\n    a -= 1\n    b -= 1\n\n    maxit = 25\n\n    x = zeros(n)\n    w = zeros(n)\n\n    for i=1:n\n        if i == 1\n            an = a / n\n            bn = b / n\n            r1 = (1 + a) * (2.78 / (4 + n * n) + 0.768an / n)\n            r2 = 1 + 1.48 * an + 0.96bn + 0.452an*an + 0.83an*bn\n            z = 1 - r1 / r2\n\n        elseif i == 2\n            r1 = (4.1 + a) / ((1 + a) * (1 + 0.156a))\n            r2 = 1 + 0.06 * (n - 8) * (1 + 0.12a) / n\n            r3 = 1 + 0.012b * (1 + 0.25 * abs(a)) / n\n            z = z - (1 - z) * r1 * r2 * r3\n\n        elseif i == 3\n            r1 = (1.67 + 0.28a) / (1 + 0.37a)\n            r2 = 1 + 0.22 * (n - 8) / n\n            r3 = 1 + 8 * b / ((6.28 + b) * n * n)\n            z = z - (x[1] - z) * r1 * r2 * r3\n\n        elseif i == n - 1\n            r1 = (1 + 0.235b) / (0.766 + 0.119b)\n            r2 = 1 / (1 + 0.639 * (n - 4) / (1 + 0.71 * (n - 4)))\n            r3 = 1 / (1 + 20a / ((7.5+ a ) * n * n))\n            z = z + (z - x[n-3]) * r1 * r2 * r3\n\n        elseif i == n\n            r1 = (1 + 0.37b) / (1.67 + 0.28b)\n            r2 = 1 / (1 + 0.22 * (n - 8) / n)\n            r3 = 1 / (1 + 8 * a / ((6.28+ a ) * n * n))\n            z = z + (z - x[n-2]) * r1 * r2 * r3\n\n        else\n            z = 3 * x[i-1] - 3 * x[i-2] + x[i-3]\n        end\n\n        ab = a + b\n\n        for its = 1:maxit\n            temp = 2 + ab\n            p1 = (a - b + temp * z) / 2\n            p2 = 1\n            for j=2:n\n              p3 = p2\n              p2 = p1\n              temp = 2 * j + ab\n              aa = 2 * j * (j + ab) * (temp - 2)\n              bb = (temp - 1) * (a * a - b * b + temp * (temp - 2) * z)\n              c = 2 * (j - 1 + a) * (j - 1 + b) * temp\n              p1 = (bb * p2 - c * p3) / aa\n            end\n            pp = (n * (a - b - temp * z) * p1 +\n                  2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))\n            z1 = z\n            z = z1 - p1 ./ pp\n            if abs(z - z1) < 3e-14 break end\n        end\n\n        if its >= maxit\n            error(\"Failure to converge in qnwbeta1\")\n        end\n\n        x[i] = z\n        w[i] = temp / (pp * p2)\n    end\n\n    x = (1 - x) ./ 2\n    w = w * exp(gammaln(a + n) +\n                gammaln(b + n) -\n                gammaln(n + 1) -\n                gammaln(n + ab + 1))\n    w = w / (2 * exp(gammaln(a + 1) +\n                     gammaln(b + 1) -\n                     gammaln(ab + 2)))\n\n    return x, w\nend\n\n\n", "meta": {"hexsha": "701f23d7d1784520e7c110200a422e71331eb973", "size": 2475, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "other/quadrature.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/QuantEcon.jl-fcd29c91-0bd7-5a09-975d-7ac3f643a60c", "max_stars_repo_head_hexsha": "ff4697f2be73edbc905373fdf268056bdc93d129", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 455, "max_stars_repo_stars_event_min_datetime": "2015-01-16T18:10:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T20:08:45.000Z", "max_issues_repo_path": "other/quadrature.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/QuantEcon.jl-fcd29c91-0bd7-5a09-975d-7ac3f643a60c", "max_issues_repo_head_hexsha": "ff4697f2be73edbc905373fdf268056bdc93d129", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 236, "max_issues_repo_issues_event_min_datetime": "2015-01-26T20:56:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T15:19:56.000Z", "max_forks_repo_path": "other/quadrature.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/QuantEcon.jl-fcd29c91-0bd7-5a09-975d-7ac3f643a60c", "max_forks_repo_head_hexsha": "ff4697f2be73edbc905373fdf268056bdc93d129", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 364, "max_forks_repo_forks_event_min_datetime": "2015-01-15T18:04:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T21:24:53.000Z", "avg_line_length": 27.808988764, "max_line_length": 71, "alphanum_fraction": 0.2896969697, "num_tokens": 1042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7533904439705693}}
{"text": "module Haversine\n\nusing Parameters\n\nR = 6.371e6 # earth's volumetric mean radius in meters\n\n\n@with_kw struct GeoLocation\n    λ::Real\n    ϕ::Real\nend\n\n\nfunction HaversineDistance(p1::GeoLocation, p2::GeoLocation)::Float64\n    λ1, ϕ1 = p1.λ, p1.ϕ\n    λ2, ϕ2 = p2.λ, p2.ϕ\n    Δϕ = ϕ2 - ϕ1\n    Δλ = λ2 - λ1\n    a = sind(Δϕ / 2)^2 + cosd(ϕ1) * cosd(ϕ2) * sind(Δλ / 2)^2\n    c = 2 * atan(sqrt(a), sqrt(1 - a))\n    return c * R   \nend\n\n\nfunction HaversineBearing(p1::GeoLocation, p2::GeoLocation)::Float64\n    λ1, ϕ1 = p1.λ, p1.ϕ\n    λ2, ϕ2 = p2.λ, p2.ϕ\n    Δλ = λ2 - λ1\n    θ = atand(sind(Δλ) * cosd(ϕ2), cosd(ϕ1) * sind(ϕ2) - sind(ϕ1) * cosd(ϕ2) * cosd(Δλ))\n    return θ\nend\n\n\nfunction HaversineDestination(geopoint::GeoLocation, θ::Real, d::Real)::GeoLocation\n    λ1, ϕ1 = geopoint.λ, geopoint.ϕ\n    δ = d / R\n    ϕ2 = asind(sind(ϕ1) * cos(δ) + cosd(ϕ1) * sin(δ) * cosd(θ))\n    λ2 = λ1 + atand(sind(θ) * sin(δ) * cosd(ϕ1), cos(δ) - sind(ϕ1) * sind(ϕ2))\n    return GeoLocation(λ=λ2, ϕ=ϕ2)\nend\n\n\nfunction HaversineDistance(p1::AbstractArray{GeoLocation}, p2::AbstractArray{GeoLocation})::Vector{Float64}\n    return map(HaversineDistance, p1, p2)\nend\n\n\nfunction HaversineBearing(p1::AbstractArray{GeoLocation}, p2::AbstractArray{GeoLocation})::Vector{Float64}\n    return map(HaversineBearing, p1, p2)\nend\n\nfunction HaversineDestination(\n        p::Union{AbstractArray, GeoLocation},\n        θ::Union{AbstractArray, Real}, \n        d::Union{AbstractArray, Real}\n    )::Vector{GeoLocation}\n    if isa(p, GeoLocation)\n        return broadcast((y, z) -> HaversineDestination(p, y, z), θ, d)\n    end\n    return broadcast((x, y, z) -> HaversineDestination(x, y, z), p, θ, d)\nend\n\nexport GeoLocation, HaversineDistance, HaversineBearing, HaversineDestination\n\nend\n", "meta": {"hexsha": "491e9513d4065aab08df8ca8a734af433b08b590", "size": 1750, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Haversine.jl", "max_stars_repo_name": "techshot25/Haversine", "max_stars_repo_head_hexsha": "9b8bf34199e4ec0a32904cbe3f3d3d593f653957", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-02-15T06:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T20:03:56.000Z", "max_issues_repo_path": "src/Haversine.jl", "max_issues_repo_name": "techshot25/Haversine", "max_issues_repo_head_hexsha": "9b8bf34199e4ec0a32904cbe3f3d3d593f653957", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-02-06T02:44:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T19:58:17.000Z", "max_forks_repo_path": "src/Haversine.jl", "max_forks_repo_name": "techshot25/Haversine", "max_forks_repo_head_hexsha": "9b8bf34199e4ec0a32904cbe3f3d3d593f653957", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5151515152, "max_line_length": 107, "alphanum_fraction": 0.648, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7533904426383871}}
{"text": "# Linear Interpolation\nfunction (A::LinearInterpolation{<:AbstractVector{<:Number}})(t::Number)\n  idx = findfirst(x->x>=t,A.t)-1\n  idx == 0 ? idx += 1 : nothing\n  θ = (t - A.t[idx])/ (A.t[idx+1] - A.t[idx])\n  (1-θ)*A.u[idx] + θ*A.u[idx+1]\nend\n\nfunction (A::LinearInterpolation{<:AbstractMatrix{<:Number}})(t::Number)\n  idx = findfirst(x->x>=t,A.t)-1\n  idx == 0 ? idx += 1 : nothing\n  θ = (t - A.t[idx])/ (A.t[idx+1] - A.t[idx])\n  (1-θ)*A.u[:,idx] + θ*A.u[:,idx+1]\nend\n\n# Quadratic Interpolation\nfunction (A::QuadraticInterpolation{<:AbstractVector{<:Number}})(t::Number)\n  idx = findfirst(x->x>=t,A.t)-1\n  idx == 0 ? idx += 1 : nothing\n  if idx == length(A.t) - 1\n    i₀ = idx - 1; i₁ = idx; i₂ = i₁ + 1;\n  else\n    i₀ = idx; i₁ = i₀ + 1; i₂ = i₁ + 1;\n  end\n  l₀ = ((t-A.t[i₁])*(t-A.t[i₂]))/((A.t[i₀]-A.t[i₁])*(A.t[i₀]-A.t[i₂]))\n  l₁ = ((t-A.t[i₀])*(t-A.t[i₂]))/((A.t[i₁]-A.t[i₀])*(A.t[i₁]-A.t[i₂]))\n  l₂ = ((t-A.t[i₀])*(t-A.t[i₁]))/((A.t[i₂]-A.t[i₀])*(A.t[i₂]-A.t[i₁]))\n  A.u[i₀]*l₀ + A.u[i₁]*l₁ + A.u[i₂]*l₂\nend\n\nfunction (A::QuadraticInterpolation{<:AbstractMatrix{<:Number}})(t::Number)\n  idx = findfirst(x->x>=t,A.t)-1\n  idx == 0 ? idx += 1 : nothing\n  if idx == length(A.t) - 1\n    i₀ = idx - 1; i₁ = idx; i₂ = i₁ + 1;\n  else\n    i₀ = idx; i₁ = i₀ + 1; i₂ = i₁ + 1;\n  end\n  l₀ = ((t-A.t[i₁])*(t-A.t[i₂]))/((A.t[i₀]-A.t[i₁])*(A.t[i₀]-A.t[i₂]))\n  l₁ = ((t-A.t[i₀])*(t-A.t[i₂]))/((A.t[i₁]-A.t[i₀])*(A.t[i₁]-A.t[i₂]))\n  l₂ = ((t-A.t[i₀])*(t-A.t[i₁]))/((A.t[i₂]-A.t[i₀])*(A.t[i₂]-A.t[i₁]))\n  A.u[:,i₀]*l₀ + A.u[:,i₁]*l₁ + A.u[:,i₂]*l₂\nend\n\n# Lagrange Interpolation\nfunction (A::LagrangeInterpolation{<:AbstractVector{<:Number}})(t::Number)\n  idxs = findRequiredIdxs(A,t)\n  if A.t[idxs[1]] == t\n    return A.u[idxs[1]]\n  end\n  N = zero(A.u[1]); D = zero(A.t[1]); tmp = N\n  for i = 1:length(idxs)\n    mult = one(A.t[1])\n    for j = 1:(i-1)\n      mult *= (A.t[idxs[i]] - A.t[idxs[j]])\n    end\n    for j = (i+1):length(idxs)\n      mult *= (A.t[idxs[i]] - A.t[idxs[j]])\n    end\n    tmp = inv((t - A.t[idxs[i]]) * mult)\n    D += tmp\n    N += (tmp * A.u[idxs[i]])\n  end\n  N/D\nend\n\nfunction (A::LagrangeInterpolation{<:AbstractMatrix{<:Number}})(t::Number)\n  idxs = findRequiredIdxs(A,t)\n  if A.t[idxs[1]] == t\n    return A.u[:,idxs[1]]\n  end\n  N = zero(A.u[:,1]); D = zero(A.t[1]); tmp = D\n  for i = 1:length(idxs)\n    mult = one(A.t[1])\n    for j = 1:(i-1)\n      mult *= (A.t[idxs[i]] - A.t[idxs[j]])\n    end\n    for j = (i+1):length(idxs)\n      mult *= (A.t[idxs[i]] - A.t[idxs[j]])\n    end\n    tmp = inv((t - A.t[idxs[i]]) * mult)\n    D += tmp\n    @. N += (tmp * A.u[:,idxs[i]])\n  end\n  N/D\nend\n\nfunction (A::AkimaInterpolation{<:AbstractVector{<:Number}})(t::Number)\n  i = searchsortedlast(A.t, t)\n  i == 0 && return A.u[1]\n  i == length(A.t) && return A.u[end]\n  wj = t - A.t[i]\n  @evalpoly wj A.u[i] A.b[i] A.c[i] A.d[i]\nend\n\n# ZeroSpline Interpolation\nfunction (A::ZeroSpline{<:AbstractVector{<:Number}})(t::Number)\n  if A.dir === :left\n    # :left means that value to the left is used for interpolation\n    i = searchsortedlast(A.t, t)\n    return A.u[max(1, i)]\n  else\n    # :right means that value to the right is used for interpolation\n    i = searchsortedfirst(A.t, t)\n    return A.u[min(length(A.t), i)]\n  end\nend\n function (A::ZeroSpline{<:AbstractMatrix{<:Number}})(t::Number)\n  if A.dir === :left\n    # :left means that value to the left is used for interpolation\n    i = searchsortedlast(A.t, t)\n    return A.u[:, max(1, i)]\n  else\n    # :right means that value to the right is used for interpolation\n    i = searchsortedfirst(A.t, t)\n    return A.u[:, min(length(A.t), i)]\n  end\nend\n\n# QuadraticSpline Interpolation\nfunction (A::QuadraticSpline{<:AbstractVector{<:Number}})(t::Number)\n  i = findfirst(x->x>=t,A.t)\n  i == 1 ? i += 1 : nothing\n  Cᵢ = A.u[i-1]\n  σ = 1//2 * (A.z[i] - A.z[i-1])/(A.t[i] - A.t[i-1])\n  A.z[i-1] * (t - A.t[i-1]) + σ * (t - A.t[i-1])^2 + Cᵢ\nend\n\n# CubicSpline Interpolation\nfunction (A::CubicSpline{<:AbstractVector{<:Number}})(t::Number)\n  i = findfirst(x->x>=t,A.t)\n  i == nothing ? i = length(A.t) - 1 : i -= 1\n  i == 0 ? i += 1 : nothing\n  I = A.z[i] * (A.t[i+1] - t)^3 / (6A.h[i+1]) + A.z[i+1] * (t - A.t[i])^3 / (6A.h[i+1])\n  C = (A.u[i+1]/A.h[i+1] - A.z[i+1]*A.h[i+1]/6)*(t - A.t[i])\n  D = (A.u[i]/A.h[i+1] - A.z[i]*A.h[i+1]/6)*(A.t[i+1] - t)\n  I + C + D\nend\n\n# BSpline Curve Interpolation\nfunction (A::BSplineInterpolation{<:AbstractVector{<:Number}})(t::Number)\n  # change t into param [0 1]\n  idx = findfirst(x->x>=t,A.t) - 1\n  idx == 0 ? idx += 1 : nothing\n  t = A.p[idx] + (t - A.t[idx])/(A.t[idx+1] - A.t[idx]) * (A.p[idx+1] - A.p[idx])\n  n = length(A.t)\n  N = spline_coefficients(n,A.d,A.k,t)\n  ucum = zero(eltype(A.u))\n  for i = 1:n\n    ucum += N[i] * A.c[i]\n  end\n  ucum\nend\n\n# BSpline Curve Approx\nfunction (A::BSplineApprox{<:AbstractVector{<:Number}})(t::Number)\n  # change t into param [0 1]\n  idx = findfirst(x->x>=t,A.t) - 1\n  idx == 0 ? idx += 1 : nothing\n  t = A.p[idx] + (t - A.t[idx])/(A.t[idx+1] - A.t[idx]) * (A.p[idx+1] - A.p[idx])\n  n = length(A.t)\n  N = spline_coefficients(A.h,A.d,A.k,t)\n  ucum = zero(eltype(A.u))\n  for i = 1:A.h\n    ucum += N[i] * A.c[i]\n  end\n  ucum\nend\n\n# Loess\nfunction (A::Loess{<:AbstractVector{<:Number}})(t::Number)\n  tmp = sort(abs.(A.t .- t))\n  w = abs.(A.t .- t) ./ tmp[A.q]\n  for i = 1:length(A.t)\n    if w[i] <= one(A.t[1])\n      w[i] = (1 - (w[i] ^ 3)) ^ 3\n    else\n      w[i] = zero(A.t[1])\n    end\n  end\n  w = Diagonal(w)\n  b = inv(transpose(A.x) * w * A.x) * transpose(A.x) * w * A.u\n  u = zero(t[1])\n  for (idx,v) in enumerate(b)\n    u += v*(t^(idx-1))\n  end\n  u\nend\n\n# GaussianProcess\nfunction (A::GPInterpolation{<:AbstractVector{<:Number}})(t::AbstractVector{<:Number})\n  rand(A.gp,t,1)\nend\n\nfunction (A::GPInterpolation{<:AbstractVector{<:Number}})(t::Number)\n  rand(A.gp,[t],1)[1]\nend\n\n# Curvefit\nfunction (A::CurvefitCache{<:AbstractVector{<:Number}})(t::Union{AbstractVector{<:Number},Number})\n  A.m(t,A.pmin)\nend\n", "meta": {"hexsha": "1bede3ddb7992e330c57e4c947f67bd15289fe4f", "size": 5926, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/interpolation_alg/interpolation_methods.jl", "max_stars_repo_name": "UnofficialJuliaMirror/DataInterpolations.jl-82cc6244-b520-54b8-b5a6-8a565e85f1d0", "max_stars_repo_head_hexsha": "383f63b92bbfd689633b43e6d30974e845459b26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/interpolation_alg/interpolation_methods.jl", "max_issues_repo_name": "UnofficialJuliaMirror/DataInterpolations.jl-82cc6244-b520-54b8-b5a6-8a565e85f1d0", "max_issues_repo_head_hexsha": "383f63b92bbfd689633b43e6d30974e845459b26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/interpolation_alg/interpolation_methods.jl", "max_forks_repo_name": "UnofficialJuliaMirror/DataInterpolations.jl-82cc6244-b520-54b8-b5a6-8a565e85f1d0", "max_forks_repo_head_hexsha": "383f63b92bbfd689633b43e6d30974e845459b26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1921182266, "max_line_length": 98, "alphanum_fraction": 0.5437057037, "num_tokens": 2481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7533904390799334}}
{"text": "using SpecialFunctions\nusing Statistics\nusing FFTW\n\nfunction fMultiSinGen(N::Integer,\n                      P::Integer,\n                      M::Integer;\n                      fMin::Float64=0.99,\n                      fMax::Float64=1.00,\n                      fs::Float64=1.0,\n                      type_signal::String=\"full\",\n                      nGroup::Integer=3,\n                      uStd::Float64=1.)\n    \"\"\"\n    generates a zero-mean random phase multisine with std = 1\n    INPUT\n    options.N: number of points per period\n    options.P: number of periods\n    options.M: number of realizations\n    options.fMin: minimum excited frequency\n    options.fMax: maximum escited frequency\n    options.fs: sample frequency\n    options.type: \"full\", \"odd\", \"oddrandom\"\n    \n    OPTIONAL\n    options.nGroup: in case of oddrandom, 1 out of nGroup odd lines is\n                     discarded. Default = 3\n    options.std: std of the generated signals. Default = 1\n    \n    OUTPUT\n    u: NPxM record of the generated signals\n    lines: excited frequency lines -> 1 = dc, 2 = fs/N\n     \n    copyright:\n    Maarten Schoukens\n    Vrije Universiteit Brussel, Brussels Belgium\n    10/05/2017\n    \n    translated from Matlab to Julia by\n    Wouter Kouw\n    TU Eindhoven, Eindhoven, Netherlands\n    22/01/2021\n    \n    This work is licensed under a \n    Creative Commons Attribution-NonCommercial 4.0 International License\n    (CC BY-NC 4.0)\n    https://creativecommons.org/licenses/by-nc/4.0/\n    \"\"\"\n\n    # Lines selection - select which frequencies to excite\n    f0 = fs/N\n    linesMin = Int64(ceil(fMin / f0) + 1)\n    linesMax = Int64(floor(fMax / f0) + 1)\n    lines = linesMin:linesMax\n\n    # Remove DC component\n    if lines[1] == 1; lines = lines[2:end]; end\n\n    if type_signal == \"full\"\n        # do nothing\n    elseif type_signal == \"odd\"\n        \n        # remove even lines - odd indices\n        if Bool(mod(lines[1],2)) # lines(1) is odd\n            lines = lines[2:2:end]\n        else\n            lines = lines[1:2:end]\n        end\n\n    elseif type_signal == \"oddrandom\"\n        \n        # remove even lines - odd indices\n        if Bool(mod(lines[1],2)) # lines(1) is odd\n            lines = lines[2:2:end]\n        else\n            lines = lines[1:2:end]\n        end\n        \n        # remove 1 out of nGroup lines\n        nLines = length(lines)\n        nRemove = floor(nLines / nGroup)\n        removeInd = rand(1:nGroup, [1 nRemove])\n        removeInd = removeInd + nGroup*[0:nRemove-1]\n        lines = lines(!removeInd)\n    end\n    nLines = length(lines)\n\n    # multisine generation - frequency domain implementation\n    U = zeros(ComplexF64, N,M)\n\n    # excite the selected frequencies\n    U[lines,:] = exp.(2im*pi*rand(nLines,M))\n    \n    # go to time domain\n    u = real(ifft(U))\n    \n    # rescale to obtain desired rms std\n    u = uStd * u ./ std(u[:,1])\n\n    # generate P periods\n    u = repeat(u, outer=(P,1))\n\n    return u, lines\nend", "meta": {"hexsha": "26a3cd54f3d208012606ca639205cf59961d2cbc", "size": 2946, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiments/gen-data/fMultiSinGen.jl", "max_stars_repo_name": "biaslab/CDC2021-vmpNARMAX", "max_stars_repo_head_hexsha": "dcc640c21aef37cedbd625c8a380c747c0fb9fe5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments/gen-data/fMultiSinGen.jl", "max_issues_repo_name": "biaslab/CDC2021-vmpNARMAX", "max_issues_repo_head_hexsha": "dcc640c21aef37cedbd625c8a380c747c0fb9fe5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experiments/gen-data/fMultiSinGen.jl", "max_forks_repo_name": "biaslab/CDC2021-vmpNARMAX", "max_forks_repo_head_hexsha": "dcc640c21aef37cedbd625c8a380c747c0fb9fe5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3269230769, "max_line_length": 72, "alphanum_fraction": 0.5773930754, "num_tokens": 788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7533904390799334}}
{"text": "\"\"\"\n    AbstractNumbers\n\nAn abstract type to represent the number system on which a manifold is built.\n\nThis provides concrete number types for dispatch. The two most common number types are\nthe fields [`RealNumbers`](@ref) (`ℝ` for short) and [`ComplexNumbers`](@ref) (`ℂ`).\n\"\"\"\nabstract type AbstractNumbers end\n\n\"\"\"\n    ℝ = RealNumbers()\n\nThe field of real numbers.\n\"\"\"\nstruct RealNumbers <: AbstractNumbers end\n\n\"\"\"\n    ℂ = ComplexNumbers()\n\nThe field of complex numbers.\n\"\"\"\nstruct ComplexNumbers <: AbstractNumbers end\n\n\"\"\"\n    ℍ = QuaternionNumbers()\n\nThe division algebra of quaternions.\n\"\"\"\nstruct QuaternionNumbers <: AbstractNumbers end\n\nconst ℝ = RealNumbers()\nconst ℂ = ComplexNumbers()\nconst ℍ = QuaternionNumbers()\n\nBase.show(io::IO, ::RealNumbers) = print(io, \"ℝ\")\nBase.show(io::IO, ::ComplexNumbers) = print(io, \"ℂ\")\nBase.show(io::IO, ::QuaternionNumbers) = print(io, \"ℍ\")\n\n^(𝔽::AbstractNumbers, n) = Euclidean(n...; field = 𝔽)\n\n@doc doc\"\"\"\n    real_dimension(𝔽::AbstractNumbers)\n\nReturn the real dimension $\\dim_ℝ 𝔽$ of the [`AbstractNumbers`] system `𝔽`.\nThe real dimension is the dimension of a real vector space with which a number in `𝔽` can be\nidentified.\nFor example, [`ComplexNumbers`](@ref) have a real dimension of 2, and\n[`QuaternionNumbers`](@ref) have a real dimension of 4.\n\"\"\"\nfunction real_dimension(𝔽::AbstractNumbers)\n    error(\"real_dimension not defined for number system $(𝔽)\")\nend\nreal_dimension(::RealNumbers) = 1\nreal_dimension(::ComplexNumbers) = 2\nreal_dimension(::QuaternionNumbers) = 4\n", "meta": {"hexsha": "dc9b7ebca21a5794be4a1c3d2105c60a4c5c5f5d", "size": 1531, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/numbers.jl", "max_stars_repo_name": "manuelweisser/Manifolds.jl", "max_stars_repo_head_hexsha": "07f889a290ece01569c6c53bb0c96a5608923a0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/numbers.jl", "max_issues_repo_name": "manuelweisser/Manifolds.jl", "max_issues_repo_head_hexsha": "07f889a290ece01569c6c53bb0c96a5608923a0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/numbers.jl", "max_forks_repo_name": "manuelweisser/Manifolds.jl", "max_forks_repo_head_hexsha": "07f889a290ece01569c6c53bb0c96a5608923a0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-09T10:46:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-09T10:46:39.000Z", "avg_line_length": 26.8596491228, "max_line_length": 92, "alphanum_fraction": 0.7191378184, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7533904364155695}}
{"text": "using DataDrivenDiffEq\nusing ModelingToolkit\nusing OrdinaryDiffEq\n\nusing Dierckx\nusing Statistics\nusing LinearAlgebra\nusing Plots\ngr()\n\n# Create a test problem\nfunction lorenz(u,p,t)\n    x, y, z = u\n\n    ẋ = 10.0*(y - x)\n    ẏ = x*(28.0-z) - y\n    ż = x*y - (8/3)*z\n    return [ẋ, ẏ, ż]\nend\n\nu0 = [-8.;8.;27.]\ntspan = (0.0,200.0)\ndt = 0.001\nprob = ODEProblem(lorenz,u0,tspan)\nsol = solve(prob, Tsit5(), reltol = 1e-12, abstol = 1e-12,  saveat = dt)\n\nplot(sol,vars=(1,2,3))\n\n# Differential data from equations\nX = Array(sol)\n\n\n# Time delay coordinates\nstackmax = 100\n\nH = zeros(eltype(x), stackmax, size(X,2)-stackmax)\nfor i in 1:stackmax\n    H[i, :] = X[1, i:end-stackmax+i-1]\nend\n\n\nm,n = minimum(size(H)), maximum(size(H))\nU, S, V = svd(H, full = false)\nτ = DataDrivenDiffEq.optimal_svht(m,n)\nr = length(S[S .> τ*median(S)])\nr = minimum([15, r])\n\nz = Array(V[:, 1:r]')\ndz = similar(z)\n\nfor (i, vi) in enumerate(eachrow(z))\n    x_int = Spline1D(sol.t[1:length(vi)], vi)\n    dz[i, :] = derivative(x_int, sol.t[1:length(vi)])\nend\n\n\nplot(plot(z[1, :]),plot(z[end, :].^2),  layout = (2, 1))\n\n@variables u[1:r]\n\nbasis = Basis(u, u)\nopt = SR3(1e-1)\nb = SInDy(z[:, 1:end], dz[1:end-1, 1:end], basis, maxiter = 1000, opt = opt, normalize = true)\n\n# Coincides with the paper results\nprintln(b)\n", "meta": {"hexsha": "92ace4208cc9e85e869301215b7e9dac9d32cf79", "size": 1291, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Havok_Examples.jl", "max_stars_repo_name": "DanielParraUnam/DataDrivenDiffEq.jl", "max_stars_repo_head_hexsha": "8e81616be8463983fb0be9cf14f273b49c2a81ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-23T15:35:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-23T15:35:00.000Z", "max_issues_repo_path": "examples/Havok_Examples.jl", "max_issues_repo_name": "DanielParraUnam/DataDrivenDiffEq.jl", "max_issues_repo_head_hexsha": "8e81616be8463983fb0be9cf14f273b49c2a81ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Havok_Examples.jl", "max_forks_repo_name": "DanielParraUnam/DataDrivenDiffEq.jl", "max_forks_repo_head_hexsha": "8e81616be8463983fb0be9cf14f273b49c2a81ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2686567164, "max_line_length": 94, "alphanum_fraction": 0.6165762974, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7533904335992064}}
{"text": "# Hellwarth 1999 PRB - Part IV; T-dep of the Feynman variation parameter\n# A Friday afternoon of hacking to try and implement the T-dep electron-phonon coupling from the above PRB\n# Which was unusually successful! And more or less reproduced Table III\n\n# one-dimensional numerical integration in Julia using adaptive Gauss-Kronrod quadrature\nusing QuadGK\n\n# Equation numbers follow above Hellwarth 1999 PRB\n# 62b\nA(v,w,β)=3/β*( log(v/w) - 1/2*log(2*π*β) - log(sinh(v*β/2)/sinh(w*β/2)))\n\n# 62d\nY(x,v,β)=1/(1-exp(-v*β))*(1+exp(-v*β)-exp(-v*x)-exp(v*(x-β)))\n# 62c integrand\nf(x,v,w,β)=(exp(β-x)+exp(x))/(w^2*x*(1-x/β)+Y(x,v,β)*(v^2-w^2)/v)^(1/2)\n# 62c\nB(v,w,β,α) = α*v/(sqrt(π)*(exp(β)-1)) * quadgk(x->f(x,v,w,β),0,β/2)[1]\n#62e\nC(v,w,β)=3/4*(v^2-w^2)/v * (coth(v*β/2)-2/(v*β))\n\nF(v,w,β,α)=-(A(v,w,β)+B(v,w,β,α)+C(v,w,β)) #(62a)\n\n# Can now evaluate, e.g.\n# F(v,w,β,α)=F(7.2,6.5,1.0,1.0)\n# BUT - this is just the objective function! Not the optimised parameters.\n# Also there's a scary numeric integration (quadgk) buried within...\n\n\n\"Print out F(alpha,beta) for a specific v,w; as a test\"\nfunction test_fns()\n    @printf(\"\\t\\t\")\n    for α in 1:5\n        @printf(\"α=%d\\t\\t\",α)\n    end\n    @printf(\"\\n\")\n\n    for β in 1:0.25:3.0\n        v=w=4\n        print(\"β: $β  \\t||\")\n        for α in 1:5\n            @printf(\"%f\\t\",F(v,w,β,α))\n        end\n        println()\n    end\nend\n\ntest_fns()  # OK - very primitive!\n\n\"\nThese are 1D traces along the solution for Alpha=Beta=1 in Helwarth PRB TABLE III,\nthis was used to correct a transcription error in the above typed-in equations\nIt was also good to see what F(v,w) looked like as a function of v and w near an optimal solution\"\nfunction test_trace()\n\tv=7.20\n\tw=6.5\n\tα=1.0\n\tβ=1.0\n\n\tfor v=6:0.1:8\n    \t@printf(\"%f %f\\n\",v,F(v,w,β,α))\n\tend\n\n\t@printf(\"\\n\")\n\tv=7.20\n\tfor w=6:0.1:7\n    \t@printf(\"%f %f\\n\",w,F(v,w,β,α))\n\tend\nend\ntest_trace()\n\n# Angle for the ringside seats, when the fall, don't blame me, Bring on the Major Leagues\nusing Optim\n# Julia package stuffed full of magic, does auto-differentation & etc. etc.\n\nFopt(x) = F(x[1],x[2],1,1)\n\nfunction test_Fopt()\n    show(Fopt([7.2,6.5]))\n# OK! It looks like I can bury the alpha, beta parameters (which we don't optimise), by wrapping our function in a function definition.\n    initial=[7.2,6.5]\n\n    show(optimize(Fopt,  initial, LBFGS()))\n\n    show(optimize(Fopt, initial, BFGS(), Optim.Options(autodiff=true)))\nend\n\ntest_Fopt()\n\nfunction test_Optim()\n\t# After a bit of fiddling, I figured out how to add bounds, to stop that 'DomainError', \n\t# which occurs where the you are evaluating log(-ve Real), i.e. w<0.0 or v<0.0\n\n\tinitial=[7.2,6.5]\n\n\tlower=[0.0,0.0]\n\tupper=[10.0,10.0]\n\n\t@printf(\"\\t\\t\")\n\tfor α in 1:5\n\t\t@printf(\"α=%d\\t\\t\",α)\n\tend\n\t@printf(\"\\n\")\n\n\tfor β in 1:0.25:3.0\n\t\tprint(\"β: $β  \\t||\")\n\t\tfor α in 1:5\n\t\t\tmyf(x) = F(x[1],x[2],β,α)\n\t\t\tsolution=optimize(DifferentiableFunction(myf), initial, lower, upper, Fminbox(); optimizer = ConjugateGradient, optimizer_o=Optim.Options(autodiff=true))\n\t\t\tminimum=Optim.minimizer(solution)\n\n\t\t\tv=minimum[1]\n\t\t\tw=minimum[2]\n\t\t\t#print(solution,\"\\t\")\n\t\t\t@printf(\"%.2f %.2f\\t\",v,w)\n\n\n\t\tend\n\t\tprintln()\n\tend \nend\n\ntest_Optim()\n\nfunction test_Optimisers()\n\t# So that looks really good! I was super stoked to see how close these values are to TABLE III in Hellwarth\n\t# However, the solutions all start on (7.20,6.50) so that top-left data point is cheating, whereas the \n\t# others have some disagreement / noise associated with them\n\t# I was wondering whether it might be a function of the optimiser, so thought I'd try them all\n\n\tinitial=[7.1,6.5]\n\t# Main use of these bounds is stopping v or w going negative, at which you get a NaN error as you are evaluating log(-ve Real)\n\tlower=[1.0,1.0]\n\tupper=[10.0,10.0]\n\n\tfor optimizer in [BFGS, LBFGS, ConjugateGradient] # Newton, GradientDescent, NelderMead - steps outside box & log(-ve)->NaN error\n\t\t@printf(\"\\n\\t\\t##### NOW TRIALING: %s #####\\n\\n\",optimizer)\n\n\t\t@printf(\"\\t\\t\")\n\t\tfor α in 1:5\n\t\t\t@printf(\"α=%d\\t\\t\",α)\n\t\tend\n\t\t@printf(\"\\n\")\n\n\t\tfor β in 1:0.25:3.0\n\t\t\tprint(\"β: $β  \\t||\")\n\t\t\tfor α in 1:5\n\t\t\t\tmyf(x) = F(x[1],x[2],β,α)\n\t\t\t\tres=optimize(DifferentiableFunction(myf), initial, lower, upper, Fminbox(); optimizer = optimizer, optimizer_o=Optim.Options(autodiff=true))\n\t\t\t\tminimum=Optim.minimizer(res)\n\t\t\t\t#show(Optim.converged(res)) # All came out as 'true'\n\n\t\t\t\t#print(solution,\"\\t\")\n\t\t\t\t@printf(\"%.2f %.2f\\t\",minimum[1],minimum[2])\n\t\t\tend\n\t\t\tprintln()\n\t\tend\n\tend\nend\n\ntest_Optimisers()\n\n", "meta": {"hexsha": "3c9e65e21443052337022031ffa5686c952378cb", "size": 4482, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/FeynmanKadanoffOsakaHellwarth-extratests.jl", "max_stars_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_stars_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-07-26T17:46:18.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-26T17:46:18.000Z", "max_issues_repo_path": "test/FeynmanKadanoffOsakaHellwarth-extratests.jl", "max_issues_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_issues_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/FeynmanKadanoffOsakaHellwarth-extratests.jl", "max_forks_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_forks_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6666666667, "max_line_length": 156, "alphanum_fraction": 0.6452476573, "num_tokens": 1625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7533904322670242}}
{"text": "module IsingMCMC\n\nfunction genFunctor( Jd, Bd)\n    Jd = Jd\n    Bd = Bd\n    \n    # E(S) = - 1/2\\sum_{i,j, i not j} J_{i,j} si sj - \\sum_i B_i si\n    function E(S, N)\n        local Et = 0\n        for i in 1:N\n            for (j,Jv) in Jd[i]\n                @inbounds Et += -S[i]*Jv*S[j]/2\n            end\n            @inbounds Et += -S[i]*Bd[i]\n        end\n        Et\n    end\n\n    # differential energy\n    function dE(S, k, N)\n        local dEt = 0\n        for (j,Jv) in Jd[k]\n            @inbounds dEt += S[k]*Jv*S[j]*2\n        end\n        @inbounds dEt += S[k]*Bd[k]*2\n        dEt\n    end\n\n    # probability for dE\n    PrE(dE, T) = exp(-dE/T)\n\n    # flip spin at x\n    function flipx!(list, x)\n        list[x] *= -1\n    end\n\n    # MCMC\n    function MCMC( T, N, trial)\n        # initialize\n        simE = zeros(Int, div(trial,1000)+1)\n        S = ones(Int8, N)\n        for i in 1:N\n            if rand() < 0.5\n                flipx!(S,i) # random flip at first\n            end\n        end\n\n        # MCMC trial\n        Ec = E(S,N) # current energy\n        simE[1] = Ec\n        local k, de\n        @inbounds for t in 1:trial\n            k  = rand(1:N) # Gibbs sampling position\n            de = dE(S, k, N)\n            if rand() < PrE(de, T) # MH criteria   \n                flipx!(S, k) # change k\n                Ec += de     # change E\n            end\n            (t % 1000 == 0) && (simE[div(t,1000)+1] = Ec)\n        end\n\n        (simE, S)\n    end\n    \n    return (E, MCMC)\nend # of functor\n\nend # of module", "meta": {"hexsha": "079620a135cff278a585a74f040426221135dcd4", "size": 1510, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src.03a/IsingMCMC03a.jl", "max_stars_repo_name": "okimebarun/03_IsingMCMC.jl", "max_stars_repo_head_hexsha": "c09366c1fad1def0d336fa07eae6e23bcbd93edc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src.03a/IsingMCMC03a.jl", "max_issues_repo_name": "okimebarun/03_IsingMCMC.jl", "max_issues_repo_head_hexsha": "c09366c1fad1def0d336fa07eae6e23bcbd93edc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src.03a/IsingMCMC03a.jl", "max_forks_repo_name": "okimebarun/03_IsingMCMC.jl", "max_forks_repo_head_hexsha": "c09366c1fad1def0d336fa07eae6e23bcbd93edc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2058823529, "max_line_length": 67, "alphanum_fraction": 0.4284768212, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7533904301927516}}
{"text": "\"\"\" Julia program to Check if a number is a Mystery Number or Not.\n\nA mystery number is that number which can be expressed as a sum of two \nnumbers and those two numbers must be the reverse of each other\n\"\"\"\n\n\nfunction reverse(n)\n    rev = 0\n    while n > 0\n        rev = rev * 10\n        rev = rev + (n % 10);\n        n = n ÷ 10\n    end\n    return rev\nend\n\n\nfunction check_mystery_num(n)\n    # Let us iterate from 1 upto n/2, to check if there is any pair, such that thier\n    # sum equals the given number and check if the pair are reverse of each other \n    temp = n ÷ 2\n    for i in 1:(temp)\n        if (reverse(i) == (n - i))\n            return true\n        end\n    end\n    return false\nend\n\n\nprint(\"Enter the number: \")\nnum = readline()\nnum = parse(Int, num)\nres = check_mystery_num(num)\nif res\n    println(\"The given number $num is a Mystery Number.\")\nelse\n    println(\"The given number $num is not a Mystery Number.\")\nend\n\n\"\"\"\nTime Complexity: O(n*log(n)), where 'n' is the given number\nSpace Complexity: O(1)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE 1\nEnter the number: 43234\nThe given number 43234 is a Mystery Number.\n\nSAMPLE 2\nEnter the number: 1234\nThe given number 1234 is not a Mystery Number.\n\n\"\"\"\n", "meta": {"hexsha": "7b03d11f79ed2bbd468e340496f6ce9712d26d61", "size": 1206, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/math/mystery_number.jl", "max_stars_repo_name": "zhcet19/NeoAlgo-1", "max_stars_repo_head_hexsha": "c534a23307109280bda0e4867d6e8e490002a4ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 897, "max_stars_repo_stars_event_min_datetime": "2020-06-25T00:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:49:31.000Z", "max_issues_repo_path": "Julia/math/mystery_number.jl", "max_issues_repo_name": "zhcet19/NeoAlgo-1", "max_issues_repo_head_hexsha": "c534a23307109280bda0e4867d6e8e490002a4ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5707, "max_issues_repo_issues_event_min_datetime": "2020-06-24T17:53:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T05:03:15.000Z", "max_forks_repo_path": "Julia/math/mystery_number.jl", "max_forks_repo_name": "zhcet19/NeoAlgo-1", "max_forks_repo_head_hexsha": "c534a23307109280bda0e4867d6e8e490002a4ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1817, "max_forks_repo_forks_event_min_datetime": "2020-06-25T03:51:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:14:07.000Z", "avg_line_length": 21.1578947368, "max_line_length": 84, "alphanum_fraction": 0.6542288557, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.8688267677469952, "lm_q1q2_score": 0.7533038707398312}}
{"text": "function rbc()\n    @parameters α β ρ δ σ Ω_1\n    @variables k z c q i\n    @make_markov k z c q i\n    x = [k, z]\n    y = [c, q, i]\n    p = [α, β, ρ]\n    p_f = [δ, σ, Ω_1]\n\n    H = [1 / c - (β / c_p) * (α * exp(z_p) * k_p^(α - 1) + (1 - δ)),\n         c + k_p - (1 - δ) * k - q,\n         q - exp(z) * k^α,\n         z_p - ρ * z,\n         i - (k_p - (1 - δ) * k)]\n\n    x̄ = [k_ss ~ (((1 / β) - 1 + δ) / α)^(1 / (α - 1)), z_ss ~ 0]\n    ȳ = [c_ss ~ (((1 / β) - 1 + δ) / α)^(α / (α - 1)) -\n                δ * (((1 / β) - 1 + δ) / α)^(1 / (α - 1)),\n         q_ss ~ (((1 / β) - 1 + δ) / α)^(α / (α - 1)),\n         i_ss ~ δ * (((1 / β) - 1 + δ) / α)^(1 / (α - 1))]\n\n    x̄_iv = [z_ss ~ 0, k_ss ~ (((1 / β) - 1 + δ) / α)^(1 / (α - 1))]\n    ȳ_iv = [q_ss ~ (((1 / β) - 1 + δ) / α)^(α / (α - 1)),\n            c_ss ~ (((1 / β) - 1 + δ) / α)^(α / (α - 1)) -\n                    δ * (((1 / β) - 1 + δ) / α)^(1 / (α - 1)),\n            i_ss ~ δ * (((1 / β) - 1 + δ) / α)^(1 / (α - 1))]\n\n    n_ϵ = 1\n    n_z = 2\n    n_x = length(x)\n    n_y = length(y)\n    n_p = length(p)\n    Γ = reshape([σ], n_ϵ, n_ϵ)\n    η = reshape([0; -1], n_x, n_ϵ) # η is n_x * n_ϵ matrix\n\n    Q = zeros(n_z, n_y + n_x) # The order is [y, x]\n    Q[1, 1] = 1.0 # c \n    Q[2, 3] = 1.0 # i\n\n    Ω = [Ω_1, Ω_1]\n\n    return H, (; x, y, x̄, ȳ, Γ, η, p_f, p, x̄_iv, ȳ_iv, Ω, Q), \"rbc\"\nend\n", "meta": {"hexsha": "0e480a7a159e0b2c5b77dab4aed5fd04ce4ee928", "size": 1339, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "deps/rbc.jl", "max_stars_repo_name": "janrosa1/HMCExamples.jl", "max_stars_repo_head_hexsha": "f3b1519d31498572b44b0e58a1310d0156ac5156", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/rbc.jl", "max_issues_repo_name": "janrosa1/HMCExamples.jl", "max_issues_repo_head_hexsha": "f3b1519d31498572b44b0e58a1310d0156ac5156", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/rbc.jl", "max_forks_repo_name": "janrosa1/HMCExamples.jl", "max_forks_repo_head_hexsha": "f3b1519d31498572b44b0e58a1310d0156ac5156", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4318181818, "max_line_length": 71, "alphanum_fraction": 0.3174010456, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305638, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.7532918568745137}}
{"text": "using DelimitedFiles\n\nfunction sigmoid(x)\n        return 1/(1+exp.(-x));\nend\n\n# Set manually so that scaling is equivalent to training set.\nresistanceMean = 49999.784590407784;\nresistanceStdDev = 28617.43200535356;\ncapacitanceMean = 4.894379617495234e-6;\ncapacitanceStdDev = 2.9095702774112495e-6;\ntimeMean = 0.6064870129571632;\ntimeStdDev = 0.7246955112804028;\n\nlayerOneWeights = readdlm(\"layer1.csv\", ',', Float64, '\\n');\nlayerTwoWeights = readdlm(\"layer2.csv\", ',', Float64, '\\n');\n\ndata = readdlm(ARGS[1], ',', Float64, '\\n');\nnumOfTestPoints = size(data, 2);\n\ninputs = vcat(data[1:3,:], ones(numOfTestPoints)'); # Adds row of ones for bias term in weights\nexpectedOutput = data[4,:];\nprint(size(expectedOutput))\n \n# Normalize inputs\ninputs[1,:] .-= resistanceMean;\ninputs[1,:] ./= resistanceStdDev;\ninputs[2,:] .-= capacitanceMean;\ninputs[2,:] ./= capacitanceStdDev;\ninputs[3,:] .-= timeMean;\ninputs[3,:] ./= timeStdDev;\n\nglobal cost = 0.0;\n\nfor i = 1:numOfTestPoints\n        netOne = layerOneWeights * inputs[:,i];\n        outputOne = vcat(sigmoid.(netOne), 1);\n       \n        netTwo = layerTwoWeights * outputOne;\n        outputTwo = netTwo[1];\n\n        absoluteError = outputTwo - expectedOutput[i];\n        global cost += absoluteError .^ 2;\n        percentError = abs(absoluteError / expectedOutput[i]) * 100;\n\n        print(\"Percent error at test point \", i, \": \", percentError, \"% \\n\")\nend\n\nglobal cost /= numOfTestPoints;\n\nprint(\"Total MSE: \", cost, '\\n')\n", "meta": {"hexsha": "25b0b84dee9d61132c1f6d54283885942c19177b", "size": 1470, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "run_net.jl", "max_stars_repo_name": "benjaminglass1/neural_proj", "max_stars_repo_head_hexsha": "6e5cefc4c08775f5047cd9eda3291a5f2f343a12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "run_net.jl", "max_issues_repo_name": "benjaminglass1/neural_proj", "max_issues_repo_head_hexsha": "6e5cefc4c08775f5047cd9eda3291a5f2f343a12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "run_net.jl", "max_forks_repo_name": "benjaminglass1/neural_proj", "max_forks_repo_head_hexsha": "6e5cefc4c08775f5047cd9eda3291a5f2f343a12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2692307692, "max_line_length": 95, "alphanum_fraction": 0.6693877551, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.7532918457861492}}
{"text": "module SolarModel\n\nusing ..vSmartMOM               # For locating default solar T\nusing DocStringExtensions       # For simplifying docstring\nusing DelimitedFiles            # For easily reading in solar spectrum \nusing Interpolations            # For interpolating solar spectrum\nusing Pkg.Artifacts             # For default solar spectrum\n\n\"\"\"\n    $(FUNCTIONNAME)(T::Real, ν_grid::Vector)\n\nProduce the black-body planck spectrum (mW/m²-sr-cm⁻¹), given the temperature (K) \nand calculation grid (ν in cm⁻¹)\n\n\"\"\"\nfunction planck_spectrum_wn(T::Real, ν_grid::Vector)\n\n    c1 = 1.1910427 * 10^(-5)    # mW/m²-sr-cm⁻¹\n    c2 = 1.4387752              # K⋅cm\n\n    # L(ν, T) = c1⋅ν³/(exp(c2⋅ν/T) - 1)\n    radiance = c1 .* (ν_grid.^3) ./ (exp.(c2 * ν_grid / T) .- 1)\n\n    return radiance\nend\n\n\"\"\"\n    $(FUNCTIONNAME)(T::Real, λ_grid::Vector)\n\nProduce the black-body planck spectrum (W/m²-sr-μm), given the temperature (K) \nand calculation grid (λ in μm)\n\n\"\"\"\nfunction planck_spectrum_wl(T::Real, λ_grid::Vector)\n\n    c1 = 1.1910427 * 10^8    # W/m²-sr-μm\n    c2 = 1.4387752 * 10^4    # K⋅μm\n\n    # L(ν, T) = c1⋅ν³/(exp(c2⋅ν/T) - 1)\n    radiance = c1 ./ (λ_grid.^5 .* (exp.(c2 ./ (λ_grid * T)) .- 1))\n\n    return radiance\nend\n\n# W/m²-sr-μm to Ph/s-m²-sr-um\n# λ_grid in micron\nfunction watts_to_photons(λ_grid::Vector, radiance::Vector)\n\n    h = 6.62607015e-34 # J⋅Hz−1\n    c = 299792458 # m/s\n\n    E_per_λ = h * c ./ (λ_grid / 1e6)\n    photons = radiance ./ E_per_λ\n\n    return photons\nend\n\n\"\"\"\n    $(FUNCTIONNAME)(T::Real; stride_length::Integer = 100)\n\nProduce the black-body planck spectrum (mW/m²-sr-cm⁻¹), given the temperature (K). \nUse a unit calculation grid and check for convergence every `stride_length` cm⁻¹ until the \nspectrum dies off. \n\n\"\"\"\nfunction planck_spectrum_wn(T::Real; stride_length::Integer = 100)\n\n    # νs, starting with ν0 = 1.0 cm⁻¹\n    νs = [1.0]\n\n    # radiances corresponding with νs\n    radiances = planck_spectrum_wn(T, νs)\n\n    # Loop until convergence\n    while true \n        \n        # Add the next ν\n        νs = vcat(νs, collect(νs[end] + 1 : νs[end] + stride_length))\n\n        # Compute the next radiance\n        radiances = vcat(radiances, planck_spectrum_wn(T, νs[(end - stride_length + 1) : end]))\n\n        # Exit if spectrum has died off\n        (radiances[end] < radiances[1]) && break \n\n    end\n\n    return [νs[1:(end-1)] radiances[1:(end-1)]]\nend\n\n\"\"\"\n    $(FUNCTIONNAME)(solar, ν_grid)\n\nInterpolate a solar linelist to the ν_grid\n\"\"\"\nfunction itp_solar_to_ν_grid(solar, ν_grid)\n\n    solar_idx_start = maximum((argmin(abs.(solar[:, 1] .- minimum(ν_grid))) - 10, 1))\n    solar_idx_end   = minimum((argmin(abs.(solar[:, 1] .- maximum(ν_grid))) + 10, length(solar[:,1])))\n\n    solar_subset = solar[solar_idx_start:solar_idx_end, :]\n\n    itp = LinearInterpolation(solar_subset[:, 1], \n                              solar_subset[:, 2])\n\n    return itp.(ν_grid)\nend\n\n\"\"\"\n    $(FUNCTIONNAME)(file_name::String)\n\nGet the solar transmission from the specified file\n\"\"\"\nsolar_transmission_from_file(file_name::String) = readdlm(file_name)\n\n\"\"\"\n    $(FUNCTIONNAME)(file_name::String, ν_grid::Union{AbstractRange{<:Real}, AbstractArray})\n\nGet the solar transmission from the specified file, and interpolate to wavenumber grid\n\"\"\"\nfunction solar_transmission_from_file(file_name::String, \n                                      ν_grid::Union{AbstractRange{<:Real}, AbstractArray})\n\n    solar = solar_transmission_from_file(file_name)\n    return itp_solar_to_ν_grid(solar, ν_grid)\nend\n\n\"\"\"\n    $(FUNCTIONNAME)(ν_grid::Union{AbstractRange{<:Real}, AbstractArray} = 600.0:0.01:26316.0)\n\nGet the default solar transmission and interpolate to wavenumber grid (entire grid if not specified)\n\"\"\"\nfunction default_solar_transmission(ν_grid::Union{AbstractRange{<:Real}, AbstractArray} = 600.0:0.01:26316.0)\n    \n    @info \"Using line-list from:\\nToon, G. C., Solar line list for GGG2014, TCCON data archive, hosted by the Carbon Dioxide Information Analysis Center, Oak Ridge National Laboratory, Oak Ridge, Tennessee, U.S.A., doi:10. 14291/tccon.ggg2014.solar.R0/1221658, 2014.\"\n    @info \"Found at: https://mark4sun.jpl.nasa.gov/toon/solar/solar_spectrum.html\"\n\n    filename = joinpath(dirname(pathof(RadiativeTransfer)), \"SolarModel\", \"solar.out\")\n    !isfile(filename) && download(\"http://web.gps.caltech.edu/~cfranken/hitran_2016/solar_merged_20160127_600_26316_100.out\", filename)\n\n    return hcat(ν_grid, solar_transmission_from_file(filename, ν_grid))\nend\n\n\"\"\"\n    $(FUNCTIONNAME)(ν_grid::Union{AbstractRange{<:Real}, AbstractArray} = 600.0:0.01:26316.0)\n\nGet the default solar spectrum and interpolate to wavenumber grid (entire grid if not specified)\n\"\"\"\nfunction default_solar_spectrum_at_earth(ν_grid::Union{AbstractRange{<:Real}, AbstractArray} = 600.0:0.01:26316.0)\n\n    T = 5777 # K\n    λ_grid = reverse(1e4 ./ ν_grid) # Wavenumber to micron\n    black_body = reverse(SolarModel.watts_to_photons(λ_grid, planck_spectrum_wl(T, λ_grid) * 2.1629e-05 * pi))\n    solar_transmission = default_solar_transmission(ν_grid)[:,2]\n\n    return hcat(ν_grid, black_body .* solar_transmission)\nend\n\nexport planck_spectrum_wn, planck_spectrum_wl, solar_transmission_from_file, default_solar_transmission\n\nend", "meta": {"hexsha": "724d5f68c2c0a974ac8591fd3a1ab0219f2e70a8", "size": 5223, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SolarModel/SolarModel.jl", "max_stars_repo_name": "RemoteSensingTools/vSmartMOM.jl", "max_stars_repo_head_hexsha": "fe5b7d28ca99bef0d1702293749d217e8c839db6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SolarModel/SolarModel.jl", "max_issues_repo_name": "RemoteSensingTools/vSmartMOM.jl", "max_issues_repo_head_hexsha": "fe5b7d28ca99bef0d1702293749d217e8c839db6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-10T21:24:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T21:31:57.000Z", "max_forks_repo_path": "src/SolarModel/SolarModel.jl", "max_forks_repo_name": "RemoteSensingTools/vSmartMOM.jl", "max_forks_repo_head_hexsha": "fe5b7d28ca99bef0d1702293749d217e8c839db6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-11T17:24:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T17:24:22.000Z", "avg_line_length": 32.4409937888, "max_line_length": 267, "alphanum_fraction": 0.6806433084, "num_tokens": 1633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7532918420288669}}
{"text": "abstract type SpectralEstimate{D,T} <: AbstractVector{T} end\n\n@doc raw\"\"\"\n    Periodogram(timeseries, Δ)\n\nCompute the periodogram for the provided timeseries with sampling rate Δ.\n\n# Arguments\n- `timeseries`: A `Vector` if univariate and an `n` by `d` `Matrix` if multivariate, where `n` is the number of observations and `d` is the dimension of the timeseries.\n- `Δ`: A positive real number.\n\nThe periodogram is defined as\n```math\n\\boldsymbol I(ω)&=\\boldsymbol J(ω) \\boldsymbol J(ω)^H \\quad \\text{where} \\quad \\boldsymbol J(ω) = \\sqrt{\\frac{Δ}{2π n}}\\sum_{t=0}^{n-1} \\boldsymbol{P}_{tΔ}e^{-itΔ ω}\n```\n\nNote the periodogram is in terms of angular frequency here, and uses the normalisation ``Δ/2π``.\nThe choice of normalisation is essentially arbitrary; however, this matches our definition for the spectral density function.\n\"\"\"\nstruct Periodogram{D,T,V} <: SpectralEstimate{D,T}\n    Ω::V\n    ordinates::Vector{T}\n    function Periodogram(timeseries::Matrix{T}, Δ::Real) where {T}\n        Δ > 0 || throw(ArgumentError(\"Δ should be a positive.\"))\n        J = fftshift(fft(timeseries, 1),1)\n        n = size(J,1)\n        D = size(J,2)\n        ordinates = [(J[ii, :]*J[ii, :]'.*(Δ / (2π * n))) for ii ∈ 1:size(J,1)]\n        Ω = fftshift(fftfreq(n, 2π/Δ))\n        new{D, eltype(ordinates), typeof(Ω)}(Ω, ordinates)\n    end\n    function Periodogram(timeseries::Vector{T}, Δ::Real) where {T}\n        Δ > 0 || throw(ArgumentError(\"Δ should be a positive.\"))\n        J = fftshift(fft(timeseries, 1),1)\n        n = size(J,1)\n        ordinates = abs.(J.^2).*(Δ / (2π * n))\n        Ω = fftshift(fftfreq(n, 2π/Δ))\n        new{1, eltype(ordinates), typeof(Ω)}(Ω, ordinates)\n    end\n    function Periodogram(Ω, ordinates::Vector{T}) where {T}\n        new{size(ordinates[1],1), T, typeof(Ω)}(Ω, ordinates)\n    end\nend\n\n@doc raw\"\"\"\n    BartlettPeriodogram(timeseries, Δ, segmentlength)\n\nCompute the Bartlett periodogram for the provided timeseries with sampling rate Δ.\n\n# Arguments\n- `timeseries`: A `Vector` if univariate and an `n` by `d` `Matrix` if multivariate, where `n` is the number of observations and `d` is the dimension of the timeseries.\n- `Δ`: A positive real number.\n- `segmentlength`: the length of series used in each segment.\n\nComputes an estimate of the spectral density function using Bartlett's method. Using the same normalisation as `Periodogram`.\n\n# External links\n\n* [Bartlett's method on Wikipedia](https://en.wikipedia.org/wiki/Bartlett%27s_method)\n\n\"\"\"\nstruct BartlettPeriodogram{D,T,V} <: SpectralEstimate{D,T}\n    Ω::V\n    ordinates::Vector{T}\n    function BartlettPeriodogram(timeseries::Matrix{T}, Δ::Real, segmentlength::Int = Int(100÷Δ)) where {T}\n        nsegments = size(timeseries, 1) ÷ segmentlength\n        P = Periodogram(timeseries[1:segmentlength, :], Δ)\n        \n        for ii = 1:nsegments-1\n            P += Periodogram(timeseries[segmentlength*ii.+(1:segmentlength), :], Δ)\n        end\n        \n        BartlettPeriodogram(P/nsegments)\n    end\n    function BartlettPeriodogram(timeseries::Vector{T}, Δ::Real, segmentlength::Int = Int(100÷Δ)) where {T}\n        nsegments = size(timeseries, 1) ÷ segmentlength\n        P = Periodogram(timeseries[1:segmentlength], Δ)\n        \n        for ii = 1:nsegments-1\n            P += Periodogram(timeseries[segmentlength*ii.+(1:segmentlength)], Δ)\n        end\n        \n        BartlettPeriodogram(P/nsegments)\n    end\n    function BartlettPeriodogram(p::Periodogram{D,T}) where {D,T}\n        new{D, T, typeof(p.Ω)}(p.Ω, p.ordinates)\n    end\n    function BartlettPeriodogram(Ω, ordinates::Vector{T}) where {T}\n        new{size(ordinates[1],1), T, typeof(Ω)}(Ω, ordinates)\n    end\nend\n\nstruct CoherancyEstimate{D,T,V} <: SpectralEstimate{D,T}\n    Ω::V\n    ordinates::Vector{T}\n\n    function CoherancyEstimate(timeseries::Matrix{T}, Δ::Real, segmentlength::Int = Int(100÷Δ)) where {T}\n        S = BartlettPeriodogram(timeseries, Δ, segmentlength)\n        CoherancyEstimate(S)\n    end\n\n    function CoherancyEstimate(S::SpectralEstimate{D,T}) where {D,T}\n        newordinates = [[s[i,j] / sqrt(s[i,i]*s[j,j]) for i ∈ 1:D, j ∈ 1:D] for s ∈ S.ordinates]\n        new{D,eltype(newordinates),typeof(S.Ω)}(S.Ω, newordinates)\n    end\n\n    function CoherancyEstimate(Ω, ordinates::Vector{T}) where {T}\n        new{size(ordinates[1],1), T, typeof(Ω)}(Ω, ordinates)\n    end\nend\n\nndims(::SpectralEstimate{D,T}) where {D,T} = D\nsize(ŝ::SpectralEstimate) = (length(getfreq(ŝ)),)\ngetindex(ŝ::T, inds) where {T<:SpectralEstimate} = getconstructor(T)(getfreq(ŝ)[inds], getordinate(ŝ)[inds])\ngetindex(ŝ::SpectralEstimate, ind::Int) = (getfreq(ŝ)[ind],getordinate(ŝ)[ind])\nlog10(ŝ::T) where {T<:SpectralEstimate} = getconstructor(T)(getfreq(ŝ), log10.(getordinate(ŝ)))\ngetfreq(p::Periodogram) = p.Ω\ngetfreq(b::BartlettPeriodogram) = b.Ω\ngetfreq(c::CoherancyEstimate) = c.Ω\ngetordinate(p::Periodogram) = p.ordinates\ngetordinate(b::BartlettPeriodogram) = b.ordinates\ngetordinate(c::CoherancyEstimate) = c.ordinates\ngetconstructor(::Type{<:Periodogram}) = Periodogram\ngetconstructor(::Type{<:BartlettPeriodogram}) = BartlettPeriodogram\ngetconstructor(::Type{<:CoherancyEstimate}) = CoherancyEstimate\n\n@recipe function f(ŝ::SpectralEstimate)\n    HermitianPlot(getfreq(ŝ), getordinate(ŝ))\nend\n\n@recipe function f(ŝ::SpectralEstimate{1,T}) where {T} # univariate plotting\n    getfreq(ŝ), getordinate(ŝ)\nend\n\nfunction Base.:+(ŝ₁::T, ŝ₂::T) where {T<:SpectralEstimate}\n    getfreq(ŝ₁) == getfreq(ŝ₂) || error(\"Frequencies must be the same to add spectral estimates.\")\n    getconstructor(T)(getfreq(ŝ₁), getordinate(ŝ₁) .+ getordinate(ŝ₂))\nend\n\nfunction Base.:/(ŝ::T, a::Real) where {T<:SpectralEstimate}\n    getconstructor(T)(getfreq(ŝ), getordinate(ŝ)./a)\nend", "meta": {"hexsha": "bc002a583ea1a49f3ef265ca3f5e891324b8d07b", "size": 5727, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nonparametric.jl", "max_stars_repo_name": "JakeGrainger/WhittleLikelihoodInference.jl", "max_stars_repo_head_hexsha": "56595739c968e7156b63c1c26e4269ee6d8acdb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nonparametric.jl", "max_issues_repo_name": "JakeGrainger/WhittleLikelihoodInference.jl", "max_issues_repo_head_hexsha": "56595739c968e7156b63c1c26e4269ee6d8acdb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-12-14T11:17:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:18:32.000Z", "max_forks_repo_path": "src/nonparametric.jl", "max_forks_repo_name": "JakeGrainger/WhittleLikelihoodInference.jl", "max_forks_repo_head_hexsha": "56595739c968e7156b63c1c26e4269ee6d8acdb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3309859155, "max_line_length": 168, "alphanum_fraction": 0.6691112275, "num_tokens": 1837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.7532918356467876}}
{"text": "using Compat\n\nif VERSION.minor == 7\n  @eval using LinearAlgebra, SparseMatrices\nend\n\nProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n\nA = Float64[\n  1/2 1/3 1/4 1/5 1/6;\n  1/3 1/4 1/5 1/6 1/7;\n  1/4 1/5 1/6 1/7 1/8;\n  1/5 1/6 1/7 1/8 1/9;\n  1/6 1/7 1/8 1/9 1/10;\n]\nb = ones(5)\n\n(Al, Au, Ap) = lu(A)\n\n@show y = Al \\ b[Ap]\nprintln()\n\n@show x = Au \\ y\nprintln()\n\n@show As = sparse(A)\nprintln()\n\n@show As\\b\nprintln()\n\n@show F = lufact(As)\nprintln()\n\nif VERSION.minor == 7\n  @show F.L * F.U == F.Rs .* A[F.p, :]\n  println()\n  \n  @show F.L*F.U\n  println()\n\n  @show sparse(F.Rs.* A[F.p, F.q])\n  println()\nelse\n  @show ys = F[:L] \\ (F[:Rs] .* b)\n  println()\n\n  @show x = F[:U] \\ ys\n  println()\n\n  @show F[:L]*F[:U] == (F[:Rs] .* A)[F[:p], F[:q]]\n  println()\n\n  @show F[:L]*F[:U]\n  println()\n\n  @show sparse((F[:Rs] .* A)[F[:p], F[:q]])\n  println()\nend\n\n@show lufact(A)\nprintln()\n\nend", "meta": {"hexsha": "227f7c8abc5309b6a6c8a0e22bdd34c87ab0c268", "size": 871, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/sparse04.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PtFEM.jl-9b64898b-da2a-5774-a656-fd6fb605642c", "max_stars_repo_head_hexsha": "35a9d7c796a92f5d44bd37a2af574fb366fa51ba", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/sparse04.jl", "max_issues_repo_name": "UnofficialJuliaMirror/PtFEM.jl-9b64898b-da2a-5774-a656-fd6fb605642c", "max_issues_repo_head_hexsha": "35a9d7c796a92f5d44bd37a2af574fb366fa51ba", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/sparse04.jl", "max_forks_repo_name": "UnofficialJuliaMirror/PtFEM.jl-9b64898b-da2a-5774-a656-fd6fb605642c", "max_forks_repo_head_hexsha": "35a9d7c796a92f5d44bd37a2af574fb366fa51ba", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.4, "max_line_length": 50, "alphanum_fraction": 0.5281285878, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7532915124574803}}
{"text": "export\n    LinearRegressionModel,\n    fit!,\n    predict\n\nmutable struct LinearRegressionModel\n    df::DataFrame\n    label::Symbol\n    features::Vector{Symbol}\n    argv::Vector{Float64}\nend\n\nfunction LinearRegressionModel(df::DataFrame, label::Symbol, features::Vector{Symbol})\n    return LinearRegressionModel(df, label, features, rand(length(features)+1))\nend\n\nfunction LinearRegressionModel(df::DataFrame, label::Symbol, features::Symbol)\n    return LinearRegressionModel(df, label, [features], rand(2))\nend\n\nfunction g(model::LinearRegressionModel, row_n::Int64)\n    xs = collect(model.df[row_n, model.features])\n    pushfirst!(xs, 1)\n    y = sum(model.argv .* xs)\n\n    return y\nend\n\nfunction loss(model::LinearRegressionModel)\n    n = nrow(model.df)\n    l = 0\n    for i in 1:n\n        l += (g(model, i) - model.df[i, model.label])^2\n    end\n\n    return l/n\nend\n\nfunction fit!(model::LinearRegressionModel; lr=1e-4, atol::Float64=1e-6, show=false)\n    while (l = loss(model)) > atol\n        show && println(\"Loss: $l\")\n        dl_da = 0\n        dl_db = zeros(length(model.features))\n        for i in 1:nrow(model.df)\n            # intersection\n            dl_da += g(model, i) - model.df[i, model.label]\n\n            # sloaps\n            for (j, f) in enumerate(model.features)\n                dl_db[j] += (g(model, i) - model.df[i, model.label]) * model.df[i, f]\n            end\n        end\n\n        # intersection\n        model.argv[1] -= lr * 2 * dl_da\n        # slopes\n        for j in 2:length(model.argv)\n            model.argv[j] -= lr * 2 * dl_db[j-1]\n        end\n    end\nend\n\nfunction predict(model::LinearRegressionModel, xs::Vector{<:Real})\n    pushfirst!(xs, 1)\n    y = sum(model.argv .* xs)\n\n    return y\nend\n\nfunction predict(model::LinearRegressionModel, x::Real)\n    return predict(model, [x])\nend\n", "meta": {"hexsha": "06b0e5bd93e2f897346301fe4dccf59e1e55fa49", "size": 1817, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear_regression.jl", "max_stars_repo_name": "yuehhua/ML101.jl", "max_stars_repo_head_hexsha": "07db01bd78782c26f1e5ad50603e9b0cda88d6b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/linear_regression.jl", "max_issues_repo_name": "yuehhua/ML101.jl", "max_issues_repo_head_hexsha": "07db01bd78782c26f1e5ad50603e9b0cda88d6b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/linear_regression.jl", "max_forks_repo_name": "yuehhua/ML101.jl", "max_forks_repo_head_hexsha": "07db01bd78782c26f1e5ad50603e9b0cda88d6b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8904109589, "max_line_length": 86, "alphanum_fraction": 0.6169510182, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7532915124250277}}
{"text": "include(\"11_two_site_state_preparation.jl\")\n\nprintln(\"\n#######################################################\n# Tutorial 12                                         #\n#                                                     #\n# n-site circuit optimization with MPS                #\n#######################################################\n\")\n\n# Beyond full state, use approximations\nn = 30\ni = [Index(2, \"S=1/2\") for j in 1:n]\n\n# Product state |Z+Z+Z+…Z+⟩\nZp = MPS(i, \"Z+\")\n\n# Product state |Z-Z-Z-…Z-⟩\nZm = MPS(i, \"Z-\")\n\ninner(Zp, Zp)\ninner(Zm, Zp)\n\n# Do some arithmatic with them, like tensors:\n# TODO: fix this when normalize PR is merged!\n#Cat = (Zp + Zm) / √2\n#\n# Performs a truncated MPS addition,\n# returns an MPS approximate up to some tolerance.\nCat = (Zp + Zm) * (1 / √2)\n@show maxlinkdim(Zp)\n@show maxlinkdim(Zm)\n@show maxlinkdim(Cat)\n@show norm(Cat)\n@show inner(Cat, Zp)\n@show inner(Cat, Zm)\n\n# Apply operators:\nj = n ÷ 2\nXⱼ = op(\"X\", i[j])\nXⱼZp = apply(Xⱼ, Zp)\n\nXⱼZp = MPS(i, [k == j ? \"Z-\" : \"Z+\" for k in 1:n])\n@show inner(XⱼZp, apply(Xⱼ, Zp))\n\nfunction ising(n; h)\n  # Symbolic representation\n  # of the Hamiltonian (\"operator sum\")\n  H = OpSum()\n  for j in 1:(n - 1)\n    H -= \"Z\", j, \"Z\", j + 1\n  end\n  for j in 1:n\n    H += h, \"X\", j\n  end\n  return H\nend\n\nh = 0.5\nH = MPO(ising(n; h=h), i)\n\n# Performs a truncated MPO*MPS contraction,\n# returns an MPS approximate up to some tolerance.\nHZp = H * Zp\n@show inner(Zp', HZp)\n@show inner(Zp', H, Zp)\n\n# Gradient energy minimization\n# Already written above! New Hamiltonian.\nfunction E(ψ)\n  ψHψ = inner(ψ', H, ψ)\n  ψψ = inner(ψ, ψ)\n  return ψHψ / ψψ\nend\n\nfunction minimize(f, ∂f, x; nsteps, γ, kwargs...)\n  for n in 1:nsteps\n    println(\"n = \", n, \", f_x = \", f(x))\n    x = -(x, γ * ∂f(x); kwargs...)\n  end\n  return x\nend\n\nψ⁰ = MPS(i, \"Z+\")\n∂E(x) = gradient(E, x)[1]\nψ = minimize(E, ∂E, ψ⁰; nsteps=50, γ=0.1, maxdim=10, cutoff=1e-5)\n\n# TODO: change to:\n# ψ /= norm(ψ)\nψ *= inv(norm(ψ))\n\nEᵈᵐʳᵍ, ψᵈᵐʳᵍ = dmrg(H, ψ⁰; nsweeps=10, maxdim=10, cutoff=1e-5)\n\n@show maxlinkdim(ψ⁰)\n@show maxlinkdim(ψ)\n@show maxlinkdim(ψᵈᵐʳᵍ)\n@show E(ψ⁰), norm(∂E(ψ⁰))\n@show E(ψ), norm(∂E(ψ))\n@show E(ψᵈᵐʳᵍ), norm(∂E(ψᵈᵐʳᵍ))\n\n#\n# Circuit optimization\n#\n\n# Form the circuit from parameters\nRy_layer(θ, i) = [op(\"Ry\", i[j]; θ=θ[j]) for j in 1:n]\nCX_layer(i) = [op(\"CX\", i[j], i[j+1]) for j in 1:2:(n-1)]\n\nfunction U(θ, i; nlayers)\n  n = length(i)\n  Uᶿ = Ry_layer(θ[1:n], i)\n  for l in 1:(nlayers - 1)\n    Uᶿ = [Uᶿ; CX_layer(i)]\n    Uᶿ = [Uᶿ; Ry_layer(θ[(1:n) .+ l * n], i)]\n  end\n  return Uᶿ\nend\n\nnlayers = 6\nmaxdim = 10\ncutoff = 1e-5\n\n# Find the circuit `U(θ)` that minimizes:\n# E(θ) = ⟨0|U(θ)† H U(θ)|0⟩ = ⟨θ|H|θ⟩\nfunction E(θ)\n  # Apply the circuit:\n  # |θ⟩ = U(θ)|0⟩\n  ψᶿ = apply(U(θ, i; nlayers=nlayers), ψ⁰; maxdim=maxdim, cutoff=cutoff)\n\n  # Compute the expecation value: ⟨θ|H|θ⟩\n  # No need to normalize!\n  return inner(ψᶿ', H, ψᶿ)\nend\n\nprintln()\nprintln(\"Circuit optimization\")\nθ⁰ = zeros(nlayers * n)\n∂E(ψ) = gradient(E, ψ)[1]\nθ = minimize(E, ∂E, θ⁰; nsteps=20, γ=0.1)\n\nψᶿ = apply(U(θ, i; nlayers=nlayers), ψ⁰; maxdim=maxdim, cutoff=cutoff)\n\n@show maxlinkdim(ψ⁰)\n@show maxlinkdim(ψᶿ)\n@show E(θ⁰), norm(∂E(θ⁰))\n@show E(θ), norm(∂E(θ))\n\n# TODO: Finish this implementation\n# Example of preparing the ground state\n# Find `U(θ)` that minimizes\n#\n# F(θ) = -|⟨ψ|U(θ)|0⟩|²\nfunction F(θ)\n  # Apply the circuit:\n  # |θ⟩ = U(θ)|0⟩\n  ψᶿ = apply(U(θ, i; nlayers=nlayers), ψ⁰; maxdim=maxdim, cutoff=cutoff)\n\n  # -|⟨ψ|θ⟩|²\n  return -abs(inner(ψ, ψᶿ))^2\nend\n\nprintln()\nprintln(\"State preparation\")\nθ⁰ = zeros(nlayers * n)\n∂F(ψ) = gradient(F, ψ)[1]\nθ = minimize(F, ∂F, θ⁰; nsteps=20, γ=0.1)\n\nψᶿ = apply(U(θ, i; nlayers=nlayers), ψ⁰; maxdim=maxdim, cutoff=cutoff)\n\n@show maxlinkdim(ψ⁰)\n@show maxlinkdim(ψᶿ)\n@show F(θ⁰), norm(∂F(θ⁰))\n@show F(θ), norm(∂F(θ))\n", "meta": {"hexsha": "3123c89b3c264b9e59e32953c87b407029dce058", "size": 3778, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tutorials/12_n_site.jl", "max_stars_repo_name": "mtfishman/ITensorTutorials.jl", "max_stars_repo_head_hexsha": "dcbc1988299e6a7f3b612faeb31563da38ece3be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-11T10:42:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T01:03:58.000Z", "max_issues_repo_path": "tutorials/12_n_site.jl", "max_issues_repo_name": "mtfishman/ITensorTutorials.jl", "max_issues_repo_head_hexsha": "dcbc1988299e6a7f3b612faeb31563da38ece3be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/12_n_site.jl", "max_forks_repo_name": "mtfishman/ITensorTutorials.jl", "max_forks_repo_head_hexsha": "dcbc1988299e6a7f3b612faeb31563da38ece3be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7126436782, "max_line_length": 72, "alphanum_fraction": 0.5714663843, "num_tokens": 1637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7532830029124852}}
{"text": "## R code 5.3\nm5.1 <- quap(\n    alist(\n        D ~ dnorm( mu , sigma ) ,\n        mu <- a + bA * A ,\n        a ~ dnorm( 0 , 0.2 ) ,\n        bA ~ dnorm( 0 , 0.5 ) ,\n        sigma ~ dexp( 1 )\n    ) , data = d )\n\n## R code 5.6\nd$M <- scale( d$Marriage )\nm5.2 <- quap(\n    alist(\n        D ~ dnorm( mu , sigma ) ,\n        mu <- a + bM * M ,\n        a ~ dnorm( 0 , 0.2 ) ,\n        bM ~ dnorm( 0 , 0.5 ) ,\n        sigma ~ dexp( 1 )\n    ) , data = d )\n\n## R code 5.10\nm5.3 <- quap(\n    alist(\n        D ~ dnorm( mu , sigma ) ,\n        mu <- a + bM*M + bA*A ,\n        a ~ dnorm( 0 , 0.2 ) ,\n        bM ~ dnorm( 0 , 0.5 ) ,\n        bA ~ dnorm( 0 , 0.5 ) ,\n        sigma ~ dexp( 1 )\n    ) , data = d )\n\n## R code 5.13\nm5.4 <- quap(\n    alist(\n        M ~ dnorm( mu , sigma ) ,\n        mu <- a + bAM * A ,\n        a ~ dnorm( 0 , 0.2 ) ,\n        bAM ~ dnorm( 0 , 0.5 ) ,\n        sigma ~ dexp( 1 )\n    ) , data = d )\n\n## R code 5.19\ndata(WaffleDivorce)\nd <- list()\nd$A <- standardize( WaffleDivorce$MedianAgeMarriage )\nd$D <- standardize( WaffleDivorce$Divorce )\nd$M <- standardize( WaffleDivorce$Marriage )\n\nm5.3_A <- quap(\n    alist(\n      ## A -> D <- M\n        D ~ dnorm( mu , sigma ) ,\n        mu <- a + bM*M + bA*A ,\n        a ~ dnorm( 0 , 0.2 ) ,\n        bM ~ dnorm( 0 , 0.5 ) ,\n        bA ~ dnorm( 0 , 0.5 ) ,\n        sigma ~ dexp( 1 ),\n      ## A -> M\n        M ~ dnorm( mu_M , sigma_M ),\n        mu_M <- aM + bAM*A,\n        aM ~ dnorm( 0 , 0.2 ),\n        bAM ~ dnorm( 0 , 0.5 ),\n        sigma_M ~ dexp( 1 )\n    ) , data = d )\n\n## R code 5.29\nm5.5_draft <- quap(\n    alist(\n        K ~ dnorm( mu , sigma ) ,\n        mu <- a + bN*N ,\n        a ~ dnorm( 0 , 1 ) ,\n        bN ~ dnorm( 0 , 1 ) ,\n        sigma ~ dexp( 1 )\n    ) , data=d )\n\n## R code 5.32\nm5.5_draft <- quap(\n    alist(\n        K ~ dnorm( mu , sigma ) ,\n        mu <- a + bN*N ,\n        a ~ dnorm( 0 , 1 ) ,\n        bN ~ dnorm( 0 , 1 ) ,\n        sigma ~ dexp( 1 )\n    ) , data=dcc )\n\n## R code 5.34\nm5.5 <- quap(\n    alist(\n        K ~ dnorm( mu , sigma ) ,\n        mu <- a + bN*N ,\n        a ~ dnorm( 0 , 0.2 ) ,\n        bN ~ dnorm( 0 , 0.5 ) ,\n        sigma ~ dexp( 1 )\n    ) , data=dcc )\n\n## R code 5.37\nm5.6 <- quap(\n    alist(\n        K ~ dnorm( mu , sigma ) ,\n        mu <- a + bM*M ,\n        a ~ dnorm( 0 , 0.2 ) ,\n        bM ~ dnorm( 0 , 0.5 ) ,\n        sigma ~ dexp( 1 )\n    ) , data=dcc )\n\n## R code 5.38\nm5.7 <- quap(\n    alist(\n        K ~ dnorm( mu , sigma ) ,\n        mu <- a + bN*N + bM*M ,\n        a ~ dnorm( 0 , 0.2 ) ,\n        bN ~ dnorm( 0 , 0.5 ) ,\n        bM ~ dnorm( 0 , 0.5 ) ,\n        sigma ~ dexp( 1 )\n    ) , data=dcc )\n\n\n## R code 5.41\n# M -> K <- N\n# M -> N\nn <- 100\nM <- rnorm( n )\nN <- rnorm( n , M )\nK <- rnorm( n , N - M )\nd_sim <- data.frame(K=K,N=N,M=M)\n\nm5.7.A <- quap(\n    alist(\n        K ~ dnorm( mu , sigma ) ,\n        mu <- a + bN*N + bM*M ,\n        a ~ dnorm( 0 , 0.2 ) ,\n        bN ~ dnorm( 0 , 0.5 ) ,\n        bM ~ dnorm( 0 , 0.5 ) ,\n        sigma ~ dexp( 1 )\n    ) , data=d_sim )\n\n## R code 5.47\nm5.8 <- quap(\n    alist(\n        height ~ dnorm( mu , sigma ) ,\n        mu <- a[sex] ,\n        a[sex] ~ dnorm( 178 , 20 ) ,\n        sigma ~ dunif( 0 , 50 )\n    ) , data=d )\nprecis( m5.8 , depth=2 )\n\n## R code 5.51\nd$K <- scale( d$kcal.per.g )\nm5.9 <- quap(\n    alist(\n        K ~ dnorm( mu , sigma ),\n        mu <- a[clade_id],\n        a[clade_id] ~ dnorm( 0 , 0.5 ),\n        sigma ~ dexp( 1 )\n    ) , data=d )\n\n## R code 5.53\nm5.10 <- quap(\n    alist(\n        K ~ dnorm( mu , sigma ),\n        mu <- a[clade_id] + h[house],\n        a[clade_id] ~ dnorm( 0 , 0.5 ),\n        h[house] ~ dnorm( 0 , 0.5 ),\n        sigma ~ dexp( 1 )\n    ) , data=d )\n\n", "meta": {"hexsha": "45572d218933f048b8b2315177c5c687d324aa7e", "size": 3642, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/05/models.jl", "max_stars_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_stars_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2020-10-01T23:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T11:48:45.000Z", "max_issues_repo_path": "models/05/models.jl", "max_issues_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_issues_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-11-24T21:59:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T12:34:49.000Z", "max_forks_repo_path": "models/05/models.jl", "max_forks_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_forks_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-11-30T18:25:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T06:59:27.000Z", "avg_line_length": 21.6785714286, "max_line_length": 53, "alphanum_fraction": 0.3909939594, "num_tokens": 1488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7532828350181812}}
{"text": "# This file investigates integration error with respect to free variables in hidden 1D integration \n\nusing FractalTools \nusing Makie \n\n# Construct interpolation data \nf(x) = sin(2π * x)  + 1\ng(x) = cos(2π * x)  + 1\ndx   = 0.1                              \nxi   = 0.                               \nxf   = 1.                               \nx    = collect(xi : dx : xf)            \ny    = f.(x)                            \nz    = g.(x)\npts  = collect.(zip(x, y, z))     \n\n# Compute errors \nfvals = (cos(2π * xi) - cos(2π * xf)) / (2π) + (xf - xi)\nfreevars = 0.001 : 0.01 : 0.999\nmse = map(freevars) do freevar \n    ival = integrate(pts, HInterp1D(fill(freevar, 2, 2)))[1]\n    abs(fval - ival)\nend \n\n# Plot mse \nfig = Figure() \nax = fig[1, 1] = Axis(fig, xlabel=\"Free Variable\", ylabel=\"MSE\", title=\"1D Hidden Interpolation MSE\") \nstem!(ax, freevars, mse, color=:black)\nsave(joinpath(@__DIR__, \"hinteg1d_error.png\"), fig)\ndisplay(fig)\n\n", "meta": {"hexsha": "5f9054b46e4dba76d0020ff833e0e824d0e5b8a2", "size": 932, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiment_2/integration_error_vs_freevars/hinteg1d/hinteg1d.jl", "max_stars_repo_name": "zekeriyasari/FractalTools.jl", "max_stars_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-08T12:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T12:50:16.000Z", "max_issues_repo_path": "experiment_1/integration_error_vs_freevars/hinteg1d/hinteg1d.jl", "max_issues_repo_name": "zekeriyasari/FractalTools.jl", "max_issues_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-09-05T18:22:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T10:09:46.000Z", "max_forks_repo_path": "experiment_2/integration_error_vs_freevars/hinteg1d/hinteg1d.jl", "max_forks_repo_name": "zekeriyasari/FractalTools.jl", "max_forks_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.125, "max_line_length": 102, "alphanum_fraction": 0.5311158798, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7532828345968811}}
{"text": "# ------------------------------------------------\n# basic math operators like dot mul,dot add,etc ..\n# ------------------------------------------------\nimport Base.+\nimport Base.-\nimport Base.*\nimport Base.^\n\nexport dotAdd\nexport dotMul\nexport matAddVec\nexport matMulVec\n\nfunction Base.:+(x::Variable{T}, constant) where T\n    # a matrix add a constant element by element\n    C = eltype(ᵛ(x))(constant)\n    y = Variable{T}(ᵛ(x) .+ C, x.backprop)\n    if x.backprop\n        function matAddScalarBackward()\n            if need2computeδ!(x)\n                δ(x) .+= δ(y)\n            end\n            ifNotKeepδThenFreeδ!(y);\n        end\n        push!(graph.backward, matAddScalarBackward)\n    end\n    return y\nend\n\n\nfunction Base.:+(constant, var::Variable{T}) where T\n    return var + constant;\nend\n\n\nfunction Base.:-(x::Variable{T}, constant) where T\n    # a matrix minus a constant element by element\n    C = eltype(ᵛ(x))(constant)\n    y = Variable{T}(ᵛ(x) .- C, x.backprop)\n    if x.backprop\n        function matMinusScalarBackward()\n            if need2computeδ!(x)\n                δ(x) .+= δ(y)\n            end\n            ifNotKeepδThenFreeδ!(y);\n        end\n        push!(graph.backward, matMinusScalarBackward)\n    end\n    return y\nend\n\n\nfunction Base.:-(constant, x::Variable{T}) where T\n    # a matrix minus a constant element by element\n    C = eltype(ᵛ(x))(constant)\n    y = Variable{T}(C .- ᵛ(x), x.backprop)\n    if x.backprop\n        function scalarMinusMatBackward()\n            if need2computeδ!(x)\n                δ(x) .-= δ(y)\n            end\n            ifNotKeepδThenFreeδ!(y);\n        end\n        push!(graph.backward, scalarMinusMatBackward)\n    end\n    return y\nend\n\n\nfunction Base.:*(x::Variable{T}, constant) where T\n    # a matrix multiplies a constant element by element\n    C = eltype(ᵛ(x))(constant)\n    y = Variable{T}(ᵛ(x) .* C, x.backprop)\n    if x.backprop\n        function matMulScalarBackward()\n            if need2computeδ!(x)\n                δ(x) .+= δ(y) .* constant\n            end\n            ifNotKeepδThenFreeδ!(y);\n        end\n        push!(graph.backward, matMulScalarBackward)\n    end\n    return y\nend\n\n\nfunction Base.:*(constant, var::Variable{T}) where T\n    return var * constant\nend\n\n\nfunction Base.:^(x::Variable{T}, n::Int) where T\n    # 矩阵、列向量与常数按元素做幂指数运算\n    n = eltype(ᵛ(x))(n)\n    y = Variable{T}(ᵛ(x) .^ n, x.backprop)\n    if x.backprop\n        function powerBackward()\n            if need2computeδ!(x)\n                δ(x) .+= n .* ᵛ(y) ./ ᵛ(x) .* δ(y);\n            end\n            ifNotKeepδThenFreeδ!(y);\n        end\n        push!(graph.backward, powerBackward)\n    end\n    return y\nend\n\n\nfunction Base.:+(x::Variable{T1}, y::Variable{T2}) where {T1,T2}\n    # a matrix add a matrix element by element: z = x + y\n   @assert T1 <: T2 || T1 >: T2\n   T = T1 <: T2 ? T1 : T2\n   @assert (x.shape == y.shape) \"2 inputs shall be the same size\"\n   backprop = (x.backprop || y.backprop)\n   z = Variable{T}(ᵛ(x) + ᵛ(y), backprop)\n   if backprop\n       function add2varBackward()\n           if need2computeδ!(x) δ(x) .+= δ(z) end\n           if need2computeδ!(y) δ(y) .+= δ(z) end\n           ifNotKeepδThenFreeδ!(z);\n       end\n       push!(graph.backward, add2varBackward)\n   end\n   return z\nend\n\n\nfunction Base.:-(x::Variable{T1}, y::Variable{T2}) where {T1,T2}\n    # a matrix minus a matrix element by element : z = x - y\n    @assert T1 <: T2 || T1 >: T2\n    T = T1 <: T2 ? T1 : T2\n    @assert (x.shape == y.shape) \"2 inputs shall be the same size\"\n    backprop = (x.backprop || y.backprop)\n    z = Variable{T}(ᵛ(x) - ᵛ(y), backprop)\n    if backprop\n        function minus2varBackward()\n            if need2computeδ!(x) δ(x) .+= δ(z) end\n            if need2computeδ!(y) δ(y) .-= δ(z) end\n            ifNotKeepδThenFreeδ!(z);\n        end\n        push!(graph.backward, minus2varBackward)\n    end\n    return z\nend\n\n\n\"\"\"\n    dotAdd(var1::Variable{T1}, var2::Variable{T2}) where {T1,T2}\na tensor add a tensor element by element\n\"\"\"\nfunction dotAdd(x::Variable{T1}, y::Variable{T2}) where {T1,T2}\n    # a tensor add a tensor element by element: z = x .+ y\n    @assert T1 <: T2 || T1 >: T2\n    T = T1 <: T2 ? T1 : T2\n    @assert (x.shape == y.shape) \"2 inputs shall be the same size\"\n    backprop = (x.backprop || y.backprop)\n    z = Variable{T}(ᵛ(x) .+ ᵛ(y), backprop)\n    if backprop\n        function dotAddBackward()\n            if need2computeδ!(x) δ(x) .+= δ(z) end\n            if need2computeδ!(y) δ(y) .+= δ(z) end\n            ifNotKeepδThenFreeδ!(z);\n        end\n        push!(graph.backward, dotAddBackward)\n    end\n    return z\nend\n\n\n\"\"\"\n    dotMul(var1::Variable{T1}, var2::Variable{T2}) where {T1,T2}\na tensor multiplies a tensor element by element\n\"\"\"\nfunction dotMul(x::Variable{T1}, y::Variable{T2}) where {T1,T2}\n    # a tensor multiplies a tensor element by element: z = x .* y\n    @assert T1 <: T2 || T1 >: T2\n    T = T1 <: T2 ? T1 : T2\n    @assert (x.shape == y.shape) \"2 inputs shall be the same size\"\n    backprop = (x.backprop || y.backprop)\n    z = Variable{T}(ᵛ(x) .* ᵛ(y), backprop)\n    if backprop\n        function dotMulBackward()\n            if need2computeδ!(x) δ(x) .+= δ(z) .* ᵛ(y) end\n            if need2computeδ!(y) δ(y) .+= δ(z) .* ᵛ(x) end\n            ifNotKeepδThenFreeδ!(z);\n        end\n        push!(graph.backward, dotMulBackward)\n    end\n    return z\nend\n\n\nfunction Base.:*(W::Variable{T1}, X::Variable{T2}) where {T1,T2}\n    # matrix W multiplies matrix X\n    # 矩阵相乘 Y[i,j] = sum(W[i,k]*X[k,j],k=...)\n    # W -- 权重矩阵\n    # X -- n个输入列向量组成的矩阵\n    # Y -- n个输出列向量组成的矩阵\n    @assert T1 <: T2 || T1 >: T2\n    T = T1 <: T2 ? T1 : T2\n    backprop = (W.backprop || X.backprop)\n    Y = Variable{T}(ᵛ(W) * ᵛ(X), backprop)\n    if backprop\n        function matMulBackward()\n            if need2computeδ!(W) δ(W) .+= δ(Y)  * ᵛ(X)' end\n            if need2computeδ!(X) δ(X) .+= ᵛ(W)' * δ(Y)  end\n            ifNotKeepδThenFreeδ!(Y);\n        end\n        push!(graph.backward, matMulBackward)\n    end\n    return Y\nend\n\n\n\"\"\"\n    matAddVec(var1::Variable{T1}, var2::Variable{T2}) where {T1,T2}\na matrix tensor `var1` adds a vector tensor `var2`\n\"\"\"\nfunction matAddVec(M::Variable{T1}, V::Variable{T2}) where {T1,T2}\n    # M -- 充当和节点，非学习的参数\n    # V -- 偏置列向量，要学习的参数\n    # Z = M .+ V\n    @assert T1 <: T2 || T1 >: T2\n    T = T1 <: T2 ? T1 : T2\n    @assert (M.shape[1]==V.shape[1] && V.shape[2]==1)\n    backprop = (M.backprop || V.backprop)\n    Z = Variable{T}(ᵛ(M) .+ ᵛ(V), backprop)\n    if backprop\n        function matAddVecBackward()\n            if need2computeδ!(M)\n                δ(M) .+= δ(Z)\n            end\n            if need2computeδ!(V)\n                δ(V) .+= sum(δ(Z), dims=2)\n            end\n            ifNotKeepδThenFreeδ!(Z);\n        end\n        push!(graph.backward, matAddVecBackward)\n    end\n    return Z\nend\n\n\n\"\"\"\n    matAddVec(var1::Variable{T1}, var2::Variable{T2}) where {T1,T2}\na matrix tensor `var1` multiplies a vector tensor `var2`\n\"\"\"\nfunction matMulVec(M::Variable{T1}, V::Variable{T2}) where {T1,T2}\n    # M -- 一般充当激活节点，非网络需要学习的参数\n    # V -- 列向量，循环权重，是网络需要学习的参数\n    # Z = M .* V\n    @assert T1 <: T2 || T1 >: T2\n    T = T1 <: T2 ? T1 : T2\n    @assert (M.shape[1]==V.shape[1] && V.shape[2]==1)\n    backprop = (M.backprop || V.backprop)\n    Z = Variable{T}(ᵛ(M) .* ᵛ(V), backprop)\n    if backprop\n        function matMulVecBackward()\n            if need2computeδ!(M) δ(M) .+=     δ(Z) .* ᵛ(V)          end\n            if need2computeδ!(V) δ(V) .+= sum(δ(Z) .* ᵛ(M), dims=2) end\n            ifNotKeepδThenFreeδ!(Z);\n        end\n        push!(graph.backward, matMulVecBackward)\n    end\n    return Z\nend\n", "meta": {"hexsha": "a4af7349371060941f09da251358690cc6ddbf83", "size": 7591, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basic/3-math.jl", "max_stars_repo_name": "sonosole/Delta", "max_stars_repo_head_hexsha": "705434e773c40d7906e215fa080a5afc973d4b43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-01T11:00:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-01T11:00:36.000Z", "max_issues_repo_path": "src/basic/3-math.jl", "max_issues_repo_name": "sonosole/Delta", "max_issues_repo_head_hexsha": "705434e773c40d7906e215fa080a5afc973d4b43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basic/3-math.jl", "max_forks_repo_name": "sonosole/Delta", "max_forks_repo_head_hexsha": "705434e773c40d7906e215fa080a5afc973d4b43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4307116105, "max_line_length": 71, "alphanum_fraction": 0.5518377025, "num_tokens": 2560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188345, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.753282831451746}}
{"text": "using ADCME \nusing PyPlot\n\nfunction residual_and_jacobian(θ, u)\n    X = ae(u, config, θ) + 1.0     # (1)\n    Xp = tf.gradients(X, u)[1]\n    Xpp = tf.gradients(Xp, u)[1]\n    up = [u[2:end];constant(zeros(1))]\n    un = [constant(zeros(1)); u[1:end-1]]\n    R = Xp .* ((up-un)/2h)^2 + X .* (up+un-2u)/h^2 - φ\n    dRdu = Xpp .* ((up-un)/2h)^2 + Xp.*(up+un-2u)/h^2 - 2/h^2*X \n    dRdun = -Xp[2:end]/h .* (up-un)[2:end]/2h + X[2:end]/h^2\n    dRdup = Xp[1:end-1]/h .* (up-un)[1:end-1]/2h + X[1:end-1]/h^2\n    J = spdiag(n-1, \n        -1=>dRdun,\n        0=>dRdu,\n        1=>dRdup)     # (2)\n    return R, J\nend\n\n\nconfig = [20,20,20,1]\nn = 100\nh = 1/n\nx = collect(LinRange(0, 1.0, n+1))\n\nφ = @. (1 - 2*x)*(-100*x^2*(2*x - 2) - 200*x*(1 - x)^2)/(100*x^2*(1 - x)^2 + 1)^2 - 2 - 2/(100*x^2*(1 - x)^2 + 1)\nφ = φ[2:end-1]\nθ = Variable(ae_init([1,config...]))\nu0 = constant(zeros(n-1)) \nfunction L(u)    # (3)\n  u_obs = (@. x * (1-x))[2:end-1]\n  loss = mean((u - u_obs)^2) \nend\nloss, solution, grad = NonlinearConstrainedProblem(residual_and_jacobian, L, θ, u0)\nX_pred = ae(collect(LinRange(0.0,0.25,100)), config, θ) + 1.0\n\nsess = Session(); init(sess)\nBFGS!(sess, loss, grad, θ)\nx_pred, sol = run(sess, [X_pred, solution])\n\nfigure(figsize=(10,4))\nsubplot(121)\ns = LinRange(0.0,0.25,100)\nx_exact = @. 1/(1+100*s^2) + 1\nplot(s, x_exact, \"-\", linewidth=3, label=\"Exact\")\nplot(s, x_pred, \"o\", markersize=2, label=\"Estimated\")\nlegend()\nxlabel(\"u\")\nylabel(\"X(u)\")\n\nsubplot(122)\ns = LinRange(0.0,1.0,101)[2:end-1]\nplot(s, (@. s * (1-s)), \"-\", linewidth=3, label=\"Exact\")\nplot(s, sol, \"o\", markersize=2, label=\"Estimated\")\nlegend()\nxlabel(\"x\")\nylabel(\"u\")\nsavefig(\"nn.png\")", "meta": {"hexsha": "db1a19724d845eaec178d174d85c1a8f231e1214", "size": 1651, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/while_loop/functional.jl", "max_stars_repo_name": "ziyiyin97/ADCME.jl", "max_stars_repo_head_hexsha": "1c9b2c1ae63059d79a5a6a7b86eee64796868755", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 202, "max_stars_repo_stars_event_min_datetime": "2019-06-12T18:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T16:56:46.000Z", "max_issues_repo_path": "examples/while_loop/functional.jl", "max_issues_repo_name": "banren456/ADCME.jl", "max_issues_repo_head_hexsha": "2ed7a0801b6ed90f2236c3cde7a1dca825cbe897", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2019-08-19T19:37:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T11:17:50.000Z", "max_forks_repo_path": "examples/while_loop/functional.jl", "max_forks_repo_name": "banren456/ADCME.jl", "max_forks_repo_head_hexsha": "2ed7a0801b6ed90f2236c3cde7a1dca825cbe897", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 56, "max_forks_repo_forks_event_min_datetime": "2019-07-30T05:50:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:41:07.000Z", "avg_line_length": 27.9830508475, "max_line_length": 113, "alphanum_fraction": 0.5493640218, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7532828306091456}}
{"text": "## Packages\nusing NLsolve\nusing Parameters\nusing BenchmarkTools\nusing ForwardDiff\n\n## Files\ninclude(\"NewtonRoot.jl\")\ninclude(\"Riccati.jl\")\n\n######################## Preliminary ###################################\n# Construct gradient and hessian at SS\nfunction getM(md,kss,hss)\n    @unpack θ,ψ,δ,γ_n,γ_z,ρ,β_hat = md\n\n    f(x::Vector) = log((x[1]^θ)*((exp(x[2])*x[5])^(1-θ))-(1+γ_n)*(1+γ_z)*x[4]+(1-δ)*x[1])+ψ*log(1-x[5]);\n    z_bar = [kss,0.0,1.0,kss,hss];\n    grad = ForwardDiff.gradient(f,z_bar);\n    hess = ForwardDiff.hessian(f,z_bar);\n\n    # Apply Kydland and Prescott's method\n    e = [0;0;1;0;0];\n\n    M = e.*(f(z_bar)-grad'*z_bar.+(0.5.*z_bar'*hess*z_bar))*e' +\n        0.5*(grad*e'-e*z_bar'*hess-hess*z_bar*e'+e*grad') +\n        0.5*hess;\n\n    # Translating M into the matrices we need:\n    Q = M[1:3,1:3];\n    W = M[1:3,4:5];\n    R = M[4:5,4:5];\n\n    A = [0 0 0; 0 ρ 0; 0 0 1];\n    B = [1 0; 0 0; 0 0];\n    C = [0; 1; 0];\n\n    #Mapping to the problem without discounting (1 VARIABLES ARE ~ IN LECTURE NOTES)\n    A_tld = sqrt(β_hat)*(A-B*(R\\W'));\n    B_tld = sqrt(β_hat)*B;\n    Q_tld = Q-W*(R\\W');\n\n    return A_tld,B_tld,Q_tld,R,W\nend\n\n\n################### LQ Approximation ##################################\nfunction LQ(A_tld,B_tld,R,Q_tld;tol=1.0e-10)\n\n    Pn, Fn = Riccati(A_tld, B_tld, R, Q_tld, tol);\n    F = Fn + R\\W';\n    P = Pn;\n\n    return P,F\nend\n\n################### Vaughan ##################################\nfunction Vaughan(A_tld,B_tld,Q_tld,R,W)\n\n    L = size(A_tld)[1]\n    H = [inv(A_tld)  (A_tld\\B_tld)*(R\\B_tld');\n        Q_tld/A_tld Q_tld*(A_tld\\B_tld)*(R\\B_tld')+A_tld'];\n\n    V = eigen(H).vectors\n    #Note that Julia puts the eigenvalues out of the unit circle in the bottom of the matrix,\n    #while in the lecture notes they are at the top\n    P = V[L+1:end,L+1:end]/(V[1:L,L+1:end]);\n    F1 = (R+B_tld'*P*B_tld)\\B_tld'*P*A_tld;\n    F = F1+R\\W';\n\n    return P,F\nend\n\n", "meta": {"hexsha": "b6527f4a6b4dac4d0e888120e4838e400a1e3b18", "size": 1902, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Ellen/HW1/LQ_Vaughan.jl", "max_stars_repo_name": "wongr003/ECON8185", "max_stars_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ellen/HW1/LQ_Vaughan.jl", "max_issues_repo_name": "wongr003/ECON8185", "max_issues_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ellen/HW1/LQ_Vaughan.jl", "max_forks_repo_name": "wongr003/ECON8185", "max_forks_repo_head_hexsha": "4f176c16f974f50edb8b787083965d5392a1c8aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0547945205, "max_line_length": 104, "alphanum_fraction": 0.5352260778, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7532828301225009}}
{"text": "\"\"\"\n    PGeneralizedGaussian(α, μ, p)\n\nThe *p-Generalized Gaussian distribution*, more commonly known as the exponential\npower or the generalized normal distribution, with scale `α`, location `μ`, and\nshape `p` has the probability density function\n\n```math\nf(x, \\\\mu, \\\\alpha, p) = \\\\frac{p}{2\\\\alpha\\\\Gamma(1/p)} e^{-(\\\\frac{|x-\\\\mu|}{\\\\alpha})^p} \\\\quad x \\\\in (-\\\\infty, +\\\\infty) , \\\\alpha > 0, p > 0\n```\n\nThe p-Generalized Gaussian (GGD) is a parametric distribution that incorporates the\nNormal and Laplacian distributions as special cases where `p = 1` and `p = 2`. As `p → ∞`,\nthe distribution approaches the Uniform distribution on `[μ-α, μ+α]`.\n\n```julia\nPGeneralizedGaussian()           # GGD with shape 2, scale 1, location 0, (the Normal distribution)\nPGeneralizedGaussian(α, μ, p)    # GGD with location α, scale μ, and shape p\n\nparams(d)                       # Get the parameters, i.e. (α, μ, p)\nshape(d)                        # Get the shape parameter, p\nscale(d)                        # Get the scale parameter, α\nlocation(d)                     # Get the location parameter, μ\n```\n\nExternal Links\n * [Generalized Gaussian on Wikipedia](http://en.wikipedia.org/wiki/Generalized_normal_distribution)\n * [Reference implementation paper](https://www.researchgate.net/publication/254282790_Simulation_of_the_p-generalized_Gaussian_distribution)\n \"\"\"\nstruct PGeneralizedGaussian{T1<:Real, T2<:Real, T3<:Real} <: ContinuousUnivariateDistribution\n    μ::T1\n    α::T2\n    p::T3\n    PGeneralizedGaussian{T1,T2,T3}(μ::T1,α::T2,p::T3) where {T1<:Real, T2<:Real, T3<:Real} = new{T1,T2,T3}(µ, α, p)\nend\n\nfunction PGeneralizedGaussian(μ::T1,α::T2,p::T3; check_args::Bool=true) where {T1<:Real, T2<:Real, T3<:Real}\n    check_args && @check_args(PGeneralizedGaussian, α > zero(α) && p > zero(p))\n    return PGeneralizedGaussian{T1,T2,T3}(μ,α,p)\nend\n\n\"\"\"\n    PGeneralizedGaussian(p)\n\nBuilds a p-generalized Gaussian with `μ=0.0, α=1.0`\n\"\"\"\nPGeneralizedGaussian(p::Real; check_args::Bool=true) = PGeneralizedGaussian(zero(p), one(p), p; check_args=check_args)\n\n\"\"\"\n    PGeneralizedGaussian()\n\nBuilds a default p-generalized Gaussian with `μ=0.0, α=√2, p=2.0`, corresponding\nto the normal distribution with `μ=0.0, σ=1.0`.\n\"\"\"\nPGeneralizedGaussian() = PGeneralizedGaussian(0.0, √2, 2.0, check_args=false) # approximate scale with unity std deviation and shape 2\n\n#### Conversions\n\nconvert(::Type{PGeneralizedGaussian{T1,T2,T3}}, μ::S1, α::S2, p::S3) where {T1 <: Real, T2 <: Real, T3 <:Real, S1 <: Real, S2 <: Real, S3 <: Real} = PGeneralizedGaussian(T1(μ),T2(α),T3(p))\nfunction convert(::Type{PGeneralizedGaussian{T1,T2,T3}}, d::PGeneralizedGaussian{S1,S2,S3}) where {T1 <: Real, T2 <: Real, T3 <: Real, S1 <: Real, S2 <: Real, S3 <: Real}\n    return PGeneralizedGaussian(T1(d.μ), T2(d.α), T3(d.p), check_args=false)\nend\n\n@distr_support PGeneralizedGaussian -Inf Inf\n\n\n#### Parameters\npartype(::PGeneralizedGaussian{T1,T2,T3}) where {T1,T2,T3} = promote_type(T1,T2,T3)\n\nparams(d::PGeneralizedGaussian) = (d.μ, d.α, d.p)\nlocation(d::PGeneralizedGaussian) = d.μ\nshape(d::PGeneralizedGaussian) = d.p\nscale(d::PGeneralizedGaussian) = d.α\n\n\n#### Statistics\n\nmean(d::PGeneralizedGaussian) = d.μ\nmedian(d::PGeneralizedGaussian) = d.μ\nmode(d::PGeneralizedGaussian) = d.μ\n\nvar(d::PGeneralizedGaussian) = (d.α^2) * (gamma(3.0 * inv(d.p)) / gamma(inv(d.p)))\nstd(d::PGeneralizedGaussian) = (d.α) * sqrt(gamma(3.0 * inv(d.p)) / gamma(inv(d.p)))\n\nskewness(d::PGeneralizedGaussian{T1, T2, T3}) where {T1,T2,T3} = zero(T1)\nkurtosis(d::PGeneralizedGaussian) = gamma(5.0 * inv(d.p)) * gamma(inv(d.p)) / (gamma(3.0 * inv(d.p))^2) - 3.0\nentropy(d::PGeneralizedGaussian) = inv(d.p) - log( d.p / (2.0 * d.α * gamma(inv(d.p))))\n\n\n#### Evaluation\n\nfunction pdf(d::PGeneralizedGaussian, x::Real)\n    (μ, α, p) = params(d)\n    return ( p / ( 2.0 * α * gamma(1 / p) ) ) * exp( -( abs(x - μ) / α )^p )\nend\nlogpdf(d::PGeneralizedGaussian, x::Real) = log(pdf(d, x))\n\n\"\"\"\n    cdf(d, x)\n\nCalculates the CDF of the distribution. To determine the CDF, the incomplete\ngamma function is required. The CDF  of the Gamma distribution provides this,\nwith the necessary 1/Γ(a) normalization.\n\"\"\"\nfunction cdf(d::PGeneralizedGaussian, x::Real)\n    (μ, α, p) = params(d)\n    v = cdf(Gamma(inv(p), 1), (abs(x - μ) / α)^p) * inv(2)\n    return typeof(v)(1/2) + sign(x - μ) * v\nend\n\n#### Sampling\n\n\"\"\"\n    rand(rng, d)\n\nExtract a sample from the p-Generalized Gaussian distribution 'd'. The sampling\nprocedure is implemented from from [1].\n[1]  Gonzalez-Farias, G., Molina, J. A. D., & Rodríguez-Dagnino, R. M. (2009).\nEfficiency of the approximated shape parameter estimator in the generalized\nGaussian distribution. IEEE Transactions on Vehicular Technology, 58(8),\n4214-4223.\n\"\"\"\nfunction rand(rng::AbstractRNG, d::PGeneralizedGaussian)\n\n    # utilizing the sampler from the Gamma distribution.\n    g = Gamma(inv(d.p), 1)\n\n    # random variable with value -1 or 1 with probability (1/2).\n    b = 2.0 * rand(Bernoulli()) -1\n\n    return d.μ + inv(sqrt(d.α)) * rand(rng, g)^inv(d.p) * b\nend\n", "meta": {"hexsha": "fe24e4355190ebe89ba76ea5bbf0f8e7cdd2e86a", "size": 5047, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/pgeneralizedgaussian.jl", "max_stars_repo_name": "pdeffebach/Distributions.jl", "max_stars_repo_head_hexsha": "8aea3cc82ee2f8ffe1e8cd754e7fcd99369c7a1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/pgeneralizedgaussian.jl", "max_issues_repo_name": "pdeffebach/Distributions.jl", "max_issues_repo_head_hexsha": "8aea3cc82ee2f8ffe1e8cd754e7fcd99369c7a1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/pgeneralizedgaussian.jl", "max_forks_repo_name": "pdeffebach/Distributions.jl", "max_forks_repo_head_hexsha": "8aea3cc82ee2f8ffe1e8cd754e7fcd99369c7a1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9473684211, "max_line_length": 188, "alphanum_fraction": 0.6677234, "num_tokens": 1686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7532567267818945}}
{"text": "export distance\n\n\"\"\"\n    distance(H1::AbstractHyperrectangle, H2::AbstractHyperrectangle;\n             [p]::Real=2)\n\nCompute the standard distance between two hyperrectangular sets, defined as\n\n```math\n    \\\\inf_{x \\\\in H_1, y \\\\in H_2} \\\\{ d(x, y) \\\\}.\n```\n\n### Input\n\n- `H1` -- hyperrectangular set\n- `H2` -- hyperrectangular set\n- `p`  -- (optional; default: `2`) value of the ``p``-norm\n\n### Output\n\nThe distance, which is zero if the sets intersect and otherwise the ``p``-norm\nof the shortest line segment between any pair of points.\n\n### Notes\n\nSee also [`hausdorff_distance`](@ref) for an alternative distance notion.\n\"\"\"\nfunction distance(H1::AbstractHyperrectangle, H2::AbstractHyperrectangle;\n                  p::Real=2)\n    n = dim(H1)\n    @assert n == dim(H2) \"incompatible set dimensions $n and $(dim(H2))\"\n\n    N = promote_type(eltype(H1), eltype(H2))\n    d = Vector{N}(undef, n)\n    @inbounds for i in 1:n\n        # find relative position in dimension i\n        # (if c1 == c2, the results are equivalent independent of the branch)\n        if center(H1, i) >= center(H2, i)\n            lhs = low(H1, i)\n            rhs = high(H2, i)\n        else\n            lhs = low(H2, i)\n            rhs = high(H1, i)\n        end\n        if _leq(lhs, rhs)\n            d[i] = zero(N)\n        else\n            d[i] = rhs - lhs\n        end\n    end\n    return norm(d, p)\nend\n\n\"\"\"\n    distance(S::AbstractSingleton, X::LazySet; [p]::Real=2.0)\n\nCompute the distance between the singleton `S` and the set `X` with respect to\nthe given `p`-norm.\n\n### Input\n\n- `S` -- singleton, i.e., a set with one element\n- `X` -- set\n- `p` -- (optional, default: `2.0`) the `p`-norm used; `p = 2.0` corresponds to\n         the usual Euclidean norm\n\n### Output\n\nA scalar representing the distance between the element wrapped by `S` and the\nset `X`.\n\"\"\"\nfunction distance(S::AbstractSingleton, X::LazySet; p::Real=2.0)\n    return distance(element(S), X; p=p)\nend\n\ndistance(X::LazySet, S::AbstractSingleton; p::Real=2.0) = distance(S, X; p=p)\n\ndistance(S1::AbstractSingleton, S2::AbstractSingleton; p::Real=2.0) =\n    distance(element(S1), element(S2); p=p)\n\n# disambiguation\ndistance(S::AbstractSingleton, H::AbstractHyperrectangle; p::Real=2.0) =\n    distance(element(S), H; p=p)\ndistance(H::AbstractHyperrectangle, S::AbstractSingleton; p::Real=2.0) =\n    distance(element(S), H; p=p)\n", "meta": {"hexsha": "56f7c8896116ab5e15b0f9d1c287467d0348f8ba", "size": 2367, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ConcreteOperations/distance.jl", "max_stars_repo_name": "nablabits/LazySets.jl", "max_stars_repo_head_hexsha": "e839322ae970e5b61271b709f8a865184b32c8e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 194, "max_stars_repo_stars_event_min_datetime": "2017-11-01T20:07:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T22:06:30.000Z", "max_issues_repo_path": "src/ConcreteOperations/distance.jl", "max_issues_repo_name": "nablabits/LazySets.jl", "max_issues_repo_head_hexsha": "e839322ae970e5b61271b709f8a865184b32c8e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1986, "max_issues_repo_issues_event_min_datetime": "2017-10-23T18:46:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T06:13:40.000Z", "max_forks_repo_path": "src/ConcreteOperations/distance.jl", "max_forks_repo_name": "nablabits/LazySets.jl", "max_forks_repo_head_hexsha": "e839322ae970e5b61271b709f8a865184b32c8e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2017-11-08T17:10:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:33:59.000Z", "avg_line_length": 27.523255814, "max_line_length": 79, "alphanum_fraction": 0.6201943388, "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7532567161294215}}
{"text": "# polar plots\n\n\n#JL Plots\nusing Plots\n\nr(θ) = 1 + cos(θ) * sin(θ)^2\nPlots.plot(r, 0, 2π, proj=:polar, lims=(0,1.5))\n\nr(θ) = 1 + cos(θ) * sin(θ)^2\nθ = range(0, stop=2π, length=50)\nPlots.plot(θ, r.(θ), proj=:polar, lims=(0,1.5), c=:steelblue,  linewidth=2)\n\n\n# Polar with markers\n\nΘ = range(0, stop = 2π, length = 100)\npr = abs.(0.1 * randn(100) + sin.(3Θ))\nPlots.plot(Θ, pr, proj = :polar, m = 2, c=:steelblue,  linewidth=2)\n\n\n", "meta": {"hexsha": "4561dbfea34e87bb74d18200dc41d4328e11dcb2", "size": 426, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polarplots/polar.jl", "max_stars_repo_name": "Ellon-M/visualizations", "max_stars_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polarplots/polar.jl", "max_issues_repo_name": "Ellon-M/visualizations", "max_issues_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polarplots/polar.jl", "max_forks_repo_name": "Ellon-M/visualizations", "max_forks_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3636363636, "max_line_length": 75, "alphanum_fraction": 0.5868544601, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789452074398, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7532567131972305}}
{"text": "\n#####################################################################\n# Base functions.\n#####################################################################\nfunction sphere(x)\n  sum(x.^2)\nend\n\n# Schwefel's ellipsoid.\nfunction ellipsoid(x) \n  res = 0\n  for(i in 1:length(x))\n    res += sum(x[1:i])^2\n  end\n  res\nend\n\nfunction elliptic(x)\n  D = length(x)\n  condition = 1e+6\n  coefficients = condition .^ linspace(0, 1, D)\n  sum(coefficients .* x.^2)\nend\n\nfunction rastrigin(x)\n  D = length(x)\n  10 * D + sum( x.^2 ) - 10 * sum( cos( 2 * π * x ) )\nend\n\nfunction ackley(x)\n  D = length(x)\n  try\n    20 - 20.*exp(-0.2.*sqrt(sum(x.^2)/D)) - exp(sum(cos(2 * π * x))/D) + e\n  catch e\n    # Sometimes we have gotten a DomainError from the cos function so we protect this call\n    println(e)\n    println(\"For input x = \", x)\n    # Return a very large fitness value to indicate that this is NOT the solution we want.\n    # TODO: Fix better way to handle this!\n    9.99e100\n  end\nend\n\nfunction schwefel1_2(x)\n  D = length(x)\n  partsums = zeros(D)\n  partsum = 0\n  for i in 1:D\n    partsum += x[i]\n    partsums[i] = partsum\n  end\n  sum(partsums.^2)\nend\n\nfunction rosenbrock(x)\n  n = length(x)\n  return( sum( 100*( x[2:n] - x[1:(n-1)].^2 ).^2 + ( x[1:(n-1)] - 1 ).^2 ) )\nend\n\nfunction step(x)\n  sum(ceil(x + 0.5))\nend\n\nfunction griewank(x)\n  n = length(x)\n  1 + (1/4000)*sum(x.^2) - prod(cos(x ./ sqrt(1:n)))\nend\n\nfunction schwefel2_22(x)\n  ax = abs(x)\n  sum(ax) + prod(ax)\nend\n\nfunction schwefel2_21(x)\n  maximum(abs(x))\nend\n\n# I'm unsure about this one since it does not return the expected minima at\n# [1.0, 1.0].\nfunction schwefel2_26(x)\n  D = length(x)\n  418.98288727243369 * D - sum(x .* sin(sqrt(abs(x))))\nend\n\nfunction cigar(x)\n  x[1]^2 + 1e6 * sum(x[2:end].^2)\nend\n\nfunction cigtab(x)\n  x[1]^2 + 1e8 * x[end]^2 + 1e4 * sum(x[2:(end-1)].^2)\nend\n\n# Shekel10 is a 4D, multi-minima, non-separable test problem. Our implementation\n# is based on the C code in:\n#   http://www.math.ntu.edu.tw/~wwang/cola_lab/test_problems/multiple_opt/multiopt_prob/Shekel10/Shekel10.c\nShekel10_A = [4 4 4 4; 1 1 1 1; 8 8 8 8; 6 6 6 6; 3 7 3 7; 2 9 2 9; 5 5 3 3; 8 1 8 1; 6 2 6 2; 7 3.6 7 3.6]\nShekel10_C = [0.1, 0.2, 0.2, 0.4, 0.4, 0.6, 0.3, 0.7, 0.5, 0.5]\nfunction shekel(x, a, c)\n  sum = 0.0\n  for i in 1:length(c)\n    den = 0.0\n    for j in 1:size(a, 2)\n      den += (x[j] - a[i,j])^2\n    end\n    sum = sum - 1 / (den + c[i])\n  end\n  return sum\nend\nshekel10(x) = shekel(x, Shekel10_A, Shekel10_C)\n\n# Shekel7 is a 4D, multi-minima, non-separable test problem. Our implementation\n# is based on the C code in:\n#   http://www.math.ntu.edu.tw/~wwang/cola_lab/test_problems/multiple_opt/multiopt_prob/Shekel7/Shekel7.c\nShekel7_A = [4 4 4 4; 1 1 1 1; 8 8 8 8; 6 6 6 6; 3 7 3 7; 2 9 2 9; 5 5 3 3]\nShekel7_C = [0.1, 0.2, 0.2, 0.4, 0.4, 0.6, 0.3]\nshekel7(x) = shekel(x, Shekel7_A, Shekel7_C)\n\n# Shekel5 is a 4D, multi-minima, non-separable test problem. Our implementation\n# is based on the C code in:\n#   http://www.math.ntu.edu.tw/~wwang/cola_lab/test_problems/multiple_opt/multiopt_prob/Shekel5/Shekel5.c\nShekel5_A = [4 4 4 4; 1 1 1 1; 8 8 8 8; 6 6 6 6; 3 7 3 7]\nShekel5_C = [0.1, 0.2, 0.2, 0.4, 0.4]\nshekel5(x) = shekel(x, Shekel5_A, Shekel5_C)\n\n# Hartman 6D is a multi-minima, non-separable test problem. Our implementation is based on:\n#  http://www.sfu.ca/~ssurjano/hart6.html\nHartman6_alpha = [1.0 1.2 3.0 3.2]\nHartman6_A = [10 3 17 3.50 1.7 8; 0.05 10 17 0.1 8 14; 3 3.5 1.7 10 17 8; 17 8 0.05 10 0.1 14]\nHartman6_P = 1e-4 * [1312 1696 5569 124 8283 5886; 2329 4135 8307 3736 1004 9991; 2348 1451 3522 2883 3047 6650; 4047 8828 8732 5743 1091 381]\nfunction hartman(x, alpha, A, P)\n  sum = 0.0\n  for i in 1:length(alpha)\n    isum = 0.0\n    for j in 1:size(A, 2)\n      isum += A[i,j] * (x[j] - P[i,j])^2\n    end\n    sum -= alpha[i] * exp(-isum)\n  end\n  sum\nend\nhartman6(x) = hartman(x, Hartman6_alpha, Hartman6_A, Hartman6_P)\n\n# Hartman 3D is a multi-minima, non-separable test problem. Our implementation is based on:\n#  http://www.sfu.ca/~ssurjano/hart3.html\n# However, we get a different global minima than the one stated on that page.\nHartman3_alpha = [1.0 1.2 3.0 3.2]\nHartman3_A = [3.0 10 30; 0.1 10 35; 3.0 10 30; 0.1 10 36]\nHartman3_P = 1e-4 * [3689 1170 2673; 4699 4387 7470; 1091 8732 5547; 381 5743 8828]\nhartman3(x) = hartman(x, Hartman3_alpha, Hartman3_A, Hartman3_P)\n# The minima should be -3.86278 but we get a different one so use that in the problem spec:\n\n#####################################################################\n# S2 functions in addition to the base functions above. As stated\n# in table II of the JADE paper: http://150.214.190.154/EAMHCO/pdf/JADE.pdf\n#####################################################################\n\nfunction quartic(x)\n  D = length(x)\n  sum( (1:D) .* x.^4 )\nend\n\nfunction noisy_quartic(x)\n  quartic(x) + rand()\nend\n\nfunction s2_step(x)\n  sum( ceil(x + 0.5).^2 )\nend\n\n#####################################################################\n# Misc other interesting optimization functions and families.\n#####################################################################\n\n# Schwefel 2.13 is a hard one...\n#function f=schwefel_213(x)\n#global initial_flag\n#persistent a b A alpha\n#[ps,D]=size(x);\n#if initial_flag==0\n#    initial_flag=1;\n#    load schwefel_213_data\n#    if length(alpha)>=D\n#        alpha=alpha(1:D);a=a(1:D,1:D);b=b(1:D,1:D);\n#    else\n#        alpha=-3+6*rand(1,D);\n#        a=round(-100+200.*rand(D,D));\n#        b=round(-100+200.*rand(D,D));\n#    end\n#    alpha=repmat(alpha,D,1);\n#    A=sum(a.*sin(alpha)+b.*cos(alpha),2);\n#end\n#for i=1:ps\n#    xx=repmat(x(i,:),D,1);\n#    B=sum(a.*sin(xx)+b.*cos(xx),2);\n#    f(i,1)=sum((A-B).^2,1);\n#end\n\n# This is a generator for the family of deceptive functions from the \n# Cuccu2011 paper on novelty-based restarts. We have vectorized it to allow\n# more than 1D versions. The Cuccu2011 paper uses the following values for\n# (l, w) = [(5, 0),  (15, 0),  (30, 0), \n#           (5, 2),  (15, 2),  (30, 2), \n#           (5, 10), (15, 10), (30, 10)]\n# and notes that (15, 2) and (30, 2) are the most difficult instances.\nfunction deceptive_cuccu2011(l, w)\n  (x) -> begin\n    absx = abs(x)\n    sumabsx = sum(absx)\n    if sumabsx <= 1\n      return sum(x.^2)\n    elseif sumabsx >= l+1\n      return sum((absx - l).^2)\n    else\n      return (1 - 0.5 * sum(sin( (π * w * (absx - 1)) / l ).^2))\n    end\n  end\nend\n\n# Deceptive/hardest instances:\ndeceptive_cuccu2011_15_2 = deceptive_cuccu2011(15, 2)\ndeceptive_cuccu2011_30_2 = deceptive_cuccu2011(30, 2)\n\n", "meta": {"hexsha": "670488feb8667e4885112ab1e2124b274c6e9154", "size": 6531, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/single_objective_base_functions.jl", "max_stars_repo_name": "tmeits/BlackBoxOptim.jl", "max_stars_repo_head_hexsha": "97c59d3d19a92d3e19994b8db7984ba3a1b67ca8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-11-27T17:30:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-27T17:30:47.000Z", "max_issues_repo_path": "src/problems/single_objective_base_functions.jl", "max_issues_repo_name": "tmeits/BlackBoxOptim.jl", "max_issues_repo_head_hexsha": "97c59d3d19a92d3e19994b8db7984ba3a1b67ca8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/single_objective_base_functions.jl", "max_forks_repo_name": "tmeits/BlackBoxOptim.jl", "max_forks_repo_head_hexsha": "97c59d3d19a92d3e19994b8db7984ba3a1b67ca8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2869955157, "max_line_length": 142, "alphanum_fraction": 0.59056806, "num_tokens": 2589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7532567120082567}}
{"text": "using UncertaintyQuantification, Random\nRandom.seed!(2547);\nN = 200\nmu = [0, 0]\nsig = [1 -0.55; -0.55 1]\nmvnormal = MvNormal(mu, sig)\n\n\nsam = zeros(200,2)\nfor i in 1:200 sam[i,:] = rand(mvnormal) end\n\nRandom.seed!()\n\nfunction likelihood(x) \n    if x[1] >1 || x[1]<-1\n        rv = 0\n    else\n        rv = 1\n        for i in 1:N\n            rv = rv/(2*pi*sqrt(1-x[1]^2))*exp(-1/(2*(1-x[1]^2))*(sam[i,1]^2-2*x[1]*\n            sam[i,1]*sam[i,2]+sam[i,2]^2))\n        end\n    end\n    return rv\nend\n\nfunction prior(x) \n    if x[1] >1 || x[1]<-1\n        rv = 0\n    else\n        rv = 1/(1-x[1]^2)^(3/2)\n    end\n    return rv\nend\npriorsample(n) = rand(Uniform(-1,1),(n))\n\n\ntmcmcsample = tmcmc(likelihood, prior, priorsample, 2000, 0.2)", "meta": {"hexsha": "afa1fb53620b8a8d7c61fc360194e1623471e73f", "size": 725, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demo/bayesianinference/correlationexample.jl", "max_stars_repo_name": "sitoryu/UncertaintyQuantification.jl", "max_stars_repo_head_hexsha": "f0e63fd3bfc176d8271b83ee999923690331472f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demo/bayesianinference/correlationexample.jl", "max_issues_repo_name": "sitoryu/UncertaintyQuantification.jl", "max_issues_repo_head_hexsha": "f0e63fd3bfc176d8271b83ee999923690331472f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo/bayesianinference/correlationexample.jl", "max_forks_repo_name": "sitoryu/UncertaintyQuantification.jl", "max_forks_repo_head_hexsha": "f0e63fd3bfc176d8271b83ee999923690331472f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0789473684, "max_line_length": 83, "alphanum_fraction": 0.5213793103, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813538993889, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7532475359508907}}
{"text": "using LinearAlgebra\r\nusing Plots\r\n\r\n#%\r\n#% The 'illustrative example' from Section 1.4, Chapter 1.\r\n#%\r\n#% written by John Bardsley 2016.\r\n#%\r\n#% Define the matrix A using the SVD\r\nv1 = [1/sqrt(2) 1/sqrt(2)]';\r\nv2 = [-1/sqrt(2) 1/sqrt(2)]';\r\ns1 = 1;\r\ns2 = 1e-2;\r\nA  = s1*v1*v1'+s2*v2*v2';\r\n\r\n#% Define true x and noise free b\r\nx   = [1 1]';\r\nb_e = A*x;\r\n\r\n#% Create realization from the data model\r\nnsamp  = 10000;\r\nσ  = 0.1;\r\nb_samp = repeat(b_e,1,nsamp)+σ*randn(2,nsamp);\r\n\r\n#figure(1),\r\n  scatter(b_samp[1,:],b_samp[2,:]) #,'k*')\r\n#% Create the corresponding least squares solutions\r\nx_LS = A\\b_samp;\r\n#figure(2)\r\n  scatter(x_LS[1,:],x_LS[2,:]) #,'k*')\r\n\r\n#% Check ill-posedness inequality (1.28)\r\nill_posed_lhs = 0.5*(1/s1+1/s2)\r\nill_posed_rhs = norm(x)/norm(b_e)\r\n", "meta": {"hexsha": "61aaddffe961745e83f0c5bf622be09b442b7029", "size": 769, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter1/TwoVarTest.jl", "max_stars_repo_name": "julianschnidder/CompUQ4InvProblems", "max_stars_repo_head_hexsha": "f69fe03a99eb5aa1672ce5e2f4c30c4601820cd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1/TwoVarTest.jl", "max_issues_repo_name": "julianschnidder/CompUQ4InvProblems", "max_issues_repo_head_hexsha": "f69fe03a99eb5aa1672ce5e2f4c30c4601820cd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1/TwoVarTest.jl", "max_forks_repo_name": "julianschnidder/CompUQ4InvProblems", "max_forks_repo_head_hexsha": "f69fe03a99eb5aa1672ce5e2f4c30c4601820cd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9714285714, "max_line_length": 59, "alphanum_fraction": 0.6072821847, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452772, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.753247534962737}}
{"text": "function draw_wireframe_sphere(pos, r; npts=11, color=(255,255,255), name=nothing, opacity=1.)\n    ϕs = range(0, stop=2π, length=npts)\n    θs = range(-π/2, stop=π/2, length=npts)\n    # vertical\n    v_xs = [[r * cos(θ) * sin(ϕ) + pos[1] for θ in θs] for ϕ in ϕs[1:end-1]]\n    v_ys = [[r * cos(θ) * cos(ϕ) + pos[2] for θ in θs] for ϕ in ϕs[1:end-1]]\n    v_zs = [[r * sin(θ) + pos[3] for θ in θs] for ϕ in ϕs[1:end-1]]\n    # horizontal\n    h_xs = [[r * cos(θ) * sin(ϕ) + pos[1] for ϕ in ϕs] for θ in θs]\n    h_ys = [[r * cos(θ) * cos(ϕ) + pos[2] for ϕ in ϕs] for θ in θs]\n    h_zs = [[r * sin(θ) + pos[3] for ϕ in ϕs] for θ in θs] \n\n    hover = isnothing(name) ? \"skip\" : nothing\n\n    xs, ys, zs = Float64[], Float64[], Float64[]\n    for i=1:length(v_xs)\n        append!(xs, v_xs[i])\n        push!(xs, NaN)\n        append!(ys, v_ys[i])\n        push!(ys, NaN)\n        append!(zs, v_zs[i])\n        push!(zs, NaN)\n    end\n    for j=1:length(h_xs)\n        append!(xs, h_xs[j])\n        push!(xs, NaN)\n        append!(ys, h_ys[j])\n        push!(ys, NaN)\n        append!(zs, h_zs[j])\n        push!(zs, NaN)\n    end\n\n    return scatter3d(;x=xs, y=ys, z=zs, \n                      mode=\"lines\",\n                      line=attr(color=\"rgb$color\"),\n                      opacity=opacity,\n                      showlegend=false, showscale=false, name=name,\n                      hovertemplate=name, hoverinfo=hover,\n            )\nend\n\ndraw_central_body(bd::Union{CelestialBody,Star}; kwargs...\n    ) = draw_wireframe_sphere(SVector{3,Float64}(0.,0.,0.), bd.eqradius; color=bd.color, name=bd.name, kwargs...)\n\ndraw_orbiting_body(bd::CelestialBody, t; kwargs...\n    ) = draw_wireframe_sphere(time_orbital_position(t, bd.orbit), bd.eqradius; color=bd.color, name=bd.name, kwargs...)\n\ndraw_soi(bd::CelestialBody, t; kwargs...\n    ) = draw_wireframe_sphere(time_orbital_position(t, bd.orbit), bd.SoI; color=bd.color, name=bd.name, opacity=0.25, kwargs...)", "meta": {"hexsha": "81766836166e063596b0c78a3d2e535e0b5e43c8", "size": 1935, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/draw/drawobject.jl", "max_stars_repo_name": "tmcgrath325/KeplerTools.jl", "max_stars_repo_head_hexsha": "bb95d6c24ca7e1cea6f7f8057f01a415f5719f6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/draw/drawobject.jl", "max_issues_repo_name": "tmcgrath325/KeplerTools.jl", "max_issues_repo_head_hexsha": "bb95d6c24ca7e1cea6f7f8057f01a415f5719f6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-19T16:28:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T16:28:17.000Z", "max_forks_repo_path": "src/draw/drawobject.jl", "max_forks_repo_name": "tmcgrath325/KeplerTools.jl", "max_forks_repo_head_hexsha": "bb95d6c24ca7e1cea6f7f8057f01a415f5719f6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4897959184, "max_line_length": 128, "alphanum_fraction": 0.5591731266, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900507, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.753232080052357}}
{"text": "module FreudenthalTriangulations\n\nusing LinearAlgebra\nusing SparseArrays\n\nexport FreudenthalTriangulation, vertices, simplex, belief_vertices, belief_simplex\n\n# Construct the Freudenthal triangulation of the belief simplex\n\nstruct FreudenthalTriangulation\n        n::Int\n        m::Int\nend\n\n\"\"\"\n    vertices(T::FreudenthalTriangulation)\nConstruct the list of Freudenthal vertices in an `n` dimensional space with grid resolution `m`.\nThe vertices are represented by a list of `n` dimensional vectors.\n\"\"\"\nfunction vertices(T::FreudenthalTriangulation)\n    V = Vector{Int}[]\n    v = Vector{Int}(undef, T.n)\n    v[1] = T.m\n    _vertices!(V, v, 2)\n    return V\nend\n\nfunction _vertices!(V::Vector{Vector{Int64}}, v::Vector{Int64}, i::Int64)\n    n = length(v)\n    if i > n\n        push!(V, copy(v))\n        return\n    end\n    for k in 0 : v[i-1]\n        v[i] = k\n        _vertices!(V, v, i+1)\n    end\nend\n\n\"\"\"\n    _freudenthal_simplex(x::Vector{Float64})\nReturns the list of vertices of the simplex of point `x` in the Freudenthal grid.\n\"\"\"\nfunction _freudenthal_simplex(x::Vector{Float64})\n    n = length(x)\n    V = Vector{Vector{Int}}(undef, n+1)\n    V[1] = floor.(Int, x)\n    d = x - V[1]\n    p = sortperm(d, rev=true)\n    for i in 2 : n+1\n        V[i] = copy(V[i-1])\n        V[i][p[i-1]] += 1\n    end\n    return V\nend\n\n\"\"\"\n    _barycentric_coordinates(x::Vector{Float64}, V::Vector{Vector{Int64}})\nGiven a point `x` and its simplex `V` in the Freudenthal grid, returns the barycentric coordinates\nof `x` in the grid. `V` must be in the same order as provided by the output of `freudenthal_simplex`\n\"\"\"\nfunction _barycentric_coordinates(x::Vector{Float64}, V::Vector{Vector{Int64}})\n    d = x - V[1]\n    p = sortperm(d, rev=true)\n    n = length(x)\n    λ = Vector{Float64}(undef, n+1)\n    λ[n+1] = d[p[n]]\n    for i in n:-1:2\n        λ[i] = d[p[i-1]] - d[p[i]]\n    end\n    λ[1] = 1.0 - sum(λ[2:end])\n    return λ\nend\n\n\"\"\"\n    simplex(T::FreudenthalTriangulation, x::Vector{Float64})\nGiven a point `x`, returns the simplex of the point `x` and the barycentric coordinates of `x` in the grid.\n\"\"\"\nfunction simplex(T::FreudenthalTriangulation, x::Vector{Float64})\n    V = _freudenthal_simplex(x)\n    return V, _barycentric_coordinates(x, V)\nend\n\n\"\"\"\n    _to_belief(x)\nTransform a point `x` in the Freudenthal space to a point in the belief space.\n\"\"\"\n_to_belief(x) = (push!(x[1:end-1] - x[2:end], x[end]))./x[1]\n\n\"\"\"\n    _to_freudenthal(b, m::Int64)\nTransform a point `b` in the belief space to a point in the Freudenthal space.\n`m` is the resolution of the Freudenthal grid.\n\"\"\"\n_to_freudenthal(b, m::Int64) = [sum(b[k] for k in i : length(b))*m for i in 1 : length(b)]\n\n\"\"\"\n    belief_vertices(T::FreudenthalTriangulation)\n    Converts the list of Freudenthal vertices with dimension `T.n` and granularity `T.m` into\n    belief space and returns the list\n\"\"\"\nbelief_vertices(T::FreudenthalTriangulation) = _to_belief.(vertices(T))\n\n\"\"\"\n    belief_simplex(T::FreudenthalTriangulation, b)\n    Constructs the belief simplex surrounding a belief `b` and the barycentric coordinates\n    corresponding to the location of the belief within the simplex\n\"\"\"\nfunction belief_simplex(T::FreudenthalTriangulation, b)\n    x = _to_freudenthal(b, T.m)\n    V, λ = simplex(T, x)\n    B = _to_belief.(V)\n    valid =  λ .> sqrt(eps())\n    return B[valid], λ[valid]\nend\n\nend # module\n", "meta": {"hexsha": "fed0f342997631331f1dfa052a1efc7671aa5449", "size": 3359, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FreudenthalTriangulations.jl", "max_stars_repo_name": "sisl/FreudenthalTriangulations.jl", "max_stars_repo_head_hexsha": "efe9e140f62cfde9bf2ab2828c8fecdc66a75f00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FreudenthalTriangulations.jl", "max_issues_repo_name": "sisl/FreudenthalTriangulations.jl", "max_issues_repo_head_hexsha": "efe9e140f62cfde9bf2ab2828c8fecdc66a75f00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FreudenthalTriangulations.jl", "max_forks_repo_name": "sisl/FreudenthalTriangulations.jl", "max_forks_repo_head_hexsha": "efe9e140f62cfde9bf2ab2828c8fecdc66a75f00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4661016949, "max_line_length": 107, "alphanum_fraction": 0.6650788925, "num_tokens": 1041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7532153687681716}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction _flux2mag(flux::T, zero_point::T, ABwave::T) where {T<:AbstractFloat}\n    if isnan(ABwave)\n        return -2.5*log10(flux) - zero_point\n    else\n        return -2.5*log10(flux) - 5 * log10(float(ABwave)) - 2.406\n    end\nend\n\n\"\"\"\n    flux2mag(flux[, zero_point, ABwave=number]) -> magnitude\n\n### Purpose ###\n\nConvert from flux expressed in erg/(s cm² Å) to magnitudes.\n\n### Explanation ###\n\nThis is the reverse of `mag2flux`.\n\n### Arguments ###\n\n* `flux`: the flux to be converted in magnitude, expressed in\n  erg/(s cm² Å).\n* `zero_point`: the zero point level of the magnitude.  If not\n supplied then defaults to 21.1 (Code et al 1976).  Ignored if the `ABwave`\n keyword is supplied\n* `ABwave` (optional numeric keyword): wavelength in Angstroms.\n If supplied, then returns Oke AB magnitudes (Oke & Gunn 1983, ApJ, 266, 713;\n http://adsabs.harvard.edu/abs/1983ApJ...266..713O).\n\n### Output ###\n\nThe magnitude.\n\nIf the `ABwave` keyword is set then magnitude is given by the expression\n\n\\$\\$\\\\text{ABmag} = -2.5\\\\log_{10}(f) - 5\\\\log_{10}(\\\\text{ABwave}) - 2.406\\$\\$\n\nOtherwise, magnitude is given by the expression\n\n\\$\\$\\\\text{mag} = -2.5\\\\log_{10}(\\\\text{flux}) - \\\\text{zero point}\\$\\$\n\n### Example ###\n\n```jldoctest\njulia> using AstroLib\n\njulia> flux2mag(5.2e-15)\n14.609991640913002\n\njulia> flux2mag(5.2e-15, 15)\n20.709991640913003\n\njulia> flux2mag(5.2e-15, ABwave=15)\n27.423535345634598\n```\n\n### Notes ###\n\nCode of this function is based on IDL Astronomy User's Library.\n\"\"\"\nflux2mag(flux::Real, zero_point::Real=21.1; ABwave::Real=NaN) =\n    _flux2mag(promote(float(flux), float(zero_point), float(ABwave))...)\n", "meta": {"hexsha": "8cc1dbd428445f38016c6bd732622cfa229994b4", "size": 1724, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/flux2mag.jl", "max_stars_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_stars_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2016-09-11T14:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T20:45:36.000Z", "max_issues_repo_path": "src/flux2mag.jl", "max_issues_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_issues_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 64, "max_issues_repo_issues_event_min_datetime": "2017-01-19T21:03:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:27:46.000Z", "max_forks_repo_path": "src/flux2mag.jl", "max_forks_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_forks_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:11:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:55:21.000Z", "avg_line_length": 25.7313432836, "max_line_length": 79, "alphanum_fraction": 0.6763341067, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7532153668850363}}
{"text": "\nusing DifferentialEquations\nusing Plots\ngr()\n\nfunction lif(u,p,t);\n    gL, EL, C, Vth, I = p\n    (-gL*(u-EL)+I)/C\nend\n\n\nfunction thr(u,t,integrator)\n    integrator.u > integrator.p[4]\nend\n\nfunction reset!(integrator)\n    integrator.u = integrator.p[2]\nend\n\nthreshold = DiscreteCallback(thr,reset!)\ncurrent_step= PresetTimeCallback([2,15],integrator -> integrator.p[5] += 210.0)\ncb = CallbackSet(current_step,threshold)\n\n\nu0 = -75\ntspan = (0.0, 40.0)\n# p = (gL, EL, C, Vth, I)\np = [10.0, -75.0, 5.0, -55.0, 0]\n\nprob = ODEProblem(lif, u0, tspan, p, callback=cb)\n\n\nsol = solve(prob)\n\n\nplot(sol)\n\n\n#Izhikevichch Model\nusing DifferentialEquations\nusing Plots\n\nfunction izh!(du,u,p,t);\n    a, b, c, d, I = p\n\n    du[1] = 0.04*u[1]^2+5*u[1]+140-u[2]+I\n    du[2] = a*(b*u[1]-u[2])\nend\n\n\nfunction thr(u,t,integrator)\n    integrator.u[1] >= 30\nend\n\nfunction reset!(integrator)\n    integrator.u[1] = integrator.p[3]\n    integrator.u[2] += integrator.p[4]\nend\n\nthreshold = DiscreteCallback(thr,reset!)\ncurrent_step= PresetTimeCallback(50,integrator -> integrator.p[5] += 10)\ncb = CallbackSet(current_step,threshold)\n\n\np = [0.02, 0.2, -50, 2, 0]\nu0 = [-65, p[2]*-65]\ntspan = (0.0, 300)\n\nprob = ODEProblem(izh!, u0, tspan, p, callback=cb)\n\n\nsol = solve(prob);\nplot(sol, vars=1)\n\n\nplot(sol, vars=2)\n\n\np = [0.02, 0.2, -65, 8, 0]\nu0 = [-65, p[2]*-65]\ntspan = (0.0, 300)\n\nprob = ODEProblem(izh!, u0, tspan, p, callback=cb)\nsol = solve(prob);\nplot(sol, vars=1)\n\n\nusing DifferentialEquations\nusing Plots\n\n# Potassium ion-channel rate functions\nalpha_n(v) = (0.02 * (v - 25.0)) / (1.0 - exp((-1.0 * (v - 25.0)) / 9.0))\nbeta_n(v) = (-0.002 * (v - 25.0)) / (1.0 - exp((v - 25.0) / 9.0))\n\n# Sodium ion-channel rate functions\nalpha_m(v) = (0.182*(v + 35.0)) / (1.0 - exp((-1.0 * (v + 35.0)) / 9.0))\nbeta_m(v) = (-0.124 * (v + 35.0)) / (1.0 - exp((v + 35.0) / 9.0))\n\nalpha_h(v) = 0.25 * exp((-1.0 * (v + 90.0)) / 12.0)\nbeta_h(v) = (0.25 * exp((v + 62.0) / 6.0)) / exp((v + 90.0) / 12.0)\n\nfunction HH!(du,u,p,t);\n    gK, gNa, gL, EK, ENa, EL, C, I = p\n    v, n, m, h = u\n\n    du[1] = (-(gK * (n^4.0) * (v - EK)) - (gNa * (m ^ 3.0) * h * (v - ENa)) - (gL * (v - EL)) + I) / C\n    du[2] = (alpha_n(v) * (1.0 - n)) - (beta_n(v) * n)\n    du[3] = (alpha_m(v) * (1.0 - m)) - (beta_m(v) * m)\n    du[4] = (alpha_h(v) * (1.0 - h)) - (beta_h(v) * h)\nend\n\n\ncurrent_step= PresetTimeCallback(100,integrator -> integrator.p[8] += 1)\n\n# n, m & h steady-states\nn_inf(v) = alpha_n(v) / (alpha_n(v) + beta_n(v))\nm_inf(v) = alpha_m(v) / (alpha_m(v) + beta_m(v))\nh_inf(v) = alpha_h(v) / (alpha_h(v) + beta_h(v))\n\np = [35.0, 40.0, 0.3, -77.0, 55.0, -65.0, 1, 0]\nu0 = [-60, n_inf(-60), m_inf(-60), h_inf(-60)]\ntspan = (0.0, 1000)\n\nprob = ODEProblem(HH!, u0, tspan, p, callback=current_step)\n\n\nsol = solve(prob);\nplot(sol, vars=1)\n\n\nplot(sol, vars=[2,3,4], tspan=(105.0,130.0))\n\n\nfunction gSyn(max_gsyn, tau, tf, t);\n    if t-tf >= 0\n        return max_gsyn * exp(-(t-tf)/tau)\n    else\n        return 0.0\n    end\nend\nfunction HH!(du,u,p,t);\n    gK, gNa, gL, EK, ENa, EL, C, I, max_gSyn, ESyn, tau, tf = p\n    v, n, m, h = u\n\n    ISyn = gSyn(max_gSyn, tau, tf, t) * (v - ESyn)\n\n    du[1] = (-(gK * (n^4.0) * (v - EK)) - (gNa * (m ^ 3.0) * h * (v - ENa)) - (gL * (v - EL)) + I - ISyn) / C\n    du[2] = (alpha_n(v) * (1.0 - n)) - (beta_n(v) * n)\n    du[3] = (alpha_m(v) * (1.0 - m)) - (beta_m(v) * m)\n    du[4] = (alpha_h(v) * (1.0 - h)) - (beta_h(v) * h)\nend\n\n\np = [35.0, 40.0, 0.3, -77.0, 55.0, -65.0, 1, 0, 0.008, 0, 20, 100]\ntspan = (0.0, 200)\nprob = ODEProblem(HH!, u0, tspan, p)\nsol = solve(prob);\nplot(sol, vars=1)\n\n\np = [35.0, 40.0, 0.3, -77.0, 55.0, -65.0, 1, 0, 0.01, 0, 20, 100]\ntspan = (0.0, 200)\nprob = ODEProblem(HH!, u0, tspan, p)\nsol = solve(prob);\nplot!(sol, vars=1)\n\n\nfunction HH!(du,u,p,t);\n    gK, gNa, gL, EK, ENa, EL, C, I, tau, tau_u, tau_R, u0, gmax, Esyn  = p\n    v, n, m, h, u, R, gsyn = u\n\n    du[1] = ((gK * (n^4.0) * (EK - v)) + (gNa * (m ^ 3.0) * h * (ENa - v)) + (gL * (EL - v)) + I + gsyn * (Esyn - v)) / C\n    du[2] = (alpha_n(v) * (1.0 - n)) - (beta_n(v) * n)\n    du[3] = (alpha_m(v) * (1.0 - m)) - (beta_m(v) * m)\n    du[4] = (alpha_h(v) * (1.0 - h)) - (beta_h(v) * h)\n\n    # Synaptic variables\n    du[5] = -(u/tau_u)\n    du[6] = (1-R)/tau_R\n    du[7] = -(gsyn/tau)\nend\n\nfunction epsp!(integrator);\n    integrator.u[5] += integrator.p[12] * (1 - integrator.u[5])\n    integrator.u[7] += integrator.p[13] * integrator.u[5] * integrator.u[6]\n    integrator.u[6] -= integrator.u[5] * integrator.u[6]\n\nend\n\nepsp_ts= PresetTimeCallback(100:100:500, epsp!)\n\np = [35.0, 40.0, 0.3, -77.0, 55.0, -65.0, 1, 0, 30, 1000, 50, 0.5, 0.005, 0]\nu0 = [-60, n_inf(-60), m_inf(-60), h_inf(-60), 0.0, 1.0, 0.0]\ntspan = (0.0, 700)\nprob = ODEProblem(HH!, u0, tspan, p, callback=epsp_ts)\nsol = solve(prob);\nplot(sol, vars=1)\n\n\nplot(sol, vars=7)\n\n\nplot(sol, vars=[5,6])\n\n\nepsp_ts= PresetTimeCallback(100:1000:5100, epsp!)\n\np = [35.0, 40.0, 0.3, -77.0, 55.0, -65.0, 1, 0, 30, 500, 50, 0.5, 0.005, 0]\nu0 = [-60, n_inf(-60), m_inf(-60), h_inf(-60), 0.0, 1.0, 0.0]\ntspan = (0.0, 5300)\nprob = ODEProblem(HH!, u0, tspan, p, callback=epsp_ts)\nsol = solve(prob);\nplot(sol, vars=7)\n\n\nplot(sol, vars=[5,6])\n\n\nepsp_ts= PresetTimeCallback(100:100:500, epsp!)\n\np = [35.0, 40.0, 0.3, -77.0, 55.0, -65.0, 1, 0, 30, 100, 1000, 0.5, 0.005, 0]\nu0 = [-60, n_inf(-60), m_inf(-60), h_inf(-60), 0.0, 1.0, 0.0]\ntspan = (0.0, 700)\nprob = ODEProblem(HH!, u0, tspan, p, callback=epsp_ts)\nsol = solve(prob);\nplot(sol, vars=7)\n\n\nplot(sol, vars=[5,6])\n\n\nusing SciMLTutorials\nSciMLTutorials.tutorial_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])\n\n", "meta": {"hexsha": "1561cf921bf7a03ed537b809677a502a928079b7", "size": 5574, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/models/08-spiking_neural_systems.jl", "max_stars_repo_name": "siravan/SciMLTutorials.jl", "max_stars_repo_head_hexsha": "34f4044f96facf351eb32c991b73325a32d17a94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-05-24T10:30:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T12:13:03.000Z", "max_issues_repo_path": "script/models/08-spiking_neural_systems.jl", "max_issues_repo_name": "LoopGlitch26/SciMLTutorials.jl", "max_issues_repo_head_hexsha": "837d71ad59de12af2fa48babb9e5cd2e280dc71a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-07T21:39:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T03:48:31.000Z", "max_forks_repo_path": "script/models/08-spiking_neural_systems.jl", "max_forks_repo_name": "LoopGlitch26/SciMLTutorials.jl", "max_forks_repo_head_hexsha": "837d71ad59de12af2fa48babb9e5cd2e280dc71a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-24T14:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T14:30:36.000Z", "avg_line_length": 23.7191489362, "max_line_length": 121, "alphanum_fraction": 0.5522066738, "num_tokens": 2585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7532153666598852}}
{"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    CubicVariogram(range=r, sill=s, nugget=n)\n    CubicVariogram(ball; sill=s, nugget=n)\n\nA cubic variogram with range `r`, sill `s` and nugget `n`.\nOptionally, use a custom metric `ball`.\n\"\"\"\nstruct CubicVariogram{V,B} <: Variogram\n  sill::V\n  nugget::V\n  ball::B\nend\n\nCubicVariogram(ball; sill=1.0, nugget=zero(typeof(sill))) =\n  CubicVariogram(sill, nugget, ball)\n\nCubicVariogram(; range=1.0, sill=1.0, nugget=zero(typeof(sill))) =\n  CubicVariogram(sill, nugget, MetricBall(range))\n\nfunction (γ::CubicVariogram)(h::T) where {T}\n  r = radius(γ.ball)\n  s = γ.sill\n  n = γ.nugget\n\n  # constants\n  c1 = T(35) / T(4)\n  c2 = T(7)  / T(2)\n  c3 = T(3)  / T(4)\n  s1 = 7*(h/r)^2 - c1*(h/r)^3 + c2*(h/r)^5 - c3*(h/r)^7\n  s2 = T(1)\n\n  (h < r) * (s - n) * s1 +\n  (h ≥ r) * (s - n) * s2 +\n  (h > 0) * n\nend\n\nisstationary(::Type{<:CubicVariogram}) = true\n", "meta": {"hexsha": "f94fefdc09acd3c9ea119e799af936c9b2fbc629", "size": 1053, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/theoretical/cubic.jl", "max_stars_repo_name": "juliohm/Variography.jl", "max_stars_repo_head_hexsha": "0a14d7e83a1a3c2fb9adc5af2847fcef13789238", "max_stars_repo_licenses": ["ISC"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-18T10:01:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-18T10:01:09.000Z", "max_issues_repo_path": "src/theoretical/cubic.jl", "max_issues_repo_name": "juliohm/Variography.jl", "max_issues_repo_head_hexsha": "0a14d7e83a1a3c2fb9adc5af2847fcef13789238", "max_issues_repo_licenses": ["ISC"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-06-14T08:34:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-01T23:03:38.000Z", "max_forks_repo_path": "src/theoretical/cubic.jl", "max_forks_repo_name": "juliohm/Variography.jl", "max_forks_repo_head_hexsha": "0a14d7e83a1a3c2fb9adc5af2847fcef13789238", "max_forks_repo_licenses": ["ISC"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-06-14T08:17:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-17T18:20:15.000Z", "avg_line_length": 25.0714285714, "max_line_length": 68, "alphanum_fraction": 0.5270655271, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7532153644390231}}
{"text": "export leaky_relu\n\ndoc\"\"\"\n    leaky_relu(x::Var, alpha=0.1)\n\nLeaky Rectified Linear Unit.\n\n```math\nf(x) =\n\\begin{cases}\nx & x > 0 \\\\\n\\alpha x & x \\leq 0\n\\end{cases}\n```\n\n# References\n* Maas et al., [\"Rectifier Nonlinearities Improve Neural Network Acoustic Models\"](http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf), ICML 2013.\n\"\"\"\nleaky_relu(x::Var, alpha=0.1) = Var(leaky_relu.(x.data,eltype(x)(alpha)), (leaky_relu,x,alpha))\nleaky_relu(x::T, alpha::T) where T = x >= zero(T) ? x : x*alpha\nleaky_relu(x::Node, alpha=0.1) = Node(leaky_relu, x, alpha)\n\nfunction addgrad!(y::Var, ::typeof(leaky_relu), x::Var, alpha::Float64)\n    isvoid(x.grad) && return\n    ∇leaky_relu!(y.grad, x.data, x.grad, eltype(x)(alpha))\nend\n\nfunction ∇leaky_relu!(gy::Array{T}, x::Array{T}, gx::Array{T}, alpha::T) where T\n    @inbounds for i = 1:length(x)\n        gx[i] += x[i] >= zero(T) ? gy[i] : gy[i]*alpha\n    end\nend\n", "meta": {"hexsha": "9fb9c117174450771e70df0cc25278271adecf90", "size": 919, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/activation/leaky_relu.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Merlin.jl-80f3d04f-b880-5e6d-8e06-6a7e799169ac", "max_stars_repo_head_hexsha": "5c13eafab1df4dc4a73e7bdc85d45d3e4990fd80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 166, "max_stars_repo_stars_event_min_datetime": "2015-12-19T08:49:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-10T08:11:27.000Z", "max_issues_repo_path": "src/functions/activation/leaky_relu.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Merlin.jl-80f3d04f-b880-5e6d-8e06-6a7e799169ac", "max_issues_repo_head_hexsha": "5c13eafab1df4dc4a73e7bdc85d45d3e4990fd80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2016-02-03T14:49:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:31:32.000Z", "max_forks_repo_path": "src/functions/activation/leaky_relu.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Merlin.jl-80f3d04f-b880-5e6d-8e06-6a7e799169ac", "max_forks_repo_head_hexsha": "5c13eafab1df4dc4a73e7bdc85d45d3e4990fd80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2016-01-12T14:19:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-17T14:21:37.000Z", "avg_line_length": 27.8484848485, "max_line_length": 163, "alphanum_fraction": 0.648531012, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7532153569064827}}
{"text": "function nlsolve(f, j, x, iterations = 10^5, r_norm = norm, r_abstol = sqrt(eps(eltype(x))))\n    xnext = x\n    r = f(x)\n    for i = 1:iterations\n        if r_norm(r) <= r_abstol\n            return r, xnext, :success\n        end\n        x = copy(xnext)\n        s = - j(x)\\r\n        xnext = x + s\n        r = f(xnext)\n    end\n    if r_norm(r) <= r_abstol\n        return r, xnext, :success\n    end\n    r, xnext, :failure\nend\n", "meta": {"hexsha": "4013f6f0edcebd22879f2df86b15689bd89eb793", "size": 422, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlsolve.jl", "max_stars_repo_name": "pkofod/SimpleSolve.jl", "max_stars_repo_head_hexsha": "319ce4e76ca4b4f8154e328fee70a9c0cfa10265", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nlsolve.jl", "max_issues_repo_name": "pkofod/SimpleSolve.jl", "max_issues_repo_head_hexsha": "319ce4e76ca4b4f8154e328fee70a9c0cfa10265", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nlsolve.jl", "max_forks_repo_name": "pkofod/SimpleSolve.jl", "max_forks_repo_head_hexsha": "319ce4e76ca4b4f8154e328fee70a9c0cfa10265", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4444444444, "max_line_length": 92, "alphanum_fraction": 0.5023696682, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.916109606718245, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7532153550233477}}
{"text": "function alphaj(a::Complex128)\n    return sqrt(1 - abs(a)^2)\nend\n\nfunction dictionaryElement(z::Complex128,a::Complex128)\n    return alphaj(a)/(z-a)\nend\n\nfunction blaschkeElement(z::Complex128,a::Complex128)\n    return (1-conj(a)*z)/(z-a)\nend\n\nfunction invBlaschkeElement(z::Complex128,a::Complex128)\n    return (z-a)/(1-conj(a)*z)\nend\n\nfunction blaschkeProd(z::Complex128,aj::Vector{Complex128})\n    r = one(z)\n    for i=1:length(aj)\n        r *= blaschkeElement(z,aj[i])\n    end\n    return r\nend\n\nfunction blaschkeProdExceptQ(z::Complex128,aj::Vector{Complex128},q::Int)\n    r = one(z)\n    for i=1:length(aj)\n        if i!=q\n            r *= blaschkeElement(z,aj[i])\n        end\n    end\n    return r\nend\n\nfunction impulseTakenakaMalmquist(n,aj::Vector{Complex128})\n    if n<=zero(n)\n        return zero(Complex128)\n    end\n    temp1 = zero(Complex128)\n    temp2 = zero(Complex128)\n    for i=1:(length(aj)-1)\n        temp1 += aj[i]^(n-1)*dictionaryElement(aj[i],aj[end])*blaschkeProdExceptQ(aj[i],aj[1:(length(aj)-1)],i)*(1-abs(aj[i])^2)\n    end\n    temp2 += aj[end]^(n-1)*alphaj(aj[end])*blaschkeProd(aj[end],aj[1:(length(aj)-1)])\n    return temp1 + temp2\nend", "meta": {"hexsha": "57ad2a61fd500043be7cc85837703eadbbba5fbf", "size": 1161, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "AnalyticTM.jl", "max_stars_repo_name": "fullerf/Time_Domain_Signal_System_Identification", "max_stars_repo_head_hexsha": "84349d2675f01967f85746ee6b499512180b54b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-21T03:10:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-21T03:10:45.000Z", "max_issues_repo_path": "AnalyticTM.jl", "max_issues_repo_name": "fullerf/Time_Domain_Signal_System_Identification", "max_issues_repo_head_hexsha": "84349d2675f01967f85746ee6b499512180b54b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AnalyticTM.jl", "max_forks_repo_name": "fullerf/Time_Domain_Signal_System_Identification", "max_forks_repo_head_hexsha": "84349d2675f01967f85746ee6b499512180b54b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-11T20:19:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-11T20:19:01.000Z", "avg_line_length": 25.2391304348, "max_line_length": 128, "alphanum_fraction": 0.6391042205, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7531886424626668}}
{"text": "\n# coding: utf-8\n\n# In[1]:\n\n#global list is the key\n#otherwise we will lose the list throughout iterations\nglobal factors=[]\n\n\n# In[2]:\n\n\nfunction factorization(num)\n    \n    #negative and float should be excluded\n    if (num<0) || !(isinteger(num))\n        \n        error(\"negative or float is not allowed\")\n        \n    end\n   \n    #if n is smaller than 4 \n    #prime number it is\n    if num>4\n            \n        #exclude 1 and itself\n        #the largest factor of n can not exceed the half of n\n        #because 2 is the smallest factor\n        #the range of factors we are gonna try starts from 2 to fld(num,2)+1\n        #int function to solve the odd number problem\n        for i in 2:(fld(num,2)+1)\n            \n            #the factorization process\n            if num%i==0\n                \n                push!(factors,i)\n\n                #return is crucial\n                #if the number is not a prime number\n                #it will stop function from appending non-prime factors\n                #the next few lines will be ignored\n                return factorization(Int32(num/i))\n                \n            end\n\n        end\n            \n    end\n    \n    #append the last factor    \n    #it could be n itself if n is a prime number\n    #in that case there is only one element in the list\n    #or it could be the last indivisible factor of n which is also a prime number\n    push!(factors,num)\n    \n    if length(factors)==1\n        \n        println(num,\" is a prime number\")\n        empty!(factors)\n        \n    end\n        \nend\n\n\n# In[3]:\n\n\nfactorization(71392643)\n\n\n# In[4]:\n\n\nprint(factors)\n\n", "meta": {"hexsha": "aa8902376afad5cec2e2fd53d340e8ae7d911b07", "size": 1614, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "factorization.jl", "max_stars_repo_name": "je-suis-tm/recursion-and-dynamic-programming", "max_stars_repo_head_hexsha": "55a6085cd45b73426379ff947d9a842ef7d325bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-03-22T10:31:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:30:17.000Z", "max_issues_repo_path": "factorization.jl", "max_issues_repo_name": "slowbrain/recursion-and-dynamic-programming", "max_issues_repo_head_hexsha": "1cd77db1e7940fee15fc8aa2cedd3ab84e10374f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "factorization.jl", "max_forks_repo_name": "slowbrain/recursion-and-dynamic-programming", "max_forks_repo_head_hexsha": "1cd77db1e7940fee15fc8aa2cedd3ab84e10374f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2019-10-27T12:34:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T13:54:37.000Z", "avg_line_length": 20.6923076923, "max_line_length": 81, "alphanum_fraction": 0.5501858736, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073577, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.753188638754243}}
{"text": "using EngEconomics\n\n# Given\n# 12 months\n# month1 - 15000 cost\n# g = 5% per month\n# grant is received in 6 monthy installments starting at month 2\n# i = 12%\n\nn = 1\nm = 12\ni = 0.12\nnc = n * m\nic = i / m\nAc = 15000\ng = 0.05\nF = Ac * presentWorthConversionFactorGeometric(g, ic, nc) * compoundAmountFactor(ic, nc)\nAg = F * capitalRecoveryFactor(ic, 6)\n", "meta": {"hexsha": "f8809e1ebd10129798e364ad8b23b77344982a7c", "size": 348, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps3/p4.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/ps3/p4.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/ps3/p4.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.3157894737, "max_line_length": 88, "alphanum_fraction": 0.6724137931, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693617046215, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7531884270692542}}
{"text": "###########################################################################################################\n###########################################################################################################\n###########################################################################################################\n###########################################################################################################\n###########################################################################################################\n###########################################################################################################\n#                                         RADIAL COEFFICIENTS                                             #\n###########################################################################################################\n###########################################################################################################\n###########################################################################################################\n###########################################################################################################\n###########################################################################################################\n###########################################################################################################\nexport SlaterON, SlaterSF, SlaterSA, SlaterSB, SlaterSN, SlaterSX\n###########################################################################################################\n########################################## SLATER TYPE ORBITALS ###########################################\nSlaterON(n::arb, ζ::arb) = ((2*ζ)^(n + 1//2))//Sqrt(Gamma(2*n + One(n)))\nSlaterON(n::Real, ζ::Real) = SlaterON(RF(n), RF(ζ))\n\nfunction SlaterON(n1::arb, n2::arb, ρ::arb, τ::arb)\n    res1 = ((ρ*(One(τ)+τ))^(n1 + 1//2)) * ((ρ*(One(τ)-τ))^(n2 + 1//2))\n    res2 = Sqrt(Gamma(2*n1 + One(n1)) * Gamma(2*n2 + One(n2)))\n    res1 // res2\nend\nSlaterON(n1::Real, n2::Real, ρ::Real, τ::Real) = SlaterON(RF(n1), RF(n2), RF(ρ), RF(τ))\n###########################################################################################################\n###########################################################################################################\n###########################################################################################################\n#                                     SLATER TYPE SPINOR ORBITALS                                         #\n###########################################################################################################\n###########################################################################################################\n###########################################################################################################\t\n########################################## NORMALIZATION FACTOR ###########################################\n################# Relativistic normalization factor N_{n\\kappa}\nSlaterSF(n::arb, κ::Int) = ifelse(κ < 0, Abs(κ), Sqrt(κ^2 + (2*n + 1)))\nSlaterSF(n::Real, κ::Int) = SlaterSF(RF(n), κ)\n###########################################################################################################\t\n############################################## COEFFICIENT A ##############################################\n################# Normalization coeeficients so called A^{\\beta}_{n\\kappa}\nSlaterSA(β::Int, n::arb, κ::Int) = ifelse(κ < 0, (β*κ)//(2*n), (β//2)*(SlaterSF(n, κ)-κ) - (RF(1)//RF(2)))\nSlaterSA(β::Int, n::Real, κ::Int) = SlaterSA(β, RF(n), RF(κ))\n###########################################################################################################\t\n############################################## COEFFICIENT B ##############################################\n################# Normalization coeeficients so called B^{\\beta}_{n\\kappa}\nSlaterSB(β::Int, n::arb, κ::Int) = ifelse(κ < 0, Zero(RF), -β*((SlaterSF(n, κ) - κ)//(2*n + 1)))\nSlaterSB(β::Int, n::Real, κ::Int) = SlaterSB(β, RF(n), RF(κ))\n###########################################################################################################\t\n############################################## COEFFICIENT N ##############################################\n################# 1/Sqrt(N) part, the dominator is used for both wave and charge density\nfunction SlaterSN(β::Int, n::arb, κ::Int)\n    res1 = SlaterSA(β, n, κ) * SlaterSA(β, n, κ) * Gamma(2*n + RF(1))\n    res2 = SlaterSA(β, n, κ) * SlaterSB(β, n, κ) * Gamma(2*n + RF(2))\n    res3 = SlaterSB(β, n, κ) * SlaterSB(β, n, κ) * (Gamma(2*n + RF(3)) // 4)\n    res1 + res2 + res3\nend\nSlaterSN(β::Int, n::Real, κ::Int) = SlaterSN(β, RF(n), κ)\n\nSlaterSN(β::Int, n::arb, κ::Int, ζ::arb) = ((2*ζ)^(n + 1//2))//Sqrt(SlaterSN(β, n, κ))\nSlaterSN(β::Int, n::Real, κ::Int, ζ::Real) = SlaterSN(β, RF(n), κ, RF(ζ))\n\nfunction SlaterON(β1::Int, n1::arb, κ1::Int, β2::Int, n2::arb, κ2::Int, ρ::arb, τ::arb)\n    res1 = ((ρ*(One(τ)+τ))^(n1 + 1//2)) * ((ρ*(One(τ)-τ))^(n2 + 1//2))\n    res2 = Sqrt(SlaterSN(β1, n1, κ1) * SlaterSN(β2, n2, κ2)) \n    res1 // res2\nend\nSlaterSN(β1::Int, n1::Real, κ1::Int, β2::Int, n2::Real, κ2::Int, ρ::Real, τ::Real) =\nSlaterSN(β1, RF(n1), κ1, β2, RF(n2), κ2, RF(ρ), RF(τ))\n\nfunction SlaterSX(β1::Int, n1::arb, κ1::Int, ζ1::arb, β2::Int, n2::arb, κ2::Int, ζ2::arb)\n    a1 = SlaterSA(β1, n1, κ1)\n    a2 = SlaterSA(β2, n2, κ2)\n    b1 = SlaterSB(β1, n1, κ1)\n    b2 = SlaterSB(β2, n2, κ2)\n\n    x1 = ζ1 * ζ1 * a1 * a2\n    x2 = ζ1 * ζ2 * b1 * a2\n    x3 = ζ1 * ζ2 * a1 * b2\n    x4 = ζ2 * ζ2 * b1 * b2\n\n    x = [x1, x2, x3, x4]\n    x = transpose(x)\n    return x\nend\nSlaterSX(β1::Int, n1::Real, κ1::Int, ζ1::Real, β2::Int, n2::Real, κ2::Int, ζ2::Real) =\nSlaterSX(β1, RF(n1), κ1, RF(ζ1), β2, RF(n2), κ2, RF(ζ2))", "meta": {"hexsha": "57e26fa9fa33bc0213317db5c704e854a69a919e", "size": 5789, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/radial_coefficients.jl", "max_stars_repo_name": "abagciphys/JRAF.jl", "max_stars_repo_head_hexsha": "911cd8e7d8af0e4d8c846afecff5a332851ba120", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-02-28T08:15:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T17:24:21.000Z", "max_issues_repo_path": "src/radial_coefficients.jl", "max_issues_repo_name": "abagciphys/JRAF.jl", "max_issues_repo_head_hexsha": "911cd8e7d8af0e4d8c846afecff5a332851ba120", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/radial_coefficients.jl", "max_forks_repo_name": "abagciphys/JRAF.jl", "max_forks_repo_head_hexsha": "911cd8e7d8af0e4d8c846afecff5a332851ba120", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 68.1058823529, "max_line_length": 108, "alphanum_fraction": 0.2703403006, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.753188426944192}}
{"text": "function primitiven{T<:Integer}(m::T)\n    1 < m || return T[]\n    m != 2 || return T[1]\n    !isprime(m) || return T[2:2:m-1]\n    rp = trues(m-1)\n    if isodd(m)\n        rp[1:2:m-1] = false\n    end\n    for p in keys(factor(m))\n        rp[p:p:m-1] = false\n    end\n    T[1:m-1][rp]\nend\n\nfunction pythagoreantripcount{T<:Integer}(plim::T)\n    primcnt = 0\n    fullcnt = 0\n    11 < plim || return (primcnt, fullcnt)\n    for m in 2:plim\n        p = 2m^2\n        p+2m <= plim || break\n        for n in primitiven(m)\n            q = p + 2m*n\n            q <= plim || break\n            primcnt += 1\n            fullcnt += div(plim, q)\n        end\n    end\n    return (primcnt, fullcnt)\nend\n\nprintln(\"Counting Pythagorian Triplets within perimeter limits:\")\nprintln(\"    Limit          All   Primitive\")\nfor om in 1:10\n    (pcnt, fcnt) = pythagoreantripcount(10^om)\n    println(@sprintf \"    10^%02d  %11d   %9d\" om fcnt pcnt)\nend\n", "meta": {"hexsha": "8e4f8f61307db51e4e1ca6d046f6d0e8b682cadf", "size": 919, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/pythagorean-triples.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/pythagorean-triples.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/pythagorean-triples.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1842105263, "max_line_length": 65, "alphanum_fraction": 0.5321001088, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693731004241, "lm_q2_score": 0.7931059462938814, "lm_q1q2_score": 0.753188426819129}}
{"text": "function lorentz_likelihood_hermitian_band_save(p,y::Vector{Float64},aex,al_small,indx,logdeta)\n# Computes the likelihood of a sum of Exponential/Cosine kernels (which have a\n# Lorentzian power spectrum) utilizing the approach of Ambikasaran (2015)\n#   Numer. Linear Algebra Appl. 2015; 22:1102-1114 DOI: 10.1002/nla\n# Uses (2.30) from Rasmussen & Williams (2006) to compute the log likelihood.\n# The form of the kernel is:\n#\n#   K(t_i,t_j) = w_i \\delta_{ij} + \\sum_{k=1}^{p} \\alpha_k \\exp{-\\beta_k |t_i-t_j|}\n#\n# This is represented by the matrix A_{ij} = K(t_i,t_j).\n# The log likelihood is given by:\n# ln(L) = -1/2 y^T A^{-1} y - 1/2 |det(A)|\n# Note: if a \\beta_k is complex, then its complex conjugate *must* be included as well.\n#\n# First, define band-diagonal matrix for kernel:\n# [x_i,{r_{i,1},...,r_{i,p}},{l_{i,1},...,l_{i,p}}]\n\n#tic()\nn = length(y)\n# There are p+1 sub-diagonals, p+1 super-diagonals + diagonal\n# for a total of 2*p+3 non-zero diagonals:\nnex = (2p+1)*n-2p\nbex = zeros(Complex{Float64},nex)\nfor i=1:n\n# Compute actual indices:\n  irow =(i-1)*(1+2p)+1\n  bex[irow] = y[i]\n# Diagonal noise:\n  for j=1:p\n    if i < n\n      bex[irow+  j] = 0.0\n      bex[irow+p+j] = 0.0\n    end\n  end\nend\n\n# Specify the number of bands below & above the diagonal:\nm1 = p+1\nm2 = p+1\n# Solve the equation A^{-1} y = b using band-diagonal LU back-substitution on\n# the extended equations: A_{ex}^{-1} y_{ex} = b_{ex}:\nbanbks(aex,nex,m1,m2,al_small,indx,bex)\n# Now select solution to compute the log likelihood:\n# The equation A^{-1} y = b has been solved in bex (the extended vector).\n# So, I need to pick out the b portion from bex, and take the dot product\n# with y (which is the residuals of the data minus model, which is correlated\n# noise that we are modeling with the multi-Lorentzian covariance function):\nlog_like = 0.0\nfor i=1:n\n  log_like += real(bex[(i-1)*(2p+1)+1])*y[i]\nend\n# Convert this to log likelihood:\nlog_like = -0.5*log_like\nreturn log_like\nend\n", "meta": {"hexsha": "e07d43b71e3406dc2d9941196a5dd4cde85b9089", "size": 1966, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lorentz_likelihood_hermitian_band_save.jl", "max_stars_repo_name": "ericagol/tyc3559_julia", "max_stars_repo_head_hexsha": "5fb14968838ab352dccb6582f1f766dc400b98af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-08-03T02:57:25.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-03T02:57:25.000Z", "max_issues_repo_path": "lorentz_likelihood_hermitian_band_save.jl", "max_issues_repo_name": "ericagol/tyc3559_julia", "max_issues_repo_head_hexsha": "5fb14968838ab352dccb6582f1f766dc400b98af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lorentz_likelihood_hermitian_band_save.jl", "max_forks_repo_name": "ericagol/tyc3559_julia", "max_forks_repo_head_hexsha": "5fb14968838ab352dccb6582f1f766dc400b98af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1071428571, "max_line_length": 95, "alphanum_fraction": 0.6831129196, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693731004241, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.753188424497078}}
{"text": "module PhysicalOceanography\n\nexport f, β\n\nΩ = 7.2921 * 10^(-5) #rad/s\nR = 6.3781 * 10^(6) #m\n\n\"\"\"\n    f(φ)\n\nCoriolis Parameter\n\"\"\"\nf(φ) = 2Ω * sind(φ)\n\n\"\"\"\n    β(φ)\n\nRossby Parameter\n\"\"\" \nβ(φ) = 2Ω / R * cosd(φ)\n \nend\n", "meta": {"hexsha": "667edf0e53921e48f1f9549e7ba6b8ec1b75eebb", "size": 218, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PhysicalOceanography.jl", "max_stars_repo_name": "gaelforget/PhysicalOceanography.jl", "max_stars_repo_head_hexsha": "2b7e7f44d2d24a62eed5e4bedfbbd76d24a4a26b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PhysicalOceanography.jl", "max_issues_repo_name": "gaelforget/PhysicalOceanography.jl", "max_issues_repo_head_hexsha": "2b7e7f44d2d24a62eed5e4bedfbbd76d24a4a26b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-04T16:57:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-16T15:02:48.000Z", "max_forks_repo_path": "src/PhysicalOceanography.jl", "max_forks_repo_name": "gaelforget/PhysicalOceanography.jl", "max_forks_repo_head_hexsha": "2b7e7f44d2d24a62eed5e4bedfbbd76d24a4a26b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 9.4782608696, "max_line_length": 27, "alphanum_fraction": 0.5275229358, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535723, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7531884200405702}}
{"text": "\"\"\"\n    eom_anishchenko1(u, p, t)\n\nEquations of motion for the system defined by eq. 13 in [1], which can \ngive strange, nonchaotic attractors.\n\n## Equations of motion \n\nThe equations of motion are \n\n```math\n\\\\begin{aligned}\ndx &= \\\\alpha (1-s \\\\cos (2 \\\\pi \\\\phi )) \\\\cdot x(1-x) \\\\\\\\\ndϕ &= (\\\\phi + \\\\omega ) \\\\mod{1}\n\\\\end{aligned}\n```\n\n## References\n\n1. Anishchenko, Vadim S., and Galina I. Strelkova. \"Irregular attractors.\"\n    Discrete dynamics in Nature and Society 2.1 (1998): 53-72.\n\"\"\"\nfunction eom_anishchenko1(u, p, t)\n    x, ϕ = (u...,)\n    α, s, ω = (p...,)\n    dx = α*(1 - s*cos(2*pi*ϕ))*x*(1 - x)\n    dϕ = (ϕ + ω) % 1\n\n    return SVector{2}(dx, dϕ)\nend\n\nfunction anishchenko1(u₀, α, s, ω)\n    p = [α, s, ω]\n    DiscreteDynamicalSystem(eom_anishchenko1, u₀, p)\nend\n\n\"\"\"\n    anishchenko1(;u₀ = rand(2), α =3.277, s=0.1, ω=0.5*(sqrt(5)-1))\n\nInitialise the system defined by eq. 13 in [1], which can give strange, \nnonchaotic attractors.\n\n## Equations of motion \n\nThe equations of motion are \n\n```math\n\\\\begin{aligned}\ndx &= \\\\alpha (1-s \\\\cos (2 \\\\pi \\\\phi )) \\\\cdot x(1-x) \\\\\\\\\ndϕ &= (\\\\phi + \\\\omega ) \\\\mod{1}\n\\\\end{aligned}\n```\n\n## References\n\n1. Anishchenko, Vadim S., and Galina I. Strelkova. \"Irregular attractors.\"\n    Discrete dynamics in Nature and Society 2.1 (1998): 53-72.\n\"\"\"\nanishchenko1(;u₀ = rand(2), α =3.277, s=0.1, ω=0.5*(sqrt(5)-1)) =\n    anishchenko1(u₀, α, s, ω)\n", "meta": {"hexsha": "c273b873fec83b2d3c50844969fd95e465ea3e08", "size": 1400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/systems/discretemaps/anishchenko1.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/CausalityTools.jl-5520caf5-2dd7-5c5d-bfcb-a00e56ac49f7", "max_stars_repo_head_hexsha": "93935b3bc73738c52b004e9cf23d6f6a4778982c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2020-06-11T01:51:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T18:39:43.000Z", "max_issues_repo_path": "src/systems/discretemaps/anishchenko1.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/CausalityTools.jl-5520caf5-2dd7-5c5d-bfcb-a00e56ac49f7", "max_issues_repo_head_hexsha": "93935b3bc73738c52b004e9cf23d6f6a4778982c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2020-12-21T02:52:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T10:40:08.000Z", "max_forks_repo_path": "src/systems/discretemaps/anishchenko1.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/CausalityTools.jl-5520caf5-2dd7-5c5d-bfcb-a00e56ac49f7", "max_forks_repo_head_hexsha": "93935b3bc73738c52b004e9cf23d6f6a4778982c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-09-27T08:56:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T15:05:51.000Z", "avg_line_length": 22.9508196721, "max_line_length": 74, "alphanum_fraction": 0.6035714286, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220787, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.7531773926174089}}
{"text": "module mlmetrics\nusing  Statistics\n\n\"\"\"\n    struct mse{T<:AbstractFloat}\n        y::Vector\n        ŷ::Vector\n    end\n    The mean squared error is the sum of the squared differences between the\n    predicted and observed values.\n\n\n    struct mae{T<:AbstractFloat}\n        y::Vector\n        ŷ::Vector\n    end\n    The mean absolute error is the sum of the absolute differences between the\n    predicted and observed values.\n\n\n    struct rmse{T<:AbstractFloat}\n        y::Vector\n        ŷ::Vector\n    end\n    The root mean squared error is the square root of the mean squared error.\n\n\n    struct rmae{T<:AbstractFloat}\n        y::Vector\n        ŷ::Vector\n    end\n    The root mean absolute error is the square root of the mean absolute error.\n\n\n    struct rmsle{T<:AbstractFloat}\n        y::Vector\n        ŷ::Vector\n    end\n    The root mean squared log error is the square root of the mean squared log error.\n\n\n    struct r2score{T<:AbstractFloat}\n        y::Vector\n        ŷ::Vector\n    end\n    The R2 is a statistic that will give some information about the goodness of fit of a model.\n\"\"\"\n\n\n\nstruct mse{T<:AbstractFloat}\n    y::Vector\n    ŷ::Vector\n\n    function mse(y, ŷ)\n        return mean((y - ŷ).^2)\n    end\nend\n\nstruct mae{T<:AbstractFloat}\n    y::Vector\n    ŷ::Vector\n\n    function mae(y, ŷ)\n        return mean(abs.(y - ŷ))\n    end\nend\n\nstruct rmse{T<:AbstractFloat}\n    y::Vector\n    ŷ::Vector\n\n    function rmse(y, ŷ)\n        return sqrt(mse(y, ŷ))\n    end\nend\n\nstruct rmae{T<:AbstractFloat}\n    y::Vector\n    ŷ::Vector\n\n    function rmae(y, ŷ)\n        return sqrt(mae(y, ŷ))\n    end\nend\n\nstruct rmsle{T<:AbstractFloat}\n    y::Vector\n    ŷ::Vector\n\n    function rmsle(y, ŷ)\n        return sqrt(mean((log.(y .+ 1) - log.(ŷ .+ 1)).^2))\n    end\nend\n\nstruct r2score{T<:AbstractFloat}\n    y::Vector\n    ŷ::Vector\n\n    function r2score(y, ŷ)\n        squares = sum(y.^2)\n        residuals = sum(y - ŷ).^2\n        return 1 - residuals/squares\n    end\nend\n\nstruct binarycrossentropy{T<:AbstractFloat}\n    y::Vector\n    ŷ::Vector\n\n    function binarycrossentropy(y::Vector, ŷ::Vector)\n        ε = 1e-10\n        return -mean(y.*log2.(ŷ .+ ε) + (1 .- y).*log2.(1 .- ŷ .+ ε))\n    end\nend\n\nstruct accuracy{T<:AbstractFloat}\n    y_true::AbstractArray\n    y_predict::AbstractArray\n\n    function accuracy(y_true::AbstractArray, y_predict::AbstractArray)\n        return sum(y_true.==y_predict)/length(y_true)\n    end\n\nend\n\nstruct precision{T<:AbstractFloat}\n    y_true::AbstractArray\n    y_predict::AbstractArray\n\n    function precision(y_true::AbstractArray, y_predict::AbstractArray)\n        true_positives = sum(y_true.== 1 .== y_predict)\n        true_negatives = sum(y_true.== 0 .== y_predict)\n        false_positives = sum(y_true.!= 1 .== y_predict)\n        false_negatives = sum(y_true.!= 0 .== y_predict)\n\n        return true_positives/(true_positives + false_positives)\n    end\n\nend\n\n\nstruct recall{T<:AbstractFloat}\n    y_true::AbstractArray\n    y_predict::AbstractArray\n\n    function recall(y_true::AbstractArray, y_predict::AbstractArray)\n        true_positives = sum(y_true.== 1 .== y_predict)\n        true_negatives = sum(y_true.== 0 .== y_predict)\n        false_positives = sum(y_true.!= 1 .== y_predict)\n        false_negatives = sum(y_true.!= 0 .== y_predict)\n\n        return true_positives/(true_positives + false_negatives)\n    end\n    \nend\n\nstruct f1_score{T<:AbstractFloat}\n    y_true::AbstractArray\n    y_predict::AbstractArray\n\n    function f1_score(y_true::AbstractArray, y_predict::AbstractArray)\n        num =  2 * precision(y_true, y_predict) * recall(y_true, y_predict) \n        den = precision(y_true, y_predict) + recall(y_true, y_predict)\n        return num/den\n    end\n\nend\n\nend\n\n", "meta": {"hexsha": "602b377427dc555bf0e7bcfdc0be61d7b338663a", "size": 3704, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/metric.jl", "max_stars_repo_name": "Navaneeth-Sharma/regressionmetrics.jl", "max_stars_repo_head_hexsha": "345c4639cadde2f973534c8604965fad3710095e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-13T12:38:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T15:10:48.000Z", "max_issues_repo_path": "src/metric.jl", "max_issues_repo_name": "Navaneeth-Sharma/regressionmetrics.jl", "max_issues_repo_head_hexsha": "345c4639cadde2f973534c8604965fad3710095e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-02-02T13:23:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T19:02:48.000Z", "max_forks_repo_path": "src/metric.jl", "max_forks_repo_name": "Navaneeth-Sharma/mlmetrics.jl", "max_forks_repo_head_hexsha": "345c4639cadde2f973534c8604965fad3710095e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5348837209, "max_line_length": 95, "alphanum_fraction": 0.6382289417, "num_tokens": 1052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.7531673197083483}}
{"text": "using EngEconomics, Roots\n\n# Given\n# a = parasailing\n# b = kayaking\naInit = -100000\naAnnual = 15000\naN = 15\n\nbInit = -10000\nbAnnual = 2000\nbN = 15\nMARR = 0.10\n\nN = aN\n\n# Determine the better alternative\nΔInit = aInit - bInit\nΔAnnual = aAnnual - bAnnual\nΔIRR(x) = ΔInit + ΔAnnual * seriesPresentAmountFactor(x, N)\nΔIRR_ans = find_zero(ΔIRR, 0.05)\n\nif ΔIRR_ans > MARR\n\tprintln(\"Choose Parasailing\")\nelse\n\tprintln(\"Choose Kayaking\")\nend\n", "meta": {"hexsha": "b9ab09c194acd319e8a343cc5b68f2c841540b6f", "size": 434, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/examples/irr_4.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/examples/irr_4.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/examples/irr_4.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.5, "max_line_length": 59, "alphanum_fraction": 0.7119815668, "num_tokens": 161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.946596665680527, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7531673114215135}}
{"text": "\n# stoichiometric matrix: fluxes (in order) are v1-v6 (v6 is reverse of v5), b1-b20\nS = [-1 0 0 1 2 -2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; #citrulline\n     -1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;  #aspartate\n     1 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; #arginosuccinate\n     0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; #fumarate\n     0 1 -1 0 -2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; #arginine\n     0 0 1 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;  #ornithine\n     0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; #urea\n     0 0 0 -1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; #carbamoyl phosphate\n     -1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; #ATP\n     1 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0; #AMP\n     1 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0; #diphosphate\n     0 0 0 1 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0; #phosphate\n     0 0 0 0 -3 3 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 0; #NADPH\n     0 0 0 0 -3 3 0 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0; #H+\n     0 0 0 0 -4 4 0 0 0 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0; #O2\n     0 0 0 0 2 -2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0; #NO2\n     0 0 0 0 3 -3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 -1 0 0; #NADP+\n     0 0 -1 0 4 -4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 -1]; #H2O\n\n#atom matrix: C H N O P S \nA = [6 13 3 3 0 0; #citrulline\n    4 7 1 4 0 0;  #aspartate\n    10 18 4 6 0 0; #arginosuccinate\n    4 4 0 4 0 0; #fumarate\n    6 14 4 2 0 0; #arginine\n    5 12 2 2 0 0; #ornithine\n    1 4 2 1 0 0; #urea\n    1 4 1 5 1 0; #carbamoyl phosphate\n    10 16 5 13 3 0; #ATP\n    10 14 5 7 1 0;  #AMP\n    0 4 0 7 2 0;  #diphosphate\n    0 3 0 4 1 0;  #phosphate\n    21 30 7 17 3 0; #NADPH\n    0 1 0 0 0 0; #H+\n    0 0 0 2 0 0; #O2\n    0 0 1 1 0 0; #NO\n    21 29 7 17 3 0; #NADP+\n    0 2 0 1 0 0] #H2O\n\ne = transpose(A)*S\n\n#look at only the balances for v1-v6, species are not balanced over boundaries\nprint(e[:,1:6])\n\n ", "meta": {"hexsha": "15adb54900385826144adace710c8b56f0bc5781", "size": 1958, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "elemental_balances.jl", "max_stars_repo_name": "mgcroen/CHEME-5440-7770-PS3-S21", "max_stars_repo_head_hexsha": "d7cfa29f756d3ed8fb4f40afc2a3a610a4c4e765", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "elemental_balances.jl", "max_issues_repo_name": "mgcroen/CHEME-5440-7770-PS3-S21", "max_issues_repo_head_hexsha": "d7cfa29f756d3ed8fb4f40afc2a3a610a4c4e765", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "elemental_balances.jl", "max_forks_repo_name": "mgcroen/CHEME-5440-7770-PS3-S21", "max_forks_repo_head_hexsha": "d7cfa29f756d3ed8fb4f40afc2a3a610a4c4e765", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6595744681, "max_line_length": 82, "alphanum_fraction": 0.5117466803, "num_tokens": 1476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.753167310430923}}
{"text": "using Knet, ParticleSwarmOptimization\ninclude(\"Args.jl\")\n\nhosaki(x) = (1 - 8*x[1] + 7*(x[1]^2) - 7/3*(x[1]^3) + (1/4)*(x[1]^4))*(x[2]^2)*exp(-1 * x[2])\n#x* = (4,2)\n#f(x*) = -2.3458\n#julia hosaki.jl --num 10 --epoch 100\n\nfunction main()\n    gpu(false)\n    args = parse_commandline()\n    \n    problem = RegularProblem(hosaki, 2, [0.0,0.0], [5.0,6.0])\n    gbest = pso(problem, args[\"num\"], args[\"epoch\"], args[\"phi1\"], args[\"phi2\"], args[\"w\"], args[\"vmin\"], args[\"vmax\"])\n    \n    println(\"\\nBest: $(gbest.pbest_fitness), $(gbest.x)\")\nend\n\nmain()\n\n", "meta": {"hexsha": "95e0bed336b8b050f05c8dc966256bfcc10dec6c", "size": 545, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/hosaki.jl", "max_stars_repo_name": "ozanarkancan/ParticleSwarmOptimization.jl", "max_stars_repo_head_hexsha": "46d0644efa8bf666a90bb540f736f8107083b5a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-01-16T01:59:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T15:10:20.000Z", "max_issues_repo_path": "examples/hosaki.jl", "max_issues_repo_name": "ozanarkancan/ParticleSwarmOptimization.jl", "max_issues_repo_head_hexsha": "46d0644efa8bf666a90bb540f736f8107083b5a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2016-03-30T21:51:57.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-19T18:18:31.000Z", "max_forks_repo_path": "examples/hosaki.jl", "max_forks_repo_name": "ozanarkancan/ParticleSwarmOptimization.jl", "max_forks_repo_head_hexsha": "46d0644efa8bf666a90bb540f736f8107083b5a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-09-25T22:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-05T19:11:02.000Z", "avg_line_length": 25.9523809524, "max_line_length": 119, "alphanum_fraction": 0.5596330275, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936262, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7531673092322246}}
{"text": "# ---\n# title: 241. Different Ways to Add Parentheses\n# id: problem241\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Medium\n# categories: Divide and Conquer\n# link: <https://leetcode.com/problems/different-ways-to-add-parentheses/description/>\n# hidden: true\n# ---\n# \n# Given a string of numbers and operators, return all possible results from\n# computing all the different possible ways to group numbers and operators. The\n# valid operators are `+`, `-` and `*`.\n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: \"2-1-1\"\n#     Output: [0, 2]\n#     Explanation:\n#     ((2-1)-1) = 0 \n#     (2-(1-1)) = 2\n# \n# **Example 2:**\n# \n#     \n#     \n#     Input:\"2*3-4*5\"\n#     Output: [-34, -14, -10, -10, 10]\n#     Explanation: (2*(3-(4*5))) = -34 \n#     ((2*3)-(4*5)) = -14 \n#     ((2*(3-4))*5) = -10 \n#     (2*((3-4)*5)) = -10 \n#     (((2*3)-4)*5) = 10 ****\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "0dc92293037871762eb66cd07bd93b4d15c90d1f", "size": 937, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/241.different-ways-to-add-parentheses.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/unresolved/241.different-ways-to-add-parentheses.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/unresolved/241.different-ways-to-add-parentheses.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 21.2954545455, "max_line_length": 86, "alphanum_fraction": 0.5389541089, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.7531597575882247}}
{"text": "\nfunction getwraparoundDFTfreqs(N::Int, fs::T, ν_begin::T) where T\n\n    U0 = getDFTfreqrange(N, fs)\n    out, inds = wrapfreqrange(U0, ν_begin, fs)\n\n    return U0, out, inds\nend\n\n\n# Assumes U0 is sorted in ascending order.\nfunction wrapfreqrange(U0, ν_begin::T, fs::T) where T <: Real\n\n    N = length(U0)\n    ind = findfirst(xx->(xx>ν_begin), U0)\n\n    # TODO handle these exceptions with more grace.\n    @assert typeof(ind) == Int\n    @assert ind <= N\n\n    out = Vector{T}(undef, N)\n    #out[1:ind] = U0[1:ind] .+ fs\n    #out[ind+1:end] = U0[ind+1:end]\n\n    M = N-ind\n    out[1:M] = U0[ind+1:end]\n    out[M+1:end] = U0[1:ind] .+ fs\n\n    inds = collect(1:N)\n    inds[1:M] = collect(ind+1:N)\n    inds[M+1:end] = collect(1:ind)\n\n    return out, inds\nend\n\nfunction gettimerange(N::Int, fs::T) where T\n    Ts::T = 1/fs\n\n    return zero(T):Ts:(N-1)*Ts\n end\n\n function getDFTfreqrange(N::Int, fs::T)::LinRange{T} where T\n     a = zero(T)\n     b = fs-fs/N\n\n     return LinRange(a, b, N)\n end\n\n # case 1D.\nfunction computeDTFTch3eq29(h, u::T, Λ)::Complex{T} where T <: Real\n\n    # debug_array = zeros(Complex{T}, length(Λ))\n    # debug_array2 = zeros(Complex{T}, length(Λ))\n    # fs = 1/(Λ[2]-Λ[1])\n\n    running_sum = zero(T)\n    for i = 1:length(Λ)\n        x = Λ[i]\n\n        running_sum += h[i]*exp(-im*2*π*u*x)\n\n\n        # # debug.\n        # debug_array[i] = h[i]*exp(-im*2*π*u*x)\n        #\n        # #debug_array2[i] = h[i]*exp(-im*2*π*u*x +im*35*2*pi)\n        # debug_array2[i] = h[i]*exp(-im*2*π*(u+3*fs)*x)\n    end\n\n    #println(\"debug: norm(debug_array -debug_array2 ) = \", norm(debug_array -debug_array2 ) )\n    return running_sum\nend\n", "meta": {"hexsha": "e17f0c3b9f056e486ac11eb77314d91b60bb3ea5", "size": 1633, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DSP/dsp.jl", "max_stars_repo_name": "AI4DBiological-Systems/NMRCalibrate.jl", "max_stars_repo_head_hexsha": "5d955b10eb7a3f9bdfaf6c88990d06c84c1f0dcc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DSP/dsp.jl", "max_issues_repo_name": "AI4DBiological-Systems/NMRCalibrate.jl", "max_issues_repo_head_hexsha": "5d955b10eb7a3f9bdfaf6c88990d06c84c1f0dcc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DSP/dsp.jl", "max_forks_repo_name": "AI4DBiological-Systems/NMRCalibrate.jl", "max_forks_repo_head_hexsha": "5d955b10eb7a3f9bdfaf6c88990d06c84c1f0dcc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3698630137, "max_line_length": 93, "alphanum_fraction": 0.5731781996, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7531376641095064}}
{"text": "# # Differentiating a QP wrt a single variable\n\n#md # [![](https://img.shields.io/badge/show-github-579ACA.svg)](@__REPO_ROOT_URL__/docs/src/examples/matrix-inversion-manual.jl)\n\n# Consider the quadratic program\n\n# ```math\n# \\begin{split}\n# \\begin{array} {ll}\n# \\mbox{minimize} & \\frac{1}{2} x^T Q x + q^T x \\\\\n# \\mbox{subject to} & G x \\leq h, x \\in \\mathcal{R}^2 \\\\\n# \\end{array}\n# \\end{split}\n# ```\n\n# where `Q`, `q`, `G` are fixed and `h` is the single parameter.\n\n# In this example, we'll try to differentiate the QP wrt `h`, by finding its\n# jacobian by hand (using Eqn (6) of [QPTH article](https://arxiv.org/pdf/1703.00443.pdf))\n# and compare the results:\n# - Manual compuation\n# - Using JuMP and DiffOpt\n\n# Assuming \n# ```\n# Q = [[4, 1], [1, 2]]\n# q = [1, 1]\n# G = [1, 1]\n# ```\n# and begining with a starting value of `h=-1`\n\n# few values just for reference\n\n# | variable | optimal value | note |\n# |----|------|-----|\n# | x* | [-0.25; -0.75] | Primal optimal | \n# | 𝜆∗ | -0.75 | Dual optimal | \n\n\n# ## Finding Jacobian using matrix inversion\n# Lets formulate Eqn (6) of [QPTH article](https://arxiv.org/pdf/1703.00443.pdf) for our QP. If we assume `h` as the only parameter and `Q`,`q`,`G` as fixed problem data - also note that our QP doesn't involves `Ax=b` constraint - then Eqn (6) reduces to \n# ```math\n# \\begin{gather}\n#  \\begin{bmatrix} \n#      Q & g^T \\\\\n#      \\lambda^* G & G x^* - h\n#  \\end{bmatrix}\n#  \\begin{bmatrix} \n#      dx \\\\\n#      d \\lambda\n#  \\end{bmatrix}\n#  =\n#   \\begin{bmatrix}\n#    0 \\\\\n#    \\lambda^* dh\n#    \\end{bmatrix}\n# \\end{gather}\n# ```\n\n# Now to find the jacobians $$ \\frac{\\partial x}{\\partial h}, \\frac{\\partial \\lambda}{\\partial h}$$\n# we substitute `dh = I = [1]` and plug in values of `Q`,`q`,`G` to get\n# ```math\n# \\begin{gather}\n#  \\begin{bmatrix} \n#      4 & 1 & 1 \\\\\n#      1 & 2 & 1 \\\\\n#      -0.75 & -0.75 & 0\n#  \\end{bmatrix}\n#  \\begin{bmatrix} \n#      \\frac{\\partial x_1}{\\partial h} \\\\\n#      \\frac{\\partial x_2}{\\partial h} \\\\\n#      \\frac{\\partial \\lambda}{\\partial h}\n#  \\end{bmatrix}\n#  =\n#   \\begin{bmatrix}\n#    0 \\\\\n#    0 \\\\\n#    -0.75\n#    \\end{bmatrix}\n# \\end{gather}\n# ```\n\n# Upon solving using matrix inversion, the jacobian is\n# ```math\n# \\frac{\\partial x_1}{\\partial h} = 0.25, \\frac{\\partial x_2}{\\partial h} = 0.75, \\frac{\\partial \\lambda}{\\partial h} = -1.75 \n# ```\n\n# ## Finding Jacobian using JuMP and DiffOpt\n\nusing JuMP\nimport DiffOpt\nimport Ipopt\n\nn = 2 # variable dimension\nm = 1; # no of inequality constraints\n\nQ = [4. 1.;1. 2.]\nq = [1.; 1.]\nG = [1. 1.;]\nh = [-1.;]   # initial values set\n\n# Initialize empty model\n\nmodel = Model(() -> DiffOpt.diff_optimizer(Ipopt.Optimizer))\nset_silent(model)\n\n# Add the variables\n\n@variable(model, x[1:2])\n\n# Add the constraints.\n\n@constraint(\n    model,\n    cons[j in 1:1],\n    sum(G[j, i] * x[i] for i in 1:2)  <= h[j]\n);\n\n@objective(\n    model,\n    Min,\n    1/2 * sum(Q[j, i] * x[i] *x[j] for i in 1:2, j in 1:2) +\n    sum(q[i] * x[i] for i in 1:2)\n)\n\n# Solve problem\n\noptimize!(model)\n\n# primal solution\n\nvalue.(x)\n\n# dual solution\n\ndual.(cons)\n\n# set sentivitity\n\nMOI.set(\n    model,\n    DiffOpt.ForwardInConstraint(),\n    cons[1],\n    0.0 * index(x[1]) - 1.0,  # to indicate the direction vector to get directional derivatives\n)\n\n# Note that `0.0 * index(x[1])` is used to make its type `typeof(0.0 * index(x[1]) - 1.0) <: MOI.AbstractScalarFunction`.\n# To indicate different direction to get directional derivative, users should replace `0.0 * index(x[1]) - 1.0` as the form of `dG*x - dh`, where `dG` and `dh` correspond to the elements of direction vectors along `G` and `h` axes, respectively.\n\n# Compute derivatives\n\nDiffOpt.forward(model)\n\n# Query derivative\n\ndx = MOI.get.(\n    model,\n    DiffOpt.ForwardOutVariablePrimal(),\n    x,\n)\n\nusing Test                                  #src\n@test dx ≈ [0.25 ,0.75] atol=1e-4 rtol=1e-4 #src\n", "meta": {"hexsha": "d53b94cb590985d7e831321abd32aa89f8ec86aa", "size": 3866, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/matrix-inversion-manual.jl", "max_stars_repo_name": "guilhermebodin/DiffOpt.jl", "max_stars_repo_head_hexsha": "b2284192260f6a0fc8ce853eea47728ed1ab59d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/src/examples/matrix-inversion-manual.jl", "max_issues_repo_name": "guilhermebodin/DiffOpt.jl", "max_issues_repo_head_hexsha": "b2284192260f6a0fc8ce853eea47728ed1ab59d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/src/examples/matrix-inversion-manual.jl", "max_forks_repo_name": "guilhermebodin/DiffOpt.jl", "max_forks_repo_head_hexsha": "b2284192260f6a0fc8ce853eea47728ed1ab59d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5731707317, "max_line_length": 255, "alphanum_fraction": 0.5964821521, "num_tokens": 1373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199754937772, "lm_q2_score": 0.8991213813246444, "lm_q1q2_score": 0.7531220293910798}}
{"text": "@inline function two_sum(a::T, b::T) where T<:AbstractFloat\n    ab =  a + b\n    B  = ab - a\n    ε  = (a - (ab - B)) + (b - B)\n    return ab, ε\nend\n\n@inline function two_diff(a::T, b::T) where T<:AbstractFloat\n    ab =  a - b\n    B  = ab - a\n    ε  = (a - (ab - B)) + (b - B)\n    return ab, ε\nend\n\n\n\"\"\"\n    fast_two_sum(x, y)::(a, b)\n\n{ ab  =  a + b,  ε  = (a - ab) + b }\n\n__unchecked precondition__: abs(a) >= abs(b).\n\"\"\"\n@inline function fast_two_sum(a::T, b::T) where T<:AbstractFloat\n     ab =  a + b\n     B  = ab - a\n     ε  =  b - B\n     return ab, ε\nend\n\n\"\"\"\n    fast_two_diff(x, y)::(a, b)\n\n{ ab  =  a - b,  ε  = (a - ab) + b }\n\n__unchecked precondition__: abs(a) >= abs(b).\n\"\"\"\n@inline function fast_two_diff(a::T, b::T) where T<:AbstractFloat \n     ab =  a - b\n     B  = ab - a\n     ε  =  B - b\n     return ab, ε\nend\n\n@inline function two_prod(a::T, b::T) where T<:AbstractFloat\n    ab =  a * b\n    ε  = fma(a, b, -ab)\n    return ab, ε\nend\n\n#=\n   Separate an IEEEFloat (fp) into two parts, (hi, lo), assuring\n      `fp === hi + lo`, `hi === fp - lo`, `lo === fp - hi`, and\n      `ulp(abs(hi)) > ufp(abs(lo))`.\n\n      ulp, ufp are acronyms for u[nit in the] {l[ast], f[irst]} p[lace]\n\n      ulp(fp) = eps(fp)/2\n      ufp(fp) = ldexp(0.5, exponent(fp)\n\n   ref\n       A floating-point technique for extending the available precision.\n       T. J. Dekker.\n       Numer. Math., 18:224–242, 1971\n=#\n\nsplitter(::Type{Float64}) =\n    Float64(one(Int64) + one(Int64) << (cld(precision(Float64),2)-1))\nsplitter(::Type{Float32}) = \n    Float32(one(Int32) + one(Int32) << (cld(precision(Float32),2)-1))\nsplitter(::Type{Float16}) = \n    Float16(one(Int16) + one(Int16) << (cld(precision(Float16),2)-1))\n\nsplitmax(::Type{Float64}) = realmax(Float64) / splitter(Float64)\nsplitmax(::Type{Float32}) = realmax(Float32) / splitter(Float32)\nsplitmax(::Type{Float16}) = realmax(Float16) / splitter(Float16)\n\n# Veldkamp splitting of a floating point value\n@inline function splitting(x::T) where T<:AbstractFloat\n    (!isfinite(x) || abs(x) > splitmax(T)) && throw(OverflowError(\"$x overflows\"))\n    z   = x * splitter(T)\n    zₕᵢ = z - (z - x)\n    zₗₒ = x - zₕᵢ\n    return zₕᵢ, zₗₒ\nend\n\n# Rump splitting\n#    In extractscalar, a floating-point number fp is split relative to p2,\n#    a fixed power of 2.\nfunction extractscalar(fp, p2=2^27)\n    hi = (p2 + fp) - p2\n    lo = fp - hi\n    return hi, lo\nend\n\n#=\n    splitfp(fp) =?= extractscalar(2^(?+exponent(fp)), fp)\n\n=#\n\nfor (U,F) in ((:UInt64, :Float64), (:UInt32, :Float32), (:UInt16, :Float16))\n  @eval begin\n    @inline function ufp(x::$F)\n        u = reinterpret($U, x)\n        u = (u >> (precision($F)-1)) << (precision($F)-1)\n        return reinterpret($F, u)\n    end\n  end\nend\n\nconst Float64ulp = inv(ldexp(1.0, precision(Float64)))\nconst Float32ulp = inv(ldexp(1.0, precision(Float32)))\nconst Float16ulp = inv(ldexp(1.0, precision(Float16)))\n\n@inline ulp(x::Float64) = ufp(x) * Float64ulp\n@inline ulp(x::Float32) = ufp(x) * Float32ulp\n@inline ulp(x::Float16) = ufp(x) * Float16ulp\n\nconst Float64eps = inv(ldexp(1.0, precision(Float64)-1))\nconst Float32eps = inv(ldexp(1.0, precision(Float32)-1))\nconst Float16eps = inv(ldexp(1.0, precision(Float16)-1))\n\n@inline epsi(x::Float64) = ufp(x) * Float64eps\n@inline epsi(x::Float32) = ufp(x) * Float32eps\n@inline epsi(x::Float16) = ufp(x) * Float16eps\n", "meta": {"hexsha": "52a3919f7b063328014b6d607385b83f35a130a0", "size": 3339, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/twoarith.jl", "max_stars_repo_name": "JuliaDocsForks/AccurateArithmetic.jl", "max_stars_repo_head_hexsha": "7bf3369d183559a11f61ebf4dc0ebb283dd3e4c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/twoarith.jl", "max_issues_repo_name": "JuliaDocsForks/AccurateArithmetic.jl", "max_issues_repo_head_hexsha": "7bf3369d183559a11f61ebf4dc0ebb283dd3e4c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/twoarith.jl", "max_forks_repo_name": "JuliaDocsForks/AccurateArithmetic.jl", "max_forks_repo_head_hexsha": "7bf3369d183559a11f61ebf4dc0ebb283dd3e4c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.712, "max_line_length": 82, "alphanum_fraction": 0.5914944594, "num_tokens": 1212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7531220163867456}}
{"text": "function fastModularExponentiation(m, e, n::Integer)\n    n > 0  || error(\"n must be positive\")\n    e >= 0 || error(\"e must be non-negative\")\n    r = 1\n    while e > 0\n        if (e & 1) > 0\n            r = (r*m)%n\n        end\n        e >>= 1\n        m = (m^2)%n\n    end\n    return r>0 ? r : r+n\nend", "meta": {"hexsha": "b0bdfa1d58f2f8b09bd892faab559eb2b0e80c5e", "size": 298, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Utility Functions/Algorithms/FME.jl", "max_stars_repo_name": "Anirban166/RSA-Cryptosystem", "max_stars_repo_head_hexsha": "2283bbeab811fb4cacf86b55c9f6e7247610bf74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 65, "max_stars_repo_stars_event_min_datetime": "2019-05-22T16:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-06T09:37:53.000Z", "max_issues_repo_path": "Utility Functions/Algorithms/FME.jl", "max_issues_repo_name": "Anirban166/RSA-Cryptosystem", "max_issues_repo_head_hexsha": "2283bbeab811fb4cacf86b55c9f6e7247610bf74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-03T05:13:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-03T05:14:03.000Z", "max_forks_repo_path": "Utility Functions/Algorithms/FME.jl", "max_forks_repo_name": "Anirban166/RSA-Cryptosystem", "max_forks_repo_head_hexsha": "2283bbeab811fb4cacf86b55c9f6e7247610bf74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-05-22T16:34:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-28T14:26:47.000Z", "avg_line_length": 22.9230769231, "max_line_length": 52, "alphanum_fraction": 0.4496644295, "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7531220114164414}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,jl:hydrogen\n#     text_representation:\n#       extension: .jl\n#       format_name: hydrogen\n#       format_version: '1.3'\n#       jupytext_version: 1.10.3\n#   kernelspec:\n#     display_name: Julia 1.6.3\n#     language: julia\n#     name: julia-1.6\n# ---\n\n# %% [markdown]\n# https://twitter.com/genkuroki/status/1459220790444920833\n\n# %%\nusing Distributions, StatsPlots\n\n# %%\nmixnormal = MixtureModel([Normal(0, 1), Normal(1, 2)], [1/3, 2/3])\n\n# %%\nX = rand(mixnormal, 10^5)\nf(x) = (1/3)*pdf(Normal(0, 1), x) + (2/3)*pdf(Normal(1, 2), x)\n\nhistogram(X; norm=true, alpha=0.3, label=\"sample of mixnormal\")\nplot!(f; label=\"(1/3)N(x|0,1)+(2/3)N(x|1,2))\", lw=2)\n\n# %%\n", "meta": {"hexsha": "75406b1f647ea3333ebb13c5131e3fde9bb7d5bb", "size": 711, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0024/mixed normal dist.jl", "max_stars_repo_name": "genkuroki/public", "max_stars_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-06-06T00:33:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T06:56:08.000Z", "max_issues_repo_path": "0024/mixed normal dist.jl", "max_issues_repo_name": "genkuroki/public", "max_issues_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0024/mixed normal dist.jl", "max_forks_repo_name": "genkuroki/public", "max_forks_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-02T11:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T11:46:05.000Z", "avg_line_length": 21.5454545455, "max_line_length": 66, "alphanum_fraction": 0.5921237693, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7531220109745349}}
{"text": "\"\"\"\n    eom_var1(x, p, n) -> Function\n\nEquations of motion for a vector autoregressive system where X₁ → X₂ → X₃.\n\"\"\"\nfunction eom_var1(x, p, n)\n    σ₁, σ₂, σ₃ = p[1], p[2], p[3]\n    x₁, x₂, x₃ = x[1], x[2], x[3]\n    θ = rand(Normal(0, σ₁))\n    η = rand(Normal(0, σ₂))\n    ϵ = rand(Normal(0, σ₃))\n\n    dx₁ = θ\n    dx₂ = x₁ * η\n    dx₃ = 0.5*x₃ * x₂ + ϵ\n    return SVector{3}(dx₁, dx₂, dx₃)\nend\n\nfunction var1(uᵢ, σ₁, σ₂, σ₃)\n    p = [σ₁, σ₂, σ₃]\n    DiscreteDynamicalSystem(eom_var1, uᵢ, p)\nend\n\n\"\"\"\n    var1(x, p, n) -> DiscreteDynamicalSystem\n\nInitialise a discrete vector autoregressive system where X₁ → X₂ → X₃.\n\"\"\"\nvar1(;uᵢ = rand(3), σ₁ = 1.0, σ₂ = 0.2, σ₃ = 0.3) = var1(uᵢ, σ₁, σ₂, σ₃)\n", "meta": {"hexsha": "9c5a138fcf63db057f4a2c5d331ef7461d98d5f6", "size": 694, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/systems/discretemaps/var1.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/CausalityTools.jl-5520caf5-2dd7-5c5d-bfcb-a00e56ac49f7", "max_stars_repo_head_hexsha": "93935b3bc73738c52b004e9cf23d6f6a4778982c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2020-06-11T01:51:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T18:39:43.000Z", "max_issues_repo_path": "src/systems/discretemaps/var1.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/CausalityTools.jl-5520caf5-2dd7-5c5d-bfcb-a00e56ac49f7", "max_issues_repo_head_hexsha": "93935b3bc73738c52b004e9cf23d6f6a4778982c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2020-12-21T02:52:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T10:40:08.000Z", "max_forks_repo_path": "src/systems/discretemaps/var1.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/CausalityTools.jl-5520caf5-2dd7-5c5d-bfcb-a00e56ac49f7", "max_forks_repo_head_hexsha": "93935b3bc73738c52b004e9cf23d6f6a4778982c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-09-27T08:56:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T15:05:51.000Z", "avg_line_length": 23.1333333333, "max_line_length": 74, "alphanum_fraction": 0.5662824207, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7530558310530489}}
{"text": "# Correlation Functions\n# #+HTML: <details><summary>Source</summary>\n# #+HTML: <p>\n\n# [[file:~/.julia/dev/MatrixProductStates/README.org::*Correlation%20Functions][Correlation Functions:1]]\n\"\"\"\n    two_point_correlator((i, op_i)::Pair{Int, Matrix}, (j, op_j)::Pair{Int, Matrix}, L)\n\nCreate an MPO on `L` sites (with bond dimension 1) representing identity operators everywhere except\nsites `i` and `j` where `op_i` and `op_j` are inserted instead. ie.\n\n    𝟙 ⊗ 𝟙 ⊗ ... ⊗ op_i ⊗ 𝟙 ⊗ ... ⊗ op_j ⊗ 𝟙 ⊗ ... ⊗ 𝟙\n\nexample: spin-spin correlation function\n\nwe can construct ⟨σᶻᵢσᶻⱼ⟩ on a 12 site lattice as\n    σᶻ = [1 0; 0 -1]\n    two_point_correlator(i=>σᶻ, j=>σᶻ, 12)  \n\"\"\"\nfunction two_point_correlator((i, op_i), (j, op_j), L)\n    d = size(op_i)[1]\n    @assert (size(op_i) == (d, d)) && (size(op_j) == (d, d))\n    @assert i in 1:L\n    @assert j in 1:L\n    id = diagm(0 => ones(Complex{Float64}, d))\n\n    op_i_tnsr = reshape(convert(Matrix{Complex{Float64}}, op_i), 1, 1, d, d) \n    op_j_tnsr = reshape(convert(Matrix{Complex{Float64}}, op_j), 1, 1, d, d)\n    id_tnsr   = reshape(id, 1, 1, d, d)\n\n    tensors = map(1:L) do l\n        O_tnsr = (l == i ? op_i_tnsr : \n                  l == j ? op_j_tnsr : \n                  id_tnsr)\n    end \n    MPO{L,Complex{Float64}}(tensors)\nend\n# Correlation Functions:1 ends here\n", "meta": {"hexsha": "3a6e3463d92d14c135e86ea6b4932757c8933be5", "size": 1314, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/correlation.jl", "max_stars_repo_name": "qcancam/MatrixProductStates.jl", "max_stars_repo_head_hexsha": "122ac09fe72eaa7e19b0fd08036375c3419b8b4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2019-04-08T23:15:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T07:01:38.000Z", "max_issues_repo_path": "src/correlation.jl", "max_issues_repo_name": "qcancam/MatrixProductStates.jl", "max_issues_repo_head_hexsha": "122ac09fe72eaa7e19b0fd08036375c3419b8b4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-01-10T09:00:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-10T09:08:27.000Z", "max_forks_repo_path": "src/correlation.jl", "max_forks_repo_name": "qcancam/MatrixProductStates.jl", "max_forks_repo_head_hexsha": "122ac09fe72eaa7e19b0fd08036375c3419b8b4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-09-25T08:21:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T14:31:44.000Z", "avg_line_length": 33.6923076923, "max_line_length": 105, "alphanum_fraction": 0.6080669711, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.753055825564451}}
{"text": "# ## Contour plot\n# ### Contour plot\n\n#md # ![FILE_NAME.png](images/FILE_NAME.png)\n\nf(x,y) = x^2 + y^2\nx = repeat(range(0, stop=2, length=50), 1, 50)\ny = repeat(range(0, stop=2, length=50), 1, 50)'\n\ncontour( f.(x, y) )\n", "meta": {"hexsha": "3f765bed5986bd42aa109b39d82aaf2713cf44bc", "size": 219, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "site_generator/contour_plot.jl", "max_stars_repo_name": "goropikari/PlotsGallery.jl", "max_stars_repo_head_hexsha": "9a3c901adfef097f86baa029af4b529b8b6cc302", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2018-12-20T12:33:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:46:34.000Z", "max_issues_repo_path": "site_generator/contour_plot.jl", "max_issues_repo_name": "goropikari/JuliaPlotsGallery.jl", "max_issues_repo_head_hexsha": "367fca5dbca42a90d1f28e3b5aae1652e3ce4f3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-08T15:39:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T11:01:09.000Z", "max_forks_repo_path": "site_generator/contour_plot.jl", "max_forks_repo_name": "goropikari/JuliaPlotsGallery.jl", "max_forks_repo_head_hexsha": "367fca5dbca42a90d1f28e3b5aae1652e3ce4f3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-03-19T22:21:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T11:42:32.000Z", "avg_line_length": 19.9090909091, "max_line_length": 47, "alphanum_fraction": 0.5890410959, "num_tokens": 92, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.8740772286044094, "lm_q1q2_score": 0.7530509366511884}}
{"text": "function lin_interp(grid, vals)\n    function func(x::Real)\n        if x <= grid[1]\n            index_1 = 1\n            index_2 = 2\n        elseif x >= grid[length(grid)]\n            index_1 = length(grid) - 1\n            index_2 = length(grid)\n        else\n            index_1 = searchsortedfirst(grid, x)\n            index_2 = searchsortedlast(grid, x)\n        end\n        x_1 = grid[index_1]\n        x_2 = grid[index_2]\n        y_1 = vals[index_1]\n        y_2 = vals[index_2]\n        \n        y = ((y_2- y_1)/(x_2 - x_1))*(x - x_1) + y_1\n        return y\n    end\n    \n    function func{T<:Real}(x::AbstractVector{T})\n        y = zeros(length(x))\n        for i in 1:length(x)\n            y[i] = func(x[i])\n        end\n        return y\n    end\n    \n    return func\nend", "meta": {"hexsha": "191f2949110ed39519a6542a20db5e086d08232e", "size": 768, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear_interpolation.jl", "max_stars_repo_name": "NlGG/Interpolation.jl", "max_stars_repo_head_hexsha": "c653a4ebe6b0dfb0f815168af49fc64f6785635f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_interpolation.jl", "max_issues_repo_name": "NlGG/Interpolation.jl", "max_issues_repo_head_hexsha": "c653a4ebe6b0dfb0f815168af49fc64f6785635f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_interpolation.jl", "max_forks_repo_name": "NlGG/Interpolation.jl", "max_forks_repo_head_hexsha": "c653a4ebe6b0dfb0f815168af49fc64f6785635f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7741935484, "max_line_length": 52, "alphanum_fraction": 0.4778645833, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741214369554, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7530387284770238}}
{"text": "\r\n# .................... cubic b-spline functions ...............................\r\n\r\n# n / 0 == 0\r\n#\r\nfunction zero_divide(a, b)\r\n    x = a / b\r\n    return ifelse(isfinite(x), x, 0)\r\nend\r\n\r\n\r\n# uniform-knot p:degree n:number_of_points\r\n#\r\nfunction knot(p, n)\r\n    base = [ifelse(k <= p, 0.0, 1.0) for k in (0:p + n)]\r\n    if n - p == 1\r\n        return base\r\n    else\r\n        for k in 0:n-p\r\n            base[p + k + 1] = k / (n - p)\r\n        end\r\n    end\r\n    return base\r\nend\r\n\r\n\r\n# b-spline basis p:degree i:number u:parameter k:knot\r\n#\r\nfunction bbasis(p, i, u, k)\r\n    if p == 0\r\n        return ifelse(k[i] <= u <= k[i+1], 1, 0)\r\n    else\r\n        m0 = zero_divide(u - k[i], k[i+p] - k[i])\r\n        m1 = zero_divide(k[i+p+1] - u, k[i+p+1] - k[i+1])\r\n        return m0 * bbasis(p-1, i, u, k) + m1 * bbasis(p-1, i+1, u, k)\r\n    end\r\nend\r\n\r\n\r\n# b-spline basis first-derivative\r\n#\r\nfunction bbasis_fd(p, i, u, k)\r\n    return zero_divide(p, k[i+p] - k[i]) * bbasis(p-1, i, u, k) -\r\n        zero_divide(p, k[i+p+1] - k[i+1]) * bbasis(p-1, i+1, u, k)\r\nend\r\n\r\n\r\n# b-spline curve, points: as columns, t: 1d vector\r\n#\r\nfunction bcurve(points, u, bas=bbasis)\r\n    knt = Ref(knot(3, size(points, 2)))\r\n    tmp = zeros(size(points, 1), length(u), size(points, 2))\r\n    for n in axes(points, 2)\r\n        tmp[:,:,n] = points[:,n] .* bas.(3, n, u, knt)'\r\n    end\r\n    return dropdims(sum(tmp, dims=3), dims=3)\r\nend\r\n\r\n\r\n# b-spline surface, points: size(cp_u, cp_v, 3), uv: size(nu, nv, 2) \r\n#\r\nfunction bsurface(points, uv, bu=bbasis, bv=bbasis)\r\n    ku, kv = knot.(3, size(points))     \r\n    uv_tmp = zeros(size(uv, 1), size(uv, 2), size(points, 3))\r\n    \r\n    for I in CartesianIndices(uv[:,:,1])\r\n        for J in CartesianIndices(points[:,:,1])\r\n            uv_tmp[I,:] += points[J,:] .* \r\n                bu(3, J[1], uv[I, 1], ku) .* \r\n                bv(3, J[2], uv[I, 2], kv)\r\n        end\r\n    end\r\n    return uv_tmp\r\nend\r\n\r\n\r\nfunction mgrid(nu, nv, a=0:1, b=0:1)\r\n    uv = zeros(nu, nv, 2)\r\n    uv[:,:,1] .= first(a) : ((last(a)-first(a)) / (nu-1)) : last(a)\r\n    uv[:,:,2] .= (first(b) : ((last(b)-first(b)) / (nv-1)) : last(b))'\r\n    return uv\r\nend\r\n\r\n\r\nfunction rnd_grid(x, y)\r\n    uv = mgrid(x, y, 0:x, 0:y)\r\n    az = rand(Float32, x, y)\r\n    return cat(uv, az, dims = 3)\r\nend", "meta": {"hexsha": "529434fa2854ea4f6f1fe26bb14af134362d094d", "size": 2277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/b-spline.jl", "max_stars_repo_name": "zaika-generative/ShapeFactory", "max_stars_repo_head_hexsha": "5bc27e27c59804a2719e91499d88daec8f475c20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-11T13:44:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-11T13:44:47.000Z", "max_issues_repo_path": "examples/b-spline.jl", "max_issues_repo_name": "zaika-generative/ShapeFactory", "max_issues_repo_head_hexsha": "5bc27e27c59804a2719e91499d88daec8f475c20", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-01-08T19:28:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-08T19:28:05.000Z", "max_forks_repo_path": "examples/b-spline.jl", "max_forks_repo_name": "zaika-generative/ShapeFactory", "max_forks_repo_head_hexsha": "5bc27e27c59804a2719e91499d88daec8f475c20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-04T09:21:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-04T09:21:48.000Z", "avg_line_length": 25.5842696629, "max_line_length": 80, "alphanum_fraction": 0.487483531, "num_tokens": 821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224333, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7530387233324433}}
{"text": "\"\"\"\n    SqExponentialKernel()\n\nSquared exponential kernel.\n\n# Definition\n\nFor inputs ``x, x' \\\\in \\\\mathbb{R}^d``, the squared exponential kernel is defined as\n```math\nk(x, x') = \\\\exp\\\\bigg(- \\\\frac{\\\\|x - x'\\\\|_2^2}{2}\\\\bigg).\n```\n\nSee also: [`GammaExponentialKernel`](@ref)\n\"\"\"\nstruct SqExponentialKernel <: SimpleKernel end\n\nkappa(::SqExponentialKernel, d²::Real) = exp(-d² / 2)\n\nmetric(::SqExponentialKernel) = SqEuclidean()\n\niskroncompatible(::SqExponentialKernel) = true\n\nBase.show(io::IO, ::SqExponentialKernel) = print(io, \"Squared Exponential Kernel\")\n\n## Aliases ##\n\n\"\"\"\n    RBFKernel()\n\nAlias of [`SqExponentialKernel`](@ref).\n\"\"\"\nconst RBFKernel = SqExponentialKernel\n\n\"\"\"\n    GaussianKernel()\n\nAlias of [`SqExponentialKernel`](@ref).\n\"\"\"\nconst GaussianKernel = SqExponentialKernel\n\n\"\"\"\n    SEKernel()\n\nAlias of [`SqExponentialKernel`](@ref).\n\"\"\"\nconst SEKernel = SqExponentialKernel\n\n\"\"\"\n    ExponentialKernel()\n\nExponential kernel.\n\n# Definition\n\nFor inputs ``x, x' \\\\in \\\\mathbb{R}^d``, the exponential kernel is defined as\n```math\nk(x, x') = \\\\exp\\\\big(- \\\\|x - x'\\\\|_2\\\\big).\n```\n\nSee also: [`GammaExponentialKernel`](@ref)\n\"\"\"\nstruct ExponentialKernel <: SimpleKernel end\n\nkappa(::ExponentialKernel, d::Real) = exp(-d)\n\nmetric(::ExponentialKernel) = Euclidean()\n\niskroncompatible(::ExponentialKernel) = true\n\nBase.show(io::IO, ::ExponentialKernel) = print(io, \"Exponential Kernel\")\n\n## Aliases ##\n\n\"\"\"\n    LaplacianKernel()\n\nAlias of [`ExponentialKernel`](@ref).\n\"\"\"\nconst LaplacianKernel = ExponentialKernel\n\n\"\"\"\n    Matern12Kernel()\n\nAlias of [`ExponentialKernel`](@ref).\n\"\"\"\nconst Matern12Kernel = ExponentialKernel\n\n\"\"\"\n    GammaExponentialKernel(; γ::Real=2.0)\n\nγ-exponential kernel with parameter `γ`.\n\n# Definition\n\nFor inputs ``x, x' \\\\in \\\\mathbb{R}^d``, the γ-exponential kernel[^RW] with parameter\n``\\\\gamma \\\\in (0, 2]`` is defined as\n```math\nk(x, x'; \\\\gamma) = \\\\exp\\\\big(- \\\\|x - x'\\\\|_2^{\\\\gamma}\\\\big).\n```\n\nSee also: [`ExponentialKernel`](@ref), [`SqExponentialKernel`](@ref)\n\n[^RW]: C. E. Rasmussen & C. K. I. Williams (2006). Gaussian Processes for Machine Learning.\n\"\"\"\nstruct GammaExponentialKernel{Tγ<:Real} <: SimpleKernel\n    γ::Vector{Tγ}\n    function GammaExponentialKernel(; gamma::Real=2.0, γ::Real=gamma)\n        @check_args(GammaExponentialKernel, γ, zero(γ) < γ ≤ 2, \"γ ∈ (0, 2]\")\n        return new{typeof(γ)}([γ])\n    end\nend\n\n@functor GammaExponentialKernel\n\nkappa(κ::GammaExponentialKernel, d::Real) = exp(-d^first(κ.γ))\n\nmetric(::GammaExponentialKernel) = Euclidean()\n\niskroncompatible(::GammaExponentialKernel) = true\n\nfunction Base.show(io::IO, κ::GammaExponentialKernel)\n    return print(io, \"Gamma Exponential Kernel (γ = \", first(κ.γ), \")\")\nend\n", "meta": {"hexsha": "e0546a9890b0857c61377ae65949b98303186c90", "size": 2706, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basekernels/exponential.jl", "max_stars_repo_name": "simonschoelly/KernelFunctions.jl", "max_stars_repo_head_hexsha": "600df21de4465c50a0bb73be344a9bf95e6212f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basekernels/exponential.jl", "max_issues_repo_name": "simonschoelly/KernelFunctions.jl", "max_issues_repo_head_hexsha": "600df21de4465c50a0bb73be344a9bf95e6212f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basekernels/exponential.jl", "max_forks_repo_name": "simonschoelly/KernelFunctions.jl", "max_forks_repo_head_hexsha": "600df21de4465c50a0bb73be344a9bf95e6212f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8225806452, "max_line_length": 91, "alphanum_fraction": 0.6718403548, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7530071368527111}}
{"text": "\"\"\"\n    Link\n\nAn abstract type whose subtypes determine methods for [`linkfun`](@ref), [`linkinv`](@ref),\n[`mueta`](@ref), and [`inverselink`](@ref).\n\"\"\"\nabstract type Link end\n\n# Make links broadcast like a scalar\nBase.Broadcast.broadcastable(l::Link) = Ref(l)\n\n\"\"\"\n    Link01\n\nAn abstract subtype of [`Link`](@ref) which are links defined on (0, 1)\n\"\"\"\nabstract type Link01 <: Link end\n\n\"\"\"\n    CauchitLink\n\nA [`Link01`](@ref) corresponding to the standard Cauchy distribution,\n[`Distributions.Cauchy`](https://juliastats.github.io/Distributions.jl/stable/univariate.html#Distributions.Cauchy).\n\"\"\"\nmutable struct CauchitLink <: Link01 end\n\n\"\"\"\n    CloglogLink\n\nA [`Link01`](@ref) corresponding to the extreme value (or log-Wiebull) distribution.  The\nlink is the complementary log-log transformation, `log(1 - log(-μ))`.\n\"\"\"\nmutable struct CloglogLink  <: Link01 end\n\n\"\"\"\n    IdentityLink\n\nThe canonical [`Link`](@ref) for the `Normal` distribution, defined as `η = μ`.\n\"\"\"\nmutable struct IdentityLink <: Link end\n\n\"\"\"\n    InverseLink\n\nThe canonical [`Link`](@ref) for [`Distributions.Gamma`](https://juliastats.github.io/Distributions.jl/stable/univariate.html#Distributions.Gamma) distribution, defined as `η = inv(μ)`.\n\"\"\"\nmutable struct InverseLink  <: Link end\n\n\"\"\"\n    InverseSquareLink\n\nThe canonical [`Link`](@ref) for [`Distributions.InverseGaussian`](https://juliastats.github.io/Distributions.jl/stable/univariate.html#Distributions.InverseGaussian) distribution, defined as `η = inv(abs2(μ))`.\n\"\"\"\nmutable struct InverseSquareLink  <: Link end\n\n\"\"\"\n    LogitLink\n\nThe canonical [`Link01`](@ref) for [`Distributions.Bernoulli`](https://juliastats.github.io/Distributions.jl/stable/univariate.html#Distributions.Bernoulli) and [`Distributions.Binomial`](https://juliastats.github.io/Distributions.jl/stable/univariate.html#Distributions.Binomial).\nThe inverse link, [`linkinv`](@ref), is the c.d.f. of the standard logistic distribution,\n[`Distributions.Logistic`](https://juliastats.github.io/Distributions.jl/stable/univariate.html#Distributions.Logistic).\n\"\"\"\nmutable struct LogitLink <: Link01 end\n\n\"\"\"\n    LogLink\n\nThe canonical [`Link`](@ref) for [`Distributions.Poisson`](https://juliastats.github.io/Distributions.jl/stable/univariate.html#Distributions.Poisson), defined as `η = log(μ)`.\n\"\"\"\nmutable struct LogLink <: Link end\n\n\"\"\"\n    NegativeBinomialLink\n\nThe canonical [`Link`](@ref) for [`Distributions.NegativeBinomial`](https://juliastats.github.io/Distributions.jl/stable/univariate.html#Distributions.NegativeBinomial) distribution, defined as `η = log(μ/(μ+θ))`.\nThe shape parameter θ has to be fixed for the distribution to belong to the exponential family.\n\"\"\"\nmutable struct NegativeBinomialLink  <: Link\n    θ::Float64\nend\n\n\"\"\"\n    ProbitLink\n\nA [`Link01`](@ref) whose [`linkinv`](@ref) is the c.d.f. of the standard normal\ndistribution, [`Distributions.Normal()`](https://juliastats.github.io/Distributions.jl/stable/univariate.html#Distributions.Normal).\n\"\"\"\nmutable struct ProbitLink <: Link01 end\n\n\"\"\"\n    SqrtLink\n\nA [`Link`](@ref) defined as `η = √μ`\n\"\"\"\nmutable struct SqrtLink <: Link end\n\n\"\"\"\n    linkfun(L::Link, μ)\n\nReturn `η`, the value of the linear predictor for link `L` at mean `μ`.\n\n# Examples\n```jldoctest\njulia> μ = inv(10):inv(5):1\n0.1:0.2:0.9\n\njulia> show(linkfun.(LogitLink(), μ))\n[-2.19722, -0.847298, 0.0, 0.847298, 2.19722]\n\n```\n\"\"\"\nfunction linkfun end\n\n\"\"\"\n    linkinv(L::Link, η)\n\nReturn `μ`, the mean value, for link `L` at linear predictor value `η`.\n\n# Examples\n```jldoctest\njulia> μ = 0.1:0.2:1\n0.1:0.2:0.9\n\njulia> η = logit.(μ);\n\njulia> linkinv.(LogitLink(), η) ≈ μ\ntrue\n```\n\"\"\"\nfunction linkinv end\n\n\"\"\"\n    mueta(L::Link, η)\n\nReturn the derivative of [`linkinv`](@ref), `dμ/dη`, for link `L` at linear predictor value `η`.\n\n# Examples\n```jldoctest\njulia> mueta(LogitLink(), 0.0)\n0.25\n\njulia> mueta(CloglogLink(), 0.0) ≈ 0.36787944117144233\ntrue\n\njulia> mueta(LogLink(), 2.0) ≈ 7.38905609893065\ntrue\n```\n\"\"\"\nfunction mueta end\n\n\"\"\"\n    inverselink(L::Link, η)\n\nReturn a 3-tuple of the inverse link, the derivative of the inverse link, and when appropriate, the variance function `μ*(1 - μ)`.\n\nThe variance function is returned as NaN unless the range of μ is (0, 1)\n\n# Examples\n```jldoctest\njulia> inverselink(LogitLink(), 0.0)\n(0.5, 0.25, 0.25)\n\njulia> μ, oneminusμ, variance = inverselink(CloglogLink(), 0.0);\n\njulia> μ + oneminusμ ≈ 1\ntrue\n\njulia> μ*(1 - μ) ≈ variance\ntrue\n\njulia> isnan(last(inverselink(LogLink(), 2.0)))\ntrue\n```\n\"\"\"\nfunction inverselink end\n\n\"\"\"\n    canonicallink(D::Distribution)\n\nReturn the canonical link for distribution `D`, which must be in the exponential family.\n\n# Examples\n```jldoctest\njulia> canonicallink(Bernoulli())\nLogitLink()\n```\n\"\"\"\nfunction canonicallink end\n\nlinkfun(::CauchitLink, μ) = tan(pi * (μ - oftype(μ, 1/2)))\nlinkinv(::CauchitLink, η) = oftype(η, 1/2) + atan(η) / pi\nmueta(::CauchitLink, η) = one(η) / (pi * (one(η) + abs2(η)))\nfunction inverselink(::CauchitLink, η)\n    μlower = atan(-abs(η)) / π\n    μlower += oftype(μlower, 1/2)\n    η > 0 ? 1 - μlower : μlower, inv(π * (1 + abs2(η))), μlower * (1 - μlower)\nend\n\nlinkfun(::CloglogLink, μ) = log(-log1p(-μ))\nfunction linkinv(::CloglogLink, η::T) where T<:Real\n    clamp(-expm1(-exp(η)), eps(T), one(T) - eps(T))\nend\nfunction mueta(::CloglogLink, η::T) where T<:Real\n    max(eps(T), exp(η) * exp(-exp(η)))\nend\nfunction inverselink(::CloglogLink, η)\n    expη = exp(η)\n    μ = -expm1(-expη)\n    omμ = exp(-expη)   # the complement, 1 - μ\n    μ, max(floatmin(μ), expη * omμ), max(floatmin(μ), μ * omμ)\nend\n\nlinkfun(::IdentityLink, μ) = μ\nlinkinv(::IdentityLink, η) = η\nmueta(::IdentityLink, η) = one(η)\ninverselink(::IdentityLink, η) = η, one(η), oftype(η, NaN)\n\nlinkfun(::InverseLink, μ) = inv(μ)\nlinkinv(::InverseLink, η) = inv(η)\nmueta(::InverseLink, η) = -inv(abs2(η))\nfunction inverselink(::InverseLink, η)\n    μ = inv(η)\n    μ, -abs2(μ), oftype(μ, NaN)\nend\n\nlinkfun(::InverseSquareLink, μ) = inv(abs2(μ))\nlinkinv(::InverseSquareLink, η) = inv(sqrt(η))\nmueta(::InverseSquareLink, η) = -inv(2η*sqrt(η))\nfunction inverselink(::InverseSquareLink, η)\n    μ = inv(sqrt(η))\n    μ, -μ / (2η), oftype(μ, NaN)\nend\n\nlinkfun(::LogitLink, μ) = logit(μ)\nlinkinv(::LogitLink, η) = logistic(η)\nfunction mueta(::LogitLink, η)\n    expabs = exp(-abs(η))\n    denom = 1 + expabs\n    (expabs / denom) / denom\nend\nfunction inverselink(::LogitLink, η)\n    expabs = exp(-abs(η))\n    opexpabs = 1 + expabs\n    deriv = (expabs / opexpabs) / opexpabs\n    η ≤ 0 ? expabs / opexpabs : inv(opexpabs), deriv, deriv\nend\n\nlinkfun(::LogLink, μ) = log(μ)\nlinkinv(::LogLink, η) = exp(η)\nmueta(::LogLink, η) = exp(η)\nfunction inverselink(::LogLink, η)\n    μ = exp(η)\n    μ, μ, oftype(μ, NaN)\nend\n\nlinkfun(nbl::NegativeBinomialLink, μ) = log(μ / (μ + nbl.θ))\nlinkinv(nbl::NegativeBinomialLink, η) = ℯ^η * nbl.θ / (1-ℯ^η)\nmueta(nbl::NegativeBinomialLink, η) = ℯ^η * nbl.θ / (1-ℯ^η)\nfunction inverselink(nbl::NegativeBinomialLink, η)\n    μ = ℯ^η * nbl.θ / (1-ℯ^η)\n    deriv = μ * (1 + μ / nbl.θ)\n    μ, deriv, oftype(μ, NaN)\nend\n\nlinkfun(::ProbitLink, μ) = -sqrt2 * erfcinv(2μ)\nlinkinv(::ProbitLink, η) = erfc(-η / sqrt2) / 2\nmueta(::ProbitLink, η) = exp(-abs2(η) / 2) / sqrt2π\nfunction inverselink(::ProbitLink, η)\n    μlower = erfc(abs(η) / sqrt2) / 2\n    μupper = 1 - μlower\n    η < 0 ? μlower : μupper, exp(-abs2(η) / 2 ) / sqrt2π, μlower * μupper\nend\n\nlinkfun(::SqrtLink, μ) = sqrt(μ)\nlinkinv(::SqrtLink, η) = abs2(η)\nmueta(::SqrtLink, η) = 2η\ninverselink(::SqrtLink, η) = abs2(η), 2η, oftype(η, NaN)\n\ncanonicallink(::Bernoulli) = LogitLink()\ncanonicallink(::Binomial) = LogitLink()\ncanonicallink(::Gamma) = InverseLink()\ncanonicallink(::InverseGaussian) = InverseSquareLink()\ncanonicallink(d::NegativeBinomial) = NegativeBinomialLink(d.r)\ncanonicallink(::Normal) = IdentityLink()\ncanonicallink(::Poisson) = LogLink()\n\n\"\"\"\n    glmvar(D::Distribution, μ)\n\nReturn the value of the variance function for `D` at `μ`\n\nThe variance of `D` at `μ` is the product of the dispersion parameter, ϕ, which does not\ndepend on `μ` and the value of `glmvar`.  In other words `glmvar` returns the factor of the\nvariance that depends on `μ`.\n\n# Examples\n```jldoctest\njulia> μ = 1/6:1/3:1;\n\njulia> glmvar.(Normal(), μ)    # constant for Normal()\n3-element Array{Float64,1}:\n 1.0\n 1.0\n 1.0\n\njulia> glmvar.(Bernoulli(), μ) ≈ μ .* (1 .- μ)\ntrue\n\njulia> glmvar.(Poisson(), μ) == μ\ntrue\n```\n\"\"\"\nfunction glmvar end\n\nglmvar(::Union{Bernoulli,Binomial}, μ) = μ * (1 - μ)\nglmvar(::Gamma, μ) = abs2(μ)\nglmvar(::InverseGaussian, μ) = μ^3\nglmvar(d::NegativeBinomial, μ) = μ * (1 + μ/d.r)\nglmvar(::Normal, μ) = one(μ)\nglmvar(::Poisson, μ) = μ\n\n\"\"\"\n    mustart(D::Distribution, y, wt)\n\nReturn a starting value for μ.\n\nFor some distributions it is appropriate to set `μ = y` to initialize the IRLS algorithm but\nfor others, notably the Bernoulli, the values of `y` are not allowed as values of `μ` and\nmust be modified.\n\n# Examples\n```jldoctest\njulia> mustart(Bernoulli(), 0.0, 1) ≈ 1/4\ntrue\n\njulia> mustart(Bernoulli(), 1.0, 1) ≈ 3/4\ntrue\n\njulia> mustart(Binomial(), 0.0, 10) ≈ 1/22\ntrue\n\njulia> mustart(Normal(), 0.0, 1) ≈ 0\ntrue\n```\n\"\"\"\nfunction mustart end\n\nmustart(::Bernoulli, y, wt) = (y + oftype(y, 1/2)) / 2\nmustart(::Binomial, y, wt) = (wt * y + oftype(y, 1/2)) / (wt + one(y))\nfunction mustart(::Union{Gamma, InverseGaussian}, y, wt)\n    fy = float(y)\n    iszero(y) ? oftype(y, 1/10) : fy\nend\nfunction mustart(::NegativeBinomial, y, wt)\n    fy = float(y)\n    iszero(y) ? fy + oftype(fy, 1/6) : fy\nend\nmustart(::Normal, y, wt) = y\nfunction mustart(::Poisson, y, wt)\n    fy = float(y)\n    fy + oftype(fy, 1/10)\nend\n\n\"\"\"\n    devresid(D, y, μ)\n\nReturn the squared deviance residual of `μ` from `y` for distribution `D`\n\nThe deviance of a GLM can be evaluated as the sum of the squared deviance residuals.  This\nis the principal use for these values.  The actual deviance residual, say for plotting, is\nthe signed square root of this value\n```julia\nsign(y - μ) * sqrt(devresid(D, y, μ))\n```\n\n# Examples\n```jldoctest\njulia> devresid(Normal(), 0, 0.25) ≈ abs2(0.25)\ntrue\n\njulia> devresid(Bernoulli(), 1, 0.75) ≈ -2*log(0.75)\ntrue\n\njulia> devresid(Bernoulli(), 0, 0.25) ≈ -2*log1p(-0.25)\ntrue\n```\n\"\"\"\nfunction devresid end\n\nfunction devresid(::Bernoulli, y, μ)\n    if y == 1\n        return -2 * log(μ)\n    elseif y == 0\n        return -2 * log1p(-μ)\n    end\n    throw(ArgumentError(\"y should be 0 or 1 (got $y)\"))\nend\nfunction devresid(::Binomial, y, μ)\n    if y == 1\n        return -2 * log(μ)\n    elseif y == 0\n        return -2 * log1p(-μ)\n    else\n        return 2 * (y * (log(y) - log(μ)) + (1 - y)*(log1p(-y) - log1p(-μ)))\n    end\nend\ndevresid(::Gamma, y, μ) = -2 * (log(y / μ) - (y - μ) / μ)\ndevresid(::InverseGaussian, y, μ) = abs2(y - μ) / (y * abs2(μ))\nfunction devresid(d::NegativeBinomial, y, μ)\n    θ = d.r\n    v = 2 * (xlogy(y, y / μ) + xlogy(y + θ, (μ + θ)/(y + θ)))\n    return μ == 0 ? oftype(v, NaN) : v\nend\ndevresid(::Normal, y, μ) = abs2(y - μ)\ndevresid(::Poisson, y, μ) = 2 * (xlogy(y, y / μ) - (y - μ))\n\n\"\"\"\n    dispersion_parameter(D)  # not exported\n\nDoes distribution `D` have a separate dispersion parameter, ϕ?\n\nReturns `false` for the `Bernoulli`, `Binomial` and `Poisson` distributions, `true` otherwise.\n\n# Examples\n```jldoctest\njulia> show(GLM.dispersion_parameter(Normal()))\ntrue\njulia> show(GLM.dispersion_parameter(Bernoulli()))\nfalse\n```\n\"\"\"\ndispersion_parameter(D) = true\ndispersion_parameter(::Union{Bernoulli, Binomial, Poisson}) = false\n\n\"\"\"\n    loglik_obs(D, y, μ, wt, ϕ)  # not exported\n\nReturns `wt * logpdf(D(μ, ϕ), y)` where the parameters of `D` are derived from `μ` and `ϕ`.\n\nThe `wt` argument is a multiplier of the result except in the case of the `Binomial` where\n`wt` is the number of trials and `μ` is the proportion of successes.\n\nThe loglikelihood of a fitted model is the sum of these values over all the observations.\n\"\"\"\nfunction loglik_obs end\n\nloglik_obs(::Bernoulli, y, μ, wt, ϕ) = wt*logpdf(Bernoulli(μ), y)\nloglik_obs(::Binomial, y, μ, wt, ϕ) = logpdf(Binomial(Int(wt), μ), Int(y*wt))\nloglik_obs(::Gamma, y, μ, wt, ϕ) = wt*logpdf(Gamma(inv(ϕ), μ*ϕ), y)\nloglik_obs(::InverseGaussian, y, μ, wt, ϕ) = wt*logpdf(InverseGaussian(μ, inv(ϕ)), y)\nloglik_obs(::Normal, y, μ, wt, ϕ) = wt*logpdf(Normal(μ, sqrt(ϕ)), y)\nloglik_obs(::Poisson, y, μ, wt, ϕ) = wt*logpdf(Poisson(μ), y)\n# We use the following parameterization for the Negative Binomial distribution:\n#    (Γ(θ+y) / (Γ(θ) * y!)) * μ^y * θ^θ / (μ+θ)^{θ+y}\n# The parameterization of NegativeBinomial(r=θ, p) in Distributions.jl is\n#    Γ(θ+y) / (y! * Γ(θ)) * p^θ(1-p)^y\n# Hence, p = θ/(μ+θ)\nloglik_obs(d::NegativeBinomial, y, μ, wt, ϕ) = wt*logpdf(NegativeBinomial(d.r, d.r/(μ+d.r)), y)\n", "meta": {"hexsha": "427a27266dadc8ae1f1e36af5e400a90e0b70658", "size": 12702, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/glmtools.jl", "max_stars_repo_name": "ianshmean/GLM.jl", "max_stars_repo_head_hexsha": "0b715a2e4be5069d5d7b09dfc4991fe2dcc03240", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/glmtools.jl", "max_issues_repo_name": "ianshmean/GLM.jl", "max_issues_repo_head_hexsha": "0b715a2e4be5069d5d7b09dfc4991fe2dcc03240", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/glmtools.jl", "max_forks_repo_name": "ianshmean/GLM.jl", "max_forks_repo_head_hexsha": "0b715a2e4be5069d5d7b09dfc4991fe2dcc03240", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6732026144, "max_line_length": 281, "alphanum_fraction": 0.6613919068, "num_tokens": 4522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7530071364226582}}
{"text": "\"\"\"\n     enkf(state_ens, d_matrix, hx_matrix)\n\nReturn updated states\n\"\"\"\nfunction enkf(state_ens, d_matrix, hx_matrix)\n\n  # Variables (Mandel)\n\n  X  = state_ens;\n  D  = d_matrix;\n  HX = hx_matrix;\n\n  # Subtract ensemble mean (Mandel)\n\n  (n, N) = size(X);\n  (m, N) = size(D);\n\n  A    = X - 1 / N * (X * ones(Float64, N, 1)) * ones(Float64, 1, N);\n  HA   = HX - 1 / N * (HX * ones(Float64, N, 1)) * ones(Float64, 1, N);\n  Dtmp = D - 1 / N * (D * ones(Float64, N, 1)) * ones(Float64, 1, N);\n\n  # Observation error variance (Mandel-theoretic, Evensen-sample)\n\n  R_sample = Dtmp * Dtmp' / (N-1);\n\n  # Variance of predicted observations (DeChant and Mandel)\n\n  C_YY = 1 / (N-1) * HA * HA';\n\n  # Covariance between states ensemble and predicted observations (DeChant and Mandel)\n\n  C_XY = 1 / (N-1) * A * HA';\n\n  # Compute kalman gain (DeChant)\n\n  K = C_XY / (C_YY + R_sample);\n\n  if any(isnan(K))\n    println(\"R_sample = $R_sample\")\n    println(\"C_YY = $C_YY\")\n    println(\"C_XY = $C_XY\")\n    error(\"Nans in Kalman gain\")\n  end\n\n  # Update states (DeChant and Mandel)\n\n  Xhat = X + K*(D-HX);\n\n  return(Xhat);\n\nend\n\n\n\n\"\"\"\n     enkf!(state_ens, d_matrix, hx_matrix)\n\nUpdate states in place\n\"\"\"\nfunction enkf!(state_ens, d_matrix, hx_matrix)\n\n  # Variables (Mandel)\n\n  X  = state_ens;\n  D  = d_matrix;\n  HX = hx_matrix;\n\n  # Subtract ensemble mean (Mandel)\n\n  (n, N) = size(X);\n  (m, N) = size(D);\n\n  A    = X - 1 / N * (X * ones(Float64, N, 1)) * ones(Float64, 1, N);\n  HA   = HX - 1 / N * (HX * ones(Float64, N, 1)) * ones(Float64, 1, N);\n  Dtmp = D - 1 / N * (D * ones(Float64, N, 1)) * ones(Float64, 1, N);\n\n  # Observation error variance (Mandel-theoretic, Evensen-sample)\n\n  R_sample = Dtmp * Dtmp' / (N-1);\n\n  # Variance of predicted observations (DeChant and Mandel)\n\n  C_YY = 1 / (N-1) * HA * HA';\n\n  # Covariance between states ensemble and predicted observations (DeChant and Mandel)\n\n  C_XY = 1 / (N-1) * A * HA';\n\n  # Compute kalman gain (DeChant)\n\n  K = C_XY / (C_YY + R_sample);\n\n  if any(isnan(K))\n    println(\"R_sample = $R_sample\")\n    println(\"C_YY = $C_YY\")\n    println(\"C_XY = $C_XY\")\n    error(\"Nans in Kalman gain\")\n  end\n\n  # Update states (DeChant and Mandel)\n\n  X = X + K*(D-HX);\n\n  nothing\n\nend\n", "meta": {"hexsha": "be92e2c1b32d30d7434da7c3f90491d64da0f5ee", "size": 2213, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils_enkf.jl", "max_stars_repo_name": "JuliaTagBot/DataAssim.jl", "max_stars_repo_head_hexsha": "6554c343143267d981c84dd44c38f1d101f282a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils_enkf.jl", "max_issues_repo_name": "JuliaTagBot/DataAssim.jl", "max_issues_repo_head_hexsha": "6554c343143267d981c84dd44c38f1d101f282a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils_enkf.jl", "max_forks_repo_name": "JuliaTagBot/DataAssim.jl", "max_forks_repo_head_hexsha": "6554c343143267d981c84dd44c38f1d101f282a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:09:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:09:48.000Z", "avg_line_length": 20.4907407407, "max_line_length": 86, "alphanum_fraction": 0.5928603705, "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920262, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7529675677250031}}
{"text": "#all kernel functions are normalized such that their support radius is h\n\n@fastmath function pos(x::Float64)::Float64\n\treturn (x > 0.0 ? x : 0.0)\nend\n\n\"\"\"\n    spline23(h::Float64, r::Float64)::Float64\n\nReturns ``w(r)``, the value of a 2d cubic spline ``w`` with support radius `h`.\nIntegrates to unity.\n\n\"\"\"\n@fastmath function spline23(h::Float64, r::Float64)::Float64\n\tx = r/h\n\tif (x < 0.5)\n\t\t# 40/7pi = 1.8189136353359467\n\t\treturn 1.8189136353359467*(1.0 - 6.0*x^2 + 6.0*x^3)/h^2\n\telseif (x < 1.0)\n\t\t# 80/7pi = 3.6378272706718935\n\t\treturn 3.6378272706718935*(1.0 - x)^3/h^2\n\tend\n\treturn 0.0\nend\n\n\"\"\"\n    Dspline23(h::Float64, r::Float64)::Float64\n\nReturns ``\\\\frac{\\\\text{d}w}{\\\\text{d}r}(r)``, the first derivative of a 2d cubic spline ``w`` with support radius `h`.\nIntegrates to unity.\n\n\"\"\"\n@fastmath function Dspline23(h::Float64, r::Float64)::Float64\n\tx = r/h\n\tif (x < 0.5)\n\t\t# 240/7pi = 10.91348181201568\n\t\treturn -10.91348181201568*(2.0*x - 3.0*x^2)/h^3\n\telseif (x < 1.0)\n\t\treturn -10.91348181201568*(1.0 - x)^2/h^3\n\tend\n\treturn 0.0\nend\n\n\"\"\"\n    rDspline23(h::Float64, r::Float64)::Float64\n\nReturns ``\\\\frac{1}{r}\\\\,\\\\frac{\\\\text{d}w}{\\\\text{d}r}(r)``, the reduced first derivative of a 2d cubic spline ``w`` with support radius `h`.\nIntegrates to unity.\n\n\"\"\"\n@fastmath function rDspline23(h::Float64, r::Float64)::Float64\n\tx = r/h\n\tif (x < 0.5)\n\t\t# 240/7pi = 10.91348181201568\n\t\treturn -10.91348181201568*(2.0 - 3.0*x)/h^4\n\telseif (x < 1.0)\n\t\treturn -10.91348181201568*(1.0 - x)^2/(x*h^4)\n\tend\n\treturn 0.0\nend\n\n\"\"\"\n    spline24(h::Float64, r::Float64)::Float64\n\nReturns ``w(r)``, the value of a 2d quartic spline ``w`` with support radius `h`.\nIntegrates to unity.\n\n\"\"\"\n@fastmath function spline24(h::Float64, r::Float64)::Float64\n\tx = r/h\n\treturn 6.222175110452539*(pos(1.0 - x)^4 - 5*pos(0.6 - x)^4 + 10*pos(0.2 - x)^4)/h^2\nend\n\n\"\"\"\n    Dspline24(h::Float64, r::Float64)::Float64\n\nReturns ``\\\\frac{\\\\text{d}w}{\\\\text{d}r}(r)``, the first derivative of a 2d quartic spline ``w`` with support radius `h`.\nIntegrates to unity.\n\n\"\"\"\n@fastmath function Dspline24(h::Float64, r::Float64)::Float64\n\tx = r/h\n\treturn -24.888700441810155*(pos(1.0 - x)^3 - 5*pos(0.6 - x)^3 + 10*pos(0.2 - x)^3)/h^3\nend\n\n\"\"\"\n    rDspline24(h::Float64, r::Float64)::Float64\n\nReturns ``\\\\frac{1}{r}\\\\,\\\\frac{\\\\text{d}w}{\\\\text{d}r}(r)``, the reduced first derivative of a 2d quartic spline ``w`` with support radius `h`.\nIntegrates to unity.\n\n\"\"\"\n@fastmath function rDspline24(h::Float64, r::Float64)::Float64\n\tx = r/h\n\tif x > 0.2\n\t\treturn -24.888700441810155*(pos(1.0 - x)^3 - 5*pos(0.6 - x)^3)/(x*h^4)\n\tend\n\treturn -24.888700441810155*(1.2 - 6.0*x^2)/h^4\nend\n\n\"\"\"\n    wendland2(h::Float64, r::Float64)::Float64\n\nReturns ``w(r)``, the value of a 2d quintic Wendland kernel ``w`` with support radius `h`.\nIntegrates to unity.\n\n\"\"\"\n@fastmath function wendland2(h::Float64, r::Float64)::Float64\n\tx = r/h\n\tif (x > 1.0)\n\t\treturn 0.0\n\tend\n\t# 7/pi ≐ 2.228169203286535\n\treturn 2.228169203286535*((1.0 - x)^4)*(1.0 + 4.0*x)/h^2\nend\n\n\"\"\"\n    Dwendland2(h::Float64, r::Float64)::Float64\n\nReturns ``\\\\frac{\\\\text{d}w}{\\\\text{d}r}(r)``, the first derivative of a 2d quintic Wendland kernel ``w`` with support radius `h`.\nIntegrates to unity.\n\n\"\"\"\n@fastmath function Dwendland2(h::Float64, r::Float64)::Float64\n\tx = r/h\n\tif (x > 1.0)\n\t\treturn 0.0\n\tend\n\t# 140/pi ≐ 44.563384065730695\n\treturn -44.563384065730695*x*((1.0 - x)^3)/h^3\nend\n\n\"\"\"\n    rDwendland2(h::Float64, r::Float64)::Float64\n\nReturns ``\\\\frac{1}{r}\\\\,\\\\frac{\\\\text{d}w}{\\\\text{d}r}(r)``, the reduced first derivative of a 2d quintic Wendland kernel ``w`` with support radius `h`.\nIntegrates to unity.\n\n\"\"\"\n@fastmath function rDwendland2(h::Float64, r::Float64)::Float64\n\tx = r/h\n\tif (x > 1.0)\n\t\treturn 0.0\n\tend\n\t# 140/pi ≐ 44.563384065730695\n\treturn -44.563384065730695*((1.0 - x)^3)/h^4\nend\n\n\"\"\"\n    wendland3(h::Float64, r::Float64)::Float64\n\nReturns ``w(r)``, the value of a 3d quintic Wendland kernel ``w`` with support radius `h`.\nIntegrates to unity.\n\n\"\"\"\n@fastmath function wendland3(h::Float64, r::Float64)::Float64\n\tx = r/h\n\tif (x > 1.0)\n\t\treturn 0.0\n\tend\n\t# 21/2pi ≐ 3.3422538049298023\n\treturn 3.3422538049298023*((1.0 - x)^4)*(1.0 + 4.0*x)/h^3\nend\n\n\"\"\"\n    Dwendland3(h::Float64, r::Float64)::Float64\n\nReturns ``\\\\frac{\\\\text{d}w}{\\\\text{d}r}(r)``, the first derivative of a 3d quintic Wendland kernel ``w`` with support radius `h`.\nIntegrates to unity.\n\n\"\"\"\n@fastmath function Dwendland3(h::Float64, r::Float64)::Float64\n\tx = r/h\n\tif (x > 1.0)\n\t\treturn 0.0\n\tend\n\t# 210/pi ≐ 66.84507609859604\n\treturn -66.84507609859604*x*((1.0 - x)^3)/h^4\nend\n\n\"\"\"\n    rDwendland3(h::Float64, r::Float64)::Float64\n\nReturns ``\\\\frac{1}{r}\\\\,\\\\frac{\\\\text{d}w}{\\\\text{d}r}(r)``, the reduced first derivative of a 3d quintic Wendland kernel ``w`` with support radius `h`.\nIntegrates to unity.\n\n\"\"\"\n@fastmath function rDwendland3(h::Float64, r::Float64)::Float64\n\tx = r/h\n\tif (x > 1.0)\n\t\treturn 0.0\n\tend\n\t# 210/pi ≐ 66.84507609859604\n\treturn -66.84507609859604*((1.0 - x)^3)/h^5\nend\n\n@fastmath function DDwendland3(h::Float64, r::Float64)::Float64\n\tx = r/h\n\tif (x > 1.0)\n\t\treturn 0.0\n\tend\n\t# 210/pi ≐ 66.84507609859604\n\treturn -66.84507609859604*((1.0 - 4.0*x)*(1.0 - x)^2)/h^5\nend\n\n@fastmath function spiky3(h::Float64, r::Float64)::Float64\n\tx = r/h\n\t#15/2pi = 2.3873241463784303\n\treturn 2.3873241463784303*(1.0 - x)^2/h^3\nend\n\n@fastmath function Dspiky3(h::Float64, r::Float64)::Float64\n\tx = r/h\n\t#15/pi = 4.7746482927568605\n\treturn -(x < 1.0)*2.3873241463784303*(1.0 - x)/h^4\nend\n\n@fastmath function rDspiky3(h::Float64, r::Float64)::Float64\n\tx = r/h\n\t#15/pi = 4.7746482927568605\n\treturn -(x < 1.0)*2.3873241463784303*(1.0 - x)/((x + 1e-6)*h^5)\nend\n\n@fastmath function DDspiky3(h::Float64, r::Float64)::Float64\n\tx = r/h\n\t#15/pi = 4.7746482927568605\n\treturn (x < 1.0)*2.3873241463784303/h^5\nend", "meta": {"hexsha": "320df146d4d4de8bb71c6dd496b3b36b760e1b29", "size": 5820, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels.jl", "max_stars_repo_name": "OndrejKincl/SPHLib.jl", "max_stars_repo_head_hexsha": "58fed2b67f5b658c25d4a926bb07182966e1ff2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-06T21:13:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T21:13:53.000Z", "max_issues_repo_path": "src/kernels.jl", "max_issues_repo_name": "OndrejKincl/SPHLib.jl", "max_issues_repo_head_hexsha": "58fed2b67f5b658c25d4a926bb07182966e1ff2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-16T15:50:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T15:50:30.000Z", "max_forks_repo_path": "src/kernels.jl", "max_forks_repo_name": "OndrejKincl/SPHLib.jl", "max_forks_repo_head_hexsha": "58fed2b67f5b658c25d4a926bb07182966e1ff2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5263157895, "max_line_length": 153, "alphanum_fraction": 0.6475945017, "num_tokens": 2396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138559, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7529675639111307}}
{"text": "using Combinatorics\n\nfunction findMinWrapDist(f_true,f_hat)\n# Assign each of the ground truth frequencies to closest\n# (squared error) canditate of estimated frequencies.\n# Metric is the wrap-aroud distance on the torus $\\mathds{T}=[0,1]$.\n#\n# Inputs:\n# f_true: ground truth frequencies\n# f_hat: estimated frequencies\n#\n# Output:\n# dists: wrap-around distances of the frequencies in f_true and f_hat\n\nK = length(f_true)\nWrapDist(x,y) = min(abs(x-y),abs(x-y+1))\n\ndists = Array{Float64,1}(undef,K)\nfor ii = 1:K\n    dists[ii] = minimum(WrapDist.(f_true[ii],f_hat))\nend\n\nreturn dists\nend\n", "meta": {"hexsha": "65be4f8ebae36f046777da44cf793db35a1476ad", "size": 584, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "algorithms/findMinWrapDist.jl", "max_stars_repo_name": "THweinberger/specAna_matComp", "max_stars_repo_head_hexsha": "77612b94f74bf484bf39d65dd2834b38389eb695", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algorithms/findMinWrapDist.jl", "max_issues_repo_name": "THweinberger/specAna_matComp", "max_issues_repo_head_hexsha": "77612b94f74bf484bf39d65dd2834b38389eb695", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algorithms/findMinWrapDist.jl", "max_forks_repo_name": "THweinberger/specAna_matComp", "max_forks_repo_head_hexsha": "77612b94f74bf484bf39d65dd2834b38389eb695", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.36, "max_line_length": 69, "alphanum_fraction": 0.7345890411, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475746920262, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7529675541388268}}
{"text": "# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.\n#\n# Find the sum of all the primes below two million.\n\nusing ProjectEulerSolutions\n\n# Run Sieve of Eratosthenes to get primes and sum them.\nfunction p010solution(n::Integer=3)::Integer\n    return sum(sieve_eratosthenes(n))\nend\n\np010 = Problems.Problem(p010solution)\n\nProblems.benchmark(p010, 1_999_999)", "meta": {"hexsha": "8977d32147b36fded957f6507772d73656fe8277", "size": 358, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/010.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/010.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/010.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5714285714, "max_line_length": 55, "alphanum_fraction": 0.748603352, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7529675541388268}}
{"text": "export Associative, Nonassociative, associativity\n\n\"\"\"\nTrait to indicate that a binary operation • is associative over set S. Only\nmethods of • with the signature •(x::S, y::S) are to be considered.\n\nThat is to say, ``\\forall x, y, z \\in S. (x \\bullet y) \\bullet z = x \\bullet (y\n\\bullet z)``. Note that in practice, this is not so absolute. Minor deviations\nsuch as `Float64` arithmetic not being perfectly associative are allowed for\npractical reasons.\n\"\"\"\nabstract Associative\n\n\"\"\"\nTrait to indicate that a binary operation • is not necessarily associative over\nset S. Despite the name, this trait does not imply the existence of a\ncounterexample to associativity.\n\"\"\"\nabstract Nonassociative\n\n\"\"\"\nReturn the associativity trait of the set S under the binary operation •.\n\"\"\"\nassociativity(::Type, ::Function) = Nonassociative\n\n# complex numbers are associative under + and *\n# note that this is not in general true for arbitrary Numbers\nassociativity{N<:AbstractComplex}(::Type{N}, ::typeof(+)) = Associative\nassociativity{N<:AbstractComplex}(::Type{N}, ::typeof(*)) = Associative\n\n# Strings are associative under *\nassociativity(::Type{String}, ::typeof(*)) = Associative\n", "meta": {"hexsha": "61f89459fa0dc7124ec70cbc702e71c76788fb7f", "size": 1177, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/associativity.jl", "max_stars_repo_name": "TotalVerb/AlgebraicTraits.jl", "max_stars_repo_head_hexsha": "7dc81229d31d2c9afc11003398c6c1fdd3468cde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-07-19T02:33:47.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-19T02:33:47.000Z", "max_issues_repo_path": "src/associativity.jl", "max_issues_repo_name": "TotalVerb/AlgebraicTraits.jl", "max_issues_repo_head_hexsha": "7dc81229d31d2c9afc11003398c6c1fdd3468cde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/associativity.jl", "max_forks_repo_name": "TotalVerb/AlgebraicTraits.jl", "max_forks_repo_head_hexsha": "7dc81229d31d2c9afc11003398c6c1fdd3468cde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6666666667, "max_line_length": 79, "alphanum_fraction": 0.7442650807, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303732328411, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7529620325003593}}
{"text": "\"\"\"\n    NormalCanon(η, λ)\n\nCanonical parametrisation of the Normal distribution with canonical parameters `η` and `λ`.\n\nThe two *canonical parameters* of a normal distribution ``\\\\mathcal{N}(\\\\mu, \\\\sigma^2)`` with mean ``\\\\mu`` and\nstandard deviation ``\\\\sigma`` are ``\\\\eta = \\\\sigma^{-2} \\\\mu`` and ``\\\\lambda = \\\\sigma^{-2}``.\n\"\"\"\nstruct NormalCanon{T<:Real} <: ContinuousUnivariateDistribution\n    η::T       # σ^(-2) * μ\n    λ::T       # σ^(-2)\n    μ::T       # μ\n\n    function NormalCanon{T}(η, λ; check_args::Bool=true) where T\n        check_args && @check_args(NormalCanon, λ > zero(λ))\n        new{T}(η, λ, η / λ)\n    end\nend\n\nNormalCanon(η::T, λ::T; check_args::Bool=true) where {T<:Real} = NormalCanon{typeof(η/λ)}(η, λ; check_args=check_args)\nNormalCanon(η::Real, λ::Real; check_args::Bool=true) = NormalCanon(promote(η, λ)...; check_args=check_args)\nNormalCanon(η::Integer, λ::Integer; check_args::Bool=true) = NormalCanon(float(η), float(λ); check_args=check_args)\nNormalCanon() = NormalCanon{Float64}(0.0, 1.0; check_args=false)\n\n@distr_support NormalCanon -Inf Inf\n\n#### Type Conversions\nconvert(::Type{NormalCanon{T}}, η::S, λ::S) where {T <: Real, S <: Real} = NormalCanon(T(η), T(λ))\nconvert(::Type{NormalCanon{T}}, d::NormalCanon{S}) where {T <: Real, S <: Real} = NormalCanon(T(d.η), T(d.λ); check_args=false)\n\n## conversion between Normal and NormalCanon\n\nconvert(::Type{Normal}, d::NormalCanon) = Normal(d.μ, 1 / sqrt(d.λ))\nconvert(::Type{NormalCanon}, d::Normal) = (λ = 1 / d.σ^2; NormalCanon(λ * d.μ, λ))\nmeanform(d::NormalCanon) = convert(Normal, d)\ncanonform(d::Normal) = convert(NormalCanon, d)\n\n\n#### Parameters\n\nparams(d::NormalCanon) = (d.η, d.λ)\n@inline partype(d::NormalCanon{T}) where {T<:Real} = T\n\n#### Statistics\n\nmean(d::NormalCanon) = d.μ\nmedian(d::NormalCanon) = mean(d)\nmode(d::NormalCanon) = mean(d)\n\nskewness(d::NormalCanon{T}) where {T<:Real} = zero(T)\nkurtosis(d::NormalCanon{T}) where {T<:Real} = zero(T)\n\nvar(d::NormalCanon) = 1 / d.λ\nstd(d::NormalCanon) = sqrt(var(d))\n\nentropy(d::NormalCanon) = (-log(d.λ) + log2π + 1) / 2\n\nlocation(d::NormalCanon) = mean(d)\nscale(d::NormalCanon) = std(d)\n\n#### Evaluation\n\npdf(d::NormalCanon, x::Real) = (sqrt(d.λ) / sqrt2π) * exp(-d.λ * abs2(x - d.μ)/2)\nlogpdf(d::NormalCanon, x::Real) = (log(d.λ) - log2π - d.λ * abs2(x - d.μ))/2\n\nzval(d::NormalCanon, x::Real) = (x - d.μ) * sqrt(d.λ)\nxval(d::NormalCanon, z::Real) = d.μ + z / sqrt(d.λ)\n\ncdf(d::NormalCanon, x::Real) = normcdf(zval(d,x))\nccdf(d::NormalCanon, x::Real) = normccdf(zval(d,x))\nlogcdf(d::NormalCanon, x::Real) = normlogcdf(zval(d,x))\nlogccdf(d::NormalCanon, x::Real) = normlogccdf(zval(d,x))\n\nquantile(d::NormalCanon, p::Real) = xval(d, norminvcdf(p))\ncquantile(d::NormalCanon, p::Real) = xval(d, norminvccdf(p))\ninvlogcdf(d::NormalCanon, lp::Real) = xval(d, norminvlogcdf(lp))\ninvlogccdf(d::NormalCanon, lp::Real) = xval(d, norminvlogccdf(lp))\n\n\n#### Sampling\n\nrand(rng::AbstractRNG, cf::NormalCanon) = cf.μ + randn(rng) / sqrt(cf.λ)\n\n#### Affine transformations\n\nfunction Base.:+(d::NormalCanon, c::Real)\n    η, λ = params(d)\n    return NormalCanon(η + c * λ, λ)\nend\nBase.:*(c::Real, d::NormalCanon) = NormalCanon(d.η / c, d.λ / c^2)\n", "meta": {"hexsha": "cc74ef3e47a33f9bab2568e9544e74b99bd79d45", "size": 3185, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/normalcanon.jl", "max_stars_repo_name": "pdeffebach/Distributions.jl", "max_stars_repo_head_hexsha": "8aea3cc82ee2f8ffe1e8cd754e7fcd99369c7a1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/normalcanon.jl", "max_issues_repo_name": "pdeffebach/Distributions.jl", "max_issues_repo_head_hexsha": "8aea3cc82ee2f8ffe1e8cd754e7fcd99369c7a1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/normalcanon.jl", "max_forks_repo_name": "pdeffebach/Distributions.jl", "max_forks_repo_head_hexsha": "8aea3cc82ee2f8ffe1e8cd754e7fcd99369c7a1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0, "max_line_length": 127, "alphanum_fraction": 0.6455259027, "num_tokens": 1107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939516, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7529620287469835}}
{"text": "module Metrics\n    using ..Representation\n    function calc_population_fitness!(population::Representation.Population,\n                                    true_values::Array{Float64, 1},\n                                    error_function, extra_params=nothing)\n        for memeber in population.members\n            pred_values = [kernels_to_values(x, memeber.gauss_kernels) for x in true_values]\n            if extra_params != nothing && error_function == weighted_mean_abs_error\n                (error, hit_ratio) = error_function(true_values,\n                                        pred_values,\n                                        extra_params[\"threshold\"],\n                                        extra_params[\"lower_weight\"],\n                                        extra_params[\"upper_weight\"])\n            else\n                (error, hit_ratio) = error_function(true_values, pred_values)\n            end\n            memeber.fitness = error\n            memeber.hit_ratio = hit_ratio\n        end\n    end\n\n\n    function mean_sqr_error(true_values::Array{Float64, 1}, pred_values::Array{Float64, 1})\n        error = sum((true_values - pred_values).^2)/length(true_values)\n        hit_ratio = sum(true_values .== pred_values)\n        return error, hit_ratio\n    end\n\n    function mean_absolute_error(true_values::Array{Float64, 1}, pred_values::Array{Float64, 1})\n        error = sum(abs.(true_values - pred_values))/length(true_values)\n        hit_ratio = sum(true_values .== pred_values)\n        return error, hit_ratio\n    end\n\n    function weighted_mean_abs_error(true_values::Array{Float64, 1},\n                                    pred_values::Array{Float64, 1},\n                                    threshold::Float64,\n                                    lower_weight::Float64,\n                                    upper_weight::Float64)\n\n        abs_error = abs.(true_values - pred_values)\n        mask = [apply_threshold(value, threshold,\n                        lower_weight, upper_weight) for value in abs_error]\n        hit_ratio = sum(mask .== 1.0)\n        return sum(abs_error.*mask)/length(true_values), hit_ratio\n\n    end\n\n    function apply_threshold(value::Float64, threshold::Float64,\n                                lower_weight::Float64, upper_weight::Float64)\n        return value <= threshold ? lower_weight : upper_weight\n    end\n\n    function kernels_to_values(x::Float64,\n                                kernels::Array{Tuple{Float64, Float64, Float64}, 1})\n        sum = Float32(0.0)\n        for kernel in kernels\n            (weight, c, γ) = kernel\n            sum += weight * exp(-γ*(c - x)^2)\n        end\n        return sum\n    end\n\nend\n", "meta": {"hexsha": "36644b3eae432f180a01e3289c3d362d89a780a7", "size": 2670, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "metrics.jl", "max_stars_repo_name": "pabloduque0/regression_genetic_algorithm", "max_stars_repo_head_hexsha": "807d6b7a2cae812fe8dfac126d8803d06c024d16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-02-21T10:11:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-24T11:24:27.000Z", "max_issues_repo_path": "metrics.jl", "max_issues_repo_name": "pabloduque0/regression_genetic_algorithm", "max_issues_repo_head_hexsha": "807d6b7a2cae812fe8dfac126d8803d06c024d16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "metrics.jl", "max_forks_repo_name": "pabloduque0/regression_genetic_algorithm", "max_forks_repo_head_hexsha": "807d6b7a2cae812fe8dfac126d8803d06c024d16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0769230769, "max_line_length": 96, "alphanum_fraction": 0.5573033708, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7529620275391224}}
{"text": "# Gaussian models\n\n### For prior IsoNormalCanon\n\nfunction logpar(d::IsoNormalCanon)\n    q = length(d)\n    h = d.h\n    σ2 = inv(d.J.value)\n    (q * log(2π * σ2) + σ2 * vecnorm(h)^2) * 0.5\nend\n\nimmutable IsoNormalCanonSuffStats\n    h::Vector{Float64}  # add to h\n    κ::Float64          # add to κ\nend\n\nlength(ss::IsoNormalCanonSuffStats) = length(ss.h)\n\nfunction posterior(d::IsoNormalCanon, ss::IsoNormalCanonSuffStats)\n    length(d) == length(ss) || throw(DimensionMismatch())\n    MvNormalCanon(d.h + ss.h, d.J.value + ss.κ)\nend\n\n\n##\n# Gaussian likelihood model\n#\n#  x ~ N(θ, σ^2)\n#\nimmutable IsoGaussModel <: LikelihoodModel\n    σ::Float64    # the standard dev of observations\nend\n\nwithparams(g::IsoGaussModel, μ::Vector{Float64}) =\n    MvNormal(μ, g.σ)\n\nfunction suffstats(g::IsoGaussModel, X::AbstractMatrix, inds::AbstractVector{Int})\n    d, n = size(X)\n    h = zeros(d)\n    c = 1.0 / g.σ^2\n    for i in inds\n        x = view(X, :, i)\n        axpy!(c, x, h)\n    end\n    IsoNormalCanonSuffStats(h, n * c)\nend\n\nsuffstats(g::IsoGaussModel, X::AbstractMatrix) = suffstats(g, X, 1:size(X,2))\n", "meta": {"hexsha": "d42dca5647c625c45ba43da0812e635897a55d58", "size": 1093, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gauss.jl", "max_stars_repo_name": "lindahua/BayesModels.jl", "max_stars_repo_head_hexsha": "a27a06f846d16914c812c00d9cfb8f2d48e4c439", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-01-25T19:07:30.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-20T07:21:30.000Z", "max_issues_repo_path": "src/gauss.jl", "max_issues_repo_name": "lindahua/LightBayes.jl", "max_issues_repo_head_hexsha": "a27a06f846d16914c812c00d9cfb8f2d48e4c439", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gauss.jl", "max_forks_repo_name": "lindahua/LightBayes.jl", "max_forks_repo_head_hexsha": "a27a06f846d16914c812c00d9cfb8f2d48e4c439", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.306122449, "max_line_length": 82, "alphanum_fraction": 0.6386093321, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303728259492, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7529620270932378}}
{"text": "using Distributions\nusing ReverseDiffOverload\nimport Distributions.logpdf\n\ntest(dist, x, params...) = begin\n    @assert isapprox(logpdf(dist, x, params...), logpdf(dist(params...), x))\n    if dist <: DiscreteDistribution\n        testdiff((params...) -> logpdf(dist, x, params...), params...)\n    else\n        testdiff((x, params...) -> logpdf(dist, x, params...), x, params...)\n    end\nend\n\n#Normal\nvalid(::Type{Normal}, x, μ, σ) = begin\n    @assert all(σ .> 0)\nend\n#Differentiable versions.\nlogpdf(::Type{Normal}, x, μ, σ) = begin\n    #valid(Normal, x, μ, σ)\n    σ2 = σ.*σ\n    diff = x-μ\n    -(log(2*pi*σ2) + diff.*diff ./ σ2)/2\nend\ntest(Normal, 1, 2, 3)\n\n\n#MvNormal\nvalid(::Type{MvNormal}, x::Vector, μ::Vector, Σ::Matrix) = begin\n    @assert isposdef(Σ)\nend\n#Differentiable versions.\nlogpdf(::Type{MvNormal}, x::Vector, μ::Vector, Σ::Matrix) = begin\n    #valid(MvNormal, x, μ, Σ)\n    diff = x-μ\n    -(length(x)*log(2*pi) + logdet(Σ) + (diff'/Σ)*x)/2\nend\n#test(MvNormal, [1., 2], [3., 4], eye(2) + ones(2,2))\n\n\n#Gamma\nvalid(::Type{Gamma}, x, shape, scale) = begin\n    @assert all(x .>= 0)\n    @assert all(shape .>= 0)\n    @assert all(scale .>= 0)\nend\nlogpdf(::Type{Gamma}, x, shape, scale) = begin\n    #valid(Gamma, x, shape, scale)\n    -logΓ(shape) - shape.*log(scale) + (shape-1).*log(x) - x./scale\nend\ntest(Gamma, 1, 2, 3)\n\n\n#InverseGamma\nvalid(::Type{InverseGamma}, x, shape, scale) = begin\n    @assert all(x .>= 0)\n    @assert all(shape .>= 0)\n    @assert all(scale .>= 0)\nend\nlogpdf(::Type{InverseGamma}, x, shape, scale) = begin\n    #valid(InverseGamma, x, shape, scale)\n    -logΓ(shape) + shape.*log(scale) - (shape+1).*log(x) - scale./x\nend\ntest(InverseGamma, 1, 2, 3)\n\n\n#Bernoulli\nvalid(::Type{Bernoulli}, x, p) = begin\n    @assert all(0 .<= p .<= 1)\n    @assert all((x .== 1)|(x .== 0))\nend\nlogpdf(::Type{Bernoulli}, x, p) = begin\n    #valid(Bernoulli, x, p)\n    x*log(p) + (1-x)*log(1-p)\nend\ntest(Bernoulli, 1., 0.9)\ntest(Bernoulli, 0., 0.9)\n\n\n#Categorical\nvalid(::Type{Categorical}, x, ps::Vector{Float64}) = begin\n    @assert isapprox(sum(ps), 1)\n    @assert all(0 .<= ps .<= 1)\nend\nlogpdf(::Type{Categorical}, x, ps) = begin\n    #valid(Categorical, x, ps)\n    log(ps[x])\nend\ntest(Categorical, 2, [0.3, 0.4, 0.3])\n\n\n#Beta\nvalid(::Type{Beta}, x, α, β) = begin\n    @assert all(α .> 0)\n    @assert all(β .> 0)\n    @assert all(0 .<= x .<= 1)\nend\nlogB(α, β) = logΓ(α) + logΓ(β) - logΓ(α + β)\nlogpdf(::Type{Beta}, x, α, β) = begin\n    #valid(Beta, x, α, β)\n    (α-1).*log(x) + (β-1).*log(1-x) - logB(α, β)\nend\ntest(Beta, 0.6, 1.3, 1.5)\n\n\n#Dirichlet\nvalid(::Type{Dirichlet}, x, α::Vector{Float64}) = begin\n    @assert all(0 .<= x)\n    @assert all(0 .<= α)\nend\nlogB(α) = sum(logΓ(α)) - logΓ(sum(α))\nlogpdf(::Type{Dirichlet}, x, α) = begin\n    #valid(Dirichlet, x, α)\n    sum((α-1).*log(x)) - logB(α)\nend\ntest(Dirichlet, [1.2, 1.6, 1.3], [1.3, 1.6, 1.3])\n    \n\n#Poisson\nvalid(::Type{Poisson}, k, λ) = begin\n    @assert all(k .>= 0)\n    @assert all(λ .>= 0)\nend\nlogpdf(::Type{Poisson}, k, λ) = begin\n    #valid(Poisson, k, λ)\n    k*log(λ) - log(factorial(k)) - λ\nend\ntest(Poisson, 3, 5)\n\n#Non-differentiable fallbacks from Distributions.jl\nlogpdf{D <: Distribution}(d::Type{D}, x, params...) = \n    logpdf(d(params...), x)\n", "meta": {"hexsha": "7fd4b293b9c52967109ed01b482b4b3a5620f575", "size": 3229, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/logpdf.jl", "max_stars_repo_name": "LaurenceA/Turing.jl", "max_stars_repo_head_hexsha": "24404c3870ec984f8f51b0321b677bd7d253218e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-05-16T17:00:36.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-16T17:00:36.000Z", "max_issues_repo_path": "src/logpdf.jl", "max_issues_repo_name": "LaurenceA/sdfiousdf.jl", "max_issues_repo_head_hexsha": "24404c3870ec984f8f51b0321b677bd7d253218e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-05-24T16:40:13.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-24T16:40:13.000Z", "max_forks_repo_path": "src/logpdf.jl", "max_forks_repo_name": "LaurenceA/Turing.jl", "max_forks_repo_head_hexsha": "24404c3870ec984f8f51b0321b677bd7d253218e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2781954887, "max_line_length": 76, "alphanum_fraction": 0.5819139052, "num_tokens": 1297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303728259492, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7529620249936074}}
{"text": "\nabstract Type1FuzzySet <: AbstractFuzzySet\nexport Type1FuzzySet\n\n#####################\nabstract Membershipfunction <: Type1FuzzySet\nexport Membershipfunction\n\nimport Base: getindex\n\ngetindex(mf::Membershipfunction, range) = [mf[value]::Float64 for value in range]\ngetindex(mf::Membershipfunction, values...) = [mf[value]::Float64 for value in values]\n\nexport getindex\n\n#####################\n# Membership Functions\n\"Triangle Membership Function\"\nimmutable TriangleMF <: Membershipfunction\n\ta::Float64\n\tb::Float64\n\tc::Float64\n\n\tTriangleMF(a,b,c) = a <= b <= c ? new(a,b,c) : error(\"Indices out of order\")\nend\nexport TriangleMF\n\nimport Base: getindex\nfunction getindex(trimf::TriangleMF, value::Real)\n\t(value <= trimf.a || trimf.c <= value) && return zero(Float64)\n\t(value == trimf.b) && return one(Float64)\n\n\tif trimf.a < value < trimf.b\n\t\tslope = (1.0 - 0.0)/(trimf.b - trimf.a)\n\t\treturn slope * (value - trimf.a)\n\telse\n\t\tslope = (0.0 - 1.0)/(trimf.c - trimf.b)\n\t\treturn (slope * (value - trimf.b) + 1.0)\n\tend\nend\nexport getindex\n\n\n\n\"Trapezoid Membership Function\"\nimmutable TrapezoidMF <: Membershipfunction\n\ta::Float64\n\tb::Float64\n\tc::Float64\n\td::Float64\nend\nexport TrapezoidMF\n\n\nimport Base: getindex\nfunction getindex(trapmf::TrapezoidMF, value::Real)\n\t(value <= trapmf.a || trapmf.d <= value) && return zero(Float64)\n\t(trapmf.b <= value <= trapmf.c) && return one(Float64)\n\n\tif trapmf.a < value < trapmf.b\n\t\tslope = (1 - 0)/(trapmf.b - trapmf.a)\n\t\treturn slope * (value - trapmf.a)\n\telse\n\t\tslope = (0 - 1)/(trapmf.d - trapmf.c)\n\t\treturn slope * (value - trapmf.c) + 1\n\tend\nend\nexport getindex\n\n\n\"Generic Membership Function\"\nimmutable GenericMF <: Membershipfunction\n\tmf::Function\nend\nexport GenericMF\n\nimport Base: getindex\nfunction getindex(gmf::GenericMF, value::Real)\n\tgmf.mf(value)\nend\nexport getindex\n\nimmutable GaussMF <: Membershipfunction\n\tmu::Float64\n\tsigma::Float64\nend\nexport GaussMF\nimmutable GaussMF <: Membershipfunction\n\tmu::Float64\n\tsigma::Float64\nend\nexport GaussMF\n\nimport Base: getindex\nfunction getindex(gmf::GaussMF, value::Real)\n\tGenericMF(x -> exp(-(x-gmf.mu).^2/(2.*gmf.sigma.^2)))[value]\nend\nexport getindex\n\n\n#####################", "meta": {"hexsha": "fe4fdfce4f5ee4ae59436bcb43b95d989f6eb783", "size": 2162, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Type1/Type1.jl", "max_stars_repo_name": "btaidm/Fuzzy.jl", "max_stars_repo_head_hexsha": "31f3b580ad576bc320e2f9ca0a322c7b0ce9d9ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Type1/Type1.jl", "max_issues_repo_name": "btaidm/Fuzzy.jl", "max_issues_repo_head_hexsha": "31f3b580ad576bc320e2f9ca0a322c7b0ce9d9ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Type1/Type1.jl", "max_forks_repo_name": "btaidm/Fuzzy.jl", "max_forks_repo_head_hexsha": "31f3b580ad576bc320e2f9ca0a322c7b0ce9d9ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4059405941, "max_line_length": 86, "alphanum_fraction": 0.6965772433, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303728259492, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7529620249936074}}
{"text": "module problem112\n\ndescription = \"\"\"\nBouncy numbers\n\nWorking from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468.\nSimilarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420.\nWe shall call a positive integer that is neither increasing nor decreasing a \"bouncy\" number; for example, 155349.\nClearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538.\nSurprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%.\n\nFind the least number for which the proportion of bouncy numbers is exactly 99%.\n\"\"\"\n\nfunction increasing(n :: Integer)\n  lastDigit = 9\n  while n > 0\n    d = n % 10\n    if d > lastDigit\n      return false\n    end\n    lastDigit = d; \n    n = div(n, 10)\n  end\n  return true  \nend\n\nfunction decreasing(n :: Integer)\n  lastDigit = 0\n  while n > 0\n    d = n % 10\n    if d < lastDigit\n      return false\n    end\n    lastDigit = d; \n    n = div(n, 10)\n  end\n  return true\nend\n\nfunction bouncy(n :: Integer)\n  return !(increasing(n) || decreasing(n))\nend\n\nfunction bouncySearch(percentage :: Integer)\n  n = 1\n  b = 0\n  while b*100 != n*percentage\n    n += 1\n    b += bouncy(n) ? 1 : 0\n  end\n  return n\nend\n\nusing Base.Test\n\n@test bouncySearch(90) == 21780\n\nend", "meta": {"hexsha": "a4aa6dcefa06c9e1e0c6628172978380636fec67", "size": 1533, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem112.jl", "max_stars_repo_name": "mbuhot/mbuhot-euler-solutions", "max_stars_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-12-18T13:25:41.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-18T13:25:41.000Z", "max_issues_repo_path": "julia/problem112.jl", "max_issues_repo_name": "mbuhot/mbuhot-euler-solutions", "max_issues_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/problem112.jl", "max_forks_repo_name": "mbuhot/mbuhot-euler-solutions", "max_forks_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9830508475, "max_line_length": 227, "alphanum_fraction": 0.6999347684, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7528823323131502}}
{"text": "\"\"\"\nHigh-order singular value decomposition (HO-SVD).\n\"\"\"\nfunction hosvd{T,N}(tensor::StridedArray{T,N}, core_dims::NTuple{N, Int};\n                    pad_zeros::Bool=false, compute_error::Bool=false)\n    pad_zeros || _check_tensor(tensor, core_dims)\n\n    factors = map(1:N) do i\n        X = _col_unfold(tensor, i)\n        f = eigs(X'X, nev=core_dims[i])[2]\n        if pad_zeros && size(f, 2) < core_dims[i] # fill missing factors with zeros\n            f = hcat(f, zeros(T, size(tensor, i), core_dims[i]-size(f, 2)))\n        end\n        mapslices(_check_sign, f, 1)\n    end\n\n    res = Tucker((factors...), tensorcontractmatrices(tensor, factors))\n    if compute_error\n        _set_rel_residue(res, tensor)\n    end\n    return res\nend\n\nhosvd{T,N}(tensor::StridedArray{T,N}, r::Int; compute_error::Bool=false) =\n    hosvd(tensor, (fill(r, N)...); compute_error=compute_error)\n", "meta": {"hexsha": "a36dd041812ff7404eae799044ba66f44c4e71f7", "size": 875, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hosvd.jl", "max_stars_repo_name": "JuliaPackageMirrors/TensorDecompositions.jl", "max_stars_repo_head_hexsha": "26190bb49f68eb33735aac22807d06e060244231", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hosvd.jl", "max_issues_repo_name": "JuliaPackageMirrors/TensorDecompositions.jl", "max_issues_repo_head_hexsha": "26190bb49f68eb33735aac22807d06e060244231", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hosvd.jl", "max_forks_repo_name": "JuliaPackageMirrors/TensorDecompositions.jl", "max_forks_repo_head_hexsha": "26190bb49f68eb33735aac22807d06e060244231", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6538461538, "max_line_length": 83, "alphanum_fraction": 0.6274285714, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7528141504681304}}
{"text": "# MIT License                                                                    #src\n#                                                                                #src\n# Copyright (c) 2020 François Pacaud                                             #src\n#                                                                                #src\n# Permission is hereby granted, free of charge, to any person obtaining a copy   #src\n# of this software and associated documentation files (the \"Software\"), to deal  #src\n# in the Software without restriction, including without limitation the rights   #src\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell      #src\n# copies of the Software, and to permit persons to whom the Software is          #src\n# furnished to do so, subject to the following conditions:                       #src\n#                                                                                #src\n# The above copyright notice and this permission notice shall be included in all #src\n# copies or substantial portions of the Software.                                #src\n#                                                                                #src\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR     #src\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,       #src\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE    #src\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER         #src\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  #src\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  #src\n# SOFTWARE.                                                                      #src\n\n# # Logistic Regression\n\n# **Originally Contributed by**: François Pacaud\n\n# This tutorial shows how to solve a logistic regression problem\n# with JuMP. Logistic regression is a well known method in machine learning,\n# useful when we want to classify binary variables with the help of\n# a given set of features. To this goal,\n# we find the optimal combination of features maximizing\n# the (log)-likelihood onto a training set. From a modern optimization glance,\n# the resulting problem is convex and differentiable. On a modern optimization\n# glance, it is even conic representable.\n#\n# ## Formulating the logistic regression problem\n#\n# Suppose we have a set of training data-point $i = 1, \\cdots, n$, where\n# for each $i$ we have a vector of features $x_i \\in \\mathbb{R}^p$ and a\n# categorical observation $y_i \\in \\{-1, 1\\}$.\n#\n# The log-likelihood is given by\n#\n# ```math\n# l(\\theta) = \\sum_{i=1}^n \\log(\\dfrac{1}{1 + \\exp(-y_i \\theta^\\top x_i)})\n# ```\n#\n# and the optimal $\\theta$ minimizes the logistic loss function:\n#\n# ```math\n# \\min_{\\theta}\\; \\sum_{i=1}^n \\log(1 + \\exp(-y_i \\theta^\\top x_i)).\n# ```\n#\n# Most of the time, instead of solving directly the previous optimization problem, we\n# prefer to add a regularization term:\n#\n# ```math\n# \\min_{\\theta}\\; \\sum_{i=1}^n \\log(1 + \\exp(-y_i \\theta^\\top x_i)) + \\lambda \\| \\theta \\|\n# ```\n#\n# with $\\lambda \\in \\mathbb{R}_+$ a penalty and $\\|.\\|$ a norm function. By adding\n# such a regularization term, we avoid overfitting on the training set and usually\n# achieve a greater score in cross-validation.\n\n# ## Reformulation as a conic optimization problem\n#\n# By introducing auxiliary variables $t_1, \\cdots, t_n$ and $r$,\n# the optimization problem is equivalent to\n#\n# ```math\n# \\begin{aligned}\n# \\min_{t, r, \\theta} \\;& \\sum_{i=1}^n t_i + \\lambda r \\\\\n# \\text{subject to } & \\quad t_i \\geq \\log(1 + \\exp(- y_i \\theta^\\top x_i)) \\\\\n#                    & \\quad r \\geq \\|\\theta\\|\n# \\end{aligned}\n# ```\n#\n# Now, the trick is to reformulate the constraints $t_i \\geq \\log(1 + \\exp(- y_i \\theta^\\top x_i))$\n# with the help of the *exponential cone*\n#\n# ```math\n# K_{exp} = \\{ (x, y, z) \\in \\mathbb{R}^3 : \\; y \\exp(x / y) \\leq z \\} .\n# ```\n#\n# Indeed, by passing to the exponential, we\n# see that for all $i=1, \\cdots, n$, the constraint $t_i \\geq \\log(1 + \\exp(- y_i \\theta^\\top x_i))$\n# is equivalent to\n#\n# ```math\n# \\exp(-t_i) + \\exp(u_i - t_i) \\leq 1\n# ```\n#\n# with $u_i = -y_i \\theta^\\top x_i$. Then, by adding two auxiliary variables\n# $z_{i1}$ and $z_{i2}$ such that $z_{i1} \\geq \\exp(u_i-t_i)$ and $z_{i2} \\geq \\exp(-t_i)$, we get\n# the equivalent formulation\n#\n# ```math\n# \\left\\{\n# \\begin{aligned}\n# (u_i -t_i , 1, z_{i1}) & \\in  K_{exp}  \\\\\n# (-t_i , 1, z_{i2}) & \\in  K_{exp}  \\\\\n# z_{i1} + z_{i2} & \\leq  1\n# \\end{aligned}\n# \\right.\n# ```\n#\n# In this setting, the conic version of the logistic regression problems writes out\n#\n# ```math\n# \\begin{aligned}\n# \\min_{t, z, r, \\theta}&  \\; \\sum_{i=1}^n t_i + \\lambda r \\\\\n# \\text{subject to } & \\quad  (u_i -t_i , 1, z_{i1})  \\in  K_{exp}  \\\\\n#                    & \\quad  (-t_i , 1, z_{i2})  \\in  K_{exp}  \\\\\n#                    & \\quad  z_{i1} + z_{i2}  \\leq  1 \\\\\n#                    & \\quad u_i = -y_i x_i^\\top \\theta \\\\\n#                    & \\quad r \\geq \\|\\theta\\|\n# \\end{aligned}\n# ```\n#\n# and thus encompasses $3n + p + 1$ variables and $3n + 1$ constraints ($u_i = -y_i \\theta^\\top x_i$\n# is only a virtual constraint used to clarify the notation).\n# Thus, if $n \\gg 1$, we get a large number of variables and constraints.\n\n\n# ## Fitting logistic regression with a conic solver\n#\n# It is now time to pass to the implementation. We choose SCS as a conic solver.\nusing JuMP\nimport Random\nimport SCS\n\nRandom.seed!(2713);\n\n# We start by implementing a function to generate a fake dataset, and where\n# we could tune the correlation between the feature variables. The function\n# is a direct transcription of the one used in [this blog post](http://fa.bianp.net/blog/2013/numerical-optimizers-for-logistic-regression/).\nfunction generate_dataset(n_samples=100, n_features=10; shift=0.0)\n    X = randn(n_samples, n_features)\n    w = randn(n_features)\n    y = sign.(X * w)\n    X .+= 0.8 * randn(n_samples, n_features) # add noise\n    X .+= shift # shift the points in the feature space\n    X = hcat(X, ones(n_samples, 1))\n    return X, y\nend\n\n# We write a `softplus` function to formulate each constraint\n# $t \\geq \\log(1 + \\exp(u))$ with two exponential cones.\nfunction softplus(model, t, u)\n    z = @variable(model, [1:2], lower_bound=0.0)\n    @constraint(model, sum(z) <= 1.0)\n    @constraint(model, [u - t, 1, z[1]] in MOI.ExponentialCone())\n    @constraint(model, [-t, 1, z[2]] in MOI.ExponentialCone())\nend\n\n# ### $\\ell_2$ regularized logistic regression\n# Then, with the help of the `softplus` function, we could write our\n# optimization model. In the $\\ell_2$ regularization case, the constraint\n# $r \\geq \\|\\theta\\|_2$ rewrites as a second order cone constraint.\nfunction build_logit_model(X, y, λ)\n    n, p = size(X)\n    model = Model()\n    @variable(model, θ[1:p])\n    @variable(model, t[1:n])\n    for i in 1:n\n        u = - (X[i, :]' * θ) * y[i]\n        softplus(model, t[i], u)\n    end\n    ## Add ℓ2 regularization\n    @variable(model, 0.0 <= reg)\n    @constraint(model, [reg; θ] in MOI.SecondOrderCone(p+1))\n    ## Define objective\n    @objective(model, Min, sum(t) + λ * reg)\n    return model\nend\n\n# We generate the dataset.\n#\n# !!! warning\n#     Be careful here, for large n and p SCS could fail to converge!\n#\nn, p = 200, 10\nX, y = generate_dataset(n, p, shift=10.0);\n\n## We could now solve the logistic regression problem\nλ = 10.0\nmodel = build_logit_model(X, y, λ)\nset_optimizer(model, SCS.Optimizer)\nJuMP.optimize!(model)\n\n#-\n\nθ♯ = JuMP.value.(model[:θ])\n\n# It appears that the speed of convergence is not that impacted by the correlation\n# of the dataset, nor by the penalty $\\lambda$.\n\n\n# ### $\\ell_1$ regularized logistic regression\n#\n# We now formulate the logistic problem with a $\\ell_1$ regularization term.\n# The $\\ell_1$ regularization ensures sparsity in the optimal\n# solution of the resulting optimization problem. Luckily, the $\\ell_1$ norm\n# is implemented as a set in `MathOptInterface`. Thus, we could easily formulate\n# the sparse logistic regression problem with the help of a `MOI.NormOneCone`\n# set.\nfunction build_sparse_logit_model(X, y, λ)\n    n, p = size(X)\n    model = Model()\n    @variable(model, θ[1:p])\n    @variable(model, t[1:n])\n    for i in 1:n\n        u = - (X[i, :]' * θ) * y[i]\n        softplus(model, t[i], u)\n    end\n    ## Add ℓ1 regularization\n    @variable(model, 0.0 <= reg)\n    @constraint(model, [reg; θ] in MOI.NormOneCone(p+1))\n    ## Define objective\n    @objective(model, Min, sum(t) + λ * reg)\n    return model\nend\n\n## Auxiliary function to count non-null components:\ncount_nonzero(v::Vector; tol=1e-6) = sum(abs.(v) .>= tol)\n\n## We solve the sparse logistic regression problem on the same dataset as before.\nλ = 10.0\nsparse_model = build_sparse_logit_model(X, y, λ)\nset_optimizer(sparse_model, SCS.Optimizer)\nJuMP.optimize!(sparse_model)\n\n#-\n\nθ♯ = JuMP.value.(sparse_model[:θ])\nprintln(\"Number of non-zero components: \", count_nonzero(θ♯),\n        \" (out of \", p, \" features)\")\n\n\n# ### Extensions\n# A direct extension would be to consider the sparse logistic regression with\n# *hard* thresholding, which, on contrary to the *soft* version using a $\\ell_1$ regularization,\n# adds an explicit cardinality constraint in its formulation:\n#\n# ```math\n# \\begin{aligned}\n# \\min_{\\theta} & \\; \\sum_{i=1}^n \\log(1 + \\exp(-y_i \\theta^\\top x_i)) + \\lambda \\| \\theta \\|_2^2 \\\\\n# \\text{subject to } & \\quad \\| \\theta \\|_0 <= k\n# \\end{aligned}\n# ```\n#\n# where $k$ is the maximum number of non-zero components in the vector $\\theta$,\n# and $\\|.\\|_0$ is the $\\ell_0$ pseudo-norm:\n#\n# ```math\n# \\| x\\|_0 = \\#\\{i : \\; x_i \\neq 0\\}\n# ```\n#\n# The cardinality constraint $\\|\\theta\\|_0 \\leq k$ could be reformulated with\n# binary variables. Thus the hard sparse regression problem could be solved\n# by any solver supporting mixed integer conic problems.\n#\n", "meta": {"hexsha": "43a120c6b5027eb55415312c0e0e6da90b16ecdb", "size": 9928, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/logistic_regression.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/logistic_regression.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/logistic_regression.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7490494297, "max_line_length": 141, "alphanum_fraction": 0.6229854956, "num_tokens": 2884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646393, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.752814142821039}}
{"text": "\"\"\"\n# Usage\n\n    solve(α, dx, dt, xStart, xEnd, n, κ, FiniteDiffEx())\n\n!!! tip\n    Here, if we set ``0<\\\\alpha\\\\leq 1``, the equation is the fractional diffusion equation or subdiffusion equation, whereas for ``1<\\\\alpha\\\\leq 2``, the equation is the fractional diffusion-wave equation.\n\nUse explicit Caputo discretization method to solve the diffusion equations.\n\n### References\n\n```tex\n@article{Murillo2011AnED,\n  title={An Explicit Difference Method for Solving Fractional Diffusion and Diffusion-Wave Equations in the Caputo Form},\n  author={Joaqu{\\'i}n Quintana Murillo and Santos B. Yuste},\n  journal={Journal of Computational and Nonlinear Dynamics},\n  year={2011},\n  volume={6},\n  pages={021014}\n}\n```\n\nMatlab version: https://github.com/awstown/Fractional-Derivative\n\"\"\"\nstruct FiniteDiffEx <: FractionalDiffEqAlgorithm end\n\nfunction solve(α, dx, dt, xStart, xEnd, n, κ, u0t, uendt, u0, ::FiniteDiffEx)\n    x = collect(0:dx:xEnd)\n    t = collect(0:dt:n)\n    S = κ*((dt^α)/(dx^2))\n    S_bar = gamma(3-α)*S\n\n    # Preallocate\n    U = zeros(Int64(n/dt + 1), round(Int, (xEnd - xStart)/dx + 1))\n\n    # Boundry conditions\n    U[:, 1] .= u0t\n    U[:, end] .= uendt\n    U[1, :] = u0.(x)\n\n    k = collect(1:length(t)-2)\n    bOfK = bbcoeff(k, α)\n    test = Float64[]\n\n    for m = 1:(length(t)- 1)\n        # It is from 2 to end - 1 because of the boundry conditions\n        U[m+1, 2:end-1], diff = nextStep(U, m, S_bar, test, bOfK)\n    end\n    return U\nend\n\n\n\nfunction bbcoeff(k, α)\n    c = zeros(length(k))\n    for i=1:length(k)\n        if maximum(k) < 2\n            @. c = (k+1)^(1-α) - k^(1-α)\n        else\n            @. c = (k+1)^(2-α) - k^(2-α)\n        end\n    end\n    return c\nend\n\n# Compute values for each time step\nfunction nextStep(U, m, S_bar, diff, bOfK)\n    row_left   = U[m, 1:end-2]\n    row_right  = U[m, 3:end]\n    row_center = U[m, 2:end-1]\n    \n    if m < 2\n        Uspatial = row_center + S_bar*(row_left - 2*row_center + row_right)\n    else\n        row_below  = U[m-1, 2:end-1]\n        Uspatial = 2 * row_center - row_below + S_bar*(row_left - 2*row_center + row_right)\n    end\n\n    if m > 2\n        if length(diff) == 0\n            diff = U[m, 2:end-1] - 2*U[m-1, 2:end-1] + U[m-2, 2:end-1]\n        else\n            diff = [U[m, 2:end-1] .- 2 .*U[m-1, 2:end-1] .+ U[m-2, 2:end-1]; diff]\n        end\n        Utemporal = bOfK[1:length(diff[:, 1])]' * diff\n        Unext = Uspatial .- Utemporal\n    elseif m > 1\n        if length(diff) == 0\n            diff = U[m, 2:end-1] .- U[m-1, 2:end-1]\n        else\n            diff = [U[m, 2:end-1] .- U[m-1,2:end-1]; diff]\n        end\n        Utemporal = bOfK[1:length(diff[:, 1])]' * diff\n        Unext = Uspatial .- Utemporal\n    else\n        Unext = Uspatial\n    end\n    return Unext, diff\nend", "meta": {"hexsha": "81378f130c215c1c4c0b19d3a67ee3e850e256da", "size": 2756, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FPDE/FiniteDiffEx.jl", "max_stars_repo_name": "SciFracX/FractionalDiffEq.jl", "max_stars_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-11-05T12:49:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:57:20.000Z", "max_issues_repo_path": "src/FPDE/FiniteDiffEx.jl", "max_issues_repo_name": "SciFracX/FractionalDiffEq.jl", "max_issues_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-11-01T22:05:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:57:19.000Z", "max_forks_repo_path": "src/FPDE/FiniteDiffEx.jl", "max_forks_repo_name": "SciFracX/FractionalDiffEq.jl", "max_forks_repo_head_hexsha": "740415ccec91b93770db768ba556ac7362722ba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.56, "max_line_length": 207, "alphanum_fraction": 0.5700290276, "num_tokens": 976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896737173119, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.752814141313189}}
{"text": "module _SpecEn\nexport SpecEn\nusing FFTW: fft\nusing DSP: conv\n    \"\"\"\n        Spec, BandEn = SpecEn(Sig) \n\n    Returns the spectral entropy estimate of the full spectrum (`Spec`)\n    and the within-band entropy (`BandEn`) estimated from the data sequence (`Sig`)\n    using the default  parameters: \n    N-point FFT = 2*len(`Sig`) + 1, normalised band edge frequencies = [0 1],\n    logarithm = base 2, normalisation = w.r.t # of spectrum/band frequency values.\n\n        Spec, BandEn = SpecEn(Sig::AbstractArray{T,1} where T<:Real; N::Int=1 + (2*size(Sig,1)), Freqs::Tuple{Real,Real}=(0,1), Logx::Real=exp(1), Norm::Bool=true)\n\n    Returns the spectral entropy (`Spec`) and the within-band entropy (`BandEn`)\n    estimate for the data sequence (`Sig`) using the specified 'keyword' arguments:\n\n    # Arguments:\n    `N`     - Resolution of spectrum (N-point FFT), an integer > 1  \\n\n    `Freqs` - Normalised band edge frequencies, a 2 element tuple with values \\n\n              in range [0 1] where 1 corresponds to the Nyquist frequency (Fs/2).\n              Note: When no band frequencies are entered, BandEn == SpecEn\n    `Logx`  - Logarithm base, a positive scalar (enter 0 for natural log) \\n\n    `Norm`  - Normalisation of `Spec` value:\\n\n              [false]  no normalisation.\n              [true]   normalises w.r.t # of spectrum/band frequency values - default.\n\n    For more info, see the EntropyHub guide.\n\n    # See also `XSpecEn`, `fft`, `MSEn`,  `XMSEn`\n  \n    # References:\n        [1] G.E. Powell and I.C. Percival,\n            \"A spectral entropy method for distinguishing regular and \n            irregular motion of Hamiltonian systems.\" \n            Journal of Physics A: Mathematical and General \n            12.11 (1979): 2053.\n  \n        [2] Tsuyoshi Inouye, et al.,\n            \"Quantification of EEG irregularity by use of the entropy of \n            the power spectrum.\" \n            Electroencephalography and clinical neurophysiology \n            79.3 (1991): 204-210.\n  \n\n    \"\"\"\n    function SpecEn(Sig::AbstractArray{T,1} where T<:Real; N::Int=1 + (2*size(Sig,1)), \n        Freqs::Tuple{Real,Real}=(0,1), Logx::Real=exp(1), Norm::Bool=true)\n        \n    (size(Sig)[1] > 4) ? nothing : error(\"Sig:   must be a numeric vector\")\n    (N > 1) ? nothing :  error(\"N:     must be an integer > 1\")\n    (0<=Freqs[1]<1 && 0<Freqs[2]<=1 && Freqs[1]<Freqs[2]) ? nothing :\n        error(\"Freq:    must be a two element tuple with values in range [0 1].\n                The values must be in increasing order.\")\n    (Logx>0) ? nothing :   error(\"Logx:     must be a positive number > 0\")\n    \n    Freqs = collect(Freqs)\n    Fx = Int(ceil(N/2))\n    Freqs = Int.(round.(Freqs.*Fx))\n    Freqs[Freqs.==0] .= 1\n\n    if Freqs[1] > Freqs[2]\n        error(\"Lower band frequency must come first.\")\n    elseif Freqs[2]-Freqs[1]<1\n        error(\"Spectrum resoution too low to determine bandwidth.\") \n    elseif minimum(Freqs)<0 || maximum(Freqs)>Fx\n        error(\"Freqs must be normalized w.r.t sampling frequency [0 1].\")\n    end\n\n    Temp = conv(Sig,Sig)\n    N <= size(Temp,1) ? Temp = Temp[1:N]  : Temp = vcat(Temp,zeros(N-size(Temp)[1]))\n    \n    Pt = abs.(fft(Temp))\n    Pxx = Pt[1:Fx]/sum(Pt[1:Fx])\n    Spec = -(transpose(Pxx)*log.(Logx, Pxx))\n    Pband = (Pxx[Freqs[1]:Freqs[2]])/sum(Pxx[Freqs[1]:Freqs[2]])\n    BandEn = -(transpose(Pband)*log.(Logx, Pband))\n\n    if Norm\n        Spec = Spec/(log(Logx, Fx));\n        BandEn = BandEn/(log(Logx, Freqs[2]-Freqs[1]+1));\n    end\n\n    return Spec, BandEn\n    end\n\nend\n\n\n\"\"\"\nCopyright 2021 Matthew W. Flood, EntropyHub\n  \nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n     http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nFor Terms of Use see https://github.com/MattWillFlood/EntropyHub\n\n\"\"\"", "meta": {"hexsha": "bb1e9be286ac6b6a126029bb33d5afb3ac5bf86a", "size": 4172, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/_SpecEn.jl", "max_stars_repo_name": "MattWillFlood/EntropyHub.jl", "max_stars_repo_head_hexsha": "d681c7fad3dbddaa708391b0afef1495c7dde20d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-06-19T19:20:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T16:13:41.000Z", "max_issues_repo_path": "src/_SpecEn.jl", "max_issues_repo_name": "MattWillFlood/EntropyHub.jl", "max_issues_repo_head_hexsha": "d681c7fad3dbddaa708391b0afef1495c7dde20d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-06-16T21:57:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T01:10:46.000Z", "max_forks_repo_path": "src/_SpecEn.jl", "max_forks_repo_name": "MattWillFlood/EntropyHub.jl", "max_forks_repo_head_hexsha": "d681c7fad3dbddaa708391b0afef1495c7dde20d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-15T05:41:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T05:41:21.000Z", "avg_line_length": 38.6296296296, "max_line_length": 163, "alphanum_fraction": 0.6311121764, "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7528141381896469}}
{"text": "using LinearAlgebra\nusing Plots\nusing CSV\nusing KernelFunctions\nusing Distributions\nusing DataFrames\n\ninclude(\"../algo/kernels.jl\")\ninclude(\"../algo/regularized_Picard.jl\")\ninclude(\"../algo/utils.jl\")\n\n\"\"\"\n    convergence_exact_solution()\n\nVisualize the convergence of regularized Picard to exact solution (see Proposition 10)\n\"\"\"\nfunction convergence_exact_solution()\n\n    # width\n    sigma = .01\n    # regularizer\n    lambda =  .05\n    # regularizer for positive definiteness\n    epsilon = 1e-10; \n    # relative objective tolerance\n    tol = 1e-6\n\n    ############# load 1 DPP samples #############\n    # intensity of the generating DPP\n    intensity = 100; # 50 or 100\n    strg_intensity = string(intensity)\n    \n    # create an array of arrays\n    indices_DPP_samples = Array{Int64,1}[];\n    \n    print(\"Loading DPP samples from: \\n\")\n    i = 1; # id of the DPP sample\n    file_name = \"data/statspats/samples/GaussDPPsample_alpha0_00p5_rho0_\"*strg_intensity*\"_nb_\"*string(i)*\".csv\"\n    print(file_name, \" \\n\")\n    temp = CSV.File(file_name; header=true) |> Tables.matrix \n    temp = temp[:,2:3]; \n    id_temp = collect(1:size(temp,1));\n    push!(indices_DPP_samples,id_temp);\n    total_samples = temp;\n\n    # for approximating Fredholm determinant\n    indices_Fredholm_sample = indices_DPP_samples[1]\n\n    ############# exact solution #############\n\n    # create full kernel matrix\n    x = (total_samples)'/sigma;\n    k = SqExponentialKernel();\n    K = kernelmatrix(k, x) + epsilon *I ; \n\n    # Chol decomposition\n    R = cholesky(K).U;\n    Rinv = inv(R);\n\n    # Exact solution\n    m = size(K,1);\n    X_exact = 0.5*(real(sqrt(m^2*I + 4*m*K/lambda))-m*I);\n    B_exact = Rinv'*X_exact*Rinv;\n\n    # objective exact solution\n    obj_det_exact,obj_reg_exact = Picard_objective(B_exact, indices_DPP_samples, indices_Fredholm_sample, R,lambda)\n    obj_exact = obj_det_exact + obj_reg_exact;\n\n    ############# approximate solution #############\n\n    # initial positive definite iterate\n    X = randn(size(K));\n    B = X*X'+ UniformScaling(epsilon);\n    \n    use_inverse = false\n\n    n_steps = 50;\n    it_max = 1;\n    err = ones(n_steps,1);\n    obj = ones(n_steps,1);\n\n    for j=1:n_steps\n        B, R, obj_j, i_stop = regularized_Picard(B, K, indices_DPP_samples, indices_Fredholm_sample, lambda, it_max ,tol,use_inverse)\n        err[j] = norm(B-B_exact)/norm(B_exact);\n        obj[j] = obj_j[end];\n    end\n    \n    #############  plotting #############\n\n    plt_error = plot(err, yaxis=:log,legend=false,ylabel = \"relative error\",xlabel = \"iteration\")\n    display(plt_error)\n    \n    plt_obj = plot(obj,legend=false,ylabel = \"objective\",xlabel = \"iteration\")\n    plot!(obj_exact*ones(size(obj)))\n    display(plt_obj)\nend\n", "meta": {"hexsha": "7027b58576c8c385b8940527e34a03eb47513a75", "size": 2720, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demos/convergence_exact_solution.jl", "max_stars_repo_name": "mrfanuel/LearningContinuousDPPs.jl", "max_stars_repo_head_hexsha": "e4d595dadca262278d43f457ed009e1ff2452989", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demos/convergence_exact_solution.jl", "max_issues_repo_name": "mrfanuel/LearningContinuousDPPs.jl", "max_issues_repo_head_hexsha": "e4d595dadca262278d43f457ed009e1ff2452989", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demos/convergence_exact_solution.jl", "max_forks_repo_name": "mrfanuel/LearningContinuousDPPs.jl", "max_forks_repo_head_hexsha": "e4d595dadca262278d43f457ed009e1ff2452989", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0412371134, "max_line_length": 133, "alphanum_fraction": 0.6400735294, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7528141336660973}}
{"text": "import Base.kron\n\n# (A ⊗ B)×vec(X) = vec(BXAᵀ)\n\"\"\"`kron(A, B)`\nKronecker tensor product of A and B in linear operator form, if either\nor both are linear operators. If both A and B are matrices, then\n`Base.kron` is used.\n\"\"\"\nfunction kron(A::AbstractLinearOperator, B::AbstractLinearOperator)\n  m, n = size(A)\n  p, q = size(B)\n  T = promote_type(eltype(A), eltype(B))\n  function prod!(res, x, α, β)\n    S = promote_type(T, eltype(x))\n    X = reshape(convert(Vector{S}, x), q, n)\n    res .= Matrix(B * X * transpose(A))[:]\n  end\n  function tprod!(res, x, α, β)\n    S = promote_type(T, eltype(x))\n    X = reshape(convert(Vector{S}, x), p, m)\n    res .= Matrix(transpose(B) * X * A)[:]\n  end\n  function ctprod!(res, x, α, β)\n    S = promote_type(T, eltype(x))\n    X = reshape(convert(Vector{S}, x), p, m)\n    res .= Matrix(B' * X * conj(A))[:]\n  end\n  symm = issymmetric(A) && issymmetric(B)\n  herm = ishermitian(A) && ishermitian(B)\n  nrow, ncol = m * p, n * q\n  Mv = Vector{T}(undef, nrow)\n  Mtu = symm ? Mv : Vector{T}(undef, ncol)\n  Maw = herm ? Mv : Vector{T}(undef, ncol)\n  return LinearOperator{T}(nrow, ncol, symm, herm, prod!, tprod!, ctprod!, Mv, Mtu, Maw)\nend\n\nkron(A::AbstractMatrix, B::AbstractLinearOperator) = kron(LinearOperator(A), B)\n\nkron(A::AbstractLinearOperator, B::AbstractMatrix) = kron(A, LinearOperator(B))", "meta": {"hexsha": "611dab50bbd0a21a889ba026be461f72c779d1cd", "size": 1328, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kron.jl", "max_stars_repo_name": "geoffroyleconte/LinearOperatorsRevamp.jl", "max_stars_repo_head_hexsha": "972a68aa8b010f1f33b253c208027712b559b221", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-14T19:40:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T19:40:49.000Z", "max_issues_repo_path": "src/kron.jl", "max_issues_repo_name": "geoffroyleconte/LinearOperatorsRevamp.jl", "max_issues_repo_head_hexsha": "972a68aa8b010f1f33b253c208027712b559b221", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-04T20:32:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-04T20:32:01.000Z", "max_forks_repo_path": "src/kron.jl", "max_forks_repo_name": "geoffroyleconte/LinearOperatorsRevamp.jl", "max_forks_repo_head_hexsha": "972a68aa8b010f1f33b253c208027712b559b221", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-06T14:39:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-06T14:39:20.000Z", "avg_line_length": 34.0512820513, "max_line_length": 88, "alphanum_fraction": 0.6310240964, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7527788274755324}}
{"text": "##  Test of fft, power spectrum, and Hilbert transform\n##  using as example of the ElNino time series\n## \n##  Author Bernd Blasius (bernd.blasius@gmail.com)\n\nmodule W\n\nusing CSV, PyPlot, FFTW, Statistics\n\ninclude(\"../src/fft_power.jl\")\n\nfunction test_power_spectrum()\n # read in the data\n  df = CSV.read(\"../data/ElNino_data.csv\"; comment=\"#\") \n  t   = df[:,1]  # time (year)\n  sst = df[:,2]  # el nino signal (sea surface temperature SST)\n  x   = df[:,3]  # el nino temperature anomaly\n\n  fs = 1 ./ (mean(diff(t)))  # mean sampling frequency\n  f, pow = power_real(x,fs)\n\n\n  figure(\"El Nino Power\")\n  clf()\n  subplot(2,1,1)\n  plot(t,x)\n  ylabel(\"El Nino\")\n  xlabel(\"time\")\n\n  subplot(2,1,2)\n  plot(f, log10.(pow))\n  xlabel(\"frequency\")\n  ylabel(\"power\")\n\nend\n\nfunction test_hilbert()\n  # read in the El Nino data\n  df = CSV.read(\"../data/ElNino_data.csv\"; comment=\"#\") \n  t   = df[:,1]  # time (year)\n  sst = df[:,2]  # el nino signal (sea surface temperature SST)\n  x   = df[:,3]  # el nino temperature anomaly\n\n  fs = 1 ./ (mean(diff(t)))  # mean sampling frequency\n  h = hilbert(x,fs)\n\n  figure(\"hilbert\")\n  clf()\n  subplot(2,1,1)  # phase plane\n  plot(t,x)  # El Nino\n  plot(t,h,\"r\") # Hilber transform\n  xlabel(\"time\")\n  ylabel(\"El Nino\")\n\n  subplot(2,1,2)  # phase plane\n  plot(x,h)\n\n\nend\n\n#test_power_spectrum()\ntest_hilbert()\n\nend # module\n\n\n", "meta": {"hexsha": "b1d940f6d95cd3767430f79b32472f413691ea59", "size": 1350, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/power_spectrum.jl", "max_stars_repo_name": "berndblasius/WaveletAnalysis", "max_stars_repo_head_hexsha": "5424602a7e4552cc3d60427c14e61f67bcd9e09b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-01-17T03:16:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-04T17:57:02.000Z", "max_issues_repo_path": "examples/power_spectrum.jl", "max_issues_repo_name": "berndblasius/WaveletAnalysis", "max_issues_repo_head_hexsha": "5424602a7e4552cc3d60427c14e61f67bcd9e09b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/power_spectrum.jl", "max_forks_repo_name": "berndblasius/WaveletAnalysis", "max_forks_repo_head_hexsha": "5424602a7e4552cc3d60427c14e61f67bcd9e09b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-12T09:19:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:19:49.000Z", "avg_line_length": 20.1492537313, "max_line_length": 63, "alphanum_fraction": 0.6266666667, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7527788231149768}}
{"text": "function simpson_integration(x_vec,y_vec)\n    \n    sum = 0.\n    dx = x_vec[2]-x_vec[1]\n\n    #First point\n    sum += 3*y_vec[1]/8 + 3*y_vec[end]/8\n    sum += 7*y_vec[2]/6 + 7*y_vec[end-1]/6\n    sum += 23*y_vec[3]/24 + 23*y_vec[end-2]/24\n\n    for idx in 4:(length(x_vec)-3)\n        sum += y_vec[idx]\n    end\n    return sum*dx\nend\n\nfunction simpson_integration_2D(x_vec,y_vec,z_vec)\n    \n    sum_vector = zeros(length(y_vec))\n\n    for idx in 1:length(sum_vector)\n        sum_vector[idx] = simpson_integration(x_vec,z_vec[:,idx])\n    end\n\n    sum = simpson_integration(y_vec , sum_vector)\n     \n    return sum\nend\n\nfunction get_field_energy( fname::String, every::Int , tlimit::Float64)\n\n    #Get Variables  \n    fid         = h5open( fname , \"r\")\n\n    rmin = read_attribute(fid, \"rmin\")\n    rmax = read_attribute(fid, \"rmax\")\n    rnodes   = read_attribute(fid, \"rnodes\")\n\n    thnodes   = read_attribute(fid, \"thnodes\")\n\n    #Discretize space\n    dr = (rmax - rmin)/(rnodes-1)\n    r = [rmin + (i-1)*dr for i in 1:rnodes]\n    \n    dth = 2*pi/(thnodes)\n    theta = [ (i-1)*dth for i in 1:thnodes]\n\n    #Create Differential Operators \n    Dr  =   Diff_Operator_2D(1 ,1, [dr,dth] , [rnodes,thnodes]) \n    Drr =   Diff_Operator_2D(2 ,1, [dr,dth] , [rnodes,thnodes])\n\n    Dp  =  Diff_Operator_2D_Periodic(1 ,2, [dr,dth] , [rnodes,thnodes]) \n    Dpp =  Diff_Operator_2D_Periodic(2 ,2, [dr,dth] , [rnodes,thnodes])\n    \n    one_over_r  = spzeros(rnodes*thnodes,rnodes*thnodes)\n    r_matrix = spzeros(rnodes*thnodes,rnodes*thnodes)\n\n    for i in 1:rnodes*thnodes\n        one_over_r[i,i] = (1/r[1 + (i-1)%rnodes])\n        r_matrix[i,i] = (r[1 + (i-1)%rnodes])\n    end\n    \n    #Get max time iteration \n    _ , tmax , max_sim_iter  = get_time_variables(fname)    \n    max_plot_iter = max_sim_iter\n\n    if(tlimit <=  tmax)\n        max_plot_iter = floor(Int , max_sim_iter * tlimit/tmax )\n    else\n        println(\"ATTENTION: max time input is larger than simulation time, using tmax\")\n    end\n    \n    # Total volume of space\n    Volume = pi*( rmax^2 - rmin^2)\n    #dV = dx*dy\n    #I_factor = dV / Volume\n\n    #Create storage matrix\n    Energy_matrix = zeros( rnodes , thnodes )\n\n    #Storage vectors\n    E_vector = Float64[]\n    t_vector = Float64[]\n\n    t = 0\n    E = 0\n    \n    #Loop to get energy\n    for i in 0:every:max_plot_iter\n        \n        #Time and fields\n        t, _ , _ , ψ , dψ = get_fields(fname,i)\n        \n        #Gradient term\n        Psi  = reshape(ψ, rnodes*thnodes)\n        dPsi = reshape(dψ, rnodes*thnodes)\n\n        vr = reshape( r_matrix * Drr * Psi ,  (rnodes,thnodes))\n        vp = reshape( r_matrix * one_over_r * Dp * Psi , (rnodes,thnodes))\n        vt = reshape( r_matrix *  dPsi , (rnodes,thnodes))\n\n        Energy_matrix = (vr.^2 .+ vp.^2 .+ vt.^2)\n    \n        E = simpson_integration_2D(r , theta ,Energy_matrix)\n\n        #Add to storage vectors  and normalize\n        push!(t_vector, t)\n        push!(E_vector, E/Volume  )\n\n    end\n\n    return t_vector , E_vector\n\nend", "meta": {"hexsha": "4bfe95cdbe715eda9554345ac0974900d50eb93c", "size": 2991, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/data_read_utils/get_field_energy.jl", "max_stars_repo_name": "diogoribeiro98/Zilindroa.jl", "max_stars_repo_head_hexsha": "d0323ac88745eb282671c52936a543dd8de70093", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/data_read_utils/get_field_energy.jl", "max_issues_repo_name": "diogoribeiro98/Zilindroa.jl", "max_issues_repo_head_hexsha": "d0323ac88745eb282671c52936a543dd8de70093", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/data_read_utils/get_field_energy.jl", "max_forks_repo_name": "diogoribeiro98/Zilindroa.jl", "max_forks_repo_head_hexsha": "d0323ac88745eb282671c52936a543dd8de70093", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2368421053, "max_line_length": 87, "alphanum_fraction": 0.5954530257, "num_tokens": 983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.752778820116455}}
{"text": "s = \"\"\"\n73167176531330624919225119674426574742355349194934\n96983520312774506326239578318016984801869478851843\n85861560789112949495459501737958331952853208805511\n12540698747158523863050715693290963295227443043557\n66896648950445244523161731856403098711121722383113\n62229893423380308135336276614282806444486645238749\n30358907296290491560440772390713810515859307960866\n70172427121883998797908792274921901699720888093776\n65727333001053367881220235421809751254540594752243\n52584907711670556013604839586446706324415722155397\n53697817977846174064955149290862569321978468622482\n83972241375657056057490261407972968652414535100474\n82166370484403199890008895243450658541227588666881\n16427171479924442928230863465674813919123162824586\n17866458359124566529476545682848912883142607690042\n24219022671055626321111109370544217506941658960408\n07198403850962455444362981230987879927244284909188\n84580156166097919133875499200524063689912560717606\n05886116467109405077541002256983155200055935729725\n71636269561882670428252483600823257530420752963450\n\"\"\"\ns2 = replace(s, \"\\n\" => \"\")\na = split(s2, \"\")\na2 = map(x -> parse(Int, x), a)\nlen = length(a2)\n\nwindow = 13\nmaxsofar = 0\nfor i = 1:(len-window+1)\n  global maxsofar\n  p = prod(a2[i:i+window-1])\n  maxsofar = max(maxsofar, p)\nend\nprintln(maxsofar)\n", "meta": {"hexsha": "55cad7adfc88020ec0096efac21d756f92b01f24", "size": 1277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ans8.jl", "max_stars_repo_name": "sujimodern/project-euler-jl", "max_stars_repo_head_hexsha": "7abbf39014cc39b39ed84ebf698d45d09fadea1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ans8.jl", "max_issues_repo_name": "sujimodern/project-euler-jl", "max_issues_repo_head_hexsha": "7abbf39014cc39b39ed84ebf698d45d09fadea1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ans8.jl", "max_forks_repo_name": "sujimodern/project-euler-jl", "max_forks_repo_head_hexsha": "7abbf39014cc39b39ed84ebf698d45d09fadea1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4722222222, "max_line_length": 50, "alphanum_fraction": 0.8981989037, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678381, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7527788151023276}}
{"text": "# Demonstrate NTF synthesis (synthesizeNTF)\nusing RSDeltaSigmaPort\nj=im\n\n\n#==Baseband modulator\n===============================================================================#\nprintln(\"\\n*** 5th order, 2-level, baseband modulator\")\nOSR = 32\n\n@info(\"Synthesizing NTF without zero-optimization...\"); flush(stdout); flush(stderr)\n#-------------------------------------------------------------------------------\nNTF_noopt = synthesizeNTF(5, OSR, opt=0)\nprintln(\"\\tdone.\")\n\nplot = plotNTF(NTF_noopt, OSR, color=:blue)\nplot.title = \"5th-Order Modulator (No Zero-Optimization)\"\nsaveimage(:png, \"dsdemo1_o5_noopt.png\", plot, AR=2/1, width=900)\ndisplaygui(plot)\n\n@info(\"Synthesizing NTF with optimized zeros...\"); flush(stdout); flush(stderr)\n#-------------------------------------------------------------------------------\nNTF_opt = synthesizeNTF(5, OSR, opt=1)\nprintln(\"\\tdone.\")\n\nplot = plotNTF(NTF_opt, OSR, color=:red)\nplot.title = \"5th-Order Modulator (Optimized Zeros)\"\nsaveimage(:png, \"dsdemo1_o5_zopt.png\", plot, AR=2/1, width=900)\ndisplaygui(plot)\n\n@info(\"Plotting NTF comparison (overlay results)\")\n#-------------------------------------------------------------------------------\nplot = plotNTF(NTF_noopt, OSR, color=:blue)\nplot = plotNTF!(plot, NTF_opt, OSR, color=:red)\nplot.title = \"5th-Order Modulator (Optimized Zeros - Overlay)\"\nsaveimage(:png, \"dsdemo1_o5_cmp.png\", plot, AR=2/1, width=900)\ndisplaygui(plot)\n\n\n#==Bandpass modulator\n===============================================================================#\nprintln(\"\\n*** 8th order, 2-level, bandpass modulator\")\nOSR = 64\norder = 8\nf0 = 0.125 #fs/8\n\nfunction calcSTF(order, OSR, NTF, f0)\n\tG = _zpk(zeros(array_round(order/2)),NTF.p,1,1)\n\tG.k = 1/abs(evalTF(G,exp(2π*j*f0)))\n\treturn G\nend\n\n@info(\"Synthesizing NTF...\"); flush(stdout); flush(stderr)\n#-------------------------------------------------------------------------------\nNTF = synthesizeNTF(order, OSR, opt=2, f0=f0)\nprintln(\"\\tdone.\")\n\n@info(\"Plotting NTF\")\n#-------------------------------------------------------------------------------\nSTF = calcSTF(order, OSR, NTF, f0)\nplot = plotNTF(NTF, OSR, color=:blue, f0=f0, STF=STF)\nplot.title = \"8th-Order Bandpass Modulator\"\nsaveimage(:png, \"dsdemo1_o8_bp.png\", plot, AR=2/1, width=900)\ndisplaygui(plot)\n\n:END_OF_DEMO\n", "meta": {"hexsha": "8812811bb4ea1d279917e0038218ee459060634f", "size": 2290, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "sample/dsdemo1.jl", "max_stars_repo_name": "ma-laforge/RSDeltaSigmaPort.jl", "max_stars_repo_head_hexsha": "eae547513db458327ca1f25fa734325d0456842b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-06-16T17:34:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T03:38:31.000Z", "max_issues_repo_path": "sample/dsdemo1.jl", "max_issues_repo_name": "ma-laforge/RSDeltaSigmaPort.jl", "max_issues_repo_head_hexsha": "eae547513db458327ca1f25fa734325d0456842b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-05-08T15:16:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T03:37:27.000Z", "max_forks_repo_path": "sample/dsdemo1.jl", "max_forks_repo_name": "ma-laforge/RSDeltaSigmaPort.jl", "max_forks_repo_head_hexsha": "eae547513db458327ca1f25fa734325d0456842b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1791044776, "max_line_length": 84, "alphanum_fraction": 0.5379912664, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7527788113953435}}
{"text": "# Largest prime factor\n\nNUMBER = 600_851_475_143\n\n\nfunction solve()\n    n = NUMBER\n    i = 2\n    while n > 1\n        if n % i == 0\n            n /= i\n        else\n            i += 1\n        end\n    end\n    return i\nend\n\n\nprint(Int(solve()))\n", "meta": {"hexsha": "c4299ae401a29ee39ed86d74e2f884b5e057ee00", "size": 241, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/p003.jl", "max_stars_repo_name": "wephy/project-euler", "max_stars_repo_head_hexsha": "cc4824478282d3e1514a1bf7a1821b938db5bfcb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/p003.jl", "max_issues_repo_name": "wephy/project-euler", "max_issues_repo_head_hexsha": "cc4824478282d3e1514a1bf7a1821b938db5bfcb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-07T19:03:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-07T19:03:35.000Z", "max_forks_repo_path": "julia/p003.jl", "max_forks_repo_name": "wephy/project-euler", "max_forks_repo_head_hexsha": "cc4824478282d3e1514a1bf7a1821b938db5bfcb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.4761904762, "max_line_length": 24, "alphanum_fraction": 0.4564315353, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333005, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7527788055629722}}
{"text": "#=\nThe power set of a set is the set of all its subsets. Write a function that, given a set, generates its power set.\n\nFor example, given the set {1, 2, 3}, it should return {{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}.\n\nYou may also use a list or array to represent a set.\n=#\n\nfunction get_powerset(set::Array{Int,1})\n    powerset = [[]]\n    for number in set\n        push!(powerset, [number])\n    end\n    set_length = 1\n    while set_length < length(set)\n        newpowerset = copy(powerset)\n        for arr_index in eachindex(powerset)\n            arr = powerset[arr_index]\n            for number in set\n                if length(arr) == set_length && !in(number, arr) && number > arr[end]\n                    new_array = union(arr, number)\n                    push!(newpowerset, new_array)\n                end\n            end\n        end\n        powerset = newpowerset\n        set_length = set_length + 1\n    end\n    return powerset\nend\n", "meta": {"hexsha": "7a142148d32de081762ff2a381563b41031642b5", "size": 951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/problem37_generate_powerset.jl", "max_stars_repo_name": "DominiqueCaron/daily-coding-problem", "max_stars_repo_head_hexsha": "41234497aa3a2c21c5dff43d86e9153d9582cced", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Solutions/problem37_generate_powerset.jl", "max_issues_repo_name": "DominiqueCaron/daily-coding-problem", "max_issues_repo_head_hexsha": "41234497aa3a2c21c5dff43d86e9153d9582cced", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2019-06-17T14:04:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-12T20:01:45.000Z", "max_forks_repo_path": "Solutions/problem37_generate_powerset.jl", "max_forks_repo_name": "DominiqueCaron/daily-coding-problem", "max_forks_repo_head_hexsha": "41234497aa3a2c21c5dff43d86e9153d9582cced", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6774193548, "max_line_length": 114, "alphanum_fraction": 0.5625657203, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7527612284492142}}
{"text": "function issquarefree{I<:Integer}(d::I)\n  # factor(d) is a dictionary whose keys are primes\n  # and whose values are corresponding prime powers.\n  # An integer is square free iff none of its prime\n  # factors have power 2 or greater. This is equivalent\n  # to its Mobius function being nonzero.\n  mobius(d) != 0\nend\n\n\"\"\"\n\n[Link](https://proofwiki.org/wiki/Definition:M%C3%B6bius_Function)\n\"\"\"\nfunction mobius{I<:Integer}(n::I)\n  if n==1 return I(1) end\n  powers = collect(values(factor(n)))\n  return all(powers.== 1) ? I(-1)^length(powers) : I(0)\nend\n\n\n#  Division by monic polynomials\n\nfunction onestep!{I<:Integer}(num::Array{I,1}, den::Array{I,1}, quo::Array{I,1})\n  n = findlast(num .!= 0)\n  d = findlast(den .!= 0)\n  den[d] == 1 || error(\"denominator is not monic\")\n  k = n-d\n  k >= 0 || error(\"numerator not divisible by denominator\")\n  quo[1+k] += num[n]\n  for i=1:d\n    num[i+k] -= num[n]*den[i]\n  end\nend\n\nfunction divide_by_monic{I<:Integer}(num::Array{I,1}, den::Array{I,1}) \n  cnum = deepcopy(num)\n  quo = zeros(I,length(num))\n  while any(cnum .!= 0)\n    onestep!(cnum, den, quo)\n  end\n  quo\nend\n\nfunction cyclotomic{I<:Integer}(n::I)\n  n >= 1 || error(\"There is no cyclotomic of degree < 1\")\n  if n==1\n    return [I(-1), I(1)]\n  end\n  num = zeros(I,n+1)\n  num[n+1]=I(1)\n  num[1] = I(-1)\n  for d in 1:(n-1)\n    if n%d == 0\n      num = divide_by_monic(num, cyclotomic(d))\n    end\n  end\n  d = findlast(num .!= 0)\n  num[1:d]\nend\n", "meta": {"hexsha": "c993caeb2985582b39ba07d8829ec90ec00f7d07", "size": 1438, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utilities.jl", "max_stars_repo_name": "WilCrofter/ZAdjoin", "max_stars_repo_head_hexsha": "3c37d4e10c8c98090ef90c226efd44e8a82770d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utilities.jl", "max_issues_repo_name": "WilCrofter/ZAdjoin", "max_issues_repo_head_hexsha": "3c37d4e10c8c98090ef90c226efd44e8a82770d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utilities.jl", "max_forks_repo_name": "WilCrofter/ZAdjoin", "max_forks_repo_head_hexsha": "3c37d4e10c8c98090ef90c226efd44e8a82770d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9666666667, "max_line_length": 80, "alphanum_fraction": 0.6244784423, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7527612267663385}}
{"text": "# # Mesh with implicit geometry\n\n# In this tutorial, we will learn\n# \n#    -  How to create a mesh of hexahedra.\n#    -  How to create a mesh using an implicit definition of the geometry.\n\n# The geometry is a ramp in the form of 3/4 part of a circle.\n\n# The tutorial will produce files for mesh visualization in the \n# [Paraview](https://www.paraview.org/) format (VTK). One can display this\n# information by loading the file with `paraview.exe`. When the tutorial is\n# executed in `mybinder.org`, the graphics file needs to be downloaded to your\n# desktop, and then visualized locally.\n\n# We shall use static arrays for the connectivities and the coordinates.\nusing StaticArrays\n\n# We start with a parametric domain: a rectangular block, with dimensions of\n# different physical units. The extent of the domain: the first\n# coordinate is angular. The next two coordinates are in the plane generating\n# section.\nL, W, H = 1.5*pi, 3.0, 1.5\nR = 4.0\n\n# This is the number of element edges along each dimension.\nM, N, K = 13, 4, 2\n\n# Now we define the indexing of the vertices. The linear index converts the\n# triple of indexes along the three dimensions into a single number. the\n# dimensions correspond to the number of nodes along direction.\nlinix = LinearIndices((M+1, N+1, K+1))\n# The serial-number function converts the triple of indexes into a single linear\n# index.\nsn(m, n, k) = linix[m, n, k]\n\n# Now we create the connectivities of the individual hexahedral cells. The\n# numbering is given by the topologically regular character of the block domain.\nC = SVector{8, Int}[]\nfor k in 1:K, n in 1:N, m in 1:M\n    c = (\n        sn(m, n, k), sn(m+1, n, k), sn(m+1, n+1, k), sn(m, n+1, k), \n        sn(m, n, k+1), sn(m+1, n, k+1), sn(m+1, n+1, k+1), sn(m, n+1, k+1)\n        )\n    push!(C, SVector{8, Int}(c))\nend\n\n# The locations of the vertices is also perfectly regular within the parametric\n# domain. The nodes are distributed uniformly along each direction. the location\n# in the physical space is computed from the parametric coordinates: the first\n# coordinate is used as an angle, and `R` is the interior radius of the circular\n# ramp.\nloc = SVector{3, Float64}[]\nfor k in 1:K+1, n in 1:N+1, m in 1:M+1\n    a = (m-1)/M*L\n    x, y, z = (R+(n-1)/N*W) * cos(a), (R+(n-1)/N*W) * sin(a), (k-1)/K*H * (1 + a)\n    push!(loc, SVector{3, Float64}(x, y, z))\nend\n\n# At this point we can create the shape collections.\nusing MeshCore: ShapeColl, H8, P1\n# This is the collection of hexahedral shapes.\nelements = ShapeColl(H8, length(C), \"elements\")\n# And this is the collection of the vertices.\nvertices = ShapeColl(P1, length(loc), \"vertices\")\n\n# The geometry is attached is an attribute. Here we use vector attribute which\n# actually stores three coordinates per vertex.\nusing MeshCore: VecAttrib\nvertices.attributes[\"geom\"] = VecAttrib(loc)\nusing MeshCore: IncRel\nconnectivities = IncRel(elements, vertices, C)\n\n# We now write out a postprocessing file with the elements. Note that we pass\n# the `connectivities` incidence relation to get the elements stored in the\n# file.\nusing MeshSteward: vtkwrite\nvtkwrite(\"block\", connectivities)\n\n# Now we will define another shape collection. This one will refer to geometry\n# defined implicitly: through a function that returns the coordinates  of a\n# vertex based on its serial number. Remember that serial numbers are stored in\n# the connectivities.\n\nvertices2 = ShapeColl(P1, prod((M+1, N+1, K+1)), \"vertices2\")\n\n# The Cartesian indices will allow us to map the linear index to a Cartesian\n# triple of indices.\ncart = CartesianIndices((M+1, N+1, K+1))\nusing MeshCore: FunAttrib\n\n# Note that this function defines the same geometry in physical space as the\n# loop above. However, the geometry is not stored, it is returned as a triple of\n# numbers.\naccess_location(i) = let \n    ci  = cart[i]\n    m, n, k = ci[1], ci[2], ci[3]\n    a = (m-1)/M*L\n    x, y, z = (R+(n-1)/N*W) * cos(a), (R+(n-1)/N*W) * sin(a), (k-1)/K*H * (1 + a)\n    SVector{3, Float64}(x, y, z)\nend\n\n# The geometry attribute is defined by providing access to the locations of the\n# vertices through the function `access_location`.\nvertices2.attributes[\"geom\"] = FunAttrib(0.0, prod((M+1, N+1, K+1)), access_location);\nconnectivities = IncRel(elements, vertices2, C)\nvtkwrite(\"block2\", connectivities)\n\n# Now both data sets have been written out. Load them into\n# [Paraview](https://www.paraview.org/) and it should be possible to verify that\n# those two meshes sets overlap perfectly.\n\ntrue\n", "meta": {"hexsha": "670bec6be435b33c1bdb82b73bf44278e39347f0", "size": 4494, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "deps/tutorial9.jl", "max_stars_repo_name": "PetrKryslUCSD/MeshTutor.jl", "max_stars_repo_head_hexsha": "42cb206396052cd2ba1c5c05fe55ab77e36833ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-17T00:32:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T00:32:58.000Z", "max_issues_repo_path": "deps/tutorial9.jl", "max_issues_repo_name": "PetrKryslUCSD/MeshTutor.jl", "max_issues_repo_head_hexsha": "42cb206396052cd2ba1c5c05fe55ab77e36833ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/tutorial9.jl", "max_forks_repo_name": "PetrKryslUCSD/MeshTutor.jl", "max_forks_repo_head_hexsha": "42cb206396052cd2ba1c5c05fe55ab77e36833ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4210526316, "max_line_length": 86, "alphanum_fraction": 0.7089452603, "num_tokens": 1303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7527612113718547}}
{"text": "# Example of MLE estimation. The data is really drawn from the\n# Logit DGP, so the model is well specified, and the MLE has\n# the properties discussed in class. E.g., if you make n very\n# large you should see that the estimator is very close to the\n# true value of theta used to generate data\n\nusing Econometrics\ninclude(\"LogitDGP.jl\")\nn = 30 # sample size\ntheta = [0, 0.5] # true theta for generating data\n(y, x) = LogitDGP(n, theta) # generate the data\n\n# now define things for estimation\nmodel = theta -> logit(theta, y, x)\ntheta = zeros(size(x,2)) # start values for estimation\n\n# Perform the estimation - Make sure that you examine\n# the MLE estimation programs so that you see how this works\nthetahat, objvalue, V, converged = mleresults(model, theta, \"estimate logit model\");\n\n", "meta": {"hexsha": "3e789fabec284d38a258702a3b24bf3055f19c2e", "size": 784, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/MLE/EstimateLogit.jl", "max_stars_repo_name": "nilshg/Econometrics", "max_stars_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "Examples/MLE/EstimateLogit.jl", "max_issues_repo_name": "nilshg/Econometrics", "max_issues_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "Examples/MLE/EstimateLogit.jl", "max_forks_repo_name": "nilshg/Econometrics", "max_forks_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 37.3333333333, "max_line_length": 84, "alphanum_fraction": 0.737244898, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9585377284730286, "lm_q2_score": 0.7853085884247212, "lm_q1q2_score": 0.7527479104989928}}
{"text": "export getLaplacianMatrix, getConvectionMatrix\n\n\"\"\"\nfunction ddxc(n)\n\ncentered one-dimensional finite difference operator.\n\nInput: \n\n    n  - number of cells\n\nOutput:\n\n    dx - sparse matrix for 1D derivative size(dx) = (n,n)\n\"\"\"\nfunction ddxc(n::Int)\n    dx = spdiagm(-1=>fill(-1.0,n-1), 1=>fill(1.0,n-1))    \n    return dx\nend\n\n\"\"\"\nfunction ddxfwd(n)\n\nforward one-dimensional finite difference operator.\n\nInput: \n\n    n  - number of cells\n\nOutput:\n\n    dx - sparse matrix for 1D derivative size(dx) = (n,n)\n\"\"\"\nfunction ddxfwd(n::Int)\n    dx = spdiagm(0=>fill(-1.0,n),1=>fill(1.0,n-1))    \n    return dx\nend\n\n\"\"\"\nfunction ddxbwd(n)\n\nbackward one-dimensional finite difference operator.\n\nInput: \n\n    n  - number of cells\n\nOutput:\n\n    dx - sparse matrix for 1D derivative size(dx) = (n,n)\n\"\"\"\nfunction ddxbwd(n::Int)\n    dx = spdiagm(-1=>fill(-1.0,n-1),0=>fill(1.0,n))    \n    return dx\nend\n\n\"\"\"\nfunction getLaplacian(M::RegularMesh)\n\nbuilds 2D/3D Laplacian for padded cell-centered vector including\nghost points and corners.\n\nInput:\n\n\tM  - computational mesh\n\t\nOutput:\n\n\tLap - 2D/3D Laplacian\n\n\"\"\"\nfunction getLaplacianMatrix(M::RegularMesh)\n    if M.dim==2\n\t\tdx = Mesh.ddx(M.n[1]+1)/M.h[1]\n\t\tdy = Mesh.ddx(M.n[2]+1)/M.h[2]\n\t\t\n\t\tDxx = kron(sparse(1.0I,M.n[2]+2, M.n[2]+2),dx'*dx)\n\t\tDyy = kron(dy'*dy, sparse(I, M.n[1]+2, M.n[1]+2))\n\t\treturn Dxx+Dyy\n\telseif M.dim==3\n\t\tdx = Mesh.ddx(M.n[1]+1)/M.h[1]\n\t\tdy = Mesh.ddx(M.n[2]+1)/M.h[2]\n\t\tdz = Mesh.ddx(M.n[3]+1)/M.h[3]\n\t\t\n\t\tDxx = kron(sparse(1.0I, M.n[3]+2, M.n[3]+2),kron(sparse(1.0I, M.n[2]+2, M.n[2]+2),dx'*dx))\n\t\tDyy = kron(sparse(1.0I, M.n[3]+2, M.n[3]+2),kron(dy'*dy, sparse(1.0I, M.n[1]+2, M.n[1]+2)))\n\t\tDzz = kron(dz'*dz, kron(sparse(1.0I, M.n[2]+2, M.n[2]+2), sparse(1.0I, M.n[1]+2, M.n[1]+2)))\n\t\t\n\t\treturn Dxx + Dyy + Dzz\n\tend\nend\n\n\"\"\"\nfunction getConvectionMatrix(M,v)\n\t\nbuilds stationary convection operator on extended mesh\n\n2D: C(v_1,v_2)     = Diagonal(v_1)*Dx + Diagonal(v_2)*Dy\n\n3D: C(v_1,v_2,v_3) = Diagonal(v_1)*Dx + Diagonal(v_2)*Dy + Diagonal(v_3)*Dz\n\n\n\nInput:\n\n\tM :: RegularMesh - original domain (not padded)\n\tv                - velocities discretized on cell-centers of extended mesh\n\t \t\t\t\t   or function that returns values (X -> vFun) where \n\t\t\t\t\t   X has x,y(,z) coordinates column wise.\n\t\nOutput:\n\n\tConv - 2D Convection operator\n\n\"\"\"\nfunction getConvectionMatrix(M::RegularMesh,v::Array{Float64})\n\n\tn   = M.n\n\th   = M.h\n\tdim = M.dim\n\tv  = reshape(v,prod(n.+2),dim)\n\n\tif dim==2\n    \tdxf = ddxfwd(n[1]+2)./(h[1])\n    \tdxb = ddxbwd(n[1]+2)./(h[1])\n    \tdyf = ddxfwd(n[2]+2)./(h[2])\n    \tdyb = ddxbwd(n[2]+2)./(h[2])\n    \t\n    \tDxf = kron(sparse(1.0I, n[2]+2, n[2]+2), dxf)\n    \tDxb = kron(sparse(1.0I, n[2]+2, n[2]+2), dxb)\n    \tDyf = kron(dyf, sparse(1.0I, n[1]+2, n[1]+2))\n    \tDyb = kron(dyb, sparse(1.0I, n[1]+2, n[1]+2))\n    \treturn Diagonal(max.(v[:,1],0))*Dxb + Diagonal(min.(v[:,1],0))*Dxf + \n\t\t       Diagonal(max.(v[:,2],0))*Dyb + Diagonal(min.(v[:,2],0))*Dyf\n\telseif dim==3\n\t\tdxf = ddxfwd(n[1]+2)./(M.h[1])\n\t\tdxb = ddxbwd(n[1]+2)./(M.h[1])\n\t\tdyf = ddxfwd(n[2]+2)./(M.h[2])\n\t\tdyb = ddxbwd(n[2]+2)./(M.h[2])\n\t\tdzf = ddxfwd(n[3]+2)./(M.h[3])\n\t\tdzb = ddxbwd(n[3]+2)./(M.h[3])\n    \n\t\tDxf = kron(sparse(1.0I, n[3]+2, n[3]+2),kron(sparse(1.0I, n[2]+2, n[2]+2), dxf));\n\t\tDxb = kron(sparse(1.0I, n[3]+2, n[3]+2),kron(sparse(1.0I, n[2]+2, n[2]+2), dxb));\n\t\tDyf = kron(sparse(1.0I, n[3]+2, n[3]+2),kron(dyf, sparse(1.0I, n[1]+2, n[1]+2)))\n\t\tDyb = kron(sparse(1.0I, n[3]+2, n[3]+2),kron(dyb, sparse(1.0I, n[1]+2, n[1]+2)))\n\t\tDzf = kron(dzf, sparse(1.0I, prod(n[1:2].+2), prod(n[1:2].+2)))\n\t\tDzb = kron(dzb, sparse(1.0I, prod(n[1:2].+2), prod(n[1:2].+2)))\n    \treturn Diagonal(max.(v[:,1],0))*Dxb + Diagonal(min.(v[:,1],0))*Dxf + \n               Diagonal(max.(v[:,2],0))*Dyb + Diagonal(min.(v[:,2],0))*Dyf +\n               Diagonal(max.(v[:,3],0))*Dzb + Diagonal(min.(v[:,3],0))*Dzf \n\tend\nend\n\t\nfunction getConvectionMatrix(M::RegularMesh,v::Function)\n\txc = getNodalGrid(getPaddedMesh(M))\n\treturn getConvectionMatrix(M,v(xc))\nend", "meta": {"hexsha": "a75323295b88163a6d483d04c2bd12f5b2b5266c", "size": 4001, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/getDiffOps.jl", "max_stars_repo_name": "JuliaInv/ConvDiffMIPDECO", "max_stars_repo_head_hexsha": "95a3aead09d34811c4c2ca14279df93a0b40ecdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-16T19:08:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T19:08:09.000Z", "max_issues_repo_path": "src/getDiffOps.jl", "max_issues_repo_name": "JuliaInv/ConvDiffMIPDECO", "max_issues_repo_head_hexsha": "95a3aead09d34811c4c2ca14279df93a0b40ecdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/getDiffOps.jl", "max_forks_repo_name": "JuliaInv/ConvDiffMIPDECO", "max_forks_repo_head_hexsha": "95a3aead09d34811c4c2ca14279df93a0b40ecdb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:13:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:13:38.000Z", "avg_line_length": 25.3227848101, "max_line_length": 94, "alphanum_fraction": 0.5823544114, "num_tokens": 1672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7527431615753366}}
{"text": "using SellmeierFit\nusing SimpleConstants  # for micro = 1e-6\nusing CairoMakie\n\n## Main section\n# Load a set of measured refractive index data from https://RefractiveIndex.info.\npath = \"https://refractiveindex.info/tmp/data/main/SiO2/Malitson.csv\"\n(; λ, ε) = SellmeierFit.read(path)\n\n# Fit the loaded data to the Sellmeier equation.\n(; mdl, err) = fit_sellmeier(λ, ε)\n\n## Analysis section\n# The calculated fit parameters are the same as those shown in RefractiveIndex.info's\n# Dispersion formula section.\nprintln(\"B = $(mdl.str)\")\nprintln(\"√C (µm) = $(mdl.λres ./ micro)\")\nprintln(\"Error between data and fit = $err\")\n\n# Visualize the measured data and fit Sellmeier equation; note that n = √ε.\nfontsize = 20\nfig = Figure(; fontsize)\nAxis(fig[1,1], title=\"Refractive Index of SiO₂\", xlabel=\"λ (meter)\", ylabel=\"n\")\nscatter!(λ, .√ε, label=\"Measurement\", color=:black)\nlines!(λ, .√mdl.(λ), label=\"Sellmeier equation\", color=:red)\naxislegend(; position=:rt)\ndisplay(fig)\n", "meta": {"hexsha": "bac1d60151be0eee042e527c701ca237a571e18a", "size": 967, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/from_web.jl", "max_stars_repo_name": "wsshin/SellmeierFit.jl", "max_stars_repo_head_hexsha": "ab75213107255d4d4dacfb7c341db86c968530d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-12-27T18:35:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:50:04.000Z", "max_issues_repo_path": "example/from_web.jl", "max_issues_repo_name": "wsshin/SellmeierFit.jl", "max_issues_repo_head_hexsha": "ab75213107255d4d4dacfb7c341db86c968530d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-12-24T20:13:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T01:56:36.000Z", "max_forks_repo_path": "example/from_web.jl", "max_forks_repo_name": "wsshin/SellmeierFit.jl", "max_forks_repo_head_hexsha": "ab75213107255d4d4dacfb7c341db86c968530d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5357142857, "max_line_length": 85, "alphanum_fraction": 0.7176835574, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642554, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7527431469202568}}
{"text": "using Distributions, Plots; pyplot()\n\nalpha, beta = 8, 2\nprior(lam) = pdf(Gamma(alpha, 1/beta), lam)\ndata = [2,1,0,0,1,0,2,2,5,2,4,0,3,2,5,0]\n\nlike(lam) = *([pdf(Poisson(lam),x) for x in data]...)\nposteriorUpToK(lam) = like(lam)*prior(lam)\n\nsig = 0.5\nfoldedNormalPDF(x,mu) = (1/sqrt(2*pi*sig^2))*(exp(-(x-mu)^2/2sig^2)\n                                                + exp(-(x+mu)^2/2sig^2))\nfoldedNormalRV(mu) = abs(rand(Normal(mu,sig)))\n\nfunction sampler(piProb,qProp,rvProp)\n    lam = 1\n    warmN, N = 10^5, 10^6\n    samples = zeros(N-warmN)\n\n    for t in 1:N\n        while true\n            lamTry = rvProp(lam)\n            L = piProb(lamTry)/piProb(lam)\n            H = min(1,L*qProp(lam,lamTry)/qProp(lamTry,lam))\n            if rand() < H\n                lam = lamTry\n                if t > warmN\n                    samples[t-warmN] = lam\n                end\n                break\n            end\n        end\n    end\n    return samples\nend\n\nmcmcSamples = sampler(posteriorUpToK,foldedNormalPDF,foldedNormalRV)\nprintln(\"MCMC Bayes Estimate: \",mean(mcmcSamples))\n\nstephist(mcmcSamples, bins=100, \n\tc=:black, normed=true, label=\"Histogram of MCMC samples\")\n\nlamRange = 0:0.01:10\nplot!(lamRange, prior.(lamRange), \n\tc=:blue, label=\"Prior distribution\")\n\nclosedFormPosterior(lam)=pdf(Gamma(alpha + sum(data),1/(beta+length(data))),lam)\nplot!(lamRange, closedFormPosterior.(lamRange), \n\tc=:red, label=\"Posterior distribution\", \n\txlims=(0, 10), ylims=(0, 1.2),\n    xlabel=L\"\\lambda\",ylabel=\"Density\")", "meta": {"hexsha": "0ab3aaaf0e05c7182601688899fbf0e63b65cb0e", "size": 1500, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5_chapter/bayesMCMC.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "5_chapter/bayesMCMC.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "5_chapter/bayesMCMC.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 29.4117647059, "max_line_length": 80, "alphanum_fraction": 0.5853333333, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878722, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7527431370601876}}
{"text": "\nusing Plots\nusing LinearAlgebra\n\nx = 3 # True slope\na = -2:.25:2\nb = a*x + randn(length(a)) # Add noise\n\np1 = plot(a, x*a, label = \"True line\") # True relationship\nscatter!(a, b, label = \"Noisy data\") # Noisy measurements\n\nU, S, V = svd(reshape(collect(a), length(a), 1))\nxtilde = (V*inv(diagm(S))*U'*b)[1] # Least-square fit\n\nplot!(a, xtilde*a, label = \"Regression line\") # Plot fit", "meta": {"hexsha": "1ffd55f6890b1d9988733b803882cef63be863e3", "size": 384, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ddsae/CODE/CH01/CH01_SEC04_1_Linear.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "ddsae/CODE/CH01/CH01_SEC04_1_Linear.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "ddsae/CODE/CH01/CH01_SEC04_1_Linear.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 25.6, "max_line_length": 58, "alphanum_fraction": 0.6380208333, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191309994468, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7527257403515909}}
{"text": "function getergodic(transmatrix::Array{Float64,2})\n    D,V = eig(transmatrix')\n    eigindex = indmin(abs.(D-1.0))\n    ergodic = vec(V[:,eigindex]/sum(V[:,eigindex]))\n    if any(abs.(imag(ergodic)).>1e-16)\n        error(\"Imaginary ergodic distribution\")\n    else\n        return real(ergodic)\n    end\nend\n\nfunction createtransmatrix_sym(numregimes::Int)\n    out = Array{SymPy.Sym}(numregimes)\n    for j = 1:numregimes\n        out[j] = Sym(\"TRANSITIONPROBABILITY_RX_RP$(j)\")\n    end\n    return out\nend\n\nfunction TransitionMatrix(trans)\n    # Sanity check the regime transition matrix\n    numregimes = size(trans,1)\n    if size(trans,2)!=size(trans,1)\n        error(\"Regime transition matrix is not square.\")\n    end\n    if any((abs.(sum(trans,2))-1.0).>1e-12)\n        error(\"Rows of the regime transition matrix do not sum to 1.\")\n    end\n    # Create a sympy version of the regime trans matrix\n    syms = createtransmatrix_sym(numregimes)\n        \n    # Get the ergodic distribution of the markovian regime process\n    ergodic = getergodic(trans)\n    return TransitionMatrix(trans,syms,ergodic,Sym(\"TRANSITIONPROBABILITY\"))\nend\n", "meta": {"hexsha": "794e9a4f56bf83903298835226c066451a783195", "size": 1126, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/constructor/transmatrix.jl", "max_stars_repo_name": "angusmoore/RSDSGE.jl", "max_stars_repo_head_hexsha": "dd36d1b2645bd2b561641cd4a4ebcd8d82b4b4d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-05-25T14:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T15:27:08.000Z", "max_issues_repo_path": "src/constructor/transmatrix.jl", "max_issues_repo_name": "jngod2011/RSDSGE.jl", "max_issues_repo_head_hexsha": "dd36d1b2645bd2b561641cd4a4ebcd8d82b4b4d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-02-14T11:04:18.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-28T11:02:30.000Z", "max_forks_repo_path": "src/constructor/transmatrix.jl", "max_forks_repo_name": "jngod2011/RSDSGE.jl", "max_forks_repo_head_hexsha": "dd36d1b2645bd2b561641cd4a4ebcd8d82b4b4d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-04-05T07:24:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-31T08:04:59.000Z", "avg_line_length": 31.2777777778, "max_line_length": 76, "alphanum_fraction": 0.6758436945, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191284552528, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7527257335896068}}
{"text": "@doc \"\"\"\n       Newton method for local optimization (multivariable)\n\n       Supported by:\n\n       Ph D Kelvyn B. Sánchez\n       e-mail: kelvyn.baruc@gmail.com\n       GitHub: Kelvyn88\n \"\"\" ->\n\nfunction Newton(f, vars, x0; error = 0.0001, maxiter = 100, iter = true)\n      try\n            const version = Pkg.installed(\"OptimJulia\")\n            length(vars) == 0 ? len = 1 : len = length(vars)\n\n            length(vars) == 0 ? sep_var = 1 : sep_var = length(vars)\n            const separator = \"=\"^(9 + (sep_var + 2)*16)\n            err = Inf\n            count = 1\n            x_num = 0\n            f_num = f\n\n            # Numeric iterations\n            iter == true ? ti = time_ns() : nothing # To measure algorithm performance\n\n            while err > error\n                  x_num = x0\n\n                  # Symbolic derivatives using Module SymPy\n                  if length(vars) == 0\n                        # Single variable\n                        dfk = diff(f)\n                  else\n                        # Multivariable variable\n                        dfk = Array(SymPy.Sym, 1, length(vars))\n                        for i=1:length(vars)\n                              dfk[i] = diff(f, vars[i])\n                        end\n                  end\n\n                  f_num = f\n\n                  # Symbolic hessian using module SymPy\n                  if length(vars) == 0\n                        # Single variable\n                        dfk2 = diff(dfk)\n                  else\n                        # Multivariable variable\n                        hess = hessian(f, vars)\n                  end\n\n                  # Numeric evaluations\n                  if length(vars) == 0\n                        # Single variable\n                        dfk = dfk |> subs(vars, x_num)\n                        dfk2 = dfk2 |> subs(vars,x_num)\n\n                        # Conversion from BigInt to Float32 (avoid overflow)\n                        dfk = convert(Float32, dfk)\n                        dfk2 = convert(Float32, dfk2)\n                  else\n                        # Multivariable variable\n                        for i=1:length(vars), j=1:length(vars), k=1:length(vars)\n                              dfk[i] = dfk[i] |> subs(vars[k], x_num[k])\n                              hess[i,j] = hess[i,j] |> subs(vars[k],x_num[k])\n                        end\n\n                        # Conversion from BigInt to Float32 (avoid overflow)\n                        dfk = convert(Array{Float32,length(vars)}, dfk)\n                        hess = convert(Array{Float32,length(vars)}, hess)\n                  end\n\n                  # Newton equation\n                  if length(vars) == 0\n                        # Single variable\n                        xk = x_num - dfk/dfk2\n                  else\n                        # Multivariable variable\n                        xk = x_num - inv(hess) * transpose(dfk)\n                  end\n\n                  err = sum(abs((xk -  x_num) ./ xk))\n\n                  # Numeric evaluation of original function\n                  for k=1:len\n                        f_num = f_num |> subs(vars[k], N(xk[k]))\n                  end\n\n                  f_num = convert(Float32, f_num)\n\n                  # Print iteration for the case of iter == true\n                  if iter == true\n                        if count == 1\n                              # Header message and version\n                              println(separator)\n                              msg1 = @sprintf(\" Newton Solver for Unconstrained Optimization %s \", version)\n                              msg2 = @sprintf(\" Ph D Kelvyn B. Sánchez \")\n                              header_left = ceil((length(separator) - length(msg1))/2)\n                              header_right = (length(separator) - length(msg1)) - header_left\n                              msg1_left = \":\"^convert(Int32,header_left)\n                              msg1_right = \":\"^convert(Int32,header_right)\n                              msg1 = string(msg1_left, msg1, msg1_right)\n                              println(msg1)\n\n                              header_left = ceil((length(separator) - length(msg2))/2)\n                              header_right = (length(separator) - length(msg2)) - header_left\n                              msg2_left = \":\"^convert(Int32,header_left)\n                              msg2_right = \":\"^convert(Int32,header_right)\n                              msg2 = string(msg2_left, msg2, msg2_right)\n                              println(msg2)\n                        end\n\n                        if count == 1 || ceil((count/1)/10) == (count/1)/10\n                              println(separator)\n\n                              # Header\n                              msg1 = \"Iter\\t \"\n\n                              for i=1:len\n                                    msg1 = string(msg1, vars[i], \"\\t\\t \")\n                              end\n\n                              msg1 = string(msg1, \"f(x)\\t\\t \",\"||err||\\t\\t \")\n                              println(msg1)\n                              println(separator)\n                        end\n\n                        # Custom message for iterator\n                        msg2 = @sprintf(\"%i\\t \", count)\n                        for i=1:len\n                              msg2 = string(msg2, @sprintf(\"%4.6e\\t \", xk[i]))\n                        end\n\n                        msg2 = string(msg2, @sprintf(\"%4.6e\\t \", f_num), @sprintf(\"%4.6e\", err))\n                        println(msg2)\n                  end\n\n                  # Backup of new data for next iteration\n                  x0 = xk\n                  x_num = xk\n                  count += 1\n\n                  if count == maxiter\n                        throw(ErrorException(\"Not Solved!. Iteration limit reached.\"))\n                  end\n            end\n\n            iter == true ? println(separator) : nothing\n            iter == true ? tf = time_ns() : nothing # To measure algorithm performance\n            iter == true ? println(\"elapse time: \", (tf - ti)/1.0e9, \" seconds\") : nothing\n\n            return x_num,  f_num, err\n\n      catch Msg\n            println(separator)\n            println(Msg)\n            return NaN, NaN, NaN\n      end\nend\n", "meta": {"hexsha": "a7e5b98ea6e46ca52db0d2da567314e27ee0b1a3", "size": 6233, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Newton.jl", "max_stars_repo_name": "JuliaChem/NumOptim.jl", "max_stars_repo_head_hexsha": "584e34e5abe8e0e6ea05cad656f6cf4609b95f70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-12-13T23:47:25.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-13T23:47:25.000Z", "max_issues_repo_path": "src/Newton.jl", "max_issues_repo_name": "Kelvyn88/OptimJulia.jl", "max_issues_repo_head_hexsha": "584e34e5abe8e0e6ea05cad656f6cf4609b95f70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Newton.jl", "max_forks_repo_name": "Kelvyn88/OptimJulia.jl", "max_forks_repo_head_hexsha": "584e34e5abe8e0e6ea05cad656f6cf4609b95f70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.95625, "max_line_length": 107, "alphanum_fraction": 0.3986844216, "num_tokens": 1259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625145783428, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7526843208368648}}
{"text": "@doc \"\"\"\n\tcgnr(A::Matrix, b::Vector, x0::Vector; prec, maxiter)\n\nConjugate gradient for normal equations residual method for solving the least squares problem `min norm( Ax - b )`.\n\n- `A` is the coefficient matrix (`M-by-N`)\n- `b` is the observation vector (`M`).\n- `x0` is the starting vector (`N`).\n\nThe iteration stops when `norm(xnew - xold) < prec` or after at most `maxiter` iterations.\n\"\"\"->\nfunction cgnr{T<:Number}(A::AbstractMatrix{T}, b::AbstractVector{T}, x0::AbstractVector{T}; prec=LARGE_EPS, maxiter=length(x0))\n\tsize(A,1) == length(b) || throw(DimensionMismatch())\n\tsize(A,2) == length(x0) || throw(DimensionMismatch())\n\tprec >= SMALL_EPS || throw(DomainError())\n\tmaxiter >= 1 || throw(DomainError())\n\n\t# Initialize\n\tx = copy(x0)\n\ty = A*x\n\tr = b - y\n\tz = A'*r\n\tp = copy(z)\n\toneT = one(T)\n\n\tfor iter = 1:maxiter\n\t\tztz = norm(z)^2\n\t\tA_mul_B!(y, A, p) # y = A*p\n\t\tmu = ztz / norm(y)^2\n\t\tBLAS.axpy!(mu, p, x) # x = x + mu*p\n\t\txdiff = mu*norm(p)\n\n\t\tBLAS.axpy!(-mu, y, r) # r = r - mu*y\n\t\tAc_mul_B!(z, A, r) # z = A'*r\n\t\ttau = norm(z)^2 / ztz\n\n\t\t# p = z + tau*p\n\t\tscale!(p, tau)\n\t\tBLAS.axpy!(oneT, z, p)\n\n\t\t# Check for convergence: |xnew - xold|\n\t\tif xdiff < prec\n\t\t\tbreak\n\t\tend\n\tend\n\n\treturn x\nend\n\n@doc \"\"\"\n\tcgnr(T::Freq2wave, b, x0; ...) -> x\n\nConjugate gradient for normal equations residual method for `Freq2Wave`.\nThe initial point `x0` must be of the same dimension as `T`.\n\"\"\"->\nfunction cgnr(T::Freq2Wave, b::AbstractVector{Complex{Float64}}, x0::AbstractVecOrMat{Complex{Float64}}=zeros(eltype(T), wsize(T)); prec=LARGE_EPS, maxiter=max(length(x0),50))\n\tsize(T,1) == length(b) || throw(DimensionMismatch())\n\twsize(T) == size(x0) || throw(DimensionMismatch())\n\tprec >= SMALL_EPS || throw(DomainError())\n\tmaxiter >= 1 || throw(DomainError())\n\n\t# Initialize\n\tx = copy(x0)\n\ty = T*x\n\tr = b - y\n\tz = T'*r\n\tp = copy(z)\n\tCone = one(Complex{Float64})\n\n\tfor iter = 1:maxiter\n\t\tztz = vecnorm(z)^2\n\t\tA_mul_B!(y, T, p) # y = T*p\n\t\tmu = ztz / vecnorm(y)^2\n\t\tBLAS.axpy!(mu, p, x) # x = x + mu*p\n\t\txdiff = mu*norm(p)\n\n\t\tBLAS.axpy!(-mu, y, r) # r = r - mu*y\n\t\tAc_mul_B!(z, T, r) # z = T'*r\n\t\ttau = vecnorm(z)^2 / ztz\n\n\t\t# p = z + tau*p\n\t\tscale!(p, tau)\n\t\tBLAS.axpy!(Cone, z, p)\n\n\t\t# Check for convergence: |xnew - xold|\n\t\tif xdiff < prec\n\t\t\tbreak\n\t\tend\n\tend\n\n\treturn x\nend\n\n", "meta": {"hexsha": "d1f5b41bfa5c96bfe8e102f8a9366ef82f93fe9b", "size": 2277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CGNR.jl", "max_stars_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_stars_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CGNR.jl", "max_issues_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_issues_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CGNR.jl", "max_forks_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_forks_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2234042553, "max_line_length": 175, "alphanum_fraction": 0.6108915239, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625145783431, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7526843186841717}}
{"text": "using Mimi\n\n@defcomp grosseconomy begin\n    YGROSS  = Variable(index=[time])    # Gross output\n    K       = Variable(index=[time])    # Capital\n    l       = Parameter(index=[time])   # Labor\n    tfp     = Parameter(index=[time])   # Total factor productivity\n    s       = Parameter(index=[time])   # Savings rate\n    depk    = Parameter()               # Depreciation rate on capital - Note that it has no time index\n    k0      = Parameter()               # Initial level of capital\n    share   = Parameter()               # Capital share\n\n    function run_timestep(p, v, d, t)\n        # Define an equation for K\n        if is_first(t)\n            v.K[t]  = p.k0  # Note the use of v. and p. to distinguish between variables and parameters\n        else\n            v.K[t]  = (1 - p.depk)^5 * v.K[t-1] + v.YGROSS[t-1] * p.s[t-1] * 5\n        end\n\n        # Define an equation for YGROSS\n        v.YGROSS[t] = p.tfp[t] * v.K[t]^p.share * p.l[t]^(1-p.share)\n    end\nend\n\n@defcomp emissions begin\n    E       = Variable(index=[time])    # Total greenhouse gas emissions\n    sigma   = Parameter(index=[time])   # Emissions output ratio\n    YGROSS  = Parameter(index=[time])   # Gross output - Note that YGROSS is now a parameter\n\n    function run_timestep(p, v, d, t)\n        # Define an eqation for E\n        v.E[t] = p.YGROSS[t] * p.sigma[t]   # Note the p. in front of YGROSS\n    end\nend\n\nfunction construct_model()\n\tm = Model()\n\n\tset_dimension!(m, :time, collect(2015:5:2110))\n\n\t# Order matters here. If the emissions component were defined first, the model would not run.\n\tadd_comp!(m, grosseconomy)  \n\tadd_comp!(m, emissions)\n\n\t# Update parameters for the grosseconomy component\n\tupdate_param!(m, :grosseconomy, :l, [(1. + 0.015)^t *6404 for t in 1:20])\n\tupdate_param!(m, :grosseconomy, :tfp, [(1 + 0.065)^t * 3.57 for t in 1:20])\n\tupdate_param!(m, :grosseconomy, :s, ones(20).* 0.22)\n\tupdate_param!(m, :grosseconomy, :depk, 0.1)\n\tupdate_param!(m, :grosseconomy, :k0, 130.)\n\tupdate_param!(m, :grosseconomy, :share, 0.3)\n\n\t# Update and connect parameters for the emissions component\n\tupdate_param!(m, :emissions, :sigma, [(1. - 0.05)^t *0.58 for t in 1:20])\n\tconnect_param!(m, :emissions, :YGROSS, :grosseconomy, :YGROSS)  \n\n\treturn m\n\nend #end function\n\nmodel = construct_model()\n\nrun(model)\n\n# Show model results\nmodel[:emissions, :E]\n\n# Or, as a DataFrame\ngetdataframe(model, :emissions, :E)\n", "meta": {"hexsha": "a4cb21f043ccd9b890034bd451e499315b7775ac", "size": 2398, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/tutorial/01-one-region-model/one-region-model.jl", "max_stars_repo_name": "Mechachleopteryx/Mimi.jl", "max_stars_repo_head_hexsha": "39472d51580274cbd43ab0d55ff82f749eb15201", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 42, "max_stars_repo_stars_event_min_datetime": "2019-03-05T18:48:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T16:44:47.000Z", "max_issues_repo_path": "examples/tutorial/01-one-region-model/one-region-model.jl", "max_issues_repo_name": "Mechachleopteryx/Mimi.jl", "max_issues_repo_head_hexsha": "39472d51580274cbd43ab0d55ff82f749eb15201", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 383, "max_issues_repo_issues_event_min_datetime": "2019-03-05T00:36:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T07:23:20.000Z", "max_forks_repo_path": "examples/tutorial/01-one-region-model/one-region-model.jl", "max_forks_repo_name": "Mechachleopteryx/Mimi.jl", "max_forks_repo_head_hexsha": "39472d51580274cbd43ab0d55ff82f749eb15201", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:15:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-21T16:49:53.000Z", "avg_line_length": 33.7746478873, "max_line_length": 103, "alphanum_fraction": 0.6217681401, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7526843159177599}}
{"text": "using LinearAlgebra\n\nabstract type AbstractForecasting end\n\nexport StateSpaceModel\n\n\"\"\"\n\nSpace-State model is defined through the following equations\n\nLet ``{x_0, x_1, \\\\dots, x_K }`` denote the discrete-time state process,\nwhich is typically unknown to the observer. Let ``{y_1,y_2,... ,y_K}`` \nrepresent the observation process, which describes the measurements of the\nsystem that are available to the observer. \n\nThese state and observation processes are related following a nonlinear \nstate-space model: The first equation describes how the system state ``x_k`` \nevolves through a nonlinear dynamical model ``f_{k−1,k}`` between successive \ntime steps ``t_{k−1}`` and ``t_k``.\n``η = {η1,η2,... ,ηK}`` is the model noise process, which accounts for\nthe imperfections of the model; it is assumed to be independent and\nidentically distributed. At each time step, ``η_k`` is assumed\nto be Gaussian with zero mean and covariance matrix Q. The second equation\nmodels how an observation ``y_k`` at time ``t_k`` is obtained from the state\n``x_k`` through a linear operator ``H``. ``ε = {ε1, ε2, . . . , εk}`` is an\nindependent and identically distributed process representing the observation \nerrors; ``ε_k`` is assumed\nGaussian with zero mean and covariance matrix ``R``. Finally, the\nprocesses ``η`` and ``ε`` are assumed to be jointly independent and independent\nof the initial (background) state x0, which is assumed to be Gaussian\nwith mean xb and covariance B.\n\n```math\n\\\\left\\\\{\n\\\\begin{array}{l}\nX_t = m(X_{t-1}) + \\\\eta_t, \\\\\\\\\nY_t = H(X_t) + \\\\varepsilon_t,\n\\\\end{array}\n\\\\right.\n```\n\n- X : hidden variables\n- Y : observed variables\n\n- `dt_integration`is the numerical time step used to solve the ODE.\n- `dt_states` is the number of `dt_integration` between ``X_{t-1}`` and ``X_t``.\n- `dt_obs` is the number of `dt_integration` between ``Y_{t-1}`` and ``Y_t``.\n\n\n\"\"\"\nstruct StateSpaceModel <: AbstractForecasting\n\n    model::Function\n    dt_integration::Float64\n    dt_states::Int64\n    dt_obs::Int64\n    params::Vector{Float64}\n    var_obs::Vector{Int64}\n    nb_loop_train::Int64\n    nb_loop_test::Int64\n    sigma2_catalog::Float64\n    sigma2_obs::Float64\n\nend\n", "meta": {"hexsha": "d588d7e2cb45bc3f5d847a40b5493efa6a061cfa", "size": 2168, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/state_space.jl", "max_stars_repo_name": "pnavaro/AnalogDataAssimilation.jl", "max_stars_repo_head_hexsha": "aed4be59c5e7e25f81546c8b8f7ad84a770a1265", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2022-01-05T21:17:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T21:18:17.000Z", "max_issues_repo_path": "src/state_space.jl", "max_issues_repo_name": "pnavaro/AnalogDataAssimilation.jl", "max_issues_repo_head_hexsha": "aed4be59c5e7e25f81546c8b8f7ad84a770a1265", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/state_space.jl", "max_forks_repo_name": "pnavaro/AnalogDataAssimilation.jl", "max_forks_repo_head_hexsha": "aed4be59c5e7e25f81546c8b8f7ad84a770a1265", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3538461538, "max_line_length": 80, "alphanum_fraction": 0.7223247232, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654263, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7526843131497889}}
{"text": "# # Solve the heat conduction equation\n\n# Synopsis: Compute the solution of the Poisson equation of heat conduction with a\n# nonzero heat source. Quadrilateral four-node elements are used.\n\n# The problem is linear heat conduction equation posed on a bi-unit square,\n# solved with Dirichlet boundary conditions around the circumference. Uniform\n# nonzero heat generation rate is present. The exact solution is in this way\n# manufactured and hence known. That gives us an opportunity to calculate the\n# true error.\n\n# The complete code is in the file [`tut_poisson_q4.jl`](tut_poisson_q4.jl).\n\n# The solution will be defined  within a module in order to eliminate conflicts\n# with data or functions defined elsewhere.\n\nmodule tut_poisson_q4\n\n# We'll need some functionality from linear algebra, and the mesh libraries.\n# Finally we will need the `Elfel` functionality.\nusing LinearAlgebra\nusing MeshCore.Exports\nusing MeshSteward.Exports\nusing Elfel.Exports\n\n# This is the top level function. \nfunction run()\n    # Input parameters:\n    A = 1.0 # length of the side of the square\n    kappa =  1.0; # thermal conductivity of the material\n    Q = -6.0; # internal heat generation rate\n    tempf(x, y) =(1.0 + x^2 + 2.0 * y^2); # the exact distribution of temperature\n    N = 1000; # number of element edges along the sides of the square domain\n\n    # Generate the computational mesh.\n    mesh = genmesh(A, N)\n\n    # Create the finite element space to represent the temperature solution. The\n    # degrees of freedom are real numbers (`Float64`), the quadrilaterals are\n    # defined by the mesh, and each of the elements has the continuity ``H\n    # ^1``, i. e. both the function values and the derivatives are square\n    # integrable.\n    Uh = FESpace(Float64, mesh, FEH1_Q4())\n\n    # Apply the essential boundary conditions at the circumference of the square\n    # domain. We find the boundary incidence relation (`boundary(mesh)`), and\n    # then the list of all vertices connected by the boundary cells. The\n    # function `tempf` defines the analytical temperature variation, and hence\n    # for each of the vertices `i` on the boundary (they are of manifold\n    # dimension  `0`), we set the component of the field (1) to the exact value\n    # of the temperature at that location.\n    vl = connectedv(boundary(mesh));\n    locs = geometry(mesh)\n    for i in vl\n        setebc!(Uh, 0, i, 1, tempf(locs[i]...))\n    end\n\n    # Number the degrees of freedom, both the unknowns and the data\n    # (prescribed) degrees of freedom.\n    numberdofs!(Uh)\n    @show ndofs(Uh), nunknowns(Uh)\n\n    # Assemble the conductivity matrix and the vector of the heat loads. Refer\n    # to the definition of this function below.\n    K, F = assembleKF(Uh, kappa, Q)\n\n    # This is a vector to hold all degrees of freedom in the system.\n    T = fill(0.0, ndofs(Uh))\n    # Here we collect the data degrees of freedom (the known values).\n    gathersysvec!(T, Uh)\n\n    # The system of linear algebraic equations is solved.\n    solve!(T, K, F, nunknowns(Uh))\n\n    # The values of all the degrees of freedom can now be introduced into the\n    # finite element space.\n    scattersysvec!(Uh, T)\n\n    # Here we associate the values of the finite element space with the entities\n    # of the mesh as an attribute.\n    makeattribute(Uh, \"T\", 1)\n\n    # The correctness of the solution is checked by comparing the values at the\n    # vertices.\n    checkcorrectness(Uh, tempf)\n\n    # The attribute can now be written out for visualization into a VTK file.\n    vtkwrite(\"q4-T\", baseincrel(mesh), [(name = \"T\",)])\n\n    true # return success\nend\n\n# The domain is a square, meshed with quadrilateral elements. The function\n# `Q4block` creates an incidence relation that defines the quadrilateral\n# element shapes by the vertices connected into the shapes. This incidence\n# relation is then attached to the mesh and the mesh is returned.\nfunction genmesh(A, N)\n    conn = Q4block(A, A, N, N)\n    return attach!(Mesh(), conn)\nend\n\n# The `assembleKF` function constructs the left-hand side coefficient matrix,\n# conductivity matrix, as a sparse matrix, and a vector of the heat loads due\n# to the internal heat generation rate `Q`.\n\n# The boundary value problem is expressed in this weak form\n# ```math\n# \\int_{V}(\\mathrm{grad}\\vartheta)\\; \\kappa (\\mathrm{grad}T\n#             )^T\\; \\mathrm{d} V\n#             -\\int_{V}  \\vartheta Q \\; \\mathrm{d} V  \n#              = 0\n# ```\n# where the test function vanishes on the boundary where the temperature is \n# prescribed, ``\\vartheta(x) =0``  for  ``x \\in{S_1}`` \n# Substituting ``\\vartheta = N_j `` and ``T = \\sum_i N_i T_i`` we obtain the \n# linear algebraic equations   \n# ```math\n# \\sum_i T_i \\int_{V} \\mathrm{grad}N_j \\; \\kappa (\\mathrm{grad}N_i)^T\\; \\mathrm{d} V\n#  -\\int_{V}  N_j Q \\; \\mathrm{d} V  = 0 , \\quad \\forall j.\n# ```\n# The volume element is ``\\mathrm{d} V``, which in our case \n# becomes ``1.0\\times\\mathrm{d} S``, since the thickness of the two \n# dimensional domain is assumed to be 1.0.\n\nfunction assembleKF(Uh, kappa, Q)\n    # At the top of the `assembleKF` we look at the function `integrate!` to\n    # evaluate the weak-form integrals. The key to making this calculation\n    # efficient is type stability. All the arguments coming in must have\n    # concrete types. This is why the `integrate!` function is an inner\n    # function: the function barrier allows for all arguments to be resolved to\n    # concrete types.\n    function integrate!(am, av, elit, qpit, kappa, Q)\n        nedof = ndofsperel(elit)\n        # The local assemblers are just like matrices or vectors\n        ke = LocalMatrixAssembler(nedof, nedof, 0.0) \n        fe = LocalVectorAssembler(nedof, 0.0)\n        for el in elit # Loop over all elements\n            init!(ke, eldofs(el), eldofs(el)) # zero out elementwise matrix\n            init!(fe, eldofs(el)) # and vector\n            for qp in qpit # Now loop over the quadrature points\n                Jac, J = jacjac(el, qp) # Calculate the Jacobian matrix, Jacobian\n                gradN = bfungrad(qp, Jac) # Evaluate the spatial gradients\n                JxW = J * weight(qp) # elementary volume\n                N = bfun(qp) # Basis function values at the quadrature point\n                # This double loop evaluates the elementwise conductivity\n                # matrix and the heat load vector precisely as the formula of\n                # the weak form  dictates; see above.\n                for i in 1:nedof\n                    for j in 1:nedof\n                        ke[j, i] += dot(gradN[j], gradN[i]) * (kappa * JxW)\n                    end\n                    fe[j] += N[j] * Q * JxW\n                end\n            end\n            # Assemble the calculated contributions from this element\n            assemble!(am, ke)\n            assemble!(av, fe)\n        end\n        return am, av # Return the updated assemblers\n    end\n\n    # In the `assembleKF` function we first we create the element iterator. We\n    # can go through all the elements that define the domain of integration\n    # using this iterator. Each time a new element is accessed, some data are\n    # precomputed such as the element degrees of freedom.\n    elit = FEIterator(Uh)\n    # This is the quadrature point iterator. We know that the elements are\n    # quadrilateral, which makes the Gauss integration rule the obvious choice.\n    # We also select order 2 for accuracy. Quadrature-point iterators provide\n    # access to basis function values and gradients, the Jacobian matrix and\n    # the Jacobian determinant, the location of the quadrature point and so\n    # on.\n    qpit = QPIterator(Uh, (kind = :Gauss, order = 2))\n    # Next we create assemblers, one for the sparse system matrix and one for\n    # the system vector.\n    am = start!(SysmatAssemblerSparse(0.0), ndofs(Uh), ndofs(Uh))\n    av = start!(SysvecAssembler(0.0), ndofs(Uh))\n    # Now we call the integration function. The assemblers are modified inside\n    # this function...\n    @time integrate!(am, av, elit, qpit, kappa, Q)\n    # ...so that when the integration is done, we can materialize the sparse\n    # matrix and the vector and return them.\n    return finish!(am), finish!(av)\nend\n\n# The linear algebraic system is solved by partitioning. The vector `T` is\n# initially all zero, except in the degrees of freedom which are prescribed as\n# nonzero. Therefore the product of the conductivity matrix and the vector `T`\n# are the heat loads due to nonzero essential boundary conditions. To this we\n# add the vector of heat loads due to the internal heat generation rate. The\n# submatrix of the heat conduction matrix corresponding to the free degrees of\n# freedom (unknowns), `K[1:nu, 1:nu]` is then used to solve for the unknowns `T\n# [1:nu]`.\nfunction solve!(T, K, F, nu)\n    @time KT = K * T\n    @time T[1:nu] = K[1:nu, 1:nu] \\ (F[1:nu] - KT[1:nu])\nend\n\n# The correctness can be checked in various ways. Here we calculate the mean\n# deviation of the calculated temperatures at the nodes relative to the exact\n# values of the temperature.\nfunction checkcorrectness(Uh, tempf)\n    geom = geometry(Uh.mesh)\n    ir = baseincrel(Uh.mesh)\n    T = attribute(ir.right, \"T\")\n    std = 0.0\n    for i in 1:length(T)\n        std += abs(T[i][1] - tempf(geom[i]...))\n    end\n    @show (std / length(T)) <= 1.0e-9\nend\n\nend # module\n\n# The module can now be used. \nusing .tut_poisson_q4\ntut_poisson_q4.run()\n", "meta": {"hexsha": "59d54e49fee9fe8bc7424c356d31b5242388ee0d", "size": 9394, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/tutorials/tut_poisson_q4.jl", "max_stars_repo_name": "PetrKryslUCSD/Elfem.jl", "max_stars_repo_head_hexsha": "4bbd57db0541dd08c181936110f4753c2d6079d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-05-17T21:30:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T19:06:50.000Z", "max_issues_repo_path": "docs/src/tutorials/tut_poisson_q4.jl", "max_issues_repo_name": "PetrKryslUCSD/Elfem.jl", "max_issues_repo_head_hexsha": "4bbd57db0541dd08c181936110f4753c2d6079d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-07-15T02:11:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-29T01:26:23.000Z", "max_forks_repo_path": "docs/src/tutorials/tut_poisson_q4.jl", "max_forks_repo_name": "PetrKryslUCSD/Elfem.jl", "max_forks_repo_head_hexsha": "4bbd57db0541dd08c181936110f4753c2d6079d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.0917431193, "max_line_length": 84, "alphanum_fraction": 0.6763891846, "num_tokens": 2493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705932, "lm_q2_score": 0.8080672043084051, "lm_q1q2_score": 0.7526843054611532}}
{"text": "\"\"\"\n    complement(g)\n\nProduces the [graph complement](https://en.wikipedia.org/wiki/Complement_graph)\nof a graph.\n\"\"\"\nfunction complement(g::Graph)\n    gnv = nv(g)\n    h = Graph(gnv)\n    for i=1:gnv\n        for j=i+1:gnv\n            if !has_edge(g, i, j)\n                add_edge!(h,i,j)\n            end\n        end\n    end\n    return h\nend\n\nfunction complement(g::DiGraph)\n    gnv = nv(g)\n    h = DiGraph(gnv)\n    for i=1:gnv\n        for j=1:gnv\n            if i != j && !has_edge(g,i,j)\n                add_edge!(h,i,j)\n            end\n        end\n    end\n    return h\nend\n\n\"\"\"\n    reverse(g::DiGraph)\n\nProduces a graph where all edges are reversed from the\noriginal.\n\"\"\"\nfunction reverse(g::DiGraph)\n    gnv = nv(g)\n    gne = ne(g)\n    h = DiGraph(gnv)\n    h.fadjlist = deepcopy(g.badjlist)\n    h.badjlist = deepcopy(g.fadjlist)\n    h.ne = gne\n    h.vertices = g.vertices\n\n    return h\nend\n\n\"\"\"\n    reverse!(g::DiGraph)\n\nIn-place reverse (modifies the original graph).\n\"\"\"\nfunction reverse!(g::DiGraph)\n    g.fadjlist, g.badjlist = g.badjlist, g.fadjlist\n    return g\nend\n\ndoc\"\"\"\n    blkdiag(g, h)\n\nProduces a graph with $|V(g)| + |V(h)|$ vertices and $|E(g)| + |E(h)|$\nedges.\n\nPut simply, the vertices and edges from graph `h` are appended to graph `g`.\n\"\"\"\nfunction blkdiag{T<:SimpleGraph}(g::T, h::T)\n    gnv = nv(g)\n    r = T(gnv + nv(h))\n    for e in edges(g)\n        add_edge!(r, e)\n    end\n    for e in edges(h)\n        add_edge!(r, gnv+src(e), gnv+dst(e))\n    end\n    return r\nend\n\n\"\"\"\n    intersect(g, h)\n\nProduces a graph with edges that are only in both graph `g` and graph `h`.\n\nNote that this function may produce a graph with 0-degree vertices.\n\"\"\"\nfunction intersect{T<:SimpleGraph}(g::T, h::T)\n    gnv = nv(g)\n    hnv = nv(h)\n\n    r = T(min(gnv, hnv))\n    for e in intersect(edges(g),edges(h))\n        add_edge!(r,e)\n    end\n    return r\nend\n\n\"\"\"\n    difference(g, h)\n\nProduces a graph with edges in graph `g` that are not in graph `h`.\n\nNote that this function may produce a graph with 0-degree vertices.\n\"\"\"\nfunction difference{T<:SimpleGraph}(g::T, h::T)\n    gnv = nv(g)\n    hnv = nv(h)\n\n    r = T(gnv)\n    for e in edges(g)\n        !has_edge(h, e) && add_edge!(r,e)\n    end\n    return r\nend\n\n\"\"\"\n    symmetric_difference(g, h)\n\nProduces a graph with edges from graph `g` that do not exist in graph `h`,\nand vice versa.\n\nNote that this function may produce a graph with 0-degree vertices.\n\"\"\"\nfunction symmetric_difference{T<:SimpleGraph}(g::T, h::T)\n    gnv = nv(g)\n    hnv = nv(h)\n\n    r = T(max(gnv, hnv))\n    for e in edges(g)\n        !has_edge(h, e) && add_edge!(r, e)\n    end\n    for e in edges(h)\n        !has_edge(g, e) && add_edge!(r, e)\n    end\n    return r\nend\n\n\"\"\"\n    union(g, h)\n\nMerges graphs `g` and `h` by taking the set union of all vertices and edges.\n\"\"\"\nfunction union{T<:SimpleGraph}(g::T, h::T)\n    gnv = nv(g)\n    hnv = nv(h)\n\n    r = T(max(gnv, hnv))\n    r.ne = ne(g)\n    for i = 1:gnv\n        r.fadjlist[i] = deepcopy(g.fadjlist[i])\n        if is_directed(g)\n            r.badjlist[i] = deepcopy(g.badjlist[i])\n        end\n    end\n    for e in edges(h)\n        add_edge!(r, e)\n    end\n    return r\nend\n\n\n\"\"\"\n    join(g, h)\n\nMerges graphs `g` and `h` using `blkdiag` and then adds all the edges between\n the vertices in `g` and those in `h`.\n\"\"\"\nfunction join(g::Graph, h::Graph)\n    r = blkdiag(g, h)\n    for i=1:nv(g)\n        for j=nv(g)+1:nv(g)+nv(h)\n            add_edge!(r, i, j)\n        end\n    end\n    return r\nend\n\n\n\"\"\"\n    crosspath(len::Integer, g::Graph)\n\nReplicate `len` times `h` and connect each vertex with its copies in a path\n\"\"\"\ncrosspath(len::Integer, g::Graph) = cartesian_product(PathGraph(len), g)\n\n\"\"\"\n    induced_subgraph(g, iter)\n\nFilters graph `g` to include only the vertices present in the iterable\nargument `vs`. Returns the subgraph of `g` induced by `vs`.\n\"\"\"\nfunction induced_subgraph{T<:SimpleGraph}(g::T, iter)\n    n = length(iter)\n    isequal(n, length(unique(iter))) || error(\"Vertices in subgraph list must be unique\")\n    isequal(n, nv(g)) && return copy(g) # if iter is not a proper subgraph\n\n    h = T(n)\n    newvid = Dict{Int, Int}()\n    i=1\n    for (i,v) in enumerate(iter)\n        newvid[v] = i\n    end\n\n    iterset = Set(iter)\n    for s in iter\n        for d in out_neighbors(g, s)\n            # println(\"s = $s, d = $d\")\n            if d in iterset && has_edge(g, s, d)\n                newe = Edge(newvid[s], newvid[d])\n                add_edge!(h, newe)\n            end\n        end\n    end\n    return h\nend\n\n# dispatch for g[[1,2,3]], g[1:3], g[Set([1,2,3])]\n# these are the only allowed dispatches, everything else is slow\ngetindex(g::SimpleGraph, iter) = induced_subgraph(g, iter)\n\n\n# The following operators allow one to use a LightGraphs.Graph as a matrix in eigensolvers for spectral ranking and partitioning.\n# \"\"\"Provides multiplication of a graph `g` by a vector `v` such that spectral\n# graph functions in [GraphMatrices.jl](https://github.com/jpfairbanks/GraphMatrices.jl) can utilize LightGraphs natively.\n# \"\"\"\nfunction *{T<:Real}(g::Graph, v::Vector{T})\n    length(v) == nv(g) || error(\"Vector size must equal number of vertices\")\n    y = zeros(T, nv(g))\n    for e in edges(g)\n        i = src(e)\n        j = dst(e)\n        y[i] += v[j]\n        y[j] += v[i]\n    end\n    return y\nend\n\nfunction *{T<:Real}(g::DiGraph, v::Vector{T})\n    length(v) == nv(g) || error(\"Vector size must equal number of vertices\")\n    y = zeros(T, nv(g))\n    for e in edges(g)\n        i = src(e)\n        j = dst(e)\n        y[i] += v[j]\n    end\n    return y\nend\n\n\"\"\"sum(g,i) provides 1:indegree or 2:outdegree vectors\"\"\"\nfunction sum(g::SimpleGraph, dim::Int)\n    dim == 1 && return indegree(g, vertices(g))\n    dim == 2 && return outdegree(g, vertices(g))\n    error(\"Graphs are only two dimensional\")\nend\n\n\nsize(g::SimpleGraph) = (nv(g), nv(g))\n\"\"\"size(g,i) provides 1:nv or 2:nv else 1 \"\"\"\nsize(g::Graph,dim::Int) = (dim == 1 || dim == 2)? nv(g) : 1\n\n\"\"\"sum(g) provides the number of edges in the graph\"\"\"\nsum(g::SimpleGraph) = ne(g)\n\n\"\"\"sparse(g) is the adjacency_matrix of g\"\"\"\nsparse(g::SimpleGraph) = adjacency_matrix(g)\n\n#arrayfunctions = (:eltype, :length, :ndims, :size, :strides, :issymmetric)\neltype(g::SimpleGraph) = Float64\nlength(g::SimpleGraph) = nv(g)*nv(g)\nndims(g::SimpleGraph) = 2\nissymmetric(g::SimpleGraph) = !is_directed(g)\n\n\"\"\"\n    cartesian_product(g, h)\n\nReturns the (cartesian product)[https://en.wikipedia.org/wiki/Tensor_product_of_graphs] of `g` and `h`\n\"\"\"\nfunction cartesian_product{G<:SimpleGraph}(g::G, h::G)\n    z = G(nv(g)*nv(h))\n    id(i, j) = (i-1)*nv(h) + j\n    for (i1, i2) in edges(g)\n        for j=1:nv(h)\n            add_edge!(z, id(i1,j), id(i2,j))\n        end\n    end\n\n    for e in edges(h)\n        j1, j2 = src(e), dst(e)\n        for i=1:nv(g)\n            add_edge!(z, id(i,j1), id(i,j2))\n        end\n    end\n    return z\nend\n\n\"\"\"\n    tensor_product(g, h)\n\nReturns the (tensor product)[https://en.wikipedia.org/wiki/Tensor_product_of_graphs] of `g` and `h`\n\"\"\"\nfunction tensor_product{G<:SimpleGraph}(g::G, h::G)\n    z = G(nv(g)*nv(h))\n    id(i, j) = (i-1)*nv(h) + j\n    for (i1, i2) in edges(g)\n        for (j1, j2) in edges(h)\n            add_edge!(z, id(i1, j1), id(i2, j2))\n        end\n    end\n    return z\nend\n", "meta": {"hexsha": "3bba32a1f84c3e3f7dfdbc59a260d898688cbbc6", "size": 7241, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operators.jl", "max_stars_repo_name": "JuliaPackageMirrors/LightGraphs.jl", "max_stars_repo_head_hexsha": "b13472899cba49999567bb88f9d32d5d87cf4a19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/operators.jl", "max_issues_repo_name": "JuliaPackageMirrors/LightGraphs.jl", "max_issues_repo_head_hexsha": "b13472899cba49999567bb88f9d32d5d87cf4a19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/operators.jl", "max_forks_repo_name": "JuliaPackageMirrors/LightGraphs.jl", "max_forks_repo_head_hexsha": "b13472899cba49999567bb88f9d32d5d87cf4a19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2083333333, "max_line_length": 129, "alphanum_fraction": 0.585140174, "num_tokens": 2277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.8774767970940975, "lm_q1q2_score": 0.7526716030352794}}
{"text": "\"Solve Computing Eccentric Anomaly from Mean Anomally via Kepler's Equation\"\nmodule KeplerEqn\n\nexport calc_ecc_anom\nexport calc_ecc_anom_cpu, calc_ecc_anom_gpu\nusing CUDAnative\n\n\"\"\"   ecc_anom_init_guess_danby(M, ecc)\nInitial guess for eccentric anomaly given mean anomaly (M) and eccentricity (ecc)\n    Based on \"The Solution of Kepler's Equations - Part Three\"  \n    Danby, J. M. A. (1987) Journal: Celestial Mechanics, Volume 40, Issue 3-4, pp. 303-312  1987CeMec..40..303D\n\"\"\"\nfunction ecc_anom_init_guess_danby(M, ecc)\n    k = convert(typeof(ecc),0.85)\n    if(M<zero(M)) M += 2pi end\n    (M<pi) ? M + k*ecc : M - k*ecc;\nend\n\n\"\"\"   update_ecc_anom_laguerre(E, M, ecc)\nUpdate the current guess (E) for the solution to Kepler's equation given mean anomaly (M) and eccentricity (ecc)\n   Based on \"An Improved Algorithm due to Laguerre for the Solution of Kepler's Equation\"\n   Conway, B. A.  (1986) Celestial Mechanics, Volume 39, Issue 2, pp.199-211  1986CeMec..39..199C\n\"\"\"\nfunction update_ecc_anom_laguerre(E, M, ecc)\n  es = ecc*sin(E)\n  ec = ecc*cos(E)\n  F = (E-es)-M\n  Fp = one(E)-ec\n  Fpp = es\n  n = 5\n  root = sqrt(abs((n-1)*((n-1)*Fp*Fp-n*F*Fpp)))\n  denom = Fp>zero(E) ? Fp+root : Fp-root\n  return E-n*F/denom\nend\n\n\"Same as update_ecc_anom_laguerre_cpu, except uses GPU math functions\"\nfunction update_ecc_anom_laguerre_gpu(E, M, ecc)\n  es = ecc*CUDAnative.sin(E)\n  ec = ecc*CUDAnative.cos(E)\n  F = (E-es)-M\n  Fp = one(E)-ec\n  Fpp = es\n  n = 5\n  root = CUDAnative.sqrt(abs((n-1)*((n-1)*Fp*Fp-n*F*Fpp)))\n  denom = Fp>zero(E) ? Fp+root : Fp-root\n  return E-n*F/denom\nend\n\n\"Loop to update the current estimate of the solution to Kepler's equation\"\nfunction calc_ecc_anom_itterative_laguerre(mean_anom, ecc, tol, max_its)\n    M = mod(mean_anom,convert(typeof(mean_anom),2pi))\n    E = ecc_anom_init_guess_danby(M,ecc)\n    for i in 1:max_its\n       E_old = E\n       E = update_ecc_anom_laguerre(E_old, M, ecc)\n       if abs(E-E_old)<convert(typeof(mean_anom),tol) break end\n    end\n    return E\nend\n\n\"Loop to update the current estimate of the solution to Kepler's equation.  Calls GPU update\"\nfunction calc_ecc_anom_itterative_laguerre_gpu(mean_anom, ecc, tol, max_its)\n    @assert zero(ecc) <= ecc < one(ecc)\n    @assert tol*100 <= one(tol)\n    M = mod(mean_anom,convert(typeof(mean_anom),2pi))\n    E = ecc_anom_init_guess_danby(M,ecc)\n    for i in 1:max_its\n       E_old = E\n       E = update_ecc_anom_laguerre_gpu(E_old, M, ecc)\n       if abs(E-E_old)<convert(typeof(mean_anom),tol) break end\n    end\n    return E\nend\n\nconst default_max_its_laguerre = 200\nconst default_ecc_anom_tol = 1e-8\n\"Calculate eccentric anomaly given mean anomaly and eccentricty (in radians)\"\ncalc_ecc_anom_cpu(mean_anom, ecc) = calc_ecc_anom_itterative_laguerre(mean_anom, ecc, default_ecc_anom_tol, default_max_its_laguerre)\ncalc_ecc_anom_gpu(mean_anom, ecc) = calc_ecc_anom_itterative_laguerre_gpu(mean_anom, ecc, default_ecc_anom_tol, default_max_its_laguerre)\ncalc_ecc_anom(mean_anom, ecc) = calc_ecc_anom_cpu(mean_anom, ecc)\n\nend # module KeplerEqn\n", "meta": {"hexsha": "8360d6143d6df9070d6b9f7a0d97c970ed0482dc", "size": 3037, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kepler_eqn.jl", "max_stars_repo_name": "apellegrino/lab7-apellegrino", "max_stars_repo_head_hexsha": "4e48fdcb98174c98160526273342d969cd8be736", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kepler_eqn.jl", "max_issues_repo_name": "apellegrino/lab7-apellegrino", "max_issues_repo_head_hexsha": "4e48fdcb98174c98160526273342d969cd8be736", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kepler_eqn.jl", "max_forks_repo_name": "apellegrino/lab7-apellegrino", "max_forks_repo_head_hexsha": "4e48fdcb98174c98160526273342d969cd8be736", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5903614458, "max_line_length": 137, "alphanum_fraction": 0.7197892657, "num_tokens": 1050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7526127344960549}}
{"text": "using Revise, Random, LinearAlgebra, Optim, StatsBase,\n  Statistics, Distributions, COSMO, BenchmarkTools, Plots\n\nRandom.seed!(11)\n\n#compute the minvol portfolio given a return target, expected returns z, and Σ\nfunction minvolw(μ, z, Σ, Σinv = Σ\\I)\n  K= length(z)\n  some1s = ones(K)\n\n  A = some1s' * Σinv * some1s\n  B = some1s' * Σinv * z\n  C = z' * Σinv * z\n\n  λ =(μ * B - C) /(B^2 - A*C)\n  γ = (μ * A - B) /(A*C -B^2)\n\n\n  w = λ * Σinv * some1s .+ γ * Σinv * z\n\n  return w\nend\n\n#same as before but acquires the solution numerically\nfunction nminvolw(μ, z, Σ)\n  K= length(z)\n  some1s = ones(K)\n\n  m = COSMO.Model()\n  c1 = COSMO.Constraint(ones(1,K), -1.0, COSMO.ZeroSet)\n  c2 = COSMO.Constraint(z', -μ, COSMO.ZeroSet)\n  COSMO.assemble!(m, Σ, zeros(K), [c1; c2])\n  res = COSMO.optimize!(m)\n\n\n  return res.x\n\n  #return w\nend\n\n\nfunction gengraphs(;N=10^5, K=15, Δ=0.001)\n  Erm = 0.08 #expected market reutn\n  rf = 0.02 #risk free rate\n  σm = 0.1 #market standard deviation\n\n  ivol = rand(K)*0.4 .+ 0.1 #stock ivols\n  beta = rand(Normal(1,0.2), K) #stock betas\n\n  rm = rand(Normal(Erm, σm), N) #the market returns\n  noise = reduce(hcat, (σe->rand(Normal(0, σe), N)).(ivol))\n  r = rm .* beta' .+ noise\n\n  z = mean(r, dims=1) |> vec\n  Σ = cov(r)\n\n  #sanity check\n  Σinv = Σ\\I\n  w = minvolw(0.1, z, Σ, Σinv)\n  nw = nminvolw(0.1, z, Σ)\n  @assert w ≈ nw\n\n  minvolσ(μ) = minvolw(μ, z, Σ, Σinv) |> (w)->(w'*Σ*w)^0.5\n  nminvolσ(μ) = nminvolw(μ, z, Σ) |> (w)->(w'*Σ*w)^0.5\n\n  #compute the minimum variance frontier\n  μs = 0.01:Δ:0.2 |> collect\n  σs = similar(μs)\n  Threads.@threads for i ∈ 1:length(μs)\n    σs[i] = minvolσ(μs[i])\n  end\n\n  #compute global min var portfolio\n  some1s = ones(K)\n  A = some1s' * Σinv * some1s\n  B = some1s' * Σinv * z\n\n  wg = Σinv * some1s / A\n  σg = (wg'*Σ*wg)^(0.5)\n  rg = z' * wg\n\n  #compute the tangency portfolio\n  wt = Σinv * (z .- some1s .* rf) ./ (B-rf*A)\n  rt = z'*wt\n  σt = (wt'*Σ*wt)^(0.5)\n\n  pth = \"C:\\\\Users\\\\Clinton\\\\Dropbox\\\\AAtawork\\\\ChernovInvestments\\\\Investments\\\\2020\\\\Exams\\\\final\"\n  p = plot(σs, μs,\n    yaxis = (\"E(r)\", (0.0,0.16), :none),\n    yticks=(0.0:0.02:0.16),\n    xaxis=(\"vol\", (0.0,0.4),),\n    xticks=(0.0:0.05:0.4),\n    title=\"Minimum Variance Frontier\",\n    legend=:none,\n    linestyle=:dot,\n    linecolor=:black)\n\n  pans = p |> deepcopy\n\n  plot!(pans, [0.0; σt; σs[μs .> rt]], [rf; rt; μs[μs .> rt]],\n    linestyle=:dash, seriestype=:path, linecolor=:black, linewidth=4,\n    annotations=(σt*1.5, rt*1.2,\n    Plots.text(\"min var frontier\\n (rf asset, no borrowing)\", :left, 7,)))\n  plot!(pans, [0.0; σt; σt*10], [rf; rt; (rt-rf)*10],\n    linestyle=:solid, seriestype=:path, linecolor=:black, linewidth=2,\n    annotations=(σt*1.1, rt*1.6,\n    Plots.text(\"min varfrontier\\n (rf asset, borrowing)\", :left, 7,)))\n\n  #scatter!(pans, [0.0], [rf], markersize=6)\n  scatter!(pans, [σt], [rt], markersize=6,\n    annotations=(σt+0.005, rt-0.0025, Plots.text(\"tangency portfolio\", :left, 7,)))\n  scatter!(pans, [σg], [rg],markersize=6,\n    annotations=(σg+0.005, rg-0.0025, Plots.text(\"global min var portfolio\", :left, 7,)))\n  savefig(p, \"$pth\\\\problem3.pdf\")\n  savefig(pans, \"$pth\\\\problemans3.pdf\")\n\nend\n\n\n@time gengraphs()\n", "meta": {"hexsha": "e51f56d0f38eb3727d0f29ff4d2d1a2ec5f85bb8", "size": 3165, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Capacity/src/Experimentation/testq.jl", "max_stars_repo_name": "clintonTE/CCA", "max_stars_repo_head_hexsha": "a555cc1fa4b6d5f1464de44e2e322d32336d1e3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Capacity/src/Experimentation/testq.jl", "max_issues_repo_name": "clintonTE/CCA", "max_issues_repo_head_hexsha": "a555cc1fa4b6d5f1464de44e2e322d32336d1e3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Capacity/src/Experimentation/testq.jl", "max_forks_repo_name": "clintonTE/CCA", "max_forks_repo_head_hexsha": "a555cc1fa4b6d5f1464de44e2e322d32336d1e3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1570247934, "max_line_length": 100, "alphanum_fraction": 0.5968404423, "num_tokens": 1330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.752612724979606}}
{"text": "function get_non_dominated_solutions_perm(population)\n    ids = Int[1]\n    n = length(population)\n\n    for i in 2:n\n        j = 1\n        while j <= length(ids)\n            jj = ids[j]\n            relation = compare(population[i], population[jj])\n \n            if relation == 2 # j dominates i\n                break\n            elseif relation == 1 # i dominates j\n                deleteat!(ids, j)\n                continue\n            end\n\n            j += 1\n        end\n\n        if j > length(ids)\n            push!(ids, i)\n        end\n        \n    end\n\n    return ids\nend\n\n\nfunction get_non_dominated_solutions(population)\n\n    mask = get_non_dominated_solutions_perm(population)\n    return population[mask]\n\nend\n\n\n\"\"\"\n    gen_ref_dirs(dimension, n_paritions)\nGenerates Das and Dennis's structured reference points. `dimension` could be\nthe number of objective functions in multi-objective functions.\n\"\"\"\nfunction gen_ref_dirs(dimension, n_paritions)\n    return  gen_weights(dimension, n_paritions)\nend\n\nfunction gen_weights(a, b)\n    nobj = a;\n    H    = b;\n    a    = zeros(nobj);\n    d    = H;\n    w    = [];\n    produce_weight!(a, 1, d, H, nobj, w)\n    return Array.(w)\nend\n\nfunction  produce_weight!(a, i, d, H, nobj, w)\n    for k=0:d\n        if i<nobj\n            a[i] = k;\n            d2   = d - k;\n            produce_weight!(a, i+1, d2, H, nobj, w);\n        else\n            a[i] = d;\n            push!(w, a/H)\n            break;\n        end\n    end\nend\n\n\n\"\"\"\n    ideal(points)\n\nComputes the ideal point from a provided array of `Vector`s or a population or row vectors\nin a `Matrix`.\n\"\"\"\nfunction ideal(points::Array{Vector{T}}) where T <: Real \n\n    isempty(points) && isempty(points[1]) && return zeros(0)\n    \n    ideal = points[1]\n\n    for point in points\n        ideal = min.(ideal, point)\n    end\n\n    return ideal\n\nend\n\n\n\"\"\"\n    nadir(points)\n\nComputes the nadir point from a provided array of `Vector`s or a population or row vectors\nin a `Matrix`.\n\"\"\"\nfunction nadir(points::Array{Vector{T}})  where T <: Real\n \n    isempty(points) && isempty(points[1]) && return zeros(0)\n    \n    nadir = points[1]\n\n    for point in points\n        nadir = max.(nadir, point)\n    end\n\n    return nadir\nend\n\n\nfunction ideal(population::Array{xFgh_indiv})\n    mask = sum_violations.(population) .== 0\n\n    ideal(fval.(population[mask]))\nend\nideal(A::Matrix) = ideal([A[i,:]  for i in 1:size(A,1)])\n\nfunction nadir(population::Array{xFgh_indiv})\n    mask = sum_violations.(population) .== 0\n\n    nadir(fval.(population[mask]))\nend\n\nnadir(A::Matrix) = nadir([A[i,:]  for i in 1:size(A,1)])\n", "meta": {"hexsha": "ca6e78ba0b432d7a3805a2b7e12111d1a3bd48c5", "size": 2592, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/common/multi-objective-functions.jl", "max_stars_repo_name": "pitmonticone/Metaheuristics.jl", "max_stars_repo_head_hexsha": "d429ff51cc921e7166d44e1c15d69f9041b8a0cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common/multi-objective-functions.jl", "max_issues_repo_name": "pitmonticone/Metaheuristics.jl", "max_issues_repo_head_hexsha": "d429ff51cc921e7166d44e1c15d69f9041b8a0cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/multi-objective-functions.jl", "max_forks_repo_name": "pitmonticone/Metaheuristics.jl", "max_forks_repo_head_hexsha": "d429ff51cc921e7166d44e1c15d69f9041b8a0cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.25, "max_line_length": 90, "alphanum_fraction": 0.5825617284, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7526127115470493}}
{"text": "\"\"\"\n    $(SIGNATURES)\n\nDiscretize given percentiles (unweighted). The smallest `pctV[1]` of values in `inV` end up in bin 1, etc.\n\"\"\"\nfunction discretize_given_percentiles(inV :: AbstractVector{F1}, \n    pctV :: AbstractVector{F2}) where {F1, F2}\n\n    edgeV = bin_edges_from_percentiles(inV, pctV);\n    return discretize(inV, edgeV)\nend\n\n\n\"\"\"\n    $(SIGNATURES)\n\nDiscretize given percentiles (weighted). The smallest `pctV[1]` of values in `inV` end up in bin 1, etc.\n\"\"\"\nfunction discretize_given_percentiles(inV :: AbstractVector{F1}, \n    wtV :: AbstractVector{F2}, \n    pctV :: AbstractVector{F3}) where {F1, F2, F3}\n\n   edgeV = bin_edges_from_percentiles(inV, wtV, pctV);\n   return discretize(inV, edgeV)\nend\n\n\n## Discretize given bounds\n# Equivalent to Discretizers LinearDiscretizer\nfunction discretize(inV :: AbstractVector{F1}, \n    edgeV :: AbstractVector{F2}) where {F1, F2}\n\n    n = length(edgeV);\n    outV = zeros(Int64, size(inV));\n    for i1 = n : -1 : 2\n        outV[inV .<= edgeV[i1]] .= i1 - 1;\n    end\n    outV[inV .<= edgeV[1]] .= 0;\n    return outV\nend\n\n\n\n\"\"\"\nBin edges from percentiles (unweighted)\nLowest bin includes minimum of inV\n\"\"\"\nfunction bin_edges_from_percentiles(inV :: AbstractVector{F1}, \n    pctV :: AbstractVector{F2}) where {F1, F2}\n\n    edgeV = quantile(inV, [zero(F2); pctV]);\n    # Ensure that lowest point is inside edges\n    edgeV[1] -= F1(1e-8);\n    return edgeV\nend\n\n\n## Bin edges from percentiles (weighted)\nfunction bin_edges_from_percentiles(inV :: AbstractVector{F1},  \n    wtV :: AbstractVector{F2}, pctV :: AbstractVector{F3}) where {F1, F2, F3}\n\n    @assert check_weights(wtV)  \"Invalid weights\"\n    # Quantile is also a built in function\n    edgeV = [minimum(inV) - F1(1e-8); quantile(inV, Weights(wtV), pctV)];\n    edgeV[end] += F1(1e-8);\n    return edgeV\nend\n\n\n\"\"\"\n\t$(SIGNATURES)\n\nCount how many cases occur in each bin. Unweighted.\n\"\"\"\nfunction count_bins(inV :: AbstractVector{F1}, \n    edgeV :: AbstractVector{F2}) where {F1, F2}\n\n    nBins = length(edgeV) - 1;\n    cntV = Vector{Int}(undef, nBins);\n    for iBin = 1 : nBins\n        cntV[iBin] = sum(x -> inbin(x, edgeV, iBin), inV);\n    end\n    return cntV\nend\n\n\n\"\"\"\n\t$(SIGNATURES)\n\nCount how many cases occur in each bin. Weighted.\n\"\"\"\nfunction count_bins(inV :: AbstractVector{F1}, \n    wtV :: AbstractVector{F2},\n    edgeV :: AbstractVector{F3}) where {F1, F2, F3}\n\n    @assert check_weights(wtV)  \"Invalid weights\"\n    nBins = length(edgeV) - 1;\n    massV = Vector{Float64}(undef, nBins);\n    for iBin = 1 : nBins\n        massV[iBin] = mapreduce(\n            (x, wt) -> (inbin(x, edgeV, iBin) ? wt : zero(F2)), \n            +, inV, wtV);\n    end\n    return massV\nend\n\ninbin(x, edgeV, iBin) = (x > edgeV[iBin])  &&  (x <= edgeV[iBin+1]);\n\nfunction check_weights(wtV :: AbstractVector{F1}) where F1\n    isValid = true;\n    if any_less(wtV, zero(F1))\n        @warn \"Negative weights\"\n        isValid = false;\n    end\n    return isValid\nend\n\n\n# ------------", "meta": {"hexsha": "bbdd0568aecdd9914be276d2ff0f116eb8639e8a", "size": 2965, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stats/discretize.jl", "max_stars_repo_name": "hendri54/CommonLH", "max_stars_repo_head_hexsha": "aba46201434da0c3fec6476b66de750eb1f7e493", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stats/discretize.jl", "max_issues_repo_name": "hendri54/CommonLH", "max_issues_repo_head_hexsha": "aba46201434da0c3fec6476b66de750eb1f7e493", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stats/discretize.jl", "max_forks_repo_name": "hendri54/CommonLH", "max_forks_repo_head_hexsha": "aba46201434da0c3fec6476b66de750eb1f7e493", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9159663866, "max_line_length": 106, "alphanum_fraction": 0.6387858347, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7526127115470493}}
{"text": "mutable struct TrackedReal{T<:Real}\n    data::T\n    grad::Union{Nothing,T}\n    children::Dict\n    # this field is only need for printing the graph. you can safely remove it.\n    name::String\nend\n\ntrack(x::Real,name=\"\") = TrackedReal(x,nothing,Dict(),name)\n\nfunction Base.show(io::IO, x::TrackedReal)\n    t = isempty(x.name) ? \"(tracked)\" : \"(tracked $(x.name))\"\n    print(io, \"$(x.data) $t\")\nend\n\nfunction accum!(x::TrackedReal)\n    if isnothing(x.grad)\n        x.grad = sum(accum!(v)*w for (v,w) in x.children)\n    end\n    x.grad\nend\n\nfunction gradient(f, args::Real...)\n    ts = track.(args)\n    y  = f(ts...)\n    y.grad = 1.0\n    accum!.(ts)\nend\n\n\n##########  RULES  #############################################################\n\nfunction Base.:*(a::TrackedReal, b::TrackedReal)\n    z = track(a.data * b.data, \"*\")\n    a.children[z] = b.data  # dz/da=b\n    b.children[z] = a.data  # dz/db=a\n    z\nend\nfunction Base.:+(a::TrackedReal{T}, b::TrackedReal{T}) where T\n    z = track(a.data + b.data, \"+\")\n    a.children[z] = one(T)\n    b.children[z] = one(T)\n    z\nend\nfunction Base.sin(x::TrackedReal)\n    z = track(sin(x.data), \"sin\")\n    x.children[z] = cos(x.data)\n    z\nend\n\n\n##########  Optimizion 2D function  ############################################\n\nusing Plots\ng(x,y) = y*y + sin(x)\ncscheme = cgrad(:RdYlBu_5, rev=true)\np1 = contour(-4:0.1:4, -2:0.1:2, g, fill=true, c=cscheme, xlabel=\"x\", ylabel=\"y\")\ndisplay(p1)\n\n\nfunction descend(f::Function, λ::Real, args::Real...)\n    Δargs = gradient(f, args...)\n    args .- λ .* Δargs\nend\n\nfunction minimize(f::Function, args::T...; niters=20, λ=0.01) where T<:Real\n    paths = ntuple(_->Vector{T}(undef,niters), length(args))\n    for i in 1:niters\n        args = descend(f, λ, args...)\n        @info f(args...)\n        for j in 1:length(args)\n            paths[j][i] = args[j]\n        end\n    end\n    paths\nend\n\nxs1, ys1 = minimize(g, 1.5, -2.4, λ=0.2, niters=34)\nxs2, ys2 = minimize(g, 1.8, -2.4, λ=0.2, niters=16)\n\nscatter!(p1, [xs1[1]], [ys1[1]], markercolor=:black, marker=:star, ms=7, label=\"Minimum\")\nscatter!(p1, [xs2[1]], [ys2[1]], markercolor=:black, marker=:star, ms=7, label=false)\nscatter!(p1, [-π/2], [0], markercolor=:red, marker=:star, ms=7, label=\"Initial Point\")\nscatter!(p1, xs1[1:1], ys1[1:1], markercolor=:black, label=\"GD Path\", xlims=(-4,4), ylims=(-2,2))\n\nanim = @animate for i in 1:max(length(xs1), length(xs2))\n    if i <= length(xs1)\n        scatter!(p1, xs1[1:i], ys1[1:i], mc=:black, lw=3, xlims=(-4,4), ylims=(-2,2), label=false)\n    end\n    if i <= length(xs2)\n        scatter!(p1, xs2[1:i], ys2[1:i], mc=:black, lw=3, label=false)\n    end\n    p1\nend\n\ngif(anim, \"gd-path.gif\", fps=15)\n", "meta": {"hexsha": "0081d4edd1e07f95fe84c31b64d84fbffa977ea4", "size": 2669, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/lecture_08/ScalarReverseDiff.jl", "max_stars_repo_name": "JuliaTeachingCTU/Scientific-Programming-in-Julia", "max_stars_repo_head_hexsha": "7e978fc27ae547fbf95d1367ef1d1d029267e356", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2021-11-12T10:17:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T21:40:39.000Z", "max_issues_repo_path": "docs/src/lecture_08/ScalarReverseDiff.jl", "max_issues_repo_name": "JuliaTeachingCTU/Scientific-Programming-in-Julia", "max_issues_repo_head_hexsha": "7e978fc27ae547fbf95d1367ef1d1d029267e356", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-10-06T09:32:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T15:15:03.000Z", "max_forks_repo_path": "docs/src/lecture_08/ScalarReverseDiff.jl", "max_forks_repo_name": "JuliaTeachingCTU/Scientific-Programming-in-Julia", "max_forks_repo_head_hexsha": "7e978fc27ae547fbf95d1367ef1d1d029267e356", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-05T16:45:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T18:21:34.000Z", "avg_line_length": 27.5154639175, "max_line_length": 98, "alphanum_fraction": 0.5605095541, "num_tokens": 925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7525949747238257}}
{"text": "\n\n\t# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\t\n\t#\tUsing librarys\n\t# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\t\n\t# GNU Scientific Library\n\tusing GSL ;\n\t\n\t# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\t\n\t#\tSpecial functions related\n\t# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\t\n\t\n\t# Spherical Bessel function first kind j_n(x)\n\tfunction Sbessj( i::Int64 , x )\n\t\treturn sqrt(pi*(1/(2*x)))*besselj(i+1.0/2,x) ;\n\tend\t\n\n\t# Spherical Bessel function second kind n_n(x) [Neumann]\n\tfunction Sneum( i::Int64 ,x )\n\t\tsqrt(pi*(1/(2*x)))*bessely(i+1.0/2,x) ;\n\tend\t\n\t\n\t# Spherical Bessel function first kind derivative ( Morse & Feshbach definition )\n\tfunction Sbessj_p( i::Int64 , x ) \n \t\treturn (1/(2*i+1))*(i*Sbessj(i-1,x) - (i+1)*Sbessj(i+1,x)) ; \n\tend\t\n\t\n\t# Spherical Bessel second kind ( Neumann ) derivative\n\tfunction Sneum_p( i::Int64 , x )\n\t\treturn Sneum(i-1,x) - ((i+1)/x)*Sneum(i,x) ;\n\tend\t\n\t\n\t# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\t\n\t#\tLiquid Sphere\n\t# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\t\n\t\n\t# Liquid sphere coefficient\n\tfunction Coef_LiquidSphere( n::Int64, x1::Float64 )\n\t\treturn x1*Sbessj_p( n, x1 )/Sbessj( n, x1 ) ;  \n\tend\n\t\n\t# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\t\n\t#\tProlate/Oblate auxiliar\n\t# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\t\n\t\n\tfunction Index( M::Int64, i::Int64, j::Int64 )\n\t\tif j < i # Domain errors\n\t\t\treturn\tdisplay(\"ERROR: j < i\");\n\t\tend\n\t\tif i > M + 1 || j > M + 1  \n\t\t\treturn\tdisplay(\"ERROR: M < i-1, j-1\");\n\t\tend\n\t\treturn map( Int64, j + ( M + 1 )*( i - 1 ) - i*( i - 1 )/2 );\n\tend\n\n\t# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\t\n\t#\tFile I/O\n\t# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\t\n\t\n\tfunction ReadFileToArrayBF( file::AbstractString, sep::Char, elem::Int )\n\t#\tRead 'file' (as BigFloat) with values 'sep' separated.\n\t#\tA newline in the 'file' means that the retrieved structure will be a matrix\n\t# \tThe 'elem' parameter selects all the entries (elem = 0) or a particular value\n\t# \t(elem = number)\n\t\tif elem == 0 # Return entire vector or matrix\n\t\t\treturn map( x -> parse(BigFloat,x), readdlm( file, sep ,ASCIIString) );\n\t\telse # Return only the specified element\n\t\t\treturn map( x -> parse(BigFloat,x), [readdlm( file, sep ,ASCIIString)[elem]] )[ 1 ] ;\n\t\tend\t\n\tend\n\t\n\tfunction ReadFileToArrayBF2( file::AbstractString, sep::Char, row::Any, col::Any )\n\t#\tRead 'file' (as BigFloat) with values 'sep' separated.\n\t# \tReturned value is a matrix in general.\n\t\treturn map( x -> parse(BigFloat,x), collect( readdlm( file, sep ,ASCIIString)[row,col] ) ) ;\n\tend \t\n\t\n\t\n\t# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\t\n\t#\tEigenvalues (prolate)\n\t# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\t\n\t\n\tfunction pro_lambdamn_approx( c::Any, m::Int64, n::Int64 )\n\t\t# Transcription to Julia of the AGD (Adelman, Gumerov & Duraiswami) MATLAB code.\n\t\t# View ' pro_calculate_lambdamn_approx.m ' in the AGD source directory\n\t\tconvert( Float64, c ) ;\n\t\tconst N = m + n + 200 ; # Size of the matrix\n\t\tconst A = zeros( Float64, N, N ) ;\n\t\tif ( mod( n - m, 2) == 0 )\n\t\t\tr = 0 ; # even\n\t\telse\n\t\t\tr = 1 ; # odd\n\t\tend\n\t\t# Fill in the A matrix\n\t\tfor i = 1 : N\n\t\t\tif i == 1 \n\t\t\t\tA[ 1, 1 ] = calculate_betar( c, m, r ) ;\n\t\t\t\tA[ 1, 2 ] = calculate_alphar( c, m, r ) ;\n\t\t\telseif  i == N \n\t\t\t\tA[ N, N - 1 ] = calculate_gammar( c, m, r ) ;\n\t\t\t\tA[ N, N ] = calculate_betar( c, m, r ) ;\n\t\t\telse\n\t\t\t\tA[ i, i - 1 ] = calculate_gammar( c, m, r ) ;\n\t\t\t\tA[ i, i ] = calculate_betar( c, m, r ) ;\n\t\t\t\tA[ i, i + 1 ] = calculate_alphar( c, m, r ) ;\n\t\t\tend\n\t\t\tr = r + 2;\n\t\tend\n\t\tconst d = eigvals!(A);\n\t\tif ( mod(n - m, 2) == 0 )\n\t\t\tconst lambda_approx = real(d[ Int( (n - m + 2) / 2 ) ]) ;\n\t\telse\n\t\t\tconst lambda_approx = real(d[ Int( (n - m + 1) / 2 ) ]) ;\n\t\tend\n\t\tfilename = @ sprintf(\"data/pro_%08d_%03d_%03d_lambda_approx.txt\", trunc( Int, c*1000 ), m, n ) ;\n\t\twritedlm( filename,lambda_approx );\n\tend\n\t\n\tfunction calculate_alphar( c::Float64, m::Int64, r::Int64 )\n\t\treturn ((( 2 * m + r + 2 )*( 2 * m + r + 1 ))/\n\t\t(( 2 * m + 2 * r + 5 )*( 2 * m + 2 * r + 3 )))*( c*c );\n\tend\n\t\n\tfunction calculate_betar( c::Float64, m::Int64, r::Int64 )\n\t\treturn ( m + r )*( m + r + 1 ) + (( 2*( m + r )*( m + r + 1 ) - 2*(m*m) - 1) /\n\t\t(( 2*m + 2*r - 1 )*( 2*m + 2 * r + 3 )))*(c*c);\n\tend\n\t\n\tfunction calculate_gammar( c::Float64, m::Int64, r::Int64 )\n\t\treturn (( r * (r - 1) )/(( 2*m + 2*r - 3 )*( 2*m + 2*r - 1 )))*(c*c);\n\tend\n\t\n\t# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\t\n\t#\tEigenvalues (oblate)\n\t# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\t\n\t\n\tfunction obl_lambdamn_approx( c::Any, m::Int64, n::Int64 )\n\t\t# Transcription to Julia of the AGD (Adelman, Gumerov & Duraiswami) MATLAB code.\n\t\t# View ' obl_calculate_lambdamn_approx.m ' in the AGD source directory\n\t\tconvert( Float64, c ) ;\n\t\tconst N = m + n + 200 ; # Size of the matrix\n\t\tconst A = zeros( Float64, N, N ) ;\n\t\tif ( mod( n - m, 2) == 0 )\n\t\t\tr = 0 ; # even\n\t\telse\n\t\t\tr = 1 ; # odd\n\t\tend\n\t\t# Fill in the A matrix\n\t\tfor i = 1 : N\n\t\t\tif i == 1 \n\t\t\t\tA[ 1, 1 ] = calculate_betar_obl( c, m, r ) ;\n\t\t\t\tA[ 1, 2 ] = calculate_alphar_obl( c, m, r ) ;\n\t\t\telseif  i == N \n\t\t\t\tA[ N, N - 1 ] = calculate_gammar_obl( c, m, r ) ;\n\t\t\t\tA[ N, N ] = calculate_betar_obl( c, m, r ) ;\n\t\t\telse\n\t\t\t\tA[ i, i - 1 ] = calculate_gammar_obl( c, m, r ) ;\n\t\t\t\tA[ i, i ] = calculate_betar_obl( c, m, r ) ;\n\t\t\t\tA[ i, i + 1 ] = calculate_alphar_obl( c, m, r ) ;\n\t\t\tend\n\t\t\tr = r + 2;\n\t\tend\n\t\tconst d = eigvals!(A);\n\t\tif ( mod( n - m, 2 ) == 0 )\n\t\t\tconst lambda_approx = real(d[ Int( (n - m + 2) / 2 ) ]) ;\n\t\telse\n\t\t\tconst lambda_approx = real(d[ Int( (n - m + 1) / 2 ) ]) ;\n\t\tend\n\t\tfilename = @ sprintf(\"data/obl_%08d_%03d_%03d_lambda_approx.txt\", trunc( Int, c*1000 ), m, n ) ;\n\t\twritedlm( filename,lambda_approx );\n\tend\t\n\t\n\t\n\tfunction calculate_alphar_obl( c::Float64, m::Int64, r::Int64 )\n\t\treturn ((( 2 * m + r + 2 )*( 2 * m + r + 1 ))/\n\t\t(( 2 * m + 2 * r + 5 )*( 2 * m + 2 * r + 3 )))*( -c*c );\n\tend\n\t\n\tfunction calculate_betar_obl( c::Float64, m::Int64, r::Int64 )\n\t\treturn ( m + r )*( m + r + 1 ) + (( 2*( m + r )*( m + r + 1 ) - 2*(m*m) - 1) /\n\t\t(( 2*m + 2*r - 1 )*( 2*m + 2 * r + 3 )))*(-c*c);\n\tend\n\t\n\tfunction calculate_gammar_obl( c::Float64, m::Int64, r::Int64 )\n\t\treturn (( r * (r - 1) )/(( 2*m + 2*r - 3 )*( 2*m + 2*r - 1 )))*(-c*c);\n\tend\t\t\n", "meta": {"hexsha": "366ffd879da69665eb07780c5fdc3087216dcfe7", "size": 6741, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linux/JUL.auxiliar.jl", "max_stars_repo_name": "elavia/liquid_spheroid", "max_stars_repo_head_hexsha": "99883b4a0f5cad9e55ab889b910135e109951214", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-18T07:37:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T07:37:21.000Z", "max_issues_repo_path": "linux/JUL.auxiliar.jl", "max_issues_repo_name": "elavia/liquid_spheroid", "max_issues_repo_head_hexsha": "99883b4a0f5cad9e55ab889b910135e109951214", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linux/JUL.auxiliar.jl", "max_forks_repo_name": "elavia/liquid_spheroid", "max_forks_repo_head_hexsha": "99883b4a0f5cad9e55ab889b910135e109951214", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-18T07:37:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T07:37:40.000Z", "avg_line_length": 35.109375, "max_line_length": 98, "alphanum_fraction": 0.46105919, "num_tokens": 2275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.752591936578327}}
{"text": "using MinFEM\nusing LinearAlgebra\n\nfunction semilinear(mesh::Mesh, L::AbstractMatrix, M::AbstractMatrix,\n                    s::AbstractVector, BoundaryIndices::Set{Int64}=[], tol=1e-10)\n\n  y = zeros(mesh.nnodes)\n\n  pde = PDESystem(A=L, b=M*s, bc=zeros(mesh.nnodes), DI=BoundaryIndices)\n\n  res = Inf\n  while res > tol\n    pde.A = L + asmCubicDerivativeMatrix(mesh, y)\n    pde.b = -L*y + M*s - asmCubicTerm(mesh, y)\n    refresh(pde)\n    solve(pde)\n\n    y += pde.state\n    res = norm(pde.state)\n    println(res)\n  end\n  return y\nend\n\nmesh = import_mesh(\"../meshes/semilinear.msh\")\n\nL = asmLaplacian(mesh)\nM = asmMassMatrix(mesh)\n\n# y = 3*sin(x[1]*pi)*sin(x[2]*pi)\nf(x) = 3*2*pi^2*sin(x[1]*pi)*sin(x[2]*pi) + (3*sin(x[1]*pi)*sin(x[2]*pi))^3\ns = evaluateMeshFunction(mesh, f)\n\nboundary = union(mesh.Boundaries[1001].Nodes,\n                 mesh.Boundaries[1002].Nodes,\n                 mesh.Boundaries[1003].Nodes,\n                 mesh.Boundaries[1004].Nodes);\n\ny = semilinear(mesh, L, M, s, boundary);\n\nvtkfile = open_vtk_file(mesh, \"semilinear.vtu\")\nwrite_point_data(vtkfile, y, \"y\")\nwrite_point_data(vtkfile, s, \"s\")\nsave_vtk_file(vtkfile)\n", "meta": {"hexsha": "130c4660560b4e78200afcbfe26a61eed1f29d75", "size": 1139, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/semilinear.jl", "max_stars_repo_name": "msiebenborn/MinFEM.jl", "max_stars_repo_head_hexsha": "f703c4c227d90ed0c327bc84ca5cd566119a3cd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-03T18:16:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T17:07:42.000Z", "max_issues_repo_path": "examples/semilinear.jl", "max_issues_repo_name": "msiebenborn/MinFEM.jl", "max_issues_repo_head_hexsha": "f703c4c227d90ed0c327bc84ca5cd566119a3cd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-15T17:02:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-15T17:02:07.000Z", "max_forks_repo_path": "examples/semilinear.jl", "max_forks_repo_name": "msiebenborn/MinFEM.jl", "max_forks_repo_head_hexsha": "f703c4c227d90ed0c327bc84ca5cd566119a3cd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-06-02T08:06:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T17:07:47.000Z", "avg_line_length": 25.3111111111, "max_line_length": 81, "alphanum_fraction": 0.6356453029, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7525919320241345}}
{"text": "const year = 365.25 * 24. * 60. * 60.\n\nGtCO2_to_ppm(GtCO2) = GtCO2 / (2.13 * (44. /12.))\ntCO2_to_ppm(tCO2) = GtCO2_to_ppm(tCO2) * 1.e-9\n\nppm_to_GtCO2(ppm) = ppm * (2.13 * (44. /12.))\nppm_to_tCO2(ppm) = ppm_to_GtCO2(ppm) * 1.e9", "meta": {"hexsha": "a8c87526f72b6028034509f497c6fe3d9d359fb5", "size": 226, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Utils/unit_conversions.jl", "max_stars_repo_name": "pitmonticone/ClimateMARGO.jl", "max_stars_repo_head_hexsha": "0d89578cc22c0034aedf2a747fe1840603c3cec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2020-11-03T17:10:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:53:29.000Z", "max_issues_repo_path": "src/Utils/unit_conversions.jl", "max_issues_repo_name": "pitmonticone/ClimateMARGO.jl", "max_issues_repo_head_hexsha": "0d89578cc22c0034aedf2a747fe1840603c3cec1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2020-10-25T23:12:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T13:18:09.000Z", "max_forks_repo_path": "src/Utils/unit_conversions.jl", "max_forks_repo_name": "pitmonticone/ClimateMARGO.jl", "max_forks_repo_head_hexsha": "0d89578cc22c0034aedf2a747fe1840603c3cec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-11-24T11:56:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T13:11:35.000Z", "avg_line_length": 32.2857142857, "max_line_length": 49, "alphanum_fraction": 0.6194690265, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172572644806, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7525919262379765}}
{"text": "module BaryTrees\n\n    using Plots, LinearAlgebra\n\n    import Base.∈, Base.∉, Plots.Shape, Base.insert!\n\n    export BaryTree, Point, insert!, ∈, ∉, Draw, Draw!, Query, BaryCentric,\n           Cartesian2BaryCentric, BaryCentric2Cartesian\n\n    const Point = Tuple{Float64,Float64}\n\n    Point(x::Float64,y::Float64) = Point((x,y))\n\n    struct BaryCentric\n        \"\"\"\n            Represents the 3 cartesian (2D) points of a Barycentric\n            coordinate system\n        \"\"\"\n        r₁::Point\n        r₂::Point\n        r₃::Point\n    end\n\n    function BaryCentric2Cartesian(λ₁,λ₂,λ₃,p::BaryCentric)\n        return Point(\n            λ₁*p.r₁[1]+λ₂*p.r₂[1]+λ₃*p.r₃[1],\n            λ₁*p.r₁[2]+λ₂*p.r₂[2]+λ₃*p.r₃[2],\n        )\n    end\n\n    function Cartesian2BaryCentric(p::Point,b::BaryCentric)\n        x,y = p\n        x1,x2,x3 = b.r₁[1],b.r₂[1],b.r₃[1]\n        y1,y2,y3 = b.r₁[2],b.r₂[2],b.r₃[2]\n\n        l1 = ( (y2-y3)*(x-x3)+(x3-x2)*(y-y3) ) / ( (y2-y3)*(x1-x3) + (x3-x2)*(y1-y3) )\n        l2 = ( (y3-y1)*(x-x3) + (x1-x3)*(y-y3) ) / ( (y2-y3)*(x1-x3) + (x3-x2)*(y1-y3) )\n        return (\n            l1,l2,1.0-l1-l2,\n        )\n    end\n\n    function Medians(b::BaryCentric)::Vector{Point}\n        \"\"\"\n            Returns the three mid points of each triangular edge of\n            the triangle defining b in cartesian units\n        \"\"\"\n        return [\n            BaryCentric2Cartesian(1/2,0,1/2,b)\n            BaryCentric2Cartesian(0,1/2,1/2,b)\n            BaryCentric2Cartesian(1/2,1/2,0,b)\n        ]\n    end\n\n    struct AxisAlignedTriangle\n        \"\"\"\n            wrapper around BaryCentric\n        \"\"\"\n        b::BaryCentric\n    end\n\n    Medians(t::AxisAlignedTriangle)::Vector{Point} = Medians(t.b)\n\n    mutable struct BaryTree\n        root::Bool\n        boundary::AxisAlignedTriangle\n        point::Union{Nothing,Point}\n        c::Union{Nothing,BaryTree}\n        t::Union{Nothing,BaryTree}\n        l::Union{Nothing,BaryTree}\n        r::Union{Nothing,BaryTree}\n    end\n\n    function ∈(p::Point,t::AxisAlignedTriangle)::Bool\n        \"\"\"\n            Test if a cartesian point is inside a triangle\n                using BaryCentric Coordinates of the triangle\n        \"\"\"\n        b = Cartesian2BaryCentric(p,t.b)\n        if (b[1] >= 0 && b[2] >= 0 && b[1]+b[2] < 1)\n            return true\n        else\n            return false\n        end\n    end\n\n    function points(a::AxisAlignedTriangle)::Vector{Point}\n        \"\"\"\n            Short hand for the corners of an AxisAlignedTriangle\n        \"\"\"\n        return  Point.([\n                a.b.r₁,\n                a.b.r₂,\n                a.b.r₃\n            ])\n    end\n\n    function intersects(a::AxisAlignedTriangle,b::AxisAlignedTriangle)::Bool\n        \"\"\"\n            Tests if any of the corners of triangle a are in triangle b\n        \"\"\"\n        for p in points(a)\n            if p ∈ b\n                return true\n            end\n        end\n        return false\n    end\n\n    ∉(p::Point,t::AxisAlignedTriangle)::Bool = !∈(p,t)\n\n    function subdivide(t::AxisAlignedTriangle)::Vector{AxisAlignedTriangle}\n        \"\"\"\n            Subdivides a triangle (as in the Sierpinski construction) and returns\n            them each initialised with their own coordinate systems\n        \"\"\"\n        m1,m2,m3 = Medians(t)\n        return AxisAlignedTriangle.([\n            BaryCentric(t.b.r₁,m3,m1),\n            BaryCentric(m3,m2,m1),\n            BaryCentric(m3,t.b.r₂,m2),\n            BaryCentric(m1,m2,t.b.r₃)\n        ])\n\n    end\n\n    ∈(p::Point,q::BaryTree)::Bool = ∈(p,q.boundary)\n    ∉(p::Point,q::BaryTree)::Bool = ∉(p,q.boundary)\n    isempty(q::BaryTree)::Bool = q.point == nothing\n\n    BaryTree(a::AxisAlignedTriangle)::BaryTree = BaryTree(false,a,nothing,nothing,nothing,nothing,nothing)\n    BaryTree(r::Bool,a::AxisAlignedTriangle)::BaryTree = BaryTree(r,a,nothing,nothing,nothing,nothing,nothing)\n    BaryTree(a::BaryCentric)::BaryTree = BaryTree(AxisAlignedTriangle(a))\n\n    function subdivide!(q::BaryTree)::Nothing\n        \"\"\"\n            Subdivide this tree node as in the Sierpinski construction\n            and store it in t,c,l,r child nodes\n        \"\"\"\n        trigs = subdivide(q.boundary)\n        q.t = BaryTree(trigs[1])\n        q.c = BaryTree(trigs[2])\n        q.l = BaryTree(trigs[3])\n        q.r = BaryTree(trigs[4])\n        nothing\n    end\n\n    function insert!(p::Point,q::BaryTree)::Bool\n        \"\"\"\n            Trial an insert of point p (cartesian) in q's\n            triangular boundary\n        \"\"\"\n        if (p ∉ q)\n            return false\n        end\n\n        if isempty(q) && q.t == nothing\n            subdivide!(q)\n            if p ∈ q.t\n                q.t.point = p\n            end\n\n            if p ∈ q.c\n                q.c.point = p\n            end\n            if p ∈ q.l\n                q.l.point = p\n            end\n            if p ∈ q.r\n                q.r.point = p\n            end\n            return true\n        end\n\n        if (q.t == nothing)\n            subdivide!(q)\n        end\n\n        if insert!(p,q.t)\n            return true\n        end\n        if insert!(p,q.c)\n            return true\n        end\n        if insert!(p,q.l)\n            return true\n        end\n        if insert!(p,q.r)\n            return true\n        end\n\n        return false\n    end\n\n    Shape(a::AxisAlignedTriangle) = Shape(\n        Shape([a.b.r₁[1],a.b.r₂[1],a.b.r₃[1]],[a.b.r₁[2],a.b.r₂[2],a.b.r₃[2]])\n    )\n\n    function Draw!(a::AxisAlignedTriangle)\n        plot!(Shape(a),label=\"\",fillalpha=0.0)\n    end\n\n    function Draw(Q::BaryTree,points=true)\n        p = plot(aspect_ratio=:equal,label=\"\")\n        Draw!(Q.boundary)\n        for q in [Q.t,Q.c,Q.l,Q.r]\n            q != nothing ? Draw!(q,points) : nothing\n        end\n        return p\n    end\n\n    function Draw!(Q::BaryTree,points=true)\n        Draw!(Q.boundary)\n        for q in [Q.t,Q.c,Q.l,Q.r]\n            q != nothing ? Draw!(q) : nothing\n        end\n    end\n\n    function query(a::AxisAlignedTriangle, Q::BaryTree)\n        if ~intersects(a,Q.boundary)\n            return Vector{Point}([])\n        end\n\n        if Q.point == nothing\n            return Vector{Point}([])\n        end\n\n        result = Vector{Point}()\n\n        if (Q.point ∈ a)\n            push!(result,Q.point)\n        end\n\n        for q in [Q.t,Q.c,Q.l,Q.r]\n            if q != nothing\n                for p in query(a,q)\n                    push!(result,p)\n                end\n            end\n        end\n\n        return result\n    end\n\n    function size(Q::BaryTree)\n        s = 1\n        for q in [Q.t,Q.c,Q.l,Q.r]\n            if q != nothing\n                s += size(q)\n            end\n        end\n        return s\n    end\nend\n", "meta": {"hexsha": "0cd8a2a157ff544508cba77e052d3661b23892ec", "size": 6629, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "BaryTrees.jl", "max_stars_repo_name": "Jerboa-app/BaryTrees", "max_stars_repo_head_hexsha": "30a707eb1a38232f1711cab59a98a04953aa90c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BaryTrees.jl", "max_issues_repo_name": "Jerboa-app/BaryTrees", "max_issues_repo_head_hexsha": "30a707eb1a38232f1711cab59a98a04953aa90c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BaryTrees.jl", "max_forks_repo_name": "Jerboa-app/BaryTrees", "max_forks_repo_head_hexsha": "30a707eb1a38232f1711cab59a98a04953aa90c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9960784314, "max_line_length": 110, "alphanum_fraction": 0.5062603711, "num_tokens": 1930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875642, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.752591920365587}}
{"text": "#using Parameters\n@with_kw mutable struct Params\n# BWH parameters\n\n# Mathematical model parameters\n    α::Float64 = 33.3333         # infiltration rate in vegetated soil\n    f::Float64 = 0.1             # infiltration contrast\n    η::Float64 = 3.5             # root augmentation\n    γ::Float64 = 16.6667         # soil water consumption rate\n    ρ::Float64 = 0.95            # shading parameter\n    ν::Float64 = 3.3333          # soil water evaporation rate\n    q::Float64 = 0.05            # infiltration shape parameter\n    db::Float64 = 0.0333333      # b diffusivity\n    dw::Float64 = 3.33333        # w diffusivity\n    dh::Float64 = 333.333        # h diffusivity\n    p::Float64 = 1.2             # precipitation rate\n\n# Domain size\n    Lx::Float64 = 28             # nondimensional X Domain size\n    Ly::Float64 = 28             # nondimensional Y domain size\n\n# Numerical code options\n    nx::Int64 = 128              # X resolution\n    ny::Int64 = 128              # Y resolution\n    dx::Float64 = Lx/nx      \n    nsigma::Int64 = 12           # Number of sigmas in the integral approximation (12-16 probably ok)\n    nint::Int64 = 3              # Frequency for b and w integral calculation (could be 1, but not much more than 3)\n\n# Run control options\n    outfile = \"bwh.dat\"          # Name of output file\n    initfile = \"bwh.init.dat\"    # Name of initialization file (used if freadinit==true)\n    finalfile = \"bwh.final.dat\"  # Name of final state\n    freadinit::Bool = false      # Start from restart\n    fplot::Bool = false          # if to show plots during run\n    fsave::Bool = true           # if to save intermediate results\n    dt::Float64 = 0.1            # Length of a single integration chunk (this value seems ok)\n    nsave::Int64 = 10            # How often (in chunks) to save\n    nstep::Int64 = 100           # How many chuncks to run  (total runtime = nstep*dt)\nend\n\n", "meta": {"hexsha": "9388c7b8d32218696dcb05ddb2fb4b952ef2da32", "size": 1895, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Params.jl", "max_stars_repo_name": "jhardenberg/bwh", "max_stars_repo_head_hexsha": "52dcba3b257baa7ae3a7841e6f0f1853f246a7c2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Params.jl", "max_issues_repo_name": "jhardenberg/bwh", "max_issues_repo_head_hexsha": "52dcba3b257baa7ae3a7841e6f0f1853f246a7c2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Params.jl", "max_forks_repo_name": "jhardenberg/bwh", "max_forks_repo_head_hexsha": "52dcba3b257baa7ae3a7841e6f0f1853f246a7c2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-16T22:57:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-16T22:57:52.000Z", "avg_line_length": 46.2195121951, "max_line_length": 116, "alphanum_fraction": 0.5947229551, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.7525811121569767}}
{"text": "\"\"\"\n    belief_ellipse(b::GaussianBelief, P::Float=0.95; δ::Number=5)\n\nConstruct and return the x and y points of a 2D gaussian belief,\nwith P being the total probability captured by the ellipse (P ∈ (0,1)),\nand δ the degree increment between points.\n\"\"\"\nfunction belief_ellipse(b::GaussianBelief, P::Number=0.95; δ::Number=5)\n    @assert 0<P<1\n    @assert 0<δ<360\n\n    θ = (pi/180)*collect(0:δ:360)\n    rad_w = (-2*log(1-P))^0.5\n\n    w1 = rad_w*cos.(θ)\n    w2 = rad_w*sin.(θ)\n\n    Sig12 = cholesky(b.Σ)\n    x=Sig12.L*[w1 w2]' .+ b.μ\n    return x[1,:], x[2,:]\nend\n\n\"\"\"\n    belief_ellipse(μ::AbstractVector, Σ::AbstractMatrix, P::Float=0.95; δ::Number=5)\n\nConstruct and return the x and y points of a 2D gaussian belief,\nwith P being the total probability captured by the ellipse (P ∈ (0,1)),\nand δ the degree increment between points.\n\"\"\"\n\nfunction belief_ellipse(μ::AbstractVector, Σ::AbstractMatrix, P::Number=0.95; δ::Number=5)\n    @assert 0<P<1\n    @assert 0<δ<360\n\n    θ = (pi/180)*collect(0:δ:360)\n    rad_w = (-2*log(1-P))^0.5\n\n    w1 = rad_w*cos.(θ)\n    w2 = rad_w*sin.(θ)\n\n    Sig12 = cholesky(Σ)\n    x = Sig12.L*[w1 w2]' .+ μ\n    return x[1,:], x[2,:]\nend\n", "meta": {"hexsha": "de937748988ee7aa69d4473b53153ea141eb2710", "size": 1166, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "JuliaTagBot/GaussianFilters.jl", "max_stars_repo_head_hexsha": "a509925631bbdde5b1adaa85024a436cfa14722f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2019-09-20T23:22:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:27:05.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "JuliaTagBot/GaussianFilters.jl", "max_issues_repo_head_hexsha": "a509925631bbdde5b1adaa85024a436cfa14722f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2019-09-21T00:10:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-06T20:48:10.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "JuliaTagBot/GaussianFilters.jl", "max_forks_repo_head_hexsha": "a509925631bbdde5b1adaa85024a436cfa14722f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:41:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T12:54:23.000Z", "avg_line_length": 25.9111111111, "max_line_length": 90, "alphanum_fraction": 0.6295025729, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7525811085742073}}
{"text": "using Match\nusing Test\n\ninput = joinpath(@__DIR__, \"input\")\nraw = readlines(input)\n\nstruct Operation\n    name::String\n    value::Int\nend\n\nfunction operations(lines)\n    acc = []\n    for line in lines\n        if startswith(line, \"cut\")\n            _, n = split(line)\n            push!(acc, Operation(\"cut\", parse(Int, n)))\n        elseif startswith(line, \"deal into\")\n            push!(acc, Operation(\"reverse\", 0))\n        elseif startswith(line, \"deal with\")\n            _, _, _, n = split(line)\n            push!(acc, Operation(\"deal\", parse(Int, n)))\n        end\n    end\n    return acc\nend\n\ndeal = (c, n) -> return mod(-1 * c - 1, n)\ninc = (c, n, i) -> return mod(c * i, n)\ncut = (c, n, i) -> return mod(c - i, n)\n\nfunction shuffle(idx, deck, ops)\n    c = idx\n    n = deck\n    for op in ops\n        @match op.name begin\n            \"cut\" => begin\n                c = cut(c, n, op.value)\n            end\n            \"reverse\" => begin\n                c = deal(c, n)\n            end\n            \"deal\" => begin\n                c = inc(c, n, op.value)\n            end\n        end\n    end\n    return c\nend\n\n\nfunction fshuffle(idx, deck, ops, iterations)\n    offset, increment = BigInt(0), BigInt(1)\n    for op in ops\n        @match op.name begin\n            \"cut\" => begin\n                n = mod(op.value, deck)\n                offset = mod(offset + n, deck)\n            end\n            \"reverse\" => begin\n                increment = mod(-1 * increment, deck)\n                offset = mod(-1 * offset - 1, deck)\n            end\n            \"deal\" => begin\n                n = invmod(mod(op.value, deck), deck)\n                increment = mod(increment * n, deck)\n                offset = mod(offset * n, deck)\n            end\n        end\n    end\n    i = powermod(increment, iterations, deck)\n    o = if increment != 1\n        (i - 1) * invmod(increment - 1, deck)\n    else\n        iterations\n    end\n    return mod(i * idx + o * offset, deck)\nend\n\nops = operations(raw)\np1 = shuffle(2019, 10007, ops)\n@assert p1 == 3589\n\nreverse!(ops)\np2 = fshuffle(2020, 119315717514047, ops, 101741582076661)\n@assert p2 == 4893716342290\n\n\nprint(\"-----------------------------------------------------------------------\\n\")\nprint(\"slam shuffle -- part one\\n    card: $p1\\n\")\nprint(\"slam shuffle -- part two\\n    card: $p2\\n\")\nprint(\"-----------------------------------------------------------------------\\n\")", "meta": {"hexsha": "6822030737755725b1e56fc54bc2b2c97417a1db", "size": 2391, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "bin/twentytwo/run.jl", "max_stars_repo_name": "talentdeficit/aoc2019", "max_stars_repo_head_hexsha": "70692f4fd61c3b640ce601bed3afdd74f93a5d73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-31T05:23:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-31T05:23:10.000Z", "max_issues_repo_path": "bin/twentytwo/run.jl", "max_issues_repo_name": "talentdeficit/aoc2019", "max_issues_repo_head_hexsha": "70692f4fd61c3b640ce601bed3afdd74f93a5d73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bin/twentytwo/run.jl", "max_forks_repo_name": "talentdeficit/aoc2019", "max_forks_repo_head_hexsha": "70692f4fd61c3b640ce601bed3afdd74f93a5d73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9891304348, "max_line_length": 82, "alphanum_fraction": 0.4755332497, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7525811054516585}}
{"text": "\nusing Random\nusing Soss\nusing DataFrames\nusing StatsPlots\nusing BenchmarkTools\n\n\n@inline function rate_to_proportion(r::Float64,t::Float64)\n    1-exp(-r*t)\nend;\n\n\nsir_markov = @model state,p begin\n    # Unpack parameters\n    β = p.β\n    c = p.c\n    γ = p.γ\n    δt = p.δt\n\n    # Unpack starting counts\n    t0 = state.t\n    S0 = state.S\n    I0 = state.I\n    R0 = state.R\n    N = S0 + I0 + R0\n\n    # Transitions between states\n    S_I ~ Binomial(S0, rate_to_proportion(β*c*I0/N,δt))\n    I_R ~ Binomial(I0, rate_to_proportion(γ,δt))\n\n    # Updated state\n    t = t0 + δt\n    S = S0 - S_I\n    I = I0 + S_I - I_R\n    R = R0 + I_R\n\n    next = (p=p, state=(t=t,S=S,I=I,R=R))\nend;\n\n\nsir_model = @model u0,p begin\n    x ~ MarkovChain(p, sir_markov(state=u0,p=p))\nend;\n\n\nδt = 0.1\nnsteps = 400\ntmax = nsteps*δt;\n\n\nu0 = (t=0.0, S=990, I=10, R=0); # t,S,I,R\n\n\np = (β=0.05, c=10.0, γ=0.25, δt=δt);\n\n\nRandom.seed!(1234);\n\n\nr = rand(sir_model(u0=u0,p=p));\ndata = [u0]\nfor (n,s) in enumerate(r.x)\n    n>nsteps && break\n    push!(data,s)\nend;\n\n\ndf_markov = DataFrame(data);\n\n\n@df df_markov plot(:t,\n    [:S :I :R],\n    label=[\"S\" \"I\" \"R\"],\n    xlabel=\"Time\",\n    ylabel=\"Number\")\n\n\n@benchmark begin\n    r = rand(sir_model(u0=u0,p=p));\n    data = [u0]\n    for (n,s) in enumerate(r.x)\n        n>nsteps && break\n        push!(data,s)\n    end\nend\n\n", "meta": {"hexsha": "c3aad14ecc59aa329717b885b80c3f0cba4cc029", "size": 1325, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/markov_soss/markov_soss.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 126, "max_stars_repo_stars_event_min_datetime": "2020-04-29T08:41:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:42:53.000Z", "max_issues_repo_path": "script/markov_soss/markov_soss.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2020-04-29T11:44:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:45:15.000Z", "max_forks_repo_path": "script/markov_soss/markov_soss.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2020-04-29T08:01:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T16:55:08.000Z", "avg_line_length": 15.0568181818, "max_line_length": 58, "alphanum_fraction": 0.5675471698, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012717045181, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.752534442881732}}
{"text": "# Description:\n# Dimensions: d\n#\n# The Styblinski-Tang function is shown here in its two-dimensional form.\n#\n# Input Domain:\n# The function is usually evaluated on the hypercube xi ∈ [-5, 5], for all i = 1, …, d.\n#\n# Global Minimum:\n# https://www.sfu.ca/~ssurjano/stybtang3.png\n\nfunction styblinskiTang(xx)\n    d = length(xx);\n    sum = 0;\n    for ii = 1:d\n       \txi = xx[ii];\n       \tnew = xi^4 - 16 * xi^2 + 5 * xi;\n       \tsum = sum + new;\n    end\n\n    y = sum / 2;\n\n    return [y]\nend\n", "meta": {"hexsha": "0a394fcce55fea3359b4ffb36a80fd1730980f57", "size": 490, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "styblinski-tang.jl", "max_stars_repo_name": "cagataycali/bacterial-foraging-optimization-algorithm", "max_stars_repo_head_hexsha": "b84ac0667707e36dbaa4a50457074245b174b491", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "styblinski-tang.jl", "max_issues_repo_name": "cagataycali/bacterial-foraging-optimization-algorithm", "max_issues_repo_head_hexsha": "b84ac0667707e36dbaa4a50457074245b174b491", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "styblinski-tang.jl", "max_forks_repo_name": "cagataycali/bacterial-foraging-optimization-algorithm", "max_forks_repo_head_hexsha": "b84ac0667707e36dbaa4a50457074245b174b491", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6, "max_line_length": 87, "alphanum_fraction": 0.5816326531, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012717045181, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7525344382989001}}
{"text": "export nrmsd\n\n\"\"\"\n    nrmsd(I,Ireco)\n\ncomputes the normalized root mean squared error of the image `Ireco`\nwith respect to the image `I`.\n\"\"\"\nfunction nrmsd(I,Ireco)\n  N = length(I)\n\n  # This is a little trick. We usually are not interested in simple scalings\n  # and therefore \"calibrate\" them away\n  alpha = (dot(vec(I),vec(Ireco))+dot(vec(Ireco),vec(I))) /\n          (2*dot(vec(Ireco),vec(Ireco)))\n  Ireco[:] .*= alpha\n\n  RMS =  1.0/sqrt(N)*norm(vec(I)-vec(Ireco))\n  NRMS = RMS/(maximum(abs.(I))-minimum(abs.(I)) )\n  return NRMS\nend\n", "meta": {"hexsha": "f17e08b5c1de9b6d67ec124e7ac12698056ef669", "size": 536, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Tools/ErrorMeasures.jl", "max_stars_repo_name": "UnofficialJuliaMirror/MRIReco.jl-bdf86e05-2d2b-5731-a332-f3fe1f9e047f", "max_stars_repo_head_hexsha": "f8ce9fcd09d81c166bae1359884489e7b0da0954", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2019-04-22T20:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T10:49:45.000Z", "max_issues_repo_path": "src/Tools/ErrorMeasures.jl", "max_issues_repo_name": "UnofficialJuliaMirror/MRIReco.jl-bdf86e05-2d2b-5731-a332-f3fe1f9e047f", "max_issues_repo_head_hexsha": "f8ce9fcd09d81c166bae1359884489e7b0da0954", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 49, "max_issues_repo_issues_event_min_datetime": "2018-11-03T09:34:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T15:13:07.000Z", "max_forks_repo_path": "src/Tools/ErrorMeasures.jl", "max_forks_repo_name": "UnofficialJuliaMirror/MRIReco.jl-bdf86e05-2d2b-5731-a332-f3fe1f9e047f", "max_forks_repo_head_hexsha": "f8ce9fcd09d81c166bae1359884489e7b0da0954", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2019-04-23T21:34:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T08:34:17.000Z", "avg_line_length": 24.3636363636, "max_line_length": 76, "alphanum_fraction": 0.6492537313, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.7524915291498785}}
{"text": "doc\"\"\"\n    Exponential(θ)\n\nThe *Exponential distribution* with scale parameter `θ` has probability density function\n\n$f(x; \\theta) = \\frac{1}{\\theta} e^{-\\frac{x}{\\theta}}, \\quad x > 0$\n\n```julia\nExponential()      # Exponential distribution with unit scale, i.e. Exponential(1)\nExponential(b)     # Exponential distribution with scale b\n\nparams(d)          # Get the parameters, i.e. (b,)\nscale(d)           # Get the scale parameter, i.e. b\nrate(d)            # Get the rate parameter, i.e. 1 / b\n```\n\nExternal links\n\n* [Exponential distribution on Wikipedia](http://en.wikipedia.org/wiki/Exponential_distribution)\n\n\"\"\"\nimmutable Exponential{T<:Real} <: ContinuousUnivariateDistribution\n    θ::T\t\t# note: scale not rate\n\n    Exponential(θ::Real) = (@check_args(Exponential, θ > zero(θ)); new(θ))\nend\n\nExponential{T<:Real}(θ::T) = Exponential{T}(θ)\nExponential(θ::Integer) = Exponential(Float64(θ))\nExponential() = Exponential(1.0)\n\n@distr_support Exponential 0.0 Inf\n\n### Conversions\nconvert{T <: Real, S <: Real}(::Type{Exponential{T}}, θ::S) = Exponential(T(θ))\nconvert{T <: Real, S <: Real}(::Type{Exponential{T}}, d::Exponential{S}) = Exponential(T(d.θ))\n\n\n#### Parameters\n\nscale(d::Exponential) = d.θ\nrate(d::Exponential) = 1 / d.θ\n\nparams(d::Exponential) = (d.θ,)\n@inline partype{T<:Real}(d::Exponential{T}) = T\n\n\n#### Statistics\n\nmean(d::Exponential) = d.θ\nmedian(d::Exponential) = logtwo * d.θ\nmode{T<:Real}(d::Exponential{T}) = zero(T)\n\nvar(d::Exponential) = d.θ^2\nskewness{T<:Real}(d::Exponential{T}) = T(2)\nkurtosis{T<:Real}(d::Exponential{T}) = T(6)\n\nentropy(d::Exponential) = 1 + log(d.θ)\n\n\n#### Evaluation\n\nzval(d::Exponential, x::Real) = x / d.θ\nxval(d::Exponential, z::Real) = z * d.θ\n\npdf(d::Exponential, x::Real) = (λ = rate(d); x < 0 ? zero(λ) : λ * exp(-λ * x))\nfunction logpdf{T<:Real}(d::Exponential{T}, x::Real)\n    (λ = rate(d); x < 0 ? -T(Inf) : log(λ) - λ * x)\nend\n\ncdf{T<:Real}(d::Exponential{T}, x::Real) = x > 0 ? -expm1(-zval(d, x)) : zero(T)\nccdf{T<:Real}(d::Exponential{T}, x::Real) = x > 0 ? exp(-zval(d, x)) : zero(T)\nlogcdf{T<:Real}(d::Exponential{T}, x::Real) = x > 0 ? log1mexp(-zval(d, x)) : -T(Inf)\nlogccdf{T<:Real}(d::Exponential{T}, x::Real) = x > 0 ? -zval(d, x) : zero(T)\n\nquantile(d::Exponential, p::Real) = -xval(d, log1p(-p))\ncquantile(d::Exponential, p::Real) = -xval(d, log(p))\ninvlogcdf(d::Exponential, lp::Real) = -xval(d, log1mexp(lp))\ninvlogccdf(d::Exponential, lp::Real) = -xval(d, lp)\n\ngradlogpdf{T<:Real}(d::Exponential{T}, x::Real) = x > 0 ? -rate(d) : zero(T)\n\nmgf(d::Exponential, t::Real) = 1/(1 - t * scale(d))\ncf(d::Exponential, t::Real) = 1/(1 - t * im * scale(d))\n\n\n#### Sampling\n\nrand(d::Exponential) = xval(d, randexp())\n\n\n#### Fit model\n\nimmutable ExponentialStats <: SufficientStats\n    sx::Float64   # (weighted) sum of x\n    sw::Float64   # sum of sample weights\n\n    ExponentialStats(sx::Real, sw::Real) = new(sx, sw)\nend\n\nsuffstats{T<:Real}(::Type{Exponential}, x::AbstractArray{T}) = ExponentialStats(sum(x), length(x))\nsuffstats{T<:Real}(::Type{Exponential}, x::AbstractArray{T}, w::AbstractArray{Float64}) = ExponentialStats(dot(x, w), sum(w))\n\nfit_mle(::Type{Exponential}, ss::ExponentialStats) = Exponential(ss.sx / ss.sw)\n", "meta": {"hexsha": "b733ee95fd78fcbe740f6ff2f19221323e8aec37", "size": 3200, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/exponential.jl", "max_stars_repo_name": "JuliaPackageMirrors/Distributions.jl", "max_stars_repo_head_hexsha": "091cad865281c92746dc455cc50f4b2a311d3dd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/exponential.jl", "max_issues_repo_name": "JuliaPackageMirrors/Distributions.jl", "max_issues_repo_head_hexsha": "091cad865281c92746dc455cc50f4b2a311d3dd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/exponential.jl", "max_forks_repo_name": "JuliaPackageMirrors/Distributions.jl", "max_forks_repo_head_hexsha": "091cad865281c92746dc455cc50f4b2a311d3dd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4761904762, "max_line_length": 125, "alphanum_fraction": 0.635625, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7524915215544368}}
{"text": "\"\"\"\nGraph Laplacian of a `m×n` lattice.\n\"\"\"\nfunction gridlaplacian(T, m, n)\n    S = sparse(T(0.0)I, n*m, n*m)\n    linear = LinearIndices((1:m, 1:n))\n    for i in 1:m\n        for j in 1:n\n            for (i2, j2) in ((i + 1, j), (i, j + 1))\n                if i2 <= m && j2 <= n\n                    S[linear[i, j], linear[i2, j2]] -= 1\n                    S[linear[i2, j2], linear[i, j]] -= 1\n\n                    S[linear[i, j], linear[i, j]] += 1\n                    S[linear[i2, j2], linear[i2, j2]] += 1\n                end\n            end\n        end\n    end\n    S\nend\n", "meta": {"hexsha": "c746961dcf773d9286727adb23d8209ee42ac2f2", "size": 573, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/gridlaplace.jl", "max_stars_repo_name": "vincentmolin/ZigZagBoomerang.jl", "max_stars_repo_head_hexsha": "40a318230854d5e1f560ea54ec46c1b970ce116e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 60, "max_stars_repo_stars_event_min_datetime": "2020-07-02T12:59:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T13:07:02.000Z", "max_issues_repo_path": "scripts/gridlaplace.jl", "max_issues_repo_name": "vincentmolin/ZigZagBoomerang.jl", "max_issues_repo_head_hexsha": "40a318230854d5e1f560ea54ec46c1b970ce116e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47, "max_issues_repo_issues_event_min_datetime": "2020-07-02T10:13:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T15:38:42.000Z", "max_forks_repo_path": "scripts/gridlaplace.jl", "max_forks_repo_name": "vincentmolin/ZigZagBoomerang.jl", "max_forks_repo_head_hexsha": "40a318230854d5e1f560ea54ec46c1b970ce116e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-07-02T16:25:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T11:51:27.000Z", "avg_line_length": 26.0454545455, "max_line_length": 58, "alphanum_fraction": 0.3891797557, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.815232480373843, "lm_q1q2_score": 0.7524915143014206}}
{"text": "using DifferentialEquations\nusing Plots\nplotlyjs()\n\n#constants\nm = 1.0                             # mass[Kg]\ng = 9.81                            # gravitational acceleration [m/s²]\n\n#function to compute the ODEs\nfunction pendulum!(du,u,p,t)\n    r,v,θ,ω=u\n    du[1]=dr=v                   \n    du[2]=dv=r*ω^2+g*cos(θ)\n    du[3]=dθ=ω                    \n    du[4] =dω=-(g\\r)*sin(θ) - (2*v*ω)/r  \nend\n\n#initial conditions\nr₀=4                            #initial radial distance\nv₀=-0.1                          #initial radial velocity \nθ₀ = 1π/18                        # initial angular deflection [rad]\nω₀ = 1                       # initial angular velocity [rad/s]\nu₀ = [r₀,v₀,θ₀, ω₀]                   # initial state vector\ntspan = (0.0,5.0)             # time interval\n\n#defining the problem and solving\nprob = ODEProblem(pendulum!,u₀,tspan)\nsol = solve(prob,saveat=0.1)\n\n#plotting\np1=plot(sol,vars=(0,1),label=\"r\",\n    color=\"purple\", xaxis=\"t (s)\", yaxis=\"r (m)\")\np2=plot(sol,vars=(0,2),label=\"v\",\n    color=\"blue\", xaxis=\"t (s)\", yaxis=\"v (m/s)\")\np3=plot(sol,vars=(0,3),label=\"θ\",\n    color=\"green\", xaxis=\"t (s)\", yaxis=\"θ (rad)\")\np4=plot(sol,vars=(0,4),label=\"ω\",\n    color=\"orange\", xaxis=\"t (s)\", yaxis=\"ω (rad/s)\")\ndisplay(plot(p1,p2,p3,p4,layout=(2,2)))\nsavefig(\"./plots/simple length changing pendulum-plot.png\")\n\n#trajectory\nt=sol.t\nU=sol[1:end,:]\n(r,v,θ,ω)=[U[x,:] for x in 1:size(U,1)]\nx=r.*sin.(θ)\ny=zeros(size(t))\nz=r.*cos.(θ)\ndisplay(plot(x,y,z,linewidth=2,label=\"trajectory\",\n    xaxis=\"x (m)\",yaxis=\"y (m)\",zaxis=\"z (m)\",grid=(:on,:black)))\nsavefig(\"./plots/simple length changing pendulum-trajectory.png\")\n", "meta": {"hexsha": "cbf14f6f87dc26a1d71efa11954af2a362c93dd4", "size": 1632, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Modeling the Dragon Module as a Pendulum/Scripts/length changing pendulum.jl", "max_stars_repo_name": "Ramana-bharathi/modelling-recovery-module", "max_stars_repo_head_hexsha": "7d522aef4ae184f7ca9991056de7327e2a782eef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Modeling the Dragon Module as a Pendulum/Scripts/length changing pendulum.jl", "max_issues_repo_name": "Ramana-bharathi/modelling-recovery-module", "max_issues_repo_head_hexsha": "7d522aef4ae184f7ca9991056de7327e2a782eef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modeling the Dragon Module as a Pendulum/Scripts/length changing pendulum.jl", "max_forks_repo_name": "Ramana-bharathi/modelling-recovery-module", "max_forks_repo_head_hexsha": "7d522aef4ae184f7ca9991056de7327e2a782eef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3846153846, "max_line_length": 71, "alphanum_fraction": 0.5508578431, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488964, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.752476742738606}}
{"text": "#!/usr/bin/julia\n\n# Trizen\n# Date: 19 August 2016\n# https://github.com/trizen\n\n# Count the number of partitions of n, using a recursive relation.\n\n# See also: https://oeis.org/A000041\n#           https://en.wikipedia.org/wiki/Partition_(number_theory)\n\nfunction partitions_count(n::Int64, cache::Dict{Int,Int})\n\n    n <= 1 && return n\n\n    if haskey(cache, n)\n        return cache[n]\n    end\n\n    sum_1 = 0\n    for i in 1:Int64(floor((sqrt(24*n + 1) + 1)/6))\n        sum_1 += ((-1)^(i-1) * partitions_count(n - div(i*(3*i - 1), 2), cache))\n    end\n\n    sum_2 = 0\n    for i in 1:Int64(ceil((sqrt(24*n + 1) - 7)/6))\n        sum_2 += ((-1)^(i-1) * partitions_count(n - div((-i) * (-3*i - 1), 2), cache))\n    end\n\n    x = (sum_1 + sum_2)\n    cache[n] = x\n    x\nend\n\nprintln(\"P(200) = \", partitions_count(200+1, Dict{Int64, Int64}()))        # 3972999029388\n", "meta": {"hexsha": "45a66dc0f9633df6eb42a343c069f5c61d2e5f1e", "size": 853, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Math/count_partitions_rec.jl", "max_stars_repo_name": "trizen/julia-scripts", "max_stars_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-03-22T09:38:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T21:38:31.000Z", "max_issues_repo_path": "Math/count_partitions_rec.jl", "max_issues_repo_name": "trizen/julia-scripts", "max_issues_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/count_partitions_rec.jl", "max_forks_repo_name": "trizen/julia-scripts", "max_forks_repo_head_hexsha": "26015006f2b37e0fcdb9dc4a96ea37a8b312a7ec", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6944444444, "max_line_length": 90, "alphanum_fraction": 0.570926143, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7524767348026509}}
{"text": "\"\"\"\n    min_even_theta_char(R)\n\nCompute the even theta characteristic for which the theta constant at the input matrix in R has the smallest absolute value.\n\"\"\"\nfunction min_even_theta_char(R::RiemannMatrix)\n    z = zeros(R.g);\n    even_chars = even_theta_char(R.g);\n    min_theta, char_index = findmin([abs(theta(z, R, char=c)) for c in even_chars])\n    char = even_chars[char_index];\n    return char\nend\n\n\"\"\"\n    hessian(z, R, char=[])\n\nCompute the hessian matrix of the theta function at input z and input matrix in R, with optional characteristics. \n\"\"\"\nfunction hessian(z::Array{<:Number}, R::RiemannMatrix, char::Array{}=[])\n    M = zeros(Complex{Float64}, R.g, R.g);\n    for i=1:R.g\n        for j=i:R.g\n            derivs = [zeros(R.g), zeros(R.g)];\n            derivs[1][i] = 1;\n            derivs[2][j] = 1;\n            M[i,j] = theta(z, R, char=char, derivs=derivs);\n            M[j,i] = M[i,j];\n        end\n    end\n    return M\nend\n\n\n\"\"\"\n    hessian(z, τ, char=[], siegel=true, ϵ=1.0e-12)\n\nCompute the hessian matrix of the theta function at inputs z and τ, with optional characteristics, and optional inputs specifying whether to compute the Siegel transformation and the error in the value of the theta function. \n\"\"\"\nfunction hessian(z::Array{<:Number}, τ::Array{<:Number}, char::Array{}=[]; siegel::Bool=true, ϵ::Real=1.0e-12)\n    R = RiemannMatrix(τ, siegel=siegel, ϵ=ϵ, nderivs=2);\n    return hessian(z, R, char)\nend\n\n\n\"\"\"\n    schottky_null(R, tol=1.0e-8)\n\nCompute the even theta characteristic where the theta constant vanishes and the hessian matrix at the characteristic, as well as its nonzero eigenvalues, up to the input tolerance. Returns an array containing the characteristic, the hessian and the nonzero eigenvalues. If there is no such characteristic, return the absolute value of the theta constant at the smallest even characteristic.\n\"\"\"\nfunction schottky_null(R::RiemannMatrix, tol::Real=1.0e-8)\n    char = min_even_theta_char(R);\n    z = zeros(R.g);\n    theta_value = abs(theta(z, R, char=char));\n    if theta_value < tol # check that there is a vanishing theta null\n        H = hessian(z, R, char);\n        hessian_eigvals = filter(x -> abs(x) > tol, eigvals(H));\n        return [char, H, hessian_eigvals]\n    end\n    return theta_value\nend\n\n\n\"\"\"\n    schottky_null(τ, tol=1.0e-8)\n\nCompute the even theta characteristic where the theta constant vanishes and the hessian matrix at the characteristic, as well as its nonzero eigenvalues, up to the input tolerance. Returns an array containing the characteristic, the hessian and the nonzero eigenvalues. If there is no such characteristic, return the absolute value of the theta constant at the smallest even characteristic.\n\"\"\"\nfunction schottky_null(τ::Array{<:Number}, tol::Real=1.0e-8)\n    R = RiemannMatrix(τ, ϵ=tol, nderivs=2);\n    return schottky_null(R, tol)\nend\n", "meta": {"hexsha": "bcce2ffdaf7a59b79b659c655eb300f6d355cb31", "size": 2852, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/schottky_null.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Theta.jl-42bdb5c4-78fb-11e9-2233-215979c148c4", "max_stars_repo_head_hexsha": "a34991260be574b5d556a53a2acf59037d4459df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/schottky_null.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Theta.jl-42bdb5c4-78fb-11e9-2233-215979c148c4", "max_issues_repo_head_hexsha": "a34991260be574b5d556a53a2acf59037d4459df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/schottky_null.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Theta.jl-42bdb5c4-78fb-11e9-2233-215979c148c4", "max_forks_repo_head_hexsha": "a34991260be574b5d556a53a2acf59037d4459df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6111111111, "max_line_length": 390, "alphanum_fraction": 0.690743338, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362858, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7524557594545251}}
{"text": "module cheb\nusing LinearAlgebra\n\nexport chebdif, projmat\n\n\"\"\"\nflippy():\n    Utility function that flips matrix up-down and left-right\n        (or, equivalently, rotates it by 180deg).\n\"\"\"\nfunction flippy(M)\n    M[end:-1:1,end:-1:1]\nend\n\n\"\"\"\nchebdif():\n\nJulia translation of the MATLAB routine by J.A.C. Weideman & S.C. Reddy (1998).\n\nOriginal MATAB documentation:\n\n%  The function DM =  chebdif(N,M) computes the differentiation\n%  matrices D1, D2, ..., DM on Chebyshev nodes.\n%\n%  Input:\n%  N:        Size of differentiation matrix.\n%  M:        Number of derivatives required (integer).\n%  Note:     0 < M <= N-1.\n%\n%  Output:\n%  DM:       DM(1:N,1:N,ell) contains ell-th derivative matrix, ell=1..M.\n%\n%  The code implements two strategies for enhanced\n%  accuracy suggested by W. Don and S. Solomonoff in\n%  SIAM J. Sci. Comp. Vol. 6, pp. 1253--1268 (1994).\n%  The two strategies are (a) the use of trigonometric\n%  identities to avoid the computation of differences\n%  x(k)-x(j) and (b) the use of the \"flipping trick\"\n%  which is necessary since sin t can be computed to high\n%  relative precision when t is small whereas sin (pi-t) cannot.\n%\n% J.A.C. Weideman, S.C. Reddy 1998.\n\n\"\"\"\nfunction chebdif(N::Integer,M::Integer)\n    I  = diagm(ones(N))             # Identity matrix\n    L  = I.!=0                      # Logical identity matrix\n\n    n1 = N÷2;    n2 = n1 + N%2      # Indices used for flipping trick.\n\n    k  = collect(0:N-1)             # Compute theta vector.\n    th = k * π/(N-1)\n\n    temp = collect(N-1:-2:1-N)\n    x  = sin.(π*temp/(2.0*(N-1)))   # Compute Chebyshev points\n\n    T  = repeat(th/2,1,N)\n    DX = 2*sin.(T'+T) .* sin.(T'-T) # Trigonometric identity.\n\n    DX = [DX[1:n1,:]; -flippy(DX[1:n2,:])]\n    DX[L] .= 1.0\n\n    temp = (-1.0).^k\n    C = temp * temp'  # generates a Toeplitz matrix with diagonal of +1 and alternating signs on diags\n    C[1,:]   *= 2;      C[end,:] *= 2\n    C[:,1]   *= 0.5;    C[:,end] *= 0.5\n\n    Z = 1.0./DX\n    Z[L] .= 0.0\n    D = diagm(ones(N))\n\n    s = size(D)\n    DM = zeros(s...,M)\n    De = zeros(n2,n2,M)\n    Do = zeros(n2,n2,M)\n    (Pe,Po,Qe,Qo) = projmat(N)\n\n    for ell in 1:M\n        D = ell * Z .* (C .* repeat(diag(D),1,N) - D)\n        D[L] = -sum(D,dims=2)\n        DM[:,:,ell] = D\n        if ell%2 == 0 # 2nd, 4th, 6th etc derivatives do not change parity\n            De[:,:,ell] = Pe * D * Qe\n            Do[:,:,ell] = Po * D * Qo\n        else # 1st, 3rd, 5th etc derivatives change parity\n            De[:,:,ell] = Po * D * Qe\n            Do[:,:,ell] = Pe * D * Qo\n        end\n    end\n    return (x,DM,De,Do)\nend\n\n\"\"\"\nprojmat():\n\n    Constructs projection matrices to project (and de-project) onto space of\n    even and odd functions, from general space of functions.\n\n    I could try to be clever here, dealing with N odd or even, but I forgo\n    cleverness in favor of readability. (In all likelihood this could be done\n    in far fewer lines, I'm sure.)\n\n    2*Peve' de-projects an even function back onto the full function space.\n    2*Podd' de-projects an odd function back onto the full function space.\n\n    Peve is the inverse of dPeve\n    Podd is the inverse of dPodd\n\"\"\"\nfunction projmat(N::Integer)\n    n1 = N÷2;  n2 = n1 + N%2\n    isNodd = (n2>n1) # is N odd?\n    top = diagm(ones(n2))\n    if isNodd\n        Qodd = [ top[1:n2,:] ; -top[n1:-1:1,:] ]\n        Qodd[n2,:] .*= 0\n        Podd = Qodd' *0.5\n        Qeve = [ top[1:n2,:] ; top[n1:-1:1,:] ]\n        Peve = Qeve' *0.5\n        Peve[:,n2] .*= 2\n    else\n        Qodd = [ top[1:n1,:] ; -top[n1:-1:1,:] ]\n        Qeve = [ top[1:n1,:] ;  top[n1:-1:1,:] ]\n        Podd = Qodd' *0.5\n        Peve = Qeve' *0.5\n    end\n    return (Peve,Podd,Qeve,Qodd)\nend\n\nend#module\n", "meta": {"hexsha": "2171787c65ce6f37ef9576aaef7026c8ed7d29f5", "size": 3698, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "cheb.jl", "max_stars_repo_name": "diakosmos/razor", "max_stars_repo_head_hexsha": "8479a950b1da8c04483b846445b262b2c2605a33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cheb.jl", "max_issues_repo_name": "diakosmos/razor", "max_issues_repo_head_hexsha": "8479a950b1da8c04483b846445b262b2c2605a33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cheb.jl", "max_forks_repo_name": "diakosmos/razor", "max_forks_repo_head_hexsha": "8479a950b1da8c04483b846445b262b2c2605a33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4461538462, "max_line_length": 102, "alphanum_fraction": 0.5624661979, "num_tokens": 1270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7524557557240991}}
{"text": "using Base.Threads\n\n\"\"\"\n    euler_matrix(α::Real, β::Real, γ::Real)\n\nReturns the rotation matrix A based on rotation along the euler angles α, β and γ corresponding to rotations around the x, y, and z-axis respectively.\n\"\"\"\nfunction euler_matrix(α::Real, β::Real, γ::Real)\n    [\n        (cos(β)*cos(γ))                         (-cos(β)*sin(γ))                        sin(β)\n        (cos(α)*sin(γ) + cos(γ)*sin(α)*sin(β))  (cos(α)*cos(γ) - sin(α)*sin(β)*sin(γ))  (-cos(β)*sin(α))\n        (sin(α)*sin(γ) - cos(α)*cos(γ)*sin(β))  (cos(γ)*sin(β) + cos(α)*sin(β)*sin(γ))  (cos(α)*cos(β))\n\n    ]\nend\n\n\n\"\"\"\n    rotate_3D_quantity(x, α, β, γ)\n\nRotates a 3D vector along the x-axis with angle α, y-axis with angle β and z-axis with angle γ.\n\"\"\"\nfunction rotate_3D_quantity(x::Array{<:Real}, α::Real, β::Real, γ::Real)\n\n    A = euler_matrix(α, β, γ)\n\n    return A * x\nend\n\n\n\"\"\"\n    rotate_3D(x::Array{<:Real}, alpha::Real, beta::Real, gamma::Real)\n\nRotates and array of 3D positions around the euler angles α, β and γ corresponding to rotations around the x, y, and z-axis respectively.\nα, β and γ need to be given in degrees.\n\"\"\"\nfunction rotate_3D(x::Array{<:Real}, alpha::Real, beta::Real, gamma::Real)\n\n    α = deg2rad(alpha)\n    β = deg2rad(beta)\n    γ = deg2rad(gamma)\n\n    N = size(x,2)\n    ret = Array{eltype(x[1]),2}(undef, 3, N)\n    @threads for i = 1:N\n        @inbounds ret[:,i] = rotate_3D_quantity(x[:,i], α, β, γ)\n    end\n\n    return ret\nend\n\n\n\"\"\"\n    rotate_3D!(x::Array{<:Real}, alpha::Real, beta::Real, gamma::Real)\n\nRotates and array of 3D positions around the euler angles α, β and γ corresponding to rotations around the x, y, and z-axis respectively.\nα, β and γ need to be given in degrees.\n\"\"\"\nfunction rotate_3D!(x::Array{<:Real}, alpha::Real, beta::Real, gamma::Real)\n\n    α = deg2rad(alpha)\n    β = deg2rad(beta)\n    γ = deg2rad(gamma)\n\n    @threads for i = 1:size(x,2)\n        @inbounds x[:,i] = rotate_3D_quantity(x[:,i], α, β, γ)\n    end\n\n    return x\nend\n\n\n\"\"\"\n    rotate_to_xz_plane!(x::Array{<:Real})\n\nRotates an array of 3D positions into the xz-plane.\n\"\"\"\nfunction rotate_to_xz_plane!(x::Array{<:Real}) \n\n    @inbounds for i = 1:size(x,2)\n        pos3   = copy(x[2,i])\n        x[2,i] = x[3,i]\n        x[3,i] = pos3\n    end\n    x\nend\n\n\"\"\"\n    rotate_to_xz_plane!(x::Array{<:Real})\n\nRotates an array of 3D positions into the xz-plane.\n\"\"\"\nfunction rotate_to_xz_plane!(x::Array{<:Real}, x_in::Array{<:Real}) \n\n    @inbounds for i = 1:size(x,2)\n        x[1,i] = x_in[1,i]\n        x[2,i] = x_in[3,i]\n        x[3,i] = x_in[2,i]\n    end\n    x\nend\n\n\"\"\"\n    rotate_to_yz_plane(x::Array{<:Real})\n\nRotates an array of 3D positions into the yz-plane.\n\"\"\"\nfunction rotate_to_yz_plane!(x::Array{<:Real}) \n\n    @inbounds for i = 1:size(x,2)\n        pos3   = copy(x[1,i])\n        x[1,i] = x[2,i]\n        x[2,i] = x[3,i]\n        x[3,i] = pos3\n    end\n    x\nend\n\n\"\"\"\n    rotate_to_yz_plane(x::Array{<:Real}, x_in::Array{<:Real})\n\nRotates an array of 3D positions into the yz-plane.\n\"\"\"\nfunction rotate_to_yz_plane!(x::Array{<:Real}, x_in::Array{<:Real}) \n\n    @inbounds for i = 1:size(x,1)\n        x[1,i] = x_in[2,i]\n        x[2,i] = x_in[3,i]\n        x[3,i] = x_in[1,i]\n    end\n    x\nend\n\n\"\"\"\n    project_along_axis!(x::Array{<:Real}, projection_axis::Integer=3)\n\nProjects and array of 3D along one of the principle axes.\nprojection_axis ∈ {1, 2, 3} => x, y, z axis.\n\"\"\"\nfunction project_along_axis!(x::Array{<:Real}, projection_axis::Integer=3)\n   \n    # rotation to xy-plane -> nothing is done\n    if projection_axis == 3\n        return x\n    end\n\n    # rotation to xz-plane\n    if projection_axis == 2\n        return rotate_to_xz_plane!(x)\n    end\n\n    # rotation to yz-plane\n    if projection_axis == 1\n        return rotate_to_yz_plane!(x)\n    end\nend\n\n\"\"\"\n    project_along_axis!(x::Array{<:Real}, projection_axis::Integer=3)\n\nProjects and array of 3D along one of the principle axes.\nprojection_axis ∈ {1, 2, 3} => x, y, z axis.\n\"\"\"\nfunction project_along_axis!(x::Array{<:Real}, x_in::Array{<:Real}, projection_axis::Integer=3)\n   \n    # rotation to xy-plane -> nothing is done\n    if projection_axis == 3\n        return x_in\n    end\n\n    # rotation to xz-plane\n    if projection_axis == 2\n        return rotate_to_xz_plane!(x, x_in)\n    end\n\n    # rotation to yz-plane\n    if projection_axis == 1\n        return rotate_to_yz_plane!(x, x_in)\n    end\nend\n\n\"\"\"\n    project_along_axis!(x::Array{<:Real}, projection_axis::Integer=3)\n\nProjects and array of 3D along one of the principle axes.\nprojection_axis ∈ {1, 2, 3} => x, y, z axis.\n\"\"\"\nfunction project_along_axis(x::Array{<:Real}, projection_axis::Integer=3)\n   \n    # allocate new array\n    ret = Array{eltype(x[1]),2}(undef, 3, size(x,2))\n\n    # rotation to xy-plane -> nothing is done\n    if projection_axis == 3\n        return x\n    end\n\n    # rotation to xz-plane\n    if projection_axis == 2\n        return rotate_to_xz_plane!(ret, x)\n    end\n\n    # rotation to yz-plane\n    if projection_axis == 1\n        return rotate_to_yz_plane!(ret, x)\n    end\nend", "meta": {"hexsha": "85e0bb91be481dd3d6ad7e0edba1405ac44d46cc", "size": 5025, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/shared/rotate_particles.jl", "max_stars_repo_name": "stevengj/SPHtoGrid.jl", "max_stars_repo_head_hexsha": "fef471bb7b2c93ce97952a80e3108760d2db4f23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-26T22:35:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T17:32:01.000Z", "max_issues_repo_path": "src/shared/rotate_particles.jl", "max_issues_repo_name": "stevengj/SPHtoGrid.jl", "max_issues_repo_head_hexsha": "fef471bb7b2c93ce97952a80e3108760d2db4f23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2020-07-17T07:56:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T13:53:31.000Z", "max_forks_repo_path": "src/shared/rotate_particles.jl", "max_forks_repo_name": "stevengj/SPHtoGrid.jl", "max_forks_repo_head_hexsha": "fef471bb7b2c93ce97952a80e3108760d2db4f23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-23T16:51:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T16:51:07.000Z", "avg_line_length": 24.2753623188, "max_line_length": 150, "alphanum_fraction": 0.6055721393, "num_tokens": 1666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7524557514741022}}
{"text": "#    Problem : GROUP A\n#    *********\n#\t Shanno's TRIDIA quadratic tridiagonal problem\n#\n#    Origonal SIF Source:problem 8 in\n#    Ph.L. Toint,\n#    \"Test problems for partially separable optimization and results\n#    for the routine PSPMIN\",\n#    Report 83/4, Department of Mathematics, FUNDP (Namur, B), 1983.\n#\n#    See also Buckley#40 (p.96)\n#\n#    TRIDIA.SIF classification QUR2-AN-V-0\n#\n#\t This problem is decomposed in n linear groups, the last n-1 of which\n#    are 2 x 2 and singular.\n#\n#    Number of variables is variable\n\nf = (x) -> begin\n\tfx   = (x[1]-1)^2\n\tfor i in firstindex(x)+1:lastindex(x)\n\t\titem    = 2x[i]-x[i-1]\n    \tfx     += item^2*i\n\tend\n    return fx\nend\n\ng! = (g, x) -> begin\n\tg[1] = 2(x[1]-1)\n\tfor i in firstindex(x)+1:lastindex(x)\n\t\titem    = 2x[i]-x[i-1]\n        g[i]   += 4item*i\n\t    g[i-1] -= 2item*i\n\tend\n    return g\nend\n\nfg! = (g, x) -> begin\n\tfx   = (x[1]-1)^2\n\tg[1] = 2(x[1]-1)\n\tfor i in firstindex(x)+1:lastindex(x)\n\t\titem    = 2x[i]-x[i-1]\n    \tfx     += item^2*i\n        g[i]   += 4item*i\n\t    g[i-1] -= 2item*i\n\tend\n    return fx, g\nend\n\ninit = (n::Int=5000) -> begin\n    return n, ones(n)\nend\n\nTestSet[\"TRIDIA\"] = UncProgram(\"TRIDIA\",f, g!, fg!, init)", "meta": {"hexsha": "830fee7c1e5220a804a953b0f3b3b689a5f37e1e", "size": 1195, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/programs/TRIDIA.jl", "max_stars_repo_name": "danphenderson/UncNLPrograms.jl", "max_stars_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/programs/TRIDIA.jl", "max_issues_repo_name": "danphenderson/UncNLPrograms.jl", "max_issues_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/programs/TRIDIA.jl", "max_forks_repo_name": "danphenderson/UncNLPrograms.jl", "max_forks_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7272727273, "max_line_length": 71, "alphanum_fraction": 0.5690376569, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7524557493491038}}
{"text": "import RowEchelon\n\n#=\nHomework 5\nSection 2.1\nProblem 2\n=#\n\n# Initialize all Matrices\nA = [2 0 -1 ; 4 -5 2]\nB = [7 -5 1 ; 1 -4 -3]\nC = [1 2 ;-2 1]\nD = [3 5 ; -1 4]\nE = [-5 ; 3]\n\nprintln(\"A + 3B: \")\nprintln(A+(3*B))\n\n# After this point, products may not exist\n# Use try/catch to find nonexistent products.\nprintln(\"2C - 3E:\")\ntry\n\tprintln((2*C) - (3*E))\ncatch\n\tprintln(\"2C - 3E cannot be computed.\")\nend\n\nprintln(\"DB:\")\ntry\n\tprintln(D*B)\ncatch\n\tprintln(\"DB cannot be computed.\")\nend\n\nprintln(\"EC:\")\ntry\n\tprintln(E*C)\ncatch\n\tprintln(\"EC cannot be computed.\")\nend\n", "meta": {"hexsha": "f352be78ea155b7447610f5436f76b7bbe2c8e13", "size": 560, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HW5_S2.1_P2.jl", "max_stars_repo_name": "tleecsm/J4LA", "max_stars_repo_head_hexsha": "0ff51fa1771e9b5fc0b8a684a65cb36cebb8eefb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW5_S2.1_P2.jl", "max_issues_repo_name": "tleecsm/J4LA", "max_issues_repo_head_hexsha": "0ff51fa1771e9b5fc0b8a684a65cb36cebb8eefb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW5_S2.1_P2.jl", "max_forks_repo_name": "tleecsm/J4LA", "max_forks_repo_head_hexsha": "0ff51fa1771e9b5fc0b8a684a65cb36cebb8eefb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.6585365854, "max_line_length": 45, "alphanum_fraction": 0.6196428571, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.752455748263247}}
{"text": "module FameSVD\nusing LinearAlgebra\n\nexport fsvd\n\nfunction fsvd(A::Array{R, 2}) where R<:AbstractFloat\n  dim = size(A)\n\n  V = Array{R, 2}(undef, dim[2], dim[2])\n  U = Array{R, 2}(undef, dim[1], dim[2])\n  S = Array{R, 1}(undef, dim[2])\n\n  V = BLAS.syrk('U', 'T', 1.0, A)\n  (S, V) = LAPACK.syevr!('V', 'A', 'U', V, 0., 0., 0, 0, 0.)\n\n  reverse!(S)\n  @inbounds for i = 1:dim[2]\n    @fastmath S[i] = sqrt(S[i])\n  end\n\n  V = reverse(V; dims = 2)\n  U = BLAS.gemm('N', 'N', A, V)\n\n  # TODO check if the loop order is optimal\n  @inbounds for i = 1:dim[2]\n    @inbounds for j = 1:dim[1]\n      U[j, i] /= S[i]\n    end\n  end\n\n  return LinearAlgebra.SVD(U, S, V')\nend\n\nend # module\n", "meta": {"hexsha": "60b3913bc5f03a4b561bd005c9aca5bfa112b9a5", "size": 669, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FameSVD.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/FameSVD.jl-9ba2d756-9ce3-11e9-1a71-0ffcb019784d", "max_stars_repo_head_hexsha": "bd2f34d91399512859e9153e2d4d5fd02b0cae7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FameSVD.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/FameSVD.jl-9ba2d756-9ce3-11e9-1a71-0ffcb019784d", "max_issues_repo_head_hexsha": "bd2f34d91399512859e9153e2d4d5fd02b0cae7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-01-10T13:01:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-11T18:27:21.000Z", "max_forks_repo_path": "src/FameSVD.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/FameSVD.jl-9ba2d756-9ce3-11e9-1a71-0ffcb019784d", "max_forks_repo_head_hexsha": "bd2f34d91399512859e9153e2d4d5fd02b0cae7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1142857143, "max_line_length": 60, "alphanum_fraction": 0.5500747384, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.752455748263247}}
{"text": "using Flux\nprintln(\"NNPDE_tests\")\nusing DiffEqFlux\nprintln(\"Starting Soon!\")\nusing ModelingToolkit\nusing DiffEqBase\nusing Test, NeuralPDE\nusing GalacticOptim\nusing Optim\nusing CUDA\n\nusing Random\nRandom.seed!(100)\n\ncb = function (p,l)\n    println(\"Current loss is: $l\")\n    return false\nend\n\n## Example 1, 3D PDE\n@parameters x y t θ\n@variables u(..)\n@derivatives Dxx''~x\n@derivatives Dyy''~y\n@derivatives Dt'~t\n\n# 3D PDE\neq  = Dt(u(x,y,t,θ)) ~ Dxx(u(x,y,t,θ)) + Dyy(u(x,y,t,θ))\n# Initial and boundary conditions\nbcs = [u(x,y,0,θ) ~ exp(x+y)*cos(x+y) ,\n      # u(x,y,2,θ) ~ exp(x+y)*cos(x+y+4*2) ,\n      u(0,y,t,θ) ~ exp(y)*cos(y+4t),\n      u(2,y,t,θ) ~ exp(2+y)*cos(2+y+4t) ,\n      u(x,0,t,θ) ~ exp(x)*cos(x+4t),\n      u(x,2,t,θ) ~ exp(x+2)*cos(x+2+4t)]\n# Space and time domains\ndomains = [x ∈ IntervalDomain(0.0,2.0),\n          y ∈ IntervalDomain(0.0,2.0),\n          t ∈ IntervalDomain(0.0,2.0)]\n\n# Discretization\ndx = 0.25; dy= 0.25; dt = 0.25\n# Neural network\nchain = FastChain(FastDense(3,16,Flux.σ),FastDense(16,16,Flux.σ),FastDense(16,1)) |>gpu\n\ndiscretization = NeuralPDE.PhysicsInformedNN([dx,dy,dt],\n                                             chain,\n                                             strategy = NeuralPDE.GridTraining())\npde_system = PDESystem(eq,bcs,domains,[x,y,t],[u])\nprob = NeuralPDE.discretize(pde_system,discretization)\n\nres = GalacticOptim.solve(prob, ADAM(0.1), progress = false; cb = cb, maxiters=1000)\nphi = discretization.phi\n\nxs,ys,ts = [domain.domain.lower:dx:domain.domain.upper for (dx,domain) in zip([dx,dy,dt],domains)]\nanalytic_sol_func(x,y,t) = exp(x+y)*cos(x+y+4t)\nu_real = [reshape([analytic_sol_func(x,y,t) for x in xs  for y in ys], (length(xs),length(ys)))  for t in ts ]\nu_predict = [reshape([first(phi([x,y,t],res.minimizer)) for x in xs  for y in ys], (length(xs),length(ys)))  for t in ts ]\n@test u_predict ≈ u_real atol = 200.0\n\n# p1 =plot(xs, ys, u_predict, st=:surface);\n# p2 = plot(xs, ys, u_real, st=:surface);\n# plot(p1,p2)\n\n## Example 2, ## Fokker-Planck equation\n# the example took from this article https://arxiv.org/abs/1910.10503\n@parameters x θ\n@variables p(..)\n@derivatives Dx'~x\n@derivatives Dxx''~x\n\n#2D PDE\nα = 0.3\nβ = 0.5\n_σ = 0.5\n# Discretization\ndx = 0.05\n# here we use normalization condition: dx*p(x,θ) ~ 1, in order to get non-zero solution.\neq  = [(α - 3*β*x^2)*p(x,θ) + (α*x - β*x^3)*Dx(p(x,θ)) ~ (_σ^2/2)*Dxx(p(x,θ)),\n       dx*p(x,θ) ~ 1.]\n\n# Initial and boundary conditions\nbcs = [p(-2.2,θ) ~ 0. ,p(2.2,θ) ~ 0. , p(-2.2,θ) ~ p(2.2,θ)]\n\n# Space and time domains\ndomains = [x ∈ IntervalDomain(-2.2,2.2)]\n\n# Neural network\nchain = FastChain(FastDense(1,12,Flux.σ),FastDense(12,12,Flux.σ),FastDense(12,1)) |>gpu\n\ndiscretization = NeuralPDE.PhysicsInformedNN(dx,\n                                             chain,\n                                             strategy= NeuralPDE.GridTraining())\n\npde_system = PDESystem(eq,bcs,domains,[x],[p])\nprob = NeuralPDE.discretize(pde_system,discretization)\n\nres = GalacticOptim.solve(prob, BFGS(); cb = cb, maxiters=8000)\nphi = discretization.phi\n\nanalytic_sol_func(x) = 28*exp((1/(2*_σ^2))*(2*α*x^2 - β*x^4))\n\nxs = [domain.domain.lower:dx:domain.domain.upper for domain in domains][1]\nu_real  = [analytic_sol_func(x) for x in xs]\nu_predict  = [first(phi(x,res.minimizer)) for x in xs]\n\n@test u_predict ≈ u_real atol = 20.0\n\n# plot(xs ,u_real, label = \"analytic\")\n# plot!(xs ,u_predict, label = \"predict\")\n", "meta": {"hexsha": "98fb74e83645d8eae4e190ea3b449b99955d1f4d", "size": 3420, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/NNPDE_tests_gpu.jl", "max_stars_repo_name": "mdmurbach/NeuralPDE.jl", "max_stars_repo_head_hexsha": "6ad14ba5a178f951f32d9159ea220eb00041cbcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/NNPDE_tests_gpu.jl", "max_issues_repo_name": "mdmurbach/NeuralPDE.jl", "max_issues_repo_head_hexsha": "6ad14ba5a178f951f32d9159ea220eb00041cbcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/NNPDE_tests_gpu.jl", "max_forks_repo_name": "mdmurbach/NeuralPDE.jl", "max_forks_repo_head_hexsha": "6ad14ba5a178f951f32d9159ea220eb00041cbcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8108108108, "max_line_length": 122, "alphanum_fraction": 0.6236842105, "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7524557456186776}}
{"text": "\nfunction L2norm(x)\n    local l2::eltype(x) = 0\n    for xᵢ in x\n        l2 += xᵢ^2\n    end\n    l2\nend\n\nfunction l2norm(x)\n    sqrt(L2norm(x))\nend\n", "meta": {"hexsha": "6959be2cbaf03b19dc7a19b68381b9470fe08de2", "size": 146, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/norms.jl", "max_stars_repo_name": "JuliaGNI/GeometricBase.jl", "max_stars_repo_head_hexsha": "5e0fe4873a7e55ca1fe3cab3a2c6c86ddfac3426", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/norms.jl", "max_issues_repo_name": "JuliaGNI/GeometricBase.jl", "max_issues_repo_head_hexsha": "5e0fe4873a7e55ca1fe3cab3a2c6c86ddfac3426", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-25T11:39:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T10:11:20.000Z", "max_forks_repo_path": "src/utils/norms.jl", "max_forks_repo_name": "JuliaGNI/GeometricBase.jl", "max_forks_repo_head_hexsha": "5e0fe4873a7e55ca1fe3cab3a2c6c86ddfac3426", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.2307692308, "max_line_length": 27, "alphanum_fraction": 0.5479452055, "num_tokens": 64, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7524557445328207}}
{"text": "#= matrixlib.jl\n=#\n\nfunction matrixlib(::Type{T}, name::Symbol, args...) where T\n  if     name == :cauchy   return matrixlib_cauchy(T, args...)\n  elseif name == :fourier  return matrixlib_fourier(T, args...)\n  elseif name == :hilb     return matrixlib_hilb(T, args...)\n  else                     throw(ArgumentError(\"name\"))\n  end\nend\nmatrixlib(name::Symbol, args...) = matrixlib(Float64, name, args...)\n\nfunction matrixlib_cauchy(::Type{T}, x::AbstractVector, y::AbstractVector) where T\n  m = length(x)\n  n = length(y)\n  A = Array{T}(undef, m, n)\n  @inbounds for j = 1:n\n    @simd for i = 1:m\n      A[i,j] = 1/(x[i] - y[j])\n    end\n  end\n  A\nend\n\nfunction matrixlib_fourier(::Type{T}, x::AbstractVector, y::AbstractVector) where T\n  S = eltype(complex(zero(T)))\n  m = length(x)\n  n = length(y)\n  A = Array{S}(undef, m, n)\n  @inbounds for j = 1:n, i = 1:m\n    A[i,j] = exp(-2im*pi*x[i]*y[j])\n  end\n  A\nend\nmatrixlib_fourier(::Type{T}, m::Integer, n::Integer) where {T} =\n  matrixlib_fourier(T, 0:m-1, (0:n-1)/n)\nmatrixlib_fourier(::Type{T}, n::Integer) where {T} = matrixlib_fourier(T, n, n)\n\nfunction matrixlib_hilb(::Type{T}, m::Integer, n::Integer) where T\n  m >= 0 || throw(ArgumentError(\"m\"))\n  n >= 0 || throw(ArgumentError(\"n\"))\n  A = Array{T}(undef, m, n)\n  @inbounds for j = 1:n, i = 1:m\n    A[i,j] = 1/(i + j - 1)\n  end\n  A\nend\nmatrixlib_hilb(::Type{T}, n::Integer) where {T} = matrixlib_hilb(T, n, n)\n", "meta": {"hexsha": "fcfa304d1f1dd2c7ee59042137c9b2639b2f521f", "size": 1412, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrixlib.jl", "max_stars_repo_name": "BambOoxX/LowRankApprox.jl", "max_stars_repo_head_hexsha": "339927c5273616b40b46ceead99f8565d5585c3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 66, "max_stars_repo_stars_event_min_datetime": "2017-10-17T13:40:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T03:02:39.000Z", "max_issues_repo_path": "src/matrixlib.jl", "max_issues_repo_name": "BambOoxX/LowRankApprox.jl", "max_issues_repo_head_hexsha": "339927c5273616b40b46ceead99f8565d5585c3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2017-10-20T00:41:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T14:43:12.000Z", "max_forks_repo_path": "src/matrixlib.jl", "max_forks_repo_name": "BambOoxX/LowRankApprox.jl", "max_forks_repo_head_hexsha": "339927c5273616b40b46ceead99f8565d5585c3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:18:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T14:18:42.000Z", "avg_line_length": 28.8163265306, "max_line_length": 83, "alphanum_fraction": 0.6069405099, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7524187823041181}}
{"text": "# 1d climate\nusing DrWatson\n@quickactivate \"NonlinearDynamicsTextbook\"\ninclude(srcdir(\"style.jl\"))\nusing DynamicalSystems, PyPlot, Random\n\nusing DynamicalSystems, PyPlot, Roots\n\nαtan(T) = 0.5 - 0.2*tanh((T-263)/4)\ndTdt(T, ε = 0.65, α=αtan, s= 1.0) = s*(1 - α(T)) - 1.6e-10 * ε * T^4\ndTdt(T; ε = 0.65, α=αtan, s = 1.0) = dTdt(T, ε, α, s)\n\n# Ts = 200:400.0\n# plot(Ts, dTdt.(Ts))\n# plot(Ts, dTdt.(Ts, 0.2))\n# plot(Ts, dTdt.(Ts, 0.9))\n# axhline(0)\n\nfig = figure(figsize = (figx/2, figy))\nTs = 200:0.5:320.0\narrows = 210:10:300 |> collect\ndeleteat!(arrows, findfirst(isequal(260), arrows))\nroots = Roots.find_zeros(dTdt, Ts[1], Ts[end])\nplot(Ts, dTdt.(Ts), color = \"C0\", label = \"\\$dT/dt\\$\")\naxhline(0; lw = 2.0, zorder = 1, color = \"C2\", ls = \"--\")\nxlim(Ts[1], Ts[end])\nylim(-0.2, 0.2)\nyticks([-0.1, 0, 0.1])\ntight_layout()\nfor (i, r) in enumerate(roots)\n    plot(r, 0, marker = \"o\", markeredgecolor = \"k\", markerfacecolor = iseven(i) ? \"w\" : \"k\",\n    markersize = 15, mew = 2)\nend\nfor r in arrows\n    f = dTdt(r)\n    x, dx = f > 0 ? (r - 5, 5) : (r+5, -5)\n    ff = abs(1.2f)^2 + 0.01\n    arrow(x, 0, dx, 0; color = \"C1\", width = ff, length_includes_head = false,\n    head_width = 1.5ff, head_length = 100ff, zorder = 99\n    )\nend\nlegend()\nxticks(200:40:320)\nxlabel(\"\\$T\\$\"; labelpad = -15)\ntight_layout(pad=0.3)\nwsave(plotsdir(\"2\", \"1dstatespace\"), fig)\n", "meta": {"hexsha": "d0315714e874361e9cf9fafe2ce8f94f0e16b89f", "size": 1351, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "figure_generation/2/2.1.jl", "max_stars_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_stars_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 88, "max_stars_repo_stars_event_min_datetime": "2021-07-18T20:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T09:23:53.000Z", "max_issues_repo_path": "figure_generation/2/2.1.jl", "max_issues_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_issues_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figure_generation/2/2.1.jl", "max_forks_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_forks_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-07-28T18:49:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:45:11.000Z", "avg_line_length": 28.7446808511, "max_line_length": 92, "alphanum_fraction": 0.5980754996, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.752418777977942}}
{"text": "# ---\n# layout: post\n# title: \"π day\"\n# date: 2019-03-13 00:00:00 +0000\n# categories: blog\n# mathjax: true\n# ---\n\n# >In the UK we have started to celebrate π day (the 3rd month's 14th day) every year, even though we don't use the USA's date formatting convention of `monthnumber` followed by `daynumber`. But we can't really celebrate the 31st of April (31/4) or the 3rd of Quatember (?) (3/14), so we'll happily celebrate π day on 14/3 along with everyone else!\n\n# >I set myself a challenge at the beginning of March: make a π-related image using Julia and the Luxor.jl package every day until π day. Some days it worked out well, others didn't, but I've gathered them all here anyway. This post has a fair few images, but not very much code or mathematical content.\n\n# The images here are in low-resolution: they should be available on my [Flickr page](https://www.flickr.com/photos/153311384@N03/) at their full resolution if you want to download or re-use them.\n\n# ### Day 1: Circle packing\n\n# Circle packing may be a well-trodden path, but it always looks neat, and it's a nice easy start. You maintain a list of circles (center point and radius). Then you create a random circle, check it against all the other ones, draw it if it doesn't overlap, or reduce the radius and try again. It's not very efficient but you can set it going and go and make some coffee.\n\n# To make the π shape appear, the code creates a path:\n\n#md fontsize(480)\n#md textoutlines(\"π\", O, :path, halign=:center, valign=:middle)\n#md πoutline = first(pathtopoly())\n\n# then checks whether each circle's centerpoint is inside or outside the outline of the π shape:\n\n#md isinside(pt, πoutline)\n\n# and colors it accordingly.\n\n# ![image label](IMAGEFOLDER/t-800.png)\n\n# ### Day 2: Dry and wet\n\n# I repeated myself today, thinking I could develop the circles a bit more, and ended up with this glossier wet-look version. The apparently random-looking shapes in the background are Bézier splodges that are supposed to be splashes...\n\n# ![image label](IMAGEFOLDER/pi-reds-balls-wet-800.png)\n\n# ### Day 3: π packing\n\n# This is π packing rather than circle packing, although the code is again quite similar in outline: choose a point at random, find the largest font size at which the π character fits without overlapping others in the list, and then place it and add it to the list. The colors are a bit murky though.\n\n# ![image label](IMAGEFOLDER/pi-swarm-3-800.png)\n\n# ### Day 4: Rainbow\n\n# Combining concentric circles and rainbow colors, this image shows about 350 digits of π.\n\n# ![image label](IMAGEFOLDER/digits-of-pi-avenir-800.png)\n\n# To generate the digits of π, I use this function:\n\nfunction pidigits(n)\n    result = BigInt[]\n    k, a, b, a1, b1 = big.([2, 4, 1, 12, 4])\n    while n > 0\n        p, q, k = k^2, 2k + 1, k + 1\n        a, b, a1, b1 = a1, b1, p * a  +  q * a1, p * b  +  q * b1\n        d, d1 = a ÷ b, a1 ÷ b1\n        while d == d1\n            push!(result, d)\n            n -= 1\n            a, a1 = 10(a % b), 10(a1 % b1)\n            d, d1 = a ÷ b, a1 ÷ b1\n        end\n    end\n    return result\nend\n\n# It looks like witchcraft to me, but I understand that it's a \"spigot\" algorithm. I was hoping for a while that it was named after a Professor Spigot, but in fact it's describing the way the digits trickle out one by one like drops of water. It's quick enough for a thousand digits or so, but slows down a lot when you ask for 100_000 or more, probably due to the hard work that the big integer library has to do: even when you're just calculating the first 15 digits of π, the values of `a1` and `b1` are way over the limits of Int64s.\n\n#md julia-1.1> @time pidigits(1000);\n#md  0.014522 seconds (44.90 k allocations: 9.425 MiB, 28.97% gc time)\n\n# The image might work better on white:\n\n# ![image label](IMAGEFOLDER/digits-of-pi-avenir-on-white-800.png)\n\n# Sometimes I wanted to check where certain sequences of digits appeared. I couldn't find a built-in function that looked for a sequence of digits in an array, but this worked well enough for my purposes:\n\nfunction findsubsequence(needle, haystack)\n    result = Int64[]\n    for k in 1:length(haystack) - length(needle)\n        if needle == view(haystack, k:k + length(needle) - 1)\n            push!(result, k)\n        end\n    end\n    return result\nend\n\nfindsubsequence(str::String, digits) =\n    findsubsequence(map(x -> parse(Int, x), split(str, \"\")), digits)\n\nfindsubsequence(\"999999\", pidigits(2000)) # => [763]\n\n# ### Day 5: Low-fat\n\n# A chunky typeface like the Avenir Heavy I used yesterday is good for masking and clipping. But I wondered how the narrowest typeface would look. I found Briem Akademi, designed by Gunnlaugur Briem at the Royal Academy of Fine Arts in Copenhagen. Adobe's description says:\n\n# >The most compressed version works best where legibility is less important than dramatic visual effect.\n\n# and I like the abstract look even though it's almost illegible... Would this make nice bathroom tiles?\n\n# ![image label](IMAGEFOLDER/many-digits-of-pi-briem-800.png)\n\n# ### Day 6 Breakfast and Tiffany\n\n# I'm still thinking about using typefaces. I'm a fan of Ed Benguiat's ITC Tiffany font, his nostalgic look back from the 1970s to the age of Edwardian elegance.\n\n# ![image label](IMAGEFOLDER/pi-digits-appearing-800.png)\n\n# It's easy to do this with tables. Like the circle packing, the code checks whether the coordinates of each table cell fall within a given perimeter, and changes the font accordingly.\n\n# ### Day 7 Distinguished\n\n# The excellent Colors.jl package has a function called `distinguishable_colors()` (which fortunately tab-completes). The help text says:\n\n# > This uses a greedy brute-force approach to choose `n` colors that are maximally distinguishable. Given `seed` color(s), and a set of possible hue, chroma, and lightness values (in LCHab space), it repeatedly chooses the next color as the one that maximizes the minimum pairwise distance to any of the colors already in the palette.\n\n# Much to do with color depends on the viewer's perception, but I think it works well here. It starts at the top left, and works from left to right. (That pesky decimal point defaults to using the previous color...) You can spot the Feynman point (`999999`) halfway down on the left (look for the six consecutive sandy brown squares), or the four purple sevens on the bottom row.\n\n# ![image label](IMAGEFOLDER/pi-distinguishable_colors-800.png)\n\n# I remembered to try to choose the color for the small labels (probably unreadable in the low-resolution PNG you see here) so that they're either light on dark, or dark on light.\n\n#md ... r, g, b = color of square\n#md gamma = 2.2\n#md luminance = 0.2126 * r^gamma + 0.7152 * g^gamma + 0.0722 * b^gamma\n#md (luminance > 0.5^gamma) ? sethue(\"black\") : sethue(\"white\")\n\n# ### Day 8 Candy crush edition\n\n# ![image label](IMAGEFOLDER/candy-crush.png)\n\n# I must have seen an advert for CandyCrush yesterday, or perhaps all that talk of gamma and LCHab spaces caused a reaction, but this sugar rush of an image was the result. The SVG version looks tasty but is too big for this web page.\n\n# ### Day 9 Like a circle in a spiral, a wheel within a wheel\n\n# Arranging the sweets in a spiral looks tidy.\n\n# ![image label](IMAGEFOLDER/pi-digits-in-spiral-balls-800.png)\n\n# ### Day 10 π into circumference\n\n# Luxor's `polysample()` function takes a polygon and samples it at regular intervals. This allows the following idea, where each point on a shape (here, the outline of the π character) is slowly moved to a matching location on the circular shape around the outside.\n\n# ![image label](IMAGEFOLDER/pi-to-circle-800.png)\n\n# For a point on the π border `p1`, and a matching point on the circumference polygon `p2`, the intermediate point is given by `between(p1, p2, n)`, where `n` is between 0 and 1.\n\n# I like the almost 3D effect you get from this.\n\n# ### Day 11 Charcoal\n\n# Time for a charcoal sketch:\n\n# ![image label](IMAGEFOLDER/pi-charcoal-1-800.png)\n\n# The crinkly edges of the paper are made by the `polysample()` function on a rectangle then applying simplex-`noise()`-y nudges to the vertices. The paper is textured with `rule()`d lines, and there's some very low values for `setopacity()` smudges. Shifting the Bézier curve handles slightly for each iteration gives a brushy/sketchy feel. (It's fortunate I can copy and paste some of this code from drawings I've made before: I've learnt the hard way that it's better keep things than throw them away...)\n\n# ### Day 12\n\n# I ran out of time on this one, and there are still some problems with the text spacing. The idea is to have the infinite digits of π spiral into some fiery star with some space-y stuff. Probably not the sort of image I should be attempting at all with simple vector-based 2D graphics tools, but it feels like a challenge. Those wispy trails are the same as yesterday's brush strokes, but using custom `setdash()` dashing patterns.\n\n# ![image label](IMAGEFOLDER/pi cosmic spiral-800.png)\n\n# ### Day 13\n\n# The idea here is to show which digit of π is the current leader, in terms of how many times that digit has appeared already. (Yes, a stupid idea, I know!) Then I couldn't decide on how many digits to show, so it's going to be an animated GIF showing the first 1000 digits. At the 200 digit mark poor old \"7\" is struggling at the back of the field, but the glory days are ahead - after 1000 digits, it's overtaken 0, 4, and 6.\n\n# ![image label](IMAGEFOLDER/200-digits-of-pi-800.png)\n\n# The animation turned into a video rather than a GIF, because I don't like the low resolution of GIFs today.\n\n# And now of course I have to add a suitable audio soundtrack. Luckily I've recently been playing with George Datseris' [MIDI interface for Julia](https://github.com/JuliaMusic), so it was easy enough to make a musical version of the first 1000 digits of π, where the digits from 0 to 9 choose the appropriate note from a reasonably harmonious scale.\n\nusing MIDI\n\nfunction savetrack(track, notes)\n    file = MIDIFile()\n    addnotes!(track, notes)\n    addtrackname!(track, \"a track\")\n    push!(file.tracks, track)\n    writeMIDIFile(\"/tmp/sound-of-pi.mid\", file)\nend\n\nscales = [46, 48, 51, 53, 55, 57, 58, 60, 62, 65, 67]\n\nfunction generatetune!(notes)\n    pos = 1\n    dur = 80\n    k = 1\n    manypidigits = pidigits(1000)\n    for i in manypidigits\n        dur = k * 960\n        pos += k * 960\n        n = scales[i + 1]\n        note = Note(n, 76, pos, dur)\n        push!(notes, note)\n    end\nend\n\nnotes = Notes()\ntrack = MIDITrack()\ngeneratetune!(notes)\nsavetrack(track, notes)\n\n# ![image label](IMAGEFOLDER/music-credits.png)\n\n# This \"sonification\" (or \"audification\") is just for fun. For a more convincing critique of these sonifications than I can provide, watch the always entertaining [Tantacrul](https://www.youtube.com/watch?v=Ocq3NeudsVk)'s presentation on YouTube.\n\n# And while you're on YouTube, the π video is on [my YouTube channel](https://www.youtube.com/channel/UCfd52kTA5JpzOEItSqXLQxg), and it's my entry for YouTube's Most Boring Video of 2019 competition, but I suspect it won't do very well—competition in this category is fierce, even if sometimes the contestants are unwilling participants.\n\n# Happy π day!\n\n# [2019-03-13]\n\n# ![cormullion signing off](http://steampiano.net/cormullionknot.gif?piday){: .center-image}\n\nusing Literate                                                                 #src\n# preprocess for notebooks                                                     #src\nfunction setimagefolder(content)                                               #src\n    content = replace(content, \"IMAGEFOLDER\" => \"$IMAGEFOLDER\")                #src\n    return content                                                             #src\nend                                                                            #src\n\n# for Jupyter notebook, put images in subfolder                                #src\n#IMAGEFOLDER = \"images/piday\"                                                   #src\n\n#Literate.notebook(\"source/piday.jl\", \"notebooks\", preprocess = setimagefolder) #src\n\n# for Markdown/Jekyll notebook, put images in \"/images\"                        #src\n\nIMAGEFOLDER = \"/images/piday\"                                                  #src\n\nLiterate.markdown(\"source/piday.jl\", \".\", name=\"_posts/2019-03-13-piday\",      #src\n preprocess = setimagefolder,                                                  #src\n codefence = \"{% highlight julia %}\" => \"{% endhighlight julia %}\",            #src\n documenter=false)                                                             #src\n\n#src\n", "meta": {"hexsha": "b67caecb1c0fd83f0bd1131d721bd160198d673c", "size": 12615, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/source/piday.jl", "max_stars_repo_name": "tlienart/cormullion.github.io", "max_stars_repo_head_hexsha": "ba8d6b780064c06fd978a888ddea4348dac2885d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/source/piday.jl", "max_issues_repo_name": "tlienart/cormullion.github.io", "max_issues_repo_head_hexsha": "ba8d6b780064c06fd978a888ddea4348dac2885d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/source/piday.jl", "max_forks_repo_name": "tlienart/cormullion.github.io", "max_forks_repo_head_hexsha": "ba8d6b780064c06fd978a888ddea4348dac2885d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.1280991736, "max_line_length": 537, "alphanum_fraction": 0.690051526, "num_tokens": 3278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.8558511469672595, "lm_q1q2_score": 0.7524187693255893}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 57ed2d88-970d-4b8d-9f36-7115f50622de\nbegin\n\tusing LinearAlgebra # for the norm and dot function\n\tusing ForwardDiff # for automatic differentiation\nend\n\n# ╔═╡ 3b36fb00-833f-11ec-0d4d-451fa6f0aaee\nmd\"\"\"\n# Programming tapas (I)\n\nThese are a few, hopefully small, tasks to practice Julia.\n\n- **Gradient decent**\n- Array interface\n\"\"\"\n\n# ╔═╡ 0efbf532-66cb-41fd-98a5-6df89e364b84\nmd\"\"\"## Gradient decent with backtracking line search\n\nWrite a function `gradient_decent(f, x0, α, β)` which implements the gradient decent with backtracking line search.\n\nYou can follow the notation form this slides (or your own).\n\nThe pseudo algorithms are:\n\"\"\"\n\n# ╔═╡ 67ab9ac3-93e0-4d9a-84aa-131aaf543198\nmd\"\"\"\n```julia\nGradient decent:\ngiven a starting point x_0\n\nx = x_0\nrepeat until stopping criterium\n\tCompute decent direction Δx = ∇f(x).\n \tLine search: Choose a step size t > 0.\n    Update: x = x + t * Δx\n\n \tStopping criterium: ‖ ∇f(x) ‖² < ε\nend\n```\n\"\"\"\n\n# ╔═╡ a5e2ee29-8de1-41be-8b05-8427b1a65bce\nmd\"\"\"\n```julia\nBacktracking line search:\ngiven x, f, Δx, α, β\n\nt = 1\nrepeat until f(x + t Δx) < f(x) + α t dot( ∇f(x), Δx )\n \tUdate: t = β t\nend\n\n```\n\nSource: [https://web.stanford.edu/class/ee364a/lectures/unconstrained.pdf](https://web.stanford.edu/class/ee364a/lectures/unconstrained.pdf)\n\"\"\"\n\n# ╔═╡ 304398ad-f680-4f8c-8a76-5768c0fbfa5e\n\n\n# ╔═╡ 2c48c94e-7d31-450c-b3c7-0194894c38b7\nfunction linesearch(f, Δx, x, α, β; t_min = 1e-5)\n\tt = 1\n\tfx = f(x)\n\tm = norm(Δx)\n\twhile t > t_min\n\t\tif f(x .+ t*Δx) <= fx + α * t * m^2\n\t\t\treturn t\n\t\tend\n\t\tt = t*β\n\t\tcond || return t\n\tend\n\n\treturn NaN\nend\n\n# ╔═╡ ae9e20b2-4f88-4c28-8856-ce61368445a3\nfunction gradientdecent(f, x0, α, β, ε; max_steps = 1e4)\n\tx = copy(x0)\n\ti = 0\n\t∇f = similar(x0)\n\n\t@assert β < 1\n\t@assert α < 0.5\n\n\twhile i < max_steps\n\t\tForwardDiff.gradient!(∇f, f, x)\n\t\tΔx = -∇f\n\t\tif norm(∇f)^2 < ε\n\t\t\treturn x\n\t\tend\n\n\t\tt = linesearch(f, Δx, x, α, β)\n\t\tx .+= t * Δx\n\n\t\ti += 1\n\tend\n\n\treturn NaN\nend\n\n# ╔═╡ e331926f-6e11-434c-a7d3-02d0e9f0f269\nbegin\n\tf(x) = exp(x[1]+3x[2]-0.1) + exp(x[1]-3x[2]-0.1) + exp(-x[1]-0.1)\n\tα = 0.25\n\tβ = 0.5\n\tε = 1e-8\n\tx0 = [0.0, 0.0]\n\n\tgradientdecent(f, x0, α, β, ε)\nend\n\n# ╔═╡ 7a5cfa1b-9b47-4741-8656-210a3515b6f3\n\n\n# ╔═╡ 81361eb6-092c-4cd1-96a0-eb9e167dfd3f\n\n\n# ╔═╡ b04a090b-e9d7-4032-b956-1238fac26f94\nmd\"## Array interpolation\"\n\n# ╔═╡ 3413f532-50ec-47f5-9547-4e9474be174e\nmd\"\"\"\nWe want to take regular vectors, but have an automated way to compute in between values with the syntax\n```julia\nx = [5, 7, 5]\nx[1.5] == 6.0  # linear interpolation between 5 and 7\n```\n\nImplement\n`Base.getindex(x::Vector{Float64}, p::Float64) = `\naccordingly.\n\"\"\"\n\n# ╔═╡ 641f85f8-368a-45eb-9912-284eca29d83b\nx = [5.0, 7.0, 5.0]\n\n# ╔═╡ 9f62d306-25f2-4b8f-a691-7a0fa3f4aa03\n# x[1.5]\n\n# ╔═╡ 61eaf1c1-f033-4e36-8171-19ff6621cc82\n\n\n# ╔═╡ 84c50e3b-b836-477f-81bb-121a2e5d055f\nmd\"\n## Merge sort\n\nImplement (any variant) of merge sort.\n\nYou can for example try this strategy\n```\nMergeSort(arr[], l,  r)\nIf r > l\n     1. Find the middle point to divide the array into two halves:\n             middle m = l+ (r-l)/2\n     2. Call mergeSort for first half:\n             Call mergeSort(arr, l, m)\n     3. Call mergeSort for second half:\n             Call mergeSort(arr, m+1, r)\n     4. Merge the two halves sorted in step 2 and 3:\n             Call merge(arr, l, m, r)\n```\nSource: https://www.geeksforgeeks.org/merge-sort/\n\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nForwardDiff = \"f6369f11-7733-5829-9624-2563aa707210\"\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[compat]\nForwardDiff = \"~0.10.25\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\njulia_version = \"1.7.1\"\nmanifest_format = \"2.0\"\n\n[[deps.ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[deps.Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[deps.Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[deps.ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"f9982ef575e19b0e5c7a98c6e75ee496c0f73a93\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.12.0\"\n\n[[deps.ChangesOfVariables]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"bf98fa45a0a4cee295de98d4c1462be26345b9a1\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.2\"\n\n[[deps.CommonSubexpressions]]\ndeps = [\"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"7b8a93dba8af7e3b42fecabf646260105ac373f7\"\nuuid = \"bbf7d656-a473-5ed7-a52c-81e309532950\"\nversion = \"0.3.0\"\n\n[[deps.Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"44c37b4636bc54afac5c574d2d02b625349d6582\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.41.0\"\n\n[[deps.CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[deps.Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[deps.DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[deps.DiffResults]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"c18e98cba888c6c25d1c3b048e4b3380ca956805\"\nuuid = \"163ba53b-c6d8-5494-b064-1a9d43ac40c5\"\nversion = \"1.0.3\"\n\n[[deps.DiffRules]]\ndeps = [\"IrrationalConstants\", \"LogExpFunctions\", \"NaNMath\", \"Random\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"84083a5136b6abf426174a58325ffd159dd6d94f\"\nuuid = \"b552c78f-8df3-52c6-915a-8e097449b14b\"\nversion = \"1.9.1\"\n\n[[deps.Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[deps.DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[deps.Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[deps.ForwardDiff]]\ndeps = [\"CommonSubexpressions\", \"DiffResults\", \"DiffRules\", \"LinearAlgebra\", \"LogExpFunctions\", \"NaNMath\", \"Preferences\", \"Printf\", \"Random\", \"SpecialFunctions\", \"StaticArrays\"]\ngit-tree-sha1 = \"1bd6fc0c344fc0cbee1f42f8d2e7ec8253dda2d2\"\nuuid = \"f6369f11-7733-5829-9624-2563aa707210\"\nversion = \"0.10.25\"\n\n[[deps.InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[deps.InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.2\"\n\n[[deps.IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[deps.JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"abc9885a7ca2052a736a600f7fa66209f96506e1\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.4.1\"\n\n[[deps.LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[deps.LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[deps.LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[deps.LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[deps.Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[deps.LinearAlgebra]]\ndeps = [\"Libdl\", \"libblastrampoline_jll\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[deps.LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"e5718a00af0ab9756305a0392832c8952c7426c1\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.6\"\n\n[[deps.Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[deps.MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[deps.Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[deps.MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[deps.Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[deps.MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[deps.NaNMath]]\ngit-tree-sha1 = \"b086b7ea07f8e38cf122f5016af580881ac914fe\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.7\"\n\n[[deps.NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[deps.OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[deps.OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[deps.OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[deps.Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[deps.Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"2cf929d64681236a2e074ffafb8d568733d2e6af\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.3\"\n\n[[deps.Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[deps.REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[deps.Random]]\ndeps = [\"SHA\", \"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[deps.SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[deps.Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[deps.SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[deps.Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[deps.SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[deps.SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"e6bf188613555c78062842777b116905a9f9dd49\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"2.1.0\"\n\n[[deps.StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"2884859916598f974858ff01df7dfc6c708dd895\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.3.3\"\n\n[[deps.Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[deps.TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[deps.Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[deps.Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[deps.UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[deps.Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[deps.Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[deps.libblastrampoline_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"OpenBLAS_jll\"]\nuuid = \"8e850b90-86db-534c-a0d3-1478176c7d93\"\n\n[[deps.nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[deps.p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─3b36fb00-833f-11ec-0d4d-451fa6f0aaee\n# ╟─0efbf532-66cb-41fd-98a5-6df89e364b84\n# ╟─67ab9ac3-93e0-4d9a-84aa-131aaf543198\n# ╟─a5e2ee29-8de1-41be-8b05-8427b1a65bce\n# ╟─304398ad-f680-4f8c-8a76-5768c0fbfa5e\n# ╠═57ed2d88-970d-4b8d-9f36-7115f50622de\n# ╠═2c48c94e-7d31-450c-b3c7-0194894c38b7\n# ╠═ae9e20b2-4f88-4c28-8856-ce61368445a3\n# ╠═e331926f-6e11-434c-a7d3-02d0e9f0f269\n# ╟─7a5cfa1b-9b47-4741-8656-210a3515b6f3\n# ╟─81361eb6-092c-4cd1-96a0-eb9e167dfd3f\n# ╟─b04a090b-e9d7-4032-b956-1238fac26f94\n# ╟─3413f532-50ec-47f5-9547-4e9474be174e\n# ╠═641f85f8-368a-45eb-9912-284eca29d83b\n# ╠═9f62d306-25f2-4b8f-a691-7a0fa3f4aa03\n# ╟─61eaf1c1-f033-4e36-8171-19ff6621cc82\n# ╟─84c50e3b-b836-477f-81bb-121a2e5d055f\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "143966746bd37da470182177ac93da41bba85489", "size": 12565, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/pluto/gradient_decent_sol.jl", "max_stars_repo_name": "SteffenPL/Julia-for-mathematicians", "max_stars_repo_head_hexsha": "accd6bc8f4e064a1d55ae5f903607778ca84a79a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercises/pluto/gradient_decent_sol.jl", "max_issues_repo_name": "SteffenPL/Julia-for-mathematicians", "max_issues_repo_head_hexsha": "accd6bc8f4e064a1d55ae5f903607778ca84a79a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercises/pluto/gradient_decent_sol.jl", "max_forks_repo_name": "SteffenPL/Julia-for-mathematicians", "max_forks_repo_head_hexsha": "accd6bc8f4e064a1d55ae5f903607778ca84a79a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5084388186, "max_line_length": 280, "alphanum_fraction": 0.7125348189, "num_tokens": 5610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7524187644770357}}
{"text": "\n# f(x) = x^2 - 2x + 2\n\nusing LaTeXStrings, Measures\ngr()\n\n\nxf(x) = x^2 - 2x + 2\n\n\nPlots.plot(xf,\n    -3, 3,\n    marker=:circle,\n    c=:darkorange3,\n    linewidth= 2,\n    xlabel=L\"n\",\n    ylabel=L\"F_n\",\n    annotation=(2, 10, L\"F_n = x^2 - 2x + 2\"))\n", "meta": {"hexsha": "7afd1be0776b5638003f766f0f64dbdf82d8a0d0", "size": 250, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lines/loss-curves/polynomials.jl", "max_stars_repo_name": "Ellon-M/visualizations", "max_stars_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lines/loss-curves/polynomials.jl", "max_issues_repo_name": "Ellon-M/visualizations", "max_issues_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lines/loss-curves/polynomials.jl", "max_forks_repo_name": "Ellon-M/visualizations", "max_forks_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.1578947368, "max_line_length": 46, "alphanum_fraction": 0.516, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.7524187617179897}}
{"text": "function GenEuropeanBinomialCall(K, T, S, sig, r, N)\n\n        dt = T/N ## Time to Maturity/ Number of Steps\n        nu = r - 0.5*sig^2\n        dxu = sqrt(sig^2*dt + (nu*dt)^2)\n        dxd = -dxu\n        pu = 1/2 + 1/2*(nu*dt/dxu)\n        pd = 1 - pu\n\n        disc = exp(-r*dt)\n\n        St = zeros(Float64, (N+1, N+1))\n\n        # Initialising asset prices at maturity\n\n        St[1 , N+1] = S / exp(N * dxd)\n        for j in 2:(N+1)\n                St[j, N+1] = St[j-1, N+1] / exp(dxu - dxd)\n        end\n\n\n        # create Array for options value tree\n\n        C = zeros(Float64, (N+1, N+1))#linspace(1, N+1, N+1)\n\n        # Initialise Option Values at maturity\n\n        for j in 1:(N+1)\n                C[j, N+1] = max(0.0, St[j, N+1] - K)\n        end\n\n        # Stepping back through the tree\n\n        for i = linrange(N, 1, N)\n                for j in 1:i\n                      C[j, i] = disc * (pu * C[j, i+1] + pd * C[j+1, i+1])\n                      #St[j,i] = St[j,i+1] / d\n                      #P[j, i] = max(P[j, i], K - St[j,i])\n                end\n        end\n\nC\nend\n", "meta": {"hexsha": "766a8cbe7fc93e753d7819f9e28d8e7b241c39bf", "size": 1078, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/IB/PricingEngines/GenEuropeanBinomialCall.jl", "max_stars_repo_name": "SvenDuve/JuliaAOT.jl", "max_stars_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/IB/PricingEngines/GenEuropeanBinomialCall.jl", "max_issues_repo_name": "SvenDuve/JuliaAOT.jl", "max_issues_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IB/PricingEngines/GenEuropeanBinomialCall.jl", "max_forks_repo_name": "SvenDuve/JuliaAOT.jl", "max_forks_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-27T15:45:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-27T15:45:30.000Z", "avg_line_length": 24.5, "max_line_length": 74, "alphanum_fraction": 0.4165120594, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211612253742, "lm_q2_score": 0.7718434925908524, "lm_q1q2_score": 0.7524093697316633}}
{"text": "# ==============================================================================\n# Xavier Gandibleux - November 2021\n#   Implemented in Julia 1.6\n\n# ==============================================================================\n# Parser of bi-01BKP instances generated by O. Perederieieva and X. Gandibleux\n#   All coefficients P, W, and  ω are integer, all variables are binary\n\n# ==============================================================================\n# Datastructure of a multi-objective multi-dimensionnal KP with 0/1 variables\nstruct _MOMKP\n    P  :: Matrix{Int} # profit of items for the objectives, k=1..p, j=1..n\n    W  :: Matrix{Int} # weight of items for the constraints, i=1..m, j=1..n\n    ω  :: Vector{Int} # capacity of knapsacks, i=1..m\nend\n\n# ==============================================================================\nfunction readInstanceMOMKPformatPG(verbose::Bool, fname::String)\n\n    f=open(fname)\n\n    n = parse(Int, readline(f) )\n    m = 2  # 2 constraints\n    p = 2  # 2 objectives\n\n    momkp = _MOMKP(zeros(Int,p,n),zeros(Int,m,n),zeros(Int,m))\n    !verbose ? nothing : println(\"Instance of bi-01BKP : \",n,\" variables\")\n\n    momkp.ω[1] = parse(Int, readline(f) )\n    momkp.ω[2] = parse(Int, readline(f) )\n    !verbose ? nothing : println(\"ω[1]=\",momkp.ω[1])\n    !verbose ? nothing : println(\"ω[2]=\",momkp.ω[2])\n\n    # Extract the data of the MKP from the following lines ---------------------\n    for j = 1:n\n        momkp.P[1,j],\n        momkp.P[2,j],\n        momkp.W[1,j],\n        momkp.W[2,j] = parse.(Int, split(readline(f)) )\n\n        !verbose ? nothing :\n          println(\"j=\",j, \"  |  \",\n                  \"p[1,\",j,\"]=\",momkp.P[1,j], \"   \",\n                  \"p[2,\",j,\"]=\",momkp.P[2,j], \"  |  \",\n                  \"w[1,\",j,\"]=\",momkp.W[1,j], \"   \",\n                  \"w[2,\",j,\"]=\",momkp.W[2,j]\n                 )\n    end\n    close(f)\n\n    return momkp\nend\n\n# ==============================================================================\n\n# Example on how to use it :\n# fname=\"set1/ZL28.DAT\"; verbose = true\n# instancePG = readInstanceMOMKPformatPG(verbose,fname)\n", "meta": {"hexsha": "abbd8f2c77d23d01df3526b56a220140973572c0", "size": 2106, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "parserMomkpPG.jl", "max_stars_repo_name": "PoltyPoltou/NSGA2-vs-MOVNS", "max_stars_repo_head_hexsha": "93ce5607d19ba077b3d659228e7fe69955c340b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "parserMomkpPG.jl", "max_issues_repo_name": "PoltyPoltou/NSGA2-vs-MOVNS", "max_issues_repo_head_hexsha": "93ce5607d19ba077b3d659228e7fe69955c340b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "parserMomkpPG.jl", "max_forks_repo_name": "PoltyPoltou/NSGA2-vs-MOVNS", "max_forks_repo_head_hexsha": "93ce5607d19ba077b3d659228e7fe69955c340b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6949152542, "max_line_length": 80, "alphanum_fraction": 0.4544159544, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7523778095142722}}
{"text": "#=\n\n  Assignment 1:\n  https://edu.swi-prolog.org/mod/assign/view.php?id=242\n  \"\"\"\n  http://cplint.eu/p/urns_and_balls.swinb\n\n  Urns and balls\n\n  Suppose you have two urns: urn1 contains 40 blue balls and 20 red balls and urn2 contains 25\n  blue balls and 30 red balls.\n\n  You throw an unbiased coin and, if it turns out head, you draw a ball from the first urn,\n  it it turns out tails you draw a ball from the second urn.\n\n  Write a program modeling this process and a query for answering the question\n  \"What is the probability of drawing a blue ball?\"\n\n  Write the program and the query in the cells below. Then save the notebook and submit the url.\n\n  \"\"\"\n  The exact answer of drawing a blue call is\n     0.5*40/60 + 0.5*25/55 = 0.56060606060606060606\n\n\n  Summary Statistics\n  parameters      mean       std   naive_se      mcse          ess      rhat   ess_per_sec \n      Symbol   Float64   Float64    Float64   Float64      Float64   Float64       Float64 \n\n        coin    1.5019    0.5000     0.0025    0.0025   40549.0446    1.0000    28840.0032\n        draw    1.4389    0.4963     0.0025    0.0023   40570.3731    1.0000    28855.1729\n\n  Distributions of variable draw\n  blue       =>   22442  (0.561050)\n  red        =>   17558  (0.438950)\n\n  Distributions of variable coin\n  head       =>   20078  (0.501950)\n  tail       =>   19922  (0.498050)\n\n\n  Cf ~/cplint/course_urns_and_balls.pl\n     ~/blog/urns_and_balls.blog\n     ~/psi/urns_and_balls.blog\n     ~/webppl/urns_and_balls.wppl\n\n=#\n\nusing Turing, StatsPlots, DataFrames\nusing ReverseDiff, Zygote, Tracker\n# Turing.setadbackend(:reversediff)\n# Turing.setadbackend(:zygote)\n# Turing.setadbackend(:tracker)\ninclude(\"jl_utils.jl\")\n\n@model function urns_and_balls()\n    tail = 1\n    head = 2\n    coin ~ Categorical(simplex([0.5,0.5]))\n\n    blue = 1\n    red = 2\n    draw ~ coin == head ? Categorical(simplex([40,20])) : Categorical(simplex([25,30]))\nend\n\nmodel = urns_and_balls()\n\nnum_chns = 4\n# chns = sample(model, Prior(), MCMCThreads(), 1000, num_chns)\n\n# chns = sample(model, MH(), 40_000)\n# chns = sample(model, MH(), MCMCThreads(), 40_000, num_chns)\n\n# chns = sample(model, PG(20), MCMCThreads(), 10_000, num_chns)\n# chns = sample(model, PG(20), 40_000)\n# chns = sample(model, IS(), MCMCThreads(), 10_000, num_chns)\nchns = sample(model, IS(), 40_000)\n\ndisplay(chns)\n\nshow_var_dist_pct(chns,:draw,[\"blue\",\"red\"])\nshow_var_dist_pct(chns,:coin,[\"tail\",\"head\"])\n", "meta": {"hexsha": "40611eff660ab0233573ec1c49d1eda3cf03da79", "size": 2428, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/urns_and_balls.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/urns_and_balls.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/urns_and_balls.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 29.2530120482, "max_line_length": 96, "alphanum_fraction": 0.6626853377, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7523778087423972}}
{"text": "function compute(n::Int)::Int\n    for c ∈ n ÷ 3 + 1:n ÷ 2\n        s = c * c - n * n + 2n * c\n        if s > 0\n            t = trunc(Int, √s)\n            if t * t == s\n                b = (n - c + t) / 2\n                a = n - c - b\n                return a * b * c\n            end\n        end\n    end\nend\n", "meta": {"hexsha": "e5dcc18618b7d3de264d07c85bca20ee18ca4439", "size": 306, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/0009/compute.jl", "max_stars_repo_name": "Dynortice/Project-Euler", "max_stars_repo_head_hexsha": "99a0201b5d5f147eab77fc52d9db8995045cded0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/0009/compute.jl", "max_issues_repo_name": "Dynortice/Project-Euler", "max_issues_repo_head_hexsha": "99a0201b5d5f147eab77fc52d9db8995045cded0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/0009/compute.jl", "max_forks_repo_name": "Dynortice/Project-Euler", "max_forks_repo_head_hexsha": "99a0201b5d5f147eab77fc52d9db8995045cded0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8571428571, "max_line_length": 35, "alphanum_fraction": 0.2875816993, "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992923570261, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7523479855801982}}
{"text": "@doc raw\"\"\"\n    GibbsKernel(; lengthscale)\n\nGibbs Kernel with lengthscale function `lengthscale`.\n\nThe Gibbs kernel is a non-stationary generalisation of the squared exponential\nkernel. The lengthscale parameter ``l`` becomes a function of\nposition ``l(x)``.\n\n# Definition\n\nFor inputs ``x, x'``, the Gibbs kernel with lengthscale function ``l(\\cdot)``\nis defined as\n```math\nk(x, x'; l) = \\sqrt{\\left(\\frac{2 l(x) l(x')}{l(x)^2 + l(x')^2}\\right)}\n\\quad \\exp{\\left(-\\frac{(x - x')^2}{l(x)^2 + l(x')^2}\\right)}.\n```\n\nFor a constant function ``l \\equiv c``, one recovers the [`SqExponentialKernel`](@ref)\nwith lengthscale `c`.\n\n# References\n\nMark N. Gibbs. \"Bayesian Gaussian Processes for Regression and Classication.\" PhD thesis, 1997\n\nChristopher J. Paciorek and Mark J. Schervish. \"Nonstationary Covariance Functions\nfor Gaussian Process Regression\". NeurIPS, 2003\n\nSami Remes, Markus Heinonen, Samuel Kaski. \"Non-Stationary Spectral Kernels\". arXiV:1705.08736, 2017\n\nSami Remes, Markus Heinonen, Samuel Kaski. \"Neural Non-Stationary Spectral Kernel\". arXiv:1811.10978, 2018\n\"\"\"\nstruct GibbsKernel{T} <: Kernel\n    lengthscale::T\nend\n\nGibbsKernel(; lengthscale) = GibbsKernel(lengthscale)\n\nfunction (k::GibbsKernel)(x, y)\n    lengthscale = k.lengthscale\n    lx = lengthscale(x)\n    ly = lengthscale(y)\n    l = invsqrt2 * hypot(lx, ly)\n    kernel = (sqrt(lx * ly) / l) * with_lengthscale(SqExponentialKernel(), l)\n    return kernel(x, y)\nend\n", "meta": {"hexsha": "46e14995dd21be41feee245272061d15f7177063", "size": 1441, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/gibbskernel.jl", "max_stars_repo_name": "pitmonticone/KernelFunctions.jl", "max_stars_repo_head_hexsha": "8687d27f9bbaa23bf0ae33069ef8ec79f721717e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/gibbskernel.jl", "max_issues_repo_name": "pitmonticone/KernelFunctions.jl", "max_issues_repo_head_hexsha": "8687d27f9bbaa23bf0ae33069ef8ec79f721717e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/gibbskernel.jl", "max_forks_repo_name": "pitmonticone/KernelFunctions.jl", "max_forks_repo_head_hexsha": "8687d27f9bbaa23bf0ae33069ef8ec79f721717e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6595744681, "max_line_length": 106, "alphanum_fraction": 0.705759889, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697695, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.7522963911648585}}
{"text": "export FiniteDiff\n\n#TODO add boundary conditions\n\n\"\"\"\n`FiniteDiff([domainType=Float64::Type,] dim_in::Tuple, direction = 1)`\n\n`FiniteDiff(x::AbstractArray, direction = 1)`\n\nCreates a `LinearOperator` which, when multiplied with an array `x::AbstractArray{N}`, returns the discretized gradient over the specified `direction` obtained using forward finite differences. \n\n```julia\njulia> FiniteDiff(Float64,(3,))\nδx  ℝ^3 -> ℝ^2\n\njulia> FiniteDiff((3,4),2)\nδy  ℝ^(3, 4) -> ℝ^(3, 3)\n\njulia> all(FiniteDiff(ones(2,2,2,3),1)*ones(2,2,2,3) .== 0)\ntrue\n\n```\n\n\"\"\"\nstruct FiniteDiff{T,N,D,C <: CartesianIndices{N}} <: LinearOperator\n\tdim_in::NTuple{N,Int}\n    idx::C\n\tfunction FiniteDiff{T,N,D}(dim_in) where {T,N,D}\n\t\tD > N && error(\"direction is bigger the number of dimension $N\")\n        idx = CartesianIndices(([i == D ? (2:d) : (1:d) for (i,d) in enumerate(dim_in)]...,))\n        new{T,N,D,typeof(idx)}(dim_in,idx)\n\tend\nend\n\n# Constructors\n#default constructor\nFiniteDiff(domainType::Type, dim_in::NTuple{N,Int}, dir::Int64 = 1) where {N} =\nFiniteDiff{domainType,N,dir}(dim_in)\n\nFiniteDiff(dim_in::NTuple{N,Int}, dir::Int64 = 1) where {N} =\nFiniteDiff(Float64, dim_in, dir)\n\nFiniteDiff(x::AbstractArray{T,N}, dir::Int64 = 1) where {T,N}  = FiniteDiff(eltype(x), size(x), dir)\n\n# Mappings\n\n@generated function mul!(y::AbstractArray{T,N},\n                         L::FiniteDiff{T,N,D},\n                         b::AbstractArray{T,N}) where {T,N,D}\n\tz = zeros(Int,N)\n\tz[D] = 1\n\tidx = CartesianIndex(z...)\n\tex = quote\n        for I in L.idx\n\t\t\ty[I-$idx] = b[I]-b[I-$idx]\n\t\tend\n\t\treturn y\n\tend\nend\n\n@generated function mul!(y::AbstractArray{T,N},\n                         L::AdjointOperator{FiniteDiff{T,N,D,C}},\n                         b::AbstractArray{T,N}) where {T,N,D,C}\n\tz = zeros(Int,N)\n\tz[D] = 1\n\tidx = CartesianIndex(z...)\n\tex = quote\n\t\tfor I in CartesianIndices(size(y))\n\t\t\ty[I] = \n\t\t\tI[$D] == 1 ? -b[I]  :\n\t\t\tI[$D] == size(y,$D) ?   b[I-$idx]  : -b[I]+b[I-$idx]\n\t\tend\n\t\treturn y\n\tend\nend\n\n# Properties\n\ndomainType(L::FiniteDiff{T, N}) where {T, N} = T\ncodomainType(L::FiniteDiff{T, N}) where {T, N} = T\n\nfunction size(L::FiniteDiff{T,N,D}) where {T,N,D} \n\tdim_out = [L.dim_in...]\n\tdim_out[D] = dim_out[D]-1\n\treturn ((dim_out...,), L.dim_in)\nend\n\nfun_name(L::FiniteDiff{T,N,1}) where  {T,N} = \"δx\"\nfun_name(L::FiniteDiff{T,N,2}) where  {T,N} = \"δy\"\nfun_name(L::FiniteDiff{T,N,3}) where  {T,N} = \"δz\"\nfun_name(L::FiniteDiff{T,N,D}) where {T,N,D}  = \"δx$D\"\n\n\nis_full_row_rank(L::FiniteDiff) = true\n\n\n", "meta": {"hexsha": "313c6f8ec90521d52ac8340b405e4b73e2264b06", "size": 2499, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linearoperators/FiniteDiff.jl", "max_stars_repo_name": "nantonel/AbstractOperators.jl", "max_stars_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2017-08-28T17:28:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-21T18:53:01.000Z", "max_issues_repo_path": "src/linearoperators/FiniteDiff.jl", "max_issues_repo_name": "nantonel/AbstractOperators.jl", "max_issues_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2017-11-17T14:43:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-23T20:02:48.000Z", "max_forks_repo_path": "src/linearoperators/FiniteDiff.jl", "max_forks_repo_name": "nantonel/AbstractOperators.jl", "max_forks_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-09-02T08:56:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T18:56:33.000Z", "avg_line_length": 25.7628865979, "max_line_length": 194, "alphanum_fraction": 0.6154461785, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7522688843918878}}
{"text": "using JuAFEM\nusing Tensors\n\n# Stiffness using normal matrices\nfunction ke_element_mat!(Ke, X::Vector{Vec{dim, T}}, fe_values::CellScalarValues{dim}, Ee, B, DB, BDB) where {T, dim}\n    n_basefuncs = getnbasefunctions(fe_values)\n    @assert length(X) == n_basefuncs\n    \n    reinit!(fe_values, X)\n    for q_point in 1:getnquadpoints(fe_values)\n        for i in 1:n_basefuncs\n            dNdx = shape_gradient(fe_values, q_point, i)[1]\n            dNdy = shape_gradient(fe_values, q_point, i)[2]\n            dNdz = shape_gradient(fe_values, q_point, i)[3]\n\n            B[1, i * 3-2] = dNdx\n            B[2, i * 3-1] = dNdy\n            B[3, i * 3-0] = dNdz\n            B[4, 3 * i-1] = dNdz\n            B[4, 3 * i-0] = dNdy\n            B[5, 3 * i-2] = dNdz\n            B[5, 3 * i-0] = dNdx\n            B[6, 3 * i-2] = dNdy\n            B[6, 3 * i-1] = dNdx\n        end\n        \n        A_mul_B!(DB, Ee, B)\n        At_mul_B!(BDB, B, DB)\n        scale!(BDB, getdetJdV(fe_values, q_point))\n        for p in 1:size(Ke,1)\n            for q in 1:size(Ke,2)\n                Ke[p, q] += BDB[p, q]\n            end\n        end\n    end\n    \n    return Ke\nend;\n\n# Stiffness using scalar values\nfunction ke_element!(Ke, X::Vector{Vec{dim, T}}, fe_values::CellScalarValues{dim}, C) where {T,dim}\n    n_basefuncs = getnbasefunctions(fe_values)\n    @assert length(X) == n_basefuncs\n    reinit!(fe_values, X)\n    @inbounds for q_point in 1:getnquadpoints(fe_values)\n        for a in 1:n_basefuncs\n            for b in 1:n_basefuncs\n                ∇ϕa = shape_gradient(fe_values, q_point, a)\n                ∇ϕb = shape_gradient(fe_values, q_point, b)\n                Ke_e = dotdot(∇ϕa, C, ∇ϕb) * getdetJdV(fe_values, q_point)\n                for d1 in 1:dim, d2 in 1:dim\n                    Ke[dim*(a-1) + d1, dim*(b-1) + d2] += Ke_e[d1,d2]\n                end\n            end\n        end\n    end\n    return Ke\nend;\n\n# Stiffness using vector values\nfunction ke_element2!(Ke, X::Vector{Vec{dim, T}}, fe_values::CellVectorValues{dim}, C) where {T,dim}\n    n_basefuncs = getnbasefunctions(fe_values)\n    @assert length(X) * dim == n_basefuncs\n    reinit!(fe_values, X)\n    ɛ = [zero(SymmetricTensor{2, dim, T}) for i in 1:n_basefuncs]\n    @inbounds for q_point in 1:getnquadpoints(fe_values)\n        for i in 1:n_basefuncs\n            ɛ[i] = symmetric(shape_gradient(fe_values, q_point, i)) \n        end\n        dΩ = getdetJdV(fe_values, q_point)\n        for i in 1:n_basefuncs\n            ɛC = ɛ[i] ⊡ C\n            for j in 1:n_basefuncs\n                Ke[i, j] += (ɛC ⊡ ɛ[j]) * dΩ\n            end\n        end\n    end\n    return Ke\nend;\n\nE = 200e9\nν = 0.3\nλ = E*ν / ((1 + ν) * (1 - 2ν))\nμ = E / (2(1 + ν))\nδ(i,j) = i == j ? 1.0 : 0.0\ng(i,j,k,l) = λ*δ(i,j)*δ(k,l) + μ*(δ(i,k)*δ(j,l) + δ(i,l)*δ(j,k))\n\nC = SymmetricTensor{4, 3}(g)\n\n\nM = λ/ν * (1 - ν)\n\nCmat = [ M      λ      λ    0.0    0.0   0.0;\n         λ      M      λ    0.0    0.0   0.0;\n         λ      λ      M    0.0    0.0   0.0;\n        0.0    0.0    0.0    μ     0.0   0.0;\n        0.0    0.0    0.0   0.0     μ    0.0;\n        0.0    0.0    0.0   0.0    0.0    μ]\n\n\ninterpolation = Lagrange{3, RefCube, 1}()\nquad_rule = QuadratureRule{3, RefCube}(1)\nvalues = CellScalarValues(quad_rule, interpolation);\nvector_values = CellVectorValues(quad_rule, interpolation);\n\n# Generate some coordinates\nx = [-1.0 -1.0 -1.0;\n      1.0 -1.0 -1.0;\n      1.0  1.0 -1.0;\n     -1.0  1.0 -1.0;\n     -1.0 -1.0  1.0;\n      1.0 -1.0  1.0;\n      1.0  1.0  1.0;\n     -1.0  1.0  1.0;]\nx = x .+ 0.05 * rand()\nx_vec = reinterpret(Vec{3, Float64}, x, (8,));\n\nn_basefunctions = getnbasefunctions(vector_values)\nKe = zeros(n_basefunctions, n_basefunctions)\nKe2 = copy(Ke)\nKe3 = copy(Ke)\n\nB   =  zeros(6, n_basefunctions)\nDB  =  zeros(6, n_basefunctions)\nBDB =  zeros(n_basefunctions, n_basefunctions);\n\nfill!(Ke, 0)\nfill!(Ke2, 0)\nfill!(Ke3, 0)\nke_element!(Ke2, x_vec, values, C)\nke_element2!(Ke3, x_vec, vector_values, C);\nke_element_mat!(Ke, x_vec, values, Cmat, B, DB, BDB);\n\nusing Test\n@test norm(Ke - Ke2) / norm(Ke) < 1e-14\n@test norm(Ke - Ke3) / norm(Ke) < 1e-14\n\nprintln(\"Stiffness successful\")\n\nKe\n\n\n", "meta": {"hexsha": "cac90e44ed469c3bc1d1c712d1582b7e271a1d93", "size": 4117, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/JuaFEM/stiffness_example.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PtFEM.jl-9b64898b-da2a-5774-a656-fd6fb605642c", "max_stars_repo_head_hexsha": "35a9d7c796a92f5d44bd37a2af574fb366fa51ba", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2017-04-16T11:52:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T06:41:59.000Z", "max_issues_repo_path": "src/JuaFEM/stiffness_example.jl", "max_issues_repo_name": "UnofficialJuliaMirror/PtFEM.jl-9b64898b-da2a-5774-a656-fd6fb605642c", "max_issues_repo_head_hexsha": "35a9d7c796a92f5d44bd37a2af574fb366fa51ba", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2018-07-04T00:14:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:16.000Z", "max_forks_repo_path": "src/JuaFEM/stiffness_example.jl", "max_forks_repo_name": "UnofficialJuliaMirror/PtFEM.jl-9b64898b-da2a-5774-a656-fd6fb605642c", "max_forks_repo_head_hexsha": "35a9d7c796a92f5d44bd37a2af574fb366fa51ba", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2017-05-28T21:43:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T12:43:12.000Z", "avg_line_length": 28.7902097902, "max_line_length": 117, "alphanum_fraction": 0.5397133835, "num_tokens": 1577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7522688824287627}}
{"text": "# Chebyshev regression: least-square fits of data\n# to multidimensional Chebyshev polynomials.\n\nfunction chebregression(x::AbstractVector{SVector{N,Td}}, y::AbstractVector{T},\n                        lb::SVector{N,Td}, ub::SVector{N,Td}, order::NTuple{N,Int}) where {N,Td<:Real,T<:Union{SVector,Number}}\n    length(x) == length(y) || throw(DimensionMismatch())\n    length(x) ≥ prod(order .+ 1) || throw(ArgumentError(\"not enough data points $(length(x)) to fit to order $order\"))\n\n    # assemble rhs as matrix\n    Y = Array{float(eltype(T))}(undef, length(y), length(first(y)))\n    for j = 1:length(y)\n        Y[j,:] .= y[j + (firstindex(y)-1)]\n    end\n\n    # assemble lhs matrix\n    # (TODO: this algorithm is O(length(x) * length(c)²),\n    #  but it should be possible to do it in linear time.\n    #  However, the A \\ Y step is also O(mn²), so this\n    #  only affects the constant factor in the complexity.)\n    c = ChebPoly{N,Td,Td}(zeros(Td, order .+ 1), lb, ub)\n    A = Array{Td}(undef, length(x), length(c.coefs))\n    for i = 1:length(c.coefs)\n        c.coefs[i] = 1 # basis function\n        for j = 1:length(x)\n            A[j,i] = c(x[j + (firstindex(x)-1)])\n        end\n        c.coefs[i] = 0 # reset\n    end\n\n    # least-square solution\n    C = A \\ Y\n\n    # rearrange C into a ChebPoly\n    Tc = typeof(zero(T) * one(eltype(Y)))\n    coefs = Array{Tc,N}(reshape(reinterpret(Tc, vec(transpose(C))), order .+ 1))\n    return ChebPoly{N,Tc,Td}(coefs, lb, ub)\nend\n\n# convert arrays to vectors of svectors or scalars\nto_svectors(x::AbstractVector{<:Number}) = x\nto_svectors(x::AbstractVector{<:Number}, ::Val{1}) = SVector{1}.(x)\nto_svectors(x::AbstractVector{<:SVector{N}}) where {N} = x\nto_svectors(x::AbstractVector{<:SVector{N}}, ::Val{N}) where {N} = x\nto_svectors(x::AbstractVector{<:AbstractVector{T}}, ::Val{N}=Val(length(first(x)))) where {T<:Number,N} =\n    SVector{N,T}.(x)\nto_svectors(x::AbstractMatrix{T}, ::Val{N}=Val(size(x,2))) where {T<:Number,N} =\n    SVector{N,T}[row for row in eachrow(x)]\n\n# normalize x and y arguments to vectors of svectors or scalars\nchebregression(x::AbstractVecOrMat, y::AbstractVecOrMat, lb::AbstractVector, ub::AbstractVector, order::NTuple{N}) where {N} =\n    chebregression(to_svectors(x, Val{N}()), to_svectors(y), SVector{N}(lb), SVector{N}(ub), order)\n\nchebregression(x::AbstractVecOrMat, y::AbstractVecOrMat, order::NTuple{N}) where {N} =\n    chebregression(to_svectors(x, Val{N}()), to_svectors(y), order)\n\n# accept scalar bounds and order in 1d case\nchebregression(x::AbstractVector{<:Real}, y::AbstractVecOrMat, lb::Real, ub::Real, order::Integer) =\n    chebregression(x, y, SVector(lb), SVector(ub), (order,))\nchebregression(x::AbstractVector{<:Real}, y::AbstractVecOrMat, order::Integer) =\n    chebregression(x, y, minimum(x), maximum(x), order)\n\n# construct lb and ub if omitted\nchebregression(x::AbstractVector{<:SVector{N}}, y::AbstractVector, order::NTuple{N}) where {N} =\n    chebregression(x, y, reduce((a,b) -> min.(a,b), x), reduce((a,b) -> max.(a,b), x), order)\n\n# promote arguments to common types\nfunction chebregression(x::AbstractVector{SVector{N,Tx}}, y::AbstractVector{Ty},\n    lb::SVector{N,Tlb}, ub::SVector{N,Tub}, order::NTuple{N,<:Integer}) where {N,Tx<:Real,Tlb<:Real,Tub<:Real,Ty<:Union{SVector,Number}}\n    Td = float(promote_type(Tx,Tub,Tlb))\n    return chebregression(AbstractVector{SVector{N,Td}}(x), y, SVector{N,Td}(lb), SVector{N,Td}(ub), NTuple{N,Int}(order))\nend\n\n\"\"\"\n    chebregression(x, y, [lb, ub,] order)\n\nReturn a Chebyshev polynomial (`ChebPoly`) constructed by\nperforming a least-square fit of Chebyshev polnomials of the\ngiven `order`, where `x` are the coordinates of the data\npoints `y`.  `lb` and `ub` are the lower and upper bounds,\nrespectively, of the Chebyshev domain; these should normally\nenclose all of the points in `x`, and default to the minimum\nand maximum coordinates in `x` if they are omitted.\n\nIn the 1d case, `x` is an array of scalars, `lb < ub`\nare scalars, and `order` is an integers.   In the `N`-dimensional\ncase, `order` is an `N`-tuple of integers (the order in each\ndimension), `lb` and `ub` are `N`-component vectors, and\n`x` is an array of `N`-component vectors (or a matrix with\n`N` columns, interpreted as the vector components).\n\n`y` can be a vector or numbers or a vector of vectors (for vector-\nvalued Chebyshev fits).  The latter case can also be input\nas a matrix whose columns are the vector componnents.  `size(x,1)`\nand `size(y,1)` must match, and must exceed `prod(order .+ 1)`.\n\"\"\"\nfunction chebregression end\n", "meta": {"hexsha": "7db4371e626b175a1f557d28e75df139d94eaf71", "size": 4550, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/regression.jl", "max_stars_repo_name": "stevengj/FastChebInterp.jl", "max_stars_repo_head_hexsha": "706d0482b1d9be08a659d507c558a80e38e0ce44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2020-08-13T21:26:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T07:21:22.000Z", "max_issues_repo_path": "src/regression.jl", "max_issues_repo_name": "stevengj/FastChebInterp.jl", "max_issues_repo_head_hexsha": "706d0482b1d9be08a659d507c558a80e38e0ce44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-07-12T21:15:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-14T02:12:36.000Z", "max_forks_repo_path": "src/regression.jl", "max_forks_repo_name": "stevengj/FastChebInterp.jl", "max_forks_repo_head_hexsha": "706d0482b1d9be08a659d507c558a80e38e0ce44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-08-16T23:27:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-09T00:33:36.000Z", "avg_line_length": 46.9072164948, "max_line_length": 136, "alphanum_fraction": 0.6742857143, "num_tokens": 1461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7522688804472356}}
{"text": "export MvNormalModel, MvNormalData, MvNormalParams\n\n\"\"\"\nModel observations as drawn from a multivariate normal distribution. See\n`MvNormalData` for summarizing data for estimation and likelihood calculations.\n\"\"\"\nstruct MvNormalModel end\n\n\"\"\"\n    $SIGNATURES\n\nTest if `matrix` is square and conformable with `vector`.\n\"\"\"\nfunction is_conformable_square(vector::AbstractVector, matrix::AbstractMatrix)\n    k = length(vector)\n    size(matrix) == (k, k)\nend\n\nstruct MvNormalData{TW <: Real, Tm <: AbstractVector, TS <: AbstractMatrix}\n    \"sum of the weights (alternatively, total number of observations)\"\n    W::TW\n    \"(weighted) sample mean\"\n    m::Tm\n    \"(weighted) sample covariance matrix\"\n    S::TS\n    @doc \"\"\"\n        MvNormalData(n, m, S)\n\n    Multivariate normal model summary statistics with `n` observations, mean `m`\n    and sample covariance `S`. Only saves the summary statistics.\n\n    !!! usage\n\n        Use `MvNormalData(X, [wv])` to construct from data.\n    \"\"\" ->                      # FIXME workaround, remove -> in v0.7\n    function MvNormalData(W::TW, m::Tm, S::TS) where {TW <: Real,\n                                                      Tm <: AbstractVector,\n                                                      TS <: AbstractMatrix}\n        @argcheck is_conformable_square(m, S)\n        new{TW, Tm, TS}(W, m, S)\n    end\nend\n\nsize(ss::MvNormalData) = ss.W, length(ss.m)\n\nfunction show(io::IO, ss::MvNormalData)\n    W, k = size(ss)\n    println(io, \"Summary statistics for multivariate normal, $(W) × $(k) samples\")\n    println(io, \"sample mean: $(ss.m)\")\n    println(io, \"sample covariance: $(ss.S)\")\nend\n\n\"\"\"\n    $SIGNATURES\n\nMultivariate normal summary statistics from observations (each row of `X` is an\nobservation).\n\"\"\"\nfunction MvNormalData(X::AbstractMatrix)\n    m, S = mean_and_cov(X, 1; corrected = false)\n    MvNormalData(size(X, 1), vec(m), S)\nend\n\n\"\"\"\n    $SIGNATURES\n\nMultivariate normal summary statistics from observations (each row of `X` is an\nobservation), with weights.\n\"\"\"\nfunction MvNormalData(X::AbstractMatrix, wv::AbstractWeights)\n    m, S = mean_and_cov(X, wv, 1; corrected = false)\n    MvNormalData(sum(wv), vec(m), S)\nend\n\nstruct MvNormalParams{Tμ, TΣ}\n    \"mean\"\n    μ::Tμ\n    \"variance\"\n    Σ::TΣ\n    @doc \"\"\"\n        MvNormalParams(μ, Σ)\n\n    Parameters for the multivariate normal model ``x ∼ MvNormal(μ, Σ)``.\n\n    !!! usage\n\n        Construct using [`MLE(::MvNormalModel, ::MvNormalData)`](@ref).\n    \"\"\" ->                      # FIXME workaround, remove -> in v0.7\n    function MvNormalParams(μ::Tμ, Σ::TΣ) where {Tμ, TΣ}\n        @argcheck is_conformable_square(μ, Σ)\n        new{Tμ, TΣ}(μ, Σ)\n    end\nend\n\nMLE(::MvNormalModel, ss::MvNormalData) = MvNormalParams(ss.m, ss.S)\n\nfunction loglikelihood(::MvNormalModel, ss::MvNormalData, params::MvNormalParams)\n    @unpack W, m, S = ss\n    @unpack μ, Σ = params\n    K = length(m)\n    @argcheck length(μ) == K\n    C = cholfact(Σ)\n    d = m-μ\n    -W/2*(K*log(2*π) + logdet(C) + dot(vec(S) + vec(d * d'), vec(inv(Σ))))\nend\n\nvec_parameters(ϕ::MvNormalParams) = vec_parameters((ϕ.μ, ϕ.Σ))\n", "meta": {"hexsha": "11754c77caf71fb62d4a4c3aa5e99da80afc4ae7", "size": 3090, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mvnormal.jl", "max_stars_repo_name": "JuliaTagBot/IndirectLikelihood.jl", "max_stars_repo_head_hexsha": "9273ccc688671e1ad35a013635074c21723d3edf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-09-25T13:14:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-14T01:42:21.000Z", "max_issues_repo_path": "src/mvnormal.jl", "max_issues_repo_name": "JuliaTagBot/IndirectLikelihood.jl", "max_issues_repo_head_hexsha": "9273ccc688671e1ad35a013635074c21723d3edf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2018-01-19T12:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-12T13:11:30.000Z", "max_forks_repo_path": "src/mvnormal.jl", "max_forks_repo_name": "JuliaTagBot/IndirectLikelihood.jl", "max_forks_repo_head_hexsha": "9273ccc688671e1ad35a013635074c21723d3edf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:48:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:48:24.000Z", "avg_line_length": 28.6111111111, "max_line_length": 82, "alphanum_fraction": 0.6233009709, "num_tokens": 913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7522688726039359}}
{"text": "\"\"\"\n    project(u::AbstractVector, v::AbstractVector) -> AbstractVector\n\nProject vector `u` onto vector `v`.\n\n# Examples\n\n```jldoctest\njulia> project([1, 1], [1, 0])\n2-element Base.Vector{Float64}:\n 1.0\n 0.0\n\njulia> project([5, 5], [1, 0])\n2-element Base.Vector{Float64}:\n 5.0\n 0.0\n\njulia> project([5, -5], [0, 1])\n2-element Base.Vector{Float64}:\n -0.0\n -5.0\n```\n\n\"\"\"\nfunction project(u::AbstractVector, v::AbstractVector)\n    return (u ⋅ v) / (v ⋅ v) * v\nend\n\n\n\"\"\"\n    project(point::AbstractVector, line::AbstractLine) -> StaticArrays.SVector\n\nProject a point onto a line.\n\n\n# Examples\n\n```jldoctest\njulia> project([1, 1], Line([0, 0], [1, 0]))\n2-element StaticArrays.SVector{2, Float64} with indices SOneTo(2):\n 1.0\n 0.0\n\njulia> project([5, -1], Line([0, 0], [1, 0]))\n2-element StaticArrays.SVector{2, Float64} with indices SOneTo(2):\n 5.0\n 0.0\n\njulia> project([1, 0], Line([0, 0], [1, 1]))\n2-element StaticArrays.SVector{2, Float64} with indices SOneTo(2):\n 0.5\n 0.5\n\njulia> point = project([1, 0, 0], Line([0, 0, 0], [1, 1, 1]));\n\njulia> round.(point, digits=3)\n3-element StaticArrays.SVector{3, Float64} with indices SOneTo(3):\n 0.333\n 0.333\n 0.333\n```\n\n\"\"\"\nfunction project(point::AbstractVector, line::AbstractLine)\n\n    # Vector from the point on the line to the point in space.\n    vector_to_point = Vector(line.point, point)\n\n    # Vector projected onto the line.\n    vector_projected = project(vector_to_point, line.direction)\n\n    return line.point + vector_projected\nend\n\n\n\"\"\"\n    project(point::AbstractVector, plane::AbstractPlane) -> StaticArrays.SVector\n\nProject a point onto a plane.\n\n# Examples\n\n```jldoctest\njulia> project([0, 0, 5], Plane([0, 0, 0], [0, 0, 1]))\n3-element StaticArrays.SVector{3, Float64} with indices SOneTo(3):\n 0.0\n 0.0\n 0.0\n\njulia> plane = Plane([1,2,3], [1, 3, -2]);\n\njulia> point_projected = project([5, 1, 3], plane);\n\njulia> round.(point_projected, digits=3)\n3-element StaticArrays.SVector{3, Float64} with indices SOneTo(3):\n 4.929\n 0.786\n 3.143\n```\n\n\"\"\"\nfunction project(point::AbstractVector, plane::AbstractPlane)\n\n    # Vector from the point in space to the point on the plane.\n    vector_to_plane_point = Vector(point, plane.point)\n\n    # Perpendicular vector from the point in space to the plane.\n    vector_to_plane = project(vector_to_plane_point, plane.normal)\n\n    return point + vector_to_plane\nend\n", "meta": {"hexsha": "582fb608470e09682254a827be4845bc4848f14a", "size": 2357, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/computations/projection.jl", "max_stars_repo_name": "ajhynes7/ScikitSpatial.jl", "max_stars_repo_head_hexsha": "60b0de7ae721c1dcfedfe4cf3b4a9409a4153d37", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-20T10:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-20T10:08:32.000Z", "max_issues_repo_path": "src/computations/projection.jl", "max_issues_repo_name": "ajhynes7/ScikitSpatial.jl", "max_issues_repo_head_hexsha": "60b0de7ae721c1dcfedfe4cf3b4a9409a4153d37", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-19T21:15:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T21:15:19.000Z", "max_forks_repo_path": "src/computations/projection.jl", "max_forks_repo_name": "ajhynes7/ScikitSpatial.jl", "max_forks_repo_head_hexsha": "60b0de7ae721c1dcfedfe4cf3b4a9409a4153d37", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8584070796, "max_line_length": 80, "alphanum_fraction": 0.6754348748, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7522688725855343}}
{"text": "# The weight_space_approx function needed for ApproximateGPs.pathwise_sample\n# Returns both the sampled basis and the distribution over w needed to approximate the GP\nfunction gp_rff_approx(rng, kernel, input_dims, feature_dims)\n    ϕ = sample_basis(rng, kernel, input_dims, feature_dims)\n    p_w = MvNormal(Diagonal(Fill(1., feature_dims)))\n    return ϕ, p_w\nend\n\n# Everything necessary to create a RFF approximation to a stationary kernel\n# Currently ony supports SqExponentialKernel with variance and lengthscale\nstruct RFFBasis{Tinner, Touter, Tω, Tτ, Tsample}\n    inner_weights::Tinner  # lengthscale\n    outer_weights::Touter  # variance (scaled)\n    ω::Tω  # Sampled frequencies;               size(ω): (input_dims, num_features)\n    τ::Tτ  # Sampled phases;                    size(τ): (num_features,)\n    sample_params::Tsample  # Returns a new sample of ω & τ\nend\n\nfunction (ϕ::RFFBasis)(x)\n    # ϕ: R^{input_dims} -> R^{num_features}\n    x_ = x ./ ϕ.inner_weights\n    ωt_x = ϕ.ω'x_\n    return ϕ.outer_weights * cos.(ωt_x .+ ϕ.τ)\nend\n\nfunction resample!(ϕ::RFFBasis)\n    ω, τ = ϕ.sample_params()\n    ϕ.ω .= ω\n    ϕ.τ .= τ\nend\n\n# Currently need to pass `input_dims` explicitly - will eventually be in KernelFunctions\n# https://github.com/JuliaGaussianProcesses/KernelFunctions.jl/issues/16\nfunction sample_basis(rng, kernel, input_dims, num_features=100)\n    inner, outer = spectral_weights(kernel)\n    outer_scaled = outer * √(2/num_features)\n    p_ω = spectral_distribution(kernel, input_dims)\n\n    function sample_params()\n        ω = rand(rng, p_ω, num_features)  #\n        τ = rand(rng, Uniform(0, 2π), num_features)  #\n        return ω, τ\n    end\n\n    return RFFBasis(inner, outer_scaled, sample_params()..., sample_params)\nend\n\nfunction spectral_distribution(::SqExponentialKernel, input_dims)\n    return MvNormal(Diagonal(Fill(1., input_dims)))\nend\n\nspectral_distribution(k::ScaledKernel, args...) = spectral_distribution(k.kernel, args...)\nspectral_distribution(k::TransformedKernel, args...) = spectral_distribution(k.kernel, args...)\n\nspectral_distribution(k::Kernel) =  error(\"Spectral distribution not implemented for kernel:\\n$k\")\n\nfunction spectral_weights(::SqExponentialKernel)\n    return 1.0, 1.0\nend\n\nfunction spectral_weights(k::ScaledKernel)\n    σ² = only(k.σ²)\n    inner, outer = spectral_weights(k.kernel)\n    return inner, outer * √σ²\nend\n\nfunction spectral_weights(k::TransformedKernel{<:Any, <:ScaleTransform})\n    s = only(k.transform.s)\n    inner, outer = spectral_weights(k.kernel)\n    return inner / s, outer\nend\n\nspectral_weights(k::Kernel) = error(\"Spectral weights not implemented for kernel:\\n$k\")\n\n# TODO:\n# ARDTransform\n# ProductKernel\n# SumKernel\n# MaternKernel\n", "meta": {"hexsha": "0c38c41e70daab14d97c0f29ff483cfbf42a4344", "size": 2708, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/random_fourier_features.jl", "max_stars_repo_name": "rossviljoen/PathwiseSampling.jl", "max_stars_repo_head_hexsha": "0da247f51360d132524ca13d0abb3d27fed6a3a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-01T07:05:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T07:05:33.000Z", "max_issues_repo_path": "src/random_fourier_features.jl", "max_issues_repo_name": "rossviljoen/PathwiseSampling.jl", "max_issues_repo_head_hexsha": "0da247f51360d132524ca13d0abb3d27fed6a3a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/random_fourier_features.jl", "max_forks_repo_name": "rossviljoen/PathwiseSampling.jl", "max_forks_repo_head_hexsha": "0da247f51360d132524ca13d0abb3d27fed6a3a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.85, "max_line_length": 98, "alphanum_fraction": 0.7186115214, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7522688706362104}}
{"text": "using StaticArrays, OrdinaryDiffEq, BenchmarkTools\ntspan = (0.0,10.0)\nprintln(\"Testing speed of solving ODEs\\n\")\nprintln(\"---Using StaticArrays: f(t, u) = du::SVector\")\n#--------------------#\n@inline eom(t, u) = SVector{5}(10.0(u[2]-u[1]), u[1]*(28.0-u[3]) - u[2],\nu[1]*u[2] - (8/3)*u[3], 2.0u[4]*(1-u[4]), 0.15*u[4]*(1-u[5]))\n\n# println(\"ODEProblem creation:\")\n# display(@benchmark ODEProblem(eom,SVector{3}(rand(3)),$tspan))\nprob = ODEProblem(eom,SVector{5}(10rand(5)),tspan)\nprintln(\"Solution (for total time 10)\")\nsol = solve(prob,Tsit5(),reltol=1e-8,abstol=1e-8)\ndisplay(@benchmark solve($prob,Tsit5(),reltol=1e-8,abstol=1e-8))\nsleep(0.1)\n\nprintln(\"\\n---Using Base Arrays: f(t, u) = du::Vector\")\n#--------------------#\n@inline eomB(t, u) = [10.0(u[2]-u[1]), u[1]*(28.0-u[3]) - u[2],\nu[1]*u[2] - (8/3)*u[3], 2.0u[4]*(1-u[4]), 0.15*u[4]*(1-u[5])]\n\n# println(\"ODEProblem creation:\")\n# display(@benchmark ODEProblem(eom,rand(3),$tspan))\nprob = ODEProblem(eomB,10rand(5),tspan)\nprintln(\"Solution (for total time 10)\")\nsol = solve(prob,Tsit5(),reltol=1e-8,abstol=1e-8)\ndisplay(@benchmark solve($prob,Tsit5(),reltol=1e-8,abstol=1e-8))\nsleep(0.1)\n\n\n\nprintln(\"\\n---Using Base & in-place: f!(t, u, du)::Vector\")\n\n@inline function eom!(t, u, du)\n    du[1] = 10.0(u[2]-u[1])\n    du[2] = u[1]*(28.0-u[3]) - u[2]\n    du[3] = u[1]*u[2] - (8/3)*u[3]\n    du[4] = 2.0u[4]*(1-u[4])\n    du[5] = 0.15*u[4]*(1-u[5])\nend\n\n# println(\"ODEProblem creation:\")\n# display(@benchmark ODEProblem(eom!,rand(3),$tspan))\nprob = ODEProblem(eom!,10rand(5),tspan)\nprintln(\"Solution (for total time 10)\")\nsol = solve(prob,Tsit5(),reltol=1e-8,abstol=1e-8)\ndisplay(@benchmark solve($prob,Tsit5(),reltol=1e-8,abstol=1e-8))\nsleep(0.1)\n\n\n\n# println(\"\\n---Using MVector & in-place: f!(t, u, du)::MVector\")\n# @inline function eomM!(t, u::MVector, du::MVector)\n#     du[1] = 10.0(u[2]-u[1])\n#     du[2] = u[1]*(28.0-u[3]) - u[2]\n#     du[3] = u[1]*u[2] - (8/3)*u[3]\n# end\n#\n# probM = ODEProblem(eomM!,MVector{3}(10rand(3)),tspan)\n# println(\"Solution (for total time 1)\")\n# sol = solve(probM,Tsit5(),reltol=1e-8,abstol=1e-8)\n# display(@benchmark solve($probM,Tsit5(),reltol=1e-8,abstol=1e-8))\n# # #this doesnt work currently\n", "meta": {"hexsha": "b8ed9bf6ce5161217fb861e48f441c4e3e81d7e6", "size": 2183, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/benchmarks/ODEs.jl", "max_stars_repo_name": "blegat/DynamicalSystems.jl", "max_stars_repo_head_hexsha": "44c9763aa8532bed4554b11d01e0b5759fa36668", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-01-26T02:58:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T17:08:27.000Z", "max_issues_repo_path": "test/benchmarks/ODEs.jl", "max_issues_repo_name": "blegat/DynamicalSystems.jl", "max_issues_repo_head_hexsha": "44c9763aa8532bed4554b11d01e0b5759fa36668", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/benchmarks/ODEs.jl", "max_forks_repo_name": "blegat/DynamicalSystems.jl", "max_forks_repo_head_hexsha": "44c9763aa8532bed4554b11d01e0b5759fa36668", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.109375, "max_line_length": 72, "alphanum_fraction": 0.6042143839, "num_tokens": 926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.7522688647376339}}
{"text": "\nmodule Problems\nexport gen_matching_pennies, manh_dist, hide_and_seek, nemirovski1, nemirovski2, policeman_and_burglar_matrix\n\n\nimport LinearAlgebra\nconst LA = LinearAlgebra\nusing Distributions\nusing Random\n\n\n\n\n\n\"\"\"\n   Two test problems from Nemirovski et al. \"Robust stochastic approximation approach to stochastic programming\"\n\"\"\"\nfunction nemirovski1(n, α=1)\n    A = zeros(n, n)\n    for i in 1:n\n        for j in 1:n\n            A[i, j] = ((i + j - 1) / ( 2n - 1 ))^α\n        end\n    end\n    return A\nend\n\nfunction nemirovski2(n, α=1)\n    A = zeros(n, n)\n    for i in 1:n\n        for j in 1:n\n            A[i, j] = ((abs(i - j) + 1) / ( 2n - 1 ))^α\n        end\n    end\n    return A\nend\n\n\n\"\"\"\n    From Juditski & Nemirovki tutorial. Problem Policemen and Burglar.\n\"\"\"\nfunction policeman_and_burglar_matrix(n, th=0.8; seed=\"false\")\n    if seed != \"false\"\n        Random.seed!(parse(Int, seed))\n    end\n    w = abs.(randn(n))\n    th = 0.8\n    C = reshape(abs.([i - j for i in 1:n, j in 1:n]), (n, n))\n    A = w .*(1 .- exp.(-th .* C))\n    return A\nend\n\nfunction randunif(m, n; seed=\"false\")\n    if seed != \"false\"\n        Random.seed!(parse(Int, seed))\n    end\n\n    A = rand(m, n)\n    return A\nend\n\n\n\"\"\"\nProblem 2.24\n\"\"\"\nfunction manh_dist(m=100, n=100)\n    A = zeros(m, n)\n    for i in 1:m\n        for j in 1:n\n            y = (i - 1) / (m - 1)\n            x = (j - 1) / (n - 1)\n            A[i,j] = abs(x - y)\n        end\n    end\n    return A\nend\n\n\n\"\"\"\n    'Hide and Seek' game\n\"\"\"\nfunction hide_and_seek(m, n, param=0.2; seed=\"false\")\n    if seed != \"false\"\n        Random.seed!(parse(Int, seed))\n    end\n    A = 1.0 * reshape(rand(Bernoulli(param),  m * n), (m,n))\n    return A\nend\n\n\nend\n", "meta": {"hexsha": "4f28ba716718e5f69020a679a763c2ca9f092044", "size": 1693, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problem_instances.jl", "max_stars_repo_name": "ymalitsky/VR_for_VI", "max_stars_repo_head_hexsha": "d96fe2eb7f4398447ab7b53ca1fd6c82cb341c50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-19T16:30:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T07:42:49.000Z", "max_issues_repo_path": "problem_instances.jl", "max_issues_repo_name": "ymalitsky/VR_for_VI", "max_issues_repo_head_hexsha": "d96fe2eb7f4398447ab7b53ca1fd6c82cb341c50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem_instances.jl", "max_forks_repo_name": "ymalitsky/VR_for_VI", "max_forks_repo_head_hexsha": "d96fe2eb7f4398447ab7b53ca1fd6c82cb341c50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.402173913, "max_line_length": 112, "alphanum_fraction": 0.5493207324, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874229, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.7522567192663497}}
{"text": "using Distributions, Statistics, Plots, Random; pyplot()\nRandom.seed!(0)\n\nmu1, sig1, n1 = 0, 2, 8\nmu2, sig2, n2 = 0, 30, 15\ndist1 = Normal(mu1, sig1)\ndist2 = Normal(mu2, sig2)\n\nN = 10^6\ntdArray = Array{Tuple{Float64,Float64}}(undef,N)\n\ndf(s1,s2,n1,n2) =\n    (s1^2/n1 + s2^2/n2)^2 / ( (s1^2/n1)^2/(n1-1) + (s2^2/n2)^2/(n2-1) )\n\nfor i in 1:N\n    x1Data = rand(dist1, n1)\n    x2Data = rand(dist2, n2)\n    x1Bar,x2Bar = mean(x1Data),mean(x2Data)\n    s1,s2 = std(x1Data),std(x2Data)\n    tStat = (x1Bar - x2Bar) / sqrt(s1^2/n1 + s2^2/n2)\n    tdArray[i] = (tStat , df(s1,s2,n1,n2))\nend\nsort!(tdArray, by = first)\n\ninvVal(v,i) = quantile(TDist(v),i/(N+1))\n\nxCoords  = Array{Float64}(undef,N)\nyCoords1 = Array{Float64}(undef,N)\nyCoords2 = Array{Float64}(undef,N)\n\nfor i in 1:N\n    xCoords[i] = first(tdArray[i])\n    yCoords1[i] = invVal(last(tdArray[i]), i)\n    yCoords2[i] = invVal(n1+n2-2, i)\nend\n\nscatter(xCoords, yCoords1, c=:blue, label=\"Calculated v\", msw=0)\nscatter!(xCoords, yCoords2, c=:red, label=\"Fixed v\", msw=0)\nplot!([-10,10], [-10,10],\n\t c=:black, lw=0.3, xlims=(-8,8), ylims=(-8,8), ratio=:equal, label=\"\", \n\t xlabel=\"Theoretical t-distribution quantiles\", \n\t ylabel=\"Simulated t-distribution quantiles\", legend=:topleft)", "meta": {"hexsha": "0596d8cd5ed9d1527c386d42c6de27578f7a999d", "size": 1228, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "6_chapter/vDOF_comparison.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "6_chapter/vDOF_comparison.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "6_chapter/vDOF_comparison.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 29.2380952381, "max_line_length": 72, "alphanum_fraction": 0.6319218241, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.75223085743864}}
{"text": "## ---- Fit\n\"\"\"\n    fit(::Type{RationalFunction}, r::Polynomial, m, n; var=:x)\n\nFit a Pade approximant ([`pade_fit`](@ref)) to `r`.\n\nExamples:\n\n```jldoctext\njulia> using Polynomials, PolynomialRatios\n\njulia> x = variable()\nPolynomial(x)\n\njulia> ex = 1 + x + x^2/2 + x^3/6 + x^4/24 + x^5/120 # Taylor polynomial for e^x\nPolynomial(1.0 + 1.0*x + 0.5*x^2 + 0.16666666666666666*x^3 + 0.041666666666666664*x^4 + 0.008333333333333333*x^5)\n\njulia> maximum(abs, exp(x) - fit(RationalFunction, ex, 1,1)(x) for x ∈ 0:.05:0.5)\n0.017945395966538547\n\njulia> maximum(abs, exp(x) - fit(RationalFunction, ex, 1,2)(x) for x ∈ 0:.05:0.5)\n0.0016624471707165078\n\njulia> maximum(abs, exp(x) - fit(RationalFunction, ex, 2,1)(x) for x ∈ 0:.05:0.5)\n0.001278729299871717\n\njulia> maximum(abs, exp(x) - fit(RationalFunction, ex, 2,2)(x) for x ∈ 0:.05:0.5)\n7.262205147950951e-5\n```\n\"\"\"\nfunction Polynomials.fit(::Type{RationalFunction},r::Polynomial, m::Integer, n::Integer;var=:x)\n    p,q = pade_fit(r, m,n, var=var)\n    p // q\nend\n    \n\n## https://mathworld.wolfram.com/PadeApproximant.html\n\"\"\"\n    pade_fit(r::Polynomial, m,n)\n\nFor a polynomial `r` of degree `d ≥ m + n`, find a rational function `p/q` with\n`degree(p) ≤ m`, `degree(q) ≤ n` and `q*r - p = x^{m+n+1}*s(x)` for some polynomial `s`.\n\nThis implementation sets up a system of equations to identify `p` and `q`.\n\"\"\"\nfunction pade_fit(p::Polynomial{T}, m::Integer, n::Integer; var=:x) where {T}\n    d = degree(p)\n    @assert (0 <= m) && (1 <= n) && (m + n <= d)\n\n    # could be much more perfomant                \n    c = convert(LaurentPolynomial, p) # for better indexing\n    cs = [c[m+j-i] for j ∈ 1:n, i ∈ 0:n]\n    \n    qs′ = cs[:, 2:end] \\ cs[:,1]\n    qs = vcat(1, -qs′)\n\n    cs = [c[0 + j - i] for j ∈ 0:m, i∈0:n]\n    ps = cs * qs\n\n    Polynomial(ps, var), Polynomial(qs,var)\nend\nexport pade_fit\n\n    \n", "meta": {"hexsha": "9f9b1fe3efa82c4bbd2d01eddf250aa5a00d9707", "size": 1843, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pade.jl", "max_stars_repo_name": "jverzani/PolynomialRatios.jl", "max_stars_repo_head_hexsha": "3159f959b89ddb28c05c3b5d666e6f1fce7956e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pade.jl", "max_issues_repo_name": "jverzani/PolynomialRatios.jl", "max_issues_repo_head_hexsha": "3159f959b89ddb28c05c3b5d666e6f1fce7956e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pade.jl", "max_forks_repo_name": "jverzani/PolynomialRatios.jl", "max_forks_repo_head_hexsha": "3159f959b89ddb28c05c3b5d666e6f1fce7956e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3538461538, "max_line_length": 113, "alphanum_fraction": 0.6115029843, "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7522308530899171}}
{"text": "function sample_interpolation(x,y,xmin,xmax,step)\n\n  nx = length(x)\n  n = round(Int64,(xmax-xmin)/step+1)\n  xnew = Vector{Float64}(undef,n)\n  ynew = Vector{Float64}(undef,n)\n\n  for i in 1:n\n   xnew[i] = xmin + (i-1)*step \n   ix = findfirst( x -> x > xnew[i], x )\n   if ix == 1 \n     ynew[i] = y[1]\n   elseif ix == nothing\n     ynew[i] = y[nx]\n   else\n     ynew[i] = y[ix-1] + (xnew[i]-x[ix-1])*((y[ix]-y[ix-1])/(x[ix]-x[ix-1]))\n   end\n  end\n\n  return xnew, ynew\n\nend\n", "meta": {"hexsha": "624040dba06c4ad800ad3a8bafe1f84bab3ba53a", "size": 467, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sample_interpolation.jl", "max_stars_repo_name": "mcubeg/M3GTools", "max_stars_repo_head_hexsha": "48ab02a23f0095e7964bfb047836f090f8d35331", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-22T05:04:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-30T06:32:25.000Z", "max_issues_repo_path": "src/sample_interpolation.jl", "max_issues_repo_name": "mcubeg/M3GTools", "max_issues_repo_head_hexsha": "48ab02a23f0095e7964bfb047836f090f8d35331", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sample_interpolation.jl", "max_forks_repo_name": "mcubeg/M3GTools", "max_forks_repo_head_hexsha": "48ab02a23f0095e7964bfb047836f090f8d35331", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-17T10:16:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T10:16:37.000Z", "avg_line_length": 20.3043478261, "max_line_length": 76, "alphanum_fraction": 0.5503211991, "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7522308495916935}}
{"text": "@doc raw\"\"\"\r\n```\r\nZ,p,q = retrieve_surface(algorithm::DiscreteShapeBound, img::AbstractArray, iterations::Int=2000)\r\n```\r\n\r\nSame as [`DiscreteShape`](@ref retrieve_surface(::DiscreteShape, ::AbstractArray, ::iterations))\r\nexcept it has its initial conditions bound by the image as per bellow where\r\n``E`` is the brightness of the image:\r\n```math\r\n\\begin{gathered}\r\nZ_{i,j}=\\begin{cases}-100E_{i,j} &\\text{if } E_{i,j}>0.75\\\\0 &\\text{otherwise}\\\\\r\n\\end{cases}\\\\\\\\p,q=\\nabla E\r\n\\end{gathered}\r\n```\r\n# Example\r\nCompute the heightmap for a synthetic image generated by `generate_surface`.\r\n```julia\r\nusing Images, Makie, ShapeFromShading\r\n\r\n#generate synthetic image\r\nimg = generate_surface(SynthSphere(), 1, [0.2,0,0.9], radius = 5)\r\n\r\n#calculate the heightmap (using 500 iterations)\r\nZ,p,q = retrieve_surface(DiscreteShapeBound(), img, 500)\r\n\r\n#normalize to maximum of 1 (not necessary but makes displaying easier)\r\nZ = Z./maximum(Z)\r\n\r\n#display using Makie (Note: Makie can often take several minutes first time)\r\nr = 0.0:0.1:2\r\nsurface(r, r, Z)\r\n```\r\n# Reference\r\n1. S. Elhabian, \"Hands on Shape from Shading\", Computer Vision and Image Processing, 2008.\r\n\"\"\"\r\nfunction retrieve_surface(algorithm::DiscreteShapeBound, img::AbstractArray, iterations::Int=2000; smoothness::Int=1000)\r\n    ρ,I,σ,τ = estimate_img_properties(img)\r\n    λ = smoothness\r\n    return retrieve_surface(DiscreteShapeBound(), img, ρ, I, iterations, smoothness=λ)\r\nend\r\n\r\nfunction retrieve_surface(algorithm::DiscreteShapeBound, img::AbstractArray, albedo::Real, illumination_direction::Vector{T} where T <: Real, iterations::Int=2000; smoothness::Int=1000)\r\n    ρ = albedo\r\n    I = illumination_direction\r\n    E = Array{Float64}(img)\r\n\r\n    #initialize variables\r\n    p = zeros(Complex{Float64},axes(E))\r\n    q = zeros(Complex{Float64},axes(E))\r\n    R = zeros(Complex{Float64},axes(E))\r\n    Z = zeros(axes(E))\r\n\r\n    #apply bounding conditions\r\n    for i in CartesianIndices(E)\r\n        if E[i] > 0.75\r\n            Z[i] = -100*E[i]\r\n        else\r\n            Z[i] = 0.0\r\n        end\r\n    end\r\n    q, p = Array{Complex{Float64}}.(imgradients(Z, KernelFactors.sobel, \"replicate\"))\r\n    return solve_EulerLagrange(ρ, I, iterations, p, q, R, smoothness, E, Z)\r\nend\r\n", "meta": {"hexsha": "23f64b75dec7c7aeda4f0052cfb9f43f58d4daf0", "size": 2233, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/discreteshapebound.jl", "max_stars_repo_name": "JuliaTagBot/ShapeFromShading.jl", "max_stars_repo_head_hexsha": "c602cf16e4c795b65164e6d96b26cbdfc0d2e0c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/discreteshapebound.jl", "max_issues_repo_name": "JuliaTagBot/ShapeFromShading.jl", "max_issues_repo_head_hexsha": "c602cf16e4c795b65164e6d96b26cbdfc0d2e0c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-02-08T06:23:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T17:29:42.000Z", "max_forks_repo_path": "src/discreteshapebound.jl", "max_forks_repo_name": "JuliaTagBot/ShapeFromShading.jl", "max_forks_repo_head_hexsha": "c602cf16e4c795b65164e6d96b26cbdfc0d2e0c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-01-08T04:40:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T20:13:00.000Z", "avg_line_length": 34.890625, "max_line_length": 186, "alphanum_fraction": 0.6793551276, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7522308454749251}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.16\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nfunction rouletteSpins(p)\n    x = 0\n    while true\n        x += 1\n        if rand() < p\n            return x\n        end\n    end\nend\n\n# ╔═╡ beee83e0-2162-11eb-10f1-7f63ce3708d2\nbegin\n\tp, xGrid, N = 18/37, 1:7, 10^6\n\tmcEstimate = counts([rouletteSpins(p) for _ in 1:N],xGrid)/N\n\n\tgDist = Geometric(p)\n\tgPmf = [pdf(gDist,x-1) for x in xGrid]\nend;\n\n# ╔═╡ beeeb36a-2162-11eb-0698-5fc29070f3ee\nbegin\n\tplot(xGrid, mcEstimate, line=:stem, marker=:circle, \n\t\tc=:blue, ms=10, msw=0, lw=4, label=\"MC estimate\")\n\tplot!( xGrid, gPmf, line=:stem, marker=:xcross,\n\t\tc=:red, ms=6, msw=0, lw=2, label=\"PMF\",\n\t\tylims=(0,0.5), xlabel=\"x\", ylabel=\"Probability\")\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.16\"\n\n# ╔═╡ Cell order:\n# ╠═ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═beee83e0-2162-11eb-10f1-7f63ce3708d2\n# ╠═beeeb36a-2162-11eb-0698-5fc29070f3ee\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "8839a0e58e2c4e23dd16dabc0bff84dc53807ad3", "size": 1456, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.16.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.16.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.16.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 24.2666666667, "max_line_length": 61, "alphanum_fraction": 0.6875, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009619539553, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7522216284156962}}
{"text": "using DataStructures: MutableBinaryMaxHeap, top_with_handle, delete!\n\nfunction proj_simplex0(v::Array{T, 1}, s::T=one(T)) where {T<:Real}\n    n = length(v)\n    if sum(v) == s && all(v .≥ 0)\n        w = v\n    else\n        u = sort(v, rev=true)\n        cssv = cumsum(u)\n        ρ = findall(>(0), u .* Array((1:n)) .> (cssv .- s))[end]\n        θ = (cssv[ρ] - s) / (ρ)\n        w = max.(v .- θ, zero(T))\n    end\n    return w\nend\n\n\n\"\"\" Algorithm from Held, M., Wolfe, P., Crowder, H.: 'Validation of\nsubgradient optimization'. The description is from the Condat L.:\n'Fast Projection onto the Simplex and the l1 Ball'. (Algorithm 1)\"\"\"\n\nfunction proj_simplex1(y::Array{T, 1}, a::T=one(T)) where {T<:Real}\n    n = length(y)\n    if sum(y) == a && all(y .≥ 0)\n        x = y\n    else\n        let τ\n            u = sort(y, rev=true)\n            cumsum_u = zero(T)\n            for k in 1:n\n                if cumsum_u + u[k] < k * u[k] + a\n                    cumsum_u += u[k]\n                    τ = (cumsum_u - a) / k\n                else\n                    break\n                end\n            end\n            x = max.(y .- τ, zero(T))\n        end\n    end\n    return x\nend\n\n\nfunction proj_simplex12(y::Array{T, 1}, a::T=one(T)) where {T<:Real}\n    n = length(y)\n    if sum(y) == a && all(y .≥ 0)\n        return y\n    else\n        τ = 0.0\n        u = sort(y, rev=true)\n        cumsum_u = zero(T)\n        for k in 1:n\n            if cumsum_u + u[k] < k * u[k] + a\n                cumsum_u += u[k]\n                τ = (cumsum_u - a) / k\n            else\n                break\n            end\n        end\n        y = max.(y .- τ, zero(T))\n    end\n    return y\nend\n\n\n\n\n\"\"\" Algorithm from van den Berg, E., Friedlander, M.P.: 'Probing the\nPareto frontier for basis pursuit solution'. The description is from\nCondat L: 'Fast Projection onto the Simplex and the l1\nBall'. (Algorithm 2)\"\"\"\n\n\nfunction proj_simplex2(y::Array{T, 1}, a::T=one(T)) where {T<:Real}\n    N = length(y)\n    if sum(y) == a && all(y .≥ 0)\n        x = y\n    else\n        τ = zero(T)\n        v = MutableBinaryMaxHeap(y)\n        cumsum_u = zero(T)\n        for k in 1:N\n            u = first(v)\n            if cumsum_u + u < k * u + a\n                cumsum_u += u\n                i = top_with_handle(v)[2]\n                delete!(v, i)\n                τ = (cumsum_u - a) / k\n            else\n                break\n            end\n        end\n        x = max.(y .- τ, zero(T))\n    end\n    return x\nend\n\nfunction proj_simplex22(y::Array{Float64, 1}, a=1.0)\n    N = length(y)\n    if sum(y) == a && all(y .≥ 0)\n        x = y\n    else\n        τ = 0.\n        v = MutableBinaryMaxHeap(y)\n        cumsum_u = 0.\n        for k in 1:N\n            u = first(v)\n            if cumsum_u + u < k * u + a\n                cumsum_u += u\n                i = top_with_handle(v)[2]\n                delete!(v, i)\n                τ = (cumsum_u - a) / k\n            else\n                break\n            end\n        end\n        x = max.(y .- τ, 0.)\n    end\n    return x\nend\n\n\"\"\"\nFrom Condat “Fast projection onto the simplex and the l_1 ball”. In: Mathematical Programming 158.1\n(2016), pp. 575–585\n\"\"\"\nfunction proj_simplex_condat(y::Array{Float64, 1}, a=Float64(1.0))\n    N = length(y)\n    v = [y[1]]\n    v_tilde = Float64[]\n    ρ = y[1] - a\n    for n in 2:N\n        yn = y[n]\n        if yn > ρ\n            ρ += (yn - ρ) / (length(v) + 1)\n            if ρ > yn - a\n                append!(v, y[n])\n            else\n                append!(v_tilde, v)\n                v = [yn]\n                ρ = yn - a\n            end\n        end\n    end\n\n    if !isempty(v_tilde)\n        for yi in v_tilde\n            if yi > ρ\n                append!(v, yi)\n                ρ += (yi - ρ) / length(v)\n            end\n        end\n    end\n    # if during the loop rho is increases at least once, then the flag is true. Otherwise we stop\n    flag = true\n    while flag\n        flag = false\n        for (i, yi) in enumerate(v)\n            if yi ≤ ρ\n                deleteat!(v, i)\n                ρ += (ρ - yi) / length(v)\n                flag = true\n            end\n        end\n    end\n    τ = ρ\n    x = max.(y .- τ, zero(y))\n    return x\nend\n\nfunction proj_simplex3(v, z=1.)\n    n = length(v)\n    U = Array((1:n))\n    s = 0\n    ρ = 0\n    while length(U) > 0\n        G = []\n        L = []\n        k = U[rand(1:length(U))]\n        ds = v[k]\n        for j in U\n            if v[j] >= v[k]\n                if j != k\n                    ds += v[j]\n                    append!(G, j)\n                end\n            elseif v[j] < v[k]\n                append!(L, j)\n            end\n        end\n        drho = length(G) + 1\n        if s + ds - (ρ + drho) * v[k] < z\n            s += ds\n            ρ += drho\n            U = L\n        else\n            U = G\n        end\n    end\n    theta = (s - z) / ρ\n    return max.(v .- theta, 0.)\n\nend\n\n\n\n\nfunction proj_simplex4(v, z=1., τ=1e-7, max_iter=1000)\n    lower = 0\n    upper = maximum(v)\n    current = Inf\n    w = zeros(n)\n    for it in 1:max_iter\n        if abs(current) / z < τ && current < 0.\n            break\n        end\n        theta = (upper + lower) / 2.0\n        w = max.(v .- theta, 0.)\n        current = sum(w) - z\n        if current <= 0.\n            upper = theta\n        else\n            lower = theta\n        end\n    end\n    return w\nend\n\n\n\n\nfunction softmax(x::Array{T, 1}) where {T<:Real}\n    # compare with NNlib implementation\n    res = exp.(x .- maximum(x))\n    res ./= sum(res)\n    return res\nend\n", "meta": {"hexsha": "0ff9ff0f59ee0e2923fb13c8f25779f162f53e3e", "size": 5470, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "utils.jl", "max_stars_repo_name": "ymalitsky/VR_for_VI", "max_stars_repo_head_hexsha": "d96fe2eb7f4398447ab7b53ca1fd6c82cb341c50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-19T16:30:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T07:42:49.000Z", "max_issues_repo_path": "utils.jl", "max_issues_repo_name": "ymalitsky/VR_for_VI", "max_issues_repo_head_hexsha": "d96fe2eb7f4398447ab7b53ca1fd6c82cb341c50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils.jl", "max_forks_repo_name": "ymalitsky/VR_for_VI", "max_forks_repo_head_hexsha": "d96fe2eb7f4398447ab7b53ca1fd6c82cb341c50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9831932773, "max_line_length": 99, "alphanum_fraction": 0.4288848263, "num_tokens": 1712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7522216225217948}}
{"text": "import Polynomials\nusing Polynomials\n\n#\n# given the coefficients of a polynomial p(x) = p(n)*x^n + + p(1)*x + p(0)\n#\n# determne a scaling factor for x and a linear factor t that the transformed\n# polynomial q(z) = t * p(s*z) has coefficient p(n) = 1 and all |p(j)| <= 1\n#\n# Invariant:\n# if q, shift, smax, u = polyscale(p) then q = polytransform(p, shift, smax) * u\n# up to numerical precision\n\nFloatOrComplex = Union{AbstractFloat, Complex, Complex{Float32}, Complex{BigFloat}}\n\nfunction polyscale(P::Poly{T}) where {T<:FloatOrComplex}\n\t  n = length(P.a) -1\n    shift = - P.a[n] / n\t\n    P = polytransform(P, shift)\t\n\t  p = P.a\n    p[n] = 0\n    pni = 1 / p[n+1]\n    smaxlog = maximum(log(abs(p[1:n] * pni)) ./ (n+1 - (1:n)))\n    smax = exp(smaxlog)\n    u = pni / exp(smaxlog * n)\n    P = polytransform(Poly(p), 0.0, smax) * u\n    P.a[n+1] = T(1)\n    P, shift, smax, u\nend\n\n\n\"\"\"\ngiven a monic polynomial (x^n + ...) determine a scaling factor s that the transformed\npolynomial q(z) = p(s*z) is half of the time < 1, rest >= 1. Ignore zero coefficients.\n\"\"\"\nfunction polyscale2(P::Poly{T}) where T<:FloatOrComplex\n\n  p = abs.(P.a)\n  n = length(p) - 1\n  pni = T(1) / p[n+1]\n  scale!(p, pni)\n  p = view(p,1:n)\n  bigg = log(realmax(T))\n  tiny = log(realmin(T))\n  clip(x::T) = x == -Inf ? -x : x\n\n  llim = exp(maximum(((log.(p) - bigg) ./ (n:-1:1))))\n  ulim = exp(minimum(clip, ((log.(p) - tiny) ./ (n:-1:1)))) \n  med = exp(sort(log.(p) ./ (n:-1:1))[n÷2+1])\n\n\n\n\n  med, llim, ulim\n\nend\n\n\"\"\"\n\nFind scaling factor for a polynomial p_1 + p_2*x^1 + ... + p_(n+1)*x^n,\nwhich has the minimal possible quotient of coefficients.\nCoefficients which are zero ignored.\n\"\"\"\nfunction polyscale_mini_quotient(P::Poly{T}) where T<:FloatOrComplex\n  p = abs.(P.a)\n  n = length(p) - 1\n  pni = log(abs(p[n+1]))\n  \n  plog = log.(p[1:n]) - pni\n\n  f = Array{real(T)}(2n)\n  copy!(f, plog)\n  copy!(f, n+1, -f, 1, n)\n  g = Array{real(T)}(2n)\n  g =\n  copy!(g, -(n:-1:1))\n  copy!(g, n+1, -g, 1, n)\n\n  xa, xb, val = minimize(f, g)\n  exp(xa), exp(xb), exp(val)\nend\n\n\"\"\"\n\n  `minimize(f::Array, g::Array of same size) -> xa, xb, vmin`\n\n\nSolve the following special linear optimization problem:\nDefine `f(x) = max{ f1[k] + g1[k] * x / k = 1..n1}`.\nMinimize `f(x)` for real x.\nThe function f is convex as maximum of linear (convex) functions is convex.\nIf f is bounded below, it has minmum value `vmin` and a solution interval `[xa, xb]`\nwith `f(x) = vmin for all x in [xa, xb]`.\nIf f is not bounded below, return `vmin = -Inf` and `xa = xb = ±Inf`.\n\"\"\"\nfunction minimize(f::AbstractVector{T}, g::AbstractVector{T}) where T<:Real\n\n  n::Int = length(f)\n  n == length(g) || error(ArgumentError(\"lengths of f1 and g1 are different\"))\n\n  Z = zero(T)\n  inf = typemax(T)\n\n  # remove unwanted infinities\n  f, g = unzip(Iterators.filter(x -> x[1] !=  inf, zip(f, g)))::NTuple{2,AbstractArray{T}}\n  n = length(f)\n  \n  if n == 0\n    return -inf, inf, -inf\n  elseif n == 1\n    if g[1] == Z\n      return -inf, inf, f[1]\n    elseif g[1] < Z\n      return inf, inf, -inf\n    else\n      return -inf, -inf, -inf\n    end\n  end\n\n  eva(x::T)::Tuple{T,T,Int} = maximum(1:n) do k; ((f[k] + g[k] * x), g[k], k) end\n\n  function nextto(x::T)::Tuple{T, T, T}\n    v, gk, k = eva(x)\n    cross(j::Int) = -(f[j] - f[k]) / (g[j] - gk)\n    \n    if isnan(v)\n      xa = xb = x\n    elseif gk > Z\n      xa = xb = maximum(filter(y->y<x, cross.(filter(j->j!=k, 1:n))))\n    elseif gk < Z\n      xa = xb = minimum(filter(y->y>x, cross.(filter(j->j!=k, 1:n))))\n    elseif gk == Z\n      xa = maximum(filter(y->y<x, cross.(filter(j->j!=k, 1:n))))\n      xb = minimum(filter(y->y>x, cross.(filter(j->j!=k, 1:n))))\n    else\n      xa, xb = inf, -inf\n    end\n    xa, xb, gk\n  end\n\n  # find extreme slopes\n  gmax::T, fmax::T, kmax::Int = maximum(1:n) do k; (g[k], f[k], k) end\n  gmin::T, fmin::T, kmin::Int = minimum(1:n) do k; (g[k], f[k], k) end\n  \n  xmax::T = maximum(filter(x->!isnan(x), -(f-f[kmax]) ./ (g - gmax)))\n  xmin::T = minimum(filter(x->!isnan(x), -(f-f[kmin]) ./ (g - gmin)))\n  xa, xb = xmax, xmin\n\n  while xmin < xa || xb < xmax\n    xa, xb, gab = nextto((xmin + xmax) / 2)\n    gs::Int = cmp(gab, Z)\n    if gs >= 0\n      xmax = xb\n    end\n    if gs <= 0\n      xmin = xa\n    end\n  end\n  xa, xb, eva((xa + xb)/ 2)...\nend\n\nmaximum1(f::Function, v0, itr) = mapreduce(f, Base.scalarmax, v0, itr)\nmaximum1(v0, itr) = mapreduce(identity, Base.scalarmax, v0, itr)\nmaximum1(f::Function, itr) = mapreduce(f, Base.scalarmax, lowerbound(f, itr), itr)\nmaximum1(itr) = mapreduce(identity, Base.scalarmax, lowerbound(itr), itr)\nlowerbound(itr) = lowerbound(eltype(itr))\nlowerbound(f::Function, itr) = lowerbound(promote_type(Base.return_types(f, (eltype(itr),))))\nlowerbound(T::Type) = error(\"no lower bound for type $T\")\nlowerbound(::Type{T}) where T<:Union{AbstractFloat,Unsigned} = typemin(T)\nlowerbound(S::Type{Rational{T}}) where T<:Integer = typemin(S)\nlowerbound(::Type{String}) = \"\"\n\n#Base.mr_empty(::typeof(identity),::typeof(Base.scalarmax),::Type{T}) where T<:Real = typemin(T)\n#Base.mr_empty(::typeof(identity),::typeof(Base.scalarmin),::Type{T}) where T<:Real = typemax(T)\n\n\"\"\"\n  `unzip(itr)`\n\nThe iterable object itr must deliver N-tuples.\nConvert an array of N-tuples into N-tuple of arrays.\n\"\"\"\nfunction unzip(aot)\n  tuple(map(x->Array(collect(x)), zip(aot...))...)\nend\n\n", "meta": {"hexsha": "0ed0df0f058f7e0e6b2abf166aae26aab5aec004", "size": 5298, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polyscale.jl", "max_stars_repo_name": "KlausC/Multroot.jl", "max_stars_repo_head_hexsha": "df3978ad1af9829f644155d834a1305b73623b7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polyscale.jl", "max_issues_repo_name": "KlausC/Multroot.jl", "max_issues_repo_head_hexsha": "df3978ad1af9829f644155d834a1305b73623b7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polyscale.jl", "max_forks_repo_name": "KlausC/Multroot.jl", "max_forks_repo_head_hexsha": "df3978ad1af9829f644155d834a1305b73623b7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4838709677, "max_line_length": 96, "alphanum_fraction": 0.5919214798, "num_tokens": 1912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.752221620870043}}
{"text": "# * Linear interpolation\n\n# https://github.com/JuliaLang/julia/pull/18777\nlerp(a::T,b::T,t) where T = T(fma(t, b, fma(-t, a, a)))\nlerp(a::R,b::R,t::C) where {R<:Real,C<:Complex} = lerp(a,b,real(t)) + im*lerp(a,b,imag(t))\nlerp(a::C,b::C,t::R) where {R<:Real,C<:Complex} = lerp(real(a),real(b),t) + im*lerp(imag(a),imag(b),(t))\n\n# * Gaußian quadrature\n\n\"\"\"\n    change_interval!(xs, ws, x, w[, a=0, b=1, γ=1])\n\nTransform the Gaußian quadrature roots `x` and weights `w` on the\nelementary interval `[-1,1]` to the interval `[γ*a,γ*b]` and store the\nresult in `xs` and `ws`, respectively. `γ` is an optional root of\nunity, used to complex-rotate the roots (but not the weights).\n\"\"\"\nfunction change_interval!(xs::AbstractVector{T}, ws, x, w,\n                          a=zero(T), b=one(T), γ=one(T)) where T\n    xs .= lerp.(γ*a, γ*b, (x .+ 1)/2)\n    ws .= (b-a)*w/2\n    xs,ws\nend\n\nchange_interval(x::AbstractVector{T}, w::AbstractVector{T},\n                a=zero(T), b=one(T), γ::U=one(T)) where {T,U} =\n    change_interval!(similar(x,U), similar(w), x, w, a, b)\n\n# * Gauß–Legendre quadrature\n\n\"\"\"\n    num_quadrature_points(k, k′)\n\nThe number of quadrature points needed to exactly compute the matrix\nelements of an operator of polynomial order `k′` with respect to a\nbasis of order `k`.\n\"\"\"\nfunction num_quadrature_points(k, k′)\n    N2 = 2*(k-1) + k′\n    N2>>1 + N2&1\nend\n\n\"\"\"\n    lgwt(t, N) -> (x,w)\n\nGenerate the `N` Gauß–Legendre quadrature roots `x` and associated\nweights `w`, with respect to the B-spline basis generated by the knot\nset `t`.\n\n# Examples\n\n```jldoctest\njulia> CompactBases.lgwt(LinearKnotSet(2, 0, 1, 3), 2)\n([0.0704416, 0.262892, 0.403775, 0.596225, 0.737108, 0.929558], [0.166667, 0.166667, 0.166667, 0.166667, 0.166667, 0.166667])\n\njulia> CompactBases.lgwt(ExpKnotSet(2, -4, 2, 7), 2)\n([2.11325e-5, 7.88675e-5, 0.000290192, 0.000809808, 0.00290192, 0.00809808, 0.0290192, 0.0809808, 0.290192, 0.809808, 2.90192, 8.09808, 29.0192, 80.9808], [5.0e-5, 5.0e-5, 0.00045, 0.00045, 0.0045, 0.0045, 0.045, 0.045, 0.45, 0.45, 4.5, 4.5, 45.0, 45.0])\n```\n\"\"\"\nfunction lgwt(t::AbstractKnotSet{k,ml,mr,T}, N) where {k,ml,mr,T}\n    2N-1 ≥ 2(k-1) || @warn \"N = $N quadrature point$(N > 1 ? \"s\" : \"\") not enough to calculate overlaps between polynomials of order k = $k\"\n    x, w = gausslegendre(N)\n\n    nei = nonempty_intervals(t)\n    ni = length(nei)\n    xo = zeros(T, ni*length(x))\n    wo = zeros(T, ni*length(x))\n\n    for (i,j) in enumerate(nei)\n        sel = (i-1)*N+1 : i*N\n        change_interval!(view(xo, sel), view(wo, sel),\n                         x, w,\n                         t[j], t[j+1])\n    end\n\n    xo,wo\nend\n\n# * Gauß–Lobatto\n\nfunction element_grid(order, a::T, b::T, c::T=zero(T), eiϕ=one(T)) where T\n    x,w = gausslobatto(order)\n    xs,ws = change_interval(x, w, a-c, b-c, eiϕ)\n    c .+ xs, ws\nend\n", "meta": {"hexsha": "6a9ce0f32e6230cc4d19575697bc47642bd04835", "size": 2825, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/quadrature.jl", "max_stars_repo_name": "mortenpi/CompactBases.jl", "max_stars_repo_head_hexsha": "2a2a4b3255c35e95418ab4a9173cf598494de864", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-05-21T20:43:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T02:16:33.000Z", "max_issues_repo_path": "src/quadrature.jl", "max_issues_repo_name": "mortenpi/CompactBases.jl", "max_issues_repo_head_hexsha": "2a2a4b3255c35e95418ab4a9173cf598494de864", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44, "max_issues_repo_issues_event_min_datetime": "2020-05-17T10:10:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T01:07:30.000Z", "max_forks_repo_path": "src/quadrature.jl", "max_forks_repo_name": "mortenpi/CompactBases.jl", "max_forks_repo_head_hexsha": "2a2a4b3255c35e95418ab4a9173cf598494de864", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-24T00:56:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-24T00:56:33.000Z", "avg_line_length": 32.8488372093, "max_line_length": 254, "alphanum_fraction": 0.6053097345, "num_tokens": 1129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7522216208700429}}
{"text": "\"\"\"\n```julia\ntowel(u0 = [0.085, -0.121, 0.075])\n```\n```math\n\\\\begin{aligned}\nx_{n+1} &= a x_n (1-x_n) -0.05 (y_n +0.35) (1-2z_n) \\\\\\\\\ny_{n+1} &= 0.1 \\\\left( \\\\left( y_n +0.35 \\\\right)\\\\left( 1+2z_n\\\\right) -1 \\\\right)\n\\\\left( 1 -1.9 x_n \\\\right) \\\\\\\\\nz_{n+1} &= 3.78 z_n (1-z_n) + b y_n\n\\\\end{aligned}\n```\nThe folded-towel map is a hyperchaotic mapping due to Rössler [1]. It is famous\nfor being a mapping that has the smallest possible dimensions necessary for hyperchaos,\nhaving two positive and one negative Lyapunov exponent.\nThe name comes from the fact that when plotted looks like a folded towel, in every\nprojection.\n\nDefault values are the ones used in the original paper.\n\n[1] : O. E. Rössler, Phys. Lett. **71A**, pp 155 (1979)\n\"\"\"\nfunction towel(u0=[0.085, -0.121, 0.075])\n    return DDS(eom_towel, u0, nothing, jacob_towel)\nend# should result in lyapunovs: [0.432207,0.378834,-3.74638]\nfunction eom_towel(x, p, n)\n    @inbounds x1, x2, x3 = x[1], x[2], x[3]\n    SVector( 3.8*x1*(1-x1) - 0.05*(x2+0.35)*(1-2*x3),\n    0.1*( (x2+0.35)*(1-2*x3) - 1 )*(1 - 1.9*x1),\n    3.78*x3*(1-x3)+0.2*x2 )\nend\nfunction jacob_towel(x, p, n)\n    @SMatrix [3.8*(1 - 2x[1]) -0.05*(1-2x[3]) 0.1*(x[2] + 0.35);\n    -0.19((x[2] + 0.35)*(1-2x[3]) - 1)  0.1*(1-2x[3])*(1-1.9x[1])  -0.2*(x[2] + 0.35)*(1-1.9x[1]);\n    0.0  0.2  3.78(1-2x[3]) ]\nend\n\nfunction eom_towel_iip(dx, x, p, n)\n    @inbounds begin\n        x1, x2, x3 = x[1], x[2], x[3]\n        dx[1] = 3.8*x1*(1-x1) - 0.05*(x2+0.35)*(1-2*x3)\n        dx[2] = 0.1*( (x2+0.35)*(1-2*x3) - 1 )*(1 - 1.9*x1)\n        dx[3] = 3.78*x3*(1-x3)+0.2*x2\n    end\nend\nfunction jacob_towel_iip(J, x, p, n)\n    @inbounds begin\n        J[1,1] = 3.8*(1 - 2x[1])\n        J[2,1] = -0.19((x[2] + 0.35)*(1-2x[3]) - 1)\n        J[3,1] = 0.0\n        J[1,2] = -0.05*(1-2x[3])\n        J[2,2] =  0.1*(1-2x[3])*(1-1.9x[1])\n        J[3,2] = 0.2\n        J[1,3] = 0.1*(x[2] + 0.35)\n        J[2,3] = -0.2*(x[2] + 0.35)*(1-1.9x[1])\n        J[3,3] = 3.78(1-2x[3])\n    end\nend\n\n\n\n\n\"\"\"\n```julia\nstandardmap(u0=0.001rand(2); k = 0.971635)\n```\n```math\n\\\\begin{aligned}\n\\\\theta_{n+1} &= \\\\theta_n + p_{n+1} \\\\\\\\\np_{n+1} &= p_n + k\\\\sin(\\\\theta_n)\n\\\\end{aligned}\n```\nThe standard map (also known as Chirikov standard map) is a two dimensional,\narea-preserving chaotic mapping due to Chirikov [1]. It is one of the most studied\nchaotic systems and by far the most studied Hamiltonian (area-preserving) mapping.\n\nThe map corresponds to the  Poincaré's surface of section of the kicked rotor system.\nChanging the non-linearity parameter `k` transitions the system from completely periodic\nmotion, to quasi-periodic, to local chaos (mixed phase-space) and finally to global\nchaos.\n\nThe default parameter `k` is the critical parameter where the golden-ratio torus is\ndestroyed, as was calculated by Greene [2]. The e.o.m. considers the angle variable\n`θ` to be the first, and the angular momentum `p` to be the second, while\nboth variables\nare always taken modulo 2π (the mapping is on the [0,2π)² torus).\n\nThe parameter container has the parameters in the same order as stated in this\nfunction's documentation string.\n\n[1] : B. V. Chirikov, Preprint N. **267**, Institute of\nNuclear Physics, Novosibirsk (1969)\n\n[2] : J. M. Greene, J. Math. Phys. **20**, pp 1183 (1979)\n\"\"\"\nfunction standardmap(u0=0.001rand(2); k = 0.971635)\n    return DDS(standardmap_eom, u0, [k], standardmap_jacob)\nend\n@inbounds function standardmap_eom(x, par, n)\n    theta = x[1]; p = x[2]\n    p += par[1]*sin(theta)\n    theta += p\n    while theta >= twopi; theta -= twopi; end\n    while theta < 0; theta += twopi; end\n    while p >= twopi; p -= twopi; end\n    while p < 0; p += twopi; end\n    return SVector(theta, p)\nend\n@inbounds standardmap_jacob(x, p, n) =\n@SMatrix [1 + p[1]*cos(x[1])    1;\n          p[1]*cos(x[1])        1]\n\n\"\"\"\n```julia\ncoupledstandardmaps(M::Int, u0 = 0.001rand(2M); ks = ones(M), Γ = 1.0)\n```\n```math\n\\\\begin{aligned}\n\\\\theta_{i}' &= \\\\theta_i + p_{i}' \\\\\\\\\np_{i}' &= p_i + k_i\\\\sin(\\\\theta_i) - \\\\Gamma \\\\left[\n\\\\sin(\\\\theta_{i+1} - \\\\theta_{i}) + \\\\sin(\\\\theta_{i-1} - \\\\theta_{i})\n\\\\right]\n\\\\end{aligned}\n```\nA discrete system of `M` nonlinearly coupled standard maps, first\nintroduced in [1] to study diffusion and chaos thresholds.\nThe *total* dimension of the system\nis `2M`. The maps are coupled through `Γ`\nand the `i`-th map has a nonlinear parameter `ks[i]`.\n\nThe first `M` entries of the state are the angles, the last `M` are the momenta.\n\n[1] : H. Kantz & P. Grassberger, J. Phys. A **21**, pp 127–133 (1988)\n\"\"\"\nfunction coupledstandardmaps end\nusing SparseArrays\nfunction coupledstandardmaps(M::Int, u0 = 0.001rand(2M);\n    ks = ones(M), Γ = 1.0)\n\n    SV = SVector{M, Int}\n    idxs = SV(1:M...) # indexes of thetas\n    idxsm1 = SV(circshift(idxs, +1)...)  #indexes of thetas - 1\n    idxsp1 = SV(circshift(idxs, -1)...)  #indexes of thetas + 1\n\n    csm = CoupledStandardMaps{M}(idxs, idxsm1, idxsp1)\n    J = zeros(eltype(u0), 2M, 2M)\n    # Set ∂/∂p entries (they are eye(M,M))\n    # And they dont change they are constants\n    for i in idxs\n        J[i, i+M] = 1\n        J[i+M, i+M] = 1\n    end\n    sparseJ = sparse(J)\n    p = (ks, Γ)\n    csm(sparseJ, u0, p, 0)\n    return DDS(csm, u0, p, csm, sparseJ)\nend\nstruct CoupledStandardMaps{N}\n    idxs::SVector{N, Int}\n    idxsm1::SVector{N, Int}\n    idxsp1::SVector{N, Int}\nend\nfunction (f::CoupledStandardMaps{N})(xnew::AbstractVector, x, p, n) where {N}\n    ks, Γ = p\n    @inbounds for i in f.idxs\n\n        xnew[i+N] = mod2pi(\n            x[i+N] + ks[i]*sin(x[i]) -\n            Γ*(sin(x[f.idxsp1[i]] - x[i]) + sin(x[f.idxsm1[i]] - x[i]))\n        )\n\n        xnew[i] = mod2pi(x[i] + xnew[i+N])\n    end\n    return nothing\nend\nfunction (f::CoupledStandardMaps{M})(\n    J::AbstractMatrix, x, p, n) where {M}\n\n    ks, Γ = p\n    # x[i] ≡ θᵢ\n    # x[[idxsp1[i]]] ≡ θᵢ+₁\n    # x[[idxsm1[i]]] ≡ θᵢ-₁\n    @inbounds for i in f.idxs\n        cosθ = cos(x[i])\n        cosθp= cos(x[f.idxsp1[i]] - x[i])\n        cosθm= cos(x[f.idxsm1[i]] - x[i])\n        J[i+M, i] = ks[i]*cosθ + Γ*(cosθp + cosθm)\n        J[i+M, f.idxsm1[i]] = - Γ*cosθm\n        J[i+M, f.idxsp1[i]] = - Γ*cosθp\n        J[i, i] = 1 + J[i+M, i]\n        J[i, f.idxsm1[i]] = J[i+M, f.idxsm1[i]]\n        J[i, f.idxsp1[i]] = J[i+M, f.idxsp1[i]]\n    end\n    return J\nend\n\n\n\"\"\"\n```julia\nhenon(u0=zeros(2); a = 1.4, b = 0.3)\n```\n```math\n\\\\begin{aligned}\nx_{n+1} &= 1 - ax^2_n+y_n \\\\\\\\\ny_{n+1} & = bx_n\n\\\\end{aligned}\n```\nThe Hénon map is a two-dimensional mapping due to Hénon [1] that can display a strange\nattractor (at the default parameters). In addition, it also displays many other aspects\nof chaos, like period doubling or intermittency, for other parameters.\n\nAccording to the author, it is a system displaying all the properties of the\nLorentz system (1963) while being as simple as possible.\nDefault values are the ones used in the original paper.\n\nThe parameter container has the parameters in the same order as stated in this\nfunction's documentation string.\n\n[1] : M. Hénon, Commun.Math. Phys. **50**, pp 69 (1976)\n\"\"\"\nfunction henon(u0=zeros(2); a = 1.4, b = 0.3)\n    return DDS(hoop, u0, [a,b], hoop_jac)\nend # should give lyapunov exponents [0.4189, -1.6229]\nhoop(x, p, n) = SVector{2}(1.0 - p[1]*x[1]^2 + x[2], p[2]*x[1])\nhoop_jac(x, p, n) = @SMatrix [-2*p[1]*x[1] 1.0; p[2] 0.0]\n\nfunction henon_iip(u0=zeros(2); a = 1.4, b = 0.3)\n    return DDS(hiip, u0, [a, b], hiip_jac)\nend\nfunction hiip(dx, x, p, n)\n    dx[1] = 1.0 - p[1]*x[1]^2 + x[2]\n    dx[2] = p[2]*x[1]\n    return\nend\nfunction hiip_jac(J, x, p, n)\n    J[1,1] = -2*p[1]*x[1]\n    J[1,2] = 1.0\n    J[2,1] = p[2]\n    J[2,2] = 0.0\n    return\nend\n\n\n\"\"\"\n```julia\nlogistic(x0 = rand(); r = 4.0)\n```\n```math\nx_{n+1} = rx_n(1-x_n)\n```\nThe logistic map is an one dimensional unimodal mapping due to May [1] and is used by\nmany as the archetypal example of how chaos can arise from very simple equations.\n\nOriginally intentend to be a discretized model of polulation dynamics, it is now famous\nfor its bifurcation diagram, an immensly complex graph that that was shown\nbe universal by Feigenbaum [2].\n\nThe parameter container has the parameters in the same order as stated in this\nfunction's documentation string.\n\n[1] : R. M. May, Nature **261**, pp 459 (1976)\n\n[2] : M. J. Feigenbaum, J. Stat. Phys. **19**, pp 25 (1978)\n\"\"\"\nfunction logistic(x0=rand(); r = 4.0)\n    return DDS(logistic_eom, x0, [r], logistic_jacob)\nend\nlogistic_eom(x, p, n) = p[1]*x*(1-x)\nlogistic_jacob(x, p, n) = p[1]*(1-2x)\n\n\"\"\"\n    pomaeu_manneville(u0 = 0.2; z = 2.5)\nThe Pomeau-Manneville map is a one dimensional discrete map which is\ncharacteristic for displaying intermittency [1]. Specifically, for\nz > 2 the average time between chaotic bursts diverges, while\nfor z > 2.5, the map iterates are long range correlated [2].\n\nNotice that here we are providing the \"symmetric\" version:\n```math\nx_{n+1} = \\\\begin{cases}\n-4x_n + 3, & \\\\quad x_n \\\\in (0.5, 1] \\\\\\\\\nx_n(1 + |2x_n|^{z-1}), & \\\\quad |x_n| \\\\le 0.5 \\\\\\\\\n-4x_n - 3, & \\\\quad x_n \\\\in [-1, 0.5)\n\\\\end{cases}\n```\n\n[1] : Manneville & Pomeau, Comm. Math. Phys. **74** (1980)\n\n[2] : Meyer et al., New. J. Phys **20** (2019)\n\"\"\"\nfunction pomeau_manneville(u0 = 0.2, z = 2.5)\n    return DDS(pm_eom, u0, [z], pm_jac)\nend\nfunction pm_eom(x, p, n)\n    if x < -0.5\n        -4x - 3\n    elseif -0.5 ≤ x ≤ 0.5\n        @inbounds x*(1 + abs(2x)^(p[1]-1))\n    else\n        -4x + 3\n    end\nend\nfunction pm_jac(x, p, n)\n    if x < -0.5\n        -4.0\n    elseif -0.5 ≤ x ≤ 0.5\n        @inbounds z = p[1]\n        0.5(x^2 * 2^z * (z-1)*abs(x)^(z-3) + 2^z * abs(x)^(z-1) + 2)\n    else\n        -4.0\n    end\nend\n", "meta": {"hexsha": "c1936fa4b9a2271218bb4801beda553332fc2e2e", "size": 9586, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/discrete_famous_systems.jl", "max_stars_repo_name": "UnofficialJuliaMirror/DynamicalSystemsBase.jl-6e36e845-645a-534a-86f2-f5d4aa5a06b4", "max_stars_repo_head_hexsha": "570ab4ab1dcddde24589e40295172596798d73bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/discrete_famous_systems.jl", "max_issues_repo_name": "UnofficialJuliaMirror/DynamicalSystemsBase.jl-6e36e845-645a-534a-86f2-f5d4aa5a06b4", "max_issues_repo_head_hexsha": "570ab4ab1dcddde24589e40295172596798d73bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/discrete_famous_systems.jl", "max_forks_repo_name": "UnofficialJuliaMirror/DynamicalSystemsBase.jl-6e36e845-645a-534a-86f2-f5d4aa5a06b4", "max_forks_repo_head_hexsha": "570ab4ab1dcddde24589e40295172596798d73bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6261980831, "max_line_length": 98, "alphanum_fraction": 0.5986855831, "num_tokens": 3813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7522216205287171}}
{"text": "immutable Uniform <: ContinuousUnivariateDistribution\n    a::Float64\n    b::Float64\n    function Uniform(a::Real, b::Real)\n\t    if a < b\n\t    \tnew(float64(a), float64(b))\n\t    else\n\t    \terror(\"a < b required for range [a, b]\")\n\t    end\n\tend\nend\n\nUniform() = Uniform(0.0, 1.0)\n\n@_jl_dist_2p Uniform unif\n\nentropy(d::Uniform) = log(d.b - d.a + 1.0)\n\ninsupport(d::Uniform, x::Number) = isreal(x) && d.a <= x <= d.b\n\nkurtosis(d::Uniform) = -6.0 / 5.0\n\nmean(d::Uniform) = (d.a + d.b) / 2.0\n\nmedian(d::Uniform) = (d.a + d.b) / 2.0\n\nfunction mgf(d::Uniform, t::Real)\n\ta, b = d.a, d.b\n\treturn (exp(t * b) - exp(t * a)) / (t * (b - a))\nend\n\nfunction cf(d::Uniform, t::Real)\n\ta, b = d.a, d.b\n\treturn (exp(im * t * b) - exp(im * t * a)) / (im * t * (b - a))\nend\n\nmodes(d::Uniform) = error(\"The uniform distribution has no modes\")\n\nrand(d::Uniform) = d.a + (d.b - d.a) * rand()\n\nskewness(d::Uniform) = 0.0\n\nfunction var(d::Uniform)\n\tw = d.b - d.a\n\treturn w * w / 12.0\nend\n", "meta": {"hexsha": "37694ccf207552ab00191f3b0c0ff7489e1bb142", "size": 961, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/uniform.jl", "max_stars_repo_name": "mewo2/Distributions.jl", "max_stars_repo_head_hexsha": "00dd06fb13632b9f0259f036bb861e47b7170a76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-16T01:43:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-16T01:43:20.000Z", "max_issues_repo_path": "src/univariate/uniform.jl", "max_issues_repo_name": "mewo2/Distributions.jl", "max_issues_repo_head_hexsha": "00dd06fb13632b9f0259f036bb861e47b7170a76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/uniform.jl", "max_forks_repo_name": "mewo2/Distributions.jl", "max_forks_repo_head_hexsha": "00dd06fb13632b9f0259f036bb861e47b7170a76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4468085106, "max_line_length": 66, "alphanum_fraction": 0.5671175858, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7522216187916339}}
{"text": "function sieve(x::Int)\n    sieve = fill(true, x)\n    for i in 2:isqrt(x)\n        if sieve[i]\n            j = 2i\n            while j <= x\n                sieve[j] = false\n                j += i\n            end\n        end\n    end\n    primes = findall(sieve)\n    popfirst!(primes)\n    return primes\nend", "meta": {"hexsha": "c9ba4c18afb1153c01cf95452883c229761ddd78", "size": 300, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/sieve_of_eratosthenes.jl", "max_stars_repo_name": "ellygaytor/Projects", "max_stars_repo_head_hexsha": "6b721d77896d8e24e138272411e0f3b581d86c62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/sieve_of_eratosthenes.jl", "max_issues_repo_name": "ellygaytor/Projects", "max_issues_repo_head_hexsha": "6b721d77896d8e24e138272411e0f3b581d86c62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/sieve_of_eratosthenes.jl", "max_forks_repo_name": "ellygaytor/Projects", "max_forks_repo_head_hexsha": "6b721d77896d8e24e138272411e0f3b581d86c62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0, "max_line_length": 32, "alphanum_fraction": 0.4366666667, "num_tokens": 84, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7522216148908099}}
{"text": "using Plots, Statistics, JLD, LaTeXStrings, StatsBase\nfunction movement(first_pos, step_num)\n    directions=[[0,1],[0,-1],[1,0],[-1,0]]\n    walking=rand(directions, step_num)\n    return first_pos .+ cumsum(hcat(walking),dims=1)[step_num]\nend\nfunction Rg(data)\n    COM=(mean(data, dims=1))\n    return sqrt(mean((data[:,1] .- COM[1]) .^2 + (data[:,2] .- COM[2]) .^2))\nend\n\nstep_num_list=[i for i in 100:100:1000]\nfirst_pos=[0,0]\nrun_num=100000\nAllData=[]\nMeanSquaredDistance=[]\nRgData=[]\nfor step_num in step_num_list\n    final_destinations=zeros(Int, run_num, 2)\n    squared_distance=[]\n    for i in 1:run_num\n        final_destinations[i,:]=movement(first_pos, step_num)\n        push!(squared_distance, (final_destinations[i,1]^2 + final_destinations[i,2]^2))\n    end\n    push!(SavedData, final_destinations)\n    push!(MeanSquaredDistance, mean(squared_distance))\n    push!(RgData, Rg(final_destinations))\nend\n#Radius of Gyration plot:\nscatter(log.(RgData), log.(step_num_list), legend=false, xlabel=\"log(Time)\", ylabel=\"log(Rg)\",\n    title=\"Logarithm of Radious of Gyration over the Logarithm of Time\", dpi=400, titlefontsize=9)\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter5\\\\4.5\\\\Figs\\\\Rg_Time.png\")\n# mean(r^2) plot:\nscatter(MeanSquaredDistance, step_num_list, ylabel=L\"<r^2>\", xlabel=\"Time\",\n    title=\"Mean Squared Distance over Time\", legend=false, dpi=400)\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter5\\\\4.5\\\\Figs\\\\MeanSquare(r)_Time.png\")\n\nsave(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter5\\\\4.5\\\\2DWalker.jld\",\n    \"data\", AllData, \"MeanSquaredDistanceData\",MeanSquaredDistance, \"RgData\",RgData )\n", "meta": {"hexsha": "1e069df18a8f6a2e1344db2900b8c6873eb8af92", "size": 1697, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter5/4.5/4.5.jl", "max_stars_repo_name": "narges8k/computational_physics", "max_stars_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter5/4.5/4.5.jl", "max_issues_repo_name": "narges8k/computational_physics", "max_issues_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter5/4.5/4.5.jl", "max_forks_repo_name": "narges8k/computational_physics", "max_forks_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T09:55:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T09:55:00.000Z", "avg_line_length": 42.425, "max_line_length": 115, "alphanum_fraction": 0.7159693577, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7522216147201469}}
{"text": "function harmonic_oscillator(; X=Universe(2))\n    A = [0.0 1.0; -1.0 0.0]\n    prob = @ivp(x' = Ax, x(0) ∈ Singleton([1.0, 0.0]), x ∈ X)\n    tspan = (0.0, 20.0)\n    return prob, tspan\nend\n\nfunction harmonic_oscillator_homog_RFEM()\n    A = [0 1; -(4π)^2 0]\n    X0 = Hyperrectangle([1.0, 0.0], [0.1, 0.1])\n    prob = @ivp(x' = A*x, x(0) ∈ X0)\n    tspan = (0.0, 2.0)\n    return prob, tspan\nend\n\nfunction harmonic_oscillator_forced_RFEM()\n    A = [0 1; -(4π)^2 0]\n    X0 = Hyperrectangle([1.0, 0.0], [0.1, 0.1])\n    B = Matrix(1.0I, 2, 2)\n    X = Universe(2)\n    U = Interval(0.0) × Interval(0.8, 1.2)\n    prob = @ivp(x' = A*x + B*u, x(0) ∈ X0, x ∈ X, u ∈ U)\n    tspan = (0.0, 2.0)\n    return prob, tspan\nend\n", "meta": {"hexsha": "bb12cfe9bacdf25e149d22475171b3c9c9ae0303", "size": 704, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/models/harmonic_oscillator.jl", "max_stars_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_stars_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-15T10:47:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-05T10:36:28.000Z", "max_issues_repo_path": "test/models/harmonic_oscillator.jl", "max_issues_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_issues_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2020-01-14T18:26:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-29T07:57:50.000Z", "max_forks_repo_path": "test/models/harmonic_oscillator.jl", "max_forks_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_forks_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-10T12:21:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-10T12:21:07.000Z", "avg_line_length": 27.0769230769, "max_line_length": 61, "alphanum_fraction": 0.5298295455, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474220263197, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.7521964870315998}}
{"text": "@doc raw\"\"\"\n    bollingerbands(ta::TimeArray, ma=20, width=2.0)\n\nBollinger Bands\n\n# Formula\n\n```math\n\\begin{align*}\n  \\text{Up}   & = \\text{SMA} + \\text{width} \\times \\sigma(P) \\\\\n  \\text{Mean} & = \\text{SMA} \\\\\n  \\text{Down} & = \\text{SMA} - \\text{width} \\times \\sigma(P)\n\\end{align*}\n```\n\"\"\"\nfunction bollingerbands(ta::TimeArray, ma::Integer = 20, width::AbstractFloat = 2.0)\n  tama   = sma(ta, ma)\n  upband = tama .+ moving(nanstd, ta, ma) .* width .* sqrt((ma - 1) / ma) # take out Bessel correction, per algorithm\n  dnband = tama .- moving(nanstd, ta, ma) .* width .* sqrt((ma - 1) / ma)\n  bands  =  merge(upband, dnband)\n  merge(bands, tama, colnames = [:up, :down, :mean])\nend\n\n@doc raw\"\"\"\n    donchianchannels(ohlc::TimeArray, n = 20; h = :High, l = :Low)\n\nDonchian Channels\n\n# Formula\n\n```math\n\\begin{align*}\n  \\text{Up}   & = \\max(P_1^\\text{High}, \\dots, P_t^\\text{High}) \\\\\n  \\text{Mid}  & = \\frac{\\text{Up} + \\text{Down}}{2} \\\\\n  \\text{Down} & = \\min(P_1^\\text{Low}, \\dots, P_t^\\text{Low})\n\\end{align*}\n```\n\n# References\n\n- [TradingView Wiki]\n  (https://www.tradingview.com/wiki/Donchian_Channels_(DC))\n\"\"\"\nfunction donchianchannels(ohlc::TimeArray, n::Integer = 20; h = :High, l = :Low)\n  up   = rename(moving(nanmax, ohlc[h], n), :up)\n  down = rename(moving(nanmin, ohlc[l], n), :down)\n  mid  = rename((up .+ down) ./ 2, :mid)\n  merge(up, merge(mid, down))\nend\n\n@doc raw\"\"\"\n    truerange(ohlc::TimeArray; h = :High, l = :Low, c = :Close)\n\nTrue Range\n\n# Formula\n\n```math\n\\text{TR} = \\max (P_t^\\text{High}, P_{t-1}^\\text{Close}) -\n            \\min (P_t^\\text{Low},  P_{t-1}^\\text{Close})\n```\n\"\"\"\nfunction truerange(ohlc::TimeArray; h = :High, l = :Low, c = :Close)\n  highs    = merge(ohlc[h], lag(ohlc[c]))\n  lows     = merge(ohlc[l], lag(ohlc[c]))\n  truehigh = TimeArray(timestamp(highs), maximum(values(highs), dims=2), [:hi], meta(highs))\n  truelow  = TimeArray(timestamp(lows),  minimum(values(lows), dims=2),  [:lo], meta(lows))\n  rename(truehigh .- truelow, :tr)\nend\n\n@doc raw\"\"\"\n    atr(ohlc::TimeArray, n = 14; h= :High, l= :Low, c = :Close)\n\nAverage True Range\n\nIt's the exponential moving average of [`truerange`](@ref)\n\n# Formula\n\n```math\n\\text{ATR} = \\text{EMA}(\\text{TR}, n)\n```\n\"\"\"\nfunction atr(ohlc::TimeArray, n::Integer = 14; h = :High, l = :Low, c = :Close)\n  # atr was invented by Wilder, so only his ema is currently supported\n  res = ema(truerange(ohlc; h = h, l = l, c = c), n, wilder = true)\n  TimeArray(timestamp(res), values(res), [:atr], meta(ohlc))\nend\n\n@doc raw\"\"\"\n    keltnerbands(ohlc, n = 20, w = 2; h = :High, l = :Low, c = :Close)\n\nKeltner Channels\n\nLinda Bradford Raschke introduced the newer version of Keltner Channels\nin the 1980s. We implement the newer version.\n\n# Formula\n\n```math\n\\begin{align*}\n  \\text{Up}   & = \\text{Mid} + w \\times \\text{ATR}(n) \\\\\n  \\text{Mid}  & = \\text{EMA}(P^{typical}, n) \\\\\n  \\text{Down} & = \\text{Mid} - w \\times \\text{ATR}(n)\n\\end{align*}\n```\n\n# References\n\n- [StockCharts]\n  (http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:keltner_channels)\n\n- [Wikipedia]\n  (https://en.wikipedia.org/wiki/Keltner_channel)\n\"\"\"\nfunction keltnerbands(ohlc::TimeArray, n::Integer = 20, w::AbstractFloat = 2.0;\n                      h = :High, l = :Low, c = :Close)\n  kma = rename(ema(typical(ohlc, h=h, l=l, c=c), n), :kma)\n  rng = atr(ohlc, n, h=h, l=l, c=c)\n\n  kup = rename(kma .+ (2 .* rng), :kup)\n  kdn = rename(kma .- (2 .* rng), :kdn)\n\n  merge(kup, merge(kma, kdn))\nend\n\n@doc raw\"\"\"\n    chaikinvolatility(ta, n = 10, p = 10; h = High, l = :Low)\n\nChaikin Volatility\n\n# Arguments\n\n- `n` is the smooth period\n- `p` is the previous period\n\n# Formula\n\n```math\n\\text{Chaikin Vola} =\n  \\frac{\\text{EMA}(P^\\text{High}_t - P^\\text{Low}_t, n) - \\text{EMA}(P^\\text{High}_{t-p} - P^\\text{Low}_{t-p}, n)}\n       {\\text{EMA}(P^\\text{High}_{t-p} - P^\\text{Low}_{t-p}, n)}\n  \\times 100\n```\n\n# References\n\n- [IncredibleCharts]\n  (https://www.incrediblecharts.com/indicators/chaikin_volatility.php)\n\"\"\"\nfunction chaikinvolatility(ta::TimeArray, n::Integer = 10, p::Integer = 10;\n                           h = :High, l = :Low)\n  rng = ema(ta[h] .- ta[l], n)\n  prev = lag(rng, p)\n  rename(@.((rng - prev) / prev * 100), :chaikinvolatility)\nend\n", "meta": {"hexsha": "c69592fdf5a6399d2d0baa65ea2c02ddb898a16c", "size": 4223, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/volatility.jl", "max_stars_repo_name": "millerjoey/MarketTechnicals.jl", "max_stars_repo_head_hexsha": "9e09b8fc7b1f324725f83a3edff8117cffc455f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 101, "max_stars_repo_stars_event_min_datetime": "2015-02-03T22:03:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:57:13.000Z", "max_issues_repo_path": "src/volatility.jl", "max_issues_repo_name": "millerjoey/MarketTechnicals.jl", "max_issues_repo_head_hexsha": "9e09b8fc7b1f324725f83a3edff8117cffc455f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 85, "max_issues_repo_issues_event_min_datetime": "2015-02-21T02:31:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T21:29:40.000Z", "max_forks_repo_path": "src/volatility.jl", "max_forks_repo_name": "millerjoey/MarketTechnicals.jl", "max_forks_repo_head_hexsha": "9e09b8fc7b1f324725f83a3edff8117cffc455f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2015-04-25T19:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T01:19:01.000Z", "avg_line_length": 26.898089172, "max_line_length": 117, "alphanum_fraction": 0.6043097324, "num_tokens": 1568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.954647415574754, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7521964843252045}}
{"text": "export LogZero\nexport LogSum2Exp\nexport LogSum3Exp\nexport LogSumExp\n\n\nLogZero(T::DataType) = - floatmax(T)\n\n\"\"\"\n    LogSum2Exp(a::Real, b::Real) -> max(a,b) + log(1.0 + exp(-abs(a-b)))\n```julia\njulia> LogSum2Exp(Float32(1.2),Float64(3.3))\n3.4155195283818967\n```\n\"\"\"\nfunction LogSum2Exp(a::Real, b::Real)\n    isinf(a) && return b\n    isinf(b) && return a\n    if a < b\n        a, b = b, a\n    end\n    return (a + log(1.0 + exp(b-a)))\nend\n\n\nfunction LogSum3Exp(a::Real, b::Real, c::Real)\n    return LogSum2Exp(LogSum2Exp(a,b),c)\nend\n\n\nfunction LogSumExp(a)\n    tmp = LogZero(eltype(a))\n    for i = 1:length(a)\n        tmp = LogSum2Exp(tmp, a[i])\n    end\n    return tmp\nend\n", "meta": {"hexsha": "da7f621fa8e6646c3ac619aafc33db3e39fbde8d", "size": 670, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kit/2-logmath.jl", "max_stars_repo_name": "sonosole/Delta", "max_stars_repo_head_hexsha": "705434e773c40d7906e215fa080a5afc973d4b43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-01T11:00:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-01T11:00:36.000Z", "max_issues_repo_path": "src/kit/2-logmath.jl", "max_issues_repo_name": "sonosole/Delta", "max_issues_repo_head_hexsha": "705434e773c40d7906e215fa080a5afc973d4b43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kit/2-logmath.jl", "max_forks_repo_name": "sonosole/Delta", "max_forks_repo_head_hexsha": "705434e773c40d7906e215fa080a5afc973d4b43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.6315789474, "max_line_length": 72, "alphanum_fraction": 0.6089552239, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474168650673, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.7521964758339041}}
{"text": "print(\"Enter latitude       => \")\nlat = parse(Float64, readline(STDIN))\nprint(\"Enter longitude      => \")\nlng = parse(Float64, readline(STDIN))\nprint(\"Enter legal meridian => \")\nref = parse(Float64, readline(STDIN))\nprintln()\n\nslat = sin(deg2rad(lat))\n@printf \"    sine of latitude:   %.3f\\n\" slat\n@printf \"    diff longitude:     %.3f\\n\" (lng - ref)\n\nprintln(\"\\nHour, sun hour angle, dial hour line angle from 6am to 6pm\\n\")\n\nfor h in -6:6\n  hra = 15 * h\n  hra -= lng - ref\n  hla = rad2deg(atan(slat * tan(deg2rad(hra))))\n  @printf \"HR = %3d; HRA = %7.3f; HLA = %7.3f\\n\" h hra hla\nend\n", "meta": {"hexsha": "c145a368867d0f4c0101e6a1d6446e1fd958e925", "size": 586, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/horizontal-sundial-calculations.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/horizontal-sundial-calculations.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/horizontal-sundial-calculations.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9047619048, "max_line_length": 73, "alphanum_fraction": 0.6211604096, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214501476359, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7521638896096304}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.29\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nZ() = sqrt(-2*log(rand()))*cos(2*pi*rand())\n\n# ╔═╡ 0000b90c-21c2-11eb-2426-fdbaf4727f0c\nbegin\n\txGrid = -4:0.01:4\n\n\thistogram([Z() for _ in 1:10^6], bins=50, \n\t\t\tnormed=true, label=\"MC estimate\")\n\tplot!(xGrid, pdf.(Normal(),xGrid), \n\t\t c=:red, lw=4, label=\"PDF\", \n\t\t xlims=(-4,4), ylims=(0,0.5), xlabel=\"x\", ylabel=\"f(x)\")\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.29\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═0000b90c-21c2-11eb-2426-fdbaf4727f0c\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "23deb7334150d23ccb1ec4becdf7f49f99bb2ebe", "size": 1094, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.29.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.29.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.29.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 24.8636363636, "max_line_length": 58, "alphanum_fraction": 0.7001828154, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.8539127603871312, "lm_q1q2_score": 0.7521238615250748}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 81915028-18e7-11eb-0aed-57a75839d4a7\nbegin\n\tusing CSV\n\tusing DataFrames\n\tusing Plots\n\tusing StatsPlots\n\tusing Pipe: @pipe\n\tusing GLM\n\tusing StatsBase\n\tusing Statistics\n\tusing Dates\nend\n\n# ╔═╡ 02eb9d36-18e8-11eb-24a9-db6f58080189\nmd\"\"\"\n# Seoul Bike Sharing Demand\n\nThis notebook demonstrates how to use GLM to analyze the Seoul Bike Sharing Demand\ndata set.\n\n## Data definitions\n\nThe following definitions are captured from the [UCI Datasets Archive page](https://archive.ics.uci.edu/ml/datasets/Seoul+Bike+Sharing+Demand).\n\n- Date: year-month-day\n- Rented Bike count: Count of bikes rented at each hour\n- Hour: Hour of he day\n- Temperature: Temperature in Celsius\n- Humidity: %\n- Windspeed: m/s\n- Visibility: 10m\n- Dew point temperature: Celsius\n- Solar radiation: MJ/m2\n- Rainfall: mm\n- Snowfall: cm\n- Seasons: Winter, Spring, Summer, Autumn\n- Holiday: Holiday/No holiday\n- Functional Day: NoFunc(Non Functional Hours), Fun(Functional hours)\n\nAs the dataset is targeted for bike sharing demand, the key metrics should be the Rented Bike Count field. The rest of the columns are variables that may be correlated to bike sharing demand.\n\nTaking a quick peek at the variables, it makes sense that they may directly or indirectly affect people's decision of renting a bike. For example, when it's very hot or very cold, then I may take on some other transportation. Likewise, humidity, solar radiation, visibility, rainfall, and snowfall probably play a part as well.\n\nMost variables are continuous variables. The last three columns seasons, holiday, and functional day are discrete variables. As for the hour of day variable, we may want to consider that as discrete because increasing the value (later in the day) does not always affect the response variable (rented bike count) in the same direction.\n\"\"\"\n\n# ╔═╡ eedb4bf8-19a9-11eb-106b-69b047d4118e\nmd\"\"\"\n## Reading data\n\"\"\"\n\n# ╔═╡ dfa5fbf0-18e7-11eb-391b-1d878b9c96f0\nfile = \"https://archive.ics.uci.edu/ml/machine-learning-databases/00560/SeoulBikeData.csv\"\n\n# ╔═╡ aed964bc-18e7-11eb-11f1-a3d9957a45f5\ndf = DataFrame(CSV.File(download(file); dateformats = Dict(:Date => \"dd/mm/yyyy\")));\n\n# ╔═╡ 4d4a9158-18ec-11eb-2fb0-c178637f903a\nmd\"\"\"\n## Data wrangling\n\"\"\"\n\n# ╔═╡ 09577b1e-19aa-11eb-3e6c-175705b4b951\nmd\"\"\"\nLet's quickly examine the data frame and its columns.\n\"\"\"\n\n# ╔═╡ c5b4e26a-18e7-11eb-2bef-2d937faa252d\ndescribe(df, :eltype, :min, :mean, :max, :nmissing)\n\n# ╔═╡ 6ddeb944-18ec-11eb-05c7-b51e7b01578e\nmd\"It looks pretty clean in general but let's rename some columns so they can be referenced more easily in the code below.\"\n\n# ╔═╡ ebc9c09a-18e9-11eb-1f56-ef92258af11f\nrename!(df, \n\t2 => :RentedBikeCount,\n\t4 => :Temperature, 5 => :Humidity, 6 => :WindSpeed, 7 => :Visibility,\n\t8 => :DewPointTemperature, 9 => :SolarRadiation, 10 => :Rainfall, 11 => :Snowfall,\n\t14 => :FunctioningDay\n);\n\n# ╔═╡ 16c31048-19b6-11eb-2ad8-1f984acfb06f\nmd\"\"\"\n## Correlation analysis\n\"\"\"\n\n# ╔═╡ 9564ab04-19b4-11eb-3c4c-815fe8a6031a\nnames(df)\n\n# ╔═╡ 3084d7a6-19b5-11eb-1fa5-9b9f7cd482f4\nlet \n\tcols = 3:11\n\tcolnames = names(df)[cols]\n\tΣ = cor(Matrix(df[:, cols]))\n\theatmap(colnames, colnames, Σ; xrotation = 45, seriescolor = :PiYG_4)\nend\n\n# ╔═╡ 2ef9d8a6-19b6-11eb-0cc5-e1831ce6c40a\nmd\"\"\"\nIt appears that temperature and dew point temperature columns are highly correlated. For that reason, we may want to exclude dew point temperature in our model below.\n\"\"\"\n\n# ╔═╡ 7deee71e-18ec-11eb-113d-fb0cdc6e07ef\nmd\"\"\"\n## Seasonal analysis\nSince this is a time series, let's check if there's a trend.\n\"\"\"\n\n# ╔═╡ 32cd8006-18ec-11eb-221a-d38281aadffb\nplot(df.Date, df.RentedBikeCount; \n\tlegend = :none, \n\tylabel = \"Rented Bike Count\")\n\n# ╔═╡ a9f3aeda-18ec-11eb-2cb9-9f12fd001d88\nmd\"\"\"\nAs we only have 1 year of data, we cannot really see any seasonal trends. However, my intuition is that people don't tend to ride bikes during winter due to the low temperature. When spring comes around March/April, the demand picked up.\n\nNow, December 2018 still look like a higher demand when compared with December 2017. A possibility is that biking may have gotten popular? Not sure...\n\"\"\"\n\n# ╔═╡ 69199458-18ef-11eb-1a46-7d71379a4c04\nmd\"\"\"\n## Time of day\n\nMy initial guess is that people probably do not rent bikes early morning or late night. Let's verify that.\n\"\"\"\n\n# ╔═╡ 5de23772-18ed-11eb-1105-85661397bcd3\nlet \n\tdata = @pipe df |> \n\t\tselect(_, :Date, :Hour, :RentedBikeCount) |>\n\t\tunstack(_, :Hour, :RentedBikeCount) |>\n\t\tsort(_, :Date)\n\t\n\tmatrix = Matrix(data[:, 2:end])'\n\t\n\theatmap(data[:, 1], 0:23, matrix;\n\t\ttitle = \"Rented Bike Count by Date / Hour\",\n\t\tylabel = \"Hour\",\n\t\txrotation = 45.0,\n\t\txticks = Date(2017,12,1):Month(1):Date(2019,1,1),\n\t\tyticks = 0:4:24)\nend\n\n# ╔═╡ 8789d48e-18ef-11eb-2b87-2337472759c7\nmd\"\"\"\n**The two horizontal stripes show that 8 AM and 6 PM are popular hours for bike rentals.** That makes sense because people might want to do some exercise right before work or after work. Or, they may use it for transportation.\n\n**Korean seems to stay up late.** Bike rental demand continues after 6 PM until almost midnight. By 3 AM, it's total silence.\n\nNow, let's take a look at the same data from a different angle using a boxplot.\n\"\"\"\n\n# ╔═╡ 5ef37b5a-18eb-11eb-3f75-cfb5947950fb\nbegin\n\thline([1800], color = :green)\n\t@df df StatsPlots.boxplot!(:Hour, :RentedBikeCount; \n\t\tlegend = :none, \n\t\tcolor = palette(:default)[1],  # reset to first color due to `hline` above\n\t\txlabel = \"Hour\", \n\t\tylabel = \"Rented Bike Count\")\nend\n\n# ╔═╡ 3dc1127e-19a4-11eb-2c09-4f2624f479ac\nmd\"\"\"\nThe boxplot shows the quartiles for each hour across all dates in the year. It confirms our findings that 8 AM and 6 AM are popular times.\n\"\"\"\n\n# ╔═╡ 716cb212-19b1-11eb-190a-7702595f6bab\nmd\"\"\"\n## Categorical Variables\n\nSome variables should be converted to categorical such that GLM.jl can encode dummy variables as such. Instead of mutating the existing `Hour` column, I will create a new `Hour2` column and make it categorical.\n\"\"\"\n\n# ╔═╡ 79056460-19b6-11eb-1c5c-bf9224a0b18e\ndf.Hour2 = df.Hour\n\n# ╔═╡ 9506548a-19b6-11eb-02dc-ad2832999a5b\ncategorical!(df, :Hour2);\n\n# ╔═╡ 7553988e-19a5-11eb-3549-bfd4ea98b2fd\nmd\"\"\"\n## Linear Regression\n\nUsing linear regression, we can fit the data to a linear equation. Here, the response variable is `RentedBikeCount`. We can choose any of the other fields as explanatory variables. Let's start with something simple - an ordinary linear model.\n\"\"\"\n\n# ╔═╡ c18fa04e-19a5-11eb-2f5c-0bdba322a26f\nhour_model = @formula(RentedBikeCount ~ 1 + Hour2)\n\n# ╔═╡ 558893b4-19a6-11eb-3e84-ef27b2749b80\nmd\"\"\"\nTo fit the model, we can use the `lm` function.\n\"\"\"\n\n# ╔═╡ 66b6f680-19a6-11eb-2d2f-afe8d206ee5f\nols = lm(hour_model, df)\n\n# ╔═╡ a46a544a-19a6-11eb-3de3-87dcf7bf431f\nmd\"\"\"\nWe can now use the fitted model to predict bike demand.\n\"\"\"\n\n# ╔═╡ bfe39e20-19a6-11eb-1b9c-b95be62dadb5\nlet \n\ty = df.RentedBikeCount\n\tyhat = round.(Int, predict(ols))\n\t(r_squared = r2(ols), rmsd = rmsd(y, yhat))\nend\n\n# ╔═╡ 079fe824-19a7-11eb-3f1d-b3aa9c9b0f33\nmd\"\"\"\nThe $R^2$ is very low, meaning that the current model cannot make very accurate prediction. That's understandable because we have only used a single explanatory variable. \n\nThe root mean squared deviation (`rmsd`) value shows how much the predicted values deviates from the actual values.\n\nNow, let's design a more complex model but we will continue to use an ordinary linear model.\n\"\"\"\n\n# ╔═╡ 41fb7ff4-19a7-11eb-0945-017db54aa411\nlet \n\tmodel = @formula(RentedBikeCount ~\n\t\t\t\t\t\t1 + Hour2 + Temperature + Humidity + WindSpeed +\n\t\t\t\t\t\tVisibility + SolarRadiation + Rainfall + Snowfall + \n\t\t\t\t\t\tSeasons + Holiday + FunctioningDay)\n\tfitted = lm(model, df)\n\ty = df.RentedBikeCount\n\tyhat = round.(Int, predict(fitted))\n\t(r_squared = r2(fitted), rmsd = rmsd(y, yhat))\nend\n\n# ╔═╡ e3615da0-19a7-11eb-3dc7-d734a6da4420\nmd\"\"\"\nThat's great result. The $R^2$ has jumped to 0.66 now! The RMSD is also reduced quite significantly from 543 to 375.\n\"\"\"\n\n# ╔═╡ ab20e2f6-19a9-11eb-09cd-eff9e75608ee\nmd\"\"\"\n## Generalized Linear Model (GLM)\n\nI wonder if we can do better. The GLM.jl package supports Generalized Linear Model (GLM) which is more flexible that linear regression. We will demonstrate how it works below.\n\nGiven that the response variable is a count, the general wisdom (not mine) is to design the model with Poisson distribution.\n\"\"\"\n\n# ╔═╡ 1accea7a-19a8-11eb-2e37-b943977ad801\nlet \n\tmodel = @formula(RentedBikeCount ~\n\t\t\t\t\t\t1 + Hour2 + Temperature + Humidity + WindSpeed +\n\t\t\t\t\t\tVisibility + SolarRadiation + Rainfall + Snowfall + \n\t\t\t\t\t\tSeasons + Holiday + FunctioningDay)\n\tfitted = glm(model, df, Poisson(), LogLink())\n\ty = df.RentedBikeCount\n\tyhat = round.(Int, predict(fitted))\n\t(rmsd = rmsd(y, yhat), )\nend\n\n# ╔═╡ 61eb2598-19a8-11eb-055d-b166da58fa50\nmd\"\"\"\nThere is no `r2` function defined for GLM models, so we just show RMSD here. As you can see, RMSD is further reduced using this model. That's an improvement.\n\nWhat if we build an even more complex model? So far, all variables are independent. If we introduce interaction terms (multiple variables interacting with each other) then we may create a more powerful predictor.\n\nThe question is how to choose the right variables for the interaction terms. My gut feeling is that it would be appropriate to choose variables that are \"orthogonal\" to each other. For example, humidity and rainfall should be highly correlated and the interaction between them would be somewhat uninteresting. Hence, I have chosen to mix hour of day, temperature, and humidity in the following experiment.\n\"\"\"\n\n# ╔═╡ 66967c54-19b3-11eb-1b13-856ef40132fa\nlet \n\tmodel = @formula(RentedBikeCount ~\n\t\t\t\t\t\t1 + Hour2 + Temperature + Humidity + WindSpeed +\n\t\t\t\t\t\tVisibility + SolarRadiation + Rainfall + Snowfall + \n\t\t\t\t\t\tSeasons + Holiday + FunctioningDay +\n\t\t\t\t\t\tHour2 * Temperature * Humidity\n\t)\n\tfitted = glm(model, df, Poisson(), LogLink())\n\ty = df.RentedBikeCount\n\tyhat = round.(Int, predict(fitted))\n\t(rmsd = rmsd(y, yhat), )\nend\n\n# ╔═╡ 1de7c9b2-19b4-11eb-2085-7b7383899819\nmd\"\"\"\nThat's great! The RMSD is now further reduced although not by a whole lot.\n\"\"\"\n\n# ╔═╡ 34be34aa-19b4-11eb-1a17-e1253c48b050\nmd\"\"\"\n## Todo's\n\nSo far, I have been fitting the model with the complete data set. In order to test the predictive power of the model, I should test it against unseen data. Of course, I don't have any more data than what I have downloaded. What I should do is to split the data set and do cross validation.\n\"\"\"\n\n# ╔═╡ 544e7ac0-19b2-11eb-3931-8f7f10c23212\nmd\"\"\"\n## Resources\n\nI don't know much about GLM before working on this. I found the following resources useful as I learn about the subject:\n\n- Foundations of Linear and Generalized Linear Models by Alan Agresti (Wiley 2015)\n- [Introduction to Generalized Linear Models](https://online.stat.psu.edu/stat504/node/216/)\n- [MIT 18.650 Statistics for Applications, Phillipe Rigolle, Lecture 21-22](https://www.youtube.com/watch?v=X-ix97pw0xY)\n\"\"\"\n\n# ╔═╡ 7c1251d4-19a9-11eb-0450-8dcae5fdc135\nmd\"\"\"\nThanks you for reading. I hope you enjoy this notebook.\n\n_Tom Kwong_, \n_October 2020_\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─02eb9d36-18e8-11eb-24a9-db6f58080189\n# ╟─eedb4bf8-19a9-11eb-106b-69b047d4118e\n# ╠═81915028-18e7-11eb-0aed-57a75839d4a7\n# ╠═dfa5fbf0-18e7-11eb-391b-1d878b9c96f0\n# ╠═aed964bc-18e7-11eb-11f1-a3d9957a45f5\n# ╟─4d4a9158-18ec-11eb-2fb0-c178637f903a\n# ╟─09577b1e-19aa-11eb-3e6c-175705b4b951\n# ╠═c5b4e26a-18e7-11eb-2bef-2d937faa252d\n# ╟─6ddeb944-18ec-11eb-05c7-b51e7b01578e\n# ╠═ebc9c09a-18e9-11eb-1f56-ef92258af11f\n# ╟─16c31048-19b6-11eb-2ad8-1f984acfb06f\n# ╠═9564ab04-19b4-11eb-3c4c-815fe8a6031a\n# ╠═3084d7a6-19b5-11eb-1fa5-9b9f7cd482f4\n# ╟─2ef9d8a6-19b6-11eb-0cc5-e1831ce6c40a\n# ╟─7deee71e-18ec-11eb-113d-fb0cdc6e07ef\n# ╠═32cd8006-18ec-11eb-221a-d38281aadffb\n# ╟─a9f3aeda-18ec-11eb-2cb9-9f12fd001d88\n# ╟─69199458-18ef-11eb-1a46-7d71379a4c04\n# ╠═5de23772-18ed-11eb-1105-85661397bcd3\n# ╟─8789d48e-18ef-11eb-2b87-2337472759c7\n# ╠═5ef37b5a-18eb-11eb-3f75-cfb5947950fb\n# ╟─3dc1127e-19a4-11eb-2c09-4f2624f479ac\n# ╟─716cb212-19b1-11eb-190a-7702595f6bab\n# ╠═79056460-19b6-11eb-1c5c-bf9224a0b18e\n# ╠═9506548a-19b6-11eb-02dc-ad2832999a5b\n# ╟─7553988e-19a5-11eb-3549-bfd4ea98b2fd\n# ╠═c18fa04e-19a5-11eb-2f5c-0bdba322a26f\n# ╟─558893b4-19a6-11eb-3e84-ef27b2749b80\n# ╠═66b6f680-19a6-11eb-2d2f-afe8d206ee5f\n# ╟─a46a544a-19a6-11eb-3de3-87dcf7bf431f\n# ╠═bfe39e20-19a6-11eb-1b9c-b95be62dadb5\n# ╟─079fe824-19a7-11eb-3f1d-b3aa9c9b0f33\n# ╠═41fb7ff4-19a7-11eb-0945-017db54aa411\n# ╟─e3615da0-19a7-11eb-3dc7-d734a6da4420\n# ╟─ab20e2f6-19a9-11eb-09cd-eff9e75608ee\n# ╠═1accea7a-19a8-11eb-2e37-b943977ad801\n# ╟─61eb2598-19a8-11eb-055d-b166da58fa50\n# ╠═66967c54-19b3-11eb-1b13-856ef40132fa\n# ╟─1de7c9b2-19b4-11eb-2085-7b7383899819\n# ╟─34be34aa-19b4-11eb-1a17-e1253c48b050\n# ╟─544e7ac0-19b2-11eb-3931-8f7f10c23212\n# ╟─7c1251d4-19a9-11eb-0450-8dcae5fdc135\n", "meta": {"hexsha": "7ab90243b25c51d406ef92a6c8f48872cbbe0111", "size": 12875, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Week1-GLM.jl/tk3369/notebook.jl", "max_stars_repo_name": "Humans-of-Julia/Challenges", "max_stars_repo_head_hexsha": "9efd04b90110e4c19456a6a75c3f137d613c92fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-15T04:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-15T08:01:32.000Z", "max_issues_repo_path": "Week1-GLM.jl/tk3369/notebook.jl", "max_issues_repo_name": "Humans-of-Julia/WeeklyContest", "max_issues_repo_head_hexsha": "9efd04b90110e4c19456a6a75c3f137d613c92fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week1-GLM.jl/tk3369/notebook.jl", "max_forks_repo_name": "Humans-of-Julia/WeeklyContest", "max_forks_repo_head_hexsha": "9efd04b90110e4c19456a6a75c3f137d613c92fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-18T03:11:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-18T03:11:18.000Z", "avg_line_length": 35.5662983425, "max_line_length": 405, "alphanum_fraction": 0.7387184466, "num_tokens": 4860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.8539127603871312, "lm_q1q2_score": 0.7521238535092603}}
{"text": "# fbp2_example.jl\n\n#using Revise\nusing Sinograms\nusing MIRT: image_geom, sino_geom\n# todo: ImagePhantoms\nusing MIRT: ellipse_im_params, ellipse_im, ellipse_sino #, :shepplogan\nusing MIRTjim: jim\nusing Plots\n\n\n# Geometry\ndown = 2 # down-sampling factor for quicker tests\nig = image_geom(nx=512, ny=504, fov=500)\nig = ig.down(down)\n\nsg = sino_geom(:par, nb=1088, na=984, orbit=360, orbit_start=0, d=541/949, offset=0.25,)\nsg = sg.down(down)\n\n# Phantom object\nell = ellipse_im_params(ig, :shepplogan)\nxtrue = ellipse_im(ig, ell, oversample = 4, hu_scale=1000)\nsino = ellipse_sino(sg, ell, oversample = 4) * 1000 # hu_scale\n\nclim = (1 .+ (-1, 1) .* 0.05) .* 1000\np1 = jim(ig.x, ig.y, xtrue, \"Phantom\"; clim)\np2 = jim(sg.r, sg.ad, sino, \"Sinogram\", aspect_ratio=:none)\n\nplan = fbp2(sg, ig)\n@info \"plan complete\"\nresult,sino_filtered = fbp2(plan, sino)\n@info \"fbp complete\"\n\n\np3 = jim(ig.x, ig.y, result, \"FBP\"; clim = clim)\n#p3 = jim(ig.x, ig.y, result)\n#p4 = jim(sr.r, sg.ad, sino_filtered, \"Filtered Sino\")\n#p4 = plot(sino_filtered, label=\"\")\np4 = jim(ig.x, ig.y, result-xtrue, \"error\"; clim=(-1,1).*100)\n\njim(p1,p2,p3,p4)\n\n\n\n#=\n#original example:\n\ndown = 2\nig = image_geom(nx=512, ny=504, fov=500)\nig = ig.down(down)\nsg = sino_geom(:par, nb=888, na=984, orbit=180 , d=541/949, offset=0.25)\nsg=sg.down(down)\n\nell = ellipse_im_params(ig, :shepplogan)\nxtrue = ellipse_im(ig, ell, oversample = 4, hu_scale=1000)\nsino = ellipse_sino(sg, ell, oversample = 4)\n\nclim = (1 .+ (-1, 1) .* 0.05) .* 1000\np1 = jim(ig.x, ig.y, xtrue; clim)\np2 = jim(sg.r, sg.ad, sino, aspect_ratio=:none)\n\nplan=fbp2(sg, ig)\nprintln(\"plan complete\")\nresult,sino_filtered=fbp2(plan,sino)\nprintln(\"fbp complete\")\n\np3 = jim(ig.x, ig.y, result; clim)\np4 = jim(real(sino_filtered))\njim(p1,p2,p3,p4)\n\n=#\n", "meta": {"hexsha": "8c60684ed663b82aa2e25f84980f5a8221a3be64", "size": 1764, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "wip/fbp2_example.jl", "max_stars_repo_name": "SoniaMinseoKim/Sinograms.jl", "max_stars_repo_head_hexsha": "48fb4fca1a846f710b0ac8e0a61e5b44c91966ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-01-22T21:07:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T19:59:52.000Z", "max_issues_repo_path": "wip/fbp2_example.jl", "max_issues_repo_name": "SoniaMinseoKim/Sinograms.jl", "max_issues_repo_head_hexsha": "48fb4fca1a846f710b0ac8e0a61e5b44c91966ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-22T03:47:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-24T03:45:38.000Z", "max_forks_repo_path": "wip/fbp2_example.jl", "max_forks_repo_name": "SoniaMinseoKim/Sinograms.jl", "max_forks_repo_head_hexsha": "48fb4fca1a846f710b0ac8e0a61e5b44c91966ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-03-08T03:42:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T03:59:15.000Z", "avg_line_length": 24.5, "max_line_length": 88, "alphanum_fraction": 0.6763038549, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.8289388083214155, "lm_q1q2_score": 0.7521063198603379}}
{"text": "using Plots, LaTeXStrings, JLD, Statistics\nTotalTime=1000\nprobability=[0.25,0.5,0.75,0.95]\nfunction RandomWalk(TotalTime, probability)\n    arr=zeros((TotalTime,length(probability)))\n    for j in 1:length(probability)\n        for i in 1:TotalTime\n            if probability[j]>rand()\n                arr[i,j]=1\n            else\n                arr[i,j]=-1\n            end\n        end\n    end\n    return cumsum(arr,dims=1)\nend\n#TheMatrix=RandomWalk(TotalTime, probability)\nrun_num=10000\n# a list cinsisting of lists to the number of probabilities,\n#each list having lists of each position in each run number per time:\nRandomWalkers=[[[] for j in 1:TotalTime] for i in 1:length(probability)]\nfor n in 1:run_num\n    TheMatrix=RandomWalk(TotalTime, probability)\n    for col in 1:length(probability)\n        for i in 1:TotalTime\n            push!(RandomWalkers[col][i],TheMatrix[i,col])\n        end\n    end\nend\nSavedData_mean=[[] for i in 1:length(probability)]\nSavedData_var=[[] for i in 1:length(probability)]\nfor i in 1:length(RandomWalkers)\n    for j in RandomWalkers[i]\n        push!(SavedData_var[i],var(j))\n        push!(SavedData_mean[i],mean(j))\n    end\nend\nsave(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter5\\\\4.2\\\\chapter5_4.2_MeanAndStdData.jld\",\n \"MeanData\", SavedData_mean, \"VarData\", SavedData_var)\n #plots:\nload(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter5\\\\4.2\\\\chapter5_4.2_MeanAndStdData.jld\")\nscatter(dpi=400)\nfor i in 1:length(probability)\n    p=probability[i]\n    scatter!(1:TotalTime, SavedData_mean[i],label=L\"%$p\",markersize=1,markerstrokewidth=0, alpha=0.7)\nend\nscatter!(title=\"<x> per time for different probabilities\", xlabel=\"t\", ylabel=\"<x>\")\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter5\\\\4.2\\\\Figs\\\\MeanPlot.png\")\nscatter(dpi=400)\nfor i in 1:length(probability)\n    p=probability[i]\n    scatter!(1:TotalTime, SavedData_var[i],label=L\"%$p\",markersize=1,markerstrokewidth=0, alpha=0.7)\nend\nscatter!(title=\"Var[x] per time  for different probabilities\", xlabel=\"t\", ylabel=\"Var[x]\")\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter5\\\\4.2\\\\Figs\\\\VarPlot.png\")\n", "meta": {"hexsha": "8cd7a242a376261bc59662103fe8c10b360303b3", "size": 2194, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter5/4.2/4.2.jl", "max_stars_repo_name": "narges8k/computational_physics", "max_stars_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter5/4.2/4.2.jl", "max_issues_repo_name": "narges8k/computational_physics", "max_issues_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter5/4.2/4.2.jl", "max_forks_repo_name": "narges8k/computational_physics", "max_forks_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T09:55:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T09:55:00.000Z", "avg_line_length": 39.1785714286, "max_line_length": 115, "alphanum_fraction": 0.6987237922, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7521063134672589}}
{"text": "push!(LOAD_PATH, expanduser(\".\")) # Assumed to be ran from the repl folder.\n\n#include(\"RadioPropagation.jl\")\nusing RadioPropagation\nusing Plots\n\nfrequency_ghz = collect(1:1000);\n\n\nattenuation_db_km = RadioPropagation.atmospheric_attenuation_db_per_km.( frequency_ghz );\n\n\nplot1 = plot(\tfrequency_ghz, attenuation_db_km,\n\t \t\t\txlabel \t= \"Frequency [GHz]\",\n\t\t\t\tylabel \t= \"One-way loss [dB/km]\",\n\t\t\t\ttitle  \t= \"Atmospheric Attenuation.\",\n\t\t\t\t#ylims \t= (),\n\t\t\t\tlabel \t= \"Standard\",\n\t\t\t\tyaxis=:log,\n\t\t\t\tdpi=300\n\t\t\t\t)\n\n\nattenuation_db_km = RadioPropagation.atmospheric_attenuation_db_per_km.( frequency_ghz, 288.15, 0 );\n\nplot!( \tfrequency_ghz, attenuation_db_km,\n\t \tlabel = \"Dry air\",\n\t \tyaxis=:log,\n\t \t)\n\nsavefig(\"figures/attenuation_example\")\n", "meta": {"hexsha": "3acab0d6d7163ff496f9d2052b87976f9364c3ef", "size": 739, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/atmospheric_atten.jl", "max_stars_repo_name": "ErikBuer/RadioPropagation", "max_stars_repo_head_hexsha": "08730c3244e478cbb38ceb21068596a55ca294db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/atmospheric_atten.jl", "max_issues_repo_name": "ErikBuer/RadioPropagation", "max_issues_repo_head_hexsha": "08730c3244e478cbb38ceb21068596a55ca294db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/atmospheric_atten.jl", "max_forks_repo_name": "ErikBuer/RadioPropagation", "max_forks_repo_head_hexsha": "08730c3244e478cbb38ceb21068596a55ca294db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.09375, "max_line_length": 100, "alphanum_fraction": 0.7050067659, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7521063131464092}}
{"text": "using LinearAlgebraicRepresentation, ViewerGL, SparseArrays\nLar = LinearAlgebraicRepresentation; GL = ViewerGL\nusing QHull\n\nV,CV = Lar.rod()([4,1])\nch = QHull.chull(convert(Lar.Points,V'))\nFV = ch.simplices\nEV = Lar.simplexFacets(FV)\nGL.VIEW([ GL.GLGrid(V,EV) ]);\n\ncyl = Lar.Struct([ Lar.t(0,0,-1.5), (V,FV,EV) ])\ntris = Lar.Struct([ cyl,\n                    Lar.Struct([Lar.r(pi/2,0,0), cyl]),\n                    Lar.Struct([Lar.r(0,pi/2,0), cyl])\n                    ])\nV,FV,EV = Lar.struct2lar(tris)\nGL.VIEW([ GL.GLGrid(V,FV) ]);\n\n\nVV = [[k] for k=1:size(V,2)]\nGL.VIEW( GL.numbering(.2)((V,[VV,EV,FV]), GL.COLORS[4]) );\n\ncop_EV = convert(Lar.ChainOp, Lar.coboundary_0(EV::Lar.Cells));\ncop_FE = Lar.coboundary_1(V, FV::Lar.Cells, EV::Lar.Cells);\nW = convert(Lar.Points, V');\nV, copEV, copFE, copCF = Lar.Arrangement.spatial_arrangement( W, cop_EV, cop_FE)\n\nW = convert(Lar.Points, V')\nV,CVs,FVs,EVs = Lar.pols2tria(W, copEV, copFE, copCF)\n\nGL.VIEW(GL.GLExplode(V,FVs,1.5,1.5,1.5,99,1));\nGL.VIEW(GL.GLExplode(V,EVs,1.5,1.5,1.5,99,1));\nmeshes = GL.GLExplode(V,CVs[1:end],8,4,6,99,1);\nGL.VIEW( push!( meshes, GL.GLFrame) );\n", "meta": {"hexsha": "d383db107a4b6c778e0339f3206fc0ae04b0d391", "size": 1124, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/3d/threerods.jl", "max_stars_repo_name": "ramorimo/LinearAlgebraicRepresentation.jl", "max_stars_repo_head_hexsha": "53fb941a83f11967361518e5a981679b851e45ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/3d/threerods.jl", "max_issues_repo_name": "ramorimo/LinearAlgebraicRepresentation.jl", "max_issues_repo_head_hexsha": "53fb941a83f11967361518e5a981679b851e45ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/3d/threerods.jl", "max_forks_repo_name": "ramorimo/LinearAlgebraicRepresentation.jl", "max_forks_repo_head_hexsha": "53fb941a83f11967361518e5a981679b851e45ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1142857143, "max_line_length": 80, "alphanum_fraction": 0.6298932384, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7521063077158784}}
{"text": "# Random forests regression\n\n\n\"\"\"\nFinds the threshold to split `features` with that minimizes the\nmean-squared-error loss over `labels`.\nReturns (best_val, best_thresh), where `best_val` is -MSE\n\nVariable name changes from original code\n  labels   -> y\n  features -> x\n  nl       -> n_left\n  nr       -> n_right\n  su       -> sum_y\n  su2      -> sum_y2\n  s_l      -> sum_y_left\n  s2_l     -> sum_y2_left\n  s_r      -> sum_y_right\n  s2_r     -> sum_y2_right\n\n\"\"\"\nfunction _best_mse_loss{T<:Float64, U<:Real}(y::Vector{T}, x::DataArray{U, 1}, domain)\n    best_val = -Inf\n    best_thresh = 0.0\n    n = length(y)\n\n    sum_y_left = sum_y2_left = zero(T)            # scalar values of 0\n\n    sum_y = sum(y)                             # scalar sum of all y_i\n    sum_y2 = zero(T);                             # scalar value of 0\n\n    # get sum of squares\n    for i = 1:n\n        sum_y2 += y[i]^2\n    end\n\n    n_left = 0\n    i = 1\n\n    # Since`x` is sorted, below is an O(n) algorithm for finding the optimal\n    # threshold in `domain`. We iterate through the array and update sum_y_left\n    # and sum_y_right (= sum(y) - sum_y_left) as we go. - @cstjean\n    for thresh in domain\n\n        # this loop checks which side of the split this x_i is on\n        while i <= n && x[i] < thresh\n            sum_y_left += y[i]\n            sum_y2_left += y[i]^2\n            n_left += 1\n            i += 1\n        end\n        sum_y_right = sum_y - sum_y_left\n        sum_y2_right = sum_y2 - sum_y2_left\n        n_right = n - n_left\n\n        # This check is necessary I think because in theory all y could\n        # be the same, then either n_left or n_right would be 0. - @cstjean\n        if n_right > 0 && n_left > 0\n\n            # This isn't really squared-error loss. We're computing the sum of variance\n            # in the daughter nodes times the N for that daughter node. This last point\n            # is why the two paranthetical terms here look a bit diffent than mere variance.\n            # We have canceled a constant term N for each term.\n            loss = (sum_y2_left - sum_y_left^2/n_left) + (sum_y2_right - sum_y_right^2/n_right)\n\n            # update best value and threshold\n            if -loss > best_val\n                best_val = -loss\n                best_thresh = thresh\n            end\n        end\n    end\n    return best_val, best_thresh\nend\n\n\n\"\"\"\nThis function returns a tuple with the column index and the threshold\nvalue of the predictor in the matrix X that minimizes MSE. The function\nassumes complete data in both y and X.\n\nVariable name changes from original code\n  labels     -> y\n  features   -> x\n  nr         -> n\n  nf         -> p\n  i          -> j\n  features_i -> x_j\n  labels_i   -> y_ord\n  domain_i   -> domain_j\n  inds       -> col_indcs\n\n\"\"\"\n\n\n\n\nfunction _split_mse_df{T<:Float64}(y::Vector{T}, X::DataFrame, mtry::Int)\n    n, p = size(X)\n    best = (0, 0.0)\n    best_val = -Inf\n    if mtry > 0\n        r = randperm(p)\n        col_indcs = r[1:mtry]\n    else\n        col_indcs = collect(1:p)\n    end\n    for j in col_indcs\n        keep_row = !isna(X[:, j])\n        \n        # x_obs = convert(Vector, X[keep_row, j])\n\n        if !any(keep_row)\n            continue\n        end\n\n        # y_obs = y[keep_row]\n        # ord::Array{Int64, 1} = sortperm(x_obs)\n        # x_j = convert(Array{typeof(x_obs[1])}, x_obs[ord])\n        # y_ord = y_obs[ord]\n\n        x_j, y_ord = prepare_xy_obs(X[keep_row, j], y[keep_row])\n\n        if n > 100\n            if VERSION >= v\"0.4.0-dev\"\n                domain_j = quantile(x_j, linspace(0.01, 0.99, 99); sorted=true)\n            else  # sorted=true isn't supported on StatsBase's Julia 0.3 version\n                domain_j = quantile(x_j, linspace(0.01, 0.99, 99))\n            end\n        else\n            domain_j = x_j\n        end\n        value, thresh = _best_mse_loss(y_ord, x_j, domain_j)\n        if value > best_val\n            best_val = value\n            best = (j, thresh)\n        end\n    end\n    return best\nend\n\nfunction prepare_xy_obs{T}(x_obs::DataArray{T, 1}, y_obs)\n    ord = sortperm(x_obs)\n    x_j::DataArray{T, 1} = x_obs[ord]\n    y_ord = y_obs[ord]\n    return (x_j, y_ord)\nend \n\n\nfunction find_na_cols(dat)\n    cols_with_na = Array{Int, 1}(0)\n\n    for j in 1:ncol(dat)\n        if sum(isna(dat[:, j])) ≠ 0\n            push!(cols_with_na, j)\n        end\n    end\n    return cols_with_na\nend\n\n\n# function find_surrogates{T::BitArray}(left_node::T, y::Vector, X::Matrix, mtry::Int)\n\n\n\nfunction build_stump{T <: Float64, U<:Real}(y::Vector{T}, X::Matrix{U})\n    S = _split_mse(y, X, 0)\n\n    if S == NO_BEST\n        return Leaf(mean(y), y)\n    end\n\n    col_idx, thresh = S\n    split = X[:, col_idx] .< thresh\n\n    return Node(col_idx,\n                thresh,\n                Leaf(mean(y[split]), y[split]),\n                Leaf(mean(y[!split]), y[!split]))\nend\n\n\n\n\n\n\nfunction build_tree_df{T <: Float64}(y::Vector{T}, X::DataFrame, maxlabels = 5, mtry = 0, maxdepth = -1, n_surrogates = 5)\n    n, p = size(X)\n    if mtry == 0\n        mtry = p \n    end \n    if maxdepth < -1\n        error(\"Unexpected value for maxdepth: $(maxdepth) (expected: maxdepth >= 0, or maxdepth = -1 for infinite depth)\")\n    end\n    if length(y) <= maxlabels || maxdepth == 0          # stopping rules\n        return Leaf(mean(y), y)\n    end\n\n    S = _split_mse_df(y, X, mtry)                       # get [complete data] optimal split point\n\n    if S == NO_BEST\n        return Leaf(mean(y), y)\n    end\n\n    col_idx, thresh = S\n\n    if n_surrogates ≠ 0\n        cols_with_na = find_na_cols(X)                  # needed for all recursive steps since rows of X change\n        surrogate_vars = Vector{Tuple{Int, Real}}(n_surrogates)\n    end\n\n    # if col_idx in cols_with_na\n    if col_idx in 1:p                             # find surrogates even when no missing data\n        na_rows = isna(X[:, col_idx])\n        split_with_na = Array{Any, 1}(n)                # vector of Bools with some NA values\n\n        for i = 1:n\n            split_with_na[i] = isna(X[i, col_idx]) ? NA : X[i, col_idx] < thresh\n        end\n        row_indcs = collect(1:n)[!na_rows]\n        col_indcs = deleteat!(collect(1:p), col_idx)\n\n        # Here we need a function that splits so as to optimize agreement\n        # with the `split_with_na` result for each observed `row_indcs`.\n        surrogate_vars = surrogate_splits(split_with_na, X, row_indcs, col_indcs, 5)\n        split = apply_surrogates(split_with_na, X, surrogate_vars)\n    else\n        split = X[:, col_idx] .< thresh\n    end\n\n    return Node(col_idx,\n                thresh,\n                surrogate_vars,\n                build_tree_df(y[split], X[split,:], maxlabels, mtry, max(maxdepth-1, -1)),\n                build_tree_df(y[!split], X[!split,:], maxlabels, mtry, max(maxdepth-1, -1)))\nend\n\n\nfunction build_forest_df{T <: Real}(y::Vector{T}, X::DataFrame, mtry, ntrees, maxlabels = 5, maxdepth = -1; nthreads = 1, n_surrogates = 5, oob_measure = \"rsq\")\n\n    n = length(y)\n    tree_arr = Array{Node, 1}(ntrees)\n\n    if nthreads ≥ 2\n        yhat_mat = fill(-Inf, (n, ntrees))              # use to compute oob-score\n        mse_inc_dicts = Array{Dict{Int, Float64}, 1}(ntrees)\n        \n        @threads for t in 1:ntrees\n            inds = sample(1:n, n)\n            tree_arr[t] = build_tree_df(y[inds], X[inds, :], maxlabels, mtry, maxdepth, n_surrogates)\n            \n            # get OOB indices to calculate OOB score\n            oob_indcs = setdiff(collect(1:n), inds)\n            yhat, mse_inc = apply_tree(tree_arr[t], X[oob_indcs, :], y[oob_indcs])\n            \n            yhat_mat[oob_indcs, t] = yhat\n            mse_inc_dicts[t] = mse_inc              # dict with MSE increases for OOB permutation importance\n        end\n\n        oob_score = par_oob_score(yhat_mat, y, oob_measure)\n        mse_inc_dict = par_mse_inc(mse_inc_dicts)\n    else\n        yhat_mat = zeros(n, 2)                      # col 1 is numerator, col 2 is denominator\n        yhat_mat[:, 1] = fill(-Inf, n)\n        mse_inc_dict = Dict{Int, Float64}()\n        \n        for t in 1:ntrees\n            inds = sample(1:n, n)\n            tree_arr[t] = build_tree_df(y[inds], X[inds, :], maxlabels, mtry, maxdepth, n_surrogates)\n\n            # get OOB indices to calculate OOB score\n            oob_indcs = setdiff(collect(1:n), inds)\n            yhat, mse_inc = apply_tree(tree_arr[t], X[oob_indcs, :], y[oob_indcs])\n            \n            if !all(isfinite(yhat_mat[oob_indcs, 1]))\n                for idx in oob_indcs\n                    if !isfinite(yhat_mat[idx, 1])\n                        yhat_mat[oob_indcs, 1] = 0.0 \n                    end \n                end \n            end            \n\n            yhat_mat[oob_indcs, 1] += yhat \n            yhat_mat[oob_indcs, 2] += 1 \n            update_mse_inc!(mse_inc_dict, mse_inc)\n        end\n\n        if all(isfinite(yhat_mat[:, 1]))\n            \n            if oob_measure == \"rsq\"\n                oob_score = rsq(y, yhat_mat[:, 1] ./ yhat_mat[:, 2])\n            elseif oob_measure == \"mse\"\n                oob_score = mean_squared_error(y, yhat_mat[:, 1] ./ yhat_mat[:, 2])\n            end \n        else \n            warn(\"Not enough trees built to compute OOB score. Some rows were never out-of-bag\")\n            return nothing\n        end  \n    end\n    return (Ensemble(tree_arr), oob_score, mse_inc_dict)\nend\n\n\n\nfunction build_forest_df_novarimp{T <: Real}(y::Vector{T}, X::DataFrame, mtry, ntrees, maxlabels = 5, maxdepth = -1; nthreads = 1, n_surrogates = 5, oob_measure = \"rsq\")\n\n    n = length(y)\n    tree_arr = Array{Node, 1}(ntrees)\n\n    if nthreads ≥ 2\n        yhat_mat = fill(-Inf, (n, ntrees))       # use to compute oob-score\n        \n        @threads for t in 1:ntrees\n            inds = sample(1:n, n)\n            tree_arr[t] = build_tree_df(y[inds], X[inds, :], maxlabels, mtry, maxdepth, n_surrogates)\n            \n            # get OOB indices to calculate OOB score\n            oob_indcs = setdiff(collect(1:n), inds)\n            yhat = apply_tree(tree_arr[t], X[oob_indcs, :])\n\n            yhat_mat[oob_indcs, t] = yhat\n        end\n        oob_score = par_oob_score(yhat_mat, y, oob_measure)\n    else\n        yhat_mat = zeros(n, 2)                  # col 1 is numerator, col 2 is denominator\n        yhat_mat[:, 1] = fill(-Inf, n)\n        \n        for t in 1:ntrees\n            inds = sample(1:n, n)\n            tree_arr[t] = build_tree_df(y[inds], X[inds, :], maxlabels, mtry, maxdepth, n_surrogates)\n\n            # get OOB indices to calculate OOB score\n            oob_indcs = setdiff(collect(1:n), inds)\n            yhat = apply_tree(tree_arr[t], X[oob_indcs, :])\n            \n            if !all(isfinite(yhat_mat[oob_indcs, 1]))\n                for idx in oob_indcs\n                    if !isfinite(yhat_mat[idx, 1])\n                        yhat_mat[oob_indcs, 1] = 0.0 \n                    end \n                end \n            end            \n\n            yhat_mat[oob_indcs, 1] += yhat \n            yhat_mat[oob_indcs, 2] += 1 \n        end\n\n        if all(isfinite(yhat_mat[:, 1]))\n            \n            if oob_measure == \"rsq\"\n                oob_score = rsq(y, yhat_mat[:, 1] ./ yhat_mat[:, 2])\n            elseif oob_measure == \"mse\"\n                oob_score = mean_squared_error(y, yhat_mat[:, 1] ./ yhat_mat[:, 2])\n            end \n        else \n            warn(\"Not enough trees built to compute OOB score. Some rows were never out-of-bag\")\n            return nothing\n        end  \n    end\n    return (Ensemble(tree_arr), oob_score)\nend\n\n# This function is a helper used for getting oob-score for \n# parallel version of random forest regression. The parallel case \n# needs to be treated a bit differently to avoid threads overwriting \n# each other. NOTE: There might be a more elegant solution. \nfunction par_oob_score(yhat_mat, y, measure = \"rsq\")\n    n, ntrees = size(yhat_mat)\n    yhat = fill(-Inf, n)\n    num_preds = zeros(Int, n)       # this will be our denomiator \n    \n    for t = 1:ntrees\n        for i = 1:n \n            if isfinite(yhat_mat[i, t])\n                if !isfinite(yhat[i])\n                    yhat[i] = 0.0\n                end \n                yhat[i] += yhat_mat[i, t]\n                num_preds[i] += 1\n            end \n        end \n    end \n    if all(isfinite(yhat))\n        yhat ./= num_preds \n    else \n        warn(\"Not enough trees built to compute OOB score. Some rows never out-of-bag\")\n        return nothing\n    end \n    if measure == \"rsq\"\n        oob_score = rsq(y, yhat) \n    elseif measure == \"mse\"\n        oob_score = mean_squared_error(y, yhat) \n    end \n    return oob_score \nend \n\n\nfunction update_mse_inc!(aggregate_dict, tree_dict)\n    for k in keys(tree_dict)\n        aggregate_dict[k] = get(aggregate_dict, k, 0.0) + tree_dict[k]\n    end \nend \n\n\nfunction par_mse_inc(mse_inc_dicts)\n    out = Dict{Int, Float64}()\n    ntrees = length(mse_inc_dicts)\n    for i = 1:ntrees \n        update_mse_inc!(out, mse_inc_dicts[i])\n    end \n    return out \nend \n\n", "meta": {"hexsha": "74644ff42d9a17e3f90faf2295e2a457773ccdf8", "size": 12957, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/random_forest_regression.jl", "max_stars_repo_name": "paulstey/random_forests", "max_stars_repo_head_hexsha": "a319f3230d1445a43a4e7cbfab1c21ebcca52516", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/random_forest_regression.jl", "max_issues_repo_name": "paulstey/random_forests", "max_issues_repo_head_hexsha": "a319f3230d1445a43a4e7cbfab1c21ebcca52516", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-07-24T13:58:35.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-03T12:20:55.000Z", "max_forks_repo_path": "src/random_forest_regression.jl", "max_forks_repo_name": "paulstey/random_forests", "max_forks_repo_head_hexsha": "a319f3230d1445a43a4e7cbfab1c21ebcca52516", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2971014493, "max_line_length": 169, "alphanum_fraction": 0.555221116, "num_tokens": 3730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7521063051570521}}
{"text": "#=\n\n  Euler #28 in Julia.\n\n  Problem 28:\n  \"\"\"\n  Starting with the number 1 and moving to the right in a clockwise\n  direction a 5 by 5 spiral is formed as follows:\n\n     21 22 23 24 25\n     20  7  8  9 10\n     19  6  1  2 11\n     18  5  4  3 12\n     17 16 15 14 13\n\n  It can be verified that the sum of the numbers on the diagonals is 101.\n\n  What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?\n  \"\"\"\n\n  This Julia program was created by Hakan Kjellerstrand, hakank@gmail.com\n  See also my Julia page: http://www.hakank.org/julia/\n\n=#\n\ninclude(\"Euler.jl\")\n\n#\nfunction euler28a()\n    s = 1\n    n = 3\n    while n <= 1001\n        s += 4*n^2 - 6*n+6\n        n+=2\n    end\n    return s\nend\n\nrun_euler(euler28a)\n", "meta": {"hexsha": "1caebecc829922adb541ebe11ddfe579cc20a6f0", "size": 751, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/euler28.jl", "max_stars_repo_name": "Wikunia/hakank", "max_stars_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/euler28.jl", "max_issues_repo_name": "Wikunia/hakank", "max_issues_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/euler28.jl", "max_forks_repo_name": "Wikunia/hakank", "max_forks_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 18.775, "max_line_length": 98, "alphanum_fraction": 0.6218375499, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7520903455190531}}
{"text": "# ### m10.3t.jl\n\nusing Pkg, DrWatson\n\n@quickactivate \"StatisticalRethinkingTuring\"\nusing Turing\nusing StatisticalRethinking\nTuring.setprogress!(false)\n\ndelim=';'\ndf = CSV.read(sr_datadir(\"chimpanzees.csv\"), DataFrame; delim);\n\n# pulled_left, condition, prosoc_left\n@model function ppl10_3(y, x₁, x₂)\n    α ~ Normal(0, 10)\n    βp ~ Normal(0, 10)\n    βpC ~ Normal(0, 10)\n\n    logits = α .+ (βp .+ βpC * x₁) .* x₂\n    y .~ BinomialLogit.(1, logits)\nend;\n\nm10_3t = ppl10_3(df.pulled_left, df.condition, df.prosoc_left)\nnchains = 4; sampler = NUTS(0.65); nsamples=2000\nchns10_3t = mapreduce(c -> sample(m10_3t, sampler, nsamples), chainscat, 1:nchains)\n\n# Rethinking result\n\nm_10_03t_result = \"\n      Mean StdDev lower 0.89 upper 0.89 n_eff Rhat\n a    0.05   0.13      -0.15       0.25  3284    1\n bp   0.62   0.22       0.28       0.98  3032    1\n bpC -0.11   0.26      -0.53       0.29  3184    1\n\";\n\n# End of m10.03t.jl\n", "meta": {"hexsha": "896e87e91930cf54187f394c0be7922d5f97e073", "size": 918, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/10/m10.03t.jl", "max_stars_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_stars_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2020-10-01T23:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T11:48:45.000Z", "max_issues_repo_path": "models/10/m10.03t.jl", "max_issues_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_issues_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-11-24T21:59:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T12:34:49.000Z", "max_forks_repo_path": "models/10/m10.03t.jl", "max_forks_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_forks_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-11-30T18:25:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T06:59:27.000Z", "avg_line_length": 24.8108108108, "max_line_length": 83, "alphanum_fraction": 0.6383442266, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7520903397934313}}
{"text": "#\n#   SVD decomposition of a matrix truncated to a rank\n#\nusing Manopt, Manifolds\nimport LinearAlgebra: norm, svd, Diagonal\n\n\"\"\"\n    truncated_svd(A, p)\n\nreturn a singular value decomposition of a real valued matrix A truncated to\nrank p.\n\n# Input\n* `A` – a real-valued matrix A of size mxn\n* `p` – an integer p in min { m, n }\n\n# Output\n* `U` – an orthonormal matrix of size mxp\n* `V` – an orthonormal matrix of size nxp\n* `S` – a diagonal matrix of size pxp with nonnegative and decreasing diagonal\n        entries\n\"\"\"\nfunction truncated_svd(A::Array{Float64,2} = randn(42, 60), p::Int64 = 5)\n    (m, n) = size(A)\n\n    if p > min(m,n)\n        throw( ErrorException(\"The Rank p=$p must be smaller than the smallest dimension of A = $min(m, n).\") )\n    end\n\n    M = ProductManifold(Grassmann(m,p), Grassmann(n,p))\n\n    function cost(X::ProductRepr)\n        return cost([submanifold_components(X)...])\n    end\n    function cost(X::Array{Matrix{Float64},1})\n        return -0.5 * norm(transpose(X[1]) * A * X[2])^2\n    end\n\n    function egrad(X::Array{Matrix{Float64},1})\n        U = X[1]\n        V = X[2]\n        AV = A*V\n        AtU = transpose(A)*U\n        return [ -AV*(transpose(AV)*U), -AtU*(transpose(AtU)*V) ];\n    end\n\n    function rgrad(M::ProductManifold, X::ProductRepr)\n        eG = egrad([submanifold_components(M,X)...])\n        x = [submanifold_components(M,X)...]\n        return Manifolds.ProductRepr(project.(M.manifolds, x, eG)...)\n    end\n\n    function e2rHess(M::Grassmann, x, ξ, eGrad::Matrix{T},Hess::Matrix{T}) where T<:Union{U, Complex{U}} where U<:AbstractFloat\n        pxHess = project(M,x,Hess)\n        xtGrad = x'*eGrad\n        ξxtGrad = ξ*xtGrad\n        return pxHess - ξxtGrad\n    end\n\n    function eHess(X::Array{Matrix{Float64},1}, H::Array{Matrix{Float64},1})\n        U = X[1]\n        V = X[2]\n        Udot = H[1]\n        Vdot = H[2]\n        AV = A*V\n        AtU = transpose(A)*U\n        AVdot = A*Vdot\n        AtUdot = transpose(A)*Udot\n        return [ -(AVdot*transpose(AV)*U + AV*transpose(AVdot)*U + AV*transpose(AV)*Udot),\n                 -(AtUdot*transpose(AtU)*V + AtU*transpose(AtUdot)*V + AtU*transpose(AtU)*Vdot)\n            ]\n    end\n\n    function rhess(M::ProductManifold, X::ProductRepr, H::ProductRepr)\n        x = [submanifold_components(M,X)...]\n        h = [submanifold_components(M,H)...]\n        eG = egrad(x)\n        eH = eHess(x,h)\n        return Manifolds.ProductRepr(e2rHess.(M.manifolds, x, h, eG, eH)...)\n    end\n\n    x = random_point(M)\n    X = trust_regions(M, cost, rgrad, x, rhess;\n        Δ_bar=4*sqrt(2*p),\n        debug = [:Iteration, \" \", :Cost, \" | \", DebugEntry(:Δ), \"\\n\", 1, :Stop]\n    )\n\n    U = get_component(M,X,1)\n    V = get_component(M,X,2)\n\n    Spp = transpose(U)*A*V\n    SVD = svd(Spp)\n    U = U*SVD.U\n    S = SVD.S\n    V = V*SVD.V\n\n    return [U, S, V]\nend\n\nA=[1. 2. 3. 4.; 5. 6. 7. 8.; 9. 10. 11. 12.; 13. 14. 15. 16.]\n\ntruncated_svd(A,2)\n", "meta": {"hexsha": "f0d382895a10649127b0881ddf35e201fbf390de", "size": 2919, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Trust_Regions/truncated_svd.jl", "max_stars_repo_name": "matbesancon/Manopt.jl", "max_stars_repo_head_hexsha": "25671e4c56728b7ab3ce82321d063308095750da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Trust_Regions/truncated_svd.jl", "max_issues_repo_name": "matbesancon/Manopt.jl", "max_issues_repo_head_hexsha": "25671e4c56728b7ab3ce82321d063308095750da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Trust_Regions/truncated_svd.jl", "max_forks_repo_name": "matbesancon/Manopt.jl", "max_forks_repo_head_hexsha": "25671e4c56728b7ab3ce82321d063308095750da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3398058252, "max_line_length": 127, "alphanum_fraction": 0.5779376499, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7520903355916361}}
{"text": "\"\"\"\n    LogNormal\n\n* Parametrization\nparametrized in \\\\mu and \\\\sigma^2\n\n* Score\n\n* Fisher Information\n\n* `time_varying_params` map.\n\n* Default link\n\"\"\"\nLogNormal\n\nfunction score!(score_til::Matrix{T}, y::T, ::Type{LogNormal}, param::Matrix{T}, t::Int) where T\n    score_til[t, 1] = (log(y) - param[t, 1])/param[t, 2]\n    score_til[t, 2] = -(0.5/param[t, 2]) * (1 - ((log(y) - param[t, 1])^2)/param[t, 2])\n    return\nend\n\nfunction fisher_information!(aux::AuxiliaryLinAlg{T}, ::Type{LogNormal}, param::Matrix{T}, t::Int) where T\n    aux.fisher[1, 1] = 1/(param[t, 2])\n    aux.fisher[2, 2] = 1/(2*(param[t, 2]^2))\n    aux.fisher[2, 1] = 0\n    aux.fisher[1, 2] = 0\n    return\nend\n\nfunction log_likelihood(::Type{LogNormal}, y::Vector{T}, param::Matrix{T}, n::Int) where T\n    loglik = -0.5*log(2*pi)*n\n    for t in 1:n\n        loglik -= log(y[t] * sqrt(param[t, 2])) + 0.5*(log(y[t]) - param[t, 1])^2/param[t, 2]\n    end\n    return -loglik\nend\n\n# Links\nfunction link!(param_tilde::Matrix{T}, ::Type{LogNormal}, param::Matrix{T}, t::Int) where T \n    param_tilde[t, 1] = link(IdentityLink, param[t, 1])\n    param_tilde[t, 2] = link(LogLink, param[t, 2], zero(T))\n    return\nend\nfunction unlink!(param::Matrix{T}, ::Type{LogNormal}, param_tilde::Matrix{T}, t::Int) where T \n    param[t, 1] = unlink(IdentityLink, param_tilde[t, 1])\n    param[t, 2] = unlink(LogLink, param_tilde[t, 2], zero(T))\n    return\nend\nfunction jacobian_link!(aux::AuxiliaryLinAlg{T}, ::Type{LogNormal}, param::Matrix{T}, t::Int) where T \n    aux.jac[1] = jacobian_link(IdentityLink, param[t, 1])\n    aux.jac[2] = jacobian_link(LogLink, param[t, 2], zero(T))\n    return\nend\n\n# utils \nfunction update_dist(::Type{LogNormal}, param::Matrix{T}, t::Int) where T\n    # lognormal here is parametrized as sigma^2\n    return LogNormal(param[t, 1], sqrt(param[t, 2]))\nend \n\nfunction params_sdm(d::LogNormal)\n    pars = Distributions.params(d)\n    return (pars[1], pars[2]^2)\nend\n\nfunction num_params(::Type{LogNormal})\n    return 2\nend", "meta": {"hexsha": "97a056b34b935a82bf1fc950d461289d6c424c72", "size": 1995, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distributions/lognormal.jl", "max_stars_repo_name": "marinadietze/ScoreDrivenModels.jl", "max_stars_repo_head_hexsha": "4ee85b8d606892535a7b0bf2aec1d976f44d796e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2020-02-05T04:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T18:46:03.000Z", "max_issues_repo_path": "src/distributions/lognormal.jl", "max_issues_repo_name": "marinadietze/ScoreDrivenModels.jl", "max_issues_repo_head_hexsha": "4ee85b8d606892535a7b0bf2aec1d976f44d796e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 109, "max_issues_repo_issues_event_min_datetime": "2019-11-26T12:34:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-27T20:16:55.000Z", "max_forks_repo_path": "src/distributions/lognormal.jl", "max_forks_repo_name": "marinadietze/ScoreDrivenModels.jl", "max_forks_repo_head_hexsha": "4ee85b8d606892535a7b0bf2aec1d976f44d796e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:11:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-04T20:05:21.000Z", "avg_line_length": 28.9130434783, "max_line_length": 106, "alphanum_fraction": 0.6355889724, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7520903342326867}}
{"text": "simulate_bm(t::Tree, k::Int; σ²::Float64=1.0, x₀::Float64=0.0) =\n    simulate_bm(t; σ²=fill(σ², k), x₀=fill(x₀, k))\n\n\"\"\"\n    simulate_bm(t::Tree, k::Int, σ::Vector{Float64} = ones(k), x₀::Vector{Float64} = zeros(k))\n\nSimulate the evolution of continuous traits under univariate Brownian motion on a phylogenetic tree.\n\nCreates a `SpeciesDataMatrix` with `k` independent traits, with `σ²` as the vector of diffusion coeffients of the traits (all 1.0 by default), and `x₀` as the vector of trait values at the root (all 0.0 by default).\n\"\"\"\nfunction simulate_bm(\n    t::Tree;\n    σ²::Union{Float64, Vector{Float64}} = 1.0,\n    x₀::Union{Float64, Vector{Float64}} = 0.0\n    )\n    ! t.rooted && @warn \"The tree is unrooted. The simulation was done using the origin node as the root.\"\n\n    if σ² isa Float64 && x₀ isa Float64\n        σ² = [σ²]\n        x₀ = [x₀]\n    elseif σ² isa Float64 && x₀ isa Vector{Float64}\n        σ² = fill(σ², length(x₀))\n    elseif σ² isa Vector{Float64} && x₀ isa Float64\n        x₀ = fill(x₀, length(σ²))\n    elseif length(σ²) ≠ length(x₀)\n        msg = \"the vectors `σ²` and `x₀` must both have `k` number of elements.\"\n        throw(ArgumentError(msg))\n    end\n\n    k = length(x₀)\n    σ = .√(σ²)\n\n    return _simulate_bm_species(t, k, σ, x₀)\nend\n\n\nfunction _simulate_bm_species(t::Tree, k::Int, σ::Vector{Float64}, x₀::Vector{Float64})::SpeciesDataMatrix{Float64}\n    x = SpeciesDataMatrix{Float64}(t.dir, k)\n    for p ∈ neighbours(t.origin)\n        _simulate_bm!(x, p, t.origin, k, σ, x₀)\n    end\n\n    return x\nend\n\nfunction _simulate_bm!(\n    x::SpeciesDataMatrix{Float64},\n    p::Node,\n    q::Node,\n    k::Int,\n    σ::Vector{Float64},\n    x₀::Vector{Float64}\n    )\n    xₚ = x₀ .+ σ .* √(brlength(q, p)) .* randn(k)\n    if p.species > 0 && p.species ∈ x.dir\n        x[p.species,:] = xₚ\n    end\n    for r in neighbours(p)\n        r == q && continue\n        _simulate_bm!(x, r, p, k, σ, xₚ)\n    end\nend", "meta": {"hexsha": "5bde8090a7b0864cd0b54955678547c12d03c049", "size": 1928, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BrownianModels/simulate.jl", "max_stars_repo_name": "eascarrunz/Phylodendron2.jl", "max_stars_repo_head_hexsha": "e4164a2b6209536fcca9706890e53fba130f5165", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BrownianModels/simulate.jl", "max_issues_repo_name": "eascarrunz/Phylodendron2.jl", "max_issues_repo_head_hexsha": "e4164a2b6209536fcca9706890e53fba130f5165", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-12-09T23:25:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-23T19:44:05.000Z", "max_forks_repo_path": "src/BrownianModels/simulate.jl", "max_forks_repo_name": "eascarrunz/Phylodendron2.jl", "max_forks_repo_head_hexsha": "e4164a2b6209536fcca9706890e53fba130f5165", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0967741935, "max_line_length": 215, "alphanum_fraction": 0.6187759336, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7520903263237286}}
{"text": "using Distributions\nusing QuadGK\n\nfunction kde_kth_neighbor_1d(xout::Vector{T}, xin::Vector{T}; k::Integer = 10, sigma::Real = 2.0) where T <: Real\n   issorted(xin) ? kde_kth_neighbor_1d_sorted(xout,xin,k=k,sigma=sigma)  :\n                   kde_kth_neighbor_1d_unsorted(xout,xin,k=k,sigma=sigma)  \nend\n\nfunction kde_kth_neighbor_1d_unsorted(xout::Vector{T}, xin::Vector{T}; k::Integer = 10, sigma::Real = 2) where T <: Real\n   @assert(length(xin)>=k+1)\n   @assert issorted(xout)\n   yout = similar(xout)\n   ilo = 1\n   ihi = k\n   perm = sortperm(xin)\n   #print(\"# ilo,ihi = \",ilo,\", \", ihi, \" length(xin)=\", length(xin), \" len(xout)=\",length(xout) )\n   #println( \" perm[ilo,ihi,ihi+1] = \", perm[ilo],\", \", perm[ihi], \", \", perm[ihi+1])\n   dlo = abs(xout[1]-xin[perm[ilo]])\n   dhi = abs(xin[perm[ihi]]-xout[1])\n   dstar = abs(xin[perm[ihi+1]]-xout[1])\n   for (i,x) in enumerate(xout)\n       while dstar<dlo && ihi<length(xin) \n          ilo += 1 \n          ihi += 1\n          dlo = abs(x-xin[perm[ilo]])\n          dhi = dstar\n          if ihi+1<=length(perm)\n            dstar = abs(xin[perm[ihi+1]]-x)\n          end\n       end \n       #width = (xin[perm[ihi]]-xin[perm[ilo]])*sigma/k\n       width = max(dlo,dhi)*sigma/k\n       distrib = Distributions.Normal(x,width)\n       yout[i] = sum(pdf(distrib,xin[perm[ilo:ihi]]))/k\n   end\n   return yout\nend\n\nfunction kde_kth_neighbor_1d_sorted(xout::Vector{T}, xin::Vector{T}; k::Integer = 10, sigma::Real = 2) where T <: Real\n   @assert(length(xin)>=k+1)\n   #@assert issorted(xin)\n   yout = similar(xout)\n   ilo = 1\n   ihi = k\n   dlo = abs(xout[1]-xin[ilo])\n   dhi = abs(xin[ihi]-xout[1])\n   dstar = abs(xin[ihi+1]-xout[1])\n   for (i,x) in enumerate(xout)\n       while dstar<dlo && ihi<length(xin) \n          ilo += 1 \n          ihi += 1\n          dlo = abs(x-xin[ilo])\n          dhi = dstar\n          if ihi+1<=length(perm)\n             dstar = abs(xin[ihi+1]-x)\n          end\n       end \n       #width = (xin[ihi]-xin[ilo])*sigma/k\n       width = max(dlo,dhi)*sigma/k\n       distrib = Distributions.Normal(x,width)\n       yout[i] = sum(pdf(distrib,xin[ilo:ihi]))/k\n   end\n   return yout\nend\n\nfunction kl_integral_arg(q::T, p::T; epsilon::T = 1e-10) where T <: Real\n  if q > epsilon\n     return p*log(p/q)\n  else\n     return p\n  end\nend\n\nfunction hellinger_integral_arg(p::T, q::T) where T <: Real\n  sqrt(p*q)\nend\n\n\nfunction calc_kl_distance_ab(x1::Vector{T}, x2::Vector{T}, a::T, b::T; n::Integer = 100, k::Integer = max(min((length(x1) - 1), (length(x2) - 1), 20), 1)) where T <: Real\n  @assert b>a\n  @assert n>=2\n  if(length(x1)<3 || length(x2)<3) return 0.0  end\n  xgrid = collect(linspace(a,b,n+1))\n  y1 = kde_kth_neighbor_1d(xgrid,x1,k=k)\n  y2 = kde_kth_neighbor_1d(xgrid,x2,k=k)\n  integral = 0.5*(kl_integral_arg(y1[1],y2[1])+kl_integral_arg(y1[end],y2[end]))\n  integral += sum([kl_integral_arg(y1[i],y2[i]) for i in 2:(length(y1)-1) ])\n  integral /= n\nend\n\nfunction calc_kl_distance(x1::Vector{T}, x2::Vector{T}; n::Integer = 100, k::Integer = max(min((length(x1) - 1), (length(x2) - 1), 20), 1)) where T <: Real\n  @assert b>a\n  @assert n>=2\n  n1 = length(x1)\n  n2 = length(x2)\n  xmin = minimum(x1,x2)\n  xmax = maximum(x1,x2)\n  padding = k*(xmax-xmin)/(n1+n2)\n  calc_kl_distance_ab(x1,x2,xmin,xmax,n=n,k=k)\nend\n\n\n\n", "meta": {"hexsha": "86d725150e8342e494a3253811d035ee08c175cf", "size": 3265, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/clusters/kde.jl", "max_stars_repo_name": "keirtheashby/ExoplanetsSysSim.jl-1", "max_stars_repo_head_hexsha": "b039911a7bd6ab8df40766baed526d65c6d07652", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-07T13:47:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-07T13:47:40.000Z", "max_issues_repo_path": "examples/clusters/kde.jl", "max_issues_repo_name": "keirtheashby/ExoplanetsSysSim.jl-1", "max_issues_repo_head_hexsha": "b039911a7bd6ab8df40766baed526d65c6d07652", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-02-23T15:47:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-07T19:08:29.000Z", "max_forks_repo_path": "examples/clusters/kde.jl", "max_forks_repo_name": "keirtheashby/ExoplanetsSysSim.jl-1", "max_forks_repo_head_hexsha": "b039911a7bd6ab8df40766baed526d65c6d07652", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-10-12T00:03:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-21T22:43:31.000Z", "avg_line_length": 31.3942307692, "max_line_length": 170, "alphanum_fraction": 0.5905053599, "num_tokens": 1213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7520891927710829}}
{"text": "struct ImbensKalyanaraman <: BandwidthSelector end\n\n_string(::ImbensKalyanaraman) = \"Imbens Kalyanaraman bandwidth\"\n\nfunction kernel_constant(::ImbensKalyanaraman, kernel)\n    kernel = EquivalentKernel(kernel)\n    νs = [kernel_moment(kernel, Val(j)) for j = 0:3]\n    πs = [squared_kernel_moment(kernel, Val(j)) for j = 0:3]\n    C1 = 1 / 4 * abs2((abs2(νs[3]) - νs[2] * νs[4]) / (νs[3] * νs[1] - abs2(νs[2])))\n    C2_num = abs2(νs[3]) * πs[1] - 2 * νs[2] * νs[3] * πs[2] + abs2(νs[2]) * πs[3]\n    C2_denom = abs2(νs[3] * νs[1] - abs2(νs[2]))\n    C2 = C2_num / C2_denom\n    (C2 / (4 * C1))^(1 / 5)\nend\n\n\nfunction bandwidth(ik::ImbensKalyanaraman, kernel::SupportedKernels, ZsR::RDData)\n    ZsR_untreated = ZsR[Untreated()]\n    ZsR_treated = ZsR[Treated()]\n\n    cutoff = ZsR.cutoff\n\n    N = nobs(ZsR)\n\n    N_untreated = nobs(ZsR_untreated)\n    N_treated = nobs(ZsR_treated)\n\n    # Step 1: Density and conditional variance at 0\n    h₁ = 1.84 * Statistics.std(ZsR.Zs) * N^(-1 / 5)\n\n    interval_h₁ = Interval{:closed,:closed}(cutoff-h₁, cutoff+h₁)\n\n    ZsR_untreated_h₁ = ZsR_untreated[interval_h₁]\n    ZsR_treated_h₁ = ZsR_treated[interval_h₁]\n\n    N_h₁_untreated = nobs(ZsR_untreated_h₁)\n    N_h₁_treated = nobs(ZsR_treated_h₁)\n\n    Ȳ_h₁_untreated = mean(ZsR_untreated_h₁.Ys)\n    sd_Y_h₁_untreated = Statistics.std(ZsR_untreated_h₁.Ys)\n    Ȳ_h₁_treated = mean(ZsR_treated_h₁.Ys)\n    sd_Y_h₁_treated = Statistics.std(ZsR_treated_h₁.Ys)\n\n    f̂₀ = (N_h₁_untreated + N_h₁_treated) / 2 / N / h₁\n\n    # Step 2: Estimation of second derivatives\n    global_cubic_lm = lm(@formula(Ys ~ 1 + (ZsC >= 0) + ZsC + ZsC^2 + ZsC^3), ZsR)\n\n    m̂₀_triple_prime = 6 * coef(global_cubic_lm)[5]\n\n    h₂_untreated = 3.56 * (sd_Y_h₁_untreated^2 / f̂₀ / m̂₀_triple_prime^2)^(1 / 7) * N_untreated^(-1 / 7)\n    h₂_treated =\n        3.56 * (sd_Y_h₁_treated^2 / f̂₀ / m̂₀_triple_prime^2)^(1 / 7) * N_treated^(-1 / 7)\n\n\n    ZsR_untreated_h₂ = ZsR_untreated[Interval{:closed,:closed}(cutoff-h₂_untreated, cutoff+h₂_untreated)]\n    ZsR_treated_h₂ = ZsR_treated[Interval{:closed,:closed}(cutoff-h₂_treated, cutoff+h₂_treated)]\n\n    N_h₂_untreated = nobs(ZsR_untreated_h₂)\n    N_h₂_treated = nobs(ZsR_treated_h₂)\n\n\n    quadratic_fit_untreated = lm(@formula(Ys ~ 1 + ZsC + ZsC^2), ZsR_untreated_h₂)\n    m̂₀_double_prime_untreated = 2 * last(coef(quadratic_fit_untreated))\n\n    quadratic_fit_treated = lm(@formula(Ys~ 1 + ZsC + ZsC^2), ZsR_treated_h₂)\n    m̂₀_double_prime_treated  = 2 * last(coef(quadratic_fit_treated ))\n\n    # Step 3: Calculation of regularization terms\n\n    r̂_untreated = 2160 * sd_Y_h₁_untreated^2 / N_h₂_untreated/ h₂_untreated^4\n    r̂_treated = 2160 * sd_Y_h₁_treated^2 / N_h₂_treated / h₂_treated^4\n\n    Ckernel = kernel_constant(ik, kernel)# 3.4375\n\n    regularized_squared_diff =\n        abs2(m̂₀_double_prime_treated - m̂₀_double_prime_untreated) + r̂_untreated + r̂_treated\n    ĥ_IK =\n        Ckernel *\n        ((sd_Y_h₁_untreated^2 + sd_Y_h₁_treated^2) / f̂₀ / regularized_squared_diff)^(1 / 5) *\n        N^(-1 / 5)\n    ĥ_IK\nend\n", "meta": {"hexsha": "59c6a10a4e17a323701d799bc03cbcf6671d5442", "size": 3028, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/imbens_kalyanaraman.jl", "max_stars_repo_name": "nignatiadis/RegressionDiscontinuity.jl", "max_stars_repo_head_hexsha": "d14db06d6084ef54cf8a34052a2bb6340b5f8f20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-10-01T23:07:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-21T23:09:24.000Z", "max_issues_repo_path": "src/imbens_kalyanaraman.jl", "max_issues_repo_name": "arubhardwaj/RegressionDiscontinuity.jl", "max_issues_repo_head_hexsha": "4f849d783bdc6489bd23efe4459ac3135a61ea79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-10-01T19:51:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-25T14:55:04.000Z", "max_forks_repo_path": "src/imbens_kalyanaraman.jl", "max_forks_repo_name": "arubhardwaj/RegressionDiscontinuity.jl", "max_forks_repo_head_hexsha": "4f849d783bdc6489bd23efe4459ac3135a61ea79", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-10-15T18:52:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T23:09:15.000Z", "avg_line_length": 36.0476190476, "max_line_length": 105, "alphanum_fraction": 0.6753632761, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7520891919284824}}
{"text": "\nusing Jecco\nusing LinearAlgebra\nusing SparseArrays\nusing Plots\n\nsource(x,y) = exp(-x^2 - y^2) * (-4 + 3 * (x^2 + y^2) + 4 * x^2 * y^2)\n\n# returns axx Dxx + ayy Dyy + axy Dxy + bx Dx + by Dy + cc. note that this\n# function overwrites the input matrices to save memory\nfunction build_operator(Dxx::SparseMatrixCSC, Dyy::SparseMatrixCSC, Dxy::SparseMatrixCSC,\n                        Dx::SparseMatrixCSC, Dy::SparseMatrixCSC,\n                        axx::Diagonal, ayy::Diagonal, axy::Diagonal,\n                        bx::Diagonal, by::Diagonal, cc::Diagonal)\n    Dxx_ = similar(Dxx)\n    Dyy_ = similar(Dyy)\n    Dxy_ = similar(Dxy)\n    Dx_  = similar(Dx)\n    Dy_  = similar(Dy)\n\n    mul!(Dxx_, axx, Dxx)\n    mul!(Dyy_, ayy, Dyy)\n    mul!(Dxy_, axy, Dxy)\n    mul!(Dx_, bx, Dx)\n    mul!(Dy_, by, Dy)\n\n    Dxx_ + Dyy_ + Dxy_ + Dx_ + Dy_ + cc\nend\n\n#=\nuse the Kronecker product (kron) to build the 2-dimensional derivation matrices\nfrom the 1-dimensional ones. see for instance:\n\n  https://en.wikipedia.org/wiki/Kronecker_product\n\n  https://arxiv.org/pdf/1801.01483.pdf (section 5)\n=#\nfunction deriv_operators(hx, hy, Nx::Int, Ny::Int, ord::Int)\n    Dx_op  = CenteredDiff{1}(1, ord, hx, Nx)\n    Dxx_op = CenteredDiff{1}(2, ord, hx, Nx)\n\n    Dy_op  = CenteredDiff{2}(1, ord, hy, Ny)\n    Dyy_op = CenteredDiff{2}(2, ord, hy, Ny)\n\n    Dx  = kron(I(Ny), SparseMatrixCSC(Dx_op))\n    Dxx = kron(I(Ny), SparseMatrixCSC(Dxx_op))\n    Dy  = kron(SparseMatrixCSC(Dy_op), I(Nx))\n    Dyy = kron(SparseMatrixCSC(Dyy_op), I(Nx))\n\n    Dx, Dy, Dxx, Dyy, Dx * Dy\nend\n\n\nx_min    = -5.0\nx_max    =  5.0\nx_nodes  =  128\ny_min    = -5.0\ny_max    =  5.0\ny_nodes  =  64\n\nord = 4\n\nxcoord  = Cartesian{1}(\"x\", x_min, x_max, x_nodes, endpoint=false)\nycoord  = Cartesian{2}(\"y\", y_min, y_max, y_nodes, endpoint=false)\n\nhx = Jecco.delta(xcoord)\nhy = Jecco.delta(ycoord)\n\nNx = xcoord.nodes\nNy = ycoord.nodes\n\nf_exact = [exp(-xcoord[i]^2 - ycoord[j]^2) for i in 1:Nx, j in 1:Ny]\n\n\nDx, Dy, Dxx, Dyy, Dxy = deriv_operators(hx, hy, Nx, Ny, ord)\n\nf0    = zeros(Nx,Ny)\nind2D = LinearIndices(f0)\n\nM = Nx * Ny\n\nb_vec = zeros(M)\n\naxx     = ones(M)\nayy     = ones(M)\naxy     = zeros(M)\nbx      = zeros(M)\nby      = zeros(M)\ncc      = zeros(M)\n\nfor j in 1:Ny, i in 1:Nx\n    idx = ind2D[i,j]\n\n    xi  = xcoord[i]\n    yi  = ycoord[j]\n\n    axy[idx] = xi * yi\n    bx[idx]  = xi\n    by[idx]  = yi\n    cc[idx]  = xi^2 + yi^2\n\n    b_vec[idx] = source(xi, yi)\nend\n\n# build operator A = Dxx + Dyy + x y Dxy + x Dx + y Dy + (x^2 + y^2)\nA_mat = build_operator(Dxx, Dyy, Dxy, Dx, Dy, Diagonal(axx), Diagonal(ayy),\n                       Diagonal(axy), Diagonal(bx), Diagonal(by), Diagonal(cc))\n\nA_fact = factorize(A_mat)\nsol    = A_fact \\ b_vec\n\n@inbounds for idx in eachindex(f0)\n    f0[idx] = sol[idx]\nend\n\nj_slice = div(Ny,2) + 1\nx = xcoord[:]\n\nplot(x, f_exact[:,j_slice])\nscatter!(x, f0[:,j_slice])\n", "meta": {"hexsha": "98ca50f466949987d80d979eb5cbbc2304ec522f", "size": 2844, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example_2D_PDE.jl", "max_stars_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_stars_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-09-08T23:37:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:19:01.000Z", "max_issues_repo_path": "examples/example_2D_PDE.jl", "max_issues_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_issues_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-02T17:57:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-02T17:57:23.000Z", "max_forks_repo_path": "examples/example_2D_PDE.jl", "max_forks_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_forks_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-02-26T15:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T08:46:55.000Z", "avg_line_length": 23.5041322314, "max_line_length": 89, "alphanum_fraction": 0.5991561181, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7520891885673849}}
{"text": "\nusing DiffEqBayes\nusing Distributions\nusing OrdinaryDiffEq, RecursiveArrayTools, ParameterizedFunctions\nusing Plots\n\n\ngr(fmt=:png)\n\n\ng1 = @ode_def LorenzExample begin\n  dx = σ*(y-x)\n  dy = x*(ρ-z) - y\n  dz = x*y - β*z\nend σ ρ β\n\n\nr0 = [1.0; 0.0; 0.0]\ntspan = (0.0, 30.0)\np = [10.0,28.0,2.66]\n\n\nprob = ODEProblem(g1,r0,tspan,p)\nsol = solve(prob,Tsit5())\n\n\nt = collect(range(1,stop=30,length=30))\nsig = 0.49\ndata = convert(Array, VectorOfArray([(sol(t[i]) + sig*randn(3)) for i in 1:length(t)]))\n\n\nPlots.scatter(t, data[1,:],markersize=4,color=:purple)\nPlots.scatter!(t, data[2,:],markersize=4,color=:yellow)\nPlots.scatter!(t, data[3,:],markersize=4,color=:black)\nplot!(sol)\n\n\ncb = AdaptiveProbIntsUncertainty(5)\nmonte_prob = MonteCarloProblem(prob)\nsim = solve(monte_prob,Tsit5(),num_monte=100,callback=cb,reltol=1e-5,abstol=1e-5)\nplot(sim,vars=(0,1),linealpha=0.4)\n\n\ncb = AdaptiveProbIntsUncertainty(5)\nmonte_prob = MonteCarloProblem(prob)\nsim = solve(monte_prob,Tsit5(),num_monte=100,callback=cb,reltol=1e-6,abstol=1e-6)\nplot(sim,vars=(0,1),linealpha=0.4)\n\n\ncb = AdaptiveProbIntsUncertainty(5)\nmonte_prob = MonteCarloProblem(prob)\nsim = solve(monte_prob,Tsit5(),num_monte=100,callback=cb,reltol=1e-8,abstol=1e-8)\nplot(sim,vars=(0,1),linealpha=0.4)\n\n\npriors = [Truncated(Normal(10,2),1,15),Truncated(Normal(30,5),1,45),Truncated(Normal(2.5,0.5),1,4)]\n\n\n@time bayesian_result = stan_inference(prob,t,data,priors;reltol=1e-8,abstol=1e-8,vars=(StanODEData(),InverseGamma(3,2)))\n\n\nplot_chain(bayesian_result)\n\n\n@time bayesian_result_turing = turing_inference(prob,Tsit5(),t,data,priors)\n\n\nplot_chain(bayesian_result_turing)\n\n", "meta": {"hexsha": "8b19a6d408b5cec6896b34f2c0fd0824d93c6a69", "size": 1622, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ParameterEstimation/DiffEqBayesLorenz.jl", "max_stars_repo_name": "jamesjscully/DiffEqBenchmarks.jl", "max_stars_repo_head_hexsha": "4a47f59717f3166864fa4f1b96a0faa5a0db7764", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-23T11:26:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T11:46:34.000Z", "max_issues_repo_path": "script/ParameterEstimation/DiffEqBayesLorenz.jl", "max_issues_repo_name": "jamesjscully/DiffEqBenchmarks.jl", "max_issues_repo_head_hexsha": "4a47f59717f3166864fa4f1b96a0faa5a0db7764", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-12T12:07:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-23T10:04:12.000Z", "max_forks_repo_path": "script/ParameterEstimation/DiffEqBayesLorenz.jl", "max_forks_repo_name": "jamesjscully/DiffEqBenchmarks.jl", "max_forks_repo_head_hexsha": "4a47f59717f3166864fa4f1b96a0faa5a0db7764", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-12T00:28:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T00:28:16.000Z", "avg_line_length": 23.1714285714, "max_line_length": 121, "alphanum_fraction": 0.7244143033, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7520107724925672}}
{"text": "### A Pluto.jl notebook ###\n# v0.11.2\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 9d996162-d41c-11ea-09b4-994ed99dd014\n\n\n# ╔═╡ 9d3661fc-d41c-11ea-1997-175b6d9a4095\n\n\n# ╔═╡ d5eaa180-d41b-11ea-32f6-6ff398c3e4c2\nbegin\n\tusing LinearAlgebra\n\tusing PlutoUI\n\tusing StatsKit\n\timport Plots\n\timport StatsPlots\n\t\n\tmd\"\"\"\n\t# Julia 102: Estatística com Pluto.jl\n\t\n\tVamos explorar um pouco as distribuições e funções estatísticas no Julia. A primeira coisa a notar é que o Julia básico contém o [pacote](https://docs.julialang.org/en/v1/stdlib/Statistics/) `Statistics`, com operações bem simples como `mean()` e `cov()`, e o [pacote](https://docs.julialang.org/en/v1/stdlib/Random/) `Random`, para a geração de números (pseudo)aleatórios. No entanto, há todo um ambiente de computação estatística em desenvolvimento para a linguagem. Vamos utilizar o [meta-pacote](https://github.com/JuliaStats/StatsKit.jl) `StatsKit` que importa alguns dos principais pacotes estatísticos.\n\t\n\tInicialmente, vamos explorar algumas funções e visualizações de interesse para a Estatística por meio das distribuicões univariadas do pacote [Distributions](https://juliastats.org/Distributions.jl/stable/univariate/).\n\t\"\"\"\nend\n\n# ╔═╡ 61be6a20-d41c-11ea-0eee-654e9ec43f39\nbegin\n\tmd\"\"\"\n\tVamos brincar um pouco com uma distribuição Normal na qual escolheremos os parâmetros μ e σ², comparando o seu gráfico com o da Normal Padrão.\n\t\n\t**Selecione o parâmetro μ da Normal**:\n\t\n\t$(@bind μ Slider(-50.0:0.1:50.0, 0)) \n\t\n\t**Selecione o parâmetro σ² da Normal**:\n\t\n\t$(@bind σ² Slider(1:0.01:50.0))\n\t\n\tAcima podemos conferir o resultado, em que a Normal Padrão está em azul escuro e a nossa Normal está em vermelho. Note que o valor inicial de μ é `0` e o σ² é `1`, logo as curvas estão sobrepostas.\n\t\"\"\"\nend\n\n# ╔═╡ 517a652c-d41c-11ea-2118-fdbf45828452\nmd\"\"\"### Distribuição Normal\n**Valor de μ**: $μ\n\n**Valor de σ²**: $σ²\n\"\"\"\n\n# ╔═╡ 57bc858e-d41c-11ea-392b-f1c840845820\n#Visualização das distribuições\nbegin\n\tPlots.plot(Normal(μ, σ²), color = :red, lw = 2, legend = false, fill = (0, :red), fillalpha = 0.5)\n\tPlots.plot!(Normal(0,1), color = :royalblue, lw = 2, legend = false, fill = (0, :royalblue), fillalpha = 0.5)\nend\n\n# ╔═╡ 664c20be-d41c-11ea-1467-e1c670479af6\nbegin\n\t\n\tx = rand(Normal(μ, σ²), 100)\n\t\n\tmd\"\"\"\n\tVamos agora gerar uma amostra aleatória de tamanho 100 da distribuição da nossa Normal(μ, σ²) usando o pacote `Random`. O comando está abaixo.\n\t\n\t\n\t\n\t\n\t\"\"\"\nend\n\n# ╔═╡ acc667f8-d59c-11ea-0805-41b21640540b\nbegin\n\tmd\"\"\"\n\tAgora vejamos a distribuição LogNormal.\n\t\n\t**Selecione o parâmetro μₗ da LogNormal**:\n\t\n\t$(@bind μₗ Slider(0.0:0.1:25.0)) \n\t\n\t**Selecione o parâmetro σ²ₗ da LogNormal**:\n\t\n\t$(@bind σ²ₗ Slider(0.01:0.01:5.0))\n\t\n\tNote que o valor inicial de μₗ é `1.0` e o σ²ₗ é `0.01`.\n\t\"\"\"\nend\n\n# ╔═╡ a3dc9324-d59c-11ea-3787-39b6dc720a4b\nmd\"\"\"### Distribuição LogNormal\n**Valor de μₗ**: $μₗ\n\n**Valor de σ²ₗ**: $σ²ₗ\n\"\"\"\n\n# ╔═╡ a651c700-d59c-11ea-029c-1d55b204a41c\n#Visualização da distribuição\nPlots.plot(LogNormal(μₗ, sqrt(σ²ₗ)), color = :red, lw = 2, legend = false, fill = (0, :red), fillalpha = 0.5)\n\n# ╔═╡ 6ebf2016-d41c-11ea-1a8d-6566e98d1f34\nbegin\n\tmd\"\"\"\n\tAgora vejamos a distribuição Gamma e o seu formato de acordo com os parâmetros k e θ, onde θ é o parâmetro de escala. Note que nesta parametrização, temos que a função de densidade é dada por\n\t\n\t\\begin{equation}\n\tf(x| k, \\theta) = \\frac{x^{k-1} e^{-x/θ}}{\\Gamma(k) \\theta^{k}} \\text{ ,} \n\t\\end{equation}\n\t\n\tpara $x > 0$, $k > 0$ e $\\theta > 0$.\n\t\n\t**Selecione o parâmetro k da Gamma**:\n\t\n\t$(@bind k Slider(1.0:0.1:25.0)) \n\t\n\t**Selecione o parâmetro θ da Gamma**:\n\t\n\t$(@bind θ Slider(0.1:0.1:25.0))\n\t\n\tNovamente podemos conferir o resultado. Note que o valor inicial de k é `1.0` e o θ é `0.1`.\n\t\"\"\"\nend\n\n# ╔═╡ 6a7b3bf2-d41c-11ea-014e-8b94632190ff\nmd\"\"\"### Distribuição Gamma\n**Valor de k**: $k\n\n**Valor de θ**: $θ\n\"\"\"\n\n# ╔═╡ 6e2923fe-d41c-11ea-03d2-0956b986677c\n#Visualização da distribuição\nPlots.plot(Gamma(k, θ), color = :red, lw = 2, legend = false, fill = (0, :red), fillalpha = 0.5)\n\n# ╔═╡ 801c622e-d41c-11ea-0441-e300c24904ae\nbegin\n\tmd\"\"\"\n\tAgora a distribuição mais versátil de todas: a distribuição Beta e o seu formato de acordo com os parâmetros α e β. \n\t\n\t**Selecione o parâmetro α da Beta**:\n\t\n\t$(@bind α Slider(0.1:0.1:10.0)) \n\t\n\t**Selecione o parâmetro β da Beta**:\n\t\n\t$(@bind β Slider(0.1:0.1:10.0))\n\t\n\tOs valores iniciais de α e de Β são ambos `0.1`.\n\t\"\"\"\nend\n\n# ╔═╡ 6f79fbca-d41c-11ea-0c49-3ffd9d1d5ab2\nmd\"\"\"### Distribuição Beta\n**Valor de α**: $α\n\n**Valor de β**: $β\n\"\"\"\n\n# ╔═╡ 80571608-d41c-11ea-2e72-b7f20192a991\n#Visualização da distribuição\nPlots.plot(Beta(α, β), color = :red, lw = 2, legend = false, fill = (0, :red), fillalpha = 0.5)\n\n# ╔═╡ 70188128-d41c-11ea-1e8f-5371e257a3bf\nbegin\n\tmd\"\"\"\n\tVemos agora a distribuição que ninguém se lembra como é a função de densidade: a distribuição Χ² e o seu formato de acordo com o parâmetro ν de graus de liberdade.\n\t\n\t**Selecione o parâmetro ν da Chi-Quadrado**:\n\t\n\t$(@bind ν Slider(1:50)) \n\t\n\tO valor inicial de ν é `1` e só assume valores inteiros positivos.\n\t\n\t\"\"\"\nend\n\n# ╔═╡ 7fd8c4ce-d41c-11ea-0790-f7afc7a1a84d\n#Verificando o valor do parâmetro\nmd\"\"\"\n### Distribuição Chi-Quadrado\n**Valor de ν**: $ν\n\"\"\"\n\n# ╔═╡ 7f661988-d41c-11ea-3167-753a433c34e3\n#Visualização da distribuição\nPlots.plot(Chisq(ν), color = :red, lw = 2, legend = false, fill = (0, :red), fillalpha = 0.5)\n\n# ╔═╡ 9dcde59a-d41c-11ea-36ec-db54e9680172\nbegin\n\tmd\"\"\"\n\tComo **com certeza** alguém disse na anterior que sabe sim a forma da função de densidade da Χ², então agora sim a distribuição cuja função de densidade que **ninguém** se lembra. Algum desafiante?\n\t\n\t**Selecione o parâmetro d₁ da F-Snedecor**:\n\t\n\t$(@bind d₁ Slider(1:50)) \n\t\n\t**Selecione o parâmetro d₂ da F-Snedecor**:\n\t\n\t$(@bind d₂ Slider(1:50)) \n\t\n\tOs valores iniciais de d₁ e d₂ são ambos `1`, e só assumem valores inteiros positivos.\n\t\"\"\"\nend\n\n# ╔═╡ 9bcc9a70-d41c-11ea-3235-0ffa6ccc0bd5\n#Verificando o valor dos parâmetros\nmd\"\"\"\n### Distribuição F-Snedecor\n**Valor de d₁**: $d₁\n\n**Valor de d₂**: $d₂\n\"\"\"\n\n# ╔═╡ 9dfe153a-d41c-11ea-2a80-79631819f1ac\n#Visualização da distribuição\nPlots.plot(FDist(d₁, d₂), color = :red, lw = 2, legend = false, fill = (0, :red), fillalpha = 0.5)\n\n# ╔═╡ Cell order:\n# ╠═d5eaa180-d41b-11ea-32f6-6ff398c3e4c2\n# ╟─517a652c-d41c-11ea-2118-fdbf45828452\n# ╟─57bc858e-d41c-11ea-392b-f1c840845820\n# ╟─61be6a20-d41c-11ea-0eee-654e9ec43f39\n# ╟─664c20be-d41c-11ea-1467-e1c670479af6\n# ╟─a3dc9324-d59c-11ea-3787-39b6dc720a4b\n# ╟─a651c700-d59c-11ea-029c-1d55b204a41c\n# ╟─acc667f8-d59c-11ea-0805-41b21640540b\n# ╟─6a7b3bf2-d41c-11ea-014e-8b94632190ff\n# ╟─6e2923fe-d41c-11ea-03d2-0956b986677c\n# ╟─6ebf2016-d41c-11ea-1a8d-6566e98d1f34\n# ╟─6f79fbca-d41c-11ea-0c49-3ffd9d1d5ab2\n# ╟─80571608-d41c-11ea-2e72-b7f20192a991\n# ╟─801c622e-d41c-11ea-0441-e300c24904ae\n# ╟─7fd8c4ce-d41c-11ea-0790-f7afc7a1a84d\n# ╠═7f661988-d41c-11ea-3167-753a433c34e3\n# ╟─70188128-d41c-11ea-1e8f-5371e257a3bf\n# ╟─9bcc9a70-d41c-11ea-3235-0ffa6ccc0bd5\n# ╟─9dfe153a-d41c-11ea-2a80-79631819f1ac\n# ╟─9dcde59a-d41c-11ea-36ec-db54e9680172\n# ╠═9d996162-d41c-11ea-09b4-994ed99dd014\n# ╠═9d3661fc-d41c-11ea-1997-175b6d9a4095\n", "meta": {"hexsha": "66f56ab875e8e8c420f48a1f804638e7d8e7f330", "size": 7515, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia_com_Pluto_Estatistica.jl", "max_stars_repo_name": "fausto-mpj/EduPluto", "max_stars_repo_head_hexsha": "4ca4d316fb9c76adde400bb78fbb4f64e6e7a8ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-23T10:26:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T17:44:38.000Z", "max_issues_repo_path": "Julia_com_Pluto_Estatistica.jl", "max_issues_repo_name": "fausto-mpj/EduPluto", "max_issues_repo_head_hexsha": "4ca4d316fb9c76adde400bb78fbb4f64e6e7a8ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia_com_Pluto_Estatistica.jl", "max_forks_repo_name": "fausto-mpj/EduPluto", "max_forks_repo_head_hexsha": "4ca4d316fb9c76adde400bb78fbb4f64e6e7a8ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8214285714, "max_line_length": 610, "alphanum_fraction": 0.7000665336, "num_tokens": 3176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.8418256452674009, "lm_q1q2_score": 0.752010771957369}}
{"text": "# indicator of a generic box\n\n\"\"\"\n  IndBox(lb, ub)\n\nReturns the function `g = ind{x : lb ⩽ x ⩽ ub}`. Parameters `lb` and `ub` can be\neither scalars or arrays of the same dimension as `x`, and must satisfy `lb <= ub`.\nBounds are allowed to take values `-Inf` and `+Inf`.\n\"\"\"\n\nimmutable IndBox{T <: Union{Real, AbstractArray}, S <: Union{Real, AbstractArray}} <: IndicatorConvex\n  lb::T\n  ub::S\n  function IndBox(lb::T, ub::S)\n    if !(eltype(lb) <: Real && eltype(ub) <: Real)\n      error(\"lb and ub must be real\")\n    end\n    if any(lb .> ub)\n      error(\"lb and ub must satisfy lb <= ub\")\n    else\n      new(lb, ub)\n    end\n  end\nend\n\nIndBox{T <: Real}(lb::T, ub::T) = IndBox{T, T}(lb, ub)\n\nIndBox{T <: AbstractArray, S <: Real}(lb::T, ub::S) = IndBox{T, S}(lb, ub)\n\nIndBox{T <: Real, S <: AbstractArray}(lb::T, ub::S) = IndBox{T, S}(lb, ub)\n\nIndBox{T <: AbstractArray, S <: AbstractArray}(lb::T, ub::S) =\n  size(lb) != size(ub) ? error(\"bounds must have the same dimensions, or at least one of them be scalar\") :\n  IndBox{T, S}(lb, ub)\n\nIndBox_lb{T <: Real, S}(f::IndBox{T, S}, i) = f.lb\nIndBox_lb{T <: AbstractArray, S}(f::IndBox{T, S}, i) = f.lb[i]\nIndBox_ub{T, S <: Real}(f::IndBox{T, S}, i) = f.ub\nIndBox_ub{T, S <: AbstractArray}(f::IndBox{T, S}, i) = f.ub[i]\n\nfunction (f::IndBox){R <: Real}(x::AbstractArray{R})\n  for k in eachindex(x)\n    if x[k] < IndBox_lb(f,k) || x[k] > IndBox_ub(f,k)\n      return +Inf\n    end\n  end\n  return 0.0\nend\n\nfunction prox!{R <: Real}(f::IndBox, x::AbstractArray{R}, y::AbstractArray{R}, gamma::Real=1.0)\n  for k in eachindex(x)\n    if x[k] < IndBox_lb(f,k)\n      y[k] = IndBox_lb(f,k)\n    elseif x[k] > IndBox_ub(f,k)\n      y[k] = IndBox_ub(f,k)\n    else\n      y[k] = x[k]\n    end\n  end\n  return 0.0\nend\n\n\"\"\"\n  IndBallLinf(r::Real=1.0)\n\nReturns the indicator function of an infinity-norm ball, that is function\n`g(x) = ind{maximum(abs(x)) ⩽ r}` for `r ⩾ 0`.\n\"\"\"\n\nIndBallLinf{R <: Real}(r::R=1.0) = IndBox(-r, r)\n\nfun_name(f::IndBox) = \"indicator of a box\"\nfun_dom(f::IndBox) = \"AbstractArray{Real}\"\nfun_expr(f::IndBox) = \"x ↦ 0 if all(lb ⩽ x ⩽ ub), +∞ otherwise\"\nfun_params(f::IndBox) =\n  string( \"lb = \", typeof(f.lb) <: AbstractArray ? string(typeof(f.lb), \" of size \", size(f.lb)) : f.lb, \", \",\n          \"ub = \", typeof(f.ub) <: AbstractArray ? string(typeof(f.ub), \" of size \", size(f.ub)) : f.ub)\n\nfunction prox_naive{R <: Real}(f::IndBox, x::AbstractArray{R}, gamma::Real=1.0)\n  y = min.(f.ub, max.(f.lb, x))\n  return y, 0.0\nend\n", "meta": {"hexsha": "fbb54397de47cb01e39ad97646f3ce8a9a534ad2", "size": 2477, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indBox.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/indBox.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/indBox.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.843373494, "max_line_length": 110, "alphanum_fraction": 0.594670973, "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7520107708035317}}
{"text": "### A Pluto.jl notebook ###\n# v0.18.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ ae47661e-95a2-11ec-119b-8194fe27f96e\nbegin\n\tusing Plots\n\tusing LsqFit\n\timport Distributions as di\n\tusing Random\n\tusing Turing\n\tusing Statistics\n\tusing StatsPlots\n\tusing FillArrays\nend\n\n# ╔═╡ 8dc3dee2-a7d2-4afd-94b1-63154910a54c\nt = 0:0.1:5\n\n# ╔═╡ 4c8163a1-1206-47dc-bc58-1d642663a22e\nfunction model(t,p)\n\treturn p[1] .* exp.(-t/p[2])\nend\n\n# ╔═╡ 38284326-0524-43cd-8fbe-3d228aac9bf4\nbegin\n\tdata_err = 0.5\n\td = di.Normal(0,data_err)\nend\n\n# ╔═╡ a0add249-405b-4f30-a667-c791d155d5ca\nampl_range = 2:0.1:5\n\n# ╔═╡ c5f1d281-fc40-4fdb-ae25-664ff7c99332\ndecay_range = 1:0.1:3\n\n# ╔═╡ 2288748b-9ae9-4032-a371-b2de8712cd88\ny = 3.0 .* exp.(-t/2.0) + rand(d,length(t))\n\n# ╔═╡ 7abe92c4-3081-429d-88b0-fd1d367fb3df\nbegin\n\tplot(t,y,yerror=data_err)\n\tplot!(t,model(t,[3.0,2.0]))\nend\n\n# ╔═╡ 8948ee55-fa92-4ac5-9836-ff2640a541db\nfit = curve_fit(model, t, y, [1.0,1.0])\n\n# ╔═╡ eb879e89-7277-4804-952b-19048874ced5\nfit.param\n\n# ╔═╡ 3a803151-2291-4798-b1f4-15e6bd1189fb\ncov = estimate_covar(fit)\n\n# ╔═╡ 7cbfb55e-8984-4bee-9848-dcaacdfb1282\nconf = confidence_interval(fit, 0.1)\n\n# ╔═╡ bf29e446-1cd4-4c2d-8f1f-0b91f39aa450\nexp_dist = di.MvNormal(fit.param,cov)\n\n# ╔═╡ 3449f76f-9dbe-4c07-898e-5b944174b374\nfunction f(x,y)\n\treturn di.pdf(exp_dist,[x,y])\nend\n\n# ╔═╡ d977a512-3085-4a87-a95d-7d3041402e0a\ncontourf(ampl_range,decay_range,f)\n\n# ╔═╡ fc76af35-ac05-418a-993d-a382c41b036f\nbegin\n\tmy_normal = di.Normal(1,2)\n\tmy_sample = rand(my_normal,200)\nend\n\n# ╔═╡ 2dacbdf4-dbf2-42c9-9529-007fff009c12\nmean(my_sample)\n\n# ╔═╡ 1d360be7-43a1-4a75-8d09-e229917ff815\nstd(my_sample)\n\n# ╔═╡ 923e8ca4-8f66-47b8-a2b1-b7b384416163\n@model function my_fit(data)\n\tμ ~ Uniform(-10,10)\n\tσ ~ Uniform(0,20)\n\tfor i in 1:length(data)\n\t\tdata[i] ~ Normal(μ,σ)\n\tend\nend\n\n# ╔═╡ b2c73bae-7a71-49b6-8ea0-3c57dd7843ae\nmodel1 = my_fit(my_sample)\n\n# ╔═╡ 46e1c786-6abc-4f82-a1a8-04e0394aa005\nchain = sample(model1,NUTS(0.65),1000)\n\n# ╔═╡ 39dc3dae-105b-490c-a5af-b8cfdc059bc0\nStatsPlots.plot(chain)\n\n# ╔═╡ 7241b49c-b5d9-438a-950a-8ffcfa3d301b\ndescribe(chain)\n\n# ╔═╡ c17062e7-42dc-4b49-8b54-2a61adf6396b\nx = 0:10\n\n# ╔═╡ fee857c0-cbb4-4a49-ab9e-59c58b92cb63\nfunction lin_model(x,p)\n\treturn p[1] .+ (p[2] .* x)\nend\n\n# ╔═╡ 7bb4d1f9-bfa7-4aef-b88e-96cb6bef96ee\nfunction quad_model(x,p)\n\treturn p[1] .+ (p[2] .* x) .+ (p[3] .* x .^ 2)\nend\n\n# ╔═╡ 974540df-328a-4855-a954-028c19f1ea56\nbegin\n\tdlin_error = 2.0\n\tdlin = di.Normal(0,dlin_error)\nend\n\n# ╔═╡ 029632a7-e923-448b-86b9-21e5c9c6acd6\nyy = 2.0 .+ (3.0 .* x) .+ 0.1 .* x .^ 2 .+ rand(dlin,length(x))\n\n# ╔═╡ a56ca084-6366-4148-b600-56f797d3927e\nfit_lin = curve_fit(lin_model,x,yy,[2.0,3.0])\n\n# ╔═╡ 57f154a5-d32c-47f0-9dec-a136b3fd44a7\nfit_lin.param\n\n# ╔═╡ 89f26e4b-f10e-47e2-a032-b3848ec618f2\nyy_fit = fit_lin.param[1] .+ fit_lin.param[2] .* x\n\n# ╔═╡ 07174e20-8292-441b-ae92-51800f641e64\nyy_quadfit = curve_fit(quad_model, x,yy,[3.0,2.0,0.0])\n\n# ╔═╡ 4b4cf4ee-27b8-4d25-a926-0c4e311c980f\nyy_quadfit.param\n\n# ╔═╡ 08e5fe39-a598-4f06-9c5c-aa8e7ac3c4b9\nyy_quad = yy_quadfit.param[1] .+ (yy_quadfit.param[2] .* x) .+ (yy_quadfit.param[3] .* x .^ 2)\n\n# ╔═╡ 89a7fbc5-ea56-4e8d-b50d-63456484dca0\ncov_quad = estimate_covar(yy_quadfit)\n\n# ╔═╡ 461b0327-1278-4c99-90f9-b8c1b6e1a5c6\ndelta_quad = sqrt(cov_quad[3,3])\n\n# ╔═╡ afb2e5ef-3d4c-439a-8574-443a09eb850d\nbegin\n\tscatter(x,yy,yerror=dlin_error,label=false)\n\tplot!(x, yy_fit, label=false)\n\tplot!(x, yy_quad, label=false)\nend\n\n# ╔═╡ 0246ae6c-974f-4e4e-a16f-6dce6a0cddfa\nchi_quad = sum(yy_quadfit.resid .^ 2 /dlin_error^2)\n\n# ╔═╡ 838f4345-c865-4712-8d39-b52777ab986d\nchi_lin = sum(fit_lin.resid .^ 2 /dlin_error^2)\n\n# ╔═╡ 44503a57-a47c-46dd-9882-c97c568b4bc7\nexp(-chi_lin)/exp(-chi_quad)*1.0/sqrt(cov_quad[3,3])/sqrt(2*π)\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nDistributions = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nFillArrays = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nLsqFit = \"2fda8390-95c7-5789-9bda-21331edee243\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nRandom = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\nStatistics = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\nStatsPlots = \"f3b207a7-027a-5e70-b257-86293d7955fd\"\nTuring = \"fce5fe82-541a-59a6-adf8-730c64b5f9a0\"\n\n[compat]\nDistributions = \"~0.25.53\"\nFillArrays = \"~0.13.2\"\nLsqFit = \"~0.12.1\"\nPlots = \"~1.27.5\"\nStatsPlots = \"~0.14.33\"\nTuring = \"~0.21.1\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[AbstractFFTs]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"6f1d9bc1c08f9f4a8fa92e3ea3cb50153a1b40d4\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"1.1.0\"\n\n[[AbstractMCMC]]\ndeps = [\"BangBang\", \"ConsoleProgressMonitor\", \"Distributed\", \"Logging\", \"LoggingExtras\", \"ProgressLogging\", \"Random\", \"StatsBase\", \"TerminalLoggers\", \"Transducers\"]\ngit-tree-sha1 = \"47aca4cf0dc430f20f68f6992dc4af0e4dc8ebee\"\nuuid = \"80f14c24-f653-4e6a-9b94-39d6b0f70001\"\nversion = \"4.0.0\"\n\n[[AbstractPPL]]\ndeps = [\"AbstractMCMC\", \"DensityInterface\", \"Setfield\", \"SparseArrays\"]\ngit-tree-sha1 = \"6320752437e9fbf49639a410017d862ad64415a5\"\nuuid = \"7a57a42e-76ec-4ea3-a279-07e840d6d9cf\"\nversion = \"0.5.2\"\n\n[[AbstractTrees]]\ngit-tree-sha1 = \"03e0550477d86222521d254b741d470ba17ea0b5\"\nuuid = \"1520ce14-60c1-5f80-bbc7-55ef81b5835c\"\nversion = \"0.3.4\"\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"af92965fb30777147966f58acb05da51c5616b5f\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.3\"\n\n[[AdvancedHMC]]\ndeps = [\"AbstractMCMC\", \"ArgCheck\", \"DocStringExtensions\", \"InplaceOps\", \"LinearAlgebra\", \"ProgressMeter\", \"Random\", \"Requires\", \"Setfield\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"UnPack\"]\ngit-tree-sha1 = \"68136ef13a2f549a20e3572c8f9f2b83b901ac1a\"\nuuid = \"0bf59076-c3b1-5ca4-86bd-e02cd72cde3d\"\nversion = \"0.3.4\"\n\n[[AdvancedMH]]\ndeps = [\"AbstractMCMC\", \"Distributions\", \"Random\", \"Requires\"]\ngit-tree-sha1 = \"5d9e09a242d4cf222080398468244389c3428ed1\"\nuuid = \"5b7e9947-ddc0-4b3f-9b55-0d8042f74170\"\nversion = \"0.6.7\"\n\n[[AdvancedPS]]\ndeps = [\"AbstractMCMC\", \"Distributions\", \"Libtask\", \"Random\", \"StatsFuns\"]\ngit-tree-sha1 = \"78620daebe1b87dfe17cac4bc08cec73b057eb0a\"\nuuid = \"576499cb-2369-40b2-a588-c64705576edc\"\nversion = \"0.3.7\"\n\n[[AdvancedVI]]\ndeps = [\"Bijectors\", \"Distributions\", \"DistributionsAD\", \"DocStringExtensions\", \"ForwardDiff\", \"LinearAlgebra\", \"ProgressMeter\", \"Random\", \"Requires\", \"StatsBase\", \"StatsFuns\", \"Tracker\"]\ngit-tree-sha1 = \"2f0ddff49ae4c812ba7b348b8427636f8bbd6c05\"\nuuid = \"b5ca4192-6429-45e5-a2d9-87aec30a685c\"\nversion = \"0.1.4\"\n\n[[ArgCheck]]\ngit-tree-sha1 = \"a3a402a35a2f7e0b87828ccabbd5ebfbebe356b4\"\nuuid = \"dce04be8-c92d-5529-be00-80e4d2c0e197\"\nversion = \"2.3.0\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Arpack]]\ndeps = [\"Arpack_jll\", \"Libdl\", \"LinearAlgebra\", \"Logging\"]\ngit-tree-sha1 = \"91ca22c4b8437da89b030f08d71db55a379ce958\"\nuuid = \"7d9fca2a-8960-54d3-9f78-7d1dccf2cb97\"\nversion = \"0.5.3\"\n\n[[Arpack_jll]]\ndeps = [\"Libdl\", \"OpenBLAS_jll\", \"Pkg\"]\ngit-tree-sha1 = \"e214a9b9bd1b4e1b4f15b22c0994862b66af7ff7\"\nuuid = \"68821587-b530-5797-8361-c406ea357684\"\nversion = \"3.5.0+3\"\n\n[[ArrayInterface]]\ndeps = [\"Compat\", \"IfElse\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"Static\"]\ngit-tree-sha1 = \"c933ce606f6535a7c7b98e1d86d5d1014f730596\"\nuuid = \"4fba245c-0d91-5ea0-9b3e-6abc04ee57a9\"\nversion = \"5.0.7\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[AxisAlgorithms]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"66771c8d21c8ff5e3a93379480a2307ac36863f7\"\nuuid = \"13072b0f-2c55-5437-9ae7-d433b7a33950\"\nversion = \"1.0.1\"\n\n[[AxisArrays]]\ndeps = [\"Dates\", \"IntervalSets\", \"IterTools\", \"RangeArrays\"]\ngit-tree-sha1 = \"cf6875678085aed97f52bfc493baaebeb6d40bcb\"\nuuid = \"39de3d68-74b9-583c-8d2d-e117c070f3a9\"\nversion = \"0.4.5\"\n\n[[BangBang]]\ndeps = [\"Compat\", \"ConstructionBase\", \"Future\", \"InitialValues\", \"LinearAlgebra\", \"Requires\", \"Setfield\", \"Tables\", \"ZygoteRules\"]\ngit-tree-sha1 = \"b15a6bc52594f5e4a3b825858d1089618871bf9d\"\nuuid = \"198e06fe-97b7-11e9-32a5-e1d131e6ad66\"\nversion = \"0.3.36\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Baselet]]\ngit-tree-sha1 = \"aebf55e6d7795e02ca500a689d326ac979aaf89e\"\nuuid = \"9718e550-a3fa-408a-8086-8db961cd8217\"\nversion = \"0.1.1\"\n\n[[Bijectors]]\ndeps = [\"ArgCheck\", \"ChainRulesCore\", \"Compat\", \"Distributions\", \"Functors\", \"IrrationalConstants\", \"LinearAlgebra\", \"LogExpFunctions\", \"MappedArrays\", \"Random\", \"Reexport\", \"Requires\", \"Roots\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"369af32fcb9be65d496dc43ad0bb713705d4e859\"\nuuid = \"76274a88-744f-5084-9051-94815aaf08c4\"\nversion = \"0.9.11\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"4b859a208b2397a7a623a03449e4636bdb17bcf2\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+1\"\n\n[[ChainRules]]\ndeps = [\"ChainRulesCore\", \"Compat\", \"IrrationalConstants\", \"LinearAlgebra\", \"Random\", \"RealDot\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"8b887daa6af5daf705081061e36386190204ac87\"\nuuid = \"082447d4-558c-5d27-93f4-14fc19e9eca2\"\nversion = \"1.28.1\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"9950387274246d08af38f6eef8cb5480862a435f\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.14.0\"\n\n[[ChangesOfVariables]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"bf98fa45a0a4cee295de98d4c1462be26345b9a1\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.2\"\n\n[[Clustering]]\ndeps = [\"Distances\", \"LinearAlgebra\", \"NearestNeighbors\", \"Printf\", \"SparseArrays\", \"Statistics\", \"StatsBase\"]\ngit-tree-sha1 = \"75479b7df4167267d75294d14b58244695beb2ac\"\nuuid = \"aaaa29a8-35af-508c-8bc3-b662a17a0fe5\"\nversion = \"0.14.2\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"12fc73e5e0af68ad3137b886e3f7c1eacfca2640\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.17.1\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Combinatorics]]\ngit-tree-sha1 = \"08c8b6831dc00bfea825826be0bc8336fc369860\"\nuuid = \"861a8166-3701-5b0c-9a16-15d98fcdc6aa\"\nversion = \"1.0.2\"\n\n[[CommonSolve]]\ngit-tree-sha1 = \"68a0743f578349ada8bc911a5cbd5a2ef6ed6d1f\"\nuuid = \"38540f10-b2f7-11e9-35d8-d573e4eb0ff2\"\nversion = \"0.2.0\"\n\n[[CommonSubexpressions]]\ndeps = [\"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"7b8a93dba8af7e3b42fecabf646260105ac373f7\"\nuuid = \"bbf7d656-a473-5ed7-a52c-81e309532950\"\nversion = \"0.3.0\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"b153278a25dd42c65abbf4e62344f9d22e59191b\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.43.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[CompositionsBase]]\ngit-tree-sha1 = \"455419f7e328a1a2493cabc6428d79e951349769\"\nuuid = \"a33af91c-f02d-484b-be07-31d278c5ca2b\"\nversion = \"0.1.1\"\n\n[[ConsoleProgressMonitor]]\ndeps = [\"Logging\", \"ProgressMeter\"]\ngit-tree-sha1 = \"3ab7b2136722890b9af903859afcf457fa3059e8\"\nuuid = \"88cd18e8-d9cc-4ea6-8889-5259c0d15c8b\"\nversion = \"0.1.2\"\n\n[[ConstructionBase]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"f74e9d5388b8620b4cee35d4c5a618dd4dc547f4\"\nuuid = \"187b0558-2788-49d3-abe0-74a17ed4e7c9\"\nversion = \"1.3.0\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[Crayons]]\ngit-tree-sha1 = \"249fe38abf76d48563e2f4556bebd215aa317e15\"\nuuid = \"a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f\"\nversion = \"4.1.1\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"3daef5523dd2e769dad2365274f760ff5f282c7d\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.11\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[DataValues]]\ndeps = [\"DataValueInterfaces\", \"Dates\"]\ngit-tree-sha1 = \"d88a19299eba280a6d062e135a43f00323ae70bf\"\nuuid = \"e7dc6d0d-1eca-5fa6-8ad6-5aecde8b7ea5\"\nversion = \"0.4.13\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DefineSingletons]]\ngit-tree-sha1 = \"0fba8b706d0178b4dc7fd44a96a92382c9065c2c\"\nuuid = \"244e2a9f-e319-4986-a169-4d1fe445cd52\"\nversion = \"0.1.2\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[DensityInterface]]\ndeps = [\"InverseFunctions\", \"Test\"]\ngit-tree-sha1 = \"80c3e8639e3353e5d2912fb3a1916b8455e2494b\"\nuuid = \"b429d917-457f-4dbc-8f4c-0cc954292b1d\"\nversion = \"0.4.0\"\n\n[[DiffResults]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"c18e98cba888c6c25d1c3b048e4b3380ca956805\"\nuuid = \"163ba53b-c6d8-5494-b064-1a9d43ac40c5\"\nversion = \"1.0.3\"\n\n[[DiffRules]]\ndeps = [\"IrrationalConstants\", \"LogExpFunctions\", \"NaNMath\", \"Random\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"dd933c4ef7b4c270aacd4eb88fa64c147492acf0\"\nuuid = \"b552c78f-8df3-52c6-915a-8e097449b14b\"\nversion = \"1.10.0\"\n\n[[Distances]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"3258d0659f812acde79e8a74b11f17ac06d0ca04\"\nuuid = \"b4f34e82-e78d-54a5-968a-f98e89d6e8f7\"\nversion = \"0.10.7\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Distributions]]\ndeps = [\"ChainRulesCore\", \"DensityInterface\", \"FillArrays\", \"LinearAlgebra\", \"PDMats\", \"Printf\", \"QuadGK\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"Test\"]\ngit-tree-sha1 = \"5a4168170ede913a2cd679e53c2123cb4b889795\"\nuuid = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nversion = \"0.25.53\"\n\n[[DistributionsAD]]\ndeps = [\"Adapt\", \"ChainRules\", \"ChainRulesCore\", \"Compat\", \"DiffRules\", \"Distributions\", \"FillArrays\", \"LinearAlgebra\", \"NaNMath\", \"PDMats\", \"Random\", \"Requires\", \"SpecialFunctions\", \"StaticArrays\", \"StatsBase\", \"StatsFuns\", \"ZygoteRules\"]\ngit-tree-sha1 = \"b51ed93e06497fc4e7ff78bbca03c4f7951d2ec2\"\nuuid = \"ced4e74d-a319-5a8a-b0ac-84af2272839c\"\nversion = \"0.6.38\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[DynamicPPL]]\ndeps = [\"AbstractMCMC\", \"AbstractPPL\", \"BangBang\", \"Bijectors\", \"ChainRulesCore\", \"Distributions\", \"LinearAlgebra\", \"MacroTools\", \"Random\", \"Setfield\", \"Test\", \"ZygoteRules\"]\ngit-tree-sha1 = \"5d1704965e4bf0c910693b09ece8163d75e28806\"\nuuid = \"366bfd00-2699-11ea-058f-f148b4cae6d8\"\nversion = \"0.19.1\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[EllipticalSliceSampling]]\ndeps = [\"AbstractMCMC\", \"ArrayInterface\", \"Distributions\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"bed775e32c6f38a19c1dbe0298480798e6be455f\"\nuuid = \"cad2338a-1db2-11e9-3401-43bc07c9ede2\"\nversion = \"0.5.0\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"bad72f730e9e91c08d9427d5e8db95478a3c323d\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.4.8+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FFTW]]\ndeps = [\"AbstractFFTs\", \"FFTW_jll\", \"LinearAlgebra\", \"MKL_jll\", \"Preferences\", \"Reexport\"]\ngit-tree-sha1 = \"505876577b5481e50d089c1c68899dfb6faebc62\"\nuuid = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nversion = \"1.4.6\"\n\n[[FFTW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea\"\nuuid = \"f5851436-0d7a-5f13-b9de-f02708fd171a\"\nversion = \"3.3.10+0\"\n\n[[FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"246621d23d1f43e3b9c368bf3b72b2331a27c286\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.13.2\"\n\n[[FiniteDiff]]\ndeps = [\"ArrayInterface\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"StaticArrays\"]\ngit-tree-sha1 = \"56956d1e4c1221000b7781104c58c34019792951\"\nuuid = \"6a86dc24-6348-571c-b903-95158fe2bd41\"\nversion = \"2.11.0\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[ForwardDiff]]\ndeps = [\"CommonSubexpressions\", \"DiffResults\", \"DiffRules\", \"LinearAlgebra\", \"LogExpFunctions\", \"NaNMath\", \"Preferences\", \"Printf\", \"Random\", \"SpecialFunctions\", \"StaticArrays\"]\ngit-tree-sha1 = \"1bd6fc0c344fc0cbee1f42f8d2e7ec8253dda2d2\"\nuuid = \"f6369f11-7733-5829-9624-2563aa707210\"\nversion = \"0.10.25\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[Functors]]\ngit-tree-sha1 = \"223fffa49ca0ff9ce4f875be001ffe173b2b7de4\"\nuuid = \"d9f16b24-f501-4c13-a1f2-28368ffc5196\"\nversion = \"0.2.8\"\n\n[[Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"51d2dfe8e590fbd74e7a842cf6d13d8a2f45dc01\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.6+0\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"RelocatableFolders\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"af237c08bda486b74318c8070adb96efa6952530\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.64.2\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"cd6efcf9dc746b06709df14e462f0a3fe0786b1e\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.64.2+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"83ea630384a13fc4f002b77690bc0afeb4255ac9\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.2\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"a32d672ac2c967f3deb8a81d828afc739c838a06\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+2\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"0fa77022fe4b511826b39c894c90daf5fce3334a\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.17\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"129acf094d168394e80ee1dc4bc06ec835e510a3\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+1\"\n\n[[IRTools]]\ndeps = [\"InteractiveUtils\", \"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"7f43342f8d5fd30ead0ba1b49ab1a3af3b787d24\"\nuuid = \"7869d1d1-7146-5819-86e3-90919afe41df\"\nversion = \"0.4.5\"\n\n[[IfElse]]\ngit-tree-sha1 = \"debdd00ffef04665ccbb3e150747a77560e8fad1\"\nuuid = \"615f187c-cbe4-4ef1-ba3b-2fcf58d6d173\"\nversion = \"0.1.1\"\n\n[[IniFile]]\ngit-tree-sha1 = \"f550e6e32074c939295eb5ea6de31849ac2c9625\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.1\"\n\n[[InitialValues]]\ngit-tree-sha1 = \"4da0f88e9a39111c2fa3add390ab15f3a44f3ca3\"\nuuid = \"22cec73e-a1b8-11e9-2c92-598750a2cf9c\"\nversion = \"0.3.1\"\n\n[[InplaceOps]]\ndeps = [\"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"50b41d59e7164ab6fda65e71049fee9d890731ff\"\nuuid = \"505f98c9-085e-5b2c-8e89-488be7bf1f34\"\nversion = \"0.3.0\"\n\n[[IntelOpenMP_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d979e54b71da82f3a65b62553da4fc3d18c9004c\"\nuuid = \"1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0\"\nversion = \"2018.0.3+2\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[Interpolations]]\ndeps = [\"AxisAlgorithms\", \"ChainRulesCore\", \"LinearAlgebra\", \"OffsetArrays\", \"Random\", \"Ratios\", \"Requires\", \"SharedArrays\", \"SparseArrays\", \"StaticArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"b15fc0a95c564ca2e0a7ae12c1f095ca848ceb31\"\nuuid = \"a98d9a8b-a2ab-59e6-89dd-64a1c18fca59\"\nversion = \"0.13.5\"\n\n[[IntervalSets]]\ndeps = [\"Dates\", \"Statistics\"]\ngit-tree-sha1 = \"be25da7314bea50ad8303325ba08d9257bf19f9c\"\nuuid = \"8197267c-284f-5f27-9208-e0e47529a953\"\nversion = \"0.6.0\"\n\n[[InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"91b5dcf362c5add98049e6c29ee756910b03051d\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.3\"\n\n[[InvertedIndices]]\ngit-tree-sha1 = \"bee5f1ef5bf65df56bdd2e40447590b272a5471f\"\nuuid = \"41ab1584-1d38-5bbf-9106-f11c6c58b48f\"\nversion = \"1.1.0\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[IterTools]]\ngit-tree-sha1 = \"fa6287a4469f5e048d763df38279ee729fbd44e5\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.4.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"abc9885a7ca2052a736a600f7fa66209f96506e1\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.4.1\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"3c837543ddb02250ef42f4738347454f95079d4e\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.3\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b53380851c6e6664204efb2e62cd24fa5c47e4ba\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.2+0\"\n\n[[KernelDensity]]\ndeps = [\"Distributions\", \"DocStringExtensions\", \"FFTW\", \"Interpolations\", \"StatsBase\"]\ngit-tree-sha1 = \"591e8dc09ad18386189610acafb970032c519707\"\nuuid = \"5ab0869b-81aa-558d-bb23-cbf5423bbe9b\"\nversion = \"0.6.3\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LERC_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"bf36f528eec6634efc60d7ec062008f171071434\"\nuuid = \"88015f11-f218-50d7-93a8-a6af411a945d\"\nversion = \"3.0.0+1\"\n\n[[LRUCache]]\ngit-tree-sha1 = \"d64a0aff6691612ab9fb0117b0995270871c5dfc\"\nuuid = \"8ac3fa9e-de4c-5943-b1dc-09c6b5f20637\"\nversion = \"1.3.0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"f2355693d6778a178ade15952b7ac47a4ff97996\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.3.0\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"6f14549f7760d84b2db7a9b10b88cd3cc3025730\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.14\"\n\n[[LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[LeftChildRightSiblingTrees]]\ndeps = [\"AbstractTrees\"]\ngit-tree-sha1 = \"b864cb409e8e445688bc478ef87c0afe4f6d1f8d\"\nuuid = \"1d6d02ad-be62-4b6b-8a6d-2f90e265016e\"\nversion = \"0.1.3\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"0b4a5d71f3e5200a7dff793393e09dfc2d874290\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+1\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtask]]\ndeps = [\"IRTools\", \"LRUCache\", \"LinearAlgebra\", \"MacroTools\", \"Statistics\"]\ngit-tree-sha1 = \"ed1b54f6df6fb7af8b315cfdc288ab5572dbd3ba\"\nuuid = \"6f1fad26-d15e-5dc8-ae53-837a1d7b8c9f\"\nversion = \"0.7.0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"LERC_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"c9551dd26e31ab17b86cbd00c2ede019c08758eb\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+1\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"a970d55c2ad8084ca317a4658ba6ce99b7523571\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.12\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[LoggingExtras]]\ndeps = [\"Dates\", \"Logging\"]\ngit-tree-sha1 = \"dfeda1c1130990428720de0024d4516b1902ce98\"\nuuid = \"e6f89c97-d47a-5376-807f-9c37f3926c36\"\nversion = \"0.4.7\"\n\n[[LsqFit]]\ndeps = [\"Distributions\", \"ForwardDiff\", \"LinearAlgebra\", \"NLSolversBase\", \"OptimBase\", \"Random\", \"StatsBase\"]\ngit-tree-sha1 = \"91aa1442e63a77f101aff01dec5a821a17f43922\"\nuuid = \"2fda8390-95c7-5789-9bda-21331edee243\"\nversion = \"0.12.1\"\n\n[[MCMCChains]]\ndeps = [\"AbstractMCMC\", \"AxisArrays\", \"Compat\", \"Dates\", \"Distributions\", \"Formatting\", \"IteratorInterfaceExtensions\", \"KernelDensity\", \"LinearAlgebra\", \"MCMCDiagnosticTools\", \"MLJModelInterface\", \"NaturalSort\", \"OrderedCollections\", \"PrettyTables\", \"Random\", \"RecipesBase\", \"Serialization\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"TableTraits\", \"Tables\"]\ngit-tree-sha1 = \"872da3b1f21fa79c66723225efabc878f18509ed\"\nuuid = \"c7f686f2-ff18-58e9-bc7b-31028e88f75d\"\nversion = \"5.1.0\"\n\n[[MCMCDiagnosticTools]]\ndeps = [\"AbstractFFTs\", \"DataAPI\", \"Distributions\", \"LinearAlgebra\", \"MLJModelInterface\", \"Random\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"Tables\"]\ngit-tree-sha1 = \"058d08594e91ba1d98dcc3669f9421a76824aa95\"\nuuid = \"be115224-59cd-429b-ad48-344e309966f0\"\nversion = \"0.1.3\"\n\n[[MKL_jll]]\ndeps = [\"Artifacts\", \"IntelOpenMP_jll\", \"JLLWrappers\", \"LazyArtifacts\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e595b205efd49508358f7dc670a940c790204629\"\nuuid = \"856f044c-d86e-5d09-b602-aeab76dc8ba7\"\nversion = \"2022.0.0+0\"\n\n[[MLJModelInterface]]\ndeps = [\"Random\", \"ScientificTypesBase\", \"StatisticalTraits\"]\ngit-tree-sha1 = \"74d7fb54c306af241c5f9d4816b735cb4051e125\"\nuuid = \"e80e1ace-859a-464e-9ed9-23947d8ae3ea\"\nversion = \"1.4.2\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[MappedArrays]]\ngit-tree-sha1 = \"e8b359ef06ec72e8c030463fe02efe5527ee5142\"\nuuid = \"dbb5928d-eab1-5f90-85c2-b9b0edb7c900\"\nversion = \"0.4.1\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[MicroCollections]]\ndeps = [\"BangBang\", \"InitialValues\", \"Setfield\"]\ngit-tree-sha1 = \"6bb7786e4f24d44b4e29df03c69add1b63d88f01\"\nuuid = \"128add7d-3638-4c79-886c-908ea0c25c34\"\nversion = \"0.1.2\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[MultivariateStats]]\ndeps = [\"Arpack\", \"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsAPI\", \"StatsBase\"]\ngit-tree-sha1 = \"7008a3412d823e29d370ddc77411d593bd8a3d03\"\nuuid = \"6f286f6a-111f-5878-ab1e-185364afe411\"\nversion = \"0.9.1\"\n\n[[NLSolversBase]]\ndeps = [\"DiffResults\", \"Distributed\", \"FiniteDiff\", \"ForwardDiff\"]\ngit-tree-sha1 = \"50310f934e55e5ca3912fb941dec199b49ca9b68\"\nuuid = \"d41bc354-129a-5804-8e4c-c37616107c6c\"\nversion = \"7.8.2\"\n\n[[NNlib]]\ndeps = [\"Adapt\", \"ChainRulesCore\", \"Compat\", \"LinearAlgebra\", \"Pkg\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a59a614b8b4ea6dc1dcec8c6514e251f13ccbe10\"\nuuid = \"872c559c-99b0-510c-b3b7-b6c96a88d5cd\"\nversion = \"0.8.4\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"b086b7ea07f8e38cf122f5016af580881ac914fe\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.7\"\n\n[[NamedArrays]]\ndeps = [\"Combinatorics\", \"DataStructures\", \"DelimitedFiles\", \"InvertedIndices\", \"LinearAlgebra\", \"Random\", \"Requires\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"2fd5787125d1a93fbe30961bd841707b8a80d75b\"\nuuid = \"86f7a689-2022-50b4-a561-43c23ac3c673\"\nversion = \"0.9.6\"\n\n[[NaturalSort]]\ngit-tree-sha1 = \"eda490d06b9f7c00752ee81cfa451efe55521e21\"\nuuid = \"c020b1a1-e9b0-503a-9c33-f039bfc54a85\"\nversion = \"1.0.0\"\n\n[[NearestNeighbors]]\ndeps = [\"Distances\", \"StaticArrays\"]\ngit-tree-sha1 = \"ded92de95031d4a8c61dfb6ba9adb6f1d8016ddd\"\nuuid = \"b8a86587-4115-5ab1-83bc-aa920d37bbce\"\nversion = \"0.4.10\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Observables]]\ngit-tree-sha1 = \"fe29afdef3d0c4a8286128d4e45cc50621b1e43d\"\nuuid = \"510215fc-4207-5dde-b226-833fc4488ee2\"\nversion = \"0.4.0\"\n\n[[OffsetArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"043017e0bdeff61cfbb7afeb558ab29536bbb5ed\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.8\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"887579a3eb005446d514ab7aeac5d1d027658b8f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+1\"\n\n[[OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ab05aa4cc89736e95915b01e7279e61b1bfe33b8\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.14+0\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[OptimBase]]\ndeps = [\"NLSolversBase\", \"Printf\", \"Reexport\"]\ngit-tree-sha1 = \"9cb1fee807b599b5f803809e85c81b582d2009d6\"\nuuid = \"87e2bd06-a317-5318-96d9-3ecbac512eee\"\nversion = \"2.0.2\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[PDMats]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"SuiteSparse\"]\ngit-tree-sha1 = \"e8185b83b9fc56eb6456200e873ce598ebc7f262\"\nuuid = \"90014a1f-27ba-587c-ab20-58faa44d9150\"\nversion = \"0.11.7\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"621f4f3b4977325b9128d5fae7a8b4829a0c2222\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.2.4\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Statistics\"]\ngit-tree-sha1 = \"8162b2f8547bc23876edd0c5181b27702ae58dce\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"3.0.0\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"bb16469fd5224100e422f0b027d26c5a25de1200\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.2.0\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"Pkg\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\", \"UnicodeFun\", \"Unzip\"]\ngit-tree-sha1 = \"88ee01b02fba3c771ac4dce0dfc4ecf0cb6fb772\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.27.5\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"d3538e7f8a790dc8903519090857ef8e1283eecd\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.5\"\n\n[[PrettyTables]]\ndeps = [\"Crayons\", \"Formatting\", \"Markdown\", \"Reexport\", \"Tables\"]\ngit-tree-sha1 = \"dfb54c4e414caa595a1f2ed759b160f5a3ddcba5\"\nuuid = \"08abe8d2-0d0c-5749-adfa-8a2ac140af0d\"\nversion = \"1.3.1\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[ProgressLogging]]\ndeps = [\"Logging\", \"SHA\", \"UUIDs\"]\ngit-tree-sha1 = \"80d919dee55b9c50e8d9e2da5eeafff3fe58b539\"\nuuid = \"33c8b6b6-d38a-422a-b730-caa89a2f386c\"\nversion = \"0.1.4\"\n\n[[ProgressMeter]]\ndeps = [\"Distributed\", \"Printf\"]\ngit-tree-sha1 = \"d7a7aef8f8f2d537104f170139553b14dfe39fe9\"\nuuid = \"92933f4c-e287-5a05-a399-4b506db050ca\"\nversion = \"1.7.2\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[QuadGK]]\ndeps = [\"DataStructures\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"78aadffb3efd2155af139781b8a8df1ef279ea39\"\nuuid = \"1fd47b50-473d-5c70-9696-f719f8f3bcdc\"\nversion = \"2.4.2\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RangeArrays]]\ngit-tree-sha1 = \"b9039e93773ddcfc828f12aadf7115b4b4d225f5\"\nuuid = \"b3c3ace0-ae52-54e7-9d0b-2c1406fd6b9d\"\nversion = \"0.3.2\"\n\n[[Ratios]]\ndeps = [\"Requires\"]\ngit-tree-sha1 = \"dc84268fe0e3335a62e315a3a7cf2afa7178a734\"\nuuid = \"c84ed2f1-dad5-54f0-aa8e-dbefe2724439\"\nversion = \"0.4.3\"\n\n[[RealDot]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"9f0a1b71baaf7650f4fa8a1d168c7fb6ee41f0c9\"\nuuid = \"c1ae055f-0cd5-4b69-90a6-9a35b1a98df9\"\nversion = \"0.1.0\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.2.1\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"dc1e451e15d90347a7decc4221842a022b011714\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.5.2\"\n\n[[RecursiveArrayTools]]\ndeps = [\"Adapt\", \"ArrayInterface\", \"ChainRulesCore\", \"DocStringExtensions\", \"FillArrays\", \"LinearAlgebra\", \"RecipesBase\", \"Requires\", \"StaticArrays\", \"Statistics\", \"ZygoteRules\"]\ngit-tree-sha1 = \"bfe14f127f3e7def02a6c2b1940b39d0dabaa3ef\"\nuuid = \"731186ca-8d62-57ce-b412-fbd966d074cd\"\nversion = \"2.26.3\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[RelocatableFolders]]\ndeps = [\"SHA\", \"Scratch\"]\ngit-tree-sha1 = \"cdbd3b1338c72ce29d9584fdbe9e9b70eeb5adca\"\nuuid = \"05181044-ff0b-4ac5-8273-598c1e38db00\"\nversion = \"0.1.3\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.3.0\"\n\n[[Rmath]]\ndeps = [\"Random\", \"Rmath_jll\"]\ngit-tree-sha1 = \"bf3188feca147ce108c76ad82c2792c57abe7b1f\"\nuuid = \"79098fc4-a85e-5d69-aa6a-4863f24498fa\"\nversion = \"0.7.0\"\n\n[[Rmath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"68db32dff12bb6127bac73c209881191bf0efbb7\"\nuuid = \"f50d1b31-88e8-58de-be2c-1cc44531875f\"\nversion = \"0.3.0+0\"\n\n[[Roots]]\ndeps = [\"CommonSolve\", \"Printf\", \"Setfield\"]\ngit-tree-sha1 = \"838b60ee62bebc794864c880a47e331e00c47505\"\nuuid = \"f2b01f46-fcfa-551c-844a-d8ac1e96c665\"\nversion = \"1.4.1\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[SciMLBase]]\ndeps = [\"ArrayInterface\", \"CommonSolve\", \"ConstructionBase\", \"Distributed\", \"DocStringExtensions\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"Logging\", \"RecipesBase\", \"RecursiveArrayTools\", \"StaticArrays\", \"Statistics\", \"Tables\", \"TreeViews\"]\ngit-tree-sha1 = \"61159e034c4cb36b76ad2926bb5bf8c28cc2fb12\"\nuuid = \"0bca4576-84f4-4d90-8ffe-ffa030f20462\"\nversion = \"1.29.0\"\n\n[[ScientificTypesBase]]\ngit-tree-sha1 = \"a8e18eb383b5ecf1b5e6fc237eb39255044fd92b\"\nuuid = \"30f210dd-8aff-4c5f-94ba-8e64358c1161\"\nversion = \"3.0.0\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[SentinelArrays]]\ndeps = [\"Dates\", \"Random\"]\ngit-tree-sha1 = \"6a2f7d70512d205ca8c7ee31bfa9f142fe74310c\"\nuuid = \"91c51154-3ec4-41a3-a24f-3f23e20d615c\"\nversion = \"1.3.12\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[Setfield]]\ndeps = [\"ConstructionBase\", \"Future\", \"MacroTools\", \"Requires\"]\ngit-tree-sha1 = \"38d88503f695eb0301479bc9b0d4320b378bafe5\"\nuuid = \"efcf1570-3423-57d1-acb7-fd33fddbac46\"\nversion = \"0.8.2\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"5ba658aeecaaf96923dce0da9e703bd1fe7666f9\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"2.1.4\"\n\n[[SplittablesBase]]\ndeps = [\"Setfield\", \"Test\"]\ngit-tree-sha1 = \"39c9f91521de844bad65049efd4f9223e7ed43f9\"\nuuid = \"171d559e-b47b-412a-8079-5efa626c420e\"\nversion = \"0.1.14\"\n\n[[Static]]\ndeps = [\"IfElse\"]\ngit-tree-sha1 = \"87e9954dfa33fd145694e42337bdd3d5b07021a6\"\nuuid = \"aedffcd0-7271-4cad-89d0-dc628f76c6d3\"\nversion = \"0.6.0\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"4f6ec5d99a28e1a749559ef7dd518663c5eca3d5\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.4.3\"\n\n[[StatisticalTraits]]\ndeps = [\"ScientificTypesBase\"]\ngit-tree-sha1 = \"271a7fea12d319f23d55b785c51f6876aadb9ac0\"\nuuid = \"64bff920-2084-43da-a3e6-9bb72801c0c9\"\nversion = \"3.0.0\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"8d7530a38dbd2c397be7ddd01a424e4f411dcc41\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.2.2\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"8977b17906b0a1cc74ab2e3a05faa16cf08a8291\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.16\"\n\n[[StatsFuns]]\ndeps = [\"ChainRulesCore\", \"InverseFunctions\", \"IrrationalConstants\", \"LogExpFunctions\", \"Reexport\", \"Rmath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"5950925ff997ed6fb3e985dcce8eb1ba42a0bbe7\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.18\"\n\n[[StatsPlots]]\ndeps = [\"AbstractFFTs\", \"Clustering\", \"DataStructures\", \"DataValues\", \"Distributions\", \"Interpolations\", \"KernelDensity\", \"LinearAlgebra\", \"MultivariateStats\", \"Observables\", \"Plots\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"StatsBase\", \"TableOperations\", \"Tables\", \"Widgets\"]\ngit-tree-sha1 = \"4d9c69d65f1b270ad092de0abe13e859b8c55cad\"\nuuid = \"f3b207a7-027a-5e70-b257-86293d7955fd\"\nversion = \"0.14.33\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"57617b34fa34f91d536eb265df67c2d4519b8b98\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.5\"\n\n[[SuiteSparse]]\ndeps = [\"Libdl\", \"LinearAlgebra\", \"Serialization\", \"SparseArrays\"]\nuuid = \"4607b0f0-06f3-5cda-b6b1-a6196a1729e9\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableOperations]]\ndeps = [\"SentinelArrays\", \"Tables\", \"Test\"]\ngit-tree-sha1 = \"e383c87cf2a1dc41fa30c093b2a19877c83e1bc1\"\nuuid = \"ab02a1b2-a7df-11e8-156e-fb1833f50b87\"\nversion = \"1.2.0\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"OrderedCollections\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"5ce79ce186cc678bbb5c5681ca3379d1ddae11a1\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.7.0\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[TerminalLoggers]]\ndeps = [\"LeftChildRightSiblingTrees\", \"Logging\", \"Markdown\", \"Printf\", \"ProgressLogging\", \"UUIDs\"]\ngit-tree-sha1 = \"62846a48a6cd70e63aa29944b8c4ef704360d72f\"\nuuid = \"5d786b92-1e48-4d6f-9151-6b4477ca9bed\"\nversion = \"0.1.5\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[Tracker]]\ndeps = [\"Adapt\", \"DiffRules\", \"ForwardDiff\", \"LinearAlgebra\", \"LogExpFunctions\", \"MacroTools\", \"NNlib\", \"NaNMath\", \"Printf\", \"Random\", \"Requires\", \"SpecialFunctions\", \"Statistics\"]\ngit-tree-sha1 = \"0874c1b5de1b5529b776cfeca3ec0acfada97b1b\"\nuuid = \"9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c\"\nversion = \"0.2.20\"\n\n[[Transducers]]\ndeps = [\"Adapt\", \"ArgCheck\", \"BangBang\", \"Baselet\", \"CompositionsBase\", \"DefineSingletons\", \"Distributed\", \"InitialValues\", \"Logging\", \"Markdown\", \"MicroCollections\", \"Requires\", \"Setfield\", \"SplittablesBase\", \"Tables\"]\ngit-tree-sha1 = \"c76399a3bbe6f5a88faa33c8f8a65aa631d95013\"\nuuid = \"28d57a85-8fef-5791-bfe6-a80928e7c999\"\nversion = \"0.4.73\"\n\n[[TreeViews]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d0d7a3fe2f30d6a7f833a5f19f7c7a5b396eae6\"\nuuid = \"a2a6695c-b41b-5b7d-aed9-dbfdeacea5d7\"\nversion = \"0.3.0\"\n\n[[Turing]]\ndeps = [\"AbstractMCMC\", \"AdvancedHMC\", \"AdvancedMH\", \"AdvancedPS\", \"AdvancedVI\", \"BangBang\", \"Bijectors\", \"DataStructures\", \"Distributions\", \"DistributionsAD\", \"DocStringExtensions\", \"DynamicPPL\", \"EllipticalSliceSampling\", \"ForwardDiff\", \"Libtask\", \"LinearAlgebra\", \"MCMCChains\", \"NamedArrays\", \"Printf\", \"Random\", \"Reexport\", \"Requires\", \"SciMLBase\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"Tracker\", \"ZygoteRules\"]\ngit-tree-sha1 = \"ef0fdc72023c4480a9372f32db88cce68b186e8a\"\nuuid = \"fce5fe82-541a-59a6-adf8-730c64b5f9a0\"\nversion = \"0.21.1\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[UnPack]]\ngit-tree-sha1 = \"387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b\"\nuuid = \"3a884ed6-31ef-47d7-9d2a-63182c4928ed\"\nversion = \"1.0.2\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[UnicodeFun]]\ndeps = [\"REPL\"]\ngit-tree-sha1 = \"53915e50200959667e78a92a418594b428dffddf\"\nuuid = \"1cfade01-22cf-5700-b092-accc4b62d6e1\"\nversion = \"0.4.1\"\n\n[[Unzip]]\ngit-tree-sha1 = \"34db80951901073501137bdbc3d5a8e7bbd06670\"\nuuid = \"41fe7b60-77ed-43a1-b4f0-825fd5a5650d\"\nversion = \"0.1.2\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4528479aa01ee1b3b4cd0e6faef0e04cf16466da\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.25.0+0\"\n\n[[Widgets]]\ndeps = [\"Colors\", \"Dates\", \"Observables\", \"OrderedCollections\"]\ngit-tree-sha1 = \"505c31f585405fc375d99d02588f6ceaba791241\"\nuuid = \"cc8bc4a8-27d6-5769-a93b-9d913e69aa62\"\nversion = \"0.6.5\"\n\n[[WoodburyMatrices]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"de67fa59e33ad156a590055375a30b23c40299d3\"\nuuid = \"efce3f68-66dc-5838-9240-27a6d6f5f9b6\"\nversion = \"0.5.5\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e45044cd873ded54b6a5bac0eb5c971392cf1927\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.2+0\"\n\n[[ZygoteRules]]\ndeps = [\"MacroTools\"]\ngit-tree-sha1 = \"8c1a8e4dfacb1fd631745552c8db35d0deb09ea0\"\nuuid = \"700de1a5-db45-46bc-99cf-38207098b444\"\nversion = \"0.2.2\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"b910cb81ef3fe6e78bf6acee440bda86fd6ae00c\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+1\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╠═ae47661e-95a2-11ec-119b-8194fe27f96e\n# ╠═8dc3dee2-a7d2-4afd-94b1-63154910a54c\n# ╠═4c8163a1-1206-47dc-bc58-1d642663a22e\n# ╠═38284326-0524-43cd-8fbe-3d228aac9bf4\n# ╠═7abe92c4-3081-429d-88b0-fd1d367fb3df\n# ╠═8948ee55-fa92-4ac5-9836-ff2640a541db\n# ╠═eb879e89-7277-4804-952b-19048874ced5\n# ╠═3a803151-2291-4798-b1f4-15e6bd1189fb\n# ╠═7cbfb55e-8984-4bee-9848-dcaacdfb1282\n# ╠═bf29e446-1cd4-4c2d-8f1f-0b91f39aa450\n# ╠═a0add249-405b-4f30-a667-c791d155d5ca\n# ╠═c5f1d281-fc40-4fdb-ae25-664ff7c99332\n# ╠═3449f76f-9dbe-4c07-898e-5b944174b374\n# ╠═d977a512-3085-4a87-a95d-7d3041402e0a\n# ╠═2288748b-9ae9-4032-a371-b2de8712cd88\n# ╠═fc76af35-ac05-418a-993d-a382c41b036f\n# ╠═2dacbdf4-dbf2-42c9-9529-007fff009c12\n# ╠═1d360be7-43a1-4a75-8d09-e229917ff815\n# ╠═923e8ca4-8f66-47b8-a2b1-b7b384416163\n# ╠═b2c73bae-7a71-49b6-8ea0-3c57dd7843ae\n# ╠═46e1c786-6abc-4f82-a1a8-04e0394aa005\n# ╠═39dc3dae-105b-490c-a5af-b8cfdc059bc0\n# ╠═7241b49c-b5d9-438a-950a-8ffcfa3d301b\n# ╠═c17062e7-42dc-4b49-8b54-2a61adf6396b\n# ╠═029632a7-e923-448b-86b9-21e5c9c6acd6\n# ╠═afb2e5ef-3d4c-439a-8574-443a09eb850d\n# ╠═fee857c0-cbb4-4a49-ab9e-59c58b92cb63\n# ╠═a56ca084-6366-4148-b600-56f797d3927e\n# ╠═57f154a5-d32c-47f0-9dec-a136b3fd44a7\n# ╠═89f26e4b-f10e-47e2-a032-b3848ec618f2\n# ╠═7bb4d1f9-bfa7-4aef-b88e-96cb6bef96ee\n# ╠═07174e20-8292-441b-ae92-51800f641e64\n# ╠═4b4cf4ee-27b8-4d25-a926-0c4e311c980f\n# ╠═08e5fe39-a598-4f06-9c5c-aa8e7ac3c4b9\n# ╠═89a7fbc5-ea56-4e8d-b50d-63456484dca0\n# ╠═461b0327-1278-4c99-90f9-b8c1b6e1a5c6\n# ╠═0246ae6c-974f-4e4e-a16f-6dce6a0cddfa\n# ╠═838f4345-c865-4712-8d39-b52777ab986d\n# ╠═44503a57-a47c-46dd-9882-c97c568b4bc7\n# ╠═974540df-328a-4855-a954-028c19f1ea56\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "20e996f0bf5ad258ed5dc6499b899add6c2ea511", "size": 58338, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "non-linear-lsq.jl", "max_stars_repo_name": "hstrey/BME-502-2022", "max_stars_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "non-linear-lsq.jl", "max_issues_repo_name": "hstrey/BME-502-2022", "max_issues_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "non-linear-lsq.jl", "max_forks_repo_name": "hstrey/BME-502-2022", "max_forks_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-15T18:19:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T18:26:08.000Z", "avg_line_length": 33.8977338757, "max_line_length": 438, "alphanum_fraction": 0.7395694059, "num_tokens": 26986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7520019075522432}}
{"text": "\"\"\"\n    initialScenario(c, d, Γ)\n\nReturns a good initial scenario ``c_0``. It is used in computation of [`evaluationProblem`](@ref)\nand [`adversarialProblem`](@ref).\n\nCheck section 5.1 _Adversarial lower bound_ of [publication](https://arxiv.org/abs/1811.06719)\nfor more information about this algorithm.\n\n# Arguments\n- `c`: vector of nonnegative nominal second stage costs.\n- `d`: vector of maximal deviations of the costs from their nominal values.\n- `Γ`: budget, or the amount of uncertainty, which can be allocated to the second stage costs\n\"\"\"\nfunction initialScenario(c, d, Γ)\n    calculateDelta(c, d, m) = collect(max(min(d[i], m - c[i]), 0) for i in 1:length(c))\n\n    ϵ = 0.001\n    l = 0\n    m = 0\n    r = maximum(map((t) -> sum(t), zip(c, d)))\n\n    δ = []\n    while abs(l - r) >= ϵ\n        m = (l + r) / 2.0\n        δ = calculateDelta(c, d, m)\n        if sum(δ) > Γ\n            r = m\n        else\n            l = m\n        end\n    end\n\n    δ = reshape(calculateDelta(c, d, m), size(c))\n    return c + δ\nend\n", "meta": {"hexsha": "d232d4e928345d203ece497a11da5b023f27c09a", "size": 1016, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/initial_scenario.jl", "max_stars_repo_name": "nikagra/RobRecSolver.jl", "max_stars_repo_head_hexsha": "f3485f84fdc63d0935da7e82a3acef7658365f1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/initial_scenario.jl", "max_issues_repo_name": "nikagra/RobRecSolver.jl", "max_issues_repo_head_hexsha": "f3485f84fdc63d0935da7e82a3acef7658365f1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/initial_scenario.jl", "max_forks_repo_name": "nikagra/RobRecSolver.jl", "max_forks_repo_head_hexsha": "f3485f84fdc63d0935da7e82a3acef7658365f1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4594594595, "max_line_length": 97, "alphanum_fraction": 0.6003937008, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7520019060603342}}
{"text": "\nfunction checkSVDDone(S::Vector, thresh::Float64)\n  N = length(S)\n  (N <= 1 || thresh < 0.0) && return (true, 1)\n  S1t = S[1] * thresh\n  start = 2\n  while start <= N\n    (S[start] < S1t) && break\n    start += 1\n  end\n  if start >= N\n    return (true, N)\n  end\n  return (false, start)\nend\n\nfunction svd_recursive(M::AbstractMatrix; thresh::Float64=1E-3, north_pass::Int=2)\n  Mr, Mc = size(M)\n  if Mr > Mc\n    V, S, U = svd_recursive(transpose(M))\n    conj!(U)\n    conj!(V)\n    return U, S, V\n  end\n\n  #rho = BLAS.gemm('N','T',-1.0,M,M) #negative to sort eigenvalues greatest to smallest\n  rho = -M * M' #negative to sort eigenvalues in decreasing order\n  D, U = eigen(Hermitian(rho), 1:size(rho, 1))\n\n  Nd = length(D)\n\n  V = M' * U\n\n  V, R = qr_positive(V)\n  for n in 1:Nd\n    D[n] = R[n, n]\n  end\n\n  (done, start) = checkSVDDone(D, thresh)\n\n  done && return U, D, V\n\n  u = view(U, :, start:Nd)\n  v = view(V, :, start:Nd)\n\n  b = u' * (M * v)\n  bu, bd, bv = svd_recursive(b; thresh=thresh, north_pass=north_pass)\n\n  u .= u * bu\n  v .= v * bv\n  view(D, start:Nd) .= bd\n\n  return U, D, V\nend\n\n# TODO: maybe move to another location?\n# Include options for other svd algorithms\nfunction polar(M::AbstractMatrix)\n  U, S, V = svd(M) # calls LinearAlgebra.svd(_)\n  return U * V', V * Diagonal(S) * V'\nend\n", "meta": {"hexsha": "9136b5fb9201d73a6ed2f2500b217fbb2e92cca8", "size": 1297, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "NDTensors/src/svd.jl", "max_stars_repo_name": "anupam-mitra/ITensors.jl", "max_stars_repo_head_hexsha": "ed8a4a45099bd55358c1dc0a7521a34a4c49c663", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 305, "max_stars_repo_stars_event_min_datetime": "2019-07-19T18:50:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:39:19.000Z", "max_issues_repo_path": "NDTensors/src/svd.jl", "max_issues_repo_name": "anupam-mitra/ITensors.jl", "max_issues_repo_head_hexsha": "ed8a4a45099bd55358c1dc0a7521a34a4c49c663", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 803, "max_issues_repo_issues_event_min_datetime": "2019-07-23T18:02:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:56:41.000Z", "max_forks_repo_path": "NDTensors/src/svd.jl", "max_forks_repo_name": "anupam-mitra/ITensors.jl", "max_forks_repo_head_hexsha": "ed8a4a45099bd55358c1dc0a7521a34a4c49c663", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 76, "max_forks_repo_forks_event_min_datetime": "2019-07-19T19:54:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T22:07:49.000Z", "avg_line_length": 20.9193548387, "max_line_length": 87, "alphanum_fraction": 0.5929067078, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.8056321819811829, "lm_q1q2_score": 0.752001898034342}}
{"text": "@with_kw struct FastTree\r\n    tolerance::Float64 = 1.0\r\nend\r\n\r\n# This is the main function\r\n\r\nfunction solve(solver::FastTree, problem::Problem)\r\n    center = problem.input.center\r\n    radius = problem.input.radius[1]\r\n    (W, b) = (problem.network.layers[1].weights, problem.network.layers[1].bias)\r\n\r\n    input = forward_affine_map(solver, W, b, problem.input)\r\n    lower, upper = low(input), high(input)\r\n    local_lower, local_upper = similar(lower), similar(lower)\r\n\r\n    k_1 = size(W, 1)\r\n\r\n    C = vcat(W, -W)\r\n    d = zeros(2k_1)\r\n\r\n    stack = Vector{Hyperrectangle}(undef, 0)\r\n    push!(stack, input)\r\n    #count = 0\r\n    while !isempty(stack)\r\n        interval = popfirst!(stack)\r\n        reach = forward_network(solver, problem.network, interval)\r\n        #count += 1\r\n        if issubset(reach, problem.output)\r\n            continue\r\n        else\r\n            if get_largest_width(interval) > solver.tolerance\r\n                sections = bisect(interval)\r\n                for i in 1:2\r\n                    local_lower = low(sections[i])\r\n                    local_upper = high(sections[i])\r\n                    d = vcat(local_upper - b, b - local_lower)\r\n\r\n                    inter = intersection(problem.input, HPolyhedron(C, d))\r\n\r\n                    if isempty(inter) == false\r\n                        push!(stack, sections[i])\r\n                    end\r\n                end\r\n            else\r\n                return BasicResult(:violated)\r\n            end\r\n        end\r\n    end\r\n    #println(\"DimTree($(solver.tolerance)): $(count)\")\r\n    return BasicResult(:holds)\r\nend\r\n\r\nfunction forward_network(solver::FastTree, nnet::Network, input::Hyperrectangle)\r\n    layers = nnet.layers\r\n    act = layers[1].activation\r\n    reach = Hyperrectangle(low = act.(low(input)), high = act.(high(input)))\r\n\r\n    for i in 2:length(layers)\r\n        reach = forward_layer(solver, layers[i], reach)\r\n    end\r\n    return reach\r\nend\r\n\r\nfunction forward_layer(solver::FastTree, L::Layer, input::Hyperrectangle)\r\n    (W, b, act) = (L.weights, L.bias, L.activation)\r\n    center = zeros(size(W, 1))\r\n    gamma  = zeros(size(W, 1))\r\n    for j in 1:size(W, 1)\r\n        node = Node(W[j,:], b[j], act)\r\n        center[j], gamma[j] = forward_node(solver, node, input)\r\n    end\r\n    return Hyperrectangle(center, gamma)\r\nend\r\n\r\nfunction forward_node(solver::FastTree, node::Node, input::Hyperrectangle)\r\n    output    = node.w' * input.center + node.b\r\n    deviation = sum(abs.(node.w) .* input.radius)\r\n    βmax = node.act(output + deviation)\r\n    βmin = node.act(output - deviation)\r\n    return ((βmax + βmin)/2, (βmax - βmin)/2)\r\nend\r\n\r\nfunction forward_affine_map(solver::FastTree, W::Matrix, b::Vector, input::Hyperrectangle)\r\n    center = W * input.center + b\r\n    radius = abs.(W) * input.radius\r\n    return Hyperrectangle(center, radius)\r\nend\r\n", "meta": {"hexsha": "6f0e69cbf0160759c14e9ca48593987a797adde0", "size": 2840, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fastTree.jl", "max_stars_repo_name": "Student2Pro/DimReduc.jl", "max_stars_repo_head_hexsha": "3843766d73d8439b69c933e7729b83650f4aaa4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fastTree.jl", "max_issues_repo_name": "Student2Pro/DimReduc.jl", "max_issues_repo_head_hexsha": "3843766d73d8439b69c933e7729b83650f4aaa4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fastTree.jl", "max_forks_repo_name": "Student2Pro/DimReduc.jl", "max_forks_repo_head_hexsha": "3843766d73d8439b69c933e7729b83650f4aaa4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2727272727, "max_line_length": 91, "alphanum_fraction": 0.5845070423, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.75199958694983}}
{"text": "using Unitful\nusing PlutoUI\nusing PhysicalConstants.CODATA2018\nusing Plots\nusing Printf\n\nk_B = BoltzmannConstant\nc_0 = SpeedOfLightInVacuum\nh = PlanckConstant\n\n\nfunction planck_spectrum(lambdas, T)\n\tres = []\n\tfor λ in lambdas\n\t\tpush!(\n\t\t\tres,\n\t\t\tustrip(\n\t\t\t\tuconvert(\n\t\t\t\t\tu\"W/m^3\", 2*pi*h*c_0^2 / λ.^5 / (exp(h*c_0/λ/k_B/T) - 1))\n\t\t\t\t)\n\t\t\t)\n\tend\n\treturn res\nend\n\nfunction add_visible_light(lambda_unit, height, alpha)\n\tbar!(\n\t\t[ustrip(uconvert(lambda_unit, 400u\"nm\"))],\n\t\t[height],\n\t\tfillcolor=[:violet],\n\t\tbar_width=ustrip(uconvert(lambda_unit, 40u\"nm\")),\n\t\tfillalpha=alpha,\n\t\tlabel=\"\",\n\t)\n\tbar!(\n\t\t[ustrip(uconvert(lambda_unit, 455u\"nm\"))],\n\t\t[height],\n\t\tfillcolor=[:blue],\n\t\tbar_width=ustrip(uconvert(lambda_unit, 70u\"nm\")),\n\t\tfillalpha=alpha,\n\t\tlabel=\"\",\n\t)\n\tbar!(\n\t\t[ustrip(uconvert(lambda_unit, 532.5u\"nm\"))],\n\t\t[height],\n\t\tfillcolor=[:green],\n\t\tbar_width=ustrip(uconvert(lambda_unit, 85u\"nm\")),\n\t\tfillalpha=alpha,\n\t\tlabel=\"\",\n\t)\n\tbar!(\n\t\t[ustrip(uconvert(lambda_unit, 580u\"nm\"))],\n\t\t[height],\n\t\tfillcolor=[:yellow],\n\t\tbar_width=ustrip(uconvert(lambda_unit, 10u\"nm\")),\n\t\tfillalpha=alpha,\n\t\tlabel=\"\",\n\t)\n\tbar!(\n\t\t[ustrip(uconvert(lambda_unit, 617.5u\"nm\"))],\n\t\t[height],\n\t\tfillcolor=[:orange],\n\t\tbar_width=ustrip(uconvert(lambda_unit, 65u\"nm\")),\n\t\tfillalpha=alpha,\n\t\tlabel=\"\",\n\t)\n\tbar!(\n\t\t[ustrip(uconvert(lambda_unit, 700u\"nm\"))],\n\t\t[height],\n\t\tfillcolor=[:red],\n\t\tbar_width=ustrip(uconvert(lambda_unit, 100u\"nm\")),\n\t\tfillalpha=alpha,\n\t\tlabel=\"\",\n\t)\nend\n\nfunction plot_stuff(T)\n    ls3 = 10 .^ (range(-2, stop=4, length=1000))\n    y = planck_spectrum(ls3.*1u\"nm\", T*1u\"K\")\n    add_visible_light(u\"nm\", maximum(y), 0.7)\n    plot!(\n        ls3,\n        #ls3,\n        y,\n        #xscale=:log10,\n        #yscale=:log10,\n        xlim=[100, 1500],\n        xlabel=\"Wellenlänge [nm]\",\n        ylabel=\"Intensität [W/m³]\",\n        label=\"$T K\",\n        color=:black,\n        grid=true,\n        lw=3\n    )\nend\n\nfor T in [3000, 6000, 12000]\n    pgfplotsx()\n    pl = plot()\n    plot_stuff(T)\n    savefig(pl, \"planck_$T.tex\")\n\n    gr()\n    pl = plot()\n    plot_stuff(T)\n    savefig(pl, \"planck_$T.png\")\n\n    pl = plot()\n    plot_stuff(T)\n    savefig(pl, \"planck_$T.svg\")\nend\n", "meta": {"hexsha": "7db96c9ac382a735f77be99395d1bf4dfba8f77f", "size": 2167, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "black_body/plot.jl", "max_stars_repo_name": "LukasNickel/astro_plots", "max_stars_repo_head_hexsha": "17a5a0d61dd06f2f30243d368d80142521b59e56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "black_body/plot.jl", "max_issues_repo_name": "LukasNickel/astro_plots", "max_issues_repo_head_hexsha": "17a5a0d61dd06f2f30243d368d80142521b59e56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "black_body/plot.jl", "max_forks_repo_name": "LukasNickel/astro_plots", "max_forks_repo_head_hexsha": "17a5a0d61dd06f2f30243d368d80142521b59e56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3482142857, "max_line_length": 62, "alphanum_fraction": 0.613290263, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144265, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7519995826660157}}
{"text": "using FractionalDiffEq, Plots, LaTeXStrings\n\ns=\"\\$D^{0.5}y(x)=1-y,\\\\ y(0)=0\\$\"\n\nfun(x, y) = 1-y\nprob=FDEProblem(fun, 0.5, 0, 5, 0.01)\nresult=solve(prob, PECE())\ntspan=collect(0:0.01:5)\n\nplot(tspan, result, title=s, linewidth=2, legend=:bottomright)", "meta": {"hexsha": "aa2489d7143e564c97706900689cbf10adb72ad1", "size": 248, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/simple_example.jl", "max_stars_repo_name": "ERIKQQY6/FractionalDiffEq.jl", "max_stars_repo_head_hexsha": "7638f3b9d31e8e1aaaca0b4328b70e4d45b169c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/simple_example.jl", "max_issues_repo_name": "ERIKQQY6/FractionalDiffEq.jl", "max_issues_repo_head_hexsha": "7638f3b9d31e8e1aaaca0b4328b70e4d45b169c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/simple_example.jl", "max_forks_repo_name": "ERIKQQY6/FractionalDiffEq.jl", "max_forks_repo_head_hexsha": "7638f3b9d31e8e1aaaca0b4328b70e4d45b169c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8, "max_line_length": 62, "alphanum_fraction": 0.6612903226, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9481545348152283, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7519870065225078}}
{"text": "using Distributions\n\np = 6\nλ = 9\n\nfunction K(t)\n    return 2λ*t / (1-2t) - p / 2 * log(1-2t)\nend\n\nfunction D1K(t)\n    return ( 4λ*t ) / (1-2t)^2 + ( 2λ + p ) / ( 1 - 2t )\nend\n\nfunction D2K(t)\n    return 2(p*(1-2t) + 4λ) / (1-2t)^3\nend\n\nfunction logf(n, t)\n    return n * (K(t) - t*D1K(t)) + 0.5log(D2K(t))\nend\n\nfunction logg(n, t)\n    return -1n * D2K(0) * t^2/2\nend\n\nfunction mh_saddle(T::Int = 10000; n::Int = 1)\n    Z = zeros(T)\n    g = Normal(0, 1 / sqrt(n*D2K(0)))\n    for t = 1:T-1\n        z = rand(g)\n        logr = logf(n, z) - logf(n, Z[t]) + logg(n, Z[t]) - logg(n, z)\n        if log(rand()) < logr \n            Z[t+1] = z\n        else\n            Z[t+1] = Z[t]\n        end\n    end\n    return Z\nend\n\nZ = mh_saddle(n = 1)\n\nfunction tau(x)\n    return ( -1p + 2x - sqrt(p^2 + 8λ * x) ) / (4x)\nend\n\nprintln(sum(Z .> tau(36.225)) / 10000)\nprintln(sum(Z .> tau(40.542)) / 10000)\nprintln(sum(Z .> tau(49.333)) / 10000)\n\n# n = 10\nZ = mh_saddle(n = 10)\n\nprintln(sum(Z .> tau(113.6667)) / 10000)\nprintln(sum(Z .> tau(102.063)) / 10000)\nprintln(sum(Z .> tau(96.19335)) / 10000)\n\n\n# n = 100\nZ = mh_saddle(n = 100)\n\nprintln(sum(Z .> tau(25.18054)) / 10000)\nprintln(sum(Z .> tau(25.52361)) / 10000)\nprintln(sum(Z .> tau(26.17395)) / 10000)\n", "meta": {"hexsha": "33da27d5d6b085cc3924617992f4f012c7f3fc73", "size": 1236, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "MH/IMH/saddle_tail.jl", "max_stars_repo_name": "szcf-weiya/MCMC", "max_stars_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-07-19T12:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T08:06:50.000Z", "max_issues_repo_path": "MH/IMH/saddle_tail.jl", "max_issues_repo_name": "szcf-weiya/MCMC", "max_issues_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-02-03T15:08:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-05T15:41:39.000Z", "max_forks_repo_path": "MH/IMH/saddle_tail.jl", "max_forks_repo_name": "szcf-weiya/MCMC", "max_forks_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-07-19T12:50:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T08:06:52.000Z", "avg_line_length": 19.0153846154, "max_line_length": 70, "alphanum_fraction": 0.5202265372, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545377452442, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7519870042096268}}
{"text": "# example showing how to do maximum likelihood estimation\n# for data generated by CLRM with normality\n# sample size\nusing Econometrics, Statistics\nn = 10\n\n# random true parameters\ntheta = [1.0,-1.0,0.0,1.0]\nb = theta[1:3]\nsig = theta[4]\n\n# generate random data\nx = [ones(n,1) rand(n,2)]\ne = sig*randn(n,1)\ny = x*b + e\n\n# do ML: note minus sign, also, do \"edit(normal)\" to see what's done\nobj = theta -> -mean(normal(theta, y, x))\nthetahat, junk, junk = fminunc(obj, theta)\n\n# results\nprintln(\"the true parameters: \", theta)\nprintln(\"the ML estimates: \", thetahat)\nprintln(\"the OLS estimates: \", inv(x'*x)*x'*y)\n", "meta": {"hexsha": "afc087ea44c190329ac5b2edc43398dc7db97463", "size": 611, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/MLE/NormalExample.jl", "max_stars_repo_name": "Vkamalvanshi/Econometrics", "max_stars_repo_head_hexsha": "9bf91e418e8f623a02ee6091af5de29853aecfab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "Examples/MLE/NormalExample.jl", "max_issues_repo_name": "Vkamalvanshi/Econometrics", "max_issues_repo_head_hexsha": "9bf91e418e8f623a02ee6091af5de29853aecfab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "Examples/MLE/NormalExample.jl", "max_forks_repo_name": "Vkamalvanshi/Econometrics", "max_forks_repo_head_hexsha": "9bf91e418e8f623a02ee6091af5de29853aecfab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 24.44, "max_line_length": 68, "alphanum_fraction": 0.6808510638, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9674102542943773, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.7519678663435853}}
{"text": "using Plots\n\n# hyperbola.png --------------------------------------------------------------------------\n\nparamlen=1.5\nt0=0.6*paramlen\nran = LinRange(-paramlen, paramlen, 100)\n\n# Hyperbola\nplot(framestyle=:origin, aspect_ratio=:equal)\nplot!(cosh, sinh, ran, color=:black, lab=\"\")\nplot!(t -> -cosh(t), sinh, ran, color=:black, lab=\"\")\n\n# Guides\nplot!(t -> t, t -> t, -sinh(last(ran)):0.01:sinh(last(ran)), style=:dash, color=:red, lab=\"\")\nplot!(t -> t, t -> -t, -sinh(last(ran)):0.01:sinh(last(ran)), style=:dash, color=:red, lab=\"\")\nplot!([(0, sinh(t0)), (cosh(t0), sinh(t0))], style=:dot, color=:black, lab=\"\")\nplot!([(cosh(t0), 0), (cosh(t0), sinh(t0))], style=:dot, color=:black, lab=\"\")\n\n# Annotations\nannotate!(cosh(t0)+0.1, sinh(t0)/2, Plots.text(\"sinh t\", :left, 8))\nannotate!(cosh(t0)/2, sinh(t0)+0.1, Plots.text(\"cosh t\", :up, 8))\nsavefig(\"hyperbola.png\")\n\n# hyperbolic-paraboloid.png -------------------------------------------------------------\n\nx = LinRange(-10, 10, 100)\ny = LinRange(-10, 10, 100)\nz(x, y) = x^2-y^2\nplot(x, y, z, st=:surface)\nsavefig(\"hyperbolic-paraboloid.png\")\n\n# image-parametrization-Y.png ------------------------------------------------------------\n\nx = LinRange(-10, 10, 100)\ny = LinRange(-10, 10, 100)\nz(x, y) = abs(y) <= abs(x) ? x^2-y^2 : NaN\nplot(x, y, z, st=:surface)\nsavefig(\"image-parametrization-Y.png\")\n\n", "meta": {"hexsha": "a929edba0afcbe47a0393ff4986ed4a47149fd8f", "size": 1349, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "images/hyperbola-images-script.jl", "max_stars_repo_name": "useredsa/exercises-surfaces-geometry", "max_stars_repo_head_hexsha": "19b17a0a4c729e3a99f51ea285ae1539352c742b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-25T03:04:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-25T03:04:15.000Z", "max_issues_repo_path": "images/hyperbola-images-script.jl", "max_issues_repo_name": "useredsa/introductory-exercises-of-differential-geometry", "max_issues_repo_head_hexsha": "19b17a0a4c729e3a99f51ea285ae1539352c742b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "images/hyperbola-images-script.jl", "max_forks_repo_name": "useredsa/introductory-exercises-of-differential-geometry", "max_forks_repo_head_hexsha": "19b17a0a4c729e3a99f51ea285ae1539352c742b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9024390244, "max_line_length": 94, "alphanum_fraction": 0.5329873981, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8376199694135333, "lm_q1q2_score": 0.7519275031176289}}
{"text": "import MultipleShootingPEM\nms = MultipleShootingPEM\nusing Plots\npyplot()\nusing LaTeXStrings\n\n# Generate Data\nk0 = 1\nN = 200\nθ_opt = 3.78\nfunction logistic_f(x_next, x, k, θ)\n    x_next .=  θ*x - θ*x.^2\n    return\nend\nfunction logistic_g(y, x, k, θ)\n    y .= x\n    return\nend\n# Define initial conditions\nx0 = [0.5]\ny = Vector{Vector{Float64}}(N)\nfor i = 1:length(y)\n    y[i] = zeros(1)\nend\nx_final = ms.simulate_space_state!(y, logistic_f, logistic_g,\n                                   x0, (k0, k0+N-1), (θ_opt,))\n\n# Multiple shooting error estimation\nM = 40\nk0_list = collect(k0:Int(N//M):k0+N-1)\nx0_list = y[k0_list]\nlist_procs = ones(Int, M)\n\n# Define polynomial model\n# f(x) = θ1*x - θ1*x^2\n@everywhere function f(y, dx, dθ, x, k, θ)\n    y .= θ[1]*x - θ[1]*x.^2\n    dx .= θ[1] - 2*θ[1]*x\n    dθ .=  x-x.^2\n    return\nend\n# g(x) = x\n@everywhere function g(y, dx, dθ, x, k, θ)\n    y .= x\n    dx .= 1\n    dθ .= 0\n    return\nend\n\nθ = 0\nmultiple_shoot = ms.MultipleShooting(f, g, x0_list,\n                                     y, k0_list, θ,\n                                     list_procs)\nms.cost_function(multiple_shoot)\n\n# Get cost function\nθ_min = 2.0\nθ_delta = 0.01\nθ_max = 4.0\nθ_range = θ_min:θ_delta:θ_max\nnpoints = length(θ_range)\ncost = Vector{Float64}(npoints)\ni = 1\nfor θ = θ_range\n    ms.new_simulation!(multiple_shoot, x0_list, [θ])\n    cost[i] = ms.cost_function(multiple_shoot)\n    i += 1\nend\n\nnrealiz = 20\ncost_matrix = Matrix{Float64}(npoints, nrealiz)\nsrand(1)\nj = 1\nfor j = 1:nrealiz\n    σ = 0.005\n    x0_list_modified = copy(x0_list)\n    for i = 1:M\n        x0_list_modified .+= σ*randn()\n    end\n    i = 1\n    for θ = θ_range\n        ms.new_simulation!(multiple_shoot, x0_list_modified, [θ])\n        cost_matrix[i, j] = ms.cost_function(multiple_shoot)\n        i += 1\n    end\n    j += 1\nend\n\n\n\n# Get solver solution\nsrand(4)\nθ_list = Float64[]\ncost_list = Float64[]\nres_list = []\nfor θp = 3.2:0.05:3.9\n    σ = 0.002\n    x0_list_modified = copy(x0_list)\n    for i = 1:M\n        x0_list_modified .+= σ*randn()\n    end\n    θ0 = [θp]\n    opt = ms.OptimizationProblem(f, g, x0_list_modified, y,\n                                 k0_list, θ0, list_procs)\n\n    res = ms.solve(opt, options=Dict(\"gtol\" => 1e-10,\n                                     \"xtol\" => 1e-10,\n                                     \"maxiter\" => 2000))\n    θ_est = res[\"x\"][1]\n    cost_est = res[\"fun\"]\n\n    push!(θ_list, θ_est)\n    push!(cost_list, cost_est)\n    push!(res_list, res)\nend\n\nplot(θ_range, cost, color=:black, lw=2, legend=false, grid=false,\n     xlims=[θ_min, θ_max], xguide=L\"\\theta\", yguide=L\"V(\\theta)\")\nplot!(θ_range, cost_matrix, color=:blue, linealpha=0.2)\nscatter!(θ_list, cost_list, marker=:c, color=:green, markersize=5)\nvline!([θ_opt], ls=:dot, color=:red)\n\n# savefig(\"ratio4_ms_logistic.tex\")\n\n# Evaluate solver performance\nniter_list = [res[\"niter\"] for res in res_list]\nmedian(niter_list)\nmaximum(niter_list)\nminimum(niter_list)\n\nnfun_list = [res[\"nfev\"] for res in res_list]\nmedian(nfun_list)\nmaximum(nfun_list)\nminimum(nfun_list)\n\nexect_list = [res[\"execution_time\"] for res in res_list]\nmedian(exect_list)\nmaximum(exect_list)\nminimum(exect_list)\n", "meta": {"hexsha": "1b97b83cadc08da32173e106bb91dabc176f8fbb", "size": 3158, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ex1/ex1_fig3.jl", "max_stars_repo_name": "antonior92/MultipleShootingPEM.jl", "max_stars_repo_head_hexsha": "cbff5ad0faf71b205e1ccf03b26f974ff5626c4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-10T13:37:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-10T13:37:51.000Z", "max_issues_repo_path": "examples/ex1/ex1_fig3.jl", "max_issues_repo_name": "antonior92/MultipleShootingPEM.jl", "max_issues_repo_head_hexsha": "cbff5ad0faf71b205e1ccf03b26f974ff5626c4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ex1/ex1_fig3.jl", "max_forks_repo_name": "antonior92/MultipleShootingPEM.jl", "max_forks_repo_head_hexsha": "cbff5ad0faf71b205e1ccf03b26f974ff5626c4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5571428571, "max_line_length": 66, "alphanum_fraction": 0.6073464218, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7519274995520736}}
{"text": "# SEIR Model\n\nusing DifferentialEquations\n\n\nbeta = 0.215; gamma = 0.07; N = 7000;\nalpha = 0.25;\n\n\"\"\"SEIR Model\nExtension of the basic SIR model\n\n\"\"\"\nfunction SEIR!(du,u,p,t)\n    du[1] = -beta* u[1]/N*u[3]\n    du[2] = beta*u[1]/N*u[3] - alpha*u[2]\n    du[3] = alpha* u[2] - gamma*u[3]\n    du[4] = gamma*u[3]\nend\n   \n   \n   u0 = [N-15.0;15.0;0.0;0.0]\n   tspan = (0.0,100.0)\n   prob = ODEProblem(SEIR!,u0,tspan)\n   sol = solve(prob)\n   \n   plot(sol)\n   ", "meta": {"hexsha": "13a09e14d2dd27d91178845195e4efd90553560f", "size": 450, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SEIR-model.jl", "max_stars_repo_name": "rubsc/COVID01.jl", "max_stars_repo_head_hexsha": "bd2f96439c8397b60598a259c9f397abab4c6793", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SEIR-model.jl", "max_issues_repo_name": "rubsc/COVID01.jl", "max_issues_repo_head_hexsha": "bd2f96439c8397b60598a259c9f397abab4c6793", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SEIR-model.jl", "max_forks_repo_name": "rubsc/COVID01.jl", "max_forks_repo_head_hexsha": "bd2f96439c8397b60598a259c9f397abab4c6793", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.6666666667, "max_line_length": 41, "alphanum_fraction": 0.5466666667, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.7519067704068676}}
{"text": "function betaBinomial(prior::P, bernoulliTrials::Vector{Int}) where {P <: Beta}\n  n = length(bernoulliTrials)\n  successes = sum(bernoulliTrials)\n  failures = n - successes\n  a = prior.α + successes\n  b = prior.β + failures\n  return Beta(a, b)\nend\n#betaBinomial(Beta(2,3), [1,0,1,1])\n\n", "meta": {"hexsha": "354278be16e29f6f8e11c0c3fe1be775df0b0ca4", "size": 284, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MCMC/Conjugate.jl", "max_stars_repo_name": "luiarthur/cytof5", "max_stars_repo_head_hexsha": "6b4df5e9fd94bfd586e96579b8c618fdf6f913ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-30T21:56:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-30T21:56:52.000Z", "max_issues_repo_path": "src/MCMC/Conjugate.jl", "max_issues_repo_name": "luiarthur/cytof5", "max_issues_repo_head_hexsha": "6b4df5e9fd94bfd586e96579b8c618fdf6f913ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2018-12-20T18:22:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-24T03:13:32.000Z", "max_forks_repo_path": "src/MCMC/Conjugate.jl", "max_forks_repo_name": "luiarthur/cytof5", "max_forks_repo_head_hexsha": "6b4df5e9fd94bfd586e96579b8c618fdf6f913ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8181818182, "max_line_length": 79, "alphanum_fraction": 0.6866197183, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.951142225532629, "lm_q2_score": 0.7905303162021597, "lm_q1q2_score": 0.7519067643035351}}
{"text": "using LinearAlgebra\n\nA = [1 1 -1; -2 0 1; 0 2 1]\nB = inv(A)\nE = B*A\n\nprintln(\"A^{-1}=\", B)\nprintln(\"A*A^{-1}=\", E)", "meta": {"hexsha": "566a879b1e9d4c967e0f99af5e2dadfb64291fe9", "size": 114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear_algebra/inverse_matrix.jl", "max_stars_repo_name": "nocotan/numerical_calculus.jl", "max_stars_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-07T06:26:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T06:21:01.000Z", "max_issues_repo_path": "linear_algebra/inverse_matrix.jl", "max_issues_repo_name": "nocotan/numerical_calculus.jl", "max_issues_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-01-10T08:22:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-08T13:31:00.000Z", "max_forks_repo_path": "linear_algebra/inverse_matrix.jl", "max_forks_repo_name": "nocotan/numerical_calculus.jl", "max_forks_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-10T05:59:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T13:22:34.000Z", "avg_line_length": 14.25, "max_line_length": 27, "alphanum_fraction": 0.5, "num_tokens": 57, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9511422172230211, "lm_q2_score": 0.7905303162021597, "lm_q1q2_score": 0.7519067577345382}}
{"text": "function f753(N::Int, K = 0, n₃ = 0, n₅ = 0, n₇ = 0)\n    if K > N\n        return 0\n    else\n        result = (n₃ > 0 && n₅ > 0 && n₇ > 0) +\n            f753(N, 10K + 3, n₃ + 1, n₅, n₇) + \n            f753(N, 10K + 5, n₃, n₅ + 1, n₇) + \n            f753(N, 10K + 7, n₃, n₅, n₇ + 1)\n        return result\n    end\nend\n\nfunction main()\n    N = parse(Int, readline())\n    println(f753(N))\nend\n\nmain()\n", "meta": {"hexsha": "94f58701949146281656599bdc637225c606f180", "size": 396, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/chapter04/nicetak/abc114_c.jl", "max_stars_repo_name": "tokuma09/algorithm_problems", "max_stars_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-07T15:46:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T15:46:58.000Z", "max_issues_repo_path": "problems/chapter04/nicetak/abc114_c.jl", "max_issues_repo_name": "tokuma09/algorithm_problems", "max_issues_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-06-05T14:16:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-10T07:08:28.000Z", "max_forks_repo_path": "problems/chapter04/nicetak/abc114_c.jl", "max_forks_repo_name": "tokuma09/algorithm_problems", "max_forks_repo_head_hexsha": "58534620df73b230afbeb12de126174362625a78", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8421052632, "max_line_length": 52, "alphanum_fraction": 0.4318181818, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.751894017212513}}
{"text": "function adjacency_matrix(adj::AbstractMatrix, T::DataType=eltype(adj))\n    m, n = size(adj)\n    (m == n) || throw(DimensionMismatch(\"adjacency matrix is not a square matrix: ($m, $n)\"))\n    T.(adj)\nend\n\nfunction degrees(adj::AbstractMatrix; dir::Symbol=:out)\n    if issymmetric(adj)\n        d = vec(sum(adj, dims=1))\n    else\n        if dir == :out\n            d = vec(sum(adj, dims=1))\n        elseif dir == :in\n            d = vec(sum(adj, dims=2))\n        elseif dir == :both\n            d = vec(sum(adj, dims=1)) + vec(sum(adj, dims=2))\n        else\n            throw(DomainError(dir, \"invalid argument, only accept :in, :out and :both\"))\n        end\n    end\n    d\nend\n\ndegrees(adj::AbstractMatrix, T::DataType; dir::Symbol=:out) = degrees(T.(adj); dir=dir)\n\n\"\"\"\n    degree_matrix(g[, T]; dir=:out)\n\nDegree matrix of graph `g`. Return a matrix which contains degrees of each vertex in its diagonal.\nThe values other than diagonal are zeros.\n\n# Arguments\n\n- `g`: should be a adjacency matrix, `FeaturedGraph`, `SimpleGraph`, `SimpleDiGraph` (from Graphs)\n    or `SimpleWeightedGraph`, `SimpleWeightedDiGraph` (from SimpleWeightedGraphs).\n- `T`: result element type of degree vector; default is the element type of `g` (optional).\n- `dir`: direction of degree; should be `:in`, `:out`, or `:both` (optional).\n\n# Examples\n\n```jldoctest\njulia> using GraphLaplacians\n\njulia> m = [0 1 1; 1 0 0; 1 0 0];\n\njulia> GraphLaplacians.degree_matrix(m)\n3×3 LinearAlgebra.Diagonal{Int64, Vector{Int64}}:\n 2  ⋅  ⋅\n ⋅  1  ⋅\n ⋅  ⋅  1\n```\n\"\"\"\nfunction degree_matrix(adj::AbstractMatrix, T::DataType=eltype(adj);\n                       dir::Symbol=:out, squared::Bool=false, inverse::Bool=false)\n    d = degrees(adj, T, dir=dir)\n    squared && (d .= sqrt.(d))\n    inverse && (d .= inv.(d); replace!(d, typemax(T)=>zero(T)))\n    return Diagonal(T.(d))\nend\n\n\"\"\"\n    laplacian_matrix(g[, T]; dir=:out)\n\nLaplacian matrix of graph `g`.\n\n# Arguments\n\n- `g`: should be a adjacency matrix, `FeaturedGraph`, `SimpleGraph`, `SimpleDiGraph` (from Graphs)\n    or `SimpleWeightedGraph`, `SimpleWeightedDiGraph` (from SimpleWeightedGraphs).\n- `T`: result element type of degree vector; default is the element type of `g` (optional).\n- `dir`: direction of degree; should be `:in`, `:out`, or `:both` (optional).\n\"\"\"\nGraphs.laplacian_matrix(adj::AbstractMatrix, T::DataType=eltype(adj); dir::Symbol=:out) =\n    degree_matrix(adj, T, dir=dir) - SparseMatrixCSC(T.(adj))\n\n\"\"\"\n    normalized_laplacian(g[, T]; dir=:both, selfloop=false)\n\nNormalized Laplacian matrix of graph `g`.\n\n# Arguments\n\n- `g`: should be a adjacency matrix, `FeaturedGraph`, `SimpleGraph`, `SimpleDiGraph` (from Graphs)\n    or `SimpleWeightedGraph`, `SimpleWeightedDiGraph` (from SimpleWeightedGraphs).\n- `T`: result element type of degree vector; default is the element type of `g` (optional).\n- `selfloop`: adding self loop while calculating the matrix (optional).\n- `dir`: direction of graph; should be `:in` or `:out` (optional).\n\"\"\"\nfunction normalized_laplacian(adj::AbstractMatrix, T::DataType=eltype(adj);\n                              dir::Symbol=:both, selfloop::Bool=false)\n    if dir == :both\n        selfloop && (adj += I)\n        inv_sqrtD = degree_matrix(adj, T, dir=:both, squared=true, inverse=true)\n        return T.(I - inv_sqrtD * adj * inv_sqrtD)\n    else\n        return T.(I - degree_matrix(adj, T, dir=dir, inverse=true) * adj)\n    end\nend\n\n@doc raw\"\"\"\n    scaled_laplacian(g[, T])\n\nScaled Laplacien matrix of graph `g`,\ndefined as ``\\hat{L} = \\frac{2}{\\lambda_{max}} L - I`` where ``L`` is the normalized Laplacian matrix.\n\n# Arguments\n\n- `g`: should be a adjacency matrix, `FeaturedGraph`, `SimpleGraph`, `SimpleDiGraph` (from Graphs)\n    or `SimpleWeightedGraph`, `SimpleWeightedDiGraph` (from SimpleWeightedGraphs).\n- `T`: result element type of degree vector; default is the element type of `g` (optional).\n\"\"\"\nfunction scaled_laplacian(adj::AbstractMatrix, T::DataType=eltype(adj))\n    @assert issymmetric(adj) \"scaled_laplacian only works with symmetric matrices\"\n    E = eigen(Symmetric(Array(adj))).values\n    T(2. / maximum(E)) * normalized_laplacian(adj, T) - I\nend\n\n\"\"\"\n    random_walk_laplacian(g[, T]; dir=:out)\n\nRandom walk normalized Laplacian matrix of graph `g`.\n\n# Arguments\n\n- `g`: should be a adjacency matrix, `FeaturedGraph`, `SimpleGraph`, `SimpleDiGraph` (from Graphs)\n    or `SimpleWeightedGraph`, `SimpleWeightedDiGraph` (from SimpleWeightedGraphs).\n- `T`: result element type of degree vector; default is the element type of `g` (optional).\n- `dir`: direction of degree; should be `:in`, `:out`, or `:both` (optional).\n\"\"\"\nfunction random_walk_laplacian(adj::AbstractMatrix, T::DataType=eltype(adj); dir::Symbol=:out)\n    d = degrees(adj, dir=dir)\n    inv_d = 1 ./ d\n    replace!(inv_d, typemax(float(T)) => zero(float(T)))  # avoid degree to be zero\n    P = Diagonal(inv_d) * adj\n    SparseMatrixCSC(T.(I - P))\nend\n\n\"\"\"\n    signless_laplacian(g[, T]; dir=:out)\n\nSignless Laplacian matrix of graph `g`.\n\n# Arguments\n\n- `g`: should be a adjacency matrix, `FeaturedGraph`, `SimpleGraph`, `SimpleDiGraph` (from Graphs)\n    or `SimpleWeightedGraph`, `SimpleWeightedDiGraph` (from SimpleWeightedGraphs).\n- `T`: result element type of degree vector; default is the element type of `g` (optional).\n- `dir`: direction of degree; should be `:in`, `:out`, or `:both` (optional).\n\"\"\"\nsignless_laplacian(adj::AbstractMatrix, T::DataType=eltype(adj); dir::Symbol=:out) =\n    degree_matrix(adj, T, dir=dir) + SparseMatrixCSC(T.(adj))\n", "meta": {"hexsha": "32d255b738ac30baea5c8a96e152bb35a63fe356", "size": 5509, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/adjmat.jl", "max_stars_repo_name": "yuehhua/GraphLaplacians.jl", "max_stars_repo_head_hexsha": "19e4a0cc84e5864ee3e48b2c50a6da00ab358540", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-07T02:43:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-21T05:15:39.000Z", "max_issues_repo_path": "src/adjmat.jl", "max_issues_repo_name": "yuehhua/GraphLaplacians.jl", "max_issues_repo_head_hexsha": "19e4a0cc84e5864ee3e48b2c50a6da00ab358540", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-11-26T07:19:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-01T06:58:54.000Z", "max_forks_repo_path": "src/adjmat.jl", "max_forks_repo_name": "yuehhua/GraphLaplacians.jl", "max_forks_repo_head_hexsha": "19e4a0cc84e5864ee3e48b2c50a6da00ab358540", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2434210526, "max_line_length": 102, "alphanum_fraction": 0.6667271737, "num_tokens": 1603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7518940129392959}}
{"text": "\"\"\"\n    Dirac(x)\n\nA *Dirac distribution* is parameterized by its only value `x`, and takes its value with probability 1.\n\n```math\nP(X = \\\\hat{x}) = \\\\begin{cases}\n1 & \\\\quad \\\\text{for } \\\\hat{x} = x, \\\\\\\\\n0 & \\\\quad \\\\text{for } \\\\hat{x} \\\\neq x.\n\\\\end{cases}\n```\n\n```julia\nDirac(2.5)   # Dirac distribution with value x = 2.5\n```\n\nExternal links:\n\n* [Dirac measure on Wikipedia](http://en.wikipedia.org/wiki/Dirac_measure)\n\"\"\"\nstruct Dirac{T} <: DiscreteUnivariateDistribution\n    value::T\nend\n\nBase.eltype(::Type{Dirac{T}}) where {T} = T\n\ninsupport(d::Dirac, x::Real) = x == d.value\nminimum(d::Dirac) = d.value\nmaximum(d::Dirac) = d.value\nsupport(d::Dirac) = (d.value,)\n\n#### Properties\nmean(d::Dirac) = d.value\nvar(d::Dirac{T}) where {T} = zero(T)\n\nmode(d::Dirac) = d.value\n\nentropy(d::Dirac{T}) where {T} = zero(T)\n\n#### Evaluation\n\npdf(d::Dirac, x::Real) = insupport(d, x) ? 1.0 : 0.0\nlogpdf(d::Dirac, x::Real) = insupport(d, x) ? 0.0 : -Inf\n\ncdf(d::Dirac, x::Real) = x < d.value ? 0.0 : 1.0\ncdf(d::Dirac, x::Integer) = x < d.value ? 0.0 : 1.0\n\nquantile(d::Dirac{T}, p::Real) where {T} = 0 <= p <= 1 ? d.value : T(NaN)\n\nmgf(d::Dirac, t) = exp(t * d.value)\ncf(d::Dirac, t) = cis(t * d.value)\n\n#### Sampling\n\nrand(rng::AbstractRNG, d::Dirac) = d.value\n", "meta": {"hexsha": "108a5609b201ec72f9a1b4c9421e572bef68b411", "size": 1256, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/discrete/dirac.jl", "max_stars_repo_name": "davibarreira/Distributions.jl", "max_stars_repo_head_hexsha": "a0cb0969d755872586ec79e985503f03beae9d08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/discrete/dirac.jl", "max_issues_repo_name": "davibarreira/Distributions.jl", "max_issues_repo_head_hexsha": "a0cb0969d755872586ec79e985503f03beae9d08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/discrete/dirac.jl", "max_forks_repo_name": "davibarreira/Distributions.jl", "max_forks_repo_head_hexsha": "a0cb0969d755872586ec79e985503f03beae9d08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4285714286, "max_line_length": 102, "alphanum_fraction": 0.6003184713, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.7518940062847501}}
{"text": "using Revise\n\tusing SparseArrays, LinearAlgebra, DiffEqOperators, Setfield, Parameters\n\tusing PseudoArcLengthContinuation\n\tusing Plots\n\tconst PALC = PseudoArcLengthContinuation\n################################################################################\n# case of the SH equation\nnorminf(x) = norm(x, Inf64)\nNx = 200; Lx = 30.;\nX = -Lx .+ 2Lx/Nx*(0:Nx-1) |> collect\nhx = X[2]-X[1]\n\nQ = Neumann0BC(hx)\n# Q = Dirichlet0BC(hx |> typeof)\nDxx = sparse(CenteredDifference(2, 2, hx, Nx) * Q)[1]\nLsh = -(I + Dxx)^2\n\nfunction R_SH(u, par)\n\t@unpack p, b, L1 = par\n\tout = similar(u)\n\tout .= L1 * u .- p .* u .+ b .* u.^3 - u.^5\nend\n\nJac_sp = (u, par) -> par.L1 + spdiagm(0 => -par.p .+ 3*par.b .* u.^2 .- 5 .* u.^4)\n\nsol0 = 1.65cos.(X) .* exp.(-X.^2/(2*5^2))\n\tparSH = (p = 0.7, b = 2., L1 = Lsh)\n\toptnew = PALC.NewtonPar(verbose = true, tol = 1e-12)\n\t# allocations 26.47k, 0.038s, tol = 1e-10\n\tsol1, hist, flag = @time PALC.newton(\n\t\tR_SH, Jac_sp,\n\t\tsol0, parSH, optnew, normN = norminf)\n\tPlots.plot(X, sol1)\n\n\nopts = PALC.ContinuationPar(dsmin = 0.0005, dsmax = 0.0055, ds = -0.001,\n\t\tnewtonOptions = optnew,\n\t\tmaxSteps = 1200,\n\t\ttheta = .6, plotEveryNsteps = 200, computeEigenValues = true)\n\tbr, u1 = @time PALC.continuation(R_SH, Jac_sp, sol1, parSH, (@lens _.p), opts,\n\t\tverbosity = 2,\n\t\tplot = true,\n\t\t# tangentAlgo = BorderedPred(),\n\t\tlinearAlgo  = MatrixBLS(),\n\t\tplotSolution = (x, p;kwargs...)->(plot!(X, x; ylabel=\"solution\", label=\"\", kwargs...)), normC = norminf)\n\tbrs = [br]\n#####################################################\n# case with computation of eigenvalues\n# optnew = PALC.NewtonPar(linsolver = Default(),\teigsolver = eig_KrylovKit{Float64}())\nplot(brs, label = \"\")\n\n\n####################################################################################################\nsol0 = 1.1cos.(X) .* exp.(-0X.^2/(2*5^2))\n\toptnew = PALC.NewtonPar(verbose = true, tol = 1e-12)\n\t# allocations 26.47k, 0.038s, tol = 1e-10\n\tsol1, hist, flag = @time PALC.newton(\n\tR_SH, Jac_sp,\n\tsol0, (@set parSH.p = -1.95), optnew)\n\tPlots.plot(X, sol1)\n\n\nopts = PALC.ContinuationPar(dsmin = 0.001, dsmax = 0.005, ds = 0.001,\n\t\tnewtonOptions = setproperties(optnew; maxIter = 30, tol = 1e-11), pMin = -2.,\n\t\tmaxSteps = 1000, theta = .4, plotEveryNsteps = 200, computeEigenValues = true)\n\t@assert opts.a<=1.5 \"sinon ca peut changer le sens du time step\"\n\n\tbr, u1 = @time PALC.continuation(\n\t\tR_SH, Jac_sp, sol1, (@set parSH.p = -1.), (@lens _.p), opts,\n\t\tverbosity = 2,\n\t\tplot = true,\n\t\t# tangentAlgo = BorderedPred(),\n\t\t# linearAlgo  = MatrixBLS(),\n\t\tplotSolution = (x, p;kwargs...)->(plot!(X, x; ylabel=\"solution\", label=\"\", kwargs...)))\n\npush!(brs, br)\n\nplot(brs)\n", "meta": {"hexsha": "355fb13f0e4b4a48aab8919e74974308821d1db6", "size": 2650, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/SHpde_snaking.jl", "max_stars_repo_name": "antoine-levitt/PseudoArcLengthContinuation.jl", "max_stars_repo_head_hexsha": "b6eef7bef6e6cc2e23b3e4eee5547b6e89c6827e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/SHpde_snaking.jl", "max_issues_repo_name": "antoine-levitt/PseudoArcLengthContinuation.jl", "max_issues_repo_head_hexsha": "b6eef7bef6e6cc2e23b3e4eee5547b6e89c6827e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/SHpde_snaking.jl", "max_forks_repo_name": "antoine-levitt/PseudoArcLengthContinuation.jl", "max_forks_repo_head_hexsha": "b6eef7bef6e6cc2e23b3e4eee5547b6e89c6827e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5443037975, "max_line_length": 106, "alphanum_fraction": 0.5773584906, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7518939954228547}}
{"text": "uniform(u::Real) = 1//2 * float64(abs(u) <= 1.0)\nuniform_unnormalized(u::Real) = 1//2 * float64(abs(u) <= 1.0)\nBase.@vectorize_1arg Real uniform\nBase.@vectorize_1arg Real uniform_unnormalized\n\ntriangular(u::Real) = (1 - abs(u)) * float64(abs(u) <= 1.0)\ntriangular_unnormalized(u::Real) = (1 - abs(u)) * float64(abs(u) <= 1.0)\nBase.@vectorize_1arg Real triangular\nBase.@vectorize_1arg Real triangular_unnormalized\n\nepanechnikov(u::Real) = 3//4 * (1 - u^2) * float64(abs(u) <= 1.0)\nepanechnikov_unnormalized(u::Real) = (1 - u^2) * float64(abs(u) <= 1.0)\nBase.@vectorize_1arg Real epanechnikov\nBase.@vectorize_1arg Real epanechnikov_unnormalized\n\nbiweight(u::Real) = 15//16 * (1 - u^2)^2 * float64(abs(u) <= 1.0)\nbiweight_unnormalized(u::Real) = (1 - u^2)^2 * float64(abs(u) <= 1.0)\nBase.@vectorize_1arg Real biweight\nBase.@vectorize_1arg Real biweight_unnormalized\n\ntriweight(u::Real) = 35//32 * (1 - u^2)^3 * float64(abs(u) <= 1.0)\ntriweight_unnormalized(u::Real) = (1 - u^2)^3 * float64(abs(u) <= 1.0)\nBase.@vectorize_1arg Real triweight\nBase.@vectorize_1arg Real triweight_unnormalized\n\ntricube(u::Real) = 70//81 * (1 - abs(u)^3)^3 * float64(abs(u) <= 1.0)\ntricube_unnormalized(u::Real) = (1 - abs(u)^3)^3 * float64(abs(u) <= 1.0)\nBase.@vectorize_1arg Real tricube\nBase.@vectorize_1arg Real tricube_unnormalized\n\ngaussian(u::Real) = (1 / sqrt(2 * pi)) *  exp(-1//2 * u^2)\ngaussian_unnormalized(u::Real) = exp(-1//2 * u^2)\nBase.@vectorize_1arg Real gaussian\nBase.@vectorize_1arg Real gaussian_unnormalized\n\ncosine(u::Real) = (pi / 4) * cos((pi / 2) * u) * float64(abs(u) <= 1.0)\ncosine_unnormalized(u::Real) = cos((pi / 2) * u) * float64(abs(u) <= 1.0)\nBase.@vectorize_1arg Real cosine\nBase.@vectorize_1arg Real cosine_unnormalized\n\nlogistic(u::Real) = 1 / (exp(u) + 2 + exp(-u))\nlogistic_unnormalized(u::Real) = 1 / (exp(u) + 2 + exp(-u))\nBase.@vectorize_1arg Real logistic\nBase.@vectorize_1arg Real logistic_unnormalized\n", "meta": {"hexsha": "d91c8737405e95c9053719479dc595ad089224aa", "size": 1923, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels.jl", "max_stars_repo_name": "JuliaPackageMirrors/SmoothingKernels.jl", "max_stars_repo_head_hexsha": "9b856bff6b0662031b8bca29493c42b9d08ddc43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-05-17T05:04:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T13:01:24.000Z", "max_issues_repo_path": "src/kernels.jl", "max_issues_repo_name": "JuliaPackageMirrors/SmoothingKernels.jl", "max_issues_repo_head_hexsha": "9b856bff6b0662031b8bca29493c42b9d08ddc43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-02-21T20:28:51.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-21T21:22:41.000Z", "max_forks_repo_path": "src/kernels.jl", "max_forks_repo_name": "JuliaPackageMirrors/SmoothingKernels.jl", "max_forks_repo_head_hexsha": "9b856bff6b0662031b8bca29493c42b9d08ddc43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-07-01T01:20:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T22:49:00.000Z", "avg_line_length": 42.7333333333, "max_line_length": 73, "alphanum_fraction": 0.6890275611, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7518939911496373}}
{"text": "using MAT, Plots\n\n@views function generate_grf3D(lx=100.0, ly=100.0, lz=100.0, sf=1.0, cl=(10.0, 8.0, 5.0), k_m=100.0, nh=10000, nx=64, ny=64, nz=64;\n                               cov_typ=\"expon\", do_reset=true, do_viz=true, do_save=false)\n    # Derived numerics\n    dx, dy, dz  = lx/nx, ly/ny, lz/nz  # numerical grid step size\n    me = 0\n    co1, co2, co3 = 0, 0, 0\n    # Array allocation\n    Yf      = @zeros(nx, ny, nz)\n    # Visu init\n    if do_viz\n        y_sl    = Int(ceil(ny/2))\n        X, Y, Z = -lx/2:dx:lx/2, -ly/2:dy:ly/2, -lz/2:dz:lz/2\n    end\n\n    if cov_typ==\"expon\"\n        # Generate the 3D exponential covariance function\n        wtime_it = grf3D_expon!(Yf, sf, cl, nh, nx, ny, nz, dx, dy, dz; me, co1, co2, co3, do_reset)\n    elseif cov_typ==\"gauss\"\n        # Generate the 3D Gaussian covariance function\n        wtime_it = grf3D_gauss!(Yf, sf, cl[1]/2.0, nh, k_m, nx, ny, nz, dx, dy, dz; me, co1, co2, co3, do_reset)\n    else\n        error(\"Undefined covariance function.\")\n    end\n\n    # Performance\n    A_eff    = 2/1e9*nx*ny*nz*sizeof(Data.Number)  # Effective main memory access per iteration [GB] (Lower bound of required memory access: H and dHdτ have to be read and written (dHdτ for damping): 4 whole-array memaccess; B has to be read: 1 whole-array memaccess)\n    T_eff    = A_eff/wtime_it                      # Effective memory throughput [GB/s]\n    if (me==0) @printf(\"T_eff = %1.2f GB/s \\n\", round(T_eff, sigdigits=2)) end\n\n    # Visualisation\n    if do_viz\n        display(heatmap(X, Z, Array(Yf)[:,y_sl,:]', aspect_ratio=1, xlims=(X[1],X[end]), ylims=(Z[1],Z[end]), c=:hot, title=\"3D RandomField (y-slice)\"))\n    end\n    if do_save  file = matopen(\"grf3D_$(cov_typ).mat\", \"w\"); write(file, \"grf3D\", Array(Yf)); close(file)  end\n\n    return Yf\nend\n", "meta": {"hexsha": "46fc823097d7a2b0d9dc943562fbcbf614fdaee9", "size": 1784, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/shared/generate_grf3D.jl", "max_stars_repo_name": "luraess/ParallelRandomFields.jl", "max_stars_repo_head_hexsha": "8587b3b56b7060c50b4b016583336de722680b03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-24T15:39:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T15:39:38.000Z", "max_issues_repo_path": "src/shared/generate_grf3D.jl", "max_issues_repo_name": "luraess/ParallelRandomFields.jl", "max_issues_repo_head_hexsha": "8587b3b56b7060c50b4b016583336de722680b03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-22T13:28:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-24T12:24:16.000Z", "max_forks_repo_path": "src/shared/generate_grf3D.jl", "max_forks_repo_name": "luraess/ParallelRandomFields.jl", "max_forks_repo_head_hexsha": "8587b3b56b7060c50b4b016583336de722680b03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6, "max_line_length": 267, "alphanum_fraction": 0.5997757848, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7518939909049177}}
{"text": "using GNSSTools\nusing JLD\nusing PyPlot\npygui(true)\n\nGM = 3.986004418e14  # m³s⁻²\neop = get_eop();\n\n# N_rand = 25\n# lats = rand(-90:0.001:90, N_rand)  # degrees\n# longs = rand(-180:0.001:180, N_rand)  # degrees\n# heights = fill(100, N_rand)  # meters\n# llas = (lats, longs, heights)\n# user_lla = llas\nfreq = L1_freq\n# user_lla = (40.01, -105.2437, 1655);\n\nfile_name = \"/home/sjbilardi/Dropbox/Apps/Overleaf/MastersThesis/ch1_doppler_curves_user_lla.jld\"\n# file_name = \"ch1_doppler_curves_user_lla.jld\"\nuser_lla = load(file_name, \"user_lla\")\n\n\nΔt = 1  # seconds\ntotal_time = 1*24*60*60  # seconds\nt_range = Array(0:Δt:total_time);\nmin_elevation = 10  # degrees\n\n# GPS\na = 26_560e3;  # m\nplane_num = 6;\nsat_per_plane = 4;\nincl = 56;\nΔΩ = 360/plane_num;\nΔf_per_plane = 360/sat_per_plane/2;  # degrees\norbital_period = 2π*sqrt(a^3 / GM)  # seconds\ndoppler_gps, doppler_rate_gps, doppler_bounds_gps, \ndoppler_rate_bounds_gps, raw_dopplers_gps = doppler_distribution(a, plane_num, \n                                           sat_per_plane, incl, \n                                           t_range, user_lla, \n                                           freq, show_plot=false,\n                                           print_steps=true, \n                                           eop=eop,\n                                           min_elevation=min_elevation,\n                                           ΔΩ=ΔΩ,\n                                           Δf_per_plane=Δf_per_plane,\n\t\t\t\t\t\t\t\t\t\t   return_constellation=false,\n                                           return_raw_dopplers=true);\ndoppler_raw_gps, doppler_rate_raw_gps, \nelevations_gps, max_elevations_gps = raw_dopplers_gps\n\n# Iridium\na = Rₑ+780*1000;  # meters\nplane_num = 6;\nsat_per_plane = 11;\nincl = 86;\nΔΩ = 360/plane_num/2;\nΔf_per_plane = 360/sat_per_plane/2;  # degrees\norbital_period = 2π*sqrt(a^3 / GM)  # seconds\ndoppler_iridium, doppler_rate_iridium, doppler_bounds_iridium, \ndoppler_rate_bounds_iridium, raw_dopplers_iridium = doppler_distribution(a, plane_num, \n                                            sat_per_plane, incl, \n                                            t_range, user_lla, \n                                            freq, show_plot=false,\n                                            print_steps=true, \n                                            eop=eop,\n                                            ΔΩ=ΔΩ,\n                                            Δf_per_plane=Δf_per_plane,\n                                            return_raw_dopplers=true);\ndoppler_raw_iridium, doppler_rate_raw_iridium, \nelevations_iridium, max_elevations_iridium = raw_dopplers_iridium\n\n# Starlink\na = Rₑ+550*1000;  # meters\nplane_num = 24;\nsat_per_plane = 66;\nincl = 53;\nΔΩ = 360/plane_num;\nΔf_per_plane = 360/sat_per_plane/2;  # degrees\norbital_period = 2π*sqrt(a^3 / GM)  # seconds\ndoppler_starlink, doppler_rate_starlink, doppler_bounds_starlink, \ndoppler_rate_bounds_starlink, raw_dopplers_starlink = doppler_distribution(a, plane_num, \n                                            sat_per_plane, incl, \n                                            t_range, user_lla, \n                                            freq, show_plot=false,\n                                            print_steps=true, \n                                            eop=eop,\n                                            ΔΩ=ΔΩ,\n                                            Δf_per_plane=Δf_per_plane,\n                                            return_raw_dopplers=true);\ndoppler_raw_starlink, doppler_rate_raw_starlink, \nelevations_starlink, max_elevations_starlink = raw_dopplers_starlink\n\n# OneWeb\na = Rₑ+1200*1000;  # meters\nplane_num = 18;\nsat_per_plane = 36;\nincl = 87.9;  # degrees\nΔΩ = 360/plane_num/2;\nΔf_per_plane = 360/sat_per_plane/2;  # degrees\norbital_period = 2π*sqrt(a^3 / GM)  # seconds\ndoppler_oneweb, doppler_rate_oneweb, doppler_bounds_oneweb, \ndoppler_rate_bounds_oneweb, raw_dopplers_oneweb = doppler_distribution(a, plane_num, \n                                            sat_per_plane, incl, \n                                            t_range, user_lla, \n                                            freq, show_plot=false,\n                                            print_steps=true, \n                                            eop=eop,\n                                            ΔΩ=ΔΩ,\n                                            Δf_per_plane=Δf_per_plane,\n                                            return_raw_dopplers=true);\ndoppler_raw_oneweb, doppler_rate_raw_oneweb, \nelevations_oneweb, max_elevations_oneweb = raw_dopplers_oneweb\n\nsave(\"ch1_doppler_curves.jld\", \n     \"doppler_gps\", doppler_gps,\n\t \"doppler_iridium\", doppler_iridium,\n\t \"doppler_starlink\", doppler_starlink,\n\t \"doppler_oneweb\", doppler_oneweb,\n\t \"doppler_rate_gps\", doppler_rate_gps,\n\t \"doppler_rate_iridium\", doppler_rate_iridium,\n\t \"doppler_rate_starlink\", doppler_rate_starlink,\n\t \"doppler_rate_oneweb\", doppler_rate_oneweb,\n\t \"doppler_bounds_gps\", doppler_bounds_gps,\n\t \"doppler_bounds_iridium\", doppler_bounds_iridium,\n\t \"doppler_bounds_starlink\", doppler_bounds_starlink,\n\t \"doppler_bounds_oneweb\", doppler_bounds_oneweb,\n\t \"doppler_raw_gps\", doppler_raw_gps,\n\t \"doppler_raw_iridium\", doppler_raw_iridium,\n\t \"doppler_raw_starlink\", doppler_raw_starlink,\n\t \"doppler_raw_oneweb\", doppler_raw_oneweb,\n\t \"doppler_rate_raw_gps\", doppler_rate_raw_gps,\n\t \"doppler_rate_raw_iridium\", doppler_rate_raw_iridium,\n\t \"doppler_rate_raw_starlink\", doppler_rate_raw_starlink,\n\t \"doppler_rate_raw_oneweb\", doppler_rate_raw_oneweb,\n\t \"freq\", freq,\n\t \"user_lla\", user_lla,\n\t \"t_range\", t_range,\n\t \"min_elevation\", min_elevation,\n\t \"elevations_gps\", elevations_gps,\n\t \"elevations_iridium\", elevations_iridium,\n\t \"elevations_starlink\", elevations_starlink,\n\t \"elevations_oneweb\", elevations_oneweb,\n\t \"max_elevations_gps\", max_elevations_gps,\n\t \"max_elevations_iridium\", max_elevations_iridium,\n\t \"max_elevations_starlink\", max_elevations_starlink,\n\t \"max_elevations_oneweb\", max_elevations_oneweb)\n\n\n# file_name = \"/home/sjbilardi/Dropbox/Apps/Overleaf/MastersThesis/ch1_doppler_curves.jld\"\n# data = load(file_name, \n#             \"doppler_gps\",\n# \t       \"doppler_iridium\",\n# \t       \"doppler_starlink\",\n# \t       \"doppler_oneweb\",\n# \t       \"doppler_rate_gps\",\n# \t       \"doppler_rate_iridium\",\n# \t       \"doppler_rate_starlink\",\n# \t       \"doppler_rate_oneweb\",\n# \t       \"doppler_bounds_gps\",\n# \t       \"doppler_bounds_iridium\",\n# \t       \"doppler_bounds_starlink\",\n# \t       \"doppler_bounds_oneweb\",\n# \t       \"doppler_raw_gps\",\n# \t       \"doppler_raw_iridium\",\n# \t       \"doppler_raw_starlink\",\n# \t       \"doppler_raw_oneweb\",\n# \t       \"doppler_rate_raw_gps\",\n# \t       \"doppler_rate_raw_iridium\",\n# \t       \"doppler_rate_raw_starlink\",\n# \t       \"doppler_rate_raw_oneweb\",\n# \t       \"freq\",\n# \t       \"user_lla\",\n# \t       \"t_range\",\n# \t       \"min_elevation\")\n\n\n# doppler_gps, doppler_iridium, doppler_starlink, doppler_oneweb, \n# doppler_rate_gps, doppler_rate_iridium, doppler_rate_starlink, doppler_rate_oneweb,\n# doppler_bounds_gps, doppler_bounds_iridium, doppler_bounds_starlink, doppler_bounds_oneweb,\n# doppler_raw_gps, doppler_raw_iridium, doppler_raw_starlink, doppler_raw_oneweb,\n# doppler_rate_raw_gps, doppler_rate_raw_iridium, doppler_rate_raw_starlink, doppler_rate_raw_oneweb,\n# freq, user_lla, t_range, min_elevation = data \n\n# # Make plots\n# fig = figure(figsize=(8.5,9))\n# # GPS\n# ax1 = fig.add_subplot(4,2,1)\n# ax1.hist(Array(doppler_gps.edges[1])[2:end]./1000,\n#          Array(doppler_gps.edges[1])./1000, weights=doppler_gps.weights,\n#          color=\"k\");\n# xlabel(\"Doppler (kHz)\")\n# ylabel(\"Probability\")\n# title(\"GPS\")\n# ax2 = fig.add_subplot(4,2,2)\n# ax2.hist(Array(doppler_rate_gps.edges[1])[2:end],\n#          Array(doppler_rate_gps.edges[1]), weights=doppler_rate_gps.weights,\n#          color=\"k\");\n# xlabel(\"Doppler Rate (Hz/s)\")\n# ylabel(\"Probability\")\n# title(\"GPS\")\n# # Iridium\n# ax3 = fig.add_subplot(4,2,3)\n# ax3.hist(Array(doppler_iridium.edges[1])[2:end]./1000,\n#          Array(doppler_iridium.edges[1])./1000, weights=doppler_iridium.weights,\n#          color=\"k\");\n# xlabel(\"Doppler (kHz)\")\n# ylabel(\"Probability\")\n# title(\"Iridium\")\n# ax4 = fig.add_subplot(4,2,4)\n# ax4.hist(Array(doppler_rate_iridium.edges[1])[2:end],\n#          Array(doppler_rate_iridium.edges[1]), weights=doppler_rate_iridium.weights,\n#          color=\"k\");\n# xlabel(\"Doppler Rate (Hz/s)\")\n# ylabel(\"Probability\")\n# title(\"Iridium\")\n# # Starlink\n# ax5 = fig.add_subplot(4,2,5)\n# ax5.hist(Array(doppler_starlink.edges[1])[2:end]./1000,\n#          Array(doppler_starlink.edges[1])./1000, weights=doppler_starlink.weights,\n#          color=\"k\");\n# xlabel(\"Doppler (kHz)\")\n# ylabel(\"Probability\")\n# title(\"Starlink\")\n# ax6 = fig.add_subplot(4,2,6)\n# ax6.hist(Array(doppler_rate_starlink.edges[1])[2:end],\n#          Array(doppler_rate_starlink.edges[1]), weights=doppler_rate_starlink.weights,\n#          color=\"k\");\n# xlabel(\"Doppler Rate (Hz/s)\")\n# ylabel(\"Probability\")\n# title(\"Starlink\")\n# # OneWeb\n# ax7 = fig.add_subplot(4,2,7)\n# ax7.hist(Array(doppler_oneweb.edges[1])[2:end]./1000,\n#          Array(doppler_oneweb.edges[1])./1000, weights=doppler_oneweb.weights,\n#          color=\"k\");\n# xlabel(\"Doppler (kHz)\")\n# ylabel(\"Probability\")\n# title(\"OneWeb\")\n# ax8 = fig.add_subplot(4,2,8)\n# ax8.hist(Array(doppler_rate_oneweb.edges[1])[2:end],\n#          Array(doppler_rate_oneweb.edges[1]), weights=doppler_rate_oneweb.weights,\n#          color=\"k\");\n# xlabel(\"Doppler Rate (Hz/s)\")\n# ylabel(\"Probability\")\n# title(\"OneWeb\")\n\n# subplots_adjust(hspace=0.7, wspace=0.35, top=0.93, left=0.1, right=0.9)\n# savefig(\"/home/sjbilardi/Dropbox/Apps/Overleaf/MastersThesis/figures/ch1_doppler_distributions.svg\", dpi=300)\n\n\n# using PyCall\n# basemap = pyimport(\"mpl_toolkits.basemap\")\n# # lon_0 is central longitude of projection.\n# # resolution = 'c' means use crude resolution coastlines.\n# fig = figure(figsize=(7.5, 2.5))\n# ax1 = fig.add_subplot(1,1,1)\n# m = basemap.Basemap(projection=\"robin\", lon_0=0, resolution=\"c\")\n# m.drawcoastlines(color=\"black\", linewidth=0.25)\n# m.fillcontinents(color=\"#69b2a2\",lake_color=\"#A6CAE0\")\n# # draw parallels and meridians.\n# m.drawparallels(range(-90., 120., step=30.), linewidth=0.5, color=\"dimgrey\")\n# m.drawmeridians(range(0., 360., step=60.), linewidth=0.5, color=\"dimgrey\")\n# m.drawmapboundary(fill_color=\"#A6CAE0\")\n# # m.fillcontinents(color=\"grey\", alpha=0.3)\n# color = \"tomato\"\n# marker = \".\"\n# markersize = 5\n# N = min(length(user_lla[1]), length(user_lla[2]), length(user_lla[3]))\n# for i in 1:N\n# \tlat = user_lla[1][i]\n# \tlon\t= user_lla[2][i]\n# \txpt, ypt = m(lon,lat)\n# \tm.plot(xpt, ypt, color=color, marker=marker, markersize=markersize)\n# end\n# # title(\"$N Random Observation Locations\")\n# subplots_adjust(bottom=0.01, left=0.1, right=0.9, top=0.99)\n# savefig(\"/home/sjbilardi/Dropbox/Apps/Overleaf/MastersThesis/figures/ch1_doppler_curves_random_location_map.pdf\",\n#         dpi=300)\n", "meta": {"hexsha": "c3a0aa761bb2f4ee90f8a7a46f71320002748656", "size": 10984, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ch1_doppler_curves.jl", "max_stars_repo_name": "cu-sense-lab/GNSSTools_Examples_Evaluations_Demos", "max_stars_repo_head_hexsha": "1713133abdf0430e10a6604827c63a13ab8477c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-20T20:24:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T20:24:14.000Z", "max_issues_repo_path": "ch1_doppler_curves.jl", "max_issues_repo_name": "cu-sense-lab/GNSSTools_Examples_Evaluations_Demos", "max_issues_repo_head_hexsha": "1713133abdf0430e10a6604827c63a13ab8477c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch1_doppler_curves.jl", "max_forks_repo_name": "cu-sense-lab/GNSSTools_Examples_Evaluations_Demos", "max_forks_repo_head_hexsha": "1713133abdf0430e10a6604827c63a13ab8477c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-12-20T20:24:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T14:23:36.000Z", "avg_line_length": 39.3691756272, "max_line_length": 115, "alphanum_fraction": 0.6324654042, "num_tokens": 3348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.751892701465082}}
{"text": "using SpecialFunctions\n\n\"\"\"\n    G(x::Real)\n\nComputes the second synchrotron function at a given frequency ratio ``x = \\\\frac{\\\\nu}{\\\\nu_0}``.\n\n``G(x) = x K_{\\\\frac{2}{3}}(x)``\n\"\"\"\nG(x::Real) = x * besselk(2/3, x)\n\n\n\"\"\"\n    𝒢(x::Real)\n\nComputes the second synchrotron function at a given frequency ratio ``x = \\\\frac{\\\\nu}{\\\\nu_0}``.\n\n``G(x) = x K_{\\\\frac{2}{3}}(x)``\n\nWrapper for [`G`](@ref).\n\"\"\"\n𝒢(x::Real) = G(x)\n", "meta": {"hexsha": "03562085864f052f8bb8d3bc2ccddb175e98f443", "size": 415, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/G.jl", "max_stars_repo_name": "LudwigBoess/SynchrotronKernel.jl", "max_stars_repo_head_hexsha": "4ed665f9b268acc14efbe3ddc69f0be610d619a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/G.jl", "max_issues_repo_name": "LudwigBoess/SynchrotronKernel.jl", "max_issues_repo_head_hexsha": "4ed665f9b268acc14efbe3ddc69f0be610d619a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-08-11T14:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T13:49:07.000Z", "max_forks_repo_path": "src/G.jl", "max_forks_repo_name": "LudwigBoess/SynchrotronKernel.jl", "max_forks_repo_head_hexsha": "4ed665f9b268acc14efbe3ddc69f0be610d619a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0434782609, "max_line_length": 97, "alphanum_fraction": 0.5638554217, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591979, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7518926954779201}}
{"text": "function sphcesaro1(A::AbstractMatrix{T}) where T\n    M, N = size(A)\n    m, n = M, N÷2\n    C = zeros(T, m, 2n+1)\n    @inbounds for i = 1:m\n        C[i,1] = (m+one(T)-i)/m\n    end\n    @inbounds for j = 1:n\n        for i = 1:m-j\n            C[i,2j] = C[i+j,1]\n            C[i,2j+1] = C[i+j,1]\n        end\n    end\n    C\nend\n\nfunction sphcesaro2(A::AbstractMatrix{T}) where T\n    M, N = size(A)\n    m, n = M, N÷2\n    C = zeros(T, m, 2n+1)\n    @inbounds for i = 1:m\n        C[i,1] = (m+2one(T)-i)*(m+one(T)-i)/((m+one(T))*m)\n    end\n    @inbounds for j = 1:n\n        for i = 1:m-j\n            C[i,2j] = C[i+j,1]\n            C[i,2j+1] = C[i+j,1]\n        end\n    end\n    C\nend\n\n\nfunction sphcesaro(A::AbstractMatrix{T}, κ::Int) where T\n    M, N = size(A)\n    m, n = M, N÷2\n    C = zeros(T, m, 2n+1)\n    @inbounds for i = 1:m\n        C[i,1] = binomial(m+κ-i, m-i)/binomial(m+κ-1, m-1)\n    end\n    @inbounds for j = 1:n\n        for i = 1:m-j\n            C[i,2j] = C[i+j,1]\n            C[i,2j+1] = C[i+j,1]\n        end\n    end\n    C\nend\n", "meta": {"hexsha": "8f6b7b64d3723954603eaa86ae9634854b799fd3", "size": 1027, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "NonlocalSphere/sphcesaro.jl", "max_stars_repo_name": "ApproxFun/SpectralTimeStepping.jl", "max_stars_repo_head_hexsha": "4f0e689275981618469ed88e4d1f62e05b0b492c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-12-15T16:08:14.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-17T19:48:32.000Z", "max_issues_repo_path": "NonlocalSphere/sphcesaro.jl", "max_issues_repo_name": "JuliaApproximation/SpectralTimeStepping.jl", "max_issues_repo_head_hexsha": "4f0e689275981618469ed88e4d1f62e05b0b492c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-12-06T20:52:39.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-03T21:48:39.000Z", "max_forks_repo_path": "NonlocalSphere/sphcesaro.jl", "max_forks_repo_name": "ApproxFun/SpectralTimeStepping.jl", "max_forks_repo_head_hexsha": "4f0e689275981618469ed88e4d1f62e05b0b492c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:51:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T12:22:37.000Z", "avg_line_length": 20.9591836735, "max_line_length": 58, "alphanum_fraction": 0.4362220058, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591979, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7518926908989966}}
{"text": "# Given the row and column indices of the lower left\n# vertex, add the location where the contour level\n# crosses the specified edge.\nfunction interpolate(x, y, z::AbstractMatrix, h::Number, ind, edge::UInt8, ::Type{VT}) where {VT}\n    xi, yi = ind\n    @inbounds if edge == W\n        y_interp = y[yi] + (y[yi + 1] - y[yi]) * (h - z[xi, yi]) / (z[xi, yi + 1] - z[xi, yi])\n        x_interp = x[xi]\n    elseif edge == E\n        y_interp = y[yi] + (y[yi + 1] - y[yi]) * (h - z[xi + 1, yi]) / (z[xi + 1, yi + 1] - z[xi + 1, yi])\n        x_interp = x[xi + 1]\n    elseif edge == N\n        y_interp = y[yi + 1]\n        x_interp = x[xi] + (x[xi + 1] - x[xi]) * (h - z[xi, yi + 1]) / (z[xi + 1, yi + 1] - z[xi, yi + 1])\n    elseif edge == S\n        y_interp = y[yi]\n        x_interp = x[xi] + (x[xi + 1] - x[xi]) * (h - z[xi, yi]) / (z[xi + 1, yi] - z[xi, yi])\n    end\n\n    return VT(x_interp, y_interp)\nend\n\nfunction interpolate(x::AbstractRange, y::AbstractRange, z::AbstractMatrix, h::Number, ind, edge::UInt8, ::Type{VT}) where {VT}\n    xi, yi = ind\n    @inbounds if edge == W\n        y_interp = y[yi] + step(y) * (h - z[xi, yi]) / (z[xi, yi + 1] - z[xi, yi])\n        x_interp = x[xi]\n    elseif edge == E\n        y_interp = y[yi] + step(y) * (h - z[xi + 1, yi]) / (z[xi + 1, yi + 1] - z[xi + 1, yi])\n        x_interp = x[xi + 1]\n    elseif edge == N\n        y_interp = y[yi + 1]\n        x_interp = x[xi] + step(x) * (h - z[xi, yi + 1]) / (z[xi + 1, yi + 1] - z[xi, yi + 1])\n    elseif edge == S\n        y_interp = y[yi]\n        x_interp = x[xi] + step(x) * (h - z[xi, yi]) / (z[xi + 1, yi] - z[xi, yi])\n    end\n\n    return VT(x_interp, y_interp)\nend\n\nfunction interpolate(x::AbstractMatrix, y::AbstractMatrix, z::AbstractMatrix, h::Number, ind, edge::UInt8, ::Type{VT}) where {VT}\n    xi, yi = ind\n    @inbounds if edge == W\n        Δ = [y[xi,  yi+1] - y[xi,  yi  ], x[xi,  yi+1] - x[xi,  yi  ]].*(h - z[xi,  yi  ])/(z[xi,  yi+1] - z[xi,  yi  ])\n        y_interp = y[xi,yi] + Δ[1]\n        x_interp = x[xi,yi] + Δ[2]\n    elseif edge == E\n        Δ = [y[xi+1,yi+1] - y[xi+1,yi  ], x[xi+1,yi+1] - x[xi+1,yi  ]].*(h - z[xi+1,yi  ])/(z[xi+1,yi+1] - z[xi+1,yi  ])\n        y_interp = y[xi+1,yi] + Δ[1]\n        x_interp = x[xi+1,yi] + Δ[2]\n    elseif edge == N\n        Δ = [y[xi+1,yi+1] - y[xi,  yi+1], x[xi+1,yi+1] - x[xi,  yi+1]].*(h - z[xi,  yi+1])/(z[xi+1,yi+1] - z[xi,  yi+1])\n        y_interp = y[xi,yi+1] + Δ[1]\n        x_interp = x[xi,yi+1] + Δ[2]\n    elseif edge == S\n        Δ = [y[xi+1,yi  ] - y[xi,  yi  ], x[xi+1,yi  ] - x[xi,  yi  ]].*(h - z[xi,  yi  ])/(z[xi+1,yi  ] - z[xi,  yi  ])\n        y_interp = y[xi,yi] + Δ[1]\n        x_interp = x[xi,yi] + Δ[2]\n    end\n\n    return VT(x_interp, y_interp)\nend\n", "meta": {"hexsha": "ead6cc222ae3fcd5c03e4531bc149a3b20ac0616", "size": 2702, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/interpolate.jl", "max_stars_repo_name": "oashour/ContourNaive.jl", "max_stars_repo_head_hexsha": "9e18fe6e02676470f234df4488cae1dcb6b3b895", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2017-08-30T09:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T16:35:13.000Z", "max_issues_repo_path": "src/interpolate.jl", "max_issues_repo_name": "oashour/ContourNaive.jl", "max_issues_repo_head_hexsha": "9e18fe6e02676470f234df4488cae1dcb6b3b895", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2017-05-04T06:11:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T01:25:10.000Z", "max_forks_repo_path": "src/interpolate.jl", "max_forks_repo_name": "oashour/ContourNaive.jl", "max_forks_repo_head_hexsha": "9e18fe6e02676470f234df4488cae1dcb6b3b895", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2017-05-16T05:55:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T13:32:46.000Z", "avg_line_length": 42.21875, "max_line_length": 129, "alphanum_fraction": 0.4777942265, "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7518762720033001}}
{"text": "function quadgk_PV(f, a, c, b; kwargs...)\r\n    if b > c > a\r\n        fc = f(c)\r\n        g(x) = 2 * x * (-c^2 + x^2)^-1 * (f(x) - fc)\r\n        return quadgk(g, a, prevfloat(c); kwargs...)[1] +\r\n               quadgk(g, nextfloat(c), b; kwargs...)[1] +\r\n               fc * log(abs((b^2 - c^2) / (a^2 - c^2)))\r\n    else\r\n        return quadgk(x -> 2 * x * (-c^2 + x^2)^-1 * f(x), a, b; kwargs...)[1]\r\n    end\r\nend\r\n\r\nfunction quadgk_PV2(f, a, c, b; initdiv=1,kwargs...)\r\n    fc = f(c)\r\n    function g(x)\r\n        if x == c\r\n            2 * x * (-nextfloat(c)^2 + x^2)^-1 * (f(x) - fc)\r\n        else\r\n            return 2 * x * (-c^2 + x^2)^-1 * (f(x) - fc)\r\n        end\r\n    end\r\n    return quadgk(g, a, b; order=ceil(Int64,initdiv/5),kwargs...)[1] + fc * log(abs((b^2 - c^2) / (a^2 - c^2)))\r\nend\r\n\r\n\r\n\r\n\r\nfunction quadgk_PV3(f, a, c, b;initdiv=1,kwargs...)\r\n    if a < c < b\r\n        fc = f(c)\r\n        function g(x)\r\n            if x == c\r\n                2 * x * (-nextfloat(c)^2 + x^2)^-1 * (f(x) - fc)\r\n            else\r\n                return 2 * x * (-c^2 + x^2)^-1 * (f(x) - fc)\r\n            end\r\n        end\r\n        return quadgk(g, a, b; order=ceil(Int64,initdiv/5),kwargs...)[1]\r\n        # + fc * log(abs((b^2 - c^2) / (a^2 - c^2)))\r\n    else\r\n        fc2 = f(nextfloat(a))\r\n        function g2(x)\r\n            if x == c\r\n                2 * x * (-nextfloat(c)^2 + x^2)^-1 * (f(x) - fc2)\r\n            else\r\n                return 2 * x * (-c^2 + x^2)^-1 * (f(x) - fc2)\r\n            end\r\n        end\r\n        return quadgk(g2, a, b; order=ceil(Int64,initdiv/5),kwargs...)[1]\r\n        # + fc * log(abs((b^2 - c^2) / (a^2 - c^2)))\r\n    end\r\nend\r\n\r\n\r\n\r\n\r\nfunction hquadrature_PV(f, a, c, b; kwargs...)\r\n    fc = f(c)\r\n    g(x) = 2 * x * (-c^2 + x^2)^-1 * (f(x) - fc)\r\n    return hquadrature(g, a, prevfloat(c); kwargs...)[1] +\r\n           hquadrature(g, nextfloat(c), b; kwargs...)[1] +\r\n           fc * log(abs((b^2 - c^2) / (a^2 - c^2)))\r\nend\r\n\r\n# function quadgk_PV2(f, c; kwargs...)\r\n#     g(x) = (2*f(x))/(x)\r\n#     return quadgk(g, 0.0, Inf; kwargs...)[1]\r\n# end\r\n\r\n\r\n\r\n# quadgk_PV(x->sin(x),10.0,15.0,20.0,atol=0.0,rtol=1e-4)\r\n# PvdkF1Tildeps(p0, k, kprim, m, T)\r\n", "meta": {"hexsha": "2f32f224a1ae454f9565afd6f9f5c02c576ffdfa", "size": 2177, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/artifacts/integrate.jl", "max_stars_repo_name": "Yangyang-Tan/FRGRealTime.jl", "max_stars_repo_head_hexsha": "6581b783432a5d5d08d00c887b483f9596d12fe3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-11T06:52:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T13:04:20.000Z", "max_issues_repo_path": "src/artifacts/integrate.jl", "max_issues_repo_name": "Yangyang-Tan/FRGRealTime.jl", "max_issues_repo_head_hexsha": "6581b783432a5d5d08d00c887b483f9596d12fe3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/artifacts/integrate.jl", "max_forks_repo_name": "Yangyang-Tan/FRGRealTime.jl", "max_forks_repo_head_hexsha": "6581b783432a5d5d08d00c887b483f9596d12fe3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4189189189, "max_line_length": 112, "alphanum_fraction": 0.4106568672, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825847, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7518762684020549}}
{"text": "@doc \"\"\"\nCalculates the stationarity KPSS test statistic of Nyblom (1989) and Kwiatkowski et all (1992).\n\n```math\n y_t = \\\\xi_t + r_t + \\\\epsilon_t\n```\n```math\n r_t = r_{t-1} + u_t, \\\\quad u_t\\\\sim\\\\mathcal{N}(0, \\\\sigma^2_u)\n```\n\nThe KPSS test has a LM-type statistic given by\n\n```math\n  LM = \\\\frac{\\\\sum^T_t S_t}{\\\\epsilon'\\\\epsilon},\n```\n\nwhere Sₜ is the partial sum of resids up to time t\n\n```math\n  S_t = \\\\sum^t_{j=1} \\\\epsilon_j\n```\n\nRequired Input Parameters\n----------------------------------\n`y::Vector{Float64}`: Observed time series in vector form.\n\nOptional Input Parameters\n----------------------------------\n\n`trend::String`: Deterministic trend specification. It determines the asymptotic distribution of the t-statistic. Possible values are `\"constant\"`, which considers a constant deterministic term; amd `\"linear\"`, which also considers a linear time trend.\n\nOutput\n----------------------------------\n`kpss_stat::Float64`: KPSS test statistic.\n\n`kpss_pval::Float64`: p-value obtained from 10000 simulations.\n\n```@example 1\n  series = simul_arma()\n  kpss_test(series)\n```\n\n\"\"\"->\nfunction kpss_test(y::Vector{Float64}; trend::String=\"constant\")\n  T = size(y,1)\n  if trend==\"constant\"\n    x = ones(T)\n    println(\"constant deteriministic detrending.\")\n  elseif trend==\"linear\"\n    x = [ones(T) collect(1:T)]\n    println(\"constant plus linear deteriministic detrending.\")\n  else\n    error(\" trend must be either, constant, or linear\")\n  end\n  β, t_stat, resid = kpss_ols(y, x[:,:])\n  S = cumsum(resid, 1)\n  nominator = sum(S.^2)/(T^2)\n  denominator = resid'resid/T\n  kpss_stat = nominator./denominator\n  kpss_pval = mean(kpss_stat.<kpss_dist(T, trend=trend))\n  return kpss_stat[1], kpss_pval\nend\n#\n#\nfunction wiener2(nobs)\n    e0 = rand(Normal(), nobs);\n    x = ones(nobs,1);\n    e1 = e0 - mean(e0);\n    b = inv(x'x)*(x'e0);\n    e2 = e0-b.*e0;\n    y1 = cumsum(e1);\n    y2 = cumsum(e2);\n    intW2_1 = nobs^(-2.)*sum(y1.^2, 1);\n    intW2_2 = nobs^(-2.)*sum(y2.^2, 1);\n    return intW2_1, intW2_2\nend\n\nfunction kpss_dist(T; trend=\"constant\")\n  nsim = 10000\n  kpss = Vector{Float64}(nsim)\n  for isim ∈ 1:nsim\n    c_tmp, trnd_tmp = wiener2(T)\n    (trend==\"constant\") && (kpss[isim, :] = c_tmp)\n    (trend==\"linear\") && (kpss[isim, :] = trnd_tmp)\n  end\n  return kpss\nend\n\nfunction kpss_ols(y::Array{Float64,}, x::Array{Float64,})\n  T, k = size(x)\n  β = inv(x'x)*(x'y)\n  ϵ = y - x*β\n  yhat = x*β\n  sse = ϵ'ϵ\n  σ2_y = sse/(T-k)\n  Σₓ = inv(x'x)\n  Σᵦ = σ2_y.*Σₓ\n  t_stat = β./sqrt.(diag(Σᵦ))\n  bic = (T-k).*log(sse./(T-k)) .+ k.*log(T-k)\n  resid = y - x*β\n  return β, t_stat, resid\nend\n\n\n#kpss_test(randn(200))\n", "meta": {"hexsha": "d798a23714fae847f6aa8a940fbca20804ab9596", "size": 2617, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kpss.jl", "max_stars_repo_name": "p-chaim/unitroot.jl", "max_stars_repo_head_hexsha": "8dca2b72aec7a2ea43336a7796ef0b5e58c62460", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kpss.jl", "max_issues_repo_name": "p-chaim/unitroot.jl", "max_issues_repo_head_hexsha": "8dca2b72aec7a2ea43336a7796ef0b5e58c62460", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kpss.jl", "max_forks_repo_name": "p-chaim/unitroot.jl", "max_forks_repo_head_hexsha": "8dca2b72aec7a2ea43336a7796ef0b5e58c62460", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-24T22:22:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-24T22:22:36.000Z", "avg_line_length": 24.6886792453, "max_line_length": 252, "alphanum_fraction": 0.6129155522, "num_tokens": 911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7518762681588131}}
{"text": "module ConfidenceIntervals\n\nusing Distributions\n\nexport binomialCI\n\n# TODO Clopper-Pearson\n# TODO Convert to string documentation\n# TODO Multinomial CI calculation\n\n## Binomial proportion confidence interval bounds calculation\n# Variables\n#   - X (int)             = successes\n#   - n (int)             = trial\n#   - method              = CI calculation method\n#   - confidence (float)  = confidence for the interval, 1-α\n# Returns\n#   lower bound, upper bound\nfunction binomialCI(X::Int, n::Int, method=:wilson, confidence::AbstractFloat=0.95)\n  ## Variable checks\n  0 <= X || error(\"Successes must be positive\")\n  X < n || error(\"Trials must be larger than successes\")\n  0 <= confidence <= 1 || error(\"Confidence must lie between 0 and 1. Typically 0.95\")\n\n  ## Method selection\n  if method == :agrestiCoull\n    return agrestiCoull_CI(X, n, confidence)\n  elseif method == :arcsineTransformation\n    return arcsineTransformation_CI(X, n, confidence)\n  elseif method == :jeffreys\n    return jeffreys_CI(X, n, confidence)\n  elseif method == :wald\n    return wald_CI(X, n, confidence)\n  elseif method == :wilson\n    return wilson_CI(X, n, confidence)\n  elseif method == :wilsonCC\n    return wilsonCC_CI(X, n, confidence)\n  else\n    error(\"No method found with such name.\")\n  end\nend\n\nfunction zCalc(confidence)\n  return quantile(Normal(), 1-(1-confidence)/2);\nend\n\nfunction agrestiCoull_CI(X, n, confidence)\n  ## Variable precalculations\n  z = zCalc(confidence)\n  m = n+z^2\n  μ = (X+z^2/2)/m\n\n  ## Bounds calculation\n  σ = sqrt(q*(1-q)/m)\n  lower = μ-z*σ\n  upper = μ+z*σ\n\n  return lower, upper\nend\n\nfunction arcsineTransformation_CI(X, n, confidence)\n  ## Variable precalculations\n  p = X/n\n  z = zCalc(confidence)\n\n  ## Bounds calculation\n  s = z/(2*sqrt(n))\n  lower = sin(asin(sqrt(p))-s)^2\n  upper = sin(asin(sqrt(p))+s)^2\n\n  return lower, upper\nend\n\nfunction jeffreys_CI(X, n, confidence)\n  α = 1-confidence\n  lower = quantile(Beta(x+1/2, n-X+1/2), α/2)\n  upper = quantile(Beta(x+1/2, n-X+1/2), 1-α/2)\n  return lower, upper\nend\n\n# Normal approximation\n#   - Extremely conservative\nfunction wald_CI(X, n, confidence)\n  ## Variable precalculations\n  p = X/n\n  z = zCalc(confidence)\n\n  ## Bounds calculation\n  A = z*sqrt(p*(1-p)/n)\n  lower = p-A\n  upper = p+A\n\n  return lower, upper\nend\n\n# Calculates the Wilson interval bounds, as developed by Edwin Bidwell Wilson (1927, JSTOR 2276774).\n#   - Improvement over the normal approximation interval\n#   - Good for even small number of trials\n#   - Not equal-tailed (systemic bias to centre)\nfunction wilson_CI(X, n, confidence)\n  ## Variable precalculations\n  neg = n-X\n  p = X/n\n  z = zCalc(confidence)\n\n  ## Bounds calculation\n  #TODO convert to p-X formulas\n  A = z*sqrt(X*neg/n+(z^2)/4)\n  B = n+z^2\n  lower = (X+(z^2)/2-A)/B\n  upper = (X+(z^2)/2+A)/B\n\n  return lower, upper\nend\n\n# Continuity correction derived from Newcombe (1998, PMID 9595616).\nfunction wilsonCC_CI(X, n, confidence)\n  ## Variable precalculations\n  p = X/n\n  z = zCalc(confidence)\n\n  ## Bounds calculation\n  A = 2*n*p+z^2\n  B = (z^2)/n+4*n*p*(1-p)\n  C = 4*p-2\n  D = 2*(n+z^2)\n  # Lower bound calculation\n  if p == 0\n    lower = 0\n  else\n    lower = maximum([0.0 A-(z*sqrt(B+C)+1)/D])\n  end\n\n  # Upper bound calculation\n  if p == 1\n    upper = 1\n  else\n    upper = minimum([1.0 A+(z*sqrt(B-C)+1)/D]);\n  end\n\n  return lower, upper\nend\n\nend\n", "meta": {"hexsha": "a72fc7b4b2c9b824532a75e1e7bd49987fa20571", "size": 3357, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ConfidenceIntervals.jl", "max_stars_repo_name": "DCLukas/HypothesisModules", "max_stars_repo_head_hexsha": "3b3778b7eb0c24b8893c93deb8ca7d053dde4dca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ConfidenceIntervals.jl", "max_issues_repo_name": "DCLukas/HypothesisModules", "max_issues_repo_head_hexsha": "3b3778b7eb0c24b8893c93deb8ca7d053dde4dca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ConfidenceIntervals.jl", "max_forks_repo_name": "DCLukas/HypothesisModules", "max_forks_repo_head_hexsha": "3b3778b7eb0c24b8893c93deb8ca7d053dde4dca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1517241379, "max_line_length": 100, "alphanum_fraction": 0.6610068514, "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7518762625137033}}
{"text": "\"\"\"\n```\nfind_threshold(Entropy(),counts,edges)\n```\nAn algorithm for finding the threshold value for a gray-level histogram using\nthe entropy of the histogram.\n\n# Output\n\nReturns the point in the `AbstractRange` which corresponds to the threshold bin in the histogram.\n\n# Details\n\nThis algorithm uses the entropy of a gray level histogram to produce a threshold\nvalue.\n\nLet ``f_1, f_2, \\\\ldots, f_I`` be the frequencies in the various bins of the\nhistogram and ``I`` the number of bins. With ``N = \\\\sum_{i=1}^{I}f_i``, let\n``p_i = \\\\frac{f_i}{N}`` (``i = 1, \\\\ldots, I``) denote the probability\ndistribution of gray levels. From this distribution one derives two additional\ndistributions. The first defined for discrete values ``1`` to ``s`` and the\nother, from ``s+1`` to ``I``. These distributions are\n\n```math\nA: \\\\frac{p_1}{P_s}, \\\\frac{p_2}{P_s}, \\\\ldots, \\\\frac{p_s}{P_s}\n\\\\quad \\\\text{and} \\\\quad\nB: \\\\frac{p_{s+1}}{1-P_s}, \\\\ldots, \\\\frac{p_n}{1-P_s}\n\\\\quad \\\\text{where} \\\\quad\nP_s = \\\\sum_{i=1}^{s}p_i.\n```\nThe entropies associated with each distribution are as follows:\n\n```math\nH(A) = \\\\ln(P_s) + \\\\frac{H_s}{P_s}\n```\n```math\nH(B) = \\\\ln(1-P_s) + \\\\frac{H_n-H_s}{1-P_s}\n```\n```math\n\\\\quad \\\\text{where} \\\\quad\nH_s = -\\\\sum_{i=1}^{s}p_i\\\\ln{p_i}\n\\\\quad \\\\text{and} \\\\quad\nH_n = -\\\\sum_{i=1}^{I}p_i\\\\ln{p_i}.\n```\n\n\nCombining these two entropy functions we have\n\n```math\n\\\\psi(s) = \\\\ln(P_s(1-P_s)) + \\\\frac{H_s}{P_s} + \\\\frac{H_n-H_s}{1-P_s}.\n```\nFinding the discrete value ``s`` which maximises the function ``\\\\psi(s)`` produces\nthe sought-after threshold value (i.e. the bin which determines the threshold).\n\nSee Section 4 of [1] for more details on the derivation of the entropy.\n\n# Options\n\n## Choices for `counts`\nYou can specify an `AbstractArray` which should be a 1D array of frequencies for\na histogram. You should submit the corresponding `edges` range for the bins of\nthe histogram. The function will throw an error if it detects that the `edges`\nand `counts` have different lengths.\n\n## Choices for `edges`\nYou can specify an `AbstractRange` which should be the corresponding range for\nthe bins of the histogram array passed into `counts`.\n\n# Example\n\n```julia\n\nusing TestImages, Images\n\nimg = testimage(\"cameraman\")\n# building a histogram with 256 bins\nedges, counts = build_histogram(img, 256)\n#=\n  The `counts` array stores at index 0 the frequencies that were below the\n  first bin edge. Since we are seeking a threshold over the interval\n  partitioned by `edges` we need to discard the first bin in `counts`\n  so that the dimensions of `edges` and `counts` match.\n=#\nfind_threshold(EntropyThresholding(), counts[1:end], edges)\n```\n\n# References\n[1] J. N. Kapur, P. K. Sahoo, and A. K. C. Wong, “A new method for gray-level picture thresholding using the entropy of the histogram,” *Computer Vision, Graphics, and Image Processing*, vol. 29, no. 1, p. 140, Jan. 1985.[doi:10.1016/s0734-189x(85)90156-2](https://doi.org/10.1016/s0734-189x%2885%2990156-2)\n\"\"\"\nfunction find_threshold(::Entropy, counts::AbstractArray, edges::AbstractRange)\n    if length(edges) != length(counts)\n        error(\"the lengths of edges and counts must match\")\n    end\n    nbins = length(counts)\n    pdf = counts ./ sum(counts)\n    Ψₘₐₓ = 0\n    Hₛ = H(pdf)\n    Hₙ = -1*Hₛ[nbins]\n    Pₛ = cumsum(pdf)\n    # Pₛ might exceed 1 for float-point numerical stability issue (issue #35)\n    Pₛ = _maybe_inplace_clamp01(Pₛ)\n\n    # Here we use a trivial findmax implementation so as to avoid additional memory allocation.\n    # Generally nbins are small number (e.g., 256) so fancy findmax strategy might give less\n    # performance boost.\n    threshold_bin = 1\n    @inbounds for i in 1:nbins\n        Pᵢ = Pₛ[i]\n        Hᵢ = -1*Hₛ[i]\n        Ψᵢ = log(Pᵢ*(1-Pᵢ)) + (Hᵢ/Pᵢ) + ((Hₙ-Hᵢ)/(1-Pᵢ))\n        if Ψᵢ > Ψₘₐₓ\n            Ψₘₐₓ = Ψᵢ\n            threshold_bin = i\n        end\n    end\n    edges[threshold_bin]\nend\n\nif VERSION > v\"1.5\"\n    function H(pdf::AbstractArray{T}) where T\n        f(x) = x == 0 ? zero(T) : convert(T, x*log(x)) # To avoid NaN when x == 0\n        cumsum(f(x) for x in pdf)\n    end\nelse\n    function H(pdf::AbstractArray{T}) where T\n        f(x) = x == 0 ? zero(T) : convert(T, x*log(x)) # To avoid NaN when x == 0\n        cumsum(f.(pdf))\n    end\nend\n\n# We can't assure that all array types support setindex!, so here we only optimize\n# for the `Vector`, which is `counts[1:end]`. `SubArray` may or may not be writable.\n_maybe_inplace_clamp01(A::AbstractArray{T}) where T = clamp.(A, zero(T), one(T))\n_maybe_inplace_clamp01(A::Vector{T}) where T = clamp!(A, zero(T), one(T))\n", "meta": {"hexsha": "64d147eac8793a8c5e23d48d383614395e854f3d", "size": 4589, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/entropy_thresholding.jl", "max_stars_repo_name": "mkitti/HistogramThresholding.jl", "max_stars_repo_head_hexsha": "dff64b67820f2c4c8fbe6c810cb3f6d80ffdcccd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-01-07T18:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-10T09:10:19.000Z", "max_issues_repo_path": "src/entropy_thresholding.jl", "max_issues_repo_name": "mkitti/HistogramThresholding.jl", "max_issues_repo_head_hexsha": "dff64b67820f2c4c8fbe6c810cb3f6d80ffdcccd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2019-01-07T05:43:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-24T04:03:55.000Z", "max_forks_repo_path": "src/entropy_thresholding.jl", "max_forks_repo_name": "mkitti/HistogramThresholding.jl", "max_forks_repo_head_hexsha": "dff64b67820f2c4c8fbe6c810cb3f6d80ffdcccd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-01-05T02:39:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T20:13:12.000Z", "avg_line_length": 33.9925925926, "max_line_length": 307, "alphanum_fraction": 0.6698627152, "num_tokens": 1461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849805, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7518762579394906}}
{"text": "using StatsBase, Distributions, IterTools #StatsPlots\n\nfunction get_freq(h::Histogram, val)\n    x = searchsortedfirst.(h.edges, val)\n    h.weights[x...]\nend\n\nfunction get_bin(h::Histogram, val)\n    bin = searchsortedfirst.(h.edges, val)\n    bin[1] - 1\nend\n\nfunction get_probability(h::Histogram, val)\n    x = searchsortedfirst.(h.edges, val)\n    h.weights[x...]/sum(h.weights)\nend\n\nfunction mutual_information(X::Vector{Vector{T}}, Y::Vector{Vector{T}}) where T <: Number\n    hx = fit(Histogram, (X...,))\n    hy = fit(Histogram, (Y...,))\n    XY = vcat(X,Y)\n    hxy = fit(Histogram, (XY...,))\n    MI = 0.0\n    rx = create_matrix_range(size(hx.weights))\n    ry = create_matrix_range(size(hy.weights))\n    for x in Iterators.product(rx...)\n        p_x = get_bin_probability(hx, x...)\n        for y in Iterators.product(ry...)\n            p_y = get_bin_probability(hy, y...)\n            index_xy = (x..., y...)\n            p_xy = get_bin_probability(hxy, index_xy...)\n            if p_xy != 0\n                MI += p_xy*log(p_xy/(p_x*p_y))\n            end\n        end\n    end\n    MI\nend\n\nfunction mutual_information(p_x, p_y, p_xy)\n    MI = 0.0\n    for x = 1:length(p_x)\n        for y = 1:length(p_y)\n            prob_xy = p_xy[x, y]\n            prob_log = prob_xy/(p_x[x]*p_y[y])\n            if prob_xy != 0 && prob_log != NaN\n                MI += prob_xy*log(prob_log)\n            end\n        end\n    end\n    MI\nend\n\nfunction mutual_information_unit(X::Vector{T}, Y::Vector{T}) where T <: Int\n    max_X, max_Y = maximum(X), maximum(Y)\n    hx = fit(Histogram, (X), 0:max_X, closed=:right)\n    hy = fit(Histogram, (Y), 0:max_Y, closed=:right)\n    XY = hcat([X],[Y])\n    hxy = fit(Histogram, (X, Y), (0:max_X, 0:max_Y), closed=:right)\n    MI = 0.0\n    rx = create_matrix_range(size(hx.weights))\n    ry = create_matrix_range(size(hy.weights))\n    for x in Iterators.product(rx...)\n        p_x = get_bin_probability(hx, x...)\n        for y in Iterators.product(ry...)\n            p_y = get_bin_probability(hy, y...)\n            index_xy = (x..., y...)\n            p_xy = get_bin_probability(hxy, index_xy...)\n            if p_xy != 0\n                MI += p_xy*log(p_xy/(p_x*p_y))\n            end\n        end\n    end\n    MI\nend\n\nfunction mutual_information_unit(X::Vector{T}, Y::Vector{T}, lim_X, lim_Y) where T <: Int\n    min_X, max_X = lim_X\n    min_Y, max_Y = lim_Y\n    range_X = min_X:max_X\n    range_Y = min_Y:max_Y\n    hx = fit(Histogram, (X), range_X, closed=:right)\n    hy = fit(Histogram, (Y), range_Y, closed=:right)\n    XY = hcat([X],[Y])\n    hxy = fit(Histogram, (X, Y), (range_X, range_Y), closed=:right)\n    MI = 0.0\n    rx = create_matrix_range(size(hx.weights))\n    ry = create_matrix_range(size(hy.weights))\n    for x in Iterators.product(rx...)\n        p_x = get_bin_probability(hx, x...)\n        for y in Iterators.product(ry...)\n            p_y = get_bin_probability(hy, y...)\n            index_xy = (x..., y...)\n            p_xy = get_bin_probability(hxy, index_xy...)\n            if p_xy != 0\n                MI += p_xy*log(p_xy/(p_x*p_y))\n            end\n        end\n    end\n    MI\nend\n\nget_bin_probability(h::Histogram, x...) = h.weights[x...]/sum(h.weights)\n\nfunction create_matrix_range(t::Tuple)\n    tuple_length = length(t)\n    ranges = []\n    for r = 1:tuple_length\n        range = 1:t[r]\n        push!(ranges, range)\n    end\n    ranges\nend\n\nfunction calculate_joint_probability(X::Vector{<:Number}, Y::Vector{<:Number}, lim_X, lim_Y)\n    min_X, max_X = lim_X\n    min_Y, max_Y = lim_Y\n    range_X = min_X:max_X\n    range_Y = min_Y:max_Y\n    p_x = fit(Histogram, (X), range_X, closed=:right)\n    p_y = fit(Histogram, (Y), range_Y, closed=:right)\n    p_xy = fit(Histogram, (X, Y), (range_X, range_Y), closed=:right)\n    p_X = p_x.weights/sum(p_x.weights)\n    p_Y = p_y.weights/sum(p_y.weights)\n    p_XY = p_xy.weights/sum(p_xy.weights)\n    return p_X, p_Y, p_XY\nend\n\nfunction calculate_joint_probability(X::Vector{<:Number}, Y::Vector{<:Number}, nbins)\n    p_x = fit(Histogram, (X), nbins=nbins[1])\n    p_y = fit(Histogram, (Y), nbins=nbins[2])\n    p_xy = fit(Histogram, (X, Y), nbins=nbins)\n    p_X = p_x.weights/sum(p_x.weights)\n    p_Y = p_y.weights/sum(p_y.weights)\n    p_XY = p_xy.weights/sum(p_xy.weights)\n    return p_X, p_Y, p_XY\nend\n\n\ninclude(\"layer_histogram.jl\")\n\nfunction calculate_joint_probability(X::Vector{<:Number}, Y::Vector{<:Number}, limits_X, limits_Y, nbins)\n    p_x = create_bin_histogram(X, nbins[1], limits_X[1], limits_X[2])\n    p_y = create_bin_histogram(Y, nbins[2], limits_Y[1], limits_Y[2])\n    p_xy = fit(Histogram, (X, Y), (p_x.edges[1], p_y.edges[1]))\n    p_X = p_x.weights/sum(p_x.weights)\n    p_Y = p_y.weights/sum(p_y.weights)\n    p_XY = p_xy.weights/sum(p_xy.weights)\n    return p_X, p_Y, p_XY\nend\n\n\n\n# Test\n#=\nX = randn(10000)\nY = randn(10000)\n\nprintln(\"Mutual Information: I(X; Y) = \", mutual_information([X], [Y]))\nprintln(\"Mutual Information: I(Y; X) = \", mutual_information([Y], [X]))\nprintln(\"Mutual Information: I(X; (Y,X)) = \", mutual_information([X], [Y, X]))\nprintln(\"Mutual Information: I(X; X) = \", mutual_information([X], [X]))\nprintln(\"Mutual Information: I(Y; Y) = \", mutual_information([Y], [Y]))\n=#\n", "meta": {"hexsha": "6c4658971767800a0206b738a814cd1d04ba9f95", "size": 5174, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MutualInformation/mutual-information.jl", "max_stars_repo_name": "Lucas-Muniz/MNEAT", "max_stars_repo_head_hexsha": "ebe55454274e5f796348c60f06e786911eda623c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MutualInformation/mutual-information.jl", "max_issues_repo_name": "Lucas-Muniz/MNEAT", "max_issues_repo_head_hexsha": "ebe55454274e5f796348c60f06e786911eda623c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MutualInformation/mutual-information.jl", "max_forks_repo_name": "Lucas-Muniz/MNEAT", "max_forks_repo_head_hexsha": "ebe55454274e5f796348c60f06e786911eda623c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3575757576, "max_line_length": 105, "alphanum_fraction": 0.5995361422, "num_tokens": 1584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509314, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.751872817261606}}
{"text": "using DiscreteFunctions, SimpleGraphs\n\n\"\"\"\n`tree2function(T::SimpleGraph)` converts a tree `T` into a\n`DiscreteFunction`. We assume the vertex set of `T` is of the\nform `{1,2,...,n}`. The resulting function has each vertex pointing\nto the next vertex on a path to the vertex `1`.\n\n**Warning**: I don't check if the input graph is valid. That is\nit *must* be a tree with vertex set `1:n`.\n\"\"\"\nfunction tree2function(G::SimpleGraph)::DiscreteFunction\n    n = NV(G)\n    data = zeros(Int,n)\n    data[1] = 1\n    for v = 2:n\n        P = find_path(G,v,1)\n        data[v] = P[2]\n    end\n    return DiscreteFunction(data)\nend\n\n\n\"\"\"\n`RandomTreeFunction(n)` creates a random function whose digraph\nis a tree (with a single selfloop).\n\"\"\"\nfunction RandomTreeFunction(n::Int)::DiscreteFunction\n    T = RandomTree(n)\n    return tree2function(T)\nend\n\n\n\"\"\"\n`is_tree_function(f::DiscreteFunction)` returns `true` exactly when the \ngraph of `f` is a tree (with a single loop at one vertex).\n\"\"\"\nfunction is_tree_function(f::DiscreteFunction)::Bool\n    clist = cycles(f)\n    if length(clist) != 1\n        return false\n    end\n    if length(clist[1]) != 1\n        return false\n    end\n    return true\nend\n", "meta": {"hexsha": "7fb289b0e7162beb8e5a988fd29375b76102e48e", "size": 1185, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tree_function.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/DiscreteFunctions.jl-b53ab163-7315-5a32-b7e7-8af45be20176", "max_stars_repo_head_hexsha": "99612254ef1a3b895b7329493aea9a81ea667c42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-09T19:15:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T19:15:23.000Z", "max_issues_repo_path": "src/tree_function.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/DiscreteFunctions.jl-b53ab163-7315-5a32-b7e7-8af45be20176", "max_issues_repo_head_hexsha": "99612254ef1a3b895b7329493aea9a81ea667c42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tree_function.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/DiscreteFunctions.jl-b53ab163-7315-5a32-b7e7-8af45be20176", "max_forks_repo_head_hexsha": "99612254ef1a3b895b7329493aea9a81ea667c42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:13:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:27:36.000Z", "avg_line_length": 24.6875, "max_line_length": 72, "alphanum_fraction": 0.6708860759, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7518728131789362}}
{"text": "module RiemannComplexNumbers\n\nimport Base.inv, Base.Complex, Base.show\nimport Base.+, Base.-, Base.*, Base./, Base.==, Base.hash\nimport Base: isinf, isnan, iszero, Complex, isequal\n\nexport RC, ComplexInf, ComplexNaN, IM\n\nstruct RC{T<:Complex} <: Number\n    val::T\n    nan_flag::Bool\n    inf_flag::Bool\nend\n\n\nconst ComplexNaN = RC((0+0im)/0,true,false)\nconst ComplexInf = RC(0+0im,false,true)\nconst IM = RC(im,false,false)\n\nfunction RC(z::Complex)\n    if isnan(z)\n        return ComplexNaN\n    end\n    if isinf(z)\n        return ComplexInf\n    end\n    return RC(z,false,false)\nend\n\nfunction Complex(a::RC)::Complex\n    if isinf(a)\n        return Inf + Inf*im\n    end\n    if isnan(a)\n        return NaN\n    end\n    return a.val\nend\n\nRC(z::Real) = RC(z+0im)\n\nisinf(z::RC) = z.inf_flag\nisnan(z::RC) = z.nan_flag\n\nfunction iszero(z::RC)\n    if isnan(z) || isinf(z)\n        return false\n    end\n    return iszero(z.val)\nend\n\nfunction show(io::IO, z::RC)\n    if isinf(z)\n        print(io,\"ComplexInf\")\n    elseif isnan(z)\n        print(io,\"ComplexNaN\")\n    else\n        sz = string(z.val)[1:end-2] * \"IM\"\n        print(io,sz)\n    end\nend\n\nfunction (==)(a::RC, b::RC)::Bool\n    if isnan(a) || isnan(b)\n        return false\n    end\n    if isinf(a) && isinf(b)\n        return true\n    end\n    if isinf(a) || isinf(b)\n        return false\n    end\n    return a.val == b.val\nend\n\nisequal(a::RC,b::Number) = isequal(promote(a,b)...)\nisequal(a::Number,b::RC) = isequal(promote(a,b)...)\n\nfunction isequal(a::RC, b::RC)::Bool\n    # for isequal, nan's compare true\n    if isnan(a) && isnan(b)\n        return true\n    end\n    # but if only one is nan, then it's false\n    if isnan(a) || isnan(b)\n        return false\n    end\n    ## complex infinites are equal\n    if isinf(a) && isinf(b)\n        return true\n    end\n    if isinf(a) || isinf(b)\n        return false\n    end\n    # finally, fall back on isequal for Complex\n    return isequal(a.val, b.val)\nend\n\n\n\n\nfunction hash(a::RC, h::UInt=UInt(0))\n    if isinf(a)\n        return hash(Inf,h)\n    end\n    if isnan(a)\n        return hash(NaN,h)\n    end\n    return hash(a.val,h)\nend\n\n\n\n\nimport Base.promote_rule\n\npromote_rule(::Type{RC{T}}, ::Type{S}) where {T,S} = RC\n\ninclude(\"arithmetic.jl\")\ninclude(\"functions.jl\")\nend  # end of module\n", "meta": {"hexsha": "2b7722305dd08353cb21fbab1cb3beea0a8a05ba", "size": 2269, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/RiemannComplexNumbers.jl", "max_stars_repo_name": "scheinerman/RiemannComplexNumbers.jl", "max_stars_repo_head_hexsha": "6154c57cf33fe1f73529e73a0c49e78b2f7d65a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2015-01-18T12:49:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-10T05:22:18.000Z", "max_issues_repo_path": "src/RiemannComplexNumbers.jl", "max_issues_repo_name": "scheinerman/RiemannComplexNumbers.jl", "max_issues_repo_head_hexsha": "6154c57cf33fe1f73529e73a0c49e78b2f7d65a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-07-10T20:18:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-03T22:38:54.000Z", "max_forks_repo_path": "src/RiemannComplexNumbers.jl", "max_forks_repo_name": "scheinerman/RiemannComplexNumbers.jl", "max_forks_repo_head_hexsha": "6154c57cf33fe1f73529e73a0c49e78b2f7d65a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-01-09T13:42:53.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-23T12:55:44.000Z", "avg_line_length": 18.5983606557, "max_line_length": 57, "alphanum_fraction": 0.595416483, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7518728094703033}}
{"text": "module FunctionZeros\nimport SpecialFunctions\nimport Roots\n\nexport besselj_zero, bessely_zero\n\n# Asymptotic formula for zeros of Bessel J function of order nu\n\"\"\"\n    besselj_zero_asymptotic(nu, n)\n\nAsymptotic formula for the `n`th zero of the the Bessel J function of order `nu`.\n\"\"\"\nbesselj_zero_asymptotic(nu, n) = pi * (n - 1 + nu / 2 + 3//4)\n\n\"\"\"\n    bessely_zero_asymptotic(nu, n)\n\nAsymptotic formula for the `n`th zero of the the Bessel Y function of order `nu`.\n\"\"\"\nbessely_zero_asymptotic(nu, n) = pi * (n + nu / 2 - 3//4)\n\n# Use the asymptotic values as starting values.\n# These find the correct zeros even for n = 1,2,...\n# Order 0 is 6 times slower and 50-100 times less accurate\n# than higher orders, with other parameters constant.\n\"\"\"\n    besselj_zero(nu, n)\n\n`n`th zero of the Bessel J function of order `nu`,\nfor `n` = `1,2,...`.\n\"\"\"\nbesselj_zero(nu, n) = Roots.fzero((x) -> SpecialFunctions.besselj(nu, x),\n                                  besselj_zero_asymptotic(nu, n); order=1)\n\n\"\"\"\n    bessely_zero(nu, n)\n\n`n`th zero of the Bessel Y function of order `nu`,\nfor `n` = `1,2,...`.\n\"\"\"\nbessely_zero(nu, n) = Roots.fzero((x) -> SpecialFunctions.bessely(nu, x),\n                                 bessely_zero_asymptotic(nu, n); order=1)\n\nend # module FunctionZeros\n", "meta": {"hexsha": "265d056c1361800852cc4095a21433af65441042", "size": 1281, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FunctionZeros.jl", "max_stars_repo_name": "UnofficialJuliaMirror/FunctionZeros.jl-b21f74c0-b399-568f-9643-d20f4fa2c814", "max_stars_repo_head_hexsha": "8440e7484920883028b4ca84b9e54307c8286a50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FunctionZeros.jl", "max_issues_repo_name": "UnofficialJuliaMirror/FunctionZeros.jl-b21f74c0-b399-568f-9643-d20f4fa2c814", "max_issues_repo_head_hexsha": "8440e7484920883028b4ca84b9e54307c8286a50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FunctionZeros.jl", "max_forks_repo_name": "UnofficialJuliaMirror/FunctionZeros.jl-b21f74c0-b399-568f-9643-d20f4fa2c814", "max_forks_repo_head_hexsha": "8440e7484920883028b4ca84b9e54307c8286a50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4666666667, "max_line_length": 81, "alphanum_fraction": 0.6572989852, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7518728082860799}}
{"text": "\"\"\"\n    randindex(a, b) -> NTuple{4, Float64}\n\nCompute the tuple of Rand-related indices between the clusterings `c1` and `c2`.\n\n`a` and `b` can be either [`ClusteringResult`](@ref) instances or\nassignments vectors (`AbstractVector{<:Integer}`).\n\nReturns a tuple of indices:\n  - Hubert & Arabie Adjusted Rand index\n  - Rand index (agreement probability)\n  - Mirkin's index (disagreement probability)\n  - Hubert's index (``P(\\\\mathrm{agree}) - P(\\\\mathrm{disagree})``)\n\n# References\n> Lawrence Hubert and Phipps Arabie (1985). *Comparing partitions.*\n> Journal of Classification 2 (1): 193–218\n\n> Meila, Marina (2003). *Comparing Clusterings by the Variation of\n> Information.* Learning Theory and Kernel Machines: 173–187.\n\"\"\"\nfunction randindex(a, b)\n    c = counts(a, b)\n\n    n = sum(c)\n    nis = sum(abs2, sum(c, dims=2))        # sum of squares of sums of rows\n    njs = sum(abs2, sum(c, dims=1))        # sum of squares of sums of columns\n\n    t1 = binomial(n, 2)                    # total number of pairs of entities\n    t2 = sum(abs2, c)                      # sum over rows & columnns of nij^2\n    t3 = .5*(nis+njs)\n\n    # Expected index (for adjustment)\n    nc = (n*(n^2+1)-(n+1)*nis-(n+1)*njs+2*(nis*njs)/n)/(2*(n-1))\n\n    A = t1+t2-t3;        # agreements count\n    D = -t2+t3;          # disagreements count\n\n    if t1 == nc\n        # avoid division by zero; if k=1, define Rand = 0\n        ARI = 0\n    else\n        # adjusted Rand - Hubert & Arabie 1985\n        ARI = (A-nc)/(t1-nc)\n    end\n\n    RI = A/t1            # Rand 1971      # Probability of agreement\n    MI = D/t1            # Mirkin 1970    # p(disagreement)\n    HI = (A-D)/t1        # Hubert 1977    # p(agree)-p(disagree)\n\n    return (ARI, RI, MI, HI)\nend\n", "meta": {"hexsha": "23576a317c4f264b14cc2c797974faa8586cc003", "size": 1734, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/randindex.jl", "max_stars_repo_name": "MartaVanin/Clustering.jl", "max_stars_repo_head_hexsha": "fd96212b77bea5c4520e05f8a8a14b5d7ea93415", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 265, "max_stars_repo_stars_event_min_datetime": "2015-01-04T00:38:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T12:24:29.000Z", "max_issues_repo_path": "src/randindex.jl", "max_issues_repo_name": "MartaVanin/Clustering.jl", "max_issues_repo_head_hexsha": "fd96212b77bea5c4520e05f8a8a14b5d7ea93415", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 161, "max_issues_repo_issues_event_min_datetime": "2015-01-22T12:09:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T16:52:24.000Z", "max_forks_repo_path": "src/randindex.jl", "max_forks_repo_name": "MartaVanin/Clustering.jl", "max_forks_repo_head_hexsha": "fd96212b77bea5c4520e05f8a8a14b5d7ea93415", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 115, "max_forks_repo_forks_event_min_datetime": "2015-01-25T18:14:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T03:51:06.000Z", "avg_line_length": 32.7169811321, "max_line_length": 80, "alphanum_fraction": 0.5905420992, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7518728049514839}}
{"text": "@doc raw\"\"\"\n    NegativeMultinomial(x₀::Real, p::AbstractVector)\n\nNegative Multinomial distribution defined as\n```math\n    p(\\boldsymbol{x}|x_0, \\boldsymbol{p}) = \\Gamma\\left(\\sum_{i=0}^M x_i \\right)\\frac{p_0^{x_0}}{\\Gamma(x_0)}\\prod_{i=1}^M \\frac{p_i^{x_i}}{x_i!}\n```\nwhere $p_0= 1-\\sum_{i=1}^M p_i$.\n\nFor a detailed understanding of this distribution, see \"Negative multinomial distribution\" - Sibuya et al. - 1964\n\"\"\"\nstruct NegativeMultinomial{Tx₀<:Real,Tp<:AbstractVector} <:\n       Distributions.DiscreteMultivariateDistribution\n    x₀::Tx₀\n    p::Tp\n    function NegativeMultinomial(x₀::Real, p::AbstractVector)\n        x₀ > 0 || throw(ArgumentError(\"x₀ has to be positive\"))\n        (all(>=(0), p) && sum(p) < 1) || throw(\n            ArgumentError(\n                \"All p should be positive and their sum should be strictly smaller than 1\",\n            ),\n        )\n        return new{typeof(x₀),typeof(p)}(x₀, p)\n    end\nend\n\n_p₀(d::NegativeMultinomial) = 1 - sum(d.p)\n\nDistributions.params(d::NegativeMultinomial) = (d.x₀, d.p)\n\nBase.eltype(::NegativeMultinomial) = Int\n\nBase.length(d::NegativeMultinomial) = length(d.p)\n\nfunction Distributions._rand!(\n    rng::AbstractRNG, d::NegativeMultinomial, x::AbstractVector{<:Real}\n)\n    p₀ = _p₀(d)\n    θ = rand(rng, Gamma(d.x₀, inv(p₀) - 1))\n    λ = d.p * θ / (1 - p₀) # convert parameters to the scaled Poisson ones\n    for i in eachindex(x)\n        x[i] = rand(rng, Poisson(λ[i]))\n    end\n    return x\nend\n\nfunction Distributions._logpdf(d::NegativeMultinomial, x::AbstractVector)\n    return loggamma(d.x₀ + sum(x)) + d.x₀ * log(_p₀(d)) - loggamma(d.x₀) +\n           mapreduce(+, d.p, x) do pᵢ, xᵢ\n        xᵢ * log(pᵢ) - logfactorial(xᵢ)\n    end\nend\n\nDistributions.mean(d::NegativeMultinomial) = d.x₀ / _p₀(d) * d.p\n\nfunction Distributions.var(d::NegativeMultinomial)\n    p₀ = _p₀(d)\n    x₀ = d.x₀\n    return x₀ / p₀^2 * abs2.(d.p) + x₀ / p₀ * p\nend\n\nfunction Distributions.cov(d::NegativeMultinomial)\n    p₀ = _p₀(d)\n    x₀ = d.x₀\n    return x₀ / p₀^2 * d.p * d.p' + x₀ / p₀ * Diagonal(d.p)\nend\n\nfunction Distributions.mgf(d::NegativeMultinomial, t::AbstractVector)\n    return (_p₀(d) / (1 - dot(d.p, exp.(t))))^d.x₀\nend\n\nfunction Distributions.kldivergence(p::NegativeMultinomial, q::NegativeMultinomial)\n    p₀ = _p₀(p)\n    x₀ = p.x₀\n    x₀ == q.x₀ || error(\n        \"KL divergence cannot be computed with different x₍\", \"p: $(p.x₀), q: $(q.x₀)\"\n    )\n    return x₀ * log(p₀) - x₀ * log(_p₀(q)) +\n           x₀ / p₀ * sum(1:length(p)) do i\n        p.p[i] * (log(p.p[i]) - log(q.p[i]))\n    end\nend\n", "meta": {"hexsha": "f0181ec09466a19c5e0ad8afd0f903aeb2cb6210", "size": 2558, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SpecialDistributions/negativemultinomial.jl", "max_stars_repo_name": "theogf/AugmentedGPLikelihoods.jl", "max_stars_repo_head_hexsha": "cf3a37ed9be9461d190675d23481d44f0cad920f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-12-14T17:10:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T22:53:15.000Z", "max_issues_repo_path": "src/SpecialDistributions/negativemultinomial.jl", "max_issues_repo_name": "theogf/AugmentedGPLikelihoods.jl", "max_issues_repo_head_hexsha": "cf3a37ed9be9461d190675d23481d44f0cad920f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2021-12-03T14:09:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:20:03.000Z", "max_forks_repo_path": "src/SpecialDistributions/negativemultinomial.jl", "max_forks_repo_name": "theogf/AugmentedGPLikelihoods.jl", "max_forks_repo_head_hexsha": "cf3a37ed9be9461d190675d23481d44f0cad920f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-31T19:02:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T19:02:30.000Z", "avg_line_length": 30.8192771084, "max_line_length": 145, "alphanum_fraction": 0.6223612197, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806522, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7518728014609258}}
{"text": "##########################\n### Points Conversions ###\n##########################\n\n###############################################\n### Conversion from LLA to ECEF coordinates ###\n###############################################\n\n\nfunction ECEF(lla::OpenStreetMapX.LLA, datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84)\n    ϕdeg, λdeg, h = lla.lat, lla.lon, lla.alt\n    d = datum\n\n    sinϕ, cosϕ = sind(ϕdeg), cosd(ϕdeg)\n    sinλ, cosλ = sind(λdeg), cosd(λdeg)\n\n    N = d.a / sqrt(1 - d.e² * sinϕ^2)  # Radius of curvature (meters)\n\n    x = (N + h) * cosϕ * cosλ\n    y = (N + h) * cosϕ * sinλ\n    z = (N * (1 - d.e²) + h) * sinϕ\n\n    return OpenStreetMapX.ECEF(x, y, z)\nend\n\n###############################################\n### Conversion from ECEF to LLA coordinates ###\n###############################################\n\nfunction LLA(ecef::OpenStreetMapX.ECEF, datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84)\n    x, y, z = ecef.x, ecef.y, ecef.z\n    d = datum\n\n    p = hypot(x, y)\n    θ = atan(z*d.a, p*d.b)\n    λ = atan(y, x)\n    ϕ = atan(z + d.e′² * d.b * sin(θ)^3, p - d.e²*d.a*cos(θ)^3)\n\n    N = d.a / sqrt(1 - d.e² * sin(ϕ)^2)  # Radius of curvature (meters)\n    h = p / cos(ϕ) - N\n\n    return OpenStreetMapX.LLA(rad2deg(ϕ), rad2deg(λ), h)\nend\n\n###############################################\n### Conversion from ECEF to ENU coordinates ###\n###############################################\n\n# Given a reference point for linarization\nfunction ENU(ecef::OpenStreetMapX.ECEF, lla_ref::OpenStreetMapX.LLA, datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84)\n    ϕdeg, λdeg = lla_ref.lat, lla_ref.lon\n\n    ecef_ref = OpenStreetMapX.ECEF(lla_ref, datum)\n    ∂x = ecef.x - ecef_ref.x\n    ∂y = ecef.y - ecef_ref.y\n    ∂z = ecef.z - ecef_ref.z\n\n    # Compute rotation matrix\n    sinλ, cosλ = sind(λdeg), cosd(λdeg)\n    sinϕ, cosϕ = sind(ϕdeg), cosd(ϕdeg)\n\n    # R = [     -sinλ       cosλ  0.0\n    #      -cosλ*sinϕ -sinλ*sinϕ cosϕ\n    #       cosλ*cosϕ  sinλ*cosϕ sinϕ]\n    #\n    # east, north, up = R * [∂x, ∂y, ∂z]\n    east  = ∂x * -sinλ      + ∂y * cosλ       + ∂z * 0.0\n    north = ∂x * -cosλ*sinϕ + ∂y * -sinλ*sinϕ + ∂z * cosϕ\n    up    = ∂x * cosλ*cosϕ  + ∂y * sinλ*cosϕ  + ∂z * sinϕ\n\n    return OpenStreetMapX.ENU(east, north, up)\nend\n\n\n# Given Bounds object for linearization\nENU(ecef::OpenStreetMapX.ECEF, bounds::OpenStreetMapX.Bounds{OpenStreetMapX.LLA}, datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84) = OpenStreetMapX.ENU(ecef, OpenStreetMapX.center(bounds), datum)\n\n\n###############################################\n### Conversion from ENU to ECEF coordinates ###\n###############################################\n\nfunction ECEF(enu::OpenStreetMapX.ENU, lla_ref::OpenStreetMapX.LLA, datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84)\n    ϕdeg, λdeg = lla_ref.lat, lla_ref.lon\n\n    ecef_ref = OpenStreetMapX.ECEF(lla_ref, datum)\n\n    # Compute rotation matrix\n    sinλ, cosλ = sind(λdeg), cosd(λdeg)\n    sinϕ, cosϕ = sind(ϕdeg), cosd(ϕdeg)\n\n    # R = [-sinλ -sinϕ*cosλ  cosϕ*cosλ\n    #      \tcosλ -sinϕ*sinλ  cosϕ*sinλ\n    #        0.0       cosϕ       sinϕ]\n    #\n    # x,y,z = R * [east, north, up] + [ecef_ref.x, ecef_ref.y, ecef_ref.z]\n\t\n\t\n\t\n\t\n    x  = -sinλ*enu.east + -sinϕ*cosλ*enu.north + cosϕ*cosλ*enu.up + ecef_ref.x\n    y = cosλ*enu.east +  -sinϕ*sinλ*enu.north + cosϕ*sinλ*enu.up + ecef_ref.y\n    z    = 0.0*enu.east + cosϕ*enu.north + sinϕ*enu.up + ecef_ref.z\n\n    return OpenStreetMapX.ECEF(x, y, z)\nend\n\n# Given Bounds object for linearization\nECEF(enu::OpenStreetMapX.ENU, bounds::OpenStreetMapX.Bounds{OpenStreetMapX.LLA}, datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84) = OpenStreetMapX.ECEF(enu, OpenStreetMapX.center(bounds), datum)\n\n##############################################\n### Conversion from LLA to ENU coordinates ###\n##############################################\n\n# Given a reference point for linarization\nENU(lla::OpenStreetMapX.LLA, lla_ref::OpenStreetMapX.LLA, datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84) = OpenStreetMapX.ENU(OpenStreetMapX.ECEF(lla, datum), lla_ref, datum)\n\n# Given Bounds object for linearization\nENU(lla::OpenStreetMapX.LLA, bounds::OpenStreetMapX.Bounds{OpenStreetMapX.LLA}, datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84) = OpenStreetMapX.ENU(OpenStreetMapX.ECEF(lla, datum), bounds, datum)\n\n##############################################\n### Conversion from ENU to LLA coordinates ###\n##############################################\n\n# Given a reference point for linarization\nLLA(enu::OpenStreetMapX.ENU, lla_ref::OpenStreetMapX.LLA, datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84) = OpenStreetMapX.LLA(OpenStreetMapX.ECEF(enu,lla_ref))\n\n# Given Bounds object for linearization\nLLA(enu::OpenStreetMapX.ENU, bounds::OpenStreetMapX.Bounds{OpenStreetMapX.LLA}, datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84) = OpenStreetMapX.LLA(OpenStreetMapX.ECEF(enu,bounds))\n\n#########################################\n### Dictionaries of Nodes Conversions ###\n#########################################\n\n###############################################\n### Conversion from LLA to ECEF coordinates ###\n###############################################\n\nfunction ECEF(nodes::Dict{Int,OpenStreetMapX.LLA}, datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84)\n    r = Dict{Int,OpenStreetMapX.ECEF}()\n    sizehint!(r, ceil(Int, 1.5*length(nodes)))\n\n    for (key, node) in nodes\n        r[key] = OpenStreetMapX.ECEF(node, datum)\n    end\n\n    return r\nend\n\n###############################################\n### Conversion from ECEF to LLA coordinates ###\n###############################################\n\nfunction LLA(nodes::Dict{Int,OpenStreetMapX.ECEF}, datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84)\n    r = Dict{Int,OpenStreetMapX.LLA}()\n    sizehint!(r, ceil(Int, 1.5*length(nodes)))\n\n    for (key, node) in nodes\n        r[key] = OpenStreetMapX.LLA(node, datum)\n    end\n\n    return r\nend\n\n\n######################################################\n### Conversion from LLA or ECEF to ENU coordinates ###\n######################################################\n\n# Given a reference point\nfunction ENU(nodes::Dict{Int,T}, lla_ref::OpenStreetMapX.LLA,\n            datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84) where T<:Union{OpenStreetMapX.LLA,OpenStreetMapX.ECEF}\n    r = Dict{Int,OpenStreetMapX.ENU}()\n    sizehint!(r, ceil(Int, 1.5*length(nodes)))\n\n    for (key, node) in nodes\n        r[key] = OpenStreetMapX.ENU(node, lla_ref, datum)\n    end\n\n    return r\nend\n\n# Given Bounds\nENU(nodes::Dict{Int,T}, bounds::OpenStreetMapX.Bounds{OpenStreetMapX.LLA}, datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84) where T<:Union{OpenStreetMapX.LLA,OpenStreetMapX.ECEF} = OpenStreetMapX.ENU(nodes, OpenStreetMapX.center(bounds), datum)\n\n###############################################\n### Conversion from ENU to ECEF coordinates ###\n###############################################\n\nfunction ECEF(nodes::Dict{Int,OpenStreetMapX.ENU},lla_ref::OpenStreetMapX.LLA , datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84)\n    r = Dict{Int,OpenStreetMapX.ECEF}()\n    sizehint!(r, ceil(Int, 1.5*length(nodes)))\n\n    for (key, node) in nodes\n        r[key] = OpenStreetMapX.ECEF(node, lla_ref, datum)\n    end\n\n    return r\nend\n\n# Given Bounds\nECEF(nodes::Dict{Int,OpenStreetMapX.ENU}, bounds::Bounds{LLA}, datum::Ellipsoid = WGS84) = ECEF(nodes, OpenStreetMapX.center(bounds), datum)\n\n###############################################\n### Conversion from ENU to LLA coordinates ###\n###############################################\n\nfunction LLA(nodes::Dict{Int,OpenStreetMapX.ENU},lla_ref::OpenStreetMapX.LLA , datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84)\n    r = Dict{Int,OpenStreetMapX.LLA}()\n    sizehint!(r, ceil(Int, 1.5*length(nodes)))\n\n    for (key, node) in nodes\n        r[key] = OpenStreetMapX.LLA(node, lla_ref, datum)\n    end\n\n    return r\nend\n\n# Given Bounds\nLLA(nodes::Dict{Int,OpenStreetMapX.ENU}, bounds::OpenStreetMapX.Bounds{OpenStreetMapX.LLA}, datum::OpenStreetMapX.Ellipsoid = OpenStreetMapX.WGS84) = OpenStreetMapX.LLA(nodes, OpenStreetMapX.center(bounds), datum)\n", "meta": {"hexsha": "065127c42a8a5c559d4d36e58228b455cccf8edc", "size": 8112, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/conversion.jl", "max_stars_repo_name": "arash-dehghan/OpenStreetMapX.jl", "max_stars_repo_head_hexsha": "179251a5cfa4a62c123dbf793674c0374a07f841", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/conversion.jl", "max_issues_repo_name": "arash-dehghan/OpenStreetMapX.jl", "max_issues_repo_head_hexsha": "179251a5cfa4a62c123dbf793674c0374a07f841", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/conversion.jl", "max_forks_repo_name": "arash-dehghan/OpenStreetMapX.jl", "max_forks_repo_head_hexsha": "179251a5cfa4a62c123dbf793674c0374a07f841", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7058823529, "max_line_length": 251, "alphanum_fraction": 0.5850591716, "num_tokens": 2484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.751869664684016}}
{"text": "#f(p,x)=KL(p,softmax(x))\n\n\nFKLsoftmax(p::Array{Float64,2},x::Array{Float64,2})=begin DN=prod(size(x));Z=sum(exp(x),1);aux=(Z,DN); return ((sum(p.*(log(p)-x))+sum(log(Z)))/DN,aux); end\n\nfunction FKLsoftmax_inplace(value,auxvalue,p::Array{Float64,2},x::Array{Float64,2})\n    DN=prod(size(x));Z=sum(exp(x),1);aux=(Z,DN) \n    value=((sum(p.*(log(p)-x))+sum(log(Z)))/DN,aux)\nend\n\n\nfunction DKLsoftmax(derivativeIDX,f_c,faux_c,grad_c,grad_n,x::Array{Float64,2})\n    if derivativeIDX==1\n        grad_c.*(1+log(p)-x) \n    elseif derivativeIDX==2\n        grad_c.*(exp(x)./aux[1]-p)./aux[2]\n    end\nend\n\nif PROC==\"GPU\"\nend\n\n\nDerivative[FKLsoftmax]=DKLsoftmax\nInplace[FKLsoftmax]=FKLsoftmax_inplace\n\nKLsoftmax(p::ADnode,x::ADnode)=ADnode(FKLsoftmax,[p x])\n\nexport KLsoftmax\n", "meta": {"hexsha": "80eef15d469e508d8551395f95b253e7583f645f", "size": 763, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/FKsoftmax.jl", "max_stars_repo_name": "davidbarber/AutoDiff", "max_stars_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2016-03-20T20:52:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T07:31:59.000Z", "max_issues_repo_path": "src/functions/FKLPsoftmaxX.jl", "max_issues_repo_name": "davidbarber/AutoDiff", "max_issues_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-06-17T20:12:48.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-17T20:12:48.000Z", "max_forks_repo_path": "src/functions/FKsoftmax.jl", "max_forks_repo_name": "davidbarber/AutoDiff", "max_forks_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-01-11T21:36:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-06T21:04:40.000Z", "avg_line_length": 25.4333333333, "max_line_length": 156, "alphanum_fraction": 0.6644823067, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248123094437, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7518696502868465}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.5\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ c7edc362-1d55-4556-94e2-5ccae0fce152\nbegin\n\tusing LinearAlgebra\n\tusing Statistics\n\tusing PlutoUI\n\tusing Plots\n\tgr()\nend\n\n# ╔═╡ e91395c4-e4dd-4bf7-8efa-c48d05418bb4\nusing Polynomials\n\n# ╔═╡ f16d832c-67ad-11ec-3474-d9f0f2241ff9\nhtml\"\"\"\n\t<div>Happy holiday! Remember to take care of yourself and your loved ones!</div>\n<div id=\"snow\"></div>\n<style>\n\tbody:not(.disable_ui):not(.more-specificity) {\n        background-color:#e9ecff;\n    }\n\tpluto-output{\n\t\tborder-radius: 0px 8px 0px 0px;\n        background-color:#e9ecff;\n\t}\n\t#snow {\n        position: fixed;\n    \ttop: 0;\n    \tleft: 0;\n    \tright: 0;\n    \tbottom: 0;\n    \tpointer-events: none;\n    \tz-index: 1000;\n\t}\n</style>\n<script src=\"https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js\"></script>\n<script>\n        setTimeout(() => window.particlesJS(\"snow\", {\n            \"particles\": {\n                \"number\": {\n                    \"value\": 70,\n                    \"density\": {\n                        \"enable\": true,\n                        \"value_area\": 800\n                    }\n                },\n                \"color\": {\n                    \"value\": \"#ffffff\"\n                },\n                \"opacity\": {\n                    \"value\": 0.7,\n                    \"random\": false,\n                    \"anim\": {\n                        \"enable\": false\n                    }\n                },\n                \"size\": {\n                    \"value\": 5,\n                    \"random\": true,\n                    \"anim\": {\n                        \"enable\": false\n                    }\n                },\n                \"line_linked\": {\n                    \"enable\": false\n                },\n                \"move\": {\n                    \"enable\": true,\n                    \"speed\": 5,\n                    \"direction\": \"bottom\",\n                    \"random\": true,\n                    \"straight\": false,\n                    \"out_mode\": \"out\",\n                    \"bounce\": false,\n                    \"attract\": {\n                        \"enable\": true,\n                        \"rotateX\": 300,\n                        \"rotateY\": 1200\n                    }\n                }\n            },\n            \"interactivity\": {\n                \"events\": {\n                    \"onhover\": {\n                        \"enable\": false\n                    },\n                    \"onclick\": {\n                        \"enable\": false\n                    },\n                    \"resize\": false\n                }\n            },\n            \"retina_detect\": true\n        }), 3000);\n\t</script>\n\"\"\"\n\n\n# ╔═╡ f16d834c-67ad-11ec-05db-f726c8f8c643\nmd\"\"\" # 機械学習帳\nここを参考にした.[機械学習帳](https://chokkan.github.io/mlnote/regression/01sra.html)\n## 1. 単回帰\n### (続き)1.4. 平均二乗誤差は$a$,$b$の関数\n\"\"\"\n\n# ╔═╡ 6ce3e88a-e10d-45c2-9722-aeed933931d9\nbegin\n\tD = [\n\t\t1 3\n\t\t3 6\n\t\t6 5\n\t\t8 7]\n\n\tX = D[:,1]\n\tY = D[:,2]\nend;\n\n# ╔═╡ bc133d95-c122-49be-8789-01dd2b87ac0a\nfunction calc_msr(a, b, D)\n\txm = mean(D[:,1])\n\tym = mean(D[:,2])\n\tx2m = mean(D[:,1].^2) \n\ty2m = mean(D[:,2].^2) \n\txym = mean(D[:,1] .* D[:,2])\n\treturn @. x2m * a^2 + b^2 + 2*xm *a *b - 2*xym *a - 2*ym*b + y2m\nend\n\n# ╔═╡ 86db1e1c-5164-4e3f-b877-f9c6f1a535c7\nbegin\n\tN = 100\n\taa = range(-10,10, N)\n\tbb = range(-10,10, N)\nend\n\n# ╔═╡ c47e13d4-f0e9-46b0-b746-73563344487e\nJ = calc_msr(aa, bb', D)\n\n# ╔═╡ f1896c70-c8ce-4d7f-832e-11a3eede0883\nlet\n\tplot(xlim=(-10,10), ylim=(-10,10), framestyle=:box, aspect_ratio=1)\n\tplot!(xticks=-10:5:10, yticks=-10.0:2.5:10.0)\n\tplot!(xlabel=\"a\", ylabel=\"b\", zlabel=\"L̂_D(a,b)\")\n\theatmap!(aa, bb, J'; colorbar_scale=:log10, clim=(10^(-1),10^4),\n\t\tfillcolor=cgrad(:viridis) )\n\tJ_levels = [1., 10.0, 100.0, 1000.0]\n\tcontour!(aa, bb, J'; lc=:red, lw=0.5, ls=:dash, levels= J_levels)\nend\n\n# ╔═╡ 02c50675-5c7e-4662-84fd-56cf5e34e666\nmd\"\"\" ### 1.5. 平均二乗残差を最小化する\n単回帰の目的関数(平均二乗残差)は\n```math\nL̂_D(a,b) = \\frac{N}{1} \\sum_{i=1}^{N} ϵ_i^2 = \\frac{1}{N} \\sum_{i=1}^{N} (y_i - ŷ_i)^2 = \\frac{1}{N} \\sum_{i=1}^{N} (y_i - ax_i - b)^2\n```\nである。\n上式を $b$ で偏微分すると\n```math\nb = ȳ - ax̄\n```\nとなる。 単回帰の傾き $a$ を求める式\n```math\na = \\frac{ \\overline{xy} - (x̄)(ȳ)}{ \\overline{x^2} - (x̄)^2} \n\t= \\frac{  \\rm{Cov[} \\it{X, Y} \\rm{]} } {\\rm{Cov[} \\it{X, X} \\rm{]}}\n    = \\frac{  \\rm{Cov[} \\it{X, Y} \\rm{]} } {\\rm{Var[} \\it{X} \\rm{]}} \n```\n\n\"\"\"\n\n# ╔═╡ 0367c8ba-1c50-43ea-828f-fb0cbaefe691\nfunction set_plot()\n\tplot(size=(500,500), xlim=(0,10), ylim=(0,10), framestyle=:box, legend=:topleft)\n\tplot!(xlabel=\"x\", ylabel=\"y\", gridalpha=0.5)\nend\n\n# ╔═╡ 4765fa67-4e96-4cc0-85fa-266128fb8fae\nfunction plot_y(X, Y, colormap)\n\tscatter!(X, Y; c=colormap,  markerstrokewidth=0, label=\"\")\nend\n\n# ╔═╡ 8f419e32-93f9-4067-9461-e0e2f69a723a\nfunction plot_ŷ(a, b, offset, colormap)\n\n\toffset_ŷ = offset\n\n\ta, b = a, b\n\tf(x, a, b) = a*x + b\n\tŶ = f.(X, a, b)\n\tx = [0, 10]\n\n\ta = round(a; digits=3)\n\tb = round(b; digits=3)\n\t\n\tlabel = (a == 1) ? \"x + $(b))\" : \"$(a)x + $(b)\" \n\tscatter!(D[:,1], Ŷ; c=colormap, shape=:star5, ms=6, markerstrokewidth=0, label=\"\")\n\tplot!(x -> f(x, a, b); c=:black, lw=2, label=label)\n\t\n\ttexts_ŷ = [\"(x₁,ŷ₁)\", \"(x₂,ŷ₂)\", \"(x₃,ŷ₃)\", \"(x₄,ŷ₄)\"]\n\tfor i in 1:length(colormap)\n\t\tannotate!([(X[i],Ŷ[i]+offset_ŷ[i],text(texts_ŷ[i], 10,\n\t\t\t:center, colormap[i]))])\n\tend\n\tplot!()\nend\n\n# ╔═╡ 59bd7898-2dcf-4c23-815b-abf13a6954d0\nfunction plot_error(a, b, offset, colormap)\n\n\tf(x, a, b) = a*x + b\n\tŶ = f.(X, a, b)\n\n\toffset_ϵ = offset\n\tx_ϵ = X + offset_ϵ\n\ty_ϵ = (Y + Ŷ) / 2\n\ttexts_ϵ = [\"ϵ₁\", \"ϵ₂\", \"ϵ₃\", \"ϵ₄\"]\n\t\t\n\tfor i in 1:length(colormap)\n\t\tplot!([(X[i], Ŷ[i]), (X[i], Y[i])]; c=colormap[i], ls=:dash, label=\"\")\n\t\tannotate!([(x_ϵ[i],y_ϵ[i],text(texts_ϵ[i], 10, :center, colormap[i]))])\n\tend\n\tplot!()\nend\n\n# ╔═╡ e776c006-777f-4a6c-8a3e-a273820a0ad8\nconst colormap = [:red, :blue, :green, :orange]\n\n# ╔═╡ 75364a95-c8ef-40d3-8373-6176540ceaf8\nlet\n\t# パラメータ a, b の計算\n\tx̄ = D[:,1] |> mean\n\tȳ = D[:,2] |> mean\n\n\tCov_XY = 1 / length(X) * sum( (X .- x̄) .* (Y .- ȳ) )\n\tVar_X =  1 / length(X) * sum( (X .- x̄).^2 )\n\n\ta = Cov_XY / Var_X\n\tb = ȳ - a* x̄\n\n\t# 可視化\n\toffset_y_new = [-1., 1.8, -1.2, 0.7]\n\toffset_ϵ_new = [0.3, -0.3, 0.3, -0.3]\n\n\tset_plot()\n\tplot_y(X, Y, colormap)\n\tplot_ŷ(a, b, offset_y_new, colormap)\n\tplot_error(a, b, offset_ϵ_new, colormap)\n\t\nend\n\n# ╔═╡ 792c62f0-222b-4048-ad6a-9655db74f080\nmd\"\"\" ### 1.6. 回帰直線の性質\n\"\"\"\n\n# ╔═╡ 0f1d5e27-f04c-47f4-bcff-bc9deea6eda2\nfunction plot_means(X, Y)\n\tx̄ = D[:,1] |> mean\n\tȳ = D[:,2] |> mean\n\n\tvline!([x̄]; c=:black, lw=1.5, ls=:dash, label=\"x̄\")\n\thline!([ȳ]; c=:black, lw=1.5, ls=:dot, label=\"ȳ\")\n\t\nend\n\n# ╔═╡ 4c2841e2-2e5e-47ca-987a-0e4c5557f023\nfunction plot_regions(X, Y)\n\tx̄ = D[:,1] |> mean\n\tȳ = D[:,2] |> mean\n\n\trectangle(x, y, w, h) = Shape(x .+ [0,w,w,0], y .+ [0,0,h,h])\n\tplot!(rectangle(0, 0, x̄, ȳ), color=:red, alpha=0.1, label=\"\")\n\tplot!(rectangle(x̄, ȳ, 10-x̄, 10-ȳ), color=:red, alpha=0.1, label=\"\")\n\t\n\tplot!(rectangle(0, ȳ, x̄, ȳ), color=:blue, alpha=0.1, label=\"\")\n\tplot!(rectangle(x̄, 0, 10-x̄, ȳ), color=:blue, alpha=0.1, label=\"\")\n\t\nend\n\n# ╔═╡ dde67d9a-5c75-4477-bbd0-3eefc7b5ef13\nlet\n\tset_plot()\n\tplot_y(X, Y, colormap)\n\tplot_means(X, Y)\n\tplot_regions(X, Y)\nend\n\n# ╔═╡ c0a1bf99-d350-47ee-9a01-763acdcdb63a\nfunction plot_regions2(X, Y, colormap)\n\tx̄ = D[:,1] |> mean\n\tȳ = D[:,2] |> mean\n\n\trectangle(x, y, w, h) = Shape(x .+ [0,w,w,0], y .+ [0,0,h,h])\n\n\txs = [D[1,1], D[2,1], x̄, x̄]\n\tys = [D[1,2], D[2,2], D[3,2], ȳ]\n\tws = [x̄-D[1,1], x̄-D[2,1], D[3,1]-x̄, D[4,1]-x̄]\n\ths = [ȳ-D[1,2], ȳ-D[2,2], ȳ-D[3,2], D[4,2]-ȳ]\n\n\tfor i in 1:length(xs)\n\t\tplot!(rectangle(xs[i], ys[i], ws[i], hs[i]), color=colormap[i],\n\t\t\talpha=0.1, label=\"\")\n\tend\n\tplot!()\nend\n\n# ╔═╡ 407a1c1b-bb2d-4188-997b-17565ef4431d\nlet\n\tset_plot()\n\tplot_y(X, Y, colormap)\n\tplot_means(X, Y)\n\tplot_regions2(X, Y, colormap)\nend\n\n# ╔═╡ cc5a8abc-ff3e-4693-94fe-79a73aaf2a19\nmd\"\"\" #### 1.6.3. 回帰直線は観測データの重心を通る\n\"\"\"\n\n# ╔═╡ 6da0bfa7-bd9e-4463-9057-bd40c56019eb\nfunction plot_slope(x̄, ȳ, a, b)\n\n\tCov_XY = 1 / length(X) * sum( (X .- x̄) .* (Y .- ȳ) )\n\tVar_X =  1 / length(X) * sum( (X .- x̄).^2 )\n\n\ta = Cov_XY / Var_X\n\tb = ȳ - a* x̄\n\t\n\t# horizontal\n\tplot!([0, x̄],[b, b]; lw=2, color=:brown, label=\"\")\n\tannotate!([(x̄/2,b-0.3,text(\"x̄\", 10, :center, color=:brown))])\n\t# vertical\n\tplot!([x̄, x̄], [b, ȳ]; lw=2, color=:brown, label=\"\")\n\tannotate!([(x̄+0.3, b+(ȳ-b)/2,text(\"ax̄\", 10, :center, color=:brown))])\nend\n\n# ╔═╡ f4215be2-c8af-4f7e-92cb-76b338714f1a\nfunction plot_ŷ_only(a, b)\n\n\ta, b = a, b\n\tf(x, a, b) = a*x + b\n\tŶ = f.(X, a, b)\n\tx = [0, 10]\n\n\ta = round(a; digits=3)\n\tb = round(b; digits=3)\n\t\n\tlabel = (a == 1) ? \"x + $(b))\" : \"$(a)x + $(b)\" \n\tplot!(x -> f(x, a, b); c=:black, lw=2, label=label)\n\t\nend\n\n# ╔═╡ c1635018-bff4-4245-91ff-278fda46f3a0\nlet\n\n\t# パラメータ a, b の計算\n\tx̄ = D[:,1] |> mean\n\tȳ = D[:,2] |> mean\n\n\tCov_XY = 1 / length(X) * sum( (X .- x̄) .* (Y .- ȳ) )\n\tVar_X =  1 / length(X) * sum( (X .- x̄).^2 )\n\n\ta = Cov_XY / Var_X\n\tb = ȳ - a* x̄\n\n\t# ----- 可視化 -----\n\t# 初期化\n\tset_plot()\n\t# データ点をプロット\n\tplot_y(X, Y, colormap)\n\t# xとyの平均の直線をプロット\n\tplot_means(X, Y)\n\t# +(赤)、 -(青)になる領域をプロット\n\tplot_regions(X, Y)\n\t# スロープ部分(茶色)をプロット\n\tplot_slope(x̄, ȳ, a, b)\n\t# 推定値 ŷ をプロット\n\tplot_ŷ_only(a, b)\nend\n\n# ╔═╡ fcd91d11-e8e0-4419-a992-47f82b39b393\nmd\"\"\" #### 1.8. 単回帰の実施例\n\"\"\"\n\n# ╔═╡ e2ae904b-c4aa-4f3c-ad18-58b0fabb6877\nbegin\n\tmmt = [\n\t\t9.1, 11.2, 12.3, 18.9, 22.2, 26. , 30.9, 31.2, 28.8, 23. , 18.3,\n       11.1,  8.3,  9.1, 12.5, 18.5, 23.6, 24.8, 30.1, 33.1, 29.8, 23. ,\n       16.3, 11.2,  9.6, 10.3, 16.4, 19.2, 24.1, 26.5, 31.4, 33.2, 28.8,\n\t   23. , 17.4, 12.1, 10.6,  9.8, 14.5, 19.6, 24.7, 26.9, 30.5, 31.2,\n\t   26.9, 23. , 17.4, 11. , 10.4, 10.4, 15.5, 19.3, 26.4, 26.4, 30.1,\n\t   30.5, 26.4, 22.7, 17.8, 13.4, 10.6, 12.2, 14.9, 20.3, 25.2, 26.3,\n\t   29.7, 31.6, 27.7, 22.6, 15.5, 13.8, 10.8, 12.1, 13.4, 19.9, 25.1,\n\t   26.4, 31.8, 30.4, 26.8, 20.1, 16.6, 11.1,  9.4, 10.1, 16.9, 22.1,\n\t   24.6, 26.6, 32.7, 32.5, 26.6, 23. , 17.7, 12.1, 10.3, 11.6, 15.4,\n\t   19. , 25.3, 25.8, 27.5, 32.8, 29.4, 23.3, 17.7, 12.6, 11.1, 13.3,\n\t   16. , 18.2, 24. , 27.5, 27.7, 34.1, 28.1, 21.4, 18.6, 12.3\n\t]\n\t\n\tspend = [\n\t  463.,  360.,  380.,  584.,  763.,  886., 1168., 1325.,  847.,\n      542.,  441.,  499.,  363.,  327.,  414.,  545.,  726.,  847.,\n     1122., 1355.,  916.,  571.,  377.,  465.,  377.,  362.,  518.,\n      683.,  838., 1012., 1267., 1464., 1000.,  629.,  448.,  466.,\n      404.,  343.,  493.,  575.,  921., 1019., 1149., 1303.,  805.,\n      739.,  587.,  561.,  486.,  470.,  564.,  609.,  899.,  946.,\n     1295., 1325.,  760.,  667.,  564.,  633.,  478.,  450.,  567.,\n      611.,  947.,  962., 1309., 1307.,  930.,  668.,  496.,  650.,\n      506.,  423.,  531.,  672.,  871.,  986., 1368., 1319.,  924.,\n      716.,  651.,  708.,  609.,  535.,  717.,  890., 1054., 1077.,\n     1425., 1378.,  900.,  725.,  554.,  542.,  561.,  459.,  604.,\n      745., 1105.,  973., 1263., 1533., 1044.,  821.,  621.,  601.,\n      549.,  572.,  711.,  819., 1141., 1350., 1285., 1643., 1133.,\n      784.,  682.,  587.\n\t]\nend;\n\n# ╔═╡ 37558fb1-0ea2-4aa5-bdae-d1b54d237812\nfunction plot_temp_vs_spend()\n\tplot(title=\"MMT vs. Spend for Icecream\", framestyle=:box)\n\tplot!(xlabel=\"month mean maximum temperature [̇Degree]\", ylabel=\"spend [Yen]\")\n\tplot!(xlim=(0,35), ylim=(-250,2000), yticks=-250:250:2000, gridalpha=0.5)\n\tscatter!(mmt, spend; marker=:dot, ms=3, label=\"\")\nend\n\n# ╔═╡ 569e9185-fb79-4a0b-b32d-b6e20dee29e8\nlet\n\tŷ = fit(mmt, spend, 1)\n\tx = range(0, 35, length=100)\n\tplot_temp_vs_spend()\n\tplot!(x, ŷ.(x); lw=2, color=:red, label=\"\")\nend\n\n# ╔═╡ e802792b-052f-4bd5-976a-2f5983fe7e06\n\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nPolynomials = \"f27b6e38-b328-58d1-80ce-0feddd5e7a45\"\nStatistics = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[compat]\nPlots = \"~1.25.3\"\nPlutoUI = \"~0.7.27\"\nPolynomials = \"~2.0.22\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\njulia_version = \"1.7.1\"\nmanifest_format = \"2.0\"\n\n[[deps.AbstractPlutoDingetjes]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"8eaf9f1b4921132a4cff3f36a1d9ba923b14a481\"\nuuid = \"6e696c72-6542-2067-7265-42206c756150\"\nversion = \"1.1.4\"\n\n[[deps.Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[deps.ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[deps.Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[deps.Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[deps.Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[deps.Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"4b859a208b2397a7a623a03449e4636bdb17bcf2\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+1\"\n\n[[deps.ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"4c26b4e9e91ca528ea212927326ece5918a04b47\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.11.2\"\n\n[[deps.ChangesOfVariables]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"bf98fa45a0a4cee295de98d4c1462be26345b9a1\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.2\"\n\n[[deps.ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"a851fec56cb73cfdf43762999ec72eff5b86882a\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.15.0\"\n\n[[deps.ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[deps.Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[deps.Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"44c37b4636bc54afac5c574d2d02b625349d6582\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.41.0\"\n\n[[deps.CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[deps.Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[deps.DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[deps.DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"3daef5523dd2e769dad2365274f760ff5f282c7d\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.11\"\n\n[[deps.DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[deps.Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[deps.DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[deps.Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[deps.DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[deps.Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[deps.EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[deps.Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[deps.ExprTools]]\ngit-tree-sha1 = \"b7e3d17636b348f005f11040025ae8c6f645fe92\"\nuuid = \"e2ba6199-217a-4e67-a87a-7c52f15ade04\"\nversion = \"0.1.6\"\n\n[[deps.FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[deps.FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[deps.FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[deps.Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[deps.Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[deps.FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[deps.FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[deps.GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"0c603255764a1fa0b61752d2bec14cfbd18f7fe8\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+1\"\n\n[[deps.GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"30f2b340c2fff8410d89bfcdc9c0a6dd661ac5f7\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.62.1\"\n\n[[deps.GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"f97acd98255568c3c9b416c5a3cf246c1315771b\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.63.0+0\"\n\n[[deps.GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[deps.Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[deps.Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"a32d672ac2c967f3deb8a81d828afc739c838a06\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+2\"\n\n[[deps.Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[deps.Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[deps.HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"0fa77022fe4b511826b39c894c90daf5fce3334a\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.17\"\n\n[[deps.HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"129acf094d168394e80ee1dc4bc06ec835e510a3\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+1\"\n\n[[deps.Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[deps.HypertextLiteral]]\ngit-tree-sha1 = \"2b078b5a615c6c0396c77810d92ee8c6f470d238\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.3\"\n\n[[deps.IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[deps.IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[deps.InlineStrings]]\ndeps = [\"Parsers\"]\ngit-tree-sha1 = \"8d70835a3759cdd75881426fced1508bb7b7e1b6\"\nuuid = \"842dd82b-1e85-43dc-bf29-5d0ee9dffc48\"\nversion = \"1.1.1\"\n\n[[deps.InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[deps.Intervals]]\ndeps = [\"Dates\", \"Printf\", \"RecipesBase\", \"Serialization\", \"TimeZones\"]\ngit-tree-sha1 = \"323a38ed1952d30586d0fe03412cde9399d3618b\"\nuuid = \"d8418881-c3e1-53bb-8760-2df7ec849ed5\"\nversion = \"1.5.0\"\n\n[[deps.InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.2\"\n\n[[deps.IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[deps.IterTools]]\ngit-tree-sha1 = \"fa6287a4469f5e048d763df38279ee729fbd44e5\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.4.0\"\n\n[[deps.IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[deps.JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[deps.JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[deps.JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[deps.LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[deps.LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[deps.LaTeXStrings]]\ngit-tree-sha1 = \"f2355693d6778a178ade15952b7ac47a4ff97996\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.3.0\"\n\n[[deps.Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a8f4f279b6fa3c3c4f1adadd78a621b13a506bce\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.9\"\n\n[[deps.LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[deps.LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[deps.LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[deps.LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[deps.LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[deps.Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[deps.Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"0b4a5d71f3e5200a7dff793393e09dfc2d874290\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+1\"\n\n[[deps.Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[deps.Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[deps.Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[deps.Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[deps.Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[deps.Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[deps.Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[deps.LinearAlgebra]]\ndeps = [\"Libdl\", \"libblastrampoline_jll\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[deps.LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"e5718a00af0ab9756305a0392832c8952c7426c1\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.6\"\n\n[[deps.Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[deps.MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[deps.Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[deps.MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[deps.MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[deps.Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[deps.Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[deps.Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[deps.Mocking]]\ndeps = [\"Compat\", \"ExprTools\"]\ngit-tree-sha1 = \"29714d0a7a8083bba8427a4fbfb00a540c681ce7\"\nuuid = \"78c3b35d-d492-501b-9361-3d52fe80e533\"\nversion = \"0.7.3\"\n\n[[deps.MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[deps.MutableArithmetics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"Test\"]\ngit-tree-sha1 = \"73deac2cbae0820f43971fad6c08f6c4f2784ff2\"\nuuid = \"d8a4904e-b15c-11e9-3269-09a3773c0cb0\"\nversion = \"0.3.2\"\n\n[[deps.NaNMath]]\ngit-tree-sha1 = \"f755f36b19a5116bb580de457cda0c140153f283\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.6\"\n\n[[deps.NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[deps.Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+0\"\n\n[[deps.OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[deps.OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[deps.Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[deps.OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[deps.PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[deps.Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"d7fa6237da8004be601e19bd6666083056649918\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.1.3\"\n\n[[deps.Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[deps.Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[deps.PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[deps.PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"68604313ed59f0408313228ba09e79252e4b2da8\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.1.2\"\n\n[[deps.Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\", \"UnicodeFun\", \"Unzip\"]\ngit-tree-sha1 = \"7eda8e2a61e35b7f553172ef3d9eaa5e4e76d92e\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.25.3\"\n\n[[deps.PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"ColorTypes\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"fed057115644d04fba7f4d768faeeeff6ad11a60\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.27\"\n\n[[deps.Polynomials]]\ndeps = [\"Intervals\", \"LinearAlgebra\", \"MutableArithmetics\", \"RecipesBase\"]\ngit-tree-sha1 = \"a2515a5baa0b6954e96e10a8dc3f6855b4dedb97\"\nuuid = \"f27b6e38-b328-58d1-80ce-0feddd5e7a45\"\nversion = \"2.0.22\"\n\n[[deps.Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"2cf929d64681236a2e074ffafb8d568733d2e6af\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.3\"\n\n[[deps.Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[deps.Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[deps.REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[deps.Random]]\ndeps = [\"SHA\", \"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[deps.RecipesBase]]\ngit-tree-sha1 = \"6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.2.1\"\n\n[[deps.RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"7ad0dfa8d03b7bcf8c597f59f5292801730c55b8\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.4.1\"\n\n[[deps.Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[deps.Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"8f82019e525f4d5c669692772a6f4b0a58b06a6a\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.2.0\"\n\n[[deps.SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[deps.Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[deps.Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[deps.SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[deps.Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[deps.Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[deps.SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[deps.SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[deps.StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3c76dde64d03699e074ac02eb2e8ba8254d428da\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.13\"\n\n[[deps.Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[deps.StatsAPI]]\ngit-tree-sha1 = \"d88665adc9bcf45903013af0982e2fd05ae3d0a6\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.2.0\"\n\n[[deps.StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"2bb0cb32026a66037360606510fca5984ccc6b75\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.13\"\n\n[[deps.StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.3\"\n\n[[deps.TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[deps.TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[deps.Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"bb1064c9a84c52e277f1096cf41434b675cd368b\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.6.1\"\n\n[[deps.Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[deps.Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[deps.TimeZones]]\ndeps = [\"Dates\", \"Downloads\", \"InlineStrings\", \"LazyArtifacts\", \"Mocking\", \"Printf\", \"RecipesBase\", \"Serialization\", \"Unicode\"]\ngit-tree-sha1 = \"ce5aab0b0146b81efefae52f13002e19c2af57ac\"\nuuid = \"f269a46b-ccf7-5d73-abea-4c690281aa53\"\nversion = \"1.7.0\"\n\n[[deps.URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[deps.UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[deps.Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[deps.UnicodeFun]]\ndeps = [\"REPL\"]\ngit-tree-sha1 = \"53915e50200959667e78a92a418594b428dffddf\"\nuuid = \"1cfade01-22cf-5700-b092-accc4b62d6e1\"\nversion = \"0.4.1\"\n\n[[deps.Unzip]]\ngit-tree-sha1 = \"34db80951901073501137bdbc3d5a8e7bbd06670\"\nuuid = \"41fe7b60-77ed-43a1-b4f0-825fd5a5650d\"\nversion = \"0.1.2\"\n\n[[deps.Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[deps.Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"66d72dc6fcc86352f01676e8f0f698562e60510f\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.23.0+0\"\n\n[[deps.XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[deps.XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[deps.Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[deps.Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[deps.Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[deps.Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[deps.Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[deps.Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[deps.Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[deps.Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[deps.Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[deps.Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[deps.Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[deps.Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[deps.Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[deps.Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[deps.Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[deps.Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[deps.Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[deps.Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[deps.Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[deps.Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[deps.libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[deps.libblastrampoline_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"OpenBLAS_jll\"]\nuuid = \"8e850b90-86db-534c-a0d3-1478176c7d93\"\n\n[[deps.libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[deps.libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[deps.libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[deps.nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[deps.p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[deps.x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[deps.x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[deps.xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─f16d832c-67ad-11ec-3474-d9f0f2241ff9\n# ╠═c7edc362-1d55-4556-94e2-5ccae0fce152\n# ╠═f16d834c-67ad-11ec-05db-f726c8f8c643\n# ╠═6ce3e88a-e10d-45c2-9722-aeed933931d9\n# ╠═bc133d95-c122-49be-8789-01dd2b87ac0a\n# ╠═86db1e1c-5164-4e3f-b877-f9c6f1a535c7\n# ╠═c47e13d4-f0e9-46b0-b746-73563344487e\n# ╠═f1896c70-c8ce-4d7f-832e-11a3eede0883\n# ╠═02c50675-5c7e-4662-84fd-56cf5e34e666\n# ╠═0367c8ba-1c50-43ea-828f-fb0cbaefe691\n# ╠═4765fa67-4e96-4cc0-85fa-266128fb8fae\n# ╠═8f419e32-93f9-4067-9461-e0e2f69a723a\n# ╠═59bd7898-2dcf-4c23-815b-abf13a6954d0\n# ╠═e776c006-777f-4a6c-8a3e-a273820a0ad8\n# ╠═75364a95-c8ef-40d3-8373-6176540ceaf8\n# ╠═792c62f0-222b-4048-ad6a-9655db74f080\n# ╠═0f1d5e27-f04c-47f4-bcff-bc9deea6eda2\n# ╠═4c2841e2-2e5e-47ca-987a-0e4c5557f023\n# ╠═dde67d9a-5c75-4477-bbd0-3eefc7b5ef13\n# ╠═c0a1bf99-d350-47ee-9a01-763acdcdb63a\n# ╠═407a1c1b-bb2d-4188-997b-17565ef4431d\n# ╠═cc5a8abc-ff3e-4693-94fe-79a73aaf2a19\n# ╠═6da0bfa7-bd9e-4463-9057-bd40c56019eb\n# ╠═f4215be2-c8af-4f7e-92cb-76b338714f1a\n# ╠═c1635018-bff4-4245-91ff-278fda46f3a0\n# ╠═fcd91d11-e8e0-4419-a992-47f82b39b393\n# ╠═e2ae904b-c4aa-4f3c-ad18-58b0fabb6877\n# ╠═37558fb1-0ea2-4aa5-bdae-d1b54d237812\n# ╠═e91395c4-e4dd-4bf7-8efa-c48d05418bb4\n# ╠═569e9185-fb79-4a0b-b32d-b6e20dee29e8\n# ╠═e802792b-052f-4bd5-976a-2f5983fe7e06\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "dc4b91e3a6bcb02b13ca741d02092337a608e3ca", "size": 45688, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ML_Tyo_pluto2.jl", "max_stars_repo_name": "harakiso/pluto", "max_stars_repo_head_hexsha": "90bb8820b063db0e90be70591df9b8b65b1e16fb", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ML_Tyo_pluto2.jl", "max_issues_repo_name": "harakiso/pluto", "max_issues_repo_head_hexsha": "90bb8820b063db0e90be70591df9b8b65b1e16fb", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ML_Tyo_pluto2.jl", "max_forks_repo_name": "harakiso/pluto", "max_forks_repo_head_hexsha": "90bb8820b063db0e90be70591df9b8b65b1e16fb", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0168185004, "max_line_length": 375, "alphanum_fraction": 0.679740851, "num_tokens": 21612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7518387766872708}}
{"text": "export gradtest, gradtest_assembleStiffAndForce\n\n@doc raw\"\"\"\n    gradtest(f::Function, x0::Array{Float64}; scale::Float64 = 1.0)\n\nTesting the gradients of a vector function `f`. \nHere `x0` is $n$-dimensional vector, `f` takes an $n$-dimensional vector as inputs, and\noutputs a $m$ dimensional vector. The function tests the second order convergence of `f`\n```math\n\\|f(x_0+\\gamma c) - f(x_0) - \\gamma \\nabla f(x_0) c\\|_2 = \\mathcal{O}(\\gamma^2)\n```\n\"\"\"\nfunction gradtest(f::Function, x0::Array{Float64}; scale::Float64 = 1.0)\n    v0 = rand(Float64,size(x0))\n    γs = scale ./10 .^(1:5)\n    err2 = []\n    err1 = []\n    f0, J = f(x0)\n    for i = 1:5\n        f1, _ = f(x0+γs[i]*v0)\n        push!(err1, norm(f1-f0))\n        # @show f1, f0, 2γs[i]*J*v0\n        push!(err2, norm(f1-f0-γs[i]*J*v0))\n        # push!(err2, norm((f1-f2)/(2γs[i])-J*v0))\n        # #@show \"test \", f1, f2, f1-f2\n    end\n    close(\"all\")\n    loglog(γs, err2, label=\"Automatic Differentiation\")\n    loglog(γs, err1, label=\"Finite Difference\")\n    loglog(γs, γs.^2 * 0.5*abs(err2[1])/γs[1]^2, \"--\",label=\"\\$\\\\mathcal{O}(\\\\gamma^2)\\$\")\n    loglog(γs, γs * 0.5*abs(err1[1])/γs[1], \"--\",label=\"\\$\\\\mathcal{O}(\\\\gamma)\\$\")\n    plt.gca().invert_xaxis()\n    legend()\n    println(\"Finite difference: $err1\")\n    println(\"Automatic differentiation: $err2\")\n    return err1, err2\nend\n\nfunction gradtest_assembleStiffAndForce(domain::Domain; scale::Float64 = 1.0)\n    function f(s)\n        domain.state[domain.dof_to_eq] = s\n        rhs, K = assembleStiffAndForce(domain, 0.0)\n        return rhs, K \n    end\n    gradtest(f, rand(domain.neqs), scale=scale)\nend", "meta": {"hexsha": "1bd4be2ed6d97cae486db3fd255256087f31a5b9", "size": 1616, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/Testsuit.jl", "max_stars_repo_name": "kailaix/NNFEM.jl", "max_stars_repo_head_hexsha": "044bd1ed9c6742cca2161f4c750716342def2efc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2020-05-05T02:06:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T06:53:09.000Z", "max_issues_repo_path": "src/utils/Testsuit.jl", "max_issues_repo_name": "smibayy/NNFEM.jl", "max_issues_repo_head_hexsha": "e1f6ce3e9ce4f00646357a2140fca120f3247e2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-04-01T23:20:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-23T21:59:58.000Z", "max_forks_repo_path": "src/utils/Testsuit.jl", "max_forks_repo_name": "smibayy/NNFEM.jl", "max_forks_repo_head_hexsha": "e1f6ce3e9ce4f00646357a2140fca120f3247e2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2020-04-01T11:11:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T10:50:18.000Z", "avg_line_length": 35.1304347826, "max_line_length": 90, "alphanum_fraction": 0.603960396, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066391, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7518387665243632}}
{"text": "function _degree_centrality(g::SimpleGraph, gtype::Integer; normalize=true)\n   n_v = nv(g)\n   c = zeros(n_v)\n   for v in 1:n_v\n       if gtype == 0    # count both in and out degree if appropriate\n           deg = outdegree(g, v) + (typeof(g) == DiGraph? indegree(g, v) : 0.0)\n       elseif gtype == 1    # count only in degree\n           deg = indegree(g, v)\n       else                 # count only out degree\n           deg = outdegree(g, v)\n       end\n       s = normalize? (1.0 / (n_v - 1.0)) : 1.0\n       c[v] = deg*s\n   end\n   return c\nend\n\n# TODO avoid repetition of this docstring\n\"\"\"Calculates the [degree centrality](https://en.wikipedia.org/wiki/Centrality#Degree_centrality)\nof the graph `g`, with optional (default) normalization.\"\"\"\ndegree_centrality(g::SimpleGraph; all...) = _degree_centrality(g, 0; all...)\n\"\"\"Calculates the [degree centrality](https://en.wikipedia.org/wiki/Centrality#Degree_centrality)\nof the graph `g`, with optional (default) normalization.\"\"\"\nindegree_centrality(g::SimpleGraph; all...) = _degree_centrality(g, 1; all...)\n\"\"\"Calculates the [degree centrality](https://en.wikipedia.org/wiki/Centrality#Degree_centrality)\nof the graph `g`, with optional (default) normalization.\"\"\"\noutdegree_centrality(g::SimpleGraph; all...) = _degree_centrality(g, 2; all...)\n", "meta": {"hexsha": "d333947d8d8a9798dd53b2d99a50067c602a519f", "size": 1300, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/centrality/degree.jl", "max_stars_repo_name": "JuliaPackageMirrors/LightGraphs.jl", "max_stars_repo_head_hexsha": "b13472899cba49999567bb88f9d32d5d87cf4a19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/centrality/degree.jl", "max_issues_repo_name": "JuliaPackageMirrors/LightGraphs.jl", "max_issues_repo_head_hexsha": "b13472899cba49999567bb88f9d32d5d87cf4a19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/centrality/degree.jl", "max_forks_repo_name": "JuliaPackageMirrors/LightGraphs.jl", "max_forks_repo_head_hexsha": "b13472899cba49999567bb88f9d32d5d87cf4a19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.4285714286, "max_line_length": 97, "alphanum_fraction": 0.6623076923, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705732, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7517868864339172}}
{"text": "\nusing FFTW\nusing DifferentialEquations\nusing Plots\n\n# Define spatial domain\nc = 2 # Wave speed\nL = 20 # Length of domain \nN = 1000 # Number of discretization points\ndx = L/N\nx = -L/2:dx:L/2-dx # Define x domain\n\n# Define discrete wavenumbers\nkappa = (2pi/L)*(-N/2:N/2-1)\nkappa = fftshift(kappa) # Re-order fft wavenumbers\n\n# Initial condition \nu0 = sech.(x)       \nuhat0 = fft(u0)\n\n# Simulate in Fourier frequency domain\nf(u, p, t) = -c*im*kappa.*u\nprob = ODEProblem(f, uhat0, (0.0,2.5))\nuhat = solve(prob)\n\n# Inverse FFT to bring back to spatial domain\nu = zeros(size(uhat))\nfor k = 1:size(u)[2]\n    u[:,k] = real(ifft(uhat[:,k]))\nend\n\n# Alternatively, simulate in spatial domain\nf2(u, p, t) = -c*real.(ifft(im*kappa.*fft(u)))\nprob2 = ODEProblem(f2, u0, (0.0,2.5))\nu2 = solve(prob2)\n\n# Plot solution in time\np1 = surface(u)\np2 = surface(hcat(u2.u...))", "meta": {"hexsha": "be711ab0b3e666e019faee194eea85f3da814b2d", "size": 853, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ddsae/CODE/CH02/CH02_SEC03_2_FFTWave.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "ddsae/CODE/CH02/CH02_SEC03_2_FFTWave.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "ddsae/CODE/CH02/CH02_SEC03_2_FFTWave.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 21.8717948718, "max_line_length": 50, "alphanum_fraction": 0.6600234467, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778048911611, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7517584744744258}}
{"text": "function orthogonalize(x, bases)\n    F = 1.0\n    x_new = copy(x)\n    @inbounds for j = 1:length(bases)\n        cji = bases[j] ⋅ x\n        F -= cji ^ 2\n        x_new -= cji * bases[j]\n    end\n    x_new /= √F\n    x_new\nend\n\n@doc raw\"\"\"All Constraints. Fixed lengths, potential energy, etc.\n\n```math\nP = 1 - \\sum_{i}^{N_C}|C_i'\\rangle\\langle C_i'|\n```\n\"\"\"\nfunction projection_matrix(∇Cs)\n    N_C = length(∇Cs)\n    ∇C_unit_new = normalize.(∇Cs)\n    P = I\n    @inbounds for i = 1:N_C\n        ∇C_unit_new[i] = orthogonalize(∇C_unit_new[i], ∇C_unit_new[1:i-1])\n        tmp = flatten(∇C_unit_new[i])\n        P -= tmp * tmp'\n    end\n    P\nend\n", "meta": {"hexsha": "da852e9b251bbd916d15c7fa6b060a40eefd78e8", "size": 634, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/projection_matrix.jl", "max_stars_repo_name": "sunoru/MosiBases.jl", "max_stars_repo_head_hexsha": "1e78693cb99ba9b7a75e97d38de4cc9a6bb83830", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/projection_matrix.jl", "max_issues_repo_name": "sunoru/MosiBases.jl", "max_issues_repo_head_hexsha": "1e78693cb99ba9b7a75e97d38de4cc9a6bb83830", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-24T22:17:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T22:17:11.000Z", "max_forks_repo_path": "src/utils/projection_matrix.jl", "max_forks_repo_name": "sunoru/MosimoBase.jl", "max_forks_repo_head_hexsha": "1ac9aadc82d299b2c85a900a18e42db5f9f84988", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1333333333, "max_line_length": 74, "alphanum_fraction": 0.5552050473, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778036723354, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7517584687072931}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.7\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local iv = try Base.loaded_modules[Base.PkgId(Base.UUID(\"6e696c72-6542-2067-7265-42206c756150\"), \"AbstractPlutoDingetjes\")].Bonds.initial_value catch; b -> missing; end\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)\n        el\n    end\nend\n\n# ╔═╡ 8c3e21c9-6514-4f14-8b1f-325d124681f5\nusing DifferentialEquations\n\n# ╔═╡ ac95a2ae-5b1b-4399-8265-4b0bfb21162e\nusing ParameterizedFunctions\n\n# ╔═╡ 2e6401b9-9c89-4b4b-8492-d0a83003579b\nusing PlutoUI,Plots, HypertextLiteral\n\n# ╔═╡ 279eaa4f-41ca-4168-b492-f36543bb8204\nmd\" ## Equilibrium And Stability \n\nThe model for Logistic Growth is simple enough that it can be solved analytically. Other more complex models cannot be solved, and therefore we have to use other tools to study them. The most common is the Linear Stability Analysis. \n\nLinear stability analysis is a method that allows us to study how a system behaves near an equilibrium point. It will help us to know if equilibrium is stable or unstable, and the bifurcations that occur in these equilibrium points, based only on a simplified linearized version of the system of study:\n\n\nLet's illustrate how linear stability analysis works this with the logistioc model,.\n\n```math\n\\begin{align*}\n\\frac{\\mathrm{d} N}{\\mathrm{d} t}=\\mu N(1 -\\frac{N}{K}) \\tag{17}\n\\end{align*}\n```\n\nThe main equation can be written in the following generic form:\n\n```math\n\\begin{eqnarray}\n\\frac{\\partial N}{\\partial t} = f(N) \n\\end{eqnarray}\n```\n\nwhere N is a variable and $f(N)$  is a functions which governs its temporal evolution. \n\nThe first step is to calculate the fixed points of Eq. \\ref{base1}. In continuous systems, the steady states occur when there is no change in the amount of our quantity $N$\n\n```math\n\\begin{eqnarray}\n\\frac{\\partial \\overline{N}}{\\partial t} = 0 = f(\\overline{N})\n\\end{eqnarray}\n```\n\nWhere we denote $\\overline{N}$ as the value of our variable in steady state.\"\n\n# ╔═╡ 00037d0a-8be0-4c75-94bc-23c2c639e6e8\nmd\" \n\nLet's find the equilibrium points of our logistic model. \n\n```math\n\\begin{align*}\n\\frac{\\mathrm{d} N}{\\mathrm{d} t}= \\mu N(1 -\\frac{N}{K}) \\tag{17}\n\\end{align*}\n```\nBy taking the derivate to zero:\n\n```math\n\\begin{align*}\n\\frac{\\mathrm{d} \\overline{N}}{\\mathrm{d} t}=0= \\mu \\overline{N}(1 -\\frac{\\overline{N}}{K}) \\tag{17}\n\\end{align*}\n```\n\n we can easily see that we have two equilibrium states: \n```math\n\\begin{align*}\n\\overline{N}=0\\\\\n1 -\\frac{\\overline{N}}{K} = 0 \\Rightarrow \\overline{N} = K\n\\end{align*}\n```\n\n\n\"\n\n# ╔═╡ 64dc539b-b268-43b6-a96e-2c4fa7b48474\nmd\" The next step after finding the equilibrium points is to check if they are stable or unstable, or what type of equilibrium we have. We do that by introducing small perturbations.\n\nLet’s take a fixed point $\\overline{N}$ and perturb it by an infinitesimal amount n. We are interested in the dynamics of N = $\\overline{N}$ + n and whether N will move away away or towards $\\overline{N}$ as time progresses. \n\n```math\n\\begin{align*}\n\\frac{\\mathrm{d} N}{\\mathrm{d} t}= \\frac{\\mathrm{d} \\overline{N} + n}{\\mathrm{d} t}= \\frac{\\mathrm{d} \\overline{N} }{\\mathrm{d} t} + \\frac{\\mathrm{d} n}{\\mathrm{d} t}\n\\end{align*}\n```\n\nand since \n\n```math\n\\begin{align*}\n\\frac{\\mathrm{d} \\overline{N} }{\\mathrm{d} t} = 0 \n\\end{align*}\n```\nby definition, we have that the change in time of the population is equivalent to the change in the time of the small perturbation. \n\n```math\n\\begin{align*}\n\\frac{\\mathrm{d} N}{\\mathrm{d} t}= \\frac{\\mathrm{d} n}{\\mathrm{d} t}\n\\end{align*}\n```\n\nSince $n$ is very small by definition, we can linearize the dynamics around the ficxed points $\\overline{N}$, using a Taylor expansion\n. \n\n```math\n\\begin{align*}\n\\frac{\\mathrm{d} N}{\\mathrm{d} t}= \\frac{\\mathrm{d} n}{\\mathrm{d} t} = f(\\overline{N}+n)= f(\\overline{N})+ f'(\\overline{N})·n +···\n\\end{align*}\n```\n\nbeing $f'(\\overline{N})$ the value of derivative of function $f(N)$ in the point of equilibrium $\\overline{N}$\n\nSince $f(\\overline{N})$ = 0 by definition, we get  \n\n```math\n\\begin{align*}\n \\frac{\\mathrm{d} n}{\\mathrm{d} t} = f'(\\overline{N})·n +···\n\\end{align*}\n```\n\"\n\n# ╔═╡ f5faefd6-f496-40fb-8043-ef6b9d172ae0\nmd\"\n\nIf the perturbation $n$ is very small, then linear and nonlinear evolution are in fact approximately the same. But as $n$ increases in size the nonlinear effects become increasingly more important and evolving y with the linearized dynamics or the full nonlinear dynamics is no longer equivalent. So, this means that if perturbations $n$ are small, we can forget about higher order terms and simply assume that this has a form of $\\dot{n}= \\lambda \\cdot n$, so if we integrate we have a solution that is an exponential fucntion. \n\n\n```math\n\\begin{align*}\nn(t)=n(0) e^{\\lambda t}\n\\end{align*}\n```\n\nSo, depending on the sign of $\\lambda$, this perturbation $n$ may increase ($\\lambda >0$) or decrease ($\\lambda <0$). As an example, let's test this for the logistic system. \n\n```math\n\\begin{align*}\n\\frac{\\mathrm{d} N}{\\mathrm{d} t}=\\mu N(1 -\\frac{N}{K}) = \\frac{\\mathrm{d} (\\mu \\overline{N}(1 -\\frac{\\overline{N}}{K})}{\\mathrm{d} t} n \\tag{17}\n\\end{align*}\n```\nFor simplicity, we will decompose the fucntion in to two terms:\n```math\n\\begin{align*}\n\\mu N(1 -\\frac{N}{K}) = g(N) \\cdot h(N)\n\\end{align*}\n```\nbeing \n\n\n```math\n\\begin{align*}\ng(N) &= \\mu N \\\\\nh(N) &= 1 -\\frac{N}{K}\n\\end{align*}\n```\n\nnow we need the detivative \n```math\n\\begin{align*}\n\\frac{\\mathrm{d} [g(N) \\cdot h(N)]}{\\mathrm{d} t}= \\frac{\\mathrm{d} g(N) }{\\mathrm{d} t}  h(N) + g(N) \\frac{\\mathrm{d} h(N) }{\\mathrm{d} t} \n\\end{align*}\n```\n\nsince \n```math\n\\begin{align*}\n\\frac{\\mathrm{d} g(N) }{\\mathrm{d} t} &=\\mu\\\\\n\\frac{\\mathrm{d} h(N) }{\\mathrm{d} t} &= -\\frac{1}{K}\n\\end{align*}\n```\n\nso,\n\n```math\n\\begin{align*}\n\\frac{\\mathrm{d} (\\mu N(1 -\\frac{N}{K})}{\\mathrm{d} t} =\\mu (1 -\\frac{N}{K}) - \\frac{\\mu \\cdot N}{K}\n\\end{align*}\n```\n\n\"\n\n# ╔═╡ 32b3bc77-c4f4-40ab-a5a9-e035022189ac\nmd\"\nnow we substitute our steady state values, for $\\overline{N}=0$, we have \n\n```math\n\\begin{align*}\n\\frac{\\mathrm{d} (\\mu \\overline{N}(1 -\\frac{\\overline{N}}{K})}{\\mathrm{d} t}\\Biggr\\rvert_{\\overline{N}=0} =\\mu (1 -\\frac{0}{K}) - \\frac{\\mu \\cdot 0}{K} = \\mu\n\\end{align*}\n```\n\nSo, as long as $\\mu > 0$ this fixed point is unestable. If we have $N=0$, the systems remains there. As soon as we perturb the number (and we can only perturb by slightly increasing, these perturbations grow exponentially. For the second steady state. \n\n```math\n\\begin{align*}\n\\frac{\\mathrm{d} (\\mu \\overline{N}(1 -\\frac{\\overline{N}}{K})}{\\mathrm{d} t}\\Biggr\\rvert_{\\overline{N}=K} =\\mu (1 -\\frac{K}{K}) - \\frac{\\mu \\cdot K}{K} = - \\mu\n\\end{align*}\n```\n\nSo, as long as $\\mu > 0$ this fixed point is stable. Perturbations will allways decrease exponentially. \n\nTo observe this grafically, lets plot the function [$\\mu N(1 -\\frac{N}{K}$]\n\n\n\"\n\n# ╔═╡ c70c7a06-d1aa-40a9-902b-4bd4b23a6392\nbegin\n\tT_slide = @bind T html\"<input type=range min=5 max=15 step=1>\"\n\tK_slide = @bind K html\"<input type=range min=100 max=500 step=10>\"\n\tmd\"\"\"\n\t**Set the Cell Cycle Length and the carrying capacity**\n\t\n\tvalue of T: $(T_slide)\n\n\tvalue of K: $(K_slide)\n\t\n\t\"\"\"\nend\n\n# ╔═╡ 10ba443a-d7bc-40f2-b4f6-540328ce6e4b\nN=collect(0:0.1:K);\n\n# ╔═╡ 2cfd31c4-803a-4880-b2a4-5af6594c0975\nplot(N, log(2)/T .* N .* (1 .- (N ./ K)),label=\"T= $T, K= $K\",seriestype=:line,xlabel=(\"N\"),ylabel=(\"f(N)\"),ylims = (0,20),xlims = (0,500))\n\n# ╔═╡ 2170f883-1b01-4d16-907e-49c72118e224\nmd\"\nEquilibrium points are the values where the function is zero. We see the two of them, the unsable $\\overline{N}=0$ and the stable $\\overline{N}=K$. In this system, every perturbation moves away from $\\overline{N}=0$ towards $\\overline{N}=K$, which is the carrying capacity of the system.\n\nThe slope represents how fast the change occurs, so increasing $T$, means that we reach the carrying capacity of the system faster. \n\nSo, this is a liner model, and we can solve it analitically, so performinng a perturbation analysis does not provide extra information (we now the full dynamics because we have an analitical solution). The advantage of this perturbation analysis (or linear stabilty analysis) is when we work with systems that cannot be solved anallyically, such as systems with multiple variables, and systems with nonlinearities. \n\n\"\n\n# ╔═╡ 6c87979a-690a-400b-9ab8-7ef26b829195\nmd\"### Stability analysis of nonlinear systems: Lotka-Volterra model\n\nThe Lotka-Volterra model, also known as Predator-Prey model describes the inteactions between two populations of species where one feeds into the other.  One can think of rabbits $x$ and foxes $y$, such that rabits multiply where there is no foxes (assuming an infinite amount of food for the rabbits). This is basically a first order production of rabbits, an autocalalitic system that results in exponetial growth of rabbits.\n\nNext, foxes $y$ feed on the rabbits and multiply due to the good food conditions. Then also foxes die at a constant rate (rabbits also die, but the mdoel assumes that their rate of birth is much higher than the rate of death). The scheme of interactions for this very simple system is the following:\n\n```math\n\\begin{align}\n x &\\overset{k_1}{\\longrightarrow} 2 x   \\\\\n x + y &\\overset{k_2}{\\longrightarrow} 2 y \\\\\n y &\\overset{k_3}{\\longrightarrow} 0 \n \\end{align}\n```\n\nFirst, we find the differential equations that govern the dynamcis of the following system, and the steady state values. we start by writting the matrices of stoichiometric coefficients:\n\n```math\nA=\\begin{bmatrix}\n  1 & 0  \\\\  \n  1 & 1   \\\\\n  0 & 1       \\end{bmatrix} ;\nB=\\begin{bmatrix}\n  2 & 0   \\\\ \n  0 & 2   \\\\\n  0 & 0       \\end{bmatrix}; \\tag{8}\n```\n\n\"\n\n# ╔═╡ 04c14475-24cd-49c3-8a7b-83a9425664be\nA = [1 0;1 1;0 1];B = [2 0;0 2;0 0];(B-A)'\n\n# ╔═╡ 919bf3e4-6aa0-440b-b76f-34a4812c6752\nmd\"in this particular case\n\n```math\nK=\\begin{pmatrix}\n k_1 & 0 & 0  \\tag{9}\\\\ \n 0 &  k_2 & 0  \\\\ \n 0 &  0 & k_3 \n\\end{pmatrix}\n```\n\nand \n\n\n```math\nX^A=\\begin{pmatrix}\nX_1^1\\cdot X_2^0  \\\\\nX_1^1\\cdot X_2^1  \\\\\nX_1^0\\cdot X_2^1   \n\\end{pmatrix} = \\begin{pmatrix}\n X_1 \\\\\n X_1 \\cdot X_2\\\\\n X_2\n\\end{pmatrix} \\tag{10}\n```\n\nso, the equations that define the system are\n\n```math\n\\begin{align}\n \\begin{bmatrix}\n\\frac{\\mathrm{d} X_1}{\\mathrm{d} t}\\\\ \\frac{\\mathrm{d} X_2}{\\mathrm{d} t} \\end{bmatrix}& \n=  \\begin{bmatrix} 1 & -1 & 0  \\\\ 0 & 1 &  -1  \\end{bmatrix}\n\\begin{pmatrix}\n k_1 & 0 & 0  \\tag{9}\\\\ \n 0 &  k_2 & 0  \\\\ \n 0 &  0 & k_3 \n\\end{pmatrix}\n \\begin{pmatrix}\n X_1 \\\\\n X_1 \\cdot X_2\\\\\n X_2\n\\end{pmatrix} \n\\end{align}\n```\nand after multiplying the matrices\n```math\n\\begin{align}\n \\begin{bmatrix}\n\\frac{\\mathrm{d} X_1}{\\mathrm{d} t}\\\\ \\frac{\\mathrm{d} X_2}{\\mathrm{d} t} \\end{bmatrix}& \n=  \\begin{bmatrix} 1 & -1 & 0  \\\\ 0 & 1 &  -1  \\end{bmatrix}\n \\begin{pmatrix}\n k_1 \\cdot X_1 \\\\\n k_2 \\cdot X_1 \\cdot X_2\\\\\n k_3 \\cdot X_2\n\\end{pmatrix} \n\\end{align}\n```\n\nso finally, \n\n```math\n\\begin{align}\n \\begin{bmatrix}\n\\frac{\\mathrm{d} X_1}{\\mathrm{d} t}\\\\ \\frac{\\mathrm{d} X_2}{\\mathrm{d} t} \n\\end{bmatrix}&= \n \\begin{pmatrix}\n   k_1 \\cdot X_1 - k_2 \\cdot X_1 \\cdot X_2 \\\\\n  k_2 \\cdot X_1 \\cdot X_2 - k_3 \\cdot X_2\n\\end{pmatrix} \\tag{11}\n\\end{align}\n```\n\nTherefore, the  equations for the evolution of `[x]` and `[y]` are as follows:\n\n```math\n\\begin{align}       \n            \\frac{ dx }{dt} &=  k_1 \\cdot x - k_2 \\cdot x \\cdot y  \\tag{5}\\\\ \n            \\frac{ dy }{dt} &= k_2 \\cdot x \\cdot y - k_3 \\cdot y  \\tag{6} \n            \\end{align} \n```\n\n\n\"\n\n# ╔═╡ 855b8530-861e-427e-b6cc-c1b0283568ca\nmd\" \n\nwhich in general form, we can write as:\n\n```math\n\\begin{eqnarray}\n\\frac{\\partial x}{\\partial t} = f(x, y) \\\\\n\\frac{\\partial y}{\\partial t} = g(x, y) \n\\end{eqnarray}\n```\n\nwhere $f(x, y)$ and $g(x, y)$ are nonlinear equations that govern the temporal evolution and couple the behavior of the two variables $x$ and $y$:\n\nNext, we need to calculate the fixed points:\n\n```math\n\\begin{eqnarray}\n\\frac{\\partial \\overline{x}}{\\partial t} =0= f(\\overline{x},\\overline{y})  \\\\\n\\frac{\\partial \\overline{y}}{\\partial t}= 0 = g(\\overline{x},\\overline{y})\n\\end{eqnarray}\n```\n\nFor the particular case of the Lotcka-Volterra, we just set eqs. 5 and 6 to zero\n\n\n\n```math\n\\begin{align}       \n            k_1 \\cdot \\overline{x} - k_2 \\cdot \\overline{x} \\cdot \\overline{y}  \\tag{5} &= 0\\\\ \n            k_2 \\cdot \\overline{x} \\cdot \\overline{y} - k_3 \\cdot \\overline{y}  \\tag{6} &= 0\n            \\end{align} \n```\n\nand solve for `x` and `y`. We obtain two solutions,  $\\overline{x}=\\overline{y}=0$ and \n\n\n```math\n\\begin{align}       \n            \\overline{x} &= \\frac{k_3}{k_2}\\tag{5} \\\\ \n            \\overline{y} &= \\frac{k_1}{k_2} \\tag{6}   \n            \\end{align}    \n```\n\n\n\t\"\n\n# ╔═╡ c112e62c-9c38-48dc-8294-42911b02ccc5\nmd\" The next step is to find the characteristics of the steady states. We do that by following the same rationalle of the logistic model, i.e., to expand our equations as Taylor series around the steady state $(\\overline{x},\\overline{y})$., but now for multi-variable equations. \n\n```math\n\\begin{eqnarray}\n\\frac{\\partial x}{\\partial t} = M_{11} \\cdot x + M_{12} \\cdot y + ... \\\\\n\\frac{\\partial y}{\\partial t} = M_{21} \\cdot x + M_{22} \\cdot y + ... \n\\end{eqnarray}\n```\n            \nWhere $M_{ij}$ are the components of the Jacobian matrix, evaluated at the steady state $(\\overline{x},\\overline{y})$. \n\n```math\n\\begin{align}\n J=\\begin{bmatrix} \n M_{11} & M_{12} \\\\ \n M_{21} & M_{22}\n \\end{bmatrix}_{\\overline{x},\\overline{y}}= \\begin{bmatrix} \n\\frac{\\partial  f(x,y)}{\\partial x}\\Biggr\\rvert_{\\overline{x},\\overline{y}} & \\frac{\\partial  f(x,y)}{\\partial y}\\Biggr\\rvert_{\\overline{x},\\overline{y}} \\\\ \n\\frac{\\partial  g(x,y)}{\\partial x}\\Biggr\\rvert_{\\overline{x},\\overline{y}} & \\frac{\\partial  g(x,y)}{\\partial y}\\Biggr\\rvert_{\\overline{x},\\overline{y}}\n \\end{bmatrix} \n \\end{align} \n```\n\nwhich for the particular case of the Lotka-Volterra is \n\n\n```math\n\\begin{align}\n J=\\begin{bmatrix} \n M_{11} & M_{12} \\\\ \n M_{21} & M_{22}\n \\end{bmatrix}_{\\overline{x},\\overline{y}} = \\begin{bmatrix} \n k_1 - k_2 \\cdot \\overline{y}  &  - k_2 \\cdot \\overline{x}   \\\\ \nk_2  \\cdot \\overline{y}  & k_2 \\cdot \\overline{x}  - k_3 \n \\end{bmatrix}\n \\end{align} \n```\n\nNext, to investigate the stability, we check solutions in the form of small perturbations as follows:\n\n```math\n\\begin{eqnarray}\n(x,y) = (X_0,Y_0) e^{\\lambda t}  \n\\end{eqnarray}\n```\nHere, $\\lambda$ is the growth rate of the perturbations, also refered as eigenvalue. Each steady state will behave differently in terms of the dynamcis of the perturbations. Therefore, each steady state will have an associated eigenvalue. To find the eigen values, we solve the characteristic polynomial $det[J-\\lambda I]=0$. \n\n```math\n\\begin{eqnarray}\nDet \\left(\\begin{array}{cc}M_{11}-\\lambda & M_{12} \\\\M_{21}& M_{22}-\\lambda \\end{array}\\right) =0 \n\\end{eqnarray}\n```\nwhich gives us the corresponding equation:\n```math\n\\begin{eqnarray}\n\\lambda^{2} -\\lambda Tr(M) + Det(M)=0\n\\end{eqnarray}\n```\nwhere:\n```math\n\\begin{eqnarray}\nTr(M)= M_{11}+M_{22} \\\\\nDet(M)= M_{11}M_{22}-M_{12}M_{21} \n\\end{eqnarray}\n```\n\n\"\n\n# ╔═╡ 6c96da07-b5ea-4096-a14c-5cd8f0f47c04\nmd\"for the lotka-volterra case:\n\n```math\n\\begin{eqnarray}\nTr(M)= k_{1} + k_2 (\\overline{x}-\\overline{y}) - k_3  \\\\\nDet(M)= (k_1- k_2 \\cdot \\overline{y})(k_2 \\cdot \\overline{x} - k_3) - (k_2 \\cdot\\overline{y})(-k_2 \\cdot \\overline{x})  )\n\\end{eqnarray}\n```\n\ncalculating \n\n```math\n\\begin{eqnarray}\nTr(M)= k_{1} + k_2 (\\overline{x}-\\overline{y}) - k_3  \\\\\nDet(M)= - k_1 \\cdot k_3 - k_2^2 \\cdot \\overline{y} \\cdot \\overline{x} + k_2  \\cdot k_3 \\cdot \\overline{y} + k_1 \\cdot k_2 \\cdot \\overline{x}+ k_2^2 \\cdot\\overline{y} \\cdot \\overline{x} \n\\end{eqnarray}\n```\nand \n\n```math\n\\begin{eqnarray}\nTr(M)= k_{1} + k_2 (\\overline{x}-\\overline{y}) - k_3  \\\\\nDet(M)= k_2  \\cdot k_3 \\cdot \\overline{y} + k_1 \\cdot k_2 \\cdot \\overline{x} - k_1 \\cdot k_3 \n\\end{eqnarray}\n```\n\nso the chracteristic equation becomes:\n```math\n\\begin{eqnarray}\n\\lambda^{2} -\\lambda (k_{1} + k_2 (\\overline{x}-\\overline{y}) - k_3) + k_2  \\cdot k_3 \\cdot \\overline{y} + k_1 \\cdot k_2 \\cdot \\overline{x} - k_1 \\cdot k_3=0\n\\end{eqnarray}\n```\n\nSo, the polynomium for the fixed point $\\overline{x},\\overline{y}=[0,0]$ is \n\n```math\n\\begin{eqnarray}\n\\lambda^{2} +\\lambda (k_3 - k_{1})  - k_1 \\cdot k_3=0\n\\end{eqnarray}\n```\n\n\n\"\n\n# ╔═╡ 906a0931-e86f-48f3-be11-eb692639e8cc\nmd\" Again, since $\\lambda$ is the exponent that sets the dynamcis of the perturbations, depending on its value, the steady state is stable or unstable. \n\nFor our Locka Volterra case, we can evaluate first the eigenvalues for the first steady state  , \n\n\n\"\n\n# ╔═╡ c374e1bd-ec3d-4cf7-aff1-072d6ba60b27\nfunction quadratic(a, b, c)\n          discr = b^2 - 4*a*c\n          discr >= 0 ?   ( (-b + sqrt(discr))/(2a), (-b - sqrt(discr))/(2a) ) : error(\"Only complex roots\")\n        end\n\n# ╔═╡ 2b91a06c-3803-4877-ac9a-1669fbe58d30\nbegin\n\tk1_slide = @bind k1 html\"<input type=range min=1 max=5 step=.1>\"\n\tk2_slide = @bind k2 html\"<input type=range min=1 max=5 step=.1>\"\n\tk3_slide = @bind k3 html\"<input type=range min=1 max=5 step=.1>\"\n\tmd\"\"\"\n\t**Set the values of the kinetic constants**\n\t\n\tvalue of k1: $(k1_slide)\n\n\tvalue of k2: $(k2_slide)\n\n\tvalue of k3: $(k3_slide)\n\t\n\t\"\"\"\nend\n\n# ╔═╡ e8ca5682-cce0-4b2c-ba18-47f2e38192c7\nbegin\n\ta= 1\n\tb= k3 - k1 \n\tc= - k1 * k3\n\tquadratic(a,b,c)\nend\n\n# ╔═╡ 17e34ce6-a1fa-4193-9201-3e61a188b48f\nmd\" For this steady state and for any combination of parameters, one eigen value is positive and the other is negative. It means that perturbations in one variable grow while perturbations in the other variable decay.  \n\nThe stability of this fixed point [0,0] is of importance. If it both ewigenvalues are negative, the point will be stable, and non-zero populations might be attracted towards it, and as such the dynamics of the system might lead towards the extinction of both species for many cases of initial population levels.\n\n\nHowever, as the steady state at the origin is unstable in one of the variables, we find that the extinction of both species is difficult in the model. In fact, in teh absence of foxes and rabits, a small increase in the foxes will lead to extintion (no food), while a small increase in the amount of rabbits will read to exponential increase (the unstable branch). \n \nThese type of points are called a saddle node (a minimum in one variabel and a maximum in the other). \n\nFor the other solution $[\\overline{x},\\overline{y}]=[\\frac{k_3}{k_2},\\frac{k_1}{k_2}]$\n\nso the chracteristic equation becomes:\n```math\n\\begin{eqnarray}\n\\lambda^{2} -\\lambda (k_{1} + k_2 (\\frac{k_3}{k_2}-\\frac{k_1}{k_2}) - k_3) + k_2  \\cdot k_3 \\cdot \\frac{k_1}{k_2} + k_1 \\cdot k_2 \\cdot \\frac{k_3}{k_2} - k_1 \\cdot k_3=0\n\\end{eqnarray}\n```\n\n```math\n\\begin{eqnarray}\n\\lambda^{2}  + \\cdot k_3 \\cdot k_1 =0\n\\end{eqnarray}\n```\n\n\"\n\n# ╔═╡ 87df7c88-7e16-4c50-bd80-df5bfea26ee8\nbegin\n\t\n\taa=1\n\tbb= 0\n\tcc=- k1  + k2 *( k1 * k3)\n\tquadratic(aa,bb,cc)\nend\n\n# ╔═╡ 9433f4d1-3abf-4dea-8107-1070ee5feb2e\nmd\"The two values are purely imaginary so we cannot say much about the stability. A small perturbation will not experience repulsion or atraction towards this steady state. There is no stable state (no atractor), and trajectories circulate about the fixed point in a stable orbit. This is called a _center_. \n\nThe solutions travel periodically around the level sets in the counterclockwise direction\n\nTo test this, we solve numerically the system \n\nWe assume as initial conditions:\n\n```math\n\\begin{align}       \n            x (0) &= 1 \\tag{7} \\\\ \n            y (0) &= 1   \\tag{8}   \n\\end{align}            \n```\n       \n\"\n\n# ╔═╡ e6f51a60-9701-4ba6-a6e6-9703f7c9ebf9\nhttps://cs.carleton.edu/faculty/awb/cs111/f19/worksheets/lotka-volterra/Lotka-Volterra%20equation.pdf\n\n# ╔═╡ 2b9e43fd-d00d-40f1-ac98-07d48c53d861\nmd\" Similarly to what we did in the previous case, we would try to see the fixed points graphically. To do that in two dimensional systems, we find the functions where $\\dot{x} = 0$ and $\\dot{y} = 0$. These lines will represent the boundaries  between increase and decrease in $x$ and $y$. \n\nThese curves are called the  nullclines. The method of nullclines is a technique for determining the global behavior of solutions of competing species models. This method provides an effective means of finding trapping regions for some differential equations. In a competition model, if a species population x is above a certain level, the fact of limited resources will cause x to decrease. \n\nLet's illustrate this again with the Lotka-Volterra. The functions that satisfy that the defivatives of $x$ and $y$ are zero are:\n\n```math\n\\begin{align}       \n            k_1 \\cdot \\overline{x} - k_2 \\cdot \\overline{x} \\cdot \\overline{y}  \\tag{5} &= 0\\\\ \n            k_2 \\cdot \\overline{x} \\cdot \\overline{y} - k_3 \\cdot \\overline{y}  \\tag{6} &= 0\n            \\end{align} \n```\nIn this particuular case, the lines are very simple, just constant values. \n\n```math\n\\begin{align}       \n            \\overline{x} &= \\frac{k_3}{k_2}\\tag{5} \\\\ \n            \\overline{y} &= \\frac{k_1}{k_2} \\tag{6}   \n            \\end{align}    \n```\n\n\"\n\n# ╔═╡ a5b38e90-cdbe-442f-a078-dd8598a0a4c2\n\n\nmd\"\n\nMore concretely, if $Re(\\lambda) < 0$, the perturbation decays in time and the steady state ($\\overline{x},\\overline{y}$) is stable. \n\nOn the contrary, when $Re(\\lambda) > 0$, the perturbation grows exponentially and the steady sate is unstable. \n\nMore concretely, the steady state is stable if the following conditions are fulfilled:\n```math\n\\begin{eqnarray}\nTr(M) < 0 \\\\\nDet(M) >0\n\\end{eqnarray}\n```\n\nWe can write the eigenvalue expression separating real and imaginary part:\n```math\n\\begin{eqnarray}\n\\lambda=\\mu \\pm i \\omega  \n\\end{eqnarray}\n```\nwhere\n\n```math\n\\begin{eqnarray}\n\\mu=\\frac{1}{2} Tr(M)\\\\\n\\omega=\\sqrt{-\\frac{1}{4} Tr(M)^2 + Det(M)}\n\\end{eqnarray}\n```\n\nThe Hopf bifurcation takes place when $Det(M) > (1 / 4) Tr(M)^2 $ and $Tr(M) > 0$. In this case the eigenvalue has nonzero imaginary part and the solution of the system is oscillatory. In the Hopf threshold ($M_{11}=-M_{22}$) the complex part of the eigenvalue becomes:\n\n```math\n\\begin{eqnarray}\n\\omega^2= \\omega_{c}^{2}=-M_{11}^{2}-M_{12}M_{21}>0 \\\\\nM_{12}M_{21}>M_{11}^{2}  (>0) \n\\end{eqnarray}\n```\nOne of the values must be positive, and the other negative. We choose $M_{11}>0$ $\\longrightarrow$ $M_{22}<0$ and $M_{12}>0$ $\\longrightarrow$ $M_{21}<0$. This way, we can write Eq. \\ref{lineal1} and  Eq. \\ref{lineal2} as follows:\n\n```math\n\\begin{eqnarray}\n\\frac{\\partial x}{\\partial t} = M_{11} x - |M_{12}| y + ... \\\\\n\\frac{\\partial y}{\\partial t} = M_{21} x - |M_{22}| y + ... \n\\end{eqnarray}\n```\n\"\n\n# ╔═╡ 3349c942-15a8-4b1e-8b4a-7f5154f48b12\nlv! = @ode_def LotkaVolterra begin\n  dx = k1*x - k2*x*y\n  dy =  k2*x*y - k3*y \n    end k1 k2 k3\n\n# ╔═╡ c3828c90-0559-4686-9f56-41b5b6d48176\nbegin\n\tx₀=1\n\ty₀=1\n\tt₀=0.0\n\tfinal_time=10.0;\n\tprob = ODEProblem(lv!,[x₀,y₀],(t₀,final_time),(k1,k2,k3))\n\tsol = solve(prob)\n\tplot(sol,ylims = (0, 5))\n\n\ttitle!(\"Lotka-Volterra \")\n\txlabel!(\"time [a.u.]\")\n    ylabel!(\"Amplitude [a.u.]\")\n\t\nend\n\n# ╔═╡ ff0c4a06-de7b-4cf2-b920-cd84ac9927ea\n[u[1] for (u,t) in tuples(sol)]\n\n\n# ╔═╡ f8238a6e-1e5e-4629-ac20-2c9cb964c53e\ntuples(sol)\n\n# ╔═╡ df81eb5c-16ef-4bf6-9ad0-2cc899c44cb6\nbegin\n\tvline([k3/k2],ylims = (0, 5),xlims = (0, 10));\n\thline!([k1/k2],ylims = (0, 5),xlims = (0, 10));\n\ttitle!(\"Null-Clines of the Lotka Volterra \")\n\txlabel!(\"x [a.u.]\")\n    ylabel!(\"y [a.u.]\")\n\tplot!([u[1] for (u,t) in tuples(sol)],[u[2] for (u,t) in tuples(sol)],ylims = (0, 15))\n\nprob2 = ODEProblem(lv!,[x₀*2,y₀*2],(0.0,10.0),(k1,k2,k3))\n\tsol2 = solve(prob2)\n\tplot!([u[1] for (u,t) in tuples(sol2)],[u[2] for (u,t) in tuples(sol2)],ylims = (0, 15))\n\t\nend\n\n# ╔═╡ cf72446a-a512-11ec-2b47-ef706c91c6a0\nmd\" ## Linear stability analysis\n\nTo study the behavior of nonlinear systems, a set of mathematical tools is  commonly used. Here, we will outline its main aspects from a simplified point of view, trying to introduce the reader to the mathematics inside the nonlinear pattern formation field. In addition we will try to illustrate the problem using a very simple autocatalitic model: the _Cubic Autocatalor Model_.\n  \n### Stability of zero-Dimensional Systems\n\nThe main equation which governs the aspects of pattern formation systems is the following nonlinear equations:\n\n```math\n\\begin{eqnarray}\n\\frac{\\partial u}{\\partial t} = f(\\mu, u, v) \\\\\n\\frac{\\partial v}{\\partial t} = g(\\mu, u, v)\n\\end{eqnarray}\n```\n\nwhere $u$ and $v$ correspond to the concentration of activator and inhibitor.\nHere, $f(\\mu, u, v)$ and $g(\\mu, u, v)$ are nonlinear functions which govern the temporal evolution of the variables. \n\nThe first step is to calculate the fixed points of Eq. \\ref{base1} and \\ref{base2}, i.e., the values of the variables where the null-clines are in coincidence and equal to zero. This defines the steady state for the variables in a zero dimensional system.\n\n```math\n\\begin{eqnarray}\nf(\\mu, u, v)=0  \\\\\ng(\\mu, u, v)=0\n\\end{eqnarray}\n```\n\nAn example of the null-clines for the \\textit{Cubic Autocatalor} Model can be seen in Fig. \\ref{nullclines_cubic}. The equations for this specific model are:\n\n```math\n\\begin{eqnarray}\n\\frac{\\partial u}{\\partial t} = u^2 v -u \\\\\n\\frac{\\partial v}{\\partial t} = \\mu - u^2 v \n\\end{eqnarray}\n```\n\nThe steady state for this model is ($u_0,v_0$)= ($\\mu, 1/\\mu$).\"\n\n# ╔═╡ 67091261-3b6c-4a94-9a70-86519a1eed76\nmd\"\nThe following step to study the evolution of the system is to linearize Eq. \\ref{base1} and \\ref{base2} around the steady state $(u_{0},v_{0})$. \n\n```math\n\\begin{eqnarray}\n\\frac{\\partial u}{\\partial t} = M_{11} u + M_{12} v + f_{2}(\\mu, u, v) +   f_{3}(\\mu, u, v) + ... \\\\\n\\frac{\\partial v}{\\partial t} = M_{21} u + M_{22} v + g_{2}(\\mu, u, v) + g_{3}(\\mu, u, v) + ... \n\\end{eqnarray}\n```\nwhere $M_{ij}$ is calculated in the steady state ($u_{0},v_{0}$) as follows:\n```math\n\\begin{eqnarray}\nM_{11} = \\frac{\\partial  f(\\mu, u, v)}{\\partial u}\\\\\nM_{12} = \\frac{\\partial  f(\\mu, u, v)}{\\partial v} \\\\\nM_{21} = \\frac{\\partial  g(\\mu, u, v)}{\\partial u}\\\\\nM_{22} = \\frac{\\partial  g(\\mu, u, v)}{\\partial v}\n\\end{eqnarray}\n```\nTo investigate the stability, we check solutions in the form of small perturbations as follows:\n```math\n\\begin{eqnarray}\n(u,v) = (U,V) e^{\\lambda t}  \n\\end{eqnarray}\n```\nHere, $\\lambda$ is the growth rate of the perturbations. The next step is to solve the eigenvalue problem, resulting of the introduction of Eq. \\ref{solucion1} in the linearized system:\n```math\n\\begin{eqnarray}\nDet \\left(\\begin{array}{cc}M_{11}-\\lambda & M_{12} \\\\M_{21}& M_{22}-\\lambda \\end{array}\\right) =0 \n\\end{eqnarray}\n```\nand the corresponding equation:\n```math\n\\begin{eqnarray}\n\\lambda^{2} -\\lambda Tr(M) + Det(M)=0\n\\end{eqnarray}\n```\nwhere:\n```math\n\\begin{eqnarray}\nTr(M)= M_{11}+M_{22} \\\\\nDet(M)= M_{11}M_{22}-M{12}M_{21} \n\\end{eqnarray}\n```\n\nDepending on the value of $\\lambda$, the solution \\ref{solucion1} is stable or unstable. If $Re(\\lambda) < 0$,the perturbation decays in time and the steady state ($u_{0},v_{o}$) calculated from \\ref{base3} and \\ref{base4} is stable. More concretely, the steady state is stable if the following conditions are fulfilled:\n```math\n\\begin{eqnarray}\nTr(M) < 0 \\\\\nDet(M) >0\n\\end{eqnarray}\n```\nOn the contrary, when $Re(\\lambda) > 0$, the perturbation grows exponentially and the steady sate is unstable. We can write the eigenvalue expression separating real and imaginary part:\n```math\n\\begin{eqnarray}\n\\lambda=\\mu \\pm i \\omega  \n\\end{eqnarray}\n```\nwhere\n\n```math\n\\begin{eqnarray}\n\\mu=\\frac{1}{2} Tr(M)\\\\\n\\omega=\\sqrt{-\\frac{1}{4} Tr(M)^2 + Det(M)}\n\\end{eqnarray}\n```\n\nThe Hopf bifurcation takes place when $Det(M) > (1 / 4) Tr(M)^2 $ and $Tr(M) > 0$. In this case the eigenvalue has nonzero imaginary part and the solution of the system is oscillatory. In the Hopf threshold ($M_{11}=-M_{22}$) the complex part of the eigenvalue becomes:\n\n```math\n\\begin{eqnarray}\n\\omega^2= \\omega_{c}^{2}=-M_{11}^{2}-M_{12}M_{21}>0 \\\\\nM_{12}M_{21}>M_{11}^{2}  (>0) \n\\end{eqnarray}\n```\nOne of the values must be positive, and the other negative. We choose $M_{11}>0$ $\\longrightarrow$ $M_{22}<0$ and $M_{12}>0$ $\\longrightarrow$ $M_{21}<0$. This way, we can write Eq. \\ref{lineal1} and  Eq. \\ref{lineal2} as follows:\n\n```math\n\\begin{eqnarray}\n\\frac{\\partial u}{\\partial t} = M_{11} u - |M_{12}| v + ... \\\\\n\\frac{\\partial v}{\\partial t} = M_{21} u - |M_{22}| v + ... \n\\end{eqnarray}\n```\n$u$ plays the role of the activator due to the autocatalitic behavior (represented in Eq. \\ref{lineal3})   and $v$ is the inhibitor, which decays by itself.\n\n### Stability of Spatial Systems\n\nThe next step is to to consider the spatial dimensions of the system in Eq. \\ref{base1} and Eq. \\ref{base2}.\n\n```math\n\\begin{eqnarray}\n\\frac{\\partial u}{\\partial t} = f(\\mu, u, v)  + D_u \\frac{\\partial^{2} u}{\\partial \\vec{r}^{2}}\\\\\n\\frac{\\partial v}{\\partial t} = g(\\mu, u, v) + D_v \\frac{\\partial^{2} v}{\\partial \\vec{r}^{2}}\n\\end{eqnarray}\n```\n\nHere, $D_u$ and $D_v$ are the diffusion coefficients of activator and inhibitor and $ \\vec{r}$ is the spatial coordinate. We will scale the diffusion coefficients in a way that we can reduce to a variable which only takes account of the ratio between the diffusion coefficients: $d=D_{v}/D_{u}$. Now we have to check solutions with the spatial part: \n```math\n\\begin{eqnarray}\n(u,v) = (U,V) e^{\\lambda t + i \\vec{k}\\vec{r}}  \n\\end{eqnarray}\n```\nThe Jacobian matrix $M$ of the system is:\n```math\n\\begin{eqnarray}\nM=\\left(\\begin{array}{cc}M_{11} - k^{2} & M_{12} \\\\M_{21}& M_{22} - d k^{2} \\end{array}\\right) \n\\end{eqnarray}\n```\nIf we solve the eigenvalue problem ($Det (M-\\lambda I)=0$), as in the previous case without spatial dimensions (unstable steady state) some other conditions are required to get positive eigenvalues. The equation is:\n```math\n\\begin{eqnarray}\n\\lambda^2+\\lambda(k^2(1+d)-Tr(M))+Det(M)=0  \n\\end{eqnarray}\n```\nThe solution is in the form:\n```math\n\\begin{eqnarray}\n\\lambda=\\frac{1}{2}(-k^{2}(1+d)+Tr (M) \\pm \n \\sqrt{(k^{2}(1+d)-Tr (M))^{2}-4 B} \n \\end{eqnarray}\n```\n where\n\n```math \n \\begin{eqnarray}\n d &=& \\frac{D_{v}}{D_{u}} \\\\\n Tr (M) &=& M_{11} + M_{22} \\\\\n Det(M) &=& M_{11}  M_{22} - M_{21}  M_{12} \\\\\n B &=& d k^{4} - d k^{2} M_{11} - k^{2} M_{22} + Det (M) \n\\end{eqnarray}\n```\nSo, the system will be unstable if one of the following conditions is fulfilled: \n```math\n\\begin{eqnarray}\nk^2(1+d)-Tr(M) < 0 \\\\\n Det(M) < 0  \n\\end{eqnarray}\n```\nIn addition, if the eigenvalues are positive and real, which means that $k^2(1+d)-Tr(M))^{2}> 4 Det(M)$, the system will grow exponentially (Turing bifurcation) The system, now with spatial dimensions, develops steady periodic patterns. There is a window of unstable wavelengths which the system may exhibit ($k$ with Re[$\\lambda_{1,2}] > 0$). But there is one with maximum growth rate, which can be easily calculated by solving Eq. \\ref{eigen1}:\n```math\n\\begin{eqnarray}\n\\frac{\\partial \\lambda}{\\partial k}=0  \n\\end{eqnarray}\n```\n\n\nFig.~\\ref{Re_dispersion} is a plot of the real part of one of the the eigenvalues $\\lambda_{1}$ which has a region of positive growth for some wavenumbers in the  Lengyel-Epstein model (see Sec.~\\ref{sec:LE_model}). This means that a perturbation with a wavenumber with positive eigenvalue will grow exponentially in time. The other eigenvalue is negative, so it does not influence the behavior of the system. In addition Fig.~\\ref{Im_dispersion} shows the imaginary part of both eigenvalues. Positive imaginary values of the growth rate are outside of the regime of positive real values in Fig.~\\ref{Re_dispersion}, so the periodic pattern (with wavenumber $k$) is steady in time.\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nDifferentialEquations = \"0c46a032-eb83-5123-abaf-570d42b7fbaa\"\nHypertextLiteral = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nParameterizedFunctions = \"65888b18-ceab-5e60-b2b9-181511a3b968\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\n\n[compat]\nDifferentialEquations = \"~7.1.0\"\nHypertextLiteral = \"~0.9.3\"\nParameterizedFunctions = \"~5.13.1\"\nPlots = \"~1.27.0\"\nPlutoUI = \"~0.7.37\"\n\n[extras]\nCPUSummary = \"2a0fbf3d-bb9c-48f3-b0a9-814d99fd7ab9\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\njulia_version = \"1.7.1\"\nmanifest_format = \"2.0\"\n\n[[deps.AbstractAlgebra]]\ndeps = [\"GroupsCore\", \"InteractiveUtils\", \"LinearAlgebra\", \"MacroTools\", \"Markdown\", \"Random\", \"RandomExtensions\", \"SparseArrays\", \"Test\"]\ngit-tree-sha1 = \"c0750f99036c12a14c93a7b10609cb892ffbd092\"\nuuid = \"c3fe647b-3220-5bb0-a1ea-a7954cac585d\"\nversion = \"0.24.1\"\n\n[[deps.AbstractPlutoDingetjes]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"8eaf9f1b4921132a4cff3f36a1d9ba923b14a481\"\nuuid = \"6e696c72-6542-2067-7265-42206c756150\"\nversion = \"1.1.4\"\n\n[[deps.AbstractTrees]]\ngit-tree-sha1 = \"03e0550477d86222521d254b741d470ba17ea0b5\"\nuuid = \"1520ce14-60c1-5f80-bbc7-55ef81b5835c\"\nversion = \"0.3.4\"\n\n[[deps.Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"af92965fb30777147966f58acb05da51c5616b5f\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.3\"\n\n[[deps.ArgCheck]]\ngit-tree-sha1 = \"a3a402a35a2f7e0b87828ccabbd5ebfbebe356b4\"\nuuid = \"dce04be8-c92d-5529-be00-80e4d2c0e197\"\nversion = \"2.3.0\"\n\n[[deps.ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[deps.ArnoldiMethod]]\ndeps = [\"LinearAlgebra\", \"Random\", \"StaticArrays\"]\ngit-tree-sha1 = \"62e51b39331de8911e4a7ff6f5aaf38a5f4cc0ae\"\nuuid = \"ec485272-7323-5ecc-a04f-4719b315124d\"\nversion = \"0.2.0\"\n\n[[deps.ArrayInterface]]\ndeps = [\"Compat\", \"IfElse\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"Static\"]\ngit-tree-sha1 = \"1ee88c4c76caa995a885dc2f22a5d548dfbbc0ba\"\nuuid = \"4fba245c-0d91-5ea0-9b3e-6abc04ee57a9\"\nversion = \"3.2.2\"\n\n[[deps.ArrayLayouts]]\ndeps = [\"FillArrays\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"56c347caf09ad8acb3e261fe75f8e09652b7b05b\"\nuuid = \"4c555306-a7a7-4459-81d9-ec55ddd5c99a\"\nversion = \"0.7.10\"\n\n[[deps.Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[deps.AutoHashEquals]]\ngit-tree-sha1 = \"45bb6705d93be619b81451bb2006b7ee5d4e4453\"\nuuid = \"15f4f7f2-30c1-5605-9d31-71845cf9641f\"\nversion = \"0.2.0\"\n\n[[deps.BandedMatrices]]\ndeps = [\"ArrayLayouts\", \"FillArrays\", \"LinearAlgebra\", \"Random\", \"SparseArrays\"]\ngit-tree-sha1 = \"0a48e1230cbbf1dce4a6961e0c92615c8be20ddd\"\nuuid = \"aae01518-5342-5314-be14-df237901396f\"\nversion = \"0.16.12\"\n\n[[deps.BangBang]]\ndeps = [\"Compat\", \"ConstructionBase\", \"Future\", \"InitialValues\", \"LinearAlgebra\", \"Requires\", \"Setfield\", \"Tables\", \"ZygoteRules\"]\ngit-tree-sha1 = \"b15a6bc52594f5e4a3b825858d1089618871bf9d\"\nuuid = \"198e06fe-97b7-11e9-32a5-e1d131e6ad66\"\nversion = \"0.3.36\"\n\n[[deps.Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[deps.Baselet]]\ngit-tree-sha1 = \"aebf55e6d7795e02ca500a689d326ac979aaf89e\"\nuuid = \"9718e550-a3fa-408a-8086-8db961cd8217\"\nversion = \"0.1.1\"\n\n[[deps.Bijections]]\ngit-tree-sha1 = \"705e7822597b432ebe152baa844b49f8026df090\"\nuuid = \"e2ed5e7c-b2de-5872-ae92-c73ca462fb04\"\nversion = \"0.1.3\"\n\n[[deps.BitTwiddlingConvenienceFunctions]]\ndeps = [\"Static\"]\ngit-tree-sha1 = \"28bbdbf0354959db89358d1d79d421ff31ef0b5e\"\nuuid = \"62783981-4cbd-42fc-bca8-16325de8dc4b\"\nversion = \"0.1.3\"\n\n[[deps.BoundaryValueDiffEq]]\ndeps = [\"BandedMatrices\", \"DiffEqBase\", \"FiniteDiff\", \"ForwardDiff\", \"LinearAlgebra\", \"NLsolve\", \"Reexport\", \"SparseArrays\"]\ngit-tree-sha1 = \"fe34902ac0c3a35d016617ab7032742865756d7d\"\nuuid = \"764a87c0-6b3e-53db-9096-fe964310641d\"\nversion = \"2.7.1\"\n\n[[deps.Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[deps.CEnum]]\ngit-tree-sha1 = \"215a9aa4a1f23fbd05b92769fdd62559488d70e9\"\nuuid = \"fa961155-64e5-5f13-b03f-caf6b980ea82\"\nversion = \"0.4.1\"\n\n[[deps.CPUSummary]]\ndeps = [\"Hwloc\", \"IfElse\", \"Preferences\", \"Static\"]\ngit-tree-sha1 = \"68150205edbf60f0410ba2463b5b38eae44cad1f\"\nuuid = \"2a0fbf3d-bb9c-48f3-b0a9-814d99fd7ab9\"\nversion = \"0.1.15\"\n\n[[deps.CSTParser]]\ndeps = [\"Tokenize\"]\ngit-tree-sha1 = \"b66abc140f8b90a1d6bc7bfad5c80070f8c1ddc6\"\nuuid = \"00ebfdb7-1f24-5e51-bd34-a7502290713f\"\nversion = \"3.3.3\"\n\n[[deps.Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"4b859a208b2397a7a623a03449e4636bdb17bcf2\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+1\"\n\n[[deps.Calculus]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"f641eb0a4f00c343bbc32346e1217b86f3ce9dad\"\nuuid = \"49dc2e85-a5d0-5ad3-a950-438e2897f1b9\"\nversion = \"0.5.1\"\n\n[[deps.ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"c9a6160317d1abe9c44b3beb367fd448117679ca\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.13.0\"\n\n[[deps.ChangesOfVariables]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"bf98fa45a0a4cee295de98d4c1462be26345b9a1\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.2\"\n\n[[deps.CloseOpenIntervals]]\ndeps = [\"ArrayInterface\", \"Static\"]\ngit-tree-sha1 = \"f576084239e6bdf801007c80e27e2cc2cd963fe0\"\nuuid = \"fb6a15b2-703c-40df-9091-08a04967cfa9\"\nversion = \"0.1.6\"\n\n[[deps.ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"12fc73e5e0af68ad3137b886e3f7c1eacfca2640\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.17.1\"\n\n[[deps.ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[deps.Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[deps.Combinatorics]]\ngit-tree-sha1 = \"08c8b6831dc00bfea825826be0bc8336fc369860\"\nuuid = \"861a8166-3701-5b0c-9a16-15d98fcdc6aa\"\nversion = \"1.0.2\"\n\n[[deps.CommonMark]]\ndeps = [\"Crayons\", \"JSON\", \"URIs\"]\ngit-tree-sha1 = \"4cd7063c9bdebdbd55ede1af70f3c2f48fab4215\"\nuuid = \"a80b9123-70ca-4bc0-993e-6e3bcb318db6\"\nversion = \"0.8.6\"\n\n[[deps.CommonSolve]]\ngit-tree-sha1 = \"68a0743f578349ada8bc911a5cbd5a2ef6ed6d1f\"\nuuid = \"38540f10-b2f7-11e9-35d8-d573e4eb0ff2\"\nversion = \"0.2.0\"\n\n[[deps.CommonSubexpressions]]\ndeps = [\"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"7b8a93dba8af7e3b42fecabf646260105ac373f7\"\nuuid = \"bbf7d656-a473-5ed7-a52c-81e309532950\"\nversion = \"0.3.0\"\n\n[[deps.Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"96b0bc6c52df76506efc8a441c6cf1adcb1babc4\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.42.0\"\n\n[[deps.CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[deps.CompositeTypes]]\ngit-tree-sha1 = \"d5b014b216dc891e81fea299638e4c10c657b582\"\nuuid = \"b152e2b5-7a66-4b01-a709-34e65c35f657\"\nversion = \"0.1.2\"\n\n[[deps.CompositionsBase]]\ngit-tree-sha1 = \"455419f7e328a1a2493cabc6428d79e951349769\"\nuuid = \"a33af91c-f02d-484b-be07-31d278c5ca2b\"\nversion = \"0.1.1\"\n\n[[deps.ConstructionBase]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"f74e9d5388b8620b4cee35d4c5a618dd4dc547f4\"\nuuid = \"187b0558-2788-49d3-abe0-74a17ed4e7c9\"\nversion = \"1.3.0\"\n\n[[deps.Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[deps.Crayons]]\ngit-tree-sha1 = \"249fe38abf76d48563e2f4556bebd215aa317e15\"\nuuid = \"a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f\"\nversion = \"4.1.1\"\n\n[[deps.DEDataArrays]]\ndeps = [\"ArrayInterface\", \"DocStringExtensions\", \"LinearAlgebra\", \"RecursiveArrayTools\", \"SciMLBase\", \"StaticArrays\"]\ngit-tree-sha1 = \"5e5f8f363c8c9a2415ef9185c4e0ff6966c87d52\"\nuuid = \"754358af-613d-5f8d-9788-280bf1605d4c\"\nversion = \"0.2.2\"\n\n[[deps.DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[deps.DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"3daef5523dd2e769dad2365274f760ff5f282c7d\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.11\"\n\n[[deps.DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[deps.Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[deps.DefineSingletons]]\ngit-tree-sha1 = \"0fba8b706d0178b4dc7fd44a96a92382c9065c2c\"\nuuid = \"244e2a9f-e319-4986-a169-4d1fe445cd52\"\nversion = \"0.1.2\"\n\n[[deps.DelayDiffEq]]\ndeps = [\"ArrayInterface\", \"DataStructures\", \"DiffEqBase\", \"LinearAlgebra\", \"Logging\", \"NonlinearSolve\", \"OrdinaryDiffEq\", \"Printf\", \"RecursiveArrayTools\", \"Reexport\", \"UnPack\"]\ngit-tree-sha1 = \"52f54bd7f7bc1ce794add0ccf08f8fa21acfaed9\"\nuuid = \"bcd4f6db-9728-5f36-b5f7-82caef46ccdb\"\nversion = \"5.35.1\"\n\n[[deps.DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[deps.DensityInterface]]\ndeps = [\"InverseFunctions\", \"Test\"]\ngit-tree-sha1 = \"80c3e8639e3353e5d2912fb3a1916b8455e2494b\"\nuuid = \"b429d917-457f-4dbc-8f4c-0cc954292b1d\"\nversion = \"0.4.0\"\n\n[[deps.DiffEqBase]]\ndeps = [\"ArrayInterface\", \"ChainRulesCore\", \"DEDataArrays\", \"DataStructures\", \"Distributions\", \"DocStringExtensions\", \"FastBroadcast\", \"ForwardDiff\", \"FunctionWrappers\", \"IterativeSolvers\", \"LabelledArrays\", \"LinearAlgebra\", \"Logging\", \"MuladdMacro\", \"NonlinearSolve\", \"Parameters\", \"PreallocationTools\", \"Printf\", \"RecursiveArrayTools\", \"RecursiveFactorization\", \"Reexport\", \"Requires\", \"SciMLBase\", \"Setfield\", \"SparseArrays\", \"StaticArrays\", \"Statistics\", \"SuiteSparse\", \"ZygoteRules\"]\ngit-tree-sha1 = \"df03eb34293066d699f8a535d1ccdcff94cb9765\"\nuuid = \"2b5f629d-d688-5b77-993f-72d75c75574e\"\nversion = \"6.82.1\"\n\n[[deps.DiffEqCallbacks]]\ndeps = [\"DataStructures\", \"DiffEqBase\", \"ForwardDiff\", \"LinearAlgebra\", \"NLsolve\", \"OrdinaryDiffEq\", \"Parameters\", \"RecipesBase\", \"RecursiveArrayTools\", \"SciMLBase\", \"StaticArrays\"]\ngit-tree-sha1 = \"c4b99e3a199e293e7290eea94ba89364d47ee557\"\nuuid = \"459566f4-90b8-5000-8ac3-15dfb0a30def\"\nversion = \"2.22.0\"\n\n[[deps.DiffEqJump]]\ndeps = [\"ArrayInterface\", \"Compat\", \"DataStructures\", \"DiffEqBase\", \"FunctionWrappers\", \"Graphs\", \"LinearAlgebra\", \"PoissonRandom\", \"Random\", \"RandomNumbers\", \"RecursiveArrayTools\", \"Reexport\", \"StaticArrays\", \"TreeViews\", \"UnPack\"]\ngit-tree-sha1 = \"eec5fd03c26dadc6b20f84d815309d060358e95b\"\nuuid = \"c894b116-72e5-5b58-be3c-e6d8d4ac2b12\"\nversion = \"8.3.0\"\n\n[[deps.DiffEqNoiseProcess]]\ndeps = [\"DiffEqBase\", \"Distributions\", \"LinearAlgebra\", \"Optim\", \"PoissonRandom\", \"QuadGK\", \"Random\", \"Random123\", \"RandomNumbers\", \"RecipesBase\", \"RecursiveArrayTools\", \"Requires\", \"ResettableStacks\", \"SciMLBase\", \"StaticArrays\", \"Statistics\"]\ngit-tree-sha1 = \"d6839a44a268c69ef0ed927b22a6f43c8a4c2e73\"\nuuid = \"77a26b50-5914-5dd7-bc55-306e6241c503\"\nversion = \"5.9.0\"\n\n[[deps.DiffResults]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"c18e98cba888c6c25d1c3b048e4b3380ca956805\"\nuuid = \"163ba53b-c6d8-5494-b064-1a9d43ac40c5\"\nversion = \"1.0.3\"\n\n[[deps.DiffRules]]\ndeps = [\"IrrationalConstants\", \"LogExpFunctions\", \"NaNMath\", \"Random\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"dd933c4ef7b4c270aacd4eb88fa64c147492acf0\"\nuuid = \"b552c78f-8df3-52c6-915a-8e097449b14b\"\nversion = \"1.10.0\"\n\n[[deps.DifferentialEquations]]\ndeps = [\"BoundaryValueDiffEq\", \"DelayDiffEq\", \"DiffEqBase\", \"DiffEqCallbacks\", \"DiffEqJump\", \"DiffEqNoiseProcess\", \"LinearAlgebra\", \"LinearSolve\", \"OrdinaryDiffEq\", \"Random\", \"RecursiveArrayTools\", \"Reexport\", \"SteadyStateDiffEq\", \"StochasticDiffEq\", \"Sundials\"]\ngit-tree-sha1 = \"3f3db9365fedd5fdbecebc3cce86dfdfe5c43c50\"\nuuid = \"0c46a032-eb83-5123-abaf-570d42b7fbaa\"\nversion = \"7.1.0\"\n\n[[deps.Distances]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"3258d0659f812acde79e8a74b11f17ac06d0ca04\"\nuuid = \"b4f34e82-e78d-54a5-968a-f98e89d6e8f7\"\nversion = \"0.10.7\"\n\n[[deps.Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[deps.Distributions]]\ndeps = [\"ChainRulesCore\", \"DensityInterface\", \"FillArrays\", \"LinearAlgebra\", \"PDMats\", \"Printf\", \"QuadGK\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"Test\"]\ngit-tree-sha1 = \"c43e992f186abaf9965cc45e372f4693b7754b22\"\nuuid = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nversion = \"0.25.52\"\n\n[[deps.DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[deps.DomainSets]]\ndeps = [\"CompositeTypes\", \"IntervalSets\", \"LinearAlgebra\", \"StaticArrays\", \"Statistics\"]\ngit-tree-sha1 = \"5f5f0b750ac576bcf2ab1d7782959894b304923e\"\nuuid = \"5b8099bc-c8ec-5219-889f-1d9e522a28bf\"\nversion = \"0.5.9\"\n\n[[deps.Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[deps.DualNumbers]]\ndeps = [\"Calculus\", \"NaNMath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"90b158083179a6ccbce2c7eb1446d5bf9d7ae571\"\nuuid = \"fa6b7ba4-c1ee-5f82-b5fc-ecf0adba8f74\"\nversion = \"0.6.7\"\n\n[[deps.DynamicPolynomials]]\ndeps = [\"DataStructures\", \"Future\", \"LinearAlgebra\", \"MultivariatePolynomials\", \"MutableArithmetics\", \"Pkg\", \"Reexport\", \"Test\"]\ngit-tree-sha1 = \"d0fa82f39c2a5cdb3ee385ad52bc05c42cb4b9f0\"\nuuid = \"7c1d4256-1411-5781-91ec-d7bc3513ac07\"\nversion = \"0.4.5\"\n\n[[deps.EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[deps.EllipsisNotation]]\ndeps = [\"ArrayInterface\"]\ngit-tree-sha1 = \"d7ab55febfd0907b285fbf8dc0c73c0825d9d6aa\"\nuuid = \"da5c29d0-fa7d-589e-88eb-ea29b0a81949\"\nversion = \"1.3.0\"\n\n[[deps.Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ae13fcbc7ab8f16b0856729b050ef0c446aa3492\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.4.4+0\"\n\n[[deps.ExponentialUtilities]]\ndeps = [\"ArrayInterface\", \"LinearAlgebra\", \"Printf\", \"Requires\", \"SparseArrays\", \"libblastrampoline_jll\"]\ngit-tree-sha1 = \"b026981973ccbe38682fbb4ccb0732fd6b1e1207\"\nuuid = \"d4d017d3-3776-5f7e-afef-a10c40355c18\"\nversion = \"1.13.0\"\n\n[[deps.ExprTools]]\ngit-tree-sha1 = \"56559bbef6ca5ea0c0818fa5c90320398a6fbf8d\"\nuuid = \"e2ba6199-217a-4e67-a87a-7c52f15ade04\"\nversion = \"0.1.8\"\n\n[[deps.FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[deps.FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[deps.FastBroadcast]]\ndeps = [\"LinearAlgebra\", \"Polyester\", \"Static\"]\ngit-tree-sha1 = \"f39bcc05eb0dcbd2c0195762df7a5737041289b9\"\nuuid = \"7034ab61-46d4-4ed7-9d0f-46aef9175898\"\nversion = \"0.1.14\"\n\n[[deps.FastClosures]]\ngit-tree-sha1 = \"acebe244d53ee1b461970f8910c235b259e772ef\"\nuuid = \"9aa1b823-49e4-5ca5-8b0f-3971ec8bab6a\"\nversion = \"0.3.2\"\n\n[[deps.FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"deed294cde3de20ae0b2e0355a6c4e1c6a5ceffc\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.12.8\"\n\n[[deps.FiniteDiff]]\ndeps = [\"ArrayInterface\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"StaticArrays\"]\ngit-tree-sha1 = \"56956d1e4c1221000b7781104c58c34019792951\"\nuuid = \"6a86dc24-6348-571c-b903-95158fe2bd41\"\nversion = \"2.11.0\"\n\n[[deps.FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[deps.Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[deps.Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[deps.ForwardDiff]]\ndeps = [\"CommonSubexpressions\", \"DiffResults\", \"DiffRules\", \"LinearAlgebra\", \"LogExpFunctions\", \"NaNMath\", \"Preferences\", \"Printf\", \"Random\", \"SpecialFunctions\", \"StaticArrays\"]\ngit-tree-sha1 = \"1bd6fc0c344fc0cbee1f42f8d2e7ec8253dda2d2\"\nuuid = \"f6369f11-7733-5829-9624-2563aa707210\"\nversion = \"0.10.25\"\n\n[[deps.FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[deps.FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[deps.FunctionWrappers]]\ngit-tree-sha1 = \"241552bc2209f0fa068b6415b1942cc0aa486bcc\"\nuuid = \"069b7b12-0de2-55c6-9aab-29f3d0a68a2e\"\nversion = \"1.1.2\"\n\n[[deps.Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[deps.GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"51d2dfe8e590fbd74e7a842cf6d13d8a2f45dc01\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.6+0\"\n\n[[deps.GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"RelocatableFolders\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"9f836fb62492f4b0f0d3b06f55983f2704ed0883\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.64.0\"\n\n[[deps.GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"a6c850d77ad5118ad3be4bd188919ce97fffac47\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.64.0+0\"\n\n[[deps.GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"83ea630384a13fc4f002b77690bc0afeb4255ac9\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.2\"\n\n[[deps.Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[deps.Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"a32d672ac2c967f3deb8a81d828afc739c838a06\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+2\"\n\n[[deps.Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[deps.Graphs]]\ndeps = [\"ArnoldiMethod\", \"Compat\", \"DataStructures\", \"Distributed\", \"Inflate\", \"LinearAlgebra\", \"Random\", \"SharedArrays\", \"SimpleTraits\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"57c021de207e234108a6f1454003120a1bf350c4\"\nuuid = \"86223c79-3864-5bf0-83f7-82e725a168b6\"\nversion = \"1.6.0\"\n\n[[deps.Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[deps.Groebner]]\ndeps = [\"AbstractAlgebra\", \"Combinatorics\", \"Logging\", \"MultivariatePolynomials\", \"Primes\", \"Random\"]\ngit-tree-sha1 = \"1a13fd88bfaf0c5181da639edf4e773f756236c7\"\nuuid = \"0b43b601-686d-58a3-8a1c-6623616c7cd4\"\nversion = \"0.2.0\"\n\n[[deps.GroupsCore]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"9e1a5e9f3b81ad6a5c613d181664a0efc6fe6dd7\"\nuuid = \"d5909c97-4eac-4ecc-a3dc-fdd0858a4120\"\nversion = \"0.4.0\"\n\n[[deps.HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"0fa77022fe4b511826b39c894c90daf5fce3334a\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.17\"\n\n[[deps.HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"129acf094d168394e80ee1dc4bc06ec835e510a3\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+1\"\n\n[[deps.HostCPUFeatures]]\ndeps = [\"BitTwiddlingConvenienceFunctions\", \"IfElse\", \"Libdl\", \"Static\"]\ngit-tree-sha1 = \"18be5268cf415b5e27f34980ed25a7d34261aa83\"\nuuid = \"3e5b6fbb-0976-4d2c-9146-d79de83f2fb0\"\nversion = \"0.1.7\"\n\n[[deps.Hwloc]]\ndeps = [\"Hwloc_jll\"]\ngit-tree-sha1 = \"92d99146066c5c6888d5a3abc871e6a214388b91\"\nuuid = \"0e44f5e4-bd66-52a0-8798-143a42290a1d\"\nversion = \"2.0.0\"\n\n[[deps.Hwloc_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d8bccde6fc8300703673ef9e1383b11403ac1313\"\nuuid = \"e33a78d0-f292-5ffc-b300-72abe9b543c8\"\nversion = \"2.7.0+0\"\n\n[[deps.HypergeometricFunctions]]\ndeps = [\"DualNumbers\", \"LinearAlgebra\", \"SpecialFunctions\", \"Test\"]\ngit-tree-sha1 = \"65e4589030ef3c44d3b90bdc5aac462b4bb05567\"\nuuid = \"34004b35-14d8-5ef3-9330-4cdb6864b03a\"\nversion = \"0.3.8\"\n\n[[deps.Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[deps.HypertextLiteral]]\ngit-tree-sha1 = \"2b078b5a615c6c0396c77810d92ee8c6f470d238\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.3\"\n\n[[deps.IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[deps.IfElse]]\ngit-tree-sha1 = \"debdd00ffef04665ccbb3e150747a77560e8fad1\"\nuuid = \"615f187c-cbe4-4ef1-ba3b-2fcf58d6d173\"\nversion = \"0.1.1\"\n\n[[deps.Inflate]]\ngit-tree-sha1 = \"f5fc07d4e706b84f72d54eedcc1c13d92fb0871c\"\nuuid = \"d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9\"\nversion = \"0.1.2\"\n\n[[deps.IniFile]]\ngit-tree-sha1 = \"f550e6e32074c939295eb5ea6de31849ac2c9625\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.1\"\n\n[[deps.InitialValues]]\ngit-tree-sha1 = \"4da0f88e9a39111c2fa3add390ab15f3a44f3ca3\"\nuuid = \"22cec73e-a1b8-11e9-2c92-598750a2cf9c\"\nversion = \"0.3.1\"\n\n[[deps.InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[deps.IntervalSets]]\ndeps = [\"Dates\", \"EllipsisNotation\", \"Statistics\"]\ngit-tree-sha1 = \"bcf640979ee55b652f3b01650444eb7bbe3ea837\"\nuuid = \"8197267c-284f-5f27-9208-e0e47529a953\"\nversion = \"0.5.4\"\n\n[[deps.InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"91b5dcf362c5add98049e6c29ee756910b03051d\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.3\"\n\n[[deps.IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[deps.IterTools]]\ngit-tree-sha1 = \"fa6287a4469f5e048d763df38279ee729fbd44e5\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.4.0\"\n\n[[deps.IterativeSolvers]]\ndeps = [\"LinearAlgebra\", \"Printf\", \"Random\", \"RecipesBase\", \"SparseArrays\"]\ngit-tree-sha1 = \"1169632f425f79429f245113b775a0e3d121457c\"\nuuid = \"42fd0dbc-a981-5370-80f2-aaf504508153\"\nversion = \"0.9.2\"\n\n[[deps.IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[deps.JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"abc9885a7ca2052a736a600f7fa66209f96506e1\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.4.1\"\n\n[[deps.JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"3c837543ddb02250ef42f4738347454f95079d4e\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.3\"\n\n[[deps.JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b53380851c6e6664204efb2e62cd24fa5c47e4ba\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.2+0\"\n\n[[deps.JuliaFormatter]]\ndeps = [\"CSTParser\", \"CommonMark\", \"DataStructures\", \"Pkg\", \"Tokenize\"]\ngit-tree-sha1 = \"7a6717e8055dc3ee240c8d44668e5908d40efd2a\"\nuuid = \"98e50ef6-434e-11e9-1051-2b60c6c9e899\"\nversion = \"0.22.7\"\n\n[[deps.KLU]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"SuiteSparse_jll\"]\ngit-tree-sha1 = \"cae5e3dfd89b209e01bcd65b3a25e74462c67ee0\"\nuuid = \"ef3ab10e-7fda-4108-b977-705223b18434\"\nversion = \"0.3.0\"\n\n[[deps.Krylov]]\ndeps = [\"LinearAlgebra\", \"Printf\", \"SparseArrays\"]\ngit-tree-sha1 = \"a024280a69c49f51ba29d2deb66f07508f0b9b49\"\nuuid = \"ba0b0d4f-ebba-5204-a429-3ac8c609bfb7\"\nversion = \"0.7.13\"\n\n[[deps.KrylovKit]]\ndeps = [\"LinearAlgebra\", \"Printf\"]\ngit-tree-sha1 = \"0328ad9966ae29ccefb4e1b9bfd8c8867e4360df\"\nuuid = \"0b1a1467-8014-51b9-945f-bf0ae24f4b77\"\nversion = \"0.5.3\"\n\n[[deps.LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[deps.LERC_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"bf36f528eec6634efc60d7ec062008f171071434\"\nuuid = \"88015f11-f218-50d7-93a8-a6af411a945d\"\nversion = \"3.0.0+1\"\n\n[[deps.LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[deps.LaTeXStrings]]\ngit-tree-sha1 = \"f2355693d6778a178ade15952b7ac47a4ff97996\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.3.0\"\n\n[[deps.LabelledArrays]]\ndeps = [\"ArrayInterface\", \"ChainRulesCore\", \"LinearAlgebra\", \"MacroTools\", \"StaticArrays\"]\ngit-tree-sha1 = \"fbd884a02f8bf98fd90c53c1c9d2b21f9f30f42a\"\nuuid = \"2ee39098-c373-598a-b85f-a56591580800\"\nversion = \"1.8.0\"\n\n[[deps.Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"4f00cc36fede3c04b8acf9b2e2763decfdcecfa6\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.13\"\n\n[[deps.LayoutPointers]]\ndeps = [\"ArrayInterface\", \"LinearAlgebra\", \"ManualMemory\", \"SIMDTypes\", \"Static\"]\ngit-tree-sha1 = \"b651f573812d6c36c22c944dd66ef3ab2283dfa1\"\nuuid = \"10f19ff3-798f-405d-979b-55457f8fc047\"\nversion = \"0.1.6\"\n\n[[deps.LevyArea]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"56513a09b8e0ae6485f34401ea9e2f31357958ec\"\nuuid = \"2d8b4e74-eb68-11e8-0fb9-d5eb67b50637\"\nversion = \"1.0.0\"\n\n[[deps.LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[deps.LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[deps.LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[deps.LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[deps.Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[deps.Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"0b4a5d71f3e5200a7dff793393e09dfc2d874290\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+1\"\n\n[[deps.Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[deps.Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[deps.Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[deps.Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[deps.Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[deps.Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"LERC_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"c9551dd26e31ab17b86cbd00c2ede019c08758eb\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+1\"\n\n[[deps.Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[deps.LineSearches]]\ndeps = [\"LinearAlgebra\", \"NLSolversBase\", \"NaNMath\", \"Parameters\", \"Printf\"]\ngit-tree-sha1 = \"f27132e551e959b3667d8c93eae90973225032dd\"\nuuid = \"d3d80556-e9d4-5f37-9878-2ab0fcc64255\"\nversion = \"7.1.1\"\n\n[[deps.LinearAlgebra]]\ndeps = [\"Libdl\", \"libblastrampoline_jll\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[deps.LinearSolve]]\ndeps = [\"ArrayInterface\", \"DocStringExtensions\", \"IterativeSolvers\", \"KLU\", \"Krylov\", \"KrylovKit\", \"LinearAlgebra\", \"RecursiveFactorization\", \"Reexport\", \"Requires\", \"SciMLBase\", \"Setfield\", \"SparseArrays\", \"SuiteSparse\", \"UnPack\"]\ngit-tree-sha1 = \"a25bc80647e44d0e1e1694b47000603497700b18\"\nuuid = \"7ed4a6bd-45f5-4d41-b270-4a48e9bafcae\"\nversion = \"1.13.0\"\n\n[[deps.LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"58f25e56b706f95125dcb796f39e1fb01d913a71\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.10\"\n\n[[deps.Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[deps.LoopVectorization]]\ndeps = [\"ArrayInterface\", \"CPUSummary\", \"ChainRulesCore\", \"CloseOpenIntervals\", \"DocStringExtensions\", \"ForwardDiff\", \"HostCPUFeatures\", \"IfElse\", \"LayoutPointers\", \"LinearAlgebra\", \"OffsetArrays\", \"PolyesterWeave\", \"SIMDDualNumbers\", \"SLEEFPirates\", \"SpecialFunctions\", \"Static\", \"ThreadingUtilities\", \"UnPack\", \"VectorizationBase\"]\ngit-tree-sha1 = \"077c7c9d746cbe30ac5f001ea4c1277f64cc5dad\"\nuuid = \"bdcacae8-1622-11e9-2a5c-532679323890\"\nversion = \"0.12.103\"\n\n[[deps.MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[deps.ManualMemory]]\ngit-tree-sha1 = \"bcaef4fc7a0cfe2cba636d84cda54b5e4e4ca3cd\"\nuuid = \"d125e4d3-2237-4719-b19c-fa641b8a4667\"\nversion = \"0.1.8\"\n\n[[deps.Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[deps.MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[deps.MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[deps.Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[deps.Metatheory]]\ndeps = [\"AutoHashEquals\", \"DataStructures\", \"Dates\", \"DocStringExtensions\", \"Parameters\", \"Reexport\", \"TermInterface\", \"ThreadsX\", \"TimerOutputs\"]\ngit-tree-sha1 = \"0886d229caaa09e9f56bcf1991470bd49758a69f\"\nuuid = \"e9d8d322-4543-424a-9be4-0cc815abe26c\"\nversion = \"1.3.3\"\n\n[[deps.MicroCollections]]\ndeps = [\"BangBang\", \"InitialValues\", \"Setfield\"]\ngit-tree-sha1 = \"6bb7786e4f24d44b4e29df03c69add1b63d88f01\"\nuuid = \"128add7d-3638-4c79-886c-908ea0c25c34\"\nversion = \"0.1.2\"\n\n[[deps.Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[deps.Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[deps.ModelingToolkit]]\ndeps = [\"AbstractTrees\", \"ArrayInterface\", \"ConstructionBase\", \"DataStructures\", \"DiffEqBase\", \"DiffEqCallbacks\", \"DiffEqJump\", \"DiffRules\", \"Distributed\", \"Distributions\", \"DocStringExtensions\", \"DomainSets\", \"Graphs\", \"IfElse\", \"InteractiveUtils\", \"JuliaFormatter\", \"LabelledArrays\", \"Latexify\", \"Libdl\", \"LinearAlgebra\", \"MacroTools\", \"NaNMath\", \"NonlinearSolve\", \"RecursiveArrayTools\", \"Reexport\", \"Requires\", \"RuntimeGeneratedFunctions\", \"SafeTestsets\", \"SciMLBase\", \"Serialization\", \"Setfield\", \"SparseArrays\", \"SpecialFunctions\", \"StaticArrays\", \"SymbolicUtils\", \"Symbolics\", \"UnPack\", \"Unitful\"]\ngit-tree-sha1 = \"cdadda283d438908ca4840c0a46ea61c4959e8a0\"\nuuid = \"961ee093-0014-501f-94e3-6117800e7a78\"\nversion = \"8.5.3\"\n\n[[deps.MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[deps.MuladdMacro]]\ngit-tree-sha1 = \"c6190f9a7fc5d9d5915ab29f2134421b12d24a68\"\nuuid = \"46d2c3a1-f734-5fdb-9937-b9b9aeba4221\"\nversion = \"0.2.2\"\n\n[[deps.MultivariatePolynomials]]\ndeps = [\"DataStructures\", \"LinearAlgebra\", \"MutableArithmetics\"]\ngit-tree-sha1 = \"13ecec3d52a409be2e8653516955ec58f1c5a847\"\nuuid = \"102ac46a-7ee4-5c85-9060-abc95bfdeaa3\"\nversion = \"0.4.4\"\n\n[[deps.MutableArithmetics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"Test\"]\ngit-tree-sha1 = \"ba8c0f8732a24facba709388c74ba99dcbfdda1e\"\nuuid = \"d8a4904e-b15c-11e9-3269-09a3773c0cb0\"\nversion = \"1.0.0\"\n\n[[deps.NLSolversBase]]\ndeps = [\"DiffResults\", \"Distributed\", \"FiniteDiff\", \"ForwardDiff\"]\ngit-tree-sha1 = \"50310f934e55e5ca3912fb941dec199b49ca9b68\"\nuuid = \"d41bc354-129a-5804-8e4c-c37616107c6c\"\nversion = \"7.8.2\"\n\n[[deps.NLsolve]]\ndeps = [\"Distances\", \"LineSearches\", \"LinearAlgebra\", \"NLSolversBase\", \"Printf\", \"Reexport\"]\ngit-tree-sha1 = \"019f12e9a1a7880459d0173c182e6a99365d7ac1\"\nuuid = \"2774e3e8-f4cf-5e23-947b-6d7e65073b56\"\nversion = \"4.5.1\"\n\n[[deps.NaNMath]]\ngit-tree-sha1 = \"b086b7ea07f8e38cf122f5016af580881ac914fe\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.7\"\n\n[[deps.NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[deps.NonlinearSolve]]\ndeps = [\"ArrayInterface\", \"FiniteDiff\", \"ForwardDiff\", \"IterativeSolvers\", \"LinearAlgebra\", \"RecursiveArrayTools\", \"RecursiveFactorization\", \"Reexport\", \"SciMLBase\", \"Setfield\", \"StaticArrays\", \"UnPack\"]\ngit-tree-sha1 = \"aeebff6a2a23506e5029fd2248a26aca98e477b3\"\nuuid = \"8913a72c-1f9b-4ce2-8d82-65094dcecaec\"\nversion = \"0.3.16\"\n\n[[deps.OffsetArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"043017e0bdeff61cfbb7afeb558ab29536bbb5ed\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.8\"\n\n[[deps.Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"887579a3eb005446d514ab7aeac5d1d027658b8f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+1\"\n\n[[deps.OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[deps.OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[deps.OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ab05aa4cc89736e95915b01e7279e61b1bfe33b8\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.14+0\"\n\n[[deps.OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[deps.Optim]]\ndeps = [\"Compat\", \"FillArrays\", \"ForwardDiff\", \"LineSearches\", \"LinearAlgebra\", \"NLSolversBase\", \"NaNMath\", \"Parameters\", \"PositiveFactorizations\", \"Printf\", \"SparseArrays\", \"StatsBase\"]\ngit-tree-sha1 = \"bc0a748740e8bc5eeb9ea6031e6f050de1fc0ba2\"\nuuid = \"429524aa-4258-5aef-a3af-852621145aeb\"\nversion = \"1.6.2\"\n\n[[deps.Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[deps.OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[deps.OrdinaryDiffEq]]\ndeps = [\"Adapt\", \"ArrayInterface\", \"DataStructures\", \"DiffEqBase\", \"DocStringExtensions\", \"ExponentialUtilities\", \"FastClosures\", \"FiniteDiff\", \"ForwardDiff\", \"LinearAlgebra\", \"LinearSolve\", \"Logging\", \"LoopVectorization\", \"MacroTools\", \"MuladdMacro\", \"NLsolve\", \"NonlinearSolve\", \"Polyester\", \"PreallocationTools\", \"RecursiveArrayTools\", \"Reexport\", \"SciMLBase\", \"SparseArrays\", \"SparseDiffTools\", \"StaticArrays\", \"UnPack\"]\ngit-tree-sha1 = \"509aa6d3b2773e5109d4a4dd9a300259ac727961\"\nuuid = \"1dea7af3-3e70-54e6-95c3-0bf5283fa5ed\"\nversion = \"6.7.1\"\n\n[[deps.PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[deps.PDMats]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"SuiteSparse\"]\ngit-tree-sha1 = \"e8185b83b9fc56eb6456200e873ce598ebc7f262\"\nuuid = \"90014a1f-27ba-587c-ab20-58faa44d9150\"\nversion = \"0.11.7\"\n\n[[deps.ParameterizedFunctions]]\ndeps = [\"DataStructures\", \"DiffEqBase\", \"DocStringExtensions\", \"Latexify\", \"LinearAlgebra\", \"ModelingToolkit\", \"Reexport\", \"SciMLBase\"]\ngit-tree-sha1 = \"2f48f745e976dc5575bbc301e6c63b8fb5f12155\"\nuuid = \"65888b18-ceab-5e60-b2b9-181511a3b968\"\nversion = \"5.13.1\"\n\n[[deps.Parameters]]\ndeps = [\"OrderedCollections\", \"UnPack\"]\ngit-tree-sha1 = \"34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe\"\nuuid = \"d96e819e-fc66-5662-9728-84c9c7592b0a\"\nversion = \"0.12.3\"\n\n[[deps.Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"85b5da0fa43588c75bb1ff986493443f821c70b7\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.2.3\"\n\n[[deps.Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[deps.Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[deps.PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[deps.PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"bb16469fd5224100e422f0b027d26c5a25de1200\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.2.0\"\n\n[[deps.Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"Pkg\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\", \"UnicodeFun\", \"Unzip\"]\ngit-tree-sha1 = \"9213b4c18b57b7020ee20f33a4ba49eb7bef85e0\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.27.0\"\n\n[[deps.PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"ColorTypes\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"bf0a1121af131d9974241ba53f601211e9303a9e\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.37\"\n\n[[deps.PoissonRandom]]\ndeps = [\"Random\", \"Statistics\", \"Test\"]\ngit-tree-sha1 = \"44d018211a56626288b5d3f8c6497d28c26dc850\"\nuuid = \"e409e4f3-bfea-5376-8464-e040bb5c01ab\"\nversion = \"0.4.0\"\n\n[[deps.Polyester]]\ndeps = [\"ArrayInterface\", \"BitTwiddlingConvenienceFunctions\", \"CPUSummary\", \"IfElse\", \"ManualMemory\", \"PolyesterWeave\", \"Requires\", \"Static\", \"StrideArraysCore\", \"ThreadingUtilities\"]\ngit-tree-sha1 = \"ad769d3f29cffb33380ab28318a10c1ccb19c827\"\nuuid = \"f517fe37-dbe3-4b94-8317-1923a5111588\"\nversion = \"0.6.7\"\n\n[[deps.PolyesterWeave]]\ndeps = [\"BitTwiddlingConvenienceFunctions\", \"CPUSummary\", \"IfElse\", \"Static\", \"ThreadingUtilities\"]\ngit-tree-sha1 = \"7e597df97e46ffb1c8adbaddfa56908a7a20194b\"\nuuid = \"1d0040c9-8b98-4ee7-8388-3f51789ca0ad\"\nversion = \"0.1.5\"\n\n[[deps.PositiveFactorizations]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"17275485f373e6673f7e7f97051f703ed5b15b20\"\nuuid = \"85a6dd25-e78a-55b7-8502-1745935b8125\"\nversion = \"0.2.4\"\n\n[[deps.PreallocationTools]]\ndeps = [\"Adapt\", \"ArrayInterface\", \"ForwardDiff\", \"LabelledArrays\"]\ngit-tree-sha1 = \"6c138c8510111fa47b5d2ed8ada482d97e279bee\"\nuuid = \"d236fae5-4411-538c-8e31-a6e3d9e00b46\"\nversion = \"0.2.4\"\n\n[[deps.Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"d3538e7f8a790dc8903519090857ef8e1283eecd\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.5\"\n\n[[deps.Primes]]\ngit-tree-sha1 = \"984a3ee07d47d401e0b823b7d30546792439070a\"\nuuid = \"27ebfcd6-29c5-5fa9-bf4b-fb8fc14df3ae\"\nversion = \"0.5.1\"\n\n[[deps.Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[deps.Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[deps.QuadGK]]\ndeps = [\"DataStructures\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"78aadffb3efd2155af139781b8a8df1ef279ea39\"\nuuid = \"1fd47b50-473d-5c70-9696-f719f8f3bcdc\"\nversion = \"2.4.2\"\n\n[[deps.REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[deps.Random]]\ndeps = [\"SHA\", \"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[deps.Random123]]\ndeps = [\"Random\", \"RandomNumbers\"]\ngit-tree-sha1 = \"afeacaecf4ed1649555a19cb2cad3c141bbc9474\"\nuuid = \"74087812-796a-5b5d-8853-05524746bad3\"\nversion = \"1.5.0\"\n\n[[deps.RandomExtensions]]\ndeps = [\"Random\", \"SparseArrays\"]\ngit-tree-sha1 = \"062986376ce6d394b23d5d90f01d81426113a3c9\"\nuuid = \"fb686558-2515-59ef-acaa-46db3789a887\"\nversion = \"0.4.3\"\n\n[[deps.RandomNumbers]]\ndeps = [\"Random\", \"Requires\"]\ngit-tree-sha1 = \"043da614cc7e95c703498a491e2c21f58a2b8111\"\nuuid = \"e6cf234a-135c-5ec9-84dd-332b85af5143\"\nversion = \"1.5.3\"\n\n[[deps.RecipesBase]]\ngit-tree-sha1 = \"6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.2.1\"\n\n[[deps.RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"995a812c6f7edea7527bb570f0ac39d0fb15663c\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.5.1\"\n\n[[deps.RecursiveArrayTools]]\ndeps = [\"Adapt\", \"ArrayInterface\", \"ChainRulesCore\", \"DocStringExtensions\", \"FillArrays\", \"LinearAlgebra\", \"RecipesBase\", \"Requires\", \"StaticArrays\", \"Statistics\", \"ZygoteRules\"]\ngit-tree-sha1 = \"f5dd036acee4462949cc10c55544cc2bee2545d6\"\nuuid = \"731186ca-8d62-57ce-b412-fbd966d074cd\"\nversion = \"2.25.1\"\n\n[[deps.RecursiveFactorization]]\ndeps = [\"LinearAlgebra\", \"LoopVectorization\", \"Polyester\", \"StrideArraysCore\", \"TriangularSolve\"]\ngit-tree-sha1 = \"7ad4c2ef15b7aecd767b3921c0d255d39b3603ea\"\nuuid = \"f2c3362d-daeb-58d1-803e-2bc74f2840b4\"\nversion = \"0.2.9\"\n\n[[deps.Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[deps.Referenceables]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"e681d3bfa49cd46c3c161505caddf20f0e62aaa9\"\nuuid = \"42d2dcc6-99eb-4e98-b66c-637b7d73030e\"\nversion = \"0.1.2\"\n\n[[deps.RelocatableFolders]]\ndeps = [\"SHA\", \"Scratch\"]\ngit-tree-sha1 = \"cdbd3b1338c72ce29d9584fdbe9e9b70eeb5adca\"\nuuid = \"05181044-ff0b-4ac5-8273-598c1e38db00\"\nversion = \"0.1.3\"\n\n[[deps.Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.3.0\"\n\n[[deps.ResettableStacks]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"256eeeec186fa7f26f2801732774ccf277f05db9\"\nuuid = \"ae5879a3-cd67-5da8-be7f-38c6eb64a37b\"\nversion = \"1.1.1\"\n\n[[deps.Rmath]]\ndeps = [\"Random\", \"Rmath_jll\"]\ngit-tree-sha1 = \"bf3188feca147ce108c76ad82c2792c57abe7b1f\"\nuuid = \"79098fc4-a85e-5d69-aa6a-4863f24498fa\"\nversion = \"0.7.0\"\n\n[[deps.Rmath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"68db32dff12bb6127bac73c209881191bf0efbb7\"\nuuid = \"f50d1b31-88e8-58de-be2c-1cc44531875f\"\nversion = \"0.3.0+0\"\n\n[[deps.RuntimeGeneratedFunctions]]\ndeps = [\"ExprTools\", \"SHA\", \"Serialization\"]\ngit-tree-sha1 = \"cdc1e4278e91a6ad530770ebb327f9ed83cf10c4\"\nuuid = \"7e49a35a-f44a-4d26-94aa-eba1b4ca6b47\"\nversion = \"0.5.3\"\n\n[[deps.SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[deps.SIMDDualNumbers]]\ndeps = [\"ForwardDiff\", \"IfElse\", \"SLEEFPirates\", \"VectorizationBase\"]\ngit-tree-sha1 = \"62c2da6eb66de8bb88081d20528647140d4daa0e\"\nuuid = \"3cdde19b-5bb0-4aaf-8931-af3e248e098b\"\nversion = \"0.1.0\"\n\n[[deps.SIMDTypes]]\ngit-tree-sha1 = \"330289636fb8107c5f32088d2741e9fd7a061a5c\"\nuuid = \"94e857df-77ce-4151-89e5-788b33177be4\"\nversion = \"0.1.0\"\n\n[[deps.SLEEFPirates]]\ndeps = [\"IfElse\", \"Static\", \"VectorizationBase\"]\ngit-tree-sha1 = \"d4c366b135fc2e1af7a000473e08edc5afd94819\"\nuuid = \"476501e8-09a2-5ece-8869-fb82de89a1fa\"\nversion = \"0.6.31\"\n\n[[deps.SafeTestsets]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"36ebc5622c82eb9324005cc75e7e2cc51181d181\"\nuuid = \"1bc83da4-3b8d-516f-aca4-4fe02f6d838f\"\nversion = \"0.0.1\"\n\n[[deps.SciMLBase]]\ndeps = [\"ArrayInterface\", \"CommonSolve\", \"ConstructionBase\", \"Distributed\", \"DocStringExtensions\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"Logging\", \"RecipesBase\", \"RecursiveArrayTools\", \"StaticArrays\", \"Statistics\", \"Tables\", \"TreeViews\"]\ngit-tree-sha1 = \"c086056df381502621dc6b5f1d1a0a1c2d0185e7\"\nuuid = \"0bca4576-84f4-4d90-8ffe-ffa030f20462\"\nversion = \"1.28.0\"\n\n[[deps.Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[deps.Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[deps.Setfield]]\ndeps = [\"ConstructionBase\", \"Future\", \"MacroTools\", \"Requires\"]\ngit-tree-sha1 = \"38d88503f695eb0301479bc9b0d4320b378bafe5\"\nuuid = \"efcf1570-3423-57d1-acb7-fd33fddbac46\"\nversion = \"0.8.2\"\n\n[[deps.SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[deps.Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[deps.SimpleTraits]]\ndeps = [\"InteractiveUtils\", \"MacroTools\"]\ngit-tree-sha1 = \"5d7e3f4e11935503d3ecaf7186eac40602e7d231\"\nuuid = \"699a6c99-e7fa-54fc-8d76-47d257e15c1d\"\nversion = \"0.9.4\"\n\n[[deps.Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[deps.SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[deps.SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[deps.SparseDiffTools]]\ndeps = [\"Adapt\", \"ArrayInterface\", \"Compat\", \"DataStructures\", \"FiniteDiff\", \"ForwardDiff\", \"Graphs\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"StaticArrays\", \"VertexSafeGraphs\"]\ngit-tree-sha1 = \"87efd1676d87706f4079e8e717a7a5f02b6ea1ad\"\nuuid = \"47a9eef4-7e08-11e9-0b38-333d64bd3804\"\nversion = \"1.20.2\"\n\n[[deps.SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"5ba658aeecaaf96923dce0da9e703bd1fe7666f9\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"2.1.4\"\n\n[[deps.SplittablesBase]]\ndeps = [\"Setfield\", \"Test\"]\ngit-tree-sha1 = \"39c9f91521de844bad65049efd4f9223e7ed43f9\"\nuuid = \"171d559e-b47b-412a-8079-5efa626c420e\"\nversion = \"0.1.14\"\n\n[[deps.Static]]\ndeps = [\"IfElse\"]\ngit-tree-sha1 = \"7f5a513baec6f122401abfc8e9c074fdac54f6c1\"\nuuid = \"aedffcd0-7271-4cad-89d0-dc628f76c6d3\"\nversion = \"0.4.1\"\n\n[[deps.StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"6976fab022fea2ffea3d945159317556e5dad87c\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.4.2\"\n\n[[deps.Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[deps.StatsAPI]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"c3d8ba7f3fa0625b062b82853a7d5229cb728b6b\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.2.1\"\n\n[[deps.StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"8977b17906b0a1cc74ab2e3a05faa16cf08a8291\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.16\"\n\n[[deps.StatsFuns]]\ndeps = [\"ChainRulesCore\", \"HypergeometricFunctions\", \"InverseFunctions\", \"IrrationalConstants\", \"LogExpFunctions\", \"Reexport\", \"Rmath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"25405d7016a47cf2bd6cd91e66f4de437fd54a07\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.16\"\n\n[[deps.SteadyStateDiffEq]]\ndeps = [\"DiffEqBase\", \"DiffEqCallbacks\", \"LinearAlgebra\", \"NLsolve\", \"Reexport\", \"SciMLBase\"]\ngit-tree-sha1 = \"3e057e1f9f12d18cac32011aed9e61eef6c1c0ce\"\nuuid = \"9672c7b4-1e72-59bd-8a11-6ac3964bc41f\"\nversion = \"1.6.6\"\n\n[[deps.StochasticDiffEq]]\ndeps = [\"Adapt\", \"ArrayInterface\", \"DataStructures\", \"DiffEqBase\", \"DiffEqJump\", \"DiffEqNoiseProcess\", \"DocStringExtensions\", \"FillArrays\", \"FiniteDiff\", \"ForwardDiff\", \"LevyArea\", \"LinearAlgebra\", \"Logging\", \"MuladdMacro\", \"NLsolve\", \"OrdinaryDiffEq\", \"Random\", \"RandomNumbers\", \"RecursiveArrayTools\", \"Reexport\", \"SparseArrays\", \"SparseDiffTools\", \"StaticArrays\", \"UnPack\"]\ngit-tree-sha1 = \"24d8b3ab7e91b351ccbed5e54499a1864a64a6c6\"\nuuid = \"789caeaf-c7a9-5a7d-9973-96adeb23e2a0\"\nversion = \"6.45.0\"\n\n[[deps.StrideArraysCore]]\ndeps = [\"ArrayInterface\", \"CloseOpenIntervals\", \"IfElse\", \"LayoutPointers\", \"ManualMemory\", \"Requires\", \"SIMDTypes\", \"Static\", \"ThreadingUtilities\"]\ngit-tree-sha1 = \"49d616ef230fec080d02ada0ca5639e652cca06b\"\nuuid = \"7792a7ef-975c-4747-a70f-980b88e8d1da\"\nversion = \"0.2.13\"\n\n[[deps.StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"57617b34fa34f91d536eb265df67c2d4519b8b98\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.5\"\n\n[[deps.SuiteSparse]]\ndeps = [\"Libdl\", \"LinearAlgebra\", \"Serialization\", \"SparseArrays\"]\nuuid = \"4607b0f0-06f3-5cda-b6b1-a6196a1729e9\"\n\n[[deps.SuiteSparse_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"Pkg\", \"libblastrampoline_jll\"]\nuuid = \"bea87d4a-7f5b-5778-9afe-8cc45184846c\"\n\n[[deps.Sundials]]\ndeps = [\"CEnum\", \"DataStructures\", \"DiffEqBase\", \"Libdl\", \"LinearAlgebra\", \"Logging\", \"Reexport\", \"SparseArrays\", \"Sundials_jll\"]\ngit-tree-sha1 = \"e0805213754f0d871f9333eacd77862a44acb46d\"\nuuid = \"c3572dad-4567-51f8-b174-8c6c989267f4\"\nversion = \"4.9.3\"\n\n[[deps.Sundials_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"OpenBLAS_jll\", \"Pkg\", \"SuiteSparse_jll\"]\ngit-tree-sha1 = \"04777432d74ec5bc91ca047c9e0e0fd7f81acdb6\"\nuuid = \"fb77eaff-e24c-56d4-86b1-d163f2edb164\"\nversion = \"5.2.1+0\"\n\n[[deps.SymbolicUtils]]\ndeps = [\"AbstractTrees\", \"Bijections\", \"ChainRulesCore\", \"Combinatorics\", \"ConstructionBase\", \"DataStructures\", \"DocStringExtensions\", \"DynamicPolynomials\", \"IfElse\", \"LabelledArrays\", \"LinearAlgebra\", \"Metatheory\", \"MultivariatePolynomials\", \"NaNMath\", \"Setfield\", \"SparseArrays\", \"SpecialFunctions\", \"StaticArrays\", \"TermInterface\", \"TimerOutputs\"]\ngit-tree-sha1 = \"bfa211c9543f8c062143f2a48e5bcbb226fd790b\"\nuuid = \"d1185830-fcd6-423d-90d6-eec64667417b\"\nversion = \"0.19.7\"\n\n[[deps.Symbolics]]\ndeps = [\"ArrayInterface\", \"ConstructionBase\", \"DataStructures\", \"DiffRules\", \"Distributions\", \"DocStringExtensions\", \"DomainSets\", \"Groebner\", \"IfElse\", \"Latexify\", \"Libdl\", \"LinearAlgebra\", \"MacroTools\", \"Metatheory\", \"NaNMath\", \"RecipesBase\", \"Reexport\", \"Requires\", \"RuntimeGeneratedFunctions\", \"SciMLBase\", \"Setfield\", \"SparseArrays\", \"SpecialFunctions\", \"StaticArrays\", \"SymbolicUtils\", \"TermInterface\", \"TreeViews\"]\ngit-tree-sha1 = \"759d6102719068d95acae0b5480c157fa278ca82\"\nuuid = \"0c5d862f-8b57-4792-8d23-62f2024744c7\"\nversion = \"4.3.1\"\n\n[[deps.TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[deps.TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[deps.Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"OrderedCollections\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"5ce79ce186cc678bbb5c5681ca3379d1ddae11a1\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.7.0\"\n\n[[deps.Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[deps.TermInterface]]\ngit-tree-sha1 = \"7aa601f12708243987b88d1b453541a75e3d8c7a\"\nuuid = \"8ea1fca8-c5ef-4a55-8b96-4e9afe9c9a3c\"\nversion = \"0.2.3\"\n\n[[deps.Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[deps.ThreadingUtilities]]\ndeps = [\"ManualMemory\"]\ngit-tree-sha1 = \"f8629df51cab659d70d2e5618a430b4d3f37f2c3\"\nuuid = \"8290d209-cae3-49c0-8002-c8c24d57dab5\"\nversion = \"0.5.0\"\n\n[[deps.ThreadsX]]\ndeps = [\"ArgCheck\", \"BangBang\", \"ConstructionBase\", \"InitialValues\", \"MicroCollections\", \"Referenceables\", \"Setfield\", \"SplittablesBase\", \"Transducers\"]\ngit-tree-sha1 = \"d223de97c948636a4f34d1f84d92fd7602dc555b\"\nuuid = \"ac1d9e8a-700a-412c-b207-f0111f4b6c0d\"\nversion = \"0.1.10\"\n\n[[deps.TimerOutputs]]\ndeps = [\"ExprTools\", \"Printf\"]\ngit-tree-sha1 = \"d60b0c96a16aaa42138d5d38ad386df672cb8bd8\"\nuuid = \"a759f4b9-e2f1-59dc-863e-4aeb61b1ea8f\"\nversion = \"0.5.16\"\n\n[[deps.Tokenize]]\ngit-tree-sha1 = \"0952c9cee34988092d73a5708780b3917166a0dd\"\nuuid = \"0796e94c-ce3b-5d07-9a54-7f471281c624\"\nversion = \"0.5.21\"\n\n[[deps.Transducers]]\ndeps = [\"Adapt\", \"ArgCheck\", \"BangBang\", \"Baselet\", \"CompositionsBase\", \"DefineSingletons\", \"Distributed\", \"InitialValues\", \"Logging\", \"Markdown\", \"MicroCollections\", \"Requires\", \"Setfield\", \"SplittablesBase\", \"Tables\"]\ngit-tree-sha1 = \"c76399a3bbe6f5a88faa33c8f8a65aa631d95013\"\nuuid = \"28d57a85-8fef-5791-bfe6-a80928e7c999\"\nversion = \"0.4.73\"\n\n[[deps.TreeViews]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d0d7a3fe2f30d6a7f833a5f19f7c7a5b396eae6\"\nuuid = \"a2a6695c-b41b-5b7d-aed9-dbfdeacea5d7\"\nversion = \"0.3.0\"\n\n[[deps.TriangularSolve]]\ndeps = [\"CloseOpenIntervals\", \"IfElse\", \"LayoutPointers\", \"LinearAlgebra\", \"LoopVectorization\", \"Polyester\", \"Static\", \"VectorizationBase\"]\ngit-tree-sha1 = \"b8d08f55b02625770c09615d96927b3a8396925e\"\nuuid = \"d5829a12-d9aa-46ab-831f-fb7c9ab06edf\"\nversion = \"0.1.11\"\n\n[[deps.URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[deps.UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[deps.UnPack]]\ngit-tree-sha1 = \"387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b\"\nuuid = \"3a884ed6-31ef-47d7-9d2a-63182c4928ed\"\nversion = \"1.0.2\"\n\n[[deps.Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[deps.UnicodeFun]]\ndeps = [\"REPL\"]\ngit-tree-sha1 = \"53915e50200959667e78a92a418594b428dffddf\"\nuuid = \"1cfade01-22cf-5700-b092-accc4b62d6e1\"\nversion = \"0.4.1\"\n\n[[deps.Unitful]]\ndeps = [\"ConstructionBase\", \"Dates\", \"LinearAlgebra\", \"Random\"]\ngit-tree-sha1 = \"b649200e887a487468b71821e2644382699f1b0f\"\nuuid = \"1986cc42-f94f-5a68-af5c-568840ba703d\"\nversion = \"1.11.0\"\n\n[[deps.Unzip]]\ngit-tree-sha1 = \"34db80951901073501137bdbc3d5a8e7bbd06670\"\nuuid = \"41fe7b60-77ed-43a1-b4f0-825fd5a5650d\"\nversion = \"0.1.2\"\n\n[[deps.VectorizationBase]]\ndeps = [\"ArrayInterface\", \"CPUSummary\", \"HostCPUFeatures\", \"Hwloc\", \"IfElse\", \"LayoutPointers\", \"Libdl\", \"LinearAlgebra\", \"SIMDTypes\", \"Static\"]\ngit-tree-sha1 = \"1901efb08ce6c4526ddf7fdfa9181dc3593fe6a2\"\nuuid = \"3d5dd08c-fd9d-11e8-17fa-ed2836048c2f\"\nversion = \"0.21.25\"\n\n[[deps.VertexSafeGraphs]]\ndeps = [\"Graphs\"]\ngit-tree-sha1 = \"8351f8d73d7e880bfc042a8b6922684ebeafb35c\"\nuuid = \"19fa3120-7c27-5ec5-8db8-b0b0aa330d6f\"\nversion = \"0.2.0\"\n\n[[deps.Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[deps.Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4528479aa01ee1b3b4cd0e6faef0e04cf16466da\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.25.0+0\"\n\n[[deps.XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[deps.XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[deps.Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[deps.Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[deps.Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[deps.Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[deps.Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[deps.Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[deps.Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[deps.Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[deps.Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[deps.Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[deps.Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[deps.Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[deps.Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[deps.Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[deps.Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[deps.Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[deps.Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[deps.Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[deps.Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[deps.Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e45044cd873ded54b6a5bac0eb5c971392cf1927\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.2+0\"\n\n[[deps.ZygoteRules]]\ndeps = [\"MacroTools\"]\ngit-tree-sha1 = \"8c1a8e4dfacb1fd631745552c8db35d0deb09ea0\"\nuuid = \"700de1a5-db45-46bc-99cf-38207098b444\"\nversion = \"0.2.2\"\n\n[[deps.libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[deps.libblastrampoline_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"OpenBLAS_jll\"]\nuuid = \"8e850b90-86db-534c-a0d3-1478176c7d93\"\n\n[[deps.libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[deps.libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[deps.libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"b910cb81ef3fe6e78bf6acee440bda86fd6ae00c\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+1\"\n\n[[deps.nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[deps.p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[deps.x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[deps.x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[deps.xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─279eaa4f-41ca-4168-b492-f36543bb8204\n# ╟─00037d0a-8be0-4c75-94bc-23c2c639e6e8\n# ╟─64dc539b-b268-43b6-a96e-2c4fa7b48474\n# ╟─f5faefd6-f496-40fb-8043-ef6b9d172ae0\n# ╟─32b3bc77-c4f4-40ab-a5a9-e035022189ac\n# ╟─c70c7a06-d1aa-40a9-902b-4bd4b23a6392\n# ╠═10ba443a-d7bc-40f2-b4f6-540328ce6e4b\n# ╠═2cfd31c4-803a-4880-b2a4-5af6594c0975\n# ╟─2170f883-1b01-4d16-907e-49c72118e224\n# ╟─6c87979a-690a-400b-9ab8-7ef26b829195\n# ╠═04c14475-24cd-49c3-8a7b-83a9425664be\n# ╟─919bf3e4-6aa0-440b-b76f-34a4812c6752\n# ╟─855b8530-861e-427e-b6cc-c1b0283568ca\n# ╟─c112e62c-9c38-48dc-8294-42911b02ccc5\n# ╟─6c96da07-b5ea-4096-a14c-5cd8f0f47c04\n# ╟─906a0931-e86f-48f3-be11-eb692639e8cc\n# ╠═c374e1bd-ec3d-4cf7-aff1-072d6ba60b27\n# ╠═2b91a06c-3803-4877-ac9a-1669fbe58d30\n# ╠═e8ca5682-cce0-4b2c-ba18-47f2e38192c7\n# ╟─17e34ce6-a1fa-4193-9201-3e61a188b48f\n# ╠═87df7c88-7e16-4c50-bd80-df5bfea26ee8\n# ╟─9433f4d1-3abf-4dea-8107-1070ee5feb2e\n# ╠═c3828c90-0559-4686-9f56-41b5b6d48176\n# ╠═e6f51a60-9701-4ba6-a6e6-9703f7c9ebf9\n# ╟─2b9e43fd-d00d-40f1-ac98-07d48c53d861\n# ╠═ff0c4a06-de7b-4cf2-b920-cd84ac9927ea\n# ╠═f8238a6e-1e5e-4629-ac20-2c9cb964c53e\n# ╠═df81eb5c-16ef-4bf6-9ad0-2cc899c44cb6\n# ╠═a5b38e90-cdbe-442f-a078-dd8598a0a4c2\n# ╠═8c3e21c9-6514-4f14-8b1f-325d124681f5\n# ╠═ac95a2ae-5b1b-4399-8265-4b0bfb21162e\n# ╠═3349c942-15a8-4b1e-8b4a-7f5154f48b12\n# ╠═cf72446a-a512-11ec-2b47-ef706c91c6a0\n# ╠═67091261-3b6c-4a94-9a70-86519a1eed76\n# ╠═2e6401b9-9c89-4b4b-8492-d0a83003579b\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "24f3bed274f6d6b5b40f7f30a188affc1bb15896", "size": 98413, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "11 Linear Stability Analysis.jl", "max_stars_repo_name": "davidgmiguez/PlutoNotebooks", "max_stars_repo_head_hexsha": "7997ea6a3a6bc942a621b66804fb711b4bad440d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "11 Linear Stability Analysis.jl", "max_issues_repo_name": "davidgmiguez/PlutoNotebooks", "max_issues_repo_head_hexsha": "7997ea6a3a6bc942a621b66804fb711b4bad440d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "11 Linear Stability Analysis.jl", "max_forks_repo_name": "davidgmiguez/PlutoNotebooks", "max_forks_repo_head_hexsha": "7997ea6a3a6bc942a621b66804fb711b4bad440d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1679529585, "max_line_length": 682, "alphanum_fraction": 0.7220692388, "num_tokens": 40928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.7517509983495039}}
{"text": "using LinearAlgebra\nimport LinearAlgebra.Eigen\nusing SparseArrays\n#this lib will be used to estimate the executon time\n\n\n\nstruct SVDCM\n\tU::Matrix{Float64}\n\tS::SparseMatrixCSC{Float64, Int64}\n\tS_inv::SparseMatrixCSC{Float64, Int64}\n\tV::Matrix{Float64}\n\n\tfunction SVDCM(A::Matrix{Float64})\n\t\tU, S, V,S_inv = svdCm(A)\n\t\treturn new( U, S, S_inv,V)\n\tend\n\tfunction svdCm(A::Matrix{Float64})\n\n\t\tr,c = size(A)\n\t\tshorter=min(r,c)\n\t\tlonger=max(r,c)\n\n\t\tAsq = zeros(shorter,shorter) \n\t\tmul!(Asq, A', A)\n\t\ta, V = eigen!(Asq)\n\n\t\tS = sparse(zeros(longer,shorter))\n\t\tSin = sparse(zeros(shorter,longer))\n\n\t\tS[diagind(S)] .= (sqrt.(a))\n\t\tSin[diagind(Sin)] .= 1 ./ S[diagind(S)]\n\n\t\tU1 = zeros(r,c) \n\t\tU = zeros(longer,longer)\n\n\t\tmul!(U1, A, V)\n\t\tmul!(U,U1,Sin) \n\t\treturn U, S, V, Sin\n\tend\nend\n\n", "meta": {"hexsha": "f9dcee3de5fff395df2488d686d401d0495826ac", "size": 775, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ELM/src/CM_SVD.jl", "max_stars_repo_name": "MLP-GAF/CM_Project", "max_stars_repo_head_hexsha": "662283ecee17117cb2765255cd956b2e5cd77f11", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ELM/src/CM_SVD.jl", "max_issues_repo_name": "MLP-GAF/CM_Project", "max_issues_repo_head_hexsha": "662283ecee17117cb2765255cd956b2e5cd77f11", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ELM/src/CM_SVD.jl", "max_forks_repo_name": "MLP-GAF/CM_Project", "max_forks_repo_head_hexsha": "662283ecee17117cb2765255cd956b2e5cd77f11", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.023255814, "max_line_length": 52, "alphanum_fraction": 0.655483871, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799430946808, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7517415080921976}}
{"text": "using LinearAlgebra\nA = [0 1/2 1/4; 1 1 2; 2 1 1.5]\nF = lu(A) # like \"A^{-1}\"\n##\nprintln(\"P = \")\ndisplay(F.P)\nprintln(\"L = \")\ndisplay(F.L)\nprintln(\"U = \")\ndisplay(F.U)\n##\n@show norm(F.P*A - F.L*F.U)\n", "meta": {"hexsha": "fcde832c40a74da5e06fdf069dda358da9cbd0db", "size": 199, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4-unit-3-demos/lu-example.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "4-unit-3-demos/lu-example.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4-unit-3-demos/lu-example.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 15.3076923077, "max_line_length": 31, "alphanum_fraction": 0.5376884422, "num_tokens": 87, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9637799472560581, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.7517415064090816}}
{"text": "import Pkg; Pkg.add(Pkg.PackageSpec(url=\"https://github.com/JuliaComputing/JuliaAcademyData.jl\"))\nusing JuliaAcademyData; activate(\"Deep learning with Flux\")\n\n# <br/>\n#\n# # Intro to Flux.jl\n\n#-\n\n# In the previous course, we learned how machine learning allows us to classify data as apples or bananas with a single neuron. However, some of those details are pretty fiddly! Fortunately, Julia has a powerful package that does much of the heavy lifting for us, called [`Flux.jl`](https://fluxml.github.io/).\n#\n# *Using `Flux` will make classifying data and images much easier!*\n\n#-\n\n# ## Using `Flux.jl`\n#\n# We can get started with `Flux.jl` via:\n\n## using Pkg; Pkg.add([\"Flux\", \"Plots\"])\nusing Flux, Plots\n\n# #### Helpful built-in functions\n#\n# When working we'll `Flux`, we'll make use of built-in functionality that we've had to create for ourselves in previous notebooks.\n#\n# For example, the sigmoid function, σ, that we have been using already lives within `Flux`:\n\n#nb ?σ\n#jl @doc σ\n\n#-\n\nplot(σ, -5, 5, label=\"\\\\sigma\", xlabel=\"x\", ylabel=\"\\\\sigma\\\\(x\\\\)\")\n\n# Importantly, `Flux` allows us to *automatically create neurons* with the **`Dense`** function. For example, in the last notebook, we were looking at a neuron with 2 inputs and 1 output:\n#\n#  <img src=\"https://raw.githubusercontent.com/JuliaComputing/JuliaAcademyData.jl/master/courses/Deep%20learning%20with%20Flux/data/single-neuron.png\" alt=\"Drawing\" style=\"width: 500px;\"/>\n#\n#  We could create a neuron with two inputs and one output via\n\nmodel = Dense(2, 1, σ)\n\n# This `model` object comes with places to store weights and biases:\n\nmodel.W\n\n#-\n\nmodel.b\n\n#-\n\ntypeof(model.W)\n\n#-\n\nx = rand(2)\nmodel(x)\n\n#-\n\nσ.(model.W*x + model.b)\n\n# Unlike in previous notebooks, note that `W` is no longer a `Vector` (1D `Array`) and `b` is no longer a number! Both are now stored in so-called `TrackedArray`s and `W` is effectively being treated as a matrix with a single row. We'll see why below.\n\n#-\n\n# Other helpful built-in functionality includes ways to automatically calculate gradients and also the cost function that we've used in the previous course -\n#\n# $$L(w, b) = \\sum_i \\left[y_i - f(x_i, w, b) \\right]^2$$\n#\n# If you normalize by dividing by the total number of elements, this becomes the \"mean square error\" function, which in `Flux` is named **`Flux.mse`**.\n\nmethods(Flux.mse)\n\n# ### Bringing it all together\n#\n# Load the datasets that contain the features of the apple and banana images.\n\nusing CSV, DataFrames\n\napples = DataFrame(CSV.File(datapath(\"data/apples.dat\"), delim='\\t', allowmissing=:none, normalizenames=true))\nbananas = DataFrame(CSV.File(datapath(\"data/bananas.dat\"), delim='\\t', allowmissing=:none, normalizenames=true));\n\n#-\n\nx_apples  = [ [row.red, row.green] for row in eachrow(apples)]\nx_bananas = [ [row.red, row.green] for row in eachrow(bananas)];\n\n# Concatenate the x (features) together to create a vector of all our datapoints, and create the corresponding vector of known labels:\n\nxs = [x_apples; x_bananas]\nys = [fill(0, size(x_apples)); fill(1, size(x_bananas))];\n\n#-\n\nmodel = Dense(2, 1, σ)\n\n# We can evaluate the model (currently initialized with random weights) to see what the output value is for a given input:\n\nmodel(xs[1])\n\n# And of course we can examine the current loss value for that datapoint:\n\nloss = Flux.mse(model(xs[1]), ys[1])\n\n#-\n\ntypeof(loss)\n\n# ### Backpropagation\n\nmodel.W\n\n#-\n\nmodel.W.grad\n\n#-\n\nusing Flux.Tracker\nback!(loss)\n\n#-\n\nmodel.W.grad\n\n# Now we have all the tools necessary to build a simple gradient descent algorithm!\n\n#-\n\n# ### The easy way\n#\n# You don't want to manually write out gradient descent algorithms every time! Flux, of course, also brings in lots of optimizers that can do this all for you.\n\n#nb ?SGD\n#jl @doc SGD\n\n#-\n\n#nb ?Flux.train!\n#jl @doc Flux.train!\n\n# So we can simply define our loss function, an optimizer, and then call `train!`. That's basic machine learning with Flux.jl.\n\nmodel = Dense(2, 1, σ)\nL(x,y) = Flux.mse(model(x), y)\nopt = SGD(params(model))\nFlux.train!(L, zip(xs, ys), opt)\n\n# ## Visualize the result\n\ncontour(0:.1:1, 0:.1:1, (x, y) -> model([x,y])[].data, fill=true)\nscatter!(first.(x_apples), last.(x_apples), label=\"apples\")\nscatter!(first.(x_bananas), last.(x_bananas), label=\"bananas\")\nxlabel!(\"mean red value\")\nylabel!(\"mean green value\")\n\n", "meta": {"hexsha": "e7f33b6c4a81c1b0a0f5705e80ef70d1246e69bb", "size": 4315, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Deep learning with Flux/1300.Intro-to-Flux.jl.jl", "max_stars_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_stars_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2020-02-13T00:50:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T07:57:22.000Z", "max_issues_repo_path": "Courses/Deep learning with Flux/1300.Intro-to-Flux.jl.jl", "max_issues_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_issues_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2019-10-30T16:22:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-26T20:02:43.000Z", "max_forks_repo_path": "Courses/Deep learning with Flux/1300.Intro-to-Flux.jl.jl", "max_forks_repo_name": "fercarozzi/JuliaAcademyMaterials", "max_forks_repo_head_hexsha": "4c7501d42e698379050fd6e6d469f3f84428cdcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2020-02-26T11:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T22:34:53.000Z", "avg_line_length": 26.96875, "max_line_length": 310, "alphanum_fraction": 0.7066048667, "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.7517298504697651}}
{"text": "\"\"\"\r\nThis enum is used to select the distance calculation type.\r\nWe converted the name into a string, and the magic happens! :D\r\n\r\n# DistanceType Possibilities:\r\n\r\n    Euclidean, Cityblock, TotalVariation, Chebyshev,\r\n    Jaccard, BrayCurtis, SpanNormDist\r\n\r\n# Examples:\r\n\r\n    Euclidean::DistanceType\r\n    Cityblock::DistanceType\r\n\"\"\"\r\n@enum DistanceType begin\r\n\r\n    Euclidean = 1\r\n    Cityblock = 2\r\n    TotalVariation = 3\r\n    Chebyshev = 4\r\n    Jaccard = 5\r\n    BrayCurtis = 6\r\n    SpanNormDist = 7\r\n\r\nend\r\n\r\n#=\r\n\r\n    This dictionary is used with the enum DistanceType to\r\n    select the distance calculation.\r\n    After convert the enum in a string we applied in this dictionary. :)\r\n\r\n=#\r\n\r\n#add\r\n# Creating the dictionary\r\n\r\ndistanceFormulas = Dict()\r\n\r\n# Setting Euclidean\r\ntemp_euc(x, y) = sqrt(sum((x - y) .^ 2))\r\ndistanceFormulas[\"Euclidean\"] = temp_euc\r\n\r\n# Setting Cityblock\r\ntemp_cb(x, y) = sum(abs.(x - y))\r\ndistanceFormulas[\"Cityblock\"] = temp_cb\r\n\r\n# Setting TotalVariation\r\ntemp_tv(x, y) = sum(abs.(x - y)) / 2\r\ndistanceFormulas[\"TotalVariation\"] = temp_tv\r\n\r\n# Setting Chebyshev\r\ntemp_chby(x, y) = maximum(abs.(x - y))\r\ndistanceFormulas[\"Chebyshev\"] = temp_chby\r\n\r\n# Setting Jaccard\r\ntemp_jcc(x, y) = 1 - sum(min(x, y)) / sum(max(x, y))\r\ndistanceFormulas[\"Jaccard\"] = temp_jcc\r\n\r\n# Setting BrayCurtis\r\ntemp_bc(x, y) = sum(abs.(x - y)) / sum(abs.(x + y))\r\ndistanceFormulas[\"BrayCurtis\"] = temp_bc\r\n\r\n# Setting SpanNormDist\r\ntemp_snd(x, y) = maximum(x - y) - minimum(x - y)\r\ndistanceFormulas[\"SpanNormDist\"] = temp_snd\r\n\r\n\"\"\"\r\n    GetDistance(distanceType::DistanceType,\r\n    v1::AbstractArray{<: Number}, v2::AbstractArray{<: Number})\r\n\r\nThis function compute distance between two numeric vectors. You can use\r\ndiferents distance calculations selecting with \"DistanceType\".\r\n\r\n# Examples:\r\n\r\n    GetDistance(Euclidean::DistanceType, [2,2], [2,4])\r\n    GetDistance(Cityblock::DistanceType, [2,2], [2,4])\r\n    GetDistance(TotalVariation::DistanceType, [2,2], [2,4])\r\n\"\"\"\r\nfunction GetDistance(distanceType::DistanceType, v1::AbstractArray{<: Number}, v2::AbstractArray{<: Number})\r\n    if length(v1) != length(v2)\r\n        throw(DimensionMismatch(\"The dimensions of the vectors are different. Therefore, impossible to calculate!\\n\r\n        Vector1: $(length(v1)) // Vector2: $(length(v2)).\"))\r\n    end\r\n\r\n    return distanceFormulas[string(distanceType)](v1, v2)\r\nend\r\n\r\n# Formulas from: https://github.com/JuliaStats/Distances.jl\r\n", "meta": {"hexsha": "14b3326da055d34d189b04860e216d751a0c3968", "size": 2450, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DistanceTypes.jl", "max_stars_repo_name": "yaansz/Distances.jl", "max_stars_repo_head_hexsha": "7edf89b5583b8f1ba445fd48833b2cb1b44b8db9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DistanceTypes.jl", "max_issues_repo_name": "yaansz/Distances.jl", "max_issues_repo_head_hexsha": "7edf89b5583b8f1ba445fd48833b2cb1b44b8db9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DistanceTypes.jl", "max_forks_repo_name": "yaansz/Distances.jl", "max_forks_repo_head_hexsha": "7edf89b5583b8f1ba445fd48833b2cb1b44b8db9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9230769231, "max_line_length": 116, "alphanum_fraction": 0.6763265306, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.870597268408361, "lm_q2_score": 0.8633916205190225, "lm_q1q2_score": 0.7516663863905293}}
{"text": "function rbc()\n\t∞ = Inf\n\t@variables α, β, ρ, δ, σ\n\t@variables t::Integer, k(..), z(..), c(..), q(..), i(..)\n\t@variables Ω_1\n\tx = [k, z]\n\ty = [c, q, i]\n\tp = [α, β, ρ, δ, σ, Ω_1]\n\n\tH = [1 / c(t) - (β / c(t + 1)) * (α * exp(z(t + 1)) * k(t + 1)^(α - 1) + (1 - δ)),\n\tc(t) + k(t + 1) - (1 - δ) * k(t) - q(t),\n\tq(t) - exp(z(t)) * k(t)^α,\n\tz(t + 1) - ρ * z(t),\n\ti(t) - (k(t + 1) - (1 - δ) * k(t))]\n\n\tsteady_states = [k(∞) ~ (((1 / β) - 1 + δ) / α)^(1 / (α - 1)), z(∞) ~ 0,\n\t\t\t\tc(∞) ~ (((1 / β) - 1 + δ) / α)^(α / (α - 1)) -\n\t\t\t\t\t\tδ * (((1 / β) - 1 + δ) / α)^(1 / (α - 1)),\n\t\t\t\tq(∞) ~ (((1 / β) - 1 + δ) / α)^(α / (α - 1)),\n\t\t\t\ti(∞) ~ δ * (((1 / β) - 1 + δ) / α)^(1 / (α - 1))]\n\n\tsteady_states_iv = [k(∞) ~ (((1 / β) - 1 + δ) / α)^(1 / (α - 1)), z(∞) ~ 0,\n\t\t\t\tc(∞) ~ (((1 / β) - 1 + δ) / α)^(α / (α - 1)) -\n\t\t\t\t\t\tδ * (((1 / β) - 1 + δ) / α)^(1 / (α - 1)),\n\t\t\t\tq(∞) ~ (((1 / β) - 1 + δ) / α)^(α / (α - 1)),\n\t\t\t\ti(∞) ~ δ * (((1 / β) - 1 + δ) / α)^(1 / (α - 1))]\n\n\tn_ϵ = 1\n\tn_x = length(x)\n\tn_y = length(y)\n\tn_p = length(p)\n\tΓ = reshape([σ], n_ϵ, n_ϵ)\n\tη = reshape([0; -1], n_x, n_ϵ) # η is n_x * n_ϵ matrix\n\n\tn_z = 2 # number of observables\n\tQ = zeros(n_z, n_x + n_y) # the order is [y, x]\n\tQ[1, 1] = 1.0 # c\n\tQ[2, 3] = 1.0 # i\n\n\tΩ = [Ω_1, Ω_1]\n\t\n\treturn H, (; t, x, y, p, steady_states, steady_states_iv, Γ, η, Ω, Q), \"rbc\"\nend\n    ", "meta": {"hexsha": "b9e1ee3b3a8d7d941603d40943b7d6ce060bc96e", "size": 1323, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "deps/rbc.jl", "max_stars_repo_name": "HighDimensionalEconLab/HMCExamples", "max_stars_repo_head_hexsha": "ad9d8abd093285dbb6e82319512771fda83b16c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-07T07:22:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T18:21:01.000Z", "max_issues_repo_path": "deps/rbc.jl", "max_issues_repo_name": "HighDimensionalEconLab/HMCExamples", "max_issues_repo_head_hexsha": "ad9d8abd093285dbb6e82319512771fda83b16c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2021-08-01T00:11:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T23:08:33.000Z", "max_forks_repo_path": "deps/rbc.jl", "max_forks_repo_name": "HighDimensionalEconLab/HMCExamples", "max_forks_repo_head_hexsha": "ad9d8abd093285dbb6e82319512771fda83b16c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-29T20:14:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-29T20:14:34.000Z", "avg_line_length": 30.0681818182, "max_line_length": 83, "alphanum_fraction": 0.3476946334, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7516159031480967}}
{"text": "module APCA\n# Write your package code here.\nusing DataFrames\nusing Wavelets\nusing StatsBase\nusing ShiftedArrays\n\nfunction runAPCA(oC::Vector, M::Int)\n     #K. Chakrabarti et al.\n     #Table V. An Algorithm to Produce the APCA\n     #Algorithm Compute APCA(C,M )2\n     #begin\n     #1. if length(C) is not a power of two, pad it with zeros to make it so.\n     #2. Perform the Haar Discrete Wavelet Transform on C.\n     #3. Sort coefficients in order of decreasing normalized magnitude, truncate after M.\n     #4. Reconstruct approximation (APCA representation) of C from retained coeffs.\n     #5. If C was padded with zeros, truncate it to the original length.\n     #6. Replace approximate segment mean values with exact mean values.\n     #7. while the number of segments is greater than M\n     #8. Merge the pair of segments that can be merged with least rise in error\n     #9. endwhile\n     #end\n    # test values\n    #M  = 3\n    #oC = [7.,5.,5.,3.,3.,3.,4.,6.] # example in paper\n    #oC = vcat(rand(40).+3,rand(40).+2,rand(40).-1)\n\n    # 1. If length of oC is not a power of two, pad it with zeros\n    newexp = ceil(log(size(oC)[1])/ log(2) )\n    padsize = Int32(2^newexp - size(oC)[1])\n    oCp = vcat(oC,fill(0.,padsize))\n    fvlength = log2(size(oCp)[1]) # length power\n\n    # 2. Perform the Haar Discrete Wavelet Transform on C.\n    Haar = dwt(oCp,wavelet(WT.haar))\n\n    #  Transform into weighting and structure in paper\n    transHaar = []\n    for i in [1:1:Int32(fvlength);]\n        j = i-1\n        addvec = -Haar[2^j+1:2^i] ./ sqrt(2^(fvlength - i + 1)) # get diff coeffs\n        addvec2 = addvec ./ 2^((i-1)/2) # normalize\n        append!(transHaar,addvec2)\n    end\n    #add final mean to normalized and non-normalized\n    transHaar=append!(first(Haar,1)/sqrt(2^fvlength),transHaar)\n\n    #3. Sort coefficients in order of decreasing normalized magnitude, truncate after M\n    # go to float32 because of rounding\n    if size(transHaar)[1] > M\n        inds = sort(DataFrame(t=abs.(Float32.(transHaar)), i=1:length(transHaar)),:t,rev=true)[!,:i][1:M,:]\n    else\n        inds = sort(DataFrame(t=abs.(Float32.(transHaar)), i=1:length(transHaar)),:t,rev=true)[!,:i]\n    end\n    # get non-normalized coefs\n    #4. Reconstruct approximation (APCA representation) of C from retained coeffs.\n    Haar[Not(inds)] .= 0\n    newrep =  idwt(Haar,wavelet(WT.haar))\n\n    #5. If C was padded with zeros, truncate it to the original length.\n    newrep = newrep[1:size(oC)[1]]\n\n    #6. Replace approximate segment mean values with exact mean values.\n    repeatlengths = vcat(1,rle(newrep)[2]) # get repeat lengths\n\n    exactrep=[]\n    for k in 2:size(repeatlengths)[1]\n        s =sum(repeatlengths[1:k-1])\n        e =repeatlengths[k] + s - 1\n        um =mean(oCp[s:e])\n\n        append!(exactrep,fill(um,repeatlengths[k]))\n    end\n\n    #7. while the number of segments is greater than M\n    while size(rle(exactrep)[2])[1] > M\n        z=vcat(rle(exactrep)[1] .- lag(rle(exactrep)[1]))\n        replace!(z, missing =>-999.)\n        z=abs.(convert(Vector{Float64}, z))\n        l=findfirst(minimum(z) .== z)\n\n        newreplengths = vcat(1,rle(exactrep)[2])\n        exactrep\n        s =sum(newreplengths[1:l-1])\n        e =newreplengths[l]+newreplengths[l+1] + s - 1\n        um =mean(exactrep[s:e])\n        exactrep[s:e] .= um\n\n    end\n\n    return exactrep\n\n  end\nexport runAPCA\n\nend\n", "meta": {"hexsha": "aa0842f7aec3463fe6b32f9247b89c736a8dddc2", "size": 3367, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/APCA.jl", "max_stars_repo_name": "LukeChristopherEvans/APCA.jl", "max_stars_repo_head_hexsha": "7fc0563f4c41882acf433a3ca407d52f72bb7697", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/APCA.jl", "max_issues_repo_name": "LukeChristopherEvans/APCA.jl", "max_issues_repo_head_hexsha": "7fc0563f4c41882acf433a3ca407d52f72bb7697", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/APCA.jl", "max_forks_repo_name": "LukeChristopherEvans/APCA.jl", "max_forks_repo_head_hexsha": "7fc0563f4c41882acf433a3ca407d52f72bb7697", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7113402062, "max_line_length": 107, "alphanum_fraction": 0.6346896347, "num_tokens": 1073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7516159008877986}}
{"text": "\"\"\"\n    IdentityMap\n\nAn identity map,\n\n```math\n    x ↦ x.\n```\n\n### Fields\n\n- `dim` -- dimension\n\"\"\"\nstruct IdentityMap <: AbstractMap\n    dim::Int\nend\nstatedim(m::IdentityMap) = m.dim\noutputdim(m::IdentityMap) = m.dim\ninputdim(::IdentityMap) = 0\nislinear(::IdentityMap) = true\nisaffine(::IdentityMap) = true\napply(m::IdentityMap, x) = x\n\n\"\"\"\n    ConstrainedIdentityMap\n\nAn identity map with state constraints of the form:\n\n```math\n    x ↦ x, x(t) ∈ \\\\mathcal{X}.\n```\n\n### Fields\n\n- `dim` -- dimension\n- `X`   -- state constraints\n\"\"\"\nstruct ConstrainedIdentityMap{ST} <: AbstractMap\n    dim::Int\n    X::ST\nend\nstatedim(m::ConstrainedIdentityMap) = m.dim\nstateset(m::ConstrainedIdentityMap) = m.X\noutputdim(m::ConstrainedIdentityMap) = m.dim\ninputdim(::ConstrainedIdentityMap) = 0\nislinear(::ConstrainedIdentityMap) = true\nisaffine(::ConstrainedIdentityMap) = true\napply(::ConstrainedIdentityMap, x) = x\n\n\"\"\"\n    LinearMap\n\nA linear map,\n\n```math\n    x ↦ Ax\n```\n\n### Fields\n\n- `A` -- matrix\n\"\"\"\nstruct LinearMap{T, MT<:AbstractMatrix{T}} <: AbstractMap\n    A::MT\nend\nstatedim(m::LinearMap) = size(m.A, 2)\noutputdim(m::LinearMap) = size(m.A, 1)\ninputdim(::LinearMap) = 0\nislinear(::LinearMap) = true\nisaffine(::LinearMap) = true\napply(m::LinearMap, x) = m.A * x\n\n\"\"\"\n    ConstrainedLinearMap\n\nA linear map with state constraints of the form:\n\n```math\n    x ↦ Ax, x(t) ∈ \\\\mathcal{X}.\n```\n\n### Fields\n\n- `A` -- matrix\n- `X` -- state constraints\n\"\"\"\nstruct ConstrainedLinearMap{T, MT<:AbstractMatrix{T}, ST} <: AbstractMap\n    A::MT\n    X::ST\nend\nstatedim(m::ConstrainedLinearMap) = size(m.A, 2)\nstateset(m::ConstrainedLinearMap) = m.X\noutputdim(m::ConstrainedLinearMap) = size(m.A, 1)\ninputdim(::ConstrainedLinearMap) = 0\nislinear(::ConstrainedLinearMap) = true\nisaffine(::ConstrainedLinearMap) = true\napply(m::ConstrainedLinearMap, x) = m.A * x\n\n\"\"\"\n    AffineMap\n\nAn affine map,\n\n```math\n    x ↦ Ax + b.\n```\n\n### Fields\n\n- `A` -- matrix\n- `b` -- vector\n\"\"\"\nstruct AffineMap{T, MT<:AbstractMatrix{T}, VT<:AbstractVector{T}} <: AbstractMap\n    A::MT\n    b::VT\n    function AffineMap(A::MT, b::VT) where {T, MT<:AbstractMatrix{T}, VT<:AbstractVector{T}}\n        @assert size(A, 1) == length(b)\n        return new{T, MT, VT}(A, b)\n    end\nend\nstatedim(m::AffineMap) = size(m.A, 2)\noutputdim(m::AffineMap) = length(m.b)\ninputdim(::AffineMap) = 0\nislinear(::AffineMap) = false\nisaffine(::AffineMap) = true\napply(m::AffineMap, x) = m.A * x + m.b\n\n\"\"\"\n    ConstrainedAffineMap\n\nAn affine map with state constraints of the form:\n\n```math\n    x ↦ Ax + b, x(t) ∈ \\\\mathcal{X}.\n```\n\n### Fields\n\n- `A` -- matrix\n- `b` -- vector\n- `X` -- state constraints\n\"\"\"\nstruct ConstrainedAffineMap{T, MT<:AbstractMatrix{T}, VT<:AbstractVector{T}, ST} <: AbstractMap\n    A::MT\n    b::VT\n    X::ST\n    function ConstrainedAffineMap(A::MT, b::VT, X::ST) where {T, MT<:AbstractMatrix{T}, VT<:AbstractVector{T}, ST}\n        @assert size(A, 1) == length(b)\n        return new{T, MT, VT, ST}(A, b, X)\n    end\nend\nstatedim(m::ConstrainedAffineMap) = size(m.A, 2)\nstateset(m::ConstrainedAffineMap) = m.X\noutputdim(m::ConstrainedAffineMap) = length(m.b)\ninputdim(::ConstrainedAffineMap) = 0\nislinear(::ConstrainedAffineMap) = false\nisaffine(::ConstrainedAffineMap) = true\napply(m::ConstrainedAffineMap, x) = m.A * x + m.b\n\n\"\"\"\n    LinearControlMap\n\nA linear control map,\n\n```math\n    (x, u) ↦ Ax + Bu.\n```\n\n### Fields\n\n- `A` -- matrix\n- `B` -- matrix\n\"\"\"\nstruct LinearControlMap{T, MTA<:AbstractMatrix{T}, MTB<:AbstractMatrix{T}} <: AbstractMap\n    A::MTA\n    B::MTB\n    function LinearControlMap(A::MTA, B::MTB) where {T, MTA<:AbstractMatrix{T}, MTB<:AbstractMatrix{T}}\n        @assert size(A, 1) == size(B, 1)\n        return new{T, MTA, MTB}(A, B)\n    end\nend\nstatedim(m::LinearControlMap) = size(m.A, 2)\ninputdim(m::LinearControlMap) = size(m.B, 2)\noutputdim(m::LinearControlMap) = size(m.A, 1)\nislinear(::LinearControlMap) = true\nisaffine(::LinearControlMap) = true\napply(m::LinearControlMap, x, u) = m.A * x + m.B * u\n\n\"\"\"\n    ConstrainedLinearControlMap\n\nA linear control map with state and input constraints,\n\n```math\n    (x, u) ↦ Ax + Bu, x ∈ \\\\mathcal{X}, u ∈ \\\\mathcal{U}.\n```\n\n### Fields\n\n- `A` -- matrix\n- `B` -- matrix\n- `X` -- state constraints\n- `U` -- input constraints\n\"\"\"\nstruct ConstrainedLinearControlMap{T, MTA <: AbstractMatrix{T}, MTB <: AbstractMatrix{T}, ST, UT} <: AbstractMap\n    A::MTA\n    B::MTB\n    X::ST\n    U::UT\n    function ConstrainedLinearControlMap(A::MTA, B::MTB, X::ST, U::UT) where {T, MTA<:AbstractMatrix{T}, MTB<:AbstractMatrix{T}, ST, UT}\n        @assert size(A, 1) == size(B, 1)\n        return new{T, MTA, MTB, ST, UT}(A, B, X, U)\n    end\nend\nstatedim(m::ConstrainedLinearControlMap) = size(m.A, 2)\nstateset(m::ConstrainedLinearControlMap) = m.X\noutputdim(m::ConstrainedLinearControlMap) = size(m.A, 1)\ninputdim(m::ConstrainedLinearControlMap) = size(m.B, 2)\ninputset(m::ConstrainedLinearControlMap) = m.U\nislinear(::ConstrainedLinearControlMap) = true\nisaffine(::ConstrainedLinearControlMap) = true\napply(m::ConstrainedLinearControlMap, x, u) = m.A * x + m.B * u\n\n\"\"\"\n    AffineControlMap\n\nAn affine control map,\n\n```math\n    (x, u) ↦ Ax + Bu + c.\n```\n\n### Fields\n\n- `A` -- matrix\n- `B` -- matrix\n- `c` -- vector\n\"\"\"\nstruct AffineControlMap{T, MTA <: AbstractMatrix{T}, MTB <: AbstractMatrix{T}, VT<:AbstractVector{T}} <: AbstractMap\n    A::MTA\n    B::MTB\n    c::VT\n    function AffineControlMap(A::MTA, B::MTB, c::VT) where {T, MTA<:AbstractMatrix{T}, MTB<:AbstractMatrix{T}, VT<:AbstractVector{T}}\n        @assert size(A, 1) == size(B, 1) == length(c)\n        return new{T, MTA, MTB, VT}(A, B, c)\n    end\nend\nstatedim(m::AffineControlMap) = size(m.A, 2)\noutputdim(m::AffineControlMap) = size(m.A, 1)\ninputdim(m::AffineControlMap) = size(m.B, 1)\nislinear(::AffineControlMap) = false\nisaffine(::AffineControlMap) = true\napply(m::AffineControlMap, x, u) = m.A * x + m.B * u + m.c\n\n\"\"\"\n    ConstrainedAffineControlMap\n\nAn affine control map with state and input constraints,\n\n```math\n    (x, u) ↦ Ax + Bu + c, x ∈ \\\\mathcal{X}, u ∈ \\\\mathcal{U}.\n```\n\n### Fields\n\n- `A` -- matrix\n- `B` -- matrix\n- `c` -- vector\n- `X` -- state constraints\n- `U` -- input constraints\n\"\"\"\nstruct ConstrainedAffineControlMap{T, MTA<:AbstractMatrix{T}, MTB<:AbstractMatrix{T}, VT<:AbstractVector{T}, ST, UT} <: AbstractMap\n    A::MTA\n    B::MTB\n    c::VT\n    X::ST\n    U::UT\n    function ConstrainedAffineControlMap(A::MTA, B::MTB, c::VT, X::ST, U::UT) where {T, MTA<:AbstractMatrix{T}, MTB<:AbstractMatrix{T}, VT<:AbstractVector{T}, ST, UT}\n        @assert size(A, 1) == size(B, 1) == length(c)\n        return new{T, MTA, MTB, VT, ST, UT}(A, B, c, X, U)\n    end\nend\nstatedim(m::ConstrainedAffineControlMap) = size(m.A, 2)\nstateset(m::ConstrainedAffineControlMap) = m.X\ninputdim(m::ConstrainedAffineControlMap) = size(m.B, 2)\ninputset(m::ConstrainedAffineControlMap) = m.U\noutputdim(m::ConstrainedAffineControlMap) = size(m.A, 1)\nislinear(::ConstrainedAffineControlMap) = false\nisaffine(::ConstrainedAffineControlMap) = true\napply(m::ConstrainedAffineControlMap, x, u) = m.A * x + m.B * u + m.c\n\n\"\"\"\n    ResetMap\n\nA reset map,\n\n```math\n    x ↦ R(x),\n```\nsuch that a subset of the variables is given a specified value, and the rest\nare unchanged.\n\n### Fields\n\n- `dim`  -- dimension\n- `dict` -- dictionary whose keys are the indices of the variables that are reset,\n            and whose values are the new values\n\"\"\"\nstruct ResetMap{N} <: AbstractMap\n    dim::Int\n    dict::Dict{Int, N}\nend\nstatedim(m::ResetMap) = m.dim\ninputdim(::ResetMap) = 0\noutputdim(m::ResetMap) = m.dim\nislinear(::ResetMap) = false\nisaffine(::ResetMap) = true\n\n# convenience constructor for a list of pairs instead of a dictionary\nResetMap(dim::Int, args::Pair{Int, <:N}...) where {N} = ResetMap(dim, Dict{Int, N}(args))\n\n\"\"\"\n    ConstrainedResetMap\n\nA reset map with state constraints of the form:\n\n```math\n    x ↦ R(x), x ∈ \\\\mathcal{X},\n```\nsuch that the specified variables are assigned a given value, and the remaining\nvariables are unchanged.\n\n### Fields\n\n- `dim`  -- dimension\n- `X`    -- state constraints\n- `dict` -- dictionary whose keys are the indices of the variables that are\n            reset, and whose values are the new values\n\"\"\"\nstruct ConstrainedResetMap{N, ST} <: AbstractMap\n    dim::Int\n    X::ST\n    dict::Dict{Int, N}\nend\nstatedim(m::ConstrainedResetMap) = m.dim\nstateset(m::ConstrainedResetMap) = m.X\ninputdim(::ConstrainedResetMap) = 0\noutputdim(m::ConstrainedResetMap) = m.dim\nislinear(::ConstrainedResetMap) = false\nisaffine(::ConstrainedResetMap) = true\n\n# convenience constructor for a list of pairs instead of a dictionary\nConstrainedResetMap(dim::Int, X::ST, args::Pair{Int, <:N}...) where {N, ST} =\n    ConstrainedResetMap(dim, X, Dict{Int, N}(args))\n\nfunction apply(m::Union{ResetMap, ConstrainedResetMap}, x)\n    y = copy(x)\n    for (index, value) in pairs(m.dict)\n        y[index] = value\n    end\n    return y\nend\n", "meta": {"hexsha": "0b8c8ccad8cc664d98e204b516e430539f2065ad", "size": 8911, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/maps.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/MathematicalSystems.jl-d14a8603-c872-5ed3-9ece-53e0e82e39da", "max_stars_repo_head_hexsha": "af916edc33ab9d27f064a8be5c96a5cb954558b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/maps.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/MathematicalSystems.jl-d14a8603-c872-5ed3-9ece-53e0e82e39da", "max_issues_repo_head_hexsha": "af916edc33ab9d27f064a8be5c96a5cb954558b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/maps.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/MathematicalSystems.jl-d14a8603-c872-5ed3-9ece-53e0e82e39da", "max_forks_repo_head_hexsha": "af916edc33ab9d27f064a8be5c96a5cb954558b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5482093664, "max_line_length": 166, "alphanum_fraction": 0.65435978, "num_tokens": 2958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7516158937533209}}
{"text": "using Munkres\nimport Base: eye, rand, *, inv\n\n# Type definitions\n\nimmutable SymmetricGroup{N} <: Group\n    σ::Vector{Int}\nend\n\nSn{N} = SymmetricGroup{N}\nSymmetricGroup(σ::Vector{Int}) = SymmetricGroup{length(σ)}(σ)\n\n# Identity element\n\neye{N}(::Type{Sn{N}}) = Sn{N}(1:N)\n\n# Random group element\n\nfunction rand{N}(::Type{Sn{N}})\n    σ = shuffle(1:N)\n    Sn(σ)\nend\n\n# Defining representation\n\n@inbounds function defrep!{N, T}(M::Matrix{T}, g::Sn{N})\n    σ = g.σ\n    n = size(M, 1)\n    for i in 1:n, j in 1:n\n        if i == σ[j]\n            M[i, j] = one(T)\n        else\n            M[i, j] = zero(T)\n        end\n    end\n\n    return M\nend\n\ndefrep{N}(g::Sn{N}) = defrep!(Matrix{Float64}(N, N), g)\n\nfunction nearest{N, T}(::Type{Sn{N}}, M_defrep::Matrix{T})\n    Sn{N}(munkres(-M_defrep'))\nend\n\n# Multiplication\nfunction *{N}(g₁::Sn{N}, g₂::Sn{N})\n    Sn{N}(g₁.σ[g₂.σ])\nend\n\n# Inversion\nfunction inv{N}(g::Sn{N})\n    Sn{N}(indexin(1:N, g.σ))\nend\n", "meta": {"hexsha": "af7ef517836a531f987cfd95c8bffb44c4b62251", "size": 941, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/symmetric_group/Sn.jl", "max_stars_repo_name": "NickMcNutt/Groups.jl", "max_stars_repo_head_hexsha": "557756d58c2b21ab6ea1c685615b33e9fdc40865", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/symmetric_group/Sn.jl", "max_issues_repo_name": "NickMcNutt/Groups.jl", "max_issues_repo_head_hexsha": "557756d58c2b21ab6ea1c685615b33e9fdc40865", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/symmetric_group/Sn.jl", "max_forks_repo_name": "NickMcNutt/Groups.jl", "max_forks_repo_head_hexsha": "557756d58c2b21ab6ea1c685615b33e9fdc40865", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1090909091, "max_line_length": 61, "alphanum_fraction": 0.572794899, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630935, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.7516158927999638}}
{"text": "# Practice implementation of code blocks 4.1 through 4.6 in McElreath's Statistical\n# Rethinking, 2nd ed.\n\nusing Random\nusing Distributions: Uniform, rand, pdf\nusing Plots: histogram\n\n\n# Set up\nRandom.seed!(17)\n\n\n# Code block 4.1\ndistro = Uniform(-1, 1)\nsteps = rand(distro, 1000, 16)\npositions = sum(steps, dims=2)\ndisplay(histogram(positions, bins=:40, xlabel=\"Position\", ylabel=\"Frequency\"))\n\n\n# Code blocks 4.2 and 4.3: Gaussian through multiplication\ndistro = Uniform(0, 0.1)\neffects = rand(distro, 1000, 12) .+ 1\ngrowth = prod(effects, dims=2)\ndisplay(histogram(growth, bins=:40, xlabel=\"Growth\", ylabel=\"Frequency\"))\n\n\n# Code block 4.4\ndistro = Uniform(0, 0.5)\neffects = rand(distro, 1000, 12) .+ 1\nbig_growth = prod(effects, dims=2)\ndisplay(histogram(big_growth, bins=:40, xlabel=\"Growth\", ylabel=\"Frequency\"))\n\ndistro = Uniform(0, 0.01)\neffects = rand(distro, 1000, 12) .+ 1\nsmall_growth = prod(effects, dims=2)\ndisplay(histogram(small_growth, bins=:40, xlabel=\"Growth\", ylabel=\"Frequency\"))\n\n\n# Code block 4.5\nlog_big_growth = log.(big_growth)\ndisplay(histogram(log_big_growth, bins=:40, xlabel=\"Log(growth)\", ylabel=\"Frequency\"))\n\n\n# Code block 4.6\nw = 6\nn = 9\nparam_grid = 0.0:1/100:1.0\nposterior = [pdf(Binomial(n, p), w) * pdf(Uniform(0, 1), p) for p in param_grid]\nposterior = posterior / sum(posterior)", "meta": {"hexsha": "05eadc7a66742e78557848c30759fe2aa6d48a34", "size": 1318, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4-1_understanding_gaussians.jl", "max_stars_repo_name": "CrosstabKite/stat_rethinking_julia", "max_stars_repo_head_hexsha": "5dd23fc7d2a438db59e4b45ae08d93503c1a4ef3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4-1_understanding_gaussians.jl", "max_issues_repo_name": "CrosstabKite/stat_rethinking_julia", "max_issues_repo_head_hexsha": "5dd23fc7d2a438db59e4b45ae08d93503c1a4ef3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4-1_understanding_gaussians.jl", "max_forks_repo_name": "CrosstabKite/stat_rethinking_julia", "max_forks_repo_head_hexsha": "5dd23fc7d2a438db59e4b45ae08d93503c1a4ef3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8979591837, "max_line_length": 86, "alphanum_fraction": 0.7124430956, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692236, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7516084030455957}}
{"text": "using ISA #References: Sandoval, Steven, and Phillip L. De Leon. \"The Instantaneous Spectrum: A General Framework for Time-Frequency Analysis.\" IEEE Transactions on Signal Processing 66.21 (2018): 5679-5693.\r\n\r\n\r\n#----------------------------\r\n# BASIC EXAMPLES\r\n#----------------------------\r\n\r\n#DEFINE 0th CANONICAL TRIPLET\r\na₀(t) = exp(-t^2)\r\nω₀(t) = 100\r\nφ₀ = 0\r\n𝐶₀ = Tuple([a₀,ω₀,φ₀])\r\n\r\n#DEFINE 0th COMPONENT\r\nψ₀ = AMFMcomp(𝐶₀)\r\n\r\n#DEFINE 1st CANONICAL TRIPLET\r\na₁(t) = 1\r\nω₁(t) = 10*t\r\nφ₁ = π\r\n𝐶₁ = Tuple([a₁,ω₁,φ₁])\r\n\r\n#DEFINE 2nd CANONICAL TRIPLET\r\na₂(t) = 0.8*cos(2t)\r\nω₂(t) = 10 + 7.5*sin(t)\r\nφ₂ = π\r\n𝐶₂ = Tuple([a₂,ω₂,φ₂])\r\n\r\n#DEFINE THE COMPONENT SET\r\n𝑆 = [𝐶₀,𝐶₁,𝐶₂]\r\n\r\n#DEFINE THE AMFM MODEL\r\nz = AMFMmodel(𝑆)\r\n\r\n#DEFINE A TIME INDEX\r\nt = Array(0.0:0.005:2.0)\r\n\r\n#EVALUATE THE 0th COMPONENT AT THE POINTS IN THE TIME INDEX\r\nψ₀(t)\r\n\r\n#EVALUATE THE AMFM MODEL AT THE POINTS IN THE TIME INDEX\r\nz(t)\r\n\r\n#----------------------------\r\n# FOURIER SERIES\r\n#----------------------------\r\n\r\nT = 1\r\naₖ(k) = 1\r\nkInds = Vector(-10:10)\r\n\r\nz₀ = fourierSeries(T,aₖ,kInds)\r\n\r\n\r\n#----------------------------\r\n# PLOTS\r\n#----------------------------\r\n\r\np1 = isaPlot3d(𝐶₁, t)\r\n\r\np2 = isaPlot3d(ψ₀, t)\r\n\r\np3 = isaPlot3d(z₀, t, FreqUnits=\"Hz\")\r\n\r\np4 = isaPlot3d(𝑆, t, FreqUnits=\"Hz\")\r\n\r\nusing Plots\r\nPlots.plot(p1,p2,p3,p4)\r\n", "meta": {"hexsha": "8d7ea31951af0cc316b2b2187b9c5547a62f7d50", "size": 1316, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/examples/basicExamples.jl", "max_stars_repo_name": "kricheso/ISA", "max_stars_repo_head_hexsha": "d6f8c60b319b7a3ea436f831a8d60995744d90b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/examples/basicExamples.jl", "max_issues_repo_name": "kricheso/ISA", "max_issues_repo_head_hexsha": "d6f8c60b319b7a3ea436f831a8d60995744d90b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/examples/basicExamples.jl", "max_forks_repo_name": "kricheso/ISA", "max_forks_repo_head_hexsha": "d6f8c60b319b7a3ea436f831a8d60995744d90b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0724637681, "max_line_length": 208, "alphanum_fraction": 0.5516717325, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7516083965374415}}
{"text": "using DataStructures\r\nusing Printf\r\n\r\n\r\nm = [[0, Inf, Inf] [7, 0, 4] [2, Inf, 0]]\r\nm2 = [[0, 7, 2] [Inf, 0, Inf] [Inf, 4, 0]]\r\n\r\ng(x,y) = x+y\r\nf(x,y) = min(x,y)\r\n\r\nfunction floyd_warshall(adjacency_matrix, nodes, f, g)\r\n    for k = 1:nodes\r\n        for i = 1:nodes\r\n            for j = 1:nodes\r\n                adjacency_matrix[i,j] = f(adjacency_matrix[i,j], g(adjacency_matrix[i,k], adjacency_matrix[k,j]))\r\n            end\r\n        end\r\n    end\r\n    return adjacency_matrix\r\nend\r\n\r\nfunction transitive_closure(adjacency_matrix, nodes)\r\n    M = copy(adjacency_matrix)\r\n    T = zeros(Int64,nodes,nodes)\r\n    for i = 1:nodes\r\n        for j = 1:nodes\r\n            if (i == j || ((M[i,j] > 0) & (M[i,j] != Inf)))\r\n                println(M[i,j])\r\n                T[i,j] = 1\r\n            end\r\n        end\r\n    end\r\n    println(T)\r\n    for k = 1:nodes\r\n        for i = 1:nodes\r\n            for j = 1:nodes\r\n                T[i,j] = (convert(Bool,T[i,j])|| (convert(Bool,T[i,k]) && convert(Bool,T[k,j])))\r\n            end\r\n        end\r\n    end\r\n    return T\r\nend\r\n\r\nballots = [\"ABC\", \"CBA\", \"BAC\"]\r\nvoters = 3\r\ncandidates = 3\r\n\r\nfunction create_preference_matrix(ballots, voters, candidates)\r\n    P = zeros(candidates,candidates)\r\n    for j = 1:candidates # iterating over each candidate\r\n        c = string('A'+j-1) # character of current candidate\r\n        for vote in ballots\r\n            current = findfirst(c, vote)[1] # position of current candidate in current ballot\r\n            println(vote)\r\n            for k = 1:candidates # the position of each candidate in respect to current (j)\r\n                other =  findfirst(string(vote[k]), vote)[1] # position of other candidates in current ballot\r\n                # @printf \"Comparing current %s at position %d with %c at position %d\\n\" c current vote[k] other\r\n                if (current < other) # if index of current character is smaller than other in the ballot\r\n                    u = Int(vote[k]-'A'+1) # the index of other candidate in respect to current\r\n                    P[j,u] = P[j,u] + 1\r\n                end\r\n            end\r\n            #println(\"\")\r\n        end\r\n    end\r\n    return P\r\nend\r\n\r\nfunction find_strongest_paths(preference_matrix, candidates)\r\n    \r\nend\r\n", "meta": {"hexsha": "3ec22eb83a9811f76e644883758fd09311dd8971", "size": 2239, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "assignment-11/assignment-11.jl", "max_stars_repo_name": "evenlwanvik-student/algdat", "max_stars_repo_head_hexsha": "e4c73524e61c713f320811c7b6f427ebf7f040c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment-11/assignment-11.jl", "max_issues_repo_name": "evenlwanvik-student/algdat", "max_issues_repo_head_hexsha": "e4c73524e61c713f320811c7b6f427ebf7f040c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment-11/assignment-11.jl", "max_forks_repo_name": "evenlwanvik-student/algdat", "max_forks_repo_head_hexsha": "e4c73524e61c713f320811c7b6f427ebf7f040c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0972222222, "max_line_length": 114, "alphanum_fraction": 0.5377400625, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7516083965374414}}
{"text": "using DifferentialEquations\nusing Distributions\nusing Distances\nusing Gadfly\nusing ApproxBayes\nusing DataFrames\nusing Plots\n\nfunction getsolution(sol, times)\n    x1 = map(x -> sol(x)[1], times)\n    y1 = map(x -> sol(x)[2], times)\n  return x1, y1\nend\n\n# define Lotka Voltera ODE where a and b can be modified\nf = @ode_def LV begin\n  dx = a*x - b*x*y\n  dy = b*x*y - y\nend a b\n\nx0 = [1.0; 0.5]\ntspan = (0.0, 15.0)\np = [2.0, 0.8]\nprob = ODEProblem(f, x0, tspan, p)\nsol = solve(prob)\nPlots.plot(sol)\n\n#generate target data by sampling 15 points and then adding Gaussian noise\ntimes = 1.0:2.0:15.0\nx, y = getsolution(sol, times)\nx .+= rand(Normal(0.0, 1), length(times))\ny .+= rand(Normal(0.0, 1), length(times))\ntargetdata = [x, y]\n\n#simulations function for ABC. return distance (sum of squared distances) and solution\nfunction simLV(params, constants, targetdata)\n  a = params[1]\n  b = params[2]\n  x0 = [1.0; 0.5]\n  tspan = (0.0, 15.0)\n  times = 1.0:2.0:15.0\n  prob = ODEProblem(f, x0, tspan, [a, b])\n  sol = solve(prob)\n  x1, y1 = getsolution(sol, times)\n  d = sum((x1 .- targetdata[1]).^2 + (y1 .- targetdata[2]).^2)\n  return d, sol\nend\n\n#define ABC setup type\nsetup = ABCSMC(simLV,\n  2,\n  0.1,\n  Prior([Uniform(0.0, 5.0), Uniform(0.0, 5.0)]),\n  maxiterations = 10^6,\n  convergence = 0.001,\n  nparticles = 1000\n  )\n  #run ABC SMC algorithm\n@time ressmc = runabc(setup, targetdata, verbose = true, progress = true, parallel=true)\n\n#show results\nshow(ressmc)\n\n#plot posterior parameters\nplotparameterposterior(ressmc)\n\n#plots results using Gadfly\n#Create data frame for target data\nDFt = DataFrame(x = targetdata[1], y = targetdata[2], time = times)\nd1 = stack(DFt, [:x, :y])\n\n#get solution for\nres = mean(ressmc.parameters, weights(ressmc.weights), 1)\nx0 = [1.0; 0.5]\ntspan = (0.0, 15.0)\nprob = ODEProblem(f, x0, tspan, [res[1], res[2]])\nsol = solve(prob)\ntimes2 = 1.0:0.001:15.0\nx2, y2 = getsolution(sol, times2)\n\nDF1 = DataFrame(x = x2, y = y2, time = times2)\nd2 = stack(DF1, [:x, :y])\n\nl1 = layer(d1,x = :time, y = :value, color = :variable, Geom.point)\nl2 = layer(d2,x = :time, y = :value, color = :variable, Geom.line)\nGadfly.plot(l1, l2)\n", "meta": {"hexsha": "40862e6d1598921450ae867fac2c5ce181207eaa", "size": 2142, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/LV.jl", "max_stars_repo_name": "wilwxk/ApproxBayes.jl", "max_stars_repo_head_hexsha": "8ca364c66a9f94ccd09910a4f73232909d91c399", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 43, "max_stars_repo_stars_event_min_datetime": "2017-10-14T22:35:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T05:30:13.000Z", "max_issues_repo_path": "examples/LV.jl", "max_issues_repo_name": "wilwxk/ApproxBayes.jl", "max_issues_repo_head_hexsha": "8ca364c66a9f94ccd09910a4f73232909d91c399", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47, "max_issues_repo_issues_event_min_datetime": "2017-06-15T08:38:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-27T10:24:48.000Z", "max_forks_repo_path": "examples/LV.jl", "max_forks_repo_name": "wilwxk/ApproxBayes.jl", "max_forks_repo_head_hexsha": "8ca364c66a9f94ccd09910a4f73232909d91c399", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-07-28T09:49:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T14:39:00.000Z", "avg_line_length": 24.6206896552, "max_line_length": 88, "alphanum_fraction": 0.6563958917, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.751608391301097}}
{"text": "export CnoidalWaveSerreGreenNaghdi, CnoidalSGN\nusing Elliptic\n\n\"\"\"\n    CnoidalWaveSerreGreenNaghdi(param; P=1)\n\nCompute the Serre-Green-Naghdi cnoidal wave with prescribed `h₀<h₁<h₂`.\n`h₁` is the minimum, `h₂` is the maximum of the wave.\nAs `h₀ -> h₁`, the cnoidal wave converges towards the solitary wave.\nSee for instance [Gavrilyuk, Nkonga, Shyue and Truskinovsky](https://doi.org/10.1088/1361-6544/ab95ac).\n\n# Arguments\n- `param :: NamedTuple`: parameters of the problem containing `h₀<h₁<h₂` and dimensionless parameters `ϵ` and `μ`, and number of collocation points `N`.\n- `P :: Int`: (keyword, optional, default = 1) the number of periods of the cnoidal wave in the constructed mesh.\n\n# Return values\n`(η,u,v,mesh,param)` with\n- `η :: Vector{Float64}`: surface deformation;\n- `u :: Vector{Float64}`: layer-averaged velocity;\n- `v :: Vector{Float64}`: derivative of the trace of the velocity potential at the surface;\n- `mesh :: Mesh`: mesh collocation points;\n- `param :: NamedTuple`: useful parameters\n\"\"\"\nfunction CnoidalWaveSerreGreenNaghdi(\n                param :: NamedTuple;\n                P = 1 :: Int)\n\n        ϵ = param.ϵ\n        μ = param.μ\n\n        h₀=param.h₀\n        h₁=param.h₁\n        h₂=param.h₂\n        c = sqrt(h₀*h₁*h₂)\n        m = sqrt((h₂-h₁)/(h₂-h₀))\n        κ = sqrt(3*(h₂-h₀))/(2*c)/sqrt(μ)\n        λ = Elliptic.K(m^2)/κ\n        mesh = Mesh((L=P*λ,N=param.N))\n        formula = h₁ .-1 .+ (h₂-h₁)*(Jacobi.cn.(κ*mesh.x,m^2).^2)\n\n        a₀ = h₀\n        a₁ = h₂ - h₀\n        formula2 = a₀ .-1 .+ a₁*(Jacobi.dn.(κ*mesh.x,m^2).^2)\n        H₀= a₀+a₁*Elliptic.E(m^2)/Elliptic.K(m^2)\n        u2 = c*(1 ./ H₀ .- 1 ./(1 .+ formula2))\n        param = (h₀=h₀,h₁=h₁,h₂=h₂,a₀=a₀,a₁=a₁,H₀=H₀,c=c,λ=λ,m=m,κ=κ)\n\n\n        η = formula/ϵ\n        h = 1 .+ ϵ*η\n        u = c*η./h\n\t\tk = mesh.k\n        Dx=  1im * k\n\t\tF₀ = sqrt(μ)*Dx\n        DxF(v) = real.(ifft(F₀ .* fft(v)))\n\t\tv = u - 1/3 ./h .* (DxF(h.^3 .*DxF(u)))\n        #\n        # h2 = 1 .+ ϵ*formula2\n        # v2 = u2 - 1/3 ./h2 .* (DxF(h2.^3 .*DxF(u2)))\n\n        return (η,u,v,mesh,param)\n\nend\n\n\"\"\"\n    CnoidalSGN(param; P=1)\n\nBuild the initial data associated with `CnoidalWaveSerreGreenNaghdi(param; P=1)`, of type `InitialData`,\nto be used in initial-value problems `Problem(model, initial::InitialData, param)`.\n\"\"\"\nstruct CnoidalSGN <: InitialData\n\n\tη\n\tv\n\tlabel :: String\n\tinfo  :: String\n\n\tfunction CnoidalSGN(param; P=1)\n\t\t(η,u,v,mesh,para)=CnoidalWaveSerreGreenNaghdi(param; P)\n\t\tinit = Init(mesh,η,v)\n\t\tlabel = \"Green-Naghdi cnoidal wave\"\n\t\tinfo = \"Cnoidal travelling wave for the Serre-Green-Naghdi model.\\n\\\n\t\t├─velocity c = $(para.c)\\n├───period P = $(2(para.λ))\\n\\\n\t\t├─maximum h₂ = $(para.h₂) (from bottom)\\n└─minimum h₁ = $(para.h₁) (from bottom).\"\n\n\t\tnew( init.η,init.v,label,info  )\n\tend\nend\n", "meta": {"hexsha": "365cfc9ff9c253ef9af4b090f3ad9ba7566e47dc", "size": 2778, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/initialdata/CnoidalWaveSerreGreenNaghdi.jl", "max_stars_repo_name": "DeepWaterModels/FModels.jl", "max_stars_repo_head_hexsha": "66f58bbee576abcc47c73d64b2a66f1f80b824f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/initialdata/CnoidalWaveSerreGreenNaghdi.jl", "max_issues_repo_name": "DeepWaterModels/FModels.jl", "max_issues_repo_head_hexsha": "66f58bbee576abcc47c73d64b2a66f1f80b824f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/initialdata/CnoidalWaveSerreGreenNaghdi.jl", "max_forks_repo_name": "DeepWaterModels/FModels.jl", "max_forks_repo_head_hexsha": "66f58bbee576abcc47c73d64b2a66f1f80b824f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2134831461, "max_line_length": 152, "alphanum_fraction": 0.6011519078, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7516083869155479}}
{"text": "# Load package\nusing Pkg;\nusing Distributions, Statistics, LinearAlgebra\nusing Plots\n\n# Define population, N()\nn_pop = 2_500; # Population size\nn_iter = 5000; # Iteration of collision\n\n# Distribution of income\nμ_income = 50_000; # Mean income\nσ_income = 12_000; # Standard deviation of income\n𝐃 = Normal(μ_income, σ_income)\n\n# Decider for selecting two agents to collide\n𝐔 = Uniform(1, n_pop)\n\n# vector of initial income of individual\nval_inc_ini = deepcopy(rand(𝐃, n_pop));\n# Equal splits\nval_inc_trc = zeros(n_pop, n_iter); # Trace the changes in distribuiton\nval_inc_trc[:,1] = val_inc_ini; # the very first distributional look\n# Uniform random split\nval_inc_trc_rand = zeros(n_pop, n_iter); # Trace the changes in distribuiton\nval_inc_trc_rand[:,1] = val_inc_ini; # the very first distributional look\n\n\n# Agent collide-split economy: two agents meet at a time, their wealth is equally distributed\n\nfor iter ∈ 2:n_iter\n    # initialize the starting wealth distributio of the period\n    val_inc_trc[:, iter] = val_inc_trc[:, (iter - 1)];\n    # For each iteration, we select two agents who will collide\n    agt_1, agt_2 = sample(1:n_pop, 2; replace = false)\n    # collect their financial values\n    val_inc_agt_1, val_inc_agt_2 = val_inc_trc[agt_1, iter], val_inc_trc[agt_2, iter];\n    # divide up their wealth equally, and save\n    val_inc_distributed = mean([val_inc_agt_1, val_inc_agt_2]);\n    val_inc_trc[agt_1, iter] = val_inc_distributed;\n    val_inc_trc[agt_2, iter] = val_inc_distributed;\n\n    # Iteration 2 - uniform wealth redistribution, ranom split =========================\n    # initialize the starting wealth distributio of the period\n    val_inc_trc_rand[:, iter] = val_inc_trc_rand[:, (iter - 1)];\n    # For each iteration, we select two agents who will collide\n    agt_1, agt_2 = sample(1:n_pop, 2; replace = false)\n    # collect their financial values\n    total_wealth = val_inc_trc_rand[agt_1, iter] + val_inc_trc_rand[agt_2, iter];\n    # How to split the wealth ..........................................................\n    ρ = rand(1)[1]; #proportion to be split`\n    # Redistribute wealth\n    #   because of randomization, no need for random in order,\n    val_inc_agt_1, val_inc_agt_2 = total_wealth * ρ, total_wealth * (1 - ρ)\n    val_inc_trc_rand[agt_1, iter] = val_inc_agt_1;\n    val_inc_trc_rand[agt_2, iter] = val_inc_agt_2;\nend\n\nprintln(\"Mean - true: $(μ_income); std - true: $(σ_income)\")\nprintln(\"Mean: $(mean(val_inc_trc[:,end])); std: $(std(val_inc_trc[:,end]))\")\n@gif for i ∈ 1:10:n_iter\n    histogram(val_inc_trc[:,i], title = \"Iteration: $(i)\", xlims = (0,1e5))\nend every 5\n\nprintln(\"Mean - true: $(μ_income); std - true: $(σ_income)\")\nprintln(\"Mean: $(mean(val_inc_trc_rand[:,end])); std: $(std(val_inc_trc_rand[:,end]))\")\n@gif for i ∈ 1:10:n_iter\n    histogram(val_inc_trc_rand[:,i], title = \"Iteration: $(i)\", xlims = (0,2e5))\nend every 5\n", "meta": {"hexsha": "c17a14ffa3043f22674375e14d73cbef64b4243a", "size": 2880, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercise/simple_collision_wealth_redistribution/collision_wealth_redistribution.jl", "max_stars_repo_name": "justinjoliver/simulation-discrete", "max_stars_repo_head_hexsha": "91deb16f5a808e0e63bffe559e8840eb29434876", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercise/simple_collision_wealth_redistribution/collision_wealth_redistribution.jl", "max_issues_repo_name": "justinjoliver/simulation-discrete", "max_issues_repo_head_hexsha": "91deb16f5a808e0e63bffe559e8840eb29434876", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise/simple_collision_wealth_redistribution/collision_wealth_redistribution.jl", "max_forks_repo_name": "justinjoliver/simulation-discrete", "max_forks_repo_head_hexsha": "91deb16f5a808e0e63bffe559e8840eb29434876", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7391304348, "max_line_length": 93, "alphanum_fraction": 0.6934027778, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.751608381679203}}
{"text": "function myfunc(x)\n    x1, x2 = x[1], x[2]\n    return x1^4 - 2*x2*x1^2 + x2^2 + x1^2 - 2*x1 + 5\nend\n\nlb = [-3.0, -1.0]\nub = [2.0, 6.0];\n\nparticles = Particles(100, lb, ub)\npso(particles, myfunc, minstep=1e-3)\n# ou posso fazer a função criar um e depor retornar\nparticles2 = pso(myfunc, lb, ub, minstep=1e-3);\n\nmínimo em [1,1] com valor 4", "meta": {"hexsha": "3fe27be248e289b195e75432c3820f859811b53e", "size": 337, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/pso.jl", "max_stars_repo_name": "phelipe/Swarm.jl", "max_stars_repo_head_hexsha": "b8cb6212473449b20217ff0c324e6bd9f188acb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-04T21:30:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-04T21:30:01.000Z", "max_issues_repo_path": "test/pso.jl", "max_issues_repo_name": "phelipe/Swarm.jl", "max_issues_repo_head_hexsha": "b8cb6212473449b20217ff0c324e6bd9f188acb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/pso.jl", "max_forks_repo_name": "phelipe/Swarm.jl", "max_forks_repo_head_hexsha": "b8cb6212473449b20217ff0c324e6bd9f188acb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0714285714, "max_line_length": 52, "alphanum_fraction": 0.6172106825, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658464, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7515926868361227}}
{"text": "\r\n\r\n\r\nfunction __oddify(n_eval::Int)\r\n    if n_eval % 2 == 0\r\n        n_eval += 1\r\n    end\r\n    return n_eval\r\nend\r\n\r\nfunction __calculate_gamma(n_eval::Int)\r\n    gamma_k = zeros(n_eval-1)\r\n    gamma_k[1] = 1/2\r\n    for kk = 2:(n_eval-1)\r\n        val = kk + 1\r\n        for ii = 2:(kk-1)\r\n            nom = ii\r\n            den = ii + kk\r\n            val *= (nom / den)\r\n        end\r\n        val *= 1/2\r\n        gamma_k[kk] = val\r\n    end\r\n    return gamma_k\r\nend\r\n\r\n\r\nfunction __select_noise_sigma(sigma_k, first_idx)\r\n    noise_sigma = 0.0\r\n    if first_idx != 0\r\n        noise_sigma = sigma_k[first_idx]\r\n    end\r\n    return noise_sigma\r\nend\r\n\r\nfunction __selection_criterion(T_ij, sigma_k, eta = 4.0, window_size = 3)\r\n    n_eval = length(sigma_k) + 1\r\n    first_idx_sigma = 0\r\n    for ii = 1:(n_eval-1-window_size+1)\r\n\r\n        min_s = min( sigma_k[ii:(ii+window_size-1)]... )\r\n        max_s = max( sigma_k[ii:(ii+window_size-1)]... )\r\n        \r\n        if max_s <= eta * min_s\r\n            first_idx_sigma = ii\r\n            break        \r\n        end\r\n    end\r\n\r\n    first_idx_sign = 0\r\n    break_flag = false\r\n    for ii = 2:(n_eval-2)\r\n        \r\n        sign_1 = sign( T_ij[1, ii+1] )\r\n        for jj = 2:(n_eval - ii)\r\n            sign_2 = sign( T_ij[jj, ii+1] )\r\n            if sign_1 != sign_2\r\n                first_idx_sign = ii\r\n                break_flag = true\r\n                break\r\n            end\r\n        end\r\n        if break_flag\r\n            break\r\n        end\r\n\r\n    end\r\n    first_idx = min(first_idx_sign, first_idx_sigma)\r\n    return first_idx\r\nend\r\n\r\nfunction __calculate_sigma(T_ij, gamma_k, n_eval)\r\n    sigma_k = zeros(n_eval-1)\r\n    for kk = 1:(n_eval-1)\r\n        vi = view( T_ij, 1:(n_eval-kk), kk+1 )\r\n        sum_T_ij = sum( vi.*vi )\r\n        sigma_k[kk] = sqrt( gamma_k[kk] / (n_eval - kk) * sum_T_ij )\r\n    end\r\n    return sigma_k\r\nend\r\n\r\n\r\n\r\n# -------------------------- #\r\n# dependent on the dimension #\r\n# -------------------------- #\r\n\r\n\r\n\r\n\r\nfunction __create_spacing(n_eval, x0::T, h::T) where {T <: Number}\r\n    x_i = zeros(n_eval)\r\n\r\n    x_i[ div(n_eval, 2)+1 ] = x0\r\n\r\n    start_idx = div(n_eval, 2)\r\n    for ii = start_idx:-1:1\r\n        x_i[ii] = x0 - (start_idx + 1 - ii) * h\r\n    end\r\n    start_idx = div(n_eval, 2)+2\r\n    for ii = start_idx:1:n_eval\r\n        x_i[ii] = x0 + (ii - start_idx + 1) * h\r\n    end\r\n\r\n    return x_i\r\nend\r\n\r\nfunction __create_spacing(n_eval, x0::Vector{T}, h::Vector{T}) where {T <: Number}\r\n    \r\n    n_dim = length(x0)\r\n    x_i = zeros(n_dim, n_eval)\r\n\r\n    x_i[ :, div(n_eval, 2)+1 ] = x0\r\n\r\n    start_idx = div(n_eval, 2)\r\n    for ii = start_idx:-1:1\r\n        x_i[:, ii] = x0 .- (start_idx + 1 - ii) .* h\r\n    end\r\n    start_idx = div(n_eval, 2)+2\r\n    for ii = start_idx:1:n_eval\r\n        x_i[:, ii] = x0 .+ (ii - start_idx + 1) .* h\r\n    end\r\n\r\n    return x_i\r\nend\r\n\r\n\r\n\r\n\r\n\r\nfunction __allocate_table(n_eval)\r\n    T_ij = zeros(n_eval, n_eval)\r\n    return T_ij\r\nend\r\n\r\nfunction __eval_function(fcn, x_i::Vector{T}, T_ij) where {T}\r\n    for ii = 1:size(T_ij, 1)\r\n        T_ij[ii, 1] = fcn( x_i[ii] )\r\n    end\r\n    return T_ij\r\nend \r\n\r\nfunction __eval_function(fcn, x_i::Matrix{T}, T_ij) where {T}\r\n    n_eval = size(T_ij, 2)\r\n    for ii = 1:n_eval\r\n        T_ij[ii, 1] = fcn( x_i[:, ii] )\r\n    end\r\n    return T_ij\r\nend \r\n\r\nfunction __calculate_differences(T_ij, n_eval)\r\n    for kk = 1:(n_eval-1)\r\n        for ii = 1:(n_eval-kk)\r\n            T_ij[ii, kk+1] = T_ij[ii+1, kk] - T_ij[ii, kk]\r\n        end\r\n    end\r\n\r\n    return T_ij\r\nend\r\n\r\nfunction __difference_table(fcn, x_i::Vector{T}, n_eval::Int) where {T}\r\n    # fcn: R -> R\r\n\r\n    # allocate the table\r\n    T_ij = __allocate_table(n_eval)\r\n\r\n    # calculate the divided differences\r\n    T_ij = __eval_function(fcn, x_i, T_ij)\r\n\r\n    T_ij = __calculate_differences(T_ij, n_eval)\r\n    \r\n    return T_ij\r\nend\r\n\r\nfunction __difference_table(fcn, x_i::Matrix{T}, n_eval::Int) where {T}\r\n    # fcn: R^n -> R\r\n\r\n    # allocate the table\r\n    T_ij = __allocate_table(n_eval)\r\n\r\n    # calculate the divided differences\r\n    T_ij = __eval_function(fcn, x_i, T_ij)\r\n\r\n    T_ij = __calculate_differences(T_ij, n_eval)\r\n    \r\n    return T_ij\r\nend\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nfunction estimate_noise(\r\n    fcn, \r\n    x0;\r\n    n_eval = 7, \r\n    h = 1e3 * sqrt.(eps.(x0))\r\n    )\r\n    # fcn : R -> R\r\n\r\n    n_eval      = __oddify(n_eval)\r\n    x_i         = __create_spacing(n_eval, x0, h)\r\n    gamma_k     = __calculate_gamma(n_eval)\r\n    T_ij        = __difference_table(fcn, x_i, n_eval)\r\n    sigma_k     = __calculate_sigma(T_ij, gamma_k, n_eval)\r\n    first_idx   = __selection_criterion(T_ij, sigma_k)\r\n    noise_sigma = __select_noise_sigma(sigma_k, first_idx)\r\n\r\n    return noise_sigma\r\nend\r\n\r\n\r\n\r\nfunction estimate_noise(\r\n    fcn, \r\n    x0::Vector{T};\r\n    step_direction = normalize( 0.5.-rand(length(x0)) ),\r\n    n_eval::Int = 7, \r\n    h = 1e3 * sqrt.(eps.(x0))\r\n    ) where {T}\r\n    # fcn : R^n -> R \r\n\r\n    n_eval      = __oddify(n_eval)                                      # indepedent of dim\r\n    x_i         = __create_spacing(n_eval, x0, step_direction .* h)     # double implementation\r\n    gamma_k     = __calculate_gamma(n_eval)                             # indepedent of dim\r\n    T_ij        = __difference_table(fcn, x_i, n_eval)                  # double implementation\r\n    sigma_k     = __calculate_sigma(T_ij, gamma_k, n_eval)              # indepedent of dim\r\n    first_idx   = __selection_criterion(T_ij, sigma_k)                  # indepedent of dim\r\n    noise_sigma = __select_noise_sigma(sigma_k, first_idx)              # indepedent of dim\r\n\r\n    return noise_sigma\r\nend\r\n\r\n\r\n\r\nfunction noisy_numdiff_fw(fcn, x0)\r\n    noise_est = estimate_noise(fcn, x0)\r\n    h = max( sqrt(noise_est), sqrt.(eps.(x0)) )\r\n    return numdiff_fw(fcn, x0, h)\r\nend\r\n", "meta": {"hexsha": "209e9f0ed539fe8a0dcb3b3b2c325ce68f5d2e80", "size": 5791, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/common/numder/src/noisy_num_diff.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "__lib__/math/common/numder/src/noisy_num_diff.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "__lib__/math/common/numder/src/noisy_num_diff.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4453441296, "max_line_length": 96, "alphanum_fraction": 0.5418753238, "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7515926815662277}}
{"text": "using Printf, Distributions\n\nnewgrid(p::Float64, M::Int=15, N::Int=15) = rand(Bernoulli(p), M, N)\n\nfunction walkmaze!(grid::Matrix{Int}, r::Int, c::Int, indx::Int)\n    NOT_VISITED = 1 # const\n    N, M = size(grid)\n    dirs = [[1, 0], [-1, 0], [0, 1], [1, 0]]\n    # fill cell\n    grid[r, c] = indx\n\n    # is the bottom line?\n    rst = r == N\n\n    # for each direction, if has not reached the bottom yet and can continue go to that direction\n    for d in dirs\n        rr, cc = (r, c) .+ d\n        if !rst && checkbounds(Bool, grid, rr, cc) && grid[rr, cc] == NOT_VISITED\n            rst = walkmaze!(grid, rr, cc, indx)\n        end\n    end\n    return rst\nend\n\nfunction checkpath!(grid::Matrix{Int})\n    NOT_VISITED = 1 # const\n    N, M = size(grid)\n    walkind = 1\n    for m in 1:M\n        if grid[1, m] == NOT_VISITED\n            walkind += 1\n            if walkmaze!(grid, 1, m, walkind)\n                return true\n            end\n        end\n    end\n    return false\nend\n\nfunction printgrid(G::Matrix{Int})\n    LETTERS = vcat(' ', '#', 'A':'Z')\n    for r in 1:size(G, 1)\n        println(r % 10, \") \", join(LETTERS[G[r, :] .+ 1], ' '))\n    end\n    if any(G[end, :] .> 1)\n        println(\"!) \", join((ifelse(c > 1, LETTERS[c+1], ' ') for c in G[end, :]), ' '))\n    end\nend\n\nconst nrep = 1000 # const\nsampleprinted = false\n\np = collect(0.0:0.1:1.0)\nf = similar(p)\nfor i in linearindices(f)\n    c = 0\n    for _ in 1:nrep\n        G = newgrid(p[i])\n        perc = checkpath!(G)\n        if perc\n            c += 1\n            if !sampleprinted\n                @printf(\"Sample percolation, %i×%i grid, p = %.2f\\n\\n\", size(G, 1), size(G, 2), p[i])\n                printgrid(G)\n                sampleprinted = true\n            end\n        end\n    end\n    f[i] = c / nrep\nend\n\nprintln(\"\\nFrequencies for $nrep tries that percolate through\\n\")\nfor (pi, fi) in zip(p, f)\n    @printf(\"p = %.1f ⇛ f = %.3f\\n\", pi, fi)\nend\n", "meta": {"hexsha": "bbfb3b9242707f344b20501beb2f0c5cd5ec718c", "size": 1908, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/percolation-site-percolation.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/percolation-site-percolation.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/percolation-site-percolation.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1052631579, "max_line_length": 101, "alphanum_fraction": 0.5115303983, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7515926783787268}}
{"text": "# ---\n# title: 1250. Check If It Is a Good Array\n# id: problem1250\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Hard\n# categories: Math\n# link: <https://leetcode.com/problems/check-if-it-is-a-good-array/description/>\n# hidden: true\n# ---\n# \n# Given an array `nums` of positive integers. Your task is to select some subset\n# of `nums`, multiply each element by an integer and add all these numbers. The\n# array is said to be  **good  **if you can obtain a sum of `1` from the array\n# by any possible subset and multiplicand.\n# \n# Return `True` if the array is **good  **otherwise return `False`.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: nums = [12,5,7,23]\n#     Output: true\n#     Explanation: Pick numbers 5 and 7.\n#     5*3 + 7*(-2) = 1\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: nums = [29,6,10]\n#     Output: true\n#     Explanation: Pick numbers 29, 6 and 10.\n#     29*1 + 6*(-3) + 10*(-1) = 1\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: nums = [3,6]\n#     Output: false\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= nums.length <= 10^5`\n#   * `1 <= nums[i] <= 10^9`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "0ba879c4a7f630df49074a533fa3e5d64f8f331b", "size": 1202, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1250.check-if-it-is-a-good-array.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/unresolved/1250.check-if-it-is-a-good-array.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/unresolved/1250.check-if-it-is-a-good-array.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 19.3870967742, "max_line_length": 80, "alphanum_fraction": 0.5557404326, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7515926783787268}}
{"text": "#!/usr/bin/env julia\n\n\"\"\"\n# Problem 3: Largest prime factor\n\nThe prime factors of 13195 are 5, 7, 13 and 29.\n\nWhat is the largest prime factor of the number `n`?\n\"\"\"\nmodule Problem003\n\ninclude(\"Primes.jl\")\n\n\"\"\"\n    solve(; n::Integer = 600851475143)\n\nReturns the solution for [`Problem003`](@ref) with the given parameters.\n\n## Preconditions\n- `n ≥ 2`\n\"\"\"\nfunction solve(; n::Integer = 600851475143)\n    return last(Primes.prime_factorization(n))[1]\nend\n\nend\n", "meta": {"hexsha": "bf22022d1b8569358a07fef20b5529ad58aeadcb", "size": 459, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jl/src/Problem003.jl", "max_stars_repo_name": "curtislb/ProjectEuler", "max_stars_repo_head_hexsha": "7baf8d7b7ac0e8697d4dec03458b473095a45da4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jl/src/Problem003.jl", "max_issues_repo_name": "curtislb/ProjectEuler", "max_issues_repo_head_hexsha": "7baf8d7b7ac0e8697d4dec03458b473095a45da4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jl/src/Problem003.jl", "max_forks_repo_name": "curtislb/ProjectEuler", "max_forks_repo_head_hexsha": "7baf8d7b7ac0e8697d4dec03458b473095a45da4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0, "max_line_length": 72, "alphanum_fraction": 0.688453159, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.7515806406940039}}
{"text": "using Flux, DiffEqFlux, OrdinaryDiffEq, DiffEqParamEstim, Plots, Optim, Dates\n####################################################### Observation ###############################################################\n# Start conditions for the two species in the system\nu0 = Float32[2.; 0.]\n# Number of evaluations of the neural ODE. It relates to the numbers of layers of the neural net (depth of network).\ndatasize = 30\n# Time span in which of evaluation will be and actual timepoints of evaluations\ntspan = (0.0f0, 1.5f0)\nt = range(tspan[1], tspan[2], length = datasize)\n# The true ODE (with the true parameters) which the neural net should learn\nfunction trueODEfunc(du, u, p, t)\n  true_A = [-0.1 2.0; -2.0 -0.1]\n  du .= ((u.^3)'true_A)'\nend\n# Construction of the ODEProblem and solving the ODEProblem with Tsit5 solver\nprob = ODEProblem(trueODEfunc, u0, tspan)\node_data = Array(solve(prob,Tsit5(),saveat=t))\n################################################### Building a neural ODE ##########################################################\n# Derivative is modeled by a neural net. Chain concatinates the functions ode function and two dense layers.\ndudt = Chain(x -> x.^3,\n       Dense(2,50,tanh),\n       Dense(50,2))\n# Parameters of the model which are to be learnt. They are: W1 (2x50), b1 (50), W2 (50x2), b2 (2)\nps = Flux.params(dudt)\n# Defining anonymous function for the neural ODE with the model. in: u0, out: solution with current params.\nn_ode = x->neural_ode(dudt, x, tspan, Tsit5(), saveat=t, reltol=1e-7, abstol=1e-9)\n#L2 loss\nn_epochs = 1\nmutable struct saver\n    losses::Array{Float64,1}\n    times::Array{Dates.Time,1}\n    count_epochs::Int128\nend\nfunction saver(n_epochs)\n    losses = zeros(n_epochs)\n    times = fill(Dates.Time(Dates.now()),n_epochs)\n    count_epochs = 0\n    return saver(losses,times,count_epochs)\nend\nfunction update_saver(saver, loss_i, time_i)\n    epoch_i = saver.count_epochs\n    saver.losses[epoch_i] = loss_i\n    saver.times[epoch_i] = time_i\nend\n\nsa_l2 = saver(n_epochs)\n\nL2_loss_fct() = sum(abs2,ode_data .- n_ode(u0))\n# Callback function to observe L2 training.\ncb = function ()\n    sa_l2.count_epochs = sa_l2.count_epochs +  1\n\n    update_saver(sa_l2, Tracker.data(L2_loss_fct()),Dates.Time(Dates.now()))\n\n    println(\"\\\"\",Tracker.data(L2_loss_fct()),\"\\\" \\\"\",Dates.Time(Dates.now()),\"\\\";\")\nend\n#training call\nopt = ADAM(0.1)\ndata = Iterators.repeated((), n_epochs)\n@time Flux.train!(L2_loss_fct, ps, data, opt, cb = cb)\n\n\n# Call n_ode to get first prediction and to show startpoint for training.\npred = n_ode(u0)\nscatter(t, ode_data[1,:], label=\"data\")\nscatter!(t, Flux.data(pred[1,:]), label=\"prediction\")\nscatter!(t, ode_data[2,:], label=\"data\")\nscatter!(t, Flux.data(pred[2,:]), label=\"prediction\")\n\n#savefig(\"sogood.png\")\n\n\nusing BSON: @save\n@save \"model_l2_1000_epochs.bson\" dudt\n", "meta": {"hexsha": "aa0d7caa02a9a22fcc879c6b84e99d345fea9cb4", "size": 2828, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/feature-1/test-node-feature-1-L2.jl", "max_stars_repo_name": "LislPisl/DiffEqFlux.jl", "max_stars_repo_head_hexsha": "a24bfdec056d2a3ab0ee047bd51325561ed64273", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/feature-1/test-node-feature-1-L2.jl", "max_issues_repo_name": "LislPisl/DiffEqFlux.jl", "max_issues_repo_head_hexsha": "a24bfdec056d2a3ab0ee047bd51325561ed64273", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/feature-1/test-node-feature-1-L2.jl", "max_forks_repo_name": "LislPisl/DiffEqFlux.jl", "max_forks_repo_head_hexsha": "a24bfdec056d2a3ab0ee047bd51325561ed64273", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7066666667, "max_line_length": 132, "alphanum_fraction": 0.6516973126, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7515806400531464}}
{"text": "\"\"\"\n    ref_int(a=1, b=1; tmax=10000, rtol=1E-12)\n\nCalculates Coulomb repulsion between two Gaussian charge distributions\nthat have same origin.\n\n# Arguments\n- `a=1`  :   with of first Gaussian exp(-ax^2)\n- `b=1`  :   with of second Gaussian exp(-bx^2)\n\n# Keywords\n- `tmax=10000`   :  maximum t-value for integration\n- `rtol=1E-12`   :  relative tolerance for t-integration\n\"\"\"\nfunction ref_int(a=1, b=1; tmax=10000, rtol=1E-12)\n    _f(t) = 1/sqrt( (a+b)*t^2 + a*b)\n    norm = a*b/π\n    return 2*√π * norm * quadgk(_f, 0, tmax; rtol=rtol)[1]\nend\n\n\nfunction test_eri_accuracy(d, ne, np; a=1, b=1)\n    basis = Basis(-0.5*d, 0.5*d, ne, np)\n    ρ1 = exp.(-a.*basis.^2) .* sqrt(a/π)\n    ρ2 = exp.(-b.*basis.^2) .* sqrt(b/π)\n    ω = get_weight(basis)\n    w = diagm(ω)\n    l = length(basis)\n\n    J = zeros(l,l)\n    for i in 1:l, j in 1:l\n        J[i,j] = eri(basis, i, j)\n    end\n    cal = ρ2'*w*J*ρ1\n\n    ref = ref_int(a, b)\n\n    return Dict(\"ref\"=>ref, \"cal\"=>cal)\nend", "meta": {"hexsha": "25e02a49840e85bce0f98e05899ece0692dee7a2", "size": 963, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/accuracy_tests.jl", "max_stars_repo_name": "tjjarvinen/OneDimensionalCorrelation", "max_stars_repo_head_hexsha": "4c0adf138e95f24da55acb32f524943b4ce3ba7e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/accuracy_tests.jl", "max_issues_repo_name": "tjjarvinen/OneDimensionalCorrelation", "max_issues_repo_head_hexsha": "4c0adf138e95f24da55acb32f524943b4ce3ba7e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-08-25T11:54:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-02T11:47:46.000Z", "max_forks_repo_path": "src/accuracy_tests.jl", "max_forks_repo_name": "tjjarvinen/OneDimensionalCorrelation", "max_forks_repo_head_hexsha": "4c0adf138e95f24da55acb32f524943b4ce3ba7e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6923076923, "max_line_length": 70, "alphanum_fraction": 0.5804776739, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7515806324168451}}
{"text": "using Compose, Colors\n\n# const padding = 0.5mm\n\nfunction sierpinski(n::Int)\n    if n == 0\n        compose(context(), polygon([(1,1), (0,1), (1/2, 0)]))\n    else\n        t = sierpinski(n - 1)\n        compose(context(),\n                (context(1/4,   0, 1/2, 1/2), t),\n                (context(  0, 1/2, 1/2, 1/2), t),\n                (context(1/2, 1/2, 1/2, 1/2), t))\n        # compose(context(),\n        #         (context(0.25w + padding, padding,        0.5w - 2*padding, 0.5h - 2*padding), t),\n        #         (context(padding,         0.5h + padding, 0.5w - 2*padding, 0.5h - 2*padding), t),\n        #         (context(0.5w + padding,  0.5h + padding, 0.5w - 2*padding, 0.5h - 2*padding), t))\n    end\nend\n\nimg = SVG(\"sierpinski.svg\", 4inch, 4(√3/2)inch)\ndraw(img, compose(sierpinski(2), linewidth(0.1mm), fill(nothing), stroke(colorant\"black\")))\n\nimg = SVG(\"sierpinski.svg\", 4inch, 4(√3/2)inch)\n@time draw(img, compose(sierpinski(8), linewidth(0.1mm), fill(nothing), stroke(colorant\"black\")))\n\n#img = SVG(\"sierpinski.svg\", 4inch, 4(√3/2)inch)\n#@profile draw(img, compose(sierpinski(10), linewidth(0.1mm), fill(nothing), stroke(colorant\"black\")))\n#Profile.print()\n", "meta": {"hexsha": "8fb5ea7a583511fcbc19f631e46d0158a9746807", "size": 1170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/sierpinski.jl", "max_stars_repo_name": "Mattriks/Compose.jl", "max_stars_repo_head_hexsha": "d38a806c29d40d7448d8f7490e917f84931a3065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/sierpinski.jl", "max_issues_repo_name": "Mattriks/Compose.jl", "max_issues_repo_head_hexsha": "d38a806c29d40d7448d8f7490e917f84931a3065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/sierpinski.jl", "max_forks_repo_name": "Mattriks/Compose.jl", "max_forks_repo_head_hexsha": "d38a806c29d40d7448d8f7490e917f84931a3065", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0, "max_line_length": 102, "alphanum_fraction": 0.5564102564, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7515806212828213}}
{"text": "function normalize(x)\n    mag = norm(x)\n    if mag > 0.0 \n        return x ./ mag \n    else \n        return ones(length(x)) ./ length(x)\n    end\nend\n\nfunction ∂normalize∂x(x)\n    mag = norm(x)\n    n = length(x)\n    if mag > 0.0 \n        n = length(x)\n        return 1.0 * I(n) ./ mag - x * transpose(x) ./ mag^3\n    else \n        return 1.0 * I(n) # TODO: confirm this is good choice\n    end\nend\n\nfunction ∂norm∂x(x)\n    mag = norm(x) \n    if mag > 0.0 \n        return x' ./ mag \n    else\n        return ones(1, length(x))\n    end\nend", "meta": {"hexsha": "c567bd76c0a0388aebc23cf67fef9869c024bd82", "size": 534, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utilities/normalize.jl", "max_stars_repo_name": "rejuvyesh/Dojo.jl", "max_stars_repo_head_hexsha": "6c9f8bdb31de3e2068ea1a51afe317ada3922379", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70, "max_stars_repo_stars_event_min_datetime": "2022-03-02T01:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:14:51.000Z", "max_issues_repo_path": "src/utilities/normalize.jl", "max_issues_repo_name": "dojo-sim/Dojo.jl", "max_issues_repo_head_hexsha": "33ccdde8d7f74c4ea3c3bffdebcc6ed65959a5be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2022-03-02T06:58:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T17:17:26.000Z", "max_forks_repo_path": "src/utilities/normalize.jl", "max_forks_repo_name": "rejuvyesh/Dojo.jl", "max_forks_repo_head_hexsha": "6c9f8bdb31de3e2068ea1a51afe317ada3922379", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2022-03-07T01:47:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T19:13:07.000Z", "avg_line_length": 19.0714285714, "max_line_length": 61, "alphanum_fraction": 0.5037453184, "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7515806209623926}}
{"text": "# Exercise 1\nusing LinearAlgebra, Random\nusing BenchmarkTools\n\nN = 50\nA = rand(N, N)\nB = rand(N, N)\n@btime $A * $B\n\n# loop by the row first\nfunction rowloop(a, b)\n    @assert size(a)[2] == size(b)[1]\n    c = zeros(size(a)[1], size(b)[2])\n    for j in 1:size(b)[2]\n        for i in 1:size(a)[1]\n            c[i, j] = a[i, :]' * b[:, j]\n        end\n    end\n    return c\nend\n@btime rowloop($A, $B)\n\n# loop by the column first\nfunction colloop(a, b)\n    @assert size(a)[2] == size(b)[1]\n    c = zeros(size(a)[1], size(b)[2])\n    for i in 1:size(a)[1]\n        for j in 1:size(b)[2]\n            c[i, j] = a[i, :]' * b[:, j]\n        end\n    end\n    return c\nend\n@btime colloop($A, $B)\n\n# loop by the dot product\nfunction rowloopdot(a, b)\n    @assert size(a)[2] == size(b)[1]\n    c = zeros(size(a)[1], size(b)[2])\n    for j in 1:size(b)[2]\n        for i in 1:size(a)[1]\n            c[i, j] = dot(a[i, :], b[:, j])\n        end\n    end\n    return c\nend\n@btime rowloopdot($A, $B)\n\nfunction colloopdot(a, b)\n    @assert size(a)[2] == size(b)[1]\n    c = zeros(size(a)[1], size(b)[2])\n    for i in 1:size(a)[1]\n        for j in 1:size(b)[2]\n            c[i, j] = dot(a[i, :], b[:, j])\n        end\n    end\n    return c\nend\n@btime colloopdot($A, $B)\n\n# Compare colloopdot(a, b) to the built-in function\nA10 = rand(10, 10)\nB10 = rand(10, 10)\nA1000 = rand(1000, 1000)\nB1000 = rand(1000, 1000)\n@btime $A10 * $B10\n@btime colloopdot($A10, $B10)\n@btime $A1000 * $B1000\n@btime colloopdot($A1000, $B1000)", "meta": {"hexsha": "70c05930200c5a03e8a13181c12bf6e4b33bd446", "size": 1480, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Problem Sets/PS4.jl", "max_stars_repo_name": "jeff72216/ECON622_exercise", "max_stars_repo_head_hexsha": "300d9c917f6feb456302b57f554739d8ef98c759", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Problem Sets/PS4.jl", "max_issues_repo_name": "jeff72216/ECON622_exercise", "max_issues_repo_head_hexsha": "300d9c917f6feb456302b57f554739d8ef98c759", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Problem Sets/PS4.jl", "max_forks_repo_name": "jeff72216/ECON622_exercise", "max_forks_repo_head_hexsha": "300d9c917f6feb456302b57f554739d8ef98c759", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4492753623, "max_line_length": 51, "alphanum_fraction": 0.5277027027, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.7515606113919171}}
{"text": "function isequispaced(t)\r\n    d1 = t[2] - t[1]\r\n    for i in 3:length(t)\r\n        d = t[i] - t[i-1]\r\n        d == d1 || return false\r\n    end\r\n    return true\r\nend\r\n\r\n\"\"\"\r\n    findnearest(val, A)\r\nReturn the index of `A` which has value nearest to `val`.\r\n\"\"\"\r\nfunction findnearest(val::Real, A::AbstractVector{<:Real})\r\n    i = 1\r\n    d = abs(val - A[i])\r\n    @inbounds for j in 1:length(A)\r\n        dd = abs(val - A[j])\r\n        if dd < d\r\n            i = j\r\n            d = dd\r\n        end\r\n    end\r\n    return i\r\nend\r\n\r\n\r\nexport nrmse, rmse\r\nfunction mse(x, y)\r\n    m = length(x)\r\n    @assert m == length(y)\r\n    @inbounds mse = sum(abs2(x[i] - y[i]) for i in 1:m) / m\r\n    return mse\r\nend\r\n\r\nusing Statistics: mean\r\n\r\n\"\"\"\r\n    rmse(x, y) → e\r\nReturn the root mean square error `e` of the \"fit\" `y` into data `x`.\r\n\"\"\"\r\nrmse(x, y) = sqrt(mse(x, y))\r\n\r\n\"\"\"\r\n    nrmse(x, y) → e\r\nReturn the normalized root mean square error of the \"fit\" `y` into data `x`.\r\nThis number is the relative error of `y` to `x` versus `mean(x)` to `x`, i.e.\r\nif `e < 1` the fit `y` is better than using `mean(x)` as a fit.\r\n\"\"\"\r\nfunction nrmse(x, y)\r\n    m = length(x)\r\n    mean_out = mean(x)\r\n    _mse     = mse(x, y)\r\n    @inbounds msemean = sum(abs2(x[i] - mean_out) for i in 1:m) / m\r\n    nrmse   = sqrt(_mse / msemean)\r\n    return nrmse\r\nend\r\n\r\n\"\"\"\r\n    σrmse(x, y) = rmse(x, y)/std(x)\r\nRelative error of the fit `y` to data `x` with respect to `std(x)`. \r\n\"\"\"\r\nσrmse(x, y) = rmse(x, y)/std(x)\r\n\r\nexport nrmse, rmse, σrmse\r\n", "meta": {"hexsha": "193b02c1ee5fdd05af182d71cf4e52a96a72025c", "size": 1509, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "JuliaDynamics/SignalDecomposition.jl", "max_stars_repo_head_hexsha": "e865058d48a5e28e827b97ed05e99952f86e9a66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2020-04-04T14:49:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T19:36:47.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "JuliaDynamics/SignalDecomposition.jl", "max_issues_repo_head_hexsha": "e865058d48a5e28e827b97ed05e99952f86e9a66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-04-04T09:29:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T14:33:06.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "JuliaDynamics/SignalDecomposition.jl", "max_forks_repo_head_hexsha": "e865058d48a5e28e827b97ed05e99952f86e9a66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8636363636, "max_line_length": 78, "alphanum_fraction": 0.5314777999, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343393, "lm_q2_score": 0.8615382094310355, "lm_q1q2_score": 0.7515606037597155}}
{"text": "# This is to facilitate conversion of MATLAB codes to Julia, if needed.\n\n\n\n@doc \"\"\"\nmeshgrid is similar to MATLAB's function. It takes in a range, vector, matrix or similar\nand makes an array of those values.\nIn the case of a cartesian grid, it would like an 'X' and 'Y' vectors and make a matrix filled with\nthe X and Y coordinates:\njulia> X = 0:3\njulia> Y = 0:3\njulia> XX,YY = meshgrid(X,Y)\njulia> XX\n4×4 Array{Int64,2}:\n 0  0  0  0\n 1  1  1  1\n 2  2  2  2\n 3  3  3  3\n julia> YY\n 4×4 Array{Int64,2}:\n 0  1  2  3\n 0  1  2  3\n 0  1  2  3\n 0  1  2  3\n\n If a single vector/range is inputted, for example X = 0:3 , it will output interpret it as meshgrid(X,X)\n\n\"\"\"-> function meshgrid(xs, ys)\n    [xs[i] for i in 1:length(xs), j in 1:length(ys)], [ys[j] for i in 1:length(xs), j in 1:length(ys)]\nend\n\nfunction meshgrid(xs;dims=3)\n    if dims==3\n        meshgrid(xs, xs,xs)\n    elseif dims==2\n        meshgrid(xs, xs)\n    end\n\nend\n\nfunction meshgrid(xs,ys,zs)\n    return ([xs[i] for i in 1:length(xs), j in 1:length(ys), k in 1:length(zs)],\n    [ys[j] for i in 1:length(xs), j in 1:length(ys), k in 1:length(zs)],\n    [zs[k] for i in 1:length(xs), j in 1:length(ys), k in 1:length(zs)])\n\nend\n", "meta": {"hexsha": "73f7f8446e017ad59df025765ce4391f2589849c", "size": 1189, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/meshgrid.jl", "max_stars_repo_name": "EliMattingly22/MPI_Tools", "max_stars_repo_head_hexsha": "159b4afe8e3b5143598d67e48a9ac130fc062af4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/meshgrid.jl", "max_issues_repo_name": "EliMattingly22/MPI_Tools", "max_issues_repo_head_hexsha": "159b4afe8e3b5143598d67e48a9ac130fc062af4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/meshgrid.jl", "max_forks_repo_name": "EliMattingly22/MPI_Tools", "max_forks_repo_head_hexsha": "159b4afe8e3b5143598d67e48a9ac130fc062af4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-06T20:49:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T20:49:56.000Z", "avg_line_length": 25.2978723404, "max_line_length": 105, "alphanum_fraction": 0.6291000841, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.8740772417253256, "lm_q1q2_score": 0.7514125229996238}}
{"text": "\n# coding: utf-8\n\n# In[1]:\n\n\n#heap sort is the alternative version of selection sort\n#heap sort is implemented on a binary heap instead of a list\n#well, u can argue binary heap is expressed in list\n#binary heap is a complete binary tree\n#for each node it has no more than two children\n#the tree is as far left as possible\n#for this binary heap, we keep minimum at root\n#similar to selection sort\n#we only need to get the smallest number for each round\n#and our list keeps shrinking until we are left with one element for final round\n#however, the traversal is kinda different from selection sort\n#what we do is to compare two children with parent node\n#we keep the smallest among the family of three as parent node for each node\n#until we reach the root and we successfully keep the smallest at root\n#next step is to remove the root and we find the minimum for the new tree\n#we would do it recursively in this script\n#otherwise we would have to use loops in loops\n\n#in this version we use min heap\n#if u intend to use max heap,check out geeks for geeks\n# https://www.geeksforgeeks.org/heap-sort/\n\n\n# In[2]:\n\n\nfunction heap_sort(arr)\n    \n    #denote layer as the height of the tree\n    layer=0\n    maxlen=length(arr)\n        \n    #when we are left with one element\n    #that is the base case for recursion\n    if maxlen<2\n    \n        return arr\n    \n    end\n    \n    #this part is to find out how many layers we got for binary heap\n    #note that layer starts from 1 in julia\n    while maxlen>2^layer\n        \n        maxlen-=2^layer\n        layer+=1\n        \n    end\n    \n    \n    #as layer starts from 1\n    #we have to use layer+1 to make sure each layer has been traveled\n    #until we reach the base case, layer 1, the root\n    for i in layer+1:-1:1\n        \n        #a special property of binary heap\n        #the beginning of each layer equals to 2^(i-1)\n        #each layer contains 2^(i-1) elements\n        for j in 2^(i-1):2^i-1\n            \n            #a special property of binary heap as well\n            #the index of left child is always even number\n            #and for the right child, always odd number\n            right=j*2+1\n            left=j*2\n\n            #we use try function in case the node is the leaf\n            #and if there is no left child\n            #there wont be right child\n            #according to the far left principle of binary heap\n            #we compare the parent with two children nodes\n            #we only keep the smallest as parent node\n            try\n            \n                if arr[left]<arr[j]\n                \n                    arr[left],arr[j]=arr[j],arr[left]\n                    \n                end\n\n                try\n                \n                    if arr[right]<arr[j]\n                    \n                        arr[right],arr[j]=arr[j],arr[right]\n                        \n                    end\n\n                    if arr[right]<arr[left]\n                        \n                        arr[right],arr[left]=arr[left],arr[right]\n                        \n                    end\n\n                catch e\n               \n                    if !(isa(e,BoundsError))\n                        \n                        throw(e)\n                    \n                    end\n\n                end\n\n            catch e\n               \n                if !(isa(e,BoundsError))\n                    \n                    throw(e)\n                    \n                end\n                \n            end\n            \n        end\n        \n    end\n    \n    #recursively, we shrink the size of the list\n    #by removing its root which is the smallest element for the current tree\n    arr[2:end]=heap_sort(arr[2:end])      \n    \n    return arr\n    \nend\n\n\n# In[3]:\n\n\n#heap sort s time complexity is o(nlogn)\n#however, this script is written in recursive function\n#it may not achieve the same speed as iterations\n\n\n# In[4]:\n\n\nfor _ in 1:100\n    \n    test_arr=rand(100)\n\n    if !(heap_sort(test_arr)==sort(test_arr))\n        printstyled(\"Erreur\",color=:red)\n    end\n\nend\n\n", "meta": {"hexsha": "43e97393336bfe1db88896a12c30eec38c093680", "size": 4034, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "heap sort.jl", "max_stars_repo_name": "je-suis-tm/search-and-sort", "max_stars_repo_head_hexsha": "822bbb1c53ac8ed6c244a18bd4ee03fcc577438e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-04-30T23:50:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:26:29.000Z", "max_issues_repo_path": "heap sort.jl", "max_issues_repo_name": "HafizSabia/search-and-sort", "max_issues_repo_head_hexsha": "b2a720b154f12549ae31f8647dc460ee343ec119", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "heap sort.jl", "max_forks_repo_name": "HafizSabia/search-and-sort", "max_forks_repo_head_hexsha": "b2a720b154f12549ae31f8647dc460ee343ec119", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-10-04T20:07:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T08:54:30.000Z", "avg_line_length": 26.0258064516, "max_line_length": 80, "alphanum_fraction": 0.5466038671, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.8740772335247531, "lm_q1q2_score": 0.7514125128072217}}
{"text": "using ThinkJulia\n\n\n# Exercise 4-1\n🐢 = Turtle() # \\:turtle:\nT = 🐢\n# @svg begin\n#     forward(T, 100)\n#     turn(T, -90)\n#     forward(T, 100)\n#     turn(T, -90)\n#     forward(T, 100)\n#     turn(T, -90)\n#     forward(T, 100)\n# end\n\n\n\n\n\n# Exercise 4-2, 4-4\nfunction square(t, len = 100)\n    for i in 1:4\n        forward(t, len)\n        turn(t, -90)\n    end\nend\n\n# Exercise 4-5\nfunction polygon(t, n, len = 100)\n    degree = 360/n;\n    for i in 1:n\n        forward(t, len)\n        turn(t, -degree)\n    end\nend\n\n# Exercise 4-6\nfunction circle(t, r)\n    # Approximate by polygon of n-sides\n    # circumference = n * len = pi * 2r, better one with tan?\n    # len = pi*2r/n\n    # len\n    #\n    # Could be better.\n\n    n = 100 # sides of polygon\n    circumference = pi * 2r\n    len = circumference / n\n    degree = 360/n\n\n    polygon(t, n, len)\nend\n\n# Exercise 4-7\nfunction arc(t, r, angle)\n    n = 100 # sides of polygon\n    circumference = pi * 2r * angle/360\n    len = circumference / n\n    degree = angle/n\n\n    #polygon(t, n, len)\n    for i in 1:n\n        forward(t, len)\n        turn(t, -degree)\n    end\nend\n\n@svg begin\n    # Exercise 4-1\n    # for i in 1:4\n    #     forward(T, 100)\n    #     turn(T, -90)\n    # end\n\n    # Exercise 4-3\n    square(T)\n\n    # Exercise 4-4\n    square(T, 10)\n\n    # Exercise 4-5\n    polygon(T, 7, 80)\n\n    # Exercise 4-6\n    circle(T, 30)\n\n    # Exercise 4-7\n    arc(T, 120, 270)\nend\n\n# TODO\n# Exercise 4-8\n# Exercise 4-12\n\n# Encapsulation\n\n\nprintln(\"DONE\")\n", "meta": {"hexsha": "dc762d42e91007feb06ddd7b9fe4e3ceaa0374c1", "size": 1485, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "think-julia/ch4.jl", "max_stars_repo_name": "ykyang/org.allnix.julia", "max_stars_repo_head_hexsha": "58933a5848dec81c53d591b4163e9a70df62ddd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "think-julia/ch4.jl", "max_issues_repo_name": "ykyang/org.allnix.julia", "max_issues_repo_head_hexsha": "58933a5848dec81c53d591b4163e9a70df62ddd8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "think-julia/ch4.jl", "max_forks_repo_name": "ykyang/org.allnix.julia", "max_forks_repo_head_hexsha": "58933a5848dec81c53d591b4163e9a70df62ddd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.85, "max_line_length": 61, "alphanum_fraction": 0.534006734, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7514125126458351}}
{"text": "### A Pluto.jl notebook ###\n# v0.18.0\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local iv = try Base.loaded_modules[Base.PkgId(Base.UUID(\"6e696c72-6542-2067-7265-42206c756150\"), \"AbstractPlutoDingetjes\")].Bonds.initial_value catch; b -> missing; end\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)\n        el\n    end\nend\n\n# ╔═╡ 74479a7e-8c34-11eb-0e09-73f47f8013bb\nbegin\n\tusing Plots, LaTeXStrings, PrettyTables, DataFrames, LinearAlgebra,\n          PlutoUI, BenchmarkTools, ForwardDiff, Printf, Random, FFTW\n\tinclude(\"tools.jl\")\nend\n\n# ╔═╡ 8728418e-8c34-11eb-3313-c52ecadbf252\nmd\"\"\"\n\n## §3 Least Squares\n\nThe topic of the next set of lectures is least squares regression. Fitting the parameters of a model to general observations about that model is a ubiquitious problem occuring throughout the sciences, engineering and technology. The focus of this lecture will be a relatively simple setting where we can explore very precisely/rigorously how we can connect least squares methods and approximation theory. In the end we will also see how least squares methods can be tweaked in an unexpected way to solve the difficult max-norm best approximation problem!\n\n* fitting a trigonometric polynomial to random data\n* lsq fitting versus approxmation\n* iteratively reweighted lsq for best approximation in the max-norm\n\"\"\"\n\n# ╔═╡ 9202b69e-9013-11eb-02a2-2f1c8e2fcc0c\nmd\"\"\"\n\n## §3.2 Fitting to Point Values\n\nWe now consider the vastly simpler question of determining the coefficients (parameters) of a trigonometric polynomial ``t_N \\in \\mathcal{T}_N`` or ``t_N \\in \\mathcal{T}_N'`` by minimising the least squares functional\n```math\n\tL(\\boldsymbol{c}) := \\frac12 \\sum_{m = 1}^M \\big| t_N(x_j) - f_j \\big|^2,\n```\nwhere the tuples ``(x_j, f_j)`` are the \"training data\" and ``L`` is called the loss function.\n\nTrigonometric interpolation can in fact be seen as a special case: if we take ``M = 2N`` and ``x_j`` the interpolation points, the loss can be minimised to achieve ``L(\\boldsymbol{c}) = 0`` and the minimiser is precisely the solution of the linear system that defined the minimiser.\n\nBut we also want to explore the situation that we *cannot* choose the training data ``(x_j, f_j)`` but it is given to us. An interesting generic case that is in fact close to many real-world scenarios is that the training data is random. That is, we will take\n```math\n\tx_j \\sim U(-\\pi, \\pi), \\qquad {\\rm iid}\n```\nMoreover, we assume that the function values ``f_j`` are consistent, i.e. they arise from evaluation of a smooth function ``f(x)`` possibly subject to noise (e.g. due to measurement errors or model errors),\n```math\n\tf_j = f(x_j) + \\eta_j, \\qquad \\eta_j \\sim N(0, \\sigma), \\quad {\\rm iid}.\n```\nAssuming that the noise is normally distributed and iid is a particularly convenient scenario for analysis.\n\"\"\"\n\n\n# ╔═╡ 73983438-8c51-11eb-3142-03410d610022\nmd\"\"\"\n#### Implementation\n\nBefore we can start experimenting with this scenario, we need to discuss how to implement least squares problems. We will only be concerned with the case when ``M \\geq 2N`` i.e. there is sufficient data to determine the coefficients (at least in principle).\n\nWe begin by rewriting it in terms of the parameters, here for the case ``t_N \\in \\mathcal{T}_N``. Let ``A_{mk} = e^{i k x_j}`` be the value of the ``k``th basis function at the data point ``x_m``, then\n```math\n\t\\begin{aligned}\n\t\tL(\\boldsymbol{c})\n\t\t&=\n\t\t\t\\frac12 \\sum_{m = 1}^M\n\t\t\t\\bigg| \\sum_{k = -N}^N c_k e^{i k x_m} - f_m \\bigg|^2\n\t\t\\\\\n\t\t&=\n\t\t\t\\frac12\n\t\t\t\\frac12 \\sum_{m = 1}^M\n\t\t\t\\bigg| \\sum_{k = -N}^N  A_{mk} c_k - f_m \\bigg|^2\n\t\t\\\\\n\t\t&=\n\t\t\t\\frac12 \\sum_{m = 1}^M \\Big| (A \\boldsymbol{c})_m - f_m \\Big|^2\n\t\t\\\\\n\t\t&=\n\t\t\t\\frac12 \\big\\| A \\boldsymbol{c} - \\boldsymbol{f} \\big\\|^2,\n\t\\end{aligned}\n```\nwhere ``\\boldsymbol{f} = (f_m)_{m = 1}^M``.\nThis is a *linear least-squares system*. The matrix ``A`` is called the *design matrix*.\n\nThe first-order criticality condition, ``\\nabla L(\\boldsymbol{c}) = 0`` takes the form\n```math\n\tA^* A \\boldsymbol{c} = A^* \\boldsymbol{f}\n```\nThe equations making up this linear system are called the *normal equations*. \n\n**Lemma:** The least square problem has a unique minimizer if and only if the normal equations have a unique solution if and only if ``A`` has full rank.\n\nWe might be tempted to assemble the matrix ``A`` then form ``A^* A`` via matrix multiplication and then solve the system, e.g., using the Cholesky factorisation. This can go very badly since ``{\\rm cond}(A^* A) = {\\rm cond}(A)^2``, i.e. numerical round-off can become severe. Instead one should normally use the numerically very stable QR factorisation: there exist ``Q \\in \\mathbb{C}^{M \\times 2N}`` and ``R \\in \\mathbb{C}^{2N \\times 2N}`` such that \n```math \n\t\tA = Q R \n```\nWith that in hand, we can manipulate ``A^* A = R^* Q^* Q R = R^* R`` and hence \n```math \n\\begin{aligned} \n\t& A^* A \\boldsymbol{c} = A^* \\boldsymbol{f} \\\\ \n\t%\n\t\\Leftrightarrow \\qquad & \n\tR^* R \\boldsymbol{c} = R^* Q^* \\boldsymbol{f} \\\\ \n\t%\n\t\\Leftrightarrow \\qquad & \n\tR \\boldsymbol{c} = Q^* \\boldsymbol{f}.\n\\end{aligned}\n```\nMoreover, since ``R`` is upper triangular the solution of this system can be performed in ``O(N^2)`` operations.\n\"\"\"\n\n# ╔═╡ d08fb928-8c53-11eb-3c35-574ef188de6b\n\n# implementation of a basic least squares code\nbegin\n\t\"\"\"\n\tnote that we now use k = -N,..., N; but we respect the ordering of the FFT\t\n\t\"\"\"\n\tkgridproj(N) = [0:N; -N:-1]\n\t\n\t\"\"\"\n\ttrigonometric basis consistent with `kgridproj`\n\t\"\"\"\n\ttrigbasis(x, N) = [exp(im * x * k) for k = kgridproj(N)]\n\n\tfunction designmatrix(X, N)\n\t\tA = zeros(ComplexF64, length(X), 2*N+1)\n\t\tfor (m, x) in enumerate(X)\n\t\t\tA[m, :] .= trigbasis(x, N)\n\t\tend\n\t\treturn A\n\tend\n\n\t\"\"\"\n\tFit a trigonometric polynomial to the data ``X = (x_m), F = (f_m)``.\n\t\"\"\"\n\tfunction lsqfit(X, F, N)\n\t\tA = designmatrix(X, N)\n\t\treturn A \\ F   # this performs A = Q*R, R \\ (Q' * F) for us\n\tend\n\n\t\n\ttrigprojeval(x, c) = real(sum(c .* trigbasis(x, (length(c)-1) ÷ 2)))\nend\n\n# ╔═╡ fc8495a6-8c50-11eb-14ac-4dbad6baa3c3\nmd\"\"\"\nWe can explore this situation with a numerical experiment:\n\nData $M$: $(@bind _M1 Slider(10:10:500; show_value=true))\n\nDegree $N$: $(@bind _N1 Slider(5:100; show_value=true))\n\nNoise $\\eta = 10^{p}$; choose $p$: $(@bind _p1 Slider(-5:0; show_value=true))\n\"\"\"\n# $(@bind _eta Slider([0.0001, 0.001, 0.01, 0.1]))\n\n# ╔═╡ 1ba8aa58-8c51-11eb-2d66-775d0fd31747\nlet N = _N1, M = _M1, σ = 10.0^(_p1), f = x -> 1 / (1 + exp(10*sin(x)))\n\tRandom.seed!(2) # make sure we always produce the same random points\n\tif M < 2*N+1\n\t\tM = 2*N+1\n\t\tmsg = \"M must be >= 2N+1\"\n\tend\n\tX = 2*π * rand(M)\n\tF = f.(X) + σ * randn(length(X))\n\tc = lsqfit(X, F, N)\n\txp = range(0, 2π, length = 200)\n\tplot(xp, f.(xp), lw=4, label = L\"f\", size = (400, 200),\n\t\t\ttitle = \"N = $N, M = $M\", legend = :outertopright,\n\t\t ylims = [-0.3, 1.3])\n\tP = plot!(xp, trigprojeval.(xp, Ref(c)), lw=2, label = \"fit\")\n\tplot!(P, X, F, lw=0, ms=2, m=:o, c=:black, label = \"\")\nend\n\n# ╔═╡ 3d14680a-98df-42e2-9734-8a5ba27f5f6d\n\n\n# ╔═╡ 48175a0c-8e87-11eb-0f42-e9ca0f676e87\nmd\"\"\"\n### WARNING\n\nA proper treatment of this subject requires an in-depth computational statistics course. We cannot go into all the subtleties that are required here, such as cross-validation, regularisation, model selection. ... But we are in the age of data science and I *highly* recommend taking some advanced courses on these topics!\n\nHere, we will only explore some approximation-theoretic perspectives on balancing available data with choice of model, i.e. polynomial degree. There is obviously a non-trivial relationship between these. Secondly we will explore what we can say about optimal choice of data points in order to learn about how to choose sampling points if we could choose as we wish.\n\"\"\"\n\n# ╔═╡ e6cf2c86-9043-11eb-04a7-f1367ad64b6b\nmd\"\"\"\n## §3.3 Equispaced Data\n\nAs a warm-up we first explore the case when we get to *choose* the training datapoints. We already discussed that without *a priori* knowledge of the function to be fitted we should choose equi-spaced data points. Specifically, let us choose \n```math\n\tx_m = m\\pi/M, \\qquad m = 0, \\dots, 2M-1.\n```\nWe then evaluate the target function to obtain the training data, ``f_m := f(x_m)`` and minimize the loss \n```math\nL(\\boldsymbol{c}) = \\sum_{m = 1}^{2M-1} \\bigg| \\sum_{k = -N}^N c_k e^{i k x_m} - f_m \\bigg|^2\n``` \nto obtain the parameters. With ``M = N`` this is equivalent to trigonometric interpolation (easy exercise), where we even have a fast solver available (FFT). \n\"\"\"\n\n# ╔═╡ 82d74ec2-92a1-11eb-0d58-4bb674a8640e\nmd\"\"\"\n### Analysis of the lsq system \n\nLet us write out the loss function explicitly, but weighted, \n```math\n\tL_M(c) = \\frac{1}{2M} \\sum_{m = 0}^{2M-1} \\big| t_N(x_m) - f(x_m) \\big|^2\n```\nwhere ``t_N \\in \\mathcal{T}_N`` has coefficients ``\\boldsymbol{c} = (c_k)_{k = -N}^N``. Note that this is the periodic trapezoidal rule approximation of\n```math\n\tL_\\infty(c) = \\int_{0}^{2\\pi} \\big|t_N(x) - f(x) \\big|^2 \\,dx.\n```\nWe know that minimizing ``L_\\infty(c)`` gives the best possible ``L^2`` approximation, i.e., if ``c = \\arg\\min L_\\infty`` then \n```math \n\tt_N = \\Pi_N f = \\sum_{k = -N}^N \\hat{f}_k e^{i k x}\n``` \nand \n```math\n\t\\|t_N - f \\|_{L^2} \\leq \\| t_N' - f  \\|_{L^2} \\qquad \\forall t_N' \\in \\mathcal{T}_N'.\n```\n\"\"\"\n\n# ╔═╡ 879e9596-90a8-11eb-23d6-935e367eeb17\nmd\"\"\"\nBecause ``L_M`` is an approximation ``L_\\infty`` we can intuit that ``t_N = \\arg\\min L_M`` will be \"close\" to ``\\Pi_N f`` in some sense. The following result is makes this precise:\n\n**Proposition:** Let ``f \\in C_{\\rm per}``, and ``t_{NM} = \\arg\\min_{\\mathcal{T}_N} L_M`` with ``M > N``, then ``t_N = \\Pi_N I_M f``. In particular, \n```math\n\t\\|t_N - f \\|_{L^2} \n\t \\leq \n\t\\| \\Pi_N f - f \\|_{L^2} + \\| \\Pi_N (I_M f - f) \\|_{L^2}.\n```\n\n**Proof:** \n```math \n\\begin{aligned}\n\tL_M(t_N) \n\t&= \n\t\\frac{1}{2M} \\sum_{m = 0}^{2M-1} |t_N(x_m) - f(x_m)|^2\n\t\\\\ &= \n\t\\frac{1}{2M} \\sum_{m = 0}^{2M-1} |t_N(x_m) - I_M f(x_m)|^2\n\t\\\\ &= \n\t\\| t_N - I_M f \\|_{L^2}^2\n\\end{aligned}\n```\nby applying for the discrete and then the semi-discrete Plancherel theorem. \nThis means that minimising ``L_M`` actually minimizes the ``L^2``-distance to the trigonometric interpolant ``I_M f``, but with ``M > N``, i.e., \n```math\n\tt_N = \\Pi_N I_M f.\n```\nThe stated result now follows easily. ``\\square``\n\"\"\"\n\n# ╔═╡ 3abcfea6-92a2-11eb-061a-d9752403eff8\nmd\"\"\"\n**Remark:** We can study the \"error term\" ``\\| \\Pi_N (f - I_M f) \\|_{L^2}`` in more detail, but it should be intuitive that for ``M \\gg N`` it will be much smaller than the best-approximation term ``\\| f - \\Pi_N f \\|_{L^2}``. Importantly, this gives us an overarching strategy to consider when we perform least-squares fits: find an approxmiation error concept, ``\\| \\bullet - f\\|_{L^2}`` that is independent of the data ``(x_m, f_m)`` and which is minimized up to a higher-order term.\n\"\"\"\n\n# ╔═╡ c4b66e46-90a7-11eb-199e-cded424c7020\nmd\"\"\"\n### Fast solver\n\nWe now turn to the implementation of the least squares system that we studied in the previous section. While the naive implementation requires ``O(M N^2)`` cost of the QR factorisation, we can use the orthogonality of the trigonometri polynomials to replace this with a matrix multiplication of ``O(MN)`` cost. But the representation \n```math \n\tt_{NM} = \\Pi_N I_M f \n```\ngives us a clue for an even faster O(M \\log M) algorithm: \n* Compute ``I_M f`` via the FFT; ``O(M \\log M)`` operations\n* Obtain ``\\Pi_N I_M f`` by only retaining the coefficients ``k = -N, \\dots, N``; ``O(N)`` operations.\n\"\"\"\n\n# ╔═╡ 69fa7e00-90ae-11eb-0681-2d9295ae5368\nbegin\n\tfunction approxL2proj(f, N, M)\n\t\t# generate the sample points\n\t\tX = range(0, 2π - π/M, length = 2M)\n\t\t# the k-grid we obtain from the\n\t\t# degree-M trigonometric interpolant\n\t\tKm = [0:M; -M+1:-1]\n\t\t# contruc the trigonometric interpolant I_M f\n\t\tF̂m = fft(f.(X)) / (2M)\n\t\t# and find the subset defining Π_N I_M f\n\t\tF̂n = [ F̂m[1:N+1]; F̂m[end-N+1:end] ]\n\tend \n\t\n\tL2err(f, F̂; xerr = range(0, 2π, length=31 * length(F̂))) = \n\t\tsqrt( sum(abs2, f.(xerr) - trigprojeval.(xerr, Ref(F̂))) / length(xerr) )\n\t\t\t\t\nend\n\n# ╔═╡ e3315558-90b5-11eb-3510-e327a6c2d209\nmd\"\"\"\nWe are now ready to run some numerical tests to confirm our theory. We pick two examples from Lecture 1: \n```math\n\\begin{aligned}\nf_4(x) &= |\\sin(2x)|^3 \\\\\nf_7(x) &= \\frac{1}{1 + 10*\\sin(x)^2} \\\\\n\\end{aligned}\n```\nIn truth there is little to explore here, the lsq solutions perform extremely well, even for a low number of training points. Indeed, the trigonometric interpolant itself already comes surprisingly close to the ``L^2``-best approximation. But let us remember that this was just a warm-up case!\n\"\"\"\n\n# ╔═╡ 8bd7b6fe-91d1-11eb-2d14-134257fa2878\nbegin\n\tf4(x) = abs(sin(x))^3\n\tf7(x) = 1 / (1.0 + 10*sin(x)^2)\n\tflabels = [L\"f_4\", L\"f_7\"]\nend;\n\n# ╔═╡ 7f9b5750-91d2-11eb-32ee-6dc5b74d9c0e\nlet f = f7, NN = 5:5:60, MM = 2*NN\n\terr = [ L2err(f, approxL2proj(f, N, M)) for (N, M) in zip(NN, MM) ]\n\tplot(NN, err, lw=3, label = L\"f_7\", \n\t\t xlabel = L\"N\", ylabel = L\"\\Vert f - \\Pi_{NM} f \\Vert_{L^2}\", \n\t\t yscale = :log10, size = (350, 230), title = L\"f_7~~{\\rm analytic}\")\n\tplot!(NN[4:8], exp.(- 1/sqrt(10) * NN[4:8]), lw=2, c=:black, ls = :dash, label = \"\")\nend \n\n# ╔═╡ 879bf380-91d5-11eb-0b46-85b15d8b2826\nlet f = f4, NN = (2).^(3:10), MM = 2 * NN\n\terr = [ L2err(f, approxL2proj(f, N, M)) for (N, M) in zip(NN, MM) ]\n\tplot(NN, err, lw=3, label = L\"f_4\", \n\t\t xlabel = L\"N\", ylabel = L\"\\Vert f - \\Pi_{NM} f \\Vert_{L^2}\", \n\t\t xscale = :log10, yscale = :log10, size = (350, 200), \n\t\t title = L\"f_4 \\in C^{2,1}\")\n\tplot!(NN[4:end], NN[4:end].^(-3.5), lw=2, c=:black, ls = :dash, label = \"\")\nend \n\n# ╔═╡ 8b7e2280-8e87-11eb-0448-9f3a5acf6032\nmd\"\"\"\n\n## §3.3 Random training points\n\nWe now return to the case we experimented with at the beginning of this lecture, choose ``x_m \\sim U([0, 2\\pi])``, iid. While this appears to be a natural choice of random samples, specific applications might lead to different choices. However, it is crucial here. The reason is the following: \n\nWe are trying to approximate \n```math\n\tf(x) \\approx \\sum_k c_k B_k(x)\n```\nwhere ``B_k`` is a basis of function on ``[0, 2\\pi]``. Suppose we sample ``x_m \\sim \\rho dx`` where ``\\rho`` is a general probability density on ``[0, 2\\pi]``. The following theory requires that ``\\{B_k\\}`` is an orthonormal basis with respect to that measure, i.e., \n```math\n\t\\int_{0}^{2\\pi} B_k(x) B_{l}(x) \\rho(x) dx = \\delta_{kl}\n```\nSince the trigonometric polynomial basis is orthonormal w.r.t. the standard ``L^2``-inner product, i.e., ``\\rho(x) = 1/(2\\pi)`` we will also sample with respect to that measure. \n\nIf ``x_m`` are distributed according to a different distribution then we need to adjust our basis. We can explore this in the assignment. \n\"\"\"\n\n# ╔═╡ d8a55fd0-91dc-11eb-033c-0b10126c5ac7\nmd\"\"\"\nThe following results are taken from \n\n\tAlbert Cohen, Mark A Davenport, and Dany Leviatan. On the stability and accuracy of least squares approximations. Found. Comut. Math., 13(5):819–834, October 2013.\n\nOur first result states stability of the least squares system with high probability:\n\n**Theorem [Stability]:** Let ``x_m \\sim U(0, 2\\pi)``, idd, and ``A_{mk} = e^{i k x_m}`` then \n```math\n\t\\mathbb{P}\\big[ \\| A^* A - I \\|_{\\rm op} \\geq 1/2 \\big] \n\t\\leq 2 N \\exp\\big( - 0.1 M N^{-1} \\big)\n```\nThis result is readily interpreted: if ``M \\gg N`` then the normal equations are well-conditioned with high probability. In particular this also means that the design matrix ``A`` has full rank and that its ``R``-factor is also well-conditioned.\n\nThe second result states a resulting near best approximation error estimate: \n\n**Theorem [Error]:** Let ``x_m \\sim U(0, 2\\pi)``, iid and let ``t_{NM}`` denote the resulting degree ``N`` least squares approximant. There exists a constant ``c`` such that, if \n```math\n\tN \\leq \\frac{c}{1+r} \\frac{M}{\\log M} \n```\nthen \n```math\n\t\\mathbb{E}\\big[ \\| f - t_{NM} \\|_{L^2}^2 \\big] \n\t\\leq\n\t(1+o(M)) \\|f - \\Pi_N f \\|_{L^2}^2 + 2 \\| f \\|_{L^\\infty}^2 M^{-r}.\n```\n\nSimilarly as in our introductory example, this result gives us a best-approximation error up to an additional term that depends on how many training points we are given. To properly appreciate it we can show that it implies the following result: \n\"\"\"\n\n# ╔═╡ fb0081a6-91df-11eb-00a9-a9deb7581813\nmd\"\"\"\n* If ``f`` is continuous(ly differentiable) but not analytic then we expect that ``\\|f - \\Pi_N f \\|_{L^2} \\approx N^{-q}`` for some ``q``. In this case, choosing ``M \\geq c N \\log N`` with any ``c > `` we obtain that ``M^{-r} \\lesssim (N \\log N)^{-r} \\ll N^{-q}``, i.e., \n```math \n\t\\mathbb{E}\\big[ \\| f - t_{NM} \\|_{L^2}^2 \\big]  \\lesssim N^{-q}.\n```\n\n* If ``f`` is analytic then this is a little trickier: the idea is to choose ``N = c (M / \\log M)^a`` for some ``a > 0`` which leads to ``r = c' (M / \\log M)^{1-a}`` and hence \n```math\n\tM^{-r} = \\exp\\Big( - r \\log M \\Big) = \n\t\\exp\\Big( - c' M^{1-a} (\\log M)^{a} \\Big)\n```\nTo ensure this scales the same as \n```math\n\t\\rho^{-N} = e^{-\\alpha N} = \\exp\\Big( - \\alpha c (M/\\log M)^a \\Big)\n``` \nwe must choose ``1-a = a`` i.e. ``a = 1/2``. That is, we obtain that for a suitable choice of ``c``, and ``N = c (M / \\log M)^{1/2}`` we recover the optimal rate \n```math\n\t\\mathbb{E}\\big[ \\| f - t_{NM} \\|_{L^2}^2 \\big] \\lesssim \\rho^{-N}.\n```\n\"\"\"\n\n# ╔═╡ 97a2f8fe-91e0-11eb-2721-9395f949cc48\nmd\"\"\"\nLet us again test these predictions numerically.\n\"\"\"\n\n# ╔═╡ b44e273a-91e0-11eb-1b99-3b20b207513d\nbegin \n\tfunction lsqfit_rand(f::Function, N::Integer, M::Integer) \n\t\tX = 2*π*rand(M)\n\t\treturn lsqfit(X, f.(X), N) \n\tend \n\n\tL2err_rand(f, N, M; xerr = range(0, 2π, length=31*M)) = \n\t\tsqrt( sum(abs2, f.(xerr) - trigprojeval.(xerr, Ref(lsqfit_rand(f, N, M)))) / (2*M) )\nend\n\n# ╔═╡ c479ca34-91e1-11eb-191e-2b8d5f2e8211\nlet f = f4, NN = (2).^(3:9), MM1 = 2 * NN .+ 1,\n\t\t\t\t\t\t     MM2 = 3 * NN, \n\t\t\t\t\t\t\t MM3 = 2 * ceil.(Int, NN .* log.(NN))\n\t\n\terr1 = L2err_rand.(f, NN, MM1)\n\terr2 = L2err_rand.(f, NN, MM2)\n\terr3 = L2err_rand.(f, NN, MM3)\n\tplot(NN, err1, lw=2, label = L\"M = 2N + 1\", \n\t\t xlabel = L\"N\", ylabel = L\"\\Vert f - \\Pi_{NM} f \\Vert_{L^2}\", \n\t\t xscale = :log10, yscale = :log10, size = (450, 250), \n\t\t title = L\"f_4 \\in C^{2,1}\", legend = :outertopright)\n\tplot!(NN, err2, lw=2, label = L\"M = 3N\")\n\tplot!(NN, err3, lw=2, label = L\"M = 2N \\log N\")\t\t\n\tplot!(NN[4:end], NN[4:end].^(-3.5), lw=2, c=:black, ls = :dash, label = \"\")\nend \n\n# ╔═╡ 96329376-91e0-11eb-0c0e-5f80723255f8\nlet f = f7, NN = 5:5:40, MM1 = 2 * NN .+ 1,\n\t\t\t\t\t\tMM2 = 3*NN,  \n\t\t\t\t\t\tMM3 = 2 * ceil.(Int, NN.^1.5)\n\terr1 = L2err_rand.(f, NN, MM1)\n\terr2 = L2err_rand.(f, NN, MM2)\n\terr3 = L2err_rand.(f, NN, MM3)\n\tplot(NN, err1, lw=2, label = L\"M = 2N + 1\", \n\t\t xlabel = L\"N\", ylabel = L\"\\Vert f - \\Pi_{NM} f \\Vert_{L^2}\", \n\t\t yscale = :log10, size = (450, 250), \n\t\t title = L\"f_7 ~~{\\rm analytic}\", legend = :outertopright)\n\tplot!(NN, err2, lw=2, label = L\"M = 3N\")\n\tplot!(NN, err3, lw=2, label = L\"M = 2 N^{3/2}\")\t\t\n\tplot!(NN[4:end], exp.(-1/sqrt(10) * NN[4:end]), lw=2, c=:black, ls = :dash, label = \"\")\nend \n\n# ╔═╡ 20b6fcfe-93f2-11eb-1b8d-852aeb86d4f8\nmd\"\"\"\nIn this final example we see a clear gap between theory and practise. Is it just pre-asyptotics? Something about this specific example? Maybe the theory isn't sharp? Or maybe the specific function we are considering has additional properties?\n\"\"\"\n\n# ╔═╡ d9a37ca0-9b46-42b4-84ac-e012a8ec4b1e\nmd\"\"\"\n\n## Regularisation (If we have time?)\n\n\n\n\"\"\"\n\n# ╔═╡ 60c2146e-d85c-435d-9262-c5dbc52fcd00\nmd\"\"\"\nLet us extend our problem from the start of the lecture: \n\nData $M$: $(@bind _Mr Slider(10:10:500; show_value=true))\n\nDegree $N$: $(@bind _Nr Slider(5:100; show_value=true))\n\nNoise $\\eta = 10^{p}$; choose $p$: $(@bind _pr Slider(-5:0; show_value=true))\n\nRegularisation $\\lambda = 10^q$; choose $q$: $(@bind _qr Slider(-10:0.1:10; show_value=true))\n\"\"\"\n\n# ╔═╡ 89f791bf-c1ff-40a7-a4ce-66b5539efccd\nbegin\n\tfunction reglsqfit(X, F, N, Γ)\n\t\tA = [ designmatrix(X, N); Γ ]\n\t\treturn qr(A) \\ [F; zeros(size(A, 2))]   # this performs the  R \\ (Q' * F) for us\n\tend\nend\n\n# ╔═╡ 18c034eb-fa16-486c-8415-46858d17f274\nlet N = _Nr, M = _Mr, σ = 10.0^(_pr), λ = 10.0^(_qr), f = x -> 1 / (1 + exp(10*sin(x)))\n\tRandom.seed!(2) # make sure we always produce the same random points\n\tif M < 2*N+1\n\t\tM = 2*N+1\n\t\tmsg = \"M must be >= 2N+1\"\n\tend\n\tX = 2*π * rand(M)\n\tF = f.(X) + σ * randn(length(X))\n\tc = lsqfit(X, F, N)\n\tcr = reglsqfit(X, F, N, λ*I)\n\t# cr = reglsqfit(X, F, N, λ * Diagonal((kgridproj(N)).^2))\n\txp = range(0, 2π, length = 200)\n\tplot(xp, f.(xp), lw=4, label = L\"f\", size = (450, 200),\n\t\t\ttitle = \"N = $N, M = $M\",\n\t\t    ylims = [-0.3, 1.3], legend = :outertopright)\n\tplot!(xp, trigprojeval.(xp, Ref(c)), lw=2, label = \"fit\")\n\tplot!(xp, trigprojeval.(xp, Ref(cr)), lw=2, label = \"regfit\")\n\tplot!(X, F, lw=0, ms=2, m=:o, c=:black, label = \"\")\nend\n\n# ╔═╡ 4d98a913-c17d-4d9c-9708-5be743a4b944\nmd\"\"\"\nA more quantitative approach: fit to a training set, but then measure error on a test set. \n\"\"\"\n\n# ╔═╡ 73e88b3f-ed14-4919-bf61-a8b77510f7f9\nmd\"\"\"\nData $M$: $(@bind _Mr2 Slider(10:10:500; show_value=true))\n\nDegree $N$: $(@bind _Nr2 Slider(5:100; show_value=true))\n\nNoise $\\eta = 10^{p}$; choose $p$: $(@bind _pr2 Slider(-5:0; show_value=true))\n\"\"\"\n\n# ╔═╡ 2fcce329-1ed3-4681-b571-b5d4c544dbf5\nlet N = _Nr2, M = _Mr2, σ = 10.0^(_pr2), f = x -> 1 / (1 + exp(10*sin(x)))\n\t\n\tRandom.seed!(2) # make sure we always produce the same random points\n\tXtrain = 2*π * rand(M)\n\tFtrain = f.(Xtrain) + σ * randn(M)\n\tXtest = 2*π * rand(M)   # this is atypical, normally we have fewer test points \n\tFtest = f.(Xtest)\n\t\n\tfunction testrmse(λ) \n\t\tcr = reglsqfit(Xtrain, Ftrain, N, λ * Diagonal((kgridproj(N)).^2))\n\t\tfit = trigprojeval.(Xtrain, Ref(cr))\n\t\tprediction = trigprojeval.(Xtest, Ref(cr))\n\t\trmsetest = norm(prediction - Ftest) / sqrt(length(Ftest))\n\t\trmsetrain = norm(fit - Ftrain) / sqrt(length(Ftrain))\n\t\treturn rmsetest, rmsetrain \n\tend\n\t\n\tLAM = 0.1.^(-3:.1:10)\n\tRMSE = testrmse.(LAM)\n\tRMSE_test = getindex.(RMSE, 1)\n\tRMSE_train = getindex.(RMSE, 2)\n\tplot(LAM, RMSE_train, lw = 3, label = \"train\",\n\t\t\txscale = :log10, yscale = :log10, size = (350, 250),\n\t\t\tlegend = :bottomright)\n\tplot!(LAM, RMSE_test, lw = 3, label = \"test\")\nend\n\n# ╔═╡ 76f189b8-93f2-11eb-259d-d52fea279464\nmd\"\"\"\n\n## Outlook: Algebraic Polynomials\n\nConsider a non-periodic version of our favourite example \n```math\n\tf(x) = \\frac{1}{1 + x^2}, \\qquad x \\in [-1, 1].\n```\nSince we are no longer on a periodic domain, let us use algebraic instead of trigonometric polynomials to approximate it, i.e. we seek a polynomial \n```math\np(x) = \\sum_{n = 0}^N c_n x^n\n```\nsuch that ``p \\approx f`` in ``[-1,1]``. Analogously as for trigonometric polynomials, we could try to determine the coefficients via interpolation, \n```math\n\tp(x_n) = f(x_n),  \\qquad x_n = -1 + 2n/N, \\qquad n = 0, \\dots, N. \n```\nhere with equispaced nodes. \n\nThis is a bad idea: \n\"\"\"\n\n# ╔═╡ e611030a-93f2-11eb-3581-1b3f4b41360a\n# Implementation of Runge example \nlet f = x -> 1/(1+25*x^2), NN1 = [5, 8, 10], NN2 =  5:5:30\n\tfunction poly_fit(N)\n\t\t# this is numerically unstable - do not do this!!! \n\t\t# we will learn in the next lecture how to do stable numerical interpolation\n\t\tA = [   (-1 + 2*m/N)^n  for m = 0:N, n = 0:N ]\n\t\tF = [ f((-1 + 2*m/N)) for m = 0:N ]\n\t\treturn A \\ F \n\tend\n\t# do not do this either, it is neither efficient nor stable!\n\tpoly_eval(x, c) = sum( c[n] * x^(n-1) for n = 1:length(c) )\n\t\n\t# first plot \n\txp = range(-1, 1, length=300)\n\tP1 = plot(xp, f.(xp); lw=4, label = \"exact\",\n\t\t\t  size = (400, 400), xlabel = L\"x\")\n\tfor (iN, N) in enumerate(NN1)\n\t\txi = [(-1 + 2*m/N) for m = 0:N]\n\t\tc = poly_fit(N)\n\t\tplot!(P1, xp, poly_eval.(xp, Ref(c)), c = iN+1, lw=2,label = L\"p_{%$(N)}\")\n\t\tplot!(P1, xi, f.(xi), lw=0, c = iN+1, m = :o, ms=3, label = \"\")\n\tend \n\t\n\t# second plot \n\txerr = range(-1, 1, length=3_000)\n\terr = [ norm( f.(xerr) - poly_eval.(xerr, Ref(poly_fit(N))), Inf )\n\t\t\tfor N in NN2 ]\n\tP2 = plot(NN2, err, lw = 3, label = L\"\\Vert f - I_N f \\Vert\", \n\t\t\t  yscale = :log10, xlabel = L\"N\", legend = :topleft)\n\tplot(P1, P2, size = (600, 300), title = \"Witch of Agnesi\")\nend\n\n# ╔═╡ 530b2eb6-93f5-11eb-2c54-6317369a6b21\nmd\"\"\"\nNext lecture will cover a range of \"random topics\" that I won't cover in much (or any) depth but which are both fun and important to have seen once. The first of these will be to explain how all our ideas from trigonometric approximation do carry over to algebraic approximation as long as we take the right perspective. \n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nBenchmarkTools = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\nDataFrames = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nFFTW = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nForwardDiff = \"f6369f11-7733-5829-9624-2563aa707210\"\nLaTeXStrings = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nPrettyTables = \"08abe8d2-0d0c-5749-adfa-8a2ac140af0d\"\nPrintf = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\nRandom = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[compat]\nBenchmarkTools = \"~1.3.1\"\nDataFrames = \"~1.3.2\"\nFFTW = \"~1.4.6\"\nForwardDiff = \"~0.10.25\"\nLaTeXStrings = \"~1.3.0\"\nPlots = \"~1.26.0\"\nPlutoUI = \"~0.7.37\"\nPrettyTables = \"~1.3.1\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\njulia_version = \"1.7.2\"\nmanifest_format = \"2.0\"\n\n[[deps.AbstractFFTs]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"6f1d9bc1c08f9f4a8fa92e3ea3cb50153a1b40d4\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"1.1.0\"\n\n[[deps.AbstractPlutoDingetjes]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"8eaf9f1b4921132a4cff3f36a1d9ba923b14a481\"\nuuid = \"6e696c72-6542-2067-7265-42206c756150\"\nversion = \"1.1.4\"\n\n[[deps.Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"af92965fb30777147966f58acb05da51c5616b5f\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.3\"\n\n[[deps.ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[deps.Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[deps.Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[deps.BenchmarkTools]]\ndeps = [\"JSON\", \"Logging\", \"Printf\", \"Profile\", \"Statistics\", \"UUIDs\"]\ngit-tree-sha1 = \"4c10eee4af024676200bc7752e536f858c6b8f93\"\nuuid = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\nversion = \"1.3.1\"\n\n[[deps.Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[deps.Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"4b859a208b2397a7a623a03449e4636bdb17bcf2\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+1\"\n\n[[deps.ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"c9a6160317d1abe9c44b3beb367fd448117679ca\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.13.0\"\n\n[[deps.ChangesOfVariables]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"bf98fa45a0a4cee295de98d4c1462be26345b9a1\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.2\"\n\n[[deps.ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"12fc73e5e0af68ad3137b886e3f7c1eacfca2640\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.17.1\"\n\n[[deps.ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[deps.Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[deps.CommonSubexpressions]]\ndeps = [\"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"7b8a93dba8af7e3b42fecabf646260105ac373f7\"\nuuid = \"bbf7d656-a473-5ed7-a52c-81e309532950\"\nversion = \"0.3.0\"\n\n[[deps.Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"96b0bc6c52df76506efc8a441c6cf1adcb1babc4\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.42.0\"\n\n[[deps.CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[deps.Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[deps.Crayons]]\ngit-tree-sha1 = \"249fe38abf76d48563e2f4556bebd215aa317e15\"\nuuid = \"a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f\"\nversion = \"4.1.1\"\n\n[[deps.DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[deps.DataFrames]]\ndeps = [\"Compat\", \"DataAPI\", \"Future\", \"InvertedIndices\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"Markdown\", \"Missings\", \"PooledArrays\", \"PrettyTables\", \"Printf\", \"REPL\", \"Reexport\", \"SortingAlgorithms\", \"Statistics\", \"TableTraits\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"ae02104e835f219b8930c7664b8012c93475c340\"\nuuid = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nversion = \"1.3.2\"\n\n[[deps.DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"3daef5523dd2e769dad2365274f760ff5f282c7d\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.11\"\n\n[[deps.DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[deps.Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[deps.DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[deps.DiffResults]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"c18e98cba888c6c25d1c3b048e4b3380ca956805\"\nuuid = \"163ba53b-c6d8-5494-b064-1a9d43ac40c5\"\nversion = \"1.0.3\"\n\n[[deps.DiffRules]]\ndeps = [\"IrrationalConstants\", \"LogExpFunctions\", \"NaNMath\", \"Random\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"dd933c4ef7b4c270aacd4eb88fa64c147492acf0\"\nuuid = \"b552c78f-8df3-52c6-915a-8e097449b14b\"\nversion = \"1.10.0\"\n\n[[deps.Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[deps.DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[deps.Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[deps.EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[deps.Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ae13fcbc7ab8f16b0856729b050ef0c446aa3492\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.4.4+0\"\n\n[[deps.FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[deps.FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[deps.FFTW]]\ndeps = [\"AbstractFFTs\", \"FFTW_jll\", \"LinearAlgebra\", \"MKL_jll\", \"Preferences\", \"Reexport\"]\ngit-tree-sha1 = \"505876577b5481e50d089c1c68899dfb6faebc62\"\nuuid = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nversion = \"1.4.6\"\n\n[[deps.FFTW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea\"\nuuid = \"f5851436-0d7a-5f13-b9de-f02708fd171a\"\nversion = \"3.3.10+0\"\n\n[[deps.FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[deps.Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[deps.Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[deps.ForwardDiff]]\ndeps = [\"CommonSubexpressions\", \"DiffResults\", \"DiffRules\", \"LinearAlgebra\", \"LogExpFunctions\", \"NaNMath\", \"Preferences\", \"Printf\", \"Random\", \"SpecialFunctions\", \"StaticArrays\"]\ngit-tree-sha1 = \"1bd6fc0c344fc0cbee1f42f8d2e7ec8253dda2d2\"\nuuid = \"f6369f11-7733-5829-9624-2563aa707210\"\nversion = \"0.10.25\"\n\n[[deps.FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[deps.FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[deps.Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[deps.GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"51d2dfe8e590fbd74e7a842cf6d13d8a2f45dc01\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.6+0\"\n\n[[deps.GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"RelocatableFolders\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"9f836fb62492f4b0f0d3b06f55983f2704ed0883\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.64.0\"\n\n[[deps.GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"a6c850d77ad5118ad3be4bd188919ce97fffac47\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.64.0+0\"\n\n[[deps.GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"83ea630384a13fc4f002b77690bc0afeb4255ac9\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.2\"\n\n[[deps.Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[deps.Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"a32d672ac2c967f3deb8a81d828afc739c838a06\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+2\"\n\n[[deps.Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[deps.Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[deps.HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"0fa77022fe4b511826b39c894c90daf5fce3334a\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.17\"\n\n[[deps.HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"129acf094d168394e80ee1dc4bc06ec835e510a3\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+1\"\n\n[[deps.Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[deps.HypertextLiteral]]\ngit-tree-sha1 = \"2b078b5a615c6c0396c77810d92ee8c6f470d238\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.3\"\n\n[[deps.IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[deps.IniFile]]\ngit-tree-sha1 = \"f550e6e32074c939295eb5ea6de31849ac2c9625\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.1\"\n\n[[deps.IntelOpenMP_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d979e54b71da82f3a65b62553da4fc3d18c9004c\"\nuuid = \"1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0\"\nversion = \"2018.0.3+2\"\n\n[[deps.InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[deps.InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"91b5dcf362c5add98049e6c29ee756910b03051d\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.3\"\n\n[[deps.InvertedIndices]]\ngit-tree-sha1 = \"bee5f1ef5bf65df56bdd2e40447590b272a5471f\"\nuuid = \"41ab1584-1d38-5bbf-9106-f11c6c58b48f\"\nversion = \"1.1.0\"\n\n[[deps.IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[deps.IterTools]]\ngit-tree-sha1 = \"fa6287a4469f5e048d763df38279ee729fbd44e5\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.4.0\"\n\n[[deps.IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[deps.JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"abc9885a7ca2052a736a600f7fa66209f96506e1\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.4.1\"\n\n[[deps.JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"3c837543ddb02250ef42f4738347454f95079d4e\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.3\"\n\n[[deps.JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b53380851c6e6664204efb2e62cd24fa5c47e4ba\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.2+0\"\n\n[[deps.LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[deps.LERC_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"bf36f528eec6634efc60d7ec062008f171071434\"\nuuid = \"88015f11-f218-50d7-93a8-a6af411a945d\"\nversion = \"3.0.0+1\"\n\n[[deps.LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[deps.LaTeXStrings]]\ngit-tree-sha1 = \"f2355693d6778a178ade15952b7ac47a4ff97996\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.3.0\"\n\n[[deps.Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"4f00cc36fede3c04b8acf9b2e2763decfdcecfa6\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.13\"\n\n[[deps.LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[deps.LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[deps.LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[deps.LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[deps.LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[deps.Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[deps.Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"0b4a5d71f3e5200a7dff793393e09dfc2d874290\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+1\"\n\n[[deps.Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[deps.Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[deps.Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[deps.Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[deps.Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[deps.Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"LERC_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"c9551dd26e31ab17b86cbd00c2ede019c08758eb\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+1\"\n\n[[deps.Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[deps.LinearAlgebra]]\ndeps = [\"Libdl\", \"libblastrampoline_jll\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[deps.LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"3f7cb7157ef860c637f3f4929c8ed5d9716933c6\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.7\"\n\n[[deps.Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[deps.MKL_jll]]\ndeps = [\"Artifacts\", \"IntelOpenMP_jll\", \"JLLWrappers\", \"LazyArtifacts\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e595b205efd49508358f7dc670a940c790204629\"\nuuid = \"856f044c-d86e-5d09-b602-aeab76dc8ba7\"\nversion = \"2022.0.0+0\"\n\n[[deps.MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[deps.Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[deps.MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[deps.MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[deps.Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[deps.Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[deps.Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[deps.MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[deps.NaNMath]]\ngit-tree-sha1 = \"b086b7ea07f8e38cf122f5016af580881ac914fe\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.7\"\n\n[[deps.NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[deps.Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"887579a3eb005446d514ab7aeac5d1d027658b8f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+1\"\n\n[[deps.OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[deps.OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[deps.OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"648107615c15d4e09f7eca16307bc821c1f718d8\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.13+0\"\n\n[[deps.OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[deps.Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[deps.OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[deps.PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[deps.Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"85b5da0fa43588c75bb1ff986493443f821c70b7\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.2.3\"\n\n[[deps.Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[deps.Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[deps.PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[deps.PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"6f1b25e8ea06279b5689263cc538f51331d7ca17\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.1.3\"\n\n[[deps.Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\", \"UnicodeFun\", \"Unzip\"]\ngit-tree-sha1 = \"23d109aad5d225e945c813c6ebef79104beda955\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.26.0\"\n\n[[deps.PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"ColorTypes\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"bf0a1121af131d9974241ba53f601211e9303a9e\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.37\"\n\n[[deps.PooledArrays]]\ndeps = [\"DataAPI\", \"Future\"]\ngit-tree-sha1 = \"db3a23166af8aebf4db5ef87ac5b00d36eb771e2\"\nuuid = \"2dfb63ee-cc39-5dd5-95bd-886bf059d720\"\nversion = \"1.4.0\"\n\n[[deps.Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"de893592a221142f3db370f48290e3a2ef39998f\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.4\"\n\n[[deps.PrettyTables]]\ndeps = [\"Crayons\", \"Formatting\", \"Markdown\", \"Reexport\", \"Tables\"]\ngit-tree-sha1 = \"dfb54c4e414caa595a1f2ed759b160f5a3ddcba5\"\nuuid = \"08abe8d2-0d0c-5749-adfa-8a2ac140af0d\"\nversion = \"1.3.1\"\n\n[[deps.Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[deps.Profile]]\ndeps = [\"Printf\"]\nuuid = \"9abbd945-dff8-562f-b5e8-e1ebf5ef1b79\"\n\n[[deps.Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[deps.REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[deps.Random]]\ndeps = [\"SHA\", \"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[deps.RecipesBase]]\ngit-tree-sha1 = \"6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.2.1\"\n\n[[deps.RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"995a812c6f7edea7527bb570f0ac39d0fb15663c\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.5.1\"\n\n[[deps.Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[deps.RelocatableFolders]]\ndeps = [\"SHA\", \"Scratch\"]\ngit-tree-sha1 = \"cdbd3b1338c72ce29d9584fdbe9e9b70eeb5adca\"\nuuid = \"05181044-ff0b-4ac5-8273-598c1e38db00\"\nversion = \"0.1.3\"\n\n[[deps.Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.3.0\"\n\n[[deps.SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[deps.Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[deps.Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[deps.SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[deps.Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[deps.Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[deps.SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[deps.SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[deps.SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"5ba658aeecaaf96923dce0da9e703bd1fe7666f9\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"2.1.4\"\n\n[[deps.StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"74fb527333e72ada2dd9ef77d98e4991fb185f04\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.4.1\"\n\n[[deps.Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[deps.StatsAPI]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"c3d8ba7f3fa0625b062b82853a7d5229cb728b6b\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.2.1\"\n\n[[deps.StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"8977b17906b0a1cc74ab2e3a05faa16cf08a8291\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.16\"\n\n[[deps.StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"57617b34fa34f91d536eb265df67c2d4519b8b98\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.5\"\n\n[[deps.TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[deps.TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[deps.Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"OrderedCollections\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"5ce79ce186cc678bbb5c5681ca3379d1ddae11a1\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.7.0\"\n\n[[deps.Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[deps.Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[deps.URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[deps.UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[deps.Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[deps.UnicodeFun]]\ndeps = [\"REPL\"]\ngit-tree-sha1 = \"53915e50200959667e78a92a418594b428dffddf\"\nuuid = \"1cfade01-22cf-5700-b092-accc4b62d6e1\"\nversion = \"0.4.1\"\n\n[[deps.Unzip]]\ngit-tree-sha1 = \"34db80951901073501137bdbc3d5a8e7bbd06670\"\nuuid = \"41fe7b60-77ed-43a1-b4f0-825fd5a5650d\"\nversion = \"0.1.2\"\n\n[[deps.Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[deps.Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4528479aa01ee1b3b4cd0e6faef0e04cf16466da\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.25.0+0\"\n\n[[deps.XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[deps.XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[deps.Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[deps.Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[deps.Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[deps.Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[deps.Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[deps.Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[deps.Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[deps.Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[deps.Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[deps.Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[deps.Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[deps.Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[deps.Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[deps.Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[deps.Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[deps.Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[deps.Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[deps.Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[deps.Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[deps.Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[deps.Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e45044cd873ded54b6a5bac0eb5c971392cf1927\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.2+0\"\n\n[[deps.libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[deps.libblastrampoline_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"OpenBLAS_jll\"]\nuuid = \"8e850b90-86db-534c-a0d3-1478176c7d93\"\n\n[[deps.libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[deps.libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[deps.libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"b910cb81ef3fe6e78bf6acee440bda86fd6ae00c\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+1\"\n\n[[deps.nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[deps.p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[deps.x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[deps.x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[deps.xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─74479a7e-8c34-11eb-0e09-73f47f8013bb\n# ╟─8728418e-8c34-11eb-3313-c52ecadbf252\n# ╟─9202b69e-9013-11eb-02a2-2f1c8e2fcc0c\n# ╟─73983438-8c51-11eb-3142-03410d610022\n# ╠═d08fb928-8c53-11eb-3c35-574ef188de6b\n# ╟─fc8495a6-8c50-11eb-14ac-4dbad6baa3c3\n# ╟─1ba8aa58-8c51-11eb-2d66-775d0fd31747\n# ╠═3d14680a-98df-42e2-9734-8a5ba27f5f6d\n# ╟─48175a0c-8e87-11eb-0f42-e9ca0f676e87\n# ╟─e6cf2c86-9043-11eb-04a7-f1367ad64b6b\n# ╟─82d74ec2-92a1-11eb-0d58-4bb674a8640e\n# ╟─879e9596-90a8-11eb-23d6-935e367eeb17\n# ╟─3abcfea6-92a2-11eb-061a-d9752403eff8\n# ╟─c4b66e46-90a7-11eb-199e-cded424c7020\n# ╠═69fa7e00-90ae-11eb-0681-2d9295ae5368\n# ╟─e3315558-90b5-11eb-3510-e327a6c2d209\n# ╠═8bd7b6fe-91d1-11eb-2d14-134257fa2878\n# ╠═7f9b5750-91d2-11eb-32ee-6dc5b74d9c0e\n# ╠═879bf380-91d5-11eb-0b46-85b15d8b2826\n# ╟─8b7e2280-8e87-11eb-0448-9f3a5acf6032\n# ╟─d8a55fd0-91dc-11eb-033c-0b10126c5ac7\n# ╟─fb0081a6-91df-11eb-00a9-a9deb7581813\n# ╟─97a2f8fe-91e0-11eb-2721-9395f949cc48\n# ╠═b44e273a-91e0-11eb-1b99-3b20b207513d\n# ╠═c479ca34-91e1-11eb-191e-2b8d5f2e8211\n# ╟─96329376-91e0-11eb-0c0e-5f80723255f8\n# ╟─20b6fcfe-93f2-11eb-1b8d-852aeb86d4f8\n# ╟─d9a37ca0-9b46-42b4-84ac-e012a8ec4b1e\n# ╟─60c2146e-d85c-435d-9262-c5dbc52fcd00\n# ╠═89f791bf-c1ff-40a7-a4ce-66b5539efccd\n# ╠═18c034eb-fa16-486c-8415-46858d17f274\n# ╟─4d98a913-c17d-4d9c-9708-5be743a4b944\n# ╟─73e88b3f-ed14-4919-bf61-a8b77510f7f9\n# ╠═2fcce329-1ed3-4681-b571-b5d4c544dbf5\n# ╟─76f189b8-93f2-11eb-259d-d52fea279464\n# ╟─e611030a-93f2-11eb-3581-1b3f4b41360a\n# ╟─530b2eb6-93f5-11eb-2c54-6317369a6b21\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "5875b52b9d61b1f36792e3f22f2a26a291811853", "size": 62570, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "pluto/ata_03_lsq.jl", "max_stars_repo_name": "cortner/ApxThyApp", "max_stars_repo_head_hexsha": "0b28c5c4370eb4d9c5a9063c2c5c1b938aa54a3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-12T18:12:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T18:12:15.000Z", "max_issues_repo_path": "pluto/ata_03_lsq.jl", "max_issues_repo_name": "cortner/ApxThyApp", "max_issues_repo_head_hexsha": "0b28c5c4370eb4d9c5a9063c2c5c1b938aa54a3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-03T22:23:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T01:58:58.000Z", "max_forks_repo_path": "pluto/ata_03_lsq.jl", "max_forks_repo_name": "cortner/ApxThyApp", "max_forks_repo_head_hexsha": "0b28c5c4370eb4d9c5a9063c2c5c1b938aa54a3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7194835681, "max_line_length": 554, "alphanum_fraction": 0.7026849928, "num_tokens": 26849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8740772253241802, "lm_q1q2_score": 0.7514124994721518}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.20\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ c823a222-6e1c-11eb-18a8-01a1b673d7b0\nbegin\n\t#import Pkg; \n\t#Pkg.add(\"LinearAlgebra\")\t\n\t#Pkg.add(\"Random\")\n\t#Pkg.add(\"PlutoUI\")\n\t#Pkg.add(\"Plots\")\n\tusing LinearAlgebra\n\tusing Random\n\tusing Plots\n    using PlutoUI\n\tmd\"\"\" **0) import packages** \"\"\"\nend\n\n# ╔═╡ 53b7c092-6e9b-11eb-0fa7-57fc1385457c\nmd\"\n# _The Gaussian Process_\nGiven a vector of pivot points $\\boldsymbol x$,\nthe corresponding random vector  $\\boldsymbol y(\\boldsymbol x)$\nis drawn from a multivariate Gaussian \n\n$\\boldsymbol z \\sim {\\cal G}(\\mu,C)$\n\nwith zero mean $\\boldsymbol \\mu  = \\boldsymbol0$\nand a covariance with matrix elements: $C_{ij} = C(x_i,x_j)$.\n\n\n\nThe different Gaussian processes differ in the kernel function $C(x,y)$\n\n1) Straight line process: $C(x,y) = \\alpha \\cdot x\\cdot y$\n\n2) Wiener process: $C(x,y) = \\alpha * min(x, y)$\n\n3) Squared exponential kernel: $C(x,y) = \\alpha * \\exp(- \\frac{(x-y)^2}{\\sigma^2})$\n\n4) Ornstein-Uhlenbeck process: $C(x,y) = \\alpha * \\exp(- \\frac{|x-y|}{\\sigma})$\n\nGPs are magic ✨ \n\"\n\n# ╔═╡ 0ac101ba-6ecc-11eb-090e-6b5998c6bbfd\nmd\"\n## Setting up the mathematical details\n\"\n\n# ╔═╡ dca69d60-6e8c-11eb-3305-3fa2cedd5dac\nbegin\n\tNslide = 100\n\tL_𝛼  = [0 100 ; 0.01 20 ; 0.01 40 ; 0.1 10]\n\tL_𝜎 = [-1 -1; -1 -1; 0.1 20; 1 20]\n\tL_d_𝛼 = \t(L_𝛼[:,2]-L_𝛼[:,1])/Nslide\n\tL_d_𝜎 = \t(L_𝜎[:,2]-L_𝜎[:,1])/Nslide\n\tmd\"\"\"**2) range of parameters**\"\"\"\nend\n\n# ╔═╡ 1edc6c32-6e1d-11eb-2f8a-b9dd2aff7b99\nbegin\n\tL_x0 = [-25:0.5:25;]\n\tmd\"\"\" **3) pivot points** \"\"\"\nend\n\n# ╔═╡ 21cff596-6ecc-11eb-093c-f97fac9ab7cb\nmd\"\n## Try it out! \n\"\n\n# ╔═╡ 2837bf6e-6eb2-11eb-2b2a-190fa3669085\nmd\"\"\"\n**Choose a kernel:** $(@bind kernel Select([\"1\"=>\"Straight lines\",\"2\"=>\"Wiener process\",\"3\"=>\"Squared exponential\",\"4\"=>\"Ornstein-Uhlenbeck process\"]))\n\"\"\"\n\n# ╔═╡ 0bef3462-6e1d-11eb-08f6-e3b2c36a0721\n\nbegin\n\nif kernel == \"1\"\n\t\ttxt = \"Straight line\";\n\t\tL_x    = L_x0;\t\t\n\t\tK(x, y, 𝛼, sigma) = 𝛼 * x * y;\n\telseif kernel == \"2\"\n\t\ttxt = \"Wiener process\";\n\t\tL_x    = [x for x in L_x0 if x >= 0];\n\t\tK(x, y, 𝛼, sigma) = 𝛼 * min(x, y);\n\telseif kernel == \"3\"\n\t\ttxt = \"Squared exponential\";\n\t\tL_x    = L_x0;\n\t\tK(x, y, 𝛼, 𝜎) = 𝛼 * exp(- (x - y)^2/𝜎^2);\n\telseif kernel == \"4\"\n\t\ttxt = \"Ornstein-Uhlenbeck process\";\n\t\tL_x    = L_x0;\n\t\tK(x, y, 𝜶, 𝜎) = 𝜶 * exp(abs(x - y)/𝜎);\n\telse\n\t\terror(\"$(kernel) not supported\")\n\tend\t\n\tn = length(L_x);\n\tmd\"\"\"**1) kernel definitions**\"\"\"\nend\n\n# ╔═╡ bc5fc60a-6e92-11eb-0003-b58331ceddcf\nik = parse(Int32,kernel);\n\n# ╔═╡ 6be2bb7a-6eb6-11eb-2cfb-87383e68bf54\nmd\"\n**Specify the seed value of random number generator**  \n\n1 $(@bind seed Slider(1:1000)) 1000\n\"\n\n# ╔═╡ 05d7032c-6e25-11eb-0b48-7f9a594b5b88\nbegin\n\trng = MersenneTwister(seed)\n\tu = randn(rng,n, 1)\n\tmd\"\"\"**4) normal random vector zero mean, unit variance**\"\"\"\nend\n\n# ╔═╡ 4fdde52e-6e8b-11eb-3199-8112d143a31a\nmd\"\"\"\nThe seed you chose: $(seed)\n\"\"\"\n\n\n# ╔═╡ 431df5da-6eb4-11eb-11af-898fdf3601d5\n\tif L_𝜎[ik,2] > 0\n\t\tmd\"\"\"**Choose parameters 𝛼:**\n\t$(L_𝛼[ik,1]) $(@bind 𝛼 Slider(L_𝛼[ik,1]:L_d_𝛼[ik]:L_𝛼[ik,2])) $(L_𝛼[ik,2]) **and 𝜎:**\n\t\t$(L_𝜎[ik,1]) $(@bind 𝜎 Slider(L_𝜎[ik,1]:L_d_𝜎[ik]:L_𝜎[ik,2])) $(L_𝜎[ik,2])\n\t\t\"\"\"\n\telse\n\t\t𝜎 = L_𝜎[ik,2]\n\t\t\t\tmd\"\"\"**Choose parameter 𝛼:**\n\t$(L_𝛼[ik,1]) $(@bind 𝛼 Slider(L_𝛼[ik,1]:L_d_𝛼[ik]:L_𝛼[ik,2])) $(L_𝛼[ik,2]) \n\t\"\"\"\n\tend\n\n# ╔═╡ 2506c99c-6e1d-11eb-31a2-dd1b99a80d8a\nbegin\n\tC = [K(x, y, 𝛼, 𝜎) for x in L_x, y in L_x];\n\tF = svd(C);\n\tA = F.U * Diagonal(sqrt.(F.S));\t\n\tz = A * u;\n\tmd\"\"\" **5) sample from mvG** \"\"\"\nend\n\n\n# ╔═╡ ac913758-6e27-11eb-1649-37b1be855f5b\nif L_𝜎[ik,2] > 0\n\tmd\" \t𝛼 = $(𝛼),    𝜎 = $(𝜎)\t\t\"\nelse\n\tmd\" \t𝛼 = $(𝛼)\"\nend\n\n# ╔═╡ b3e26166-6e1e-11eb-1708-25be9e2a339f\nplot(\n    L_x,\n    z,\n\tline =(1,1,:line),\n    grid = true,\n    title = txt,\n    palette = :tab10,\n    legend = :none,\n    label = false,\n    marker = :cross,\n    xlabel = \"x\",\n    ylabel = \"y\",\n    ylim = (-20, 20),\n)\n\n# ╔═╡ Cell order:\n# ╟─53b7c092-6e9b-11eb-0fa7-57fc1385457c\n# ╟─0ac101ba-6ecc-11eb-090e-6b5998c6bbfd\n# ╟─c823a222-6e1c-11eb-18a8-01a1b673d7b0\n# ╟─0bef3462-6e1d-11eb-08f6-e3b2c36a0721\n# ╟─dca69d60-6e8c-11eb-3305-3fa2cedd5dac\n# ╟─1edc6c32-6e1d-11eb-2f8a-b9dd2aff7b99\n# ╟─05d7032c-6e25-11eb-0b48-7f9a594b5b88\n# ╟─2506c99c-6e1d-11eb-31a2-dd1b99a80d8a\n# ╟─21cff596-6ecc-11eb-093c-f97fac9ab7cb\n# ╟─2837bf6e-6eb2-11eb-2b2a-190fa3669085\n# ╟─bc5fc60a-6e92-11eb-0003-b58331ceddcf\n# ╟─6be2bb7a-6eb6-11eb-2cfb-87383e68bf54\n# ╟─4fdde52e-6e8b-11eb-3199-8112d143a31a\n# ╟─431df5da-6eb4-11eb-11af-898fdf3601d5\n# ╟─ac913758-6e27-11eb-1649-37b1be855f5b\n# ╟─b3e26166-6e1e-11eb-1708-25be9e2a339f\n", "meta": {"hexsha": "e37732fe5496b258a9179ad48c27255f3e6430b6", "size": 4903, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/gp.jl", "max_stars_repo_name": "fonsp/bayes-imoox", "max_stars_repo_head_hexsha": "bed7e40655a2912da56d338e4ce60af16dc1dd57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/gp.jl", "max_issues_repo_name": "fonsp/bayes-imoox", "max_issues_repo_head_hexsha": "bed7e40655a2912da56d338e4ce60af16dc1dd57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/gp.jl", "max_forks_repo_name": "fonsp/bayes-imoox", "max_forks_repo_head_hexsha": "bed7e40655a2912da56d338e4ce60af16dc1dd57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3930348259, "max_line_length": 195, "alphanum_fraction": 0.6330817867, "num_tokens": 2377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7514079145065834}}
{"text": "# A palindromic number reads the same both ways. The largest palindrome made\n# from the product of two 2-digit numbers is 9009 = 91 × 99.\n#\n# Find the largest palindrome made from the product of two 3-digit numbers.\n\nusing ProjectEulerSolutions\n\n# Treat numbers as strings and test by reversing them.\nfunction p004solution_string(n_digits::Integer=1)::Integer\n    testnums = sort(unique_products_of_ndigits(n_digits), rev=true)\n    for i in testnums\n        if ispalindrome_string(i)\n            return i\n        end\n    end\n    return 0\nend\n\n# Treat numbers as integers and test by reversing them using modulus and floor\n# to pull out individual digits.\nfunction p004solution_integer(n_digits::Integer=1)::Integer\n    testnums = sort(unique_products_of_ndigits(n_digits), rev=true)\n    for i in testnums\n        if ispalindrome(i)\n            return i\n        end\n    end\n    return 0\nend\n\n# Same as previous, but no initial list construction using list comprehension.\nfunction p004solution_integer_fast(n_digits::Integer=1)::Integer\n    maxnum = 10^n_digits - 1\n    minnum = 10^(n_digits - 1) # Can probably assume this can be larger\n    maxval = 0\n    for i in minnum:maxnum\n        for j in minnum:maxnum\n            if j > i && ispalindrome_integer(i*j)\n                maxval = max(maxval, i*j)\n            end\n        end\n    end\n    return maxval\nend\n\np004 = Problems.Problem(Dict(\"String reversal\" => p004solution_string,\n                             \"Integer math\" => p004solution_integer,\n                             \"Integer math fast\" => p004solution_integer_fast))\n\nProblems.benchmark(p004, 3)", "meta": {"hexsha": "b1b4975a5e33b5caacf3e650cf65d92b3270f3f5", "size": 1608, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/004.jl", "max_stars_repo_name": "gnujosh/julia-euler-project", "max_stars_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/004.jl", "max_issues_repo_name": "gnujosh/julia-euler-project", "max_issues_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/004.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.16, "max_line_length": 79, "alphanum_fraction": 0.6747512438, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.884039278690883, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7514079100759151}}
{"text": "module ImgProcMic\n\nusing ColorTypes\n\nexport complex_show, gray_show\n\n\n\"\"\"\n    complex_show(arr)\n\nDisplays a complex array. Color encodes phase, brightness encodes magnitude.\nWorks within Jupyter and Pluto.\n\"\"\"\nfunction complex_show(cpx::AbstractArray{<:Complex, N}) where N\n\tac = abs.(cpx)\n\tHSV.(angle.(cpx)./2pi*256,ones(Float32,size(cpx)),ac./maximum(ac))\nend\n\n\"\"\"\n    gray_show(arr; set_one=false, set_zero=false)\nDisplays a real gray color array. Brightness encodes magnitude.\nWorks within Jupyter and Pluto.\n\n## Keyword args\n* `set_one=false` divides by the maximum to set maximum to 1\n* `set_zero=false` subtracts the minimum to set minimum to 1\n\"\"\"\nfunction gray_show(arr; set_one=true, set_zero=false)\n    arr = set_zero ? arr .- minimum(arr) : arr\n    arr = set_one ? arr ./ maximum(arr) : arr\n    Gray.(arr)\nend\n\n\nend \n", "meta": {"hexsha": "d5679853fb3bfac91b524da733f219d28003fde4", "size": 829, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ImgProcMic.jl", "max_stars_repo_name": "GuillaumePail/Image-Processing-in-Microscopy", "max_stars_repo_head_hexsha": "4b7c62ca9d50064f3fa69be3eefb21b300765130", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-11-05T21:01:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T16:02:52.000Z", "max_issues_repo_path": "src/ImgProcMic.jl", "max_issues_repo_name": "GuillaumePail/Image-Processing-in-Microscopy", "max_issues_repo_head_hexsha": "4b7c62ca9d50064f3fa69be3eefb21b300765130", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-03T01:37:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-03T13:56:12.000Z", "max_forks_repo_path": "src/ImgProcMic.jl", "max_forks_repo_name": "GuillaumePail/Image-Processing-in-Microscopy", "max_forks_repo_head_hexsha": "4b7c62ca9d50064f3fa69be3eefb21b300765130", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-08T19:18:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T03:36:04.000Z", "avg_line_length": 23.0277777778, "max_line_length": 76, "alphanum_fraction": 0.7237635706, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7514079094670324}}
{"text": "### A Pluto.jl notebook ###\n# v0.18.0\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 8af90e7a-0e5e-4a9d-b39e-f7603fc1e25e\nbegin \n\tENV[\"LC_NUMERIC\"]=\"C\" # necessary for ensuring \n\t                      # proper parallel use of PyPlot and Triangulate\n\tusing Triangulate, PyPlot, PlutoUI, Printf\n\tPyPlot.svg(true)\nend;\n\n# ╔═╡ 7b468c8a-ce16-11eb-3009-f9e4c79e6c17\nmd\"\"\"\n# Triangulate examples\n$(TableOfContents(title=\"\",aside=false))\n## Triangulations of point sets\n\"\"\"\n\n# ╔═╡ 83f07f94-7e35-42de-9214-715c92b6dddd\nmd\"\"\"\n### Delaunay triangulation (DT)\n\nThe Delaunay triangulation of a set of points is a triangulation\nwhere for each triangle, the interior of its circumcircle  does not contain any points\nof the triangulation.\n\nThe Delaunay triangulation of a set of points in general position\n(no 4 of them on a circle) is unique. At the same time, it is a\ntriangulation of the convex hull of these points.\n\nGiven an input list of points, without any further flags, Triangle creates\njust this triangulation (the \"Q\" flag suppresses the text output of Triangle).\nFor this and the next examples, the input list of points is created randomly,\nbut on a raster, preventing the appearance of too close points.\n\n\"\"\"\n\n# ╔═╡ c56434f3-e0a4-462e-86d5-fcfbb6778c11\nmd\"\"\"\n### DT with boundary\nSame as the previous example, but in addition specify the \"c\" flag.\n\nIn this case, Triangle outputs an additional list of segments\ndescribing the boundary of the convex hull. In fact this is a constrained\nDelaunay triangulation (CDT) where the boundary segments\nare the seen constraining edges which must appear in the output.\n\n\"\"\"\n\n# ╔═╡ f13ad00e-a3d3-462f-93d4-ebe1fe4a7b4d\nmd\"\"\"\n### DT with Voronoi diagram\n\nSame as the previous example, but instead of \"c\" specify the \"v\" flag.\nIn this case, Triangle outputs information about the Voronoi diagram\nof the point set which is a structure dual to  the Delaunay triangulation.\n\nThe Voronoi cell around a point $p$ a point set $S$ is defined\nas the set of points $x$ such that $|x-p|<|x-q|$ for all $q\\in S$\nsuch that $p\\neq q$.\nThe Voronoi cells of boundary points\nof the convex hull are of infinite size. The corners of the Voronoi\ncells are the circumcenters of the triangles. They can be far\noutside of the triangulated domain.\n\n\"\"\"\n\n# ╔═╡ 852e1ebf-3f29-472a-945e-53920d7653be\nmd\"\"\"\n### Boundary conforming DT (BCDT)\nSpecify \"c\" flag for convex hull segments, \"v\" flag for Voronoi\nand \"D\" flag for creating a boundary conforming Delaunay triangulation of\nthe point set. \n\nIn this case additional points (\"Steiner points\") are created which split\nthe boundary segments and ensure that all triangle circumcenters\nlie within the convex hull.\nDue to random input, there may be situations where Triangle fails with this task,\nso we check for the corresponding exception.\n\n\"\"\"\n\n# ╔═╡ b95859af-ab21-4c41-b095-82b3ea39724a\nmd\"\"\"\n### Constrained DT (CDT) \nConstrained Delaunay triangulation (CDT) of a point set with\nadditional constraints given a priori. This is obtained when\nspecifying the \"p\" flag and an additional list of segments each described\nby two points \nwhich should become edges of the triangulation. Note that\nthe resulting triangulation is not Delaunay in the sense\ngiven above.\n\n\"\"\"\n\n# ╔═╡ c5a87fb5-c264-498d-aa7c-91d9e6d7bfe2\nmd\"\"\"\n## Triangulations of domains\n\"\"\"\n\n# ╔═╡ 7f2b4252-a827-4de4-abb6-42d1bbde44b9\nmd\"\"\"\n### CDT of a domain \n\nSpecification is similar to that of the CDT of a point set.\n\nThe domain is given by a segment list specifying its boundary.\n\nThis is obtained by specifying the \"p\" flag.\n\n\"\"\"\n\n# ╔═╡ 6793711b-d476-45c6-8b2b-b1d0693d8e6e\nmd\"\"\"\n### CDT with maximum area constraint\n\nThis constraint is specfied as a floating\npoint number given after the -a flag.\nBe careful to not give it in the exponential format as Triangle would be unable to analyse it.\nTherefore it is dangerous to provide it via string interpolation and it is better to convert it to a string before using `@sprintf`.\n\nSpecifying only the maximum area constraint does not prevent very thin\ntriangles from occuring at the boundary.\n\n\"\"\"\n\n# ╔═╡ 3f2f0b19-3c13-482d-abd5-e6325802c6e8\nmd\"\"\"\n### BCDT with maximum area constraint \n\nIn addition to the area constraint specify the -D flag\nin order to keep the triangle circumcenters  within the domain.\n\n\"\"\"\n\n# ╔═╡ 14145886-2a5f-4ae8-bf00-a5eaaa7e0568\nmd\"\"\"\n### CDT with minimum angle condition\n\nThe \"q\" flag  allows to specify a minimum angle\nconstraint preventing skinny triangles.\n\nThis combination of flags, possibly with an additional \"D\" flag is recommended\nwhen creating triangulations for finite element or finite volume methods.\nIt the mimimum angle is larger then 28.6 degrees, Triangle's algorithm may\nrun into an infinite loop.\n\n\"\"\"\n\n# ╔═╡ 61dc30ce-9256-4f20-9163-e8d473ac9e53\nmd\"\"\"\n### Triangulation with refinement callback\n\nA maximum area constraint is specified in the `unsuitable` callback\nwhich is activated via the \"u\" flag if it has been passed before calling triangulate.\n\nIn addition, the \"q\" flag  allows to specify a minimum angle\nconstraint preventing skinny triangles.\n\n\"\"\"\n\n# ╔═╡ 30990760-92e1-4a26-98a5-b43be658dee7\nmd\"\"\"\n### Triangulation of a heterogeneous domain\n\nThe segment list specifies its boundary and the inner boundary between subdomains.\nAn additional region list is specified which provides \"region points\" in `regionlist[1,:]`\nand `regionlist[2,:]`.  These kind of mark the subdomains. `regionlist[3,:]` contains an attribute\nwhich labels the subdomains. `regionlist[4,:]` contains a maximum area value. `size(regionlist,2)`\nis the number of regions.\n\nWith the \"A\" flag, the subdomain labels are spread to all triangles in the corresponding\nsubdomains, becoming available in `triangleattributelist[1,:]`.\nWith the \"a\" flag, the area constraints are applied in the corresponding subdomains.\n\n\"\"\"\n\n# ╔═╡ 783975f5-cbab-4b23-9155-7a6276cd25df\nmd\"\"\"\n### Triangulation of a domain with holes\nThe segment list specifies its boundary and the boundaries of the holes.\nAn additional hole list is specified which provides \"hole points\" in `holelist[1,:]`\nand `holelist[2,:]`. \n\n\"\"\"\n\n# ╔═╡ 9a090bba-093b-4ca4-a186-1c43b52cd4ff\nhtml\"\"\"<hr>\"\"\"\n\n# ╔═╡ 9447e874-22ce-4b99-9037-e0d202430ee2\n# Wrap \"Pyplotting\" into this function in order to shield calling code\n# from all these peculiarities.\nfunction pyplot(f;w=650,h=300)\n\tPyPlot.close()\n\tPyPlot.clf()\n\tfig=PyPlot.figure(1,dpi=100)\n\tfig.set_size_inches(w/100,h/100,forward=true)\n\tf()\n\tPyPlot.gcf()\nend;\n\n# ╔═╡ a5f7aca5-9e40-471a-bece-34498a804bd8\nfunction example_convex_hull(;n=10,raster=10)\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=hcat(unique([ Cdouble[rand(1:raster)/raster, rand(1:raster)/raster] for i in 1:n])...)\n    display(triin)\n    (triout, vorout)=triangulate(\"Q\", triin)\n\tpyplot() do\n\t\tplot_in_out(PyPlot,triin,triout,title=\"Convex hull\",circumcircles=true)\n\tend\nend;\n\n# ╔═╡ d0e63ebd-9288-42d5-9735-3c94a2baa8e3\nexample_convex_hull(;n=10,raster=10)\n\n# ╔═╡ 6f3f0014-42bc-4565-a03e-208fed8b8f48\nfunction example_convex_hull_with_boundary(;n=10,raster=10)\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=hcat(unique([ Cdouble[rand(1:raster)/raster, rand(1:raster)/raster] for i in 1:n])...)\n    display(triin)\n    (triout, vorout)=triangulate(\"cQ\", triin)\n\tpyplot() do\n    \tplot_in_out(PyPlot,triin,triout,title=\"Convex hull with boundary\")\n\tend\nend;\n\n# ╔═╡ 6ec811ca-e6d3-43ea-8da9-02bb05060d8d\nexample_convex_hull_with_boundary(;n=10,raster=10)\n\n# ╔═╡ 6e2d70c4-dc0f-4672-823a-930a50114811\nfunction example_convex_hull_voronoi(;n=10,raster=10)\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=hcat(unique([ Cdouble[rand(1:raster)/raster, rand(1:raster)/raster] for i in 1:n])...)\n    (triout, vorout)=triangulate(\"vQ\", triin)\n\tpyplot() do\n    plot_in_out(PyPlot,triin,triout,voronoi=vorout,title=\"Convex hull with Voronoi diagram\")\n\tend\nend;\n\n# ╔═╡ 0b54833f-0458-4417-aa03-27c4fe2a873c\nexample_convex_hull_voronoi(;n=10,raster=10)\n\n# ╔═╡ 1ee0af11-96e4-4929-926e-d7143ed1f791\nfunction example_convex_hull_voronoi_delaunay(;n=10,raster=10)\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=hcat(unique([ Cdouble[rand(1:raster)/raster, rand(1:raster)/raster] for i in 1:n])...)\n    try\n        (triout, vorout)=triangulate(\"vcDQ\", triin)\n\t\tpyplot() do\n        plot_in_out(PyPlot,triin,triout,voronoi=vorout,title=\"Convex hull with Voronoi diagram\")\n\t\tend\n    catch err\n        if typeof(err)==TriangulateError\n            println(\"Triangle had some problem.\")\n            return true\n        end\n    end\nend;\n\n# ╔═╡ 4da9a598-bf59-4b3b-aea7-ee1c2721c206\n example_convex_hull_voronoi_delaunay(;n=10,raster=10)\n\n# ╔═╡ 0d648d22-aa03-437b-b019-59bd693bc55e\nfunction example_cdt(;n=10,raster=10)\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=hcat(unique([ Cdouble[rand(1:raster)/raster, rand(1:raster)/raster] for i in 1:n])...)\n    npt=size(triin.pointlist,2)\n    triin.segmentlist=Matrix{Cint}([1 2; npt-1 npt-2;  1 npt;]')\n    triin.segmentmarkerlist=Vector{Cint}([2,3,4])\n    (triout, vorout)=triangulate(\"pcQ\", triin)\n\tpyplot() do\n    plot_in_out(PyPlot,triin,triout,title=\"CDT\")\n\tend\nend;\n\n# ╔═╡ 910ce428-4989-4b08-8037-887dae5c847e\nexample_cdt(;n=10,raster=10)\n\n# ╔═╡ ccd8ed8d-7991-4a19-8a05-65761adc2fee\nfunction example_domain_cdt()\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=Matrix{Cdouble}([0.0 0.0 ; 1.0 0.0 ; 1.0  1.0 ; 0.6 0.6; 0.0 1.0]')\n    triin.segmentlist=Matrix{Cint}([1 2 ; 2 3 ; 3 4 ; 4 5 ; 5 1 ]')\n    triin.segmentmarkerlist=Vector{Int32}([1, 2, 3, 4, 5])\n    (triout, vorout)=triangulate(\"pQ\", triin)\n\tpyplot() do\n    plot_in_out(PyPlot,triin,triout,title=\"Domain CDT\")\n\tend\nend;\n\n# ╔═╡ fc5264cf-b1f7-43c5-bcff-09e6274ca215\nexample_domain_cdt()\n\n# ╔═╡ b71b1faf-ff3f-4404-8a2c-9de84fa498f7\nfunction example_domain_cdt_area(;maxarea=0.05)\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=Matrix{Cdouble}([0.0 0.0 ; 1.0 0.0 ; 1.0  1.0 ; 0.6 0.6; 0.0 1.0]')\n    triin.segmentlist=Matrix{Cint}([1 2 ; 2 3 ; 3 4 ; 4 5 ; 5 1 ]')\n    triin.segmentmarkerlist=Vector{Int32}([1, 2, 3, 4, 5])\n    area=@sprintf(\"%.15f\",maxarea) # Don't use exponential format!\n    (triout, vorout)=triangulate(\"pa$(area)Q\", triin)\n\tpyplot() do\n    plot_in_out(PyPlot,triin,triout,voronoi=vorout, title=\"Domain CDT with area constraint\",circumcircles=true)\n\tend\nend;\n\n# ╔═╡ cd007961-7f0e-4c56-9c86-1a9827a71e3e\nexample_domain_cdt_area(;maxarea=0.05)\n\n# ╔═╡ 8ac6cc0b-e4e7-4aa0-bc37-b22b15bf2a83\nfunction example_domain_bcdt_area(;maxarea=0.05)\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=Matrix{Cdouble}([0.0 0.0 ; 1.0 0.0 ; 1.0  1.0 ; 0.6 0.6; 0.0 1.0]')\n    triin.segmentlist=Matrix{Cint}([1 2 ; 2 3 ; 3 4 ; 4 5 ; 5 1 ]')\n    triin.segmentmarkerlist=Vector{Int32}([1, 2, 3, 4, 5])\n    area=@sprintf(\"%.15f\",maxarea)\n    (triout, vorout)=triangulate(\"pa$(area)DQ\", triin)\n\tpyplot() do\n    plot_in_out(PyPlot,triin,triout,voronoi=vorout, title=\"Boundary conforming Delaunay triangulation\", circumcircles=true)\n\n\tend\nend;\n\n# ╔═╡ a0cb6060-8278-444a-a4e5-46055d98616c\nexample_domain_bcdt_area(;maxarea=0.05)\n\n# ╔═╡ a7e97f1c-e091-4555-abc0-a71abd22dd8a\nfunction example_domain_qcdt_area(;minangle=20, maxarea=0.05)\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=Matrix{Cdouble}([0.0 0.0 ; 1.0 0.0 ; 1.0  1.0 ; 0.6 0.6; 0.0 1.0]')\n    triin.segmentlist=Matrix{Cint}([1 2 ; 2 3 ; 3 4 ; 4 5 ; 5 1 ]')\n    triin.segmentmarkerlist=Vector{Int32}([1, 2, 3, 4, 5])\n    area=@sprintf(\"%.15f\",maxarea)\n    angle=@sprintf(\"%.15f\",minangle)\n    (triout, vorout)=triangulate(\"pa$(area)q$(angle)\", triin)\n\tpyplot() do\n    plot_in_out(PyPlot,triin,triout,voronoi=vorout, title=\"Quality triangulation\")\n\tend\nend;\n\n# ╔═╡ 4e7dad4d-7d3c-4201-a56f-28e3df51e885\nexample_domain_qcdt_area(;maxarea=0.05,minangle=20)\n\n# ╔═╡ 083b8aef-67f1-489a-8eff-b70fb6dc9da4\nfunction example_domain_localref(;minangle=20)\n    center_x=0.6\n    center_y=0.6\n    localdist=0.1\n    function unsuitable(x1,y1,x2,y2,x3,y3,area)\n        bary_x=(x1+x2+x3)/3.0\n        bary_y=(y1+y2+y3)/3.0\n        dx=bary_x-center_x\n        dy=bary_y-center_y\n        qdist=dx^2+dy^2\n        qdist>1.0e-5 && area>0.1*qdist\n    end\n\n    triunsuitable(unsuitable)\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=Matrix{Cdouble}([0.0 0.0 ; 1.0 0.0 ; 1.0  1.0 ; 0.6 0.6; 0.0 1.0]')\n    triin.segmentlist=Matrix{Cint}([1 2 ; 2 3 ; 3 4 ; 4 5 ; 5 1 ]')\n    triin.segmentmarkerlist=Vector{Int32}([1, 2, 3, 4, 5])\n    angle=@sprintf(\"%.15f\",minangle)\n    (triout, vorout)=triangulate(\"pauq$(angle)Q\", triin)\n\tpyplot() do\n    plot_in_out(PyPlot,triin,triout,voronoi=vorout, title=\"Quality triangulation with local refinement\")\n\tend\nend;\n\n# ╔═╡ 3c88e5cb-5e85-4146-a6d7-3682f4b9a892\nexample_domain_localref(;minangle=20)\n\n# ╔═╡ f0f9922b-70ce-4866-bc41-349a26095ade\nfunction example_domain_regions(;minangle=20)\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=Matrix{Cdouble}([0.0 0.0 ;0.5 0.0; 1.0 0.0 ; 1.0  1.0 ; 0.6 0.6; 0.0 1.0]')\n    triin.segmentlist=Matrix{Cint}([1 2 ; 2 3 ;3 4 ; 4 5 ; 5 6 ; 6 1 ; 2 5]')\n    triin.segmentmarkerlist=Vector{Int32}([1, 2, 3, 4, 5, 6, 7])\n    triin.regionlist=Matrix{Cdouble}([0.2 0.8; 0.2 0.2; 1 2 ; 0.01 0.05])\n    angle=@sprintf(\"%.15f\",minangle)\n    (triout, vorout)=triangulate(\"paAq$(angle)Q\", triin)\n\tpyplot() do\n    plot_in_out(PyPlot,triin,triout,voronoi=vorout, title=\"Hetero domain triangulation\")\n\tend\nend;\n\n# ╔═╡ 58dbd0e3-b34f-44ec-905a-488c7bbd07ca\nexample_domain_regions(minangle=20)\n\n# ╔═╡ 3dfe5acd-72f7-4510-b3a0-40364f679073\nfunction example_domain_holes(;minangle=20,maxarea=0.001)\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=Matrix{Cdouble}([0.0 0.0;\n                                     1.0 0.0;\n                                     1.0 1.0;\n                                     0.0 1.0;\n                                     0.2 0.2;\n                                     0.3 0.2;\n                                     0.3 0.3;\n                                     0.2 0.3;                                     \n                                     0.6 0.6;\n                                     0.7 0.6;\n                                     0.7 0.7;\n                                     0.6 0.7;                                     \n                                     ]')\n    triin.segmentlist=Matrix{Cint}([1 2; 2 3; 3 4; 4 1; 5 6; 6 7; 7 8; 8 5;  9 10; 10 11; 11 12; 12 9;]')\n    triin.segmentmarkerlist=Vector{Int32}([1, 1,1,1, 2,2,2,2, 3,3,3,3])\n    triin.holelist=[0.25 0.25; 0.65 0.65;]'\n    area=@sprintf(\"%.15f\",maxarea) # Don't use exponential format!\n    angle=@sprintf(\"%.15f\",minangle)\n    (triout, vorout)=triangulate(\"pa$(area)q$(angle)Q\", triin)\n \n\tpyplot() do\n    plot_in_out(PyPlot,triin,triout,voronoi=vorout, title=\"Domain with holes\")\n\tend\nend;\n\n# ╔═╡ 6545d149-d4dd-4f26-8f51-5db90f6b444d\nexample_domain_holes(minangle=20,maxarea=0.05)\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nPrintf = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\nPyPlot = \"d330b81b-6aea-500a-939a-2ce795aea3ee\"\nTriangulate = \"f7e6ffb2-c36d-4f8f-a77e-16e897189344\"\n\n[compat]\nPlutoUI = \"~0.7.34\"\nPyPlot = \"~2.10.0\"\nTriangulate = \"~2.1.1\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[AbstractPlutoDingetjes]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"8eaf9f1b4921132a4cff3f36a1d9ba923b14a481\"\nuuid = \"6e696c72-6542-2067-7265-42206c756150\"\nversion = \"1.1.4\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Conda]]\ndeps = [\"Downloads\", \"JSON\", \"VersionParsing\"]\ngit-tree-sha1 = \"6cdc8832ba11c7695f494c9d9a1c31e90959ce0f\"\nuuid = \"8f4d0f93-b110-5947-807f-2305c1781a2d\"\nversion = \"1.6.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[HypertextLiteral]]\ngit-tree-sha1 = \"2b078b5a615c6c0396c77810d92ee8c6f470d238\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.3\"\n\n[[IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"abc9885a7ca2052a736a600f7fa66209f96506e1\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.4.1\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"3c837543ddb02250ef42f4738347454f95079d4e\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.3\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"f2355693d6778a178ade15952b7ac47a4ff97996\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.3.0\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"13468f237353112a01b2d6b32f3d0f80219944aa\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.2.2\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"ColorTypes\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"8979e9802b4ac3d58c503a20f2824ad67f9074dd\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.34\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"2cf929d64681236a2e074ffafb8d568733d2e6af\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.3\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[PyCall]]\ndeps = [\"Conda\", \"Dates\", \"Libdl\", \"LinearAlgebra\", \"MacroTools\", \"Serialization\", \"VersionParsing\"]\ngit-tree-sha1 = \"71fd4022ecd0c6d20180e23ff1b3e05a143959c2\"\nuuid = \"438e738f-606a-5dbb-bf0a-cddfbfd45ab0\"\nversion = \"1.93.0\"\n\n[[PyPlot]]\ndeps = [\"Colors\", \"LaTeXStrings\", \"PyCall\", \"Sockets\", \"Test\", \"VersionParsing\"]\ngit-tree-sha1 = \"14c1b795b9d764e1784713941e787e1384268103\"\nuuid = \"d330b81b-6aea-500a-939a-2ce795aea3ee\"\nversion = \"2.10.0\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[Triangle_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"bfdd9ef1004eb9d407af935a6f36a4e0af711369\"\nuuid = \"5639c1d2-226c-5e70-8d55-b3095415a16a\"\nversion = \"1.6.1+0\"\n\n[[Triangulate]]\ndeps = [\"DocStringExtensions\", \"Libdl\", \"Printf\", \"Test\", \"Triangle_jll\"]\ngit-tree-sha1 = \"0b011b75202d936d2f1af6215bf3b6cce26f2b7b\"\nuuid = \"f7e6ffb2-c36d-4f8f-a77e-16e897189344\"\nversion = \"2.1.1\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[VersionParsing]]\ngit-tree-sha1 = \"58d6e80b4ee071f5efd07fda82cb9fbe17200868\"\nuuid = \"81def892-9a0e-5fdd-b105-ffc91e053289\"\nversion = \"1.3.0\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─7b468c8a-ce16-11eb-3009-f9e4c79e6c17\n# ╟─83f07f94-7e35-42de-9214-715c92b6dddd\n# ╠═a5f7aca5-9e40-471a-bece-34498a804bd8\n# ╠═d0e63ebd-9288-42d5-9735-3c94a2baa8e3\n# ╟─c56434f3-e0a4-462e-86d5-fcfbb6778c11\n# ╠═6f3f0014-42bc-4565-a03e-208fed8b8f48\n# ╠═6ec811ca-e6d3-43ea-8da9-02bb05060d8d\n# ╟─f13ad00e-a3d3-462f-93d4-ebe1fe4a7b4d\n# ╠═6e2d70c4-dc0f-4672-823a-930a50114811\n# ╠═0b54833f-0458-4417-aa03-27c4fe2a873c\n# ╟─852e1ebf-3f29-472a-945e-53920d7653be\n# ╠═1ee0af11-96e4-4929-926e-d7143ed1f791\n# ╠═4da9a598-bf59-4b3b-aea7-ee1c2721c206\n# ╟─b95859af-ab21-4c41-b095-82b3ea39724a\n# ╠═0d648d22-aa03-437b-b019-59bd693bc55e\n# ╠═910ce428-4989-4b08-8037-887dae5c847e\n# ╟─c5a87fb5-c264-498d-aa7c-91d9e6d7bfe2\n# ╟─7f2b4252-a827-4de4-abb6-42d1bbde44b9\n# ╠═ccd8ed8d-7991-4a19-8a05-65761adc2fee\n# ╠═fc5264cf-b1f7-43c5-bcff-09e6274ca215\n# ╟─6793711b-d476-45c6-8b2b-b1d0693d8e6e\n# ╠═b71b1faf-ff3f-4404-8a2c-9de84fa498f7\n# ╠═cd007961-7f0e-4c56-9c86-1a9827a71e3e\n# ╟─3f2f0b19-3c13-482d-abd5-e6325802c6e8\n# ╠═8ac6cc0b-e4e7-4aa0-bc37-b22b15bf2a83\n# ╠═a0cb6060-8278-444a-a4e5-46055d98616c\n# ╟─14145886-2a5f-4ae8-bf00-a5eaaa7e0568\n# ╠═a7e97f1c-e091-4555-abc0-a71abd22dd8a\n# ╠═4e7dad4d-7d3c-4201-a56f-28e3df51e885\n# ╟─61dc30ce-9256-4f20-9163-e8d473ac9e53\n# ╠═083b8aef-67f1-489a-8eff-b70fb6dc9da4\n# ╠═3c88e5cb-5e85-4146-a6d7-3682f4b9a892\n# ╟─30990760-92e1-4a26-98a5-b43be658dee7\n# ╠═f0f9922b-70ce-4866-bc41-349a26095ade\n# ╠═58dbd0e3-b34f-44ec-905a-488c7bbd07ca\n# ╟─783975f5-cbab-4b23-9155-7a6276cd25df\n# ╠═3dfe5acd-72f7-4510-b3a0-40364f679073\n# ╠═6545d149-d4dd-4f26-8f51-5db90f6b444d\n# ╟─9a090bba-093b-4ca4-a186-1c43b52cd4ff\n# ╠═8af90e7a-0e5e-4a9d-b39e-f7603fc1e25e\n# ╠═9447e874-22ce-4b99-9037-e0d202430ee2\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "8143b543e5ea828b509168887a043e641f4edb39", "size": 24128, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/pluto-examples.jl", "max_stars_repo_name": "JuliaGeometry/TriangulateIO.jl", "max_stars_repo_head_hexsha": "cb7eacf7b21d0ae0f6023bfb2a70b80a1dea6e64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-11T19:41:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-11T19:41:30.000Z", "max_issues_repo_path": "examples/pluto-examples.jl", "max_issues_repo_name": "JuliaGeometry/TriangulateIO.jl", "max_issues_repo_head_hexsha": "cb7eacf7b21d0ae0f6023bfb2a70b80a1dea6e64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-12-11T18:07:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-12T08:00:32.000Z", "max_forks_repo_path": "examples/pluto-examples.jl", "max_forks_repo_name": "JuliaGeometry/TriangulateIO.jl", "max_forks_repo_head_hexsha": "cb7eacf7b21d0ae0f6023bfb2a70b80a1dea6e64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4737550471, "max_line_length": 196, "alphanum_fraction": 0.7103779841, "num_tokens": 10055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.8840392909114836, "lm_q1q2_score": 0.7514079087041212}}
{"text": "int\nmain() {\n\tprintInt(fac(10));\n\tprintInt(rfac(10));\n\tprintInt(mfac(10));\n        printInt(ifac(10));\n        double r ; // just to test blocks \n\t{\n\t  int n = 10;\n\t  int r = 1;\n\t  while (n>0) {\n\t    r = r * n;\n\t    n = n - 1;\n\t  }\n\t  printInt(r);\n\t}\n\tprintDouble(dfac(10.0));\n\tprintString (\"hello */\");\n        printString (\"/* world\") ;\n        return 0 ;\n}\n\nint \nfac(int a) {\n\tint r;\n\tint n;\n\n\tr = 1;\n\tn = a;\n\twhile (n > 0) {\n\t\tr = r * n;\n\t\tn = n - 1;\n\t}\n\treturn r;\n}\n\nint\nrfac(int n)\n{\n\tif (n == 0)\n\t\treturn 1;\n\telse\n\t\treturn n * rfac(n-1);\n}\n\nint\nmfac(int n)\n{\n\tif (n == 0)\n\t\treturn 1;\n\telse\n\t\treturn n * nfac(n-1);\n}\n\nint\nnfac(int n)\n{\n\tif (n != 0)\n\t\treturn mfac(n-1) * n;\n\telse\n\t\treturn 1;\n}\n\ndouble\ndfac(double n)\n{\n\tif (n == 0.0)\n\t\treturn 1.0;\n\telse\n\t\treturn n * dfac(n-1.0);\n}\n\nint ifac(int n) { return ifac2f(1,n); }\n\nint ifac2f(int l, int h) {\n        if (l == h)\n                return l;\n        if (l > h)\n                return 1;\n        int m;\n        m = (l+h) / 2;\n        return ifac2f(l,m) * ifac2f(m+1,h);\n}\n", "meta": {"hexsha": "143c9a96a26fa20caee5847c96f756bb431f2723", "size": 1031, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tests/examples/good/core001.jl", "max_stars_repo_name": "lukaszcz/javalette", "max_stars_repo_head_hexsha": "3ba79ca57d6332261bdbb5bea1e106451504b506", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/examples/good/core001.jl", "max_issues_repo_name": "lukaszcz/javalette", "max_issues_repo_head_hexsha": "3ba79ca57d6332261bdbb5bea1e106451504b506", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/examples/good/core001.jl", "max_forks_repo_name": "lukaszcz/javalette", "max_forks_repo_head_hexsha": "3ba79ca57d6332261bdbb5bea1e106451504b506", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.2738095238, "max_line_length": 43, "alphanum_fraction": 0.462657614, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.751407908396065}}
{"text": "# Raised Cosine distribution\n#\n# Ref: http://en.wikipedia.org/wiki/Raised_cosine_distribution\n#\n\nimmutable Cosine{T<:Real} <: ContinuousUnivariateDistribution\n    μ::T\n    σ::T\n\n    Cosine(μ::T, σ::T) = (@check_args(Cosine, σ > zero(σ)); new(μ, σ))\nend\n\nCosine{T<:Real}(μ::T, σ::T) = Cosine{T}(μ, σ)\nCosine(μ::Real, σ::Real) = Cosine(promote(μ, σ)...)\nCosine(μ::Integer, σ::Integer) = Cosine(Float64(μ), Float64(σ))\nCosine(μ::Real) = Cosine(μ, 1.0)\nCosine() = Cosine(0.0, 1.0)\n\n@distr_support Cosine d.μ - d.σ d.μ + d.σ\n\n#### Conversions\nfunction convert{T<:Real}(::Type{Cosine{T}}, μ::Real, σ::Real)\n    Cosine(T(μ), T(σ))\nend\nfunction convert{T <: Real, S <: Real}(::Type{Cosine{T}}, d::Cosine{S})\n    Cosine(T(d.μ), T(d.σ))\nend\n\n#### Parameters\n\nlocation(d::Cosine) = d.μ\nscale(d::Cosine) = d.σ\n\nparams(d::Cosine) = (d.μ, d.σ)\n@inline partype{T<:Real}(d::Cosine{T}) = T\n\n\n#### Statistics\n\nmean(d::Cosine) = d.μ\n\nmedian(d::Cosine) = d.μ\n\nmode(d::Cosine) = d.μ\n\nvar{T<:Real}(d::Cosine{T}) = d.σ^2 * (1//3 - 2/T(π)^2)\n\nskewness{T<:Real}(d::Cosine{T}) = zero(T)\n\nkurtosis{T<:Real}(d::Cosine{T}) = 6*(90-T(pi))/(5*(T(π)^2-6)^2)\n\n\n#### Evaluation\n\nfunction pdf{T<:Real}(d::Cosine{T}, x::Real)\n    if insupport(d, x)\n        z = (x - d.μ) / d.σ\n        return (1 + cospi(z)) / (2d.σ)\n    else\n        return zero(T)\n    end\nend\n\nfunction logpdf{T<:Real}(d::Cosine{T}, x::Real)\n    insupport(d, x) ? log(pdf(d, x)) : -T(Inf)\nend\n\nfunction cdf(d::Cosine, x::Real)\n    z = (x - d.μ) / d.σ\n    (1 + z + sinpi(z) * invπ) / 2\nend\n\nfunction ccdf(d::Cosine, x::Real)\n    nz = (d.μ - x) / d.σ\n    (1 + nz + sinpi(nz) * invπ) / 2\nend\n\nquantile(d::Cosine, p::Real) = quantile_bisect(d, p)\n", "meta": {"hexsha": "be91e1f26771c7f447422a850e3c7a5d6938d3ed", "size": 1674, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/cosine.jl", "max_stars_repo_name": "JuliaPackageMirrors/Distributions.jl", "max_stars_repo_head_hexsha": "091cad865281c92746dc455cc50f4b2a311d3dd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/cosine.jl", "max_issues_repo_name": "JuliaPackageMirrors/Distributions.jl", "max_issues_repo_head_hexsha": "091cad865281c92746dc455cc50f4b2a311d3dd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/cosine.jl", "max_forks_repo_name": "JuliaPackageMirrors/Distributions.jl", "max_forks_repo_head_hexsha": "091cad865281c92746dc455cc50f4b2a311d3dd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1898734177, "max_line_length": 71, "alphanum_fraction": 0.5740740741, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.8840392924390585, "lm_q1q2_score": 0.7514079032831142}}
{"text": "# %% transfer entropy\nusing DrWatson\n@quickactivate \"NonlinearDynamicsTextbook\"\ninclude(srcdir(\"style.jl\"))\nusing DynamicalSystems, PyPlot\n\nusing TransferEntropy, Random\n\nfunction ulam(dx, x, p, t)\n    f(x) = 2 - x^2;\n    ε = p[1];\n    N = length(x)\n    for i in 1:N\n        dx[i] = f(ε*x[mod1(i-1, N)] + (1-ε)*x[i])\n    end\nend\nds = DiscreteDynamicalSystem(ulam, rand(100), [0.04])\n\ngenmeth(r) = VisitationFrequency(RectangularBinning(r))\nmethods = genmeth.((0.01, 0.1, 0.4))\nεs = 0.0:0.01:1.0\ntes = [zeros(length(εs), 2) for j in 1:length(methods)]\n\nfor (i, ε) in enumerate(εs), (j, meth) in enumerate(methods)\n    set_parameter!(ds, 1, ε)\n    A = trajectory(ds, 10000; Ttr = 10000)\n    x1 = A[:, 1]; x2 = A[:, 2]\n    tes[j][i, 1] = transferentropy(x1, x2, meth)\n    tes[j][i, 2] = transferentropy(x2, x1, meth)\nend\n\n\nfig = figure(figsize = (6figx/10, figx/3))\nrs = (0.01, 0.1, 0.4)\n\nfor j in 1:length(methods)\n    plot(εs, tes[j][:, 1], color = \"C$(j-1)\", label = \"\\$r=$(rs[j])\\$\")\n    plot(εs, tes[j][:, 2], color = \"C$(j-1)\", ls = \"dashed\")\nend\nxlabel(\"coupling strength \\$\\\\epsilon\\$\")\nylabel(\"transfer entropy\")\nlegend(loc = \"center\", handlelength = 1)\ntight_layout(pad=0.3)\nwsave(plotsdir(\"7\", \"transfer\"), fig)", "meta": {"hexsha": "e654e16bf0a1f4fdaf132e782acf8cbadd7fd18f", "size": 1219, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "figure_generation/7/7.2.jl", "max_stars_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_stars_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 88, "max_stars_repo_stars_event_min_datetime": "2021-07-18T20:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T09:23:53.000Z", "max_issues_repo_path": "figure_generation/7/7.2.jl", "max_issues_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_issues_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figure_generation/7/7.2.jl", "max_forks_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_forks_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-07-28T18:49:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:45:11.000Z", "avg_line_length": 27.7045454545, "max_line_length": 71, "alphanum_fraction": 0.6095159967, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7514079007597243}}
{"text": "# vanderPol winding number arnold tongues\nusing DrWatson\n@quickactivate \"NonlinearDynamicsTextbook\"\ninclude(srcdir(\"style.jl\"))\nusing DynamicalSystems, PyPlot\n\nfunction winding_number(ds, ω, a, u0, Ttr, T)\n    period = 2π/ω\n    ds.p[2:3] .= (a, period)\n    # T = period*ceil(T/period)   # no. of periods required for transient\n    # Ttr = period*ceil(Ttr/period)     # no. of periods used for averaging\n    tr = trajectory(ds, T, u0; Δt = period/20, Ttr)\n    tvec = 0:period/20:T\n    u1, u2 = columns(tr)\n    θ = 0.0\n    θ_old = atan(u2[1], u1[1])\n    for (x, y) ∈ zip(u1, u2)\n        θ_new = atan(y, x)\n        θ += mod(θ_new - θ_old + π, 2π) - π\n        θ_old = θ_new\n    end\n    W = abs(θ / (tvec[end] * 2π/period))\n    return tr[end], W\nend\n\nusing ProgressMeter\n\nd = 5.0\n\na_min = 0.0\na_max = 1.0\nna = 100\na_vec = LinRange(a_min, a_max, na)\n\nω_min = 0.2\nω_max = 2.0\nnω =  1000\nω_vec = LinRange(ω_min, ω_max, nω)\n\nds = Systems.vanderpol(; μ = d)\n  \nwmat = zeros(nω,na)\n\nTtr =  5000 # transient time\nT =   4000 #  time on the attractor used for estimating winding no.\nu0 = ds.u0\n\n\nW_vec = zeros(nω)\n@showprogress 1 \"Computing...\" for ia = 1:na\n    a = a_vec[ia]\n    for iω = 1:length(ω_vec)\n        ω = ω_vec[iω]\n        u0, W = winding_number(ds, ω, a, u0, Ttr, T)\n        wmat[iω,ia] = 1/W\n    end # of frequency loop\nend  # of amplitude loop\n\n# %% Plot with all numbers\nfig = figure(figsize=(0.6*figx,figy)) \nim1 = plt.pcolormesh(ω_vec,a_vec,wmat',cmap = \"gnuplot\" )\n\nxlabel(L\"\\omega\") \nylabel(L\"a\") \n\nax = gca()\nax.set_xlim([ω_min,ω_max])\n\ncbar = plt.colorbar(im1)  # , ticks=[-0.2, 0.2, 0.6, 1.], orientation=\"horizontal\")\ncbar.set_label(L\"W\") \n\nfig.tight_layout(pad=0.3)\n\n# %% Plot version with only wanted numbers\nfigure()\nqmat = 4*ones(nω,na)   # array with winding numbers to be displayed\n\nrat_num = [1/2, 2/3,   1, 4/3, 3/2, 5/3, 2,  7/3, 5/2, 8/3,  3,  10/3,  7/2]\nnrn = length(rat_num)\nfor ia = 1:na\n    for iomega = 1:nω\n        wind_no = wmat[iomega,ia] \n        # check whether equal p/q\n        for rat in rat_num\n            if abs(rat - wind_no) < 0.008  # this threshold should be as small as possible\n               qmat[iomega,ia] = rat\n            end\n        end  \n    end\nend\n\nim1 = plt.pcolormesh(ω_vec,a_vec,qmat',cmap = \"CMRmap\") # a color map which ends with white\nplt.clim(0.,4.)\nylabel(L\"a\") \nxlabel(L\"\\omega\"; labelpad = -10) \ncbar = plt.colorbar(im1)\ncbar.set_label(L\"W\") \nfig.tight_layout(pad=0.3)\nwsave(plotsdir(\"9\", \"vanderPol_tongues\"), fig)\n", "meta": {"hexsha": "d1fb2360d5a50e123adf99f9d23e6439bf73e32d", "size": 2479, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "figure_generation/9/9.7.jl", "max_stars_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_stars_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 88, "max_stars_repo_stars_event_min_datetime": "2021-07-18T20:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T09:23:53.000Z", "max_issues_repo_path": "figure_generation/9/9.7.jl", "max_issues_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_issues_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figure_generation/9/9.7.jl", "max_forks_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_forks_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-07-28T18:49:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:45:11.000Z", "avg_line_length": 24.79, "max_line_length": 91, "alphanum_fraction": 0.6107301331, "num_tokens": 957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7513851086016126}}
{"text": "# Many derivative free methods of different orders\n#\n# TODO: rework Order5 #https://pdfs.semanticscholar.org/ce50/3210d96f653a14b28da96600d5990d2abe97.pdf\n# https://content.sciendo.com/view/journals/tmj/10/4/article-p103.xml 7 and 8\n# order8: https://www.hindawi.com/journals/ijmms/2012/493456/ref/\n\n\n\n\n## Order0 and 1 are secant type\nfunction init_state(method::AbstractSecant, fs, x::Number)\n    x1 = float(x)\n    x0 = _default_secant_step(x1)\n    init_state(method, fs, (x0, x1))\nend\n\n\nfunction init_state(method::AbstractSecant, fs, x::Union{Tuple, Vector})\n    x0, x1 = promote(float(x[1]), float(x[2]))\n    fx0, fx1 = fs(x0), fs(x1)        \n    state = UnivariateZeroState(x1, x0, eltype(x1)[],\n                                fx1, fx0, eltype(fx1)[],\n                                0, 2,\n                                false, false, false, false, \"\")\n\n    state\nend\n\n\n\nfunction init_state!(state::UnivariateZeroState{T, S}, method::AbstractSecant, fs, x::Number) where {T, S}\n    x1::T = float(x)\n    x0::T = _default_secant_step(x1)\n    init_state!(state, method, fs, (x0, x1))\nend\n\n\nfunction init_state!(state::UnivariateZeroState{T, S}, ::AbstractSecant, f, x::Union{Tuple, Vector}) where {T, S}\n    x0,x1 = promote(float.(x)...)\n    fx0, fx1 = promote(f(x0), f(x1))\n    init_state!(state, x1, x0, T[], fx1, fx0, S[])\n    state.fnevals = 2\n    nothing\nend\n\n##################################################\n\n## Order0 and Secant are related\n\"\"\"\n    Order0()\n\n\nThe `Order0` method is engineered to be a more robust, though possibly\nslower, alternative to to the other derivative-free root-finding\nmethods. The implementation roughly follows the algorithm described in\n*Personal Calculator Has Key to Solve Any Equation f(x) = 0*, the\nSOLVE button from the\n[HP-34C](http://www.hpl.hp.com/hpjournal/pdfs/IssuePDFs/1979-12.pdf).\nThe basic idea is to use a secant step. If along the way a bracket is\nfound, switch to bisection, using `AlefeldPotraShi`.  If the secant\nstep fails to decrease the function value, a quadratic step is used up\nto 3 times.\n\n\"\"\"\nstruct Order0 <: AbstractSecant end\n\nfunction find_zero(fs, x0, method::Order0;\n                   tracks::AbstractTracks=NullTracks(),\n                   verbose=false,\n                   kwargs...)\n    M = Order1()\n    N = AlefeldPotraShi()\n    _find_zero(fs, x0, M, N; tracks=tracks,verbose=verbose, kwargs...)\nend\n\n##################################################\n\n## Secant\n## https://en.wikipedia.org/wiki/Secant_method\n\"\"\" \n    Order1()\n\nThe `Order1()` method is an alias for `Secant`. It specifies the\n[secant method](https://en.wikipedia.org/wiki/Secant_method).\nThis method keeps two values in its state, `x_n` and `x_n1`. The\nupdated point is the intersection point of x axis with the secant line\nformed from the two points. The secant method uses 1 function\nevaluation per step and has order `(1+sqrt(5))/2`.\n\n\"\"\"\nstruct Secant <: AbstractSecant end\nconst Order1 = Secant\n\nfunction update_state(method::Secant, fs, o::UnivariateZeroState{T,S}, options)  where {T, S}\n\n    if (o.fxn0 == o.fxn1) || (o.xn0 == o.xn1) \n         o.stopped = true\n         o.message = \"Derivative approximation had issues\"\n         return\n     end\n  \n    dx = o.fxn1 * (o.xn1 - o.xn0) / (o.fxn1 - o.fxn0)\n    o.xn0, o.xn1 = o.xn1, o.xn1 - dx\n    o.fxn0, o.fxn1 = o.fxn1, fs(o.xn1)\n    incfn(o)\n    \n    nothing\n\nend\n\n\n\n##################################################\n\n### Steffensen\n## https://en.wikipedia.org/wiki/Steffensen's_method#Simple_description\nstruct Steffensen <: AbstractUnivariateZeroMethod\nend\n\n\"\"\"\n    Order2()\n\nThe quadratically converging\n[Steffensen](https://en.wikipedia.org/wiki/Steffensen's_method#Simple_description)\nmethod is used for the derivative-free `Order2()` algorithm. Unlike\nthe quadratically converging Newton's method, no derivative is\nnecessary, though like Newton's method, two function calls per step\nare. This algorithm is more sensitive than Newton's method to poor\ninitial guesses.\n\n\"\"\"    \nconst Order2 = Steffensen\n\nfunction update_state(method::Steffensen, fs, o::UnivariateZeroState{T,S}, options) where {T, S}\n    \n    wn::T = o.xn1 + steff_step(o.xn1, o.fxn1)\n\n    fwn::S = fs(wn)\n    incfn(o)\n\n    fp, issue = _fbracket(o.xn1, wn, o.fxn1, fwn)\n\n    if issue\n        o.stopped = true\n        o.message = \"Derivative approximation had issues\"\n        return\n    end\n\n    o.xn0 = o.xn1\n    o.fxn0 = o.fxn1\n    o.xn1 = o.xn1 - o.fxn1 / fp #xn1\n    o.fxn1 = fs(o.xn1)\n    incfn(o)\n\n\n    nothing\nend\n\nsteffenson(f, x0; kwargs...) = find_zero(f, x0, Steffensen(); kwargs...)\n\n##################################################\n\n\n\"\"\"\n    Order5()\n\nImplements an order 5 algorithm from *A New Fifth Order Derivative\nFree Newton-Type Method for Solving Nonlinear Equations* by Manoj\nKumar, Akhilesh Kumar Singh, and Akanksha, Appl. Math. Inf. Sci. 9,\nNo. 3, 1507-1513 (2015), DOI: 10.12785/amis/090346. Four function\ncalls per step are needed.\n\n\"\"\"    \nstruct Order5 <: AbstractUnivariateZeroMethod end\n\n\n## If we have a derivative, we have this\nfunction update_state(method::Order5, fs::Union{FirstDerivative,SecondDerivative},\n                      o::UnivariateZeroState{T,S}, options)  where {T, S}\n\n\n    xn, fxn = o.xn1, o.fxn1\n\n    fpxn::S = fs(xn, 1)\n    incfn(o)\n\n    if isissue(fpxn)\n        o.stopped  = true\n        return\n    end\n\n    yn::T = xn - fxn / fpxn\n    fyn::S, fpyn::S = fs(yn), fs(yn, 1)\n    incfn(o, 2)\n\n    if isissue(fpyn)\n        o.xn0, o.xn1 = xn, yn\n        o.fxn0, o.fxn1 = fxn, fyn\n        o.stopped  = true\n        return\n    end\n\n\n    zn::T = xn  - (fxn + fyn) / fpxn\n    fzn::S = fs(zn)\n    incfn(o, 1)\n\n    xn1 = zn - fzn / fpyn\n    fxn1 = fs(xn1)\n    incfn(o, 1)\n\n    o.xn0, o.xn1 = xn, xn1\n    o.fxn0, o.fxn1 = fxn, fxn1\n\n    nothing\nend\n\n\nfunction update_state(method::Order5, fs, o::UnivariateZeroState{T,S}, options) where {T, S}\n\n    xn = o.xn1\n    fxn = o.fxn1\n\n    wn::T = o.xn1 + steff_step(o.xn1, o.fxn1)\n\n    fwn::S = fs(wn)\n    incfn(o)\n\n    fp, issue = _fbracket(o.xn1, wn, o.fxn1, fwn)\n    if issue\n        o.xn0, o.xn1 = o.xn1, wn\n        o.fxn0, o.fxn1 = o.fxn1, fwn\n        o.message = \"Issue with divided difference f[xn, wn]\"\n        o.stopped  = true\n        return\n    end\n\n    yn::T = o.xn1 - o.fxn1 / fp\n    fyn::S = fs(yn)\n    incfn(o)\n\n\n    zn::T = xn - (fxn + fyn) / fp\n    fzn::S = fs(zn)\n    incfn(o)\n\n    fp, issue = _fbracket_ratio(yn, o.xn1, wn, fyn, o.fxn1, fwn)\n    if issue\n        o.xn0, o.xn1 = o.xn1, yn\n        o.fxn0, o.fxn1 = o.fxn1, fyn\n        o.message = \"Issue with f[xn,yn]*f[yn,wn] / f[xn, wn]\"\n        o.stopped = true\n        return\n    end\n\n    o.xn0 = o.xn1\n    o.fxn0 = o.fxn1\n    o.xn1 = zn  - fzn  / fp\n    o.fxn1 = fs(o.xn1)\n    incfn(o)\n\n    nothing\nend\n\n##################################################\n\n\n## cf also: https://doi.org/10.1515/tmj-2017-0049\n\"\"\"\n    Order8()\n\nImplements an eighth-order algorithm from *New Eighth-Order\nDerivative-Free Methods for Solving Nonlinear Equations* by Rajinder\nThukral, International Journal of Mathematics and Mathematical\nSciences Volume 2012 (2012), Article ID 493456, 12 pages DOI:\n10.1155/2012/493456. Four function calls per step are required.\n    \n\"\"\"\nstruct Order8 <: AbstractUnivariateZeroMethod\nend\n\nfunction update_state(method::Order8, fs, o::UnivariateZeroState{T,S}, options) where {T, S}\n\n    xn = o.xn1\n    fxn = o.fxn1\n\n    wn::T = xn + steff_step(xn, fxn)\n    fwn::S = fs(wn)\n    incfn(o)\n\n    if isissue(fwn)\n        o.xn0,o.xn1 = xn, wn\n        o.fxn0,o.fxn1 = fxn, fwn\n        o.stopped = true\n        o.message = \"issue with Steffensen step fwn\"\n        return \n    end\n\n\n\n    fp, issue = _fbracket(xn, wn, fxn, fwn)\n\n    if issue\n        o.stopped = true\n        o.message = \"issue with divided difference f[xn, wn]\"\n        return \n    end\n\n    yn::T = xn - fxn / fp\n    fyn::S = fs(yn)\n    incfn(o)\n\n    fp, issue = _fbracket(yn, xn, fyn, fxn)\n    if issue #fp\n        o.xn0,o.xn1 = xn, yn\n        o.fxn0,o.fxn1 = fxn, fyn\n        o.stopped = true\n        o.message = \"issue with divided difference f[xn, yn]\"\n        return\n    end\n\n\n    phi = (1 + fyn / fwn)           # pick one of options\n    zn =  yn - phi * fyn / fp\n    fzn::S = fs(zn)\n    incfn(o)\n\n    fp, issue =  _fbracket_diff(xn, yn, zn, fxn, fyn, fzn)\n    if issue\n        o.xn0,o.xn1 = xn, zn\n        o.fxn0,o.fxn1 = fxn, fzn\n        o.message = \"issue with divided difference  f[y,z] - f[x,y] + f[x,z]\"\n        o.stopped = true\n        return\n    end\n\n    w = 1 / (1 - fzn/fwn)\n\n    xi = (1 - 2fyn*fyn*fyn / (fwn * fwn * fxn))\n\n    xn1 = zn - w * xi * fzn / fp\n    fxn1::S = fs(xn1)\n    incfn(o)\n\n    o.xn0,o.xn1 = xn, xn1\n    o.fxn0,o.fxn1 = fxn, fxn1\n\n    nothing\nend\n\n##################################################\n\n\"\"\"\n    Order16()\n\nImplement the algorithm from\n*New Sixteenth-Order Derivative-Free Methods for Solving Nonlinear Equations*\nby R. Thukral, \nAmerican Journal of Computational and Applied Mathematics\np-ISSN: 2165-8935;    e-ISSN: 2165-8943; 2012;  2(3): 112-118\ndoi: 10.5923/j.ajcam.20120203.08.\n\nFive function calls per step are required. Though rapidly converging,\nthis method generally isn't faster (fewer function calls/steps) over\nother methods when using `Float64` values, but may be useful for\nsolving over `BigFloat`.\n\n\"\"\"\nstruct Order16 <: AbstractUnivariateZeroMethod\nend\n\nfunction update_state(method::Order16, fs, o::UnivariateZeroState{T,S}, options) where {T, S}\n    xn = o.xn1\n    fxn = o.fxn1\n\n    wn::T = xn + steff_step(xn, fxn)\n    fwn::S = fs(wn)\n    incfn(o)\n\n    fp, issue = _fbracket(xn, wn, fxn, fwn)\n\n  \n    if issue\n        o.xn0, o.xn1 = xn, wn\n        o.fxn0, o.fxn1 = fxn, fwn\n        o.message = \"issue with f[xn,wn]\"\n        o.stopped = true\n        return\n    end\n\n    yn::T = xn - fxn / fp\n    fyn::S = fs(yn)\n    incfn(o)\n\n    fp, issue = _fbracket_ratio(yn, xn, wn, fyn, fxn, fwn)\n    if issue\n        o.xn0, o.xn1 = xn, yn\n        o.fxn0, o.fxn1 = fxn, fyn\n        o.message = \"issue with f[xn,yn]*f[yn,wn]/f[xn,wn]\"\n        o.stopped = true\n        return\n    end\n\n\n\n    zn = yn - fyn / fp\n    fzn::S = fs(zn)\n    incfn(o)\n\n    fp, issue = _fbracket_diff(xn, yn, zn, fxn, fyn, fzn)\n    u2, u3, u4 = fzn/fwn, fyn/fxn, fyn/fwn\n\n    \n    eta = 1 / (1 + 2*u3*u4^2) / (1 - u2)\n    if issue\n        o.xn0, o.xn1 = xn, zn\n        o.fxn0, o.fxn1 = fxn, fzn\n        o.stopped = true\n        o.message = \"Approximate derivative failed\"\n        return\n    end\n\n    an = zn - eta * fzn / fp\n    fan::S = fs(an)\n    incfn(o)\n\n        \n    fp, issue = _fbracket_ratio(an, yn, zn, fan, fyn, fzn)\n    if issue\n        o.xn0, o.xn1 = xn, an\n        o.fxn0, o.fxn1 = fxn, fan\n        o.stopped = true\n        o.message = \"Approximate derivative failed\"\n        return\n    end\n\n    u1, u5, u6 = fzn/fxn, fan/fxn, fan/fwn\n\n    fp1, issue = _fbracket(xn,yn, fxn, fyn)\n    \n    sigma =  1 + u1*u2 - u1*u3*u4^2 + u5 + u6 + u1^2*u4 +\n    u2^2*u3 + 3*u1*u4^2*(u3^2 - u4^2)/(fp1/oneunit(fp1))\n\n\n    xn1 = an - sigma * fan / fp\n    fxn1::S = fs(xn1)\n    incfn(o)\n\n    o.xn0, o.xn1 = xn, xn1\n    o.fxn0, o.fxn1 = fxn, fxn1\n\n    nothing\nend\n\n\n", "meta": {"hexsha": "cb5a83af596fe44b91a8bf2acae6ddc24ec7f856", "size": 11095, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/derivative_free.jl", "max_stars_repo_name": "ksmcreynolds/Roots.jl", "max_stars_repo_head_hexsha": "022de5dcc477c17ceeb28e4db400f35cf58859bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/derivative_free.jl", "max_issues_repo_name": "ksmcreynolds/Roots.jl", "max_issues_repo_head_hexsha": "022de5dcc477c17ceeb28e4db400f35cf58859bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/derivative_free.jl", "max_forks_repo_name": "ksmcreynolds/Roots.jl", "max_forks_repo_head_hexsha": "022de5dcc477c17ceeb28e4db400f35cf58859bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3311403509, "max_line_length": 113, "alphanum_fraction": 0.5879224876, "num_tokens": 3771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7513851055743331}}
{"text": "\"\"\"\n\n```\neulermat(beta, gamma, theta, deg::String)\n```\n\nThis routine was added because it defines \nthe rotation in the \"human\" way, an is thus used\nto set the position of the fixed molecules. `deg` can only be `\"degree\"`, in which\ncase the angles with be considered in degrees. If no `deg` argument\nis provided, radians are used.\n\nThat means: `beta` is a counterclockwise rotation around `x` axis.\n            `gamma` is a counterclockwise rotation around `y` axis.\n            `theta` is a counterclockwise rotation around `z` axis.\n\n\n\"\"\"\nfunction eulermat(beta, gamma, theta, deg::String)\n\n    if deg != \"degree\"\n        error(\"ERROR: to use radians just omit the last parameter\")\n    end\n\n    beta = beta * π / 180\n    gamma = gamma * π / 180\n    theta = theta * π / 180\n\n    return eulermat(beta, gamma, theta)\nend\n\nfunction eulermat(beta::T, gamma::T, theta::T) where {T}\n    c1 = cos(beta)\n    s1 = sin(beta)\n    c2 = cos(gamma)\n    s2 = sin(gamma)\n    c3 = cos(theta)\n    s3 = sin(theta)\n    @SMatrix [\n        c2*c3 -c2*s3 s2\n        (c1*s3+c3*s1*s2) (c1*c3-s1*s2*s3) -c2*s1\n        (s1*s3-c1*c3*s2) (c1*s2*s3+c3*s1) c1*c2\n    ]\nend\n", "meta": {"hexsha": "e75318d2d729616fa5925e18cb3adf4fc14db313", "size": 1141, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/eulermat.jl", "max_stars_repo_name": "m3g/MDDF", "max_stars_repo_head_hexsha": "efbc8e0dcf426c9b2246217eb9edaf4605318e84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-04T21:33:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-04T21:33:56.000Z", "max_issues_repo_path": "src/eulermat.jl", "max_issues_repo_name": "m3g/MDDF", "max_issues_repo_head_hexsha": "efbc8e0dcf426c9b2246217eb9edaf4605318e84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-31T00:18:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-23T20:04:16.000Z", "max_forks_repo_path": "src/eulermat.jl", "max_forks_repo_name": "m3g/ComplexMixtures", "max_forks_repo_head_hexsha": "efbc8e0dcf426c9b2246217eb9edaf4605318e84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3555555556, "max_line_length": 82, "alphanum_fraction": 0.6231375986, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.947381048137938, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7513735565830632}}
{"text": "# This file includes chaotic maps \n\nexport Logistic, Cubic, Tent, Henon, Bernoulli, \n    Lorenz, Chua, Rossler,  \n    trajectory!, normalize \n\nabstract type AbstractOscillator end \nabstract type AbstractDiscreteOscillator <: AbstractOscillator  end\nabstract type AbstractContinuousOscillator <: AbstractOscillator  end\n\n# ----------------------------- Discrete Time Maps --------------------------------- # \n\nstruct Cubic <: AbstractDiscreteOscillator \n    a::Float64 \n    b::Float64 \n    x::Vector{Float64} \n    t::Float64\nend\nCubic() = Cubic(4, 3, rand(1), 0.) \n(cmap::Cubic)(dx, x, u, t) = ( dx[1] = cmap.a * x[1]^3 - cmap.b * x[1] )\n\nstruct Tent <: AbstractDiscreteOscillator\n    a::Float64 \n    b::Float64 \n    c::Float64 \n    x::Vector{Float64}\n    t::Float64 \nend \nTent() = Tent(0.6, 0.6, 0.4, rand(1), 0.) \n(cmap::Tent)(dx, x, u, t) = ( dx[1] = 0 ≤ x[1] ≤ cmap.a ? x[1] / cmap.b : (1 - x[1]) / cmap.c )\n\nstruct Henon <: AbstractDiscreteOscillator\n    a::Float64 \n    b::Float64 \n    x::Vector{Float64} \n    t::Float64 \nend \nHenon() = Henon(1.4, 0.3, rand(2), 0.)\n\nfunction (cmap::Henon)(dx, x, u, t)\n    dx[1] = 1 + x[2] - cmap.a * x[1]^2\n    dx[2] = cmap.b * x[1]\nend \n\nstruct Bernoulli <: AbstractDiscreteOscillator\n    a::Float64 \n    x::Vector{Float64} \n    t::Float64 \nend \nBernoulli() = Bernoulli(1.2, rand(1), 0.) \n(cmap::Bernoulli)(dx, x, u, t) = ( dx[1] = x[1] < 0 ? cmap.a * x[1] + 1 : cmap.a * x[1] - 1 )\n\n# ----------------------------- Continuous Time Maps --------------------------------- # \n\nstruct Lorenz <: AbstractContinuousOscillator\n    σ::Float64 \n    β::Float64 \n    ρ::Float64 \n    γ::Float64\n    x::Vector{Float64} \n    t::Float64 \nend \nLorenz() = Lorenz(10, 8 / 3, 28, 1, rand(3), 0) \n\nfunction (cmap::Lorenz)(dx, x, u, t) \n    dx[1] = cmap.σ * (x[2] - x[1]) \n    dx[2] = x[1] * (cmap.ρ - x[3]) - x[2] \n    dx[3] = x[1] * x[2] - cmap.β * x[3]\nend \n\nstruct Diode \n    a::Float64 \n    b::Float64\n    bp::Float64 \nend\nDiode() = Diode(-1.143, -0.714, 1.) \nfunction (diode::Diode)(x) \n    if x < -cmap.bp \n        cmap.b * x + (cmap.b - cmap.a) * cmap.bp\n    elseif -cmap.bp ≤ x ≤ cmap.bp \n        cmap.a * x\n    elseif x > cmap.bp \n        cmap.b * x +  (cmap.a - cmap.b) * bp1\n    end \nend \n\nstruct Chua <: AbstractContinuousOscillator\n    α::Float64 \n    β::Float64 \n    h::Diode \n    x::Vector{Float64} \n    t::Float64\nend\nChua() = Chua(15, 28, Diode(), rand(3), 0.)\n\nfunction (cmap::Chua)(dx, x, u, t) \n    dx[1] = cmap.α * (x[2] - x[1] - cmap.h(x[1]))\n    dx[2] = x[1] - x[2] + x[3] \n    dx[3] = -β * x[2] \nend \n\n\nstruct Rossler <: AbstractContinuousOscillator\n    a::Float64 \n    b::Float64 \n    c::Float64 \n    x::Vector{Float64} \n    t::Float64 \nend \nRossler() = Rossler(0.38, 0.3, 4.82, rand(3), 0.)\n\nfunction (cmap::Rossler)(dx, x, u, t)\n    dx[1] = -x[2] - x[3]\n    dx[2] = x[1] + cmap.a * x[2]\n    dx[3] = cmap.b + x[3] * (x[1] - cmap.c)\nend\n\n# --------------------------------------- Methods  -------------------------------------- # \n\n\"\"\"\n   $SIGNATURES\n\nNormalizes (zero mean and unity variance)  `x`.  \n\"\"\"\nnormalize(x) = (x .- mean(x)) / std(x)\n\n\"\"\"\n    $SIGNATURES\n\nReturns the dimension of the state space of `cmap`. \n\"\"\"\nstatedim(cmap::AbstractOscillator) = length(cmap.x)\n\n\"\"\"\n    $SIGNATURES\n\nReturns a trajectory! of `camp` for a time span of `trange`. `idx` is the indices of trajectory! to be returned. \n\"\"\"\nfunction trajectory! end \n\nfunction trajectory!(cmap::AbstractDiscreteOscillator, trange, idx=1)\n    sol = solve(DiscreteProblem(cmap, cmap.x, (cmap.t, cmap.t + trange)))\n    cmap.t = sol.t[end] \n    cmap.x = sol.u[end]\n    map(i -> normalize(getindex.(sol.u, i)), idx) \nend\n\nfunction trajectory!(cmap::AbstractContinuousOscillator, trange, tsample, idx=1) \n    sol = solve(ODEProblem(cmap, cmap.x, (cmap.t, cmap.t + trange)), saveat=tsample)\n    cmap.t = sol.t[end] \n    cmap.x = sol.u[end]\n    map(i -> normalize(getindex.(sol.u, i)), idx) \nend \n\n\n", "meta": {"hexsha": "4a813063e9bb01b290dc406c0151a154881f31b1", "size": 3913, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/maps.jl", "max_stars_repo_name": "zekeriyasari/ChaoticCommunications.jl", "max_stars_repo_head_hexsha": "79e85609165bf6fa96b63a1e3276f4ff756a3ada", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-07T00:05:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-07T00:05:58.000Z", "max_issues_repo_path": "src/maps.jl", "max_issues_repo_name": "zekeriyasari/ChaoticCommunications.jl", "max_issues_repo_head_hexsha": "79e85609165bf6fa96b63a1e3276f4ff756a3ada", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-17T17:45:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-17T17:45:56.000Z", "max_forks_repo_path": "src/maps.jl", "max_forks_repo_name": "zekeriyasari/ChaoticCommunications.jl", "max_forks_repo_head_hexsha": "79e85609165bf6fa96b63a1e3276f4ff756a3ada", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0833333333, "max_line_length": 113, "alphanum_fraction": 0.5545617174, "num_tokens": 1442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809827, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7513735530482254}}
{"text": "\"\"\"\nSolving the travelling salesman problem.\n\nif you have a costs square symetric matrix with diagonal equal to zero use the function solve_TSP()\nif you have the set of (x,y) coordinates then use the function hacematrixdedistancias() first to generate the costs matrix\n\nThe function solve_TSP give the minimun costs posible and the elements of the costs matrix that minimize the costs the travel\n\"\"\"\nfunction solve_TSP(costs_matrix)\n    N=size(costs_matrix)[1]\n    if N==size(costs_matrix)[2];\n        m = JuMP.Model(JuMP.with_optimizer(GLPK.Optimizer))\n        @variable(m, x[1:N,1:N], Bin)\n\n        @objective(m, Min, sum(costs_matrix.*x))\n        @constraint(m, notself[i=1:N], x[i,i] == 0)\n        @constraint(m, goto[i=1:N], sum(x[i,1:N]) == 1)\n        @constraint(m, cometo[j=1:N], sum(x[1:N,j]) == 1)\n        @variable(m, t[1:N], Int)\n        for i=1:N,j=2:N\n            if i!=j\n                @constraint(m,t[j]>=t[i]+1-N*(1-x[i,j]))\n            end\n        end\n\n        optimize!(m)\n        println(\"El coste optimo es: \")\n        println(objective_value(m))\n        for i=1:N\n            for j=1:N\n                if value(x[i,j])!=0\n                    println(\"d[$i,$j]=\",costs_matrix[i,j])\n                end\n            end\n        end\n    else println(\"La matriz debe ser cuadrada, con diagonal principal =0 y simetrica\")\n    end\n\nend\n\nfunction hacematrixdedistancias(listadeptos)\n    distmatrix=zeros(Float64,(length(listadeptos),length(listadeptos)));\n    for i=1:length(listadeptos)\n        for j=1:length(listadeptos)\n            distmatrix[i,j]=distanciacartesiana(listadeptos[i],listadeptos[j])\n        end\n    end\n    return distmatrix;\nend\n\nfunction distanciacartesiana(pto1,pto2)\n    dis=sqrt((pto1[1]-pto2[1])^2+(pto1[2]-pto2[2])^2);\n    return dis;\nend\n", "meta": {"hexsha": "ef35f7331be5894f5516951bd649848ff5e9b077", "size": 1781, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solving_TSP.jl", "max_stars_repo_name": "jesusalba9504/TravellingSalesmanProblem.jl", "max_stars_repo_head_hexsha": "c3d6ea6fe02ab014eded0b11fa58c939d1b611ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/solving_TSP.jl", "max_issues_repo_name": "jesusalba9504/TravellingSalesmanProblem.jl", "max_issues_repo_head_hexsha": "c3d6ea6fe02ab014eded0b11fa58c939d1b611ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solving_TSP.jl", "max_forks_repo_name": "jesusalba9504/TravellingSalesmanProblem.jl", "max_forks_repo_head_hexsha": "c3d6ea6fe02ab014eded0b11fa58c939d1b611ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3818181818, "max_line_length": 125, "alphanum_fraction": 0.6097697923, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809827, "lm_q2_score": 0.793105941403651, "lm_q1q2_score": 0.7513735345165792}}
{"text": "using Printf\nusing PyPlot\n\nfunction inverse_const(r)\n    B = [ 1 / (i+j-1) for i = 1:r+1, j=1:r+1 ]\n    D = zeros(r+1, r+1)\n    for j = 2:r+1\n        for i = 2:r+1\n            D[i,j] = (i-1)*(j-1) / (i+j-3)\n        end\n    end\n    F = eigen(D, B)\n    λmax = F.values[r+1]\n    amax = F.vectors[:,r+1]\n    return λmax, amax\nend\n\nfigure(1)\nξ = range(0, stop=1, length=201)\n@printf(\"\\n%4s %8s\\n\\n\", \"r\", \"Cr\")\nfor r = 0:3\n    Cr, ar = inverse_const(r)\n    pr = Poly(ar, :ξ)\n    plot(ξ, polyval(pr, ξ))\n    @printf(\"%4d& %8.2f\\\\\\\\\\n\", r, Cr)\nend\ngrid(true)\n", "meta": {"hexsha": "ec508e4f9a92453d8754eceb2fbe5b8a4ec78b4f", "size": 552, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chap4/inverse_ineq.jl", "max_stars_repo_name": "billmclean/ComputationalMathsNotes", "max_stars_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T21:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:30:20.000Z", "max_issues_repo_path": "src/chap4/inverse_ineq.jl", "max_issues_repo_name": "billmclean/ComputationalMathsNotes", "max_issues_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chap4/inverse_ineq.jl", "max_forks_repo_name": "billmclean/ComputationalMathsNotes", "max_forks_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7142857143, "max_line_length": 46, "alphanum_fraction": 0.4891304348, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.7905303285397348, "lm_q1q2_score": 0.7513287019082037}}
{"text": "include(\"Graph.jl\")\n\nusing SparseArrays\nusing LinearAlgebra\n\nfunction OutDegree(G)\n    C = zeros(G.n)\n    for (u, v, w) in G.E\n        C[u] += w\n    end\n    return C\nend\n\nfunction spA(G)\n    Is = zeros(Int, G.m)\n    Js = zeros(Int, G.m)\n    Vs = zeros(G.m)\n    ID = 0\n    for (u, v, w) in G.E\n        ID += 1\n        Is[ID] = u\n        Js[ID] = v\n        Vs[ID] = w\n    end\n    return sparse(Is, Js, Vs, G.n, G.n)\nend\n\nfunction alpP(G, alp)\n    d = OutDegree(G)\n    Is = zeros(Int, G.m)\n    Js = zeros(Int, G.m)\n    Vs = zeros(G.m)\n    ID = 0\n    for (u, v, w) in G.E\n        ID += 1\n        Is[ID] = v\n        Js[ID] = u\n        Vs[ID] = alp * w / d[u]\n    end\n    return sparse(Is, Js, Vs, G.n, G.n)\nend\n\nfunction PageRank(G; alpha = 0.85)\n    aP = alpP(G, alpha)\n    C = zeros(G.n)\n    C[1] = 1.0\n    adC = ((1.0 - alpha) / G.n) * ones(G.n)\n\n    while true\n        pC = copy(C)\n        C = aP * C + adC\n        if norm(C - pC) < 1e-12\n            break\n        end\n    end\n\n    return C\nend\n\nfunction EigenvectorCentrality(G)\n    C = zeros(G.n)\n    C[1] = 1.0\n    A = spA(G)\n\n    while true\n        pC = copy(C)\n        C = A * C\n        C ./= C[argmax(C)]\n        if norm(C - pC) < 1e-9\n            break\n        end\n    end\n\n    return C\nend\n\nfunction getPc(C; eps = 1e-9)\n    A = copy(C)\n    n = size(A, 1)\n    sort!(A)\n    sum = 0.0\n    for i = 1 : n\n        ts = 0.0\n        for j = i-1 : -1 : 1\n            if abs(A[i] - A[j]) < eps\n                ts += 1.0\n            else\n                break\n            end\n        end\n        for j = i+1 : n\n            if abs(A[i] - A[j]) < eps\n                ts += 1.0\n            else\n                break\n            end\n        end\n        sum += ts\n    end\n    sum /= (n * (n - 1))\n    return (1.0 - sum) * 100\nend\n", "meta": {"hexsha": "6df26bc205c6ed491855ec76294bc2651eb94cba", "size": 1774, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dirExp/Centrality.jl", "max_stars_repo_name": "Accelerator950113/DPnode", "max_stars_repo_head_hexsha": "485c9f3751ba7ebd21fe42080558ea7d30223e06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dirExp/Centrality.jl", "max_issues_repo_name": "Accelerator950113/DPnode", "max_issues_repo_head_hexsha": "485c9f3751ba7ebd21fe42080558ea7d30223e06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dirExp/Centrality.jl", "max_forks_repo_name": "Accelerator950113/DPnode", "max_forks_repo_head_hexsha": "485c9f3751ba7ebd21fe42080558ea7d30223e06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.2233009709, "max_line_length": 43, "alphanum_fraction": 0.4069898534, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410972802222, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.7513286985771096}}
{"text": "# example showing how to do maximum likelihood estimation\n# for data generated by CLRM with normality\n# sample size\nusing Econometrics, Distributions\nfunction main()\nn = 1000\n# random true parameters\ntheta = [1.0,-1.0,0.0,1.0]\nb = theta[1:3]\nsig = theta[4]\n# generate random data\nx = [ones(n,1) rand(n,2)]\ne = sig*randn(n,1)\ny = x*b + e\n# do ML\nobj = theta -> -mean(normal(theta, y, x))\nthetahat, logL, junk = fminunc(obj, theta)\nlogL = -logL\n# restricted ML\nR = [0 1 0 0]\nr = -1.5\nthetahatr, logLr, junk = fmincon(obj, theta, R, r)\nlogLr = -logLr\n# LR rest\nLR = 2.0*n*(logL-logLr)\n# results\nprintln(\"the true parameters: \", theta)\nprintln(\"the ML estimates: \", thetahat)\nprintln(\"the restricted ML estimates: \", thetahatr)\nprintln(\"the LR test: \", LR);\nprintln(\"p-value of the LR test: \", 1.0-cdf(Chisq(1),LR))\nend\nmain()\n", "meta": {"hexsha": "c8d94a72b853884ca18721d84a24551903ac6e4e", "size": 823, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/MLE/LikelihoodRatioTest.jl", "max_stars_repo_name": "Hiroakiyusheng/Econometrics", "max_stars_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "Examples/MLE/LikelihoodRatioTest.jl", "max_issues_repo_name": "Hiroakiyusheng/Econometrics", "max_issues_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "Examples/MLE/LikelihoodRatioTest.jl", "max_forks_repo_name": "Hiroakiyusheng/Econometrics", "max_forks_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 24.2058823529, "max_line_length": 57, "alphanum_fraction": 0.6755771567, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7513286972178971}}
{"text": "module Arithmetic\nexport evaluate, Constant, BinaryOp, ADD, SUB, MUL, DIV\n\nabstract type Expression end\n\nstruct Constant{T} <: Expression\n  value::T\nend\n\n@enum Op begin\n  ADD = 1\n  SUB = 2\n  MUL = 3\n  DIV = 4\nend\n\nstruct BinaryOp{T1, T2} <: Expression\n  left::T1\n  op::Op\n  right::T2\nend\n\nevaluate(expr::Constant) = expr.value\n\nfunction evaluate(expr::BinaryOp)\n  left_val = evaluate(expr.left)\n  right_val = evaluate(expr.right)\n  if expr.op == ADD\n    return left_val + right_val\n  elseif expr.op == SUB\n    return left_val - right_val\n  elseif expr.op == MUL\n    return left_val * right_val\n  elseif expr.op == DIV\n    return left_val / right_val\n  else \n    throw(error(\"Unknown op while evaluating BinaryOp\"))\n  end\nend\n\nend # module", "meta": {"hexsha": "d84659a43f8d4a60ccdcc8e9af861219f09ff44c", "size": 738, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ExampleModels/Arithmetic/src/Arithmetic.jl", "max_stars_repo_name": "zenna/Ailuj.jl", "max_stars_repo_head_hexsha": "d36486b7b7b33cca25242dcadc519e9f11318ffd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-07-27T08:51:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T10:04:14.000Z", "max_issues_repo_path": "ExampleModels/Arithmetic/src/Arithmetic.jl", "max_issues_repo_name": "zenna/ParametricInversion.jl", "max_issues_repo_head_hexsha": "d36486b7b7b33cca25242dcadc519e9f11318ffd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2020-06-28T01:16:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-29T19:24:34.000Z", "max_forks_repo_path": "ExampleModels/Arithmetic/src/Arithmetic.jl", "max_forks_repo_name": "zenna/Ailuj.jl", "max_forks_repo_head_hexsha": "d36486b7b7b33cca25242dcadc519e9f11318ffd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-12-06T04:43:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T08:27:35.000Z", "avg_line_length": 18.0, "max_line_length": 56, "alphanum_fraction": 0.6924119241, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.7905303236047048, "lm_q1q2_score": 0.751328697217897}}
{"text": "using LinearAlgebra\nusing Plots \n\n# sphere to capsule \n\n# capsule points\nca = [0.0; 0.0; 0.0] \ncb = [0.0; 0.0; 1.0] \n\n# sphere point\ns = [0.0; 1.0; -1.0] \n\ndab = cb - ca\ndas = s - ca\n\nlen = dot(dab, dab)\n\nt = dot(das, dab) ./ dot(dab, dab)\nt_clamp = min(max(t, 0.0), 1.0)\n\n# closest point \nif t <= 0.0 \n    p = ca \nelseif t >= 1.0 \n    p = cb \nelse\n    p = ca + t * dab\nend\n\n\n###\n# https://stackoverflow.com/questions/44824512/how-to-find-the-closest-point-on-a-right-rectangular-prism-3d-rectangle/44824522#44824522\nusing LinearAlgebra\np = [0.0; 1.0; 1.0]\norigin = [0.0; 0.0; 0.0] \nr = 0.5 \nv1 = [r; 0.0; 0.0]\nv2 = [0.0; r; 0.0] \nv3 = [0.0; 0.0; r] \n\ntx = dot(p - origin, v1) / dot(v1, v1) \nty = dot(p - origin, v2) / dot(v2, v2) \ntz = dot(p - origin, v3) / dot(v3, v3)\n\ntx_clamp = min(max(tx, 0.0), 1.0)\nty_clamp = min(max(ty, 0.0), 1.0)\ntz_clamp = min(max(tz, 0.0), 1.0)\n\ncp = tx_clamp * v1 + ty_clamp * v2 + tz_clamp * v3 + origin\n\n", "meta": {"hexsha": "59c9cdab070e02e2961b17c3dc24e8b80d2991ae", "size": 936, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/simulation/dev/tests.jl", "max_stars_repo_name": "dojo-sim/Dojo.jl", "max_stars_repo_head_hexsha": "33ccdde8d7f74c4ea3c3bffdebcc6ed65959a5be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70, "max_stars_repo_stars_event_min_datetime": "2022-03-02T01:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:14:51.000Z", "max_issues_repo_path": "examples/simulation/dev/tests.jl", "max_issues_repo_name": "dojo-sim/Dojo.jl", "max_issues_repo_head_hexsha": "33ccdde8d7f74c4ea3c3bffdebcc6ed65959a5be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2022-03-02T06:58:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T17:17:26.000Z", "max_forks_repo_path": "examples/simulation/dev/tests.jl", "max_forks_repo_name": "dojo-sim/Dojo.jl", "max_forks_repo_head_hexsha": "33ccdde8d7f74c4ea3c3bffdebcc6ed65959a5be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2022-03-07T01:47:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T19:13:07.000Z", "avg_line_length": 18.3529411765, "max_line_length": 136, "alphanum_fraction": 0.5694444444, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109728022221, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.7513286962319564}}
{"text": "module TargetFunction\n\nimmutable ObjFun\n    name::ASCIIString\n    f_x::Function\n    g_x::Function\n    about_alpha::Function\n    about_alpha_prime::Function\nend\n\n\nfunction f_x(x::Array{Float64, 1})\n    f = 10.0 * (x[2] - x[1]*x[1])*(x[2] - x[1]*x[1]) + (1 - x[1])*(1 - x[1])\n    return f\nend\n\nfunction g_x(x::Array{Float64, 1})\n    g1 = -40.0 * (x[1]*x[2] - x[1]*x[1]*x[1]) - 2.0 + 2.0 * x[1]\n    g2 = 20.0 * (x[2] - x[1]*x[1])\n    return [g1; g2]\nend\n\nfunction about_alpha(x::Array{Float64, 1}, s::Array{Float64, 1})\n    function along_s(alpha::Float64)\n        return f_x(x + s*alpha)\n    end\n    return along_s\nend\n\nfunction about_alpha_prime(x::Array{Float64, 1}, s::Array{Float64, 1})\n    function along_s(alpha::Float64)\n        return g_x(x + alpha * s)' * s\n    end\n    return along_s\nend\n\nrosenbrock = ObjFun(\"Rosenbrock\", f_x, g_x, about_alpha, about_alpha_prime)\n\nend\n", "meta": {"hexsha": "7015e2eb7cf481268062cf6bd832d35296f8bab4", "size": 878, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jl/TargetFunction.jl", "max_stars_repo_name": "wyli/gradient", "max_stars_repo_head_hexsha": "ae6b4bdb39a6977388213ef5038e6e42659d399b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-02-25T15:54:40.000Z", "max_stars_repo_stars_event_max_datetime": "2016-02-25T15:54:40.000Z", "max_issues_repo_path": "jl/TargetFunction.jl", "max_issues_repo_name": "wyli/gradient", "max_issues_repo_head_hexsha": "ae6b4bdb39a6977388213ef5038e6e42659d399b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jl/TargetFunction.jl", "max_forks_repo_name": "wyli/gradient", "max_forks_repo_head_hexsha": "ae6b4bdb39a6977388213ef5038e6e42659d399b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.95, "max_line_length": 76, "alphanum_fraction": 0.6082004556, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109728022221, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.7513286962319563}}
{"text": "using StanModels, StanSample, MCMCChains, CSV\n\ndf = CSV.read(stanmodels_path(\"..\", \"data\", \"WaffleDivorce.csv\"), DataFrame)\nStanModels.scale!(df, [:MedianAgeMarriage])\n\n# Define the Stan language model\n\nm5_1s = \"\ndata {\n int < lower = 1 > N; // Sample size\n vector[N] divorce; // Predictor\n vector[N] median_age; // Outcome\n}\n\nparameters {\n real a; // Intercept\n real bA; // Slope (regression coefficients)\n real < lower = 0 > sigma; // Error SD\n}\n\nmodel {\n  # priors\n  a ~ normal(10, 10);\n  bA ~ normal(0, 1);\n  sigma ~ uniform(0, 10);\n  \n  # model\n  divorce ~ normal(a + bA*median_age , sigma);\n}\n\";\n\n# Define the Stanmodel and set the output format to :mcmcchains.\n\nm_5_1s = SampleModel(\"m5.1s\", m5_1s);\n\n# Input data for cmdstan\n\nm5_1_data = Dict(\"N\" => length(df[!, :Divorce]), \"divorce\" => df[!, :Divorce],\n    \"median_age\" => df[!, :MedianAgeMarriage_s]);\n\n# Sample using cmdstan\n\nrc = stan_sample(m_5_1s, data=m5_1_data);\n\n# Result rethinking\n\nrethinking = \"\n       mean   sd  5.5% 94.5% n_eff Rhat\na      9.69 0.22  9.34 10.03  2023    1\nbA    -1.04 0.21 -1.37 -0.71  1882    1\nsigma  1.51 0.16  1.29  1.79  1695    1\n\"\n\n# Describe the draws\nif success(rc)\n  chn = read_samples(m_5_1s; output_format=:mcmcchains)\n  show(chn)\nend\n\n", "meta": {"hexsha": "1eea20ab11fb03999b1b18272ac59c18f02b9ec4", "size": 1239, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/05/m5.1s.jl", "max_stars_repo_name": "statisticalrethinking/StatisticalRethinkingStan.jl", "max_stars_repo_head_hexsha": "cbb7e3cf8547262b0e2b980f3f002937616e6b19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-03-08T16:01:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T08:09:28.000Z", "max_issues_repo_path": "scripts/05/m5.1s.jl", "max_issues_repo_name": "statisticalrethinking/StatisticalRethinkingStan.jl", "max_issues_repo_head_hexsha": "cbb7e3cf8547262b0e2b980f3f002937616e6b19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2019-08-16T00:01:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-03T11:38:28.000Z", "max_forks_repo_path": "scripts/05/m5.1s.jl", "max_forks_repo_name": "statisticalrethinking/StatisticalRethinkingStan.jl", "max_forks_repo_head_hexsha": "cbb7e3cf8547262b0e2b980f3f002937616e6b19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.65, "max_line_length": 78, "alphanum_fraction": 0.6440677966, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109784205502, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7513286912928014}}
{"text": "module Forward\n\nexport Dual, ind_var\n\nstruct Dual{T<:AbstractFloat} <: AbstractFloat\n    value::T\n    grad::T\nend\n\n#===== Operations =====#\n# https://en.wikipedia.org/wiki/Automatic_differentiation#Automatic_differentiation_using_dual_numbers\n\nimport Base: +, -, *, /, ^\nu::Dual + v::Dual = Dual(u.value + v.value, u.grad + v.grad)\nu::Dual - v::Dual = Dual(u.value - v.value, u.grad - v.grad)\nu::Dual * v::Dual = Dual(u.value * v.value, v.value * u.grad + u.value * v.grad)\nu::Dual / v::Dual = Dual(u.value * v.value, (v.value * u.grad - u.value * v.grad) / (v.value ^ 2))\n\nu::Dual ^ k::Int = Dual(u.value ^ k, k * (u.value ^ (k - 1)) * u.grad)\n\nBase.sin(u::Dual) = Dual(sin(u.value), u.grad * cos(u.value))\nBase.cos(u::Dual) = Dual(cos(u.value), -u.grad * sin(u.value))\n\nBase.exp(u::Dual) = begin\n    exp_u = exp(u.value)\n    Dual(exp_u, u.grad * exp_u)\nend\nBase.log(u::Dual) = Dual(log(u.value), u.grad / u.value)\n\n#===== Conversions =====#\n\nfunction Base.convert(::Type{Dual{T}}, x::Dual) where T\n    Dual(convert(T, x.value), convert(T, x.grad))\nend\n\nfunction Base.convert(::Type{Dual{T}}, x::AbstractFloat) where T\n    Dual(convert(T, x), zero(T))\nend\n\nfunction Base.promote_rule(::Type{Dual{T}}, ::Type{U}) where {T, U}\n    Dual{promote_type(T, U)}\nend\n\n\"Independent variable\"\nind_var(x::AbstractFloat) = Dual(x, one(x))\n\nend\n", "meta": {"hexsha": "6ccabe8d5b709a53231b087eb0fc0693f1e09db2", "size": 1332, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "AutomaticDifferentiation/src/forward.jl", "max_stars_repo_name": "gyk/TrivialSolutions", "max_stars_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T05:51:37.000Z", "max_issues_repo_path": "AutomaticDifferentiation/src/forward.jl", "max_issues_repo_name": "gyk/TrivialSolutions", "max_issues_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AutomaticDifferentiation/src/forward.jl", "max_forks_repo_name": "gyk/TrivialSolutions", "max_forks_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.75, "max_line_length": 102, "alphanum_fraction": 0.6306306306, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109784205502, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.7513286842573411}}
{"text": "# generalised OU\ninclude(\"common.jl\")\nimport SDELab2\n################### problem parameters\nT=1 # time step, final time\nx0=1. # initial data\nalp=-1/2 # drift parameter\nbet= 4/5 # drift parameter\nsig=sqrt(1/2) # diffusion param\nquad0=SDELab2.delta_measure(x0)\n###########################################\nfunction drift(u,alp,bet)\n  x=u[1]; mf=u[2]\n  return alp*x+bet*mf\nend\n##########################################\nfunction diff(u,sig)\n  return sig\nend\n#######################################\nfunction mf_r(x)\n  return [x]\nend\n##########################################\nfcn=SDELab2.set_fcn_mf(u->drift(u,alp,bet),\n          u->diff(u,sig),\n          x->mf_r(x))\n# test function\nphi=x->[x;x.^2]\n###################################### exact\nexact_mean=x0*exp((alp+bet));\nexact_var=(sig^2)/(2*alp)*exp(2*alp)-sig^2/(2*alp);\nexact_mom2=exact_var+exact_mean^2;\nexact=[exact_mean,exact_mom2];\nprintln(\"ode soln \",exact)\n##################################### method parameters\ndt=1e-3\nsolver=\"MFEM0\"\nparams=SDELab2.set_opt(dt,solver)\nparams[\"cutoff\"]=10 # radius R for Alg 3.1\nparams[\"const\"]=1e3 # for no_Gauss_points\nparams[\"length_scale\"]=1 # for no_Gauss_points\nparams[\"skiphalf\"]=true\nparams[\"periodic\"]=false\nparams[\"no_partition\"]=1\ndtpts=[0.2,0.1,0.05,0.025,0.01,0.005]#,0.0025,0.001]\nerrors=zeros(length(dtpts),2)\nerrors_no=deepcopy(errors)\nerrors_nd=deepcopy(errors)\ncpu_times=zeros(length(dtpts))\ncpu_times_no=deepcopy(cpu_times)\ncpu_times_nd=deepcopy(cpu_times)\n\n\nparams[\"Solver\"]=\"MFEM0\"\ndtpts_no=dtpts/4\nfor i=1:(length(dtpts))\n    params[\"MaxStepSize\"]=dtpts_no[i]\n    qoi,cpu_time,stats,q=get_soln(fcn,quad0,params,phi,false)\n    errors_no[i,:],cpu_times_no[i]=helper(qoi, exact, cpu_time, \"normal\")\nend\n########################\nparams[\"Solver\"]=\"MFEM0\"\nfor i=1:(length(dtpts))\n    params[\"MaxStepSize\"]=dtpts[i]\n    qoi,cpu_time,stats,q=get_soln(fcn,quad0,params,phi,true)\n    errors[i,:],cpu_times[i]=helper(qoi, exact, cpu_time, \"normal\")\nend\n################\nparams[\"Solver\"]=\"MFEM2\"\nfor i=1:(length(dtpts))\n    params[\"MaxStepSize\"]=dtpts[i]\n    qoi,cpu_time,stats,q=get_soln(fcn,quad0,params,phi,false)\n    errors_nd[i,:],cpu_times_nd[i]=helper(qoi, exact, cpu_time, \"normal\")\nend\n#########################################\n\nfigure(1);\n# first functional\ni=1\ntime_step_err(dtpts,errors[:,i],\n  dtpts_no,errors_no[:,i],\n  dtpts,errors_nd[:,i],[1e0,1e0],utf8(\"mom1.pdf\"))\nerr_cpu(errors[:,i],cpu_times[:],\n  errors_no[:,i],cpu_times_no[:],\n  errors_nd[:,i],cpu_times_nd[:],[1e0,1e0], utf8(\"mom1_.pdf\"))\n# second functional\ni=2\ntime_step_err(dtpts,errors[:,i],\n      dtpts_no,errors_no[:,i],\n      dtpts,errors_nd[:,i],[1e0,1],utf8(\"mom2.pdf\"))\nerr_cpu(errors[:,i], cpu_times[:],\n      errors_no[:,i],cpu_times_no[:],\n      errors_nd[:,i],cpu_times_nd[:],[1e0,1], utf8(\"mom2_.pdf\"))\n#########################################\nprintln(\"finished preparing plots\")\n", "meta": {"hexsha": "6c15b0a74db8babd7d3a50af644f0d9ffd24e928", "size": 2873, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/run_gq2.jl", "max_stars_repo_name": "fkastner/SDELab2.jl", "max_stars_repo_head_hexsha": "1790859a63afad80af24ced4e9cd776568776dca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-10-20T13:26:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-01T13:43:33.000Z", "max_issues_repo_path": "src/run_gq2.jl", "max_issues_repo_name": "fkastner/SDELab2.jl", "max_issues_repo_head_hexsha": "1790859a63afad80af24ced4e9cd776568776dca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-02-21T03:39:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-02T11:53:36.000Z", "max_forks_repo_path": "src/run_gq2.jl", "max_forks_repo_name": "fkastner/SDELab2.jl", "max_forks_repo_head_hexsha": "1790859a63afad80af24ced4e9cd776568776dca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-07-26T15:53:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T13:08:32.000Z", "avg_line_length": 29.618556701, "max_line_length": 73, "alphanum_fraction": 0.6056387052, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7513149256836424}}
{"text": "\"\"\"\n    power_method(x0,Hop,PARAM)\nPOWER_METHOD: Power iteration method to computes max eigenvalue of H'H\n              where H and H' are given by Hop. This function is\n              needed to evaluate the step parameter of FISTA.\n# Arguments\n- `x0`:initial seed with dimensions such that H'*H*x0 does not abort\n- `Hop`:liner operator that encapsulates H and H' such that\n        Hop(x,PARAM, 1) = H x\n        Hop(y,PARAM,-1) = H'y \n- `PARAM`:parameters to run Hop and it's adjoint\n\n\"\"\"\nfunction power_method(x0,Hop,PARAM)\n   #x = x0;\n   x=copy(x0);\n   value=0;\n    for k = 1:10;\n       aux = Hop(x,PARAM,1);\n       y = Hop(aux,PARAM,-1);\n       n = norm(y);\n       x = y/n;\n       value = n;\n    end\n    return value\nend\n", "meta": {"hexsha": "e0388334a0fca1e091215384ca7489bd6c188ba0", "size": 723, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Tools/power_method.jl", "max_stars_repo_name": "SeismicJulia/SeisReconstruction.jl", "max_stars_repo_head_hexsha": "aefcd9712bfb95e0c855c6d3c479125d8a9c7080", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-13T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T11:11:49.000Z", "max_issues_repo_path": "src/Tools/power_method.jl", "max_issues_repo_name": "SeismicJulia/SeisReconstruction.jl", "max_issues_repo_head_hexsha": "aefcd9712bfb95e0c855c6d3c479125d8a9c7080", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-11-18T21:58:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T22:19:13.000Z", "max_forks_repo_path": "src/Tools/power_method.jl", "max_forks_repo_name": "SeismicJulia/SeisReconstruction.jl", "max_forks_repo_head_hexsha": "aefcd9712bfb95e0c855c6d3c479125d8a9c7080", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-01-22T20:39:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T22:47:02.000Z", "avg_line_length": 26.7777777778, "max_line_length": 70, "alphanum_fraction": 0.5988934993, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.751253053749996}}
{"text": "function frenet_serret(coordinate::Matrix{T_Number}) where {T_Number<:Number}\n    r = copy(coordinate)\n    n_points = size(r, 1)\n    if size(r, 2) == 2\n        r = cat(r, zeros(eltype(r), size(r, 1)), dims = 2)\n    end\n    t = 1.0:size(r,1)\n    dt = (maximum(t) - minimum(t)) / length(r)\n    dr = gradient(r)\n    ddr = gradient(dr)\n    dddr = gradient(ddr)\n\n\n    T = similar(dr)\n    N = similar(dr)\n    B = similar(dr)\n\n    for i = 1:n_points\n\n        T[i, :] = LinearAlgebra.normalize(dr[i, :])\n\n        B[i, :] = LinearAlgebra.normalize(cross(dr[i, :], ddr[i, :]))\n\n        N[i, :] = LinearAlgebra.normalize(cross(B[i, :], T[i, :]))\n\n    end\n\n    ds = Array{eltype(dr),1}(undef, n_points)\n    curvature = similar(ds)\n    torsion = similar(ds)\n\n    for i in eachindex(ds)\n        selected_dr = dr[i, :]\n        selected_ddr = ddr[i, :]\n        selected_dddr = dddr[i, :]\n        ds[i] = norm(selected_dr)\n\n        dr_cross_ddr = cross(selected_dr, selected_ddr)\n        curvature_num = norm(dr_cross_ddr) # || dr X ddr ||\n        curvature_denom = norm(selected_dr)^3 # || dr ||^3\n        curvature[i] = curvature_num / curvature_denom\n\n        torsion_num = dot(dr_cross_ddr, selected_dddr) # (dr X ddr) . dddr\n        torsion_denom = norm(dr_cross_ddr)^2 # || dr X ddr ||^2\n        torsion[i] = torsion_num / torsion_denom\n    end\n    speed = ds ./ dt\n    return T,N,B,curvature,torsion,speed\nend\n", "meta": {"hexsha": "f97f49301baf1855d2d78ab2a6bf2d5792c28646", "size": 1400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/frenet_serret.jl", "max_stars_repo_name": "yusri-dh/MVApp.jl", "max_stars_repo_head_hexsha": "c5694839d2229982b0ae5cec7c18390019222c7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-28T07:25:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T11:59:15.000Z", "max_issues_repo_path": "src/frenet_serret.jl", "max_issues_repo_name": "yusri-dh/MovingFrame.jl", "max_issues_repo_head_hexsha": "1be0d7e4ec1f20d898dfbaf9f85e5b9ac86c7b6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/frenet_serret.jl", "max_forks_repo_name": "yusri-dh/MovingFrame.jl", "max_forks_repo_head_hexsha": "1be0d7e4ec1f20d898dfbaf9f85e5b9ac86c7b6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0, "max_line_length": 77, "alphanum_fraction": 0.5742857143, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.7512530364170006}}
{"text": "using LinearAlgebra\r\n\r\nfunction positive_definite(x,y)\r\n    Q = [6 -2; -2 6]\r\n    q = [0 ; 0]\r\n    return quadratic_function(x,y,Q,q)\r\nend\r\n\r\nfunction semi_positive_definite(x,y)\r\n    Q = [0 1; 0 1]\r\n    q = [0 ; 0]\r\n    return quadratic_function(x,y,Q,q)\r\nend\r\n\r\nfunction not_positive_definite(x,y)\r\n    Q = [-5 -2; -4 -2]\r\n    q = [0 ; 0]\r\n    return quadratic_function(x,y,Q,q)\r\nend\r\n\r\nfunction quadratic_function(x,y,Q,q)\r\n    Q_f = ([x y]*Q*[x ; y])[1] * 0.5\r\n    q_f = q' * [x ; y]\r\n    return Q_f + q_f\r\nend\r\n\r\n#derivatives\r\n\r\nfunction positive_definite_d(x,y)\r\n    Q = [6 -2; -2 6]\r\n    q = [0 ; 0]\r\n    return quadratic_function_d(x,y,Q,q)\r\nend\r\n\r\nfunction semi_positive_definite_d(x,y)\r\n    Q = [0 1; 0 1]\r\n    q = [0 ; 0]\r\n    return quadratic_function_d(x,y,Q,q)\r\nend\r\n\r\nfunction not_positive_definite_d(x,y)\r\n    Q = [-5 -2; -4 -2]\r\n    q = [0 ; 0]\r\n    return quadratic_function_d(x,y,Q,q)\r\nend\r\n\r\nfunction quadratic_function_d(x,y,Q,q)\r\n    return (Q*[x ; y]) + q\r\nend\r\n", "meta": {"hexsha": "e03d5c61ee0fac84cab189e7c366d9563d06c568", "size": 985, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "quadratic_function.jl", "max_stars_repo_name": "WilliamSimoni/Computational-Mathematics-Resources", "max_stars_repo_head_hexsha": "67aa6cd3f9125d26ad54c3027be8cd680ac88393", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quadratic_function.jl", "max_issues_repo_name": "WilliamSimoni/Computational-Mathematics-Resources", "max_issues_repo_head_hexsha": "67aa6cd3f9125d26ad54c3027be8cd680ac88393", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quadratic_function.jl", "max_forks_repo_name": "WilliamSimoni/Computational-Mathematics-Resources", "max_forks_repo_head_hexsha": "67aa6cd3f9125d26ad54c3027be8cd680ac88393", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7, "max_line_length": 41, "alphanum_fraction": 0.5705583756, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465188527684, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7512458166595483}}
{"text": "# Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/\n#  Niccolò Antonello <nantonel@idiap.ch>\n\nexport NLogWeight\n\n\"\"\"\n`NLogWeight(x)`\n\n| Set                                 |     ``\\\\oplus``         |  ``\\\\otimes``  | ``\\\\bar{0}`` | ``\\\\bar{1}`` |\n|:-----------------------------------:|:-----------------------:|:--------------:|:------------:|:------------:|\n|``\\\\mathbb{R}\\\\cup\\\\{\\\\pm\\\\infty\\\\}``|``-\\\\log(e^{-x}+e^{-y})``|     ``+``      |``\\\\infty``   |   ``0``      | \n\"\"\"\nstruct NLogWeight{T <: AbstractFloat} <: Semiring\n  x::T\nend\n\nNLogWeight(x::Number) = NLogWeight(float(x))\n\nzero(::Type{NLogWeight{T}}) where T = NLogWeight{T}(T(Inf))\none(::Type{NLogWeight{T}}) where T = NLogWeight{T}(zero(T))\n\n*(a::NLogWeight{T}, b::NLogWeight{T}) where {T <: AbstractFloat} = NLogWeight{T}(a.x + b.x)\n+(a::NLogWeight{T}, b::NLogWeight{T}) where {T <: AbstractFloat} = NLogWeight{T}(-logadd(-a.x,-b.x))\n/(a::NLogWeight{T}, b::NLogWeight{T}) where {T <: AbstractFloat} = NLogWeight{T}(a.x - b.x)\nreverse(a::NLogWeight) = a\n\n# parsing\nparse(::Type{S},str) where {T, S <: NLogWeight{T}} = S(parse(T,str))\n\n#properties\niscommulative(::Type{W}) where {W <: NLogWeight} = true\nisleft(::Type{W}) where {W <: NLogWeight} = true\nisright(::Type{W}) where {W <: NLogWeight}= true\nisweaklydivisible(::Type{W}) where {W <: NLogWeight}= true\niscomplete(::Type{W}) where {W <: NLogWeight}= true\n", "meta": {"hexsha": "842ab70e833f4efa80ae113b54a09ec6e2a1fdf7", "size": 1393, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/semirings/nlog.jl", "max_stars_repo_name": "idiap/FiniteStateTransducers.jl", "max_stars_repo_head_hexsha": "430bf273960bd3f43f4042ee85a7c9f3d846d37f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-20T10:41:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-20T10:41:21.000Z", "max_issues_repo_path": "src/semirings/nlog.jl", "max_issues_repo_name": "idiap/FiniteStateTransducers.jl", "max_issues_repo_head_hexsha": "430bf273960bd3f43f4042ee85a7c9f3d846d37f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-02-09T16:54:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-14T00:10:46.000Z", "max_forks_repo_path": "src/semirings/nlog.jl", "max_forks_repo_name": "idiap/FiniteStateTransducers.jl", "max_forks_repo_head_hexsha": "430bf273960bd3f43f4042ee85a7c9f3d846d37f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6944444444, "max_line_length": 113, "alphanum_fraction": 0.5391241924, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7512458115611534}}
{"text": "# simplified model from Chakrawal21\n\nfunction chak21_simp_system()\n    #using ModelingToolkit, DifferentialEquations, Plots\n    @parameters t ks km kd Y HS HB\n    # t in hours\n    # masses per soilmass in mol/g\n    @variables s(t) b(t) cr_tot(t) r_tot(t) q(t) dec_s(t) tvr_b(t)\n    D = Differential(t)\n    HG = HS - Y * HB # can take out of system because does not involve t\n    eqs = [\n        dec_s ~ (ks*s*b)/(s + km),\n        tvr_b ~ kd*b,\n        D(s) ~ -dec_s + tvr_b,\n        D(b) ~ Y * dec_s - tvr_b,\n        r_tot ~ (1-Y) * dec_s,\n        D(cr_tot) ~ r_tot,\n        q ~ -HG * dec_s,\n        ]\n    @named chak21_simp = ODESystem(eqs)\n    chak21_simp_s = structural_simplify(chak21_simp) # omit r,q\n    p_straw = Dict(\n        :parms => [ks => 0.15, km => 2.62e-6, kd => 1.35e-2, Y => 0.72, \n            HB => -492, HS => -469],\n        #:x0 => [s => 4.17e-6, b => 1.14e-5, cr => 0] # twutz: wrong in paper\n        :x0 => [s => 4.17e-5, b => 1.14e-5, cr_tot => 0]\n    ) # see S5\n    chak21_simp_s, chak21_simp, p_straw\nend\n\n", "meta": {"hexsha": "358cea224274914a2dbf7d6ce41099ea09ad19e1", "size": 1031, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chakrawal21/chakrawal21simp.jl", "max_stars_repo_name": "bgctw/MicMods.jl", "max_stars_repo_head_hexsha": "f555bb22897ead268aeca499c50e862f7639ea08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/chakrawal21/chakrawal21simp.jl", "max_issues_repo_name": "bgctw/MicMods.jl", "max_issues_repo_head_hexsha": "f555bb22897ead268aeca499c50e862f7639ea08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chakrawal21/chakrawal21simp.jl", "max_forks_repo_name": "bgctw/MicMods.jl", "max_forks_repo_head_hexsha": "f555bb22897ead268aeca499c50e862f7639ea08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2580645161, "max_line_length": 77, "alphanum_fraction": 0.5392822502, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392797, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7512458101777956}}
{"text": "struct QStructs{FT<:Real}\n\tA  :: FT\n\tLx :: FT\n\tQx :: FT\n\tLy :: FT\n\tQy :: FT\nend\n\nfunction QfieldProperties(\n\tFT = Float64;\n\tA  :: Real = 1.,\n\tLx :: Real = 2.,\n\tQx :: Real = 0.,\n\tLy :: Real = 2.,\n\tQy :: Real = 0.\n)\n\n\treturn QStructs{FT}(A,Lx,Qx,Ly,Qy)\n\nend\n\nfunction createQ(\n\tQParams::Array{QStructs{FT}},\n\tg::Grid{FT},\n) where FT <: Real\n\n\txc = g.xc\n\tyc = g.yc\n\tnQ = length(QParams)\n\tQ  = zeros(FT,g.nx,g.ny)\n\n\tfor Qs in QParams, jj = 1 : g.ny, ii = 1 : g.nx\n\t\tif abs(xc[ii]-Qs.Qx) < Qs.Lx\n\t\t\tQ[ii,jj] += Qs.A * cos(pi*(xc[ii]-Qs.Qx)*0.5/Qs.Lx) *\n\t\t\t\t\t\t\t   exp(-((yc[jj]-Qs.Qy)/Qs.Ly)^2)\n\t\tend\n\tend\n\n\treturn Q\n\nend\n\nfunction show(io::IO, Q::QStructs{FT}) where FT <: Real\n    print(\n\t\tio,\n\t\t\"The Q{$FT}-field forcing is defined as follows:\\n\",\n\t\t\"           Amplitude : \", Q.A, '\\n',\n\t\t\"        Size (Lx,Ly) : \", (Q.Lx,Q.Ly), '\\n',\n\t\t\"    Position (Qx,Qy) : \", (Q.Qx,Q.Qy), '\\n'\n\t)\nend\n", "meta": {"hexsha": "767163263c29faf7669c1ae90dc858c72f66d75c", "size": 887, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/QForcing.jl", "max_stars_repo_name": "natgeo-wong/GillMatsuno.jl", "max_stars_repo_head_hexsha": "b351f6453281af4f9600d36317da0b3ca0db220b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-12-20T18:49:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T09:59:07.000Z", "max_issues_repo_path": "src/QForcing.jl", "max_issues_repo_name": "natgeo-wong/GillMatsuno.jl", "max_issues_repo_head_hexsha": "b351f6453281af4f9600d36317da0b3ca0db220b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-12-20T18:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T03:19:20.000Z", "max_forks_repo_path": "src/QForcing.jl", "max_forks_repo_name": "natgeo-wong/GillMatsuno.jl", "max_forks_repo_head_hexsha": "b351f6453281af4f9600d36317da0b3ca0db220b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:53:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:53:38.000Z", "avg_line_length": 17.0576923077, "max_line_length": 56, "alphanum_fraction": 0.5231116122, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.7512458086661163}}
{"text": "include(\"07_two_site_operator.jl\")\n\nprintln(\"\n#######################################################\n# Tutorial 8                                          #\n#                                                     #\n# 2-site custom operator/gate definition              #\n#######################################################\n\")\n\nimport ITensors: op\n\n# Controlled-Ry rotation gate\nfunction op(::OpName\"CRy\", ::SiteType\"S=1/2\"; θ)\n  return [\n    1 0 0           0\n    0 1 0           0\n    0 0 cos(θ / 2) -sin(θ / 2)\n    0 0 sin(θ / 2) cos(θ / 2)\n  ]\nend\n\n# CRy(θ=π/2)\nθ = π / 2\nCRyθ = op(\"CRy\", i1, i2; θ)\n\n# |10⟩ = |Z-Z+⟩\nZmZp = Zm1 * Zp2\n\n# CRyθ|Z-Z+⟩ = |Z-X+⟩\n@show apply(CRyθ, ZmZp) ≈ Zm1 * Xp2\n", "meta": {"hexsha": "698b1d51b034eaf22cf185f96104853c9bca07f9", "size": 699, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tutorials/08_two_site_operator_custom.jl", "max_stars_repo_name": "mtfishman/ITensorTutorials.jl", "max_stars_repo_head_hexsha": "dcbc1988299e6a7f3b612faeb31563da38ece3be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-11T10:42:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T01:03:58.000Z", "max_issues_repo_path": "tutorials/08_two_site_operator_custom.jl", "max_issues_repo_name": "mtfishman/ITensorTutorials.jl", "max_issues_repo_head_hexsha": "dcbc1988299e6a7f3b612faeb31563da38ece3be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/08_two_site_operator_custom.jl", "max_forks_repo_name": "mtfishman/ITensorTutorials.jl", "max_forks_repo_head_hexsha": "dcbc1988299e6a7f3b612faeb31563da38ece3be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.84375, "max_line_length": 55, "alphanum_fraction": 0.3690987124, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7512458079102768}}
{"text": "module LogisticRegression\n\nusing LinearAlgebra\n\n\"\"\"\n    sigmoid(z)\n\nCompute the sigmoid of z.\n\"\"\"\n@inline function sigmoid(z::Number)\n    return 1.0 / (1.0 + exp(-z))\nend\n\n\"\"\"\n    logistic_loss(y, a)\n\nCalculate logistic loss or cross-entropy loss for sample.\n\"\"\"\n@inline function logistic_loss(y::Number, a::Number)\n    return -1.0 * (y * log(a) + (1.0 - y) * log(1.0 - a))\nend\n\n\n\"\"\"\n    evaluate_linear!(z, W, b, x)\n\nEvaluate linear layer, i.e. calculate `z = W*x + b`.\n\"\"\"\n@inline function evaluate_linear!(\n    z::AbstractVector,\n    W::AbstractMatrix,\n    b::AbstractVector,\n    x::AbstractVector)\n    mul!(z, W, x)\n    z .+= b\n    return z\nend\n\n\"\"\"\n    propagate!(J, dw, db, W, b, X, Y, z, a, dz)\n\nForward- and backpropagation.\n\nGiven set of samples (X, Y), calculate total cost and partial derivatives with\nrespect to w and b. X and Y must be iterables with length of m, where m is the\nnumber of samples. Algoritm writes to J, dw, db, z, a, and dz. The last three\nauxiliary vectors for intemediate results and they size needs to equal b.\n\"\"\"\nfunction propagate!(\n    J::AbstractVector,\n    dW::AbstractMatrix,\n    db::AbstractVector,\n    W::AbstractMatrix,\n    b::AbstractVector,\n    X::AbstractVector{V},\n    Y::AbstractVector,\n    z::AbstractVector,\n    a::AbstractVector,\n    dz::AbstractVector\n) where {V<:AbstractVector}\n    @assert length(X) == length(Y)\n    m = length(X)\n    @assert m > 0\n    fill!(J, 0.)\n    fill!(dW, 0.0)\n    fill!(db, 0.0)\n    for (x, y) in zip(X, Y)\n        z = evaluate_linear!(z, W, b, x)\n     @. a = sigmoid(z)\n     @. dz = a - y\n     @. J += logistic_loss(y, a)\n     @. dW += x' * dz\n     @. db += dz\n    end\n @. J /= m\n @. dW /= m\n @. db /= m\n    return\nend\n\n\"\"\"\n    optimize!(J, W, b, X, Y; num_iterations = 1000, learning_rate = 1.0)\n\nGiven initial model (J, W, b) and data (X, Y), optimize model parameters using\ngradient descent method. Model optimization is done in place.\n\"\"\"\nfunction optimize!(\n    J::AbstractVector,\n    W::AbstractMatrix,\n    b::AbstractVector,\n    X::AbstractVector{T},\n    Y::AbstractVector;\n    num_iterations::Integer = 1000,\n    learning_rate::Float64 = 1.0,\n) where {T<:AbstractVector}\n    dW = zero(W)\n    db = zero(b)\n    z = zero(b) \n    a = zero(b)\n    dz = zero(b)\n    for i in 1:num_iterations\n        propagate!(J, dW, db, W, b, X, Y, z, a, dz)\n     @. W = W - learning_rate * dW\n     @. b = b - learning_rate * db\n    end\n    return J, W, b\nend\n\n\"\"\"\n    predict(W, b, x)\n\nGiven model (W, b) and sample x, predict the class y.\n\"\"\"\n@inline function predict(W, b, x)\n    return 1 * (sigmoid.(W*x .+ b) .> 0.5)\nend\n\nend # module\n", "meta": {"hexsha": "552f3ab70c36d96634d64908a5c3416c76005343", "size": 2606, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LogisticRegression.jl", "max_stars_repo_name": "ahojukka5/LogisticRegression.jl", "max_stars_repo_head_hexsha": "ebdc7157bdce92d295496eb6a8c2012f73e599bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-01T16:32:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T11:33:36.000Z", "max_issues_repo_path": "src/LogisticRegression.jl", "max_issues_repo_name": "ahojukka5/LogisticRegression.jl", "max_issues_repo_head_hexsha": "ebdc7157bdce92d295496eb6a8c2012f73e599bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LogisticRegression.jl", "max_forks_repo_name": "ahojukka5/LogisticRegression.jl", "max_forks_repo_head_hexsha": "ebdc7157bdce92d295496eb6a8c2012f73e599bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8991596639, "max_line_length": 78, "alphanum_fraction": 0.6013046815, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7512458028118817}}
{"text": "\"\"\"\n    Monomials(n) = [ x-> x^k for k = 0:n-1 ]\n\"\"\"\nstruct Monomials <: AbstractBasis\n    n::Int\nend\n\nBase.length(B::Monomials) = B.n\n\napproxpoints(B::Monomials) = exp.(2π*im/length(B).*(0:length(B)-1))\napproxtransform(B::Monomials,f) = fft(convert(Array,f),1)./length(B)\n\nfunction iterate_basis(B::Monomials, x)\n    length(B) == 0 && return nothing\n    p = one(x)\n    return p,(2,p)\nend\nfunction iterate_basis(B::Monomials, x, (i,p))\n    i > length(B) && return nothing\n    p = x*p\n    return p,(i+1,p)\nend\n\nevaluate_basis(B::Monomials,i,x) = x^(i-1)\n", "meta": {"hexsha": "de2e40db117629df84f71b55bf38dd4713941634", "size": 553, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bases/Monomials.jl", "max_stars_repo_name": "ettersi/ApproxTools.jl", "max_stars_repo_head_hexsha": "5a14019a3ed7a545c3446a7dd03b4584adf6ff46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bases/Monomials.jl", "max_issues_repo_name": "ettersi/ApproxTools.jl", "max_issues_repo_head_hexsha": "5a14019a3ed7a545c3446a7dd03b4584adf6ff46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-03-16T15:54:22.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-09T16:37:30.000Z", "max_forks_repo_path": "src/bases/Monomials.jl", "max_forks_repo_name": "ettersi/ApproxTools.jl", "max_forks_repo_head_hexsha": "5a14019a3ed7a545c3446a7dd03b4584adf6ff46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.12, "max_line_length": 68, "alphanum_fraction": 0.6184448463, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069627, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7512419727230116}}
{"text": "function mse(semantics::Vector{T}, data) where T\n    res = 0\n    @simd for i in 1:length(semantics)\n        res += (data.target[i] - semantics[i])^2\n    end\n    res /= length(data.target)\nend\n\nfunction mse(tree, data)\n    res = 0\n    for i in 1:length(data.target)\n        output = evaluate(tree, view(data.input, :, i))\n        res += (data.target[i] - output)^2\n    end\n    res /= length(data.target)\nend\n    \nrmse(x, data) = sqrt(mse(x, data))\n\nfunction se(tree, data)\n    res = 0\n    for i in 1:length(data.target)\n        output = evaluate(tree, view(data.input, :, i))\n        res += (data.target[i] - output)^2\n    end\n    res\nend\n\nfunction se(semantics::Vector{T}, data) where T\n    res = 0\n    @simd for i in 1:length(semantics)\n        res += (data.target[i] - semantics[i])^2\n    end\n    res\nend", "meta": {"hexsha": "1948b394584bfac636c7387c1e88fc4533122a7b", "size": 806, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fitness.jl", "max_stars_repo_name": "kogad/JuliaGSGP", "max_stars_repo_head_hexsha": "ab729324eec8e58421682910fd0a889c3d55b681", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fitness.jl", "max_issues_repo_name": "kogad/JuliaGSGP", "max_issues_repo_head_hexsha": "ab729324eec8e58421682910fd0a889c3d55b681", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fitness.jl", "max_forks_repo_name": "kogad/JuliaGSGP", "max_forks_repo_head_hexsha": "ab729324eec8e58421682910fd0a889c3d55b681", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0285714286, "max_line_length": 55, "alphanum_fraction": 0.5818858561, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.7512419633609491}}
{"text": "\"\"\"\nGenerates a non-trivial random MOI linear program by adding variables\nand constraints to MOI-compatible Optimizer `optimizer`\n\nminimize `c' * x`\nsubject to `Ax <= b, x >= 0`\nwhere `x in R^{n}, A in R^{m*n}, b in R^{m}, c in R^{n}`\n\nNote: Mutates the `optimizer` object\n\"\"\"\nfunction generate_lp(optimizer, n, m)\n    s = rand(m)\n    s = 2*s .- 1\n    λ = max.(-s, 0)\n    s = max.(s, 0)\n    x̂ = rand(n)\n    A = rand(m, n)\n    b = A * x̂ .+ s\n    c = -A' * λ\n\n    x = MOI.add_variables(optimizer, n)\n\n    # define objective\n    objective_function = MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(c, x), 0.0)\n    MOI.set(optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), objective_function)\n    MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MIN_SENSE)\n\n    # set constraints\n    for i in 1:m\n        MOI.add_constraint(\n            optimizer,\n            MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(A[i,:], x), 0.), MOI.LessThan(b[i]),\n        )\n    end\n\n    for i in 1:n\n        MOI.add_constraint(optimizer, MOI.SingleVariable(x[i]), MOI.GreaterThan(0.0))\n    end\nend\n\n\n\"\"\"\nGenerates a non-trivial random MOI convex quadratic program \nby adding variables and constraints to MOI compatible Optimizer `optimizer`\n\nminimize `0.5 * x' * Q * x  + q' * x`\nsubject to `Gx <= h, Ax == b`\nwhere `x in R^{n}, Q in R^{n*n}, q in R^{n}, G in R^{m,n}, h in R^{m}, A in R^{p*n}, b in R^{p}`\n\nNote: (1) Mutates the `optimizer` object\n      (2) Matrix `Q` is Positive Semidefinite\n\"\"\"\nfunction generate_qp(optimizer,n,m,p)\n    x̂ = rand(n)\n    Q = rand(n, n)\n    Q = Q' * Q # ensure PSD\n    q = rand(n)\n    G = rand(m, n)\n    h = G * x̂ + rand(m)\n    A = rand(p, n)\n    b = A * x̂\n\n    x = MOI.add_variables(optimizer, n)\n\n    # define objective\n    quadratic_terms = MOI.ScalarQuadraticTerm{Float64}[]\n    for i in 1:n\n        for j in i:n # indexes (i,j), (j,i) will be mirrored. specify only one kind\n            push!(quadratic_terms, MOI.ScalarQuadraticTerm(Q[i,j],x[i],x[j]))\n        end\n    end\n\n    objective_function = MOI.ScalarQuadraticFunction(MOI.ScalarAffineTerm.(q, x), quadratic_terms, 0.0)\n    MOI.set(optimizer, MOI.ObjectiveFunction{MOI.ScalarQuadraticFunction{Float64}}(), objective_function)\n    MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MIN_SENSE)\n\n    # set constraints\n    for i in 1:m\n        MOI.add_constraint(\n            optimizer,\n            MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(G[i,:], x), 0.),MOI.LessThan(h[i])\n        )\n    end\n\n    for i in 1:p\n        MOI.add_constraint(\n            optimizer,\n            MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(A[i,:], x), 0.),MOI.EqualTo(b[i])\n        )\n    end\nend\n", "meta": {"hexsha": "8d5f45bea7591e37418bfadc7e02ac259a7bef76", "size": 2668, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gen_random_problem.jl", "max_stars_repo_name": "niklasschmitz/DiffOpt.jl", "max_stars_repo_head_hexsha": "7c240031b924289ba650530dbe2eefae6355a571", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gen_random_problem.jl", "max_issues_repo_name": "niklasschmitz/DiffOpt.jl", "max_issues_repo_head_hexsha": "7c240031b924289ba650530dbe2eefae6355a571", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gen_random_problem.jl", "max_forks_repo_name": "niklasschmitz/DiffOpt.jl", "max_forks_repo_head_hexsha": "7c240031b924289ba650530dbe2eefae6355a571", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0, "max_line_length": 105, "alphanum_fraction": 0.6105697151, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7512419585738473}}
{"text": "export spectral!\n\n\"\"\"\n`spectral!(X::GraphEmbedding)` gives the graph held in `X` an\nembedding based on the eigenvectors of the Laplacian matrix of the\ngraph. Specifically, the `x`-coordinates come from the eigenvector\nassociated with the second smallest eigenvalue, and the\n`y`-coordinates come from the eigenveector associated with the third\nsmallest.\n\nThis may also be invoked as `spectral!(X,xcol,ycol)` to choose other\neigenvectors to use for the x and y coordinates of the embedding.\n\"\"\"\nfunction spectral!(X::GraphEmbedding,xcol::Int=2,ycol::Int=3)\n    L = laplace(X.G)\n    EV = eigvecs(L)\n    x = EV[:,xcol]\n    y = EV[:,ycol]\n\n    VV = vlist(X.G)\n    n = length(VV)\n\n    for k=1:n\n        v = VV[k]\n        X.xy[v] = [x[k],y[k]]\n    end\n    rescale!(X)\n    return X\nend\n", "meta": {"hexsha": "000b0ee4eb1272309b13050186a6221604e19803", "size": 778, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/embedding/spectral.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_stars_repo_head_hexsha": "a22fbfc7f37c5b4debf209a11f5b059a688d8676", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/embedding/spectral.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_issues_repo_head_hexsha": "a22fbfc7f37c5b4debf209a11f5b059a688d8676", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/embedding/spectral.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_forks_repo_head_hexsha": "a22fbfc7f37c5b4debf209a11f5b059a688d8676", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9333333333, "max_line_length": 68, "alphanum_fraction": 0.6735218509, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7512419575361776}}
{"text": "# Equation references to\n#\n# - Bethe, H., & Salpeter, E. (1977). Quantum mechanics of one-and\n#   two-electron atoms. New York: Plenum Pub. Corp.\n\n@doc raw\"\"\"\n    non_relativistic_energy(n[, Z=1])\n\nReturns the non-relativistic energy of a hydrogen orbital with\nprincipal quantum number ``n`` (and an effective nuclear charge ``Z``)\naccording to\n\n```math\n\\begin{equation}\n\\tag{BS2.11}\nE_n =\n-\\frac{Z^2}{2n^2}\n\\end{equation}\n```\n\n\"\"\"\nnon_relativistic_energy(n, Z=1) = -Z^2/2n^2\n\n\"\"\"\n    non_relativistic_energy(o)\n\nReturn the non-relativistic energy of the orbital `o`.\n\n# Examples\n\n```jldoctest\njulia> non_relativistic_energy(o\"1s\")\n-0.5\n\njulia> non_relativistic_energy(o\"2p\")\n-0.125\n\njulia> non_relativistic_energy(ro\"2p\")\n-0.125\n\njulia> non_relativistic_energy(ro\"2p-\")\n-0.125\n```\n\"\"\"\nnon_relativistic_energy(o::AbstractOrbital) = non_relativistic_energy(o.n)\nnon_relativistic_energy(o::SpinOrbital) = non_relativistic_energy(o.orb)\n\n@doc raw\"\"\"\n    relativistic_energy(n, κ[, Z=1])\n\nReturns the relativistic energy of a hydrogen orbital with principal\nquantum number ``n`` and \"angular momentum\" quantum number ``κ`` (and\nan effective nuclear charge ``Z``) according to\n\n```math\n\\begin{equation}\n\\tag{BS14.29*}\nE_{nκ} =\nc^2\\left[\n-1+\n\\frac{1}{\\sqrt{1 +\n\\left(\n\\frac{Zα}{n - \\abs{κ} + \\sqrt{κ^2-Z^2α^2}}\n\\right)^2}}\n\\right]\n\\end{equation}\n```\n\nwhere the energy has been shifted by ``-c^2`` compared to\n``\\mathrm{(BS14.29)}``.\n\n\"\"\"\nfunction relativistic_energy(n, κ, Z=1)\n    r = Z*α/(n-abs(κ)+√(κ^2-Z^2*α^2))\n    -c^2*(1-inv(√(1+r^2)))\nend\n\n\"\"\"\n    relativistic_energy(o::RelativisticOrbital)\n\nReturn the relativistic energy for the orbital `o`.\n\n# Example\n\n```jldoctest\njulia> relativistic_energy(ro\"1s\")\n-0.5000066565961734\n\njulia> relativistic_energy(ro\"2p-\")\n-0.12500208019062972\n\njulia> relativistic_energy(ro\"2p\")\n-0.1250004160284539\n```\n\"\"\"\nrelativistic_energy(o::RelativisticOrbital) = relativistic_energy(o.n, o.κ)\nrelativistic_energy(o::SpinOrbital) = relativistic_energy(o.orb)\n\n\"\"\"\n    orbital_energy(o)\n\nReturn the energy of orbital `o`, automatically choosing between\n[`non_relativistic_energy`](@ref) and [`relativistic_energy`](@ref),\ndepending on the type of `o`.\n\n# Examples\n\n```jldoctest\njulia> orbital_energy(o\"1s\")\n-0.5\n\njulia> orbital_energy(ro\"1s\")\n-0.5000066565961734\n\njulia> orbital_energy(o\"2p\")\n-0.125\n\njulia> orbital_energy(ro\"2p\")\n-0.1250004160284539\n```\n\n\"\"\"\norbital_energy(o::Orbital) = non_relativistic_energy(o)\norbital_energy(o::RelativisticOrbital) = relativistic_energy(o)\norbital_energy(o::SpinOrbital) = orbital_energy(o.orb)\n\nground_state( ::Orbital) = o\"1s\"\nground_state( ::RelativisticOrbital) = ro\"1s\"\nground_state(o::SpinOrbital) = ground_state(o.orb)\n\n\"\"\"\n    atomic_hamiltonian(orbitals[; Efun=orbital_energy, neutral_zero=true])\n\nReturn the diagonal matrix whose elements corresponds to the energies\nof each of the `orbitals`, by default [`orbital_energy`](@ref) is used\nto determine the energy, which dispatches on the orbital type to\nreturn the appropriate energy (non-relativistic or relativistic), and\nall energies are shifted such that `1s` has zero energy, if\n`neutral_zero==true`.\n\n# Examples\n\n```jldoctest\njulia> atomic_hamiltonian(os\"1[s] 2[s-p]\")\n3×3 LinearAlgebra.Diagonal{Float64,Array{Float64,1}}:\n 0.0   ⋅      ⋅\n  ⋅   0.375   ⋅\n  ⋅    ⋅     0.375\n\njulia> atomic_hamiltonian(ros\"1[s] 2[s-p]\")\n4×4 LinearAlgebra.Diagonal{Float64,Array{Float64,1}}:\n 0.0   ⋅         ⋅         ⋅\n  ⋅   0.375005   ⋅         ⋅\n  ⋅    ⋅        0.375005   ⋅\n  ⋅    ⋅         ⋅        0.375006\n```\n\"\"\"\nfunction atomic_hamiltonian(orbitals; Efun::Function=orbital_energy,\n                            neutral_zero=true)\n    E = zeros(length(orbitals))\n\n    for (i,o) in enumerate(orbitals)\n        E[i] = Efun(o)\n    end\n\n    if neutral_zero && !isempty(orbitals)\n        E .-= Efun(ground_state(first(orbitals)))\n    end\n\n    Diagonal(E)\nend\n\nexport non_relativistic_energy, relativistic_energy, orbital_energy, atomic_hamiltonian\n", "meta": {"hexsha": "f0054adffa4dd114411a0caf7f8a270b3cbc3aa3", "size": 3966, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/energies.jl", "max_stars_repo_name": "JuliaAtoms/Hydrogen.jl", "max_stars_repo_head_hexsha": "b92a18f86d42bbf60990960339748dc95d6ec655", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/energies.jl", "max_issues_repo_name": "JuliaAtoms/Hydrogen.jl", "max_issues_repo_head_hexsha": "b92a18f86d42bbf60990960339748dc95d6ec655", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-05-28T00:44:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T10:40:30.000Z", "max_forks_repo_path": "src/energies.jl", "max_forks_repo_name": "JuliaAtoms/Hydrogen.jl", "max_forks_repo_head_hexsha": "b92a18f86d42bbf60990960339748dc95d6ec655", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-16T01:57:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-16T01:57:06.000Z", "avg_line_length": 22.7931034483, "max_line_length": 87, "alphanum_fraction": 0.6944024206, "num_tokens": 1346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476385, "lm_q2_score": 0.8244619263765706, "lm_q1q2_score": 0.7512329849572469}}
{"text": "using Statistics, StatsBase\n\nfunction MNmodel(θ, rndseed=1234)\n    n = 1000\n    μ1, μ2, σ1, σ2, prob = θ\n    d1=randn(n).*σ1 .+ μ1\n    d2=randn(n).*(σ1+σ2) .+ (μ1 - μ2) # second component lower mean and higher variance\n    ps=rand(n).<prob\n    data=zeros(n)\n    data[ps].=d1[ps]\n    data[.!ps].=d2[.!ps]\n    return data\nend\n\nfunction auxstat(data)\n    r = 0.0 : 0.1 : 1.0\n    sqrt(1000.).*vcat(mean(data), std(data), skewness(data), kurtosis(data),\n        quantile.(Ref(data),r))\nend\n\nfunction auxstat(θ, reps)\n    auxstat.([MNmodel(θ, rand(1:Int64(1e12))) for i = 1:reps]) \nend\n\nfunction TrueParameters()\n    [1.0, 1.0, 0.2, 1.8, 0.4] # first component N(1,0.2) second component N(0,2)\nend    \n\nfunction PriorSupport()\n    lb = [0.0, 0.0, 0.0, 0.0, 0.05] # there is always at least 5% prob for each component  \n    ub = [3.0, 3.0, 1.0, 3.0, 0.95] \n    lb,ub\nend    \n\nfunction PriorDraw()\n    lb, ub = PriorSupport()\n    θ = (ub-lb).*rand(size(lb,1)) + lb\nend    \n\nfunction InSupport(θ)\n    lb,ub = PriorSupport()\n    all(θ .>= lb) & all(θ .<= ub)\nend\n\n# prior should be an array of distributions, one for each parameter\nlb, ub = PriorSupport() # need these in Prior\nmacro Prior()\n    return :( arraydist([Uniform(lb[i], ub[i]) for i = 1:size(lb,1)]) )\nend\n\n\n", "meta": {"hexsha": "fbecf727c1eb0d2456cda9b1fa09422129ab89c7", "size": 1260, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/MN/MNlib.jl", "max_stars_repo_name": "mcreel/SimulatedNeuralMoments", "max_stars_repo_head_hexsha": "c8c32cf5ce4101f6ce92a565c50b38f1a96ffa9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/MN/MNlib.jl", "max_issues_repo_name": "mcreel/SimulatedNeuralMoments", "max_issues_repo_head_hexsha": "c8c32cf5ce4101f6ce92a565c50b38f1a96ffa9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/MN/MNlib.jl", "max_forks_repo_name": "mcreel/SimulatedNeuralMoments", "max_forks_repo_head_hexsha": "c8c32cf5ce4101f6ce92a565c50b38f1a96ffa9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2307692308, "max_line_length": 91, "alphanum_fraction": 0.6, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7512329789445192}}
{"text": "@doc raw\"\"\"\n    HomogeneousPoissonPointProcess{T<:Vector{Float64}} <: AbstractSpatialPointProcess{T}\n\nHomegeneous [Poisson point process](https://en.wikipedia.org/wiki/Poisson_point_process) with intensity ``\\beta > 0``, denoted ``\\operatorname{Poisson}(\\beta)``.\n\n``\\operatorname{Poisson}(\\beta)`` has density (w.r.t. the homogenous Poisson point process with unit intensity ``\\operatorname{Poisson}(1)``) proportional to\n\n```math\n    \\prod_{x \\in X}\n        \\beta.\n```\n\"\"\"\nstruct HomogeneousPoissonPointProcess{T<:Vector{Float64}} <: AbstractSpatialPointProcess{T}\n    β::Float64\n    window::AbstractSpatialWindow{Float64}\nend\n\nfunction Base.show(io::IO, pp::HomogeneousPoissonPointProcess{T}) where {T}\n    print(io, \"HomogeneousPoissonPointProcess{$T}\\n- β = $(pp.β)\\n- window = $(pp.window)\")\nend\n\n@doc raw\"\"\"\n    HomogeneousPoissonPointProcess(\n        β::Real,\n        window::Union{Nothin,AbstractSpatialWindow}=nothing\n    )\n\nConstruct a [`PRS.HomogeneousPoissonPointProcess`](@ref) with intensity `β` restricted to `window`.\n\nDefault window (`window=nothing`) is [`PRS.SquareWindow`](@ref)`()`.\n\n```jldoctest; output = true\nusing PartialRejectionSampling\n\nβ = 40\nwin = PRS.SquareWindow(zeros(2), 1)\nPRS.HomogeneousPoissonPointProcess(β, win)\n\n# output\n\nHomogeneousPoissonPointProcess{Array{Float64,1}}\n- β = 40.0\n- window = SquareWindow [0.0, 1.0]^2\n```\n\"\"\"\nfunction HomogeneousPoissonPointProcess(\n    β::Real,\n    window::Union{Nothing,AbstractSpatialWindow}=nothing\n)\n    @assert β > 0\n    win = isnothing(window) ? SquareWindow() : window\n    return HomogeneousPoissonPointProcess{Vector{Float64}}(β, win)\nend\n\n\"\"\"\n    intensity(pp::HomogeneousPoissonPointProcess) = pp.β\n\"\"\"\nintensity(pp::HomogeneousPoissonPointProcess) = pp.β\n\n## Sampling\n\n\"\"\"\n    generate_sample(\n        [rng::Random.AbstractRNG,]\n        pp::HomogeneousPoissonPointProcess{Vector{T}},\n        win::Union{Nothing,AbstractWindow}=nothing\n    )::Matrix{T} where {T<:Float64}\n\nGenerate an exact sample from [`PRS.HomogeneousPoissonPointProcess`](@ref) on window `win`.\nSampled points are stored as columns of the output matrix.\n\nDefault window (`win=nothing`) is `window(pp)`.\n\"\"\"\nfunction generate_sample(\n    rng::Random.AbstractRNG,\n    pp::HomogeneousPoissonPointProcess{Vector{T}},\n    win::Union{Nothing,AbstractWindow}=nothing\n)::Matrix{T} where {T<:Float64}\n    window_ = isnothing(win) ? window(pp) : win\n    n = rand(rng, Distributions.Poisson(pp.β * volume(window_)))\n    return rand(rng, window_, n)\nend\n\n# function generate_sample(\n#     pp::HomogeneousPoissonPointProcess,\n#     win::Union{Nothing,AbstractWindow}=nothing\n# )\n#     return generate_sample(Random.default_rng(), pp, win=win)\n# end\n\n@doc raw\"\"\"\n    generate_sample_poisson_union_balls(\n        [rng::Random.AbstractRNG,]\n        β::Real,\n        centers::Matrix,\n        radius::Real,\n        win::Union{Nothing,AbstractWindow}=nothing\n    )::Matrix{Float64}\n\nGenerate an exact sample from a homogenous [`PRS.HomogeneousPoissonPointProcess`](@ref) Poisson(β) on ``\\bigcup_{i} B(c_i, r)`` (union of balls centered at ``c_i`` with the same radius ``r``).\n\nIf `win ≂̸ nothing`, returns the points falling in `win`.\n\n!!! hint\n\n    Use the independence property of the Poisson point process on disjoint subsets in order to\n\n    - Sample from Poisson(β) on ``B(c_1, r)``,\n    - Sample from Poisson(β) on ``B(c_2, r) \\setminus B(c_1, r)``,\n    - Sample from Poisson(β) on ``B(c_j, r) \\setminus \\bigcup_{i<j} B(c_i, r)``,\n    - ...\n\"\"\"\nfunction generate_sample_poisson_union_balls(\n    rng::Random.AbstractRNG,\n    β::Real,\n    centers::Matrix,\n    radius::Real,\n    win::Union{Nothing,AbstractWindow}=nothing\n)::Matrix{Float64}\n    d = size(centers, 1)\n    !(isnothing(win)) && @assert dimension(win) == d\n\n    𝒫 = Distributions.Poisson(β * volume(BallWindow(zeros(d), radius)))\n    points = Matrix{Float64}(undef, d, 0)\n    for (i, c) in enumerate(eachcol(centers))\n        n = rand(rng, 𝒫)\n        n == 0 && continue\n        proposed = rand(rng, BallWindow(c, radius), n)\n        if i == 1\n            points = hcat(points, proposed)\n            continue\n        end\n        centers_ = @view centers[:, 1:i-1]\n        accept = vec(all(pairwise_distances(centers_, proposed) .> radius, dims=1))\n        points = hcat(points, proposed[:, accept])\n    end\n\n    if isnothing(win) || isempty(points)\n        return points\n    end\n    return points[:, vec(mapslices(x -> x in win, points; dims=1))]\nend\n\nfunction generate_sample_poisson_union_balls(\n    β::Real,\n    centers::Matrix,\n    radius::Real,\n    win::Union{Nothing,AbstractWindow}=nothing\n)\n    generate_sample_poisson_union_balls(Random.default_rng(), β, centers, radius, win)\nend\n", "meta": {"hexsha": "07ca856af625b468a0038bcd784c48b680d902c1", "size": 4692, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spatial/poisson.jl", "max_stars_repo_name": "guilgautier/PartialRejectionSampling.jl", "max_stars_repo_head_hexsha": "b9b586b9347430cd5375e34ff6f1d37193555997", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-08T11:11:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-08T11:11:26.000Z", "max_issues_repo_path": "src/spatial/poisson.jl", "max_issues_repo_name": "guilgautier/PartialRejectionSampling.jl", "max_issues_repo_head_hexsha": "b9b586b9347430cd5375e34ff6f1d37193555997", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-25T10:55:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-25T14:16:55.000Z", "max_forks_repo_path": "src/spatial/poisson.jl", "max_forks_repo_name": "guilgautier/PartialRejectionSampling.jl", "max_forks_repo_head_hexsha": "b9b586b9347430cd5375e34ff6f1d37193555997", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8684210526, "max_line_length": 192, "alphanum_fraction": 0.6792412617, "num_tokens": 1346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356994, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.751232977073647}}
{"text": "function dataTransf(x::AbstractVecOrMat, transfId::Vector{Int})\n    y = similar(x)\n    n_loss = 0\n    for i = 1:size(x, 2)\n        (y[:,i], n_loss_temp) = dataTransf(x[:,i], transfId[i])\n        n_loss = max(n_loss, n_loss_temp)\n    end\n    return (y = y, n_loss = n_loss)\nend\n\nfunction dataTransf(x::AbstractVecOrMat, transfId::Int)\n#   Categories:\n#   ------------------------------------------------------------------------\n#   1. Levels (Y_{t})\n#   2. First Difference (Y_{t}-Y_{t-1})\n#   3. Seasonal difference in quarterly data ((Y_{t})-(Y_{t-4}))\n#   4. Seasonal difference in monthly data ((Y_{t})-(Y_{t-12}))\n#   5. Log-levels (Ln(Y_{t}))\n#   6. Log-First Difference (Ln(Y_{t})-Ln(Y_{t-1}))\n#   7. Seasonal log difference in quarterly data (Ln(Y_{t})-Ln(Y_{t-4}))\n#   8. Seasonal log difference in monthly data (Ln(Y_{t})-Ln(Y_{t-12}))\n#   9. Detrending Ln(Y_{t}) by HP filter using quarterly data\n#   10. Detrending Ln(Y_{t}) by HP filter using monthly data\n#   11. Seasonal difference of a detrended Ln(Y_{t}) by HP filter using quarterly data\n#   12. Seasonal difference of a detrended Ln(Y_{t}) by HP filter using monthly data\n#   13. Seasonal difference of a detrended Ln(Y_{t}) by removing a linear trend\n#   14. Detrended Y_{t} by removing a linear trend (for already SA data)\n#   15. Detrended Ln(Y_{t}) by removing a linear trend (for already SA data)\n#  =========================================================================\n    y = similar(x)\n\n    if transfId == 1\n        y = copy(x)\n        n_loss = 0\n    elseif transfId == 2\n        y[2:end,:] = x[2:end,:] - x[1:end - 1,:]\n        n_loss = 1\n    elseif transfId == 3\n        y[5:end,:] = x[5:end,:] - x[1:end - 4,:]\n        n_loss = 4\n    elseif transfId == 4\n        y[13:end,:] = x[13:end,:] - x[1:end - 12,:]\n        n_loss = 12\n    elseif transfId == 5\n        y = log.(x)\n        n_loss = 0\n    elseif transfId == 6\n        y[2:end,:] = log.(x[2:end,:]) - log.(x[1:end - 1,:])\n        n_loss = 1\n    elseif transfId == 7\n        y[5:end,:] = log.(x[5:end,:]) - log.(x[1:end - 4,:])\n        n_loss = 4\n    elseif transfId == 8\n        y[13:end,:] = log.(x[13:end,:]) - log.(x[1:end - 12,:])\n        n_loss = 12\n        # case 7\n        #     yt=hpfilter(log(x),1600);\n        #     y=log(x)-yt;\n        #     n_loss=0;\n        # case 8\n        #     yt=hpfilter(log(x),14400);\n        #     y=log(x)-yt;\n        #     n_loss=0;\n        # case 9\n        #     yt=hpfilter(log(x),1600);\n        #     yt=log(x)-yt;\n        #     y(5:end,:)=yt(5:end,:)-yt(1:end-4,:);\n        #     n_loss=4;\n        # case 10\n        #     yt=hpfilter(log(x),14400);\n        #     yt=log(x)-yt;\n        #     y(13:end,:)=yt(13:end,:)-yt(1:end-12,:);            \n        #     n_loss=12;\n    elseif transfId == 13\n        yt = log.(x)\n        yt = yt[13:end,:] - yt[1:end - 12,:]           \n        y[14:end,:] = yt[2:end,:] - yt[1:end - 1,:]\n        n_loss = 13\n    elseif transfId == 14\n        y = detrend(x, power=1)\n        n_loss = 0 \n    elseif transfId == 15\n        y = detrend(log.(x), power=1)\n        n_loss = 0 \n    else\n        error(\"Please specify a valid transformation index\")\n    end\n\n    return (y = y, n_loss = n_loss)\nend\n\nfunction detrend(y::AbstractVecOrMat;power::Int = 1)\n    T = size(y, 1)\n    X = similar(y, T, power + 1)\n    X[:,1] = ones(T)\n    if power > 0\n        for i = 1:power\n            X[:,i + 1] = collect(1:T).^i\n        end\n    end\n    b = X \\ y\n    return y - X * b\nend", "meta": {"hexsha": "3436ad939156d59bfb052388340847cbdde5f2fc", "size": 3473, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/data_manipulation.jl", "max_stars_repo_name": "zymbuzz/myJuliaUtils", "max_stars_repo_head_hexsha": "bd18eff600ca8a5052575706dc3a4b494128c4a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/data_manipulation.jl", "max_issues_repo_name": "zymbuzz/myJuliaUtils", "max_issues_repo_head_hexsha": "bd18eff600ca8a5052575706dc3a4b494128c4a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/data_manipulation.jl", "max_forks_repo_name": "zymbuzz/myJuliaUtils", "max_forks_repo_head_hexsha": "bd18eff600ca8a5052575706dc3a4b494128c4a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7184466019, "max_line_length": 86, "alphanum_fraction": 0.4903541607, "num_tokens": 1170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7512329769795032}}
{"text": "#   Unit \"tapers\" of the FourierAnalysis Package for julia language\n#\n#   MIT License\n#   Copyright (c) 2019-2022,\n#   Marco Congedo, CNRS, Grenobe, France:\n#   https://sites.google.com/site/marcocongedo/home\n\n# ? CONTENTS :\n#   This unit implements several tapering windows in the time domain.\n#\n#   See F.J. Harris\n#   \"On the Use of Windows for Harmonic Analysis with the Discrete Fourier Transform\"\n#   Proc. IEEE, 66, 51-53, 1978\n#   http://www.utdallas.edu/~cpb021000/EE%204361/Great%20DSP%20Papers/Harris%20on%20Windows.pdf\n#\n#   D. Slepian\n#   \"Prolate Spheroidal Wave Functions. Fourier Analysis, and Uncertainty—V: The Discrete Case\"\n#   The Bell System Technical Journal,VoL 57, No. 5. May-June 1978\n#   https://ieeexplore-ieee-org.gaelnomade-1.grenet.fr/stamp/stamp.jsp?tp=&arnumber=6771595\n#\n#   D.J. Thomson\n#   \"Spectrum estimation and harmonic analysis.\"\n#   Proc. IEEE 70: 1055-1096, 1982.\n#   http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.471.1278&rep=rep1&type=pdf\n\n#   Other resources :\n#   https://pdfs.semanticscholar.org/752d/1a551b96559458064323eb3de7faaaef4c4e.pdf\n#   ~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~  #\n#                                                                             #\n#   ~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~~¤~  #\n\n\n# time-domain tapering windows.\n@enum TaperKind begin\n    rectangular = 1\n    triangular  = 2\n    hann        = 3\n    hamming     = 4\n    blackman    = 5\n    harris4     = 6\n    riesz       = 7\n    parzen      = 8\n    slepian     = 9\nend\n\nTaperData=Union{Vector{T}, Matrix{T}} where T<:Union{Real, Complex}\n\nstruct Taper\n    y    :: TaperData # here is the taper\n    kind :: TaperKind # enumerated type; see here above\n    α    :: Real # 1-parameter tapers are supported\n    n    :: Int # number of tapers; >1 only for slepians\nend\n\n\n### Time-domain tapering ###\n###############################################################################\n\"\"\"\n```julia\nfunction taper( kind  :: TaperKind,\n                wl    :: Int;\n            α       :: Real    = 2.,\n            n       :: Int     = ceil(Int, 2*α)-1,\n            padding :: Int     = 0,\n            type    :: Type{T} = Float64) where T<:Union{Real, Complex}\n\n```\nUniversal constructor of [Taper](@ref) objects, given a tapering window\n`kind`, of type [TaperKind](@ref) and the window length `wl`.\nNB: for the `hamming` and `blackman` type use `FourierAnalysis.hamming` and `FourierAnalysis.blackman` \nto avoid conflicts with the DSP package.\n\nReturn a vector of length `wl` for all types of tapers, but for the dpss\n(Slepian multi-tapers), for which return a matrix of size `wl` x `n`.\n\nIf optional keyword argument `padding` is >0, then the actual window length\nwill be `wl` + `padding`.\n\nThe `type` optional keyword argument can be use to specify the the type of\nelements of the typering window. By default, this is the `Float64` type.\n\nOptional keywords arguments `α` and `n` currently apply only for slepian\nmulti-tapering (*discrete prolate spheroidal sequences*):\n\n`α` is the *half bandwidth* (hbw) parameter as per the DSP.jl package.\nThis unit is used in many dpss implementations and it is often reported\nthat \"typical values\" for `α` are 2, 2.5, 3, 3.5 or 4.\nHowever, the optimal smoothing increases with the ratio between window length\nand sampling rate, thus these values in absolute terms are not useful.\nIn fact, the larger the *hbw* and the higher `n`, the smoother the\nspectra will be (variance reduction). In order to overcome these\ndifficulties, for Slepian's multitapering\n*FourirAnalysis* implements the [`slepians`](@ref) constructor,\nwhich allows the bandwidth parameter to be given in Hz and the\nnumber of tapering windows to be chosen automatically.\n\n`n` is the number of tapering windows. For slepian tapers this is\nthe number of the discrete prolate spheroidal sequences.\nAs in the DSP package, by default it is set to\n`ceil(Int, 2*α)-1`, however, depending on how large this number is,\nlow eigenvalues may correspond to the last sequences, therefore\nthose should be discarded.\n\n**See**: [plot tapering windows](@ref).\n\n**See also**: [`slepians`](@ref), [`taperinfo`](@ref)\n\n**Examples**:\n```julia\nusing FourierAnalysis\n\n## Use the constructor\nsr, t, f, a = 128, 128, 10, 0.5\n# create a sinusoidal superimposed to white noise\nv=sinusoidal(a, f, sr, t*16, 0) + randn(t*16)\n# create a data matrix\nX=broadcast(+, v, randn(t*16, 3))*randn(3, 3)\n# compute spectra using hamming tapering window\n# we need to prepend 'FourierAnalysis.' since `hamming`\n# is declared also in DSP.jl\nH=taper(FourierAnalysis.hamming, t)\nS=spectra(X, sr, t; tapering=H)\n# you can obtain the same thing with\nS=spectra(X, sr, t; tapering=H)\n# which will create the hamming tapering window on the fly,\n# thus calling explicitly the constructor is interesting\n# only if you need to reuse the same tapering window many times.\n\n## Plot tapering windows using the standard plot function\nusing Plots\ntapers=[TaperKind(i) for i=1:8]\nX=zeros(t, 8)\nfor i=1:8 X[:, i] = taper(tapers[i], t).y end\nmylabels=Array{String}(undef, 1, 8)\nfor i=1:8 mylabels[1, i]=string(tapers[i]) end\nplot(X; labels=mylabels)\n\n## using the recipe declared in recipes.jl\nplot(taper(parzen, 256))\nplot(taper(slepian, 256, α=4, n=7))\n\n```\n\"\"\"\nfunction taper( kind :: TaperKind,\n                wl   :: Int;  # wl is the window length\n            α        :: Real    = 2.,    # only for splepians;\n            n        :: Int     = ceil(Int, 2*α)-1, #ceil : Int greater then or equal to\n            padding  :: Int     = 0,\n            type     :: Type{T} = Float64) where T<:Union{Real, Complex}\n\n    if      kind ∉ (rectangular, slepian)\n            wl₋₁     = wl-1\n            wl₋₁½    = wl₋₁/2\n            c(i::Int) = cos(2π*(i-1)/wl₋₁)\n            c(i::Int, j::Int) = cos(2π*j*(i-1)/wl₋₁)\n    end\n\n    if      kind == rectangular v = ones(type, wl)\n    elseif  kind == triangular  v = Vector{type}([1 - abs(2*(i-1)-wl₋₁)/wl₋₁ for i=1:wl]) # zero at the edge\n    elseif  kind == hann        v = Vector{type}([0.5*(1-c(i)) for i=1:wl])\n    elseif  kind == hamming     v = Vector{type}([0.54 - 0.46*c(i) for i=1:wl])\n    elseif  kind == blackman    v = Vector{type}([0.42 + 0.50*-c(i) + 0.08*c(i, 2) for i=1:wl])\n                                     v[1]=0.; v[end]=0.\n    elseif  kind == harris4     v = Vector{type}([0.35875 - 0.48829*c(i) + 0.14128*c(i, 2) - 0.01168*c(i, 3) for i=1:wl])\n    elseif  kind == riesz       v = Vector{type}([1 - ((i-1-wl₋₁½)/wl₋₁½)^2 for i=1:wl])\n    elseif  kind == parzen\n            v=Vector{type}(undef, wl)\n            wl½, wl¼= wl÷2, wl÷4\n            for i=1:wl¼        v[i] = 2*((1 - (abs(i-wl½)/wl½))^3) end\n            for i=wl¼+1:wl½    v[i] = 1 - 6*(abs(i-wl½)/wl½ )^2 + 6*(abs(i-wl½)/wl½)^3 end\n            for i=wl½+1:wl-wl¼ v[i] = 1 - 6*(abs(i-1-wl½)/wl½)^2 + 6*(abs(i-1-wl½)/wl½)^3 end\n            for i=wl-wl¼+1:wl  v[i] = 2*((1 - (abs(i-1-wl½)/wl½))^3) end\n    elseif  kind == slepian    v    = Matrix{type}(dpss(wl, α, n, zerophase=false))\n    end\n\n    # This has to be checked:\n\n    # normalize to unit mean or unit mean of absolute values\n    if      kind ∉ (rectangular, slepian) v ./= mean(v) end\n    if      kind == slepian v./=mean(abs.(a) for a in v) end\n\n    # if      kind == slepian v./=mean(v.^2; dims=1) end\n    # if      kind ∉ (rectangular, slepian) v ./= mean(v) end\n\n    # normalization in DSP.jl\n    #    if      taper == slepian for i=1:size(v, 2) v[:, i]./= (norm(v[:, i])/wl) end end\n    # as above but givin less and less weight to the sequences\n    #    if      taper == slepian for i=1:size(v, 2) v[:, i]./= √i*(norm(v[:, i])/wl) end end\n\n    p=padding\n    p>0 && (kind == slepian ? v=[v; zeros(type, p, n)] : v=[v; zeros(type, p)])\n\n    return kind == slepian ? Taper(v, kind, α, n) : Taper(v, kind, 0., 1)\nend\n\n\"\"\"\nConstruct a [Taper](@ref) objects holding Slepian's multi-tapering\n*discrete prolate spheroidal sequences*,\ngiven sampling rate `sr`, window length `wl` and\nthe `bandwidth` argument in Hz.\nFor EEG data, 1<=bandwidth<=2 is an adequate choice.\n\nThe 'half-bandwidth' parameter `α` used in the DSP package and in the\nuniversal [Taper](@ref) constructor is set as\n\n        `α=(bandwidth/2)*wl/sr`.\n\nThe optimal number of dpss is heuristically set to\n\n        `n=max(1, trunc(Int, 2*α)-trunc(Int, log(2*α)))`.\n\nThe created object can be passed as argument\nin constructors [`spectra`](@ref), [`crossSpectra`](@ref) and\n[`coherence`](@ref).\n\n**See**: [plot tapering windows](@ref).\n\n**Examples**:\n```julia\nusing FourierAnalysis\nsr, t, f, a = 128, 128, 10, 0.5\n# create a sinusoidal superimposed to white noise\nv=sinusoidal(a, f, sr, t*16, 0) + randn(t*16)\n# create a data matrix\nX=broadcast(+, v, randn(t*16, 3))*randn(3, 3)\n# compute spectra using slepian multi-tapering with bandwidth 1.5\nH=slepians(sr, t, 2)\nS=spectra(X, sr, t; tapering=H)\n\nusing Plots\nplot(H)\nplot(S)\n```\n\"\"\"\nfunction slepians( sr    :: Int,\n                   wl    :: Int,\n               bandwidth :: Real = 1.5)\n    α=(bandwidth/2)*wl/sr # α parameter\n    # heuristic to eliminate eigenfunctions with small eigenvalues\n    n=max(1, trunc(Int, 2*α)-trunc(Int, log(2*α)))\n    return taper(slepian, wl, α=α, n=n)\nend\n###############################################################################\n\n\"\"\"\n```julia\nfunction taperinfo(taper::Taper)\n```\n\nReturn the name of the\ntapering window(s) encapsulated in the [Taper](@ref) object\nas a string.\n\nOnly for Slepian's discrete prolate spheroidal sequences (dpss),\ntheir parameters, namely, ``α`` (half-bandwidth)\nand ``n`` (number of windows), are reported within parentheses as well.\n\n**Examples**:\n```julia\nH=taper(hamming, 128*8)\ntaperinfo(H)\n\nH=slepians(128, 128*8, 2)\ntaperinfo(H)\n```\n\"\"\"\ntaperinfo(taper::Taper) =\n     taper.kind==slepian ? string(taper.kind)*\"'s dpss (alpha=$(taper.α), n=$(taper.n))\" :\n                           string(taper.kind)\n\n\n# ++++++++++++++++++++  Show override  +++++++++++++++++++ # (REPL output)\nfunction Base.show(io::IO, ::MIME{Symbol(\"text/plain\")}, 𝜏::Taper)\nprintln(io, titleFont, \"⍓ Taper type; $(size(𝜏.y, 1))-samples\")\n#println(io, \"□  □    □      □        □           □\", defaultFont)\nprintln(io, separatorFont, \"⭒  ⭒    ⭒      ⭒        ⭒           ⭒\", defaultFont)\nprintln(io, \"taper kind   (.kind): \", string(𝜏.kind))\nprintln(io, \"half-bandwidth  (.α): $(𝜏.α)\")\nprintln(io, \"number of tapers(.n): $(𝜏.n)\")\n𝜏.kind==slepian ? println(io, \"data            (.y): $(size(𝜏.y, 1))x$(size(𝜏.y, 2))-\", typeof(𝜏.y)) :\n                 println(io, \"data            (.y): $(length(𝜏.y))-\", typeof(𝜏.y))\n\nend\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #\n", "meta": {"hexsha": "b43f67fd42b62eef4b180fe530b9ef3c2c1c79c8", "size": 10674, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tapers.jl", "max_stars_repo_name": "proteanblank/FourierAnalysis.jl", "max_stars_repo_head_hexsha": "a1633c9e43bc53d915486b49a9355ff61b3ecb28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tapers.jl", "max_issues_repo_name": "proteanblank/FourierAnalysis.jl", "max_issues_repo_head_hexsha": "a1633c9e43bc53d915486b49a9355ff61b3ecb28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tapers.jl", "max_forks_repo_name": "proteanblank/FourierAnalysis.jl", "max_forks_repo_head_hexsha": "a1633c9e43bc53d915486b49a9355ff61b3ecb28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4526315789, "max_line_length": 121, "alphanum_fraction": 0.5991193554, "num_tokens": 3539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7512329671308873}}
{"text": "\"\"\"\n    complement(g)\n\nReturn the [graph complement](https://en.wikipedia.org/wiki/Complement_graph)\nof a graph\n\n### Implementation Notes\nPreserves the eltype of the input graph.\n\"\"\"\nfunction complement(g::Graph)\n    gnv = nv(g)\n    h = Graph(gnv)\n    for i=1:gnv\n        for j=i+1:gnv\n            if !has_edge(g, i, j)\n                add_edge!(h,i,j)\n            end\n        end\n    end\n    return h\nend\n\nfunction complement(g::DiGraph)\n    gnv = nv(g)\n    h = DiGraph(gnv)\n    for i in vertices(g), j in vertices(g)\n      if i != j && !has_edge(g,i,j)\n        add_edge!(h,i,j)\n      end\n    end\n    return h\nend\n\n\"\"\"\n    reverse(g)\n\nReturn a directed graph where all edges are reversed from the\noriginal directed graph.\n\n### Implementation Notes\nPreserves the eltype of the input graph.\n\"\"\"\nfunction reverse end\n@traitfn function reverse(g::::IsDirected)\n    gnv = nv(g)\n    gne = ne(g)\n    h = DiGraph(gnv)\n    h.fadjlist = deepcopy(g.badjlist)\n    h.badjlist = deepcopy(g.fadjlist)\n    h.ne = gne\n    return h\nend\n\n\"\"\"\n    reverse!(g)\n\nIn-place reverse of a directed graph (modifies the original graph).\n\"\"\"\nfunction reverse! end\n@traitfn function reverse!(g::::IsDirected)\n    g.fadjlist, g.badjlist = g.badjlist, g.fadjlist\n    return g\nend\n\ndoc\"\"\"\n    blkdiag(g, h)\n\nReturn a graph with ``|V(g)| + |V(h)|`` vertices and ``|E(g)| + |E(h)|``\nedges where the vertices an edges from graph `h` are appended to graph `g`.\n\n### Implementation Notes\nPreserves the eltype of the input graph. Will error if the\nnumber of vertices in the generated graph exceeds the eltype.\n\"\"\"\nfunction blkdiag(g::T, h::T) where T<:AbstractGraph\n    gnv = nv(g)\n    r = T(gnv + nv(h))\n    for e in edges(g)\n        add_edge!(r, e)\n    end\n    for e in edges(h)\n        add_edge!(r, gnv+src(e), gnv+dst(e))\n    end\n    return r\nend\n\n\"\"\"\n    intersect(g, h)\n\nReturn a graph with edges that are only in both graph `g` and graph `h`.\n\n### Implementation Notes\nThis function may produce a graph with 0-degree vertices.\nPreserves the eltype of the input graph.\n\"\"\"\nfunction intersect(g::T, h::T) where T<:AbstractGraph\n    gnv = nv(g)\n    hnv = nv(h)\n\n    r = T(min(gnv, hnv))\n    for e in intersect(edges(g),edges(h))\n        add_edge!(r,e)\n    end\n    return r\nend\n\n\"\"\"\n    difference(g, h)\n\nReturn a graph with edges in graph `g` that are not in graph `h`.\n\n### Implementation Notes\nNote that this function may produce a graph with 0-degree vertices.\nPreserves the eltype of the input graph.\n\"\"\"\nfunction difference(g::T, h::T) where T<:AbstractGraph\n    gnv = nv(g)\n    hnv = nv(h)\n\n    r = T(gnv)\n    for e in edges(g)\n        !has_edge(h, e) && add_edge!(r,e)\n    end\n    return r\nend\n\n\"\"\"\n    symmetric_difference(g, h)\n\nReturn a graph with edges from graph `g` that do not exist in graph `h`,\nand vice versa.\n\n### Implementation Notes\nNote that this function may produce a graph with 0-degree vertices.\nPreserves the eltype of the input graph. Will error if the\nnumber of vertices in the generated graph exceeds the eltype.\n\"\"\"\nfunction symmetric_difference(g::T, h::T) where T<:AbstractGraph\n    gnv = nv(g)\n    hnv = nv(h)\n\n    r = T(max(gnv, hnv))\n    for e in edges(g)\n        !has_edge(h, e) && add_edge!(r, e)\n    end\n    for e in edges(h)\n        !has_edge(g, e) && add_edge!(r, e)\n    end\n    return r\nend\n\n\"\"\"\n    union(g, h)\n\nReturn a graph that combines graphs `g` and `h` by taking the set union\nof all vertices and edges.\n\n### Implementation Notes\nPreserves the eltype of the input graph. Will error if the\nnumber of vertices in the generated graph exceeds the eltype.\n\"\"\"\nfunction union(g::T, h::T) where T<:AbstractGraph\n    gnv = nv(g)\n    hnv = nv(h)\n\n    r = T(max(gnv, hnv))\n    r.ne = ne(g)\n    for i in vertices(g)\n        r.fadjlist[i] = deepcopy(g.fadjlist[i])\n        if is_directed(g)\n            r.badjlist[i] = deepcopy(g.badjlist[i])\n        end\n    end\n    for e in edges(h)\n        add_edge!(r, e)\n    end\n    return r\nend\n\n\n\"\"\"\n    join(g, h)\n\nReturn a graph that combines graphs `g` and `h` using `blkdiag` and then\nadds all the edges between the vertices in `g` and those in `h`.\n\n### Implementation Notes\nPreserves the eltype of the input graph. Will error if the number of vertices\nin the generated graph exceeds the eltype.\n\"\"\"\nfunction join(g::T, h::T) where T<:AbstractGraph\n    r = blkdiag(g, h)\n    for i in vertices(g)\n        for j=nv(g)+1:nv(g)+nv(h)\n            add_edge!(r, i, j)\n        end\n    end\n    return r\nend\n\n\n\"\"\"\n    crosspath(len::Integer, g::Graph)\n\nReturn a graph that duplicates `g` `len` times and connects each vertex\nwith its copies in a path.\n\n### Implementation Notes\nPreserves the eltype of the input graph. Will error if the number of vertices\nin the generated graph exceeds the eltype.\n\"\"\"\nfunction crosspath end\n@traitfn function crosspath(len::Integer, g::::(!IsDirected))\n    T = eltype(g)\n    p = PathGraph(len)\n    h = Graph{T}(p)\n    return cartesian_product(h, g)\nend\n\n# The following operators allow one to use a LightGraphs.Graph as a matrix in eigensolvers for spectral ranking and partitioning.\n# \"\"\"Provides multiplication of a graph `g` by a vector `v` such that spectral\n# graph functions in [GraphMatrices.jl](https://github.com/jpfairbanks/GraphMatrices.jl) can utilize LightGraphs natively.\n# \"\"\"\nfunction *(g::Graph, v::Vector{T}) where T<:Real\n    length(v) == nv(g) || error(\"Vector size must equal number of vertices\")\n    y = zeros(T, nv(g))\n    for e in edges(g)\n        i = src(e)\n        j = dst(e)\n        y[i] += v[j]\n        y[j] += v[i]\n    end\n    return y\nend\n\nfunction *(g::DiGraph, v::Vector{T}) where T<:Real\n    length(v) == nv(g) || error(\"Vector size must equal number of vertices\")\n    y = zeros(T, nv(g))\n    for e in edges(g)\n        i = src(e)\n        j = dst(e)\n        y[i] += v[j]\n    end\n    return y\nend\n\n\"\"\"\n    sum(g, i)\n\nReturn a vector of indegree (`i`=1) or outdegree (`i`=2) values for graph `g`.\n\"\"\"\nfunction sum(g::AbstractGraph, dim::Int)\n    dim == 1 && return indegree(g, vertices(g))\n    dim == 2 && return outdegree(g, vertices(g))\n    error(\"Graphs are only two dimensional\")\nend\n\n\nsize(g::AbstractGraph) = (nv(g), nv(g))\n\"\"\"\n    size(g, i)\n\nReturn the number of vertices in `g` if `i`=1 or `i`=2, or `1` otherwise.\n\"\"\"\nsize(g::Graph,dim::Int) = (dim == 1 || dim == 2)? nv(g) : 1\n\n\"\"\"\n    sum(g)\n\nReturn the number of edges in `g`\n\"\"\"\nsum(g::AbstractGraph) = ne(g)\n\n\"\"\"\n    sparse(g)\n\nReturn the default adjacency matrix of `g`.\n\"\"\"\nsparse(g::AbstractGraph) = adjacency_matrix(g)\n\n#arrayfunctions = (:eltype, :length, :ndims, :size, :strides, :issymmetric)\n# eltype(g::AbstractGraph) = Float64\nlength(g::AbstractGraph) = nv(g)*nv(g)\nndims(g::AbstractGraph) = 2\nissymmetric(g::AbstractGraph) = !is_directed(g)\n\n\"\"\"\n    cartesian_product(g, h)\n\nReturn the (cartesian product)[https://en.wikipedia.org/wiki/Tensor_product_of_graphs]\nof `g` and `h`.\n\n### Implementation Notes\nPreserves the eltype of the input graph. Will error if the number of vertices\nin the generated graph exceeds the eltype.\n\"\"\"\nfunction cartesian_product(g::G, h::G) where G<:AbstractGraph\n    z = G(nv(g)*nv(h))\n    id(i, j) = (i-1)*nv(h) + j\n    for e in edges(g)\n        i1, i2 = Tuple(e)\n        for j=1:nv(h)\n            add_edge!(z, id(i1,j), id(i2,j))\n        end\n    end\n\n    for e in edges(h)\n        j1, j2 = Tuple(e)\n        for i in vertices(g)\n            add_edge!(z, id(i,j1), id(i,j2))\n        end\n    end\n    return z\nend\n\n\"\"\"\n    tensor_product(g, h)\n\nReturn the (tensor product)[https://en.wikipedia.org/wiki/Tensor_product_of_graphs]\nof `g` and `h`.\n\n### Implementation Notes\nPreserves the eltype of the input graph. Will error if the number of vertices\nin the generated graph exceeds the eltype.\n\"\"\"\nfunction tensor_product(g::G, h::G) where G<:AbstractGraph\n    z = G(nv(g)*nv(h))\n    id(i, j) = (i-1)*nv(h) + j\n    for e1 in edges(g)\n        i1, i2 = Tuple(e1)\n        for e2 in edges(h)\n            j1, j2 = Tuple(e2)\n            add_edge!(z, id(i1, j1), id(i2, j2))\n        end\n    end\n    return z\nend\n\n\n## subgraphs ###\n\n\"\"\"\n    induced_subgraph(g, vlist)\n    induced_subgraph(g, elist)\n\nReturn the subgraph of `g` induced by the vertices in  `vlist` or edges in `elist`\nalong with a vector mapping the new vertices to the old ones\n(the  vertex `i` in the subgraph corresponds to the vertex `vmap[i]` in `g`.)\n\nThe returned graph has `length(vlist)` vertices, with the new vertex `i`\ncorresponding to the vertex of the original graph in the `i`-th position\nof `vlist`.\n\n### Usage Examples\n```doctestjl\njulia> g = CompleteGraph(10)\n\njulia> sg, vmap = induced_subgraph(g, 5:8)\n\njulia> @assert g[5:8] == sg\n\njulia> @assert nv(sg) == 4\n\njulia> @assert ne(sg) == 6\n\njulia> @assert vm[4] == 8\n\njulia> sg, vmap = induced_subgraph(g, [2,8,3,4])\n\njulia> @assert sg == g[[2,8,3,4]]\n\njulia> elist = [Edge(1,2), Edge(3,4), Edge(4,8)]\n\njulia> sg, vmap = induced_subgraph(g, elist)\n\njulia> @assert sg == g[elist]\n```\n\"\"\"\nfunction induced_subgraph(g::T, vlist::AbstractVector{U}) where T<:AbstractGraph where U<:Integer\n    allunique(vlist) || error(\"Vertices in subgraph list must be unique\")\n    h = T(length(vlist))\n    newvid = Dict{U, U}()\n    vmap =Vector{U}(length(vlist))\n    for (i,v) in enumerate(vlist)\n        newvid[v] = U(i)\n        vmap[i] = v\n    end\n\n    vset = Set(vlist)\n    for s in vlist\n        for d in out_neighbors(g, s)\n            # println(\"s = $s, d = $d\")\n            if d in vset && has_edge(g, s, d)\n                newe = Edge(newvid[s], newvid[d])\n                add_edge!(h, newe)\n            end\n        end\n    end\n    return h, vmap\nend\n\n\nfunction induced_subgraph(g::T, elist::AbstractVector{U}) where T<:AbstractGraph where U<:AbstractEdge\n    h = zero(g)\n    et = eltype(h)\n    newvid = Dict{et, et}()\n    vmap = Vector{et}()\n\n    for e in elist\n        u, v = Tuple(e)\n        for i in (u,v)\n            if !haskey(newvid, i)\n                add_vertex!(h)\n                newvid[i] = nv(h)\n                push!(vmap, i)\n            end\n        end\n        add_edge!(h, newvid[u], newvid[v])\n    end\n    return h, vmap\nend\n\n\n\"\"\"\n    g[iter]\n\nReturn the subgraph induced by `iter`.\nEquivalent to [`induced_subgraph`](@ref)`(g, iter)[1]`.\n\"\"\"\ngetindex(g::AbstractGraph, iter) = induced_subgraph(g, iter)[1]\n\n\n\"\"\"\n    egonet(g, v:, d)\n\nReturn the subgraph of `g` induced by the neighbors of `v` up to distance\n`d`.\nThis is equivalent to [`induced_subgraph`](@ref)`(g, neighborhood(g, v, d, dir=dir))[1].`\n\n### Optional Arguments\n- `dir=:out`: if `g` is directed, this argument specifies the edge direction\nwith respect to `v` (i.e. `:in` or `:out`).\n\"\"\"\negonet(g::AbstractGraph, v::Integer, d::Integer; dir=:out) = g[neighborhood(g, v, d, dir=dir)]\n", "meta": {"hexsha": "2936426cccc0bfb8297d1156201d751aa7b2abc8", "size": 10681, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operators.jl", "max_stars_repo_name": "AsileBcd/JohnsonCycles", "max_stars_repo_head_hexsha": "4928bc05eaaad75a6d05a1390be9f5840c68705e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/operators.jl", "max_issues_repo_name": "AsileBcd/JohnsonCycles", "max_issues_repo_head_hexsha": "4928bc05eaaad75a6d05a1390be9f5840c68705e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/operators.jl", "max_forks_repo_name": "AsileBcd/JohnsonCycles", "max_forks_repo_head_hexsha": "4928bc05eaaad75a6d05a1390be9f5840c68705e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.002247191, "max_line_length": 129, "alphanum_fraction": 0.6189495366, "num_tokens": 3202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7512221418537037}}
{"text": "function gausshermite( n::Int )\n# GAUSSHERMITE(n) COMPUTE THE GAUSS-HERMITE NODES AND WEIGHTS IN O(n) time.\n\n\nif n < 0\n    x = (Float64[],Float64[])\n    return x\nelseif n == 0\n    x = (Float64[],Float64[])\n    return x\nelseif n == 1\n    x = ([0.0],[sqrt(pi)])\n    return x\nelseif n <= 20\n   # GW algorithm\n   x = hermpts_gw( n )\nelseif n <= 200\n   # REC algorithm\n   x = hermpts_rec( n )\nelse\n   # ASY algorithm\n   x = hermpts_asy( n )\nend\n\nif mod(n,2) == 1                              # fold out\n    w = [flipdim(x[2][:],1); x[2][2:end]]\n    w = (sqrt(pi)/sum(w))*w\n    x = ([-flipdim(x[1],1) ; x[1][2:end]], w)\nelse\n    w = [flipdim(x[2][:],1); x[2][:]]\n    w = (sqrt(pi)/sum(w))*w\n    x = ([-flipdim(x[1],1) ; x[1]], w)\nend\n\nend\n\nfunction hermpts_asy( n::Int )\n# Compute Hermite nodes and weights using asymptotic formula\n\nx0 = HermiteInitialGuesses( n ) # get initial guesses\nt0 = x0./sqrt(2n+1)\ntheta0 = acos(t0)               # convert to theta-variable\nval = x0;\nfor k = 1:20\n    val = hermpoly_asy_airy(n, theta0);\n    dt = -val[1]./(sqrt(2)*sqrt(2n+1)*val[2].*sin(theta0))\n    theta0 = theta0 - dt;                        # Newton update\n    if norm(dt,Inf) < sqrt(eps(Float64))/10\n       break\n    end\nend\nt0 = cos(theta0)\nx = sqrt(2n+1)*t0                          #back to x-variable\nders = x.*val[1] + sqrt(2)*val[2]\nw = (exp(-x.^2)./ders.^2)';            # quadrature weights\n\nx = (x, w)\nend\n\nfunction hermpts_rec( n::Int )\n# Compute Hermite nodes and weights using recurrence relation.\n\nx0 = HermiteInitialGuesses( n )\nx0 = x0.*sqrt(2)\nval = x0\nfor kk = 1:10\n    val = hermpoly_rec(n, x0)\n    dx = val[1]./val[2]\n    dx[ isnan( dx ) ] = 0\n    x0 = x0 - dx\n    if norm(dx, Inf)<sqrt(eps(Float64))\n        break\n    end\nend\nx = x0/sqrt(2)\nw = exp(-x.^2)./val[2].^2           # quadrature weights\n\nx = (x, w)\nend\n\nfunction hermpoly_rec( n::Int, x0)\n# HERMPOLY_rec evaluation of scaled Hermite poly using recurrence\n\n# evaluate:\nHold = exp(-x0.^2/4)\nH = x0.*exp(-x0.^2/4)\nfor k = 1:n-1\n    Hold, H = H, (x0.*H./sqrt(k+1) - Hold./sqrt(1+1/k))\nend\n# return (value, derivative):\nval = (H, (-x0.*H + sqrt(n)*Hold))\nend\n\n\nfunction hermpoly_asy_airy(n::Int, theta)\n# HERMPOLY_ASY evaluation hermite poly using Airy asymptotic formula in\n# theta-space.\n\nmusq = 2n+1;\ncosT = cos(theta)\nsinT = sin(theta)\nsin2T = 2*cosT.*sinT\neta = .5*theta - .25*sin2T\nchi = -(3*eta/2).^(2/3)\nphi = (-chi./sinT.^2).^(1/4)\nC = 2*sqrt(pi)*musq^(1/6)*phi\nAiry0 = real(airy(musq.^(2/3)*chi))\nAiry1 = real(airy(1,musq.^(2/3)*chi))\n\n# Terms in (12.10.43):\na0 = 1; b0 = 1\na1 = 15/144; b1 = -7/5*a1\na2 = 5*7*9*11/2/144^2; b2 = -13/11*a2\na3 = 7*9*11*13*15*17/6/144^3\nb3 = -19/17*a3\n\n# u polynomials in (12.10.9)\nu0 = 1; u1 = (cosT.^3-6*cosT)/24\nu2 = (-9*cosT.^4 + 249*cosT.^2 + 145)/1152\nu3 = (-4042*cosT.^9+18189*cosT.^7-28287*cosT.^5-151995*cosT.^3-259290*cosT)/414720\n\n#first term\nA0 = 1\nval = A0*Airy0\n\n#second term\nB0 = -(a0*phi.^6.*u1+a1*u0)./chi.^2\nval = val + B0.*Airy1./musq.^(4/3)\n\n# third term\nA1 = (b0*phi.^12.*u2 + b1*phi.^6.*u1 + b2*u0)./chi.^3\nval = val + A1.*Airy0/musq.^2\n\n# fourth term\nB1 = -(phi.^18.*u3 + a1*phi.^12.*u2 + a2*phi.^6.*u1 + a3*u0)./chi.^5\nval = val + B1.*Airy1./musq.^(4/3+2)\n\nval = C.*val\n\n## Derivative\n\neta = .5*theta - .25*sin2T\nchi = -(3*eta/2).^(2/3)\nphi = (-chi./sinT.^2).^(1/4)\nC = sqrt(2*pi)*musq^(1/3)./phi\n\n# v polynomials in (12.10.10)\nv0 = 1; v1 = (cosT.^3+6*cosT)/24\nv2 = (15*cosT.^4-327*cosT.^2-143)/1152\nv3 = (259290*cosT + 238425*cosT.^3 - 36387*cosT.^5 + 18189*cosT.^7 - 4042*cosT.^9)/414720\n\n# first term\nC0 = -(b0*phi.^6.*v1 + b1.*v0)./chi\ndval = C0.*Airy0/musq.^(2/3)\n\n# second term\nD0 =  a0*v0\ndval = dval + D0*Airy1\n\n# third term\nC1 = -(phi.^18.*v3 + b1*phi.^12.*v2 + b2*phi.^6.*v1 + b3*v0)./chi.^4\ndval = dval + C1.*Airy0/musq.^(2/3+2)\n\n#fourth term\nD1 = (a0*phi.^12.*v2 + a1*phi.^6.*v1 + a2*v0)./chi.^3\ndval = dval + D1.*Airy1/musq.^2\n\ndval = C.*dval\n\nval = (val, dval)\nend\n\nfunction HermiteInitialGuesses( n::Int )\n#HERMITEINTITIALGUESSES(N), Initial guesses for Hermite zeros.\n#\n# [1] L. Gatteschi, Asymptotics and bounds for the zeros of Laguerre\n# polynomials: a survey, J. Comput. Appl. Math., 144 (2002), pp. 7-27.\n#\n# [2] F. G. Tricomi, Sugli zeri delle funzioni di cui si conosce una\n# rappresentazione asintotica, Ann. Mat. Pura Appl. 26 (1947), pp. 283-300.\n\n# Error if n < 20 because initial guesses are based on asymptotic expansions: \n@assert n>=20    \n    \n# Gatteschi formula involving airy roots [1].\n# These initial guess are good near x = sqrt(n+1/2);\nif mod(n,2) == 1\n    m = (n-1)>>1\n    bess = collect(1:m)*pi\n    a = .5\nelse\n    m = n>>1\n    bess = (collect(0:m-1)+.5)*pi\n    a = -.5\nend\nnu = 4*m + 2*a + 2\nT(t) = t.^(2/3).*(1+5/48*t.^(-2)-5/36*t.^(-4)+(77125/82944)*t.^(-6) -108056875/6967296*t.^(-8)+162375596875/334430208*t.^(-10));\nairyrts = -T(3/8*pi*(4*collect(1:m)-1))\n\nairyrts_exact = [-2.338107410459762           # Exact Airy roots.\n    -4.087949444130970\n    -5.520559828095555\n    -6.786708090071765\n    -7.944133587120863\n    -9.022650853340979\n    -10.040174341558084\n    -11.008524303733260\n    -11.936015563236262\n    -12.828776752865757]\nairyrts[1:10] = airyrts_exact  # correct first 10.\n\nx_init = sqrt(abs(nu + 2^(2/3)*airyrts*nu^(1/3) + 1/5*2^(4/3)*airyrts.^2*nu^(-1/3) +\n    (11/35-a^2-12/175*airyrts.^3)/nu + (16/1575*airyrts+92/7875*airyrts.^4)*2^(2/3)*nu^(-5/3) -\n    (15152/3031875*airyrts.^5+1088/121275*airyrts.^2)*2^(1/3)*nu^(-7/3)))\nx_init_airy = real( flipdim(x_init,1) )\n\n# Tricomi initial guesses. Equation (2.1) in [1]. Originally in [2].\n# These initial guesses are good near x = 0 . Note: zeros of besselj(+/-.5,x)\n# are integer and half-integer multiples of pi.\n# x_init_bess =  bess/sqrt(nu).*sqrt((1+ (bess.^2+2*(a^2-1))/3/nu^2) );\nTnk0 = pi/2*ones(m)\nnu = (4*m+2*a+2)\nrhs = (4*m-4*collect(1:m)+3)./nu*pi\n\nfor k = 1:7\n    val = Tnk0 - sin(Tnk0) - rhs\n    dval = 1 - cos(Tnk0)\n    dTnk0 = val./dval\n    Tnk0 = Tnk0 - dTnk0\nend\n\ntnk = cos(Tnk0/2).^2\nx_init_sin = sqrt(nu*tnk - (5./(4*(1-tnk).^2) - 1./(1-tnk)-1+3*a^2)/3/nu)\n\n# Patch together\np = 0.4985+eps(Float64)\nx_init = [x_init_sin[1:convert(Int,floor(p*n))] ;\nx_init_airy[convert(Int,ceil(p*n)):end]]\n\nif mod(n, 2) == 1\n    x_init = [0 ; x_init]\n    x_init = x_init[1:m+1]\nelse\n    x_init = x_init[1:m]\nend\n\nreturn x_init\nend\n\n\nfunction hermpts_gw( n::Int )\n# Golub--Welsch algorithm. Used here for n<=20.\n\n    beta = sqrt(.5*(1:n-1))              # 3-term recurrence coeffs\n    T = diagm(beta, 1) + diagm(beta, -1)   # Jacobi matrix\n    (D, V) = eig(T)                      # Eigenvalue decomposition\n    indx = sortperm(D)                  # Hermite points\n    x = D[indx]\n    w = sqrt(pi)*V[1,indx].^2            # weights\n\n    # Enforce symmetry:\n    ii = floor(Int, n/2)+1:n\n    x = x[ii]\n    w = w[ii]\n    return (x,w)\nend", "meta": {"hexsha": "1608cf0b8a301ffe3545d2c3095e1593e9b005e7", "size": 6779, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gausshermite.jl", "max_stars_repo_name": "MikaelSlevinsky/FastGaussQuadrature.jl", "max_stars_repo_head_hexsha": "d1f1c6a089096eafc830e0ea8e34fb234a097347", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-07-31T23:02:17.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-31T23:02:17.000Z", "max_issues_repo_path": "src/gausshermite.jl", "max_issues_repo_name": "JuliaPackageMirrors/FastGaussQuadrature.jl", "max_issues_repo_head_hexsha": "ada3e7d2c56cebded0a99744f607845974454c74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gausshermite.jl", "max_forks_repo_name": "JuliaPackageMirrors/FastGaussQuadrature.jl", "max_forks_repo_head_hexsha": "ada3e7d2c56cebded0a99744f607845974454c74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.484962406, "max_line_length": 128, "alphanum_fraction": 0.5837144122, "num_tokens": 2900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7512149162002949}}
{"text": "using LinearAlgebra: checksquare\n\n\"\"\"\n    quadratic_expansion(A::IntervalMatrix, α::Real, β::Real)\n\nCompute the quadratic expansion of an interval matrix, ``αA + βA^2``, using\ninterval arithmetics.\n\n### Input\n\n- `A` -- interval matrix\n- `α` -- linear coefficient\n- `β` -- quadratic coefficient\n\n### Output\n\nAn interval matrix that encloses ``B := αA + βA^2``.\n\n### Algorithm\n\nThis a variation of the algorithm in [1, Section 6]. If ``A = (aᵢⱼ)`` and\n``B := αA + βA^2 = (bᵢⱼ)``, the idea is to compute each ``bᵢⱼ`` by factoring\nout repeated expressions (thus the term *single-use expressions*).\n\nFirst, let ``i = j``. In this case,\n\n```math\nbⱼⱼ = β\\\\sum_\\\\{k, k ≠ j} a_{jk} a_{kj} + (α + βa_{jj}) a_{jj}.\n```\n\nNow consider ``i ≠ j``. Then,\n\n```math\nbᵢⱼ = β\\\\sum_\\\\{k, k ≠ i, k ≠ j} a_{ik} a_{kj} + (α + βa_{ii} + βa_{jj}) a_{ij}.\n```\n\n[1] Kosheleva, Kreinovich, Mayer, Nguyen. Computing the cube of an interval\nmatrix is NP-hard. SAC 2005.\n\"\"\"\nfunction quadratic_expansion(A::IntervalMatrix, α::Real, β::Real)\n    B = similar(A)\n    n = checksquare(A)\n\n    # case i = j\n    @inbounds for j in 1:n\n        B[j, j] = quadratic_expansion(A[j, j], α, β)\n        for k in 1:n\n            k == j && continue\n            B[j, j] += β * (A[j, k] * A[k, j])\n        end\n    end\n\n    # case i ≠ j\n    @inbounds for j in 1:n\n        for i in 1:n\n            i == j && continue\n            B[i, j] = A[i, j] * (α + β*(A[j, j] + A[i, i]))\n            for k in 1:n\n                (k == i || k == j) && continue\n                B[i, j] += β * (A[i, k] * A[k, j])\n            end\n        end\n    end\n    return B\nend\n\nfunction quadratic_expansion(x::Interval, α::Real, β::Real)\n    iszero(β) && return α * x\n\n    return ((2 * β * x + α) ^ 2 - α ^ 2) / (4 * β)\nend\n\nfunction _truncated_exponential_series(A::IntervalMatrix{T}, t, p::Integer;\n                                       n=checksquare(A)) where {T}\n    if p == 0\n        # index i = 0 (identity matrix)\n        return IntervalMatrix(Interval(one(T)) * I, n)\n    elseif p == 1\n        # index i = 1\n        S = A * t\n    else\n        # indices i = 1 and i = 2\n        S = quadratic_expansion(A, t, t^2/2)\n    end\n\n    # index i = 0, (identity matrix, added implicitly)\n    for i in 1:n\n        S[i, i] += one(T)\n    end\n\n    if p < 3\n        return S\n    end\n\n    # indices i >= 3\n    pow = IntervalMatrixPower(A)\n    increment!(pow)\n    fact_num = t^2\n    fact_denom = 2\n    for i in 3:p\n        fact_num *= t\n        fact_denom *= i\n        Aⁱ = increment!(pow)\n        S += Aⁱ * (fact_num / fact_denom)\n    end\n\n    return S\nend\n\n\"\"\"\n    exp_overapproximation(A::IntervalMatrix{T, Interval{T}}, t, p) where {T}\n\nOverapproximation of the exponential of an interval matrix.\n\n### Input\n\n- `A` -- interval matrix\n- `t` -- non-negative time value\n- `p` -- order of the approximation\n\n### Algorithm\n\nSee Theorem 1 in *Reachability Analysis of Linear Systems with Uncertain\nParameters and Inputs* by M. Althoff, O. Stursberg, M. Buss.\n\"\"\"\nfunction exp_overapproximation(A::IntervalMatrix{T, Interval{T}}, t, p) where {T}\n    n = checksquare(A)\n    S = _truncated_exponential_series(A, t, p; n=n)\n    E = _exp_remainder(A, t, p; n=n)\n    return S + E\nend\n\n# Implementation of Prop. 1 in Althoff, Matthias, Bruce H. Krogh, and Olaf Stursberg.\n# \"Analyzing reachability of linear dynamic systems with parametric uncertainties.\"\n# Modeling, Design, and Simulation of Systems with Uncertainties. Springer, Berlin, Heidelberg, 2011. 69-94.\nfunction _exp_remainder(A::IntervalMatrix{T}, t, p; n=checksquare(A)) where {T}\n    C = max.(abs.(inf(A)), abs.(sup(A)))\n    # compute Q = I + Ct + (Ct)^2/2! + ... + (Ct)^p/p!\n    Q = Matrix(Diagonal(ones(T, n)))\n\n    tⁱ = 1\n    i! = 1\n    Cⁱ = copy(C)\n    for i in 1:p\n        i! *= i\n        tⁱ *= t\n        Q += Cⁱ * tⁱ/i!\n        Cⁱ *= C\n    end\n    M = exp(C*t)\n    Y = M - Q\n    Γ = IntervalMatrix(fill(zero(T)±one(T), (n, n)))\n    E = Γ * Y\n    return E\nend\n\n# Estimates the sum of the series in the matrix exponential. See Theorem 1\n# in [1] Althoff, Matthias, Olaf Stursberg, and Martin Buss.\n# Reachability analysis of nonlinear systems with uncertain parameters using conservative linearization.\n# 2008 47th IEEE Conference on Decision and Control. IEEE, 2008.\nfunction _exp_remainder_series(A::IntervalMatrix{T}, t, p; n=checksquare(A)) where {T}\n    nA = opnorm(A, Inf)\n    c = nA * t / (p + 2)\n    @assert c < 1 \"the remainder of the matrix exponential could not be \" *\n        \"computed because a convergence condition is not satisfied: $c ≥ 1 \" *\n        \"but it should be smaller than 1; try choosing a larger order\"\n    Γ = IntervalMatrix(fill(zero(T)±one(T), (n , n)))\n    return Γ * ((nA*t)^(p+1) * (1/factorial(p + 1) * 1/(1-c)))\nend\n\n\"\"\"\n    horner(A::IntervalMatrix{T}, K::Integer; [validate]::Bool=true)\n\nCompute the matrix exponential using the Horner scheme.\n\n### Input\n\n- `A` -- interval matrix\n- `K` -- number of expansions in the Horner scheme\n- `validate` -- (optional; default: `true`) option to validate the precondition\n                of the algorithm\n\n### Algorithm\n\nWe use the algorithm in [1, Section 4.2].\n\n[1] Goldsztejn, Alexandre, Arnold Neumaier. \"On the exponentiation of interval\nmatrices\". Reliable Computing. 2014.\n\"\"\"\nfunction horner(A::IntervalMatrix{T}, K::Integer;\n                       validate::Bool=true) where {T}\n    if validate\n        nA = opnorm(A, Inf)\n        c = K + 2\n        if c <= nA\n            throw(ArgumentError(\"the precondition for the \" *\n                \"Horner-scheme algorithm is not satisfied: $c <= $nA; \" *\n                \"try choosing a larger order\"))\n        end\n    end\n    if K <= 0\n        throw(ArgumentError(\"the Horner evaluation requires a positive \" *\n            \"number of expansions but received $K\"))\n    end\n\n    n = checksquare(A)\n    Iₙ = IntervalMatrix(Interval(one(T)) * I, n)\n    H = Iₙ + A/K\n    for i in (K-1):-1:1\n        H = Iₙ + A / i * H\n    end\n\n    # remainder; the paper uses a less precise computation here\n    R = _exp_remainder(A, one(T), K)\n\n    return H + R\nend\n\n\"\"\"\n    scale_and_square(A::IntervalMatrix{T}, l::Integer, t, p;\n                     [validate]::Bool=true)\n\nCompute the matrix exponential using scaling and squaring.\n\n### Input\n\n- `A` -- interval matrix\n- `l` -- scaling-and-squaring order\n- `t` -- non-negative time value\n- `p` -- order of the approximation\n- `validate` -- (optional; default: `true`) option to validate the precondition\n                of the algorithm\n\n### Algorithm\n\nWe use the algorithm in [1, Section 4.3], which first scales `A` by factor\n``2^{-l}``, computes the matrix exponential for the scaled matrix, and then\nsquares the result ``l`` times.\n\n```math\n    \\\\exp(A * 2^{-l})^{2^l}\n```\n\n[1] Goldsztejn, Alexandre, Arnold Neumaier. \"On the exponentiation of interval\nmatrices\". Reliable Computing. 2014.\n\"\"\"\nfunction scale_and_square(A::IntervalMatrix{T}, l::Integer, t, p;\n                          validate::Bool=true) where {T}\n    if validate\n        nA = opnorm(A, Inf) * t\n        c = (p + 2) * 2.0^l\n        if c <= nA\n            throw(ArgumentError(\"the precondition for the \" *\n                \"scaling-and-squaring algorithm is not satisfied: $c <= $nA; \" *\n                \"try choosing a larger order\"))\n        end\n    end\n\n    A_scaled = A / Interval(T(2))^l\n    E = exp_overapproximation(A_scaled, t, p)\n    for i in 1:l\n        E = square(E)\n    end\n    return E\nend\n\n\"\"\"\n    exp_underapproximation(M::IntervalMatrix{T, Interval{T}}, t, p) where {T}\n\nOverapproximation of the exponential of an interval matrix.\n\n### Input\n\n- `A` -- interval matrix\n- `t` -- non-negative time value\n- `p` -- order of the approximation\n\n### Algorithm\n\nSee Theorem 2 in *Reachability Analysis of Linear Systems with Uncertain\nParameters and Inputs* by M. Althoff, O. Stursberg, M. Buss.\n\"\"\"\nfunction exp_underapproximation(A::IntervalMatrix{T, Interval{T}}, t, p) where {T}\n    @assert p > 1 \"the order $p < 2 is not supported\"\n    n = checksquare(A)\n\n    Y = zeros(n, n)\n    LA = inf(A)\n    Aⁱl = LA^2\n    Z = zeros(n, n)\n    RA = sup(A)\n    Aⁱr = RA^2\n    fact_num = t^2\n    fact_denom = 2\n    for i in 3:p\n        fact_num *= t\n        fact_denom *= i\n        fact = fact_num / fact_denom\n        Aⁱl *= LA\n        Y += Aⁱl * fact\n        Aⁱr *= RA\n        Z += Aⁱr * fact\n    end\n\n    B = IntervalMatrix{T}(undef, n , n)\n    @inbounds for j in 1:n\n        for i in 1:n\n            minYZ = min(Y[i, j], Z[i, j])\n            maxYZ = max(Y[i, j], Z[i, j])\n            B[i, j] = Interval(minYZ, maxYZ)\n        end\n    end\n\n    W = quadratic_expansion(A, t, t^2/2)\n    res = W + B\n\n    # add identity matrix implicitly\n    for i in 1:n\n        @inbounds res[i, i] += one(T)\n    end\n    return res\nend\n", "meta": {"hexsha": "bc10acdfec2ce9172cb40995a2bd4805818df0d2", "size": 8724, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/exponential.jl", "max_stars_repo_name": "JuliaReach/IntervalMatrices.jl", "max_stars_repo_head_hexsha": "2689974c1b5bc57daf4eccf37552f912986f1b27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-03-07T06:01:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T17:54:28.000Z", "max_issues_repo_path": "src/exponential.jl", "max_issues_repo_name": "JuliaReach/IntervalMatrices.jl", "max_issues_repo_head_hexsha": "2689974c1b5bc57daf4eccf37552f912986f1b27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113, "max_issues_repo_issues_event_min_datetime": "2018-02-12T22:54:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T19:16:29.000Z", "max_forks_repo_path": "src/exponential.jl", "max_forks_repo_name": "JuliaReach/IntervalMatrices.jl", "max_forks_repo_head_hexsha": "2689974c1b5bc57daf4eccf37552f912986f1b27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:30:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-30T18:05:43.000Z", "avg_line_length": 27.0092879257, "max_line_length": 108, "alphanum_fraction": 0.5804676754, "num_tokens": 2734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676518712608, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7512149104602829}}
{"text": "using LinearAlgebraicRepresentation\nLar = LinearAlgebraicRepresentation\nusing Plasm\n\n\nV,EV = Lar.randomcuboids(100, .2)\nV = Plasm.normalize(V,flag=true)\nmodel2d = V,EV\n\nSigma =  Lar.spaceindex(model2d);\nfor k=1:length(Sigma) println(k,Sigma[k]) end\n\nPlasm.view(Plasm.numbering(.15)((V,[[[k] for k=1:size(V,2)], EV])))\nPlasm.viewexploded(V,EV)(1.2,1.2,1.2) \t# no numerical errors\n\nW,EW = Lar.fragmentlines((V,EV)) \nPlasm.viewexploded(W,EW)(1.2,1.2,1.2)\t\nPlasm.view(Plasm.numbering(.015)((W,[[[k] for k=1:size(W,2)], EW])))\n\nV,EVs = Lar.biconnectedComponent((W,EW::Lar.Cells)) # 2-connected components (H & T)\nhpcs = [ Plasm.lar2hpc(V,EVs[i]) for i=1:length(EVs) ]\nPlasm.view([ Plasm.color(Plasm.colorkey[(k%12)==0 ? 12 : k%12])(hpcs[k]) for k=1:(length(hpcs)) ])\n\nW = convert(Lar.Points, V')\ncop_EV = Lar.coboundary_0(EW::Lar.Cells)\ncop_EW = convert(Lar.ChainOp, cop_EV)\nV, copEV, copFE = Lar.Arrangement.planar_arrangement(W::Lar.Points, cop_EW::Lar.ChainOp)\n\ntriangulated_faces = Lar.triangulate2D(V, [copEV, copFE])\nFVs = convert(Array{Lar.Cells}, triangulated_faces)\nW = convert(Lar.Points, V')\nPlasm.viewcolor(W::Lar.Points, FVs::Array{Lar.Cells})\n\n\n", "meta": {"hexsha": "18589861b6567012f60974b5d8ff11e28476fcf4", "size": 1154, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/2d/randomshapes.jl", "max_stars_repo_name": "eOnofri04/LinearAlgebraicRepresentation.jl", "max_stars_repo_head_hexsha": "11d5a283dc55929c0654b63b7847b01c0a4e6956", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/2d/randomshapes.jl", "max_issues_repo_name": "eOnofri04/LinearAlgebraicRepresentation.jl", "max_issues_repo_head_hexsha": "11d5a283dc55929c0654b63b7847b01c0a4e6956", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-03T11:48:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-03T11:48:14.000Z", "max_forks_repo_path": "examples/2d/randomshapes.jl", "max_forks_repo_name": "eOnofri04/LinearAlgebraicRepresentation.jl", "max_forks_repo_head_hexsha": "11d5a283dc55929c0654b63b7847b01c0a4e6956", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9714285714, "max_line_length": 98, "alphanum_fraction": 0.7019064125, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7512149082386538}}
{"text": "module FEM_P2\n\nusing SparseArrays\n\n@enum BdryCond Dirichlet Neumann\n\nexport Dirichlet, Neumann, Mesh \nexport assemble_matrix, assemble_vector, Neumann_bc_vector\nexport deriv_times_deriv!, func_times_func!\nexport evaluate_from_ndvals\n\nstruct Mesh\n    node    :: Vector{Float64}\n    elm     :: Matrix{Int64}\n    left    :: BdryCond\n    right   :: BdryCond\n    ndof    :: Int64\n    leftnd  :: Int64\n    rightnd :: Int64\nend\n\n# Element stiffness matrix = MAT1 / (3hm)\nconst MAT1 = [ 7.0  -8.0   1.0\n              -8.0  16.0  -8.0\n               1.0  -8.0   7.0 ] \n\n# Element mass matrix = (hm/30) * MAT2\nconst MAT2 = [  4.0   2.0  -1.0\n                2.0  16.0   2.0\n               -1.0   2.0   4.0 ]\n\nPsi1(ξ) = 2 * ( ξ - 1/2 ) * ( ξ - 1 )\nPsi2(ξ) = 4 * ξ * ( 1 - ξ )\nPsi3(ξ) = 2 * ξ * ( ξ - 1/2 )\nconst PSI = ( Psi1, Psi2, Psi3 )\n\ndPsi1(ξ) = 4ξ - 3\ndPsi2(ξ) = 4 * ( 1 - 2ξ )\ndPsi3(ξ) = 4ξ - 1\nconst DPSI = [ dPsi1(0.0) dPsi2(0.0) dPsi3(0.0) \n               dPsi1(0.5) dPsi2(0.5) dPsi3(0.5) \n               dPsi1(1.0) dPsi2(1.0) dPsi3(1.0) ]\n\nconst SIMPSON_WT = [ 1/6, 4/6, 1/6 ]\n\nfunction Mesh(pts::Vector{Float64}, bc::Tuple{BdryCond,BdryCond})\n    M = length(pts) - 1\n    h = diff(pts)\n    node = Vector{Float64}(undef, 2M+1)\n    elm = Matrix{Int64}(undef, 3, M)\n    if bc[1] == Dirichlet\n        for m = 1:M\n            node[2m-1] = pts[m] + h[m]/2\n            node[2m]   = pts[m+1]\n        end\n        node[2M+1] = pts[1]\n        leftnd = 2M+1\n        rightnd = 2M\n        elm[:,1] .= [ 2M+1, 1, 2]\n        for m = 2:M\n            elm[:,m] .= [ 2m-2, 2m-1, 2m ]\n        end\n        if bc[2] == Dirichlet\n            ndof = 2M-1\n        else\n            ndof = 2M\n        end\n    else\n        node[1] = pts[1]\n        leftnd = 1\n        rightnd = 2M+1\n        for m = 1:M\n            node[2m]   = pts[m] + h[m]/2\n            node[2m+1] = pts[m+1]\n            elm[:,m] .= [ 2m-1, 2m, 2m+1 ]\n        end\n        if bc[2] == Dirichlet\n            ndof = 2M\n        else\n            ndof = 2M+1\n        end\n    end\n    return Mesh(node, elm, bc[1], bc[2], ndof, leftnd, rightnd) \nend\n\nfunction assemble_matrix(mesh::Mesh, elm_mat!::Function, \n                         coef::Union{Float64,Function})\n    node, elm, ndof = mesh.node, mesh.elm, mesh.ndof\n    M = size(elm, 2)\n    Am = zeros(3, 3)\n    nodem = zeros(3)\n    I = Int64[]\n    J = Int64[]\n    V = Float64[]\n    for m = 1:M\n        for p = 1:3\n            nodem[p] = node[elm[p,m]]\n        end\n        elm_mat!(Am, nodem, coef)\n        for p = 1:3\n            if elm[p,m] > ndof\n                continue\n            end\n            for q = 1:3\n                push!(I, elm[p,m])\n                push!(J, elm[q,m])\n                push!(V, Am[p,q])\n            end\n        end\n    end\n    return sparse(I, J, V, ndof, 2M+1)\nend\n\nfunction assemble_vector(mesh::Mesh, f::Function)\n    node, elm, ndof = mesh.node, mesh.elm, mesh.ndof\n    M = size(mesh.elm, 2)\n    F = zeros(ndof)\n    Fm = zeros(3)\n    nodem = zeros(3)\n    I = Int64[]\n    V = Float64[]\n    for m = 1:M\n        for p = 1:3\n            nodem[p] = node[elm[p,m]]\n        end\n        # Use Simpson's rule\n        hm = nodem[3] - nodem[1]\n        for p = 1:3\n            Fm[p] = hm * SIMPSON_WT[p] * f(nodem[p])\n        end\n        for p = 1:3\n            if elm[p,m] > ndof\n                continue\n            end\n            F[elm[p,m]] += Fm[p]\n        end\n    end\n    return F\nend\n\nfunction Neumann_bc_vector(mesh::Mesh, γ::Vector{Float64})\n    left, right, ndof = mesh.left, mesh.right, mesh.ndof\n    leftnd, rightnd = mesh.leftnd, mesh.rightnd\n    count = 0\n    if left == Neumann\n        count += 1\n    end\n    if right == Neumann\n        count += 1\n    end\n    if length(γ) != count\n        ArgumentError(\"Wrong number of Neumann boundary values\")\n    end\n    I = zeros(Int64, count)\n    V = zeros(Float64, count)\n    k = 0\n    if left == Neumann\n        k += 1\n        I[k] = leftnd\n        V[k] = γ[k]\n    end\n    if right == Neumann\n        k += 1\n        I[k] = rightnd\n        V[k] = γ[k]\n    end\n    return sparsevec(I, V, ndof)\nend\n\nfunction deriv_times_deriv!(A::Matrix{Float64}, node::Vector{Float64},\n                            coef::Float64)\n    hm = node[3] - node[1]\n    A .= MAT1\n    A .*= coef/(3hm)\nend\n\nfunction deriv_times_deriv!(A::Matrix{Float64}, node::Vector{Float64},\n                            coef::Function)\n    hm = node[3] - node[1]\n    coefs = coef.(node)\n    for q = 1:3\n        for p = 1:q-1\n            A[p,q] = A[q,p]\n        end\n        for p = q:3\n            s = 0.0\n            for j = 1:3\n                s += SIMPSON_WT[j] * coefs[j] * DPSI[j,q] * DPSI[j,p]\n            end\n            A[p,q] = s / hm\n        end\n    end\nend\n\nfunction func_times_func!(A::Matrix{Float64}, node::Vector{Float64},\n                          coef::Float64)\n    hm = node[3] - node[1]\n    A .= MAT2\n    A .*= hm / 30\nend\n\nfunction func_times_func!(A::Matrix{Float64}, node::Vector{Float64},\n                          coef::Function)\n    hm = node[3] - node[1]\n    for p = 1:3\n        A[p,p] = hm * SIMPSON_WT[p] * coef(node[p]) \n    end\nend\n\nfunction evaluate_from_ndvals(mesh::Mesh, Und::Vector{Float64}, \n                              r::Int64=10)\n    node, elm, ndof = mesh.node, mesh.elm, mesh.ndof\n    left, right = mesh.left, mesh.right\n    leftnd, rightnd = mesh.leftnd, mesh.rightnd\n    M = size(elm, 2)\n    x = zeros(r*M+1)\n    U = zeros(r*M+1)\n    x[1] = node[leftnd]\n    U[1] = Und[elm[1,1]]\n    for m = 1:M\n        lo = node[elm[1,m]]\n        hi = node[elm[3,m]]\n        hm = hi - lo\n        step = hm / r\n        for k = 1:r\n            j = (m-1) * r + 1 + k\n            x[j] = lo + k * step\n            s = 0.0\n            for p = 1:3\n                ξ = k / r\n                s += Und[elm[p,m]] * PSI[p](ξ)\n            end\n            U[j] = s\n        end\n    end\n    return x, U\nend\n\nend # module\n", "meta": {"hexsha": "089a7ae98b1cff0ecc59b8f17d946c94db1a978b", "size": 5855, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chap2/FEM_P2.jl", "max_stars_repo_name": "billmclean/ComputationalMathsNotes", "max_stars_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T21:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:30:20.000Z", "max_issues_repo_path": "src/chap2/FEM_P2.jl", "max_issues_repo_name": "billmclean/ComputationalMathsNotes", "max_issues_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chap2/FEM_P2.jl", "max_forks_repo_name": "billmclean/ComputationalMathsNotes", "max_forks_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3958333333, "max_line_length": 70, "alphanum_fraction": 0.4652433817, "num_tokens": 2129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159727, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7512149081230438}}
{"text": "module Sigmoid\n    using LoopVectorization\n\n    function func!(output_matrix::Array{Float32}, value_matrix::Array{Float32})\n        @avxt for i in eachindex(value_matrix)\n            value_matrix[i] = ifelse(value_matrix[i]>3.0f38, 3.0f38, value_matrix[i])\n            value_matrix[i] = ifelse(value_matrix[i]<-3.0f38, -3.0f38, value_matrix[i])\n            output_matrix[i] = ifelse(value_matrix[i]>=0, 1/(1+exp(-value_matrix[i])), exp(value_matrix[i])/(1+exp(value_matrix[i])))\n        end\n    end\n\n    function get_∇biases!(∇biases::Array{Float32}, value_matrix::Array{Float32}, δ::Array{Float32})\n        @avxt for i in eachindex(value_matrix)\n            ∇biases[i] = exp(-value_matrix[i])/(1+exp(-value_matrix[i]))^2*δ[i]\n        end\n    end\n\n    function get_name()\n        return \"Sigmoid\"\n    end\nend\n\n# Source: https://timvieira.github.io/blog/post/2014/02/11/exp-normalize-trick/\n", "meta": {"hexsha": "2082c93e1791d3d340e6de301a2425714beb7d8e", "size": 890, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/activation_function/sigmoid.jl", "max_stars_repo_name": "SkyWorld117/Dianoia.jl", "max_stars_repo_head_hexsha": "f5f9e4ffcbb7ef70c796430ba430e82aa24705c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-02-17T15:37:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T19:33:39.000Z", "max_issues_repo_path": "src/activation_function/sigmoid.jl", "max_issues_repo_name": "SkyWorld117/YisyAIFramework.jl", "max_issues_repo_head_hexsha": "f5f9e4ffcbb7ef70c796430ba430e82aa24705c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-21T05:58:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-24T12:39:04.000Z", "max_forks_repo_path": "src/activation_function/sigmoid.jl", "max_forks_repo_name": "SkyWorld117/YisyAIFramework.jl", "max_forks_repo_head_hexsha": "f5f9e4ffcbb7ef70c796430ba430e82aa24705c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0833333333, "max_line_length": 133, "alphanum_fraction": 0.6483146067, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765187126078, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7512149024986415}}
{"text": "import MLBase\nimport StatsBase\n\n\"\"\"\n\"\"\"\nfunction getallrocnums(\n        ytrue::AbstractVector{<:Integer},\n        yscore::AbstractVector{<:Real};\n        additionalthreshold::AbstractFloat = 0.5,\n        )\n    allthresholds = get_binary_thresholds(\n        yscore;\n        additionalthreshold = additionalthreshold,\n        )\n    allrocnums = MLBase.roc(\n        ytrue,\n        yscore,\n        allthresholds,\n        )\n    return allrocnums, allthresholds\nend\n\n\"\"\"\n\"\"\"\naccuracy(x::MLBase.ROCNums) = (x.tp + x.tn)/(x.p + x.n)\n\n\"\"\"\n\"\"\"\ntrue_positive_rate(x::MLBase.ROCNums) = (x.tp)/(x.p)\n\n\"\"\"\n\"\"\"\ntrue_negative_rate(x::MLBase.ROCNums) = (x.tn)/(x.n)\n\n\"\"\"\n\"\"\"\nfalse_positive_rate(x::MLBase.ROCNums) = (x.fp)/(x.n)\n\n\"\"\"\n\"\"\"\nfalse_negative_rate(x::MLBase.ROCNums) = (x.fn)/(x.p)\n\n\"\"\"\n\"\"\"\nfunction positive_predictive_value(x::MLBase.ROCNums)\n    if (x.tp == 0) && (x.tp + x.fp == 0)\n        result = 1\n    elseif (x.tp != 0) && (x.tp + x.fp == 0)\n        error(\"x.tp != 0) && (x.tp + x.fp == 0)\")\n    else\n        result = (x.tp) / (x.tp + x.fp)\n    end\n    return result\nend\n\n\"\"\"\n\"\"\"\nfunction negative_predictive_value(x::MLBase.ROCNums)\n    if (x.tn == 0) && (x.tn + x.fn ==0)\n        result = 1\n    elseif (x.tn != 0) && (x.tn + x.fn == 0)\n        error(\"(x.tn != 0) && (x.tn + x.fn == 0)\")\n    else\n        result = (x.tn) / (x.tn + x.fn)\n    end\n    return result\nend\n\n\"\"\"\n\"\"\"\nsensitivity(x::MLBase.ROCNums) = true_positive_rate(x)\n\n\"\"\"\n\"\"\"\nspecificity(x::MLBase.ROCNums) = true_negative_rate(x)\n\n\"\"\"\n\"\"\"\nprecision(x::MLBase.ROCNums) = positive_predictive_value(x)\n\n\"\"\"\n\"\"\"\nrecall(x::MLBase.ROCNums) = true_positive_rate(x)\n\n\"\"\"\n\"\"\"\nfunction fbetascore(\n        x::MLBase.ROCNums,\n        beta::Real,\n        )\n    p = precision(x)\n    r = recall(x)\n    result = ( 1 + beta^2 ) * ( p*r ) / ( ((beta^2) * p) + r )\n    return result\nend\n\n\"\"\"\n\"\"\"\nf1score(x::MLBase.ROCNums) = fbetascore(x, 1)\n\n", "meta": {"hexsha": "f6a240ad0df4ce30f9f11b18f91bedd34615134d", "size": 1892, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/toplevel/always-loaded/metrics/rocnumsmetrics.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PredictMD.jl-3e7d7328-36f8-4388-bd01-4613c92c7370", "max_stars_repo_head_hexsha": "7987993b5900e658c3aa9c568a9ed7fe38e82f11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2018-05-24T14:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T08:17:39.000Z", "max_issues_repo_path": "src/toplevel/always-loaded/metrics/rocnumsmetrics.jl", "max_issues_repo_name": "UnofficialJuliaMirror/PredictMD.jl-3e7d7328-36f8-4388-bd01-4613c92c7370", "max_issues_repo_head_hexsha": "7987993b5900e658c3aa9c568a9ed7fe38e82f11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 383, "max_issues_repo_issues_event_min_datetime": "2018-04-12T21:53:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-24T15:53:37.000Z", "max_forks_repo_path": "src/toplevel/always-loaded/metrics/rocnumsmetrics.jl", "max_forks_repo_name": "UnofficialJuliaMirror/PredictMD.jl-3e7d7328-36f8-4388-bd01-4613c92c7370", "max_forks_repo_head_hexsha": "7987993b5900e658c3aa9c568a9ed7fe38e82f11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-05-06T23:16:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T15:49:49.000Z", "avg_line_length": 18.7326732673, "max_line_length": 62, "alphanum_fraction": 0.5523255814, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.751214894594805}}
{"text": "using Plots, RDatasets, DataFrames, StatPlots, Query\n\ngr()\n\niris = dataset(\"datasets\", \"iris\")\n\nfunction dfmean(df::DataFrame)\n    return [mean(i) for i in df.columns]\nend\n\nfunction dfcov(df)\n    cols = df.columns\n    ncols = size(cols)[1]\n    ndatas = size(cols[1])[1]\n    array = zeros(ncols, ncols)\n    mean = dfmean(df)\n    for i in 1:ncols\n        for j in 1:ncols\n            array[i, j] = 1/ndatas * (cols[i] .- mean[i])' * (cols[j] .- mean[j])\n        end\n    end\n    return array\nend\n\nfunction whitening(df)\n    groups = Array(df[:Species])\n    petals = df[[:PetalLength, :PetalWidth]]\n    colnames = names(petals)\n\n    values = Array(petals)\n    mu = reshape(dfmean(petals), (1, 2))\n\n    coviris = dfcov(petals)\n    S = -swap(eigvecs(coviris))\n\n    Lambda = S' * coviris * S\n    L = zeros(size(Lambda))\n    for i in 1:size(L)[1]\n        L[i, i] = sqrt(Lambda[i, i])\n    end\n    u = (values .- mu) * S * inv(L)\n\n    tf_df = DataFrame()\n    tf_df[colnames[1]] = u[:, 1]\n    tf_df[colnames[2]] = u[:, 2]\n    tf_df[:Species] = groups\n    return tf_df\nend\n\nfunction swap(array)\n    temp = zeros(2, 2)\n    temp[:, 1] = array[:, 2]\n    temp[:, 2] = array[:, 1]\n\n    return temp\nend\n\n@df iris scatter(:PetalLength, :PetalWidth, group=:Species,\n                 m=(0.5, [:+ :h :star7], 12), bg=RGB(.2,.2,.2))\n\nscatter!(xlabel=\"Petal Length\", ylabel=\"Petal Width\", title=\"No Whitening\",\n         xlims=(1, 7), ylims=(-1, 4))\nsavefig(\"../figures/no_whitening.png\")\n\nwhitened = whitening(iris)\n\n@df whitened scatter(:PetalLength, :PetalWidth, group=:Species,\n                         m=(0.5, [:+ :h :star7], 12), bg=RGB(.2,.2,.2))\nscatter!(xlabel=\"Petal Length\", ylabel=\"Petal Width\", title=\"Whitened\",\n         xlims=(-3, 3), ylims=(-3, 3))\nsavefig(\"../figures/whitened.png\")\n", "meta": {"hexsha": "e09256dfcd56b382e56149e0f2d45760593d5bba", "size": 1775, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JuliaScripts/Whitening.jl", "max_stars_repo_name": "koukyo1994/pattern_recognition", "max_stars_repo_head_hexsha": "0bf835b98baa66cdb78aa46c677b8de91790a767", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JuliaScripts/Whitening.jl", "max_issues_repo_name": "koukyo1994/pattern_recognition", "max_issues_repo_head_hexsha": "0bf835b98baa66cdb78aa46c677b8de91790a767", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JuliaScripts/Whitening.jl", "max_forks_repo_name": "koukyo1994/pattern_recognition", "max_forks_repo_head_hexsha": "0bf835b98baa66cdb78aa46c677b8de91790a767", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6527777778, "max_line_length": 81, "alphanum_fraction": 0.5729577465, "num_tokens": 594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7512144031792579}}
{"text": "#---------------------------------------------------------------------#\n#This function computes the Norm of two vectors\n#Written by F.X. Giraldo on April 19, 2019\n#           Department of Applied Mathematics\n#           Naval Postgraduate School\n#           Monterey; CA 93943-5216\n#---------------------------------------------------------------------#\nusing LinearAlgebra\n\nfunction compute_norms(qn,qe,npoin,DFloat)\n\n    norms=zeros(DFloat,3)\n    norms[1]=norm(qn-qe,1)/norm(qe,1)\n    norms[2]=norm(qn-qe,2)/norm(qe,2)\n    norms[3]=norm(qn-qe,Inf)/norm(qe,Inf)\n    return (norms)\n\nend\n", "meta": {"hexsha": "dda6bed7fde365266136b84d1128ff8e75d6c54e", "size": 588, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Projects/Project_03_1D_Burger/For_Instructors/julia/compute_norms.jl", "max_stars_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_stars_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-12-28T06:19:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:40:33.000Z", "max_issues_repo_path": "Projects/Project_03_1D_Burger/For_Instructors/julia/compute_norms.jl", "max_issues_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_issues_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-29T19:12:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-29T21:53:41.000Z", "max_forks_repo_path": "Projects/Project_03_1D_Burger/For_Instructors/julia/compute_norms.jl", "max_forks_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_forks_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:35:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T06:53:34.000Z", "avg_line_length": 30.9473684211, "max_line_length": 71, "alphanum_fraction": 0.5051020408, "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7512143990129629}}
{"text": "#!/usr/bin/env julia\n\nusing Random\n\n# mod must always be positive\n\nfunction mod(a, n)\n    if (t = a % n) < 0\n        n + t\n    else\n        t\n    end\nend\n\n#=\na^b (mod n) using the method of repeated squares.\n\nThe key here is that every integer can be written as a sum of powers of 2 (binary numbers)\nand that includes the exponent. By repeated squaring we get a raised to a power of 2. Also\nrecall that a^b * a^c = a^(b + c), so rather than adding we multiply since we are dealing\nwith the exponent.\n=#\n\nfunction powerMod(a, d, n)\n    v = 1 # Value\n    p = a # Powers of a\n    while d > 0\n        if isodd(d) # 1 bit in the exponent\n           v = mod(v * p, n)\n        end\n        p = mod(p^2, n) # Next power of two\n        d >>>= 1\n    end\n    v\nend\n\n#=\nGreatest common divisor, Euclidean version.\n=#\n\nfunction gcd(a, b)\n    while b ≠ 0\n        a, b = b, mod(a, b)\n    end\n    a\nend\n\n#=\nWitness loop of the Miller-Rabin probabilistic primality test.\n=#\n\nfunction witness(a, n)\n    u, t = n - 1, 0\n    while iseven(u) # n = u * 2^t + 1\n        t += 1   # Increase exponent\n        u >>>= 1 # Decrease the multiplier\n    end\n    x = powerMod(a, u, n)\n    for i in 1:t\n        y = powerMod(x, 2, n)\n        if y == 1 && x ≠ 1 && x ≠ n - 1\n            return true\n        end\n        x = y\n    end\n    x ≠ 1\nend\n\n#=\nMiller-Rabin probabilistic primality test: the chance of being wrong is ≈ 1/4 each pass through\nthe loop.\n=#\n\nfunction isPrime(n, k)\n    if n < 2 || (n ≠ 2 && iseven(n)) # 0, 1, and even except for 2 are not prime.\n        return false\n    elseif n < 4 # 3 is prime\n        return true\n    end # We must test all others\n    for j in 1:k\n        a = rand(2:n - 2) # Choose a random witness\n        if witness(a, n)\n            return false\n        end\n    end\n    true\nend\n\n#=\nWe need a random prime number in [low, high] and for now a 4^–100 chance of a composite is\ngood enough.\n=#\n\nfunction randomPrime(low, high)\n    guess = 0 # Certainly not prime!\n    while !isPrime(guess, 100)\n        guess = rand(low:high) # Half will be even, the rest have Pr[prime] ≈ 1/log(N).\n    end\n    guess\nend\n\n#=\nA safe prime is the one following a Sophie German prime. If prime(p) and prime(2p + 1) then\n2p + 1 is a safe prime.\n=#\n\nfunction safePrime(low, high)\n    p = randomPrime(low, high)\n    while !isPrime(2 * p + 1,100)\n        p = randomPrime(low, high)\n    end\n    return 2 * p + 1\nend\n\n#=\nA generator must not be congruent to 1 for any of its powers that are\nproper divisors of p – 1.  Since p is safe prime, there are only two:\n2 and (p – 1) / 2. The number of such generators is 𝜑(p – 1).\n=#\n\nfunction generator(n, p)\n    g = n\n    q = (p - 1) ÷ 2\n    while powerMod(g, 2, p) == 1 && powerMod(g, q, p) == 1\n        g = g + 1\n    end\n    g\nend\n\n#=\nGenerate an efficient description of a cyclic group G of order p, with generator r.\n\nChoose a random integer a ∊ {(p – 1)/2, ..., p − 1}\n\nCompute b = r^a\n\nThe public key consists of the values (p, r, b)\n\nThe private key consists of the values (p, a)\n=#\n\nfunction keys(safe, k)\n    f = safe ? safePrime : randomPrime\n    p = f(big\"2\"^(k - 1), big\"2\"^k - 1)\n    r = generator(big\"2\"^16 + 1, p)\n    a = rand((p - 1) ÷ 2:p - 1)\n    b = powerMod(r, a, p)\n    ((p, a), (p, r, b))\nend\n\n#=\nChoose a random k ∊ {1, ..., p – 2}\n\nCompute 𝛾 = r^k (mod p)\n\nCompute 𝛿 = m b^k (mod p)\n\nThe encrypted message is (𝛾, 𝛿)\n=#\n\nfunction encrypt(m, key)\n    (p, r, b) = key\n    k = rand(1:p - 2)\n    𝛾 = powerMod(r, k, p)\n    𝛿 = mod(m * powerMod(b, k, p), p)\n    (𝛾, 𝛿)\nend\n\n#=\nThe decrypted message is 𝛿 𝛾^(p – 1 – a) (mod p)\n=#\n\nfunction decrypt(m, key)\n    (p, a) = key\n    (𝛾, 𝛿) = m\n    mod((powerMod(𝛾, p - 1 - a, p) * 𝛿), p)\nend\n\nfunction encode(s)\n    sum::BigInt = 0\n    pow::BigInt = 1\n    for c in s\n        sum += pow * BigInt(c)\n        pow *= 256\n    end\n    sum\nend\n\n#=\nTransform a BigInt back into a string, subtracting off the 0xAA. We treat it as a base-256\ninteger and just pull off the digits.\n=#\n\nfunction decode(n)\n    s = \"\"\n    while n > 0\n        s = s * Char(mod(n, 256))\n        n ÷= 256\n    end\n    s\nend\n\nprint(\"How many bits? \")\n\nbits = parse(Int64, readline())\n\n(prv, pub) = keys(false, bits)\n\nprintln(\"pub = $pub\")\nprintln(\"prv = $prv\")\n\nprint(\">> \")\nfor m in eachline()\n    c = encrypt(encode(m), pub); println(\"En[$m] = $c\")\n    t = decode(decrypt(c, prv)); println(\"De[$c] = $t\")\n    print(\">> \")\nend\n", "meta": {"hexsha": "6afe37d4540160356c9b1ba25a8a8bfc78032d9d", "size": 4375, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "elgamal.jl", "max_stars_repo_name": "darrelllong/El-Gamal-in-Julia", "max_stars_repo_head_hexsha": "49199ed4572451f0cf68567e0702e671d2a40c4b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "elgamal.jl", "max_issues_repo_name": "darrelllong/El-Gamal-in-Julia", "max_issues_repo_head_hexsha": "49199ed4572451f0cf68567e0702e671d2a40c4b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "elgamal.jl", "max_forks_repo_name": "darrelllong/El-Gamal-in-Julia", "max_forks_repo_head_hexsha": "49199ed4572451f0cf68567e0702e671d2a40c4b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0688073394, "max_line_length": 95, "alphanum_fraction": 0.5620571429, "num_tokens": 1528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7512143988277643}}
{"text": "using ADCME\nusing LinearAlgebra \nusing AdFem\nusing PyPlot \nusing SparseArrays\n\nfunction Q_exact(x, y)\n    # (2*x^2*y*(x - 1)*(2*y - 1) + 1.0*(y^2 + 1)^2*(x*y*(x - 1) + x*y*(y - 1) + x*(x - 1)*(y - 1) + y*(x - 1)*(y - 1)) - (y^2 + 1)*(2*x*(x - 1)*(x + (x^2 + 1)*(y^2 + 1)) + 2*y*(x + (x^2 + 1)*(y^2 + 1))*(y - 1) + y*(2*x - 1)*(y - 1)*(2*x*(y^2 + 1) + 1)))/(y^2 + 1)^2\n    # (2*x^2*y*(x - 1)*(2*y - 1) + x*(y^2 + 1)^2*(-y^2*(2*x - 1)*(y - 1)^2 + 1.0*y*(x - 1) + 1.0*(x - 1)*(y - 1)) - (y^2 + 1)*(2*x*(x - 1)*(x + (x^2 + 1)*(y^2 + 1)) + 2*y*(x + (x^2 + 1)*(y^2 + 1))*(y - 1) + y*(2*x - 1)*(y - 1)*(2*x*(y^2 + 1) + 1)))/(y^2 + 1)^2\n    (2*x^2*y*(x - 1)*(2*y - 1)*(x + y + 1) - x*y^2*(2*x - 1)*(y - 1)^2*(y^2 + 1)^2*(x + y + 1) + x*(x - 1)*(2*y - 1)*(y^2 + 1)^2 - (y^2 + 1)*(x + y + 1)*(2*x*(x - 1)*(x + (x^2 + 1)*(y^2 + 1)) + 2*y*(x + (x^2 + 1)*(y^2 + 1))*(y - 1) + y*(2*x - 1)*(y - 1)*(2*x*(y^2 + 1) + 1)))/((y^2 + 1)^2*(x + y + 1))\nend\n\nfunction T_exact(x, y)\n    x * (1-x) * y * (1-y)\nend\n\nfunction u_exact(x, y)\n    x * y * (1-y)\nend\n\nfunction v_exact(x, y)\n    1 / (1 + x + y)\nend\n\nfunction k_exact(x, y)\n    1 + x^2 + x / (1 + y^2)\nend\n\n# function k_nn(xy) # xy shape N (=m*n) x 2\n#     out = fc(xy, [20,20,20,1])^2 + 0.1 # N x 1 \n#     squeeze(out)\n# end\n\n#---------------------------------------------\n# grid setup\n\n######## mesh 1 ########\n# m = 20\n# n = 20\n# h = 1/n \n# mesh = Mesh(m, n, h)\n\n######## mesh 2 ########\nfilename = \"CHT_2D.stl\"\nfile_format = \"stl\"\nmesh = Mesh(filename, file_format = file_format)\nmesh = Mesh(mesh.nodes ./ 0.0305, mesh.elems)\n\nnnode = size(mesh.nodes, 1)\nnelem = size(mesh.elems, 1)\n\n#---------------------------------------------\n# discretized governing equation \n#  J * u^{n+1} - J * u^n = - v ⋅ grad u + K * u^{n+1} + F^{n+1}\n#---------------------------------------------\nxy = mesh.nodes\nx, y = xy[:,1], xy[:,2]\nT0 = @. T_exact(x, y)\nu = @. u_exact(x,y)\nv = @. v_exact(x,y)\nQ = @. Q_exact(x,y)\nk = @. k_exact(x, y)\n# k0 = @. k_nn(xy)\n\n# ---------------------------------------------\n\nbd = Array{Int64, 1}([])\neps = 1e-6\nfor j = 1:nnode\n    nodex, nodey = mesh.nodes[j, 1], mesh.nodes[j, 2]\n    if abs(nodex-0.0) <= eps || abs(nodex-1.0) <= eps || abs(nodey-0.0) <= eps || abs(nodey-1.0) <= eps\n        global bd = [bd; j]\n    end\nend\n\nugauss = fem_to_gauss_points(u, mesh)\nvgauss = fem_to_gauss_points(v, mesh)\nkgauss = fem_to_gauss_points(k, mesh)\nQgauss = fem_to_gauss_points(Q, mesh)\n\nAdvection = constant(compute_fem_advection_matrix1(constant(ugauss), constant(vgauss), mesh))\nLaplace = compute_fem_laplace_matrix1(constant(kgauss), mesh)\nA = Advection + Laplace\nA, _ = fem_impose_Dirichlet_boundary_condition1(A, bd, mesh)\nb = constant(compute_fem_source_term1(constant(Qgauss), mesh))\nb = scatter_update(b, bd, zeros(length(bd)))\nsol = A\\b\n\n# ---------------------------------------------------\n# create a session and run \nsess = Session(); init(sess)\nT_computed = run(sess, sol)\n\n#---------------------------------------------\n# visualize numerical solution and exact solution\nfigure(figsize=(10,4))\nsubplot(121)\nvisualize_scalar_on_fem_points(T_computed, mesh, with_mesh=true)\nsubplot(122)\nvisualize_scalar_on_fem_points(T0, mesh, with_mesh=true)\nsavefig(\"forward_solution_unstructured.png\")\nclose(\"all\")", "meta": {"hexsha": "a65723fb54404af85d7369fd643e39d849e46a9d", "size": 3254, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/codes/CHTEnergy/CHTEnergy_fem_unstructured.jl", "max_stars_repo_name": "kailaix/AdFem.jl", "max_stars_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2020-10-18T01:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:13:24.000Z", "max_issues_repo_path": "docs/src/codes/CHTEnergy/CHTEnergy_fem_unstructured.jl", "max_issues_repo_name": "kailaix/AdFem.jl", "max_issues_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-10-19T03:51:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:38:46.000Z", "max_forks_repo_path": "docs/src/codes/CHTEnergy/CHTEnergy_fem_unstructured.jl", "max_forks_repo_name": "kailaix/AdFem.jl", "max_forks_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-11-05T11:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T19:30:09.000Z", "avg_line_length": 31.9019607843, "max_line_length": 301, "alphanum_fraction": 0.4938537185, "num_tokens": 1334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7512143988277643}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction _geo2geodetic{T<:AbstractFloat}(lat::T, long::T, alt::T, eqrad::T, polrad::T)\n    e = sqrt(eqrad^2 - polrad^2)/eqrad\n    lat = deg2rad(lat)\n    long_rad = deg2rad(long)\n    x = (eqrad + alt)*cos(lat)*cos(long_rad)\n    y = (eqrad + alt)*cos(lat)*sin(long_rad)\n    z = (eqrad + alt)*sin(lat)\n    r = hypot(x, y)\n    s    = hypot(r, z)*(1.0 - eqrad*sqrt((1.0 - e^2)/((1.0 - e^2)*r^2 + z^2)))\n    t0   = 1.0 + s*sqrt(1.0 - (e*z)^2/(r^2 + z^2))/eqrad\n    dzeta1 = z*t0\n    xi1  = r*(t0 - e^2)\n    rho1 = hypot(xi1, dzeta1)\n    c1   = xi1/rho1\n    s1   = dzeta1/rho1\n    b1   = eqrad/sqrt(1.0 - (e*s1)^2)\n    u1   = b1*c1\n    w1   = b1*s1*(1.0 - e^2)\n    return rad2deg(atan2(s1, c1)), long, hypot(r - u1, z - w1)\nend\n\n\"\"\"\n    geo2geodetic(latitude, longitude, altitude) -> latitude, longitude, altitude\n    geo2geodetic(latitude, longitude, altitude, planet) -> latitude, longitude, altitude\n    geo2geodetic(latitude, longitude, altitude, equatorial_radius, polar_radius) -> latitude, longitude, altitude\n\n### Purpose ###\n\nConvert from geographic (or planetographic) to geodetic coordinates.\n\n### Explanation ###\n\nConverts from geographic (latitude, longitude, altitude) to geodetic (latitude,\nlongitude, altitude).  In geographic coordinates, the Earth is assumed a perfect\nsphere with a radius equal to its equatorial radius.  The geodetic (or\nellipsoidal) coordinate system takes into account the Earth's oblateness.\n\nGeographic and geodetic longitudes are identical.  Geodetic latitude is the\nangle between local zenith and the equatorial plane.  Geographic and geodetic\naltitudes are both the closest distance between the satellite and the ground.\n\n### Arguments ###\n\nThe function has two base methods.  The arguments common to all methods and\nalways mandatory are `latitude`, `longitude`, and `altitude`:\n\n* `latitude`: geographic latitude, in degrees.\n* `longitude`: geographic longitude, in degrees.\n* `altitude`: geographic altitude, in kilometers.\n\nIn order to convert to geodetic coordinates, you can either provide custom\nequatorial and polar radii of the planet or use the values of one of the planets\nof Solar System (Pluto included).\n\nIf you want to use the method with explicit equatorial and polar radii the\nadditional mandatory arguments are:\n\n* `equatorial_radius`: value of the equatorial radius of the body, in\n  kilometers.\n* `polar_radius`: value of the polar radius of the body, in kilometers.\n\nInstead, if you want to use the method with the selection of a planet, the only\nadditional argument is the planet name:\n\n* `planet` (optional string argument): string with the name of the Solar System\n  planet, from \"Mercury\" to \"Pluto\".  If omitted (so, when only `latitude`,\n  `longitude`, and `altitude` are provided), the default is \"Earth\".\n\nIn all cases, the three coordinates can be passed as a 3-tuple `(latitude,\nlongitude, altitude)`.  In addition, geographical `latitude`, `longitude`, and\n`altitude` can be given as arrays of the same length.\n\n### Output ###\n\nThe 3-tuple `(latitude, longitude, altitude)` in geodetic coordinates, for the\nbody with specified equatorial and polar radii (Earth by default).\n\nIf geographical coordinates are given as arrays, a 3-tuple of arrays of the same\nlength is returned.\n\n### Method ###\n\nStephen P.  Keeler and Yves Nievergelt, \"Computing geodetic coordinates\", SIAM\nRev. Vol. 40, No. 2, pp. 300-309, June 1998\n(DOI:[10.1137/S0036144597323921](http://dx.doi.org/10.1137/S0036144597323921)).\n\nPlanetary constants are from Planetary Fact Sheet\n(http://nssdc.gsfc.nasa.gov/planetary/factsheet/index.html).\n\n### Example ###\n\nLocate the Earth geographic North pole (latitude: 90°, longitude: 0°, altitude 0\nkm), in geodetic coordinates:\n\n``` julia\ngeo2geodetic(90, 0, 0)\n# => (90.0,0.0,21.38499999999931)\n```\n\nThe same for Jupiter:\n\n``` julia\ngeo2geodetic(90, 0, 0, \"Jupiter\")\n# => (90.0,0.0,4355.443799999994)\n```\n\nFind geodetic coordinates for point of geographic coordinates (latitude,\nlongitude, altitude) = (43.16°, -24.32°, 3.87 km) on a planet with equatorial\nradius 8724.32 km and polar radius 8619.19 km:\n\n``` julia\ngeo2geodetic(43.16, -24.32, 3.87, 8724.32, 8619.19)\n# => (43.849399515234516,-24.32,53.53354478670836)\n```\n\n### Notes ###\n\nWhereas the conversion from geodetic to geographic coordinates is given by an\nexact, analytical formula, the conversion from geographic to geodetic isn't.\nApproximative iterations (as used here) exist, but tend to become less good with\nincreasing eccentricity and altitude.  The formula used in this routine should\ngive correct results within six digits for all spatial locations, for an\nellipsoid (planet) with an eccentricity similar to or less than Earth's.  More\naccurate results can be obtained via calculus, needing a non-determined amount\nof iterations.\n\nIn any case, the function `geodetic2geo`, which converts from geodetic (or\nplanetodetic) to geographic coordinates, can be used to estimate the accuracy of\n`geo2geodetic`.\n\n``` julia\ncollect(geodetic2geo(geo2geodetic(67.2, 13.4, 1.2))) - [67.2, 13.4, 1.2]\n# => 3-element Array{Float64,1}:\n#     -3.56724e-9\n#      0.0\n#      9.47512e-10\n```\n\nCode of this function is based on IDL Astronomy User's Library.\n\"\"\"\ngeo2geodetic(lat::Real, long::Real, alt::Real, eq::Real, pol::Real) =\n    _geo2geodetic(promote(float(lat), float(long), float(alt),\n                          float(eq), float(pol))...)\n\ngeo2geodetic(lla::Tuple{Real, Real, Real}, eq::Real, pol::Real) =\n    geo2geodetic(lla..., eq, pol)\n\nfunction geo2geodetic{LA<:Real, LO<:Real, AL<:Real}(lat::AbstractArray{LA},\n                                                    long::AbstractArray{LO},\n                                                    alt::AbstractArray{AL},\n                                                    eq::Real, pol::Real)\n    @assert length(lat) == length(long) == length(alt)\n    typela  = typeof(float(one(LA)))\n    outlat  = similar(lat, typela)\n    outlong = similar(lat, typela)\n    outalt  = similar(lat, typela)\n    for i in eachindex(lat)\n        outlat[i], outlong[i], outalt[i] =\n            geo2geodetic(lat[i], long[i], alt[i], eq, pol)\n    end\n    return outlat, outlong, outalt\nend\n\n##### Select a planet.\ngeo2geodetic(lat::Real, long::Real, alt::Real, planet::AbstractString=\"earth\") =\n    (planet = lowercase(strip(planet));\n     geo2geodetic(lat, long, alt, planets[planet].eqradius*1e-3,\n                  planets[planet].polradius*1e-3))\n\ngeo2geodetic(lla::Tuple{Real, Real, Real}, planet::AbstractString=\"earth\") =\n    geo2geodetic(lla..., planet)\n\nfunction geo2geodetic{LA<:Real, LO<:Real, AL<:Real}(lat::AbstractArray{LA},\n                                                    long::AbstractArray{LO},\n                                                    alt::AbstractArray{AL},\n                                                    planet::AbstractString=\"earth\")\n    @assert length(lat) == length(long) == length(alt)\n    typela  = typeof(float(one(LA)))\n    outlat  = similar(lat, typela)\n    outlong = similar(lat, typela)\n    outalt  = similar(lat, typela)\n    for i in eachindex(lat)\n        outlat[i], outlong[i], outalt[i] =\n            geo2geodetic(lat[i], long[i], alt[i], planet)\n    end\n    return outlat, outlong, outalt\nend\n", "meta": {"hexsha": "7bf110997c7c4b6862ad2daeb088411514f1c7a3", "size": 7310, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geo2geodetic.jl", "max_stars_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_stars_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/geo2geodetic.jl", "max_issues_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_issues_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geo2geodetic.jl", "max_forks_repo_name": "JuliaPackageMirrors/AstroLib.jl", "max_forks_repo_head_hexsha": "d56c7307efa7e784554c1ee806664af51b82a052", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2722513089, "max_line_length": 113, "alphanum_fraction": 0.6701778386, "num_tokens": 2119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7512143959885016}}
{"text": "\"\"\"\n    centroid(simplex::AbstractArray{Float64, 2}) where {T<:Number} -> Array{Float64, 2}\n\nComputes the centroid of a simplex given by `(dim+1)`-by-`dim` array, where\neach row is a vertex. Returns the centroid as a vertex (a `1`-by-`dim`\ntwo-dimensional array).\n\n\"\"\"\nfunction centroid(simplex::AbstractArray{T, 2}) where {T<:Number}\n    n = size(simplex, 1) # Dimension of the space the simplex lives in\n    transpose(ones(n, 1)/n) * simplex\nend\n\n\"\"\"\n    radius(simplex::Array{T, 2}, centroid::Array{T, 2}) where {T<:Number}\n\nCompute radius of a simplex (`(dim+1)`-by-`dim` sized `Array{Float64, 2}`\ngiven its centroid (`1`-by-`dim` sized `Array{Float64, 2}`).\n\"\"\"\nfunction radius(simplex::AbstractArray{T, 2}, centroid::AbstractArray{T, 2}) where {T<:Number}\n\n    # Express vertices with respect to origin\n    dim = size(simplex, 2)\n    dists_to_centroid = broadcast(-, centroid, simplex) # subtract centroid from all vertices\n    maximum(sqrt.(sum(dists_to_centroid.^2, 2)))\nend\n\n\n\"\"\"\n    radius(s::AbstractArray{T, 2}) where {T<:Number} -> Float64\n\nCompute radius of a simplex `s`, represented by a `Array{Float64, 2}` of size\n`(dim+1)`-by-`dim`.\n\"\"\"\nfunction radius(simplex::AbstractArray{T, 2}) where {T<:Number}\n\n    # Express vertices with respect to origin\n    dim = size(simplex, 2)\n    dists_to_centroid = broadcast(-, centroid(simplex), simplex) # subtract centroid from all vertices\n    maximum(sqrt.(sum(dists_to_centroid .^ 2, 2)))\nend\n\n\n\"\"\"\n    orientation(simplex::AbstractArray{T, 2}) where {T<:Number} -> Float64\n\nCompute orientation of a `simplex`, represented by a `Array{Float64, 2}` of size `(dim+1)`-by-`dim`.\n\"\"\"\nfunction orientation(simplex::AbstractArray{T, 2}) where {T<:Number}\n    dim = size(simplex, 2)\n    hcat(ones(dim + 1, 1), simplex) |> det\nend\n\n\"\"\"\n    volume(simplex::AbstractArray{T, 2}) where {T<:Number} -> Float64\n\nCompute the volume of a `simplex`, represented by a `Array{Float64, 2}` of size `(dim+1)`-by-`dim`.\n\"\"\"\nfunction volume(simplex::AbstractArray{T, 2}) where {T<:Number}\n    orientation(simplex) |> abs\nend\n\n\"\"\"\n    childsimplex(parentsimplex::AbstractArray{T, 2}) where {T<:Number} -> Array{Float64, 2}\n\nGenerates a random simplex which is entirely contained within `parentsimplex`,\nwhich is a (dim+1)-by-dim array.\n\"\"\"\nfunction childsimplex(parentsimplex::AbstractArray{T, 2}) where {T}\n    # Convex expansion coefficients of the random simplex\n    dim = size(parentsimplex, 2)\n    rs = rand(dim + 1, dim + 1)\n    normalised_colsums = 1 ./ sum(rs, dims = 2)\n    (normalised_colsums .* rs) * parentsimplex\nend\n\n\"\"\"\n    issingular(simplex::AbstractArray{T, 2}) where {T<:Number}\n\nDetermines if a simplex is singular by checking if any of its vertices are\nidentical.\n\"\"\"\nfunction issingular(simplex::AbstractArray{T, 2}) where {T<:Number}\n    size(unique(simplex, 1), 1) != size(simplex, 1)\nend\n\n\"\"\"\n    insidepoints(npts::Int, parentsimplex::AbstractArray{T, 2}) where {T<:Number}\n\nGenerates `npts` points that located inside `parentsimplex`.\n\"\"\"\nfunction insidepoints(npts::Int, parentsimplex::AbstractArray{T, 2}) where {T<:Number}\n    dim = size(parentsimplex, 2)\n    # Random linear combination coefficients\n    R = rand(Uniform(), npts, dim + 1)\n\n    # Normalise the coefficients so that they sum to one. We can then create the new point\n    # as a convex linear combination of the vertices of the parent simplex.\n    normalised_coeffs = (1 ./ sum(R, dims = 2)) .* R\n    normalised_coeffs * parentsimplex\nend\n\n\"\"\"\n    outsidepoint(parentsimplex::AbstractArray{T, 2}) where {T<:Number}\n\nGenerate a single point that is guaranteed to lie outside `parentsimplex`.\n\"\"\"\nfunction outsidepoint(parentsimplex::AbstractArray{T, 2}) where {T<:Number}\n    dim = size(parentsimplex, 2)\n    # Random linear combination coefficients\n    R = rand(1, dim + 1)\n\n    # Normalise the coefficients so that they sum to one. We can then create the new point\n    # as a convex linear combination of the vertices of the parent simplex.\n    normalised_coeffs = (1 ./ sum(R, dims = 2)) .* R\n    normalised_coeffs[1] += (1 - sum(normalised_coeffs[2:dim+1])) + rand()\n\n    normalised_coeffs * parentsimplex\nend\n\n\"\"\"\n    outsidepoints(npts::Int, parentsimplex::AbstractArray{T, 2}) where T <: Number\n\nGenerates `npts` points that located outside `parentsimplex`.\n\"\"\"\nfunction outsidepoints(npts::Int, parentsimplex::AbstractArray{T, 2}) where {T<:Number}\n    vcat([outsidepoint(parentsimplex) for i in 1:npts]...)\nend\n\n\n\n\"\"\"\n    nontrivially_intersecting_simplices(dim::Int) -> Array{Float64, 2}\n\nGenereate a set of non-trivially intersecting `dim`-dimensional simplices\n(i.e. they don't intersect along boundaries or vertices only).\n\"\"\"\nfunction nontrivially_intersecting_simplices(dim::Int)\n    rs = rand(dim + 1, dim) # random simplex with dim+1 vertices\n    n_inside = rand(1:dim, 1)[1]\n\n    verts_inside = insidepoints(n_inside, rs)\n\n    verts_outside = vcat([outsidepoint(rs) for i in 1:(dim+1-n_inside)]...)\n\n    return rs, vcat(verts_inside, verts_outside)\nend\n\n\n\"\"\"\n    simplices_sharing_vertices(dim::Int) -> Array{Float64, 2}\n\nGenereate a set of non-trivially intersecting `dim`-dimensional simplices\n(i.e. they don't intersect along boundaries or vertices only).\n\"\"\"\nfunction simplices_sharing_vertices(dim::Int)\n    rs = rand(dim + 1, dim) # random simplex with dim+1 vertices\n\n    # Determine how many vertices should be shared and how many are remaining\n    n_shared_verts = rand(1:dim, 1)[1]\n    n_remaining_verts = dim + 1 - n_shared_verts\n\n    # Pick the shared vertices and generate remaining vertices\n    new_simplex = zeros(Float64, 0, dim)\n    shared_verts = rs[rand(1:n_shared_verts, n_shared_verts), :]\n\n    if ndims(shared_verts) == 1\n        new_simplex = vcat(new_simplex, transpose(shared_verts))\n    else\n        new_simplex = vcat(new_simplex, shared_verts)\n    end\n    for i = 1:n_remaining_verts\n        if rand(Bool) == true\n            new_simplex  = vcat(new_simplex, insidepoints(1, rs))\n        else\n            new_simplex  = vcat(new_simplex, outsidepoints(1, rs))\n        end\n    end\n\n    return rs, new_simplex\nend\n\n\"\"\"\n    intersecting_simplices(;dim::Int = 3, intersection_type = \"nontrivial\")\n\nGenerate a pair of `dim` dimensional intersecting simplices. Each resulting\nsimplex is a `(dim+1)`-by-`dim` two-dimensional array. The `intersection_type`\nargument can be either `\"nontrivial\"` or `\"sharingvertices\"`.\n\"\"\"\nfunction intersecting_simplices(;dim::Int = 3, intersection_type = \"nontrivial\")\n    if intersection_type == \"nontrivial\"\n        return nontrivially_intersecting_simplices(dim)\n    elseif intersection_type == \"sharingvertices\"\n        return simplices_sharing_vertices(dim)\n    end\nend\n", "meta": {"hexsha": "c7f575905f9c7be7be3f0913a81cec2590a4bc2e", "size": 6677, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simplexoperations.jl", "max_stars_repo_name": "kahaaga/Simplices.jl", "max_stars_repo_head_hexsha": "206e0615511753a8945e46f007e434a5c19a0cf8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-08T00:07:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T00:07:46.000Z", "max_issues_repo_path": "src/simplexoperations.jl", "max_issues_repo_name": "kahaaga/Simplices.jl", "max_issues_repo_head_hexsha": "206e0615511753a8945e46f007e434a5c19a0cf8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2018-04-04T02:26:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-29T15:46:04.000Z", "max_forks_repo_path": "src/simplexoperations.jl", "max_forks_repo_name": "JuliaDynamics/Simplices.jl", "max_forks_repo_head_hexsha": "206e0615511753a8945e46f007e434a5c19a0cf8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-12-11T08:36:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:03:05.000Z", "avg_line_length": 33.8934010152, "max_line_length": 102, "alphanum_fraction": 0.697618691, "num_tokens": 1927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520764, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7512143942910714}}
{"text": "\"\"\"\n    mincut(flow_graph::Graphs.IsDirected, source::Integer, target::Integer, capacity_matrix::AbstractMatrix, algorithm::AbstractFlowAlgorithm)\n\nCompute the min-cut between `source` and `target` for the given graph.\nFirst computes the maxflow using `algorithm` and then builds the partition of the residual graph\nReturns a triplet `(part1, part2, flow)` with the partition containing the source, the partition containing the target (the rest) and the min-cut(max-flow) value\n\"\"\"\nfunction mincut(\n        flow_graph::Graphs.DiGraph,             # the input graph\n        source::Integer,                       # the source vertex\n        target::Integer,                       # the target vertex\n        capacity_matrix::AbstractMatrix,       # edge flow capacities\n        algorithm::AbstractFlowAlgorithm       # keyword argument for algorithm\n    )\n    flow, flow_matrix = maximum_flow(flow_graph, source, target, capacity_matrix, algorithm)\n    residual_matrix = spzeros(Graphs.nv(flow_graph),Graphs.nv(flow_graph))\n    for edge in Graphs.edges(flow_graph)\n        residual_matrix[edge.src,edge.dst] = max(0.0, capacity_matrix[edge.src,edge.dst] - flow_matrix[edge.src,edge.dst])\n        residual_matrix[edge.dst,edge.src] = max(0.0, capacity_matrix[edge.dst,edge.src] - flow_matrix[edge.dst,edge.src])\n    end\n    part1 = typeof(source)[]\n    queue = [source]\n    while !isempty(queue)\n        node = pop!(queue)\n        push!(part1, node)\n        dests = [dst for dst in 1:Graphs.nv(flow_graph) if residual_matrix[node,dst]>0.0 && dst ∉ part1 && dst ∉ queue]\n        append!(queue, dests)\n    end\n    part2 = [node for node in 1:Graphs.nv(flow_graph) if node ∉ part1]\n    return (part1, part2, flow)\nend\n", "meta": {"hexsha": "56a5da5104260865ad5532724342e1a96a5841c8", "size": 1713, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mincut.jl", "max_stars_repo_name": "JuliaGraphs/GraphsFlows.jl", "max_stars_repo_head_hexsha": "b521ada330563c3f6ac30b122b784118e5c06a3b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-10-19T07:20:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T14:37:28.000Z", "max_issues_repo_path": "src/mincut.jl", "max_issues_repo_name": "JuliaGraphs/GraphsFlows.jl", "max_issues_repo_head_hexsha": "b521ada330563c3f6ac30b122b784118e5c06a3b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-27T09:44:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T09:44:45.000Z", "max_forks_repo_path": "src/mincut.jl", "max_forks_repo_name": "JuliaGraphs/GraphsFlows.jl", "max_forks_repo_head_hexsha": "b521ada330563c3f6ac30b122b784118e5c06a3b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-06T16:06:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T16:52:58.000Z", "avg_line_length": 53.53125, "max_line_length": 161, "alphanum_fraction": 0.6795096322, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357702, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7512046913955387}}
{"text": "include(\"subtour.jl\")\n\nfunction add_subtour_elimination!(mip, X, s)\n\n    S = length(s)\n    @constraint(mip, sum(X[s[k], s[(k+1)]] for k in 1:S-1) + X[s[end], s[1]] <= S-1)\n    @constraint(mip, sum(X[s[k+1], s[k]] for k in 1:S-1) + X[s[1], s[end]] <= S-1)\n\n    return nothing\nend\n\n\n\"\"\"\n    solve_tsp(n, D)\n\n\n\"\"\"\nfunction solve_tsp(n, D, optimizer; itermax = 100)\n\n    # instantiate model\n    mip = Model(with_optimizer(optimizer))\n\n    # Basic formulation\n    @variable(mip, X[1:n, 1:n], Bin)\n\n    # Objective\n    @objective(mip, Min, sum(X.*D))\n\n    for i in 1:n\n        @constraint(mip, X[i, i] == 0.0)  # city `i` cannot follow itself in the tour\n    end\n\n    # Each city has one predecessor and one successor\n    for i in 1:n\n        @constraint(mip, sum(X[i, j] for j in 1:n) == 1.0)\n        @constraint(mip, sum(X[j, i] for j in 1:n) == 1.0)\n    end\n\n    t_start = time()\n    num_iter = 0\n    while (time() - t_start < 300.0) && (num_iter < itermax)\n        num_iter += 1\n        # solve relaxed model\n        optimize!(mip)\n\n        # get solution\n        X_ = value.(X)\n\n        # find sub-tours\n        sub_tours = find_subtours(n, X_)\n\n        if length(sub_tours) == 0\n            @info \"Optimal solution found\"\n            return X_\n        else\n            for subtour in sub_tours\n                add_subtour_elimination!(mip, X, subtour)\n            end\n        end\n    end\n    \n    @info \"Time limit reached.\"\n    return value.(X)\nend", "meta": {"hexsha": "6df9a5347c4ae3867584b5ee68afd644376021f0", "size": 1449, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tsp/tsp_cuts.jl", "max_stars_repo_name": "mtanneau/tutorial_jump", "max_stars_repo_head_hexsha": "e87ca0f6da5149d3f6bba3e2ff7963c31e23358f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-25T20:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-25T20:19:57.000Z", "max_issues_repo_path": "tsp/tsp_cuts.jl", "max_issues_repo_name": "mtanneau/tutorial_jump", "max_issues_repo_head_hexsha": "e87ca0f6da5149d3f6bba3e2ff7963c31e23358f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-17T21:06:12.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-17T21:06:12.000Z", "max_forks_repo_path": "tsp/tsp_cuts.jl", "max_forks_repo_name": "mtanneau/tutorial_jump", "max_forks_repo_head_hexsha": "e87ca0f6da5149d3f6bba3e2ff7963c31e23358f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.640625, "max_line_length": 85, "alphanum_fraction": 0.5431331953, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8128673223709252, "lm_q1q2_score": 0.7512046900936971}}
{"text": "type LSFractal\n  axiom::String\n  rules::Dict{Char,String}\n  angle::Real\n  n::Int\n  points::Matrix{Real}\nend\n\nfunction LSFractal(axiom, rules, angle=0.0,n=2;first_angle = nothing)\n  axiom_ex = axiom\n  if first_angle == nothing\n    first_angle = angle\n  end\n  for i in 2:n\n    axiom_ex = join([(c in keys(rules)) ? rules[c] : c  for c in axiom_ex])\n  end\n  points = zeros(1,3)\n  points[1,3] = first_angle\n  for action in axiom_ex\n    if action in 'A':'Z'\n      x = points[end,1] + cos(points[end,3]*(π/180))\n      y = points[end,2] + sin(points[end,3]*(π/180))\n      alfa = points[end,3]\n      points = vcat(points,[x y alfa])\n    else\n      alfa = points[end,3]\n      points[end, 3]=eval(parse(\"$action($alfa,$angle)\"))\n    end\n  end\n  LSFractal(axiom,rules,angle,n,points)\nend\nimport GR: plot\nfunction plot(fractal::LSFractal)\n  l_x = minimum(fractal.points[:,1]); h_x = maximum(fractal.points[:,1])\n  l_y = minimum(fractal.points[:,2]); h_y = maximum(fractal.points[:,2])\n  w_x = h_x - l_x; w_y =h_y - l_y\n  w_xy = max(w_x,w_y)\n  setwindow(l_x, l_x + w_xy, l_y, l_y+w_xy)\n  polyline(fractal.points[:,1],fractal.points[:,2])\nend\n\nusing GR\ninline(\"atom\")\n# Snowflake\naxiom=\"F++F++F\"\nrules=Dict('F' => \"F-F++F-F\")\nangle=60.0\nn=5\nsnowflake2 = LSFractal(axiom,rules,angle,n)\nplot(snowflake2)\nGR.show()\n\n#Sierpinsky triangle\naxiom=\"R\"\nrules=Dict('L' => \"R+L+R\", 'R' => \"L-R-L\")\nangle=-60.0\nn=6\nStriangle = LSFractal(axiom,rules,angle,n;first_angle = 0.0)\nplot(Striangle)\nGR.show()\n\n#Koch Island\naxiom=\"F-F-F-F\"\nrules=Dict('F' => \"F-F+F+FF-F-F+F\")\nangle=90\nn = 3\nKochIsland = LSFractal(axiom,rules,angle,n)\nplot(KochIsland)\nGR.show()\n\n#Koch Island\naxiom=\"F-F-F-F\"\nrules=Dict('F' => \"F-F+F+FF-F-F+F\")\nangle=90\nn = 3\nKochIsland = LSFractal(axiom,rules,angle,n)\nplot(KochIsland)\nGR.show()\n\n# Hexagonal Gosper Curve\naxiom=\"L\"\nrules=Dict('L'=>\"L+R++R-L--LL-R+\", 'R'=>\"-L+RR++R+L--L-R\")\nangle=60\nn=4\nHGosper = LSFractal(axiom,rules,angle,n)\nplot(HGosper)\nGR.show()\n\n# Cuadratic Gosper Curve\naxiom=\"-R\"\nrules=Dict('L'=>\"LL-R-R+L+L-R-RL+R+LLR-L+R+LL+R-LR-R-L+L+RR-\",\n           'R'=>\"+LL-R-R+L+LR+L-RR-L-R+LRR-L-RL+L+R-R-L+L+RR\")\nangle=90\nn=3\nCGosper = LSFractal(axiom,rules,angle,n)\nplot(CGosper)\nGR.show()\n\n#Sierpinsky Carpet\naxiom=\"F\"\nrules=Dict('F'=>\"F+F-F-F-G+F+F+F-F\", 'G'=>\"GGG\")\nangle=90\nn=5\nCarpet = LSFractal(axiom,rules,angle,n;first_angle = 45.0)\nplot(Carpet)\nGR.show()\n\n#Sierpinsky Triangle 2\naxiom=\"F-G-G\"\nrules=Dict('G'=>\"GG\", 'F'=>\"F-G+F+G-F\")\nangle=120\nn=6\nSTriangle2 = LSFractal(axiom,rules,angle,n)\nplot(STriangle2)\nGR.show()\n\n#Sierpinsky Median Curve\naxiom=\"L--F--L--F\"\nrules=Dict('L'=>\"+R-F-R+\", 'R'=>\"-L+F+L-\")\nangle=45\nn=8\nSMedian = LSFractal(axiom,rules,angle,n)\nplot(SMedian)\nGR.show()\n", "meta": {"hexsha": "1f92cec1b027bc21013cf7838cc93e9cf053bc57", "size": 2697, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LSystems.jl", "max_stars_repo_name": "Paulms/MyJuliaScripts", "max_stars_repo_head_hexsha": "8c8efa977411645ce959efa8deb1f708d87c5de2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-01-08T09:55:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-08T09:56:12.000Z", "max_issues_repo_path": "LSystems.jl", "max_issues_repo_name": "Paulms/MyJuliaScripts", "max_issues_repo_head_hexsha": "8c8efa977411645ce959efa8deb1f708d87c5de2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LSystems.jl", "max_forks_repo_name": "Paulms/MyJuliaScripts", "max_forks_repo_head_hexsha": "8c8efa977411645ce959efa8deb1f708d87c5de2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.576, "max_line_length": 75, "alphanum_fraction": 0.6433073786, "num_tokens": 1051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7512046859042372}}
{"text": "\"\"\"\n    gsdec(sys; job = \"finite\", smarg, fast = true,  atol = 0,  atol1 = atol, atol2 = atol, rtol = nϵ) -> (sys1, sys2)\n\nCompute for the descriptor system `sys = (A-λE,B,C,D)` with the transfer function matrix\n`G(λ)`, the additive spectral decomposition `G(λ) = G1(λ) + G2(λ)` such that `G1(λ)`, \nthe transfer function matrix of the descriptor system `sys1 = (A1-λE1,B1,C1,D1)`, \nhas only poles in a certain domain of interest `Cg` of the complex plane and `G2(λ)`, \nthe transfer function matrix of the descriptor system `sys2 = (A2-λE2,B2,C2,0)`, has\nonly poles outside of `Cg`. \n\nThe keyword argument `smarg`, if provided, specifies the stability margin for the\nstable eigenvalues of `A-λE`, such that, in the continuous-time case, \nthe stable eigenvalues have real parts less than or equal to `smarg`, and\nin the discrete-time case, the stable eigenvalues\nhave moduli less than or equal to `smarg`. If `smarg = missing`, the used default values \nare: `smarg = -sqrt(ϵ)`, for a continuous-time system, and `smarg = 1-sqrt(ϵ)`, \nfor a discrete-time system), where `ϵ` is the machine precision of the working accuracy. \n\nThe keyword argument `job`, in conjunction with `smarg`, defines the domain of \ninterest `Cg`, as follows:\n\nfor `job = \"finite\"`, `Cg` is the whole complex plane without the point at infinity, and \n   `sys1` has only finite poles and `sys2` has only infinite poles (default); \n   the resulting `A2` is nonsingular and upper triangular, while the\n   resulting `E2` is nilpotent and upper triangular;   \n\nfor `job = \"infinite\"`, `Cg` is the point at infinity, and \n   `sys1` has only infinite poles and `sys2` has only finite poles and \n   is the strictly proper part of `sys`; \n   the resulting `A1` is nonsingular and upper triangular, while the\n   resulting `E1` is nilpotent and upper triangular;   \n\nfor `job = \"stable\"`, `Cg` is the stability domain of eigenvalues defined by `smarg`, and  \n    `sys1` has only stable poles and `sys2` has only unstable and infinite poles;    \n    the resulting pairs `(A1,E1)` and `(A2,E2)` are in generalized Schur form with\n    `E1` upper triangular and nonsingular and `E2` upper triangular;   \n \nfor `job = \"unstable\"`, `Cg` is the complement of the stability domain of the \n    eigenvalues defined by `smarg`, and  \n    `sys1` has only unstable and infinite poles and `sys2` has only stable poles;    \n    the resulting pairs `(A1,E1)` and `(A2,E2)` are in generalized Schur form with\n    `E1` upper triangular and `E2` upper triangular  and nonsingular.   \n\nThe keyword arguments `atol1`, `atol2`, and `rtol`, specify, respectively, the absolute tolerance for the \nnonzero elements of `A`, the absolute tolerance for the nonzero elements of `E`,  and the relative tolerance \nfor the nonzero elements of `A` and `E`. The default relative tolerance is `n*ϵ`, where `ϵ` is the working machine epsilon \nand `n` is the order of the system `sys`. The keyword argument `atol` can be used \nto simultaneously set `atol1 = atol`, `atol2 = atol`. \n\nThe separation of the finite and infinite eigenvalues is performed using \nrank decisions based on rank revealing QR-decompositions with column pivoting \nif `fast = true` or the more reliable SVD-decompositions if `fast = false`.\n\"\"\"\nfunction gsdec(SYS::DescriptorStateSpace{T}; job::String = \"finite\", smarg::Union{Real,Missing} = missing, \n               fast::Bool = true,  atol::Real = zero(real(T)),  atol1::Real = atol, atol2::Real = atol, \n               rtol::Real = (SYS.nx*eps(real(float(one(T)))))*iszero(min(atol1,atol2))) where T\n    disc = !iszero(SYS.Ts)\n    if SYS.E == I\n       if job == \"finite\" \n          return SYS, dss(zeros(T,SYS.ny,SYS.nu), Ts = SYS.Ts)\n       elseif job == \"infinite\"\n          return dss(SYS.D, Ts = SYS.Ts), \n                 dss(SYS.A, SYS.B, SYS.C, zeros(T,SYS.ny,SYS.nu), Ts = SYS.Ts)\n       elseif job == \"stable\" || job == \"unstable\"\n          stable_unstable = (job == \"stable\")\n          A, B, C, _, _, blkdims, = ssblkdiag(SYS.A, SYS.B, SYS.C; smarg = smarg, disc = disc, stable_unstable = stable_unstable,  \n                                              withQ = false, withZ = false)\n          n1 = blkdims[1];\n          i1 = 1:n1; i2 = n1+1:SYS.nx \n          return dss(A[i1,i1], B[i1,:], C[:,i1], SYS.D, Ts = SYS.Ts), \n                 dss(A[i2,i2], B[i2,:], C[:,i2], zeros(T,SYS.ny,SYS.nu), Ts = SYS.Ts) \n       else\n          error(\"No such job option\")\n       end \n    else \n        if job == \"finite\"\n           A, E, B, C, _, _, _, blkdims = fiblkdiag(SYS.A, SYS.E, SYS.B, SYS.C; fast = fast, finite_infinite = true, trinv = false, \n                                                    atol1 = atol1, atol2 = atol2, rtol = rtol, withQ = false, withZ = false) \n           n1 = blkdims[1];\n        elseif job == \"infinite\"\n           A, E, B, C, _, _, _, blkdims = fiblkdiag(SYS.A, SYS.E, SYS.B, SYS.C; fast = fast, finite_infinite = false, trinv = false, \n                                                    atol1 = atol1, atol2 = atol2, rtol= rtol, withQ = false, withZ = false) \n           n1 = blkdims[1];\n        elseif job == \"stable\"\n           A, E, B, C, _, _, _, blkdims, = gsblkdiag(SYS.A, SYS.E, SYS.B, SYS.C; smarg = smarg, disc = disc, fast = fast, \n                                                      finite_infinite = true, stable_unstable = true, \n                                                      atol1 = atol1, atol2 = atol2, rtol = rtol, withQ = false, withZ = false)\n           n1 = blkdims[1];\n        elseif job == \"unstable\"\n           A, E, B, C, _, _, _, blkdims, = gsblkdiag(SYS.A, SYS.E, SYS.B, SYS.C; smarg = smarg, disc = disc, fast = fast, \n                                                      finite_infinite = false, stable_unstable = false, \n                                                      atol1 = atol1, atol2 = atol2, rtol = rtol, withQ = false, withZ = false)\n           n1 = blkdims[1]+blkdims[2];\n        else\n            error(\"No such job option\")\n        end\n        i1 = 1:n1; i2 = n1+1:SYS.nx \n        return dss(A[i1,i1], E[i1,i1], B[i1,:], C[:,i1], SYS.D, Ts = SYS.Ts), \n               dss(A[i2,i2], E[i2,i2], B[i2,:], C[:,i2], zeros(T,size(SYS.D)...), Ts = SYS.Ts) \n    end\nend\n", "meta": {"hexsha": "5b010fe4d1ae0577b9d4a4c881ee187574a3a773", "size": 6199, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/decompositions.jl", "max_stars_repo_name": "andreasvarga/DescriptorSystems.jl", "max_stars_repo_head_hexsha": "2745eda6a24a2334d82a81fb9c4247438cf4473d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-10-06T23:28:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T02:26:16.000Z", "max_issues_repo_path": "src/decompositions.jl", "max_issues_repo_name": "andreasvarga/DescriptorSystems.jl", "max_issues_repo_head_hexsha": "2745eda6a24a2334d82a81fb9c4247438cf4473d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-01-21T13:10:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T15:48:54.000Z", "max_forks_repo_path": "src/decompositions.jl", "max_forks_repo_name": "andreasvarga/DescriptorSystems.jl", "max_forks_repo_head_hexsha": "2745eda6a24a2334d82a81fb9c4247438cf4473d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-26T04:53:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T13:15:48.000Z", "avg_line_length": 60.7745098039, "max_line_length": 133, "alphanum_fraction": 0.5994515244, "num_tokens": 1820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.924141826246517, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7512046813183331}}
{"text": "\nexport ChebPEP\n\n# Returns the chebyshev nodes scaled to interval [a,b]\n# computed with type T\nfunction get_chebyshev_nodes(::Type{T},a,b,k) where {T<:Real}\n    mypi=T(pi);\n    return (T(a)+T(b))/2 .+ (T(b)-T(a))*(cos.((2*Vector(1:k).-1)*mypi/(2*k)))/2\nend\n\nimport Base.acos\nfunction acos(S::LowerTriangular)\n    # Specialized acos-function for a lower triangular matrix\n    # Some extra allocations, but preserves realness.\n    #\n    # This is a work-around julia issue:\n    #    https://github.com/JuliaLang/julia/issues/32721\n    F=acos(Matrix(S));\n    if (all(isreal.(acos.(diag(S)))))\n        F .= real(F); # Try to enforce realness\n    end\n    return F \nend\nfunction cheb_f_cosine_formula(a,b,x,k)\n    x1=2*(x-a*one(x))/(b-a)-one(x);\n    if (istril(x1) && (x1 isa AbstractMatrix))\n        x1=LowerTriangular(x1);\n    end\n    return cos(k*acos(x1));\nend\nfunction cheb_f_poly(a,b,x,k)\n    x1=2*(x-a*one(x))/(b-a) -one(x);\n    if (k==0)\n        return one(x1);\n    elseif k==1\n        return x1\n    elseif k==2\n        return 2*x1^2-one(x1)\n    elseif k==3\n        return 4*x1^3-3*x1\n    elseif k==4\n        return 8*x1^4-8*x1^2+one(x1)\n    elseif k==5\n        return 16*x1^5 - 20*x1^3 + 5*x1;\n    elseif k==6\n        return 32*x1^6-48*x1^4+18*x1^2-one(x1);\n    elseif k==7\n        return 64*x1^7-112*x1^5+56*x1^3-7*x1;\n    elseif k==8\n        return 128*x1^8-256*x1^6+160*x1^4-32*x1^2+one(x1);\n    else\n        error(\"Not implemented\")\n    end\nend\n\nfunction cheb_f(a,b,x,k)\n    return cheb_f_cosine_formula(a,b,x,k);\nend\n\n# Evaluate F in the chebyshev nodes\nfunction chebyshev_eval(a,b,k,F::Function)\n    x=get_chebyshev_nodes(Float64,a,b,k)\n    Fk=F.(x);\n    return (Fk,x)\nend\n\n\nfunction chebyshev_compute_coefficients_naive(a,b,Fk,k)\n    xk=get_chebyshev_nodes(Float64,a,b,k)\n    @show xk\n    if (size(xk) != size(Fk))\n        error(\"Incompatible sizes\");\n    end\n\n\n    Tinv=zeros(k,k);\n    for i=1:k\n        for j=1:k\n            Tinv[i,j]=cheb_f(a,b,xk[i],j-1);\n        end\n    end\n    @show Tinv\n\n    Ck=Tinv\\Fk\n\n    return Ck\n\nend\n\n# Compute the chebyshev coefficients of the coefficients\n# stored in Fk. xk should be the chebyshev points\n# Chebyshev Polynomials, 1st Edition, J.C. Mason, David C. Handscomb\n# Chapter 8\nfunction chebyshev_compute_coefficients(a,b,Fk,xk)\n    # Return coefficient\n    k=size(Fk,1);\n    Tmat=zeros(k,k);\n    for i=1:k\n        # for each chebyshev polynomial, compute the k coefficients\n        Tmat[i,:]= map(x->cheb_f(a,b,x,i-1)*2/k,xk)\n    end\n    Tmat[1,:] *= 0.5; # Fix the prime in the sum\n\n    # Compute the coefficients from the Tmat via\n    # a \"matrix vector multiplication\"\n\n    # When Fk are scalars\n    #Ck=Tmat*Fk;\n    # Generalization when Fk are vectors or matrices:\n    Ck=map(i-> sum(Fk .* Tmat[i,:]), 1:k)\n\n\n    return Ck\nend\n\n\n\n\n\n\n\nstruct ChebPEP{T<:AbstractMatrix,Ftype} <: AbstractSPMF{T}\n    n::Int # size\n    # Chebyshev polys are scaled to the interval [a,b]\n    a::Ftype\n    b::Ftype\n    k::Int; # Number of Chebyshev polys\n    spmf::SPMF_NEP{T,Ftype}; # The cheb-coefficents are stored directly in the SPMF\nend\n\n\n\n# Delegate compute functions\n\nfunction size(nep::ChebPEP)\n    return (nep.n,nep.n)\nend\nfunction size(nep::ChebPEP,dim)\n    return nep.n\nend\ncompute_Mlincomb(nep::ChebPEP,λ::Number,V::AbstractVecOrMat,a::Vector)= compute_Mlincomb(nep.spmf,λ,V,a);\ncompute_Mlincomb(nep::ChebPEP,λ::Number,V::AbstractVecOrMat)= compute_Mlincomb(nep.spmf,λ,V);\ncompute_Mder(nep::ChebPEP,λ::Number)=compute_Mder(nep.spmf,λ,0)\ncompute_Mder(nep::ChebPEP,λ::Number,der::Integer)=compute_Mder(nep.spmf,λ,der)\ncompute_MM(nep::ChebPEP,par...)=compute_MM(nep.spmf,par...)\nget_Av(nep::ChebPEP)=get_Av(nep.spmf)\nget_fv(nep::ChebPEP)=get_fv(nep.spmf)\n\n\n\n\"\"\"\n    ChebPEP(orgnep::NEP,k,[a=-1,[b=1]] [,cosine_formula_cutoff=5])\n\nThe type `ChebPEP<:AbstractSPMF` represents a polynomial function\nwhere the function is stored using a Chebyshev basis scaled to the\ninterval `[a,b]`, i.e.,\n```math\nM(λ)= B_0T_0(λ)+⋯+B_{k-1}T_{k-1}(λ)\n```\nwhere ``T_i`` are the scaled and shifted Chebyshev polynomials.\n\nThe constructor `ChebPEP` takes `nep::NEP` as an input\nand interpolates this NEP in `k` Chebyshev nodes, resulting\nin a polynomial of degree `k-1`, represented by its\ncoefficients in the Chebyshev basis.\nInterpolation in Chebyshev nodes and representation\nwith Chebyshev basis, is known to have\nattractive approximation properties, as well\nas robustness with respect to round-off errors.\n\nThe kwarg `cosine_formula_cutoff` decides how the Chebyshev\npolynomials should be computed. For larger degrees, it is better\nto use the cosine formula, whereas for low degrees\nthe explicit monomial expression is more efficient.\nThe explicit monomial expression will be used for degrees\nlower than `cosine_formula_cutoff`.\n\n\n# Example:\n\n```julia\njulia> nep=nep_gallery(\"dep0\");\njulia> chebpep=ChebPEP(nep,9);\njulia> using LinearAlgebra;\njulia> norm(compute_Mder(nep,0.3)-compute_Mder(chebpep,0.3))\n1.2881862971045282e-8\njulia> chebpep=ChebPEP(nep,19); # Better interpolation\njulia> norm(compute_Mder(nep,0.3)-compute_Mder(chebpep,0.3))\n2.0312004517316714e-15\n```\n\nSee also: [`polyeig`](methods.md#NonlinearEigenproblems.NEPSolver.polyeig), [`PEP`](@ref)\n\"\"\"\nfunction ChebPEP(orgspmf,k,a=-1,b=1;cosine_formula_cutoff=5)\n    F=s-> compute_Mder(orgspmf,s);\n    (Fk,xk)=chebyshev_eval(a,b,k,F);\n    Ck=chebyshev_compute_coefficients(a,b,Fk,xk);\n\n    fv=Array{Function}(undef,0);\n    for j=1:k\n        if (j>cosine_formula_cutoff)\n            push!(fv, S-> cheb_f_cosine_formula(a,b,S,j-1))\n        else\n            push!(fv, S-> cheb_f_poly(a,b,S,j-1))\n        end\n    end\n\n    # Determine the types (based on Ck[1])\n    MatType=typeof(Ck[1]);\n    T=eltype(Ck[1]);\n\n    # Create an SPMF with the correct type\n    cheb_spmf=SPMF_NEP(Ck,fv,check_consistency=false,Ftype=T);\n\n    n=size(Fk[1],1);\n    # Instantiate the type\n    return ChebPEP{MatType,T}(n,a,b,k,cheb_spmf);\nend\n", "meta": {"hexsha": "674c712c27eaed3ee7e147c8a0d638b14daf20c8", "size": 5904, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/types_cheb_pep.jl", "max_stars_repo_name": "harrymd/NonlinearEigenproblems.jl", "max_stars_repo_head_hexsha": "ffb050eb040dc22cb9c3c00c38da117b45ca7937", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2018-06-07T09:54:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T06:57:07.000Z", "max_issues_repo_path": "src/types_cheb_pep.jl", "max_issues_repo_name": "harrymd/NonlinearEigenproblems.jl", "max_issues_repo_head_hexsha": "ffb050eb040dc22cb9c3c00c38da117b45ca7937", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 180, "max_issues_repo_issues_event_min_datetime": "2018-06-06T11:25:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T21:49:00.000Z", "max_forks_repo_path": "src/types_cheb_pep.jl", "max_forks_repo_name": "harrymd/NonlinearEigenproblems.jl", "max_forks_repo_head_hexsha": "ffb050eb040dc22cb9c3c00c38da117b45ca7937", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2018-06-05T15:30:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T08:39:25.000Z", "avg_line_length": 26.9589041096, "max_line_length": 105, "alphanum_fraction": 0.6700542005, "num_tokens": 2045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7512046812058233}}
{"text": "################################################################################\n#\n#   Calculates integer coordinates in ℤⁿ lying inside the n\n#          dimensional ellipsoid\n#\n#   Implementation of Remarks page 1426 of\n#   B. Deconinck, M.  Heil, A. Bobenko, M. van Hoeij and M. Schmies,\n#    Computing Riemann Theta Functions, Mathematics of Computation, 73, (2004),\n#    1417-1442.\n#\n################################################################################\n\nconst padding = 0.5 # necessary for uniform approximation (page 1428)\n\nfunction innerpoints(T::Matrix{Float64}, radius::Float64)\n    n   = size(T, 1) # problem size\n\n    # precalculate what is independent of points\n    δcs = [ inv(T[1:i-1,1:i-1]) * T[1:i-1,i] for i in 1:n ]\n    Tgg = diag(T)\n\n    ns     = Vector{Float64}(undef, n)\n    points = Vector{Float64}[]\n    function _innerpoints(Rₒ, c, g)\n        hw = Rₒ / Tgg[g]\n        for ng in ceil(c[g]-hw):floor(c[g]+hw)\n            ns[g] = ng\n            if g == 1\n                push!(points, copy(ns))\n            else\n                δcn = (ng - c[g])\n                nc = c[1:g-1] - δcs[g] * δcn\n                nsqRₒ = Rₒ^2 - (Tgg[g] * δcn)^2\n                nsqRₒ > 0. && _innerpoints(sqrt(nsqRₒ), nc, g-1)\n            end\n        end\n    end\n\n    # add to initial R such that half-width 'hw' is augmented by 'padding'\n    padded_Rₒ = radius / sqrt(π) + padding * Tgg[n]\n    _innerpoints(padded_Rₒ, zeros(n), n)\n\n    points\nend\n", "meta": {"hexsha": "408bb958f2cf21f0252389f92eade7d63311c909", "size": 1457, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/innerpoints.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/RiemannTheta.jl-803aa692-84f0-5eed-9cc1-fbb46710dded", "max_stars_repo_head_hexsha": "af371a543767493c495f535ada2ce896a27644e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/innerpoints.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/RiemannTheta.jl-803aa692-84f0-5eed-9cc1-fbb46710dded", "max_issues_repo_head_hexsha": "af371a543767493c495f535ada2ce896a27644e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/innerpoints.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/RiemannTheta.jl-803aa692-84f0-5eed-9cc1-fbb46710dded", "max_forks_repo_head_hexsha": "af371a543767493c495f535ada2ce896a27644e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3777777778, "max_line_length": 80, "alphanum_fraction": 0.4948524365, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7512046715250614}}
{"text": "## define initial values ##\n\nfunction defineY(N, y0, β)\n\n    Y = zeros(N + 1)\n    Y[1] = y0\n    Y\n\nend\n\nfunction defineY(N, y0::Vector{<:Real}, β)\n\n    if size(y0) == size(β)\n\n        Y = zeros(N + 1, length(β))\n        Y[1, :] .= y0\n        Y\n\n    elseif size(y0) != size(β)\n\n        Y = zeros(N + 1)\n        Y[1] = y0[1]\n        Y\n\n    end\n\nend\n\nfunction defineY(N, y0::Matrix{<:Real}, β)\n\n    Y = zeros(N + 1, size(y0)[2])\n    Y[1, :] .= y0[1, :]\n    Y\n\nend\n\n## indexY ##\nfunction indexY(n, Y::Vector{<:Real}, Ynext)\n\n    Y[n + 1] = Ynext\n    Y\n\nend\n\nfunction indexY(n, Y::Matrix{<:Real}, Ynext)\n\n    Y[n + 1, :] = Ynext\n    Y\n\nend\n\n## taylor_expansion ##\ntaylor_expansion(t0, t, y0, β, m) = y0\n\nfunction taylor_expansion(t0, t, y0::Vector{<:Real}, β, m)\n\n    if size(y0) == size(β)\n\n        return y0\n\n    elseif size(y0) != size(β)\n\n        return sum([(t - t0) ^ k / factorial(k) * y0[k + 1] for k in 0:m - 1])\n\n    end\n\nend\n\ntaylor_expansion(t0, t, y0::Matrix{<:Real}, β, m) = sum([(t - t0) ^ k / factorial(k) * y0[:, k + 1] for k in 0:m - 1])\n\n## function ϕ ##\nfunction Phi(y, F, β, t, n, par...)\n\n    alpha = zeros(n - 1)\n    fun = zeros(n - 1)\n\n    alpha = map((x) -> α(x, β), n - 1:-1:1)\n    fun = map((x) -> F(t, x, β, y, par...), 2:n)\n\n    a_n0(n, β) .* F(t, 1, β, y, par...) .+ sum([alpha[i] .* fun[i] for i in 1:n - 1])\n\nend\n\na_n0(n, β) = ((n - 1) .^ (β .+ 1) .- n .^ β .* (n .- β .- 1)) ./ Γ(β .+ 2)\n\n## function α ##\nfunction α(n, β)\n\n    if n == 0\n\n        return 1 ./ Γ(β .+ 2)\n\n    else\n\n        return ((n .- 1) .^ (β .+ 1) .- 2 .* n .^ (β .+ 1) .+ (n .+ 1) .^ (β .+ 1)) ./ Γ(β .+ 2)\n\n    end\n\nend\n\n## Gamma function for vectors ##\nΓ(b) = map(gamma, b)\n", "meta": {"hexsha": "9de2b9763140164899415c13ddaa867b7684f445", "size": 1674, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SupFuns.jl", "max_stars_repo_name": "moeinkh88/FdeSolver.jl", "max_stars_repo_head_hexsha": "21c2922de90484328d794465cb5000db0281fcfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SupFuns.jl", "max_issues_repo_name": "moeinkh88/FdeSolver.jl", "max_issues_repo_head_hexsha": "21c2922de90484328d794465cb5000db0281fcfb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SupFuns.jl", "max_forks_repo_name": "moeinkh88/FdeSolver.jl", "max_forks_repo_head_hexsha": "21c2922de90484328d794465cb5000db0281fcfb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.2524271845, "max_line_length": 118, "alphanum_fraction": 0.4551971326, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7512011176005015}}
{"text": "#=\nGeometry in 2d euclidean space\n=#\n\n\"\"\"\ndeltaangle(a::Real, b::Real)\n\nReturn the minimum δ such that\n    a + δ = mod(b, 2π)\n\"\"\"\ndeltaangle(a::Real, b::Real) = atan2(sin(b-a), cos(b-a))\n\n# distance between two angles\nangledist( a::Real, b::Real ) = abs(deltaangle(a,b))\n\n# linear interpolation between angles\nlerp_angle(a::Real, b::Real, t::AbstractFloat) = a + deltaangle(a, b)*t\n\n# true if the values are collinear within a tolerance\nfunction are_collinear(a::AbstractVec, b::AbstractVec, c::AbstractVec, tol::Float64=1e-8)\n    # http://mathworld.wolfram.com/Collinear.html\n    # if val = 0 then they are collinear\n    val = a.x*(b.y-c.y) + b.x*(c.y-a.y)+c.x*(a.y-b.y)\n    abs(val) < tol\nend\n\nfunction inertial2body(point::VecE2, reference::VecSE2)\n\n    #=\n    Convert a point in an inertial cartesian coordinate frame\n    to be relative to a body's coordinate frame\n\n    The body's position is given relative to the same inertial coordinate frame\n    =#\n\n    s, c = sin(reference.θ), cos(reference.θ)\n    Δx = point.x - reference.x\n    Δy = point.y - reference.y\n    VecE2(c*Δx + s*Δy, c*Δy - s*Δx)\nend\nfunction inertial2body(point::VecSE2, reference::VecSE2)\n\n    #=\n    Convert a point in an inertial cartesian coordinate frame\n    to be relative to a body's coordinate frame\n\n    The body's position is given relative to the same inertial coordinate frame\n    =#\n\n    s, c = sin(reference.θ), cos(reference.θ)\n    Δx = point.x - reference.x\n    Δy = point.y - reference.y\n    VecSE2(c*Δx + s*Δy, c*Δy - s*Δx, point.θ - reference.θ)\nend\nfunction body2inertial(point::VecE2, reference::VecSE2)\n\n    #=\n    Convert a point in a body-relative cartesian coordinate frame\n    to be relative to a the inertial coordinate frame the body is described by\n    =#\n\n    c, s = cos(reference.θ), sin(reference.θ)\n    VecE2(c*point.x -s*point.y + reference.x, s*point.x +c*point.y + reference.y)\nend\nfunction body2inertial(point::VecSE2, reference::VecSE2)\n\n    #=\n    Convert a point in a body-relative cartesian coordinate frame\n    to be relative to a the inertial coordinate frame the body is described by\n    =#\n\n    c, s = cos(reference.θ), sin(reference.θ)\n    VecSE2(c*point.x -s*point.y + reference.x, s*point.x +c*point.y + reference.y, reference.θ + point.θ)\nend\n\ninclude(\"1d.jl\")\ninclude(\"lines.jl\")\ninclude(\"line_segments.jl\")\ninclude(\"rays.jl\")\ninclude(\"projectiles.jl\")\ninclude(\"solids.jl\")", "meta": {"hexsha": "c628824abaf21adbb851914d83377e73ff01e753", "size": 2397, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geom/geom.jl", "max_stars_repo_name": "wxuejing/Vec.jl", "max_stars_repo_head_hexsha": "38294563ad20d5e5f864fff19886d0d74a504c87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/geom/geom.jl", "max_issues_repo_name": "wxuejing/Vec.jl", "max_issues_repo_head_hexsha": "38294563ad20d5e5f864fff19886d0d74a504c87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geom/geom.jl", "max_forks_repo_name": "wxuejing/Vec.jl", "max_forks_repo_head_hexsha": "38294563ad20d5e5f864fff19886d0d74a504c87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5925925926, "max_line_length": 105, "alphanum_fraction": 0.6804338757, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7512011091577707}}
{"text": "@doc doc\"\"\"\n    Euclidean{T<:Tuple} <: Manifold\n\nEuclidean vector space $\\mathbb R^n$.\n\n# Constructor\n\n    Euclidean(n)\n\ngenerates the $n$-dimensional vector space $\\mathbb R^n$.\n\n   Euclidean(m, n)\n\ngenerates the $mn$-dimensional vector space $\\mathbb R^{m \\times n}$, whose\nelements are interpreted as $m \\times n$ matrices.\n\"\"\"\nstruct Euclidean{T<:Tuple} <: Manifold where {T} end\n\nEuclidean(n::Int) = Euclidean{Tuple{n}}()\nEuclidean(m::Int, n::Int) = Euclidean{Tuple{m,n}}()\n\n@generated manifold_dimension(::Euclidean{T}) where {T} = *(T.parameters...)\n\nstruct EuclideanMetric <: RiemannianMetric end\n\n@traitimpl HasMetric{Euclidean,EuclideanMetric}\n\nfunction local_metric(::MetricManifold{<:Manifold,EuclideanMetric}, x)\n    return Diagonal(ones(SVector{size(x, 1),eltype(x)}))\nend\n\nfunction inverse_local_metric(M::MetricManifold{<:Manifold,EuclideanMetric}, x)\n    return local_metric(M, x)\nend\n\ndet_local_metric(M::MetricManifold{<:Manifold,EuclideanMetric}, x) = one(eltype(x))\n\nlog_local_metric_density(M::MetricManifold{<:Manifold,EuclideanMetric}, x) = zero(eltype(x))\n\ninner(::Euclidean, x, v, w) = dot(v, w)\ninner(::MetricManifold{<:Manifold,EuclideanMetric}, x, v, w) = dot(v, w)\n\nnorm(::Euclidean, x, v) = norm(v)\nnorm(::MetricManifold{<:Manifold,EuclideanMetric}, x, v) = norm(v)\n\nexp!(M::Euclidean, y, x, v) = (y .= x + v)\n\nlog!(M::Euclidean, v, x, y) = (v .= y - x)\n", "meta": {"hexsha": "c37f9508689e27e9efa6b4163a372c06fb0290ef", "size": 1385, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Euclidean.jl", "max_stars_repo_name": "mschauer/Manifolds.jl", "max_stars_repo_head_hexsha": "7a2900e09f304546cef2cb1a9ab51b31ca83497e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Euclidean.jl", "max_issues_repo_name": "mschauer/Manifolds.jl", "max_issues_repo_head_hexsha": "7a2900e09f304546cef2cb1a9ab51b31ca83497e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Euclidean.jl", "max_forks_repo_name": "mschauer/Manifolds.jl", "max_forks_repo_head_hexsha": "7a2900e09f304546cef2cb1a9ab51b31ca83497e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2653061224, "max_line_length": 92, "alphanum_fraction": 0.6981949458, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7512011067252468}}
{"text": "# indicator of second-order cones\n\n\"\"\"\n  IndSOC()\n\nReturns the indicator of the second-order cone (ice-cream cone) of R^n.\n\"\"\"\n\nimmutable IndSOC <: IndicatorConvexCone end\n\nfunction (f::IndSOC){T <: Real}(x::AbstractArray{T,1})\n  # the tolerance in the following line should be customizable\n  if norm(x[2:end]) - x[1] <= 1e-14\n    return 0.0\n  end\n  return +Inf\nend\n\nfunction prox!{T <: Real}(f::IndSOC, x::AbstractArray{T,1}, y::AbstractArray{T,1}, gamma::Real=1.0)\n  nx = norm(x[2:end])\n  t = x[1]\n  if t <= -nx\n    y[:] = 0.0\n  elseif t >= nx\n    y[:] = x\n  else\n    r = 0.5 * (1 + t / nx)\n    y[1] = r * nx\n    y[2:end] = r * x[2:end]\n  end\n  return 0.0\nend\n\nfun_name(f::IndSOC) = \"indicator of the second-order cone\"\nfun_dom(f::IndSOC) = \"AbstractArray{Real,1}\"\nfun_expr(f::IndSOC) = \"x ↦ 0 if x[1] >= ||x[2:end]||, +∞ otherwise\"\nfun_params(f::IndSOC) = \"none\"\n\nfunction prox_naive{T <: Real}(f::IndSOC, x::AbstractArray{T,1}, gamma::Real=1.0)\n  nx = norm(x[2:end])\n  t = x[1]\n  if t <= -nx\n    y = zeros(x)\n  elseif t >= nx\n    y = x\n  else\n    y = zeros(x)\n    r = 0.5 * (1 + t / nx)\n    y[1] = r * nx\n    y[2:end] = r * x[2:end]\n  end\n  return y, 0.0\nend\n\n# ########################\n# ROTATED SOC\n# ########################\n\n\"\"\"\n  IndRotatedSOC()\n\nReturns the indicator of the *rotated* second-order cone of R^n, that is {(p,q,x) : norm(x)^2 ⩽ 2pq, p ⩾ 0, q ⩾ 0}\n\"\"\"\n\nimmutable IndRotatedSOC <: IndicatorConvexCone end\n\nfunction (f::IndRotatedSOC){T <: Real}(x::AbstractArray{T,1})\n  if x[1] >= -1e-14 && x[2] >= -1e-14 && norm(x[3:end])^2 - 2*x[1]*x[2] <= 1e-14\n    return 0.0\n  end\n  return +Inf\nend\n\nfunction prox!{T <: Real}(f::IndRotatedSOC, x::AbstractArray{T,1}, y::AbstractArray{T,1}, gamma::Real=1.0)\n  # sin(pi/4) = cos(pi/4) = 0.7071067811865475\n  # rotate x ccw by pi/4\n  x1 = 0.7071067811865475*x[1] + 0.7071067811865475*x[2]\n  x2 = 0.7071067811865475*x[1] - 0.7071067811865475*x[2]\n  # project rotated x onto SOC\n  nx = sqrt(x2^2+norm(x[3:end])^2)\n  t = x1\n  if t <= -nx\n    y[:] = 0.0\n  elseif t >= nx\n    y[1] = x1\n    y[2] = x2\n    y[3:end] = x[3:end]\n  else\n    r = 0.5 * (1 + t / nx)\n    y[1] = r * nx\n    y[2] = r * x2\n    y[3:end] = r * x[3:end]\n  end\n  # rotate back y cw by pi/4\n  y1 = 0.7071067811865475*y[1] + 0.7071067811865475*y[2]\n  y2 = 0.7071067811865475*y[1] - 0.7071067811865475*y[2]\n  y[1] = y1\n  y[2] = y2\n  return 0.0\nend\n\nfun_name(f::IndRotatedSOC) = \"indicator of the rotated second-order cone\"\nfun_dom(f::IndRotatedSOC) = \"AbstractArray{Real,1}\"\nfun_expr(f::IndRotatedSOC) = \"x ↦ 0 if x[1] ⩾ 0, x[2] ⩾ 0, norm(x[3:end])² ⩽ 2*x[1]*x[2], +∞ otherwise\"\nfun_params(f::IndRotatedSOC) = \"none\"\n\nfunction prox_naive{T <: Real}(f::IndRotatedSOC, x::AbstractArray{T,1}, gamma::Real=1.0)\n  g = IndSOC()\n  z = copy(x)\n  z[1] = 0.7071067811865475*x[1] + 0.7071067811865475*x[2]\n  z[2] = 0.7071067811865475*x[1] - 0.7071067811865475*x[2]\n  y, = prox_naive(g, z, gamma)\n  y1 = 0.7071067811865475*y[1] + 0.7071067811865475*y[2]\n  y2 = 0.7071067811865475*y[1] - 0.7071067811865475*y[2]\n  y[1] = y1\n  y[2] = y2\n  return y, 0.0\nend\n", "meta": {"hexsha": "f2d529ebc94894d555b5c00cb7a18ee41896d344", "size": 3060, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indSOC.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/indSOC.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/indSOC.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7142857143, "max_line_length": 114, "alphanum_fraction": 0.5849673203, "num_tokens": 1322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7512010999499747}}
{"text": "using LinearAlgebra, Krylov, LinearOperators, SparseArrays, Stopping\n\n#Krylov @kdot\nmacro kdot(n, x, y)\n  return esc(:(Krylov.krylov_dot($n, $x, 1, $y, 1)))\nend\n\nusing SolverTools, Logging\n\"\"\"\nRandomized coordinate descent\n\nSect. 3.7 in Gower, R. M., & Richtárik, P. (2015).\nRandomized iterative methods for linear systems.\nSIAM Journal on Matrix Analysis and Applications, 36(4), 1660-1690.\n\"\"\"\nfunction RandomizedCD(A :: AbstractMatrix,\n                      b :: AbstractVector{T};\n                      is_zero_start :: Bool = true,\n                      x0 :: AbstractVector{T} = zeros(T,size(A,2)),\n                      atol :: AbstractFloat = 1e-7,\n                      rtol :: AbstractFloat = 1e-15,\n                      max_iter :: Int = size(A,2)^2,\n                      max_time :: Float64 = 60.,\n                      max_cntrs = Stopping._init_max_counters_linear_operators(quick=20000),\n                      verbose :: Int = 100,\n                      kwargs...) where T <: AbstractFloat\n\n    m, n = size(A)\n    x    = copy(x0)\n    res  = is_zero_start ? b : b - A*x\n    nrm0 = norm(res)\n\n    time_init = time()\n    elapsed_time = time_init\n\n    cntrs = LACounters()\n    max_f = false\n\n    OK = nrm0 <= atol\n    k  = 0\n\n    #@info log_header([:iter, :un, :time], [Int, T, T])\n    #@info log_row(Any[0, res[1], elapsed_time])\n    while !OK && (k <= max_iter) && (elapsed_time - time_init <= max_time) && !max_f\n\n     #rand a number between 1 and n\n     #224.662 ns (4 allocations: 79 bytes) - independent of the n\n     i  = mod(k,n)+1#Int(floor(rand() * n) + 1)\n     Ai = A[:,i]\n\n     #ei = zeros(n); ei[i] = 1.0 #unit vector in R^n\n     #xk  = Ai == 0 ? x0 : x0 - dot(Ai,res)/norm(Ai,2)^2 * ei\n     Aires = @kdot(m, Ai, res)\n     nAi   = @kdot(m, Ai, Ai)\n     x[i] -= Aires/nAi\n\n     #res = b - A*x\n     res += Ai * Aires/nAi\n     cntrs.nprod += 1\n     nrm = norm(res,Inf)\n     OK  = nrm <= atol + nrm0 * rtol\n\n     sum, max_f = 0, false\n     for f in [:nprod, :ntprod, :nctprod]\n      ff    = getfield(cntrs, f)\n      max_f = max_f || (ff > max_cntrs[f])\n      sum  += ff\n     end\n     max_f = max_f || sum > max_cntrs[:neval_sum]\n     k += 1\n     elapsed_time = time()\n     if mod(k, verbose) == 0 #print every 20 iterations\n     # @info log_row(Any[k, res[1], elapsed_time])\n     end\n\n    end\n\n return x, OK, k\nend\n", "meta": {"hexsha": "42965fdd9e4ca11d488b42c2e145e96fd0ef6955", "size": 2337, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "paper/LinearAlgebra-test/random_coordinate_descent_method.jl", "max_stars_repo_name": "vepiteski/Stopping.jl", "max_stars_repo_head_hexsha": "404b31ff5eb951db1773a4e22b6d4539e99ddd08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-01-30T19:02:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T06:33:24.000Z", "max_issues_repo_path": "paper/LinearAlgebra-test/random_coordinate_descent_method.jl", "max_issues_repo_name": "vepiteski/Stopping.jl", "max_issues_repo_head_hexsha": "404b31ff5eb951db1773a4e22b6d4539e99ddd08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31, "max_issues_repo_issues_event_min_datetime": "2017-05-18T13:41:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T18:07:07.000Z", "max_forks_repo_path": "paper/LinearAlgebra-test/random_coordinate_descent_method.jl", "max_forks_repo_name": "vepiteski/Stopping.jl", "max_forks_repo_head_hexsha": "404b31ff5eb951db1773a4e22b6d4539e99ddd08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-05-18T13:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T00:06:25.000Z", "avg_line_length": 29.2125, "max_line_length": 92, "alphanum_fraction": 0.5361574668, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7511651355773713}}
{"text": "# Algorithm for Optimization\n\ndiff_forward(f,x;h=sqrt(eps(Float64))) = (f(x+h)-f(x))/h\ndiff_central(f,x;h=sqrt(eps(Float64))) = (f(x+h/2)-f(x-h/2))/h\ndiff_backward(f,x;h=sqrt(eps(Float64))) = (f(x)-f(x-h))/2\ndiff_complex(f,x;h=1e-20) = imag(f(x+h*im))/h\n\nf=x->sin(x^2);\nv = f(π/2+0.001im);\n@show real(v) #f(x)\n@show imag(v)/0.001 #f'(x)\n@show sin(pi/2*pi/2), π*cos(π^2/4)\n", "meta": {"hexsha": "3556a83188c80529d26569e9aa78834bbc06d80c", "size": 372, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "differential/numerical_diff.jl", "max_stars_repo_name": "terasakisatoshi/juliaExer", "max_stars_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-02T01:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-04T12:03:25.000Z", "max_issues_repo_path": "differential/numerical_diff.jl", "max_issues_repo_name": "terasakisatoshi/juliaExer", "max_issues_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "differential/numerical_diff.jl", "max_forks_repo_name": "terasakisatoshi/juliaExer", "max_forks_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6153846154, "max_line_length": 62, "alphanum_fraction": 0.6048387097, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7511651258790952}}
{"text": "# This script includes a demo for the errot plots. \n\nusing Makie \nusing FractalTools \nusing GeometryBasics\nusing Random \n\nRandom.seed!(0)\n\n# Generate data \ntrig = Triangle(\n    Point(BigFloat(-1.), BigFloat(-1.)), \n    Point(BigFloat(1.), BigFloat(-1)),\n    Point(BigFloat(0.), BigFloat(2.)) \n)\nf(x, y) = x^2 + y^2\npnts3d = getdata(f, trig, 100)\n \n# Construct interpolant \nitp = interpolate(pnts3d)\nfunction erf(x, y)\n    ival = itp(x, y) \n    fval = f(x, y) \n    abs(fval - ival) / abs(fval) * 100\nend\n\n# Construct gui\n_, msh3 = triangulate(pnts3d)\nmsh2 = project(msh3)\npnts2d = project(pnts3d)   \n\nfig         = Figure() \nlb          = Label(fig, \"Show Interpolant\") \ntog         = Toggle(fig, active=false) \nax1         = LScene(fig, scenekw=(camema=cam3d!, raw=false), tellwidth=false)\nfig[1, 1]   = vgrid!(ax1, hgrid!(lb, tog, tellwidth=false), tellwidth=false)\nax2         = fig[1, 2] = LScene(fig, scenekw=(camema=cam3d!, raw=false), tellwidth=false)\n\n        trisurf!(ax1, msh2, f, meshcolor3=first.(msh3.position), colormap=:viridis)\nplt =   trisurf!(ax1, msh2, itp, meshcolor3=first.(msh3.position), colormap=:heat)\n        wireframe!(ax1, msh2)  \n        trisurf!(ax2, msh2, erf, meshcolor3=first.(msh2.position))\n\non(tog.active) do val \n    plt.visible[] = val\nend \n\ntog.active[] = false\n\ndisplay(fig)\n\n# fps = 60\n# record(fig.scene, \"errorplot.mp4\"; framerate = fps) do io\n#     for i = 1 : 10 * fps\n#         sleep(1/fps)\n#         recordframe!(io)\n#     end\n# end", "meta": {"hexsha": "90d71050eb0361453c374a3bb489f86ab69dbed9", "size": 1478, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/stash/mesh/triangularerrorplots.jl", "max_stars_repo_name": "zekeriyasari/FractalTools.jl", "max_stars_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-08T12:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T12:50:16.000Z", "max_issues_repo_path": "example/stash/mesh/triangularerrorplots.jl", "max_issues_repo_name": "zekeriyasari/FractalTools.jl", "max_issues_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-09-05T18:22:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T10:09:46.000Z", "max_forks_repo_path": "example/stash/mesh/triangularerrorplots.jl", "max_forks_repo_name": "zekeriyasari/FractalTools.jl", "max_forks_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4827586207, "max_line_length": 90, "alphanum_fraction": 0.6244925575, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7511651256669611}}
{"text": "function trap_rule(xarr::Vector{T},farr::Vector{T}) where T\n    N = length(xarr)\n\n    Δx = xarr[2] - xarr[1]\n    quad = zero(T)\n    for ti=1:N-1\n        quad += farr[ti] + farr[ti+1]\n    end\n\n    quad *= 0.5*Δx\n\n    return quad\nend\n\n# return J. Compares how well particle field (represented by θ) \n# approximates F(y)\nfunction cost(θ,y,F)\n    x,s,h = decompose_theta(θ)\n    G = get_gauss_field(θ,y)\n    f = (G - F).^2\n    J = trap_rule(y,f)\n    return J\nend\n\nfunction grad_cost(θ,y,F)\n    dJdx = compute_dJdx(θ,y,F)\n    dJds = compute_dJds(θ,y,F)\n    dJdh = compute_dJdh(θ,y,F)\n    dJdθ = vcat(dJdx,dJds,dJdh)\n\n    return dJdθ\nend\n\nfunction compute_dJdx(θ,y,F)\n    x,s,h = decompose_theta(θ)\n    G = get_gauss_field(θ,y)\n\n    N = length(x)\n    M = length(y)\n    dJdx = zeros(N)\n\n    for ti=1:N\n        f = zeros(M)\n        for tj=1:M\n            f[tj] = 2*(G[tj] - F[tj])*compute_dGdx(x[ti],s[ti],h,y[tj])\n        end\n        dJdx[ti] = trap_rule(y,f)\n    end\n    return dJdx\nend\n\nfunction compute_dJds(θ,y,F)\n    x,s,h = decompose_theta(θ)\n    G = get_gauss_field(θ,y)\n\n    N = length(x)\n    M = length(y)\n    dJds = zeros(N)\n\n    for ti=1:N\n        f = zeros(M)\n        for tj=1:M\n            f[tj] = 2*(G[tj] - F[tj])*compute_dGds(x[ti],s[ti],h,y[tj])\n        end\n        dJds[ti] = trap_rule(y,f)\n    end\n    return dJds\nend\n\nfunction compute_dJdh(θ,y,F)\n    x,s,h = decompose_theta(θ)\n    G = get_gauss_field(θ,y)\n\n    M = length(y)\n    f = zeros(M)\n    for tj=1:M\n        f[tj] = 2*(G[tj] - F[tj])*compute_dGdh(x,s,h,y[tj])\n    end\n    dJdh = trap_rule(y,f)\n    return dJdh\nend\n\nfunction compute_dGdx(x::T,s::T,h::T,y::T) where T\n    dGdx = -2*s*(x - y)*GaussKernel(x-y,h)/h^2\n    return dGdx\nend\n\nfunction compute_dGds(x::T,s::T,h::T,y::T) where T\n    dGds = GaussKernel(x-y,h)\n    return dGds\nend\n\nfunction compute_dGdh(x::Vector{T},s::Vector{T},h::T,y::T) where T\n    N = length(x)\n    dGdh = zero(T)\n    for ti=1:N\n        dGdh += s[ti]*(x[ti] - y)^2*GaussKernel(x[ti]-y,h)\n    end\n    dGdh *= 2/h^3\n    return dGdh\nend\n\n# computes grad_cost with finite difference method\n# to brute-force check the analytic gradient\nfunction grad_cost_FD(θ,y,F)\n    n_temp = length(θ)\n    N = Int((n_temp-1)/2)\n\n    Δx = 0.01*(maximum(y) -minimum(y))\n    Δs = 0.01*maximum(F)\n    Δh = Δx\n    dJdx = zeros(N)\n    dJds = zeros(N)\n    dJdh = 0.0\n    \n    # compute dJdx\n    for ti=1:N\n        θtemp = copy(θ)\n        θtemp[ti] = θtemp[ti] + Δx\n        J1 = cost(θtemp,y,F)\n        J0 = cost(θ,y,F)\n        dJdx[ti] = (J1 - J0)/Δx\n    end\n\n    # compute dJds\n    for ti=1:N\n        θtemp = copy(θ)\n        θtemp[ti+N] = θtemp[ti+N] + Δs\n        J1 = cost(θtemp,y,F)\n        J0 = cost(θ,y,F)\n        dJds[ti] = (J1 - J0)/Δs\n    end\n\n    # compute dJdh\n    θtemp = copy(θ)\n    θtemp[2N+1] = θtemp[2N+1] + Δh\n    J1 = cost(θtemp,y,F)\n    J0 = cost(θ,y,F)\n    dJdh = (J1 - J0)/Δh\n\n    dJdθ = vcat(dJdx,dJds,dJdh)\n    return dJdθ\nend\n\nfunction plot_fields(θ,y,F;iter=-1)\n    x,s,h = decompose_theta(θ)\n\n    G = get_gauss_field(θ,y)\n    p = plot()\n    if iter == -1\n        plot!(p,y,G,label=\"G\")\n    else\n        plot!(p,y,G,label=\"G\",title=\"iteration $(iter)\")\n    end\n    plot!(p,y,F,label=\"F\")\n    gui(p)\n\n    nothing\nend\n\nfunction get_gauss_field(θ,y)\n    # decompose theta\n    x,s,h = decompose_theta(θ)\n\n    # plot gauss field from particles\n    d = 1                                   # dimension of data\n    M = length(y)                           # number of targets\n    N = length(x)                           # number of sources\n    ε = 1e-2                                # max tolerance\n    W = 1                                   # number of sources being evaluated\n    G = zeros(M)                            # output values array\n    mydgt!(G,d,M,N,h,ε,x,y,s,W)\n    return G\nend\n\nfunction gradient_descent_step!(θ,∇f,α)\n    N = length(θ)\n    for ti=1:N\n        θ[ti] -= α*∇f[ti]\n    end\n    nothing\nend\n\nfunction gradient_descent(θ0,y,F;NiterMAX=100,TOL=1e-10,pause=false)\n    error = 100.0\n    α = 0.2\n\n    iter = 1\n    θ = θ0\n    Jtemp = 100.0\n    while iter<NiterMAX && error > TOL\n        println(\"\\riteration \",iter,\"          \")        \n        plot_fields(θ,y,F;iter=iter)\n\n        J = cost(θ,y,F)\n        error = abs(J - Jtemp)\n\n        #∇J = grad_cost_FD(θ,y,F)\n        ∇J = grad_cost(θ,y,F)\n        \n        gradient_descent_step!(θ,∇J,α)\n                \n        if pause; readline(); end\n\n        Jtemp = J\n\n        iter += 1\n    end\n\n    return θ\nend\n\nfunction compose_theta(x,s,h)\n    N = length(x)\n    θ = zeros(2N+1)\n    for ti=1:N\n        θ[ti] = x[ti]\n        θ[ti+N] = s[ti]\n    end\n    θ[2N+1] = h\n    return θ\nend\n\nfunction decompose_theta(θ)\n    n_temp = length(θ)\n    N = Int((n_temp-1)/2)\n    x = zeros(N)\n    s = zeros(N)\n    for ti=1:N\n        x[ti] = θ[ti]\n        s[ti] = θ[ti+N]\n    end\n    h = θ[2N+1]\n    return x,s,h \nend", "meta": {"hexsha": "bae5a821f213b14044a87b68ed18224946c65ded", "size": 4854, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ctd_functions.jl", "max_stars_repo_name": "pseastham/InverseGaussTransform.jl", "max_stars_repo_head_hexsha": "6af5ff2b3ef91a8de17b762b09a99edd9afb4c05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ctd_functions.jl", "max_issues_repo_name": "pseastham/InverseGaussTransform.jl", "max_issues_repo_head_hexsha": "6af5ff2b3ef91a8de17b762b09a99edd9afb4c05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ctd_functions.jl", "max_forks_repo_name": "pseastham/InverseGaussTransform.jl", "max_forks_repo_head_hexsha": "6af5ff2b3ef91a8de17b762b09a99edd9afb4c05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6553191489, "max_line_length": 79, "alphanum_fraction": 0.5152451586, "num_tokens": 1819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7511651176962058}}
{"text": "function estimate_norm(mat; tol=1e-4, itmax = 1000)\n    v = rand(size(mat,2))\n\n    v = v/norm(v)\n    itermin = 3\n    i = 1\n    σold = 1\n    σnew = 1\n    while (norm(sqrt(σold)-sqrt(σnew))/norm(sqrt(σold)) > tol || i < itermin) && i < itmax\n        σold = σnew\n        w = mat*v\n        x = adjoint(mat)*w\n        σnew = norm(x)\n        v = x/norm(x)\n        i += 1\n    end\n    return sqrt(σnew)\nend\n\nfunction estimate_reldifference(hmat, refmat; tol=1e-4)\n    #if size(hmat) != size(refmat)\n    #    error(\"Dimensions of matrices do not match\")\n    #end\n    \n    v = rand(size(hmat,2))\n\n    v = v/norm(v)\n    itermin = 3\n    i = 1\n    σold = 1\n    σnew = 1\n    while norm(sqrt(σold)-sqrt(σnew))/norm(sqrt(σold)) > tol || i < itermin\n        σold = σnew\n        w = hmat*v - refmat*v\n        x = adjoint(hmat)*w - adjoint(refmat)*w\n        σnew = norm(x)\n        v = x/norm(x)\n        i += 1\n    end\n\n    norm_refmat = estimate_norm(refmat, tol=tol)\n\n    return sqrt(σnew)/norm_refmat\nend", "meta": {"hexsha": "9c78f88dc550f450aef0c7afc466c5b2a16061e8", "size": 987, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "sbadrian/FastBEAST", "max_stars_repo_head_hexsha": "c5a7b46944d79b5291743d02dd0823630f686912", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-17T09:17:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T09:24:09.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "JoshuaTetzner/FastBEAST", "max_issues_repo_head_hexsha": "233c0a52da7a4dfc0af796d36d9656eef9f1082d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-12-01T14:15:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T22:30:15.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "JoshuaTetzner/FastBEAST", "max_forks_repo_head_hexsha": "233c0a52da7a4dfc0af796d36d9656eef9f1082d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:58:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-16T10:09:30.000Z", "avg_line_length": 22.4318181818, "max_line_length": 90, "alphanum_fraction": 0.5288753799, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164657, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7511483968966247}}
{"text": "fejer_plan1(μ) = FFTW.plan_r2r!(μ, FFTW.REDFT01)\nfejer_plan2(μ) = FFTW.plan_r2r!(μ, FFTW.RODFT00)\n\n\"\"\"\nCompute nodes and weights of Fejer's first quadrature rule with a Jacobi weight.\n\"\"\"\nfejer1{T<:AbstractFloat}(N::Int,α::T,β::T) = fejer1(N,α,β,fejer_plan1(zeros(T,N)))\n\n\"\"\"\nCompute nodes and weights of Fejer's second quadrature rule with a Jacobi weight.\n\"\"\"\nfejer2{T<:AbstractFloat}(N::Int,α::T,β::T) = fejer2(N,α,β,fejer_plan2(zeros(T,N)))\n\nfejer1{T<:AbstractFloat}(N::Int,α::T,β::T,plan) = T[sinpi((N-2k-one(T))/2N) for k=0:N-1],fejerweights1(N,α,β,plan)\nfejer2{T<:AbstractFloat}(N::Int,α::T,β::T,plan) = T[cospi((k+one(T))/(N+one(T))) for k=0:N-1],fejerweights2(N,α,β,plan)\n\n\n\"\"\"\nCompute weights of Fejer's first quadrature rule with a Jacobi weight.\n\"\"\"\nfejerweights1{T<:AbstractFloat}(N::Int,α::T,β::T) = fejerweights1(N,α,β,fejer_plan1(zeros(T,N)))\n\n\"\"\"\nCompute weights of Fejer's second quadrature rule with a Jacobi weight.\n\"\"\"\nfejerweights2{T<:AbstractFloat}(N::Int,α::T,β::T) = fejerweights2(N,α,β,fejer_plan2(zeros(T,N)))\n\nfunction fejerweights1{T<:AbstractFloat}(N::Int,α::T,β::T,plan)\n    μ = chebyshevjacobimoments1(N,α,β)\n    scale!(μ,inv(T(N)))\n    return plan*μ\nend\n\nfunction fejerweights2{T<:AbstractFloat}(N::Int,α::T,β::T,plan)\n    μ = chebyshevjacobimoments2(N,α,β)\n    Np1 = N+one(T)\n    scale!(μ,inv(Np1))\n    plan*μ\n    @inbounds for i=1:N μ[i] = sinpi(i/Np1)*μ[i] end\n    return μ\nend\n", "meta": {"hexsha": "f1089ccba493cb76d7179dd5ae057eae33891055", "size": 1414, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fejer.jl", "max_stars_repo_name": "JuliaPackageMirrors/FastTransforms.jl", "max_stars_repo_head_hexsha": "eb9f1612f174cc1f7c3bc349deee94aedde77825", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fejer.jl", "max_issues_repo_name": "JuliaPackageMirrors/FastTransforms.jl", "max_issues_repo_head_hexsha": "eb9f1612f174cc1f7c3bc349deee94aedde77825", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fejer.jl", "max_forks_repo_name": "JuliaPackageMirrors/FastTransforms.jl", "max_forks_repo_head_hexsha": "eb9f1612f174cc1f7c3bc349deee94aedde77825", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6666666667, "max_line_length": 119, "alphanum_fraction": 0.6768033946, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7511483910497687}}
{"text": "using IntervalArithmetic, StaticArrays, IntervalLinearAlgebra, IntervalRootFinding\n\nA = @SMatrix [4..6 -1..1 -1..1 -1..1;-1..1 -6.. -4 -1..1 -1..1;-1..1 -1..1 9..11 -1..1;-1..1 -1..1 -1..1 -11.. -9]\n\nb = @SVector [-2..4, 1..8, -4..10, 2..12]\n\njac = Jacobi()\ngs = GaussSeidel()\nhbr = HansenBliekRohn()\n\n@btime solve($A, $b, $gs)\n\n@btime solve($A, $b, $jac)\n\n@btime solve($A, $b, $hbr)\n\n# comparison with IntervalRootFinding\n\n@btime gauss_seidel_interval($A, $b)\n@btime gauss_seidel_contractor($A, $b) #NOTE: THIS IS THE JACOBI method\n@btime gauss_elimination_interval($A, $b)\n", "meta": {"hexsha": "f56586706f0abe2f7110e9ce4fb2de2c06852c55", "size": 575, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "perf/benchmark.jl", "max_stars_repo_name": "mforets/IntervalLinearAlgebra.jl", "max_stars_repo_head_hexsha": "40726db50873af9a2d956496aa67a57aeb366c54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "perf/benchmark.jl", "max_issues_repo_name": "mforets/IntervalLinearAlgebra.jl", "max_issues_repo_head_hexsha": "40726db50873af9a2d956496aa67a57aeb366c54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "perf/benchmark.jl", "max_forks_repo_name": "mforets/IntervalLinearAlgebra.jl", "max_forks_repo_head_hexsha": "40726db50873af9a2d956496aa67a57aeb366c54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1363636364, "max_line_length": 114, "alphanum_fraction": 0.64, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.751148390743528}}
{"text": "import Pkg\nPkg.activate(\"RbfInterpolationTools\")\nusing RbfInterpolationTools\nusing Plots\n\n# Lets generate some observed points\nxx = rand(500)\nxy = rand(500)\nX = hcat(xx, xy)\n# The hidden function will be:\nz_func(x, y) = (x + y) * exp(-6.0 * (x^2 + y^2))\n# Taking the values in the points of\nz_obs = [z_func(x, y) for (x, y) in zip(xx, xy)]\n# To visualize it:\nPlots.scatter(X[:, 1], X[:, 2], zcolor = z_obs)\n\n\n# For example, lets generate a interpolation environment using the observed points.\n# We will be using as a basis fuction the ThinPlate [https://en.wikipedia.org/wiki/Thin_plate_spline]\ninter = RbfInterpolationTools.Interpolator(X = X, y = z_obs, basis_name = \"ThinPlate\")\n\n# Now, lets generate a 10 times denser mesh to generate the points\nnew_domain = (hcat(rand(100000), rand(100000)))\n# And we can actually see the it generates an interpolated value for each new coordinate\nz_interpolated = RbfInterpolationTools.interpolateMesh(inter, new_domain)\n# It can be easilly visualized using Plots and a scatter\nPlots.scatter(new_domain[:, 1], new_domain[:, 2], zcolor = z_interpolated)", "meta": {"hexsha": "848f61b7d4b8da980a2cde620ddc611e9b1f0906", "size": 1092, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/usageMesh.jl", "max_stars_repo_name": "munozariasjm/RbfInterpolationTools.jl", "max_stars_repo_head_hexsha": "f9889bf24e774761a973db25c9a9540970e5cfbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-03T19:26:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T19:26:24.000Z", "max_issues_repo_path": "examples/usageMesh.jl", "max_issues_repo_name": "munozariasjm/RbfInterpolationTools.jl", "max_issues_repo_head_hexsha": "f9889bf24e774761a973db25c9a9540970e5cfbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-03T01:08:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T22:40:06.000Z", "max_forks_repo_path": "examples/usageMesh.jl", "max_forks_repo_name": "munozariasjm/RbfInterpolationTools.jl", "max_forks_repo_head_hexsha": "f9889bf24e774761a973db25c9a9540970e5cfbc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4444444444, "max_line_length": 101, "alphanum_fraction": 0.739010989, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750360641186, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7511151294482143}}
{"text": "function sampleMarkovChain(n::Int, P::AbstractMatrix, πₚ::AbstractVector)\n    s = Vector{Int}(undef, n)\n    sampleMarkovChain!(s, n, P, πₚ)\nend\n\nfunction sampleMarkovChain!(s, n::Int, P::AbstractMatrix, πₚ::AbstractVector)\n    s[1] = rand(Categorical(πₚ))\n    @inbounds for i = 2:n\n        s[i] = rand(Categorical(P[s[i-1], :]))\n    end\n    s\nend\n\n# categorical sequence encoding/decoding\n@inline function encode(arr::Union{Vector{Int},Tuple}, k::Int)\n  s = 1\n  n = 1\n  @inbounds for i = 1:length(arr)\n    s += (arr[i] - 1) * n\n    n *= k\n  end\n  s\nend\n\n@inline function decode(s::Int, k::Int, l::Int)\n  arr = []\n  n = k^(l-1)\n  c = s - 1\n  for i = 1:l\n    pushfirst!(arr, div(c, n) + 1)\n    c = mod(c, n)\n    n = n // k\n  end  \n  arr\nend\n\n@inline function logsumexp(x::Vector{T}) where T<:Real\n  xmax = maximum(x)\n  y = map(x -> exp.(x - xmax), x)\n\n  log(sum(y)) + xmax\nend\n", "meta": {"hexsha": "8d235d59b63d63a2b982ec2db3b83837ffd41c38", "size": 875, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "riyadm/ConvHMM.jl", "max_stars_repo_head_hexsha": "9ca479b80a21355e1fdf27cda87e48cc9980874a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "riyadm/ConvHMM.jl", "max_issues_repo_head_hexsha": "9ca479b80a21355e1fdf27cda87e48cc9980874a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "riyadm/ConvHMM.jl", "max_forks_repo_head_hexsha": "9ca479b80a21355e1fdf27cda87e48cc9980874a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3488372093, "max_line_length": 77, "alphanum_fraction": 0.584, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.819893335913536, "lm_q1q2_score": 0.7511121709040436}}
{"text": "#=\nHackerrank problem - Geometric Distribution\nhttps://www.hackerrank.com/challenges/s10-geometric-distribution-1/problem\nhttps://www.hackerrank.com/challenges/s10-geometric-distribution-2/problem\n\nDate: 2020-07-30\nAuthor: Eric Nam\n=#\n\nusing Printf\n\nfunction dist_geomteric(p, n)\n    (1. - p) ^ (n - 1) * p\nend\n\n# Part 1\nfunction day4_1()\n    # STDIN \n    nu, denom = parse.(Int, split(readline(stdin)))\n    nth = parse(Int, readline(stdin))\n\n    result = dist_geomteric(nu / denom, nth)\n    println(\"$(@sprintf(\"%.3f\", result))\")\nend\n\n# day4_1()\n\n# Part 2\nfunction day4_2()\n    # STDIN \n    nu, denom = parse.(Int, split(readline(stdin)))\n    nth = parse(Int, readline(stdin))\n\n    result = sum(x -> dist_geomteric(nu / denom, x), 1:5)\n    println(\"$(@sprintf(\"%.3f\", result))\")\nend\n\nday4_2()\n", "meta": {"hexsha": "133a2ebc84659c13071bdc70b78d1d56d69dba7b", "size": 794, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "hackerrank_geometric_distribution.jl", "max_stars_repo_name": "eric-nam/julia_practices", "max_stars_repo_head_hexsha": "8baaff9533fd229dfd1ee298065c89d408e8c2b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hackerrank_geometric_distribution.jl", "max_issues_repo_name": "eric-nam/julia_practices", "max_issues_repo_head_hexsha": "8baaff9533fd229dfd1ee298065c89d408e8c2b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hackerrank_geometric_distribution.jl", "max_forks_repo_name": "eric-nam/julia_practices", "max_forks_repo_head_hexsha": "8baaff9533fd229dfd1ee298065c89d408e8c2b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.358974359, "max_line_length": 74, "alphanum_fraction": 0.6549118388, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7511121694400372}}
{"text": "﻿M(P) = [Int(sign(P[i]-P[j])) for i=1:length(P), j=1:length(P)]\r\npreference(d::Dict{String,Int}) = [d[k] for k in sort([keys(d)...])]\r\n\r\n\"\"\"\r\n    ⦸(d₁, d₂[, dₛ...])\r\n\r\nReturn \"light\" preference matrix of given rankings.\r\nA binary (infix) operation on two or more rankings.\r\n\r\n# Examples\r\n```jldoctest\r\njulia> ranking\"a₂,a₄,a₁,a₃\" ⦸ \r\n       ranking\"a₁,a₃∼a₄,a₂\" ⦸\r\n       ranking\"a₂∼a₃,a₄,a₁\" ⦸ \r\n       ranking\"a₃,a₂,a₁∼a₄\"\r\n4×4 Array{Int64,2}:\r\n  0   2  0   1\r\n -2   0  1  -2\r\n  0  -1  0  -1\r\n -1   2  1   0\r\n\r\njulia> ⦸(ranking\"123\",ranking\"231\",ranking\"312\")\r\n3×3 Array{Int64,2}:\r\n  0  -1   1\r\n  1   0  -1\r\n -1   1   0\r\n```\r\n\"\"\"\r\nfunction  ⦸(d₁::Dict{String,Int}, d₂::Dict{String,Int}, dₛ::Dict{String,Int}...)\r\n    @assert length(d₁) == length(d₂)\r\n    @assert sort([keys(d₁)...]) == sort([keys(d₂)...])\r\n    R =  -M(preference(d₁))-M(preference(d₂))\r\n    for d ∈ dₛ \r\n        @assert size(R)[1] == size(R)[2] == length(d)\r\n        @assert sort([keys(d₁)...]) == sort([keys(d)...])\r\n        R = ⦸(R, d)\r\n    end\r\n    return R\r\nend\r\n\r\n⦸(R::Matrix{Int}, d::Dict{String,Int}) = R - M(preference(d))\r\n\r\n", "meta": {"hexsha": "188ce07845bcc82b2fa73bf6bd211b09bf116cea", "size": 1103, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/op_obslash.jl", "max_stars_repo_name": "vaa-msu/Rankings.jl", "max_stars_repo_head_hexsha": "6043284d04b4e8e6e02ffaa071ba96766c70a9de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/op_obslash.jl", "max_issues_repo_name": "vaa-msu/Rankings.jl", "max_issues_repo_head_hexsha": "6043284d04b4e8e6e02ffaa071ba96766c70a9de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/op_obslash.jl", "max_forks_repo_name": "vaa-msu/Rankings.jl", "max_forks_repo_head_hexsha": "6043284d04b4e8e6e02ffaa071ba96766c70a9de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6511627907, "max_line_length": 81, "alphanum_fraction": 0.5149592022, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278533, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7511121636684497}}
{"text": "# Import needed libraries\nusing Plots\nusing XLSX\nusing DataFrames\nusing Statistics\n\n\n# Read the relevant excel workbook\ndf = DataFrames.DataFrame(XLSX.readtable(\"Folds5x2_pp.xlsx\", \"Sheet5\")...)\n\n# Split into design matrix and target vector\nX = df[:, 1:4]\ndesign_matrix = convert(Matrix, X)\n\ny = df[:, 5]  # Target vector\n\n# Split into training and test\ntrain_size = 0.80\ndata_size = size(design_matrix)[1]\n\ntrain_index = trunc(Int, train_size * data_size)\n\n# Split using the desired train size\nX_train = design_matrix[1:train_index, :]\nX_test = design_matrix[train_index+1:end, :]\n\ny_train = y[1:train_index]\ny_test = y[train_index+1:end]\n\n\n\"\"\"\n    scale_features(X)\n\nThis function attempts to normalise the design matrix (X) user pass.\nThe input data X is standardised and return along with other learned metrics.\n\nA tuple with 3 elements is returned representing (Standardised data, mean, std deviation).\n\n\"\"\"\nfunction scale_features(X)\n\n    μ = mean(X, dims=1)\n    σ = std(X, dims=1)\n\n    X_norm = (X .- μ) ./ σ\n\n    return (X_norm, μ, σ)\nend\n\n\n\"\"\"\n    transform_features(X, μ, σ)\n\nThis functions uses the mean and standard deviation values users pass to\nnormalise a new design matrix.\n\"\"\"\nfunction transform_features(X, μ, σ)\n    X_norm = (X .- μ) ./ σ\n    return X_norm\nend\n\n# Scale training features and get artificats for future use\nX_train_scaled, μ, σ = scale_features(X_train)\n\n# Transform the testing features by using the learned artifacts\nX_test_scaled = transform_features(X_test, μ, σ)\n\n\n\"\"\"\n    mean_squared_cost(X, y, θ)\n\nThis function computes the batch cost based on the values of the design matrix (X),\ntarget vector (y), and the weights (θ) passed to it.\n\"\"\"\nfunction mean_squared_cost(X, y, θ)\n    # Sample size\n    m = size(X)[1]\n\n    # Vectorised Prediction loss\n    preds = X * θ\n    loss = preds - y\n\n    # Half mean squared loss\n    cost =  (1/(2m)) * (loss' * loss)\n\n    return cost\nend\n\n\n\"\"\"\n    lin_reg_grad_descent(X, y, α, fit_intercept=true, n_iter=1000)\n\nThis function uses gradient descent algorithm to find the best weights (θ)\nthat minimises the mean squared loss between the predictions that the model\ngenerates and the target vector (y).\n\nA tuple of 1D vectors representing the weights (θ)\nand a history of loss at each iteration (𝐉) is returned.\n\"\"\"\nfunction lin_reg_grad_descent(X, y, α, fit_intercept=true, n_iter=2000)\n    # Initialize some useful values\n    m = length(y) # number of training examples\n\n    if fit_intercept\n        # Add a constant of 1s if fit_intercept is specified\n        constant = ones(m, 1)\n        X = hcat(constant, X)\n    else\n        X # Assume user added constants\n    end\n\n    # Use the number of features to initialise the theta θ vector\n    n = size(X)[2]\n    θ = zeros(n)\n\n    # Initialise the cost vector based on the number of iterations\n    𝐉 = zeros(n_iter)\n\n    for iter in range(1, stop=n_iter)\n        pred = X * θ\n\n        # Calcaluate the cost for each iter\n        𝐉[iter] = mean_squared_cost(X, y, θ)\n\n        # Update the theta θ at each iter\n        θ = θ - ((α/m) * X') * (pred - y);\n    end\n    return (θ, 𝐉)\nend\n\n\nθ, 𝐉 = lin_reg_grad_descent(X_train_scaled, y_train, 0.05, true, 3000)\n\nplot(𝐉,\n     label=\"Cost per iter\",\n     ylabel=\"Cost\",\n     xlabel=\"Number of Iteration\",\n     title=\"Cost Per Iteration\")\n\nsavefig(\"cost_plot\")\n\n\"\"\"\n    predict(X, θ, fit_intercept=true)\n\nThis function uses the learned weights (θ) to make predictions based on the\ndesign matrix passed as (X).\n\nThe 1D vector representing these predictions is finally returned.\n\"\"\"\nfunction predict(X, θ, fit_intercept=true)\n    m = size(X)[1]\n\n    if fit_intercept\n        constant = ones(m)\n        X = hcat(constant, X)\n    else\n        X\n    end\n\n    predictions = X * θ\n\n    return predictions\nend\n\n\n# Make predictions for both training and testing datasets\ntrain_preds = predict(X_train_scaled, θ)\ntest_preds = predict(X_test_scaled, θ)\n\n\n\n\"\"\"\n    rmse_score(y_true, y_pred)\n\nThis function calculates the RMSE based on the values of ground truth (y_true)\nand the predicted values generated by a model (y_pred)\n\"\"\"\nfunction rmse_score(y_true, y_pred)\n\n    errors = y_pred - y_true\n    errors² = errors .^ 2\n    mse = mean(errors²)\n    rmse = sqrt(mse)\n\n    return rmse\n\nend\n\n\nprintln(\"RMSE for Training Set: \", rmse_score(y_train, train_preds))\nprintln(\"RMSE for Testing Set: \", rmse_score(y_test, test_preds))\n\n\n\n\"\"\"\n    r_squared_score(y_pred, y_true)\n\nThis function returns the R squared value based on the predictions (y_pred)\nand the ground truth values (y_true)passed to it.\n\"\"\"\nfunction r_squared_score(y_pred, y_true)\n    # Just a convinient way of using notations\n    ∑ = sum\n    μ = mean\n\n    # Compute sum of explained variance (SST) and sum of squares of residuals\n    sst = ∑(((y_true .- μ(y_true)) .^ 2))\n    ssr = ∑(((y_pred .- y_true) .^ 2))\n\n    r² = 1 - (ssr / sst)\n\n    return r²\nend\n\n\n# Get the r-squared score for training and test datasets\ntrain_r² = r_squared_score(train_preds, y_train)\ntest_r² = r_squared_score(test_preds, y_test)\n\n\nprintln(\"Training R² score for test sets: \", train_r²)\nprintln(\"Testing R² score for test sets: \", test_r²)\n", "meta": {"hexsha": "c5b4825c2deae125667fb6a980871ec2446c415e", "size": 5136, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Tutorials/power_plant_project/multi_reg_grad_descent.jl", "max_stars_repo_name": "stratosmacker/Python-for-Data-Science", "max_stars_repo_head_hexsha": "ef83f391eb985c177ee44a891ad3efa979b9c368", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 166, "max_stars_repo_stars_event_min_datetime": "2017-11-20T06:34:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T17:24:48.000Z", "max_issues_repo_path": "Tutorials/power_plant_project/multi_reg_grad_descent.jl", "max_issues_repo_name": "ApurvShah007/Python-for-Data-Science", "max_issues_repo_head_hexsha": "5a25b1c734f48e77c652a1bfd68513fbd2e45891", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-12-03T12:01:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-06T12:36:01.000Z", "max_forks_repo_path": "Tutorials/power_plant_project/multi_reg_grad_descent.jl", "max_forks_repo_name": "ApurvShah007/Python-for-Data-Science", "max_forks_repo_head_hexsha": "5a25b1c734f48e77c652a1bfd68513fbd2e45891", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 70, "max_forks_repo_forks_event_min_datetime": "2018-01-02T16:22:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T07:18:14.000Z", "avg_line_length": 23.0313901345, "max_line_length": 90, "alphanum_fraction": 0.6859423676, "num_tokens": 1415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7511121632545796}}
{"text": "# Ridge Regression (Tikhonov regularization)\n\n#### auxiliary\n\nfunction lreg_chkdims(X::AbstractMatrix, Y::AbstractVecOrMat, trans::Bool)\n    mX, nX = size(X)\n    dX = ifelse(trans, mX, nX)\n    dY = ifelse(trans, nX, mX)\n    size(Y, 1) == dY || throw(DimensionMismatch(\"Dimensions of X and Y mismatch.\"))\n    return dX\nend\n\nlrsoltype{T}(::DenseVector{T}) = Vector{T}\nlrsoltype{T}(::DenseMatrix{T}) = Matrix{T}\n\n_vaug{T}(X::DenseMatrix{T}) = vcat(X, ones(T, 1, size(X,2)))::Matrix{T}\n_haug{T}(X::DenseMatrix{T}) = hcat(X, ones(T, size(X,1), 1))::Matrix{T}\n\n\n## linear least square\n\nfunction llsq{T<:FloatingPoint}(X::DenseMatrix{T}, Y::DenseVecOrMat{T}; \n                                trans::Bool=false, bias::Bool=true)\n    if trans\n        mX, nX = size(X)\n        size(Y, 1) == nX || throw(DimensionMismatch(\"Dimensions of X and Y mismatch.\"))\n        mX <= nX || error(\"mX <= nX is required when trans is false.\")\n    else\n        mX, nX = size(X)\n        size(Y, 1) == mX || throw(DimensionMismatch(\"Dimensions of X and Y mismatch.\"))\n        mX >= nX || error(\"mX >= nX is required when trans is false.\")\n    end\n    _ridge(X, Y, zero(T), trans, bias)\nend\n\n## ridge regression\n\nfunction ridge{T<:FloatingPoint}(X::DenseMatrix{T}, Y::DenseVecOrMat{T}, r::Real; \n                                trans::Bool=false, bias::Bool=true)\n    lreg_chkdims(X, Y, trans)\n    r >= zero(r) || error(\"r must be non-negative.\")\n    _ridge(X, Y, convert(T, r), trans, bias)\nend\n\nfunction ridge{T<:FloatingPoint}(X::DenseMatrix{T}, Y::DenseVecOrMat{T}, r::DenseVector{T}; \n                                trans::Bool=false, bias::Bool=true)\n    d = lreg_chkdims(X, Y, trans)\n    length(r) == d || throw(DimensionMismatch(\"Incorrect length of r.\"))\n    _ridge(X, Y, r, trans, bias)\nend\n\nfunction ridge{T<:FloatingPoint}(X::DenseMatrix{T}, Y::DenseVecOrMat{T}, r::DenseMatrix{T}; \n                                trans::Bool=false, bias::Bool=true)\n    d = lreg_chkdims(X, Y, trans)\n    size(r) == (d, d) || throw(DimensionMismatch(\"Incorrect size of r.\"))\n    _ridge(X, Y, r, trans, bias)\nend\n\n## implementation\n\nfunction _ridge{T<:FloatingPoint}(X::DenseMatrix{T}, Y::DenseVecOrMat{T}, \n                                  r::Union(Real, DenseVecOrMat), trans::Bool, bias::Bool)\n    if bias\n        if trans\n            X_ = _vaug(X)\n            A = cholfact!(_ridge_reg!(A_mul_Bt(X_, X_), r, bias)) \\ (X_ * Y)\n        else\n            X_ = _haug(X)\n            A = cholfact!(_ridge_reg!(X_'X_, r, bias)) \\ (X_'Y)\n        end\n    else\n        if trans\n            A = cholfact!(_ridge_reg!(A_mul_Bt(X, X), r, bias)) \\ (X * Y)\n        else\n            A = cholfact!(_ridge_reg!(X'X, r, bias)) \\ (X'Y)\n        end\n    end\n    return A::lrsoltype(Y)\nend\n\nfunction _ridge_reg!(Q::Matrix, r::Real, bias::Bool)\n    if r > zero(r)\n        n = size(Q, 1) - int(bias)\n        for i = 1:n\n            @inbounds Q[i,i] += r\n        end\n    end\n    return Q\nend\n\nfunction _ridge_reg!(Q::Matrix, r::DenseVector, bias::Bool)\n    n = size(Q, 1) - int(bias)\n    @assert length(r) == n\n    for i = 1:n\n        @inbounds Q[i,i] += r[i]\n    end\n    return Q\nend\n\nfunction _ridge_reg!(Q::Matrix, r::Matrix, bias::Bool)\n    n = size(Q, 1) - int(bias)\n    @assert size(r) == (n, n)\n    for j = 1:n, i = 1:n\n        @inbounds Q[i,j] += r[i,j]\n    end\n    return Q\nend\n\n", "meta": {"hexsha": "58761f184cd1cae46649052d7ff76e75cbec6147", "size": 3332, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lreg.jl", "max_stars_repo_name": "jfsantos/MultivariateStats.jl", "max_stars_repo_head_hexsha": "af494814f2102e9a18c4d9860a8971cd3b7bea33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-03-19T08:56:42.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-19T08:56:42.000Z", "max_issues_repo_path": "src/lreg.jl", "max_issues_repo_name": "jfsantos/MultivariateStats.jl", "max_issues_repo_head_hexsha": "af494814f2102e9a18c4d9860a8971cd3b7bea33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lreg.jl", "max_forks_repo_name": "jfsantos/MultivariateStats.jl", "max_forks_repo_head_hexsha": "af494814f2102e9a18c4d9860a8971cd3b7bea33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5688073394, "max_line_length": 92, "alphanum_fraction": 0.5600240096, "num_tokens": 1087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.751112161100789}}
{"text": "using LightGraphs\nusing LightGraphs.SimpleGraphs\nusing LinearAlgebra\nusing SparseArrays\nusing DifferentialEquations\nusing ProgressMeter\n\ninclude(\"utils\\\\randutils.jl\")\ninclude(\"utils\\\\categorical_tree.jl\")\n\n\"\"\"\n    contact_process_gillespie(g, Xi, β; kwargs)\n\nSimulate SI spreading on network `g` using the Gillespie algorithm.\n\n`g` is an `AbstractSimpleGraph{<:Integer}`, `β` is the infection rate and `Xi` is a bit vector whose true entries denote initially infected nodes. Additional arguments are\n  * `nmax=1000`: the maximum number of iterations of the algorithm\n  * `tmax=100.0`: the maximum time allowed\n  * `sampling_method=:tree`: The algorithm for sampling which node gets infected at a given time step. Choose from `:array`, `:sparse` or `:tree`. Default is `:tree` which scales better with the number of nodes (log(N) vs. N^2).\n  * `record=false`: Whether or not to record which node gets infected and by whom. If `true`, return a vector of pairs `(k,j)` describing which node `k` got infected and `j` its neighbor that infected it.\n\"\"\"\nfunction contact_process_gillespie(g::AbstractSimpleGraph{<:Integer}, Xi::BitVector, β::Real; nmax=length(Xi), tmax=100, sampling_method=:tree, record=false)\n    N = nv(g)\n    X = copy(Xi)\n    #nreactions::Int64 = 0\n    if sampling_method == :tree\n        a = zeros(N)\n    elseif sampling_method == :sparse\n        a = spzeros(N)\n    else\n        a = zeros(N)\n    end\n    for k in 1:N\n        if !X[k]\n            l = length(filter(i->X[i], inneighbors(g,k)))\n            a[k] = β*l# probability of k recieving infection is β time its number of infected incoming neighbors\n            #nreactions += l\n        end\n    end\n    if sampling_method == :tree # use a specialized binary tree\n        a = CategoricalTree(a)\n    end\n    a0 = sum(a)\n    #a0 = nreactions*β\n    if record\n        Es = Vector{Tuple{Int64,Int64}}(undef, nmax-1) # which node gets infected, and by whom\n    end\n    ts = zeros(nmax)\n    t = 0.0\n    n = 1\n    while n < nmax && t < tmax && a0 > 0\n        τ = log(1/rand())/a0\n        k = rand_categorical(a, a0) # which node gets infected\n        X[k] = true\n        #nreactions -= Int(floor(a[k]/β))\n        a[k] = 0.0\n        for i in Iterators.filter(j->!X[j],outneighbors(g,k))\n            a[i] += β\n            #nreactions += 1\n        end\n        if sampling_method == :sparse\n            SparseArrays.dropstored!(a,k) # O(1) cost?\n        end\n        #a0 = β*nreactions\n        a0 = sum(a)\n        t += τ\n        ts[n+1] = t\n        if record\n            j = rand(filter(l->X[l],inneighbors(g,k)))\n            Es[n] = (k,j)\n        end\n        n += 1\n    end\n    if record\n        return ts[1:n], sum(Xi) .+ collect(0:n-1), Es[1:(n-1)]\n    else\n        return ts[1:n], sum(Xi) .+ collect(0:n-1)\n    end\nend\n\n\"\"\"\n    contact_process_ode(g, Xi, β; kwargs)\n\nIntegrate the mean field approximation for SI spreading on network `g`.\n\n`Xi` is the initial condition, a vector whose elements denote infected nodes by 1 and susceptible by 0. `β` is the infection rate.\n\nKeyword arguments:\n  * `tmax = 100.0`: maximum time of the simulation.\n\"\"\"\nfunction contact_process_ode(g::AbstractSimpleGraph{<:Integer}, Xi, β::Real; tmax=100.0, saveat=[])\n    A = adjacency_matrix(g)\n    u0 = float(Xi)\n    f! = function(du,u,p,t)\n        du .= β*(1.0 .- u).*(A*u)\n    end\n    prob = ODEProblem(f!, u0, (0.0,tmax))\n    sol = solve(prob, Tsit5(), saveat=saveat)\n    return  sol.t, hcat(sol.u...)', sol\nend\n\n\"\"\"\n    contact_process_montecarlo(g, Xi, β; kwargs)\n\nCompute the average and variance of trajectories given by the gillespie algorithm over `nsims` simulations.\n\nKeyword arguments:\n  * `nmax=1000`: maximum number of iterations of each simulation\n  * `tmax=100.0`: maximum time of the simulations\n  * `nsims=100`: number of simulations to perform\n  * `nbins`: the number of time steps at which the average is computed\n\"\"\"\nfunction contact_process_montecarlo(g::AbstractSimpleGraph{<:Integer}, Xi::BitVector, β::Real; nmax = length(Xi), tmax = 100.0, nsims=1000, nbins = 100)\n    ts = LinRange(0.0, tmax, nbins)\n    X_sum = zeros(nbins)\n    M_sum = zeros(nbins) # running SSE\n    p = Progress(nsims, dt=1.0)\n    for n in 1:nsims\n        t, X = contact_process_gillespie(g, Xi, β, nmax=nmax, tmax=tmax)\n        l = 1\n        for k in 1:nbins\n            while l < length(t) && t[l+1] < ts[k]\n                l += 1\n            end\n            Xn = X[l]\n            Δn = Xn - X_sum[k]/(n>1 ? n-1 : 1)\n            X_sum[k] += Xn\n            M_sum[k] += Δn*(Xn-X_sum[k]/n)\n        end\n        ProgressMeter.next!(p; showvalues= [(:n,n)])\n    end\n    return ts, X_sum/nsims, sqrt.(M_sum/(nsims-1))\nend\n", "meta": {"hexsha": "3611520a84245b2cf55234468d188d84c6e047a5", "size": 4655, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "old/contact_process.jl", "max_stars_repo_name": "csimal/metaplex-networks", "max_stars_repo_head_hexsha": "2010f6bdb9a0cb7be78e74f8bf64dd9aba5871ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "old/contact_process.jl", "max_issues_repo_name": "csimal/metaplex-networks", "max_issues_repo_head_hexsha": "2010f6bdb9a0cb7be78e74f8bf64dd9aba5871ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "old/contact_process.jl", "max_forks_repo_name": "csimal/metaplex-networks", "max_forks_repo_head_hexsha": "2010f6bdb9a0cb7be78e74f8bf64dd9aba5871ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7388059701, "max_line_length": 228, "alphanum_fraction": 0.6128893663, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.751112159360869}}
{"text": "### Monte Carlo routines for\n### the 2D Ising model\n\nimport StatsBase: countmap\nimport StaticArrays: SVector\n\n\"\"\"\n    randomConfiguration(L)\n\nReturns a LxL Matrix filled randomly with ±1.\n\"\"\"\nfunction randomConfiguration(L::Int)\n    return rand(Int8[-1,1], L,L)\nend\n\n\"\"\"\n    frustratedConfiguration(L)\n\nReturns a configuration where all bonds are frustrated.\n\"\"\"\nfunction frustratedConfiguration(L::Int)\n    return Int8[(-1)^(i+j) for i=1:L,j=1:L]\nend\n\n\"\"\"\n    H(state, J=1.,h=0.)\n\nEnergy of Ising configuration for a given coupling `J` and external field `h`.\n\"\"\"\nfunction H(state::Matrix{Int8},J=1.,h=0.)\n    L = size(state,1)\n    s = h*(sum(state))\n\n    @inbounds for i in 1:L, j in 1:L\n        s += -J*state[i,j]*(state[i%L+1,j]+state[i,j%L+1])\n    end\n    return s\nend\n\n\"\"\"\n    dH(state,pos,J=1.,h=0.)\n\nEnergy difference between the current state `state`\nand one spin flipped at position `(i,j)` given coupling and field strength.\n\"\"\"\nfunction dH(state::Matrix{Int8},i,j,J=1.,h=0.)\n    L = size(state,1)\n    @inbounds return 2*J*state[i,j]*( state[i%L+1,j]+state[i,j%L+1]+\n        state[i==1 ? L : i-1,j]+state[i,j==1 ? L : j-1] ) + 2*h*state[i,j]\nend\n\n\"\"\"\n    m(state)\n\nMagnetization per spin\n\"\"\"\nm(state) = Float64(sum(state)/length(state))\n\n@inline neighbors(i,j,L) = CartesianIndex.([(i%L+1,j),(i,j%L+1),(i==1 ? L : i-1,j),(i,j==1 ? L : j-1)])\n@inline function neighbors(i,L)\n    r = (i-1)%L\n    c = div(i-1, L)\n    # @info r,c\n    SVector{4, Int32}(1 + (r+1)%L + c*L, 1 + ((r-1)>=0 ? r-1 : L-1) + c*L, 1 + r + L*((c+1)%L), 1 + r + L*((c-1)>=0 ? c-1 : L-1))\nend\n@inline function neighbors_leftup(i,L)\n    r = (i-1)%L\n    c = div(i-1, L)\n    # @info r,c\n    SVector{2, Int32}(1 + ((r-1)>=0 ? r-1 : L-1) + c*L, 1 + r + L*((c-1)>=0 ? c-1 : L-1))\nend\n\n\n\"\"\"\n    cluster_sizes(state)\n\nA cluster is a connected region of aligned spins. Retrieve the sizes of all of them.\n\"\"\"\nfunction cluster_sizes(state)\n    # Check for each element if they belong to the same cluster\n    # as their left or upper neighbor. \n    cluster = zeros(Int32, size(state))\n    max_cluster = 0\n    pointer = 1\n    new_cluster = true\n    while pointer <= length(state)\n        nn = neighbors_leftup(pointer, size(state, 1))\n        new_cluster = true\n        for n in nn\n            if cluster[n]!=0 && state[pointer]==state[n]\n                cluster[pointer] = cluster[n]\n                new_cluster = false\n            end\n        end\n        if new_cluster\n            cluster[pointer] = max_cluster += 1\n        end\n        pointer += 1\n    end\n\n    return countmap(reshape(cluster, length(cluster))) |> values |> collect\nend\n\n\"\"\"\n    metropolis_step!(state,beta,h)\n\nPerform one step of the Metropolis algorithm.\n`state` is mutated.\n\"\"\"\nfunction metropolis_step!(state::Matrix{Int8},beta,h)\n    i = rand(1:size(state,1))\n    j = rand(1:size(state,2))\n    dh = dH(state,i,j,1.,h)\n    if dh <= 0 || rand()<exp(-beta*dh)\n        state[i,j] *= -1\n    end\n    return nothing\nend\n\n\"\"\"\n    metropolis_sweep!(state,n,beta,h)\n\nPerform n Metropolis steps.\n\"\"\"\nfunction metropolis_sweep!(state,n,beta,h)\n    for _ in 1:n\n        metropolis_step!(state,beta,h)\n    end\nend\n\n\"\"\"\n    init(L,beta,h,sweep)\n\nSetup a configuration with `LxL` spins and perform an intial thermal sweep of\n`sweep` timesteps.\n\"\"\"\nfunction init(L,beta,h,sweep)\n    state = fill(Int8(-1), L, L)\n    # Initial sweep to get into the steady state\n    metropolis_sweep!(state,sweep,beta,h)\n    return state\nend\n\n\"\"\"\n    run_metropolis(L, beta, h;Tmax=1, sweep=0, sample_interval=1)\n\nSets up a random state and runs the Metropolis algorithm for a given set of parameters.\nSamples in defined intervals along the Markov-Chain.\n\nAn initial thermal sweep to go to equilibrium may be specified.\n\nReturns an array of averaged observables: [E, E^2, m, m^2, m^4] with total\nenergy E and magnetisation per spin m.\n\n# Arguments\n- L::Integer:            Linear system size\n- beta::Float:            Inverse temperature\n- h::Float:               External field\n- Tmax::Integer:          Number of steps\n- sweep::Integer:         Length of the initial sweep\n- sample_interval::Integer: sample interval\n\n# Example\n```\njulia> run_metropolis(50, 0., 0.;Tmax=50*10^3*50^2,sample_interval=10*50^2,sweep=10^3*50^2)\n5-element Array{Float64,1}:\n  -39.9664      # <E>\n 1753.5168      # <E^2>\n    0.010382079999999908 # <m>\n    0.00011572633600000021 # <m^2>\n    1.6924325969920386e-8 # <m^4>\n```\n\"\"\"\nfunction run_metropolis(L::Int, beta,h;Tmax::Int=1,sweep::Int=0,sample_interval::Int=1)\n    ## Initialise a random state\n    state = init(L,beta,h,sweep)\n    return _run_metropolis!(state,beta,h,Tmax=Tmax,sample_interval=sample_interval)\nend\n\n\"\"\"\n    _run_metropolis!(state::Matrix{Int8},beta,h;Tmax::Int=1,sample_interval::Int=1)\n\nAnalogous to `run_metropolis` but mutates an existing state. Called by `run_metropolis`.\n\"\"\"\nfunction _run_metropolis!(state::Matrix{Int8},beta,h;Tmax::Int=1,sample_interval::Int=1)\n\n    ## Define a matrix to record the observables.\n    ## One entry for each observable, e.g E and m.\n    ## Preallocating the matrix gives much better performance than\n    ## constructing it on the fly.\n    observables = zeros(Float64, 5)\n\n    k = 0 #counts the number of samples\n\n    t = 0 #simulation steps\n    e = 0.\n    mag = 0.\n\n    @inbounds begin\n        while(t<Tmax)\n            ## Take the defined no. of steps before\n            ## recording a measurement\n            metropolis_sweep!(state,sample_interval,beta,h)\n\n            ## Record observables\n            e = H(state,1.,h)\n            mag = m(state)\n            observables[1] += e\n            observables[2] += e^2\n            observables[3] += mag\n            observables[4] += mag^2\n            observables[5] += mag^4\n\n            ## increment counters\n            k+=1\n            t+=sample_interval\n        end\n    end\n    ## Return sample means\n    return observables/k\nend\n\n\"\"\"\n    metropolis_timeseries(L, β, Tmax; sample_interval=L^2, sweep=1000)\n\nFollows along a Markov chain in time.\nInitialises a random configuration, sweeps it for `sweep*L^2` timsteps, and records\nmagnetetisation and energy every `sample_interval` until `Tmax`.\n\nReturns a tuple of these time series.\n\"\"\"\nfunction metropolis_timeseries(L::Int, beta, Tmax; sample_interval=L^2, sweep=1000)\n    state = init(L,beta,0.,sweep*L^2)\n    #time series magnetization\n    tsm = Vector{Float64}(undef, div(Tmax,sample_interval))\n    #time series energy\n    tse = Vector{Float64}(undef, div(Tmax,sample_interval))\n\n    t=0\n    k=1\n    mag0 = m(state)\n    while(t<Tmax)\n        metropolis_sweep!(state,sample_interval,beta,0.)\n        tsm[k] = m(state)\n        tse[k] = H(state)\n        t+=sample_interval\n        k+=1\n    end\n    return tsm, tse\nend\n\n### Wolff algorithm ###\n### --------------- ###\n\n\"\"\"\n    cluster!(cluster_state, state, i,j, p)\n\nBuilds a cluster around position `(i,j)` with acceptance rate `p`.\n\n`cluster_state` is a boolean matrix of the same size as the system. It is set to `true` whenever\na site belongs to the cluster.\n\"\"\"\nfunction cluster!(cluster_state, state, i,j, p)\n    @inbounds begin L = size(state, 1)\n        s = state[i,j]\n        cluster_state[i,j] = true\n        for neighbor in neighbors(i,j,L)\n            if state[neighbor] == s && !cluster_state[neighbor] && rand()<p\n                cluster_state[neighbor] = true\n                cluster!(cluster_state, state, Tuple(neighbor)..., p)\n            end\n        end\n    end\nend\n\n\"\"\"\n    wolff_step!(state, cluster_state, beta)\n\nBuild a cluster and flip it.\n\"\"\"\nfunction wolff_step!(state, cluster_state, beta, h)\n    @inbounds begin\n        L = size(state,1)\n        i,j = rand(1:L,2)\n        fill!(cluster_state, false)\n        cluster!(cluster_state, state, i,j, 1.0-exp(-2.0*beta))\n        state[cluster_state] *= -1\n    end\n    return nothing\nend\n\nfunction wolff_sweep!(state, cluster, n, args...)\n    for _ in 1:n\n        wolff_step!(state, cluster, args...)\n    end\nend\n\n\"\"\"\n    _run_wolff!(state,cluster,beta,h;Tmax=1,sample_interval=1)\n\nRun the Wolff cluster algorithm on a given state. You need to provide a cluster matrix, e.g\n`similar(state,Bool)`.\n\nSee also: [`_run_metropolis`]\n\"\"\"\nfunction _run_wolff!(state::Matrix{Int8},cluster,beta,h;Tmax::Int=1,sample_interval::Int=1)\n\n    ## Define a matrix in which to record the observables.\n    ## One row for each observable, e.g E and m.\n    ## Preallocating the matrix gives much better performance than\n    ## constructing it on the fly.\n    observables = zeros(Float64,5)\n\n    k = 0 #counts the number of samples\n\n    # pick the middle lattice site for the spin correlation\n\n    t=0 #number of simulation steps\n    r=0 #repeat counter\n    e=0.\n    mag=0.\n    @inbounds begin\n        while(t<Tmax)\n            ## Do the defined no. of steps before\n            ## taking a measurement\n            for _ in 1:sample_interval\n                wolff_step!(state, cluster, beta, h)\n            end\n            ## Record observables\n            e = H(state,1.,0.)\n            mag = m(state)|>abs\n            observables[1] += e\n            observables[2] += e^2\n            observables[3] += mag\n            observables[4] += mag^2\n            observables[5] += mag^4\n\n            ## increment counters\n            k+=1\n            t+=sample_interval\n        end\n    end\n    ## Return statistics about the observables\n    return observables/k\nend\n\n\"\"\"\n    run_wolff(L, beta,h;Tmax=1,sweep=0,sample_interval=1)\n\nSee also: [`run_metropolis`]\n\"\"\"\nfunction run_wolff(L::Int, beta,h;Tmax::Int=1,sweep::Int=0,sample_interval::Int=1)\n    ## Initialise a random state\n    function init(L,beta)\n        state = randomConfiguration(L)\n        cluster = zeros(Bool,L,L)\n        # Initial sweep to get into the steady state\n        for _ in 1:sweep\n            wolff_step!(state, cluster, beta, h)\n        end\n        return state,cluster\n    end\n\n    state,cluster = init(L,beta)\n    return _run_wolff!(state,cluster,beta,0.,Tmax=Tmax,sample_interval=sample_interval)\nend\n", "meta": {"hexsha": "d4eb0ae9e0c95237eec73ee944ee2fb1a8756793", "size": 9972, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mcmc.jl", "max_stars_repo_name": "skleinbo/Ising", "max_stars_repo_head_hexsha": "8f07aee679738e921e16d31b824e3fc373b1f812", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-08-24T17:34:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T11:20:05.000Z", "max_issues_repo_path": "src/mcmc.jl", "max_issues_repo_name": "Yaren-Github/Ising", "max_issues_repo_head_hexsha": "8f07aee679738e921e16d31b824e3fc373b1f812", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-08-25T12:14:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-28T07:52:21.000Z", "max_forks_repo_path": "src/mcmc.jl", "max_forks_repo_name": "Yaren-Github/Ising", "max_forks_repo_head_hexsha": "8f07aee679738e921e16d31b824e3fc373b1f812", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-08T10:21:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T10:21:58.000Z", "avg_line_length": 27.1716621253, "max_line_length": 129, "alphanum_fraction": 0.6174288006, "num_tokens": 2933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7511121576209487}}
{"text": "@doc raw\"\"\"\n    translate_forces_moments(forces_1, moments_1, p1, p2)\n\nCalculate equivalent moment at point 2 (p2) given the forces (forces_1)  and moments\n(moments_1) at point 1 (p1).\n\n`` r = p_1 - p_2 ``\n\n``M_{2} = M_{1} + r \\times F_{1}``\n\"\"\"\nfunction translate_forces_moments(forces_1, moments_1, p1, p2)\n    r21 = p1 - p2\n    moments_2 = moments_1 + r21 × forces_1\n    return moments_2\nend\n\n\n@doc raw\"\"\"\n    steiner_inertia(cg, inertia_g, mass, p2)\n\nCalculate the inertia tensor of a rigid solid at point 2 (p2), given the inertia tensor\n(inertia_g) at the center of gravity (cg) and the mass of the system.\n\n`` r = p_2 - cg ``\n\n``I_{2} = I_{cg} + m (r^T · r I - r · r^T) ``\n\"\"\"\nfunction steiner_inertia(cg, inertia1, mass, p2)\n    r = p2 - cg\n    inertia2 = inertia1 + mass * ((r' * r) * I - r*r')\n    return inertia2\nend\n\n\n\"\"\"\n    coordinated_turn_bank(ψ_dot, α, β, tas, γ[, g])\n\nCalculate roll angle (ϕ) [rad] for a given turn rate, angle of attack, angle of sideslip,\ntas and flight path angle in the absence of wind for a coordinated turn bank.\n\nImposes sum of forces along y body axis equal to zero.\n\n# Arguments\n- `ψ_dot`: turn rate (rad/s).\n- `α`: angle of attack (rad).\n- `β`: angle of sideslip (rad).\n- `tas`: true air speed (m/s).\n- `γ`: flight path angle (rad).\n- `g`: gravity (m/s²). Optional. Default value is `gD`.\n\"\"\"\nfunction coordinated_turn_bank(ψ_dot, α, β, tas, γ, g=gD)\n    G = ψ_dot * tas / g\n\n    if abs(γ) < 1e-8\n        ϕ = G * cos(β) / (cos(α) - G * sin(α) * sin(β))\n        ϕ = atan(ϕ)\n    else\n        a = 1 - G * tan(α) * sin(β)\n        b = sin(γ) / cos(β)\n        c = 1 + G^2 * cos(β)^2\n\n        sq = sqrt(c * (1 - b^2) + G^2 * sin(β)^2)\n\n        num = (a - b^2) + b * tan(α) * sq\n        den = a ^ 2 - b^2 * (1 + c * tan(α)^2)\n\n        ϕ = atan(G * cos(β) / cos(α) * num / den)\n    end\n    return ϕ\nend\n", "meta": {"hexsha": "8be592147a6a7d109134b34436769e26b45bce52", "size": 1840, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mechanics.jl", "max_stars_repo_name": "AlexS12/FlightMechanicsUtils.jl", "max_stars_repo_head_hexsha": "862f3cdac936c65881bc2aa8f1168ead8d5284d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-06-24T17:05:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T16:56:11.000Z", "max_issues_repo_path": "src/mechanics.jl", "max_issues_repo_name": "AlexS12/FlightMechanicsUtils.jl", "max_issues_repo_head_hexsha": "862f3cdac936c65881bc2aa8f1168ead8d5284d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-03-13T19:26:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-06T11:41:07.000Z", "max_forks_repo_path": "src/mechanics.jl", "max_forks_repo_name": "AlexS12/FlightMechanicsUtils.jl", "max_forks_repo_head_hexsha": "862f3cdac936c65881bc2aa8f1168ead8d5284d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9154929577, "max_line_length": 89, "alphanum_fraction": 0.5798913043, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.751050326875026}}
{"text": "\nmodule LPC\n\n#\n# TODO:\n# [v] lpc-burg\n# [ ] lattice-filter synth\n# [ ] warped-lpc\n# [ ] lpc-acorr\n# [ ] lpc-covar\n# [ ] Line-Spectral-Pairs\n# [v] power-spectrum est\n#\n\nexport lpc_burg, pow_spect\nexport log_area_ratio, inv_sine_coeffs\n\nfunction lpc_burg{T <: Number}( x::AbstractVector{T}, p::Int)\n# LPC (Linear-Predictive-Code) estimation, using the Burg-method\n# @param: x - signal to predict\n# @param: p - prediction order\n# @retval: a - direct form coeffs\n# @retval: r - reflection coefficients (usable for lattice-filter?)\n# such that:\n# minimizing x_prediction(n) = a*x\n# ie: an IIR:\n#  y = filt(1, a, white)\n# should have similiar spectrum to x\n# where 'white' is a signal with white spectrum\n# \n# The Burg-Method, which, provide both a minimal-phase (stable IIR)\n# and estimates 'a', on a finite support [1]\n# Combining the advantages on both traditional LPC methods\n# (autocorrelation - minPhase, and covariance - finite-support)\n#\n# Implementing the loop from the article:\n# [1] - ENHANCED PARTIAL TRACKING USING LINEAR PREDICTION\n# (DAFX'03 article, Lagrange et al)\n# http://www.elec.qmul.ac.uk/dafx03/proceedings/pdfs/dafx19.pdf\n#\n# Note: After implementing - I found matlab has an 'arburg()' - in\n# the 'signal-processing-toolbox', with virtually identical code\n# but hey, why use a library when you can easily reimplement it?\n# anyhow, normalized interface.\n#\n# (c) Kobic, 2009, 2015, MIT License\n# Translated my old(er) matlab code into julia::\n\n# TODO: check memory allocations, gc etc!\n\n    ef = x    # forward error\n    eb = x    # backwards error\n    a = [1; zeros(T, p)]  # prediction coeffs\n    refl = zeros(T, p) # reflection coeffs\n    k = zero(T)\n\n# zero-mean - or not?\n    prediction_err = dot(x,x) ./ length(x)  # variance\n\n    for m in 1:p\n        efp = ef[1:end-1]\n        ebp = eb[2:end]\n        k = -2 .* dot(ebp,efp) ./ ( dot(ebp,ebp) .+ dot(efp,efp) )\n        refl[m] = k           # save reflection coeffs (if needed)\n        ef = efp + k.*ebp\n        eb = ebp + k.*efp\n        a[1:m+1] = [a[1:m]; 0] + k.*[0; a[m:-1:1]]\n        prediction_err *= (1 - k*k)\n    end\n\n    return a, prediction_err, refl \nend\n\n\n\nfunction pow_spect(ar, err, dft_order = 256)\n    f = rfft( [ar; zeros(dft_order - length(ar))] )\n    psd = err ./ (abs(f).^2 + eps() )\n\n    return psd\nend\n\nfunction log_area_ratio(k)\n    return log( (1 + k) ./ (1 - k) )\nend\n\nfunction inv_sine_coeffs(k)\n    return 2asin(k) ./ pi\nend\n\nend # module\n\n", "meta": {"hexsha": "903e018d4befbc0a11e8ee88277ae0670a97974d", "size": 2439, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LPC.jl", "max_stars_repo_name": "oyd11/LPC.jl", "max_stars_repo_head_hexsha": "3d252385ac58f4f39fdecaa705f9c448c0dcc7c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LPC.jl", "max_issues_repo_name": "oyd11/LPC.jl", "max_issues_repo_head_hexsha": "3d252385ac58f4f39fdecaa705f9c448c0dcc7c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-12-15T21:27:01.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-13T07:37:23.000Z", "max_forks_repo_path": "src/LPC.jl", "max_forks_repo_name": "oyd11/LPC.jl", "max_forks_repo_head_hexsha": "3d252385ac58f4f39fdecaa705f9c448c0dcc7c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2258064516, "max_line_length": 67, "alphanum_fraction": 0.6404264043, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440397949314, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7510503211263532}}
{"text": "## this generates data from the simple supply-demand model\n#  q = α1 + α2*p + α3*m + e1\n#  q = β1 + β2*p +        e2\n## setup\nusing Econometrics, Plots, DelimitedFiles\n# number of obsn\nn = 500\n# model parameters\nα1 = 100.0\nα2 = -1.0\nα3 = 1.0\nβ1 = 20.0\nβ2 = 1.0\n\n## make variables and shocks\n# exog var income\nm = randn(n,5)\nm = sum(m.*m,dims=2) # chi square df=5\n# structural shocks\nϵ1 = 1.0*randn(n)\nϵ2 = 1.0*randn(n)\n# rf shocks\nν1 = (β2*ϵ1-α2*ϵ2)/(β2-α2)\nν2 = (ϵ1-ϵ2)/(β2-α2)\n# rf coefs\nπ11 = (β2*α1-α2*β1)/(β2-α2)\nπ21 = β2*α3/(β2-α2)\nπ12 = (α1-β1)/(β2-α2)\nπ22 = α3/(β2-α2)\n\n##  generate endog variables computed from rf\nq = π11 .+ π21*m + ν1\np = π12 .+ π22*m + ν2\n## write and plot data\ndata = [q p m]\ndata = sortbyc(data,3)\nnn = Int(n/4)\np = scatter(data[1:nn,2], data[1:nn,1], markersize=8, xlabel=\"price\", ylabel=\"quantity\", legend=false)\nfor i = 2:4\n    scatter!(data[(i-1)*nn+1:i*nn,2], data[(i-1)*nn:i*nn,1], markersize=8, show=true)\nend\ndisplay(p)\n#writedlm(\"data.txt\", data)\n", "meta": {"hexsha": "f6de9823f441918426991683c25ada66307ebe1c", "size": 987, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/Intro/SupplyDemand.jl", "max_stars_repo_name": "mcreel/EconometricsNotes", "max_stars_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-19T18:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T18:23:45.000Z", "max_issues_repo_path": "Examples/Intro/SupplyDemand.jl", "max_issues_repo_name": "mcreel/EconometricsNotes", "max_issues_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/Intro/SupplyDemand.jl", "max_forks_repo_name": "mcreel/EconometricsNotes", "max_forks_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4318181818, "max_line_length": 102, "alphanum_fraction": 0.6160081054, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948495, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7510503195470145}}
{"text": "export metric_lorenz, distancecircle!, distancecircle\n\nfunction metric_lorenz(Nx::Int64)\n    #Pairwise distance matrix\n    dist = zeros(Int64, Nx, Nx)\n    for i=2:Nx\n        for j=1:i-1\n            dist[i,j] = distancecircle!(i, j, Nx)\n        end\n    end\n    dist  += dist'\nend\n\nfunction distancecircle!(i, j, Nx)\nd1 = abs(i-j)\n\nif i<j\n    d2 = i + Nx - j\nelseif i>j\n    d2 = j + Nx -i\nelse\n    d2 = 0\nend\nreturn minimum([d1, d2])\nend\n\ndistancecircle(Nx) = (i,j)-> distancecircle!(i, j, Nx)\n", "meta": {"hexsha": "d08af622b13bdcf26649f2df1ccdfa6ba7a0ff7a", "size": 492, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lorenz63/metric_lorenz.jl", "max_stars_repo_name": "mleprovost/TransportBasedInference.jl", "max_stars_repo_head_hexsha": "bdcedf72e9ea23c24678fe6af7a00202c5f9d5d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-23T03:16:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T03:16:56.000Z", "max_issues_repo_path": "src/lorenz63/metric_lorenz.jl", "max_issues_repo_name": "mleprovost/TransportBasedInference.jl", "max_issues_repo_head_hexsha": "bdcedf72e9ea23c24678fe6af7a00202c5f9d5d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lorenz63/metric_lorenz.jl", "max_forks_repo_name": "mleprovost/TransportBasedInference.jl", "max_forks_repo_head_hexsha": "bdcedf72e9ea23c24678fe6af7a00202c5f9d5d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5714285714, "max_line_length": 54, "alphanum_fraction": 0.5955284553, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7510503155662446}}
{"text": "#!/usr/bin/env julia\n\nexport pe25\n\nfunction pe25(n::Integer=1000)\n    fib(n::Integer) = ([1 1;1 0]^n)[1,2]\n    i=big(1)\n    while ndigits(fib(i))<n\n        i+=1\n    end\n    i\nend\n\nif !haskey(ENV,\"PROJECT_EULER_WITHOUT_RESULT\")\n    pe25()|>print\nend\n", "meta": {"hexsha": "3dc91f7877717d26820d56deae11989d1a816432", "size": 249, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "25. 1000-digit Fibonacci number/25.jl", "max_stars_repo_name": "miRoox/ProjectEuler", "max_stars_repo_head_hexsha": "020e8efddbf0dde33f2b2561e7b636fa199be75c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-11-13T16:11:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T23:20:05.000Z", "max_issues_repo_path": "25. 1000-digit Fibonacci number/25.jl", "max_issues_repo_name": "miRoox/ProjectEuler", "max_issues_repo_head_hexsha": "020e8efddbf0dde33f2b2561e7b636fa199be75c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-12-27T15:12:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-27T15:12:05.000Z", "max_forks_repo_path": "25. 1000-digit Fibonacci number/25.jl", "max_forks_repo_name": "miRoox/ProjectEuler", "max_forks_repo_head_hexsha": "020e8efddbf0dde33f2b2561e7b636fa199be75c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.6470588235, "max_line_length": 46, "alphanum_fraction": 0.59437751, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404057671712, "lm_q2_score": 0.808067208930584, "lm_q1q2_score": 0.7510503145555876}}
{"text": "normalizecolumns(m::AbstractArray{T, 2}) where {T<:Number} = m ./ sqrt.(sum(m .^ 2, dims = 1) .+ eps(T))\nfunction normalizecolumns!(m::AbstractArray{T, 2}) where {T<:Number}\n\tm .= normalizecolumns(m)\nend\n\n\"\"\"\n\t\thsplitsoftp(x, ϵ = 1f-5)\n\n\t\tSplits x horizontally into two equal parts and use softplus to the lower part.\n\t\tϵ is added to the soft-plus to prevent underflow and improve the numerical stability\n\n\"\"\"\nhsplitsoftp(x,ϵ = 1f-5) = x[1:size(x, 1) ÷ 2, :], softplus.(x[size(x, 1) ÷ 2 + 1 : 2 * (size(x, 1) ÷ 2), :] .+ ϵ)\nhsplit1softp(x,ϵ = 1f-5) = x[1:size(x, 1) - 1, :], softplus.(x[end, :] .+ ϵ)\n\n\"\"\"\n\t\tkldiv(μ,σ2)\n\n\t\tkl-divergence of a Gaussian min mean `μ` and diagonal variance `σ^2`\n\t\tto N(0,I)\n\"\"\"\nkldiv(μ,σ2) = - mean(sum((@.log(σ2) - μ^2 - σ2), dims = 1))\n\nlog_normal(x) = - sum((x.^2), dims = 1) ./ 2 .- size(x, 1) * log(2f0 * π) / 2\nlog_normal(x, μ) = log_normal(x - μ)\nlog_normal(x, μ, σ2::Vector{T}) where {T<:Number} = - sum((x - μ) .^ 2 ./ σ2' .+ log.(σ2' .* 2π), dims = 1) / 2\nlog_normal(x, μ, Σ::Matrix{T}) where {T<:Number} = - (log(det(Σ)) + (x - μ)' * inv(Σ) * (x - μ) + size(Σ, 1) * log(2π)) / 2\n\n\"\"\"\n\tvmfentropy(m, κ)\n\n\tEntropy of Von Mises-Fisher distribution\n\"\"\"\nvmfentropy(m, κ) = .-κ .* besselix(m / 2, κ) ./ besselix(m / 2 - 1, κ) .- ((m ./ 2 .- 1) .* log.(κ) .- (m ./ 2) .* log(2π) .- (κ .+ log.(besselix(m / 2 - 1, κ))))\n\n\"\"\"\n\thuentropy(m)\n\n\tEntropy of Hyperspherical Uniform distribution\n\"\"\"\nhuentropy(m) = m / 2 * log(π) + log(2) - lgamma(m / 2)\n\n# Likelihood estimation of a sample x under VMF with given parameters taken from https://pdfs.semanticscholar.org/2b5b/724fb175f592c1ff919cc61499adb26996b1.pdf\n# normalizing constant for density function of VMF\nc(p, κ) = κ ^ (p / 2 - 1) / ((2π) ^ (p / 2) * besseli(p / 2 - 1, κ))\n\n# log likelihood of one sample under the VMF dist with given parameters\nlog_vmf_c(x, μ, κ) = κ * μ' * x .+ log(c(length(μ), κ))\nlog_vmf_c(x::AbstractMatrix, μ::AbstractMatrix, κ::T) where {T <: Number} = [log_vmf_c(x[:, i], μ[:, i], κ) for i in size(x, 2)] \nlog_vmf_c(x::AbstractMatrix, μ::AbstractMatrix, κ::AbstractVector) = [log_vmf_c(x[:, i], μ[:, i], κ[i]) for i in size(x, 2)] \nlog_vmf_wo_c(x, μ, κ) = κ * μ' * x\n\npairwisecos(x, y) = max.(1 .- (x' * y), 0) # This is a bit of a hack to avoid the distance being negative due to float\npairwisecos(x) = pairwisecos(x, x)\n\nk_imq(x, y, c) = sum( c./ (c .+ pairwisecos(x, y))) / (size(x, 2) * size(y, 2))\nk_imq(x::T, c) where {T <: AbstractMatrix} = sum(c ./ (c .+ pairwisecos(x))) / (size(x, 2) * (size(x, 2) - 1))\nk_imq(x::T, c) where {T <: AbstractVector} = zero(eltype(x))\n\nmmd_imq(x,y,c) = k_imq(x,c) + k_imq(y,c) - 2 * k_imq(x,y,c)\n\nfunction gaussiansample(μ, σ2)\n\tϵ = randn!(similar(μ,size(μ)))\n\tμ .+ sqrt.(σ2) .* ϵ\nend\n\nfunction samplehsuniform(size...)\n\tv = randn(size...)\n\tv = normalizecolumns(v)\nend", "meta": {"hexsha": "3f69920e770d1b77bceb7178a78a7ca37574417d", "size": 2822, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "honzabim/FewShotAnomalyDetection", "max_stars_repo_head_hexsha": "63e3186ec72dcb1b5907edb347759eae515dfade", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-08-19T14:01:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-20T18:31:46.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "honzabim/FewShotAnomalyDetection", "max_issues_repo_head_hexsha": "63e3186ec72dcb1b5907edb347759eae515dfade", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "honzabim/FewShotAnomalyDetection", "max_forks_repo_head_hexsha": "63e3186ec72dcb1b5907edb347759eae515dfade", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-16T12:04:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-16T12:04:24.000Z", "avg_line_length": 40.3142857143, "max_line_length": 162, "alphanum_fraction": 0.5963855422, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7510503119655921}}
{"text": "immutable LogNormal <: ContinuousUnivariateDistribution\n    meanlog::Float64\n    sdlog::Float64\n    function LogNormal(ml::Real, sdl::Real)\n    \tsdl > zero(sdl) || error(\"sdlog must be positive\")\n    \tnew(float64(ml), float64(sdl))\n    end\nend\n\nLogNormal(ml::Real) = LogNormal(ml, 1.0)\nLogNormal() = LogNormal(0.0, 1.0)\n\n@_jl_dist_2p LogNormal lnorm\n\nentropy(d::LogNormal) = 0.5 + 0.5 * log(2.0 * pi * d.sdlog^2) + d.meanlog\n\ninsupport(::LogNormal, x::Real) = zero(x) < x < Inf\ninsupport(::Type{LogNormal}, x::Real) = zero(x) < x < Inf\n\nfunction kurtosis(d::LogNormal)\n   exp(4.0 * d.sdlog^2) + 2.0 * exp(3.0 * d.sdlog^2) +\n        3.0 * exp(2.0 * d.sdlog^2) - 6.0\nend\n\nmean(d::LogNormal) = exp(d.meanlog + d.sdlog^2 / 2)\n\nmedian(d::LogNormal) = exp(d.meanlog)\n\n# mgf(d::LogNormal)\n# cf(d::LogNormal)\n\nmode(d::LogNormal) = exp(d.meanlog - d.sdlog^2)\nmodes(d::LogNormal) = [mode(d)]\n\nfunction skewness(d::LogNormal)\n    (exp(d.sdlog^2) + 2.0) * sqrt(exp(d.sdlog^2) - 1.0)\nend\n\nfunction var(d::LogNormal)\n    sigsq = d.sdlog^2\n    (exp(sigsq) - 1) * exp(2d.meanlog + sigsq)\nend\n\nfunction fit_mle{T <: Real}(::Type{LogNormal}, x::Array{T})\n    lx = log(x)\n    LogNormal(mean(lx), std(lx))\nend\n", "meta": {"hexsha": "54e4b34dc062d8a4d9c02c811f4812c83dbc8750", "size": 1190, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/lognormal.jl", "max_stars_repo_name": "simonbyrne/Distributions.jl", "max_stars_repo_head_hexsha": "a9bd0e62002a94007ecd590e51cb27af9a346544", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/lognormal.jl", "max_issues_repo_name": "simonbyrne/Distributions.jl", "max_issues_repo_head_hexsha": "a9bd0e62002a94007ecd590e51cb27af9a346544", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/lognormal.jl", "max_forks_repo_name": "simonbyrne/Distributions.jl", "max_forks_repo_head_hexsha": "a9bd0e62002a94007ecd590e51cb27af9a346544", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7916666667, "max_line_length": 73, "alphanum_fraction": 0.6302521008, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.8289388083214155, "lm_q1q2_score": 0.7510101136434861}}
{"text": "using ReachabilityAnalysis, SparseArrays\n\nLazySets.set_ztol(Float64, 1e-14)\n\nfunction platoon_connected(; deterministic_switching::Bool=true,\n                             c1=5.0)  # clock constraints\n    n = 10 # 9 dimensions + time\n    # x' = Ax + Bu + c\n    A = Matrix{Float64}(undef, n, n)\n    A[1, :] = [0, 1.0, 0, 0, 0, 0, 0, 0, 0, 0]\n    A[2, :] = [0, 0, -1.0, 0, 0, 0, 0, 0, 0, 0]\n    A[3, :] = [1.6050, 4.8680, -3.5754, -0.8198, 0.4270, -0.0450, -0.1942,  0.3626, -0.0946, 0.]\n    A[4, :] = [0, 0, 0, 0, 1.0, 0, 0, 0, 0, 0,]\n    A[5, :] = [0, 0, 1.0, 0, 0, -1.0, 0, 0, 0, 0]\n    A[6, :] = [0.8718, 3.8140, -0.0754,  1.1936, 3.6258, -3.2396, -0.5950,  0.1294, -0.0796, 0.]\n    A[7, :] = [0, 0, 0, 0, 0, 0, 0, 1.0, 0, 0]\n    A[8, :] = [0, 0, 0, 0, 0, 1.0, 0, 0, -1.0, 0]\n    A[9, :] = [0.7132, 3.5730, -0.0964,  0.8472, 3.2568, -0.0876,  1.2726,  3.0720, -3.1356, 0.]\n    A[10, :] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0]; # t' = 1\n\n    if deterministic_switching\n        invariant = HalfSpace(sparsevec([n], [1.], n), c1) # t <= c1\n    else\n        invariant = Universe(n)\n    end\n\n    # acceleration of the lead vehicle + time\n    B = sparse([2], [1], [1.0], n, 1)\n    U = Hyperrectangle(low=[-9.], high=[1.])\n    c = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0]\n    @system(x' = Ax + Bu + c, x ∈ invariant, u ∈ U)\nend\n\nfunction platoon_disconnected(; deterministic_switching::Bool=true,\n                                c2=5.0)  # clock constraints\n    n = 10 # 9 dimensions + time\n    # x' = Ax + Bu + c\n    A = Matrix{Float64}(undef, n, n)\n    A[1, :] = [0, 1.0, 0, 0, 0, 0, 0, 0, 0, 0]\n    A[2, :] = [0, 0, -1.0, 0, 0, 0, 0, 0, 0, 0]\n    A[3, :] = [1.6050, 4.8680, -3.5754, 0, 0, 0, 0, 0, 0, 0]\n    A[4, :] = [0, 0, 0, 0, 1.0, 0, 0, 0, 0, 0,]\n    A[5, :] = [0, 0, 1.0, 0, 0, -1.0, 0, 0, 0, 0]\n    A[6, :] = [0, 0, 0,  1.1936, 3.6258, -3.2396, 0, 0, 0, 0.]\n    A[7, :] = [0, 0, 0, 0, 0, 0, 0, 1.0, 0, 0]\n    A[8, :] = [0, 0, 0, 0, 0, 1.0, 0, 0, -1.0, 0]\n    A[9, :] = [0.7132, 3.5730, -0.0964,  0.8472, 3.2568, -0.0876,  1.2726,  3.0720, -3.1356, 0.]\n    A[10, :] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0]; # t' = 1\n\n    if deterministic_switching\n        invariant = HalfSpace(sparsevec([n], [1.], n), c2) # t <= c2\n    else\n        invariant = Universe(n)\n    end\n\n    # acceleration of the lead vehicle + time\n    B = sparse([2], [1], [1.0], n, 1)\n    U = Hyperrectangle(low=[-9.], high=[1.])\n    c = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0]\n    @system(x' = Ax + Bu + c, x ∈ invariant, u ∈ U)\nend\n\nfunction platoon(; deterministic_switching::Bool=true,\n                   c1=5.0,  # clock constraints\n                   c2=5.0,  # clock constraints\n                   tb=10.0,  # lower bound for loss of communication\n                   tc=20.0, tr=20.0) # upper bound for loss of communication (tc) and reset time (tr)\n\n    # three variables for each vehicle, (ei, d(et)/dt, ai) for\n    # (spacing error, relative velocity, speed), and the last dimension is time\n    n = 9 + 1\n\n    # transition graph\n    automaton = LightAutomaton(2)\n    add_transition!(automaton, 1, 2, 1)\n    add_transition!(automaton, 2, 1, 2)\n\n    # modes\n    mode1 = platoon_connected(deterministic_switching=deterministic_switching, c1=c1)\n    mode2 = platoon_disconnected(deterministic_switching=deterministic_switching, c2=c2)\n    modes = [mode1, mode2]\n\n    # common reset\n    reset = Dict(n => 0.)\n\n    # transition l1 -> l2\n    if deterministic_switching\n        guard = Hyperplane(sparsevec([n], [1.], n), c1) # t == c1\n    else\n        # tb <= t <= tc\n        guard = HPolyhedron([HalfSpace(sparsevec([n], [-1.], n), -tb),\n                             HalfSpace(sparsevec([n], [1.], n), tc)])\n    end\n    t1 = ConstrainedResetMap(n, guard, reset)\n\n    # transition l2 -> l1\n    if deterministic_switching\n        guard = Hyperplane(sparsevec([n], [1.], n), c2) # t == c2\n    else\n        guard = HalfSpace(sparsevec([n], [1.], n), tr) # t <= tr\n    end\n    t2 = ConstrainedResetMap(n, guard, reset)\n    resetmaps = [t1, t2]\n\n    H = HybridSystem(automaton, modes, resetmaps, [AutonomousSwitching()])\n\n    # initial condition is at the orgin in mode 1\n    X0 = BallInf(zeros(n), 0.0)\n    initial_condition = [(1, X0)]\n\n    return IVP(H, initial_condition)\nend\n\nfunction dmin_specification(sol, dmin)\n    return (-ρ(sparsevec([1], [-1.0], 10), sol) > dmin) &&\n           (-ρ(sparsevec([4], [-1.0], 10), sol) > dmin) &&\n           (-ρ(sparsevec([7], [-1.0], 10), sol) > dmin)\nend\n", "meta": {"hexsha": "9089843cd448d0ac9f50e235304e023f6a9a05f4", "size": 4440, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/Platoon/Platoon.jl", "max_stars_repo_name": "JuliaReach/ARCH2021_AFF_RE", "max_stars_repo_head_hexsha": "205737b30c75404c0a3954c06e882c26fe64ab9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/Platoon/Platoon.jl", "max_issues_repo_name": "JuliaReach/ARCH2021_AFF_RE", "max_issues_repo_head_hexsha": "205737b30c75404c0a3954c06e882c26fe64ab9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/Platoon/Platoon.jl", "max_forks_repo_name": "JuliaReach/ARCH2021_AFF_RE", "max_forks_repo_head_hexsha": "205737b30c75404c0a3954c06e882c26fe64ab9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3109243697, "max_line_length": 101, "alphanum_fraction": 0.5146396396, "num_tokens": 1987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7510101121087313}}
{"text": "immutable Beta <: ContinuousUnivariateDistribution\n    alpha::Float64\n    beta::Float64\n    function Beta(a::Real, b::Real)\n        (a > zero(a) && b > zero(b)) || error(\"alpha and beta must be positive\")\n        new(float64(a), float64(b))\n    end\nend\n\nBeta(a::Real) = Beta(a, a) # symmetric in [0, 1]\nBeta() = Beta(1.0) # uniform\n\n@_jl_dist_2p Beta beta\n\nfunction entropy(d::Beta)\n    o = lbeta(d.alpha, d.beta)\n    o -= (d.alpha - 1.0) * digamma(d.alpha)\n    o -= (d.beta - 1.0) * digamma(d.beta)\n    o += (d.alpha + d.beta - 2.0) * digamma(d.alpha + d.beta)\n    o\nend\n\nfunction kurtosis(d::Beta)\n    α, β = d.alpha, d.beta\n    num = 6.0 * ((α - β)^2 * (α + β + 1.0) - α * β * (α + β + 2.0))\n    den = α * β * (α + β + 2.0) * (α + β + 3.0)\n    num / den\nend\n\nmean(d::Beta) = d.alpha / (d.alpha + d.beta)\n\nmedian(d::Beta) = quantile(d, 0.5)\n\nfunction mode(d::Beta)\n    α, β = d.alpha, d.beta\n    if α >= 1.0\n        if β > 1.0\n            (α - 1.0) / (α + β - 2.0)\n        elseif α == 1.0 && β == 1.0\n            # Uniform[0,1]: what should be returned?\n            0.5\n        else\n            1.0\n        end\n    else\n        if β >= 1.0\n            0.0\n        else\n            # not unique: return largest\n            α > β ? 1.0 : 0.0\n        end\n    end\nend\n\nfunction modes(d::Beta)\n    α, β = d.alpha, d.beta\n    if α >= 1.0\n        if β > 1.0\n            [(α - 1.0) / (α + β - 2.0)]\n        elseif α == 1.0 && β == 1.0\n            # Uniform[0,1]: what should be returned?\n            Float64[]\n        else\n            [1.0]\n        end\n    else\n        if β >= 1.0\n            [0.0]\n        else\n            [0.0,1.0]\n        end\n    end\nend\n\nfunction skewness(d::Beta)\n    num = 2.0 * (d.beta - d.alpha) * sqrt(d.alpha + d.beta + 1.0)\n    den = (d.alpha + d.beta + 2.0) * sqrt(d.alpha * d.beta)\n    num / den\nend\n\nfunction var(d::Beta)\n    ab = d.alpha + d.beta\n    d.alpha * d.beta / (ab * ab * (ab + 1.0))\nend\n\nfunction gradlogpdf(d::Beta, x::Real)\n  insupport(Beta, x) ? (d.alpha - 1.0) / x - (d.beta - 1.0) / (1 - x) : 0.0\nend\n\n### handling support\n\n@continuous_distr_support Beta 0.0 1.0\n\n## Fit model\n\n# TODO: add MLE method (should be similar to Dirichlet)\n\n# This is a moment-matching method (not MLE)\n#\nfunction fit(::Type{Beta}, x::Array)\n    for xi in x\n        insupport(Beta, xi) || error(\"Beta observations must be in [0,1]\")\n    end\n    x_bar = mean(x)\n    v_bar = varm(x, x_bar)\n    α = x_bar * (((x_bar * (1.0 - x_bar)) / v_bar) - 1.0)\n    β = (1.0 - x_bar) * (((x_bar * (1.0 - x_bar)) / v_bar) - 1.0)\n    Beta(α, β)\nend\n\n\n", "meta": {"hexsha": "3bc2bcd923fdcc2db9efb5f0cd792baa9b6106fd", "size": 2552, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/beta.jl", "max_stars_repo_name": "bicycle1885/Distributions.jl", "max_stars_repo_head_hexsha": "9b897a2865b91f7decb856e1b5a025225c777979", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-08-08T03:44:46.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-08T03:44:46.000Z", "max_issues_repo_path": "src/univariate/beta.jl", "max_issues_repo_name": "bicycle1885/Distributions.jl", "max_issues_repo_head_hexsha": "9b897a2865b91f7decb856e1b5a025225c777979", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/beta.jl", "max_forks_repo_name": "bicycle1885/Distributions.jl", "max_forks_repo_head_hexsha": "9b897a2865b91f7decb856e1b5a025225c777979", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7857142857, "max_line_length": 80, "alphanum_fraction": 0.4902037618, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7509869509452425}}
{"text": "export cycles\n\nfunction _find_cycle(f::DiscreteFunction, s::Int)\n    hits = Set{Int}()\n    push!(hits, s)\n    current = s\n\n    while true\n        current = f(current)\n        if in(current, hits)  # we found a cycle!\n            result = Array{Int,1}()\n            push!(result, current)\n            while true\n                current = f(current)\n                if current == result[1]\n                    return result\n                end\n                push!(result, current)\n            end\n        end\n        push!(hits, current)\n    end\n    error(\"This can't happen\")\nend\n\nfunction _standardize_cycle(c::Array{Int,1})\n    (x,idx) = findmin(c)\n    front = c[idx:end]\n    back  = c[1:idx-1]\n    return vcat(front,back)\nend\n\n\n\"\"\"\n`cycles(f::DiscreteFunction)` returns a list of the cycles in `f`.\n\"\"\"\nfunction cycles(f::DiscreteFunction)::Array{Array{Int,1},1}\n    result = Set{Array{Int,1}}()\n\n    n = length(f)\n    for s=1:n\n        c = _find_cycle(f,s)\n        c = _standardize_cycle(c)\n        push!(result,c)\n    end\n\n    return sort(collect(result))\nend\n", "meta": {"hexsha": "3604ff40822bf76c5e46464a9c594766381415d7", "size": 1066, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cycles.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/DiscreteFunctions.jl-b53ab163-7315-5a32-b7e7-8af45be20176", "max_stars_repo_head_hexsha": "99612254ef1a3b895b7329493aea9a81ea667c42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-09T19:15:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T19:15:23.000Z", "max_issues_repo_path": "src/cycles.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/DiscreteFunctions.jl-b53ab163-7315-5a32-b7e7-8af45be20176", "max_issues_repo_head_hexsha": "99612254ef1a3b895b7329493aea9a81ea667c42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cycles.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/DiscreteFunctions.jl-b53ab163-7315-5a32-b7e7-8af45be20176", "max_forks_repo_head_hexsha": "99612254ef1a3b895b7329493aea9a81ea667c42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:13:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:27:36.000Z", "avg_line_length": 21.7551020408, "max_line_length": 66, "alphanum_fraction": 0.5384615385, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7509869330427589}}
{"text": "julia> function f(n)\n    s = 0.0\n    for k = 1:n\n      s += 1/k^2\n    end\n    return s\nend\n\njulia> f(1000)\n1.6439345666815615\n", "meta": {"hexsha": "763e8c15bbd9662c38eaf6b07bb2a0fd830ebcb3", "size": 126, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/sum-of-a-series-2.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/sum-of-a-series-2.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/sum-of-a-series-2.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.4545454545, "max_line_length": 20, "alphanum_fraction": 0.5396825397, "num_tokens": 58, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7509259989301043}}
{"text": "# functions related to gamma distribution\n\nimport .RFunctions:\n    gammapdf,\n    gammalogpdf,\n    gammacdf,\n    gammaccdf,\n    gammalogcdf,\n    gammalogccdf,\n    gammainvcdf,\n    gammainvccdf,\n    gammainvlogcdf,\n    gammainvlogccdf\n\n# pdf for numbers with generic types\ngammapdf(k::Real, θ::Real, x::Number) = 1 / (gamma(k) * θ^k) * x^(k - 1) * exp(-x / θ)\n\n# logpdf for numbers with generic types\ngammalogpdf(k::Real, θ::Real, x::Number) = -loggamma(k) - k * log(θ) + (k - 1) * log(x) - x / θ\n", "meta": {"hexsha": "26dbef62434c136ae3432548eb2d67703f377934", "size": 495, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distrs/gamma.jl", "max_stars_repo_name": "mileslucas/StatsFuns.jl", "max_stars_repo_head_hexsha": "d99fdf43d40a70ca7a688e11afba1a84963eb396", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distrs/gamma.jl", "max_issues_repo_name": "mileslucas/StatsFuns.jl", "max_issues_repo_head_hexsha": "d99fdf43d40a70ca7a688e11afba1a84963eb396", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distrs/gamma.jl", "max_forks_repo_name": "mileslucas/StatsFuns.jl", "max_forks_repo_head_hexsha": "d99fdf43d40a70ca7a688e11afba1a84963eb396", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.75, "max_line_length": 95, "alphanum_fraction": 0.6363636364, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897525789547, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7509259411414514}}
{"text": "using Revise\nusing PortfolioBedtest\nimport PortfolioBedtest: order, execute\nusing Dates\nusing Statistics\nusing Setfield\nusing Convex, SCS # It can be simplifed, but existing solutions are fine\n\n########################################\n# Auxiliary functions\n########################################\nfunction get_optim_weights(w, risk, ret, λ)\n    p = minimize(λ * risk - (1 - λ) * ret,\n                 sum(w) == 1,\n                 0.0 <= w,\n                 w <= 1.0)\n    solve!(p, () -> SCS.Optimizer(verbose = false))\n    \n    return sqrt(evaluate(risk)), evaluate(w)\nend\n\nfunction find_weights(M, r, risk0, tol = 1e-8)\n    w = Variable(length(r))\n    risk = quadform(w, M)\n    ret = dot(w, r)\n    l1 = 0.01\n    risk1, _ = get_optim_weights(w, risk, ret, l1)\n    l2 = 0.99\n    risk2, _ = get_optim_weights(w, risk, ret, l2)\n    l3 = (l1 + l2)/2\n    risk3, _ = get_optim_weights(w, risk, ret, l3)\n    while abs(l1 - l2) > tol\n        if risk1 >= risk0 >= risk3\n            l2 = l3\n        else\n            l1 = l3\n        end\n        l3 = (l1 + l2) / 2\n        risk3, _ = get_optim_weights(w, risk, ret, l3)\n    end\n    risk3, w3 = get_optim_weights(w, risk, ret, l3)\n\n    return risk3, w3\nend\n\nfunction build(assts, rng, risk = 0.1)\n    # not very efficient, but ok\n    wnd = assts[rng]\n    wnd2 = wnd[2:end] ./ wnd[1:end - 1]\n    ret = exp.((252 * mean(map.(log, wnd2))).event) .- 1\n    # It can be done in row-wise format, but optimization is not important here\n    # So we transform data to column-wise matrix\n    M = 252 .* cov(hcat(map(i -> getindex.(getfield.(wnd2, :event), i), 1:length(ret))...))\n    _, w = find_weights(M, ret, risk)\n\n    return w\nend\n\nfunction create_signal(assts, risk = 0.1, period = 36)\n    indx = filter_eom_indices(assts)\n    w = build(assts, indx[1]:indx[period+1], risk)\n    w2 = tuple(w...)\n    res = [TimedEvent(assts[indx[period + 1]].ts, w2)]\n    for i in period+2:length(indx)\n        w = build(assts, indx[i - period]:indx[i], risk)\n        w2 = tuple(w...)\n        push!(res, TimedEvent(assts[indx[i]].ts, w2))\n    end\n    Signal(res)\nend\n\n########################################\n# Simulation auxiliary structures\n########################################\nstruct RatioStrategy end\n\nstruct Order{T} <: AbstractOrder\n    shares::T\nend\n\nfunction order(strat::RatioStrategy, broker, signal, prices)\n    a = assets(broker, prices)\n    ntuple(length(signal)) do i\n        floor(Int, a * signal[i] / prices[i])\n    end |> Order\nend\n\nfunction execute(broker, ord::Order, prices)\n    a = assets(broker, prices)\n    for i in 1:length(ord.shares)\n        a -= ord.shares[i] * prices[i]\n    end\n    Broker(a, ord.shares)\nend\n\n########################################\n# Calculations\n########################################\n\n# ETF\nspyts = yahoo(\"SPY\") |> x -> map(x -> TimedEvent(x.Date, getproperty(x, Symbol(\"Adj Close\"))), x);\naggts = yahoo(\"AGG\") |> x -> map(x -> TimedEvent(x.Date, getproperty(x, Symbol(\"Adj Close\"))), x);\ngldts = yahoo(\"GLD\") |> x -> map(x -> TimedEvent(x.Date, getproperty(x, Symbol(\"Adj Close\"))), x);\n\nassts = glue(spyts, aggts, gldts) do v1, v2, k\n    k == 0 && return (v1..., v2...)\n    k == 1 && return (v1..., map(_ -> NaN, v2)...)\n    return (map(_ -> NaN, v1)..., v2...)\nend\n\nassts = filter(x -> !any(isnan.(x.event)), assts)\nsignal = create_signal(assts)\nbroker = Broker(1_000_000.0, ntuple(_ -> 0, length(assts[1].event)))\nstrat = RatioStrategy()\nrecorder = Recorder{Date, typeof((; shares = broker.shares, total = 0.0))}([])\n\nsim(broker, strat, assts, signal, recorder)\n\n########################################\n# Volatility 7.5%\n########################################\nvol75_signal = create_signal(assts, 0.075)\nvol75_recorder = Recorder{Date, typeof((; shares = broker.shares, total = 0.0))}([])\n\nsim(broker, strat, assts, vol75_signal, vol75_recorder)\n\n########################################\n# 60/40 comparison\n########################################\n\nsfsignal = Signal(mutate.(_ -> (0.6, 0.4, 0.0), signal.signal))\nsfrecorder = Recorder{Date, typeof((; shares = broker.shares, total = 0.0))}([])\n\nsim(broker, strat, assts, sfsignal, sfrecorder)\n\n########################################\n# Pure SPY\n########################################\nspysignal = Signal(mutate.(_ -> (1.0, 0.0, 0.0), signal.signal))\nspyrecorder = Recorder{Date, typeof((; shares = broker.shares, total = 0.0))}([])\n\nsim(broker, strat, assts, spysignal, spyrecorder)\n\n########################################\n# Plotting\n########################################\nusing Plots\ntsts = getfield.(signal.signal, :ts)\nplot(tsts, getfield.(mutate.(x -> x[1], signal.signal), :event), legend = :outerright, label = \"SPY\")\nplot!(tsts, getfield.(mutate.(x -> x[2], signal.signal), :event), label = \"AGG\")\nplot!(tsts, getfield.(mutate.(x -> x[3], signal.signal), :event), label = \"GLD\")\n\n\n# Equities\nequity_curve = mutate.(x -> x.total, recorder.data)\nplot(getfield.(equity_curve, :ts), getfield.(equity_curve, :event), legend = :topleft, label = \"10% volatilty rebalance\", linewidth = 0.5)\n\nsfequity_curve = mutate.(x -> x.total, sfrecorder.data)\nplot!(getfield.(sfequity_curve, :ts), getfield.(sfequity_curve, :event), label = \"60/40 SPY/AGG\", linewidth = 0.5)\n\nspyequity_curve = mutate.(x -> x.total, spyrecorder.data)\nplot!(getfield.(spyequity_curve, :ts), getfield.(spyequity_curve, :event), label = \"100% SPY\", linewidth = 0.5)\n\nvol75_equity_curve = mutate.(x -> x.total, vol75_recorder.data)\nplot!(getfield.(vol75_equity_curve, :ts), getfield.(vol75_equity_curve, :event))\n\n########################################\n# Volatility spectre\n########################################\nfunction build_vol_plot(assts, rng)\n    isfirst = true\n    broker = Broker(1_000_000.0, ntuple(_ -> 0, length(assts[1].event)))\n    strat = RatioStrategy()\n    recorder = Recorder{Date, typeof((; shares = broker.shares, total = 0.0))}([])\n    local g\n    for vol in rng\n        signal = create_signal(assts, vol)\n        sim(broker, strat, assts, signal, recorder)\n        equity_curve = mutate.(x -> x.total, recorder.data)\n        g = if isfirst\n            isfirst = false\n            plot(getfield.(equity_curve, :ts), getfield.(equity_curve, :event), legend = :topleft, label = \"Risk: $vol\")\n        else\n            plot!(getfield.(equity_curve, :ts), getfield.(equity_curve, :event), label = \"Risk: $vol\")\n        end\n    end\n\n    return g\nend\n\nbuild_vol_plot(assts, 0.06:0.02:0.12)\n\n########################################\n# Sliding window spectre\n########################################\n\nfunction build_win_plot(assts, rng, risk = 0.1)\n    isfirst = true\n    broker = Broker(1_000_000.0, ntuple(_ -> 0, length(assts[1].event)))\n    strat = RatioStrategy()\n    recorder = Recorder{Date, typeof((; shares = broker.shares, total = 0.0))}([])\n    local g\n    for wnd in rng\n        signal = create_signal(assts, risk, wnd)\n        sim(broker, strat, assts, signal, recorder)\n        equity_curve = mutate.(x -> x.total, recorder.data)\n        g = if isfirst\n            isfirst = false\n            plot(getfield.(equity_curve, :ts), getfield.(equity_curve, :event), legend = :topleft, label = \"Window: $wnd\", linewidth = 0.5)\n        else\n            plot!(getfield.(equity_curve, :ts), getfield.(equity_curve, :event), label = \"Window: $wnd\", linewidth = 0.5)\n        end\n    end\n\n    return g\nend\n\nbuild_win_plot(assts, 12:6:48)\nbuild_win_plot(assts, 20:2:28)\nbuild_win_plot(assts, 20:2:28, 0.12)\n", "meta": {"hexsha": "8a99965e52b6d1e4dda9f37555117e5f9331932f", "size": 7422, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/03_VOL10/plain_julia.jl", "max_stars_repo_name": "Arkoniak/PortfolioBedtest.jl", "max_stars_repo_head_hexsha": "40f61d3ab0ca94664a179929b418cfabeb161bb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/03_VOL10/plain_julia.jl", "max_issues_repo_name": "Arkoniak/PortfolioBedtest.jl", "max_issues_repo_head_hexsha": "40f61d3ab0ca94664a179929b418cfabeb161bb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/03_VOL10/plain_julia.jl", "max_forks_repo_name": "Arkoniak/PortfolioBedtest.jl", "max_forks_repo_head_hexsha": "40f61d3ab0ca94664a179929b418cfabeb161bb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5837104072, "max_line_length": 139, "alphanum_fraction": 0.5649420641, "num_tokens": 2211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897558991952, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7509259392751773}}
{"text": "export get_discrete_Grad\n\n\"\"\"\n2D version\n input:\n# Arguments\n - n1 : number of grid points in the first dimension\n - n2 : number of grid points in the second dimension\n - h1 : distance between grid points in the first dimension\n - h2 : distance between grid points in the second dimension\n - TD_type : type of derivative operator as a string\n\n output :\n - TD_OP : transform domain operator as a sparse matrix\n\"\"\"\nfunction get_discrete_Grad(n1,n2,h1::TF,h2::TF,TD_type::String) where {TF<:Real}\n    TI=Int64\n\n    #define difference matrix D acting on vectorized model using Kronecker products\n    Ix = SparseMatrixCSC{TF}(LinearAlgebra.I,n1,n1) #x\n    Iz = SparseMatrixCSC{TF}(LinearAlgebra.I,n2,n2) #z\n    Dx = spdiagm(0 => ones(TF,n1-1)*-1, 1 => ones(TF,n1-1)*1); Dx = Dx[1:end-1,:] ./ h1\n    Dz = spdiagm(0 => ones(TF,n2-1)*-1, 1 => ones(TF,n2-1)*1); Dz = Dz[1:end-1,:] ./ h2\n\n\n    if TD_type==\"D_z\"\n      D_OP = kron(Dz,Ix) #D2z\n    elseif TD_type==\"D_x\"\n      D_OP = kron(Iz,Dx) #D2x\n    elseif  TD_type==\"TV\" || TD_type==\"D2D\"\n      D2z  = kron(Dz,Ix)\n      D2x  = kron(Iz,Dx)\n      D_OP = vcat(D2z,D2x) #D2D\n    end\n      \n    return D_OP\nend\n\n\n\"\"\"\n  3D version\n  input: n1 : number of grid points in the first dimension\n         n2 : number of grid points in the second dimension\n         n3 : number of grid points in the third dimension\n         h1 : distance between grid points in the first dimension\n         h2 : distance between grid points in the second dimension\n         h3 : distance between grid points in the third dimension\n         TD_type : type of derivative operator as a string\n   output : TD_OP : transform domain operator as a sparse matrix\n\"\"\"\nfunction get_discrete_Grad(n1,n2,n3,h1::TF,h2::TF,h3::TF,TD_type::String) where {TF<:Real}\n    TI = Int64\n\n    #define difference matrix D acting on vectorized model using Kronecker products\n    Ix = SparseMatrixCSC{TF}(LinearAlgebra.I,n1,n1) #x\n    Iy = SparseMatrixCSC{TF}(LinearAlgebra.I,n2,n2) #x\n    Iz = SparseMatrixCSC{TF}(LinearAlgebra.I,n3,n3) #z\n    Dx = spdiagm(0 => ones(TF,n1-1)*-1, 1 => ones(TF,n1-1)*1); Dx = Dx[1:end-1,:] ./ h1\n    Dy = spdiagm(0 => ones(TF,n2-1)*-1, 1 => ones(TF,n2-1)*1); Dy = Dy[1:end-1,:] ./ h2\n    Dz = spdiagm(0 => ones(TF,n3-1)*-1, 1 => ones(TF,n3-1)*1); Dz = Dz[1:end-1,:] ./ h3\n\n    if TD_type==\"D_z\"\n      D_OP = kron(Dz,Iy,Ix)\n    elseif TD_type==\"D_y\"\n      D_OP = kron(Iz,Dy,Ix)\n    elseif TD_type==\"D_x\"\n      D_OP = kron(Iz,Iy,Dx)\n    elseif TD_type==\"TV\" || TD_type==\"D3D\"\n      D3z = kron(Dz,Iy,Ix)\n      D3y = kron(Iz,Dy,Ix)\n      D3x = kron(Iz,Iy,Dx)\n      D_OP = vcat(D3z,D3y,D3x)\n    end\n\n    return D_OP\nend\n", "meta": {"hexsha": "cdfec7615db271868c616bf36799eac16774aed6", "size": 2636, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/get_discrete_Grad.jl", "max_stars_repo_name": "slimgroup/SetIntersectionProjection", "max_stars_repo_head_hexsha": "d7dd8cf018bb960fa626e761e62b865e2725b466", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/get_discrete_Grad.jl", "max_issues_repo_name": "slimgroup/SetIntersectionProjection", "max_issues_repo_head_hexsha": "d7dd8cf018bb960fa626e761e62b865e2725b466", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/get_discrete_Grad.jl", "max_forks_repo_name": "slimgroup/SetIntersectionProjection", "max_forks_repo_head_hexsha": "d7dd8cf018bb960fa626e761e62b865e2725b466", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2337662338, "max_line_length": 90, "alphanum_fraction": 0.6320182094, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7509259358411068}}
{"text": "import NearlyNewton: minimize!\nfunction theta(x)\n    if x[1] > 0\n        return atan(x[2] / x[1]) / (2.0 * pi)\n    else\n        return (pi + atan(x[2] / x[1])) / (2.0 * pi)\n    end\nend\n\nfunction fletcher_powell_fg!(∇f, x)\n    theta_x = theta(x)\n\n    if !(∇f==nothing)\n        if ( x[1]^2 + x[2]^2 == 0 )\n            dtdx1 = 0;\n            dtdx2 = 0;\n        else\n            dtdx1 = - x[2] / ( 2 * pi * ( x[1]^2 + x[2]^2 ) );\n            dtdx2 =   x[1] / ( 2 * pi * ( x[1]^2 + x[2]^2 ) );\n        end\n        ∇f[1] = -2000.0*(x[3]-10.0*theta_x)*dtdx1 +\n            200.0*(sqrt(x[1]^2+x[2]^2)-1)*x[1]/sqrt( x[1]^2+x[2]^2 );\n        ∇f[2] = -2000.0*(x[3]-10.0*theta_x)*dtdx2 +\n            200.0*(sqrt(x[1]^2+x[2]^2)-1)*x[2]/sqrt( x[1]^2+x[2]^2 );\n        ∇f[3] =  200.0*(x[3]-10.0*theta_x) + 2.0*x[3];\n    end\n\n    fx = 100.0 * ((x[3] - 10.0 * theta_x)^2 + (sqrt(x[1]^2 + x[2]^2) - 1.0)^2) + x[3]^2\n\n    return fx\nend\n\ntp_fletch_powell_fg! = TestProblem(fletcher_powell_fg!, [-1.0, 0.0, 0.0], I, NearlyNewton.OptOptions())\ntp_fletch_powell_fg!_alt = TestProblem(fletcher_powell_fg!, [-0.5, 0.0, 0.0], I, NearlyNewton.OptOptions())\n\nminimize!(tp_fletch_powell_fg!, BFGS(InverseApprox()))\nminimize!(tp_fletch_powell_fg!, BFGS(DirectApprox()))\n\nminimize!(tp_fletch_powell_fg!, SR1(InverseApprox()))\nminimize!(tp_fletch_powell_fg!, SR1(DirectApprox()))\n\nminimize!(tp_fletch_powell_fg!, DFP(InverseApprox()))\nminimize!(tp_fletch_powell_fg!, DFP(DirectApprox()))\n\nminimize!(tp_fletch_powell_fg!_alt, BFGS(InverseApprox()))\nminimize!(tp_fletch_powell_fg!_alt, BFGS(DirectApprox()))\n\nminimize!(tp_fletch_powell_fg!_alt, SR1(InverseApprox()))\nminimize!(tp_fletch_powell_fg!_alt, SR1(DirectApprox()))\n\nminimize!(tp_fletch_powell_fg!_alt, DFP(InverseApprox()))\nminimize!(tp_fletch_powell_fg!_alt, DFP(DirectApprox()))\n", "meta": {"hexsha": "6c1a37c7658cc94371f683c97de08b2aec12df91", "size": 1805, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testproblems/fletcher_powell.jl", "max_stars_repo_name": "pkofod/NearlyNewton.jl", "max_stars_repo_head_hexsha": "f9f0f80f3b5e89dc3c56af838e338c9d77d8356a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/testproblems/fletcher_powell.jl", "max_issues_repo_name": "pkofod/NearlyNewton.jl", "max_issues_repo_head_hexsha": "f9f0f80f3b5e89dc3c56af838e338c9d77d8356a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/testproblems/fletcher_powell.jl", "max_forks_repo_name": "pkofod/NearlyNewton.jl", "max_forks_repo_head_hexsha": "f9f0f80f3b5e89dc3c56af838e338c9d77d8356a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0566037736, "max_line_length": 107, "alphanum_fraction": 0.5944598338, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.750925933433645}}
{"text": "module Metropolis\n\nexport metropolis, metropolis_uniform\n\nusing Distributions\n\n\"\"\"\nGenerate a series of random samples from a given probability distribution\nusing the metropolis algorithm\n\n# Arguments\n- `distribution`: the target probability distribution\n- `step`: the probability distribution of the steps\n- `samples`: the number of samples\n- `init`: the initial value of the series (starting point of the \"walker\")\n\n# Returns\n\nthe series of randome samples from the distribution and the acceptance rate\n\"\"\"\nfunction metropolis(distribution::Function, step::Function, samples::Integer;\n        init::Real=0.0)\n    series = Vector{Float64}(undef, samples)\n\n    position = init\n    probability = distribution(position)\n    series[1] = position\n\n    acceptcount = 0\n    for i in 2:samples\n        newposition = position + step(position)\n        newprobablity = distribution(newposition)\n\n        if newprobablity / probability > 1 || rand() <= newprobablity / probability\n            position, probability = newposition, newprobablity\n            acceptcount += 1\n        end\n\n        series[i] = position\n    end\n\n    return series, acceptcount / (samples - 1)\nend\n\n\"\"\"\nMetropolis algorithm with uniform step probability between `-stepsize` and `+stepsize`\n\"\"\"\nfunction metropolis_uniform(distribution::Function, stepsize::Real, samples::Integer;\n        init::Real=0.0)\n    return metropolis(distribution, x -> rand(Uniform(-stepsize, stepsize)), samples,\n        init=init)\nend\n\nend\n", "meta": {"hexsha": "80f3d21cdf813e47759ff6fd0ca68d6ab60c4514", "size": 1484, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ps7-integration-metropolis/p3-metropolis-algorithm/Metropolis.jl", "max_stars_repo_name": "slhshamloo/comp-phys", "max_stars_repo_head_hexsha": "04d6759e0eb9d7e16e2781417d389bc15e22b01b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ps7-integration-metropolis/p3-metropolis-algorithm/Metropolis.jl", "max_issues_repo_name": "slhshamloo/comp-phys", "max_issues_repo_head_hexsha": "04d6759e0eb9d7e16e2781417d389bc15e22b01b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ps7-integration-metropolis/p3-metropolis-algorithm/Metropolis.jl", "max_forks_repo_name": "slhshamloo/comp-phys", "max_forks_repo_head_hexsha": "04d6759e0eb9d7e16e2781417d389bc15e22b01b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9818181818, "max_line_length": 86, "alphanum_fraction": 0.7088948787, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7507667081782323}}
{"text": "\nfunction rk4(f, t, y, dt, P, k)\n    k1 = f(t, y, P)\n    k2 = f(t + 1/2*dt, y + 1/2*dt*k1, P)\n    k3 = f(t + 1/2*dt, y + 1/2*dt*k2, P)\n    k4 = f(t + dt, y + dt*k3, P)\n    y + dt*(k1+2*k2+2*k3+k4)/6\nend\n\nstruct Rk4 <: ODESolverType end\n\n#=\n        FOUR components\n=#\nfunction update(::Rk4, fs, t, A, B, C, D, dt, P, tableau=NaN)\n    kA1 = update(fs[1], t, A, B, C, D, P)\n    kB1 = update(fs[2], t, A, B, C, D, P)\n    kC1 = update(fs[3], t, A, B, C, D, P)\n    kD1 = update(fs[4], t, A, B, C, D, P)\n\n    Ai = A + 1/2*dt*kA1\n    Bi = B + 1/2*dt*kB1\n    Ci = C + 1/2*dt*kC1\n    Di = D + 1/2*dt*kD1\n\n    kA2 = update(fs[1], t + 1/2*dt, Ai, Bi, Ci, Di, P)\n    kB2 = update(fs[2], t + 1/2*dt, Ai, Bi, Ci, Di, P)\n    kC2 = update(fs[3], t + 1/2*dt, Ai, Bi, Ci, Di, P)\n    kD2 = update(fs[4], t + 1/2*dt, Ai, Bi, Ci, Di, P)\n\n    Ai = A + 1/2*dt*kA2\n    Bi = B + 1/2*dt*kB2\n    Ci = C + 1/2*dt*kC2\n    Di = D + 1/2*dt*kD2\n\n    kA3 = update(fs[1], t + 1/2*dt, Ai, Bi, Ci, Di, P)\n    kB3 = update(fs[2], t + 1/2*dt, Ai, Bi, Ci, Di, P)\n    kC3 = update(fs[3], t + 1/2*dt, Ai, Bi, Ci, Di, P)\n    kD3 = update(fs[4], t + 1/2*dt, Ai, Bi, Ci, Di, P)\n\n    Ai = A + dt*kA3\n    Bi = B + dt*kB3\n    Ci = C + dt*kC3\n    Di = D + dt*kD3\n\n    kA4 = update(fs[1], t + dt, Ai, Bi, Ci, Di, P)\n    kB4 = update(fs[2], t + dt, Ai, Bi, Ci, Di, P)\n    kC4 = update(fs[3], t + dt, Ai, Bi, Ci, Di, P)\n    kD4 = update(fs[4], t + dt, Ai, Bi, Ci, Di, P)\n\n    (A + dt*(kA1 + 2*kA2 + 2*kA3 + kA4)/6, B + dt*(kB1 + 2*kB2 + 2*kB3 + kB4)/6,\n     C + dt*(kC1 + 2*kC2 + 2*kC3 + kC4)/6, D + dt*(kD1 + 2*kD2 + 2*kD3 + kD4)/6)\nend\n\n#=\n        THREE components\n=#\nfunction update(::Rk4, fs, t, A, B, C, dt, P, tableau=NaN)\n    kA1 = update(fs[1], t, A, B, C, P)\n    kB1 = update(fs[2], t, A, B, C, P)\n    kC1 = update(fs[3], t, A, B, C, P)\n\n    Ai = A + 1/2*dt*kA1\n    Bi = B + 1/2*dt*kB1\n    Ci = C + 1/2*dt*kC1\n\n    kA2 = update(fs[1], t + 1/2*dt, Ai, Bi, Ci, P)\n    kB2 = update(fs[2], t + 1/2*dt, Ai, Bi, Ci, P)\n    kC2 = update(fs[3], t + 1/2*dt, Ai, Bi, Ci, P)\n\n    Ai = A + 1/2*dt*kA2\n    Bi = B + 1/2*dt*kB2\n    Ci = C + 1/2*dt*kC2\n\n    kA3 = update(fs[1], t + 1/2*dt, Ai, Bi, Ci, P)\n    kB3 = update(fs[2], t + 1/2*dt, Ai, Bi, Ci, P)\n    kC3 = update(fs[3], t + 1/2*dt, Ai, Bi, Ci, P)\n\n    Ai = A + dt*kA3\n    Bi = B + dt*kB3\n    Ci = C + dt*kC3\n\n    kA4 = update(fs[1], t + dt, Ai, Bi, Ci, P)\n    kB4 = update(fs[2], t + dt, Ai, Bi, Ci, P)\n    kC4 = update(fs[3], t + dt, Ai, Bi, Ci, P)\n\n    (A + dt*(kA1 + 2*kA2 + 2*kA3 + kA4)/6, B + dt*(kB1 + 2*kB2 + 2*kB3 + kB4)/6,\n     C + dt*(kC1 + 2*kC2 + 2*kC3 + kC4)/6)\nend\n\n\n#=\n        TWO components\n=#\nfunction update(::Rk4, fs, t, A, B, dt, P, tableau=NaN)\n    kA1 = update(fs[1], t, A, B, P)\n    kB1 = update(fs[2], t, A, B, P)\n\n    Ai = A + 1/2*dt*kA1\n    Bi = B + 1/2*dt*kB1\n\n    kA2 = update(fs[1], t + 1/2*dt, Ai, Bi, P)\n    kB2 = update(fs[2], t + 1/2*dt, Ai, Bi, P)\n\n    Ai = A + 1/2*dt*kA2\n    Bi = B + 1/2*dt*kB2\n\n    kA3 = update(fs[1], t + 1/2*dt, Ai, Bi, P)\n    kB3 = update(fs[2], t + 1/2*dt, Ai, Bi, P)\n\n    Ai = A + dt*kA3\n    Bi = B + dt*kB3\n\n    kA4 = update(fs[1], t + dt, Ai, Bi, P)\n    kB4 = update(fs[2], t + dt, Ai, Bi, P)\n\n    (A + dt*(kA1 + 2*kA2 + 2*kA3 + kA4)/6, B + dt*(kB1 + 2*kB2 + 2*kB3 + kB4)/6)\nend\n", "meta": {"hexsha": "1aa1396e5413c65f8bdd746d127c0363814f4579", "size": 3241, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rk4.jl", "max_stars_repo_name": "mschauer/BridgeSDEInference.jl", "max_stars_repo_head_hexsha": "a5859fb56fb03c665f9f925dc8b3fd6003773ae3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rk4.jl", "max_issues_repo_name": "mschauer/BridgeSDEInference.jl", "max_issues_repo_head_hexsha": "a5859fb56fb03c665f9f925dc8b3fd6003773ae3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rk4.jl", "max_forks_repo_name": "mschauer/BridgeSDEInference.jl", "max_forks_repo_head_hexsha": "a5859fb56fb03c665f9f925dc8b3fd6003773ae3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2352941176, "max_line_length": 80, "alphanum_fraction": 0.4566491824, "num_tokens": 1660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7507667008967215}}
{"text": "\"\"\"\nMLEPoisson(data::AbstractVector)\nMLEPoisson estimates intensity of homogenous poisson process. Homogenous poisson process has one independent prameter, intensity $\\lambda$, and the result of maximum likelihood shows following relationship\n$$\n\\lambda = E[t_{i}-t_{i-1}].\n$$\n\"\"\"\n\nfunction MLEPoisson(x::AbstractVector;data::AbstractVector = x)\n    mu = diff(x)\n    return 1/mean(mu)\nend", "meta": {"hexsha": "b012a7feae2490d8e87803ec0e222550a9ae4d58", "size": 388, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Likelihood/MLEPoisson.jl", "max_stars_repo_name": "yukki-jpn/JuliaTSA", "max_stars_repo_head_hexsha": "ee6a65b5854be4eb33690c6ff509ae7954cdad3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Likelihood/MLEPoisson.jl", "max_issues_repo_name": "yukki-jpn/JuliaTSA", "max_issues_repo_head_hexsha": "ee6a65b5854be4eb33690c6ff509ae7954cdad3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Likelihood/MLEPoisson.jl", "max_forks_repo_name": "yukki-jpn/JuliaTSA", "max_forks_repo_head_hexsha": "ee6a65b5854be4eb33690c6ff509ae7954cdad3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3333333333, "max_line_length": 205, "alphanum_fraction": 0.7525773196, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966732132747, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7507514548965302}}
{"text": "using LinearAlgebra\n\nA = [1 2 3; 4 5 6; 7 8 9]\n\nfor t in [\nSymmetric\nHermitian\nUpperTriangular\nLowerTriangular\nTridiagonal\nDiagonal\n]\n    show(stdout, MIME(\"text/plain\"), t(A))\n    println()\nend\n\nA = [1, 2, 3]\nB = [5, 6]\nfor t in [\nSymTridiagonal\n]\n    show(stdout, MIME(\"text/plain\"), t(A, B))\n    println()\nend\n\nA = [1, 2, 3]\nB = [5, 6]\nfor t in [\nBidiagonal\n]\n    show(stdout, MIME(\"text/plain\"), t(A, B, :U))\n    println()\n    show(stdout, MIME(\"text/plain\"), t(A, B, :L))\n    println()\nend\n\nfor t in [\nUniformScaling\n]\n    println(t(2))\nend\n\n\n#=\n3×3 Symmetric{Int64,Array{Int64,2}}:\n 1  2  3\n 2  5  6\n 3  6  9\n3×3 Hermitian{Int64,Array{Int64,2}}:\n 1  2  3\n 2  5  6\n 3  6  9\n3×3 UpperTriangular{Int64,Array{Int64,2}}:\n 1  2  3\n ⋅  5  6\n ⋅  ⋅  9\n3×3 LowerTriangular{Int64,Array{Int64,2}}:\n 1  ⋅  ⋅\n 4  5  ⋅\n 7  8  9\n3×3 Tridiagonal{Int64,Array{Int64,1}}:\n 1  2  ⋅\n 4  5  6\n ⋅  8  9\n3×3 Diagonal{Int64,Array{Int64,1}}:\n 1  ⋅  ⋅\n ⋅  5  ⋅\n ⋅  ⋅  9\n3×3 SymTridiagonal{Int64,Array{Int64,1}}:\n 1  5  ⋅\n 5  2  6\n ⋅  6  3\n3×3 Bidiagonal{Int64,Array{Int64,1}}:\n 1  5  ⋅\n ⋅  2  6\n ⋅  ⋅  3\n3×3 Bidiagonal{Int64,Array{Int64,1}}:\n 1  ⋅  ⋅\n 5  2  ⋅\n ⋅  6  3\nUniformScaling{Int64}\n2*I\n=#\n", "meta": {"hexsha": "0cfcb84b09ec787d136217a4b4264d5d3098eb69", "size": 1176, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/linalg.jl", "max_stars_repo_name": "wookay/TestJulia07.jl", "max_stars_repo_head_hexsha": "17f139763d96e456fdb4b59fbb7964273523cb00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/linalg.jl", "max_issues_repo_name": "wookay/TestJulia07.jl", "max_issues_repo_head_hexsha": "17f139763d96e456fdb4b59fbb7964273523cb00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/linalg.jl", "max_forks_repo_name": "wookay/TestJulia07.jl", "max_forks_repo_head_hexsha": "17f139763d96e456fdb4b59fbb7964273523cb00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.0, "max_line_length": 49, "alphanum_fraction": 0.5663265306, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7507496326568238}}
{"text": "\"\"\"\nA reservoir Outlet should always have the following:\n    - An elevation field z\n    - A discharge function.\n\nThe discharge function depends on the hydralic head measured from the elevation\nof the outlet (z) to the reservoir water surface.\n\"\"\"\n\nabstract type Outlet end\n\ndischarge(o::Outlet; z) = z > o.z ? discharge(o, z - o.z) : 0.0\n\ndischarge(o::Outlet, h) =\n    error(\"Please implement a discharge function for type \", typeof(o))\n\nBase.@kwdef struct Orifice <: Outlet\n    C::Float64\n    A::Float64\n    z::Float64\n    g::Float64 = 9.81\nend\n\ndischarge(o::Orifice, h) = o.C * o.A * √(2.0 * o.g * h)\n\nBase.@kwdef struct Weir <: Outlet\n    C::Float64\n    B::Float64\n    z::Float64\nend\n\ndischarge(o::Weir, h) = o.C * o.B * h^1.5\n", "meta": {"hexsha": "cb938ad3411f691090acc14fc7c0ef45b426b828", "size": 730, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/outlet.jl", "max_stars_repo_name": "dact221/WaterReservoir.jl", "max_stars_repo_head_hexsha": "802416db99c867eddac4cfdce0bf5db6f07ebaf1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/outlet.jl", "max_issues_repo_name": "dact221/WaterReservoir.jl", "max_issues_repo_head_hexsha": "802416db99c867eddac4cfdce0bf5db6f07ebaf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/outlet.jl", "max_forks_repo_name": "dact221/WaterReservoir.jl", "max_forks_repo_head_hexsha": "802416db99c867eddac4cfdce0bf5db6f07ebaf1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1212121212, "max_line_length": 79, "alphanum_fraction": 0.6534246575, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7507496251186901}}
{"text": "module ContinuedFractions\n\nimport Base: start, done, next, length, eltype, collect\n\nexport ContinuedFraction, quotients, convergents, ConvergentIterator\n\nimmutable ContinuedFraction{T<:Integer}\n\tquotients::Vector{T}\nend\n\nquotients(cf::ContinuedFraction) = cf.quotients\n\nimmutable ConvergentIterator{T<:Integer}\n    qs::Vector{T}\nend\n\nstart(::ConvergentIterator) = 1\ndone(it::ConvergentIterator, state::Int) = state > length(it.qs)\nlength(it::ConvergentIterator) = length(it.qs)\n\nfunction next(it::ConvergentIterator, state::Int)\n    convergent = Rational(ContinuedFraction(it.qs[1:state]))\n    convergent, state + 1\nend\n\neltype(it::ConvergentIterator) = Rational{eltype(it.qs)}\ncollect(it::ConvergentIterator) = collect(eltype(it), it)\n\nconvergents(cf::ContinuedFraction) = convergents(quotients(cf))\nconvergents{T<:Integer}(qs::Vector{T}) = ConvergentIterator(qs)\n\nfunction Base.Rational(cf::ContinuedFraction)\n    qs = quotients(cf)\n    isempty(qs) && return 0 // 1\n    length(qs) == 1 && return qs[1] // 1\n\n    remainder = qs[2:end]\n    rat = Rational(ContinuedFraction(remainder))\n    (qs[1] * rat.num + rat.den) // rat.num\nend\n\nfunction ContinuedFraction{T<:Integer}(rat::Rational{T})\n    a = div(rat.num, rat.den)\n    a * rat.den == rat.num && return ContinuedFraction(T[a])  # Exact!\n\n    cf = ContinuedFraction(rat.den//(rat.num - a*rat.den))\n    unshift!(quotients(cf), a) # insert at index 1\n    cf\nend\n\n# let rationalize handle conversion from floating point\nContinuedFraction(x::BigFloat) = ContinuedFraction(rationalize(BigInt, x))\nContinuedFraction(x::AbstractFloat) = ContinuedFraction(rationalize(x))\n\nContinuedFraction(x::Integer) = ContinuedFraction([x])\n\nend # module ContinuedFractions\n", "meta": {"hexsha": "c571ffc8fbddd5af6f483584fc31c12eee1d901e", "size": 1706, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ContinuedFractions.jl", "max_stars_repo_name": "JuliaPackageMirrors/ContinuedFractions.jl", "max_stars_repo_head_hexsha": "912fcd1a89ee901c49d03eacb793774d4c36a735", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ContinuedFractions.jl", "max_issues_repo_name": "JuliaPackageMirrors/ContinuedFractions.jl", "max_issues_repo_head_hexsha": "912fcd1a89ee901c49d03eacb793774d4c36a735", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ContinuedFractions.jl", "max_forks_repo_name": "JuliaPackageMirrors/ContinuedFractions.jl", "max_forks_repo_head_hexsha": "912fcd1a89ee901c49d03eacb793774d4c36a735", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4137931034, "max_line_length": 74, "alphanum_fraction": 0.7309495897, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.750749420701646}}
{"text": "module PDE\n\nusing GPUBenchmarks, BenchmarkTools, Primes\n\ndescription = \"\"\"\nKuramoto-Sivashinsky algorithm benchmark ([original benchmark](https://github.com/johnfgibson/julia-pde-benchmark/blob/master/1-Kuramoto-Sivashinksy-benchmark.ipynb)).\n\nThis benchmark is dominated by the cost of the FFT, leading to worse results for OpenCL with\nCLFFT compared to the faster CUFFT.\nSimilarly the multithreaded backend doesn't improve much over base with the same FFT implementation.\nResult of the benchmarked PDE:\n![](https://github.com/JuliaGPU/GPUBenchmarks.jl/blob/master/results/plots/pde_result.png?raw=true)\n\"\"\"\n\n\nsq3(x) = Complex64(x * x * x) # cudanative doesn't like Complex64 directly broadcasted.\n\n# source: http://nbviewer.jupyter.org/url/homepages.warwick.ac.uk/staff/C.Ortner/julia/PlaneWaves.ipynb\n# an optimised implementation of CH_vectorised!\n\nfunction inner_loop(\n        nruns,\n        planv, planw, planwi, u0, u, v, w, Â,\n        c1, c2, c3, c4\n    )\n    u .= identity.(u0)\n    w .= tocomplex64.(u0)\n    for n = 1:nruns\n        v .= sq3.(u)\n        planv * v\n        planw * w\n        @. w = ((1f0+c1*Â)*w - (c2*Â)*v) / ((1f0+c3*Â+c4)*Â)\n        planwi * w\n        u .= real.(w)\n    end\n    synchronize(u)\n    return u\nend\n\n\nfunction makeresult(bench, N, device, hardware, mdiff)\n    BenchResult(\n        \"PDE\",\n        bench,\n        N,\n        Float32,\n        string(device),\n        hardware,\n        @__FILE__,\n        mdiff\n    )\nend\n\nfunction execute2(device)\n    hardware, array_type = init(device)\n    T = Float32\n    results = BenchResult[]\n    for x in (4,)\n        N = 2 ^ x\n        # initialisations\n        h = 2*π/N; epsn = h * 3; C = 2/epsn; tau = epsn * h\n        k = [0:N/2; -N/2+1:-1]\n        acpu = kron(k.^2, ones(1,N)) + kron(ones(N), k'.^2)\n        ucpu = 2*(rand(N, N)-0.5)\n\n        Â = array_type(T.(acpu))\n        u = array_type(T.(ucpu))\n\n        w = tocomplex64.(u)\n        v = copy(w)\n        c1 = (C*tau + tau/epsn)\n        c2 = (tau / epsn)\n        c3 = (epsn * tau)\n        c4 = (C*tau)\n        planv = plan_fft!(v)\n        planw = plan_fft!(w)\n        planwi = plan_ifft!(w)\n        nruns = 5\n        u0 = copy(u)\n        bench = @benchmark $(inner_loop)(\n                $nruns,\n                $planv, $planw, $planwi,$u0, $u, $v, $w, $Â,\n                $c1, $c2, $c3, $c4\n        )\n        wcpu = tocomplex64.(ucpu)\n        vcpu = copy(wcpu)\n        planvcpu = plan_fft!(vcpu)\n        planwcpu = plan_fft!(wcpu)\n        planwicpu = plan_ifft!(wcpu)\n        inner_loop(\n                nruns,\n                planvcpu, planwcpu, planwicpu, copy(ucpu), ucpu, vcpu, wcpu, acpu,\n                c1, c2, c3, c4\n        )\n        println(Array(ucpu))\n        # mdiff = meandifference(ucpu, u)\n        # @show mdiff\n        # push!(results, makeresult(bench, N, device, hardware, mdiff))\n        # free(Â); free(u0); free(u); free(v); free(w)\n    end\n    results\nend\n\n# execute(Float32, 512, :opencl)\n\nfunction CH_memory_af!(nruns, N, AT)\n    # initialisations\n    h = Float32(2*π/N); epsn = Float32(h * 3); C = Float32(2/epsn); tau = Float32(epsn * h)\n    k = [0:N/2; -N/2+1:-1]\n    Â = AT((Float32.(kron(k.^2, ones(1,N)) + kron(ones(N), k'.^2))))\n    u = AT(Float32.((2*(rand(N, N)-0.5))))\n\n\n    # ============= ACTUAL CODE THAT IS BEING TESTED ======================\n    # allocate arrays and define constants\n    w = AT{Complex64}(u)\n    v = copy(w)\n    c1 = (C*tau + tau/epsn)\n    c2 = (tau / epsn)\n    c3 = (epsn * tau)\n    c4 = (C*tau)\n    tic()\n    for n = 1:nruns\n        v .= complex.(u .* u .* u)\n        v = fft(v)\n        w = fft(w)\n        w .= (( (1f0 + c1) .* Â) .* w .- (c2 .* Â) .* v) ./ ((1f0 + c3 .* Â .+ c4) .* Â)\n        w = ifft(w)\n        u .= real.(w)\n    end\n    GPUArrays.synchronize(u)\n    toc()\n    # ======================================================================\n    u\nend\n\n# source: https://github.com/johnfgibson/julia-pde-benchmark/blob/master/1-Kuramoto-Sivashinksy-benchmark.ipynb\nfunction inner_ks(IFFT!, FFT!, Nt, Nn, Nn1, u, G, A_inv, B, dt2, dt32)\n    for n = 1:Nt\n        Nn1 .= Nn       # shift nonlinear term in time\n        Nn .= u         # put u into Nn in prep for comp of nonlinear term\n\n        IFFT! * Nn\n            # transform Nn to gridpt values, in place\n        Nn .= Nn .* Nn   # collocation calculation of u^2\n        FFT!*Nn        # transform Nn back to spectral coeffs, in place\n\n        Nn .= G .* Nn    # compute Nn == -1/2 d/dx (u^2) = -u u_x\n\n        # loop fusion! Julia translates the folling line of code to a single for loop.\n        u .= A_inv .* (B .* u .+ dt32 .* Nn .- dt2 .* Nn1)\n    end\n    synchronize(u)\nend\n\nfunction makeresult(bench, N, device, hardware, mdiff)\n    BenchResult(\n        \"PDE\",\n        bench,\n        N,\n        Complex64,\n        string(device),\n        hardware,\n        @__FILE__,\n        mdiff\n    )\nend\nfunction execute(device)\n    hardware, AT = init(device)\n    results = BenchResult[]\n    is_gpuarrays(device) || device == :julia_base || return results\n    T = Float32\n    for i = 1:7\n        N = 10^i\n        Lx = T(64*pi)\n        Nx = T(N)\n        dt = T(1/16)\n        Nt = 50\n\n        x = Lx*(0:Nx-1)/Nx\n        u = T.(cos.(x) + 0.1*sin.(x/8) + 0.01*cos.((2*pi/Lx)*x))\n\n        u = AT((T(1)+T(0)im)*u)             # force u to be complex\n        Nx = length(u)                      # number of gridpoints\n        kx = T.(vcat(0:Nx/2-1, 0:0, -Nx/2+1:-1))# integer wavenumbers: exp(2*pi*kx*x/L)\n        alpha = T(2)*pi*kx/Lx                  # real wavenumbers:    exp(alpha*x)\n\n        D = T(1)im*alpha                       # spectral D = d/dx operator\n\n        L = alpha.^2 .- alpha.^4            # spectral L = -D^2 - D^4 operator\n\n        G = AT(T(-0.5) .* D)               # spectral -1/2 D operator, to eval -u u_x = 1/2 d/dx u^2\n\n        # convenience variables\n        dt2  = T(dt/2)\n        dt32 = T(3*dt/2)\n        A_inv = AT((ones(T, Nx) - dt2*L).^(-1))\n        B = AT(ones(T, Nx) + dt2*L)\n\n        # compute in-place FFTW plans\n        FFT! = plan_fft!(u)\n        IFFT! = plan_ifft!(u)\n\n        # compute nonlinear term Nn == -u u_x\n        powed = u .* u\n        Nn = G .* fft(powed);    # Nn == -1/2 d/dx (u^2) = -u u_x\n        Nn1 = copy(Nn);        # Nn1 = Nn at first time step\n        FFT! * u;\n\n        # timestepping loop\n        bench = @benchmark $inner_ks($(IFFT!), $(FFT!), $Nt, $Nn, $Nn1, $u, $G, $A_inv, $B, $dt2, $dt32)\n        push!(results, makeresult(bench, N, device, hardware, 0.0))\n    end\n    results\nend\n\n\nfunction ksintegrateNaive(u, Lx, dt, Nt, nsave)\n    Nx = length(u)                  # number of gridpoints\n    x = collect(0:(Nx-1)/Nx)*Lx\n    kx = vcat(0:Nx/2-1, 0, -Nx/2+1:-1)  # integer wavenumbers: exp(2*pi*kx*x/L)\n    alpha = 2*pi*kx/Lx              # real wavenumbers:    exp(alpha*x)\n    D = 1im*alpha;                  # D = d/dx operator in Fourier space\n    L = alpha.^2 - alpha.^4         # linear operator -D^2 - D^4 in Fourier space\n    G = -0.5*D                      # -1/2 D operator in Fourier space\n\n    Nsave = div(Nt, nsave)+1        # number of saved time steps, including t=0\n    t = (0:Nsave)*(dt*nsave)        # t timesteps\n    U = zeros(Nsave, Nx)            # matrix of u(xⱼ, tᵢ) values\n    U[1,:] = u                      # assign initial condition to U\n    s = 2                           # counter for saved data\n\n    dt2  = dt/2\n    dt32 = 3*dt/2;\n    A_inv = (ones(Nx) - dt2*L).^(-1)\n    B     =  ones(Nx) + dt2*L\n\n    Nn  = G.*fft(u.*u) # -u u_x (spectral), notation Nn = N^n     = N(u(n dt))\n    Nn1 = copy(Nn)     #                   notation Nn1 = N^{n-1} = N(u((n-1) dt))\n    u  = fft(u)        # transform u to spectral\n\n    # timestepping loop\n    for n = 1:Nt\n        Nn1 = copy(Nn)                 # shift nonlinear term in time: N^{n-1} <- N^n\n        Nn  = G.*fft(real(ifft(u)).^2) # compute Nn = -u u_x\n\n        u = A_inv .* (B .* u + dt32*Nn - dt2*Nn1)\n\n        if mod(n, nsave) == 0\n            U[s,:] = real(ifft(u))\n            s += 1\n        end\n    end\n    t,U\nend\n#\n# using FileIO, Interpolations, Colors, GPUBenchmarks, GPUArrays, ColorVectorSpace, FixedPointNumbers\n# Lx = 64*pi\n# Nx = 1024\n# dt = 1/16\n# nsave = 8\n# Nt = 3200\n#\n# x = Lx*(0:Nx-1)/Nx\n# u = cos.(x) + 0.1*sin.(x/8) + 0.01*cos.((2*pi/Lx)*x);\n# t,U = ksintegrateNaive(u, Lx, dt, Nt, nsave)\n# cn = 100\n# cmap = interpolate(colormap(\"Oranges\", cn), BSpline(Linear()), OnCell());\n# mini, maxi = extrema(U)\n# img_color = map(U) do val\n#     val = (val - mini) / (maxi - mini)\n#     val = 1 - clamp(val, 0f0, 1f0);\n#     idx = (val * (cn - 1)) + 1.0\n#     RGB{N0f8}(cmap[idx])\n# end\n# save(GPUBenchmarks.dir(\"results\", \"plots\", \"pde_result.png\"), img_color)\n\nend\n", "meta": {"hexsha": "40765dbda252db13bb53b628a4460ba0cebc3f16", "size": 8668, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmark/PDE.jl", "max_stars_repo_name": "JuliaTagBot/GPUBenchmarks.jl", "max_stars_repo_head_hexsha": "758534553780e330af5f31f70b23e8c5413eaaea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2017-09-12T01:28:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T05:10:06.000Z", "max_issues_repo_path": "benchmark/PDE.jl", "max_issues_repo_name": "JuliaTagBot/GPUBenchmarks.jl", "max_issues_repo_head_hexsha": "758534553780e330af5f31f70b23e8c5413eaaea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark/PDE.jl", "max_forks_repo_name": "JuliaTagBot/GPUBenchmarks.jl", "max_forks_repo_head_hexsha": "758534553780e330af5f31f70b23e8c5413eaaea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2017-10-13T18:55:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T00:09:59.000Z", "avg_line_length": 31.0681003584, "max_line_length": 167, "alphanum_fraction": 0.5098061837, "num_tokens": 2999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.7507494182810182}}
{"text": "# define exceptions for stopping conditions in algorithm\ntype OptimalPointFound <: Exception end\ntype UnboundedFunctionException <: Exception end\n\nfunction get_min(x, d, assts)\n    n = length(assts)\n    e = zeros(n)\n    e[assts] = d\n    ratios = []\n    for i in 1:n\n        if (assts[i]) & (e[i] > 0)\n            push!(ratios, (x[i]/e[i], i))\n        end\n    end\n\n    try\n        return minimum(ratios)\n    catch\n        println(ratios)\n    end\nend\n\nfunction get_q(s_N, assts)\n    n = length(assts)\n    e = zeros(n)\n    e[!assts] = s_N\n\n    try\n        return indmax(e.<0)\n    catch\n            print e\n    end\nend\n\n# a single iteration of the simplex algorithm\nfunction simplex_iteration(assts, x, A, b, c)\n    \"\"\"\n    We have a linear program of the form: min c^T x s.t. Ax = b\n\n    arguments:\n        assts: true indicates the element belongs to the basic set and false to the nonbasic set\n        x: the vector x as given above in the LP\n        A: constraint matrix, of the form Ax = b\n        b: solutions of constraints\n        c: coefficients of the LP function\n    \"\"\"\n\n    B = A[:,assts]\n    N = A[:,!assts]\n\n    x_B = x[assts]\n    x_N = x[!assts]\n\n\n    # solve B^T lambda = c_B for lambda\n    lambda = B' \\ c[assts]\n\n    # compute s_N = c_N - N^\\top \\lambda\n    s_N = c[!assts] - N' * lambda\n\n    # check if all elements of s_N are >= 0\n    if all(s_N .>= 0)\n        throw(OptimalPointFound())\n    end\n\n    # select q \\in N with s_q < 0 as entering index\n    q = get_q(s_N, assts) # here we always choose the first negative element\n\n    # solve Bd = A_q for d\n    d = B \\ A[:,q]\n\n    # check d\n    if all(s_N .>= 0)\n        throw(UnboundedFunctionException())\n    end\n\n    # calculate x_q+\n    x_q, p = get_min(x, d, assts)\n\n    # update x\n    x[assts] = x[assts] - d * x_q\n    x[q] = x_q\n\n    # update the assts\n    assts[p] = !assts[p]\n    assts[q] = !assts[q]\n\n    # returns new assts, x\n    return assts, x\n\nend\n\nfunction run_simplex(assts, x, A, b, c, num_iters, verbose=false)\n\n    for i in 1:num_iters\n        #println(\"Starting iteration: \", i)\n\n        try\n            assts, x = simplex_iteration(assts, x, A, b, c)\n\n            if verbose\n                println(\"Resulting x, assts: \\n\\t\", (x,assts))\n            end\n\n        catch err\n            if isa(err, UnboundedFunctionException)\n\n                println(\"Unbounded function exception!\")\n                return assts, x\n\n            elseif isa(err, OptimalPointFound)\n\n                println(\"Optimal point found!\")\n\n                if verbose\n                    println(\"Optimal x, assts: \\n\\t\", (x,assts))\n                end\n\n                return assts, x\n            else\n                println(err)\n\n                throw(err)\n            end\n        end\n\n    end\n    return assts, x\nend\n\nfunction get_starting_values(A, b)\n    \"\"\"\n    given a LP min c'x s.t. Ax = b, we want to create the new LP e'z s.t. Ax + Ez = b, where x=0, e=ones(.)\n\n    A: the original constraint matrix\n    b: the original b\n\n    returns new A, x, c, assts to pass into simplex algorithm\n    \"\"\"\n    nrows, ncols = size(A)\n    # init x, c\n    x = zeros(ncols + nrows)\n    c = zeros(ncols + nrows)\n\n    # add z to x\n    x[ncols+1:ncols+nrows,:] = abs(b')\n    c[ncols+1:ncols+nrows,:] = 1.\n\n    # assignments are non-zero elements of x\n    assts = (x .!= 0)\n\n    E = zeros(nrows, nrows)\n    vals = b .> 0\n\n    for i in 1:nrows\n        if vals[i]\n            E[i,i] = 1\n        else\n            E[i,i] = -1\n        end\n    end\n\n    return [A E], x, c, assts\n\nend\n\nfunction run_two_stage_simplex(A, b, c, num_iters)\n    time1 = time()\n    A0, x0, c0, assts0 = get_starting_values(A, b)\n\n    nrows, ncols = size(A)\n    l = length(x0)\n\n    println(\"\\nRunning Phase I of simplex algorithm\\n\")\n    # run phase I\n    assts_start, x_start = run_simplex(assts0,x0,A0,b,c0,num_iters)\n\n    # run phase II\n    try\n        @assert x_start[l] == 0\n    catch err\n        println(\"No feasible solution for m=\", size(A)[2])\n    end\n\n    # discard z\n    xnew = x_start[1:l-nrows]\n    assts_new = assts_start[1:l-nrows]\n\n    println(\"\\nRunning Phase II of simplex algorithm \\n\")\n\n    x, assts = run_simplex(assts_new,xnew,A,b,c,num_iters)\n\n    time2 = time()\n\n    @printf(\"\\nTime: %.5f (s)\", time2-time1)\n\n    return x, assts, (time2-time1)\n\nend\n\n#run_two_stage_simplex(A, b, c, 10)\n\n\n\n\nfunction solve_subproblem(assts, x_k, G, c, A, b)\n    g_k = G * x_k + c\n\n    ## if all assignments are false\n    if all(assts .== false)\n        return G \\ -g_k\n\n    else\n        dimx = length(x_k)\n        A_w = A[assts,:]\n        k,k = size(G)\n        m,n = size(A_w)\n\n        # construct matrix\n        mat = [G A_w'; A_w zeros(k+m - n,k+m - n)]\n\n        # pad with 0's\n        d, = size(g_k)\n        answ = [-g_k; zeros(k+m - d)]\n\n        # compute solution and get x\n        sol = mat \\ answ\n        x = sol[1:dimx,:]\n\n        return x\n    end\nend\n\nfunction compute_multipliers(assts, x_k, G, c, A)\n    g = G * x_k + c\n    lambda = A[assts,:]' \\ g\n\n    n = length(assts)\n    return lambda, (1:n)[assts]\nend\n\nfunction compute_step_length(A, b, x_k, p_k, assts)\n    \"\"\"\n    Returns step length alpha_k and blocking constraint of choice -- if the latter is 0, then alpha_k = 1\n    \"\"\"\n    n = length(b)\n\n    # by default, return 1 with no blocking constraints\n    min = 1\n    blocking = 0\n\n    for i in 1:n\n        # if i is in the working set, continue\n        if assts[i]\n            continue\n        end\n\n        a_i = A[i,:] ## this is a row vector so no need to transpose\n        prod = a_i * p_k\n        @assert length(prod) == 1\n\n        # if a_i^ p_k >= 0, continue\n        if (prod)[1] >= 0\n            continue\n        end\n\n        val = (b[i] - a_i * x_k) / (prod)\n        @assert length(val) == 1\n        if val[1] < min\n            min = val[1]\n            blocking = i\n        end\n    end\n\n    return min, blocking\nend\n\n\nfunction active_set_iteration(assts, x_k, G, c, A, b)\n    \"\"\"\n    assts: assignments of constraint indices to the working set -- 1's are in the working set, 0's are not\n    x_k: the current value of x_k obtained from the previous iteration\n    G: the matrix in the quadratic function, i.e., x^T G x + x^T c\n    c: the c from the quadratic function above\n    A: matrix, where each row is the a_i from the constraint\n    b: vector where each index is the b_i corresponding to constraint i\n    \"\"\"\n    # solve subproblem to find p_k\n    p_k = solve_subproblem(assts, x_k, G, c, A, b)\n\n    #if all(p_k == 0) sufficient close to 0\n    if all(abs(p_k-0) .<= 1e-6)\n\n        if all(assts .== false)\n            throw(OptimalPointFound())\n        else\n\n            # compute lagrange multipliers lambda_i that satisfy\n            lambda, inds = compute_multipliers(assts, x_k, G, c, A)\n        end\n\n        # if lambda_i >= 0 for all i in W_k \\cap I\n        if all(lambda .>= 0)\n            # stop with solution x* = x_k\n            throw(OptimalPointFound())\n\n        # (not all lambda_i >= 0)\n        else\n            # index of most negative multiplier lambda_j\n            j = inds[indmin(lambda)]\n\n            # remove j from working set\n            assts[j] = false\n            x_new = x_k\n        end\n\n    # (p_k != 0)\n    else\n        # compute step length alpha_k\n        alpha_k, blocking = compute_step_length(A, b, x_k, p_k, assts)\n\n        # update x_{k} += alpha_k * p_k\n        x_new = x_k + alpha_k * p_k\n\n        # if there are blocking constraints, update W_k (assts) by adding one of them to W_k\n        if blocking != 0\n            assts[blocking] = true\n        end\n    end\n\n    return assts, x_new\n\nend\n\n\nfunction run_active_set(num_iters, assts, x_0, G, c, A, b, verbose=true)\n    x_k = x_0\n    for i in 1:num_iters\n        if verbose\n            println(\"Iteration:\\t\", i)\n        end\n        try\n            assts, x_k = active_set_iteration(assts, x_k, G, c, A, b)\n            if verbose\n                println(\"Resulting x, assts: \\n\\t\", (x_k,assts))\n            end\n        catch err\n            if isa(err, OptimalPointFound)\n\n                println(\"Optimal point found!\")\n\n                if verbose\n                    println(\"Optimal x, assts: \\n\\t\", (x_k,assts))\n                end\n\n                return assts, x_k\n            else\n                println(err)\n                throw(err)\n            end\n        end\n\n    end\n    return assts, x_k\nend\n\nfunction run_active_set_full(num_iters, assts, x_0, G, c, A, b, verbose=true)\n    x_k = x_0\n    vals = []\n    for i in 1:num_iters\n        if verbose\n            println(\"Iteration:\\t\", i)\n        end\n        try\n            assts, x_k = active_set_iteration(assts, x_k, G, c, A, b)\n\n            val = 1/2 * x_k' * G * x_k + c' * x_k\n            push!(vals, val)\n\n            if verbose\n                println(\"Resulting x, assts: \\n\\t\", (x_k,assts))\n            end\n        catch err\n            if isa(err, OptimalPointFound)\n\n                println(\"Optimal point found!\")\n\n                if verbose\n                    println(\"Optimal x, assts: \\n\\t\", (x_k,assts))\n                end\n\n                return assts, x_k, vals\n            else\n                println(err)\n                throw(err)\n            end\n        end\n\n    end\n    return assts, x_k, vals\nend\n", "meta": {"hexsha": "1b8826fc77cb047f1d9f69b027dddbe52b696a5a", "size": 9228, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "optimizers/activeset.jl", "max_stars_repo_name": "dicai/descent.jl", "max_stars_repo_head_hexsha": "f684b69f6c8dadc86402fc465455b51c0484cedf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-08-12T22:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-25T01:37:28.000Z", "max_issues_repo_path": "optimizers/activeset.jl", "max_issues_repo_name": "dicai/descent.jl", "max_issues_repo_head_hexsha": "f684b69f6c8dadc86402fc465455b51c0484cedf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimizers/activeset.jl", "max_forks_repo_name": "dicai/descent.jl", "max_forks_repo_head_hexsha": "f684b69f6c8dadc86402fc465455b51c0484cedf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9552238806, "max_line_length": 107, "alphanum_fraction": 0.5332683138, "num_tokens": 2729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.750749407012878}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n    quote\n        local el = $(esc(element))\n        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n        el\n    end\nend\n\n# ╔═╡ 6b359fc5-ec8d-47ec-89ec-b1b214a37a82\nbegin\n\tusing PlutoUI # user-interface do Pluto.jl\n\tusing Plots  # Julia package para gráficos \n\tusing Dierckx  # Julia package para interpolação/extrapolação de dados\nend\n\n# ╔═╡ c7838496-100f-4901-abcf-0d4e59fbc4a9\nhtml\"<button onclick='present()'>present</button>\"\n\n# ╔═╡ 44201f7b-84df-4b8d-aeec-0f142ac2008b\nmd\"\"\"\n# Máquinas de corrente contínua (Ex. 7)\nMotores de corrente contínua, exercício 7:\n\"\"\"\n\n# ╔═╡ ed4846d5-70d2-4deb-9a4a-41cdc8c99bdd\nmd\"\"\"\n**Considere um motor de corrente contínua, com a seguinte chapa de características:**\n\"\"\"\n\n# ╔═╡ 1301d1ad-89e8-4282-ab35-1a6b8214bea0\n(Pᵤ, Uₙ, nₙ, ηₙ, Rᵢ, Rₛ, Ns, Rd, Nd)=(17e3, 250, 1200, 0.85, 0.6, 0.1, 12, 200, 3000)\n\n# ╔═╡ 1a427cf6-b2d3-4d9b-9cb5-4682d5f49869\nbegin\n\tnmag=1200 # velocidade angular da característica magnética, rpm\n\tIex=[0,0.0132,0.03,0.033,0.067,0.1,0.133,0.167,0.2,0.233,0.267,0.3,0.333,0.367,0.4,0.433,0.467,0.5,0.533,0.567,0.6,0.633,0.667,0.7,0.733,0.767,0.8,0.833,0.867,0.9,0.933,0.966,1,1.033,1.067,1.1,1.133,1.167,1.2,1.233,1.267,1.3,1.333,1.367,1.4,1.433,1.466,1.5]\n\tE₀=[5.40, 6.67,13.33,16,31.3,45.46,60.26,75.06,89.74,104.4,118.86,132.86,146.46,159.78,172.18,183.98,195.04,205.18,214.52,223.06,231.2,238,244.14,249.74,255.08,259.2,263.74,267.6,270.8,273.6,276.14,278,279.74,281.48,282.94,284.28,285.48,286.54,287.3,287.86,288.36,288.82,289.2,289.38,289.57,289.69,289.81,289.95]\n\tplot(Iex, E₀, title=\"E₀=f(Iₑₓ), n=1200rpm\", xlabel = \"Iₑₓ (A)\", ylabel=\"E₀ (V)\", ylims=(0,300), framestyle = :origin, minorticks=10, label=:none, linewidth=2)\nend\n\n# ╔═╡ e2fc78d6-480b-4fe0-b844-0d4329c0d572\nmd\"\"\"\n## Influência de $$ΔE$$ 💻\n\"\"\"\n\n# ╔═╡ 8bde3ad9-2d03-4557-ab50-a89ac8e834a3\nmd\"\"\"\n!!! nota\n\tNo enunciado original não é considerada a existência de reacção magnética do induzido, $$(ΔE=0\\rm V)$$.  \n\tNo entanto, na versão *notebook* para que se possa verificar a influência de $$ΔE$$, nas características de funcionamento do motor DC, para os diferentes tipos de excitação, uma curva de $$ΔE=f(I_i)$$ é considerada como uma opção de análise.\"\"\"\n\n# ╔═╡ 61238dc4-3c9d-4b59-9486-501988806c27\n\"Com ΔE?\", @bind z CheckBox()\n\n# ╔═╡ c4d5e3f9-7808-48f6-8d33-05607d8e5a4e\nbegin\n\tIᵢ=[0.0:15:120;]\n\t#Iᵢ=[0.0, 15, 30, 45, 60, 75, 90, 105, 120]\n\tΔE=[0.0, 1.5, 4, 7.5, 12, 17, 23, 30.5, 40]*z\n\tplot(Iᵢ, ΔE, title=\"ΔE=f(Iᵢ)\", xlabel = \"Iᵢ (A)\", ylabel=\"ΔE (V)\", xlims=(0,120), ylims=(0,40), framestyle = :origin, minorticks=5, label=:none, linewidth=2)\nend\n\n# ╔═╡ f6fcec56-b080-4016-baf0-0ab728f255f3\nmd\"\"\"\n## **a) $$R_c$$ para condições nominais**\n**Com o motor em excitação derivação, determine o valor do reóstato de campo, nas\ncondições nominais $$(U_n, I_n, n_n)$$**;\n\"\"\"\n\n# ╔═╡ d9e431c5-be62-40c8-b5d6-59d5808e4436\nmd\"\"\"\nPara se ter a informação completa das condições nominais do motor, falta determinar o valor da corrente nominal, $$I_n$$.\\\nDa chapa de características do motor conhecem-se a potência útil (potência mecânica) e rendimento nominais, $$P_u$$ e $$\\eta_n$$, respectivamente, o que permite obter a potência absorvida, $$P_{ab}=U_nI_n$$. Assim: \n\"\"\"\n\n# ╔═╡ cde4847b-6c38-4bc6-a869-514774630c89\nmd\"\"\"\n$$I_n=\\frac{P_n}{\\eta U_n}$$\n\"\"\"\n\n# ╔═╡ 1c70002d-e3fb-4d81-b0f9-ed00d69173ff\nIₙ=Pᵤ/(ηₙ*Uₙ);\n\n# ╔═╡ 5b4c1912-126d-4fe8-87c5-f65b299f3642\nmd\"\"\"\nCalculando obtém-se $$I_n=$$ $(Iₙ)A\n\"\"\"\n\n# ╔═╡ d8d6a6e9-df8d-47d2-832a-0d2126ce760e\nmd\"\"\"\nA velocidade, $$n$$, é dependente do fluxo magnético, $$kϕ_0$$, que por sua vez depende da corrente de excitação, $$I_d$$ e da característica magnética da máquina.\\\nAssim, a imagem do fluxo magnético presente na máquina é dada pela a força contra-electromotriz de vazio do motor, $$E_0^{'}$$:\n\"\"\"\n\n# ╔═╡ 0ff562ff-7af2-4749-87f5-8766cb695893\nmd\"\"\"\n$$E_0^{'}=E^{'}+ΔE$$\nSendo a  a força contra-electromotriz efectiva, $$E^{'}$$, dada por:\\\n\"\"\"\n\n# ╔═╡ cf0f089a-1901-4ad1-8fe9-b9028679b109\nmd\"\"\"\n$$E^{'}=U-R_iI_i$$\n\"\"\"\n\n# ╔═╡ de954f1d-a3ac-4830-acd0-85e64afdf0cd\n# forma computacional de consultar a curva de ΔE(Ii), por interpolação dos dados através do Pkg Dierckx.jl\nbegin\n\tΔE_int=Spline1D(Iᵢ,ΔE)  \n\tΔEₙ=ΔE_int(Iₙ)\n\tΔEₙ=round(ΔEₙ, digits=1)\nend;\n\n# ╔═╡ 68969be8-0bee-4cca-85de-7a8d2aa35ee2\nmd\"\"\"\nO valor de $$ΔE$$ para $$I_n$$, consultando a sua curva de q.d.t é: $$ΔE=$$ $(ΔEₙ)V.  \n\"\"\"\n\n\n# ╔═╡ 8f5b0bd5-7a65-4ba3-bdd1-7cc3128fa8d8\nE=Uₙ-Rᵢ*Iₙ;\n\n# ╔═╡ 7d6a01a4-4876-42dc-ab66-f7f736d41a32\nE₀ₙ=E+ΔEₙ;\n\n# ╔═╡ 0a35c6dc-0967-4f8a-9fff-904f9062eeab\nmd\"\"\"\nCalculando as f.c.e.m., obtêm-se $$E^{'}=$$ $(E)V e $$E_0^{'}=$$ $(E₀ₙ)V.\n\"\"\"\n\n# ╔═╡ 9d82a20f-3a14-4796-88e9-e27720632bbd\nmd\"\"\"\n\nNote que tomou-se a corrente do rotor aproximadamente igual à corrente absorvida, $$I_i\\simeq I_n$$, sendo no entanto, $$I_i=I_n+I_d$$. Contudo, não se está a desprezar a corrente $$I_d$$, mas sim a q.d.t. em $$R_i$$ devido a $$I_d$$. Ou seja, $$R_iI_d\\lll R_iI$$ para efeito de cálculo de $$E_0^{'}$$ e uma vez que $$I_d$$ ainda não está calculada.\n\"\"\"\n\n# ╔═╡ 04b517f9-ed9f-4a5d-929b-82b10de843b9\nmd\"\"\"\nA característica magnética foi obtida à mesma velocidade inscrita na chapa de características da máquina, $$n_n$$, por conseguinte, obtém-se dela directamente a corrente de campo, $$I_d$$.\n\"\"\"\n\n# ╔═╡ cfc7844e-3974-46ef-a53a-ee6a1a85d7f3\n# forma computacional de consultar a característica magnética, por interpolação dos dados através do Pkg Dierckx.jl\nbegin\n\tId_int=Spline1D(E₀,Iex)  \n\tId=Id_int(E₀ₙ)\n\tId=round(Id, digits=2)\nend;\n\n# ╔═╡ 71356175-ffe4-4c3a-a895-8a4be8713a44\nmd\"\"\"\nConsultando a característica magnética a 1200rpm, verifica-se para $$E₀=$$ $(E₀ₙ)V $$\\Rightarrow$$ $$I_d=$$ $(Id)A.\n\"\"\"\n\n# ╔═╡ d85a5505-1ab5-43d0-97ad-a0cb4a220c06\nmd\"\"\"\nAssim, o reostato de campo para colocar o motor *shunt* nas condições nominais é dado por:\n\"\"\"\n\n# ╔═╡ 7c572ab7-2292-423c-b611-68573b289265\nmd\"\"\"\n$$R_c=\\frac{U_n}{I_d}-R_d$$\n\"\"\"\n\n# ╔═╡ 14ad0875-e27a-442e-81e9-29d1abaeac17\nbegin\n\tRc=Uₙ/Id-Rd\n\tRc=round(Rc, digits=1)\nend;\n\n# ╔═╡ 50022e39-c2f4-455f-8d26-7c9246190b11\nmd\"\"\"\nCalculando, obtém-se $$R_c=$$ $(Rc)Ω\n\"\"\"\n\n# ╔═╡ 4bac08e5-7a7a-496f-8d67-aa2bc4b10236\nmd\"\"\"\n> Poderá então observar as diferenças de cálculo relativas à presença de q.d.t. devido à reacção magnética do induzido, ou seja, uma máquina com pólos auxiliares (caso mais frequente), conduz a $$ΔE \\neq 0$$V, variável em função da corrente do induzido. No caso de uma máquina com pólos auxiliares e enrolamentos de compensação, a reacção magnética do induzido estará compensada e assim tem-se:\n\"\"\"\n\n# ╔═╡ 5abe64cf-9291-48d6-bf60-7335551ee791\nmd\"\"\"\n$$ΔE=0 \\Rightarrow E_0^{'}=E^{'}$$\n\"\"\"\n\n# ╔═╡ ac32afe0-e30f-402e-995e-8b0cacf8af10\n\n\n# ╔═╡ 4989ff81-ac16-446c-8d8a-e3cb9e5950b6\nmd\"\"\"\n## **b) Motor shunt**\n**Utilizando o reóstato de campo calculado na alínea anterior, determine as características de velocidade, binário e mecânica deste motor (excitação derivação);**\n\"\"\"\n\n# ╔═╡ 1d458a5a-545f-4ab6-900b-9d84ebbaf51d\nmd\"\"\"\n> Na resolução computacional para o **motor de excitação derivação**, as grandezas calculadas estão identificadas como: k$$ϕ$$₀₁, n₁, E₁, ω₁, Td₁\n\"\"\"\n\n# ╔═╡ d25759bf-6e81-439c-a2c9-c19704379437\nbegin\n\tkϕ₀₁=E₀ₙ/nmag\n\tkϕ₀₁=round(kϕ₀₁, digits=3)\nend;\n\n# ╔═╡ 4652d9e4-e2c6-47c4-93d1-1e360ffb7e57\nmd\"\"\"\nTomando o valor calculado de $$R_c=$$ $(Rc)Ω, resulta $$I_d=$$ $(Id)A, o que permite calcular o fluxo magnético da máquina em vazio, $$kϕ₀$$, que no motor de excitação derivação permanece constante.  \nAssim, $$kϕ₀=$$ $(kϕ₀₁)V/rpm\n\"\"\"\n\n# ╔═╡ 4629c049-8882-4823-bdea-93e3d70cc901\nmd\"\"\"\nA determinação da característica de velocidade $$n=f(I)$$ ou $$n=f(I_i)$$, uma vez que $$I_i\\simeq I$$, consiste em sucessivamente realizar o cálculo da velocidade do motor para diferentes valores de corrente:  \n\"\"\"\n\n# ╔═╡ ea81ca51-dccc-4187-b788-7ed64716e698\nmd\"\"\"\n$$n=\\frac{U-R_iI_i+\\Delta E}{k\\phi_0}$$ com $$n$$ em rpm, $$\\Delta E=f(I_i)$$ e $$k\\phi_0=$$constante, em V/rpm.\n\"\"\"\n\n# ╔═╡ 6030b931-51a0-42fc-9b74-5635b590e6f5\n# Característica de velocidade:\nbegin\n\tI=0:1:1.5*Iₙ\n\tIi=I.-Id\n\tΔEᵢ=ΔE_int(Ii)\n\tn₁=(Uₙ.-Rᵢ*Ii.+ΔEᵢ)/kϕ₀₁\nend;\n\n# ╔═╡ d47a90f0-f8bc-44d0-b71c-c0bc59d0d23c\nmd\"\"\"\nSimilarmente, a característica de binário, $$T=f(I)$$ ou $$T=f(I_i)$$, podendo $$T$$ ser o binário desenvolvido, $$T_d$$, ou o binário útil, $$T_u$$, atendendo que: $$T_d=T_u+T_p$$, consiste em sucessivamente realizar o cálculo do binário para diferentes valores de corrente:  \n\"\"\"\n\n# ╔═╡ 3c921729-6534-4eac-abb0-4eb362295b91\nmd\"\"\"\n$$T_d=\\frac{E^{'}}{ω}I_i\\:\\:\\:;\\:\\:\\:ω=\\frac{2πn}{60}$$ com $$ω$$ em rad/s.\n\"\"\"\n\n# ╔═╡ 4da7f391-e3bf-4e12-aa6b-a7ef5e45d3b9\n# Característica de binário:\nbegin\n\tE₁=Uₙ.-Rᵢ*Ii\n\tω₁=2π.*n₁/60\n\tTd₁=(E₁./ω₁).*Ii\nend;\n\n# ╔═╡ df3609ef-80f2-464a-b522-f289ea9344b4\n\n\n# ╔═╡ f499659c-b042-4002-bb27-980daf8502d4\nmd\"\"\"\n## **c) Motor excitação composta** \n**Idem, com excitação composta em longa derivação aditiva e subtrativa. Representar as características nos mesmos gráficos para comparação;**\n\"\"\"\n\n# ╔═╡ 72a079e6-0c41-4c50-9ee2-838d5cc60c85\nmd\"\"\"\nNo motor de excitação composta, o fluxo magnético depende da contribuição das forças magnetomotrizes de ambos os enrolamentos de excitação e da forma como estes estão ligados entre si (de forma aditiva ou subtractiva):\n\"\"\"\n\n# ╔═╡ 58e9df34-7471-4942-ac06-2505f52875f2\nmd\"\"\"\n$$I_{ex}N_d=I_dN_d\\pm I_sN_s$$\nsendo $$I_s$$ a corrente que percorre o enrolamento de excitação série.\n\"\"\"\n\n# ╔═╡ f305c434-9d0c-497d-8335-bf25aa80e915\nmd\"\"\"\nAssim, $$I_{ex}$$ é a corrente de campo que representa o fluxo total da máquina, sendo obtida por:\n\"\"\"\n\n# ╔═╡ 0ce81a6e-965c-4dc0-b9f3-f8c09143460e\nmd\"\"\"\n$$I_{ex}=I_d \\pm \\frac{N_s}{N_d}I_s$$\n\"\"\"\n\n# ╔═╡ 1cd42258-7583-4288-9c6d-4d47facb69e1\nmd\"\"\"\nAssim, a característica de velocidade para o motor de excitação composta em longa derivação é obtida por cálculo sucessivo da velocidade do motor para diferentes valores de corrente, através de:  \n\"\"\"\n\n# ╔═╡ facb1900-1093-46c7-97b2-187b67e21294\nmd\"\"\"\n$$n=\\frac{U-(R_i+R_s)I_i+\\Delta E}{k\\phi_t}$$ com $$k\\phi_t=k(\\phi_d \\pm \t\\phi_s)$$, em V/rpm obtido através da característica magnética da máquina.\n\"\"\"\n\n# ╔═╡ 6aae7842-4889-4be6-bd1d-eab44c610af8\n\n\n# ╔═╡ 7ad852d3-e3b8-4799-8aae-a52c1ebe34ac\nmd\"\"\"\n> Na resolução computacional para o **motor de excitação composta aditiva**, as grandezas calculadas estão identificadas como: `Iex₂`, `E₀₂`, `kϕ₀₂`, `n₂`, `E₂`, `ω₂`, `Td₂`\n\"\"\"\n\n# ╔═╡ b4e5cbd1-c1c1-47e1-a8aa-8fc2ef628e87\nbegin\n\tIex₂=Id.+(Ns/Nd)*Ii\n\tE₀_int1=Spline1D(Iex, E₀)  # função de interpolação para a caract. magnética\n\tE₀₂=E₀_int1(Iex₂) # fem que contém os fluxos derivação + série\n\tkϕ₀₂=E₀₂/nmag\n\tn₂=(Uₙ.-(Rᵢ+Rₛ)*Ii.+ΔEᵢ)./kϕ₀₂\n\tE₂=Uₙ.-(Rᵢ+Rₛ)*Ii\n\tω₂=2π.*n₂/60\n\tTd₂=(E₂./ω₂).*Ii\nend;\n\n# ╔═╡ 55397202-48ae-4a3d-a053-9f46e6638560\n\n\n# ╔═╡ 1a154f27-cd9a-4de8-b850-599b5e810811\nmd\"\"\"\n> Na resolução computacional para o **motor de excitação composta subractiva**, as grandezas calculadas estão identificadas como: `Iex₃`, `E₀₃`, `kϕ₀₃`, `n₃`, `ω₃`, `Td₃`\n\"\"\"\n\n# ╔═╡ 626c5cab-64e2-446c-9d38-f01dde099d3e\nbegin\n\tIex₃=Id.-(Ns/Nd)*Ii\n\tE₀₃=E₀_int1(Iex₃) #fem que contém os fluxos derivação - série\n\tkϕ₀₃=E₀₃/nmag\n\tn₃=(Uₙ.-(Rᵢ+Rₛ)*Ii.+ΔEᵢ)./kϕ₀₃\n\tω₃=2π.*n₃/60\n\tTd₃=(E₂./ω₃).*Ii\nend;\n\n# ╔═╡ 1c659ae6-1b29-43a5-92f7-30b1f24c3696\n\n\n# ╔═╡ 426c40b4-5fa1-4d8a-b03c-11f3008484f6\nmd\"\"\"\n## **d) Motor série**\n**Determinar as curvas características com o circuito de derivação desligado (motor série). Representar as características nos mesmos gráficos para comparação;**\n\"\"\"\n\n# ╔═╡ 8dfd7146-2e55-4ea0-8cf2-3557d89e96e1\nmd\"\"\"\n> Na resolução computacional para o **motor de excitação série**, as grandezas calculadas estão identificadas como: Iex₄, E₀₄, k$$ϕ$$₀₄, n₄, ω₄, Td₄\n\"\"\"\n\n# ╔═╡ 4e4469c8-994d-42c6-b373-8f295768b8b0\nbegin\n\tIex₄=(Ns/Nd)*Ii\n\tE₀₄=E₀_int1(Iex₄) #fem que contém apenas fluxo série\n\tkϕ₀₄=E₀₄/nmag\n\tn₄=(Uₙ.-(Rᵢ+Rₛ)*Ii.+ΔEᵢ)./kϕ₀₄\n\tω₄=2π.*n₄/60\n\tTd₄=(E₂./ω₄).*Ii\nend;\n\n# ╔═╡ a45ad7c2-2f83-4e04-bdaf-8dcc30a150f5\n# Características de velocidade, plots:\nbegin\n\tplot(I, n₁, linewidth=2, title=\"Características de velocidade\", xlabel = \"I (A)\", ylabel=\"n (rpm)\",  framestyle = :origin, minorticks=5, label=\"shunt\")\n\tplot!(I,n₂, linewidth=2, label=\"comp. aditivo\")\n\tplot!(I,n₃, linewidth=2, label=\"comp. subtractivo\", legend=:bottomleft)\n\tplot!(I,n₄, linewidth=2, label=\"série\", xlims=(0,120), ylims=(0,3000))\nend\n\n# ╔═╡ 5b866db3-ddd6-4bfd-b027-761c07d6755c\n# Características de binário, plots:\nbegin\n\tplot(I, Td₁, linewidth=2, title=\"Características de binário\", xlabel = \"I (A)\", ylabel=\"Td (Nm)\",  framestyle = :origin, minorticks=5, label=\"shunt\")\n\tplot!(I,Td₂, linewidth=2, label=\"comp. aditivo\")\n\tplot!(I,Td₃, linewidth=2, label=\"comp. subtractivo\", legend=:topleft)\n\tplot!(I,Td₄, linewidth=2, label=\"série\", xlims=(0,120), ylims=(0,250))\nend\n\n# ╔═╡ 326135bd-24e3-492d-a7d5-1a14f065e80f\n# Características mecânicas, plots:\nbegin\n\tplot(Td₁, n₁, linewidth=2, title=\"Características mecânicas\", ylabel = \"n (rpm)\", xlabel=\"Td (Nm)\",  framestyle = :origin, minorticks=5, label=\"shunt\")\n\tplot!(Td₂, n₂, linewidth=2, label=\"comp. aditivo\")\n\tplot!(Td₃, n₃, linewidth=2, label=\"comp. subtractivo\", legend=:topright)\n\tplot!(Td₄, n₄, linewidth=2, label=\"série\", xlims=(0,250), ylims=(0,3000))\nend\n\n# ╔═╡ 66e32f84-8b2a-4a3d-81fe-16437ecc3c18\n\n\n# ╔═╡ 60db00b7-c78b-4c26-9530-c62fcfd1bfd2\nmd\"\"\"\n## **e) MI: variação $$n=f(I)$$ 💻**\n**Considere o motor com excitação independente (MI), Uexc = 240V , com o reóstato de campo calculado na alínea a). Explicite a variação da característica de velocidade nas situações:**\n1. **aumento de tensão do induzido;**\n2. **diminuição do reóstato de campo;**\n3. **aumento da resistência adicional.**\n\"\"\"\n\n# ╔═╡ 4fdea2ae-3bf8-42cd-bf6f-411eaf8223c3\nmd\"\"\"\n> Na resolução computacional para o **motor de excitação separada**, as grandezas calculadas estão identificadas como: `Ui`, `Iex5`, `E₀₅`, `kϕ₀₅`, `ΔEᵢᵢ`, `n₅`, `ω₅`, `Td₅`\n\"\"\"\n\n# ╔═╡ 36295cf6-19ba-4240-9806-745ec0bfdccd\nbegin\n\tH1=(\"Tensão do induzido, Ui\", @bind Ui PlutoUI.Slider(150:1:350, default=250.0, show_value=true))\n\tH2=(\"Reostato de campo, Rc1\", @bind Rc1 PlutoUI.Slider(0*Rc:0.01*Rc:2.5*Rc, default= Rc, show_value=true))\n\tH3=(\"Resistência adicional, Rad\", @bind Rad PlutoUI.Slider(0:0.1:1.5, default=0.0, show_value=true))\n\tH1, H2, H3\nend\n\n# ╔═╡ e648310c-8172-4cf0-ab72-f40229ba2577\nbegin\n\tUexc=240\n\tIex₅=Uexc/(Rc1+Rd)\n\tE₀₅=E₀_int1(Iex₅) #fem para excitação separada\n\tkϕ₀₅=E₀₅/nmag\n\tΔEᵢᵢ=ΔE_int(I)\n\tn₅=(Ui.-(Rᵢ+Rad)*I.+ΔEᵢᵢ)./kϕ₀₅\n\tE₅=Ui.-(Rᵢ+Rad)*I\n\tω₅=2π.*n₅/60\n\tTd₅=(E₅./ω₅).*Ii\nend;\n\n# ╔═╡ 4919a95d-cd66-401c-af76-6155087462a3\n# Característica de velocidade vs. variação de Ui, Rc1 ou Rad; plots:\nbegin\n\tplot(I, n₅, ylims=(0,3000),linewidth=2, framestyle = :origin, title=\"Variação da característica de velocidade\", label=:none, xlabel = \"I (A)\", ylabel=\"n (rpm)\", minorticks=5, xlims=(0,120))\nend\n\n# ╔═╡ 8ad59666-3801-44a3-b26a-197a8f60db02\nmd\"\"\"\n!!! nota\n\t**Apresenta-se uma alínea f) idêntica à alínea anterior, mas considerando a característica de binário:**  \n\"\"\"\n\n# ╔═╡ babc5b0b-3263-47d5-bd33-56917ece1e6b\nmd\"\"\"\n## **f) MI: variação $$T=f(I)$$ 💻**\n**Considere o motor com excitação independente (MI), Uexc = 240V , com o reóstato de campo calculado na alínea a). Explicite a variação da característica de binário nas situações:**\n1. **aumento de tensão do induzido;**\n2. **diminuição do reóstato de campo;**\n3. **aumento da resistência adicional.**\n\"\"\"\n\n# ╔═╡ 49cc56bc-bd1e-4e07-9d9c-0ccfaa92e7b0\n# Característica de binário vs. variação de Ui, Rc1 ou Rad; plots:\nbegin\n\tplot(I, Td₅, ylims=(0,250),linewidth=2, framestyle = :origin, title=\"Variação da característica de binário\", label=:none, xlabel = \"I (A)\", ylabel=\"Td (Nm)\", minorticks=5, xlims=(0,120))\nend\n\n# ╔═╡ 0bda0726-fcf9-491d-ad24-301521cb5892\n\n\n# ╔═╡ f34820a6-bd96-463f-b747-2b910914d152\nmd\"\"\"\n# Setup\n\"\"\"\n\n# ╔═╡ 50588330-7af4-4c41-af8d-ffbb4c074394\nTableOfContents(title=\"📚 Índice, Exercício 7\")\n\n# ╔═╡ e99f40c0-1752-4096-8fc9-c4550ae86168\nmd\"\"\"\n!!! info\n\tNo índice deste *notebook*, os tópicos assinalados com \"💻\" permitem interacção com o utilizador.\n\"\"\"\n\n# ╔═╡ 8e683ba6-fe89-41d5-8f0a-5e3e59ca747c\nmd\"\"\"\n## _Julia packages_\n*Links to package help*: [Dierckx](https://github.com/kbarbary/Dierckx.jl), [Plots](http://docs.juliaplots.org/latest/), [PlutoUI](https://juliahub.com/docs/PlutoUI/abXFp/0.7.6/)  \n\"\"\"\n\n# ╔═╡ 80c412ed-1cc3-42c0-acf6-56248b5aa327\nmd\"\"\"\n!!! info\n\t## Programação _Julia_ e _notebooks Pluto_\n\tSaber mais sobre: [_Julia_/_Pluto_](https://github.com/Ricardo-Luis/notebooks/blob/main/ME2/README.md)\n\"\"\"\n\n# ╔═╡ e88b50d7-bd66-4e3c-8740-b1c5e36b6b5f\nversion=VERSION;\n\n# ╔═╡ a7d43c39-1780-446a-928a-1bc5cf841390\nmd\"\"\"\n## _Notebook_\n\n*Notebook* realizado em linguagem de programação *Julia* versão $(version) para a unidade curricular de Máquinas Elétricas 2 (ISEL\\LEE) \\\n**Ricardo Luís** (Professor Adjunto, ISEL\\DEEEA\\GDME) \\\nISEL, 23/Out/2021\n\"\"\"\n\n# ╔═╡ bfc8ce5b-3b3e-4448-bd60-23ed853a9ed9\nmd\"\"\"\nEste conteúdo possui licença [![](https://img.shields.io/badge/License-CC%20BY--SA%204.0-lightgrey.svg)](http://creativecommons.org/licenses/by-sa/4.0/).\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nDierckx = \"39dd38d3-220a-591b-8e3c-4c3a8c710a94\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\n\n[compat]\nDierckx = \"~0.5.1\"\nPlots = \"~1.22.6\"\nPlutoUI = \"~0.7.16\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"f2202b55d816427cd385a9a4f3ffb226bee80f99\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+0\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"d9e40e3e370ee56c5b57e0db651d8f92bce98fea\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.10.1\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"a851fec56cb73cfdf43762999ec72eff5b86882a\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.15.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"31d0151f5716b655421d9d75b7fa74cc4e744df2\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.39.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Dierckx]]\ndeps = [\"Dierckx_jll\"]\ngit-tree-sha1 = \"5fefbe52e9a6e55b8f87cb89352d469bd3a3a090\"\nuuid = \"39dd38d3-220a-591b-8e3c-4c3a8c710a94\"\nversion = \"0.5.1\"\n\n[[Dierckx_jll]]\ndeps = [\"CompilerSupportLibraries_jll\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"a580560f526f6fc6973e8bad2b036514a4e3b013\"\nuuid = \"cd4c43a9-7502-52ba-aa6d-59fb2a88580b\"\nversion = \"0.0.1+0\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"a32185f5428d3986f47c2ab78b1f216d5e6cc96f\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.5\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"dba1e8614e98949abfa60480b13653813d8f0157\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+0\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"d189c6d2004f63fd3c91748c458b09f26de0efaa\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.61.0\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"cafe0823979a5c9bff86224b3b8de29ea5a44b2e\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.61.0+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"7bf67e9a481712b3dbe9cb3dac852dc4b1162e02\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+0\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"14eece7a3308b4d8be910e265c724a6ba51a9798\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.16\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"8a954fed8ac097d5be04921d595f741115c1b2ad\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+0\"\n\n[[Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[HypertextLiteral]]\ngit-tree-sha1 = \"f6532909bf3d40b308a0f360b6a0e626c0e263a8\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.1\"\n\n[[IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"f0c6489b12d28fb4c2103073ec7452f3423bd308\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.1\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"669315d963863322302137c4591ffce3cb5b8e68\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.8\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"761a393aeccd6aa92ec3515e428c26bf99575b3b\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+0\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"6193c3815f13ba1b78a51ce391db8be016ae9214\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.4\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"5a5bc6bf062f0f95e62d0fe0a2d99699fed82dd9\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.8\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+0\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"98f59ff3639b3d9485a03a72f3ab35bab9465720\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.6\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"b084324b4af5a438cd63619fd006614b3b20b87b\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.0.15\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\"]\ngit-tree-sha1 = \"ba43b248a1f04a9667ca4a9f782321d9211aa68e\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.22.6\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"4c8a7d080daca18545c56f1cac28710c362478f3\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.16\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"44a75aa7a527910ee3d1751d1f0e4148698add9e\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.2\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"7ad0dfa8d03b7bcf8c597f59f5292801730c55b8\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.4.1\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3c76dde64d03699e074ac02eb2e8ba8254d428da\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.13\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"1958272568dc176a1d881acb797beb909c785510\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.0.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"eb35dcc66558b2dda84079b9a1be17557d32091a\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.12\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.3\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"fed34d0e71b91734bf0a7e10eb1bb05296ddbcd0\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.6.0\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\"]\ngit-tree-sha1 = \"2839f1c1296940218e35df0bbb220f2a79686670\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.18.0+4\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─c7838496-100f-4901-abcf-0d4e59fbc4a9\n# ╟─44201f7b-84df-4b8d-aeec-0f142ac2008b\n# ╟─ed4846d5-70d2-4deb-9a4a-41cdc8c99bdd\n# ╠═1301d1ad-89e8-4282-ab35-1a6b8214bea0\n# ╟─1a427cf6-b2d3-4d9b-9cb5-4682d5f49869\n# ╟─e2fc78d6-480b-4fe0-b844-0d4329c0d572\n# ╟─8bde3ad9-2d03-4557-ab50-a89ac8e834a3\n# ╟─61238dc4-3c9d-4b59-9486-501988806c27\n# ╟─c4d5e3f9-7808-48f6-8d33-05607d8e5a4e\n# ╟─f6fcec56-b080-4016-baf0-0ab728f255f3\n# ╟─d9e431c5-be62-40c8-b5d6-59d5808e4436\n# ╟─cde4847b-6c38-4bc6-a869-514774630c89\n# ╟─5b4c1912-126d-4fe8-87c5-f65b299f3642\n# ╠═1c70002d-e3fb-4d81-b0f9-ed00d69173ff\n# ╟─d8d6a6e9-df8d-47d2-832a-0d2126ce760e\n# ╟─0ff562ff-7af2-4749-87f5-8766cb695893\n# ╟─cf0f089a-1901-4ad1-8fe9-b9028679b109\n# ╟─68969be8-0bee-4cca-85de-7a8d2aa35ee2\n# ╠═de954f1d-a3ac-4830-acd0-85e64afdf0cd\n# ╟─0a35c6dc-0967-4f8a-9fff-904f9062eeab\n# ╠═8f5b0bd5-7a65-4ba3-bdd1-7cc3128fa8d8\n# ╠═7d6a01a4-4876-42dc-ab66-f7f736d41a32\n# ╟─9d82a20f-3a14-4796-88e9-e27720632bbd\n# ╟─04b517f9-ed9f-4a5d-929b-82b10de843b9\n# ╟─71356175-ffe4-4c3a-a895-8a4be8713a44\n# ╠═cfc7844e-3974-46ef-a53a-ee6a1a85d7f3\n# ╟─d85a5505-1ab5-43d0-97ad-a0cb4a220c06\n# ╟─7c572ab7-2292-423c-b611-68573b289265\n# ╟─50022e39-c2f4-455f-8d26-7c9246190b11\n# ╠═14ad0875-e27a-442e-81e9-29d1abaeac17\n# ╟─4bac08e5-7a7a-496f-8d67-aa2bc4b10236\n# ╟─5abe64cf-9291-48d6-bf60-7335551ee791\n# ╟─ac32afe0-e30f-402e-995e-8b0cacf8af10\n# ╟─4989ff81-ac16-446c-8d8a-e3cb9e5950b6\n# ╟─1d458a5a-545f-4ab6-900b-9d84ebbaf51d\n# ╟─4652d9e4-e2c6-47c4-93d1-1e360ffb7e57\n# ╠═d25759bf-6e81-439c-a2c9-c19704379437\n# ╟─4629c049-8882-4823-bdea-93e3d70cc901\n# ╟─ea81ca51-dccc-4187-b788-7ed64716e698\n# ╠═6030b931-51a0-42fc-9b74-5635b590e6f5\n# ╟─d47a90f0-f8bc-44d0-b71c-c0bc59d0d23c\n# ╟─3c921729-6534-4eac-abb0-4eb362295b91\n# ╠═4da7f391-e3bf-4e12-aa6b-a7ef5e45d3b9\n# ╟─a45ad7c2-2f83-4e04-bdaf-8dcc30a150f5\n# ╟─5b866db3-ddd6-4bfd-b027-761c07d6755c\n# ╟─326135bd-24e3-492d-a7d5-1a14f065e80f\n# ╟─df3609ef-80f2-464a-b522-f289ea9344b4\n# ╟─f499659c-b042-4002-bb27-980daf8502d4\n# ╟─72a079e6-0c41-4c50-9ee2-838d5cc60c85\n# ╟─58e9df34-7471-4942-ac06-2505f52875f2\n# ╟─f305c434-9d0c-497d-8335-bf25aa80e915\n# ╟─0ce81a6e-965c-4dc0-b9f3-f8c09143460e\n# ╟─1cd42258-7583-4288-9c6d-4d47facb69e1\n# ╟─facb1900-1093-46c7-97b2-187b67e21294\n# ╟─6aae7842-4889-4be6-bd1d-eab44c610af8\n# ╟─7ad852d3-e3b8-4799-8aae-a52c1ebe34ac\n# ╠═b4e5cbd1-c1c1-47e1-a8aa-8fc2ef628e87\n# ╟─55397202-48ae-4a3d-a053-9f46e6638560\n# ╟─1a154f27-cd9a-4de8-b850-599b5e810811\n# ╠═626c5cab-64e2-446c-9d38-f01dde099d3e\n# ╟─1c659ae6-1b29-43a5-92f7-30b1f24c3696\n# ╟─426c40b4-5fa1-4d8a-b03c-11f3008484f6\n# ╟─8dfd7146-2e55-4ea0-8cf2-3557d89e96e1\n# ╠═4e4469c8-994d-42c6-b373-8f295768b8b0\n# ╟─66e32f84-8b2a-4a3d-81fe-16437ecc3c18\n# ╟─60db00b7-c78b-4c26-9530-c62fcfd1bfd2\n# ╟─4fdea2ae-3bf8-42cd-bf6f-411eaf8223c3\n# ╠═e648310c-8172-4cf0-ab72-f40229ba2577\n# ╟─36295cf6-19ba-4240-9806-745ec0bfdccd\n# ╟─4919a95d-cd66-401c-af76-6155087462a3\n# ╟─8ad59666-3801-44a3-b26a-197a8f60db02\n# ╟─babc5b0b-3263-47d5-bd33-56917ece1e6b\n# ╟─49cc56bc-bd1e-4e07-9d9c-0ccfaa92e7b0\n# ╠═0bda0726-fcf9-491d-ad24-301521cb5892\n# ╟─f34820a6-bd96-463f-b747-2b910914d152\n# ╠═50588330-7af4-4c41-af8d-ffbb4c074394\n# ╟─e99f40c0-1752-4096-8fc9-c4550ae86168\n# ╟─8e683ba6-fe89-41d5-8f0a-5e3e59ca747c\n# ╠═6b359fc5-ec8d-47ec-89ec-b1b214a37a82\n# ╟─80c412ed-1cc3-42c0-acf6-56248b5aa327\n# ╟─a7d43c39-1780-446a-928a-1bc5cf841390\n# ╟─e88b50d7-bd66-4e3c-8740-b1c5e36b6b5f\n# ╟─bfc8ce5b-3b3e-4448-bd60-23ed853a9ed9\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "917fc6f27c479ebc511c948160edb214669d0074", "size": 50539, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ME2/DC_machines_Ex7.jl", "max_stars_repo_name": "Ricardo-Luis/notebooks", "max_stars_repo_head_hexsha": "f3e597c1711a4a25f67058bd673359484a4750da", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ME2/DC_machines_Ex7.jl", "max_issues_repo_name": "Ricardo-Luis/notebooks", "max_issues_repo_head_hexsha": "f3e597c1711a4a25f67058bd673359484a4750da", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ME2/DC_machines_Ex7.jl", "max_forks_repo_name": "Ricardo-Luis/notebooks", "max_forks_repo_head_hexsha": "f3e597c1711a4a25f67058bd673359484a4750da", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4271117166, "max_line_length": 394, "alphanum_fraction": 0.7250242387, "num_tokens": 24249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7507494028227475}}
{"text": "# Goal: Implement Conways Game of Life in Julia\n# author: Jay Jagtap\n\n#=\nRules for Game of Life\n\n Now Neighbors           Next\n#   --- ---------           --------------\n#   1   0,1             ->  0  # Lonely\n#   1   4,5,6,7,8       ->  0  # Overcrowded\n#   1   2,3             ->  1  # Lives\n#   0   3               ->  1  # It takes three to give birth!\n#   0   0,1,2,4,5,6,7,8 ->  0  # Barren\n\n=#\n\n\nfunction nextGen(A)\n  #= \n    Function returns next Generation of Life based on above mentioned Rules\n    param A: 2D matrix of previous Generation\n    return next_Gen: 2D matrix derived from A(previous Generation)\n  =#\n  \n  # Initializing next_Gen with all Zero Values\n  next_Gen = zeros(Int, size(A,1), size(A,2))\n  \n  for i in 1:size(next_Gen, 1)\n    for j in 1:size(next_Gen, 2)\n      alive_count = get_no_of_alive_neighbors(A, i, j)\n      if A[i,j] == 0\n        if alive_count == 3\n            next_Gen[i,j] = 1\n        end\n      else\n        if alive_count == 2 || alive_count == 3\n            next_Gen[i,j] = 1\n        end\n      end\n    end\n  end\n  return next_Gen\nend\n\n\nfunction get_no_of_alive_neighbors(A, i, j)\n    #=\n    param A: 2D matrix\n    i: row index\n    j: column index\n    return alive_count: Number of 1's(alive cells) in neighborhood\n    =#\n\n    # Collecting Neighborhood co-ordinates\n    neighbor_coord = []\n      for k in 1:3\n        if k < 2\n          push!(neighbor_coord , (i-1,j-1))\n          push!(neighbor_coord , (i-1,j))\n          push!(neighbor_coord , (i-1,j+1))\n        elseif k > 2\n          push!(neighbor_coord , (i+1,j-1))\n          push!(neighbor_coord , (i+1,j))\n          push!(neighbor_coord , (i+1,j+1))\n        else\n          push!(neighbor_coord , (i,j-1))\n          push!(neighbor_coord , (i,j+1))\n        end\n      end\n      \n    # Deriving alive count from neighbors\n    alive = 0\n    for coord in neighbor_coord\n        if (coord[1] >= 1 && coord[1] <= size(A,1) ) && (coord[2] >= 1 && coord[2] <= size(A,2))\n            if A[coord[1] , coord[2]] == 1\n                alive=alive+1\n            end\n        end\n    end\n    return alive\nend\n\n\nfunction main()\n  initial_Gen = \n  [  0 0 0 1 1 1 0 0; \n     0 1 0 1 0 1 1 1;\n     0 1 0 1 0 1 0 1;\n     0 1 0 1 0 1 1 1;\n     0 1 0 1 0 1 0 1;\n     0 1 0 1 0 1 0 1;\n     1 1 1 1 1 0 0 0;\n     1 1 1 1 1 1 1 1]\n\n no_of_iterations = 20\n println(\"Generation: initial_Gen\")\n display(initial_Gen)\n println()\n for i in 1:no_of_iterations\n    println(\"Generation: \" , i)\n    current_Gen = nextGen(initial_Gen)\n    display(current_Gen)\n    println()\n    initial_Gen = current_Gen\n end\n\nend\n\nmain()\n\n\n\n\n", "meta": {"hexsha": "744174fd41bf11f97f425c83ccb082a069ba2e5d", "size": 2588, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code/julia/main.jl", "max_stars_repo_name": "ssp4all/csc-510-hw-02", "max_stars_repo_head_hexsha": "fab31b52df97c30f4191545e0a512a4d78142eb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/julia/main.jl", "max_issues_repo_name": "ssp4all/csc-510-hw-02", "max_issues_repo_head_hexsha": "fab31b52df97c30f4191545e0a512a4d78142eb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-08-24T15:26:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-25T03:13:50.000Z", "max_forks_repo_path": "code/julia/main.jl", "max_forks_repo_name": "ssp4all/csc-510-hw-02", "max_forks_repo_head_hexsha": "fab31b52df97c30f4191545e0a512a4d78142eb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.701754386, "max_line_length": 96, "alphanum_fraction": 0.53438949, "num_tokens": 903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361276, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.750749397330366}}
{"text": "#   Copyright (c) 2020-2022 Velexi Corporation\n#\n#   Licensed under the Apache License, Version 2.0 (the \"License\");\n#   you may not use this file except in compliance with the License.\n#   You may obtain a copy of the License at\n#\n#       http://www.apache.org/licenses/LICENSE-2.0\n#\n#   Unless required by applicable law or agreed to in writing, software\n#   distributed under the License is distributed on an \"AS IS\" BASIS,\n#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#   See the License for the specific language governing permissions and\n#   limitations under the License.\n\n\"\"\"\nsubtract.jl defines methods for the -(x, y) function\n\"\"\"\n\n# --- Exports\n\nimport Base.:(-)\n\n# --- Method definitions\n\n-(M::AbstractMultivector, N::AbstractMultivector) = M + -N\n\n# ------ Specializations involving a Pseudoscalar instance\n\n# B::Pseudoscalar, C::Pseudoscalar\n-(B::Pseudoscalar, C::Pseudoscalar) = Pseudoscalar(B, value=value(B) - value(C))\n\n# ------ Specializations involving an AbstractScalar instance\n\n# B::AbstractScalar, C::One\n# B::One, C::AbstractScalar\n-(B::AbstractScalar, C::One) = Scalar{typeof(value(B))}(value(B) - 1)\n-(B::One, C::AbstractScalar) = Scalar{typeof(value(C))}(1 - value(C))\n\n# B::AbstractScalar, C::Zero\n# B::Zero, C::AbstractScalar\n-(B::AbstractScalar, C::Zero) = B\n-(B::Zero, C::AbstractScalar) = -C\n\n# B::AbstractScalar, x::Real\n# x::Real, B::AbstractScalar\n-(B::AbstractScalar, x::Real) = Scalar{typeof(value(B))}(value(B) - x)\n-(x::Real, B::AbstractScalar) = Scalar{typeof(value(B))}(x - value(B))\n\n# ------ Specializations involving a Scalar instance\n\n# B::Scalar, C::Scalar\n-(B::Scalar, C::Scalar) = Scalar{typeof(value(B))}(value(B) - value(C))\n\n# ------ Specializations involving a One instance\n\n# B::One, C::One\n-(B::One, C::One) = Zero{typeof(value(B))}()\n\n# B::One, C::Zero\n# B::Zero, C::One\n-(B::One, C::Zero) = B\n-(B::Zero, C::One) = -C\n\n# ------ Specializations involving a Zero instance\n\n# B::Zero, C::Zero\n-(B::Zero, C::Zero) = B\n\n# B::Zero, v::Vector\n# v::Vector, B::Zero\n-(B::Zero, v::Vector{<:Real}) = -v\n-(v::Vector{<:Real}, B::Zero) = v\n", "meta": {"hexsha": "b47b1c45300896371c12aa74949d6175596643ee", "size": 2114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operations/subtract.jl", "max_stars_repo_name": "velexi-corporation/GeometricAlgebra.jl", "max_stars_repo_head_hexsha": "e635c3fde4bb242632cc2b7a10c7229ee1f92683", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/operations/subtract.jl", "max_issues_repo_name": "velexi-corporation/GeometricAlgebra.jl", "max_issues_repo_head_hexsha": "e635c3fde4bb242632cc2b7a10c7229ee1f92683", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2022-03-20T02:20:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T05:54:07.000Z", "max_forks_repo_path": "src/operations/subtract.jl", "max_forks_repo_name": "velexi-corporation/GeometricAlgebra.jl", "max_forks_repo_head_hexsha": "e635c3fde4bb242632cc2b7a10c7229ee1f92683", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9589041096, "max_line_length": 80, "alphanum_fraction": 0.6617786187, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7507493937913609}}
{"text": "\"\"\"\n    cl1(x::Float64)::Float64\n\nReturns the value of the Clausen function ``\\\\operatorname{Cl}_1(x)``\nfor a real angle ``x`` of type `Float64`.  This function is defined as\n\n```math\n\\\\operatorname{Cl}_1(x) = \\\\Re[\\\\operatorname{Li}_1(e^{ix})] = \\\\Re[-\\\\log(1 - e^{ix})]\n```\n\nNote: ``\\\\operatorname{Cl}_1(x)`` is not defined for ``x=2n\\\\pi`` with\n``n\\\\in\\\\mathbb{Z}``.\n\nAuthor: Alexander Voigt\n\nLicense: MIT\n\n# Example\n```jldoctest; setup = :(using ClausenFunctions), output = false\njulia> cl1(1.0)\n0.04201950582536895\n```\n\"\"\"\nfunction cl1(x::Float64)::Float64\n    x = range_reduce_odd(x)\n\n    if x == zero(x)\n        return Inf\n    end\n\n    -log(2.0*sin(0.5*x))\nend\n", "meta": {"hexsha": "ddfbc8010c41188d5c59e9f02189e0af24e5078e", "size": 668, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Cl1.jl", "max_stars_repo_name": "Expander/Clausen.jl", "max_stars_repo_head_hexsha": "658c88bbbeecea05c8113061454c85acb5f41e38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-08T12:01:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T15:04:50.000Z", "max_issues_repo_path": "src/Cl1.jl", "max_issues_repo_name": "Expander/Clausen.jl", "max_issues_repo_head_hexsha": "658c88bbbeecea05c8113061454c85acb5f41e38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Cl1.jl", "max_forks_repo_name": "Expander/Clausen.jl", "max_forks_repo_head_hexsha": "658c88bbbeecea05c8113061454c85acb5f41e38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2424242424, "max_line_length": 87, "alphanum_fraction": 0.621257485, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693688269984, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.7507424381429297}}
{"text": "\"\"\"\n    qbins(x, y, z, n)\n\nBins x into n quantiles, each xbin into n quantiles of y, return z quantile\n\n# Examples\n```julia-repl\njulia> df = DataFrame(x=1:20, y=6:25, z=11:30)\njulia> xmed, ymed, zmed = qbins(df.T, df.M, df.R, 3)\n  xmed = [9, 9, 9, 15, 15, 15, 21, 21, 21]\n  ymed = [12, 14, 16, 19, 20.5, 22, 25, 27, 29]\n  zmed = [2, 4, 6, 8.5, 10.5, 15, 17, 19]\n```\n\"\"\"\nfunction qbins(x, y, z, n)\n  xq = quantile(x, 0:1/n:1)\n  xmed = Float64[] # between quantiles x values\n  ymed = Float64[] # between quantiles y values\n  zmed = Float64[] # z median for each xy bins\n  for i = 1:n # loop for each x between-quantile bin\n    ybin = y[x .>= xq[i] .&& x .<= xq[i+1]]\n    ybinq = quantile(ybin, 0:1/n:1)\n    for j = 1:n # loop for each y between-quantile bin\n      push!(xmed, (xq[i] + xq[i+1]) / 2)\n      push!(ymed, (ybinq[j] + ybinq[j+1]) / 2)\n      push!(zmed, median(z[x .>= xq[i] .&& x .<= xq[i+1] .&& y .>= ybinq[j] .&& y .<= ybinq[j+1]]))\n    end\n  end\n  return xmed, ymed, zmed\nend\n", "meta": {"hexsha": "7885e5e8866c91cd48054cf37757c474c8e29ed4", "size": 988, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/maths/qbins.jl", "max_stars_repo_name": "jamesafranke/DAMMmodel.jl", "max_stars_repo_head_hexsha": "f7d19f68bbe3dc1030583411a77b939fd9731160", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2021-12-09T20:18:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T19:39:18.000Z", "max_issues_repo_path": "src/functions/maths/qbins.jl", "max_issues_repo_name": "jamesafranke/DAMMmodel.jl", "max_issues_repo_head_hexsha": "f7d19f68bbe3dc1030583411a77b939fd9731160", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-12-09T19:51:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T17:38:03.000Z", "max_forks_repo_path": "src/functions/maths/qbins.jl", "max_forks_repo_name": "jamesafranke/DAMMmodel.jl", "max_forks_repo_head_hexsha": "f7d19f68bbe3dc1030583411a77b939fd9731160", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-12-27T17:35:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T16:25:57.000Z", "avg_line_length": 31.8709677419, "max_line_length": 99, "alphanum_fraction": 0.5546558704, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025231, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.7507424346735154}}
{"text": "using MultivariateSeries\nX = @ring x0 x1 x2\nd = 4\nF = (x0+x1+x2)^d + 1.5*(x0+x1)^d -2.0*(x0-x2)^d\nw, Xi = decompose(F)\nF1 = tensor(w, Xi, X, d)\n@assert norm(F-F1)<1.e-6\n\n", "meta": {"hexsha": "f9d3a3ae9ff9427b095a4b725984f9ae157025ad", "size": 170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tst1.jl", "max_stars_repo_name": "blegat/MultivariateSeries.jl", "max_stars_repo_head_hexsha": "a469f5d75ef8e99677400038b76ed057683d4748", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/tst1.jl", "max_issues_repo_name": "blegat/MultivariateSeries.jl", "max_issues_repo_head_hexsha": "a469f5d75ef8e99677400038b76ed057683d4748", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/tst1.jl", "max_forks_repo_name": "blegat/MultivariateSeries.jl", "max_forks_repo_head_hexsha": "a469f5d75ef8e99677400038b76ed057683d4748", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-24T12:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T20:05:47.000Z", "avg_line_length": 18.8888888889, "max_line_length": 47, "alphanum_fraction": 0.5882352941, "num_tokens": 88, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7507424252090799}}
{"text": "# code for Video 4.4:\r\nfname = \"iris.csv\"\r\nusing DataFrames\r\ndata = readtable(fname, separator = ',')\r\n\r\n###Distributions:\r\nPkg.add(\"Distributions\")\r\nusing Distributions\r\n\r\ntypeof(Normal) # DataType\r\nsuper(Normal) # Distributions.Distribution{Distributions.Univariate,Distributions.Continuous}\r\nsuper(Poisson) # Distributions.Distribution{Distributions.Univariate,Distributions.Discrete}\r\n\r\nn1 = Normal(10, 1.5) # Distributions.Normal(μ=10.0, σ=1.5)\r\nparams(n1) # (10.0,1.5)\r\nfieldnames(n1) # 2-element Array{Symbol,1}:  :μ :σ\r\n\r\nrand(n1, 100)\r\n# 100-element Array{Float64,1}:\r\n#   8.48529\r\n#   7.90919\r\n#  13.2968\r\n#   6.55532\r\n#   ...\r\n # 13.1982\r\n # 10.7262\r\n # 11.1575\r\n # 11.5623\r\n\r\nrandn(50)\r\n50-element Array{Float64,1}:\r\n  1.34669\r\n -1.73781\r\n  0.801373\r\n -1.11795\r\n ...\r\n\r\nb = Binomial(10, 0.7) # binomial distribution with 10 trials and succes rate 0.7\r\n# Distributions.Binomial(n=10, p=0.7)\r\nrand(b, 1000)\r\n1000-element Array{Int64,1}:\r\n 6\r\n 9\r\n 7\r\n 7\r\n 6\r\n 6\r\n 9\r\n\r\n\r\n### Kernel density:\r\nusing Winston, KernelDensity\r\nx = convert(Array, data[1:50, :sepal_width])\r\ny = convert(Array, data[1:50, :sepal_length])\r\nkx = kde(x) # kernel density function\r\nky = kde(y)\r\nplot(kx.x, kx.density, \"r--\", ky.x, ky.density, \"b;\")\r\n\r\n###\r\nusing Gadfly\r\nset_default_plot_size(20cm, 12cm)\r\nGadfly.plot(data, x = \"petal_length\", y = \"petal_width\", color = \"species\", Geom.point)\r\n\r\n### K-means Clustering\r\nPkg.add(\"Clustering\")\r\nusing Clustering\r\nfeatures = convert(Array, data[:, 1:4])' # 4x150 Array{Float64,2}:\r\n# group the data onto 3 clusters\r\ninitseeds(:rand, features, 3) # choose 3 random starting points (centroids)\r\n# 3-element Array{Int64,1}:\r\n#  36\r\n#  93\r\n#  41\r\nresult = kmeans( features, 3) # make 3 clusters\r\n# Clustering.KmeansResult{Float64}(4x3 Array{Float64,2}:\r\n#  5.006  5.90161  6.85\r\n#  3.418  2.74839  3.07368\r\n#  1.464  4.39355  5.74211\r\n#  0.244  1.43387  2.07105,[1,1,1,1,1,1,1,1,1,1  …  3,3,\r\nGadfly.plot(data, x = \"petal_length\", y = \"petal_width\", color = result.assignments, Geom.point)\r\n\r\n### HypothesisTests\r\nPkg.add(\"HypothesisTests\")\r\nusing HypothesisTests\r\n# test sepal_length I. setosa versus I. versicolor:\r\nxset = convert(Array, data[1:50, :sepal_length])\r\nxver = convert(Array, data[51:100, :sepal_length])\r\n\r\nuneqtt = UnequalVarianceTTest(xset, xver)\r\n# Two sample t-test (unequal variance)\r\n# ------------------------------------\r\n# Population details:\r\n#     parameter of interest:   Mean difference\r\n#     value under h_0:         0\r\n#     point estimate:          -0.9299999999999997\r\n#     95% confidence interval: (-1.1057073727210804,-0.7542926272789189)\r\n\r\n# Test summary:\r\n#     outcome with 95% confidence: reject h_0\r\n#     two-sided p-value:           3.74674261398387e-17 (extremely significant)\r\n\r\n# Details:\r\n#     number of observations:   [50,50]\r\n#     t-statistic:              -10.52098626754911\r\n#     degrees of freedom:       86.53800179765493\r\n#     empirical standard error: 0.08839475466938762\r\n\r\npvalue(uneqtt) # 3.74674261398387e-17\r\nci(uneqtt) # (-1.1057073727210804,-0.7542926272789189)", "meta": {"hexsha": "4d7875e77fcfdef133048f1a820e06d53a7b83a8", "size": 3054, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Section 4/4_4.jl", "max_stars_repo_name": "lytemar/Julia-for-Data-Science-Video", "max_stars_repo_head_hexsha": "e7cb2427b10979d4be0f1e00be1cc1090f4da736", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-09-01T15:05:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T14:09:53.000Z", "max_issues_repo_path": "Section 4/4_4.jl", "max_issues_repo_name": "lytemar/Julia-for-Data-Science-Video", "max_issues_repo_head_hexsha": "e7cb2427b10979d4be0f1e00be1cc1090f4da736", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Section 4/4_4.jl", "max_forks_repo_name": "lytemar/Julia-for-Data-Science-Video", "max_forks_repo_head_hexsha": "e7cb2427b10979d4be0f1e00be1cc1090f4da736", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-09-01T15:05:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-08T15:00:22.000Z", "avg_line_length": 28.0183486239, "max_line_length": 97, "alphanum_fraction": 0.6565160445, "num_tokens": 1083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514736, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7507424252090797}}
{"text": "function courant(Δt, flux, mesh, w)\n    c = zero(eltype(Δt))\n    for i_face in inner_faces(mesh)\n        c = max(c, courant(Δt, flux, mesh, w, i_face))\n    end\n    return c\nend\n\nfunction courant(Δt, flux, mesh, w, i_face)\n    i_cell_1, i_cell_2 = cells_next_to_inner_face(mesh, i_face)\n    n = normal_vector(mesh, i_face)\n    w_mean = (w[i_cell_1] + w[i_cell_2])/2\n    λ = eigvals(flux, w_mean, n)\n    maxλ = maximum(abs.(λ))\n    return maxλ * Δt * face_area(mesh, i_face) / min(cell_volume(mesh, i_cell_1), cell_volume(mesh, i_cell_2))\nend\n\nfunction courant(Δt, flux::AdvectionFlux, mesh, w, i_face)\n    v = LinearAdvectionFlux(flux.velocity_at_face(mesh, i_face))\n    return FiniteVolumes.courant(Δt, v, mesh, w, i_face)\nend\n\n# function courant(Δt, flux::LinearAdvectionFlux, mesh::AbstractCartesianMesh{1}, w)\n#     return abs(flux.velocity[1]) * Δt / FiniteVolumes.CartesianMeshes.dx(mesh)[1]\n# end\n\n# function courant(Δt, flux::LinearAdvectionFlux, mesh::PeriodicRegularMesh2D, w)\n#     vx, vy = model.velocity\n#     return max(abs(vx) * Δt / dx(mesh), abs(vy) * Δt / dy(mesh))\n# end\n", "meta": {"hexsha": "a6753ce2df86bbed33fe394b09e0d4badecfecca", "size": 1089, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/courant.jl", "max_stars_repo_name": "mancellin/FiniteVolumes.jl", "max_stars_repo_head_hexsha": "96d22209e1e1be3c237196b235708b215d9ef6af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-07T19:31:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T04:00:16.000Z", "max_issues_repo_path": "src/courant.jl", "max_issues_repo_name": "mancellin/FiniteVolumes.jl", "max_issues_repo_head_hexsha": "96d22209e1e1be3c237196b235708b215d9ef6af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/courant.jl", "max_forks_repo_name": "mancellin/FiniteVolumes.jl", "max_forks_repo_head_hexsha": "96d22209e1e1be3c237196b235708b215d9ef6af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1290322581, "max_line_length": 110, "alphanum_fraction": 0.6822773186, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025231, "lm_q2_score": 0.7905303112671295, "lm_q1q2_score": 0.7507424206135744}}
{"text": "\"\"\"\n    haltonsequence(b, n)\n\nGenerate the first `n` numbers in Halton's sequence with base `b`.\n\"\"\"\nhaltonsequence(b, n) = haltonnumber.(b, 1:n)\n\n\"\"\"\n    haltonnumber(base, index)\n\nGenerate the `n`-th Halton number in the sequence with base `b`.\n\n# Note\n    Implementation is based on the psudo code in:\n        http://en.wikipedia.org/wiki/Halton_sequence\n\"\"\"\nfunction haltonnumber(base::Integer, index::Integer)\n    res = 0\n    f = 1 / base\n    i = index\n\n    while (i > 0)\n        res += f * (i % base)\n        i = floor(Integer, i / base)\n        f = f / base\n    end\n\n    return res\nend\n", "meta": {"hexsha": "b2c7428e932fec074a7e0f8897616a3624dc5df9", "size": 593, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utilities/halton_sequence.jl", "max_stars_repo_name": "devmotion/BlackBoxOptim.jl", "max_stars_repo_head_hexsha": "252b373da6571b209f82660839923add60eba34d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 322, "max_stars_repo_stars_event_min_datetime": "2015-02-15T19:35:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T07:03:29.000Z", "max_issues_repo_path": "src/utilities/halton_sequence.jl", "max_issues_repo_name": "tpapp/BlackBoxOptim.jl", "max_issues_repo_head_hexsha": "b36833ef59966c16ed026dc9bc2e3c165c79c909", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 167, "max_issues_repo_issues_event_min_datetime": "2015-04-30T19:40:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T07:12:53.000Z", "max_forks_repo_path": "src/utilities/halton_sequence.jl", "max_forks_repo_name": "tpapp/BlackBoxOptim.jl", "max_forks_repo_head_hexsha": "b36833ef59966c16ed026dc9bc2e3c165c79c909", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 66, "max_forks_repo_forks_event_min_datetime": "2015-05-05T20:23:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T15:30:29.000Z", "avg_line_length": 19.7666666667, "max_line_length": 66, "alphanum_fraction": 0.6037099494, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.750718034026276}}
{"text": "# Deterministic Value Function Iteration\n# Greg Kaplan 2017\n# Translated by Tom Sweeney Dec 2020\n\nusing Random, Interpolations, Plots\n\n# PARAMETERS\n\n## preferences\nrisk_aver = 2\nbeta = 0.95\n\n## returns\nr = 0.03\nR = 1+r\n\n## income\ny = 1\n\n## asset grids\nna = 1000\namax = 20\nborrow_lim = 0\nagrid_par = 1 # 1 for linear, 0 for L-shaped\n\n## computation\nmax_iter = 1000\ntol_iter = 1.0e-6\nNsim = 100\nTsim = 500\n\n# OPTIONS\nDisplay = 1\nDoSimulate = 1\nMakePlots = 1\n\n# DRAW RANDOM NUMBERS\nRandom.seed!(2020)\narand = rand(Nsim)\n\n# SET UP GRIDS\n\n## assets\nagrid = range(0,1,length=na)\nagrid = agrid.^(1 ./ agrid_par)\nagrid = borrow_lim .+ (amax.-borrow_lim).*agrid\n\n# UTILITY FUNCTION\n\nif risk_aver==1\n    u(c) = log.(c)\nelse\n    u(c) = (c.^(1-risk_aver).-1)./(1-risk_aver)\nend\n\nu1(c) = c.^(-risk_aver)\n\n# INITIALIZE VALUE FUNCTION\n\nVguess = u(r.*agrid.+y)./(1-beta)\n\n# ITERATE ON VALUE FUNCTION\n\nV = copy(Vguess)\n\nVdiff = 1\niter = 0\n\nwhile iter <= max_iter && Vdiff > tol_iter\n    iter = iter + 1\n    Vlast = copy(V)\n    V = zeros(na)\n    global sav = zeros(na)\n    global savind = zeros(Int,na)\n    global con = zeros(na)\n\n    ## loop over assets\n    for ia = 1:na\n        \n        cash = R.*agrid[ia] + y\n        Vchoice = u(max.(cash.-agrid,1.0e-10)) + beta.*Vlast         \n        V[ia] = maximum(Vchoice)\n        savind[ia] = argmax(Vchoice)[1]\n        sav[ia] = agrid[savind[ia]]\n        con[ia] = cash .- sav[ia]\n    end\n    \n    Vdiff = maximum(abs.(V-Vlast))\n    if Display>=1\n        println(\"Iteration no. \" * string(iter), \" max val fn diff is \" * string(Vdiff))\n    end\nend\n\n# SIMULATE\nif DoSimulate==1\n    yindsim = zeros(Int,Nsim,Tsim)\n    aindsim = zeros(Int,Nsim,Tsim)\n    \n    ## initial assets: uniform on [borrow_lim, amax]    \n    ainitial = borrow_lim .+ arand.*(amax-borrow_lim)\n    \n    ## allocate to nearest point on agrid;\n    aindsim[:,1] = interpolate((agrid,), 1:na, Gridded(Constant())).(ainitial)\n    \n    ## loop over time periods\n    for it = 1:Tsim\n        if Display >= 1 && mod(it,100)==0\n            println(\" Simulating, time period \" * string(it))\n        end\n        ## asset choice\n        if it<Tsim\n            aindsim[:,it+1] = savind[aindsim[:,it]]\n        end\n    end\n    \n    ## assign actual asset and income values;\n    asim = agrid[aindsim]\n    csim = R.*asim[:,1:Tsim-1] .+ y .- asim[:,2:Tsim]\nend\n\n# MAKE PLOTS\nif MakePlots==1\n    \n    ## consumption policy function\n    p1 = plot(agrid, con, xlims=(0,amax), title=\"Consumption\", color=:blue, legend=false)\n    display(p1)\n    \n    ## savings policy function\n    p2 = plot(agrid, sav.-agrid, xlims=(0,amax), title=\"Savings\", color=:blue, legend=false)\n    plot!(agrid, zeros(na,1), color=:black, lw=0.5)\n    display(p2)\n    \n    ## nice zoom\n    xlimits = (0,1)\n    xlimind = trues(na)\n    if minimum(agrid) < xlimits[1]\n        xlimind = xlimind .& (agrid.>=maximum(agrid[agrid<xlimits[1]]))\n    elseif minimum(agrid) > xlimits[2]\n        xlimind .= 0\n    end\n    if maximum(agrid) > xlimits[2]\n        xlimind = xlimind .& (agrid.<=minimum(agrid[agrid.>xlimits[2]]))\n    elseif maximum(agrid) < xlimits[1]\n        xlimind .= 0\n    end\n\n    ## consumption policy function: zoomed in\n    p3 = plot(agrid[xlimind], con[xlimind], xlims=xlimits, title=\"Consumption: Zoomed\", marker=:circle, color=:blue, linewidth=2, legend=false)\n    plot!(show=true)\n    display(p3)\n\n    ## savings policy function: zoomed in\n    p4 = plot(agrid[xlimind], sav[xlimind].-agrid[xlimind], xlims=xlimits, title=\"Savings: Zoomed (a'-a)\", marker=:circle, color=:blue, linewidth=2, legend=false)\n    plot!(agrid, zeros(na), color=:black, lw=0.5)\n    display(p4)\n       \n    ## asset dynamics distribution\n    p5 = plot(repeat((1:Tsim),1,Nsim), asim', title=\"Asset Dynamics\", legend=false)\n    display(p5)\n    \n    ## consumption dynamics distribution\n    p6 = plot(repeat((1:Tsim-1),1,Nsim), csim', title=\"Consumption Dynamics\", legend=false)\n    display(p6)\n\nend", "meta": {"hexsha": "a63db603c04e16330e3da319f047908430d37927", "size": 3930, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Guides/HA_codes/Julia/vfi_deterministic.jl", "max_stars_repo_name": "pranjalrawat007/Recursive-Macro", "max_stars_repo_head_hexsha": "6caab42818e32b3a23584dca91837ad50db71616", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2022-01-25T10:14:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T06:38:17.000Z", "max_issues_repo_path": "Guides/HA_codes/Julia/vfi_deterministic.jl", "max_issues_repo_name": "pranjalrawat007/Recursive-Macro", "max_issues_repo_head_hexsha": "6caab42818e32b3a23584dca91837ad50db71616", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Guides/HA_codes/Julia/vfi_deterministic.jl", "max_forks_repo_name": "pranjalrawat007/Recursive-Macro", "max_forks_repo_head_hexsha": "6caab42818e32b3a23584dca91837ad50db71616", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-25T05:58:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T09:19:48.000Z", "avg_line_length": 23.8181818182, "max_line_length": 162, "alphanum_fraction": 0.6099236641, "num_tokens": 1280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7507180322098003}}
{"text": "\n\"\"\"\n    xxhat, Mhat = kalmanEM(yy, M1::LinearHomogSystem, maxit = 500, tol = 0.001) \n\nEM procedure for the state space model (Shumway, Stoffer)\n\n- yy -- data\n- M1 -- initial model\n- maxit -- maximum number of iterations\n- tol -- rel. tolerance for test for convergence of marginal likelihood\n\n- xxhat, Mhat -- smoothed process with estimated model\n\"\"\"\nfunction kalmanEM(yy, M::LinearHomogSystem, maxit = 500, tol = 0.001) \n\n    H, Phi, b, Q, R = M.H, M.Phi, M.b, M.Q, M.R\n    d2, d = size(M.H)\n    assert(ndims(yy) == 2)\n    assert(norm(b) == 0)\n    n = size(yy,2)\n\n    x0 = M.x0\n    P0 = M.P0\n    xxs = xxf = zeros(d, n) # #x(f/s)[k] predited and corrected (and smoothed)\n       \n    PPf = zeros(d, d, n)  #P[k,k]\n    PPpred = zeros(d, d, n)     #P[k, k-1]\n    PPs = zeros(d, d, n)  #P[k,k]\n    PPcs = zeros(d, d, n)  #P[k-1,k]\n\n        \n    K = zeros(d, d)\n    \n    cvg = 1.+tol\n    nll = NaN\n    for k in 1:maxit\n        xf = x0\n        Pf = P0\n\n        # E step, forward pass\n        nllold = nll\n        nll = 0.\n        for i in 1:n\n            xf, Pf, Ppred, l, K  = kalman_kernel(xf, yy[:, i], Pf, H, Phi, b, Q, R)\n            xxf[:, i], PPf[:, :, i], PPpred[:, :, i] = xf, Pf, Ppred  \n            l += d*log(2pi)/2         # constant messes up convergence test      \n            nll -= l\n        end\n    \n        if k > 1\n            cvg = (nllold-nll)/abs(nllold)\n            cvg < 0 && warn(\"Likelihood decreasing\")\n            if abs(cvg) < tol\n#                println([nll, cvg])\n                break\n            end\n        end\n        \n        # E step, backwards pass including PPcs\n\n        #start with xf, Pf from forward pass\n        xs = xf\n        Ps = Pf\n\n        PPcs[:, :, n] = (I - K*H)*Phi*PPf[:, :, n-1]\n        J = PPf[:, :, n]*Phi'/(Phi*Ps*Phi' + Q)\n        PPs[:, :, n] = Ps\n        for i in n-1:-1:1\n            Jprev = J   \n            xs, Ps, J = smoother_kernel(xs, Ps, xxf[:, i],  PPf[:, :, i], PPpred[:, :, i+1], Phi, b)\n            xxs[:, i], PPs[:, :, i] = xs, Ps\n            \n            j = i + 2 #i = j - 2 as J = J(i)\n            if 2 < j <= n\n                \n                 Jjm2 = J\n                 Jjm1 = Jprev\n                 PPcs[:, :, j-1] = PPf[:, :, j-1]*Jjm2' +  Jjm1*(PPcs[:, :, j]  - Phi*PPf[:, :, j-1])*Jjm2'\n                 #Pcs[,,j-1]=Pf[,,j-1]%*%t(J[,,j-2])+ J[,,j-1]%*%(Pcs[,,j]-Phi%*%Pf[,,j-1])%*%t(J[,,j-2])}\n                 \n            end\n        end\n        x0, P0, J0 = smoother_kernel(xs, Ps, x0, P0, PPpred[:, :, 1], Phi, b)\n        PPcs[:, :, 1] = PPf[:, :, 1]*J0' +  J*(PPcs[:, :, 2]  - Phi*PPf[:, :, 1])*J0'\n    \n\n        # M step\n\n        A11 = xxs[:, 1]*xxs[:, 1]' + PPs[:, :, 1]\n        A10 = xxs[:, 1]*x0' + PPcs[:, :, 1] \n        A00 = x0*x0' + P0\n        \n        u = yy[:,1]-H*xxs[:,1]\n        R = u*u' + H*PPs[:, :, 1]*H'\n        \n        for i in 1:n-1\n            A11 = A11 + xxs[:, i+1]*xxs[:, i+1]' + PPs[:, :, i+1]\n            A10 = A10 + xxs[:, i+1]*xxs[:, i]' + PPcs[:, :, i+1] \n            A00 = A00 + xxs[:, i]*xxs[:, i]' + PPs[:, :, i]\n            \n            u = yy[:,i+1]-H*xxs[:,i+1]\n            R = R + u * u' + H*PPs[:, :, i+1]*H'\n        end\n      \n        Phi = A10/A00\n        Q = (A11 - Phi*A10')/n\n        Q = (Q+Q')/2\n        R = R/n\n\n     \n#        println(\"PARAM $k: nll\", [nll, cvg], \"\\n x0 $x0\\n P0 $P0\\n R $R\\n Phi $Phi\\n Q $Q\")\n\n    end\n\n    \n    xxs, LinearHomogSystem(x0, P0, Phi, b, Q, H, R)\nend\n", "meta": {"hexsha": "8bacd1c7d04b080a4ec556c8d1f0c1767e99bbef", "size": 3414, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kalmanem.jl", "max_stars_repo_name": "yakir12/Kalman.jl", "max_stars_repo_head_hexsha": "4379d156f3ef1711513435dbce7bf6a1ed004e5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kalmanem.jl", "max_issues_repo_name": "yakir12/Kalman.jl", "max_issues_repo_head_hexsha": "4379d156f3ef1711513435dbce7bf6a1ed004e5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kalmanem.jl", "max_forks_repo_name": "yakir12/Kalman.jl", "max_forks_repo_head_hexsha": "4379d156f3ef1711513435dbce7bf6a1ed004e5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9322033898, "max_line_length": 107, "alphanum_fraction": 0.4001171646, "num_tokens": 1292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.7506576679132153}}
{"text": "using DrWatson\n@quickactivate \"StatReth\"\n\n# %%\nusing StatsBase\nusing Distributions\nusing Plots\nusing StatsPlots\nusing Turing  # for MCMCChains\n\n# %% 3.2\nn = 1000\np_grid = range(0, 1, length = n)\nprob_p = ones(n)\nprob_data = @. pdf(Binomial(9, p_grid), 6)\nposterior = prob_data .* prob_p\nposterior ./= sum(posterior)\n\nplot(p_grid, posterior)\n\n# %% 3.3 - 3.5\nweights = pweights(posterior)\nsamples = sample(p_grid, weights, 10_000)\n\nscatter(samples)\ndensity(samples)\n# plot!(p_grid, posterior * n)\n\n# %% 3.6, 3.7\nsum(posterior[p_grid .< 0.5])\n\nsum(samples .< 0.5) / 10_000    # either\nmean(samples .< 0.5)            # or\n\n# %% 3.8\nmean(0.5 .< samples .< 0.75)    # either\nmean(samples) do s              # or (this will be faster than above)\n    0.5 < s < 0.75\nend\nmean(samples) do s              # or (can do multi-line; return variable on the last line)\n    condition1 = 0.5 < s\n    condition2 = s < 0.75\n    both_conditions = condition1 & condition2\n    both_conditions\nend\n\n# %% 3.9, 3.10\nquantile(samples, 0.8)\nquantile(samples, (0.1, 0.9))\n\n# %% 3.11\np_grid = range(0, 1, length = n)\nprior = ones(n)\nlikelihood = @. pdf(Binomial(3, p_grid), 3)\nposterior = likelihood .* prior\nposterior ./= sum(posterior)\nsamples = sample(p_grid, pweights(posterior), 10_000)\n\n# %% 3.12, 3.13\nquantile(samples, (0.25, 0.75))\n\nchn = Chains(samples)\nhpd(chn; alpha = 0.5)\n\n# %% 3.14, 3.16, TODO: not sure about 3.15\np_grid[argmax(posterior)]\n\nmean(samples)\nmedian(samples)\n\n# %% 3.17\nsum(posterior .* abs.(0.5 .- p_grid))\n\n# %% 3.18, 3.19\nloss = map(p_grid) do d\n    sum(posterior .* abs.(d .- p_grid))\nend\nplot(loss)\n\np_grid[argmin(loss)]\n", "meta": {"hexsha": "3bcef32a2cbf67606b6f56a93bcca09e95bb2d31", "size": 1625, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/snippet_03_02.jl", "max_stars_repo_name": "karajan9/statisticalrethinking", "max_stars_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-06-03T14:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T16:52:26.000Z", "max_issues_repo_path": "scripts/snippet_03_02.jl", "max_issues_repo_name": "karajan9/statisticalrethinking", "max_issues_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-13T05:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T14:05:57.000Z", "max_forks_repo_path": "scripts/snippet_03_02.jl", "max_forks_repo_name": "karajan9/statisticalrethinking", "max_forks_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-01T13:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-03T23:40:53.000Z", "avg_line_length": 20.0617283951, "max_line_length": 90, "alphanum_fraction": 0.64, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856298, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7506576646676373}}
{"text": "# Principal Component Analysis\n\n\"\"\"\nLinear Principal Component Analysis\n\"\"\"\nstruct PCA{T<:Real} <: LinearDimensionalityReduction\n    mean::AbstractVector{T}     # sample mean: of length d (mean can be empty, which indicates zero mean)\n    proj::AbstractMatrix{T}     # projection matrix: of size d x p\n    prinvars::AbstractVector{T} # principal variances: of length p\n    tprinvar::T                 # total principal variance, i.e. sum(prinvars)\n    tvar::T                     # total input variance\nend\n\n## constructor\n\nfunction PCA(mean::AbstractVector{T}, proj::AbstractMatrix{T}, pvars::AbstractVector{T}, tvar::T) where {T<:Real}\n    d, p = size(proj)\n    (isempty(mean) || length(mean) == d) ||\n        throw(DimensionMismatch(\"Dimensions of mean and projection matrix are inconsistent.\"))\n    length(pvars) == p ||\n        throw(DimensionMismatch(\"Dimensions of projection matrix and principal variables are inconsistent.\"))\n    tpvar = sum(pvars)\n    tpvar <= tvar || isapprox(tpvar,tvar) || throw(ArgumentError(\"principal variance cannot exceed total variance.\"))\n    PCA(mean, proj, pvars, tpvar, tvar)\nend\n\n## properties\n\"\"\"\n    size(M)\n\nReturns a tuple with the dimensions of input (the dimension of the observation space)\nand output (the dimension of the principal subspace).\n\"\"\"\nsize(M::PCA) = size(M.proj)\n\n\"\"\"\n    mean(M::PCA)\n\nReturns the mean vector (of length `d`).\n\"\"\"\nmean(M::PCA) = fullmean(size(M.proj,1), M.mean)\n\n\"\"\"\n    projection(M::PCA)\n\nReturns the projection matrix (of size `(d, p)`). Each column of the projection matrix corresponds to a principal component.\nThe principal components are arranged in descending order of the corresponding variances.\n\"\"\"\nprojection(M::PCA) = M.proj\n\n\"\"\"\n    eigvecs(M::PCA)\n\nGet the eigenvalues of the PCA model `M`.\n\"\"\"\neigvecs(M::PCA) = projection(M)\n\n\"\"\"\n    principalvars(M::PCA)\n\nReturns the variances of principal components.\n\"\"\"\nprincipalvars(M::PCA) = M.prinvars\nprincipalvar(M::PCA, i::Int) = M.prinvars[i]\n\n\"\"\"\n    eigvals(M::PCA)\n\nGet the eigenvalues of the PCA model `M`.\n\"\"\"\neigvals(M::PCA) = principalvars(M)\n\n\"\"\"\n    tprincipalvar(M::PCA)\n\nReturns the total variance of principal components, which is equal to `sum(principalvars(M))`.\n\"\"\"\ntprincipalvar(M::PCA) = M.tprinvar\n\n\"\"\"\n    tresidualvar(M::PCA)\n\nReturns the total residual variance.\n\"\"\"\ntresidualvar(M::PCA) = M.tvar - M.tprinvar\n\n\"\"\"\n    var(M::PCA)\n\nReturns the total observation variance, which is equal to `tprincipalvar(M) + tresidualvar(M)`.\n\"\"\"\nvar(M::PCA) = M.tvar\n\n\"\"\"\n    r2(M::PCA)\n    principalratio(M::PCA)\n\nReturns the ratio of variance preserved in the principal subspace, which is equal to `tprincipalvar(M) / var(M)`.\n\"\"\"\nr2(M::PCA) = M.tprinvar / M.tvar\nconst principalratio = r2\n\n\"\"\"\n    loadings(M::PCA)\n\nReturns model loadings, i.e. the weights for each original variable when calculating the principal component.\n\"\"\"\nloadings(M::PCA) = sqrt.(principalvars(M))' .* projection(M)\n\n## use\n\n\"\"\"\n    predict(M::PCA, x::AbstractVecOrMat{<:Real})\n\nGiven a PCA model `M`, retur transform observations `x` into principal components space, as\n\n\\$\\\\mathbf{y} = \\\\mathbf{P}^T (\\\\mathbf{x} - \\\\boldsymbol{\\\\mu})\\$\n\nHere, `x` can be either a vector of length `d` or a matrix where each column is an observation,\nand `\\\\mathbf{P}` is the projection matrix.\n\"\"\"\npredict(M::PCA, x::AbstractVecOrMat{T}) where {T<:Real} = transpose(M.proj) * centralize(x, M.mean)\n\n\"\"\"\n    reconstruct(M::PCA, y::AbstractVecOrMat{<:Real})\n\nGiven a PCA model `M`, returns a (approximately) reconstructed observations\nfrom principal components space, as\n\n\\$\\\\tilde{\\\\mathbf{x}} = \\\\mathbf{P} \\\\mathbf{y} + \\\\boldsymbol{\\\\mu}\\$\n\nHere, `y` can be either a vector of length `p` or a matrix where each column\ngives the principal components for an observation, and \\$\\\\mathbf{P}\\$ is the projection matrix.\n\"\"\"\nreconstruct(M::PCA, y::AbstractVecOrMat{T}) where {T<:Real} = decentralize(M.proj * y, M.mean)\n\n## show & dump\n\nfunction show(io::IO, M::PCA)\n    idim, odim = size(M)\n    print(io, \"PCA(indim = $idim, outdim = $odim, principalratio = $(r2(M)))\")\nend\n\n#### PCA Training\n\n## auxiliary\n\nconst default_pca_pratio = 0.99\n\nfunction check_pcaparams(d::Int, mean::AbstractVector, md::Int, pr::Real)\n    isempty(mean) || length(mean) == d ||\n        throw(DimensionMismatch(\"Incorrect length of mean.\"))\n    md >= 1 || error(\"`maxoutdim` parameter must be a positive integer.\")\n    0.0 < pr <= 1.0 || throw(ArgumentError(\"principal ratio must be a positive real value ≤ 1.0.\"))\nend\n\nfunction choose_pcadim(v::AbstractVector{T}, ord::Vector{Int}, vsum::T, md::Int,\n                       pr::Real) where {T<:Real}\n    md = min(length(v), md)\n    k = 1\n    a = v[ord[1]]\n    thres = vsum * convert(T, pr)\n    while k < md && a < thres\n        a += v[ord[k += 1]]\n    end\n    return k\nend\n\n\n## core algorithms\n\"\"\"\n    pcacov(C, mean; ...)\n\nCompute and return a PCA model based on eigenvalue decomposition of a given covariance matrix `C`.\n\n**Parameters:**\n- `C`: The covariance matrix of the samples.\n- `mean`: The mean vector of original samples, which can be a vector of length `d`,\n           or an empty vector `Float64[]` indicating a zero mean.\n\n*Note:* This function accepts two keyword arguments: `maxoutdim` and `pratio`.\n\"\"\"\nfunction pcacov(C::AbstractMatrix{T}, mean::AbstractVector{T};\n                maxoutdim::Int=size(C,1),\n                pratio::Real=default_pca_pratio) where {T<:Real}\n\n    check_pcaparams(size(C,1), mean, maxoutdim, pratio)\n    Eg = eigen(Symmetric(C))\n    ev = Eg.values\n    ord = sortperm(ev; rev=true)\n    vsum = sum(ev)\n    k = choose_pcadim(ev, ord, vsum, maxoutdim, pratio)\n    v, P = extract_kv(Eg, ord, k)\n    PCA(mean, P, v, vsum)\nend\n\n\"\"\"\n    pcasvd(Z, mean, tw; ...)\n\nCompute and return a PCA model based on singular value decomposition of a centralized sample matrix `Z`.\n\n**Parameters:**\n- `Z`: a matrix of centralized samples.\n- `mean`: The mean vector of the **original** samples, which can be a vector of length `d`,\n          or an empty vector `Float64[]` indicating a zero mean.\n- `n`: a number of samples.\n\n*Note:* This function accepts two keyword arguments: `maxoutdim` and `pratio`.\n\"\"\"\nfunction pcasvd(Z::AbstractMatrix{T}, mean::AbstractVector{T}, n::Real;\n                maxoutdim::Int=min(size(Z)...),\n                pratio::Real=default_pca_pratio) where {T<:Real}\n\n    check_pcaparams(size(Z,1), mean, maxoutdim, pratio)\n    Svd = svd(Z)\n    v = Svd.S::Vector{T}\n    U = Svd.U::Matrix{T}\n    for i = 1:length(v)\n        @inbounds v[i] = abs2(v[i]) / n\n    end\n    ord = sortperm(v; rev=true)\n    vsum = sum(v)\n    k = choose_pcadim(v, ord, vsum, maxoutdim, pratio)\n    si = ord[1:k]\n    PCA(mean, U[:,si], v[si], vsum)\nend\n\n## interface functions\n\"\"\"\n    fit(PCA, X; ...)\n\nPerform PCA over the data given in a matrix `X`. Each column of `X` is an **observation**.\n\n**Keyword arguments**\n\n- `method`: The choice of methods:\n    - `:auto`: use `:cov` when `d < n` or `:svd` otherwise (*default*).\n    - `:cov`: based on covariance matrix decomposition.\n    - `:svd`: based on SVD of the input data.\n- `maxoutdim`: The output dimension, i.e. dimension of the transformed space (*min(d, nc-1)*)\n- `pratio`: The ratio of variances preserved in the principal subspace (*0.99*)\n- `mean`: The mean vector, which can be either of\n    - `0`: the input data has already been centralized\n    - `nothing`: this function will compute the mean (*default*)\n    - a pre-computed mean vector\n\n**Notes:**\n\n- The output dimension `p` depends on both `maxoutdim` and `pratio`, as follows. Suppose\n  the first `k` principal components preserve at least `pratio` of the total variance, while the\n  first `k-1` preserves less than `pratio`, then the actual output dimension will be \\$\\\\min(k, maxoutdim)\\$.\n\n- This function calls [`pcacov`](@ref) or [`pcasvd`](@ref) internally, depending on the choice of method.\n\"\"\"\nfunction fit(::Type{PCA}, X::AbstractMatrix{T};\n             method::Symbol=:auto,\n             maxoutdim::Int=size(X,1),\n             pratio::Real=default_pca_pratio,\n             mean=nothing) where {T<:Real}\n\n    @assert !SparseArrays.issparse(X) \"Use Kernel PCA for sparse arrays\"\n\n    d, n = size(X)\n\n    # choose method\n    if method == :auto\n        method = d < n ? :cov : :svd\n    end\n\n    # process mean\n    mv = preprocess_mean(X, mean)\n\n    # delegate to core\n    if method == :cov\n        C = covm(X, isempty(mv) ? 0 : mv, 2)\n        M = pcacov(C, mv; maxoutdim=maxoutdim, pratio=pratio)\n    elseif method == :svd\n        Z = centralize(X, mv)\n        M = pcasvd(Z, mv, n; maxoutdim=maxoutdim, pratio=pratio)\n    else\n        throw(ArgumentError(\"Invalid method name $(method)\"))\n    end\n\n    return M::PCA\nend\n", "meta": {"hexsha": "b56a718e48e2ffa178887ec1c5a2b1adccbd7a4a", "size": 8707, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pca.jl", "max_stars_repo_name": "kescobo/MultivariateStats.jl", "max_stars_repo_head_hexsha": "99ee965df3a8e136ff2d0fcb10456b434e1f9001", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pca.jl", "max_issues_repo_name": "kescobo/MultivariateStats.jl", "max_issues_repo_head_hexsha": "99ee965df3a8e136ff2d0fcb10456b434e1f9001", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pca.jl", "max_forks_repo_name": "kescobo/MultivariateStats.jl", "max_forks_repo_head_hexsha": "99ee965df3a8e136ff2d0fcb10456b434e1f9001", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4440559441, "max_line_length": 124, "alphanum_fraction": 0.6515447341, "num_tokens": 2450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7506576519686416}}
{"text": "struct Camera{T <: AbstractFloat}\n\torigin::Vec3{T}\n\tlower_left_corner::Vec3{T}\n\thorizontal::Vec3{T}\n\tvertical::Vec3{T}\n\tu::Vec3{T}\n\tv::Vec3{T}\n\tw::Vec3{T}\n\tlens_radius::T\nend\n\n\"\"\"\n\tArgs:\n\t\tvfov: vertical field-of-view in degrees\n\t\taspect_ratio: horizontal/vertical ratio of pixels\n      aperture: if 0 - no depth-of-field\n\"\"\"\nfunction default_camera(lookfrom::Vec3{T}=(SA{T}[0,0,0]), \n\t\t\t\t\t\tlookat::Vec3{T}=(SA{T}[0,0,-1]), \n\t\t\t\t\t\tvup::Vec3{T}=(SA{T}[0,1,0]), \n\t\t\t\t\t\tvfov::T=T(90), aspect_ratio::T=T(16/9),\n\t\t\t\t\t\taperture::T=T(0), focus_dist::T=T(1)) where T\n\tviewport_height = T(2) * tand(vfov/T(2))\n\tviewport_width = aspect_ratio * viewport_height\n\t\n\tw = normalize(lookfrom - lookat)\n\tu = normalize(vup × w)\n\tv = w × u\n\t\n\torigin = lookfrom\n\thorizontal = focus_dist * viewport_width * u\n\tvertical = focus_dist * viewport_height * v\n\tlower_left_corner = origin - horizontal/T(2) - vertical/T(2) - focus_dist*w\n\tlens_radius = aperture/T(2)\n\tCamera{T}(origin, lower_left_corner, horizontal, vertical, u, v, w, lens_radius)\nend\n\ndefault_camera(lookfrom, lookat, vup, vfov, aspect_ratio, aperture, focus_dist; elem_type::Type{T}) where T =\n\tdefault_camera(Vec3{T}(lookfrom), Vec3{T}(lookat), Vec3{T}(vup), \n\t\tT(vfov), T(aspect_ratio), T(aperture), T(focus_dist)\n\t)\n\n@inline @fastmath function get_ray(c::Camera{T}, s::T, t::T) where T\n\trd = SVector{2,T}(c.lens_radius * random_vec2_in_disk(T))\n\toffset = c.u * rd.x + c.v * rd.y #offset = c.u * rd.x + c.v * rd.y\n    Ray(c.origin + offset, normalize(c.lower_left_corner + s*c.horizontal +\n\t\t\t\t\t\t\t\t\t t*c.vertical - c.origin - offset))\nend\n", "meta": {"hexsha": "edec96721f5ada47960ce2e6e7abff73249d2e87", "size": 1583, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/camera.jl", "max_stars_repo_name": "stillyslalom/RayTracingWeekend.jl", "max_stars_repo_head_hexsha": "d5c8f889f35b1f6054bbe3e7551646236d9a985d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 51, "max_stars_repo_stars_event_min_datetime": "2021-12-12T16:47:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T21:39:08.000Z", "max_issues_repo_path": "src/camera.jl", "max_issues_repo_name": "stillyslalom/RayTracingWeekend.jl", "max_issues_repo_head_hexsha": "d5c8f889f35b1f6054bbe3e7551646236d9a985d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-22T10:38:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T10:38:38.000Z", "max_forks_repo_path": "src/camera.jl", "max_forks_repo_name": "stillyslalom/RayTracingWeekend.jl", "max_forks_repo_head_hexsha": "d5c8f889f35b1f6054bbe3e7551646236d9a985d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-12-12T06:30:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T01:37:15.000Z", "avg_line_length": 32.306122449, "max_line_length": 109, "alphanum_fraction": 0.6677195199, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774727, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7505821437986395}}
{"text": "#=\nThe arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another.\n\nThere are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence.\n\nWhat 12-digit number do you form by concatenating the three terms in this sequence?\n=#\ninclude(\"projecteulerutils.jl\")\nusing Primes\n\nfunction calc()\n  b = c = 0\n  for a in 1000:10000-3330-3330\n    if a == 1487\n      continue\n    end\n    b = a+3330\n    c = b+3330\n    if isprime(a) && isprime(b) && isprime(c) && ispermutation(digits(a),digits(b)) && ispermutation(digits(b), digits(c))\n      return \"$a$b$c\"\n    end\n  end\nend\n@time println(calc())\n", "meta": {"hexsha": "fbd3acfbdc8152dbc500344f7475b2f4d9ad37a0", "size": 832, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p49.jl", "max_stars_repo_name": "daniel-beard/JuliaProjectEuler", "max_stars_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-01T15:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:01:04.000Z", "max_issues_repo_path": "Solutions/p49.jl", "max_issues_repo_name": "daniel-beard/JuliaProjectEuler", "max_issues_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/p49.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 33.28, "max_line_length": 222, "alphanum_fraction": 0.6935096154, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475778774727, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7505821415131683}}
{"text": "module TrajOpt\n\n    using FixedSizeArrays\n    using Polynomials\n\n    export HermiteBasis, QuadratureRule, BCTypes\n    export compute_interpolation_matrices\n    export assemble_stiffness_matrix\n    export apply_bc!\n\n    immutable Block{T,N} <: MutableFixedMatrix{T,N,N}\n\n    end\n\n    \"\"\"\n        hb = HermiteBasis(degree=N)\n\n    Return left and right Hermite interpolation polynomials of specified degree.\n\n    # Description\n    Hermite basis function are used to interpolate a function over the interval\n    τ = [0, 1] when the value of the function and it's first k derviatives are\n    known at endpoints of the interval. The basis functions are simple τ-poly-\n    nomials with degree N = 2k-1. To compute the value of the interpolant at a\n    point within the interval, the basis functions are used to construct a\n    weighted sum of the function data as follows (note: this is pseudo code):\n\n        x_left  = [ x(0.0), x'(0.0) ... ]\n        x_right = [ x(1.0), x'(1.0) ... ]\n        x(τ) = sum( h.left(τ).*x_left ) + sum( h.right(τ).*x_right )\n\n    # Fields\n    * left::Vector{Poly}   Basis functions for left-endpoint function data\n    * right::Vector{Poly}  Basis functions for right-endpoint function data\n    \"\"\"\n    immutable HermiteBasis\n\n        left  :: Vector{Poly{Rational{Int64}}}\n        right :: Vector{Poly{Rational{Int64}}}\n\n        function HermiteBasis(; degree=3)\n            if degree == 1\n                left  = [ Poly([ 1,  -1 ]//1, :τ) ]\n                right = [ Poly([ 0,   1 ]//1, :τ) ]\n            elseif degree == 3\n                left  = [\n                    Poly([ 1,   0,  -3,   2 ]//1, :τ)\n                    Poly([ 0,   1,  -2,   1 ]//1, :τ)\n                ]\n                right = [\n                    Poly([ 0,   0,   3,  -2 ]//1, :τ)\n                    Poly([ 0,   0,  -1,   1 ]//1, :τ)\n                ]\n            elseif degree == 5\n                left  = [\n                    Poly([ 1,   0,   0, -10,  15,  -6 ]//1, :τ)\n                    Poly([ 0,   1,   0,  -6,   8,  -3 ]//1, :τ)\n                    Poly([ 0,   0,   1,  -3,   3,  -1 ]//2, :τ)\n                ]\n                right = [\n                    Poly([ 0,   0,   0,  10, -15,   6 ]//1, :τ)\n                    Poly([ 0,   0,   0,  -4,   7,  -3 ]//1, :τ)\n                    Poly([ 0,   0,   0,   1,  -2,   1 ]//2, :τ)\n                ]\n            else\n                throw(ArgumentError(\"degree=$degree: must be 1, 3, or 5.\"))\n            end\n            return new(left, right)\n        end\n\n    end\n\n\n    \"\"\"\n        qr = QuadratureRule(num_points=N)\n\n    Returns the N-point Guassian quadrature rule.\n\n    # Description\n    Numerical quadrature approximates the integral of a continuous function\n    by sampling the integrand at discrete points in the domiain of integration\n    and then taking a weighted sum of the sample values. Guassian quadrature\n    rules are optimal for a 1D domain of integration: an N-point rule can\n    exactly integrate a polynomial of degree 2*N-1. This type returns the\n    sample locations and weights for a Gaussian Quadrature Rule with a\n    specified number of sample locations.\n\n    # Fields\n    * locations::Vector{Real}  Quad point locations on bi-unit interval\n    * weights::Vector{Real}    Summation weights for function samples\n\n    \"\"\"\n    immutable QuadratureRule\n\n        locations :: Vector{Float64}\n        weights   :: Vector{Float64}\n\n        function QuadratureRule(; num_points=2)\n            if num_points == 1\n                locations = [  0.0 ]\n                weights   = [  2.0 ]\n            elseif num_points == 2\n                locations = [ -1.0,  1.0 ] * sqrt(1/3)\n                weights   = [  1.0,  1.0 ]\n            elseif num_points == 3\n                locations = [ -1.0,  0.0,  1.0 ] * sqrt(3/5)\n                weights   = [  5.0,  8.0,  5.0 ] / 9.0\n            else\n                throw(ArgumentError(\n                    \"num_points=$num_points: must be integer between 1 and 3.\"\n                ))\n            end\n            return new(locations, weights)\n        end\n    end\n\n    function compute_interpolation_matrices(hb, qr, time_points)\n\n        # Preliminaries\n        n_interval = length(time_points)-1\n        n_quad = length(qr.locations)\n        n_dof = length(hb.left)\n\n        # Allocate interpolation matrices\n        zero_block = MutableFixedMatrix{n_dof, n_quad, Float64}(0.0)\n        HL = repmat([zero_block], n_interval)\n        HR = repmat([zero_block], n_interval)\n\n        # Map quadrature locations to unit interval\n        τ = (qr.locations + 1)/2  # Maps [-1,1] => [0,1]\n        τ_scaling = 1/2\n\n        # Compute unit-interval interp matrices\n        HL_unit = τ_scaling * polyval.( hb.left,  τ' )\n        HR_unit = τ_scaling * polyval.( hb.right, τ' )\n\n        # Apply interval scaling to interp matrices\n        Δt = diff(time_points)\n        scale_factors(Δt) = [ Δt^(q+1) for q = 0:n_dof-1 ]\n        for i = 1:n_interval\n            S = scale_factors(Δt[i]);\n            HL[i] = S .* HL_unit\n            HR[i] = S .* HR_unit\n        end\n\n        return (HL, HR)\n\n    end\n\n    \"\"\"\n        K = assemble_stiffness_matrix(hb, time)\n\n    Compute stiffness matrix for time integration of 2nd order ODEs.\n\n    # Description\n    The Continuous Galerkin method can be used to discretize and solve systems\n    of differential equations of the form ``\\ddot{x} = f(t,x,\\dot{x})``. The\n    discretization of this system using Hermite basis functions results in a\n    system of simultaneous non-linear equations ``Kx + f(x) = 0``, where ``K``\n    is the stiffness matrix. This matrix is a block tri-diagonal matrix that\n    is independent of the solution, x, and depends only on the distribution of\n    time points used to discretize the solution domain. See the Jupyter note-\n    book 'Theory.ipynb' for details.\n\n    # Inputs\n    * hb::HermiteBasis  Basis functions used to represent solution\n    * time::AbstractVector{Float64}  Time points discretizing solution domain\n\n    # Outputs\n    * K::Tridiagonal{FixedSizeArrays.Mat}  Block tridiagonal stiffness matrix\n    \"\"\"\n    function assemble_stiffness_matrix(hb, time_points)\n\n        # Preliminaries\n        n_point = length(time_points)\n        n_interval = n_point-1\n        n_dof = length(hb.left)\n\n        # Error checking\n        @assert n_dof>1   \"Must use HermiteBasis with order >= 3\"\n        @assert n_point>2 \"Must be at least 3 time points\"\n\n        # Allocate stiffness matrix\n        zero_block = MutableFixedMatrix{Float64, n_dof, n_dof}(0.0)\n        K = Tridiagonal(\n            repmat( [zero_block], n_point-1 ), # Lower Diagonal\n            repmat( [zero_block], n_point   ), # Main  Diagonal\n            repmat( [zero_block], n_point-1 ), # Upper Diagonal\n        )\n\n        # Compute unit-interval stiffness matrices\n        dhb_left  = polyder(hb.left)\n        dhb_right = polyder(hb.right)\n        integrate(x) = polyval( polyint(x), 1.0 )\n        KLL = [ integrate(bi*bj) for bi=dhb_left,  bj=dhb_left  ]\n        KLR = [ integrate(bi*bj) for bi=dhb_left,  bj=dhb_right ]\n        KRL = [ integrate(bi*bj) for bi=dhb_right, bj=dhb_left  ]\n        KRR = [ integrate(bi*bj) for bi=dhb_right, bj=dhb_right ]\n\n        # Assemble global matrix from scaled unit-interval matrices\n        Δt = diff(time_points)\n        scale_factors(Δt) = [ Δt^-(p*q+1) for p=0:n_dof-1, q=0:n_dof-1 ]\n        for i = 1:n_interval\n            S = scale_factors(Δt[i])\n            K[ i , i ] += S.*KLL\n            K[ i ,i+1] += S.*KLR\n            K[i+1, i ] += S.*KRL\n            K[i+1,i+1] += S.*KRR\n        end\n\n        # Add boundary operators\n        BL = [ polyval(bi*bj, 0.0) for bi=hb.left,  bj=dhb_left  ]\n        BR = [ polyval(bi*bj, 1.0) for bi=hb.right, bj=dhb_right ]\n        K[ 1 , 1 ] += scale_factors(Δt[ 1 ]) .* BL\n        K[end,end] -= scale_factors(Δt[end]) .* BR\n\n        return K\n\n    end\n\n    \"\"\"\n        F = assemble_load_vector(HL, HR, accel)\n\n    Constructs the discrete load vector (RHS) for a uniform acceleration.\n\n    # Description\n    This function is a specicialized version of the assemble_load_vector that\n    only works for constant accelerations that are independent of the trajectory\n    solution (e.g. a constant gravitational acceleration). This is mainly used\n    to verify correctness and accuracy of the Continuous Galerkin stiffness\n    matrix and the associated boundary conditions.\n\n    # Inputs\n    HL::Vector{Mat}  Left-hand Hermite interpolation matrices\n    HR::Vector{Mat}  Right-hand Hermite interpolation matrices\n    accel::Float64   Constant acceleration applied to trajectory\n\n    # Outputs\n    F::Vector{Vec}   Load vector for discrete system of equations\n    \"\"\"\n    function assemble_load_vector(HL, HR, weights, accel)\n\n        # Preliminaries\n        n_interval = length(HL)\n        n_point = n_interval+1\n        n_dof = size(HL[1],1)\n\n        # Error checking\n        @assert n_dof>1   \"Must use HermiteBasis with order >= 3\"\n        @assert n_point>2 \"Must be at least 3 time points\"\n\n        # Allocate load vector\n        F = repmat(MutableFixedVector{Float64, n_dof}(0.0), n_point)\n\n        # Evaluate load integrals\n        aw = accel * weights\n        for i = 1:n_interval\n            F[ i ] += HL[i] * aw\n            F[i+1] += HR[i] * aw\n        end\n\n    end\n\n    \"\"\"\n    Defines named constants for different boundary condition types\n    \"\"\"\n    module BCTypes\n        @enum BCType dirichlet=1 neumann=2\n    end\n\n\n    \"\"\"\n        apply_bc!(K, bc, i)\n\n    Modifies stiffness matrix to enforce Dirichlet/Neumman boundary conditions.\n\n    # Description:\n    Modifies stiffness matrix to enforce Dirichlet/Neumman boundary conditions\n    at a specified time-point in the solution. Note that this doesn't actually\n    define what the *value* at the boundary will be; the value is specified by\n    calling apply_bc! with the load vector as the first argument, e.g.\n\n        apply_bc!(f, bc, i, value)\n\n    This version of apply_bc! simply modifies the stiffness matrix so that the\n    required degree of freedom is set equal to the value specified in the load\n    vector.\n    \"\"\"\n    function apply_bc!{T <: MutableFixedMatrix}(K::Tridiagonal{T}, bc, i)\n        # How this works:\n        # To embed a boundary condition in the K matrix, we need to replace the\n        # existing discrete equation for the \"p\"-th degree of freedom such that\n        #   (K*x)[p] = x[p] = f[p]\n        # Since K block tri-diagonal, this boils down to zero-ing out the\n        # \"q\"-th row in of the three blocks coupled to the i-th node and then\n        # setting the diagonal element to unity.\n        #\n        # Since we are using Hermite shape functions, the value of \"q\" depends\n        # on the type of BC. If we want a Dirichlet BC we modify the 1st nodal\n        # degree of freedom; if we want a Neumann BC, we modifiy the 2nd nodal\n        # degree of freedom. This mapping from BC type to row index is codified\n        # using the BCType enumeration.\n        N = size(K,2)\n        ibc = Int(bc)\n        K[i,i][ibc,:]  = 0.0\n        K[i,i][ibc,ibc] = 1.0\n        if i > 1;  K[i,i-1][ibc,:] = 0.0;  end\n        if i < N;  K[i,i+1][ibc,:] = 0.0;  end\n        return nothing\n    end\n\n\n    \"\"\"\n        apply_bc!(F, bc, i, value)\n\n    Modifies load vector to apply a Dirichlet/Neumman boundary conditions.\n\n    # Description:\n    Modifies assembled load vector to apply a Dirichlet or Neumman boundary\n    conditions at a specified time-point in the solution. Note that for this\n    to be effective, the stiffness matrix must also be modified at the specified\n    node to accept a boundary condition. This is achieved by calling apply_bc!\n    with the stiffness matrix as the first argument.\n    \"\"\"\n    function apply_bc!{T <: MutableFixedVector}(F::Vector{T}, bc, i, value)\n        F[i][Int(bc)] = value\n        return nothing\n    end\n\n\nend\n", "meta": {"hexsha": "aea6e903cc8b367906b84495840fbaa2b004d3d2", "size": 11854, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TrajOpt.jl", "max_stars_repo_name": "flying-tiger/TrajOpt.jl", "max_stars_repo_head_hexsha": "5892b3e580c26c752e1565b5e2f635d112d143cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TrajOpt.jl", "max_issues_repo_name": "flying-tiger/TrajOpt.jl", "max_issues_repo_head_hexsha": "5892b3e580c26c752e1565b5e2f635d112d143cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TrajOpt.jl", "max_forks_repo_name": "flying-tiger/TrajOpt.jl", "max_forks_repo_head_hexsha": "5892b3e580c26c752e1565b5e2f635d112d143cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7048192771, "max_line_length": 80, "alphanum_fraction": 0.5887464147, "num_tokens": 3295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.7505821379604338}}
{"text": "using Distributions\r\nusing DataFrames\r\nusing Random\r\n\r\n\"\"\"\r\n    generateFormants(nTokens; [cats=[\"iy\", \"aa\", \"uw\"], gender=[\"w\", \"m\"]])\r\n\r\nGenerate synthetic formants from multivariate normal distributions based on observations from  Hillenbrand et al. (1995, Acoustic characteristics of American English vowels, DOI: 10.1121/1.411872). Currently supports generating vowels for /i/ as `\"iy\"`, /ɑ/ as `\"aa\"`, and /u/ as `\"uw\"`, using values for men as `\"m\"` and women as `\"w\"`. One observation was dropped from the women /ɑ/ token because the F2 value could not be measured when Hillenbrand et al. collected the data. Values in the mean vectors and covariance matrices were rounded to two decimal places.\r\n\r\nArgs\r\n======\r\n\r\n* `nTokens` The number of tokens to generate for each category and gender pairing\r\n* `cats` (keyword argument) A vector of vowel categories to generate tokens for\r\n* `gender` (keyword argument) A vector of gender categories to generate tokens for\r\n* `seed` A seed value for a `MersenneTwister` random number generator; allows for reproducible results; using the default value of `nothing` will use the system-generated random seed.\r\n* `rng` An `AbstractRNG` object to use for random number generation; if the default value of `nothing` is used, a `MersenneTwister` object will be created\r\n\"\"\"\r\nfunction generateFormants(nTokens; cats=[\"iy\", \"aa\", \"uw\"], gender=[\"m\", \"w\"], seed=nothing, rng::T=nothing) where T <: Union{AbstractRNG, Nothing}\r\n\r\n  if isnothing(seed) && isnothing(rng)\r\n    rng = MersenneTwister()\r\n  elseif isnothing(rng)\r\n    rng = MersenneTwister(seed)\r\n  end\r\n  \r\n  mappings = Dict()\r\n\r\n  mappings[(\"iy\", \"w\")] = MultivariateNormal([437.25, 2761.31], [1650.06 1277.86; 1277.86 21738.56])\r\n  mappings[(\"aa\", \"w\")] = MultivariateNormal([916.36, 1525.83], [8449.85 4354.50; 4354.50 15615.80])\r\n  mappings[(\"uw\", \"w\")] = MultivariateNormal([459.67, 1105.52], [1496.06 -417.93; -417.93 42130.34])  \r\n\r\n  mappings[(\"iy\", \"m\")] = MultivariateNormal([342.69, 2322.78], [796.99 493.36; 493.36 18580.77])\r\n  mappings[(\"aa\", \"m\")] = MultivariateNormal([756.49, 1308.93], [3879.39 1751.56; 1751.56 12324.24])\r\n  mappings[(\"uw\", \"m\")] = MultivariateNormal([379.67, 992.24], [1106.32 1482.52; 1482.52 12833.73])\r\n\r\n  generated = []\r\n  vowel = []\r\n  gend = []\r\n\r\n  for c in cats\r\n    for g in gender\r\n      \r\n      if ! haskey(mappings, (c, g))\r\n        error(\"Unsupported vowel and gender combination: ($c, $g)\")\r\n      end\r\n\r\n      dist = mappings[(c, g)]\r\n      data = rand(rng, dist, nTokens)\r\n      push!(generated, data)\r\n      vowel = [vowel; repeat([c], nTokens)]\r\n      gend = [gend; repeat([g], nTokens)]\r\n    end\r\n  end\r\n\r\n  gen = reduce(hcat, generated)\r\n  return DataFrame(f1=gen[1,:], f2=gen[2,:], vowel=vowel, gender=gend)\r\nend\r\n", "meta": {"hexsha": "1028aafe8802c42586b7127521d276c2f6a45d7e", "size": 2771, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/util.jl", "max_stars_repo_name": "maetshju/Phonetics.jl", "max_stars_repo_head_hexsha": "5ebc68cdc85f196f67ee4b812d249f46865b5d02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/util.jl", "max_issues_repo_name": "maetshju/Phonetics.jl", "max_issues_repo_head_hexsha": "5ebc68cdc85f196f67ee4b812d249f46865b5d02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-06-27T00:29:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-31T19:00:16.000Z", "max_forks_repo_path": "src/util.jl", "max_forks_repo_name": "maetshju/Phonetics.jl", "max_forks_repo_head_hexsha": "5ebc68cdc85f196f67ee4b812d249f46865b5d02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-31T18:51:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-31T18:51:08.000Z", "avg_line_length": 46.9661016949, "max_line_length": 565, "alphanum_fraction": 0.6654637315, "num_tokens": 837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774729, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7505821369422259}}
{"text": "\"\"\"\n    F = JopTanh(spc)\n\nwhere `F` is the hyperbolic tangent operator with domain and range given by `spc::JetSpace`.\nwe use 'tanh'(c*x) = (\\exp{c*x}-\\exp{-c*x})/(\\exp{c*x}+\\exp{-c*x}),\nthe derivative of which is 1-tanh(c*x)^2.\nWe expect the domain and range to be real.\n\"\"\"\nJopTanh(spc::JetSpace{T}, c = 1) where {T} = JopNl(dom = spc, rng = spc, f! = JopTanh_f!, df! = JopTanh_df!, df′! = JopTanh_df′!, s = (c=T(c),))\nexport JopTanh\n\nJopTanh_f!(d::AbstractArray, m::AbstractArray; c) = d .= tanh.(c .* m)\n\nJopTanh_df!(δd::AbstractArray, δm::AbstractArray; mₒ, c) = δd .= c .* (1 .- tanh.(c .* mₒ).^2) .* δm\n\nJopTanh_df′!(δd::AbstractArray, δm::AbstractArray; mₒ, c) = δd .= conj.(c .* (1 .- tanh.(c .* mₒ).^2)) .* δm\n\n", "meta": {"hexsha": "f567f496ac83550068453c9173aad6de847bb874", "size": 721, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/jop_tanh.jl", "max_stars_repo_name": "ChevronETC/JetPack.jl", "max_stars_repo_head_hexsha": "7b18a65344155dee4422958f54d045db354aaf6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-02T16:23:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-02T16:23:43.000Z", "max_issues_repo_path": "src/jop_tanh.jl", "max_issues_repo_name": "ChevronETC/JetPack.jl", "max_issues_repo_head_hexsha": "7b18a65344155dee4422958f54d045db354aaf6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-10-08T15:13:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T02:56:17.000Z", "max_forks_repo_path": "src/jop_tanh.jl", "max_forks_repo_name": "ChevronETC/JetPack.jl", "max_forks_repo_head_hexsha": "7b18a65344155dee4422958f54d045db354aaf6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0555555556, "max_line_length": 144, "alphanum_fraction": 0.6033287101, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615413, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7505628691245607}}
{"text": "immutable Rayleigh <: ContinuousUnivariateDistribution\n    σ::Float64\n\n    function Rayleigh(σ::Real)\n        σ > zero(σ) || error(\"Rayleigh: σ must be positive\")\n        @compat new(Float64(σ))\n    end\n\n    Rayleigh() = new(1.0)\nend\n\n@distr_support Rayleigh 0.0 Inf\n\n\n#### Parameters\n\nscale(d::Rayleigh) = d.σ\nparams(d::Rayleigh) = (d.σ,)\n\n\n#### Statistics\n\nmean(d::Rayleigh) = sqrthalfπ * d.σ\nmedian(d::Rayleigh) = 1.177410022515474691 * d.σ   # sqrt(log(4.0)) = 1.177410022515474691\nmode(d::Rayleigh) = d.σ\n\nvar(d::Rayleigh) = 0.429203673205103381 * d.σ^2   # (2.0 - π / 2) = 0.429203673205103381\nstd(d::Rayleigh) = 0.655136377562033553 * d.σ\n\nskewness(d::Rayleigh) = 0.631110657818937138\nkurtosis(d::Rayleigh) = 0.245089300687638063\n\nentropy(d::Rayleigh) = 0.942034242170793776 + log(d.σ)\n\n\n#### Evaluation\n\nfunction pdf(d::Rayleigh, x::Float64)\n\tσ2 = d.σ^2\n\tx > 0.0 ? (x / σ2) * exp(- (x^2) / (2.0 * σ2)) : 0.0\nend\n\nfunction logpdf(d::Rayleigh, x::Float64)\n\tσ2 = d.σ^2\n\tx > 0.0 ? log(x / σ2) - (x^2) / (2.0 * σ2) : -Inf\nend\n\nlogccdf(d::Rayleigh, x::Float64) = - (x^2) / (2.0 * d.σ^2)\nccdf(d::Rayleigh, x::Float64) = exp(logccdf(d, x))\n\ncdf(d::Rayleigh, x::Float64) = 1.0 - ccdf(d, x)\nlogcdf(d::Rayleigh, x::Float64) = log1mexp(logccdf(d, x))\n\nquantile(d::Rayleigh, p::Float64) = sqrt(-2.0 * d.σ^2 * log1p(-p))\n\n\n#### Sampling\n\nrand(d::Rayleigh) = d.σ * sqrt(2.0 * randexp())\n\n", "meta": {"hexsha": "65add7a370f1fb3786b50808c9fae49840e63896", "size": 1381, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/rayleigh.jl", "max_stars_repo_name": "wildart/Distributions.jl", "max_stars_repo_head_hexsha": "041315226c919c1a6c7dae8437bddd61907bc73b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/rayleigh.jl", "max_issues_repo_name": "wildart/Distributions.jl", "max_issues_repo_head_hexsha": "041315226c919c1a6c7dae8437bddd61907bc73b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/rayleigh.jl", "max_forks_repo_name": "wildart/Distributions.jl", "max_forks_repo_head_hexsha": "041315226c919c1a6c7dae8437bddd61907bc73b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6393442623, "max_line_length": 90, "alphanum_fraction": 0.622737147, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7505240205233045}}
{"text": "println(\"\\n\\tEstimate autocorrelations\");\nprintln(\"\\n\\t...for N1...\");\nxcorr = [0:10:400];\nycorr1 = zeros( length( xcorr ), 5 );\nfor a in [1:5]\n  # Calculate autocorrelations\n  ycorr1[:,a] = autocorrelation(N1, v1, a, xcorr);\n  # Normalize by dividing through by Ĉ[1,a]\n  ycorr1[:,a] /= ycorr1[1,a];\nend\nprintln(\"\\n\\t...for N2 (See plots below)\");\nycorr2 = zeros( length( xcorr ), 5 );\nfor a in [1:5]\n  # Calculate autocorrelations\n  ycorr2[:,a] = autocorrelation(N2, v2, a, xcorr);\n  # Normalize by dividing through by Ĉ[1,a]\n  ycorr2[:,a] /= ycorr2[1,a];\nend\n\n# Make plots for each alpha\nprintln(\"\\n\\tPlacing estimated autocorrelation plots 'plots1' and 'plots2':\");\nusing Gadfly\nplots1 = Plot[];\nplots2 = Plot[];\nfor i in [1:5]\n  # Plot\n  push!(plots1, Gadfly.plot ( x = xcorr, y = ycorr1[:,i], Geom.line, Geom.point,\n      Guide.xlabel(\"Separation\"), Guide.ylabel(\"Normalized Autocorrelation\"),\n      Guide.title(join([\"Estimated Autocorrelation for Dataset\",string(i),\n                        \"with Sample Size N1 = $N1\"],\" \",\" \"))))\n  push!(plots2, Gadfly.plot ( x = xcorr, y = ycorr2[:,i], Geom.line, Geom.point,\n      Guide.xlabel(\"Separation\"), Guide.ylabel(\"Normalized Autocorrelation\"),\n      Guide.title(join([\"Estimated Autocorrelation for Dataset\",string(i),\n                        \"with Sample Size N2 = $N2\"],\" \",\" \"))))\nend\n\n# Estimate autocorrelation times\nprintln(\"\\n\\tEstimating autocorrelation times τ1 and τ2\");\nτ1 = Float64[];\nτ2 = Float64[];\nfor a in [1:5]\n  corra = autocorrelation(N1, v1, a, ns);\n  corra /= corra[1];                          # Normalize\n  push!(τ1,sum(corra) - 0.5);                 # Get autocorrelation time\nend\nfor a in [1:5]\n  corra = autocorrelation(N2, v2, a, ns);\n  corra /= corra[1];                          # Normalize\n  push!(τ2,sum(corra) - 0.5);                 # Get autocorrelation time\nend\n\nprintln(\"\\n\\tEstimated Autocorrelation Times for N1 = $N1:\\n\");\nfor i in [1:5]\n  println(\"\\t\\tτ̂1v$i:\\t$(τ1[i])\");\nend\nprintln(\"\\n\\tEstimated Autocorrelation Times for N2 = $N2:\\n\");\nfor i in [1:5]\n  println(\"\\t\\tτ̂2v$i:\\t$(τ2[i])\");\nend\nprintln(\"\\n\\tThe estimated autocorrelation times are clearly far better for the larger sample.\");\n\n", "meta": {"hexsha": "4b131feadfaaa9fb7c8dbb36dab787c3dedc421b", "size": 2191, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "set03/q4/tau-plots.jl", "max_stars_repo_name": "stefco/g6080", "max_stars_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "set03/q4/tau-plots.jl", "max_issues_repo_name": "stefco/g6080", "max_issues_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "set03/q4/tau-plots.jl", "max_forks_repo_name": "stefco/g6080", "max_forks_repo_head_hexsha": "dd57d90bcdf67f096b35a18533be8660510ffc97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3387096774, "max_line_length": 97, "alphanum_fraction": 0.6198083067, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347107, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7505240087086331}}
{"text": "\"\"\"\n## sample!\n\nThis subroutine returns the local coordinates and weighting coefficients\nof the integrating points.\n\n### Function\n```julia\nsample!(fin_el, s, wt)\n```\n\n### Arguments\n```julia\n* fin_el::FiniteElement      : Finite element type\n* s::Matrix{Float64}        : Local coordinates (Updated)\n* wt::Vector{Float64}       : Weighting coefficients (Updated)\n```\n\"\"\"\nfunction sample!(fin_el::Line, s::Matrix{Float64} , wt::Vector{Float64})\n  #\n  # This subroutine returns the local coordinates and weighting coefficients\n  # of the integrating points.\n  #\n  nip = size(s,1)\n  (s[:,1], wt[:]) = QuadGK.gauss(Float64, nip)\nend\n", "meta": {"hexsha": "8f6f04ed1de0d5184c9d8a70c0d2171c006eb41c", "size": 628, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PtFEM/Main/sample_line.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PtFEM.jl-9b64898b-da2a-5774-a656-fd6fb605642c", "max_stars_repo_head_hexsha": "35a9d7c796a92f5d44bd37a2af574fb366fa51ba", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2017-04-16T11:52:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T06:41:59.000Z", "max_issues_repo_path": "src/PtFEM/Main/sample_line.jl", "max_issues_repo_name": "UnofficialJuliaMirror/PtFEM.jl-9b64898b-da2a-5774-a656-fd6fb605642c", "max_issues_repo_head_hexsha": "35a9d7c796a92f5d44bd37a2af574fb366fa51ba", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2018-07-04T00:14:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:16.000Z", "max_forks_repo_path": "src/PtFEM/Main/sample_line.jl", "max_forks_repo_name": "UnofficialJuliaMirror/PtFEM.jl-9b64898b-da2a-5774-a656-fd6fb605642c", "max_forks_repo_head_hexsha": "35a9d7c796a92f5d44bd37a2af574fb366fa51ba", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2017-05-28T21:43:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T12:43:12.000Z", "avg_line_length": 23.2592592593, "max_line_length": 76, "alphanum_fraction": 0.678343949, "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951643678382, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7504817202673157}}
{"text": "# Soft thresholding function\n@inline soft_threshold(x, ϵ) = max(x - ϵ, 0) + min(x + ϵ, 0)\n\n# RPCA using the inexact Augumented Lagrange Multiplier (ALM).\n# Given a observation matrix D, find row-rank matrix A and sparse matrix E\n# so that D = A + E.\nfunction inexact_alm_rpca(D::AbstractMatrix;\n                          sparseness::Float64=1.0/sqrt(maximum(size(D))),\n                          max_iter::Int=1000,\n                          error_tol::Float64=1.0e-7,\n                          ρ::Float64=1.5,\n                          verbose::Bool=false,\n                          nonnegativeA::Bool=false,\n                          nonnegativeE::Bool=false)\n    M, N = size(D)\n    λ = sparseness\n\n    A⁰, E⁰ = zeros(M, N), zeros(M, N)\n\n    # initialize\n    Y⁰ = copy(D)\n    norm² = svdvals(Y⁰)[1] # can be tuned\n    norm∞ = norm(vec(Y⁰), Inf) / λ\n    dual_norm = max(norm², norm∞)\n    d_norm = norm(D)\n    Y⁰ /= dual_norm\n\n    μ⁰ = 1.25 / norm²\n    μ̄ = μ⁰ * 1.0e+7\n\n    converged::Bool = false\n    k = 0\n    sv⁰ = 10\n\n    Yᵏ, Aᵏ, Eᵏ, μᵏ, svᵏ = Y⁰, A⁰, E⁰, μ⁰, sv⁰\n    while !converged\n        # update sparse matrix E\n        Eᵏ = soft_threshold(D - Aᵏ + 1/μᵏ * Yᵏ, λ * 1/μᵏ)\n        # force non-negative (heuristic)\n        if nonnegativeE\n            Eᵏ = max(Eᵏ, 0)\n        end\n\n        U, S, V = svd(D - Eᵏ + μᵏ^-1 * Yᵏ)\n\n        # trancate dimention\n        svpᵏ = trunc(Int, sum(S .> μᵏ^-1))\n        if svpᵏ < svᵏ\n            svᵏ = min(svpᵏ + 1, N)\n        else\n            svᵏ = min(svpᵏ + round(0.05 * N), N)\n        end\n\n        # update row-rank matrix A\n        Aᵏ = U[:,1:svpᵏ] * diagm(S[1:svpᵏ] - 1/μᵏ) * V[:,1:svpᵏ]'\n        # force non-negative (heuristic)\n        if nonnegativeA\n            Aᵏ = max(Aᵏ, 0)\n        end\n\n        Z = D - Aᵏ - Eᵏ\n\n        Yᵏ = Yᵏ + μᵏ * Z\n        μᵏ = min(μᵏ * ρ, μ̄)\n\n        objective = norm(Z) / d_norm\n        verbose && println(\"#$(k) objective: $(objective)\")\n\n        if objective < error_tol\n            if verbose\n                println(\"converged\")\n            end\n            converged = true\n        end\n\n        k = k + 1\n        k >= max_iter && break\n    end\n\n    Aᵏ, Eᵏ\nend\n", "meta": {"hexsha": "e35277cf7a3e8b6d4ab5552f111abee5bd000924", "size": 2143, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/inexact_alm.jl", "max_stars_repo_name": "r9y9/RPCA.jl", "max_stars_repo_head_hexsha": "585849f4ff168fabccb6692503bd70ff4d2cda91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-02-25T01:30:48.000Z", "max_stars_repo_stars_event_max_datetime": "2016-04-13T08:13:43.000Z", "max_issues_repo_path": "src/inexact_alm.jl", "max_issues_repo_name": "r9y9/RPCA.jl", "max_issues_repo_head_hexsha": "585849f4ff168fabccb6692503bd70ff4d2cda91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/inexact_alm.jl", "max_forks_repo_name": "r9y9/RPCA.jl", "max_forks_repo_head_hexsha": "585849f4ff168fabccb6692503bd70ff4d2cda91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-09-04T13:23:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-29T22:23:54.000Z", "avg_line_length": 26.1341463415, "max_line_length": 74, "alphanum_fraction": 0.4792347177, "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951570602081, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7504817121969017}}
{"text": "function η_karnik(u::Matrix{FuzzyNumber}, d2::Matrix{FuzzyNumber}; m::Real=2.0)\n\tm > 1 || error(\"fuzzifier m ∈ (1, ∞), got $m\")\n\tlevels = u[1, 1].levels\n\tnum_levels = length(levels)\n\tN, c = size(u)\n\n\tη = Vector{FuzzyNumber}(undef, c)\n\tfor i = 1:c\n\t\tgrades = Vector{Interval}(undef, num_levels)\n\t\tfor (lvl, α) in enumerate(levels)\n\t\t\tu_cut = cut(FuzzyVector(u[:, i]), α)\n\t\t\td2_cut = cut(FuzzyVector(d2[:, i]), α)\n\t\t\tc_left = km_iwa(d2_cut, u_cut; bound=\"lower\", m=m)\n\t\t\tc_right = km_iwa(d2_cut, u_cut; bound=\"upper\", m=m)\n\t\t\tgrades[lvl] = Interval(c_left, c_right)\n\t\tend\n\t\tη[i] = FuzzyNumber(levels, grades)\n\tend\n\tη\nend\n\nfunction u_lpcm(X⃗::FuzzyVector, C⃗::FuzzyVector, η::Real; m::Real=2.0)\n\tm > 1 || error(\"fuzzifier m ∈ (1, ∞), got $m\")\n\tη > 0 || error(\"η must be suitable positive number\")\n\tlevels = X⃗[1].levels\n\tnum_levels = length(levels)\n\n\tgrades = Vector{Interval}(undef, num_levels)\n\tD2 = FuzzySets.d_interval(X⃗, C⃗, squared=true)\n\tfor (lvl, α) in enumerate(levels)\n\t\tD2_cut = cut(D2, α)\n\t\tgrades[lvl] = u_lpcm(D2_cut, η; m=m)\n\tend\n\tu = FuzzyNumber(levels, grades)\n\tu\nend\n\nfunction u_lpcm(d2::Interval, η::Real; m::Real=2.0)\n\tm > 1 || error(\"fuzzifier m ∈ (1, ∞)\")\n\tη > 0 || error(\"η must be suitable positive number\")\n\tpower = 1 / (m - 1)\n\n\tu = Interval(1) / (Interval(1) + (d2 / η)^power)\n\tu\nend", "meta": {"hexsha": "549aa05f92a31a4db27cc849f6457fc0653385ee", "size": 1308, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LPCM.jl", "max_stars_repo_name": "tmwatchanan/FuzzySets.jl", "max_stars_repo_head_hexsha": "c17ebb15a1ec3b1e4c18e58e58449221376efc7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LPCM.jl", "max_issues_repo_name": "tmwatchanan/FuzzySets.jl", "max_issues_repo_head_hexsha": "c17ebb15a1ec3b1e4c18e58e58449221376efc7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LPCM.jl", "max_forks_repo_name": "tmwatchanan/FuzzySets.jl", "max_forks_repo_head_hexsha": "c17ebb15a1ec3b1e4c18e58e58449221376efc7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0666666667, "max_line_length": 79, "alphanum_fraction": 0.6345565749, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678382, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7504817114628476}}
{"text": "\"\"\"\n    hahn(x, p::Integer, α, β, N::Integer)\n\nEvaluate the Hahn polynomial with parameters `α`, `β`, `N` of degree `p` at `x`\nusing the three term recursion [Öffner, Zweidimensionale klassische und diskrete\northogonale Polynome, Chapter 5].\n\"\"\"\nfunction hahn(x, p::Integer, α, β, N)\n    T = typeof( (α+β+2)*x/(N*(α+1)) )\n    a = one(T)\n    b = 1 - (α+β+2)*x/(N*(α+1))\n\n    if p <= 0\n        return a\n    elseif p == 1\n        return b\n    elseif typeof(N) <: Integer && p > N\n        throw(ArgumentError(\"p==$p must not be larger than N==$N.\"))\n    end\n\n    for n in 2:p\n        An = T( (n+α+β)*(n+α)*(N-n+1) ) / ( (2n-1+α+β)*(2n+α+β) )\n        Cn = T( (n-1)*(n+α+β+N)*(n-1+β) ) / ( (2n-2+α+β)*(2n-1+α+β) )\n        a, b = b, ( (An+Cn-x)*b - Cn*a ) / An\n    end\n\n    b\nend\n", "meta": {"hexsha": "a5a84eb8f408471880eeed41eb13f84978a2454a", "size": 773, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hahn.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_stars_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-09-11T18:12:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T21:08:56.000Z", "max_issues_repo_path": "src/hahn.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_issues_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2018-02-15T06:32:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T15:59:07.000Z", "max_forks_repo_path": "src/hahn.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_forks_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:34:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:01:42.000Z", "avg_line_length": 26.6551724138, "max_line_length": 80, "alphanum_fraction": 0.5019404916, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.8031737916455819, "lm_q1q2_score": 0.7504817099952615}}
{"text": "\"\"\"\n    Logistic(μ,θ)\n\nThe *Logistic distribution* with location `μ` and scale `θ` has probability density function\n\n```math\nf(x; \\\\mu, \\\\theta) = \\\\frac{1}{4 \\\\theta} \\\\mathrm{sech}^2\n\\\\left( \\\\frac{x - \\\\mu}{2 \\\\theta} \\\\right)\n```\n\n```julia\nLogistic()       # Logistic distribution with zero location and unit scale, i.e. Logistic(0, 1)\nLogistic(u)      # Logistic distribution with location u and unit scale, i.e. Logistic(u, 1)\nLogistic(u, b)   # Logistic distribution with location u ans scale b\n\nparams(d)       # Get the parameters, i.e. (u, b)\nlocation(d)     # Get the location parameter, i.e. u\nscale(d)        # Get the scale parameter, i.e. b\n```\n\nExternal links\n\n* [Logistic distribution on Wikipedia](http://en.wikipedia.org/wiki/Logistic_distribution)\n\n\"\"\"\nstruct Logistic{T<:Real} <: ContinuousUnivariateDistribution\n    μ::T\n    θ::T\n    Logistic{T}(µ::T, θ::T) where {T} = new{T}(µ, θ)\nend\n\n\nfunction Logistic(μ::T, θ::T; check_args=true) where {T <: Real}\n    check_args && @check_args(Logistic, θ > zero(θ))\n    return Logistic{T}(μ, θ)\nend\n\nLogistic(μ::Real, θ::Real) = Logistic(promote(μ, θ)...)\nLogistic(μ::Integer, θ::Integer) = Logistic(float(μ), float(θ))\nLogistic(μ::T) where {T <: Real} = Logistic(μ, one(T))\nLogistic() = Logistic(0.0, 1.0, check_args=false)\n\n@distr_support Logistic -Inf Inf\n\n#### Conversions\nfunction convert(::Type{Logistic{T}}, μ::S, θ::S) where {T <: Real, S <: Real}\n    Logistic(T(μ), T(θ))\nend\nfunction convert(::Type{Logistic{T}}, d::Logistic{S}) where {T <: Real, S <: Real}\n    Logistic(T(d.μ), T(d.θ), check_args=false)\nend\n\n#### Parameters\n\nlocation(d::Logistic) = d.μ\nscale(d::Logistic) = d.θ\n\nparams(d::Logistic) = (d.μ, d.θ)\n@inline partype(d::Logistic{T}) where {T<:Real} = T\n\n\n#### Statistics\n\nmean(d::Logistic) = d.μ\nmedian(d::Logistic) = d.μ\nmode(d::Logistic) = d.μ\n\nstd(d::Logistic) = π * d.θ / sqrt3\nvar(d::Logistic) = (π * d.θ)^2 / 3\nskewness(d::Logistic{T}) where {T<:Real} = zero(T)\nkurtosis(d::Logistic{T}) where {T<:Real} = T(6)/5\n\nentropy(d::Logistic) = log(d.θ) + 2\n\n\n#### Evaluation\n\nzval(d::Logistic, x::Real) = (x - d.μ) / d.θ\nxval(d::Logistic, z::Real) = d.μ + z * d.θ\n\npdf(d::Logistic, x::Real) = (lz = logistic(-abs(zval(d, x))); lz*(1-lz)/d.θ)\nlogpdf(d::Logistic, x::Real) = (u = -abs(zval(d, x)); u - 2*log1pexp(u) - log(d.θ))\n\ncdf(d::Logistic, x::Real) = logistic(zval(d, x))\nccdf(d::Logistic, x::Real) = logistic(-zval(d, x))\nlogcdf(d::Logistic, x::Real) = -log1pexp(-zval(d, x))\nlogccdf(d::Logistic, x::Real) = -log1pexp(zval(d, x))\n\nquantile(d::Logistic, p::Real) = xval(d, logit(p))\ncquantile(d::Logistic, p::Real) = xval(d, -logit(p))\ninvlogcdf(d::Logistic, lp::Real) = xval(d, -logexpm1(-lp))\ninvlogccdf(d::Logistic, lp::Real) = xval(d, logexpm1(-lp))\n\nfunction gradlogpdf(d::Logistic, x::Real)\n    e = exp(-zval(d, x))\n    ((2e) / (1 + e) - 1) / d.θ\nend\n\nmgf(d::Logistic, t::Real) = exp(t * d.μ) / sinc(d.θ * t)\n\nfunction cf(d::Logistic, t::Real)\n    a = (π * t) * d.θ\n    a == zero(a) ? complex(one(a)) : cis(t * d.μ) * (a / sinh(a))\nend\n", "meta": {"hexsha": "27fd5005ad719377bc77ee0fe692f56574c32a59", "size": 3030, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/logistic.jl", "max_stars_repo_name": "darsnack/Distributions.jl", "max_stars_repo_head_hexsha": "37bac79cec9052c78e0f7c616312dc1a1714cb16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-07T23:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-07T23:36:42.000Z", "max_issues_repo_path": "src/univariate/continuous/logistic.jl", "max_issues_repo_name": "darsnack/Distributions.jl", "max_issues_repo_head_hexsha": "37bac79cec9052c78e0f7c616312dc1a1714cb16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-10-30T02:14:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-31T00:46:58.000Z", "max_forks_repo_path": "src/univariate/continuous/logistic.jl", "max_forks_repo_name": "darsnack/Distributions.jl", "max_forks_repo_head_hexsha": "37bac79cec9052c78e0f7c616312dc1a1714cb16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-24T16:14:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-24T16:14:30.000Z", "avg_line_length": 28.8571428571, "max_line_length": 95, "alphanum_fraction": 0.6161716172, "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.8031737916455819, "lm_q1q2_score": 0.7504817085279374}}
{"text": "\"\"\"\n    function dwz_ranking(\n        players::Vector{Player},\n        ranking_scheme_to_update::String,\n        last_tournament_id::String\n    )\n\nUpdate the players rankings using the Deutsche Wertungszahl Algorithm\n\nArguments\n=========\n- `players`:\n    an array of players in the simulation.\n- `ranking_scheme_to_update`:\n    the name of the ranking scheme to update for each Player.\n- `last_tournament_id`:\n    the last tournament that was completed.\n\"\"\"\n\nfunction dwz_ranking(\n    players::Vector{Player},\n    ranking_scheme_to_update::String,\n    last_tournament_id::String\n)\n    updatedRankings = Dict{Int64, Int64}();\n    for player in players\n        if haskey(player.doubles_results, last_tournament_id)\n            player_ranking = player.rankings[\"Dwz\"]\n            teammate_ranking = search_dwz_ranking(player.doubles_results.partner_player_id, players)\n            achieved_points = 0\n            expected_points = 0\n            n = length(player.doubles_results[last_tournament_id])\n            for match in player.doubles_results[last_tournament_id].matches\n                zA = (player_ranking + teammate_ranking) / 2\n                zG = search_dwz_ranking(match.opponent1_player_id, players) + search_dwz_ranking(match.opponent2_player_id, players)\n                wE = 1/(1+(10^((zG-zA)/400)))\n                wA = match.result == \"Won\" ? 1 : 0\n                achieved_points += wA\n                expected_points += wE\n            end\n            if player.age < 20\n                J = 5\n            elseif player.age <= 25\n                J = 10\n            else\n                J = 15\n            end\n            E0 = (player_ranking/1000)^4 + J\n            a = player.age <= 20 && achieved_points > expected_points ? player_ranking/2000 : 1\n            B = player_ranking < 1300 && achieved_points <= expected_points ? exp((1300-player_ranking)/150)-1 : 0\n            E = a * E0 + B\n            Zn = player_ranking + (800/(E+n))(achieved_points-expected_points)\n            updatedRankings[player.id] = Zn\n        else\n            # If player didn't participate in tournament, their ranking doesn't change\n            updatedRankings[player.id] = player.rankings[\"Dwz\"];\n        end\n    end\n    map(player -> player.rankings[ranking_scheme_to_update] = updatedRankings[player.id], players)\n    return nothing\nend\n\n\n\"\"\"\n    function search_dwz_ranking(\n        player_id::Int64, \n        players::Vector{Player}\n    )::Float64 \n\nSearch for a player's current Dwz Ranking\n\nArguments\n=========\n- `player_id`:\n    the player whose ranking is under search.\n- `players`:\n    an array of players in the simulation.\n\"\"\"\n\nfunction search_dwz_ranking(\n    player_id::Int64, \n    players::Vector{Player}\n)::Float64 \n    player_ranking = filter(p -> p.id == player_id, players)[1].rankings[\"Dwz\"]\n    return player_ranking\nend", "meta": {"hexsha": "e26ccc867dc4b5738f0ca5e4184291f29f2ff456", "size": 2838, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algorithm/dwz_ranking.jl", "max_stars_repo_name": "Danial-Hussain/Tennis-Ranking", "max_stars_repo_head_hexsha": "0cc4f4e27158c0690a9d70b4bdb1ec621e11d212", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algorithm/dwz_ranking.jl", "max_issues_repo_name": "Danial-Hussain/Tennis-Ranking", "max_issues_repo_head_hexsha": "0cc4f4e27158c0690a9d70b4bdb1ec621e11d212", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithm/dwz_ranking.jl", "max_forks_repo_name": "Danial-Hussain/Tennis-Ranking", "max_forks_repo_head_hexsha": "0cc4f4e27158c0690a9d70b4bdb1ec621e11d212", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0, "max_line_length": 132, "alphanum_fraction": 0.6236786469, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7504817011910548}}
{"text": "using FFTW\nimport LinearAlgebra: svd, diag, diagm, eigen\nimport QuantumInfo: eye\n\nfunction hilbert(signal)\n\t# construct the Hilbert transform of the signal via the FFT\n\t# in essense, we just want to set negative frequency components to zero\n\tspectrum = fft(signal)\n\tn = length(signal)\n\tmidpoint = ceil(Int, n/2)\n\n\tkernel = zeros(n)\n\tkernel[1] = 1\n\tif iseven(n)\n\t\tkernel[midpoint + 1] = 1\n\tend\n\tkernel[2:midpoint] .= 2\n\tifft(kernel .* spectrum)\nend\n\nfunction KT_estimation(data, timeStep, order)\n\t#Perform a modified KT estimation to obtain the estimates of the parameters\n\t#from a set of data.\n\t#\n\t# function [freqs, Tcs, amps] = KT_estimation(data, timeStep, order)\n\t#\n\t# See ? Van Huffel, S. (1993). Enhanced resolution based on minimum variance estimation and exponential data modeling.\n\t#       Signal Processing, 33(3), 333-355. doi:10.1016/0165-1684(93)90130-3\n\n\tanalyticSig = hilbert(data)\n\n\t#Create the raw Hankel matrix\n\tN = length(analyticSig)\n\tK = order\n\tM = trunc(Integer, N/2)-1\n\tL = N-M+1\n\tH = zeros(ComplexF64, L, M)\n\tfor ct = 1:M\n\t    H[:,ct] = analyticSig[ct:ct+L-1]\n\tend\n\n\t#Try and seperate the signal and noise subspace via the svd\n\tU,S,V = svd(H)\n\n\t#Reconstruct the approximate Hankel matrix with the first K singular values\n\t#Here we can iterate and modify the singular values\n\tS_k = diagm(0=>S[1:K])\n\t#Estimate the variance from the rest of the singular values\n\tvarEst = (1/((M-K)*L)) * sum(S[K+1:end].^2)\n\tSfilt = (S_k.^2 - L*varEst*eye(K)) / S_k\n\tHbar = U[:,1:K] * Sfilt * V[:,1:K]'\n\n\t#Reconstruct the data from the averaged anti-diagonals\n\tcleanedData = zeros(ComplexF64, N)\n\ttmpMat = reverse(Hbar,dims=2)\n\tidx = -L+1\n\tfor ct = N:-1:1\n\t    cleanedData[ct] = mean(diag(tmpMat,idx))\n\t    idx += 1\n\tend\n\n\t#Create a cleaned Hankel matrix\n\tcleanedH = similar(H)\n\tcleanedAnalyticSig = hilbert(cleanedData)\n\tfor ct = 1:M\n\t    cleanedH[:,ct] = cleanedAnalyticSig[ct:ct+L-1]\n\tend\n\n\t#Compute Q with total least squares\n\t#U_K1*Q = U_K2\n\tU,_,_ = svd(cleanedH)\n\tU_K = U[:,1:K]\n\ttmpMat = [U_K[1:end-1,:] U_K[2:end,:]]\n\t_,_,V = svd(tmpMat)\n\tn = size(U_K,2)\n\tV_AB = V[1:n,1+n:end]\n\tV_BB = V[1+n:end,1+n:end]\n\tQ = -V_AB/V_BB\n\n\t#Now poles are eigenvalues of Q\n\tpoles, _ = eigen(Q)\n\n\t#Take the log and return the decay constant and frequency\n\tfreqs = zeros(K)\n\tTcs = zeros(K)\n\tfor ct = 1:K\n\t    sk = log(poles[ct])\n\t    freqs[ct] = imag(sk)/2/pi/timeStep\n\t    Tcs[ct] = -1/real(sk)*timeStep\n\tend\n\n\t#Refit the data to get the amplitude\n\tA = zeros(ComplexF64, N, K)\n\tfor ct = 1:K\n\t    A[:,ct] = poles[ct].^(0:N-1)\n\tend\n\n\tamps = A\\cleanedData\n\n\treturn freqs, Tcs, amps\n\nend\n", "meta": {"hexsha": "f7556f353776ee931448cb62c53600e4f5f13ab8", "size": 2577, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/KT_estimation.jl", "max_stars_repo_name": "BBN-Q/Qlab.jl", "max_stars_repo_head_hexsha": "2f6330adff30723eea4d7db15ce90c1114cfdd90", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2016-05-10T15:05:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:16:59.000Z", "max_issues_repo_path": "src/KT_estimation.jl", "max_issues_repo_name": "BBN-Q/Qlab.jl", "max_issues_repo_head_hexsha": "2f6330adff30723eea4d7db15ce90c1114cfdd90", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 38, "max_issues_repo_issues_event_min_datetime": "2016-08-02T13:08:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-30T06:23:46.000Z", "max_forks_repo_path": "src/KT_estimation.jl", "max_forks_repo_name": "BBN-Q/Qlab.jl", "max_forks_repo_head_hexsha": "2f6330adff30723eea4d7db15ce90c1114cfdd90", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-10-28T12:11:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:53:31.000Z", "avg_line_length": 25.0194174757, "max_line_length": 119, "alphanum_fraction": 0.670935196, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7504816989901993}}
{"text": "# Create confusion matrix for any number of classes\nfunction confusion_matrix(y_cond::Vector{Int}, y_pred::Vector{Int})\n\n    # Generate empty confusion matrix\n    classes = sort(unique([y_cond; y_pred]))\n    conf_matrix = zeros(Int64, length(classes), length(classes))\n\n    # Add counts\n    for i in 1:length(y_cond)\n        # translate label to index\n        cond_class_index = findfirst(classes, y_cond[i])\n        pred_class_index = findfirst(classes, y_pred[i])\n        # predicted class is the row, condition class is the column\n        conf_matrix[pred_class_index, cond_class_index] += 1\n  end\n\n  return conf_matrix\nend\n\n# plot confusion matrix\nfunction plot_confusion_matrix(y_cond::Vector{Int},\n                               y_pred::Vector{Int},\n                               ylabel::String = \"Var1\",\n                               xlabel::String = \"Var2\",\n                               classes::Vector{String} = string.(sort(unique([y_cond; y_pred]))))\n    # Number of classes\n    num = length(classes)\n\n    # Create DataFrame with data from confusion matrix\n    axes = vcat([[classes[i] classes[j]] for i in 1:num, j in 1:num]...)\n    df = DataFrame([axes confusion_matrix(y_cond, y_pred)[:]])\n\n    # Colormap\n    cmap = vcat(RGB(1,1,1), sequential_palette(255, 99, c=0.88, s=0.6, b=0.75, w=0.3, d=0.25,\n                            wcolor=RGB(1,1,1), dcolor=RGB(0,0,1), logscale=false))\n\n    # Plot\n    plot(df, x=\"x2\", y=\"x1\", color=\"x3\", Geom.rectbin,\n         Coord.cartesian(yflip=true, xflip=false, fixed=true),\n         Guide.YLabel(ylabel), Guide.XLabel(xlabel), Guide.colorkey(\"Count\"),\n         Scale.color_continuous(colormap = p->cmap[round(Int, p*99+1)], minvalue=0))\nend\n\n# Print accuracy stats\n# Optional to print short, medium or long version\nfunction print_binary_accuracy(y_cond::Vector{Int}, y_pred::Vector{Int}; size=\"short\")\n\n    # Check only 2 classes\n    length(unique([y_cond; y_pred])) > 2 && throw(\"function is only for 2 classes\")\n\n    # Create confusion matrix\n    CM = confusion_matrix(y_cond, y_pred)\n\n    # Calculate metrics\n\n    # 1st level metrics\n    Population = sum(CM)          # Total number in population\n\n    TP = CM[1, 1]                 # \"True Positive\" / \"Hit\"\n    TN = CM[2, 2]                 # \"True Negative\" / \"Correct Reject\"\n    FP = CM[1, 2]                 # \"False Positive\" / \"False Alarm\" / Type I Error\n    FN = CM[2, 1]                 # \"False Negative\" / \"Miss\" / Type II Error\n\n    CondPos = TP + FN             # Sum of Condition = Positive\n    CondNeg = FP + TN             # Sum of Condition = Negative\n    PredPos = TP + FP             # Sum of Prediction = Positive\n    PredNeg = FN + TN             # Sum of Prediction = Negative\n\n    # 2nd level metrics\n\n    TPR = TP / CondPos            # True Positive Rate / Sensitivity / Hit Rate / Recall\n    TNR = TN / CondNeg            # True Negative Rate / Specificity\n    PPV = TP / PredPos            # Positive Predictive Value / Precision\n    NPV = TN / PredNeg            # Negative Predictive Value\n    FPR = FP / CondNeg            # False Positive Rate / Fall-out\n    FDR = FP / PredNeg            # False Discovery Rate\n    FNR = FN / CondNeg            # False Negative Rate\n    FOR = FN / PredNeg            # False Omission Rate\n\n    # 3rd level metrics\n\n    Accuracy = (TP + TN) / Population                  # Accuracy Rate\n    PosLR = TPR / FPR                                  # Positive Likelihood Ratio\n    NegLR = FNR / TNR                                  # Negative Likelihood Ratio\n    DiagOR = PosLR / NegLR                             # Diagnostic Odds Ratio\n\n    # F Scores i.e. F_β = ((1 + β^2) * PPV * TPR)/ (β^2 * PPV + TPR)\n    F_1 = (2 * PPV * TPR) / (PPV + TPR)                # F1 Score / Harmonic Mean of Precision and Recall\n    F_2 = (5 * PPV * TPR) / (4 * PPV + TPR)            # F2 Score - weights recall higher than precision\n    F_05 = (1.25 * PPV * TPR) / (0.25 * PPV + TPR)     # F0.5 Score - weights precision higher than recall\n\n    # Matthews's Correlation Coefficient\n    # Guideline:\n    # +1 = perfect prediction, 0 = no better than random, -1 = total disagreement\n    MCC = (TP*TN - FP*FN) / sqrt((TP+FP)*(TP+FN)*(TN+FP)*(TN+FN))\n\n    # Kappa Coefficient - compares Observed Accuracy with Expected Accuracy (random chance)\n    # Guidelines:\n    # L&K: <0 = no agreement, 0-0.20 = slight, 0.21-0.40 = fair, 0.41-0.60 = moderate, 0.61-0.80 = substantial, 0.81-1 = almost perfect\n    # Fleiss: <0.4 = poor, 0.40-0.75 = fair to good, >0.75 = excellent\n    ObsAcc = (TP + TN) / Population                                    # Observed Accuracy\n    ExpAcc = (CondPos * PredPos + CondNeg * PredNeg) / Population^2    # Expected Accuracy\n    Kappa = (ObsAcc - ExpAcc) / (1 - ExpAcc)                           # Kappa\n\n    # Display metrics\n    if size == \"short\"\n        @printf \"Accuracy:    %f\\n\" Accuracy\n        @printf \"F_1:         %f\\n\" F_1\n    elseif size == \"medium\"\n        @printf \"Accuracy:    %f\\n\" Accuracy\n        @printf \"F_1:         %f\\n\" F_1\n        @printf \"F_2:         %f\\n\" F_2\n        @printf \"F_05:        %f\\n\" F_05\n        @printf \"MCC:         %f\\n\" MCC\n        @printf \"Kappa:       %f\\n\" Kappa\n    elseif size == \"long\"\n        @printf \"Accuracy:    %f\\n\" Accuracy\n        @printf \"F_1:         %f\\n\" F_1\n        @printf \"F_2:         %f\\n\" F_2\n        @printf \"F_05:        %f\\n\" F_05\n        @printf \"MCC:         %f\\n\" MCC\n        @printf \"Kappa:       %f\\n\" Kappa\n        @printf \"Precision:   %f\\n\" PPV\n        @printf \"Recall:      %f\\n\" TPR\n        @printf \"Specificity: %f\\n\" TNR\n    end\nend\n\n# ROC Curve\n", "meta": {"hexsha": "b363fa0a5ea008d097f3d22d1578be4f5c5505b0", "size": 5608, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/accuracy.jl", "max_stars_repo_name": "Wedg/MLTools.jl", "max_stars_repo_head_hexsha": "950220ef92a16c16de5051545845a4697ef15cb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-09-25T12:57:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-10T23:54:02.000Z", "max_issues_repo_path": "src/accuracy.jl", "max_issues_repo_name": "Wedg/MLTools.jl", "max_issues_repo_head_hexsha": "950220ef92a16c16de5051545845a4697ef15cb0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/accuracy.jl", "max_forks_repo_name": "Wedg/MLTools.jl", "max_forks_repo_head_hexsha": "950220ef92a16c16de5051545845a4697ef15cb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.1384615385, "max_line_length": 135, "alphanum_fraction": 0.5531383738, "num_tokens": 1618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570318, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7504336258961716}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.10\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing DataFrames, CSV, Dates, StatsBase, Plots, TimeSeries\nend\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing4.20\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tdata = CSV.read(datadir(\"temperatures.csv\"),copycols = true)\n\tbrisbane = data.Brisbane\n\tdates = [Date(\n\t\t\t\tYear(data.Year[i]), \n\t\t\t\tMonth(data.Month[i]), \n\t\t\t\tDay(data.Day[i])\n\t\t\t) for i in 1:nrow(data)]\n\n\twindow1, window2 = 7, 14\n\td1 = values(moving(mean,TimeArray(dates,brisbane),window1))\n\td2 = values(moving(mean,TimeArray(dates,brisbane),window2))\nend;\n\n# ╔═╡ 56bc1334-250c-11eb-3c15-f98b6097c3a6\nbegin\n\tgrid = (2pi:-2pi/365:0) .+ pi/2\n\tmonthsNames = Dates.monthname.(dates[1:31:365])\n\n\tplot(grid, d1[1:366], \n\t\tc=:blue, proj=:polar, label=\"Brisbane weekly average temp.\")\n\tplot!(grid, d2[1:366], \n\t\txticks=([mod.((11pi/6:-pi/6:0) .+ pi/2,2pi) ;], monthsNames),\n\t\tc=:red, proj=:polar, \n\t\tlabel=\"Brisbane fortnightly average temp.\", legend=:outerbottom)\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing4.20\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═56bc1334-250c-11eb-3c15-f98b6097c3a6\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "27701484ca2428da012ca67df68d4041506e94bd", "size": 1519, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/04/listing4.20.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/04/listing4.20.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/04/listing4.20.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 26.649122807, "max_line_length": 66, "alphanum_fraction": 0.7077024358, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7504336206655104}}
{"text": "import RowEchelon\n\n#=\nHomework 3\nSection 1.7\nProblem 41\n=#\n\nimport RowEchelon\n\n#=\nHomework 3\nSection 1.7\nProblem 5\n=#\n\n# Create the matrix\nA = [3 -4 10 7 -4 ;\n\t -5 -3 -7 -11 15 ;\n\t 4 3 5 2 1 ;\n\t 8 -7 23 4 15]\n\n# Row Reduce the matrix\nA_rref = RowEchelon.rref(A)\n\n# Store the rows and columns of A\nrows = size(A)[1]\ncols = size(A)[2]\n\n# Find the pivot columns\npivotCols = zeros(0)\nfor i = 1:rows\n\tfor j = 1:cols\n\t\tif A_rref[i,j] != 0\n\t\t\tappend!(pivotCols,j)\n\t\t\tbreak\n\t\tend\n\tend\nend\n\n# The columns we want are the pivot columns\nB = Array{Float64}(undef, 4, 0)\nfor col in pivotCols\n\tglobal B\n\tB = hcat(B, A[:,Int64(col)])\nend\n\n# Row Reduce\nB_rref = RowEchelon.rref(B)\n\n# Print results:\nprintln(\"Original Matrix:\")\nprintln(A)\nprint(\"Matrix made from columns \")\nprint(pivotCols)\nprintln(\":\")\nprintln(B)\nprintln(\"Row Reduced:\")\nprintln(B_rref)\n", "meta": {"hexsha": "adf891045a09e567e1c6f1079fae7f8bdf690e59", "size": 838, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HW3_S1.7_P41.jl", "max_stars_repo_name": "tleecsm/J4LA", "max_stars_repo_head_hexsha": "0ff51fa1771e9b5fc0b8a684a65cb36cebb8eefb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW3_S1.7_P41.jl", "max_issues_repo_name": "tleecsm/J4LA", "max_issues_repo_head_hexsha": "0ff51fa1771e9b5fc0b8a684a65cb36cebb8eefb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW3_S1.7_P41.jl", "max_forks_repo_name": "tleecsm/J4LA", "max_forks_repo_head_hexsha": "0ff51fa1771e9b5fc0b8a684a65cb36cebb8eefb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.9666666667, "max_line_length": 43, "alphanum_fraction": 0.6622911695, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7504336177192963}}
{"text": "\"\"\"\n    PoissonProcess{T<:Real} <: AbstractMarkovChain\n\n##### Fields\n- `rate::T` : the rate; i.e., the parameter \"lambda\".\n\"\"\"\nstruct PoissonProcess{T<:Real} <: AbstractMarkovChain\n    rate::T\nend\n\n\"\"\"\n    Base.show(io::IO, pp::PoissonProcess) -> nothing\n\nShow a `PoissonProcess` in a human-friendly manner.\n\"\"\"\nfunction Base.show(io::IO, pp::PoissonProcess)\n    println(io, typeof(pp))\n    println(io, \" Rate (i.e. lambda):\")\n    println(io, pp.rate)\n    return nothing\nend\n\n\"\"\"\n    Base.eltype(pp::PoissonProcess) -> DataType\n\nReturn the type associated with `pp`'s `rate` parameter.\n\"\"\"\nfunction Base.eltype(pp::PoissonProcess)\n    return typeof(pp.rate)\nend\n\n\"\"\"\n    nexpectedarrivals(pp::PoissonProcess, intervallength::Real) -> Int\n\nReturn the expected number of arrivals `E[N(intervallength)]` over the time interval\n`[0, intervallength]` for `pp`.\n\n##### Complexity\n-Time complexity: `O(1)`.\n\"\"\"\nfunction nexpectedarrivals(pp::PoissonProcess, intervallength::Real)\n    return pp.rate*intervallength\nend\n", "meta": {"hexsha": "3ff31cadee259d2931254ea5ae747d19dcec392a", "size": 1011, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PoissonProcesses/poissonprocesses.jl", "max_stars_repo_name": "LoganDGraham/StochasticProcesses", "max_stars_repo_head_hexsha": "c3f9947d9f93c9d8397664ed3acf93c8bf7da444", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-11-15T19:57:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T22:42:14.000Z", "max_issues_repo_path": "src/PoissonProcesses/poissonprocesses.jl", "max_issues_repo_name": "LoganDGraham/StochasticProcesses", "max_issues_repo_head_hexsha": "c3f9947d9f93c9d8397664ed3acf93c8bf7da444", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-02T16:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-14T17:56:52.000Z", "max_forks_repo_path": "src/PoissonProcesses/poissonprocesses.jl", "max_forks_repo_name": "LoganDGraham/StochasticProcesses", "max_forks_repo_head_hexsha": "c3f9947d9f93c9d8397664ed3acf93c8bf7da444", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9772727273, "max_line_length": 84, "alphanum_fraction": 0.6894164194, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7504336158554765}}
{"text": "\"\"\"\n    entropy(P)\n\nComputes the entropy of a distribution.\n\"\"\"\nfunction entropy(P; norm=false)\n    if norm\n        P /= sum(P)\n    end\n    return - sum(P[P.>0] .* log.(P[P.>0]))\nend\n\n\"\"\"\n    relative_entropy(P, Q)\n\nComputes the relative entropy of P to Q.\n\"\"\"\nrelative_entropy(P, Q) = - sum(P .* log.(Q))\n\n\"\"\"\n    KL(P, Q)\n\nComputes the Kullback-Leibler divergence of P to Q\n\"\"\"\nKL(P, Q) = relative_entropy(P, Q) - entropy(P)\n\n\n\"\"\"\n    utility(P, M)\n\nComputes the average utility.\n\"\"\"\nfunction utility(P, M)\n    return sum(P .* M)\nend\n\nfunction report_utility(P, M, bottom_species=nothing, top_species=nothing)\n    @assert size(P) == size(M) \"P and M should be of the same size\"\n    n, m = size(P)\n    bottom_species == nothing && bottom_species == 1:n\n    top_species == nothing && top_species == 1:m\n    U = P .* M\n    a, b = marginals(P)\n    println(\"Bottom species\")\n    for i in 1:n\n        println(\"\\t$(bottom_species[i]): utility = $(sum(U[i,:]) / a[i]), entropy = $(\n                                entropy(P[i,:] |> x -> x / sum(x)))\")\n    end\n    println()\n    println(\"Top species\")\n    for j in 1:m\n        println(\"\\t$(top_species[j]): utility = $(sum(U[:,j] / b[j])), entropy = $(\n                                entropy(P[:,j] |> x -> x / sum(x)))\")\n    end\n    println()\n    println(\"Average utility = $(sum(U))\")\n    println(\"Average entropy = $(entropy(P))\")\nend\n", "meta": {"hexsha": "1fb47f4630d075b2d4439699ec6cbdcc42e58776", "size": 1382, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/metrics.jl", "max_stars_repo_name": "PoisotLab/OTSIN", "max_stars_repo_head_hexsha": "52b240a1cbf61f15bc58fcb3bb5c8ab5a8153082", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/metrics.jl", "max_issues_repo_name": "PoisotLab/OTSIN", "max_issues_repo_head_hexsha": "52b240a1cbf61f15bc58fcb3bb5c8ab5a8153082", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/metrics.jl", "max_forks_repo_name": "PoisotLab/OTSIN", "max_forks_repo_head_hexsha": "52b240a1cbf61f15bc58fcb3bb5c8ab5a8153082", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4237288136, "max_line_length": 86, "alphanum_fraction": 0.5484804631, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7504171916403991}}
{"text": "using Distributions\nimport Base.size, Base.length, Base.rand, Base.mean, Base.convert\n\ndoc\"\"\"\n    MatrixNormal(M, U, V)\nThe *Matrix Normal distribution* with mean `M` and row and column covariances `U` and `V` has probability density function\n$f(\\mathbf{X}; \\mathbf{M}, \\mathbf{U}, \\mathbf{V}) = \\frac{\\exp\\left(\n    -\\frac{1}{2} \\mathrm{tr}\\left[\n        \\mathbf{V}^{-1} (\\mathbf{X} - \\mathbf{M})^\\top \\mathbf{U}^{-1}\n        (\\mathbf{X} - \\mathbf{M})\n    \\right]\n    \\right)}{(2\\pi)^{np/2} |\\mathbf{V}|^{n/2} |\\mathbf{U}|^{p/2}}$\nwhen $\\mathbf{X}$ is $n \\times p$.\n```julia\nMatrixNormal(U, V)      # Matrix Normal with mean 0 and covariances U and V\nMatrixNormal(M, U, V)      # Matrix Normal with mean M and covariances U and V\nparams(d)        # Get the parameters, i.e. (M, U, V)\nmean(d)          # Get the mean, i.e., M\ncov(d)           # Get the covariance, i.e., V ⊗ U\nvar(d)           # Get the marginal variances for individual entries\ninvcov(d)        # inverse of covariance\nlogdetcov(d)     # log determinant of covariance\nlogpdf(d, X)     # log of the pdf at point X\n```\nExternal links\n* [Matrix Normal distribution on Wikipedia](http://en.wikipedia.org/wiki/Matrix_normal_distribution)\n\"\"\"\nimmutable MatrixNormal{Mean<:AbstractMatrix, CovU<:AbstractPDMat, CovV<:AbstractPDMat} <: ContinuousMatrixDistribution\n    M::Mean\n    U::CovU\n    V::CovV\nend\n\n### Constructors\ntypealias CovLike Union{AbstractMatrix, AbstractVector, AbstractPDMat}\nnormalize(σ::AbstractVector) = PDiagMat(abs2(σ))\nnormalize(Σ::AbstractMatrix) = PDMat(Σ)\nnormalize(Σ::AbstractPDMat) = Σ\nnormalize(d::Int, σ::Real) = PDScalMat(d, abs2(σ))\n\nfunction MatrixNormal{Mean <: AbstractMatrix, CovU<:AbstractPDMat, CovV<:AbstractPDMat}(M::Mean, U::CovU, V::CovV)\n    size(M) == (dim(U), dim(V)) || throw(DimensionMismatch(\"The dimensions of M, U, and V are inconsistent.\"))\n    MatrixNormal{Mean, CovU, CovV}(M, U, V)\nend\nfunction MatrixNormal{Mean<:AbstractMatrix, CovU<:CovLike, CovV<:CovLike}(M::Mean, U::CovU, V::CovV)\n    MatrixNormal(M, normalize(U), normalize(V))\nend\n\nMatrixNormal{CovU<:AbstractPDMat, CovV<:AbstractPDMat}(U::CovU, V::CovV) = MatrixNormal(zeros(dim(U), dim(V)), U, V)\nMatrixNormal{CovU<:CovLike, CovV<:CovLike}(U::CovU, V::CovV) = MatrixNormal(normalize(U), normalize(V))\n\n### Conversions\nconvert(::Type{MvNormal}, d::MatrixNormal) = MvNormal(vec(mean(d)), cov(d))\n\n### interface\nsize(d::MatrixNormal) = (dim(d.U), dim(d.V))\nparams(d::MatrixNormal) = (d.M, d.U, d.V)\nmean(d::MatrixNormal) = d.M\ncov(d::MatrixNormal) = kron(full(d.V), full(d.U))\nvar(d::MatrixNormal) = diag(d.U) * diag(d.V)'\ninvcov(d::MatrixNormal) = kron(full(inv(d.V)), full(inv(d.U)))\nlogdetcov(d::MatrixNormal) = ((n, p) = size(d); n * logdet(d.V) + p * logdet(d.U))\n\nrand(d::MatrixNormal) = reshape(rand(convert(MvNormal, d)), size(d))\nentropy(d::MatrixNormal) = entropy(convert(MvNormal, d))\n\nfunction logpdf(d::MatrixNormal, X::AbstractMatrix)\n    size(X) == size(d) || error(\"Input matrix x has wrong size.\")\n    m = X - d.M\n    n, p = size(d)\n    invU = full(inv(d.U))\n    invV = full(inv(d.V))\n    lpdf = -0.5 * trace(invV * m' * invU * m)\n    lpdf -= (n * p/2) * Float64(Distributions.log2π)\n    lpdf -= 0.5 * logdetcov(d)\n    lpdf\nend\n", "meta": {"hexsha": "05705f14381eb483e59e6ad15bfc909e9541bfab", "size": 3216, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distributions/matrixnormal.jl", "max_stars_repo_name": "lbollar/VinDsl.jl", "max_stars_repo_head_hexsha": "3445e98c634b711f4583cfa4d422d3a3ee99a4f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2016-03-31T20:48:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T20:21:24.000Z", "max_issues_repo_path": "src/distributions/matrixnormal.jl", "max_issues_repo_name": "lbollar/VinDsl.jl", "max_issues_repo_head_hexsha": "3445e98c634b711f4583cfa4d422d3a3ee99a4f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2016-03-21T02:01:51.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-06T15:41:19.000Z", "max_forks_repo_path": "src/distributions/matrixnormal.jl", "max_forks_repo_name": "lbollar/VinDsl.jl", "max_forks_repo_head_hexsha": "3445e98c634b711f4583cfa4d422d3a3ee99a4f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-03-31T16:21:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:13:28.000Z", "avg_line_length": 41.2307692308, "max_line_length": 122, "alphanum_fraction": 0.6560945274, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.8006920068519378, "lm_q1q2_score": 0.7504171908159486}}
{"text": "@doc doc\"\"\"\n    LPDistLoss{P} <: DistanceLoss\n\nThe P-th power absolute distance loss. It is Lipschitz continuous\niff `P == 1`, convex if and only if `P >= 1`, and strictly convex\niff `P > 1`.\n\n```math\nL(r) = |r|^P\n```\n\"\"\"\nstruct LPDistLoss{P} <: DistanceLoss end\n\nLPDistLoss(p::Number) = LPDistLoss{p}()\n\nvalue(loss::LPDistLoss{P}, difference::Number) where {P} = abs(difference)^P\nfunction deriv(loss::LPDistLoss{P}, difference::T)::promote_type(typeof(P),T) where {P,T<:Number}\n    if difference == 0\n        zero(difference)\n    else\n        P * difference * abs(difference)^(P-convert(typeof(P), 2))\n    end\nend\nfunction deriv2(loss::LPDistLoss{P}, difference::T)::promote_type(typeof(P),T) where {P,T<:Number}\n    if difference == 0\n        zero(difference)\n    else\n        (abs2(P)-P) * abs(difference)^P / abs2(difference)\n    end\nend\n\nisminimizable(::LPDistLoss{P}) where {P} = true\nissymmetric(::LPDistLoss{P}) where {P} = true\nisdifferentiable(::LPDistLoss{P}) where {P} = P > 1\nisdifferentiable(::LPDistLoss{P}, at) where {P} = P > 1 || at != 0\nistwicedifferentiable(::LPDistLoss{P}) where {P} = P > 1\nistwicedifferentiable(::LPDistLoss{P}, at) where {P} = P > 1 || at != 0\nislipschitzcont(::LPDistLoss{P}) where {P} = P == 1\nislocallylipschitzcont(::LPDistLoss{P}) where {P} = P >= 1\nisconvex(::LPDistLoss{P}) where {P} = P >= 1\nisstrictlyconvex(::LPDistLoss{P}) where {P} = P > 1\nisstronglyconvex(::LPDistLoss{P}) where {P} = P >= 2\n\n# ===========================================================\n\n@doc doc\"\"\"\n    L1DistLoss <: DistanceLoss\n\nThe absolute distance loss.\nSpecial case of the [`LPDistLoss`](@ref) with `P=1`.\nIt is Lipschitz continuous and convex, but not strictly convex.\n\n```math\nL(r) = |r|\n```\n\n---\n```\n              Lossfunction                     Derivative\n      ┌────────────┬────────────┐      ┌────────────┬────────────┐\n    3 │\\.                     ./│    1 │            ┌------------│\n      │ '\\.                 ./' │      │            |            │\n      │   \\.               ./   │      │            |            │\n      │    '\\.           ./'    │      │_           |           _│\n    L │      \\.         ./      │   L' │            |            │\n      │       '\\.     ./'       │      │            |            │\n      │         \\.   ./         │      │            |            │\n    0 │          '\\./'          │   -1 │------------┘            │\n      └────────────┴────────────┘      └────────────┴────────────┘\n      -3                        3      -3                        3\n                 ŷ - y                            ŷ - y\n```\n\"\"\"\nconst L1DistLoss = LPDistLoss{1}\n\nvalue(loss::L1DistLoss, difference::Number) = abs(difference)\nderiv(loss::L1DistLoss, difference::T) where {T<:Number} = convert(T, sign(difference))\nderiv2(loss::L1DistLoss, difference::T) where {T<:Number} = zero(T)\n\nisdifferentiable(::L1DistLoss) = false\nisdifferentiable(::L1DistLoss, at) = at != 0\nistwicedifferentiable(::L1DistLoss) = false\nistwicedifferentiable(::L1DistLoss, at) = at != 0\nislipschitzcont(::L1DistLoss) = true\nisconvex(::L1DistLoss) = true\nisstrictlyconvex(::L1DistLoss) = false\nisstronglyconvex(::L1DistLoss) = false\n\n# ===========================================================\n\n@doc doc\"\"\"\n    L2DistLoss <: DistanceLoss\n\nThe least squares loss.\nSpecial case of the [`LPDistLoss`](@ref) with `P=2`.\nIt is strictly convex.\n\n```math\nL(r) = |r|^2\n```\n\n---\n```\n              Lossfunction                     Derivative\n      ┌────────────┬────────────┐      ┌────────────┬────────────┐\n    9 │\\                       /│    3 │                   .r/   │\n      │\".                     .\"│      │                 .r'     │\n      │ \".                   .\" │      │              _./'       │\n      │  \".                 .\"  │      │_           .r/         _│\n    L │   \".               .\"   │   L' │         _:/'            │\n      │    '\\.           ./'    │      │       .r'               │\n      │      \\.         ./      │      │     .r'                 │\n    0 │        \"-.___.-\"        │   -3 │  _/r'                   │\n      └────────────┴────────────┘      └────────────┴────────────┘\n      -3                        3      -2                        2\n                 ŷ - y                            ŷ - y\n```\n\"\"\"\nconst L2DistLoss = LPDistLoss{2}\n\nvalue(loss::L2DistLoss, difference::Number) = abs2(difference)\nderiv(loss::L2DistLoss, difference::T) where {T<:Number} = convert(T,2) * difference\nderiv2(loss::L2DistLoss, difference::T) where {T<:Number} = convert(T,2)\n\nisdifferentiable(::L2DistLoss) = true\nisdifferentiable(::L2DistLoss, at) = true\nistwicedifferentiable(::L2DistLoss) = true\nistwicedifferentiable(::L2DistLoss, at) = true\nislipschitzcont(::L2DistLoss) = false\nisconvex(::L2DistLoss) = true\nisstrictlyconvex(::L2DistLoss) = true\nisstronglyconvex(::L2DistLoss) = true\n\n# ===========================================================\n\n@doc doc\"\"\"\n    PeriodicLoss <: DistanceLoss\n\nMeasures distance on a circle of specified circumference `c`.\n\n```math\nL(r) = 1 - \\cos \\left( \\frac{2 r \\pi}{c} \\right)\n```\n\"\"\"\nstruct PeriodicLoss{T<:AbstractFloat} <: DistanceLoss\n    k::T   # k = 2π/circumference\n    function PeriodicLoss{T}(circ::T) where T\n        circ > 0 || error(\"circumference should be strictly positive\")\n        new{T}(convert(T, 2π/circ))\n    end\nend\nPeriodicLoss(circ::T=1.0) where {T<:AbstractFloat} = PeriodicLoss{T}(circ)\nPeriodicLoss(circ) = PeriodicLoss{Float64}(Float64(circ))\n\nvalue(loss::PeriodicLoss, difference::T) where {T<:Number} = 1 - cos(difference*loss.k)\nderiv(loss::PeriodicLoss, difference::T) where {T<:Number} = loss.k * sin(difference*loss.k)\nderiv2(loss::PeriodicLoss, difference::T) where {T<:Number} = abs2(loss.k) * cos(difference*loss.k)\n\nisdifferentiable(::PeriodicLoss) = true\nisdifferentiable(::PeriodicLoss, at) = true\nistwicedifferentiable(::PeriodicLoss) = true\nistwicedifferentiable(::PeriodicLoss, at) = true\nislipschitzcont(::PeriodicLoss) = true\nisconvex(::PeriodicLoss) = false\nisstrictlyconvex(::PeriodicLoss) = false\nisstronglyconvex(::PeriodicLoss) = false\n\n\n# ===========================================================\n\n@doc doc\"\"\"\n    HuberLoss <: DistanceLoss\n\nLoss function commonly used for robustness to outliers.\nFor large values of `d` it becomes close to the [`L1DistLoss`](@ref),\nwhile for small values of `d` it resembles the [`L2DistLoss`](@ref).\nIt is Lipschitz continuous and convex, but not strictly convex.\n\n```math\nL(r) = \\begin{cases} \\frac{r^2}{2} & \\quad \\text{if } | r | \\le \\alpha \\\\ \\alpha | r | - \\frac{\\alpha^3}{2} & \\quad \\text{otherwise}\\\\ \\end{cases}\n```\n\n---\n```\n              Lossfunction (d=1)               Derivative\n      ┌────────────┬────────────┐      ┌────────────┬────────────┐\n    2 │                         │    1 │                .+-------│\n      │                         │      │              ./'        │\n      │\\.                     ./│      │             ./          │\n      │ '.                   .' │      │_           ./          _│\n    L │   \\.               ./   │   L' │           /'            │\n      │     \\.           ./     │      │          /'             │\n      │      '.         .'      │      │        ./'              │\n    0 │        '-.___.-'        │   -1 │-------+'                │\n      └────────────┴────────────┘      └────────────┴────────────┘\n      -2                        2      -2                        2\n                 ŷ - y                            ŷ - y\n```\n\"\"\"\nstruct HuberLoss{T<:AbstractFloat} <: DistanceLoss\n    d::T   # boundary between quadratic and linear loss\n    function HuberLoss{T}(d::T) where T\n        d > 0 || error(\"Huber crossover parameter must be strictly positive.\")\n        new{T}(d)\n    end\nend\nHuberLoss(d::T=1.0) where {T<:AbstractFloat} = HuberLoss{T}(d)\nHuberLoss(d) = HuberLoss{Float64}(Float64(d))\n\nfunction value(loss::HuberLoss{T1}, difference::T2) where {T1,T2<:Number}\n    T = promote_type(T1,T2)\n    abs_diff = abs(difference)\n    if abs_diff <= loss.d\n        return convert(T,0.5)*abs2(difference)   # quadratic\n    else\n        return (loss.d*abs_diff) - convert(T,0.5)*abs2(loss.d)   # linear\n    end\nend\nfunction deriv(loss::HuberLoss{T1}, difference::T2) where {T1,T2<:Number}\n    T = promote_type(T1,T2)\n    if abs(difference) <= loss.d\n        return convert(T,difference)   # quadratic\n    else\n        return loss.d*convert(T,sign(difference))   # linear\n    end\nend\nfunction deriv2(loss::HuberLoss{T1}, difference::T2) where {T1,T2<:Number}\n    T = promote_type(T1,T2)\n    abs(difference) <= loss.d ? one(T) : zero(T)\nend\n\nisdifferentiable(::HuberLoss) = true\nisdifferentiable(l::HuberLoss, at) = true\nistwicedifferentiable(::HuberLoss) = false\nistwicedifferentiable(l::HuberLoss, at) = at != abs(l.d)\nislipschitzcont(::HuberLoss) = true\nisconvex(::HuberLoss) = true\nisstrictlyconvex(::HuberLoss) = false\nisstronglyconvex(::HuberLoss) = false\nissymmetric(::HuberLoss) = true\n\n# ===========================================================\n\n@doc doc\"\"\"\n    L1EpsilonInsLoss <: DistanceLoss\n\nThe ``ϵ``-insensitive loss. Typically used in linear support vector\nregression. It ignores deviances smaller than ``ϵ``, but penalizes\nlarger deviances linarily.\nIt is Lipschitz continuous and convex, but not strictly convex.\n\n```math\nL(r) = \\max \\{ 0, | r | - \\epsilon \\}\n```\n\n---\n```\n              Lossfunction (ϵ=1)               Derivative\n      ┌────────────┬────────────┐      ┌────────────┬────────────┐\n    2 │\\                       /│    1 │                  ┌------│\n      │ \\                     / │      │                  |      │\n      │  \\                   /  │      │                  |      │\n      │   \\                 /   │      │_      ___________!     _│\n    L │    \\               /    │   L' │      |                  │\n      │     \\             /     │      │      |                  │\n      │      \\           /      │      │      |                  │\n    0 │       \\_________/       │   -1 │------┘                  │\n      └────────────┴────────────┘      └────────────┴────────────┘\n      -3                        3      -2                        2\n                 ŷ - y                            ŷ - y\n```\n\"\"\"\nstruct L1EpsilonInsLoss{T<:AbstractFloat} <: DistanceLoss\n    ε::T\n\n    function L1EpsilonInsLoss{T}(ɛ::T) where T\n        ɛ > 0 || error(\"ɛ must be strictly positive\")\n        new{T}(ɛ)\n    end\nend\nconst EpsilonInsLoss = L1EpsilonInsLoss\n@inline L1EpsilonInsLoss(ε::T) where {T<:AbstractFloat} = L1EpsilonInsLoss{T}(ε)\n@inline L1EpsilonInsLoss(ε::Number) = L1EpsilonInsLoss{Float64}(Float64(ε))\n\nfunction value(loss::L1EpsilonInsLoss{T1}, difference::T2) where {T1,T2<:Number}\n    T = promote_type(T1,T2)\n    max(zero(T), abs(difference) - loss.ε)\nend\nfunction deriv(loss::L1EpsilonInsLoss{T1}, difference::T2) where {T1,T2<:Number}\n    T = promote_type(T1,T2)\n    abs(difference) <= loss.ε ? zero(T) : convert(T,sign(difference))\nend\nderiv2(loss::L1EpsilonInsLoss{T1}, difference::T2) where {T1,T2<:Number} = zero(promote_type(T1,T2))\n\nissymmetric(::L1EpsilonInsLoss) = true\nisdifferentiable(::L1EpsilonInsLoss) = false\nisdifferentiable(loss::L1EpsilonInsLoss, at) = abs(at) != loss.ε\nistwicedifferentiable(::L1EpsilonInsLoss) = false\nistwicedifferentiable(loss::L1EpsilonInsLoss, at) = abs(at) != loss.ε\nislipschitzcont(::L1EpsilonInsLoss) = true\nisconvex(::L1EpsilonInsLoss) = true\nisstrictlyconvex(::L1EpsilonInsLoss) = false\nisstronglyconvex(::L1EpsilonInsLoss) = false\n\n# ===========================================================\n\n@doc doc\"\"\"\n    L2EpsilonInsLoss <: DistanceLoss\n\nThe quadratic ``ϵ``-insensitive loss.\nTypically used in linear support vector regression.\nIt ignores deviances smaller than ``ϵ``, but penalizes\nlarger deviances quadratically. It is convex, but not strictly convex.\n\n```math\nL(r) = \\max \\{ 0, | r | - \\epsilon \\}^2\n```\n\n---\n```\n              Lossfunction (ϵ=0.5)             Derivative\n      ┌────────────┬────────────┐      ┌────────────┬────────────┐\n    8 │                         │    1 │                  /      │\n      │:                       :│      │                 /       │\n      │'.                     .'│      │                /        │\n      │ \\.                   ./ │      │_         _____/        _│\n    L │  \\.                 ./  │   L' │         /               │\n      │   \\.               ./   │      │        /                │\n      │    '\\.           ./'    │      │       /                 │\n    0 │      '-._______.-'      │   -1 │      /                  │\n      └────────────┴────────────┘      └────────────┴────────────┘\n      -3                        3      -2                        2\n                 ŷ - y                            ŷ - y\n```\n\"\"\"\nstruct L2EpsilonInsLoss{T<:AbstractFloat} <: DistanceLoss\n    ε::T\n\n    function L2EpsilonInsLoss{T}(ɛ::T) where T\n        ɛ > 0 || error(\"ɛ must be strictly positive\")\n        new{T}(ɛ)\n    end\nend\nL2EpsilonInsLoss(ε::T) where {T<:AbstractFloat} = L2EpsilonInsLoss{T}(ε)\nL2EpsilonInsLoss(ε) = L2EpsilonInsLoss{Float64}(Float64(ε))\n\nfunction value(loss::L2EpsilonInsLoss{T1}, difference::T2) where {T1,T2<:Number}\n    T = promote_type(T1,T2)\n    abs2(max(zero(T), abs(difference) - loss.ε))\nend\nfunction deriv(loss::L2EpsilonInsLoss{T1}, difference::T2) where {T1,T2<:Number}\n    T = promote_type(T1,T2)\n    absr = abs(difference)\n    absr <= loss.ε ? zero(T) : convert(T,2)*sign(difference)*(absr - loss.ε)\nend\nfunction deriv2(loss::L2EpsilonInsLoss{T1}, difference::T2) where {T1,T2<:Number}\n    T = promote_type(T1,T2)\n    abs(difference) <= loss.ε ? zero(T) : convert(T,2)\nend\n\nissymmetric(::L2EpsilonInsLoss) = true\nisdifferentiable(::L2EpsilonInsLoss) = true\nisdifferentiable(::L2EpsilonInsLoss, at) = true\nistwicedifferentiable(::L2EpsilonInsLoss) = false\nistwicedifferentiable(loss::L2EpsilonInsLoss, at) = abs(at) != loss.ε\nislipschitzcont(::L2EpsilonInsLoss) = false\nisconvex(::L2EpsilonInsLoss) = true\nisstrictlyconvex(::L2EpsilonInsLoss) = true\nisstronglyconvex(::L2EpsilonInsLoss) = true\n\n# ===========================================================\n\n@doc doc\"\"\"\n    LogitDistLoss <: DistanceLoss\n\nThe distance-based logistic loss for regression.\nIt is strictly convex and Lipschitz continuous.\n\n```math\nL(r) = - \\ln \\frac{4 e^r}{(1 + e^r)^2}\n```\n\n---\n```\n              Lossfunction                     Derivative\n      ┌────────────┬────────────┐      ┌────────────┬────────────┐\n    2 │                         │    1 │                   _--'''│\n      │\\                       /│      │                ./'      │\n      │ \\.                   ./ │      │              ./         │\n      │  '.                 .'  │      │_           ./          _│\n    L │   '.               .'   │   L' │           ./            │\n      │     \\.           ./     │      │         ./              │\n      │      '.         .'      │      │       ./                │\n    0 │        '-.___.-'        │   -1 │___.-''                  │\n      └────────────┴────────────┘      └────────────┴────────────┘\n      -3                        3      -4                        4\n                 ŷ - y                            ŷ - y\n```\n\"\"\"\nstruct LogitDistLoss <: DistanceLoss end\n\nfunction value(loss::LogitDistLoss, difference::Number)\n    er = exp(difference)\n    T = typeof(er)\n    -log(convert(T,4)) - difference + 2log(one(T) + er)\nend\nfunction deriv(loss::LogitDistLoss, difference::T) where T<:Number\n    tanh(difference / convert(T,2))\nend\nfunction deriv2(loss::LogitDistLoss, difference::Number)\n    er = exp(difference)\n    T = typeof(er)\n    convert(T,2)*er / abs2(one(T) + er)\nend\n\nissymmetric(::LogitDistLoss) = true\nisdifferentiable(::LogitDistLoss) = true\nisdifferentiable(::LogitDistLoss, at) = true\nistwicedifferentiable(::LogitDistLoss) = true\nistwicedifferentiable(::LogitDistLoss, at) = true\nislipschitzcont(::LogitDistLoss) = true\nisconvex(::LogitDistLoss) = true\nisstrictlyconvex(::LogitDistLoss) = true\nisstronglyconvex(::LogitDistLoss) = false\n\n\n# ===========================================================\n@doc doc\"\"\"\n    QuantileLoss <: DistanceLoss\n\nThe distance-based quantile loss, also known as pinball loss,\ncan be used to estimate conditional τ-quantiles.\nIt is Lipschitz continuous and convex, but not strictly convex.\nFurthermore it is symmetric if and only if `τ = 1/2`.\n\n```math\nL(r) = \\begin{cases} -\\left( 1 - \\tau  \\right) r & \\quad \\text{if } r < 0 \\\\ \\tau r & \\quad \\text{if } r \\ge 0 \\\\ \\end{cases}\n```\n\n---\n```\n              Lossfunction (τ=0.7)             Derivative\n      ┌────────────┬────────────┐      ┌────────────┬────────────┐\n    2 │'\\                       │  0.3 │            ┌------------│\n      │  \\.                     │      │            |            │\n      │   '\\                    │      │_           |           _│\n      │     \\.                  │      │            |            │\n    L │      '\\              ._-│   L' │            |            │\n      │        \\.         ..-'  │      │            |            │\n      │         '.     _r/'     │      │            |            │\n    0 │           '_./'         │ -0.7 │------------┘            │\n      └────────────┴────────────┘      └────────────┴────────────┘\n      -3                        3      -3                        3\n                 ŷ - y                            ŷ - y\n```\n\"\"\"\nstruct QuantileLoss{T <: AbstractFloat} <: DistanceLoss\n    τ::T\nend\n\nfunction value(loss::QuantileLoss{T1}, diff::T2) where {T1, T2 <: Number}\n    T = promote_type(T1, T2)\n    diff * (convert(T,diff > 0) - loss.τ)\nend\nfunction deriv(loss::QuantileLoss{T1}, diff::T2) where {T1, T2 <: Number}\n    T = promote_type(T1, T2)\n    convert(T,diff > 0) - loss.τ\nend\nderiv2(::QuantileLoss{T1}, diff::T2) where {T1, T2 <: Number} = zero(promote_type(T1, T2))\n\nissymmetric(loss::QuantileLoss) = loss.τ == 0.5\nisdifferentiable(::QuantileLoss) = false\nisdifferentiable(::QuantileLoss, at) = at != 0\nistwicedifferentiable(::QuantileLoss) = false\nistwicedifferentiable(::QuantileLoss, at) = at != 0\nislipschitzcont(::QuantileLoss) = true\nislipschitzcont_deriv(::QuantileLoss) = true\nisconvex(::QuantileLoss) = true\nisstrictlyconvex(::QuantileLoss) = false\nisstronglyconvex(::QuantileLoss) = false\n\n# ======================================================\n\n@doc doc\"\"\"\n    LogCoshLoss <: DistanceLoss\n\nThe log cosh loss is twice differentiable, strongly convex,\nLipschitz continous function.\n\n```math\nL(r) = log ( cosh ( x ))\n```\n---\n```\n           Lossfunction                     Derivative\n      ┌────────────┬────────────┐      ┌────────────┬────────────┐\n  2.5 │\\                       /│    1 │                 .-------│\n      │\".                     .\"│      │                |        │\n      │ \".                   .\" │      │               /         │\n      │  \".                 .\"  │      │_           . \"         _│\n    L │   \".               .\"   │   L' │         /\"              │\n      │    '\\.           ./'    │      │       .\"                │\n      │      \\.         ./      │      │       |                 │\n    0 │        \"-. _ .-\"        │   -1 │------\"                  │\n      └────────────┴────────────┘      └────────────┴────────────┘\n      -3                        3      -3                        3\n                 ŷ - y                            ŷ - y\n```\n\"\"\"\n\nstruct LogCoshLoss <: DistanceLoss end\n\n_softplus(x::T) where T<:Number = x > zero(T) ? x + log1p(exp(-x)) : log1p(exp(x))\n_log_cosh(x::T) where T<:Number = x + _softplus(-2x) - log(convert(T, 2))\n\nfunction value(loss::LogCoshLoss, diff::T) where {T <: Number}\n  _log_cosh(diff)\nend\n\nfunction deriv(loss::LogCoshLoss, diff::T) where {T <: Number}\n  tanh.(diff)\nend\n\nfunction deriv2(::LogCoshLoss, diff::T) where {T <: Number} \n  (sech.(diff))^2\nend\n\nissymmetric(loss::LogCoshLoss)           = true\nisdifferentiable(::LogCoshLoss)          = true\nisdifferentiable(::LogCoshLoss, at)      = true\nistwicedifferentiable(::LogCoshLoss, at) = true\nistwicedifferentiable(::LogCoshLoss)     = true\nislipschitzcont(::LogCoshLoss)           = true\nisconvex(::LogCoshLoss)                  = true\nisstrictlyconvex(::LogCoshLoss)          = true\nisstronglyconvex(::LogCoshLoss)          = true\n", "meta": {"hexsha": "15e3efd322b836cc1d4e77610737272d68db6865", "size": 20200, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/supervised/distance.jl", "max_stars_repo_name": "Evizero/MLModels.jl", "max_stars_repo_head_hexsha": "521ff95e5514329b7c98260df99cfde25d08d3b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 103, "max_stars_repo_stars_event_min_datetime": "2016-11-03T06:52:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T16:45:19.000Z", "max_issues_repo_path": "src/supervised/distance.jl", "max_issues_repo_name": "JuliaML/LossFunctions.jl", "max_issues_repo_head_hexsha": "cd5f5a493ced706825489de5e5cae60492b8fc2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 91, "max_issues_repo_issues_event_min_datetime": "2016-10-17T21:39:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-03T00:38:47.000Z", "max_forks_repo_path": "src/supervised/distance.jl", "max_forks_repo_name": "Evizero/MLModels.jl", "max_forks_repo_head_hexsha": "521ff95e5514329b7c98260df99cfde25d08d3b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2016-10-17T11:10:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T02:21:29.000Z", "avg_line_length": 37.6163873371, "max_line_length": 146, "alphanum_fraction": 0.4582673267, "num_tokens": 6012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567177, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.750417188587269}}
{"text": "@doc raw\"\"\"\r\n```\r\nbinarize(Yen(), img)\r\n```\r\n\r\nComputes the binarization threshold value using Yen's maximum correlation criterion for\r\nbilevel thresholding.\r\n\r\n# Output\r\n\r\nReturns the binarized image as an `Array{Gray{Bool},2}`.\r\n\r\n\r\n# Details\r\n\r\nThis algorithm uses the concept of *entropic correlation* of a gray level histogram to produce a threshold\r\nvalue.\r\n\r\nLet ``f_1, f_2, \\ldots, f_I`` be the frequencies in the various bins of the\r\nhistogram and ``I`` the number of bins. With ``N = \\sum_{i=1}^{I}f_i``, let\r\n``p_i = \\frac{f_i}{N}`` (``i = 1, \\ldots, I``) denote the probability\r\ndistribution of gray levels. From this distribution one derives two additional\r\ndistributions. The first defined for discrete values ``1`` to ``s`` and the\r\nother, from ``s+1`` to ``I``. These distributions are\r\n\r\n```math\r\nA: \\frac{p_1}{P_s}, \\frac{p_2}{P_s}, \\ldots, \\frac{p_s}{P_s}\r\n\\quad \\text{and} \\quad\r\nB: \\frac{p_{s+1}}{1-P_s}, \\ldots, \\frac{p_n}{1-P_s}\r\n\\quad \\text{where} \\quad\r\nP_s = \\sum_{i=1}^{s}p_i.\r\n```\r\nThe entropic correlations associated with each distribution are\r\n\r\n```math\r\nC(A) = -\\ln \\sum_{i=1}^{s} \\left( \\frac{p_i}{P_s} \\right)^2 \\quad \\text{and} \\quad C(B) = -\\ln \\sum_{i=s+1}^{I} \\left( \\frac{p_i}{1 - P_s} \\right)^2.\r\n```\r\n\r\nCombining these two entropic correlation functions we have\r\n\r\n```math\r\n\\psi(s) = -\\ln \\sum_{i=1}^{s} \\left( \\frac{p_i}{P_s} \\right)^2 -\\ln \\sum_{i=s+1}^{I} \\left( \\frac{p_i}{1 - P_s} \\right)^2.\r\n```\r\nFinding the discrete value ``s`` which maximises the function ``\\psi(s)`` produces\r\nthe sought-after threshold value (i.e. the bin which determines the threshold).\r\n\r\n# Arguments\r\n\r\nThe function argument is described in more detail below.\r\n\r\n##  `img`\r\n\r\nAn `AbstractArray` representing an image. The image is automatically converted\r\nto `Gray` in order to construct the requisite graylevel histogram.\r\n\r\n# Example\r\n\r\nBinarize the \"cameraman\" image in the `TestImages` package.\r\n\r\n```julia\r\nusing TestImages, ImageBinarization\r\n\r\nimg = testimage(\"cameraman\")\r\nimg_binary = binarize(Yen(), img)\r\n```\r\n\r\n# Reference\r\n\r\n1. Yen JC, Chang FJ, Chang S (1995), “A New Criterion for Automatic Multilevel Thresholding”, IEEE Trans. on Image Processing 4 (3): 370-378, [doi:10.1109/83.366472](https://doi.org/10.1109/83.366472)\r\n\"\"\"\r\nfunction binarize(algorithm::Yen,  img::AbstractArray{T,2}) where T <: Colorant\r\n  img₀₁ = zeros(Gray{Bool}, axes(img))\r\n  edges, counts = build_histogram(img,  256)\r\n  t = find_threshold(HistogramThresholding.Yen(), counts[1:end], edges)\r\n  for i in CartesianIndices(img)\r\n    img₀₁[i] = img[i] < t ? 0 : 1\r\n  end\r\n  img₀₁\r\nend\r\n", "meta": {"hexsha": "b2457bc97fa8ce7e7870a49209d21f1af20d1673", "size": 2598, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/yen.jl", "max_stars_repo_name": "bellascalzi1/ImageBinarization.jl", "max_stars_repo_head_hexsha": "43011cd85eff0fefcaadb14f517eb75160c7d5e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/yen.jl", "max_issues_repo_name": "bellascalzi1/ImageBinarization.jl", "max_issues_repo_head_hexsha": "43011cd85eff0fefcaadb14f517eb75160c7d5e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/yen.jl", "max_forks_repo_name": "bellascalzi1/ImageBinarization.jl", "max_forks_repo_head_hexsha": "43011cd85eff0fefcaadb14f517eb75160c7d5e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.475, "max_line_length": 201, "alphanum_fraction": 0.6716705158, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7504171857788114}}
{"text": "module TestFunctions\n\nstruct Rosenbrock\n    f\n    ∇f\n    argmin\n    Rosenbrock(; a = 1, b = 5) =\n    new(x->(a - x[1])^2 + b * (x[2] - x[1]^2)^2,\n        x->[\n            -2 * (a - x[1]) - 4 * b * x[1] * (x[2] - x[1]^2),\n            2 * b * (x[2] - x[1]^2)\n        ],\n        [a, a^2])\nend\n\nend # module\n", "meta": {"hexsha": "b767c0141b8e44b47099a4772803759d3f6a78a0", "size": 304, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TestFunctions.jl", "max_stars_repo_name": "gshaikov/Algopt.jl", "max_stars_repo_head_hexsha": "0fced0ae1963b68cf1c6118ab03e6eb6ccc0e6c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TestFunctions.jl", "max_issues_repo_name": "gshaikov/Algopt.jl", "max_issues_repo_head_hexsha": "0fced0ae1963b68cf1c6118ab03e6eb6ccc0e6c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TestFunctions.jl", "max_forks_repo_name": "gshaikov/Algopt.jl", "max_forks_repo_head_hexsha": "0fced0ae1963b68cf1c6118ab03e6eb6ccc0e6c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8823529412, "max_line_length": 61, "alphanum_fraction": 0.3552631579, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.750417183550132}}
{"text": "using Plots\n\n\n@fastmath function SIR_fs(N,bet,gamm)\n    final_size = zeros(N+1,1);\n    final_size[2] = 1;\n    for Z2 in 0:N\n        @inbounds for Z1 in Z2+1:N-1\n            p1 = 1 / ( 1 + gamm/(bet*(N-Z1)));\n            final_size[Z1+2] = final_size[Z1+2] + final_size[Z1+1]*p1; \n            final_size[Z1+1] = final_size[Z1+1]*(1-p1);\n        end\n    end\n    return final_size;\nend\n\nN = 20;                       \nbet = 2/(N-1);\ngamm = 1.0;\n\nfinal_size = SIR_fs(N,bet,gamm);\n\n@time final_size = SIR_fs(N,bet,gamm);\n\nbar(0:N,final_size)\n", "meta": {"hexsha": "216c2f0abd7880ab1fc08c2f69b9ba922de38643", "size": 537, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/epidemic_final_size/ere_sir.jl", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/epidemic_final_size/ere_sir.jl", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/epidemic_final_size/ere_sir.jl", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 20.6538461538, "max_line_length": 71, "alphanum_fraction": 0.5400372439, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.7504171732311851}}
{"text": "\"\"\"\n    fourier_pade(u, degree_num, degree_den, num_output=length(u))\n\nCompute the Fourier-Padé reconstruction of `u` with degrees\n`(degree_num, degree_den)` and evaluate it at `num_output`\nequispaced points, cf.\nDriscoll and Fornberg (2001) A Padé-based algorithm for overcoming the Gibbs phenomenon,\ndoi: 10.1023/A:1016648530648.\n\"\"\"\nfunction fourier_pade(u, degree_num, degree_den, num_output=length(u))\n  N = degree_num + degree_den\n  modes = length(u) ÷ 2 + 1\n  if modes <= N\n    throw(ArgumentError(\"Cannot perform a Fourier-Padé reconstruction with degrees ($degree_num, $degree_den) given $(length(u)) real coefficients corresponding to $modes complex modes.\"))\n  end\n\n  uhat = rfft(u)\n  uhat ./= length(u)\n\n  # denominator\n  col_den = uhat[degree_num+2:N+1]\n  row_den = zeros(eltype(col_den), degree_den+1)\n  row_den[1:min(degree_num+2,degree_den+1)] = uhat[degree_num+2:-1:max(1, degree_num+2-degree_den)]\n  Z = nullspace(Matrix(Toeplitz(col_den, row_den)))\n  den_p = zeros(eltype(uhat), num_output)\n  den_p[1:degree_den+1] = Z[:, end]\n  den_p ./= den_p[findfirst(!iszero, den_p)]\n\n  # numerator\n  col_num = uhat[1:degree_num+1]\n  col_num[1] /= 2\n  row_num = zeros(eltype(col_num), degree_den+1)\n  row_num[1] = col_num[1]\n  A = Toeplitz(col_num, row_num)\n  num_p = zeros(eltype(uhat), num_output)\n  mul!(view(num_p, 1:degree_num+1), A, view(den_p, 1:degree_den+1))\n\n  # evaluate Fourier-Padé approximation\n  bfft_plan = plan_bfft(num_p)\n  2 .* real.((bfft_plan * num_p) ./ (bfft_plan * den_p))\nend\n\n\nfunction reference(::typeof(fourier_pade))\n\"\"\"\n@article{driscoll2001pade,\n  title={A {P}ad{\\'e}-based algorithm for overcoming the {G}ibbs phenomenon},\n  author={Driscoll, Tobin A and Fornberg, Bengt},\n  journal={Numerical Algorithms},\n  volume={26},\n  number={1},\n  pages={77--92},\n  year={2001},\n  publisher={Springer},\n  doi={10.1023/A:1016648530648}\n}\n\"\"\"\nend\n", "meta": {"hexsha": "7c321c26ec3ae5e693695459fa309edf749bfe59", "size": 1874, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fourier_pade.jl", "max_stars_repo_name": "ranocha/Postprocessing.jl", "max_stars_repo_head_hexsha": "51d1924bf55911dc631670482aa41f6d680cdef4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fourier_pade.jl", "max_issues_repo_name": "ranocha/Postprocessing.jl", "max_issues_repo_head_hexsha": "51d1924bf55911dc631670482aa41f6d680cdef4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-03-19T07:37:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-16T06:04:17.000Z", "max_forks_repo_path": "src/fourier_pade.jl", "max_forks_repo_name": "ranocha/Postprocessing.jl", "max_forks_repo_head_hexsha": "51d1924bf55911dc631670482aa41f6d680cdef4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7627118644, "max_line_length": 188, "alphanum_fraction": 0.7081109925, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7504161895612573}}
{"text": "\"\"\"\n    Student's t\n\n* Parametrization\nparametrized in \\\\nu\n\n* Score\n\n* Fisher Information\n\n* `time_varying_params` map.\n\n* Default link\n\"\"\"\nTDist\n\nfunction score!(score_til::Matrix{T}, y::T, ::Type{TDist}, param::Matrix{T}, t::Int) where T\n    score_til[t, 1] = 0.5 * (((y^2)*(param[t, 1] + 1)/(param[t, 1] * y^2 + param[t, 1]^2)) -\n                      1/param[t, 1] - \n                      log((y^2)/(param[t, 1]) + 1) - \n                      digamma(param[t, 1] / 2) + digamma((param[t, 1] + 1) / 2))\n    return\nend\n\nfunction fisher_information!(aux::AuxiliaryLinAlg{T}, ::Type{TDist}, param::Matrix{T}, t::Int) where T\n    aux.fisher[1, 1] = 0.5 * (0.5 * trigamma(0.5 * param[t, 1]) - 0.5 * trigamma( 0.5 * (param[t, 1] + 1.0) ) -\n                             (param[t, 1] + 5.0) / (param[t, 1] * (param[t, 1] + 3.0) * (param[t, 1] + 1.0)))\n    return\nend\n\nfunction log_likelihood(::Type{TDist}, y::Vector{T}, param::Matrix{T}, n::Int) where T\n    loglik = zero(T)\n    for t in 1:n\n        loglik -= 0.5 * log(param[t, 1]) + logbeta(0.5, param[t, 1]/2) + ((param[t, 1] + 1)/2) *\n                  log(1 + (y[t]^2)/param[t, 1])\n    end\n    return -loglik\nend\n\n# Links\nfunction link!(param_tilde::Matrix{T}, ::Type{TDist}, param::Matrix{T}, t::Int) where T \n    param_tilde[t, 1] = link(LogLink, param[t, 1], zero(T))\n    return\nend\nfunction unlink!(param::Matrix{T}, ::Type{TDist}, param_tilde::Matrix{T}, t::Int) where T \n    param[t, 1] = unlink(LogLink, param_tilde[t, 1], zero(T))\n    return\nend\nfunction jacobian_link!(aux::AuxiliaryLinAlg{T}, ::Type{TDist}, param::Matrix{T}, t::Int) where T \n    aux.jac[1] = jacobian_link(LogLink, param[t, 1], zero(T))\n    return\nend\n\n# utils \nfunction update_dist(::Type{TDist}, param::Matrix{T}, t::Int) where T\n    return TDist(param[t, 1])\nend \n\nfunction params_sdm(d::TDist)\n    return Distributions.params(d)\nend\n\nfunction num_params(::Type{TDist})\n    return 1\nend\n", "meta": {"hexsha": "1bf552a9748a7695ee757574a0997b280ae91276", "size": 1921, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distributions/tdist.jl", "max_stars_repo_name": "marinadietze/ScoreDrivenModels.jl", "max_stars_repo_head_hexsha": "4ee85b8d606892535a7b0bf2aec1d976f44d796e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2020-02-05T04:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T18:46:03.000Z", "max_issues_repo_path": "src/distributions/tdist.jl", "max_issues_repo_name": "marinadietze/ScoreDrivenModels.jl", "max_issues_repo_head_hexsha": "4ee85b8d606892535a7b0bf2aec1d976f44d796e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 109, "max_issues_repo_issues_event_min_datetime": "2019-11-26T12:34:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-27T20:16:55.000Z", "max_forks_repo_path": "src/distributions/tdist.jl", "max_forks_repo_name": "LAMPSPUC/GAS.jl", "max_forks_repo_head_hexsha": "e169248c3f8908170868d898a4def97af15774cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:11:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-04T20:05:21.000Z", "avg_line_length": 29.1060606061, "max_line_length": 111, "alphanum_fraction": 0.5710567413, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7504161895612573}}
{"text": "\"\"\"\n    @polyeval(z, p, N)\n\nEvaluate the polynomial ``\\\\sum_k c[k] z^{k-1}`` for the coefficients `c[1]`, `c[2]`, ..., `c[N]`;\nthat is, the coefficients are given in ascending order by power of `z`.  This macro expands\nto efficient inline code that uses either Horner's method.\n\n```jldoctest\n\njulia> p = randn(5)\n5-element Array{Float64,1}:\n  0.106455 \n  0.0351716\n -0.204764 \n -0.87642  \n  0.260407 \n\njulia> @polyeval(0.5, p, 5)\n-0.020427265391245605\n\n```\n\"\"\"\nmacro polyeval(x, p, N)\n    if N==1\n        return :($(esc(p))[1])\n    elseif N==2\n        return :($(esc(p))[1] + $(esc(x))*$(esc(p))[2])\n    else\n        nm1 = N-1\n        ex = :($(esc(p))[$nm1] + $(esc(x))*$(esc(p))[$N])\n        for i in N-2:-1:1\n            ex = :($(esc(p))[$i] + $(esc(x))*$ex)\n        end\n    end\n    return ex\nend\n\n\"\"\"\n    ConvergenceError([msg, val, niter, err])\n\nException that is to be thrown when an iterative procedure fails\nto converge.\n\n\"\"\"\nmutable struct ConvergenceError <: Exception\n    msg::String\n    val::Float64\n    niter::Int\n    err::Float64\n    ConvergenceError() = new(\"Calculations failed to converge\", NaN, -1, NaN)\n    ConvergenceError(msg) = new(msg, NaN, -1, NaN)\n    ConvergenceError(msg, val) = new(msg, val, -1, NaN)\n    ConvergenceError(msg, val, niter) = new(msg, val, niter, NaN)\n    ConvergenceError(msg, val, niter, err) = new(msg, val, niter, err)\nend\n\n\n\"\"\"\n    calcz(vm, b0, c0, [EPS, [MAXITER, [relax]]])\n\nCalculates the compressibility factor using a virial equation:\n\n`z = 1 + b₀/z + c₀/vₘ²`\n\nThe algorithm initially uses as an initial guess only the b₀ virial \ncoefficient. Then it uses a Newton-Raphson algorithm to compute the\ncompressibility factor\n\n * `b0` b₀ parameter of the virial equation\n * `c0` c₀ parameter of the virial equation\n * `EPS` Convergence criterium\n * `MAXITER` Maximim number of iterations\n * `relax` Sub-relaxation parameter if convergence is difficult.\n\"\"\"\nfunction calcz(b0, c0, EPS=1e-8, MAXITER=200, relax=1.0)\n\n    z = (1.0 + sqrt(1.0 + 4*b0)) / 2.0\n    dz = 0.0\n    \n    for i = 1:MAXITER\n        f = -c0 + z*(-b0 + z*(-1.0 + z))\n        df = -b0 + z*(-2.0 + 3.0*z)\n        dz = -f / df\n        if abs(dz) < EPS\n            return z + dz\n        end\n        z = z + relax*dz\n    end\n    throw(ConvergenceError(\"Compressibility factor failed to converge properly!\",\n                           z, MAXITER, abs(dz)))\n        \nend\n", "meta": {"hexsha": "cec30293a9daac21c12793ddff9b4e8136c08f46", "size": 2380, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utilities.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Psychro.jl-9516f557-4a54-5a79-b954-c272e753c77a", "max_stars_repo_head_hexsha": "bb2dd6732f6f4a84504cee827eb75418e357bb74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utilities.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Psychro.jl-9516f557-4a54-5a79-b954-c272e753c77a", "max_issues_repo_head_hexsha": "bb2dd6732f6f4a84504cee827eb75418e357bb74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utilities.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Psychro.jl-9516f557-4a54-5a79-b954-c272e753c77a", "max_forks_repo_head_hexsha": "bb2dd6732f6f4a84504cee827eb75418e357bb74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5913978495, "max_line_length": 98, "alphanum_fraction": 0.5932773109, "num_tokens": 795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7504161778019529}}
{"text": "# ---\n# title: 1515. Best Position for a Service Centre\n# id: problem1515\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Hard\n# categories: Geometry\n# link: <https://leetcode.com/problems/best-position-for-a-service-centre/description/>\n# hidden: true\n# ---\n# \n# A delivery company wants to build a new service centre in a new city. The\n# company knows the positions of all the customers in this city on a 2D-Map and\n# wants to build the new centre in a position such that **the sum of the\n# euclidean distances to all customers is minimum**.\n# \n# Given an array `positions` where `positions[i] = [xi, yi]` is the position of\n# the `ith` customer on the map, return _the minimum sum of the euclidean\n# distances_ to all customers.\n# \n# In other words, you need to choose the position of the service centre\n# `[xcentre, ycentre]` such that the following formula is minimized:\n# \n# ![](https://assets.leetcode.com/uploads/2020/06/25/q4_edited.jpg)\n# \n# Answers within `10^-5` of the actual value will be accepted.\n# \n# \n# \n# **Example 1:**\n# \n# ![](https://assets.leetcode.com/uploads/2020/06/25/q4_e1.jpg)\n# \n#     \n#     \n#     Input: positions = [[0,1],[1,0],[1,2],[2,1]]\n#     Output: 4.00000\n#     Explanation: As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.\n#     \n# \n# **Example 2:**\n# \n# ![](https://assets.leetcode.com/uploads/2020/06/25/q4_e3.jpg)\n# \n#     \n#     \n#     Input: positions = [[1,1],[3,3]]\n#     Output: 2.82843\n#     Explanation: The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: positions = [[1,1]]\n#     Output: 0.00000\n#     \n# \n# **Example 4:**\n# \n#     \n#     \n#     Input: positions = [[1,1],[0,0],[2,0]]\n#     Output: 2.73205\n#     Explanation: At the first glance, you may think that locating the centre at [1, 0] will achieve the minimum sum, but locating it at [1, 0] will make the sum of distances = 3.\n#     Try to locate the centre at [1.0, 0.5773502711] you will see that the sum of distances is 2.73205.\n#     Be careful with the precision!\n#     \n# \n# **Example 5:**\n# \n#     \n#     \n#     Input: positions = [[0,1],[3,2],[4,5],[7,6],[8,9],[11,1],[2,12]]\n#     Output: 32.94036\n#     Explanation: You can use [4.3460852395, 4.9813795505] as the position of the centre.\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= positions.length <= 50`\n#   * `positions[i].length == 2`\n#   * `0 <= positions[i][0], positions[i][1] <= 100`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "fff62cabaa6415e334f963f73c137a7638e2a75d", "size": 2664, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1515.best-position-for-a-service-centre.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/unresolved/1515.best-position-for-a-service-centre.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/unresolved/1515.best-position-for-a-service-centre.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 28.3404255319, "max_line_length": 203, "alphanum_fraction": 0.6227477477, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7504161688567357}}
{"text": "using EconPDEs\n\nstruct WangWangYangModel\n    μ::Float64 \n    σ::Float64\n    r::Float64\n    ρ::Float64  \n    γ::Float64 \n    ψ::Float64\n    wmax::Float64\nend\n\nfunction WangWangYangModel(;μ = 0.015, σ = 0.1, r = 0.035, ρ = 0.04, γ = 3, ψ = 1.1, wmax = 5000.0)\n    WangWangYangModel(μ, σ, r, ρ, γ, ψ, wmax)\nend\n\nfunction initialize_stategrid(m::WangWangYangModel; n = 500)\n    OrderedDict(:w => range(0.0, stop = sqrt(m.wmax), length = n).^2)\nend\n\nfunction initialize_y(m::WangWangYangModel, stategrid)\n    OrderedDict(:p => 1 .+ stategrid[:w])\nend\n    \nfunction (m::WangWangYangModel)(state::NamedTuple, y::NamedTuple)\n    μ = m.μ ;  σ = m.σ ;  r = m.r ;  ρ = m.ρ ;  γ = m.γ ;  ψ = m.ψ ; wmax = m.wmax\n    w = state.w\n    p, pw, pww = y.p, y.pw, y.pww\n    c = (r + ψ * (ρ - r)) * p * pw^(-ψ)\n    μw = (r - μ + σ^2) * w + 1 - c\n    # One only needs a ghost node if μw <= 0 (since w^2p_ww = 0). In this case, we obtain a formula for pw so that c <= 1\n    if w ≈ 0.0 && μw <= 0.0\n       pw = ((r + ψ * (ρ - r)) * p)^(1 / ψ)\n       c = (r + ψ * (ρ - r)) * p * pw^(-ψ)\n       μw = (r - μ + σ^2) * w + 1 - c\n    end\n    # At the top, I use the solution of the unconstrainted, i.e. pw = 1 (I could also do reflecting boundary but less elegant)\n    pt = (((r + ψ * (ρ - r)) * pw^(1 - ψ) - ψ * ρ) / (ψ - 1) + μ - γ * σ^2 / 2) * p + ((r - μ + γ * σ^2) * w + 1) * pw + σ^2 * w^2 / 2  * (pww - γ * pw^2 / p)\n    μw = 1 + (r - μ + σ^2) * w - c\n    return (pt,), (μw,), (w = w, p = p, pw = pw, pww = pww, μw = μw, c = c)\nend\n\nm = WangWangYangModel()\nstategrid = initialize_stategrid(m)\ny0 = initialize_y(m, stategrid)\ny, result, distance = pdesolve(m, stategrid, y0; bc = OrderedDict(:pw => (1.0, 1.0)))", "meta": {"hexsha": "1ba131599b556c35b0e3d52c855797c2ca14ba72", "size": 1687, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ConsumptionProblem/WangWangYang.jl", "max_stars_repo_name": "vr235/EconPDEs.jl", "max_stars_repo_head_hexsha": "045aede7cdcb7b6ae702b152676fb9d5bc85f99f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/ConsumptionProblem/WangWangYang.jl", "max_issues_repo_name": "vr235/EconPDEs.jl", "max_issues_repo_head_hexsha": "045aede7cdcb7b6ae702b152676fb9d5bc85f99f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ConsumptionProblem/WangWangYang.jl", "max_forks_repo_name": "vr235/EconPDEs.jl", "max_forks_repo_head_hexsha": "045aede7cdcb7b6ae702b152676fb9d5bc85f99f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6739130435, "max_line_length": 158, "alphanum_fraction": 0.5257854179, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576759, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7504161657911708}}
{"text": "export jacobian,  StabilityType\n\n\n@with_kw struct jacobian \n    ode\n    jac_func\n    u\n    p\n    t\nend\n\n\"\"\"\n    StabilityType \n\nStore the information about stability.\n\"\"\"\n@with_kw struct StabilityType\n    stable ::Bool \n    unstable ::Bool \n    saddle  ::Bool \n    damping ::Bool \nend\n\n\n\"\"\"\nConstruct the jacobian struct type\n\nArgument\n--------\n- `ode` {ODE function}: with the form `f(du,u,p,t)`\n- `u` {Array}: initial values\n- `p` {Array}: parameters\n\nReturn \n------\n- `Jacobian` {struct}\n\nWarning\n-------\nNameTuple definition of `ode` function is unrecommended. Due to the incompatibility with `ModelingToolkit.modelingtoolkitize`\n\"\"\"\nfunction jacobian(ode, u, p; t=nothing)\n    prob = ODEProblem(ode, u, t, p)\n    de =  ModelingToolkit.modelingtoolkitize(prob)\n    \n    jac_func = ModelingToolkit.generate_jacobian(de, expression=Val{false})[2]\n    return jacobian(ode=ode, jac_func=jac_func, u=u, p=p, t=t)\nend\n\n\"\"\"Use DEmeta for jacobian generation\"\"\"\nfunction jacobian(de::T; t= nothing) where T<:DEmeta\n    return jacobian(de.func, de.u0, de.p; t=t)\nend\n\n\"\"\"\nCalculate the jacobian of given initial valuables and parameters.\n\"\"\"\nfunction (self::jacobian)(u,p;t=nothing)\n    l = length(u)\n    j = zeros(l,l)\n    self.jac_func(j, u, p, t)\n    return j\nend\n\n\n\"\"\"\nGet jacobian from state variable with default paramter set\n\"\"\"\nfunction (self::jacobian)(u;t=nothing)\n    return self(u, self.p; t=t)\nend\n\n\"\"\"\nGet jacobian from default state.\n\"\"\"\nfunction (self::jacobian)()\n    return self(self.u, self.p; t=self.t)\nend\n\n\n\nfunction StabilityType(jac_matrix)\n    es = eigvals(jac_matrix)\n\n    return StabilityType(\n    stable = is_stable(es),\n    unstable = is_unstable(es),\n    saddle = is_saddle(es),\n    damping = is_damping(es)\n    )\nend\n\n\n\"\"\"\nStability identification\n\"\"\"\nfunction is_stable(es) :: Bool\n    method(e) = real(e) >= 0. ? true : false \n    return judge_jac(es, method, true)\nend\n\n\"\"\"\nUnstability identification\n\"\"\"\nfunction is_unstable(es) :: Bool\n    method(e) = real(e) >= 0. ? true : false \n    return judge_jac(es, method, false)\nend\n\n\"\"\"\nDamping identification\n\"\"\"\nfunction is_damping(es) :: Bool\n   method(e) = imag(e) != 0. ? true : false \n   return judge_jac(es, method, false)\nend\n\n\"\"\"\nSaddle point identification\n\"\"\"\nfunction is_saddle(es) :: Bool \n    real_es = real.(es)\n    if (maximum(real_es) > 0. ) & (minimum(real_es) < 0.)\n        saddle = true\n    else \n        saddle = false\n    end\n    return saddle\nend\n\n\"\"\"\nGeneral method for judging jacobian \n\"\"\"\nfunction judge_jac(es, eigval_method, default_bool)\n    feature = default_bool\n    for e in es\n        if eigval_method(e) \n            feature = !feature\n            break \n        end\n    end\n    return feature\nend", "meta": {"hexsha": "5dcddc928bcb4f6e2496155821b55cc27548f8c3", "size": 2707, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/jacobian.jl", "max_stars_repo_name": "stevengogogo/FindSteadyStates.jl", "max_stars_repo_head_hexsha": "863042b248702ff7e68c20aa69128c94b346fb5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-11-25T00:04:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T06:51:41.000Z", "max_issues_repo_path": "src/jacobian.jl", "max_issues_repo_name": "stevengogogo/FindSteadyStates.jl", "max_issues_repo_head_hexsha": "863042b248702ff7e68c20aa69128c94b346fb5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 40, "max_issues_repo_issues_event_min_datetime": "2020-11-06T10:04:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T08:22:56.000Z", "max_forks_repo_path": "src/jacobian.jl", "max_forks_repo_name": "stevengogogo/FindSteadyStates.jl", "max_forks_repo_head_hexsha": "863042b248702ff7e68c20aa69128c94b346fb5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9300699301, "max_line_length": 125, "alphanum_fraction": 0.6501662357, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7503975475565443}}
{"text": "# Estimate polynomial linear regression model with a half-T prior.\n\nusing DynamicHMCModels\n\nProjDir = @__DIR__\ncd(ProjDir)\n\n# Import the dataset.\n\ndata = CSV.read(joinpath(\"..\", \"..\", \"data\", \"Howell1.csv\"), DataFrame)\n\n# Use only adults and standardize\n\ndf = filter(row -> row[:age] >= 18, data);\ndf[!, :weight] = convert(Vector{Float64}, df[:, :weight]);\ndf[!, :weight_s] = (df[:, :weight] .- mean(df[:, :weight])) / std(df[:, :weight]);\ndf[!, :weight_s2] = df[:, :weight_s] .^ 2;\n\n\n# Define a structure to hold the data: observables, covariates,\n# and the degrees of freedom for the prior.\n\n\"\"\"\nLinear regression model ``y ∼ Xβ + ϵ``, where ``ϵ ∼ N(0, σ²)`` IID.\nFlat prior for `β`, half-T for `σ`.\n\"\"\"\nBase.@kwdef mutable struct LinearRegressionModel{Ty <: AbstractVector, Tx <: AbstractMatrix,\nTv <: Real}\n    \"Observations.\"\n    y::Ty\n    \"Covariates\"\n    x::Tx\n    \"Degrees of freedom for prior.\"\n    v::Tv\nend\n\n# Write a function to return a properly dimensioned transformation.\n\nfunction make_transformation(model::LinearRegressionModel)\n  as((β = as(Array, size(model.x, 2)), σ = asℝ₊))\nend\n\nN = size(df, 1)\nx = hcat(ones(N), hcat(df[:, :weight_s], df[:, :weight_s2]));\nmodel = LinearRegressionModel(;y = df[:, :height], x=x, v=1.0)\n  \n# Pack parameters *as a single argument*.\n\nfunction (model::LinearRegressionModel)(θ)\n    @unpack y, x, v = model   # extract data\n    @unpack β, σ = θ                 # extract parameters\n    loglikelihood(Normal(0, σ), y .- x*β) + logpdf(TDist(v), σ)\nend\n\n# Evaluate at model function at some initial valuues\n\nprintln()\nmodel((β = [1.0, 2.0, 3.0], σ = 1.0)) |> display\nprintln()\n\n# Wrap the problem with a transformation, then use Flux for the gradient.\n\nP = TransformedLogDensity(make_transformation(model), model)\n∇P = ADgradient(:ForwardDiff, P);\n\n# Tune and sample.\n\nresults = mcmc_with_warmup(Random.GLOBAL_RNG, ∇P, 1000)\nposterior = P.transformation.(results.chain)\n\np = as_particles(posterior)\ndisplay(p)\n\nstan_result = \"\nIterations = 1:1000\nThinning interval = 1\nChains = 1,2,3,4\nSamples per chain = 1000\n\nEmpirical Posterior Estimates:\n           Mean         SD       Naive SE       MCSE      ESS\n    a 154.609019750 0.36158389 0.0057171433 0.0071845548 1000\n   b1   5.838431778 0.27920926 0.0044146860 0.0048693502 1000\n   b2  -0.009985954 0.22897191 0.0036203637 0.0047224478 1000\nsigma   5.110136300 0.19096315 0.0030193925 0.0030728192 1000\n\nQuantiles:\n          2.5%        25.0%        50.0%       75.0%        97.5%   \n    a 153.92392500 154.3567500 154.60700000 154.8502500 155.32100000\n   b1   5.27846200   5.6493250   5.83991000   6.0276275   6.39728200\n   b2  -0.45954687  -0.1668285  -0.01382935   0.1423620   0.43600905\nsigma   4.76114350   4.9816850   5.10326000   5.2300450   5.51500975\n\";\n\n# end of m4.5d.jl", "meta": {"hexsha": "d17d1b203d60eba171d223dd8f918cc66ca1eca5", "size": 2781, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/04/m4.5d1.jl", "max_stars_repo_name": "StatisticalRethinkingJulia/SRDynamicHMC.jl", "max_stars_repo_head_hexsha": "fba06cfe037b98d5a9a64d367f15bec8dcecb9ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2019-03-01T23:51:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T10:02:40.000Z", "max_issues_repo_path": "scripts/04/m4.5d1.jl", "max_issues_repo_name": "StatisticalRethinkingJulia/SRDynamicHMC.jl", "max_issues_repo_head_hexsha": "fba06cfe037b98d5a9a64d367f15bec8dcecb9ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2019-07-22T23:28:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-03T11:55:47.000Z", "max_forks_repo_path": "scripts/04/m4.5d1.jl", "max_forks_repo_name": "StatisticalRethinkingJulia/SRDynamicHMC.jl", "max_forks_repo_head_hexsha": "fba06cfe037b98d5a9a64d367f15bec8dcecb9ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-28T09:34:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:52:10.000Z", "avg_line_length": 29.2736842105, "max_line_length": 92, "alphanum_fraction": 0.6598345919, "num_tokens": 971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7503975428699959}}
{"text": "using NLsolve, StaticArrays\n\nfunction f!(F, x)\n    F[1] = (x[1]+3)*(x[2]^3-7)+18\n    F[2] = sin(x[2]*exp(x[1])-1)\nend\n\nfunction j!(J, x)\n    J[1, 1] = x[2]^3-7\n    J[1, 2] = 3*x[2]^2*(x[1]+3)\n    u = exp(x[1])*cos(x[2]*exp(x[1])-1)\n    J[2, 1] = x[2]*u\n    J[2, 2] = u\nend\n\nnlsolve(f!, j!, @MArray [ 0.1; 1.2], )", "meta": {"hexsha": "9bb8f3b2e856f1e25f1456cb2a0140ab33128d11", "size": 312, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/NEqProblems/randoms.jl", "max_stars_repo_name": "pkofod/NLSolvers.jl", "max_stars_repo_head_hexsha": "65034bb76cbf91e22784bd0156f28b85416adb2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2019-09-09T19:46:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T07:14:45.000Z", "max_issues_repo_path": "problems/NEqProblems/randoms.jl", "max_issues_repo_name": "pkofod/NLSolvers.jl", "max_issues_repo_head_hexsha": "65034bb76cbf91e22784bd0156f28b85416adb2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2019-08-05T01:35:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-03T09:37:14.000Z", "max_forks_repo_path": "problems/NEqProblems/randoms.jl", "max_forks_repo_name": "pkofod/NLSolvers.jl", "max_forks_repo_head_hexsha": "65034bb76cbf91e22784bd0156f28b85416adb2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-23T19:54:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-23T19:54:29.000Z", "avg_line_length": 19.5, "max_line_length": 39, "alphanum_fraction": 0.4455128205, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811611608242, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7503906375706421}}
{"text": "using LinearAlgebra: I, nullspace\nusing UniqueVectors: UniqueVector\nusing StaticArrays: MMatrix\n\n\"\"\"\n    parametrize_subspace(M::AbstractMatrix{<:Real}, v::AbstractVector{<:Real})\n\n`M` is a `K-n × K` full rank matrix and `v` is a `K-n` length vector. The equation `Mx = v`\ndescribes an `n`-dimensional affine subspace. Compute `a` and `b` so that this space is\nparametrized as `x = a + b * x[1:n]`. The columns of `b` are a basis for the null space of\n`M` and `a` is a solution of `Mx=v`.\n\"\"\"\nfunction parametrize_subspace(M::AbstractMatrix{<:Real}, v::AbstractVector{<:Real})\n    n = size(M, 2) - size(M, 1)\n    @assert n >= 0\n    b = nullspace(M)\n    N = inv([transpose(b); M]) # this is square because M is full rank\n    a = N[:, (n+1):end] * v\n    return a, b\nend\n\n\"\"\"\n    intersect_linear_quadratic(A::AbstractMatrix{<:Real},\n    B::AbstractVector{<:Real}, C::Real, a::AbstractVector{<:Real},\n    b::AbstractVector{<:Real})\n\nIntersect the line `x = a + b * t` with the quadratic `xᵀAx + Bᵀx + C = 0` and return the\ntwo intersection points.\n\"\"\"\nfunction intersect_linear_quadratic(A::AbstractMatrix{<:Real},\n    B::AbstractVector{<:Real}, C::Real, a::AbstractVector{<:Real},\n    b::AbstractVector{<:Real})\n    quadratic = transpose(b) * A * b\n    linear = transpose(a) * A * b + transpose(b) * A * a + transpose(B) * b\n    constant = transpose(a) * A * a + transpose(B) * a + C\n    t1, t2 = solve_quadratic(quadratic, linear, constant)\n    return a + b * t1, a + b * t2\nend\n\n\"\"\"\n    solve_quadratic(a::Real, b::Real, c::Real)\n\nFind the two solutions of `ax² + bx + c = 0`.\n\"\"\"\nfunction solve_quadratic(a::Real, b::Real, c::Real)\n    t1 = -b/(2 * a)\n    t2 = sqrt(b^2 - 4 * a * c)/(2 * a)\n    return t1 + t2, t1 - t2\nend\n\n\"\"\"\n    sign_of_permutation(a1::AbstractVector{T}, a2::AbstractVector{T}) where T\n\nGiven two arrays which are permutations of each other, find the sign of the permutation.\n\"\"\"\nfunction sign_of_permutation(a1::AbstractVector{T}, a2::AbstractVector{T}) where T\n    n = length(a1)\n    @assert length(a2) == n\n    inds = [findfirst(isequal(x), a2) for x in a1]\n    m = MMatrix{n,n,Int}(zeros(n,n)) # det is faster for small matrices using StaticArrays\n    for i in 1:n\n        m[i, inds[i]] = 1\n    end\n    return sign(det(m))\nend\n\n\"\"\"\n    first_setdiff_index(l1, l2)\n\nGiven two collections `l1` and `l2` find the index of the first element of `l1` that is\nnot in `l2`. If no such element exists return `0`.\n\"\"\"\nfunction first_setdiff_index(l1, l2)\n    for (i, e) in enumerate(l1)\n        if !(e in l2)\n            return i\n        end\n    end\n    return 0\nend\n\n\"\"\"\n    first_setdiff(l1, l2)\n\nGiven two collections `l1` and `l2` find the first element of `l1` that is not in `l2`.\nIf no such element exists return `nothing`.\n\"\"\"\nfunction first_setdiff(l1, l2)\n    i = first_setdiff_index(l1, l2)\n    return i > 0 ? l1[i] : nothing\nend\n\n\"\"\"\n    triangulated_lattice(v1::Vector{<:Real}, v2::Vector{<:Real}, n::Int, m::Int)\n\nSubdivide a parallelogram with sides `v1` and `v2` into `n*m` similar parallelograms.\nDivide each in two pieces to find a triangulation. Return the points and a\nTriangulatedComplex.\n\"\"\"\nfunction triangulated_lattice(v1::Vector{<:Real}, v2::Vector{<:Real}, n::Int, m::Int)\n    @assert length(v1) == length(v2) == 2\n    inds = UniqueVector([(i, j) for i in 1:(n+1) for j in 1:(m+1)])\n    points = [Point(v1 * (i-1)/n + v2 * (j-1)/m) for (i, j) in inds]\n    simplices = Simplex{2, 3}[]\n    for i in 1:n\n        for j in 1:m\n            p11 = points[findfirst(isequal((i,j)), inds)]\n            p12 = points[findfirst(isequal((i,j+1)), inds)]\n            p21 = points[findfirst(isequal((i+1,j)), inds)]\n            p22 = points[findfirst(isequal((i+1,j+1)), inds)]\n            push!(simplices, Simplex([p11, p12, p21]))\n            push!(simplices, Simplex([p12, p22, p21]))\n        end\n    end\n    return points, TriangulatedComplex(simplices)\nend\n", "meta": {"hexsha": "c12dd1fd7606f0db90c0489afce747ad3d71824e", "size": 3888, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "mgscheer/DiscreteExteriorCalculus.jl", "max_stars_repo_head_hexsha": "6e95c222921fed6119824c2771740f030101ac59", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2019-06-26T08:25:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T01:21:16.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "mgscheer/DiscreteExteriorCalculus.jl", "max_issues_repo_head_hexsha": "6e95c222921fed6119824c2771740f030101ac59", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-10-24T22:27:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-09T00:06:56.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "mgscheer/DiscreteExteriorCalculus.jl", "max_forks_repo_head_hexsha": "6e95c222921fed6119824c2771740f030101ac59", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2019-06-26T04:21:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T01:21:28.000Z", "avg_line_length": 33.2307692308, "max_line_length": 91, "alphanum_fraction": 0.6283436214, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7503083714677224}}
{"text": "# calculate probability by bayes theorem\n\nmodule ProbsBayes\n    using DataFrames, CSV, FreqTables\n\n    function main()\n        data_path = joinpath(split(@__FILE__, \"src\")[1], \"data/sensor_data_600.txt\")\n        df_org = CSV.read(data_path, DataFrame, \n                      header=[\"date\", \"time\", \"ir\", \"lidar\"],\n                      delim=' ')\n        \n        hours = [Int64(floor(e/10000)) for e in df_org.time]\n\n        # add hour array to df\n        df_h = DataFrame(hour=hours)\n        df_new = hcat(df_org, df_h)\n\n        # P(t)\n        freqs = freqtable(df_new, :lidar, :hour)\n        probs = freqs / length(df_org.lidar)\n        keys = names(probs, 2)\n        p_t = [sum(probs[begin:end, Name(key)]) for key in keys]\n        println(\"P(t) = $(p_t)\")\n\n        # P(z)\n        probs_trans = transpose(probs)\n        keys_trans = names(probs_trans, 2)\n        p_z = [sum(probs_trans[begin:end, Name(key)]) for key in keys_trans]\n        println(\"P(z) = $(p_z)\")\n\n        # P(t|z)\n        for (i, key) in enumerate(keys_trans)\n            probs_trans[begin:end, Name(key)] /= p_z[i]\n        end\n        cond_t_z = probs_trans\n\n        p_z_630 = p_z[findfirst(keys_trans .== 630)]\n        p_t_13 = p_t[findfirst(keys .== 13)]\n        p_t_13_z_630 = cond_t_z[Name(13), Name(630)]\n\n        bayes = p_t_13_z_630 * p_z_630 /p_t_13\n\n        cond_z_t = probs / p_t[findfirst(keys .== 13)]\n        answer = cond_z_t[Name(630), Name(13)]\n        \n        println(\"P(z=630) = $(p_z_630)\")\n        println(\"P(t=13) = $(p_t_13)\")\n        println(\"P(t=13|z=630) = $(p_t_13_z_630)\")\n        println(\"Bayes P(z=630|t=13) = $(bayes)\")\n        println(\"Answer P(z=630|t=13) = $(answer)\")\n    end\nend", "meta": {"hexsha": "de7d8cef8ffd8f670fd71a59bb6e41c752df2507", "size": 1689, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/prob_stats/complex_dist/probs_bayes/probs_bayes.jl", "max_stars_repo_name": "ShisatoYano/JuliaAutonomy", "max_stars_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2021-03-10T12:43:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T16:40:19.000Z", "max_issues_repo_path": "src/prob_stats/complex_dist/probs_bayes/probs_bayes.jl", "max_issues_repo_name": "ShisatoYano/JuliaAutonomy", "max_issues_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/prob_stats/complex_dist/probs_bayes/probs_bayes.jl", "max_forks_repo_name": "ShisatoYano/JuliaAutonomy", "max_forks_repo_head_hexsha": "d1643add4ab9625996fafeac23fc03f25eedff12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-14T02:46:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T09:19:40.000Z", "avg_line_length": 32.4807692308, "max_line_length": 84, "alphanum_fraction": 0.5435168739, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381606, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7503083690041773}}
{"text": "import Base.length\nimport Base.isempty\nimport Base.getindex\nimport Base.setindex!\nimport Base.firstindex\nimport Base.lastindex\nimport Base.sum\n\n# Use a binary tree to describe a categorical distribution\n# This allows for O(1) read, O(log n) write and O(log n) generation of a random index\n# Optimized for categorical distributions with a large number of possible outcomes\n\n# Should this be a subtype of AbstractVector?\nstruct CategoricalTree{T<:Real}\n    ns::Vector{<:Integer} # number of nodes at each layer of the tree (`ns[end]` should be 1, i.e. the root of the tree\n    as::Vector{Vector{T}} # store each layer into a separate array. Each parent node contains the sum of its children\nend\n\nfunction CategoricalTree(a::Vector{T}) where T<:Real\n    n = length(a)\n    ns::Vector{Int64} = [n]\n    while n > 1\n        if isodd(n)\n            n = Int((n+1)/2)\n            push!(ns,n)\n        else\n            n = Int(n/2)\n            push!(ns,n)\n        end\n    end\n    as = [zeros(T,k) for k in ns]\n    as[1] = a\n    for i in 1:(length(ns)-1)\n        for j in 2:2:ns[i]\n            as[i+1][Int(j/2)] = as[i][j-1] + as[i][j]\n        end\n        if isodd(ns[i])\n            as[i+1][ns[i+1]] = as[i][ns[i]]\n        end\n    end\n    return CategoricalTree{T}(ns,as)\nend\n\nisempty(ct::CategoricalTree{<:Real}) = isempty(ct.as[1])\nlength(ct::CategoricalTree{<:Real}) = length(ct.as[1])\n\nfirstindex(::CategoricalTree) = 1\nlastindex(ct::CategoricalTree) = length(ct)\n\ngetindex(ct::CategoricalTree{<:Real}, i) = ct.as[1][i]\n\nfunction setindex!(ct::CategoricalTree{<:Real}, x, i)\n    ct.as[1][i] = x\n    j = i\n    for k in 2:length(ct.ns)\n        j = isodd(j) ? Int((j+1)/2) : Int(j/2)\n        if isodd(ct.ns[k-1]) && j == ct.ns[k]\n                ct.as[k][j] = ct.as[k-1][2*j-1]\n        else\n            ct.as[k][j] = ct.as[k-1][2*j-1] + ct.as[k-1][2*j]\n        end\n    end\nend\n\n\n# since we already computed the sum, we might as well make use of it\nsum(ct::CategoricalTree{<:Real}) = ct.as[end][1]\n\n\"\"\"\n    rand_categorical(ct::CategoricalTree{<:Real}, a0)\n\nPick one index according to a categorical distribution described by `ct`.\n\"\"\"\nfunction rand_categorical(ct::CategoricalTree{<:Real}, a0 = sum(ct))\n    r = rand()*sum(ct)\n    i = length(ct.ns) - 1\n    j = 1\n    while i > 1\n        if r <= ct.as[i][j]\n            j = 2*j - 1\n        else\n            r -= ct.as[i][j]\n            j = 2*j + 1\n        end\n        i -= 1\n    end\n    if r <= ct.as[i][j]\n        return j\n    else\n        return j+1\n    end\nend\n", "meta": {"hexsha": "79d67d197f03e63fc008cff22854c0b8ed0483c9", "size": 2502, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "old/utils/categorical_tree.jl", "max_stars_repo_name": "csimal/metaplex-networks", "max_stars_repo_head_hexsha": "2010f6bdb9a0cb7be78e74f8bf64dd9aba5871ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "old/utils/categorical_tree.jl", "max_issues_repo_name": "csimal/metaplex-networks", "max_issues_repo_head_hexsha": "2010f6bdb9a0cb7be78e74f8bf64dd9aba5871ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "old/utils/categorical_tree.jl", "max_forks_repo_name": "csimal/metaplex-networks", "max_forks_repo_head_hexsha": "2010f6bdb9a0cb7be78e74f8bf64dd9aba5871ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9032258065, "max_line_length": 119, "alphanum_fraction": 0.5751398881, "num_tokens": 795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7503083638414292}}
{"text": "using PyPlot\n\nA = [1.0 2.0\n     2.0 1.0]\n\nevals, evecs = eig(A)\nevecs =(evecs[:,1], evecs[:,2])\n\nfig, ax = subplots()\nfor spine in [\"left\", \"bottom\"]\n    ax[:spines][spine][:set_position](\"zero\")\nend\n\nfor spine in [\"right\", \"top\"]\n    ax[:spines][spine][:set_color](\"none\")\nend\nax[:grid](alpha=0.4)\n\nxmin, xmax = -3, 3\nymin, ymax = -3, 3\nax[:set_xlim](xmin, xmax)\nax[:set_ylim](ymin, ymax)\n\nfor v in evecs\n    # Plot each eigenvector\n    ax[:annotate](\" \", xy=v, xytext=[0, 0],\n                  arrowprops={\"facecolor\"=>\"blue\",\n                              \"shrink\"=>0,\n                              \"alpha\"=>0.6,\n                              \"width\"=>0.5})\n\n    # Plot the image of each eigenvector\n    v = A * v\n    ax[:annotate](\" \", xy=v, xytext=[0, 0],\n                  arrowprops={\"facecolor\"=>\"red\",\n                              \"shrink\"=>0,\n                              \"alpha\"=>0.6,\n                              \"width\"=>0.5})\nend\n\nx = linspace(xmin, xmax, 3)\nfor v in evecs\n    a = v[2] / v[1]\n    ax[:plot](x, a .* x, \"b-\", lw=0.4)\nend\n", "meta": {"hexsha": "428dcaaa628e5f405b85a07d8d6b9eead10fa3b6", "size": 1054, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "_archive_/jl/examples/eigenvec.jl", "max_stars_repo_name": "seapanda85/My_Quant_Econ", "max_stars_repo_head_hexsha": "0e8719becef0a9526619885afe547cc9a34c5512", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_archive_/jl/examples/eigenvec.jl", "max_issues_repo_name": "seapanda85/My_Quant_Econ", "max_issues_repo_head_hexsha": "0e8719becef0a9526619885afe547cc9a34c5512", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_archive_/jl/examples/eigenvec.jl", "max_forks_repo_name": "seapanda85/My_Quant_Econ", "max_forks_repo_head_hexsha": "0e8719becef0a9526619885afe547cc9a34c5512", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9130434783, "max_line_length": 50, "alphanum_fraction": 0.4525616698, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7503083634701146}}
{"text": "#=\n\nPurpose: Use the Schur method to find the bounded solution of the\n         discrete Lyapunov equation:\n\n         X = B + A*X*A'.\n\nInputs:  A (n*n)\n         B (n*n) = Symmetric positive semidefinite\n\nOutputs: X (n*n) = Symmetric positive semidefinite solution.\n\nBased on Octave code written by A.S. Hodel.\n\n=#\n\nfunction dlyap{T<:AbstractFloat}(a::Array{T,2},b::Array{T,2})\n\n  n = size(a,1)\n  x = zeros(n,n)\n  j = n\n\n  (s,u) = schur(a)\n  b = u'b*u\n\n  while j > 0\n    j1 = j\n    if j == 1\n      block = 1\n    elseif s[j,j-1] > 2*eps(T)*norm(s)\n      block = 2\n      j -= 1\n    else\n      block = 1\n    end\n    lhs = kron(s[j:j1,j:j1],s) - I # I = eye(block*n)\n    rhs = vec(b[:,j:j1])\n    if j1 < n\n      rhs2 = s*(x[:,(j1+1):n]*s[j:j1,(j1+1):n]')\n      rhs += vec(rhs2)\n    end\n    w = -lhs\\rhs\n    x[:,j] = w[1:n]\n    if block == 2\n      x[:,j1] = w[(n+1):block*n]\n    end\n    j -= 1\n  end\n\n  x = u*x*u'\n\n  return x\n\nend\n", "meta": {"hexsha": "9fa6de3df893dba038c44ed3e079d9a7090a7697", "size": 924, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dlyap.jl", "max_stars_repo_name": "JuliaPackageMirrors/SolveDSGE.jl", "max_stars_repo_head_hexsha": "1f416fa81fe7a77279bff1d81474b85e652fb58a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-07T23:17:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-07T23:17:35.000Z", "max_issues_repo_path": "src/dlyap.jl", "max_issues_repo_name": "JuliaPackageMirrors/SolveDSGE.jl", "max_issues_repo_head_hexsha": "1f416fa81fe7a77279bff1d81474b85e652fb58a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dlyap.jl", "max_forks_repo_name": "JuliaPackageMirrors/SolveDSGE.jl", "max_forks_repo_head_hexsha": "1f416fa81fe7a77279bff1d81474b85e652fb58a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.8, "max_line_length": 65, "alphanum_fraction": 0.5, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.750226412564301}}
{"text": "\nusing Plots\nusing Optim\n\n# Calculate dose-response\n# flux reaction:\nfunction reaction(conc,Km,Vmax)\n    10 .^Vmax.*conc./(10 .^Km .+ conc)\nend\n\nKm = 0\nVmax = 1\nconc = collect(0:.01:2)\n\nflux = reaction(conc, Km, Vmax)\nplot(conc,flux)\n\n# simulate data with 7% std\nconc_sim = [.1,.5,1,2]\nflux_sim = reaction(conc_sim,  Km, Vmax)\nflux_sim = randn(length(flux_sim))*0.07.*flux_sim+flux_sim\nstd_sim = flux_sim * .07\n\nscatter!(conc_sim,flux_sim,yerror=std_sim,grid=false,linealpha = 0)\n\n# negative log-likelihood for simulated data\nfunction L(conc,flux,std,p)\n    X = reaction(conc,p[1],p[2])\n    LL = -sum(-length(X)*log(2π)/2 .- length(X).*log.(abs.(std)) .- (sum((flux .- X).^2) ./ (2std.^2)))\nend\n\n# maximum likelihood fit\ninit = [1.0,1.0]        # start parameters Km,Vmax\noptimum = optimize(p -> L(conc_sim,flux_sim,std_sim,p),init,Newton())\n\n\n### We will continue with the profile likelihood on July, 10th\n", "meta": {"hexsha": "8dc24f896b98e1d523d4317791bcfb8cab3d63bf", "size": 907, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Exercises/Tutorial_8_Likelihood.jl", "max_stars_repo_name": "dlill/DynSysBio2019", "max_stars_repo_head_hexsha": "6fdf691a2fd184ac7fa665bc2865c619570f05f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-24T12:34:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-24T12:34:57.000Z", "max_issues_repo_path": "Exercises/Tutorial_8_Likelihood.jl", "max_issues_repo_name": "dlill/DynSysBio2019", "max_issues_repo_head_hexsha": "6fdf691a2fd184ac7fa665bc2865c619570f05f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercises/Tutorial_8_Likelihood.jl", "max_forks_repo_name": "dlill/DynSysBio2019", "max_forks_repo_head_hexsha": "6fdf691a2fd184ac7fa665bc2865c619570f05f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-04-24T12:33:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-31T09:20:23.000Z", "avg_line_length": 23.8684210526, "max_line_length": 103, "alphanum_fraction": 0.6736493936, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.798186784940666, "lm_q1q2_score": 0.7502264121335268}}
{"text": "include(\"../algoritmos-busqueda/generar-vecino.jl\")\ninclude(\"../learner/euclidean-1-NN.jl\")\ninclude(\"../algoritmos-busqueda/busqueda-local.jl\")\ninclude(\"../utils/funcion-objetivo.jl\")\n\nfunction HeuristicaEnfriamiento(F_w, F_w_nuevo, T)\n    return rand() < exp((F_w - F_w_nuevo)/ (T*1.380649*10^(-23)))\nend\n\n\"\"\"\n    Expresón para pasar avanzar en la construcción de la T\n\"\"\"\nmacro SiguienteT(ß, T)\n    quote\n        $(esc(T))  / (1 + $(esc(ß))*$(esc(T)))\n    end \nend \n\n\"\"\"\n    Expresión para calcular la beta \n\"\"\"\nmacro calculaß(T, T_f, M)\n    quote\n        ($(esc(T)) - $(esc(T_f)))/($(esc(M))*$(esc(T)) *$(esc(T_f)))\n    end\nend\n\n\"\"\"\nfunction EnfriamientoSimulado(\n    evaluaciones_maximas_funcion_objetivo::Int,\n    numero_atributos::Int, \n    umbral_atributo::Real, \n    F,  # fitness\n    probabilidad_aceptar_peor = 0.3,\n    temperatura_final = 10^(-3),\n    maximo_vecinos,\n    maximo_vecinos_aceptados\n    )::Vector{<:Real}\nDevuelve mejor vector de peso encontrando de acorde\nal algoritmo de enfriamiento simulado\n\"\"\"\nfunction EnfriamientoSimulado(\n    evaluaciones_maximas_funcion_objetivo::Int,\n    numero_atributos::Int, \n    umbral_atributo::Real, \n    F,  # fitness\n    probabilidad_aceptar_peor,\n    temperatura_final,\n    maximo_vecinos,\n    maximo_vecinos_aceptados\n    )::Vector{<:Real}\n    µ = 0.3\n    M = 15000/maximo_vecinos\n\n    # inicializaciones\n    w = rand(numero_atributos) # vector de tamaño atributo uniformement inicializado\n    # Ponemos a cero atributos menores que umbral atributo\n    w = map(x-> (x<umbral_atributo) ? 0 : x , w)\n    w_mejor = w\n    F_w = F(w)\n    F_w_mejor = F_w\n\n    vecinos_aceptados = 1\n    evaluaciones = 0\n    primera_iteracion = true\n\n    T = µ * F_w / -log(probabilidad_aceptar_peor)\n    ß = (T - temperatura_final) / (M * T * temperatura_final) \n    while ((evaluaciones < evaluaciones_maximas_funcion_objetivo \n        && vecinos_aceptados > 0\n        &&\n        T <= temperatura_final\n    )\n        ||\n        primera_iteracion\n    )\n        #reseteamos valores\n        vecinos_aceptados = 0\n        vecinos_generados = 0\n        primera_iteracion = false\n\n        while( vecinos_generados < maximo_vecinos &&\n            vecinos_aceptados < maximo_vecinos_aceptados)\n            w_n = GenNeighbourhood(w, 0, 1)\n            F_w_vecino = F(w_n)\n            vecinos_generados += 1\n            ß = @calculaß(T, temperatura_final, M)\n            \n            if(F_w < F_w_vecino || HeuristicaEnfriamiento(F_w, F_w_vecino, T))\n                vecinos_aceptados += 1\n                w = w_n\n                F_w = F_w_vecino\n                if F_w_vecino > F_w_mejor\n                    w_mejor = w_n\n                    F_w_mejor = F_w_vecino\n                end\n            end\n        end\n        evaluaciones += 1\n        T = @SiguienteT(ß, T)\n    end\n    return w_mejor\nend\n\n\n\"\"\"\n    BL_LearnerOneNN(data::Matrix{<:Real}, labels::Vector{<:Real})\nDevuelve un clasificado 1-NN refinado por unos pesos en la distancia euclídea. \nEse vector de pesos se ha obtenido a partir de un algoritmo de búsqueda local \n\"\"\"\nfunction EnfriamientoSimulado_LearnerOneNN(data::Matrix{<:Real}, labels)\n    # Creamos función objetivo \n    a = 0.5\n    umbral_tasa_reduccion = 0.1\n    F = CrearFuncionObjetivo(data, labels, a, umbral_tasa_reduccion )\n\n    numero_atributos = size(data)[2] # los atributos son las columnas \n    # Criterios de acorde a los requisitos \n    probabilidad_aceptar_peor = 0.3\n    temperatura_final = 10^(-3)\n    numero_maximo_vecinos_sin_mejora = 20 * numero_atributos \n    evaluaciones_maximas_funcion_objetivo = 15000\n    maximo_vecinos = 10*numero_atributos\n    maximo_vecinos_aceptados = 0.1*maximo_vecinos\n    # Buscamos pesos de acorde a parámetros calculados\n    w = EnfriamientoSimulado(\n        evaluaciones_maximas_funcion_objetivo,\n        numero_atributos, \n        umbral_tasa_reduccion, \n        F,  # fitness\n        probabilidad_aceptar_peor,\n        temperatura_final,\n        maximo_vecinos,\n        maximo_vecinos_aceptados\n    )\n\n    return WeightedLearnerEuclideanOneNN(w, data, labels), F(w), w\nend", "meta": {"hexsha": "d69871a2fb3d35361213d28782e819c66e4dbde8", "size": 4080, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algoritmo-enfriamiento/enfriamiento-simulado.jl", "max_stars_repo_name": "BlancaCC/Problema-aprendiaje-pesos-en-caracter-stica", "max_stars_repo_head_hexsha": "cb64e50afa704ded4eb9bfa81aa8a7e2f3f7f617", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algoritmo-enfriamiento/enfriamiento-simulado.jl", "max_issues_repo_name": "BlancaCC/Problema-aprendiaje-pesos-en-caracter-stica", "max_issues_repo_head_hexsha": "cb64e50afa704ded4eb9bfa81aa8a7e2f3f7f617", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algoritmo-enfriamiento/enfriamiento-simulado.jl", "max_forks_repo_name": "BlancaCC/Problema-aprendiaje-pesos-en-caracter-stica", "max_forks_repo_head_hexsha": "cb64e50afa704ded4eb9bfa81aa8a7e2f3f7f617", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5652173913, "max_line_length": 84, "alphanum_fraction": 0.6458333333, "num_tokens": 1271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428692, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7502264112208542}}
{"text": "# Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/\n#  Niccolò Antonello <nantonel@idiap.ch>\n\nexport LogWeight\n\n\"\"\"\n`LogWeight(x)`\n\n| Set                                 |     ``\\\\oplus``      |  ``\\\\otimes``  | ``\\\\bar{0}`` | ``\\\\bar{1}`` |\n|:-----------------------------------:|:--------------------:|:--------------:|:------------:|:------------:|\n|``\\\\mathbb{R}\\\\cup\\\\{\\\\pm\\\\infty\\\\}``|``\\\\log(e^{x}+e^{y})``|     ``+``      |``-\\\\infty``  |   ``0``      | \n\"\"\"\nstruct LogWeight{T <: AbstractFloat} <: Semiring\n  x::T\nend\n\nLogWeight(x::Number) = LogWeight(float(x))\n\nzero(::Type{LogWeight{T}}) where T = LogWeight{T}(T(-Inf))\none(::Type{LogWeight{T}}) where T = LogWeight{T}(zero(T))\n\n*(a::LogWeight{T}, b::LogWeight{T}) where {T <: AbstractFloat} = LogWeight{T}(a.x + b.x)\n+(a::LogWeight{T}, b::LogWeight{T}) where {T <: AbstractFloat} = LogWeight{T}(logadd(a.x,b.x))\n/(a::LogWeight{T}, b::LogWeight{T}) where {T <: AbstractFloat} = LogWeight{T}(a.x - b.x)\nreverse(a::LogWeight) = a\nfunction logadd(y::T, x::T) where {T <: AbstractFloat} \n  if isinf(x) return y end\n  if isinf(y) return x end\n  if x < y\n    diff = x-y\n    x = y \n  else\n    diff = y-x\n  end\n  return x + log1p(exp(diff))\nend\n\n# parsing\nparse(::Type{S},str) where {T, S <: LogWeight{T}} = S(parse(T,str))\n\n#properties\niscommulative(::Type{W}) where {W <: LogWeight} = true\nisleft(::Type{W}) where {W <: LogWeight} = true\nisright(::Type{W}) where {W <: LogWeight}= true\nisweaklydivisible(::Type{W}) where {W <: LogWeight}= true\niscomplete(::Type{W}) where {W <: LogWeight}= true\n", "meta": {"hexsha": "c19bb72d4ecfba2bcce9f8d7b8b48456de7f5865", "size": 1566, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/semirings/log.jl", "max_stars_repo_name": "idiap/FiniteStateTransducers.jl", "max_stars_repo_head_hexsha": "430bf273960bd3f43f4042ee85a7c9f3d846d37f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-20T10:41:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-20T10:41:21.000Z", "max_issues_repo_path": "src/semirings/log.jl", "max_issues_repo_name": "idiap/FiniteStateTransducers.jl", "max_issues_repo_head_hexsha": "430bf273960bd3f43f4042ee85a7c9f3d846d37f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-02-09T16:54:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-14T00:10:46.000Z", "max_forks_repo_path": "src/semirings/log.jl", "max_forks_repo_name": "idiap/FiniteStateTransducers.jl", "max_forks_repo_head_hexsha": "430bf273960bd3f43f4042ee85a7c9f3d846d37f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3191489362, "max_line_length": 110, "alphanum_fraction": 0.5402298851, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922387, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7502264084828361}}
{"text": "\n\"\"\"\n    cheby1(n, x)\n\nCompute the Chebyshev polynomial of the first kind of order n at point x.\n\nThis family of Chebyshev polynomials are a special case of the Jacobi polynomials\nwith α, β = -1/2.\n\"\"\"\nfunction cheby1(n, x)\n    return Jacobi.jacobi(n, -0.5, -0.5, x)\nend\n\n\"\"\"\n    cheby2(n, x)\n\nCompute the Chebyshev polynomial of the second kind of order n at point x.\n\nThis family of Chebyshev polynomials are a special case of the Jacobi polynomials\nwith α, β = 1/2.\n\"\"\"\nfunction cheby2(n, x)\n    return Jacobi.jacobi(n, 0.5, 0.5, x)\nend\n", "meta": {"hexsha": "0d51b5b09f080088dfe87dab70a2a29544049d6e", "size": 540, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cheby.jl", "max_stars_repo_name": "mileslucas/OpticsPolynomials.jl", "max_stars_repo_head_hexsha": "ca8ec35c627a6c1d1c2b8a792460900b600e584e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cheby.jl", "max_issues_repo_name": "mileslucas/OpticsPolynomials.jl", "max_issues_repo_head_hexsha": "ca8ec35c627a6c1d1c2b8a792460900b600e584e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cheby.jl", "max_forks_repo_name": "mileslucas/OpticsPolynomials.jl", "max_forks_repo_head_hexsha": "ca8ec35c627a6c1d1c2b8a792460900b600e584e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6, "max_line_length": 81, "alphanum_fraction": 0.6944444444, "num_tokens": 179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766225, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7502264040217219}}
{"text": "#=\ngauss2.jl\n=#\n\n\n#using ImagePhantoms #: Object, Object2d\n\nexport Gauss2\nexport phantom, radon, spectrum, fwhm2spread\n\n\n\"\"\"\n    Gauss2 <: AbstractShape2\n\"\"\"\nstruct Gauss2 <: AbstractShape2 end\n\n\n# constructors\n\n\n\"\"\"\n    Gauss2(cx, cy, wx, wy=wx, ϕ=0, value::Number=1)\n    Gauss2(center::NTuple{2,RealU}, width::NTuple{2,RealU}=(1,1), ϕ::RealU=0, v=1)\n    Gauss2([6-vector])\n    Gauss2(w, v=1) (isotropic of width `w`)\nConstruct `Gauss2` object from parameters;\nhere `width` = FWHM (full-width at half-maximum).\n\nIn 1D, the formula is `g(x) = exp(-π ((x - cx) / sx)^2)`\nwhere `sx = fwhm2spread(w) = w * sqrt(π / log(16))`,\nwhich, for `cx=0`,  has 1D FT `G(ν) = sx^2 exp(π (sx νx)^2)`.\n\"\"\"\nfunction Gauss2(\n    cx::RealU,\n    cy::RealU,\n    wx::RealU,\n    wy::RealU = wx,\n    ϕ::RealU = 0,\n    value::Number = 1,\n)\n    (cx, cy, wx, wy) = promote(cx, cy, wx, wy)\n    Object(Gauss2(), (cx,cy), (wx,wy), ϕ, value)\nend\n\nfunction Gauss2(\n    center::NTuple{2,RealU},\n    width::NTuple{2,RealU} = (1,1) .* oneunit(center[1]),\n    ϕ::RealU = 0,\n    value::Number = 1,\n)\n    Gauss2(center..., width..., ϕ, value)\nend\n\nfunction Gauss2(v::AbstractVector{<:Number})\n    length(v) == 6 || throw(ArgumentError(\"$v wrong length\"))\n    Gauss2(v...)\nend\n\nGauss2(w::RealU, v::Number = 1) = Gauss2((zero(w),zero(w)), (w,w), 0, v)\n\n\n# helper\n\n\"\"\"\n    s = fwhm2spread(w)\nConvert FWHM `w` to equivalent Gaussian spread `s` for ``\\\\exp(-π (x/s)^2)``.\n`exp(-π (fwhm/2/s)^2) = 1/2` means\n`fwhm/2/s) = sqrt(log(2)/π)`\n`2s/fwhm = sqrt(π/log(2))`\n`2s = fwhm * sqrt(π/log(2))`\n`s = fwhm * sqrt(π / log(16))`\n\"\"\"\n@inline fwhm2spread(w) = w * sqrt(π / log(16))\n\n\n# methods\n\n\n\"\"\"\n    phantom(ob::Object2d{Gauss2})\nReturns function of `(x,y)` for making image.\n\"\"\"\nfunction phantom(ob::Object2d{Gauss2})\n    return (x,y) -> ob.value * # trick due to fwhm to spread scaling:\n        exp(-π * sum(abs2.(coords(ob, x, y))) / fwhm2spread(1)^2)\nend\n\n\n\"\"\"\n    radon_gauss2(r, ϕ, cx, cy, wx, wy, θ)\nRadon transform at `(r,ϕ)` of 2D Gaussian.\n\"\"\"\nfunction radon_gauss2(r, ϕ, cx, cy, wx, wy, θ)\n    (sx, sy) = fwhm2spread.((wx, wy))\n    (sinϕ, cosϕ) = sincos(ϕ)\n    r -= cx * cosϕ + cy * sinϕ # Radon translation property\n    (sinϕ, cosϕ) = sincos(ϕ - θ) # Radon rotation property\n    s = sqrt(abs2(sx * cosϕ) + abs2(sy * sinϕ)) # by Fourier-slice Thm.\n    return sx * sy / s * exp(-π * abs2(r / s))\nend\n\n\n\"\"\"\n    radon(ob::Object2d{Gauss2})\nReturns function of `(r,ϕ)` for making a sinogram.\n\"\"\"\nradon(ob::Object2d{Gauss2}) = (r,ϕ) -> ob.value *\n    radon_gauss2(r, ϕ, ob.center..., ob.width..., ob.angle[1])\n\n\nfunction spectrum_gauss2(fx, fy, cx, cy, wx, wy, θ)\n    (sx, sy) = fwhm2spread.((wx, wy))\n    (kx, ky) = rotate2d(fx, fy, θ) # rotate first, then translate\n    return sx * exp(-2im*π*fx*cx) *\n           sy * exp(-2im*π*fy*cy) * exp(-π * (abs2(sx*kx) + abs2(sy*ky)))\nend\n\n\"\"\"\n    spectrum(ob::Object2d{Gauss2})\nReturns function of ``(f_x,f_y)`` for the spectrum (2D Fourier transform).\n\"\"\"\nspectrum(ob::Object2d{Gauss2}) = (fx,fy) -> ob.value *\n    spectrum_gauss2(fx, fy, ob.center..., ob.width..., ob.angle[1])\n", "meta": {"hexsha": "7c33ce9fdaa69bbfd41f9d5ca05cc1ae86da9c85", "size": 3082, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gauss2.jl", "max_stars_repo_name": "EricCheek3731/ImagePhantoms.jl", "max_stars_repo_head_hexsha": "e9d32d41553d634334c939a34d0fd1174ebd4e0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-08-21T07:57:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T21:25:31.000Z", "max_issues_repo_path": "src/gauss2.jl", "max_issues_repo_name": "EricCheek3731/ImagePhantoms.jl", "max_issues_repo_head_hexsha": "e9d32d41553d634334c939a34d0fd1174ebd4e0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2021-07-16T16:10:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T16:42:07.000Z", "max_forks_repo_path": "src/gauss2.jl", "max_forks_repo_name": "EricCheek3731/ImagePhantoms.jl", "max_forks_repo_head_hexsha": "e9d32d41553d634334c939a34d0fd1174ebd4e0d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-01T01:39:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T01:39:08.000Z", "avg_line_length": 24.8548387097, "max_line_length": 82, "alphanum_fraction": 0.5902011681, "num_tokens": 1195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.750226399509483}}
{"text": "export cwt\n\n\"\"\"\n    cwt(signal, Λ)\n\nCalculate the continuous wavelet transform of a signal given filter bank Λ.\n\n# Arguments\n - `signal::Vector{Float64}`: Time series.\n - `Λ::Array{Float64, 2}`: Fourier transformed filters arranged by [frequency, scale].\n\"\"\"\nfunction cwt(signal::Vector{Float64}, Λ::Array{Float64,2})\n    signal_ft = fft(signal, 1)\n    W = ifft(signal_ft.*Λ, 1)\n    return W\nend\n\n\"\"\"\n    cwt(signal, Λ, ω0, δt, δj)\n\nConvenience method for cwt that constructs the filter bank Λ given a signal.\n\n# Arguments\n - `signal::Vector{Float64}`: Time series.\n - `F::FilterBank1dBlock`: Fourier transformed filters and metadata\n\"\"\"\nfunction cwt(signal::Vector{Float64}, F::FilterBank1dBlock)\n    W = cwt(signal, F.Λ)\n    return W\nend\n", "meta": {"hexsha": "71678d6acf636ab00ab6b5fdad135e17bd5a41b0", "size": 740, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transform/cwt.jl", "max_stars_repo_name": "jaredbryan881/Scat.jl", "max_stars_repo_head_hexsha": "743f51629bec62767c64c51ae932e1a8f4926d0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/transform/cwt.jl", "max_issues_repo_name": "jaredbryan881/Scat.jl", "max_issues_repo_head_hexsha": "743f51629bec62767c64c51ae932e1a8f4926d0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/transform/cwt.jl", "max_forks_repo_name": "jaredbryan881/Scat.jl", "max_forks_repo_head_hexsha": "743f51629bec62767c64c51ae932e1a8f4926d0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8709677419, "max_line_length": 86, "alphanum_fraction": 0.6932432432, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7502263972533636}}
{"text": "@doc raw\"\"\"\n    rating_constraint!(canonical::Canonical,\n                            rating_data::Vector{Tuple{String, Float64}},\n                            cons_name::Symbol,\n                            var_names::Tuple{Symbol, Symbol})\n\nConstructs constraint from rating data and related variable tuple.\n\n# Constraint\n\n``` var1[r[1], t]^2 + var2[r[1], t]^2 <= r[2]^2 ```\n\nwhere r in rating data and t in time steps.\n\n# LaTeX\n\n`` x_1^2 + x_2^2 \\leq r^2 ``\n\n# Arguments\n* canonical::Canonical : the canonical model built in PowerSimulations\n* rating_data::Vector{Tuple{String, Float64}} : rating data name (1) and value (2)\n* cons_name::Symbol : name of the constraint\n* var_names::Tuple{Symbol, Symbol} : the names of the variables\n- : var_names[1] : var1\n- : var_names[2] : var2\n\"\"\"\nfunction rating_constraint!(canonical::Canonical,\n                            rating_data::Vector{Tuple{String, Float64}},\n                            cons_name::Symbol,\n                            var_names::Tuple{Symbol, Symbol})\n    time_steps = model_time_steps(canonical)\n    var1 = get_variable(canonical, var_names[1])\n    var2 = get_variable(canonical, var_names[2])\n    add_cons_container!(canonical, cons_name, (r[1] for r in rating_data), time_steps)\n    constraint = get_constraint(canonical, cons_name)\n\n    for r in rating_data\n        for t in time_steps\n          constraint[r[1], t] = JuMP.@constraint(canonical.JuMPmodel, var1[r[1], t]^2 + var2[r[1], t]^2 <= r[2]^2)\n        end\n    end\n\n    return\n\nend\n", "meta": {"hexsha": "49c8b7dcaedd9ff6e5898246215a091032246be5", "size": 1508, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/devices_models/devices/common/rating_constraints.jl", "max_stars_repo_name": "mattirish/PowerSimulations.jl", "max_stars_repo_head_hexsha": "f2ebec4c68926e749a2ec422cc94c84a4ac7584c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/devices_models/devices/common/rating_constraints.jl", "max_issues_repo_name": "mattirish/PowerSimulations.jl", "max_issues_repo_head_hexsha": "f2ebec4c68926e749a2ec422cc94c84a4ac7584c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/devices_models/devices/common/rating_constraints.jl", "max_forks_repo_name": "mattirish/PowerSimulations.jl", "max_forks_repo_head_hexsha": "f2ebec4c68926e749a2ec422cc94c84a4ac7584c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7826086957, "max_line_length": 114, "alphanum_fraction": 0.6187002653, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191309994468, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7502203206603751}}
{"text": "# Hessian Eigenmaps (HLLE)\n# ---------------------------\n# Hessian eigenmaps: Locally linear embedding techniques for high-dimensional data,\n# D. Donoho and C. Grimes, Proc Natl Acad Sci U S A. 2003 May 13; 100(10): 5591–5596\n\nimport Combinatorics: combinations\n\n#### HLLE type\nstruct HLLE{T <: AbstractFloat} <: SpectralResult\n    k::Int\n    λ::AbstractVector{T}\n    proj::Projection{T}\n\n    HLLE{T}(k::Int, λ::AbstractVector{T}, proj::Projection{T}) where T = new(k, λ, proj)\nend\n\n## properties\noutdim(M::HLLE) = size(M.proj, 1)\nprojection(M::HLLE) = M.proj\n\neigvals(M::HLLE) = M.λ\nneighbors(M::HLLE) = M.k\n\n## show & dump\nfunction show(io::IO, M::HLLE)\n    print(io, \"Hessian Eigenmaps(outdim = $(outdim(M)), neighbors = $(neighbors(M)))\")\nend\n\nfunction dump(io::IO, M::HLLE)\n    show(io, M)\n    println(io, \"eigenvalues: \")\n    Base.showarray(io, transpose(M.λ), header=false, repr=false)\n    println(io)\n    println(io, \"projection:\")\n    Base.showarray(io, M.proj, header=false, repr=false)\nend\n\n## interface functions\nfunction transform(::Type{HLLE}, X::DenseMatrix{T}; d::Int=2, k::Int=12) where T<:AbstractFloat\n    n = size(X, 2)\n\n    # Identify neighbors\n    D, I = find_nn(X, k)\n\n    # Obtain tangent coordinates and develop Hessian estimator\n    hs = round(Int, d*(d+1)/2)\n    W = spzeros(hs*n,n)\n    for i=1:n\n        # re-center points in neighborhood\n        μ = mean(X[:,I[:,i]], dims=2)\n        N = X[:,I[:,i]] .- μ\n        # calculate tangent coordinates\n        #tc = svd(transpose(N)).U[:,1:d]\n        tc = svd(N).V[:,1:d]\n\n        # Develop Hessian estimator\n        Yi = [ones(k) tc zeros(k,hs)]\n        for ii=1:d\n            Yi[:,d+ii+1] = tc[:,ii].^2\n        end\n        yi = 2(1+d)\n        for (ii,jj) in combinations(1:d,2)\n            Yi[:, yi] = tc[:, ii] .* tc[:, jj]\n            yi += 1\n        end\n        F = qr(Yi)\n        H = transpose(Matrix(F.Q)[:,d+2:end])\n        W[(i-1)*hs .+ (1:hs),I[:,i]] = H\n    end\n\n    # decomposition\n    λ, V = decompose(transpose(W)*W, d)\n    return HLLE{T}(k, λ, transpose(V) .* sqrt(n))\nend\n", "meta": {"hexsha": "31279ea944e55d78b4a1f2f2d10ccca43f9dc0d5", "size": 2060, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hlle.jl", "max_stars_repo_name": "simonschoelly/ManifoldLearning.jl", "max_stars_repo_head_hexsha": "ac0f75fd0ea71a625e939d36d3f2ae118fdb2069", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hlle.jl", "max_issues_repo_name": "simonschoelly/ManifoldLearning.jl", "max_issues_repo_head_hexsha": "ac0f75fd0ea71a625e939d36d3f2ae118fdb2069", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hlle.jl", "max_forks_repo_name": "simonschoelly/ManifoldLearning.jl", "max_forks_repo_head_hexsha": "ac0f75fd0ea71a625e939d36d3f2ae118fdb2069", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4666666667, "max_line_length": 95, "alphanum_fraction": 0.567961165, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7502167194845963}}
{"text": "###########################################################\n# Load (old) functions \ninclude(\"bils_chang_kim_2011/steady_state_equilibrium.jl\")\n\n###########################################################\n# Import necessary packages\nusing BasisMatrices\nusing Optim \nusing Distributions \nusing Parameters \nusing LinearAlgebra \nusing Distributions\nusing Optim\nusing QuantEcon\nusing SpecialFunctions\nusing SparseArrays\nusing Plots \nusing LaTeXStrings \nusing ThreadTools \n\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n# Model parameters \n@with_kw mutable struct ModelParameters\n    A::Float64              = 1.0                           # output productivity factor\n    r::Float64              = 0.06                          # annual interest rate \n    r_mon::Float64          = (1.0 + r)^(1.0/12.0) - 1.0    # monthly interest rate \n    worker_surplus::Float64 = 0.5                           # worker's share of surplus \n    β::Float64              = 0.9948                        # discount factor \n    β_mon::Float64          = 1.0/(1.0 + r_mon)             # monthly depreciation rate \n    γ::Float64              = 1.0                           # curvature of utility function \n    λ::Float64              = 0.02                          # exogenous separation rate \n    b::Float64              = 0.4                           # UI benefits \n    B::Float64              = 0.15                          # utility from leisure \n    κ::Float64              = 0.522                         # vacancy posting cost with log utility \n    θ::Float64              = 1.0                           # labor market tightness, v/u, normalized to 1\n    α::Float64              = 0.5                           # power term in the matching function \n    η::Float64              = 0.3133                        # scale parameter in the matching function\n    p_θ::Float64            = η*θ^α                         # unemployed worker matching rate  \n    q_θ::Float64            = η*θ^(α-1)                     # vacancy matching probability \n    amin::Float64           = -6.0                          # minimum asset \n    amax::Float64           = 120.0                         # maximum asset \n    agrid::Vector{Float64}  = LinRange(amin, amax, 20)      # asset grid \n    ρ_x::Float64            = 0.97                          # persistence of idiosyncratic productivity ln(x)\n    σ_x::Float64            = 0.13                          # std. dev. of innovation to ln(x) \n    π_x                     = TauchenApprox(9, ρ_x, σ_x).distribution           # probability weights on ln(x) \n    xgrid                   = exp.(TauchenApprox(9, ρ_x, σ_x).state_values)     # match productivity grid \n    spline_A                = SplineParams(agrid,0,1)  \n    spline_X                = SplineParams(xgrid,0,1) \n    basis_A                 = Basis(spline_A)\n    basis_AX                = Basis(spline_A,spline_X)\n    nodes_A                 = nodes(basis_A)[1]\n    nodes_AX                = nodes(basis_AX)[1] \nend;\n\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n# utility function \nfunction utility(para::ModelParameters, c::Real)\n    \n    γ = para.γ # Store risk-aversion parameter\n\n    # Define the utility mapping \n    # condition on the input `c`\n    if c > 0 \n        if γ == 1\n          return log(c) # if σ = 1, CRRA utility is log\n        else\n          return (c^(1-γ)-1)/(1-γ) # if σ != 1, regular specification\n        end\n    else\n        return -Inf # infinite disutility if c∈(-∞,0]\n    end\nend;\n\nfunction utility(para::ModelParameters, cvec)\n\n  u(c) = utility(para,c)\n\n  return u.(cvec)\nend;\n\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n# Initialize interpolated worker value functions\nfunction InitializeValues(para::ModelParameters)\n    \n    # Retrieve asset and productivity shock grids \n    @unpack basis_A, basis_AX, nodes_A, nodes_AX = para \n    \n    # Create functions to map all (a,x) and (a) to 1\n    # for both W(a,x) and U(a) \n    g1d = x -> x[1]^0\n    gvals = [g1d(nodes_AX[i,:]) for i in 1:size(nodes_A,1)]\n    f2d = x -> x[1]^0 * x[2]^0\n    fvals = [f2d(nodes_AX[i,:]) for i in 1:size(nodes_AX,1)]\n\n    # Interpolate W(a,x) and U(a) \n    W_init = Interpoland(basis_AX, fvals);\n    U_init = Interpoland(basis_A, gvals)\n\n    # Return bases for A and A×X\n    # as well as interpolated initial W(a,x) and U(a) \n    return W_init, U_init\nend;\n\n###########################################################\n# Initialize interpolated worker value functions\nW_init, U_init = InitializeValues(ModelParameters());\n\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n# Initialize interpolated worker wage schedule\nfunction InitializeWage(para::ModelParameters)\n    \n    # Retrieve asset and productivity shock grids \n    # as well as the market tightness paramter θ\n    @unpack θ, basis_AX, nodes_AX = para\n    \n    # Map all (a,x) to θ*0.9 = 0.9\n    f2d = x -> x[1]^0 * x[2]^0 * θ * 0.9\n    fvals = [f2d(nodes_AX[i,:]) for i in 1:size(nodes_AX,1)]\n\n    # Interpolate wage schedule over A×X\n    wage_init = Interpoland(basis_AX, fvals);\n\n    # Return basis for A×X \n    # and interpolated wage schedule \n    return wage_init\nend;\n\n###########################################################\n# Initialize interpolated wage schedule\nwage_init = InitializeWage(ModelParameters());\n\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n# Interpolated invariant productivity shock process density function\nfunction ShockDensity(para::ModelParameters, xval)\n\n    @unpack ρ_x, σ_x = para  \n\n    distr = LogNormal(0, σ_x/sqrt(1-ρ_x^2))\n    density = pdf(distr, xval)\n\n    return density  \nend \n\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n# Single iteration of the Bellman map w interpolated objects \nfunction WorkerBellmanMap(para::ModelParameters, wage, W_old, U_old)\n\n    # Import parameters \n    @unpack xgrid, π_x, β, b, B, p_θ, r, basis_A, basis_AX, nodes_A, nodes_AX = para \n    \n    # Shorthand for utility\n    u(c) = utility(para,c)\n\n    # Create empty W and U objects \n    W_new           = similar(nodes_AX[:,1])\n    U_new           = similar(nodes_A)\n    emp_policy      = similar(W_new)\n    unemp_policy    = similar(U_new)\n\n    # Initialize index for U(a) \n    k=0\n\n    # Fill out W_new and U_new matrices \n     Threads.@threads for i in 1:length(nodes_AX[:,1])\n    #for i in 1:length(nodes_AX[:,1])\n        \n        # Create (a,x) vector \n        ax = vec(nodes_AX[i,:])\n\n        # Create Bellman mapping under employment \n        c_emp(a′) = (1+r)*ax[1] + wage(ax) - a′ \n        obj_emp     = tmap(a′ -> (1)*(u(c_emp(a′)) + β * sum( π_x[i]*max.(W_old(vec([a′ xgrid[i]])), U_old(xgrid[i])) for i in 1:length(xgrid))), nodes_A)\n        # Solve for maximum W(a,x) \n        # and maximizing a′ \n        W_new[i], optimal_a′ = findmax(obj_emp)\n        emp_policy[i] = nodes_A[optimal_a′]\n\n        # If x equals E[x], then \n        # start solving for max. U(a) \n        # and maximizing a′\n        if ax[2] ≈ 1.0 \n            # Update index for U(a) \n            k = k + 1\n            # Create Bellman mapping under unemployment \n            c_unemp(a′) = (1+r)*ax[1] + b - a′\n            obj_unemp   = tmap( a′ -> u(c_unemp(a′)) + B + β*(1-p_θ)*U_old(ax[1]) .+ β*(p_θ)*W_old(ax), nodes_A)\n            # Solve for maximum W(a,x) \n            # and maximizing a′\n            U_new[k], optimal_a′ = findmax(obj_unemp)\n            unemp_policy[k] = nodes_A[optimal_a′]\n        end\n    end\n\n    # Interpolate W_new & U_new \n    W_new = Interpoland(basis_AX, W_new)\n    U_new = Interpoland(basis_A, U_new)\n\n    return W_new, U_new, emp_policy, unemp_policy\nend;\n\n###########################################################\n# Iterate Bellman map\npara = ModelParameters()\npara.agrid = LinRange(para.amin, para.amax, 18)\nW_new, U_new, emp_policy, unemp_policy = WorkerBellmanMap(para, wage_init, W_init, U_init)\n\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n# Value function iteration \nfunction SolveWorkerBellman(para::ModelParameters, wage, W0, U0, ϵ=1e-5)\n\n    @unpack nodes_A = para \n\n    W_old = W0\n    U_old = U0 \n\n    diff = 1.\n    iter = 0\n    \n    while diff > ϵ\n        iter = iter + 1\n        W_new, U_new = WorkerBellmanMap(para, wage, W_old, U_old)\n        diff = norm(U_new.(nodes_A)-U_old.(nodes_A))\n        W_old = W_new \n        U_old = U_new \n        println(\"Iteration: $(iter); Norm: $(diff)\")\n    end\n    \n    W, U, emp_policy, unemp_policy = WorkerBellmanMap(para, wage, W_old, U_old)\n\n    return W, U, emp_policy, unemp_policy\nend;\n\n###########################################################\n# Iterate Bellman map\nW_init, U_init = InitializeValues(ModelParameters());\nwage_init = InitializeWage(ModelParameters());\npara = ModelParameters()\npara.agrid = LinRange(para.amin, para.amax, 100)\npara.B = 0.0\nW_new, U_new, emp_policy, unemp_policy = SolveWorkerBellman(para, \n                                                            wage_init, \n                                                            W_init, \n                                                            U_init);\n\nplot(a -> U_new(a), LinRange(-6.0,120.0,5000))\n\nU_new(0)\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n###########################################################\n# \n\nusing Profile \n\n@profile InitializeValues(ModelParameters())\nProfile.print()\n", "meta": {"hexsha": "7485c12f97d66700c80e21244786e0cc8a7c4203", "size": 14565, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "bils_chang_kim_2011/ss_equilibrium_interpolated.jl", "max_stars_repo_name": "gionikola/unemployment_modeling", "max_stars_repo_head_hexsha": "9349950d08223ee4efab3985562c72c52ba17b6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-10T05:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T05:30:52.000Z", "max_issues_repo_path": "bils_chang_kim_2011/ss_equilibrium_interpolated.jl", "max_issues_repo_name": "gionikola/unemployment_modeling", "max_issues_repo_head_hexsha": "9349950d08223ee4efab3985562c72c52ba17b6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bils_chang_kim_2011/ss_equilibrium_interpolated.jl", "max_forks_repo_name": "gionikola/unemployment_modeling", "max_forks_repo_head_hexsha": "9349950d08223ee4efab3985562c72c52ba17b6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4635568513, "max_line_length": 154, "alphanum_fraction": 0.3283213182, "num_tokens": 2523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.75021671784964}}
{"text": "using LinearAlgebra\n\nfunction Cn(v, n::Integer)\n    θ = 2*π / n\n    return rotation_matrix(v, θ)\nend\n\n\"\"\"\n    Molecules.rotation_matrix(v, θ::AbstractFloat)\n\nReturns a rotation matrix by θ about a rotation axis v\n\"\"\"\nfunction rotation_matrix(V, θ::AbstractFloat)\n    cosθ = cos(θ)\n    sinθ = sin(θ)\n    v = normalize(V)\n    a = [1,2,3]\n    O = zeros(eltype(v), (3,3))\n    O .+= 1 - cosθ\n    for i = 1:3, j = 1:3\n        if i == j\n            O[i,i] *= v[i]^2\n            O[i,i] += cosθ\n        else\n            O[i,j] *= v[i]*v[j]\n            b = [i,j]\n            C = [i for i in a if i ∉ b][1]\n            if i < j\n                O[i,j] += (-1)^(i+j) * v[C]*sinθ\n            else\n                O[i,j] += (-1)^(i+j-1) * v[C]*sinθ\n            end\n        end\n    end\n    return O\nend\n\nfunction rotation_matrixd(v, θ::AbstractFloat)\n    r = deg2rad(θ)\n    return rotation_matrix(v, r)\nend\n\n\"\"\"\n    Molecules.reflection_matrix(v::Vector)\n\nReturns a reflection matrix through the plane with normal vector v\n\"\"\"\nfunction reflection_matrix(V)\n    O = zeros(eltype(V), (3,3))\n    v = normalize(V)\n    for i = 1:3, j = i:3\n        if i == j\n            O[i,i] = 1 - 2*v[i]^2\n        else\n            O[i,j] = -2 * v[i] * v[j]\n            O[j,i] = O[i,j]\n        end\n    end\n    return O\nend\n\nfunction σ(v)\n    return reflection_matrix(v)\nend\n\n\"\"\"\n    Molecules.Sn(v::Vector, n::int)\n\nReturns Sn improper rotation about vector v\n\"\"\"    \nfunction Sn(v, n)\n    return Cn(v, n) * σ(v)\nend\n\n\"\"\"\n    Molecules.inversion_matrix()\n\nReturns a diagonal matrix with -1 along the diagonal\n\"\"\"\nfunction inversion_matrix()\n    a = zeros((3,3))\n    for i = 1:3\n        a[i,i] = -1\n    end    \n    return a\nend\n\nfunction i()\n    return inversion_matrix()\nend\n    \n", "meta": {"hexsha": "ff50379d013935ffc6626718cb0c09fd9d466fa2", "size": 1744, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Transformations.jl", "max_stars_repo_name": "sgoodlett/Symmetry.jl", "max_stars_repo_head_hexsha": "666e5be97a787327f8d9f72dbb3a3cd2fb6cf619", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Transformations.jl", "max_issues_repo_name": "sgoodlett/Symmetry.jl", "max_issues_repo_head_hexsha": "666e5be97a787327f8d9f72dbb3a3cd2fb6cf619", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Transformations.jl", "max_forks_repo_name": "sgoodlett/Symmetry.jl", "max_forks_repo_head_hexsha": "666e5be97a787327f8d9f72dbb3a3cd2fb6cf619", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9565217391, "max_line_length": 66, "alphanum_fraction": 0.5137614679, "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7502167151590187}}
{"text": "include(\"getdigit_n.jl\")\ninclude(\"myprintf.jl\")\nusing Printf\nusing .GetDigit_n\nusing .MyPrintf\n\nconst DIGIT = 100\nconst MAXN = 500\n\nfunction viete(n)\n    numerator = sqrt(BigFloat(2))\n    result = BigFloat(1)\n    \n    for i = 1:n\n        result *= (numerator / BigFloat(2))\n        numerator = sqrt(BigFloat(2) + numerator)\n    end\n\n    return BigFloat(2) / result\nend\n\nfunction main()\n    n = GetDigit_n.getn(viete, MAXN, DIGIT, true)\n    precision = GetDigit_n.getdigit(viete, n, DIGIT, true)\n    precision = GetDigit_n.getdigit_2(viete, n, DIGIT, precision)\n\n    setprecision(precision)\n    MyPrintf.myprintf(\"π（計算値） = \", DIGIT, viete(n))\n    MyPrintf.myprintf(\"π（厳密値） = \", DIGIT, BigFloat(π))\n    @printf(\"n = %d, 計算%d桁で、%d桁求まりました\\n\", n, precision, DIGIT)\nend\n\nmain()\n", "meta": {"hexsha": "1b6f39caea4a88a9dcbf12c6a05572def9f960eb", "size": 772, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "viete.jl", "max_stars_repo_name": "dc1394/pi_julia", "max_stars_repo_head_hexsha": "a097705dab169aea82b8639638fded92cef32bbe", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "viete.jl", "max_issues_repo_name": "dc1394/pi_julia", "max_issues_repo_head_hexsha": "a097705dab169aea82b8639638fded92cef32bbe", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "viete.jl", "max_forks_repo_name": "dc1394/pi_julia", "max_forks_repo_head_hexsha": "a097705dab169aea82b8639638fded92cef32bbe", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7058823529, "max_line_length": 65, "alphanum_fraction": 0.6541450777, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7502167093014027}}
{"text": "using StanSample, MCMCChains, CSV\n\ndf = filter(row -> row[:age] >= 18, \n  CSV.read(joinpath(@__DIR__, \"..\", \"..\", \"data\", \"Howell1.csv\"), DataFrame))\ndf[!, :weight_s] = (df[!, :weight] .- mean(df[!, :weight])) / std(df[!, :weight]);\ndf[!, :weight_s2] = df[!, :weight_s] .^ 2;\n\n# Define the Stan language model\n\nm4_5s = \"\ndata{\n    int N;\n    real height[N];\n    real weight_s2[N];\n    real weight_s[N];\n}\nparameters{\n    real a;\n    real b1;\n    real b2;\n    real sigma;\n}\nmodel{\n    vector[N] mu;\n    sigma ~ uniform( 0 , 50 );\n    b2 ~ normal( 0 , 10 );\n    b1 ~ normal( 0 , 10 );\n    a ~ normal( 178 , 100 );\n    for ( i in 1:N ) {\n        mu[i] = a + b1 * weight_s[i] + b2 * weight_s2[i];\n    }\n    height ~ normal( mu , sigma );\n}\n\";\n\n# Define the Stanmodel and set the output format to :mcmcchains.\n\nm_4_5s = SampleModel(\"m4.5s\", m4_5s);\n\n# Input data for cmdstan\n\nm4_5_data = Dict(\"N\" => size(df, 1), \"height\" => df[!, :height],\n\"weight_s\" => df[!, :weight_s], \"weight_s2\" => df[!, :weight_s2]);\n\n# Sample using cmdstan\n\nrc= stan_sample(m_4_5s, data=m4_5_data);\n\n# Describe the draws\nif success(rc)\n  chn = read_samples(m_4_5s; output_format=:mcmcchains)\n  #chn = set_names(chn, Dict(\"mu\" => \"μ\", \"sigma\" => \"σ\"))\n  describe(chn)\nend", "meta": {"hexsha": "e2c0e7513021cdea34cf8f4cbe0bd35819fef47b", "size": 1240, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/04/m4.5s.jl", "max_stars_repo_name": "statisticalrethinking/StatisticalRethinkingStan.jl", "max_stars_repo_head_hexsha": "cbb7e3cf8547262b0e2b980f3f002937616e6b19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-03-08T16:01:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T08:09:28.000Z", "max_issues_repo_path": "scripts/04/m4.5s.jl", "max_issues_repo_name": "statisticalrethinking/StatisticalRethinkingStan.jl", "max_issues_repo_head_hexsha": "cbb7e3cf8547262b0e2b980f3f002937616e6b19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2019-08-16T00:01:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-03T11:38:28.000Z", "max_forks_repo_path": "scripts/04/m4.5s.jl", "max_forks_repo_name": "statisticalrethinking/StatisticalRethinkingStan.jl", "max_forks_repo_head_hexsha": "cbb7e3cf8547262b0e2b980f3f002937616e6b19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.962962963, "max_line_length": 82, "alphanum_fraction": 0.5790322581, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087926320944, "lm_q2_score": 0.8080672135527631, "lm_q1q2_score": 0.7502167061001016}}
{"text": "function curve_fit(model::Function, xpts, ydata, p0)\n\t# assumes model(xpts, params...) = ydata + noise\n\t# minimizes F(p) = sum(ydata - f(xdata)).^2 using leastsq()\n\t# returns p, f(p), g(p) where\n\t#   p - best fit parameters\n\t#   f(p) - vector of residuals\n\t#   g(p) - estimated Jacobian at p\n\n\t# construct the cost function\n\tf(p) = model(xpts, p) - ydata\n\t\n\t# construct Jacobian function\n\tg = Calculus.jacobian(f)\n\n\tresults = levenberg_marquardt(f, g, p0)\n\tp = results.minimum\n\treturn p, f(p), g(p)\nend\n\nestimate_errors(p, residuals, J) = estimate_errors(p, residuals, J, .95)\n\nfunction estimate_errors(p, residuals, J, alpha)\n\t# estimate_errors(p, residuals, J, alpha) computes (1-alpha) error estimates for the parameters from leastsq\n\t#   p - parameters\n\t#   residuals - vector of residuals\n\t#   J - Jacobian\n\t#   alpha - compute alpha percent confidence interval, (e.g. alpha=0.95 for 95% CI)\n\n\t# mean square error is: standard square error / degrees of freedom\n\tn, p = size(J)\n\tmse = sse(residuals)/(n-p)\n\n\t# compute the covariance matrix from the QR decomposition\n\tQ,R = qr(J)\n\tRinv = inv(R)\n\tcovar = Rinv*Rinv*mse\n\n\t# then the standard errors are given by the sqrt of the diagonal\n\tstd_error = sqrt(diag(covar))\n\n\t# scale by quantile of the student-t distribution\n\tdist = TDist(n-p)\n\tstd_error *= quantile(dist, alpha)\nend", "meta": {"hexsha": "de5779291a7fb90d162a783244ff1fc475076120", "size": 1329, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/curve_fit.jl", "max_stars_repo_name": "aviks/Optim.jl", "max_stars_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-22T09:32:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-22T09:32:32.000Z", "max_issues_repo_path": "src/curve_fit.jl", "max_issues_repo_name": "aviks/Optim.jl", "max_issues_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/curve_fit.jl", "max_forks_repo_name": "aviks/Optim.jl", "max_forks_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2045454545, "max_line_length": 109, "alphanum_fraction": 0.6922498119, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087926320944, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.75021670180883}}
{"text": "export Descent, Momentum, AdaGrad, Adam\n\nconst ε = 1e-8\n\n\"\"\"\n    Descent(η=0.1)\nBasic gradient descent optimizer with learning rate `η`.\n\n# Parameters\n- learning rate : `η`\n\n# Example\n\n\"\"\"\nstruct Descent\n    eta::Float64\nend\n\nDescent(;η::Float64 = 0.1) = Descent(η)\n\napply!(opt::Descent, x::Array, Δ::Array) = opt.eta .* Δ\n\n\"\"\"\n    Momentum(η=0.01, α=0.9, velocity)\nMomentum gradient descent optimizer with learning rate `η` and parameter of velocity `α`.\n\n# Parameters\n- learning rate : `η`\n- parameter of velocity : `α`\n\n# Example\n\n\"\"\"\nstruct Momentum\n    eta::Float64\n    alpha::Float64\n    velocity::Dict\nend\n\nMomentum(η = 0.01, α = 0.9) = Momentum(η, α, Dict())\n\nfunction apply!(opt::Momentum, x::Array, Δ::Array)\n    η, α = opt.eta, opt.alpha\n    v = get!(() -> zero(x), opt.velocity, x)::typeof(x) #get!() function returns a view.\n    @. v = (α*v - η*Δ)\n    @. Δ = -v\nend\n\n\"\"\"\n    AdaGrad(η = 0.01)\nGradient descent optimizer with learning rate attenuation.\n\n# Parameters\n- η : initial learning rate\n\n# Examples\n\n\"\"\"\nstruct AdaGrad\n    eta::Float64\n    h::Dict\nend\n\nAdaGrad(η = 0.01) = AdaGrad(η, Dict())\n\nfunction apply!(opt::AdaGrad, x::Array, Δ::Array)\n    η = opt.eta\n    h = get!(() -> zero(x), opt.h, x)::typeof(x)\n    @. h += Δ^2\n    @. Δ *= η / (√h + ε)\n    return Δ\nend\n\n\"\"\"\n    Adam(η=0.01, β=(0.9, 0.99))\nGradient descent adaptive moment estimation optimizer.\n\n# Parameters\n- η : learning rate\n- β : Decay of momentums\n\n# Examples\n\n\"\"\"\nstruct Adam\n    eta::Float64\n    beta::Tuple{Float64, Float64}\n    recode::Dict\nend\n\nAdam(η = 0.01, β = (0.9, 0.99)) = Adam(η, β, Dict())\n\nfunction apply!(opt::Adam, x::Array, Δ::Array)\n    η, β = opt.eta, opt.beta\n    mt, vt , βp = get!(opt.recode, x) do\n        (zero(x), zero(x), Float64[β[1], β[2]])\n    end::Tuple{typeof(x),typeof(x),Vector{Float64}}\n    @. mt = β[1] * mt + (1 - β[1]) * Δ\n    @. vt = β[2] * vt + (1 - β[2]) * Δ^2\n    @. Δ =  mt / (1 - βp[1]) / (√(vt / (1 - βp[2])) + ε) * η\n    βp .= βp .* β    \n    return Δ\nend", "meta": {"hexsha": "7439b222975c21813ab79638e313575f531cb627", "size": 1989, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NeuralNetwork/Optimize/optimizers.jl", "max_stars_repo_name": "MommaWatasu/LearningHorse.jl", "max_stars_repo_head_hexsha": "f7cd74a3c2a1b09bd736844e30970b19cd3ae1d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-12-08T05:42:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T08:14:39.000Z", "max_issues_repo_path": "src/NeuralNetwork/Optimize/optimizers.jl", "max_issues_repo_name": "MommaWatasu/LearningHorse.jl", "max_issues_repo_head_hexsha": "f7cd74a3c2a1b09bd736844e30970b19cd3ae1d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-12T12:32:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-12T12:45:49.000Z", "max_forks_repo_path": "src/NeuralNetwork/Optimize/optimizers.jl", "max_forks_repo_name": "MommaWatasu/LearningHorse.jl", "max_forks_repo_head_hexsha": "f7cd74a3c2a1b09bd736844e30970b19cd3ae1d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-06T08:14:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T08:14:43.000Z", "avg_line_length": 19.3106796117, "max_line_length": 89, "alphanum_fraction": 0.5776772247, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7502167007188592}}
{"text": "# derive epsilon given K=minpts using the median\nfunction eps_Kmedian{T <: Real}(A::Matrix{T},k::Int)\n  return median(Knearest(A,k))\nend\n\n# derive epsilon given K=minpts using the mean\nfunction eps_Kmean{T <: Real}(A::Matrix{T},k::Int)\n  return mean(Knearest(A,k))\nend\n\n#derive epsilon from unit grid of region\nfunction eps_grid{T <: Real}(A::Matrix{T})\n  gd = maximum(A)/sqrt(2)\n  n = size(A,1)\n  return gd/sqrt(n)\nend\n\n#derive epsilon from random [median, .85%]\nfunction eps_randm85{T <: Real}(A::Matrix{T},k::Int)\n  i = rand(0.5:0.01:0.85)\n  return quantile(Knearest(A,k),i)\nend\n\n#derivce epsilon from quanitle at K level\nfunction eps_Q{T <: Real}(A::Matrix{T},Q::Float64,k::Int)\n  @assert 0.0 <= Q <= 1.0 \"Quantile Q must be in range [0.0, 1.0].\"\n  return quantile(Knearest(A,k),Q)\nend\n\nfunction eps_Q{T <: Real}(A::Matrix{T},Q::Vector{Float64},k::Int)\n  return quantile(Knearest(A,k),Q)\nend\n\n#= Strip all zero values and return a vector\n    of all remaining entities =#\nfunction nonZeros{T <: Real}(A::Matrix{T})\n  nnzA = countnz(A)\n  NZs = Vector{T}(nnzA)\n  count = 1\n  if nnzA > 0\n    for j=indices(A,2), i=indices(A,1)\n      Aij = A[i,j]\n      if Aij != zero(T)\n        NZs[count] = Aij\n        count += 1\n      end\n    end\n  end\n  return NZs\nend\n\nfunction Knearest{T <: Real}(A::Matrix{T},k::Int)\n  n = size(A,2)\n  mins = zeros(T,n)\n  for i=1:n\n    a = A[:,i]\n    mins[i] = a[sortperm(a)[k+1]]\n  end\n  return sort(mins)\nend\n\n\n", "meta": {"hexsha": "ec7b5cf2a300d6aa1b70ec30600d033373991fbd", "size": 1435, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dbscan_utils.jl", "max_stars_repo_name": "matago/EVOCLUS.jl", "max_stars_repo_head_hexsha": "c0f154ca50a975c23056f0ba931bcc108f152628", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dbscan_utils.jl", "max_issues_repo_name": "matago/EVOCLUS.jl", "max_issues_repo_head_hexsha": "c0f154ca50a975c23056f0ba931bcc108f152628", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dbscan_utils.jl", "max_forks_repo_name": "matago/EVOCLUS.jl", "max_forks_repo_head_hexsha": "c0f154ca50a975c23056f0ba931bcc108f152628", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7777777778, "max_line_length": 67, "alphanum_fraction": 0.6334494774, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7501951032878799}}
{"text": "using Distributions\nusing LinearAlgebra\nusing Random\nusing Plots\nusing EnsembleKalmanProcesses.EnsembleKalmanProcessModule\nusing EnsembleKalmanProcesses.ParameterDistributionStorage\n\n# Seed for pseudo-random number generator for reproducibility\nrng_seed = 41\nRandom.seed!(rng_seed)\n\n# Number of synthetic observations from G(u)\nn_obs = 1\n# Defining the observation noise level\nnoise_level =  1e-8   \n# Independent noise for synthetic observations       \nΓy = noise_level * Matrix(I, n_obs, n_obs) \nnoise = MvNormal(zeros(n_obs), Γy)\n\n# Loss Function (unique minimum)\nfunction G(u)\n    return [sqrt((u[1]-1)^2 + (u[2]+1)^2)]\nend\n\n# Loss Function Minimum\nu_star = [1.0, -1.0]\ny_obs  = G(u_star) + 0 * rand(noise) \n\n# Define Prior\nprior_distns = [Parameterized(Normal(0., sqrt(1))),\n                Parameterized(Normal(-0., sqrt(1)))]\nconstraints = [[no_constraint()], [no_constraint()]]\nprior_names = [\"u1\", \"u2\"]\nprior = ParameterDistribution(prior_distns, constraints, prior_names)\nprior_mean = get_mean(prior)\nprior_cov = get_cov(prior)\n\n# Calibrate\nN_ens = 50  # number of ensemble members\nN_iter = 20 # number of EKI iterations\ninitial_ensemble = EnsembleKalmanProcessModule.construct_initial_ensemble(prior, N_ens;\n                                                rng_seed=rng_seed)\n\nekiobj = EnsembleKalmanProcessModule.EnsembleKalmanProcess(initial_ensemble,\n                    y_obs, Γy, Inversion())\n#\nfor i in 1:N_iter\n    params_i = get_u_final(ekiobj)\n    g_ens = hcat([G(params_i[:,i]) for i in 1:N_ens]...)\n    EnsembleKalmanProcessModule.update_ensemble!(ekiobj, g_ens)\nend\n\nu_init = get_u_prior(ekiobj)\n\nfor i in 1:N_iter\n    u_i = get_u(ekiobj,i)\n    p = plot(u_i[1,:], u_i[2,:], seriestype=:scatter, xlims = extrema(u_init[1,:]), ylims = extrema(u_init[2,:]))\n    plot!([u_star[1]], xaxis=\"u1\", yaxis=\"u2\", seriestype=\"vline\",\n        linestyle=:dash, linecolor=:red, label = false,\n        title = \"EKI iteration = \" * string(i)\n        )\n    plot!([u_star[2]], seriestype=\"hline\", linestyle=:dash, linecolor=:red, label = \"optimum\")\n    display(p)\n    sleep(0.1)\nend\n\n##\nrng_seed = 10 # 10 converges to one minima 100 converges to the other\n\n# Loss Function (two minima)\nfunction G(u)\n    return [abs((u[1]-1)*(u[1]+1))^2 + (u[2]+1)^2]\nend\n\n# Loss Function Minimum\nu_star1 = [1.0, -1.0]\nu_star2 = [-1.0, -1.0]\nG(u_star1)[1] == G(u_star2)[1]\ny_obs  = [0.0]\n\n# Define Prior\nprior_distns = [Parameterized(Normal(0., sqrt(2))),\n                Parameterized(Normal(-0., sqrt(2)))]\nconstraints = [[no_constraint()], [no_constraint()]]\nprior_names = [\"u1\", \"u2\"]\nprior = ParameterDistribution(prior_distns, constraints, prior_names)\nprior_mean = get_mean(prior)\nprior_cov = get_cov(prior)\n\n# Calibrate\nN_ens = 50  # number of ensemble members\nN_iter = 40 # number of EKI iterations\ninitial_ensemble = EnsembleKalmanProcessModule.construct_initial_ensemble(prior, N_ens;\n                                                rng_seed=rng_seed)\n\nekiobj = EnsembleKalmanProcessModule.EnsembleKalmanProcess(initial_ensemble,\n                    y_obs, Γy, Inversion())\n#\nfor i in 1:N_iter\n    params_i = get_u_final(ekiobj)\n    g_ens = hcat([G(params_i[:,i]) for i in 1:N_ens]...)\n    EnsembleKalmanProcessModule.update_ensemble!(ekiobj, g_ens)\nend\n\nu_init = get_u_prior(ekiobj)\nfor i in 1:N_iter\n    u_i = get_u(ekiobj,i)\n    p = plot(u_i[1,:], u_i[2,:], seriestype=:scatter, xlims = (-2,2), ylims = (-2,2))\n    plot!([1], xaxis=\"u1\", yaxis=\"u2\", seriestype=\"vline\",\n        linestyle=:dash, linecolor=:red, label = false,\n        title = \"EKI iteration = \" * string(i)\n        )\n    plot!([-1], seriestype=\"hline\", linestyle=:dash, linecolor=:red, label = \"optima 1\")\n\n    plot!([-1], xaxis=\"u1\", yaxis=\"u2\", seriestype=\"vline\",\n        linestyle=:dash, linecolor=:green, label = false,\n        title = \"EKI iteration = \" * string(i)\n        )\n    plot!([-1], seriestype=\"hline\", linestyle=:dash, linecolor=:green, label = \"optima 2\")\n    display(p)\n    sleep(0.1)\nend\n", "meta": {"hexsha": "1c20fd256d7c647a2b4cb9a118a3d5f531eff9ec", "size": 3975, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/LossMinimization/loss_minimization.jl", "max_stars_repo_name": "szy21/EnsembleKalmanProcesses.jl", "max_stars_repo_head_hexsha": "48535b8fd199da8094df4b26ec928115d60d4564", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/LossMinimization/loss_minimization.jl", "max_issues_repo_name": "szy21/EnsembleKalmanProcesses.jl", "max_issues_repo_head_hexsha": "48535b8fd199da8094df4b26ec928115d60d4564", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-06-25T04:20:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-07T21:51:30.000Z", "max_forks_repo_path": "examples/LossMinimization/loss_minimization.jl", "max_forks_repo_name": "szy21/EnsembleKalmanProcesses.jl", "max_forks_repo_head_hexsha": "48535b8fd199da8094df4b26ec928115d60d4564", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-07T03:50:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T23:19:14.000Z", "avg_line_length": 32.3170731707, "max_line_length": 113, "alphanum_fraction": 0.6623899371, "num_tokens": 1207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7501950993424583}}
{"text": "# # Fractional Maxwell\n#md # [![](https://mybinder.org/badge_logo.svg)](@__BINDER_ROOT_URL__/notebooks/model_maxwell.ipynb)\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/notebooks/model_maxwell.ipynb)\n\nusing RHEOS\n## include a helper function for plotting\ninclude(\"assets/plothelper.jl\");\n#-\n\nFract_Maxwell\n\n# #### Constitutive Equation\n# ```math\n# \\sigma(t) + \\frac{c_\\alpha}{c_\\beta} \\frac{d^{\\alpha-\\beta} \\sigma(t)}{dt^{\\alpha-\\beta}}= c_{\\alpha} \\frac{d^\\alpha \\epsilon(t)}{dt^\\alpha}\n# ```\n\n# ```math\n# \\text{for}\\; \\ 0 \\leq \\beta \\leq \\alpha \\leq 1\n# ```\n\n# #### Relaxation Modulus\n# ```math\n# G(t) = c_\\beta t^{-\\beta} E_{\\alpha-\\beta,1-\\beta}\\left(-\\frac{c_\\beta}{c_\\alpha} t^{\\alpha-\\beta}\\right)\n# ```\n\n# #### Creep Modulus\n# ```math\n# J(t) = \\frac{1}{c_\\alpha \\Gamma(1+\\alpha)}t^\\alpha+\\frac{1}{c_\\beta \\Gamma(1+\\beta)}t^\\beta\n# ```\n\n# #### Storage Modulus\n# ```math\n# G^{\\prime}(\\omega) = \\frac{\\left(c_\\beta \\omega^\\beta\\right)^2 \\cdot c_\\alpha \\omega^\\alpha \\cos(\\alpha \\frac{\\pi}{2}) + \\left(c_\\alpha \\omega^\\alpha\\right)^2 \\cdot c_\\beta \\omega^\\beta \\cos(\\beta \\frac{\\pi}{2})}{\\left(c_\\alpha \\omega^\\alpha\\right)^2+\\left(c_\\beta \\omega^\\beta\\right)^2+2c_\\alpha \\omega^\\alpha \\cdot c_\\beta \\omega^\\beta \\cos((\\alpha-\\beta)\\frac{\\pi}{2})}\n# ```\n\n# #### Loss Modulus\n# ```math\n# G^{\\prime\\prime}(\\omega) = \\frac{\\left(c_\\beta \\omega^\\beta\\right)^2 \\cdot c_\\alpha \\omega^\\alpha \\sin(\\alpha \\frac{\\pi}{2}) + \\left(c_\\alpha \\omega^\\alpha\\right)^2 \\cdot c_\\beta \\omega^\\beta \\sin(\\beta \\frac{\\pi}{2})}{\\left(c_\\alpha \\omega^\\alpha\\right)^2+\\left(c_\\beta \\omega^\\beta\\right)^2+2c_\\alpha \\omega^\\alpha \\cdot c_\\beta \\omega^\\beta \\cos((\\alpha-\\beta)\\frac{\\pi}{2})}\n# ```\n\n# # Fractional (Spring) Maxwell\n\nFractS_Maxwell\n#-\n\nmodels = Vector{RheoModel}()\n\n## plot moduli for varying α\nfor alpha in [0.1, 0.3, 0.5, 0.7, 0.9]\n    \n    push!(models, RheoModel(FractS_Maxwell, (cₐ = 1.0, a = alpha, k = 1.0)))\n \nend\n\nplotmodel(models)\n\n# # Fraction (Dashpot) Maxwell\n\nFractD_Maxwell\n#-\n\nmodels = Vector{RheoModel}()\n\n## plot moduli for varying β\nfor beta in [0.1, 0.3, 0.5, 0.7, 0.9]\n    \n    push!(models, RheoModel(FractD_Maxwell, (η = 10, cᵦ= 1.0, β = beta)))\n \nend\n\nplotmodel(models, ymaxG = 2.0)\n\n# # Maxwell\n\nMaxwell\n#-\n\nmodels = Vector{RheoModel}()\n\n## plot moduli for varying k\nfor k in [5.0, 10.0, 20.0]\n    \n    push!(models, RheoModel(Maxwell, (η = 10, k = k)))\n \nend\n\nplotmodel(models)", "meta": {"hexsha": "924c627019636e2920cbb2e672d85f7e2c442883", "size": 2442, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/model_maxwell.jl", "max_stars_repo_name": "moustachio-belvedere/RHEOS.jl", "max_stars_repo_head_hexsha": "b0dc226d09b941ae39fe329b566fe2e39fd9a8d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-08-08T16:01:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T11:02:00.000Z", "max_issues_repo_path": "docs/src/model_maxwell.jl", "max_issues_repo_name": "rheos-cambridge/RHEOS.jl", "max_issues_repo_head_hexsha": "b0dc226d09b941ae39fe329b566fe2e39fd9a8d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122, "max_issues_repo_issues_event_min_datetime": "2018-08-10T08:55:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-15T22:12:03.000Z", "max_forks_repo_path": "docs/src/model_maxwell.jl", "max_forks_repo_name": "rheos-cambridge/RHEOS.jl", "max_forks_repo_head_hexsha": "b0dc226d09b941ae39fe329b566fe2e39fd9a8d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-06-19T12:00:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T12:24:54.000Z", "avg_line_length": 28.0689655172, "max_line_length": 380, "alphanum_fraction": 0.6318591319, "num_tokens": 926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7501950934693179}}
{"text": "# This file is a part of RunStatistics.jl, licensed under the MIT License (MIT).\n\nexport squares_cdf_approx, squares_pvalue_approx\n\n\"\"\"\n    IntegrandData\n\nRepresent the parameters needed for the 1D numerical integration performed in `Delta()`.\n\n`T_obs` is the value for the Squares statistic observed in the data, `Nl` the left-hand length and \n`Nr` the right-hand length of a boundary spanning run, as defined in section II.A. in\n\nFrederik Beaujean and Allen Caldwell. *Is the bump significant? An axion-search example*\n\nhttps://arxiv.org/abs/1710.06642\n\"\"\"\nmutable struct IntegrandData\n    T_obs::Float64\n    Nl::Int\n    Nr::Int\nend\n\n\"\"\"\n    h(chisq::Real, N::Integer)\n\nCompute the probability density h(χ2 | Nr) for the right-hand side of a boundary spanning \nrun to be above expectation; \nas explained in section II.A. in the paper below.\n\nCalculate it as the sum of probability densities for runs of different length times the χ2 \n    probability for that number of degrees of freedom.\n\nImplements the term defined in equation (8) in \n\nFrederik Beaujean and Allen Caldwell. *Is the bump significant? An axion-search example*\n\nhttps://arxiv.org/abs/1710.06642\n\"\"\"\nfunction h(chisq::Real, N::Integer)\n    res = 0\n    weight = 0.5\n\n    for i = 1:N\n        if (i < N)\n            weight *= 0.5\n        end\n        res += weight * pdf(Chisq(i), chisq)\n    end\n\n    return res\nend\n\n\"\"\"\n    H(a::Real, b::Real, N::Integer)\n\nCompute the cumulative of `h()` as defined in section II.A. in\n\nFrederik Beaujean and Allen Caldwell. *Is the bump significant? An axion-search example*\n\nhttps://arxiv.org/abs/1710.06642\n\"\"\"\nfunction H(a::Real, b::Real, N::Integer)\n\n    res = 0\n    weight = 0.5\n\n    for i = 1:N\n        if (i < N)\n            weight *= 0.5\n        end\n\n        res += weight * (cdf(Chisq(i), b) - cdf(Chisq(i), a))\n    end\n\n    return res\nend\n\n\"\"\"\n    (integrand::IntegrandData)(x::Real)\n\nCompute the integrand in the Δ(T_obs | N_l, N_r) term defined in equation (13) in \n\nFrederik Beaujean and Allen Caldwell. *Is the bump significant? An axion-search example*\n\nhttps://arxiv.org/abs/1710.06642\n\"\"\"\nfunction (integrand::IntegrandData)(x::Real)\n    return h(x, integrand.Nl) * H(integrand.T_obs - x, integrand.T_obs, integrand.Nr)  \nend\n \n\"\"\"\n    Delta(T_obs::Real, Nl::Integer, Nr::Integer, epsrel::Real, epsabs::Real)\n\nCompute the Δ(T_obs | N_l, N_r) term defined in equation (13) in \n\nFrederik Beaujean and Allen Caldwell. *Is the bump significant? An axion-search example*\n\nhttps://arxiv.org/abs/1710.06642\n\nThe calculation involves a 1D numerical integration using the `quadgk()` function with the \nrelative and absolute target precision `epsrel` and `epsabs`. If not specified, the default \nvalues of `quadgk()` are used.\nSee https://juliamath.github.io/QuadGK.jl/stable/ for documentation.\n\"\"\"\nfunction Delta(T_obs::Real, Nl::Integer, Nr::Integer, epsrel::Nothing = nothing, epsabs::Real = nothing)\n\n    F = IntegrandData(T_obs, Nl, Nr)\n    return quadgk(F, 0, T_obs, rtol = epsrel, atol = epsabs, order = 10)\nend\n\n\"\"\"\nsquares_cdf_approx(T_obs::Real, L::Integer, [epsp::Real])\n\nCompute an approximation of P(T < `T_obs` | `L = n * N`), the value of the cumulative distribution \nfunction for the Squares test statistic at `T_obs`, \nthe value of the Squares statistic observed in the data. \nThe total number of datapoints is `L = n * N`, if not defined otherwise, the function chooses the default values `N = 80` and `n = L / N`.\n\nThe accuracy's lower bound is `10^(-14)`, a desired accuracy up to this boundary can be specified with the optional `epsp` argument.\nSee documentation on Accuracy.\n\nThis function implements equation (17) from:\n\nFrederik Beaujean and Allen Caldwell. *Is the bump significant? An axion-search example*\n\nhttps://arxiv.org/abs/1710.06642\n  \n\"\"\"\nfunction squares_cdf_approx(T_obs::Real, L::Integer, epsp::Real = 0)\n    N = 80\n    n = L / N\n\n    @argcheck (epsp == 0 || epsp / n >= 10^(-14)) error(\"The desired accuracy is too high. See documentation on Accuracy.\")\n\n    if epsp != 0\n\n        epsabs = (epsp / n) * 0.1\n        F = squares_cdf(T_obs, N)\n        Fn1 = (F / (1 + Delta(T_obs, N, N, nothing, epsabs)[1]))^(n - 1)\n        return F * Fn1\n    end\n        \n    F = squares_cdf(T_obs, N)\n    Fn1 = (F / (1 + Delta(T_obs, N, N)[1]))^(n - 1)\n    return F * Fn1\nend\n\nfunction squares_cdf_approx(T_obs::Real, N::Integer, n::Real,  epsp::Real = 0)\n\n    @argcheck (epsp == 0 || epsp / n >= 10^(-14)) error(\"The desired accuracy is too high. See documentation on Accuracy.\")\n\n    if epsp != 0\n\n        epsabs = (epsp / n) * 0.1\n        F = squares_cdf(T_obs, N)\n        Fn1 = (F / (1 + Delta(T_obs, N, N, nothing, epsabs)[1]))^(n - 1)\n        return F * Fn1\n    end\n        \n    F = squares_cdf(T_obs, N)\n    Fn1 = (F / (1 + Delta(T_obs, N, N)[1]))^(n - 1)\n    return F * Fn1\nend\n\n\"\"\"\n    squares_pvalue_approx(T_obs::Real, N::Integer, n::Real, [epsrel::Real, epsabs::Real])\n\nCompute an approximation of P(T >= `T_obs` | `n * N`), the p value for the Squares test \nstatistic T being larger or equal to `T_obs`, \nthe value of the Squares statistic observed in the data. \nThe total number of datapoints is `L = n * N`, if not defined otherwise, the function chooses the default values `N = 80` and `n = L / N`.\n\nThe accuracy's lower bound is `10^(-14)`, a desired accuracy up to this boundary can be specified with the optional `epsp` argument.\nSee documentation on Accuracy.\n\nVia `squares_cdf_approx()` this function implements equation (17) from:\n\nFrederik Beaujean and Allen Caldwell. *Is the bump significant? An axion-search example*\n\nhttps://arxiv.org/abs/1710.06642\n  \n\"\"\"\nfunction squares_pvalue_approx(T_obs::Real, L::Integer,  epsp::Real = 0)\n\n    return 1 - squares_cdf_approx(T_obs, L, epsp)\nend\n\nfunction squares_pvalue_approx(T_obs::Real, N::Integer, n::Real,  epsp::Real = 0)\n\n    return 1 - squares_cdf_approx(T_obs, N, n, epsp)\nend", "meta": {"hexsha": "dbc2c2ec56313468d92eba7b765ccf3645729beb", "size": 5883, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/squares_approx.jl", "max_stars_repo_name": "fredRos/RunStatistics.jl", "max_stars_repo_head_hexsha": "58e1ea9e064476f547b0e2db259cb03d7689d1e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/squares_approx.jl", "max_issues_repo_name": "fredRos/RunStatistics.jl", "max_issues_repo_head_hexsha": "58e1ea9e064476f547b0e2db259cb03d7689d1e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/squares_approx.jl", "max_forks_repo_name": "fredRos/RunStatistics.jl", "max_forks_repo_head_hexsha": "58e1ea9e064476f547b0e2db259cb03d7689d1e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8010471204, "max_line_length": 138, "alphanum_fraction": 0.6739758627, "num_tokens": 1768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7501950933493384}}
{"text": "# different  recipes / formulas to create a gray image from a RGB image\n# see 'Seven grayscale conversion algorithms' at\n# URL: http://www.tannerhelland.com/3643/grayscale-image-algorithm-vb6/\n# and the German\n# https://de.wikipedia.org/wiki/RGB-Farbraum\n# and the English\n# https://en.wikipedia.org/wiki/CIE_1931_color_space\n# https://en.wikipedia.org/wiki/Grayscale <=> especially 'Converting color to grayscale'\n# https://en.wikipedia.org/wiki/Gamma_correction\n\n###########\n###  !!!  WATCH  !!!\n##\n## !!! Different kinds of devices, tools, applications may use different formulas !!!\n##\n\n#########\n# Methods in brief:\n#\n# General\n# The RGB-version of an Gray image has the same value for red, green and blue\n#    RGB.r = gray\n#    RGB.g = gray\n#    RGB.b = gray\n#\n# Gamma correction (sRGB is non-linear!)\n# Gamma-Korrektur (from https://de.wikipedia.org/wiki/RGB-Farbraum)\n# Y (0…1), L (0…1: 0 am Schwarzpunkt, 1 am Weißpunkt) \tBerechnung\n# Umrechnung von Luminanz L in die nichtlineare Y \tY = 1,055 · L ^ (1/2,4) - 0,055 , falls L > 0,0031306684425, sonst Y = 12,92 · L\n# Umrechnung der nichtlinearen Y in die Luminanz \tL = ((Y + 0,055) / 1,055) ^(2,4) , falls Y > 0,040448236277, sonst L = Y / 12,92\n# Lref \t80 cd/m² Gesamthelligkeit aller Primärvalenzen\n#\n# ==> According to CIE\n#   make sRGB linear, then apply Gray formula, then make value non-linear again\n#     at least with using test image \"lena_color_256\", the difference is not worth the effort.\n#\n#   BT.709 is '... used by PAL and NTSC, the rec601 luma (Y') component ...'\n#   BT.601 is '... ITU-R BT.709 standard used for HDTV developed by the ATSC uses different color coefficients ...'\n#   both applied to non-linear sRGB values directly\n#\n# Method 1\n#   Gray = (Red + Green + Blue) / 3\n#\n# Method 2\n# common in Photoshop, GIMP\n#   Gray = (Red * 0.3 + Green * 0.59 + Blue * 0.11)\n#\n# ITU-R recommendation (BT.709, specifically) which is the historical precedent.  This formula, sometimes called Luma, looks like this:\n#   Gray = (Red * 0.2126 + Green * 0.7152 + Blue * 0.0722)\n#\n# Some modern digital image and video formats use a different recommendation (BT.601), which calls for slightly different coefficients:\n#   Gray = (Red * 0.299 + Green * 0.587 + Blue * 0.114)\n#\n# Most don't care / remeber the difference\n#\n# Method 3 – Desaturation\n#   Gray = ( Max(Red, Green, Blue) + Min(Red, Green, Blue) ) / 2\n# gives flattest (least contrast) and darkest overall image until now.\n#\n# Method 4 – Decomposition\n#   Maximum decomposition:\n#   Gray = Max(Red, Green, Blue)\n#\n#   Minimum decomposition:\n#   Gray = Min(Red, Green, Blue)\n#\n# Method 5 – Single color channel\n#   Gray = Red\n#   Gray = Green\n#   Gray = Blue\n# the poorest, but simplest - often used in SSD camera models\n#\n# Method 6 – Custom # of gray shades\n#\n# Method 7 - Custom # of gray shades with dithering (in this example, horizontal error-diffusion dithering)\n#\n\n", "meta": {"hexsha": "5f2970247c971075685058cf94efcc00cc520ca2", "size": 2898, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/RGBtoGray.jl", "max_stars_repo_name": "t37w/ImageHistograms", "max_stars_repo_head_hexsha": "bb03a34e88f495eb3150931756e0bdb8f1736174", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-04-21T20:05:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-21T20:05:48.000Z", "max_issues_repo_path": "src/RGBtoGray.jl", "max_issues_repo_name": "t37w/ImageHistograms", "max_issues_repo_head_hexsha": "bb03a34e88f495eb3150931756e0bdb8f1736174", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RGBtoGray.jl", "max_forks_repo_name": "t37w/ImageHistograms", "max_forks_repo_head_hexsha": "bb03a34e88f495eb3150931756e0bdb8f1736174", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1538461538, "max_line_length": 135, "alphanum_fraction": 0.6832298137, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7501950816030578}}
{"text": "#\n# Least square solver \n#\n# author: Atsushi Sakai\n#\n\nexport solve_least_square\nexport solve_multi_objective_least_square\nexport solve_constrained_least_square\nexport solve_nonlinear_least_square_with_newton_raphson\nexport solve_nonlinear_least_square_with_gauss_newton\nexport solve_nonlinear_least_square_with_levenberg_marquardt\nexport solve_constrained_nonlinear_least_square_with_augmented_lagragian\n\neye(T::Type, n) = Diagonal{T}(I, n)\neye(n) = eye(Float64, n)\n\n\"\"\"\n\tsolve least square\n\txhat = argmin(|Ax = b|^2)\n\n\tAll are same solution \n\t- xhat = inv(A’*A)*(A’*b)\n\t- xhat = pinv(A)*b\n\t- Q,R = qr(A); xhat = inv(R)*(Q’*b)\n\t- xhat = A\\b \n\"\"\"\nfunction solve_least_square(A, b)\n\treturn A\\b\nend\n\n\"\"\"\n\tsolve constrained least_square\n\txhat = argmin(|Ax = b|^2) s.t. Cx = d\n\"\"\"\nfunction solve_least_square(A,b,C,d)\n\tm, n = size(A)\n    p, n = size(C)\n    G = A'*A  # Gram matrix\n    KKT = [2*G C'; C zeros(p,p)]  # KKT matrix\n    xzhat = KKT \\ [2*A'*b; d]\n    return xzhat[1:n,:]\nend\n\n\"\"\"\n\tsolve multi objective least square\n\txhat = argmin(λ_1|Ax = b|^2+λ_2|Ax = b|^2...)\n\"\"\"\nfunction solve_multi_objective_least_square(As, bs, lambdas)\n   k = length(lambdas);\n   Atil = vcat([sqrt(lambdas[i])*As[i] for i=1:k]...)\n   btil = vcat([sqrt(lambdas[i])*bs[i] for i=1:k]...)\n   return solve_least_square(Atil, btil)\nend\n\n\n\"\"\"\n\tsolve nonlinear least square with newton-raphson method\n\n\tThe inputs have to be length(x) == length(f(x)).\n\tIf it is not, you cant use solve_nonlinear_least_square_with_gauss_newton\n\n\txhat = argmin(|f(x)|^2)\n\"\"\"\nfunction solve_nonlinear_least_square_with_newton_raphson(\n\t\tf, Df, x1; kmax = 20, tol = 1e-6)\n\n\tx=x1\n\t@assert length(x) == length(f(x))\n\tfor k = 1:kmax\n\t\tfk = f(x)\n\t\tdx = fk / Df(x)\n\t\tif norm(dx) < tol break end;\n\t\tx = x - dx\n\tend\n\n\treturn x\nend\n\n\"\"\"\n\tsolve nonlinear least square with gauss-newton method\n\n\txhat = argmin(|f(x)|^2)\n\"\"\"\nfunction solve_nonlinear_least_square_with_gauss_newton(\n\t\tf, Df, x0;\n\t   \tkmax = 20, tol = 1e-6)\n\tx=x0\n   \tobj = zeros(0,1)\n   \tresiduals = zeros(0,1)\n\tfor k=1:kmax\n\t\tfx = f(x)\n\t\tdfx = Df(x)\n\t\tobj = [obj; norm(fx)^2]\n\t\tres = norm(2*dfx'*fx)\n\t\tresiduals = [residuals; res]\n\t\tif res < tol break end;\n\n\t\ttmp = (dfx'*fx)\n\t\tif isa(tmp, Array)\n\t\t\tdx = (dfx'*dfx) \\ tmp\n\t\telse\n\t\t\tdx = (dfx'*dfx) \\ [tmp]\n\t\tend\n\n\t\tx = x - dx\n\tend\n\n\treturn x, Dict([ (\"objectives\", obj), (\"residuals\", residuals)])\nend\n\n\n\"\"\"\n\tsolve nonlinear least square with levenberg marquardt\n\n\txhat = argmin(|f(x)|^2)\n\"\"\"\nfunction solve_nonlinear_least_square_with_levenberg_marquardt(\n\t\tf, Df, x0, lambda0;\n\t   \tkmax = 20, tol = 1e-6, lamr_n = 0.8, lamr_p = 2.0)\n\n\tn = length(x0)\n\tx=x0\n\tlambda = lambda0\n\tobj = zeros(0,1)\n\tresiduals = zeros(0,1)\n\txhist = x0'\n\tfor k = 1:kmax\n\t\tfx = f(x)\n\t\tDfk = Df(x)\n\t\tobj = [obj; norm(fx)^2]\n\t\tres = norm(2*Dfk'*fx)\n\t\tresiduals = [residuals; res]\n\t\tif res < tol break end;\n\t\ttmp = Dfk'*fx\n\t\tif isa(tmp, Array)\n\t\t\tdx = (Dfk'*Dfk+lambda*eye(n)) \\ tmp\n\t\telse\n\t\t\t# dx = (Dfk'*Dfk+lambda*eye(n)) \\ [tmp]\n\t\t\tdx = (Dfk'*Dfk+lambda*1.0) \\ [tmp]\n\t\tend\n\t\txt = x - dx\n\t\tif norm(f(xt)) < norm(fx)\n\t\t\tlambda = lamr_n*lambda\n\t\t\tx = xt\n\t\telse\n\t\t\tlambda = lamr_p*lambda\n\t\tend\n\t\txhist = [xhist; x']\n\tend\n\n\treturn x, Dict([ (\"objectives\", obj), (\"residuals\", residuals), (\"x_history\", xhist)])\nend\n\n\n\"\"\"\nSolve constrained nonlinear least square with augmentedl lagrangian method\n\nxhat = argmin(|f(x)|^2) s.t g(x) = 0\n\n\"\"\"\nfunction solve_constrained_nonlinear_least_square_with_augmented_lagragian(\n\t\tf, Df, g, Dg, x1, lambda1;\n\t   \tkmax = 100, feas_tol = 1e-4, oc_tol = 1e-4)\n\tx=x1\n\tz = zeros(length(g(x)))\n\tmu=1.0\n\tfeas_res = [norm(g(x))]\n\toc_res = [norm(2*Df(x)'*f(x) + 2*mu*Dg(x)'*z)]\n\tlm_iters = zeros(Int64,0,1)\n\n\tfor k=1:kmax\n\t\tF(x) = [f(x); sqrt(mu)*(g(x) + z/(2*mu))]\n\t\tDF(x) = [Df(x); sqrt(mu)*Dg(x)]\n\t\tx, hist = solve_nonlinear_least_square_with_levenberg_marquardt(F, DF, x, lambda1, tol=oc_tol)\n        z = z + 2*mu*g(x)\n        feas_res = [feas_res; norm(g(x))]\n        oc_res = [oc_res; hist[\"residuals\"][end]]\n        lm_iters = [lm_iters; length(hist[\"residuals\"])]\n        if norm(g(x)) < feas_tol\n\t\t\tbreak\n\t\tend\n        mu = (norm(g(x)) < 0.25*feas_res[end-1]) ? mu : 2*mu\n    end\n\n    return x, z, Dict([ (\"lm_iterations\", lm_iters),\n         (\"feas_res\", feas_res), (\"oc_res\", oc_res)])\nend\n\n\n", "meta": {"hexsha": "8629882ca73cb26c66954457f45438548111e0bd", "size": 4261, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/least_square_solver.jl", "max_stars_repo_name": "AtsushiSakai/ArgMin.jl", "max_stars_repo_head_hexsha": "8584acd49640ac775f5ac5e47860a0d2d4953d54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/least_square_solver.jl", "max_issues_repo_name": "AtsushiSakai/ArgMin.jl", "max_issues_repo_head_hexsha": "8584acd49640ac775f5ac5e47860a0d2d4953d54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/least_square_solver.jl", "max_forks_repo_name": "AtsushiSakai/ArgMin.jl", "max_forks_repo_head_hexsha": "8584acd49640ac775f5ac5e47860a0d2d4953d54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3089005236, "max_line_length": 96, "alphanum_fraction": 0.632011265, "num_tokens": 1568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7501836889604382}}
{"text": "export selu\n\ndoc\"\"\"\n    selu(x::Var)\n\nScaled Exponential Linear Unit.\n\n```math\nf(x) = \\lambda\n\\begin{cases}\nx & x > 0 \\\\\n\\alpha e^{x}-\\alpha & x\\leq0\n\\end{cases}\n```\nwhere ``\\lambda=1.0507`` and ``\\alpha=1.6733``.\n\n# References\nKlambauer et al., [\"Self-Normalizing Neural Networks\"](https://arxiv.org/abs/1706.02515), NIPS 2017.\n\"\"\"\nselu(x::Var) = Var(selu.(x.data), (selu,x))\nselu(x::T) where T = x > 0 ? T(1.0507)*x : T(1.0507)*T(1.6733)*(exp(x)-1)\nselu(x::Node) = Node(selu, x)\n\nfunction addgrad!(y::Var, ::typeof(selu), x::Var)\n    isvoid(x.grad) || ∇selu!(y.data, y.grad, x.data, x.grad)\nend\n\nfunction ∇selu!(y::Array{T}, gy::Array{T}, x::Array{T}, gx::Array{T}) where T\n    alpha = T(1.6733)\n    lambda = T(1.0507)\n    @inbounds for i = 1:length(x)\n        gx[i] +=  x[i] > 0 ? gy[i]*lambda : gy[i]*(y[i]+lambda*alpha)\n    end\nend\n", "meta": {"hexsha": "e74f9a3b015d2bbd971689a33e894d108945ff1b", "size": 837, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/activation/selu.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Merlin.jl-80f3d04f-b880-5e6d-8e06-6a7e799169ac", "max_stars_repo_head_hexsha": "5c13eafab1df4dc4a73e7bdc85d45d3e4990fd80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 166, "max_stars_repo_stars_event_min_datetime": "2015-12-19T08:49:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-10T08:11:27.000Z", "max_issues_repo_path": "src/functions/activation/selu.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Merlin.jl-80f3d04f-b880-5e6d-8e06-6a7e799169ac", "max_issues_repo_head_hexsha": "5c13eafab1df4dc4a73e7bdc85d45d3e4990fd80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2016-02-03T14:49:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:31:32.000Z", "max_forks_repo_path": "src/functions/activation/selu.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Merlin.jl-80f3d04f-b880-5e6d-8e06-6a7e799169ac", "max_forks_repo_head_hexsha": "5c13eafab1df4dc4a73e7bdc85d45d3e4990fd80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2016-01-12T14:19:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-17T14:21:37.000Z", "avg_line_length": 23.9142857143, "max_line_length": 100, "alphanum_fraction": 0.5878136201, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7501836829177525}}
{"text": "@doc raw\"\"\"\n    Direction2\n\nAn object `d` of the class [`Direction_2`](@ref) is a vector in the\ntwo-dimensional vector space ``ℝ^2`` where we forget about its length.\n\nThey can be viewed as unit vectors, although there is no normalization\ninternally, since this is error prone. Directions are used whenever the\nlength of a vector does not matter. They also characterize a set of parallel\noriented lines that have the same orientations. For example, you can ask for\nthe direction orthogonal to an oriented plane, or the direction of an\noriented line. Further, they can be used to indicate angles. The slope of a\ndirection is [`dy()`](@ref)/[`dx()`](@ref).\n\nThere is a total order on directions.\n\nWe compare the angles between the positive ``x``-axis and the directions in\ncounterclockwise order.\n\"\"\"\nDirection2\n\n\"\"\"\n    Direction2(v::Vector2)\n\nIntroduces the direction `d` of vector `v`.\n\"\"\"\nDirection2(v::Vector2)\n\n\"\"\"\n    Direction2(l::Line2)\n\nIntroduces the direction `d` of line `l`.\n\"\"\"\nDirection2(l::Line2)\n\n\"\"\"\n    Direction2(r::Ray2)\n\nIntroduces the direction `d` of ray `r`.\n\"\"\"\nDirection2(r::Ray2)\n\n\"\"\"\n    Direction2(s::Segment2)\n\nIntroduces the direction `d` of segment `s`.\n\"\"\"\nDirection2(s::Segment2)\n\n\"\"\"\n    Direction2(x::Real, y::Real)\n\nIntroduces a direction `d` passing through the origin and the point with\nCartesian coordinates ``(x, y)``.\n\"\"\"\nDirection2(x::Real, y::Real) = Direction2(convert(FT, x), convert(FT, y))\n\n@doc raw\"\"\"\n    delta(d::Direction2, i::Integer)\n\nReturns values, such that `d == [Direction2](@ref)(delta(d, 0), delta(d, 1))`.\n\n!!! info \"Precondition\"\n\n    ``0 ≤ i ≤ 1``\n\"\"\"\ndelta(d::Direction2, i::Integer)\n\n\"\"\"\n    dx(d::Direction2)\n\nReturns `delta(d, 0)`.\n\"\"\"\ndx(d::Direction2)\n\n\"\"\"\n    dy(d::Direction2)\n\nReturns `delta(d, 1)`.\n\"\"\"\ndy(d::Direction2)\n\n\"\"\"\n    counterclockwise_in_between(d::Direction2, d1::Direction2, d2::Direction2)\n\nReturns `true`, iff `d` is not equal to `d1`, and while rotating\ncounterclockwise starting at `d1`, `d` is reached strictly before `d2` is\nreached.\n\nNote that `true` is returned if `d1 == d2`, unless also `d == d1`.\n\"\"\"\ncounterclockwise_in_between(d::Direction2, d1::Direction2, d2::Direction2)\n\n\"\"\"\n    -(d::Direction2)\n\nThe direction opposite to `d`.\n\"\"\"\n-(d::Direction2)\n\n\"\"\"\n    vector(d::Direction2)\n\nReturns a vector that has the same direction as `d`.\n\"\"\"\nvector(d::Direction2)\n\n\"\"\"\n    transform(d::Direction2, t::AffTransformation2)\n\nReturns the direction obtained by applying `t` on `d`.\n\"\"\"\ntransform(d::Direction2, t::AffTransformation2)\n", "meta": {"hexsha": "7c68ff8dbcc9cbb239c4aea84c04607ed71cab1f", "size": 2530, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernel/direction_2.jl", "max_stars_repo_name": "rgcv/CGAL.jl", "max_stars_repo_head_hexsha": "a3d55993938f271f3243fb86cb59f2e481bac7d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-07-17T22:06:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T08:32:54.000Z", "max_issues_repo_path": "src/kernel/direction_2.jl", "max_issues_repo_name": "rgcv/CGAL.jl", "max_issues_repo_head_hexsha": "a3d55993938f271f3243fb86cb59f2e481bac7d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-10-31T19:37:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T20:04:37.000Z", "max_forks_repo_path": "src/kernel/direction_2.jl", "max_forks_repo_name": "rgcv/CGAL.jl", "max_forks_repo_head_hexsha": "a3d55993938f271f3243fb86cb59f2e481bac7d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-16T13:55:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T18:07:26.000Z", "avg_line_length": 22.1929824561, "max_line_length": 78, "alphanum_fraction": 0.6873517787, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088002, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7501836809035238}}
{"text": "using OrdinaryDiffEq\r\nusing ModelingToolkit\r\nusing DataDrivenDiffEq\r\nusing LinearAlgebra, DiffEqSensitivity, Optim\r\nusing DiffEqFlux, Flux\r\nusing Plots\r\ngr()\r\n\r\nfunction triNN!(du,u,p,t,dens,cons)\r\n    # unpack rates and constants\r\n    nᵣ,nₓ,n₃ = u\r\n    k₁,k₋₁,k₂,k₋₂ = cons\r\n    mᵣ,mₗ,mₓ,A = dens\r\n    z = L(u,p)\r\n    # model\r\n    du[1] = dnᵣ = A*k₁*mᵣ*mₗ - k₋₁*nᵣ - z[1] + z[2]\r\n    du[2] = dnₓ = A*k₂*mₓ*mₗ - k₋₂*nₓ - z[3] + z[4]\r\n    du[3] = dn₃ = z[1] + z[3] - z[2] - z[4] + z[5]\r\n\r\nend\r\nfunction triNN!(du,u,p,t,dens,cons)\r\n    # unpack rates and constants\r\n    nᵣ,nₓ,n₃ = u\r\n    k₁,k₋₁,k₂,k₋₂ = cons\r\n    mᵣ,mₗ,mₓ,A = dens\r\n    z = L(u,p)\r\n    # model\r\n    du[1] = dnᵣ = A*k₁*mᵣ*mₗ - k₋₁*nᵣ + z[1] - z[2]\r\n    du[2] = dnₓ = A*k₂*mₓ*mₗ - k₋₂*nₓ + z[3] - z[4]\r\n    du[3] = dn₃ = z[5] - z[6]\r\n\r\nend\r\n\r\nL = FastChain(FastDense(3, 50, tanh),\r\n                FastDense(50, 100, tanh),\r\n                FastDense(100, 100, tanh),\r\n                FastDense(100, 50, tanh),\r\n                FastDense(50, 6))\r\n#L = FastChain(FastDense(3, 20, tanh),FastDense(20, 20, tanh), FastDense(20, 2))\r\np = initial_params(L)\r\n\r\n# Define the experimental parameter\r\ntspan = (0.0,16.1) # A little bit longer because there are two values to save at final t?\r\nu0 = Float32[0.0,0.0,0.0]\r\n\r\n# Xₙ = n_tc1 #load data\r\nXₙ = [0.02020270731751947\r\n 0.0\r\n 0.06187540371808745\r\n 0.10536051565782635\r\n 0.083381608939051\r\n 0.19845093872383823\r\n 0.3011050927839216\r\n 0.3011050927839216\r\n 0.3566749439387324\r\n 0.38566248081198473\r\n 0.5108256237659907\r\n 0.6931471805599453\r\n 0.8209805520698303\r\n 0.7339691750802005\r\n 0.8209805520698303\r\n 0.7339691750802005]\r\n t = [0.25\r\n  0.25\r\n  0.5\r\n  0.5\r\n  1.0\r\n  1.0\r\n  2.0\r\n  2.0\r\n  4.0\r\n  4.0\r\n  6.0\r\n  6.0\r\n  8.0\r\n  8.0\r\n 16.0\r\n 16.0]\r\ndensities_tc1 = [15.0,38.0,10.0,1.0]\r\ncons_tc = [ 0.0006692541890287495,0.8662361534770547,1.169965568192585e-6,0.4]\r\n\r\nf = (du,u,p,t) -> triNN!(du,u, p,t,densities_tc1,cons_tc)\r\nprob_nn = ODEProblem(f,u0, tspan, p)\r\nsol_nn = solve(prob_nn, Tsit5(), saveat = t)\r\n\r\n# plot(solution)\r\nplot(sol_nn)\r\n# summ = reduce(vcat,sum(sol_nn,dims=1))\r\n# h = plot!(sol_nn.t,summ,linecolor=:black)\r\n\r\nfunction predict(θ)\r\n\r\n    tmp_prob = remake(prob_nn,u0=u0,p=θ)\r\n    tmp_sol =  solve(tmp_prob, VCABM(), saveat = t,\r\n                  abstol=1e-5, reltol=1e-5)\r\n                  # backsolve=true)\r\n    Σ_sol = sum(Array(tmp_sol),dims=1) # Note: this returns a row vector!\r\nend\r\n\r\nfunction loss(θ)\r\n    pred = predict(θ)\r\n    # sum(abs2, (Xₙ .- pred') .* t), pred\r\n    sum(abs2, (Xₙ .- pred')), pred\r\nend\r\n\r\n# Test\r\n@time loss(p)\r\n\r\nlosses = []\r\n\r\ncallback(θ,l,pred) = begin\r\n    push!(losses, l)\r\n    @show l\r\n    if length(losses)%50==0\r\n        println(\"Current loss after $(length(losses)) iterations: $(losses[end])\")\r\n    end\r\n    p = plot(t, pred')\r\n    scatter!(p, t, Xₙ)\r\n    display(p)\r\n    false\r\nend\r\n\r\n# First train with ADAM for better convergence\r\n@time res1 = DiffEqFlux.sciml_train(loss, p, ADAM(0.005), cb=callback, maxiters = 10)\r\n\r\n# Train with BFGS\r\nres2 = DiffEqFlux.sciml_train(loss, res1.minimizer, BFGS(initial_stepnorm=0.01),\r\n                                cb=callback, maxiters = 1000)\r\n\r\nres2 = DiffEqFlux.sciml_train(loss, res1.minimizer, NelderMead(),\r\n                                cb=callback)\r\n\r\nprintln(\"Final training loss after $(length(losses)) iterations: $(losses[end])\")\r\n\r\n# Plot the losses\r\nplot(losses, yaxis = :log, xaxis = :log, xlabel = \"Iterations\", ylabel = \"Loss\")\r\n\r\n# Plot the data and the approximation\r\nNNsolution = predict(res2.minimizer)\r\n# Trained on noisy data vs real solution\r\nplot(t, NNsolution')\r\nscatter!(t, Xₙ)\r\n", "meta": {"hexsha": "a044987b9521751de90a558c3724eb0c5420d16b", "size": 3615, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "neuralODE modeling/NNode_try1_from_chris.jl", "max_stars_repo_name": "vaglino/kinetic_modeling", "max_stars_repo_head_hexsha": "2a15f74df5844eb21d5bf47bc9014b6bf74f84e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "neuralODE modeling/NNode_try1_from_chris.jl", "max_issues_repo_name": "vaglino/kinetic_modeling", "max_issues_repo_head_hexsha": "2a15f74df5844eb21d5bf47bc9014b6bf74f84e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neuralODE modeling/NNode_try1_from_chris.jl", "max_forks_repo_name": "vaglino/kinetic_modeling", "max_forks_repo_head_hexsha": "2a15f74df5844eb21d5bf47bc9014b6bf74f84e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2797202797, "max_line_length": 90, "alphanum_fraction": 0.5980636238, "num_tokens": 1429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7501836788892952}}
{"text": "using Gnuplot\n\nx = collect(1.:100);\n\n#-----------------------------------------------------------------\nfor i in 1:10\n    @gp :gp1 \"plot sin($i*x)\"\n    @gp :gp2 \"plot sin($i*x)\"\n    @gp :gp3 \"plot sin($i*x)\"\n    sleep(0.3)\nend\nquitall()\n\n#-----------------------------------------------------------------\n@gp \"plot sin(x)\"\n@gp \"plot sin(x)\" \"pl cos(x)\"\n@gp \"plo sin(x)\" \"s cos(x)\"\n\n@gp \"plot sin(x)\" :-\n@gp :- \"plot cos(x)\"\n\n\n@gp \"plot sin(x)\" 2 xr=(-2pi,2pi) \"pause 2\" \"plot cos(4*x)\"\n\nx = range(-2pi, stop=2pi, length=100);\ny = 1.5 * sin.(0.3 .+ 0.7x) ;\nnoise = randn(length(x))./2;\ne = 0.5 * fill(1, size(x));\n\n@gp hist(noise, nbins=10)\n\n\n@gp x y\n@gp x y \"w l\"\n\nname = \"\\$MyDataSet1\"\n@gp x y name \"plot $name w l\" \"pl $name u 1:(2*\\$2) w l\"\n\n@gsp randn(Float64, 30, 50)\n@gp randn(Float64, 30, 50) \"w image\"\n@gsp x y y\n\n@gp(\"set key horizontal\", \"set grid\",\n    xrange=(-7,7), ylabel=\"Y label\",\n    x, y, \"w l t 'Real model' dt 2 lw 2 lc rgb 'red'\",\n    x, y+noise, e, \"w errorbars t 'Data'\")\n\n@gp \"f(x) = a * sin(b + c*x); a = 1; b = 1; c = 1;\"   :-\n@gp :- x y+noise e name                               :-\n@gp :- \"fit f(x) $name u 1:2:3 via a, b, c;\"          :-\n@gp :- \"set multiplot layout 2,1\"                     :-\n@gp :- \"plot $name w points\" ylab=\"Data and model\"    :-\n@gp :- \"plot $name u 1:(f(\\$1)) w lines\"              :-\n@gp :- 2 xlab=\"X label\" ylab=\"Residuals\"              :- \n@gp :- \"plot $name u 1:((f(\\$1)-\\$2) / \\$3):(1) w errorbars notit\"\n\n# Retrieve values for a, b and c\na = 0; b = 0; c = 0;\ntry\n    a = parse(Float64, exec(\"print a\"))\n    b = parse(Float64, exec(\"print b\"))\n    c = parse(Float64, exec(\"print c\"))\ncatch\nend\ngnuplot(:dry)\n@gp    :dry \"f(x) = a * sin(b + c*x); a = 1; b = 1; c = 1;\"  :-\n@gp :- :dry \"a = $a; b = $b; c = $c\"                         :-\n@gp :- :dry \"set multiplot layout 2,1\" ylab=\"Data and model\" :-\nname = \"\\$MyDataSet1\"\n@gp :- :dry x y+noise e name                                 :-\n@gp :- :dry \"plot $name w points\"                            :-\n@gp :- :dry \"plot $name u 1:(f(\\$1)) w lines\"                :-\n@gp :- :dry 2 xlab=\"X label\" ylab=\"Residuals\"                :- \n@gp :- :dry \"plot $name u 1:((f(\\$1)-\\$2) / \\$3):(1) w errorbars notit\" :-\n@gp :- :dry\nsave(\"test.gp\")        # write on file test.gp\nquitall()\nexec(\"load 'test.gp'\") # load file test.gp\n\n#-----------------------------------------------------------------\n@gp(\"\"\"\n        approx_1(x) = x - x**3/6\n        approx_2(x) = x - x**3/6 + x**5/120\n        approx_3(x) = x - x**3/6 + x**5/120 - x**7/5040\n        label1 = \"x - {x^3}/3!\"\n        label2 = \"x - {x^3}/3! + {x^5}/5!\"\n        label3 = \"x - {x^3}/3! + {x^5}/5! - {x^7}/7!\"\n        #\n        set termoption enhanced\n        save_encoding = GPVAL_ENCODING\n        set encoding utf8\n        #\n        set title \"Polynomial approximation of sin(x)\"\n        set key Left center top reverse\n        set xrange [ -3.2 : 3.2 ]\n        set xtics (\"-π\" -pi, \"-π/2\" -pi/2, 0, \"π/2\" pi/2, \"π\" pi)\n        set format y \"%.1f\"\n        set samples 500\n        set style fill solid 0.4 noborder\"\"\",\n    \"plot '+' using 1:(sin(\\$1)):(approx_1(\\$1)) with filledcurve title label1 lt 3\",\n    \"plot '+' using 1:(sin(\\$1)):(approx_2(\\$1)) with filledcurve title label2 lt 2\",\n    \"plot '+' using 1:(sin(\\$1)):(approx_3(\\$1)) with filledcurve title label3 lt 1\",\n    \"plot sin(x) with lines lw 1 lc rgb 'black'\")\n\n#-----------------------------------------------------------------\n@gp(\"\"\"\n        set zrange [-1:1]\n        unset label\n        unset arrow\n        sinc(u,v) = sin(sqrt(u**2+v**2)) / sqrt(u**2+v**2)\n        set xrange [-5:5]; set yrange [-5:5]\n        set arrow from 5,-5,-1.2 to 5,5,-1.2 lt -1\n        set label 1 \"increasing v\" at 6,0,-1\n        set arrow from 5,6,-1 to 5,5,-1 lt -1\n        set label 2 \"u=0\" at 5,6.5,-1\n        set arrow from 5,6,sinc(5,5) to 5,5,sinc(5,5) lt -1\n        set label 3 \"u=1\" at 5,6.5,sinc(5,5)\n        set parametric\n        set hidden3d offset 0\t# front/back coloring makes no sense for fenceplot #\n        set isosamples 2,33\n        xx=-5; dx=(4.99-(-4.99))/9\n        x0=xx; xx=xx+dx\n        x1=xx; xx=xx+dx\n        x2=xx; xx=xx+dx\n        x3=xx; xx=xx+dx\n        x4=xx; xx=xx+dx\n        x5=xx; xx=xx+dx\n        x6=xx; xx=xx+dx\n        x7=xx; xx=xx+dx\n        x8=xx; xx=xx+dx\n        x9=xx; xx=xx+dx\"\"\",\n    \"splot [u=0:1][v=-4.99:4.99]x0, v, (u<0.5) ? -1 : sinc(x0,v) notitle\",\n\t\"splot x1, v, (u<0.5) ? -1 : sinc(x1,v) notitle\",\n\t\"splot x2, v, (u<0.5) ? -1 : sinc(x2,v) notitle\",\n\t\"splot x3, v, (u<0.5) ? -1 : sinc(x3,v) notitle\",\n\t\"splot x4, v, (u<0.5) ? -1 : sinc(x4,v) notitle\",\n\t\"splot x5, v, (u<0.5) ? -1 : sinc(x5,v) notitle\",\n\t\"splot x6, v, (u<0.5) ? -1 : sinc(x6,v) notitle\",\n\t\"splot x7, v, (u<0.5) ? -1 : sinc(x7,v) notitle\",\n\t\"splot x8, v, (u<0.5) ? -1 : sinc(x8,v) notitle\",\n\t\"splot x9, v, (u<0.5) ? -1 : sinc(x9,v) notitle\")\n\nquitall()\n", "meta": {"hexsha": "3f09684c06b1b0f817f53cba400cf712235f1d20", "size": 4869, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Gnuplot.jl-dc211083-a33a-5b79-959f-2ff34033469d", "max_stars_repo_head_hexsha": "05048093dbd6e6bf58648b9096eb1d854803d6ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Gnuplot.jl-dc211083-a33a-5b79-959f-2ff34033469d", "max_issues_repo_head_hexsha": "05048093dbd6e6bf58648b9096eb1d854803d6ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Gnuplot.jl-dc211083-a33a-5b79-959f-2ff34033469d", "max_forks_repo_head_hexsha": "05048093dbd6e6bf58648b9096eb1d854803d6ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8125, "max_line_length": 85, "alphanum_fraction": 0.4623125899, "num_tokens": 1883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.7501802228495231}}
{"text": "function _degree_centrality(g::AbstractGraph, gtype::Integer; normalize=true)\n    n_v = nv(g)\n    c = zeros(n_v)\n    for v in vertices(g)\n        if gtype == 0    # count both in and out degree if appropriate\n            deg = is_directed(g) ? outdegree(g, v) + indegree(g, v) : outdegree(g, v)\n        elseif gtype == 1    # count only in degree\n            deg = indegree(g, v)\n        else                 # count only out degree\n            deg = outdegree(g, v)\n        end\n        s = normalize ? (1.0 / (n_v - 1.0)) : 1.0\n        c[v] = deg * s\n    end\n    return c\nend\n\n\"\"\"\n    degree_centrality(g)\n    indegree_centrality(g)\n    outdegree_centrality(g)\n\nCalculate the [degree centrality](https://en.wikipedia.org/wiki/Centrality#Degree_centrality)\nof graph `g`. Return a vector representing the centrality calculated for each node in `g`.\n\n### Optional Arguments\n- `normalize=true`: If true, normalize each centrality measure by ``\\\\frac{1}{|V|-1}``.\n\n# Examples\n```jldoctest\njulia> using LightGraphs\n\njulia> degree_centrality(star_graph(4))\n4-element Array{Float64,1}:\n 1.0               \n 0.3333333333333333\n 0.3333333333333333\n 0.3333333333333333\n\njulia> degree_centrality(path_graph(3))\n3-element Array{Float64,1}:\n 0.5\n 1.0\n 0.5\n```\n\"\"\"\ndegree_centrality(g::AbstractGraph; all...) = _degree_centrality(g, 0; all...)\nindegree_centrality(g::AbstractGraph; all...) = _degree_centrality(g, 1; all...)\noutdegree_centrality(g::AbstractGraph; all...) = _degree_centrality(g, 2; all...)\n", "meta": {"hexsha": "3908b937fbc5e5290188e54cb4187703a111fc18", "size": 1493, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/centrality/degree.jl", "max_stars_repo_name": "blepabyte/LightGraphs.jl", "max_stars_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 745, "max_stars_repo_stars_event_min_datetime": "2015-03-19T03:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-07T00:59:06.000Z", "max_issues_repo_path": "src/centrality/degree.jl", "max_issues_repo_name": "blepabyte/LightGraphs.jl", "max_issues_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1491, "max_issues_repo_issues_event_min_datetime": "2015-03-19T17:04:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T14:47:57.000Z", "max_forks_repo_path": "src/centrality/degree.jl", "max_forks_repo_name": "blepabyte/LightGraphs.jl", "max_forks_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 288, "max_forks_repo_forks_event_min_datetime": "2015-04-04T14:31:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T10:37:21.000Z", "avg_line_length": 29.86, "max_line_length": 93, "alphanum_fraction": 0.6483590087, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.8670357529306639, "lm_q1q2_score": 0.7501802138909297}}
{"text": "# ---\n# title: 119. Pascal's Triangle II\n# id: problem119\n# author: Indigo\n# date: 2021-02-12\n# difficulty: Easy\n# categories: Array\n# link: <https://leetcode.com/problems/pascals-triangle-ii/description/>\n# hidden: true\n# ---\n# \n# Given an integer `rowIndex`, return the `rowIndexth` row of the Pascal's\n# triangle.\n# \n# Notice that the row index starts from  **0**.\n# \n# ![](https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif)  \n# In Pascal's triangle, each number is the sum of the two numbers directly above\n# it.\n# \n# **Follow up:**\n# \n# Could you optimize your algorithm to use only _O_ ( _k_ ) extra space?\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: rowIndex = 3\n#     Output: [1,3,3,1]\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: rowIndex = 0\n#     Output: [1]\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: rowIndex = 1\n#     Output: [1,1]\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `0 <= rowIndex <= 33`\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction get_pascal_row(row_index::Int)\n    res = fill(1, row_index + 1)\n    for i in 2:row_index\n        res[2:i] .= @view(res[1:(i - 1)]) + @view(res[2:i])\n    end\n    res\nend\n## @lc code=end\n", "meta": {"hexsha": "65b3aee41134840abea3cbe0c1972ad44d1f3cde", "size": 1214, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/119.pascals-triangle-ii.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/119.pascals-triangle-ii.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/119.pascals-triangle-ii.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 17.5942028986, "max_line_length": 88, "alphanum_fraction": 0.5716639209, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.865224070413529, "lm_q1q2_score": 0.750180209290121}}
{"text": "#=\r\nfor variables X in R^{n, m} and Y in S^n:\r\nmaximize    tr(C*X) :\r\nsubject to  Y - X*X' in S^n_+\r\n            Y_ij = P_ij for (i, j) in Omega\r\nwhere Omega is a set of fixed indices and P is a random PSD matrix\r\n\r\nthe nonlinear constraint Y - X*X' in S^n_+ is equivalent to\r\nthe conic constraint (Y, 0.5, X) in MatrixEpiPerSquareCone(),\r\nand also to the larger conic constraint [I X'; X Y] in S^{n + m}_+\r\n\r\nsimple case of nonlinfear matrix inequality example from Lectures on Modern\r\nConvex Optimization by Aharon Ben-Tal and Arkadi Nemirovski, pg 154\r\n=#\r\n\r\nusing SparseArrays\r\n\r\nstruct MatrixQuadraticJuMP{T <: Real} <: ExampleInstanceJuMP{T}\r\n    num_rows::Int\r\n    num_cols::Int\r\n    use_matrixepipersquare::Bool # use matrixepipersquare cone, else PSD cone\r\nend\r\n\r\nfunction build(inst::MatrixQuadraticJuMP{T}) where {T <: Float64}\r\n    (num_rows, num_cols) = (inst.num_rows, inst.num_cols)\r\n    C = randn(num_cols, num_rows)\r\n    P = randn(num_rows, num_rows)\r\n    P = Symmetric(P * P')\r\n    (row_idxs, col_idxs, _) = findnz(tril!(sprand(Bool, num_rows,\r\n        num_rows, inv(sqrt(num_rows)))) + I)\r\n\r\n    model = JuMP.Model()\r\n    JuMP.@variable(model, X[1:num_rows, 1:num_cols])\r\n    JuMP.@variable(model, Y[1:num_rows, 1:num_rows], Symmetric)\r\n    JuMP.@objective(model, Max, tr(C * X))\r\n    JuMP.@constraint(model, [(row, col) in zip(row_idxs, col_idxs)],\r\n        Y[row, col] == P[row, col])\r\n\r\n    if inst.use_matrixepipersquare\r\n        U_svec = zeros(JuMP.GenericAffExpr{T, JuMP.VariableRef},\r\n            Cones.svec_length(num_rows))\r\n        U_svec = Cones.smat_to_svec!(U_svec, 1.0 * Y, sqrt(2))\r\n        JuMP.@constraint(model, vcat(U_svec, 0.5, vec(X)) in\r\n            Hypatia.MatrixEpiPerSquareCone{T, T}(num_rows, num_cols))\r\n    else\r\n        JuMP.@constraint(model, Symmetric(\r\n            [Matrix(I, num_cols, num_cols) X'; X Y]) in JuMP.PSDCone())\r\n    end\r\n\r\n    return model\r\nend\r\n", "meta": {"hexsha": "02a1acbc854f2849f8d7063eea8167f2e1e5260f", "size": 1911, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/matrixquadratic/JuMP.jl", "max_stars_repo_name": "matbesancon/Hypatia.jl", "max_stars_repo_head_hexsha": "9e1487850b5db87ea23545bd07348e5a36ac8bf3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2018-11-26T15:51:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:21:57.000Z", "max_issues_repo_path": "examples/matrixquadratic/JuMP.jl", "max_issues_repo_name": "matbesancon/Hypatia.jl", "max_issues_repo_head_hexsha": "9e1487850b5db87ea23545bd07348e5a36ac8bf3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 208, "max_issues_repo_issues_event_min_datetime": "2018-11-26T21:30:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:02:04.000Z", "max_forks_repo_path": "examples/matrixquadratic/JuMP.jl", "max_forks_repo_name": "matbesancon/Hypatia.jl", "max_forks_repo_head_hexsha": "9e1487850b5db87ea23545bd07348e5a36ac8bf3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-05-18T20:26:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T10:22:31.000Z", "avg_line_length": 36.75, "max_line_length": 78, "alphanum_fraction": 0.6467817896, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172572644807, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7501478664593789}}
{"text": "degree_size(currDegree, spatialDim) =\n    factorial(currDegree + spatialDim - 1) ÷\n    (factorial(currDegree) * factorial(spatialDim - 1))\n\n\nfunction basis_size(LMaxDegree, spatialDim)\n    basisLen = 0\n    for idx_degree = 0:LMaxDegree\n        basisLen += degree_size(idx_degree, spatialDim)\n    end\n    return basisLen\nend\n\n\nfunction power(basis, exponent)\n    if exponent == 0\n        return 1.0\n    end\n    result = basis\n    for i = 2:exponent\n        result *= basis\n    end\n    return result\nend\n\n\nfunction monomial_basis(pointX, pointY, pointZ, polyDegree::T) where {T<:Integer}\n    idx_vector = 1\n    spatialDim = 3\n    basisLen = basis_size(polyDegree, spatialDim)\n    basisAtPt = ones(1, basisLen)\n    for idx_degree = 0:polyDegree\n        for a = 0:idx_degree\n            for b = 0:(idx_degree-a)\n                c = idx_degree - a - b\n                basisAtPt[idx_vector] =\n                    power(pointX, a) * power(pointY, b) * power(pointZ, c)\n                idx_vector = idx_vector + 1\n            end\n        end\n    end\n\n    return basisAtPt\nend\n\n\nfunction monomial_basis(pointX, polyDegree::T) where {T<:Integer}\n    idx_vector = 1\n    spatialDim = 1\n    basisLen = basis_size(polyDegree, spatialDim)\n    basisAtPt = ones(1, basisLen)\n    for a = 0:polyDegree\n        basisAtPt[idx_vector] = power(pointX, a)\n        idx_vector = idx_vector + 1\n    end\n\n    return basisAtPt\nend\n\n\nfunction eval_sphermonomial(quadpts::AV, polyDegree::Integer)\n    monomialBasis = zeros(basis_size(polyDegree, 1), size(quadpts, 1))\n\n    for idx_quad = 1:length(quadpts)\n        monomialBasis[:, idx_quad] = monomial_basis(quadpts[idx_quad, 1], polyDegree)\n    end\n\n    return monomialBasis\nend\n\n\nfunction eval_sphermonomial(quadpts::Matrix, polyDegree::Integer)\n    monomialBasis = zeros(basis_size(polyDegree, 3), size(quadpts, 1))\n\n    for idx_quad = 1:(size(quadpts)[1])\n        monomialBasis[:, idx_quad] = monomial_basis(\n            quadpts[idx_quad, 1],\n            quadpts[idx_quad, 2],\n            quadpts[idx_quad, 3],\n            polyDegree,\n        )\n    end\n\n    return monomialBasis\nend\n", "meta": {"hexsha": "1d67764a70ed77043123fa3132a08a7d84eb8dc2", "size": 2106, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Math/sphere_monomials.jl", "max_stars_repo_name": "vavrines/KineticBase.jl", "max_stars_repo_head_hexsha": "d00cefe073346a3bab3b4d3577a95631e320dc9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Math/sphere_monomials.jl", "max_issues_repo_name": "vavrines/KineticBase.jl", "max_issues_repo_head_hexsha": "d00cefe073346a3bab3b4d3577a95631e320dc9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/sphere_monomials.jl", "max_forks_repo_name": "vavrines/KineticBase.jl", "max_forks_repo_head_hexsha": "d00cefe073346a3bab3b4d3577a95631e320dc9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.488372093, "max_line_length": 85, "alphanum_fraction": 0.6329534663, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.7905303112671295, "lm_q1q2_score": 0.750147855894054}}
{"text": "using LinearAlgebra: axpy!\nusing SparseArrays\n\n# exponential_utils.jl\n# Contains functions related to the evaluation of scalar/matrix phi functions\n# that are used by the exponential integrators.\n#\n# TODO: write a version of `exp!` that is non-allocating.\n\n###################################################\n# Dense algorithms\nusing LinearAlgebra: exp!\n\n\"\"\"\n    phi(z,k[;cache]) -> [phi_0(z),phi_1(z),...,phi_k(z)]\n\nCompute the scalar phi functions for all orders up to k.\n\nThe phi functions are defined as\n\n```math\n\\\\varphi_0(z) = \\\\exp(z),\\\\quad \\\\varphi_k(z+1) = \\\\frac{\\\\varphi_k(z) - 1}{z}\n```\n\nInstead of using the recurrence relation, which is numerically unstable, a\nformula given by Sidje is used (Sidje, R. B. (1998). Expokit: a software\npackage for computing matrix exponentials. ACM Transactions on Mathematical\nSoftware (TOMS), 24(1), 130-156. Theorem 1).\n\"\"\"\nfunction phi(z::T, k::Integer; cache=nothing) where {T <: Number}\n  # Construct the matrix\n  if cache == nothing\n    cache = fill(zero(T), k+1, k+1)\n  else\n    fill!(cache, zero(T))\n  end\n  cache[1,1] = z\n  for i = 1:k\n    cache[i,i+1] = one(T)\n  end\n  P = exp!(cache)\n  return P[1,:]\nend\n\n\"\"\"\n    phiv_dense(A,v,k[;cache]) -> [phi_0(A)v phi_1(A)v ... phi_k(A)v]\n\nCompute the matrix-phi-vector products for small, dense `A`. `k`` >= 1.\n\nThe phi functions are defined as\n\n```math\n\\\\varphi_0(z) = \\\\exp(z),\\\\quad \\\\varphi_k(z+1) = \\\\frac{\\\\varphi_k(z) - 1}{z}\n```\n\nInstead of using the recurrence relation, which is numerically unstable, a\nformula given by Sidje is used (Sidje, R. B. (1998). Expokit: a software\npackage for computing matrix exponentials. ACM Transactions on Mathematical\nSoftware (TOMS), 24(1), 130-156. Theorem 1).\n\"\"\"\nfunction phiv_dense(A, v, k; cache=nothing)\n  w = Matrix{eltype(A)}(undef, length(v), k+1)\n  phiv_dense!(w, A, v, k; cache=cache)\nend\n\"\"\"\n    phiv_dense!(w,A,v,k[;cache]) -> w\n\nNon-allocating version of `phiv_dense`.\n\"\"\"\nfunction phiv_dense!(w::AbstractMatrix{T}, A::AbstractMatrix{T},\n  v::AbstractVector{T}, k::Integer; cache=nothing) where {T <: Number}\n  @assert size(w, 1) == size(A, 1) == size(A, 2) == length(v) \"Dimension mismatch\"\n  @assert size(w, 2) == k+1 \"Dimension mismatch\"\n  m = length(v)\n  # Construct the extended matrix\n  if cache == nothing\n    cache = fill(zero(T), m+k, m+k)\n  else\n    @assert size(cache) == (m+k, m+k) \"Dimension mismatch\"\n    fill!(cache, zero(T))\n  end\n  cache[1:m, 1:m] = A\n  cache[1:m, m+1] = v\n  for i = m+1:m+k-1\n    cache[i, i+1] = one(T)\n  end\n  P = exp!(cache)\n  # Extract results\n  @views mul!(w[:, 1], P[1:m, 1:m], v)\n  @inbounds for i = 1:k\n    @inbounds for j = 1:m\n      w[j, i+1] = P[j, m+i]\n    end\n  end\n  return w\nend\n\n\"\"\"\n    phi(A,k[;cache]) -> [phi_0(A),phi_1(A),...,phi_k(A)]\n\nCompute the matrix phi functions for all orders up to k. `k` >= 1.\n\nThe phi functions are defined as\n\n```math\n\\\\varphi_0(z) = \\\\exp(z),\\\\quad \\\\varphi_k(z+1) = \\\\frac{\\\\varphi_k(z) - 1}{z}\n```\n\nCalls `phiv_dense` on each of the basis vectors to obtain the answer.\n\"\"\"\nfunction phi(A::AbstractMatrix{T}, k; caches=nothing) where {T <: Number}\n  m = size(A, 1)\n  out = [Matrix{T}(undef, m, m) for i = 1:k+1]\n  phi!(out, A, k; caches=caches)\nend\n\"\"\"\n    phi!(out,A,k[;caches]) -> out\n\nNon-allocating version of `phi` for matrix inputs.\n\"\"\"\nfunction phi!(out::Vector{Matrix{T}}, A::AbstractMatrix{T}, k::Integer; caches=nothing) where {T <: Number}\n  m = size(A, 1)\n  @assert length(out) == k + 1 && all(P -> size(P) == (m,m), out) \"Dimension mismatch\"\n  if caches == nothing\n    e = Vector{T}(undef, m)\n    W = Matrix{T}(undef, m, k+1)\n    C = Matrix{T}(undef, m+k, m+k)\n  else\n    e, W, C = caches\n    @assert size(e) == (m,) && size(W) == (m, k+1) && size(C) == (m+k, m+k) \"Dimension mismatch\"\n  end\n  @inbounds for i = 1:m\n    fill!(e, zero(T)); e[i] = one(T) # e is the ith basis vector\n    phiv_dense!(W, A, e, k; cache=C) # W = [phi_0(A)*e phi_1(A)*e ... phi_k(A)*e]\n    @inbounds for j = 1:k+1\n      @inbounds for s = 1:m\n        out[j][s, i] = W[s, j]\n      end\n    end\n  end\n  return out\nend\n\n##############################################\n# Krylov algorithms\n\"\"\"\n    KrylovSubspace{T}(n,[maxiter=30]) -> Ks\n\nConstructs an uninitialized Krylov subspace, which can be filled by `arnoldi!`.\n\nThe dimension of the subspace, `Ks.m`, can be dynamically altered but should\nbe smaller than `maxiter`, the maximum allowed arnoldi iterations.\n\n    getV(Ks) -> V\n    getH(Ks) -> H\n\nAccess methods for the (extended) orthonormal basis `V` and the (extended)\nGram-Schmidt coefficients `H`. Both methods return a view into the storage\narrays and has the correct dimensions as indicated by `Ks.m`.\n\n    resize!(Ks, maxiter) -> Ks\n\nResize `Ks` to a different `maxiter`, destroying its contents.\n\nThis is an expensive operation and should be used scarsely.\n\"\"\"\nmutable struct KrylovSubspace{B, T}\n  m::Int        # subspace dimension\n  maxiter::Int  # maximum allowed subspace size\n  beta::B       # norm(b,2)\n  V::Matrix{T}  # orthonormal bases\n  H::Matrix{T}  # Gram-Schmidt coefficients\n  KrylovSubspace{T}(n::Integer, maxiter::Integer=30) where {T} = new{real(T), T}(\n    maxiter, maxiter, zero(real(T)), Matrix{T}(undef, n, maxiter + 1),\n    fill(zero(T), maxiter + 1, maxiter))\nend\ngetH(Ks::KrylovSubspace) = @view(Ks.H[1:Ks.m + 1, 1:Ks.m])\ngetV(Ks::KrylovSubspace) = @view(Ks.V[:, 1:Ks.m + 1])\nfunction Base.resize!(Ks::KrylovSubspace{B,T}, maxiter::Integer) where {B,T}\n  V = Matrix{T}(undef, size(Ks.V, 1), maxiter + 1)\n  H = fill(zero(T), maxiter + 1, maxiter)\n  Ks.V = V; Ks.H = H\n  Ks.m = Ks.maxiter = maxiter\n  return Ks\nend\nfunction Base.show(io::IO, Ks::KrylovSubspace)\n  println(io, \"$(Ks.m)-dimensional Krylov subspace with fields\")\n  println(io, \"beta: $(Ks.beta)\")\n  print(io, \"V: \")\n  println(IOContext(io, limit=true), getV(Ks))\n  print(io, \"H: \")\n  println(IOContext(io, limit=true), getH(Ks))\nend\n\n\"\"\"\n    arnoldi(A,b[;m,tol,opnorm,cache]) -> Ks\n\nPerforms `m` anoldi iterations to obtain the Krylov subspace K_m(A,b).\n\nThe n x (m + 1) basis vectors `getV(Ks)` and the (m + 1) x m upper Heisenberg\nmatrix `getH(Ks)` are related by the recurrence formula\n\n```\nv_1=b,\\\\quad Av_j = \\\\sum_{i=1}^{j+1}h_{ij}v_i\\\\quad(j = 1,2,\\\\ldots,m)\n```\n\n`iop` determines the length of the incomplete orthogonalization procedure [^1].\nThe default value of 0 indicates full Arnoldi. For symmetric/Hermitian `A`,\n`iop` will be ignored and the Lanczos algorithm will be used instead.\n\nRefer to `KrylovSubspace` for more information regarding the output.\n\nHappy-breakdown occurs whenver `norm(v_j) < tol * opnorm(A, Inf)`, in this case\nthe dimension of `Ks` is smaller than `m`.\n\n[^1]: Koskela, A. (2015). Approximating the matrix exponential of an\nadvection-diffusion operator using the incomplete orthogonalization method. In\nNumerical Mathematics and Advanced Applications-ENUMATH 2013 (pp. 345-353).\nSpringer, Cham.\n\"\"\"\nfunction arnoldi(A, b; m=min(30, size(A, 1)), tol=1e-7, opnorm=LinearAlgebra.opnorm,\n  iop=0, cache=nothing)\n  Ks = KrylovSubspace{eltype(b)}(length(b), m)\n  arnoldi!(Ks, A, b; m=m, tol=tol, opnorm=opnorm, cache=cache, iop=iop)\nend\n\"\"\"\n    arnoldi!(Ks,A,b[;tol,m,opnorm,cache]) -> Ks\n\nNon-allocating version of `arnoldi`.\n\"\"\"\nfunction arnoldi!(Ks::KrylovSubspace{B, T}, A, b::AbstractVector{T}; tol::Real=1e-7,\n  m::Int=min(Ks.maxiter, size(A, 1)), opnorm=LinearAlgebra.opnorm, iop::Int=0, cache=nothing) where {B, T <: Number}\n  if ishermitian(A)\n    return lanczos!(Ks, A, b; tol=tol, m=m, opnorm=opnorm, cache=cache)\n  end\n  if m > Ks.maxiter\n    resize!(Ks, m)\n  else\n    Ks.m = m # might change if happy-breakdown occurs\n  end\n  V, H = getV(Ks), getH(Ks)\n  vtol = tol * opnorm(A, Inf)\n  if iop == 0\n    iop = m\n  end\n  # Safe checks\n  n = size(V, 1)\n  @assert length(b) == size(A,1) == size(A,2) == n \"Dimension mismatch\"\n  if cache == nothing\n    cache = similar(b)\n  else\n    @assert size(cache) == (n,) \"Dimension mismatch\"\n  end\n  # Arnoldi iterations (with IOP)\n  fill!(H, zero(T))\n  Ks.beta = norm(b)\n  @. V[:, 1] = b / Ks.beta\n  @inbounds for j = 1:m\n    mul!(cache, A, @view(V[:, j]))\n    @inbounds for i = max(1, j - iop + 1):j\n      alpha = dot(@view(V[:, i]), cache)\n      H[i, j] = alpha\n      axpy!(-alpha, @view(V[:, i]), cache)\n    end\n    beta = norm(cache)\n    H[j+1, j] = beta\n    @inbounds for i = 1:n\n      V[i, j+1] = cache[i] / beta\n    end\n    if beta < vtol # happy-breakdown\n      Ks.m = j\n      break\n    end\n  end\n  return Ks\nend\n\"\"\"\n    lanczos!(Ks,A,b[;tol,m,opnorm,cache]) -> Ks\n\nA variation of `arnoldi!` that uses the Lanczos algorithm for Hermitian matrices.\n\"\"\"\nfunction lanczos!(Ks::KrylovSubspace{B, T}, A, b::AbstractVector{T}; tol=1e-7,\n  m=min(Ks.maxiter, size(A, 1)), opnorm=LinearAlgebra.opnorm, cache=nothing) where {B, T <: Number}\n  if m > Ks.maxiter\n    resize!(Ks, m)\n  else\n    Ks.m = m # might change if happy-breakdown occurs\n  end\n  V, H = getV(Ks), getH(Ks)\n  vtol = tol * opnorm(A, Inf)\n  # Safe checks\n  n = size(V, 1)\n  @assert length(b) == size(A,1) == size(A,2) == n \"Dimension mismatch\"\n  if cache == nothing\n    cache = similar(b)\n  else\n    @assert size(cache) == (n,) \"Dimension mismatch\"\n  end\n  # Lanczos iterations\n  fill!(H, zero(T))\n  Ks.beta = norm(b)\n  @. V[:, 1] = b / Ks.beta\n  @inbounds for j = 1:m\n    vj = @view(V[:, j])\n    mul!(cache, A, vj)\n    alpha = dot(vj, cache)\n    H[j, j] = alpha\n    axpy!(-alpha, vj, cache)\n    if j > 1\n      axpy!(-H[j-1, j], @view(V[:, j-1]), cache)\n    end\n    beta = norm(cache)\n    H[j+1, j] = beta\n    if j < m\n      H[j, j+1] = beta\n    end\n    @inbounds for i = 1:n\n      V[i, j+1] = cache[i] / beta\n    end\n    if beta < vtol # happy-breakdown\n      Ks.m = j\n      break\n    end\n  end\n  return Ks\nend\n\n# Cache type for expv\nmutable struct ExpvCache{T}\n  mem::Vector{T}\n  ExpvCache{T}(maxiter::Int) where {T} = new{T}(Vector{T}(undef, maxiter^2))\nend\nfunction Base.resize!(C::ExpvCache{T}, maxiter::Int) where {T}\n  C.mem = Vector{T}(undef, maxiter^2 * 2)\n  return C\nend\nfunction get_cache(C::ExpvCache, m::Int)\n  m^2 > length(C.mem) && resize!(C, m) # resize the cache if needed\n  reshape(@view(C.mem[1:m^2]), m, m)\nend\n\"\"\"\n    expv(t,A,b; kwargs) -> exp(tA)b\n\nCompute the matrix-exponential-vector product using Krylov.\n\nA Krylov subspace is constructed using `arnoldi` and `exp!` is called\non the Heisenberg matrix. Consult `arnoldi` for the values of the keyword\narguments.\n\n    expv(t,Ks; cache) -> exp(tA)b\n\nCompute the expv product using a pre-constructed Krylov subspace.\n\"\"\"\nfunction expv(t, A, b; m=min(30, size(A, 1)), tol=1e-7, opnorm=LinearAlgebra.opnorm, cache=nothing, iop=0)\n  Ks = arnoldi(A, b; m=m, tol=tol, opnorm=opnorm, iop=iop)\n  w = similar(b)\n  expv!(w, t, Ks; cache=cache)\nend\nfunction expv(t, Ks::KrylovSubspace{B, T}; cache=nothing) where {B, T}\n  n = size(getV(Ks), 1)\n  w = Vector{T}(undef, n)\n  expv!(w, t, Ks; cache=cache)\nend\n\"\"\"\n    expv!(w,t,Ks[;cache]) -> w\n\nNon-allocating version of `expv` that uses precomputed Krylov subspace `Ks`.\n\"\"\"\nfunction expv!(w::AbstractVector{T}, t::Number, Ks::KrylovSubspace{B, T};\n  cache=nothing) where {B, T <: Number}\n  m, beta, V, H = Ks.m, Ks.beta, getV(Ks), getH(Ks)\n  @assert length(w) == size(V, 1) \"Dimension mismatch\"\n  if cache == nothing\n    cache = Matrix{T}(undef, m, m)\n  elseif isa(cache, ExpvCache)\n    cache = get_cache(cache, m)\n  else\n    throw(ArgumentError(\"Cache must be an ExpvCache\"))\n  end\n  lmul!(t, copyto!(cache, @view(H[1:m, :])))\n  if ishermitian(cache)\n    # Optimize the case for symtridiagonal H\n    F = eigen!(SymTridiagonal(cache))\n    expHe = F.vectors * (exp.(F.values) .* @view(F.vectors[1, :]))\n  else\n    expH = exp!(cache)\n    expHe = @view(expH[:, 1])\n  end\n  lmul!(beta, mul!(w, @view(V[:, 1:m]), expHe)) # exp(A) ≈ norm(b) * V * exp(H)e\nend\n\n# Cache type for phiv\nmutable struct PhivCache{T}\n  mem::Vector{T}\n  function PhivCache{T}(maxiter::Int, p::Int) where {T}\n    numelems = maxiter + maxiter^2 + (maxiter + p)^2 + maxiter*(p + 1)\n    new{T}(Vector{T}(undef, numelems))\n  end\nend\nfunction Base.resize!(C::PhivCache{T}, maxiter::Int, p::Int) where {T}\n  numelems = maxiter + maxiter^2 + (maxiter + p)^2 + maxiter*(p + 1)\n  C.mem = Vector{T}(undef, numelems * 2)\n  return C\nend\nfunction get_caches(C::PhivCache, m::Int, p::Int)\n  numelems = m + m^2 + (m + p)^2 + m*(p + 1)\n  numelems^2 > length(C.mem) && resize!(C, m, p) # resize the cache if needed\n  e = @view(C.mem[1:m]); offset = m\n  Hcopy = reshape(@view(C.mem[offset + 1:offset + m^2]), m, m); offset += m^2\n  C1 = reshape(@view(C.mem[offset + 1:offset + (m+p)^2]), m+p, m+p); offset += (m+p)^2\n  C2 = reshape(@view(C.mem[offset + 1:offset + m*(p+1)]), m, p+1)\n  return e, Hcopy, C1, C2\nend\n\"\"\"\n    phiv(t,A,b,k;correct,kwargs) -> [phi_0(tA)b phi_1(tA)b ... phi_k(tA)b][, errest]\n\nCompute the matrix-phi-vector products using Krylov. `k` >= 1.\n\nThe phi functions are defined as\n\n```math\n\\\\varphi_0(z) = \\\\exp(z),\\\\quad \\\\varphi_k(z+1) = \\\\frac{\\\\varphi_k(z) - 1}{z}\n```\n\nA Krylov subspace is constructed using `arnoldi` and `phiv_dense` is called\non the Heisenberg matrix. If `correct=true`, then phi_0 through phi_k-1 are\nupdated using the last Arnoldi vector v_m+1 [^1]. If `errest=true` then an\nadditional error estimate for the second-to-last phi is also returned. For\nthe additional keyword arguments, consult `arnoldi`.\n\n  phiv(t,Ks,k;correct,kwargs) -> [phi_0(tA)b phi_1(tA)b ... phi_k(tA)b][, errest]\n\nCompute the matrix-phi-vector products using a pre-constructed Krylov subspace.\n\n[^1]: Niesen, J., & Wright, W. (2009). A Krylov subspace algorithm for evaluating\nthe φ-functions in exponential integrators. arXiv preprint arXiv:0907.4631.\nFormula (10).\n\"\"\"\nfunction phiv(t, A, b, k; m=min(30, size(A, 1)), tol=1e-7, opnorm=LinearAlgebra.opnorm, iop=0,\n  cache=nothing, correct=false, errest=false)\n  Ks = arnoldi(A, b; m=m, tol=tol, opnorm=opnorm, iop=iop)\n  w = Matrix{eltype(b)}(undef, length(b), k+1)\n  phiv!(w, t, Ks, k; cache=cache, correct=correct, errest=errest)\nend\nfunction phiv(t, Ks::KrylovSubspace{B, T}, k; cache=nothing, correct=false,\n  errest=false) where {B, T}\n  n = size(getV(Ks), 1)\n  w = Matrix{T}(undef, n, k+1)\n  phiv!(w, t, Ks, k; cache=cache, correct=correct, errest=errest)\nend\n\"\"\"\n    phiv!(w,t,Ks,k[;cache,correct,errest]) -> w[,errest]\n\nNon-allocating version of 'phiv' that uses precomputed Krylov subspace `Ks`.\n\"\"\"\nfunction phiv!(w::AbstractMatrix{T}, t::Number, Ks::KrylovSubspace{B, T}, k::Integer;\n  cache=nothing, correct=false, errest=false) where {B, T <: Number}\n  m, beta, V, H = Ks.m, Ks.beta, getV(Ks), getH(Ks)\n  @assert size(w, 1) == size(V, 1) \"Dimension mismatch\"\n  @assert size(w, 2) == k + 1 \"Dimension mismatch\"\n  if cache == nothing\n    cache = PhivCache{T}(m, k)\n  elseif !isa(cache, PhivCache)\n    throw(ArgumentError(\"Cache must be a PhivCache\"))\n  end\n  e, Hcopy, C1, C2 = get_caches(cache, m, k)\n  lmul!(t, copyto!(Hcopy, @view(H[1:m, :])))\n  fill!(e, zero(T)); e[1] = one(T) # e is the [1,0,...,0] basis vector\n  phiv_dense!(C2, Hcopy, e, k; cache=C1) # C2 = [ϕ0(H)e ϕ1(H)e ... ϕk(H)e]\n  lmul!(beta, mul!(w, @view(V[:, 1:m]), C2)) # f(A) ≈ norm(b) * V * f(H)e\n  if correct\n    # Use the last Arnoldi vector for correction with little additional cost\n    # correct_p = beta * h_{m+1,m} * (em^T phi_p+1(H) e1) * v_m+1\n    betah = beta * H[end,end] * t\n    vlast = @view(V[:,end])\n    @inbounds for i = 1:k\n      axpy!(betah * C2[end, i+1], vlast, @view(w[:, i]))\n    end\n  end\n  if errest\n    err = abs(beta * H[end, end] * t * C2[end, end])\n    return w, err\n  else\n    return w\n  end\nend\n\n###########################################\n# Krylov phiv with internal time-stepping\n\"\"\"\n    exp_timestep(ts,A,b[;adaptive,tol,kwargs...]) -> U\n\nEvaluates the matrix exponentiation-vector product using time stepping\n\n```math\nu = \\\\exp(tA)b\n```\n\n`ts`` is an array of time snapshots for u, with `U[:,j] ≈ u(ts[j])`. `ts` can\nalso be just one value, in which case only the end result is returned and `U`\nis a vector.\n\nThe time stepping formula of Niesen & Wright is used [^1]. If the time step\n`tau` is not specified, it is chosen according to (17) of Neisen & Wright. If\n`adaptive==true`, the time step and Krylov subsapce size adaptation scheme of\nNiesen & Wright is used, the relative tolerance of which can be set using the\nkeyword parameter `tol`. The delta and gamma parameter of the adaptation\nscheme can also be adjusted.\n\nSet `verbose=true` to print out the internal steps (for debugging). For the\nother keyword arguments, consult `arnoldi` and `phiv`, which are used\ninternally.\n\nNote that this function is just a special case of `phiv_timestep` with a more\nintuitive interface (vector `b` instead of a n-by-1 matrix `B`).\n\n[^1]: Niesen, J., & Wright, W. (2009). A Krylov subspace algorithm for\nevaluating the φ-functions in exponential integrators. arXiv preprint\narXiv:0907.4631.\n\"\"\"\nfunction expv_timestep(ts::Vector{tType}, A, b; kwargs...) where {tType <: Real}\n  U = Matrix{eltype(A)}(undef, size(A, 1), length(ts))\n  expv_timestep!(U, ts, A, b; kwargs...)\nend\nfunction expv_timestep(t::tType, A, b; kwargs...) where {tType <: Real}\n  u = Vector{eltype(A)}(undef, size(A, 1))\n  expv_timestep!(u, t, A, b; kwargs...)\nend\n\"\"\"\n    expv_timestep!(u,t,A,b[;kwargs]) -> u\n\nNon-allocating version of `expv_timestep`.\n\"\"\"\nfunction expv_timestep!(u::AbstractVector{T}, t::tType, A, b::AbstractVector{T};\n  kwargs...) where {T <: Number, tType <: Real}\n  expv_timestep!(reshape(u, length(u), 1), [t], A, b; kwargs...)\n  return u\nend\nfunction expv_timestep!(U::AbstractMatrix{T}, ts::Vector{tType}, A, b::AbstractVector{T};\n  kwargs...) where {T <: Number, tType <: Real}\n  B = reshape(b, length(b), 1)\n  phiv_timestep!(U, ts, A, B; kwargs...)\nend\n\"\"\"\n    phiv_timestep(ts,A,B[;adaptive,tol,kwargs...]) -> U\n\nEvaluates the linear combination of phi-vector products using time stepping\n\n```math\nu = \\\\varphi_0(tA)b_0 + t\\\\varphi_1(tA)b_1 + \\\\cdots + t^p\\\\varphi_p(tA)b_p\n```\n\n`ts`` is an array of time snapshots for u, with `U[:,j] ≈ u(ts[j])`. `ts` can\nalso be just one value, in which case only the end result is returned and `U`\nis a vector.\n\nThe time stepping formula of Niesen & Wright is used [^1]. If the time step\n`tau` is not specified, it is chosen according to (17) of Neisen & Wright. If\n`adaptive==true`, the time step and Krylov subsapce size adaptation scheme of\nNiesen & Wright is used, the relative tolerance of which can be set using the\nkeyword parameter `tol`. The delta and gamma parameter of the adaptation\nscheme can also be adjusted.\n\nSet `verbose=true` to print out the internal steps (for debugging). For the\nother keyword arguments, consult `arnoldi` and `phiv`, which are used\ninternally.\n\n[^1]: Niesen, J., & Wright, W. (2009). A Krylov subspace algorithm for\nevaluating the φ-functions in exponential integrators. arXiv preprint\narXiv:0907.4631.\n\"\"\"\nfunction phiv_timestep(ts::Vector{tType}, A, B; kwargs...) where {tType <: Real}\n  U = Matrix{eltype(A)}(undef, size(A, 1), length(ts))\n  phiv_timestep!(U, ts, A, B; kwargs...)\nend\nfunction phiv_timestep(t::tType, A, B; kwargs...) where {tType <: Real}\n  u = Vector{eltype(A)}(undef, size(A, 1))\n  phiv_timestep!(u, t, A, B; kwargs...)\nend\n\"\"\"\n    phiv_timestep!(U,ts,A,B[;kwargs]) -> U\n\nNon-allocating version of `phiv_timestep`.\n\"\"\"\nfunction phiv_timestep!(u::AbstractVector{T}, t::tType, A, B::AbstractMatrix{T};\n  kwargs...) where {T <: Number, tType <: Real}\n  phiv_timestep!(reshape(u, length(u), 1), [t], A, B; kwargs...)\n  return u\nend\nfunction phiv_timestep!(U::AbstractMatrix{T}, ts::Vector{tType}, A, B::AbstractMatrix{T}; tau::Real=0.0,\n  m::Int=min(10, size(A, 1)), tol::Real=1e-7, opnorm=LinearAlgebra.opnorm, iop::Int=0,\n  correct::Bool=false, caches=nothing, adaptive=false, delta::Real=1.2,\n  gamma::Real=0.8, NA::Int=0, verbose=false) where {T <: Number, tType <: Real}\n  # Choose initial timestep\n  abstol = tol * opnorm(A, Inf)\n  verbose && println(\"Absolute tolerance: $abstol\")\n  if iszero(tau)\n    Anorm = opnorm(A, Inf)\n    b0norm = norm(@view(B[:, 1]), Inf)\n    tau = 10/Anorm * (abstol * ((m+1)/ℯ)^(m+1) * sqrt(2*pi*(m+1)) /\n      (4*Anorm*b0norm))^(1/m)\n    verbose && println(\"Initial time step unspecified, chosen to be $tau\")\n  end\n  # Initialization\n  n = size(U, 1)\n  sort!(ts); tend = ts[end]\n  p = size(B, 2) - 1\n  @assert length(ts) == size(U, 2) \"Dimension mismatch\"\n  @assert n == size(A, 1) == size(A, 2) == size(B, 1) \"Dimension mismatch\"\n  if caches == nothing\n    u = Vector{T}(undef, n)              # stores the current state\n    W = Matrix{T}(undef, n, p+1)         # stores the w vectors\n    P = Matrix{T}(undef, n, p+2)         # stores output from phiv!\n    Ks = KrylovSubspace{T}(n, m)  # stores output from arnoldi!\n    phiv_cache = nothing         # cache used by phiv!\n  else\n    u, W, P, Ks, phiv_cache = caches\n    @assert length(u) == n && size(W, 1) == n && size(P, 1) == n \"Dimension mismatch\"\n    # W and P may be bigger than actually needed\n    W = @view(W[:, 1:p+1])\n    P = @view(P[:, 1:p+2])\n  end\n  copyto!(u, @view(B[:, 1])) # u(0) = b0\n  coeffs = ones(tType, p);\n  if adaptive # initialization step for the adaptive scheme\n    if ishermitian(A)\n      iop = 2 # does not have an effect on arnoldi!, just for flops estimation\n    end\n    if iszero(NA)\n      _A = convert(AbstractMatrix, A)\n      if isa(_A, SparseMatrixCSC)\n        NA = nnz(_A)\n      else\n        NA = count(!iszero, _A) # not constant operation, should be best avoided\n      end\n    end\n  end\n\n  t = 0.0       # current time\n  snapshot = 1  # which snapshot to compute next\n  while t < tend # time stepping loop\n    if t + tau > tend # last step\n      tau = tend - t\n    end\n    # Part 1: compute w0...wp using the recurrence relation (16)\n    copyto!(@view(W[:, 1]), u) # w0 = u(t)\n    @inbounds for l = 1:p-1 # compute cl = t^l/l!\n      coeffs[l+1] = coeffs[l] * t / l\n    end\n    @views @inbounds for j = 1:p\n      mul!(W[:, j+1], A, W[:, j])\n      for l = 0:p-j\n        axpy!(coeffs[l+1], B[:, j+l+1], W[:, j+1])\n      end\n    end\n    # Part 2: compute ϕp(tau*A)wp using Krylov, possibly with adaptation\n    arnoldi!(Ks, A, @view(W[:, end]); tol=tol, m=m, opnorm=opnorm, iop=iop, cache=u)\n    _, epsilon = phiv!(P, tau, Ks, p + 1; cache=phiv_cache, correct=correct, errest=true)\n    verbose && println(\"t = $t, m = $m, tau = $tau, error estimate = $epsilon\")\n    if adaptive\n      omega = (tend / tau) * (epsilon / abstol)\n      epsilon_old = epsilon; m_old = m; tau_old = tau\n      q = m/4; kappa = 2.0; maxtau = tend - t\n      while omega > delta # inner loop of Algorithm 3\n        m_new, tau_new, q, kappa = _phiv_timestep_adapt(\n          m, tau, epsilon, m_old, tau_old, epsilon_old, q, kappa,\n          gamma, omega, maxtau, n, p, NA, iop, opnorm(getH(Ks), 1), verbose)\n        m, m_old = m_new, m\n        tau, tau_old = tau_new, tau\n        # Compute ϕp(tau*A)wp using the new parameters\n        arnoldi!(Ks, A, @view(W[:, end]); tol=tol, m=m, opnorm=opnorm, iop=iop, cache=u)\n        _, epsilon_new = phiv!(P, tau, Ks, p + 1; cache=phiv_cache, correct=correct, errest=true)\n        epsilon, epsilon_old = epsilon_new, epsilon\n        omega = (tend / tau) * (epsilon / abstol)\n        verbose && println(\"  * m = $m, tau = $tau, error estimate = $epsilon\")\n      end\n    end\n    # Part 3: update u using (15)\n    lmul!(tau^p, copyto!(u, @view(P[:, end - 1])))\n    @inbounds for l = 1:p-1 # compute cl = tau^l/l!\n      coeffs[l+1] = coeffs[l] * tau / l\n    end\n    @views @inbounds for j = 0:p-1\n      axpy!(coeffs[j+1], W[:, j+1], u)\n    end\n    # Fill out all snapshots in between the current step\n    while snapshot <= length(ts) && t + tau >= ts[snapshot]\n      tau_snapshot = ts[snapshot] - t\n      u_snapshot = @view(U[:, snapshot])\n      phiv!(P, tau_snapshot, Ks, p + 1; cache=phiv_cache, correct=correct)\n      lmul!(tau_snapshot^p, copyto!(u_snapshot, @view(P[:, end - 1])))\n      @inbounds for l = 1:p-1 # compute cl = tau^l/l!\n        coeffs[l+1] = coeffs[l] * tau_snapshot / l\n      end\n      @views @inbounds for j = 0:p-1\n        axpy!(coeffs[j+1], W[:, j+1], u_snapshot)\n      end\n      snapshot += 1\n    end\n\n    t += tau\n  end\n\n  return U\nend\n# Helper functions for phiv_timestep!\nfunction _phiv_timestep_adapt(m, tau, epsilon, m_old, tau_old, epsilon_old, q, kappa,\n  gamma, omega, maxtau, n, p, NA, iop, Hnorm, verbose)\n  # Compute new m and tau (Algorithm 4)\n  if tau_old > tau\n    q = log(tau/tau_old) / log(epsilon/epsilon_old) - 1\n  end # else keep q the same\n  tau_new = tau * (gamma / omega)^(1/(q + 1))\n  tau_new = min(max(tau_new, tau/5), 2*tau, maxtau)\n  if m_old < m\n    kappa = (epsilon/epsilon_old)^(1/(m_old - m))\n  end # else keep kappa the same\n  m_new = m + ceil(Int, log(omega / gamma) / log(kappa))\n  m_new = min(max(m_new, div(3*m, 4), 1), Int(ceil(4*m / 3)))\n  verbose && println(\"  - Proposed new m: $m_new, new tau: $tau_new\")\n  # Compare costs of using new m vs new tau (23)\n  cost_tau = _phiv_timestep_estimate_flops(m, tau_new, n, p, NA, iop, Hnorm, maxtau)\n  cost_m = _phiv_timestep_estimate_flops(m_new, tau, n, p, NA, iop, Hnorm, maxtau)\n  verbose && println(\"  - Cost to use new m: $cost_m flops, new tau: $cost_tau flops\")\n  if cost_tau < cost_m\n    m_new = m\n  else\n    tau_new = tau\n  end\n  return m_new, tau_new, q, kappa\nend\nfunction _phiv_timestep_estimate_flops(m, tau, n, p, NA, iop, Hnorm, maxtau)\n  # Estimate flops for the update of W and u\n  flops_W = 2 * (p - 1) * (NA + n)\n  flops_u = (2 * p + 1) * n\n  # Estimate flops for arnoldi!\n  if iop == 0\n    iop = m\n  end\n  flops_matvec = 2 * m * NA\n  flops_vecvec = 0\n  for i = 1:m\n    flops_vecvec += 3 * min(i, iop)\n  end\n  # Estimate flops for phiv! (7)\n  MH = 44/3 + 2 * ceil(max(0.0, log2(Hnorm / 5.37)))\n  flops_phiv = round(Int, MH * (m + p)^3)\n\n  flops_onestep = flops_W + flops_u + flops_matvec + flops_vecvec + flops_phiv\n  return flops_onestep * Int(ceil(maxtau / tau))\nend\nfunction _phiv_timestep_caches(u_prototype, maxiter::Int, p::Int)\n  n = length(u_prototype); T = eltype(u_prototype)\n  u = similar(u_prototype)                      # stores the current state\n  W = Matrix{T}(undef, n, p+1)                         # stores the w vectors\n  P = Matrix{T}(undef, n, p+2)                         # stores output from phiv!\n  Ks = KrylovSubspace{T}(n, maxiter)            # stores output from arnoldi!\n  phiv_cache = PhivCache{T}(maxiter, p+1)       # cache used by phiv! (need +1 for error estimation)\n  return u, W, P, Ks, phiv_cache\nend\n", "meta": {"hexsha": "10e3995797ad46973d6dbdecff41126fe916ee88", "size": 26388, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/exponential_utils.jl", "max_stars_repo_name": "timkittel/OrdinaryDiffEq.jl", "max_stars_repo_head_hexsha": "f1492f26a84bd53f3f78bf2756f6ba5d0f0f284f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/exponential_utils.jl", "max_issues_repo_name": "timkittel/OrdinaryDiffEq.jl", "max_issues_repo_head_hexsha": "f1492f26a84bd53f3f78bf2756f6ba5d0f0f284f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/exponential_utils.jl", "max_forks_repo_name": "timkittel/OrdinaryDiffEq.jl", "max_forks_repo_head_hexsha": "f1492f26a84bd53f3f78bf2756f6ba5d0f0f284f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6754270696, "max_line_length": 116, "alphanum_fraction": 0.6285053812, "num_tokens": 9169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7501422524986705}}
{"text": "using FFTW\nusing Plots\n\nimport Plots: default\ndefault(show=false, reuse=true)\n\nENV[\"GKSwstype\"]=\"nul\"\n\nfunction signal_plot(i, signal1, signal2, out; filebase = \"out\",\n                     out_name = \"convolution\")\n    println(i)\n    n = length(signal1)\n    shift_signal = real([signal2[i:n-1];signal2[1:i]])\n    conv_sum = real(signal1).*shift_signal\n    plt = plot(real(signal1); label = \"signal\")\n    plt = plot!(plt, shift_signal; label = \"filter\")\n    plt = plot!(plt, zeros(n); label = \"area\", ribbon=(zeros(n),conv_sum))\n    plt = plot!(plt, real(out); label = out_name)\n    savefig(filebase*lpad(string(i),5,string(0))*\".png\")\nend\n\nfunction is_norm(signal)\n    if isapprox(sum(signal), 1.0)\n        return true\n    else\n        return false\n    end\nend\n\nfunction norm(signal)\n    return signal ./ sum(signal)\nend\n\n# TODO: better name than temp_signal\nfunction expectation_value(signal)\n    temp_signal = signal\n    if !is_norm(signal)\n        temp_signal = norm(signal)\n    end \n    expectation_value = 0\n    for i = 1:length(signal)\n        expectation_value += i*temp_signal[i]\n    end\n    return expectation_value\nend\n\nfunction covariance(signal1, signal2)\n    return expectation_value((signal1 .- expectation_value(signal1)).*\n                             (signal2 .- expectation_value(signal2)))\nend\n\nfunction conv_lin(signal1::Array{Complex{Float64},1},\n                  signal2::Array{Complex{Float64},1})\n    n = length(signal1)\n    out = Array{Complex{Float64},1}(undef,n)\n    rsum = 0\n\n    # time domain\n    for i = 1:n-1\n        # inner domain between signals\n        for j = 1:length(signal2)\n            if (j < length(signal1))\n                index = i-j\n                if i-j < 1\n                    index = length(signal2)+(i-j)\n                end\n                rsum += signal1[j] * signal2[(index)%(length(signal2))+1]\n            end\n        end\n        out[i] = rsum\n        rsum = 0\n    end\n\n    return out\nend\n\nfunction conv_fft(signal1::Array{Complex{Float64},1},\n                  signal2::Array{Complex{Float64},1})\n    return ifft(fft(signal1).*fft(signal2))\nend\n\nfunction conv_plot(signal1::Array{Complex{Float64},1},\n                   signal2::Array{Complex{Float64},1}; norm_factor = 1)\n    n = length(signal1)\n    out = zeros(Complex, n)\n    rsum = 0\n\n    # time domain\n    for i = 1:n-1\n        # inner domain between signals\n        for j = 1:length(signal2)\n            if (j < length(signal1))\n                index = j-i\n                if j-i < 1\n                    index = length(signal2)+(j-i)\n                end\n                rsum += signal1[j] * signal2[(index)%(length(signal2))+1]\n            end\n        end\n\n\n        out[i] = rsum / norm_factor\n        rsum = 0\n\n        signal_plot(i, signal1, signal2, out)\n\n    end\n\n    return out\nend\n\nfunction corr_lin(signal1::Array{Complex{Float64},1},\n                  signal2::Array{Complex{Float64},1})\n    n = length(signal1)\n    out = Array{Complex{Float64},1}(undef,n)\n    rsum = 0\n\n    for i = 1:n-1\n        for j = 1:length(signal2)\n            if j < length(signal1)\n                rsum += conj(signal1[j]) * signal2[(j+i)%(length(signal2))+1]\n            end\n        end\n        out[i] = rsum\n        rsum = 0\n    end\n\n    return out\nend\n\nfunction corr_plot(signal1::Array{Complex{Float64},1},\n                   signal2::Array{Complex{Float64},1}; norm_factor = 1)\n    n = length(signal1)\n    out = zeros(Complex, n)\n    rsum = 0\n\n    for i = 1:n-1\n        for j = 1:length(signal2)\n            if j < length(signal1)\n                rsum += conj(signal1[j]) * signal2[(j+i)%(length(signal2))+1]\n            end\n\n        end\n\n        out[i] = rsum / norm_factor\n        rsum = 0\n\n        signal_plot(i, signal1, signal2, out)\n\n    end\n\n    return out\nend\n\nfunction main()\n    x = [exp(-((i-50)/100)^2/.01) + 0im for i = 1:100]\n    out_conv = conv_plot(x,x, norm_factor=20)\n\n\n#=\n    x = zeros(Complex{Float64},100)\n    x[40:60] .= 1\n\n    y = copy(x)\n    y[40:60] .= [float(1-i*0.05) for i = 0:20]\n\n    # Make plots\n    out_corr = corr_plot(x,y;norm_factor=20; filebase = \"corr_out\")\n    out_conv = conv_plot(x,y, norm_factor=20)\n=#\nend\n", "meta": {"hexsha": "905e207241d3c6f3b82b9c992427c8cb9b3e64c8", "size": 4150, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "convolutions/conv.jl", "max_stars_repo_name": "mika314/simuleios", "max_stars_repo_head_hexsha": "0b05660c7df0cd6e31eb5e70864cbedaec29b55a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "convolutions/conv.jl", "max_issues_repo_name": "mika314/simuleios", "max_issues_repo_head_hexsha": "0b05660c7df0cd6e31eb5e70864cbedaec29b55a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "convolutions/conv.jl", "max_forks_repo_name": "mika314/simuleios", "max_forks_repo_head_hexsha": "0b05660c7df0cd6e31eb5e70864cbedaec29b55a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1279069767, "max_line_length": 77, "alphanum_fraction": 0.5590361446, "num_tokens": 1190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7501422489260561}}
{"text": "# 2D Heat Diffusion\n# LBM\n#\n# Hongyang Zhou, hyzhou@umich.edu 05/01/2019\n\n# Problem Description\n# A two dimensional square slab is subjected to the given boundary conditions.\n# Initially the slab was at zero temperature. For time>0, the boundary at x = 0\n# is subjected to a high temperature of value 1.0 and other boundaries are kept\n# as before. The length of the domain is 100 units. Determine the temperature\n# distribution in the slab at time = 400 units (s).\n# Thermal diffusivity is 0.25 and xl = yl = 1.0.\n\nusing PyPlot\n\nfunction solveHeatDiffusion2D()\n# Parameters\nnD = 2             # Dimension of the system\nΔx = 1.0           # Discretized space interval\nΔt = 1.0           # Discretized time interval\nα  = 0.25          # Thermal diffusivity\nω  = inv(nD*Δt*α/Δx^2 + 0.5)  # Relaxation coefficient\nTotalTime = 400.   # Total simulation time\nnT = Int(TotalTime/Δt)        # Total timesteps\nnx = 100           # Number of total space intervals\nny = 100\nw  = [0.25,0.25,0.25,0.25]    # Lattice weights\nnw = size(w,1)\n\nTleft  = 1.0       # Left boundary temperature\nTright = 0.0       # Right boundary temperature\nTtop   = 0.0       # Top boundary temperature\nTbot   = 0.0       # Bottom boundary temperature\n\nheatflux  = 100.   # Constant heat flux, [W/mK]\nk_thermal = 20.    # Thermal conductivity, [W/mK]\n\nBCDirichlet,BCRiemann = 1,2 # Constants for different boundary types\nBCtype = 1         # Type of boundary conditions\n\nUseSource = false  # Logical for calculating source terms\nif UseSource\n   qg = 1.0        # Rate of heat generation per volume\n   ρ  = 1.0        # Density\n   C  = 1.0        # Heat capacity\n   source = qg/(ρ*C) # Source term. Note that α=k/(ρC)\nend\n\n# Initializations\nf   = zeros(nw,nx,ny)\nfeq = zeros(nw,nx,ny) # This can be moved inside the main loop!\nT   = zeros(1,nx,ny)\nt   = 0.0     # Current simulation time\n\n# Advance\nwhile t < TotalTime\n\n   # Calculate equilibrium distribution\n   for iw = 1:nw\n      feq[iw,:,:] .= w[iw].*T[1,:,:]\n   end\n\n   # Collision\n   for iw = 1:nw\n      f[iw,:,:] .= (1.0-ω).*f[iw,:,:] .+ ω.*feq[iw,:,:]\n   end\n   if UseSource\n      for iw = 1:nw\n         f[iw,:,:] .+= Δt*w[iw]*source\n      end\n   end\n\n   # Streaming\n   f[1,2:nx,:]   .= f[1,1:nx-1,:]\n   f[2,1:nx-1,:] .= f[2,2:nx,:]\n   f[3,:,2:ny]   .= f[3,:,1:ny-1]\n   f[4,:,1:ny-1] .= f[4,:,2:ny]\n\n   # Remaining BCs\n   if BCtype == BCDirichlet\n      f[1,1,:] .= (w[1]+w[2])*Tleft  .- f[2,1,:]\n      f[2,nx,:].= (w[1]+w[2])*Tright .- f[1,nx,:]\n      f[3,:,1] .= (w[3]+w[4])*Ttop   .- f[4,:,1]\n      f[4,:,ny].= (w[3]+w[4])*Tbot   .- f[3,:,ny]\n   elseif BCtype == BCRiemann\n      # This is not complete, and not flexible enough!\n      f[1,1,:] .= f[1,2,:] .- heatflux*Δx/k_thermal\n      #f[2,nx,:] = f[2,nx-1,:] .- heatflux*Δx/k_thermal\n   end\n\n   # Calculate macroscopic T\n   T .= sum(f, dims=1)\n\n   t += Δt\nend\n\n\n# Visualization\nx = range(0,stop=nx-1,length=nx)\ny = range(0,stop=ny-1,length=ny)\n\ncontourf(x,y,T[1,:,:]); colorbar()\ntitle(\"2D Heat Diffusion in a Plate\")\nxlabel(\"x\")\nylabel(\"y\")\ngrid(\"on\")\n\n# 1D cut plot\n#plot(0:nx-1,T[1,:,50],linestyle=\"-\",marker=\"o\",label=\"LBM\")\n#xlim(0,30)\n\nend\n", "meta": {"hexsha": "8e2b9ebb534d38ed76c6224d4e20c11cd3154e89", "size": 3122, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Diffusion/2D_box_oneFile/HeatDiffusion2D.jl", "max_stars_repo_name": "henry2004y/LBM_tutorial", "max_stars_repo_head_hexsha": "fb733cf3de084370bb5ead9a57268ee2daac7ec4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-10-15T07:17:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T16:25:17.000Z", "max_issues_repo_path": "Diffusion/2D_box_oneFile/HeatDiffusion2D.jl", "max_issues_repo_name": "henry2004y/LBM_tutorial", "max_issues_repo_head_hexsha": "fb733cf3de084370bb5ead9a57268ee2daac7ec4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Diffusion/2D_box_oneFile/HeatDiffusion2D.jl", "max_forks_repo_name": "henry2004y/LBM_tutorial", "max_forks_repo_head_hexsha": "fb733cf3de084370bb5ead9a57268ee2daac7ec4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6283185841, "max_line_length": 79, "alphanum_fraction": 0.5948110186, "num_tokens": 1154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7501212077664539}}
{"text": "using Random\nusing LinearAlgebra\nusing Statistics\nusing Optim\nusing DataFrames\nusing CSV\nusing HTTP\nusing GLM\nusing FreqTables\nusing ForwardDiff # for bonus at the very end\n\nfunction wrapall()\n\nurl = \"https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2020/master/ProblemSets/PS3-gev/nlsw88w.csv\"\ndf = CSV.read(HTTP.get(url).body)\nX = [df.age df.white df.collgrad]\nZ = hcat(df.elnwage1, df.elnwage2, df.elnwage3, df.elnwage4, \n         df.elnwage5, df.elnwage6, df.elnwage7, df.elnwage8)\ny = df.occupation\n\nfunction mlogit_with_Z(theta, X, Z, y)\n        \n        alpha = theta[1:end-1]\n        gamma = theta[end] # Indexing Z variables at the end\n        K = size(X,2) # N Variables\n        J = length(unique(y))\n        N = length(y)\n        bigY = zeros(N,J) # Same as PS2.jl ...\n        for j=1:J\n            bigY[:,j] = y.==j\n        end\n        bigAlpha = [reshape(alpha,K,J-1) zeros(K)]\n        \n        T = promote_type(eltype(X),eltype(theta))\n        num   = zeros(T,N,J)\n        dem   = zeros(T,N)\n        for j=1:J\n            num[:,j] = exp.(X*bigAlpha[:,j] .+ (Z[:,j] .- Z[:,J])*gamma)\n            dem .+= num[:,j]\n        end\n        \n        P = num./repeat(dem,1,J)\n        \n        loglike = -sum( bigY.*log.(P) )\n        \n        return loglike\n    end\n\nstartvals = [2*rand(7*size(X,2)).-1; .1] # 7 == J - 1\ntd = TwiceDifferentiable(theta -> mlogit_with_Z(theta, X, Z, y), startvals; autodiff = :forward)\n# run the optimizer\ntheta_hat_optim_ad = optimize(td, startvals, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\ntheta_hat_mle_ad = theta_hat_optim_ad.minimizer\n# evaluate the Hessian at the estimates\nH  = Optim.hessian!(td, theta_hat_mle_ad)\ntheta_hat_mle_ad_se = sqrt.(diag(inv(H)))\nprintln([theta_hat_mle_ad theta_hat_mle_ad_se]) # these standard errors match Stata\n\nfunction nested_logit_with_Z(theta, X, Z, y, nesting_structure)\n        \n        alpha = theta[1:end-3]\n        lambda = theta[end-2:end-1]\n        gamma = theta[end]\n        K = size(X,2)\n        J = length(unique(y))\n        N = length(y)\n        bigY = zeros(N,J)\n        for j=1:J\n            bigY[:,j] = y.==j\n        end\n        bigAlpha = [repeat(alpha[1:K],1,length(nesting_structure[1])) repeat(alpha[K+1:2K],1,length(nesting_structure[2])) zeros(K)]\n        \n        T = promote_type(eltype(X),eltype(theta))\n        num   = zeros(T,N,J)\n        lidx  = zeros(T,N,J)\n        dem   = zeros(T,N)\n        for j=1:J\n            if j in nesting_structure[1]\n                lidx[:,j] = exp.( (X*bigAlpha[:,j] .+ (Z[:,j] .- Z[:,J])*gamma)./lambda[1] )\n            elseif j in nesting_structure[2]\n                lidx[:,j] = exp.( (X*bigAlpha[:,j] .+ (Z[:,j] .- Z[:,J])*gamma)./lambda[2] )\n            else\n                lidx[:,j] = exp.(zeros(N))\n            end\n        end\n        for j=1:J\n            if j in nesting_structure[1]\n                num[:,j] = lidx[:,j].*sum(lidx[:,nesting_structure[1][:]];dims=2).^(lambda[1]-1)\n            elseif j in nesting_structure[2]\n                num[:,j] = lidx[:,j].*sum(lidx[:,nesting_structure[2][:]];dims=2).^(lambda[2]-1)\n            else\n                num[:,j] = lidx[:,j]\n            end\n            dem .+= num[:,j]\n        end\n        \n        P = num./repeat(dem,1,J)\n        \n        loglike = -sum( bigY.*log.(P) )\n        \n        return loglike\n    end\nnesting_structure = [[1 2 3], [4 5 6 7]] # This is a list with the mentioned nested structure\n\nstartvals = [2*rand(2*size(X,2)).-1; \n\t\t1; 1; .1 # Unclear\n\t\t]    \n# Same as before\ntd = TwiceDifferentiable(theta -> nested_logit_with_Z(theta, X, Z, y, nesting_structure), startvals; autodiff = :forward)\n# run the optimizer\nnlogit_theta_hat_optim_ad = optimize(td, startvals, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\nnlogit_theta_hat_mle_ad = nlogit_theta_hat_optim_ad.minimizer\n# evaluate the Hessian at the estimates\nH  = Optim.hessian!(td, nlogit_theta_hat_mle_ad)\nnlogit_theta_hat_mle_ad_se = sqrt.(diag(inv(H)))\nprintln([nlogit_theta_hat_mle_ad nlogit_theta_hat_mle_ad_se]) # these standard errors match Stata\n\n    return nothing\nend\nwrapall()\n", "meta": {"hexsha": "b04d40cd823e72d90c039dbf8a344daf28d34c53", "size": 4160, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/Sol_PS3.jl", "max_stars_repo_name": "gpetrini/OU_Econometrics_III", "max_stars_repo_head_hexsha": "81b5f35999d6b10f65f84b3344593d1c28acf1e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSets/Sol_PS3.jl", "max_issues_repo_name": "gpetrini/OU_Econometrics_III", "max_issues_repo_head_hexsha": "81b5f35999d6b10f65f84b3344593d1c28acf1e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/Sol_PS3.jl", "max_forks_repo_name": "gpetrini/OU_Econometrics_III", "max_forks_repo_head_hexsha": "81b5f35999d6b10f65f84b3344593d1c28acf1e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3801652893, "max_line_length": 141, "alphanum_fraction": 0.5860576923, "num_tokens": 1294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320035, "lm_q2_score": 0.8198933447152498, "lm_q1q2_score": 0.7501211983651123}}
{"text": "using Plots, Printf, LinearAlgebra\n\n# enable plotting by default\nif !@isdefined do_visu; do_visu = true end\n\n@views function diffusion_1D(; do_visu=true)\n    # Physics\n    lx     = 10.0        # domain size\n    D      = 1.0         # diffusion coefficient\n    ttot   = 0.6         # total simulation time\n    # Numerics\n    nx     = 256         # numerical grid resolution\n    # Derived numerics\n    dx     = lx/nx       # grid size\n    dt     = dx^2/D/2.1  # time step (obeys CFL condition)\n    xc     = LinRange(dx/2, lx-dx/2, nx)\n    # Array allocation\n    qH     = zeros(nx-1) # on staggered grid\n    dHdt   = zeros(nx-2) # normal grid, without boundary points\n    # Initial condition\n    H0     = exp.(-(xc.-lx/2).^2)\n    H      = copy(H0)\n    t = 0.0; it = 0\n    # Physical time loop\n    while t<ttot\n        qH         .= -D*diff(H)/dx         # flux\n        dHdt       .=  -diff(qH)/dx         # rate of change\n        H[2:end-1] .= H[2:end-1] .+ dt*dHdt # update rule, sets the BC as H[1]=H[end]=0\n        t += dt; it += 1\n    end\n    # Analytic solution\n    Hana = 1/sqrt(4*(ttot+1/4)) * exp.(-(xc.-lx/2).^2 /(4*(ttot+1/4)))\n    @printf(\"Total time = %1.2f, time steps = %d, error vs analytic = %1.2e \\n\", round(ttot, sigdigits=2), it, norm(H-Hana))\n    # Visualize\n    if do_visu\n        plot(xc, H0, linewidth=3); display(plot!(xc, H, legend=false, framestyle=:box, linewidth=3, xlabel=\"lx\", ylabel=\"H\", title=\"explicit diffusion (nt=$it)\"))\n    end\n    return xc, H0\nend\n\ndiffusion_1D(; do_visu=do_visu);\n", "meta": {"hexsha": "eafaf4fd9bb4a87c74869769830aff5e773d407a", "size": 1518, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/diffusion_1D_expl.jl", "max_stars_repo_name": "luraess/julia-parallel-course-EGU21", "max_stars_repo_head_hexsha": "d7f0616e07f12deac45a635410d846e33eec0739", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2021-03-26T08:25:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T15:10:27.000Z", "max_issues_repo_path": "scripts/diffusion_1D_expl.jl", "max_issues_repo_name": "speedshi/julia-parallel-course-EGU21", "max_issues_repo_head_hexsha": "b700a9ad0d1d14f26e0590ce41a8e63380a1df15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-04-14T17:33:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T10:19:26.000Z", "max_forks_repo_path": "scripts/diffusion_1D_expl.jl", "max_forks_repo_name": "speedshi/julia-parallel-course-EGU21", "max_forks_repo_head_hexsha": "b700a9ad0d1d14f26e0590ce41a8e63380a1df15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-04-21T13:09:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-29T05:59:37.000Z", "avg_line_length": 36.1428571429, "max_line_length": 162, "alphanum_fraction": 0.5546772069, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7501211961304288}}
{"text": "\"\"\"\nSolve the constrained least-squares problem\n\n    minimize  ||Ax-b||₂  st  0 ≤ x ≤ u.\n\nRephrases the problem as linear SOC program:\n\n    minimize  [0]'[x]  st  [A 0 I][x] = [b] m\n              [0] [r]             [t]\n                                  [r]\n                            n 1 m\n\n                               x, (t,r) ∈  Rn₊ x (Qn₊)\n\nwith dimensions  len(x) = n  len(b) = m\n                 len(r) = m\n\nSolve using ECOS, which formulates linear SOC programs as\n\n    minimize  c'x  st  A*x=b, G*x + s = h, s in cone\n\"\"\"\nfunction lsbox(Ain::Matrix{Float64}, b::Vector{Float64},\n               u::Vector{Float64}=zeros(0); kwargs...)\n    m, n = size(Ain)\n    nu = length(u)       # number of vars x with upper bound\n    n_ecos = n + 1 + m   # number of vars == len(x)\n    p = m                # number of equality constraints == len(b)\n    l = n + nu           # number of vars in positive orthant\n    ncones = 1           # number of SOC cones\n    q = [1+m]            # number of vars in the SOC\n    e = 0                # number of exponential cones\n\n    GG = [ sparse(-1.0I,n ,n)  spzeros(n ,1)       spzeros(n ,m)\n           sparse(+1.0I,nu,n)  spzeros(nu,1)       spzeros(nu,m)\n                spzeros(1 ,n)      -1.0            spzeros( 1,m)\n                spzeros(m ,n)  spzeros(m ,1)  sparse(-1.0I,m ,m)]\n    G = ECOS.ECOSMatrix(GG)\n    h = vcat(zeros(n), u,   0,  zeros(m))\n    m_ecos =       n + nu + 1 + m\n    A = ECOS.ECOSMatrix([Ain spzeros(m,1) sparse(1.0I,m,m)])\n    c = zeros(n_ecos); c[n+1] = 1.0\n\n    ecos_ptr = ECOS.setup(n_ecos, m_ecos, p, l, ncones, q, e,\n                          G, A, c, h, b; kwargs...)\n    ECOS.solve(ecos_ptr)\n    # finalizer(cleanup!, problem)\n\n    # Extract the primal and dual solutions of the ECOS problem\n    ecos_prob = unsafe_wrap(Array, ecos_ptr, 1)[1]\n    xtr = unsafe_wrap(Array, ecos_prob.x, n_ecos)[:]\n\n    ECOS.cleanup(ecos_ptr, 0)\n    x = xtr[1:n]\n    t = xtr[n+1] # t = norm(r)\n    r = xtr[n+2:end]\n    return x, r, t\nend\n", "meta": {"hexsha": "2ba3a4e6c21688c042beb1ff1596c0cdc71c3ee9", "size": 1995, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lsbox.jl", "max_stars_repo_name": "mpf/ECOSProblems.jl", "max_stars_repo_head_hexsha": "05fb3c057f907b3bfc3ad6b88e9cd37f831ae80c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lsbox.jl", "max_issues_repo_name": "mpf/ECOSProblems.jl", "max_issues_repo_head_hexsha": "05fb3c057f907b3bfc3ad6b88e9cd37f831ae80c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lsbox.jl", "max_forks_repo_name": "mpf/ECOSProblems.jl", "max_forks_repo_head_hexsha": "05fb3c057f907b3bfc3ad6b88e9cd37f831ae80c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-03T22:43:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-03T22:43:08.000Z", "avg_line_length": 34.3965517241, "max_line_length": 67, "alphanum_fraction": 0.494235589, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7501211959089191}}
{"text": "using Manopt, Manifolds, Plots\n#\n# Settings\nresultsFolder = \"examples/Total_Variation/S1_TV/\"\nexperimentName = \"S1_TV12\"\nplotAndExportResult = true\n\nn = 500\nσ = 0.2\nα = 0.5\nβ = 1.0\n\ndataColor = RGBA{Float64}(colorant\"#BBBBBB\")\ns2dColor = RGBA{Float64}(colorant\"#EE7733\") # data Color: Tol Vibrant Orange\ns1Color = RGBA{Float64}(colorant\"#0077BB\") # control point data color: Tol Virbant Blue\nnColor = RGBA{Float64}(colorant\"#33BBEE\") # tangent vector: Tol Vibrant Teal\n\nif !isdir(resultsFolder)\n    mkdir(resultsFolder)\nend\n#\n# Manifolds and Data\nM = Circle()\nN = PowerManifold(M, n)\nf = artificial_S1_signal(n)\nxCompare = f\nfn = exp.(Ref(M),f, random_tangent.(Ref(M),f, Val(:Gaussian), σ))\ndata = fn\nt = range(0.0, 1.0, length = n)\n\nif plotAndExportResult\n    scene = scatter(\n        t,\n        f,\n        markersize = 2,\n        markercolor = dataColor,\n        markerstrokecolor = dataColor,\n        lab = \"original\",\n    )\n    scatter!(\n        scene,\n        t,\n        fn,\n        markersize = 2,\n        markercolor = nColor,\n        markerstrokecolor = nColor,\n        lab = \"noisy\",\n    )\n    yticks!(\n        [-π, -π/2, 0, π/2, π],\n        [raw\"$-\\pi$\",raw\"$-\\frac{\\pi}{2}$\",raw\"$0$\",raw\"$\\frac{\\pi}{2}$\",raw\"$\\pi$\"]\n    )\n    png(scene, \"$(resultsFolder)$(experimentName)-original.png\")\nend\n#\n# Setup and Optimize\nF = x -> costL2TVTV2(N, data, α, β, x)\nproxes = [\n    (λ, x) -> prox_distance(N, λ, data, x,2),\n    (λ, x) -> prox_TV(N, α * λ, x),\n    (λ, x) -> prox_TV2(N, β * λ, x),\n]\n\no = cyclic_proximal_point(\n    N,\n    F,\n    proxes,\n    data;\n    λ = i -> π / (2*i),\n    debug = Dict(\n        :Stop => DebugStoppingCriterion(),\n        :Step => DebugEvery(\n            DebugGroup([\n                DebugIteration(),\n                DebugDivider(),\n                DebugProximalParameter(),\n                DebugDivider(),\n                DebugCost(),\n                DebugDivider(),\n                DebugChange(),\n                DebugDivider(\"\\n\"),\n            ]),\n            1000,\n        ),\n        :Start => DebugDivider(\"Starting the solver\\n\"),\n    ),\n    record = [:Iteration, :Cost, :Change, :Iterate],\n    return_options = true,\n)\nfR = get_solver_result(o)\nr = get_record(o)\n#\n# Result\nif plotAndExportResult\n    scene = scatter(\n        t,\n        f,\n        markersize = 2,\n        markercolor = dataColor,\n        markerstrokecolor = dataColor,\n        lab = \"original\",\n    )\n    scatter!(\n        scene,\n        t,\n        fR,\n        markersize = 2,\n        markercolor = nColor,\n        markerstrokecolor = nColor,\n        lab = \"reconstruction\",\n    )\n    yticks!(\n        [-π, -π/2, 0, π/2, π],\n        [raw\"$-\\pi$\",raw\"$-\\frac{\\pi}{2}$\",raw\"$0$\",raw\"$\\frac{\\pi}{2}$\",raw\"$\\pi$\"]\n    )\n    png(scene, \"$(resultsFolder)$(experimentName)-result.png\")\nend\n\nprint(\"MSE (input):  \", 1 / n * distance(N, xCompare, data)^2, \"\\n\")\nprint(\"MSE (result): \", 1 / n * distance(N, xCompare, fR)^2, \"\\n\")\n", "meta": {"hexsha": "a810c5886dd3eed1f7925201d0ad9bfcf1bfe1ba", "size": 2927, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Total_Variation/S1_TV12_CPPA.jl", "max_stars_repo_name": "matbesancon/Manopt.jl", "max_stars_repo_head_hexsha": "25671e4c56728b7ab3ce82321d063308095750da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Total_Variation/S1_TV12_CPPA.jl", "max_issues_repo_name": "matbesancon/Manopt.jl", "max_issues_repo_head_hexsha": "25671e4c56728b7ab3ce82321d063308095750da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Total_Variation/S1_TV12_CPPA.jl", "max_forks_repo_name": "matbesancon/Manopt.jl", "max_forks_repo_head_hexsha": "25671e4c56728b7ab3ce82321d063308095750da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1900826446, "max_line_length": 87, "alphanum_fraction": 0.5377519645, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7501211944495189}}
{"text": "# Integrates the following set of equations outwards:\n# dy1/dx =                y2\n# dy2/dx = C1 * y1 + C2 * y2\nfunction sch_rk4_step!(\n    rmesh::Array{Float64,1}, # Grid\n    y0::Array{Float64,1}, # Initial condition\n    C1::Array{Float64,1},\n    C2::Array{Float64,1},\n    C1mid::Array{Float64,1},\n    C2mid::Array{Float64,1},\n    y1::Array{Float64,1},\n    y2::Array{Float64,1}, # Solution y1 and y2\n    maxval_stop::Float64,  # Maximum value (if y1 > max_val, the integration stops)\n)\n\n    Neqn = size(y0,1)  # should be hardcoded at 2 ?\n    @assert Neqn == 2\n\n    dym = zeros(Float64,2)\n    dyt = zeros(Float64,2)\n    yt = zeros(Float64,2)\n    dydx = zeros(Float64,2)\n    y = zeros(Float64, Neqn)\n\n    Nr = size(rmesh,1)\n    y = copy(y0)\n    y1[1] = y[1]\n    y2[1] = y[2]\n    \n    for i in 2:Nr\n        # rk4 step size\n        h = rmesh[i] - rmesh[i-1]\n\n        # k1, evaluate F\n        dydx[1] = y[2]\n        dydx[2] = C1[i-1] * y[1] + C2[i-1] * y[2]\n        #\n        yt = y + h/2 * dydx  # yi + h/2*k1\n        # k2, evaluate F at x_i + h/2 and yi + k1/2\n        dyt[1] = yt[2]\n        dyt[2] = C1mid[i-1] * yt[1] + C2mid[i-1] * yt[2]\n        #\n        yt = y + h/2 * dyt # yi + h/2*k2\n        #\n        dym[1] = yt[2]\n        dym[2] = C1mid[i-1] * yt[1] + C2mid[i-1] * yt[2]\n        #\n        yt = y + h * dym\n        dym = dyt + dym\n        dyt[1] = yt[2]\n        dyt[2] = C1[i] * yt[1] + C2[i] * yt[2]\n        #\n        y = y + h/6 * (dydx + dyt + 2*dym)\n        #\n        y1[i] = y[1]\n        y2[i] = y[2]\n\n        # The integration stops at R(imax)\n        if abs(y[1]) >= maxval_stop\n            imax = i\n            return imax\n        end\n    end\n    imax = Nr\n    return imax\nend", "meta": {"hexsha": "0f666c0980b73f68b6afa059a8645806f8f8ff73", "size": 1693, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dftatom/sch_rk4_step.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "dftatom/sch_rk4_step.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dftatom/sch_rk4_step.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 25.6515151515, "max_line_length": 83, "alphanum_fraction": 0.4689899587, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900945711678, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7501211823704744}}
{"text": "using LinearAlgebra\nusing JLD2\nimport StatisticalNonlocality: ou_transition_matrix\nimport StatisticalNonlocality: fourier\n\nfilename = \"three_state.jld2\"\n\nn = 2\nM = ou_transition_matrix(n)\n\nΛ, V = eigen(M)\nΛ, W = eigen(M')\n\n# Right eigenvectors\nV³ = round.(V[:, 1] ./ V[1, 1])\nV² = round.(V[:, 2] ./ V[1, 2])\nV¹ = round.(V[:, 3] ./ V[1, 3])\n\n# Left eigenvectors\nW³ = round.(W[:, 1] ./ W[1, 1])\nW² = round.(W[:, 2] ./ W[1, 2])\nW¹ = round.(W[:, 3] ./ W[1, 3])\n\nW[:, 1] .= W¹\nW[:, 2] .= -W²\nW[:, 3] .= W³\n\nU = [-1 0 0; 0 0 0; 0 0 1] # advection operator structure\nW * U * inv(W)\n\nN = 128\n\nD, x = fourier(N, a = 0, b = 2π)\n\nγ = 1.0 # 1/ γ is the eddy timescale\nU = 1.0\nκ = 1.0\n\nfluxkernel =\n    -U * inv(κ .* D^2 - γ * I - U * D * inv(κ .* D^2 - 2 * γ * I) * U * D) * U\nλ = eigvals(fluxkernel)\nσ = svdvals(fluxkernel)\n\n\ndata_directory = \"data\"\nmkpath(data_directory)\nfilepath = data_directory * \"/\" * filename\nif isfile(filepath)\n    rm(filepath)\nend\n\nfile = jldopen(filepath, \"a+\")\n\nfile[\"kernel\"] = fluxkernel\nfile[\"eigenvalues\"] = λ\nfile[\"singularvalues\"] = σ\n\nclose(file)\n", "meta": {"hexsha": "118794b1afa967e2a74862762c8a4b5d8baa001d", "size": 1071, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/three_state.jl", "max_stars_repo_name": "sandreza/StatisticalNonlocality", "max_stars_repo_head_hexsha": "0e58dcd6a1a8a8c2594ffe428760520556211aa9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/three_state.jl", "max_issues_repo_name": "sandreza/StatisticalNonlocality", "max_issues_repo_head_hexsha": "0e58dcd6a1a8a8c2594ffe428760520556211aa9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-07T18:48:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-07T18:48:00.000Z", "max_forks_repo_path": "examples/three_state.jl", "max_forks_repo_name": "sandreza/StatisticalNonlocality", "max_forks_repo_head_hexsha": "0e58dcd6a1a8a8c2594ffe428760520556211aa9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.1525423729, "max_line_length": 78, "alphanum_fraction": 0.5882352941, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876286, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7501206254864328}}
{"text": "using Plots\nusing Zygote\nusing LaTeXStrings\n\n\nvecindario(;x₀, ϵ=2.0, Δ=0.05) = x₀ - ϵ:Δ:x₀ + ϵ\n\nf(x) = sin(5x) - cos(3x)\n\nx₀ = 10\nx = vecindario(x₀=x₀);\n\nf₁ = f'(x₀)\nf₂ = f''(x₀)\n\ny = f.(x);\ny = hcat(y, ones(length(y)) .* f(x₀))\ny = hcat(y, @. y[:, end] + (x - x₀) * f₁)\ny = hcat(y, @. y[:, end] + (x - x₀)^2 * f₂)\n\ngr(size=(800, 800))\np = plot(x, y[:,1], label=L\"f(x)\")\nplot!(p, x, y[:,2], label=\"Orden cero\")\nplot!(p, x, y[:,3], label=\"Primer orden\")\nplot!(p, x, y[:,4], label=\"Segundo orden\")\nplot!(p, [x₀], [f(x₀)], mark=:cirle, label=L\"x_0\")\ntitle!(\"Aproximación por series de Taylor\")\nxlabel!(p, L\"x\")\nylabel!(p, L\"f(x)\")\nxlims!(p, (x[1], x[end]))\n\nsavefig(p, \"Taylor_borrar.png\")", "meta": {"hexsha": "c55b0bb8bd7ecb08fdd5ce292e3dc34cca78cf60", "size": 686, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "projects/Taylor/Taylor.jl", "max_stars_repo_name": "ccaballeroh/JuliaCORE21", "max_stars_repo_head_hexsha": "4a2fca8184194d5a9cc51da4f4b60cfa2811881d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-14T04:01:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T04:01:11.000Z", "max_issues_repo_path": "projects/Taylor/Taylor.jl", "max_issues_repo_name": "ccaballeroh/Julia_CORE2021", "max_issues_repo_head_hexsha": "4a2fca8184194d5a9cc51da4f4b60cfa2811881d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/Taylor/Taylor.jl", "max_forks_repo_name": "ccaballeroh/Julia_CORE2021", "max_forks_repo_head_hexsha": "4a2fca8184194d5a9cc51da4f4b60cfa2811881d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4375, "max_line_length": 50, "alphanum_fraction": 0.5466472303, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768144, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7501206137021306}}
{"text": "\"\"\"\n    Module Basis2D\nIncludes DG core functions for evaluating 2D bases on quads\n\"\"\"\nmodule Basis2D\n\nexport vandermonde2D, grad_vandermonde2D\nexport chebyshev2D, equidistant_nodes2D, gauss_quad2D\nexport dPhi2D\n\nimport Basis1D\nusing LinearAlgebra, SparseArrays\n\n\"\"\"\n    vandermonde2D(p, x, y)\nReturn the 2D vandermonde matrix - the order 0:p Legendre polynomials\nevaluated at 2D nodes (x,y)\n\"\"\"\nfunction vandermonde2D(p, x, y)\n    V = Array{Float64,4}(undef,length(x),length(y),p+1,p+1)\n    lx = Basis1D.vandermonde1D(p, x)\n    ly = Basis1D.vandermonde1D(p, y)\n    for ipy = 1:p+1\n        for ipx = 1:p+1\n            V[:,:,ipx,ipy] = lx[:,ipx]*(ly[:,ipy]')\n        end\n    end\n    return V\nend\n\n\"\"\"\n    grad_vandermonde2D(p, x, y)\nReturn the gradient of the order 0:p Legendre polynomials\nevaluated at 2D nodes (x,y)\n\"\"\"\nfunction grad_vandermonde2D(p, x, y)\n    dV = Array{Float64,5}(undef, length(x),length(y), p+1,p+1, 2)\n    lx = Basis1D.vandermonde1D(p, x)\n    ly = Basis1D.vandermonde1D(p, y)\n    dlx = Basis1D.grad_vandermonde1D(p, x)\n    dly = Basis1D.grad_vandermonde1D(p, y)\n    # Derivative wrt x\n    for ipy = 1:p+1\n        for ipx = 1:p+1\n            dV[:,:,ipx,ipy,1] = dlx[:,ipx]*(ly[:,ipy]')\n        end\n    end\n    # Derivative wrt y\n    for ipy = 1:p+1\n        for ipx = 1:p+1\n            dV[:,:,ipx,ipy,2] = lx[:,ipx]*(dly[:,ipy]')\n        end\n    end\n    return dV\nend\n\n\"\"\"\n    gauss_quad2D(p)\nReturn the 2D Gaussian quadrature points and weights (x,w) of order p on the domain [-1,1]^2\n\"\"\"\nfunction gauss_quad2D(p)\n    (x1D,w1D) = Basis1D.gauss_quad(p)\n    n = length(x1D)\n    x2D = Array{Float64,3}(undef, 2, n,n)\n    w2D = Array{Float64,2}(undef, n,n)\n    for iy = 1:n\n        for ix = 1:n\n            x2D[1,ix,iy] = x1D[ix]\n            x2D[2,ix,iy] = x1D[iy]\n            w2D[ix,iy] = w1D[ix]*w1D[iy]\n        end\n    end\n    return (x2D, w2D)\nend\n\n\"\"\"\n    chebyshev2D(p)\nReturn the 2D chebyshev points of order p on the domain [-1,1]^2\n\"\"\"\nfunction chebyshev2D(p)\n    x1D = Basis1D.chebyshev(p)\n    n = length(x1D)\n    x2D = Array{Float64,3}(undef, 2, n, n)\n    for iy = 1:n\n        for ix = 1:n\n            x2D[1,ix,iy] = x1D[ix]\n            x2D[2,ix,iy] = x1D[iy]\n        end\n    end\n    return x2D\nend\n\n\"\"\"\n    equidistant_nodes2D(p)\nReturn the \"order p\" 2D points on the domain [-1,1]^2\n\"\"\"\nfunction equidistant_nodes2D(p)\n    x1D = -1:2/p:1\n    n = length(x1D)\n    x2D = Array{Float64,3}(undef, 2, n, n)\n    for iy = 1:n\n        for ix = 1:n\n            x2D[1,ix,iy] = x1D[ix]\n            x2D[2,ix,iy] = x1D[iy]\n        end\n    end\n    return x2D\nend\n\n\"\"\"\n    interpolation_matrix2D(xy_from, xy_to)\nCompute an interpolation matrix from a set of 2D points to another set of 2D points.\nAssumes that points interpolating from provide enough accuracy (aka - they are\nwell spaced out and of high enough order), and define a square. Points\ninterpolating onto can be of any size, but must be defined on this same square.\nInterpolation matrix ∈ ℜ^(2D size of xy_to x 2D size of xy_from)\n\"\"\"\nfunction interpolation_matrix2D(xy_from, xy_to)\n    # Create nodal representation of reference bases\n    (x_from, y_from) = xy_from\n    order = size(x_from,1) - 1 # Assumes order = (size of x_from) - 1\n    @assert size(x_from,1) == size(y_from,1)\n    n_from = size(x_from,1)*size(y_from,1)\n    l_from = vandermonde2D(order, x_from, y_from)\n\n    eye = diagm(0=>ones(n_from))\n    V = reshape(l_from, n_from,n_from)\n    coeffs_phi = V \\ eye\n\n    # Compute reference bases on the output points\n    l_to = vandermonde2D(order, xy_to...)\n    n_to = prod(size.(xy_to,1))\n    V_to = reshape(l_to, n_to,n_from)\n\n    # Construct interpolation matrix\n    Interp2D = V_to*coeffs_phi\nend\n\n\"\"\"\n    dPhi2D(xy_from, xy_to)\nCompute the gradient of the basis functions defined by 2D points on another\nset of 2D points.\n\nAssumes that points interpolating from provide enough accuracy (aka - they are\nwell spaced out and of high enough order), and define a square. Points\ninterpolating onto can be of any size, but must be defined on this same square.\ndPhi ∈ ℜ^(size of xy_to × size of xy_from × 2)\n\"\"\"\nfunction dPhi2D(xy_from, xy_to)\n    dim = 2\n    # Create nodal representation of reference bases\n    (x_from, y_from) = xy_from\n    order = size(x_from,1) - 1 # Assumes order = (size of x_from) - 1\n    @assert size(x_from,1) == size(y_from,1)\n    n_from = size(x_from,1)*size(y_from,1)\n    l_from = vandermonde2D(order, x_from, y_from)\n\n    eye = diagm(0=>ones(n_from))\n    V = reshape(l_from, n_from,n_from)\n    coeffs_phi = V \\ eye\n\n    # Compute derivative of reference bases on the output points\n    dl_to = grad_vandermonde2D(order, xy_to...)\n    n_to = prod(size.(xy_to,1))\n    dV = reshape(dl_to, n_to,n_from,dim)\n    # Construct gradient of phi = dV*coeffs_phi\n    dPhi_to = Array{Float64,3}(undef, n_to,n_from,dim)\n    for l = 1:dim\n        dPhi_to[:,:,l] = dV[:,:,l]*coeffs_phi\n    end\n    return dPhi_to\nend\n\nend\n", "meta": {"hexsha": "2d518eee3ede04ca986e6d11583c898b5b1ddf24", "size": 4918, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Basis2D.jl", "max_stars_repo_name": "NoseKnowsAll/DGToolkit", "max_stars_repo_head_hexsha": "e029ed96f337b187876a52a3f63b7636336374c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-22T03:23:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T03:23:48.000Z", "max_issues_repo_path": "src/Basis2D.jl", "max_issues_repo_name": "NoseKnowsAll/DGToolkit", "max_issues_repo_head_hexsha": "e029ed96f337b187876a52a3f63b7636336374c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Basis2D.jl", "max_forks_repo_name": "NoseKnowsAll/DGToolkit", "max_forks_repo_head_hexsha": "e029ed96f337b187876a52a3f63b7636336374c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-22T03:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-22T03:23:50.000Z", "avg_line_length": 28.1028571429, "max_line_length": 92, "alphanum_fraction": 0.6364375763, "num_tokens": 1720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7501206054420518}}
{"text": "## Pendulum\n# https://github.com/HarvardAgileRoboticsLab/unscented-dynamic-programming/blob/master/pendulum_dynamics.m\nfunction pendulum_dynamics!(ẋ::AbstractVector{T},x::AbstractVector{T},u::AbstractVector{T}) where T\n    m = 1.\n    l = 0.5\n    b = 0.1\n    lc = 0.5\n    I = 0.25\n    g = 9.81\n    ẋ[1] = x[2]\n    ẋ[2] = (u[1] - m*g*lc*sin(x[1]) - b*x[2])/I\nend\n\nn,m = 2,1\npendulum = Model(pendulum_dynamics!,n,m) # inplace model\n\n\nfunction pendulum_dynamics2!(ẋ::AbstractVector{T},x::AbstractVector{T},u::AbstractVector{T}) where T\n    ẋ[1] = x[2];\n    ẋ[2] = sin(x[1]) + u[1];\n\n\nend\n\npendulum2 = Model(pendulum_dynamics2!,n,m) # inplace model\n\n\n\n\n\n# unknown mass\nfunction pendulum_dynamics_uncertain!(ẋ,x,u,w)\n    m = 1. + w[1]\n    l = 0.5\n    b = 0.1\n    lc = 0.5\n    I = 0.25\n    g = 9.81\n\n    ẋ[1] = x[2]\n    ẋ[2] = u[1]/(m*lc*lc) - g*sin(x[1])/lc - b*x[2]/(m*lc*lc)\n    return nothing\nend\n\nn = 2; m = 1; r = 1\npendulum_uncertain = UncertainModel(pendulum_dynamics_uncertain!,n,m,r)\n", "meta": {"hexsha": "3b2d1e268cd301ada28a31811b8c59f8d79fa644", "size": 996, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "TrajectoryOptimization.jl/dynamics/pendulum.jl", "max_stars_repo_name": "MehrdadZareian/GMARA", "max_stars_repo_head_hexsha": "85428ae55a0cb8ae541d6db668307cacc3899cee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-14T08:14:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T08:14:31.000Z", "max_issues_repo_path": "TrajectoryOptimization.jl/dynamics/pendulum.jl", "max_issues_repo_name": "MehrdadZareian/GMARA", "max_issues_repo_head_hexsha": "85428ae55a0cb8ae541d6db668307cacc3899cee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TrajectoryOptimization.jl/dynamics/pendulum.jl", "max_forks_repo_name": "MehrdadZareian/GMARA", "max_forks_repo_head_hexsha": "85428ae55a0cb8ae541d6db668307cacc3899cee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1914893617, "max_line_length": 106, "alphanum_fraction": 0.6004016064, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7500857143032894}}
{"text": "# ---\n# title: 9. Palindrome Number\n# id: problem9\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Easy\n# categories: Math\n# link: <https://leetcode.com/problems/palindrome-number/description/>\n# hidden: true\n# ---\n# \n# Determine whether an integer is a palindrome. An integer is a palindrome when\n# it reads the same backward as forward.\n# \n# **Follow up:** Could you solve it without converting the integer to a string?\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: x = 121\n#     Output: true\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: x = -121\n#     Output: false\n#     Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: x = 10\n#     Output: false\n#     Explanation: Reads 01 from right to left. Therefore it is not a palindrome.\n#     \n# \n# **Example 4:**\n# \n#     \n#     \n#     Input: x = -101\n#     Output: false\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `-231 <= x <= 231 - 1`\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction is_palindrome(x::Int)::Bool\n    if x < 0\n        false\n    else\n        y = x\n        y_reverse = 0\n        while y > 0\n            y, n = divrem(y, 10)\n            y_reverse = y_reverse * 10 + n\n        end\n        x == y_reverse\n    end\nend\n## @lc code=end\n", "meta": {"hexsha": "d3ccf684cf7e7e0377a2fb5b9af7fc9b9630f39c", "size": 1347, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/9.palindrome-number.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/9.palindrome-number.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/9.palindrome-number.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 17.4935064935, "max_line_length": 124, "alphanum_fraction": 0.5404602821, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543454, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7500857102944514}}
{"text": "# This file is a part of SimilaritySearch.jl\n\nexport JaccardDistance, DiceDistance, IntersectionDissimilarity\nimport Distances: evaluate\n\n\"\"\"\n    JaccardDistance()\n\nThe Jaccard distance is defined as\n\n```math\nJ(u, v) = \\\\frac{|u \\\\cap v|}{|u \\\\cup v|}\n```\n\"\"\"\nstruct JaccardDistance <: PreMetric end\n\n\"\"\"\n    DiceDistance()\n\nThe Dice distance is defined as\n\n```math\nD(u, v) = \\\\frac{2 |u \\\\cap v|}{|u| + |v|}\n```\n\"\"\"\nstruct DiceDistance <: PreMetric end\n\n\"\"\"\n    IntersectionDissimilarity()\n\nThe intersection dissimilarity uses the size of the intersection as a mesuare of similarity as follows:\n\n```math\nI(u, v) = 1 - \\\\frac{|u \\\\cap v|}{\\\\max \\\\{|u|, |v|\\\\}}\n```\n\"\"\"\nstruct IntersectionDissimilarity <: PreMetric end\n\n\"\"\"\n    union_intersection(a::T, b::T)\n\nComputes both the size of the unions an the size the intersections of `a` and `b`;\nspecified as ordered sequences.\n\"\"\"\nfunction union_intersection(a::T, b::T) where {T <: AbstractVector}\n    len_a::Int = length(a)\n    len_b::Int = length(b)\n    ia::Int = 1\n    ib::Int = 1\n    intersection_size::Int = 0\n    c::Int = 0\n    @inbounds while ia <= len_a && ib <= len_b\n        c = cmp(a[ia], b[ib])\n        if c == 0\n            ia += 1\n            ib += 1\n            intersection_size += 1\n        elseif c < 0\n            ia += 1\n        else\n            ib += 1\n        end\n    end\n\n    len_a + len_b - intersection_size, intersection_size\nend\n\n\n\"\"\"\n    evaluate(::JaccardDistance, a, b)\n\nComputes the Jaccard's distance of `a` and `b` both sets specified as\nsorted vectors.\n\"\"\"\nfunction evaluate(::JaccardDistance, a, b)\n    u, i = union_intersection(a, b)\n    1.0 - i / u\nend\n\n\"\"\"\n    evaluate(::DiceDistance, a, b)\n\nComputes the Dice's distance of `a` and `b` both sets specified as\nsorted vectors.\n\"\"\"\nfunction evaluate(::DiceDistance, a, b)\n    u, i = union_intersection(a, b)\n    1.0 - 2 * i / (length(a) + length(b))\nend\n\n\n\"\"\"\n    evaluate(::IntersectionDissimilarity, a, b)\n\nUses the intersection as a distance function (non-metric)\n\"\"\"\nfunction evaluate(::IntersectionDissimilarity, a, b)\n    u, i = union_intersection(a, b)\n\n    return 1.0 - i / max(length(a), length(b))\nend", "meta": {"hexsha": "15b8af38d206c1532b22312e53cc6ac3e907b2c0", "size": 2146, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances/sets.jl", "max_stars_repo_name": "sadit/SimilaritySearch.jl", "max_stars_repo_head_hexsha": "c540baff09e1b2e55af6489826e62436f0d7cf44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-12-03T01:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:43:56.000Z", "max_issues_repo_path": "src/distances/sets.jl", "max_issues_repo_name": "sadit/SimilaritySearch.jl", "max_issues_repo_head_hexsha": "c540baff09e1b2e55af6489826e62436f0d7cf44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2017-05-26T01:14:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T16:26:21.000Z", "max_forks_repo_path": "src/distances/sets.jl", "max_forks_repo_name": "sadit/SimilaritySearch.jl", "max_forks_repo_head_hexsha": "c540baff09e1b2e55af6489826e62436f0d7cf44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-05-26T09:51:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T09:13:48.000Z", "avg_line_length": 21.2475247525, "max_line_length": 103, "alphanum_fraction": 0.6197576887, "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122138417878, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.750085708087379}}
{"text": "using SciPyDiffEq\nusing Test\n\nfunction lorenz(u,p,t)\n du1 = 10.0(u[2]-u[1])\n du2 = u[1]*(28.0-u[3]) - u[2]\n du3 = u[1]*u[2] - (8/3)*u[3]\n [du1, du2, du3]\nend\nu0 = [1.0;0.0;0.0]\ntspan = (0.0,100.0)\nprob = ODEProblem(lorenz,u0,tspan)\nsol = solve(prob,SciPyDiffEq.RK45())\nsol = solve(prob,SciPyDiffEq.RK23())\nsol = solve(prob,SciPyDiffEq.Radau())\nsol = solve(prob,SciPyDiffEq.BDF())\nsol = solve(prob,SciPyDiffEq.LSODA())\nsol = solve(prob,SciPyDiffEq.odeint())\n\nfunction lorenz(du,u,p,t)\n du[1] = 10.0(u[2]-u[1])\n du[2] = u[1]*(28.0-u[3]) - u[2]\n du[3] = u[1]*u[2] - (8/3)*u[3]\nend\nu0 = [1.0;0.0;0.0]\ntspan = (0.0,100.0)\nprob = ODEProblem(lorenz,u0,tspan)\nsol = solve(prob,SciPyDiffEq.RK45())\nsol(4.0)\nsol = solve(prob,SciPyDiffEq.RK23())\nsol(4.0)\nsol = solve(prob,SciPyDiffEq.Radau())\nsol(4.0)\nsol = solve(prob,SciPyDiffEq.BDF())\nsol(4.0)\nsol = solve(prob,SciPyDiffEq.LSODA())\nsol(4.0)\nsol = solve(prob,SciPyDiffEq.odeint())\nsol(4.0)\n\n#using Plots; plot(sol,vars=(1,2,3))\n", "meta": {"hexsha": "3c8d63291b11b7557266378e19e511a561a48629", "size": 969, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "stjordanis/SciPyDiffEq.jl", "max_stars_repo_head_hexsha": "a881bd3bc9ef6dc63f8bbbdcc71faa5903d8e5aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2019-11-23T20:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-02T19:16:47.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "stjordanis/SciPyDiffEq.jl", "max_issues_repo_head_hexsha": "a881bd3bc9ef6dc63f8bbbdcc71faa5903d8e5aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-11-24T01:16:25.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-28T07:08:10.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "stjordanis/SciPyDiffEq.jl", "max_forks_repo_head_hexsha": "a881bd3bc9ef6dc63f8bbbdcc71faa5903d8e5aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-01-26T23:50:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-23T14:34:29.000Z", "avg_line_length": 23.0714285714, "max_line_length": 38, "alphanum_fraction": 0.6377708978, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7500857062856132}}
{"text": "# Autonomous van der Pol\nusing DrWatson\n@quickactivate \"NonlinearDynamicsTextbook\"\ninclude(srcdir(\"style.jl\"))\nusing DynamicalSystems, PyPlot\n\n# parameters and initial values\ndvec = [0.1, 5]    # damping parameters\ny_0 = [0.1, 0.1]   # initial condition\nttrans = 100   # transient time\ntattr = 16     # time on attractor\nΔt = 0.01   # sampling time \ntvec = 0:Δt:tattr\n\nfig, axs = subplots(1,2; figsize=(0.6figx,0.8figy)) \n\nfor id = 1:2\n    d = dvec[id]\n    y_init = y_0\n    ds = Systems.vanderpol(; F = 0, μ = d)\n    tr = trajectory(ds, tattr, y_0; Δt, Ttr = ttrans)\n    x1vec, x2vec = columns(tr)\n    axs[1].plot(tvec,x1vec; c = COLORS[id] ) \n    axs[2].plot(x1vec,x2vec; c = COLORS[id] )  \nend\naxs[1].set_xlabel(L\"$t$\"; labelpad = -20) \naxs[1].set_ylabel(L\"$x$\", rotation = 0) \naxs[2].set_xlabel(L\"$x$\"; labelpad = -20)  \naxs[2].set_ylabel(L\"$\\dot x$\", rotation = 0)\naxs[1].set_xticks([0,15])\naxs[2].set_xticks([-2,0,2])\naxs[2].set_xticklabels([\"-2\", \"\", \"2\"])\nadd_identifiers!(fig)\nfig.tight_layout(pad=0.33)\n\nwsave(plotsdir(\"9\", \"vanderPol_autonomous\"), fig)\n", "meta": {"hexsha": "071bf3608441c55b8317d4dc94f9968b5aeb67bc", "size": 1063, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "figure_generation/9/9.4.jl", "max_stars_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_stars_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 88, "max_stars_repo_stars_event_min_datetime": "2021-07-18T20:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T09:23:53.000Z", "max_issues_repo_path": "figure_generation/9/9.4.jl", "max_issues_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_issues_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figure_generation/9/9.4.jl", "max_forks_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_forks_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-07-28T18:49:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:45:11.000Z", "avg_line_length": 28.7297297297, "max_line_length": 53, "alphanum_fraction": 0.6462841016, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7500528164027102}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.21\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 4fb1c47c-8d70-11eb-3d5c-01c5bb7190fe\nusing Pkg, DrWatson\n\n# ╔═╡ 5838d806-8d70-11eb-2a78-fb586f056012\nbegin\n\tusing Distributions\n\tusing StatsPlots\n\tusing StatsBase\n\tusing LaTeXStrings\n\tusing CSV\n\tusing DataFrames\n\tusing LinearAlgebra\n\tusing Random\n\tusing StatisticalRethinking\nend\n\n# ╔═╡ 3562c0e2-8d70-11eb-0f89-9d039fe996b9\nmd\" ## Clip-11-01-05s.jl\"\n\n# ╔═╡ 07c85e9e-8d95-11eb-295d-63a99f7aa921\nmd\" ##### Fig 10.7.\"\n\n# ╔═╡ 9bfd33fc-8d70-11eb-3a9c-bb9a990cbcf9\nx = collect(-1.0:0.01:1.0);\n\n# ╔═╡ ee25cbe6-8d8c-11eb-3323-c521a67b10f0\nbegin\n\tα = 0.0\n\tβ = 2.0\n\t\n\t# p = exp.(α .+ β .* x) ./ (1 .+ exp.(α .+ β .* x))\n\t\n\tp = logistic.(α .+ β .* x)\nend\n\n# ╔═╡ 1cba8970-8d91-11eb-01d8-09d8d076dc73\nbegin\n\todds = p ./ (1 .- p)\n\tlogodds = log.(odds)\nend\n\n# ╔═╡ 6b96d95e-8d91-11eb-25ac-75f21ee9c98e\nlogistic.(x)\n\n# ╔═╡ 15dcde1e-8d8c-11eb-0964-d9c5f616e59c\nbegin\n\tfig1 = plot(x, logodds, leg=false)\n\tfig2 = plot(x, p, ylims=(0,1), leg=false)\n\tplot(fig1, fig2, layout=(1, 2))\nend\n\n# ╔═╡ 1404a820-8d95-11eb-27d2-531cea578fda\nmd\" ##### Fig 10.8.\"\n\n# ╔═╡ c859986c-8d93-11eb-1211-db9c435de034\nlogsig = exp.(α .+ β .* x)\n\n# ╔═╡ f3bac6a4-8d93-11eb-2614-1572443e3415\nbegin\n\tfig3 = plot(x, log.(logsig), leg=false)\n\tfig4 = plot(x, logsig, ylims=(0,10), leg=false)\n\tplot(fig3, fig4, layout=(1, 2))\nend\n\n# ╔═╡ 7e069492-8d70-11eb-2093-8375b07f4099\nmd\" ## End of clip-11-01-05s.jl\"\n\n# ╔═╡ Cell order:\n# ╠═3562c0e2-8d70-11eb-0f89-9d039fe996b9\n# ╠═4fb1c47c-8d70-11eb-3d5c-01c5bb7190fe\n# ╠═5838d806-8d70-11eb-2a78-fb586f056012\n# ╟─07c85e9e-8d95-11eb-295d-63a99f7aa921\n# ╠═9bfd33fc-8d70-11eb-3a9c-bb9a990cbcf9\n# ╠═ee25cbe6-8d8c-11eb-3323-c521a67b10f0\n# ╠═1cba8970-8d91-11eb-01d8-09d8d076dc73\n# ╠═6b96d95e-8d91-11eb-25ac-75f21ee9c98e\n# ╠═15dcde1e-8d8c-11eb-0964-d9c5f616e59c\n# ╟─1404a820-8d95-11eb-27d2-531cea578fda\n# ╠═c859986c-8d93-11eb-1211-db9c435de034\n# ╠═f3bac6a4-8d93-11eb-2614-1572443e3415\n# ╟─7e069492-8d70-11eb-2093-8375b07f4099\n", "meta": {"hexsha": "44b959af923a4be535d3ceae8c4e79b53f1f968c", "size": 1992, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks_old/10/Fig-10.7s.jl", "max_stars_repo_name": "StatisticalRethinkingJulia/SR2StanPluto.jl", "max_stars_repo_head_hexsha": "6eea864f4ca098320d7bc295c6254304c86d7d19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-17T01:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T00:23:37.000Z", "max_issues_repo_path": "notebooks_old/10/Fig-10.7s.jl", "max_issues_repo_name": "StatisticalRethinkingJulia/SR2StanPluto.jl", "max_issues_repo_head_hexsha": "6eea864f4ca098320d7bc295c6254304c86d7d19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks_old/10/Fig-10.7s.jl", "max_forks_repo_name": "StatisticalRethinkingJulia/SR2StanPluto.jl", "max_forks_repo_head_hexsha": "6eea864f4ca098320d7bc295c6254304c86d7d19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-21T21:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T21:01:50.000Z", "avg_line_length": 22.6363636364, "max_line_length": 52, "alphanum_fraction": 0.6932730924, "num_tokens": 1124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.8615382058759128, "lm_q1q2_score": 0.7500528115575898}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e03dd22c-884c-11eb-2432-3dc04b0cf286\nbegin\n  using Pkg; Pkg.activate(\"MLJ_env\", shared=true)\n  using Test\n  using Plots\n  using PlutoUI\n  using Random\n  using Distributions\n\n  push!(LOAD_PATH, \"./src\")\n  using YaLinearAlgebra\nend\n\n# ╔═╡ 380c26d0-881d-11eb-0461-f339488ea81e\nmd\"\"\"\n## Gradient Descent\n\nref. from book **\"Data Science from Scratch\"**, Chap 8\n\n$(html\"<div><sub>&copy; Pascal, April 2021</sub></div>\")\n\"\"\"\n\n# ╔═╡ 83e01f80-884a-11eb-1ef7-e9cb5ab3ed20\nPlutoUI.TableOfContents(indent=true, depth=4, aside=true)\n\n# ╔═╡ 853ab02c-884a-11eb-01bf-1712dc177ffb\nhtml\"\"\"\n<style>\n  main {\n\tmax-width: calc(800px + 25px + 6px);\n  }\n  .plutoui-toc.aside {\n    background: linen;\n  }\n  h3, h4 {\n\tbackground: wheat;\n  }\n</style>\n\"\"\"\n\n# ╔═╡ 4c951444-8869-11eb-0b88-55a9fb9e51e6\nhtml\"\"\"\n<hr />\n\"\"\"\n\n# ╔═╡ 8c87c3b8-884a-11eb-10c8-73e2dab560ea\nmd\"\"\"\n### Context\n\"\"\"\n\n# ╔═╡ 8c6ba818-884a-11eb-23e0-2f1c297d88f5\nmd\"\"\"\nThe gradient (vector of partial derivatives) gives the direction in which the function most quickly increase.\n\nIn ML we are looking at a best model (relative to some criteria) to fit the data. In this context \"best\" is obtained by minimizing a quantity (ex. minimize MSE between prediction and ground truth in a supervised setting) or maximizing a quantity (ex. likelihood of the data). This means that the problem is cast as an optimization problem. One technique to solve those optimization problems, which scale rather weel is **Gradient Descent** (or **Gradient Ascent**).\n\nIn a nutshell, Gradient Descent consists in picking a random starting point, computing the gradient (derivatives) of a given function w.r.t its parameters and take a small step in the opposite direction of the gradient (minimization setup, alternatively in the direction, for gradient ascent and a maximization setup) and repeat the process with this updated point until some convergence criteria.\n\"\"\"\n\n# ╔═╡ d2d18b22-884c-11eb-1f93-037453c5395b\nbegin\n  f(x, y) = x^2 + y^2\n  x = -10:10\n  y = x\n  plot(x, y, f, linetype=:surface)\n\n  xₛ = 0:0.5:10\n  yₛ = 0:-.45:-9\n  zₛ = f.(xₛ, yₛ)\n  scatter!(xₛ, yₛ, zₛ, marker=:v, markersize=4, color=:steelblue, legend=false)\nend\n\n# ╔═╡ 221734fe-8869-11eb-331a-b5810d0b784c\nhtml\"\"\"\n<hr />\n\"\"\"\n\n# ╔═╡ d297fa06-884c-11eb-294e-85992f901be1\nmd\"\"\"\n### Estimating the gradient\n\nIf f is a function of one variable, its derivative at point x measures how f(x) changes as we make a very small change of x. The derivative is the limit of the difference of the quotients\n\"\"\"\n\n# ╔═╡ 1859c082-8853-11eb-18f6-2bc7a180b4a2\nbegin\n  const AF =  AbstractFloat\n  const VT = Vector{T} where T <: AbstractFloat\nend\n\n# ╔═╡ d27feefa-884c-11eb-3b84-1f529d7f6410\nbegin\n  function diff_quotient(f::Function, x::AF, Δ::AF)::AF\n    (f(x + Δ) - f(x)) / Δ\n  end\n\n  diff_quotient(f::Function, v::Vector{AF}, Δ::AF) = diff_quotient.(f, v, Δ)\nend\n\n# ╔═╡ 5618fb40-8853-11eb-3d2f-032437d22a09\nmd\"\"\"\nThe derivative is the slope of the tangent line at (x, f (x)) , while the difference quotient is the slope of the almost-tangent line that runs through (x + Δ, f (x + Δ)) . As Δ gets tends to 0,, the almost-tangent line gets closer and closer to the tangent line.\n\"\"\"\n\n# ╔═╡ 55fab426-8853-11eb-01f8-cbde45c7de9c\n# TODO figure\n\n# ╔═╡ 55e3efea-8853-11eb-0821-c5c580bc8fc5\nmd\"\"\"\nFor many function it is easy to compute the exact derivatives. For example for the square function we have:\n\"\"\"\n\n# ╔═╡ 55c56cc8-8853-11eb-04f4-3be84a352808\nbegin\n  square(x::AF) = x * x\n  square(v::Vector{AF}) = square.(v)\n\n  deriv_square(x::AF) = 2. * x\n  deriv_square(v::VT) = deriv_square.(v)\n  end\n\n# ╔═╡ d25d8eac-884c-11eb-2063-27413f8aba04\nmd\"\"\"\nWhat if we cannot? Weel we can estimate the derivative by evaluating the difference quotient for very small Δ. For example:\n\"\"\"\n\n# ╔═╡ 480f7b18-8854-11eb-2898-8d876317ebe2\nbegin\n  xᵣ = -10.:10.\n  Δ = 1e-3\n\n  yᵣ = square.(collect(xᵣ));\n  dyᵣ = deriv_square.(xᵣ);\n  dŷᵣ = diff_quotient.(square, xᵣ, Δ);\nend\n\n# ╔═╡ 47ee8cb4-8854-11eb-252b-852fd56aa40f\nbegin\n  plot(xᵣ, yᵣ, label=\"Square\", marker=:o, color=:green)\n  scatter!(xᵣ, dyᵣ, label=\"Actual\", marker=:o, color=:salmon)\n  scatter!(xᵣ, dŷᵣ, label=\"Estimate\", marker=:x, color=:darkslateblue,\n    markersize=5, title=\"Actual derivatives vs Estimates\")\nend\n\n# ╔═╡ 47d2c2cc-8854-11eb-35f9-952876481d02\nmd\"\"\"\nWhen a function has sevral variables, it has multiple *partila derivatives* each indicating how f change when a small change is made in one of the input variable (while keeping the rest constant).\n\"\"\"\n\n# ╔═╡ f5980b54-8856-11eb-3e30-89c3f188ca8d\nbegin\n  function ∂_diff_quotient(f::Function, v::VT, i::Integer, Δ::AF)::AF\n    \"\"\"\n    Returns the i-th partial difference quotient of f at v\n    \"\"\"\n    w = copy(v)\n    w[i] += Δ\n    (f.(w...) - f.(v...)) / Δ\n  end\n\n  ∂_diff_quotient(f::Function, v::Vector{AF}, Δ::AF)::AF =\n    ∂_diff_quotient.(f, Tuple(v), 1:length(v), Δ)\nend\n\n# ╔═╡ f57b16b6-8856-11eb-3409-47f7b438f491\nmd\"\"\"\nWith this definition we can then estimate the gradient.\n\"\"\"\n\n# ╔═╡ f55dd09c-8856-11eb-1823-290fcb200662\nfunction estimate_∇(f::Function, v::VT, Δ::AF)::VT\n  [∂_diff_quotient(f, v, i, Δ) for i in 1:length(v)]\nend\n\n# ╔═╡ 33df0458-885c-11eb-2635-371a9590d833\nbegin\n  fn(u::AF, v::AF) = u^2 + v\n\n  ∂fnᵤ(u::AF, _v::AF) = 2. * u  # ∂fn w.r.t u\n  ∂fnᵥ(_u::AF, v::AF) = 1       # ∂fn w.r.t v\nend\n\n# ╔═╡ e76a5b58-885c-11eb-0067-010ba1d4c9b5\nbegin\n  Base.:≈(x::AF, y::AF; ϵ=1e-4) = abs(x - y) ≤ ϵ\n\n  Base.:≈(u::Vector{T}, v::Vector{T}; ϵ=1e-4) where T <: AF = abs.(u - v) .≤ ϵ\nend\n\n# ╔═╡ e783d618-8858-11eb-0c0b-b57e54bd3757\nbegin\n  Δ₁ = 1e-6\n  vm = Float64[1., 2.]\n  ix = 1\n  @test ∂fnᵤ(vm...) ≈ ∂_diff_quotient(fn, vm, ix, Δ₁)\nend\n\n# ╔═╡ e767c1bc-8858-11eb-1b29-596a25a4fea4\nhtml\"\"\"\n<hr />\n\"\"\"\n\n# ╔═╡ e747b052-8858-11eb-3c50-5355fef542c9\nmd\"\"\"\n### Using the Gradient\n\"\"\"\n\n# ╔═╡ cc17413a-885d-11eb-1629-47fc5220529e\nmd\"\"\"\nIt is easy to see that the function `f` defines above is smallest when its input is a vector of zeros. But imagine let's say we do not know. In this case we can use  the gradients to find the minimum (this function is bivariate convexe) among all three-dimensional vectors.\n\nWe will start by picking a random starting point and then take tiny steps in the opposite direction of the gradient until we reach a point where the gradient is very small (which is guarantee to happen)\n\"\"\"\n\n# ╔═╡ cbfa193c-885d-11eb-3a48-97b26377b4fb\nfunction ∇_step(v::VT, ∇::VT, η::AF)::VT\n  @assert length(v) == length(∇)\n  v + η * ∇\nend\n\n# ╔═╡ cbe180fe-885d-11eb-1307-7f3ac4897441\n∇_sum_of_square(v::VT) = deriv_square(v)\n\n# ╔═╡ d21bb0fe-884c-11eb-224f-216a811365a8\nfunction gradient_descent(fn;range=1000, rng=MersenneTwister(42), η=1e-2)\n  v = rand(rng, 3)\n  for epoch ∈ 1:range\n    ∇ = fn(v)\n    v = ∇_step(v, ∇, -η) ## take a step in negative direction of the gradient\n    epoch % 100 == 0 && println(\"$(epoch) => v: $(v)\")\n  end\n  v\nend\n\n# ╔═╡ de2e6604-8863-11eb-3a27-8f8e8b55e5d8\nwith_terminal() do\n  gradient_descent(∇_sum_of_square)\nend\n\n# ╔═╡ 3082d12e-8864-11eb-06bc-cdf9202cd20a\nbegin\n  @test all(Base.:≈(gradient_descent(∇_sum_of_square), zeros(Float64, 3); ϵ=1.e-7))\n  @test all(gradient_descent(∇_sum_of_square) ≈ zeros(Float64, 3))\nend9.93698\n\n-1.0823\n\n# ╔═╡ 306b8d52-8864-11eb-1cbd-1341afcd52ff\nhtml\"\"\"\n<hr />\n\"\"\"\n\n# ╔═╡ 304ff894-8864-11eb-1449-b71da9112247\nmd\"\"\"\n### Choosing the right step\n\nIt is clear why we choose to move in the opposite direction of the gradient while minimizing an (objective) function. Determining the right step however is something like an art and its value depends on the context.\n  - Too large a step size and we are likely to overshoot and not converge to the optimum.\n  - Too small a step and it will take ages to converge...\n\nNot easy. There are mutliple options like fixed step size, gradual shrinking of the step size over time and other fancier options... To select the right step (or rnage of steps) one can try different options on a validation set...\n\"\"\"\n\n# ╔═╡ 8c4d28fc-884a-11eb-0de2-b58988dc7422\nhtml\"\"\"\n<hr />\n\"\"\"\n\n# ╔═╡ 8a07d906-8869-11eb-0bae-2582b352c05c\nmd\"\"\"\n### Using Gradient Descent (GD) to fit models\n\nIn this collection of notebooks, we will be using gradient descent to fit parameterized models to data.\n\nThe usual case involves some dataset which we try to fit with a model (our hypothesis) that is characterized by some differentiable parameters. Also to measure the quality of our progress we will have a loss function.\n\nTaking the data as being fixed, the loss function tells us how good (or bad) our model parameters are. We can use gradient descent to optimize this loss.\n\nLet us try on a toy example.\n\"\"\"\n\n# ╔═╡ 89ebdac6-8869-11eb-25ac-2dac6a4b20aa\nbegin\n  rng = MersenneTwister(42)\n  data = [[x, 10x + 5. + 40. * randn(rng, 1)[1]] for x ∈ -50.:50.]\n  # linear pattern with some (Normally distributed) noise\nend\n\n# ╔═╡ 89d1728a-8869-11eb-0001-875c2a452cf8\nscatter(map(x -> x[1], data), map(y -> y[2], data), legend=false)\n\n# ╔═╡ c0cc67c8-888b-11eb-272c-05a727c634ea\ntypeof(data)\n\n# ╔═╡ 4bf3d986-886d-11eb-3ea8-7926f5babce0\nfunction linear_∇(x::AF, y::AF, θ::VT)::VT\n  slope, intercept = θ\n  ŷ = slope * x + intercept   # prediction model\n  Δerr = (ŷ - y)\n  # squared_Δerr = Δerr^2\n  [2. * Δerr * x, 2. * Δerr]\nend\n\n# ╔═╡ d8f972a0-8881-11eb-2be8-db89fb95a9f1\nmd\"\"\"\nWe are going to:\n  1. Start with random initialisation of the parameters (θ)\n  1. Compute the mean of the gradient\n  1. Adjust θ\n  1. Repeat\n\"\"\"\n\n# ╔═╡ 1b26337a-8882-11eb-2439-e106cdb884f5\nfunction ∇_descent(inputs::Vector{Vector{T}};\n    η=1e-5, nepochs=5_000) where T <: AF\n  u = Uniform(-1., 1.)\n  θ = [rand(u) for _ ∈ 1:2]\n\n  for epoch ∈ 1:nepochs\n    ∇ = μ([linear_∇(x, y, θ) for (x, y) ∈ inputs])\n    θ = ∇_step(θ, ∇, -η)\n    epoch % 100 == 0 && println(\"$(epoch) => θ: $(θ)\")\n  end\n\n  (slope, intercept) = θ\nend\n\n# ╔═╡ 1b09cc9e-8882-11eb-0efc-630028d87217\nbegin\n  slope, intercept = ∇_descent(data; nepochs=1_000)\n  @test 9.90 ≤ slope ≤ 10.1\n  @test abs(intercept) ≤ 1.0\nend\n\n# ╔═╡ 28b44b3c-88f8-11eb-23dd-bbfe325d70d3\nmd\"\"\"\nLet's plot our result:\n\"\"\"\n\n# ╔═╡ 1c89f188-88f6-11eb-026c-e59bb08ac7ac\nbegin\n  x_ = [-50.0, 50.0]\n  y_ = slope .* x_ .+ intercept\n  #\n  scatter(map(x -> x[1], data), map(y -> y[2], data), legend=false)\n  plot!(x_, y_, lw=3, color=:darkred)\nend\n\n# ╔═╡ 1ad358e4-8882-11eb-0559-bd43867dacfd\nhtml\"\"\"\n<hr />\n\"\"\"\n\n# ╔═╡ d8d3bb0a-8881-11eb-35b2-8f486d6cc094\nmd\"\"\"\n### Mini-batch and Stochastic Gradient Descent\n\nIn the preceding approach we evaluated the gradient on the whole dataset. This was fine because our dataset was small. In practice datasets can be big/large and this technique  becomes computationally expensive. This is why other techniques were devised, namely stochastic gradient descent and mini-batch gradient descent (a good trade-off between full gradient descent and stochastic gradient descent).\n\n\nIn mini-batch gradient descent, we compute the gradient and take a  gradient step based on a mini-batch sampled from the dataset:\n\"\"\"\n\n# ╔═╡ cd7c444a-8893-11eb-2409-f161ebc287b5\nbegin\n\t\"\"\"\n\tGenerates batch-size sized min-batches from given dataset\n\t\"\"\"\t\n\t\n\tstruct MiniBatch{T <: Any}\n\t\tds::Vector{Vector{T}}\n\t\tbsize::Integer  # batch-size\n\n\t\tfunction MiniBatch{T}(ds::Vector{Vector{T}}, bs::Integer) where T <: Any\n\t\t\t@assert 0 < bs ≤ length(ds)\n\t\t\tnew(ds, bs)\n    \tend\n  \tend\n\n  \tBase.collect(iter::MiniBatch) = iter.ds\n\n\tfunction Base.iterate(iter::MiniBatch, \n\t\t\tstate=(view(iter.ds, 1:iter.bsize), iter.bsize + 1))\n\t\tbatch, ix = state\n\t\t##\n\t\tisnothing(batch) && return nothing\n\t\tix ≥ length(iter.ds) && return (batch, (nothing, ix))\n\t\t## otherwise\n\t\tjx = ix\n\t\tix += iter.bsize\n\t\tix = ix ≥ length(iter.ds) ? length(iter.ds) : ix\n\t\t(batch, (view(iter.ds, jx:ix - 1), ix))\n\tend\n\n\tBase.length(iter::MiniBatch) = length(iter.ds)\n\tBase.eltype(iter::MiniBatch) = eltype(iter.ds)\nend\n\n# ╔═╡ 714137c2-8900-11eb-3b4b-57abc5409bd2\nlet _ix = 0, bsz = 15\n\tfor batch ∈ MiniBatch{Float64}(data, bsz)\n\t\t@assert length(batch) == bsz || 0 ≤ length(batch) ≤ bsz\n\t\t_ix += 1\n\tend\n\t@test _ix == 7\nend\n\n# ╔═╡ 7125e906-8900-11eb-3cd5-69755931c32d\nlet _ix = 0, bsz = 12\n\tfor batch ∈ MiniBatch{Float64}(data, bsz)\n\t\t@assert length(batch) == bsz || 0 ≤ length(batch) ≤ bsz\n\t\t_ix += 1\n\tend\n\t@test _ix == 9\nend\n\n# ╔═╡ 401f3d8e-8904-11eb-1065-1de6c9bf32be\nmd\"\"\"\nlet's rewrite our gradient(∇) descent with min-batch:\n\"\"\"\n\n# ╔═╡ 70eef976-8900-11eb-3a03-af04f8dea9cc\nfunction minibatch_∇_descent(inputs::Vector{Vector{T}};\n    η=1e-5, nepochs=5_000, bsize=10) where T <: AF\n  u = Uniform(-1., 1.)\n  θ = [rand(u) for _ ∈ 1:2]\n\n  for epoch ∈ 1:nepochs\n\t\tfor batch ∈ MiniBatch{eltype(inputs[1][1])}(inputs, bsize)\n\t\t\t∇ = μ([linear_∇(x, y, θ) for (x, y) ∈ inputs])\n    \t\tθ = ∇_step(θ, ∇, -η)\n\t\tend\n    epoch % 100 == 0 && println(\"$(epoch) => θ: $(θ)\")\n  end\n\n  (slope, intercept) = θ\nend\n\n# ╔═╡ 70d67f74-8900-11eb-0174-f5c05571848e\nbegin\n  slope₂, intercept₂ = minibatch_∇_descent(data; nepochs=100) ## only 100 epochs \n  @test 9.90 ≤ slope₂ ≤ 10.1\n  @test abs(intercept₂) ≤ 1.0\nend\n\n# ╔═╡ 8d33a0f4-8906-11eb-3690-ddd49fc6cee1\nbegin\n  # x_₂ = [-50.0, 50.0]\n  y_₂ = slope .* x_ .+ intercept\n  #\n  scatter(map(x -> x[1], data), map(y -> y[2], data), legend=false)\n  plot!(x_, y_₂, lw=3, color=:darkred)\nend\n\n# ╔═╡ 0a1acf66-8907-11eb-3eac-59a3e18d9c43\nmd\"\"\"\nIn this instance our mini-batch gradient descent worked pretty well, finding the optimal parameters in just 100 iteration (and actually less)... \n\nBasing gradient step on a small min-batch or just on one sampel (in the case of stochastic gradient descent) allows to take more steps, but the gradient can fluctuate a lot...\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─380c26d0-881d-11eb-0461-f339488ea81e\n# ╠═e03dd22c-884c-11eb-2432-3dc04b0cf286\n# ╟─83e01f80-884a-11eb-1ef7-e9cb5ab3ed20\n# ╟─853ab02c-884a-11eb-01bf-1712dc177ffb\n# ╟─4c951444-8869-11eb-0b88-55a9fb9e51e6\n# ╟─8c87c3b8-884a-11eb-10c8-73e2dab560ea\n# ╟─8c6ba818-884a-11eb-23e0-2f1c297d88f5\n# ╠═d2d18b22-884c-11eb-1f93-037453c5395b\n# ╟─221734fe-8869-11eb-331a-b5810d0b784c\n# ╟─d297fa06-884c-11eb-294e-85992f901be1\n# ╠═1859c082-8853-11eb-18f6-2bc7a180b4a2\n# ╠═d27feefa-884c-11eb-3b84-1f529d7f6410\n# ╟─5618fb40-8853-11eb-3d2f-032437d22a09\n# ╠═55fab426-8853-11eb-01f8-cbde45c7de9c\n# ╟─55e3efea-8853-11eb-0821-c5c580bc8fc5\n# ╠═55c56cc8-8853-11eb-04f4-3be84a352808\n# ╟─d25d8eac-884c-11eb-2063-27413f8aba04\n# ╠═480f7b18-8854-11eb-2898-8d876317ebe2\n# ╠═47ee8cb4-8854-11eb-252b-852fd56aa40f\n# ╟─47d2c2cc-8854-11eb-35f9-952876481d02\n# ╠═f5980b54-8856-11eb-3e30-89c3f188ca8d\n# ╟─f57b16b6-8856-11eb-3409-47f7b438f491\n# ╠═f55dd09c-8856-11eb-1823-290fcb200662\n# ╠═33df0458-885c-11eb-2635-371a9590d833\n# ╠═e76a5b58-885c-11eb-0067-010ba1d4c9b5\n# ╠═e783d618-8858-11eb-0c0b-b57e54bd3757\n# ╟─e767c1bc-8858-11eb-1b29-596a25a4fea4\n# ╟─e747b052-8858-11eb-3c50-5355fef542c9\n# ╟─cc17413a-885d-11eb-1629-47fc5220529e\n# ╠═cbfa193c-885d-11eb-3a48-97b26377b4fb\n# ╠═cbe180fe-885d-11eb-1307-7f3ac4897441\n# ╠═d21bb0fe-884c-11eb-224f-216a811365a8\n# ╠═de2e6604-8863-11eb-3a27-8f8e8b55e5d8\n# ╠═3082d12e-8864-11eb-06bc-cdf9202cd20a\n# ╟─306b8d52-8864-11eb-1cbd-1341afcd52ff\n# ╟─304ff894-8864-11eb-1449-b71da9112247\n# ╟─8c4d28fc-884a-11eb-0de2-b58988dc7422\n# ╟─8a07d906-8869-11eb-0bae-2582b352c05c\n# ╠═89ebdac6-8869-11eb-25ac-2dac6a4b20aa\n# ╠═89d1728a-8869-11eb-0001-875c2a452cf8\n# ╠═c0cc67c8-888b-11eb-272c-05a727c634ea\n# ╠═4bf3d986-886d-11eb-3ea8-7926f5babce0\n# ╟─d8f972a0-8881-11eb-2be8-db89fb95a9f1\n# ╠═1b26337a-8882-11eb-2439-e106cdb884f5\n# ╠═1b09cc9e-8882-11eb-0efc-630028d87217\n# ╟─28b44b3c-88f8-11eb-23dd-bbfe325d70d3\n# ╠═1c89f188-88f6-11eb-026c-e59bb08ac7ac\n# ╟─1ad358e4-8882-11eb-0559-bd43867dacfd\n# ╟─d8d3bb0a-8881-11eb-35b2-8f486d6cc094\n# ╠═cd7c444a-8893-11eb-2409-f161ebc287b5\n# ╠═714137c2-8900-11eb-3b4b-57abc5409bd2\n# ╠═7125e906-8900-11eb-3cd5-69755931c32d\n# ╟─401f3d8e-8904-11eb-1065-1de6c9bf32be\n# ╠═70eef976-8900-11eb-3a03-af04f8dea9cc\n# ╠═70d67f74-8900-11eb-0174-f5c05571848e\n# ╠═8d33a0f4-8906-11eb-3690-ddd49fc6cee1\n# ╟─0a1acf66-8907-11eb-3eac-59a3e18d9c43\n", "meta": {"hexsha": "04b8a10b67a526007ea12ed0904203d4a3b439b2", "size": 15965, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Data Science From Scratch/08_Gradient_Descent.jl", "max_stars_repo_name": "pascal-p/julia-notebooks", "max_stars_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-01T20:34:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-01T20:34:56.000Z", "max_issues_repo_path": "Data Science From Scratch/08_Gradient_Descent.jl", "max_issues_repo_name": "pascal-p/julia-notebooks", "max_issues_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Science From Scratch/08_Gradient_Descent.jl", "max_forks_repo_name": "pascal-p/julia-notebooks", "max_forks_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-10T09:03:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T09:03:18.000Z", "avg_line_length": 30.3517110266, "max_line_length": 465, "alphanum_fraction": 0.6967115565, "num_tokens": 6797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711870587667, "lm_q2_score": 0.8824278741843884, "lm_q1q2_score": 0.7500382677142486}}
{"text": "#=\n# 3. Applying pulse forcing to a flow\nHere, we will show how to apply a transient force (a 'pulse') to a flow.\n=#\n\nusing ViscousFlow\n#-\nusing Plots\n\n#=\nFor this case, we first seek to introduce a pulse to an otherwise quiescent fluid,\nwith no boundaries. The pulse shape will be a smooth dipole, directed upward.\n\nWe will start with the usual steps: specify the problem parameters and the discretization.\n=#\n\nRe = 200\nxlim, ylim = (-2,2), (-2,4)\nΔx,Δt = setstepsizes(Re,gridRe=4)\n\n#=\n### Construct the pulse\nNow create the pulse. For the spatial shape of this pulse, we make use of a Gaussian\nfield, differentiated once in the `x` direction. We will center it at (0,0), and\ngive it a strength of 10.\n=#\nσx = 0.5\nσy = 0.1\ngauss = SpatialGaussian(σx,σy,0,0,10,deriv=1);\n\n#=\nNow we now 'shape' the pulse in time, also with a Gaussian. We center it at `t = 0.1`\nwith a half-width in time equal to 0.1.\n=#\nt0 = 0.1\nσt = 0.1\npparams = PulseParams(gauss,t0,σt);\n\n#=\n### Construct the system structure\nWe supply these pulse characteristics with the keyword argument `pulses` as we\nset up the usual system structure:\n=#\nsys = NavierStokes(Re,Δx,xlim,ylim,Δt,pulses=pparams)\n\n#=\nThe remaining steps go just as they did for the previous examples. We will simulate\nthe pulse for 5 time units and make an animation of the results:\n=#\nu0 = newstate(sys)\ntspan = (0.0,10.0) # longer than we need, but just being safe\nintegrator = init(u0,tspan,sys)\n#-\nstep!(integrator,5.0)\n\n#=\n### Examine\n=#\nsol = integrator.sol\n@gif for t in sol.t\n    plot(vorticity(sol,sys,t),sys)\nend every 5\n#-\nplot(streamfunction(integrator),sys,title=\"Streamfunction at t = $(round(integrator.t,digits=2))\")\n\n#=\nWe can also supply more than one pulse. Let's give 3, each separated by 1 time unit.\n=#\npparams = [PulseParams(gauss,0.1,0.1), PulseParams(gauss,1.1,0.1), PulseParams(gauss,2.1,0.1)];\n#-\nsys = NavierStokes(Re,Δx,xlim,ylim,Δt,pulses=pparams)\n#-\nu0 = newstate(sys)\ntspan = (0.0,10.0)\nintegrator = init(u0,tspan,sys)\n#-\nstep!(integrator,4.0)\n#=\n### Examine\n=#\nsol = integrator.sol\n@gif for t in sol.t\n    plot(vorticity(sol,sys,t),sys)\nend every 5\n", "meta": {"hexsha": "61e72b6b8a637a3ee56685f1359837a4c7b3cc46", "size": 2120, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/literate/3.-Applying-pulse-forcing-to-a-flow.jl", "max_stars_repo_name": "YvonneThoy/ViscousFlow.jl", "max_stars_repo_head_hexsha": "b36600c2b3561c29ecd53cd68cdf15fc50f08525", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 51, "max_stars_repo_stars_event_min_datetime": "2020-05-06T19:45:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T09:47:59.000Z", "max_issues_repo_path": "test/literate/3.-Applying-pulse-forcing-to-a-flow.jl", "max_issues_repo_name": "antoniosgeme/ViscousFlow.jl", "max_issues_repo_head_hexsha": "0eb254702b0298a3dabbd27b312b80190b8492ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2020-06-05T05:19:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T17:49:06.000Z", "max_forks_repo_path": "test/literate/3.-Applying-pulse-forcing-to-a-flow.jl", "max_forks_repo_name": "antoniosgeme/ViscousFlow.jl", "max_forks_repo_head_hexsha": "0eb254702b0298a3dabbd27b312b80190b8492ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-04-27T19:38:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T17:31:33.000Z", "avg_line_length": 24.9411764706, "max_line_length": 98, "alphanum_fraction": 0.7080188679, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7500192048712143}}
{"text": "# cubic L2 norm (times a constant\n\nexport CubeNormL2\n\n\"\"\"\n**Cubic Euclidean norm (weighted)**\n\n    CubeNormL2(λ=1.0)\n\nWith a nonnegative scalar `λ`, returns the function\n```math\nf(x) = λ\\\\|x\\\\|^3.\n```\n\"\"\"\nstruct CubeNormL2{R <: Real} <: ProximableFunction\n    lambda::R\n    function CubeNormL2{R}(lambda::R) where R\n        if lambda < 0\n            error(\"coefficient λ must be nonnegative\")\n        else\n            new(lambda)\n        end\n    end\nend\n\nis_convex(f::CubeNormL2) = true\nis_smooth(f::CubeNormL2) = true\n\nCubeNormL2(lambda::R=1.0) where {R <: Real} = CubeNormL2{R}(lambda)\n\nfunction (f::CubeNormL2{R})(x::AbstractArray{T}) where {R, T <: RealOrComplex{R}}\n    return f.lambda * norm(x)^3\nend\n\nfunction gradient!(y::AbstractArray{T}, f::CubeNormL2{R}, x::AbstractArray{T}) where {R, T <: RealOrComplex{R}}\n    norm_x = norm(x)\n    y .= (3 * f.lambda * norm_x) .* x\n    return f.lambda * norm_x^3\nend\n\nfunction prox!(y::AbstractArray{T}, f::CubeNormL2{R}, x::AbstractArray{T}, gamma::R=R(1)) where {R, T <: RealOrComplex{R}}\n    norm_x = norm(x)\n    scale = 2 / (1 + sqrt(1 + 12 * gamma * f.lambda * norm_x))\n    y .= scale .* x\n    return f.lambda * (scale * norm_x)^3\nend\n\nfunction prox_naive(f::CubeNormL2{R}, x::AbstractArray{T}, gamma=R(1)) where {R, T <: RealOrComplex{R}}\n    y = 2 / (1 + sqrt(1 + 12 * gamma * f.lambda * norm(x))) * x\n    return y, f.lambda * norm(y)^3\nend\n", "meta": {"hexsha": "d3ae7929b67e90faa0da8d74ece4428abd2e7701", "size": 1395, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/cubeNormL2.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_stars_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/cubeNormL2.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_issues_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/cubeNormL2.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ProximalOperators.jl-a725b495-10eb-56fe-b38b-717eba820537", "max_forks_repo_head_hexsha": "0e77f72cae83cceb27543a7a91af0762fc5f1d88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8269230769, "max_line_length": 122, "alphanum_fraction": 0.6157706093, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389113, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7500191991563725}}
{"text": "# Triangulations of point sets\n# ===========================\n#\n#\n# These examples can be loaded into Julia (Revise.jl recommended)\n# and run by calling one of the methods with the optional arguments \"Plotter=PyPlot\".\n# Alternatively, you can download a [jupyter notebook](example_pointsets.ipynb) created\n# from this source.\n# \n# \n#---\n#\n# Set  up environment\n\nusing Triangulate\nusing Test\n\ninjupyter()=(isdefined(Main, :IJulia) && Main.IJulia.inited)\n\nif injupyter()\n    import PyPlot\nend\n\n# ### Delaunay triangulation of point set\n#\n# Create a set of random points in the plane and calculate\n# the Delaunay triangulation of this set of points. It is a triangulation\n# where for each triangle, the interior of its circumcircle  does not contain any points\n# of the trianglation.\n#\n# The Delaunay triangulation of a set of points in general position\n# (no 4 of them on a circle) is unique. At the same time, it is a\n# triangulation of the convex hull of these points.\n#\n# Given an input list of points, without any further flags, Triangle creates\n# just this triangulation (the \"Q\" flag suppresses the text output of Triangle).\n# For this and the next examples, the input list of points is created randomly,\n# but on a raster, preventing the appearance of too close points.\n# \nfunction example_convex_hull(;Plotter=nothing,n=10,raster=10)\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=hcat(unique([ Cdouble[rand(1:raster)/raster, rand(1:raster)/raster] for i in 1:n])...)\n    display(triin)\n    (triout, vorout)=triangulate(\"Q\", triin)\n    display(triout)\n    plot_in_out(Plotter,triin,triout,title=\"Convex hull\")\n    @test numberofpoints(triin)==numberofpoints(triout)\n    @test numberoftriangles(triout)>0\nend\n#\ninjupyter()&& example_convex_hull(Plotter=PyPlot,n=10,raster=10);\n\n\n# ### Delaunay triangulation of point set with boundary\n#\n# Same as the previous example, but in addition specify the \"c\" flag\n# In this case, Triangle outputs an additional list of segments\n# describing the boundary of the convex hull. In fact this is a constrained\n# Delaunay triangulation (CDT) where the boundary segments\n# are the seen constraining edges which must appear in the output.\nfunction example_convex_hull_with_boundary(;Plotter=nothing,n=10,raster=10)\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=hcat(unique([ Cdouble[rand(1:raster)/raster, rand(1:raster)/raster] for i in 1:n])...)\n    display(triin)\n    (triout, vorout)=triangulate(\"cQ\", triin)\n    display(triout)\n    @test numberofpoints(triin)==numberofpoints(triout)\n    @test numberoftriangles(triout)>0\n    @test numberofsegments(triout)>0\n    plot_in_out(Plotter,triin,triout,title=\"Convex hull with boundary\")\nend\n#\ninjupyter()&&  example_convex_hull_with_boundary(Plotter=PyPlot,n=10,raster=10);\n\n# ### Delaunay triangulation of point set with Voronoi diagram\n#\n# Same as the previous example, but instead of \"c\" specify the \"v\" flag\n# In this case, Triangle outputs information about the Voronoi diagram\n# of the point set which is a structure dual to  the Delaunay triangulation.\n#\n# The Voronoi cell around a point $p$ a point set $S$ is defined\n# as the set of points $x$ such that $|x-p|<|x-q|$ for all $q\\in S$\n# such that $p\\neq q$.\n# The Voronoi cells of boundary points\n# of the convex hull are of infinite size. The corners of the Voronoi\n# cells are the circumcenters of the triangles. They can be far\n# outside of the triangulated domain.\nfunction example_convex_hull_voronoi(;Plotter=nothing,n=10,raster=10)\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=hcat(unique([ Cdouble[rand(1:raster)/raster, rand(1:raster)/raster] for i in 1:n])...)\n    display(triin)\n    (triout, vorout)=triangulate(\"vQ\", triin)\n    display(triout)\n    display(vorout)\n    plot_in_out(Plotter,triin,triout,voronoi=vorout,title=\"Convex hull with Voronoi diagram\")\n    @test numberofpoints(triin)==numberofpoints(triout)\n    @test numberoftriangles(triout)>0\n    @test numberofpoints(vorout)>0\nend\n#\ninjupyter()&&  example_convex_hull_voronoi(Plotter=PyPlot,n=10,raster=10);\n\n# ### Boundary conforming Delaunay triangulation of point set\n# Specify \"c\" flag for convex hull segments, \"v\" flag for Voronoi\n# and \"D\" flag for creating a boundary conforming Delaunay triangulation of\n# the point set. In this case additional points are created which split\n# the boundary segments and ensure that all triangle circumcenters\n# lie within the convex hull.\n# Due to random input, there may be situations where Triangle fails with this task,\n# so we check for the corresponding exception.\nfunction example_convex_hull_voronoi_delaunay(;Plotter=nothing,n=10,raster=10)\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=hcat(unique([ Cdouble[rand(1:raster)/raster, rand(1:raster)/raster] for i in 1:n])...)\n    display(triin)\n    try\n        (triout, vorout)=triangulate(\"vcDQ\", triin)\n        plot_in_out(Plotter,triin,triout,voronoi=vorout,title=\"Convex hull with Voronoi diagram\")\n        display(triout)\n        display(vorout)\n        @test numberofpoints(triin)<=numberofpoints(triout)\n        @test numberoftriangles(triout)>0\n        @test numberofpoints(vorout)>0\n    catch err\n        if typeof(err)==TriangulateError\n            println(\"Triangle had some problem.\")\n            return true\n        end\n    end\nend\n#\ninjupyter()&&  example_convex_hull_voronoi_delaunay(Plotter=PyPlot,n=10,raster=10);\n\n# ### Constrained Delaunay triangulation (CDT) of a point set with edges\n# Constrained Delaunay triangulation (CDT) of a point set with\n# additional constraints given a priori. This is obtained when\n# specifying the \"p\" flag and an additional list of segments each described\n# by two points \n# which should become edges of the triangulation. Note that\n# the resulting triangulation is not Delaunay in the sense\n# given above.\nfunction example_cdt(;Plotter=nothing,n=10,raster=10)\n    triin=Triangulate.TriangulateIO()\n    triin.pointlist=hcat(unique([ Cdouble[rand(1:raster)/raster, rand(1:raster)/raster] for i in 1:n])...)\n    npt=size(triin.pointlist,2)\n    triin.segmentlist=Matrix{Cint}([1 2; npt-1 npt-2;  1 npt;]')\n    triin.segmentmarkerlist=Vector{Cint}([2,3,4])\n    display(triin)\n    (triout, vorout)=triangulate(\"pcQ\", triin)\n    display(triout)\n    plot_in_out(Plotter,triin,triout,title=\"CDT\")\n    @test numberofpoints(triin)<=numberofpoints(triout)\n    @test numberofsegments(triout)>=numberofsegments(triin)\n    @test numberoftriangles(triout)>0\nend\n#\ninjupyter()&&  example_cdt(Plotter=PyPlot,n=10,raster=10);\n\n", "meta": {"hexsha": "2b64862a93f3d5e1f21d8e669a8c2a31552afafe", "size": 6525, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/example_pointsets.jl", "max_stars_repo_name": "fonsp/Triangulate.jl", "max_stars_repo_head_hexsha": "c741278fab9f0a6abaa1689057ad9b622905e875", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2019-12-12T20:00:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T20:05:24.000Z", "max_issues_repo_path": "test/example_pointsets.jl", "max_issues_repo_name": "fonsp/Triangulate.jl", "max_issues_repo_head_hexsha": "c741278fab9f0a6abaa1689057ad9b622905e875", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-12-12T17:16:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T17:09:21.000Z", "max_forks_repo_path": "test/example_pointsets.jl", "max_forks_repo_name": "JuliaGeometry/TriangulateIO.jl", "max_forks_repo_head_hexsha": "cb7eacf7b21d0ae0f6023bfb2a70b80a1dea6e64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:00:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T15:00:56.000Z", "avg_line_length": 41.2974683544, "max_line_length": 106, "alphanum_fraction": 0.7379310345, "num_tokens": 1903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7500191956670668}}
{"text": "# ---\n# title: 713. Subarray Product Less Than K\n# id: problem713\n# author: Indigo\n# date: 2021-06-29\n# difficulty: Medium\n# categories: Array, Two Pointers\n# link: <https://leetcode.com/problems/subarray-product-less-than-k/description/>\n# hidden: true\n# ---\n# \n# Your are given an array of positive integers `nums`.\n# \n# Count and print the number of (contiguous) subarrays where the product of all\n# the elements in the subarray is less than `k`.\n# \n# **Example 1:**  \n# \n#     \n#     \n#     Input: nums = [10, 5, 2, 6], k = 100\n#     Output: 8\n#     Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].\n#     Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.\n#     \n# \n# **Note:**\n# \n# * `0 < nums.length <= 50000`.\n# * `0 < nums[i] < 1000`.\n# * `0 <= k < 10^6`.\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction num_subarray_productLess_than_k(nums::Vector{Int}, k::Int)\n    k <= 1 && return 0\n    res, left = 0, 1\n    p = 1\n    for (right, val) in enumerate(nums)\n        p *= val\n        while p >= k\n            p ÷= nums[left]\n            left += 1\n        end\n        res += right - left + 1\n    end\n    return res\nend\n## @lc code=end\n", "meta": {"hexsha": "3b67608fe5e0b96dd392651f0494d23b27020229", "size": 1252, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/713.subarray-product-less-than-k.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/713.subarray-product-less-than-k.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/713.subarray-product-less-than-k.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 24.0769230769, "max_line_length": 128, "alphanum_fraction": 0.5694888179, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7500096461416613}}
{"text": "export Sum\n\n\"\"\"\n**Sum of functions**\n\n    Sum(f₁,…,fₖ)\n\nGiven functions `f₁` to `fₖ`, returns their sum\n\n```math\ng(x) = ∑_{i=1}^k f_i(x).\n```\n\nThe functions `fᵢ` should all have the same domain, which will be the domain of\nthe result. If all `fᵢ` have gradients then this function will also have a\ngradient.\n\n\"\"\"\nstruct Sum{T <: Tuple} <: ProximableFunction fs::T end\n\nSum(fs::Vararg{ProximableFunction}) = Sum((fs...,))\n\n# note: is_prox_accurate false because prox in general doesn't exist?\nis_prox_accurate(f::Sum) = false\nis_convex(f::Sum) = all(is_convex.(f.fs))\nis_set(f::Sum) = all(is_set.(f.fs))\nis_cone(f::Sum) = all(is_cone.(f.fs))\nis_affine(f::Sum) = all(is_affine.(f.fs))\nis_smooth(f::Sum) = all(is_smooth.(f.fs))\nis_quadratic(f::Sum) = all(is_quadratic.(f.fs))\nis_generalized_quadratic(f::Sum) = all(is_generalized_quadratic.(f.fs))\nis_strongly_convex(f::Sum) = all(is_convex.(f.fs)) && any(is_strongly_convex.(f.fs))\n\nfunction (sumobj::Sum)(x::AbstractArray{T}) where {R <: Real, T <: Union{R, Complex{R}}}\n    sum = zero(R)\n    for f in sumobj.fs\n        sum += f(x)\n    end\n    sum\nend\n\nfunction gradient!(grad::AbstractArray{T}, sumobj::Sum, x::AbstractArray{T}) where {R <: Real, T <: Union{R, Complex{R}}}\n    # gradient of sum is sum of gradients\n    val = zero(R)\n    # to keep track of this sum, i may not be able to\n    # avoid allocating an array\n    grad .= zero(T)\n    temp = similar(grad)\n    for f in sumobj.fs\n        val += gradient!(temp, f, x)\n        grad .+= temp\n    end\n    return val\nend\n\nfun_name(f::Sum) = \"sum\"\nfun_dom(f::Sum) = fun_dom(f.fs[1]) # check to make sure same??\nfun_expr(f::Sum) = \"x ↦ f₁(x) + … + fₖ(x)\"\nfun_params(f::Sum) = \"n/a\"\n", "meta": {"hexsha": "179cd6193ffed008fb7bba9839c1842f629c7807", "size": 1683, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/calculus/sum.jl", "max_stars_repo_name": "lostella/ProximalOperators.jl", "max_stars_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-15T13:57:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T13:57:52.000Z", "max_issues_repo_path": "src/calculus/sum.jl", "max_issues_repo_name": "lostella/ProximalOperators.jl", "max_issues_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/calculus/sum.jl", "max_forks_repo_name": "lostella/ProximalOperators.jl", "max_forks_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.05, "max_line_length": 121, "alphanum_fraction": 0.6434937611, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7500096447511023}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Statistics, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.7\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\tdist1 = TriangularDist(0,1,1)\n\tdist2 = TriangularDist(0,1,0)\n\tN=10^6\n\n\tdata1, data2 = rand(dist1,N), rand(dist2,N)\n\tdataSum = data1 + data2\nend\n\n# ╔═╡ 8f60b2f6-20f9-11eb-0a66-771e655035a3\nmgf(s) = 4(1+(s-1)*MathConstants.e^s)*(MathConstants.e^s-1-s)/s^4\n\n# ╔═╡ 8f61044a-20f9-11eb-1485-d145145c4c57\nmgfPointEst(s) = mean([MathConstants.e^(s*z) for z in \n\t\t\t\t\trand(dist1,20) + rand(dist2,20)])\n\n# ╔═╡ 8f6181a4-20f9-11eb-3eae-6dc331b9a88a\nbegin\n\tp1 = histogram(dataSum, bins=80, normed=:true, \n\t\tylims=(0,1.4), xlabel=\"z\", ylabel=\"PDF\")\n\n\tsGrid = -1:0.01:1\n\tp2 = plot(sGrid, mgfPointEst.(sGrid), c=:blue, ylims=(0,3.5))\n\tp2 = plot!(sGrid, mgf.(sGrid), c=:red)\n\tp2 = plot!( [minimum(sGrid),maximum(sGrid)], \n\t\t[minimum(sGrid),maximum(sGrid)].+1, \n\t\tc=:black, xlabel=\"s\", ylabel=\"MGF\")\n\n\tplot(p1, p2, legend=:none, size=(800, 400))\nend\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.7\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═8f60b2f6-20f9-11eb-0a66-771e655035a3\n# ╠═8f61044a-20f9-11eb-1485-d145145c4c57\n# ╠═8f6181a4-20f9-11eb-3eae-6dc331b9a88a\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "55932c671434bc2cf292a018ac1975f22d7af76f", "size": 1698, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.07.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.07.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.07.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 26.53125, "max_line_length": 70, "alphanum_fraction": 0.7014134276, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976953003183444, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7500096429124641}}
{"text": "\n@doc raw\"\"\"\n\tquantiledep(x,y,q)\n\nQuantile Dependence at the `q`-th quantile of vector-like data `x` and `y`.\n\nLet ``q_x`` and ``q_y`` be the `q`-th quantiles of `x` and `y`.\n\nReturns ``E[xy | x \\leq q_x, y \\leq q_y] / q`` if `q<=0.5` and\n``(1 -2q + E[xy | x \\leq q_x, y \\leq q_y]) / (1-q)`` otherwise.\n\"\"\"\nfunction quantiledep(x,y,q)\n    qx = quantile(x,q)\n    qy = quantile(y,q)\n    tmp = mean((x.<=qx).*(y.<=qy))\n    if q <= 0.5\n        return tmp/q\n    else\n        return (1-2*q + tmp)/(1-q)\n    end\nend\n\n\n\n\n\"\"\"\n\texceedancecor(x,y,c;kind=:both,side=:lower)\n\nComputes exceedance correlations between `x` and `y`, using exceedance threshold `c`.\nKeyword `kind` refers to which type of conditioning: `:both` conditions on `x` and `y` simultaneously,\nwhile `:onx` conditions only on `x`. Keyword `side` refers to look below (`:lower`) or above (`:upper`)\nthe threshold `c`. Inputs `x` and `y` are standardized before conditioning, \nso `c` should be in standard deviation units.\n\"\"\"\nfunction exceedancecor(x,y,c;kind=:both,side=:lower)\n    xs = standardize(x)\n\tys = standardize(y)\n    if side==:lower\n        if kind==:both\n            loc = (xs .<= c) .& (ys .<= c)\n        elseif kind==:onx\n            loc = (xs .<= c)\n        end\n    elseif side==:upper\n        if kind==:both\n            loc = (xs .>= c) .& (ys .>= c)\n        elseif kind==:onx\n            loc = (xs .>= c)    \n        end\n    end\n\treturn cor(xs[loc],ys[loc])\nend\n\n\n\n\n\"\"\"\n\tdownsidebeta(x,y;kind=:both)\n\nComputes the downside beta of `y` on `x` as defined in Ang & Chen. \n\n`kind=:onx` allows to condition only on `x`.\n\"\"\"\nfunction downsidebeta(x,y;kind=:both)\n\tmux = mean(x)\n\tmuy = mean(y)\n\tif kind==:both\n\t\tloc = (x .<= mux) .& (y .<= muy)\n\telseif kind==:onx\n\t\tloc = (x .<= mux)\n\tend\n\txtmp = x[loc]\n\tytmp = y[loc]\n\tvarx = var(xtmp)\n\tcovxy = cov(xtmp,ytmp)\n\treturn covxy/varx\nend\n\n\n\n\"\"\"\n\tupsidebeta(x,y;kind=:both)\n\nComputes the upside beta of `y` on `x` as defined in Ang & Chen. \n\n`kind=:onx` allows to condition only on `x`.\n\"\"\"\nfunction upsidebeta(x,y;kind=:both)\n\tmux = mean(x)\n\tmuy = mean(y)\n\tif kind==:both\n\t\tloc = (x .>= mux) .& (y .>= muy)\n\telseif kind==:onx\n\t\tloc = (x .>= mux)\n\tend\n\txtmp = x[loc]\n\tytmp = y[loc]\n\tvarx = var(xtmp)\n\tcovxy = cov(xtmp,ytmp)\n\treturn covxy/varx\nend\n\n\n# x here is \"the market return\"\n\n@doc raw\"\"\"\n\tcoskewness(x,y)\n\nComputes the coskewness between vectors `x` and `y`. The vector `x` receives the\npowers in the expression.\n\n``\\frac{E[(x - E[x])^2 (y-E[y])]}{\\sigma_x^2 \\sigma_y}``\n\n\"\"\"\nfunction coskewness(x,y)\n    dmx = x .- mean(x)\n    dmy = y .- mean(y)\n    top = mean( dmy .* (dmx.^2))\n    bot = std(dmy) * var(dmx)\n    return top/bot\nend\n\n@doc raw\"\"\"\n\tcokurtosis(x,y;kind::Symbol=:asymmetric)\n\nComputes the cokurtosis between vectors `x` and `y`. The default is asymmetric cokurtosis.\n\n`kind=:asymmetric`:\n``\\frac{E[(x - E[x])^3 (y-E[y])]}{\\sigma_x^3 \\sigma_y}``\n\n`kind=:symmetric`:\n``\\frac{E[(x - E[x])^2 (y-E[y])^2]}{\\sigma_x^2 \\sigma_y^2}``\n\"\"\"\nfunction cokurtosis(x,y;kind::Symbol=:asymmetric)\n    dmx = x .- mean(x)\n    dmy = y .- mean(y)\n    if kind == :symmetric\n        top = mean( (dmy.^2) .* (dmx.^2))\n        bot = var(dmy) * var(dmx)\n    else\n        top = mean( dmy .* (dmx.^3))\n        bot = std(dmy)  * std(dmx)^3\n    end\n    return top/bot\nend\n\n\n\n#### TODO\n# - better API\n\n\n\n#### Correlation-based (Ang & Chen 2001 + statistical test of Hong, Tu, & Zhou 2007 + one-sided as in Schreindorfer 2019)\nfunction downsidecor(x,y)\n    qs = 0.15:0.025:1\n    out = zeros(length(qs))\n    for (i,qi) in enumerate(qs)\n        qxi = quantile(x,qi)\n        loc = x .<= qxi\n        tmpxi = x[loc]\n        tmpyi = y[loc]\n        out[i] = cor(tmpxi,tmpyi)\n        #println([length(tmpxi) length(tmpyi) length(tmpxj) length(tmpyj)])\n    end\n    return out\nend\n\nfunction upsidecor(x,y)\n    qs = 0:0.025:0.85\n    out = zeros(length(qs))\n    for (i,qi) in enumerate(qs)\n        qxi = quantile(x,qi)\n        loc = x .>= qxi\n        tmpxi = x[loc]\n        tmpyi = y[loc]\n        out[i] = cor(tmpxi,tmpyi)\n        #println([length(tmpxi) length(tmpyi) length(tmpxj) length(tmpyj)])\n    end\n    return out\nend\n\n\n\n##### Asymmetry test from Guofu Zhou et al.\n#standardize(x) = (x .- mean(x)) ./ std(x)\nbartlett(z) = abs(z) < 1 ? (1-abs(z)) : zero(eltype(z))\n# this only does 1 value of c\nfunction buildEC(x,y,c)\n\tT = length(x)\n\txs = standardize(x)\n\tys = standardize(y)\n\tiL = (xs .< -c) #.& (ys .< -c)\n\tiU = (xs .> c) #.& (ys .> c)\n\tlower_xs = xs[iL]\n\tupper_xs = xs[iU]\n\tlower_ys = ys[iL]\n\tupper_ys = ys[iU]\n\tTl = length(lower_xs)\n\tTu = length(upper_xs)\n\tlower_cor = cor(lower_xs,lower_ys)\n\tupper_cor = cor(upper_xs,upper_ys)\n\t\n\t# standardize again\n\txs[iL] = standardize(lower_xs)\n\tys[iL] = standardize(lower_ys)\n\txs[iU] = standardize(upper_xs)\n\tys[iU] = standardize(upper_ys)\n\t\n\tEC = (((T-Tu)/T) .* (xs.*ys .- upper_cor) .* iU) .- (((T-Tl)/T) .* (xs.*ys .- lower_cor) .* iL)\n\treturn (EC=EC,corL=lower_cor,corU=upper_cor)\nend\n\n# this wraps it together\n# conditioning is standardized x .< -c[i] vs standardized x .> c[i]\n# p represents some sort of bandwith? -- lag order?\nfunction asymmetrictest(x,y,c,p)\n\tT = length(x)\n\tNc = length(c)\n\t\n\tif Nc == 1\n\t\touts=buildEC(x,y,c)\n\t\tECmat=outs.EC\n\t\tuppercors = outs.corU\n\t\tlowercors = outs.corL\n\t\tS = 0.0\n\t\tfor L=-p:p\n\t\t\tw = bartlett(L/p)\n\t\t\tg_l = 0.0\n\t\t\tfor t=(abs(L)+1):T\n\t\t\t\tg_l += ECmat[t]*ECmat[t-abs(L)]\n\t\t\tend\n\t\t\tS += w*(1/T)*g_l\n\t\tend\n\telse\n\t\tECmat = zeros(eltype(x),T,Nc)\n\t\tuppercors = zeros(eltype(x),Nc)\n\t\tlowercors = zeros(eltype(x),Nc)\n\t\tfor i =1:Nc\n\t\t\touts=buildEC(x,y,c[i])\n\t\t\tECmat[:,i]=outs.EC\n\t\t\tuppercors[i] = outs.corU\n\t\t\tlowercors[i] = outs.corL\n\t\tend\n\t\tS = zeros(eltype(x),Nc,Nc)\n\t\tfor L=-p:p\n\t\t\tw = bartlett(L/p)\n\t\t\tg_l = zeros(eltype(x),Nc,Nc)\n\t\t\tfor ic=1:Nc,jc=1:Nc\n\t\t\t\tfor t=(abs(L)+1):T\n\t\t\t\t\tg_l[ic,jc] += ECmat[t,ic]*ECmat[t-abs(L),jc]\n\t\t\t\tend\n\t\t\tend\n\t\t\tS += w*(1/T).*g_l\n\t\tend\n\tend\n\t\n\tJ = T * (uppercors - lowercors)' * inv(S) * (uppercors - lowercors)\n\tpval = pdf(Chisq(Nc),J)\n\treturn (pval=pval,J=J,S=S,corL=lowercors,corU=uppercors,T=T)\nend\n\n\n\n#### Entropy-based (Jiang, Wu, & Zhou 2018)\nquadrantprobabilities(f,c;kwargs...) = (LQP=hcubature(f, [-10;-10], [-c;-c];kwargs...), UQP=hcubature(f, [c;c], [10;10];kwargs...))\nfunction entropy_S(f,c;kwargs...)\n    newf(x) = (sqrt(abs(f(x))) - sqrt(abs(f(-x))))^2\n    int,se = hcubature(x->newf(x),[c;c],[20;20];kwargs...)\n    return (int/2,se)\nend\nfunction DOWN_ASY_JWZ(f,c=0;kwargs...)\n    lqp,uqp = quadrantprobabilities(f,c;kwargs...)\n    S = entropy_S(f,c;kwargs...)\n    val = sign(first(lqp)-first(uqp))*first(S)\n    return val\nend\n# FF = kde((standardize(dfnew[!,:GDPg]),standardize(dfnew[!,:NDSg])))\n# PF = InterpKDE(FF)\n# quadrantprobabilities.(x->pdf(PF,x[1],x[2]),0:0.5:1.5)", "meta": {"hexsha": "505c9949ff830e956c12cd259f226eaf6e3a9a2c", "size": 6701, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bivariate.jl", "max_stars_repo_name": "tbeason/AsymmetricRisk.jl", "max_stars_repo_head_hexsha": "f077a6a6eb634fa2325eccc177be6c0da977bfbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-25T21:16:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-27T02:50:16.000Z", "max_issues_repo_path": "src/bivariate.jl", "max_issues_repo_name": "tbeason/AsymmetricRisk.jl", "max_issues_repo_head_hexsha": "f077a6a6eb634fa2325eccc177be6c0da977bfbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-01-01T22:47:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-28T22:19:21.000Z", "max_forks_repo_path": "src/bivariate.jl", "max_forks_repo_name": "tbeason/AsymmetricRisk.jl", "max_forks_repo_head_hexsha": "f077a6a6eb634fa2325eccc177be6c0da977bfbc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9321428571, "max_line_length": 131, "alphanum_fraction": 0.5857334726, "num_tokens": 2462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7500096420163054}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.0\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 1c7e914c-03c9-11eb-11cf-0d9346305a53\nbegin\n\tusing Pkg\n\tcd(joinpath(dirname(@__FILE__),\"..\"))\n    Pkg.activate(pwd())\n\tusing NLopt\nend\n\n# ╔═╡ 1866ec44-03c9-11eb-0a21-416587e4e0e0\n# Solve the problem with NLopt\nlet\n\t\n\t\"\"\"\n\tFunction to be minimized (with its gradient)\n\t\"\"\"\n\tfunction myfun(x::Vector, grad::Vector)\n\t\tif length(grad) > 0\n\t\t\tgrad[1] = -1\n\t\t\tgrad[2] = -1\n\t\tend\n\t\treturn -x[1] - x[2]\n\tend\n\n\t\"\"\"\n\tConstraints in form c_i(x)  <= 0 (with gradient)\n\t\"\"\"\n\tfunction c1(x::Vector, grad::Vector)\n\t\tif length(grad) > 0\n\t\t\tgrad[1] = 2*x[1]\n\t\t\tgrad[2] = -1\n\t\tend\n\t\tx[1]^2 - x[2]\n\tend\n\n\tfunction c2(x::Vector, grad::Vector)\n\t\tif length(grad) > 0\n\t\t\tgrad[1] = 2*x[1]\n\t\t\tgrad[2] = 2*x[2]\n\t\tend\n\t\tx[1]^2 + x[2]^2 - 1\n\tend\n\t\n\t# optimisation setup\n\topt = Opt(:LD_SLSQP, 2)\n\topt.lower_bounds = [-Inf, 0.] # only x_2 > 0\n\topt.xtol_rel = 1e-4\n\topt.min_objective = myfun\n\tinequality_constraint!(opt, c1, 1e-8)\n\tinequality_constraint!(opt, c2, 1e-8)\n\n\t# solving it.\n\t(minf,minx,ret) = NLopt.optimize(opt, [0, 0])\n\tnumevals = opt.numevals # the number of function evaluations\n\tprintln(\"got $minf at $minx after $numevals iterations (returned $ret)\")\nend\n\n\n# ╔═╡ 2121e5be-03c9-11eb-2b8b-a10cb146216d\nret\n\n# ╔═╡ Cell order:\n# ╠═1c7e914c-03c9-11eb-11cf-0d9346305a53\n# ╠═1866ec44-03c9-11eb-0a21-416587e4e0e0\n# ╠═2121e5be-03c9-11eb-2b8b-a10cb146216d\n", "meta": {"hexsha": "b6e1f1686f62fd7619ddbcd0042fb52622772586", "size": 1416, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Exercises/PS04 - Optimisation techniques II.jl", "max_stars_repo_name": "BenLauwens/ES313.jl", "max_stars_repo_head_hexsha": "5a7553e53c288834f768d26e0d5aa22f9062b6af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-12-17T16:00:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-18T04:09:25.000Z", "max_issues_repo_path": "Exercises/PS04 - Optimisation techniques II.jl", "max_issues_repo_name": "BenLauwens/ES313", "max_issues_repo_head_hexsha": "5a7553e53c288834f768d26e0d5aa22f9062b6af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercises/PS04 - Optimisation techniques II.jl", "max_forks_repo_name": "BenLauwens/ES313", "max_forks_repo_head_hexsha": "5a7553e53c288834f768d26e0d5aa22f9062b6af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-08-27T13:41:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:00:53.000Z", "avg_line_length": 19.9436619718, "max_line_length": 73, "alphanum_fraction": 0.6511299435, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703476, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7500096374428695}}
{"text": "\"\"\"\n    LogitNormal\n\n* Parametrization\nparametrized in \\\\mu and \\\\sigma^2\n\n* Score\n\n* Fisher Information\n\n* `time_varying_params` map.\n\n* Default link\n\"\"\"\nLogitNormal\n\nlogit(x) = log(x) - log(1-x)\n\nfunction score!(score_til::Matrix{T}, y::T, ::Type{LogitNormal}, param::Matrix{T}, t::Int) where T\n    score_til[t, 1] = (logit(y) - param[t, 1])/param[t, 2]\n    score_til[t, 2] = -(0.5/param[t, 2]) * (1 - ((logit(y) - param[t, 1])^2)/param[t, 2])\n    return\nend\n\nfunction fisher_information!(aux::AuxiliaryLinAlg{T}, ::Type{LogitNormal}, param::Matrix{T}, t::Int) where T\n    aux.fisher[1, 1] = 1/(param[t, 2])\n    aux.fisher[2, 2] = 1/(2*(param[t, 2]^2))\n    aux.fisher[2, 1] = 0\n    aux.fisher[1, 2] = 0\n    return\nend\n\nfunction log_likelihood(::Type{LogitNormal}, y::Vector{T}, param::Matrix{T}, n::Int) where T\n    loglik = -0.5*log(2*pi)*n\n    for t in 1:n\n        loglik -= log((y[t] * (1 - y[t])) * sqrt(param[t, 2])) + 0.5*(logit(y[t]) - param[t, 1])^2/param[t, 2]\n    end\n    return -loglik\nend\n\n# Links\nfunction link!(param_tilde::Matrix{T}, ::Type{LogitNormal}, param::Matrix{T}, t::Int) where T \n    param_tilde[t, 1] = link(IdentityLink, param[t, 1])\n    param_tilde[t, 2] = link(LogLink, param[t, 2], zero(T))\n    return\nend\nfunction unlink!(param::Matrix{T}, ::Type{LogitNormal}, param_tilde::Matrix{T}, t::Int) where T \n    param[t, 1] = unlink(IdentityLink, param_tilde[t, 1])\n    param[t, 2] = unlink(LogLink, param_tilde[t, 2], zero(T))\n    return\nend\nfunction jacobian_link!(aux::AuxiliaryLinAlg{T}, ::Type{LogitNormal}, param::Matrix{T}, t::Int) where T \n    aux.jac[1] = jacobian_link(IdentityLink, param[t, 1])\n    aux.jac[2] = jacobian_link(LogLink, param[t, 2], zero(T))\n    return\nend\n\n# utils \nfunction update_dist(::Type{LogitNormal}, param::Matrix{T}, t::Int) where T\n    # LogitNormal here is parametrized as sigma^2\n    return LogitNormal(param[t, 1], sqrt(param[t, 2]))\nend \n\nfunction params_sdm(d::LogitNormal)\n    pars = Distributions.params(d)\n    return (pars[1], pars[2]^2)\nend\n\nfunction num_params(::Type{LogitNormal})\n    return 2\nend", "meta": {"hexsha": "3034d5255b167ab55e59c5e11bc94154f72e8f56", "size": 2072, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distributions/logitnormal.jl", "max_stars_repo_name": "marinadietze/ScoreDrivenModels.jl", "max_stars_repo_head_hexsha": "4ee85b8d606892535a7b0bf2aec1d976f44d796e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2020-02-05T04:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T18:46:03.000Z", "max_issues_repo_path": "src/distributions/logitnormal.jl", "max_issues_repo_name": "marinadietze/ScoreDrivenModels.jl", "max_issues_repo_head_hexsha": "4ee85b8d606892535a7b0bf2aec1d976f44d796e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 109, "max_issues_repo_issues_event_min_datetime": "2019-11-26T12:34:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-27T20:16:55.000Z", "max_forks_repo_path": "src/distributions/logitnormal.jl", "max_forks_repo_name": "LAMPSPUC/GAS.jl", "max_forks_repo_head_hexsha": "e169248c3f8908170868d898a4def97af15774cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:11:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-04T20:05:21.000Z", "avg_line_length": 29.1830985915, "max_line_length": 110, "alphanum_fraction": 0.6361003861, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7500096319269546}}
{"text": "# Algorithm 3.1\n# Neville polynomial interpolation.\n\nfunction neville(x, y, x0)\n\tn = length(x)\n\tq = zeros(n, n)\n\tfor i ∈ 1:n\n\t\tq[i, 1] = y[i];\n\tend\n\tfor i ∈ 2:n\n\t\tfor j ∈ i:n\n\t\t\tq[j,i] = ((x0 - x[j-i+1]) * q[j,i-1] - (x0 - x[j]) * q[j-1,i-1]) / (x[j] - x[j-i+1])\n\t\tend\n\tend\n\treturn q[n,n]\nend\n\nprintln(neville([1, 56, 73], [67, 5, 35], 3))\n", "meta": {"hexsha": "d49f9edcfb5c84ef542bf07b5c206aa3e863e390", "size": 340, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter3/neville_interpolation.jl", "max_stars_repo_name": "Matt8898/julia-numerical", "max_stars_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-05T01:36:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-26T04:07:41.000Z", "max_issues_repo_path": "chapter3/neville_interpolation.jl", "max_issues_repo_name": "Matt8898/julia-numerical", "max_issues_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter3/neville_interpolation.jl", "max_forks_repo_name": "Matt8898/julia-numerical", "max_forks_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8947368421, "max_line_length": 87, "alphanum_fraction": 0.5088235294, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.7879311981328134, "lm_q1q2_score": 0.7500027365445275}}
{"text": "@doc_str \"Calculates x for `0 = a*x^2+b*x+c`, arguments types can be defined\nin function definitions\"\nfunction quadratic2(a::Float64, b::Float64, c::Float64)\n    quadratic(a, sqr_term, b) = (-b + sqr_term) / 2a\n    sqr_term = sqrt(b^2-4a*c)\n    r1 = quadratic(a, sqr_term, b)\n    r2 = quadratic(a, -sqr_term, b)\n    r1, r2\nend\n", "meta": {"hexsha": "53b1aeb1fc5815fd7fe34352e6d3c785d54a484c", "size": 327, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "try1.jl", "max_stars_repo_name": "FavioVazquez/juliadoc_try", "max_stars_repo_head_hexsha": "e8df607c5eea1cb57913b47614b381dd23d63863", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-23T18:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T18:56:01.000Z", "max_issues_repo_path": "try1.jl", "max_issues_repo_name": "FavioVazquez/juliadoc_try", "max_issues_repo_head_hexsha": "e8df607c5eea1cb57913b47614b381dd23d63863", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "try1.jl", "max_forks_repo_name": "FavioVazquez/juliadoc_try", "max_forks_repo_head_hexsha": "e8df607c5eea1cb57913b47614b381dd23d63863", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7, "max_line_length": 76, "alphanum_fraction": 0.6513761468, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632343454895, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7500027363263543}}
